{"text": "#!python\n# This file is subject to the terms and conditions defined in\n# file 'LICENCE', which is part of this source code package.\n# Author: Leo Guignard (guignardl...@AT@...janelia.hhmi.org)\n\nfrom scipy.spatial import cKDTree as KDTree\nimport os\nimport xml.etree.ElementTree as ET\nfrom copy import copy\nfrom scipy import spatial\nimport numpy as np\nfrom multiprocessing import Pool\nfrom scipy.spatial import Delaunay\nfrom itertools import combinations\nimport struct\nimport sys\n\nclass lineageTree(object):\n    ''' lineageTree is a class container for lineage tree structures\n        The main attributes are the following:\n        self.nodes: [int, ], list of node/cell ids\n        self.edges: [(int, int), ], a list of couple of cell/objects ids that represents the edges\n        self.time_nodes: {int, [int, ]}, a dictionary that maps time points to\n            a list of cell ids that belong to that time point\n        self.time_edges: {int, [(int, int), ]}, a dictionary that maps time points to\n            a list of edges couples that belong to that time point\n        self.successor: {int, [int, ]}, a dictionary that maps a cell id to\n            the list of its successors in time\n        self.predecessor: {int, [int, ]}, a dictionary that maps a cell id to\n            the list of its predecessors in time\n        self.time: {int: int, }, a dictionary that maps a cell to the time\n            it belongs to.\n    '''\n\n    def _dist_v(self, v1, v2):\n        ''' Computes the L2 norm between two vectors v1 and v2\n            Args:\n                v1: [float, ], list of values for the first vector\n                v2: [float, ], list of values for the second vector\n            Return:\n                float: L2 norm between v1 and v2\n        '''\n        v1 = np.array(v1)\n        v2 = np.array(v2)\n        return np.sum((v1-v2)**2)**(.5)\n\n    def get_next_id(self):\n        ''' Computes the next authorized id.\n            Returns:\n                int, next authorized id\n        '''\n        if self.next_id == []:\n            self.max_id += 1\n            return self.max_id\n        else:\n            return self.next_id.pop()\n\n    def add_node(self, t, succ, pos, id = None, reverse = False):\n        ''' Adds a node to the lineageTree and update it accordingly.\n            Args:\n                t: int, time to which to add the node\n                succ: id of the node the new node is a successor to\n                pos: [float, ], list of three floats representing the 3D spatial position of the node\n                id: id value of the new node, to be used carefully, \n                    if None is provided the new id is automatically computed.\n                reverse: bool, True if in this lineageTree the predecessors are the successors and reciprocally.\n                    This is there for bacward compatibility, should be left at False.\n            Returns:\n                C_next: int, id of the new node.\n        '''\n        if id is None:\n            C_next = self.get_next_id()\n        else:\n            C_next = id\n        self.time_nodes.setdefault(t, []).append(C_next)\n        if not succ is None and not reverse:\n            self.successor.setdefault(succ, []).append(C_next)\n            self.predecessor.setdefault(C_next, []).append(succ)\n            self.edges.append((succ, C_next))\n        elif not succ is None:\n            self.predecessor.setdefault(succ, []).append(C_next)\n            self.successor.setdefault(C_next, []).append(succ)\n            self.edges.append((C_next, succ))\n        else:\n            self.roots.append(C_next)\n        self.nodes.append(C_next)\n        self.pos[C_next] = pos\n        self.progeny[C_next] = 0\n        self.time[C_next] = t\n        return C_next\n\n    def remove_node(self, c):\n        ''' Removes a node and update the lineageTree accordingly\n            Args:\n                c: int, id of the node to remove\n        '''\n        self.nodes.remove(c)\n        self.time_nodes[self.time[c]].remove(c)\n        # self.time_nodes.pop(c, 0)\n        pos = self.pos.pop(c, 0)\n        e_to_remove = [e for e in self.edges if c in e]\n        for e in e_to_remove:\n            self.edges.remove(e)\n        if c in self.roots:\n            self.roots.remove(c)\n        succ = self.successor.pop(c, [])\n        s_to_remove = [s for s, ci in self.successor.iteritems() if c in ci]\n        for s in s_to_remove:\n            self.successor[s].remove(c)\n\n        pred = self.predecessor.pop(c, [])\n        p_to_remove = [s for s, ci in self.predecessor.iteritems() if ci == c]\n        for s in p_to_remove:\n            self.predecessor[s].remove(c)\n\n        self.time.pop(c, 0)\n        self.spatial_density.pop(c, 0)\n\n        self.next_id.append(c)\n        return e_to_remove, succ, s_to_remove, pred, p_to_remove, pos\n\n    def fuse_nodes(self, c1, c2):\n        ''' Fuses together two nodes that belong to the same time point\n            and update the lineageTree accordingly.\n            Args:\n                c1: int, id of the first node to fuse\n                c2: int, id of the second node to fuse\n        '''\n        e_to_remove, succ, s_to_remove, pred, p_to_remove, c2_pos = self.remove_node(c2)\n        for e in e_to_remove:\n            new_e = [c1] + [other_c for other_c in e if e != c2]\n            self.edges.append(new_e)\n\n        self.successor.setdefault(c1, []).extend(succ)\n        self.predecessor.setdefault(c1, []).extend(pred)\n\n        for s in s_to_remove:\n            self.successor[s].append(c1)\n\n        for p in p_to_remove:\n            self.predecessor[p].append(c1)\n\n\n        self.pos[c1] = np.mean([self.pos[c1], c2_pos], axis = 0)\n        self.progeny[c1] += 1\n\n    def to_tlp(self, fname, t_min=-1, t_max=np.inf, temporal=True, spatial=False, VF=False):\n        '''\n        Write a lineage tree into an understable tulip file\n        Args:\n            fname: string, path to the tulip file to create\n            t_min: int, minimum time to consider, default -1\n            t_max: int, maximum time to consider, default np.inf\n            temporal: boolean, True if the temporal links should be printed, default True\n            spatial: boolean, True if the special links should be printed, default True\n            VF: boolean, useless\n        '''\n        f=open(fname, \"w\")\n\n        f.write(\"(tlp \\\"2.0\\\"\\n\")\n        f.write(\"(nodes \")\n        if t_max!=np.inf or t_min>-1:\n            nodes_to_use = [n for n in self.nodes if t_min<n.time<=t_max]\n            edges_to_use = []\n            if temporal:\n                edges_to_use += [e for e in self.edges if t_min<e[0].time<t_max]\n            if spatial:\n                edges_to_use += [e for e in self.spatial_edges if t_min<e[0].time<t_max]\n        else:\n            nodes_to_use = self.nodes\n            edges_to_use = []\n            if temporal:\n                edges_to_use += self.edges\n            if spatial:\n                edges_to_use += self.spatial_edges\n\n        for n in nodes_to_use:\n            f.write(str(n)+ \" \")\n        f.write(\")\\n\")\n\n        for i, e in enumerate(edges_to_use):\n            f.write(\"(edge \" + str(i) + \" \" + str(e[0]) + \" \" + str(e[1]) + \")\\n\")\n\n        f.write(\"(property 0 int \\\"time\\\"\\n\")\n        f.write(\"\\t(default \\\"0\\\" \\\"0\\\")\\n\")\n        for n in nodes_to_use:\n            f.write(\"\\t(node \" + str(n) + str(\" \\\"\") + str(self.time[n]) + \"\\\")\\n\")\n        f.write(\")\\n\")\n\n        f.write(\"(property 0 layout \\\"viewLayout\\\"\\n\")\n        f.write(\"\\t(default \\\"(0, 0, 0)\\\" \\\"()\\\")\\n\")\n        for n in nodes_to_use:\n            f.write(\"\\t(node \" + str(n) + str(\" \\\"\") + str(tuple(self.pos[n])) + \"\\\")\\n\")\n        f.write(\")\\n\")\n\n        f.write(\"(property 0 double \\\"distance\\\"\\n\")\n        f.write(\"\\t(default \\\"0\\\" \\\"0\\\")\\n\")\n        for i, e in enumerate(edges_to_use):\n            d_tmp = self._dist_v(self.pos[e[0]], self.pos[e[1]])\n            f.write(\"\\t(edge \" + str(i) + str(\" \\\"\") + str(d_tmp) + \"\\\")\\n\")\n            f.write(\"\\t(node \" + str(e[0]) + str(\" \\\"\") + str(d_tmp) + \"\\\")\\n\")\n        f.write(\")\\n\")\n        f.write(\")\")\n        f.close()\n\n    def median_average(self, subset):\n        ''' Build the median vector of a subset *subset* of cells. *WARNING DEPRECATED*\n            Since deprecated, no more doc.\n        '''\n        subset_dist = [np.mean([di.pos for di in c.D], axis = 0) - c.pos for c in subset if c.D != []]\n        target_C = [c for c in subset if c.D != []]\n        if subset_dist != []:\n            med_distance = spatial.distance.squareform(spatial.distance.pdist(subset_dist))\n            return subset_dist[np.argmin(np.sum(med_distance, axis=0))]\n        else:\n            return [0, 0, 0]\n\n    def median_average_bw(self, subset):\n        ''' Build the median vector of a subset *subset* of cells. *WARNING DEPRECATED*\n            Since deprecated, no more doc.\n        '''\n        subset_dist = [c.M.pos - c.pos for c in subset if c.M != self.R]\n        target_C = [c for c in subset if c.D != []]\n        if subset_dist != []:\n            med_distance = spatial.distance.squareform(spatial.distance.pdist(subset_dist))\n            return subset_dist[np.argmin(np.sum(med_distance, axis=0))]\n        else:\n            return [0, 0, 0]\n\n    def build_median_vector(self, C, dist_th, delta_t = 2):\n        ''' Computes the median vector for a cell *C*. *WARNING DEPRECATED*\n            Since deprecated, no more doc.\n        '''\n        if not hasattr(self, 'spatial_edges'):\n            self.compute_spatial_edges(dist_th)\n        subset = [C]\n        subset += C.N\n        added_D = added_M = subset\n        for i in xrange(delta_t):\n            _added_D = []\n            _added_M = []\n            for c in added_D:\n                _added_D += c.D\n            for c in added_M:\n                if not c.M is None:\n                    _added_M += [c.M]\n            subset += _added_M\n            subset += _added_D\n            added_D = _added_D\n            added_M = _added_M\n\n\n        return self.median_average(subset)\n\n    def build_vector_field(self, dist_th=50):\n        ''' Builds the median vectors of every nodes using the cells at a distance *dist_th*. *WARNING DEPRECATED*\n            Since deprecated, no more doc.\n        '''\n        ruler = 0\n        for C in self.nodes:\n            if ruler != C.time:\n                print C.time\n            C.direction = self.build_median_vector(C, dist_th)\n            ruler = C.time\n    \n    def single_cell_propagation(self, params):\n        ''' Computes the incoming displacement vector of a cell. *WARNING DEPRECATED*\n            Since deprecated, no more doc.\n        '''\n        C, t, nb_max, dist_max, to_check_self, R, pos, successor, predecessor = params\n        idx3d = self.kdtrees[t]\n        closest_cells = np.array(to_check_self)[list(idx3d.query(tuple(pos[C]), nb_max)[1])]\n        max_value = np.min(np.where(np.array([_dist_v(pos[C], pos[ci]) for ci in closest_cells]+[dist_max+1])>dist_max))\n        cells_to_keep = closest_cells[:max_value]\n        subset_dist = [np.mean([pos[cii] for cii in predecessor[ci]], axis=0) - pos[ci] for ci in cells_to_keep if not ci in R]\n        if subset_dist != []:\n            med_distance = spatial.distance.squareform(spatial.distance.pdist(subset_dist))\n            med = subset_dist[np.argmin(np.sum(med_distance, axis=0))]\n        else:\n            med = [0, 0, 0]\n        return C, med\n    \n    def read_from_xml(self, file_format, tb, te, z_mult=1., mask = None):\n        ''' Reads a lineage tree from TGMM xml output.\n            Args:\n                file_format: string, path to the xmls location.\n                        it should be written as follow:\n                            path/to/xml/standard_name_t%06d.xml where (as an example)\n                            %06d means a series of 6 digits representing the time and\n                            if the time values is smaller that 6 digits, the missing\n                            digits are filed with 0s\n                tb: int, first time point to read\n                te: int, last time point to read\n                z_mult: float, aspect ratio\n                mask: SpatialImage, binary image that specify the region to read\n        '''\n        self.time_nodes = {}\n        self.time_edges = {}\n        unique_id = 0\n        self.nodes = []\n        self.edges = []\n        self.roots = []\n        self.successor = {}\n        self.predecessor = {}\n        self.pos = {}\n        self.time_id = {}\n        self.time = {}\n        self.mother_not_found = []\n        self.ind_cells = {}\n        self.svIdx = {}\n        self.is_root = {}\n        self.lin = {}\n        self.C_lin = {}\n        self.coeffs = {}\n        self.intensity = {}\n        self.W = {}\n        for t in range(tb, te+1):\n            print t,\n            if t%10==0:\n                print\n            tree = ET.parse(file_format%t)\n            root = tree.getroot()\n            self.time_nodes[t] = []\n            self.time_edges[t] = []\n            for it in root:\n                if not '-1.#IND' in it.attrib['m']:\n                    M_id, pos, cell_id, svIdx, lin_id = (int(it.attrib['parent']), \n                                                [float(v) for v in it.attrib['m'].split(' ') if v!=''], \n                                                int(it.attrib['id']),\n                                                [int(v) for v in it.attrib['svIdx'].split(' ') if v!=''],\n                                                int(it.attrib['lineage']))\n                    try:\n                        alpha, W, nu, alphaPrior = (float(it.attrib['alpha']),\n                                                    [float(v) for v in it.attrib['W'].split(' ') if v!=''],\n                                                    float(it.attrib['nu']),\n                                                    float(it.attrib['alphaPrior']))\n                        pos = np.array(pos)\n                        pos_tmp = np.round(pos).astype(np.uint16)\n                        if mask is None or mask[pos_tmp[0], pos_tmp[1], pos_tmp[2]]:\n                            C = unique_id\n                            pos[-1] = pos[-1]*z_mult\n                            if (t-1, M_id) in self.time_id:\n                                M = self.time_id[(t-1, M_id)]\n                                self.successor.setdefault(M, []).append(C)\n                                self.predecessor.setdefault(C, []).append(M)\n                                self.edges.append((M, C))\n                                self.time_edges[t].append((M, C))\n                                self.is_root[C] = False\n                            else:\n                                if M_id != -1:\n                                    self.mother_not_found.append(C)\n                                self.roots.append(C)\n                                self.is_root[C] = True\n                            self.pos[C] = pos\n                            self.nodes.append(C)\n                            self.time_nodes[t].append(C)\n                            self.time_id[(t, cell_id)] = C\n                            self.time[C] = t\n                            self.svIdx[C] = svIdx\n                            self.lin.setdefault(lin_id, []).append(C)\n                            self.C_lin[C] = lin_id\n                            self.intensity[C] = max(alpha - alphaPrior, 0)\n                            tmp = list(np.array(W) * nu)\n                            self.W[C] = np.array(W).reshape(3, 3)\n                            self.coeffs[C] = tmp[:3] + tmp[4:6] + tmp[8:9] + list(pos)\n                            unique_id += 1\n                    except Exception, e:\n                        pass\n                else:\n                    if self.ind_cells.has_key(t):\n                        self.ind_cells[t] += 1\n                    else:\n                        self.ind_cells[t] = 1\n        self.max_id = unique_id - 1\n\n    def read_from_mamut_xml(self, path):\n        ''' Read a lineage tree from a MaMuT xml.\n            Args:\n                path: string, path to the MaMut xml\n        '''\n        tree = ET.parse(path)\n        Model = tree.getroot()[0]\n        FeatureDeclarations, AllSpots, AllTracks, FilteredTracks = list(Model)\n\n        self.time_nodes = {}\n        self.time_edges = {}\n        self.nodes = []\n        self.pos = {}\n        self.time = {}\n        self.node_name = {}\n        for frame in AllSpots:\n            t = int(frame.attrib['frame'])\n            self.time_nodes[t] = []\n            for cell in frame:\n                cell_id, n, x, y, z = (int(cell.attrib['ID']), cell.attrib['name'],\n                                                 float(cell.attrib['POSITION_X']),\n                                                 float(cell.attrib['POSITION_Y']),\n                                                 float(cell.attrib['POSITION_Z']))\n                self.time_nodes[t].append(cell_id)\n                self.nodes.append(cell_id)\n                self.pos[cell_id] = np.array([x, y, z])\n                self.time[cell_id] = t\n                self.node_name[cell_id] = n\n\n        self.edges = []\n        self.roots = []\n        tracks = {}\n        self.successor = {}\n        self.predecessor = {}\n        for track in AllTracks:\n            t_id, l = int(track.attrib['TRACK_ID']), float(track.attrib['TRACK_DURATION'])\n            tracks[t_id] = []\n            for edge in track:\n                s, t = int(edge.attrib['SPOT_SOURCE_ID']), int(edge.attrib['SPOT_TARGET_ID'])\n                if s in self.nodes and t in self.nodes:\n                    if self.time[s] > self.time[t]:\n                        s, t = t, s\n                    self.successor.setdefault(s, []).append(t)\n                    self.predecessor.setdefault(t, []).append(s)\n                    tracks[t_id].append((s, t))\n                    self.edges.append((s, t))\n        self.t_b = min(self.time_nodes.keys())\n        self.t_e = max(self.time_nodes.keys())\n    \n    def to_binary(self, fname, starting_points = None):\n        ''' Writes the lineage tree (a forest) as a binary structure\n            (assuming it is a binary tree, it would not work for *n*ary tree with 2 < *n*).\n            The binary file is composed of 3 sequences of numbers and\n            a header specifying the size of each of these sequences.\n            The first sequence, *number_sequence*, represents the lineage tree\n            as a DFT preporder transversal list. -1 signifying a leaf and -2 a branching\n            The second sequence, *time_sequence*, represent the starting time of each tree.\n            The third sequence, *pos_sequence*, reprensent the 3D coordinates of the objects.\n            The header specify the size of each of these sequences.\n            Each size is stored as a long long\n            The *number_sequence* is stored as a list of long long (0 -> 2^(8*8)-1)\n            The *time_sequence* is stored as a list of unsigned short (0 -> 2^(8*2)-1)\n            The *pos_sequence* is stored as a list of double\n            Args:\n                fname: string, name of the binary file\n                starting_points: [int, ], list of the roots to be written.\n                        If None, all roots are written\n                        Default: None\n        '''\n        if starting_points is None:\n            starting_points = [c for c in self.successor.iterkeys() if self.predecessor.get(c, []) == []]\n        number_sequence = [-1]\n        pos_sequence = []\n        time_sequence = []\n        default_lin = -1\n        for c in starting_points:\n            time_sequence.append(self.time.get(c, 0))\n            to_treat = [c]\n            while to_treat != []:\n                curr_c = to_treat.pop()\n                number_sequence.append(curr_c)\n                pos_sequence += list(self.pos[curr_c])\n                if self.successor.get(curr_c, []) == []:\n                    number_sequence.append(-1)\n                elif len(self.successor[curr_c]) == 1:\n                    to_treat += self.successor[curr_c]\n                else:\n                    number_sequence.append(-2)\n                    to_treat += self.successor[curr_c]\n        remaining_nodes = set(self.nodes) - set(number_sequence)\n\n        for c in remaining_nodes:\n            time_sequence.append(self.time.get(c, 0))\n            number_sequence.append(c)\n            pos_sequence += list(self.pos[c])\n            number_sequence.append(-1)\n\n        f = open(fname, 'wb')\n        f.write(struct.pack('q', len(number_sequence)))\n        f.write(struct.pack('q', len(time_sequence)))\n        f.write(struct.pack('q', len(pos_sequence)))\n        f.write(struct.pack('q'*len(number_sequence), *number_sequence))\n        f.write(struct.pack('H'*len(time_sequence), *time_sequence))\n        f.write(struct.pack('d'*len(pos_sequence), *pos_sequence))\n\n        f.close()\n\n\n    def read_from_binary(self, fname, reverse_time = False):\n        ''' Reads a binary lineageTree file name.\n            Format description:\n                see self.to_binary\n            Args:\n                fname: string, path to the binary file\n                reverse_time: bool, not used\n        '''\n        q_size = struct.calcsize('q')\n        H_size = struct.calcsize('H')\n        d_size = struct.calcsize('d')\n\n        f = open(fname, 'rb')\n        len_tree = struct.unpack('q', f.read(q_size))[0]\n        len_time = struct.unpack('q', f.read(q_size))[0]\n        len_pos = struct.unpack('q', f.read(q_size))[0]\n        number_sequence = list(struct.unpack('q'*len_tree, f.read(q_size*len_tree)))\n        time_sequence = list(struct.unpack('H'*len_time, f.read(H_size*len_time)))\n        pos_sequence = np.array(struct.unpack('d'*len_pos, f.read(d_size*len_pos)))\n\n        f.close()\n\n        successor = {}\n        predecessor = {}\n        time = {}\n        time_nodes = {}\n        time_edges = {}\n        pos = {}\n        is_root = {}\n        nodes = []\n        edges = []\n        waiting_list = []\n        print number_sequence[0]\n        i = 0\n        done = False\n        if max(number_sequence[::2]) == -1:\n            # number_sequence = number_sequence[1::2]\n            tmp = number_sequence[1::2]\n            if len(tmp)*3 == len(pos_sequence) == len(time_sequence)*3:\n                time = dict(zip(tmp, time_sequence))\n                for c, t in time.iteritems():\n                    time_nodes.setdefault(t, []).append(c)\n                pos = dict(zip(tmp, np.reshape(pos_sequence, (len_time, 3))))\n                is_root = {c:True for c in tmp}\n                nodes = tmp\n                done = True\n        shown = set()\n        while i < len(number_sequence) and not done:#, c in enumerate(number_sequence[:-1]):\n            c = number_sequence[i]\n            # if (1000.*i)//len(number_sequence)%10==0 and not (1000.*i)//len(number_sequence) in shown:\n            #     shown.add((1000.*i)//len(number_sequence))\n            #     sys.stdout.write('\\b'*(4))\n            #     sys.stdout.flush()\n            #     sys.stdout.write(\"%03d\"%((100*i)//len(number_sequence))+\"%\")#(100*i)//len(number_sequence)\n            #     sys.stdout.flush()\n            if c == -1:\n                if waiting_list != []:\n                    prev_mother = waiting_list.pop()\n                    successor[prev_mother].insert(0, number_sequence[i+1])\n                    edges.append((prev_mother, number_sequence[i+1]))\n                    time_edges.setdefault(t, []).append((prev_mother, number_sequence[i+1]))\n                    is_root[number_sequence[i+1]] = False\n                    t = time[prev_mother] + 1\n                else:\n                    t = time_sequence.pop(0)\n                    is_root[number_sequence[i+1]] = True\n\n            elif c == -2:\n                successor[waiting_list[-1]] = [number_sequence[i+1]]\n                edges.append((waiting_list[-1], number_sequence[i+1]))\n                time_edges.setdefault(t, []).append((waiting_list[-1], number_sequence[i+1]))\n                is_root[number_sequence[i+1]] = False\n                pos[waiting_list[-1]] = pos_sequence[:3]\n                pos_sequence = pos_sequence[3:]\n                nodes.append(waiting_list[-1])\n                time[waiting_list[-1]] = t\n                time_nodes.setdefault(t, []).append(waiting_list[-1])\n                t += 1\n\n            elif number_sequence[i+1] >= 0:\n                successor[c] = [number_sequence[i+1]]\n                edges.append((c, number_sequence[i+1]))\n                time_edges.setdefault(t, []).append((c, number_sequence[i+1]))\n                is_root[number_sequence[i+1]] = False\n                pos[c] = pos_sequence[:3]\n                pos_sequence = pos_sequence[3:]\n                nodes.append(c)\n                time[c] = t\n                time_nodes.setdefault(t, []).append(c)\n                t += 1\n\n            elif number_sequence[i+1] == -2:\n                waiting_list += [c]\n\n            elif number_sequence[i+1] == -1:\n                pos[c] = pos_sequence[:3]\n                pos_sequence = pos_sequence[3:]\n                nodes.append(c)\n                time[c] = t\n                time_nodes.setdefault(t, []).append(c)\n                t += 1\n                i += 1\n                if waiting_list != []:\n                    prev_mother = waiting_list.pop()\n                    successor[prev_mother].insert(0, number_sequence[i+1])\n                    edges.append((prev_mother, number_sequence[i+1]))\n                    time_edges.setdefault(t, []).append((prev_mother, number_sequence[i+1]))\n                    if i+1<len(number_sequence):\n                        is_root[number_sequence[i+1]] = False\n                    t = time[prev_mother] + 1\n                else:\n                    if 0 < len(time_sequence):\n                        t = time_sequence.pop(0)\n                    if i+1<len(number_sequence):\n                        is_root[number_sequence[i+1]] = True\n            i += 1\n\n        predecessor = {vi: [k] for k, v in successor.iteritems() for vi in v}\n        print '100%'\n\n        self.successor = successor\n        self.predecessor = predecessor\n        self.time = time\n        self.time_nodes = time_nodes\n        self.time_edges = time_edges\n        self.pos = pos\n        self.nodes = nodes\n        self.edges = edges\n        self.t_b = min(time_nodes.iterkeys())\n        self.t_e = max(time_nodes.iterkeys())\n        self.is_root = is_root\n        self.max_id = max(self.nodes)\n    \n    def write_to_prune(self, file_format_input, file_format_output):\n        ''' Useless function that reads and rewrites a TGMM files from a TGMM intput\n            only keeping the objects in self.to_keep between time points 200 and 205 (mostly why this function is useless).\n            Args:\n                file_format_input: string, format of the input TGMM files\n                file_format_output: string, format of the output TGMM files\n        '''\n        old_id_to_new = {}\n        old_lin_to_new = {}\n        lin_id = 0\n        for t in range(200, 205+1):\n            new_id = 0\n            print t,\n            if t%10==0:\n                print\n            tree = ET.parse(file_format_input%t)\n            root = tree.getroot()\n            for it in list(root.getchildren()):\n                if not '-1.#IND' in it.attrib['m']:\n                    M_id, pos, cell_id, old_lin_id = (int(it.attrib['parent']), \n                                                   [float(v) for v in it.attrib['m'].split(' ') if v!=''], \n                                                   int(it.attrib['id']), int(it.attrib['lineage']))\n                    if not self.to_keep.get(self.time_id[(t, cell_id)], False):\n                        root.remove(it)\n                    else:\n                        if M_id != -1:\n                            it.set('parent', M_id)\n                        it.set('id', cell_id)\n                        old_id_to_new[(t, cell_id)] = new_id\n                        new_id += 1\n            tree.write(file_format_output%t)\n\n    def get_idx3d(self, t):\n        ''' Get a 3d kdtree for the dataset at time *t*\n            The  kdtree is stored in self.kdtrees[t]\n            Args:\n                t: int, time\n            Returns:\n                idx3d: kdtree, the built kdtree\n                to_check_self: the correspondancy list:\n                    If the query in the kdtree gives you the value i,\n                    then it corresponds to the id in the tree to_check_self[i] \n        '''\n        to_check_self = self.time_nodes[t]\n        if not self.kdtrees.has_key(t):\n            data_corres = {}\n            data = []\n            for i, C in enumerate(to_check_self):\n                data.append(tuple(self.pos[C]))\n                data_corres[i] = C\n            idx3d = KDTree(data)\n            self.kdtrees[t] = idx3d\n        else:\n            idx3d = self.kdtrees[t]\n        return idx3d, to_check_self\n\n    def get_gabriel_graph(self, t):\n        ''' Build the Gabriel graph of the given graph for time point *t*\n            The Garbiel graph is then stored in self.Gabriel_graph.\n            *WARNING: the graph is not recomputed if already computed. even if nodes were added*.\n            Args:\n                t: int, time\n        '''\n        if not hasattr(self, 'Gabriel_graph'):\n            self.Gabriel_graph = {}\n\n        if not self.Gabriel_graph.has_key(t):\n            idx3d, nodes = self.get_idx3d(t)\n\n            data_corres = {}\n            data = []\n            for i, C in enumerate(nodes):\n                data.append(self.pos[C])\n                data_corres[i] = C\n\n            tmp = Delaunay(data)\n\n            delaunay_graph = {}\n\n            for N in tmp.simplices:\n                for e1, e2 in combinations(np.sort(N), 2):\n                    delaunay_graph.setdefault(e1, set([])).add(e2)\n\n            Gabriel_graph = {}\n\n            for e1, neighbs in delaunay_graph.iteritems():\n                for ni in neighbs:\n                    if not any([np.linalg.norm((data[ni] + data[e1])/2 - data[i])<np.linalg.norm(data[ni] - data[e1])/2\n                            for i in delaunay_graph[e1].intersection(delaunay_graph[ni])]):\n                        Gabriel_graph.setdefault(data_corres[e1], set()).add(data_corres[ni])\n                        Gabriel_graph.setdefault(data_corres[ni], set()).add(data_corres[e1])\n            # for e1, ni in delaunay_graph.iteritems():\n            #     ni = list(ni)\n            #     pos_e1 = data[e1]\n            #     distances = np.array([self._dist_v(pos_e1, data[e2]) for e2 in ni])\n            #     sorted_neighbs = list(np.array(ni)[np.argsort(distances)])\n            #     tmp_pt = sorted_neighbs.pop(0)\n            #     while not tmp_pt is None and len(idx3d.query_ball_point((data[tmp_pt] + pos_e1)/2., (self._dist_v(pos_e1, data[tmp_pt])/2)-10**-3))<=2:\n            #         Gabriel_graph.setdefault(nodes[e1], set()).add(nodes[tmp_pt])\n            #         Gabriel_graph.setdefault(nodes[tmp_pt], set()).add(nodes[e1])\n            #         if sorted_neighbs != []:\n            #             tmp_pt = sorted_neighbs.pop(0)\n            #         else:\n            #             tmp_pt = None\n\n            self.Gabriel_graph[t] = Gabriel_graph\n\n        return self.Gabriel_graph[t]\n\n    def parallel_gabriel_graph_preprocess(self, nb_proc = 20):\n        ''' Build the gabriel graphs for each time point. *WARNING DEPRECATED*\n            Since deprecated, no more doc.\n        ''' \n        mapping = []\n        if not hasattr(self, 'Gabriel_graph'):\n            self.Gabriel_graph = {}\n        for t in xrange(self.t_b, self.t_e + 1):\n            if not self.Gabriel_graph.has_key(t):\n                mapping += [(self, t)]\n        if nb_proc<2:\n            out = []\n            for params in mapping:\n              out += [get_gabriel_graph_for_parallel(params)]\n        else:\n            pool = Pool(processes=nb_proc)\n            out = pool.map(get_gabriel_graph_for_parallel, mapping)\n            pool.terminate()\n            pool.close()\n        for t, G_g in out:\n            self.Gabriel_graph[t] = G_g\n\n\n    def build_VF_propagation_backward(self, t_b=0, t_e=200, nb_max=20, dist_max=200, nb_proc = 8):\n        ''' Build the backward propagation from TGMM data. *WARNING DEPRECATED*\n            Since deprecated, no more doc.\n        '''\n        self.VF = lineageTree(None, None, None)\n        from time import time\n\n        # Hack to allow pickling of kdtrees for multiprocessing\n        # kdtree.node = kdtree.KDTree.node\n        # kdtree.leafnode = kdtree.KDTree.leafnode\n        # kdtree.innernode = kdtree.KDTree.innernode\n\n        starting_cells = self.time_nodes[t_b]\n        unique_id = 0\n        self.VF.time_nodes = {t_b: []}\n        for C in starting_cells:\n            i = self.VF.get_next_id()\n            self.VF.nodes.append(i)\n            self.VF.time_nodes[t_b].append(i)\n            self.VF.roots.append(i)\n            self.VF.pos[i]=self.pos[C]\n\n        for t in range(t_b, t_e, -1):\n            tic = time()\n            print t, ': ',\n            to_check_VF = self.VF.time_nodes[t]\n\n            idx3d, to_check_self = self.get_idx3d(t)\n\n            self.VF.time_nodes[t-1] = []\n            mapping = []\n\n            Gabriel_graph = self.get_gabriel_graph(t)\n\n            print 'Gabriel graph built (%f s); '%(time() - tic),\n\n            cell_mapping_LT_VF = {}\n            for C in to_check_VF:\n                C_self = to_check_self[idx3d.query(self.VF.pos[C])[1]]\n                cell_mapping_LT_VF[C_self] = C\n                mapping += [(C_self, Gabriel_graph, dist_max, self.roots, self.pos, self.predecessor)]\n\n            out = []\n\n            if nb_proc<2:\n                for params in mapping:\n                  out += [single_cell_propagation(params)]\n            else:\n                pool = Pool(processes=nb_proc)\n                out = pool.map(single_cell_propagation, mapping)\n                pool.terminate()\n                pool.close()\n            for C, med in out:\n                C_VF = cell_mapping_LT_VF[C]\n                self.VF.add_node(t-1, C_VF, self.VF.pos[C_VF] + med)\n\n            idx3d, to_check_self = self.get_idx3d(t-1)\n            to_check_VF = self.VF.time_nodes[t-1]\n\n            print 'propagation done (%f s); '%(time() - tic),\n\n            if not self.spatial_density.has_key(to_check_self[0]):\n                self.compute_spatial_density(t-1, t-1, nb_max)\n\n            print 'Spatial density done (%f s); '%(time() - tic),\n\n            dist_to_VF, equivalence = idx3d.query([self.VF.pos[c] for c in to_check_VF], 1)\n\n            count = np.bincount(equivalence)\n            self_too_close, = np.where(count > 1)\n            TMP = []\n            for C_self in self_too_close:\n                to_potentially_fuse, = np.where(equivalence == C_self)\n                pos_tmp = [self.VF.pos[to_check_VF[c]] for c in to_potentially_fuse]\n                dist_tmp = spatial.distance.squareform(spatial.distance.pdist(pos_tmp))\n                dist_tmp[dist_tmp==0] = np.inf\n                if (dist_tmp<self.spatial_density[to_check_self[C_self]]/2.).any():\n                    to_fuse = np.where(dist_tmp == np.min(dist_tmp))[0]\n                    c1, c2 = to_potentially_fuse[list(to_fuse)][:2]\n                    to_check_VF[c1], to_check_VF[c2]\n                    TMP.append([to_check_VF[c1], to_check_VF[c2]])\n\n            for c1, c2 in TMP:\n                if c1 != c2:\n                    self.VF.fuse_nodes(c1, c2)\n\n            print 'Fusion done (%f s); '%(time() - tic),\n\n            idx3d, to_check_VF = self.VF.get_idx3d(t-1)[:2]\n            dist_to_VF, equivalence = idx3d.query([self.pos[c] for c in to_check_self], 1)\n            tmp = np.array([dist_to_VF[i]/self.spatial_density[c] for i, c in enumerate(to_check_self)])\n            to_add = [to_check_self[i] for i in np.where(tmp>1)[0]]\n            for C in to_add:\n                self.VF.add_node(t-1, None, self.pos[C])\n\n            print 'Addition done (%f s); '%(time() - tic),\n            print '#cells: %d'%(len(self.VF.time_nodes[t-1]))\n\n        self.VF.t_b = t_b\n        self.VF.t_e = t_e\n\n        return self.VF\n\n    def compute_spatial_density(self, t_b=0, t_e=200, n_size=10):\n        ''' Computes the average distance between the *n_size* closest object for a set of time points\n            The results is stored in self.spatial_density\n            Args:\n                t_b: int, starting time to look at\n                t_e: int, ending time to look at\n                n_size: int, number of neighbors to look at\n        '''\n        time_range = [t for t in self.time_nodes.keys() if t_b <= t <= t_e]\n        for t in time_range:\n            Cs = self.time_nodes[t]\n            data_corres = {}\n            data = []\n            for i, C in enumerate(Cs):\n                data.append(tuple(self.pos[C]))\n                data_corres[i] = C\n            if not self.kdtrees.has_key(t):\n                idx3d = KDTree(data)\n            else:\n                idx3d = self.kdtrees[t]\n            distances, indices = idx3d.query(data, n_size)\n            self.spatial_density.update(dict(zip(Cs, np.mean(distances[:, 1:], axis=1))))\n\n    def compute_spatial_edges(self, th=50):\n        ''' Innefitiently computes the connection between cells at a given distance\n            Writes the output in self.spatial_edges\n            Args:\n                th: float, distance to consider neighbors\n        '''\n        self.spatial_edges=[]\n        for t, Cs in self.time_nodes.iteritems():\n            nodes_tmp, pos_tmp = zip(*[(C, C.pos) for C in Cs])\n            nodes_tmp = np.array(nodes_tmp)\n            distances = spatial.distance.squareform(spatial.distance.pdist(pos_tmp))\n            nodes_to_match = np.where((0<distances) & (distances<th))\n            to_link = zip(nodes_tmp[nodes_to_match[0]], nodes_tmp[nodes_to_match[1]])\n            self.spatial_edges.extend(to_link)\n            for C1, C2 in to_link:\n                C1.N.append(C2)\n\n    def __init__(self, file_format, tb = None, te = None, z_mult = 1., mask = None, MaMuT = False):\n        ''' Main library to build tree graph representation of TGMM and SVF data\n            It can read TGMM xml outputs, MaMuT files and binary files (see to_binary and read_from_binary)\n            Args:\n                file_format: string, either: - path format to the TGMM xml \n                                             - path to the MaMuT file\n                                             - path to the binary file\n                tb: int, first time point (necessary for TGMM xmls only)\n                te: int, last time point (necessary for TGMM xmls only)\n                z_mult: float, z aspect ratio if necessary (usually only for TGMM xmls)\n                mask: SpatialImage, binary image that specify the region to read (for TGMM xmls only)\n                MaMuT: boolean, to specify that a MaMuT file is read\n        '''\n        super(lineageTree, self).__init__()\n        self.time_nodes = {}\n        self.time_edges = {}\n        self.max_id = -1\n        self.next_id = []\n        self.nodes = []\n        self.edges = []\n        self.roots = []\n        self.successor = {}\n        self.predecessor = {}\n        self.pos = {}\n        self.time_id = {}\n        self.time = {}\n        self.kdtrees = {}\n        self.spatial_density = {}\n        self.progeny = {}\n        if not (file_format is None or tb is None or te is None) and not MaMuT:\n            self.read_from_xml(file_format, tb, te, z_mult=z_mult, mask = mask)\n            self.t_b = tb\n            self.t_e = te\n        elif not (file_format is None) and MaMuT:\n            self.read_from_mamut_xml(file_format)\n        elif not (file_format is None):\n            self.read_from_binary(file_format)\n\n", "meta": {"hexsha": "f6c70c1a153c8ae3ed072c8448d2c2c3b100eada", "size": 39698, "ext": "py", "lang": "Python", "max_stars_repo_path": "TGMMlibraries/TGMMlibraries/lineageTree.py", "max_stars_repo_name": "Xqua/standalone-Mouse", "max_stars_repo_head_hexsha": "1655a2cf15563155a13d6094638c5d440a383005", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-10-16T01:52:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T11:53:46.000Z", "max_issues_repo_path": "TGMMlibraries/TGMMlibraries/lineageTree.py", "max_issues_repo_name": "Xqua/standalone-Mouse", "max_issues_repo_head_hexsha": "1655a2cf15563155a13d6094638c5d440a383005", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-11-24T00:16:44.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-11T09:01:26.000Z", "max_forks_repo_path": "TGMMlibraries/TGMMlibraries/lineageTree.py", "max_forks_repo_name": "Xqua/standalone-Mouse", "max_forks_repo_head_hexsha": "1655a2cf15563155a13d6094638c5d440a383005", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-11-21T23:55:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-10T16:52:54.000Z", "avg_line_length": 42.6860215054, "max_line_length": 153, "alphanum_fraction": 0.5187666885, "include": true, "reason": "import numpy,from scipy", "num_tokens": 9204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.2974699363766585, "lm_q1q2_score": 0.19999846777887292}}
{"text": "import numpy as np\nimport pandas as pd\nfrom scipy import interpolate\nimport pnptransport.finitesource as pnpfs\nimport os\nimport multiprocessing\nimport logging\nfrom functools import partial\nfrom datetime import datetime\nimport pidsim.ml_simulator as ml_kinetics\nfrom pidsim.parameter_span import create_filetag\nimport traceback\nimport json\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport matplotlib.ticker as mticker\nimport matplotlib.gridspec as gridspec\nfrom matplotlib.ticker import ScalarFormatter\nimport h5py\n\ncsv_file = r'/home'\n\nS0_s = [1E8, 1E9, 1E10, 1E11] # 1/cm^2\nh_s = [1E-8, 1E-10, 1E-12, 1E-14] # cm/s\nDSF_s = [1E-14, 1E-16, 1E-18, 1E-20] # cm^2/s\n\ntsteps = 360\ntemperature = 85\nrate_source = 1E-4\nDSIN = 3.92E-16\nL1 = 0.075\nN1 = 50\nL2 = 1\nN2 = 50\n\nvoltage = 0.375\ne_field = voltage / L1 / 100\ncsv_file = r'/home/fenics/shared/fenics/shared/pid_fit/PID_mc_BSF_4_ready.csv'\n\n\ndef cost_function(y, rsh_norm_) -> float:\n    # x = model['time (s)']\n    # y = model['rsh (ohms cm^2)']\n    # f = interpolate.interp1d(x, y)\n    # y_pred = f(time_s)\n    y = np.array(y)\n    m = len(y)\n    diff = np.log10(y / y[0]) - np.log10(rsh_norm_)\n    r = 0.5 * np.dot(diff.T, diff) / m\n    return r\n\n\ndef func(beta, **kwargs_):\n    temp = kwargs_.get('temp', 85)\n    rate_source_ = kwargs_.get('rate_source', 1E-4)\n    DSIN_ = kwargs_.get('DSIN', 3.92E-16)\n    stress_voltage = kwargs_.get('stress_voltage', 3.75)\n    L1_ = kwargs_.get('L1', 0.075)\n    N1_ = int(kwargs_.get('N1', 100))\n    tsteps_ = int(kwargs_.get('tsteps', 360))\n    time_s = kwargs_.get('time_s', np.array([0]))\n    # h5_file = kwargs_.get('h5file', None)\n\n    S0_ = float(beta[0])\n    h_ = float(beta[1])\n    DSF_ = float(beta[2])\n    h5_file = beta[3]\n    print('func, h5file: {0}'.format(h5_file))\n\n    kw = dict(\n        simulation_time=np.amax(time_s) * 1.1,\n        temperature=temp, rate_source=rate_source_, DSIN=DSIN_,\n        stress_voltage=stress_voltage, L1=L1_, m=1, time_steps=tsteps_,\n        N1=N1_, h5file=h5_file\n    )\n\n    model = simulate_rsh(\n        S0=S0_, h=h_, DSF=DSF_, **kw\n    )\n\n    f = interpolate.interp1d(model['time (s)'], model['rsh (ohms cm^2)'])\n    y_pred = f(time_s)\n\n    base_dir = os.path.dirname(h5_file)\n    base_name = os.path.splitext(os.path.basename(h5_file))[0]\n    csv_file = os.path.join(base_dir, base_name + '.csv')\n    csv_df = pd.DataFrame(\n        data={\n            'time (s)': time_s,\n            'Rsh (ohm cm^2)': y_pred,\n            'Rsh norm': y_pred / y_pred[0]\n        }\n    )\n    csv_df.to_csv(path_or_buf=csv_file, index=False)\n\n    return y_pred\n\n\ndef get_logger(output_path, file_tag, name):\n    log_file_tag = '{0}_{1}.log'.format(file_tag, name)\n    log_file = os.path.join(output_path, log_file_tag)\n\n    # logging.basicConfig(filename=logFile, level=logging.INFO)\n    # get pnp_logger\n    fit_logger = logging.getLogger('simlog')\n    fit_logger.setLevel(logging.DEBUG)\n    # create file handler which logs even debug messages\n    fh = logging.FileHandler(log_file)\n    fh.setLevel(logging.DEBUG)\n    # create console handler and set level to debug\n    ch = logging.StreamHandler()\n    ch.setLevel(logging.DEBUG)\n    # create formatter and add it to the handlers\n    #    formatter \t= logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')\n    #    ch.setFormatter(formatter)\n    #    fh.setFormatter(formatter)\n\n    # add the handlers to the logger\n    fit_logger.addHandler(fh)\n    fit_logger.addHandler(ch)\n\n    return fit_logger\n\n\ndef simulate_rsh(S0: float, h: float, DSF: float, h5file: float, *args, **kwargs) -> np.ndarray:\n    \"\"\"\n    This function simulates the PID kinetics for a p-Si Al-BSF PV module using a trained RFR model.\n    Na transport is simulated using FEniCS.\n\n    Parameters\n    ----------\n    S0: float\n        The initial Na surface concentration at the source in 1/cm^2\n    h: float\n        The surface mass transfer coefficient at the SiNx/Si interface\n    DSF: float\n        The diffusion coefficient of Na in the stacking fault\n    args: list\n        Positional arguments\n    kwargs: dict\n        Keyword arguments\n\n    Returns\n    -------\n    np.ndarray:\n        Rsh as a function of PID stress time\n    \"\"\"\n    # The total simulation time in seconds\n    t_max = float(kwargs.get('simulation_time', 345600))\n    # Temperature in celsius\n    temp_c = float(kwargs.get('temperature', 85))\n    # The bulk concentration (cm-3)\n    c_bulk = float(kwargs.get('cb', 1E-20))\n    # The number of time steps\n    tsteps = int(kwargs.get('time_steps', 720))\n    # The surface concentration of the sourceW\n    surface_concentration = S0\n    # The rate of ingress at the source in 1/s.\n    rate_source = float(kwargs.get('rate_source', 1E-4))\n\n    # The diffusion coefficient of layer 1 in cm2/s\n    D1cms = float(kwargs.get('DSIN', 3.92E-16))\n    # The diffusion coefficient of layer 1 in cm2/s\n    D2cms = DSF\n    # The dielectric constant of the dielectric\n    er = float(kwargs.get('er', 7.0))\n    # The electric fields\n    voltage = float(kwargs.get('stress_voltage', 3.75))  # volts\n    # The geometry\n    L1 = float(kwargs.get('L1', 0.075))  # um\n    # The number of points in the sinx layer\n    x1points = int(kwargs.get('N1', 100))\n    # The thickness of the simulated Si layer in um\n    L2 = float(kwargs.get('L2', 1.0))\n    # The number of points in the layer\n    x2points = int(kwargs.get('N2', 100))\n    # The segregation coefficient at the SiNx/Si interface\n    m = float(kwargs.get('m', 1.0))\n\n    e_field = voltage / L1 / 100\n\n    # The configuration file\n    # Logging\n\n    try:\n        out_path = os.path.dirname(h5file)\n        file_tag = os.path.splitext(os.path.basename(h5file))[0]\n\n        myLogger = get_logger(out_path, file_tag, name='pnp')\n        _, _, _, _, _, _, _, _ = pnpfs.two_layers_constant_flux(\n            D1cms=D1cms, D2cms=D2cms,\n            h=h, m=m,\n            thickness_sinx=L1,\n            thickness_si=L2,\n            tempC=temp_c,\n            voltage=voltage,\n            time_s=t_max,\n            surface_concentration=surface_concentration,\n            rate=rate_source,\n            recovery_time_s=0,\n            recovery_voltage=0,\n            fcallLogger=myLogger,\n            xpoints_sinx=x1points,\n            xpoints_si=x2points,\n            tsteps=tsteps,\n            h5_storage=h5file,\n            er=er,\n            z=1.0,\n            maxr_calls=2,\n            trapping=False,\n            c_fp=0.0,\n            cbulk=c_bulk,\n            debug=True\n        )\n\n    except Exception as e:\n        traceback.print_exc()\n        print('Error occured trying to simulate.')\n        print(e)\n\n    rfr_simulator = ml_kinetics.MLSim(h5_transport_file=h5file)\n    time_s = rfr_simulator.time_s\n    requested_indices = rfr_simulator.get_requested_time_indices(time_s)\n    rsh = rfr_simulator.rsh_time_series(requested_indices=requested_indices)\n\n    result = np.empty(len(rsh), dtype=np.dtype([('time (s)', 'd'), ('rsh (ohms cm^2)', 'd')]))\n    for i, t, r in zip(range(len(time_s)), time_s, rsh):\n        result[i] = (t, r)\n    print(result)\n\n    return result\n\n\nif __name__ == \"__main__\":\n    root_dir = os.path.dirname(csv_file)\n    file_tag = os.path.basename(csv_file)\n    file_tag = os.path.splitext(file_tag)[0]\n\n    exp_df = pd.read_csv(csv_file)\n    exp_df = exp_df[exp_df['time (s)'] <= 345600]\n    time = np.array(exp_df['time (s)'].values)\n    rsh = np.array(exp_df['Rsh (ohm cm^2)'].values)\n    rsh_norm = rsh / rsh[0]\n\n    base_path = r'/home/fenics/shared/fenics/shared/pid_fit/combinations'\n\n    if not os.path.exists(base_path):\n        os.makedirs(base_path)\n    now = datetime.now()\n    time_stamp = now.strftime('%Y%m%d-%H%M%S_%f')\n    out_path = os.path.join(base_path, time_stamp)\n    if not os.path.exists(out_path):\n        os.makedirs(out_path)\n\n    # The total simulation time in seconds\n    t_max = time.max()\n    # Temperature in celsius\n    temp_c = 85\n    # The bulk concentration (cm-3)\n    c_bulk = 1E-20\n    # The number of time steps\n    tsteps = 360\n\n    # The rate of ingress at the source in 1/s.\n    rate_source = 1E-4\n\n    # The diffusion coefficient of layer 1 in cm2/s\n    D1cms = 3.92E-16\n\n    # The dielectric constant of the dielectric\n    er = 7.0\n    e_field = voltage / L1 / 100\n\n    if not os.path.exists(out_path):\n        os.makedirs(out_path)\n\n    kw = dict(\n        temperature=temperature,\n        tsteps=tsteps,\n        rate_source=rate_source,\n        DSIN=DSIN,\n        er=7.0,\n        stress_voltage=voltage,\n        L1=L1,\n        N1=N1,\n        L2=L1,\n        N2=N2,\n        time_s=time,\n        rsh_norm=rsh_norm,\n        out_path=out_path\n    )\n\n    now = datetime.now()\n    time_stamp = now.strftime('%Y%m%d-%H%M%S')\n    file_tag = '{0}_{1}'.format(file_tag, time_stamp)\n\n    n_simulations = len(S0_s) * len(h_s) * len(DSF_s)\n\n    pool = multiprocessing.Pool(70)\n\n    sim_params = []\n\n    for s in S0_s:\n        for hi in h_s:\n            for d in DSF_s:\n                filetag = create_filetag(\n                    time_s=t_max,\n                    temp_c=temp_c,\n                    sigma_s=s,\n                    zeta=rate_source,\n                    d_sf=d,\n                    ef=e_field,\n                    m=1.0,\n                    h=hi\n                )\n                h5file = os.path.join(out_path, filetag + \".h5\")\n                params = np.array([s, hi, d, h5file])\n                sim_params.append(params)\n\n    results = pool.map(partial(func, **kw), sim_params)\n    permutations_df = pd.DataFrame(data=sim_params)\n    permutations_df.columns = [\n        'S0 (1/cm^2)', 'h (cm/s)', 'D_SF (cm^2/s)', 'h5 file'\n    ]\n    pool.close()\n    costs = np.empty(n_simulations, dtype=np.float)\n\n    for i, r in permutations_df.iterrows():\n        csv_file = os.path.splitext(r['h5 file'])[0] + '.csv'\n        df = pd.read_csv(csv_file)\n        y = df['Rsh norm'].values\n        costs[i] = cost_function(y=y, rsh_norm_=rsh_norm)\n\n    permutations_df['cost'] = costs\n    csv_grid_file = os.path.join(root_dir, file_tag + \".h5\")\n    permutations_df.to_csv(path_or_buf=csv_grid_file + '_grid.csv', index=False)\n\n    idx_min = np.argmin(costs)\n    opt_h5 = permutations_df.iloc[idx_min]['h5 file']\n    rpath = os.path.dirname(opt_h5)\n    opt_basename = os.path.splitext(os.path.basename(opt_h5))[0]\n    opt_csv = os.path.join(rpath, opt_basename + '.csv')\n    opt_df = pd.read_csv(opt_csv)\n\n    # Load my style\n    with open('plotstyle.json', 'r') as style_file:\n        mpl.rcParams.update(json.load(style_file)['defaultPlotStyle'])\n\n    # Plot PID data\n    fig_pid = plt.figure(1)\n    fig_pid.set_size_inches(4.0, 3.0, forward=True)\n    fig_pid.subplots_adjust(hspace=0.1, wspace=0.1)\n    gs_0 = gridspec.GridSpec(ncols=1, nrows=1, figure=fig_pid)\n    gs_00 = gridspec.GridSpecFromSubplotSpec(\n        nrows=1, ncols=1, subplot_spec=gs_0[0], hspace=0.1,\n    )\n    ax_pid = fig_pid.add_subplot(gs_00[0, 0])\n    ax_pid.set_xlabel('Time (hr)')\n    ax_pid.set_ylabel('Normalized $R_{\\mathrm{sh}}$')\n    ax_pid.set_xlim(0, 96.)\n\n    idx = time < 96. * 3600.\n\n    ax_pid.plot(\n        time / 3600, rsh_norm, marker='o', ls='none', fillstyle='none', label='Experiment',\n        color='k'\n    )\n    ax_pid.plot(\n        time / 3600, opt_df['Rsh norm'].values,  ls='-', color='tab:red',\n        label='Best fit'\n    )\n\n    xfmt = ScalarFormatter(useMathText=True)\n    xfmt.set_powerlimits((-3, 3))\n\n    ax_pid.xaxis.set_major_formatter(xfmt)\n    ax_pid.xaxis.set_major_locator(mticker.MaxNLocator(12, prune=None))\n    ax_pid.xaxis.set_minor_locator(mticker.AutoMinorLocator(2))\n\n    ax_pid.set_yscale('log')\n\n    leg = ax_pid.legend(loc='best', frameon=True)\n    opt_fig_tag = os.path.join(root_dir, file_tag + '_optimized')\n\n    fig_pid.tight_layout()\n\n    fig_pid.savefig(opt_fig_tag + '.png', dpi=300)\n    fig_pid.savefig(opt_fig_tag + '.svg', dpi=600)\n\n    fig_pid.show()\n", "meta": {"hexsha": "aaa09d1c1c7fdb493f4bb9cf53077b85b83d93de", "size": 11858, "ext": "py", "lang": "Python", "max_stars_repo_path": "asu_fit_permutation.py", "max_stars_repo_name": "erickmartinez/pnptransport", "max_stars_repo_head_hexsha": "6ac9ae8930649abc880bf2d7fa0d9e19bee58b9e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "asu_fit_permutation.py", "max_issues_repo_name": "erickmartinez/pnptransport", "max_issues_repo_head_hexsha": "6ac9ae8930649abc880bf2d7fa0d9e19bee58b9e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "asu_fit_permutation.py", "max_forks_repo_name": "erickmartinez/pnptransport", "max_forks_repo_head_hexsha": "6ac9ae8930649abc880bf2d7fa0d9e19bee58b9e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3273657289, "max_line_length": 99, "alphanum_fraction": 0.6228706359, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.19997374755068487}}
{"text": "\"\"\"Selective sampling algorithms for ALSA\"\"\"\n\nimport random\nimport math\nimport numpy as np\nimport torch\nfrom scipy.stats import mode\n\nfrom alsa.nets.alt_common import train as sep_train\nfrom alsa.nets.common import train\nfrom alsa.config import LONG_MILESTONES\nfrom alsa.adaptation.label_shift import label_shift\n\n\ndef general_sampling(network, net_cls, dataset, args=None):  # pylint: disable=R0914,R0912,R0915\n    \"\"\"Query-by-committee (pool): disagreement between random inits of net.\"\"\"\n    # Batch-mode settings\n    batch_size = int(dataset.online_len() / args.num_batches)\n    label_batch_size = int(args.sample_prop * batch_size)\n    labeled_ptrs = np.array([], dtype=np.int32)\n\n    # Initialize committee\n    committee = [network]\n    if args.sampling_strategy in [\"qbc\"]:\n        for i in range(args.vs_size - 1):\n            this_network = net_cls(args.num_cls).to(args.device)\n            this_network.train()\n            train(this_network,\n                  dataset,\n                  epochs=args.initial_epochs,\n                  args=args,\n                  milestones=LONG_MILESTONES)\n            this_network.eval()\n            committee.append(this_network)\n\n    # Map pointers to label\n    if args.diversify == \"cheat\":\n        ys = []\n        for i in dataset.indices(split=\"online\"):\n            y, _ = dataset.train_labels[i]\n            ys.append(y)\n        ys = np.array(ys, dtype=np.int32)\n\n    # Begin batch-mode sampling\n    for batch_i in range(1, args.num_batches + 1):\n        stats = []  # Smaller stats means higher priority\n        sep_stats = []  # Bigger value means more important\n        with torch.no_grad():\n            for image, y, _ in dataset.iterate(\n                    batch_size=args.infer_batch_size,\n                    shuffle=False,\n                    split=\"online\"):\n                image = image.to(args.device)\n\n                # Aggregate domain sep\n                if args.domainsep:\n                    this_network = committee[0]\n                    this_network.eval()\n                    output = torch.exp(this_network(image))\n                    p = output.cpu().data.numpy()\n                    sep_stats.append(np.sum(-p * np.log(p + 1e-9), axis=1))\n\n                # Produce stats depending on algorithm\n                if args.sampling_strategy == \"qbc\":\n                    predictions = []\n                    for this_network in committee:\n                        this_network.eval()\n                        output = torch.exp(this_network(image))\n                        p = output.cpu().data.numpy()\n                        if not args.train_iw and not args.only_rlls_infer:\n                            p = p * dataset.label_weights\n                            p = p / np.sum(p, axis=1)[:, None]\n                        predictions.append(np.argmax(p, axis=1))\n                    predictions = np.stack(predictions)\n                    stats.append(mode(predictions, axis=0).count[0])\n                if args.sampling_strategy == \"bald\":\n                    predictions = []\n                    this_network = committee[0]\n                    this_network.train()\n                    with torch.no_grad():\n                        for _ in range(args.bald_size):\n                            output = torch.exp(this_network(image))\n                            p = output.cpu().data.numpy()\n                            if not args.train_iw and not args.only_rlls_infer:\n                                p = p * dataset.label_weights\n                                p = p / np.sum(p, axis=1)[:, None]\n                            predictions.append(np.argmax(p, axis=1))\n                    predictions = np.stack(predictions)\n                    stats.append(mode(predictions, axis=0).count[0])\n                if args.sampling_strategy == \"cheat\":\n                    this_network = committee[0]\n                    this_network.eval()\n                    output = torch.exp(this_network(image))\n                    p = output.cpu().data.numpy()\n                    if not args.train_iw and not args.only_rlls_infer:\n                        p = p * dataset.label_weights\n                        p = p / np.sum(p, axis=1)[:, None]\n                    stats.append(np.equal(np.argmax(p, axis=1), y))\n                if args.sampling_strategy == \"margin\":\n                    margin = []\n                    this_network = committee[0]\n                    this_network.eval()\n                    output = torch.exp(this_network(image))\n                    p = output.cpu().data.numpy()\n                    if not args.train_iw and not args.only_rlls_infer:\n                        p = p * dataset.label_weights\n                        p = p / np.sum(p, axis=1)[:, None]\n                    sorted_p = np.sort(p)\n                    margin = sorted_p[:, -1] - sorted_p[:, -2]\n                    stats.append(margin)\n                if args.sampling_strategy == \"maxent\":\n                    this_network = committee[0]\n                    this_network.eval()\n                    output = torch.exp(this_network(image))\n                    p = output.cpu().data.numpy()\n                    if not args.train_iw and not args.only_rlls_infer:\n                        p = p * dataset.label_weights\n                        p = p / np.sum(p, axis=1)[:, None]\n                    stats.append(-np.sum(-p * np.log(p + 1e-9), axis=1))\n                if args.sampling_strategy == \"random\":\n                    stats.append(np.random.uniform(size=(len(image), )))\n\n            if args.diversify in [\"guess\", \"overguess\"]:\n                # Produce new ys\n                ys = []\n                network.eval()\n                for image, _, _ in dataset.iterate(\n                        batch_size=args.infer_batch_size,\n                        shuffle=False,\n                        split=\"online\"):\n                    image = image.to(args.device)\n                    output = torch.exp(network(image))\n                    p = output.cpu().data.numpy()\n                    if not args.train_iw and not args.only_rlls_infer:\n                        p = p * dataset.label_weights\n                        p = p / np.sum(p, axis=1)[:, None]\n                    ys.append(np.argmax(p, axis=1))\n                ys = np.concatenate(ys)\n\n        # Concatenate stats\n        stats = np.concatenate(stats)\n\n        if args.domainsep:\n            sep_stats = np.concatenate(sep_stats)\n            sep_stats[sep_stats < 0.5] = 0\n            sep_odds = np.uniform(size=sep_stats.shape)\n            selection = np.greater(sep_odds, np.uniform(size=sep_stats.shape))\n            stats[~selection] = np.infty\n\n        # Stack stats\n        new_ptrs = np.setdiff1d(np.arange(len(stats)), labeled_ptrs)\n        sorted_ptrs = new_ptrs[np.argsort(stats[new_ptrs])]\n\n        if args.diversify == \"none\":\n            labeled_ptrs = np.concatenate(\n                [labeled_ptrs, sorted_ptrs[:label_batch_size]])\n        elif args.diversify == \"guess\":\n            # Take top examples from each label\n            sorted_ptrs_by_label = {y: [] for y in range(args.num_cls)}\n            for ptr in sorted_ptrs:\n                sorted_ptrs_by_label[ys[ptr]].append(ptr)\n\n            # Of remaining ptrs per label, find most equal allocation\n            label_lens = sorted(\n                [len(x) for x in sorted_ptrs_by_label.values()])\n            for i, l in enumerate(label_lens):\n                size = math.ceil((label_batch_size - sum(label_lens[:i])) /\n                                 len(label_lens[i:]))\n                if size <= l:\n                    break\n                size = -1\n            if size == -1:\n                raise ValueError()\n\n            # Label pts per each\n            for k, ptrs in sorted_ptrs_by_label.items():\n                labeled_ptrs = np.concatenate([labeled_ptrs, ptrs[:size]])\n            assert len(np.unique(labeled_ptrs)) == len(labeled_ptrs)\n        elif args.diversify == \"overguess\":\n            # Take top examples from each label\n            sorted_ptrs_by_label = {y: [] for y in range(args.num_cls)}\n            for ptr in sorted_ptrs:\n                sorted_ptrs_by_label[ys[ptr]].append(ptr)\n\n            # Label pts per each\n            for k, ptrs in sorted_ptrs_by_label.items():\n                size = math.ceil(dataset.label_weights[k] /\n                                 sum(dataset.label_weights) * label_batch_size)\n                labeled_ptrs = np.concatenate([labeled_ptrs, ptrs[:size]])\n            assert len(np.unique(labeled_ptrs)) == len(labeled_ptrs)\n\n        dataset.label_ptrs(labeled_ptrs)\n\n        # Note sample proportion\n        print(\"Sample proportion: \", len(labeled_ptrs) / dataset.online_len())\n\n        # Train networks on current batch status\n        if args.domainsep:\n            committee[0].train()\n            sep_train(committee[0],\n                      dataset,\n                      epochs=args.partial_epochs,\n                      lr=args.finetune_lr,\n                      args=args)\n            committee[0].eval()\n\n        for this_network in committee:\n            this_network.train()\n            train(this_network,\n                  dataset,\n                  epochs=args.partial_epochs,\n                  lr=args.finetune_lr,\n                  args=args)\n            this_network.eval()\n\n        # Handle reweighting procedure\n        if args.iterative_iw:\n            label_shift(committee[0], dataset, args)\n\n        yield committee[0]\n\n\n######################################################################\ndef iwal_bootstrap_old(network, net_cls, dataset, args=None):\n    \"\"\"Query-by-committee (pool): disagreement between random inits of net.\"\"\"\n    # Batch-mode settings\n    batch_size = int(dataset.online_len() / args.num_batches)\n    label_batch_size = int(args.sample_prop * batch_size)\n    labeled_ptrs = np.array([], dtype=np.int32)\n\n    # Initialize committee\n    committee = [\n            network\n    ]\n    for i in range(args.vs_size - 1):\n        this_network = net_cls(args.num_cls).to(args.device)\n        this_network.train()\n        train(this_network,\n              dataset,\n              epochs=args.initial_epochs,\n              args=args,\n              milestones=LONG_MILESTONES)\n        this_network.eval()\n        committee.append(this_network)\n\n    last_ptr = 0\n\n    # Begin batch-mode sampling\n    for batch_i in range(1, args.num_batches + 1):\n        # Process IWAL probabilities\n        all_probs = np.zeros(\n            (len(committee), args.num_cls, dataset.online_len()))\n        with torch.no_grad():\n            # Get committee probability predictions\n            for model_i, model in enumerate(committee):\n                model.eval()\n                probs = [list() for i in range(args.num_cls)]\n                for (data, _,\n                     _) in dataset.iterate(batch_size=args.infer_batch_size,\n                                           shuffle=False,\n                                           split=\"online\"):\n                    data = data.to(args.device)\n                    logits = model(data)\n                    output = torch.exp(logits)  # p(y | x)\n                    output = output.cpu().data.numpy()\n                    if not args.train_iw and not args.only_rlls_infer:\n                        output = output * dataset.label_weights\n                        output = output / np.sum(output, axis=1)[:, None]\n                    for i in range(args.num_cls):\n                        probs[i].append(output[:, i])\n                for i, x in enumerate(probs):\n                    all_probs[model_i, i] = np.concatenate(x)\n\n            # Get ys for diversification\n            if args.diversify in [\"guess\", \"overguess\"]:\n                # Produce new ys\n                ys = []\n                network.eval()\n                for image, _, _ in dataset.iterate(\n                        batch_size=args.infer_batch_size,\n                        shuffle=False,\n                        split=\"online\"):\n                    image = image.to(args.device)\n                    output = torch.exp(network(image))\n                    p = output.cpu().data.numpy()\n                    if not args.train_iw and not args.only_rlls_infer:\n                        p = p * dataset.label_weights\n                        p = p / np.sum(p, axis=1)[:, None]\n                    ys.append(np.argmax(p, axis=1))\n                ys = np.concatenate(ys)\n\n        all_probs = np.transpose(all_probs, [2, 0, 1])\n        # For some datapoint and some label, this is largest disagreement in prob:\n        probs_disagreement = np.max(all_probs, axis=1) - np.min(all_probs, axis=1)\n        assert probs_disagreement.shape == (dataset.online_len(), args.num_cls)\n        # For some datapoint, this is largest disagreement in prob:\n        probs_disagreement = np.max(probs_disagreement, axis=1)\n        sample_probs = args.iwal_normalizer + \\\n            (1 - args.iwal_normalizer) * probs_disagreement\n\n        if args.diversify == \"none\":\n            sample_probs = sample_probs\n        elif args.diversify == \"guess\":\n            yunique, ycounts = np.unique(ys, return_counts=True)\n            ycounts = np.array(ycounts, dtype=np.float32) / np.sum(ycounts)\n            ycounts += 1e-4\n            ycounts = 1 / ycounts\n            ycounts = ycounts / np.sum(ycounts)\n            dss = {}\n            for y, c in zip(yunique, ycounts):\n                dss[y] = c\n            for i, y in enumerate(ys):\n                all_probs[i] *= dss[y]\n\n        # Labeled data\n        labeled_ptrs = np.array([], dtype=np.int32)\n        new_ptrs = []\n        for i in range(last_ptr, dataset.online_len()):\n            if len(labeled_ptrs) > label_batch_size:\n                break\n            sample_probs[i] = max(sample_probs[i], 0)\n            sample_probs[i] = min(sample_probs[i], 1)\n            if random.random() < sample_probs[i]:\n                last_ptr = i\n                new_ptrs.append(i)\n        labeled_ptrs = np.concatenate(\n            [labeled_ptrs, np.array(new_ptrs, dtype=np.int32)])\n        dataset.label_ptrs(labeled_ptrs)\n\n        # Note sample proportion\n        print(\"Sample proportion: \", len(labeled_ptrs) / dataset.online_len())\n\n        # Train networks on current batch status\n        for this_network in committee:\n            this_network.train()\n            train(this_network,\n                  dataset,\n                  epochs=args.partial_epochs,\n                  lr=args.finetune_lr,\n                  args=args)\n            this_network.eval()\n\n        # Handle reweighting procedure\n        if args.iterative_iw:\n            label_shift(committee[0], dataset, args)\n\n        yield committee[0]\n\n\ndef iwal_bootstrap(network, net_cls, dataset, args=None):\n    \"\"\"Query-by-committee (pool): disagreement between random inits of net.\"\"\"\n    # Batch-mode settings\n    batch_size = int(dataset.online_len() / args.num_batches)\n    label_batch_size = int(args.sample_prop * batch_size)\n    labeled_ptrs = np.array([], dtype=np.int32)\n\n    # Initialize committee\n    committee = [\n            network\n    ]\n\n    last_ptr = 0\n\n    # Begin batch-mode sampling\n    for batch_i in range(1, args.num_batches + 1):\n        # Process IWAL probabilities\n        all_probs = np.zeros(\n            (args.bald_size, args.num_cls, dataset.online_len()))\n        model = network\n        model.train()\n        with torch.no_grad():\n            # Get committee probability predictions\n            for model_i in range(args.bald_size):\n                probs = [list() for i in range(args.num_cls)]\n                for (data, _,\n                     _) in dataset.iterate(batch_size=args.infer_batch_size,\n                                           shuffle=False,\n                                           split=\"online\"):\n                    data = data.to(args.device)\n                    logits = model(data)\n                    output = torch.exp(logits)  # p(y | x)\n                    output = output.cpu().data.numpy()\n                    if not args.train_iw and not args.only_rlls_infer:\n                        output = output * dataset.label_weights\n                        output = output / np.sum(output, axis=1)[:, None]\n                    for i in range(args.num_cls):\n                        probs[i].append(output[:, i])\n                for i, x in enumerate(probs):\n                    all_probs[model_i, i] = np.concatenate(x)\n\n            # Get ys for diversification\n            model.eval()\n            if args.diversify in [\"guess\", \"overguess\", \"subguess\"]:\n                # Produce new ys\n                ys = []\n                network.eval()\n                for image, _, _ in dataset.iterate(\n                        batch_size=args.infer_batch_size,\n                        shuffle=False,\n                        split=\"online\"):\n                    image = image.to(args.device)\n                    output = torch.exp(network(image))\n                    p = output.cpu().data.numpy()\n                    if not args.train_iw and not args.only_rlls_infer:\n                        p = p * dataset.label_weights\n                        p = p / np.sum(p, axis=1)[:, None]\n                    ys.append(np.argmax(p, axis=1))\n                ys = np.concatenate(ys)\n\n        all_probs = np.transpose(all_probs, [2, 0, 1])\n        # For some datapoint and some label, this is largest disagreement in prob:\n        probs_disagreement = np.max(all_probs, axis=1) - np.min(all_probs, axis=1)\n        assert probs_disagreement.shape == (dataset.online_len(), args.num_cls)\n        # For some datapoint, this is largest disagreement in prob:\n        probs_disagreement = np.max(probs_disagreement, axis=1)\n        sample_probs = args.iwal_normalizer + \\\n            (1 - args.iwal_normalizer) * probs_disagreement\n\n        print(\"Original sample_probs:\", sample_probs)\n\n        if args.diversify == \"none\":\n            sample_probs = sample_probs\n        elif args.diversify == \"guess\":\n            yunique, ycounts = np.unique(ys, return_counts=True)\n            ycounts = np.array(ycounts, dtype=np.float32) / np.sum(ycounts)\n            ycounts += 1e-4\n            ycounts = 1 / ycounts\n            ycounts = ycounts / np.sum(ycounts)\n            dss = {}\n            for y, c in zip(yunique, ycounts):\n                dss[y] = c\n            for i, y in enumerate(ys):\n                all_probs[i] *= dss[y]\n        elif args.diversify == \"subguess\":\n            yunique = np.unique(ys)\n            ycounts = np.sqrt(dataset.first_weight)\n            ycounts += 1e-4\n            ycounts = ycounts / np.sum(ycounts)\n            dss = {}\n            for y, c in zip(yunique, ycounts):\n                dss[y] = c\n            for i, y in enumerate(ys):\n                all_probs[i] *= dss[y]\n\n        # Labeled data\n        new_ptrs = []\n        for i in range(last_ptr, dataset.online_len()):\n            if len(new_ptrs) > label_batch_size:\n                break\n            sample_probs[i] = max(sample_probs[i], 0)\n            sample_probs[i] = min(sample_probs[i], 1)\n            if random.random() < sample_probs[i]:\n                last_ptr = i\n                new_ptrs.append(i)\n        labeled_ptrs = np.concatenate(\n            [labeled_ptrs, np.array(new_ptrs, dtype=np.int32)])\n        dataset.label_ptrs(labeled_ptrs)\n\n        # Note sample proportion\n        print(\"Sample proportion: \", len(labeled_ptrs) / dataset.online_len())\n\n        # Train networks on current batch status\n        for this_network in committee:\n            this_network.train()\n            train(this_network,\n                  dataset,\n                  epochs=args.partial_epochs,\n                  lr=args.finetune_lr,\n                  args=args)\n            this_network.eval()\n\n        # Handle reweighting procedure\n        if args.iterative_iw:\n            label_shift(committee[0], dataset, args)\n\n        yield committee[0]\n", "meta": {"hexsha": "028ce4482efab3a700b700d899c6181a678bd627", "size": 19930, "ext": "py", "lang": "Python", "max_stars_repo_path": "alsa/sampling.py", "max_stars_repo_name": "ericzhao28/ALLS", "max_stars_repo_head_hexsha": "7d85650926857ea5497444c12f093832efc33ba1", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-10T20:20:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-01T14:40:19.000Z", "max_issues_repo_path": "alsa/sampling.py", "max_issues_repo_name": "ericzhao28/ALLS", "max_issues_repo_head_hexsha": "7d85650926857ea5497444c12f093832efc33ba1", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-05-03T09:53:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-20T00:36:23.000Z", "max_forks_repo_path": "alsa/sampling.py", "max_forks_repo_name": "ericzhao28/ALLS", "max_forks_repo_head_hexsha": "7d85650926857ea5497444c12f093832efc33ba1", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-12-14T02:16:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T23:08:49.000Z", "avg_line_length": 41.7819706499, "max_line_length": 96, "alphanum_fraction": 0.5189663823, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.1999737435643712}}
{"text": "\"\"\"\nIonization Modeling for MCMC setup.  This also contains stand-alone model\nprediction.\n\"\"\"\n\nimport numpy as np\n# interpolation on regular grid in arbitrary dimension\nfrom scipy.interpolate import RectBivariateSpline, interp1d\nfrom scipy.interpolate import RegularGridInterpolator\nfrom read_solarabund import SpecieMetalFraction, MetalFraction, NumberFraction\n\n################################################################################\n# utils\n################################################################################\n\n\ndef helper(ion):\n    if ion == 'h1':\n        return 'H'\n    elif ion == 'c2' or ion == 'c3' or ion == 'c4':\n        return 'C'\n    elif ion == 'ne8':\n        return 'Ne'\n    elif ion == 'n5' or ion == 'n2' or ion == 'n3':\n        return 'N'\n    elif ion == 's2' or ion == 's3' or ion == 's4':\n        return 'Si'\n    elif ion == 'o1' or ion == 'o6':\n        return 'O'\n    elif ion == 'mg1' or ion == 'mg2':\n        return 'Mg'\n    elif ion == 'fe2':\n        return 'Fe'\n\n\ndef ion_lists():\n    ions = np.array(['h1', 'c2', 'c3', 'c4', 'n2', 'n3',\n                     's2', 's3', 's4', 'o1',\n                     'o6', 'ne8', 'n5', 'mg2', 'fe2'])\n    return ions\n\n\ndef Cloudy_InputParamers():\n    lognH = np.arange(-6.0, 0.2, 0.2)\n    logNHI = np.arange(15, 19.2, 0.2)\n    logT = np.arange(4.0, 7.2, 0.2)\n    return lognH, logNHI, logT\n\n\ndef Cloudy_InputParamers_redshift(): \n    low_redshift = np.arange(0, 3.0, 0.2)\n    high_redshift = np.arange(3.0, 7.5, 0.5)\n    redshift = np.sort(np.concatenate((low_redshift, high_redshift)))\n\n    lognH = np.arange(-7.0, 0.2, 0.2)\n    logT = np.arange(3.5, 7.1, 0.2)\n    return lognH, logT, redshift\n\n\ndef GenericModelInterp(gal_z, ion_name, model_choice):\n\n    input_path = '/Users/cameronliang/research/cloudy_models'\n    if model_choice == 'photo_collision_thin':\n\n        # load the CLOUDY input parameters\n        clognH, clogT, redshift = Cloudy_InputParamers_redshift()\n\n        # Load the ionization fraction grid\n        path = input_path + '/photo_collision_thin/CombinedGrid/cubes/'\n        ind = int(np.where(abs(redshift-gal_z) < 0.1)[0])  # Use the closest z\n        ion = np.load(path + ion_name + '.npy')[ind, :, :]\n\n        # Interpolate the function\n        f = np.vectorize(RectBivariateSpline(clognH, clogT, ion))\n\n    elif model_choice == 'photo_collision_noUVB':\n        clognH, clogNHI, clogT = Cloudy_InputParamers()\n        path = input_path + '/photo_collision_rahmati/f0.0/cubes/'\n        ion = np.load(path + ion_name + '.npy')\n        f = np.vectorize(RectBivariateSpline(clognH, clogT, ion))\n\n    elif model_choice == 'photo_collision_rahmati':\n        # will change name from optically_thick_rahmati\n        # to photo_collision_rahmati after the models are finished\n        clognH, clogNHI, clogT = Cloudy_InputParamers()\n        path = input_path + '/' + model_choice + '/CombinedGrid/cubes/'\n        cgamma_ratios = np.load(path + '/uvb_fraction.npy')\n        ion = np.load(path + ion_name + '.npy')\n        f = RegularGridInterpolator((clognH, clogT, cgamma_ratios), ion)\n\n    elif model_choice == 'jv_model':\n        path = input_path + '/' + model_choice + '/combined_grid/cubes/'\n        amp_a = np.load(path+'a.npy')\n        amp_b = np.load(path+'b.npy')\n        clognH = np.load(path+'lognH.npy')\n        clogNHI = np.load(path+'logNHI.npy')\n        ion = np.load(path + ion_name + '.npy')\n\n        f = RegularGridInterpolator((amp_a, amp_b, clognH, clogNHI), ion)\n\n    elif model_choice == 'photo_collision_thick':\n        clognH = np.arange(-6, 0.2, 0.2)\n        clogNHI = np.arange(15, 19.2, 0.2)\n        clogT = np.arange(3.8, 6.2, 0.2)\n        path = input_path + '/' + model_choice + '/CombinedGrid/cubes/'\n        ion = np.load(path + ion_name + '.npy')\n        f = RegularGridInterpolator((clognH, clogNHI, clogT), ion)\n\n    elif model_choice == 'photo_thick':\n        credshift = np.arange(0, 0.4, 0.1)\n        clogNHI = np.arange(14, 22.2, 0.2)\n        clognH = np.arange(-4.2, 0.2, 0.2)\n        path = input_path + '/' + model_choice + '/CombinedGrid/cubes/'\n\n        #ind = int(np.where(abs(redshift-gal_z) < 0.1)[0]) # Use the closest z\n        ion = np.load(path + ion_name + '.npy')  # [ind,:,:]\n        f_3D = RegularGridInterpolator((credshift, clognH, clogNHI), ion)\n\n        new_ion = np.zeros((len(clognH), len(clogNHI)))\n        for i in range(len(clognH)):\n            for j in range(len(clogNHI)):\n                new_ion[i][j] = f_3D((gal_z, clognH[i], clogNHI[j]))\n        f = RectBivariateSpline(clognH, clogNHI, new_ion)\n\n    elif model_choice == 'photo_thick_aUV':\n        # c before aUV just means cloudy grid values\n        credshift = np.arange(0, 0.4, 0.1)\n        caUV = np.arange(-3, 2.0, 0.5)\n        clogNHI = np.arange(14, 22, 0.3)\n        clognH = np.linspace(-4.4, 0., 12)\n        path = input_path + '/' + model_choice + '/grids/CombinedGrid/cubes/'\n\n        ion = np.load(path + ion_name + '.npy')  # 4D array\n        f_4D = RegularGridInterpolator((credshift, caUV, clognH, clogNHI), ion)\n\n        new_ion = np.zeros(( len(caUV), len(clognH), len(clogNHI) ))\n        for i in range(len(caUV)):\n            for j in range(len(clognH)):\n                for k in range(len(clogNHI)):\n                    new_ion[i][j][k] = f_4D((gal_z, caUV[i], clognH[j], clogNHI[k]))\n\n        f = RegularGridInterpolator((caUV, clognH, clogNHI), new_ion)\n\n    return f\n\n\ndef GetAllIonFunctions(gal_z, model_choice):\n    ions_names = ion_lists()\n    f = []\n    for ion_name in ions_names:\n        f.append(GenericModelInterp(gal_z, ion_name, model_choice))\n    f = np.array(f)\n\n    # Make the dictionary between functions and ionization state\n    dict_intepfunc = {}\n    for i in range(len(ions_names)):\n        dict_intepfunc[ions_names[i]] = f[i]\n    return dict_intepfunc\n\n#############################################################################\n# Physics related Utils\n#############################################################################\n\n\ndef ComputeGammaRatio(lognH):\n    \"\"\"\n    ratio = Gamma/Gamma_UVB\n    eqn 14. from Rahmati 2013.\n    \"\"\"\n    # value taken from table 2 Rahmati+ 2013\n    nH_ssh = 5.1*1.0e-4\n    nH = 10**lognH\n    ratio = 0.98*(1+(nH/nH_ssh)**1.64)**-2.28 + 0.02*(1+nH/nH_ssh)**-0.84\n    return ratio\n\n\ndef logZfrac(logZ, specie):\n    # logZ is in solar units already\n    logNx_NH = NumberFraction(specie)  # number density ratio in the sun\n    return logZ + logNx_NH\n\n###############################################################################\n\n\nclass DefineIonizationModel:\n    def __init__(self, config_params):\n        self.config_params = config_params\n        self.logf_ion = GetAllIonFunctions(config_params.model_redshift,\n                                           config_params.model)\n\n    def model_prediction(self, alpha, ion_name):\n        \"\"\"\n        Calculate column density given a specific ion, and the model\n        parameters in a photo-ionization model\n        \"\"\"\n        specie = helper(ion_name)\n        if ion_name == 'h1':\n            logNHI = alpha[-1]\n            return logNHI\n        else:\n            if self.config_params.model == 'photo_collision_thin':\n                lognH, logZ, logT, logNHI = alpha\n                if -6 < lognH < 0 and 10 < logNHI <= 22 and 3.8 <= logT < 7:\n                    logN = (self.logf_ion[ion_name](lognH, logT) -\n                            self.logf_ion['h1'](lognH, logT) +\n                            logNHI)[0][0]\n                else:\n                    logN = -np.inf\n\n            elif self.config_params.model == 'photo_collision_noUVB':\n                lognH, logZ, logT, logNHI = alpha\n                logN = (self.logf_ion[ion_name](lognH, logT) -\n                        self.logf_ion['h1'](lognH, logT) +\n                        logZfrac(logZ, specie) + logNHI)[0][0]\n\n            elif self.config_params.model == 'photo_collision_rahmati':\n                lognH, logZ, logT, logNHI = alpha\n                if lognH < -6:\n                    lognH = -6.0  # because the models were not run below -6\n                elif lognH > 0:\n                    lognH = 0.\n\n                gamma_ratio = ComputeGammaRatio(lognH)\n                logN = (self.logf_ion[ion_name]((lognH, logT, gamma_ratio)) -\n                        self.logf_ion['h1']((lognH, logT, gamma_ratio)) +\n                        logZfrac(logZ, specie) + logNHI)[0][0]\n\n            elif self.config_params.model == 'photo_collision_thick':\n                lognH, logZ, logT, logNHI = alpha\n                # ranges to protect out of range in interpolated function\n                if -6. < lognH <= 0. and 10. < logNHI <= 19. and 3.8 <= logT < 6.:\n                    if logNHI <= 15:\n                        ifrac_alpha = np.array([lognH, 15.0, logT])\n                    else:\n                        ifrac_alpha = np.array([lognH, logNHI, logT])\n                    logN = (self.logf_ion[ion_name](ifrac_alpha) -\n                            self.logf_ion['h1'](ifrac_alpha) +\n                            logZfrac(logZ, specie) + logNHI)[0]\n                else:\n                    logN = -np.inf\n\n            elif self.config_params.model == 'jv_model':\n                amp_a, amp_b, lognH, logZ, logNHI = alpha\n                print 'enter'\n                # ranges to protect out of range in interpolated function\n                if (-5.0 < lognH <= 0. and 10. < logNHI <= 19. and -1 <\n                   amp_a <= 4 and -1 < amp_b <= 1):\n                    if logNHI <= 10:\n                        ifrac_alpha = np.array([amp_a, amp_b, lognH, 10.0])\n                    else:\n                        print 'here???'\n                        ifrac_alpha = np.array([amp_a, amp_b, lognH, logNHI])\n                    logN = (self.logf_ion[ion_name](ifrac_alpha) -\n                            self.logf_ion['h1'](ifrac_alpha) +\n                            logZfrac(logZ, specie) + logNHI)[0]\n                else:\n                    print 'here!!'\n                    logN = -np.inf\n\n            elif self.config_params.model == 'photo_fix_logT_thin':\n                lognH, logZ, logNHI = alpha\n                logT = 4.0  # one can fix this to whatever tempature\n                logN = (self.logf_ion[ion_name](lognH, logT) -\n                        self.logf_ion['h1'](lognH, logT) +\n                        logZfrac(logZ, specie) + logNHI)\n\n            elif self.config_params.model == 'photo_thick':\n                lognH, logZ, logNHI = alpha\n                if -4.2 < lognH < 0 and 0 < logNHI <= 22:\n                    if logNHI < 14:\n                        # if < 14, use optically thin for all values of NHI\n                        logN = (self.logf_ion[ion_name](lognH, 14.0) -\n                                self.logf_ion['h1'](lognH, logNHI) +\n                                logZfrac(logZ, specie) + logNHI)[0][0]\n                    else:\n                        logN = (self.logf_ion[ion_name](lognH, logNHI) -\n                                self.logf_ion['h1'](lognH, logNHI) +\n                                logZfrac(logZ, specie) + logNHI)[0][0]\n                else:\n                    logN = -np.inf\n\n            elif self.config_params.model == 'photo_thick_aUV':\n                lognH, logZ, aUV, logNHI = alpha\n                if -4.2 <= lognH < 0 and -3 <= aUV < 2 and 0 < logNHI <= 22:\n                    if logNHI <= 14:\n                        # if < 14 use optically thin for all values of NHI\n                        logN = (self.logf_ion[ion_name]((aUV, lognH, 14.0)) -\n                                self.logf_ion['h1']((aUV, lognH, 14.0)) +\n                                logZfrac(logZ, specie) + logNHI)\n                    else:\n                        logN = (self.logf_ion[ion_name]((aUV, lognH, logNHI)) -\n                                self.logf_ion['h1']((aUV, lognH, logNHI)) +\n                                logZfrac(logZ, specie) + logNHI)\n                else:\n                    logN = -np.inf\n            return logN\n\n####################################\n\n\nclass DefineIonizationModel_test:\n    \"\"\"\n    A Ionization model class\n    \"\"\"\n    def __init__(self, model, model_redshift):\n        self.model = model\n        self.logf_ion = GetAllIonFunctions(model_redshift, model)\n\n    def produce_ion_logn(self, alpha, ion_name):\n        if self.model == 'photo_collision_thin':\n            # for this model ony.. for now\n            lognH, logZ, logT = alpha\n            specie = helper(ion_name)\n            if ion_name == 'h1':\n                logn_ion = self.logf_ion[ion_name](lognH, logT) + lognH\n            else:\n                logn_ion = self.logf_ion[ion_name](lognH, logT) + \\\n                            logZfrac(logZ, specie) + lognH\n        return logn_ion[0][0]\n\n    def model_prediction(self, alpha, ion_name):\n        \"\"\"\n        Calculate column density given a specific ion, and the model\n        parameters in a photo-ionization model\n        \"\"\"\n        specie = helper(ion_name)\n        if ion_name == 'h1':\n            logNHI = alpha[-1]\n            return logNHI\n        else:\n            if self.model == 'photo_collision_thin':\n                lognH, logZ, logT, logNHI = alpha\n                if -6 < lognH < 0 and 10 < logNHI <= 22 and 3.8 <= logT < 7:\n                    logN = (self.logf_ion[ion_name](lognH, logT) -\n                            self.logf_ion['h1'](lognH, logT) +\n                            logNHI)[0][0]\n                else:\n                    logN = -np.inf\n\n            elif self.model == 'photo_collision_noUVB':\n                lognH, logZ, logT, logNHI = alpha\n                logN = (self.logf_ion[ion_name](lognH, logT) -\n                        self.logf_ion['h1'](lognH, logT) +\n                        logZfrac(logZ, specie) + logNHI)[0][0]\n\n            elif self.model == 'photo_collision_rahmati':\n                lognH, logZ, logT, logNHI = alpha\n                if lognH < -6:\n                    lognH = -6.0  # because the models were not run below -6\n                elif lognH > 0:\n                    lognH = 0.\n                gamma_ratio = ComputeGammaRatio(lognH)\n                logN = (self.logf_ion[ion_name]((lognH, logT, gamma_ratio)) -\n                        self.logf_ion['h1']((lognH, logT, gamma_ratio)) +\n                        logZfrac(logZ, specie) + logNHI)[0][0]\n\n            elif self.model == 'photo_collision_thick':\n                lognH, logZ, logT, logNHI = alpha\n                # ranges to protect out of range in interpolated function\n                if -6. < lognH <= 0. and 10. < logNHI <= 19. and 3.8 <= logT < 6.:\n                    if logNHI <= 15:\n                        ifrac_alpha = np.array([lognH, 15.0, logT])\n                    else:\n                        ifrac_alpha = np.array([lognH, logNHI, logT])\n                    logN = (self.logf_ion[ion_name](ifrac_alpha) -\n                            self.logf_ion['h1'](ifrac_alpha) +\n                            logZfrac(logZ, specie) + logNHI)[0]\n                else:\n                    logN = -np.inf\n\n            elif self.model == 'jv_model':\n                amp_a, amp_b, lognH, logZ, logNHI = alpha\n                # ranges to protect out of range in interpolated function\n                if (-6. < lognH <= 0. and 10. < logNHI <= 19. and -1 <\n                   amp_a <= 4 and -1 <= amp_b < 4):\n                    if logNHI <= 10:\n                        ifrac_alpha = np.array([amp_a, amp_b, lognH, 10.0])\n                    else:\n                        ifrac_alpha = np.array([amp_a, amp_b, lognH, logNHI])\n                    logN = (self.logf_ion[ion_name](ifrac_alpha) -\n                            self.logf_ion['h1'](ifrac_alpha) +\n                            logZfrac(logZ, specie) + logNHI)[0]\n                else:\n                    logN = -np.inf\n\n            elif self.model == 'photo_fix_logT_thin':\n                lognH, logZ, logNHI = alpha\n                logT = 4.0  # one can fix this to whatever tempature\n                logN = (self.logf_ion[ion_name](lognH, logT) -\n                        self.logf_ion['h1'](lognH, logT) +\n                        logZfrac(logZ, specie) + logNHI)\n\n            elif self.model == 'photo_thick':\n                lognH, logZ, logNHI = alpha\n                if -4.2 < lognH < 0 and 0 < logNHI <= 22:\n                    if logNHI < 14:\n                        # if < 14, use optically thin for all values of NHI\n                        logN = (self.logf_ion[ion_name](lognH, 14.0) -\n                                self.logf_ion['h1'](lognH, logNHI) +\n                                logZfrac(logZ, specie) + logNHI)[0][0]\n                    else:\n                        logN = (self.logf_ion[ion_name](lognH, logNHI) -\n                                self.logf_ion['h1'](lognH, logNHI) +\n                                logZfrac(logZ, specie) + logNHI)[0][0]\n                else:\n                    logN = -np.inf\n\n            elif self.model == 'photo_thick_aUV':\n                lognH, logZ, aUV, logNHI = alpha\n                if -4.2 <= lognH < 0 and -3 <= aUV < 2 and 0 < logNHI <= 22:\n                    if logNHI <= 14:\n                        # if < 14 use optically thin for all values of NHI\n                        logN = (self.logf_ion[ion_name]((aUV, lognH, 14.0)) -\n                                self.logf_ion['h1']((aUV, lognH, 14.0)) +\n                                logZfrac(logZ, specie) + logNHI)\n                    else:\n                        logN = (self.logf_ion[ion_name]((aUV, lognH, logNHI)) -\n                                self.logf_ion['h1']((aUV, lognH, logNHI)) +\n                                logZfrac(logZ, specie) + logNHI)\n                else:\n                    logN = -np.inf\n            return logN\n\n\ndef AskForParameters(model):\n    lognH = float(raw_input(\"lognH = \"))\n    logZ = float(raw_input(\"logZ/Zsun = \"))\n\n    if model == 'photo_thick_aUV':\n        aUV = float(raw_input(\"aUV = \"))\n        logNHI = float(raw_input(\"logNHI = \"))\n        alpha = np.array([lognH, logZ, aUV, logNHI])\n\n    elif model == 'photo_thick':\n        logNHI = float(raw_input(\"logNHI = \"))\n        alpha = np.array([lognH, logZ, logNHI])\n\n    elif model == 'jv_model':\n        logNHI = float(raw_input(\"logNHI = \"))\n        amp_a = float(raw_input(\"a = \"))\n        amp_b = float(raw_input(\"b = \"))\n        alpha = np.array([amp_a, amp_b, lognH, logZ, logNHI])\n\n    elif (model == 'photo_collision_thick' or\n          model == 'photo_collision_rahmati' or\n          model == 'photo_collision_thin'):\n        logT = float(raw_input(\"logT = \"))\n        logNHI = float(raw_input(\"logNHI = \"))\n        alpha = np.array([lognH, logZ, logT, logNHI])\n    else:\n        print(\"Your model does not exist. Did you have a typo?\")\n        print(\"photo_collision_thin\")\n        print(\"photo_collision_thick\")\n        print(\"photo_collision_rahmati\")\n        print(\"photo_thick\")\n        print(\"photo_thick_aUV\")\n        exit()\n    return alpha\n\nif __name__ == '__main__':\n\n    import sys\n    model = sys.argv[1]\n    if model == 'jv_model':\n        model_redshift = 0.0\n    else:\n        model_redshift = float(sys.argv[2])\n    alpha = AskForParameters(model)\n    ion_model = DefineIonizationModel_test(model, model_redshift)\n\n    ions = ion_lists()\n    for ion in ions:\n        logN = ion_model.model_prediction(alpha, ion)\n        print(\"LogN: %s = %.2f\" % (ion, logN))\n", "meta": {"hexsha": "024df697b36968f7752e854ad9cbd5d750d48c20", "size": 19410, "ext": "py", "lang": "Python", "max_stars_repo_path": "ionfit/Model.py", "max_stars_repo_name": "cameronliang/ionfit", "max_stars_repo_head_hexsha": "137709e33a745da94442885c22fb2752ac5ae2d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ionfit/Model.py", "max_issues_repo_name": "cameronliang/ionfit", "max_issues_repo_head_hexsha": "137709e33a745da94442885c22fb2752ac5ae2d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ionfit/Model.py", "max_forks_repo_name": "cameronliang/ionfit", "max_forks_repo_head_hexsha": "137709e33a745da94442885c22fb2752ac5ae2d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.8631578947, "max_line_length": 84, "alphanum_fraction": 0.5018547141, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.19997373884349054}}
{"text": "import sys\nimport os\nimport re\nimport copy\nfrom warnings import warn\nfrom collections import OrderedDict\nimport logging\nimport numpy as np\n\nimport intermol.unit as units\nfrom collections import deque\nfrom intermol.atom import Atom\nfrom intermol.molecule import Molecule\nfrom intermol.system import System\nfrom intermol.types import *\nfrom intermol.forces import *\nfrom intermol.hashmap import *\nimport math\n\nlogger = logging.getLogger('InterMolLog')\n\nclass GromacsTopologyParser(object):\n    \"\"\"\n    A class containing methods required to read in a Gromacs(4.5.4) Topology File\n    \"\"\"\n    _GroTopParser = None\n\n    def __init__(self, defines=None):\n        \"\"\"\n        Initializes a GromacsTopologyParse object which serves to read in a Gromacs\n        topology into the abstract representation.\n\n        Args:\n            defines: Sets of default defines to use while parsing.\n        \"\"\"\n        self.includes = set()       # set storing includes\n        self.defines = dict()        # list of defines\n        self.comments = list()      # list of comments\n\n        self.atomtypes = HashMap()\n        self.bondtypes = HashMap()\n        self.pairtypes = HashMap()\n        self.angletypes = HashMap()\n        self.dihedraltypes = HashMap()\n        self.constrainttypes = HashMap()\n\n        if defines:\n            self.defines.union(defines)\n            self.defines[\"FLEX_SPC\"] = None\n            self.defines[\"POSRE\"] = None\n\n    def parse_topology(self, topfile, verbose=False):\n        \"\"\"\n        Parses a Gromacs topology reading into the abstract\n\n        Args:\n            topfile: filename of the file to be parsed\n            verbose: verbose output\n        \"\"\"\n        lines = self.preprocess(topfile, verbose)\n        if lines:\n            self.read_topology(lines, verbose)\n\n    def read_topology(self, expanded, verbose=False):\n        \"\"\"\n        Read in a previously preprocessed Gromacs topology file\n\n        Args:\n            expanded: lines from a preprocessed topology file\n            verbose: verbose output\n        \"\"\"\n        sysDirective = re.compile(r\"\"\"\n          \\[[ ]{1}\n          ((?P<defaults>defaults)\n          |\n          (?P<atomtypes>atomtypes)\n          |\n          (?P<bondtypes>bondtypes)\n          |\n          (?P<pairtypes>pairtypes)\n          |\n          (?P<angletypes>angletypes)\n          |\n          (?P<dihedraltypes>dihedraltypes)\n          |\n          (?P<constrainttypes>constrainttypes)\n          |\n          (?P<nonbond_params>nonbond_params)\n          |\n          (?P<system>system))\n          [ ]{1} \\]\n        \"\"\", re.VERBOSE)\n        i = 0\n        while i < len(expanded):\n            match = sysDirective.match(expanded[i])\n            if match:\n                logger.debug(match.groups())\n                if match.group('defaults'):\n                    logger.debug(\"Parsing [ defaults ]...\")\n                    expanded.pop(i)\n\n                    fields = expanded[i].split()\n                    System._sys.nonbonded_function = int(fields[0])\n                    System._sys.combination_rule = int(fields[1])\n                    System._sys.genpairs = fields[2]\n                    System._sys.lj_correction = float(fields[3])\n                    System._sys.coulomb_correction = float(fields[4])\n\n                    expanded.pop(i)\n\n                elif match.group('atomtypes'):\n                    logger.debug(\"Parsing [ atomtypes ]...\")\n                    expanded.pop(i)\n\n                    while not (expanded[i].count('[')) and i < len(expanded)-1:\n                        split = expanded.pop(i).split()\n                        newAtomType = None\n\n                        # note -- we should be able to store either C6 and C12 parameters or sigma and epsilon: not both\n                        atomtype = split[0].strip()\n                        if len(split) == 7:  # atom name and bond type are the same, or there is no z.\n                            d = 0  #offset\n                            if (split[1].isdigit()):\n                                atomic_number = int(split[1])\n                                bondtype = split[0].strip()\n                            else:\n                                atomic_number = -1\n                                bondtype = split[1].strip()\n                        elif len(split) == 8: #atom and bond name and atomic_number\n                            d = 1\n                            bondtype = split[1].strip()            # bondtype\n                            atomic_number = split[2]                           # atomic_number\n                        else:\n                            raise Exception(\"Incorrect number of points in atomtype entry (%s)\" % split)\n\n                        mass =  float(split[2+d]) * units.amu\n                        charge = float(split[3+d]) * units.elementary_charge\n                        ptype = split[4+d]\n                        if System._sys.combination_rule == 1:\n                            sigma = (float(split[6+d]) / float(split[5+d])) ** (1.0/6.0)\n                            epsilon = float(split[5+d]) / (4*sigma**6)\n\n                            newAtomType = AtomCR1Type(atomtype,\n                                                      bondtype,\n                                                      atomic_number,\n                                                      mass,\n                                                      charge,\n                                                      ptype,\n                                                      sigma * units.kilojoules_per_mole * units.nanometers**(6),      # C6\n                                                      epsilon * units.kilojoules_per_mole * units.nanometers**(12))   # C12\n\n                        elif (System._sys.combination_rule == 2) or (System._sys.combination_rule == 3):\n                            newAtomType = AtomCR23Type(atomtype,\n                                                       bondtype,\n                                                       atomic_number,\n                                                       mass,\n                                                       charge,\n                                                       ptype,\n                                                       float(split[5+d]) * units.nanometers,           # sigma\n                                                       float(split[6+d]) * units.kilojoules_per_mole)  # epsilon\n                        System._sys._atomtypes.add(newAtomType)\n\n                elif match.group('bondtypes'):\n                    logger.debug(\"Parsing [ bondtypes ]...\")\n                    expanded.pop(i)\n\n                    while not (expanded[i].count('[')) and i < len(expanded)-1:\n                        split = expanded.pop(i).split()\n                        newBondType = None\n\n                        # Bond\n                        if int(split[2]) == 1:\n                            newBondType = BondType(split[0],\n                                    split[1],\n                                    float(split[3]) * units.nanometers,\n                                    float(split[4]) * units.kilojoules_per_mole * units.nanometers**(-2))\n\n                        # G96Bond\n                        elif int(split[2]) == 2:\n                            newBondType = G96BondType(split[0],\n                                        split[1],\n                                        float(split[3]) * units.nanometers,\n                                        float(split[4]) * units.kilojoules_per_mole * units.nanometers**(-4))\n\n                        # Morse\n                        elif int(split[2]) == 3:\n                            newBondType = MorseBondType(split[0],\n                                        split[1],\n                                        float(split[3]) * units.nanometers,\n                                        float(split[4]) * units.kilojoules_per_mole,\n                                        float(split[5]) * units.nanometers**(-1))\n\n                        # Cubic\n                        elif int(split[2]) == 4:\n                            newBondType = CubicBondType(split[0],\n                                        split[1],\n                                        float(split[3]) * units.nanometers,\n                                        float(split[4]) * units.kilojoules_per_mole * units.nanometers**(-2),\n                                        float(split[5]) * units.kilojoules_per_mole * units.nanometers**(-3))\n\n                        # Harmonic\n                        elif int(split[2]) == 6:\n                            newBondType = HarmonicPotentialType(split[0],\n                                        split[1],\n                                        float(split[3]) * units.nanometers,\n                                        float(split[4]) * units.kilojoules_per_mole * units.nanometers**(-2))\n                        else:\n                            raise Exception(\"%s is not a supported bond type\" % split[2])\n\n                        if newBondType:\n                            self.bondtypes.add(newBondType)\n\n                elif match.group('pairtypes'):\n                    logger.debug(\"Parsing [ pairtypes ]...\")\n                    expanded.pop(i)\n\n                    while not (expanded[i].count('[')) and i < len(expanded)-1:\n\n                        split = expanded.pop(i).split()\n                        newPairType = None\n                        if int(split[2]) == 1:\n                            # LJ/Coul. 1-4 (Type 1)\n                            if len(split) == 5:\n                                if System._sys.combination_rule == 1:\n                                    newPairType = LJ1PairCR1Type(split[0],\n                                            split[1],\n                                            split[2],\n                                            float(split[3]) * units.kilojoules_per_mole * units.nanometers**(6),\n                                            float(split[4]) * units.kilojoules_per_mole * units.nanometers**(12))\n\n                                elif System._sys.combination_rule == (2 or 3):\n                                    newPairType = LJ1PairCR1Type(split[0],\n                                            split[1],\n                                            split[2],\n                                            float(split[3]) * units.nanometers,\n                                            float(split[4]) * units.kilojoules_per_mole)\n\n                            # LJ/C. pair NB\n                            elif len(split) == 7:\n                                if System._sys.combination_rule == 1:\n                                    newPairType = LJ1PairCR1Type(split[0],\n                                            split[1],\n                                            split[2],\n                                            float(split[3]) * units.elementary_charge,\n                                            float(split[4]) * units.elementary_charge,\n                                            float(split[5]) * units.kilojoules_per_mole * units.nanometers**(6),\n                                            float(split[6]) * units.kilojoules_per_mole * units.nanometers**(12))\n\n                                elif System._sys.combination_rule == (2 or 3):\n                                    newPairType = LJ1PairCR1Type(split[0],\n                                            split[1],\n                                            split[2],\n                                            float(split[3]) * units.elementary_charge,\n                                            float(split[4]) * units.elementary_charge,\n                                            float(split[5]) * units.nanometers,\n                                            float(split[6]) * units.kilojoules_per_mole)\n\n                        # LJ/Coul. 1-4 (Type 2)\n                        elif int(split[2]) == 2:\n                            if System._sys.combination_rule == 1:\n                                newPairType = LJ1PairCR1Type(split[0],\n                                        split[1],\n                                        split[2],\n                                        split[3],\n                                        float(split[4]) * units.elementary_charge,\n                                        float(split[5]) * units.elementary_charge,\n                                        float(split[6]) * units.kilojoules_per_mole * units.nanometers**(6),\n                                        float(split[7]) * units.kilojoules_per_mole * units.nanometers**(12))\n\n                            elif System._sys.combination_rule == (2 or 3):\n                                newPairType = LJ1PairCR1Type(split[0],\n                                         split[1],\n                                         split[2],\n                                         split[3],\n                                         float(split[4]) * units.elementary_charge,\n                                         float(split[5]) * units.elementary_charge,\n                                         float(split[6]) * units.nanometers,\n                                         float(split[7]) * units.kilojoules_per_mole)\n\n                        else:\n                            raise Exception(\"Could not find pair type\")\n\n                        if newPairType:\n                            self.pairtypes.add(newPairType)\n\n                elif match.group('angletypes'):\n                    logger.debug(\"Parsing [ angletypes ]...\")\n                    expanded.pop(i)\n\n                    while not (expanded[i].count('[')) and i < len(expanded)-1:\n                        split = expanded.pop(i).split()\n                        newAngleType = None\n\n                        # Angle\n                        if int(split[3]) == 1:\n                            newAngleType = AngleType(split[0],\n                                    split[1],\n                                    split[2],\n                                    float(split[4]) * units.degrees,\n                                    float(split[5]) * units.kilojoules_per_mole * units.radians**(-2))\n\n                        # G96Angle\n                        elif int(split[3]) == 2:\n                            newAngleType = G96AngleType(split[0],\n                                    split[1],\n                                    split[2],\n                                    float(split[4]) * units.degrees,\n                                    float(split[5]) * units.kilojoules_per_mole)\n\n                        # Cross bond-bond\n                        elif int(split[3]) == 3:\n                            newAngleType = CrossBondBondAngleType(split[0],\n                                    split[1],\n                                    split[2],\n                                    float(split[4]) * units.nanometers,\n                                    float(split[5]) * units.nanometers,\n                                    float(split[6]) * units.kilojoules_per_mole * units.nanometers**(-2))\n\n                        # Cross bond-angle\n                        elif int(split[3]) == 4:\n                            newAngleType = CrossBondAngleAngleType(split[0],\n                                    split[1],\n                                    split[2],\n                                    float(split[4]) * units.nanometers,\n                                    float(split[5]) * units.nanometers,\n                                    float(split[6]) * units.nanometers,\n                                    float(split[7]) * units.kilojoules_per_mole * units.nanometers**(-2))\n\n                        # Urey-Bradley\n                        elif int(split[3]) == 5:\n                            newAngleType = UreyBradleyAngleType(split[0],\n                                    split[1],\n                                    split[2],\n                                    float(split[4]) * units.degrees,\n                                    float(split[5]) * units.kilojoules_per_mole * units.radians**(-2),\n                                    float(split[6]) * units.nanometers,\n                                    float(split[7]) * units.kilojoules_per_mole * units.nanometers**(-2))\n\n                        # Quartic\n                        elif int(split[3]) == 6:\n                            newAngleType = QuarticAngleType(split[0],\n                                    split[1],\n                                    split[2],\n                                    float(split[4]) * units.degrees,\n                                    float(split[5]) * units.kilojoules_per_mole,\n                                    float(split[6]) * units.kilojoules_per_mole * units.radians**(-1),\n                                    float(split[7]) * units.kilojoules_per_mole * units.radians**(-2),\n                                    float(split[8]) * units.kilojoules_per_mole * units.radians**(-3),\n                                    float(split[9]) * units.kilojoules_per_mole * units.radians**(-4))\n\n                        else:\n                            raise Exception(\"Could not find angle type\")\n\n                        if newAngleType:\n                            self.angletypes.add(newAngleType)\n\n                elif match.group('dihedraltypes'):\n                    logger.debug(\"Parsing [ dihedraltypes ]...\")\n                    expanded.pop(i)\n\n                    while not (expanded[i].count('[')) and i < len(expanded)-1:\n                        split = expanded.pop(i).split()\n                        newDihedralType = None\n                        # first, check whether they are using 2 or 4 atom types\n                        if split[2].isdigit():\n                            atom1 = 'X'\n                            atom2 = split[0]\n                            atom3 = split[1]\n                            atom4 = 'X'\n                            d = 0\n\n                        elif split[4].isdigit():\n                            atom1 = split[0]\n                            atom2 = split[1]\n                            atom3 = split[2]\n                            atom4 = split[3]\n                            d = 2\n\n                        # We can fit everything into two types of dihedrals - dihedral_trig, and improper harmonic\n                        # dihedral trig is of the form fc0 + sum_i=1^6 fci (cos(nx-phi)\n                        # proper dihedrals can be stored easily in this form, since they have only 1 n\n                        # improper dihedrals can as well (flag as improper)\n                        # RB can be stored as well, assuming phi = 0 or 180\n                        # Fourier can also be stored.\n                        # a full dihedral trig can be decomposied in to multiple proper dihedrals.\n\n                        # will need to handle this a little differently, in that we will need\n                        # to add multiple 9 dihedrals together into a single dihedral_trig, as long as they\n                        # have the same phi angle (seems to be always the case).\n\n                        dtype = int(split[2+d])\n                        nentries = len(split)\n\n                        if (dtype == 1 or dtype == 4 or dtype == 9) and nentries == 6+d:\n\n                            if dtype == 4:\n                                improper = True\n                            else:\n                                improper = False\n\n                            fc0,fc1,fc2,fc3,fc4,fc5,fc6 = ConvertDihedralFromProperDihedralToDihedralTrig(\n                                float(split[4+d])*units.kilojoules_per_mole,int(split[5+d]))\n                            newDihedralType = DihedralTrigType(\n                                atom1, atom2, atom3, atom4, float(split[3+d]) * units.degrees,\n                                fc0, fc1, fc2, fc3, fc4, fc5, fc6, improper = improper)\n\n                        # Improper Harmonic Dihedral: type 2. Can't be converted to any other type\n                        elif (dtype == 2) and nentries == 5+d:\n                            newDihedralType = ImproperHarmonicDihedralType(\n                                atom1,atom2,atom3,atom4,\n                                float(split[3+d]) * units.degrees,\n                                float(split[4+d]) * units.kilojoules_per_mole * units.radians**(-2))\n\n                        # RBDihedral: type 3\n                        elif (dtype == 3) and nentries == 9+d:\n                            fc0, fc1, fc2, fc3, fc4, fc5, fc6 = ConvertDihedralFromRBToDihedralTrig(\n                                float(split[3+d]) * units.kilojoules_per_mole,\n                                float(split[4+d]) * units.kilojoules_per_mole,\n                                float(split[5+d]) * units.kilojoules_per_mole,\n                                float(split[6+d]) * units.kilojoules_per_mole,\n                                float(split[7+d]) * units.kilojoules_per_mole,\n                                float(split[8+d]) * units.kilojoules_per_mole,\n                                0 * units.kilojoules_per_mole)\n                            newDihedralType = DihedralTrigType(\n                                atom1, atom2, atom3, atom4, 0 * units.degrees,\n                                fc0, fc1, fc2, fc3, fc4, fc5, fc6)  # need to look at the sign here\n\n                        # Fourier Dihedral 5\n                        elif dtype == 5 and nentries == 7+d:\n                            fc0, fc1, fc2, fc3, fc4, fc5, fc6  = ConvertDihedralFromFourierToDihedralTrig(\n                                float(split[3+d]) * units.kilojoules_per_mole,\n                                float(split[4+d]) * units.kilojoules_per_mole,\n                                float(split[5+d]) * units.kilojoules_per_mole,\n                                float(split[6+d]) * units.kilojoules_per_mole)\n\n                            newDihedralType = DihedralTrigType(\n                                atom1, atom2, atom3, atom4, 0 * units.degrees,\n                                fc0, fc1, fc2, fc3, fc4, fc5, fc6)\n\n                        elif dtype == 8:\n                            raise Exception(\"Tabulated dihedrals not supported\")\n                        else:\n                            raise Exception(\"Could not find dihedral type\")\n\n                        if newDihedralType:\n                            if dtype == 9:\n                                # we can't actually store multiple dihedral parameters in our\n                                # architecture, so we add up the types into a single DihedralTrigDihedral angle\n                                try:\n                                    dihedralmatch = self.dihedraltypes.get(newDihedralType)\n                                    dihedralmatch.sum_parameters(newDihedralType)\n                                except Exception as e:\n                                    logger.exception(e) # EDZ: used to be pass, now recorded but supressed\n                            self.dihedraltypes.add(newDihedralType)\n\n                elif match.group('constrainttypes'):\n                    logger.debug(\"Parsing [ constrainttypes ]...\")\n                    expanded.pop(i)\n\n                    while not (expanded[i].count('[')) and i < len(expanded)-1:\n                        #newPairType = PairType(expanded.pop(i).split())\n                        #self.pairtypes.add(newPairType)\n                        expanded.pop(i)\n\n                elif match.group('nonbond_params'):\n                    logger.debug(\"Parsing [ nonbond_params ]...\")\n                    expanded.pop(i)\n\n                    while not (expanded[i].count('[')) and i < len(expanded)-1:\n                        split = expanded.pop(i).split()\n                        newNonbondedType = None\n                        if int(split[2]) == 1:\n                            if System._sys.combination_rule == 1:\n                                sigma = (float(split[4]) / float(split[3])) ** (1.0/6.0)\n                                sigma *= units.kilojoules_per_mole * units.nanometers**(6)\n                                epsilon = float(split[3]) / (4 * sigma**6)\n                                epsilon *= units.kilojoules_per_mole * units.nanometers**(12)\n                                newNonbondedType = NonbondedLJCR1Type(split[0], split[1], split[2],\n                                        sigma, epsilon)\n                            elif System._sys.combination_rule in (2, 3):\n                                sigma = float(split[3]) * units.nanometers\n                                epsilon = float(split[4]) * units.kilojoules_per_mole\n                                newNonbondedType = NonbondedLJCR23Type(split[0], split[1], split[2],\n                                        sigma, epsilon)\n\n                        elif int(split[2]) == 2:\n                            # TODO\n                            warn(\"Found Buckingham entry in [ nonbond_param ]. Not yet implemented!\")\n                        else:\n                            warn(\"Found unknown entry type in [ nonbond_param ]. Ignoring.\")\n                        System._sys._nonbonded.add(newNonbondedType)\n\n                elif match.group('system'):\n                    logger.debug(\"Parsing [ system ]...\")\n                    expanded.pop(i)\n\n                    while not (expanded[i].count('[')) and i < len(expanded)-1:\n                        expanded.pop(i)\n                else:\n                    i += 1\n            else:\n                i += 1\n\n        molDirective = re.compile(r\"\"\"\n          \\[[ ]{1}\n          ((?P<moleculetype>moleculetype)\n          |\n          (?P<atoms>atoms)\n          |\n          (?P<bonds>bonds)\n          |\n          (?P<pairs>pairs)\n          |\n          (?P<angles>angles)\n          |\n          (?P<dihedrals>dihedrals)\n          |\n          (?P<constraints>constraints)\n          |\n          (?P<settles>settles)\n          |\n          (?P<exclusions>exclusions)\n          |\n          (?P<molecules>molecules))\n          [ ]{1} \\]\n        \"\"\", re.VERBOSE)\n        i = 0\n        moleculeName = None\n        currentMolecule = None\n        while i < len(expanded):\n            match = molDirective.match(expanded[i])\n            if match:\n                if match.group('moleculetype'):\n                    logger.debug(\"Parsing [ moleculetype ]...\")\n                    expanded.pop(i)\n                    split = expanded[i].split()\n\n                    moleculeName = split[0]\n                    currentMolecule = Molecule(moleculeName)\n                    System._sys.add_molecule(currentMolecule)\n                    currentMoleculeType = System._sys._molecules[moleculeName]\n                    currentMoleculeType.nrexcl = int(split[1])\n                    expanded.pop(i)\n\n                elif match.group('atoms'):\n                    logger.debug(\"Parsing [ atoms ]...\")\n                    expanded.pop(i)\n\n                    while not (expanded[i].count('[')) and i < len(expanded)-1:\n                        split = expanded.pop(i).split()\n\n                        atom = Atom(int(split[0]),          # AtomNum  (index)\n                                split[4].strip(),           # name\n                                int(split[2]),              # resNum\n                                split[3].strip())           # resName\n                        atom.setAtomType(0, split[1].strip())\n                        atom.cgnr = int(split[5])\n                        atom.setCharge(0, float(split[6]) * units.elementary_charge)\n                        try:\n                            atom.setMass(0, float(split[7]) * units.amu)\n                        except:\n                            atom.setMass(0, -1 * units.amu)\n\n                        if len(split) == 11:\n                            atom.setAtomType(1, split[8].strip())\n                            atom.setCharge(1, float(split[9]) * units.elementary_charge)\n                            atom.setMass(1, float(split[10]) * units.amu)\n\n                        index = 0\n                        for atomType in atom._atomtype:\n                            # Searching for a matching atomType to pull values from\n                            tempType = AbstractAtomType(atom._atomtype[index])\n                            atomType = System._sys._atomtypes.get(tempType)\n                            if atomType:\n                                atom.atomic_number = atomType.atomic_number\n                                if not atom.bondtype:\n                                    if atomType.bondtype:\n                                        atom.bondtype = atomType.bondtype\n                                    else:\n                                        logger.warn(\"A suspicious parameter was found in atom/atomtypes. Visually inspect before using.\\n\")\n                                if atom._mass[index]._value < 0:\n                                    if atomType.mass._value >= 0:\n                                        atom.setMass(index, atomType.mass)\n                                    else:\n                                        logger.warn(\"A suspicious parameter was found in atom/atomtypes. Visually inspect before using.\\n\")\n                                # Assuming ptype = A\n                                #atom.ptype = atomType.ptype\n\n                                atom.setSigma(index, atomType.sigma)\n                                atom.setEpsilon(index, atomType.epsilon)\n\n                            else:\n                                logger.warn(\"A corresponding AtomType was not found. Insert missing values yourself.\\n\")\n                            index += 1\n\n                        currentMolecule.addAtom(atom)\n                elif match.group('bonds'):\n                    logger.debug(\"Parsing [ bonds ]...\")\n                    expanded.pop(i)\n\n                    while not (expanded[i].count('[')) and i < len(expanded)-1:\n                        split = expanded.pop(i).split()\n                        newBondForce = None\n\n                        if len(split) == 3:\n                            atomtype1 = currentMolecule._atoms[int(split[0])-1].bondtype\n                            atomtype2 = currentMolecule._atoms[int(split[1])-1].bondtype\n                            tempType = AbstractBondType(atomtype1, atomtype2)\n                            bondType = self.bondtypes.get(tempType)\n                            if not bondType:\n                                # we only have the reversed bond order stored, flip the atoms\n                                tempType = AbstractBondType(atomtype2, atomtype1)\n                                bondType = self.bondtypes.get(tempType)\n                            if not bondType:\n                                raise Exception(\"Bondtype lookup failed for '{0}'\".format(\" \".join(split)))\n\n                            if isinstance(bondType, BondType):\n                                split.append(bondType.length)\n                                split.append(bondType.k)\n\n                            elif isinstance(bondType, G96BondType):\n                                split.append(bondType.length)\n                                split.append(bondType.k)\n\n                            elif isinstance(bondType, CubicBondType):\n                                split.append(bondType.length)\n                                split.append(bondType.C2)\n                                split.append(bondType.C3)\n\n                            elif isinstance(bondType, MorseBondType):\n                                split.append(bondType.length)\n                                split.append(bondType.D)\n                                split.append(bondType.beta)\n\n                            elif isinstance(bondType, HarmonicPotentialType):\n                                split.append(bondType.length)\n                                split.append(bondType.k)\n                            else:\n                                warn(\"Bondtype '{0}' is unsupported or something more complicated went wrong\".format(bondType.type))\n\n                        if int(split[2]) == 1:\n                            try:\n                                newBondForce = Bond(int(split[0]),\n                                        int(split[1]),\n                                        float(split[3]) * units.nanometers,\n                                        float(split[4]) * units.kilojoules_per_mole * units.nanometers**(-2))\n                            except:\n                                newBondForce = Bond(int(split[0]),\n                                        int(split[1]),\n                                        split[3],\n                                        split[4])\n\n                        if int(split[2]) == 2:\n                            try:\n                                newBondForce = G96Bond(int(split[0]),\n                                        int(split[1]),\n                                        float(split[3]) * units.nanometers,\n                                        float(split[4]) * units.kilojoules_per_mole * units.nanometers**(-4))\n                            except:\n                                newBondForce = G96Bond(int(split[0]),\n                                        int(split[1]),\n                                        split[3],\n                                        split[4])\n\n                        if int(split[2]) == 3:\n                            try:\n                                newBondForce = MorseBond(int(split[0]),\n                                        int(split[1]),\n                                        float(split[3]) * units.nanometers,\n                                        float(split[4]) * units.kilojoules_per_mole,\n                                        float(split[5]) * units.nanometers**(-1))\n                            except:\n                                newBondForce = MorseBond(int(split[0]),\n                                        int(split[1]),\n                                        split[3],\n                                        split[4],\n                                        split[5])\n\n                        if int(split[2]) == 4:\n                            try:\n                                newBondForce = CubicBond(int(split[0]),\n                                        int(split[1]),\n                                        float(split[3]) * units.nanometers,\n                                        float(split[4]) * units.kilojoules_per_mole * units.nanometers**(-2),\n                                        float(split[4]) * units.kilojoules_per_mole * units.nanometers**(-3))\n                            except:\n                                newBondForce = CubicBond(int(split[0]),\n                                        int(split[1]),\n                                        split[3],\n                                        split[4],\n                                        split[5])\n\n                        if int(split[2]) == 6:\n                            try:\n                                newBondForce = HarmonicPotential(int(split[0]),\n                                        int(split[1]),\n                                        float(split[3]) * units.nanometers,\n                                        float(split[4]) * units.kilojoules_per_mole * units.nanometers**(-2))\n                            except:\n                                newBondForce = HarmonicPotential(int(split[0]),\n                                        int(split[1]),\n                                        split[3],\n                                        split[4])\n\n                        currentMoleculeType.bondForceSet.add(newBondForce)\n\n                elif match.group('pairs'):\n                    logger.debug(\"Parsing [ pairs ]...\")\n                    expanded.pop(i)\n\n                    while not (expanded[i].count('[')) and i < len(expanded)-1:\n                        split = expanded.pop(i).split()\n                        newPairForce = None\n\n                        if int(split[2]) == 1:\n                            if len(split) == 3:\n                                # this probably won't work due to units\n                                newPairForce = AbstractPair(int(split[0]), int(split[1]), \"Both\")\n\n                        currentMoleculeType.pairForceSet.add(newPairForce)\n\n                elif match.group('angles'):\n                    logger.debug(\"Parsing [ angles ]...\")\n                    expanded.pop(i)\n\n                    while not (expanded[i].count('[')) and i < len(expanded)-1:\n                        split = expanded.pop(i).split()\n                        newAngleForce = None\n\n                        if len(split) == 4:\n                            atomtype1 = currentMolecule._atoms[int(split[0])-1].bondtype\n                            atomtype2 = currentMolecule._atoms[int(split[1])-1].bondtype\n                            atomtype3 = currentMolecule._atoms[int(split[2])-1].bondtype\n                            tempType = AbstractAngleType(atomtype1, atomtype2, atomtype3)\n                            angleType = self.angletypes.get(tempType)\n                            if not (angleType):\n                                #flip it around.\n                                tempType = AbstractAngleType(atomtype3, atomtype2, atomtype1)\n                                angleType = self.angletypes.get(tempType)\n\n                            if isinstance(angleType, AngleType):\n                                split.append(angleType.theta)\n                                split.append(angleType.k)\n\n                            if isinstance(angleType, G96AngleType):\n                                split.append(angleType.theta)\n                                split.append(angleType.k)\n\n                            if isinstance(angleType, CrossBondBondAngleType):\n                                split.append(angleType.r1)\n                                split.append(angleType.r2)\n                                split.append(angleType.k)\n\n                            if isinstance(angleType, CrossBondAngleAngleType):\n                                split.append(angleType.r1)\n                                split.append(angleType.r2)\n                                split.append(angleType.r3)\n                                split.append(angleType.k)\n\n                            if isinstance(angleType, UreyBradleyAngleType):\n                                split.append(angleType.theta)\n                                split.append(angleType.k)\n                                split.append(angleType.r)\n                                split.append(angleType.kUB)\n\n                            if isinstance(angleType, QuarticAngleType):\n                                split.append(angleType.theta)\n                                split.append(angleType.C0)\n                                split.append(angleType.C1)\n                                split.append(angleType.C2)\n                                split.append(angleType.C3)\n                                split.append(angleType.C4)\n\n                        # Angle\n                        if int(split[3]) == 1:\n                            try:\n                                newAngleForce = Angle(int(split[0]),\n                                        int(split[1]),\n                                        int(split[2]),\n                                        float(split[4]) * units.degrees,\n                                        float(split[5]) * units.kilojoules_per_mole * units.radians**(-2))\n                            except:\n                                newAngleForce = Angle(int(split[0]),\n                                        int(split[1]),\n                                        int(split[2]),\n                                        split[4],\n                                        split[5])\n\n                        # G96Angle\n                        elif int(split[3]) == 2:\n                            try:\n                                newAngleForce = G96Angle(int(split[0]),\n                                        int(split[1]),\n                                        int(split[2]),\n                                        float(split[4]) * units.degrees,\n                                        float(split[5]) * units.kilojoules_per_mole)\n                            except:\n                                newAngleForce = G96Angle(int(split[0]),\n                                        int(split[1]),\n                                        int(split[2]),\n                                        split[4],\n                                        split[5])\n\n                        # Cross Bond-Bond\n                        elif int(split[3]) == 3:\n                            try:\n                                newAngleForce = CrossBondBondAngle(int(split[0]),\n                                        int(split[1]),\n                                        int(split[2]),\n                                        float(split[4]) * units.nanometers,\n                                        float(split[5]) * units.nanometers,\n                                        float(split[6]) * units.kilojoules_per_mole * units.nanometers**(-2))\n                            except:\n                                newAngleForce = CrossBondBondAngle(int(split[0]),\n                                        int(split[1]),\n                                        int(split[2]),\n                                        split[4],\n                                        split[5],\n                                        split[6])\n\n                        # Cross Bond-Angle\n                        elif int(split[3]) == 4:\n                            try:\n                                newAngleForce = CrossBondAngleAngle(int(split[0]),\n                                        int(split[1]),\n                                        int(split[2]),\n                                        float(split[4]) * units.nanometers,\n                                        float(split[5]) * units.nanometers,\n                                        float(split[6]) * units.nanometers,\n                                        float(split[7]) * units.kilojoules_per_mole * units.nanometers**(-2))\n                            except:\n                                newAngleForce = CrossBondAngleAngle(int(split[0]),\n                                        int(split[1]),\n                                        int(split[2]),\n                                        split[4],\n                                        split[5],\n                                        split[6],\n                                        split[7])\n\n                        # Urey-Bradley\n                        elif int(split[3]) == 5:\n                            try:\n                                newAngleForce = UreyBradleyAngle(int(split[0]),\n                                        int(split[1]),\n                                        int(split[2]),\n                                        float(split[4]) * units.degrees,\n                                        float(split[5]) * units.kilojoules_per_mole * units.radians**(-2),\n                                        float(split[6]) * units.nanometers,\n                                        float(split[7]) * units.kilojoules_per_mole * units.nanometers**(-2))\n                            except:\n                                newAngleForce = UreyBradleyAngle(int(split[0]),\n                                        int(split[1]),\n                                        int(split[2]),\n                                        split[4],\n                                        split[5],\n                                        split[6],\n                                        split[7])\n\n                        # Quartic\n                        elif int(split[3]) == 6:\n                            try:\n                                newAngleForce = QuarticAngle(int(split[0]),\n                                        int(split[1]),\n                                        int(split[2]),\n                                        float(split[4]) * units.degrees,\n                                        float(split[5]) * units.kilojoules_per_mole,\n                                        float(split[6]) * units.kilojoules_per_mole * units.radians**(-1),\n                                        float(split[7]) * units.kilojoules_per_mole * units.radians**(-2),\n                                        float(split[8]) * units.kilojoules_per_mole * units.radians**(-3),\n                                        float(split[9]) * units.kilojoules_per_mole * units.radians**(-4))\n                            except:\n                                newAngleForce = QuarticAngle(int(split[0]),\n                                        int(split[1]),\n                                        int(split[2]),\n                                        split[4],\n                                        split[5],\n                                        split[6],\n                                        split[7],\n                                        split[8],\n                                        split[9])\n\n                        currentMoleculeType.angleForceSet.add(newAngleForce)\n\n                elif match.group('dihedrals'):\n                    logger.debug(\"Parsing [ dihedrals ]...\")\n                    expanded.pop(i)\n                    while not (expanded[i].count('[')) and i < len(expanded)-1:\n                        split = expanded.pop(i).split()\n                        newDihedralForce = None\n                        dihedralType = None\n\n                        dtype = int(split[4])\n                        improper = (dtype == 4) or (dtype == 2)\n                        if len(split) == 5:\n\n                            atomtype1 = currentMolecule._atoms[int(split[0])-1].bondtype\n                            atomtype2 = currentMolecule._atoms[int(split[1])-1].bondtype\n                            atomtype3 = currentMolecule._atoms[int(split[2])-1].bondtype\n                            atomtype4 = currentMolecule._atoms[int(split[3])-1].bondtype\n\n                            # check the possible ways to match a dihedraltype\n                            atomtypelists = [[atomtype1, atomtype2, atomtype3, atomtype4],  # original order\n                                             [atomtype4, atomtype3, atomtype2, atomtype1],  # flip it\n                                             [atomtype1, atomtype2, atomtype3, 'X'],  #single wildcard 1\n                                             ['X', atomtype2, atomtype3, atomtype4],  #single wildcard 2\n                                             ['X', atomtype3, atomtype2, atomtype1], # flipped single wildcard 1\n                                             [atomtype4, atomtype3, atomtype2, 'X'], # flipped single wildcard 2\n                                             ['X', atomtype2, atomtype3, 'X'], # double wildcard\n                                             ['X', atomtype3, atomtype2, 'X'], # flipped double wildcard\n                                             ['X', 'X', atomtype3, atomtype4], # end double wildcard\n                                             [atomtype1, atomtype2,'X', 'X'] # flipped end double wildcard\n                                             ]\n\n                            for alist in atomtypelists:\n                                if not dihedralType:\n                                    tempType = AbstractDihedralType(alist[0], alist[1], alist[2], alist[3], improper)\n                                    dihedralType = self.dihedraltypes.get(tempType)\n                                else:\n                                    break\n\n                            if isinstance(dihedralType, DihedralTrigType):\n                                phi = dihedralType.phi\n                                fc0 = dihedralType.fc0\n                                fc1 = dihedralType.fc1\n                                fc2 = dihedralType.fc2\n                                fc3 = dihedralType.fc3\n                                fc4 = dihedralType.fc4\n                                fc5 = dihedralType.fc5\n                                fc6 = dihedralType.fc6\n\n                            elif isinstance(dihedralType, ImproperHarmonicDihedralType):\n                                phi = dihedralType.xi\n                                k = dihedralType.k\n                            else:\n                                warn(\"Did not find matching dihedraltype!\")\n\n                        atom1 = int(split[0])\n                        atom2 = int(split[1])\n                        atom3 = int(split[2])\n                        atom4 = int(split[3])\n                        nentries = len(split)\n\n                        # Proper Dihedral 1\n                        if int(split[4]) == 1 or int(split[4]) == 9 or int(split[4]) == 4:\n\n                            if nentries > 5:\n                                fc0, fc1, fc2, fc3, fc4, fc5, fc6 = ConvertDihedralFromProperDihedralToDihedralTrig(\n                                        float(split[6]) * units.kilojoules_per_mole, int(split[7]))\n                                phi = float(split[5]) * units.degrees\n                            newDihedralForce = DihedralTrigDihedral(\n                                atom1, atom2, atom3, atom4, phi,\n                                fc0, fc1, fc2, fc3, fc4, fc5, fc6, improper=improper)\n\n                            # for dihedral type 9, there can be multiple interactions\n\n                        # Improper Dihedral 2\n                        elif dtype == 2:\n                            if nentries > 5:\n                                phi = float(split[5]) * units.degrees\n                                k = float(split[6]) * units.kilojoules_per_mole * units.radians**(-2)\n\n                            newDihedralForce = ImproperHarmonicDihedral(\n                                atom1, atom2, atom3, atom4, phi, k)\n\n                        # RBDihedral\n                        elif dtype == 3:\n\n                            if nentries > 5:\n                                fc0, fc1, fc2, fc3, fc4, fc5, fc6 = ConvertDihedralFromRBToDihedralTrig(\n                                    float(split[5]) * units.kilojoules_per_mole,\n                                    float(split[6]) * units.kilojoules_per_mole,\n                                    float(split[7]) * units.kilojoules_per_mole,\n                                    float(split[8]) * units.kilojoules_per_mole,\n                                    float(split[9]) * units.kilojoules_per_mole,\n                                    float(split[10]) * units.kilojoules_per_mole,\n                                    0 * units.kilojoules_per_mole)\n\n                            newDihedralForce = DihedralTrigDihedral(\n                                atom1, atom2, atom3, atom4,\n                                0 * units.degrees, fc0, fc1, fc2, fc3, fc4, fc5, fc6)  # need to look at the use of sign here\n\n                        elif dtype == 5:\n\n                            if nentries > 5:\n                                fc0, fc1, fc2, fc3, fc4, fc5, fc6 = ConvertDihedralFromFourierToDihedralTrig(\n                                    float(split[5])*units.kilojoules_per_mole,\n                                    float(split[6])*units.kilojoules_per_mole,\n                                    float(split[7])*units.kilojoules_per_mole,\n                                    float(split[8])*units.kilojoules_per_mole,\n                                    )\n\n                            newDihedralForce = DihedralTrigDihedral(\n                                atom1, atom2, atom3, atom4,\n                                0 * units.degrees, fc0, fc1, fc2, fc3, fc4, fc5, fc6)  # need to look at the use of sign here\n\n                        elif dtype == 8:\n                            raise Exception(\"Cannot support tabulated dihedrals\")\n                        else:\n                            raise Exception(\"Unsupported dihedral\")\n\n                        if dtype == 9:\n                            # we need to retrive the information add to the dihedral,\n                            # rather than overwrite it\n                            # warning: right now, I don't think we can have BOTH duplicate dihedrals and\n                            # duplicate dihedral types.  Will have to investigate.\n                            try:\n                                # retrive a dihedral with the same atoms, add to it if it exists\n                                dihedralmatch = currentMoleculeType.dihedralForceSet.map[newDihedralForce]\n                                dihedralmatch.sum_parameters(newDihedralForce)\n                            except Exception as e:\n                                logger.exception(e) # used to be pass, now recorded but surpressed\n                        currentMoleculeType.dihedralForceSet.add(newDihedralForce)\n\n                elif match.group('constraints'):\n                    logger.debug(\"Parsing [ constraints ]...\")\n                    expanded.pop(i)\n\n                    while not (expanded[i].count('[')) and i < len(expanded)-1:\n                        expanded.pop(i)\n\n                elif match.group('settles'):\n                    logger.debug(\"Parsing [ settles ]...\")\n                    expanded.pop(i)\n\n                    while not (expanded[i].count('[')) and i < len(expanded)-1:\n                        split = expanded.pop(i).split()\n                        newSettlesForce = None\n\n                        if len(split) == 4:\n                            newSettlesForce = Settles(int(split[0]),\n                                    float(split[2]) * units.nanometers,\n                                    float(split[3]) * units.nanometers)\n\n                        currentMoleculeType.settles = newSettlesForce\n\n                        # we need to add a constrainted bonded forces as well between the atoms in these molecules.\n                        # we assume the gromacs default of 1. O, 2. H, 3. H\n                        # reference bond strength is 900 kj/mol, but doesn't really matter since constrainted.\n                        #waterbondrefk = 900*units.kilojoules_per_mole * units.nanometers**(-2)\n                        #wateranglerefk = 400*units.kilojoules_per_mole * units.degrees**(-2)\n                        \n                        # From oplsaa.ff/tip3p.itp - JPT\n                        waterbondrefk = 502416.0 * units.kilojoules_per_mole * units.nanometers**(-2)\n                        wateranglerefk = 628.02 * units.kilojoules_per_mole * units.radians**(-2)\n\n                        angle = 2.0 * math.asin(0.5 * float(split[3]) / float(split[2])) * units.radians\n                        dOH = float(split[2]) * units.nanometers\n\n                        newBondForce = Bond(1,2,dOH,waterbondrefk,c=True)\n                        currentMoleculeType.bondForceSet.add(newBondForce)\n\n                        newBondForce = Bond(1,3,dOH,waterbondrefk,c=True)\n                        currentMoleculeType.bondForceSet.add(newBondForce)\n\n                        newAngleForce = Angle(3,1,2,angle,wateranglerefk,c=True)\n                        currentMoleculeType.angleForceSet.add(newAngleForce)\n\n                elif match.group('exclusions'):\n                    logger.debug(\"Parsing [ exclusions ]...\")\n                    expanded.pop(i)\n\n                    while not (expanded[i].count('[')) and i < len(expanded)-1:\n                        split = expanded.pop(i).split()\n                        for j in range(len(split)):\n                            if split[0] < split[j]:\n                                newExclusion = Exclusions([int(split[0]),int(split[j])])\n                                currentMoleculeType.exclusions.add(newExclusion)\n\n\n                elif match.group('molecules'):\n                    logger.debug(\"Parsing [ molecules ]...\")\n                    expanded.pop(i)\n                    ordered_moleculetypes = OrderedDict()\n                    while i < len(expanded) and not (expanded[i].count('[')):\n                        split = expanded.pop(i).split()\n                        mol_name = split[0]\n                        mol_num = int(split[1])\n                        System._sys._components.append((mol_name, mol_num))\n\n                        ordered_moleculetypes[mol_name] = System._sys._molecules[mol_name]\n                        tempMolecule = System._sys._molecules[mol_name].moleculeSet[0]\n                        if len(System._sys._molecules[mol_name].moleculeSet) > 1:\n                            n = 0\n                        else:\n                            n = 1\n                        while n < mol_num:\n                            mol = copy.deepcopy(tempMolecule)\n                            System._sys.add_molecule(mol)\n                            n += 1\n                    System._sys._molecules = ordered_moleculetypes\n                else:\n                    i += 1\n            else:\n                i += 1\n\n    def preprocess(self, filename, verbose=False):\n        \"\"\"\n        Preprocess a topology file\n\n        Preprocesses for #include, #define, #ifdef directives and handles them\n\n        Args:\n            filename: the filename to preprocess\n            verbose: verbose output\n        \"\"\"\n        expanded = list()\n        lineReg = re.compile(r\"\"\"\n         [ ]*                   # omit spaces\n         (?P<directive>[^\\\\;\\n]*)   # search for directive section\n         [ ]*                   # omit spaces\n         (?P<ignore_newline>\\\\)?        # look for the \\ for newline\n         (?P<comment>;.*)?          # look for a comment\n        \"\"\", re.VERBOSE)\n        preReg = re.compile(r\"\"\"\n         (?:\\#include[ ]+)\n          (?:\"|<)\n          (?P<include>.+\\.itp|.+\\.top)\n          (?:\"|>)\n         |\n         (?:\\#define[ ]+)\n          (?P<defineLiteral>[\\S]+)\n          (?P<defineData>[ ]+.+)?\n         |\n         (?:\\#undef[ ]+)\n          (?P<undef>[\\S]+)\n         |\n         (?:\\#ifdef[ ]+)\n          (?P<ifdef>[\\S]+)\n         |\n         (?:\\#ifndef[ ]+)\n          (?P<ifndef>[\\S]+)\n         |\n         (?P<else>\\#else)\n         |\n         (?P<endif>\\#endif)\n        \"\"\", re.VERBOSE)\n        condDepth = 0\n        write = [True]\n        fd = self.open(filename)\n        if fd is not None:\n            lines = deque(fd)   # initial read of root file\n            fd.close()\n            while(lines):       # while the queue isn't empty continue preprocessing\n                line = lines.popleft()\n                logger.debug(\"=========================\")\n                logger.debug(\"Original line: %s\" % line)\n                match = lineReg.match(line)   # ensure that the line matches what we expect!\n                if match:\n                    line = match.group('directive')\n                    comment = match.group('comment')\n                    logger.debug(\"Directive: %s\" % line)\n                    logger.debug(\"Comment: %s\" % comment)\n                    while True:     # expand the lines\n                        if match.group('ignore_newline'):\n                            logger.debug(\"Ignore newline found\")\n                            if lines:\n                                temp = lines.popleft()\n                                match = lineReg.match(temp)\n                                line += match.group('directive')\n                            else:\n                                logger.warn(\"Previous line continues yet EOF encountered\")\n                                break   # EOF so we can't loop again\n                        else:\n                            break   # line terminates\n                    line = line.strip()  # just in case theres whitespace we missed\n\n                    match = preReg.match(line)\n                    if match is not None:\n                        if match.group('ifdef') and write[condDepth]:\n                            logger.debug('Found an ifdef: %s' % match.group('ifdef'))\n                            condDepth += 1\n                            ifdef = match.group('ifdef')\n                            if ifdef in self.defines:\n                                write.append(True)\n                            else:\n                                write.append(False)\n                        elif match.group('ifndef') and write[condDepth]:\n                            logger.debug('Found an ifndef: %s' % match.group('ifndef'))\n                            condDepth += 1\n                            ifndef = match.group('ifndef')\n                            if ifndef not in self.defines:\n                                write.append(True)\n                            else:\n                                write.append(False)\n                        elif match.group('else'):\n                            logger.debug('Found an else')\n                            if condDepth > 0:\n                                write[condDepth] = not write[condDepth]\n                            else:\n                                logger.warn(\"Found an else not associated with a conditional\")\n                        elif match.group('endif'):\n                            logger.debug('Found an endif')\n                            if condDepth > 0:\n                                condDepth -= 1\n                                write.pop()\n                            else:\n                                raise Exception(\"Found an endif not associated with a conditional\")\n                        elif write[condDepth]:\n                            if match.group('include'):\n                                logger.debug(\"Found a include: %s\" % line)\n                                include = match.group('include')\n                                fd = self.open(include)\n                                if fd is not None:\n                                    tempList = list(fd)\n                                    tempList.reverse()\n                                    lines.extendleft(tempList)\n                            elif match.group('defineLiteral'):\n                                logger.debug(\"Found a define: %s\" % line)\n                                define = match.group('defineLiteral')\n\n                                if define not in self.defines:\n                                    self.defines[define] = match.group('defineData')\n                                else:\n                                    logger.warn(\"WARNING: Overriding define: %s\" % define)\n                                    self.define[define] = match.group('defineData')\n                            elif match.group('undef'):\n                                logger.debug(\"Found a undefine: %s\" % line)\n                                undef = match.group('undef')\n                                if undef in self.defines:\n                                    self.defines.pop(undef)\n                    elif write[condDepth]:\n                        if line != '':\n                            for define in self.defines:\n                                if define in line:\n                                    line = line.replace(define, self.defines[define])\n                            logger.debug(\"Writing: %s\" % line)\n                            expanded.append(line)\n                        if comment:\n                            self.comments.append(comment)\n                else:\n                    raise Exception(\"Unreadable line!\")\n            return expanded\n        else:\n            fd.close()\n\n    def open(self, filename, parentfile=''):\n        \"\"\"\n        Open a file and add to includes list\n\n        Checks if a file exists in the same directory as the top and gro files\n        or in the GMXLIB environment; then opens if found or fails if not\n\n        Args:\n            filename: the name of the file to open\n\n        Returns:\n            file descriptor of the file to be openend\n\n        Raises:\n            IOError when the file cannot be opened for any reason\n        \"\"\"\n        if filename in self.includes:\n            logger.warn(\"Omitting file %s. It has already been included!\" % filename)\n            return None\n        temp = filename\n\n        if os.path.exists(filename):\n            try:\n                fd = open(filename)\n                self.includes.add(temp)\n                logger.info(\"Local instance of topology file '%s' used\\n\" % (filename))\n                return fd\n            except IOError, (errno, strerror):\n                logger.exception(\"I/O error(%d): %s for local instance of '%s'\\n\" % (errno, strerror, filename))\n\n        # if we can't include the file locally, let's look for it in\n        # the directory of one of the previous files.  \n\n        # NOTE: could be\n        # dangerous if multiple files with the same name are found in\n        # different directories!\n        found = False\n        for parentfile in self.includes:\n            parentdir, oldfile = os.path.split(parentfile)\n            filename = os.path.join(parentdir, temp)\n            if os.path.exists(filename):\n                found = True\n                break\n\n        if found:\n            try:\n                fd = open(filename)\n                self.includes.add(temp)\n                logger.info(\"version in %s used for topology file '%s'\\n\" % (parentdir, filename))\n                return fd\n            except Exception as e:\n                logger.exception(e) # EDZ: used to be pass, now recorded but supressed\n        else:\n            try:\n                filename = os.path.join(os.environ['GMXLIB'], temp)\n                fd = open(filename)\n                self.includes.add(filename)\n                logger.info(\"version in GMXLIB = %s used for topology file '%s'\\n\" % (os.environ['GMXLIB'], temp))\n                return fd\n\n            except IOError, (errno, strerror):\n                logger.exception(\"Unrecoverable I/O error(%d): can'd find %s anywhere: '%s'\\n\" % (errno, strerror, filename))\n                sys.exit()\n\n    def write_topology(self, filename):\n        \"\"\"Write this topology in GROMACS file format.\n\n        Args:\n            filename: the name of the file to write out to\n        \"\"\"\n        lines = list()\n\n        # [ defaults ]\n        lines.append('[ defaults ]\\n')\n        lines.append('; nbfunc        comb-rule       gen-pairs       fudgeLJ fudgeQQ\\n')\n        lines.append('%d%16d%18s%20.4g%8.4g\\n'\n                % (System._sys.nonbonded_function,\n                   System._sys.combination_rule,\n                   System._sys.genpairs,\n                   System._sys.lj_correction,\n                   System._sys.coulomb_correction))\n        lines.append('\\n')\n\n        # [ atomtypes ]\n        lines.append('[ atomtypes ]\\n')\n        lines.append(';type, bondtype, atomic_number, mass, charge, ptype, sigma, epsilon\\n')\n        atomtypelist = sorted(System._sys._atomtypes.itervalues(), key=lambda x: x.atomtype)\n        for atomtype in atomtypelist:\n#            if atomtype.atomtype.isdigit():\n#                atomtype.atomtype = \"LMP_\" + atomtype.atomtype\n#            if atomtype.bondtype.isdigit():\n#                atomtype.bondtype = \"LMP_\" + atomtype.bondtype\n            if System._sys.combination_rule == 1:\n                lines.append('%-11s%5s%6d%18.8f%18.8f%5s%18.8e%18.8e\\n'\n                        % (atomtype.atomtype,\n                           atomtype.bondtype,\n                           int(atomtype.atomic_number),\n                           atomtype.mass.in_units_of(units.atomic_mass_unit)._value,\n                           atomtype.charge.in_units_of(units.elementary_charge)._value,\n                           atomtype.ptype,\n                           atomtype.sigma.in_units_of(units.kilojoules_per_mole * units.nanometers**(6))._value,\n                           atomtype.epsilon.in_units_of(units.kilojoules_per_mole * units.nanometers**(12))._value))\n            elif System._sys.combination_rule in (2, 3):\n                lines.append('%-10s %-10s %4d %12.6f %9.3f %5s %16.6e %16.6e\\n'\n                        % (atomtype.atomtype,\n                           atomtype.bondtype,\n                           int(atomtype.atomic_number),\n                           atomtype.mass.in_units_of(units.atomic_mass_unit)._value,\n                           atomtype.charge.in_units_of(units.elementary_charge)._value,\n                           atomtype.ptype,\n                           atomtype.sigma.in_units_of(units.nanometers)._value,\n                           atomtype.epsilon.in_units_of(units.kilojoules_per_mole)._value))\n        lines.append('\\n')\n\n        if System._sys._nonbonded:\n            # [ nonbond_params ]\n            lines.append('[ nonbond_params ]\\n')\n            nonbondedlist = sorted(moleculeType.bondForceSet.itervalues(), key=lambda x: (x.atom1, x.atom2))\n            for nonbonded in nonbondedlist:\n                if System._sys.combination_rule == 1:\n                    lines.append('{0:6s} {1:6s} {2:3d} {3:18.8e} {4:18.8e}\\n'.format(\n                            nonbonded.atom1, nonbonded.atom2, nonbonded.type,\n                            nonbonded.sigma.in_units_of(units.kilojoules_per_mole * units.nanometers**(6))._value,\n                            nonbonded.epsilon.in_units_of(units.kilojoules_per_mole * units.nanometers**(12))._value))\n                elif System._sys.combination_rule in (2, 3):\n                    lines.append('{0:6s} {1:6s} {2:3s} {3:18.8e} {4:18.8e}\\n'.format(\n                            nonbonded.atom1, nonbonded.atom2, nonbonded.type,\n                            nonbonded.sigma.in_units_of(units.nanometers)._value,\n                            nonbonded.epsilon.in_units_of(units.kilojoules_per_mole)._value))\n        lines.append('\\n')\n\n        # [ moleculetype]\n        moleculeTypelist = sorted(System._sys._molecules.itervalues(), key=lambda x: x.name)        \n        for moleculeType in moleculeTypelist:\n            lines.append('[ moleculetype ]\\n')\n            # gromacs can't handle spaces in the molecule name\n            printname = moleculeType.name\n            printname = printname.replace(' ','_')\n            printname = printname.replace('\"','')\n            lines.append('%s%10d\\n\\n'\n                    % (printname,\n                       moleculeType.nrexcl))\n\n            # [ atoms ]\n            lines.append('[ atoms ]\\n')\n            lines.append(';num, type, resnum, resname, atomname, cgnr, q, m\\n')\n            molecule = moleculeType.moleculeSet[0]\n            count = 1\n            for atom in molecule._atoms:\n#                if atom.name.isdigit():\n#                    atom.name = \"LMP_\" + atom.name\n#                if atom._atomtype[0].isdigit():\n#                    atom._atomtype[0] = \"LMP_\" + atom._atomtype[0]\n\n                try:\n                    lines.append('%6d %10s %6d %8s %8s %6d %12.6f %12.6f %10s %12.6f %12.6f\\n'\n                            % (count,\n                               atom._atomtype[0],\n                               atom.residue_index,\n                               atom.residue_name,\n                               atom.name,\n                               atom.cgnr,\n                               atom._charge[0].in_units_of(units.elementary_charge)._value,\n                               atom._mass[0].in_units_of(units.atomic_mass_unit)._value,\n                               atom._atomtype[1],\n                               atom._charge[1].in_units_of(units.elementary_charge)._value,\n                               atom._mass[1].in_units_of(units.atomic_mass_unit)._value))\n                except:\n                    lines.append('%6d %10s %6d %8s %8s %6d %12.6f %12.6f\\n'\n                                 % (count,\n                                    atom._atomtype[0],\n                                    atom.residue_index,\n                                    atom.residue_name,\n                                    atom.name,\n                                    atom.cgnr,\n                                    atom._charge[0].in_units_of(units.elementary_charge)._value,\n                                    atom._mass[0].in_units_of(units.atomic_mass_unit)._value))\n                count += 1\n            lines.append('\\n')\n\n            if moleculeType.bondForceSet and not moleculeType.settles:\n                # [ bonds ]\n                lines.append('[ bonds ]\\n')\n                lines.append(';   ai     aj funct  r               k\\n')\n                bondlist = sorted(moleculeType.bondForceSet.itervalues(), key=lambda x: (x.atom1,x.atom2))\n                for bond in bondlist:\n                    if isinstance(bond, Bond):\n                        b_type = 1\n                        lines.append('%6d %6d %3d %12.6f %16.6e\\n'\n                                % (bond.atom1,\n                                   bond.atom2,\n                                   b_type,\n                                   bond.length.in_units_of(units.nanometers)._value,\n                                   bond.k.in_units_of(units.kilojoules_per_mole*units.nanometers**(-2))._value))\n                    elif isinstance(bond, G96Bond):\n                        b_type = 2\n                        lines.append('%6d%7d%4d%5.8f%5.8f\\n'\n                                % (bond.atom1,\n                                   bond.atom2,\n                                   b_type,\n                                   bond.length.in_units_of(units.nanometers)._value,\n                                   bond.k.in_units_of(units.kilojoules_per_mole*units.nanometers**(-4))._value))\n                    elif isinstance(bond, MorseBond):\n                        b_type = 3\n                        lines.append('%6d%7d%4d%5.8f%5.8f%5.8f\\n'\n                                % (bond.atom1,\n                                   bond.atom2,\n                                   b_type,\n                                   bond.length.in_units_of(units.nanometers)._value,\n                                   bond.D.in_units_of(units.kilojoules_per_mole)._value,\n                                   bond.beta.in_units_of(units.nanometers**(-1))._value))\n                    elif isinstance(bond, CubicBond):\n                        b_type = 4\n                        lines.append('%6d%7d%4d%5.8f%5.8f%5.8f\\n'\n                                % (bond.atom1,\n                                   bond.atom2,\n                                   b_type,\n                                   bond.length.in_units_of(units.nanometers)._value,\n                                   bond.C2.in_units_of(units.kilojoules_per_mole * units.nanometers**(-2))._value,\n                                   bond.C3.in_units_of(units.kilojoules_per_mole * units.nanometers**(-3))._value))\n                    else:\n                        raise Exception(\"WriteError: found unsupported bond type\")\n                lines.append('\\n')\n\n            #MRS: why are there two pairs sections?\n            if moleculeType.pairForceSet:\n                # [ pair ]\n                lines.append('[ pairs ]\\n')\n                lines.append(';  ai    aj   funct\\n')\n                pairlist = sorted(moleculeType.pairForceSet.itervalues(), key=lambda x: (x.atom1, x.atom2))\n                for pair in pairlist:\n\n                    if isinstance(pair, AbstractPair):\n                        p_type = 1\n                        lines.append('%6d %6d %3d\\n'\n                                % (pair.atom1,\n                                   pair.atom2,\n                                   p_type))\n\n                    else:\n                        raise Exception(\"WriteError: found unsupported pair type\")\n                lines.append('\\n')\n\n            if moleculeType.angleForceSet and not moleculeType.settles:\n                # [ angles ]\n                lines.append('[ angles ]\\n')\n                lines.append(';   ai     aj     ak    funct   theta         cth\\n')\n\n                anglelist = sorted(moleculeType.angleForceSet.itervalues(), key=lambda x: (x.atom1, x.atom2, x.atom3))\n                for angle in anglelist:\n                    atomindex = \"%6d %6d %6d\" % (angle.atom1,angle.atom2,angle.atom3)\n                    if isinstance(angle, Angle):\n                        a_type = 1\n                        lines.append('%s %3d %12.3f %12.6f\\n'\n                                % (atomindex,\n                                   a_type,\n                                   angle.theta.in_units_of(units.degrees)._value,\n                                   angle.k.in_units_of(units.kilojoules_per_mole*units.radians**(-2))._value))\n                    elif isinstance(angle, G96Angle):\n                        a_type = 2\n                        lines.append('%s%4d%18.8e%18.8e\\n'\n                                     % (atomindex,\n                                        a_type,\n                                        angle.theta.in_units_of(units.degrees)._value,\n                                        angle.k.in_units_of(units.kilojoules_per_mole)._value))\n                    elif isinstance(angle, UreyBradleyAngle):\n                        a_type = 5\n                        lines.append('%s%4d%18.8e%18.8e%18.8e%18.8e\\n'\n                                     % (atomindex,\n                                        a_type,\n                                        angle.theta.in_units_of(units.degrees)._value,\n                                        angle.k.in_units_of(units.kilojoules_per_mole*units.radians**(-2))._value,\n                                        angle.r.in_units_of(units.nanometers)._value,\n                                        angle.kUB.in_units_of(units.kilojoules_per_mole*units.nanometers**(-2))._value))\n                    else:\n                        raise Exception(\"WriteError: found unsupported angle type\")\n                lines.append('\\n')\n\n            \"\"\"\n            # [ pairs]\n            lines.append('[ pairs ]\\n')\n            lines.append(';   ai     aj    funct')\n\n            pairlist = sorted(moleculeType.pairForceSet.itervalues(), key=lambda x: x.atom1)\n            for pair in pairlist:\n                if isinstance(pair, LJ1PairCR1) or isinstance(pair, LJ1PairCR23)\n                    type = 1\n                    lines.append('%6d%7d%4d%18.8e%18.8e\\n'%(pair.atom1, pair.atom2, type,\n                            pair.V.in_units_of(units.XXX)._value,\n                            pair.W.in_units_of(units.XXX)._value)\n\n                elif isinstance(pair, LJ2PairCR1) or isinstance(pair, LJ2PairCR23):\n                    type = 2\n                    lines.append('%6d%7d%4d%18.8e%18.8e\\n'%(pair.atom1, pair.atom2, type,\n                            pair.V.in_units_of(units.XXX)._value,\n                            pair.W.in_units_of(units.XXX)._value))\n\n                elif isinstance(pair, LJNBCR1) or isinstance( pair, LJNBCR23):\n                    type = 1\n                    lines.append('%6d%7d%4d%18.8f%18.8f%18.8f%18.8f\\n'%(pair.atom1, pair.atom2, type,\n                            pair.qi.in_units_of(units.XXX)._value,\n                            pair.qj.in_units_of(units.XXX)._value,\n                            pair.V.in_units_of(units.XXX)._value,\n                            pair.W.in_units_of(units.XXX)._value))\n                else:\n                    print \"Could not identify pair!\"\n            \"\"\"\n\n            if moleculeType.dihedralForceSet:\n                # [ dihedrals ]\n                lines.append('[ dihedrals ]\\n')\n                lines.append(';    i      j      k      l   func\\n')\n                dihedrallist = sorted(moleculeType.dihedralForceSet.itervalues(),\n                        key=lambda x: (x.atom1, x.atom2, x.atom3, x.atom4))\n                for dihedral in dihedrallist:\n                    # this atom index will be the same for all of types.\n                    atomindex = \"%6d %6d %6d %6d\" % (dihedral.atom1, dihedral.atom2,\n                            dihedral.atom3, dihedral.atom4)\n                    if isinstance(dihedral, DihedralTrigDihedral):\n                        # convienience array\n                        coefficients = [dihedral.fc1, dihedral.fc2, dihedral.fc3,\n                                dihedral.fc4, dihedral.fc5, dihedral.fc6]\n                        if dihedral.improper:\n                            found_nonzero = False\n                            for n, coeff in enumerate(coefficients):  # only one of these should be nonzero\n                                if coeff._value != 0.0:\n                                    if found_nonzero == False:\n                                        found_nonzero = True\n                                    else:\n                                        raise ValueError(\"Found more than one nonzero \"\n                                                \"coefficient in improper trigonal dihedral!\")\n                                    lines.append('%s %3d %7.1f %17.6f %5d\\n'\n                                                 % (atomindex, 4,\n                                                    dihedral.phi.in_units_of(units.degrees)._value,\n                                                    coeff.in_units_of(units.kilojoules_per_mole)._value,\n                                                    n + 1))\n                        else:\n                            rb_coeffs = ConvertDihedralFromDihedralTrigToRB(\n                                np.cos(dihedral.phi.in_units_of(units.radians)._value),\n                                dihedral.phi, dihedral.fc0, * coefficients)\n                            # there are some cases where some dihedrals will have c[6] values, which gromacs\n                            # can't yet handle.  We need a workaround, and will go through the route of multiple 9s.\n                            if (dihedral.phi in [0*units.degrees, 180*units.degrees] and\n                                    rb_coeffs[6]._value == 0):\n                                d_type = 3\n                                lines.append('%s %3d %12.6f %12.6f %12.6f %12.6f %12.6f %12.6f\\n'\n                                             % (atomindex,\n                                                d_type,\n                                                rb_coeffs[0].in_units_of(units.kilojoules_per_mole)._value,\n                                                rb_coeffs[1].in_units_of(units.kilojoules_per_mole)._value,\n                                                rb_coeffs[2].in_units_of(units.kilojoules_per_mole)._value,\n                                                rb_coeffs[3].in_units_of(units.kilojoules_per_mole)._value,\n                                                rb_coeffs[4].in_units_of(units.kilojoules_per_mole)._value,\n                                                rb_coeffs[5].in_units_of(units.kilojoules_per_mole)._value))\n                            else:\n                                ncount = sum(coeff._value != 0.0 for coeff in coefficients)\n                                if ncount > 1:\n                                    dtype = 9\n                                else:\n                                    dtype = 1\n                                # all of the terms should have consistent phi now\n                                for n, coeff in enumerate(coefficients):\n                                    if coeff._value < 0:\n                                        # kludge for different definitions of trigonometric\n                                        # dihedral with multiplicity in the central representation\n                                        # and in GROMACS\n                                        coefficients[n] *= -1\n                                        if dihedral.phi.value_in_unit(units.degrees)==180:\n                                            printphi = 0*units.degrees\n                                        else:\n                                            printphi = 180*units.degrees\n                                    else:\n                                        printphi = dihedral.phi\n                                    lines.append('%s%4d%18.8f%18.8f%6d\\n'\n                                                 % (atomindex,\n                                                    dtype,\n                                                    printphi.in_units_of(units.degrees)._value,\n                                                    coeff.in_units_of(units.kilojoules_per_mole)._value,\n                                                    n + 1))\n\n                    elif isinstance(dihedral, ImproperHarmonicDihedral):\n                        d_type = 2\n                        lines.append('%s%4d%18.8f%18.8f\\n'\n                                     % (atomindex,\n                                        d_type,\n                                        dihedral.xi.in_units_of(units.degrees)._value,\n                                        dihedral.k.in_units_of(units.kilojoules_per_mole*units.radians**(-2))._value))\n\n                    else:\n                        raise Exception(\"WriteError: found unsupported dihedral type\")\n                lines.append('\\n')\n\n            if moleculeType.settles:\n                settles = moleculeType.settles\n                # [ settles ]\n                lines.append('[ settles ]\\n')\n                lines.append('; i  funct   dOH  dHH\\n')\n                s_type = 1\n                lines.append('%6d%6d%18.8f%18.8f\\n'\n                             % (settles.atom1,\n                                s_type,\n                                settles.dOH.in_units_of(units.nanometers)._value,\n                                settles.dHH.in_units_of(units.nanometers)._value))\n                lines.append('\\n')\n\n            if moleculeType.exclusions:\n                # [ exclusions ]\n                lines.append('[ exclusions ]\\n')\n                exclusionlist = sorted(moleculeType.exclusions.itervalues(), key=lambda x: x.exclusions[0])\n                for exclusion in exclusionlist:\n                    lines.append('%-6d' % exclusion.exclusions[0])\n                    for i in range(1, len(exclusion.exclusions)):\n                        lines.append(' %-6d' % exclusion.exclusions[i]),\n                    lines.append('\\n')\n\n        # [ system ]\n        lines.append('[ system ]\\n')\n        lines.append('%s\\n' % (System._sys._name))\n        lines.append('\\n')\n\n        # [ molecules ]\n        lines.append('[ molecules ]\\n')\n        lines.append('; Compound        nmols\\n')\n        #for component in System._sys._components:\n        #    lines.append('%-15s%8d\\n'\n        #                 % (component[0],\n        #                    component[1]))\n        #keeping this for now, since we don't know when it might be preferable.\n        # The following lines are more 'chemical'\n        for molType in System._sys._molecules:\n            printname = molType\n            printname = printname.replace(' ','_')\n            printname = printname.replace('\"','')            \n            lines.append('%-15s%8d\\n'\n                    % (printname,\n                      len(System._sys._molecules[molType].moleculeSet)))\n\n        fout = open(filename, 'w')\n        for line in lines:\n            fout.write(line)\n        fout.close()\n\n", "meta": {"hexsha": "d802e6711a77b87f796134103579e9c0aed41c09", "size": 87339, "ext": "py", "lang": "Python", "max_stars_repo_path": "intermol/gromacs_extension/gromacs_topology_parser.py", "max_stars_repo_name": "jpthompson17/InterMol", "max_stars_repo_head_hexsha": "9289ea770bc2d069482bf5fa74dceea4c14d0e4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "intermol/gromacs_extension/gromacs_topology_parser.py", "max_issues_repo_name": "jpthompson17/InterMol", "max_issues_repo_head_hexsha": "9289ea770bc2d069482bf5fa74dceea4c14d0e4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "intermol/gromacs_extension/gromacs_topology_parser.py", "max_forks_repo_name": "jpthompson17/InterMol", "max_forks_repo_head_hexsha": "9289ea770bc2d069482bf5fa74dceea4c14d0e4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.0494636472, "max_line_length": 139, "alphanum_fraction": 0.4116145136, "include": true, "reason": "import numpy", "num_tokens": 16497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19997007186460308}}
{"text": "# functions to run velocyto and scvelo\nimport numpy as np\nimport pandas as pd\n\n# import velocyto as vcy\n# import scvelo as scv\nfrom scipy.sparse import csr_matrix\nimport matplotlib.pyplot as plt\nfrom .moments import *\nfrom anndata import AnnData\n\n\ndef vlm_to_adata(vlm, n_comps=30, basis=\"umap\", trans_mats=None, cells_ixs=None):\n    \"\"\" Conversion function from the velocyto world to the dynamo world.\n    Code original from scSLAM-seq repository\n\n    Parameters\n    ----------\n        vlm: VelocytoLoom Object\n            The VelocytoLoom object that will be converted into adata.\n        n_comps: `int` (default: 30)\n            The number of pc components that will be stored.\n        basis: `str` (default: `umap`)\n            The embedding that will be used to store the vlm.ts attribute. Note that velocyto doesn't usually use\n            umap as embedding although `umap` as set as default for the convenience of dynamo itself.\n        trans_mats: None or dict\n            A dict of all relevant transition matrices\n        cell_ixs: list of int\n            These are the indices of the subsampled cells\n\n    Returns\n    -------\n        adata: AnnData object\n\t\"\"\"\n\n    from collections import OrderedDict\n\n    # set obs, var\n    obs, var = pd.DataFrame(vlm.ca), pd.DataFrame(vlm.ra)\n    if \"CellID\" in obs.keys():\n        obs[\"obs_names\"] = obs.pop(\"CellID\")\n    if \"Gene\" in var.keys():\n        var[\"var_names\"] = var.pop(\"Gene\")\n\n    if hasattr(vlm, \"q\"):\n        var[\"gamma_b\"] = vlm.q\n    if hasattr(vlm, \"gammas\"):\n        var[\"gamma\"] = vlm.gammas\n    if hasattr(vlm, \"R2\"):\n        var[\"gamma_r2\"] = vlm.R2\n\n    # rename clusters to louvain\n    try:\n        ix = np.where(obs.columns == \"Clusters\")[0][0]\n        obs_names = list(obs.columns)\n        obs_names[ix] = \"louvain\"\n        obs.columns = obs_names\n\n        # make louvain a categorical field\n        obs[\"louvain\"] = pd.Categorical(obs[\"louvain\"])\n    except:\n        print(\"Could not find a filed 'Clusters' in vlm.ca.\")\n\n    # set layers basics\n    layers = OrderedDict(\n        unspliced=csr_matrix(vlm.U.T),\n        spliced=csr_matrix(vlm.S.T),\n        velocity_S=csr_matrix(vlm.velocity.T),\n    )\n\n    # set X_spliced / X_unspliced\n    if hasattr(vlm, \"S_norm\"):\n        layers[\"X_spliced\"] = csr_matrix(2**vlm.S_norm - 1).T\n    if hasattr(vlm, \"U_norm\"):\n        layers[\"X_unspliced\"] = csr_matrix(2**vlm.U_norm - 1).T\n    if hasattr(vlm, \"S_sz\") and not hasattr(vlm, \"S_norm\"):\n        layers[\"X_spliced\"] = csr_matrix(vlm.S_sz).T\n    if hasattr(vlm, \"U_sz\") and hasattr(vlm, \"U_norm\"):\n        layers[\"X_unspliced\"] = csr_matrix(vlm.U_sz).T\n\n    # set M_s / M_u\n    if hasattr(vlm, \"Sx\"):\n        layers[\"M_s\"] = csr_matrix(vlm.Sx).T\n    if hasattr(vlm, \"Ux\"):\n        layers[\"M_u\"] = csr_matrix(vlm.Ux).T\n    if hasattr(vlm, \"Sx_sz\") and not hasattr(vlm, \"Sx\"):\n        layers[\"M_s\"] = csr_matrix(vlm.Sx_sz).T\n    if hasattr(vlm, \"Ux_sz\") and hasattr(vlm, \"Ux\"):\n        layers[\"M_u\"] = csr_matrix(vlm.Ux_sz).T\n\n    # set obsm\n    obsm = {}\n    obsm[\"X\"] = vlm.pcs[:, : min(n_comps, vlm.pcs.shape[1])]\n    # set basis and velocity on the basis\n    if basis is not None:\n        obsm[\"X_\" + basis] = vlm.ts\n        obsm[\"velocity_\" + basis] = vlm.delta_embedding\n\n    # set transition matrix:\n    uns = {}\n    if hasattr(vlm, \"corrcoef\"):\n        uns[\"transition_matrix\"] = vlm.corrcoef\n    if hasattr(vlm, \"colorandum\"):\n        uns[\"louvain_colors\"] = list(np.unique(vlm.colorandum))\n\n    # add uns annotations\n    if trans_mats is not None:\n        for key, value in trans_mats.items():\n            uns[key] = trans_mats[key]\n    if cells_ixs is not None:\n        uns[\"cell_ixs\"] = cells_ixs\n    if hasattr(vlm, \"embedding_knn\"):\n        from .connectivity import adj_to_knn\n\n        n_neighbors = np.unique((vlm.embedding_knn > 0).sum(1)).min()\n        ind_mat, dist_mat = adj_to_knn(\n            vlm.emedding_knn, n_neighbors\n        )\n        uns[\"neighbors\"] = {\"indices\": ind_mat}\n        obsp = {'distances': dist_mat, \"connectivities\": vlm.emedding_knn}\n\n    uns[\"dynamics\"] = {\n        \"filter_gene_mode\": None,\n        \"t\": None,\n        \"group\": None,\n        \"X_data\": None,\n        \"X_fit_data\": None,\n        \"asspt_mRNA\": \"ss\",\n        \"experiment_type\": \"conventional\",\n        \"normalized\": True,\n        \"model\": \"deterministic\",\n        \"est_method\": \"ols\",\n        \"has_splicing\": True,\n        \"has_labeling\": False,\n        \"has_protein\": False,\n        \"use_smoothed\": True,\n        \"NTR_vel\": False,\n        \"log_unnormalized\": True,\n    }\n\n    # set X\n    if hasattr(vlm, \"S_norm\"):\n        X = csr_matrix(vlm.S_norm.T)\n    else:\n        X = csr_matrix(vlm.S_sz.T) if hasattr(vlm, \"S_sz\") else csr_matrix(vlm.S.T)\n\n    # create an anndata object with Dynamo characteristics.\n    dyn_adata = AnnData(X=X, obs=obs, obsp=obsp, obsm=obsm, var=var, layers=layers, uns=uns)\n\n    return dyn_adata\n\n\ndef converter(data_in, from_type=\"adata\", to_type=\"vlm\", dir=\".\"):\n    \"\"\"\n\tconvert adata to loom object\n\t- we may save_fig to a temp directory automatically\n\t- we may write a on-the-fly converter which doesn't involve saving and reading files  \n\t\"\"\"\n    if from_type == \"adata\":\n        if to_type == \"vlm\":\n            file = dir + \"/data.loom\"\n            data_in.write_loom(file)\n            data_out = vcy.VelocytoLoom(file)\n    elif from_type == \"vlm\":\n        if to_type == \"adata\":\n            data_out = vlm_to_adata(vlm)\n\n    data_out.ra[\"Gene\"] = data_out.ra[\"var_names\"]  # required by plot_phase_portraits\n    colors20 = np.vstack(\n        (\n            plt.cm.tab20b(np.linspace(0.0, 1, 20))[::2],\n            plt.cm.tab20c(np.linspace(0, 1, 20))[1::2],\n        )\n    )\n\n    def colormap_fun(x: np.ndarray) -> np.ndarray:\n        return colors20[np.mod(x, 20)]\n\n    data_out.colorandum = colormap_fun([1] * data_out.S.shape[1])\n\n    return data_out\n\n\ndef run_velocyto(adata):\n    \"\"\"\n\t1. convert adata to vlm data\n\t2. set up PCA, UMAP, etc.\n\t3. estimate the gamma parameter\n\t\"\"\"\n    vlm = converter(adata)\n\n    # U_norm: log2(U_sz + pcount)\n    # vlm.U_sz: norm_factor * U\n    # S_norm: log2(S_sz + pcount)\n    # vlm.S_sz norm_factor * S\n    # vlm.Ux: smoothed unspliced\n    # vlm.Sx: smoothed spliced\n    # vlm.Ux_sz: smoothed unspliced -- old code\n    # vlm.Sx_sz: smoothed spliced -- old code\n\n    vlm.normalize()  # add U_norm, U_sz, S_norm, S_sz\n    vlm.perform_PCA()\n    vlm.knn_imputation()  # Ux, Sx, Ux_sz, Sx_sz\n    vlm.pcs = adata.X  # pcs: cell x npcs ndarray\n\n    # vlm.Sx = vlm.S_sz\n    # vlm.Ux = vlm.U_sz\n    # vlm.Sx_sz = vlm.S_sz\n    # vlm.Ux_sz = vlm.U_sz\n\n    # gamma fit\n    vlm.fit_gammas()  # limit_gamma = False, fit_offset = True,  use_imputed_data = False, use_size_norm = False\n\n    # estimate velocity\n    vlm.predict_U()\n    vlm.calculate_velocity()\n\n    # predict future state after dt\n    vlm.calculate_shift()  # assumption = 'constant_velocity'\n    vlm.extrapolate_cell_at_t()  # delta_t = 1.\n\n    return vlm\n\n\ndef run_scvelo(adata):\n    \"\"\"\n\t1. set up PCA, UMAP, etc. \n\t2. estimate gamma and all other parameters \n\t3. return results (adata.var['velocity_gamma'])\n\t\"\"\"\n    # scv.pp.filter_and_normalize(adata, min_counts=2, min_counts_u=1, n_top_genes=3000)\n    scv.pp.moments(adata)  # , n_pcs = 12, n_neighbors = 15, mode = 'distances'\n    scv.tl.velocity(adata)\n    scv.tl.velocity_graph(adata)\n\n    # how to fit other parameters, beta, etc.?\n\n    return adata\n\n\ndef mean_var_by_time(X, Time):\n    import pandas as pd\n\n    exp_data = pd.DataFrame(X)\n    exp_data[\"Time\"] = Time\n\n    mean_val = exp_data.groupby([\"Time\"]).mean()\n    var_val = exp_data.groupby([\"Time\"]).var()\n\n    return mean_val.values, var_val.values\n\n\ndef run_dynamo(adata, normalize=True, init_num=1, sample_method=\"lhs\"):\n    time = adata.obs[\"Step\"].values\n    uniqe_time = list(set(time))\n    gene_num = adata.X.shape[1]\n\n    # prepare data\n    import numpy as np\n\n    x_data = np.zeros((8, len(uniqe_time), gene_num))  # use unique time\n    uu, ul, su, sl = (\n        adata.layers[\"uu\"].toarray(),\n        adata.layers[\"ul\"].toarray(),\n        adata.layers[\"su\"].toarray(),\n        adata.layers[\"sl\"].toarray(),\n    )\n    uu = np.log2(uu + 1) if normalize else uu\n    ul = np.log2(ul + 1) if normalize else ul\n    su = np.log2(su + 1) if normalize else su\n    sl = np.log2(sl + 1) if normalize else sl\n\n    x_data[0], x_data[4] = mean_var_by_time(uu, time)\n    x_data[1], x_data[5] = mean_var_by_time(ul, time)\n    x_data[2], x_data[6] = mean_var_by_time(su, time)\n    x_data[3], x_data[7] = mean_var_by_time(sl, time)\n\n    # estimation all parameters\n    p0_range = {\n        \"a\": [0, 1],\n        \"b\": [0, 1],\n        \"la\": [0, 1],\n        \"alpha_a\": [10, 1000],\n        \"alpha_i\": [0, 10],\n        \"sigma\": [0, 1],\n        \"beta\": [0, 10],\n        \"gamma\": [0, 10],\n    }\n\n    estm = estimation(list(p0_range.values()))\n    param_out = pd.DataFrame(\n        index=adata.var.index,\n        columns=[\"a\", \"b\", \"la\", \"alpha_a\", \"alpha_i\", \"sigma\", \"beta\", \"gamma\"],\n    )\n    for i in range(gene_num):\n        cur_x_data = x_data[:, :, i].squeeze()\n        param_out.iloc[i, :], cost = estm.fit_lsq(\n            uniqe_time, cur_x_data, p0=None, n_p0=init_num, sample_method=sample_method\n        )\n\n    # estimate only on the spliced and unspliced dataset\n\n    # estimate on the labeled and unlabeled dataset\n\n    # store the fitting result in adata.uns\n    adata.uns.update({\"dynamo\": param_out})\n\n    return adata\n\n\ndef run_dynamo_simple_fit(adata, log=True):\n    ncells, gene_num = adata.X.shape\n\n    # estimation all parameters\n    param_out = pd.DataFrame(index=adata.var.index, columns=[\"alpha\", \"gamma\"])\n\n    u, s = adata.layers[\"unspliced\"], adata.layers[\"spliced\"]\n    velocity_u, velocity_s = u, s\n    for i in range(gene_num):\n        cur_u, cur_s = u[:, i], s[:, i]\n        gamma = fit_gamma(cur_u.toarray().squeeze(), cur_s.toarray().squeeze())\n        alpha = np.mean(cur_s)\n\n        velocity_u[:, i] = cur_u - cur_s * gamma\n        velocity_s[:, i] = cur_s / (1 - np.exp(-1)) - cur_u\n        param_out.iloc[i, :] = [alpha, gamma]\n\n    adata.layers[\"velocity_u\"] = velocity_u\n    adata.layers[\"velocity_s\"] = velocity_s\n    adata.uns.update({\"dynamo_simple_fit\": param_out})\n\n    return adata\n\n\ndef run_dynamo_labelling(adata, log=True, group=False):\n    ncells, gene_num = adata.X.shape\n\n    # estimation all parameters\n    T = adata.obs[\"Time\"]\n\n    groups = [\"\"] if group == False else np.unique(adata.obs[group])\n\n    param_out = pd.DataFrame(\n        index=adata.var.index,\n        columns=[i + \"_\" + j for j in groups for i in [\"alpha\", \"gamma\", \"u0\", \"l0\"]],\n    )\n    L, U = adata.layers[\"L\"], adata.layers[\"U\"]\n    velocity_u, velocity_s = L, U\n\n    for i in range(gene_num):\n        all_parm = []\n        for cur_grp in groups.tolist():\n            cur_L, cur_U = (\n                (L[:, i], U[:, i])\n                if cur_grp == \"\"\n                else (\n                    L[adata.obs[group] == cur_grp, i],\n                    U[adata.obs[group] == cur_grp, i],\n                )\n            )\n            if log:\n                cur_U, cur_L = (\n                    np.log(cur_U.toarray().squeeze() + 1),\n                    np.log(cur_L.toarray().squeeze() + 1),\n                )\n            else:\n                cur_U, cur_L = cur_U.toarray().squeeze(), cur_L.toarray().squeeze()\n\n            gamma, l0 = fit_gamma_labelling(T, cur_L, mode=None)\n            alpha, u0 = fit_alpha_labelling(T, cur_U, gamma, mode=None)\n            tmp = [alpha, gamma, u0, l0]\n            all_parm.extend(tmp)\n\n            velocity_u[:, i] = (cur_L - cur_U * gamma)[:, None]\n            velocity_s[:, i] = (cur_U / (1 - np.exp(-1)) - cur_L)[:, None]\n            adata.layers[cur_grp + \"velocity_u\"] = velocity_u\n            adata.layers[cur_grp + \"velocity_s\"] = velocity_s\n\n        param_out.iloc[i, :] = all_parm\n\n    adata.uns.update({\"dynamo_labelling\": param_out})\n\n    return adata\n\n\ndef compare_res(\n    adata,\n    velocyto_res,\n    svelo_res,\n    dynamo_res,\n    a_val,\n    b_val,\n    la_val,\n    alpha_a_val,\n    alpha_i_val,\n    sigma_val,\n    beta_val,\n    gamma_val,\n):\n    \"\"\"\n\tfunction to compare results from velocyto and scvelo with our new method\n\t0. retrieve gamm or gamma with other parameters from velocyto result or scvelo\n\t1. plot the correlation between parameters estimated with different methods\n\t2. calculate the correltion between those parameters\n\t\"\"\"\n    # self._offset, self._offset2, self._beta, self._gamma, self._r2, self._velocity_genes\n\n    velocyto_gammas = velocyto_res.gammas\n    scvelo_gammas = svelo_res.var[\"velocity_gamma\"]\n\n    # scatter plot the true gammas with our result\n    plt.subplots(figsize=(15, 5))\n    plt.plot()\n    plt.subplot(131)\n    plt.plot(gamma_val, velocyto_gammas, \"o\")\n    plt.xlabel(r\"True $\\gamma$\")\n    plt.ylabel(r\"$\\gamma$ (velocyto)\")\n    plt.subplot(132)\n    plt.plot(gamma_val, scvelo_gammas, \"o\")\n    plt.xlabel(r\"True $\\gamma$\")\n    plt.ylabel(r\"$\\gamma$ (scvelo)\")\n    plt.subplot(133)\n    plt.plot(gamma_val, dynamo_res.uns[\"dynamo\"][\"gamma\"], \"o\")\n    plt.xlabel(r\"True $\\gamma$\")\n    plt.ylabel(r\"$\\gamma$ (dynamo)\")\n\n    # what if we only have a small number of parameters?\n    plt.subplots(figsize=(15, 5))\n    plt.plot()\n    plt.subplot(131)\n    plt.plot(alpha_a_val, svelo_res.var[\"fit_alpha\"], \"o\")\n    plt.xlabel(r\"True alpha\")\n    plt.ylabel(r\"$\\alpha$ (scvelo)\")\n    plt.subplot(132)\n    plt.plot(beta_val, svelo_res.var[\"fit_beta\"], \"o\")\n    plt.xlabel(r\"True $\\beta$\")\n    plt.ylabel(r\"$\\beta$ (scvelo)\")\n    plt.subplot(133)\n    plt.plot(gamma_val, svelo_res.var[\"fit_gamma\"], \"o\")\n    plt.xlabel(r\"True $\\gamma$\")\n    plt.ylabel(r\"$\\gamma$ (scvelo)\")\n\n    #     param_out = pd.DataFrame(index=adata.var.index, columns=['a', 'b', 'la', 'alpha_a', 'alpha_i', 'sigma', 'beta', 'gamma'])\n    # what if we only have a small number of parameters?\n    plt.subplots(figsize=(15, 15))\n    plt.subplot(331)\n    plt.plot(a_val, adata.uns[\"dynamo\"][\"a\"], \"o\")\n    plt.xlabel(r\"True $a$\")\n    plt.ylabel(r\"$a$ (dynamo)\")\n    plt.subplot(332)\n    plt.plot(b_val, adata.uns[\"dynamo\"][\"b\"], \"o\")\n    plt.xlabel(r\"True $b$\")\n    plt.ylabel(r\"$b$ (dynamo)\")\n    plt.subplot(333)\n    plt.plot(la_val, adata.uns[\"dynamo\"][\"la\"], \"o\")\n    plt.xlabel(r\"True $l_a$\")\n    plt.ylabel(r\"$l_a$ (dynamo)\")\n    plt.subplot(334)\n    plt.plot(alpha_a_val, adata.uns[\"dynamo\"][\"alpha_a\"], \"o\")\n    plt.xlabel(r\"True $\\alpha_a$\")\n    plt.ylabel(r\"$\\alpha_a$ (dynamo)\")\n    plt.subplot(335)\n    plt.plot(alpha_i_val, adata.uns[\"dynamo\"][\"alpha_i\"], \"o\")\n    plt.xlabel(r\"True $\\alpha_i$\")\n    plt.ylabel(r\"$\\alpha_i$ (dynamo)\")\n    plt.subplot(336)\n    plt.plot(sigma_val, adata.uns[\"dynamo\"][\"sigma\"], \"o\")\n    plt.xlabel(r\"True $\\sigma$\")\n    plt.ylabel(r\"$\\sigma$ (dynamo)\")\n    plt.subplot(337)\n    plt.plot(beta_val, adata.uns[\"dynamo\"][\"beta\"], \"o\")\n    plt.xlabel(r\"True $\\beta$\")\n    plt.ylabel(r\"$\\beta$ (dynamo)\")\n    plt.subplot(338)\n    plt.plot(gamma_val, adata.uns[\"dynamo\"][\"gamma\"], \"o\")\n    plt.xlabel(r\"True $\\gamma$\")\n    plt.ylabel(r\"$\\gamma$ (dynamo)\")\n\n    velocyto_coef = {\"gamma\": np.corrcoef(gamma_val, velocyto_gammas)[1, 0]}\n    scvelo_coef = {\n        \"alpha\": np.corrcoef(alpha_a_val, svelo_res.var[\"fit_alpha\"])[1, 0],\n        \"beta\": np.corrcoef(beta_val, svelo_res.var[\"fit_beta\"])[1, 0],\n        \"gamma\": np.corrcoef(gamma_val, svelo_res.var[\"fit_gamma\"])[1, 0],\n    }\n\n    dynamo_coef = {\n        \"a\": np.corrcoef(a_val, list(dynamo_res.uns[\"dynamo\"][\"a\"]))[1, 0],\n        \"b\": np.corrcoef(b_val, list(dynamo_res.uns[\"dynamo\"][\"b\"]))[1, 0],\n        \"la\": np.corrcoef(la_val, list(dynamo_res.uns[\"dynamo\"][\"la\"]))[1, 0],\n        \"alpha_a\": np.corrcoef(alpha_a_val, list(dynamo_res.uns[\"dynamo\"][\"alpha_a\"]))[\n            1, 0\n        ],\n        \"alpha_i\": np.corrcoef(alpha_i_val, list(dynamo_res.uns[\"dynamo\"][\"alpha_i\"]))[\n            1, 0\n        ],\n        \"sigma\": np.corrcoef(sigma_val, list(dynamo_res.uns[\"dynamo\"][\"sigma\"]))[1, 0],\n        \"beta\": np.corrcoef(beta_val, list(dynamo_res.uns[\"dynamo\"][\"beta\"]))[1, 0],\n        \"gamma\": np.corrcoef(gamma_val, list(dynamo_res.uns[\"dynamo\"][\"gamma\"]))[1, 0],\n    }\n\n    return {\n        \"velocyto\": pd.DataFrame.from_dict(velocyto_coef, orient=\"index\").T,\n        \"scvelo\": pd.DataFrame.from_dict(scvelo_coef, orient=\"index\").T,\n        \"dynamo\": pd.DataFrame.from_dict(dynamo_coef, orient=\"index\").T,\n    }\n", "meta": {"hexsha": "e80d69c83c74d94605fc2b90ef58d43683719f17", "size": 16396, "ext": "py", "lang": "Python", "max_stars_repo_path": "dynamo/tools/velocyto_scvelo.py", "max_stars_repo_name": "davisidarta/dynamo-release", "max_stars_repo_head_hexsha": "0dbd769f52ea07f3cdaa8fb31022ceb89938c382", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dynamo/tools/velocyto_scvelo.py", "max_issues_repo_name": "davisidarta/dynamo-release", "max_issues_repo_head_hexsha": "0dbd769f52ea07f3cdaa8fb31022ceb89938c382", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dynamo/tools/velocyto_scvelo.py", "max_forks_repo_name": "davisidarta/dynamo-release", "max_forks_repo_head_hexsha": "0dbd769f52ea07f3cdaa8fb31022ceb89938c382", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4031620553, "max_line_length": 131, "alphanum_fraction": 0.5996584533, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.38491214448393357, "lm_q1q2_score": 0.19997006613770818}}
{"text": "__author__ = ['sibirrer', 'ajshajib', 'dgilman']\n\nimport time\n\nimport numpy as np\nfrom lenstronomy.Sampling.Samplers.pso import ParticleSwarmOptimizer\nfrom lenstronomy.Util import sampling_util\nimport emcee\nimport schwimmbad\nfrom scipy.optimize import minimize\n\n\ndef choose_pool(mpi=False, processes=1, **kwargs):\n    \"\"\"\n    Extends the capabilities of the schwimmbad.choose_pool method.\n    \n    It handles the `use_dill` parameters in kwargs, that would otherwise raise an error when processes > 1.\n    Any thread in the returned multiprocessing pool (e.g. processes > 1) also default\n    \n\n    Docstring from schwimmbad:\n\n    mpi : bool, optional\n        Use the MPI processing pool, :class:`~schwimmbad.mpi.MPIPool`. By\n        default, ``False``, will use the :class:`~schwimmbad.serial.SerialPool`.\n    processes : int, optional\n        Use the multiprocessing pool,\n        :class:`~schwimmbad.multiprocessing.MultiPool`, with this number of\n        processes. By default, ``processes=1``, will use the\n        :class:`~schwimmbad.serial.SerialPool`.\n    **kwargs\n            Any additional kwargs are passed in to the pool class initializer selected by the arguments.\n    \"\"\"\n    if processes == 1 or mpi:\n        pool = schwimmbad.choose_pool(mpi=mpi, processes=1, **kwargs)\n        is_master = pool.is_master()\n    else:\n        if 'use_dill' in kwargs:\n            # schwimmbad MultiPool does not support dill so we remove this option from the kwargs\n            _ = kwargs.pop('use_dill')\n        pool = schwimmbad.choose_pool(mpi=False, processes=processes, **kwargs)\n        # this MultiPool has no is_master() attribute like the SerialPool and MpiPool\n        # all threads will then be 'master'.\n        is_master = True\n    return pool, is_master\n\n\nclass Sampler(object):\n    \"\"\"\n    class which executes the different sampling  methods\n    Available are: MCMC with emcee and comsoHammer and a Particle Swarm Optimizer.\n    This are examples and depending on your problem, you might find other/better solutions.\n    Feel free to sample with your convenient sampler!\n\n    \"\"\"\n    def __init__(self, likelihoodModule):\n        \"\"\"\n\n        :param likelihoodModule: instance of LikelihoodModule class\n        \"\"\"\n        self.chain = likelihoodModule\n        self.lower_limit, self.upper_limit = self.chain.param_limits\n\n    def simplex(self, init_pos, n_iterations, method, print_key='SIMPLEX'):\n        \"\"\"\n\n        :param init_pos: starting point for the optimization\n        :param n_iterations: maximum number of iterations\n        :param method: the optimization method, default is 'Nelder-Mead'\n        :return: the best fit for the lens model using the optimization routine specified by method\n        \"\"\"\n        print('Performing the optimization using algorithm:', method)\n        time_start = time.time()\n\n        #negativelogL = lambda x: -1 * self.chain.logL(x)\n\n        result = minimize(self.chain.negativelogL, x0=init_pos, method=method,\n                          options={'maxiter': n_iterations, 'disp': True})\n        logL = self.chain.logL(result['x'])\n        kwargs_return = self.chain.param.args2kwargs(result['x'])\n        print(-logL * 2 / (max(self.chain.effective_num_data_points(**kwargs_return), 1)),\n              'reduced X^2 of best position')\n        print(logL, 'logL')\n        print(self.chain.effective_num_data_points(**kwargs_return), 'effective number of data points')\n        print(kwargs_return.get('kwargs_lens', None), 'lens result')\n        print(kwargs_return.get('kwargs_source', None), 'source result')\n        print(kwargs_return.get('kwargs_lens_light', None), 'lens light result')\n        print(kwargs_return.get('kwargs_ps', None), 'point source result')\n        print(kwargs_return.get('kwargs_special', None), 'special param result')\n        time_end = time.time()\n        print(time_end - time_start, 'time used for ', print_key)\n        print('===================')\n\n        return result['x']\n\n    def pso(self, n_particles, n_iterations, lower_start=None, upper_start=None,\n            threadCount=1, init_pos=None, mpi=False, print_key='PSO'):\n        \"\"\"\n        Return the best fit for the lens model on catalogue basis with\n        particle swarm optimizer.\n\n        :param n_particles: number of particles in the sampling process\n        :param n_iterations: number of iterations of the swarm\n        :param lower_start: numpy array, lower end parameter of the values of the starting particles\n        :param upper_start: numpy array, upper end parameter of the values of the starting particles\n        :param threadCount: number of threads in the computation (only applied if mpi=False)\n        :param init_pos: numpy array, position of the initial best guess model\n        :param mpi: bool, if True, makes instance of MPIPool to allow for MPI execution\n        :param print_key: string, prints the process name in the progress bar (optional)\n        :return: kwargs_result (of best fit), [lnlikelihood of samples, positions of samples, velocity of sampels)\n        \"\"\"\n        if lower_start is None or upper_start is None:\n            lower_start, upper_start = np.array(self.lower_limit), np.array(self.upper_limit)\n            print(\"PSO initialises its particles with default values\")\n        else:\n            lower_start = np.maximum(lower_start, self.lower_limit)\n            upper_start = np.minimum(upper_start, self.upper_limit)\n\n        pool, is_master = choose_pool(mpi=mpi, processes=threadCount, use_dill=True)\n        \n        if mpi is True and is_master:\n            print('MPI option chosen for PSO.')\n\n        pso = ParticleSwarmOptimizer(self.chain.logL,\n                                     lower_start, upper_start, n_particles,\n                                     pool=pool)\n\n        if init_pos is None:\n            init_pos = (upper_start - lower_start) / 2 + lower_start\n\n        pso.set_global_best(init_pos, [0]*len(init_pos),\n                            self.chain.logL(init_pos))\n\n        if is_master:\n            print('Computing the %s ...' % print_key)\n\n        time_start = time.time()\n\n        result, [chi2_list, pos_list, vel_list] = pso.optimize(n_iterations)\n\n        if is_master:\n            kwargs_return = self.chain.param.args2kwargs(result)\n            print(pso.global_best.fitness * 2 / (max(\n                self.chain.effective_num_data_points(**kwargs_return), 1)), 'reduced X^2 of best position')\n            print(pso.global_best.fitness, 'logL')\n            print(self.chain.effective_num_data_points(**kwargs_return), 'effective number of data points')\n            print(kwargs_return.get('kwargs_lens', None), 'lens result')\n            print(kwargs_return.get('kwargs_source', None), 'source result')\n            print(kwargs_return.get('kwargs_lens_light', None), 'lens light result')\n            print(kwargs_return.get('kwargs_ps', None), 'point source result')\n            print(kwargs_return.get('kwargs_special', None), 'special param result')\n            time_end = time.time()\n            print(time_end - time_start, 'time used for ', print_key)\n            print('===================')\n        return result, [chi2_list, pos_list, vel_list]\n\n    def mcmc_emcee(self, n_walkers, n_run, n_burn, mean_start, sigma_start, mpi=False, progress=False, threadCount=1):\n        \"\"\"\n        Run MCMC with emcee.\n        For details, please have a look at the documentation of the emcee packager.\n\n        :param n_walkers: number of walkers in the emcee process\n        :type n_walkers: integer\n        :param n_run: number of sampling (after burn-in) of the emcee\n        :type n_run: integer\n        :param n_burn: number of burn-in iterations (those will not be saved in the output sample)\n        :type n_burn: integer\n        :param mean_start: mean of the parameter position of the initialising sample\n        :type mean_start: numpy array of length the number of parameters\n        :param sigma_start: spread of the parameter values (uncorrelated in each dimension) of the initialising sample\n        :type sigma_start: numpy array of length the number of parameters\n        :param mpi: if True, initializes an MPIPool to allow for MPI execution of the sampler\n        :type mpi: bool\n        :param progress: if True, prints the progress bar\n        :type progress: bool\n        :param threadCount: number of threats in multi-processing (not applicable for MPI)\n        :type threadCount: integer\n        :return: samples, ln likelihood value of samples\n        :rtype: numpy 2d array, numpy 1d array\n        \"\"\"\n        num_param, _ = self.chain.param.num_param()\n        p0 = sampling_util.sample_ball(mean_start, sigma_start, n_walkers)\n        time_start = time.time()\n\n        pool, is_master = choose_pool(mpi=mpi, processes=threadCount, use_dill=True)\n\n        sampler = emcee.EnsembleSampler(n_walkers, num_param, self.chain.logL,\n                                        pool=pool)\n\n        sampler.run_mcmc(p0, n_burn + n_run, progress=progress)\n        flat_samples = sampler.get_chain(discard=n_burn, thin=1, flat=True)\n        dist = sampler.get_log_prob(flat=True, discard=n_burn, thin=1)\n        if is_master:\n            print('Computing the MCMC...')\n            print('Number of walkers = ', n_walkers)\n            print('Burn-in iterations: ', n_burn)\n            print('Sampling iterations:', n_run)\n            time_end = time.time()\n            print(time_end - time_start, 'time taken for MCMC sampling')\n        return flat_samples, dist\n", "meta": {"hexsha": "2aff7883bead0a96d3419b7d8eac9391927dd127", "size": 9508, "ext": "py", "lang": "Python", "max_stars_repo_path": "lenstronomy/Sampling/sampler.py", "max_stars_repo_name": "Thomas-01/lenstronomy", "max_stars_repo_head_hexsha": "36db4c7f43ba28d6bdecdab1f15c537043f4a286", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lenstronomy/Sampling/sampler.py", "max_issues_repo_name": "Thomas-01/lenstronomy", "max_issues_repo_head_hexsha": "36db4c7f43ba28d6bdecdab1f15c537043f4a286", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lenstronomy/Sampling/sampler.py", "max_forks_repo_name": "Thomas-01/lenstronomy", "max_forks_repo_head_hexsha": "36db4c7f43ba28d6bdecdab1f15c537043f4a286", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.3034825871, "max_line_length": 118, "alphanum_fraction": 0.6567101388, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19997006613770815}}
{"text": "# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n# This module was adapted from Scikit-Survival python package to\n# extract the adjusted TPR and FPR rates for all classification\n# thresholds for the censoring adjusted ROC curve. It depends on\n# Scikit-Survival. For the full package please check: \n# https://github.com/sebp/scikit-survival\n\nimport numpy\nfrom scipy.integrate import trapz\nfrom sklearn.utils import check_consistent_length, check_array\n\nfrom sksurv.nonparametric import CensoringDistributionEstimator, SurvivalFunctionEstimator\nfrom sksurv.util import check_y_survival\n\n__all__ = [\n    'brier_score',\n    'concordance_index_censored',\n    'concordance_index_ipcw',\n    'cumulative_dynamic_auc',\n    'integrated_brier_score',\n]\n\n\ndef _check_estimate(estimate, test_time):\n    estimate = check_array(estimate, ensure_2d=False)\n    if estimate.ndim != 1:\n        raise ValueError(\n            'Expected 1D array, got {:d}D array instead:\\narray={}.\\n'.format(\n                estimate.ndim, estimate))\n    check_consistent_length(test_time, estimate)\n    return estimate\n\n\ndef _check_inputs(event_indicator, event_time, estimate):\n    check_consistent_length(event_indicator, event_time, estimate)\n    event_indicator = check_array(event_indicator, ensure_2d=False)\n    event_time = check_array(event_time, ensure_2d=False)\n    estimate = _check_estimate(estimate, event_time)\n\n    if not numpy.issubdtype(event_indicator.dtype, numpy.bool_):\n        raise ValueError(\n            'only boolean arrays are supported as class labels for survival analysis, got {0}'.format(\n                event_indicator.dtype))\n\n    if len(event_time) < 2:\n        raise ValueError(\"Need a minimum of two samples\")\n\n    if not event_indicator.any():\n        raise ValueError(\"All samples are censored\")\n\n    return event_indicator, event_time, estimate\n\n\ndef _check_times(test_time, times):\n    times = check_array(numpy.atleast_1d(times), ensure_2d=False, dtype=test_time.dtype)\n    times = numpy.unique(times)\n\n    if times.max() >= test_time.max() or times.min() < test_time.min():\n        raise ValueError(\n            'all times must be within follow-up time of test data: [{}; {}['.format(\n                test_time.min(), test_time.max()))\n\n    return times\n\n\ndef _get_comparable(event_indicator, event_time, order):\n    n_samples = len(event_time)\n    tied_time = 0\n    comparable = {}\n    i = 0\n    while i < n_samples - 1:\n        time_i = event_time[order[i]]\n        start = i + 1\n        end = start\n        while end < n_samples and event_time[order[end]] == time_i:\n            end += 1\n\n        # check for tied event times\n        event_at_same_time = event_indicator[order[i:end]]\n        censored_at_same_time = ~event_at_same_time\n        for j in range(i, end):\n            if event_indicator[order[j]]:\n                mask = numpy.zeros(n_samples, dtype=bool)\n                mask[end:] = True\n                # an event is comparable to censored samples at same time point\n                mask[i:end] = censored_at_same_time\n                comparable[j] = mask\n                tied_time += censored_at_same_time.sum()\n        i = end\n\n    return comparable, tied_time\n\n\ndef _estimate_concordance_index(event_indicator, event_time, estimate, weights, tied_tol=1e-8):\n    order = numpy.argsort(event_time)\n\n    comparable, tied_time = _get_comparable(event_indicator, event_time, order)\n\n    concordant = 0\n    discordant = 0\n    tied_risk = 0\n    numerator = 0.0\n    denominator = 0.0\n    for ind, mask in comparable.items():\n        est_i = estimate[order[ind]]\n        event_i = event_indicator[order[ind]]\n        w_i = weights[order[ind]]\n\n        est = estimate[order[mask]]\n\n        assert event_i, 'got censored sample at index %d, but expected uncensored' % order[ind]\n\n        ties = numpy.absolute(est - est_i) <= tied_tol\n        n_ties = ties.sum()\n        # an event should have a higher score\n        con = est < est_i\n        n_con = con[~ties].sum()\n\n        numerator += w_i * n_con + 0.5 * w_i * n_ties\n        denominator += w_i * mask.sum()\n\n        tied_risk += n_ties\n        concordant += n_con\n        discordant += est.size - n_con - n_ties\n\n    cindex = numerator / denominator\n    return cindex, concordant, discordant, tied_risk, tied_time\n\n\ndef concordance_index_censored(event_indicator, event_time, estimate, tied_tol=1e-8):\n    \"\"\"Concordance index for right-censored data\n\n    The concordance index is defined as the proportion of all comparable pairs\n    in which the predictions and outcomes are concordant.\n\n    Two samples are comparable if (i) both of them experienced an event (at different times),\n    or (ii) the one with a shorter observed survival time experienced an event, in which case\n    the event-free subject \"outlived\" the other. A pair is not comparable if they experienced\n    events at the same time.\n\n    Concordance intuitively means that two samples were ordered correctly by the model.\n    More specifically, two samples are concordant, if the one with a higher estimated\n    risk score has a shorter actual survival time.\n    When predicted risks are identical for a pair, 0.5 rather than 1 is added to the count\n    of concordant pairs.\n\n    See [1]_ for further description.\n\n    Parameters\n    ----------\n    event_indicator : array-like, shape = (n_samples,)\n        Boolean array denotes whether an event occurred\n\n    event_time : array-like, shape = (n_samples,)\n        Array containing the time of an event or time of censoring\n\n    estimate : array-like, shape = (n_samples,)\n        Estimated risk of experiencing an event\n\n    tied_tol : float, optional, default: 1e-8\n        The tolerance value for considering ties.\n        If the absolute difference between risk scores is smaller\n        or equal than `tied_tol`, risk scores are considered tied.\n\n    Returns\n    -------\n    cindex : float\n        Concordance index\n\n    concordant : int\n        Number of concordant pairs\n\n    discordant : int\n        Number of discordant pairs\n\n    tied_risk : int\n        Number of pairs having tied estimated risks\n\n    tied_time : int\n        Number of comparable pairs sharing the same time\n\n    References\n    ----------\n    .. [1] Harrell, F.E., Califf, R.M., Pryor, D.B., Lee, K.L., Rosati, R.A,\n           \"Multivariable prognostic models: issues in developing models,\n           evaluating assumptions and adequacy, and measuring and reducing errors\",\n           Statistics in Medicine, 15(4), 361-87, 1996.\n    \"\"\"\n    event_indicator, event_time, estimate = _check_inputs(\n        event_indicator, event_time, estimate)\n\n    w = numpy.ones_like(estimate)\n\n    return _estimate_concordance_index(event_indicator, event_time, estimate, w, tied_tol)\n\n\ndef concordance_index_ipcw(survival_train, survival_test, estimate, tau=None, tied_tol=1e-8):\n    \"\"\"Concordance index for right-censored data based on inverse probability of censoring weights.\n\n    This is an alternative to the estimator in :func:`concordance_index_censored`\n    that does not depend on the distribution of censoring times in the test data.\n    Therefore, the estimate is unbiased and consistent for a population concordance\n    measure that is free of censoring.\n\n    It is based on inverse probability of censoring weights, thus requires\n    access to survival times from the training data to estimate the censoring\n    distribution. Note that this requires that survival times `survival_test`\n    lie within the range of survival times `survival_train`. This can be\n    achieved by specifying the truncation time `tau`.\n    The resulting `cindex` tells how well the given prediction model works in\n    predicting events that occur in the time range from 0 to `tau`.\n\n    The estimator uses the Kaplan-Meier estimator to estimate the\n    censoring survivor function. Therefore, it is restricted to\n    situations where the random censoring assumption holds and\n    censoring is independent of the features.\n\n    See [1]_ for further description.\n\n    Parameters\n    ----------\n    survival_train : structured array, shape = (n_train_samples,)\n        Survival times for training data to estimate the censoring\n        distribution from.\n        A structured array containing the binary event indicator\n        as first field, and time of event or time of censoring as\n        second field.\n\n    survival_test : structured array, shape = (n_samples,)\n        Survival times of test data.\n        A structured array containing the binary event indicator\n        as first field, and time of event or time of censoring as\n        second field.\n\n    estimate : array-like, shape = (n_samples,)\n        Estimated risk of experiencing an event of test data.\n\n    tau : float, optional\n        Truncation time. The survival function for the underlying\n        censoring time distribution :math:`D` needs to be positive\n        at `tau`, i.e., `tau` should be chosen such that the\n        probability of being censored after time `tau` is non-zero:\n        :math:`P(D > \\\\tau) > 0`. If `None`, no truncation is performed.\n\n    tied_tol : float, optional, default: 1e-8\n        The tolerance value for considering ties.\n        If the absolute difference between risk scores is smaller\n        or equal than `tied_tol`, risk scores are considered tied.\n\n    Returns\n    -------\n    cindex : float\n        Concordance index\n\n    concordant : int\n        Number of concordant pairs\n\n    discordant : int\n        Number of discordant pairs\n\n    tied_risk : int\n        Number of pairs having tied estimated risks\n\n    tied_time : int\n        Number of comparable pairs sharing the same time\n\n    References\n    ----------\n    .. [1] Uno, H., Cai, T., Pencina, M. J., D’Agostino, R. B., & Wei, L. J. (2011).\n           \"On the C-statistics for evaluating overall adequacy of risk prediction\n           procedures with censored survival data\".\n           Statistics in Medicine, 30(10), 1105–1117.\n    \"\"\"\n    test_event, test_time = check_y_survival(survival_test)\n\n    if tau is not None:\n        mask = test_time < tau\n        survival_test = survival_test[mask]\n\n    estimate = _check_estimate(estimate, test_time)\n\n    cens = CensoringDistributionEstimator()\n    cens.fit(survival_train)\n    ipcw_test = cens.predict_ipcw(survival_test)\n    if tau is None:\n        ipcw = ipcw_test\n    else:\n        ipcw = numpy.empty(estimate.shape[0], dtype=ipcw_test.dtype)\n        ipcw[mask] = ipcw_test\n        ipcw[~mask] = 0\n\n    w = numpy.square(ipcw)\n\n    return _estimate_concordance_index(test_event, test_time, estimate, w, tied_tol)\n\n\ndef cumulative_dynamic_auc(survival_train, survival_test, estimate, times, tied_tol=1e-8):\n    \"\"\"Estimator of cumulative/dynamic AUC for right-censored time-to-event data.\n\n    The receiver operating characteristic (ROC) curve and the area under the\n    ROC curve (AUC) can be extended to survival data by defining\n    sensitivity (true positive rate) and specificity (true negative rate)\n    as time-dependent measures. *Cumulative cases* are all individuals that\n    experienced an event prior to or at time :math:`t` (:math:`t_i \\\\leq t`),\n    whereas *dynamic controls* are those with :math:`t_i > t`.\n    The associated cumulative/dynamic AUC quantifies how well a model can\n    distinguish subjects who fail by a given time (:math:`t_i \\\\leq t`) from\n    subjects who fail after this time (:math:`t_i > t`).\n\n    Given an estimator of the :math:`i`-th individual's risk score\n    :math:`\\\\hat{f}(\\\\mathbf{x}_i)`, the cumulative/dynamic AUC at time\n    :math:`t` is defined as\n\n    .. math::\n\n        \\\\widehat{\\\\mathrm{AUC}}(t) =\n        \\\\frac{\\\\sum_{i=1}^n \\\\sum_{j=1}^n I(y_j > t) I(y_i \\\\leq t) \\\\omega_i\n        I(\\\\hat{f}(\\\\mathbf{x}_j) \\\\leq \\\\hat{f}(\\\\mathbf{x}_i))}\n        {(\\\\sum_{i=1}^n I(y_i > t)) (\\\\sum_{i=1}^n I(y_i \\\\leq t) \\\\omega_i)}\n\n    where :math:`\\\\omega_i` are inverse probability of censoring weights (IPCW).\n\n    To estimate IPCW, access to survival times from the training data is required\n    to estimate the censoring distribution. Note that this requires that survival\n    times `survival_test` lie within the range of survival times `survival_train`.\n    This can be achieved by specifying `times` accordingly, e.g. by setting\n    `times[-1]` slightly below the maximum expected follow-up time.\n    IPCW are computed using the Kaplan-Meier estimator, which is\n    restricted to situations where the random censoring assumption holds and\n    censoring is independent of the features.\n\n    The function also provides a single summary measure that refers to the mean\n    of the :math:`\\\\mathrm{AUC}(t)` over the time range :math:`(\\\\tau_1, \\\\tau_2)`.\n\n    .. math::\n\n        \\\\overline{\\\\mathrm{AUC}}(\\\\tau_1, \\\\tau_2) =\n        \\\\frac{1}{\\\\hat{S}(\\\\tau_1) - \\\\hat{S}(\\\\tau_2)}\n        \\\\int_{\\\\tau_1}^{\\\\tau_2} \\\\widehat{\\\\mathrm{AUC}}(t)\\\\,d \\\\hat{S}(t)\n\n    where :math:`\\\\hat{S}(t)` is the Kaplan–Meier estimator of the survival function.\n\n    See [1]_, [2]_, [3]_ for further description.\n\n    Parameters\n    ----------\n    survival_train : structured array, shape = (n_train_samples,)\n        Survival times for training data to estimate the censoring\n        distribution from.\n        A structured array containing the binary event indicator\n        as first field, and time of event or time of censoring as\n        second field.\n\n    survival_test : structured array, shape = (n_samples,)\n        Survival times of test data.\n        A structured array containing the binary event indicator\n        as first field, and time of event or time of censoring as\n        second field.\n\n    estimate : array-like, shape = (n_samples,)\n        Estimated risk of experiencing an event of test data.\n\n    times : array-like, shape = (n_times,)\n        The time points for which the area under the\n        time-dependent ROC curve is computed. Values must be\n        within the range of follow-up times of the test data\n        `survival_test`.\n\n    tied_tol : float, optional, default: 1e-8\n        The tolerance value for considering ties.\n        If the absolute difference between risk scores is smaller\n        or equal than `tied_tol`, risk scores are considered tied.\n\n    Returns\n    -------\n    auc : array, shape = (n_times,)\n        The cumulative/dynamic AUC estimates (evaluated at `times`).\n    mean_auc : float\n        Summary measure referring to the mean cumulative/dynamic AUC\n        over the specified time range `(times[0], times[-1])`.\n\n    References\n    ----------\n    .. [1] H. Uno, T. Cai, L. Tian, and L. J. Wei,\n           \"Evaluating prediction rules for t-year survivors with censored regression models,\"\n           Journal of the American Statistical Association, vol. 102, pp. 527–537, 2007.\n    .. [2] H. Hung and C. T. Chiang,\n           \"Estimation methods for time-dependent AUC models with survival data,\"\n           Canadian Journal of Statistics, vol. 38, no. 1, pp. 8–26, 2010.\n    .. [3] J. Lambert and S. Chevret,\n           \"Summary measure of discrimination in survival models based on cumulative/dynamic time-dependent ROC curves,\"\n           Statistical Methods in Medical Research, 2014.\n    \"\"\"\n        \n    test_event, test_time = check_y_survival(survival_test)\n    \n    estimate = _check_estimate(estimate, test_time)\n\n    times = _check_times(test_time, times)\n\n    # sort by risk score (descending)\n    o = numpy.argsort(-estimate)\n    test_time = test_time[o]\n    test_event = test_event[o]\n    estimate = estimate[o]\n    survival_test = survival_test[o]\n\n    cens = CensoringDistributionEstimator()\n    cens.fit(survival_train)\n    ipcw = cens.predict_ipcw(survival_test)\n\n    n_samples = test_time.shape[0]\n    scores = numpy.empty(times.shape[0], dtype=float)\n    rocs = []\n    \n    \n    for k, t in enumerate(times):\n        is_case = (test_time <= t) & test_event\n        is_control = test_time > t\n        n_controls = is_control.sum()\n\n        true_pos = []\n        false_pos = []\n        tp_value = 0.0\n        fp_value = 0.0\n        est_prev = numpy.infty\n\n        for i in range(n_samples):\n            est = estimate[i]\n            if numpy.absolute(est - est_prev) > tied_tol:\n                true_pos.append(tp_value)\n                false_pos.append(fp_value)\n                est_prev = est\n            if is_case[i]:\n                tp_value += ipcw[i]\n            elif is_control[i]:\n                fp_value += 1\n        true_pos.append(tp_value)\n        false_pos.append(fp_value)\n\n        sens = numpy.array(true_pos) / ipcw[is_case].sum()\n        fpr = numpy.array(false_pos) / n_controls\n        scores[k] = trapz(sens, fpr)\n        \n        rocs.append((sens, fpr))\n        \n    if times.shape[0] == 1:\n        mean_auc = scores[0]\n    else:\n        surv = SurvivalFunctionEstimator()\n        surv.fit(survival_test)\n        s_times = surv.predict_proba(times)\n        # compute integral of AUC over survival function\n        d = -numpy.diff(numpy.concatenate(([1.0], s_times)))\n        integral = (scores * d).sum()\n        mean_auc = integral / (1.0 - s_times[-1])\n\n    return rocs, scores, mean_auc\n\n\ndef brier_score(survival_train, survival_test, estimate, times):\n    \"\"\"Estimate the time-dependent Brier score for right censored data.\n\n    The time-dependent Brier score is the mean squared error at time point :math:`t`:\n\n    .. math::\n\n        \\\\mathrm{BS}^c(t) = \\\\frac{1}{n} \\\\sum_{i=1}^n I(y_i \\\\leq t \\\\land \\\\delta_i = 1)\n        \\\\frac{(0 - \\\\hat{\\\\pi}(t | \\\\mathbf{x}_i))^2}{\\\\hat{G}(y_i)} + I(y_i > t)\n        \\\\frac{(1 - \\\\hat{\\\\pi}(t | \\\\mathbf{x}_i))^2}{\\\\hat{G}(t)} ,\n\n    where :math:`\\\\hat{\\\\pi}(t | \\\\mathbf{x})` is the predicted probability of\n    remaining event-free up to time point :math:`t` for a feature vector :math:`\\\\mathbf{x}`,\n    and :math:`1/\\\\hat{G}(t)` is a inverse probability of censoring weight, estimated by\n    the Kaplan-Meier estimator.\n\n    See [1]_ for details.\n\n    Parameters\n    ----------\n    survival_train : structured array, shape = (n_train_samples,)\n        Survival times for training data to estimate the censoring\n        distribution from.\n        A structured array containing the binary event indicator\n        as first field, and time of event or time of censoring as\n        second field.\n\n    survival_test : structured array, shape = (n_samples,)\n        Survival times of test data.\n        A structured array containing the binary event indicator\n        as first field, and time of event or time of censoring as\n        second field.\n\n    estimate : array-like, shape = (n_samples, n_times)\n        Estimated risk of experiencing an event for test data at `times`.\n        The i-th column must contain the estimated probability of\n        remaining event-free up to the i-th time point.\n\n    times : array-like, shape = (n_times,)\n        The time points for which to estimate the Brier score.\n        Values must be within the range of follow-up times of\n        the test data `survival_test`.\n\n    Returns\n    -------\n    times : array, shape = (n_times,)\n        Unique time points at which the brier scores was estimated.\n\n    brier_scores : array , shape = (n_times,)\n        Values of the brier score.\n\n    Examples\n    --------\n    >>> from sksurv.datasets import load_gbsg2\n    >>> from sksurv.linear_model import CoxPHSurvivalAnalysis\n    >>> from sksurv.metrics import brier_score\n    >>> from sksurv.preprocessing import OneHotEncoder\n\n    Load and prepare data.\n\n    >>> X, y = load_gbsg2()\n    >>> X.loc[:, \"tgrade\"] = X.loc[:, \"tgrade\"].map(len).astype(int)\n    >>> Xt = OneHotEncoder().fit_transform(X)\n\n    Fit a Cox model.\n\n    >>> est = CoxPHSurvivalAnalysis(ties=\"efron\").fit(Xt, y)\n\n    Retrieve individual survival functions and get probability\n    of remaining event free up to 5 years (=1825 days).\n\n    >>> survs = est.predict_survival_function(Xt)\n    >>> preds = [fn(1825) for fn in survs]\n\n    Compute the Brier score at 5 years.\n\n    >>> times, score = brier_score(y, y, preds, 1825)\n    >>> print(score)\n    [0.20881843]\n\n    See also\n    --------\n    integrated_brier_score\n\n    References\n    ----------\n    .. [1] E. Graf, C. Schmoor, W. Sauerbrei, and M. Schumacher,\n           \"Assessment and comparison of prognostic classification schemes for survival data,\"\n           Statistics in Medicine, vol. 18, no. 17-18, pp. 2529–2545, 1999.\n    \"\"\"\n    test_event, test_time = check_y_survival(survival_test)\n    times = _check_times(test_time, times)\n\n    estimate = check_array(estimate, ensure_2d=False)\n    if estimate.ndim == 1 and times.shape[0] == 1:\n        estimate = estimate.reshape(-1, 1)\n\n    if estimate.shape[0] != test_time.shape[0]:\n        raise ValueError(\"expected estimate with {} samples, but got {}\".format(\n            test_time.shape[0], estimate.shape[0]\n        ))\n\n    if estimate.shape[1] != times.shape[0]:\n        raise ValueError(\"expected estimate with {} columns, but got {}\".format(\n            times.shape[0], estimate.shape[1]))\n\n    # fit IPCW estimator\n    cens = CensoringDistributionEstimator().fit(survival_train)\n    # calculate inverse probability of censoring weight at current time point t.\n    prob_cens_t = cens.predict_proba(times)\n    prob_cens_t[prob_cens_t == 0] = numpy.inf\n    # calculate inverse probability of censoring weights at observed time point\n    prob_cens_y = cens.predict_proba(test_time)\n    prob_cens_y[prob_cens_y == 0] = numpy.inf\n\n    # Calculating the brier scores at each time point\n    brier_scores = numpy.empty(times.shape[0], dtype=float)\n    for i, t in enumerate(times):\n        est = estimate[:, i]\n        is_case = (test_time <= t) & test_event\n        is_control = test_time > t\n\n        brier_scores[i] = numpy.mean(numpy.square(est) * is_case.astype(int) / prob_cens_y\n                                     + numpy.square(1.0 - est) * is_control.astype(int) / prob_cens_t[i])\n\n    return times, brier_scores\n\n\ndef integrated_brier_score(survival_train, survival_test, estimate, times):\n    \"\"\"The Integrated Brier Score (IBS) provides an overall calculation of\n    the model performance at all available times :math:`t_1 \\\\leq t \\\\leq t_\\\\text{max}`.\n\n    The integrated time-dependent Brier score over the interval\n    :math:`[t_1; t_\\\\text{max}]` is defined as\n\n    .. math::\n\n        \\\\mathrm{IBS} = \\\\int_{t_1}^{t_\\\\text{max}} \\\\mathrm{BS}^c(t) d w(t)\n\n    where the weighting function is :math:`w(t) = t / t_\\\\text{max}`.\n    The integral is estimated via the trapezoidal rule.\n\n    See [1]_ for further details.\n\n    Parameters\n    ----------\n    survival_train : structured array, shape = (n_train_samples,)\n        Survival times for training data to estimate the censoring\n        distribution from.\n        A structured array containing the binary event indicator\n        as first field, and time of event or time of censoring as\n        second field.\n\n    survival_test : structured array, shape = (n_samples,)\n        Survival times of test data.\n        A structured array containing the binary event indicator\n        as first field, and time of event or time of censoring as\n        second field.\n\n    estimate : array-like, shape = (n_samples, n_times)\n        Estimated risk of experiencing an event for test data at `times`.\n        The i-th column must contain the estimated probability of\n        remaining event-free up to the i-th time point.\n\n    times : array-like, shape = (n_times,)\n        The time points for which to estimate the Brier score.\n        Values must be within the range of follow-up times of\n        the test data `survival_test`.\n\n    Returns\n    -------\n    ibs : float\n        The integrated Brier score.\n\n    Examples\n    --------\n    >>> import numpy\n    >>> from sksurv.datasets import load_gbsg2\n    >>> from sksurv.linear_model import CoxPHSurvivalAnalysis\n    >>> from sksurv.metrics import integrated_brier_score\n    >>> from sksurv.preprocessing import OneHotEncoder\n\n    Load and prepare data.\n\n    >>> X, y = load_gbsg2()\n    >>> X.loc[:, \"tgrade\"] = X.loc[:, \"tgrade\"].map(len).astype(int)\n    >>> Xt = OneHotEncoder().fit_transform(X)\n\n    Fit a Cox model.\n\n    >>> est = CoxPHSurvivalAnalysis(ties=\"efron\").fit(Xt, y)\n\n    Retrieve individual survival functions and get probability\n    of remaining event free from 1 year to 5 years (=1825 days).\n\n    >>> survs = est.predict_survival_function(Xt)\n    >>> times = numpy.arange(365, 1826)\n    >>> preds = numpy.asarray([[fn(t) for t in times for fn in survs]])\n\n    Compute the integrated Brier score from 1 to 5 years.\n\n    >>> score = integrated_brier_score(y, y, preds, times)\n    >>> print(score)\n    0.1815853064627424\n\n    See also\n    --------\n    brier_score\n\n    References\n    ----------\n    .. [1] E. Graf, C. Schmoor, W. Sauerbrei, and M. Schumacher,\n           \"Assessment and comparison of prognostic classification schemes for survival data,\"\n           Statistics in Medicine, vol. 18, no. 17-18, pp. 2529–2545, 1999.\n    \"\"\"\n    # Computing the brier scores\n    times, brier_scores = brier_score(survival_train, survival_test, estimate, times)\n\n    if times.shape[0] < 2:\n        raise ValueError(\"At least two time points must be given\")\n\n    # Computing the IBS\n    ibs_value = trapz(brier_scores, times) / (times[-1] - times[0])\n\n    return ibs_value\n", "meta": {"hexsha": "396abd8d3ac77f4549c60192039b173a7ff97ba0", "size": 25843, "ext": "py", "lang": "Python", "max_stars_repo_path": "deep_cox_mixtures/dcm/skmetrics.py", "max_stars_repo_name": "chiragnagpal/google-research", "max_stars_repo_head_hexsha": "b9225e1eb6d83a2b9a69cd9b4b319129d0c68fc7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2021-01-19T15:38:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T09:25:15.000Z", "max_issues_repo_path": "deep_cox_mixtures/dcm/skmetrics.py", "max_issues_repo_name": "chiragnagpal/google-research", "max_issues_repo_head_hexsha": "b9225e1eb6d83a2b9a69cd9b4b319129d0c68fc7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-04-09T12:00:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-10T15:23:02.000Z", "max_forks_repo_path": "deep_cox_mixtures/dcm/skmetrics.py", "max_forks_repo_name": "chiragnagpal/google-research", "max_forks_repo_head_hexsha": "b9225e1eb6d83a2b9a69cd9b4b319129d0c68fc7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-12-09T06:41:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T18:01:52.000Z", "avg_line_length": 37.0243553009, "max_line_length": 120, "alphanum_fraction": 0.6627713501, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19997006613770815}}
{"text": "from collections import OrderedDict\n\nimport numpy as np\nimport pinocchio\nfrom numpy.linalg import inv\nfrom pinocchio.utils import zero\n\nfrom .activation import ActivationModelQuad\nfrom .cost import CostDataPinocchio, CostModelPinocchio, CostModelSum\nfrom .state import StatePinocchio\nfrom .utils import a2m\n\n\n# --------------------------------------------------------------------------\n# --------------------------------------------------------------------------\n# --------------------------------------------------------------------------\nclass ImpulseModelPinocchio:\n    def __init__(self, pinocchioModel, nimpulse):\n        assert (hasattr(self, 'ImpulseDataType'))\n        self.pinocchio = pinocchioModel\n        self.nq, self.nv = pinocchioModel.nq, pinocchioModel.nv\n        self.nx = self.nq + self.nv\n        self.ndx = 2 * self.nv\n        self.nimpulse = nimpulse\n\n    def createData(self, pinocchioData):\n        return self.ImpulseDataType(self, pinocchioData)\n\n    def calc(self, data, x):\n        assert (False and \"This should be defined in the derivative class.\")\n\n    def calcDiff(self, data, x, recalc=True):\n        assert (False and \"This should be defined in the derivative class.\")\n\n    def setForces(self, data, forcesArr, forcesVec=None):\n        '''\n        Convert a numpy array of forces into a stdVector of spatial forces.\n        If forcesVec is not none, sum the result in it. Otherwise, reset self.fs\n        and put the result there.\n        '''\n        assert (False and \"This should be defined in the derivative class.\")\n        return self.forces\n\n\nclass ImpulseDataPinocchio:\n    def __init__(self, model, pinocchioData):\n        nc, nv = model.nimpulse, model.nv\n        self.pinocchio = pinocchioData\n        self.J = np.zeros([nc, nv])\n        self.Jq = np.zeros([nc, nv])\n        self.f = np.nan  # not set at construction type\n        self.forces = pinocchio.StdVec_Force()\n        for i in range(model.pinocchio.njoints):\n            self.forces.append(pinocchio.Force.Zero())\n        self.Vq = np.zeros([nc, nv])\n\n\n# --------------------------------------------------------------------------\n\n\nclass ImpulseModel6D(ImpulseModelPinocchio):\n    def __init__(self, pinocchioModel, frame):\n        self.ImpulseDataType = ImpulseData6D\n        ImpulseModelPinocchio.__init__(self, pinocchioModel, nimpulse=6)\n        self.frame = frame\n\n    def calc(self, data, x):\n        # We suppose forwardKinematics(q,v,a), computeJointJacobian and updateFramePlacement already\n        # computed.\n        data.J[:, :] = pinocchio.getFrameJacobian(self.pinocchio, data.pinocchio, self.frame,\n                                                  pinocchio.ReferenceFrame.LOCAL)\n\n    def calcDiff(self, data, x, recalc=True):\n        if recalc:\n            self.calc(data, x)\n        dv_dq, dv_dv = pinocchio.getJointVelocityDerivatives(self.pinocchio, data.pinocchio, data.joint,\n                                                             pinocchio.ReferenceFrame.LOCAL)\n        data.Vq[:, :] = data.fXj * dv_dq\n\n    def setForces(self, data, forcesArr, forcesVec=None):\n        '''\n        Convert a numpy array of forces into a stdVector of spatial forces.\n        Side effect: keep the force values in data.\n        '''\n        # In the dynamic equation, we wrote M*a + J.T*fdyn, while in the ABA it would be\n        # M*a + b = tau + J.T faba, so faba = -fdyn (note the minus operator before a2m).\n        data.f = forcesArr\n        if forcesVec is None:\n            forcesVec = data.forces\n            data.forces[data.joint] *= 0\n        forcesVec[data.joint] += data.jMf * pinocchio.Force(a2m(forcesArr))\n        return forcesVec\n\n\nclass ImpulseData6D(ImpulseDataPinocchio):\n    def __init__(self, model, pinocchioData):\n        ImpulseDataPinocchio.__init__(self, model, pinocchioData)\n        frame = model.pinocchio.frames[model.frame]\n        self.joint = frame.parent\n        self.jMf = frame.placement\n        self.fXj = self.jMf.inverse().action\n\n\n# --------------------------------------------------------------------------\n\n\nclass ImpulseModel3D(ImpulseModelPinocchio):\n    def __init__(self, pinocchioModel, frame):\n        self.ImpulseDataType = ImpulseData3D\n        ImpulseModelPinocchio.__init__(self, pinocchioModel, nimpulse=3)\n        self.frame = frame\n\n    def calc(self, data, x):\n        # We suppose forwardKinematics(q,v,a), computeJointJacobian and updateFramePlacement already\n        # computed.\n        data.J[:, :] = pinocchio.getFrameJacobian(self.pinocchio, data.pinocchio, self.frame,\n                                                  pinocchio.ReferenceFrame.LOCAL)[:3, :]\n\n    def calcDiff(self, data, x, recalc=True):\n        if recalc:\n            self.calc(data, x)\n        dv_dq, dv_dv = pinocchio.getJointVelocityDerivatives(self.pinocchio, data.pinocchio, data.joint,\n                                                             pinocchio.ReferenceFrame.LOCAL)\n        data.Vq[:, :] = data.fXj[:3, :] * dv_dq\n\n    def setForces(self, data, forcesArr, forcesVec=None):\n        '''\n        Convert a numpy array of forces into a stdVector of spatial forces.\n        Side effect: keep the force values in data.\n        '''\n        # In the dynamic equation, we wrote M*a + J.T*fdyn, while in the ABA it would be\n        # M*a + b = tau + J.T faba, so faba = -fdyn (note the minus operator before a2m).\n        data.f = forcesArr\n        if forcesVec is None:\n            forcesVec = data.forces\n            data.forces[data.joint] *= 0\n        forcesVec[data.joint] += data.jMf * pinocchio.Force(a2m(forcesArr), np.zeros((3, 1)))\n        return forcesVec\n\n\nclass ImpulseData3D(ImpulseDataPinocchio):\n    def __init__(self, model, pinocchioData):\n        ImpulseDataPinocchio.__init__(self, model, pinocchioData)\n        frame = model.pinocchio.frames[model.frame]\n        self.joint = frame.parent\n        self.jMf = frame.placement\n        self.fXj = self.jMf.inverse().action\n\n\n# --------------------------------------------------------------------------\n\n\nclass ImpulseModelMultiple(ImpulseModelPinocchio):\n    def __init__(self, pinocchioModel, impulses={}):\n        self.ImpulseDataType = ImpulseDataMultiple\n        ImpulseModelPinocchio.__init__(self, pinocchioModel, nimpulse=0)\n        self.impulses = OrderedDict()\n        for n, i in impulses.items():\n            self.addImpulse(name=n, impulse=i)\n\n    def addImpulse(self, name, impulse):\n        self.impulses.update([[name, impulse]])\n        self.nimpulse += impulse.nimpulse\n\n    def __getitem__(self, key):\n        if isinstance(key, str):\n            return self.impulses[key]\n        elif isinstance(key, ImpulseModelPinocchio):\n            filter = [v for k, v in self.impulses.items() if v.impulse == key]\n            assert (len(filter) == 1 and \"The given key is not or not unique in the impulse dict. \")\n            return filter[0]\n        else:\n            raise (KeyError(\"The key should be string or impulsemodel.\"))\n\n    def calc(self, data, x):\n        npast = 0\n        for m, d in zip(self.impulses.values(), data.impulses.values()):\n            m.calc(d, x)\n            data.J[npast:npast + m.nimpulse, :] = d.J\n            npast += m.nimpulse\n\n    def calcDiff(self, data, x, recalc=True):\n        if recalc:\n            self.calc(data, x)\n        npast = 0\n        for m, d in zip(self.impulses.values(), data.impulses.values()):\n            m.calcDiff(d, x, recalc=False)\n            data.Vq[npast:npast + m.nimpulse, :] = d.Vq\n            npast += m.nimpulse\n\n    def setForces(self, data, fsArr):\n        npast = 0\n        for i, f in enumerate(data.forces):\n            data.forces[i] *= 0\n        for m, d in zip(self.impulses.values(), data.impulses.values()):\n            m.setForces(d, fsArr[npast:npast + m.nimpulse], data.forces)\n            npast += m.nimpulse\n        return data.forces\n\n\nclass ImpulseDataMultiple(ImpulseDataPinocchio):\n    def __init__(self, model, pinocchioData):\n        ImpulseDataPinocchio.__init__(self, model, pinocchioData)\n        self.model = model\n        self.impulses = OrderedDict([[k, m.createData(pinocchioData)] for k, m in model.impulses.items()])\n\n    def __getitem__(self, key):\n        if isinstance(key, str):\n            return self.impulses[key]\n        elif isinstance(key, ImpulseModelPinocchio):\n            filter = [k for k, v in self.model.impulses.items() if v == key]\n            assert (len(filter) == 1 and \"The given key is not or not unique in the impulse dict. \")\n            return self.impulses[filter[0]]\n        else:\n            raise (KeyError(\"The key should be string or impulsemodel.\"))\n\n\nclass CostModelImpactBase(CostModelPinocchio):\n    def __init__(self, pinocchioModel, ncost):\n        CostModelPinocchio.__init__(self, pinocchioModel, ncost=ncost, nu=0)\n\n    def setImpactData(self, data, vnext):\n        data.vnext = vnext\n\n    def setImpactDiffData(self, data, dvnext_dx):\n        data.dvnext_dx = dvnext_dx\n\n    def assertImpactDataSet(self, data):\n        assert (data.vnext is not None and \"vnext should be copied first from impact-data. Call setImpactData first\")\n\n    def assertImpactDiffDataSet(self, data):\n        assert (data.dvnext_dx is not None and \"\"\"\n        dvnext_dx should be copied first from impact-data. Call setImpactData first\"\"\")\n\n\nclass CostDataImpactBase(CostDataPinocchio):\n    def __init__(self, model, pinocchioData):\n        CostDataPinocchio.__init__(self, model, pinocchioData)\n        # These two fields must be informed by ImpactData.\n        self.vnext = None\n        self.dvnext_dx = None\n\n\n# --------------------------------------------------------------------------\nclass CostModelImpactWholeBody(CostModelImpactBase):\n    '''\n    Penalize the impact on the whole body, i.e. the sum-of-square of ||vnext-v||\n    with vnext the velocity after impact and v the velocity before impact.\n    '''\n    def __init__(self, pinocchioModel, activation=None):\n        self.CostDataType = CostDataImpactWholeBody\n        CostModelImpactBase.__init__(self, pinocchioModel, ncost=pinocchioModel.nv)\n        self.activation = activation if activation is not None else ActivationModelQuad()\n\n    def calc(self, data, x, u=None):\n        self.assertImpactDataSet(data)\n        nv = self.pinocchio.nv\n        data.residuals[:] = data.vnext - x[-nv:]\n        data.cost = sum(self.activation.calc(data.activation, data.residuals))\n        return data.cost\n\n    def calcDiff(self, data, x, u=None, recalc=True):\n        if recalc:\n            self.calc(data, x, u)\n        self.assertImpactDiffDataSet(data)\n        nv = self.pinocchio.nv\n        Ax, Axx = self.activation.calcDiff(data.activation, data.residuals)\n        data.Rx[:, :] = data.dvnext_dx\n        data.Rx[range(nv), range(nv, 2 * nv)] -= 1\n        data.Lx[:] = np.dot(data.Rx.T, Ax)\n        data.Lxx[:, :] = np.dot(data.Rx.T, Axx * data.Rx)\n\n\nclass CostDataImpactWholeBody(CostDataImpactBase):\n    def __init__(self, model, pinocchioData):\n        CostDataImpactBase.__init__(self, model, pinocchioData)\n        self.activation = model.activation.createData()\n        self.Lu = 0\n        self.Lxu = 0\n        self.Luu = 0\n        self.Ru = 0\n\n\n# --------------------------------------------------------------------------\nclass CostModelImpactCoM(CostModelImpactBase):\n    '''\n    Penalize the impact on the com, i.e. the sum-of-square of ||Jcom*(vnext-v)||\n    with vnext the velocity after impact and v the velocity before impact.\n    '''\n    def __init__(self, pinocchioModel, activation=None):\n        self.CostDataType = CostDataImpactCoM\n        CostModelImpactBase.__init__(self, pinocchioModel, ncost=3)\n        self.activation = activation if activation is not None else ActivationModelQuad()\n\n    def calc(self, data, x, u=None):\n        self.assertImpactDataSet(data)\n        nq, nv = self.pinocchio.nq, self.pinocchio.nv\n        pinocchio.centerOfMass(self.pinocchio, data.pinocchio_dv, a2m(x[:nq]), a2m(data.vnext - x[-nv:]))\n        data.residuals[:] = data.pinocchio_dv.vcom[0].flat\n        data.cost = sum(self.activation.calc(data.activation, data.residuals))\n        return data.cost\n\n    def calcDiff(self, data, x, u=None, recalc=True):\n        if recalc:\n            self.calc(data, x, u)\n        self.assertImpactDiffDataSet(data)\n        nv = self.pinocchio.nv\n        Ax, Axx = self.activation.calcDiff(data.activation, data.residuals)\n\n        # TODO ???\n        # r = Jcom(vnext-v)\n        # dr/dv = Jcom*(dvnext/dv - I)\n        # dr/dq = dJcom_dq*(vnext-v)   + Jcom*dvnext_dq\n        #       = dvcom_dq(vq=vnext-v) + Jcom*dvnext_dq\n        # Jcom*v = M[:3,:]/mass * v = RNEA(q,0,v)[:3]/mass\n        # => dvcom/dq = dRNEA_dq(q,0,v)[:3,:]/mass\n\n        dvc_dq = pinocchio.getCenterOfMassVelocityDerivatives(self.pinocchio, data.pinocchio_dv)\n        dvc_dv = pinocchio.jacobianCenterOfMass(self.pinocchio, data.pinocchio_dv)\n\n        # res = vcom(q,vnext-v)\n        # dres/dq = dvcom_dq + dvcom_dv*dvnext_dq\n        data.Rx[:, :nv] = dvc_dq + np.dot(dvc_dv, data.dvnext_dx[:, :nv])\n\n        # dres/dv = dvcom_dv*(dvnext_dv-I)\n        ddv_dv = data.dvnext_dx[:, nv:].copy()\n        ddv_dv[range(nv), range(nv)] -= 1\n        data.Rx[:, nv:] = np.dot(dvc_dv, ddv_dv)\n\n        data.Lx[:] = np.dot(data.Rx.T, Ax)\n        data.Lxx[:, :] = np.dot(data.Rx.T, Axx * data.Rx)\n\n\nclass CostDataImpactCoM(CostDataImpactBase):\n    def __init__(self, model, pinocchioData):\n        CostDataImpactBase.__init__(self, model, pinocchioData)\n        self.activation = model.activation.createData()\n        # Those data are ment to be evaluated at v=vnext-v\n        self.pinocchio_dv = model.pinocchio.createData()\n        self.Lu = 0\n        self.Lxu = 0\n        self.Luu = 0\n        self.Ru = 0\n\n\n# --------------------------------------------------------------------------\n# --------------------------------------------------------------------------\n# --------------------------------------------------------------------------\n\n\nclass ActionModelImpact:\n    def __init__(self, pinocchioModel, impulseModel, costModel):\n        self.pinocchio = pinocchioModel\n        self.State = StatePinocchio(self.pinocchio)\n        self.impulse = impulseModel\n        self.nq, self.nv = self.pinocchio.nq, self.pinocchio.nv\n        self.nx = self.State.nx\n        self.ndx = self.State.ndx\n        self.nout = self.nx\n        self.nu = 0\n        self.unone = np.zeros(self.nu)\n        self.costs = costModel\n        self.impulseWeight = 100.\n\n    @property\n    def nimpulse(self):\n        return self.impulse.nimpulse\n\n    @property\n    def ncost(self):\n        return self.costs.ncost\n\n    def createData(self):\n        return ActionDataImpact(self)\n\n    def calc(self, data, x, u=None):\n        '''\n        M(vnext-v) - J^T f = 0\n        J vnext = 0\n\n        [MJ^T][vnext] = [Mv]\n        [J   ][ -f   ]   [0 ]\n\n        [vnext] = K^-1[Mv], with K = [MJ^T;J0]\n        [ -f   ]       [0 ]\n        '''\n        nq, nv = self.nq, self.nv\n        q = a2m(x[:nq])\n        v = a2m(x[-nv:])\n\n        pinocchio.computeAllTerms(self.pinocchio, data.pinocchio, q, v)\n        pinocchio.updateFramePlacements(self.pinocchio, data.pinocchio)\n\n        self.impulse.calc(data.impulse, x)\n\n        data.K[:nv, :nv] = data.pinocchio.M\n        if hasattr(self.pinocchio, 'armature'):\n            data.K[range(nv), range(nv)] += self.pinocchio.armature.flat\n        data.K[nv:, :nv] = data.impulse.J\n        data.K.T[nv:, :nv] = data.impulse.J\n        data.Kinv = inv(data.K)\n        data.r[:nv] = (data.K[:nv, :nv] * v).flat\n        data.r[nv:] = 0\n\n        data.af[:] = np.dot(data.Kinv, data.r)\n        data.f[:] *= -1.\n        # Convert force array to vector of spatial forces.\n        self.impulse.setForces(data.impulse, data.f)\n\n        data.xnext[:nq] = q.flat\n        data.xnext[nq:] = data.vnext\n\n        if isinstance(self.costs, CostModelImpactBase):\n            self.costs.setImpactData(data.costs, data.vnext)\n        if isinstance(self.costs, CostModelSum):\n            for cmodel, cdata in zip(self.costs.costs.values(), data.costs.costs.values()):\n                if isinstance(cmodel.cost, CostModelImpactBase):\n                    cmodel.cost.setImpactData(cdata, data.vnext)\n\n        data.cost = self.costs.calc(data.costs, x, u=None)\n        return data.xnext, data.cost\n\n    def calcDiff(self, data, x, u=None, recalc=True):\n        '''\n        k = [Mv;0]; K = [MJ^T;J0]\n        r = [vnext;f] = K^-1 k\n        dr/dv = K^-1 [M;0]\n        dr/dq = -K^-1 K'K^-1 k + K^-1 k' = -K^-1 (K'r-k')\n              = -K^-1 [ M'vnext + J'^T f- M'v ]\n                      [ J'vnext               ]\n              = -K^-1 [ M'(vnext-v) + J'^T f ]\n                      [ J' vnext             ]\n        '''\n        if recalc:\n            xout, cost = self.calc(data, x, u)\n        nq, nv = self.nq, self.nv\n        q = a2m(x[:nq])\n        v = a2m(x[-nv:])\n        vnext = a2m(data.vnext)\n        fs = data.impulse.forces\n\n        # Derivative M' dv + J'f + b'\n        g6bak = self.pinocchio.gravity.copy()\n        self.pinocchio.gravity = pinocchio.Motion.Zero()\n        pinocchio.computeRNEADerivatives(self.pinocchio, data.pinocchio, q, zero(nv), vnext - v, fs)\n        self.pinocchio.gravity = g6bak\n        data.did_dq[:, :] = data.pinocchio.dtau_dq\n\n        # Derivative of the impulse constraint\n        pinocchio.computeForwardKinematicsDerivatives(self.pinocchio, data.pinocchio, q, vnext, zero(nv))\n        # pinocchio.updateFramePlacements(self.pinocchio,data.pinocchio)\n        self.impulse.calcDiff(data.impulse, x, recalc=False)\n        data.dv_dq = data.impulse.Vq\n\n        data.Fq[:nv, :] = 0\n        np.fill_diagonal(data.Fq[:nv, :], 1)  # dq/dq\n        data.Fv[:nv, :] = 0  # dq/dv\n        data.Fx[nv:, :nv] = -np.dot(data.Kinv[:nv, :], np.vstack([data.did_dq, data.dv_dq]))  # dvnext/dq\n        data.Fx[nv:, nv:] = np.dot(data.Kinv[:nv, :nv], data.K[:nv, :nv])  # dvnext/dv\n\n        # data.Rx[:,:] = 0\n        # np.fill_diagonal(data.Rv,-1)\n        # data.Rx[:,:] += data.Fx[nv:,:]\n        # data.Rx *= self.impulseWeight\n        # data.Lx [:]   = np.dot(data.Rx.T,data.costResiduals)\n        # data.Lxx[:,:] = np.dot(data.Rx.T,data.Rx)\n\n        if isinstance(self.costs, CostModelImpactBase):\n            self.costs.setImpactDiffData(data.costs, data.Fx[nv:, :])\n        if isinstance(self.costs, CostModelSum):\n            for cmodel, cdata in zip(self.costs.costs.values(), data.costs.costs.values()):\n                if isinstance(cmodel.cost, CostModelImpactBase):\n                    cmodel.cost.setImpactDiffData(cdata, data.Fx[nv:, :])\n\n        self.costs.calcDiff(data.costs, x, u=None, recalc=recalc)\n\n        return data.xnext, data.cost\n\n\nclass ActionDataImpact:\n    def __init__(self, model):\n        self.pinocchio = model.pinocchio.createData()\n        self.impulse = model.impulse.createData(self.pinocchio)\n        if model.costs is not None:\n            self.costs = model.costs.createData(self.pinocchio)\n        self.cost = np.nan\n        nx, nu, ndx, nv, nc = model.nx, model.nu, model.State.ndx, model.nv, model.nimpulse\n        self.F = np.zeros([ndx, ndx + nu])\n        self.Fx = self.F[:, :ndx]\n        self.Fu = self.F[:, ndx:]\n        self.Fq = self.Fx[:, :nv]\n        self.Fv = self.Fx[:, nv:]\n        self.Fq[:, :] = 0\n        np.fill_diagonal(self.Fq, 1)\n\n        self.costResiduals = np.zeros(nv)\n        self.Rx = np.zeros([nv, ndx])\n        self.Rq = self.Rx[:, :nv]\n        self.Rv = self.Rx[:, nv:]\n\n        self.costResiduals = self.costs.residuals\n        self.Lx = self.costs.Lx\n        self.Lu = self.costs.Lu\n        self.Lxx = self.costs.Lxx\n        self.Lxu = self.costs.Lxu\n        self.Luu = self.costs.Luu\n        self.Rx = self.costs.Rx\n        self.Ru = self.costs.Ru\n\n        self.K = np.zeros([nv + nc, nv + nc])  # KKT matrix = [ MJ.T ; J0 ]\n        self.r = np.zeros(nv + nc)  # NLE effects =  [ tau-b ; -gamma ]\n        self.af = np.zeros(nv + nc)  # acceleration&forces = [ a ; f ]\n        self.vnext = self.af[:nv]\n        self.f = self.af[nv:]\n        self.did_dq = np.zeros([nv, nv])\n\n        self.xnext = np.zeros(nx)\n", "meta": {"hexsha": "50950c32e80e56efdd5ab12c56934021ab9426fe", "size": 20088, "ext": "py", "lang": "Python", "max_stars_repo_path": "unittest/python/crocoddyl/impact.py", "max_stars_repo_name": "pFernbach/crocoddyl", "max_stars_repo_head_hexsha": "cbf81a329e3abaf4ce1b4a8fab1431f93cd9a5c8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-23T12:57:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T16:27:14.000Z", "max_issues_repo_path": "unittest/python/crocoddyl/impact.py", "max_issues_repo_name": "pFernbach/crocoddyl", "max_issues_repo_head_hexsha": "cbf81a329e3abaf4ce1b4a8fab1431f93cd9a5c8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittest/python/crocoddyl/impact.py", "max_forks_repo_name": "pFernbach/crocoddyl", "max_forks_repo_head_hexsha": "cbf81a329e3abaf4ce1b4a8fab1431f93cd9a5c8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-26T14:31:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T14:31:17.000Z", "avg_line_length": 38.7799227799, "max_line_length": 117, "alphanum_fraction": 0.5803962565, "include": true, "reason": "import numpy,from numpy", "num_tokens": 5474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19997006613770815}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nMulti-lib backend for POT\n\nThe goal is to write backend-agnostic code. Whether you're using Numpy, PyTorch,\nor Jax, POT code should work nonetheless.\nTo achieve that, POT provides backend classes which implements functions in their respective backend\nimitating Numpy API. As a convention, we use nx instead of np to refer to the backend.\n\nExamples\n--------\n\n>>> from ot.utils import list_to_array\n>>> from ot.backend import get_backend\n>>> def f(a, b):  # the function does not know which backend to use\n...     a, b = list_to_array(a, b)  # if a list in given, make it an array\n...     nx = get_backend(a, b)  # infer the backend from the arguments\n...     c = nx.dot(a, b)  # now use the backend to do any calculation\n...     return c\n\"\"\"\n\n# Author: Remi Flamary <remi.flamary@polytechnique.edu>\n#         Nicolas Courty <ncourty@irisa.fr>\n#\n# License: MIT License\n\nimport numpy as np\nimport scipy.special as scipy\nfrom scipy.sparse import issparse, coo_matrix, csr_matrix\n\ntry:\n    import torch\n    torch_type = torch.Tensor\nexcept ImportError:\n    torch = False\n    torch_type = float\n\ntry:\n    import jax\n    import jax.numpy as jnp\n    import jax.scipy.special as jscipy\n    jax_type = jax.numpy.ndarray\nexcept ImportError:\n    jax = False\n    jax_type = float\n\nstr_type_error = \"All array should be from the same type/backend. Current types are : {}\"\n\n\ndef get_backend_list():\n    \"\"\"Returns the list of available backends\"\"\"\n    lst = [NumpyBackend(), ]\n\n    if torch:\n        lst.append(TorchBackend())\n\n    if jax:\n        lst.append(JaxBackend())\n\n    return lst\n\n\ndef get_backend(*args):\n    \"\"\"Returns the proper backend for a list of input arrays\n\n        Also raises TypeError if all arrays are not from the same backend\n    \"\"\"\n    # check that some arrays given\n    if not len(args) > 0:\n        raise ValueError(\" The function takes at least one parameter\")\n    # check all same type\n    if not len(set(type(a) for a in args)) == 1:\n        raise ValueError(str_type_error.format([type(a) for a in args]))\n\n    if isinstance(args[0], np.ndarray):\n        return NumpyBackend()\n    elif isinstance(args[0], torch_type):\n        return TorchBackend()\n    elif isinstance(args[0], jax_type):\n        return JaxBackend()\n    else:\n        raise ValueError(\"Unknown type of non implemented backend.\")\n\n\ndef to_numpy(*args):\n    \"\"\"Returns numpy arrays from any compatible backend\"\"\"\n\n    if len(args) == 1:\n        return get_backend(args[0]).to_numpy(args[0])\n    else:\n        return [get_backend(a).to_numpy(a) for a in args]\n\n\nclass Backend():\n    \"\"\"\n    Backend abstract class.\n    Implementations: :py:class:`JaxBackend`, :py:class:`NumpyBackend`, :py:class:`TorchBackend`\n\n    - The `__name__` class attribute refers to the name of the backend.\n    - The `__type__` class attribute refers to the data structure used by the backend.\n    \"\"\"\n\n    __name__ = None\n    __type__ = None\n    __type_list__ = None\n\n    rng_ = None\n\n    def __str__(self):\n        return self.__name__\n\n    # convert to numpy\n    def to_numpy(self, a):\n        \"\"\"Returns the numpy version of a tensor\"\"\"\n        raise NotImplementedError()\n\n    # convert from numpy\n    def from_numpy(self, a, type_as=None):\n        \"\"\"Creates a tensor cloning a numpy array, with the given precision (defaulting to input's precision) and the given device (in case of GPUs)\"\"\"\n        raise NotImplementedError()\n\n    def set_gradients(self, val, inputs, grads):\n        \"\"\"Define the gradients for the value val wrt the inputs \"\"\"\n        raise NotImplementedError()\n\n    def zeros(self, shape, type_as=None):\n        r\"\"\"\n        Creates a tensor full of zeros.\n\n        This function follows the api from :any:`numpy.zeros`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.zeros.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def ones(self, shape, type_as=None):\n        r\"\"\"\n        Creates a tensor full of ones.\n\n        This function follows the api from :any:`numpy.ones`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.ones.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def arange(self, stop, start=0, step=1, type_as=None):\n        r\"\"\"\n        Returns evenly spaced values within a given interval.\n\n        This function follows the api from :any:`numpy.arange`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.arange.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def full(self, shape, fill_value, type_as=None):\n        r\"\"\"\n        Creates a tensor with given shape, filled with given value.\n\n        This function follows the api from :any:`numpy.full`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.full.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def eye(self, N, M=None, type_as=None):\n        r\"\"\"\n        Creates the identity matrix of given size.\n\n        This function follows the api from :any:`numpy.eye`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.eye.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def sum(self, a, axis=None, keepdims=False):\n        r\"\"\"\n        Sums tensor elements over given dimensions.\n\n        This function follows the api from :any:`numpy.sum`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.sum.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def cumsum(self, a, axis=None):\n        r\"\"\"\n        Returns the cumulative sum of tensor elements over given dimensions.\n\n        This function follows the api from :any:`numpy.cumsum`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.cumsum.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def max(self, a, axis=None, keepdims=False):\n        r\"\"\"\n        Returns the maximum of an array or maximum along given dimensions.\n\n        This function follows the api from :any:`numpy.amax`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.amax.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def min(self, a, axis=None, keepdims=False):\n        r\"\"\"\n        Returns the maximum of an array or maximum along given dimensions.\n\n        This function follows the api from :any:`numpy.amin`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.amin.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def maximum(self, a, b):\n        r\"\"\"\n        Returns element-wise maximum of array elements.\n\n        This function follows the api from :any:`numpy.maximum`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.maximum.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def minimum(self, a, b):\n        r\"\"\"\n        Returns element-wise minimum of array elements.\n\n        This function follows the api from :any:`numpy.minimum`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.minimum.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def dot(self, a, b):\n        r\"\"\"\n        Returns the dot product of two tensors.\n\n        This function follows the api from :any:`numpy.dot`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.dot.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def abs(self, a):\n        r\"\"\"\n        Computes the absolute value element-wise.\n\n        This function follows the api from :any:`numpy.absolute`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.absolute.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def exp(self, a):\n        r\"\"\"\n        Computes the exponential value element-wise.\n\n        This function follows the api from :any:`numpy.exp`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.exp.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def log(self, a):\n        r\"\"\"\n        Computes the natural logarithm, element-wise.\n\n        This function follows the api from :any:`numpy.log`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.log.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def sqrt(self, a):\n        r\"\"\"\n        Returns the non-ngeative square root of a tensor, element-wise.\n\n        This function follows the api from :any:`numpy.sqrt`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.sqrt.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def power(self, a, exponents):\n        r\"\"\"\n        First tensor elements raised to powers from second tensor, element-wise.\n\n        This function follows the api from :any:`numpy.power`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.power.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def norm(self, a):\n        r\"\"\"\n        Computes the matrix frobenius norm.\n\n        This function follows the api from :any:`numpy.linalg.norm`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.linalg.norm.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def any(self, a):\n        r\"\"\"\n        Tests whether any tensor element along given dimensions evaluates to True.\n\n        This function follows the api from :any:`numpy.any`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.any.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def isnan(self, a):\n        r\"\"\"\n        Tests element-wise for NaN and returns result as a boolean tensor.\n\n        This function follows the api from :any:`numpy.isnan`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.isnan.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def isinf(self, a):\n        r\"\"\"\n        Tests element-wise for positive or negative infinity and returns result as a boolean tensor.\n\n        This function follows the api from :any:`numpy.isinf`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.isinf.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def einsum(self, subscripts, *operands):\n        r\"\"\"\n        Evaluates the Einstein summation convention on the operands.\n\n        This function follows the api from :any:`numpy.einsum`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.einsum.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def sort(self, a, axis=-1):\n        r\"\"\"\n        Returns a sorted copy of a tensor.\n\n        This function follows the api from :any:`numpy.sort`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.sort.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def argsort(self, a, axis=None):\n        r\"\"\"\n        Returns the indices that would sort a tensor.\n\n        This function follows the api from :any:`numpy.argsort`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.argsort.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def searchsorted(self, a, v, side='left'):\n        r\"\"\"\n        Finds indices where elements should be inserted to maintain order in given tensor.\n\n        This function follows the api from :any:`numpy.searchsorted`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.searchsorted.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def flip(self, a, axis=None):\n        r\"\"\"\n        Reverses the order of elements in a tensor along given dimensions.\n\n        This function follows the api from :any:`numpy.flip`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.flip.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def clip(self, a, a_min, a_max):\n        \"\"\"\n        Limits the values in a tensor.\n\n        This function follows the api from :any:`numpy.clip`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.clip.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def repeat(self, a, repeats, axis=None):\n        r\"\"\"\n        Repeats elements of a tensor.\n\n        This function follows the api from :any:`numpy.repeat`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.repeat.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def take_along_axis(self, arr, indices, axis):\n        r\"\"\"\n        Gathers elements of a tensor along given dimensions.\n\n        This function follows the api from :any:`numpy.take_along_axis`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.take_along_axis.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def concatenate(self, arrays, axis=0):\n        r\"\"\"\n        Joins a sequence of tensors along an existing dimension.\n\n        This function follows the api from :any:`numpy.concatenate`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def zero_pad(self, a, pad_width):\n        r\"\"\"\n        Pads a tensor.\n\n        This function follows the api from :any:`numpy.pad`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.pad.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def argmax(self, a, axis=None):\n        r\"\"\"\n        Returns the indices of the maximum values of a tensor along given dimensions.\n\n        This function follows the api from :any:`numpy.argmax`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.argmax.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def mean(self, a, axis=None):\n        r\"\"\"\n        Computes the arithmetic mean of a tensor along given dimensions.\n\n        This function follows the api from :any:`numpy.mean`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.mean.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def std(self, a, axis=None):\n        r\"\"\"\n        Computes the standard deviation of a tensor along given dimensions.\n\n        This function follows the api from :any:`numpy.std`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.std.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def linspace(self, start, stop, num):\n        r\"\"\"\n        Returns a specified number of evenly spaced values over a given interval.\n\n        This function follows the api from :any:`numpy.linspace`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.linspace.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def meshgrid(self, a, b):\n        r\"\"\"\n        Returns coordinate matrices from coordinate vectors (Numpy convention).\n\n        This function follows the api from :any:`numpy.meshgrid`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.meshgrid.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def diag(self, a, k=0):\n        r\"\"\"\n        Extracts or constructs a diagonal tensor.\n\n        This function follows the api from :any:`numpy.diag`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.diag.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def unique(self, a):\n        r\"\"\"\n        Finds unique elements of given tensor.\n\n        This function follows the api from :any:`numpy.unique`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.unique.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def logsumexp(self, a, axis=None):\n        r\"\"\"\n        Computes the log of the sum of exponentials of input elements.\n\n        This function follows the api from :any:`scipy.special.logsumexp`\n\n        See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.logsumexp.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def stack(self, arrays, axis=0):\n        r\"\"\"\n        Joins a sequence of tensors along a new dimension.\n\n        This function follows the api from :any:`numpy.stack`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.stack.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def outer(self, a, b):\n        r\"\"\"\n        Computes the outer product between two vectors.\n\n        This function follows the api from :any:`numpy.outer`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.outer.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def reshape(self, a, shape):\n        r\"\"\"\n        Gives a new shape to a tensor without changing its data.\n\n        This function follows the api from :any:`numpy.reshape`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.reshape.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def seed(self, seed=None):\n        r\"\"\"\n        Sets the seed for the random generator.\n\n        This function follows the api from :any:`numpy.random.seed`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.random.seed.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def rand(self, *size, type_as=None):\n        r\"\"\"\n        Generate uniform random numbers.\n\n        This function follows the api from :any:`numpy.random.rand`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.random.rand.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def randn(self, *size, type_as=None):\n        r\"\"\"\n        Generate normal Gaussian random numbers.\n\n        This function follows the api from :any:`numpy.random.rand`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.random.rand.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def coo_matrix(self, data, rows, cols, shape=None, type_as=None):\n        r\"\"\"\n        Creates a sparse tensor in COOrdinate format.\n\n        This function follows the api from :any:`scipy.sparse.coo_matrix`\n\n        See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.coo_matrix.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def issparse(self, a):\n        r\"\"\"\n        Checks whether or not the input tensor is a sparse tensor.\n\n        This function follows the api from :any:`scipy.sparse.issparse`\n\n        See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.issparse.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def tocsr(self, a):\n        r\"\"\"\n        Converts this matrix to Compressed Sparse Row format.\n\n        This function follows the api from :any:`scipy.sparse.coo_matrix.tocsr`\n\n        See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.coo_matrix.tocsr.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def eliminate_zeros(self, a, threshold=0.):\n        r\"\"\"\n        Removes entries smaller than the given threshold from the sparse tensor.\n\n        This function follows the api from :any:`scipy.sparse.csr_matrix.eliminate_zeros`\n\n        See: https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.sparse.csr_matrix.eliminate_zeros.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def todense(self, a):\n        r\"\"\"\n        Converts a sparse tensor to a dense tensor.\n\n        This function follows the api from :any:`scipy.sparse.csr_matrix.toarray`\n\n        See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.toarray.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def where(self, condition, x, y):\n        r\"\"\"\n        Returns elements chosen from x or y depending on condition.\n\n        This function follows the api from :any:`numpy.where`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.where.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def copy(self, a):\n        r\"\"\"\n        Returns a copy of the given tensor.\n\n        This function follows the api from :any:`numpy.copy`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.copy.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def allclose(self, a, b, rtol=1e-05, atol=1e-08, equal_nan=False):\n        r\"\"\"\n        Returns True if two arrays are element-wise equal within a tolerance.\n\n        This function follows the api from :any:`numpy.allclose`\n\n        See: https://numpy.org/doc/stable/reference/generated/numpy.allclose.html\n        \"\"\"\n        raise NotImplementedError()\n\n    def dtype_device(self, a):\n        r\"\"\"\n        Returns the dtype and the device of the given tensor.\n        \"\"\"\n        raise NotImplementedError()\n\n    def assert_same_dtype_device(self, a, b):\n        r\"\"\"\n        Checks whether or not the two given inputs have the same dtype as well as the same device\n        \"\"\"\n        raise NotImplementedError()\n\n\nclass NumpyBackend(Backend):\n    \"\"\"\n    NumPy implementation of the backend\n\n    - `__name__` is \"numpy\"\n    - `__type__` is np.ndarray\n    \"\"\"\n\n    __name__ = 'numpy'\n    __type__ = np.ndarray\n    __type_list__ = [np.array(1, dtype=np.float32),\n                     np.array(1, dtype=np.float64)]\n\n    rng_ = np.random.RandomState()\n\n    def to_numpy(self, a):\n        return a\n\n    def from_numpy(self, a, type_as=None):\n        if type_as is None:\n            return a\n        elif isinstance(a, float):\n            return a\n        else:\n            return a.astype(type_as.dtype)\n\n    def set_gradients(self, val, inputs, grads):\n        # No gradients for numpy\n        return val\n\n    def zeros(self, shape, type_as=None):\n        if type_as is None:\n            return np.zeros(shape)\n        else:\n            return np.zeros(shape, dtype=type_as.dtype)\n\n    def ones(self, shape, type_as=None):\n        if type_as is None:\n            return np.ones(shape)\n        else:\n            return np.ones(shape, dtype=type_as.dtype)\n\n    def arange(self, stop, start=0, step=1, type_as=None):\n        return np.arange(start, stop, step)\n\n    def full(self, shape, fill_value, type_as=None):\n        if type_as is None:\n            return np.full(shape, fill_value)\n        else:\n            return np.full(shape, fill_value, dtype=type_as.dtype)\n\n    def eye(self, N, M=None, type_as=None):\n        if type_as is None:\n            return np.eye(N, M)\n        else:\n            return np.eye(N, M, dtype=type_as.dtype)\n\n    def sum(self, a, axis=None, keepdims=False):\n        return np.sum(a, axis, keepdims=keepdims)\n\n    def cumsum(self, a, axis=None):\n        return np.cumsum(a, axis)\n\n    def max(self, a, axis=None, keepdims=False):\n        return np.max(a, axis, keepdims=keepdims)\n\n    def min(self, a, axis=None, keepdims=False):\n        return np.min(a, axis, keepdims=keepdims)\n\n    def maximum(self, a, b):\n        return np.maximum(a, b)\n\n    def minimum(self, a, b):\n        return np.minimum(a, b)\n\n    def dot(self, a, b):\n        return np.dot(a, b)\n\n    def abs(self, a):\n        return np.abs(a)\n\n    def exp(self, a):\n        return np.exp(a)\n\n    def log(self, a):\n        return np.log(a)\n\n    def sqrt(self, a):\n        return np.sqrt(a)\n\n    def power(self, a, exponents):\n        return np.power(a, exponents)\n\n    def norm(self, a):\n        return np.sqrt(np.sum(np.square(a)))\n\n    def any(self, a):\n        return np.any(a)\n\n    def isnan(self, a):\n        return np.isnan(a)\n\n    def isinf(self, a):\n        return np.isinf(a)\n\n    def einsum(self, subscripts, *operands):\n        return np.einsum(subscripts, *operands)\n\n    def sort(self, a, axis=-1):\n        return np.sort(a, axis)\n\n    def argsort(self, a, axis=-1):\n        return np.argsort(a, axis)\n\n    def searchsorted(self, a, v, side='left'):\n        if a.ndim == 1:\n            return np.searchsorted(a, v, side)\n        else:\n            # this is a not very efficient way to make numpy\n            # searchsorted work on 2d arrays\n            ret = np.empty(v.shape, dtype=int)\n            for i in range(a.shape[0]):\n                ret[i, :] = np.searchsorted(a[i, :], v[i, :], side)\n            return ret\n\n    def flip(self, a, axis=None):\n        return np.flip(a, axis)\n\n    def outer(self, a, b):\n        return np.outer(a, b)\n\n    def clip(self, a, a_min, a_max):\n        return np.clip(a, a_min, a_max)\n\n    def repeat(self, a, repeats, axis=None):\n        return np.repeat(a, repeats, axis)\n\n    def take_along_axis(self, arr, indices, axis):\n        return np.take_along_axis(arr, indices, axis)\n\n    def concatenate(self, arrays, axis=0):\n        return np.concatenate(arrays, axis)\n\n    def zero_pad(self, a, pad_width):\n        return np.pad(a, pad_width)\n\n    def argmax(self, a, axis=None):\n        return np.argmax(a, axis=axis)\n\n    def mean(self, a, axis=None):\n        return np.mean(a, axis=axis)\n\n    def std(self, a, axis=None):\n        return np.std(a, axis=axis)\n\n    def linspace(self, start, stop, num):\n        return np.linspace(start, stop, num)\n\n    def meshgrid(self, a, b):\n        return np.meshgrid(a, b)\n\n    def diag(self, a, k=0):\n        return np.diag(a, k)\n\n    def unique(self, a):\n        return np.unique(a)\n\n    def logsumexp(self, a, axis=None):\n        return scipy.logsumexp(a, axis=axis)\n\n    def stack(self, arrays, axis=0):\n        return np.stack(arrays, axis)\n\n    def reshape(self, a, shape):\n        return np.reshape(a, shape)\n\n    def seed(self, seed=None):\n        if seed is not None:\n            self.rng_.seed(seed)\n\n    def rand(self, *size, type_as=None):\n        return self.rng_.rand(*size)\n\n    def randn(self, *size, type_as=None):\n        return self.rng_.randn(*size)\n\n    def coo_matrix(self, data, rows, cols, shape=None, type_as=None):\n        if type_as is None:\n            return coo_matrix((data, (rows, cols)), shape=shape)\n        else:\n            return coo_matrix((data, (rows, cols)), shape=shape, dtype=type_as.dtype)\n\n    def issparse(self, a):\n        return issparse(a)\n\n    def tocsr(self, a):\n        if self.issparse(a):\n            return a.tocsr()\n        else:\n            return csr_matrix(a)\n\n    def eliminate_zeros(self, a, threshold=0.):\n        if threshold > 0:\n            if self.issparse(a):\n                a.data[self.abs(a.data) <= threshold] = 0\n            else:\n                a[self.abs(a) <= threshold] = 0\n        if self.issparse(a):\n            a.eliminate_zeros()\n        return a\n\n    def todense(self, a):\n        if self.issparse(a):\n            return a.toarray()\n        else:\n            return a\n\n    def where(self, condition, x, y):\n        return np.where(condition, x, y)\n\n    def copy(self, a):\n        return a.copy()\n\n    def allclose(self, a, b, rtol=1e-05, atol=1e-08, equal_nan=False):\n        return np.allclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)\n\n    def dtype_device(self, a):\n        if hasattr(a, \"dtype\"):\n            return a.dtype, \"cpu\"\n        else:\n            return type(a), \"cpu\"\n\n    def assert_same_dtype_device(self, a, b):\n        # numpy has implicit type conversion so we automatically validate the test\n        pass\n\n\nclass JaxBackend(Backend):\n    \"\"\"\n    JAX implementation of the backend\n\n    - `__name__` is \"jax\"\n    - `__type__` is jax.numpy.ndarray\n    \"\"\"\n\n    __name__ = 'jax'\n    __type__ = jax_type\n    __type_list__ = None\n\n    rng_ = None\n\n    def __init__(self):\n        self.rng_ = jax.random.PRNGKey(42)\n\n        for d in jax.devices():\n            self.__type_list__ = [jax.device_put(jnp.array(1, dtype=jnp.float32), d),\n                                  jax.device_put(jnp.array(1, dtype=jnp.float64), d)]\n\n    def to_numpy(self, a):\n        return np.array(a)\n\n    def _change_device(self, a, type_as):\n        return jax.device_put(a, type_as.device_buffer.device())\n\n    def from_numpy(self, a, type_as=None):\n        if type_as is None:\n            return jnp.array(a)\n        else:\n            return self._change_device(jnp.array(a).astype(type_as.dtype), type_as)\n\n    def set_gradients(self, val, inputs, grads):\n        from jax.flatten_util import ravel_pytree\n        val, = jax.lax.stop_gradient((val,))\n\n        ravelled_inputs, _ = ravel_pytree(inputs)\n        ravelled_grads, _ = ravel_pytree(grads)\n\n        aux = jnp.sum(ravelled_inputs * ravelled_grads) / 2\n        aux = aux - jax.lax.stop_gradient(aux)\n\n        val, = jax.tree_map(lambda z: z + aux, (val,))\n        return val\n\n    def zeros(self, shape, type_as=None):\n        if type_as is None:\n            return jnp.zeros(shape)\n        else:\n            return self._change_device(jnp.zeros(shape, dtype=type_as.dtype), type_as)\n\n    def ones(self, shape, type_as=None):\n        if type_as is None:\n            return jnp.ones(shape)\n        else:\n            return self._change_device(jnp.ones(shape, dtype=type_as.dtype), type_as)\n\n    def arange(self, stop, start=0, step=1, type_as=None):\n        return jnp.arange(start, stop, step)\n\n    def full(self, shape, fill_value, type_as=None):\n        if type_as is None:\n            return jnp.full(shape, fill_value)\n        else:\n            return self._change_device(jnp.full(shape, fill_value, dtype=type_as.dtype), type_as)\n\n    def eye(self, N, M=None, type_as=None):\n        if type_as is None:\n            return jnp.eye(N, M)\n        else:\n            return self._change_device(jnp.eye(N, M, dtype=type_as.dtype), type_as)\n\n    def sum(self, a, axis=None, keepdims=False):\n        return jnp.sum(a, axis, keepdims=keepdims)\n\n    def cumsum(self, a, axis=None):\n        return jnp.cumsum(a, axis)\n\n    def max(self, a, axis=None, keepdims=False):\n        return jnp.max(a, axis, keepdims=keepdims)\n\n    def min(self, a, axis=None, keepdims=False):\n        return jnp.min(a, axis, keepdims=keepdims)\n\n    def maximum(self, a, b):\n        return jnp.maximum(a, b)\n\n    def minimum(self, a, b):\n        return jnp.minimum(a, b)\n\n    def dot(self, a, b):\n        return jnp.dot(a, b)\n\n    def abs(self, a):\n        return jnp.abs(a)\n\n    def exp(self, a):\n        return jnp.exp(a)\n\n    def log(self, a):\n        return jnp.log(a)\n\n    def sqrt(self, a):\n        return jnp.sqrt(a)\n\n    def power(self, a, exponents):\n        return jnp.power(a, exponents)\n\n    def norm(self, a):\n        return jnp.sqrt(jnp.sum(jnp.square(a)))\n\n    def any(self, a):\n        return jnp.any(a)\n\n    def isnan(self, a):\n        return jnp.isnan(a)\n\n    def isinf(self, a):\n        return jnp.isinf(a)\n\n    def einsum(self, subscripts, *operands):\n        return jnp.einsum(subscripts, *operands)\n\n    def sort(self, a, axis=-1):\n        return jnp.sort(a, axis)\n\n    def argsort(self, a, axis=-1):\n        return jnp.argsort(a, axis)\n\n    def searchsorted(self, a, v, side='left'):\n        if a.ndim == 1:\n            return jnp.searchsorted(a, v, side)\n        else:\n            # this is a not very efficient way to make jax numpy\n            # searchsorted work on 2d arrays\n            return jnp.array([jnp.searchsorted(a[i, :], v[i, :], side) for i in range(a.shape[0])])\n\n    def flip(self, a, axis=None):\n        return jnp.flip(a, axis)\n\n    def outer(self, a, b):\n        return jnp.outer(a, b)\n\n    def clip(self, a, a_min, a_max):\n        return jnp.clip(a, a_min, a_max)\n\n    def repeat(self, a, repeats, axis=None):\n        return jnp.repeat(a, repeats, axis)\n\n    def take_along_axis(self, arr, indices, axis):\n        return jnp.take_along_axis(arr, indices, axis)\n\n    def concatenate(self, arrays, axis=0):\n        return jnp.concatenate(arrays, axis)\n\n    def zero_pad(self, a, pad_width):\n        return jnp.pad(a, pad_width)\n\n    def argmax(self, a, axis=None):\n        return jnp.argmax(a, axis=axis)\n\n    def mean(self, a, axis=None):\n        return jnp.mean(a, axis=axis)\n\n    def std(self, a, axis=None):\n        return jnp.std(a, axis=axis)\n\n    def linspace(self, start, stop, num):\n        return jnp.linspace(start, stop, num)\n\n    def meshgrid(self, a, b):\n        return jnp.meshgrid(a, b)\n\n    def diag(self, a, k=0):\n        return jnp.diag(a, k)\n\n    def unique(self, a):\n        return jnp.unique(a)\n\n    def logsumexp(self, a, axis=None):\n        return jscipy.logsumexp(a, axis=axis)\n\n    def stack(self, arrays, axis=0):\n        return jnp.stack(arrays, axis)\n\n    def reshape(self, a, shape):\n        return jnp.reshape(a, shape)\n\n    def seed(self, seed=None):\n        if seed is not None:\n            self.rng_ = jax.random.PRNGKey(seed)\n\n    def rand(self, *size, type_as=None):\n        self.rng_, subkey = jax.random.split(self.rng_)\n        if type_as is not None:\n            return jax.random.uniform(subkey, shape=size, dtype=type_as.dtype)\n        else:\n            return jax.random.uniform(subkey, shape=size)\n\n    def randn(self, *size, type_as=None):\n        self.rng_, subkey = jax.random.split(self.rng_)\n        if type_as is not None:\n            return jax.random.normal(subkey, shape=size, dtype=type_as.dtype)\n        else:\n            return jax.random.normal(subkey, shape=size)\n\n    def coo_matrix(self, data, rows, cols, shape=None, type_as=None):\n        # Currently, JAX does not support sparse matrices\n        data = self.to_numpy(data)\n        rows = self.to_numpy(rows)\n        cols = self.to_numpy(cols)\n        nx = NumpyBackend()\n        coo_matrix = nx.coo_matrix(data, rows, cols, shape=shape, type_as=type_as)\n        matrix = nx.todense(coo_matrix)\n        return self.from_numpy(matrix)\n\n    def issparse(self, a):\n        # Currently, JAX does not support sparse matrices\n        return False\n\n    def tocsr(self, a):\n        # Currently, JAX does not support sparse matrices\n        return a\n\n    def eliminate_zeros(self, a, threshold=0.):\n        # Currently, JAX does not support sparse matrices\n        if threshold > 0:\n            return self.where(\n                self.abs(a) <= threshold,\n                self.zeros((1,), type_as=a),\n                a\n            )\n        return a\n\n    def todense(self, a):\n        # Currently, JAX does not support sparse matrices\n        return a\n\n    def where(self, condition, x, y):\n        return jnp.where(condition, x, y)\n\n    def copy(self, a):\n        # No need to copy, JAX arrays are immutable\n        return a\n\n    def allclose(self, a, b, rtol=1e-05, atol=1e-08, equal_nan=False):\n        return jnp.allclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)\n\n    def dtype_device(self, a):\n        return a.dtype, a.device_buffer.device()\n\n    def assert_same_dtype_device(self, a, b):\n        a_dtype, a_device = self.dtype_device(a)\n        b_dtype, b_device = self.dtype_device(b)\n\n        assert a_dtype == b_dtype, \"Dtype discrepancy\"\n        assert a_device == b_device, f\"Device discrepancy. First input is on {str(a_device)}, whereas second input is on {str(b_device)}\"\n\n\nclass TorchBackend(Backend):\n    \"\"\"\n    PyTorch implementation of the backend\n\n    - `__name__` is \"torch\"\n    - `__type__` is torch.Tensor\n    \"\"\"\n\n    __name__ = 'torch'\n    __type__ = torch_type\n    __type_list__ = None\n\n    rng_ = None\n\n    def __init__(self):\n\n        self.rng_ = torch.Generator()\n        self.rng_.seed()\n\n        self.__type_list__ = [torch.tensor(1, dtype=torch.float32),\n                              torch.tensor(1, dtype=torch.float64)]\n\n        if torch.cuda.is_available():\n            self.__type_list__.append(torch.tensor(1, dtype=torch.float32, device='cuda'))\n            self.__type_list__.append(torch.tensor(1, dtype=torch.float64, device='cuda'))\n\n        from torch.autograd import Function\n\n        # define a function that takes inputs val and grads\n        # ad returns a val tensor with proper gradients\n        class ValFunction(Function):\n\n            @staticmethod\n            def forward(ctx, val, grads, *inputs):\n                ctx.grads = grads\n                return val\n\n            @staticmethod\n            def backward(ctx, grad_output):\n                # the gradients are grad\n                return (None, None) + tuple(g * grad_output for g in ctx.grads)\n\n        self.ValFunction = ValFunction\n\n    def to_numpy(self, a):\n        return a.cpu().detach().numpy()\n\n    def from_numpy(self, a, type_as=None):\n        if isinstance(a, float):\n            a = np.array(a)\n        if type_as is None:\n            return torch.from_numpy(a)\n        else:\n            return torch.as_tensor(a, dtype=type_as.dtype, device=type_as.device)\n\n    def set_gradients(self, val, inputs, grads):\n\n        Func = self.ValFunction()\n\n        res = Func.apply(val, grads, *inputs)\n\n        return res\n\n    def zeros(self, shape, type_as=None):\n        if isinstance(shape, int):\n            shape = (shape,)\n        if type_as is None:\n            return torch.zeros(shape)\n        else:\n            return torch.zeros(shape, dtype=type_as.dtype, device=type_as.device)\n\n    def ones(self, shape, type_as=None):\n        if isinstance(shape, int):\n            shape = (shape,)\n        if type_as is None:\n            return torch.ones(shape)\n        else:\n            return torch.ones(shape, dtype=type_as.dtype, device=type_as.device)\n\n    def arange(self, stop, start=0, step=1, type_as=None):\n        if type_as is None:\n            return torch.arange(start, stop, step)\n        else:\n            return torch.arange(start, stop, step, device=type_as.device)\n\n    def full(self, shape, fill_value, type_as=None):\n        if isinstance(shape, int):\n            shape = (shape,)\n        if type_as is None:\n            return torch.full(shape, fill_value)\n        else:\n            return torch.full(shape, fill_value, dtype=type_as.dtype, device=type_as.device)\n\n    def eye(self, N, M=None, type_as=None):\n        if M is None:\n            M = N\n        if type_as is None:\n            return torch.eye(N, m=M)\n        else:\n            return torch.eye(N, m=M, dtype=type_as.dtype, device=type_as.device)\n\n    def sum(self, a, axis=None, keepdims=False):\n        if axis is None:\n            return torch.sum(a)\n        else:\n            return torch.sum(a, axis, keepdim=keepdims)\n\n    def cumsum(self, a, axis=None):\n        if axis is None:\n            return torch.cumsum(a.flatten(), 0)\n        else:\n            return torch.cumsum(a, axis)\n\n    def max(self, a, axis=None, keepdims=False):\n        if axis is None:\n            return torch.max(a)\n        else:\n            return torch.max(a, axis, keepdim=keepdims)[0]\n\n    def min(self, a, axis=None, keepdims=False):\n        if axis is None:\n            return torch.min(a)\n        else:\n            return torch.min(a, axis, keepdim=keepdims)[0]\n\n    def maximum(self, a, b):\n        if isinstance(a, int) or isinstance(a, float):\n            a = torch.tensor([float(a)], dtype=b.dtype, device=b.device)\n        if isinstance(b, int) or isinstance(b, float):\n            b = torch.tensor([float(b)], dtype=a.dtype, device=a.device)\n        if hasattr(torch, \"maximum\"):\n            return torch.maximum(a, b)\n        else:\n            return torch.max(torch.stack(torch.broadcast_tensors(a, b)), axis=0)[0]\n\n    def minimum(self, a, b):\n        if isinstance(a, int) or isinstance(a, float):\n            a = torch.tensor([float(a)], dtype=b.dtype, device=b.device)\n        if isinstance(b, int) or isinstance(b, float):\n            b = torch.tensor([float(b)], dtype=a.dtype, device=a.device)\n        if hasattr(torch, \"minimum\"):\n            return torch.minimum(a, b)\n        else:\n            return torch.min(torch.stack(torch.broadcast_tensors(a, b)), axis=0)[0]\n\n    def dot(self, a, b):\n        return torch.matmul(a, b)\n\n    def abs(self, a):\n        return torch.abs(a)\n\n    def exp(self, a):\n        return torch.exp(a)\n\n    def log(self, a):\n        return torch.log(a)\n\n    def sqrt(self, a):\n        return torch.sqrt(a)\n\n    def power(self, a, exponents):\n        return torch.pow(a, exponents)\n\n    def norm(self, a):\n        return torch.sqrt(torch.sum(torch.square(a)))\n\n    def any(self, a):\n        return torch.any(a)\n\n    def isnan(self, a):\n        return torch.isnan(a)\n\n    def isinf(self, a):\n        return torch.isinf(a)\n\n    def einsum(self, subscripts, *operands):\n        return torch.einsum(subscripts, *operands)\n\n    def sort(self, a, axis=-1):\n        sorted0, indices = torch.sort(a, dim=axis)\n        return sorted0\n\n    def argsort(self, a, axis=-1):\n        sorted, indices = torch.sort(a, dim=axis)\n        return indices\n\n    def searchsorted(self, a, v, side='left'):\n        right = (side != 'left')\n        return torch.searchsorted(a, v, right=right)\n\n    def flip(self, a, axis=None):\n        if axis is None:\n            return torch.flip(a, tuple(i for i in range(len(a.shape))))\n        if isinstance(axis, int):\n            return torch.flip(a, (axis,))\n        else:\n            return torch.flip(a, dims=axis)\n\n    def outer(self, a, b):\n        return torch.outer(a, b)\n\n    def clip(self, a, a_min, a_max):\n        return torch.clamp(a, a_min, a_max)\n\n    def repeat(self, a, repeats, axis=None):\n        return torch.repeat_interleave(a, repeats, dim=axis)\n\n    def take_along_axis(self, arr, indices, axis):\n        return torch.gather(arr, axis, indices)\n\n    def concatenate(self, arrays, axis=0):\n        return torch.cat(arrays, dim=axis)\n\n    def zero_pad(self, a, pad_width):\n        from torch.nn.functional import pad\n        # pad_width is an array of ndim tuples indicating how many 0 before and after\n        # we need to add. We first need to make it compliant with torch syntax, that\n        # starts with the last dim, then second last, etc.\n        how_pad = tuple(element for tupl in pad_width[::-1] for element in tupl)\n        return pad(a, how_pad)\n\n    def argmax(self, a, axis=None):\n        return torch.argmax(a, dim=axis)\n\n    def mean(self, a, axis=None):\n        if axis is not None:\n            return torch.mean(a, dim=axis)\n        else:\n            return torch.mean(a)\n\n    def std(self, a, axis=None):\n        if axis is not None:\n            return torch.std(a, dim=axis, unbiased=False)\n        else:\n            return torch.std(a, unbiased=False)\n\n    def linspace(self, start, stop, num):\n        return torch.linspace(start, stop, num, dtype=torch.float64)\n\n    def meshgrid(self, a, b):\n        X, Y = torch.meshgrid(a, b)\n        return X.T, Y.T\n\n    def diag(self, a, k=0):\n        return torch.diag(a, diagonal=k)\n\n    def unique(self, a):\n        return torch.unique(a)\n\n    def logsumexp(self, a, axis=None):\n        if axis is not None:\n            return torch.logsumexp(a, dim=axis)\n        else:\n            return torch.logsumexp(a, dim=tuple(range(len(a.shape))))\n\n    def stack(self, arrays, axis=0):\n        return torch.stack(arrays, dim=axis)\n\n    def reshape(self, a, shape):\n        return torch.reshape(a, shape)\n\n    def seed(self, seed=None):\n        if isinstance(seed, int):\n            self.rng_.manual_seed(seed)\n        elif isinstance(seed, torch.Generator):\n            self.rng_ = seed\n        else:\n            raise ValueError(\"Non compatible seed : {}\".format(seed))\n\n    def rand(self, *size, type_as=None):\n        if type_as is not None:\n            return torch.rand(size=size, generator=self.rng_, dtype=type_as.dtype, device=type_as.device)\n        else:\n            return torch.rand(size=size, generator=self.rng_)\n\n    def randn(self, *size, type_as=None):\n        if type_as is not None:\n            return torch.randn(size=size, dtype=type_as.dtype, generator=self.rng_, device=type_as.device)\n        else:\n            return torch.randn(size=size, generator=self.rng_)\n\n    def coo_matrix(self, data, rows, cols, shape=None, type_as=None):\n        if type_as is None:\n            return torch.sparse_coo_tensor(torch.stack([rows, cols]), data, size=shape)\n        else:\n            return torch.sparse_coo_tensor(\n                torch.stack([rows, cols]), data, size=shape,\n                dtype=type_as.dtype, device=type_as.device\n            )\n\n    def issparse(self, a):\n        return getattr(a, \"is_sparse\", False) or getattr(a, \"is_sparse_csr\", False)\n\n    def tocsr(self, a):\n        # Versions older than 1.9 do not support CSR tensors. PyTorch 1.9 and 1.10 offer a very limited support\n        return self.todense(a)\n\n    def eliminate_zeros(self, a, threshold=0.):\n        if self.issparse(a):\n            if threshold > 0:\n                mask = self.abs(a) <= threshold\n                mask = ~mask\n                mask = mask.nonzero()\n            else:\n                mask = a._values().nonzero()\n            nv = a._values().index_select(0, mask.view(-1))\n            ni = a._indices().index_select(1, mask.view(-1))\n            return self.coo_matrix(nv, ni[0], ni[1], shape=a.shape, type_as=a)\n        else:\n            if threshold > 0:\n                a[self.abs(a) <= threshold] = 0\n            return a\n\n    def todense(self, a):\n        if self.issparse(a):\n            return a.to_dense()\n        else:\n            return a\n\n    def where(self, condition, x, y):\n        return torch.where(condition, x, y)\n\n    def copy(self, a):\n        return torch.clone(a)\n\n    def allclose(self, a, b, rtol=1e-05, atol=1e-08, equal_nan=False):\n        return torch.allclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)\n\n    def dtype_device(self, a):\n        return a.dtype, a.device\n\n    def assert_same_dtype_device(self, a, b):\n        a_dtype, a_device = self.dtype_device(a)\n        b_dtype, b_device = self.dtype_device(b)\n\n        assert a_dtype == b_dtype, \"Dtype discrepancy\"\n        assert a_device == b_device, f\"Device discrepancy. First input is on {str(a_device)}, whereas second input is on {str(b_device)}\"\n", "meta": {"hexsha": "fa164c39f36ab2fbe007dd31ac575770cb386acb", "size": 44930, "ext": "py", "lang": "Python", "max_stars_repo_path": "ot/backend.py", "max_stars_repo_name": "cedricvincentcuaz/POT", "max_stars_repo_head_hexsha": "cb510644b2fd65e4ce216a7799ce7401f71548b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ot/backend.py", "max_issues_repo_name": "cedricvincentcuaz/POT", "max_issues_repo_head_hexsha": "cb510644b2fd65e4ce216a7799ce7401f71548b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ot/backend.py", "max_forks_repo_name": "cedricvincentcuaz/POT", "max_forks_repo_head_hexsha": "cb510644b2fd65e4ce216a7799ce7401f71548b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8935462409, "max_line_length": 151, "alphanum_fraction": 0.6079679501, "include": true, "reason": "import numpy,from numpy,import scipy,from scipy,import jax,from jax", "num_tokens": 10553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19997006613770815}}
{"text": "\"\"\"\nPart of code is from Kai Li \"kailigo\". The gitub website is https://github.com/kailigo/cvcZSL.\nWe add virtual classes and IAS in the code.\n\"\"\"\nfrom scipy import io\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch.nn import functional as F\nfrom torch.optim import lr_scheduler\nimport torch.utils.data as data\nfrom sklearn.metrics import accuracy_score\nfrom tensorboardX import SummaryWriter\n\nfrom utils import ReDirectSTD\nfrom unseen_data_loader import data_loader_virtualCls\nfrom unseen_option import Options\n\nimport os\nimport random\nimport pickle\n# from test_embeded import test_while_training_simple\n\nTMP = 10\n\nargs = Options().parse()\nmodel_file_name = './chk/' + args.model_file\nsummaryFolder = './summary/' + args.log_file\nif not os.path.exists(summaryFolder):\n    os.mkdir(summaryFolder)\nwriter = SummaryWriter(summaryFolder)\nprint(args)\n\ndef init_seeds(seed=0):\n    random.seed(seed)\n    np.random.seed(seed)\n\n    # torch cuda\n    torch.cuda.empty_cache()\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.cuda.manual_seed_all(seed)\n\ninit_seeds(520)\ndef calc_accuracy(test_visual, test_label, attM, test_id, test_id_seen_unseen,cossim=False):       \n        outpred = [0] * test_visual.shape[0]    \n        end = 0\n        outpred_list = []\n        zslpred_list = []\n        score_n_list = []\n        for j in range(0,len(test_visual),64):\n            if j+64>len(test_visual):\n                end = len(test_visual)\n            else:\n                end = j+64\n            all_cls_weights = forward(attM,test_visual[j:end],tmp=TMP)       \n            score,score_n=apply_classification_weights(test_visual[j:end].cuda(), \n                    all_cls_weights,norm=True)\n            score = score.squeeze(0)\n            score_n = score_n.squeeze(0)\n            \n            _, pred = score.max(dim=1)\n            pred = pred.view(-1)\n            select_test_label = test_label[j:end].view(-1)\n\n            outpred_list.extend(test_id[pred.cpu().detach().numpy()])\n            zslpred_list.extend([ i in test_id_seen_unseen for i in test_id[pred.cpu().detach().numpy()]])\n            score_n_list.extend(score_n.cpu().detach().numpy())\n\n        seen_unseen_acc = accuracy_score(np.ones(len(zslpred_list)),zslpred_list)\n        \n        outpred = np.array(outpred_list, dtype='int')\n        score_n = np.array(score_n_list)\n        test_label = test_label.numpy()\n        unique_labels = np.unique(test_label)\n        acc = 0\n        acc_cls = {}\n        preds_cls = {}\n        cos_cls = {}\n        for l in unique_labels:\n                idx = np.nonzero(test_label == l)[0]\n                acc_cls[l] = accuracy_score(test_label[idx],outpred[idx])\n                try:\n                    preds_cls[l].extend(list(outpred[idx])) \n                except(KeyError):\n                    preds_cls[l] = list(outpred[idx])\n\n                acc += acc_cls[l]\n                loc = test_label == l\n                outpred_l = outpred[idx]\n                score_n_l = score_n[idx]\n                loc = outpred_l == l\n\n                if cossim:\n                    cos_c = score_n_l[loc,l]\n                    try:\n                        cos_cls[l].extend(cos_c)\n                    except(KeyError):\n                        cos_cls[l] = [cos_c]\n        acc = acc / unique_labels.shape[0]\n\n        return acc,seen_unseen_acc,acc_cls,cos_cls,preds_cls\n\n\ndef compute_accuracy_all(test_att, att_all, test_visual_unseen, test_id_unseen, test_label_unseen,\n                test_visual_seen, test_id_all, test_label_seen,train_id):\n\n        acc_zsl,_,unseenacc_cls,_,unseenpred_cls = calc_accuracy(test_visual_unseen, test_label_unseen, test_att, test_id_unseen,test_id_unseen)\n        acc_seenAcc,_,seenacc_cls,_,_ = calc_accuracy(test_visual_seen, test_label_seen, att_all, train_id, train_id)\n\n        att_all_cls = torch.cat((att_all, test_att))\n        \n        acc_gzsl_unseen,Ru,unseengeneralAcc_cls,unseenCos_cls,_ = calc_accuracy(test_visual_unseen, test_label_unseen, att_all_cls, test_id_all,test_id_unseen,cossim=True)\n        \n        acc_gzsl_seen,Rs,seengeneralAcc_cls,seenCos_cls,_ = calc_accuracy(test_visual_seen, test_label_seen, att_all_cls, test_id_all,train_id,cossim=True)       \n        acc_cls = {**unseenacc_cls,**seenacc_cls}\n        generalAcc_cls = {**unseengeneralAcc_cls,**seengeneralAcc_cls}\n        H = 2 * acc_gzsl_seen * acc_gzsl_unseen / (acc_gzsl_seen + acc_gzsl_unseen)\n\n        return acc_zsl, acc_seenAcc, acc_gzsl_unseen, acc_gzsl_seen, H, Rs, Ru, acc_cls, generalAcc_cls,unseenCos_cls,seenCos_cls,unseenpred_cls\n\n\ndef apply_classification_weights(features, cls_weights,norm=False):\n\n        features = F.normalize(features,dim=-1)\n        cls_weights = F.normalize(cls_weights, p=2, dim=-1, eps=1e-12) \n\n        cls_scores = scale_cls * (torch.matmul(cls_weights,features.t()))\n        cls_scores = cls_scores.permute(0,2,1)\n        cls_scores = torch.diagonal(cls_scores,offset=0,dim1=0,dim2=1)\n        cls_scores = cls_scores.t()\n        if norm:\n            return cls_scores,cls_scores/scale_cls\n        else:\n            return cls_scores\n\n\ndef IASatt(features,AttM,tmp):\n        cls_num = len(AttM)\n        attdims = AttM.shape[1]\n        atten = torch.mm(features,w_IAS)+b_IAS\n        atten = F.softmax(atten/tmp,dim=1).reshape(-1,1,attdims)\n        atten = atten.reshape(-1,1,attdims)\n        atten = atten + torch.ones_like(atten)\n        atten = atten.repeat(1,cls_num,1)\n        AttM = AttM.unsqueeze(0)\n        AttM = AttM.repeat(len(features),1,1)\n        AttM = atten*AttM\n        return AttM\n\ndef forward(att,features,tmp):\n        features = features.squeeze()\n        att = IASatt(features,att,tmp)\n\n        a1 = F.relu(torch.matmul(att, w1) + b1)\n        a2 = F.relu(torch.matmul(a1, w2) + b2)\n\n        return a2\n\ndataroot = './dataset/xlsa/'\nimage_embedding = 'res101' \nclass_embedding = 'att'\ndataset = args.dataset\nmatcontent = io.loadmat(dataroot + \"/\" + dataset + \"/\" + image_embedding + \".mat\")\n\nfeature = matcontent['features'].T\nlabel = matcontent['labels'].astype(int).squeeze() - 1\nmatcontent = io.loadmat(dataroot + \"/\" + dataset + \"/\" + class_embedding + \"_splits.mat\")\n\ntrainvalloc = matcontent['trainval_loc'].squeeze() - 1\ntest_seen_loc = matcontent['test_seen_loc'].squeeze() - 1\ntest_unseen_loc = matcontent['test_unseen_loc'].squeeze() - 1\n\natt_name = 'att'\nattribute = matcontent[att_name].T \n\nchkFile = './dataset/finetune/'+args.dataset+'/dvbeExtracted.pkl'\nwith open(chkFile,'rb') as f:\n    Feature_target = pickle.load(f)\n\nclsname = [ matcontent['allclasses_names'][i][0][0] for i in range(len(matcontent['allclasses_names']))]\n\ntrain_x = Feature_target['train_seen']['features']\ntrain_label = Feature_target['train_seen']['labels']\ntrain_att = attribute[train_label]\ntrain_id, idx = np.unique(train_label, return_inverse=True)\ntrain_att_unique = attribute[train_id]\n\ntest_x_unseen = Feature_target['test_unseen']['features']\ntest_label_unseen = Feature_target['test_unseen']['labels']\ntest_id, idx = np.unique(test_label_unseen, return_inverse=True)\natt_pro = attribute[test_id]\ntrain_test_id = np.concatenate((train_id, test_id))\n\ntest_x_seen = Feature_target['test_seen']['features'] \ntest_label_seen = Feature_target['test_seen']['labels']\n_, idx = np.unique(test_label_seen, return_inverse=True)\n\natt_dim = train_att.shape[1]\nfeat_dim = train_x.shape[1]\n\natt_pro = torch.from_numpy(att_pro).float().cuda()\ntest_x_seen = torch.from_numpy(test_x_seen).float().cuda()\ntest_x_seen = F.normalize(test_x_seen, p=2, dim=test_x_seen.dim()-1, eps=1e-12)\ntest_x_unseen = torch.from_numpy(test_x_unseen).float().cuda()\ntest_x_unseen = F.normalize(test_x_unseen, p=2, dim=test_x_unseen.dim()-1, eps=1e-12)\ntest_label_seen = torch.tensor(test_label_seen)\ntest_label_unseen = torch.tensor(test_label_unseen)\n\natt_all = torch.from_numpy(train_att_unique).float().cuda()\n\nbias = nn.Parameter(torch.FloatTensor(1).fill_(0).cuda(), requires_grad=True)\nscale_cls = nn.Parameter(torch.FloatTensor(1).fill_(10).cuda(), requires_grad=True)\nw1 = Variable(torch.FloatTensor(att_dim, args.hidden_dim).cuda(), requires_grad=True)\nb1 = Variable(torch.FloatTensor(args.hidden_dim).cuda(), requires_grad=True)\nw2 = Variable(torch.FloatTensor(args.hidden_dim, 2048).cuda(), requires_grad=True)\nb2 = Variable(torch.FloatTensor(2048).cuda(), requires_grad=True)\nw_IAS = Variable(torch.FloatTensor(2048, att_dim).cuda(), requires_grad=True)\nb_IAS = Variable(torch.FloatTensor(att_dim).cuda(), requires_grad=True)\n\nw1.data.normal_(0, 0.02)\nw2.data.normal_(0, 0.02)\nb1.data.fill_(0)\nb2.data.fill_(0)\nw_IAS.data.normal_(0,0.02)\nb_IAS.data.fill_(0)\n\noptimizer = torch.optim.Adam([w_IAS,b_IAS,w1, b1, w2, b2, bias, scale_cls], lr=args.lr, weight_decay=args.opt_decay)\n\n# breakpoint()\nstep_size = args.step_size\ngamma = args.gamma\nlr_scheduler = lr_scheduler.StepLR(optimizer, step_size=step_size, gamma=gamma)\ncriterion = nn.CrossEntropyLoss()\n\nways = args.ways\nshots = args.shots\n\ndataset = data_loader_virtualCls(train_x, train_att, train_label, ways=ways, shots=shots)\n\n# breakpoint()\nbest_acc_zsl = 0.0\nbest_acc_gzsl_seen = 0.0\nbest_acc_gzsl_unseen = 0.0\nbest_H = 0.0\nbest_epoch = 0\nbest_unseenAcc = 0.0\n\n\nfor epoch in range(args.num_epochs):    \n        epoch_loss = 0\n        lr_scheduler.step()\n\n        for i in range(1000):           \n                batch_visual, batch_att, batch_label = dataset.__getitem__(i)                           \n                batch_visual = batch_visual.cuda()                              \n                batch_visual_norm = F.normalize(batch_visual, p=2, dim=batch_visual.dim()-1, eps=1e-12)                         \n\n                indx = torch.tensor(list(range(0, ways*shots, shots)))  \n                unique_batch_att = torch.index_select(batch_att, 0, indx).float().cuda()                \n\n                batch_weights = forward(unique_batch_att,batch_visual_norm,tmp=TMP)       \n                all_cls_weights = batch_weights\n\n                score = apply_classification_weights(batch_visual_norm, all_cls_weights)\n                score = score.squeeze(0)                \n                loss = criterion(score, Variable(batch_label.cuda()))\n\n                optimizer.zero_grad()\n                loss.backward()\n                torch.nn.utils.clip_grad_norm_([w_IAS,b_IAS,w1, b1, w2, b2, scale_cls, bias], 1)\n                optimizer.step()\n                epoch_loss = epoch_loss + loss\n\n        epoch_loss = epoch_loss / 1000.0\n        epoch_loss = epoch_loss.data.cpu().numpy()\n\n        acc_zsl, seenAcc, acc_unseen_gzsl, acc_seen_gzsl, H, Rs,Ru,accs_cls,generalAccs_cls,unseenCos_cls,seenCos_cls,unseenpred_cls = compute_accuracy_all(att_pro, att_all, test_x_unseen, \n                test_id, test_label_unseen, test_x_seen, train_test_id,  test_label_seen, train_id)\n        \n        H = 2 * acc_seen_gzsl * acc_unseen_gzsl / (acc_seen_gzsl + acc_unseen_gzsl)\n        writer.add_scalar('general/acc_seen_gzsl',acc_seen_gzsl,epoch)\n        writer.add_scalar('general/acc_unseen_gzsl',acc_unseen_gzsl,epoch)\n        writer.add_scalar('general/H',H,epoch)\n        writer.add_scalar('split/unseenAcc',acc_zsl,epoch)\n        writer.add_scalar('split/seenAcc',seenAcc,epoch)\n        writer.add_scalar('split/Rs',Rs,epoch)\n        writer.add_scalar('split/Ru',Ru,epoch)\n        writer.add_scalar('loss/loss',epoch_loss,epoch)\n        \n\n        if acc_zsl > best_unseenAcc:\n                print('save best acc')\n                best_unseenAcc = acc_zsl\n                best_epoch = epoch\n                best_acc_zsl = acc_zsl          \n                best_seen_acc = seenAcc          \n                best_acc_gzsl_seen = acc_seen_gzsl\n                best_acc_gzsl_unseen = acc_unseen_gzsl\n                best_H = H\n                best_Ru = Ru\n                best_Rs = Rs\n\n                best_w1 = w1.data.clone()\n                best_b1 = b1.data.clone()\n                best_w2 = w2.data.clone()\n                best_b2 = b2.data.clone()\n                best_scale_cls = scale_cls.data.clone()\n                best_bias = bias.data.clone()\n\n                torch.save({'w1': best_w1, 'b1': best_b1, 'w2': best_w2, 'b2': best_b2, \n                    'scale_cls': best_scale_cls, 'bias': best_bias,'w_IAS':w_IAS,'b_IAS':b_IAS}, model_file_name.replace('.pt','bestunseenAcc.pt'))\n                \n\n        for param_group in optimizer.param_groups:\n                print('ep: %d,  lr: %lf, loss: %.4f,  zsl: %.4f, seenAcc: %.4f  gzsl: seen=%.4f, unseen=%.4f, h=%.4f, Rs=%.4f, Ru=%.4f ' % \n                        (epoch, param_group['lr'],  epoch_loss, acc_zsl, seenAcc, acc_seen_gzsl, acc_unseen_gzsl, H, Rs, Ru,))            \nprint(model_file_name)\nprint('best_ep: %d, zsl: %.4f, seenAcc: %.4f  gzsl: seen=%.4f, unseen=%.4f, h=%.4f, Rs=%.4f, Ru=%.4f' % \n        (best_epoch, best_acc_zsl,best_seen_acc, best_acc_gzsl_seen, best_acc_gzsl_unseen, best_H, best_Rs, best_Ru))   \n\n", "meta": {"hexsha": "9ac6af783446a65220a6b2ec56660ba8825206a0", "size": 12959, "ext": "py", "lang": "Python", "max_stars_repo_path": "train_unseen.py", "max_stars_repo_name": "anonmous529/AGZSL", "max_stars_repo_head_hexsha": "1d916f9e950d1c21c1150a0f670833439c89abb3", "max_stars_repo_licenses": ["Apache-1.1"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2020-12-04T07:14:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T07:00:55.000Z", "max_issues_repo_path": "train_unseen.py", "max_issues_repo_name": "anonmous529/AGZSL", "max_issues_repo_head_hexsha": "1d916f9e950d1c21c1150a0f670833439c89abb3", "max_issues_repo_licenses": ["Apache-1.1"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-15T23:54:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-16T00:09:17.000Z", "max_forks_repo_path": "train_unseen.py", "max_forks_repo_name": "anonmous529/AGZSL", "max_forks_repo_head_hexsha": "1d916f9e950d1c21c1150a0f670833439c89abb3", "max_forks_repo_licenses": ["Apache-1.1"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-04-16T00:01:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-05T10:38:30.000Z", "avg_line_length": 40.1207430341, "max_line_length": 189, "alphanum_fraction": 0.650358824, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19997006613770812}}
{"text": "import numpy as np\nimport array\nimport os, sys\nimport re\nimport time\nimport multiprocessing, logging\n# mpl = multiprocessing.log_to_stderr()\n# mpl.setLevel(logging.INFO)\n\nimport h5py\nimport logging\nfrom astropy.table import Table, Column\nfrom astropy import units as u\nfrom scipy.interpolate import griddata\n\n\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-p\",\"--params\", type=str,\n                    help = \"Parameter file\")\nparser.add_argument(\"-q\", \"--quiet\", help = \"Suppress extra outputs\",\n                    action = \"store_true\")\nargs = parser.parse_args()\nquiet = args.quiet\n\nparams_root = re.split(\".py\", args.params)[0]\nif os.path.isfile(params_root+\".pyc\"):\n    os.remove(params_root+\".pyc\")\n\nimport importlib\ntry:\n    params = importlib.import_module(params_root)\n    print('Successfully loaded \"{}\" as params'.format(args.params))\n    #reload(params)\nexcept:\n    print('Failed to load \"{}\" as params'.format(args.params))\n    raise\n\nif quiet:\n    quietprint = lambda *a: None\nelse:\n    def quietprint(*args):\n        for arg in args:\n            print (arg)\n\n# Fitting function definition for later use by Processess\n\ndef galaxyFit(inputQueue, printQueue, printlock):\n    for gal in iter(inputQueue.get, 'STOP'):\n        j = np.argmin(np.abs(z-zobs[gal])) # Find closest model redshift\n\n\n        flux_obs = obs[gal,:]\n        flux_err = obs_err[gal,:]\n\n        #flux_obs[fo <= 0.] = 0.       # Set negative fluxes to zero\n        I = np.where(flux_err > 0.)[0] # Find bands with no observation\n\n        if len(I) == 0:\n            if include_rest:\n                M_scaled = np.ones(len(fo)) * -99.\n                restframe_output = ' '.join(M_scaled.astype('str'))\n                output_string = '{} {} {} {} {} {} {} {}' \\\n                                ' {} {} {} {} {} {} {} {} {}'.format(gal+1,ID[gal],zobs[gal],-99,-99,-99,-99,-99,-99, -99, -99,-99,len(I),-99,z[j],restframe_output,'\\n')\n            else:\n                output_string = '{} {} {} {} {} {} {} {} {} {} {} {} {} {} {}'.format(gal+1,ID[gal],zobs[gal],-99,-99,-99,-99,-99,-99,-99, -99,-99,len(I),-99,'\\n')\n            printQueue.put(output_string)\n            continue\n\n        flux_obs = flux_obs[I]                    # and exclude from fit\n        flux_err = flux_err[I]\n        flux_models = f[j,I,:]\n\n        tot_err = np.sqrt(flux_err**2 + (0.1*flux_obs)**2)\n\n        top = 0.\n        bottom = 0.\n\n        for i in range(len(flux_obs)):\n            top += (flux_models[i,:]*flux_obs[i])/(tot_err[i]**2)\n            bottom += (flux_models[i,:]**2)/(tot_err[i]**2)\n\n        scale = top/bottom\n        scale = np.reshape(scale, (n_metal, n_tg, n_tau, n_tauv, n_fesc))\n\n        chisq = 0.\n        for i in range(len(flux_obs)):\n            chisq += ((np.abs(scale*flux_models[i,:]-flux_obs[i])**2)/(flux_err[i])**2)\n\n        chimin, minind = np.nanmin(chisq), np.nanargmin(chisq)\n\n        if np.isinf(chimin) or np.isnan(minind):\n            if include_rest:\n                M_scaled = np.ones(len(flux_obs)) * -99.\n                restframe_output = ' '.join(M_scaled.astype('str'))\n                output_string = '{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}'.format(gal+1,ID[gal],zobs[gal],-99,-99,-99,-99,-99,-99, -99, -99,-99,len(I),-99,z[j],restframe_output,'\\n')\n            else:\n                output_string = '{} {} {} {} {} {} {} {} {} {} {} {} {} {} {}'.format(gal+1,ID[gal],zobs[gal],-99,-99,-99,-99,-99,-99,-99, -99,-99,len(I),-99,'\\n')\n            printQueue.put(output_string)\n            continue\n\n\n        #Find the coordinate of the model with the bestfit mass\n        mi, tgi, ti, tvi, fi = np.unravel_index(minind,\n                                                   (n_metal, n_tg,\n                                                   n_tau, n_tauv, n_fesc))\n\n        Bestfit_Mass = np.log10(scale[mi, tgi, ti, tvi, fi]*flux_corr)\n        Bestfit_SFR = (scale[mi, tgi, ti, tvi, fi] *\n                       SFR[mi, tgi, ti, tvi, fi]*flux_corr)\n        #Bestfit_Beta = beta[tgi,tvi,ti,mi]\n        Bestfit_Beta = -99.\n\n        #Scale the observed tot_mag band of the template to be the same as the observed tot_mag band of the galaxy\n        #Convert the templates so they are no longer units of per stellar mass\n\n        F_rest = f[0,:]*scale[mi, tgi, ti, tvi, fi]*flux_corr\n        restframeMags = 23.9 - 2.5*np.log10(F_rest)\n\n        #UV_rest = UV_flux[0]*scale[tgi,tvi,ti,mi]*flux_corr\n        #restframeMUV = 23.9 - 2.5*np.log10(UV_rest)\n\n        M_scaled = restframeMags[:, mi, tgi, ti, tvi, fi]\n        #MUV_scaled = restframeMUV[tgi,tvi,ti,mi]\n        MUV_scaled = -99.\n\n        if np.isnan(Bestfit_Mass) or np.isinf(chimin):\n            Bestfit_Mass = -99\n            #M_scaled[:] = -99\n            tgs = -99\n            tvs = -99\n            taus = -99\n            mis = -99\n            escape_fraction = -99\n\n        else:\n            tgs = tg[tgi]/1e9\n            tvs = tv[tvi]\n            taus = tau[ti]\n            mis = metallicities[mi]\n            escape_fraction = fesc[fi]\n\n\n        printlock.acquire()\n\n        print('{:6d} {:8d} {:>5.2f} {:>7.2f} {:>8.1f} {:>8.3f} {:>5.1f} {:>8.2f} {:>4.2f} {:>5.2f}'.format(gal+1,ID[gal], zobs[gal],Bestfit_Mass,chimin,tgs,tvs,taus,mis,np.log10(Bestfit_SFR)))\n\n        if include_rest:\n            restframe_output = ' '.join(M_scaled.astype('str'))\n            output_string = '{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}'.format(gal+1,ID[gal],zobs[gal],Bestfit_Mass,chimin,tgs,tvs,taus,mis, MUV_scaled, minind,Bestfit_SFR,len(I),Bestfit_Beta,z[j],restframe_output,'\\n')\n        else:\n            output_string = '{} {} {} {} {} {} {} {} {} {} {} {} {} {} {}'.format(gal+1,ID[gal],zobs[gal],Bestfit_Mass,chimin,tgs,tvs,taus,mis, MUV_scaled, minind,Bestfit_SFR,len(I),Bestfit_Beta,'\\n')\n\n        printlock.release()\n        printQueue.put(output_string)\n\ndef galaxyFit2(inputQueue, printQueue, printlock):\n    for gal in iter(inputQueue.get, 'STOP'):\n\n\n        output_string = '{0[0]} {0[1]} {0[2]} {0[3]} {0[4]} {0[5]} ' + \\\n                        '{0[6]} {0[7]} {0[8]} {0[9]} {0[10]} {0[11]} ' + \\\n                        '{0[12]} {0[13]} {0[14]}'\n\n        j = np.argmin(np.abs(z-zobs[gal])) # Find closest model redshift\n\n        log_mass_min, log_mass_max = 7, 13\n        log_sfr_min, log_sfr_max = -3, 4\n\n        flux_obs = obs[gal,:]\n        flux_err = obs_err[gal,:]\n\n        #flux_obs[fo <= 0.] = 0.       # Set negative fluxes to zero\n        #I = np.where(flux_err > 0.)[0] # Find bands with no observation\n        I = (flux_err > 0.) * ((filt_lambda / (1+z[j])) < 3e5)\n\n        flux_obs = flux_obs[I] * zp_offsets[I]                    # and exclude from fit\n        flux_err = flux_err[I] * zp_offsets[I]\n        flux_models = f[j,I,:,j,:]\n\n        if params.temp_err != None:\n            terr = griddata(terr_wl, terr_sigma, filt_lambda[I] / (1+z[j]))\n            tot_err = np.sqrt(flux_err**2 + (terr*flux_obs)**2 + (params.flux_err*flux_obs)**2)\n        else:\n            tot_err = np.sqrt(flux_err**2 + (params.flux_err*flux_obs)**2)\n\n        top = 0.\n        bottom = 0.\n\n        for i in range(len(flux_obs)):\n            top += (flux_models[i,:]*flux_obs[i])/(tot_err[i]**2)\n            bottom += (flux_models[i,:]**2)/(tot_err[i]**2)\n\n        scale = top/bottom\n        scale = np.reshape(scale, (n_metal, n_tau, n_tauv, n_fesc))\n\n        chisq = 0.\n        for i in range(len(flux_obs)):\n            chisq += ((np.abs(scale*flux_models[i,:]-flux_obs[i])**2)/(tot_err[i])**2)\n\n        chimin, minind = np.nanmin(chisq), np.nanargmin(chisq)\n        likelihood = np.reshape(np.exp(-0.5*chisq),\n                                (n_metal, n_tau, n_tauv, n_fesc))\n        likelihood[np.isnan(likelihood)] = 0.\n        likelihood = np.abs(likelihood/likelihood.sum())\n\n        if np.isinf(chimin) or np.isnan(minind):\n            output_string = '{n} {id} {zobs} {ztemp} {mass_best} {sfr_best} '+ \\\n                            '{chi_best} {tvs} {taus} {mis} {fesc} '+ \\\n                            '{mass_med} {mass_l68} {mass_u68} ' + \\\n                            '{sfr_med} {sfr_l68} {sfr_u68} ' + \\\n                            '{nfilts} '\n\n            output_values = {'n': gal+1,\n                             'id': ID[gal],\n                             'zobs': zobs[gal], 'ztemp':z[j],\n                             'mass_best': -99.,\n                             'sfr_best': -99,\n                             'chi_best': -99,\n                             'tvs': -99, 'taus': -99,\n                             'mis': -99, 'fesc': -99,\n                             'mass_med': -99, 'mass_l68': -99, 'mass_u68': -99,\n                             'sfr_med': -99, 'sfr_l68': -99, 'sfr_u68': -99,\n                             'nfilts': np.sum(I)}\n\n            output_array = [gal+1, ID[gal], zobs[gal],\n                            Bestfit_Mass, chimin, tvs, taus, mis,\n                            MUV_scaled, minind, Bestfit_SFR, np.sum(I), -99., '\\n']\n            output = output_string.format(**output_values)\n\n            printlock.acquire()\n            print_string = \"{0[0]:6d} {0[1]:8d} {0[2]:>5.2f} \" + \\\n                           \"{0[3]:>7.2f} {0[4]:>8.3f} \" + \\\n                           \"{0[5]:>5.1f} {0[6]:>8.2f} {0[7]:>4.2f} \" + \\\n                           \"{0[8]:>5.2f}\"\n\n            print_array = [gal+1, ID[gal], zobs[gal],\n                           -99, -99,\n                           -99, -99, -99,\n                           -99]\n            print(print_string.format(print_array))\n            printlock.release()\n\n        else:\n            #Find the coordinate of the model with the bestfit mass\n            mi, ti, tvi, fi = np.unravel_index(minind,\n                                                       (n_metal,\n                                                       n_tau, n_tauv, n_fesc))\n\n\n            Masses = np.abs(np.log10(scale*flux_corr))\n            SFRs = np.log10(scale * SFR[:,j,:] * flux_corr)\n\n            mass_hist = np.histogram(Masses.flatten(),\n                                     range = (log_mass_min, log_mass_max),\n                                     bins = 120,\n                                     weights = likelihood.flatten(),\n                                     density = True)\n\n            sfr_hist = np.histogram(SFRs.flatten(),\n                                     range = (log_sfr_min, log_sfr_max),\n                                     bins = 140,\n                                     weights = likelihood.flatten(),\n                                     density = True)\n\n            Bestfit_Mass = np.abs(np.log10(scale[mi, ti, tvi, fi]*flux_corr))\n            Bestfit_SFR = np.abs(np.log10(scale[mi, ti, tvi, fi] *\n                                   SFR[mi, j, ti, tvi, fi]*flux_corr))\n\n            Bestfit_fluxes = (scale[mi, ti, tvi, fi] *\n                              f[j,:, mi, j, ti, tvi, fi] *\n                              flux_corr)\n\n            tgs = tg[j]/1e9\n            tvs = tv[tvi]\n            taus = tau[ti]\n            mis = metallicities[mi]\n            escape_fraction = fesc[fi]\n\n            m16, m50, m84 = weighted_quantile(Masses.flatten(),\n                                              [0.16, 0.5, 0.84],\n                                              sample_weight=likelihood.flatten(),\n                                              values_sorted=False)\n            s16, s50, s84 = weighted_quantile(SFRs.flatten(),\n                                              [0.16, 0.5, 0.84],\n                                              sample_weight=likelihood.flatten(),\n                                              values_sorted=False)\n\n            printlock.acquire()\n\n            MUV_scaled = -99.\n            Bestfit_Beta = -99.\n\n            print_string = \"{0[0]:6d} {0[1]:8d} {0[2]:>5.2f} \" + \\\n                           \"{0[3]:>7.2f} {0[4]:>8.3f} \" + \\\n                           \"{0[5]:>5.1f} {0[6]:>8.2f} {0[7]:>4.2f} \" + \\\n                           \"{0[8]:>5.2f}\"\n\n            print_array = [gal+1, ID[gal], zobs[gal],\n                           Bestfit_Mass, chimin,\n                           tvs, taus, mis,\n                           Bestfit_SFR]\n            print(print_string.format(print_array))\n            printlock.release()\n            output_string = '{n} {id} {zobs} {ztemp} {mass_best} {sfr_best} '+ \\\n                            '{chi_best} {tvs} {taus} {mis} {fesc} '+ \\\n                            '{mass_med} {mass_l68} {mass_u68} ' + \\\n                            '{sfr_med} {sfr_l68} {sfr_u68} ' + \\\n                            '{nfilts} '\n\n            output_values = {'n': gal+1,\n                             'id': ID[gal],\n                             'zobs': zobs[gal], 'ztemp':z[j],\n                             'mass_best': Bestfit_Mass,\n                             'sfr_best': Bestfit_SFR,\n                             'chi_best': chimin,\n                             'tvs': tvs, 'taus': taus,\n                             'mis': mis, 'fesc': escape_fraction,\n                             'mass_med': m50, 'mass_l68': m16, 'mass_u68': m84,\n                             'sfr_med': s50, 'sfr_l68': s16, 'sfr_u68': s84,\n                             'nfilts': np.sum(I)}\n\n            output_array = [gal+1, ID[gal], zobs[gal],\n                            Bestfit_Mass, chimin, tvs, taus, mis,\n                            MUV_scaled, minind, Bestfit_SFR, np.sum(I), -99., '\\n']\n            output = output_string.format(**output_values)\n\n        if include_rest:\n            if np.isinf(chimin) or np.isnan(minind):\n                M_scaled = np.ones(len(flux_obs)) * -99.\n                restframe_output = ' '.join(M_scaled.astype('str'))\n                output = output + restframe_output + ' \\n'\n\n            else:\n                F_rest = np.array(f[0, :, mi, j, ti, tvi, fi] *\n                                  scale[mi, ti, tvi, fi] * flux_corr)\n                restframeMags = 23.9 - 2.5*np.log10(F_rest)\n                restframe_output = ' '.join(restframeMags.astype('str'))\n                output = output + restframe_output + ' \\n'\n        else:\n            output = output + ' \\n'\n\n        printQueue.put([gal, output, mass_hist, sfr_hist, Bestfit_fluxes,\n                        [obs[gal, :], obs_err[gal, :]]])\n\ndef galaxyFitMz(inputQueue, printQueue, printlock):\n    for gal in iter(inputQueue.get, 'STOP'):\n\n        output_string = '{0[0]} {0[1]} {0[2]} {0[3]} {0[4]} {0[5]} ' + \\\n                        '{0[6]} {0[7]} {0[8]} {0[9]} {0[10]} {0[11]} ' + \\\n                        '{0[12]} {0[13]} {0[14]}'\n\n        log_mass_min, log_mass_max = 7, 13\n        log_sfr_min, log_sfr_max = -3, 4\n\n        # Set up output arrays\n        chi_z_best = np.zeros(len(z))\n\n        m_z_best = np.zeros(len(z))\n        m_z_median = np.zeros(len(z))\n        m_z_u68 = np.zeros(len(z))\n        m_z_l68 = np.zeros(len(z))\n\n        sfr_z_best = np.zeros(len(z))\n        sfr_z_median = np.zeros(len(z))\n        sfr_z_u68 = np.zeros(len(z))\n        sfr_z_l68 = np.zeros(len(z))\n\n        #m_z_hist = np.zeros((len(z), 120))\n        #sfr_z_hist = np.zeros((len(z), 140))\n\n        flux_obs = obs[gal,:]\n        flux_err = obs_err[gal,:]\n\n        #flux_obs[fo <= 0.] = 0.       # Set negative fluxes to zero\n        I = np.where(flux_err > 0.)[0] # Find bands with no observation\n\n        if len(I) == 0:\n            output_array = [gal+1, ID[gal], zobs[gal], z[j],\n                            -99, -99, -99, -99, -99, -99, -99,\n                            -99,-99,len(I),-99,'\\n']\n            output = output_string.format(output_array)\n\n            if include_rest:\n                M_scaled = np.ones(len(flux_obs)) * -99.\n                restframe_output = ' '.join(M_scaled.astype('str'))\n                output = output + restframe_output + ' \\n'\n\n            else:\n                output = output + ' \\n'\n            printQueue.put(output_string)\n            continue\n\n\n        flux_obs = flux_obs[I]                    # and exclude from fit\n        flux_err = flux_err[I]\n        tot_err = np.sqrt(flux_err**2 + (params.flux_err*flux_obs)**2)\n\n        for j, jz in enumerate(z):\n            #j = np.argmin(np.abs(z-zobs[gal])) # Find closest model redshift\n            flux_models = f[j,I,:,j]\n\n            top = 0.\n            bottom = 0.\n\n            for i in range(len(flux_obs)):\n                top += (flux_models[i,:]*flux_obs[i])/(tot_err[i]**2)\n                bottom += (flux_models[i,:]**2)/(tot_err[i]**2)\n\n            scale = top/bottom\n            scale = np.reshape(scale, (n_metal, n_tau, n_tauv, n_fesc))\n\n            chisq = 0.\n            for i in range(len(flux_obs)):\n                chisq += ((np.abs(scale*flux_models[i,:]-flux_obs[i])**2)/(tot_err[i])**2)\n\n            chimin, minind = np.nanmin(chisq), np.nanargmin(chisq)\n            likelihood = np.reshape(np.exp(-0.5*chisq),\n                                    (n_metal, n_tau, n_tauv, n_fesc))\n            likelihood[np.isnan(likelihood)] = 0.\n            likelihood = np.abs(likelihood/likelihood.sum())\n\n\n            if np.isinf(chimin) or np.isnan(minind):\n                output_array = [gal+1, ID[gal], zobs[gal], z[j],\n                                -99, -99, -99, -99, -99, -99,\n                                -99,-99,len(I),-99,'\\n']\n                output = output_string.format(output_array)\n\n            else:\n                #Find the coordinate of the model with the bestfit mass\n                mi, ti, tvi, fi = np.unravel_index(minind,\n                                                   (n_metal,\n                                                   n_tau, n_tauv, n_fesc))\n\n                Masses = np.log10(np.abs(scale * flux_corr))\n                SFRs = np.log10(np.abs(scale * SFR[:,j] * flux_corr))\n\n                \"\"\"\n                mass_hist = np.histogram(Masses.flatten(),\n                                         range = (log_mass_min, log_mass_max),\n                                         bins = 120,\n                                         weights = likelihood.flatten(),\n                                         density = True)\n\n                sfr_hist = np.histogram(SFRs.flatten(),\n                                         range = (log_sfr_min, log_sfr_max),\n                                         bins = 140,\n                                         weights = likelihood.flatten(),\n                                         density = True)\n                \"\"\"\n\n                Bestfit_Mass = np.log10(np.abs(scale[mi, ti, tvi, fi]*flux_corr))\n                Bestfit_SFR = np.log10(np.abs(scale[mi, ti, tvi, fi]) *\n                                       SFR[mi, j, ti, tvi, fi]*flux_corr)\n\n\n\n            if np.isnan(Bestfit_Mass) or np.isinf(chimin):\n                Bestfit_Mass = -99\n                #M_scaled[:] = -99\n                tvs = -99\n                taus = -99\n                mis = -99\n                escape_fraction = -99\n\n            else:\n                tvs = tv[tvi]\n                taus = tau[ti]\n                mis = metallicities[mi]\n                escape_fraction = fesc[fi]\n\n            m16, m50, m84 = weighted_quantile(Masses.flatten(),\n                                              [0.16, 0.5, 0.84],\n                                              sample_weight=likelihood.flatten(),\n                                              values_sorted=False)\n            s16, s50, s84 = weighted_quantile(SFRs.flatten(),\n                                              [0.16, 0.5, 0.84],\n                                              sample_weight=likelihood.flatten(),\n                                              values_sorted=False)\n\n            chi_z_best[j] = chimin\n            m_z_best[j] = Bestfit_Mass\n            sfr_z_best[j] = Bestfit_SFR\n\n            m_z_l68[j], m_z_median[j], m_z_u68[j] = m16, m50, m84\n            sfr_z_l68[j], sfr_z_median[j], sfr_z_u68[j] = s16, s50, s84\n\n            MUV_scaled = -99.\n            Bestfit_Beta = -99.\n\n        printlock.acquire()\n        j = np.argmin(np.abs(z-zobs[gal])) # Find closest model redshift\n        print_string = \"{0[0]:6d} {0[1]:8d} {0[2]:>5.2f} \" + \\\n                       \"{0[3]:>7.2f} {0[4]:>8.1f} {0[5]:>8.3f}\"\n\n        print_array = [gal+1, ID[gal], zobs[gal],\n                       m_z_best[j], chi_z_best[j],\n                       sfr_z_best[j]]\n        print(print_string.format(print_array))\n\n        output_string = '{n} {id} {zobs} {ztemp} {mass_best} {sfr_best} '+ \\\n                        '{chi_best} ' + \\\n                        '{mass_med} {mass_l68} {mass_u68} ' + \\\n                        '{sfr_med} {sfr_l68} {sfr_u68} ' + \\\n                        '{nfilts} '\n\n        output_values = {'n': gal+1,\n                         'id': ID[gal],\n                         'zobs': zobs[gal], 'ztemp':z[j],\n                         'mass_best': Bestfit_Mass,\n                         'sfr_best': Bestfit_SFR,\n                         'chi_best': chimin,\n                         'mass_med': m50, 'mass_l68': m16, 'mass_u68': m84,\n                         'sfr_med': s50, 'sfr_l68': s16, 'sfr_u68': s84,\n                         'nfilts': len(I)}\n\n        output = output_string.format(**output_values) + ' \\n'\n\n        printlock.release()\n        printQueue.put([gal, output,\n                        [m_z_best, sfr_z_best, chi_z_best],\n                        [m_z_l68, m_z_median, m_z_u68]\n                        [sfr_z_l68, sfr_z_median, sfr_z_u68]])\n\n\ndef getObservations(inputpath):\n    input_data = Table.read(inputpath,format=input_format).filled(-99.)\n\n    column_names = list(input_data.columns.keys())\n\n    ID = input_data[ID_col]\n    zobs = input_data[z_col]\n\n    filter_names = []\n\n    k,l = 0,0\n    for ii in range(len(column_names)):\n        if column_names[ii].lower().endswith(flux_col_end.lower()):\n            if k == 0:\n                fluxes = input_data[column_names[ii]]\n            else:\n                fluxes = np.column_stack((fluxes,input_data[column_names[ii]]))\n            k+=1\n            filter_names.append(column_names[ii])\n\n        if column_names[ii].lower().endswith(fluxerr_col_end.lower()):\n            if l == 0:\n                fluxerrs = input_data[column_names[ii]]\n            else:\n                fluxerrs = np.column_stack((fluxerrs,input_data[column_names[ii]]))\n            l+=1\n    \"\"\"\n    if filts_used != None:\n        try:\n            fluxes = fluxes[:,filts_used]\n            fluxerrs = fluxerrs[:,filts_used]\n        except:r\n            print('Filter mismatch 1')\n            # Array slicing fail\n    \"\"\"\n    return ID, zobs, fluxes, fluxerrs, k, filter_names\n\nclass _function_wrapper:\n    \"\"\"\n    This is a hack to make the likelihood function pickleable when ``args``\n    or ``kwargs`` are also included.\n\n    Stolen from emcee\n    \"\"\"\n    def __init__(self, f, args, kwargs):\n        self.f = f\n        self.args = args\n        self.kwargs = kwargs\n\n    def __call__(self, x):\n        try:\n            return self.f(x, *self.args, **self.kwargs)\n        except:\n            import traceback\n            print(\"emcee: Exception while calling your likelihood function:\")\n            print(\"  params:\", x)\n            print(\"  args:\", self.args)\n            print(\"  kwargs:\", self.kwargs)\n            print(\"  exception:\")\n            traceback.print_exc()\n            raise\n\ndef weighted_quantile(values, quantiles, sample_weight=None, values_sorted=False, old_style=False):\n    \"\"\" Very close to np.percentile, but supports weights.\n    NOTE: quantiles should be in [0, 1]!\n    :param values: np.array with data\n    :param quantiles: array-like with many quantiles needed\n    :param sample_weight: array-like of the same length as `array`\n    :param values_sorted: bool, if True, then will avoid sorting of initial array\n    :param old_style: if True, will correct output to be consistent with np.percentile.\n    :return: np.array with computed quantiles.\n    \"\"\"\n    values = np.array(values)\n    quantiles = np.array(quantiles)\n    if sample_weight is None:\n        sample_weight = np.ones(len(values))\n    sample_weight = np.array(sample_weight)\n    assert np.all(quantiles >= 0) and np.all(quantiles <= 1), 'quantiles should be in [0, 1]'\n\n    if not values_sorted:\n        sorter = np.argsort(values)\n        values = values[sorter]\n        sample_weight = sample_weight[sorter]\n\n    weighted_quantiles = np.cumsum(sample_weight) - 0.5 * sample_weight\n    if old_style:\n        # To be convenient with np.percentile\n        weighted_quantiles -= weighted_quantiles[0]\n        weighted_quantiles /= weighted_quantiles[-1]\n    else:\n        weighted_quantiles /= np.sum(sample_weight)\n    return np.interp(quantiles, weighted_quantiles, values)\n\nif __name__ == '__main__':\n\n    logfile = open(\"error.log\", \"w\")\n    original_stderr = sys.stderr\n    sys.stderr = logfile\n\n    start = time.time()\n\n    \"\"\"\n    SECTION 1\n\n    \"\"\"\n    model_path = params.model_path\n\n    input_catalog = params.input_catalog\n    input_format = params.input_format\n    z_col = params.z_col\n    ID_col = params.ID_col\n    flux_col_end = params.flux_col_end\n    fluxerr_col_end = params.fluxerr_col_end\n\n    ncpus = params.ncpus\n    filts_used = params.filts_used\n    include_rest = params.include_rest\n\n    output_path = params.output_catalog_path\n    output_format = params.output_format\n    output_hdf_path = params.output_hdf_path\n\n    calc_mode = params.fitting_mode\n    flux_corr = params.flux_corr\n\n\n    ID, zobs, obs, obs_err, filters_found, filter_names = getObservations(input_catalog)\n\n    \"\"\"\n    Section 2\n\n    \"\"\"\n\n\n    print(\"Loading synthetic mags and mass array:\")\n    models = h5py.File(model_path, 'r')\n    tg = models['ages'][()]\n    tv = models['dust'][()]\n    tau = models['sfh'][()]\n    metallicities = models['metallicities'][()]\n    fesc = models['fesc'][()]\n\n    Mshape = models['fluxes'].shape\n    z = models['z']\n    nfilts = Mshape[1]\n    n_metal = Mshape[2]\n    n_tg = Mshape[3]\n    n_tau = Mshape[4]\n    n_tauv = Mshape[5]\n    n_fesc = Mshape[6]\n\n    filt_lambda = models['wl'][()]\n    #UV_flux = synmags['UV_flux']\n    SFR = models['SFR']\n    Ms = models['Ms']\n\n    if params.zp_offsets != None:\n        zp_offsets = Table.read(params.zp_offsets, format='ascii.no_header')['col1']\n\n    if params.temp_err != None:\n        terr_wl, terr_sigma = np.loadtxt(params.temp_err).T\n\n\n    if (nfilts == filters_found) and (filts_used == None):\n        f = models['fluxes']\n\n    elif (nfilts != filters_found) and (filts_used == None):\n        raise Exception('Mis-match between model and observed filter numbers')\n\n    elif filts_used != None:\n        try:\n            f = models['fluxes'][:,filts_used]\n            obs = obs[:,filts_used]\n            obs_err = obs_err[:,filts_used]\n            filter_names = np.array(filter_names)[filts_used]\n        except:\n            print('Mis-match between model and observed filter numbers')\n            raise\n            # Slice fail\n\n\n    print (\"Done.\")\n\n    \"\"\"\n    SECTION 3\n    \"\"\"\n    if os.path.isfile(output_path+\".temp_output.txt\"):\n        os.remove(output_path+\".temp_output.txt\")\n    temp_file = open(output_path+\".temp_output.txt\",\"w\")\n\n\n    \"\"\"\n    SECTION 4\n    Chi-sq calculation\n\n    \"\"\"\n    out_string = '{0:6s} {1:8s} {2:>5s} {3:>7s} {4:>8s}' + \\\n                 '{5:>5s} {6:>8s} {7:>4s} {8:>5s}'\n\n    print(out_string.format('N','ID','zobs','Best', 'chimin',\n                            'tauv','tau','met', 'sfr'))\n\n    loop_start = time.time()\n    ncpus = np.clip(ncpus, 1, multiprocessing.cpu_count())\n\n    inputQueue = multiprocessing.Queue()\n    printQueue = multiprocessing.Queue()\n    printlock = multiprocessing.Lock()\n\n    if calc_mode == 'hist':\n        output_hdf = h5py.File(output_hdf_path, 'w')\n        output_hdf.create_dataset(\"mass_pdf\", (len(ID), 120), dtype=\"f\")\n        output_hdf.create_dataset(\"sfr_pdf\", (len(ID), 140), dtype=\"f\")\n        output_hdf.create_dataset(\"fit_flux\", (len(ID), f.shape[1]), dtype=\"f\")\n        output_hdf.create_dataset(\"obs_flux\", (len(ID), f.shape[1]), dtype=\"f\")\n        output_hdf.create_dataset(\"obs_fluxerr\", (len(ID), f.shape[1]),\n                                  dtype=\"f\")\n        output_hdf.create_dataset(\"lambda_filt\", data = models[\"wl\"])\n        output_hdf.create_dataset(\"fwhm_filt\", data = models[\"fwhm\"])\n\n        fitFunction = galaxyFit2\n\n    elif calc_mode == 'Mz':\n        output_hdf = h5py.File(output_hdf_path, 'w')\n\n        output_hdf.create_dataset(\"m_z_best\", (len(ID), len(z)), dtype=\"f\")\n        output_hdf.create_dataset(\"sfr_z_best\", (len(ID), len(z)), dtype=\"f\")\n        output_hdf.create_dataset(\"chi_z_best\", (len(ID), len(z)), dtype=\"f\")\n\n        output_hdf.create_dataset(\"m_z_median\", (len(ID), len(z)), dtype=\"f\")\n        output_hdf.create_dataset(\"m_z_l68\", (len(ID), len(z)), dtype=\"f\")\n        output_hdf.create_dataset(\"m_z_u68\", (len(ID), len(z)), dtype=\"f\")\n\n        output_hdf.create_dataset(\"sfr_z_median\", (len(ID), len(z)), dtype=\"f\")\n        output_hdf.create_dataset(\"sfr_z_u68\", (len(ID), len(z)), dtype=\"f\")\n        output_hdf.create_dataset(\"sfr_z_l68\", (len(ID), len(z)), dtype=\"f\")\n\n        output_hdf.create_dataset(\"z\", data=z)\n\n        fitFunction = galaxyFitMz\n    else:\n        fitFunction = galaxyFit\n\n    for i in range( ncpus ):\n        multiprocessing.Process(target = fitFunction,\n                                args = (inputQueue, printQueue,\n                                        printlock)).start()\n\n    # Put elements in the send queue for processing\n    for gal in range( len(ID) ):\n        inputQueue.put( gal )\n\n    if calc_mode == 'hist':\n        for i, gal in enumerate(ID):\n            j, out, mass_hist, sfr_hist, fit_flux, obs_flux = printQueue.get()\n\n            if i == 0:\n                mass_centers = 0.5*(mass_hist[1][1:] + mass_hist[1][:-1])\n                sfr_centers = 0.5*(sfr_hist[1][1:] + sfr_hist[1][:-1])\n\n                output_hdf.create_dataset(\"mass_bins\", data = mass_centers)\n                output_hdf.create_dataset(\"sfr_bins\", data = sfr_centers)\n\n            output_hdf[\"mass_pdf\"][j] = mass_hist[0]\n            output_hdf[\"sfr_pdf\"][j] = sfr_hist[0]\n            output_hdf[\"fit_flux\"][j] = fit_flux\n            output_hdf[\"obs_flux\"][j] = obs_flux[0]\n            output_hdf[\"obs_fluxerr\"][j] = obs_flux[1]\n\n            temp_file.write( out )\n\n    elif calc_mode == 'Mz':\n        for i, gal in enumerate(ID):\n            j, out, pz_best, mz_median, sfrz_median = printQueue.get()\n\n            output_hdf[\"m_z_best\"][j,:] = pz_best[0]\n            output_hdf[\"sfr_z_best\"][j,:] = pz_best[1]\n            output_hdf[\"chi_z_best\"][j,:] = pz_best[2]\n\n            output_hdf[\"m_z_l68\"][j,:] = mz_median[0]\n            output_hdf[\"m_z_median\"][j,:] = mz_median[1]\n            output_hdf[\"m_z_u68\"][j,:] = mz_median[2]\n\n            output_hdf[\"sfr_z_l68\"][j,:] = sfrz_median[0]\n            output_hdf[\"sfr_z_median\"][j,:] = sfrz_median[1]\n            output_hdf[\"sfr_z_u68\"][j,:] = sfrz_median[2]\n\n            temp_file.write( out )\n    else:\n        for i, gal in enumerate(ID):\n            printout = printQueue.get()\n            temp_file.write( printout )\n            #print len(mass_array), len(muv_array), len(beta_array)\n\n\n    # Stop all the running processes\n    for i in range( ncpus ):\n        inputQueue.put( 'STOP' )\n\n    # Close both send and receive queues\n    inputQueue.close()\n    printQueue.close()\n\n    temp_file.close()\n    models.close()\n    output_hdf.close()\n    print(\"Fitting time taken: {:.2f} {}\".format(time.time()-loop_start,\n                                                   '\\n'))\n\n    \"\"\"\n    Section 3\n    Reload, format and save output table\n    \"\"\"\n    while temp_file.closed == False:\n        pause(0.1)\n\n    data = np.loadtxt(output_path+\".temp_output.txt\")\n    try:\n        rows, cols = data.shape\n    except:\n        cols = len(data)\n\n    output = Table()\n\n    names = ['N', 'ID', 'z', 'zmodel',\n             'Mass_best', 'SFR_best', 'chi_best',\n             'Dust_best', 'SFH_best',\n             'Metallicity_best', 'fesc_best',\n             'Mass_median', 'Mass_l68', 'Mass_u68',\n             'SFR_median', 'SFR_l68', 'SFR_u68',\n             'Nfilts']\n\n    units = [None, None, None, None,\n             u.Msun, u.Msun/u.yr, None,\n             None, None,\n             None, None,\n             u.Msun, u.Msun, u.Msun,\n             u.Msun/u.yr, u.Msun/u.yr, u.Msun/u.yr,\n             None]\n\n    types = ['i4', 'i4', 'f4', 'f4',\n             'f4', 'f4', 'f4',\n             'f4', 'f4',\n             'f4', 'f4',\n             'f4', 'f4', 'f4',\n             'f4', 'f4', 'f4',\n             'i4']\n\n    if include_rest:\n        for name in filter_names:\n            names.append(name[:-len(flux_col_end)]+'_rest')\n            units.append(u.mag)\n            types.append('f4')\n\n    for col in range(cols):\n        column = Column( data[:,col], name = names[col], unit=units[col], dtype=types[col])\n        output.add_column(column)\n\n    table_format = params.output_format\n    output.sort('ID')\n    if os.path.isfile(output_path):\n        os.remove(output_path)\n    output.write(output_path,format=table_format, overwrite=True)\n    print('Catalog saved')\n\n    os.remove(temp_file.name)\n\n    print('\\n')\n    print(\"Total time taken: \"+str(time.time()-start))\n\n    sys.stderr = original_stderr\n    logfile.close()\n", "meta": {"hexsha": "6b48c40c998b401f11b9c5fed2381fe149f1c4ac", "size": 33271, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/fitting.py", "max_stars_repo_name": "dunkenj/smpy", "max_stars_repo_head_hexsha": "2c7ad73726e8fcfbbdf3667a918f60890c84673f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2015-04-09T13:51:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T00:25:05.000Z", "max_issues_repo_path": "scripts/fitting.py", "max_issues_repo_name": "bamford/smpy", "max_issues_repo_head_hexsha": "2c7ad73726e8fcfbbdf3667a918f60890c84673f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-04-29T13:00:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-17T13:50:16.000Z", "max_forks_repo_path": "scripts/fitting.py", "max_forks_repo_name": "dunkenj/smpy", "max_forks_repo_head_hexsha": "2c7ad73726e8fcfbbdf3667a918f60890c84673f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-08-12T13:15:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-07T14:05:43.000Z", "avg_line_length": 37.0088987764, "max_line_length": 228, "alphanum_fraction": 0.4974602507, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 8858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19997006613770812}}
{"text": "import numpy as np\nfrom numpy.random import uniform\nimport json\nimport math\nfrom utils.quaternion import Quaternion\nfrom utils.quaternion import computeAngVel, computeAngVelRel\n\nfrom Kinematic.py import KinematicCore\n\nclass JointType():\n    BASE     = 0\n    FIXED    = 1\n    REVOLUTE = 2\n    SPHERE   = 3\n\n# pose dof for joints\nDof = {\n    JointType.BASE:       4,\n    JointType.FIXED:      0,\n    JointType.REVOLUTE:   1,\n    JointType.SPHERE:     4,\n}\n\n# exp dof for joints\nExpDof = {\n    JointType.BASE:       0,\n    JointType.FIXED:      0,\n    JointType.REVOLUTE:   1,\n    JointType.SPHERE:     3,\n}\n\nNAME2TYPE={\n    \"none\":       JointType.BASE,\n    \"fixed\":      JointType.FIXED,\n    \"revolute\":   JointType.REVOLUTE,\n    \"spherical\": JointType.SPHERE,\n}\n\nPOSE2QUAT={\n    JointType.BASE:       lambda x: Quaternion(x[0], x[1], x[2], x[3]),\n    JointType.FIXED:      lambda x: Quaternion(1, 0, 0, 0),\n    JointType.REVOLUTE:   lambda x: Quaternion(math.cos(x/2), 0.0, 0.0, math.sin(x/2)),\n    JointType.SPHERE:     lambda x: Quaternion(x[0], x[1], x[2], x[3]),\n}\n\nVEL2OMG={\n    JointType.BASE:       lambda x: np.array([x[0], x[1], x[2]]),\n    JointType.FIXED:      lambda x: np.array([0, 0, 0]),\n    JointType.REVOLUTE:   lambda x: np.array([0, 0, x[0]]),\n    JointType.SPHERE:     lambda x: np.array([x[0], x[1], x[2]]),\n}\n\nclass Joint(object):\n    def __init__(self, info):\n        \"\"\"\n            Inputs:\n                info  json item load from character file\n        \"\"\"\n        self._pos       = np.array([info[\"AttachX\"], info[\"AttachY\"], info[\"AttachZ\"]])\n        self._name      = info[\"Name\"]\n        self._parent_id = info[\"Parent\"]\n        self._parent    = None\n        self._type_name = info['Type']\n        self._type      = NAME2TYPE[info['Type']]\n        self._dof       = Dof[self._type]\n        self._expdof    = ExpDof[self._type]\n        self._w         = info[\"DiffWeight\"]\n        self._is_end_effector = info[\"IsEndEffector\"]\n\n        if self._type is JointType.REVOLUTE:\n            self._torque_lim = [info[\"TorqueLim\"]]\n        elif self._type is JointType.SPHERE:\n            if \"TorqueLimX\" not in info:\n                self._torque_lim = [info[\"TorqueLim\"]]*4\n            else:\n                self._torque_lim = [info[\"TorqueLimX\"], info[\"TorqueLimY\"], info[\"TorqueLimZ\"], 0]\n        else:\n            self._torque_lim = [0]*4\n\n        if self._type is JointType.REVOLUTE:\n            self.limlow = np.array([info[\"LimLow0\"]])\n            self.limhigh = np.array([info[\"LimHigh0\"]])\n        elif self._type is JointType.SPHERE:\n            self.limlow = -3.14 * np.ones(3)\n            self.limhigh = 3.14 * np.ones(3)\n        else:\n            self.limlow = np.array([])\n            self.limhigh = np.array([])\n\n        self.pose = np.zeros(self._dof)\n        self.pose2quat = POSE2QUAT[self._type]\n        self.quat = Quaternion(1, 0, 0, 0)\n\n        self.vel = np.zeros(self._dof)\n        self.vel2omg = VEL2OMG[self._type]\n        self.omg = np.zeros(3)\n\n    def __unicode__(self):\n        info = u\"Joint: name %s, pos %s, parent %d\" % (self._name, str(self._pos), self._parent_id)\n        return info\n\n    __str__ = __unicode__\n    __repr__= __unicode__\n\n    def dof(self):\n        return self._dof\n\n    def expdof(self):\n        return self._expdof\n\n    def local_pos(self):\n        return self._pos\n\n    def set_pose(self, pose):\n        assert(pose.shape == self.pose.shape)\n        self.pose = pose\n        # calculate quat\n        self.quat = self.pose2quat(pose)\n\n    def set_vel(self, vel):\n        assert(vel.shape == self.vel.shape)\n        self.omg = self.vel2omg(vel)\n\n    def get_quat(self):\n        return self.quat\n\n    def get_omg(self):\n        return self.omg\n\n    def get_parent(self):\n        return self._parent_id\n\n    def get_a_min(self):\n        std = (self.limhigh - self.limlow) / 2\n        mean = (self.limhigh + self.limlow) / 2\n        a_min = mean - std*2\n        return a_min\n\n    def get_a_max(self):\n        std = (self.limhigh - self.limlow) / 2\n        mean = (self.limhigh + self.limlow) / 2\n        a_max = mean + std*2\n        return a_max\n\nclass Body:\n    def __init__(self, info):\n        self._info = info\n        self._pos = np.array([info[\"AttachX\"], info[\"AttachY\"], info[\"AttachZ\"]])\n        self._name = info[\"Name\"]\n        self._joint_id = info[\"ID\"]\n\n    def get_joint_id(self):\n        return self._joint_id\n\n    def get_local_pos(self):\n        return self._pos\n    \n    def get_body_name(self):\n        return self._name\n    \n    def get_body_shape(self):\n        return self._info[\"Shape\"]\n    \n    def get_body_size(self):\n        ar = np.array([self._info[\"Param0\"], self._info[\"Param1\"], self._info[\"Param2\"]])\n        shape = self.get_body_shape()\n        if shape == \"sphere\":\n            ar /= 2.0\n        if shape == \"capsule\":\n            ar[0] /= 2.0\n            ar[2] /= 2.0\n        return ar\n\nclass HumanoidSkeleton(object):\n    \"\"\" Store humanoid skeleton information, can perform following functions:\n\n            1) compute link positions and velocities when given character pose and vel\n            2) construct character state when given root position and orintaion\n            3) slerp between two character poses\n            4) transfer between action and target poses\n\n            __init__()\n                 _calc_kin_info()\n                 _calc_ctrl_info()\n\n            set_pose()\n\n            set_vel()\n\n            build_state()\n\n            slerp()\n\n            pose representation:\n                - root pos (x, y, z)\n                - root rot (w, x, y, z) in world frame\n                - joint rots theta or (w, z, y, z) in local frame, VelRel\n\n            vel w/ padding representation:\n                - root vel (vx, vy, vz)\n                - root angular vel (wx, wy, wz) in world frame\n                - joint angular vel w or (wx, wy, wz, 0) in local frame, VelRel\n\n            vel w/o padding representation\n                - root vel (vx, vy, vz)\n                - root angular vel (wx, wy, wz) in world frame\n                - joint angular vel w or (wx, wy, wz) in local frame, VelRel\n\n            state\n                - Y coordinate of origin pos\n                - Root link's pos (x, y, z) in xyz coordinate\n                - Root link's quat (W, X, Y, Z) in XYZ coordinate\n                - Other links' pos (x, y, z) and quat (w, x, y, z) in xyz coordinate\n                - Root link's vel (Vx, Vy, Vz) in XYZ coordinate\n                - Root link's omega (Wx, Wy, Wz) in XYZ coordinate\n                - Other links' vel (vx, vy, vz) and omg (wx, wy, wz) in xyz coordinate\n\n                xyz's origin is set by origin_pos, or character's root joint\n                xyz's rotation is calculated by rotating Y-axis to make X-axis to heading\n                direction calculated by origin_rot or root joint's rotation\n\n            action\n                - no root pose or joint\n                - angle-axis (\\theta, nx, ny, nz) for spherical joints and \\theta for\n                    revolute joints\n\n            action represented in exponential map\n                - no root pose or joint\n                - exponential map (\\Omega_x, \\Omega_y, \\Omega_z) for spherical joints and\n                    \\theta for revolute joints\n    \"\"\"\n\n    def __init__(self, char_file, ctrl_file):\n        # NOTICE humanoid.txt and humanoid.urdf have different scales, urdf is 4x larger\n        self._kin_core = KinematicCore.cKinematicCore(char_file)\n\n        ### all private members\n        self.joints = None\n        self.bodys  = None\n        self.dof    = None\n        self.expdof = None\n\n        # TODO move to function\n        self.num_joints  = None\n        self.joint_types = None\n        self.joint_dof   = None\n        self.pos_start   = None     # start position in pose/vel vec\n        self.act_start   = None     # start position in action vec\n        self.joint_w     = None\n\n        # control configuration\n        self.kp = None\n        self.kd = None\n        self.a_max = None\n        self.a_min = None\n\n        ### all private members\n        self._calc_kin_info(char_file)\n        self._calc_ctrl_info(ctrl_file)\n\n    def _calc_kin_info(self, char_file):\n        # handle character skeleton information\n        with open(char_file, 'r') as f:\n            json_data = json.load(f)\n            joints_data = json_data[\"Skeleton\"][\"Joints\"]\n            bodys_data = json_data[\"BodyDefs\"]\n\n        # build for pose/vel transfer\n        self.joints = list(map(lambda x: Joint(x),  joints_data))\n        self.bodys  = list(map(lambda x: Body(x),   bodys_data))\n\n        self.dof = sum(map(lambda x: x.dof(), self.joints)) + 3\n        self.expdof = sum(map(lambda x: x.expdof(), self.joints))\n\n        # build velocity padding - compressing\n        self.comp2pad = [0, 1, 2]  # root vel\n        p_off = 3\n        for j in self.joints:\n            if j.dof() == 1:\n                self.comp2pad += [p_off]\n                p_off += 1\n            if j.dof() == 4:\n                self.comp2pad += [p_off, p_off+1, p_off+2]\n                p_off += 4\n\n        self.comp2pad = np.array(self.comp2pad, dtype=np.int)\n\n        # build joint infomation mat\n        self.num_joints     = len(self.joints)\n        self.joint_types    = list(map(lambda x: x._type,   self.joints))\n        self.joint_w        = list(map(lambda x: x._w,      self.joints))\n        self.joint_dof      = list(map(lambda x: x.dof(),   self.joints))\n        self.joint_dof      = np.array(self.joint_dof, dtype=np.int)\n        self.joint_expdof   = list(map(lambda x: x.expdof(),self.joints))\n        self.joint_expdof   = np.array(self.joint_expdof, dtype=np.int)\n        self.end_effectors  = list(filter(\n                                                        lambda x: self.joints[x]._is_end_effector,\n                                                        range(self.num_joints)))\n\n        self.pos_start = np.zeros(self.num_joints, dtype=np.int)  # start offset for each joint in pos vector\n        for i in range(1, self.num_joints):\n            self.pos_start[i] = self.pos_start[i-1] + self.joint_dof[i-1]\n\n        self.exp_start = np.zeros(self.num_joints, dtype=np.int)  # start offset for each joint in exp vector\n        for i in range(1, self.num_joints):\n            self.exp_start[i] = self.exp_start[i-1] + self.joint_expdof[i-1]\n\n        self.pos_start += 3                     # offset for root pos\n        self.act_start = self.pos_start - 7     # 7 dim for root pos and root joint\n                                                                                        # so the act_start[0] is meaningless\n\n        self.joint_mat = np.array([\n                                                                self.joint_types, self.joint_dof,\n                                                                self.pos_start, self.act_start,\n                                                            ], dtype=np.int)\n        self.joint_mat = self.joint_mat.transpose()\n\n    def _calc_ctrl_info(self, ctrl_file):\n        \"\"\" Build Kp, Kd and torque_lim\n        \"\"\"\n        # handle controller information\n        with open(ctrl_file, 'r') as f:\n            data = json.load(f)\n            controller = data[\"PDControllers\"]\n            assert(len(data[\"PDControllers\"]) == self.num_joints)\n\n        self.kp = [0,0,0] # for root pos\n        self.kd = [0,0,0] # for root pos\n        self.torque_lim = [0, 0, 0] # for root pos\n        for i in range(self.num_joints):\n            if self.joint_types[i] is not JointType.FIXED:\n                self.kp += [controller[i][\"Kp\"]] * self.joint_dof[i]\n                self.kd += [controller[i][\"Kd\"]] * self.joint_dof[i]\n                self.torque_lim += self.joints[i]._torque_lim\n\n        self.kp = np.array(self.kp)\n        self.kd = np.array(self.kd)\n        self.torque_lim = np.array(self.torque_lim)\n\n    def build_a_min(self):\n        a_mins = [j.get_a_min() for j in self.joints]\n        a_min = np.concatenate(a_mins)\n        assert(a_min.size == self.expdof)\n        return a_min\n\n    def build_a_max(self):\n        a_maxs = [j.get_a_max() for j in self.joints]\n        a_max = np.concatenate(a_maxs)\n        assert(a_max.size == self.expdof)\n        return a_max\n\n    def get_link_ids(self):\n        return list(range(len(self.bodys)))\n\n    def get_link_names(self):\n        return list(map(lambda body: body.get_body_name(), self.bodys))\n\n    def get_link_shapes(self):\n        return list(map(lambda body: body.get_body_shape(), self.bodys))\n\n    def get_link_sizes(self):\n        return list(map(lambda body: body.get_body_size().tolist(), self.bodys))\n\n    def set_pose(self, pose):\n        \"\"\" Set character's pose\n\n        Inputs:\n            pose   np.array of float, should be equal to self.dof\n        \"\"\"\n        assert(pose.size == self.dof)\n        self._kin_core.setPose(pose)\n\n    def set_vel(self, vel):\n        \"\"\" Set character's velocity\n\n            *NOTICE* set_pose should be already called\n\n        Inputs:\n            vel  numpy array of velocity, shoubld be equal to self.dof\n        \"\"\"\n        assert(vel.size == self.dof)\n        self._kin_core.setVel(vel)\n\n    def set_heading_vec(self, head):\n        \"\"\" Set heading vector\n\n        \"\"\"\n        assert(len(head) == 3)\n        self._kin_core.setHeadingVec(head)\n\n    def build_state(self, origin_pos=None, origin_rot=None, root_global=True):\n        \"\"\" Build character state\n\n            Inputs:\n                origin_pos      new coordinate's origin (x, y, z)\n                origin_rot      reference rotation (w, x, y, z), then a heading direction\n                                                is calculated as new coordinate's x-axis\n\n            Outputs:\n                state           np.array of float\n        \"\"\"\n        if origin_pos is None and origin_rot is None:\n            state = self._kin_core.buildState()\n            state = np.array(state)\n        elif origin_pos is not None and origin_rot is not None:\n            state = self._kin_core.buildState(origin_pos, origin_rot, root_global)\n        else:\n            raise ValueError(\"not implemented yet\")\n        return state\n\n    def build_state2(self):\n        state = self._kin_core.buildState2()\n        return np.array(state)\n\n    def get_com_pos(self):\n        \"\"\" Return CoM position\n\n            *NOTICE* set_pose should be already called\n        \"\"\"\n        return np.array(self._kin_core.getCoMPos())\n\n    def get_com_vel(self):\n        \"\"\" Return CoM velocity\n\n            *NOTICE* set_pose and set_vel should be already called\n        \"\"\"\n        return np.array(self._kin_core.getCoMVel())\n\n    def slerp(self, pose0, pose1, t):\n        \"\"\" slerp between two poses\n\n            Inputs:\n                pose0   np.array of float, start pose\n                pose1   np.array of float, end pose\n                t       float in [0, 1], interpolating parameter\n\n            Outputs:\n                pose_t  np.array of float, interpolated pose\n        \"\"\"\n\n        assert(pose0.size == self.dof)\n        assert(pose1.size == self.dof)\n\n        pose_t = self._kin_core.slerp(pose0, pose1, t)\n        pose_t = np.array(pose_t)\n\n        return pose_t\n\n    def computeVel(self, pose0, pose1, dt, padding=True):\n        \"\"\" Compute velocity between two poses\n\n            Inputs:\n                pose0   np.array of float, start pose\n                pose1   np.array of float, end pose\n                dt      float, duraction between two poses\n\n            Outputs:\n                avg_vel np.array of float, vel (w/ or w/o padding)\n        \"\"\"\n        assert(pose0.size == self.dof)\n        assert(pose1.size == self.dof)\n\n        avg_vel = np.zeros_like(pose0)\n\n        root0 = pose0[:3]\n        root1 = pose1[:3]\n        avg_vel[:3] = (root1 - root0) / dt\n\n        offset = 3\n\n        # root angular velocity is in world coordinate\n        dof = self.joint_dof[0]\n        quat0 = Quaternion.fromWXYZ(pose0[offset:offset+dof])\n        quat1 = Quaternion.fromWXYZ(pose1[offset:offset+dof])\n        avg_vel[offset : offset+3] = computeAngVel(quat0, quat1, dt)\n        offset += dof\n\n        # other joints\n        for i in range(1, self.num_joints):\n            dof = self.joint_dof[i]\n            if dof == 1:  # revolute\n                theta0 = pose0[offset]\n                theta1 = pose1[offset]\n                avg_vel[offset] = (theta1 - theta0) / dt\n            elif dof == 4:  # spherical\n                quat0 = Quaternion.fromWXYZ(pose0[offset:offset+dof])\n                quat1 = Quaternion.fromWXYZ(pose1[offset:offset+dof])\n                avg_vel[offset : offset+3] = computeAngVelRel(quat0, quat1, dt)\n            offset += dof\n\n        if padding is False:\n            avg_vel = avg_vel[self.comp2pad]\n\n        return avg_vel\n\n    def toLocalFrame(self, pose, vel, ori_pos=None, ori_rot=None):\n        \"\"\" Convert pose and vel from world frame to local frame,\n                the local frame heading direction is rotated x-axis\n\n            Inputs:\n                pose        np.array of float, character pose\n                vel         np.array of float, character vel w/ padding\n                ori_pos     np.array of float, 3 dim, position of local coordinate origin\n                ori_rot     np.array of float, 4 dim, (w, x, y, z) quat of local coordinate orientation\n\n            Outputs:\n                local_pose\n                local_vel\n        \"\"\"\n        if ori_pos is None:\n            ori_pos = pose[:3]\n        if ori_rot is None:\n            ori_rot = pose[3:7]\n\n        # heading theta\n        inv_ori_rot = self.buildHeadingTrans(ori_rot)\n\n        local_pos = pose.copy()\n        local_vel = vel.copy()\n\n        # ignore y difference, because local cooridnate shares xoz plane with world\n        local_pos[0] -= ori_pos[0]                      # root x pos\n        local_pos[2] -= ori_pos[2]                      # root y pos\n\n        ori_rot = Quaternion.fromWXYZ(ori_rot)\n        ori_rot = inv_ori_rot.mul(ori_rot)\n        local_pos[3:7] = ori_rot.pos_wxyz()              # root orientation\n\n        local_vel[:3] = inv_ori_rot.rotate(vel[:3])      # root velocity\n        local_vel[3:6] = inv_ori_rot.rotate(vel[3:6])    # root angular velocity\n\n        return local_pos, local_vel\n\n    def buildHeadingTrans(self, rot):\n        \"\"\" Build the rotation that rotate to local coordinate\n            rot     np.array of float, 4 dim, (w, x, y, z) quat of coordinate orientation\n        \"\"\"\n        theta = self._kin_core.getHeadingTheta(rot)\n        inv_rot = Quaternion.fromExpMap(np.array([0, -theta, 0]))\n        return inv_rot\n\n    def compressVel(self, vel):\n        \"\"\" Squeeze velocity from padded to compressed\n\n            Inputs:\n                vel     np.array of float, vel w/ padding\n\n            Outputs:\n                vel_cmp np.array of float, vel w/o padding\n        \"\"\"\n        vel_cmp = vel[self.comp2pad]\n        return vel_cmp\n\n    def padVel(self, vel):\n        \"\"\" Pad velocity from compressed to padded\n\n            Inputs:\n                vel     np.array of float, vel w/o padding\n\n            Outputs:\n                vel_pad np.array of float, vel w/ padding\n        \"\"\"\n        vel_pad = np.zeros(self.dof)\n        vel_pad[self.comp2pad] = vel\n        return vel_pad\n\n    def action_to_targ_pose(self, action):\n        \"\"\" Converte action to PD controller target pose\n\n            Inputs:\n                action      np.array of float, action which DeepMimicSim can take in\n\n            Outputs:\n                pose        np.array of float, pose of character\n        \"\"\"\n        assert(action.size == self.dof - 7)\n\n        targ_pose = np.zeros(self.dof)\n        targ_pose[3] = 1\n        for i in range(1, self.num_joints):\n            dof = self.joint_dof[i]\n            p_off = self.pos_start[i]\n            a_off = self.act_start[i]\n            if dof == 1:  # revolute\n                targ_pose[p_off] = action[a_off]\n            elif dof == 4:  # spherical\n                angle = action[a_off]\n                axis = action[a_off+1:a_off+4]\n                quata = Quaternion.fromAngleAxis(angle, axis)\n                targ_pose[p_off : p_off+4] = quata.wxyz()\n\n        assert(np.isfinite(sum(targ_pose))), embed() #(action, targ_pose)\n        return targ_pose\n\n    def targ_pose_to_action(self, pose):\n        \"\"\" Convert desired pose to action\n\n            Inputs:\n                pose        np.array of float, pose of character\n\n            Outputs:\n                action      np.array of float, action which DeepMimicSim can take in\n        \"\"\"\n        assert(pose.size == self.dof)\n\n        action = np.zeros(self.dof-7)\n        for i in range(1, self.num_joints):\n            dof = self.joint_dof[i]\n            p_off = self.pos_start[i]\n            a_off = self.act_start[i]\n            if dof == 1:  # revolute\n                action[a_off] = pose[p_off]\n            elif dof == 4:  # spherical\n                quata = Quaternion.fromWXYZ(pose[p_off:p_off+4])\n                action[a_off : a_off+4] = quata.angaxis()\n\n        assert(np.isfinite(sum(action))), embed() #(action, targ_pose)\n        return action\n\n    def action_as_offset(self, pose, action):\n        \"\"\" Take action as offset of a given reference pose, return standard action\n\n            Inputs:\n                pose        np.array of float, pose of character\n                action      np.array of float, offset action to the character\n\n            Outputs:\n                new_action  np.array of float, standard action which DeepMimicSim can take in\n        \"\"\"\n        assert(pose.size == self.dof)\n        assert(action.size == self.dof - 7)\n\n        new_action = self._kin_core.actionAsOffset(pose, action.tolist())\n\n        return new_action\n\n    def exp_to_action(self, expmap):\n        \"\"\" Convert action represented in exponential map to angle-axis action\n                which deepmimic_sim can take in\n\n            Inputs:\n                expmap      np.array of float, action represented in exponential map\n\n            Outputs:\n                action      np.array of float, action for deepmimic environment\n        \"\"\"\n        assert(expmap.size == self.expdof)\n        action = np.zeros(self.dof-7)\n\n        for i in range(1, self.num_joints):\n            dof = self.joint_dof[i]\n            e_off = self.exp_start[i]\n            a_off = self.act_start[i]\n            if dof == 1:  # revolute\n                action[a_off] = expmap[e_off]\n            elif dof == 4:  # spherical\n                quata = Quaternion.fromExpMap(expmap[e_off:e_off+3])\n                action[a_off:a_off+4] = quata.angaxis()\n\n        assert(np.isfinite(sum(action))), embed() #(action, targ_pose)\n        return action\n\n\n    def exp_to_targ_pose(self, expmap, padding=True):\n        \"\"\" Convert action represented in exponential map to angle-axis action\n                which deepmimic_sim can take in\n\n            Inputs:\n                expmap      np.array of float, action represented in exponential map\n\n            Outputs:\n                pose        np.array of float, pose of character\n        \"\"\"\n        assert(expmap.size == self.expdof)\n        return self._kin_core.expMapToTargetPose(expmap.tolist(), padding)\n\n    def exp_to_targ_pose_old(self, expmap):\n        \"\"\" Convert action represented in exponential map to angle-axis action\n                which deepmimic_sim can take in\n\n            Inputs:\n                expmap      np.array of float, action represented in exponential map\n\n            Outputs:\n                pose        np.array of float, pose of character\n        \"\"\"\n        assert(expmap.size == self.expdof)\n        pose = np.zeros(self.dof)\n\n        for i in range(1, self.num_joints):\n            dof = self.joint_dof[i]\n            e_off = self.exp_start[i]\n            p_off = self.pos_start[i]\n            if dof == 1:  # revolute\n                pose[p_off] = expmap[e_off]\n            elif dof == 4:  # spherical\n                quata = Quaternion.fromExpMap(expmap[e_off:e_off+3])\n                pose[p_off:p_off+4] = quata.wxyz()\n\n        assert(np.isfinite(sum(pose))), embed() #(action, targ_pose)\n        return pose\n\n    def targ_pose_to_exp(self, pose):\n        \"\"\" Convert target pose to exponential map, used as initialization of\n                Actor_FDM reference memory\n\n            Inputs:\n                pose        np.array of float, pose of character\n\n            Outputs:\n                exp         np.array of float, action represented in exponential map\n        \"\"\"\n        assert(pose.size == self.dof)\n\n        expmap = np.zeros(self.expdof)\n        for i in range(1, self.num_joints):\n            dof = self.joint_dof[i]\n            p_off = self.pos_start[i]\n            e_off = self.exp_start[i]\n            if dof == 1:  # revolute\n                expmap[e_off] = pose[p_off]\n            elif dof == 4:  # spherical\n                quata = Quaternion.fromWXYZ(pose[p_off:p_off+4])\n                expmap[e_off : e_off+3] = quata.expmap()\n\n        assert(np.isfinite(sum(expmap))), embed() #(action, targ_pose)\n        return expmap\n\n    def normalize_target_pose(self, pose):\n        \"\"\"\n            normalize given pose to make quaternions norm as 1\n        \"\"\"\n        assert(pose.size == self.dof)\n        norm_pose = pose.copy()\n        for i in range(self.num_joints):\n            dof = self.joint_dof[i]\n            p_off = self.pos_start[i]\n            if dof == 4:  # spherical\n                quata = Quaternion.fromWXYZ(pose[p_off:p_off+4])\n                norm_pose[p_off : p_off+4] = quata.pos_wxyz()\n\n        assert(np.isfinite(sum(norm_pose))), embed() #(action, targ_pose)\n        return norm_pose\n\n    def pose_wxyz_to_xyzw(self, pose):\n        pose_new = pose.copy()\n\n        p_off = 3\n        quat = pose[p_off:p_off+4]\n        pose_new[p_off:p_off+3] = quat[1:]\n        pose_new[p_off+3] = quat[0]\n\n        for i in range(1, self.num_joints):\n            dof = self.joint_dof[i]\n            p_off = self.pos_start[i]\n            if dof == 4:\n                quat = pose[p_off:p_off+4]\n                pose_new[p_off:p_off+3] = quat[1:]\n                pose_new[p_off+3] = quat[0]\n\n        return pose_new\n\n    def get_reward(self, pose0, vel0, pose1, vel1):\n        assert(len(pose0) == self.dof), \"pose 0 size missmatch\"\n        assert(len(pose1) == self.dof), \"pose 1 size missmatch\"\n        assert(len(vel0) == self.dof), \"vel 0 size missmatch\"\n        assert(len(vel1) == self.dof), \"vel 1 size missmatch\"\n        return self._kin_core.calcReward(pose0, vel0, pose1, vel1)\n\n    def get_reward2(self, pose0, vel0, pose1, vel1):\n        assert(len(pose0) == self.dof), \"pose 0 size missmatch\"\n        assert(len(pose1) == self.dof), \"pose 1 size missmatch\"\n        assert(len(vel0) == self.dof), \"vel 0 size missmatch\"\n        assert(len(vel1) == self.dof), \"vel 1 size missmatch\"\n        return self._kin_core.calcReward2(pose0, vel0, pose1, vel1)\n\n    def get_err_vec(self, pose0, vel0, pose1, vel1):\n        assert(len(pose0) == self.dof), \"pose 0 size missmatch\"\n        assert(len(pose1) == self.dof), \"pose 1 size missmatch\"\n        assert(len(vel0) == self.dof), \"vel 0 size missmatch\"\n        assert(len(vel1) == self.dof), \"vel 1 size missmatch\"\n        self._kin_core.calcReward(pose0, vel0, pose1, vel1)\n        return np.array(self._kin_core.getErrorVec())\n\n    def get_sub_rewards(self, pose0, vel0, pose1, vel1):\n        err_vec = self.get_err_vec(pose0, vel0, pose1, vel1)\n        scale = np.array([2, 0.1, 40, 5, 10])\n        sub_rewards = np.exp(- scale * err_vec)\n        return sub_rewards\n\n    def lowest_height(self, pose):\n        return self._kin_core.lowestHeight(pose)\n\n    def disturb_pose(self, pose, noise):\n        \"\"\" uniform disturb pose\n\n            pose\n            noise  float, deviation angle in radius\n        \"\"\"\n        new_pose = pose.copy()\n\n        noise3d = noise / np.sqrt(3)\n        new_pose[:3] += uniform(-noise3d, noise3d, 3)\n\n        for jstar, jdof in zip(self.pos_start, self.joint_dof):\n            if jdof == 1:\n                new_pose[jstar] += uniform(-noise, noise)\n            elif jdof == 4:\n                noise_quat = Quaternion.fromExpMap(uniform(-noise3d, noise3d, 3))\n                ori_quat = Quaternion.fromWXYZ(pose[jstar:jstar+4])\n                new_quat = noise_quat.mul(ori_quat)\n                new_pose[jstar:jstar+4] = new_quat.wxyz()\n            elif jdof == 0:\n                pass\n            else:\n                assert(False and \"not support jdof other than 1 and 4\")\n\n        return new_pose\n\n    def disturb_vel(self, vel, noise):\n        \"\"\" uniform disturb vel\n\n            vel\n            noise  float, deviation angle in radius\n        \"\"\"\n        new_vel = vel.copy()\n\n        noise3d = noise / np.sqrt(3)\n        new_vel[:3] += uniform(-noise3d, noise3d, 3)\n\n        for jstar, jdof in zip(self.pos_start, self.joint_dof):\n            if jdof == 1:\n                new_vel[jstar] += uniform(-noise, noise)\n            elif jdof == 4:\n                new_vel[jstar:jstar+3] += uniform(-noise3d, noise3d, 3)\n            elif jdof == 0:\n                pass\n            else:\n                assert(False and \"not support jdof other than 1 and 4\")\n\n        return new_vel\n    \n    def get_joint_global_pos(self, id):\n        return list(self._kin_core.getJointPos(id))\n    \n    def get_joint_global_quat(self, id):\n        return list(self._kin_core.getJointQuat(id))\n    \n    def get_body_global_pos(self, id):\n        return list(self._kin_core.getBodyPos(id))\n    \n    def get_feature(self):\n        return self._kin_core.getFeature()\n    \n    def inv_feature(self, pos):\n        return self._kin_core.invFeature(pos)\n", "meta": {"hexsha": "c58018d4b551c6eb0ceb9485fb5796db404eb713", "size": 29689, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/humanoid_kin.py", "max_stars_repo_name": "arpspoof/Jump", "max_stars_repo_head_hexsha": "1c9c1bd5c499e24bab25eb7decaa772b60798794", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2021-04-25T03:36:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T00:23:59.000Z", "max_issues_repo_path": "utils/humanoid_kin.py", "max_issues_repo_name": "squalidux/Jump", "max_issues_repo_head_hexsha": "1c9c1bd5c499e24bab25eb7decaa772b60798794", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-05-25T10:04:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T01:54:00.000Z", "max_forks_repo_path": "utils/humanoid_kin.py", "max_forks_repo_name": "squalidux/Jump", "max_forks_repo_head_hexsha": "1c9c1bd5c499e24bab25eb7decaa772b60798794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-04-25T03:05:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-05T19:58:01.000Z", "avg_line_length": 34.6429404901, "max_line_length": 124, "alphanum_fraction": 0.5538414901, "include": true, "reason": "import numpy,from numpy", "num_tokens": 7485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.3174262785020255, "lm_q1q2_score": 0.19990700992345709}}
{"text": "# -*- coding: utf-8 -*-\nfrom os.path import dirname, exists, join\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom astropy.coordinates import AltAz, EarthLocation\nfrom exoorbit.orbit import Orbit\n\nfrom exoplanet_transit_snr.snr_estimate import (\n    calculate_cohen_d_for_dataset,\n    coadd_cross_correlation,\n    load_data,\n    run_cross_correlation,\n)\nfrom exoplanet_transit_snr.stats import gaussfit\nfrom exoplanet_transit_snr.stellardb import StellarDb\n\n# define the names of the star and planet\n# as well as the datasets within the datasets folder\nstar, planet = \"WASP-107\", \"b\"\ndatasets = {50: \"WASP-107b_SNR50\", 100: \"WASP-107b_SNR100\", 200: \"WASP-107b_SNR200\"}\n\n# Load the nominal data for this star and planet from simbad/nasa exoplanet archive\nsdb = StellarDb()\nstar = sdb.get(star)\nplanet = star.planets[planet]\norbit = Orbit(star, planet)\ntelescope = EarthLocation.of_site(\"Paranal\")\n\n# Define the +- range of the radial velocity points,\n# and the density of the sampling\nrv_range = 200\nrv_step = 0.25\n\nfor snr in [200]:\n    # Where to find the data, might need to be adjusted\n    data_dir = join(dirname(__file__), \"../datasets\", datasets[snr], \"Spectrum_00\")\n    # load the data from the fits files, returns several objects\n    data = load_data(data_dir, load=True)\n    wave, flux, uncs, times, segments = data\n\n    # Determine orbital parameters\n    phi = (times - planet.time_of_transit) / planet.period\n    phi = phi.to_value(1)\n    phi = phi % 1\n    ingress = (-planet.transit_duration / 2 / planet.period).to_value(1) % 1\n    egress = (planet.transit_duration / 2 / planet.period).to_value(1) % 1\n    in_transit = (phi >= ingress) | (phi <= egress)\n    out_transit = ~in_transit\n\n    altaz = star.coordinates.transform_to(AltAz(obstime=times, location=telescope))\n    airmass = altaz.secz.value\n\n    rv = orbit.radial_velocity_planet(times)\n    rv_star = -star.coordinates.radial_velocity_correction(\n        obstime=times, location=telescope\n    )\n\n    # TODO: Create initial stellar spectrum guess\n    # sme = SME_Structure()\n    # sme.wave = wave[low:upp].to_value(u.AA)\n    # sme.spec = flux[low:upp]\n    # # We need the specific intensities, not the combined spectrum\n    # sme.vrad_flag = \"whole\"\n    # sme.vrad = -11\n    # sme.vrad_limit = 20\n    # sme.cscale_flag = \"none\"\n    # sme.cscale_type = \"match\"\n    # # Set stellar parameters\n    # sme.teff = star.teff.to_value(u.K)\n    # sme.logg = star.logg.to_value(u.one)\n    # sme.abund = Abund(star.monh.to_value(u.one), \"asplund2009\")\n    # sme.vmic = 1\n    # sme.vmac = 0\n    # sme.vsini = 0\n    # # Define atmosphere\n    # sme.atmo.source = \"marcs2012.sav\"\n    # sme.atmo.method = \"grid\"\n    # # Set linelist\n    # valdfile = join(dirname(__file__), \"ltt1445A.lin\")\n    # sme.linelist = ValdFile(valdfile)\n    # # sme.linelist = sme.linelist.trim(sme.wave[0, 0], sme.wave[0, -1], 1000)\n    # # Set Mu to the specific positions we need\n    # d = orbit.projected_radius(times)\n    # r = orbit.planet.radius\n    # R = orbit.star.radius\n    # mu = np.sqrt(1 - (d / R) ** 2)\n\n    # sme_fname = f\"sme_intensities_{star.name}_{planet.name}_snr{snr}.npz\"\n    # try:\n    #     sme_data = np.load(sme_fname)\n    #     wave_int, flux_int, cont_int = sme_data[\"wave\"], sme_data[\"flux\"], sme_data[\"cont\"]\n    #     wave_sme, flux_sme = sme_data[\"wave_sme\"], sme_data[\"flux_sme\"]\n    #     sme.mu = mu[np.isfinite(mu)]\n    # except (FileNotFoundError, KeyError):\n    #     sme = synthesize_spectrum(sme)\n    #     flux_sme = np.copy(sme.synth.ravel())\n    #     wave_sme = np.copy(sme.wave.ravel())\n\n    #     sme.specific_intensities_only = True\n    #     sme.mu = mu[np.isfinite(mu)]\n    #     wave_int, flux_int, cont_int = synthesize_spectrum(sme)\n    #     wave_int, flux_int, cont_int = wave_int[0], flux_int[0], cont_int[0]\n\n    #     np.savez(\n    #         sme_fname,\n    #         wave=wave_int,\n    #         flux=flux_int,\n    #         cont=cont_int,\n    #         wave_sme=wave_sme,\n    #         flux_sme=flux_sme,\n    #     )\n\n    # str_wave, str_flux = wave_sme, flux_sme\n\n    # Run the cross correlation to the next neighbour\n    cc_data, rv_array = run_cross_correlation(\n        data,\n        nsysrem=1,\n        rv_range=rv_range,\n        rv_step=rv_step,\n        load=False,\n        data_dir=data_dir,\n        rv_star=rv_star,\n        rv_planet=rv,\n        airmass=airmass,\n    )\n\n    cc_data = cc_data[\"10\"]\n    cc_data_coadd, cc_it, cc_oot = coadd_cross_correlation(\n        cc_data, rv, rv_array, times, planet, data_dir=data_dir, load=False\n    )\n\n    # Normalize by the oot signal\n    cc_it /= cc_oot\n\n    # Fit a gaussian\n    p0 = [np.max(cc_data_coadd) - np.min(cc_data_coadd), 0, 10, np.min(cc_data_coadd)]\n    gauss, pval = gaussfit(rv_array, cc_data_coadd, p0=p0)\n\n    # Plot the results\n    plt.plot(rv_array, cc_data_coadd, label=\"all observations\")\n    plt.plot(rv_array, gauss, label=\"best fit gaussian\")\n    plt.plot(rv_array, cc_it, label=\"in-transit\")\n    plt.plot(rv_array, cc_oot, label=\"out-of-transit\")\n    plt.legend()\n    plt.title(f\"{star.name} {planet.name} SNR{snr}\")\n    plt.xlabel(r\"$\\Delta$RV [km/s]\")\n    plt.ylabel(\"CCF\")\n    plt.show()\n", "meta": {"hexsha": "aeaf5fe76841ac3f7a7c959ffbd8291fac54ea4d", "size": 5163, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/wasp107b.py", "max_stars_repo_name": "AWehrhahn/exoplanet_transit_snr", "max_stars_repo_head_hexsha": "f1bdaddb89e1c8b819651bcd2d80ed95d2a1fc0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/wasp107b.py", "max_issues_repo_name": "AWehrhahn/exoplanet_transit_snr", "max_issues_repo_head_hexsha": "f1bdaddb89e1c8b819651bcd2d80ed95d2a1fc0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/wasp107b.py", "max_forks_repo_name": "AWehrhahn/exoplanet_transit_snr", "max_forks_repo_head_hexsha": "f1bdaddb89e1c8b819651bcd2d80ed95d2a1fc0f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1920529801, "max_line_length": 93, "alphanum_fraction": 0.654077087, "include": true, "reason": "import numpy,from astropy", "num_tokens": 1538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.19990700585689233}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2020 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport ctypes\nimport time\nfrom functools import reduce\nimport numpy\nimport h5py\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf import ao2mo\nfrom pyscf.ao2mo import _ao2mo\nfrom pyscf.ao2mo import outcore\n\n# least memory requirements:\n# nmo  ncore  ncas  outcore  incore\n# 200  40     16    0.8GB    3.7 GB (_eri 1.6GB intermediates 1.3G)\n# 250  50     16    1.7GB    8.2 GB (_eri 3.9GB intermediates 2.6G)\n# 300  60     16    3.1GB    16.8GB (_eri 8.1GB intermediates 5.6G)\n# 400  80     16    8.5GB    53  GB (_eri 25.6GB intermediates 19G)\n# 500  100    16    19 GB\n# 600  120    16    37 GB\n# 750  150    16    85 GB\n\nlibmcscf = lib.load_library('libmcscf')\n\ndef trans_e1_incore(eri_ao, mo, ncore, ncas):\n    nmo = mo.shape[1]\n    nocc = ncore + ncas\n    eri1 = ao2mo.incore.half_e1(eri_ao, (mo,mo[:,:nocc]), compact=False)\n    eri1 = eri1.reshape(nmo,nocc,-1)\n\n    klppshape = (0, nmo, 0, nmo)\n    klpashape = (0, nmo, ncore, nocc)\n    aapp = numpy.empty((ncas,ncas,nmo,nmo))\n    for i in range(ncas):\n        _ao2mo.nr_e2(eri1[ncore+i,ncore:nocc], mo, klppshape,\n                      aosym='s4', mosym='s1', out=aapp[i])\n    ppaa = lib.transpose(aapp.reshape(ncas*ncas,-1)).reshape(nmo,nmo,ncas,ncas)\n    aapp = None\n\n    papa = numpy.empty((nmo,ncas,nmo,ncas))\n    for i in range(nmo):\n        _ao2mo.nr_e2(eri1[i,ncore:nocc], mo, klpashape,\n                      aosym='s4', mosym='s1', out=papa[i])\n\n    pp = numpy.empty((nmo,nmo))\n    j_cp = numpy.zeros((ncore,nmo))\n    k_pc = numpy.zeros((nmo,ncore))\n    for i in range(ncore):\n        _ao2mo.nr_e2(eri1[i,i:i+1], mo, klppshape, aosym='s4', mosym='s1', out=pp)\n        j_cp[i] = pp.diagonal()\n    j_pc = j_cp.T.copy()\n\n    pp = numpy.empty((ncore,ncore))\n    for i in range(nmo):\n        klshape = (i, i+1, 0, ncore)\n        _ao2mo.nr_e2(eri1[i,:ncore], mo, klshape, aosym='s4', mosym='s1', out=pp)\n        k_pc[i] = pp.diagonal()\n    return j_pc, k_pc, ppaa, papa\n\n\n# level = 1: ppaa, papa and jpc, kpc\n# level > 1: ppaa, papa only.  It affects accuracy of hdiag\ndef trans_e1_outcore(mol, mo, ncore, ncas, erifile,\n                     max_memory=None, level=1, verbose=logger.WARN):\n    time0 = (time.clock(), time.time())\n    log = logger.new_logger(mol, verbose)\n    log.debug1('trans_e1_outcore level %d  max_memory %d', level, max_memory)\n    nao, nmo = mo.shape\n    nao_pair = nao*(nao+1)//2\n    nocc = ncore + ncas\n\n    faapp_buf = lib.H5TmpFile()\n    if isinstance(erifile, h5py.Group):\n        feri = erifile\n    else:\n        feri = lib.H5TmpFile(erifile, 'w')\n\n    mo_c = numpy.asarray(mo, order='C')\n    mo = numpy.asarray(mo, order='F')\n    pashape = (0, nmo, ncore, nocc)\n    papa_buf = numpy.zeros((nao,ncas,nmo*ncas))\n    j_pc = numpy.zeros((nmo,ncore))\n    k_pc = numpy.zeros((nmo,ncore))\n\n    mem_words = int(max(2000,max_memory-papa_buf.nbytes/1e6)*1e6/8)\n    aobuflen = mem_words//(nao_pair+nocc*nmo) + 1\n    ao_loc = numpy.array(mol.ao_loc_nr(), dtype=numpy.int32)\n    shranges = outcore.guess_shell_ranges(mol, True, aobuflen, None, ao_loc)\n    intor = mol._add_suffix('int2e')\n    ao2mopt = _ao2mo.AO2MOpt(mol, intor,\n                             'CVHFnr_schwarz_cond', 'CVHFsetnr_direct_scf')\n    nstep = len(shranges)\n    maxbuflen = max([x[2] for x in shranges])\n    log.debug('mem_words %.8g MB, maxbuflen = %d', mem_words*8/1e6, maxbuflen)\n    bufs1 = numpy.empty((maxbuflen, nao_pair))\n    bufs2 = numpy.empty((maxbuflen, nmo*ncas))\n    if level == 1:\n        bufs3 = numpy.empty((maxbuflen, nao*ncore))\n        log.debug('mem cache %.8g MB',\n                  (bufs1.nbytes+bufs2.nbytes+bufs3.nbytes)/1e6)\n    else:\n        log.debug('mem cache %.8g MB', (bufs1.nbytes+bufs2.nbytes)/1e6)\n    ti0 = log.timer('Initializing trans_e1_outcore', *time0)\n\n    # fmmm, ftrans, fdrv for level 1\n    fmmm = libmcscf.AO2MOmmm_ket_nr_s2\n    ftrans = libmcscf.AO2MOtranse1_nr_s4\n    fdrv = libmcscf.AO2MOnr_e2_drv\n    for istep,sh_range in enumerate(shranges):\n        log.debug('[%d/%d], AO [%d:%d], len(buf) = %d',\n                  istep+1, nstep, *sh_range)\n        buf = bufs1[:sh_range[2]]\n        _ao2mo.nr_e1fill(intor, sh_range,\n                         mol._atm, mol._bas, mol._env, 's4', 1, ao2mopt, buf)\n        if log.verbose >= logger.DEBUG1:\n            ti1 = log.timer('AO integrals buffer', *ti0)\n        bufpa = bufs2[:sh_range[2]]\n        _ao2mo.nr_e1(buf, mo, pashape, 's4', 's1', out=bufpa)\n# jc_pp, kc_pp\n        if level == 1: # ppaa, papa and vhf, jcp, kcp\n            if log.verbose >= logger.DEBUG1:\n                ti1 = log.timer('buffer-pa', *ti1)\n            buf1 = bufs3[:sh_range[2]]\n            fdrv(ftrans, fmmm,\n                 buf1.ctypes.data_as(ctypes.c_void_p),\n                 buf.ctypes.data_as(ctypes.c_void_p),\n                 mo.ctypes.data_as(ctypes.c_void_p),\n                 ctypes.c_int(sh_range[2]), ctypes.c_int(nao),\n                 (ctypes.c_int*4)(0, nao, 0, ncore),\n                 ctypes.POINTER(ctypes.c_void_p)(), ctypes.c_int(0))\n            p0 = 0\n            for ij in range(sh_range[0], sh_range[1]):\n                i,j = lib.index_tril_to_pair(ij)\n                i0 = ao_loc[i]\n                j0 = ao_loc[j]\n                i1 = ao_loc[i+1]\n                j1 = ao_loc[j+1]\n                di = i1 - i0\n                dj = j1 - j0\n                if i == j:\n                    dij = di * (di+1) // 2\n                    buf = numpy.empty((di,di,nao*ncore))\n                    idx = numpy.tril_indices(di)\n                    buf[idx] = buf1[p0:p0+dij]\n                    buf[idx[1],idx[0]] = buf1[p0:p0+dij]\n                    buf = buf.reshape(di,di,nao,ncore)\n                    mo1 = mo_c[i0:i1]\n                    tmp = numpy.einsum('uvpc,pc->uvc', buf, mo[:,:ncore])\n                    tmp = lib.dot(mo1.T, tmp.reshape(di,-1))\n                    j_pc += numpy.einsum('vp,pvc->pc', mo1, tmp.reshape(nmo,di,ncore))\n                    tmp = numpy.einsum('uvpc,uc->vcp', buf, mo1[:,:ncore])\n                    tmp = lib.dot(tmp.reshape(-1,nmo), mo).reshape(di,ncore,nmo)\n                    k_pc += numpy.einsum('vp,vcp->pc', mo1, tmp)\n                else:\n                    dij = di * dj\n                    buf = buf1[p0:p0+dij].reshape(di,dj,nao,ncore)\n                    mo1 = mo_c[i0:i1]\n                    mo2 = mo_c[j0:j1]\n                    tmp = numpy.einsum('uvpc,pc->uvc', buf, mo[:,:ncore])\n                    tmp = lib.dot(mo1.T, tmp.reshape(di,-1))\n                    j_pc += numpy.einsum('vp,pvc->pc',\n                                         mo2, tmp.reshape(nmo,dj,ncore)) * 2\n                    tmp = numpy.einsum('uvpc,uc->vcp', buf, mo1[:,:ncore])\n                    tmp = lib.dot(tmp.reshape(-1,nmo), mo).reshape(dj,ncore,nmo)\n                    k_pc += numpy.einsum('vp,vcp->pc', mo2, tmp)\n                    tmp = numpy.einsum('uvpc,vc->ucp', buf, mo2[:,:ncore])\n                    tmp = lib.dot(tmp.reshape(-1,nmo), mo).reshape(di,ncore,nmo)\n                    k_pc += numpy.einsum('up,ucp->pc', mo1, tmp)\n                p0 += dij\n            if log.verbose >= logger.DEBUG1:\n                ti1 = log.timer('j_cp and k_cp', *ti1)\n\n        if log.verbose >= logger.DEBUG1:\n            ti1 = log.timer('half transformation of the buffer', *ti1)\n\n# ppaa, papa\n        faapp_buf[str(istep)] = \\\n                bufpa.reshape(sh_range[2],nmo,ncas)[:,ncore:nocc].reshape(-1,ncas**2).T\n        p0 = 0\n        for ij in range(sh_range[0], sh_range[1]):\n            i,j = lib.index_tril_to_pair(ij)\n            i0 = ao_loc[i]\n            j0 = ao_loc[j]\n            i1 = ao_loc[i+1]\n            j1 = ao_loc[j+1]\n            di = i1 - i0\n            dj = j1 - j0\n            if i == j:\n                dij = di * (di+1) // 2\n                buf1 = numpy.empty((di,di,nmo*ncas))\n                idx = numpy.tril_indices(di)\n                buf1[idx] = bufpa[p0:p0+dij]\n                buf1[idx[1],idx[0]] = bufpa[p0:p0+dij]\n            else:\n                dij = di * dj\n                buf1 = bufpa[p0:p0+dij].reshape(di,dj,-1)\n                mo1 = mo[j0:j1,ncore:nocc].copy()\n                for i in range(di):\n                    lib.dot(mo1.T, buf1[i], 1, papa_buf[i0+i], 1)\n            mo1 = mo[i0:i1,ncore:nocc].copy()\n            buf1 = lib.dot(mo1.T, buf1.reshape(di,-1))\n            papa_buf[j0:j1] += buf1.reshape(ncas,dj,-1).transpose(1,0,2)\n            p0 += dij\n        if log.verbose >= logger.DEBUG1:\n            ti1 = log.timer('ppaa and papa buffer', *ti1)\n\n        ti0 = log.timer('gen AO/transform MO [%d/%d]'%(istep+1,nstep), *ti0)\n    buf = buf1 = bufpa = None\n    bufs1 = bufs2 = bufs3 = None\n    time1 = log.timer('mc_ao2mo pass 1', *time0)\n\n    log.debug1('Half transformation done. Current memory %d',\n               lib.current_memory()[0])\n\n    nblk = int(max(8, min(nmo, (max_memory*1e6/8-papa_buf.size)/(ncas**2*nmo))))\n    log.debug1('nblk for papa = %d', nblk)\n    dset = feri.create_dataset('papa', (nmo,ncas,nmo,ncas), 'f8')\n    for i0, i1 in prange(0, nmo, nblk):\n        tmp = lib.dot(mo[:,i0:i1].T, papa_buf.reshape(nao,-1))\n        dset[i0:i1] = tmp.reshape(i1-i0,ncas,nmo,ncas)\n    papa_buf = tmp = None\n    time1 = log.timer('papa pass 2', *time1)\n\n    tmp = numpy.empty((ncas**2,nao_pair))\n    p0 = 0\n    for istep, sh_range in enumerate(shranges):\n        tmp[:,p0:p0+sh_range[2]] = faapp_buf[str(istep)]\n        p0 += sh_range[2]\n    nblk = int(max(8, min(nmo, (max_memory*1e6/8-tmp.size)/(ncas**2*nmo)-1)))\n    log.debug1('nblk for ppaa = %d', nblk)\n    dset = feri.create_dataset('ppaa', (nmo,nmo,ncas,ncas), 'f8')\n    for i0, i1 in prange(0, nmo, nblk):\n        tmp1 = _ao2mo.nr_e2(tmp, mo, (i0,i1,0,nmo), 's4', 's1', ao_loc=ao_loc)\n        tmp1 = tmp1.reshape(ncas,ncas,i1-i0,nmo)\n        for j in range(i1-i0):\n            dset[i0+j] = tmp1[:,:,j].transpose(2,0,1)\n    tmp = tmp1 = None\n    time1 = log.timer('ppaa pass 2', *time1)\n\n    time0 = log.timer('mc_ao2mo', *time0)\n    return j_pc, k_pc\n\n\n# level = 1: ppaa, papa and vhf, jpc, kpc\n# level = 2: ppaa, papa, vhf,  jpc=0, kpc=0\nclass _ERIS(object):\n    def __init__(self, casscf, mo, method='incore', level=1):\n        mol = casscf.mol\n        nao, nmo = mo.shape\n        ncore = casscf.ncore\n        ncas = casscf.ncas\n\n        dm_core = numpy.dot(mo[:,:ncore], mo[:,:ncore].T)\n        vj, vk = casscf._scf.get_jk(mol, dm_core)\n        self.vhf_c = reduce(numpy.dot, (mo.T, vj*2-vk, mo))\n\n        mem_incore, mem_outcore, mem_basic = _mem_usage(ncore, ncas, nmo)\n        mem_now = lib.current_memory()[0]\n        eri = casscf._scf._eri\n        if (method == 'incore' and eri is not None and\n            (mem_incore+mem_now < casscf.max_memory*.9) or\n            mol.incore_anyway):\n            if eri is None:\n                eri = mol.intor('int2e', aosym='s8')\n            self.j_pc, self.k_pc, self.ppaa, self.papa = \\\n                    trans_e1_incore(eri, mo, ncore, ncas)\n        else:\n            log = logger.Logger(casscf.stdout, casscf.verbose)\n            self.feri = lib.H5TmpFile()\n            max_memory = max(3000, casscf.max_memory*.9-mem_now)\n            if max_memory < mem_basic:\n                log.warn('Calculation needs %d MB memory, over CASSCF.max_memory (%d MB) limit',\n                         (mem_basic+mem_now)/.9, casscf.max_memory)\n            self.j_pc, self.k_pc = \\\n                    trans_e1_outcore(mol, mo, ncore, ncas, self.feri,\n                                     max_memory=max_memory,\n                                     level=level, verbose=log)\n            self.ppaa = self.feri['ppaa']\n            self.papa = self.feri['papa']\n\ndef _mem_usage(ncore, ncas, nmo):\n    outcore = basic = ncas**2*nmo**2*2 * 8/1e6\n    incore = outcore + (ncore+ncas)*nmo**3*4/1e6\n    return incore, outcore, basic\n\ndef prange(start, end, step):\n    for i in range(start, end, step):\n        yield i, min(i+step, end)\n\nif __name__ == '__main__':\n    from pyscf import scf\n    from pyscf import gto\n    from pyscf.mcscf import mc1step\n\n    mol = gto.Mole()\n    mol.verbose = 0\n    mol.output = None#\"out_h2o\"\n    mol.atom = [\n        ['O', ( 0., 0.    , 0.   )],\n        ['H', ( 0., -0.757, 0.587)],\n        ['H', ( 0., 0.757 , 0.587)],]\n    mol.basis = {'H': 'cc-pvtz',\n                 'O': 'cc-pvtz',}\n    mol.build()\n\n    m = scf.RHF(mol)\n    ehf = m.scf()\n\n    mc = mc1step.CASSCF(m, 6, 4)\n    mc.verbose = 4\n    mo = m.mo_coeff.copy()\n\n    eris0 = _ERIS(mc, mo, 'incore')\n    eris1 = _ERIS(mc, mo, 'outcore')\n    eris2 = _ERIS(mc, mo, 'outcore', level=1)\n    eris3 = _ERIS(mc, mo, 'outcore', level=2)\n    print('vhf_c', numpy.allclose(eris0.vhf_c, eris1.vhf_c))\n    print('j_pc ', numpy.allclose(eris0.j_pc , eris1.j_pc ))\n    print('k_pc ', numpy.allclose(eris0.k_pc , eris1.k_pc ))\n    print('ppaa ', numpy.allclose(eris0.ppaa , eris1.ppaa ))\n    print('papa ', numpy.allclose(eris0.papa , eris1.papa ))\n\n    print('vhf_c', numpy.allclose(eris0.vhf_c, eris2.vhf_c))\n    print('j_pc ', numpy.allclose(eris0.j_pc , eris2.j_pc ))\n    print('k_pc ', numpy.allclose(eris0.k_pc , eris2.k_pc ))\n    print('ppaa ', numpy.allclose(eris0.ppaa , eris2.ppaa ))\n    print('papa ', numpy.allclose(eris0.papa , eris2.papa ))\n\n    print('vhf_c', numpy.allclose(eris0.vhf_c, eris3.vhf_c))\n    print('ppaa ', numpy.allclose(eris0.ppaa , eris3.ppaa ))\n    print('papa ', numpy.allclose(eris0.papa , eris3.papa ))\n\n    ncore = mc.ncore\n    ncas = mc.ncas\n    nocc = ncore + ncas\n    nmo = mo.shape[1]\n    eri = ao2mo.incore.full(m._eri, mo, compact=False).reshape((nmo,)*4)\n    aaap = numpy.array(eri[ncore:nocc,ncore:nocc,ncore:nocc,:])\n    ppaa = numpy.array(eri[:,:,ncore:nocc,ncore:nocc])\n    papa = numpy.array(eri[:,ncore:nocc,:,ncore:nocc])\n    jc_pp = numpy.einsum('iipq->ipq', eri[:ncore,:ncore,:,:])\n    kc_pp = numpy.einsum('ipqi->ipq', eri[:ncore,:,:,:ncore])\n    vhf_c = numpy.einsum('cij->ij', jc_pp)*2 - numpy.einsum('cij->ij', kc_pp)\n    j_pc = numpy.einsum('ijj->ji', jc_pp)\n    k_pc = numpy.einsum('ijj->ji', kc_pp)\n\n    print('vhf_c', numpy.allclose(vhf_c, eris1.vhf_c))\n    print('j_pc ', numpy.allclose(j_pc, eris1.j_pc))\n    print('k_pc ', numpy.allclose(k_pc, eris1.k_pc))\n    print('ppaa ', numpy.allclose(ppaa , eris0.ppaa ))\n    print('papa ', numpy.allclose(papa , eris0.papa ))\n\n", "meta": {"hexsha": "869fa5e80a5c8136c2ce204723b028e729cec47c", "size": 14872, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/mcscf/mc_ao2mo.py", "max_stars_repo_name": "mfkasim1/pyscf", "max_stars_repo_head_hexsha": "7be5e015b2b40181755c71d888449db936604660", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-12T11:55:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T11:55:25.000Z", "max_issues_repo_path": "pyscf/mcscf/mc_ao2mo.py", "max_issues_repo_name": "mfkasim1/pyscf", "max_issues_repo_head_hexsha": "7be5e015b2b40181755c71d888449db936604660", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2018-08-22T19:44:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-09T10:02:36.000Z", "max_forks_repo_path": "pyscf/mcscf/mc_ao2mo.py", "max_forks_repo_name": "mfkasim1/pyscf", "max_forks_repo_head_hexsha": "7be5e015b2b40181755c71d888449db936604660", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-02-14T16:28:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-12T16:40:30.000Z", "avg_line_length": 40.5231607629, "max_line_length": 96, "alphanum_fraction": 0.5591043572, "include": true, "reason": "import numpy", "num_tokens": 5055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3415825128436339, "lm_q1q2_score": 0.19986032252045022}}
{"text": "#!/usr/bin/env python\n# Computes the matrix of similarities between structures in a xyz file\n# by first getting SOAP descriptors for all environments, finding the best\n# match between environments using the Hungarian algorithm, and finally\n# summing up the environment distances.\n# Supports periodic systems, matching between structures with different\n# atom number and kinds, and sports the infrastructure for introducing an\n# alchemical similarity kernel to match different atomic species\n\n# import sys, os, pickle\nimport sys, os\nimport cPickle as pickle\nimport gc \nfrom lap.lap import best_pairs, best_cost, lcm_best_cost\nfrom lap.perm import xperm, mcperm, rematch\nimport numpy as np\nfrom environments import environ, alchemy, envk\nimport quippy\n__all__ = [ \"structk\", \"structure\" ]\n\n   \nclass structure:\n   def __init__(self, salchem=None):\n      self.env={}\n      self.species={}\n      self.zspecies = []\n      self.atz = []\n      self.nenv=0  \n      self.alchem=salchem\n      if self.alchem is None: self.alchem=alchemy()\n      self.globenv = None\n      \n   def getnz(self, sp):\n      if sp in self.species:\n         return self.species[sp]\n      else: return 0\n      \n   def getatomenv(self, i):\n      if i>=len(self.atz):\n          raise IndexError(\"Trying to access atom past structure size\")\n      k=0\n      lsp = {}\n      for z in self.atz:\n         if z in lsp: lsp[z]+=1\n         else: lsp[z] = 0\n         if i==k: \n             return self.env[z][lsp[z]]           \n         k+=1\n       \n   def getenv(self, sp, i):\n      if sp in self.env and i<len(self.env[sp]):\n         return self.env[sp][i]\n      else: \n         return environ(self.nmax,self.lmax,self.alchem,sp)  # missing atoms environments just returned as isolated species!\n         \n   def ismissing(self, sp, i):\n      if sp in self.species and i<self.species[sp]:\n         return False\n      else: return True\n   \n      \n   def parse(self, fat, coff=5.0, cotw=0.5, nmax=4, lmax=3, gs=0.5, cw=1.0, nocenter=[], noatom=[], unsoap=False, kit=None, soapdump=None):\n      \"\"\" Takes a frame in the QUIPPY format and computes a list of its environments. \"\"\"\n      \n      # removes atoms that are to be ignored\n      at = fat.copy()\n      nol = []\n      for s in range(1,at.z.size+1):\n         if at.z[s] in noatom: nol.append(s)\n      if len(nol)>0: at.remove_atoms(nol)\n      \n      \n      self.nmax = nmax\n      self.lmax = lmax\n      self.atz = at.z.copy()\n      self.species = {}\n      for z in at.z:      \n         if z in self.species: self.species[z]+=1\n         else: self.species[z] = 1\n            \n      self.zspecies = self.species.keys();\n      self.zspecies.sort(); \n      lspecies = 'n_species='+str(len(self.zspecies))+' species_Z={ '\n      for z in self.zspecies: lspecies = lspecies + str(z) + ' '\n      lspecies = lspecies + '}'\n   \n      at.set_cutoff(coff);\n      at.calc_connect();\n      \n      self.nenv = 0\n      if not soapdump is None:\n         soapdump.write(\"####### SOAP VECTOR FRAME ######\\n\")\n      for sp in self.species:\n         \n         if sp in nocenter: \n            self.species[sp]=0\n            continue # Option to skip some environments\n         \n         # first computes the descriptors of species that are present\n         if not soapdump is None: sys.stderr.write(\"SOAP STRING:    \"+\"soap central_reference_all_species=F central_weight=\"+str(cw)+\"  covariance_sigma0=0.0 atom_sigma=\"+str(gs)+\" cutoff=\"+str(coff)+\" cutoff_transition_width=\"+str(cotw)+\" n_max=\"+str(nmax)+\" l_max=\"+str(lmax)+' '+lspecies+' Z='+str(sp)+\"\\n\")\n         desc = quippy.descriptors.Descriptor(\"soap central_reference_all_species=F \"+(\"normalise=F\" if unsoap else \"\")+\" central_weight=\"+str(cw)+\"  covariance_sigma0=0.0 atom_sigma=\"+str(gs)+\" cutoff=\"+str(coff)+\" cutoff_transition_width=\"+str(cotw)+\" n_max=\"+str(nmax)+\" l_max=\"+str(lmax)+' '+lspecies+' Z='+str(sp) )   \n         try:\n            psp = desc.calc(at)[\"descriptor\"]\n         except TypeError:\n            print(\"Interface change in QUIP/GAP. Update your code first.\")\n\n         if not soapdump is None:\n            soapdump.write(\"Specie %d - %d atoms\\n\"% (sp,len(psp)))\n            for p in psp:\n                np.savetxt(soapdump,[p])\n\n         # now repartitions soaps in environment descriptors\n         lenv = []\n         for p in psp:\n            nenv = environ(nmax, lmax, self.alchem)\n            nenv.convert(sp, self.zspecies, p, unsoap)\n            lenv.append(nenv)\n         self.env[sp] = lenv\n         self.nenv += self.species[sp]\n         \n      # adds kit data   \n      if kit is None: kit = {}\n      \n      for sp in kit:         \n         if not sp in self.species: \n            self.species[sp]=0\n            self.env[sp] = []\n         for k in range(self.species[sp], kit[sp]):            \n            self.env[sp].append(environ(self.nmax,self.lmax,self.alchem,sp))\n            self.nenv+=1\n         self.species[sp] = kit[sp]          \n      \n      self.zspecies = self.species.keys()\n      self.zspecies.sort() \n      \n      # also compute the global (flattened) fingerprint\n      self.globenv = environ(nmax, lmax, self.alchem)\n      \n      for k, se in self.env.items():\n         for e in se:\n            self.globenv.add(e)\n      # divides by the number of atoms in the structure\n      for sij in self.globenv.soaps:  self.globenv.soaps[sij]*=1.0/self.nenv\n      # self.globenv.normalize()  #if needed, normalization will be done later on.....\n      \n\ndef gcd(a,b):\n   if (b>a): a,b = b, a\n   \n   while (b):  a, b = b, a%b\n   \n   return a\n   \ndef lcm(a,b):\n   return a*b/gcd(b,a)\n\n#def gstructk(strucA, strucB, alchem=alchemy(), peratom=False):\n#    \n#   return envk(strucA.globenv, strucB.globenv, alchem) \n\ndef structk(strucA, strucB, alchem=alchemy(), peratom=False, mode=\"match\", fout=None, peps=0.0, gamma=1.0, zeta=1.0, xspecies=False):\n   # computes the SOAP similarity KERNEL between two structures by combining atom-centered kernels\n   # possible kernel modes include:\n   #   average :  scalar product between averaged kernels\n   #   match:     best-match hungarian kernel\n   #   permanent: average over all permutations\n      \n   # average kernel. quick & easy!   \n   if mode==\"fastavg\":\n       genvA=strucA.globenv\n       genvB=strucB.globenv        \n       return envk(genvA, genvB, alchem)**zeta, 0\n   elif mode==\"fastspecies\": \n       # for now, only implement standard Kronecker alchemy\n       senvB = environ(strucB.nmax, strucB.lmax, strucB.alchem)\n       kk = 0\n       for za in strucA.zspecies:    \n         if not za in strucB.zspecies: continue         \n         senvA = environ(strucA.nmax, strucA.lmax, strucA.alchem)\n         for ia in xrange(strucA.getnz(za)):\n            senvA.add(strucA.getenv(za, ia))\n         senvB = environ(strucB.nmax, strucB.lmax, strucB.alchem)   \n         for ib in xrange(strucB.getnz(za)):\n            senvB.add(strucB.getenv(za, ib))\n         kk += envk(senvA, senvB, alchem)**zeta\n       \n       kk/=strucA.nenv*strucB.nenv\n       return kk,0\n         \n       #  for zb, nzb in nspeciesB:\n       #         for ib in xrange(nzb):\n       #            return envk(genvA, genvB, alchem), 0\n\n   nenv = 0\n   \n   if peratom: # replicate structures to match structures of different peratomity\n      # we do not check for compatibility at this stage, just assume that the \n      # matching will be done somehow (otherwise it would be exceedingly hard to manage in case of non-standard alchemy)\n      nspeciesA = []\n      nspeciesB = []\n      for z in strucA.zspecies:\n         nspeciesA.append( (z, strucA.getnz(z)) )\n      for z in strucB.zspecies:\n         nspeciesB.append( (z, strucB.getnz(z)) )\n      nenv=nenvA = strucA.nenv\n      nenvB = strucB.nenv            \n   else:   \n      # top up missing atoms with isolated environments\n      # first checks which atoms are present\n      zspecies = sorted(list(set(strucB.zspecies+strucA.zspecies)))\n      nspecies = []\n      for z in zspecies:\n         nz = max(strucA.getnz(z),strucB.getnz(z))\n         nspecies.append((z,nz)) \n         nenv += nz\n      nenvA = nenvB = nenv\n      nspeciesA = nspeciesB = nspecies   \n         \n   np.set_printoptions(linewidth=500,precision=4)\n\n   kk = np.zeros((nenvA,nenvB),float)\n   ika = 0\n   ikb = 0  \n   for za, nza in nspeciesA:      \n      for ia in xrange(nza):\n         envA = strucA.getenv(za, ia)         \n         ikb = 0\n         for zb, nzb in nspeciesB:\n            for ib in xrange(nzb):\n               envB = strucB.getenv(zb, ib)\n               if alchem.mu > 0 and (strucA.ismissing(za, ia) ^ strucB.ismissing(zb, ib)):\n                   # includes a penalty dependent on \"mu\", in a way that is consistent with the definition of kernel distance\n                   kk[ika,ikb] = exp(-alchem.mu)\n               else:\n                  if za == zb or not xspecies:  #uncomment to zero out kernels between different species\n                    kk[ika,ikb] = envk(envA, envB, alchem)**zeta              \n                  else: kk[ika,ikb] = 0\n               ikb+=1\n         ika+=1\n   aidx = {}\n   ika=0\n   for za, nza in nspeciesA: \n      aidx[za] = range(ika,ika+nza)\n      ika+=nza\n   ikb=0\n   bidx = {}\n   for zb, nzb in nspeciesB: \n      bidx[zb] = range(ikb,ikb+nzb)\n      ikb+=nzb\n\n   if fout != None:\n      # prints out similarity information for the environment pairs\n      fout.write(\"# atomic species in the molecules (possibly topped up with dummy isolated atoms): \\n\")      \n      for za, nza in nspeciesA:\n         for ia in xrange(nza): fout.write(\" %d \" % (za) )\n      fout.write(\"\\n\");\n      for zb, nzb in nspeciesB:\n         for ib in xrange(nzb): fout.write(\" %d \" % (zb) )\n      fout.write(\"\\n\");\n      \n      fout.write(\"# environment kernel matrix: \\n\")      \n      for r in kk:\n         for e in r:\n            fout.write(\"%20.14e \" % (e) )\n         fout.write(\"\\n\")\n      #fout.write(\"# environment kernel eigenvalues: \\n\")      \n      #ev = np.linalg.eigvals(kk)\n      #for e in ev:\n      #    fout.write(\"(%8.4e,%8.4e) \" % (e.real,e.imag) )\n      #fout.write(\"\\n\");\n         \n       \n\n      \n   # Now we have the matrix of scalar products. \n   # We can first find the optimal scalar product kernel\n   # we must find the maximum \"cost\"\n   if mode == \"match\":\n        if peratom and nenvA != nenvB:\n            nenv = lcm(nenvA, nenvB)\n            hun = lcm_best_cost(1-kk)\n        else:\n            hun=best_cost(1.0-kk)        \n        cost = 1-hun/nenv\n   elif mode == \"permanent\":\n        # there is no place to hide: cross-species environments are not necessarily zero \n        if peps>0: cost = mcperm(kk, peps)\n        else: cost = xperm(kk)\n            \n        cost = cost/np.math.factorial(nenv)/nenv        \n   elif mode == \"rematch\":\n       cost=rematch(kk, gamma, 1e-6)  # hard-coded residual error for regularized gamma\n       # print cost, kk.sum()/(nenv*nenv), envk(strucA.globenv, strucB.globenv, alchem)\n   elif mode == \"average\":\n       cost = kk.sum()/(nenvA*nenvB)\n       # print 'elem: {}'.format(kk.sum()) \n       # print 'elem norm: {}'.format(cost) \n       # print 'avg norm: {}'.format((nenvA*nenvB)) \n       \n   else: raise ValueError(\"Unknown global fingerprint mode \", mode)\n   \n         \n   return cost,kk\n\n\nclass structurelist(list):\n    def __init__(self, basedir=\"tmpstructures\"):\n        self.basedir=basedir\n        # create the folder if it is not there        \n        if not os.path.exists(basedir):os.makedirs(basedir)\n        self.count=0\n        \n    def exists(self, index):\n        # return true if the file associated with index exists, false otherwise\n        f=self.basedir+'/sl_'+str(index)+'.dat'\n        return os.path.isfile(f)\n    # @profile\n    def append(self, element):\n        #pickle the element for later use\n        ind=self.count\n        f=self.basedir+'/sl_'+str(ind)+'.dat'\n        file = open(f,\"wb\")\n        gc.disable()\n        pickle.dump(element, file,protocol=pickle.HIGHEST_PROTOCOL) # HIGHEST_PROTOCOL is 2 in py 2.7\n        file.close()\n        gc.enable()\n        self.count+=1\n\n        \n    # @profile\n    def __getitem__(self, index):\n        f = self.basedir+'/sl_'+str(index)+'.dat'\n        try:\n            file = open(f,\"rb\")\n        except IOError:\n            raise IOError(\"Cannot load descriptors for index %d\" % (index) )\n        gc.disable()\n        l = pickle.load(file)\n        file.close()\n        gc.enable()\n        return l\n", "meta": {"hexsha": "94e2e71a752727aabea9c7e84729fa89c66f474c", "size": 12376, "ext": "py", "lang": "Python", "max_stars_repo_path": "libmatch/structures.py", "max_stars_repo_name": "cosmo-epfl/glosim", "max_stars_repo_head_hexsha": "930998b7249adc0ac3e48308314233341de6e73f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2017-04-19T14:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T13:37:23.000Z", "max_issues_repo_path": "libmatch/structures.py", "max_issues_repo_name": "lab-cosmo/glosim", "max_issues_repo_head_hexsha": "930998b7249adc0ac3e48308314233341de6e73f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-05-23T10:30:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-05T06:43:04.000Z", "max_forks_repo_path": "libmatch/structures.py", "max_forks_repo_name": "lab-cosmo/glosim", "max_forks_repo_head_hexsha": "930998b7249adc0ac3e48308314233341de6e73f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2017-05-01T14:37:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T14:00:12.000Z", "avg_line_length": 36.1871345029, "max_line_length": 323, "alphanum_fraction": 0.5789431157, "include": true, "reason": "import numpy", "num_tokens": 3374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032313, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.19986031859871706}}
{"text": "\"\"\"Contains the classes that deal with the normal mode representation.\n\nCopyright (C) 2013, Joshua More and Michele Ceriotti\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see <http.//www.gnu.org/licenses/>.\n\n\nDeals with the normal mode transformation, including the complications\nintroduced by PA-CMD when the bead masses are rescaled. Also deals with\nthe change in the dynamics introduced by this mass-scaling, and has its\nown functions to calculate the kinetic energy, and the exact propagator\nin the normal mode representation under the ring polymer Hamiltonian.\n\nClasses:\n   NormalModes: Deals with the normal mode transformation in RPMD and PA-CMD.\n\"\"\"\n\nimport numpy as np\nfrom ipi.utils.depend import *\nfrom ipi.utils import units\nfrom ipi.utils import nmtransform\nfrom ipi.utils.messages import verbosity, warning, info\n\n__all__ = [ \"NormalModes\" ]\n\nclass NormalModes(dobject):\n   \"\"\" A helper class to manipulate the path NM.\n\n   Normal-modes transformation, determination of path frequencies,\n   dynamical mass matrix change, etc.\n\n   Attributes:\n      natoms: The number of atoms.\n      nbeads: The number of beads.\n      beads: The beads object for which the normal mode transformation should\n         be done.\n      ensemble: The ensemble object, specifying the temperature to hold the\n         system to.\n      transform: A nm_trans object that contains the functions that are\n         required for the normal mode transformation.\n\n   Depend objects:\n      mode: A string specifying how the bead masses are chosen.\n      transform_method: A string specifying how to do the normal mode\n         transformation.\n      nm_freqs: An array that specifies how the normal mode frequencies\n         of the ring polymers are to be calculated, and thus how the\n         bead masses should be chosen.\n      qnm: The bead positions in the normal mode representation. Depends on\n         beads.q.\n      pnm: The bead momenta in the normal mode representation. Depends on\n         beads.p.\n      omegan: The effective vibrational frequency for the interaction\n         between the replicas. Depends on the simulation temperature.\n      omegan2: omegan**2.\n      omegak: The normal mode frequencies for the free ring polymer.\n         Depends on omegan.\n      prop_pq: An array holding the exact normal mode propagator for the\n         free ring polymer, using mass scaled coordinates.\n         See J. Chem. Phys. 133, 124101 (2010). Depends on the bead masses\n         and the timestep.\n      nm_factor: An array of dynamical mass factors associated with each of\n         the normal modes. Depends on nm_freqs and mode.\n      dynm3: An array that gives the dynamical masses of individual atoms in the\n         normal modes representation. Depends on nm_factor and beads.m3.\n      dynomegak: The scaled vibrational frequencies. Depends on nm_factor and\n         omegak.\n      kins: A list of the kinetic energy for each normal mode, as\n         calculated in the normal mode representation, using the\n         dynamical mass factors. Depends on beads.sm3, beads.p and nm_factor.\n      kin: The total kinetic energy, as calculated in the normal mode\n         representation, using the dynamical mass factors.\n      kstress: The kinetic stress tensor, as calculated in the normal mode\n         representation, using the dynamical mass factors. Depends on\n         beads.sm3, beads.p and nm_factor.\n   \"\"\"\n\n   def __init__(self, mode=\"rpmd\", transform_method=\"fft\", freqs=None):\n      \"\"\"Initializes NormalModes.\n\n      Sets the options for the normal mode transform.\n\n      Args:\n         mode: A string specifying how to calculate the bead masses.\n         transform_method: A string specifying how to do the normal mode\n            transformation.\n         freqs: A list of data used to calculate the dynamical mass factors.\n      \"\"\"\n\n      if freqs is None:\n         freqs = []\n      dset(self,\"mode\",   depend_value(name='mode', value=mode))\n      dset(self,\"transform_method\",\n         depend_value(name='transform_method', value=transform_method))\n      dset(self,\"nm_freqs\",\n         depend_array(name=\"nm_freqs\",value=np.asarray(freqs, float) ) )\n\n   def bind(self, beads, ensemble):\n      \"\"\" Initializes the normal modes object and binds to beads and ensemble.\n\n      Do all the work down here as we need a full-formed necklace and ensemble\n      to know how this should be done.\n\n      Args:\n         beads: A beads object to be bound.\n         ensemble: An ensemble object to be bound.\n      \"\"\"\n\n      self.nbeads = beads.nbeads\n      self.natoms = beads.natoms\n\n      # stores a reference to the bound beads and ensemble objects\n      self.beads = beads\n      self.ensemble = ensemble\n\n      # sets up what's necessary to perform nm transformation.\n      if self.transform_method == \"fft\":\n         self.transform = nmtransform.nm_fft(nbeads=self.nbeads, natoms=self.natoms)\n      elif self.transform_method == \"matrix\":\n         self.transform = nmtransform.nm_trans(nbeads=self.nbeads)\n\n      # creates arrays to store normal modes representation of the path.\n      # must do a lot of piping to create \"ex post\" a synchronization between the beads and the nm\n      sync_q = synchronizer()\n      sync_p = synchronizer()\n      dset(self,\"qnm\",\n         depend_array(name=\"qnm\",\n            value=np.zeros((self.nbeads,3*self.natoms), float),\n               func={\"q\": (lambda : self.transform.b2nm(depstrip(self.beads.q)) ) },\n                  synchro=sync_q ) )\n      dset(self,\"pnm\",\n         depend_array(name=\"pnm\",\n            value=np.zeros((self.nbeads,3*self.natoms), float),\n               func={\"p\": (lambda : self.transform.b2nm(depstrip(self.beads.p)) ) },\n                  synchro=sync_p ) )\n\n      # must overwrite the functions\n      dget(self.beads, \"q\")._func = { \"qnm\": (lambda : self.transform.nm2b(depstrip(self.qnm)) )  }\n      dget(self.beads, \"p\")._func = { \"pnm\": (lambda : self.transform.nm2b(depstrip(self.pnm)) )  }\n      dget(self.beads, \"q\").add_synchro(sync_q)\n      dget(self.beads, \"p\").add_synchro(sync_p)\n\n      # also within the \"atomic\" interface to beads\n      for b in range(self.nbeads):\n         dget(self.beads._blist[b],\"q\")._func = { \"qnm\": (lambda : self.transform.nm2b(depstrip(self.qnm)) )  }\n         dget(self.beads._blist[b],\"p\")._func = { \"pnm\": (lambda : self.transform.nm2b(depstrip(self.pnm)) )  }\n         dget(self.beads._blist[b],\"q\").add_synchro(sync_q)\n         dget(self.beads._blist[b],\"p\").add_synchro(sync_p)\n\n\n      # finally, we mark the beads as those containing the set positions\n      dget(self.beads, \"q\").update_man()\n      dget(self.beads, \"p\").update_man()\n\n      # create path-frequencies related properties\n      dset(self,\"omegan\",\n         depend_value(name='omegan', func=self.get_omegan,\n            dependencies=[dget(self.ensemble,\"temp\")]) )\n      dset(self,\"omegan2\", depend_value(name='omegan2',func=self.get_omegan2,\n            dependencies=[dget(self,\"omegan\")]) )\n      dset(self,\"omegak\", depend_array(name='omegak',\n         value=np.zeros(self.beads.nbeads,float),\n            func=self.get_omegak, dependencies=[dget(self,\"omegan\")]) )\n\n      # sets up \"dynamical\" masses -- mass-scalings to give the correct RPMD/CMD dynamics\n      dset(self,\"nm_factor\", depend_array(name=\"nmm\",\n         value=np.zeros(self.nbeads, float), func=self.get_nmm,\n            dependencies=[dget(self,\"nm_freqs\"), dget(self,\"mode\") ]) )\n      dset(self,\"dynm3\", depend_array(name=\"dm3\",\n         value=np.zeros((self.nbeads,3*self.natoms), float),func=self.get_dynm3,\n            dependencies=[dget(self,\"nm_factor\"), dget(self.beads, \"m3\")] ) )\n      dset(self,\"dynomegak\", depend_array(name=\"dynomegak\",\n         value=np.zeros(self.nbeads, float), func=self.get_dynwk,\n            dependencies=[dget(self,\"nm_factor\"), dget(self,\"omegak\") ]) )\n\n      dset(self,\"prop_pq\",\n         depend_array(name='prop_pq',value=np.zeros((self.beads.nbeads,2,2)),\n            func=self.get_prop_pq,\n               dependencies=[dget(self,\"omegak\"), dget(self,\"nm_factor\"), dget(self.ensemble,\"dt\")]) )\n\n      # if the mass matrix is not the RPMD one, the MD kinetic energy can't be\n      # obtained in the bead representation because the masses are all mixed up\n      dset(self,\"kins\",\n         depend_array(name=\"kins\",value=np.zeros(self.nbeads, float),\n            func=self.get_kins,\n               dependencies=[dget(self,\"pnm\"), dget(self.beads,\"sm3\"), dget(self, \"nm_factor\") ] ))\n      dset(self,\"kin\",\n         depend_value(name=\"kin\", func=self.get_kin,\n            dependencies=[dget(self,\"kins\")] ))\n      dset(self,\"kstress\",\n         depend_array(name=\"kstress\",value=np.zeros((3,3), float),\n            func=self.get_kstress,\n               dependencies=[dget(self,\"pnm\"), dget(self.beads,\"sm3\"), dget(self, \"nm_factor\") ] ))\n\n   def get_omegan(self):\n      \"\"\"Returns the effective vibrational frequency for the interaction\n      between replicas.\n      \"\"\"\n\n      return self.ensemble.temp*self.nbeads*units.Constants.kb/units.Constants.hbar\n\n   def get_omegan2(self):\n      \"\"\"Returns omegan**2.\"\"\"\n\n      return self.omegan**2\n\n   def get_omegak(self):\n      \"\"\"Gets the normal mode frequencies.\n\n      Returns:\n         A list of the normal mode frequencies for the free ring polymer.\n         The first element is the centroid frequency (0.0).\n      \"\"\"\n\n      return 2*self.omegan*np.array([np.sin(k*np.pi/self.nbeads) for k in range(self.nbeads)])\n\n   def get_dynwk(self):\n      \"\"\"Gets the dynamical normal mode frequencies.\n\n      Returns:\n         A list of the scaled normal mode frequencies for the free ring polymer.\n         The first element is the centroid frequency (0.0).\n      \"\"\"\n\n      return self.omegak/np.sqrt(self.nm_factor)\n\n   def get_prop_pq(self):\n      \"\"\"Gets the normal mode propagator matrix.\n\n      Note the special treatment for the centroid normal mode, which is\n      propagated using the standard velocity Verlet algorithm as required.\n      Note that both the normal mode positions and momenta are propagated\n      using this matrix.\n\n      Returns:\n         An array of the form (nbeads, 2, 2). Each 2*2 array prop_pq[i,:,:]\n         gives the exact propagator for the i-th normal mode of the\n         ring polymer.\n      \"\"\"\n\n      dt = self.ensemble.dt\n      pqk = np.zeros((self.nbeads,2,2), float)\n      pqk[0] = np.array([[1,0], [dt,1]])\n\n      for b in range(1, self.nbeads):\n         sk = np.sqrt(self.nm_factor[b]) # NOTE THAT THE PROPAGATOR USES MASS-SCALED MOMENTA!\n\n         dtomegak = self.omegak[b]*dt/sk\n         c = np.cos(dtomegak)\n         s = np.sin(dtomegak)\n         pqk[b,0,0] = c\n         pqk[b,1,1] = c\n         pqk[b,0,1] = -s*self.omegak[b]*sk\n         pqk[b,1,0] = s/(self.omegak[b]*sk)\n\n      return pqk\n\n   def get_nmm(self):\n      \"\"\"Returns dynamical mass factors, i.e. the scaling of normal mode\n      masses that determine the path dynamics (but not statics).\"\"\"\n\n      # also checks that the frequencies and the mode given in init are\n      # consistent with the beads and ensemble\n\n      dmf = np.zeros(self.nbeads,float)\n      dmf[:] = 1.0\n      if self.mode == \"rpmd\":\n         if len(self.nm_freqs) > 0:\n            warning(\"nm.frequencies will be ignored for RPMD mode.\", verbosity.low)\n      elif self.mode == \"manual\":\n         if len(self.nm_freqs) != self.nbeads-1:\n            raise ValueError(\"Manual path mode requires (nbeads-1) frequencies, one for each internal mode of the path.\")\n         for b in range(1, self.nbeads):\n            sk = self.omegak[b]/self.nm_freqs[b-1]\n            dmf[b] = sk**2\n      elif self.mode == \"pa-cmd\":\n         if len(self.nm_freqs) > 1:\n            warning(\"Only the first element in nm.frequencies will be considered for PA-CMD mode.\", verbosity.low)\n         if len(self.nm_freqs) == 0:\n            raise ValueError(\"PA-CMD mode requires the target frequency of all the internal modes.\")\n         for b in range(1, self.nbeads):\n            sk = self.omegak[b]/self.nm_freqs[0]\n            info(\" \".join([\"NM FACTOR\", str(b), str(sk), str(self.omegak[b]), str(self.nm_freqs[0])]), verbosity.medium)\n            dmf[b] = sk**2\n      elif self.mode == \"wmax-cmd\":\n         if len(self.nm_freqs) > 2:\n            warning(\"Only the first two element in nm.frequencies will be considered for WMAX-CMD mode.\", verbosity.low)\n         if len(self.nm_freqs) < 2:\n            raise ValueError(\"WMAX-CMD mode requires [wmax, wtarget]. The normal modes will be scaled such that the first internal mode is at frequency wtarget and all the normal modes coincide at frequency wmax.\")\n         wmax = self.nm_freqs[0]\n         wt = self.nm_freqs[1]\n         for b in range(1, self.nbeads):\n            sk = 1.0/np.sqrt((wt)**2*(1+(wmax/self.omegak[1])**2)/(wmax**2+(self.omegak[b])**2))\n            dmf[b] = sk**2\n\n      return dmf\n\n   def get_dynm3(self):\n      \"\"\"Returns an array with the dynamical masses of individual atoms in the normal modes representation.\"\"\"\n\n      dm3 = np.zeros(self.beads.m3.shape,float)\n      for b in range(self.nbeads):\n         dm3[b] = self.beads.m3[b]*self.nm_factor[b]\n\n      return dm3\n\n   def free_qstep(self):\n      \"\"\"Exact normal mode propagator for the free ring polymer.\n\n      Note that the propagator works in mass scaled coordinates, so that the\n      propagator matrix can be determined independently from the particular\n      atom masses, and so the same propagator will work for all the atoms in\n      the system. All the ring polymers are propagated at the same time by a\n      matrix multiplication.\n\n      Also note that the centroid coordinate is propagated in qcstep, so is\n      not altered here.\n      \"\"\"\n\n      if self.nbeads == 1:\n         pass\n      else:\n         pq = np.zeros((2,self.natoms*3),float)\n         sm = depstrip(self.beads.sm3)[0]\n         prop_pq = depstrip(self.prop_pq)\n         for k in range(1,self.nbeads):\n            pq[0,:] = depstrip(self.pnm)[k]/sm\n            pq[1,:] = depstrip(self.qnm)[k]*sm\n            pq = np.dot(prop_pq[k],pq)\n            self.qnm[k] = pq[1,:]/sm\n            self.pnm[k] = pq[0,:]*sm\n\n   def get_kins(self):\n      \"\"\"Gets the MD kinetic energy for all the normal modes.\n\n      Returns:\n         A list of the kinetic energy for each NM.\n      \"\"\"\n\n      kmd = np.zeros(self.nbeads,float)\n      sm = depstrip(self.beads.sm3[0])\n      pnm = depstrip(self.pnm)\n      nmf = depstrip(self.nm_factor)\n\n      # computes the MD ke in the normal modes representation, to properly account for CMD mass scaling\n      for b in range(self.nbeads):\n         sp = pnm[b]/sm                      # mass-scaled momentum of b-th NM\n         kmd[b] = np.dot(sp,sp)*0.5/nmf[b]   # include the partially adiabatic CMD mass scaling\n\n      return kmd\n\n   def get_kin(self):\n      \"\"\"Gets the total MD kinetic energy.\n\n      Note that this does not correspond to the quantum kinetic energy estimate\n      for the system.\n\n      Returns:\n         The sum of the kinetic energy of each NM in the path.\n      \"\"\"\n\n      return self.kins.sum()\n\n   def get_kstress(self):\n      \"\"\"Calculates the total MD kinetic stress tensor.\n\n      Note that this does not correspond to the quantum kinetic stress tensor\n      estimate for the system.\n\n      Returns:\n         The sum of the MD kinetic stress tensor contributions from each NM.\n      \"\"\"\n\n      kmd = np.zeros((3,3),float)\n      sm = depstrip(self.beads.sm3[0])\n      pnm = depstrip(self.pnm)\n      nmf = depstrip(self.nm_factor)\n\n      for b in range(self.nbeads):\n         sp = pnm[b]/sm  # mass-scaled momentum of b-th NM\n\n         for i in range(3):\n            for j in range(3):\n               # computes the outer product of the p of various normal modes\n               # singling out Cartesian components to build the tensor\n               # also takes care of the possibility of having non-RPMD masses\n               kmd[i,j] += np.dot(sp[i:3*self.natoms:3],sp[j:3*self.natoms:3])/nmf[b]\n\n      return kmd\n", "meta": {"hexsha": "38566736f7e1e131e4e6f5d385fafbd8a15ab8b0", "size": 16476, "ext": "py", "lang": "Python", "max_stars_repo_path": "lammps-master/tools/i-pi/ipi/engine/normalmodes.py", "max_stars_repo_name": "rajkubp020/helloword", "max_stars_repo_head_hexsha": "4bd22691de24b30a0f5b73821c35a7ac0666b034", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lammps-master/tools/i-pi/ipi/engine/normalmodes.py", "max_issues_repo_name": "rajkubp020/helloword", "max_issues_repo_head_hexsha": "4bd22691de24b30a0f5b73821c35a7ac0666b034", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lammps-master/tools/i-pi/ipi/engine/normalmodes.py", "max_forks_repo_name": "rajkubp020/helloword", "max_forks_repo_head_hexsha": "4bd22691de24b30a0f5b73821c35a7ac0666b034", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0872817955, "max_line_length": 214, "alphanum_fraction": 0.6460912843, "include": true, "reason": "import numpy", "num_tokens": 4155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.1998603107552507}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom astropy import units as u\nfrom astropy.io import fits\nfrom astropy.nddata import CCDData\nfrom astropy.nddata import Cutout2D\nfrom astropy.wcs import WCS\nfrom .utils import *\n\n\n__all__ = ['imgblock_standard', 'imgblock_subcomp']\n\nclass imgblock_standard(object):\n    '''\n    GALFIT standard output.  E.g., output from\n        `galfit -o2 <file> (standard img. block)`\n    '''\n    def __init__(self, filename, zeromag=None, pixelscale=None, exptime=None,\n                 sigmasky=None, unit=None):\n        '''\n        Parameters\n        ----------\n        filename : string\n            Path of the GALFIT output file.\n        '''\n        f = fits.open(filename)\n        header = f[1].header\n        self.model_info = get_model_from_header(header)\n        self.zeromag = zeromag\n        self.sigmasky = sigmasky\n\n        if unit is None:\n            unit = convert_unit_hst2astropy(header.get('BUNIT'))\n        self.unit = unit\n\n        self.extensions = {\n            'data': [CCDData.read(filename, hdu=1, unit=unit), None],\n            'model': [CCDData.read(filename, hdu=2, unit=unit), None],\n            'residual': [CCDData.read(filename, hdu=3, unit=unit), None]\n        }\n        if pixelscale is None:\n            pixelscale = self.get_pixelscale_wcs(units='arcsec')\n        self.pixelscale = pixelscale\n        if exptime is None:\n            exptime = header.get('EXPTIME', None)\n        self.exptime = exptime\n        self.isophotes = {}\n\n    def cut_fov(self, position, size):\n        '''\n        Cut the field of view.\n\n        Parameters\n        ----------\n        position : (x, y)\n            Position of the image center, units: pixel.\n        size : (dx, dy)\n            Size of the new image, units: pixel.\n        '''\n        for loop, ext_name in enumerate(self.extensions):\n            ext, tag = self.extensions[ext_name]\n            img_cut = Cutout2D(ext.data, position=position, size=size)\n            if ext.wcs is not None:\n                header = ext.wcs.to_header()\n                crpix_org = [header['CRPIX1'], header['CRPIX2']]\n                crpix_new = img_cut.to_cutout_position(crpix_org)\n                header['CRPIX1'] = crpix_new[0]\n                header['CRPIX2'] = crpix_new[1]\n                wcs = WCS(header)\n            else:\n                wcs = None\n\n            if ext.mask is not None:\n                mask = Cutout2D(ext.mask, position=position, size=size).data\n            else:\n                mask = None\n            ccd_new = CCDData(img_cut.data, wcs=wcs, mask=mask, unit=ext.unit)\n            self.extensions[ext_name] = [ccd_new, tag]\n\n    def fit_ellipse(self, ext_name, x0=None, y0=None, sma=None, eps=0, pa=0,\n                    expand=False, **kwargs):\n        '''\n        Fit isophotes of an extension.\n\n        Parameters\n        ----------\n        ext_name : string\n            Name of the extenstion to be fitted.\n        x0, y0 : float\n            The center pixel coordinate of the ellipse.\n        sma : float\n            The semimajor axis of the ellipse in pixels.\n        eps : ellipticity\n            The ellipticity of the ellipse.\n        pa : float\n            The position angle (in radians) of the semimajor axis in\n            relation to the postive x axis of the image array (rotating\n            towards the positive y axis). Position angles are defined in the\n            range :math:`0 < PA <= \\\\pi`. Avoid using as starting position\n            angle of 0., since the fit algorithm may not work properly. When\n            the ellipses are such that position angles are near either\n            extreme of the range, noise can make the solution jump back and\n            forth between successive isophotes, by amounts close to 180\n            degrees.\n        **kwargs : Additional parameters feed to ellipse.fit_image().\n\n        Returns\n        -------\n        isolist : IsophoteList instance\n            A list-like object of Isophote instances, sorted by increasing\n            semimajor axis length.\n        '''\n        ext = self.get_extension(ext_name)\n        if ext.mask is None:\n            image = ext.data\n        else:\n            image = np.ma.array(ext.data, mask=ext.mask)\n\n        if x0 is None:\n            x0 = image.shape[1] / 2\n        if y0 is None:\n            y0 = image.shape[0] / 2\n        if sma is None:\n            ## Estimate the size of the source\n            #xx, yy = np.meshgrid(np.arange(image.shape[1]), np.arange(image.shape[0]))\n            #xx = xx.astype(np.float64) - x0\n            #yy = yy.astype(np.float64) - y0\n            #rr = np.sqrt(xx**2 + yy**2)\n            #sma = np.sum(rr * image) / np.sum(image)\n            sma = 10\n\n        isolist = fit_ellipse(image, x0, y0, sma, eps, pa, **kwargs)\n\n        if expand is True:\n            step = kwargs.get('step', 0.1)\n            fflag = kwargs.get('fflag', 0.7)\n            maxsma = kwargs.get('maxsma', None)\n            isolist_exp = grow_isophote(image, isolist[-1], step=step, fflag=fflag,\n                                        maxsma=maxsma, maxsteps=np.inf)\n            isolist = isolist + isolist_exp\n\n        self.isophotes[ext_name] = isolist\n        return isolist\n\n    def fit_isophote(self, ext_name, isolist):\n        '''\n        Fit isophotes according to the input isolist.\n\n        Parameters\n        ----------\n        ext_name : string\n            Name of the extenstion to be fitted.\n        isolist : IsophoteList\n            Input isophotes.\n\n        Returns\n        -------\n        isolist_out : IsophoteList\n            New measurements.\n        '''\n        ext = self.get_extension(ext_name)\n        if ext.mask is None:\n            image = ext.data\n        else:\n            image = np.ma.array(ext.data, mask=ext.mask)\n        isolist_out = fit_isophote(image, isolist)\n        self.isophotes[ext_name] = isolist_out\n        return isolist_out\n\n    def get_CRPIX(self):\n        '''\n        Get the reference pixel.\n        '''\n        header = self.extensions['data'][0].wcs.to_header()\n        return (header['CRPIX1'], header['CRPIX2'])\n\n    def get_extension(self, ext_name):\n        '''\n        Get the extension data.\n        '''\n        return self.extensions[ext_name][0]\n\n    def get_extent(self, units='arcsec'):\n        '''\n        Get the extent for imshow based on the data wcs.\n\n        Parameters\n        ----------\n        units : string (default: 'arcsec')\n            Units of the pixel scale.\n        '''\n        data = self.get_extension('data')\n        nrow, ncol = data.shape\n        x_len = ncol * self.get_pixelscale(units)\n        y_len = nrow * self.get_pixelscale(units)\n        extent = (-x_len/2, x_len/2, -y_len/2, y_len/2)\n        return extent\n\n    def get_ImageCenter(self):\n        '''\n        Get the central pixel of the image.\n\n        BE CAREFUL:\n            For values exactly halfway between rounded decimal values, NumPy\n            rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,\n            -0.5 and 0.5 round to 0.0, etc.\n        '''\n        image = self.get_extension('data').data\n        xcent = np.around(image.shape[1]/2.0, decimals=0)\n        ycent = np.around(image.shape[0]/2.0, decimals=0)\n        return (xcent, ycent)\n\n    def get_isolist(self, ext_name):\n        '''\n        Get isolist of an extension.\n        '''\n        return self.isophotes[ext_name]\n\n    def get_mu(self, ext_name, pixelscale=None, exptime=None, zeromag=None, sigmasky=None):\n        '''\n        Get the surface brightness.\n        '''\n        isolist = self.isophotes.get(ext_name, None)\n        if isolist is None:\n            raise KeyError('Cannot find isolist for {0}!'.format(ext_name))\n        if pixelscale is None:\n            assert self.pixelscale is not None\n            pixelscale = self.pixelscale\n        if exptime is None:\n            assert self.exptime is not None\n            exptime = self.exptime\n        if zeromag is None:\n            assert self.zeromag is not None\n            zeromag = self.zeromag\n        if sigmasky is None:\n            if self.sigmasky is None:\n                sigmasky = 0\n            else:\n                sigmasky = self.sigmasky\n\n        x = isolist.sma * pixelscale\n        y = isolist.intens / exptime / pixelscale**2\n        e = np.sqrt(isolist.int_err**2 + sigmasky**2) / exptime / pixelscale**2\n        y, e = flux2mag(y, e, zeromag)\n        return x, y, e\n\n    def get_tag(self, ext_name):\n        '''\n        Get the extension tag.\n        '''\n        return self.extensions[ext_name][1]\n\n    def get_pixelscale(self, units='arcsec'):\n        '''\n        Get pixel scale of the data image.\n        '''\n        ps_arcsec = self.pixelscale * u.arcsec\n        ps_out = ps_arcsec.to(units).value\n        return ps_out\n\n    def get_pixelscale_wcs(self, units='arcsec'):\n        '''\n        Get pixel scale of the data image from WCS.\n        '''\n        cdelt1, cdelt2 = wcs_pixel_scale(self.get_extension('data').wcs)\n        cdelt1 = cdelt1.to(units).value\n        cdelt2 = cdelt2.to(units).value\n        if not np.isclose(cdelt1, cdelt2, rtol=0.001):\n            raise ValueError('The pixel scale of two axes are not the same!')\n        ps = (cdelt1 + cdelt2) / 2\n        return ps\n\n    def grow_isophote(self, ext_name, isophote, step=0.1, fflag=0.7, maxsma=None,\n                      maxsteps=1000):\n        '''\n        Fit the isophote of the extension starting from the input isophote and\n        use its shape fixed.\n\n        Parameters\n        ----------\n        ext_name : string\n            The name of the extension.\n        isophote : photutils.isophote.Isophote\n            The isophote to be expanded.\n        step : float (default: 0.1)\n            The step value for growing/shrinking the semimajor axis.\n        fflag : float (default: 0.7)\n            The acceptable fraction of flagged data points in the\n            sample.  If the actual fraction of valid data points is\n            smaller than this, the iterations will stop.  Flagged\n            data points are points that either lie outside the image\n            frame, are masked, or were rejected by sigma-clipping.\n        maxsma (optional) : float\n            Maximum semimajor axis length, units: pixel.\n        maxsteps : int (default: 1000)\n            Maximum steps to grow the isophote.\n        '''\n        ext = self.get_extension(ext_name)\n        if ext.mask is None:\n            image = ext.data\n        else:\n            image = np.ma.array(ext.data, mask=ext.mask)\n        isolist = grow_isophote(image, isophote, step=step, fflag=fflag,\n                                maxsma=maxsma, maxsteps=maxsteps)\n        return isolist\n\n    def plot_direction(self, ax, xy, len_E=None, len_N=None, color='k', fontsize=20,\n                       linewidth=2, frac_len=0.15, units='arcsec', backextend=0.05):\n        '''\n        Plot the direction arrow. Only applied to plots using WCS.\n\n        Parameters\n        ----------\n        ax : Axis\n            Axis to plot the direction.\n        xy : (x, y)\n            Coordinate of the origin of the arrows.\n        length : float\n            Length of the arrows, units: pixel.\n        units: string (default: arcsec)\n            Units of xy.\n        '''\n        xlim = ax.get_xlim()\n        len_total = np.abs(xlim[1] - xlim[0])\n        pixelscale = self.get_pixelscale(units)\n        if len_E is None:\n            len_E = len_total * frac_len / pixelscale\n        if len_N is None:\n            len_N = len_total * frac_len / pixelscale\n\n        wcs = self.extensions['data'][0].wcs\n        header = wcs.to_header()\n        d_ra = len_E * self.get_pixelscale('degree')\n        d_dec = len_N * self.get_pixelscale('degree')\n        ra = [header['CRVAL1'], header['CRVAL1']+d_ra, header['CRVAL1']]\n        dec = [header['CRVAL2'], header['CRVAL2'], header['CRVAL2']+d_dec]\n        ra_pix, dec_pix = wcs.all_world2pix(ra, dec, 1)\n        d_arrow1 = [ra_pix[1]-ra_pix[0], dec_pix[1]-dec_pix[0]]\n        d_arrow2 = [ra_pix[2]-ra_pix[0], dec_pix[2]-dec_pix[0]]\n        l_arrow1 = np.sqrt(d_arrow1[0]**2 + d_arrow1[1]**2)\n        l_arrow2 = np.sqrt(d_arrow2[0]**2 + d_arrow2[1]**2)\n        d_arrow1 = np.array(d_arrow1) / l_arrow1 * len_E * pixelscale\n        d_arrow2 = np.array(d_arrow2) / l_arrow2 * len_N * pixelscale\n\n        def sign_2_align(sign):\n            '''\n            Determine the alignment of the text.\n            '''\n            if sign[0] < 0:\n                ha = 'right'\n            else:\n                ha = 'left'\n            if sign[1] < 0:\n                va = 'top'\n            else:\n                va = 'bottom'\n            return ha, va\n        ha1, va1 = sign_2_align(np.sign(d_arrow1))\n        ha2, va2 = sign_2_align(np.sign(d_arrow2))\n\n        xy_e = (xy[0] - d_arrow1[0] * backextend, xy[1] - d_arrow1[1] * backextend)\n        ax.annotate('E', xy=xy_e, xycoords='data', fontsize=fontsize,\n                    xytext=(d_arrow1[0]+xy[0], d_arrow1[1]+xy[1]), color=color,\n                    arrowprops=dict(color=color, arrowstyle=\"<-\", lw=linewidth),\n                    ha=ha1, va=va1)\n        xy_n = (xy[0] - d_arrow2[0] * backextend, xy[1] - d_arrow2[1] * backextend)\n        ax.annotate('N', xy=xy_n, xycoords='data', fontsize=fontsize,\n                    xytext=(d_arrow2[0]+xy[0], d_arrow2[1]+xy[1]), color=color,\n                    arrowprops=dict(color=color, arrowstyle=\"<-\", lw=linewidth),\n                    ha=ha2, va=va2)\n\n    def plot_extension(self, ext_name, stretch='asinh', units='arcsec',\n                       vmin=None, vmax=None, a=None, ax=None, plain=False,\n                       **kwargs):\n        '''\n        Plot one extenstion.\n\n        Parameters\n        ----------\n        ext_name : string\n            Extension name.\n        stretch : string (default: 'asinh')\n            Choice of stretch: asinh, linear, sqrt, log.\n        units : string (default: 'arcsec')\n            Units of pixel scale.\n        vmin (optional) : float\n            Minimal value of imshow.\n        vmax (optional) : float\n            Maximal value of imshow.\n        a (optional) : float\n            Scale factor of some stretch function.\n        ax (optional) : matplotlib Axis\n            Axis to plot the image.\n        plain : bool (default: False)\n            If False, tune the image.\n        **kwargs : Additional parameters goes into plt.imshow()\n\n        Returns\n        -------\n        ax : matplotlib Axis\n            Axis to plot the image.\n        '''\n        ext = self.get_extension(ext_name)\n        ax = plot_image(ext, ext.wcs, stretch, units, vmin, vmax, a, ax, plain, **kwargs)\n        return ax\n\n    def plot_ellipse(self, ext_name, ax=None, thin=1, **kwargs):\n        '''\n        Plot the ellipse isophotes.\n        '''\n        if ax is None:\n            plt.figure(figsize=(7, 7))\n            ax = plt.gca()\n\n        isolist = self.isophotes.get(ext_name, None)\n        if isolist is None:\n            raise KeyError('Cannot find isolist for {0}!'.format(ext_name))\n\n        if 'color' not in kwargs:\n            kwargs['color'] = 'r'\n        if 'lw' not in kwargs:\n            kwargs['lw'] = 0.5\n        for iso in isolist[::thin]:\n            x, y, = iso.sampled_coordinates()\n            ax.plot(x, y, **kwargs)\n        return ax\n\n    def plot_mu(self, ext_name, xscale='log', yscale='mag', pixelscale=None,\n                zeromag=None, exptime=None, ax=None, plain=False, show_error=True,\n                error_type='int_err', **kwargs):\n        '''\n        Plot surface brightness profile.\n        '''\n        if yscale == 'mag':\n            x, y, e = self.get_mu(ext_name, pixelscale=pixelscale, exptime=exptime,\n                                  zeromag=zeromag)\n        else:\n            isolist = self.isophotes.get(ext_name, None)\n            if isolist is None:\n                raise KeyError('Cannot find isolist for {0}!'.format(ext_name))\n            x = isolist.sma\n            y = isolist.intens\n            e = isolist.int_err\n\n        # Plot\n        if ax is None:\n            plt.figure(figsize=(7, 7))\n            ax = plt.gca()\n        if show_error is True:\n            ax.errorbar(x, y, yerr=e, **kwargs)\n        else:\n            ax.plot(x, y, **kwargs)\n        if plain is False:\n            if yscale == 'mag':\n                ax.set_xlabel(r'Radius (arcsec)', fontsize=24)\n                ax.set_ylabel(r'$\\mu\\,(\\mathrm{mag\\,arcsec^{-2}})$', fontsize=24)\n            else:\n                ax.set_xlabel(r'Radius (pixel)', fontsize=24)\n                ax.set_ylabel(r'Flux ({0} per pixel)'.format(self.unit), fontsize=24)\n            ax.minorticks_on()\n            ax.set_xscale(xscale)\n            if yscale != 'mag':\n                ax.set_yscale(yscale)\n            else:\n                ax.invert_yaxis()\n        return ax\n\n    def remove_mask(self, ext_name):\n        '''\n        Remove the mask of the extension.\n        '''\n        self.extensions[ext_name][0].mask = None\n\n    def set_mask(self, ext_name, mask):\n        '''\n        Set mask for the extension.\n\n        Parameters\n        ----------\n        ext_name : string\n            The name of the extentsion.\n        mask : 2D array\n            The mask.\n        '''\n        if ext_name not in self.extensions:\n            raise ValueError('Cannot find {0} in the extensions!'.format(ext_name))\n\n        assert self.extensions[ext_name][0].shape == mask.shape, 'Mask shape incorrect!'\n        self.extensions[ext_name][0].mask = mask\n\n    def __getitem__(self, key):\n        '''\n        Get the extension and tag.\n\n        Parameters\n        ----------\n        key : string\n            Name of extention.\n        '''\n        return self.extensions[key]\n\n    def __repr__(self):\n        ext_names = list(self.extensions.keys())\n        image = self.get_extension(self.get_ext_names()[0])\n        info1 = 'Extensions: {0}'.format(', '.join(ext_names))\n        info2 = 'Image size: {0}x{1}'.format(image.shape[1], image.shape[0])\n        return '\\n'.join([info1, info2])\n\n\nclass imgblock_subcomp(object):\n    '''\n    GALFIT subcomponent output.  E.g., output from\n        `galfit -o3 <file> (standard img. block)`\n    '''\n    def __init__(self, filename, zeromag=None, pixelscale=None, exptime=None, unit='adu'):\n        '''\n        Parameters\n        ----------\n        filename : string\n            Path of the GALFIT output file.\n        '''\n        f = fits.open(filename)\n        header = f[1].header\n        self.model_info = get_model_from_header(header)\n        self.unit = unit\n        self.zeromag = zeromag\n        self.pixelscale = pixelscale\n        self.exptime = exptime\n\n        self.extensions = {}\n        for loop in range(self.model_info['N_components']):\n            ext = CCDData.read(filename, hdu=loop+1, unit=unit)\n            ext_obj = ext.header['OBJECT']\n            counter = 0\n            comp_name = '{0}_{1}'.format(ext_obj, counter)\n            while True:\n                if comp_name in self.extensions:\n                    counter += 1\n                    comp_name = '{0}_{1}'.format(ext_obj, counter)\n                else:\n                    break\n            self.extensions[comp_name] = [ext, None]\n        self.isophotes = {}\n\n    def combine_components(self, ext_list, ext_name=None, tag=None):\n        '''\n        Combine the components.\n\n        Parameters\n        ----------\n        ext_list : list\n            List of extension names.\n\n        Returns\n        -------\n        ext : 2D array\n            Image combining different components.\n        '''\n        extList = []\n        for en in ext_list:\n            extList.append(self.get_extension(en).data)\n        ext = CCDData(np.sum(extList, axis=0), unit=self.unit)\n\n        if ext_name is not None:\n            assert ext_name not in self.extensions, 'The name has been used!'\n            self.extensions[ext_name] = (ext, tag)\n        return ext\n\n    def cut_fov(self, position, size):\n        '''\n        Cut the field of view.\n\n        Parameters\n        ----------\n        position : (x, y)\n            Position of the image center, units: pixel.\n        size : (dx, dy)\n            Size of the new image, units: pixel.\n        '''\n        for loop, ext_name in enumerate(self.extensions):\n            ext, tag = self.extensions[ext_name]\n            img_cut = Cutout2D(ext.data, position=position, size=size).data\n            if ext.mask is not None:\n                mask = Cutout2D(ext.mask, position=position, size=size).data\n            else:\n                mask = None\n            ccd_new = CCDData(img_cut, wcs=ext.wcs, mask=mask, unit=ext.unit)\n            self.extensions[ext_name] = [ccd_new, tag]\n\n    def fit_ellipse(self, ext_name, x0=None, y0=None, sma=None, eps=0, pa=0,\n                    expand=False, **kwargs):\n        '''\n        Fit isophotes of an extension.\n\n        Parameters\n        ----------\n        ext_name : string\n            Name of the extenstion to be fitted.\n        x0, y0 : float\n            The center pixel coordinate of the ellipse.\n        sma : float\n            The semimajor axis of the ellipse in pixels.\n        eps : ellipticity\n            The ellipticity of the ellipse.\n        pa : float\n            The position angle (in radians) of the semimajor axis in\n            relation to the postive x axis of the image array (rotating\n            towards the positive y axis). Position angles are defined in the\n            range :math:`0 < PA <= \\\\pi`. Avoid using as starting position\n            angle of 0., since the fit algorithm may not work properly. When\n            the ellipses are such that position angles are near either\n            extreme of the range, noise can make the solution jump back and\n            forth between successive isophotes, by amounts close to 180\n            degrees.\n        **kwargs : Additional parameters feed to ellipse.fit_image().\n\n        Returns\n        -------\n        isolist : IsophoteList instance\n            A list-like object of Isophote instances, sorted by increasing\n            semimajor axis length.\n        '''\n        ext = self.get_extension(ext_name)\n        if ext.mask is None:\n            image = ext.data\n        else:\n            image = np.ma.array(ext.data, mask=ext.mask)\n\n        if x0 is None:\n            x0 = image.shape[1] / 2\n        if y0 is None:\n            y0 = image.shape[0] / 2\n        if sma is None:\n            ## Estimate the size of the source\n            #xx, yy = np.meshgrid(np.arange(image.shape[1]), np.arange(image.shape[0]))\n            #xx = xx.astype(np.float64) - x0\n            #yy = yy.astype(np.float64) - y0\n            #rr = np.sqrt(xx**2 + yy**2)\n            #sma = np.sum(rr * image) / np.sum(image)\n            sma = 10\n\n        isolist = fit_ellipse(image, x0, y0, sma, eps, pa, **kwargs)\n\n        if expand is True:\n            step = kwargs.get('step', 0.1)\n            fflag = kwargs.get('fflag', 0.7)\n            maxsma = kwargs.get('maxsma', None)\n            isolist_exp = grow_isophote(image, isolist[-1], step=step, fflag=fflag,\n                                        maxsma=maxsma, maxsteps=np.inf)\n            isolist = isolist + isolist_exp\n\n        self.isophotes[ext_name] = isolist\n        return isolist\n\n    def fit_isophote(self, ext_name, isolist):\n        '''\n        Fit isophotes according to the input isolist.\n\n        Parameters\n        ----------\n        ext_name : string\n            Name of the extenstion to be fitted.\n        isolist : IsophoteList\n            Input isophotes.\n\n        Returns\n        -------\n        isolist_out : IsophoteList\n            New measurements.\n        '''\n        ext = self.get_extension(ext_name)\n        if ext.mask is None:\n            image = ext.data\n        else:\n            image = np.ma.array(ext.data, mask=ext.mask)\n        isolist_out = fit_isophote(image, isolist)\n        self.isophotes[ext_name] = isolist_out\n        return isolist_out\n\n    def get_ext_names(self):\n        '''\n        Get list of extension names.\n        '''\n        return list(self.extensions.keys())\n\n    def get_extension(self, ext_name):\n        '''\n        Get the extension data.\n        '''\n        return self.extensions[ext_name][0]\n\n    def get_model_param(self, ext_name, parname):\n        '''\n        Get model parameter value.\n        '''\n        idx = list(self.extensions.keys()).index(ext_name) + 1\n        info = self.model_info['COMP_{0}'.format(idx)]\n        return info.get('{0}_{1}'.format(idx, parname))\n\n    def get_mu(self, ext_name, pixelscale=None, exptime=None, zeromag=None):\n        '''\n        Get the surface brightness.\n        '''\n        isolist = self.isophotes.get(ext_name, None)\n        if isolist is None:\n            raise KeyError('Cannot find isolist for {0}!'.format(ext_name))\n        if pixelscale is None:\n            assert self.pixelscale is not None\n            pixelscale = self.pixelscale\n        if exptime is None:\n            assert self.exptime is not None\n            exptime = self.exptime\n        if zeromag is None:\n            assert self.zeromag is not None\n            zeromag = self.zeromag\n\n        x = isolist.sma * pixelscale\n        y = isolist.intens / exptime / pixelscale**2\n        e = isolist.int_err / exptime / pixelscale**2\n        y, e = flux2mag(y, e, zeromag)\n        return x, y, e\n\n    def get_isolist(self, ext_name):\n        '''\n        Get isolist of an extension.\n        '''\n        return self.isophotes[ext_name]\n\n    def get_tag(self, ext_name):\n        '''\n        Get the extension tag.\n        '''\n        return self.extensions[ext_name][1]\n\n    def plot_extension(self, ext_name, stretch='asinh', units='arcsec',\n                       vmin=None, vmax=None, a=None, ax=None, plain=False,\n                       **kwargs):\n        '''\n        Plot one extenstion.\n\n        Parameters\n        ----------\n        ext_name : string\n            Extension name.\n        stretch : string (default: 'asinh')\n            Choice of stretch: asinh, linear, sqrt, log.\n        units : string (default: 'arcsec')\n            Units of pixel scale.\n        vmin (optional) : float\n            Minimal value of imshow.\n        vmax (optional) : float\n            Maximal value of imshow.\n        a (optional) : float\n            Scale factor of some stretch function.\n        ax (optional) : matplotlib Axis\n            Axis to plot the image.\n        plain : bool (default: False)\n            If False, tune the image.\n        **kwargs : Additional parameters goes into plt.imshow()\n\n        Returns\n        -------\n        ax : matplotlib Axis\n            Axis to plot the image.\n        '''\n        ext = self.get_extension(ext_name)\n        ax = plot_image(ext, ext.wcs, stretch, units, vmin, vmax, a, ax, plain, **kwargs)\n        return ax\n\n    def plot_extension_all(self, stretch='asinh', units='arcsec', vmin=None,\n                           vmax=None, a=None, axs=None, plain=False, **kwargs):\n        '''\n        Plot all of the extensions for quick look.\n        '''\n        next = len(self.extensions)\n        if axs is None:\n            fig, axs = plt.subplots(1, next, sharey=True, figsize=(5*next, 5))\n        for loop, ext in enumerate(self.extensions):\n            ax = axs[loop]\n            self.plot_extension(ext, stretch, units, vmin, vmax, a, ax,\n                                True, **kwargs)\n            if plain is False:\n                fig.subplots_adjust(wspace=0)\n                ax.text(0.05, 0.95, ext, fontsize=20, transform=ax.transAxes,\n                        ha='left', va='top')\n        return axs\n\n    def plot_ellipse(self, ext_name, ax=None, thin=1, **kwargs):\n        '''\n        Plot the ellipse isophotes.\n        '''\n        if ax is None:\n            plt.figure(figsize=(7, 7))\n            ax = plt.gca()\n\n        isolist = self.isophotes.get(ext_name, None)\n        if isolist is None:\n            raise KeyError('Cannot find isolist for {0}!'.format(ext_name))\n\n        if 'color' not in kwargs:\n            kwargs['color'] = 'r'\n        if 'lw' not in kwargs:\n            kwargs['lw'] = 0.5\n        for iso in isolist[::thin]:\n            x, y, = iso.sampled_coordinates()\n            ax.plot(x, y, **kwargs)\n        return ax\n\n    def plot_mu(self, ext_name, xscale='log', yscale='mag', pixelscale=None,\n                zeromag=None, exptime=None, ax=None, plain=False, **kwargs):\n        '''\n        Plot surface brightness profile.\n        '''\n        if yscale == 'mag':\n            x, y, e = self.get_mu(ext_name, pixelscale=pixelscale, exptime=exptime,\n                                  zeromag=zeromag)\n        else:\n            isolist = self.isophotes.get(ext_name, None)\n            if isolist is None:\n                raise KeyError('Cannot find isolist for {0}!'.format(ext_name))\n            x = isolist.sma\n            y = isolist.intens\n            e = isolist.int_err\n\n        # Plot\n        if ax is None:\n            plt.figure(figsize=(7, 7))\n            ax = plt.gca()\n        ax.plot(x, y, **kwargs)\n        if plain is False:\n            if yscale == 'mag':\n                ax.set_xlabel(r'Radius (arcsec)', fontsize=24)\n                ax.set_ylabel(r'$\\mu\\,(\\mathrm{mag\\,arcsec^{-2}})$', fontsize=24)\n            else:\n                ax.set_xlabel(r'Radius (pixel)', fontsize=24)\n                ax.set_ylabel(r'Flux ({0} per pixel)'.format(self.unit), fontsize=24)\n            ax.minorticks_on()\n            ax.set_xscale(xscale)\n            if yscale != 'mag':\n                ax.set_yscale(yscale)\n            else:\n                ax.invert_yaxis()\n        return ax\n\n    def remove_mask(self, ext_name):\n        '''\n        Remove the mask of the extension.\n        '''\n        self.extensions[ext_name][0].mask = None\n\n    def set_mask(self, ext_name, mask):\n        '''\n        Set mask for the extension.\n\n        Parameters\n        ----------\n        ext_name : string\n            The name of the extentsion.\n        mask : 2D array\n            The mask.\n        '''\n        if ext_name not in self.extensions:\n            raise ValueError('Cannot find {0} in the extensions!'.format(ext_name))\n\n        assert self.extensions[ext_name][0].shape == mask.shape, 'Mask shape incorrect!'\n        self.extensions[ext_name][0].mask = mask\n\n    def set_tag(self, ext_name, tag):\n        '''\n        Set the tag.\n        '''\n        self.extensions[ext_name][1] = tag\n\n    def __getitem__(self, key):\n        '''\n        Get the extension and tag.\n\n        Parameters\n        ----------\n        key : string\n            Name of extention.\n        '''\n        return self.extensions[key]\n\n    def __repr__(self):\n        ext_names = list(self.extensions.keys())\n        image = self.get_extension(self.get_ext_names()[0])\n        info1 = 'Extensions: {0}'.format(', '.join(ext_names))\n        info2 = 'Image size: {0}x{1}'.format(image.shape[1], image.shape[0])\n        return '\\n'.join([info1, info2])\n", "meta": {"hexsha": "f1d65d340c8976098730f1712f38f174e084c924", "size": 30915, "ext": "py", "lang": "Python", "max_stars_repo_path": "sgGALFIT/output_wrapper.py", "max_stars_repo_name": "jyshangguan/sgAstroTool", "max_stars_repo_head_hexsha": "05392b57848598655a1d2c52fd3b1f1392243575", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-01T04:49:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-01T04:49:16.000Z", "max_issues_repo_path": "sgGALFIT/output_wrapper.py", "max_issues_repo_name": "jyshangguan/sgAstroTool", "max_issues_repo_head_hexsha": "05392b57848598655a1d2c52fd3b1f1392243575", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-12-11T06:59:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-25T15:51:13.000Z", "max_forks_repo_path": "sgGALFIT/output_wrapper.py", "max_forks_repo_name": "jyshangguan/sgAstroTool", "max_forks_repo_head_hexsha": "05392b57848598655a1d2c52fd3b1f1392243575", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-25T15:29:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-25T15:29:06.000Z", "avg_line_length": 34.696969697, "max_line_length": 91, "alphanum_fraction": 0.5406760472, "include": true, "reason": "import numpy,from astropy", "num_tokens": 7542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.1998603068335176}}
{"text": "# -*- coding: utf-8 -*-\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n#\n# Copyright (C) 2014-2018 GEM Foundation\n#\n# OpenQuake is free software: you can redistribute it and/or modify it\n# under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# OpenQuake is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"\nModule exports :class:`AbrahamsonEtAl2014`\n               :class:`AbrahamsonEtAl2014RegCHN`\n               :class:`AbrahamsonEtAl2014RegJPN`\n               :class:`AbrahamsonEtAl2014RegTWN`\n\"\"\"\nimport copy\nimport numpy as np\n\nfrom scipy import interpolate\nfrom openquake.hazardlib.gsim.base import GMPE, CoeffsTable\nfrom openquake.hazardlib import const\nfrom openquake.hazardlib.imt import PGA, PGV, SA\n\nMETRES_PER_KM = 1000.0\n\n\nclass AbrahamsonEtAl2014(GMPE):\n    \"\"\"\n    Implements GMPE by Abrahamson, Silva and Kamai developed within the\n    the PEER West 2 Project. This GMPE is described in a paper\n    published in 2014 on Earthquake Spectra, Volume 30, Number 3 and\n    titled 'Summary of the ASK14 Ground Motion Relation for Active Crustal\n    Regions'.\n    \"\"\"\n    #: Supported tectonic region type is active shallow crust, see title!\n    DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.ACTIVE_SHALLOW_CRUST\n\n    #: Supported intensity measure types are spectral acceleration, peak\n    #: ground velocity and peak ground acceleration, see tables 4\n    #: pages 1036\n    DEFINED_FOR_INTENSITY_MEASURE_TYPES = set([\n        PGA,\n        PGV,\n        SA\n    ])\n\n    #: Supported intensity measure component is orientation-independent\n    #: average horizontal :attr:`~openquake.hazardlib.const.IMC.RotD50`,\n    #: see page 1025.\n    DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = const.IMC.RotD50\n\n    #: Supported standard deviation types are inter-event, intra-event\n    #: and total, see paragraph \"Equations for standard deviations\", page\n    #: 1046.\n    DEFINED_FOR_STANDARD_DEVIATION_TYPES = set([\n        const.StdDev.TOTAL,\n        const.StdDev.INTER_EVENT,\n        const.StdDev.INTRA_EVENT\n    ])\n\n    #: Required site parameters are Vs30 and Z1.0, see table 2, page 1031\n    #: Unit of measure for Z1.0 is [m]\n    REQUIRES_SITES_PARAMETERS = set(('vs30', 'z1pt0', 'vs30measured'))\n\n    #: Required rupture parameters are magnitude, rake, dip, ztor, and width\n    #: (see table 2, page 1031)\n    REQUIRES_RUPTURE_PARAMETERS = set(('mag', 'rake', 'dip', 'ztor', 'width'))\n\n    #: Required distance measures are Rrup, Rjb, Ry0 and Rx (see Table 2,\n    #: page 1031).\n    REQUIRES_DISTANCES = set(('rrup', 'rjb', 'rx', 'ry0'))\n\n    def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):\n        \"\"\"\n        See :meth:`superclass method\n        <.base.GroundShakingIntensityModel.get_mean_and_stddevs>`\n        for spec of input and result values.\n        \"\"\"\n        # get the necessary set of coefficients\n        C = self.COEFFS[imt]\n        # compute median sa on rock (vs30=1180m/s). Used for site response\n        # term calculation\n        sa1180 = np.exp(self._get_sa_at_1180(C, imt, sites, rup, dists))\n\n        # get the mean value\n        mean = (self._get_basic_term(C, rup, dists) +\n                self._get_faulting_style_term(C, rup) +\n                self._get_site_response_term(C, imt, sites.vs30, sa1180) +\n                self._get_hanging_wall_term(C, dists, rup) +\n                self._get_top_of_rupture_depth_term(C, imt, rup) +\n                self._get_soil_depth_term(C, sites.z1pt0 / METRES_PER_KM,\n                                          sites.vs30)\n                )\n        mean += self._get_regional_term(C, imt, sites.vs30, dists.rrup)\n        # get standard deviations\n        stddevs = self._get_stddevs(C, imt, rup, sites, stddev_types, sa1180,\n                                    dists)\n        return mean, stddevs\n\n    def _get_sa_at_1180(self, C, imt, sites, rup, dists):\n        \"\"\"\n        Compute and return mean imt value for rock conditions\n        (vs30 = 1100 m/s)\n        \"\"\"\n        # reference vs30 = 1180 m/s\n        vs30_1180 = np.ones_like(sites.vs30) * 1180.\n        # reference shaking intensity = 0\n        ref_iml = np.zeros_like(sites.vs30)\n        # fake Z1.0 - Since negative it will be replaced by the default Z1.0\n        # for the corresponding region\n        fake_z1pt0 = np.ones_like(sites.vs30) * -1\n        return (self._get_basic_term(C, rup, dists) +\n                self._get_faulting_style_term(C, rup) +\n                self._get_site_response_term(C, imt, vs30_1180, ref_iml) +\n                self._get_hanging_wall_term(C, dists, rup) +\n                self._get_top_of_rupture_depth_term(C, imt, rup) +\n                self._get_soil_depth_term(C, fake_z1pt0, vs30_1180) +\n                self._get_regional_term(C, imt, vs30_1180, dists.rrup)\n                )\n\n    def _get_basic_term(self, C, rup, dists):\n        \"\"\"\n        Compute and return basic form, see page 1030.\n        \"\"\"\n        # Fictitious depth calculation\n        if rup.mag > 5.:\n            c4m = C['c4']\n        elif rup.mag > 4.:\n            c4m = C['c4'] - (C['c4']-1.) * (5. - rup.mag)\n        else:\n            c4m = 1.\n        R = np.sqrt(dists.rrup**2. + c4m**2.)\n        # basic form\n        base_term = C['a1'] * np.ones_like(dists.rrup) + C['a17'] * dists.rrup\n        # equation 2 at page 1030\n        if rup.mag >= C['m1']:\n            base_term += (C['a5'] * (rup.mag - C['m1']) +\n                          C['a8'] * (8.5 - rup.mag)**2. +\n                          (C['a2'] + C['a3'] * (rup.mag - C['m1'])) *\n                          np.log(R))\n        elif rup.mag >= self.CONSTS['m2']:\n            base_term += (C['a4'] * (rup.mag - C['m1']) +\n                          C['a8'] * (8.5 - rup.mag)**2. +\n                          (C['a2'] + C['a3'] * (rup.mag - C['m1'])) *\n                          np.log(R))\n        else:\n            base_term += (C['a4'] * (self.CONSTS['m2'] - C['m1']) +\n                          C['a8'] * (8.5 - self.CONSTS['m2'])**2. +\n                          C['a6'] * (rup.mag - self.CONSTS['m2']) +\n                          C['a7'] * (rup.mag - self.CONSTS['m2'])**2. +\n                          (C['a2'] + C['a3'] * (self.CONSTS['m2'] - C['m1'])) *\n                          np.log(R))\n        return base_term\n\n    def _get_faulting_style_term(self, C, rup):\n        \"\"\"\n        Compute and return faulting style term, that is the sum of the second\n        and third terms in equation 1, page 74.\n        \"\"\"\n        # this implements equations 5 and 6 at page 1032. f7 is the\n        # coefficient for reverse mechanisms while f8 is the correction\n        # factor for normal ruptures\n        if rup.mag > 5.0:\n            f7 = C['a11']\n            f8 = C['a12']\n        elif rup.mag >= 4:\n            f7 = C['a11'] * (rup.mag - 4.)\n            f8 = C['a12'] * (rup.mag - 4.)\n        else:\n            f7 = 0.0\n            f8 = 0.0\n        # ranges of rake values for each faulting mechanism are specified in\n        # table 2, page 1031\n        return (f7 * float(rup.rake > 30 and rup.rake < 150) +\n                f8 * float(rup.rake > -150 and rup.rake < -30))\n\n    def _get_vs30star(self, vs30, imt):\n        \"\"\"\n        This computes equations 8 and 9 at page 1034\n        \"\"\"\n        # compute the v1 value (see eq. 9, page 1034)\n        if isinstance(imt, SA):\n            t = imt.period\n            if t <= 0.50:\n                v1 = 1500.0\n            elif t < 3.0:\n                v1 = np.exp(-0.35 * np.log(t / 0.5) + np.log(1500.))\n            else:\n                v1 = 800.0\n        elif isinstance(imt, PGA):\n            v1 = 1500.0\n        else:\n            # This covers the PGV case\n            v1 = 1500.0\n        # set the vs30 star value (see eq. 8, page 1034)\n        vs30_star = np.ones_like(vs30) * vs30\n        vs30_star[vs30 >= v1] = v1\n        return vs30_star\n\n    def _get_site_response_term(self, C, imt, vs30, sa1180):\n        \"\"\"\n        Compute and return site response model term see page 1033\n        \"\"\"\n        # vs30 star\n        vs30_star = self._get_vs30star(vs30, imt)\n        # compute the site term\n        site_resp_term = np.zeros_like(vs30)\n        gt_vlin = vs30 >= C['vlin']\n        lw_vlin = vs30 < C['vlin']\n        # compute site response term for sites with vs30 greater than vlin\n        vs30_rat = vs30_star / C['vlin']\n        site_resp_term[gt_vlin] = ((C['a10'] + C['b'] * self.CONSTS['n']) *\n                                   np.log(vs30_rat[gt_vlin]))\n        # compute site response term for sites with vs30 lower than vlin\n        site_resp_term[lw_vlin] = (C['a10'] * np.log(vs30_rat[lw_vlin]) -\n                                   C['b'] * np.log(sa1180[lw_vlin] + C['c']) +\n                                   C['b'] * np.log(sa1180[lw_vlin] + C['c'] *\n                                                   vs30_rat[lw_vlin] **\n                                                   self.CONSTS['n']))\n        return site_resp_term\n\n    def _get_hanging_wall_term(self, C, dists, rup):\n        \"\"\"\n        Compute and return hanging wall model term, see page 1038.\n        \"\"\"\n        if rup.dip == 90.0:\n            return np.zeros_like(dists.rx)\n        else:\n            Fhw = np.zeros_like(dists.rx)\n            Fhw[dists.rx > 0] = 1.\n            # Compute taper t1\n            T1 = np.ones_like(dists.rx)\n            T1 *= 60./45. if rup.dip <= 30. else (90.-rup.dip)/45.0\n            # Compute taper t2 (eq 12 at page 1039) - a2hw set to 0.2 as\n            # indicated at page 1041\n            T2 = np.zeros_like(dists.rx)\n            a2hw = 0.2\n            if rup.mag > 6.5:\n                T2 += (1. + a2hw * (rup.mag - 6.5))\n            elif rup.mag > 5.5:\n                T2 += (1. + a2hw * (rup.mag - 6.5) - (1. - a2hw) *\n                       (rup.mag - 6.5)**2)\n            else:\n                T2 *= 0.\n            # Compute taper t3 (eq. 13 at page 1039) - r1 and r2 specified at\n            # page 1040\n            T3 = np.zeros_like(dists.rx)\n            r1 = rup.width * np.cos(np.radians(rup.dip))\n            r2 = 3. * r1\n            #\n            idx = dists.rx < r1\n            T3[idx] = (np.ones_like(dists.rx)[idx] * self.CONSTS['h1'] +\n                       self.CONSTS['h2'] * (dists.rx[idx] / r1) +\n                       self.CONSTS['h3'] * (dists.rx[idx] / r1)**2)\n            #\n            idx = ((dists.rx >= r1) & (dists.rx <= r2))\n            T3[idx] = 1. - (dists.rx[idx] - r1) / (r2 - r1)\n            # Compute taper t4 (eq. 14 at page 1040)\n            T4 = np.zeros_like(dists.rx)\n            #\n            if rup.ztor <= 10.:\n                T4 += (1. - rup.ztor**2. / 100.)\n            # Compute T5 (eq 15a at page 1040) - ry1 computed according to\n            # suggestions provided at page 1040\n            T5 = np.zeros_like(dists.rx)\n            ry1 = dists.rx * np.tan(np.radians(20.))\n            #\n            idx = (dists.ry0 - ry1) <= 0.0\n            T5[idx] = 1.\n            #\n            idx = (((dists.ry0 - ry1) > 0.0) & ((dists.ry0 - ry1) < 5.0))\n            T5[idx] = 1. - (dists.ry0[idx] - ry1[idx]) / 5.0\n            # Finally, compute the hanging wall term\n            return Fhw*C['a13']*T1*T2*T3*T4*T5\n\n    def _get_top_of_rupture_depth_term(self, C, imt, rup):\n        \"\"\"\n        Compute and return top of rupture depth term. See paragraph\n        'Depth-to-Top of Rupture Model', page 1042.\n        \"\"\"\n        if rup.ztor >= 20.0:\n            return C['a15']\n        else:\n            return C['a15'] * rup.ztor / 20.0\n\n    def _get_z1pt0ref(self, vs30):\n        \"\"\"\n        This computes the reference depth to the 1.0 km/s interface using\n        equation 18 at page 1042 of Abrahamson et al. (2014)\n        \"\"\"\n        return (1. / 1000.) * np.exp((-7.67 / 4.)*np.log((vs30**4 + 610.**4) /\n                                                         (1360.**4 + 610.**4)))\n\n    def _get_soil_depth_term(self, C, z1pt0, vs30):\n        \"\"\"\n        Compute and return soil depth term.  See page 1042.\n        \"\"\"\n        # Get reference z1pt0\n        z1ref = self._get_z1pt0ref(vs30)\n        # Get z1pt0\n        z10 = copy.deepcopy(z1pt0)\n        # This is used for the calculation of the motion on reference rock\n        idx = z1pt0 < 0\n        z10[idx] = z1ref[idx]\n        factor = np.log((z10 + 0.01) / (z1ref + 0.01))\n        # Here we use a linear interpolation as suggested in the 'Application\n        # guidelines' at page 1044\n        # Above 700 m/s the trend is flat, but we extend the Vs30 range to\n        # 6,000 m/s (basically the upper limit for mantle shear wave velocity\n        # on earth) to allow extrapolation without throwing an error.\n        f2 = interpolate.interp1d(\n            [0.0, 150, 250, 400, 700, 1000, 6000],\n            [C['a43'], C['a43'], C['a44'], C['a45'], C['a46'], C['a46'],\n             C['a46']],\n            kind='linear')\n        return f2(vs30) * factor\n\n    def _get_regional_term(self, C, imt, vs30, rrup):\n        \"\"\"\n        In accordance with Abrahamson et al. (2014) we assume California\n        as the default region hence here the regional term is assumed = 0.\n        \"\"\"\n        return 0.\n\n    def _get_stddevs(self, C, imt, rup, sites, stddev_types, sa1180, dists):\n        \"\"\"\n        Return standard deviations as described in paragraph 'Equations for\n        standard deviation', page 1046.\n        \"\"\"\n        std_intra = self._get_intra_event_std(C, rup.mag, sa1180, sites.vs30,\n                                              sites.vs30measured, dists.rrup)\n        std_inter = self._get_inter_event_std(C, rup.mag, sa1180, sites.vs30)\n        stddevs = []\n        for stddev_type in stddev_types:\n            assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES\n            if stddev_type == const.StdDev.TOTAL:\n                stddevs.append(np.sqrt(std_intra ** 2 +\n                                       std_inter ** 2))\n            elif stddev_type == const.StdDev.INTRA_EVENT:\n                stddevs.append(std_intra)\n            elif stddev_type == const.StdDev.INTER_EVENT:\n                stddevs.append(std_inter)\n        return stddevs\n\n    def _get_intra_event_std(self, C, mag, sa1180, vs30, vs30measured,\n                             rrup):\n        \"\"\"\n        Returns Phi as described at pages 1046 and 1047\n        \"\"\"\n        phi_al = self._get_phi_al_regional(C, mag, vs30measured, rrup)\n        derAmp = self._get_derivative(C, sa1180, vs30)\n        phi_amp = 0.4\n        idx = phi_al < phi_amp\n        if np.any(idx):\n            # In the case of small magnitudes and long periods it is possible\n            # for phi_al to take a value less than phi_amp, which would return\n            # a complex value. According to the GMPE authors in this case\n            # phi_amp should be reduced such that it is fractionally smaller\n            # than phi_al\n            phi_amp = 0.4 * np.ones_like(phi_al)\n            phi_amp[idx] = 0.99 * phi_al[idx]\n        phi_b = np.sqrt(phi_al**2 - phi_amp**2)\n        phi = np.sqrt(phi_b**2 * (1 + derAmp)**2 + phi_amp**2)\n        return phi\n\n    def _get_derivative(self, C, sa1180, vs30):\n        \"\"\"\n        Returns equation 30 page 1047\n        \"\"\"\n        derAmp = np.zeros_like(vs30)\n        n = self.CONSTS['n']\n        c = C['c']\n        b = C['b']\n        idx = vs30 < C['vlin']\n        derAmp[idx] = (b * sa1180[idx] * (-1./(sa1180[idx]+c) +\n                       1./(sa1180[idx] + c*(vs30[idx]/C['vlin'])**n)))\n        return derAmp\n\n    def _get_phi_al_regional(self, C, mag, vs30measured, rrup):\n        \"\"\"\n        Returns intra-event (Phi) standard deviation (equation 24, page 1046)\n        \"\"\"\n        phi_al = np.ones((len(vs30measured)))\n        s1 = np.ones_like(phi_al) * C['s1e']\n        s2 = np.ones_like(phi_al) * C['s2e']\n        s1[vs30measured] = C['s1m']\n        s2[vs30measured] = C['s2m']\n        if mag < 4:\n            phi_al *= s1\n        elif mag <= 6:\n            phi_al *= s1 + (s2 - s1) / 2. * (mag - 4.)\n        else:\n            phi_al *= s2\n        return phi_al\n\n    def _get_inter_event_std(self, C, mag, sa1180, vs30):\n        \"\"\"\n        Returns inter event (tau) standard deviation (equation 25, page 1046)\n        \"\"\"\n        if mag < 5:\n            tau_al = C['s3']\n        elif mag <= 7:\n            tau_al = C['s3'] + (C['s4'] - C['s3']) / 2. * (mag - 5.)\n        else:\n            tau_al = C['s4']\n        tau_b = tau_al\n        tau = tau_b * (1 + self._get_derivative(C, sa1180, vs30))\n        return tau\n\n    #: Coefficient tables as per annex B of Abrahamson et al. (2014)\n    COEFFS = CoeffsTable(sa_damping=5, table=\"\"\"\\\nIMT     m1      vlin    b       c       c4      a1      a2      a3      a4      a5      a6      a7   a8      a10     a11     a12     a13     a14     a15     a17     a43     a44     a45     a46     a25     a28     a29     a31     a36     a37     a38     a39     a40     a41     a42     s1e     s2e     s3      s4      s1m     s2m     s5      s6\npga     6.75    660     -1.47   2.4     4.5     0.587   -0.79   0.275   -0.1    -0.41   2.154   0.0  -0.015  1.735   0       -0.1    0.6     -0.3    1.1     -0.0072 0.1     0.05    0       -0.05   -0.0015 0.0025  -0.0034 -0.1503 0.265   0.337   0.188   0       0.088   -0.196  0.044   0.754   0.52    0.47    0.36    0.741   0.501   0.54    0.6300\npgv     6.75    330     -2.02   2400    4.5     5.975   -0.919  0.275   -0.1    -0.41   2.366   0.0  -0.094  2.36    0       -0.1    0.25    0.22    0.3     -0.0005 0.28    0.15    0.09    0.07    -0.0001 0.0005  -0.0037 -0.1462 0.377   0.212   0.157   0       0.095   -0.038  0.065   0.662   0.51    0.38    0.38    0.66    0.51    0.58    0.5300\n0.01    6.75    660     -1.47   2.4     4.5     0.587   -0.790  0.275   -0.1    -0.41   2.154   0.0  -0.015  1.735   0       -0.1    0.6     -0.3    1.1     -0.0072 0.1     0.05    0       -0.05   -0.0015 0.0025  -0.0034 -0.1503 0.265   0.337   0.188   0       0.088   -0.196  0.044   0.754   0.52    0.47    0.36    0.741   0.501   0.54    0.6300\n0.02    6.75    680     -1.46   2.4     4.5     0.598   -0.790  0.275   -0.1    -0.41   2.146   0.0  -0.015  1.718   0       -0.1    0.6     -0.3    1.1     -0.0073 0.1     0.05    0       -0.05   -0.0015 0.0024  -0.0033 -0.1479 0.255   0.328   0.184   0       0.088   -0.194  0.061   0.76    0.52    0.47    0.36    0.747   0.501   0.54    0.6300\n0.03    6.75    770     -1.39   2.4     4.5     0.602   -0.790  0.275   -0.1    -0.41   2.157   0.0  -0.015  1.615   0       -0.1    0.6     -0.3    1.1     -0.0075 0.1     0.05    0       -0.05   -0.0016 0.0023  -0.0034 -0.1447 0.249   0.32    0.18    0       0.093   -0.175  0.162   0.781   0.52    0.47    0.36    0.769   0.501   0.55    0.6300\n0.05    6.75    915     -1.22   2.4     4.5     0.707   -0.790  0.275   -0.1    -0.41   2.085   0.0  -0.015  1.358   0       -0.1    0.6     -0.3    1.1     -0.008  0.1     0.05    0       -0.05   -0.002  0.0027  -0.0033 -0.1326 0.202   0.289   0.167   0       0.133   -0.09   0.451   0.81    0.53    0.47    0.36    0.798   0.512   0.56    0.6500\n0.075   6.75    960     -1.15   2.4     4.5     0.973   -0.790  0.275   -0.1    -0.41   2.029   0.0  -0.015  1.258   0       -0.1    0.6     -0.3    1.1     -0.0089 0.1     0.05    0       -0.05   -0.0027 0.0032  -0.0029 -0.1353 0.126   0.275   0.173   0       0.186   0.09    0.506   0.81    0.54    0.47    0.36    0.798   0.522   0.57    0.6900\n0.1     6.75    910     -1.23   2.4     4.5     1.169   -0.790  0.275   -0.1    -0.41   2.041   0.0  -0.015  1.31    0       -0.1    0.6     -0.3    1.1     -0.0095 0.1     0.05    0       -0.05   -0.0033 0.0036  -0.0025 -0.1128 0.022   0.256   0.189   0       0.16    0.006   0.335   0.81    0.55    0.47    0.36    0.795   0.527   0.57    0.7000\n0.15    6.75    740     -1.59   2.4     4.5     1.442   -0.790  0.275   -0.1    -0.41   2.121   0.0  -0.022  1.66    0       -0.1    0.6     -0.3    1.1     -0.0095 0.1     0.05    0       -0.05   -0.0035 0.0033  -0.0025 0.0383  -0.136  0.162   0.108   0       0.068   -0.156  -0.084  0.801   0.56    0.47    0.36    0.773   0.519   0.58    0.7000\n0.2     6.75    590     -2.01   2.4     4.5     1.637   -0.790  0.275   -0.1    -0.41   2.224   0.0  -0.03   2.22    0       -0.1    0.6     -0.3    1.1     -0.0086 0.1     0.05    0       -0.03   -0.0033 0.0027  -0.0031 0.0775  -0.078  0.224   0.115   0       0.048   -0.274  -0.178  0.789   0.565   0.47    0.36    0.753   0.514   0.59    0.7000\n0.25    6.75    495     -2.41   2.4     4.5     1.701   -0.790  0.275   -0.1    -0.41   2.312   0.0  -0.038  2.77    0       -0.1    0.6     -0.24   1.1     -0.0074 0.1     0.05    0       0       -0.0029 0.0024  -0.0036 0.0741  0.037   0.248   0.122   0       0.055   -0.248  -0.187  0.77    0.57    0.47    0.36    0.729   0.513   0.61    0.7000\n0.3     6.75    430     -2.76   2.4     4.5     1.712   -0.790  0.275   -0.1    -0.41   2.338   0.0  -0.045  3.25    0       -0.1    0.6     -0.19   1.03    -0.0064 0.1     0.05    0.03    0.03    -0.0027 0.002   -0.0039 0.2548  -0.091  0.203   0.096   0       0.073   -0.203  -0.159  0.74    0.58    0.47    0.36    0.693   0.519   0.63    0.7000\n0.4     6.75    360     -3.28   2.4     4.5     1.662   -0.790  0.275   -0.1    -0.41   2.469   0.0  -0.055  3.99    0       -0.1    0.58    -0.11   0.92    -0.0043 0.1     0.07    0.06    0.06    -0.0023 0.001   -0.0048 0.2136  0.129   0.232   0.123   0       0.143   -0.154  -0.023  0.699   0.59    0.47    0.36    0.644   0.524   0.66    0.7000\n0.5     6.75    340     -3.6    2.4     4.5     1.571   -0.790  0.275   -0.1    -0.41   2.559   0.0  -0.065  4.45    0       -0.1    0.56    -0.04   0.84    -0.0032 0.1     0.1     0.1     0.09    -0.002  0.0008  -0.005  0.1542  0.31    0.252   0.134   0       0.16    -0.159  -0.029  0.676   0.6     0.47    0.36    0.616   0.532   0.69    0.7000\n0.75    6.75    330     -3.8    2.4     4.5     1.299   -0.790  0.275   -0.1    -0.41   2.682   0.0  -0.095  4.75    0       -0.1    0.53    0.07    0.68    -0.0025 0.14    0.14    0.14    0.13    -0.001  0.0007  -0.0041 0.0787  0.505   0.208   0.129   0       0.158   -0.141  0.061   0.631   0.615   0.47    0.36    0.566   0.548   0.73    0.6900\n1       6.75    330     -3.5    2.4     4.5     1.043   -0.790  0.275   -0.1    -0.41   2.763   0.0  -0.11   4.3     0       -0.1    0.5     0.15    0.57    -0.0025 0.17    0.17    0.17    0.14    -0.0005 0.0007  -0.0032 0.0476  0.358   0.208   0.152   0       0.145   -0.144  0.062   0.609   0.63    0.47    0.36    0.541   0.565   0.77    0.6800\n1.5     6.75    330     -2.4    2.4     4.5     0.665   -0.790  0.275   -0.1    -0.41   2.836   0.0  -0.124  2.6     0       -0.1    0.42    0.27    0.42    -0.0022 0.22    0.21    0.2     0.16    -0.0004 0.0006  -0.002  -0.0163 0.131   0.108   0.118   0       0.131   -0.126  0.037   0.578   0.64    0.47    0.36    0.506   0.576   0.8     0.6600\n2       6.75    330     -1      2.4     4.5     0.329   -0.790  0.275   -0.1    -0.41   2.897   0.0  -0.138  0.55    0       -0.1    0.35    0.35    0.31    -0.0019 0.26    0.25    0.22    0.16    -0.0002 0.0003  -0.0017 -0.1203 0.123   0.068   0.119   0       0.083   -0.075  -0.143  0.555   0.65    0.47    0.36    0.48    0.587   0.8     0.6200\n3       6.82    330     0       2.4     4.5     -0.060  -0.790  0.275   -0.1    -0.41   2.906   0.0  -0.172  -0.95   0       -0.1    0.2     0.46    0.16    -0.0015 0.34    0.3     0.23    0.16    0       0       -0.002  -0.2719 0.109   -0.023  0.093   0       0.07    -0.021  -0.028  0.548   0.64    0.47    0.36    0.472   0.576   0.8     0.5500\n4       6.92    330     0       2.4     4.5     -0.299  -0.790  0.275   -0.1    -0.41   2.889   0.0  -0.197  -0.95   0       -0.1    0       0.54    0.05    -0.001  0.41    0.32    0.23    0.14    0       0       -0.002  -0.2958 0.135   0.028   0.084   0       0.101   0.072   -0.097  0.527   0.63    0.47    0.36    0.447   0.565   0.76    0.5200\n5       7       330     0       2.4     4.5     -0.562  -0.765  0.275   -0.1    -0.41   2.898   0.0  -0.218  -0.93   0       -0.1    0       0.61    -0.04   -0.001  0.51    0.32    0.22    0.13    0       0       -0.002  -0.2718 0.189   0.031   0.058   0       0.095   0.205   0.015   0.505   0.63    0.47    0.36    0.425   0.568   0.72    0.5000\n6       7.06    330     0       2.4     4.5     -0.875  -0.711  0.275   -0.1    -0.41   2.896   0.0  -0.235  -0.91   0       -0.2    0       0.65    -0.11   -0.001  0.55    0.32    0.2     0.1     0       0       -0.002  -0.2517 0.215   0.024   0.065   0       0.133   0.285   0.104   0.477   0.63    0.47    0.36    0.395   0.571   0.7     0.5000\n7.5     7.15    330     0       2.4     4.5     -1.303  -0.634  0.275   -0.1    -0.41   2.870   0.0  -0.255  -0.87   0       -0.2    0       0.72    -0.19   -0.001  0.49    0.28    0.17    0.09    0       0       -0.002  -0.14   0.15    -0.07   0       0       0.151   0.329   0.299   0.457   0.63    0.47    0.36    0.378   0.575   0.67    0.5000\n10      7.25    330     0       2.4     4.5     -1.928  -0.529  0.275   -0.1    -0.41   2.843   0.0  -0.285  -0.8    0       -0.2    0       0.8     -0.3    -0.001  0.42    0.22    0.14    0.08    0       0       -0.002  -0.0216 0.092   -0.159  -0.05   0       0.124   0.301   0.243   0.429   0.63    0.47    0.36    0.359   0.585   0.64    0.5000\n    \"\"\")\n\n    #: equation constants (that are IMT independent)\n    CONSTS = {\n        'n': 1.5,\n        # m2 specified at page 1032 (top)\n        'm2': 5.00,\n        # h1, h2, h3 specified at page 1040 (top)\n        'h1': +0.25,\n        'h2': +1.50,\n        'h3': -0.75,\n    }\n\n\nclass AbrahamsonEtAl2014RegTWN(AbrahamsonEtAl2014):\n    \"\"\"\n    Implements GMPE developed by Abrahamson, Silva and Kamai in 2014 as\n    part of the PEER West 2 Project. The GMPE is described in a paper\n    published in 2014 on Earthquake Spectra, Volume 30, Number 3.\n\n    Regional corrections for Taiwan\n    \"\"\"\n\n    def _get_regional_term(self, C, imt, vs30, rrup):\n        \"\"\"\n        In accordance with Abrahamson et al. (2014) we assume as the default\n        region California\n        \"\"\"\n        vs30star = self._get_vs30star(vs30, imt)\n        return C['a31'] * np.log(vs30star/C['vlin']) + C['a25'] * rrup\n\n\nclass AbrahamsonEtAl2014RegCHN(AbrahamsonEtAl2014):\n    \"\"\"\n    Implements GMPE developed by Abrahamson, Silva and Kamai in 2014 as\n    part of the PEER West 2 Project. The GMPE is described in a paper\n    published in 2014 on Earthquake Spectra, Volume 30, Number 3.\n\n    Regional corrections for China\n    \"\"\"\n\n    def _get_regional_term(self, C, imt, vs30, rrup):\n        \"\"\"\n        In accordance with Abrahamson et al. (2014) we assume as the default\n        region California\n        \"\"\"\n        return C['a28'] * rrup\n\n\nclass AbrahamsonEtAl2014RegJPN(AbrahamsonEtAl2014):\n    \"\"\"\n    Implements GMPE developed by Abrahamson, Silva and Kamai in 2014 as\n    part of the PEER West 2 Project. The GMPE is described in a paper\n    published in 2014 on Earthquake Spectra, Volume 30, Number 3.\n\n    Regional corrections for Japan\n    \"\"\"\n\n    def _get_z1pt0ref(self, vs30):\n        \"\"\"\n        This provides the default depth to the 1.0 km/s interface for Japan\n        \"\"\"\n        return 1./1000. * np.exp(-5.23/2.*np.log((vs30**2+412.**2.) /\n                                                 (1360.**2+412**2.)))\n\n    def _get_regional_term(self, C, imt, vs30, rrup):\n        \"\"\"\n        Compute regional term for Japan. See page 1043\n        \"\"\"\n        f3 = interpolate.interp1d(\n            [150, 250, 350, 450, 600, 850, 1150, 2000],\n            [C['a36'], C['a37'], C['a38'], C['a39'], C['a40'], C['a41'],\n             C['a42'], C['a42']],\n            kind='linear')\n        return f3(vs30) + C['a29'] * rrup\n\n    def _get_phi_al_regional(self, C, mag, vs30measured, rrup):\n        \"\"\"\n        Returns intra-event (Tau) standard deviation (equation 26, page 1046)\n        \"\"\"\n        phi_al = np.ones((len(vs30measured)))\n\n        idx = rrup < 30\n        phi_al[idx] *= C['s5']\n\n        idx = ((rrup <= 80) & (rrup >= 30.))\n        phi_al[idx] *= C['s5'] + (C['s6'] - C['s5']) / 50. * (rrup[idx] - 30.)\n\n        idx = rrup > 80\n        phi_al[idx] *= C['s6']\n\n        return phi_al\n", "meta": {"hexsha": "3d8e6846d0e6f19583d45891d0b1f50e22cdf3c4", "size": 28590, "ext": "py", "lang": "Python", "max_stars_repo_path": "openquake/hazardlib/gsim/abrahamson_2014.py", "max_stars_repo_name": "gfzriesgos/shakyground-lfs", "max_stars_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-01T00:28:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-01T00:28:24.000Z", "max_issues_repo_path": "openquake/hazardlib/gsim/abrahamson_2014.py", "max_issues_repo_name": "gfzriesgos/shakyground-lfs", "max_issues_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-08-31T14:14:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-11T12:53:13.000Z", "max_forks_repo_path": "openquake/hazardlib/gsim/abrahamson_2014.py", "max_forks_repo_name": "gfzriesgos/shakyground-lfs", "max_forks_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-08-31T14:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-17T10:06:02.000Z", "avg_line_length": 53.1412639405, "max_line_length": 347, "alphanum_fraction": 0.4981811822, "include": true, "reason": "import numpy,from scipy", "num_tokens": 11062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.19985352561001243}}
{"text": "from amuse.community import *\n\nfrom amuse.community.interface.mhd import MagnetohydrodynamicsInterface\nfrom amuse.community.interface.common import CommonCode\n\nimport numpy\n\nfrom amuse.units.generic_unit_system import *\n\nclass AthenaInterface(CodeInterface, MagnetohydrodynamicsInterface, LiteratureReferencesMixIn, StoppingConditionInterface):\n    \"\"\"\n    Athena is a grid-based code for astrophysical hydrodynamics. Athena can solve \n    magnetohydrodynamics (MHD) as well, but this is currently not supported from \n    AMUSE. It was developed primarily for studies of the interstellar medium, \n    star formation, and accretion flows.\n    \n    The current version (Athena v4.0) implements algorithms for the following physics:\n    * compressible hydrodynamics and MHD in 1D, 2D, and 3D,\n    * ideal gas equation of state with arbitrary gamma (including gamma = 1, an isothermal EOS),\n    * an arbitrary number of passive scalars advected with the flow,\n    * self-gravity, and/or a static gravitational potential,\n    * Ohmic resistivity, ambipolar diffusion, and the Hall effect,\n    * both Navier-Stokes and anisotropic (Braginskii) viscosity,\n    * both isotropic and anisotropic thermal conduction,\n    * optically-thin radiative cooling. \n    \n    In addition, Athena allows for the following grid and parallelization options:\n    * Cartesian or cylindrical coordinates,\n    * static (fixed) mesh refinement,\n    * shearing-box source terms, and an orbital advection algorithm for MHD,\n    * parallelization using domain decomposition and  MPI. \n    \n    A variety of choices are also available for the numerical algorithms, such as \n    different Riemann solvers and spatial reconstruction methods.\n    \n    The relevant references are:\n        .. [#] Gardiner & Stone 2005, JCP, 205, 509  (2D JCP Method)\n        .. [#] Gardiner & Stone 2007, JCP, 227, 4123 (3D JCP Method)\n        .. [#] Stone et al. 2008, ApJS, 178, 137 (Method)\n        .. [#] Stone & Gardiner 2009, NewA, 14, 139 (van Leer Integrator)\n        .. [#] Skinner & Ostriker 2010, ApJ, 188, 290 (Cylindrical Integrator)\n        .. [#] Stone & Gardiner 2010, ApJS, 189, 142 (Shearing Box Method)\n    \"\"\"\n    \n    include_headers = ['worker_code.h', 'stopcond.h']\n    \n    MODE_NORMAL = 'normal'\n    MODE_SELF_GRAVITY   = 'self-gravity'\n    MODE_MHD   = 'mhd'\n    MODE_SCALAR   = 'scalar'\n    \n    def __init__(self, mode = MODE_NORMAL, **options):\n        \n        self.mode = mode\n        CodeInterface.__init__(self, name_of_the_worker=self.name_of_the_worker(mode), **options)\n        self.set_auto_decomposition(1)\n        self.par_seti(\"domain1\", \"AutoWithNProc\", \"%d\", self.channel.number_of_workers, \"-\")\n        LiteratureReferencesMixIn.__init__(self)\n        self.number_of_grids = 1\n        \n    def name_of_the_worker(self, mode):\n        if mode == self.MODE_NORMAL:\n            return 'athena_worker'\n        elif mode == self.MODE_SELF_GRAVITY:\n            return 'athena_worker_selfgrav'\n        elif mode == self.MODE_MHD:\n            return 'athena_worker_mhd'\n        elif mode == self.MODE_SCALAR:\n            return 'athena_worker_scalar'\n        else:\n            return 'athena_worker'\n        \n    @legacy_function\n    def par_seti():\n        function = LegacyFunctionSpecification() \n        function.addParameter('block', dtype='s', direction=function.IN) \n        function.addParameter('name', dtype='s', direction=function.IN) \n        function.addParameter('fmt', dtype='s', direction=function.IN) \n        function.addParameter('ival', dtype='int32', direction=function.IN) \n        function.addParameter('comment', dtype='s', direction=function.IN) \n        function.result_type = None\n        return function\n        \n    @legacy_function\n    def par_geti():\n        function = LegacyFunctionSpecification() \n        function.addParameter('block', dtype='s', direction=function.IN) \n        function.addParameter('name', dtype='s', direction=function.IN) \n        function.result_type = 'int32'\n        return function\n        \n    @legacy_function\n    def par_setd():\n        function = LegacyFunctionSpecification() \n        function.addParameter('block', dtype='s', direction=function.IN) \n        function.addParameter('name', dtype='s', direction=function.IN) \n        function.addParameter('fmt', dtype='s', direction=function.IN) \n        function.addParameter('dval', dtype='float64', direction=function.IN) \n        function.addParameter('comment', dtype='s', direction=function.IN) \n        function.result_type = None\n        return function\n        \n    @legacy_function\n    def par_getd():\n        function = LegacyFunctionSpecification() \n        function.addParameter('block', dtype='s', direction=function.IN) \n        function.addParameter('name', dtype='s', direction=function.IN) \n        function.result_type = 'float64'\n        return function\n          \n    def setup_mesh(self, nmeshx, nmeshy, nmeshz, xlength, ylength, zlength):\n        self.par_seti(\"job\",\"num_domains\", \"%d\", self.number_of_grids, \"-\")\n        self.par_seti(\"domain1\", \"level\", \"%d\", 0, \"-\")\n        \n        self.par_seti(\"domain1\", \"Nx1\", \"%d\", nmeshx, \"-\")\n        self.par_seti(\"domain1\", \"Nx2\", \"%d\", nmeshy, \"-\")\n        self.par_seti(\"domain1\", \"Nx3\", \"%d\", nmeshz, \"-\")\n        \n        self.par_setd(\"domain1\", \"x1min\", \"%.15e\", 0.0, \"-\")\n        self.par_setd(\"domain1\", \"x1max\", \"%.15e\", xlength, \"-\")\n        self.par_setd(\"domain1\", \"x2min\", \"%.15e\", 0.0, \"-\")\n        self.par_setd(\"domain1\", \"x2max\", \"%.15e\", ylength, \"-\")\n        self.par_setd(\"domain1\", \"x3min\", \"%.15e\", 0.0, \"-\")\n        self.par_setd(\"domain1\", \"x3max\", \"%.15e\", zlength, \"-\")\n        self.par_seti(\"domain1\", \"iDisp\", \"%d\", 0, \"-\")\n        self.par_seti(\"domain1\", \"jDisp\", \"%d\", 0, \"-\")\n        self.par_seti(\"domain1\", \"kDisp\", \"%d\", 0, \"-\")\n        \n        return 0\n    \n    def define_subgrid(self, level, nmeshx, nmeshy, nmeshz, i, j, k):\n        \"\"\"\n        Define a new domain on the given level the number of cells in this \n        domain is given by nmeshx,  nmeshy, nmeshz. \n        \n        Each level is twice as dense as in every directory as \n        the previous level (there are 8 cells per higher level cell).\n        \"\"\"\n        self.number_of_grids += 1\n        \n        domain = \"domain{0}\".format(self.number_of_grids)\n        \n        self.par_seti(\"job\",\"num_domains\", \"%d\", self.number_of_grids, \"-\")\n        \n        self.par_seti(domain, \"level\", \"%d\", level, \"-\")\n        self.par_seti(domain, \"Nx1\", \"%d\", nmeshx, \"-\")\n        self.par_seti(domain, \"Nx2\", \"%d\", nmeshy, \"-\")\n        self.par_seti(domain, \"Nx3\", \"%d\", nmeshz, \"-\")\n        self.par_seti(domain, \"iDisp\", \"%d\", i, \"-\")\n        self.par_seti(domain, \"jDisp\", \"%d\", j, \"-\")\n        self.par_seti(domain, \"kDisp\", \"%d\", k, \"-\")\n        \n        return self.number_of_grids\n\n    @legacy_function    \n    def get_position_of_index():\n        \"\"\"\n        Retrieves the x, y and z position of the center of\n        the cell with coordinates i, j, k in the grid specified\n        by the index_of_grid\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.must_handle_array = True\n        for x in ['i','j','k']:\n            function.addParameter(x, dtype='i', direction=function.IN)\n        function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1)\n        for x in ['x','y','z']:\n            function.addParameter(x, dtype='d', direction=function.OUT)\n        function.addParameter('number_of_points', 'i', function.LENGTH)           \n        function.result_type = 'i'\n        return function\n    \n    '''\n    @legacy_function    \n    def get_index_of_position():\n        \"\"\"\n        Retrieves the i,j and k index of the grid cell containing the\n        given x, y and z position. The cell is looked up\n        in the grid specified by index_of_grid.\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.must_handle_array = True\n        for x in ['x','y','z']:\n            function.addParameter(x, dtype='d', direction=function.IN)\n        \n        function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1)\n        \n        for x in ['i','j','k']:\n            function.addParameter(x, dtype='d', direction=function.OUT)\n        function.addParameter('number_of_points', 'i', function.LENGTH)\n\n        function.result_type = 'i'\n        return function\n    '''\n    def get_index_range_inclusive(self, index_of_grid = 1):\n        \"\"\"\n        Returns the min and max values of indices in each\n        direction. The range is inclusive, the min index\n        and max index both exist and can be queried.\n        The total number of cells in one direction\n        is max - min + 1.\n        \"\"\"\n        domainid = \"domain{0}\".format(index_of_grid)\n        \n        ni = self.par_geti(domainid, \"Nx1\")\n        nj = self.par_geti(domainid, \"Nx2\")\n        nk = self.par_geti(domainid, \"Nx3\")\n        idisp = self.par_geti(domainid, \"iDisp\")\n        jdisp = self.par_geti(domainid, \"jDisp\")\n        kdisp = self.par_geti(domainid, \"kDisp\")\n        #print index_of_grid, \"  ===  > \", (idisp, idisp+ni[0]-1, jdisp, jdisp + nj[0]-1, kdisp, kdisp + nk[0]-1)\n        \n        return (idisp, idisp+ni-1, jdisp, jdisp + nj-1, kdisp, kdisp + nk-1)\n        \n    \n\n    def get_index_range_magnetic_field_inclusive(self, index_of_grid = 1):\n        original = list(self.get_index_range_inclusive(index_of_grid))\n        original[1] += 1\n        original[3] += 1\n        original[5] += 1\n        return original\n        \n    def get_mesh_indices(self):\n        \"\"\"\n        Return 3 arrays, containing the indices for i, j and k\n        \"\"\"\n        si,ei,sj,ej,sk,ek = self.get_index_range_inclusive()\n        indexgrid = numpy.mgrid[slice(si,ei+1),slice(sj,ej+1),slice(sk,ek+1)]\n        return indexgrid.reshape(3, -1)\n        \n    \n        \n    def set_four_pi_G(self, value):\n        self.par_setd(\"problem\", \"four_pi_G\", \"%.15e\", value, \"\")\n        return 0 \n        \n    def set_grav_mean_rho(self, value):\n        self.par_setd(\"problem\", \"grav_mean_rho\", \"%.15e\", value, \"\")\n        return 0 \n\n    def set_isocsound(self, value):\n        self.par_setd(\"problem\", \"iso_csound\", \"%.15e\", value, \"\")\n        return 0 \n        \n    def set_gamma(self, value):\n        self.par_setd(\"problem\", \"gamma\", \"%.15e\", value, \"-\") \n        return 0 \n    \n    def set_courant_friedrichs_lewy_number(self, value):\n        self.par_setd(\"time\", \"cour_no\", \"%.15e\", value, \"-\")\n        return 0 \n        \n    def set_boundary(self, xbound1, xbound2, ybound1, ybound2, zbound1, zbound2):\n        map_from_string_to_flag = {\n            \"reflective\": 1, \n            \"outflow\":2, \n            \"periodic\":4,\n            \"interface\": 10,\n        }\n        \n        self.par_seti(\"domain1\", \"bc_ix1\", \"%d\", map_from_string_to_flag[xbound1], \"-\")\n        self.par_seti(\"domain1\", \"bc_ox1\", \"%d\", map_from_string_to_flag[xbound2], \"-\")\n        self.par_seti(\"domain1\", \"bc_ix2\", \"%d\", map_from_string_to_flag[ybound1], \"-\")\n        self.par_seti(\"domain1\", \"bc_ox2\", \"%d\", map_from_string_to_flag[ybound2], \"-\")\n        self.par_seti(\"domain1\", \"bc_ix3\", \"%d\", map_from_string_to_flag[zbound1], \"-\")\n        self.par_seti(\"domain1\", \"bc_ox3\", \"%d\", map_from_string_to_flag[zbound2], \"-\")\n        \n        return 0\n        \n    \n    def set_parallel_decomposition(self, nx, ny, nz):\n        if nx == 0 or ny == 0 or nz == 0:\n            self.par_seti(\"domain1\", \"AutoWithNProc\", \"%d\", self.channel.number_of_workers, \"-\")\n        else:\n            self.par_seti(\"domain1\", \"AutoWithNProc\", \"%d\", 0, \"-\")\n            self.par_seti(\"domain1\", \"NGrid_x1\", \"%d\", nx, \"-\")\n            self.par_seti(\"domain1\", \"NGrid_x2\", \"%d\", ny, \"-\")\n            self.par_seti(\"domain1\", \"NGrid_x3\", \"%d\", nz, \"-\")\n        return 0\n        \n    def set_auto_decomposition(self, value):\n        self.par_seti(\"parallel\", \"auto\", \"%d\", value, \"-\")\n        return 0\n        \n    @legacy_function    \n    def initialize_grid():\n        function = LegacyFunctionSpecification()  \n        function.result_type = 'i'\n        return function\n        \n    @legacy_function\n    def get_timestep():\n        function = LegacyFunctionSpecification() \n        function.addParameter('value', dtype='float64', direction=function.OUT) \n        function.result_type = 'i'\n        return function\n        \n    @legacy_function\n    def set_timestep():\n        function = LegacyFunctionSpecification() \n        function.addParameter('value', dtype='float64', direction=function.IN) \n        function.result_type = 'i'\n        return function\n        \n    \n    @legacy_function\n    def get_evolve_to_exact_time():\n        function = LegacyFunctionSpecification() \n        function.addParameter('value', dtype='bool', direction=function.OUT) \n        function.result_type = 'i'\n        return function\n        \n    @legacy_function\n    def set_evolve_to_exact_time():\n        function = LegacyFunctionSpecification() \n        function.addParameter('value', dtype='bool', direction=function.IN) \n        function.result_type = 'i'\n        return function\n        \n    @legacy_function\n    def set_has_external_gravitational_potential():\n        function = LegacyFunctionSpecification() \n        function.addParameter('value', dtype='int32', direction=function.IN) \n        function.result_type = 'i'\n        return function\n        \n    @legacy_function\n    def get_has_external_gravitational_potential():\n        function = LegacyFunctionSpecification() \n        function.addParameter('value', dtype='int32', direction=function.OUT) \n        function.result_type = 'i'\n        return function\n    \n    @legacy_function\n    def get_nghost():\n        function = LegacyFunctionSpecification() \n        function.addParameter('value', dtype='int32', direction=function.OUT) \n        function.result_type = 'i'\n        return function\n        \n    @legacy_function\n    def get_time():\n        function = LegacyFunctionSpecification() \n        function.addParameter('value', dtype='float64', direction=function.OUT) \n        function.result_type = 'i'\n        return function\n        \n    @legacy_function\n    def esys_roe_adb_hydro():\n        function = LegacyFunctionSpecification() \n        function.addParameter('index', dtype='int32', direction=function.OUT) \n        function.addParameter('u', dtype='float64', direction=function.OUT) \n        function.addParameter('v', dtype='float64', direction=function.OUT) \n        function.addParameter('w', dtype='float64', direction=function.OUT) \n        function.addParameter('h', dtype='float64', direction=function.OUT) \n        function.addParameter('ev', dtype='float64', direction=function.OUT) \n        for i in range(5):\n            function.addParameter('rem{0}'.format(i), dtype='float64', direction=function.OUT) \n        for i in range(5):\n            function.addParameter('lem{0}'.format(i), dtype='float64', direction=function.OUT) \n        function.result_type = 'i'\n        function.can_handle_array = True\n        return function\n        \n    @legacy_function\n    def fill_grid_linearwave_1d():\n        function = LegacyFunctionSpecification() \n        function.addParameter('wave_flag', dtype='int32', direction=function.IN) \n        function.addParameter('amplitude', dtype='float64', direction=function.IN) \n        function.addParameter('vflow', dtype='float64', direction=function.IN) \n        function.addParameter('wave_dir', dtype='int32', direction=function.IN) \n        function.result_type = 'i'\n        function.can_handle_array = True\n        return function\n        \n    def get_index_range_for_potential(self, index_of_grid = 1):\n        \"\"\"\n        Returns the min and max values of indices in each\n        direction for the potential field, this\n        range is 1 cell larger than the normal grid\n        in all directions\"\"\"\n        imin,imax,jmin,jmax,kmin,kmax = numpy.asarray(self.get_index_range_inclusive(index_of_grid = index_of_grid))\n        imin -= 1\n        imax += 1\n        if jmin != jmax:\n            jmin -= 1\n            jmax += 1\n        if kmin != kmax:\n            kmin -= 1\n            kmax += 1\n        return imin,imax, jmin, jmax, kmin, kmax        \n    \n    @legacy_function    \n    def set_potential():\n        function = LegacyFunctionSpecification()  \n        function.must_handle_array = True\n        for x in ['i','j','k']:\n            function.addParameter(x, dtype='i', direction=function.IN)\n        \n        #function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1)\n        \n        function.addParameter('potential', dtype='d', direction=function.IN)\n        function.addParameter('number_of_points', 'i', function.LENGTH)\n        function.result_type = 'i'\n        return function\n        \n    @legacy_function    \n    def get_potential():\n        function = LegacyFunctionSpecification()  \n        function.must_handle_array = True\n        for x in ['i','j','k']:\n            function.addParameter(x, dtype='i', direction=function.IN)\n        #function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1)\n        function.addParameter('potential', dtype='d', direction=function.OUT)\n        function.addParameter('number_of_points', 'i', function.LENGTH)\n        function.result_type = 'i'\n        return function\n        \n    @legacy_function    \n    def get_interpolated_gravitational_potential():\n        \"\"\"\n        Return the interpolated gravitational potential, can\n        only interpolate over one axis at the time and\n        only at half way points between the grid points.\n        **For debugging purposes only**\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.can_handle_array = True\n        for x in ['x','y','z']:\n            function.addParameter(x, dtype='d', direction=function.IN)\n        function.addParameter('potential', dtype='d', direction=function.OUT)\n        function.result_type = 'i'\n        return function\n\n    def get_isocsound(self):\n        return self.par_getd(\"problem\", \"iso_csound\"), 0\n\n    def get_gamma(self):\n        return self.par_getd(\"problem\", \"gamma\"), 0\n        \n    def get_four_pi_G(self):\n        return self.par_getd(\"problem\", \"four_pi_G\"), 0\n        \n    def get_courant_friedrichs_lewy_number(self):\n        return self.par_getd(\"time\", \"cour_no\"), 0\n        \n    def get_grav_mean_rho(self):\n        return self.par_getd(\"problem\", \"grav_mean_rho\"), 0\n        \n    @legacy_function\n    def get_grid_gravitational_potential():\n        function = LegacyFunctionSpecification()\n        function.must_handle_array = True\n        for x in ['i','j','k']:\n            function.addParameter(x, dtype='i', direction=function.IN)\n        function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1)\n        for x in ['phi']:\n            function.addParameter(x, dtype='d', direction=function.OUT)\n        function.addParameter('number_of_points', 'i', function.LENGTH)\n        function.result_type = 'i'\n        \n        return function\n    \n    \n    \n\n    @legacy_function\n    def get_grid_acceleration():\n        function = LegacyFunctionSpecification()\n        function.must_handle_array = True\n        for x in ['i','j','k']:\n            function.addParameter(x, dtype='i', direction=function.IN)\n        function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1)\n        for x in ['fx', 'fy', 'fz']:\n            function.addParameter(x, dtype='d', direction=function.OUT)\n        function.addParameter('number_of_points', 'i', function.LENGTH)\n        function.result_type = 'i'\n        \n        return function\n        \n    @legacy_function\n    def set_grid_acceleration():\n        function = LegacyFunctionSpecification()\n        function.must_handle_array = True\n        for x in ['i','j','k']:\n            function.addParameter(x, dtype='i', direction=function.IN)\n        for x in ['fx', 'fy', 'fz']:\n            function.addParameter(x, dtype='d', direction=function.IN)\n        function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1)\n        function.addParameter('number_of_points', 'i', function.LENGTH)\n        function.result_type = 'i'\n        \n        return function\n\n    @legacy_function\n    def get_grid_gravitational_acceleration():\n        function = LegacyFunctionSpecification()\n        function.must_handle_array = True\n        for x in ['i','j','k']:\n            function.addParameter(x, dtype='i', direction=function.IN)\n        function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1)\n        for x in ['fx', 'fy', 'fz']:\n            function.addParameter(x, dtype='d', direction=function.OUT)\n        function.addParameter('number_of_points', 'i', function.LENGTH)\n        function.result_type = 'i'\n        \n        return function\n        \n    @legacy_function\n    def get_gravity_at_point():\n        \"\"\"\n        Determine the gravitational force on a given point\n        \"\"\"\n        function = LegacyFunctionSpecification()\n        function.addParameter('eps', dtype='float64', direction=function.IN,\n            description = \"The smoothing parameter\")\n        function.addParameter('x', dtype='float64', direction=function.IN,\n            description = \"The position vector of the point\")\n        function.addParameter('y', dtype='float64', direction=function.IN,\n            description = \"The position vector of the point\")\n        function.addParameter('z', dtype='float64', direction=function.IN,\n            description = \"The position vector of the point\")\n        function.addParameter('forcex', dtype='float64', direction=function.OUT,\n            description = \"Force created by the particles in the code at the given position\")\n        function.addParameter('forcey', dtype='float64', direction=function.OUT,\n            description = \"Force created by the particles in the code at the given position\")\n        function.addParameter('forcez', dtype='float64', direction=function.OUT,\n            description = \"Force created by the particles in the code at the given position\")\n        function.result_type = 'int32'\n        function.can_handle_array = True\n        function.result_doc = \"\"\"\n         0 - OK\n            Force could be calculated\n        -1 - ERROR\n            No force calculation supported\n        \"\"\"\n        return function\n\n\n    @legacy_function\n    def get_potential_at_point():\n        \"\"\"\n        Determine the potential on a given point\n        \"\"\"\n        function = LegacyFunctionSpecification()\n        function.addParameter('eps', dtype='float64', direction=function.IN,\n         description = \"The smoothing factor, may be ignored by the code\")\n        function.addParameter('x', dtype='float64', direction=function.IN)\n        function.addParameter('y', dtype='float64', direction=function.IN)\n        function.addParameter('z', dtype='float64', direction=function.IN)\n        function.addParameter('phi', dtype='float64', direction=function.OUT)\n        function.can_handle_array = True\n        function.result_type = 'int32'\n        return function\n        \n\n    @legacy_function\n    def get_grid_scalar():\n        \"\"\"\n        Retreives advected scalar property\n        \"\"\"\n        function = LegacyFunctionSpecification()\n        function.must_handle_array = True\n        for x in ['i','j','k']:\n            function.addParameter(x, dtype='i', direction=function.IN)\n        function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1)\n        for x in ['scalar',]:\n            function.addParameter(x, dtype='d', direction=function.OUT)\n        function.addParameter('number_of_points', 'i', function.LENGTH)\n        function.result_type = 'i'\n        return function\n        \n    @legacy_function\n    def set_grid_scalar():\n        \"\"\"\n        Stores advected scalar property\n        \"\"\"\n        function = LegacyFunctionSpecification()\n        function.must_handle_array = True\n        for x in ['i','j','k']:\n            function.addParameter(x, dtype='i', direction=function.IN)\n        for x in ['scalar',]:\n            function.addParameter(x, dtype='d', direction=function.IN)\n        function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1)\n        function.addParameter('number_of_points', 'i', function.LENGTH)\n        function.result_type = 'i'\n        return function\n    \n    \n    \n    @legacy_function\n    def get_boundary_index_range_inclusive():\n        function = LegacyFunctionSpecification()\n        function.addParameter('index_of_boundary', dtype='i', direction=function.IN)\n        function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1)\n        function.addParameter('minx', dtype='i', direction=function.OUT)\n        function.addParameter('maxx', dtype='i', direction=function.OUT)\n        function.addParameter('miny', dtype='i', direction=function.OUT)\n        function.addParameter('maxy', dtype='i', direction=function.OUT)\n        function.addParameter('minz', dtype='i', direction=function.OUT)\n        function.addParameter('maxz', dtype='i', direction=function.OUT)\n        function.result_type = 'i'\n        return function\n\n    @legacy_function\n    def set_boundary_state():\n        function = LegacyFunctionSpecification()\n        function.must_handle_array = True\n        for x in ['i','j','k']:\n            function.addParameter(x, dtype='i', direction=function.IN)\n        for x in ['rho','rhovx','rhovy','rhovz','en']:\n            function.addParameter(x, dtype='d', direction=function.IN)\n        function.addParameter('index_of_boundary', dtype='i', direction=function.IN, default = 1)\n        function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1)\n        function.addParameter('number_of_points', 'i', function.LENGTH)\n        function.result_type = 'i'\n        return function\n        \n    @legacy_function\n    def get_boundary_state():\n        function = LegacyFunctionSpecification()\n        function.must_handle_array = True\n        for x in ['i','j','k']:\n            function.addParameter(x, dtype='i', direction=function.IN)\n        function.addParameter('index_of_boundary', dtype='i', direction=function.IN, default = 1)\n        function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1)\n        for x in ['rho','rhovx','rhovy','rhovz','en']:\n            function.addParameter(x, dtype='d', direction=function.OUT)\n        function.addParameter('number_of_points', 'i', function.LENGTH)\n        function.result_type = 'i'\n        return function\n    \n    \n    @legacy_function    \n    def get_boundary_position_of_index():\n        \"\"\"\n        Retrieves the x, y and z position of the center of\n        the cell with coordinates i, j, k in the grid specified\n        by the index_of_grid\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.must_handle_array = True\n        for x in ['i','j','k']:\n            function.addParameter(x, dtype='i', direction=function.IN)\n        function.addParameter('index_of_boundary', dtype='i', direction=function.IN, default = 1)\n        function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1)\n        for x in ['x','y','z']:\n            function.addParameter(x, dtype='d', direction=function.OUT)\n        function.addParameter('number_of_points', 'i', function.LENGTH)           \n        function.result_type = 'i'\n        return function\n        \n    @legacy_function    \n    def get_hydro_state_at_point():\n        function = LegacyFunctionSpecification()  \n        for x in ['x','y','z']:\n            function.addParameter(x, dtype='d', direction=function.IN)\n        for x in ['vx','vy','vz']:\n            function.addParameter(x, dtype='d', direction=function.IN, default = 0)\n        for x in ['rho','rhovx','rhovy','rhovz','rhoe']:\n            function.addParameter(x, dtype='d', direction=function.OUT)\n        function.addParameter('npoints', dtype='i', direction=function.LENGTH)\n        function.result_type = 'i' \n        function.must_handle_array = True\n        return function\n        \n    @legacy_function    \n    def get_hydro_state_for_cell():\n        function = LegacyFunctionSpecification()  \n        for x in ['x','y','z']:\n            function.addParameter(x, dtype='d', direction=function.IN)\n        for x in ['dx','dy','dz']:\n            function.addParameter(x, dtype='d', direction=function.IN)\n        for x in ['vx','vy','vz']:\n            function.addParameter(x, dtype='d', direction=function.IN, default = 0)\n        for x in ['rho','rhovx','rhovy','rhovz','rhoe']:\n            function.addParameter(x, dtype='d', direction=function.OUT)\n        function.addParameter('npoints', dtype='i', direction=function.LENGTH)\n        function.result_type = 'i' \n        function.must_handle_array = True\n        return function\n    \nclass Athena(CommonCode):\n\n    def __init__(self, unit_converter = None, **options):\n        self.unit_converter = unit_converter\n        \n        self.stopping_conditions = StoppingConditions(self)\n        CommonCode.__init__(self,  AthenaInterface(**options), **options)\n        \n    def define_converter(self, handler):\n        if self.unit_converter is None:\n            return\n        \n        handler.set_converter(self.unit_converter.as_converter_from_si_to_generic())\n\n    def define_properties(self, handler):\n        handler.add_property('get_time', public_name = \"model_time\")\n        \n    def define_methods(self, handler):\n        handler.add_method(\n            'evolve_model',\n            (time,),\n            (handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            'get_position_of_index',\n            (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX),\n            (length, length, length, handler.ERROR_CODE,)\n        )\n        \n        density = mass / (length**3)\n        momentum =  mass / (time * (length**2))\n        energy =  mass / ((time**2) * length)\n        potential_energy =  length ** 2 / time ** 2\n        magnetic_field = mass / current / time ** 2\n        \n        handler.add_method(\n            'set_grid_state',\n            (handler.INDEX, handler.INDEX, handler.INDEX,\n            density, momentum, momentum, momentum, energy,\n            handler.INDEX),\n            (handler.ERROR_CODE,)\n        )\n        \n        handler.add_method(\n            'set_grid_magnetic_field',\n            (handler.INDEX, handler.INDEX, handler.INDEX,\n             magnetic_field, magnetic_field, magnetic_field,\n            handler.INDEX),\n            (handler.ERROR_CODE,)\n        )\n\n        handler.add_method(\n            'get_grid_state',\n            (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX),\n            (density, momentum, momentum, momentum, energy,\n            handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            'set_grid_energy_density',\n            (handler.INDEX, handler.INDEX, handler.INDEX,\n            energy, handler.INDEX),\n            (handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            'get_grid_energy_density',\n            (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX),\n            ( energy,\n            handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            'set_grid_density',\n            (handler.INDEX, handler.INDEX, handler.INDEX,\n            density, handler.INDEX),\n            (handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            'get_grid_density',\n            (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX),\n            (density,\n            handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            'set_grid_scalar',\n            (handler.INDEX, handler.INDEX, handler.INDEX,\n            handler.NO_UNIT, handler.INDEX),\n            (handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            'get_grid_scalar',\n            (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX),\n            (handler.NO_UNIT,\n            handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            'set_grid_momentum_density',\n            (handler.INDEX, handler.INDEX, handler.INDEX,\n            momentum, momentum, momentum, handler.INDEX),\n            (handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            'get_grid_momentum_density',\n            (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX),\n            ( momentum, momentum, momentum, \n            handler.ERROR_CODE,)\n        )\n    \n        handler.add_method(\n            'get_grid_magnetic_field',\n            (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX),\n            ( magnetic_field, magnetic_field, magnetic_field,\n            handler.ERROR_CODE,)\n        )\n\n        handler.add_method(\n            'set_potential',\n            (handler.INDEX, handler.INDEX, handler.INDEX,\n            potential_energy),\n            (handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            'get_potential',\n            (handler.INDEX, handler.INDEX, handler.INDEX,),\n            (potential_energy,\n            handler.ERROR_CODE,)\n        )\n    \n        handler.add_method(\n            'get_grid_gravitational_potential',\n            (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX,),\n            (potential_energy,\n            handler.ERROR_CODE,)\n        )\n         \n        handler.add_method(\n            'get_interpolated_gravitational_potential',\n            (length, length, length),\n            (potential_energy,\n            handler.ERROR_CODE,)\n        )\n        \n        handler.add_method(\n            'get_grid_gravitational_acceleration',\n            (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX,),\n            (acceleration,acceleration,acceleration,\n            handler.ERROR_CODE,)\n        )\n        \n        handler.add_method(\n            'get_grid_acceleration',\n            (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX,),\n            (acceleration,acceleration,acceleration,\n            handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            'set_grid_acceleration',\n            (handler.INDEX, handler.INDEX, handler.INDEX,\n            acceleration,acceleration,acceleration, handler.INDEX),\n            (handler.ERROR_CODE,)\n        )\n        \n        handler.add_method(\n            'get_gravity_at_point',\n            (length, length, length, length),\n            (acceleration, acceleration, acceleration, handler.ERROR_CODE)\n        )\n\n        handler.add_method(\n            'get_potential_at_point',\n            (length, length, length, length),\n            (potential, handler.ERROR_CODE)\n        )\n    \n        handler.add_method(\n            \"get_isocsound\",\n            (),\n            (length / time, handler.ERROR_CODE,)\n        )\n    \n        handler.add_method(\n            \"set_isocsound\",\n            (length / time, ),\n            (handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            \"get_timestep\",\n            (),\n            (time, handler.ERROR_CODE,)\n        )\n    \n        handler.add_method(\n            \"set_timestep\",\n            (time, ),\n            (handler.ERROR_CODE,)\n        )\n    \n        handler.add_method(\n            \"get_gamma\",\n            (),\n            (handler.NO_UNIT, handler.ERROR_CODE,)\n        )\n    \n        handler.add_method(\n            \"set_gamma\",\n            (handler.NO_UNIT, ),\n            (handler.ERROR_CODE,)\n        )\n    \n        handler.add_method(\n            \"get_courant_friedrichs_lewy_number\",\n            (),\n            (handler.NO_UNIT, handler.ERROR_CODE,)\n        )\n    \n        handler.add_method(\n            \"set_courant_friedrichs_lewy_number\",\n            (handler.NO_UNIT, ),\n            (handler.ERROR_CODE,)\n        )\n    \n        handler.add_method(\n            'get_time',\n            (),\n            (time, handler.ERROR_CODE,)\n        )\n    \n        handler.add_method(\n            'set_four_pi_G',\n            ( length**3 / (mass * time**2)),\n            (handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            'get_four_pi_G',\n            (),\n            ( (length**3) / (mass * (time**2)), handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            'set_grav_mean_rho',\n            (  mass / length**3, ),\n            (handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            'get_grav_mean_rho',\n            (),\n            (mass / length**3, handler.ERROR_CODE,)\n        )\n    \n        handler.add_method(\n            'setup_mesh',\n            (handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, length, length, length,),\n            (handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            'set_boundary',\n            (handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT,),\n            (handler.ERROR_CODE,)\n        )\n        \n        handler.add_method(\n            'set_boundary_state',\n            (handler.INDEX, handler.INDEX, handler.INDEX,\n            density, momentum, momentum, momentum, energy,\n            handler.INDEX, handler.INDEX),\n            (handler.ERROR_CODE,)\n        )\n        \n        handler.add_method(\n            'get_boundary_state',\n            (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX),\n            (density, momentum, momentum, momentum, energy,\n            handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            'get_boundary_position_of_index',\n            (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX),\n            (length, length, length, handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            'get_boundary_index_range_inclusive',\n            (handler.INDEX, handler.INDEX),\n            (handler.NO_UNIT, handler.NO_UNIT,handler.NO_UNIT, handler.NO_UNIT,handler.NO_UNIT, handler.NO_UNIT, handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            'get_hydro_state_at_point',\n            (generic_unit_system.length, generic_unit_system.length, generic_unit_system.length,\n                generic_unit_system.speed, generic_unit_system.speed, generic_unit_system.speed),\n            (generic_unit_system.density, generic_unit_system.momentum_density, generic_unit_system.momentum_density, \n                generic_unit_system.momentum_density, generic_unit_system.energy_density, handler.ERROR_CODE)\n        )\n        handler.add_method(\n            'get_hydro_state_for_cell',\n            (generic_unit_system.length, generic_unit_system.length, generic_unit_system.length,\n                generic_unit_system.length, generic_unit_system.length, generic_unit_system.length,\n                generic_unit_system.speed, generic_unit_system.speed, generic_unit_system.speed),\n            (generic_unit_system.density, generic_unit_system.momentum_density, generic_unit_system.momentum_density, \n                generic_unit_system.momentum_density, generic_unit_system.energy_density, handler.ERROR_CODE)\n        )\n        \n        \n        \n        self.stopping_conditions.define_methods(handler)\n    \n    \n    def specify_grid(self, definition, index_of_grid = 1):\n        definition.set_grid_range('get_index_range_inclusive')\n        \n        definition.add_getter('get_position_of_index', names=('x','y','z'))\n        \n        definition.add_getter('get_grid_state', names=('rho', 'rhovx','rhovy','rhovz','energy'))\n        definition.add_setter('set_grid_state', names=('rho', 'rhovx','rhovy','rhovz','energy'))\n        \n        definition.add_getter('get_grid_density', names=('rho',))\n        definition.add_setter('set_grid_density', names=('rho',))\n        \n        if self.mode == self.MODE_SCALAR:\n            definition.add_getter('get_grid_scalar', names=('scalar',))\n            definition.add_setter('set_grid_scalar', names=('scalar',))\n            \n        definition.add_getter('get_grid_momentum_density', names=('rhovx','rhovy','rhovz'))\n        definition.add_setter('set_grid_momentum_density', names=('rhovx','rhovy','rhovz'))\n        definition.add_getter('get_grid_energy_density', names=('energy',))\n        definition.add_setter('set_grid_energy_density', names=('energy',))\n        \n        \n        definition.add_getter('get_grid_gravitational_potential', names=('gravitational_potential',))\n        definition.add_getter('get_grid_gravitational_acceleration', names=('gravitational_acceleration_x','gravitational_acceleration_y','gravitational_acceleration_z',))\n        \n        definition.add_getter('get_grid_acceleration', names=('ax','ay','az'))\n        definition.add_setter('set_grid_acceleration', names=('ax','ay','az'))\n        \n        definition.define_extra_keywords({'index_of_grid':index_of_grid})\n        \n\n    def specify_mangnetic_filed_grid(self, definition, index_of_grid = 1):\n        definition.set_grid_range('get_index_range_magnetic_field_inclusive')\n        \n        definition.add_getter('get_position_of_index', names=('x','y','z'))\n    \n        definition.add_getter('get_grid_magnetic_field', names=('B1i','B2i','B3i'))   \n        definition.add_setter('set_grid_magnetic_field', names=('B1i','B2i','B3i'))\n         \n        definition.define_extra_keywords({'index_of_grid':index_of_grid})\n        \n  \n    def specify_boundary_grid(self, definition, index_of_boundary, index_of_grid = 1):\n        definition.set_grid_range('get_boundary_index_range_inclusive')\n        \n        definition.add_getter('get_boundary_position_of_index', names=('x','y','z'))\n        \n        definition.add_getter('get_boundary_state', names=('rho', 'rhovx','rhovy','rhovz','energy'))\n        definition.add_setter('set_boundary_state', names=('rho', 'rhovx','rhovy','rhovz','energy'))\n       \n        definition.define_extra_keywords({'index_of_boundary': index_of_boundary, 'index_of_grid':index_of_grid})\n        \n    \n    \n    def sepecify_extended_grid(self, definition, index_of_grid = 1):\n        self.specify_grid(definition, index_of_grid = index_of_grid)\n        definition.set_grid_range('get_index_range_extended')\n        \n        \n    @property\n    def grid(self):\n        return self._create_new_grid(self.specify_grid, index_of_grid = 1)\n    \n    BOUNDARY_NAME_TO_INDEX = {\n        'xbound1': 1,\n        'xbound2': 2,\n        'ybound1': 3,\n        'ybound2': 4,\n        'zbound1': 5,\n        'zbound2': 6,\n    }\n    def get_boundary_grid(self, name):\n        if not name in self.BOUNDARY_NAME_TO_INDEX:\n            raise Exception(\"boundary name is not known {0}\".format(name))\n        index_of_boundary = self.BOUNDARY_NAME_TO_INDEX[name]\n        \n        return self._create_new_grid(self.specify_boundary_grid, index_of_boundary = index_of_boundary, index_of_grid = 1)\n    \n\n    def get_extended_grid(self, index_of_grid = 1):\n        return self._create_new_grid(self.sepecify_extended_grid, index_of_grid = index_of_grid)\n                \n    def get_index_range_extended(self, index_of_grid = 1):\n        i0,i1, j0,j1, k0,k1 = self.get_index_range_inclusive(index_of_grid = index_of_grid)\n        dj = 2 if j1 > j0 else 0\n        dk = 2 if k1 > k0 else 0\n        return i0-2, i1+2, j0-dj, j0+dj, k0-dk, k1+dk\n    \n    def itergrids(self):\n        n = self.get_number_of_grids()\n        \n        for x in range(1,n+1):\n            yield self._create_new_grid(self.specify_grid, index_of_grid = x)\n\n    def iter_magnetic_field_grids(self):\n        n = self.get_number_of_grids()\n        \n        for x in range(1,n+1):\n            yield self._create_new_grid(self.specify_mangnetic_filed_grid, index_of_grid = x)\n\n    \n    def iter_hydro_and_mhd_grids(self):\n        n = self.get_number_of_grids()\n        \n        for x in range(1,n+1):\n            yield (\n                self._create_new_grid(self.specify_grid, index_of_grid = x),\n                self._create_new_grid(self.specify_mangnetic_filed_grid, index_of_grid = x),\n            )\n\n    def define_particle_sets(self, handler):\n        handler.define_grid('potential_grid')\n        handler.set_grid_range('potential_grid', 'get_index_range_for_potential')\n        handler.add_getter('potential_grid', 'get_position_of_index', names=('x','y','z'))\n        handler.add_getter('potential_grid', 'get_potential', names=('potential',))\n        handler.add_setter('potential_grid', 'set_potential', names=('potential', ))\n        handler.define_extra_keywords('potential_grid', {'index_of_grid':1})\n        \n        \n    def define_parameters(self, handler):\n        handler.add_method_parameter(\n            \"get_isocsound\", \n            \"set_isocsound\",\n            \"isothermal_sound_speed\", \n            \"isothermal sound speed, only used for isothermal EOS\", \n            default_value = 0.0 | length / time,\n            must_set_before_get = True\n        )\n        \n        handler.add_method_parameter(\n            \"get_gamma\", \n            \"set_gamma\",\n            \"gamma\", \n            \"ratio of specific heats used in equation of state\", \n            default_value = 1.6666666666666667,\n            must_set_before_get = True\n        )\n        \n        handler.add_method_parameter(\n            \"get_four_pi_G\", \n            \"set_four_pi_G\",\n            \"four_pi_G\", \n            \"value of four times pi time G\", \n            default_value = 4 * numpy.pi * (1| (length**3) / (mass * (time**2))),\n            must_set_before_get = True\n        )\n        \n        handler.add_method_parameter(\n            \"get_grav_mean_rho\", \n            \"set_grav_mean_rho\",\n            \"gravity_mean_rho\", \n            \"define the mean density in the field for self gravity calulations\", \n            default_value = 0 | mass / length ** 3,\n            must_set_before_get = True\n        )\n        \n        \n        handler.add_method_parameter(\n            \"get_courant_friedrichs_lewy_number\", \n            \"set_courant_friedrichs_lewy_number\",\n            \"courant_number\", \n            \"CFL number\", \n            default_value = 0.3,\n            must_set_before_get = True\n        )\n        \n        \n        handler.add_method_parameter(\n            \"get_evolve_to_exact_time\", \n            \"set_evolve_to_exact_time\",\n            \"must_evolve_to_exact_time\", \n            \"End the evolve model at the exact specified time\", \n            default_value = True\n        )\n        \n        handler.add_caching_parameter(\n            \"setup_mesh\", \n            \"nmeshx\",\n            \"nx\", \n            \"number of cells in the x direction\", \n            10,\n        )\n        \n        \n        handler.add_caching_parameter(\n            \"setup_mesh\", \n            \"nmeshy\",\n            \"ny\", \n            \"number of cells in the y direction\", \n            10,\n        )\n        \n        \n        handler.add_caching_parameter(\n            \"setup_mesh\", \n            \"nmeshz\",\n            \"nz\", \n            \"number of cells in the z direction\", \n            10,\n        )\n        \n        handler.add_caching_parameter(\n            \"setup_mesh\", \n            \"xlength\",\n            \"length_x\", \n            \"length of model in the x direction\", \n            10 | length,\n        )\n        handler.add_caching_parameter(\n            \"setup_mesh\", \n            \"ylength\",\n            \"length_y\", \n            \"length of model in the x direction\", \n            10 | length,\n        )\n        handler.add_caching_parameter(\n            \"setup_mesh\", \n            \"zlength\",\n            \"length_z\", \n            \"length of model in the z direction\", \n            10 | length,\n        )\n        \n        handler.add_vector_parameter(\n            \"mesh_size\",\n            \"number of cells in the x, y and z directions\",\n            (\"nx\", \"ny\", \"nz\")\n        )\n        \n        handler.add_vector_parameter(\n            \"mesh_length\",\n            \"length of the model in the x, y and z directions\",\n            (\"length_x\", \"length_y\", \"length_z\")\n        )\n        \n        handler.add_caching_parameter(\n            \"set_parallel_decomposition\", \n            \"nx\",\n            \"nproc_x\", \n            \"number of processors for the x direction\",\n            0,\n        )\n        handler.add_caching_parameter(\n            \"set_parallel_decomposition\", \n            \"ny\",\n            \"nproc_y\", \n            \"number of processors for the y direction\",\n            0,\n        )\n        handler.add_caching_parameter(\n            \"set_parallel_decomposition\", \n            \"nz\",\n            \"nproc_z\", \n            \"number of processors for the z direction\",\n            0,\n        )\n        \n        handler.add_vector_parameter(\n            \"parallel_decomposition\",\n            \"number of processors for each dimensions\",\n            (\"nproc_x\", \"nproc_y\", \"nproc_z\")\n        )\n        \n        handler.add_caching_parameter(\n            \"set_boundary\", \n            \"xbound1\",\n            \"xbound1\", \n            \"boundary conditions on first (inner, left) X boundary\", \n            \"reflective\",\n        )\n        \n        \n        handler.add_caching_parameter(\n            \"set_boundary\", \n            \"xbound2\",\n            \"xbound2\", \n            \"boundary conditions on second (outer, right) X boundary\",\n            \"reflective\",\n        )\n        \n        handler.add_caching_parameter(\n            \"set_boundary\", \n            \"ybound1\",\n            \"ybound1\", \n            \"boundary conditions on first (inner, front) Y boundary\", \n            \"reflective\",\n        )\n        \n        \n        handler.add_caching_parameter(\n            \"set_boundary\", \n            \"ybound2\",\n            \"ybound2\", \n            \"boundary conditions on second (outer, back) Y boundary\",\n            \"reflective\",\n        )\n        \n        handler.add_caching_parameter(\n            \"set_boundary\", \n            \"zbound1\",\n            \"zbound1\", \n            \"boundary conditions on first (inner, bottom) Z boundary\", \n            \"reflective\",\n        )\n        \n        \n        handler.add_caching_parameter(\n            \"set_boundary\", \n            \"zbound2\",\n            \"zbound2\", \n            \"boundary conditions on second (outer, top) Z boundary\", \n            \"reflective\",\n        )\n        \n        \n        \n        handler.add_vector_parameter(\n            \"x_boundary_conditions\",\n            \"boundary conditions for the X directorion\",\n            (\"xbound1\", \"xbound2\")\n        )\n        \n        \n        handler.add_vector_parameter(\n            \"y_boundary_conditions\",\n            \"boundary conditions for the Y directorion\",\n            (\"ybound1\", \"ybound2\")\n        )\n        \n        \n        handler.add_vector_parameter(\n            \"z_boundary_conditions\",\n            \"boundary conditions for the Z directorion\",\n            (\"zbound1\", \"zbound2\")\n        )\n        \n        self.stopping_conditions.define_parameters(handler)\n\n    def commit_parameters(self):\n        self.parameters.send_not_set_parameters_to_code()\n        self.parameters.send_cached_parameters_to_code()\n        self.overridden().commit_parameters()\n    \n    def define_state(self, handler): \n        CommonCode.define_state(self, handler)       \n        #handler.add_transition('END', 'INITIALIZED', 'initialize_code', False)\n        \n        handler.add_transition('INITIALIZED','EDIT','commit_parameters')\n        handler.add_transition('RUN','CHANGE_PARAMETERS_RUN','before_set_parameter', False)\n        handler.add_transition('EDIT','CHANGE_PARAMETERS_EDIT','before_set_parameter', False)\n        handler.add_transition('CHANGE_PARAMETERS_RUN','RUN','recommit_parameters')\n        handler.add_transition('CHANGE_PARAMETERS_EDIT','EDIT','recommit_parameters')\n        \n        handler.add_method('CHANGE_PARAMETERS_RUN', 'before_set_parameter')\n        handler.add_method('CHANGE_PARAMETERS_EDIT', 'before_set_parameter')\n        \n        handler.add_method('CHANGE_PARAMETERS_RUN', 'before_get_parameter')\n        handler.add_method('CHANGE_PARAMETERS_EDIT', 'before_get_parameter')\n        handler.add_method('RUN', 'before_get_parameter')\n        handler.add_method('EDIT', 'before_get_parameter')\n        \n        handler.add_transition('EDIT', 'RUN', 'initialize_grid')\n        handler.add_method('RUN', 'evolve_model')\n        handler.add_method('RUN', 'get_hydro_state_at_point')\n        \n        for state in ['EDIT', 'RUN']:\n            for methodname in [\n                    'get_grid_state',\n                    'set_grid_state',\n                    'get_potential',\n                    'set_potential',\n                    'get_grid_density',\n                    'set_grid_density',\n                    'set_grid_energy_density',\n                    'get_grid_energy_density',\n                    'get_grid_momentum_density',\n                    'set_grid_momentum_density', \n                    'get_position_of_index',\n                    'get_index_of_position',\n                    'set_grid_scalar',\n                    'get_grid_scalar',\n                    'get_number_of_grids',\n                    'get_index_range_inclusive',\n                    'get_boundary_state',\n                    'set_boundary_state',\n                    'get_boundary_position_if_index',\n                    'get_boundary_index_range_inclusive'\n                ]:\n                handler.add_method(state, methodname)\n                \n        self.stopping_conditions.define_state(handler)\n\n", "meta": {"hexsha": "78b8a94c66b2b479da3c75c4661e7c02e045db6f", "size": 53462, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/amuse/community/athena/interface.py", "max_stars_repo_name": "aatrani/amuse", "max_stars_repo_head_hexsha": "fd1abcfb1b118a9ab13031912abf6e65e9c60dde", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-09T09:06:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-09T09:06:08.000Z", "max_issues_repo_path": "src/amuse/community/athena/interface.py", "max_issues_repo_name": "aatrani/amuse", "max_issues_repo_head_hexsha": "fd1abcfb1b118a9ab13031912abf6e65e9c60dde", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-01-27T17:01:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-28T02:09:55.000Z", "max_forks_repo_path": "src/amuse/community/athena/interface.py", "max_forks_repo_name": "aatrani/amuse", "max_forks_repo_head_hexsha": "fd1abcfb1b118a9ab13031912abf6e65e9c60dde", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8249818446, "max_line_length": 171, "alphanum_fraction": 0.5947027795, "include": true, "reason": "import numpy", "num_tokens": 11909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.19985352561001243}}
{"text": "# AI for Business - Minimize cost with Deep Q-Learning\n# Building the Environment\n\n# Importing the libraries\nimport numpy as np\n\n# BUILDING THE ENVIRONMENT IN A CLASS\n\nclass Environment(object):\n    \n    # INTRODUCING AND INITIALIZING ALL THE PARAMETERS AND VARIABLES OF THE ENVIRONMENT\n    \n    def __init__(self, optimal_temperature = (18.0, 24.0), initial_month = 0, initial_number_users = 10, initial_rate_data = 60):\n        self.monthly_atmospheric_temperatures = [1.0, 5.0, 7.0, 10.0, 11.0, 20.0, 23.0, 24.0, 22.0, 10.0, 5.0, 1.0]\n        self.initial_month = initial_month\n        self.atmospheric_temperature = self.monthly_atmospheric_temperatures[initial_month]\n        self.optimal_temperature = optimal_temperature\n        self.min_temperature = -20\n        self.max_temperature = 80\n        self.min_number_users = 10\n        self.max_number_users = 100\n        self.max_update_users = 5\n        self.min_rate_data = 20\n        self.max_rate_data = 300\n        self.max_update_data = 10\n        self.initial_number_users = initial_number_users\n        self.current_number_users = initial_number_users\n        self.initial_rate_data = initial_rate_data\n        self.current_rate_data = initial_rate_data\n        self.intrinsic_temperature = self.atmospheric_temperature + 1.25 * self.current_number_users + 1.25 * self.current_rate_data\n        self.temperature_ai = self.intrinsic_temperature\n        self.temperature_noai = (self.optimal_temperature[0] + self.optimal_temperature[1]) / 2.0\n        self.total_energy_ai = 0.0\n        self.total_energy_noai = 0.0\n        self.reward = 0.0\n        self.game_over = 0\n        self.train = 1\n\n    # MAKING A METHOD THAT UPDATES THE ENVIRONMENT RIGHT AFTER THE AI PLAYS AN ACTION\n    \n    def update_env(self, direction, energy_ai, month):\n        \n        # GETTING THE REWARD\n        \n        # Computing the energy spent by the server's cooling system when there is no AI\n        energy_noai = 0\n        if (self.temperature_noai < self.optimal_temperature[0]):\n            energy_noai = self.optimal_temperature[0] - self.temperature_noai\n            self.temperature_noai = self.optimal_temperature[0]\n        elif (self.temperature_noai > self.optimal_temperature[1]):\n            energy_noai = self.temperature_noai - self.optimal_temperature[1]\n            self.temperature_noai = self.optimal_temperature[1]\n        # Computing the Reward\n        self.reward = energy_noai - energy_ai\n        # Scaling the Reward\n        self.reward = 1e-3 * self.reward\n        \n        # GETTING THE NEXT STATE\n        \n        # Updating the atmospheric temperature\n        self.atmospheric_temperature = self.monthly_atmospheric_temperatures[month]\n        # Updating the number of users\n        self.current_number_users += np.random.randint(-self.max_update_users, self.max_update_users)\n        if (self.current_number_users > self.max_number_users):\n            self.current_number_users = self.max_number_users\n        elif (self.current_number_users < self.min_number_users):\n            self.current_number_users = self.min_number_users\n        # Updating the rate of data\n        self.current_rate_data += np.random.randint(-self.max_update_data, self.max_update_data)\n        if (self.current_rate_data > self.max_rate_data):\n            self.current_rate_data = self.max_rate_data\n        elif (self.current_rate_data < self.min_rate_data):\n            self.current_rate_data = self.min_rate_data\n        # Computing the Delta of Intrinsic Temperature\n        past_intrinsic_temperature = self.intrinsic_temperature\n        self.intrinsic_temperature = self.atmospheric_temperature + 1.25 * self.current_number_users + 1.25 * self.current_rate_data\n        delta_intrinsic_temperature = self.intrinsic_temperature - past_intrinsic_temperature\n        # Computing the Delta of Temperature caused by the AI\n        if (direction == -1):\n            delta_temperature_ai = -energy_ai\n        elif (direction == 1):\n            delta_temperature_ai = energy_ai\n        # Updating the new Server's Temperature when there is the AI\n        self.temperature_ai += delta_intrinsic_temperature + delta_temperature_ai\n        # Updating the new Server's Temperature when there is no AI\n        self.temperature_noai += delta_intrinsic_temperature\n        \n        # GETTING GAME OVER\n        \n        if (self.temperature_ai < self.min_temperature):\n            if (self.train == 1):\n                self.game_over = 1\n            else:\n                self.total_energy_ai += self.optimal_temperature[0] - self.temperature_ai\n                self.temperature_ai = self.optimal_temperature[0]\n        elif (self.temperature_ai > self.max_temperature):\n            if (self.train == 1):\n                self.game_over = 1\n            else:\n                self.total_energy_ai += self.temperature_ai - self.optimal_temperature[1]\n                self.temperature_ai = self.optimal_temperature[1]\n        \n        # UPDATING THE SCORES\n        \n        # Updating the Total Energy spent by the AI\n        self.total_energy_ai += energy_ai\n        # Updating the Total Energy spent by the server's cooling system when there is no AI\n        self.total_energy_noai += energy_noai\n        \n        # SCALING THE NEXT STATE\n        \n        scaled_temperature_ai = (self.temperature_ai - self.min_temperature) / (self.max_temperature - self.min_temperature)\n        scaled_number_users = (self.current_number_users - self.min_number_users) / (self.max_number_users - self.min_number_users)\n        scaled_rate_data = (self.current_rate_data - self.min_rate_data) / (self.max_rate_data - self.min_rate_data)\n        next_state = np.matrix([scaled_temperature_ai, scaled_number_users, scaled_rate_data])\n        \n        # RETURNING THE NEXT STATE, THE REWARD, AND GAME OVER\n        \n        return next_state, self.reward, self.game_over\n\n    # MAKING A METHOD THAT RESETS THE ENVIRONMENT\n    \n    def reset(self, new_month):\n        self.atmospheric_temperature = self.monthly_atmospheric_temperatures[new_month]\n        self.initial_month = new_month\n        self.current_number_users = self.initial_number_users\n        self.current_rate_data = self.initial_rate_data\n        self.intrinsic_temperature = self.atmospheric_temperature + 1.25 * self.current_number_users + 1.25 * self.current_rate_data\n        self.temperature_ai = self.intrinsic_temperature\n        self.temperature_noai = (self.optimal_temperature[0] + self.optimal_temperature[1]) / 2.0\n        self.total_energy_ai = 0.0\n        self.total_energy_noai = 0.0\n        self.reward = 0.0\n        self.game_over = 0\n        self.train = 1\n\n    # MAKING A METHOD THAT GIVES US AT ANY TIME THE CURRENT STATE, THE LAST REWARD AND WHETHER THE GAME IS OVER\n    \n    def observe(self):\n        scaled_temperature_ai = (self.temperature_ai - self.min_temperature) / (self.max_temperature - self.min_temperature)\n        scaled_number_users = (self.current_number_users - self.min_number_users) / (self.max_number_users - self.min_number_users)\n        scaled_rate_data = (self.current_rate_data - self.min_rate_data) / (self.max_rate_data - self.min_rate_data)\n        current_state = np.matrix([scaled_temperature_ai, scaled_number_users, scaled_rate_data])\n        return current_state, self.reward, self.game_over\n", "meta": {"hexsha": "40f68d8cde0909c1f1cb3b374203afdb19b44f78", "size": 7328, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter 11/environment.py", "max_stars_repo_name": "Bazzaware/AI-Crash-Course", "max_stars_repo_head_hexsha": "066e4bf62cf76c5ced7b08b249ac4f1379cb11dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 147, "max_stars_repo_stars_event_min_datetime": "2019-04-15T18:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T11:08:11.000Z", "max_issues_repo_path": "Chapter 11/environment.py", "max_issues_repo_name": "Bazzaware/AI-Crash-Course", "max_issues_repo_head_hexsha": "066e4bf62cf76c5ced7b08b249ac4f1379cb11dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter 11/environment.py", "max_forks_repo_name": "Bazzaware/AI-Crash-Course", "max_forks_repo_head_hexsha": "066e4bf62cf76c5ced7b08b249ac4f1379cb11dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 120, "max_forks_repo_forks_event_min_datetime": "2019-04-19T08:01:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T05:19:04.000Z", "avg_line_length": 50.5379310345, "max_line_length": 132, "alphanum_fraction": 0.6883187773, "include": true, "reason": "import numpy", "num_tokens": 1646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3629692124105862, "lm_q1q2_score": 0.19985352181579394}}
{"text": "# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport functools\nimport operator\n\nimport numpy as np\n\nfrom jaxlib import xla_client\n\ntry:\n  from jaxlib import cublas_kernels\n  for _name, _value in cublas_kernels.registrations().items():\n    xla_client.register_custom_call_target(_name, _value, platform=\"CUDA\")\nexcept ImportError:\n  pass\n\ntry:\n  from jaxlib import cusolver_kernels\n  for _name, _value in cusolver_kernels.registrations().items():\n    xla_client.register_custom_call_target(_name, _value, platform=\"CUDA\")\nexcept ImportError:\n  pass\n\n_ops = xla_client.ops\n_Shape = xla_client.Shape\n\n# TODO(phawkins): remove after we no longer need to support old jax releases.\ndef _unpack_builder(c):\n  # If `c` is a ComputationBuilder object, extracts the underlying XlaBuilder.\n  return getattr(c, \"_builder\", c)\n\ndef _real_type(dtype):\n  \"\"\"Returns the real equivalent of 'dtype'.\"\"\"\n  if dtype == np.float32:\n    return np.float32\n  elif dtype == np.float64:\n    return np.float64\n  elif dtype == np.complex64:\n    return np.float32\n  elif dtype == np.complex128:\n    return np.float64\n  else:\n    raise NotImplementedError(\"Unsupported dtype {}\".format(dtype))\n\n_prod = lambda xs: functools.reduce(operator.mul, xs, 1)\n\ndef trsm(c, a, b, left_side=False, lower=False, trans_a=False, conj_a=False,\n         diag=False):\n  \"\"\"Batched triangular solve.\n\n  XLA implements unbatched triangular solve directly, so we need only implement\n  the batched case.\"\"\"\n  c = _unpack_builder(c)\n  b_shape = c.get_shape(b)\n  dtype = b_shape.element_type()\n  dims = b_shape.dimensions()\n  assert len(dims) >= 2\n  m, n = dims[-2:]\n  batch_dims = tuple(dims[:-2])\n  num_bd = len(batch_dims)\n  batch = _prod(batch_dims)\n  k = m if left_side else n\n\n  a_shape = c.get_shape(a)\n  if (batch_dims + (k, k) != a_shape.dimensions() or\n      a_shape.element_type() != dtype):\n    raise ValueError(\"Argument mismatch for trsm, got {} and {}\".format(\n      a_shape, b_shape))\n\n  if conj_a and not trans_a:\n    raise NotImplementedError(\"Conjugation without transposition not supported\")\n\n  lwork, opaque = cublas_kernels.build_trsm_batched_descriptor(\n    np.dtype(dtype), batch, m, n, left_side, lower, trans_a, conj_a, diag)\n  layout = (num_bd, num_bd + 1) + tuple(range(num_bd - 1, -1, -1))\n  out = _ops.CustomCallWithLayout(\n      c, b\"cublas_trsm_batched\",\n      operands=(a, b),\n      shape_with_layout=_Shape.tuple_shape((\n          _Shape.array_shape(dtype, b_shape.dimensions(), layout),\n          _Shape.array_shape(np.dtype(np.int8), (lwork,), (0,)),\n          _Shape.array_shape(np.dtype(np.int8), (lwork,), (0,)))),\n      operand_shapes_with_layout=(\n          _Shape.array_shape(dtype, a_shape.dimensions(), layout),\n          _Shape.array_shape(dtype, b_shape.dimensions(), layout),\n      ),\n      opaque=opaque)\n  return _ops.GetTupleElement(out, 0)\n\n\ndef potrf(c, a, lower):\n  \"\"\"Cholesky decomposition.\"\"\"\n  c = _unpack_builder(c)\n  a_shape = c.get_shape(a)\n  dtype = a_shape.element_type()\n  dims = a_shape.dimensions()\n  m, n = dims[-2:]\n  assert m == n\n  batch_dims = tuple(dims[:-2])\n  num_bd = len(batch_dims)\n  batch = _prod(batch_dims)\n\n  lwork, opaque = cusolver_kernels.build_potrf_descriptor(\n      np.dtype(dtype), lower, batch, n)\n  kernel = b\"cusolver_potrf\"\n\n  out = _ops.CustomCallWithLayout(\n      c, kernel,\n      operands=(a,),\n      shape_with_layout=_Shape.tuple_shape((\n          _Shape.array_shape(\n              dtype, batch_dims + (n, n),\n              (num_bd, num_bd + 1) + tuple(range(num_bd - 1, -1, -1))),\n          _Shape.array_shape(\n              np.dtype(np.int32), batch_dims, tuple(range(num_bd - 1, -1, -1))),\n          _Shape.array_shape(np.dtype(np.int8), (lwork,), (0,)),\n      )),\n      operand_shapes_with_layout=(_Shape.array_shape(\n          dtype, batch_dims + (n, n),\n          (num_bd, num_bd + 1) + tuple(range(num_bd - 1, -1, -1))),),\n      opaque=opaque)\n  return _ops.GetTupleElement(out, 0), _ops.GetTupleElement(out, 1)\n\n\ndef getrf(c, a):\n  \"\"\"LU decomposition.\"\"\"\n  c = _unpack_builder(c)\n  a_shape = c.get_shape(a)\n  dtype = a_shape.element_type()\n  dims = a_shape.dimensions()\n  assert len(dims) >= 2\n  m, n = dims[-2:]\n  batch_dims = tuple(dims[:-2])\n  num_bd = len(batch_dims)\n  batch = _prod(batch_dims)\n\n  if batch > 1 and m == n and m // batch <= 128:\n    lwork, opaque = cublas_kernels.build_getrf_batched_descriptor(\n      np.dtype(dtype), batch, m)\n    workspace = _Shape.array_shape(np.dtype(np.int8), (lwork,), (0,))\n    kernel = b\"cublas_getrf_batched\"\n  else:\n    lwork, opaque = cusolver_kernels.build_getrf_descriptor(\n        np.dtype(dtype), batch, m, n)\n    workspace = _Shape.array_shape(dtype, (lwork,), (0,))\n    kernel = b\"cusolver_getrf\"\n\n  out = _ops.CustomCallWithLayout(\n      c, kernel,\n      operands=(a,),\n      shape_with_layout=_Shape.tuple_shape((\n          _Shape.array_shape(\n              dtype, batch_dims + (m, n),\n              (num_bd, num_bd + 1) + tuple(range(num_bd - 1, -1, -1))),\n          _Shape.array_shape(\n              np.dtype(np.int32), batch_dims + (min(m, n),),\n              tuple(range(num_bd, -1, -1))),\n          _Shape.array_shape(\n              np.dtype(np.int32), batch_dims, tuple(range(num_bd - 1, -1, -1))),\n          workspace,\n      )),\n      operand_shapes_with_layout=(_Shape.array_shape(\n          dtype, batch_dims + (m, n),\n          (num_bd, num_bd + 1) + tuple(range(num_bd - 1, -1, -1))),),\n      opaque=opaque)\n  return (_ops.GetTupleElement(out, 0), _ops.GetTupleElement(out, 1),\n          _ops.GetTupleElement(out, 2))\n\ndef geqrf(c, a):\n  \"\"\"QR decomposition.\"\"\"\n  c = _unpack_builder(c)\n  a_shape = c.get_shape(a)\n  dtype = a_shape.element_type()\n  dims = a_shape.dimensions()\n  assert len(dims) >= 2\n  m, n = dims[-2:]\n  batch_dims = tuple(dims[:-2])\n  num_bd = len(batch_dims)\n  batch = _prod(batch_dims)\n\n  lwork, opaque = cusolver_kernels.build_geqrf_descriptor(\n      np.dtype(dtype), batch, m, n)\n  workspace = _Shape.array_shape(dtype, (lwork,), (0,))\n  kernel = b\"cusolver_geqrf\"\n\n  out = _ops.CustomCallWithLayout(\n      c, kernel,\n      operands=(a,),\n      shape_with_layout=_Shape.tuple_shape((\n          _Shape.array_shape(\n              dtype, batch_dims + (m, n),\n              (num_bd, num_bd + 1) + tuple(range(num_bd - 1, -1, -1))),\n          _Shape.array_shape(\n              dtype, batch_dims + (min(m, n),),\n              tuple(range(num_bd, -1, -1))),\n          _Shape.array_shape(\n              np.dtype(np.int32), batch_dims, tuple(range(num_bd - 1, -1, -1))),\n          workspace,\n      )),\n      operand_shapes_with_layout=(_Shape.array_shape(\n          dtype, batch_dims + (m, n),\n          (num_bd, num_bd + 1) + tuple(range(num_bd - 1, -1, -1))),),\n      opaque=opaque)\n  return (_ops.GetTupleElement(out, 0), _ops.GetTupleElement(out, 1),\n          _ops.GetTupleElement(out, 2))\n\ndef orgqr(c, a, tau):\n  \"\"\"Product of elementary Householder reflections.\"\"\"\n  c = _unpack_builder(c)\n  a_shape = c.get_shape(a)\n  dtype = a_shape.element_type()\n  dims = a_shape.dimensions()\n  assert len(dims) >= 2\n  m, n = dims[-2:]\n  batch_dims = tuple(dims[:-2])\n  num_bd = len(batch_dims)\n  batch = _prod(batch_dims)\n\n  tau_dims = c.get_shape(tau).dimensions()\n  assert tau_dims[:-1] == dims[:-2]\n  k = tau_dims[-1]\n\n  lwork, opaque = cusolver_kernels.build_orgqr_descriptor(\n      np.dtype(dtype), batch, m, n, k)\n  workspace = _Shape.array_shape(dtype, (lwork,), (0,))\n  kernel = b\"cusolver_orgqr\"\n\n  out = _ops.CustomCallWithLayout(\n      c, kernel,\n      operands=(a, tau),\n      shape_with_layout=_Shape.tuple_shape((\n          _Shape.array_shape(\n              dtype, batch_dims + (m, n),\n              (num_bd, num_bd + 1) + tuple(range(num_bd - 1, -1, -1))),\n          _Shape.array_shape(\n              np.dtype(np.int32), batch_dims, tuple(range(num_bd - 1, -1, -1))),\n          workspace,\n      )),\n      operand_shapes_with_layout=(\n          _Shape.array_shape(\n              dtype, batch_dims + (m, n),\n              (num_bd, num_bd + 1) + tuple(range(num_bd - 1, -1, -1))),\n          _Shape.array_shape(\n              dtype, batch_dims + (k,),\n              tuple(range(num_bd, -1, -1))),\n          ),\n      opaque=opaque)\n  return (_ops.GetTupleElement(out, 0), _ops.GetTupleElement(out, 1))\n\n\ndef syevd(c, a, lower=False):\n  \"\"\"Symmetric (Hermitian) eigendecomposition.\"\"\"\n  c = _unpack_builder(c)\n\n  a_shape = c.get_shape(a)\n  dtype = a_shape.element_type()\n  dims = a_shape.dimensions()\n  assert len(dims) >= 2\n  m, n = dims[-2:]\n  assert m == n\n  batch_dims = tuple(dims[:-2])\n  num_bd = len(batch_dims)\n  batch = _prod(batch_dims)\n  layout = (num_bd, num_bd + 1) + tuple(range(num_bd - 1, -1, -1))\n\n  if n <= 32:\n    kernel = b\"cusolver_syevj\"\n    lwork, opaque = cusolver_kernels.build_syevj_descriptor(\n        np.dtype(dtype), lower, batch, n)\n  else:\n    kernel = b\"cusolver_syevd\"\n    lwork, opaque = cusolver_kernels.build_syevd_descriptor(\n        np.dtype(dtype), lower, batch, n)\n  eigvals_type = _real_type(dtype)\n\n  out = _ops.CustomCallWithLayout(\n      c, kernel,\n      operands=(a,),\n      shape_with_layout=_Shape.tuple_shape((\n          _Shape.array_shape(dtype, dims, layout),\n          _Shape.array_shape(\n              np.dtype(eigvals_type), batch_dims + (n,),\n              tuple(range(num_bd, -1, -1))),\n          _Shape.array_shape(\n              np.dtype(np.int32), batch_dims,\n              tuple(range(num_bd - 1, -1, -1))),\n          _Shape.array_shape(dtype, (lwork,), (0,))\n      )),\n      operand_shapes_with_layout=(\n          _Shape.array_shape(dtype, dims, layout),\n      ),\n      opaque=opaque)\n  return (_ops.GetTupleElement(out, 0), _ops.GetTupleElement(out, 1),\n          _ops.GetTupleElement(out, 2))\n\n\ndef gesvd(c, a, full_matrices=True, compute_uv=True):\n  \"\"\"Singular value decomposition.\"\"\"\n  c = _unpack_builder(c)\n\n  a_shape = c.get_shape(a)\n  dims = a_shape.dimensions()\n  dtype = a_shape.element_type()\n  assert len(dims) >= 2\n  m, n = dims[-2:]\n  batch_dims = tuple(dims[:-2])\n  num_bd = len(batch_dims)\n  b = _prod(batch_dims)\n  singular_vals_dtype = np.dtype(_real_type(dtype))\n\n  if m < 32 and n < 32:\n    lwork, opaque = cusolver_kernels.build_gesvdj_descriptor(\n        np.dtype(dtype), b, m, n, compute_uv)\n    scalar_layout = tuple(range(num_bd - 1, -1, -1))\n    vector_layout = (num_bd,) + scalar_layout\n    matrix_layout = (num_bd, num_bd + 1) + scalar_layout\n    out = _ops.CustomCallWithLayout(\n        c, b\"cusolver_gesvdj\",\n        operands=(a,),\n        shape_with_layout=_Shape.tuple_shape((\n            _Shape.array_shape(dtype, batch_dims + (m, n), matrix_layout),\n            _Shape.array_shape(singular_vals_dtype, batch_dims + (min(m, n),),\n                               vector_layout),\n            _Shape.array_shape(dtype, batch_dims + (m, m), matrix_layout),\n            _Shape.array_shape(dtype, batch_dims + (n, n), matrix_layout),\n            _Shape.array_shape(np.dtype(np.int32), batch_dims, scalar_layout),\n            _Shape.array_shape(dtype, (lwork,), (0,)),\n        )),\n        operand_shapes_with_layout=(\n            _Shape.array_shape(dtype, batch_dims + (m, n), matrix_layout),\n        ),\n        opaque=opaque)\n    s = _ops.GetTupleElement(out, 1)\n    u = _ops.GetTupleElement(out, 2)\n    v = _ops.GetTupleElement(out, 3)\n    info = _ops.GetTupleElement(out, 4)\n    vt = _ops.Transpose(v, tuple(range(num_bd)) + (num_bd + 1, num_bd))\n    if np.issubdtype(dtype, np.complexfloating):\n      vt = _ops.Conj(vt)\n  elif m < n:\n    lwork, opaque = cusolver_kernels.build_gesvd_descriptor(\n        np.dtype(dtype), b, n, m, compute_uv, full_matrices)\n    scalar_layout = tuple(range(num_bd - 1, -1, -1))\n    vector_layout = (num_bd,) + scalar_layout\n    matrix_layout = (num_bd + 1, num_bd) + scalar_layout\n    out = _ops.CustomCallWithLayout(\n        c, b\"cusolver_gesvd\",\n        operands=(a,),\n        shape_with_layout=_Shape.tuple_shape((\n            _Shape.array_shape(dtype, batch_dims + (m, n), matrix_layout),\n            _Shape.array_shape(singular_vals_dtype, batch_dims + (min(m, n),),\n                               vector_layout),\n            _Shape.array_shape(dtype, batch_dims + (n, n), matrix_layout),\n            _Shape.array_shape(dtype, batch_dims + (m, m), matrix_layout),\n            _Shape.array_shape(np.dtype(np.int32), batch_dims, scalar_layout),\n            _Shape.array_shape(dtype, (lwork,), (0,)),\n        )),\n        operand_shapes_with_layout=(\n            _Shape.array_shape(dtype, batch_dims + (m, n), matrix_layout),\n        ),\n        opaque=opaque)\n    s = _ops.GetTupleElement(out, 1)\n    vt = _ops.GetTupleElement(out, 2)\n    u = _ops.GetTupleElement(out, 3)\n    info = _ops.GetTupleElement(out, 4)\n  else:\n    lwork, opaque = cusolver_kernels.build_gesvd_descriptor(\n        np.dtype(dtype), b, m, n, compute_uv, full_matrices)\n\n    scalar_layout = tuple(range(num_bd - 1, -1, -1))\n    vector_layout = (num_bd,) + scalar_layout\n    matrix_layout = (num_bd, num_bd + 1) + scalar_layout\n    out = _ops.CustomCallWithLayout(\n        c, b\"cusolver_gesvd\",\n        operands=(a,),\n        shape_with_layout=_Shape.tuple_shape((\n            _Shape.array_shape(dtype, batch_dims + (m, n), matrix_layout),\n            _Shape.array_shape(singular_vals_dtype, batch_dims + (min(m, n),),\n                               vector_layout),\n            _Shape.array_shape(dtype, batch_dims + (m, m), matrix_layout),\n            _Shape.array_shape(dtype, batch_dims + (n, n), matrix_layout),\n            _Shape.array_shape(np.dtype(np.int32), batch_dims, scalar_layout),\n            _Shape.array_shape(dtype, (lwork,), (0,)),\n        )),\n        operand_shapes_with_layout=(\n            _Shape.array_shape(dtype, batch_dims + (m, n), matrix_layout),\n        ),\n        opaque=opaque)\n    s = _ops.GetTupleElement(out, 1)\n    u = _ops.GetTupleElement(out, 2)\n    vt = _ops.GetTupleElement(out, 3)\n    info = _ops.GetTupleElement(out, 4)\n  if not full_matrices:\n    u = _ops.Slice(u, (0,) * len(dims), batch_dims + (m, min(m, n)),\n                   (1,) * len(dims))\n    vt = _ops.Slice(vt, (0,) * len(dims), batch_dims + (min(m, n), n),\n                    (1,) * len(dims))\n  return s, u, vt, info\n", "meta": {"hexsha": "1c50ceb006840ee7e1781e49c78c0aa844f03dc9", "size": 14689, "ext": "py", "lang": "Python", "max_stars_repo_path": "jaxlib/cusolver.py", "max_stars_repo_name": "tataudat/jax", "max_stars_repo_head_hexsha": "62862267e416ec4e053cca91a1376f1ac2ad7b72", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-05T15:35:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-05T15:35:59.000Z", "max_issues_repo_path": "jaxlib/cusolver.py", "max_issues_repo_name": "tataudat/jax", "max_issues_repo_head_hexsha": "62862267e416ec4e053cca91a1376f1ac2ad7b72", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jaxlib/cusolver.py", "max_forks_repo_name": "tataudat/jax", "max_forks_repo_head_hexsha": "62862267e416ec4e053cca91a1376f1ac2ad7b72", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6529126214, "max_line_length": 80, "alphanum_fraction": 0.6276805773, "include": true, "reason": "import numpy,from jax", "num_tokens": 4024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.3629692193015555, "lm_q1q2_score": 0.19985352025675818}}
{"text": "\"\"\"\nModule containing a container which can hold an arbitrary number of\n`distpy.distribution.Distribution.Distribution` objects, each of which can have\nany number of parameters which it describes (as long as the specific\n`distpy.distribution.Distribution.Distribution` supports that number of\nparameters). `distpy.distribution.Distribution.Distribution` objects can be\nadded through `DistributionList.add_distribution`. Once all the distributions\nare added, points can be drawn using the `DistributionList.draw` method and the\nlog value of the entire set of distributions can be evaluated at a point using\nthe `DistributionList.log_value` method. See documentation of individual\nmethods for further details. This class represents a list-like container of\n`distpy.distribution.Distribution.Distribution` objects; see\n`distpy.distribution.DistributionSet.DistributionSet` for a dictionary- or set-\nlike container of `distpy.distribution.Distribution.Distribution` objects.\nUnlike the `distpy.distribution.DistributionSet.DistributionSet` class,\n`DistributionList` is a subclass of\n`distpy.distribution.Distribution.Distribution` and implements all of its\nmethods and properties.\n\n**File**: $DISTPY/distpy/distribution/DistributionList.py  \n**Author**: Keith Tauscher  \n**Date**: 31 May 2021\n\"\"\"\nimport numpy as np\nimport numpy.random as rand\nimport scipy.linalg as scila\nfrom ..util import int_types, numerical_types, sequence_types\nfrom ..transform import TransformList, NullTransform\nfrom .Distribution import Distribution\n\nclass DistributionList(Distribution):\n    \"\"\"\n    An object which keeps track of many distributions which can be univariate\n    or multivariate. It provides methods like log_value, which calls log_value\n    on all of its constituent distributions, and draw, which draws from all of\n    its constituent distributions.\n    \"\"\"\n    def __init__(self, distribution_tuples=[]):\n        \"\"\"\n        Creates a new `DistributionList` with the given distributions inside.\n        \n        Parameters\n        ----------\n        distribution_tuples : sequence\n            a list of lists/tuples of the form `(distribution,)` or\n            `(distribution, transforms)` where:\n            \n            - `distribution` is a\n            `distpy.distribution.Distribution.Distribution` object\n            - `transforms` is either a\n            `distpy.transform.TransformList.TransformList` or something that\n            can be cast to one (see the\n            `distpy.transform.TransformList.TransformList.cast` method). It\n            should describe the space in which the distribution applies. For\n            example, to draw a variable from a normal distribution in log10\n            space, `distribution` should be a\n            `distpy.distribution.GaussianDistribution.GaussianDistribution` and\n            `transforms` should be a\n            `distpy.transform.Log10Transform.Log10Transform`. The result will\n            contain only positive numbers.\n        \"\"\"\n        self._data = []\n        if type(distribution_tuples) in sequence_types:\n            for idistribution in range(len(distribution_tuples)):\n                this_tup = distribution_tuples[idistribution]\n                if (type(this_tup) in sequence_types):\n                    self.add_distribution(*this_tup)\n                else:\n                    raise ValueError(\"One of the distribution tuples \" +\\\n                        \"provided to the initializer of a DistributionList \" +\\\n                        \"was not a sequence of length 2 like \" +\\\n                        \"(distribution, transforms).\")\n        else:\n            raise ValueError(\"The distribution_tuples argument given to \" +\\\n                \"the initializer was not list-like. It should be a list of \" +\\\n                \"tuples of the form (distribution, transformations) \" +\\\n                \"where distribution is a Distribution object and \" +\\\n                \"transformations are lists of strings.\")\n\n    @property\n    def empty(self):\n        \"\"\"\n        Boolean describing whether this `DistributionList` is empty.\n        \"\"\"\n        return (len(self._data) == 0)\n\n    @property\n    def numparams(self):\n        \"\"\"\n        The total number of parameters described by in this `DistributionList`.\n        \"\"\"\n        return len(self.transform_list)\n    \n    @property\n    def mean(self):\n        \"\"\"\n        The approximate mean of this distribution. If the transform has a large\n        second derivative at the mean, then this approximation is poor.\n        \"\"\"\n        if not hasattr(self, '_mean'):\n            mean = []\n            for (distribution, transforms) in self._data:\n                if distribution.numparams == 1:\n                    mean.append(transforms[0].apply_inverse(distribution.mean))\n                else:\n                    this_mean = distribution.mean\n                    for (itransform, transform) in enumerate(transforms):\n                        mean.append(\\\n                            transform.apply_inverse(this_mean[itransform]))\n            self._mean = np.array(mean)\n        return self._mean\n    \n    @property\n    def variance(self):\n        \"\"\"\n        The covariance of this distribution.\n        \"\"\"\n        if not hasattr(self, '_variance'):\n            variances = []\n            for (distribution, transforms) in self._data:\n                if distribution.numparams == 1:\n                    this_mean = np.array([distribution.mean])\n                    this_covariance = np.array([[distribution.variance]])\n                    variances.append(transforms.inverse.transform_covariance(\\\n                        this_covariance, this_mean))\n                else:\n                    this_mean = distribution.mean\n                    this_covariance = distribution.variance\n                    variances.append(transforms.inverse.transform_covariance(\\\n                        this_covariance, this_mean))\n            self._variance = scila.block_diag(*variances)\n        return self._variance\n\n    def add_distribution(self, distribution, transforms=None):\n        \"\"\"\n        Adds a `distpy.distribution.Distribution.Distribution` and the\n        parameters it describes to the `DistributionList`.\n        \n        Parameters\n        ----------\n        distribution : `distpy.distribution.Distribution.Distribution`\n            the distribution to add\n        transforms : `distpy.transform.TransformList.TransformList` or\\\n        `distpy.transform.Transform.Transform` or sequence or str or None\n            a `distpy.transform.TransformList.TransformList` object (or\n            something castable to one, see\n            `distpy.transform.TransformList.TransformList.cast`) which apply to\n            the parameters (can be a single\n            `distpy.transform.Transform.Transform` or something castable to\n            one, see `distpy.transform.CastTransform.cast_to_transform`, if the\n            distribution is univariate). If `transforms` is None, then the\n            transforms are assumed to be\n            `distpy.transform.NullTransform.NullTransform`\n        \"\"\"\n        if isinstance(distribution, Distribution):\n            transforms = TransformList.cast(transforms,\\\n                num_transforms=distribution.numparams)\n            self._data.append((distribution, transforms))\n        else:\n            raise ValueError(\"The distribution given to a DistributionList \" +\\\n                \"was not recognized as a distribution.\")\n    \n    @property\n    def num_distributions(self):\n        \"\"\"\n        The number of distributions stored in this `DistributionList` object.\n        \"\"\"\n        return len(self._data)\n    \n    def __add__(self, other):\n        \"\"\"\n        Adds this `DistributionList` to another to create a combined set.\n        \n        Parameters\n        ----------\n        other : `DistributionList`\n            another `DistributionList` with parameters distinct from this one\n        \n        Returns\n        -------\n        sum : `DistributionList`\n            the combination of the two `DistributionList` objects being added\n        \"\"\"\n        if isinstance(other, DistributionList):\n            return DistributionList(distribution_tuples=self._data+other._data)\n        else:\n            raise TypeError(\"Can only add DistributionList objects to \" +\\\n                \"other DistributionList objects.\")\n    \n    def __iadd__(self, other):\n        \"\"\"\n        Adds all distributions from `other` to this `DistributionList`.\n        \n        Parameters\n        ----------\n        other : `DistributionList`\n            set of distributions to add into this one\n        \n        Returns\n        -------\n        enlarged : `DistributionList`\n            this `DistributionList` after the distributions from `other` have\n            been added in\n        \"\"\"\n        if isinstance(other, DistributionList):\n            for distribution_tuple in other._data:\n                self.add_distribution(*distribution_tuple)\n            return self\n        else:\n            raise TypeError(\"DistributionList objects can only have other \" +\\\n                \"DistributionList objects added to them.\")\n    \n    def modify_transforms(self, new_transform_list):\n        \"\"\"\n        Creates a `DistributionList` with the same distribution and parameters\n        but different transforms. Draws from this `DistributionList` and the\n        returned `DistributionList` will differ by the given transforms.\n        \n        Parameters\n        ----------\n        new_transform_list : `distpy.transform.TransformList.TransformList` or\\\n        `distpy.transform.Transform.Transform` or str or None\n            a `distpy.transform.TransformList.TransformList` containing the new\n            transforms (or something that can be cast to one with a number of\n            transforms equal to the `DistributionList.numparams`; see\n            `distpy.transform.TransformList.TransformList.cast` for details on\n            what can be cast successfully)\n        \n        Returns\n        -------\n        modified : `DistributionList`\n            new `DistributionList` object with the same distribution and\n            parameters but different transforms\n        \"\"\"\n        new_transform_list =\\\n            TransformList.cast(transforms, num_transforms=self.numparams)\n        (new_data, running_index) = ([], 0)\n        for (distribution, transforms) in self._data:\n            new_running_index = running_index + distribution.numparams\n            new_transforms =\\\n                new_transform_list[running_index:new_running_index]\n            running_index = new_running_index\n            new_data.append((distribution, new_transforms))\n        return DistributionList(distribution_tuples=new_data)\n    \n    def draw(self, shape=None, random=rand):\n        \"\"\"\n        Draws a point from all distributions.\n        \n        Parameters\n        ----------\n        shape : int or tuple or None\n            shape of arrays which are values of return value\n        random : `numpy.random.RandomState`\n            the random number generator to use (default: numpy.random)\n        \n        Returns\n        -------\n        drawn_points : `numpy.ndarray`\n            random variates drawn from the distribution (in the following `p`\n            is `DistributionList.numparams`):\n            - if `shape` is None, then `drawn_points` is a 1D `numpy.ndarray`\n            of length `p`\n            - if `shape` is an integer, then `drawn_points` is a 2D\n            `numpy.ndarray` of shape `(shape,p)`\n            - if `shape` is a tuple, then drawn points is a `numpy.ndarray` of\n            shape `shape + (p,)`\n        \"\"\"\n        none_shape = (type(shape) is type(None))\n        if none_shape:\n            shape = 1\n        if type(shape) in int_types:\n            shape = (shape,)\n        point = np.ndarray(shape+(self.numparams,))\n        params_included = 0\n        for (distribution, transforms) in self._data:\n            numparams = distribution.numparams\n            if numparams == 1:\n                transform = transforms[0]\n                point[...,params_included] = transforms[0].apply_inverse(\\\n                    distribution.draw(shape=shape, random=random))\n            else:\n                this_draw = distribution.draw(shape=shape, random=random)\n                for (itransform, transform) in enumerate(transforms):\n                    point[...,params_included+itransform] =\\\n                        transform.apply_inverse(this_draw[...,itransform])\n            params_included += numparams\n        if self.numparams == 1:\n            point = point[...,0]\n        if none_shape:\n            return point[0]\n        else:\n            return point\n    \n    def log_value(self, point):\n        \"\"\"\n        Evaluates the log of the product of the values of the\n        `distpy.distribution.Distribution.Distribution` objects contained in\n        this `DistributionList`, which is the sum of their log values.\n        \n        Parameters\n        ----------\n        point : `numpy.ndarray`\n            array of parameter values\n        \n        Returns\n        -------\n        total_log_value : float\n            total log_value coming from contributions from all distributions\n        \"\"\"\n        if type(point) in numerical_types:\n            point = [point]\n        if type(point) in sequence_types:\n            point = np.array(point)\n            if point.shape == (self.numparams,):\n                result = 0.\n                params_included = 0\n                for (distribution, transforms) in self._data:\n                    numparams = distribution.numparams\n                    if numparams == 1:\n                        subpoint = transforms[0].apply(point[params_included])\n                    else:\n                        subpoint = [\\\n                            transform.apply(point[params_included+itransform])\\\n                            for (itransform, transform) in\\\n                            enumerate(transforms)]\n                    result += distribution.log_value(subpoint)\n                    for (itransform, transform) in enumerate(transforms):\n                        result += transform.log_derivative(\\\n                            point[params_included+itransform])\n                    params_included += numparams\n                    if not np.isfinite(result):\n                        return -np.inf\n                return result\n            else:\n                raise ValueError(\"point given to log_value function of a \" +\\\n                    \"DistributionList did not have the correct length.\")\n        else:\n            raise ValueError(\"point given to log_value function of a \" +\\\n                \"DistributionList was not an array.\")\n    \n    def __getitem__(self, which):\n        \"\"\"\n        Gets a `DistributionList` with only the specified distributions.\n        \n        Parameters\n        ----------\n        which : int or slice or sequence\n            the index or indices of the distributions to include in the\n            returned value\n        \n        Returns\n        -------\n        sublist : `DistributionList`\n            a `DistributionList` object with only the specified distribution(s)\n        \"\"\"\n        if type(which) in int_types:\n            distribution_list =\\\n                DistributionList(distribution_tuples=[self._data[which]])\n        elif isinstance(which, slice):\n            distribution_list =\\\n                DistributionList(distribution_tuples=self._data[which])\n        elif type(which) in sequence_types:\n            distribution_list = DistributionList()\n            for which_element in which:\n                distribution_list.add_distribution(*self._data[which_element])\n        else:\n            raise ValueError(\"Only integers, sequences of integers, and \" +\\\n                \"slices are allowed as arguments to __getitem__.\")\n        return distribution_list\n    \n    def delete_distribution(self, index):\n        \"\"\"\n        Deletes a distribution from this `DistributionList`.\n        \n        Parameters\n        ----------\n        index : int\n            the index of the distribution to delete\n        \"\"\"\n        self._data = self._data[:index] + self._data[index+1:]\n    \n    def __delitem__(self, which):\n        \"\"\"\n        Deletes a distribution from this `DistributionList`. Alias of\n        `DistributionList.delete_distribution` that allows for usage of the\n        `del` keyword.\n        \n        Parameters\n        ----------\n        index : int\n            the index of the distribution to delete\n        \"\"\"\n        if type(which) in int_types:\n            self.delete_distribution(which)\n        elif isinstance(which, slice) or (type(which) in sequence_types):\n            if isinstance(which, slice):\n                which = list(range(*which.indices(self.num_distributions)))\n            which = sorted(which)[-1::-1]\n            for index in which:\n                self.delete_distribution(index)\n        else:\n            raise ValueError(\"Only integers, sequences of integers, and \" +\\\n                \"slices are allowed as arguments to __delitem__.\")\n    \n    @property\n    def summary_string(self):\n        \"\"\"\n        A string with the dimenstionality of the distribution.\n        \"\"\"\n        return '{:d}D DistributionList'.format(self.numparams)\n    \n    @property\n    def minimum(self):\n        \"\"\"\n        The minimum allowable value(s) in this distribution.\n        \"\"\"\n        if not hasattr(self, '_minimum'):\n            self._minimum = []\n            for (distribution, transforms) in self._data:\n                if distribution.numparams == 1:\n                    self._minimum.append(transforms[0].untransform_minimum(\\\n                        distribution.minimum))\n                else:\n                    self._minimum.extend([transform.untransform_minimum(\\\n                        minimum) for (minimum, transform) in\\\n                        zip(distribution.minimum, transforms)])\n        return self._minimum\n    \n    @property\n    def maximum(self):\n        \"\"\"\n        The maximum allowable value(s) in this distribution.\n        \"\"\"\n        if not hasattr(self, '_maximum'):\n            self._maximum = []\n            for (distribution, transforms) in self._data:\n                if distribution.numparams == 1:\n                    self._maximum.append(transforms[0].untransform_maximum(\\\n                        distribution.maximum))\n                else:\n                    self._maximum.extend([transform.untransform_maximum(\\\n                        maximum) for (maximum, transform) in\\\n                        zip(distribution.maximum, transforms)])\n        return self._maximum\n    \n    @property\n    def is_discrete(self):\n        \"\"\"\n        Boolean describing whether all of the distributions in this list are\n        discrete.\n        \"\"\"\n        return all([distribution.is_discrete\\\n            for (distribution, transforms) in self._data])\n    \n    @staticmethod\n    def _distribution_tuples_equal(first, second):\n        \"\"\"\n        Checks whether two distribution tuples are equal.\n        \n        Parameters\n        ----------\n        first : tuple\n            tuple of form `(distribution, parameters)` as internally\n            represented in a `DistributionList`\n        second : tuple\n            tuple of form `(distribution, transforms)` as internally\n            represented in a `DistributionList`\n        \n        Returns\n        -------\n        result : bool\n            True if and only if the distribution and transformations stored in\n            `first` are the same as those stored in `second`.\n        \"\"\"\n        (first_distribution, first_transforms) = first\n        (second_distribution, second_transforms) = second\n        numparams = first_distribution.numparams\n        if second_distribution.numparams == numparams:\n            for (first_transform, second_transform) in\\\n                zip(first_transforms, second_transforms):\n                if first_transform != second_transform:\n                    return False\n            return (first_distribution == second_distribution)\n        else:\n            return False\n    \n    def __eq__(self, other):\n        \"\"\"\n        Checks for equality of this `DistributionList` with `other`.\n        \n        Parameters\n        ----------\n        other : object\n            object to check for equality\n        \n        Returns\n        -------\n        result : bool\n            True if and only if `other` is a `DistributionList` with the same\n            distribution tuples (though they need not be internally stored in\n            the same order).\n        \"\"\"\n        if isinstance(other, DistributionList):\n            if len(self._data) == len(other._data):\n                return all([DistributionList._distribution_tuples_equal(\\\n                    *tuples) for tuples in zip(self._data, other._data)])\n            else:\n                return False\n        else:\n            return False\n    \n    @property\n    def transform_list(self):\n        \"\"\"\n        The `distpy.transform.TransformList.TransformList` object describing\n        the transforms in this `DistributionList`.\n        \"\"\"\n        answer = TransformList()\n        for (distribution, transforms) in self._data:\n            answer += transforms\n        return answer\n    \n    def discrete_sublist(self):\n        \"\"\"\n        Compiles the subset of the `Distribution` objects in this\n        `DistributionList` that represent discrete variables.\n        \n        Returns\n        -------\n        subset : `DistributionList`\n            a `DistributionList` object containing all\n            `distpy.distribution.Distribution.Distribution` objects in this\n            `DistributionList` which describe discrete variables\n        \"\"\"\n        answer = DistributionList()\n        for (distribution, transforms) in self._data:\n            if distribution.is_discrete:\n                answer.add_distribution(distribution, transforms)\n        return answer\n    \n    def continuous_sublist(self):\n        \"\"\"\n        Compiles the subset of the `Distribution` objects in this\n        `DistributionList` that represent continuous variables.\n        \n        Returns\n        -------\n        subset : `DistributionList`\n            a `DistributionList` object containing all\n            `distpy.distribution.Distribution.Distribution` objects in this\n            `DistributionList` which describe continuous variables\n        \"\"\"\n        answer = DistributionList()\n        for (distribution, transforms) in self._data:\n            if not distribution.is_discrete:\n                answer.add_distribution(distribution, transforms)\n        return answer\n    \n    def transformed_version(self):\n        \"\"\"\n        Compiles a version of this `DistributionList` where the parameters\n        exist in transformed space (instead of transforms being carried through\n        this object).\n        \n        Returns\n        -------\n        transformless : `DistributionList`\n            a `DistributionList` with the same distributions and parameter\n            names but without transforms\n        \"\"\"\n        answer = DistributionList()\n        for (distribution, transforms) in self._data:\n            answer.add_distribution(distribution)\n        return answer\n    \n    def fill_hdf5_group(self, group, save_metadata=True):\n        \"\"\"\n        Fills the given hdf5 file group with data about this\n        `DistributionList`.\n        \n        Parameters\n        ----------\n        group : h5py.Group\n            the hdf5 file group to fill\n        save_metadata : bool\n            - if True, attempts to save metadata alongside distribution list\n            and throws error if it fails\n            - if False, metadata is ignored in saving process\n        \"\"\"\n        group.attrs['class'] = 'DistributionList'\n        for (ituple, distribution_tuple) in enumerate(self._data):\n            (distribution, transforms) = distribution_tuple\n            subgroup = group.create_group('distribution_{}'.format(ituple))\n            distribution.fill_hdf5_group(subgroup, save_metadata=save_metadata)\n            transforms.fill_hdf5_group(subgroup)\n    \n    @staticmethod\n    def load_from_hdf5_group(group, *distribution_classes):\n        \"\"\"\n        Loads a `DistributionList` object from the given group.\n        \n        Parameters\n        ----------\n        group : h5py.Group\n            the hdf5 file group in which a `DistributionList` was saved\n        distribution_classes : sequence\n            sequence of Distribution subclasses with which to load\n            subdistributions (if the sub-distributions are defined in `distpy`,\n            then these are not necessary because all distributions save their\n            class as an attribute when they run\n            `distpy.distribution.Distribution.Distribution.fill_hdf5_group`)\n        \n        Returns\n        -------\n        loaded : `DistributionList`\n            a `DistributionList` that was saved in `group`\n        \"\"\"\n        ituple = 0\n        distribution_tuples = []\n        while ('distribution_{}'.format(ituple)) in group:\n            subgroup = group['distribution_{}'.format(ituple)]\n            distribution_class_name = subgroup.attrs['class']\n            if ituple >= len(distribution_classes):\n                module = __import__('distpy')\n                distribution_class = getattr(module, distribution_class_name)\n            else:\n                distribution_class =  distribution_classes[ituple]\n            distribution = distribution_class.load_from_hdf5_group(subgroup)\n            transform_list = TransformList.load_from_hdf5_group(subgroup)\n            distribution_tuples.append((distribution, transform_list))\n            ituple += 1\n        return DistributionList(distribution_tuples=distribution_tuples)\n    \n    @property\n    def gradient_computable(self):\n        \"\"\"\n        Boolean describing whether the gradient of the distributions inside\n        this `DistributionList` have been implemented.\n        \"\"\"\n        answer = True\n        for (distribution, transforms) in self._data:\n            answer = (answer and distribution.gradient_computable)\n        return answer\n    \n    def gradient_of_log_value(self, point):\n        \"\"\"\n        Computes the derivatives of the log value with respect to the\n        parameters.\n        \n        Parameters\n        ----------\n        point : `numpy.ndarray`\n            array of parameter values\n        \n        Returns\n        -------\n        gradient : `numpy.ndarray`\n            1D array of length `DistributionSet.numparams` of derivative values\n            corresponding to the parameters\n        \"\"\"\n        if type(point) in sequence_types:\n            point = np.array(point)\n            result = np.zeros((self.numparams,))\n            params_included = 0\n            for (idistribution, distribution_tuple) in enumerate(self._data):\n                (distribution, transforms) = distribution_tuple\n                numparams = distribution.numparams\n                if numparams == 1:\n                    result[params_included] +=\\\n                        distribution.gradient_of_log_value(\\\n                        transforms[0].apply(point[params_included]))\n                else:\n                    subpoint = np.array([\\\n                        transform.apply(point[params_included+itransform])\\\n                        for (itransform, transform) in enumerate(transforms)])\n                    result[params_included:params_included+numparams] +=\\\n                        distribution.gradient_of_log_value(subpoint)\n                for index in range(numparams):\n                    result[params_included+index] +=\\\n                        transforms[index].derivative_of_log_derivative(\\\n                        point[params_included+index])\n                params_included += numparams\n            return result\n        else:\n            raise ValueError(\"point given to gradient_of_log_value \" +\\\n                \"function of a DistributionList was not a sequence of values.\")\n    \n    @property\n    def hessian_computable(self):\n        \"\"\"\n        Boolean describing whether the hessian of the distributions inside this\n        `DistributionList` have been implemented.\n        \"\"\"\n        answer = True\n        for (distribution, transforms) in self._data:\n            answer = (answer and distribution.hessian_computable)\n        return answer\n    \n    def hessian_of_log_value(self, point):\n        \"\"\"\n        Computes the second derivatives of the log value with respect to the\n        parameters.\n        \n        Parameters\n        ----------\n        point : `numpy.ndarray`\n            array of parameter values\n        \n        Returns\n        -------\n        gradient : `numpy.ndarray`\n            1D array of length `DistributionSet.numparams` of second derivative\n            values corresponding to the parameters\n        \"\"\"\n        if type(point) in sequence_types:\n            point = np.array(point)\n            result = np.zeros((self.numparams,) * 2)\n            params_included = 0\n            for (idistribution, distribution_tuple) in enumerate(self._data):\n                (distribution, transforms) = distribution_tuple\n                numparams = distribution.numparams\n                if numparams == 1:\n                    subpoint = transforms[0].apply(point[params_included])\n                    result[params_included,params_included] +=\\\n                        distribution.hessian_of_log_value(subpoint)\n                else:\n                    subpoint = np.array([\\\n                        transform.apply(point[params_included+itransform])\\\n                        for (itransform, transform) in enumerate(transforms)])\n                    result_slice = 2 *\\\n                        (slice(params_included, params_included + numparams),)\n                    result[result_slice] +=\\\n                        distribution.hessian_of_log_value(subpoint)\n                for i in range(numparams):\n                    result[params_included+index,params_included+index] +=\\\n                        transforms[index].second_derivative_of_log_derivative(\\\n                        point[params_included+index])\n                params_included += numparams\n            return result\n        else:\n            raise ValueError(\"point given to hessian_of_log_value \" +\\\n                \"function of a DistributionList was not a sequence of values.\")\n    \n    def copy(self):\n        \"\"\"\n        Finds a deep copy of this `DistributionList`.\n        \n        Returns\n        -------\n        copied : `DistributionList`\n            deep copy of this `DistributionList`\n        \"\"\"\n        copied = DistributionList()\n        for (distribution, transforms) in self._data:\n            copied_distribution = distribution.copy()\n            copied_transforms = [transform for transform in transforms]\n            copied.add_distribution(copied_distribution, copied_transforms)\n        return copied\n    \n    def reset(self):\n        \"\"\"\n        Resets this distribution. This allows ideal distributions to live\n        alongside samples as the same kind of object.\n        \"\"\"\n        for (distribution, transforms) in self._data:\n            distribution.reset()\n\n", "meta": {"hexsha": "b271adbd0a5158b6748a83c9ed41e43bd17971c1", "size": 31309, "ext": "py", "lang": "Python", "max_stars_repo_path": "distpy/distribution/DistributionList.py", "max_stars_repo_name": "CU-NESS/distpy", "max_stars_repo_head_hexsha": "279ba7e46726a85246566401fca19b8739d18d08", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "distpy/distribution/DistributionList.py", "max_issues_repo_name": "CU-NESS/distpy", "max_issues_repo_head_hexsha": "279ba7e46726a85246566401fca19b8739d18d08", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "distpy/distribution/DistributionList.py", "max_forks_repo_name": "CU-NESS/distpy", "max_forks_repo_head_hexsha": "279ba7e46726a85246566401fca19b8739d18d08", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.7139141743, "max_line_length": 79, "alphanum_fraction": 0.5907885911, "include": true, "reason": "import numpy,import scipy", "num_tokens": 5840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.19985351802157544}}
{"text": "#   Copyright 2020 Google LLC\n\n#   Licensed under the Apache License, Version 2.0 (the \"License\");\n#   you may not use this file except in compliance with the License.\n#   You may obtain a copy of the License at\n#\n#       http://www.apache.org/licenses/LICENSE-2.0\n#\n#   Unless required by applicable law or agreed to in writing, software\n#   distributed under the License is distributed on an \"AS IS\" BASIS,\n#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#   See the License for the specific language governing permissions and\n#   limitations under the License.\n\"\"\"Wavefunction class for accessing and manipulation of the state of interest\n\"\"\"\n#zeros_like is incorrectly flagged by pylint\n#pylint: disable=unsupported-assignment-operation\n#there are many instances where access to protected members/methods simplify the\n#code structure. They are not exposed to the users, and therefore, harmless\n#pylint: disable=protected-access\n\nimport copy\nimport os\nimport math\nfrom typing import (Any, Callable, cast, Dict, KeysView, List, Optional, Tuple,\n                    Union)\n\nimport pickle\nimport numpy\nfrom scipy import linalg\nfrom scipy.special import factorial, jv\n\nfrom fqe.fqe_decorators import wrap_apply, wrap_apply_generated_unitary\nfrom fqe.fqe_decorators import wrap_time_evolve, wrap_rdm\nfrom fqe.fqe_data import FqeData\nfrom fqe.fqe_data_set import FqeDataSet\nfrom fqe.util import alpha_beta_electrons\nfrom fqe.util import map_broken_symmetry\nfrom fqe.util import sort_configuration_keys\nfrom fqe.util import vdot\nfrom fqe.hamiltonians import hamiltonian, sparse_hamiltonian, \\\n                             diagonal_hamiltonian, diagonal_coulomb, \\\n                             restricted_hamiltonian\nfrom fqe.bitstring import count_bits\nfrom fqe.fqe_ops import fqe_operator, fqe_ops_utils\nfrom fqe.wick import wick\n\n\nclass Wavefunction:\n    \"\"\"Wavefunction is the central object for manipulaion in the\n    OpenFermion-FQE.\n    \"\"\"\n\n    def __init__(self,\n                 param: Optional[List[List[int]]] = None,\n                 broken: Optional[Union[List[str], str]] = None) -> None:\n        \"\"\"\n        Args:\n            param (list[list[n, ms, norb]]): the constructor accepts a list of \\\n              parameter lists.  The parameter lists are comprised of\n\n              p[0] (integer) - number of particles;\n\n              p[1] (integer) - z component of spin angular momentum;\n\n              p[2] (integer) - number of spatial orbitals\n\n            broken (str): pass in the symmetries that should be preserved by \\\n                the wavefunction.\n\n        Member Variables:\n            _conserve_spin (bool): When this flag is true, the wavefunction \\\n                will maintain a constant m_s\n\n            _conserve_number (bool): When this flag is true, the wavefunction \\\n                will maintain a constant nele\n\n            _civec (dict[(int, int)] -> FqeData): This is a dictionary for \\\n                FqeData objects.  The key is a tuple defined by the number of \\\n                electrons and the spin projection of the system.\n        \"\"\"\n        self._symmetry_map: Dict[Tuple[int, int], Tuple[int, int]] = {}\n        self._conserved: Dict[str, int] = {}\n\n        self._conserve_spin: bool = False\n        if broken is None or 'spin' not in broken:\n            self._conserve_spin = True\n\n        self._conserve_number: bool = False\n        if broken is None or 'number' not in broken:\n            self._conserve_number = True\n\n        self._norb: int = 0\n        self._civec: Dict[Tuple[int, int], 'FqeData'] = {}\n\n        if not self._conserve_spin and not self._conserve_number:\n            raise TypeError('Number and spin non-conserving waveunfction is' \\\n                            ' the complete Fock space.')\n\n        if param:\n            user_input_norbs = set([x[2] for x in param])\n            if len(user_input_norbs) != 1:\n                raise ValueError('Number of orbitals is not consistent')\n\n            self._norb = list(user_input_norbs)[0]\n            for i in param:\n                nalpha, nbeta = alpha_beta_electrons(i[0], i[1])\n                self._civec[(i[0], i[1])] = FqeData(nalpha, nbeta, self._norb)\n\n            if self._conserve_number:\n                self._conserved['n'] = param[0][0]\n\n            if self._conserve_spin:\n                self._conserved['s_z'] = param[0][1]\n\n                if not self._conserve_number:\n                    self._symmetry_map = map_broken_symmetry(\n                        param[0][1], param[0][2])\n\n    def __add__(self, other: 'Wavefunction') -> 'Wavefunction':\n        \"\"\"Intrinsic addition function to combine two wavefunctions.  This acts \\\n        to iterate through the wavefunctions, combine coefficients of \\\n        configurations they have in common and add configurations that are \\\n        unique to each one.  The values are all combined into a new \\\n        wavefunction object\n\n        Args:\n            other (wavefunction.Wavefunction): the second wavefunction to \\\n                add with the local wavefunction\n\n        Returns:\n            wfn (wavefunction.Wavefunction): a new wavefunction with the \\\n                values set by adding together values\n        \"\"\"\n        out = copy.deepcopy(self)\n        out.ax_plus_y(1.0, other)\n        return out\n\n    def __iadd__(self, wfn: 'Wavefunction') -> 'Wavefunction':\n        \"\"\"Same is __add___ but performed in-place\n\n        Args:\n            wfn (wavefunction.Wavefunction): the second wavefunction to \\\n                add with the local wavefunction\n\n        Returns:\n            Wavefunction: self\n        \"\"\"\n        self.ax_plus_y(1.0, wfn)\n        return self\n\n    def __sub__(self, other: 'Wavefunction') -> 'Wavefunction':\n        \"\"\"Intrinsic subtraction function to combine two wavefunctions.  This\n        acts to iterate through the wavefunctions, combine coefficients of\n        configurations they have in common and include configurations that are\n        unique to each one. The values are all combined into a new\n        wavefunction object\n\n        Args:\n            other (wavefunction.Wavefunction): the second wavefunction that \\\n                will be subtracted from the first wavefunction\n\n        Returns:\n            wfn (wavefunction.Wavefunction): a new wavefunction with the\n                values set by subtracting the wfn from the first\n        \"\"\"\n        out = copy.deepcopy(self)\n        out.ax_plus_y(-1.0, other)\n        return out\n\n    def __getitem__(self, key: Tuple[int, int]) -> complex:\n        \"\"\"Element read access to the wave function.\n        Args:\n            key (Tuple[int, int]): a pair of strings for alpha and beta\n\n        Returns:\n            (complex): the value of the wave function\n        \"\"\"\n        astr, bstr = key[0], key[1]\n        sector = (count_bits(astr) + count_bits(bstr),\n                  count_bits(astr) - count_bits(bstr))\n        return self._civec[sector][key]\n\n    def __setitem__(self, key: Tuple[int, int], value: complex) -> None:\n        \"\"\"Element write access to the wave function.\n        Args:\n            key (Tuple[int, int]): a pair of strings for alpha and beta\n\n            value (complex): the value to be set to the wave function\n        \"\"\"\n        astr, bstr = key[0], key[1]\n        sector = (count_bits(astr) + count_bits(bstr),\n                  count_bits(astr) - count_bits(bstr))\n        self._civec[sector][key] = value\n\n    def empty_copy(self) -> 'Wavefunction':\n        \"\"\"create a copy of self with zero coefficients\n\n        Returns:\n            Wavefunction: a new object with zero coefficients\n        \"\"\"\n        out = Wavefunction()\n        out._norb = self._norb\n        out._conserved = self._conserved\n        out._symmetry_map = self._symmetry_map\n        for key, civec in self._civec.items():\n            out._civec[key] = civec.empty_copy()\n        return out\n\n    def _copy_beta_inversion(self) -> 'Wavefunction':\n        \"\"\"Return a copy of the wavefunction with the beta particle and hole\n        inverted.\n\n        Returns:\n            Wavefunction: wavefuction with beta particle/hole conjugation\n        \"\"\"\n        norb = self._norb\n        m_s = self._conserved['s_z']\n\n        nele = norb + m_s\n        param = []\n        maxb = min(norb, nele)\n        minb = nele - maxb\n        param = [\n            [nele, nele - nbeta * 2, norb] for nbeta in range(minb, maxb + 1)\n        ]\n\n        inverted = Wavefunction(param, broken=['spin'])\n\n        data = {}\n        for key, sector in self._civec.items():\n            work = ((key[0] + key[1]) // 2, (key[0] - key[1]) // 2)\n            nkey = self._symmetry_map[work]\n            data[(nkey[0] + nkey[1],\n                  nkey[0] - nkey[1])] = sector.beta_inversion()\n\n        inverted.set_wfn(strategy='from_data', raw_data=data)\n\n        return inverted\n\n    def ax_plus_y(self, sval: complex, wfn: 'Wavefunction') -> None:\n        \"\"\"Perform scale and add of the wavefunction. The result will be stored\n        in self.\n\n        Args:\n            sval (complex): a factor to be multiplied to wfn\n\n            wfn (Wavefunction): a wavefunction to be added to self\n        \"\"\"\n        if self._civec.keys() != wfn._civec.keys():\n            raise ValueError('inconsistent sectors in Wavefunction.ax_plus_y')\n\n        for sector in self._civec:\n            self._civec[sector].ax_plus_y(sval, wfn._civec[sector])\n\n    def sector(self, key: Tuple[int, int]) -> 'FqeData':\n        \"\"\"Return a specific sector of the wavefunction using a key.\n\n        Args:\n            key (Tuple[int, int]): key for ci vector\n        Returns:\n            FqeData: corresponding sector as an FqeData object\n        \"\"\"\n        return self._civec[key]\n\n    def sectors(self) -> KeysView[Tuple[int, int]]:\n        \"\"\"\n        Return:\n            KeysView[Tuple[int, int]]: a list of the configuration keys \\\n                in the wavefunction\n        \"\"\"\n        return self._civec.keys()\n\n    def conserve_number(self) -> bool:\n        \"\"\"\n        Returns:\n            (bool): True if this wave function conserves the number symmetry\n        \"\"\"\n        return self._conserve_number\n\n    def conserve_spin(self) -> bool:\n        \"\"\"\n        Returns:\n            (bool): True if this wave function conserves the spin (Sz) \\\n                symmetry. Otherwise False\n        \"\"\"\n        return self._conserve_spin\n\n    def norb(self) -> int:\n        \"\"\"\n        Returns:\n            (int): the number of orbitals\n        \"\"\"\n        return self._norb\n\n    def norm(self) -> float:\n        \"\"\"Calculate the norm of the wavefuntion\n\n        Returns:\n            (float): the norm\n        \"\"\"\n        normall = 0.0\n        for sector in self._civec.values():\n            normall += sector.norm()**2\n        normall = math.sqrt(normall)\n        return normall\n\n    def normalize(self) -> None:\n        \"\"\"Generte the wavefunction norm and then scale each element by that\n        value.\n        \"\"\"\n        self.scale(1.0 / self.norm())\n\n    @wrap_apply\n    def apply(self, hamil: 'hamiltonian.Hamiltonian') -> 'Wavefunction':\n        \"\"\" Returns a wavefunction subject to application of the Hamiltonian\n        (or more generally, the operator).\n\n        Args:\n            hamil (Hamiltonian): Hamiltonian to be applied\n\n        Returns:\n            (Wavefunction): resulting wave function array\n        \"\"\"\n        if not self._conserve_number or not hamil.conserve_number():\n            if self._conserve_number:\n                raise TypeError('Number non-conserving hamiltonian passed to'\n                                ' number conserving wavefunction')\n            if hamil.conserve_number():\n                raise TypeError('Number conserving hamiltonian passed to'\n                                ' number non-conserving wavefunction')\n\n        if isinstance(hamil, sparse_hamiltonian.SparseHamiltonian):\n\n            transformed = self._apply_few_nbody(hamil)\n\n        else:\n            if self._conserve_spin and not self._conserve_number:\n                out = self._copy_beta_inversion()\n            else:\n                out = self\n\n            if isinstance(hamil, diagonal_hamiltonian.Diagonal):\n                transformed = out._apply_diagonal(hamil)\n            elif isinstance(hamil, diagonal_coulomb.DiagonalCoulomb):\n                transformed = out._apply_diagonal_coulomb(hamil)\n            else:\n                if isinstance(hamil,\n                              restricted_hamiltonian.RestrictedHamiltonian):\n                    expected = self._norb\n                else:\n                    expected = self._norb * 2\n                if hamil.dim() != expected:\n                    raise ValueError('Hamiltonian has incorrect size:' \\\n                                     + ' expected {}'.format(expected) \\\n                                     + ' provided {}'.format(hamil.dim()))\n\n                transformed = out._apply_array(hamil.tensors(), hamil.e_0())\n\n            if self._conserve_spin and not self._conserve_number:\n                transformed = transformed._copy_beta_restore(\n                    self._conserved['s_z'], self._norb, self._symmetry_map)\n\n        return transformed\n\n    def _apply_array(self, array: Tuple[numpy.ndarray, ...],\n                     e_0: complex) -> 'Wavefunction':\n        \"\"\"Return a wavefunction subject to application of the numpy array as\n\n        .. math::\n            h[i, j]a_i^+ a_j|Psi>\n            h[i, j, k, l]a_i^+(rho) a_j^+(eta) a_k(rho) a_l(eta)|Psi>\n\n        Arg:\n            array (numpy.array): numpy array\n\n            e_0 (complex): scalar part of the Hamiltonian\n\n        Returns:\n            newwfn (Wavefunction): a new intialized wavefunction object\n\n        \"\"\"\n        if self._conserve_spin:\n            assert array[0].shape[0] == self._norb or array[0].shape[\n                0] == self._norb * 2\n            out = copy.deepcopy(self)\n            for _, sector in out._civec.items():\n                sector.apply_inplace(array)\n        else:\n            assert array[0].shape[0] == self._norb * 2\n            out = copy.deepcopy(self)\n            nsectors = out._number_sectors()\n            for _, nsector in nsectors.items():\n                nsector.apply_inplace(array)\n\n        if numpy.abs(e_0) > 1.e-15:\n            out.ax_plus_y(e_0, self)\n\n        return out\n\n    def _apply_diagonal(self, hamil: 'diagonal_hamiltonian.Diagonal'\n                       ) -> 'Wavefunction':\n        \"\"\"Applies the diagonal operator to the wavefunction\n\n        Args:\n            hamil (Diagonal): diagonal Hamiltonian to be applied\n\n        Returns:\n            (Wavefunction): resulting wave function\n        \"\"\"\n        out = copy.deepcopy(self)\n\n        for _, sector in out._civec.items():\n            sector.apply_diagonal_inplace(hamil.diag_values())\n\n        if numpy.abs(hamil.e_0()) > 1.e-15:\n            out.ax_plus_y(hamil.e_0(), self)\n\n        return out\n\n    def _apply_diagonal_coulomb(self, hamil: 'diagonal_coulomb.DiagonalCoulomb'\n                               ) -> 'Wavefunction':\n        \"\"\"Applies the diagonal coulomb operator to the wavefunction\n\n        Args:\n            hamil (DiagonalCoulomb): diagonal coulomb Hamiltonian to be applied\n\n        Returns:\n            (Wavefunction): resulting wave function\n        \"\"\"\n        out = copy.deepcopy(self)\n\n        for _, sector in out._civec.items():\n            diag, array = hamil._tensor[1], hamil._tensor[2]\n            sector.apply_diagonal_coulomb(diag, array, inplace=True)\n\n        if numpy.abs(hamil.e_0()) > 1.e-15:\n            out.ax_plus_y(hamil.e_0(), self)\n\n        return out\n\n    def _number_sectors(self) -> Dict[int, FqeDataSet]:\n        \"\"\"An internal utility function that groups FqeData into a set of\n        FqeDataSet that corresponds to the same number of electrons.  It checks\n        spin completeness and raises an exception if the wave function space is\n        not spin complete\n\n        Returns:\n            Dict[int, FqeDataSet]: stores FqeDataSet for each number of\n                particles. Keys are the number of particles.\n        \"\"\"\n        norb = self.norb()\n        numbers = set(key[0] for key in self._civec)\n        numbersectors = {}\n        for nele in numbers:\n            # generate all possible sz\n            maxalpha = min(norb, nele)\n            minalpha = nele - maxalpha\n            sectors = {}\n            sp_compl = set(((nele, 2 * nalpha - nele)\n                            for nalpha in range(minalpha, maxalpha + 1)))\n\n            if set(self._civec.keys()).intersection(sp_compl) != sp_compl:\n                raise ValueError('Wave function space is not spin complete.')\n\n            for nalpha in range(minalpha, maxalpha + 1):\n                nbeta = nele - nalpha\n                sectors[(nalpha, nbeta)] = self._civec[(nele, nalpha - nbeta)]\n            dataset = FqeDataSet(nele, norb, sectors)\n            numbersectors[nele] = dataset\n        return numbersectors\n\n    def _copy_beta_restore(self, s_z: int, norb: int,\n                           map_symm: Dict[Tuple[int, int], Tuple[int, int]]\n                          ) -> 'Wavefunction':\n        \"\"\"Return a copy of the wavefunction with beta restored back to number\n        breaking/spin conserving.\n\n        Args:\n            s_z (int): the value of Sz\n\n            norb (int): the number of orbitals in the system\n\n            map_symm (Dict[Tuple[int,int], Tuple[int,int]]): dictionary that maps \\\n                between number-conserved and spin-conserved wave function sectors\n\n        Returns:\n            Wavefunction: restored wavefunction\n        \"\"\"\n        max_alpha = min(norb, norb + s_z)\n        min_alpha = max(s_z, 0)\n\n        param = [[2 * nalpha - s_z, s_z, norb]\n                 for nalpha in range(min_alpha, max_alpha + 1)]\n\n        restored = Wavefunction(param, broken=['number'])\n\n        data = {}\n        for key in param:\n            work = ((key[0] + key[1]) // 2, (key[0] - key[1]) // 2)\n            nkey = map_symm[work]\n            other = (nkey[0] + nkey[1], nkey[0] - nkey[1])\n            data[(key[0], key[1])] = self._civec[other].beta_inversion()\n\n        restored.set_wfn(strategy='from_data', raw_data=data)\n\n        return restored\n\n    @wrap_apply_generated_unitary\n    def apply_generated_unitary(self,\n                                time: float,\n                                algo: str,\n                                hamil: 'hamiltonian.Hamiltonian',\n                                accuracy: float = 1.0E-14,\n                                expansion: int = 30,\n                                spec_lim: Optional[List[float]] = None\n                               ) -> 'Wavefunction':\n        \"\"\"Perform the exponentiation of fermionic algebras to the\n        wavefunction according the method and accuracy.\n\n        Args:\n            time (float): the final time value to evolve to\n\n            algo (string): polynomial expansion algorithm to be used\n\n            hamil (Hamiltonian): the Hamiltonian used to generate the unitary\n\n            accuracy (float): the accuracy to which the system should be evolved\n\n            expansion (int): the maximum number of terms in the polynomial expansion\n\n            spec_lim (List[float]): spectral range of the Hamiltonian, the length of \\\n                the list should be 2. Optional.\n\n        Returns:\n            newwfn (Wavefunction): a new intialized wavefunction object\n        \"\"\"\n\n        assert isinstance(hamil, hamiltonian.Hamiltonian)\n\n        algo_avail = ['taylor', 'chebyshev']\n\n        assert algo in algo_avail\n\n        if not isinstance(hamil, sparse_hamiltonian.SparseHamiltonian) \\\n            and self._conserve_spin and not self._conserve_number:\n            base = self._copy_beta_inversion()\n        else:\n            base = self\n\n        max_expansion = max(30, expansion)\n\n        if algo == 'taylor':\n            ham_arrays = hamil.iht(time)\n\n            time_evol = copy.deepcopy(base)\n            work = copy.deepcopy(base)\n\n            for order in range(1, max_expansion):\n                work = work.apply(ham_arrays)\n                coeff = 1.0 / factorial(order)\n                time_evol.ax_plus_y(coeff, work)\n                if work.norm() * numpy.abs(coeff) < accuracy:\n                    break\n\n        elif algo == 'chebyshev':\n\n            assert spec_lim, 'Spectral range was not provided.' + \\\n                                 ' Provide upper and lower limits.'\n\n            wprime = 0.9875\n            ascale = (spec_lim[1] - spec_lim[0]) / (2.0 * wprime)\n            eshift = -(spec_lim[0] + ascale * wprime)\n\n            time_evol = copy.deepcopy(base)\n            time_evol.scale(jv(0, ascale * time))\n            minus = copy.deepcopy(base)\n\n            current = minus.apply(hamil)\n            current.ax_plus_y(eshift, minus)\n            current.scale(1.0 / ascale)\n            time_evol.ax_plus_y(2.0 * jv(1, ascale * time) * (-1.j), current)\n\n            for order in range(2, max_expansion):\n                minus.scale(-1.0)\n                minus.ax_plus_y(2.0 / ascale, current.apply(hamil))\n                minus.ax_plus_y(2.0 * eshift / ascale, current)\n                current, minus = minus, current\n\n                coeff = 2.0 * jv(order, ascale * time) * (-1.j)**order\n                time_evol.ax_plus_y(coeff, current)\n\n                if current.norm() * numpy.abs(coeff) < accuracy:\n                    break\n\n            time_evol.scale(numpy.exp(eshift * time * 1.j))\n\n        if numpy.abs(hamil.e_0() * time) > 1.e-15:\n            time_evol.scale(numpy.exp(-1.j * time * hamil.e_0()))\n\n        if self._conserve_spin and not self._conserve_number:\n            time_evol = time_evol._copy_beta_restore(self._conserved['s_z'],\n                                                     self._norb,\n                                                     self._symmetry_map)\n        return time_evol\n\n    def get_coeff(self, key: Tuple[int, int]) -> numpy.ndarray:\n        \"\"\"Retrieve a vector from a configuration in the wavefunction\n\n        key indicates wavefunction sector by [num_alpha, num_beta]\n\n        Args:\n            key (Tuple[int, int]): a key identifying the configuration to access\n\n        Returns:\n            numpy.array(dtype=numpy.complex128): coeff that corresponds to key\n        \"\"\"\n        return self._civec[key].coeff\n\n    def max_element(self) -> complex:\n        \"\"\"\n        Return:\n            (complex): the largest magnitude value in the wavefunction\n        \"\"\"\n        maxval = 0.0\n        for config in self._civec.values():\n            configmax = max(config.coeff.max(),\n                            config.coeff.min(),\n                            key=numpy.abs)\n            maxval = max(configmax, maxval)\n\n        return maxval\n\n    def print_wfn(self, threshold: float = 0.001, fmt: str = 'str') -> None:\n        \"\"\"Print occupations and coefficients to the screen.\n\n        Args:\n            threshhold (float): only print CI vector values such that \\\n              :math:`|c|` > threshold.\n\n            fmt (string): formats print according to argument\n        \"\"\"\n\n        def _print_format(fmt: str) -> Callable[[int, int], str]:\n            \"\"\" Select the function which will perform formatted printing\n            \"\"\"\n            if fmt == 'occ':\n\n                def _occupation_format(iastring: int, ibstring: int):\n                    \"\"\"occ - Prints a string indicating occupation state of each spatial\n                    orbital.  A doubly occupied orbital will be indicated with \"2\",\n                    a singly occupied orbital will get \"a\" or \"b\" depending on the\n                    spin state.  An empy orbital will be \".\".\n                    \"\"\"\n                    astring = int(iastring)\n                    bstring = int(ibstring)\n                    occstr = [\n                        '.' for _ in range(\n                            max(astring.bit_length(), bstring.bit_length()))\n                    ]\n                    docc = astring & bstring\n\n                    def build_occ_value(bstr: int, char: str,\n                                        occstr: List[str]):\n                        \"\"\"Fill a list with a character corresponding to the\n                        location of '1' bits in bitstring\n\n                        Args:\n                            bstr (int): a bitstring to examine\n\n                            char (str): a string to put into the list\n\n                            occstr (list): a list to store the value\n                                corresponding to flipped bits\n                        \"\"\"\n                        ind = 1\n                        while bstr:\n                            if bstr & 1:\n                                occstr[-ind] = char\n                            ind += 1\n                            bstr = bstr >> 1\n\n                    build_occ_value(astring, 'a', occstr)\n                    build_occ_value(bstring, 'b', occstr)\n                    build_occ_value(docc, '2', occstr)\n\n                    return ''.join(occstr).rjust(self._norb, '.')\n\n                return _occupation_format\n\n            def _string_format(iastring: int, ibstring: int) -> str:\n                \"\"\"Prints a binary string indicating which orbital creation\n                operators are acting on the vacuum with a 1. The position in\n                the string indicates the index of the orbital. The beta string\n                is shown acting on the vacuum first.\n\n                Args:\n                    iastring (int): alpha string\n\n                    ibstring (int): alpha string\n\n                Returns:\n                    str: representation of binary string\n                \"\"\"\n                astring = int(iastring)\n                bstring = int(ibstring)\n                fmt_a = bin(1 << self._norb | astring)\n                fmt_b = bin(1 << self._norb | bstring)\n                return \"a'{}'b'{}'\".format(fmt_a[3:], fmt_b[3:])\n\n            return _string_format\n\n        print_format = _print_format(fmt)\n\n        config_in_order = sort_configuration_keys(self.sectors())\n        for key in config_in_order:\n            self._civec[key].print_sector(pformat=print_format,\n                                          threshold=threshold)\n\n    def read(self, filename: str, path: str = os.getcwd()) -> None:\n        \"\"\"Initialize a wavefunction from a binary file.\n\n        Args:\n            filename (str): the name of the file to write the wavefunction to.\n\n            path (str): the path to save the file.  If no path is given then \\\n              it is saved in the current working directory.\n        \"\"\"\n        with open(os.path.join(path, filename), 'r+b') as wfnfile:\n            wfn_data = pickle.load(wfnfile)\n\n        self._symmetry_map = wfn_data[0]\n        self._conserved = wfn_data[1]\n        self._conserve_spin = wfn_data[2]\n        self._conserve_number = wfn_data[3]\n        self._norb = wfn_data[4]\n\n        for sector in wfn_data[5:]:\n            self._civec[(sector[0][0], sector[0][1])] = sector[1]\n\n    def save(self, filename: str, path: str = os.getcwd()) -> None:\n        \"\"\"Save the wavefunction into path/filename.\n\n        Args:\n            filename (str): the name of the file to write the wavefunction to.\n\n            path (str): the path to save the file.  If no path is given, then \\\n              it is saved in the current working directory.\n        \"\"\"\n        wfn_data = [\n            self._symmetry_map, self._conserved, self._conserve_spin,\n            self._conserve_number, self._norb\n        ]\n\n        for key in self._civec:\n            wfn_data.append([key, self._civec[key]])\n\n        with open(os.path.join(path, filename), 'w+b') as wfnfile:\n            pickle.dump(wfn_data, wfnfile)\n\n    def scale(self, sval: complex) -> None:\n        \"\"\" Scale each configuration space by the value sval\n\n        Args:\n            sval (complex): value to scale by\n        \"\"\"\n\n        sval = complex(sval)  # type: ignore\n\n        for sector in self._civec.values():\n            sector.scale(sval)\n\n    def set_wfn(self,\n                strategy: str = 'ones',\n                raw_data: Optional[Dict[Tuple[int, int], numpy.ndarray]] = None\n               ) -> None:\n        \"\"\"Set the values of the wavefunction inplace based on a strategy.\n\n        Args:\n            strategy (string): The procedure to follow to set the wavefunction \\\n                coefficients. One of 'random', 'hartree-fock', 'ones', 'zeros', \\\n                or 'from_data'. If 'from_data', raw_data must be provided.\n\n            raw_data (Dict[Tuple[int, int], numpy.ndarray]): The values to use \\\n                if setting from data. Optional.\n        \"\"\"\n        if strategy == 'from_data' and not raw_data:\n            raise ValueError('No data provided for set_wfn')\n\n        if strategy == 'from_data':\n            for key, data in raw_data.items():  # type: ignore\n                self._civec[key].set_wfn(strategy='from_data', raw_data=data)\n        elif strategy == 'hartree-fock':\n            # make sure we only have 1 sector\n            if len(self.sectors()) != 1:\n                raise ValueError((\"Hartree-Fock wf initialization only works \"\n                                  \"with single sector wavefunctions\"))\n            for sector in self._civec.values():\n                sector.set_wfn(strategy=strategy)\n        else:\n            for sector in self._civec.values():\n                sector.set_wfn(strategy=strategy)\n\n        if strategy == 'random':\n            self.normalize()\n\n    def transform(\n            self,\n            rotation: numpy.ndarray,\n            low: Optional[numpy.ndarray] = None,\n            upp: Optional[numpy.ndarray] = None\n    ) -> Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray, 'Wavefunction']:\n        \"\"\"Transform the wavefunction using the orbtial rotation matrix and\n        return the new wavefunction and the permutation matrix for the unitary\n        transformation. This is an internal code, so performs minimal checking\n\n        Args:\n            rotation (numpy.ndarray): MO rotation matrix, which is unitary\n\n            low (numpy.ndarray): L in the LU decomposition (optional)\n\n            upp (numpy.ndarray): U in the LU decomposition (optional)\n\n        Returns:\n            (numpy.ndarray, numpy.ndarray, numpy.ndarray, 'Wavefunction'): \\\n                permutation, L, U, and transformed wavefunction\n        \"\"\"\n        norb = self._norb\n        external = low is not None\n        assert external == (upp is not None)\n        if external:\n            assert numpy.allclose(rotation, low @ upp)  # type: ignore\n\n        def ludecomp(rotmat: numpy.ndarray\n                    ) -> Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]:\n            \"\"\"Returns permutation, lower triangular, and upper triangular\n            matrices from the LU decomposition. Note that the rotation matrix\n            is Hermitian conjugated.\n\n            Args:\n                rotmat (numpy.ndarray): MO rotation matrix, which is unitary\n\n                (numpy.ndarray, numpy.ndarray, numpy.ndarray): permutation, \\\n                    L, and U from the LU decomposition.\n            \"\"\"\n            tmat = rotmat.transpose().conjugate()\n            return linalg.lu(tmat)\n\n        def transpose_matrix(low: numpy.ndarray, upp: numpy.ndarray\n                            ) -> Tuple[numpy.ndarray, numpy.ndarray]:\n            \"\"\"Returns Hermitian conjugate of the L and U factors. The diagonal\n            elements are in the upper triagular matrix. This transposition seeks to\n            compensate the transposition in ludecomp above.\n\n            Args:\n                low (numpy.ndarray): L in the LU decomposition\n\n                upp (numpy.ndarray): U in the LU decomposition\n\n            Returns:\n                (numpy.ndarray, numpy.ndarray): L and U after transposition \\\n                    where L and U are lower- and upper-triangular, respectively\n            \"\"\"\n            ndim = low.shape[0]\n            assert low.shape[1] == ndim and upp.shape == (ndim, ndim)\n            lowt = copy.deepcopy(low)\n            uppt = copy.deepcopy(upp)\n            for irow in range(ndim):\n                for icol in range(irow + 1, ndim):\n                    uppt[irow, icol] /= uppt[irow, irow]\n                lowt[irow, irow], uppt[irow, irow] = uppt[irow, irow], lowt[\n                    irow, irow]\n                for icol in range(irow):\n                    lowt[irow, icol] *= lowt[icol, icol]\n            return uppt.T.conj(), lowt.T.conj()\n\n        def process_matrix(low: numpy.ndarray,\n                           upp: numpy.ndarray) -> numpy.ndarray:\n            \"\"\"Returns an operator using which the wavefuction will be transformed.\n\n            Args:\n                low (numpy.ndarray): L in the LU decomposition\n\n                upp (numpy.ndarray): U in the LU decomposition\n\n            Returns:\n                (numpy.ndarray): matrix elements of the transformation operator T\n            \"\"\"\n            ndim = low.shape[0]\n            assert low.shape[1] == ndim and upp.shape == (ndim, ndim)\n            unitmat = numpy.identity(ndim)\n            output = linalg.solve_triangular(upp, unitmat)\n\n            for icol in range(ndim):\n                for irow in range(icol + 1, ndim):\n                    output[irow, icol] -= low[irow, icol]\n                output[icol, icol] -= 1.0\n            return output\n\n        current = self\n        perm = None\n\n        if not self._conserve_spin:\n            if not external:\n                perm, low, upp = ludecomp(rotation)\n                lowt, uppt = transpose_matrix(low, upp)\n            else:\n                lowt, uppt = low, upp\n            output = process_matrix(lowt, uppt)\n            for icol in range(norb * 2):\n                work = numpy.zeros_like(rotation)\n                work[:, icol] = output[:, icol]\n                onefwfn = current.apply((work,))\n                current.ax_plus_y(1.0, onefwfn)\n        else:\n            if rotation.shape[0] == norb:\n                if not external:\n                    perm, low, upp = ludecomp(rotation)\n                    lowt, uppt = transpose_matrix(low, upp)\n                else:\n                    lowt, uppt = low, upp\n                output = process_matrix(lowt, uppt)\n                for _, civec in current._civec.items():\n                    civec.apply_columns_recursive_inplace(output, output)\n            elif rotation.shape[0] == norb * 2:\n                assert numpy.std(rotation[:norb, norb:]) \\\n                       + numpy.std(rotation[norb:, :norb]) < 1.0e-8\n                if not external:\n                    perm1, low1, upp1 = ludecomp(rotation[:norb, :norb])\n                    perm2, low2, upp2 = ludecomp(rotation[norb:, norb:])\n                    lowt1, uppt1 = transpose_matrix(low1, upp1)\n                    lowt2, uppt2 = transpose_matrix(low2, upp2)\n                else:\n                    lowt1 = low[:norb, :norb]  # type: ignore\n                    lowt2 = low[norb:, norb:]  # type: ignore\n                    uppt1 = upp[:norb, :norb]  # type: ignore\n                    uppt2 = upp[norb:, norb:]  # type: ignore\n                output1 = process_matrix(lowt1, uppt1)\n                output2 = process_matrix(lowt2, uppt2)\n                for _, civec in current._civec.items():\n                    civec.apply_columns_recursive_inplace(output1, output2)\n                if not external:\n                    perm = numpy.zeros_like(rotation)\n                    perm[:norb, :norb] = perm1[:, :]\n                    perm[norb:, norb:] = perm2[:, :]\n                    upp = numpy.zeros_like(rotation)\n                    upp[:norb, :norb] = upp1[:, :]\n                    upp[norb:, norb:] = upp2[:, :]\n                    low = numpy.zeros_like(rotation)\n                    low[:norb, :norb] = low1[:, :]\n                    low[norb:, norb:] = low2[:, :]\n\n        return perm, low, upp, current\n\n    @wrap_time_evolve\n    def time_evolve(\n            self,\n            time: float,\n            hamil: Union['fqe_operator.FqeOperator', 'hamiltonian.Hamiltonian'],\n            inplace: bool = False) -> 'Wavefunction':\n        \"\"\"Perform time evolution of the wavefunction given Fermion Operators\n        either as raw operations or wrapped up in a Hamiltonian.\n\n        Args:\n            time (float): the duration by which to evolve the operators\n\n            hamil (Hamiltoninan or FermionOperator): Hamiltonian to be used for \\\n                time evolution\n\n            inplace (bool): whether the result will be stored in place\n\n        Returns:\n            (Wavefunction): a wavefunction object that has been time evolved.\n        \"\"\"\n        assert isinstance(hamil, hamiltonian.Hamiltonian)\n\n        if not self._conserve_number or not hamil.conserve_number():\n            if self._conserve_number:\n                raise TypeError('Number non-conserving hamiltonian passed to'\n                                ' number conserving wavefunction')\n            if hamil.conserve_number():\n                raise TypeError('Number conserving hamiltonian passed to'\n                                ' number non-conserving wavefunction')\n\n        if isinstance(\n                hamil,\n                sparse_hamiltonian.SparseHamiltonian) and hamil.is_individual():\n\n            final_wfn = self._evolve_individual_nbody(time, hamil, inplace)\n\n        else:\n            is_diag = ((hamil.quadratic() and hamil.diagonal()) or\n                       hamil.diagonal_coulomb())\n            if inplace and (not is_diag and not hamil.quadratic()):\n                raise ValueError(\"Inplace is not implemented for this case\")\n\n            if self._conserve_spin and not self._conserve_number:\n                work_wfn = self._copy_beta_inversion()\n            elif inplace:\n                work_wfn = self\n            else:\n                work_wfn = copy.deepcopy(self)\n\n            if hamil.quadratic():\n                if hamil.diagonal():\n\n                    ihtdiag = -1.j * time * hamil.diag_values()\n                    final_wfn = work_wfn._evolve_diagonal(ihtdiag, inplace)\n\n                else:\n                    transformation = hamil.calc_diag_transform()\n\n                    permu, low, upp, work_wfn = work_wfn.transform(\n                        transformation)\n\n                    ci_trans = transformation @ permu\n\n                    h1e = hamil.transform(ci_trans)\n\n                    ihtdiag = -1.j * time * h1e.diagonal()\n                    evolved_wfn = work_wfn._evolve_diagonal(ihtdiag,\n                                                            inplace=True)\n\n                    _, _, _, final_wfn = evolved_wfn.transform(\n                        ci_trans.T.conj(), low, upp)\n\n            elif hamil.diagonal_coulomb():\n\n                diag, vij = hamil.iht(time)\n\n                final_wfn = work_wfn._evolve_diagonal_coulomb_inplace(diag, vij)\n\n            else:\n\n                final_wfn = work_wfn.apply_generated_unitary(\n                    time, 'taylor', hamil)\n\n            if self._conserve_spin and not self._conserve_number:\n                final_wfn = final_wfn._copy_beta_restore(\n                    self._conserved['s_z'], self._norb, self._symmetry_map)\n\n        if numpy.abs(hamil.e_0()) > 1.0e-15:\n            final_wfn.scale(numpy.exp(-1.j * time * hamil.e_0()))\n\n        return final_wfn\n\n    def _evolve_diagonal(self, ithdiag: numpy.ndarray,\n                         inplace: bool = False) -> 'Wavefunction':\n        \"\"\"Evolve a diagonal Hamiltonian on the wavefunction\n\n        Args:\n            ithdiag (numpy.ndarray): preprocessed diagonal array\n\n            inplace (bool): whether the result will be stored in-place\n\n        Returns:\n            (Wavefunction): resulting wave function. If in-place is True,\n                self is returned.\n        \"\"\"\n        if inplace:\n            wfn = self\n        else:\n            wfn = copy.deepcopy(self)\n\n        for key, sector in self._civec.items():\n            wfn._civec[key].coeff = sector.evolve_diagonal(ithdiag, inplace)\n\n        return wfn\n\n    def _evolve_diagonal_coulomb_inplace(self, diag: numpy.ndarray,\n                                         vij: numpy.ndarray) -> 'Wavefunction':\n        \"\"\"Evolve a diagonal coulomb Hamiltonian on the wavefunction and store the\n        result inplace.  (Not in-place version is no longer used and thus has been\n        removed).\n\n        Args:\n            diag (numpy.ndarray): 1-body part of the Hamiltonian\n\n            vij (numpy.ndarray): 2-body part of the Hamiltonian\n\n        Returns:\n            (Wavefunction): wavefunction after 1 time step of the time evolution.\n                since this function is in-place, what is returned is always self.\n        \"\"\"\n\n        for key, sector in self._civec.items():\n            self._civec[key].coeff = sector.evolve_diagonal_coulomb(\n                diag, vij, inplace=True)\n        return self\n\n    def expectationValue(\n            self,\n            ops: Union['fqe_operator.FqeOperator', 'hamiltonian.Hamiltonian'],\n            brawfn: 'Wavefunction' = None) -> Union[complex, numpy.ndarray]:\n        \"\"\"Calculates expectation values given operators\n\n        Args:\n            ops (FqeOperator or Hamiltonian): operator for which the expectation value is \\\n                computed\n\n            brawfn (Wavefunction): bra-side wave function for transition quantity (optional)\n\n        Returns:\n            (complex or numpy.ndarray): resulting expectation value or RDM\n        \"\"\"\n        if isinstance(ops, fqe_operator.FqeOperator):\n            if brawfn:\n                return ops.contract(brawfn, self)\n            return ops.contract(self, self)\n\n        if isinstance(ops, str):\n            if any(char.isdigit() for char in ops):\n                ops = sparse_hamiltonian.SparseHamiltonian(ops)\n            else:\n                return self.rdm(ops, brawfn=brawfn)\n\n        if not isinstance(ops, hamiltonian.Hamiltonian):\n            raise TypeError('Expected an Fqe Hamiltonian or Operator' \\\n                            ' but recieved {}'.format(type(ops)))\n        workwfn = self.apply(ops)\n\n        if brawfn:\n            return vdot(brawfn, workwfn)\n        return vdot(self, workwfn)\n\n    def _apply_individual_nbody(self,\n                                hamil: 'sparse_hamiltonian.SparseHamiltonian',\n                                base: 'Wavefunction' = None) -> 'Wavefunction':\n        \"\"\"\n        Applies an individual n-body operator to the wave function self.\n\n        Args:\n            hamil (SparseHamiltonian): Sparse Hamiltonian to be applied to the wavefunction\n`\n            base (Wavefunction): the result will be accumulated to base\n\n        Returns:\n            (Wavefunction): resulting wavefunciton. When base is provided, base is returned\n        \"\"\"\n        assert isinstance(hamil, sparse_hamiltonian.SparseHamiltonian)\n\n        if hamil.nterms() > 1:\n            raise ValueError(\n                'Indivisual n-body code is called with multiple terms')\n\n        [(coeff, alpha, beta)] = hamil.terms()\n        daga = []\n        dagb = []\n        undaga = []\n        undagb = []\n        for oper in alpha:\n            assert oper[0] < self._norb\n            if oper[1] == 1:\n                daga.append(oper[0])\n            else:\n                undaga.append(oper[0])\n        for oper in beta:\n            assert oper[0] < self._norb\n            if oper[1] == 1:\n                dagb.append(oper[0])\n            else:\n                undagb.append(oper[0])\n\n        if len(daga) + len(dagb) != len(undaga) + len(undagb):\n            raise ValueError('Number non-conserving operators specified')\n\n        if base is None:\n            out = self.empty_copy()\n        else:\n            out = base\n        if len(daga) == len(undaga) and len(dagb) == len(undagb):\n            for key in self._civec.keys():\n                out._civec[key].apply_individual_nbody_accumulate(\n                    coeff, self._civec[key], daga, undaga, dagb, undagb)\n        else:\n            ssectors = self._number_sectors()\n            nsectors = out._number_sectors()\n            for skey, nsector in nsectors.items():\n                nsector.apply_individual_nbody_accumulate(\n                    coeff, ssectors[skey], daga, undaga, dagb, undagb)\n        return out\n\n    def _evolve_individual_nbody(self,\n                                 time: float,\n                                 hamil: 'sparse_hamiltonian.SparseHamiltonian',\n                                 inplace: bool = False) -> 'Wavefunction':\n        \"\"\"Apply up to 4-body individual operator.\n\n        This routine assumes the Hamiltonian is normal ordered.\n\n        Args:\n            time (float): time for evolution\n\n            hamil (SparseHamiltonian): Sparse Hamiltonian using which \\\n                the wavefunction is evolved\n\n            inplace (bool): whether to store the results in-place\n\n        Returns:\n            (Wavefunction): resulting wavefunciton. If inplace is True, \\\n                self is returned.\n        \"\"\"\n        if not isinstance(hamil, sparse_hamiltonian.SparseHamiltonian):\n            raise TypeError('Expected a Hamiltonian Object but received' \\\n                            ' {}'.format(hamil))\n\n        if hamil.nterms() > 2:\n            raise ValueError(\n                'Individual n-body code is called with multiple terms')\n\n        # check if everything is paired\n        if hamil.nterms() == 2:\n            [(coeff0, alpha0, beta0), (coeff1, alpha1, beta1)] = hamil.terms()\n            check = True\n            for aop in alpha0:\n                check &= (aop[0], aop[1] ^ 1) in alpha1\n            for bop in beta0:\n                check &= (bop[0], bop[1] ^ 1) in beta1\n\n            if self._conserve_number:\n                if not check:\n                    raise ValueError(\n                        'Operators in _evolve_individual_nbody is not Hermitian'\n                    )\n        else:\n            [\n                (coeff0, alpha0, beta0),\n            ] = hamil.terms()\n            check = True\n            for aop in alpha0:\n                check &= (aop[0], aop[1] ^ 1) in alpha0\n            for bop in beta0:\n                check &= (bop[0], bop[1] ^ 1) in beta0\n\n            if self._conserve_number:\n                if not check:\n                    raise ValueError(\n                        'Operators in _evolve_individual_nbody is not Hermitian'\n                    )\n            coeff0 *= 0.5\n\n        daga = []\n        dagb = []\n        undaga = []\n        undagb = []\n\n        for oper in alpha0:\n            assert oper[0] < self._norb\n            if oper[1] == 1:\n                daga.append(oper[0])\n            else:\n                undaga.append(oper[0])\n\n        for oper in beta0:\n            assert oper[0] < self._norb\n            if oper[1] == 1:\n                dagb.append(oper[0])\n            else:\n                undagb.append(oper[0])\n\n        if hamil.nterms() == 2:\n            parity = (-1)**(len(alpha0) * len(beta0) + len(daga) * (len(daga)-1)//2 \\\n                            + len(dagb) * (len(dagb) - 1) // 2 \\\n                            + len(undaga) * (len(undaga) - 1) // 2 \\\n                            + len(undagb) * (len(undagb) - 1) // 2)\n            if not numpy.abs(coeff0 - numpy.conj(coeff1) * parity) < 1.0e-8:\n                raise ValueError(\n                    'Coefficients in _evolve_individual_nbody is not Hermitian')\n\n\n        if daga == undaga and dagb == undagb:\n            out = self if inplace else copy.deepcopy(self)\n            for _, sector in out._civec.items():\n                sector.evolve_inplace_individual_nbody_trivial(\n                    time, coeff0, daga, dagb)\n        else:\n            out = Wavefunction()\n            out._norb = self._norb\n            out._conserved = self._conserved\n            out._symmetry_map = self._symmetry_map\n            if len(daga) == len(undaga) and len(dagb) == len(undagb):\n                for label, isec in self._civec.items():\n                    osec = isec.evolve_individual_nbody_nontrivial(time, coeff0, daga, \\\n                                                                   undaga, dagb, undagb)\n                    out._civec[label] = osec\n            else:\n                nsectors = self._number_sectors()\n                for _, nsector in nsectors.items():\n                    osector = nsector.evolve_individual_nbody(time, coeff0, daga, \\\n                                                              undaga, dagb, undagb)\n                    for (nalpha, nbeta), osec in osector.sectors().items():\n                        out._civec[(nalpha + nbeta, nalpha - nbeta)] = osec\n        return out\n\n    def _apply_few_nbody(self, hamil: 'sparse_hamiltonian.SparseHamiltonian'\n                        ) -> 'Wavefunction':\n        \"\"\" Applies SparseHamiltonian by looping over all of the operators.\n        Useful when the operator is extremely sparse\n\n        Args:\n            hamil (SparseHamiltonian): Sparse Hamiltonian to be applied to the wavefunction\n\n        Returns:\n            (Wavefunction): resulting wavefunciton\n        \"\"\"\n        out = None\n        for oper in hamil.terms_hamiltonian():\n            if out is None:\n                out = self._apply_individual_nbody(oper)\n            else:\n                out = self._apply_individual_nbody(oper, base=out)\n\n        if out is None:\n            out = copy.deepcopy(self)\n\n        if numpy.abs(hamil.e_0()) > 1.e-15:\n            out.ax_plus_y(hamil.e_0(), self)\n\n        return out\n\n    @wrap_rdm\n    def rdm(self, string: str, brawfn: Optional['Wavefunction'] = None\n           ) -> Union[complex, numpy.ndarray]:\n        \"\"\" Returns rank-1 RDM. The operator order is specified by string.\n        Note that, if the entire RDM is requested for N-broken wave function,\n        this returns a packed format.\n\n        Args:\n            string (str): character strings that specify the quantity to be computed\n\n            brawfn (Wavefunction): bra-side wave function for transition RDM (optional)\n\n        Returns:\n            Union[complex, numpy.ndarray]: Resulting RDM in numpy.ndarray or \\\n                an RDM element in complex\n        \"\"\"\n        rank = len(string.split()) // 2\n        if any(char.isdigit() for char in string):\n            result = self.apply(sparse_hamiltonian.SparseHamiltonian(string))\n            if brawfn is None:\n                return vdot(self, result)\n            return vdot(brawfn, result)\n\n        fqe_ops_utils.validate_rdm_string(string)\n        rdm = list(self._compute_rdm(rank, brawfn))\n        return wick(string, rdm, self._conserve_spin)\n\n    def _compute_rdm(self, rank: int, brawfn: 'Wavefunction' = None\n                    ) -> Tuple[numpy.ndarray, ...]:\n        \"\"\"Internal function that computes RDM up to rank = rank\n\n        Args:\n            rank (int): the rank up to which RDMs are computed\n\n            brawfn (Wavefunction): bra wavefunction for transition RDMs (optional)\n\n        Returns:\n            Tuple[numpy.ndarray, ...]: tuple of RDMs\n        \"\"\"\n        assert rank > 0\n        assert rank < 5\n\n        out: List[Any] = [None, None, None, None]\n        tmp: List[Any] = [None, None, None, None]\n\n        if self._conserve_spin:\n            for key, sector in self._civec.items():\n                assert brawfn is None or key in brawfn.sectors()\n                bra = None if brawfn is None else brawfn._civec[key]\n                if rank == 1:\n                    (tmp[0],) = sector.rdm1(bra)\n                elif rank == 2:\n                    (tmp[0], tmp[1]) = sector.rdm12(bra)\n                elif rank == 3:\n                    (tmp[0], tmp[1], tmp[2]) = sector.rdm123(bra)\n                elif rank == 4:\n                    (tmp[0], tmp[1], tmp[2], tmp[3]) = sector.rdm1234(bra)\n                for i in range(4):\n                    if tmp[i] is not None:\n                        out[i] = tmp[i] if out[i] is None else out[i] + tmp[i]\n            out2: List[numpy.ndarray] = []\n            for i in range(4):\n                if out[i] is not None:\n                    out2.append(out[i])\n            return tuple(out2)\n\n        numbersectors = self._number_sectors()\n        for nkey, dataset in numbersectors.items():\n            assert brawfn is None or nkey in brawfn._number_sectors().keys()\n            nbra = None if brawfn is None else brawfn._number_sectors()[nkey]\n            if rank == 1:\n                (tmp[0],) = dataset.rdm1(nbra)\n            elif rank == 2:\n                (tmp[0], tmp[1]) = dataset.rdm12(nbra)\n            elif rank == 3:\n                (tmp[0], tmp[1], tmp[2]) = dataset.rdm123(nbra)\n            elif rank == 4:\n                (tmp[0], tmp[1], tmp[2], tmp[3]) = dataset.rdm1234(nbra)\n            for i in range(4):\n                if tmp[i] is not None:\n                    out[i] = tmp[i] if out[i] is None else out[i] + tmp[i]\n        out2 = []\n        for i in range(4):\n            if out[i] is not None:\n                out2.append(out[i])\n        return tuple(out2)\n", "meta": {"hexsha": "c4934823c184163bfdd9838fa5a370d484d3d9b8", "size": 53149, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/fqe/wavefunction.py", "max_stars_repo_name": "MichaelBroughton/OpenFermion-FQE", "max_stars_repo_head_hexsha": "b0c041d3284d9ce6523295b2a4cf17a8e6b37190", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fqe/wavefunction.py", "max_issues_repo_name": "MichaelBroughton/OpenFermion-FQE", "max_issues_repo_head_hexsha": "b0c041d3284d9ce6523295b2a4cf17a8e6b37190", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fqe/wavefunction.py", "max_forks_repo_name": "MichaelBroughton/OpenFermion-FQE", "max_forks_repo_head_hexsha": "b0c041d3284d9ce6523295b2a4cf17a8e6b37190", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7746979389, "max_line_length": 92, "alphanum_fraction": 0.5465389753, "include": true, "reason": "import numpy,from scipy", "num_tokens": 12156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.19985351422735698}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Ed Mountjoy (March 2018)\n#\n\"\"\"\nWrapper for Verena Zuber's colocalisation method\n\nAssumptions:\n    - GWAS and cov matrix are referring to the same strand\n\"\"\"\n\nimport sys\nimport argparse\nimport pandas as pd\nimport numpy as np\nimport Finemap\nimport pickle\n\ndef main():\n\n    # Get args\n    args = parse_args()\n    chrom, start, end = parse_range(args.range)\n\n    #\n    # Load and run 1-D finemapping on left dataset -----------------------------\n    #\n\n    # Load left sumstats\n    print(\"Loading left sumstats...\")\n    left_z, left_efal, left_n = parse_sumstats(args.left_sumstats, chrom, start,\n        end, args.left_rsidcol, args.left_chromcol, args.left_poscol,\n        args.left_betacol, args.left_secol, args.left_effalcol, args.left_ncol,\n        args.sep)\n    print(\"  {0} variants loaded...\".format(left_z.shape[0]))\n\n    # Load left cov matrix\n    print(\"Loading left cov matrix...\")\n    left_cov, left_cov_efal = parse_cov_matrix(args.left_cov, args.left_covmeta)\n    print(\"  {0} variants loaded...\".format(left_cov.shape[0]))\n\n    # Harmonise left z-scores and cov matrix\n    print(\"Harmonising left sumstat and cov matrix...\")\n    left_z, left_cov = harmonise_z_covmat(left_z, left_cov, left_efal,\n                                          left_cov_efal)\n    print(\"  {0} overlapping variants...\".format(left_z.shape[0]))\n\n    # Run finemap on left\n    print(\"Running finemap on left...\")\n    left_res = Finemap.finemap(left_z.as_matrix(),\n                               left_cov.as_matrix(),\n                               left_n,\n                               left_z.index.tolist(),\n                               kmax=args.left_kmax,\n                               kstart=args.left_kstart,\n                               max_iter=args.maxiter,\n                               prior=args.prior,\n                               v_scale=args.v_scale,\n                               g=args.g)\n    # Write output as a pickled object and pandas df\n    save_object(left_res, \"{0}.left_configurations.pkl\".format(args.outprefix))\n    left_res_df = finemap_obj_to_df(left_res)\n    left_res_df.to_csv(\"{0}.left_configurations.tsv\".format(args.outprefix),\n                       sep=\"\\t\", index=None)\n\n    #\n    # Load and run 1-D finemapping on 2nd (right) dataset ----------------------\n    #\n\n    # Skip if no 2nd dataset is provided\n    if args.right_sumstats is None:\n        print(\"No right dataset provided (--right_sumstats). Finishing here!\")\n        return 0\n\n    # Load right sumstats\n    print(\"Loading right sumstats...\")\n    right_z, right_efal, right_n = parse_sumstats(args.right_sumstats, chrom,\n        start, end, args.right_rsidcol, args.right_chromcol, args.right_poscol,\n        args.right_betacol, args.right_secol, args.right_effalcol,\n        args.right_ncol, args.sep)\n    print(\"  {0} variants loaded...\".format(right_z.shape[0]))\n\n    # Load right cov matrix\n    print(\"Loading right cov matrix...\")\n    right_cov, right_cov_efal = parse_cov_matrix(args.right_cov,\n                                                 args.right_covmeta)\n    print(\"  {0} variants loaded...\".format(right_cov.shape[0]))\n\n    # Harmonise right z-scores and cov matrix\n    print(\"Harmonising right sumstat and cov matrix...\")\n    right_z, right_cov = harmonise_z_covmat(right_z, right_cov, right_efal,\n                                            right_cov_efal)\n    print(\"  {0} overlapping variants...\".format(right_z.shape[0]))\n\n    # Run finemap on right\n    print(\"Running finemap on right...\")\n    right_res = Finemap.finemap(right_z.as_matrix(),\n                                right_cov.as_matrix(),\n                                right_n,\n                                right_z.index.tolist(),\n                                kmax=args.right_kmax,\n                                kstart=args.right_kstart,\n                                max_iter=args.maxiter,\n                                prior=args.prior,\n                                v_scale=args.v_scale,\n                                g=args.g)\n    # Write output as a pickled object and pandas df\n    save_object(right_res, \"{0}.right_configurations.pkl\".format(args.outprefix))\n    right_res_df = finemap_obj_to_df(right_res)\n    right_res_df.to_csv(\"{0}.right_configurations.tsv\".format(args.outprefix),\n                       sep=\"\\t\", index=None)\n\n    #\n    # Caluclate 2D joint posteriors (colocalisation)\n    #\n\n    print(\"Running colocalisation between left and right...\")\n\n    coloc_evidence, joint_res = left_res.joint_posterior(right_res)\n\n    # Write table of joint posterior configurations\n    joint_res_df = joint_posterior_to_df(joint_res)\n    joint_res_df.to_csv(\"{0}.joint_configurations.tsv\".format(args.outprefix),\n                       sep=\"\\t\", index=None)\n    save_object(joint_res, \"{0}.joint_configurations.pkl\".format(args.outprefix))\n    # Write file containing single colocalisation evidence score\n    outf = \"{0}.joint_evidence.tsv\".format(args.outprefix)\n    with open(outf, \"wb\") as out_h:\n        out_h.write(\"{0}\\n\".format(coloc_evidence).encode(\"utf8\"))\n\n    print(\"Finished!\")\n\n    return 0\n\ndef joint_posterior_to_df(obj):\n    \"\"\" Converts POSTGAP joint posterior (colocalisation) in a pandas df\n    Args:\n        obj (TwoDConfigurationSample)\n    Returns:\n        Dataframe\n    \"\"\"\n    # Add each configuration as a row\n    rows = []\n    for configuration in obj.configurations:\n        snp_labels = \";\".join([obj.labels[position] for position in configuration])\n        index = obj.configurations[configuration]\n        posterior  = obj.posterior[index]\n        posterior1 = obj.posterior1[index]\n        posterior2 = obj.posterior2[index]\n        rows.append([snp_labels, posterior1, posterior2, posterior])\n    df = pd.DataFrame(rows, columns=[\"snps\", \"left_posterior\", \"right_posterior\", \"joint_posterior\"])\n    df = df.sort_values(\"joint_posterior\", ascending=False)\n    return df\n\ndef finemap_obj_to_df(obj):\n    \"\"\" Converts POSTGAP finemap object to a pandas df\n    Args:\n        obj (OneDConfigurationSample)\n    Returns:\n        Dataframe\n    \"\"\"\n    # Add each configuration as a row\n    rows = []\n    for configuration in obj.configurations:\n        index_of_configuration = obj.configurations[configuration]\n        posterior = obj.posterior[index_of_configuration]\n        prior = np.exp(obj.log_prior[index_of_configuration])\n        logBF = obj.log_BF[index_of_configuration]\n        snps = ';'.join([obj.labels[position] for position in configuration])\n        rows.append([snps, prior, logBF, posterior])\n    df = pd.DataFrame(rows, columns=[\"snps\", \"prior\", \"logBF\", \"posterior\"])\n    df = df.sort_values(\"posterior\", ascending=False)\n\n    return df\n\ndef save_object(obj, filename):\n    \"\"\" Write object as a pickle\n    Args:\n        obj: any object\n        filename: output file\n    \"\"\"\n    with open(filename, 'wb') as output:\n        pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)\n    return 0\n\ndef harmonise_z_covmat(z, cov, z_efal, cov_efal):\n    \"\"\" Harmonise z-scores and covariance matrix. This includes:\n        1. Take intersection of rsids between the two\n        2. sort into the same orders\n        3. if effect alleles are not the same, flip in the cov matrix\n    Args:\n        z (Series)\n        cov (Dataframe)\n        z_efal (Series)\n        cov_efal (Series)\n    Returns:\n        z (Series), cov (Dataframe)\n    \"\"\"\n    intersect = z.index[z.index.isin(cov.index)]\n    z = z.loc[intersect]\n    cov = cov.loc[intersect, intersect]\n\n    # Make harmonisation vector to flip cov if effect alleles don't match\n    vec = [1 if z_efal[snp] == cov_efal[snp] else -1 for snp in intersect]\n    vec = pd.Series(vec, index=intersect)\n\n    # Multiply the cov matrix by the harmonisation vector across both axes\n    cov = cov.multiply(vec, axis=0)\n    cov = cov.multiply(vec, axis=1)\n\n    return z, cov\n\ndef parse_cov_matrix(in_cov, in_meta):\n    \"\"\" Parses ldstore cov matrix and associated meta data file\n    Args:\n        in_cov (str): file containing matrix of correlations\n        in_meta (str): file containing variant meta-data\n    Returns:\n        cov matrix (dataframe), effect alleles (dict)\n    \"\"\"\n    cov = pd.read_csv(in_cov, sep=\" \", header=None)\n    meta = pd.read_csv(in_meta, sep=\" \", header=0)\n    cov.index = meta.RSID\n    meta.index = meta.RSID\n    cov.columns = meta.RSID\n\n    # Remove duplicates\n    isdupe = meta.index.duplicated()\n    cov = cov.loc[~isdupe, ~isdupe]\n    meta = meta[~isdupe]\n\n    return cov, meta[\"A_allele\"].to_dict()\n\ndef parse_sumstats(inf, chrom, start, end, rsid_col, chrom_col, pos_col,\n                   beta_col, se_col, effal_col, n_col, sep):\n    \"\"\" Parse a summary stat file and return zscores\n    Args:\n        inf (str):   input summary stat file\n        chrom (str): chrom to extract\n        start (int): position to extract from\n        end (int):   position to extract to\n        ...column names\n    Returns:\n        zscores (Series), effect alleles (dict), n (int)\n    \"\"\"\n    # Load iteratively\n    iter_csv = pd.read_csv(inf, sep=sep, header=0, iterator=True,\n               chunksize=100000)\n    iter_chunks = []\n    for chunk in iter_csv:\n        chunk[chrom_col] = chunk[chrom_col].astype(str)\n        iter_chunks.append(chunk[((chunk[chrom_col] == chrom) &\n                               (chunk[pos_col] >= start) &\n                               (chunk[pos_col] <= end))])\n    df = pd.concat(iter_chunks)\n    # df.to_csv(\"temp/test_sumstat_slice.tsv\", index=None, sep=\"\\t\") # DEBUG\n\n    # Only keep rows with a valid rsid\n    df = df[df[rsid_col].str.startswith(\"rs\")]\n    df.index = df[rsid_col]\n\n    # Remove duplicates\n    df = df.loc[~df.index.duplicated(), :]\n\n    # Calculate z-scores\n    zscores = df[beta_col] / df[se_col]\n\n    # Get mean N\n    n_mean = int(np.mean(df[n_col]))\n\n    return zscores, df[effal_col].to_dict(), n_mean\n\ndef parse_range(range_str):\n    \"\"\" Parse the chrom, start and end from the range string\n    Args:\n        range_str (str): In format chrom:start-end\n    Returns:\n        chrom (str), start (int), end (int)\n    \"\"\"\n    chrom, start_end = range_str.split(\":\")\n    start, end = start_end.split(\"-\")\n    return str(chrom), int(start), int(end)\n\ndef parse_args():\n    \"\"\" Load command line args.\n    \"\"\"\n    parser = argparse.ArgumentParser()\n    # Input args\n    parser.add_argument('--left_sumstats', metavar=\"<file>\", help=('Summary statistics file'), type=str, required=True)\n    parser.add_argument('--left_cov', metavar=\"<file>\", help=(\"Covariance matrix - correlation structure between variants\"), type=str, required=True)\n    parser.add_argument('--left_covmeta', metavar=\"<file>\", help=(\"Covariance matrix SNP info (from LDstore)\"), type=str, required=True)\n    parser.add_argument('--range', metavar=\"<str>\", help=(\"Genomic range in format chrom:start-end\"), type=str, required=True)\n    parser.add_argument('--right_sumstats', metavar=\"<file>\", help=('(Optional) Summary statistics file'), type=str, required=False)\n    parser.add_argument('--right_cov', metavar=\"<file>\", help=(\"Covariance matrix - leave blank if same as left_cov\"), type=str, required=False)\n    parser.add_argument('--right_covmeta', metavar=\"<file>\", help=(\"Covariance matrix SNP info (from LDstore)\"), type=str, required=False)\n    # Output args\n    parser.add_argument('--outprefix', metavar=\"<str>\", help=(\"Output prefix\"), type=str, required=True)\n    # Finemapping args\n    parser.add_argument('--left_kmax', metavar=\"<int>\", help=('Maximum number of causal variants (default: 5)'), default=5, type=int)\n    parser.add_argument('--left_kstart', metavar=\"<int>\", help=('Full exploration of sets with #kstart causal variants (default: 1)'), default=1, type=int)\n    parser.add_argument('--right_kmax', metavar=\"<int>\", help=('Maximum number of causal variants (default: left_kmax)'), type=int)\n    parser.add_argument('--right_kstart', metavar=\"<int>\", help=('Full exploration of sets with #kstart causal variants (default: left_kstart)'), type=int)\n    parser.add_argument('--v_scale', metavar=\"<float>\", help=('Prior variance of the independence prior (default: 0.0025)'), default=0.0025, type=float)\n    parser.add_argument('--maxiter', metavar=\"<int>\", help=('Max iterations of stochastic search (default: 100000)'), default=100000, type=int)\n    parser.add_argument('--prior', metavar=\"<str>\", help=('Choice of \"independence\" or \"gprior\" (default: independence)'), default=\"independence\", type=str, choices=[\"independence\", \"gprior\"])\n    parser.add_argument('--g', metavar=\"<str>\", help=('g-parameter of the g-prior (default: BRIC). see Mixtures of g Priors for Bayesian Variable Selection Liang et al 2008'), default=\"BRIC\", type=str, choices=[\"BRIC\", \"BIC\", \"RIC\"])\n    # File parsing args\n    parser.add_argument('--sep', metavar=\"<str>\", help=('Column sep (default: tab)'), type=str, default=\"\\t\")\n    parser.add_argument('--left_rsidcol', metavar=\"<str>\", help=('RSID column (default: rsid)'), default=\"rsid\", type=str)\n    parser.add_argument('--left_chromcol', metavar=\"<str>\", help=('Chromosome column (default: chrom)'), default=\"chrom\", type=str)\n    parser.add_argument('--left_poscol', metavar=\"<str>\", help=('Position column (default: pos)'), default=\"pos\", type=str)\n    parser.add_argument('--left_betacol', metavar=\"<str>\", help=('Beta column (default: beta)'), default=\"beta\", type=str)\n    parser.add_argument('--left_secol', metavar=\"<str>\", help=('Standard error column (default: se)'), default=\"se\", type=str)\n    parser.add_argument('--left_effalcol', metavar=\"<str>\", help=('Effect allele column (default: effect_allele)'), default=\"effect_allele\", type=str)\n    parser.add_argument('--left_ncol', metavar=\"<str>\", help=('Sample size column (default: n)'), default=\"n\", type=str)\n    parser.add_argument('--right_rsidcol', metavar=\"<str>\", help=('RSID column (default: left_rsidcol)'), type=str)\n    parser.add_argument('--right_chromcol', metavar=\"<str>\", help=('Chromosome column (default: left_chromcol)'), type=str)\n    parser.add_argument('--right_poscol', metavar=\"<str>\", help=('Position column (default: left_poscol)'), type=str)\n    parser.add_argument('--right_betacol', metavar=\"<str>\", help=('Beta column (default: left_betacol)'), type=str)\n    parser.add_argument('--right_secol', metavar=\"<str>\", help=('Standard error column (default: left_secol)'), type=str)\n    parser.add_argument('--right_effalcol', metavar=\"<str>\", help=('Effect allele columns (default: left_effalcol)'), type=str)\n    parser.add_argument('--right_ncol', metavar=\"<str>\", help=('Sample size column (default: n)'), default=\"n\", type=str)\n\n    args = parser.parse_args()\n\n    # If right argument is not set, set to same as left argument\n    for rarg in [\"right_cov\", \"right_covmeta\", \"right_kmax\", \"right_kstart\",\n                 \"right_rsidcol\", \"right_chromcol\", \"right_poscol\",\n                 \"right_betacol\", \"right_secol\", \"right_effalcol\",\n                 \"right_ncol\"]:\n        if getattr(args, rarg) is None:\n            larg_val = getattr(args, rarg.replace(\"right_\", \"left_\"))\n            setattr(args, rarg, larg_val)\n\n    return args\n\nif __name__ == '__main__':\n\n    main()\n", "meta": {"hexsha": "ecb9f4d36f3e34f3b2330264640f200b63ce2584", "size": 15187, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/vloc.py", "max_stars_repo_name": "edm1/verena_coloc_wrapper", "max_stars_repo_head_hexsha": "060dc05d3ad1231061b8fbaf27fae092fa9f0b69", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/vloc.py", "max_issues_repo_name": "edm1/verena_coloc_wrapper", "max_issues_repo_head_hexsha": "060dc05d3ad1231061b8fbaf27fae092fa9f0b69", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/vloc.py", "max_forks_repo_name": "edm1/verena_coloc_wrapper", "max_forks_repo_head_hexsha": "060dc05d3ad1231061b8fbaf27fae092fa9f0b69", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.5366568915, "max_line_length": 233, "alphanum_fraction": 0.6374530849, "include": true, "reason": "import numpy", "num_tokens": 3637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.36296919173767833, "lm_q1q2_score": 0.1998535104331386}}
{"text": "\nimport numpy as np\n\ndef provide_PSF_2D(x=None,y=None,PSF_version=None):\n    \"\"\" Provides 2D PSF at any position in the detector plane\n        This a version which takes a finite nubmer of pregenerated PSF and \\\n        creates the interpolated version at required position\n        (Future: version which takes interpolated values for Zernike \\\n        coefficients and generates image on the fly?)\n        \n        To be used with the focused data taken on July 25 and 26\n        (e.g., 21400 for HgAr, 21604 for Ne, 21808 for Kr)\n        \n        Example usage: ``provide_PSF_2D(10,2010)'' 10 is x-coordinate,\n        and 2010 is y-coordinate        \n\n    @param[in] x            x-coordinate\n    @param[in] y            y-coordinate\n    @param[in] PSF_version  version of the PSF input files\n    @returns                numpy array, 100x100, oversampled 5 times, \n                            corresponding to 20x20 physical pixels\n                            (300x300 microns)\n    \"\"\"    \n    \n    # on tiger the directory contaning array of PSFs is at:\n    DATA_DIRECTORY='/tigress/ncaplar/PIPE2D-450/'\n    \n    if PSF_version is None:\n        PSF_version='Sep12_v1'\n\n    positions_of_simulation=np.load(DATA_DIRECTORY+\\\n                        'positions_of_simulation_00_from_'+PSF_version+'.npy')\n    array_of_simulation=np.load(DATA_DIRECTORY+\\\n                        'array_of_simulation_00_from_'+PSF_version+'.npy')\n    \n    # x and y position with simulated PSFs\n    x_positions_of_simulation=positions_of_simulation[:,1]\n    y_positions_of_simulation=positions_of_simulation[:,2]\n    \n    # This is a simple code that finds the closest avaliable PSFs, given the x and y position\n    # This will have to be improved in order when we get to work with the full populated dectector plane\n    \n    \n    # how far in x-dimension are you willing to search for suitable simulated PSFs\n    x_search_distance=20\n    # positions of all simulated PSFs in that range\n    positions_of_simulation_in_acceptable_x_range=\\\n    positions_of_simulation[(x_positions_of_simulation<(x+x_search_distance))\\\n                            &(x_positions_of_simulation>(x-x_search_distance))]\n    \n    # if there are no simulated PSF avaliable in the specified x-range we are not able to provide the solution\n    if len(positions_of_simulation_in_acceptable_x_range)<2:\n        print('No simulated PSFs are avaliable in this x-area of the detector,')\n        print('probably because this fiber has not been illuminated;')\n        print('returning the closest avaliable PSFs, BUT that is probably not what you want')\n        distances=np.sqrt(((x-x_positions_of_simulation)**2+\\\n                           (y-y_positions_of_simulation)**2).astype(float))\n        index_of_closest_distance=np.where(distances[distances==\\\n                                                     np.min(distances)])[0][0]\n        return array_of_simulation[index_of_closest_distance]\n    \n    # y-distance from the requested positions for all of the suitable simulated PSFs\n    distances_of_y_requested_position_from_avaliable=\\\n    y-positions_of_simulation_in_acceptable_x_range[:,2]\n    # out of the suitable PSFs which 2 are the closest\n    index_of_1st_closest_simulated_psf=\\\n    np.where(np.abs(distances_of_y_requested_position_from_avaliable)==\\\n             np.sort(np.abs(distances_of_y_requested_position_from_avaliable))[0])[0][0]\n    index_of_2nd_closest_simulated_psf=\\\n    np.where(np.abs(distances_of_y_requested_position_from_avaliable)==\\\n             np.sort(np.abs(distances_of_y_requested_position_from_avaliable))[1])[0][0]\n    # where are these 2 closest PSF in the initial table\n    index_of_1st_closest_simulated_psf_in_positions_of_simulation=\\\n    np.where(np.sum(positions_of_simulation,axis=1)==\\\n             np.sum(positions_of_simulation_in_acceptable_x_range[index_of_1st_closest_simulated_psf]))[0][0]\n    index_of_2nd_closest_simulated_psf_in_positions_of_simulation=\\\n    np.where(np.sum(positions_of_simulation,axis=1)==\\\n             np.sum(positions_of_simulation_in_acceptable_x_range[index_of_2nd_closest_simulated_psf]))[0][0]\n    # extract the 2 simulated PSFs\n    first_array_simulation=\\\n    array_of_simulation[index_of_1st_closest_simulated_psf_in_positions_of_simulation]\n    second_array_simulation=\\\n    array_of_simulation[index_of_2nd_closest_simulated_psf_in_positions_of_simulation]\n    # distance of each PSF from the proposed position\n    y1_distance=\\\n    y-positions_of_simulation[index_of_1st_closest_simulated_psf_in_positions_of_simulation][2]\n    y2_distance=\\\n    y-positions_of_simulation[index_of_2nd_closest_simulated_psf_in_positions_of_simulation][2]\n    \n    # if you requested psf at the exact position of existing PSF use that one\n    if y1_distance==0:\n        return first_array_simulation\n    else:    \n        # create the predicted PSF as a linear interpolation of these two PSFs\n        predicted_psf=(second_array_simulation-first_array_simulation*(y2_distance/y1_distance))/(1-y2_distance/y1_distance)\n        return predicted_psf\n    ", "meta": {"hexsha": "fef2daf4a0ac0128aa8faa54a5ca0dfef20ab933", "size": 5078, "ext": "py", "lang": "Python", "max_stars_repo_path": "2d_PSF_code/PIPE2D-347/Provide_PSF_2D.py", "max_stars_repo_name": "Subaru-PFS/dev_pfsmodel", "max_stars_repo_head_hexsha": "d01cf03a4c4eaa01ba5a9590ccf17744a33bdb05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2d_PSF_code/PIPE2D-347/Provide_PSF_2D.py", "max_issues_repo_name": "Subaru-PFS/dev_pfsmodel", "max_issues_repo_head_hexsha": "d01cf03a4c4eaa01ba5a9590ccf17744a33bdb05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2d_PSF_code/PIPE2D-347/Provide_PSF_2D.py", "max_forks_repo_name": "Subaru-PFS/dev_pfsmodel", "max_forks_repo_head_hexsha": "d01cf03a4c4eaa01ba5a9590ccf17744a33bdb05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.3505154639, "max_line_length": 124, "alphanum_fraction": 0.7138637259, "include": true, "reason": "import numpy", "num_tokens": 1191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.19969821684043815}}
{"text": "\"\"\"\nClass for calculating IRC using Morokuma Algorithm\n\"\"\"\n\nimport sys\nimport os\nimport psi4\nimport json\nimport numpy as np\n\n\n\ndef JSON2XYZ(input_params):\n    charge = input_params['molecule']['molecular_charge']\n    mult = input_params['molecule']['molecular_multiplicity']\n    geom = ''\n    geom += '\\n%d %d\\n' %(charge, mult)\n    symbols = input_params['molecule']['symbols']\n    geometry = input_params['molecule']['geometry']\n    for i in range(len(symbols)):\n        geom += \"%s  \" %symbols[i]\n        for j in range(3):\n            if(j==2):\n                geom += \"   %f   \\n\" %geometry[(i + 2*i) + j]\n            else:\n                geom += \"   %f   \" %geometry[(i + 2*i) + j]\n    #print(geom)\n    return geom\n    \nclass ToolKit():\n    # Placeholder for Common Data\n    def __init__(self,name):\n        self.natoms=0\n        self.basis = '3-21G'\n        self.method = 'SCF'\n        self.level_of_theory = \"%s/%s\" %(self.method,self.basis)\n        self.alpha=0.1\n        self.basename='.'.join(name.split('.')[:-1])\n        self.out=open(\"%s.log\"%(self.basename),'a',1)\n        self.delta=0.05\n        self.direction=1\n        self.energies=[]\n        self.energy=0.00\n        self.geos=[]\n        self.restart=False\n        self.geometry=[]\n        self.guessfn=''\n        self.damp=0.05\n        self.algorithm=1\n        self.autodamp=False\n        self.prevgrad=0.0\n        self.hessfn=''\n        self.maxdispl=0.01\n        self.mode=4\n        self.dgrad=0.0\n        self.npoints=25\n        self.template=[]\n        self.keywords={}\n        self.tolerance=1.0e-04\n        self.orcacmd='UNDEFINED'\n        self.ReadInput(name)\n        self.ComputeHessian()\n    def printPars(self):\n        stmp=\"  %13s: %s\\n\"\n        ftmp=\"  %13s: %7.4f\\n\"\n        itmp=\"  %13s: %7d\\n\"\n        self.out.write('')\n        self.out.write(itmp%('Algorithm',self.algorithm))\n        self.out.write(itmp%('N. Points',self.npoints))\n        self.out.write(ftmp%('Grad. Tol.',self.tolerance))\n        self.out.write('')\n        self.out.write(stmp%('Hessian',self.hessfn))\n        self.out.write(itmp%('Mode',self.mode))\n        self.out.write(itmp%('Direction',self.direction))\n        self.out.write('')\n        self.out.write(ftmp%('Alpha',self.alpha))\n        self.out.write(ftmp%('Delta',self.delta))\n        self.out.write('')\n        self.out.write(ftmp%('Damp Factor',self.damp))\n        self.out.write(itmp%('Damp Update',self.autodamp))\n        self.out.write('')\n        self.out.write(ftmp%('Max. Displ.',self.maxdispl))\n        self.out.write('')\n        self.out.write(stmp%('Guess',self.guessfn))\n        self.out.write(\"\\n------------------------------------------------\\n\")\n    def ReadInput(self,json_input):\n        # Read in input from JSON input file\n        json_data=open(json_input).read()\n        input_params = json.loads(json_data)\n        if input_params['molecule']['geometry']:\n            self.geometry = JSON2XYZ(input_params)\n        if input_params['model']['basis']:\n            self.basis = input_params['model']['basis']\n            self.level_of_theory = \"%s/%s\" %(self.method,self.basis)\n            #print(\"IN HERE\")\n        if input_params['model']['method']:\n            self.method = input_params['model']['method']\n            self.level_of_theory = \"%s/%s\" %(self.method,self.basis)\n        if input_params['molecule']['symbols']: \n            self.natoms = len(input_params['molecule']['symbols'])\n        if input_params['keywords']:\n            self.keywords = input_params['keywords']\n        if \"irc\" in input_params:\n            if input_params['irc']['hessfile']:\n                self.hessfn = input_params['irc']['hessfile']\n            if input_params['irc']['guess']:\n                self.guessfn = input_params['irc']['guess']\n            if input_params['irc']['alpha']:\n                self.alpha = input_params['irc']['alpha']\n            if input_params['irc']['delta']:\n                self.delta = input_params['irc']['delta']\n            if input_params['irc']['damp']:\n                self.damp = input_params['irc']['damp']\n            if input_params['irc']['restart']:\n                if(input_params['irc']['restart']==1):\n                    self.restart = True\n                else:\n                    self.restart = False\n            if input_params['irc']['autodamp']:\n                if(input_params['irc']['autodamp']==1):\n                    self.autodamp=True\n                else:\n                    self.autodamp=False\n            if input_params['irc']['tol']:\n                self.tolerance= input_params['irc']['tol']\n            if input_params['irc']['alg']:\n                self.algorithm = input_params['irc']['alg']\n            if input_params['irc']['dir']:\n                self.direction = input_params['irc']['dir']\n            if input_params['irc']['mode']:\n                self.mode = input_params['irc']['mode']\n            if input_params['irc']['maxd']:\n                self.maxdispl = input_params['irc']['maxd']\n            if input_params['irc']['pts']:\n                self.npoints = input_params['irc']['pts']\n        else: \n            pass\n   # def JSON2XYZ(self, input_params):\n   #     geom = ''\n   #     geom += '%d ' %input_params['molecule']['molecular_charge']\n   #     geom += '%d \\n' %input_params['molecule']['molecular_multiplicity'] \n   #     symbols = input_params['molecule']['symbols']\n   #     geometry = input_params['molecule']['geometry']\n   #     for i in range(len(symbols)):\n   #         geom += \"%s  \" %symbols[i]\n   #         for j in range(3):\n   #             if(j==2):\n   #                 geom += \"   %f   \\n\" %geometry[(i + 2*i) + j]\n   #             else:\n   #                 geom += \"   %f   \" %geometry[(i + 2*i) + j]\n   #     self.geom = geom\t\n\n    def ComputeHessian(self):\n        # Use PSI4 to calculate Hessian matrix\n        psi4.core.set_output_file(\"hessian.out\", False)\n        psi4.geometry(self.geometry)\n        #print(self.keywords)\n        psi4.set_options(self.keywords)\n        H = psi4.hessian(self.method)\n        Hess = np.array(H)\n        print(Hess.shape)\n        self.displacement = Hess[:,self.mode]\n        print(self.displacement.shape)\n        self.grad = np.zeros(3*self.natoms) \n\n\n##########################\n# Energies and Gradients #\n##########################\n\ndef doEnergy(geom,pars):\n    psi4.geometry(geom)\n    E = psi4.energy(pars.level_of_theory)\n    return E\n\ndef doGrad(geom,pars):\n    psi4.geometry(geom)\n    Grad, wfn = psi4.gradient(pars.level_of_theory, return_wfn=True)\n    e = wfn.energy()\n    G = np.array(Grad)\n    print(G.shape)\n    pars.grad = G\n    return G, e\n\n\n######################################\n# Geometry manipulation and printing #\n######################################\n\ndef geodisplace(geom, displace):\n    new_geom = []\n    displaced_geom = ''\n    symbols = []\n    #print(geom)\n    lines = geom.split('\\n')\n    lines.pop(0)\n    del lines[-1]\n    charge_mult_line = lines[0].split() #Extract the Charge and Multiplicity from top of string\n    charge = int(charge_mult_line[0])\n    mult = int(charge_mult_line[1])\n    for line in lines[1:]: # Loop Over lines that actually contain atoms\n        atom_line = line.split()\n        #print(atom_line)\n        symbols.append(atom_line[0])\n        atom_line.pop(0) # Get rid of atom symbol temporarily\n        new_geom.append(list(map(float,atom_line)))\n    i=0\n    for atom in new_geom:\n        atom[0] += displace[i]\n        atom[1] += displace[i+1]\n        atom[2] += displace[i+2]\n        i += 3\n#TODO (12/15/18) Finish this, all we have to do is transform the geometry from a list to a\n#string like the geometry given as an input to this function.\n    displaced_geom += \"\\n%d %d\\n\" %(charge, mult)\n    for i in range(len(symbols)):\n        displaced_geom += \"%s  \" %symbols[i]\n        for j in range(3):\n            if(j==2):\n                #displaced_geom += \"   %f   \\n\" %new_geom[(i + 2*i) + j]\n                displaced_geom += \"   %f   \\n\" %new_geom[i][j]\n            else:\n                #displaced_geom += \"   %f   \" %new_geom[(i + 2*i) + j]\n                displaced_geom += \"   %f   \" %new_geom[i][j]\n    print(displaced_geom)\n    return displaced_geom\n\ndef printTrj(params, n):\n    trajectory_file = open(params.basename+'.trj', 'a')\n    trajectory_file.write(\"%d\\npyREX IRC point %d E=%14.7f\\n\"%(params.natoms,n,params.energy))\n    trajectory_file.write(\"%s\\n\" %params.geometry)\n    trajectory_file.close()\n\n###############\n#IRC Functions#\n###############\n\ndef Morokuma(pars,start=False):\n    #Does a cycle in the Morokuma algorithm, returns the energy and MaxGrad of the\n    # new point\n    if (start):\n        #apply the appropriate sign to the displacement and convert to angs.\n        pars.displacement=float(pars.direction)*pars.displacement\n        #for i in range(len(pars.mass)):\n        #   pars.displacement[(3*i)] /= np.sqrt(pars.mass[i])\n        #   pars.displacement[(3*i)+1] /= np.sqrt(pars.mass[i])\n        #   pars.displacement[(3*i)+2] /= np.sqrt(pars.mass[i])\n        pars.displacement=pars.alpha*(pars.displacement/np.linalg.norm(pars.displacement))\n        #Eo,MGo = doGrad(pars.geometry, pars)\n        #tmpvec0=pars.grad\n        #displace geometry following the normal mode\n        geo1=geodisplace(pars.geometry,pars.displacement)\n        E1,MG1=doGrad(geo1,pars)\n        #generate vector D, adapting from eq 6 in J. Chem. Phys. 66, 2153\n        tmpvec1=pars.grad\n        D=-(tmpvec0/np.linalg.norm(tmpvec0))+(tmpvec1/np.linalg.norm(tmpvec1))\n        #D=(pars.displacement/np.linalg.norm(pars.displacement))-(tmpvec/np.linalg.norm(tmpvec))\n    else:\n        #scale down gradients and calculate the displacement\n        pars.displacement=(pars.damp*pars.displacement)-((1.0-pars.damp)*pars.grad)\n        for i in range(len(pars.mass)):\n            pars.displacement[(3*i)] /= np.sqrt(pars.mass[i])\n            pars.displacement[(3*i)+1] /= np.sqrt(pars.mass[i])\n            pars.displacement[(3*i)+2] /= np.sqrt(pars.mass[i])\n        pars.displacement=pars.maxdispl*(pars.displacement/np.linalg.norm(pars.displacement))\n        #displace geometry following the gradient\n        geo1=geodisplace(pars.geometry,pars.displacement)\n        E1,MG1=doGrad(geo1,pars)\n        #generate vector D, adapting from eq 6 in J. Chem. Phys. 66, 2153\n        tmpvec=pars.grad\n        D=(pars.displacement/np.linalg.norm(pars.displacement))-(tmpvec/np.linalg.norm(tmpvec))\n    # find the optimum delta that will assure the new point is at the\n    # local minimum\n    if (pars.algorithm==1):\n        geo2=geodisplace(geo1,pars.delta*D)\n        E2=doEnergy(geo2,pars)\n        if (E2>E1):\n            newdelta=0.5*pars.delta\n        else:\n            newdelta=2.0*pars.delta\n        geo3=geodisplace(geo1,newdelta*D)\n        E3=doEnergy(geo3,pars)\n        Evals=np.array([E1, E2, E3])\n        Deltavals=np.array([0.0,pars.delta,newdelta])\n    else:\n        geo2=geodisplace(geo1,pars.delta*D)\n        E2=doEnergy(geo2,pars)\n        delta3=0.5*pars.delta\n        geo3=geodisplace(geo1,delta3*D)\n        E3=doEnergy(geo3,pars)\n        delta4=2.0*pars.delta\n        geo4=geodisplace(geo1,delta4*D)\n        E4=doEnergy(geo4,pars)\n        delta5=-0.5*pars.delta\n        geo5=geodisplace(geo1,delta5*D)\n        E5=doEnergy(geo5,pars)\n        Evals=np.array([E1, E2, E3, E4, E5])\n        Deltavals=np.array([0.0,pars.delta,delta3, delta4, delta5])\n    deltaFit=np.polyfit(Deltavals,Evals,deg=2)\n    opdelta=-(deltaFit[1]/(2.0*deltaFit[0]))\n    # update the geometry to the new point, update and return energy and gradients\n    pars.geos.append(pars.geometry)\n    pars.energies.append(pars.energy)\n    pars.geometry=geodisplace(geo1,opdelta*D)\n    newE, newMaxGrad = doGrad(pars.geometry,pars)\n    pars.energy=newE\n    #the following line is just for debugging purposes\n    #print(Evals, Deltavals,np.linalg.norm(pars.displacement), opdelta)\n    return (newE, newMaxGrad)\n\ndef ircdrv(inpname):\n    params=ToolKit(inpname)\n    params.out.write(\"\"\"   IRC wrapper for Orca - version 2.0\n   by Filipe Teixeira,\n   REQUIMTE\n   Faculdade de Ciencias da Universidade do Porto\n\n  Using Orca from: %s\n\n  Parameters for this run: \\n\"\"\"%(params.orcacmd))\n    params.printPars()\n    #print(params.geometry)\n    keep=True\n    n=0\n    oldE=0.0\n    params.out.write(\"   Pt. %20s %9s %10s\\n\"%('Energy','RMS Grad.','Damp'))\n    params.out.write(\"------------------------------------------------\\n\")\n    while (keep):\n        if (params.restart or (n>0)):\n            E,MG=Morokuma(params,False)\n        else:\n            E,MG=Morokuma(params,True)\n        n=n+1\n        if(params.autodamp and (n>1)):\n            params.damp = params.damp * (0.1/np.log(n))\n            if (params.damp<1.0e-5):\n                params.damp=0.0\n                params.autodamp=False\n        params.out.write('@  %3d %20.9f %9.5f %10.2e\\n'%(n, E, MG, params.damp))\n        if (n>params.npoints):\n            keep=False\n            printTrj(params,n) #appends newGeo\n            params.out.write(\"----------------------------------------------\\n\")\n            params.out.write(\"--          IRC CALCULATION ENDED           --\\n\")\n            params.out.write(\"--             MAXPTS ACHIEVED!             --\\n\")\n            params.out.write(\"----------------------------------------------\\n\")\n        elif (MG<params.tolerance):\n            keep=False\n            printTrj(params,n) #appends newGeo\n            params.out.write(\"----------------------------------------------\\n\")\n            params.out.write(\"--          IRC CALCULATION ENDED           --\\n\")\n            params.out.write(\"--              TOL ACHIEVED!               --\\n\")\n            params.out.write(\"----------------------------------------------\\n\")\n        elif (E>oldE):\n            keep=False\n            #printTrj(params,n) #appends newGeo\n            params.out.write(\"----------------------------------------------\\n\")\n            params.out.write(\"--             ENERGY INCREASED             --\\n\")\n            params.out.write(\"--            GEOMETRY  MIGHT BE            --\\n\")\n            params.out.write(\"--          VERY CLOSE TO A MINIMUM         --\\n\")\n            params.out.write(\"--                                          --\\n\")\n            params.out.write(\"--        IRC CALCULATION TERMINATED!       --\\n\")\n            params.out.write(\"----------------------------------------------\\n\")\n        else:\n            printTrj(params,n) #appends newGeo\n            oldE=E\n    params.out.close()\n\nif __name__=='__main__':\n    if(len(sys.argv)!=2):\n        print(\"\"\"IRC4Orca - Version 2.0\nAn Implementation of Morokuma's IRC method for the Orca ESS Software.\nby Filipe Teixeira\n\nUsage: %s file.inp\n\nPlease consult https://github.com/teixeirafilipe/irc4orca for more information.\n\n\"\"\"%(sys.argv[0]))\n        sys.exit(1)\n    ircdrv(sys.argv[1])\n \n", "meta": {"hexsha": "4c548a5461bcdd69651eb0c5fd39c4c5a7a12f9a", "size": 14832, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyrex/irc_class.py", "max_stars_repo_name": "derricottegroup/pyrex", "max_stars_repo_head_hexsha": "edc3b2bd73314b87212d9d4069c0b511f7cfb021", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-11-21T14:42:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-23T03:06:50.000Z", "max_issues_repo_path": "pyrex/irc_class.py", "max_issues_repo_name": "derricottegroup/pyrex", "max_issues_repo_head_hexsha": "edc3b2bd73314b87212d9d4069c0b511f7cfb021", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-11-26T11:19:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-31T13:11:30.000Z", "max_forks_repo_path": "pyrex/irc_class.py", "max_forks_repo_name": "WDerricotte/pyrex", "max_forks_repo_head_hexsha": "edc3b2bd73314b87212d9d4069c0b511f7cfb021", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-04T12:22:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-04T12:22:21.000Z", "avg_line_length": 38.725848564, "max_line_length": 96, "alphanum_fraction": 0.5453748652, "include": true, "reason": "import numpy", "num_tokens": 3853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.19958119293562745}}
{"text": "import numbers\nimport logging\nfrom copy import deepcopy\nfrom collections import Counter\n\nimport scipy.stats\nimport kappy\nimport itertools\nimport numpy as np\nimport networkx as nx\nfrom pysb import WILD, export, Observable, ComponentSet, Annotation\nfrom pysb.core import as_complex_pattern, ComponentDuplicateNameError\nfrom pysb.pattern import RulePatternMatcher\nfrom indra.explanation.reporting import stmt_from_rule, agent_from_obs\nfrom indra.statements import *\nfrom indra.assemblers.pysb import assembler as pa\nfrom indra.assemblers.pysb.kappa_util import im_json_to_graph\nfrom indra.statements.agent import default_ns_order\nfrom indra.ontology.bio import bio_ontology\n\nfrom . import ModelChecker, PathResult, NodesContainer\nfrom .model_checker import signed_edges_to_signed_nodes\n\nlogger = logging.getLogger(__name__)\n\ntry:\n    import paths_graph as pg\n    has_pg = True\nexcept ImportError:\n    pg = None\n    has_pg = False\n    logger.warning('PathsGraph is not available')\n\n\nclass PysbModelChecker(ModelChecker):\n    \"\"\"Check a PySB model against a set of INDRA statements.\n\n    Parameters\n    ----------\n    model : pysb.Model\n        A PySB model to check.\n    statements : Optional[list[indra.statements.Statement]]\n        A list of INDRA Statements to check the model against.\n    agent_obs: Optional[list[indra.statements.Agent]]\n        A list of INDRA Agents in a given state to be observed.\n    do_sampling : bool\n        Whether to use breadth-first search or weighted sampling to\n        generate paths. Default is False (breadth-first search).\n    seed : int\n        Random seed for sampling (optional, default is None).\n    model_stmts : list[indra.statements.Statement]\n        A list of INDRA statements used to assemble PySB model.\n    nodes_to_agents : dict\n        A dictionary mapping nodes of intermediate signed edges graph to INDRA\n        agents.\n\n    Attributes\n    ----------\n    graph : nx.Digraph\n        A DiGraph with signed nodes to find paths in.\n    \"\"\"\n\n    def __init__(self, model, statements=None, agent_obs=None,\n                 do_sampling=False, seed=None, model_stmts=None,\n                 nodes_to_agents=None):\n        super().__init__(model, statements, do_sampling, seed, nodes_to_agents)\n        if agent_obs:\n            self.agent_obs = agent_obs\n        else:\n            self.agent_obs = []\n        mps_to_agents, rules_to_mps = pa.get_grounded_agents(model)\n        self.mps_to_agents = mps_to_agents\n        self.rules_to_mps = rules_to_mps\n        self.model_agents = self.get_model_agents()\n        self.model_stmts = model_stmts if model_stmts else []\n        # Influence map\n        self._im = None\n        # Map from statements to associated observables\n        self.stmt_to_obs = {}\n        # Map from agents to associated observables\n        self.agent_to_obs = {}\n        # Map between rules and downstream observables\n        self.rule_obs_dict = {}\n        # Map from observables to agents\n        self.obs_to_agents = {}\n\n    def generate_im(self, model):\n        \"\"\"Return a graph representing the influence map generated by Kappa\n\n        Parameters\n        ----------\n        model : pysb.Model\n            The PySB model whose influence map is to be generated\n\n        Returns\n        -------\n        graph : networkx.MultiDiGraph\n            A MultiDiGraph representing the influence map\n        \"\"\"\n        kappa = kappy.KappaStd()\n        model_str = export.export(model, 'kappa')\n        kappa.add_model_string(model_str)\n        kappa.project_parse()\n        imap = kappa.analyses_influence_map(accuracy='medium')\n        graph = im_json_to_graph(imap)\n        return graph\n\n    def draw_im(self, fname):\n        \"\"\"Draw and save the influence map in a file.\n\n        Parameters\n        ----------\n        fname : str\n            The name of the file to save the influence map in.\n            The extension of the file will determine the file format,\n            typically png or pdf.\n        \"\"\"\n        im = self.get_im()\n        im_agraph = nx.nx_agraph.to_agraph(im)\n        im_agraph.draw(fname, prog='dot')\n\n    def get_im(self, force_update=False):\n        \"\"\"Get the influence map for the model, generating it if necessary.\n\n        Parameters\n        ----------\n        force_update : bool\n            Whether to generate the influence map when the function is called.\n            If False, returns the previously generated influence map if\n            available. Defaults to True.\n\n        Returns\n        -------\n        networkx MultiDiGraph object containing the influence map.\n            The influence map can be rendered as a pdf using the dot layout\n            program as follows::\n\n                im_agraph = nx.nx_agraph.to_agraph(influence_map)\n                im_agraph.draw('influence_map.pdf', prog='dot')\n        \"\"\"\n        if self._im and not force_update:\n            return self._im\n        if not self.model:\n            raise Exception(\"Cannot get influence map if there is no model.\")\n\n        def add_obs_for_agents(main_agent, ref_agents=None):\n            if ref_agents:\n                all_agents = [main_agent] + ref_agents\n            else:\n                all_agents = [main_agent]\n            ag_to_obj_mps = self.get_all_mps(all_agents, mapping=True)\n            if all([not v for v in ag_to_obj_mps.values()]):\n                logger.debug('No monomer patterns found in model for agents %s'\n                             ', skipping' % all_agents)\n                return\n            obs_nodes = NodesContainer(main_agent, ref_agents)\n            main_obs_set = set()\n            ref_obs_set = set()\n            for agent in ag_to_obj_mps:\n                for obj_mp in ag_to_obj_mps[agent]:\n                    obs_name = _monomer_pattern_label(obj_mp) + '_obs'\n                    self.obs_to_agents[obs_name] = agent\n                    # Add the observable\n                    obj_obs = Observable(obs_name, obj_mp, _export=False)\n                    if agent.matches(main_agent):\n                        main_obs_set.add(obs_name)\n                    else:\n                        ref_obs_set.add(obs_name)\n                    try:\n                        self.model.add_component(obj_obs)\n                        self.model.add_annotation(\n                            Annotation(obs_name, agent.name,\n                                       'from_indra_agent'))\n                    except ComponentDuplicateNameError as e:\n                        pass\n            obs_nodes.main_interm = main_obs_set\n            obs_nodes.ref_interm = ref_obs_set\n            return obs_nodes\n\n        # Create observables for all statements to check, and add to model\n        # Remove any existing observables in the model\n        self.model.observables = ComponentSet([])\n        for stmt in self.statements:\n            # Generate observables for Modification statements\n            if isinstance(stmt, Modification) or \\\n               isinstance(stmt, SelfModification):\n                # If the statement is a regular Mod, the target is stmt.sub\n                if isinstance(stmt, Modification):\n                    sub = stmt.sub\n                # If it's a SelfMod, the target is stmt.enz\n                elif isinstance(stmt, SelfModification):\n                    sub = stmt.enz\n                # Add the mod for the agent\n                if sub is None:\n                    self.stmt_to_obs[stmt] = NodesContainer(None)\n                else:\n                    mod_condition_name = modclass_to_modtype[stmt.__class__]\n                    if isinstance(stmt, RemoveModification):\n                        mod_condition_name = modtype_to_inverse[\n                            mod_condition_name]\n                    # Add modification to substrate agent\n                    modified_sub = _add_modification_to_agent(\n                            sub, mod_condition_name, stmt.residue,\n                            stmt.position)\n                    # Get all refinements of substrate agent\n                    ref_subs = self.get_refinements(modified_sub)\n                    obs_nodes = add_obs_for_agents(modified_sub, ref_subs)\n                    # Associate this statement with this observable\n                    self.stmt_to_obs[stmt] = obs_nodes\n            # Generate observables for Activation/Inhibition statements\n            elif isinstance(stmt, RegulateActivity):\n                if stmt.obj is None:\n                    self.stmt_to_obs[stmt] = NodesContainer(None)\n                else:\n                    # Add activity to object agent\n                    regulated_obj = _add_activity_to_agent(\n                        stmt.obj, stmt.obj_activity, stmt.is_activation)\n                    # Get all refinements of object agent\n                    ref_objs = self.get_refinements(stmt.obj)\n                    obs_nodes = add_obs_for_agents(regulated_obj, ref_objs)\n                    # Associate this statement with this observable\n                    self.stmt_to_obs[stmt] = obs_nodes\n            elif isinstance(stmt, RegulateAmount):\n                if stmt.obj is None:\n                    self.stmt_to_obs[stmt] = NodesContainer(None)\n                else:\n                    # Get all refinements of object agent\n                    ref_objs = self.get_refinements(stmt.obj)\n                    obs_nodes = add_obs_for_agents(stmt.obj, ref_objs)\n                    self.stmt_to_obs[stmt] = obs_nodes\n            elif isinstance(stmt, Influence):\n                if stmt.obj is None:\n                    self.stmt_to_obs[stmt] = NodesContainer(None)\n                else:\n                    # Get all refinements of object agent\n                    ref_objs = self.get_refinements(stmt.obj)\n                    concepts = [obj.concept for obj in ref_objs]\n                    obs_nodes = add_obs_for_agents(stmt.obj.concept, concepts)\n                    self.stmt_to_obs[stmt] = obs_nodes\n        # Add observables for each agent\n        for ag in self.agent_obs:\n            obs_nodes = add_obs_for_agents(ag)\n            self.agent_to_obs[ag] = obs_nodes\n\n        logger.info(\"Generating influence map\")\n        self._im = self.generate_im(self.model)\n        # self._im.is_multigraph = lambda: False\n        # Now, for every rule in the model, check if there are any observables\n        # downstream; alternatively, for every observable in the model, get a\n        # list of rules.\n        # We'll need the dictionary to check if nodes are observables\n        node_attributes = nx.get_node_attributes(self._im, 'node_type')\n        for rule in self.model.rules:\n            obs_list = []\n            # Get successors of the rule node\n            for neighb in self._im.neighbors(rule.name):\n                # Check if the node is an observable\n                if node_attributes[neighb] != 'variable':\n                    continue\n                # Get the edge and check the polarity\n                edge_sign = _get_edge_sign(self._im, (rule.name, neighb))\n                obs_list.append((neighb, edge_sign))\n            self.rule_obs_dict[rule.name] = obs_list\n        return self._im\n\n    def get_graph(self, prune_im=True, prune_im_degrade=True,\n                  prune_im_subj_obj=False, add_namespaces=False,\n                  edge_filter_func=None):\n        \"\"\"Get influence map and convert it to a graph with signed nodes.\"\"\"\n        if self.graph:\n            return self.graph\n        # NOTE edge_filter_func is not currently used in PySB\n        im = self.get_im(force_update=True)\n        if prune_im:\n            self.prune_influence_map()\n        if prune_im_degrade:\n            self.prune_influence_map_degrade_bind_positive(self.model_stmts)\n        if prune_im_subj_obj:\n            self.prune_influence_map_subj_obj()\n        self.get_nodes_to_agents(add_namespaces=add_namespaces)\n        self.graph = signed_edges_to_signed_nodes(\n            im, prune_nodes=False, edge_signs={'pos': 1, 'neg': -1})\n        return self.graph\n\n    def get_nodes_to_agents(self, add_namespaces=False):\n        \"\"\"Return a dictionary mapping influence map nodes to INDRA agents.\n\n        Parameters\n        ----------\n        add_namespaces : bool\n            Whether to propagate namespaces to node data. Default: False.\n\n        Returns\n        -------\n        nodes_to_agents : dict\n            A dictionary mapping influence map nodes to INDRA agents.\n        \"\"\"\n        if self.nodes_to_agents:\n            return self.nodes_to_agents\n\n        logger.info('Mapping nodes to agents')\n        im = self.get_im()\n        nodes_to_agents = {}\n\n        # First map rules to their subject agents\n        for rule, mps in self.rules_to_mps.items():\n            for mp in mps:\n                for ann in self.model.annotations:\n                    if ann.subject == rule and ann.object == mp.monomer.name:\n                        # We usually want to map rule to subject agent\n                        if ann.predicate == 'rule_has_subject':\n                            nodes_to_agents[rule] = self.mps_to_agents[mp]\n\n        # Add observables to agents stored earlier\n        nodes_to_agents.update(self.obs_to_agents)\n\n        # Optionally propagate namespaces to node data\n        if add_namespaces:\n            logger.info('Adding namespaces to influence map nodes')\n            for n, data in im.nodes(data=True):\n                ag = nodes_to_agents.get(n)\n                if ag:\n                    ns, gr = ag.get_grounding()\n                    data['ns'] = ns\n        self.nodes_to_agents = nodes_to_agents\n\n    def process_statement(self, stmt):\n        self.get_im()\n        # Check if this is one of the statement types that we can check\n        if not isinstance(stmt, (Modification, RegulateAmount,\n                                 RegulateActivity, Influence)):\n            logger.info('Statement type %s not handled' %\n                        stmt.__class__.__name__)\n            return (None, None, 'STATEMENT_TYPE_NOT_HANDLED')\n        # Get the polarity for the statement\n        if isinstance(stmt, Modification):\n            target_polarity = 1 if isinstance(stmt, RemoveModification) else 0\n        elif isinstance(stmt, RegulateActivity):\n            target_polarity = 0 if stmt.is_activation else 1\n        elif isinstance(stmt, RegulateAmount):\n            target_polarity = 1 if isinstance(stmt, DecreaseAmount) else 0\n        elif isinstance(stmt, Influence):\n            target_polarity = 1 if stmt.overall_polarity() == -1 else 0\n        # Get the subject and object (works also for Modifications)\n        subj, obj = stmt.agent_list()\n        # Get a list of monomer patterns matching the subject FIXME Currently\n        # this will match rules with the corresponding monomer pattern on it.\n        # In future, this statement should (possibly) also match rules in which\n        # 1) the agent is in its active form, or 2) the agent is tagged as the\n        # enzyme in a rule of the appropriate activity (e.g., a phosphorylation\n        # rule) FIXME\n        if subj is not None:\n            ref_agents = self.get_refinements(subj)\n            subj_mps = self.get_all_mps([subj], ignore_activities=True)\n            subj_ref_mps = self.get_all_mps(ref_agents, ignore_activities=True)\n            if not subj_mps and not subj_ref_mps:\n                return (None, None, 'SUBJECT_MONOMERS_NOT_FOUND')\n            subj_nodes = NodesContainer(subj, ref_agents)\n            meaningful_res_code = None\n            # Each subject might produce a different input set and we need to\n            # combine them\n            for subj_mp in subj_mps:\n                inp, res_code = self.process_subject(subj_mp)\n                if res_code:\n                    meaningful_res_code = res_code\n                    continue\n                subj_nodes.main_nodes += inp\n            for subj_mp in subj_ref_mps:\n                inp, res_code = self.process_subject(subj_mp)\n                if res_code:\n                    meaningful_res_code = res_code\n                    continue\n                subj_nodes.ref_nodes += inp\n            subj_nodes.get_all_nodes()\n            if not subj_nodes.all_nodes and meaningful_res_code:\n                return (None, None, meaningful_res_code)\n        else:\n            subj_nodes = NodesContainer(None)\n            subj_nodes.all_nodes = None\n        # Observables may not be found for an activation since there may be no\n        # rule in the model activating the object, and the object may not have\n        # an \"active\" site of the appropriate type\n        obs_nodes = self.stmt_to_obs[stmt]\n        if obs_nodes is None:\n            logger.info(\"No observables for stmt %s, returning False\" % stmt)\n            return (None, None, 'OBSERVABLES_NOT_FOUND')\n        # Statement object is None\n        if obs_nodes.main_agent is None:\n            # Cannot check modifications in this case\n            if isinstance(stmt, Modification):\n                return (None, None, 'STATEMENT_TYPE_NOT_HANDLED')\n            obs_nodes.all_nodes = None\n        else:\n            obs_nodes.main_nodes = [\n                (obs, target_polarity) for obs in obs_nodes.main_interm]\n            obs_nodes.ref_nodes = [\n                (obs, target_polarity) for obs in obs_nodes.ref_interm]\n            obs_nodes.get_all_nodes()\n        result_code = None\n        return subj_nodes, obs_nodes, result_code\n\n    def process_subject(self, subj_mp):\n        if subj_mp is None:\n            input_set_signed = None\n        else:\n            input_rule_set = self._get_input_rules(subj_mp)\n            if not input_rule_set:\n                logger.info('Input rules not found for %s' % subj_mp)\n                return (None, 'INPUT_RULES_NOT_FOUND')\n            input_set_signed = {(rule, 0) for rule in input_rule_set}\n        return input_set_signed, None\n\n    def get_model_agents(self):\n        return set(self.mps_to_agents.values())\n\n    def get_refinements(self, agent):\n        \"\"\"Return a list of refinement agents that are part of the model.\"\"\"\n        agents = set()\n        for ag in self.model_agents:\n            if not ag.matches(agent) and ag.refinement_of(agent, bio_ontology):\n                agents.add(ag)\n        return list(agents)\n\n    def get_all_mps(self, agents, ignore_activities=False, mapping=False):\n        \"\"\"Get a list of all monomer patterns for a list of agents.\"\"\"\n        ag_to_mps = {}\n        mps = []\n        for ag in agents:\n            ag_mps = list(pa.grounded_monomer_patterns(\n                self.model, ag, ignore_activities=ignore_activities))\n            if ag_mps:\n                ag_to_mps[ag] = ag_mps\n                mps += ag_mps\n        if mapping:\n            return ag_to_mps\n        return set(mps)\n\n    def _get_input_rules(self, subj_mp):\n        if subj_mp is None:\n            raise ValueError(\"Cannot take None as an argument for subj_mp.\")\n        input_rules = _match_lhs(subj_mp, self.model.rules)\n        logger.debug('Found %s input rules matching %s' %\n                     (len(input_rules), str(subj_mp)))\n        # Filter to include only rules where the subj_mp is actually the\n        # subject (i.e., don't pick up upstream rules where the subject\n        # is itself a substrate/object)\n        # FIXME: Note that this will eliminate rules where the subject\n        # being checked is included on the left hand side as\n        # a bound condition rather than as an enzyme.\n        subj_rules = pa.rules_with_annotation(self.model,\n                                              subj_mp.monomer.name,\n                                              'rule_has_subject')\n        logger.debug('%d rules with %s as subject' %\n                     (len(subj_rules), subj_mp.monomer.name))\n        input_rule_set = set([r.name for r in input_rules]).intersection(\n                             set([r.name for r in subj_rules]))\n        logger.debug('Final input rule set contains %d rules' %\n                     len(input_rule_set))\n        return input_rule_set\n\n    def _sample_paths(self, input_rule_set, obs_name, target_polarity,\n                      max_paths=1, max_path_length=5):\n        if max_paths == 0:\n            raise ValueError(\"max_paths cannot be 0 for path sampling.\")\n        if not has_pg:\n            raise ImportError(\"Paths Graph is not imported\")\n        # Convert path polarity representation from 0/1 to 1/-1\n\n        def convert_polarities(path_list):\n            return [tuple((n[0], 0 if n[1] > 0 else 1) for n in path)\n                    for path in path_list]\n\n        pg_polarity = 0 if target_polarity > 0 else 1\n        nx_graph = self._im_to_signed_digraph(self.get_im())\n        # Add edges from dummy node to input rules\n        source_node = 'SOURCE_NODE'\n        for rule in input_rule_set:\n            nx_graph.add_edge(source_node, rule, sign=0)\n        # -------------------------------------------------\n        # Create combined paths_graph\n        f_level, b_level = pg.get_reachable_sets(nx_graph, source_node,\n                                                 obs_name, max_path_length,\n                                                 signed=True)\n        pg_list = []\n        for path_length in range(1, max_path_length+1):\n            cfpg = pg.CFPG.from_graph(\n                    nx_graph, source_node, obs_name, path_length, f_level,\n                    b_level, signed=True, target_polarity=pg_polarity)\n            pg_list.append(cfpg)\n        combined_pg = pg.CombinedCFPG(pg_list)\n        # Make sure the combined paths graph is not empty\n        if not combined_pg.graph:\n            pr = PathResult(\n                False, 'NO_PATHS_FOUND', max_paths, max_path_length)\n            pr.path_metrics = None\n            pr.paths = []\n            return pr\n\n        # Get a dict of rule objects\n        rule_obj_dict = {}\n        for ann in self.model.annotations:\n            if ann.predicate == 'rule_has_object':\n                rule_obj_dict[ann.subject] = ann.object\n\n        # Get monomer initial conditions\n        ic_dict = {}\n        for mon in self.model.monomers:\n            # FIXME: A hack that depends on the _0 convention\n            ic_name = '%s_0' % mon.name\n            # TODO: Wrap this in try/except?\n            ic_param = self.model.parameters[ic_name]\n            ic_value = ic_param.value\n            ic_dict[mon.name] = ic_value\n\n        # Set weights in PG based on model initial conditions\n        for cur_node in combined_pg.graph.nodes():\n            edge_weights = {}\n            rule_obj_list = []\n            edge_weights_by_gene = {}\n            for u, v in combined_pg.graph.out_edges(cur_node):\n                v_rule = v[1][0]\n                # Get the object of the rule (a monomer name)\n                rule_obj = rule_obj_dict.get(v_rule)\n                if rule_obj:\n                    # Add to list so we can count instances by gene\n                    rule_obj_list.append(rule_obj)\n                    # Get the abundance of rule object from the initial\n                    # conditions\n                    # TODO: Wrap in try/except?\n                    ic_value = ic_dict[rule_obj]\n                else:\n                    ic_value = 1.0\n                edge_weights[(u, v)] = ic_value\n                edge_weights_by_gene[rule_obj] = ic_value\n            # Get frequency of different rule objects\n            rule_obj_ctr = Counter(rule_obj_list)\n            # Normalize results by weight sum and gene frequency at this level\n            edge_weight_sum = sum(edge_weights_by_gene.values())\n            edge_weights_norm = {}\n            for e, v in edge_weights.items():\n                v_rule = e[1][1][0]\n                rule_obj = rule_obj_dict.get(v_rule)\n                if rule_obj:\n                    rule_obj_count = rule_obj_ctr[rule_obj]\n                else:\n                    rule_obj_count = 1\n                edge_weights_norm[e] = ((v / float(edge_weight_sum)) /\n                                        float(rule_obj_count))\n            # Add edge weights to paths graph\n            nx.set_edge_attributes(combined_pg.graph, name='weight',\n                                   values=edge_weights_norm)\n\n        # Sample from the combined CFPG\n        paths = combined_pg.sample_paths(max_paths)\n        # -------------------------------------------------\n        if paths:\n            pr = PathResult(True, 'PATHS_FOUND', max_paths, max_path_length)\n            pr.path_metrics = None\n            # Convert path polarity representation from 0/1 to 1/-1\n            pr.paths = convert_polarities(paths)\n            # Strip off the SOURCE_NODE prefix\n            pr.paths = [p[1:] for p in pr.paths]\n        else:\n            assert False\n            pr = PathResult(\n                False, 'NO_PATHS_FOUND', max_paths, max_path_length)\n            pr.path_metrics = None\n            pr.paths = []\n        return pr\n\n    def score_paths(self, paths, agents_values, loss_of_function=False,\n                    sigma=0.15, include_final_node=False):\n        \"\"\"Return scores associated with a given set of paths.\n\n        Parameters\n        ----------\n        paths : list[list[tuple[str, int]]]\n            A list of paths obtained from path finding. Each path is a list\n            of tuples (which are edges in the path), with the first element\n            of the tuple the name of a rule, and the second element its\n            polarity in the path.\n        agents_values : dict[indra.statements.Agent, float]\n            A dictionary of INDRA Agents and their corresponding measured\n            value in a given experimental condition.\n        loss_of_function : Optional[boolean]\n            If True, flip the polarity of the path. For instance, if the effect\n            of an inhibitory drug is explained, set this to True.\n            Default: False\n        sigma : Optional[float]\n            The estimated standard deviation for the normally distributed\n            measurement error in the observation model used to score paths\n            with respect to data. Default: 0.15\n        include_final_node : Optional[boolean]\n            Determines whether the final node of the path is included in the\n            score. Default: False\n        \"\"\"\n        obs_model = lambda x: scipy.stats.norm(x, sigma)\n        # Build up dict mapping observables to values\n        obs_dict = {}\n        for ag, val in agents_values.items():\n            obs_list = self.agent_to_obs[ag]\n            if obs_list is not None:\n                for obs in obs_list:\n                    obs_dict[obs] = val\n        # For every path...\n        path_scores = []\n        for path in paths:\n            logger.info('------')\n            logger.info(\"Scoring path:\")\n            logger.info(path)\n            # Look at every node in the path, excluding the final\n            # observable...\n            path_score = 0\n            last_path_node_index = -1 if include_final_node else -2\n            for node, sign in path[:last_path_node_index]:\n                # ...and for each node check the sign to see if it matches the\n                # data. So the first thing is to look at what's downstream\n                # of the rule\n                # affected_obs is a list of observable names alogn\n                for affected_obs, rule_obs_sign in self.rule_obs_dict[node]:\n                    flip_polarity = -1 if loss_of_function else 1\n                    pred_sign = sign * rule_obs_sign * flip_polarity\n                    # Check to see if this observable is in the data\n                    logger.info('%s %s: effect %s %s' %\n                                (node, sign, affected_obs, pred_sign))\n                    measured_val = obs_dict.get(affected_obs)\n                    if measured_val:\n                        # For negative predictions use CDF (prob that given\n                        # measured value, true value lies below 0)\n                        if pred_sign <= 0:\n                            prob_correct = obs_model(measured_val).logcdf(0)\n                        # For positive predictions, use log survival function\n                        # (SF = 1 - CDF, i.e., prob that true value is\n                        # above 0)\n                        else:\n                            prob_correct = obs_model(measured_val).logsf(0)\n                        logger.info('Actual: %s, Log Probability: %s' %\n                                    (measured_val, prob_correct))\n                        path_score += prob_correct\n                if not self.rule_obs_dict[node]:\n                    logger.info('%s %s' % (node, sign))\n                    prob_correct = obs_model(0).logcdf(0)\n                    logger.info('Unmeasured node, Log Probability: %s' %\n                                (prob_correct))\n                    path_score += prob_correct\n            # Normalized path\n            # path_score = path_score / len(path)\n            logger.info(\"Path score: %s\" % path_score)\n            path_scores.append(path_score)\n        path_tuples = list(zip(paths, path_scores))\n        # Sort first by path length\n        sorted_by_length = sorted(path_tuples, key=lambda x: len(x[0]))\n        # Sort by probability; sort in reverse order to large values\n        # (higher probabilities) are ranked higher\n        scored_paths = sorted(sorted_by_length, key=lambda x: x[1],\n                              reverse=True)\n        return scored_paths\n\n    def prune_influence_map(self):\n        \"\"\"Remove edges between rules causing problematic non-transitivity.\n\n        First, all self-loops are removed. After this initial step, edges are\n        removed between rules when they share *all* child nodes except for each\n        other; that is, they have a mutual relationship with each other and\n        share all of the same children.\n\n        Note that edges must be removed in batch at the end to prevent edge\n        removal from affecting the lists of rule children during the comparison\n        process.\n        \"\"\"\n        im = self.get_im()\n\n        # First, remove all self-loops\n        logger.info('Removing self loops')\n        edges_to_remove = []\n        for e in im.edges():\n            if e[0] == e[1]:\n                logger.info('Removing self loop: %s', e)\n                edges_to_remove.append((e[0], e[1]))\n        # Now remove all the edges to be removed with a single call\n        im.remove_edges_from(edges_to_remove)\n\n        # Remove parameter nodes from influence map\n        remove_im_params(self.model, im)\n\n        # Now compare nodes pairwise and look for overlap between child nodes\n        logger.info('Get successors of each node')\n        succ_dict = {}\n        for node in im.nodes():\n            succ_dict[node] = set(im.successors(node))\n        # Sort and then group nodes by number of successors\n        logger.info('Compare combinations of successors')\n        group_key_fun = lambda x: len(succ_dict[x])\n        nodes_sorted = sorted(im.nodes(), key=group_key_fun)\n        groups = itertools.groupby(nodes_sorted, key=group_key_fun)\n        # Now iterate over each group and then construct combinations\n        # within the group to check for shared sucessors\n        edges_to_remove = []\n        for gix, group in groups:\n            combos = itertools.combinations(group, 2)\n            for ix, (p1, p2) in enumerate(combos):\n                # Children are identical except for mutual relationship\n                if succ_dict[p1].difference(succ_dict[p2]) == set([p2]) and \\\n                   succ_dict[p2].difference(succ_dict[p1]) == set([p1]):\n                    for u, v in ((p1, p2), (p2, p1)):\n                        edges_to_remove.append((u, v))\n                        logger.debug('Will remove edge (%s, %s)', u, v)\n        logger.info('Removing %d edges from influence map' %\n                    len(edges_to_remove))\n        # Now remove all the edges to be removed with a single call\n        im.remove_edges_from(edges_to_remove)\n\n    def prune_influence_map_subj_obj(self):\n        \"\"\"Prune influence map to include only edges where the object of the\n        upstream rule matches the subject of the downstream rule.\"\"\"\n        def get_rule_info(r):\n            result = {}\n            for ann in self.model.annotations:\n                if ann.subject == r:\n                    if ann.predicate == 'rule_has_subject':\n                        result['subject'] = ann.object\n                    elif ann.predicate == 'rule_has_object':\n                        result['object'] = ann.object\n            return result\n        im = self.get_im()\n        rules = im.nodes()\n        edges_to_prune = []\n        for r1, r2 in itertools.permutations(rules, 2):\n            if (r1, r2) not in im.edges():\n                continue\n            r1_info = get_rule_info(r1)\n            r2_info = get_rule_info(r2)\n            if 'object' not in r1_info or 'subject' not in r2_info:\n                continue\n            if r1_info['object'] != r2_info['subject']:\n                logger.info(\"Removing edge %s --> %s\" % (r1, r2))\n                edges_to_prune.append((r1, r2))\n        logger.info('Removing %d edges from influence map' %\n                    len(edges_to_prune))\n        im.remove_edges_from(edges_to_prune)\n\n    def prune_influence_map_degrade_bind_positive(self, model_stmts):\n        \"\"\"Prune positive edges between X degrading and X forming a\n        complex with Y.\"\"\"\n        im = self.get_im()\n        edges_to_prune = []\n        for r1, r2, data in im.edges(data=True):\n            s1 = stmt_from_rule(r1, self.model, model_stmts)\n            s2 = stmt_from_rule(r2, self.model, model_stmts)\n            # Make sure this is a degradation/binding combo\n            s1_is_degrad = (s1 and isinstance(s1, DecreaseAmount))\n            s2_is_bind = (s2 and isinstance(s2, Complex) and 'bind' in r2)\n            if not s1_is_degrad or not s2_is_bind:\n                continue\n            # Make sure what is degraded is part of the complex\n            if s1.obj.name not in [m.name for m in s2.members]:\n                continue\n            # Make sure we're dealing with a positive influence\n            if data['sign'] == 1:\n                edges_to_prune.append((r1, r2))\n        logger.info('Removing %d edges from influence map' %\n                    len(edges_to_prune))\n        im.remove_edges_from(edges_to_prune)\n\n    def _im_to_signed_digraph(self, im):\n        edges = []\n        for e in im.edges():\n            edge_sign = _get_edge_sign(im, e)\n            polarity = 0 if edge_sign > 0 else 1\n            edges.append((e[0], e[1], {'sign': polarity}))\n        dg = nx.DiGraph()\n        dg.add_edges_from(edges)\n        return dg\n\n\ndef _find_sources_sample(im, target, sources, polarity, rule_obs_dict,\n                         agent_to_obs, agents_values):\n    # Build up dict mapping observables to values\n    obs_dict = {}\n    for ag, val in agents_values.items():\n        obs_list = agent_to_obs[ag]\n        for obs in obs_list:\n            obs_dict[obs] = val\n\n    sigma = 0.2\n\n    def obs_model(x):\n        return scipy.stats.norm(x, sigma)\n\n    def _sample_pred(im, target, rule_obs_dict, obs_model):\n        preds = list(_get_signed_predecessors(im, target, 1))\n        if not preds:\n            return None\n        pred_scores = []\n        for pred, sign in preds:\n            pred_score = 0\n            for affected_obs, rule_obs_sign in rule_obs_dict[pred]:\n                pred_sign = sign * rule_obs_sign\n                # Check to see if this observable is in the data\n                logger.info('%s %s: effect %s %s' %\n                            (pred, sign, affected_obs, pred_sign))\n                measured_val = obs_dict.get(affected_obs)\n                if measured_val:\n                    logger.info('Actual: %s' % measured_val)\n                    # The tail probability of the real value being above 1\n                    tail_prob = obs_model(measured_val).cdf(1)\n                    pred_score += (tail_prob if pred_sign == 1 else\n                                   1-tail_prob)\n            pred_scores.append(pred_score)\n        # Normalize scores\n        pred_scores = np.array(pred_scores) / np.sum(pred_scores)\n        pred_idx = np.random.choice(range(len(preds)), p=pred_scores)\n        pred = preds[pred_idx]\n        return pred\n\n    preds = []\n    for i in range(100):\n        pred = _sample_pred(im, target, rule_obs_dict, obs_model)\n        preds.append(pred[0])\n\n\ndef remove_im_params(model, im):\n    \"\"\"Remove parameter nodes from the influence map.\n\n    Parameters\n    ----------\n    model : pysb.core.Model\n        PySB model.\n    im : networkx.MultiDiGraph\n        Influence map.\n\n    Returns\n    -------\n    networkx.MultiDiGraph\n        Influence map with the parameter nodes removed.\n    \"\"\"\n    for param in model.parameters:\n        # If the node doesn't exist e.g., it may have already been removed),\n        # skip over the parameter without error\n        try:\n            im.remove_node(param.name)\n        except:\n            pass\n\n\ndef _get_signed_predecessors(im, node, polarity):\n    \"\"\"Get upstream nodes in the influence map.\n    Return the upstream nodes along with the overall polarity of the path\n    to that node by account for the polarity of the path to the given node\n    and the polarity of the edge between the given node and its immediate\n    predecessors.\n    Parameters\n    ----------\n    im : networkx.MultiDiGraph\n        Graph containing the influence map.\n    node : str\n        The node (rule name) in the influence map to get predecessors (upstream\n        nodes) for.\n    polarity : int\n        Polarity of the overall path to the given node.\n    Returns\n    -------\n    generator of tuples, (node, polarity)\n        Each tuple returned contains two elements, a node (string) and the\n        polarity of the overall path (int) to that node.\n    \"\"\"\n    signed_pred_list = []\n    for pred in im.predecessors(node):\n        pred_edge = (pred, node)\n        yield (pred, _get_edge_sign(im, pred_edge) * polarity)\n\n\ndef _get_edge_sign(im, edge):\n    \"\"\"Get the polarity of the influence by examining the edge sign.\"\"\"\n    edge_data = im[edge[0]][edge[1]]\n    # Handle possible multiple edges between nodes\n    signs = list(set([v['sign'] for v in edge_data.values()\n                                  if v.get('sign')]))\n    if len(signs) > 1:\n        logger.warning(\"Edge %s has conflicting polarities; choosing \"\n                       \"positive polarity by default\" % str(edge))\n        sign = 1\n    else:\n        sign = signs[0]\n    if sign is None:\n        raise Exception('No sign attribute for edge.')\n    elif abs(sign) == 1:\n        return sign\n    else:\n        raise Exception('Unexpected edge sign: %s' % edge.attr['sign'])\n\n\ndef _add_modification_to_agent(agent, mod_type, residue, position):\n    \"\"\"Add a modification condition to an Agent.\"\"\"\n    new_mod = ModCondition(mod_type, residue, position)\n    # Check if this modification already exists\n    for old_mod in agent.mods:\n        if old_mod.equals(new_mod):\n            return agent\n    new_agent = deepcopy(agent)\n    new_agent.mods.append(new_mod)\n    return new_agent\n\n\ndef _add_activity_to_agent(agent, act_type, is_active):\n    # Default to active, and return polarity if it's an inhibition\n    new_act = ActivityCondition(act_type, True)\n    # Check if this state already exists\n    if agent.activity is not None and agent.activity.equals(new_act):\n        return agent\n    new_agent = deepcopy(agent)\n    new_agent.activity = new_act\n    polarity = 1 if is_active else -1\n    return new_agent\n\n\ndef _match_lhs(cp, rules):\n    \"\"\"Get rules with a left-hand side matching the given ComplexPattern.\"\"\"\n    rule_matches = []\n    for rule in rules:\n        reactant_pattern = rule.rule_expression.reactant_pattern\n        for rule_cp in reactant_pattern.complex_patterns:\n            if _cp_embeds_into(rule_cp, cp):\n                rule_matches.append(rule)\n                break\n    return rule_matches\n\n\ndef _cp_embeds_into(cp1, cp2):\n    \"\"\"Check that any state in ComplexPattern2 is matched in ComplexPattern1.\n    \"\"\"\n    # Check that any state in cp2 is matched in cp1\n    # If the thing we're matching to is just a monomer pattern, that makes\n    # things easier--we just need to find the corresponding monomer pattern\n    # in cp1\n    if cp1 is None or cp2 is None:\n        return False\n    cp1 = as_complex_pattern(cp1)\n    cp2 = as_complex_pattern(cp2)\n    if len(cp2.monomer_patterns) == 1:\n        mp2 = cp2.monomer_patterns[0]\n        # Iterate over the monomer patterns in cp1 and see if there is one\n        # that has the same name\n        for mp1 in cp1.monomer_patterns:\n            if _mp_embeds_into(mp1, mp2):\n                return True\n    return False\n\n\ndef _mp_embeds_into(mp1, mp2):\n    \"\"\"Check that conditions in MonomerPattern2 are met in MonomerPattern1.\"\"\"\n    sc_matches = []\n    if mp1.monomer.name != mp2.monomer.name:\n        return False\n    # Check that all conditions in mp2 are met in mp1\n    for site_name, site_state in mp2.site_conditions.items():\n        if site_name not in mp1.site_conditions or \\\n           site_state != mp1.site_conditions[site_name]:\n            return False\n    return True\n\n\ndef _monomer_pattern_label(mp):\n    \"\"\"Return a string label for a MonomerPattern.\"\"\"\n    site_strs = []\n    for site, cond in mp.site_conditions.items():\n        if isinstance(cond, tuple) or isinstance(cond, list):\n            assert len(cond) == 2\n            if cond[1] == WILD:\n                site_str = '%s_%s' % (site, cond[0])\n            else:\n                site_str = '%s_%s%s' % (site, cond[0], cond[1])\n        elif isinstance(cond, numbers.Real):\n            continue\n        else:\n            site_str = '%s_%s' % (site, cond)\n        site_strs.append(site_str)\n    return '%s_%s' % (mp.monomer.name, '_'.join(site_strs))\n", "meta": {"hexsha": "135f3b06cf33f7c7416becdd4d59b97f98fa19d6", "size": 41892, "ext": "py", "lang": "Python", "max_stars_repo_path": "indra/explanation/model_checker/pysb.py", "max_stars_repo_name": "johnbachman/belpy", "max_stars_repo_head_hexsha": "1f8052c294fa05b3cd471c544b725f6f0adf9869", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 136, "max_stars_repo_stars_event_min_datetime": "2016-02-11T22:06:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:26:20.000Z", "max_issues_repo_path": "indra/explanation/model_checker/pysb.py", "max_issues_repo_name": "johnbachman/belpy", "max_issues_repo_head_hexsha": "1f8052c294fa05b3cd471c544b725f6f0adf9869", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 748, "max_issues_repo_issues_event_min_datetime": "2016-02-03T16:27:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T14:27:54.000Z", "max_forks_repo_path": "indra/explanation/model_checker/pysb.py", "max_forks_repo_name": "johnbachman/belpy", "max_forks_repo_head_hexsha": "1f8052c294fa05b3cd471c544b725f6f0adf9869", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 56, "max_forks_repo_forks_event_min_datetime": "2015-08-28T14:03:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T06:15:55.000Z", "avg_line_length": 42.7906026558, "max_line_length": 79, "alphanum_fraction": 0.5870571947, "include": true, "reason": "import numpy,import scipy,import networkx", "num_tokens": 8888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.19958119293562745}}
{"text": "# Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\nfrom graphlearn.python.nn.tf.module import Module\nfrom graphlearn.python.nn.tf.layers.linear_layer import LinearLayer\n\nclass EgoSAGELayerGroup(Module):\n  def __init__(self, layers):\n    super(EgoSAGELayerGroup, self).__init__()\n    self.layers = layers\n\n  def append(self, layer):\n    self.layers.append(layer)\n\n  def forward(self, x_list, expands):\n    \"\"\" Compute node embeddings based on GraphSAGE.\n\n    x_list = [nodes, hop1, hop2, ... , hopK-1, hopK]\n               |   /  |   /  |   /        |    /\n               |  /   |  /   |  /         |   /\n               | /    | /    | /          |  /\n    output = [ret0,  ret1, ret2, ... , retK-1]\n\n    Args:\n      x_list: A list of tensors, representing input nodes and their neighbors.\n        If len(x_list) is K+1, that means x_list[0], x_list[1], ... , x_list[K]\n        are the hidden embedding values at each hop. Tensors in x_list[i] are\n        the neighbors of that in x_list[i-1]. In this layer, we will do\n        convolution for each adjencent pair and return a list with length K.\n\n        The shape of x_list[0] is `[n, input_dim_0]`, and the shape of x_list[i]\n        is `[n * k_1 * ... * k_i, input_dim_i]`, where `k_i` means the neighbor\n        count of each node at (i-1)th hop. Each `input_dim_i` must match with\n        `input_dim` parameter when layer construction.\n\n      expands: An integer list of neighbor count at each hop. For the above\n        x_list, expands = [k_1, k_2, ... , k_K]\n\n    Return:\n      A list with K tensors, and the ith shape is\n      `[n * k_1 * ... * k_i, output_dim]`.\n    \"\"\"\n    assert len(self.layers) == (len(x_list) - 1)\n    assert len(self.layers) == len(expands)\n\n    rets = []\n    for i in range(1, len(x_list)):\n      x = x_list[i - 1]\n      neighbors = x_list[i]\n      ret = self.layers[i - 1](x, neighbors, expands[i - 1])\n      rets.append(ret)\n    return rets\n\nclass EgoSAGELayer(Module):\n  \"\"\" GraphSAGE. https://arxiv.org/abs/1706.02216.\n\n  Args:\n    name: A string, layer name.\n    input_dim: An integer or a two elements tuple. Dimension of input features.\n      If an integer, nodes and neighbors share the same dimension.\n      If an tuple, the two elements represent the dimensions of node features\n      and neighbor features.\n      Usually, different dimensions happen in the heterogeneous graph.\n    output_dim: An integer, dimension of the output embeddings. Both the node\n      features and neighbor features will be encoded into the same dimension,\n      and then do some combination.\n    agg_type: A string, how to merge neighbor values. The optional values are\n      'mean', 'sum', 'max'.\n    com_type: A string, how to combine neighbors to self. The optional values\n      are 'add', 'concat'.\n    use_bias: A boolean, whether add bias after computation.\n  \"\"\"\n\n  def __init__(self,\n               name,\n               input_dim,\n               output_dim,\n               agg_type=\"mean\",\n               com_type=\"add\",\n               use_bias=False,\n               parameter_share=False,\n               **kwargs):\n    super(EgoSAGELayer, self).__init__()\n    assert agg_type in {\"mean\", \"sum\", \"max\", \"gcn\"}\n    assert com_type in {\"add\", \"concat\", \"gcn\"}\n\n    self.agg_type = agg_type\n    self.com_type = com_type\n    self.out_dim = output_dim\n\n    if isinstance(input_dim, list) or isinstance(input_dim, tuple):\n      self.in_dim = input_dim\n      assert len(self.in_dim) == 2\n    else:\n      self.in_dim = [input_dim, input_dim]\n\n    with tf.variable_scope(\"ego_sage_layer_\" + name, reuse=tf.AUTO_REUSE):\n      self.linears = self.add_transform_layers(parameter_share, use_bias)\n\n  def add_transform_layers(self, parameter_share, use_bias):\n    layers = []\n    if self.com_type == \"concat\":\n      dim = self.in_dim[0] + self.in_dim[1]\n      layers.append(LinearLayer(\"trans_nodes\", dim, self.out_dim, use_bias))\n    elif parameter_share and self.in_dim[0] == self.in_dim[1]:\n      layer = LinearLayer(\"trans_nodes\", self.in_dim[0], self.out_dim, use_bias)\n      layers.append(layer)\n      layers.append(layer)\n    else:\n      layers.append(\n          LinearLayer(\"trans_nodes\", self.in_dim[0], self.out_dim, use_bias))\n      layers.append(\n          LinearLayer(\"trans_nbrs\", self.in_dim[1], self.out_dim, use_bias))\n    return layers\n\n  def forward(self, x, neighbor, expand):\n    \"\"\" Compute node embeddings based on GraphSAGE.\n    Args:\n      x: A float tensor with shape = [batch_size, input_dim].\n      neighbor: A float tensor with shape = [batch_size * expand, input_dim].\n      expand: An integer, the neighbor count.\n\n    Return:\n      A float tensor with shape=[batch_size, output_dim].\n    \"\"\"\n    # aggregate neighbors at each hop\n    agg_func = self.aggregator()\n    agg_info = agg_func(neighbor, expand, self.in_dim[1])\n\n    # combine self info with aggregated neighbors\n    comb_func = self.combiner()\n    return comb_func(x, agg_info)\n\n  def aggregator(self):\n    func_name = self.agg_type + \"_agg\"\n    if not hasattr(self, func_name):\n      raise TypeError(\"Unsupported agg_type: \" + self.agg_type)\n    return getattr(self, func_name)\n\n  def sum_agg(self, x, expand, dim):\n    t = tf.reshape(x, [-1, expand, dim])\n    return tf.math.reduce_sum(t, axis=1)\n\n  def mean_agg(self, x, expand, dim):\n    t = tf.reshape(x, [-1, expand, dim])\n    return tf.math.reduce_mean(t, axis=1)\n\n  def gcn_agg(self, x, expand, dim):\n    return tf.reshape(x, [-1, expand, dim])\n\n  def max_agg(self, x, expand, dim):\n    t = tf.reshape(x, [-1, expand, dim])\n    return tf.math.reduce_max(t, axis=1)\n\n  def combiner(self):\n    func_name = self.com_type + \"_comb\"\n    if not hasattr(self, func_name):\n      raise TypeError(\"Unsupported com_type: \" + self.com_type)\n    return getattr(self, func_name)\n\n  def add_comb(self, x, neighbors):\n    current = self.linears[0](x)\n    nbr_info = self.linears[1](neighbors)\n    return tf.add(current, nbr_info)\n\n  def concat_comb(self, x, neighbors):\n    tmp = tf.concat([x, neighbors], axis=1)\n    ret = self.linears[0](tmp)\n    return ret\n\n  def gcn_comb(self, x, neighbors):\n    x = tf.reduce_mean(tf.concat(\n          [neighbors, tf.expand_dims(x, axis=1)], axis=1), axis=1)\n    return self.linears[0](x)\n", "meta": {"hexsha": "7332aefdae3f427856489f1b4cdb443611dc2d59", "size": 7024, "ext": "py", "lang": "Python", "max_stars_repo_path": "graphlearn/python/nn/tf/layers/ego_sage_layer.py", "max_stars_repo_name": "gasdaf/graph-learn", "max_stars_repo_head_hexsha": "4a77b39be37bb7507f0e9fb5d4ed40ca623b2ceb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-30T03:13:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T03:13:23.000Z", "max_issues_repo_path": "graphlearn/python/nn/tf/layers/ego_sage_layer.py", "max_issues_repo_name": "gasdaf/graph-learn", "max_issues_repo_head_hexsha": "4a77b39be37bb7507f0e9fb5d4ed40ca623b2ceb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphlearn/python/nn/tf/layers/ego_sage_layer.py", "max_forks_repo_name": "gasdaf/graph-learn", "max_forks_repo_head_hexsha": "4a77b39be37bb7507f0e9fb5d4ed40ca623b2ceb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5833333333, "max_line_length": 80, "alphanum_fraction": 0.6445045558, "include": true, "reason": "import numpy", "num_tokens": 1798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.19958119293562745}}
{"text": "# This file is part of QuTiP: Quantum Toolbox in Python.\n#\n#    Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.\n#    All rights reserved.\n#\n#    Redistribution and use in source and binary forms, with or without\n#    modification, are permitted provided that the following conditions are\n#    met:\n#\n#    1. Redistributions of source code must retain the above copyright notice,\n#       this list of conditions and the following disclaimer.\n#\n#    2. Redistributions in binary form must reproduce the above copyright\n#       notice, this list of conditions and the following disclaimer in the\n#       documentation and/or other materials provided with the distribution.\n#\n#    3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names\n#       of its contributors may be used to endorse or promote products derived\n#       from this software without specific prior written permission.\n#\n#    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n#    \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n#    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n#    PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n#    HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n#    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n#    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n#    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n#    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n#    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n#    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n###############################################################################\n\"\"\"\nThis module contains a collection of routines for operating on sparse\nmatrices on the scipy.sparse formats, for use internally by other modules\nthroughout QuTiP.\n\"\"\"\n\n__all__ = ['sp_fro_norm', 'sp_inf_norm', 'sp_L2_norm', 'sp_max_norm',\n           'sp_one_norm', 'sp_reshape', 'sp_eigs', 'sp_expm', 'sp_permute',\n           'sp_reverse_permute', 'sp_bandwidth', 'sp_profile']\n\nimport scipy.sparse as sp\nimport scipy.sparse.linalg as spla\nimport numpy as np\nimport scipy.linalg as la\nfrom scipy.linalg.blas import get_blas_funcs\n_dznrm2 = get_blas_funcs(\"znrm2\")\nfrom qutip.cy.sparse_utils import (_sparse_profile, _sparse_permute,\n                                   _sparse_reverse_permute, _sparse_bandwidth)\nfrom qutip.settings import debug\n\nimport qutip.logging\nlogger = qutip.logging.get_logger()\n\nif debug:\n    import inspect\n\n\ndef sp_fro_norm(data):\n    \"\"\"\n    Frobius norm for sparse matrix\n    \"\"\"\n    out = np.sum(np.abs(data.data)**2)\n    return np.sqrt(out)\n\n\ndef sp_inf_norm(data):\n    \"\"\"\n    Infinity norm for sparse matrix\n    \"\"\"\n    return np.max([np.sum(np.abs(data.getrow(k).data))\n                   for k in range(data.shape[0])])\n\n\ndef sp_L2_norm(data):\n    \"\"\"\n    L2 norm sparse vector\n    \"\"\"\n    if 1 not in data.shape:\n        raise TypeError(\"Use L2-norm only for vectors.\")\n\n    if len(data.data):\n        return _dznrm2(data.data)\n    else:\n        return 0\n\n\ndef sp_max_norm(data):\n    \"\"\"\n    Max norm for sparse matrix\n    \"\"\"\n    return np.max(np.abs(data.data)) if any(data.data) else 0\n\n\ndef sp_one_norm(data):\n    \"\"\"\n    One norm for sparse matrix\n    \"\"\"\n    return np.max(np.array([np.sum(np.abs((data.getcol(k).data)))\n                            for k in range(data.shape[1])]))\n\n\ndef sp_reshape(A, shape, format='csr'):\n    \"\"\"\n    Reshapes a sparse matrix.\n\n    Parameters\n    ----------\n    A : sparse_matrix\n        Input matrix in any format\n    shape : list/tuple\n        Desired shape of new matrix\n    format : string {'csr','coo','csc','lil'}\n        Optional string indicating desired output format\n\n    Returns\n    -------\n    B : csr_matrix\n        Reshaped sparse matrix\n\n    References\n    ----------\n\n        http://stackoverflow.com/questions/16511879/reshape-sparse-matrix-efficiently-python-scipy-0-12\n\n    \"\"\"\n    if not hasattr(shape, '__len__') or len(shape) != 2:\n        raise ValueError('Shape must be a list of two integers')\n\n    C = A.tocoo()\n    nrows, ncols = C.shape\n    size = nrows * ncols\n    new_size = shape[0] * shape[1]\n\n    if new_size != size:\n        raise ValueError('Total size of new array must be unchanged.')\n\n    flat_indices = ncols * C.row + C.col\n    new_row, new_col = divmod(flat_indices, shape[1])\n    B = sp.coo_matrix((C.data, (new_row, new_col)), shape=shape)\n\n    if format == 'csr':\n        return B.tocsr()\n    elif format == 'coo':\n        return B\n    elif format == 'csc':\n        return B.tocsc()\n    elif format == 'lil':\n        return B.tolil()\n    else:\n        raise ValueError('Return format not valid.')\n\n\ndef _dense_eigs(data, isherm, vecs, N, eigvals, num_large, num_small):\n    \"\"\"\n    Internal functions for computing eigenvalues and eigenstates for a dense\n    matrix.\n    \"\"\"\n    if debug:\n        logger.debug(inspect.stack()[0][3] + \": vectors = \" + str(vecs))\n\n    evecs = None\n\n    if vecs:\n        if isherm:\n            if eigvals == 0:\n                evals, evecs = la.eigh(data)\n            else:\n                if num_small > 0:\n                    evals, evecs = la.eigh(\n                        data, eigvals=[0, num_small - 1])\n                if num_large > 0:\n                    evals, evecs = la.eigh(\n                        data, eigvals=[N - num_large, N - 1])\n        else:\n            evals, evecs = la.eig(data)\n    else:\n        if isherm:\n            if eigvals == 0:\n                evals = la.eigvalsh(data)\n            else:\n                if num_small > 0:\n                    evals = la.eigvalsh(data, eigvals=[0, num_small - 1])\n                if num_large > 0:\n                    evals = la.eigvalsh(data, eigvals=[N - num_large, N - 1])\n        else:\n            evals = la.eigvals(data)\n\n    _zipped = list(zip(evals, range(len(evals))))\n    _zipped.sort()\n    evals, perm = list(zip(*_zipped))\n\n    if vecs:\n        evecs = np.array([evecs[:, k] for k in perm])\n\n    if not isherm and eigvals > 0:\n        if vecs:\n            if num_small > 0:\n                evals, evecs = evals[:num_small], evecs[:num_small]\n            elif num_large > 0:\n                evals, evecs = evals[(N - num_large):], evecs[(N - num_large):]\n        else:\n            if num_small > 0:\n                evals = evals[:num_small]\n            elif num_large > 0:\n                evals = evals[(N - num_large):]\n\n    return np.array(evals), np.array(evecs)\n\n\ndef _sp_eigs(data, isherm, vecs, N, eigvals, num_large, num_small, tol,\n             maxiter):\n    \"\"\"\n    Internal functions for computing eigenvalues and eigenstates for a sparse\n    matrix.\n    \"\"\"\n    if debug:\n        print(inspect.stack()[0][3] + \": vectors = \" + str(vecs))\n\n    big_vals = np.array([])\n    small_vals = np.array([])\n    evecs = None\n\n    remove_one = False\n    if eigvals == (N - 1):\n        # calculate all eigenvalues and remove one at output if using sparse\n        eigvals = 0\n        num_small = int(np.ceil(N / 2.0))\n        num_large = N - num_small\n        remove_one = True\n\n    if vecs:\n        if isherm:\n            if num_large > 0:\n                big_vals, big_vecs = sp.linalg.eigsh(data, k=num_large,\n                                                     which='LA', tol=tol,\n                                                     maxiter=maxiter)\n                big_vecs = sp.csr_matrix(big_vecs, dtype=complex)\n            if num_small > 0:\n                small_vals, small_vecs = sp.linalg.eigsh(\n                    data, k=num_small, which='SA',\n                    tol=tol, maxiter=maxiter)\n\n        else:\n            if num_large > 0:\n                big_vals, big_vecs = sp.linalg.eigs(data, k=num_large,\n                                                    which='LR', tol=tol,\n                                                    maxiter=maxiter)\n                big_vecs = sp.csr_matrix(big_vecs, dtype=complex)\n            if num_small > 0:\n                small_vals, small_vecs = sp.linalg.eigs(\n                    data, k=num_small, which='SR',\n                    tol=tol, maxiter=maxiter)\n\n        if num_large != 0 and num_small != 0:\n            evecs = sp.hstack([small_vecs, big_vecs], format='csr')\n        elif num_large != 0 and num_small == 0:\n            evecs = big_vecs\n        elif num_large == 0 and num_small != 0:\n            evecs = small_vecs\n    else:\n        if isherm:\n            if num_large > 0:\n                big_vals = sp.linalg.eigsh(\n                    data, k=num_large, which='LA',\n                    return_eigenvectors=False, tol=tol, maxiter=maxiter)\n            if num_small > 0:\n                small_vals = sp.linalg.eigsh(\n                    data, k=num_small, which='SA',\n                    return_eigenvectors=False, tol=tol, maxiter=maxiter)\n        else:\n            if num_large > 0:\n                big_vals = sp.linalg.eigs(\n                    data, k=num_large, which='LR',\n                    return_eigenvectors=False, tol=tol, maxiter=maxiter)\n            if num_small > 0:\n                small_vals = sp.linalg.eigs(\n                    data, k=num_small, which='SR',\n                    return_eigenvectors=False, tol=tol, maxiter=maxiter)\n\n    evals = np.hstack((small_vals, big_vals))\n    if isherm:\n        evals = np.real(evals)\n\n    _zipped = list(zip(evals, range(len(evals))))\n    _zipped.sort()\n    evals, perm = list(zip(*_zipped))\n\n    if vecs:\n        evecs = np.array([evecs[:, k] for k in perm])\n\n    # remove last element if requesting N-1 eigs and using sparse\n    if remove_one:\n        evals = np.delete(evals, -1)\n        if vecs:\n            evecs = np.delete(evecs, -1)\n\n    return np.array(evals), np.array(evecs)\n\n\ndef sp_eigs(data, isherm, vecs=True, sparse=False, sort='low',\n            eigvals=0, tol=0, maxiter=100000):\n    \"\"\"Returns Eigenvalues and Eigenvectors for a sparse matrix.\n    Uses dense eigen-solver unless user sets sparse=True.\n\n    Parameters\n    ----------\n    data : csr_matrix\n        Input matrix\n    isherm : bool\n        Indicate whether the matrix is hermitian or not\n    vecs : bool {True , False}\n        Flag for requesting eigenvectors\n    sparse : bool {False , True}\n        Flag to use sparse solver\n    sort : str {'low' , 'high}\n        Return lowest or highest eigenvals/vecs\n    eigvals : int\n        Number of eigenvals/vecs to return.  Default = 0 (return all)\n    tol : float\n        Tolerance for sparse eigensolver.  Default = 0 (Machine precision)\n    maxiter : int\n        Max. number of iterations used by sparse sigensolver.\n\n    Returns\n    -------\n    Array of eigenvalues and (by default) array of corresponding Eigenvectors.\n\n    \"\"\"\n\n    if debug:\n        print(inspect.stack()[0][3])\n\n    if data.shape[0] != data.shape[1]:\n        raise TypeError(\"Can only diagonalize square matrices\")\n\n    N = data.shape[0]\n    if eigvals == N:\n        eigvals = 0\n\n    if eigvals > N:\n        raise ValueError(\"Number of requested eigen vals/vecs must be <= N.\")\n\n    # set number of large and small eigenvals/vecs\n    if eigvals == 0:  # user wants all eigs (default)\n        D = int(np.ceil(N / 2.0))\n        num_large = N - D\n        if not np.mod(N, 2):\n            M = D\n        else:\n            M = D - 1\n        num_small = N - M\n    else:  # if user wants only a few eigen vals/vecs\n        if sort == 'low':\n            num_small = eigvals\n            num_large = 0\n        elif sort == 'high':\n            num_large = eigvals\n            num_small = 0\n        else:\n            raise ValueError(\"Invalid option for 'sort'.\")\n\n    # Dispatch to sparse/dense solvers\n    if sparse:\n        evals, evecs = _sp_eigs(data, isherm, vecs, N, eigvals, num_large,\n                                num_small, tol, maxiter)\n    else:\n        evals, evecs = _dense_eigs(data.todense(), isherm, vecs, N, eigvals,\n                                   num_large, num_small)\n\n    if sort == 'high':  # flip arrays to largest values first\n        if vecs:\n            evecs = np.flipud(evecs)\n        evals = np.flipud(evals)\n\n    return (evals, evecs) if vecs else evals\n\n\ndef sp_expm(data, sparse=True):\n    \"\"\"\n    Sparse matrix exponential.\n    \"\"\"\n    A = data.tocsc()  # extract Qobj data (sparse matrix)\n    m_vals = np.array([3, 5, 7, 9, 13])\n    theta = np.array([0.01495585217958292, 0.2539398330063230,\n                      0.9504178996162932, 2.097847961257068,\n                      5.371920351148152], dtype=float)\n    normA = sp_one_norm(data)\n    if normA <= theta[-1]:\n        for ii in range(len(m_vals)):\n            if normA <= theta[ii]:\n                F = _pade(A, m_vals[ii], sparse)\n                break\n    else:\n        t, s = np.frexp(normA / theta[-1])\n        s = s - (t == 0.5)\n        A = A / 2.0 ** s\n        F = _pade(A, m_vals[-1], sparse)\n        for i in range(s):\n            F = F * F\n\n    return F\n\n\ndef _pade(A, m, sparse):\n    n = np.shape(A)[0]\n    c = _padecoeff(m)\n\n    if m != 13:\n        apows = [[] for jj in range(int(np.ceil((m + 1) / 2)))]\n        apows[0] = sp.eye(n, n, format='csc')\n        apows[1] = A * A\n        for jj in range(2, int(np.ceil((m + 1) / 2))):\n            apows[jj] = apows[jj - 1] * apows[1]\n        U = sp.lil_matrix((n, n)).tocsc()\n        V = sp.lil_matrix((n, n)).tocsc()\n        for jj in range(m, 0, -2):\n            U = U + c[jj] * apows[jj // 2]\n        U = A * U\n        for jj in range(m - 1, -1, -2):\n            V = V + c[jj] * apows[(jj + 1) // 2]\n\n        if sparse:\n            F = spla.spsolve((-U + V), (U + V))\n            return F.tocsr()\n        else:\n            F = la.solve((-U + V).todense(), (U + V).todense())\n            return sp.lil_matrix(F).tocsr()\n\n    elif m == 13:\n        A2 = A * A\n        A4 = A2 * A2\n        A6 = A2 * A4\n        U = A * (A6 * (c[13] * A6 + c[11] * A4 + c[9] * A2) +\n                 c[7] * A6 + c[5] * A4 + c[3] * A2 +\n                 c[1] * sp.eye(n, n).tocsc())\n        V = A6 * (c[12] * A6 + c[10] * A4 + c[8] * A2) + c[6] * A6 + c[4] * \\\n            A4 + c[2] * A2 + c[0] * sp.eye(n, n).tocsc()\n\n        if sparse:\n            F = spla.spsolve((-U + V), (U + V))\n            return F.tocsr()\n        else:\n            F = la.solve((-U + V).todense(), (U + V).todense())\n            return sp.csr_matrix(F)\n\n\ndef _padecoeff(m):\n    \"\"\"\n    Private function returning coefficients for Pade approximation.\n    \"\"\"\n    if m == 3:\n        return np.array([120, 60, 12, 1])\n    elif m == 5:\n        return np.array([30240, 15120, 3360, 420, 30, 1])\n    elif m == 7:\n        return np.array([17297280, 8648640, 1995840, 277200,\n                         25200, 1512, 56, 1])\n    elif m == 9:\n        return np.array([17643225600, 8821612800, 2075673600,\n                         302702400, 30270240, 2162160, 110880,\n                         3960, 90, 1])\n    elif m == 13:\n        return np.array([64764752532480000, 32382376266240000,\n                         7771770303897600, 1187353796428800,\n                         129060195264000, 10559470521600, 670442572800,\n                         33522128640, 1323241920, 40840800,\n                         960960, 16380, 182, 1])\n\n\ndef sp_permute(A, rperm=(), cperm=(), safe=True):\n    \"\"\"\n    Permutes the rows and columns of a sparse CSR/CSC matrix\n    according to the permutation arrays rperm and cperm, respectively.\n    Here, the permutation arrays specify the new order of the rows and\n    columns. i.e. [0,1,2,3,4] -> [3,0,4,1,2].\n\n    Parameters\n    ----------\n    A : csr_matrix, csc_matrix\n        Input matrix.\n    rperm : array_like of integers\n        Array of row permutations.\n    cperm : array_like of integers\n        Array of column permutations.\n    safe : bool\n        Check structure of permutation arrays.\n\n    Returns\n    -------\n    perm_csr : csr_matrix, csc_matrix\n        CSR or CSC matrix with permuted rows/columns.\n\n    \"\"\"\n    rperm = np.asarray(rperm, dtype=np.int32)\n    cperm = np.asarray(cperm, dtype=np.int32)\n    nrows = A.shape[0]\n    ncols = A.shape[1]\n    if len(rperm) == 0:\n        rperm = np.arange(nrows, dtype=np.int32)\n    if len(cperm) == 0:\n        cperm = np.arange(ncols, dtype=np.int32)\n    if safe:\n        if len(np.setdiff1d(rperm, np.arange(nrows))) != 0:\n            raise Exception('Invalid row permutation array.')\n        if len(np.setdiff1d(cperm, np.arange(ncols))) != 0:\n            raise Exception('Invalid column permutation array.')\n\n    shp = A.shape\n    kind = A.getformat()\n    if kind == 'csr':\n        flag = 0\n    elif kind == 'csc':\n        flag = 1\n    else:\n        raise Exception('Input must be Qobj, CSR, or CSC matrix.')\n\n    data, ind, ptr = _sparse_permute(A.data, A.indices, A.indptr,\n                                     nrows, ncols, rperm, cperm, flag)\n    if kind == 'csr':\n        return sp.csr_matrix((data, ind, ptr), shape=shp, dtype=data.dtype)\n    elif kind == 'csc':\n        return sp.csc_matrix((data, ind, ptr), shape=shp, dtype=data.dtype)\n\n\ndef sp_reverse_permute(A, rperm=(), cperm=(), safe=True):\n    \"\"\"\n    Performs a reverse permutations of the rows and columns of a sparse CSR/CSC\n    matrix according to the permutation arrays rperm and cperm, respectively.\n    Here, the permutation arrays specify the order of the rows and columns used\n    to permute the original array.\n\n    Parameters\n    ----------\n    A : csr_matrix, csc_matrix\n        Input matrix.\n    rperm : array_like of integers\n        Array of row permutations.\n    cperm : array_like of integers\n        Array of column permutations.\n    safe : bool\n        Check structure of permutation arrays.\n\n    Returns\n    -------\n    perm_csr : csr_matrix, csc_matrix\n        CSR or CSC matrix with permuted rows/columns.\n\n    \"\"\"\n    rperm = np.asarray(rperm, dtype=np.int32)\n    cperm = np.asarray(cperm, dtype=np.int32)\n    nrows = A.shape[0]\n    ncols = A.shape[1]\n    if len(rperm) == 0:\n        rperm = np.arange(nrows, dtype=np.int32)\n    if len(cperm) == 0:\n        cperm = np.arange(ncols, dtype=np.int32)\n    if safe:\n        if len(np.setdiff1d(rperm, np.arange(nrows))) != 0:\n            raise Exception('Invalid row permutation array.')\n        if len(np.setdiff1d(cperm, np.arange(ncols))) != 0:\n            raise Exception('Invalid column permutation array.')\n\n    shp = A.shape\n    kind = A.getformat()\n    if kind == 'csr':\n        flag = 0\n    elif kind == 'csc':\n        flag = 1\n    else:\n        raise Exception('Input must be Qobj, CSR, or CSC matrix.')\n\n    data, ind, ptr = _sparse_reverse_permute(A.data, A.indices, A.indptr,\n                                             nrows, ncols, rperm, cperm, flag)\n\n    if kind == 'csr':\n        return sp.csr_matrix((data, ind, ptr), shape=shp, dtype=data.dtype)\n    elif kind == 'csc':\n        return sp.csc_matrix((data, ind, ptr), shape=shp, dtype=data.dtype)\n\n\ndef sp_bandwidth(A):\n    \"\"\"\n    Returns the max(mb), lower(lb), and upper(ub) bandwidths of a\n    sparse CSR/CSC matrix.\n\n    If the matrix is symmetric then the upper and lower bandwidths are\n    identical. Diagonal matrices have a bandwidth equal to one.\n\n    Parameters\n    ----------\n    A : csr_matrix, csc_matrix\n        Input matrix\n\n    Returns\n    -------\n    mb : int\n        Maximum bandwidth of matrix.\n    lb : int\n        Lower bandwidth of matrix.\n    ub : int\n        Upper bandwidth of matrix.\n\n    \"\"\"\n    nrows = A.shape[0]\n    ncols = A.shape[1]\n\n    if A.getformat() == 'csr':\n        return _sparse_bandwidth(A.indices, A.indptr, nrows)\n    elif A.getformat() == 'csc':\n        # Normal output is mb,lb,ub but since CSC\n        # is transpose of CSR switch lb and ub\n        mb, ub, lb = _sparse_bandwidth(A.indices, A.indptr, ncols)\n        return mb, lb, ub\n    else:\n        raise Exception('Invalid sparse input format.')\n\n\ndef sp_profile(A):\n    \"\"\"Returns the total, lower, and upper profiles of a sparse matrix.\n\n    If the matrix is symmetric then the upper and lower profiles are\n    identical. Diagonal matrices have zero profile.\n\n    Parameters\n    ----------\n    A : csr_matrix, csc_matrix\n        Input matrix\n    \"\"\"\n    if sp.isspmatrix_csr(A):\n        up = _sparse_profile(A.indices, A.indptr, A.shape[0])\n        A = A.tocsc()\n        lp = _sparse_profile(A.indices, A.indptr, A.shape[0])\n\n    elif sp.isspmatrix_csc(A):\n        lp = _sparse_profile(A.indices, A.indptr, A.shape[0])\n        A = A.tocsr()\n        up = _sparse_profile(A.indices, A.indptr, A.shape[0])\n\n    else:\n        raise TypeError('Input sparse matrix must be in CSR or CSC format.')\n\n    return up+lp, lp, up\n", "meta": {"hexsha": "fe7d6eb36f81f8f195d77a75541c635008688544", "size": 20675, "ext": "py", "lang": "Python", "max_stars_repo_path": "qutip/sparse.py", "max_stars_repo_name": "kiuthed/qutip", "max_stars_repo_head_hexsha": "b6fb8e5bbd9ffeae117b54e56313e8617038deab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "qutip/sparse.py", "max_issues_repo_name": "kiuthed/qutip", "max_issues_repo_head_hexsha": "b6fb8e5bbd9ffeae117b54e56313e8617038deab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qutip/sparse.py", "max_forks_repo_name": "kiuthed/qutip", "max_forks_repo_head_hexsha": "b6fb8e5bbd9ffeae117b54e56313e8617038deab", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0542635659, "max_line_length": 103, "alphanum_fraction": 0.5632889964, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 5537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.19958119293562745}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\n\"\"\"Identifies events of small particles crossing through an ion channel.\n\nThis script parses a trajectory and of an ion-channel-in-membrane simulation\nand identifies events of small target particles (e.g. ions, water molecules)\ncrossing the ion channel. A crossing event is defined as an ion moving from the\nbulk domain on one side of the membrane through the channel pore domain to the\nbulk domain on the opposite side of the membrane. Cases where the target\nparticle moves through the periodic boundary or through the membrane itself are\nnot classified as crossing events.\n\nParticles are assigned to the two bulk domains based on whether their\nz-coordinate is smaller or larger than the mean z-coordinate of the membrane.\nHowever, if a particle is located within a cylindrical region around the centre\nof geometry of the channel protein, it is assigned to the pore domain instead.\nCrossing events are then identified based on the particles moving between these\nthree domains.\n\nThe user can specify an MDAnalysis selection that defines which particles will\nbe considered. It should be noted that the script operates on a per-atom basis.\nTherefore, if the user selected e.g. water molecules on a per-residue bases, the\ncrossing of one water molecule will be recorded as the three individual\ncrossings of the constituent atoms.\n\nOutput is written to a JSON file and corresponds to a data frame structure in\nwhich each row represents one crossing event. The columns will contain the\n(res)ID, (res)name, charge, and mass of the particle that crossed the pore\nalongside the times at which the particle enters and exits the pore. A crossing\nnumber is given which indicates the direction in which the particle crossed\nthe pore (i.e. +1 for crossing in positive z-direction and -1 for crossing in\nnegative z-direction).\n\nThe overall number of particles that cross the pore can be readily calculated\nfrom this data as the cumulative sum over the crossing number. Similarly, the\ntotal amount of charge or mass transported can be evaluated as the cumulative\nsum over the product of the crossing number with charge and mass respectively.\n\"\"\"\n\n\nimport argparse\n\nimport numpy as np\nimport pandas as pd\n\nimport MDAnalysis as mda\n\n\ndef determine_domain_indices(\n    topology_file,\n    trajectory_file,\n    sel_pore,\n    sel_bilayer,\n    sel_target,\n    r_margin,\n    z_margin,\n    b,\n    e,\n    dt\n):\n    \"\"\"Passes through trajectory and assigns domain indices.\n\n    The return value is a data frame containing three columns for particle ID,\n    time stamp, and the domain index of that particle at the given time. The\n    domain index gives an indication of whether a particle is located below\n    the membrane (-1), above the membrane (+1), or inside the channel pore (0).\n    The user can set a start time, end time, and time step based on which frames\n    will be analysed or skipped.\n\n    Particles are assigned to the -1 and +1 domains based on whether their\n    z-coordinate is larger or smaller than the mean z-coordinate of the\n    membrane. If a particle is located within a cylindrical region around the\n    center of geometry of the protein, it is assigned the domain index 0\n    instead. Radius and z-extend of the cylindrical region are determined from\n    the bounding box of the protein, but the user may add a margin to either\n    of these parameters.\n    \"\"\"\n\n    # create MDA universe:\n    u = mda.Universe(topology_file, trajectory_file)\n\n    # determine atom groups for analysis:\n    protein = u.select_atoms(sel_pore)\n    membrane = u.select_atoms(sel_bilayer)\n    target = u.select_atoms(sel_target)\n\n    # find pore radius:\n    prot_radius = max(np.diff(protein.bbox(), axis=0)[0][0:2]) / 2.0\n    radius = prot_radius + r_margin\n\n    # create data frame of target positions over time:\n    dat = []\n    for ts in u.trajectory:\n\n        # skip unwanted frames:\n        if ts.time < b or ts.time > e or ts.time % dt != 0.0:\n            continue\n\n        # inform user:\n        print(\n            \"  ~> identifying domain indices in frame: \" + str(ts.frame)\n            + \" at time: \" + str(ts.time)\n        )\n\n        # create data frame from target particle positions:\n        tmp = pd.DataFrame(\n            target.positions,\n            columns=[\"x\", \"y\", \"z\"]\n        )\n\n        # add particle properties:\n        tmp[\"particle_id\"] = target.ids\n        tmp[\"name\"] = [str(x) for x in target.names]\n        tmp[\"resname\"] = [str(x) for x in target.resnames]\n        tmp[\"resid\"] = [int(x) for x in target.resids]\n        tmp[\"charge\"] = target.charges\n        tmp[\"mass\"] = target.masses\n\n        # add time stamp:\n        tmp[\"t\"] = ts.time\n\n        # position of protein COG in x/y-plane:\n        x_cen = protein.center_of_geometry()[0]\n        y_cen = protein.center_of_geometry()[1]\n\n        # z-extent of proteina nd middle of membrane:\n        z_min = protein.bbox()[0, 2] - z_margin\n        z_max = protein.bbox()[1, 2] + z_margin\n        z_mid = np.mean(membrane.bbox(), axis=0)[2]\n\n        # assign domain indices:\n        tmp.loc[\n            (tmp[\"z\"] < z_mid),\n            \"domain_idx\"\n        ] = int(-1)\n        tmp.loc[\n            (tmp[\"z\"] >= z_mid),\n            \"domain_idx\"\n        ] = int(1)\n        tmp.loc[\n            (tmp[\"z\"] >= z_min)\n            & (tmp[\"z\"] <= z_max)\n            & ((tmp[\"x\"] - x_cen)**2 + (tmp[\"y\"] - y_cen)**2 < radius**2),\n            \"domain_idx\"\n        ] = int(0)\n\n        # sanity check:\n        num_nan = np.sum(tmp[\"domain_idx\"].isna())\n        if num_nan > 0:\n            raise Exception(\"Could not unambiguously assign domain indices.\")\n\n        # drop unneccessary columns:\n        tmp = tmp.drop(columns=[\"x\", \"y\", \"z\"])\n\n        # add to data frame list:\n        dat.append(tmp)\n\n    # combine into overall data frame:\n    df = pd.concat(dat)\n\n    # return the overall data frame of domain indices:\n    return(df)\n\n\ndef aggregate_event_pairs(df):\n    \"\"\"Aggregates pairs of subsequent events.\n\n    The resulting data frame will contain as many rows as the number of\n    crossing events (i.e. a particle going through the channel) occuring in the\n    given data frame. This means that the output data frame will be empty if no\n    crossing event occurs. Each row will contain the time at which the particle\n    entered and left the pore region as well as the mean of those two times. In\n    addition it will contain a crossing number, which indicates whether the\n    particle crossed the pore in positive or negative z-direction (its absolute\n    value is always one).\n\n    The input data frame must contain the domain index difference for a single\n    particle only and may not contain any jump events, i.e. events where the\n    particle moved from domain +1 to domain -1 (or vice versa) without passing\n    through domain 0 (the pore). This can happen if the particle jumps through\n    the periodic boundary or if it moves through the membrane.\n\n    The crossing number is calculated as the mean of two subsequent domain index\n    differences. If they have opposite sign, the crossing number will be zero\n    and the row will be dropped. If they have the same sign, this indicates that\n    the particle moved either from domain -1 to domain 0 to domain +1 or from\n    domain +1 to domain 0 to domain -1, corresponding to a true crossing event.\n    The sign of the crossing number will reflect the direction of the crossing.\n    \"\"\"\n\n    # make copy of input data frame to avoid overwriting contents:\n    df = df.copy()\n\n    # make sure data frame has even number of rows:\n    if df.shape[0] % 2 is not 0:\n        df = df.iloc[:-1]\n\n    # introduce pairing index:\n    df[\"pairing\"] = np.repeat(range(0, int(df.shape[0]/2)), 2)\n\n    # calculate summry statistics over pairings:\n    df[\"crossing_number\"] = df.groupby(\"pairing\").domain_diff.transform(\"mean\")\n    df[\"t_enter\"] = df.groupby(\"pairing\").t.transform(\"min\")\n    df[\"t_mean\"] = df.groupby(\"pairing\").t.transform(\"mean\")\n    df[\"t_exit\"] = df.groupby(\"pairing\").t.transform(\"max\")\n    df = df.groupby([\"pairing\", \"name\"]).mean()\n\n    # remove all rows not corresponding to a crossing event:\n    df = df.loc[df.domain_diff != 0.0, ]\n\n    # return data frame to caller:\n    return(df)\n\n\ndef identify_crossing_events(df):\n    \"\"\"Identifies pore crossing events in data frame of domain indices.\n\n    Given a data frame of domain indices alongside time stamps and particle IDs,\n    this function identifies crossing events, i.e. a particle moving from one\n    side of the membrane to the other THROUGH THE PORE REGION. Cases where a\n    particle moves through the periodic boundary or through the membrane itself\n    (i.e. outside the cylindrical protein region) are not counted as crossing\n    events.\n\n    The return value is a data frame in which each row corresponds to a\n    crossing event and the columns identify times at which the particle entered\n    and exited the pore, the mean of these times, and the ID of the particle\n    which crosses the pore. Note that the input data frame should contain only\n    a single unique particle ID, i.e. this function should by run on the domain\n    index data frame grouped by particle indices. In addition, a further column\n    contains a crossing number indicating the direction in which the particle\n    passed the pore.\n\n    This is done by first calculating the difference between subsequent domain\n    indices. Where this difference is zero, the particle stayed in the given\n    domain and the corresponding row can be ignored. Where this difference is\n    +1/-1, the particle moved into or out of the pore. Where the difference is\n    +2/-2, the particle moved across the periodic boundary or through the\n    membrane.\n\n    The time series of domain index differences is then partitioned into\n    individual series between periodic boundary jump events. In each such\n    subdivision the target particle is known to start outside the pore domain.\n    A crossing event can then be identified by averaging over the sum of\n    pairs of subsequent domain index differences. Note that for a particle that\n    starts out inside the pore domain at the beginning of the trajectory no\n    clear crossing direction can be established (i.e. is it going back to the\n    domain it came from or is it moving across the pore to the opposite domain).\n    By convention, these events will therefore not be counted as pore crossing\n    events.\n    \"\"\"\n\n    # make copy of input data frame to avoid overwriting contents:\n    df = df.copy()\n\n    # calculate difference between subsequent indices:\n    df[\"domain_diff\"] = df[\"domain_idx\"].shift(0) - df[\"domain_idx\"].shift(1)\n    df[\"t\"] = 0.5*(df[\"t\"].shift(0) + df[\"t\"].shift(1))\n    df = df.dropna()\n    df = df.drop(columns=[\"domain_idx\"])\n\n    # drop cases where particle did not change domain at all:\n    df = df.loc[np.abs(df[\"domain_diff\"]) != 0.0, ]\n\n    # create index for number of jumps across period boundary (or through the\n    # membrane)\n    df[\"pbcjump\"] = 0\n    df.pbcjump[(df.domain_diff == -2) | (df.domain_diff == 2)] = 1\n    df.pbcjump = df.pbcjump.cumsum()\n\n    # drop all pbcjump groupings with less then two non-pbcjump events:\n    df = df.loc[(df.domain_diff != -2) & (df.domain_diff != 2), ]\n    df[\"pbccount\"] = df.groupby(\"pbcjump\").domain_diff.transform(\"count\")\n    df = df.loc[df.pbccount > 1, ]\n    df = df.drop(columns=[\"pbccount\"])\n\n    # handle special case of empty data frame:\n    if df.empty is True:\n\n        # manually add columns:\n        df[\"crossing_number\"] = None\n        df[\"t_enter\"] = None\n        df[\"t_mean\"] = None\n        df[\"t_exit\"] = None\n\n    else:\n\n        # aggregate pairwise domain index differences:\n        df = df.groupby(\"pbcjump\").apply(aggregate_event_pairs)\n\n    # remove unneccessary columns and indices:\n    df = df.drop(columns=[\"t\", \"domain_diff\", \"pbcjump\"])\n    df = df.reset_index(drop=True)\n\n    # return data frame:\n    return(df)\n\n\ndef main(argdict):\n    \"\"\"Main function for entry point checking.\n\n    Expects to be given a dictionary of command line arguments.\n    \"\"\"\n\n    # parse trajectory and assign domain indices:\n    print(\"--> identifying domain indices...\")\n    nm2ang = 10.0\n    domain_indices = determine_domain_indices(\n        argdict[\"s\"],\n        argdict[\"f\"],\n        argdict[\"sel_pore\"],\n        argdict[\"sel_bilayer\"],\n        argdict[\"sel_target\"],\n        argdict[\"r_margin\"] * nm2ang,\n        argdict[\"z_margin\"] * nm2ang,\n        argdict[\"b\"],\n        argdict[\"e\"],\n        argdict[\"dt\"]\n    )\n\n    # find crossing events by particle:\n    print(\"--> identifying crossing events...\")\n    crossing_events = (\n        domain_indices.groupby([\"particle_id\"]).apply(identify_crossing_events)\n    )\n    crossing_events = crossing_events.reset_index(drop=True)\n\n    # restore atom and residue names:\n    name = domain_indices.groupby(\"particle_id\").name.first()\n    crossing_events[\"name\"] = np.array(name.loc[crossing_events.particle_id])\n    crossing_events[\"resname\"] = np.array(name.loc[crossing_events.particle_id])\n\n    # serialize results:\n    crossing_events.to_json(argdict[\"o\"], orient=\"records\")\n    with open(argdict[\"o\"], \"a\") as f:\n        f.write(\"\\n\")\n\n\n# entry point check:\nif __name__ == \"__main__\":\n\n    # turn off this warning:\n    pd.options.mode.chained_assignment = None\n\n    # parse command line arguments:\n    parser = argparse.ArgumentParser(\n        description=__doc__,\n        formatter_class=argparse.ArgumentDefaultsHelpFormatter\n    )\n    parser.add_argument(\n        \"-s\",\n        type=str,\n        nargs=None,\n        default=\"production.tpr\",\n        help=\"\"\"Topology file. Should contain charges and masses!\"\"\"\n    )\n    parser.add_argument(\n        \"-f\",\n        type=str,\n        nargs=None,\n        default=\"production.xtc\",\n        help=\"\"\"Trajectory file name.\"\"\"\n    )\n    parser.add_argument(\n        \"-o\",\n        type=str,\n        nargs=None,\n        default=\"crossing_events.json\",\n        help=\"\"\"Name of output JSON file containing all crossing events.\"\"\"\n    )\n    parser.add_argument(\n        \"-sel_target\",\n        type=str,\n        nargs=None,\n        default=\"resname NA CL\",\n        help=\"\"\"MDAnalysis selection identifying the mobile particles\n        crossing the pore.\"\"\"\n    )\n    parser.add_argument(\n        \"-sel_pore\",\n        type=str,\n        nargs=None,\n        default=\"protein\",\n        help=\"\"\"MDAnalysis selection identifying the channel domain.\"\"\"\n    )\n    parser.add_argument(\n        \"-sel_bilayer\",\n        type=str,\n        nargs=None,\n        default=\"resname DOPC POPC\",\n        help=\"\"\"MDAnalysis selection identifying the lipid bilayer.\"\"\"\n    )\n    parser.add_argument(\n        \"-r_margin\",\n        type=float,\n        nargs=None,\n        default=0.0,\n        help=\"\"\"Radius margin around protein for identification of pore\n        domain in nanometers. The pore domain is taken to be a cylinder whose\n        radius is the radius of the protein (in the x/y-plane) plus this\n        margin.\"\"\"\n    )\n    parser.add_argument(\n        \"-z_margin\",\n        type=float,\n        nargs=None,\n        default=-1.0,\n        help=\"\"\"Margin for extension of pore domain around protein in\n        nanometers. The pore domain is taken to be a cylinder whose the\n        extension is determined from the z-extension of the protein plus this\n        margin. Should never exceed half the length of the pore.\"\"\"\n    )\n    parser.add_argument(\n        \"-b\",\n        type=float,\n        nargs=None,\n        default=0.0,\n        help=\"\"\"Start time for trajectory analysis in picoseconds. Frames\n        before this time will be ignored.\"\"\"\n    )\n    parser.add_argument(\n        \"-e\",\n        type=float,\n        nargs=None,\n        default=float(\"inf\"),\n        help=\"\"\"End time for trajectory analysis in picoseconds. Frames\n        after this time will be ignored.\"\"\"\n    )\n    parser.add_argument(\n        \"-dt\",\n        type=float,\n        nargs=None,\n        default=100.0,\n        help=\"\"\"Time step for trajectroy analysis. Frames not that are not\n        an integer multiple of this time step will be ignored. A time step of\n        100 picoseconds seems to be sufficiently small for ions.\"\"\"\n    )\n\n    # parse arguments and convert to dictionary:\n    args = parser.parse_args()\n    argdict = vars(args)\n\n    # pass arguments to main function:\n    main(argdict)\n", "meta": {"hexsha": "fbd6d3a91a7cdb343f96d9505fc3aedf0cf9ab68", "size": 16379, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/ion-transport/identify_crossing_events.py", "max_stars_repo_name": "Inniag/nanopore-electrowetting-scripts", "max_stars_repo_head_hexsha": "5539a2b6f7b06ae8b386cf3cb1d9b9bce2c5828f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-24T17:09:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T17:09:36.000Z", "max_issues_repo_path": "scripts/ion-transport/identify_crossing_events.py", "max_issues_repo_name": "Inniag/nanopore-electrowetting-scripts", "max_issues_repo_head_hexsha": "5539a2b6f7b06ae8b386cf3cb1d9b9bce2c5828f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/ion-transport/identify_crossing_events.py", "max_forks_repo_name": "Inniag/nanopore-electrowetting-scripts", "max_forks_repo_head_hexsha": "5539a2b6f7b06ae8b386cf3cb1d9b9bce2c5828f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-28T13:52:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-28T13:52:33.000Z", "avg_line_length": 36.6420581655, "max_line_length": 80, "alphanum_fraction": 0.666463154, "include": true, "reason": "import numpy", "num_tokens": 3757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.19958119293562745}}
{"text": "import warnings\n\nimport numpy as np\nimport operator\n\nfrom .. import types, utils, config\nfrom .templates import (AttributeTemplate, AbstractTemplate, CallableTemplate,\n                        Registry, signature)\n\nfrom ..numpy_support import (ufunc_find_matching_loop,\n                             supported_ufunc_loop, as_dtype,\n                             from_dtype, as_dtype, resolve_output_type,\n                             carray, farray)\nfrom ..errors import TypingError, NumbaPerformanceWarning\nfrom numba import pndindex\n\nregistry = Registry()\ninfer = registry.register\ninfer_global = registry.register_global\ninfer_getattr = registry.register_attr\n\n\nclass Numpy_rules_ufunc(AbstractTemplate):\n    @classmethod\n    def _handle_inputs(cls, ufunc, args, kws):\n        \"\"\"\n        Process argument types to a given *ufunc*.\n        Returns a (base types, explicit outputs, ndims, layout) tuple where:\n        - `base types` is a tuple of scalar types for each input\n        - `explicit outputs` is a tuple of explicit output types (arrays)\n        - `ndims` is the number of dimensions of the loop and also of\n          any outputs, explicit or implicit\n        - `layout` is the layout for any implicit output to be allocated\n        \"\"\"\n        nin = ufunc.nin\n        nout = ufunc.nout\n        nargs = ufunc.nargs\n\n        # preconditions\n        assert nargs == nin + nout\n\n        if nout > 1:\n            msg = \"ufunc '{0}': not supported in this mode (more than 1 output)\"\n            raise TypingError(msg=msg.format(ufunc.__name__))\n\n        if len(args) < nin:\n            msg = \"ufunc '{0}': not enough arguments ({1} found, {2} required)\"\n            raise TypingError(msg=msg.format(ufunc.__name__, len(args), nin))\n\n        if len(args) > nargs:\n            msg = \"ufunc '{0}': too many arguments ({1} found, {2} maximum)\"\n            raise TypingError(msg=msg.format(ufunc.__name__, len(args), nargs))\n\n        args = [a.as_array if isinstance(a, types.ArrayCompatible) else a\n                for a in args]\n        arg_ndims = [a.ndim if isinstance(a, types.ArrayCompatible) else 0\n                     for a in args]\n        ndims = max(arg_ndims)\n\n        # explicit outputs must be arrays (no explicit scalar return values supported)\n        explicit_outputs = args[nin:]\n\n        # all the explicit outputs must match the number max number of dimensions\n        if not all(d == ndims for d in arg_ndims[nin:]):\n            msg = \"ufunc '{0}' called with unsuitable explicit output arrays.\"\n            raise TypingError(msg=msg.format(ufunc.__name__))\n\n        if not all(isinstance(output, types.ArrayCompatible)\n                   for output in explicit_outputs):\n            msg = \"ufunc '{0}' called with an explicit output that is not an array\"\n            raise TypingError(msg=msg.format(ufunc.__name__))\n\n        if not all(output.mutable for output in explicit_outputs):\n            msg = \"ufunc '{0}' called with an explicit output that is read-only\"\n            raise TypingError(msg=msg.format(ufunc.__name__))\n\n        # find the kernel to use, based only in the input types (as does NumPy)\n        base_types = [x.dtype if isinstance(x, types.ArrayCompatible) else x\n                      for x in args]\n\n        # Figure out the output array layout, if needed.\n        layout = None\n        if ndims > 0 and (len(explicit_outputs) < ufunc.nout):\n            layout = 'C'\n            layouts = [x.layout if isinstance(x, types.ArrayCompatible) else ''\n                       for x in args]\n\n            # Prefer C contig if any array is C contig.\n            # Next, prefer F contig.\n            # Defaults to C contig if not layouts are C/F.\n            if 'C' not in layouts and 'F' in layouts:\n                layout = 'F'\n\n        return base_types, explicit_outputs, ndims, layout\n\n    @property\n    def ufunc(self):\n        return self.key\n\n    def generic(self, args, kws):\n        ufunc = self.ufunc\n        base_types, explicit_outputs, ndims, layout = self._handle_inputs(\n            ufunc, args, kws)\n        ufunc_loop = ufunc_find_matching_loop(ufunc, base_types)\n        if ufunc_loop is None:\n            raise TypingError(\"can't resolve ufunc {0} for types {1}\".format(ufunc.__name__, args))\n\n        # check if all the types involved in the ufunc loop are supported in this mode\n        if not supported_ufunc_loop(ufunc, ufunc_loop):\n            msg = \"ufunc '{0}' using the loop '{1}' not supported in this mode\"\n            raise TypingError(msg=msg.format(ufunc.__name__, ufunc_loop.ufunc_sig))\n\n        # if there is any explicit output type, check that it is valid\n        explicit_outputs_np = [as_dtype(tp.dtype) for tp in explicit_outputs]\n\n        # Numpy will happily use unsafe conversions (although it will actually warn)\n        if not all (np.can_cast(fromty, toty, 'unsafe') for (fromty, toty) in\n                    zip(ufunc_loop.numpy_outputs, explicit_outputs_np)):\n            msg = \"ufunc '{0}' can't cast result to explicit result type\"\n            raise TypingError(msg=msg.format(ufunc.__name__))\n\n        # A valid loop was found that is compatible. The result of type inference should\n        # be based on the explicit output types, and when not available with the type given\n        # by the selected NumPy loop\n        out = list(explicit_outputs)\n        implicit_output_count = ufunc.nout - len(explicit_outputs)\n        if implicit_output_count > 0:\n            # XXX this is currently wrong for datetime64 and timedelta64,\n            # as ufunc_find_matching_loop() doesn't do any type inference.\n            ret_tys = ufunc_loop.outputs[-implicit_output_count:]\n            if ndims > 0:\n                assert layout is not None\n                ret_tys = [types.Array(dtype=ret_ty, ndim=ndims, layout=layout)\n                           for ret_ty in ret_tys]\n                ret_tys = [resolve_output_type(self.context, args, ret_ty)\n                           for ret_ty in ret_tys]\n            out.extend(ret_tys)\n\n        # note: although the previous code should support multiple return values, only one\n        #       is supported as of now (signature may not support more than one).\n        #       there is an check enforcing only one output\n        out.extend(args)\n        return signature(*out)\n\n\n@infer_global(operator.pos)\nclass UnaryPositiveArray(AbstractTemplate):\n    '''Typing template class for +(array) expressions.  This operator is\n    special because there is no Numpy ufunc associated with it; we\n    include typing for it here (numba.typing.npydecl) because this is\n    where the remaining array operators are defined.\n    '''\n    key = operator.pos\n\n    def generic(self, args, kws):\n        assert not kws\n        if len(args) == 1 and isinstance(args[0], types.ArrayCompatible):\n            arg_ty = args[0]\n            return arg_ty.copy()(arg_ty)\n\n\nclass NumpyRulesArrayOperator(Numpy_rules_ufunc):\n    _op_map = {\n        operator.add: \"add\",\n        operator.sub: \"subtract\",\n        operator.mul: \"multiply\",\n        operator.truediv: \"true_divide\",\n        operator.floordiv: \"floor_divide\",\n        operator.mod: \"remainder\",\n        operator.pow: \"power\",\n        operator.lshift: \"left_shift\",\n        operator.rshift: \"right_shift\",\n        operator.and_: \"bitwise_and\",\n        operator.or_: \"bitwise_or\",\n        operator.xor: \"bitwise_xor\",\n        operator.eq: \"equal\",\n        operator.gt: \"greater\",\n        operator.ge: \"greater_equal\",\n        operator.lt: \"less\",\n        operator.le: \"less_equal\",\n        operator.ne: \"not_equal\",\n    }\n\n    @property\n    def ufunc(self):\n        return getattr(np, self._op_map[self.key])\n\n    @classmethod\n    def install_operations(cls):\n        for op, ufunc_name in cls._op_map.items():\n            infer_global(op)(\n                type(\"NumpyRulesArrayOperator_\" + ufunc_name, (cls,), dict(key=op))\n            )\n\n    def generic(self, args, kws):\n        '''Overloads and calls base class generic() method, returning\n        None if a TypingError occurred.\n\n        Returning None for operators is important since operators are\n        heavily overloaded, and by suppressing type errors, we allow\n        type inference to check other possibilities before giving up\n        (particularly user-defined operators).\n        '''\n        try:\n            sig = super(NumpyRulesArrayOperator, self).generic(args, kws)\n        except TypingError:\n            return None\n        if sig is None:\n            return None\n        args = sig.args\n        # Only accept at least one array argument, otherwise the operator\n        # doesn't involve Numpy's ufunc machinery.\n        if not any(isinstance(arg, types.ArrayCompatible)\n                   for arg in args):\n            return None\n        return sig\n\n\n_binop_map = NumpyRulesArrayOperator._op_map\n\nclass NumpyRulesInplaceArrayOperator(NumpyRulesArrayOperator):\n    _op_map = {\n        operator.iadd: \"add\",\n        operator.isub: \"subtract\",\n        operator.imul: \"multiply\",\n        operator.itruediv: \"true_divide\",\n        operator.ifloordiv: \"floor_divide\",\n        operator.imod: \"remainder\",\n        operator.ipow: \"power\",\n        operator.ilshift: \"left_shift\",\n        operator.irshift: \"right_shift\",\n        operator.iand: \"bitwise_and\",\n        operator.ior: \"bitwise_or\",\n        operator.ixor: \"bitwise_xor\",\n    }\n\n    def generic(self, args, kws):\n        # Type the inplace operator as if an explicit output was passed,\n        # to handle type resolution correctly.\n        # (for example int8[:] += int16[:] should use an int8[:] output,\n        #  not int16[:])\n        lhs, rhs = args\n        if not isinstance(lhs, types.ArrayCompatible):\n            return\n        args = args + (lhs,)\n        sig = super(NumpyRulesInplaceArrayOperator, self).generic(args, kws)\n        # Strip off the fake explicit output\n        assert len(sig.args) == 3\n        real_sig = signature(sig.return_type, *sig.args[:2])\n        return real_sig\n\n\nclass NumpyRulesUnaryArrayOperator(NumpyRulesArrayOperator):\n    _op_map = {\n        # Positive is a special case since there is no Numpy ufunc\n        # corresponding to it (it's essentially an identity operator).\n        # See UnaryPositiveArray, above.\n        operator.neg: \"negative\",\n        operator.invert: \"invert\",\n    }\n\n    def generic(self, args, kws):\n        assert not kws\n        if len(args) == 1 and isinstance(args[0], types.ArrayCompatible):\n            return super(NumpyRulesUnaryArrayOperator, self).generic(args, kws)\n\n\n# list of unary ufuncs to register\n\n_math_operations = [ \"add\", \"subtract\", \"multiply\",\n                     \"logaddexp\", \"logaddexp2\", \"true_divide\",\n                     \"floor_divide\", \"negative\", \"power\",\n                     \"remainder\", \"fmod\", \"absolute\",\n                     \"rint\", \"sign\", \"conjugate\", \"exp\", \"exp2\",\n                     \"log\", \"log2\", \"log10\", \"expm1\", \"log1p\",\n                     \"sqrt\", \"square\", \"reciprocal\",\n                     \"divide\", \"mod\", \"abs\", \"fabs\" , \"gcd\", \"lcm\"]\n\n_trigonometric_functions = [ \"sin\", \"cos\", \"tan\", \"arcsin\",\n                             \"arccos\", \"arctan\", \"arctan2\",\n                             \"hypot\", \"sinh\", \"cosh\", \"tanh\",\n                             \"arcsinh\", \"arccosh\", \"arctanh\",\n                             \"deg2rad\", \"rad2deg\", \"degrees\",\n                             \"radians\" ]\n\n_bit_twiddling_functions = [\"bitwise_and\", \"bitwise_or\",\n                            \"bitwise_xor\", \"invert\",\n                            \"left_shift\", \"right_shift\",\n                            \"bitwise_not\" ]\n\n_comparison_functions = [ \"greater\", \"greater_equal\", \"less\",\n                          \"less_equal\", \"not_equal\", \"equal\",\n                          \"logical_and\", \"logical_or\",\n                          \"logical_xor\", \"logical_not\",\n                          \"maximum\", \"minimum\", \"fmax\", \"fmin\" ]\n\n_floating_functions = [ \"isfinite\", \"isinf\", \"isnan\", \"signbit\",\n                        \"copysign\", \"nextafter\", \"modf\", \"ldexp\",\n                        \"frexp\", \"floor\", \"ceil\", \"trunc\",\n                        \"spacing\" ]\n\n\n# This is a set of the ufuncs that are not yet supported by Lowering. In order\n# to trigger no-python mode we must not register them until their Lowering is\n# implemented.\n#\n# It also works as a nice TODO list for ufunc support :)\n_unsupported = set([ 'frexp', # this one is tricky, as it has 2 returns\n                     'modf',  # this one also has 2 returns\n                 ])\n\n# A list of ufuncs that are in fact aliases of other ufuncs. They need to insert the\n# resolve method, but not register the ufunc itself\n_aliases = set([\"bitwise_not\", \"mod\", \"abs\"])\n\n# In python3 np.divide is mapped to np.true_divide\nif np.divide == np.true_divide:\n    _aliases.add(\"divide\")\n\ndef _numpy_ufunc(name):\n    func = getattr(np, name)\n    class typing_class(Numpy_rules_ufunc):\n        key = func\n\n    typing_class.__name__ = \"resolve_{0}\".format(name)\n\n    if not name in _aliases:\n        infer_global(func, types.Function(typing_class))\n\nall_ufuncs = sum([_math_operations, _trigonometric_functions,\n                  _bit_twiddling_functions, _comparison_functions,\n                  _floating_functions], [])\n\nsupported_ufuncs = [x for x in all_ufuncs if x not in _unsupported]\n\nfor func in supported_ufuncs:\n    _numpy_ufunc(func)\n\nall_ufuncs = [getattr(np, name) for name in all_ufuncs]\nsupported_ufuncs = [getattr(np, name) for name in supported_ufuncs]\n\nNumpyRulesUnaryArrayOperator.install_operations()\nNumpyRulesArrayOperator.install_operations()\nNumpyRulesInplaceArrayOperator.install_operations()\n\nsupported_array_operators = set(\n    NumpyRulesUnaryArrayOperator._op_map.keys()\n).union(\n    NumpyRulesArrayOperator._op_map.keys()\n).union(\n    NumpyRulesInplaceArrayOperator._op_map.keys()\n)\n\ndel _math_operations, _trigonometric_functions, _bit_twiddling_functions\ndel _comparison_functions, _floating_functions, _unsupported\ndel _aliases, _numpy_ufunc\n\n\n# -----------------------------------------------------------------------------\n# Install global helpers for array methods.\n\nclass Numpy_method_redirection(AbstractTemplate):\n    \"\"\"\n    A template redirecting a Numpy global function (e.g. np.sum) to an\n    array method of the same name (e.g. ndarray.sum).\n    \"\"\"\n\n    def generic(self, args, kws):\n        pysig = None\n        if kws:\n            if self.method_name == 'sum':\n                if 'axis' in kws and 'dtype' not in kws:\n                    def sum_stub(arr, axis):\n                        pass\n                    pysig = utils.pysignature(sum_stub)\n                elif 'dtype' in kws and 'axis' not in kws:\n                    def sum_stub(arr, dtype):\n                        pass\n                    pysig = utils.pysignature(sum_stub)\n                elif 'dtype' in kws and 'axis' in kws:\n                    def sum_stub(arr, axis, dtype):\n                        pass\n                    pysig = utils.pysignature(sum_stub)\n            elif self.method_name == 'argsort':\n                def argsort_stub(arr, kind='quicksort'):\n                    pass\n                pysig = utils.pysignature(argsort_stub)\n            else:\n                fmt = \"numba doesn't support kwarg for {}\"\n                raise TypingError(fmt.format(self.method_name))\n\n        arr = args[0]\n        # This will return a BoundFunction\n        meth_ty = self.context.resolve_getattr(arr, self.method_name)\n        # Resolve arguments on the bound function\n        meth_sig = self.context.resolve_function_type(meth_ty, args[1:], kws)\n        if meth_sig is not None:\n            return meth_sig.as_function().replace(pysig=pysig)\n\n\n# Function to glue attributes onto the numpy-esque object\ndef _numpy_redirect(fname):\n    numpy_function = getattr(np, fname)\n    cls = type(\"Numpy_redirect_{0}\".format(fname), (Numpy_method_redirection,),\n               dict(key=numpy_function, method_name=fname))\n    infer_global(numpy_function, types.Function(cls))\n\nfor func in ['min', 'max', 'sum', 'prod', 'mean', 'var', 'std',\n             'cumsum', 'cumprod', 'argmin', 'argmax', 'argsort',\n             'nonzero', 'ravel']:\n    _numpy_redirect(func)\n\n\n# -----------------------------------------------------------------------------\n# Numpy scalar constructors\n\n# Register np.int8, etc. as converters to the equivalent Numba types\nnp_types = set(getattr(np, str(nb_type)) for nb_type in types.number_domain)\nnp_types.add(np.bool_)\n# Those may or may not be aliases (depending on the Numpy build / version)\nnp_types.add(np.intc)\nnp_types.add(np.intp)\nnp_types.add(np.uintc)\nnp_types.add(np.uintp)\n\n\ndef register_number_classes(register_global):\n    for np_type in np_types:\n        nb_type = getattr(types, np_type.__name__)\n\n        register_global(np_type, types.NumberClass(nb_type))\n\n\nregister_number_classes(infer_global)\n\n\n# -----------------------------------------------------------------------------\n# Numpy array constructors\n\ndef _parse_shape(shape):\n    ndim = None\n    if isinstance(shape, types.Integer):\n        ndim = 1\n    elif isinstance(shape, (types.Tuple, types.UniTuple)):\n        if all(isinstance(s, types.Integer) for s in shape):\n            ndim = len(shape)\n    return ndim\n\ndef _parse_dtype(dtype):\n    if isinstance(dtype, types.DTypeSpec):\n        return dtype.dtype\n\ndef _parse_nested_sequence(context, typ):\n    \"\"\"\n    Parse a (possibly 0d) nested sequence type.\n    A (ndim, dtype) tuple is returned.  Note the sequence may still be\n    heterogeneous, as long as it converts to the given dtype.\n    \"\"\"\n    if isinstance(typ, (types.Buffer,)):\n        raise TypingError(\"%r not allowed in a homogeneous sequence\" % typ)\n    elif isinstance(typ, (types.Sequence,)):\n        n, dtype = _parse_nested_sequence(context, typ.dtype)\n        return n + 1, dtype\n    elif isinstance(typ, (types.BaseTuple,)):\n        if typ.count == 0:\n            # Mimick Numpy's behaviour\n            return 1, types.float64\n        n, dtype = _parse_nested_sequence(context, typ[0])\n        dtypes = [dtype]\n        for i in range(1, typ.count):\n            _n, dtype = _parse_nested_sequence(context, typ[i])\n            if _n != n:\n                raise TypingError(\"type %r does not have a regular shape\"\n                                  % (typ,))\n            dtypes.append(dtype)\n        dtype = context.unify_types(*dtypes)\n        if dtype is None:\n            raise TypingError(\"cannot convert %r to a homogeneous type\" % typ)\n        return n + 1, dtype\n    else:\n        # Scalar type => check it's valid as a Numpy array dtype\n        as_dtype(typ)\n        return 0, typ\n\n\n\n@infer_global(np.array)\nclass NpArray(CallableTemplate):\n    \"\"\"\n    Typing template for np.array().\n    \"\"\"\n\n    def generic(self):\n        def typer(object, dtype=None):\n            ndim, seq_dtype = _parse_nested_sequence(self.context, object)\n            if dtype is None:\n                dtype = seq_dtype\n            else:\n                dtype = _parse_dtype(dtype)\n                if dtype is None:\n                    return\n            return types.Array(dtype, ndim, 'C')\n\n        return typer\n\n\n@infer_global(np.empty)\n@infer_global(np.zeros)\n@infer_global(np.ones)\nclass NdConstructor(CallableTemplate):\n    \"\"\"\n    Typing template for np.empty(), .zeros(), .ones().\n    \"\"\"\n\n    def generic(self):\n        def typer(shape, dtype=None):\n            if dtype is None:\n                nb_dtype = types.double\n            else:\n                nb_dtype = _parse_dtype(dtype)\n\n            ndim = _parse_shape(shape)\n            if nb_dtype is not None and ndim is not None:\n                return types.Array(dtype=nb_dtype, ndim=ndim, layout='C')\n\n        return typer\n\n\n@infer_global(np.empty_like)\n@infer_global(np.zeros_like)\nclass NdConstructorLike(CallableTemplate):\n    \"\"\"\n    Typing template for np.empty_like(), .zeros_like(), .ones_like().\n    \"\"\"\n\n    def generic(self):\n        \"\"\"\n        np.empty_like(array) -> empty array of the same shape and layout\n        np.empty_like(scalar) -> empty 0-d array of the scalar type\n        \"\"\"\n        def typer(arg, dtype=None):\n            if dtype is not None:\n                nb_dtype = _parse_dtype(dtype)\n            elif isinstance(arg, types.Array):\n                nb_dtype = arg.dtype\n            else:\n                nb_dtype = arg\n            if nb_dtype is not None:\n                if isinstance(arg, types.Array):\n                    layout = arg.layout if arg.layout != 'A' else 'C'\n                    return arg.copy(dtype=nb_dtype, layout=layout, readonly=False)\n                else:\n                    return types.Array(nb_dtype, 0, 'C')\n\n        return typer\n\n\ninfer_global(np.ones_like)(NdConstructorLike)\n\n\n@infer_global(np.full)\nclass NdFull(CallableTemplate):\n\n    def generic(self):\n        def typer(shape, fill_value, dtype=None):\n            if dtype is None:\n                nb_dtype = fill_value\n            else:\n                nb_dtype = _parse_dtype(dtype)\n\n            ndim = _parse_shape(shape)\n            if nb_dtype is not None and ndim is not None:\n                return types.Array(dtype=nb_dtype, ndim=ndim, layout='C')\n\n        return typer\n\n@infer_global(np.full_like)\nclass NdFullLike(CallableTemplate):\n\n    def generic(self):\n        \"\"\"\n        np.full_like(array, val) -> array of the same shape and layout\n        np.full_like(scalar, val) -> 0-d array of the scalar type\n        \"\"\"\n        def typer(arg, fill_value, dtype=None):\n            if dtype is not None:\n                nb_dtype = _parse_dtype(dtype)\n            elif isinstance(arg, types.Array):\n                nb_dtype = arg.dtype\n            else:\n                nb_dtype = arg\n            if nb_dtype is not None:\n                if isinstance(arg, types.Array):\n                    return arg.copy(dtype=nb_dtype, readonly=False)\n                else:\n                    return types.Array(dtype=nb_dtype, ndim=0, layout='C')\n\n        return typer\n\n\n@infer_global(np.identity)\nclass NdIdentity(AbstractTemplate):\n\n    def generic(self, args, kws):\n        assert not kws\n        n = args[0]\n        if not isinstance(n, types.Integer):\n            return\n        if len(args) >= 2:\n            nb_dtype = _parse_dtype(args[1])\n        else:\n            nb_dtype = types.float64\n\n        if nb_dtype is not None:\n            return_type = types.Array(ndim=2, dtype=nb_dtype, layout='C')\n            return signature(return_type, *args)\n\n\ndef _infer_dtype_from_inputs(inputs):\n    return dtype\n\n\n@infer_global(np.linspace)\nclass NdLinspace(AbstractTemplate):\n\n    def generic(self, args, kws):\n        assert not kws\n        bounds = args[:2]\n        if not all(isinstance(arg, types.Number) for arg in bounds):\n            return\n        if len(args) >= 3:\n            num = args[2]\n            if not isinstance(num, types.Integer):\n                return\n        if len(args) >= 4:\n            # Not supporting the other arguments as it would require\n            # keyword arguments for reasonable use.\n            return\n        if any(isinstance(arg, types.Complex) for arg in bounds):\n            dtype = types.complex128\n        else:\n            dtype = types.float64\n        return_type = types.Array(ndim=1, dtype=dtype, layout='C')\n        return signature(return_type, *args)\n\n\n@infer_global(np.frombuffer)\nclass NdFromBuffer(CallableTemplate):\n\n    def generic(self):\n        def typer(buffer, dtype=None):\n            if not isinstance(buffer, types.Buffer) or buffer.layout != 'C':\n                return\n            if dtype is None:\n                nb_dtype = types.float64\n            else:\n                nb_dtype = _parse_dtype(dtype)\n\n            if nb_dtype is not None:\n                return types.Array(dtype=nb_dtype, ndim=1, layout='C',\n                                   readonly=not buffer.mutable)\n\n        return typer\n\n\n@infer_global(np.sort)\nclass NdSort(CallableTemplate):\n\n    def generic(self):\n        def typer(a):\n            if isinstance(a, types.Array) and a.ndim == 1:\n                return a\n\n        return typer\n\n\n@infer_global(np.asfortranarray)\nclass AsFortranArray(CallableTemplate):\n\n    def generic(self):\n        def typer(a):\n            if isinstance(a, types.Array):\n                return a.copy(layout='F', ndim=max(a.ndim, 1))\n\n        return typer\n\n\n@infer_global(np.ascontiguousarray)\nclass AsContiguousArray(CallableTemplate):\n\n    def generic(self):\n        def typer(a):\n            if isinstance(a, types.Array):\n                return a.copy(layout='C', ndim=max(a.ndim, 1))\n\n        return typer\n\n\n@infer_global(np.copy)\nclass NdCopy(CallableTemplate):\n\n    def generic(self):\n        def typer(a):\n            if isinstance(a, types.Array):\n                layout = 'F' if a.layout == 'F' else 'C'\n                return a.copy(layout=layout, readonly=False)\n\n        return typer\n\n\n@infer_global(np.expand_dims)\nclass NdExpandDims(CallableTemplate):\n\n    def generic(self):\n        def typer(a, axis):\n            if (not isinstance(a, types.Array)\n                or not isinstance(axis, types.Integer)):\n                return\n\n            layout = a.layout if a.ndim <= 1 else 'A'\n            return a.copy(ndim=a.ndim + 1, layout=layout)\n\n        return typer\n\n\nclass BaseAtLeastNdTemplate(AbstractTemplate):\n\n    def generic(self, args, kws):\n        assert not kws\n        if not args or not all(isinstance(a, types.Array) for a in args):\n            return\n\n        rets = [self.convert_array(a) for a in args]\n        if len(rets) > 1:\n            retty = types.BaseTuple.from_types(rets)\n        else:\n            retty = rets[0]\n        return signature(retty, *args)\n\n\n@infer_global(np.atleast_1d)\nclass NdAtLeast1d(BaseAtLeastNdTemplate):\n\n    def convert_array(self, a):\n        return a.copy(ndim=max(a.ndim, 1))\n\n\n@infer_global(np.atleast_2d)\nclass NdAtLeast2d(BaseAtLeastNdTemplate):\n\n    def convert_array(self, a):\n        return a.copy(ndim=max(a.ndim, 2))\n\n\n@infer_global(np.atleast_3d)\nclass NdAtLeast3d(BaseAtLeastNdTemplate):\n\n    def convert_array(self, a):\n        return a.copy(ndim=max(a.ndim, 3))\n\n\ndef _homogeneous_dims(context, func_name, arrays):\n    ndim = arrays[0].ndim\n    for a in arrays:\n        if a.ndim != ndim:\n            raise TypeError(\"%s(): all the input arrays \"\n                            \"must have same number of dimensions\"\n                            % func_name)\n    return ndim\n\ndef _sequence_of_arrays(context, func_name, arrays,\n                        dim_chooser=_homogeneous_dims):\n    if (not isinstance(arrays, types.BaseTuple)\n        or not len(arrays)\n        or not all(isinstance(a, types.Array) for a in arrays)):\n        raise TypeError(\"%s(): expecting a non-empty tuple of arrays, \"\n                        \"got %s\" % (func_name, arrays))\n\n    ndim = dim_chooser(context, func_name, arrays)\n\n    dtype = context.unify_types(*(a.dtype for a in arrays))\n    if dtype is None:\n        raise TypeError(\"%s(): input arrays must have \"\n                        \"compatible dtypes\" % func_name)\n\n    return dtype, ndim\n\ndef _choose_concatenation_layout(arrays):\n    # Only create a F array if all input arrays have F layout.\n    # This is a simplified version of Numpy's behaviour,\n    # while Numpy's actually processes the input strides to\n    # decide on optimal output strides\n    # (see PyArray_CreateMultiSortedStridePerm()).\n    return 'F' if all(a.layout == 'F' for a in arrays) else 'C'\n\n\n@infer_global(np.concatenate)\nclass NdConcatenate(CallableTemplate):\n\n    def generic(self):\n        def typer(arrays, axis=None):\n            if axis is not None and not isinstance(axis, types.Integer):\n                # Note Numpy allows axis=None, but it isn't documented:\n                # https://github.com/numpy/numpy/issues/7968\n                return\n\n            dtype, ndim = _sequence_of_arrays(self.context,\n                                              \"np.concatenate\", arrays)\n            if ndim == 0:\n                raise TypeError(\"zero-dimensional arrays cannot be concatenated\")\n\n            layout = _choose_concatenation_layout(arrays)\n\n            return types.Array(dtype, ndim, layout)\n\n        return typer\n\n\n@infer_global(np.stack)\nclass NdStack(CallableTemplate):\n\n    def generic(self):\n        def typer(arrays, axis=None):\n            if axis is not None and not isinstance(axis, types.Integer):\n                # Note Numpy allows axis=None, but it isn't documented:\n                # https://github.com/numpy/numpy/issues/7968\n                return\n\n            dtype, ndim = _sequence_of_arrays(self.context,\n                                                \"np.stack\", arrays)\n\n            # This diverges from Numpy's behaviour, which simply inserts\n            # a new stride at the requested axis (therefore can return\n            # a 'A' array).\n            layout = 'F' if all(a.layout == 'F' for a in arrays) else 'C'\n\n            return types.Array(dtype, ndim + 1, layout)\n\n        return typer\n\n\nclass BaseStackTemplate(CallableTemplate):\n\n    def generic(self):\n        def typer(arrays):\n            dtype, ndim = _sequence_of_arrays(self.context,\n                                              self.func_name, arrays)\n\n            ndim = max(ndim, self.ndim_min)\n            layout = _choose_concatenation_layout(arrays)\n\n            return types.Array(dtype, ndim, layout)\n\n        return typer\n\n\n@infer_global(np.hstack)\nclass NdStack(BaseStackTemplate):\n    func_name = \"np.hstack\"\n    ndim_min = 1\n\n@infer_global(np.vstack)\nclass NdStack(BaseStackTemplate):\n    func_name = \"np.vstack\"\n    ndim_min = 2\n\n@infer_global(np.dstack)\nclass NdStack(BaseStackTemplate):\n    func_name = \"np.dstack\"\n    ndim_min = 3\n\n\n\ndef _column_stack_dims(context, func_name, arrays):\n    # column_stack() allows stacking 1-d and 2-d arrays together\n    for a in arrays:\n        if a.ndim < 1 or a.ndim > 2:\n            raise TypeError(\"np.column_stack() is only defined on \"\n                            \"1-d and 2-d arrays\")\n    return 2\n\n\n@infer_global(np.column_stack)\nclass NdColumnStack(CallableTemplate):\n\n    def generic(self):\n        def typer(arrays):\n            dtype, ndim = _sequence_of_arrays(self.context,\n                                              \"np.column_stack\", arrays,\n                                              dim_chooser=_column_stack_dims)\n\n            layout = _choose_concatenation_layout(arrays)\n\n            return types.Array(dtype, ndim, layout)\n\n        return typer\n\n\n# -----------------------------------------------------------------------------\n# Linear algebra\n\n\nclass MatMulTyperMixin(object):\n\n    def matmul_typer(self, a, b, out=None):\n        \"\"\"\n        Typer function for Numpy matrix multiplication.\n        \"\"\"\n        if not isinstance(a, types.Array) or not isinstance(b, types.Array):\n            return\n        if not all(x.ndim in (1, 2) for x in (a, b)):\n            raise TypingError(\"%s only supported on 1-D and 2-D arrays\"\n                              % (self.func_name, ))\n        # Output dimensionality\n        ndims = set([a.ndim, b.ndim])\n        if ndims == set([2]):\n            # M * M\n            out_ndim = 2\n        elif ndims == set([1, 2]):\n            # M* V and V * M\n            out_ndim = 1\n        elif ndims == set([1]):\n            # V * V\n            out_ndim = 0\n\n        if out is not None:\n            if out_ndim == 0:\n                raise TypeError(\"explicit output unsupported for vector * vector\")\n            elif out.ndim != out_ndim:\n                raise TypeError(\"explicit output has incorrect dimensionality\")\n            if not isinstance(out, types.Array) or out.layout != 'C':\n                raise TypeError(\"output must be a C-contiguous array\")\n            all_args = (a, b, out)\n        else:\n            all_args = (a, b)\n\n        if not (config.DISABLE_PERFORMANCE_WARNINGS or\n                all(x.layout in 'CF' for x in (a, b))):\n            msg = (\"%s is faster on contiguous arrays, called on %s\" %\n                   (self.func_name, (a, b)))\n            warnings.warn(NumbaPerformanceWarning(msg))\n        if not all(x.dtype == a.dtype for x in all_args):\n            raise TypingError(\"%s arguments must all have \"\n                              \"the same dtype\" % (self.func_name,))\n        if not isinstance(a.dtype, (types.Float, types.Complex)):\n            raise TypingError(\"%s only supported on \"\n                              \"float and complex arrays\"\n                              % (self.func_name,))\n        if out:\n            return out\n        elif out_ndim > 0:\n            return types.Array(a.dtype, out_ndim, 'C')\n        else:\n            return a.dtype\n\n\n@infer_global(np.dot)\nclass Dot(MatMulTyperMixin, CallableTemplate):\n    func_name = \"np.dot()\"\n\n    def generic(self):\n        def typer(a, b, out=None):\n            # NOTE: np.dot() and the '@' operator have distinct semantics\n            # for >2-D arrays, but we don't support them.\n            return self.matmul_typer(a, b, out)\n\n        return typer\n\n\n@infer_global(np.vdot)\nclass VDot(CallableTemplate):\n\n    def generic(self):\n        def typer(a, b):\n            if not isinstance(a, types.Array) or not isinstance(b, types.Array):\n                return\n            if not all(x.ndim == 1 for x in (a, b)):\n                raise TypingError(\"np.vdot() only supported on 1-D arrays\")\n            if not all(x.layout in 'CF' for x in (a, b)):\n                warnings.warn(\"np.vdot() is faster on contiguous arrays, called on %s\"\n                              % ((a, b),), NumbaPerformanceWarning)\n            if not all(x.dtype == a.dtype for x in (a, b)):\n                raise TypingError(\"np.vdot() arguments must all have \"\n                                  \"the same dtype\")\n            if not isinstance(a.dtype, (types.Float, types.Complex)):\n                raise TypingError(\"np.vdot() only supported on \"\n                                  \"float and complex arrays\")\n            return a.dtype\n\n        return typer\n\n\n@infer_global(operator.matmul)\nclass MatMul(MatMulTyperMixin, AbstractTemplate):\n    key = operator.matmul\n    func_name = \"'@'\"\n\n    def generic(self, args, kws):\n        assert not kws\n        restype = self.matmul_typer(*args)\n        if restype is not None:\n            return signature(restype, *args)\n\n\ndef _check_linalg_matrix(a, func_name):\n    if not isinstance(a, types.Array):\n        return\n    if not a.ndim == 2:\n        raise TypingError(\"np.linalg.%s() only supported on 2-D arrays\"\n                          % func_name)\n    if not isinstance(a.dtype, (types.Float, types.Complex)):\n        raise TypingError(\"np.linalg.%s() only supported on \"\n                          \"float and complex arrays\" % func_name)\n\n# -----------------------------------------------------------------------------\n# Miscellaneous functions\n\n@infer_global(np.ndenumerate)\nclass NdEnumerate(AbstractTemplate):\n\n    def generic(self, args, kws):\n        assert not kws\n        arr, = args\n\n        if isinstance(arr, types.Array):\n            enumerate_type = types.NumpyNdEnumerateType(arr)\n            return signature(enumerate_type, *args)\n\n\n@infer_global(np.nditer)\nclass NdIter(AbstractTemplate):\n\n    def generic(self, args, kws):\n        assert not kws\n        if len(args) != 1:\n            return\n        arrays, = args\n\n        if isinstance(arrays, types.BaseTuple):\n            if not arrays:\n                return\n            arrays = list(arrays)\n        else:\n            arrays = [arrays]\n        nditerty = types.NumpyNdIterType(arrays)\n        return signature(nditerty, *args)\n\n\n@infer_global(pndindex)\n@infer_global(np.ndindex)\nclass NdIndex(AbstractTemplate):\n\n    def generic(self, args, kws):\n        assert not kws\n\n        # Either ndindex(shape) or ndindex(*shape)\n        if len(args) == 1 and isinstance(args[0], types.BaseTuple):\n            tup = args[0]\n            if tup.count > 0 and not isinstance(tup, types.UniTuple):\n                # Heterogeneous tuple\n                return\n            shape = list(tup)\n        else:\n            shape = args\n\n        if all(isinstance(x, types.Integer) for x in shape):\n            iterator_type = types.NumpyNdIndexType(len(shape))\n            return signature(iterator_type, *args)\n\n\n# We use the same typing key for np.round() and np.around() to\n# re-use the implementations automatically.\n@infer_global(np.round)\n@infer_global(np.around, typing_key=np.round)\nclass Round(AbstractTemplate):\n\n    def generic(self, args, kws):\n        assert not kws\n        assert 1 <= len(args) <= 3\n\n        arg = args[0]\n        if len(args) == 1:\n            decimals = types.intp\n            out = None\n        else:\n            decimals = args[1]\n            if len(args) == 2:\n                out = None\n            else:\n                out = args[2]\n\n        supported_scalars = (types.Integer, types.Float, types.Complex)\n        if isinstance(arg, supported_scalars):\n            assert out is None\n            return signature(arg, *args)\n        if (isinstance(arg, types.Array) and isinstance(arg.dtype, supported_scalars) and\n            isinstance(out, types.Array) and isinstance(out.dtype, supported_scalars) and\n            out.ndim == arg.ndim):\n            # arg can only be complex if out is complex too\n            if (not isinstance(arg.dtype, types.Complex)\n                or isinstance(out.dtype, types.Complex)):\n                return signature(out, *args)\n\n\n@infer_global(np.where)\nclass Where(AbstractTemplate):\n\n    def generic(self, args, kws):\n        assert not kws\n\n        if len(args) == 1:\n            # 0-dim arrays return one result array\n            ary = args[0]\n            ndim = max(ary.ndim, 1)\n            retty = types.UniTuple(types.Array(types.intp, 1, 'C'), ndim)\n            return signature(retty, ary)\n\n        elif len(args) == 3:\n            cond, x, y = args\n            retdty = from_dtype(np.promote_types(\n                        as_dtype(getattr(args[1], 'dtype', args[1])),\n                        as_dtype(getattr(args[2], 'dtype', args[2]))))\n            if isinstance(cond, types.Array):\n                # array where()\n                if isinstance(x, types.Array) and isinstance(y, types.Array):\n                    if (cond.ndim == x.ndim == y.ndim):\n                        if x.layout == y.layout == cond.layout:\n                            retty = types.Array(retdty, x.ndim, x.layout)\n                        else:\n                            retty = types.Array(retdty, x.ndim, 'C')\n                        return signature(retty, *args)\n                else:\n                    # x and y both scalar\n                    retty = types.Array(retdty, cond.ndim, cond.layout)\n                    return signature(retty, *args)\n            else:\n                # scalar where()\n                if not isinstance(x, types.Array):\n                    retty = types.Array(retdty, 0, 'C')\n                    return signature(retty, *args)\n\n\n@infer_global(np.sinc)\nclass Sinc(AbstractTemplate):\n\n    def generic(self, args, kws):\n        assert not kws\n        assert len(args) == 1\n        arg = args[0]\n        supported_scalars = (types.Float, types.Complex)\n        if (isinstance(arg, supported_scalars) or\n              (isinstance(arg, types.Array) and\n               isinstance(arg.dtype, supported_scalars))):\n            return signature(arg, arg)\n\n\n@infer_global(np.angle)\nclass Angle(CallableTemplate):\n    \"\"\"\n    Typing template for np.angle()\n    \"\"\"\n    def generic(self):\n        def typer(z, deg=False):\n            if isinstance(z, types.Array):\n                dtype = z.dtype\n            else:\n                dtype = z\n            if isinstance(dtype, types.Complex):\n                ret_dtype = dtype.underlying_float\n            elif isinstance(dtype, types.Float):\n                ret_dtype = dtype\n            else:\n                return\n            if isinstance(z, types.Array):\n                return z.copy(dtype=ret_dtype)\n            else:\n                return ret_dtype\n        return typer\n\n\n@infer_global(np.diag)\nclass DiagCtor(CallableTemplate):\n    \"\"\"\n    Typing template for np.diag()\n    \"\"\"\n    def generic(self):\n        def typer(ref, k=0):\n            if isinstance(ref, types.Array):\n                if ref.ndim == 1:\n                    rdim = 2\n                elif ref.ndim == 2:\n                    rdim = 1\n                else:\n                    return None\n                if isinstance(k, (int, types.Integer)):\n                    return types.Array(ndim=rdim, dtype=ref.dtype, layout='C')\n        return typer\n\n\n@infer_global(np.take)\nclass Take(AbstractTemplate):\n\n    def generic(self, args, kws):\n        assert not kws\n        assert len(args) == 2\n        arr, ind = args\n        if isinstance(ind, types.Number):\n            retty = arr.dtype\n        elif isinstance(ind, types.Array):\n            retty = types.Array(ndim=ind.ndim, dtype=arr.dtype, layout='C')\n        elif isinstance(ind, types.List):\n            retty = types.Array(ndim=1, dtype=arr.dtype, layout='C')\n        elif isinstance(ind, types.BaseTuple):\n            retty = types.Array(ndim=np.ndim(ind), dtype=arr.dtype, layout='C')\n        else:\n            return None\n\n        return signature(retty, *args)\n\n# -----------------------------------------------------------------------------\n# Numba helpers\n\n@infer_global(carray)\nclass NumbaCArray(CallableTemplate):\n    layout = 'C'\n\n    def generic(self):\n        func_name = self.key.__name__\n\n        def typer(ptr, shape, dtype=types.none):\n            if ptr is types.voidptr:\n                ptr_dtype = None\n            elif isinstance(ptr, types.CPointer):\n                ptr_dtype = ptr.dtype\n            else:\n                raise TypeError(\"%s(): pointer argument expected, got '%s'\"\n                                % (func_name, ptr))\n\n            if dtype is types.none:\n                if ptr_dtype is None:\n                    raise TypeError(\"%s(): explicit dtype required for void* argument\"\n                                    % (func_name,))\n                dtype = ptr_dtype\n            elif isinstance(dtype, types.DTypeSpec):\n                dtype = dtype.dtype\n                if ptr_dtype is not None and dtype != ptr_dtype:\n                    raise TypeError(\"%s(): mismatching dtype '%s' for pointer type '%s'\"\n                                    % (func_name, dtype, ptr))\n            else:\n                raise TypeError(\"%s(): invalid dtype spec '%s'\"\n                                % (func_name, dtype))\n\n            ndim = _parse_shape(shape)\n            if ndim is None:\n                raise TypeError(\"%s(): invalid shape '%s'\"\n                                % (func_name, shape))\n\n            return types.Array(dtype, ndim, self.layout)\n\n        return typer\n\n\n@infer_global(farray)\nclass NumbaFArray(NumbaCArray):\n    layout = 'F'\n", "meta": {"hexsha": "6ad8e1489ad5010b5b59349e2010de7a78d91b79", "size": 42912, "ext": "py", "lang": "Python", "max_stars_repo_path": "numba/typing/npydecl.py", "max_stars_repo_name": "tolysz/numba", "max_stars_repo_head_hexsha": "d7953a18dbf5ea231dc16e967ce8e9b754578ea6", "max_stars_repo_licenses": ["Apache-2.0", "BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numba/typing/npydecl.py", "max_issues_repo_name": "tolysz/numba", "max_issues_repo_head_hexsha": "d7953a18dbf5ea231dc16e967ce8e9b754578ea6", "max_issues_repo_licenses": ["Apache-2.0", "BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-02-11T13:46:30.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-11T13:46:30.000Z", "max_forks_repo_path": "numba/typing/npydecl.py", "max_forks_repo_name": "asodeur/numba", "max_forks_repo_head_hexsha": "d7953a18dbf5ea231dc16e967ce8e9b754578ea6", "max_forks_repo_licenses": ["Apache-2.0", "BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8957345972, "max_line_length": 99, "alphanum_fraction": 0.574408091, "include": true, "reason": "import numpy,from numba", "num_tokens": 9661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.19956023315356078}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Implementation for Single Image Haze Removal Using Dark Channel Prior.\n\nReference:\nhttp://research.microsoft.com/en-us/um/people/kahe/cvpr09/\nhttp://research.microsoft.com/en-us/um/people/kahe/eccv10/\n\"\"\"\n\nimport numpy as np\nfrom PIL import Image\n\nfrom guidedfilter import guided_filter\n\nR, G, B = 0, 1, 2  # index for convenience\nL = 256  # color depth\n\n\ndef get_dark_channel(I, w):\n    \"\"\"Get the dark channel prior in the (RGB) image data.\n\n    Parameters\n    -----------\n    I:  an M * N * 3 numpy array containing data ([0, L-1]) in the image where\n        M is the height, N is the width, 3 represents R/G/B channels.\n    w:  window size\n\n    Return\n    -----------\n    An M * N array for the dark channel prior ([0, L-1]).\n    \"\"\"\n    M, N, _ = I.shape\n    padded = np.pad(I, ((w / 2, w / 2), (w / 2, w / 2), (0, 0)), 'edge')\n    darkch = np.zeros((M, N))\n    for i, j in np.ndindex(darkch.shape):\n        darkch[i, j] = np.min(padded[i:i + w, j:j + w, :])  # CVPR09, eq.5\n    return darkch\n\n\ndef get_atmosphere(I, darkch, p):\n    \"\"\"Get the atmosphere light in the (RGB) image data.\n\n    Parameters\n    -----------\n    I:      the M * N * 3 RGB image data ([0, L-1]) as numpy array\n    darkch: the dark channel prior of the image as an M * N numpy array\n    p:      percentage of pixels for estimating the atmosphere light\n\n    Return\n    -----------\n    A 3-element array containing atmosphere light ([0, L-1]) for each channel\n    \"\"\"\n    # reference CVPR09, 4.4\n    M, N = darkch.shape\n    flatI = I.reshape(M * N, 3)\n    flatdark = darkch.ravel()\n    searchidx = (-flatdark).argsort()[:M * N * p]  # find top M * N * p indexes\n    print('atmosphere light region:', [(i / N, i % N) for i in searchidx])\n\n    # return the highest intensity for each channel\n    return np.max(flatI.take(searchidx, axis=0), axis=0)\n\n\ndef get_transmission(I, A, darkch, omega, w):\n    \"\"\"Get the transmission esitmate in the (RGB) image data.\n\n    Parameters\n    -----------\n    I:       the M * N * 3 RGB image data ([0, L-1]) as numpy array\n    A:       a 3-element array containing atmosphere light\n             ([0, L-1]) for each channel\n    darkch:  the dark channel prior of the image as an M * N numpy array\n    omega:   bias for the estimate\n    w:       window size for the estimate\n\n    Return\n    -----------\n    An M * N array containing the transmission rate ([0.0, 1.0])\n    \"\"\"\n    return 1 - omega * get_dark_channel(I / A, w)  # CVPR09, eq.12\n\n\ndef dehaze_raw(I, tmin=0.2, Amax=220, w=15, p=0.0001,\n               omega=0.95, guided=True, r=40, eps=1e-3):\n    \"\"\"Get the dark channel prior, atmosphere light, transmission rate\n       and refined transmission rate for raw RGB image data.\n\n    Parameters\n    -----------\n    I:      M * N * 3 data as numpy array for the hazy image\n    tmin:   threshold of transmission rate\n    Amax:   threshold of atmosphere light\n    w:      window size of the dark channel prior\n    p:      percentage of pixels for estimating the atmosphere light\n    omega:  bias for the transmission estimate\n\n    guided: whether to use the guided filter to fine the image\n    r:      the radius of the guidance\n    eps:    epsilon for the guided filter\n\n    Return\n    -----------\n    (Idark, A, rawt, refinedt) if guided=False, then rawt == refinedt\n    \"\"\"\n    m, n, _ = I.shape\n    Idark = get_dark_channel(I, w)\n\n    A = get_atmosphere(I, Idark, p)\n    A = np.minimum(A, Amax)  # threshold A\n    print('atmosphere', A)\n\n    rawt = get_transmission(I, A, Idark, omega, w)\n    print('raw transmission rate',)\n    print('between [%.4f, %.4f]' % (rawt.min(), rawt.max()))\n\n    rawt = refinedt = np.maximum(rawt, tmin)  # threshold t\n    if guided:\n        normI = (I - I.min()) / (I.max() - I.min())  # normalize I\n        refinedt = guided_filter(normI, refinedt, r, eps)\n\n    print('refined transmission rate',)\n    print('between [%.4f, %.4f]' % (refinedt.min(), refinedt.max()))\n\n    return Idark, A, rawt, refinedt\n\n\ndef get_radiance(I, A, t):\n    \"\"\"Recover the radiance from raw image data with atmosphere light\n       and transmission rate estimate.\n\n    Parameters\n    ----------\n    I:      M * N * 3 data as numpy array for the hazy image\n    A:      a 3-element array containing atmosphere light\n            ([0, L-1]) for each channel\n    t:      estimate fothe transmission rate\n\n    Return\n    ----------\n    M * N * 3 numpy array for the recovered radiance\n    \"\"\"\n    tiledt = np.zeros_like(I)  # tiled to M * N * 3\n    tiledt[:, :, R] = tiledt[:, :, G] = tiledt[:, :, B] = t\n    return (I - A) / tiledt + A  # CVPR09, eq.16\n\n\ndef dehaze(im, tmin=0.2, Amax=220, w=15, p=0.0001,\n           omega=0.95, guided=True, r=40, eps=1e-3):\n    \"\"\"Dehaze the given RGB image.\n\n    Parameters\n    ----------\n    im:     the Image object of the RGB image\n    guided: refine the dehazing with guided filter or not\n    other parameters are the same as `dehaze_raw`\n\n    Return\n    ----------\n    (dark, rawt, refinedt, rawrad, rerad)\n    Images for dark channel prior, raw transmission estimate,\n    refiend transmission estimate, recovered radiance with raw t,\n    recovered radiance with refined t.\n    \"\"\"\n    I = np.asarray(im, dtype=np.float64)\n    Idark, A, rawt, refinedt = dehaze_raw(I, tmin, Amax, w, p,\n                                          omega, guided, r, eps)\n    white = np.full_like(Idark, L - 1)\n\n    def to_img(raw):\n        # threshold to [0, L-1]\n        cut = np.maximum(np.minimum(raw, L - 1), 0).astype(np.uint8)\n\n        if len(raw.shape) == 3:\n            print('Range for each channel:')\n            for ch in range(3):\n                print('[%.2f, %.2f]' % (raw[:, :, ch].max(), raw[:, :, ch].min()))\n            return Image.fromarray(cut)\n        else:\n            return Image.fromarray(cut)\n\n    return [to_img(raw) for raw in (Idark, white * rawt, white * refinedt,\n                                    get_radiance(I, A, rawt),\n                                    get_radiance(I, A, refinedt))]\n", "meta": {"hexsha": "331738b152b5ee3211162b591873fae812b1bfb5", "size": 6018, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/iodh/combined/dark-channel-prior-dehazing/src/dehaze.py", "max_stars_repo_name": "guanlongzhao/dehaze", "max_stars_repo_head_hexsha": "c76346584f8d76502aa854ad9d7e06135ca77bcf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2018-07-05T01:15:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-23T12:03:51.000Z", "max_issues_repo_path": "code/iodh/combined/dark-channel-prior-dehazing/src/dehaze.py", "max_issues_repo_name": "TAMU-VITA/dehaze", "max_issues_repo_head_hexsha": "c76346584f8d76502aa854ad9d7e06135ca77bcf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-01-12T07:08:20.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-02T11:13:58.000Z", "max_forks_repo_path": "code/iodh/combined/dark-channel-prior-dehazing/src/dehaze.py", "max_forks_repo_name": "guanlongzhao/dehaze", "max_forks_repo_head_hexsha": "c76346584f8d76502aa854ad9d7e06135ca77bcf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-07-06T02:19:31.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-02T15:21:43.000Z", "avg_line_length": 32.5297297297, "max_line_length": 82, "alphanum_fraction": 0.5837487537, "include": true, "reason": "import numpy", "num_tokens": 1751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.19956023315356075}}
{"text": "\"\"\"\n\nSource.py\n\nAuthor: Jordan Mirocha\nAffiliation: University of Colorado at Boulder\nCreated on: Sun Jul 22 16:28:08 2012\n\nDescription: Initialize a radiation source.\n\n\"\"\"\n\nimport re, os\nimport numpy as np\nfrom scipy.integrate import quad\nfrom ..util import ParameterFile\nfrom ..physics.Hydrogen import Hydrogen\nfrom ..physics.Cosmology import Cosmology\nfrom ..physics.Constants import erg_per_ev, E_LL\nfrom ..static.IntegralTables import IntegralTable\nfrom ..static.InterpolationTables import LookupTable\nfrom ..util.SetDefaultParameterValues import SourceParameters, \\\n    CosmologyParameters\nfrom ..physics.CrossSections import PhotoIonizationCrossSection as sigma_E\n\ntry:\n    import h5py\nexcept ImportError:\n    pass\n\nnp.seterr(all='ignore')   # exp overflow occurs when integrating BB\n                          # will return 0 as it should for x large\n\ncosmo_pars = CosmologyParameters()\n\nclass Source(object):\n    def __init__(self, grid=None, logN=None, init_tabs=True):\n        \"\"\" \n        Initialize a radiation source object. \n        \n        ..note:: This is inherited by all other ares.sources classes.\n    \n        Parameters\n        ----------\n        grid: rt1d.static.Grid.Grid instance\n        logN: column densities over which to tabulate integral quantities\n        \n        \"\"\"    \n        \n        # Update cosmological parameters\n        # Why is this necessary? J.M.12.27.2015\n        for par in cosmo_pars:\n            if par in self.pf:\n                continue\n        \n            self.pf[par] = cosmo_pars[par]\n                \n        # Modify parameter file if spectrum_file provided\n        #self._load_spectrum()        \n            \n        # Correct emission limits if none were provided\n        self.Emin = self.pf['source_Emin']\n        self.Emax = self.pf['source_Emax']\n        self.logEmin = np.log10(self.Emin)\n        self.logEmax = np.log10(self.Emax)\n                \n        if self.pf['source_EminNorm'] == None:\n            self.pf['source_EminNorm'] = self.pf['source_Emin']\n        if self.pf['source_EmaxNorm'] == None:\n            self.pf['source_EmaxNorm'] = self.pf['source_Emax']\n            \n        self.EminNorm = self.pf['source_EminNorm']\n        self.EmaxNorm = self.pf['source_EmaxNorm']    \n               \n        # Number of frequencies\n        #if self.discrete:\n        #    self.E = np.array(self.pf['source_E'])\n        #    self.LE = np.array(self.pf['source_LE'])\n        #    self.Nfreq = len(self.E)\n        #    \n        #if self.src._name == 'DiffuseSource':\n        #    self.ionization_rate = self.src.ionization_rate\n        #    self.secondary_ionization_rate = self.src.secondary_ionization_rate\n        #    self.heating_rate = self.src.heating_rate\n        #        \n        #self.Lbol = self.Lbol0 = self.BolometricLuminosity(0.0)\n\n        # Create lookup tables for integral quantities\n        if init_tabs and grid is not None:\n            self._create_integral_table(logN=logN)\n    \n    @property\n    def cosm(self):\n        if not hasattr(self, '_cosm'):\n            if self.grid is None:\n                self._cosm = Cosmology(\n                    omega_m_0=self.pf['omega_m_0'], \n                    omega_l_0=self.pf['omega_l_0'], \n                    omega_b_0=self.pf['omega_b_0'],  \n                    hubble_0=self.pf['hubble_0'],  \n                    helium_by_number=self.pf['helium_by_number'], \n                    cmb_temp_0=self.pf['cmb_temp_0'], \n                    approx_highz=self.pf['approx_highz'], \n                    sigma_8=self.pf['sigma_8'], \n                    primordial_index=self.pf['primordial_index'])\n            else:\n                self._cosm = self.grid.cosm\n        \n        return self._cosm\n    \n    @property\n    def multi_freq(self):\n        if not hasattr(self, '_multi_freq'):\n            self._multi_freq = self.discrete and not self.pf['source_multigroup']\n            \n        return self._multi_freq    \n    \n    @property        \n    def multi_group(self):        \n        if not hasattr(self, '_multi_group'):\n            self._multi_group = self.discrete and self.pf['source_multigroup']\n        \n        return self._multi_group\n            \n    @property\n    def ionizing(self):\n        # See if source emits ionizing photons\n        # Should also be function of absorbers\n        if not hasattr(self, '_ionizing'):\n            self._ionizing = self.pf['source_Emax'] > E_LL\n        \n        return self._ionizing\n    \n    @property\n    def grid(self):\n        if not hasattr(self, '_grid'):\n            self._grid = None\n        \n        return self._grid\n            \n    @grid.setter\n    def grid(self, value):\n        self._grid = value\n    \n    @property \n    def discrete(self):\n        if not hasattr(self, '_discrete'):\n            self._discrete = (self.pf['source_E'] != None) #\\\n                  #or self.pf['optically_thin']\n        \n        return self._discrete\n        \n    @property\n    def continuous(self):\n        if not hasattr(self, '_continuous'):\n            self._continuous = not self.discrete\n            \n        return self._continuous\n\n    @property\n    def hydr(self):\n        if not hasattr(self, '_hydr'):\n            self._hydr = None\n                \n        return self._hydr\n\n    @hydr.setter\n    def hydr(self, value):\n        self._hydr = value\n\n    @property\n    def frec(self):\n        \"\"\"\n        Compute average recycling fraction (i.e., spectrum-weighted frec).\n        \"\"\"    \n        \n        if self.hydr is None:\n            return None\n        \n        n = np.arange(2, self.hydr.nmax)\n        En = np.array(map(self.hydr.ELyn, n))\n        In = np.array(map(self.Spectrum, En)) / En\n        fr = np.array(map(self.hydr.frec, n))\n        \n        return np.sum(fr * In) / np.sum(In)\n\n    @property\n    def intrinsic_hardening(self):\n        if not hasattr(self, '_intrinsic_hardening'): \n            if 'source_hardening' in self.pf:           \n                self._intrinsic_hardening = \\\n                    self.pf['source_hardening'] == 'intrinsic'\n            else:\n                self._intrinsic_hardening = False\n    \n        return self._intrinsic_hardening    \n        \n    def _hardening_factor(self, E):\n        return np.exp(-10.**self.logN \\\n            * (sigma_E(E, 0) + self.cosm.y * sigma_E(E, 1)))\n    \n    @property\n    def logN(self):\n        if not hasattr(self, '_logN'):\n            if 'source_logN' in self.pf:\n                self._logN = self.pf['source_logN']\n            else:\n                self._logN = -np.inf\n                \n        return self._logN\n        \n    @property\n    def _normL(self):\n        if not hasattr(self, '_normL_'):\n            if self.intrinsic_hardening:\n                self._normL_ = 1. / quad(self._Intensity,\n                    self.pf['source_EminNorm'], self.pf['source_EmaxNorm'])[0]\n            else:    \n                integrand = lambda EE: self._Intensity(EE) / self._hardening_factor(EE)\n                self._normL_ = 1. / quad(integrand,\n                    self.pf['source_EminNorm'], self.pf['source_EmaxNorm'])[0]\n                \n        return self._normL_          \n              \n    #def _load_spectrum(self):\n    #    \"\"\" Modify a few parameters if spectrum_file provided. \"\"\"\n    #    \n    #    fn = self.pf['spectrum_file']\n    #    \n    #    if fn is None:\n    #        return\n    #        \n    #    # Read spectrum - expect hdf5 with (at least) E, LE, and t datasets.    \n    #    if re.search('.hdf5', fn):    \n    #        f = h5py.File(fn)\n    #        try:\n    #            self.pf['tables_times'] = f['t'].value\n    #        except:\n    #            self.pf['tables_times'] = None\n    #            self.pf['spectrum_evolving'] = False\n    #                \n    #        self.pf['spectrum_E'] = f['E'].value\n    #        self.pf['spectrum_LE'] = f['LE'].value\n    #        f.close()\n    #        \n    #        if len(self.pf['spectrum_LE'].shape) > 1 \\\n    #            and not self.pf['spectrum_evolving']:\n    #            self.pf['spectrum_LE'] = self.pf['spectrum_LE'][0]\n    #    else: \n    #        spec = readtab(fn)\n    #        if len(spec) == 2:\n    #            self.pf['spectrum_E'], self.pf['spectrum_LE'] = spec\n    #        else:\n    #            self.pf['spectrum_E'], self.pf['spectrum_LE'], \\\n    #                self.pf['spectrum_t'] = spec\n                    \n    @property\n    def tables(self):\n        if not hasattr(self, '_tables'):\n            self._create_integral_table()\n        return self._tables    \n    \n    @property\n    def tab(self):\n        if not hasattr(self, '_tab'):\n            self._create_integral_table()\n        return self._tab     \n        \n    @property\n    def tabs(self):\n        if not hasattr(self, '_tabs'):\n            self._create_integral_table()\n        return self._tabs\n        \n    def _create_integral_table(self, logN=None):\n        \"\"\"\n        Take tables and create interpolation functions.\n        \"\"\"\n        \n        if self.discrete:\n            return\n            \n        if self._name == 'diffuse':\n            return\n        \n        if self.pf['source_table'] is None:\n            # Overide defaults if supplied - this is dangerous\n            if logN is not None:\n                self.pf.update({'tables_dlogN': [np.diff(tmp) for tmp in logN]})\n                self.pf.update({'tables_logNmin': [np.min(tmp) for tmp in logN]})\n                self.pf.update({'tables_logNmax': [np.max(tmp) for tmp in logN]})\n\n            # Tabulate away!            \n            self._tab = IntegralTable(self.pf, self, self.grid, logN)\n            self._tabs = self.tab.TabulateRateIntegrals()\n        else:\n            self._tab = IntegralTable(self.pf, self, self.grid, logN)\n            self._tabs = self.tab.load(self.pf['source_table'])\n        \n        self._setup_interp()\n        \n    def _setup_interp(self):            \n        self._tables = {}\n        for tab in self.tabs:\n            self._tables[tab] = \\\n                LookupTable(self.pf, tab, self.tab.logN, self.tabs[tab], \n                    self.tab.logx, self.tab.t)                 \n    \n    @property\n    def sigma(self):\n        \"\"\"\n        Compute bound-free absorption cross-section for all frequencies.\n        \"\"\"    \n        if not self.discrete:\n            return None\n        if not hasattr(self, '_sigma_all'):\n            self._sigma_all = np.array(map(sigma_E, self.E))\n        \n        return self._sigma_all\n        \n    @property\n    def Qdot(self):\n        \"\"\"\n        Returns number of photons emitted (s^-1) at all frequencies.\n        \"\"\"    \n        if not hasattr(self, '_Qdot_all'):\n            self._Qdot_all = self.Lbol * self.LE / self.E / erg_per_ev\n        \n        return self._Qdot_all\n        \n    @property\n    def hnu_bar(self):\n        \"\"\"\n        Average ionizing (per absorber) photon energy in eV.\n        \"\"\"\n        if not hasattr(self, '_hnu_bar_all'):\n            self._hnu_bar_all = np.zeros_like(self.grid.zeros_absorbers)\n            self._qdot_bar_all = np.zeros_like(self.grid.zeros_absorbers)\n            for i, absorber in enumerate(self.grid.absorbers):\n                self._hnu_bar_all[i], self._qdot_bar_all[i] = \\\n                    self._FrequencyAveragedBin(absorber=absorber)\n            \n        return self._hnu_bar_all\n    \n    def AveragePhotonEnergy(self, Emin, Emax):\n        \"\"\"\n        Return average photon energy in supplied band.\n        \"\"\"\n        \n        integrand = lambda EE: self.Spectrum(EE) * EE\n        norm = lambda EE: self.Spectrum(EE)\n        \n        return quad(integrand, Emin, Emax)[0] / quad(norm, Emin, Emax)[0]\n        \n    @property\n    def qdot_bar(self):\n        \"\"\"\n        Average ionizing photon luminosity (per absorber) in s^-1.\n        \"\"\"\n        if not hasattr(self, '_qdot_bar_all'):\n            hnu_bar = self.hnu_bar\n            \n        return self._qdot_bar_all   \n    \n    @property\n    def sigma_bar(self):\n        \"\"\"\n        Frequency averaged cross section (single bandpass).\n        \"\"\"\n        if not hasattr(self, '_sigma_bar_all'):\n            self._sigma_bar_all = np.zeros_like(self.grid.zeros_absorbers)\n            for i, absorber in enumerate(self.grid.absorbers):\n                integrand = lambda x: self.Spectrum(x) \\\n                    * self.grid.bf_cross_sections[absorber](x) / x\n                    \n                self._sigma_bar_all[i] = self.Lbol \\\n                    * quad(integrand, self.grid.ioniz_thresholds[absorber], \n                      self.Emax)[0] / self.qdot_bar[i] / erg_per_ev\n            \n        return self._sigma_bar_all\n    \n    @property\n    def sigma_tilde(self):\n        if not hasattr(self, '_sigma_tilde_all'):\n            self._sigma_tilde_all = np.zeros_like(self.grid.zeros_absorbers)\n            for i, absorber in enumerate(self.grid.absorbers):\n                integrand = lambda x: self.Spectrum(x) \\\n                    * self.grid.bf_cross_sections[absorber](x)\n                self._sigma_tilde_all[i] = quad(integrand, \n                    self.grid.ioniz_thresholds[absorber], self.Emax)[0] \\\n                    / self.fLbol_ionizing[i]\n        \n        return self._sigma_tilde_all\n        \n    @property\n    def fLbol_ionizing(self):\n        \"\"\"\n        Fraction of bolometric luminosity emitted above all ionization\n        thresholds.\n        \"\"\"\n        if not hasattr(self, '_fLbol_ioniz_all'):\n            self._fLbol_ioniz_all = np.zeros_like(self.grid.zeros_absorbers)\n            for i, absorber in enumerate(self.grid.absorbers):\n                self._fLbol_ioniz_all[i] = quad(self.Spectrum, \n                    self.grid.ioniz_thresholds[absorber], self.Emax)[0]\n                    \n        return self._fLbol_ioniz_all\n        \n    @property\n    def Gamma_bar(self):\n        \"\"\"\n        Return ionization rate (as a function of radius) assuming optical \n        depth to cells and of cells is small.\n        \"\"\"\n        if not hasattr(self, '_Gamma_bar_all'):\n            self._Gamma_bar_all = \\\n                np.zeros([self.grid.dims, self.grid.N_absorbers])\n            for i, absorber in enumerate(self.grid.absorbers):\n                self._Gamma_bar_all[..., i] = self.Lbol * self.sigma_bar[i] \\\n                    * self.fLbol_ionizing[i] / 4. / np.pi / self.grid.r_mid**2 \\\n                    / self.hnu_bar[i] / erg_per_ev\n                    \n        return self._Gamma_bar_all\n    \n    @property\n    def gamma_bar(self):\n        \"\"\"\n        Return ionization rate (as a function of radius) assuming optical \n        depth to cells and of cells is small.\n        \"\"\"\n        if not hasattr(self, '_gamma_bar_all'):\n            self._gamma_bar_all = \\\n                np.zeros([self.grid.dims, self.grid.N_absorbers, \n                    self.grid.N_absorbers])\n                    \n            if not self.pf['secondary_ionization']:\n                return self._gamma_bar_all\n                    \n            for i, absorber in enumerate(self.grid.absorbers):\n                for j, otherabsorber in enumerate(self.grid.absorbers):\n                    self._gamma_bar_all[..., i, j] = self.Gamma_bar[j] \\\n                        * (self.hnu_bar[j] * self.sigma_tilde[j] \\\n                        /  self.hnu_bar[i] / self.sigma_bar[j] \\\n                        - self.grid.ioniz_thresholds[otherabsorber] \\\n                        / self.grid.ioniz_thresholds[absorber])\n                    \n        return self._gamma_bar_all\n    \n    @property\n    def Heat_bar(self):\n        \"\"\"\n        Return ionization rate (as a function of radius) assuming optical \n        depth to cells and of cells is small.\n        \"\"\"\n        if not hasattr(self, '_Heat_bar_all'):\n            self._Heat_bar_all = \\\n                np.zeros([self.grid.dims, self.grid.N_absorbers])\n            for i, absorber in enumerate(self.grid.absorbers):\n                self._Heat_bar_all[..., i] = self.Gamma_bar[..., i] \\\n                    * erg_per_ev * (self.hnu_bar[i] * self.sigma_tilde[i] \\\n                    / self.sigma_bar[i] - self.grid.ioniz_thresholds[absorber])\n                    \n        return self._Heat_bar_all\n                                \n    def IonizingPhotonLuminosity(self, t=0, bin=None):\n        \"\"\"\n        Return Qdot (photons / s) for this source at energy E.\n        \"\"\"\n        \n        if self.pf['source_type'] in [0, 1, 2]:\n            return self.Qdot[bin]\n        else:\n            # Currently only BHs have a time-varying bolometric luminosity\n            return self.BolometricLuminosity(t) * self.LE[bin] / self.E[bin] / erg_per_ev          \n              \n    #def _Intensity(self, E, i, Type, t=0, absorb=True):\n    #    \"\"\"\n    #    Return quantity *proportional* to fraction of bolometric luminosity emitted\n    #    at photon energy E.  Normalization handled separately.\n    #    \"\"\"\n    #    \n    #    Lnu = self.src._Intensity(E, i, Type, t=t)\n    #    \n    #    # Apply absorbing column\n    #    if self.SpectrumPars['logN'][i] > 0 and absorb:\n    #        return Lnu * np.exp(-10.**self.SpectrumPars['logN'][i] \\\n    #            * (sigma_E(E, 0) + y * sigma_E(E, 1)))   \n    #    else:\n    #        return Lnu     \n    #            \n    def Spectrum(self, E, t=0.0):\n        r\"\"\"\n        Return fraction of bolometric luminosity emitted at energy E.\n        \n        Elsewhere denoted as :math:`I_{\\nu}`, normalized such that\n        :math:`\\int I_{\\nu} d\\nu = 1`\n        \n        Parameters\n        ----------\n        E: float\n            Emission energy in eV\n        t: float\n            Time in seconds since source turned on.   \n        i: int\n            Index of component to include. If None, includes contribution\n            from all components.\n                    \n        Returns\n        -------\n        Fraction of bolometric luminosity emitted at E in units of \n        eV\\ :sup:`-1`\\.\n\n        \"\"\"   \n                \n        return self._normL * self._Intensity(E, t=t)\n        \n    def BolometricLuminosity(self, t=0.0, M=None):\n        \"\"\"\n        Returns the bolometric luminosity of a source in units of erg/s.  \n        For accreting black holes, the bolometric luminosity will increase \n        with time, hence the optional 't' and 'M' arguments.\n        \"\"\"        \n        \n        if self._name == 'bh':\n            return self.Luminosity(t, M)\n        else:\n            return self.Luminosity(t)\n                \n    def _FrequencyAveragedBin(self, absorber='h_1', Emin=None, Emax=None,\n        energy_weighted=False):\n        \"\"\"\n        Bolometric luminosity / number of ionizing photons in spectrum in bandpass\n        spanning interval (Emin, Emax). Returns mean photon energy and number of \n        ionizing photons in band.\n        \"\"\"     \n        \n        if Emin is None:\n            Emin = max(self.grid.ioniz_thresholds[absorber], self.Emin)\n        if Emax is None:\n            Emax = self.Emax\n            \n        if energy_weighted:\n            f = lambda x: x\n        else:\n            f = lambda x: 1.0    \n            \n        L = self.Lbol * quad(lambda x: self.Spectrum(x) * f(x), Emin, Emax)[0] \n        Q = self.Lbol * quad(lambda x: self.Spectrum(x) * f(x) / x, Emin, \n            Emax)[0] / erg_per_ev\n                        \n        return L / Q / erg_per_ev, Q            \n\n    def dump(self, fn, E, clobber=False):\n        \"\"\"\n        Write SED out to file.\n        \n        Parameters\n        ----------\n        fn : str\n            Filename, suffix determines type. If 'hdf5' or 'h5' will write \n            to HDF5 file, otherwise, to ASCII.\n        E : np.ndarray\n            Array of photon energies at which to sample SED. Units = eV.\n        \n        \"\"\"\n\n        if os.path.exists(fn) and (clobber == False):\n            raise OSError('%s exists!')\n\n        if re.search('.hdf5', fn) or re.search('.h5', fn):\n            out = 'hdf5'\n        else:\n            out = 'ascii'\n            \n        LE = map(self.Spectrum, E)    \n            \n        if out == 'hdf5':\n            f = h5py.File(fn, 'w')    \n            f.create_dataset('E', data=E)\n            f.create_dataset('LE', data=LE)\n            f.close()\n        else:\n            f = open(fn, 'w')\n            print >> f, \"# E     LE\"\n            for i, nrg in enumerate(E):\n                print >> f, \"%.8e %.8e\" % (nrg, LE[i])\n            f.close()    \n    \n        print \"Wrote %s.\" % fn    \n    \n    def sed_name(self, i=0):\n        \"\"\"\n        Return name of output file based on SED properties.\n        \"\"\"\n            \n        name = '%s_logM_%.2g_Gamma_%.3g_fsc_%.3g_logE_%.2g-%.2g' % \\\n            (self.SpectrumPars['type'][i], np.log10(self.src.M0), \n             self.src.spec_pars['alpha'][i], \n             self.src.spec_pars['fsc'][i], self.logEmin, self.logEmax)\n\n        return name\n        \n        \n                        \n        \n        ", "meta": {"hexsha": "b4049a25c4dea25e177e6ce069e34094942d55de", "size": 20836, "ext": "py", "lang": "Python", "max_stars_repo_path": "ares/sources/Source.py", "max_stars_repo_name": "astrojhgu/ares", "max_stars_repo_head_hexsha": "42008c8e4bf79f0b000cc833e02a86510bce7611", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-04T15:13:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-04T15:13:18.000Z", "max_issues_repo_path": "ares/sources/Source.py", "max_issues_repo_name": "astrojhgu/ares", "max_issues_repo_head_hexsha": "42008c8e4bf79f0b000cc833e02a86510bce7611", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ares/sources/Source.py", "max_forks_repo_name": "astrojhgu/ares", "max_forks_repo_head_hexsha": "42008c8e4bf79f0b000cc833e02a86510bce7611", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3828382838, "max_line_length": 99, "alphanum_fraction": 0.5262046458, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.19956022523869069}}
{"text": "# Copyright 2018-2020 Xanadu Quantum Technologies Inc.\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n#     http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"This module contains functions to read the structure of molecules, build a Hartree-Fock state,\nbuild an active space and generate single and double excitations.\n\"\"\"\n# pylint: disable=too-many-locals\nimport os\nfrom shutil import copyfile\n\nfrom pennylane import numpy as np\n\n# Bohr-Angstrom correlation coefficient (https://physics.nist.gov/cgi-bin/cuu/Value?bohrrada0)\nbohr_angs = 0.529177210903\n\n\ndef read_structure(filepath, outpath=\".\"):\n    r\"\"\"Read the structure of the polyatomic system from a file and returns\n    a list with the symbols of the atoms in the molecule and a 1D array\n    with their positions :math:`[x_1, y_1, z_1, x_2, y_2, z_2, \\dots]` in\n    atomic units (Bohr radius = 1).\n\n    The atomic coordinates in the file must be in Angstroms.\n    The `xyz <https://en.wikipedia.org/wiki/XYZ_file_format>`_ format is supported. Additionally,\n    the new file ``structure.xyz``, containing the input geometry, is created in a directory with\n    path given by ``outpath``.\n\n    Args:\n        filepath (str): name of the molecular structure file in the working directory\n            or the absolute path to the file if it is located in a different folder\n        outpath (str): path to the output directory\n\n    Returns:\n        tuple[list, array]: symbols of the atoms in the molecule and a 1D array with their\n        positions in atomic units.\n\n    **Example**\n\n    >>> symbols, coordinates = read_structure('h2.xyz')\n    >>> print(symbols, coordinates)\n    ['H', 'H'] [0.    0.   -0.66140414    0.    0.    0.66140414]\n    \"\"\"\n    file_in = filepath.strip()\n    file_out = os.path.join(outpath, \"structure.xyz\")\n\n    copyfile(file_in, file_out)\n\n    symbols = []\n    coordinates = []\n    with open(file_out, encoding=\"utf-8\") as f:\n        for line in f.readlines()[2:]:\n            symbol, x, y, z = line.split()\n            symbols.append(symbol)\n            coordinates.append(float(x))\n            coordinates.append(float(y))\n            coordinates.append(float(z))\n\n    return symbols, np.array(coordinates) / bohr_angs\n\n\ndef active_space(electrons, orbitals, mult=1, active_electrons=None, active_orbitals=None):\n    r\"\"\"Build the active space for a given number of active electrons and active orbitals.\n\n    Post-Hartree-Fock (HF) electron correlation methods expand the many-body wave function\n    as a linear combination of Slater determinants, commonly referred to as configurations.\n    This configurations are generated by exciting electrons from the occupied to the\n    unoccupied HF orbitals as sketched in the figure below. Since the number of configurations\n    increases combinatorially with the number of electrons and orbitals this expansion can be\n    truncated by defining an active space.\n\n    The active space is created by classifying the HF orbitals as core, active and\n    external orbitals:\n\n    - Core orbitals are always occupied by two electrons\n    - Active orbitals can be occupied by zero, one, or two electrons\n    - The external orbitals are never occupied\n\n    |\n\n    .. figure:: ../../_static/qchem/sketch_active_space.png\n        :align: center\n        :width: 50%\n\n    |\n\n    .. note::\n        The number of active *spin*-orbitals ``2*active_orbitals`` determines the number of\n        qubits required to perform the quantum simulations of the electronic structure\n        of the many-electron system.\n\n    Args:\n        electrons (int): total number of electrons\n        orbitals (int): total number of orbitals\n        mult (int): Spin multiplicity :math:`\\mathrm{mult}=N_\\mathrm{unpaired} + 1` for\n            :math:`N_\\mathrm{unpaired}` unpaired electrons occupying the HF orbitals.\n            Possible values for ``mult`` are :math:`1, 2, 3, \\ldots`. If not specified,\n            a closed-shell HF state is assumed.\n        active_electrons (int): Number of active electrons. If not specified, all electrons\n            are treated as active.\n        active_orbitals (int): Number of active orbitals. If not specified, all orbitals\n            are treated as active.\n\n    Returns:\n        tuple: lists of indices for core and active orbitals\n\n    **Example**\n\n    >>> electrons = 4\n    >>> orbitals = 4\n    >>> core, active = active_space(electrons, orbitals, active_electrons=2, active_orbitals=2)\n    >>> print(core) # core orbitals\n    [0]\n    >>> print(active) # active orbitals\n    [1, 2]\n    \"\"\"\n    # pylint: disable=too-many-branches\n\n    if active_electrons is None:\n        ncore_orbs = 0\n        core = []\n    else:\n        if active_electrons <= 0:\n            raise ValueError(\n                f\"The number of active electrons ({active_electrons}) \" f\"has to be greater than 0.\"\n            )\n\n        if active_electrons > electrons:\n            raise ValueError(\n                f\"The number of active electrons ({active_electrons}) \"\n                f\"can not be greater than the total \"\n                f\"number of electrons ({electrons}).\"\n            )\n\n        if active_electrons < mult - 1:\n            raise ValueError(\n                f\"For a reference state with multiplicity {mult}, \"\n                f\"the number of active electrons ({active_electrons}) should be \"\n                f\"greater than or equal to {mult - 1}.\"\n            )\n\n        if mult % 2 == 1:\n            if active_electrons % 2 != 0:\n                raise ValueError(\n                    f\"For a reference state with multiplicity {mult}, \"\n                    f\"the number of active electrons ({active_electrons}) should be even.\"\n                )\n        else:\n            if active_electrons % 2 != 1:\n                raise ValueError(\n                    f\"For a reference state with multiplicity {mult}, \"\n                    f\"the number of active electrons ({active_electrons}) should be odd.\"\n                )\n\n        ncore_orbs = (electrons - active_electrons) // 2\n        core = list(range(ncore_orbs))\n\n    if active_orbitals is None:\n        active = list(range(ncore_orbs, orbitals))\n    else:\n        if active_orbitals <= 0:\n            raise ValueError(\n                f\"The number of active orbitals ({active_orbitals}) \" f\"has to be greater than 0.\"\n            )\n\n        if ncore_orbs + active_orbitals > orbitals:\n            raise ValueError(\n                f\"The number of core ({ncore_orbs}) + active orbitals ({active_orbitals}) cannot \"\n                f\"be greater than the total number of orbitals ({orbitals})\"\n            )\n\n        homo = (electrons + mult - 1) / 2\n        if ncore_orbs + active_orbitals <= homo:\n            raise ValueError(\n                f\"For n_active_orbitals={active_orbitals}, there are no virtual orbitals \"\n                f\"in the active space.\"\n            )\n\n        active = list(range(ncore_orbs, ncore_orbs + active_orbitals))\n\n    return core, active\n\n\ndef excitations(electrons, orbitals, delta_sz=0):\n    r\"\"\"Generate single and double excitations from a Hartree-Fock reference state.\n\n    Single and double excitations can be generated by acting with the operators\n    :math:`\\hat T_1` and :math:`\\hat T_2` on the Hartree-Fock reference state:\n\n    .. math::\n\n        && \\hat{T}_1 = \\sum_{r \\in \\mathrm{occ} \\\\ p \\in \\mathrm{unocc}}\n        \\hat{c}_p^\\dagger \\hat{c}_r \\\\\n        && \\hat{T}_2 = \\sum_{r>s \\in \\mathrm{occ} \\\\ p>q \\in\n        \\mathrm{unocc}} \\hat{c}_p^\\dagger \\hat{c}_q^\\dagger \\hat{c}_r \\hat{c}_s.\n\n\n    In the equations above the indices :math:`r, s` and :math:`p, q` run over the\n    occupied (occ) and unoccupied (unocc) *spin* orbitals and :math:`\\hat c` and\n    :math:`\\hat c^\\dagger` are the electron annihilation and creation operators,\n    respectively.\n\n    |\n\n    .. figure:: ../../_static/qchem/sd_excitations.png\n        :align: center\n        :width: 80%\n\n    |\n\n    Args:\n        electrons (int): Number of electrons. If an active space is defined, this\n            is the number of active electrons.\n        orbitals (int): Number of *spin* orbitals. If an active space is defined,\n            this is the number of active spin-orbitals.\n        delta_sz (int): Specifies the selection rules ``sz[p] - sz[r] = delta_sz`` and\n            ``sz[p] + sz[p] - sz[r] - sz[s] = delta_sz`` for the spin-projection ``sz`` of\n            the orbitals involved in the single and double excitations, respectively.\n            ``delta_sz`` can take the values :math:`0`, :math:`\\pm 1` and :math:`\\pm 2`.\n\n    Returns:\n        tuple(list, list): lists with the indices of the spin orbitals involved in the\n        single and double excitations\n\n    **Example**\n\n    >>> electrons = 2\n    >>> orbitals = 4\n    >>> singles, doubles = excitations(electrons, orbitals)\n    >>> print(singles)\n    [[0, 2], [1, 3]]\n    >>> print(doubles)\n    [[0, 1, 2, 3]]\n    \"\"\"\n\n    if not electrons > 0:\n        raise ValueError(\n            f\"The number of active electrons has to be greater than 0 \\n\"\n            f\"Got n_electrons = {electrons}\"\n        )\n\n    if orbitals <= electrons:\n        raise ValueError(\n            f\"The number of active spin-orbitals ({orbitals}) \"\n            f\"has to be greater than the number of active electrons ({electrons}).\"\n        )\n\n    if delta_sz not in (0, 1, -1, 2, -2):\n        raise ValueError(\n            f\"Expected values for 'delta_sz' are 0, +/- 1 and +/- 2 but got ({delta_sz}).\"\n        )\n\n    # define the spin projection 'sz' of the single-particle states\n    sz = np.array([0.5 if (i % 2 == 0) else -0.5 for i in range(orbitals)])\n\n    singles = [\n        [r, p]\n        for r in range(electrons)\n        for p in range(electrons, orbitals)\n        if sz[p] - sz[r] == delta_sz\n    ]\n\n    doubles = [\n        [s, r, q, p]\n        for s in range(electrons - 1)\n        for r in range(s + 1, electrons)\n        for q in range(electrons, orbitals - 1)\n        for p in range(q + 1, orbitals)\n        if (sz[p] + sz[q] - sz[r] - sz[s]) == delta_sz\n    ]\n\n    return singles, doubles\n\n\ndef hf_state(electrons, orbitals):\n    r\"\"\"Generate the occupation-number vector representing the Hartree-Fock state.\n\n    The many-particle wave function in the Hartree-Fock (HF) approximation is a `Slater determinant\n    <https://en.wikipedia.org/wiki/Slater_determinant>`_. In Fock space, a Slater determinant\n    for :math:`N` electrons is represented by the occupation-number vector:\n\n    .. math::\n\n        \\vert {\\bf n} \\rangle = \\vert n_1, n_2, \\dots, n_\\mathrm{orbs} \\rangle,\n        n_i = \\left\\lbrace \\begin{array}{ll} 1 & i \\leq N \\\\ 0 & i > N \\end{array} \\right.,\n\n    where :math:`n_i` indicates the occupation of the :math:`i`-th orbital.\n\n    Args:\n        electrons (int): Number of electrons. If an active space is defined, this\n            is the number of active electrons.\n        orbitals (int): Number of *spin* orbitals. If an active space is defined,\n            this is the number of active spin-orbitals.\n\n    Returns:\n        array: NumPy array containing the vector :math:`\\vert {\\bf n} \\rangle`\n\n    **Example**\n\n    >>> state = hf_state(2, 6)\n    >>> print(state)\n    [1 1 0 0 0 0]\n    \"\"\"\n\n    if electrons <= 0:\n        raise ValueError(\n            f\"The number of active electrons has to be larger than zero; \"\n            f\"got 'electrons' = {electrons}\"\n        )\n\n    if electrons > orbitals:\n        raise ValueError(\n            f\"The number of active orbitals cannot be smaller than the number of active electrons;\"\n            f\" got 'orbitals'={orbitals} < 'electrons'={electrons}\"\n        )\n\n    state = np.where(np.arange(orbitals) < electrons, 1, 0)\n\n    return np.array(state)\n\n\ndef excitations_to_wires(singles, doubles, wires=None):\n    r\"\"\"Map the indices representing the single and double excitations\n    generated with the function :func:`~.excitations` to the wires that\n    the Unitary Coupled-Cluster (UCCSD) template will act on.\n\n    Args:\n        singles (list[list[int]]): list with the indices ``r``, ``p`` of the two qubits\n            representing the single excitation\n            :math:`\\vert r, p \\rangle = \\hat{c}_p^\\dagger \\hat{c}_r \\vert \\mathrm{HF}\\rangle`\n        doubles (list[list[int]]): list with the indices ``s``, ``r``, ``q``, ``p`` of the four\n            qubits representing the double excitation\n            :math:`\\vert s, r, q, p \\rangle = \\hat{c}_p^\\dagger \\hat{c}_q^\\dagger\n            \\hat{c}_r \\hat{c}_s \\vert \\mathrm{HF}\\rangle`\n        wires (Iterable[Any]): Wires of the quantum device. If None, will use consecutive wires.\n\n    The indices :math:`r, s` and :math:`p, q` in these lists correspond, respectively, to the\n    occupied and virtual orbitals involved in the generated single and double excitations.\n\n    Returns:\n        tuple[list[list[Any]], list[list[list[Any]]]]: lists with the sequence of wires,\n        resulting from the single and double excitations, that the Unitary Coupled-Cluster\n        (UCCSD) template will act on.\n\n    **Example**\n\n    >>> singles = [[0, 2], [1, 3]]\n    >>> doubles = [[0, 1, 2, 3]]\n    >>> singles_wires, doubles_wires = excitations_to_wires(singles, doubles)\n    >>> print(singles_wires)\n    [[0, 1, 2], [1, 2, 3]]\n    >>> print(doubles_wires)\n    [[[0, 1], [2, 3]]]\n\n    >>> wires=['a0', 'b1', 'c2', 'd3']\n    >>> singles_wires, doubles_wires = excitations_to_wires(singles, doubles, wires=wires)\n    >>> print(singles_wires)\n    [['a0', 'b1', 'c2'], ['b1', 'c2', 'd3']]\n    >>> print(doubles_wires)\n    [[['a0', 'b1'], ['c2', 'd3']]]\n    \"\"\"\n\n    if (not singles) and (not doubles):\n        raise ValueError(\n            f\"'singles' and 'doubles' lists can not be both empty; \"\n            f\"got singles = {singles}, doubles = {doubles}\"\n        )\n\n    expected_shape = (2,)\n    for single_ in singles:\n        if np.array(single_).shape != expected_shape:\n            raise ValueError(\n                f\"Expected entries of 'singles' to be of shape (2,); got {np.array(single_).shape}\"\n            )\n\n    expected_shape = (4,)\n    for double_ in doubles:\n        if np.array(double_).shape != expected_shape:\n            raise ValueError(\n                f\"Expected entries of 'doubles' to be of shape (4,); got {np.array(double_).shape}\"\n            )\n\n    max_idx = 0\n    if singles:\n        max_idx = np.max(singles)\n    if doubles:\n        max_idx = max(np.max(doubles), max_idx)\n\n    if wires is None:\n        wires = range(max_idx + 1)\n    elif len(wires) != max_idx + 1:\n        raise ValueError(f\"Expected number of wires is {max_idx + 1}; got {len(wires)}\")\n\n    singles_wires = []\n    for r, p in singles:\n        s_wires = [wires[i] for i in range(r, p + 1)]\n        singles_wires.append(s_wires)\n\n    doubles_wires = []\n    for s, r, q, p in doubles:\n        d1_wires = [wires[i] for i in range(s, r + 1)]\n        d2_wires = [wires[i] for i in range(q, p + 1)]\n        doubles_wires.append([d1_wires, d2_wires])\n\n    return singles_wires, doubles_wires\n", "meta": {"hexsha": "a06088af91fa98adb5e6702c8cfd52b638b71b0d", "size": 15382, "ext": "py", "lang": "Python", "max_stars_repo_path": "pennylane/qchem/structure.py", "max_stars_repo_name": "therooler/pennylane", "max_stars_repo_head_hexsha": "88a8a5960a2ffd218a12f85ace632021eef2abf5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 539, "max_stars_repo_stars_event_min_datetime": "2018-11-13T08:45:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-27T18:17:16.000Z", "max_issues_repo_path": "pennylane/qchem/structure.py", "max_issues_repo_name": "therooler/pennylane", "max_issues_repo_head_hexsha": "88a8a5960a2ffd218a12f85ace632021eef2abf5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 588, "max_issues_repo_issues_event_min_datetime": "2018-11-14T10:21:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-28T06:27:14.000Z", "max_forks_repo_path": "pennylane/qchem/structure.py", "max_forks_repo_name": "therooler/pennylane", "max_forks_repo_head_hexsha": "88a8a5960a2ffd218a12f85ace632021eef2abf5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 165, "max_forks_repo_forks_event_min_datetime": "2018-11-13T18:58:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-27T17:18:17.000Z", "avg_line_length": 37.065060241, "max_line_length": 100, "alphanum_fraction": 0.6178650371, "include": true, "reason": "import numpy", "num_tokens": 4023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.3702254064929193, "lm_q1q2_score": 0.19954528745521383}}
{"text": "# -*- coding: utf-8 -*-\n\n\"\"\"Vector Field.\n\nThis is some documentation.\n\n\nAn example construction.\n\n.. todo::\n\n    store VECTORFIELD_REPRESENTATIONS keys as str, not the BaseRepresentation\n    class.\n\n\n\"\"\"\n\n__all__ = [\n    \"BaseVectorField\",\n    \"CartesianVectorField\",\n    \"CylindricalVectorField\",\n    \"SphericalVectorField\",\n    \"PhysicsSphericalVectorField\",\n]\n\n\n##############################################################################\n# IMPORTS\n\n# BUILT-IN\nimport functools\nimport inspect\nimport operator\nimport typing as T\n\n# THIRD PARTY\nimport astropy.coordinates as coord\nimport astropy.units as u\nimport numpy as np\nfrom astropy.coordinates.representation import (\n    REPRESENTATION_CLASSES as _REP_CLSs,\n)\nfrom astropy.coordinates.representation import (\n    BaseRepresentationOrDifferential,\n    _array2string,\n    _make_getter,\n)\nfrom erfa import ufunc as erfa_ufunc\n\n# PROJECT-SPECIFIC\nfrom .coordinates import resolve_framelike\nfrom discO.type_hints import (\n    FrameLikeType,\n    FrameType,\n    QuantityType,\n    RepresentationType,\n)\n\n##############################################################################\n# PARAMETERS\n\n_VECTORFIELD_CLASSES: T.Dict[str, object] = {}\nVECTORFIELD_REPRESENTATIONS: T.Dict[coord.BaseRepresentation, object] = {}\n\n\ndef _invalidate_psp_cls_hash():\n    global _PSP_HASH\n    _PSP_HASH = None\n\n\n##############################################################################\n# CODE\n##############################################################################\n\n\nclass BaseVectorField(BaseRepresentationOrDifferential):\n    \"\"\"Base Vector-Field.\n\n    Parameters\n    ----------\n    points : |Representation|\n    *args\n        The components\n    frame : frame-like or None (optional, keyword only)\n        The frame of the vector-field. None (default), does not attach a frame.\n    **kwargs\n        passed along\n\n    \"\"\"\n\n    def __init_subclass__(cls, **kwargs) -> None:\n        \"\"\"Set default ``attr_classes`` and component getters on a VectorField.\n        class BaseVectorField(BaseRepresentationOrDifferential):\n        For these, the components are those of the base representation prefixed\n        by 'd_', and the class is `~astropy.units.Quantity`.\n\n        \"\"\"\n        if not hasattr(cls, \"base_representation\"):\n            raise NotImplementedError(\n                \"VectorField representations must have a\"\n                '\"base_representation\" class attribute.',\n            )\n\n        # If not defined explicitly, create attr_classes.\n        if not hasattr(cls, \"attr_classes\"):\n            base_attr_classes = cls.base_representation.attr_classes\n            cls.attr_classes = {\n                \"vf_\" + c: u.Quantity for c in base_attr_classes\n            }\n\n        # Now check caches!\n        repr_name = cls.get_name()\n        if repr_name in _VECTORFIELD_CLASSES:\n            raise ValueError(\n                f\"VectorField class '{repr_name}' already exists.\",\n            )\n        elif cls.base_representation in VECTORFIELD_REPRESENTATIONS:\n            raise ValueError(\n                \"VectorField with representation \"\n                f\"'{cls.base_representation}' already exists.\",\n            )\n\n        _VECTORFIELD_CLASSES[repr_name] = cls\n        _invalidate_psp_cls_hash()\n\n        # add to representations dict\n        VECTORFIELD_REPRESENTATIONS[cls.base_representation] = cls\n\n        # If not defined explicitly, create properties for the components.\n        for component in cls.attr_classes:\n            if not hasattr(cls, component):\n                setattr(\n                    cls,\n                    component,\n                    property(\n                        _make_getter(component),\n                        doc=f\"Component '{component}' of the VectorField.\",\n                    ),\n                )\n\n        super().__init_subclass__(**kwargs)\n\n    # /def\n\n    def __init__(\n        self,\n        points: RepresentationType,\n        *args,\n        frame: T.Optional[FrameLikeType] = None,\n        **kwargs,\n    ) -> None:\n        super().__init__(*args, **kwargs)\n        self._frame = None if frame is None else resolve_framelike(frame)\n\n        vf_q1 = getattr(self, \"_\" + self.components[0])\n        vf_qs = [getattr(self, \"_\" + c) for c in self.components[1:]]\n\n        if not all(vf_q1.unit.is_equivalent(vf_q.unit) for vf_q in vf_qs):\n            raise u.UnitsError(\"components should have equivalent units.\")\n\n        if not isinstance(points, coord.BaseRepresentation):\n            raise TypeError(\"points is not <BaseRepresentation>.\")\n\n        # TODO store in CoordinateFrame. If representation, use GenericFrame\n        # \"points\" property and stuff links to the _points.data\n        self._points = points.represent_as(self.base_representation)\n\n    # /def\n\n    @property\n    def points(self):\n        return self._points\n\n    @property\n    def frame(self) -> FrameType:\n        return self._frame\n\n    # /def\n\n    #######################################################\n    # Representation\n\n    def to_cartesian(self):\n        \"\"\"Convert the field to 3D rectangular cartesian coordinates.\n\n        Returns\n        -------\n        `CartesianVectorField`\n            This object, converted\n\n        \"\"\"\n        base_e = self.points.unit_vectors()\n        c = functools.reduce(\n            operator.add,\n            (\n                getattr(self, d_c) * base_e[c]\n                for d_c, c in zip(self.components, self.points.components)\n            ),\n        )\n\n        return CartesianVectorField(\n            self.points.to_cartesian(),\n            vf_x=c.x,\n            vf_y=c.y,\n            vf_z=c.z,\n            frame=self.frame,\n        )\n\n    # /def\n\n    @classmethod\n    def from_cartesian(cls, other):\n        \"\"\"Convert field from 3D Cartesian coordinates to the desired class.\n\n        Parameters\n        ----------\n        other : `CartesianVectorField`\n            The object to convert into this vector field.\n\n        Returns\n        -------\n        BaseVectorField\n            A new Vector Field object that is this class' type.\n\n        \"\"\"\n        points = cls.base_representation.from_cartesian(other.points)\n        base_e = points.unit_vectors()\n\n        return cls(\n            points,\n            *(other.dot(e) for e in base_e.values()),\n            copy=False,\n            frame=other.frame,\n        )\n\n    # /def\n\n    def represent_as(self, other_class):\n        \"\"\"Convert coordinates to another representation.\n\n        If the instance is of the requested class, it is returned unmodified.\n        By default, conversion is done via cartesian coordinates.\n\n        Parameters\n        ----------\n        other_class : `~BaseVectorField` subclass\n            The type of representation to turn the coordinates into.\n\n        \"\"\"\n        if other_class is self.__class__:\n            return self\n\n        # The default is to convert via cartesian coordinates.\n        self_cartesian = self.to_cartesian()\n\n        if inspect.isclass(other_class) and issubclass(\n            other_class,\n            BaseVectorField,\n        ):\n            pass\n        elif inspect.isclass(other_class) and issubclass(\n            other_class,\n            coord.BaseRepresentation,\n        ):\n            # convert other_class to the corresponding VectorField\n            other_class = VECTORFIELD_REPRESENTATIONS[other_class]\n        elif isinstance(other_class, str):\n            rep_cls = _REP_CLSs[other_class]\n            # convert rep_cls to the corresponding VectorField\n            other_class = VECTORFIELD_REPRESENTATIONS[rep_cls]\n        else:\n            raise TypeError\n\n        return other_class.from_cartesian(self_cartesian)\n\n    # /def\n\n    @classmethod\n    def from_field(cls, vectorfield):\n        \"\"\"Create a new instance of this vectorfield from another one.\n\n        Parameters\n        ----------\n        vectorfield : `~BaseVectorField` instance\n            The presentation that should be converted to this class.\n\n        \"\"\"\n        if isinstance(vectorfield, BaseVectorField):\n            cartesian = vectorfield.to_cartesian(\n                # base.represent_as(vectorfield.base_representation)\n            )\n        else:\n            raise TypeError\n\n        return cls.from_cartesian(cartesian)\n\n    # /def\n\n    #######################################################\n    # math\n\n    def _scale_operation(self, op: T.Callable, *args):\n        \"\"\"Scale all components.\n\n        Parameters\n        ----------\n        op : `~operator` callable\n            Operator to apply (e.g., `~operator.mul`, `~operator.neg`, etc.\n        *args\n            Any arguments required for the operator (typically, what is to\n            be multiplied with, divided by).\n\n        \"\"\"\n        scaled_attrs = [op(getattr(self, c), *args) for c in self.components]\n        scaled_points = self.points._scale_operation(op, *args)\n        return self.__class__(\n            scaled_points,\n            *scaled_attrs,\n            copy=False,\n            frame=self.frame,\n        )\n\n    # /def\n\n    def _combine_operation(self, op: T.Callable, other, reverse: bool = False):\n        \"\"\"Combine two vector fields.\n\n        If ``other`` is of the same phase space position type as ``self``, the\n        components will simply be combined.  If ``other`` is a representation,\n        it will be used as a base for which to evaluate the phase space\n        position, and the result is a new representation.\n\n        Parameters\n        ----------\n        op : `~operator` callable\n            Operator to apply (e.g., `~operator.add`, `~operator.sub`, etc.\n        other : `BaseVectorField` instance\n            The other phase space position or representation.\n        reverse : bool\n            Whether the operands should be reversed (e.g., as we got here via\n            ``self.__rsub__`` because ``self`` is a subclass of ``other``).\n\n        \"\"\"\n        # ----------\n        # make sure points are the same\n\n        diff = (\n            self.points.represent_as(\n                coord.CartesianRepresentation,\n            )\n            - other.points.represent_as(coord.CartesianRepresentation)\n        )\n\n        if not np.allclose(diff.norm().value, 0):\n            raise Exception(\"can't combine mismatching points.\")\n\n        # ----------\n\n        if isinstance(self, type(other)):\n\n            first, second = (self, other) if not reverse else (other, self)\n            return self.__class__(\n                self.points,\n                *[\n                    op(getattr(first, c), getattr(second, c))\n                    for c in self.components\n                ],\n                frame=self.frame,\n            )\n        else:\n            try:\n                self_cartesian = self.to_cartesian()\n            except TypeError:\n                return NotImplemented\n\n            return other._combine_operation(op, self_cartesian, not reverse)\n\n    # /def\n\n    def norm(self) -> QuantityType:\n        \"\"\"Vector norm.\n\n        The norm is the standard Frobenius norm, i.e., the square root of the\n        sum of the squares of all components with non-angular units.\n\n        Note that any associated differentials will be dropped during this\n        operation.\n\n        Returns\n        -------\n        norm : `astropy.units.Quantity`\n            Vector norm, with the same shape as the representation.\n\n        \"\"\"\n        return np.sqrt(\n            functools.reduce(\n                operator.add,\n                (\n                    getattr(self, component) ** 2\n                    for component, cls in self.attr_classes.items()\n                ),\n            ),\n        )\n\n    # /def\n\n    #######################################################\n    # utils\n\n    def unit_vectors(self) -> T.Dict[str, RepresentationType]:\n        r\"\"\"Cartesian unit vectors in the direction of each component.\n\n        Given unit vectors :math:`\\hat{e}_c` and scale factors :math:`f_c`,\n        a change in one component of :math:`\\delta c` corresponds to a change\n        in representation of :math:`\\delta c \\times f_c \\times \\hat{e}_c`.\n\n        Returns\n        -------\n        unit_vectors : dict of `CartesianRepresentation`\n            The keys are the component names.\n\n        \"\"\"\n        return self.points.unit_vectors()\n\n    # /def\n\n    def scale_factors(self) -> T.Dict[str, QuantityType]:\n        r\"\"\"Scale factors for each component's direction.\n\n        Given unit vectors :math:`\\hat{e}_c` and scale factors :math:`f_c`,\n        a change in one component of :math:`\\delta c` corresponds to a change\n        in representation of :math:`\\delta c \\times f_c \\times \\hat{e}_c`.\n\n        Returns\n        -------\n        scale_factors : dict of `~astropy.units.Quantity`\n            The keys are the component names.\n\n        \"\"\"\n        return self.points.scale_factors()\n\n    # /def\n\n    def __repr__(self) -> str:\n        prefixstr = \"    \"\n        # TODO combine with points\n        arrstr = _array2string(\n            np.lib.recfunctions.merge_arrays(\n                (self.points._values, self._values),\n            ),\n            prefix=prefixstr,\n        )\n\n        pointsunitstr = (\n            (\"in \" + self.points._unitstr)\n            if self.points._unitstr\n            else \"[dimensionless]\"\n        )\n        unitstr = (\n            (\"in \" + self._unitstr) if self._unitstr else \"[dimensionless]\"\n        )\n        return \"<{} ({}) {:s} | ({}) {:s}\\n{}{}>\".format(\n            self.__class__.__name__,\n            \", \".join(self.points.components),\n            pointsunitstr,\n            \", \".join(self.components),\n            unitstr,\n            prefixstr,\n            arrstr,\n        )\n\n    # /def\n\n    def _apply(self, method: T.Union[str, T.Callable], *args, **kwargs):\n        \"\"\"Create a new representation or differential with ``method`` applied\n        to the component data.\n\n        In typical usage, the method is any of the shape-changing methods for\n        `~numpy.ndarray` (``reshape``, ``swapaxes``, etc.), as well as those\n        picking particular elements (``__getitem__``, ``take``, etc.), which\n        are all defined in `~astropy.utils.shapes.ShapedLikeNDArray`. It will be\n        applied to the underlying arrays (e.g., ``x``, ``y``, and ``z`` for\n        `~astropy.coordinates.CartesianRepresentation`), with the results used\n        to create a new instance.\n\n        Internally, it is also used to apply functions to the components\n        (in particular, `~numpy.broadcast_to`).\n\n        Parameters\n        ----------\n        method : str or callable\n            If str, it is the name of a method that is applied to the internal\n            ``components``. If callable, the function is applied.\n        args : tuple\n            Any positional arguments for ``method``.\n        kwargs : dict\n            Any keyword arguments for ``method``.\n\n        \"\"\"\n        if callable(method):\n\n            def apply_method(array):\n                return method(array, *args, **kwargs)\n\n        else:\n            apply_method = operator.methodcaller(method, *args, **kwargs)\n\n        new = super().__new__(self.__class__)\n        new._points = self.points._apply(method, *args, **kwargs)\n        for component in self.components:\n            setattr(\n                new,\n                \"_\" + component,\n                apply_method(getattr(self, component)),\n            )\n\n        # Copy other 'info' attr only if it has actually been defined.\n        # See PR #3898 for further explanation and justification, along\n        # with Quantity.__array_finalize__\n        if \"info\" in self.__dict__:\n            new.info = self.info\n\n        return new\n\n    # /def\n\n\n# /class\n\n\n# -------------------------------------------------------------------\n\n\nclass CartesianVectorField(BaseVectorField):\n    \"\"\"Cartesian Vector Field.\"\"\"\n\n    _xyz = None\n    _vf_xyz = None\n\n    base_representation = coord.CartesianRepresentation\n\n    @property\n    def x(self) -> QuantityType:\n        return self.points.x\n\n    @property\n    def y(self) -> QuantityType:\n        return self.points.y\n\n    @property\n    def z(self) -> QuantityType:\n        return self.points.z\n\n    def __init__(\n        self,\n        points: RepresentationType,\n        vf_x,\n        vf_y=None,\n        vf_z=None,\n        frame: T.Optional[FrameLikeType] = None,\n        copy: bool = False,\n    ) -> None:\n        super().__init__(points, vf_x, vf_y, vf_z, frame=frame, copy=copy)\n\n    # /def\n\n    def get_xyz(self, xyz_axis: int = 0) -> QuantityType:\n        \"\"\"Return a vector array of the x, y, and z coordinates.\n\n        Parameters\n        ----------\n        xyz_axis : int, optional\n            The axis in the final array along which the x, y, z components\n            should be stored (default: 0).\n\n        Returns\n        -------\n        xyz : `~astropy.units.Quantity`\n            With dimension 3 along ``xyz_axis``.  Note that, if possible,\n            this will be a view.\n\n        \"\"\"\n        return self.points.get_xyz(xyz_axis=xyz_axis)\n\n    xyz = property(get_xyz)\n    # /def\n\n    def get_vf_xyz(self, vf_xyz_axis: int = 0):\n        \"\"\"Return a vector array of the vf_x, vf_y, and vf_z coordinates.\n\n        Parameters\n        ----------\n        vf_xyz_axis : int, optional\n            The axis in the final array along which the vf_x, vf_y, vf_z\n            components should be stored (default: 0).\n\n        Returns\n        -------\n        vf_xyz : `~astropy.units.Quantity`\n            With dimension 3 along ``vf_xyz_axis``.  Note that, if possible,\n            this will be a view.\n\n        \"\"\"\n        if self._vf_xyz is not None:\n            if self._vf_xyz_axis == vf_xyz_axis:\n                return self._vf_xyz\n            else:\n                return np.moveaxis(\n                    self._vf_xyz,\n                    self._vf_xyz_axis,\n                    vf_xyz_axis,\n                )\n\n        # Create combined array.  TO DO: keep it in _xyz for repeated use?\n        # But then in-place changes have to cancel it. Likely best to\n        # also update components.\n        return np.stack([self._vf_x, self._vf_y, self._vf_z], axis=vf_xyz_axis)\n\n    vf_xyz = property(get_vf_xyz)\n    # /def\n\n    def dot(self, other):\n        \"\"\"Dot product of two vector fields.\n\n        Note that any associated differentials will be dropped during this\n        operation.\n\n        Parameters\n        ----------\n        other : `BaseVectorField` or |Representation|\n            If not already cartesian, it is converted.\n\n        Returns\n        -------\n        dot_product : `~astropy.units.Quantity`\n            The sum of the product of the x, y, and z components of ``self``\n            and ``other``.\n\n        \"\"\"\n        try:\n            other_c = other.to_cartesian()\n        except Exception:\n            raise TypeError(\n                \"cannot only take dot product with another \"\n                \"vector field, not a {} instance.\".format(type(other)),\n            )\n\n        if isinstance(other_c, BaseVectorField):\n            other_vf_xyz = other_c.get_vf_xyz(vf_xyz_axis=-1)\n        else:\n            other_vf_xyz = other_c.get_xyz(xyz_axis=-1)\n\n        # erfa pdp: p-vector inner (=scalar=dot) product.\n        return erfa_ufunc.pdp(self.get_vf_xyz(vf_xyz_axis=-1), other_vf_xyz)\n\n    # /def\n\n\n# /class\n\n# -------------------------------------------------------------------\n\n\nclass CylindricalVectorField(BaseVectorField):\n    \"\"\"Cylindrical Vector Field.\"\"\"\n\n    base_representation = coord.CylindricalRepresentation\n\n    def __init__(\n        self,\n        points: RepresentationType,\n        vf_rho,\n        vf_phi=None,\n        vf_z=None,\n        frame: T.Optional[FrameLikeType] = None,\n        copy: bool = False,\n    ) -> None:\n        super().__init__(points, vf_rho, vf_phi, vf_z, frame=frame, copy=copy)\n\n    # /def\n\n    @property\n    def rho(self) -> QuantityType:\n        return self.points.rho\n\n    @property\n    def phi(self) -> QuantityType:\n        return self.points.phi\n\n    @property\n    def z(self) -> QuantityType:\n        return self.points.z\n\n    # /def\n\n\n# /class\n\n# -------------------------------------------------------------------\n\n\nclass SphericalVectorField(BaseVectorField):\n    \"\"\"Spherical Vector Field.\"\"\"\n\n    base_representation = coord.SphericalRepresentation\n\n    def __init__(\n        self,\n        points: RepresentationType,\n        vf_lon,\n        vf_lat=None,\n        vf_distance=None,\n        frame: T.Optional[FrameLikeType] = None,\n        copy: bool = False,\n    ) -> None:\n        super().__init__(\n            points,\n            vf_lon,\n            vf_lat,\n            vf_distance,\n            frame=frame,\n            copy=copy,\n        )\n\n    # /def\n\n    @property\n    def lon(self) -> QuantityType:\n        return self.points.lon\n\n    @property\n    def lat(self) -> QuantityType:\n        return self.points.lat\n\n    @property\n    def distance(self) -> QuantityType:\n        return self.points.distance\n\n    # /def\n\n\n# /class\n\n# -------------------------------------------------------------------\n\n\nclass PhysicsSphericalVectorField(BaseVectorField):\n    \"\"\"PhysicsSpherical Vector Field.\"\"\"\n\n    base_representation = coord.PhysicsSphericalRepresentation\n\n    def __init__(\n        self,\n        points: RepresentationType,\n        vf_phi,\n        vf_theta=None,\n        vf_r=None,\n        frame: T.Optional[FrameLikeType] = None,\n        copy: bool = False,\n    ) -> None:\n        super().__init__(\n            points,\n            vf_phi,\n            vf_theta,\n            vf_r,\n            frame=frame,\n            copy=copy,\n        )\n\n    # /def\n\n    @property\n    def phi(self) -> QuantityType:\n        return self.points.phi\n\n    @property\n    def theta(self) -> QuantityType:\n        return self.points.theta\n\n    @property\n    def r(self) -> QuantityType:\n        return self.points.r\n\n    # /def\n\n\n# /class\n\n##############################################################################\n# END\n", "meta": {"hexsha": "553ac51f62a88246d9736386c92de41b294ec146", "size": 21922, "ext": "py", "lang": "Python", "max_stars_repo_path": "discO/utils/vectorfield.py", "max_stars_repo_name": "GalOrrery/discO", "max_stars_repo_head_hexsha": "3b17b6ead65908c053b09a1a967e8a1819a06209", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-17T14:40:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-17T14:40:51.000Z", "max_issues_repo_path": "discO/utils/vectorfield.py", "max_issues_repo_name": "nstarman/discO", "max_issues_repo_head_hexsha": "3b17b6ead65908c053b09a1a967e8a1819a06209", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 45, "max_issues_repo_issues_event_min_datetime": "2020-11-17T14:30:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-26T18:47:37.000Z", "max_forks_repo_path": "discO/utils/vectorfield.py", "max_forks_repo_name": "nstarman/discO", "max_forks_repo_head_hexsha": "3b17b6ead65908c053b09a1a967e8a1819a06209", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7142857143, "max_line_length": 80, "alphanum_fraction": 0.5528236475, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 4577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.1995452819719607}}
{"text": "# Third-party\nimport astropy.coordinates as coord\nimport astropy.units as u\nimport numpy as np\nfrom scipy.signal import argrelmax\n\n# Project\nfrom gala.logging import logger\nfrom .core import PhaseSpacePosition\nfrom .util import peak_to_peak_period\nfrom .plot import plot_projections\nfrom ..io import quantity_to_hdf5, quantity_from_hdf5\nfrom ..util import atleast_2d\nfrom ..units import dimensionless, UnitSystem, DimensionlessUnitSystem\n\n__all__ = ['Orbit']\n\n\nclass Orbit(PhaseSpacePosition):\n    \"\"\"\n    Represents an orbit: positions and velocities (conjugate momenta) as a\n    function of time.\n\n    The class can be instantiated with Astropy representation objects (e.g.,\n    :class:`~astropy.coordinates.CartesianRepresentation`), Astropy\n    :class:`~astropy.units.Quantity` objects, or plain Numpy arrays.\n\n    If passing in Quantity or Numpy array instances for both position and\n    velocity, they are assumed to be Cartesian. Array inputs are interpreted as\n    dimensionless quantities. The input position and velocity objects can have\n    an arbitrary number of (broadcastable) dimensions. For Quantity or array\n    inputs, the first axes have special meaning:\n\n        - ``axis=0`` is the coordinate dimension (e.g., x, y, z)\n        - ``axis=1`` is the time dimension\n\n    So if the input position array, ``pos``, has shape ``pos.shape = (3, 100)``,\n    this would be a 3D orbit at 100 times (``pos[0]`` is ``x``, ``pos[1]``` is\n    ``y``, etc.). For representing multiple orbits, the position array could\n    have 3 axes, e.g., it might have shape `pos.shape = (3, 100, 8)`, where this\n    is interpreted as a 3D position at 100 times for 8 different orbits. The\n    same is true for velocity. The position and velocity arrays must have the\n    same shape.\n\n    If a time argument is specified, the position and velocity arrays must have\n    the same number of timesteps as the length of the time object::\n\n        len(t) == pos.shape[1]\n\n    Parameters\n    ----------\n    pos : representation, quantity_like, or array_like\n        Positions. If a numpy array (e.g., has no units), this will be\n        stored as a dimensionless :class:`~astropy.units.Quantity`. See\n        the note above about the assumed meaning of the axes of this object.\n    vel : differential, quantity_like, or array_like\n        Velocities. If a numpy array (e.g., has no units), this will be\n        stored as a dimensionless :class:`~astropy.units.Quantity`. See\n        the note above about the assumed meaning of the axes of this object.\n    t : array_like, :class:`~astropy.units.Quantity` (optional)\n        Array of times. If a numpy array (e.g., has no units), this will be\n        stored as a dimensionless :class:`~astropy.units.Quantity`.\n    hamiltonian : `~gala.potential.Hamiltonian` (optional)\n        The Hamiltonian that the orbit was integrated in.\n\n    \"\"\"\n    def __init__(self, pos, vel, t=None,\n                 hamiltonian=None, potential=None, frame=None):\n\n        super().__init__(pos=pos, vel=vel)\n\n        if self.pos.ndim < 1:\n            self.pos = self.pos.reshape(1)\n            self.vel = self.vel.reshape(1)\n\n        # TODO: check that Hamiltonian ndim is consistent with here\n\n        if t is not None:\n            t = np.atleast_1d(t)\n            if self.pos.shape[0] != len(t):\n                raise ValueError(\"Position and velocity must have the same \"\n                                 \"length along axis=1 as the length of the \"\n                                 \"time array {} vs {}\"\n                                 .format(len(t), self.pos.shape[0]))\n\n            if not hasattr(t, 'unit'):\n                t = t * u.one\n\n        self.t = t\n\n        if hamiltonian is not None:\n            self.potential = hamiltonian.potential\n            self.frame = hamiltonian.frame\n\n        else:\n            self.potential = potential\n            self.frame = frame\n\n    def __getitem__(self, slice_):\n\n        if isinstance(slice_, np.ndarray) or isinstance(slice_, list):\n            slice_ = (slice_,)\n\n        try:\n            slice_ = tuple(slice_)\n        except TypeError:\n            slice_ = (slice_,)\n\n        kw = dict()\n        if self.t is not None:\n            kw['t'] = self.t[slice_[0]]\n\n        pos = self.pos[slice_]\n        vel = self.vel[slice_]\n\n        # if one time is sliced out, return a phasespaceposition\n        try:\n            int_tslice = int(slice_[0])\n        except TypeError:\n            int_tslice = None\n\n        if int_tslice is not None:\n            return PhaseSpacePosition(pos=pos, vel=vel, frame=self.frame)\n\n        else:\n            return self.__class__(pos=pos, vel=vel,\n                                  potential=self.potential,\n                                  frame=self.frame, **kw)\n\n    @property\n    def hamiltonian(self):\n        if self.potential is None or self.frame is None:\n            return None\n\n        try:\n            return self._hamiltonian\n        except AttributeError:\n            from gala.potential import Hamiltonian\n            self._hamiltonian = Hamiltonian(potential=self.potential,\n                                            frame=self.frame)\n\n        return self._hamiltonian\n\n    def w(self, units=None):\n        \"\"\"\n        This returns a single array containing the phase-space positions.\n\n        Parameters\n        ----------\n        units : `~gala.units.UnitSystem` (optional)\n            The unit system to represent the position and velocity in\n            before combining into the full array.\n\n        Returns\n        -------\n        w : `~numpy.ndarray`\n            A numpy array of all positions and velocities, without units.\n            Will have shape ``(2*ndim, ...)``.\n\n        \"\"\"\n\n        if units is None:\n            if self.hamiltonian is None:\n                units = dimensionless\n            else:\n                units = self.hamiltonian.units\n\n        return super().w(units=units)\n\n    # ------------------------------------------------------------------------\n    # Convert from Cartesian to other representations\n    #\n    def represent_as(self, new_pos, new_vel=None):\n        \"\"\"\n        Represent the position and velocity of the orbit in an alternate\n        coordinate system. Supports any of the Astropy coordinates\n        representation classes.\n\n        Parameters\n        ----------\n        new_pos : :class:`~astropy.coordinates.BaseRepresentation`\n            The type of representation to generate. Must be a class (not an\n            instance), or the string name of the representation class.\n        new_vel : :class:`~astropy.coordinates.BaseDifferential` (optional)\n            Class in which any velocities should be represented. Must be a class\n            (not an instance), or the string name of the differential class. If\n            None, uses the default differential for the new position class.\n\n        Returns\n        -------\n        new_orbit : `gala.dynamics.Orbit`\n        \"\"\"\n        kw = dict()\n        if self.t is not None:\n            kw['t'] = self.t\n        o = super().represent_as(new_pos=new_pos, new_vel=new_vel)\n        return self.__class__(pos=o.pos,\n                              vel=o.vel,\n                              hamiltonian=self.hamiltonian,\n                              **kw)\n\n    # ------------------------------------------------------------------------\n    # Shape and size\n    # ------------------------------------------------------------------------\n    @property\n    def ntimes(self):\n        return self.shape[0]\n\n    @property\n    def norbits(self):\n        if len(self.shape) < 2:\n            return 1\n        else:\n            return self.shape[1]\n\n    def reshape(self, new_shape):\n        \"\"\"\n        Reshape the underlying position and velocity arrays.\n        \"\"\"\n        kw = dict()\n        if self.t is not None:\n            kw['t'] = self.t\n        return self.__class__(pos=self.pos.reshape(new_shape),\n                              vel=self.vel.reshape(new_shape),\n                              hamiltonian=self.hamiltonian,\n                              **kw)\n\n    # ------------------------------------------------------------------------\n    # Input / output\n    #\n    def to_hdf5(self, f):\n        \"\"\"\n        Serialize this object to an HDF5 file.\n\n        Requires ``h5py``.\n\n        Parameters\n        ----------\n        f : str, :class:`h5py.File`\n            Either the filename or an open HDF5 file.\n        \"\"\"\n\n        f = super().to_hdf5(f)\n\n        if self.potential is not None:\n            import yaml\n            from ..potential.potential.io import to_dict\n            f['potential'] = yaml.dump(to_dict(self.potential)).encode('utf-8')\n\n        if self.t:\n            quantity_to_hdf5(f, 'time', self.t)\n\n        return f\n\n    @classmethod\n    def from_hdf5(cls, f):\n        \"\"\"\n        Load an object from an HDF5 file.\n\n        Requires ``h5py``.\n\n        Parameters\n        ----------\n        f : str, :class:`h5py.File`\n            Either the filename or an open HDF5 file.\n        \"\"\"\n        # TODO: this is duplicated code from PhaseSpacePosition\n        if isinstance(f, str):\n            import h5py\n            f = h5py.File(f, mode='r')\n            close = True\n        else:\n            close = False\n\n        pos = quantity_from_hdf5(f['pos'])\n        vel = quantity_from_hdf5(f['vel'])\n\n        time = None\n        if 'time' in f:\n            time = quantity_from_hdf5(f['time'])\n\n        frame = None\n        if 'frame' in f:\n            g = f['frame']\n\n            frame_mod = g.attrs['module']\n            frame_cls = g.attrs['class']\n            frame_units = [u.Unit(x.decode('utf-8')) for x in g['units']]\n\n            if u.dimensionless_unscaled in frame_units:\n                units = DimensionlessUnitSystem()\n            else:\n                units = UnitSystem(*frame_units)\n\n            pars = dict()\n            for k in g['parameters']:\n                pars[k] = quantity_from_hdf5(g['parameters/'+k])\n\n            exec(\"from {0} import {1}\".format(frame_mod, frame_cls))\n            frame_cls = eval(frame_cls)\n\n            frame = frame_cls(units=units, **pars)\n\n        potential = None\n        if 'potential' in f:\n            import yaml\n            from ..potential.potential.io import from_dict\n            _dict = yaml.load(f['potential'][()].decode('utf-8'),\n                              Loader=yaml.Loader)\n            potential = from_dict(_dict)\n\n        if close:\n            f.close()\n\n        return cls(pos=pos, vel=vel, t=time,\n                   frame=frame, potential=potential)\n\n    def orbit_gen(self):\n        \"\"\"\n        Generator for iterating over each orbit.\n        \"\"\"\n        if self.norbits == 1:\n            yield self\n\n        else:\n            for i in range(self.norbits):\n                yield self[:, i]\n\n    # ------------------------------------------------------------------------\n    # Computed dynamical quantities\n    #\n\n    def potential_energy(self, potential=None):\n        r\"\"\"\n        The potential energy *per unit mass*:\n\n        .. math::\n\n            E_\\Phi = \\Phi(\\boldsymbol{q})\n\n        Returns\n        -------\n        E : :class:`~astropy.units.Quantity`\n            The potential energy.\n        \"\"\"\n        if self.hamiltonian is None and potential is None:\n            raise ValueError(\"To compute the potential energy, a potential\"\n                             \" object must be provided!\")\n        if potential is None:\n            potential = self.hamiltonian.potential\n\n        return super().potential_energy(potential)\n\n    def energy(self, hamiltonian=None):\n        r\"\"\"\n        The total energy *per unit mass*:\n\n        Parameters\n        ----------\n        hamiltonian : `gala.potential.Hamiltonian`, `gala.potential.PotentialBase` instance\n            The Hamiltonian object to evaluate the energy. If a potential is\n            passed in, this assumes a static reference frame.\n\n        Returns\n        -------\n        E : :class:`~astropy.units.Quantity`\n            The total energy.\n        \"\"\"\n\n        if self.hamiltonian is None and hamiltonian is None:\n            raise ValueError(\"To compute the total energy, a hamiltonian\"\n                             \" object must be provided!\")\n\n        if hamiltonian is None:\n            hamiltonian = self.hamiltonian\n        else:\n            from gala.potential import Hamiltonian\n            hamiltonian = Hamiltonian(hamiltonian)\n\n        return hamiltonian(self)\n\n    def _max_helper(self, arr, approximate=False):\n        \"\"\"\n        Helper function for computing extrema (apocenter, pericenter, z_height)\n        and times of extrema.\n\n        Parameters\n        ----------\n        arr : `numpy.ndarray`\n        \"\"\"\n        assert self.norbits == 1\n        assert self.t[-1] > self.t[0]  # time must increase\n\n        _ix = argrelmax(arr.value, mode='wrap')[0]\n        _ix = _ix[(_ix != 0) & (_ix != (len(arr)-1))]  # remove edges\n        t = self.t.value\n\n        approx_arr = arr[_ix]\n        approx_t = t[_ix]\n\n        if approximate:\n            return approx_arr, approx_t * self.t.unit\n\n        better_times = np.zeros(_ix.shape, dtype=float)\n        better_arr = np.zeros(_ix.shape, dtype=float)\n        for i, j in enumerate(_ix):\n            tvals = t[j-1:j+2]\n            rvals = arr[j-1:j+2].value\n            coeffs = np.polynomial.polynomial.polyfit(tvals, rvals, 2)\n            better_times[i] = (-coeffs[1])/(2*coeffs[2])\n            better_arr[i] = ((coeffs[2] * better_times[i]**2)\n                             + (coeffs[1] * better_times[i]) + coeffs[0])\n\n        return better_arr * arr.unit, better_times * self.t.unit\n\n    def _max_return_helper(self, vals, times, return_times, reduce):\n        if return_times:\n            if len(vals) == 1:\n                return vals[0], times[0]\n            else:\n                return vals, times\n\n        elif reduce:\n            return u.Quantity(vals).reshape(self.shape[1:])\n\n        else:\n            return u.Quantity(vals)\n\n    def pericenter(self, return_times=False, func=np.mean,\n                   approximate=False):\n        \"\"\"\n        Estimate the pericenter(s) of the orbit by identifying local minima in\n        the spherical radius, fitting a parabola around these local minima and\n        then solving this parabola to find the pericenter(s).\n\n        By default, this returns the mean of all local minima (pericenters). To\n        get, e.g., the minimum pericenter, pass in ``func=np.min``. To get\n        all pericenters, pass in ``func=None``.\n\n        Parameters\n        ----------\n        func : func (optional)\n            A function to evaluate on all of the identified pericenter times.\n        return_times : bool (optional)\n            Also return the pericenter times.\n        approximate : bool (optional)\n            Compute an approximate pericenter by skipping interpolation.\n\n        Returns\n        -------\n        peri : float, :class:`~numpy.ndarray`\n            Either a single number or an array of pericenters.\n        times : :class:`~numpy.ndarray` (optional, see ``return_times``)\n            If ``return_times=True``, also returns an array of the pericenter\n            times.\n\n        \"\"\"\n\n        if return_times and func is not None:\n            raise ValueError(\"Cannot return times if reducing pericenters \"\n                             \"using an input function. Pass `func=None` if \"\n                             \"you want to return all individual pericenters \"\n                             \"and times.\")\n\n        if func is None:\n            reduce = False\n            func = lambda x: x  # noqa\n        else:\n            reduce = True\n\n        # time must increase\n        if self.t[-1] < self.t[0]:\n            self = self[::-1]\n\n        vals = []\n        times = []\n        for orbit in self.orbit_gen():\n            v, t = orbit._max_helper(-orbit.physicsspherical.r,  # pericenter\n                                     approximate=approximate)\n            vals.append(func(-v))  # negative for pericenter\n            times.append(t)\n\n        return self._max_return_helper(vals, times, return_times, reduce)\n\n    def apocenter(self, return_times=False, func=np.mean,\n                  approximate=False):\n        \"\"\"\n        Estimate the apocenter(s) of the orbit by identifying local maxima in\n        the spherical radius, fitting a parabola around these local maxima and\n        then solving this parabola to find the apocenter(s).\n\n        By default, this returns the mean of all local maxima (apocenters). To\n        get, e.g., the largest apocenter, pass in ``func=np.max``. To get\n        all apocenters, pass in ``func=None``.\n\n        Parameters\n        ----------\n        func : func (optional)\n            A function to evaluate on all of the identified apocenter times.\n        return_times : bool (optional)\n            Also return the apocenter times.\n        approximate : bool (optional)\n            Compute an approximate apocenter by skipping interpolation.\n\n        Returns\n        -------\n        apo : float, :class:`~numpy.ndarray`\n            Either a single number or an array of apocenters.\n        times : :class:`~numpy.ndarray` (optional, see ``return_times``)\n            If ``return_times=True``, also returns an array of the apocenter\n            times.\n\n        \"\"\"\n\n        if return_times and func is not None:\n            raise ValueError(\"Cannot return times if reducing apocenters \"\n                             \"using an input function. Pass `func=None` if \"\n                             \"you want to return all individual apocenters \"\n                             \"and times.\")\n\n        if func is None:\n            reduce = False\n            func = lambda x: x  # noqa\n        else:\n            reduce = True\n\n        # time must increase\n        if self.t[-1] < self.t[0]:\n            self = self[::-1]\n\n        vals = []\n        times = []\n        for orbit in self.orbit_gen():\n            v, t = orbit._max_helper(orbit.physicsspherical.r,  # apocenter\n                                     approximate=approximate)\n            vals.append(func(v))\n            times.append(t)\n\n        return self._max_return_helper(vals, times, return_times, reduce)\n\n    def zmax(self, return_times=False, func=np.mean,\n             approximate=False):\n        \"\"\"\n        Estimate the maximum ``z`` height of the orbit by identifying local\n        maxima in the absolute value of the ``z`` position, fitting a parabola\n        around these local maxima and then solving this parabola to find the\n        maximum ``z`` height.\n\n        By default, this returns the mean of all local maxima. To get, e.g., the\n        largest ``z`` excursion, pass in ``func=np.max``. To get all ``z``\n        maxima, pass in ``func=None``.\n\n        Parameters\n        ----------\n        func : func (optional)\n            A function to evaluate on all of the identified z maximum times.\n        return_times : bool (optional)\n            Also return the times of maximum.\n        approximate : bool (optional)\n            Compute approximate values by skipping interpolation.\n\n        Returns\n        -------\n        zs : float, :class:`~numpy.ndarray`\n            Either a single number or an array of maximum z heights.\n        times : :class:`~numpy.ndarray` (optional, see ``return_times``)\n            If ``return_times=True``, also returns an array of the apocenter\n            times.\n\n        \"\"\"\n\n        if return_times and func is not None:\n            raise ValueError(\"Cannot return times if reducing \"\n                             \"using an input function. Pass `func=None` if \"\n                             \"you want to return all individual values \"\n                             \"and times.\")\n\n        if func is None:\n            reduce = False\n            func = lambda x: x  # noqa\n        else:\n            reduce = True\n\n        # time must increase\n        if self.t[-1] < self.t[0]:\n            self = self[::-1]\n\n        vals = []\n        times = []\n        for orbit in self.orbit_gen():\n            v, t = orbit._max_helper(np.abs(orbit.cylindrical.z),\n                                     approximate=approximate)\n            vals.append(func(v))\n            times.append(t)\n\n        return self._max_return_helper(vals, times, return_times, reduce)\n\n    def eccentricity(self, **kw):\n        r\"\"\"\n        Returns the eccentricity computed from the mean apocenter and\n        mean pericenter.\n\n        .. math::\n\n            e = \\frac{r_{\\rm apo} - r_{\\rm per}}{r_{\\rm apo} + r_{\\rm per}}\n\n        Parameters\n        ----------\n        **kw\n            Any keyword arguments passed to ``apocenter()`` and\n            ``pericenter()``. For example, ``approximate=True``.\n\n        Returns\n        -------\n        ecc : float\n            The orbital eccentricity.\n\n        \"\"\"\n        ra = self.apocenter(**kw)\n        rp = self.pericenter(**kw)\n        return (ra - rp) / (ra + rp)\n\n    def estimate_period(self, radial=True):\n        \"\"\"\n        Estimate the period of the orbit. By default, computes the radial\n        period. If ``radial==False``, this returns period estimates for\n        each dimension of the orbit.\n\n        Parameters\n        ----------\n        radial : bool (optional)\n            What period to estimate. If ``True``, estimates the radial\n            period. If ``False``, estimates period in each dimension, e.g.,\n            if the orbit is 3D, along x, y, and z.\n\n        Returns\n        -------\n        T : `~astropy.units.Quantity`\n            The period or periods.\n        \"\"\"\n\n        if self.t is None:\n            raise ValueError(\"To compute the period, a time array is needed. \"\n                             \"Specify a time array when creating this object.\")\n\n        if radial:\n            r = self.physicsspherical.r.value\n            if self.norbits == 1:\n                T = u.Quantity(peak_to_peak_period(self.t, r))\n            else:\n                T = u.Quantity([peak_to_peak_period(self.t, r[:, n])\n                                for n in range(r.shape[1])])\n\n        else:\n            raise NotImplementedError(\"sorry 'bout that...\")\n\n        return T\n\n    # ------------------------------------------------------------------------\n    # Misc. useful methods\n    # ------------------------------------------------------------------------\n    def circulation(self):\n        \"\"\"\n        Determine which axes the Orbit circulates around by checking\n        whether there is a change of sign of the angular momentum\n        about an axis. Returns a 2D array with ``ndim`` integers per orbit\n        point. If a box orbit, all integers will be 0. A 1 indicates\n        circulation about the corresponding axis.\n\n        TODO: clockwise / counterclockwise?\n\n        For example, for a single 3D orbit:\n\n        - Box and boxlet = [0, 0, 0]\n        - z-axis (short-axis) tube = [0, 0, 1]\n        - x-axis (long-axis) tube = [1, 0, 0]\n\n        Returns\n        -------\n        circulation : :class:`numpy.ndarray`\n            An array that specifies whether there is circulation about any of\n            the axes of the input orbit. For a single orbit, will return a\n            1D array, but for multiple orbits, the shape will be\n            ``(3, norbits)``.\n\n        \"\"\"\n        L = self.angular_momentum()\n\n        # if only 2D, add another empty axis\n        if L.ndim == 2:\n            single_orbit = True\n            L = L[..., None]\n        else:\n            single_orbit = False\n\n        ndim, ntimes, norbits = L.shape\n\n        # initial angular momentum\n        L0 = L[:, 0]\n\n        # see if at any timestep the sign has changed\n        circ = np.ones((ndim, norbits))\n        for ii in range(ndim):\n            cnd = (np.sign(L0[ii]) != np.sign(L[ii, 1:])) | \\\n                  (np.abs(L[ii, 1:]).value < 1E-13)\n            ix = np.atleast_1d(np.any(cnd, axis=0))\n            circ[ii, ix] = 0\n\n        circ = circ.astype(int)\n        if single_orbit:\n            return circ.reshape((ndim,))\n        else:\n            return circ\n\n    def align_circulation_with_z(self, circulation=None):\n        \"\"\"\n        If the input orbit is a tube orbit, this function aligns the circulation\n        axis with the z axis and returns a copy.\n\n        Parameters\n        ----------\n        circulation : array_like (optional)\n            Array of bits that specify the axis about which the orbit\n            circulates. If not provided, will compute this using\n            :meth:`~gala.dynamics.Orbit.circulation`. See that method for more\n            information.\n\n        Returns\n        -------\n        orb : :class:`~gala.dynamics.Orbit`\n            A copy of the original orbit object with circulation aligned with\n            the z axis.\n        \"\"\"\n\n        if circulation is None:\n            circulation = self.circulation()\n        circulation = atleast_2d(circulation, insert_axis=1)\n\n        cart = self.cartesian\n        pos = cart.xyz\n        vel = np.vstack((cart.v_x.value[None],\n                         cart.v_y.value[None],\n                         cart.v_z.value[None])) * cart.v_x.unit\n\n        if pos.ndim < 3:\n            pos = pos[..., np.newaxis]\n            vel = vel[..., np.newaxis]\n\n        if (circulation.shape[0] != self.ndim or\n                circulation.shape[1] != pos.shape[2]):\n            raise ValueError(\"Shape of 'circulation' array should match the \"\n                             \"shape of the position/velocity (minus the time \"\n                             \"axis).\")\n\n        new_pos = pos.copy()\n        new_vel = vel.copy()\n        for n in range(pos.shape[2]):\n            if circulation[2, n] == 1 or np.all(circulation[:, n] == 0):\n                # already circulating about z or box orbit\n                continue\n\n            if sum(circulation[:, n]) > 1:\n                logger.warning(\"Circulation about multiple axes - are you sure \"\n                               \"the orbit has been integrated for long enough?\")\n\n            if circulation[0, n] == 1:\n                circ = 0\n            elif circulation[1, n] == 1:\n                circ = 1\n            else:\n                raise RuntimeError(\"Should never get here...\")\n\n            new_pos[circ, :, n] = pos[2, :, n]\n            new_pos[2, :, n] = pos[circ, :, n]\n\n            new_vel[circ, :, n] = vel[2, :, n]\n            new_vel[2, :, n] = vel[circ, :, n]\n\n        return self.__class__(pos=new_pos.reshape(cart.xyz.shape),\n                              vel=new_vel.reshape(cart.xyz.shape),\n                              t=self.t,\n                              hamiltonian=self.hamiltonian)\n\n    def plot(self, components=None, units=None, auto_aspect=True, **kwargs):\n        \"\"\"\n        Plot the positions in all projections. This is a wrapper around\n        `~gala.dynamics.plot_projections` for fast access and quick\n        visualization. All extra keyword arguments are passed to that function\n        (the docstring for this function is included here for convenience).\n\n        Parameters\n        ----------\n        components : iterable (optional)\n            A list of component names (strings) to plot. By default, this is the\n            Cartesian positions ``['x', 'y', 'z']``. To plot Cartesian\n            velocities, pass in the velocity component names\n            ``['v_x', 'v_y', 'v_z']``. If the representation is different, the\n            component names will be different. For example, for a Cylindrical\n            representation, the components are ``['rho', 'phi', 'z']`` and\n            ``['v_rho', 'pm_phi', 'v_z']``.\n        units : `~astropy.units.UnitBase`, iterable (optional)\n            A single unit or list of units to display the components in.\n        auto_aspect : bool (optional)\n            Automatically enforce an equal aspect ratio.\n        relative_to : bool (optional)\n            Plot the values relative to this value or values.\n        autolim : bool (optional)\n            Automatically set the plot limits to be something sensible.\n        axes : array_like (optional)\n            Array of matplotlib Axes objects.\n        subplots_kwargs : dict (optional)\n            Dictionary of kwargs passed to :func:`~matplotlib.pyplot.subplots`.\n        labels : iterable (optional)\n            List or iterable of axis labels as strings. They should correspond to\n            the dimensions of the input orbit.\n        plot_function : callable (optional)\n            The ``matplotlib`` plot function to use. By default, this is\n            :func:`~matplotlib.pyplot.scatter`, but can also be, e.g.,\n            :func:`~matplotlib.pyplot.plot`.\n        **kwargs\n            All other keyword arguments are passed to the ``plot_function``.\n            You can pass in any of the usual style kwargs like ``color=...``,\n            ``marker=...``, etc.\n\n        Returns\n        -------\n        fig : `~matplotlib.Figure`\n\n        \"\"\"\n        from gala.tests.optional_deps import HAS_MATPLOTLIB\n        if not HAS_MATPLOTLIB:\n            raise ImportError('matplotlib is required for visualization.')\n        import matplotlib.pyplot as plt\n\n        if components is None:\n            if self.ndim == 1:  # only a 1D orbit, so just plot time series\n                components = ['t', self.pos.components[0]]\n            else:\n                components = self.pos.components\n\n        x, labels = self._plot_prepare(components=components,\n                                       units=units)\n\n        kwargs.setdefault('marker', '')\n        kwargs.setdefault('linestyle', '-')\n        kwargs.setdefault('labels', labels)\n        kwargs.setdefault('plot_function', plt.plot)\n\n        fig = plot_projections(x, **kwargs)\n\n        if self.pos.get_name() == 'cartesian' and \\\n                all([not c.startswith('d_') for c in components]) and \\\n                't' not in components and \\\n                auto_aspect:\n            for ax in fig.axes:\n                ax.set(aspect='equal', adjustable='datalim')\n\n        return fig\n\n    def plot_3d(self, components=None, units=None, auto_aspect=True,\n                subplots_kwargs=None, **kwargs):\n        \"\"\"\n        Plot the specified 3D components.\n\n        Parameters\n        ----------\n        components : iterable (optional)\n            A list of component names (strings) to plot. By default, this is the\n            Cartesian positions ``['x', 'y', 'z']``. To plot Cartesian\n            velocities, pass in the velocity component names\n            ``['v_x', 'v_y', 'v_z']``. If the representation is different, the\n            component names will be different. For example, for a Cylindrical\n            representation, the components are ``['rho', 'phi', 'z']`` and\n            ``['v_rho', 'pm_phi', 'v_z']``.\n        units : `~astropy.units.UnitBase`, iterable (optional)\n            A single unit or list of units to display the components in.\n        auto_aspect : bool (optional)\n            Automatically enforce an equal aspect ratio.\n        ax : `matplotlib.axes.Axes`\n            The matplotlib Axes object to draw on.\n        subplots_kwargs : dict (optional)\n            Dictionary of kwargs passed to :func:`~matplotlib.pyplot.subplots`.\n        labels : iterable (optional)\n            List or iterable of axis labels as strings. They should correspond\n            to the dimensions of the input orbit.\n        plot_function : str (optional)\n            The ``matplotlib`` plot function to use. By default, this is 'plot'\n            but can also be, e.g., 'scatter'.\n        **kwargs\n            All other keyword arguments are passed to the ``plot_function``.\n            You can pass in any of the usual style kwargs like ``color=...``,\n            ``marker=...``, etc.\n\n        Returns\n        -------\n        fig : `~matplotlib.Figure`\n\n        \"\"\"\n        from gala.tests.optional_deps import HAS_MATPLOTLIB\n        if not HAS_MATPLOTLIB:\n            raise ImportError('matplotlib is required for visualization.')\n        import matplotlib.pyplot as plt\n        from mpl_toolkits import mplot3d  # noqa\n\n        if components is None:\n            components = self.pos.components\n\n        if subplots_kwargs is None:\n            subplots_kwargs = dict()\n\n        if len(components) != 3:\n            raise ValueError(\n                f\"The number of components ({len(components)}) must be 3\")\n\n        x, labels = self._plot_prepare(components=components,\n                                       units=units)\n\n        kwargs.setdefault('marker', '')\n        kwargs.setdefault('linestyle', kwargs.pop('ls', '-'))\n        plot_function_name = kwargs.pop('plot_function', 'plot')\n\n        ax = kwargs.pop('ax', None)\n        subplots_kwargs.setdefault('constrained_layout', True)\n        if ax is None:\n            fig, ax = plt.subplots(figsize=(6, 6),\n                                   subplot_kw=dict(projection='3d'),\n                                   **subplots_kwargs)\n        else:\n            fig = ax.figure\n\n        plot_function = getattr(ax, plot_function_name)\n        if x[0].ndim > 1:\n            for n in range(x[0].shape[1]):\n                plot_function(*[xx[:, n] for xx in x], **kwargs)\n        else:\n            plot_function(*x, **kwargs)\n        ax.set_xlabel(labels[0])\n        ax.set_ylabel(labels[1])\n        ax.set_zlabel(labels[2])\n\n        if self.pos.get_name() == 'cartesian' and \\\n                all([not c.startswith('d_') for c in components]) and \\\n                't' not in components and \\\n                auto_aspect:\n            for ax in fig.axes:\n                ax.set(aspect='auto', adjustable='datalim')\n\n        return fig, ax\n\n    def animate(self,\n                components=None,\n                units=None,\n                stride=1,\n                segment_nsteps=10,\n                underplot_full_orbit=True,\n                marker_style=None,\n                segment_style=None,\n                FuncAnimation_kwargs=None,\n                orbit_plot_kwargs=None,\n                axes=None):\n        \"\"\"\n        Animate an orbit or collection of orbits.\n\n        Parameters\n        ----------\n        components : iterable (optional)\n            A list of component names (strings) to plot. By default, this is the\n            Cartesian positions ``['x', 'y', 'z']``. To plot Cartesian\n            velocities, pass in the velocity component names\n            ``['v_x', 'v_y', 'v_z']``. If the representation is different, the\n            component names will be different. For example, for a Cylindrical\n            representation, the components are ``['rho', 'phi', 'z']`` and\n            ``['v_rho', 'pm_phi', 'v_z']``.\n        units : `~astropy.units.UnitBase`, iterable (optional)\n            A single unit or list of units to display the components in.\n        stride : int (optional)\n            How often to draw a new frame, in terms of orbit timesteps.\n        segment_nsteps : int (optional)\n            How many timesteps to draw in an orbit segment trailing\n            the timestep marker. Set this to 0 or None to disable.\n        underplot_full_orbit : bool (optional)\n            Controls whether to under-plot the full orbit as a thin line.\n        marker_style : dict (optional)\n            Matplotlib style arguments passed to `matplotlib.pyplot.plot`\n            that control the plot style of the timestep marker.\n        segment_style : dict (optional)\n            Matplotlib style arguments passed to `matplotlib.pyplot.plot`\n            that control the plot style of the orbit segment.\n        FuncAnimation_kwargs : dict (optional)\n            Keyword arguments passed through to\n            `matplotlib.animation.FuncAnimation`.\n        orbit_plot_kwargs : dict (optional)\n            Keyword arguments passed through to `gala.dynamics.Orbit.plot`.\n        axes : `matplotlib.axes.Axes` (optional)\n            Where to draw the orbit.\n\n        Returns\n        -------\n        fig : `matplotlib.figure.Figure`\n        anim : `matplotlib.animation.FuncAnimation`\n\n        \"\"\"\n        from gala.tests.optional_deps import HAS_MATPLOTLIB\n        if not HAS_MATPLOTLIB:\n            raise ImportError('matplotlib is required for visualization.')\n        from matplotlib.animation import FuncAnimation\n\n        if components is None:\n            if self.ndim == 1:  # only a 1D orbit, so just plot time series\n                components = ['t', self.pos.components[0]]\n            else:\n                components = self.pos.components\n\n        # Extract the relevant components, in the given unit system\n        xs, _ = self._plot_prepare(components=components,\n                                   units=units)\n        xs = [atleast_2d(xx, insert_axis=1) for xx in xs]\n\n        # Figure out which components to plot on which axes\n        data_paired = []\n        for i in range(len(xs)):\n            for j in range(len(xs)):\n                if i >= j:\n                    continue  # skip diagonal, upper triangle\n                data_paired.append((xs[i], xs[j]))\n\n        if FuncAnimation_kwargs is None:\n            FuncAnimation_kwargs = dict()\n\n        if orbit_plot_kwargs is None:\n            orbit_plot_kwargs = dict()\n        orbit_plot_kwargs.setdefault('zorder', 1)\n        orbit_plot_kwargs.setdefault('color', '#aaaaaa')\n        orbit_plot_kwargs.setdefault('linewidth', '1')\n        orbit_plot_kwargs.setdefault('axes', axes)\n\n        if marker_style is None:\n            marker_style = dict()\n        marker_style.setdefault('marker', 'o')\n        marker_style.setdefault('linestyle', marker_style.pop('ls', 'None'))\n        marker_style.setdefault('markersize', marker_style.pop('ms', 4.))\n        marker_style.setdefault('color', marker_style.pop('c', 'tab:red'))\n        marker_style.setdefault('zorder', 100)\n\n        if segment_style is None:\n            segment_style = dict()\n        segment_style.setdefault('marker', 'None')\n        segment_style.setdefault('linestyle', segment_style.pop('ls', '-'))\n        segment_style.setdefault('linewidth', segment_style.pop('lw', 2.))\n        segment_style.setdefault('color', segment_style.pop('c', 'tab:blue'))\n        segment_style.setdefault('zorder', 10)\n        if segment_nsteps is None or segment_nsteps == 0:  # HACK\n            segment_style['alpha'] = 0\n\n        # Use this to get a figure with axes with the right limits\n        # Note: Labels are added by .plot()\n        if not underplot_full_orbit:\n            orbit_plot_kwargs['alpha'] = 0\n        fig = self.plot(components=components, units=units,\n                        **orbit_plot_kwargs)\n\n        # Set up all of the (data-less) markers and line segments\n        markers = []\n        segments = []\n        for n in range(self.norbits):\n            _m = []\n            _s = []\n            for i in range(len(data_paired)):\n                _m.append(fig.axes[i].plot([], [], **marker_style)[0])\n                _s.append(fig.axes[i].plot([], [], **segment_style)[0])\n            markers.append(_m)\n            segments.append(_s)\n\n        def anim_func(n):\n            i = max(0, n - segment_nsteps)\n\n            for k in range(self.norbits):\n                for j in range(len(data_paired)):\n                    markers[k][j].set_data(data_paired[j][0][n:n+1, k],\n                                           data_paired[j][1][n:n+1, k])\n                    segments[k][j].set_data(data_paired[j][0][i:n+1, k],\n                                            data_paired[j][1][i:n+1, k])\n\n            return (*[m for m in markers for x in m],\n                    *[s for s in segments for x in s])\n\n        anim = FuncAnimation(fig, anim_func,\n                             frames=np.arange(0, self.ntimes, stride),\n                             **FuncAnimation_kwargs)\n\n        return fig, anim\n\n    def to_frame(self, frame, current_frame=None, **kwargs):\n        \"\"\"\n        Transform to a different reference frame.\n\n        Parameters\n        ----------\n        frame : `gala.potential.CFrameBase`\n            The frame to transform to.\n        current_frame : `gala.potential.CFrameBase` (optional)\n            If the Orbit has no associated Hamiltonian, this specifies the\n            current frame of the orbit.\n\n        Returns\n        -------\n        orbit : `gala.dynamics.Orbit`\n            The orbit in the new reference frame.\n\n        \"\"\"\n\n        kw = kwargs.copy()\n\n        # TODO: this short-circuit sux\n        if current_frame is None:\n            current_frame = self.frame\n        if frame == current_frame and not kwargs:\n            return self\n\n        # TODO: need a better way to do this!\n        from ..potential.frame.builtin import ConstantRotatingFrame\n        for fr in [frame, current_frame, self.frame]:\n            if isinstance(fr, ConstantRotatingFrame):\n                if 't' not in kw:\n                    kw['t'] = self.t\n\n        # TODO: this needs a re-write...\n        psp = super().to_frame(frame, current_frame, **kw)\n\n        return Orbit(pos=psp.pos, vel=psp.vel, t=self.t,\n                     frame=frame, potential=self.potential)\n\n    # ------------------------------------------------------------------------\n    # Compatibility with other packages\n    #\n\n    def to_galpy_orbit(self, ro=None, vo=None):\n        \"\"\"Convert this object to a ``galpy.Orbit`` instance.\n\n        Parameters\n        ----------\n        ro : `astropy.units.Quantity` or `astropy.units.UnitBase`\n            \"Natural\" length unit.\n        vo : `astropy.units.Quantity` or `astropy.units.UnitBase`\n            \"Natural\" velocity unit.\n\n        Returns\n        -------\n        galpy_orbit : `galpy.orbit.Orbit`\n\n        \"\"\"\n        from galpy.orbit import Orbit\n        from galpy.util.config import __config__ as galpy_config\n\n        if self.frame is not None:\n            from ..potential import StaticFrame\n            w = self.to_frame(StaticFrame(self.frame.units))\n        else:\n            w = self\n\n        if ro is None:\n            ro = galpy_config.getfloat('normalization', 'ro')\n            ro = ro * u.kpc\n\n        if vo is None:\n            vo = galpy_config.getfloat('normalization', 'vo')\n            vo = vo * u.km/u.s\n\n        # PhaseSpacePosition or Orbit:\n        cyl = w.cylindrical\n\n        R = cyl.rho.to_value(ro).T\n        phi = cyl.phi.to_value(u.rad).T\n        z = cyl.z.to_value(ro).T\n\n        vR = cyl.v_rho.to_value(vo).T\n        vT = (cyl.rho * cyl.pm_phi).to_value(vo, u.dimensionless_angles()).T\n        vz = cyl.v_z.to_value(vo).T\n\n        o = Orbit(np.array([R, vR, vT, z, vz, phi]).T, ro=ro, vo=vo)\n        if w.t is not None:\n            o.t = w.t.to_value(ro / vo)\n\n        return o\n\n    @classmethod\n    def from_galpy_orbit(self, galpy_orbit):\n        \"\"\"Create a Gala ``PhaseSpacePosition`` or ``Orbit`` instance from a\n        ``galpy.Orbit`` instance.\n\n        Parameters\n        ----------\n        galpy_orbit : :class:`galpy.orbit.Orbit`\n\n        Returns\n        -------\n        orbit : :class:`~gala.dynamics.Orbit`\n\n        \"\"\"\n        ro = galpy_orbit._ro * u.kpc\n        vo = galpy_orbit._vo * u.km/u.s\n        ts = galpy_orbit.t\n\n        rep = coord.CylindricalRepresentation(\n            rho=galpy_orbit.R(ts) * ro,\n            phi=galpy_orbit.phi(ts) * u.rad,\n            z=galpy_orbit.z(ts) * ro\n        )\n        with u.set_enabled_equivalencies(u.dimensionless_angles()):\n            dif = coord.CylindricalDifferential(\n                d_rho=galpy_orbit.vR(ts) * vo,\n                d_phi=galpy_orbit.vT(ts) * vo / rep.rho,\n                d_z=galpy_orbit.vz(ts) * vo\n            )\n\n        t = galpy_orbit.t * ro / vo\n        return Orbit(rep, dif, t=t)\n", "meta": {"hexsha": "131effdc453fe91d7c6237864a00b0e540452ca1", "size": 43561, "ext": "py", "lang": "Python", "max_stars_repo_path": "gala/dynamics/orbit.py", "max_stars_repo_name": "akeemlh/gala", "max_stars_repo_head_hexsha": "0fdaf9159bccc59af2a3525f2926e04501754f48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 86, "max_stars_repo_stars_event_min_datetime": "2016-05-19T21:58:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T14:56:37.000Z", "max_issues_repo_path": "gala/dynamics/orbit.py", "max_issues_repo_name": "akeemlh/gala", "max_issues_repo_head_hexsha": "0fdaf9159bccc59af2a3525f2926e04501754f48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 170, "max_issues_repo_issues_event_min_datetime": "2016-06-27T14:10:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T22:52:39.000Z", "max_forks_repo_path": "gala/dynamics/orbit.py", "max_forks_repo_name": "akeemlh/gala", "max_forks_repo_head_hexsha": "0fdaf9159bccc59af2a3525f2926e04501754f48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 66, "max_forks_repo_forks_event_min_datetime": "2016-09-13T07:31:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T15:08:45.000Z", "avg_line_length": 35.7643678161, "max_line_length": 91, "alphanum_fraction": 0.5471407911, "include": true, "reason": "import numpy,from scipy,import astropy", "num_tokens": 9558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.19954527448153153}}
{"text": "from os import path\nimport numpy as np\nfrom pvpy import PowerSpectrum\n\ntry:\n    filename = 'ASTMG173.csv'\n    with open(path.join(__path__[0], filename)) as file:\n        pass\nexcept IOError as e:\n    print(\"Unable to open file %s\" % filename)  # Does not exist OR no read permissions\n# TODO: Maybe allow direct download of ASTM1.5G spectrum if it is missing? It shoudln't be missing.\n#    import os\n#    if not os.path.isfile('ASTMG173.csv'):\n#        try:\n#            import urllib2, StringIO, tarfile\n#            data_url = 'http://rredc.nrel.gov/solar/spectra/am1.5/ASTMG173/compressed/ASTMG173.csv.tar'\n#            download_as_string = urllib2.urlopen(data_url).read()\n#            download_as_file = StringIO.StringIO(download_as_string)\n#            download_as_tarfile_object = tarfile.open(fileobj=download_as_file)\n#            download_as_tarfile_object.extractfile('ASTMG173.csv')\n#        except:\n#            print(\"Unable to open file\")  # Does not exist OR no read permissions\n#            raise\n\n\ndef jsc(*args, kind: str =\"linear\", spectra: str =\"AM1.5G\", **kwargs):\n    \"\"\"\n    Gives the absorbed photocurrent in mA/cm**2 of a normalized spectrum.\n    :param args: (array like) ideally (N,2)D numpy array with spec_in[:,0] as the wavelengths in nm and spec_in[:,1] as\n     the values, but can also be two lists/vectors\n    :param kind: (str) interpolation kind. see scipy.interpolate.interp1d\n    :param spectra:\n    :return:\n    \"\"\"\n    if len(args) > 1:\n        assert args[0].size == args[1].size, \\\n            \"arg1 is %g, arg2 is %g. The inputs should be the same sizes.\" % (args[0].size, args[1].size)\n        args = [np.asarray(arg) if type(arg) is list else arg for arg in args]\n        spec_in = np.column_stack((args[0], args[1]))\n        print(\"Hi\")\n        print(np.shape(spec_in))\n        assert np.shape(spec_in)[1] == 2, \"The input arguments could not be converted to a (N,2) dimensional array.\"\n    elif len(args[0].shape) > 1 and args[0].shape[1] != 1:\n        spec_in = args[0].transpose()\n    else:\n        spec_in = args[0]\n    spec_in = np.squeeze(spec_in)\n    spec = PowerSpectrum.PhotocurrentSpectrum(spec_in[0, 0], spec_in[-1, 0], spectra)\n    spec.weight_spectrum(spec_in, kind=kind)\n    return spec.integrate() * .1\n", "meta": {"hexsha": "610441415f016db93ea327011116be18aeafbe82", "size": 2265, "ext": "py", "lang": "Python", "max_stars_repo_path": "build/lib/solspec/__init__.py", "max_stars_repo_name": "soamaven/pvpy", "max_stars_repo_head_hexsha": "3f8aa318642c91f9585b5885e94a7a464a1208f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-04T13:06:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-04T13:06:54.000Z", "max_issues_repo_path": "build/lib/solspec/__init__.py", "max_issues_repo_name": "soamaven/pvpy", "max_issues_repo_head_hexsha": "3f8aa318642c91f9585b5885e94a7a464a1208f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/lib/solspec/__init__.py", "max_forks_repo_name": "soamaven/pvpy", "max_forks_repo_head_hexsha": "3f8aa318642c91f9585b5885e94a7a464a1208f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.4117647059, "max_line_length": 119, "alphanum_fraction": 0.6463576159, "include": true, "reason": "import numpy", "num_tokens": 627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.1995452744815315}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nWritten by Lucas Sinclair and Paul Rougieux.\n\nJRC Biomass Project.\nUnit D1 Bioeconomy.\n\nTypically you can use this submodule like this:\n\n    >>> from forest_puller.conversion.bcef_by_country import country_bcef\n    >>> print(country_bcef.by_country_year)\n\"\"\"\n\n# Built-in modules #\nimport itertools\n\n# Internal modules #\nfrom forest_puller.conversion.load_expansion_factor import bcef_coefs\nfrom forest_puller.common                           import country_codes\nfrom forest_puller                                  import cache_dir\n\n# First party modules #\nfrom plumbing.cache import property_cached, property_pickled_at\n\n# Third party modules #\nimport numpy, pandas\n\n###############################################################################\nclass CountryBCEF:\n    \"\"\"\n    This class uses the stock of merchantable biomass in each country\n    to choose 2 factors:\n\n    * The biomass conversion and expansion factor BCEF.\n    * The root to shoot ratio R.\n\n    These factors come from table 4.5 and 4.4 respectively in the following\n    IPCC guideline document:\n\n    https://www.ipcc-nggip.iges.or.jp/public/2006gl/pdf/4_Volume4/V4_04_Ch4_Forest_Land.pd\n\n    We first use the BCEF_R to expand the merchantable growing stock volume to\n    above-ground biomass stock. The above ground biomass stock is then used as\n    a threshold to choose the root to shoot ratio.\n\n    Interesting intermediary tables for further analysis:\n\n    * `all_stock_merch` contains the stock in merchantable volume per ha\n      and per leaf type.\n    * `all_stock_abg_biomass` contains the stock in above ground biomass weight\n       expressed in tons per ha and per leaf type.\n    \"\"\"\n\n    min_year = 1990\n    max_year = 2020\n\n    @property_cached\n    def country_climates(self):\n        \"\"\"\n        This dataframe looks like this:\n\n               country  climatic_zone  climatic_coef\n            0       AT         boreal            0.0\n            1       AT      temperate            1.0\n            2       AT  mediterranean            0.0\n            3       BE         boreal            0.0\n            4       BE      temperate            1.0\n        \"\"\"\n        # Load #\n        df = country_codes\n        # Keep only some columns #\n        columns = ['iso2_code', 'boreal', 'temperate', 'mediterranean']\n        df = df[columns].copy()\n        # Rename column #\n        df = df.rename(columns={'iso2_code': 'country'})\n        # Unpivot #\n        df = df.melt(id_vars    = ['country'],\n                     var_name   = 'climatic_zone',\n                     value_name = 'climatic_coef')\n        # Sort #\n        df = df.sort_values('country')\n        # Reset index #\n        df = df.reset_index(drop=True)\n        # Return #\n        return df\n\n    @property\n    def all_stock_merch(self):\n        \"\"\"\n        This data frame looks like this:\n\n            country  year forest_type   area stock_per_ha\n        0        AT  1990         con    ...          ...\n        1        AT  1990       broad    ...          ...\n        2        AT  1990       mixed    ...          ...\n        3        AT  2000         con    ...          ...\n        4        AT  2000       broad    ...          ...\n        ..      ...   ...         ...    ...          ...\n\n        All columns are:\n\n            ['country', 'year', 'forest_type', 'area', 'stock_per_ha']\n\n        \"\"\"\n        # Import #\n        import forest_puller.soef.concat\n        # Load #\n        area  = forest_puller.soef.concat.tables['area_by_type'].copy()\n        stock = forest_puller.soef.concat.tables['stock_by_type'].copy()\n        # Remove null areas and make them NaNs #\n        selector = area.area == 0\n        area.loc[selector, 'area'] = numpy.NaN\n        # Add the area to make one big dataframe #\n        df = stock.left_join(area, on=['country', 'year', 'category'])\n        # Rename category to forest_type #\n        df = df.rename(columns={'category': 'forest_type'})\n        # Compute stock by hectare #\n        df['stock_per_ha'] = df['stock'] / df['area']\n        # Drop lines with NaN #\n        df = df.query(\"stock_per_ha == stock_per_ha\")\n        # Now we don't need the stock column anymore #\n        df = df.drop(columns=['stock'])\n        # Return #\n        return df\n\n    @property\n    def all_stock_merch_by_climate(self):\n        \"\"\"\n        This dataframe looks like this:\n\n               country  year forest_type  area   stock_per_ha  climatic_zone  climatic_coef\n           0        AT  1990         con   ...            ...         boreal            0.0\n           1        AT  1990         con   ...            ...      temperate            1.0\n           2        AT  1990         con   ...            ...  mediterranean            0.0\n           3        AT  1990       broad   ...            ...         boreal            0.0\n           4        AT  1990       broad   ...            ...      temperate            1.0\n\n        Warning: the stock per area values are duplicated for each country and forest type\n\n        All columns are:\n\n            ['country', 'year', 'forest_type', 'area', 'climatic_zone',\n             'climatic_coef', 'stock_per_ha']\n        \"\"\"\n        # Load #\n        df = self.all_stock_merch.copy()\n        # Drop mixed forest #\n        df = df.query(\"forest_type != 'mixed'\")\n        # Add country info #\n        df = df.left_join(self.country_climates, on=\"country\")\n        # Return #\n        return df\n\n    def get_one_bcef(self, row, kind):\n        \"\"\"Function to be applied to each row of the previous dataframe.\"\"\"\n        # If we get a NaN we return a NaN #\n        if row['stock_per_ha'] != row['stock_per_ha']: return numpy.nan\n        # Load #\n        df = bcef_coefs\n        # Select corresponding climatic zone #\n        df = df.query(f\"climatic_zone == '{row['climatic_zone']}'\")\n        # Select corresponding fores type#\n        df = df.query(f\"forest_type == '{row['forest_type']}'\")\n        # Select corresponding bounds on stock per hectare #\n        df = df.query(f\"lower < {row['stock_per_ha']} <= upper\")\n        # Make sure we have note more than one line #\n        assert len(df) <= 1\n        # Extract single float #\n        result = df['bcef' + kind].iloc[0]\n        # Return #\n        return result\n\n    @property\n    def with_bcef_coefs(self):\n        \"\"\"\n        This dataframe is the same as above except we have added three\n        columns. All columns are:\n\n            ['country', 'year', 'forest_type', 'area', 'climatic_zone',\n             'climatic_coef', 'bcefi', 'bcefr', 'bcefs']\n        \"\"\"\n        # Load #\n        df = self.all_stock_merch_by_climate.copy()\n        # Add three columns #\n        df['bcefi'] = df.apply(lambda row: self.get_one_bcef(row, 'i'), axis=1)\n        df['bcefr'] = df.apply(lambda row: self.get_one_bcef(row, 'r'), axis=1)\n        df['bcefs'] = df.apply(lambda row: self.get_one_bcef(row, 's'), axis=1)\n        # Now we don't need the stock_per_ha column anymore #\n        df = df.drop(columns=['stock_per_ha'])\n        # Return #\n        return df\n\n    @property_pickled_at('cache_path')\n    def by_country_year(self):\n        \"\"\"\n        This dataframe has three coefficients 'bcefi', 'bcefr', 'bcefs'\n        for every country and for every SOEF year (except 2015).\n\n        The dataframe looks like this:\n\n                             bcefi     bcefr     bcefs\n            country year\n            AT      1990  0.600000  0.843959  0.764714\n                    2000  0.574885  0.795115  0.720929\n                    2005  0.573515  0.796485  0.722071\n                    2010  0.572161  0.797839  0.723199\n        \"\"\"\n        # Load #\n        df = self.with_bcef_coefs.copy()\n        # Multiply by the climatic situation #\n        df['bcefi'] *= df['climatic_coef']\n        df['bcefr'] *= df['climatic_coef']\n        df['bcefs'] *= df['climatic_coef']\n        # Now we don't need that column anymore #\n        df = df.drop(columns=['climatic_coef'])\n        # Group and sum each BCEF while keeping area #\n        groups = df.groupby(['country', 'year', 'forest_type'])\n        df     = groups.agg({'bcefi': 'sum',\n                             'bcefr': 'sum',\n                             'bcefs': 'sum',\n                             'area':  'first'})\n        # Get the ratio of conifers against broadleaved #\n        groups           = df.groupby(['country', 'year'])\n        df['area_total'] = groups['area'].transform('sum')\n        df['tree_coef']  = df['area'] / df['area_total']\n        # Multiply by the ratio of the given leaf type #\n        df['bcefi'] *= df['tree_coef']\n        df['bcefr'] *= df['tree_coef']\n        df['bcefs'] *= df['tree_coef']\n        # Group and sum each BCEF #\n        groups = df.groupby(['country', 'year'])\n        df     = groups.agg({'bcefi': 'sum',\n                             'bcefr': 'sum',\n                             'bcefs': 'sum'})\n        df = df.reset_index()\n        # Return #\n        return df\n\n    #------------------------------- Interpolation ---------------------------#\n    @property\n    def by_country_year_intrpld(self):\n        \"\"\"\n        Same as above but interpolate the coefficients to get more years.\n        \"\"\"\n        # Create a small data frame with all country and years #\n        countries   = self.by_country_year['country'].drop_duplicates()\n        years       = range(self.min_year, self.max_year)\n        expand_grid = list(itertools.product(countries, years))\n        df          = pandas.DataFrame(expand_grid, columns=('country', 'year'))\n        # Join the BCEF data #\n        df = df.left_join(self.by_country_year, on=['country','year'])\n        # Interpolate #\n        country_groups = df.groupby('country')\n        df['bcefi'] = country_groups['bcefi'].transform(pandas.DataFrame.interpolate,\n                                                        limit_direction='both')\n        df['bcefr'] = country_groups['bcefr'].transform(pandas.DataFrame.interpolate,\n                                                        limit_direction='both')\n        df['bcefs'] = country_groups['bcefs'].transform(pandas.DataFrame.interpolate,\n                                                        limit_direction='both')\n        # Return #\n        return df\n\n    #---------------------------- Special properties -------------------------#\n    @property_cached\n    def all_stock_abg_biomass(self):\n        \"\"\"\n        This data frame contains the above ground biomass stock per hectare\n        expressed in tons of dry biomass. The method converts merchantable\n        biomass volume (m3 of trunk) to above ground biomass weight (tons of\n        dry biomass of trunk plus branches).\n\n        The table looks like this:\n\n            country  year forest_type  area  stock_per_ha\n        1        AT  1990         con   ...           ...\n        1        AT  1990       broad   ...           ...\n        2        AT  1990       mixed   ...           ...\n        3        AT  2000         con   ...           ...\n        \"\"\"\n        # Load #\n        stock_merch          = self.all_stock_merch\n        bcef_by_country_year = self.by_country_year\n        # Join the biomass conversion factors (bcef) to the stock data\n        index = ['country', 'year']\n        df    = stock_merch.left_join(bcef_by_country_year, on=index)\n        # Compute the above ground biomass stock\n        df['stock_per_ha'] *= df['bcefs']\n        # Drop the coefficients columns #\n        df = df.drop(columns=['bcefi', 'bcefr', 'bcefs'])\n        # Return #\n        return df\n\n    # --------------------------------- Cache --------------------------------- #\n    @property\n    def cache_path(self):\n        \"\"\"Specify where on the file system we will pickle the dataframe.\"\"\"\n        path = cache_dir + 'conversion/bcef.pickle'\n        return path\n\n###############################################################################\n# Create a singleton #\ncountry_bcef = CountryBCEF()\n", "meta": {"hexsha": "3b33959998de49a884526d5daf1533f725ea6d9a", "size": 11951, "ext": "py", "lang": "Python", "max_stars_repo_path": "forest_puller/conversion/bcef_by_country.py", "max_stars_repo_name": "xapple/forest_puller", "max_stars_repo_head_hexsha": "3bc9c35e2308e57b90e9210b30d68e67ee86f4d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-10T14:52:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T14:52:34.000Z", "max_issues_repo_path": "forest_puller/conversion/bcef_by_country.py", "max_issues_repo_name": "xapple/forest_puller", "max_issues_repo_head_hexsha": "3bc9c35e2308e57b90e9210b30d68e67ee86f4d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "forest_puller/conversion/bcef_by_country.py", "max_forks_repo_name": "xapple/forest_puller", "max_forks_repo_head_hexsha": "3bc9c35e2308e57b90e9210b30d68e67ee86f4d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-16T08:07:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-16T08:07:28.000Z", "avg_line_length": 39.1836065574, "max_line_length": 91, "alphanum_fraction": 0.5237218643, "include": true, "reason": "import numpy", "num_tokens": 2819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.1995452744815315}}
{"text": "\"\"\" Gravitational Wave Surrogate classes for text and hdf5 files\"\"\"\n\nfrom __future__ import division  # for py2\n\n__copyright__ = \"Copyright (C) 2014 Scott Field and Chad Galley\"\n__email__     = \"sfield@astro.cornell.edu, crgalley@tapir.caltech.edu\"\n__status__    = \"testing\"\n__author__    = \"Jonathan Blackman, Scott Field, Chad Galley, Vijay Varma, Kevin Barkett\"\n\n__license__ = \"\"\"\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\n\n# adding \"_\" prefix to potentially unfamiliar module names\n# so they won't show up in gws' tab completion\nimport numpy as np\nfrom scipy.interpolate import InterpolatedUnivariateSpline as _iuspline\nfrom gwtools.harmonics import sYlm as _sYlm\n\nif __package__ is \"\" or \"None\": # py2 and py3 compatible\n  print(\"setting __package__ to gwsurrogate.new so relative imports work\")\n  __package__=\"gwsurrogate.new\"\n\n# assumes unique global names\nfrom .saveH5Object import SimpleH5Object\nfrom .saveH5Object import H5ObjectList\nfrom .saveH5Object import H5ObjectDict\nfrom .nodeFunction import NodeFunction\nfrom .spline_evaluation import TensorSplineGrid, fast_complex_tensor_spline_eval\nfrom gwsurrogate import spline_interp_Cwrapper\nfrom .tidal_functions import UniversalRelationLambda2ToI, \\\n    UniversalRelationLambda2ToOmega2, UniversalRelationLambda2ToLambda3, \\\n    UniversalRelationLambda3ToOmega3, UniversalRelationLambda2ToAqm, \\\n    EffectiveDeformabilityFromDynamicalTides, PNT2Tidal, \\\n    EffectiveDissipativeDynamicalTides, StrainTidalEnhancementFactor\n\nPARAM_NUDGE_TOL = 1.e-12 # Default relative tolerance for nudging edge cases\n\n\ndef _identity(r1, r2):\n    return r1, r2\ndef _amp_phase(r1, r2):\n    return r1['amp']*np.exp(1.j*r1['phase'])\ndef _re_im(r1, r2):\n    return r1['re'] + 1.j*r1['im']\n\nRECOMBINATION_FUNCS = {\n    'identity': _identity,\n    'amp_phase': _amp_phase,\n    're_im': _re_im,\n        }\n\n\ndef _mode_sum(modes, theta, phi):\n    h = 0.\n    for (ell, m), h_mode in modes.items(): # inefficient in py2\n        h += _sYlm(-2, ell, m, theta, phi) * h_mode\n    return h\n\n\ndef _splinterp(xout, xin, yin, k=3, ext='const'):\n    \"\"\"Uses InterpolatedUnivariateSpline to interpolate real or complex data\"\"\"\n    if np.iscomplexobj(yin):\n        re = _splinterp(xout, xin, np.real(yin), k=k, ext=ext)\n        im = _splinterp(xout, xin, np.imag(yin), k=k, ext=ext)\n        return re + 1.j*im\n    else:\n        return _iuspline(xin, yin, k=k, ext=ext)(xout)\n\ndef _splinterp_Cwrapper(xout, xin, yin):\n    \"\"\"Uses gsl splines with a wrapper to interpolate real or complex data.\n    Uses natural boundary conditions instead of not-a-knot boundary conditions\n    like InterpolatedUnivariateSpline.\"\"\"\n    if len(xin) != len(yin):\n        raise Exception('Expected x and y input lengths to match.')\n    if np.iscomplexobj(yin):\n        re = _splinterp_Cwrapper(xout, xin, np.real(yin))\n        im = _splinterp_Cwrapper(xout, xin, np.imag(yin))\n        return re + 1.j*im\n    else:\n        return spline_interp_Cwrapper.interpolate(xout, xin, yin)\n\n\nclass ParamDim(SimpleH5Object):\n    \"\"\"\n    A helper class containing the information and functions for a single\n    parameter space dimension\n    \"\"\"\n\n    def __init__(self, name='', min_val=0, max_val=1, rtol=PARAM_NUDGE_TOL):\n        \"\"\"\n        name: A descriptive name for this parameter dimension\n        min_val: The minimum allowed value for this parameter\n        max_val: The maximum allowed value for this parameter\n        rtol: A relative tolerance for nudging parameters lying outside\n             [min_val, max_val]. Scaled by (max_val - min_val) for an absolute\n             tolerance. Useful to avoid machine precision issues.\n        \"\"\"\n        super(ParamDim, self).__init__()\n\n        tol = rtol * (max_val - min_val)\n\n        if min_val + 2*tol > max_val:\n            raise Exception(\"tol %s is too large for %s with range [%s, %s]\"%(\n                            tol, name, min_val, max_val))\n\n        self.name = name\n        self.min_val = min_val\n        self.max_val = max_val\n        self.tol = tol\n        self.tol_max = max_val - tol\n        self.tol_min = min_val + tol\n\n    def __str__(self):\n        return self.name\n\n    def __repr__(self):\n        return '%s: [%s, %s] with tol %s'%(self.name, self.min_val,\n                                           self.max_val, self.tol)\n\n    def nudge(self, x):\n        \"\"\"\n        Returns a nudged version of x lying within [min_val+tol, max_val-tol].\n        x can have any shape. Returns x if it already lies in the interval.\n        x must already lie within [min_val - tol, max_val + tol].\n        \"\"\"\n        xmax = np.max(x)\n        xmin = np.min(x)\n\n        if xmax > self.tol_max:\n            if xmax > self.max_val + self.tol:\n                raise Exception(\"The maximum allowed %s is %s, got %s\"%(\n                                self.name, self.max_val, xmax))\n            x = np.amin([x, np.ones(np.shape(x)) * self.tol_max], axis=0)\n\n        if xmin < self.tol_min:\n            if xmin < self.min_val - self.tol:\n                raise Exception(\"The maximum allowed %s is %s, got %s\"%(\n                                self.name, self.min_val, xmin))\n            x = np.amax([x, np.ones(np.shape(x)) * self.tol_min], axis=0)\n\n        return x\n\n\nclass ParamSpace(SimpleH5Object):\n    \"\"\"\n    A helper class for all the parameter domain related information and\n    functions.\n    \"\"\"\n\n    def __init__(self, name='', params=[]):\n        \"\"\"\n        name: A descriptive name for this parameter space\n        params: A list of ParamDim instances, one per parameter dimension\n        \"\"\"\n        super(ParamSpace, self).__init__(['name', 'dim'], ['_params'])\n\n        self.name = name\n        self._params = H5ObjectList(params)\n        self.dim = len(params)\n\n    def __str__(self):\n        return self.name\n\n    def __repr__(self):\n        return '%s: %s'%(self.name, [p.name for p in self._params])\n\n    def param_names(self):\n        \"\"\"Returns the list of names for each parameter space dimension\"\"\"\n        return [p.name for p in self._params]\n\n    def min_vals(self):\n        \"\"\"Returns a list of minimum parameter space values\"\"\"\n        return [p.min_val for p in self._params]\n\n    def max_vals(self):\n        \"\"\"Returns a list of maximum parameter space values\"\"\"\n        return [p.max_val for p in self._params]\n\n    def nudge_params(self, x):\n        \"\"\"\n        Nudges parameters lying slightly outside the valid domain to the\n        boundary. x can be a single 1d parameter vector or a 2d vector with\n        shape (n_params, self.dim).\n        \"\"\"\n\n        xshape = np.shape(x)\n\n        # It's convenient to be able to accept a float instead of a length-1\n        # array for 1d parameter spaces.\n        if len(xshape) == 0:\n            x = np.array([x])\n            xshape = np.shape(x)\n\n        if len(xshape) == 1:\n            if len(x) != self.dim:\n                raise Exception(\"Parameter space has dimension %s, got %s.\"%(\n                                self.dim, xshape))\n            res = np.array([p.nudge(xi) for p, xi in zip(self._params, x)])\n\n        elif len(xshape) == 2:\n            if xshape[1] != self.dim:\n                raise Exception(\"Expecting array with shape (n, %s), got %s\"%(\n                                self.dim, xshape))\n            res = np.array([p.nudge(xi) for p, xi in zip(self._params, x.T)])\n\n        else:\n            raise Exception(\"x should be 1d or 2d, got shape {}\".format(xshape))\n\n        return res\n\n    def h5_prepare_subs(self):\n        \"\"\"Setup dummy subordinates before loading them\"\"\"\n        params = [ParamDim() for _ in range(self.dim)]\n        self._params = H5ObjectList(params)\n\n\nclass _SingleFunctionSurrogate_NoChecks(SimpleH5Object):\n    \"\"\"\n    A surrogate model for a single (real or complex) function on a 1d domain.\n    Skips sanity/validity checks, so should be called with sanitized inputs.\n    Use SingleFunctionSurrogate for actual surrogates of single functions.\n    \"\"\"\n\n    def __init__(self, name=None, ei_basis=None, node_functions=[]):\n        \"\"\"\n        name: A descriptive name for the function this surrogate models\n        ei_basis: A basis with shape (n_nodes, len(domain)).\n                  Interpolation is done via nodes.dot(ei_basis)\n        node_functions: A list of evaluators for each node.\n                        Each one takes a parameter space vector x and returns\n                        the node evaluated at x.\n        \"\"\"\n        super(_SingleFunctionSurrogate_NoChecks, self).__init__(\n                data_keys=['name', 'ei_basis', 'n_nodes'],\n                sub_keys=['node_functions'])\n\n        self.name = name\n        self.ei_basis = ei_basis\n        self.n_nodes = len(node_functions)\n        self.node_functions = H5ObjectList(node_functions)\n\n    def __str__(self):\n        return self.name\n\n    def __repr__(self):\n        return self.name\n\n    def __call__(self, x):\n        \"\"\"\n        Evaluates the surrogate at x, returning the result.\n        \"\"\"\n        nodes = np.array([nf(x) for nf in self.node_functions])\n        return nodes.dot(self.ei_basis)\n\n    def h5_prepare_subs(self):\n        \"\"\"Setup NodeFunctions before loading them\"\"\"\n        tmp_nodes = [NodeFunction() for _ in range(self.n_nodes)]\n        self.node_functions = H5ObjectList(tmp_nodes)\n\n\nclass SingleFunctionSurrogate(_SingleFunctionSurrogate_NoChecks):\n    \"\"\"\n    A surrogate model for a single (real or complex) function on a 1d domain.\n    \"\"\"\n\n    def __init__(self, name=None, domain=None, param_space=None,\n                 ei_basis=None, node_functions=[]):\n        \"\"\"\n        name: A descriptive name for the function this surrogate models\n        domain: A 1d array of the monotonically increasing domain\n                (time/frequency) values\n        param_space: A ParamSpace for this surrogate\n        ei_basis: A basis with shape (n_nodes, len(domain)).\n                  Interpolation is done via nodes.dot(ei_basis)\n        node_functions: A list of evaluators for each node.\n                        Each one takes a parameter space vector x and returns\n                        the node evaluated at x.\n        \"\"\"\n        super(SingleFunctionSurrogate, self).__init__(name=name,\n                ei_basis=ei_basis, node_functions=node_functions)\n\n        if domain is not None and np.min(np.diff(domain)) <= 0.0:\n            raise Exception(\"domain should be monotonically increasing\")\n\n        self.domain = domain\n        self.param_space = param_space\n\n        self._h5_data_keys.append('domain')\n        self._h5_subordinate_keys.append('param_space')\n\n    def h5_prepare_subs(self):\n        super(SingleFunctionSurrogate, self).h5_prepare_subs()\n        self.param_space = ParamSpace()\n\n    def __repr__(self):\n        return '%s (%s)'%(self.name, self.param_space.name)\n\n    def __call__(self, x, domain=None):\n        \"\"\"\n        Evaluates the surrogate at x, returning the result.\n        domain: An optional 1d array of domain values. If given, the result is\n                evaluated at the domain values.\n        \"\"\"\n        # Verify valid parameters and domain\n        x = self.param_space.nudge_params(x)\n        if domain is not None:\n            if domain[0] < self.domain[0] or domain[-1] > self.domain[-1]:\n                raise Exception(\"Domain must lie in [%s, %s]\"%(\n                                self.domain[0], self.domain[-1]))\n\n        res = super(SingleFunctionSurrogate, self).__call__(x)\n\n        if domain is not None:\n            res = _splinterp(domain, self.domain, res)\n\n        return res\n\n\nclass _ManyFunctionSurrogate_NoChecks(SimpleH5Object):\n    \"\"\"\n    A container for surrogates sharing the same parameter space and domain.\n    Skips checks, assuming they have already been performed.\n    \"\"\"\n\n    def __init__(self, name='', single_function_components={},\n                 many_function_components={}, combine_func='identity'):\n        \"\"\"\n        name: A descriptive name for this surrogate.\n        single_function_components: A dictionary of components, where the\n                values are (ei_basis, node_functions) tuples.\n        many_function_components: A dictionary of _ManyFunctionSurrogate_NoCheck\n                components, where the values are\n                (combine_func, single_function_components,\n                 many_function_components) tuples.\n        combine_func: A key of RECOMBINATION_FUNCS used to combine subordinate\n                      results into a single result.\n        \"\"\"\n        super(_ManyFunctionSurrogate_NoChecks, self).__init__(\n                data_keys=['name', 'func_keys', 'sur_keys', 'combine_func'],\n                sub_keys=['func_subs', 'sur_subs'])\n\n        self.name = name\n        self.combine_func = combine_func\n        self.func_keys = list(single_function_components.keys())\n        self.sur_keys = list(many_function_components.keys())\n        if len(set(self.func_keys).intersection(self.sur_keys)) > 0:\n            raise Exception(\"Component keys must be unique! Got %s, %s\"%(\n                            self.func_keys, self.sur_keys))\n\n        func_sub_dict = {}\n        for k, (ei, nf) in single_function_components.items(): # inefficient in py2\n            func_sub_dict[k] = _SingleFunctionSurrogate_NoChecks(k, ei, nf)\n        self.func_subs = H5ObjectDict(func_sub_dict)\n\n        sur_sub_dict = {}\n        for k, (cf, sfc, mfc) in many_function_components.items(): # inefficient in py2\n            sur_sub_dict[k] = _ManyFunctionSurrogate_NoChecks(k, sfc, mfc, cf)\n        self.sur_subs = H5ObjectDict(sur_sub_dict)\n\n    def h5_prepare_subs(self):\n        \"\"\"\n        Initialize subordinate surrogate class instances so they can\n        load their own data from h5 files.\n        \"\"\"\n        self.func_subs = H5ObjectDict({k: _SingleFunctionSurrogate_NoChecks()\n                                       for k in self.func_keys})\n        self.sur_subs = H5ObjectDict({k: _ManyFunctionSurrogate_NoChecks()\n                                      for k in self.sur_keys})\n\n    def __str__(self):\n        return self.name\n\n    def __call__(self, x):\n        func_evals = {k: sur(x) for k, sur in self.func_subs.iteritems()} # inefficient in py2\n        sur_evals = {k: sur(x) for k, sur in self.sur_subs.iteritems()} # inefficient in py2\n        return RECOMBINATION_FUNCS[self.combine_func](func_evals, sur_evals)\n\n    def _eval_func(self, x, key):\n        return self.func_subs[key](x)\n\n    def _eval_sur(self, x, key):\n        return self.sur_subs[key](x)\n\n\nclass ManyFunctionSurrogate(_ManyFunctionSurrogate_NoChecks):\n    \"\"\"\n    A container for surrogates sharing the same parameter space and domain.\n    \"\"\"\n\n    def __init__(self, name='', domain=None, param_space=None,\n                 single_function_components={}, many_function_components={},\n                 combine_func='identity'):\n        \"\"\"\n        name: A descriptive name for this surrogate.\n        param_space: A ParamSpace for this surrogate.\n        single_function_components: A dictionary of components, where the\n                values are (ei_basis, node_functions) tuples.\n        many_function_components: A dictionary of _ManyFunctionSurrogate_NoCheck\n                components, where the values are\n                (combine_func, single_function_components,\n                 many_function_components) tuples.\n        combine_func: A key of RECOMBINATION_FUNCS used to combine subordinate\n                      results into a single result.\n        \"\"\"\n        super(ManyFunctionSurrogate, self).__init__(\n                name=name,\n                single_function_components=single_function_components,\n                many_function_components=many_function_components,\n                combine_func=combine_func,\n            )\n\n        self.domain = domain\n        self.param_space = param_space\n        self._h5_data_keys.append('domain')\n        self._h5_subordinate_keys.append('param_space')\n\n    def h5_prepare_subs(self):\n        super(ManyFunctionSurrogate, self).h5_prepare_subs()\n        self.param_space = ParamSpace()\n\n    def __call__(self, x):\n        \"\"\"\n        Evaluates the surrogate at x, returning the result.\n        \"\"\"\n        # Verify valid parameters\n        x = self.param_space.nudge_params(x)\n        return super(ManyFunctionSurrogate, self)(x)\n\nclass FastTensorSplineSurrogate(SimpleH5Object):\n    \"\"\"\n    A special case of having a complex empirical interpolant combined with\n    tensor splines for the real and imaginary parts of each empirical node,\n    for each waveform mode. All tensor splines must use the same grid.\n    Written for speed, minimizing python operations\n    between tensor spline interpolations, which are done simultaneously for\n    each mode to keep numpy busy. Obtained ~25ms evaluation time per waveform\n    for 12 waveform modes. This was ~66ms when using the python class\n    hierarchy, and using a separate call to numpy for each tensor spline\n    interpolation. Note that similar C code written with gsl splines takes\n    ~50ms, but should have room for optimization.\n    \"\"\"\n\n    def __init__(self, name=None, domain=None, param_space=None,\n                 knot_vecs=[], mode_data={}, modes=None):\n\n        super(FastTensorSplineSurrogate, self).__init__(\n                sub_keys=['param_space', 'ts_grid'],\n                data_keys=['name', 'domain', 'ei', 'cre', 'cim', 'mode_list',\n                           'mode_indices'])\n\n        self.name = name\n        self.domain = domain\n        self.param_space = param_space\n        if param_space is None:\n            self.param_space = ParamSpace()\n        if modes is None:\n            modes = list(mode_data.keys())\n        self.mode_list = modes\n        self.mode_indices = {str(k): i for i, k in enumerate(modes)}\n        self.ei = [mode_data[k][0] for k in modes]\n        self.cre = [mode_data[k][1] for k in modes]\n        self.cim = [mode_data[k][2] for k in modes]\n        self.ts_grid = TensorSplineGrid(knot_vecs)\n\n    def __call__(self, x, theta=None, phi=None, modes=None):\n        \"\"\"\n        Return surrogate evaluation.\n        Arguments:\n            x : The intrinsic parameters (see self.param_space)\n            theta/phi : polar and azimuthal angles of the direction of\n                        gravitational wave emission. If given, sums up modes\n                        and returns h_plus and h_cross (default returns modes)\n            modes : A list of (ell, m) modes to be evaluated (default: all)\n        Returns h:\n            h : If theta and phi are None, h is a dictionary of waveform modes\n                sampled at self.domain with (ell, m) keys.\n                If theta and phi are given, h = h_plus - i * h_cross is a\n                complex array given by the sum of the modes.\n        \"\"\"\n        if (theta is None) != (phi is None):\n            raise Exception(\"Either give theta and phi or neither\")\n\n        x = self.param_space.nudge_params(x)\n\n        if modes is None:\n            modes = self.mode_list\n\n        h_modes = {}\n        for k in modes:\n            i = self.mode_indices[str(k)]\n\n            h_eim = fast_complex_tensor_spline_eval(x,self.ts_grid,self.cre[i],self.cim[i])\n\n            # Evaluate the empirical interpolant\n            h_modes[k] = h_eim.dot(self.ei[i])\n\n        if theta is not None:\n            return _mode_sum(h_modes, theta, phi)\n\n        return h_modes\n\n\nclass MultiModalSurrogate(ManyFunctionSurrogate):\n    \"\"\"\n    A surrogate for multimodal waveforms, where each waveform mode has\n    its own surrogate. Contains added functionality for evaluating on\n    sphere.\n    \"\"\"\n\n    def __init__(self, name=None, domain=None, param_space=None,\n                 mode_data={}, mode_type='complex', modes=None):\n        \"\"\"\n        name: A descriptive name for this surrogate.\n        domain: A 1d array of the monotonically increasing domain\n                (time/frequency) values\n        param_space: A ParamSpace for this surrogate.\n        mode_data: A dictionary of modes with (l, m) integer keys,\n                   where the values are (ei_basis, node_functions) tuples.\n        mode_type: Can be 'amp_phase', 're_im', or 'complex' depending on\n                   how mode surrogates are built. If 'amp_phase' or 're_im',\n                   mode_data values should instead be dictionaries with keys\n                   ['amp', 'phase'] or ['re', 'im'] and\n                   (ei_basis, node_functions) values.\n        modes: A list of (ell, m) modes giving an ordering to mode_data.keys().\n               If None, uses mode_data.keys().\n        \"\"\"\n\n        if mode_type == 'complex':\n            super(MultiModalSurrogate, self).__init__(name, domain, param_space,\n                                                      mode_data, {}, 'identity')\n        elif mode_type in ['amp_phase', 're_im']:\n            mode_data = {k: (mode_type, v, {})\n                         for k, v in mode_data.items()} # inefficient in py2\n            super(MultiModalSurrogate, self).__init__(name, domain, param_space,\n                                                      {}, mode_data, mode_type)\n        else:\n            raise ValueError(\"Invalid mode_type: %s\"%(mode_type))\n\n        self.mode_type = mode_type\n        if modes is None:\n            self.modes = list(mode_data.keys())\n        else:\n            self.modes = modes\n\n        self._h5_data_keys.append('modes')\n        self._h5_data_keys.append('mode_type')\n\n\n    def __call__(self, x, theta=None, phi=None, modes=None):\n        \"\"\"\n        Return surrogate evaluation.\n        Arguments:\n            x : The intrinsic parameters (see self.param_space)\n            theta/phi : polar and azimuthal angles of the direction of\n                        gravitational wave emission. If given, sums up modes\n                        and returns h_plus and h_cross (default returns modes)\n            modes : A list of (ell, m) modes to be evaluated (default: all)\n        Returns h:\n            h : If theta and phi are None, h is a dictionary of waveform modes\n                sampled at self.domain with (ell, m) keys.\n                If theta and phi are given, h = h_plus - i * h_cross is a\n                complex array given by the sum of the modes.\n        \"\"\"\n        if (theta is None) != (phi is None):\n            raise Exception(\"Either give theta and phi or neither\")\n\n        x = self.param_space.nudge_params(x)\n\n        if modes is None:\n            modes = self.modes\n\n        if self.mode_type == 'complex':\n            h_modes = {k: self._eval_func(x, k) for k in modes}\n        else:\n            h_modes = {k: self._eval_sur(x, k) for k in modes}\n\n        if theta is not None:\n            return _mode_sum(h_modes, theta, phi)\n\n        return h_modes\n\n\nclass AlignedSpinCoOrbitalFrameSurrogate(ManyFunctionSurrogate):\n    \"\"\"\n    A surrogate for coorbital frame multimodal waveforms, where each waveform\n    data piece has its own surrogate.\n\n    The waveform data pieces are:\n    Amplitude and phase of the (2,2) mode.\n    Real and imaginary parts of coorbital frame waveform for other modes.\n    \"\"\"\n\n    def __init__(self, name=None, domain=None, param_space=None, \\\n            phaseAlignIdx=None, TaylorT3_t_ref=None, \\\n            coorb_mode_data={(2, 2): {}}\n            ):\n        \"\"\"\n        name:               A descriptive name for this surrogate.\n\n        domain:             A 1d array of the monotonically increasing time\n                            values.\n\n        param_space:        A ParamSpace for this surrogate.\n\n        phaseAlignIdx:      This value should be loaded directly from the\n            surrogate's h5 file. Index of domain at which the orbital phase is\n            aligned. This is used when putting back the TaylorT3 contribution\n            that was subtracted before modeling the phase.\n\n        TaylorT3_t_ref:     This value should be loaded directly from the\n            surrogate's h5 file. This is an arbitrary reference time used\n            in the TaylorT3 contribution, but is fixed during the surrogate\n            construction.\n\n        coorb_mode_data: A dictionary of modes with (l, m) integer keys, where\n            the values are themselves dictionaries containing the coorbital\n            frame waveform for that mode. The coorbital frame is defined as:\n            H_lm = h_lm*exp(i*m*phi_22/2), where h_lm is the inertial frame\n            waveform and h_22 = A_22 * exp(-i phi_22). NOTE the minus sign.\n\n            coorb_mode_data should be a dict with mode_key: mode_value pairs,\n                where mode_value = AmpPhase_22 for mode_key = (2, 2)\n                and mode_value = CoorbReIm_lm for other modes.\n\n            Above, AmpPhase_22 and CoorbReIm_lm are themselved dictionaries:\n                AmpPhase_22 = {'amp': Amp_22, 'phase': phi_22}\n                CoorbReIm_lm = {'re': re_H_lm, 'im': im_H_lm}, where\n                re_H_lm = Real(H_lm) and im_H_lm = Imag(H_lmc).\n            Finally, all of Amp_22, phi_22, re_H_lm and im_H_lm should be\n            (ei_basis, node_functions) tuples of that data piece.\n\n            IMPORTANT NOTE: The phase of (2, 2) mode should be defined with\n            a minus sign as shown above, this is opposite to what is done for\n            MultiModalSurrogate.\n        \"\"\"\n\n        # get list of modes, but move (2,2) mode to start of the list.\n        # This is important because we need the phase of the 22 mode to\n        # transform the other modes from coorbital frame to inertial frame.\n        self.mode_list = list(coorb_mode_data.keys())\n        mode22_idx = [i for i in range(len(self.mode_list)) \\\n            if self.mode_list[i] == tuple([2, 2])]\n        if len(mode22_idx) != 1:\n            raise Exception('Seems to have found multiple or no 22 mode!')\n        mode22_idx = mode22_idx[0]\n\n        # shift 22 mode to the first index\n        self.mode_list.insert(0, self.mode_list.pop(mode22_idx))\n\n        if self.mode_list[0] != tuple([2, 2]):\n            raise Exception('Expected the first mode at this point to be the'\\\n                ' 22 mode.')\n        # make sure shifting the 22 mode index did not delete or add a\n        # mode by mistake\n        if len(self.mode_list) != len(coorb_mode_data.keys()):\n            raise Exception('Number of modes do not agree')\n\n        self.mode_type = 'identity'\n        many_function_components = {}\n        for mode in self.mode_list:\n            many_function_components[mode] = ('identity', \\\n                coorb_mode_data[mode], {})\n\n        # required for TaylorT3\n        self.phaseAlignIdx = phaseAlignIdx\n        self.TaylorT3_t_ref = TaylorT3_t_ref\n        self.TaylorT3_factor_without_eta = None\n\n        super(AlignedSpinCoOrbitalFrameSurrogate, self).__init__(name,\n                domain, param_space, {}, many_function_components,\n                self.mode_type)\n\n        self._h5_data_keys.append('mode_list')\n        self._h5_data_keys.append('mode_type')\n        self._h5_data_keys.append('phaseAlignIdx')\n        self._h5_data_keys.append('TaylorT3_t_ref')\n\n    def _search_omega(self, omega22, omega_val):\n        \"\"\" Find closest index such taht omega22[index] = omega_val\n        \"\"\"\n        # find first index where omega22 > omega_val\n        idx = np.where(omega22 > omega_val)[0][0]\n        # if idx-1 is closer to omega_val, pick that instead\n        if abs(omega22[idx-1] - omega_val) < abs(omega22[idx] - omega_val):\n            idx -= 1\n        return idx\n\n    def _coorbital_to_inertial_frame(self, h_coorb, h_22, mode_list, dtM,\n        timesM, fM_low, fM_ref, do_not_align):\n        \"\"\" Transforms a dict from Coorbital frame to inertial frame.\n\n            The surrogate data is sparsely sampled, so upsamples to time\n            step dtM if given. This is done in the coorbital frame since\n            the waveform is slowly varying in that frame.\n\n            If fM_low is given, only part of the waveform where frequency of\n            the (2, 2) mode is greater than fM_low is retained.\n\n            if do_not_align = False:\n                Aligns the 22 mode phase to be 0 at fM_ref. This means\n                that at this reference frequency, the heavier BH is roughly on\n                the +ve x axis and the lighter BH is on the -ve x axis.\n            do_not_align should be True only when converting from pySurrogate\n            format to gwsurrogate format as we may want to do some checks that\n            the waveform has not been modified\n        \"\"\"\n\n        Amp_22 = h_22[0]['amp']\n        phi_22 = h_22[0]['phase']\n        domain = np.copy(self.domain)\n\n        # Get omega22_sparse, the angular frequency of the 22 mode, from the\n        # sparse surrogate domain.\n        # Use np.diff instead of np.gradient to match the LAL version\n        omega22_sparse = np.append(np.diff(phi_22)/np.diff(domain), 0)\n\n        # t=0 is at the waveform peak for the surrogate\n        peak22Idx = np.argmin(np.abs(domain))\n        omega22_peak = omega22_sparse[peak22Idx]\n        # We ignore the part after the peak.  This way we avoid the noisy part\n        # at late times, which can randomly be at frequency = fM_low.\n        omega22_sparse = omega22_sparse[domain <= domain[peak22Idx]]\n\n        # Get initIdx such that the initial (2, 2) mode frequency ~ fM_low.\n        # We will make this more precise below.\n        if fM_low != 0:\n            omega_low = 2*np.pi*fM_low\n            if omega_low < omega22_sparse[0]:\n                raise ValueError('f_low is lower than the minimum allowed'\n                    ' frequency')\n            if omega_low > omega22_peak:\n                raise ValueError('f_low is higher than the peak frequency')\n\n            # Choose 5 indices less, to ensure omega_low is included\n            initIdx = self._search_omega(omega22_sparse, omega_low) - 5\n            # But if initIdx < 0, we are at the start of the surrogate data\n            # so just choose 0\n            if initIdx < 0:\n                initIdx = 0\n\n        else:\n            # If fM_low is 0, we use the entire waveform\n            initIdx = 0\n\n            # But, if fM_low = 0 and timesM is given, the output of the\n            # interpolant depends very slightly on the length of the sparse\n            # data used to construct the interpolant. So, to achieve machine\n            # precision equivalence between using dtM and timesM options, we\n            # need to do the following: truncate before interpolation to the\n            # same index as the dtM option would have used above (initIdx).\n            # Using 6 rather than 5 because of the greater than condition.\n            if timesM is not None:\n                initIdx = np.where(domain > timesM[0])[0][0] - 6\n\n        Amp_22 = Amp_22[initIdx:]\n        phi_22 = phi_22[initIdx:]\n        domain = domain[initIdx:]\n\n        if timesM is not None:\n            if timesM[-1] > domain[-1]:\n                raise Exception(\"'times' includes times larger than the\"\n                    \" maximum time value in domain.\")\n            if timesM[0] < domain[0]:\n                raise Exception(\"'times' starts before start of domain. Try\"\n                    \" increasing initial value of times or reducing f_low.\")\n\n        if dtM is None and timesM is None:\n            # Use the sparse domain\n            timesM = domain\n            omega22 = omega22_sparse[initIdx:]\n            do_interp = False\n        else:\n            ## Interpolate onto uniform-domain/timesM if needed\n            do_interp = True\n            if dtM is not None:\n                t0 = domain[0]\n                tf = domain[-1]\n                num_times = int(np.ceil((tf - t0)/dtM));\n                timesM = t0 + dtM*np.arange(num_times)\n            else:\n                if timesM[0] < domain[0] or timesM[-1] > domain[-1]:\n                    raise Exception('Trying to evaluate at times outside the'\n                        ' domain.')\n\n            Amp_22 = _splinterp_Cwrapper(timesM, domain, Amp_22)\n            phi_22 = _splinterp_Cwrapper(timesM, domain, phi_22)\n\n            # now recompute omega22 with the dense data, but retain only data\n            # upto the peak to avoid the noisy part\n            omega22 = np.append(np.diff(phi_22)/np.diff(timesM), 0)\n            omega22 = omega22[timesM <= 0]\n\n            # Truncate data so that only freqs above omega_low are retained\n            # If timesM are already given, we don't need to truncate data\n            if dtM is not None:\n                if fM_low != 0:\n                    startIdx = self._search_omega(omega22, omega_low)\n                else:\n                    # If fM_low is 0, we use the entire waveform\n                    startIdx = 0\n\n                Amp_22 = Amp_22[startIdx:]\n                phi_22 = phi_22[startIdx:]\n                omega22 = omega22[startIdx:]\n                timesM = timesM[startIdx:]\n\n\n        # Get reference index where waveform needs to be aligned.\n        if (abs(fM_ref-fM_low) < 1e-13) and (dtM is not None):\n            # This means that the data is already truncated at fM_low,\n            # so we just need the first index for fM_ref=fM_low\n            refIdx = 0\n        else:\n            omega_ref = 2*np.pi*fM_ref\n            if omega_ref > omega22_peak:\n                raise ValueError('f_ref is higher than the peak frequency')\n\n            refIdx = self._search_omega(omega22, omega_ref)\n\n\n        # do_not_align should be True only when converting from pySurrogate\n        # format to gwsurrogate format as we may want to do some checks that\n        # the waveform has not been modified\n        if not do_not_align:\n            # Set orbital phase to 0 refIdx. Note that the Coorbital\n            # frame data is not affected by this constant phase shift.\n\n            # The orbital phase is obtained as phi_22/2, so this leaves a pi\n            # ambiguity.  But the surrogate data is already aligned such that\n            # the heavier BH is on the +ve x-axis at t=-1000M. See Sec.VI.A.4\n            # of arxiv:1812.07865, the resolves the pi ambiguity. This means\n            # that the after the realignment, the orbital phase at reference\n            # frequency is 0.\n            phi_22 += -phi_22[refIdx]\n\n        h_dict = {}\n        for mode in mode_list:\n            if mode == tuple([2, 2]):\n                h_dict[mode] = Amp_22 * np.exp(-1j*phi_22)\n            else:\n                l,m = mode\n                h_coorb_lm = 0\n                if 're' in h_coorb[mode][0].keys():\n                    h_coorb_lm += h_coorb[mode][0]['re'] + 1j * 0\n                if 'im' in h_coorb[mode][0].keys():\n                    h_coorb_lm += 1j*h_coorb[mode][0]['im']\n\n                h_coorb_lm = h_coorb_lm[initIdx:]\n                if do_interp:\n                    h_coorb_lm = _splinterp_Cwrapper(timesM,domain,h_coorb_lm)\n\n                h_dict[mode] = h_coorb_lm * np.exp(-1j*m*phi_22/2.)\n\n        return timesM, h_dict, None     # None is for dynamics\n\n    def _set_TaylorT3_factor(self):\n        \"\"\" Sets a term used in the 0 PN TaylorT3 phase. See Eq.43 of\n        arxiv.1812.07865.\n        \"\"\"\n        # Set only once\n        if self.TaylorT3_factor_without_eta is None:\n            # TaylorT3_t_ref is arbitrary. This is where the phase diverges,\n            # so we choose it much after ringdown. This matches what was used\n            # in the construction of the surrogate. See discussion near Eq.43\n            # of arxiv.1812.07865\n            theta_without_eta = ((self.TaylorT3_t_ref -self.domain)/5)**(-1./8)\n            self.TaylorT3_factor_without_eta = -2./theta_without_eta**5\n\n    def _TaylorT3_phase_22(self, x):\n        \"\"\" 0 PN TaylorT3 phase. See Eq.43 of arxiv.1812.07865\n        \"\"\"\n\n        q, chi1z, chi2z = x\n        eta = q/(1.+q)**2\n\n        # 0PN TaylorT3 phase\n        phi22_T3 = 1./eta**(3./8) * self.TaylorT3_factor_without_eta\n\n        # Align at phaseAlignIdx\n        phi22_T3 -= phi22_T3[self.phaseAlignIdx]\n\n        return phi22_T3\n\n\n    def __call__(self, x, fM_low=None, fM_ref=None, dtM=None,\n            timesM=None, dfM=None, freqsM=None, mode_list=None, ellMax=None,\n            precessing_opts=None, tidal_opts=None, par_dict=None,\n            return_dynamics=False, do_not_align=False):\n        \"\"\"\n    Return dimensionless surrogate modes.\n    Arguments:\n    x :             The intrinsic parameters EXCLUDING total Mass (see\n                    self.param_space)\n\n    fM_low :        Initial frequency of (2,2) mode in units of cycles/M.\n                    If 0, will use the entire data of the surrogate.\n                    Default None.\n\n    fM_ref:         Frequency used to set the reference epoch at which\n                    the reference frame is defined and the spins are specified.\n                    See below for definition of the reference frame.\n                    Default: None.\n\n                    For time domain models, f_ref is used to determine a t_ref,\n                    such that the frequency of the (2, 2) mode equals f_ref at\n                    t=t_ref.\n\n    dtM :           Uniform time step to use, in units of M. If None, the\n                    returned time array will be the array used in the\n                    construction of the surrogate, which can be nonuniformly\n                    sampled.\n                    Default None.\n\n    timesM:         Time samples to evaluate the waveform at. Use either dtM or\n                    timesM, not both.\n\n    dfM :           This should always be None as for now we are assuming\n                    a time domain model.\n\n    freqsM:         Frequency samples to evaluate the waveform at. Use either\n                    dfM or freqsM, not both.\n\n    ellMax:         Maximum ell index for modes to include. All available m\n                    indicies for each ell will be included automatically.\n                    Default: None, in which case all available modes wll be\n                    included.\n\n    mode_list :     A list of (ell, m) modes to be evaluated.\n                    Default None, which evaluates all avilable modes.\n                    Will deduce the m<0 modes from m>0 modes.\n\n    par_dict:       This should always be None for this model.\n\n    do_not_align:   Ignore fM_ref and do not align the waveform. This should be\n                    True only when converting from pySurrogate format to\n                    gwsurrogate format as we may want to do some checks that\n                    the waveform has not been modified.\n\n    Returns\n    timesM, h, dynamics:\n        timesM : time array in units of M.\n        h : A dictionary of waveform modes sampled at timesM with\n            (ell, m) keys.\n        dynamics: None, since this is a nonprecessing model.\n\n\n    IMPORTANT NOTES:\n    ===============\n\n    The reference frame (or inertial frame) is defined as follows:\n        The +ve z-axis is along the orbital angular momentum at the reference\n        epoch. The separation vector from the lighter BH to the heavier BH at\n        the reference epoch is along the +ve x-axis. The y-axis completes the\n        right-handed triad. The reference epoch is set using f_ref.\n        \"\"\"\n\n        if dfM is not None:\n            raise ValueError('Expected dfM to be None for a Time domain model')\n        if freqsM is not None:\n            raise ValueError('Expected freqsM to be None for a Time domain'\n                ' model')\n\n        if mode_list is None:\n            mode_list = self.mode_list\n        if ellMax is not None:\n            if ellMax > np.max(np.array(self.mode_list).T[0]):\n                raise ValueError('ellMax is greater than max allowed ell.')\n            include_modes = np.array(self.mode_list).T[0] <= ellMax\n            mode_list = [self.mode_list[idx]\n                    for idx in range(len(self.mode_list))\n                    if include_modes[idx]]\n\n        if par_dict is not None:\n            raise ValueError('par_dict should be None for this model')\n\n        # always evaluate the (2,2) mode, the other modes neeed this\n        # for transformation from coorbital to inertial frame\n\n        # At this stage the phase of the (2,2) mode is the residual after\n        # removing the TaylorT3 part (see. Eq.44 of arxiv.1812.07865)\n        h_22 = self._eval_sur(x, tuple([2, 2]))\n\n        # Get the TaylorT3 part and add to get the actual phase\n        self._set_TaylorT3_factor()\n        h_22[0]['phase'] += self._TaylorT3_phase_22(x)\n\n        h_coorb = {k: self._eval_sur(x, k) for k in mode_list \\\n                        if k != tuple([2,2])}\n\n        return self._coorbital_to_inertial_frame(h_coorb, h_22, \\\n            mode_list, dtM, timesM, fM_low, fM_ref, do_not_align)\n\nclass AlignedSpinCoOrbitalFrameSurrogateTidal(AlignedSpinCoOrbitalFrameSurrogate):\n    \"\"\"\n    A surrogate for coorbital frame multimodal waveforms, where each waveform\n    data piece has its own surrogate.\n\n    The waveform data pieces are:\n    Amplitude and phase of the (2,2) mode.\n    Real and imaginary parts of coorbital frame waveform for other modes.\n\n    This generates tidal inspiral waveforms by taking the surrogate output tuned\n    to BBH results and incorporates the PN tidal corrections according to the\n    tidal splicing method\n\n    NOTE: This returns the waveform only during the inspiral portion of the\n    binary's evolution, where the PN expansion is still valid; additional work\n    will need to be done in order to complete the merger/ringdown portion of the\n    waveform\n\n    NOTE: The waveform is output with the time set so that t=0 corresponds to\n    the peak of the waveform for the BBH waveform from the underlying surrogate,\n    and NOT the peak of the tidally spliced waveform\n    \"\"\"\n\n    def _coorbital_to_inertial_frame(self, h_coorb, h_22, mode_list, dtM,\n        timesM, fM_low, fM_ref, do_not_align, x):\n        \"\"\" Transforms a dict from Coorbital frame to inertial frame.\n\n            The surrogate data is sparsely sampled, so upsamples to time\n            step dtM if given. This is done in the coorbital frame since\n            the waveform is slowly varying in that frame.\n\n            If fM_low must be specified. The option of fM_low == 0 has been\n            turned off for this model because of its excessive computational\n            cost to evaluate\n\n            if do_not_align = False:\n                Aligns the 22 mode phase to be 0 at fM_ref. This means\n                that at this reference frequency, the heavier BH is roughly on\n                the +ve x axis and the lighter BH is on the -ve x axis.\n            do_not_align should be True only when converting from pySurrogate\n            format to gwsurrogate format as we may want to do some checks that\n            the waveform has not been modified\n        \"\"\"\n\n        Amp_22 = h_22[0]['amp']\n        phi_22 = h_22[0]['phase']\n        domain = np.copy(self.domain)\n\n        # Get omega22_sparse, the angular frequency of the 22 mode, from the\n        # sparse surrogate domain.\n        # Use np.gradient\n        omega22_sparse = np.gradient(phi_22, domain)\n\n        # t=0 is at the waveform peak for the surrogate\n        peak22Idx = np.argmin(np.abs(domain))\n        omega22_peak = omega22_sparse[peak22Idx]\n        # We ignore the part after the peak.  This way we avoid the noisy part\n        # at late times, which can randomly be at frequency = fM_low.\n        omega22_sparse = omega22_sparse[domain <= domain[peak22Idx]]\n\n        # Get initIdx such that the initial (2, 2) mode frequency ~ fM_low.\n        # We will make this more precise below.\n        if fM_low != 0:\n            omega_low = 2*np.pi*fM_low\n            if omega_low < omega22_sparse[0]:\n                raise ValueError('f_low is lower than the minimum allowed'\n                    ' frequency')\n            if omega_low > omega22_peak:\n                raise ValueError('f_low is higher than the peak frequency')\n\n            # Choose 5 indices less, to ensure omega_low is included\n            initIdx = self._search_omega(omega22_sparse, omega_low) - 5\n            # But if initIdx < 0, we are at the start of the surrogate data\n            # so just choose 0\n            if initIdx < 0:\n                initIdx = 0\n        else:\n            raise ValueError(\"The option of setting 'fM_low' to 0 is turned off\"\n                    \" for this model; must specifiy a non-zero 'fM_low'\")\n            ## If fM_low is 0, we use the entire waveform where frequency is\n            ## monotonic, uncomment if want to allow this option\n            #freq_orbital = np.gradient(phi_22[:peak22Idx], domain[:peak22Idx])\n            #if np.min(np.diff(freq_orbital))<=0:\n            #  initIdx = len(freq_orbital)-np.argmin((np.diff(freq_orbital)>np.zeros(len(freq_orbital)-1))[::-1])-1\n            #else:\n            #  initIdx = 0\n\n        Amp_22 = Amp_22[initIdx:peak22Idx]\n        phi_22 = phi_22[initIdx:peak22Idx]\n        domain = domain[initIdx:peak22Idx]\n        v_domain = np.power(np.abs(np.gradient(phi_22, domain))/2,1./3.)\n        if(np.min(np.diff(v_domain))<0):\n            raise ValueError('frequency is not monotonic over the entire'\n                ' considered here')\n\n        if timesM is not None:\n            # This check is performed after the tidal terms computed\n            #if timesM[-1] > domain[-1]:\n            #    raise Exception(\"'times' includes times larger than the\"\n            #        \" maximum time value in domain.\")\n            if timesM[0] < domain[0]:\n                raise Exception(\"'times' starts before start of domain. Try\"\n                    \" increasing initial value of times or reducing f_low.\")\n\n        # For tidal splicing, always want to interpolate first to a dense domain\n        # in order to compute an accurate orbital frequency for the PN equations\n        # then interpolated to the desired times afterwards\n\n        if dtM is None and timesM is None:\n            raise ValueError(\"For this model, must specify either the 'dtM' or\"\n                \" 'timesM' option\")\n        else:\n            ## Interpolate onto uniform domain\n            ## WARNING -- if the the time points are not sampled densely enough\n            ## here, there is a potential for error due to inaccurate orbital\n            ## freq being used for the PN tidal equations\n            if dtM is not None:\n                t0 = domain[0]\n                tf = domain[-1]\n                num_times = int(np.ceil((tf - t0)/dtM));\n                timesM_tmp = t0 + dtM*np.arange(num_times)\n            else:\n                # Because the spliced waveform is shifted so the final time\n                # is the peak of the final waveform, we must ensure the check\n                # here is performed similarly\n                if timesM[0] < (domain[0]-domain[-1]) or timesM[-1] > 0:\n                    raise Exception('Trying to evaluate at times outside the'\n                        ' domain.')\n                min_dt = np.min(np.diff(timesM))\n                t0 = domain[0] #timesM[0] - min_dt\n                tf = domain[-1]\n                num_times = int(np.ceil((tf - t0)/min_dt));\n                timesM_tmp = t0 + min_dt*np.arange(num_times)\n\n            Amp_22 = _splinterp_Cwrapper(timesM_tmp, domain, Amp_22)\n            phi_22 = _splinterp_Cwrapper(timesM_tmp, domain, phi_22)\n\n            # now recompute omega22 with the dense data, but retain only data\n            # upto the peak to avoid the noisy part\n            omega22 = np.gradient(phi_22, timesM_tmp)\n\n            #omega22 = omega22[timesM_tmp <= timesM_tmp[np.argmax(Amp_22)]]\n\n            # Truncate data so that only freqs above omega_low are retained\n            # If timesM are already given, we don't need to truncate data\n            if dtM is not None:\n                if fM_low != 0:\n                    startIdx = max(np.argmin(np.abs(omega22 - omega_low)) - 4,0)\n                else:\n                    raise ValueError(\"The option of setting 'fM_low' to 0\"\n                            \" is turned off for this model; must specifiy a\"\n                            \" non-zero 'fM_low'\")\n                    ## If fM_low is 0, we use the entire waveform that is monotonic\n                    #startIdx = 0\n                    #if np.min(np.diff(omega22))<=0:\n                    #  startIdx = len(omega22)-np.argmin((np.diff(omega22)>np.zeros(len(omega22)-1))[::-1])-1\n                    ## Because the splicing changes the frequencies slightly, to\n                    ## ensure we have wiggle room for interpolation later, buffer\n                    ## the altered initial frequency of the spliced waveform so\n                    ## it is not less than the initial frequency of v_domain\n                    #gap = int((domain[5]-domain[0])/(timesM_tmp[1]-timesM_tmp[0]))\n                    #if startIdx<gap:\n                    #  startIdx=gap\n\n                Amp_22 = Amp_22[startIdx:]\n                phi_22 = phi_22[startIdx:]\n                omega22 = omega22[startIdx:]\n                timesM_tmp = timesM_tmp[startIdx:]\n\n        freq_orbital = np.abs(omega22)/2\n        v = np.power(freq_orbital,1./3.)\n\n        # Setup all of the tidal parameters\n        # Use universal relations to compute parameters beyond the quad love num\n        # NOTE: omega2AB and omega3AB are stored as M*omega{2,3}{A,B}, to use the\n        #   dimensionless value set the total mass of the system and that the\n        #   universal relations return M{A,B}*omega{2,3}{A,B}\n        # Aqm is the dimensionless quadrupole moment, however for splicing the 2PN BBH\n        #   (v^4) term, the qm of a BBH must be subtracted off (Aqm_BH = 1; see\n        #   arXiv:gr-qc/9709032 just below eqn 8), which will be done in the tidal\n        #   function itself\n        # If the NS is spinning, the effective driving frequency that the NS sees,\n        #   from its own reference frame, is shifted according to the NS spin by the\n        #   dimensionless rotation = M omega_spin =  (M / m_NS) * chi_NS / \\bar{I}\n        # WARNING: This effect has been turned off (omega_spin = 0) for NS anti-\n        #   aligned spins, b/c the resonance peak is shifted to early enough in the\n        #   inspiral that the approximation being used to model it might be breaking\n        #   down by the end of the late inspiral (only supposed to be good up until\n        #   shortly after resonance)\n        qqq = x[0]; chiAz = x[1]; chiBz = x[2]; lambda2A = x[3]; lambda2B = x[4]\n        XA = qqq/(1.+qqq); XB = 1.-XA\n        omega2A = lambda3A = omega3A = AqmA = 0.\n        omega2B = lambda3B = omega3B = AqmB = 0.\n        omegaSpinA = omegaSpinB = 0.\n        ell2Adyn = ell2Adiss = ell2Bdyn = ell2Bdiss = np.zeros(len(timesM_tmp))\n        ell3Adyn = ell3Bdyn = np.zeros(len(timesM_tmp))\n        if(lambda2A>0):\n            IbarA     = UniversalRelationLambda2ToI(lambda2A)\n            omegaSpinA = max(chiAz,0) / IbarA / XA\n            omega2A   = UniversalRelationLambda2ToOmega2(lambda2A)/XA\n            lambda3A  = UniversalRelationLambda2ToLambda3(lambda2A)\n            omega3A   = UniversalRelationLambda3ToOmega3(lambda3A)/XA\n            AqmA      = UniversalRelationLambda2ToAqm(lambda2A)\n            ell2Adyn  = EffectiveDeformabilityFromDynamicalTides \\\n                        (np.abs(freq_orbital-omegaSpinA),omega2A,2,qqq)\n            ell3Adyn  = EffectiveDeformabilityFromDynamicalTides \\\n                        (np.abs(freq_orbital-omegaSpinA),omega3A,3,qqq)\n        if(lambda2B>0):\n            IbarB     = UniversalRelationLambda2ToI(lambda2B)\n            omegaSpinB = max(chiBz,0) / IbarB / XB\n            omega2B   = UniversalRelationLambda2ToOmega2(lambda2B)/XB\n            lambda3B  = UniversalRelationLambda2ToLambda3(lambda2B)\n            omega3B   = UniversalRelationLambda3ToOmega3(lambda3B)/XB\n            AqmB      = UniversalRelationLambda2ToAqm(lambda2B)\n            ell2Bdyn  = EffectiveDeformabilityFromDynamicalTides \\\n                        (np.abs(freq_orbital-omegaSpinB),omega2B,2,qqq)\n            ell3Bdyn  = EffectiveDeformabilityFromDynamicalTides \\\n                        (np.abs(freq_orbital-omegaSpinB),omega3B,3,qqq)\n\n        dt_tid, dp_tid = PNT2Tidal(v, qqq, lambda2A*ell2Adyn, \\\n                lambda3A*ell3Adyn, AqmA, chiAz, lambda2B*ell2Bdyn, \\\n                lambda3B*ell3Bdyn, AqmB, chiBz, order=5)\n\n        timesM_tmp += dt_tid - dt_tid[0]\n\n        # Limit the waveform to the last time in the array that is increasing\n        find = np.argmin(np.diff(timesM_tmp)>0)\n        if(find == 0):\n            find = len(timesM_tmp)\n\n        timesM_tmp = timesM_tmp[:find]\n\n        # There is a small region of parameter space where the interpolation\n        # behaves poorly at very late times due to oddly shaped steps, so we\n        # need to check the final handful of steps for that and truncate as\n        # needed to avoid interpolation failures\n        numcheck = 500\n        factorLimit = 2.\n        tdiff = np.diff(timesM_tmp[-numcheck-1:])\n        for i in range(len(tdiff)-1):\n          if ((tdiff[i]>tdiff[i+1]*factorLimit) or (tdiff[i]<tdiff[i+1]/factorLimit)):\n            find = len(timesM_tmp)-numcheck+i-1\n            timesM_tmp = timesM_tmp[:find]\n            break\n\n        timesM_tmp -= timesM_tmp[-1]\n        phi_22 = phi_22[:find] + 2.*(dp_tid[:find] - dp_tid[0])\n\n        # Reinterpolate to the final time grid\n        if dtM is not None:\n            t0 = timesM_tmp[0]\n            tf = timesM_tmp[-1]\n            num_times = int(np.ceil((tf - t0)/dtM));\n            timesM = t0 + dtM*np.arange(num_times)\n            timesM -= timesM[-1] # Ensure peak amplitude at t=0\n        else:\n            if timesM[-1] > timesM_tmp[-1]:\n                raise Exception(\"'times' includes times larger than the\"\n                    \" maximum time value in domain after splicing. (Remember\"\n                    \" that tidal effects cause the binary to merger earlier)\")\n            if timesM[0] < timesM_tmp[0]:\n                raise Exception(\"'times' includes times smaller than the\"\n                    \" initial time value in domain after splicing. (Remember\"\n                    \" that tidal effects cause the binary to merger earlier)\")\n\n        # Find the 'v' corresponding to the final time array, then perform the\n        # interpolation in the 'v' domain as that is where most of the PN\n        # quantities are defined\n        v_uniform = _splinterp_Cwrapper(timesM, timesM_tmp, v[:find])\n\n        Amp_22 = _splinterp_Cwrapper(v_uniform, v[:find], Amp_22[:find])\n        phi_22 = _splinterp_Cwrapper(v_uniform, v[:find], phi_22)\n        freq_orbital = np.power(v_uniform,3.)\n\n        # Dynamical Tidal deformability stuff on final array for strain\n        # amplitudes\n        ell2Adyn = ell2Adiss = ell2Bdyn = ell2Bdiss = np.zeros(len(timesM))\n        if(lambda2A>0):\n          ell2Adyn  = EffectiveDeformabilityFromDynamicalTides \\\n                      (np.abs(freq_orbital-omegaSpinA),omega2A,2,qqq)\n          ell2Adiss = EffectiveDissipativeDynamicalTides \\\n                      (np.abs(freq_orbital-omegaSpinA),ell2Adyn,omega2A,XA)\n        if(lambda2B>0):\n          ell2Bdyn  = EffectiveDeformabilityFromDynamicalTides \\\n                      (np.abs(freq_orbital-omegaSpinB),omega2B,2,qqq)\n          ell2Bdiss = EffectiveDissipativeDynamicalTides \\\n                      (np.abs(freq_orbital-omegaSpinB),ell2Bdyn,omega2B,XB)\n\n        # Get reference index where waveform needs to be aligned.\n        if (abs(fM_ref-fM_low) < 1e-13) and (dtM is not None):\n            # This means that the data is already truncated at fM_low,\n            # so we just need the first index for fM_ref=fM_low\n            refIdx = 0\n        else:\n            omega_ref = 2*np.pi*fM_ref\n            if omega_ref > omega22_peak:\n                raise ValueError('f_ref is higher than the peak frequency')\n\n            refIdx = np.argmin(np.abs(2.*freq_orbital - omega_ref))\n\n\n        # do_not_align should be True only when converting from pySurrogate\n        # format to gwsurrogate format as we may want to do some checks that\n        # the waveform has not been modified\n        if not do_not_align:\n            # Set orbital phase to 0 refIdx. Note that the Coorbital\n            # frame data is not affected by this constant phase shift.\n\n            # The orbital phase is obtained as phi_22/2, so this leaves a pi\n            # ambiguity.  But the surrogate data is already aligned such that\n            # the heavier BH is on the +ve x-axis at t=-1000M. See Sec.VI.A.4\n            # of arxiv:1812.07865, the resolves the pi ambiguity. This means\n            # that the after the realignment, the orbital phase at reference\n            # frequency is 0.\n            phi_22 += -phi_22[refIdx]\n\n\n        h_dict = {}\n        for mode in mode_list:\n            if mode == tuple([2, 2]):\n                h_dict[mode] = (Amp_22+StrainTidalEnhancementFactor(2,2, \\\n                      qqq,(lambda2A*ell2Adiss),(lambda2B*ell2Bdiss),v_uniform)) \\\n                      * np.exp(-1j*phi_22)\n            else:\n                l,m = mode\n                h_coorb_lm = 0\n                if 're' in h_coorb[mode][0].keys():\n                    h_coorb_lm += h_coorb[mode][0]['re'] + 1j * 0\n                if 'im' in h_coorb[mode][0].keys():\n                    h_coorb_lm += 1j*h_coorb[mode][0]['im']\n\n                h_coorb_lm = h_coorb_lm[initIdx:peak22Idx]\n\n                h_coorb_lm = _splinterp_Cwrapper(v_uniform,v_domain,h_coorb_lm)\n\n                h_coorb_lm_amp = np.abs(h_coorb_lm)\n                h_coorb_lm_phase = np.unwrap(np.angle(h_coorb_lm))\n                h_coorb_lm_tid = StrainTidalEnhancementFactor(l,m,qqq, \\\n                        (lambda2A*ell2Adiss),(lambda2B*ell2Bdiss),v_uniform)\n                h_dict[mode] = (h_coorb_lm_amp + h_coorb_lm_tid) \\\n                        * np.exp((-1j*m/2.)*phi_22+1j*h_coorb_lm_phase)\n\n        return timesM, h_dict, None     # None is for dynamics\n\n    def __call__(self, x, fM_low=None, fM_ref=None, dtM=None,\n        timesM=None, dfM=None, freqsM=None, mode_list=None, ellMax=None,\n        precessing_opts=None, tidal_opts=None, par_dict=None,\n        do_not_align=False):\n        \"\"\"\n    Return dimensionless surrogate modes.\n    Arguments:\n    x :             The intrinsic parameters EXCLUDING total Mass (see\n                    self.param_space)\n\n    fM_low :        Initial frequency of (2,2) mode in units of cycles/M.\n                    If 0, will use the entire data of the surrogate.\n                    Default None.\n\n    fM_ref:         Frequency used to set the reference epoch at which\n                    the reference frame is defined and the spins are specified.\n                    See below for definition of the reference frame.\n                    Default: None.\n\n                    For time domain models, f_ref is used to determine a t_ref,\n                    such that the frequency of the (2, 2) mode equals f_ref at\n                    t=t_ref.\n\n    dtM :           Uniform time step to use, in units of M. If None, the\n                    returned time array will be the array used in the\n                    construction of the surrogate, which can be nonuniformly\n                    sampled.\n                    Default None.\n\n    timesM:         Time samples to evaluate the waveform at. Use either dtM or\n                    timesM, not both.\n\n    dfM :           This should always be None as for now we are assuming\n                    a time domain model.\n\n    freqsM:         Frequency samples to evaluate the waveform at. Use either\n                    dfM or freqsM, not both.\n\n    ellMax:         Maximum ell index for modes to include. All available m\n                    indicies for each ell will be included automatically.\n                    Default: None, in which case all available modes wll be\n                    included.\n\n    mode_list :     A list of (ell, m) modes to be evaluated.\n                    Default None, which evaluates all avilable modes.\n                    Will deduce the m<0 modes from m>0 modes.\n\n    par_dict:       This should always be None for this model.\n\n    do_not_align:   Ignore fM_ref and do not align the waveform. This should be\n                    True only when converting from pySurrogate format to\n                    gwsurrogate format as we may want to do some checks that\n                    the waveform has not been modified.\n\n    Returns\n    timesM, h, dynamics:\n        timesM : time array in units of M.\n        h : A dictionary of waveform modes sampled at timesM with\n            (ell, m) keys.\n        dynamics: None, since this is a nonprecessing model.\n\n\n    IMPORTANT NOTES:\n    ===============\n\n    The reference frame (or inertial frame) is defined as follows:\n        The +ve z-axis is along the orbital angular momentum at the reference\n        epoch. The separation vector from the lighter BH to the heavier BH at\n        the reference epoch is along the +ve x-axis. The y-axis completes the\n        right-handed triad. The reference epoch is set using f_ref.\n        \"\"\"\n\n        if par_dict is not None:\n            raise ValueError('Expected par_dict to be None.')\n        if dfM is not None:\n            raise ValueError('Expected dfM to be None for a Time domain model')\n        if freqsM is not None:\n            raise ValueError('Expected freqsM to be None for a Time domain'\n                ' model')\n\n        if mode_list is None:\n            mode_list = self.mode_list\n        if ellMax is not None:\n            if ellMax > np.max(np.array(self.mode_list).T[0]):\n                raise ValueError('ellMax is greater than max allowed ell.')\n            include_modes = np.array(self.mode_list).T[0] <= ellMax\n            mode_list = [self.mode_list[idx]\n                    for idx in range(len(self.mode_list))\n                    if include_modes[idx]]\n\n        # The last to parameters are the tidal parameters and are not a part of\n        # the base surrogate model\n        x_sur = x[:-2]\n\n        # always evaluate the (2,2) mode, the other modes neeed this\n        # for transformation from coorbital to inertial frame\n\n        # At this stage the phase of the (2,2) mode is the residual after\n        # removing the TaylorT3 part (see. Eq.44 of arxiv.1812.07865)\n        h_22 = self._eval_sur(x_sur, tuple([2, 2]))\n\n        # Get the TaylorT3 part and add to get the actual phase\n        self._set_TaylorT3_factor()\n        h_22[0]['phase'] += self._TaylorT3_phase_22(x_sur)\n\n        h_coorb = {k: self._eval_sur(x_sur, k) for k in mode_list \\\n                        if k != tuple([2,2])}\n\n        return self._coorbital_to_inertial_frame(h_coorb, h_22, \\\n            mode_list, dtM, timesM, fM_low, fM_ref, do_not_align, x)\n\n\n\nclass SpEC_nonspinning_q10_surrogate(MultiModalSurrogate):\n    \"\"\"A special class for the SpEC nonspinning surrogate\"\"\"\n\n    skip_2_0_mode = True\n\n    def __call__(self, x, theta=None, phi=None, modes=None,\n                 fake_neg_modes=True):\n        \"\"\"\n        Return surrogate evaluation.\n        Arguments:\n            x : The intrinsic parameters (see self.param_space)\n            theta/phi : polar and azimuthal angles of the direction of\n                        gravitational wave emission. If given, sums up modes\n                        and returns h_plus and h_cross (default returns modes)\n            modes : A list of (ell, m) modes to be evaluated (default: all)\n            fake_neg_modes: Deduce (ell, -m) modes from (ell, m) modes for m>0.\n        Returns h:\n            h : If theta and phi are None, h is a dictionary of waveform modes\n                sampled at self.domain with (ell, m) keys.\n                If theta and phi are given, h = h_plus - i * h_cross is a\n                complex array given by the sum of the modes.\n        \"\"\"\n        if modes is None:\n            modes = self.modes\n\n        if self.skip_2_0_mode:\n            # removed by 2to3 tool\n            #modes = filter(lambda mode: mode != (2, 0), modes)\n            modes = [mode for mode in modes if mode != (2, 0)]\n\n        h_modes = super(SpEC_nonspinning_q10_surrogate, self).__call__(\n                x, modes=modes)\n\n        if fake_neg_modes:\n            new_modes = {}\n            for (ell, m), h in h_modes.items(): # inefficient in py2\n                if m > 0:\n                    new_modes[(ell, -m)] = np.power(-1, ell) * h.conjugate()\n            for k, v in new_modes.items(): # inefficient in py2\n                h_modes[k] = v\n\n        if theta is not None:\n            return _mode_sum(h_modes, theta, phi)\n\n        return h_modes\n", "meta": {"hexsha": "c037fb5d5a92a571ea14dd7076e571f0d57aaeb9", "size": 65447, "ext": "py", "lang": "Python", "max_stars_repo_path": "gwsurrogate/new/surrogate.py", "max_stars_repo_name": "thompsonphys/gwsurrogate", "max_stars_repo_head_hexsha": "d32fbd4506c664ab7b7c6048edbd51835b17b644", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-04-11T12:52:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T07:40:04.000Z", "max_issues_repo_path": "gwsurrogate/new/surrogate.py", "max_issues_repo_name": "jyoo1042/gwsurrogate", "max_issues_repo_head_hexsha": "1459f8e6a855d183a4a3b08e4fcd36d2d14f5285", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2019-11-24T07:39:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-02T09:35:08.000Z", "max_forks_repo_path": "gwsurrogate/new/surrogate.py", "max_forks_repo_name": "jyoo1042/gwsurrogate", "max_forks_repo_head_hexsha": "1459f8e6a855d183a4a3b08e4fcd36d2d14f5285", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-12-05T20:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T10:17:02.000Z", "avg_line_length": 43.2850529101, "max_line_length": 115, "alphanum_fraction": 0.6060934802, "include": true, "reason": "import numpy,from scipy", "num_tokens": 15757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.1995452669911025}}
{"text": "from __future__ import print_function, division\n\nfrom sympy import Expr, sympify, Symbol, Matrix\nfrom sympy.printing.pretty.stringpict import prettyForm\nfrom sympy.core.containers import Tuple\nfrom sympy.core.compatibility import is_sequence, string_types\n\nfrom sympy.physics.quantum.dagger import Dagger\nfrom sympy.physics.quantum.matrixutils import (\n    numpy_ndarray, scipy_sparse_matrix,\n    to_sympy, to_numpy, to_scipy_sparse\n)\n\n__all__ = [\n    'QuantumError',\n    'QExpr'\n]\n\n\n#-----------------------------------------------------------------------------\n# Error handling\n#-----------------------------------------------------------------------------\n\nclass QuantumError(Exception):\n    pass\n\n\ndef _qsympify_sequence(seq):\n    \"\"\"Convert elements of a sequence to standard form.\n\n    This is like sympify, but it performs special logic for arguments passed\n    to QExpr. The following conversions are done:\n\n    * (list, tuple, Tuple) => _qsympify_sequence each element and convert\n      sequence to a Tuple.\n    * basestring => Symbol\n    * Matrix => Matrix\n    * other => sympify\n\n    Strings are passed to Symbol, not sympify to make sure that variables like\n    'pi' are kept as Symbols, not the SymPy built-in number subclasses.\n\n    Examples\n    ========\n\n    >>> from sympy.physics.quantum.qexpr import _qsympify_sequence\n    >>> _qsympify_sequence((1,2,[3,4,[1,]]))\n    (1, 2, (3, 4, (1,)))\n\n    \"\"\"\n\n    return tuple(__qsympify_sequence_helper(seq))\n\n\ndef __qsympify_sequence_helper(seq):\n    \"\"\"\n       Helper function for _qsympify_sequence\n       This function does the actual work.\n    \"\"\"\n    #base case. If not a list, do Sympification\n    if not is_sequence(seq):\n        if isinstance(seq, Matrix):\n            return seq\n        elif isinstance(seq, string_types):\n            return Symbol(seq)\n        else:\n            return sympify(seq)\n\n    # base condition, when seq is QExpr and also\n    # is iterable.\n    if isinstance(seq, QExpr):\n        return seq\n\n    #if list, recurse on each item in the list\n    result = [__qsympify_sequence_helper(item) for item in seq]\n\n    return Tuple(*result)\n\n\n#-----------------------------------------------------------------------------\n# Basic Quantum Expression from which all objects descend\n#-----------------------------------------------------------------------------\n\nclass QExpr(Expr):\n    \"\"\"A base class for all quantum object like operators and states.\"\"\"\n\n    # In sympy, slots are for instance attributes that are computed\n    # dynamically by the __new__ method. They are not part of args, but they\n    # derive from args.\n\n    # The Hilbert space a quantum Object belongs to.\n    __slots__ = ['hilbert_space']\n\n    is_commutative = False\n\n    # The separator used in printing the label.\n    _label_separator = u''\n\n    @property\n    def free_symbols(self):\n        return {self}\n\n    def __new__(cls, *args, **old_assumptions):\n        \"\"\"Construct a new quantum object.\n\n        Parameters\n        ==========\n\n        args : tuple\n            The list of numbers or parameters that uniquely specify the\n            quantum object. For a state, this will be its symbol or its\n            set of quantum numbers.\n\n        Examples\n        ========\n\n        >>> from sympy.physics.quantum.qexpr import QExpr\n        >>> q = QExpr(0)\n        >>> q\n        0\n        >>> q.label\n        (0,)\n        >>> q.hilbert_space\n        H\n        >>> q.args\n        (0,)\n        >>> q.is_commutative\n        False\n        \"\"\"\n\n        # First compute args and call Expr.__new__ to create the instance\n        args = cls._eval_args(args)\n        if len(args) == 0:\n            args = cls._eval_args(tuple(cls.default_args()))\n        inst = Expr.__new__(cls, *args, **old_assumptions)\n        # Now set the slots on the instance\n        inst.hilbert_space = cls._eval_hilbert_space(args)\n        return inst\n\n    @classmethod\n    def _new_rawargs(cls, hilbert_space, *args, **old_assumptions):\n        \"\"\"Create new instance of this class with hilbert_space and args.\n\n        This is used to bypass the more complex logic in the ``__new__``\n        method in cases where you already have the exact ``hilbert_space``\n        and ``args``. This should be used when you are positive these\n        arguments are valid, in their final, proper form and want to optimize\n        the creation of the object.\n        \"\"\"\n\n        obj = Expr.__new__(cls, *args, **old_assumptions)\n        obj.hilbert_space = hilbert_space\n        return obj\n\n    #-------------------------------------------------------------------------\n    # Properties\n    #-------------------------------------------------------------------------\n\n    @property\n    def label(self):\n        \"\"\"The label is the unique set of identifiers for the object.\n\n        Usually, this will include all of the information about the state\n        *except* the time (in the case of time-dependent objects).\n\n        This must be a tuple, rather than a Tuple.\n        \"\"\"\n        if len(self.args) == 0:  # If there is no label specified, return the default\n            return self._eval_args(list(self.default_args()))\n        else:\n            return self.args\n\n    @property\n    def is_symbolic(self):\n        return True\n\n    @classmethod\n    def default_args(self):\n        \"\"\"If no arguments are specified, then this will return a default set\n        of arguments to be run through the constructor.\n\n        NOTE: Any classes that override this MUST return a tuple of arguments.\n        Should be overridden by subclasses to specify the default arguments for kets and operators\n        \"\"\"\n        raise NotImplementedError(\"No default arguments for this class!\")\n\n    #-------------------------------------------------------------------------\n    # _eval_* methods\n    #-------------------------------------------------------------------------\n\n    def _eval_adjoint(self):\n        obj = Expr._eval_adjoint(self)\n        if obj is None:\n            obj = Expr.__new__(Dagger, self)\n        if isinstance(obj, QExpr):\n            obj.hilbert_space = self.hilbert_space\n        return obj\n\n    @classmethod\n    def _eval_args(cls, args):\n        \"\"\"Process the args passed to the __new__ method.\n\n        This simply runs args through _qsympify_sequence.\n        \"\"\"\n        return _qsympify_sequence(args)\n\n    @classmethod\n    def _eval_hilbert_space(cls, args):\n        \"\"\"Compute the Hilbert space instance from the args.\n        \"\"\"\n        from sympy.physics.quantum.hilbert import HilbertSpace\n        return HilbertSpace()\n\n    #-------------------------------------------------------------------------\n    # Printing\n    #-------------------------------------------------------------------------\n\n    # Utilities for printing: these operate on raw sympy objects\n\n    def _print_sequence(self, seq, sep, printer, *args):\n        result = []\n        for item in seq:\n            result.append(printer._print(item, *args))\n        return sep.join(result)\n\n    def _print_sequence_pretty(self, seq, sep, printer, *args):\n        pform = printer._print(seq[0], *args)\n        for item in seq[1:]:\n            pform = prettyForm(*pform.right((sep)))\n            pform = prettyForm(*pform.right((printer._print(item, *args))))\n        return pform\n\n    # Utilities for printing: these operate prettyForm objects\n\n    def _print_subscript_pretty(self, a, b):\n        top = prettyForm(*b.left(' '*a.width()))\n        bot = prettyForm(*a.right(' '*b.width()))\n        return prettyForm(binding=prettyForm.POW, *bot.below(top))\n\n    def _print_superscript_pretty(self, a, b):\n        return a**b\n\n    def _print_parens_pretty(self, pform, left='(', right=')'):\n        return prettyForm(*pform.parens(left=left, right=right))\n\n    # Printing of labels (i.e. args)\n\n    def _print_label(self, printer, *args):\n        \"\"\"Prints the label of the QExpr\n\n        This method prints self.label, using self._label_separator to separate\n        the elements. This method should not be overridden, instead, override\n        _print_contents to change printing behavior.\n        \"\"\"\n        return self._print_sequence(\n            self.label, self._label_separator, printer, *args\n        )\n\n    def _print_label_repr(self, printer, *args):\n        return self._print_sequence(\n            self.label, ',', printer, *args\n        )\n\n    def _print_label_pretty(self, printer, *args):\n        return self._print_sequence_pretty(\n            self.label, self._label_separator, printer, *args\n        )\n\n    def _print_label_latex(self, printer, *args):\n        return self._print_sequence(\n            self.label, self._label_separator, printer, *args\n        )\n\n    # Printing of contents (default to label)\n\n    def _print_contents(self, printer, *args):\n        \"\"\"Printer for contents of QExpr\n\n        Handles the printing of any unique identifying contents of a QExpr to\n        print as its contents, such as any variables or quantum numbers. The\n        default is to print the label, which is almost always the args. This\n        should not include printing of any brackets or parenteses.\n        \"\"\"\n        return self._print_label(printer, *args)\n\n    def _print_contents_pretty(self, printer, *args):\n        return self._print_label_pretty(printer, *args)\n\n    def _print_contents_latex(self, printer, *args):\n        return self._print_label_latex(printer, *args)\n\n    # Main printing methods\n\n    def _sympystr(self, printer, *args):\n        \"\"\"Default printing behavior of QExpr objects\n\n        Handles the default printing of a QExpr. To add other things to the\n        printing of the object, such as an operator name to operators or\n        brackets to states, the class should override the _print/_pretty/_latex\n        functions directly and make calls to _print_contents where appropriate.\n        This allows things like InnerProduct to easily control its printing the\n        printing of contents.\n        \"\"\"\n        return self._print_contents(printer, *args)\n\n    def _sympyrepr(self, printer, *args):\n        classname = self.__class__.__name__\n        label = self._print_label_repr(printer, *args)\n        return '%s(%s)' % (classname, label)\n\n    def _pretty(self, printer, *args):\n        pform = self._print_contents_pretty(printer, *args)\n        return pform\n\n    def _latex(self, printer, *args):\n        return self._print_contents_latex(printer, *args)\n\n    #-------------------------------------------------------------------------\n    # Methods from Basic and Expr\n    #-------------------------------------------------------------------------\n\n    def doit(self, **kw_args):\n        return self\n\n    #-------------------------------------------------------------------------\n    # Represent\n    #-------------------------------------------------------------------------\n\n    def _represent_default_basis(self, **options):\n        raise NotImplementedError('This object does not have a default basis')\n\n    def _represent(self, **options):\n        \"\"\"Represent this object in a given basis.\n\n        This method dispatches to the actual methods that perform the\n        representation. Subclases of QExpr should define various methods to\n        determine how the object will be represented in various bases. The\n        format of these methods is::\n\n            def _represent_BasisName(self, basis, **options):\n\n        Thus to define how a quantum object is represented in the basis of\n        the operator Position, you would define::\n\n            def _represent_Position(self, basis, **options):\n\n        Usually, basis object will be instances of Operator subclasses, but\n        there is a chance we will relax this in the future to accommodate other\n        types of basis sets that are not associated with an operator.\n\n        If the ``format`` option is given it can be (\"sympy\", \"numpy\",\n        \"scipy.sparse\"). This will ensure that any matrices that result from\n        representing the object are returned in the appropriate matrix format.\n\n        Parameters\n        ==========\n\n        basis : Operator\n            The Operator whose basis functions will be used as the basis for\n            representation.\n        options : dict\n            A dictionary of key/value pairs that give options and hints for\n            the representation, such as the number of basis functions to\n            be used.\n        \"\"\"\n        basis = options.pop('basis', None)\n        if basis is None:\n            result = self._represent_default_basis(**options)\n        else:\n            result = dispatch_method(self, '_represent', basis, **options)\n\n        # If we get a matrix representation, convert it to the right format.\n        format = options.get('format', 'sympy')\n        result = self._format_represent(result, format)\n        return result\n\n    def _format_represent(self, result, format):\n        if format == 'sympy' and not isinstance(result, Matrix):\n            return to_sympy(result)\n        elif format == 'numpy' and not isinstance(result, numpy_ndarray):\n            return to_numpy(result)\n        elif format == 'scipy.sparse' and \\\n                not isinstance(result, scipy_sparse_matrix):\n            return to_scipy_sparse(result)\n\n        return result\n\n\ndef split_commutative_parts(e):\n    \"\"\"Split into commutative and non-commutative parts.\"\"\"\n    c_part, nc_part = e.args_cnc()\n    c_part = list(c_part)\n    return c_part, nc_part\n\n\ndef split_qexpr_parts(e):\n    \"\"\"Split an expression into Expr and noncommutative QExpr parts.\"\"\"\n    expr_part = []\n    qexpr_part = []\n    for arg in e.args:\n        if not isinstance(arg, QExpr):\n            expr_part.append(arg)\n        else:\n            qexpr_part.append(arg)\n    return expr_part, qexpr_part\n\n\ndef dispatch_method(self, basename, arg, **options):\n    \"\"\"Dispatch a method to the proper handlers.\"\"\"\n    method_name = '%s_%s' % (basename, arg.__class__.__name__)\n    if hasattr(self, method_name):\n        f = getattr(self, method_name)\n        # This can raise and we will allow it to propagate.\n        result = f(arg, **options)\n        if result is not None:\n            return result\n    raise NotImplementedError(\n        \"%s.%s can't handle: %r\" %\n        (self.__class__.__name__, basename, arg)\n    )\n", "meta": {"hexsha": "6aa389f62fd3bf3626492749177568b577d9f65c", "size": 14257, "ext": "py", "lang": "Python", "max_stars_repo_path": "sympy/physics/quantum/qexpr.py", "max_stars_repo_name": "FabianBall/sympy", "max_stars_repo_head_hexsha": "9d849ddfc45427fe7f6733ce4d18fa397d0f43a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-01-17T23:15:04.000Z", "max_stars_repo_stars_event_max_datetime": "2015-05-26T14:11:44.000Z", "max_issues_repo_path": "sympy/physics/quantum/qexpr.py", "max_issues_repo_name": "FabianBall/sympy", "max_issues_repo_head_hexsha": "9d849ddfc45427fe7f6733ce4d18fa397d0f43a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-08-26T01:07:46.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-26T16:05:49.000Z", "max_forks_repo_path": "sympy/physics/quantum/qexpr.py", "max_forks_repo_name": "FabianBall/sympy", "max_forks_repo_head_hexsha": "9d849ddfc45427fe7f6733ce4d18fa397d0f43a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-10-21T06:32:46.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-21T06:32:46.000Z", "avg_line_length": 33.864608076, "max_line_length": 98, "alphanum_fraction": 0.5945149751, "include": true, "reason": "from sympy", "num_tokens": 3060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.19954526699110245}}
{"text": "import numpy as np\nimport random\nimport statsmodels.api as sm\nimport itertools as it\nimport os\nfrom statsmodels.sandbox.stats.multicomp import multipletests\nfrom itertools import compress\nfrom sys import argv\n\ndef read_gems(directory, file_name):\n    \"\"\"\n    Read a GEM file of the form \"PlinePgem\".\n    Args:\n       directory (str): directory of the file location (ex: '/Users/kimm/')\n       file_name (str): name of the file (ex: 'SHG0008H.Fragnum_PlinePgem')\n    Returns:\n       in_gems (list): tab-separated lists of lists\n    \"\"\"\n    with open(directory + file_name) as f:\n        next(f)\n        for line in f:\n            entries = line.strip().split(\"\\t\")\n            frags = entries[4]\n            gem_id = entries[0]\n            in_gems.append([frags+'|'+gem_id])\n    return in_gems\n\ndef read_chroms(directory, genome_name):\n    \"\"\"\n    Read a tab-delimited text file with list of chromosomes and their sizes.\n    Args:\n       directory (str): directory of the file location (ex: '/Users/kimm/')\n       genome_name (str): name of reference genome (ex: 'dm3', 'mm10', 'hg38', 'hg19', etc.)\n                        Note: must have a text file <genome_name>.chrom.sizes in the directory.\n    Returns:\n       chrom_dict (dictionary): tab-separated lists of lists\n    \"\"\"\n    chrom_dict = {}\n    with open(directory + genome_name + '.chrom.sizes') as f:\n        for line in f:\n            tmp_list = line.strip().split(\"\\t\")\n            chrom_dict[tmp_list[0]] = int(tmp_list[1])\n    return chrom_dict\n\ndef extract_info(gem_list):\n    \"\"\"\n    Extract necessary information from input gem.\n    Args:\n       gem_list (list): list with 10 items as encoded in PlinePgem file\n    Returns:\n       gem_id (str): GEM ID (ex: SHG0008H-1000-10000799-AAACACCCACTAGTAC-K00384-FA-1-0)\n       chrom (str): chromosome name (ex: chr2L)\n       frags (list of list): [start,end] for each fragment \n                        (ex: [3251935, 3252561], [3413857, 3414485])\n       span (int): start of leftmost fragment to end of rightmost fragment (ex: 162550)\n       fraglen (list): length of each fragment (ex: [626, 628])\n       f2fdist (list): distance between neighboring fragments (ex: [161296])\n       fragnum (int): number of fragments\n       fragstr (str): fragment coordinates string\n       coord (str): gem coordinates\n    \"\"\"\n    raw_frags = gem_list[0].split(\"|\")[0].split(\";\")\n    frags = []\n    for j in range(len(raw_frags)):\n        bedentry = raw_frags[j].split(\"(\")[0].replace(\"-\", \":\").split(\":\")\n        frags.append([int(x) for x in bedentry[1:]])\n    if '|' in gem_list[0]:\n        gem_id = gem_list[0].split(\"|\")[1]\n    else:\n        gem_id = ''\n    chrom = bedentry[0]\n    span = frags[-1][1] - frags[0][0]\n    fraglen = [x[1]-x[0] for x in frags]\n    f2fdist = [frags[x][0]-frags[x-1][1] for x in range(1,len(frags))]\n    fragnum = j + 1\n    fragstr = ';'.join([chrom+':'+str(x[0])+'-'+str(x[1]) for x in frags])\n    coord = chrom+':'+str(frags[0][0])+'-'+str(frags[-1][1])\n    return gem_id, chrom, frags, span, fraglen, f2fdist, fragnum, fragstr, coord\n\ndef norm_shannon_ent(prob_list):\n    \"\"\"\n    Compute the normalized Shannon entropy of a list of probabilities.\n    Args:\n       prob_list (list): list of probabilities (ex: [0.1, 0.4, 0.5])\n    Returns:\n       entropy (float): tab-separated lists of lists (ex: 0.85867)\n    \"\"\"\n    if sum(prob_list) != 1:   ## input is count or frequency instead of probability\n        prob_list = [i/sum(prob_list) for i in prob_list]\n    entropy = sum([x*np.log2(1/x) for x in prob_list])/np.log2(len(prob_list))\n    return float(format(entropy, '.5f'))\n\ndef create_pseudo_gems(f2f_bucket, fragnum_bucket, samp_size, file_name):\n    \"\"\"\n    Create <samp_size> pseudoGEMs for each unique fragment number.\n    Args:\n       f2f_bucket (list): list of fragment-to-fragment distances, from which samples will be drawn\n       fragnum_bucket (list): number of fragments in each GEM for all GEMs\n       samp_size (int): number of pseudoGEMs to create\n       file_name (str): file to write 1000 pseudoGEMs per frag_num\n    Returns:\n       pseudo_gem_tot_dist (dictionary): dictionary of a list of <samp_size> total distances for fragnum\n       pseudo_gem_mean_ent (dictionary): dictionary of mean entropy for fragnum\n    \"\"\"\n    unique_frag_num = sorted(list(set(fragnum_bucket)))\n    f2f_bucket_size = len(f2f_bucket)\n    bucket_array = np.array(f2f_bucket)\n    pseudo_gem_tot_dist = {}\n    pseudo_gem_mean_ent = {}\n    np.random.seed(12345)\n    with open(file_name, 'a') as file1:\n        for i in unique_frag_num:\n            rand_ind = list(np.random.choice(range(f2f_bucket_size), (i-1)*samp_size))\n            count = 0\n            sum_ent = 0\n            tmp_tot_dist = []\n            for j in range(0,len(rand_ind), (i-1)):\n                tmp_dist = bucket_array[rand_ind[j:(j+i-1)]].tolist()\n                # get normalized Shannon entropy of first 1000 pseudoGEMs if a given GEM has > 2 fragments\n                if (count < 1000): \n                    file1.write(str(i) + '\\t')\n                    file1.write(';'.join(map(str, tmp_dist)) + '\\t')\n                    if (i > 2):\n                        tmp_ent = norm_shannon_ent(tmp_dist)\n                        file1.write(str(tmp_ent) + '\\n')\n                        sum_ent = sum_ent + tmp_ent\n                    else:\n                        file1.write(\"NA\" + '\\n')\n                    count += 1\n                tmp_tot_dist.append(sum(tmp_dist))\n            pseudo_gem_tot_dist[str(i)] = np.sort(tmp_tot_dist)\n            pseudo_gem_mean_ent[str(i)] = float(format(sum_ent/1000, '.5f'))\n        pseudo_gem_tot_dist['1'] = [] # empty for singleton\n    file1.close()\n    return pseudo_gem_tot_dist, pseudo_gem_mean_ent\n\n\ndef get_raw_pval(f2f_dist, pseudo_gem_dist, samp_size):\n    \"\"\"\n    Get raw p-value by performing a distance test.\n    Args:\n       f2f_dist (list): fragment-to-fragment distances for a GEM (ex: [446,21231,249])\n       pseudo_gem_dist (list): pseudo gem total distances of a given <fragnum>\n       samp_size (int): number of pseudoGEMs to create (ex: 10000)\n    Returns:\n       raw_pval (float): raw p-value from a total distance test; '.' if singleton GEM\n    \"\"\"\n    if not f2f_dist:\n        pval = '.'\n    else:\n        tot_dist = sum(f2f_dist)\n        count = max(1, np.searchsorted(pseudo_gem_dist, tot_dist))\n        pval = count/samp_size\n    return pval\n\ndef get_adj_pval(raw_pval_list, fdr_thresh, method):\n    \"\"\" \n    Adjust raw pvalues by Benjamini Hochberg multiple testing adjustment. \n    Args:\n       raw_pval_list (list): list of raw p-values (ex: [0.1, 0.04, 0.1])\n       fdr_thresh (float): false discovery rate (ex: 0.05)\n       method (string): adjustment method (ex: 'fdr_bh')\n    Returns:\n       adj_pval_list (array): array of booleans and adjusted p-values (ex: [0.1, 0.1, 0.1])\n    \"\"\"\n    adj_pval_list = multipletests(raw_pval_list, alpha = fdr_thresh, method = method)\n    return(adj_pval_list)\n\ndef entropy_filter(in_gem, pseudo_gem_ent, cutoff_ent_filter):\n    \"\"\" \n    Filter a GEM into subGEMs if potentially doublet or triplet (metric: norm shannon Entropy). \n    Args:\n       in_gem (string): input GEM with fragments and GEM ID (ex: 'chr2L:11-33;chr2L:44-55|tmp_gem_id')\n       pseudo_gem_ent (float): mean of normalized Shannon entropies in 1000 pseudoGEM (ex: 0.12)\n       cutoff_ent_filter (int): max_dist/sec_max_dist ratio cutoff threshold (ex: 2)\n    Returns:\n       num_cuts (int): number of cuts made in this filter (ex: 0,1, or 2)\n       sub_gems (list of strings): [sub_gem1, sub_gem2, etc.]\n    \"\"\"\n    gem_id, chrom, frags, span, fraglen, f2fdist, fragnum, frag_str, coord = list(extract_info(in_gem))\n    num_cuts = 0\n    sub_gems = []\n    obs_ent = norm_shannon_ent(f2fdist)\n    if obs_ent < pseudo_gem_ent[str(fragnum)]: # cut once\n        max_dist = max(f2fdist)\n        max_dist_ind = f2fdist.index(max_dist)\n        sec_max_dist = sorted(set(f2fdist))[-2]\n        sec_max_dist_ind = f2fdist.index(sec_max_dist)\n        sub_frags = [frags[:(max_dist_ind+1)], frags[(max_dist_ind+1):]]\n        if max_dist/sec_max_dist < cutoff_ent_filter: # cut twice\n            sorted_ind = sorted([max_dist_ind, sec_max_dist_ind])\n            sub_frags = [frags[:(sorted_ind[0]+1)], frags[(sorted_ind[0]+1):(sorted_ind[1]+1)], frags[(sorted_ind[1]+1):]]\n        num_cuts = len(sub_frags)-1\n        for i in range(len(sub_frags)):\n            sub_gems.append(';'.join([chrom+':'+str(x[0])+'-'+str(x[1]) for x in sub_frags[i]])+'|'+gem_id+'-sub-'+str(len(sub_frags))+'-'+str(i+1))\n    else:\n        sub_gems = [frag_str+'|'+gem_id]\n    return sub_gems, num_cuts\n\ndef write_master_result(out_gem_list, out_name):\n    \"\"\" \n    Write out significance test results.\n    Args: \n       out_gem_list (list): list with 11 items including gem_id, frag_str, p-values, etc.\n       out_name (string): output file name\n    Returns:\n       None\n    \"\"\"\n    with open(out_name, 'a') as file1:\n        for i in range(len(out_gem_list)):\n            file1.write('\\t'.join(map(str, out_gem_list[i])) + '\\n')\n    file1.close()\n\nif __name__ == '__main__':\n    \"\"\" \n    Final results with following columns:\n    1) GEM ID 2) GEM coordinate 3) GEM span 4) fragnum 5) frag coord 6) orig/postEF 7) totdist \n    8) pval1 9) adj.pval1 10) status1 11) pval2 12) adj.pval2 13) status2\n    \"\"\"\n    ### Set parameters ###\n    library_name = argv[1] ## Library name of our data ##\n    genome_name = argv[2] ## Name of the reference genome ##\n    fdr_thresh = float(argv[3])  ## Benjamini-Hochberg FDR; p-value cutoff ##\n    cutoff_ent_filter = int(argv[4]) ## Ratio of largest to second largest F2F cutoff in our entropy filter ##\n    samp_size = int(argv[5]) ## Number of pseudo-GEMs ##\n    prefix = library_name + \"_FDR_\" + str(fdr_thresh) + \"_ratiothresh_\"+ str(cutoff_ent_filter) + \"_pseudoGEM_\"+str(samp_size)\n\n    ### Set directory and input file name ###\n    directory = argv[6]\n    file_name = argv[7]\n    chrom_dir = argv[8]\n    out_directory = directory + library_name + \"_DistTest_FDR_\" + str(fdr_thresh) + '/'\n    if not os.path.exists(out_directory):\n        os.mkdir(out_directory)\n\n    #### Log file ####\n    out = open(out_directory + prefix + \"_distTest_logFile.txt\", \"a\")\n    \n    out.write(\"Software version: v0.2 (2019-10-08, Kim)\" + \"\\n\")\n    out.write(\"Directory: \" + directory + \"\\n\")\n    out.write(\"File name: \" + file_name + \"\\n\")\n    out.write(\"Library name: \" + library_name + \"\\n\")\n    out.write(\"Reference genome: \" + genome_name + \"\\n\")\n    out.write(\"FDR threshold: \" + str(fdr_thresh) + \"\\n\")\n    out.write(\"Ratio threshold in entropy filter: \" + str(cutoff_ent_filter) + \"\\n\")\n    out.write(\"Number of pseudo-GEMs: \" + str(samp_size) + \"\\n\")\n    out.write(\"Started processing domain-based distance test. \\n\")\n    out.write(\"================================= \\n\")\n        \n    ### Read input GEM file ###\n    in_gems = []\n    in_gems = read_gems(directory, file_name)\n    out.write(\"Finished reading the input GEM file. \\n\")\n    out.write(str(len(in_gems)) + \" total GEMs. \\n\")\n    out.write(\"================================= \\n\")\n    \n    ### Read chromosome names and sizes ###\n    chrom_dict = read_chroms(chrom_dir, genome_name)\n\n    header = ['GEM_ID', 'GEM_coord', 'GEM_span', 'Frag_number', 'List_of_frag_coord', 'category', 'dist', 'rawpval1', 'adjpval1', 'decis1', 'rawpval2', 'adjpval2', 'decis2']\n    with open(out_directory+prefix+'_distTest_master.txt', 'a') as file1:\n        file1.write('\\t'.join(map(str, header)) + '\\n')\n    file1.close()\n\n    tot_pass = 0\n    for chr_name in chrom_dict.keys():\n        ### Subset input GEM files by chromosome ###\n        out.write(\"================================= \\n\")\n        out.write(\"===== Chromosome is: \" + chr_name + \". ===== \\n\")\n        out.write(\"================================= \\n\")\n        subset_gems = [x for x in in_gems if chr_name == x[0].split(\":\")[0]]\n        out.write(\"Finished subsetting GEMs. \\n\")\n        out.write(str(len(subset_gems)) + \" GEMs in \" + chr_name + \" (of \" + str(len(in_gems)) + \" total GEMs). \\n\")\n        if len(subset_gems) < 100:\n            out.write(\"Skipped: less than 100 GEMs. \\n\")\n            out.write(\"================================= \\n\")\n            continue\n            \n        ### Initialize output GEM list ###\n        out_gems = [] \n        \n        ### Create distance bucket ###\n        f2f_bucket = []\n        fragnum_bucket = []\n        for i in range(len(subset_gems)):\n            gem_id, chrom, frags, span, fraglen, f2fdist, fragnum, frag_str, coord = extract_info(subset_gems[i])\n            f2f_bucket.extend(f2fdist)\n            fragnum_bucket.append(fragnum)\n        out.write(\"Maximum number of fragments in a GEM: \"+str(max(fragnum_bucket))+\"\\n\")\n        \n        ### Create pseudoGEMS ###i\n        pseudo_file = out_directory + prefix + '_distTest_pseudo_' + chr_name + '.txt'\n        pseudo_gem_tot_dist, pseudo_gem_mean_ent = create_pseudo_gems(f2f_bucket, fragnum_bucket, samp_size, pseudo_file)\n        out.write(\"Finished creating \"+str(samp_size)+\" pseudoGEMs and total distance for each fragment number class. \\n\")\n        del f2f_bucket\n        \n        ### Calculate raw p-values for subset_gems via distance test ###\n        out.write(\"================================= \\n\")\n        out.write(\" 1) Distance test. \\n\")\n        out.write(\"================================= \\n\")\n        for k in range(len(subset_gems)):\n            gem_id, chrom, frags, span, fraglen, f2fdist, fragnum, frag_str, coord = list(extract_info(subset_gems[k]))\n            raw_pval = get_raw_pval(f2fdist, pseudo_gem_tot_dist[str(fragnum)], samp_size)\n            out_gems.append([gem_id, coord, span, fragnum, frag_str, 'Orig', sum(f2fdist), raw_pval])\n        out.write(\"Finished computing raw p-values for \"+str(k+1)+\" GEMs. \\n\")\n        \n        ### Adjust p-values by fragment number classes in each chromosome ###\n        deferred_gems = []\n        for fn in sorted(list(set(fragnum_bucket))):\n            indx = [i for i,val in enumerate(fragnum_bucket) if val==fn]\n            pvals1 = [out_gems[k][7] for k in indx]\n            adj_pval1 = get_adj_pval(pvals1, fdr_thresh, 'fdr_bh')\n            for k in range(len(indx)):\n                out_gems[indx[k]].append(round(adj_pval1[1][k], 4))\n                # Subcategories from first distance test #\n                if adj_pval1[0][k]==True:\n                    if fn < 101: # GEMs with <= 100 fragments pass; 20191008\n                        out_gems[indx[k]].extend(['PASS', '.', '.', '.'])\n                    else: # GEMs with > 100 fragments fail; 20191008\n                        out_gems[indx[k]].extend(['FAIL', '.', '.', '.'])\n                elif adj_pval1[0][k]==False:\n                    if fn==2: # GEMs with 2 fragments fail\n                        out_gems[indx[k]].extend(['FAIL', '.', '.', '.'])\n                    else: # GEMs with > 2 fragments go to entropy filter\n                        out_gems[indx[k]].extend(['DEFER', '.', '.', '.'])\n                        deferred_gems.append(subset_gems[indx[k]])\n        out.write(\"Finished adjusting p-values. \\n\")\n        out.write(\"First test PASS: \"+str(len([x for x in out_gems if x[9] =='PASS']))+\"\\n\")\n        out.write(\"First test FAIL: \"+str(len([x for x in out_gems if x[9] =='FAIL']))+\"\\n\")\n        out.write(\"First test DEFER: \"+str(len([x for x in out_gems if x[9] =='DEFER']))+\"\\n\")\n        pass1 = len([x for x in out_gems if x[9] =='PASS'])\n        \n        del pvals1\n        del adj_pval1\n        \n        ### Entropy Filter for those in 'DEFER' category ###\n        out.write(\"================================= \\n\")\n        out.write(\" 2) Entropy filter. \\n\")\n        out.write(\"================================= \\n\")\n        ef_gems = []\n        num_frag_list = []\n        num_cut_list = []\n        for k in range(len(deferred_gems)):\n            sub_gems, num_cuts = entropy_filter(deferred_gems[k], pseudo_gem_mean_ent, cutoff_ent_filter)\n            num_cut_list.append(num_cuts)\n            for i in range(len(sub_gems)): \n                gem_id, chrom, frags, span, fraglen, f2fdist, fragnum, fragstr, coord = list(extract_info([sub_gems[i]]))\n                num_frag_list.append(fragnum)\n                raw_pval = get_raw_pval(f2fdist, pseudo_gem_tot_dist[str(fragnum)], samp_size)\n                ef_gems.append([gem_id, coord, span, fragnum, fragstr, 'EF-'+str(num_cuts), sum(f2fdist),'.','.', 'DEFER', raw_pval])\n        out.write(\"Finished entropy filter for removing doublets. \\n\")\n        out.write(\"Number of GEMs not split: \"+str(len([x for x in num_cut_list if x == 0]))+\"\\n\")\n        out.write(\"Number of GEMs split once: \"+str(len([x for x in num_cut_list if x == 1]))+\"\\n\")\n        out.write(\"Number of GEMs split twice: \"+str(len([x for x in num_cut_list if x == 2]))+\"\\n\")\n        out.write(\"Number of non-singleton GEMs after cutting: \"+str(len([x for x in num_frag_list if x > 1]))+\"\\n\")\n        out.write(\"Number of singleton GEMs after cutting: \"+str(len([x for x in num_frag_list if x == 1]))+\"\\n\")\n        \n        ### Adjust p-values by fragment number classes in each chromosome ###\n        out.write(\"================================= \\n\")\n        out.write(\" 3) Distance test.  \\n\")\n        out.write(\"================================= \\n\")\n        sub_fragnum_bucket = [x[3] for x in ef_gems]\n        for fn in sorted(list(set(sub_fragnum_bucket))):\n            indx = [i for i,val in enumerate(sub_fragnum_bucket) if val==fn]\n            if fn==1:\n                for k in range(len(indx)):\n                    ef_gems[indx[k]].extend(['.','.'])\n            else:\n                pvals2 = [ef_gems[k][10] for k in indx]\n                adj_pval2 = get_adj_pval(pvals2, fdr_thresh, 'fdr_bh')\n                for k in range(len(indx)):\n                    ef_gems[indx[k]].append(round(adj_pval2[1][k], 4))\n                    if adj_pval2[0][k]==True:\n                        ef_gems[indx[k]].append('PASS')\n                    elif adj_pval2[0][k]==False:\n                        ef_gems[indx[k]].append('FAIL')\n        out.write(\"Finished adjusting p-values. \\n\")\n        out.write(\"Second test PASS: \"+str(len([x for x in ef_gems if x[12] =='PASS']))+\"\\n\")\n        out.write(\"Second test FAIL: \"+str(len([x for x in ef_gems if x[12] =='FAIL']))+\"\\n\")\n        pass2 = len([x for x in ef_gems if x[12] =='PASS'])\n        out.write(\"================================= \\n\")\n        \n        del pvals2\n        del adj_pval2\n        \n        ### Write results ###\n        write_master_result(out_gems, out_directory+prefix+'_distTest_master.txt')\n        write_master_result(ef_gems, out_directory+prefix+'_distTest_master.txt')\n        out.write(\"Finished writing files. \\n\")\n        \n        tot_pass += pass1+pass2\n        \n        out.write(\"Total \" +  str(pass1+pass2) + \" GEMs out of \" + str(len(subset_gems))+ \" GEMs passed. \\n\")\n        out.write(\"i.e., \" + str(round((pass1+pass2)*100/len(subset_gems), 3)) + \"% passed in \" +chr_name+ \". \\n\")\n        out.write(\"================================= \\n\")\n        del out_gems\n        del ef_gems\n        del deferred_gems\n    out.write(\"================================= \\n\")\n    out.write(\"======= Summary Statistics ======= \\n\")\n    out.write(\"Total \" +  str(tot_pass) + \" GEMs out of \" + str(len(in_gems))+ \" GEMs passed. \\n\")\n    out.write(\"i.e., \" + str(round((tot_pass)*100/len(in_gems), 3)) + \"% passed. \\n\")\n    out.write(\"================================= \\n\")\n    out.write(\"DONE. \\n\")\n    \n    out.close()\n", "meta": {"hexsha": "cfc5a570b7c16095f90e70c03bd45cc8fb855342", "size": 19537, "ext": "py", "lang": "Python", "max_stars_repo_path": "bin/domain_dist_sigtest.py", "max_stars_repo_name": "TheJacksonLaboratory/mia-sig", "max_stars_repo_head_hexsha": "a9a3b920c240c95cb589e77ae7e094036e6a0939", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-06-19T17:39:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-20T06:04:38.000Z", "max_issues_repo_path": "bin/domain_dist_sigtest.py", "max_issues_repo_name": "TheJacksonLaboratory/mia-sig", "max_issues_repo_head_hexsha": "a9a3b920c240c95cb589e77ae7e094036e6a0939", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-12-16T13:54:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T16:45:57.000Z", "max_forks_repo_path": "bin/domain_dist_sigtest.py", "max_forks_repo_name": "TheJacksonLaboratory/mia-sig", "max_forks_repo_head_hexsha": "a9a3b920c240c95cb589e77ae7e094036e6a0939", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-27T09:56:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-27T09:56:53.000Z", "avg_line_length": 48.0024570025, "max_line_length": 173, "alphanum_fraction": 0.5802835645, "include": true, "reason": "import numpy,import statsmodels,from statsmodels", "num_tokens": 5350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3812195803163617, "lm_q1q2_score": 0.19953808575054907}}
{"text": "'''\n@Author: ConghaoWong\n@Date: 2019-12-20 09:39:34\nLastEditors: Conghao Wong\nLastEditTime: 2020-09-16 16:27:24\n@Description: classes and methods of training model\n'''\nimport os\nimport random\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tqdm import tqdm\n\nfrom GridRefine import SocialRefine_one\nfrom helpmethods import calculate_ADE_FDE_numpy, dir_check, list2array\nfrom sceneFeature import TrajectoryMapManager\nfrom visual import TrajVisual\n\n\nclass Base_Model():\n    \"\"\"\n    Base model for prediction.\n\n    Following items should be given when using this model:\n    ```\n    self.create_model(self), # create prediction model\n    self.loss(self, model_output, gt, obs='null'),  # loss function when training model\n    self.loss_eval(self, model_output, gt, obs='null'), # loss function when test model\n    self.forward_train(self, mode_inputs), # model result in training steps\n    self.forward_test(self, test_tensor:list). # model result in test steps\n    ```\n    \"\"\"\n    def __init__(self, train_info, args):\n        self.args = args\n        self.train_info = train_info\n        \n    def run_commands(self):\n        self.get_data()     # 获取与训练数据有关的信息\n\n        if self.args.load == 'null':\n            self.model, self.optimizer = self.create_model()\n            self.model.summary()\n            self.train()\n        else:\n            self.model, self.agents_test = self.load_from_checkpoint()\n            self.model.summary()\n        \n            if self.args.test:\n                self.test_batch(\n                    self.agents_test, \n                    test_on_neighbors=False,\n                    batch_size=0.2,         # set 0.5 on toy exp\n                    social_refine=self.args.sr_enable,\n                    draw_results=self.args.draw_results,\n                    save_agents=False,\n                )\n\n    def get_data(self):\n        self.obs_frames = self.args.obs_frames\n        self.pred_frames = self.args.pred_frames\n        self.total_frames = self.obs_frames + self.pred_frames\n        self.log_dir = dir_check(self.args.log_dir)\n\n        if not self.args.load == 'null':\n            return\n\n        self.agents_train = self.train_info['train_data']\n        self.agents_test = self.train_info['test_data']\n        self.train_number = self.train_info['train_number']\n        self.sample_time = self.train_info['sample_time'] \n    \n    def load_from_checkpoint(self):\n        base_path = self.args.load + '{}'\n        if self.args.save_best:\n            best_epoch = np.loadtxt(os.path.join(self.args.log_dir, 'best_ade_epoch.txt'))[1].astype(int)\n            model = keras.models.load_model(base_path.format('_epoch{}.h5'.format(best_epoch)))\n        else:\n            model = keras.models.load_model(base_path.format('.h5'))\n\n        agents_test = np.load(base_path.format('test.npy'), allow_pickle=True)\n        return model, agents_test\n    \n    def create_model(self):\n        raise 'MODEL is not defined!'\n        return model, optimizer\n\n    def loss(self, model_output, gt, obs='null'):\n        \"\"\"\n        Train loss, using ADE by default\n        \"\"\"\n        self.loss_namelist = ['ADE_t']\n        loss_ADE = calculate_ADE(model_output[0], gt)\n        loss_list = tf.stack([loss_ADE])\n        return loss_ADE, loss_list\n\n    def loss_eval(self, model_output, gt, obs='null'):\n        \"\"\"\n        Eval metrics, using ADE and FDE by default.\n        return: `np.array`\n        \"\"\"\n        self.loss_eval_namelist = ['ADE', 'FDE']\n        return calculate_ADE(model_output[0], gt).numpy(), calculate_FDE(model_output[0], gt).numpy()\n\n    def prepare_model_inputs_all(self, input_agents):\n        model_inputs = []\n        gt = []\n        agent_index = []\n        for agent_index_current, agent in enumerate(tqdm(input_agents, desc='Prepare inputs...')):\n            model_inputs.append(agent.get_train_traj())\n            gt.append(agent.get_gt_traj())\n            agent_index.append(agent_index_current)\n\n        model_inputs = tf.cast(tf.stack(model_inputs), tf.float32)\n        gt = tf.cast(tf.stack(gt), tf.float32)\n        return [model_inputs, gt], agent_index\n\n    def prepare_model_inputs_batch(self, train_tensor=0, batch_size=0, init=False):\n        \"\"\"\n        Get batch data from all data\n        \"\"\"\n        if init:\n            self.batch_start = 0\n            self.train_length = len(train_tensor[1])\n            return self.train_length\n        \n        start = self.batch_start\n        end = (self.batch_start + batch_size) % self.train_length\n        # 每次最多取 1 epoch\n        if end < start:\n            if type(train_tensor[0]) == list:\n                train_inputs = [\n                    tf.concat([\n                        train_input[start:],\n                        train_input[:end],\n                    ], axis=0) for train_input in train_tensor[0]\n                ]\n            else:\n                train_inputs = tf.concat([\n                    train_tensor[0][start:],\n                    train_tensor[0][:end],\n                ], axis=0)\n                \n            gt = tf.concat([\n                train_tensor[1][start:],\n                train_tensor[1][:end],\n            ], axis=0)\n\n        elif start + batch_size < self.train_length:\n            if type(train_tensor[0]) == list:\n                train_inputs = [train_input[start:end] for train_input in train_tensor[0]]\n            else:\n                train_inputs = train_tensor[0][start:end]\n            gt = train_tensor[1][start:end]\n\n        else:\n            train_inputs = train_tensor[0]\n            gt = train_tensor[1]\n\n        self.batch_start = end\n        return train_inputs, gt, len(gt)\n\n    def forward_train(self, model_inputs):\n        \"\"\"\n        Run a training implement\n        \"\"\"\n        output = self.model(model_inputs)\n        if not type(output) == list:\n            output = [output]\n        return output\n\n    def forward_test(self, test_tensor:list):\n        \"\"\"\n        Run test once.\n        `test_tensor` is a `list`. `test_tensor[0]` is the inputs of model and `test_tensor[1]` are their grount truths.\n        \"\"\"\n        model_inputs = test_tensor[0]\n        gt = test_tensor[1]\n        output = self.model(model_inputs)\n        if not type(output) == list:\n            output = [output]\n        return output, gt, model_inputs\n\n    def test_during_training(self, test_tensor, input_agents, test_index):\n        \"\"\"\n        Run test during training.\n        Results will NOT be written to inputs.\n        \"\"\"\n        model_output, gt, obs = self.forward_test(test_tensor)\n        loss_eval = self.loss_eval(model_output, gt, obs=obs)\n        return model_output, loss_eval, gt, input_agents\n    \n    def train(self):\n        \"\"\"\n        Train the built model `self.model`\n        \"\"\"\n        batch_number = int(np.ceil(self.train_number / self.args.batch_size))\n        summary_writer = tf.summary.create_file_writer(self.args.log_dir)\n\n        print('\\n-----------------dataset options-----------------')\n        if self.args.train_percent[0] and self.args.train_type == 'all':\n            print('Sampling data from training sets. ({}x)'.format(self.args.train_percent))\n        if self.args.reverse:\n            print('Using reverse data to train. (2x)')\n        if self.args.add_noise:\n            print('Using noise data to train. ({}x)'.format(self.args.add_noise))\n        if self.args.rotate:\n            print('Using rotate data to train. ({}x)'.format(self.args.rotate))\n        print('train_number = {}, total {}x train samples.'.format(self.train_number, self.sample_time))\n\n        print('-----------------training options-----------------')\n        print('model_name = {}, \\ndataset = {},\\nbatch_number = {},\\nbatch_size = {},\\nlr={}'.format(\n            self.args.model_name,\n            self.args.test_set, \n            batch_number, \n            self.args.batch_size,\n            self.args.lr,\n        ))\n\n        print('\\nPrepare training data...')\n        self.train_tensor, self.train_index = self.prepare_model_inputs_all(self.agents_train)\n        self.test_tensor, self.test_index = self.prepare_model_inputs_all(self.agents_test)\n        train_length = self.prepare_model_inputs_batch(self.train_tensor, init=True)\n\n        if self.args.save_model:\n            self.test_data_save_path = os.path.join(self.args.log_dir, '{}.npy'.format(self.args.model_name + '{}'))\n            np.save(self.test_data_save_path.format('test'), self.agents_test)   \n            np.save(self.test_data_save_path.format('args'), self.args)\n            \n        test_results = []\n        test_loss_dict = dict()\n        test_loss_dict['-'] = 0\n\n        batch_number = 1 + (train_length * self.args.epochs)// self.args.batch_size\n        print(batch_number, train_length, self.args.epochs, self.args.batch_size)\n        \n        time_bar = tqdm(range(batch_number), desc='Training...')\n        best_ade = 100.0\n        best_epoch = 0\n        for batch in time_bar:\n            ADE = 0\n            ADE_move_average = tf.cast(0.0, dtype=tf.float32)    # 计算移动平均\n            loss_list = []\n            \n            obs_current, gt_current, train_sample_number = self.prepare_model_inputs_batch(self.train_tensor, self.args.batch_size)\n\n            if train_sample_number < 20:\n                continue\n\n            with tf.GradientTape() as tape:\n                model_output_current = self.forward_train(obs_current)\n                loss_ADE, loss_list_current = self.loss(model_output_current, gt_current, obs=obs_current)\n                ADE_move_average = 0.7 * loss_ADE + 0.3 * ADE_move_average\n\n            ADE += loss_ADE\n            grads = tape.gradient(ADE_move_average, self.model.trainable_variables)\n            self.optimizer.apply_gradients(zip(grads, self.model.trainable_variables))\n\n            loss_list.append(loss_list_current)\n            loss_list = tf.reduce_mean(tf.stack(loss_list), axis=0).numpy()\n\n            epoch = (batch * self.args.batch_size) // train_length\n\n            if (epoch >= self.args.start_test_percent * self.args.epochs) and (epoch % self.args.test_step == 0):\n                model_output, loss_eval, _, _ = self.test_during_training(self.test_tensor, self.agents_test, self.test_index)\n                test_results.append(loss_eval)\n                test_loss_dict = create_loss_dict(loss_eval, self.loss_eval_namelist)\n                ade_current = loss_eval[0]\n                if ade_current <= best_ade:\n                    best_ade = ade_current\n                    best_epoch = epoch\n                    \n                    if self.args.save_best:\n                        self.model.save(os.path.join(self.args.log_dir, '{}_epoch{}.h5'.format(self.args.model_name, epoch)))\n                        np.savetxt(os.path.join(self.args.log_dir, 'best_ade_epoch.txt'), np.array([best_ade, best_epoch]))\n\n            \n            if epoch % 2 == 0:\n                train_loss_dict = create_loss_dict(loss_list, self.loss_namelist)\n                loss_dict = dict(train_loss_dict, **test_loss_dict) # 拼接字典\n                time_bar.set_postfix(loss_dict)\n                \n            with summary_writer.as_default():\n                for loss_name in loss_dict:\n                    value = loss_dict[loss_name]\n                    tf.summary.scalar(loss_name, value, step=epoch)\n\n        print('Training done.')\n        print('Tensorboard training log file is saved at \"{}\"'.format(self.args.log_dir))\n        print('To open this log file, please use \"tensorboard --logdir {} --port 54393\"'.format(self.args.log_dir))\n        \n        latest_epochs = 10\n        test_results = list2array(test_results)\n        latest_results = np.mean(test_results[-latest_epochs-1:-1, :], axis=0)\n        print('In latest {} test epochs, average test loss = {}'.format(\n            latest_epochs,\n            latest_results\n        ))\n        np.savetxt(os.path.join(self.args.log_dir, 'train_log.txt'), list2array(test_results))\n\n        if self.args.save_model:\n            self.model_save_path = os.path.join(self.args.log_dir, '{}.h5'.format(self.args.model_name))\n            self.model.save(self.model_save_path)\n            \n            print('Trained model is saved at \"{}\".'.format(self.model_save_path.split('.h5')[0]))\n            print('To re-test this model, please use \"python main.py --load {}\".'.format(self.model_save_path.split('.h5')[0]))\n            \n            model_name = self.model_save_path.split('.h5')[0].split('/')[-1]\n            np.savetxt('./results/result-{}{}.txt'.format(model_name, self.args.test_set), latest_results)\n            with open('./results/path-{}{}.txt'.format(model_name, self.args.test_set), 'w+') as f:\n                f.write(self.model_save_path.split('.h5')[0])\n\n    def test_batch(self, agents_test, test_on_neighbors=False, draw_results=True, batch_size=0.2, save_agents=False, social_refine=False):\n        \"\"\"\n        Eval model on test sets.\n        Results WILL be written to inputs.\n        测试可以分段进行，并使用`batch_size`以百分比形式调节时间段长短;\n        `test_on_neighbors`将会被自动打开当`social_refine == True`\n        \"\"\"\n        print('-----------------Test options-----------------')\n        print('model_name = {},\\ndataset = {},\\ntest_length= {} * length of test video.\\n'.format(\n            self.args.model_name,\n            self.args.test_set, \n            batch_size,\n        ))\n        \n        start_frame = agents_test[0].obs_frame\n        end_frame = agents_test[-1].obs_frame\n        frame_length = end_frame - start_frame\n        \n        # sort by obs time\n        agents_batch = dict()\n        for agent in agents_test:\n            batch_index = min(int((agent.obs_frame - start_frame)/(batch_size * frame_length)), int(1/batch_size)-1)\n            if not batch_index in agents_batch:\n                agents_batch[batch_index] = []\n            else:\n                agents_batch[batch_index].append(agent)\n        \n        if social_refine:\n            test_on_neighbors = True\n\n        agents_batch, test_index = self.prepare_test_agents_batch(agents_batch, test_on_neighbors)\n        \n        # run test\n        all_loss = []\n        all_loss_batch = []\n        for batch_index in agents_batch:\n            batch_loss = []\n            [test_tensor, _], _ = self.prepare_model_inputs_all(agents_batch[batch_index], calculate_neighbor=test_on_neighbors)\n            pred = self.forward_train(test_tensor)\n            pred = pred[0].numpy()\n\n            for agent_index, index in enumerate(test_index[batch_index]):\n                current_pred = pred[index]\n                agents_batch[batch_index][agent_index].write_pred(current_pred[0])\n                if test_on_neighbors:\n                    agents_batch[batch_index][agent_index].write_pred_neighbor(current_pred[1:])\n                \n                if social_refine:\n                    agents_batch[batch_index][agent_index].write_pred_sr(SocialRefine_one(\n                        agent=agents_batch[batch_index][agent_index],\n                        args=self.args,\n                        epochs=10,\n                        save=False,\n                    ))\n                \n                loss = agents_batch[batch_index][agent_index].calculate_loss(SR=social_refine)\n                all_loss.append(loss)\n                batch_loss.append(loss)\n            \n            all_loss_batch.append(np.mean(np.stack(batch_loss), axis=0))\n        \n        average_loss = np.mean(np.stack(all_loss), axis=0)\n        print('test_loss={}\\nTest done.'.format(create_loss_dict(average_loss, ['ADE', 'FDE'])))\n        # print(all_loss_batch)\n\n        if draw_results:\n            result_agents = []\n            for batch_index in agents_batch:\n                result_agents += agents_batch[batch_index]\n\n            # draw results only\n            for index in range(len(result_agents)):\n                result_agents[index].draw_results(self.log_dir, '{}.png'.format(index), draw_neighbors=False)\n            \n            # draw results on video frames\n            # tv = TrajVisual(save_base_path=self.args.log_dir, verbose=True, draw_neighbors=False, social_refine=social_refine)\n            # tv.visual(result_agents, dataset=self.args.test_set)\n\n        if save_agents:\n            result_agents = []\n            for batch_index in agents_batch:\n                result_agents += agents_batch[batch_index]\n            np.save(os.path.join(self.log_dir, 'pred.npy'), result_agents)\n            return result_agents\n    \n    def test(self, agents_test, test_on_neighbors=False, social_refine=True, draw_results=True, batch_size=0.2, save_agents=False):\n        \"\"\"\n        Eval model on test sets.\n        Results WILL be written to inputs.\n        \"\"\"\n        all_loss = []\n        loss_name_list = ['ADE', 'FDE']\n        loss_function = calculate_ADE_FDE_numpy\n\n        self.test_tensor, self.test_index = self.prepare_model_inputs_all(self.agents_test)\n        pred = self.forward_train(self.test_tensor)\n\n        for index in tqdm(range(len(agents_test)), desc='Testing...'):\n            obs = agents_test[index].get_train_traj().reshape([1, agents_test[index].obs_length, 2])\n            \n            # if test_on_neighbors and agents_test[index].neighbor_number > 0:\n            #     obs_neighbor = (np.stack(agents_test[index].get_neighbor_traj())).reshape([agents_test[index].neighbor_number, agents_test[index].obs_length, 2])\n            #     obs = np.concatenate([obs, obs_neighbor], axis=0)\n\n            \n            agents_test[index].write_pred(pred[0].numpy()[index])\n            # if test_on_neighbors:\n            #     agents_test[index].write_pred_neighbor(pred[1:].numpy()[index])\n\n            # if social_refine:\n            #     agents_test[index].write_pred_sr(SocialRefine_one(agents_test[index], self.args_old))\n            \n            if draw_results:\n                agents_test[index].draw_results(self.log_dir, '{}.png'.format(index), draw_neighbors=False # test_on_neighbors\n                )\n\n            all_loss.append(agents_test[index].calculate_loss())\n            \n        \n        loss = np.mean(np.stack(all_loss), axis=0)\n            \n        print('test_loss={}'.format(create_loss_dict(loss, loss_name_list)))\n        # for l in loss:\n        #     print(loss, end='\\t')\n        print('\\nTest done.')\n\n        if save_agents:\n            np.save(os.path.join(self.log_dir, 'pred.npy'), agents_test)\n        return agents_test\n    \n    def prepare_test_agents_batch(self, agents_batch:dict, test_on_neighbors=False):\n        \"\"\"\n        Prepare test agents and save test order. (When test on neighbors of current agent)\n        returns: Test agents (in batch order) `agents_batch` and their order `test_index`.\n        \"\"\"\n        # save test order\n        test_index = dict()\n        for batch_index in agents_batch:\n            total_count = 0\n            if not batch_index in test_index:\n                test_index[batch_index] = []\n\n            for agent_index, _ in enumerate(agents_batch[batch_index]):\n                start_count = total_count\n                total_count += 1\n                if test_on_neighbors:\n                    nei_len = agents_batch[batch_index][agent_index].neighbor_number\n                    total_count += nei_len\n                test_index[batch_index].append([i for i in range(start_count, total_count)])\n        \n        return agents_batch, test_index\n\n\nclass BGM(Base_Model):\n    \"\"\"\n    `B`uilding a Dynamic `G`uidance `M`ap for Trajectory Prediction\n    \"\"\"\n    def __init__(self, train_info, args):\n        super().__init__(train_info, args)\n        self.given_maps_when_test=False\n\n    def create_model(self):\n        positions = keras.layers.Input(shape=[self.obs_frames, 2])\n        traj_maps = keras.layers.Input(shape=[self.args.gridmapsize, self.args.gridmapsize])\n        start_point = tf.reshape(positions[:, -1, :], [-1, 1, 2])\n        \n        # sequence feature\n        positions_n = positions - start_point\n        positions_embadding_lstm = keras.layers.Dense(64)(positions_n)\n        traj_feature = keras.layers.LSTM(64, return_sequences=True)(positions_embadding_lstm)\n        feature_flatten = tf.reshape(traj_feature, [-1, self.obs_frames * 64])\n        sequence_feature = keras.layers.Dense(self.obs_frames * 32, activation=tf.nn.tanh)(feature_flatten)\n        \n        # context feature\n        traj_maps_r = tf.reshape(traj_maps, [-1, self.args.gridmapsize, self.args.gridmapsize, 1])\n        average_pooling = keras.layers.AveragePooling2D([2, 2], padding='same')(traj_maps_r)\n        cnn1 = keras.layers.Conv2D(32, [8, 8], activation=tf.nn.relu)(average_pooling)\n        cnn2 = keras.layers.Conv2D(32, [5, 5], activation=tf.nn.relu)(cnn1)\n        pooling2 = keras.layers.AveragePooling2D([2, 2])(cnn2)\n        flatten = keras.layers.Flatten()(pooling2)\n        context_feature = keras.layers.Dense(self.obs_frames * 32, activation=tf.nn.tanh)(flatten)\n        \n        # joint feature\n        concat_feature = tf.concat([sequence_feature, context_feature], axis=-1)\n        feature_fc = keras.layers.Dense(self.pred_frames * 64)(concat_feature)\n        feature_reshape = tf.reshape(feature_fc, [-1, self.pred_frames, 64])\n        output5 = keras.layers.Dense(2)(feature_reshape)\n        output5 = output5 + start_point\n        \n        lstm = keras.Model(inputs=[positions, traj_maps], outputs=[output5])\n        lstm.build(input_shape=[None, self.obs_frames, 2])\n        lstm_optimizer = keras.optimizers.Adam(lr=self.args.lr)\n        \n        return lstm, lstm_optimizer\n\n    def get_feature(self, inputs, layer_name):\n        submodel = keras.Model(inputs=self.model.input, outputs=self.model.get_layer(layer_name).output)\n        return submodel(inputs)\n\n    def prepare_model_inputs_all(self, input_agents, calculate_neighbor=False):\n        input_trajs = []\n        input_maps = []\n        gt = []\n        agent_index = []\n        for agent_index_current, agent in enumerate(tqdm(input_agents, desc='Prepare inputs...')):\n            input_trajs.append(agent.get_train_traj())\n            input_maps.append(agent.get_traj_map())\n            gt.append(agent.get_gt_traj())\n            agent_index.append(agent_index_current)\n\n            if calculate_neighbor and agent.neighbor_number:\n                for traj, traj_map in zip(agent.get_neighbor_traj(), agent.get_traj_map_for_neighbors()):\n                    input_trajs.append(traj)\n                    input_maps.append(agent.get_traj_map())\n                    # No GT\n\n        input_trajs = tf.cast(tf.stack(input_trajs), tf.float32)\n        input_maps = tf.cast(tf.stack(input_maps), tf.float32)\n        gt = tf.cast(tf.stack(gt), tf.float32)\n        return [[input_trajs, input_maps], gt], agent_index\n\n    def prepare_test_agents_batch(self, agents_batch:dict, test_on_neighbors=False):\n        # create trajectory map for each batch\n        if not type(self.given_maps_when_test) == np.ndarray:\n            traj_maps = [TrajectoryMapManager(agents_batch[batch_index]) for batch_index in agents_batch]\n        else:\n            traj_maps = self.given_maps_when_test\n            print('Using given maps')\n\n        # write traj map and save batch order     \n        test_index = dict()\n        for batch_index, traj_map in zip(agents_batch, traj_maps):\n            total_count = 0\n            if not batch_index in test_index:\n                test_index[batch_index] = []\n                \n            for agent_index, _ in enumerate(agents_batch[batch_index]):\n                agents_batch[batch_index][agent_index].write_traj_map(traj_map)\n                start_count = total_count\n                total_count += 1\n                if test_on_neighbors:\n                    agents_batch[batch_index][agent_index].write_traj_map_for_neighbors(traj_map)\n                    nei_len = agents_batch[batch_index][agent_index].neighbor_number\n                    total_count += nei_len\n                test_index[batch_index].append([i for i in range(start_count, total_count)])\n\n        return agents_batch, test_index\n\n\nclass Linear(Base_Model):\n    def __init__(self, train_info, args):\n        super().__init__(train_info, args)\n        self.args.batch_size = 1\n        self.args.epochs = 1\n        self.args.draw_results = False\n        self.args.train_percent = 0.0\n    \n    def run_commands(self):\n        self.get_data()\n        self.model, self.optimizer = self.create_model()\n        self.test_batch(\n            self.agents_test,\n            batch_size=1.0,\n            test_on_neighbors=False,\n            social_refine=False,\n            draw_results=self.args.draw_results,\n            save_agents=False\n        )\n\n    def predict_linear(self, x, y, x_p, diff_weights=0):\n        if diff_weights == 0:\n            P = np.diag(np.ones(shape=[x.shape[0]]))\n        else:\n            P = np.diag(softmax([(i+1)**diff_weights for i in range(x.shape[0])]))\n\n        A = tf.transpose(tf.stack([np.ones_like(x), x]))\n        A_p = tf.transpose(tf.stack([np.ones_like(x_p), x_p]))\n        Y = tf.transpose(y)\n\n        P = tf.cast(P, tf.float32)\n        A = tf.cast(A, tf.float32)\n        A_p = tf.cast(A_p, tf.float32)\n        Y = tf.reshape(tf.cast(Y, tf.float32), [-1, 1])\n        \n        B = tf.matmul(tf.matmul(tf.matmul(tf.linalg.inv(tf.matmul(tf.matmul(tf.transpose(A), P), A)), tf.transpose(A)), P), Y)\n        Y_p = np.matmul(A_p, B)\n        return Y_p, B\n\n    def predict_linear_for_person(self, positions, diff_weights):\n        t = np.array([t for t in range(self.obs_frames)])\n        t_p = np.array([t + self.obs_frames for t in range(self.pred_frames)])\n        x = tf.transpose(positions)[0]\n        y = tf.transpose(positions)[1]\n\n        x_p, _ = self.predict_linear(t, x, t_p, diff_weights=diff_weights)\n        y_p, _ = self.predict_linear(t, y, t_p, diff_weights=diff_weights)\n\n        return tf.transpose(tf.reshape(tf.stack([x_p, y_p]), [2, self.pred_frames]))\n    \n    def create_model(self):\n        return self.predict_linear_for_person, 0\n\n    def forward_train(self, train_tensor, index):\n        input_trajs = train_tensor[0][index[0]:index[1]]\n        gt = train_tensor[1][index[0]:index[1]]\n\n        results = []\n        for inputs_current in input_trajs:\n            results.append(self.model(inputs_current, diff_weights=self.args.diff_weights))\n        \n        return [tf.stack(results)], gt, input_trajs\n\n    def forward_test(self, test_tensor):\n        input_trajs = test_tensor[0]\n        gt = test_tensor[1]\n        \n        results = []\n        for inputs_current in input_trajs:\n            results.append(self.model(inputs_current, diff_weights=self.args.diff_weights))     \n        \n        return output, gt, input_trajs\n\n\n\"\"\"\nhelpmethods\n\"\"\"\n\ndef create_loss_dict(loss, name_list):\n    return dict(zip(name_list, loss))\n\n\ndef softmax(x):\n    return np.exp(x)/np.sum(np.exp(x),axis=0)\n\n\ndef calculate_ADE(pred, GT):\n    \"\"\"input_shape = [batch, pred_frames, 2]\"\"\"\n    pred = tf.cast(pred, tf.float32)\n    GT = tf.cast(GT, tf.float32)\n    return tf.reduce_mean(tf.linalg.norm(pred - GT, ord=2, axis=2))\n    \n\ndef calculate_FDE(pred, GT):\n    pred = tf.cast(pred, tf.float32)\n    GT = tf.cast(GT, tf.float32)\n    return tf.reduce_mean(tf.linalg.norm(pred[:, -1, :] - GT[:, -1, :], ord=2, axis=1))\n", "meta": {"hexsha": "856170da65a1b3e71e3a0de6cfa95ab68384c583", "size": 27276, "ext": "py", "lang": "Python", "max_stars_repo_path": "models.py", "max_stars_repo_name": "conghaowoooong/Project-Erina", "max_stars_repo_head_hexsha": "e4e645a348d5df6d571d5334a0e2d5ecba8466bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models.py", "max_issues_repo_name": "conghaowoooong/Project-Erina", "max_issues_repo_head_hexsha": "e4e645a348d5df6d571d5334a0e2d5ecba8466bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models.py", "max_forks_repo_name": "conghaowoooong/Project-Erina", "max_forks_repo_head_hexsha": "e4e645a348d5df6d571d5334a0e2d5ecba8466bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2647503782, "max_line_length": 163, "alphanum_fraction": 0.6036442294, "include": true, "reason": "import numpy", "num_tokens": 6053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.3812195803163617, "lm_q1q2_score": 0.19953808575054902}}
{"text": "import os\nimport pickle\n\nimport numpy as np\n\nfrom astropy.io import fits\nfrom astropy.table import Table\nfrom astropy.wcs import WCS\n\nfrom .config_file import get_values_from_config_file\nfrom .gausspy_py3.gp_plus import get_fully_blended_gaussians\nfrom .utils.fit_quality_checks import negative_residuals\nfrom .utils.gaussian_functions import gaussian, combined_gaussian, area_of_gaussian\nfrom .utils.output import say\nfrom .utils.spectral_cube_functions import correct_header, change_header, update_header, save_fits, return_hdu_options\nfrom .spatial_fitting import SpatialFitting\n\n\nclass Finalize(object):\n    def __init__(self, path_to_pickle_file=None,\n                 path_to_decomp_file=None, fin_filename=None,\n                 config_file=''):\n        \"\"\"Class containing methods to finalize the GaussPy+ results.\n\n        Parameters\n        ----------\n        path_to_pickle_file : type\n            Description of parameter `path_to_pickle_file`.\n        path_to_decomp_file : type\n            Description of parameter `path_to_decomp_file`.\n        fin_filename : type\n            Description of parameter `fin_filename`.\n        config_file : type\n            Description of parameter `config_file`.\n\n        \"\"\"\n        self.path_to_pickle_file = path_to_pickle_file\n        self.path_to_decomp_file = path_to_decomp_file\n        self.dirpath_gpy = None\n        self.dirpath_table = None\n        self.fin_filename = fin_filename\n\n        self.dct_params = None\n        self.config_file = config_file\n        self.ncomps_max = None\n\n        self.subcube_nr = None\n        self.xpos_offset = 0\n        self.ypos_offset = 0\n\n        self.main_beam_efficiency = None\n\n        self.initialized_state = False\n\n        if config_file:\n            get_values_from_config_file(\n                self, config_file, config_key='DEFAULT')\n\n    def check_settings(self):\n        \"\"\"Check user settings and raise error messages or apply corrections.\"\"\"\n        if self.path_to_pickle_file is None:\n            raise Exception(\"Need to specify 'path_to_pickle_file'\")\n        if self.path_to_decomp_file is None:\n            raise Exception(\"Need to specify 'path_to_decomp_file'\")\n        self.decomp_dirname = os.path.dirname(self.path_to_decomp_file)\n        self.file = os.path.basename(self.path_to_decomp_file)\n        self.filename, self.file_extension = os.path.splitext(self.file)\n\n        if self.fin_filename is None:\n            suffix = '_finalized'\n            self.fin_filename = self.filename + suffix\n\n        if self.dirpath_gpy is None:\n            self.dirpath_gpy = os.path.dirname(self.decomp_dirname)\n\n        if self.dirpath_table is None:\n            self.dirpath_table = self.decomp_dirname\n\n    def initialize(self):\n        \"\"\"Read in data files and initialize parameters.\"\"\"\n        with open(self.path_to_pickle_file, \"rb\") as pickle_file:\n            self.pickled_data = pickle.load(pickle_file, encoding='latin1')\n\n        with open(self.path_to_decomp_file, \"rb\") as pickle_file:\n            self.decomposition = pickle.load(pickle_file, encoding='latin1')\n\n        self.length = len(self.pickled_data['index'])\n\n        if 'header' in self.pickled_data.keys():\n            self.header = correct_header(self.pickled_data['header'])\n            self.wcs = WCS(self.header)\n            self.velocity_increment = (\n                self.wcs.wcs.cdelt[2] * self.wcs.wcs.cunit[2]).to(\n                    self.vel_unit).value\n            self.to_unit = (self.wcs.wcs.cunit[2]).to(self.vel_unit)\n        if 'location' in self.pickled_data.keys():\n            self.location = self.pickled_data['location']\n        if 'nan_mask' in self.pickled_data.keys():\n            self.nan_mask = self.pickled_data['nan_mask']\n\n        self.channels = self.pickled_data['x_values']\n\n        self.initialized_state = True\n\n    def finalize_dct(self):\n        self.check_settings()\n        self.initialize()\n        sp = SpatialFitting(config_file=self.config_file)\n        if self.dct_params is not None:\n            for key, value in self.dct_params.items():\n                try:\n                    setattr(sp, key, value)\n                except ValueError:\n                    raise Exception('Could not parse parameter {} from dct_params'.format(key))\n\n        sp.log_output = False\n        sp.path_to_pickle_file = self.path_to_pickle_file\n        sp.path_to_decomp_file = self.path_to_decomp_file\n\n        results_list = sp.finalize()\n\n        list_means_interval, list_n_centroids = (\n            [{} for _ in range(self.length)] for _ in range(2))\n\n        for i, item in enumerate(results_list):\n            if not isinstance(item, list):\n                say(\"Error for index {}: {}\".format(i, item))\n                continue\n\n            index, means_interval, n_centroids = item\n            list_means_interval[index] = means_interval\n            list_n_centroids[index] = n_centroids\n\n        self.decomposition['broad'] = sp.mask_broad_flagged\n        self.decomposition['ncomps_wmedian'] = sp.ncomps_wmedian.astype('int')\n        self.decomposition['ncomps_jumps'] = sp.ncomps_jumps.astype('int')\n        self.decomposition['means_interval'] = list_means_interval\n        self.decomposition['n_centroids'] = list_n_centroids\n\n    def get_flag_blended(self, amps, fwhms, means):\n        params_fit = amps + fwhms + means\n        indices = get_fully_blended_gaussians(params_fit)\n        flags = np.zeros(len(amps))\n        flags[indices] = 1\n        return flags.astype('int')\n\n    def get_flag_broad(self, fwhms, broad):\n        flags = np.zeros(len(fwhms))\n        if broad:\n            flags[np.argmax(fwhms)] = 1\n        return flags.astype('int')\n\n    def get_flag_centroid(self, means, means_interval, n_centroids):\n        flag = 0\n        for key in means_interval.keys():\n            n_wanted = n_centroids[key]\n            lower = means_interval[key][0]\n            upper = means_interval[key][1]\n            n_real = np.count_nonzero(\n                np.logical_and(lower <= means, means <= upper))\n\n            flag += abs(n_wanted - n_real)\n\n        return flag\n\n    def get_table_rows(self, idx, j):\n        rows = []\n        ncomps = self.decomposition['N_components'][idx]\n\n        #  do not continue if spectrum was masked out, was not fitted,\n        #  or was fitted by too many components\n        if ncomps is None:\n            return rows\n        elif ncomps == 0:\n            return rows\n        elif self.ncomps_max is not None:\n            if ncomps > self.ncomps_max:\n                return rows\n\n        yi, xi = self.pickled_data['location'][idx]\n        spectrum = self.pickled_data['data_list'][idx]\n        fit_amps = self.decomposition['amplitudes_fit'][idx]\n        fit_fwhms = self.decomposition['fwhms_fit'][idx]\n        fit_means = self.decomposition['means_fit'][idx]\n        fit_e_amps = self.decomposition['amplitudes_fit_err'][idx]\n        fit_e_fwhms = self.decomposition['fwhms_fit_err'][idx]\n        fit_e_means = self.decomposition['means_fit_err'][idx]\n        error = self.pickled_data['error'][idx][0]\n\n        residual = spectrum - combined_gaussian(\n            fit_amps, fit_fwhms, fit_means, self.pickled_data['x_values'])\n\n        aicc = self.decomposition['best_fit_aicc'][idx]\n        rchi2 = self.decomposition['best_fit_rchi2'][idx]\n        pvalue = self.decomposition['pvalue'][idx]\n\n        broad = self.decomposition['broad'][idx]\n\n        ncomp_wmedian = self.decomposition['ncomps_wmedian'][idx]\n        ncomp_jumps = self.decomposition['ncomps_jumps'][idx]\n\n        means_interval = self.decomposition['means_interval'][idx]\n        n_centroids = self.decomposition['n_centroids'][idx]\n\n        flags_blended = self.get_flag_blended(fit_amps, fit_fwhms, fit_means)\n        flags_neg_res_peak = negative_residuals(\n            spectrum, residual, error, get_flags=True,\n            fwhms=fit_fwhms, means=fit_means)\n        flags_broad = self.get_flag_broad(fit_fwhms, broad)\n        flag_centroid = self.get_flag_centroid(\n            np.array(fit_means), means_interval, n_centroids)\n\n        x_wcs, y_wcs, z_wcs = self.wcs.wcs_pix2world(\n            xi, yi, np.array(fit_means), 0)\n\n        velocities = z_wcs * self.to_unit\n        e_velocities = np.array(fit_e_means) * self.velocity_increment\n        vel_disps = (\n            np.array(fit_fwhms) / 2.354820045) * self.velocity_increment\n        e_vel_disps = (\n            np.array(fit_e_fwhms) / 2.354820045) * self.velocity_increment\n\n        amplitudes = np.array(fit_amps)\n        e_amplitudes = np.array(fit_e_amps)\n\n        if self.main_beam_efficiency is not None:\n            amplitudes /= self.main_beam_efficiency\n            e_amplitudes /= self.main_beam_efficiency\n            error /= self.main_beam_efficiency\n\n        integrated_intensity = area_of_gaussian(\n            amplitudes, np.array(fit_fwhms) * self.velocity_increment)\n        fit_fwhms_plus_error = np.array(fit_fwhms) + np.array(fit_e_fwhms)\n        e_integrated_intensity = area_of_gaussian(\n            amplitudes + e_amplitudes,\n            fit_fwhms_plus_error * self.velocity_increment) -\\\n            integrated_intensity\n\n        for i in range(ncomps):\n            row = [\n                xi + self.xpos_offset, yi + self.ypos_offset,\n                x_wcs[0], y_wcs[0],\n                amplitudes[i], e_amplitudes[i],\n                velocities[i], e_velocities[i],\n                vel_disps[i], e_vel_disps[i],\n                integrated_intensity[i], e_integrated_intensity[i],\n                error, pvalue, aicc, rchi2,\n                ncomps, ncomp_wmedian, ncomp_jumps,\n                flags_blended[i], flags_neg_res_peak[i],\n                flags_broad[i], flag_centroid]\n\n            if self.subcube_nr is not None:\n                row.append(self.subcube_nr)\n\n            rows.append(row)\n\n        return rows\n\n    def make_table(self, save=True):\n        \"\"\"Create table of the decomposition results.\n\n        Parameters\n        ----------\n        save : bool\n            Set to `True` if the table should be saved.\n\n        Returns\n        -------\n        table_results : astropy.table.table.Table\n            Table of the decomposition results.\n\n        \"\"\"\n        import gausspyplus.parallel_processing\n        gausspyplus.parallel_processing.init([self.decomposition['index_fit'], [self]])\n\n        results_list = gausspyplus.parallel_processing.func(\n            use_ncpus=self.use_ncpus, function='make_table')\n\n        for i, item in enumerate(results_list):\n            if not isinstance(item, list):\n                say(\"Error for spectrum with index {}: {}\".format(i, item))\n                continue\n\n        # results_list = [item for item in results_list if len(item) > 0]\n        results_list = np.array([item for sublist in results_list\n                                 for item in sublist])\n\n        names = [\n            'x_pos', 'y_pos', self.wcs.wcs.lngtyp, self.wcs.wcs.lattyp,\n            'amp', 'e_amp', 'VLSR', 'e_VLSR', 'vel_disp', 'e_vel_disp',\n            'int_tot', 'e_int_tot', 'rms', 'pvalue', 'aicc', 'rchi2',\n            'ncomps', 'ncomp_wmedian', 'ncomp_jumps',\n            'flag_blended', 'flag_neg_res_peak', 'flag_broad', 'flag_centroid']\n\n        dtype = ['i4']*2 + ['f4']*14 + ['i4']*7\n\n        if self.subcube_nr is not None:\n            names.append('subcube_nr')\n            dtype.append('i4')\n\n        table_results = Table(data=results_list, names=names, dtype=dtype)\n\n        for key in names[2:16]:\n            table_results[key].format = \"{0:.4f}\"\n\n        if save:\n            filename = self.fin_filename + '.dat'\n            path_to_table = os.path.join(self.dirpath_table, filename)\n            table_results.write(path_to_table, format='ascii', overwrite=True)\n            say(\"\\033[92mSAVED FILE:\\033[0m '{}' in '{}'\".format(\n                filename, self.decomp_dirname))\n\n        return table_results\n\n    def save_final_results(self):\n        \"\"\"Save the results of the spatially coherent refitting iterations.\"\"\"\n        filename = self.fin_filename + '.pickle'\n        pathToFile = os.path.join(self.decomp_dirname, filename)\n        pickle.dump(self.decomposition, open(pathToFile, 'wb'), protocol=2)\n        say(\"\\033[92mSAVED FILE:\\033[0m '{}' in '{}'\".format(\n            filename, self.decomp_dirname))\n\n    def produce_map(self, keyword='error', comments=[], suffix='', save=True,\n                    dtype='float32'):\n        \"\"\"Generate an array/FITS map of a GaussPy+ quantity.\n\n        Parameters\n        ----------\n        keyword : str ['error', 'best_fit_rchi2', 'N_components']\n            Keyword contained in GaussPy+ dictionary whose values should be made into an array.\n        comments : list\n            List of strings that are added to the FITS header of the map.\n        suffix : str\n            Suffix that is added to the filename.\n        save : bool\n            Set to `True` if the map should be saved.\n        dtype : str\n            Valid dtype for the resulting map.\n\n        Returns\n        -------\n        astropy.io.fits.HDUList\n            FITS HDU object of the map.\n\n        \"\"\"\n        #  TODO: routine in case pickled_data is missing the header key\n        shape = (self.header['NAXIS2'], self.header['NAXIS1'])\n        array = np.ones((shape[0], shape[1])) * np.nan\n\n        if keyword in self.pickled_data.keys():\n            data = self.pickled_data[keyword]\n        elif keyword in self.decomposition.keys():\n            data = self.decomposition[keyword]\n\n        for (y, x), value in zip(self.pickled_data['location'], data):\n            if value is None:\n                continue\n\n            try:\n                array[y, x] = value\n            except ValueError:\n                array[y, x] = value[0]\n\n        header = change_header(self.header.copy(), format='pp',\n                               comments=comments)\n\n        array = array.astype(dtype)\n\n        if save:\n            if keyword == 'error':\n                filename, _ = os.path.splitext(\n                    os.path.basename(self.path_to_pickle_file))\n            else:\n                filename = self.filename\n\n            filename = \"{}{}.fits\".format(filename, suffix)\n            path_to_file = os.path.join(\n                self.dirpath_gpy, 'gpy_maps', filename)\n\n            save_fits(array, header, path_to_file,\n                      verbose=False)\n            say(\"\\n\\033[92mSAVED FILE:\\033[0m '{}' in '{}'\".format(\n                filename, os.path.dirname(path_to_file)), logger=self.logger)\n\n        return fits.PrimaryHDU(array, header)\n\n    def produce_noise_map(self, comments=['Rms noise values.'],\n                          suffix='_noise_map', save=True, dtype='float32',\n                          get_hdu=False, get_data=False, get_header=False):\n        \"\"\"Produce a map of the rms noise values.\n\n        Parameters\n        ----------\n        comments : list\n            List of strings that are added to the FITS header of the map.\n        suffix : str\n            Suffix that is added to the filename.\n        save : bool\n            Set to `True` if the map should be saved.\n        dtype : str\n            Valid dtype for the resulting map.\n        get_hdu : bool\n            Default is `False`. If set to `True`, an astropy.io.fits.HDUList is returned. Overrides 'get_data' and 'get_header'.\n        get_data : bool\n            Default is `False`. Returns a numpy.ndarray of the FITS array.\n        get_header : bool\n            Default is `False`. Returns a astropy.io.fits.Header of the FITS array.\n\n        Returns\n        -------\n        tuple or None\n            Result from `return_hdu_options`.\n\n        \"\"\"\n        if not self.initialized_state:\n            self.check_settings()\n            self.initialize()\n        hdu = self.produce_map(keyword='error', comments=comments,\n                               suffix=suffix, save=save, dtype=dtype)\n\n        return return_hdu_options(\n            hdu, get_hdu=get_hdu, get_data=get_data, get_header=get_header)\n\n    def produce_rchi2_map(self, suffix='_rchi2_map', save=True, dtype='float32',\n                          get_hdu=False, get_data=False, get_header=False,\n                          comments=['Reduced chi-square values.']):\n        \"\"\"Produce a map of the reduced chi-square values.\n\n        Parameters\n        ----------\n        comments : list\n            List of strings that are added to the FITS header of the map.\n        suffix : str\n            Suffix that is added to the filename.\n        save : bool\n            Set to `True` if the map should be saved.\n        dtype : str\n            Valid dtype for the resulting map.\n        get_hdu : bool\n            Default is `False`. If set to `True`, an astropy.io.fits.HDUList is returned. Overrides 'get_data' and 'get_header'.\n        get_data : bool\n            Default is `False`. Returns a numpy.ndarray of the FITS array.\n        get_header : bool\n            Default is `False`. Returns a astropy.io.fits.Header of the FITS array.\n\n        Returns\n        -------\n        tuple or None\n            Result from `return_hdu_options`.\n\n        \"\"\"\n        if not self.initialized_state:\n            self.check_settings()\n            self.initialize()\n        hdu = self.produce_map(keyword='best_fit_rchi2', comments=comments,\n                               suffix=suffix, save=save, dtype=dtype)\n\n        return return_hdu_options(\n            hdu, get_hdu=get_hdu, get_data=get_data, get_header=get_header)\n\n    def produce_component_map(self, suffix='_component_map', save=True,\n                              dtype='float32', get_hdu=False, get_data=False, get_header=False, comments=['Number of fitted Gaussian components.']):\n        \"\"\"Produce a map of the number of fitted Gaussian components.\n\n        Parameters\n        ----------\n        comments : list\n            List of strings that are added to the FITS header of the map.\n        suffix : str\n            Suffix that is added to the filename.\n        save : bool\n            Set to `True` if the map should be saved.\n        dtype : str\n            Valid dtype for the resulting map.\n        get_hdu : bool\n            Default is `False`. If set to `True`, an astropy.io.fits.HDUList is returned. Overrides 'get_data' and 'get_header'.\n        get_data : bool\n            Default is `False`. Returns a numpy.ndarray of the FITS array.\n        get_header : bool\n            Default is `False`. Returns a astropy.io.fits.Header of the FITS array.\n\n        Returns\n        -------\n        tuple or None\n            Result from `return_hdu_options`.\n\n        \"\"\"\n        if not self.initialized_state:\n            self.check_settings()\n            self.initialize()\n        hdu = self.produce_map(keyword='N_components', comments=comments,\n                               suffix=suffix, save=save, dtype=dtype)\n\n        return return_hdu_options(\n            hdu, get_hdu=get_hdu, get_data=get_data, get_header=get_header)\n\n    def make_cube(self, mode='full_decomposition', save=True, get_hdu=False,\n                  get_data=False, get_header=False, dtype='float32'):\n        \"\"\"Create FITS cube of the decomposition results.\n\n        Parameters\n        ----------\n        mode : str\n            'full_decomposition' recreates the whole FITS cube, 'integrated_intensity' creates a cube with the integrated intensity values of the Gaussian components placed at their mean positions, 'main_component' only retains the fitted component with the largest amplitude value\n        save : bool\n            Set to `True` if the map should be saved.\n        dtype : str\n            Valid dtype for the resulting map.\n        get_hdu : bool\n            Default is `False`. If set to `True`, an astropy.io.fits.HDUList is returned. Overrides 'get_data' and 'get_header'.\n        get_data : bool\n            Default is `False`. Returns a numpy.ndarray of the FITS array.\n        get_header : bool\n            Default is `False`. Returns a astropy.io.fits.Header of the FITS array.\n\n        Returns\n        -------\n        tuple or None\n            Result from `return_hdu_options`.\n\n        \"\"\"\n        say('\\ncreate {} cube...'.format(mode))\n\n        x = self.header['NAXIS1']\n        y = self.header['NAXIS2']\n        z = self.header['NAXIS3']\n\n        array = np.zeros([z, y, x], dtype=np.float32)\n        nSpectra = len(self.decomposition['N_components'])\n\n        for idx in range(nSpectra):\n            ncomps = self.decomposition['N_components'][idx]\n            if ncomps is None:\n                continue\n\n            yi = self.location[idx][0]\n            xi = self.location[idx][1]\n\n            amps = self.decomposition['amplitudes_fit'][idx]\n            fwhms = self.decomposition['fwhms_fit'][idx]\n            means = self.decomposition['means_fit'][idx]\n\n            if self.main_beam_efficiency is not None:\n                amps = [amp / self.main_beam_efficiency for amp in amps]\n\n            if mode == 'main_component' and ncomps > 0:\n                j = amps.index(max(amps))\n                array[:, yi, xi] = gaussian(\n                    amps[j], fwhms[j], means[j], self.channels)\n            elif mode == 'integrated_intensity' and ncomps > 0:\n                for j in range(ncomps):\n                    integrated_intensity = area_of_gaussian(\n                        amps[j], fwhms[j] * self.velocity_increment)\n                    channel = int(round(means[j]))\n                    if self.channels[0] <= channel <= self.channels[-1]:\n                        array[channel, yi, xi] += integrated_intensity\n            elif mode == 'full_decomposition':\n                array[:, yi, xi] = combined_gaussian(\n                    amps, fwhms, means, self.channels)\n\n            nans = self.nan_mask[:, yi, xi]\n            array[:, yi, xi][nans] = np.NAN\n\n        array[self.nan_mask] = np.nan\n        array = array.astype(dtype)\n\n        if mode == 'main_component':\n            comment = 'Fit component with highest amplitude per spectrum.'\n            filename = \"{}_main.fits\".format(self.filename, self.suffix)\n        elif mode == 'integrated_intensity':\n            comment = 'Integrated intensity of fit component at VLSR position.'\n            filename = \"{}_int_tot.fits\".format(self.filename, self.suffix)\n        elif mode == 'full_decomposition':\n            comment = 'Recreated dataset from fit components.'\n            filename = \"{}_decomp.fits\".format(self.filename, self.suffix)\n\n        comments = ['GaussPy+ decomposition results:']\n        comments.append(comment)\n        if self.main_beam_efficiency is not None:\n            comments.append('Corrected for main beam efficiency of {}.'.format(\n                self.main_beam_efficiency))\n\n        header = update_header(\n            self.header.copy(), comments=comments, write_meta=True)\n\n        if save:\n            pathToFile = os.path.join(self.decomp_dirname, 'FITS', filename)\n            save_fits(array, header, pathToFile, verbose=False)\n            say(\"\\033[92mSAVED FILE:\\033[0m '{}' in '{}'\".format(\n                filename, os.path.dirname(pathToFile)))\n\n        hdu = fits.PrimaryHDU(array, header)\n\n        return return_hdu_options(\n            hdu, get_hdu=get_hdu, get_data=get_data, get_header=get_header)\n", "meta": {"hexsha": "4cfa1271eb728817163587d4a1a45c73044515a2", "size": 23239, "ext": "py", "lang": "Python", "max_stars_repo_path": "gausspyplus/finalize.py", "max_stars_repo_name": "cmurray-astro/gausspyplus", "max_stars_repo_head_hexsha": "bb26e561da70b8b130c785fbc4324c95bc416766", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2019-06-03T14:03:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T16:25:23.000Z", "max_issues_repo_path": "gausspyplus/finalize.py", "max_issues_repo_name": "cmurray-astro/gausspyplus", "max_issues_repo_head_hexsha": "bb26e561da70b8b130c785fbc4324c95bc416766", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-03-13T06:35:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-06T07:06:23.000Z", "max_forks_repo_path": "gausspyplus/finalize.py", "max_forks_repo_name": "cmurray-astro/gausspyplus", "max_forks_repo_head_hexsha": "bb26e561da70b8b130c785fbc4324c95bc416766", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-06-26T01:48:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T23:54:07.000Z", "avg_line_length": 38.9916107383, "max_line_length": 281, "alphanum_fraction": 0.5993373209, "include": true, "reason": "import numpy,from astropy", "num_tokens": 5242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.38121958031636166, "lm_q1q2_score": 0.199538085750549}}
{"text": "#!/usr/bin/env python\n\"\"\"\n\nrunsim.py by John Swoboda 3/16/2015\nThis script will run the SimISR code. The user can run a number of different\naspects including making data, fitting applying matrix formulation of the\nspace-time ambuiguty operator and calling inversion methods.\n\n\nInputs\n             -f These will be the possible functions that can be used\n                 spectrums :makespectrums,\n                 radardata :makeradardata,\n                 fitting :fitdata,'\n                 fittingmat :fitdata,\n                 fittinginv :fitdata,\n                 applymat applymat\n\"\"\"\nfrom __future__ import print_function\n\n#imported basic modules\nimport time\nimport sys\nfrom datetime import datetime\nimport traceback\nimport argparse\nimport ipdb\n\n# Imported scipy and matplotlib modules\nimport scipy as sp\n# My modules\nfrom SimISR import Path\nfrom SimISR.IonoContainer import IonoContainer\nfrom SimISR.radarData import RadarDataFile\nimport SimISR.specfunctions as specfuncs\nfrom SimISR.fitterMethodGen import Fitterionoconainer\nfrom SimISR.utilFunctions import readconfigfile, update_progress\nfrom SimISR.operators import RadarSpaceTimeOperator\n\n#%% Make spectrums\ndef makespectrums(basedir, configfile, printlines=True):\n    \"\"\" This will make all of the spectra for a set of data and save it in a\n    folder in basedir called Spectrums. It is assumed that the data in the Origparams\n    is time tagged in the title with a string seperated by a white space and the\n    rest of the file name. For example ~/DATA/Basedir/0 origdata.h5.\n    Inputs:\n        basedir: A string for the directory that will hold all of the data for the simulation.\n        configfile: The configuration file for the simulation.\n         \"\"\"\n    basedir = Path(basedir).expanduser()\n    dirio = ('Origparams', 'Spectrums')\n    inputdir = basedir/dirio[0]\n    outputdir = basedir/dirio[1]\n    # determine the list of h5 files in Origparams directory\n    dirlist = sorted(inputdir.glob('*.h5'))\n    # Make the lists of numbers and file names for the dictionary\n    (listorder, _, _, timebeg, _) = IonoContainer.gettimes(dirlist)\n    slist = [dirlist[ikey] for ikey in listorder]\n    (sensdict, simparams) = readconfigfile(configfile)\n    # Delete data\n    outfiles = outputdir.glob('*.h5')\n    for ifile in outfiles:\n        ifile.unlink()\n\n    for inum, curfile in zip(timebeg, slist):\n\n        outfile = outputdir / (str(inum)+' spectrum.h5')\n        update_progress(float(inum)/float(len(slist)),\n                        'Processing file {} starting at {}'.format(curfile.name, datetime.now()))\n        curiono = IonoContainer.readh5(str(curfile))\n\n        curiono.makespectruminstanceopen(specfuncs.ISRSspecmake, sensdict,\n                                         int(simparams['numpoints']), float(inum),\n                                         float(len(slist)), printlines).saveh5(str(outfile))\n        update_progress(float(inum+1)/float(len(slist)),\n                        'Finished file {} starting at {}'.format(curfile.name, datetime.now()))\n\n#%% Make Radar Data\ndef makeradardata(basedir,configfile,remakealldata):\n    \"\"\" This function will make the radar data and create the acf estimates.\n    Inputs:\n        basedir: A string for the directory that will hold all of the data for the simulation.\n        configfile: The configuration file for the simulation.\n        remakealldata: A bool that determines if the radar data is remade. If false\n            only the acfs will be estimated using the radar that is already made.\"\"\"\n\n    dirio = ('Spectrums', 'Radardata', 'ACF')\n    inputdir = basedir/dirio[0]\n    outputdir = basedir/dirio[1]\n    outputdir2 = basedir/dirio[2]\n\n    # determine the list of h5 files in Origparams directory\n    dirlist = [str(i) for i in inputdir.glob('*.h5')]\n    # Make the lists of numbers and file names for the dictionary\n    if len(dirlist) > 0:\n        (listorder, _, _, timebeg, _) = IonoContainer.gettimes(dirlist)\n\n        Ionodict = {timebeg[itn]:dirlist[it] for itn, it in enumerate(listorder)}\n    else:\n        Ionodict = {0.:str(inputdir.joinpath('00.h5'))}\n    # Find all of the raw data files\n    radardatalist = outputdir.glob('*RawData.h5')\n    if radardatalist and (not remakealldata):\n        # XXX need to work on time stuff\n        outlist2 = radardatalist\n    else:\n        outlist2 = None\n\n    # create the radar data file class\n    rdata = RadarDataFile(Ionodict, configfile, outputdir, outfilelist=outlist2)\n    # From the ACFs and uncertainties\n    (ionoout, ionosig) = rdata.processdataiono()\n    # save the acfs and uncertianties in ionocontainer h5 files.\n    ionoout.saveh5(str(outputdir2.joinpath('00lags.h5')))\n    ionosig.saveh5(str(outputdir2.joinpath('00sigs.h5')))\n    return ()\n#%% Fit data\ndef fitdata(basedir,configfile,optinputs):\n    \"\"\" This function will run the fitter on the estimated ACFs saved in h5 files.\n        Inputs:\n        basedir: A string for the directory that will hold all of the data for the simulation.\n        configfile: The configuration file for the simulation.\n        optinputs:A string that helps determine the what type of acfs will be fitted.\n         \"\"\"\n    # determine the input folders which can be ACFs from the full simulation\n    dirdict = {'fitting':('ACF', 'Fitted'), 'fittingmat':('ACFMat', 'FittedMat'),\n               'fittinginv':('ACFInv', 'FittedInv'), 'fittingmatinv':('ACFMatInv', 'FittedMatInv')}\n    dirio = dirdict[optinputs[0]]\n    inputdir = basedir/dirio[0]\n    outputdir = basedir/dirio[1]\n    fitlist = optinputs[1]\n    if len(optinputs) > 2:\n        exstr = optinputs[2]\n        printlines = optinputs[3]\n    else:\n        exstr = ''\n    dirlist = [str(i) for i in inputdir.glob('*lags{0}.h5'.format(exstr))]\n    dirlistsig = [str(i) for i in inputdir.glob('*sigs{0}.h5'.format(exstr))]\n\n    Ionoin = IonoContainer.readh5(dirlist[0])\n    if len(dirlistsig) == 0:\n        Ionoinsig = None\n    else:\n        Ionoinsig = IonoContainer.readh5(dirlistsig[0])\n    fitterone = Fitterionoconainer(Ionoin, Ionoinsig, configfile)\n\n    fitoutput = fitterone.fitdata(specfuncs.ISRSfitfunction,\n                                  fitterone.simparams['startfile'], fittimes=fitlist,\n                                  printlines=printlines)\n\n    #ipdb.set_trace()\n    (fitteddata, fittederror, funcevals, fittedcov) = fitoutput\n    if fitterone.simparams['Pulsetype'].lower() == 'barker':\n        paramlist = fitteddata\n\n        species = fitterone.simparams['species']\n        paramnames = ['Ne']\n        if not fittederror is None:\n            fittederronly = sp.sqrt(fittederror)\n            paramlist = sp.concatenate([fitteddata, fittederronly], axis=2)\n            paramnamese = ['n'+ip for ip in paramnames]\n            paranamsf = sp.array(paramnames+paramnamese)\n        else:\n            paranamsf = sp.array(paramnames)\n    else:\n        fittederronly = sp.sqrt(fittederror)\n        paramnames = []\n        species = fitterone.simparams['species']\n        # Seperate Ti and put it in as an element of the ionocontainer.\n        Ti = fitteddata[:, :, 1]\n\n        nTi = fittederronly[:, :, 1]\n\n        nTiTe = fittedcov[:, :, 0, 1]\n        nTiNe = fittedcov[:, :, 0, 2]\n        nTiVi = fittedcov[:, :, 0, 3]\n        nTeNe = fittedcov[:, :, 1, 2]\n        nTeVi = fittedcov[:, :, 1, 3]\n        nNeVi = fittedcov[:, :, 2, 3]\n        cov_list = [nTiTe[:, :, sp.newaxis], nTiNe[:, :, sp.newaxis],\n                    nTiVi[:, :, sp.newaxis], nTeNe[:, :, sp.newaxis],\n                    nTeVi[:, :, sp.newaxis], nNeVi[:, :, sp.newaxis]]\n        cov_list_names = ['nTiTe', 'nTiNe', 'nTiVi', 'nTeNe', 'nTeVi','nNeVi']\n        paramlist = sp.concatenate([fitteddata, Ti[:, :, sp.newaxis], fittederronly,\n                                    nTi[:, :, sp.newaxis], funcevals[:, :, sp.newaxis]]\n                                   + cov_list, axis=2)\n        for isp in species[:-1]:\n            paramnames.append('Ni_'+isp)\n            paramnames.append('Ti_'+isp)\n        paramnames = paramnames+['Ne', 'Te', 'Vi', 'Nepow', 'Ti']\n        paramnamese = ['n'+ip for ip in paramnames]\n        paranamsf = sp.array(paramnames+paramnamese+['FuncEvals']+cov_list_names)\n\n    if fitlist is None:\n        timevec = Ionoin.Time_Vector\n    else:\n        if len(fitlist) == 0:\n            timevec = Ionoin.Time_Vector\n        else:\n            timevec = Ionoin.Time_Vector[fitlist]\n    # This requires\n    if set(Ionoin.Coord_Vecs) == {'x', 'y', 'z'}:\n        newver = 0\n        ionoout = IonoContainer(Ionoin.Cart_Coords, paramlist.real, timevec, ver=newver,\n                                coordvecs=Ionoin.Coord_Vecs, paramnames=paranamsf,\n                                species=species)\n    elif set(Ionoin.Coord_Vecs) == {'r', 'theta', 'phi'}:\n        newver = 1\n        ionoout = IonoContainer(Ionoin.Sphere_Coords, paramlist.real, timevec, ver=newver,\n                                coordvecs=Ionoin.Coord_Vecs, paramnames=paranamsf,\n                                species=species)\n\n\n    outfile = outputdir.joinpath('fitteddata{0}.h5'.format(exstr))\n    ionoout.saveh5(str(outfile))\n#%% apply the matrix for the data\ndef applymat(basedir, configfile, optinputs):\n    \"\"\"\n        This function apply the matrix version of the space time ambiugty function\n        to the ACFs and save the outcome in h5 files within the directory ACFMat.\n        Inputs:\n        basedir: A string for the directory that will hold all of the data for the simulation.\n        configfile: The configuration file for the simulation.\n    \"\"\"\n    dirio = ('Spectrums', 'Mat', 'ACFMat')\n    basedir = Path(basedir)\n    inputdir = basedir.joinpath(dirio[0])\n    outputdir2 = basedir.joinpath(dirio[2])\n\n    dirlist = [str(i) for i in inputdir.glob('*.h5')]\n    (listorder, timevector, _, _, _) = IonoContainer.gettimes(dirlist)\n    ionolist = [dirlist[ikey] for ikey in listorder]\n    rsto = RadarSpaceTimeOperator(ionolist, configfile, timevector, mattype='matrix')\n    ionoout = rsto.mult_iono(ionolist)\n    outfile = outputdir2.joinpath('00lags.h5')\n    ionoout.saveh5(str(outfile))\n\n#%% For sorting\ndef ke(item):\n    \"\"\"\n        Used for sorting names of files.\n    \"\"\"\n    if item[0].isdigit():\n        return int(item.partition(' ')[0])\n    else:\n        return float('inf')\n#%% Main function\ndef main(funcnamelist,basedir,configfile,remakealldata,fitlist=None,invtype='',printlines=True):\n    \"\"\" Main function for this module. The function will set up the directory\n    structure, create or update a diary file and run the simulation depending\n    on the user input.\n    Inputs\n        funcnamelist: A list of strings that coorespond to specific functions.\n                The stirng and function they correspond to, that will be shown.\n\n                 spectrums: makespectrums, This will create the ISR spectrums\n\n                 radardata :makeradardata, This will make the radar data and\n                     form the ACF estimates. If the raw radar data exists then\n                     the user must use the -r option on the command line and set\n                     it to y.\n\n                 fitting :fitdata, This will apply the fitter to the data in\n                 the ACF folder of the base directory.\n\n                 fittingmat :fitdata,This will apply the fitter to the data in\n                 the ACFMat folder of the base directory.\n\n                 fittinginv :fitdata,This will apply the fitter to the data in\n                 the ACFInv folder of the base directory.\n\n                 applymat :applymat, This wil create and apply a matrix\n                 formulation of thespace-time ambiguity function to ISR spectrums.\n        basedir: The base directory that will contain all of the data. This directory\n                must contain a directory called Origparams with h5 files to run\n                the full simulation. The user can also start with a directory\n                from a later stage of the simulation instead though.\n\n        configfile: The configuration used for the simulation. Can be an ini file or\n                a pickle file.\n\n        remakealldata: A bool to determine if the raw radar data will be remade. If\n                this is False the radar data will only be made if it does\n                not exist in the file first.\n        fitlist:  A list of time entries that will be fit.\n\n        invtype\n\n    \"\"\"\n\n    inputsep = '***************************************************************\\n'\n\n    funcdict = {'spectrums':makespectrums, 'radardata':makeradardata, 'fitting':fitdata,'fittingmat':fitdata,\n                'fittinginv':fitdata,'applymat':applymat,'fittingmatinv':fitdata}\n    #inout = {'spectrums':('Origparams','Spectrums'),'radardata':('Spectrums','Radardata'),'fitting':('ACF','Fitted')}\n    #pdb.set_trace()\n\n    # check for the directories\n    dirnames = ['Origparams','Spectrums','Radardata','ACF','Fitted','ACFOrig','ACFMat','ACFInv','FittedMat','FittedInv','ACFMatInv','FittedMatInv']\n    basedir=Path(basedir).expanduser()\n    for idir in dirnames:\n        curdir = basedir/idir\n        curdir.mkdir(exist_ok=True,parents=True)\n\n    if len(funcnamelist)==3:\n        funcname='all'\n    else:\n        funcname=''.join(funcnamelist)\n\n    dfilename = 'diary'+funcname+'.txt'\n    dfullfilestr = basedir/dfilename\n\n    with open(str(dfullfilestr),'a') as f:\n        failure=False\n        for curfuncn in funcnamelist:\n            curfunc = funcdict[curfuncn]\n            f.write(inputsep)\n            f.write(curfunc.__name__+'\\n')\n            f.write(time.asctime()+'\\n')\n            if curfunc.__name__=='fitdata':\n                ex_inputs=[curfuncn,fitlist,invtype,printlines]\n            elif curfunc.__name__=='makeradardata':\n                ex_inputs = remakealldata\n            else:\n                ex_inputs=printlines\n            try:\n                stime = datetime.now()\n                curfunc(basedir,configfile,ex_inputs)\n                ftime = datetime.now()\n                ptime = ftime-stime\n                f.write('Success!\\n')\n                f.write('Duration: {}\\n'.format(ptime))\n                f.write('Base directory: {}\\n'.format(basedir))\n\n            except Exception as e:\n                f.write('Failed!\\n')\n                ftime = datetime.now()\n                ptime = ftime-stime\n                f.write('Duration: {}\\n'.format(ptime))\n                f.write('Base directory: {}\\n'.format(basedir))\n                traceback.print_exc(file=sys.stdout)\n                traceback.print_exc(file=f)\n                failure = True\n                break\n\n        f.write(inputsep)\n\n\n    return failure\n\ndef parse_command_line(str_input=None):\n    \"\"\"\n        This will parse through the command line arguments\n    \"\"\"\n    # if str_input is None:\n    parser = argparse.ArgumentParser()\n    # else:\n    #     parser = argparse.ArgumentParser(str_input)\n    fstr = '''      These will be the possible strings for the argument and the\n                    function they correspond to, that will be used ish shown.\n\n                     spectrums: makespectrums, This will create the ISR spectrums\n\n                     radardata :makeradardata, This will make the radar data and\n                         form the ACF estimates. If the raw radar data exists then\n                         the user must use the -r option on the command line and set\n                         it to y.\n\n                     fitting :fitdata, This will apply the fitter to the data in\n                     the ACF folder of the base directory.\n\n                     fittingmat :fitdata,This will apply the fitter to the data in\n                     the ACFMat folder of the base directory.\n\n                     fittinginv :fitdata,This will apply the fitter to the data in\n                     the ACFInv folder of the base directory.\n\n                     applymat :applymat, This wil create and apply a matrix\n                     formulation of thespace-time ambiguity function to ISR spectrums.\n\n\n                     all - This will run the commands from using the spectrums, radardata,\n                         and fitting\n                    '''\n    parser.add_argument('-f', '--funclist', dest='funclist', default='all', help=fstr)\n\n    parser.add_argument(\"-v\", \"--verbose\", action=\"store_true\",\n                        dest=\"verbose\", default=False,\n                        help=\"prints debug output and additional detail.\")\n    parser.add_argument(\"-c\", \"--config\", dest=\"config\", default='default.ini',\n                        help=\" Config file used for the simulation, .ini or yaml file.\")\n    parser.add_argument('-p', \"--path\", dest='path', default=None,\n                        help='Number of incoherent integrations in calculations.')\n    parser.add_argument('-r', \"--remake\", action=\"store_true\", dest='remake', default=False,\n                        help='Remake data flag.')\n\n    if str_input is None:\n        return parser.parse_args()\n    else:\n        return parser.parse_args(str_input)\n\nif __name__ == \"__main__\":\n\n    outstr = '''\n             Usage: python runsim.py -f <function: spectrums, radardata, fitting or all> -i <basedir> -c <config> -r <type y to remake data>\n\n             or\n\n             python runsim.py -h\n\n             This script will run the SimISR code. The user\n             can run a number of different aspects including making data, fitting\n             applying matrix formulation sof the space-time operator and calling\n             inversion methods.\n\n\n             Manditory Arguments to run code, for help just use the -h option.\n\n             -f These will be the possible strings for the argument and the\n                function they correspond to, that will be used ish shown.\n\n                 spectrums: makespectrums, This will create the ISR spectrums\n\n                 radardata :makeradardata, This will make the radar data and\n                     form the ACF estimates. If the raw radar data exists then\n                     the user must use the -r option on the command line and set\n                     it to y.\n\n                 fitting :fitdata, This will apply the fitter to the data in\n                 the ACF folder of the base directory.\n\n                 fittingmat :fitdata,This will apply the fitter to the data in\n                 the ACFMat folder of the base directory.\n\n                 fittinginv :fitdata,This will apply the fitter to the data in\n                 the ACFInv folder of the base directory.\n\n                 applymat :applymat, This wil create and apply a matrix\n                 formulation of thespace-time ambiguity function to ISR spectrums.\n\n\n                 all - This will run the commands from using the spectrums, radardata,\n                     and fitting\n\n            -i The base directory that will contain all of the data. This directory\n                must contain a directory called Origparams with h5 files to run\n                the full simulation. The user can also start with a directory\n                from a later stage of the simulation instead though.\n\n            -c The configuration used for the simulation. Can be an ini file or\n                a pickle file.\n\n            Optional arguments\n\n            -r If a y follows this then the raw radar data will be remade. If\n                this is not used the radar data will only be made if it does\n                not exist in the file first.\n\n             Example:\n             python runsim.py -f radardata -f fitting -i ~/DATA/ExampleLongPulse -c ~/DATA/Example -r y'''\n\n    args_commd = parse_command_line()\n    if args_commd.path is None:\n        print(\"Please provide an input source with the -p option!\")\n        sys.exit(1)\n    basedir =  str(Path(args_commd.path).expanduser())\n    configfile = str(Path(args_commd.config).expanduser())\n    funcname = args_commd.funclist\n    remakealldata = args_commd.remake\n\n    if funcname.lower() == 'all':\n        funcnamelist = ['spectrums', 'radardata', 'fitting']\n    else:\n        funcnamelist = funcname.split()\n\n    failflag = main(funcnamelist, basedir, configfile, remakealldata)\n", "meta": {"hexsha": "7c21df7ef12f621960cf6fe2434a7154b9786890", "size": 20100, "ext": "py", "lang": "Python", "max_stars_repo_path": "SimISR/runsim.py", "max_stars_repo_name": "jswoboda/RadarDataSim", "max_stars_repo_head_hexsha": "3eb6fcd8601e8ae25acc375e6d933169d14bb40f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-10-06T14:15:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T21:29:07.000Z", "max_issues_repo_path": "SimISR/runsim.py", "max_issues_repo_name": "jswoboda/SimISR", "max_issues_repo_head_hexsha": "3eb6fcd8601e8ae25acc375e6d933169d14bb40f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2016-12-03T23:27:19.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-06T03:04:06.000Z", "max_forks_repo_path": "SimISR/runsim.py", "max_forks_repo_name": "jswoboda/SimISR", "max_forks_repo_head_hexsha": "3eb6fcd8601e8ae25acc375e6d933169d14bb40f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-11-18T08:00:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T13:47:57.000Z", "avg_line_length": 42.1383647799, "max_line_length": 147, "alphanum_fraction": 0.6152238806, "include": true, "reason": "import scipy", "num_tokens": 4865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19953807839114812}}
{"text": "\"\"\" This module provides the basic classes for the pulse retrieval algorithms.\r\n\"\"\"\r\nimport numpy as np\r\nfrom types import SimpleNamespace\r\nfrom .. import io\r\nfrom ..mesh_data import MeshData\r\nfrom ..pulse_error import pulse_error\r\nfrom .. import lib\r\nfrom ..pnps import BasePNPS\r\nfrom math import isclose\r\n\r\n# global dictionary that contains all PNPS classes\r\n_RETRIEVER_CLASSES = {}\r\n\r\n\r\n# =============================================================================\r\n# Metaclass and factory\r\n# =============================================================================\r\nclass MetaRetriever(type):\r\n    \"\"\" Metaclass that registers Retriever classes in a global dictionary.\r\n    \"\"\"\r\n    def __new__(cls, clsmethod, bases, attrs):\r\n        global _RETRIEVER_CLASSES\r\n        newclass = super().__new__(cls, clsmethod, bases, attrs)\r\n        method = newclass.method\r\n        if method is None:\r\n            return newclass\r\n        # register the Retriever method, e.g. 'copra'\r\n        if method in _RETRIEVER_CLASSES:\r\n            raise ValueError(\"Two retriever classes implement retriever '%s'.\"\r\n                             % method)\r\n        _RETRIEVER_CLASSES[method] = newclass\r\n        return newclass\r\n\r\n\r\nclass MetaIORetriever(io.MetaIO, MetaRetriever):\r\n    # to fix metaclass conflicts\r\n    pass\r\n\r\n\r\n# =============================================================================\r\n# Retriever Base class\r\n# =============================================================================\r\nclass BaseRetriever(io.IO, metaclass=MetaIORetriever):\r\n    \"\"\" The abstract base class for pulse retrieval.\r\n\r\n    This class implements common functionality for different retrieval\r\n    algorithms.\r\n    \"\"\"\r\n    method = None\r\n    supported_schemes = None\r\n    _io_store = ['pnps', 'options', 'logging', 'log',\r\n                 '_retrieval_state', '_result']\r\n\r\n    def __init__(self, pnps, logging=False, verbose=False, **kwargs):\r\n        self.pnps = pnps\r\n        self.ft = self.pnps.ft\r\n        self.options = SimpleNamespace(**kwargs)\r\n        self._result = None\r\n        self.logging = logging\r\n        self.verbose = verbose\r\n        self.log = None\r\n        rs = self._retrieval_state = SimpleNamespace()\r\n        rs.running = False\r\n        if (self.supported_schemes is not None and\r\n                pnps.scheme not in self.supported_schemes):\r\n            raise ValueError(\"Retriever '%s' does not support scheme '%s'. \"\r\n                             \"It only supports %s.\" %\r\n                             (self.method, pnps.scheme, self.supported_schemes)\r\n                             )\r\n\r\n    def retrieve(self, measurement, initial_guess, weights=None,\r\n                 **kwargs):\r\n        \"\"\" Retrieve pulse from ``measurement`` starting at ``initial_guess``.\r\n\r\n        Parameters\r\n        ----------\r\n        measurement : MeshData\r\n            A MeshData instance that contains the PNPS measurement. The first\r\n            axis has to correspond to the PNPS parameter, the second to the\r\n            frequency. The data has to be the measured _intensity_ over the\r\n            frequency (not wavelength!). The second axis has to match exactly\r\n            the frequency axis of the underlying PNPS instance. No\r\n            interpolation is done.\r\n        initial_guess : 1d-array\r\n            The spectrum of the pulse that is used as initial guess in the\r\n            iterative retrieval.\r\n        weights : 1d-array\r\n            Weights that are attributed to the measurement for retrieval.\r\n            In the case of (assumed) Gaussian uncertainties with standard\r\n            deviation sigma they should correspond to 1/sigma.\r\n            Not all algorithms support using the weights.\r\n        kwargs : dict\r\n            Can override retrieval options specified in :func:`__init__`.\r\n\r\n        Notes\r\n        -----\r\n        This function provides no interpolation or data processing. You have\r\n        to write a retriever wrapper for that purpose.\r\n        \"\"\"\r\n        self.options.__dict__.update(**kwargs)\r\n        if not isinstance(measurement, MeshData):\r\n            raise ValueError(\"measurement has to be a MeshData instance!\")\r\n        self._retrieve_begin(measurement, initial_guess, weights)\r\n        self._retrieve()\r\n        self._retrieve_end()\r\n\r\n    def _retrieve_begin(self, measurement, initial_guess, weights):\r\n        pnps = self.pnps\r\n        if not np.allclose(pnps.process_w, measurement.axes[1], rtol=1e-6):\r\n            raise ValueError(\"Measurement has to lie on simulation grid!\")\r\n        # Store measurement\r\n        self.measurement = measurement\r\n        self.parameter = measurement.axes[0]\r\n        self.Tmn_meas = measurement.data\r\n\r\n        self.initial_guess = initial_guess\r\n        # set the size\r\n        self.M, self.N = self.Tmn_meas.shape\r\n        # Setup the weights\r\n        if weights is None:\r\n            self._weights = np.ones((self.M, self.N))\r\n        else:\r\n            self._weights = weights.copy()\r\n        # Retrieval state\r\n        rs = self._retrieval_state\r\n        rs.approximate_error = False\r\n        rs.running = True\r\n        rs.steps_since_improvement = 0\r\n        # Initialize result\r\n        res = self._result = SimpleNamespace()\r\n        res.trace_error = self.trace_error(self.initial_guess)\r\n        res.approximate_error = False\r\n        res.spectrum = self.initial_guess.copy()\r\n        # Setup the logger\r\n        if self.logging:\r\n            log = self.log = SimpleNamespace()\r\n            log.trace_error = []\r\n            log.initial_guess = self.initial_guess.copy()\r\n        else:\r\n            self.log = None\r\n        if self.verbose:\r\n            print(\"Started retriever '%s'\" % self.method)\r\n            print(\"Options:\")\r\n            print(self.options)\r\n            print(\"Initial trace error R = {:.10e}\".format(res.trace_error))\r\n            print(\"Starting retrieval...\")\r\n            print()\r\n\r\n    def _retrieve_end(self):\r\n        rs = self._retrieval_state\r\n        rs.running = False\r\n        res = self._result\r\n        if res.approximate_error:\r\n            res.trace_error = self.trace_error(res.spectrum)\r\n            res.approximate_error = False\r\n\r\n    def _project(self, measured, Smk):\r\n        \"\"\" Performs the projection on the measured intensity.\r\n        \"\"\"\r\n        # in frequency domain\r\n        Smn = self.ft.forward(Smk)\r\n        # project and specially handle values with zero amplitude\r\n        absSmn = np.abs(Smn)\r\n        f = (absSmn > 0.0)\r\n        Smn[~f] = np.sqrt(measured[~f] + 0.0j)\r\n        Smn[f] = Smn[f] / absSmn[f] * np.sqrt(measured[f] + 0.0j)\r\n        # back in time domain\r\n        Smk2 = self.ft.backward(Smn)\r\n        return Smk2\r\n\r\n    def _objective_function(self, spectrum):\r\n        \"\"\" Calculates the minimization objective from the pulse spectrum.\r\n\r\n        This is Eq. 11 in the paper:\r\n\r\n            r = sum (Tmn^meas - mu * Tmn)\r\n        \"\"\"\r\n        # calculate the PNPS trace\r\n        Tmn = self.pnps.calculate(spectrum, self.parameter)\r\n        return self._r(Tmn)\r\n\r\n    def trace_error(self, spectrum, store=True):\r\n        \"\"\" Calculates the trace error from the pulse spectrum.\r\n        \"\"\"\r\n        Tmn = self.pnps.calculate(spectrum, self.parameter)\r\n        return self._R(Tmn, store=store)\r\n\r\n    def _r(self, Tmn, store=True):\r\n        \"\"\" Calculates the minimization objective r from a simulated trace Tmn.\r\n        \"\"\"\r\n        diff = self._error_vector(Tmn, store=store)\r\n        return np.sum(diff * diff)\r\n\r\n    def _error_vector(self, Tmn, store=True):\r\n        \"\"\" Calculates the residual vector from measured to simulated\r\n        intensity.\r\n        \"\"\"\r\n        # rename\r\n        rs = self._retrieval_state\r\n        Tmn_meas = self.Tmn_meas\r\n        # scaling factor\r\n        w2 = self._weights * self._weights\r\n        mu = np.sum(Tmn_meas * Tmn * w2) / np.sum(Tmn * Tmn * w2)\r\n        # store intermediate results in current retrieval state\r\n        if store:\r\n            rs.mu = mu\r\n            rs.Tmn = Tmn\r\n            rs.Smk = self.pnps.Smk\r\n        return np.ravel((Tmn_meas - mu * Tmn) * self._weights)\r\n\r\n    def _R(self, Tmn, store=True):\r\n        \"\"\" Calculates the trace error from a simulated trace Tmn.\r\n        \"\"\"\r\n        r = self._r(Tmn, store=store)\r\n        return self._Rr(r)\r\n\r\n    def _Rr(self, r):\r\n        \"\"\" Calculates the trace error from the minimization objective r.\r\n        \"\"\"\r\n        return np.sqrt(r / (self.M * self.N *\r\n                            (self.Tmn_meas * self._weights).max()**2))\r\n\r\n    def result(self, pulse_original=None, full=True):\r\n        \"\"\" Analyzes the retrieval results in one retrieval instance\r\n            and processes it for plotting or storage.\r\n        \"\"\"\r\n        rs = self._retrieval_state\r\n        if self._result is None or self._retrieval_state.running:\r\n            return None\r\n        res = SimpleNamespace()\r\n        # the meta data\r\n        res.parameter = self.parameter\r\n        res.options = self.options\r\n        res.logging = self.logging\r\n        res.measurement = self.measurement\r\n        # store the retriever itself\r\n        if full:\r\n            res.pnps = self.pnps\r\n        else:\r\n            res.pnps = None\r\n\r\n        # the pulse spectra\r\n        # 1 - the retrieved pulse\r\n        res.pulse_retrieved = self._result.spectrum\r\n        # 2 - the original test pulse, optional\r\n        res.pulse_original = pulse_original\r\n        # 3 - the initial guess\r\n        res.pulse_initial = self.initial_guess\r\n\r\n        # the measurement traces\r\n        # 1 - the original data used for retrieval\r\n        res.trace_input = self.Tmn_meas\r\n        # 2 - the trace error and the trace calculated from the retrieved pulse\r\n        res.trace_error = self.trace_error(res.pulse_retrieved)\r\n        res.trace_retrieved = rs.mu * rs.Tmn\r\n        res.response_function = rs.mu\r\n        # the weights\r\n        res.weights = self._weights\r\n\r\n        # this is set if the original spectrum is provided\r\n        if res.pulse_original is not None:\r\n            # the trace error of the test pulse (non-zero for noisy input)\r\n            res.trace_error_optimal = self.trace_error(res.pulse_original)\r\n            # 3 - the optimal trace calculated from the test pulse\r\n            res.trace_original = rs.mu * rs.Tmn\r\n            dot_ambiguity = False\r\n            if self.pnps.method == \"ifrog\" or self.pnps.scheme == \"shg-frog\":\r\n                dot_ambiguity = True\r\n            # the pulse error to the test pulse\r\n            res.pulse_error, res.pulse_retrieved = pulse_error(\r\n                    res.pulse_retrieved, res.pulse_original, self.ft,\r\n                    dot_ambiguity=dot_ambiguity)\r\n\r\n        if res.logging:\r\n            # the logged trace errors\r\n            res.trace_errors = np.array(self.log.trace_error)\r\n            # the running minimum of the trace errors (for plotting)\r\n            res.rm_trace_errors = np.minimum.accumulate(res.trace_errors,\r\n                                                        axis=-1)\r\n        if self.verbose:\r\n            lib.retrieval_report(res)\r\n        return res\r\n\r\n\r\ndef Retriever(pnps: BasePNPS, method: str = \"copra\", maxiter=300, maxfev=None,\r\n              logging=False, verbose=False, **kwargs) -> BaseRetriever:\r\n    \"\"\" Creates a retriever instance.\r\n\r\n    Parameters\r\n    ----------\r\n    pnps : PNPS\r\n        A PNPS instance that is used to simulate a PNPS measurement.\r\n    method : str, optional\r\n        Type of solver.  Should be one of\r\n            - 'copra'       :class:`(see here) <COPRARetriever>`\r\n            - 'gpa'         :class:`(see here) <GPARetriever>`\r\n            - 'gp-dscan'     :class:`(see here) <GPDSCANRetriever>`\r\n            - 'pcgpa'       :class:`(see here) <PCGPARetriever>`\r\n            - 'pie'         :class:`(see here) <PIERetriever>`\r\n            - 'lm'          :class:`(see here) <LMRetriever>`\r\n            - 'bfgs'        :class:`(see here) <BFGSRetriever>`\r\n            - 'de'          :class:`(see here) <DERetriever>`\r\n            - 'nelder-mead' :class:`(see here) <NMRetriever>`\r\n\r\n        'copra' is the default choice.\r\n    maxiter : int, optional\r\n        The maximum number of algorithm iterations. The default is 300.\r\n    maxfev : int, optional\r\n        The maximum number of function evaluations. If given, the algorithms\r\n        stop before this number is reached. Not all algorithms support this\r\n        feature. Default is ``None``, in which case it is ignored.\r\n    logging : bool, optional\r\n        Stores trace errors and pulses over the iterations if supported\r\n        by the retriever class. Default is `False`.\r\n    verbose : bool, optional\r\n        Prints out trace errors during the iteration if supported by the\r\n        retriever class. Default is `False`.\r\n    \"\"\"\r\n    method = method.lower()\r\n    try:\r\n        cls = _RETRIEVER_CLASSES[method]\r\n    except KeyError:\r\n        raise ValueError(\"Retriever '%s' is unknown!\" % (method))\r\n    return cls(pnps, maxiter=maxiter, maxfev=maxfev,\r\n               logging=logging, verbose=verbose, **kwargs)\r\n", "meta": {"hexsha": "d486804a554d435cc7821c231874793ca816080f", "size": 13072, "ext": "py", "lang": "Python", "max_stars_repo_path": "pypret/retrieval/retriever.py", "max_stars_repo_name": "liam-clink/pypret", "max_stars_repo_head_hexsha": "c84e954efc12137c6b5ade4fae920d60a15d4875", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pypret/retrieval/retriever.py", "max_issues_repo_name": "liam-clink/pypret", "max_issues_repo_head_hexsha": "c84e954efc12137c6b5ade4fae920d60a15d4875", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pypret/retrieval/retriever.py", "max_forks_repo_name": "liam-clink/pypret", "max_forks_repo_head_hexsha": "c84e954efc12137c6b5ade4fae920d60a15d4875", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9755351682, "max_line_length": 80, "alphanum_fraction": 0.5738219094, "include": true, "reason": "import numpy", "num_tokens": 2906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19953807839114812}}
{"text": "\"\"\"\nPython Navigation Abstract Class\n@Author: Kristian Gibson\nTODO: Comments + Sphynx Docs Structured Text\nTODO: Bug-fix, testing\n\n\"\"\"\n\nfrom abc import ABC\nfrom scipy import integrate\nfrom scipy.ndimage import interpolation\nfrom spatialmath.base.transforms2d import *\nfrom spatialmath.base.vectors import *\nfrom spatialmath import SE2, SE3\nfrom matplotlib import cm\nfrom abc import ABC, abstractmethod\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport copy\nfrom roboticstoolbox.mobile.OccGrid import BaseOccupancyGrid, BinaryOccupancyGrid\nfrom roboticstoolbox.mobile.Animations import VehiclePolygon\nfrom colored import fg, attr\n\ntry:\n    from progress.bar import FillingCirclesBar\n    _progress = True\nexcept:\n    _progress = False\n\nclass PlannerBase(ABC):\n    r\"\"\"\n    Mobile robot motion planner (superclass)\n\n    :param occgrid: occupancy grid, defaults to None\n    :type occgrid: :class:`OccGrid` instance of ndarray(N,M), optional\n    :param start: start position :math:`(x, y)` or configuration :math:`(x, y, \\theta)`, defaults to None\n    :type start: array_like(2) or array_like(3), optional\n    :param goal: goal position :math:`(x, y)` or configuration :math:`(x, y, \\theta)`, defaults to None\n    :type goal: array_like(2) or array_like(3), optional\n    :param inflate: obstacle inflation, defaults to 0\n    :type inflate: float, optional\n    :param ndims: dimensionality of the planning, either 2 for :math:`\\mathbb{R}^2` or \n        3 for :math:`\\SE{2}`\n    :param ndims: int, optional\n    :param verbose: verbosity, defaults to False\n    :type verbose: bool, optional\n    :param msgcolor: color for message channel printing\n    :type msgcolor: str, defaults to yellow\n    :param seed: seed provided to private random number generator, defaults to None\n    :type seed: int, optional\n\n    Superclass for all mobile robot motion planners.  Key functionality\n    includes:\n\n    - encapsulates an occupancy grid and optionally inflates it\n    - encapsulates a private random number generator with specifiable seed\n    - encapsulates state such as start, goal, and the plan\n    - provides a message channel for diagnostic output\n\n    :seealso: :class:`OccGrid`\n    \"\"\"\n\n    def __init__(self, occgrid=None, inflate=0, ndims=None,\n                 verbose=False, msgcolor='yellow', \n                 progress=True, marker=None, seed=None, **unused):\n\n        self._occgrid = None\n        if ndims is None:\n            raise ValueError('ndims must be specified')\n        self._ndims = ndims\n        self._verbose = verbose\n        self._msgcolor = msgcolor\n        self._seed = seed\n        self._private_random = np.random.default_rng(seed=seed)\n        self._inflate = inflate\n        self._start = None\n        self._goal = None\n\n        self._progress = progress and _progress\n\n        self.marker = marker\n\n        if occgrid is not None:\n            if not isinstance(occgrid, BaseOccupancyGrid):\n                occgrid = BinaryOccupancyGrid(occgrid)\n            self._occgrid0 = occgrid  # original occgrid for reference\n\n            if inflate > 0:\n                self._occgrid = occgrid.copy()\n                self._occgrid.inflate(inflate)\n            else:\n                self._occgrid = occgrid\n\n    def __str__(self):\n        \"\"\"\n        Compact representation of the planner\n\n        :return: pretty printed representation\n        :rtype: str\n        \"\"\"\n        s = f\"{self.__class__.__name__}: \"\n        if self._occgrid0 is not None:\n            s += str(self.occgrid)\n        if self._start is not None:\n            s += f\"\\n  Start: {self.start}\"\n        if self._goal is not None:\n            s += f\"\\n  Goal: {self.goal}\"\n        return s\n\n    def __repr__(self):\n        return str(self)\n\n    @property\n    def occgrid(self):\n        \"\"\"\n        Occupancy grid\n\n        :return: occupancy grid used for planning\n        :rtype: :class:`OccGrid` instance or None\n\n        Returns the grid that was optionally inflated at constructor time.\n\n        :seealso: :class:`OccGrid`\n        \"\"\"\n        return self._occgrid\n\n    @property\n    def start(self):\n        r\"\"\"\n        Start point or configuration used for planning\n\n        :return: start point :math:`(x, y)` or configuration :math:`(x, y, \\theta)`\n        :rtype: ndarray(2) or ndarray(3)\n        \"\"\"\n        return self._start\n\n    @start.setter\n    def start(self, start):\n        r\"\"\"\n        Set start point or configuration for planning\n\n        :param start: Set start :math:`(x, y)` or configuration :math:`(x, y, \\theta)`\n        :type start: array_like(2) or array_like(3)\n        :raises ValueError: if start point is occupied\n        \"\"\"\n        if start is not None:\n            if self.isoccupied(start):\n                raise ValueError(\"Start location inside obstacle\")\n            self._start = base.getvector(start)\n\n    @property\n    def goal(self):\n        r\"\"\"\n        Goal point or configuration used for planning\n\n        :return: goal point :math:`(x, y)` or configuration :math:`(x, y, \\theta)`\n        :rtype: ndarray(2) or ndarray(3)\n        \"\"\"\n        return self._goal\n\n    @goal.setter\n    def goal(self, goal):\n        r\"\"\"\n        Set goal point or configuration for planning\n\n        :param goal: Set goal :math:`(x, y)` or configuration :math:`(x, y, \\theta)`\n        :type goal: array_like(2) or array_like(3)\n        :raises ValueError: if goal point is occupied\n        \"\"\"\n        if goal is not None:\n            if self.isoccupied(goal):\n                raise ValueError(\"Goal location inside obstacle\")\n            self._goal = base.getvector(goal)\n\n    def isoccupied(self, p):\n        \"\"\"\n        Test if point is occupied\n\n        :param p: world coordinate (x, y)\n        :type p: array_like(2)\n        :return: occupancy status of corresponding grid cell\n        :rtype: bool\n\n        The world coordinate is transformed and the status of the occupancy\n        grid cell is returned.  If the point lies outside the bounds of\n        the occupancy grid return True (obstacle)\n\n        If there is no occupancy grid this function always returns False (free).\n\n        :seealso: :meth:`OccGrid.isoccupied`\n        \"\"\"\n        if self.occgrid is None:\n            return False\n        else:\n            return self.occgrid.isoccupied(p)\n\n    @property\n    def verbose(self):\n        \"\"\"\n        Get verbosity\n\n        :return: verbosity\n        :rtype: bool\n\n        If ``verbosity`` print more diagnostic messages to the planner's\n        message channel.\n        \"\"\"\n        return self._verbose\n\n    @verbose.setter\n    def verbose(self, v):\n        \"\"\"\n        Set verbosity\n\n        :param v: verbosity\n        :type v: bool\n\n        If ``verbosity`` print more diagnostic messages to the planner's\n        message channel.\n        \"\"\"\n        self._verbose = v\n\n    @property\n    def random(self):\n        \"\"\"\n        Private random number generator\n\n        :return: random number generator\n        :rtype: NumPy Generator\n\n        For example::\n\n            planner.random(size, dtype)\n            planner.integers(low, high, size, dtype)\n            planner.uniform(0, 5)\n       \n        :seealso: `Random Generator <https://numpy.org/doc/stable/reference/random/generator.html>`_\n        \"\"\"\n        return self._private_random\n\n    def randinit(self):\n        if self._seed is not None:\n            self._private_random = np.random.default_rng(seed=self._seed)\n\n    # Define abstract classes to be implemented later\n    def plan(self):\n        r\"\"\"\n        Plan path (abstract superclass)\n\n        :param start: start position :math:`(x, y)` or configuration :math:`(x, y, \\theta)`, defaults to None\n        :type start: array_like(2) or array_like(3), optional\n        :param goal: goal position :math:`(x, y)` or configuration :math:`(x, y, \\theta)`, defaults to None\n        :type goal: array_like(2) or array_like(3), optional\n\n        The implementation depends on the particular planner.  Some may have\n        no planning phase.  The plan may also depend on just the start or goal.\n        \"\"\"\n        pass\n\n    def validate_endpoint(self, p, dtype=None):\n        if p is not None:\n            p = base.getvector(p, self._ndims, dtype=dtype)\n            if self.isoccupied(p):\n                raise ValueError(\"Point is inside obstacle\")\n        return p\n\n    def progress_start(self, n):\n        self._bar = FillingCirclesBar(self.__class__.__name__, max=n, \n            suffix = '%(percent).1f%% - %(eta)ds')\n\n    def progress_next(self):\n        self._bar.next()\n\n    def progress_end(self):\n        self._bar.finish()\n\n    def query(self, start=None, goal=None, dtype=None, next=True, animate=False, movie=None):\n        \"\"\"\n        Find a path from start to goal using plan (superclass)\n\n        :param start: start position :math:`(x, y)` or configuration :math:`(x, y, \\theta)`, defaults to None\n        :type start: array_like(2) or array_like(3), optional\n        :param goal: goal position :math:`(x, y)` or configuration :math:`(x, y, \\theta)`, defaults to None\n        :type goal: array_like(2) or array_like(3), optional\n        :param animate: show the vehicle path, defaults to False\n        :type animate: bool, optional\n        :return: path from start to goal, one point :math:`(x, y)` or configuration :math:`(x, y, \\theta)` per row\n        :rtype: ndarray(N,2) or ndarray(N,3)\n\n        Find a path from ``start`` to ``goal`` using a previously computed plan.\n        \n        The method performs the following steps:\n        - Initialize navigation, invoke method N.navigate_init()\n        - Visualize the environment, invoke method N.plot()\n        - Iterate on the ``next()`` method of the subclass until the ``goal`` is\n          achieved.\n        \"\"\"\n        # make sure start and goal are set and valid\n        self.start = self.validate_endpoint(start, dtype=dtype)\n        self.goal = self.validate_endpoint(goal, dtype=dtype)\n\n        # if movie is not None:\n        #     animate = True\n\n        if next:\n            if animate:\n                self.plot()\n\n            # movie = MovieWriter(movie)\n\n            robot = self._start\n            path = [robot]\n\n            while True:\n                if animate:\n                    plt.plot(robot[0], robot[1], 'y.', 12)\n                    plt.pause(0.05)\n\n                # get next point on the path\n                robot = self.next(robot)\n\n                # are we are done?\n                if robot is None:\n                    path.append(self._goal)\n                    return np.array(path).astype(int)\n\n                path.append(robot)\n\n    def plot(self, path=None,\n            style='striped', stripe=(('black', 4), ('yellow', 3)),\n            stripe_r=(('black', 4), ('red', 3)),\n            line=None, line_r=None,\n            configspace=False, unwrap=True,\n            direction=None, background=True,\n            path_marker=None, path_marker_reverse=None,\n            start_marker=None, goal_marker=None,\n            start_vehicle=None, goal_vehicle=None,\n            start=None, goal=None,\n            ax=None, block=False, **kwargs):\n        r\"\"\"\n        Plot vehicle path\n\n        :param path: path, defaults to None\n        :type path: ndarray(N, 2) or ndarray(N, 3)\n        :param style: line style: 'striped' [default] or 'line'\n        :type style: str\n        :param stripe: striped line style for forward motion\n        :type stripe: tuple of (color, linewidth)\n        :param stripe_r: striped line style for reverse motion\n        :type stripe: tuple of (color, linewidth)\n        :param line: plain line style for forward motion\n        :type line: dict of arguments for ``plot``\n        :param line_r: plain line style for forward motion\n        :type line_r: dict of arguments for ``plot``\n        :param direction: travel direction associated with each point on path, is either >0 or <0, defaults to None\n        :type direction: ndarray(N,), optional\n        :param configspace: plot the path in 3D configuration space, input must be 3xN.  \n            Start and goal style will be given by ``qstart_marker`` and ``qgoal_marker``, defaults to False\n        :type configspace: bool, optional\n        :param unwrap: for configuration space plot unwrap :math:`\\theta` so\n            there are no discontinuities at :math:`\\pm \\pi`, defaults to True\n        :type unwrap: bool, optional\n        :param background: plot occupancy grid if present, default True\n        :type background: bool, optional\n        :param start_marker: style for marking start point\n        :type start_marker: dict, optional\n        :param goal_marker: style for marking goal point\n        :type goal_marker: dict, optional\n        :param start_vehicle: style for vehicle animation object at start configuration\n        :type start_vehicle: dict\n        :param goal_vehicle: style for vehicle animation object at goal configuration\n        :type goal_vehicle: dict\n        :param start: start position :math:`(x, y)` or configuration :math:`(x, y, \\theta)`, defaults to value used for ``plan/query``\n        :type start: array_like(2) or array_like(3), optional\n        :param goal: goal position :math:`(x, y)` or configuration :math:`(x, y, \\theta)`, defaults to value used for ``plan/query``\n        :type goal: array_like(2) or array_like(3), optional\n        :param ax: axes to plot into\n        :type ax: matplotlib axes\n        :param block: block after displaying the plot\n        :type block: bool, optional\n\n        The path has one column per point and either 2 or 3 rows:\n        \n        - 2 rows describes motion in the :math:`x-y` plane and a 2D plot  is created\n        - 3 rows describes motion in the :math:`x-y-\\theta` configuration space. By\n          default only the :math:`x-y` plane is plotted unless ``configspace``\n          is True in which case motion in :math:`x-y-\\theta` configuration space\n          is shown.\n\n        If the planner supports bi-directional motion then the ``direction``\n        option gives the direction for each point on the path.\n\n        The default line style is a ``'striped'`` line which comprises a wide first\n        line with a slightly narrow dashed line plotted on top.  For example::\n\n                (('black', 4), ('yellow', 3))\n\n        is a blackline of width 4 with a dashed yellow line of width 3 plotted\n        on top, giving a line of alternating black and yellow dashes.\n\n        The parameters ``stripe`` and ``stripe_r`` specify the colors and widths for\n        forward and reverse motion respectively.\n\n        The ``'line'`` style is a regular Matplotlib and the parameters \n        ``line`` and ``line_r`` specify the line and marker styles for\n        forward and reverse motion respectively.\n\n        For 2D plots with an :math:`x-y` path or 3D plots, the start and goal markers are specified\n        by the dicts ``start_marker`` and ``goal_marker`` respectively.\n\n        For 2D plots with an :math:`x-y-\\theta` path the vehicle pose\n        is indicated by a vehicle animation object passed to the constructor.\n\n        Markers are specified as dicts using Matplotlib keywords, for example::\n\n            planner.plot(path, path_marker=dict(marker='s', color='b'))\n\n        Default values are provided for all markers:\n\n            - the start point is a circle\n            - the goal point is a star\n            - the start vehicle style is a ``VehiclePolygon(shape='car')`` as\n              an unfilled outline\n            - the goal vehicle style is a ``VehiclePolygon(shape='car')`` as\n              a transparent filled shape\n    \n        If ``configspace`` is True then direction-indicating markers are used to\n        display start and goal configuration. These are also given as dicts but\n        have two items: ``'shape'`` which is the shape of the polygonal marker\n        and is either ``'triangle'`` or ``'car'``.  The second item ``'args'`` is\n        passed to :func:`base.plot_poly` and Matplotlib.\n\n        If ``background`` is True then the background of the plot is either or\n        both of:\n        \n        - the occupancy grid\n        - the distance field of the planner\n\n        Additional arguments are passed through to :meth:`plot_bg`\n\n        :seealso: :meth:`plot_bg` :func:`base.plot_poly`\n        \"\"\"\n        # create default markers\n        \n        # passed to Matplotlib plot()\n        if start_marker is None:\n            start_marker = {'marker': 'o',\n                            'markeredgecolor': 'w',\n                            'markerfacecolor': 'y', \n                            'markersize': 10,\n                            'zorder': 10,\n                           }\n        if goal_marker is None:\n            goal_marker = { 'marker': '*',\n                            'markeredgecolor': 'w',\n                            'markerfacecolor': 'y',\n                            'markersize': 16,\n                            'zorder': 10,\n                          }\n\n        # passed to VehiclePolygon\n        if start_vehicle is None:\n            start_vehicle = {'facecolor': 'none', 'edgecolor': 'k', 'linewidth': 2}\n\n        if goal_vehicle is None:\n            goal_vehicle = {'alpha': 0.5}\n\n        ndims = self._ndims\n\n        if ndims == 3 and not configspace:\n            ndims = 2\n            if path is not None:\n                path = path[:, :2]\n            \n\n        if configspace and ndims < 3 and path is not None:\n            raise ValueError(f\"path should have {ndims} rows\")\n                \n        ax = base.axes_logic(ax, ndims)\n\n        # plot occupancy grid background\n        if background:\n            self.plot_bg(ax=ax, **kwargs)\n        \n        # mark the path\n        if path is not None:\n            if ndims == 2:\n                # 2D case\n                if direction is not None:\n                    direction = np.array(direction)\n                    if direction.shape[0] != path.shape[0]:\n                        raise ValueError('direction vector must have same length as path')\n\n                    while len(direction) > 0:\n                        dir = direction[0]\n                        change = np.argwhere(dir != direction)\n                        if len(change) == 0:\n                            k = -1\n                        else:\n                            k = change[0, 0]\n                        \n                        if style == 'striped':\n                            if dir > 0:\n                                xstripe = stripe\n                            else:\n                                xstripe = stripe_r\n                            ax.plot(path[:k, 0], path[:k, 1], color=xstripe[0][0], linewidth=xstripe[0][1])\n                            ax.plot(path[:k, 0], path[:k, 1], color=xstripe[1][0], linewidth=xstripe[1][1], dashes=(5,5))\n                        elif style == 'line':\n                            if dir > 0:\n                                ax.plot(path[:, 0], path[:, 1], **line)\n                            else:\n                                ax.plot(path[:, 0], path[:, 1], **line_r)\n\n                        if len(change) == 0:\n                            break\n                        direction = direction[k-1:]\n                        direction[0] = direction[1]\n                        path = path[k-1:, :]\n\n                else:\n                    if style == 'striped':\n                        ax.plot(path[:, 0], path[:, 1], color=stripe[0][0], linewidth=stripe[0][1], zorder=9)\n                        ax.plot(path[:, 0], path[:, 1], color=stripe[1][0], linewidth=stripe[1][1], dashes=(5,5), zorder=9)\n                    elif style == 'line':\n                        ax.plot(path[:, 0], path[:, 1], **kwargs)\n            elif ndims == 3:\n                # 3D case\n                if direction is not None:\n                    direction = np.array(direction)\n                    if direction.shape[0] != path.shape[0]:\n                        raise ValueError('direction vector must have same length as path')\n                    theta = path[:, 2]\n                    if unwrap:\n                        theta = np.unwrap(theta)\n\n                    while len(direction) > 0:\n                        dir = direction[0]\n                        change = np.argwhere(dir != direction)\n                        if len(change) == 0:\n                            k = -1\n                        else:\n                            k = change[0, 0]\n                        \n\n                        if style == 'striped':\n                            if dir > 0:\n                                xstripe = stripe\n                            else:\n                                xstripe = stripe_r\n                            ax.plot(path[:k, 0], path[:k, 1], theta[:k], color=xstripe[0][0], linewidth=xstripe[0][1])\n                            ax.plot(path[:k, 0], path[:k, 1], theta[:k], color=xstripe[1][0], linewidth=xstripe[1][1], dashes=(5,5))\n                        elif style == 'line':\n                            if dir > 0:\n                                ax.plot(path[:, 0], path[:, 1], **line)\n                            else:\n                                ax.plot(path[:, 0], path[:, 1], **line_r)\n\n                        if len(change) == 0:\n                            break\n                        direction = direction[k-1:]\n                        direction[0] = direction[1]\n                        path = path[k-1:, :]\n                        theta = theta[k-1:]\n        \n                else:\n                    theta = path[:, 2]\n                    if unwrap:\n                        theta = np.unwrap(theta)\n                    if style == 'striped':\n                        ax.plot(path[:, 0], path[:, 1], theta, color=stripe[0][0], linewidth=stripe[0][1])\n                        ax.plot(path[:, 0], path[:, 1], theta, color=stripe[1][0], linewidth=stripe[1][1], dashes=(5,5))\n                    elif style == 'line':\n                        ax.plot(path[:, 0], path[:, 1], **line)\n\n        # mark start and goal if requested\n        if start is not None:\n            start = self.validate_endpoint(start)\n        else:\n            start = self.start\n        if goal is not None:\n            self.goal = self.validate_endpoint(goal)\n        else:\n            goal = self.goal\n\n        if ndims == 2 and self._ndims == 2:\n            # proper 2d plot\n            if start is not None:\n                ax.plot(start[0], start[1], **start_marker)\n            if goal is not None:\n                ax.plot(goal[0], goal[1], **goal_marker)\n        \n        elif ndims == 2 and self._ndims == 3:\n            # 2d projection of 3d plot, show start/goal configuration\n            scale = base.axes_get_scale(ax) / 10\n            \n            if self.marker is None:\n                self.marker = VehiclePolygon(shape='car', scale=scale)\n\n            if start is not None:\n                self.marker.plot(start, **start_vehicle)\n            if goal is not None:\n                self.marker.plot(goal, **goal_vehicle)\n\n        elif ndims == 3:\n            # 3d plot\n\n            if start is not None:\n                ax.plot(start[0], start[1], start[2], **start_marker)\n            if goal is not None:\n                \n                if path is not None and unwrap:\n                    theta = theta[-1]\n                else:\n                    theta = goal[2]\n                plt.plot(goal[0], goal[1], theta, **goal_marker)\n\n        ax.set_xlabel('x')\n        ax.set_ylabel('y')\n        if ndims == 2:\n            ax.set_aspect('equal')\n        else:\n            ax.set_zlabel(r'$\\theta$')\n\n        plt.show(block=block)\n\n        return ax\n\n    def _qmarker(self, shape):\n        h = 0.3\n        t = 0.8  # start of head taper\n        c = 0.5  # centre x coordinate\n        w = 1    # width in x direction\n        if shape == 'car':\n            return np.array([\n                [-c,     h],\n                [t - c,  h],\n                [w - c,  0],\n                [t - c, -h],\n                [-c,    -h],\n            ]).T\n        elif shape == 'triangle':\n            return np.array([\n                [-c,  h],\n                [ w,  0],\n                [-c, -h],\n                [-c,  h],\n            ]).T\n\n    def plot_bg(self, distance=None, cmap='gray',\n                ax=None, inflated=True,  **unused):\n        \"\"\"\n        Plot background\n\n        :param distance: override distance field, defaults to None\n        :type distance: ndarray(N,M), optional\n        :param cmap: Specify a colormap for the distance field, defaults to 'gray'\n        :type cmap: str or Colormap, optional\n\n        Displays the background which is either the occupancy grid or a distance\n        field.  The distance field encodes the distance of a point from the goal, small\n        distance is dark, a large distance is bright.\n\n        If the planner has an occupancy grid then that will be displayed with:\n            - free cells in white\n            - occupied cells in red\n            - inflated occupied cells in pink\n\n        If distance is provided, or the planner has a distancemap attribute\n        the the distance field will be used as the background and obstacle cells\n        (actual or inflated) will be shown in red. A colorbar is added.\n        \"\"\"\n        if self._occgrid is None:\n            return\n\n        if isinstance(self._occgrid, BaseOccupancyGrid):\n            ax = base.plotvol2(dim=self._occgrid.workspace, ax=ax)\n        else:\n            ax = base.axes_logic(ax, 2)\n\n        # create color map for free space + obstacle:\n        #   free space, color index = 1, white, alpha=0 to allow background and grid lines to show\n        #   obstacle, color index = 2, red, alpha=1\n\n        if self._inflate > 0 and inflated:\n            # 0 background (white, transparent)\n            # 1 inflated obstacle (pink)\n            # 2 original obstacle (red)\n            colors = [(1, 1, 1, 0), (1, 0.75, 0.8, 1), (1, 0, 0, 1)]\n            image = self.occgrid.grid.astype(int) + self._occgrid0.grid.astype(int)\n        else:\n            # 0 background\n            # 1 obstacle\n            colors = [(1, 1, 1, 0), (1, 0, 0, 1)]\n            image = self.occgrid.grid\n\n        if distance is None and hasattr(self, 'distancemap'):\n            distance = self.distancemap\n\n        if distance is not None:\n            # distance field with obstacles\n\n            # find largest finite value\n\n            v = distance.ravel()\n            vmax = max(v[np.isfinite(v)])\n\n            # create a copy of greyscale color map\n            c_map = copy.copy(mpl.cm.get_cmap(cmap))\n            # c_map.set_bad(color=(1,0,0,1))  # nan and inf are red\n\n            # change all inf to large value, so they are not 'bad' ie. red\n            distance[np.isinf(distance)] = 2 * vmax\n            c_map.set_over(color=(0,0,1))  # ex-infs are now blue\n\n            # display image\n            norm = mpl.colors.Normalize(vmin=0, vmax=vmax, clip=False)\n            ax.imshow(distance, origin='lower',\n                interpolation=None,\n                cmap=c_map,\n                norm=norm,\n                )\n            ax.grid(True, alpha=0.1, color=(1,1,1))\n\n            # add colorbar\n            scalar_mappable_c_map = cm.ScalarMappable(cmap=c_map, norm=norm)\n            plt.colorbar(scalar_mappable_c_map, label='Distance', shrink=0.7, aspect=20*0.7)\n\n            # overlay obstacles\n            c_map = mpl.colors.ListedColormap(colors)\n            self.occgrid.plot(image, cmap=c_map, zorder=1)\n\n        else:\n            # occupancy grid only\n\n            # overlay obstacles\n            c_map = mpl.colors.ListedColormap(colors)\n            self.occgrid.plot(image, cmap=c_map, zorder=1)\n        \n        ax.set_facecolor((1, 1, 1)) # create white background\n        ax.set_xlabel('x (cells)')\n        ax.set_ylabel('y (cells)')\n        ax.grid(True, zorder=0)\n\n        # lock axis limits to current value\n        # ax.set_xlim(ax.get_xlim())\n        # ax.set_ylim(ax.get_ylim())\n\n        plt.draw()\n        plt.show(block=False)\n\n\n    def message(self, s, color=None):\n        \"\"\"\n        Print message to message channel\n\n        :param s: message to print\n        :type s: str\n        :param color: color to print it, defaults to color specified at\n            constructor time.\n        :type color: str, optional\n\n        \"\"\"\n        if self.verbose:\n            if color is None:\n                color = self._msgcolor\n            print(fg(color), \"Planner:: \" + s, attr(0))\n\n    # @staticmethod\n    # def show_distance(d):\n    #     d[np.isinf(d)] = None\n    #     ax = plt.gca()\n    #     c_map = plt.get_cmap(\"Greys\")\n    #     plt.clim(0, np.max(d[:]))\n    #     plt.figimage(d)\n    #     plt.xlabel('X')\n    #     plt.ylabel('Y')\n    #     plt.show()\n\nclass MovieWriter:\n\n    def __init__(self, filename=None, interval=0.1, fig=None):\n        \"\"\"\n        Save animation as a movie file\n\n        :param filename: name of movie file, or tuple containing filename and\n            frame interval\n        :type filename: str or tuple(str, float)\n        :param interval: frame interval, defaults to 0.1\n        :type interval: float, optional\n        :param fig: figure to record for the movie\n        :type fig: figure reference \n\n        Example::\n\n            movie = MovieWriter(filename)\n\n            while ...\n                movie.add()\n\n            movie.done()\n\n        To avoid extra user-logic, if ``MovieWriter`` is called with ``filename`` equal to None,\n        then the writer will do nothing when the ``add`` and ``done`` methods are called.\n        \"\"\"\n        # Set up formatting for the movie files\n        if filename is None:\n            self.writer = None\n            return\n\n        if isinstance(filename, (tuple, list)):\n            filename, interval = filename\n\n        if os.path.exists(filename):\n            print(\"overwriting movie\", filename)\n        else:\n            print(\"creating movie\", filename)\n        self.writer = animation.FFMpegWriter(\n            fps=round(1 / interval), extra_args=[\"-vcodec\", \"libx264\"]\n        )\n        if fig is None:\n            fig = plt.gcf()\n        self.writer.setup(fig, filename)\n        self.filename = filename\n\n    def add(self):\n        \"\"\"\n        Add frame to the movie\n        \"\"\"\n        if self.writer is not None:\n            self.writer.grab_frame()\n\n    def done(self):\n        if self.writer is not None:\n            self.writer.finish()\n            self.writer = None\n", "meta": {"hexsha": "6fdacf1c399be934851893567210f462b64e77a7", "size": 30445, "ext": "py", "lang": "Python", "max_stars_repo_path": "roboticstoolbox/mobile/PlannerBase.py", "max_stars_repo_name": "tassos/robotics-toolbox-python", "max_stars_repo_head_hexsha": "51aa8bbb3663a7c815f9880d538d61e7c85bc470", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 749, "max_stars_repo_stars_event_min_datetime": "2015-04-28T03:02:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:55:12.000Z", "max_issues_repo_path": "roboticstoolbox/mobile/PlannerBase.py", "max_issues_repo_name": "tassos/robotics-toolbox-python", "max_issues_repo_head_hexsha": "51aa8bbb3663a7c815f9880d538d61e7c85bc470", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 226, "max_issues_repo_issues_event_min_datetime": "2015-04-16T22:22:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T16:42:28.000Z", "max_forks_repo_path": "roboticstoolbox/mobile/PlannerBase.py", "max_forks_repo_name": "tassos/robotics-toolbox-python", "max_forks_repo_head_hexsha": "51aa8bbb3663a7c815f9880d538d61e7c85bc470", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 251, "max_forks_repo_forks_event_min_datetime": "2015-04-30T23:52:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T13:32:16.000Z", "avg_line_length": 36.3739545998, "max_line_length": 134, "alphanum_fraction": 0.5435046806, "include": true, "reason": "from scipy", "num_tokens": 6978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3812195521959383, "lm_q1q2_score": 0.19953807103174723}}
{"text": "\nimport numpy as np\nfrom scipy.interpolate import interp1d\n\nfrom .. import constants as c\nfrom . import scatmodels as sms\nfrom ..distlib.composition import cmindex as cmi\nfrom .. import distlib\n\n__all__ = ['ScatModel','DiffScat','SigmaExt','SigmaScat','KappaExt','KappaScat']\n\n#----------------------------------------------------------\n# evals( emin=1.0, emax=2.0, de=0.1 ) : np.array [keV]\n# angles( thmin=5.0, thmax=100.0, dth=5.0 ) : np.array [arcsec]\n#\n\ndef evals( emin=1.0, emax=2.0, de=0.1 ):\n    \"\"\"\n    FUNCTION evals( emin=1.0, emax=2.0, de=0.1 )\n    RETURNS : np.array\n    Distribution of energies [keV]\n    \"\"\"\n    return np.arange( emin, emax+de, de )\n\ndef angles( thmin=5.0, thmax=100.0, dth=5.0 ):\n    \"\"\"\n    FUNCTION angles( thmin=5.0, thmax=100.0, dth=5.0 )\n    RETURNS : np.array\n    Distribution of angles [arcsec]\n    \"\"\"\n    return np.arange( thmin, thmax+dth, dth )\n\n#-------------- Tie scattering mechanism to an index of refraction ------------------\n\nclass ScatModel(object):\n    \"\"\"\n    | **ATTRIBUTES**\n    | smodel : scattering model object : RGscat(), Mie()\n    | cmodel : cmindex object : CmDrude(), CmGraphite(), CmSilicate()\n    | stype  : string : 'RGscat', 'Mie'\n    | cmtype : 'Drude', 'Silicate', 'Graphite'\n    \"\"\"\n    def __init__( self, smodel=sms.RGscat(), cmodel=cmi.CmDrude() ):\n        self.smodel = smodel\n        self.cmodel = cmodel\n        self.stype  = smodel.stype\n        self.cmtype = cmodel.cmtype\n        # cmtype choices : 'Drude' (requires rho term only)\n        #                  'Graphite' (Carbonaceous grains)\n        #                  'Silicate' (Astrosilicate)\n        #                  --- Graphite and Silicate values come from Draine (2003)\n\n#-------------- Quickly make a common ScatModel object ---------------------------\n\ndef makeScatModel( model_name, material_name ):\n    \"\"\"\n    | **INPUTS**\n    | model_name    : string : 'RG' or 'Mie'\n    | material_name : string : 'Drude', 'Silicate', 'Graphite', 'SmallGraphite'\n    |\n    | **RETURNS**\n    | ScatModel object\n    \"\"\"\n\n    if model_name == 'RG':\n        sm = sms.RGscat()\n    elif model_name == 'Mie':\n        sm = sms.Mie()\n    else:\n        print('Error: Model name not recognized')\n        return\n\n    if material_name == 'Drude':\n        cm = cmi.CmDrude()\n    elif material_name == 'Silicate':\n        cm = cmi.CmSilicate()\n    elif material_name == 'Graphite':\n        cm = cmi.CmGraphite()\n    elif material_name == 'SmallGraphite': # Small Graphite ~ 0.01 um\n        cm = cmi.CmGraphite( size='small' )\n    else:\n        print('Error: CM name not recognized')\n        return\n\n    return ScatModel(sm, cm)\n\n\n#-------------- Various Types of Scattering Cross-sections -----------------------\n\nclass DiffScat(object):\n    \"\"\"\n    | A differential scattering cross-section [cm^2 ster^-1] integrated\n    | over dust grain size distribution\n    |\n    | **ATTRIBUTES**\n    | scatm : ScatModel\n    | theta : np.array : arcsec\n    | E     : scalar or np.array : Note, must match number of theta values if size > 1\n    | a     : scalar : um\n    | dsig  : np.array : cm^2 ster^-1\n    \"\"\"\n    def __init__(self, scatm=ScatModel(), theta=angles(), E=1.0, a=1.0):\n        self.scatm  = scatm\n        self.theta  = theta\n        self.E      = E\n        self.a      = a\n\n        cm   = scatm.cmodel\n        scat = scatm.smodel\n        # Do not print citation here, because this function is called multiple times by other modules\n\n        if cm.cmtype == 'Graphite':\n            dsig_pe = scat.Diff(theta=theta, a=a, E=E, cm=cmi.CmGraphite(size=cm.size, orient='perp'))\n            dsig_pa = scat.Diff(theta=theta, a=a, E=E, cm=cmi.CmGraphite(size=cm.size, orient='para'))\n            self.dsig = (dsig_pa + 2.0 * dsig_pe) / 3.0\n        else:\n            self.dsig   = scat.Diff(theta=theta, a=a, E=E, cm=cm)\n\nclass SigmaScat(object):\n    \"\"\"\n    | Total scattering cross-section [cm^2] integrated over a dust grain\n    | size distribution\n    |\n    | **ATTRIBUTES**\n    | scatm : ScatModel\n    | E     : scalar or np.array : keV\n    | a     : scalar : um\n    | qsca  : scalar or np.array : unitless scattering efficiency\n    | sigma : scalar or np.array : cm^2\n    \"\"\"\n    def __init__(self, scatm=ScatModel(), E=1.0, a=1.0):\n        self.scatm  = scatm\n        self.E      = E\n        self.a      = a\n\n        cm   = scatm.cmodel\n        scat = scatm.smodel\n        print(cm.citation)\n\n        cgeo  = np.pi * np.power(a*c.micron2cm, 2)\n\n        if cm.cmtype == 'Graphite':\n            qsca_pe = scat.Qsca(a=a, E=E, cm=cmi.CmGraphite(size=cm.size, orient='perp'))\n            qsca_pa = scat.Qsca(a=a, E=E, cm=cmi.CmGraphite(size=cm.size, orient='para'))\n            self.qsca = (qsca_pa + 2.0*qsca_pe) / 3.0\n        else:\n            self.qsca = scat.Qsca(a=a, E=E, cm=cm)\n\n        self.sigma = self.qsca * cgeo\n\nclass SigmaExt(object):\n    \"\"\"\n    | Total EXTINCTION cross-section [cm^2] integrated over a dust grain\n    | size distribution\n    |\n    | **ATTRIBUTES**\n    | scatm : ScatModel\n    | E     : scalar or np.array : keV\n    | a     : scalar : um\n    | qext  : scalar or np.array : unitless extinction efficiency\n    | sigma : scalar or np.array : cm^2\n    \"\"\"\n    def __init__(self, scatm=ScatModel(), E=1.0, a=1.0):\n        self.scatm  = scatm\n        self.E      = E\n        self.a      = a\n\n        if scatm.stype == 'RGscat':\n            print('Rayleigh-Gans cross-section not currently supported for KappaExt')\n            self.qext = None\n            self.sigma = None\n            return\n\n        cm   = scatm.cmodel\n        scat = scatm.smodel\n        print(cm.citation)\n\n        cgeo  = np.pi * np.power(a*c.micron2cm, 2)\n        if cm.cmtype == 'Graphite':\n            qext_pe = scat.Qext(a=a, E=E, cm=cmi.CmGraphite(size=cm.size, orient='perp'))\n            qext_pa = scat.Qext(a=a, E=E, cm=cmi.CmGraphite(size=cm.size, orient='para'))\n            self.qext = (qext_pa + 2.0*qext_pe) / 3.0\n        else:\n            self.qext = scat.Qext(a=a, E=E, cm=cm)\n        self.sigma = self.qext * cgeo\n\nclass KappaScat(object):\n    \"\"\"\n    | Opacity to scattering [g^-1 cm^2] integrated over dust grain size distribution.\n    |\n    | **ATTRIBUTES**\n    | scatm : ScatModel\n    | E     : scalar or np.array : keV\n    | dist  : distlib.DustSpectrum\n    | kappa : scalar or np.array : cm^2 g^-1, typically\n    \"\"\"\n    def __init__(self, E=1.0, scatm=ScatModel(), dist=distlib.MRN_dist()):\n        self.scatm  = scatm\n        self.E      = E\n        self.dist   = dist\n\n        cm   = scatm.cmodel\n        scat = scatm.smodel\n        print(cm.citation)\n\n        cgeo = np.pi * np.power(dist.a * c.micron2cm, 2)\n\n        qsca    = np.zeros(shape=(np.size(E),np.size(dist.a)))\n        qsca_pe = np.zeros(shape=(np.size(E),np.size(dist.a)))\n        qsca_pa = np.zeros(shape=(np.size(E),np.size(dist.a)))\n\n        # Test for graphite case\n        if cm.cmtype == 'Graphite':\n            cmGraphitePerp = cmi.CmGraphite(size=cm.size, orient='perp')\n            cmGraphitePara = cmi.CmGraphite(size=cm.size, orient='para')\n\n            if np.size(dist.a) > 1:\n                for i in range(np.size(dist.a)):\n                    qsca_pe[:,i] = scat.Qsca(E, a=dist.a[i], cm=cmGraphitePerp)\n                    qsca_pa[:,i] = scat.Qsca(E, a=dist.a[i], cm=cmGraphitePara)\n            else:\n                qsca_pe = scat.Qsca(E, a=dist.a, cm=cmGraphitePerp)\n                qsca_pa = scat.Qsca(E, a=dist.a, cm=cmGraphitePara)\n\n            qsca    = (qsca_pa + 2.0 * qsca_pe) / 3.0\n\n        else:\n            if np.size(dist.a) > 1:\n                for i in range(np.size(dist.a)):\n                    qsca[:,i] = scat.Qsca(E, a=dist.a[i], cm=cm)\n            else:\n                qsca = scat.Qsca(E, a=dist.a, cm=cm)\n\n        if np.size(dist.a) == 1:\n            kappa = dist.nd * qsca * cgeo / dist.md\n        else:\n            kappa = np.array([])\n            for j in range(np.size(E)):\n                kappa = np.append(kappa,\n                                  c.intz(dist.a, dist.nd * qsca[j,:] * cgeo) / dist.md)\n\n        self.kappa = kappa\n\n\nclass KappaExt(object):\n    \"\"\"\n    | Opacity to EXTINCTION [g^-1 cm^2] integrated over dust grain size\n    | distribution\n    |\n    | **ATTRIBUTES**\n    | scatm : ScatModel\n    | E     : scalar or np.array : keV\n    | dist  : distlib.DustSpectrum\n    | kappa : scalar or np.array : cm^2 g^-1, typically\n    \"\"\"\n    def __init__(self, E=1.0, scatm=ScatModel(), dist=distlib.MRN_dist()):\n        self.scatm  = scatm\n        self.E      = E\n        self.dist   = dist\n\n        if scatm.stype == 'RGscat':\n            print 'Rayleigh-Gans cross-section not currently supported for KappaExt'\n            self.kappa = None\n            return\n\n        cm   = scatm.cmodel\n        scat = scatm.smodel\n        print(cm.citation)\n\n        cgeo = np.pi * np.power(dist.a * c.micron2cm, 2)\n\n        qext    = np.zeros(shape=(np.size(E),np.size(dist.a)))\n        qext_pe = np.zeros(shape=(np.size(E),np.size(dist.a)))\n        qext_pa = np.zeros(shape=(np.size(E),np.size(dist.a)))\n\n        # Test for graphite case\n        if cm.cmtype == 'Graphite':\n            cmGraphitePerp = cmi.CmGraphite(size=cm.size, orient='perp')\n            cmGraphitePara = cmi.CmGraphite(size=cm.size, orient='para')\n\n            if np.size(dist.a) > 1:\n                for i in range(np.size(dist.a)):\n                    qext_pe[:,i] = scat.Qext(E, a=dist.a[i], cm=cmGraphitePerp)\n                    qext_pa[:,i] = scat.Qext(E, a=dist.a[i], cm=cmGraphitePara)\n            else:\n                qext_pe = scat.Qext(E, a=dist.a, cm=cmGraphitePerp)\n                qext_pa = scat.Qext(E, a=dist.a, cm=cmGraphitePara)\n\n            qext    = (qext_pa + 2.0 * qext_pe) / 3.0\n\n        else:\n            if np.size(dist.a) > 1:\n                for i in range(np.size(dist.a)):\n                    qext[:,i] = scat.Qext(E, a=dist.a[i], cm=cm)\n            else:\n                qext = scat.Qext(E, a=dist.a, cm=cm)\n\n        if np.size(dist.a) == 1:\n            kappa = dist.nd * qext * cgeo / dist.md\n        else:\n            kappa = np.array([])\n            for j in range(np.size(E)):\n                kappa = np.append(kappa,\n                                  c.intz(dist.a, dist.nd * qext[j,:] * cgeo) / dist.md)\n\n        self.kappa = kappa\n", "meta": {"hexsha": "cc030d530ed48030c421c124c2af03f8f4c8c1b7", "size": 10277, "ext": "py", "lang": "Python", "max_stars_repo_path": "astrodust/extinction/sigma_scat.py", "max_stars_repo_name": "eblur/dust", "max_stars_repo_head_hexsha": "babbee0d5b6625f431eaff11ef33e8a839c7d7ff", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2016-03-25T03:35:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-12T10:29:13.000Z", "max_issues_repo_path": "astrodust/extinction/sigma_scat.py", "max_issues_repo_name": "eblur/dust", "max_issues_repo_head_hexsha": "babbee0d5b6625f431eaff11ef33e8a839c7d7ff", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2016-03-21T15:57:18.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-03T04:28:07.000Z", "max_forks_repo_path": "astrodust/extinction/sigma_scat.py", "max_forks_repo_name": "eblur/dust", "max_forks_repo_head_hexsha": "babbee0d5b6625f431eaff11ef33e8a839c7d7ff", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2015-07-01T19:31:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-27T02:18:50.000Z", "avg_line_length": 33.4755700326, "max_line_length": 102, "alphanum_fraction": 0.5352729396, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.709019146082187, "lm_q2_score": 0.2814055953761019, "lm_q1q2_score": 0.19952195493631317}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nStationSim\nCreated on Tue Nov 20 15:25:27 2018\n@author: medkmin\n\"\"\"\n\n# sspmm.py\n'''\nStationSim (aka Mike's model) converted into python.\n'''\n# Note cm (classmethods): Class Methods seem to have caused an issue.. Is so we can take these methods outside the class (excluding __init__).  This will reduce reproducing methods in the PF.\n\n\n#%% INIT\nimport numpy as np\nfrom scipy.spatial import cKDTree\nimport matplotlib.pyplot as plt\nsqrt2 = np.sqrt(2)  # required for Agent.lerp()\n\ndef two_element_norm(arr):\n    \"\"\"\n    A helpful function to calculate the norm for an array of two elements.\n    This simply takes the square root of the sum of the square of the elements.\n    This appears to be faster than np.linalg.norm.\n    No doubt the numpy implementation would be faster for large arrays.\n    Fortunately, all of our norms are of two-element arrays.\n\n    :param arr:     A numpy array (or array-like DS) with length two.\n    :return norm:   The norm of the array.\n    \"\"\"\n    return np.sqrt(arr[0] * arr[0] + arr[1] * arr[1])\n\n#%% MODEL\nclass Agent:\n    \"\"\"\n    A class representing a generic agent for the StationSim ABM.\n    \"\"\"\n    def __init__(self, model, unique_id):\n        \"\"\"\n        Initialise a new agent.\n\n        Creates a new agent and gives it a randomly chosen entrance, exit, and\n        desired speed. All agents start with active state 0 ('not started').\n        Their initial location (** HOW IS LOCATION REPRESENTED?? Answer: With (x,y) tuple-floats **) is set\n        to the location of the entrance that they are assigned to.\n\n        :param model: a pointer to the station sim model that is creating this agent\n        \"\"\"\n        # Required\n        self.unique_id = unique_id\n        self.active = 0  # 0 Not Started, 1 Active, 2 Finished\n        model.pop_active += 1\n\n        # Choose at random at which of the entrances the agent starts\n        self.location = model.loc_entrances[np.random.randint(model.entrances)]\n        self.location[1] += model.entrance_space * (np.random.uniform() - .5)\n        self.loc_desire = model.loc_exits[np.random.randint(model.exits)]\n\n        # Parameters\n        # model.entrance_speed -> the rate at which agents enter\n        # self.time_activate -> the time at which the agent should become active\n        # time_activate is exponentially distributed based on entrance_speed\n        self.time_activate = np.random.exponential(model.entrance_speed)\n        # The maximum speed that this agent can travel at:\n        # self.speed_desire = max(np.random.normal(model.speed_desire_mean, model.speed_desire_std), 2*model.speed_min)  # this is not a truncated normal distribution\n        self.speed_desire = model.speed_min - 1\n        while self.speed_desire <= model.speed_min:\n            self.speed_desire = np.random.normal(model.speed_desire_mean, model.speed_desire_std)\n        self.wiggle = min(self.speed_desire, model.wiggle)  # if they can wiggle faster than they can move they may beat the expected time\n        # A few speeds to check; used if a step at the max speed would cause a collision\n        self.speeds = np.arange(self.speed_desire, model.speed_min, -model.speed_step)\n        if model.do_save:\n            self.history_loc = []\n        self.time_expected = None\n        self.time_start = None\n\n    def step(self, model):\n        \"\"\"\n        Iterate the agent. If they are inactive then it checks to see if they\n        should become active. If they are active then then move (see\n        self.move()) and, possibly, leave the model (see exit_query())).\n        \"\"\"\n        if self.active == 0:\n            self.activate(model)\n        elif self.active == 1:\n            self.move(model)\n            self.exit_query(model)\n            self.save(model)\n\n    def activate(self, model):\n        \"\"\"\n        Test whether an agent should become active. This happens when the model\n        time is greater than the agent's activate time.\n        \"\"\"\n        if not self.active and model.time_id > self.time_activate:\n            self.active = 1\n            self.time_start = model.time_id\n            self.time_expected = (np.linalg.norm(self.location - self.loc_desire) - model.exit_space) / self.speed_desire\n\n    @staticmethod\n    def is_within_bounds(boundaries, new_location):\n        \"\"\"\n        Check if new location is within the bounds of the model.\n        :param boundaries      The boundaries of the model\n        :param new_location    The proposed location for the agent\n        :return                Is new location within boundaries, boolean\n        \"\"\"\n        within0 = all(boundaries[0] <= new_location)\n        within1 = all(boundaries[1] <= new_location)\n        return within0 and within1\n\n    def move(self, model):\n        \"\"\"\n        Move the agent towards their destination. If the way is clear then the\n        agent moves the maximum distance they can given their maximum possible\n        speed (self.speed_desire). If not, then they iteratively test smaller\n        and smaller distances until they find one that they can travel to\n        without causing a collision with another agent.\n        \"\"\"\n        for speed in self.speeds:\n            # Direct\n            new_location = Agent.lerp(self.loc_desire, self.location, speed)\n            if not Agent.collision(model, new_location):\n                break\n            elif speed == self.speeds[-1]:\n                # Wiggle\n                # Why 1+1? Answer: randint(1)=0, randint(2)=0 or 1 - i think it is the standard pythonic idea of up to that number like array[0:2] is elements (array[0],array[1])\n                # randint is upper-bound exclusive, so 2 instead of 1\n                new_location = self.location + self.wiggle*np.random.randint(-1, 1+1, 2)\n        # Rebound\n        if not self.is_within_bounds(model.boundaries, new_location):\n            new_location = np.clip(new_location, model.boundaries[0], model.boundaries[1])\n        # Move\n        self.location = new_location\n\n    @classmethod\n    def collision(cls, model, new_location):\n        \"\"\"\n        Detects whether a move to the new_location will cause a collision\n        (either with the model boundary or another agent).\n        \"\"\"\n        within_bounds = all(model.boundaries[0] <= new_location) and all(new_location <= model.boundaries[1])\n        if not within_bounds:\n            collide = True\n        elif Agent.neighbourhood(model, new_location):\n            collide = True\n        else:\n            collide = False\n        return collide\n\n    @classmethod\n    def neighbourhood(cls, model, new_location):\n        \"\"\"\n        XXXX WHAT DOES THIS DO??  Answer: This method finds whether or not nearby neighbours are a collision.\n\n         :param model:        the model that this agent is part of\n         :param new_location: the proposed new location that the agent will move to\n                         (a XXXX - what kind of object/data is the location?  Answer: the standard (x,y) floats-tuple)\n         :param do_kd_tree    whether to use a spatial index (kd_tree) (default true)\n        \"\"\"\n        neighbours = False\n        neighbouring_agents = model.tree.query_ball_point(new_location, model.separation)\n        for neighbouring_agent in neighbouring_agents:\n            agent = model.agents[neighbouring_agent]\n            if agent.active == 1 and new_location[0] <= agent.location[0]:\n                neighbours = True\n                break\n        return neighbours\n\n    @classmethod\n    def lerp(cls, loc1, loc2, speed):\n        \"\"\"\n        lerp - linear extrapolation\n        Find the new position of after moving 'speed' distance from loc2 towards loc1.\n            :param loc1: desired location\n            :param loc2: current location\n            :param speed: distance that can be covered in an iteration\n            :return: The new location\n        lerp is a intensively used method hence profiling and adjustments have been made, see 'github dust/Projects/awest/code/experiments/lerp.py' for more understanding.\n        \"\"\"\n        #distance = np.linalg.norm(loc1 - loc2)     # frobenius norm: profiled at 8.05μs\n        #distance = np.sqrt(sum((loc1 - loc2)**2))  # euclidean norm: profiled at 7.82μs\n        #distance = sum(abs(loc1 - loc2))           # manhattan norm: profiled at 6.19μs\n        reciprocal_distance = sqrt2 / sum(abs(loc1 - loc2))  # lerp5: profiled at 6.41μs\n        loc = loc2 + speed * (loc1 - loc2) * reciprocal_distance\n        return loc\n\n    def exit_query(self, model):\n        \"\"\"\n        Determine whether the agent should leave the model and, if so,\n        remove them. Otherwise do nothing.\n        \"\"\"\n        if sum(abs(self.location - self.loc_desire)) / sqrt2 < model.exit_space:\n#        if two_element_norm(self.location - self.loc_desire) < model.exit_space:\n            self.active = 2\n            model.pop_active -= 1\n            model.pop_finished += 1\n            if model.do_save:\n                time_delta = model.time_id - self.time_start\n                model.time_taken.append(time_delta)\n                time_delta -= self.time_expected\n                model.time_delay.append(time_delta)\n\n    def save(self, model):\n        \"\"\"\n        Save agent location.\n        \"\"\"\n        if model.do_save:\n            self.history_loc.append(self.location)\n\n\nclass Model:\n    \"\"\"\n    A class to represent the StationSim model.\n    \"\"\"\n    def __init__(self, params):\n        \"\"\"\n        Create a new model, reading parameters from a dictionary.\n        XXXX Need to document the required parameters.\n        \"\"\"\n        self.params = params\n        # There are a lot of required attributes here that we hope are in params\n        # Perhaps we should have a way to ensure we get what we require?\n        # Also, consider using **kwargs\n        [setattr(self, key, value) for key, value in params.items()]\n        # Average number of speeds to check\n        self.speed_step = (self.speed_desire_mean - self.speed_min) / 3\n        # Batch Details\n        self.time_id = 0\n        self.step_id = 0\n        if self.do_save:\n            self.time_taken = []\n            self.time_delay = []\n        # Model Parameters\n        self.boundaries = np.array([[0, 0], [self.width, self.height]])\n        self.pop_active = 0\n        self.pop_finished = 0\n        # Initialise\n        self.initialise_gates()\n        self.agents = [Agent(self, unique_id) for unique_id in range(self.pop_total)]\n\n    def step(self):\n        \"\"\"\n        Iterate model forward one step.\n        \"\"\"\n        if self.pop_finished < self.pop_total and self.step:\n            self.kdtree_build()\n            [agent.step(self) for agent in self.agents]\n        self.time_id += 1\n        self.step_id += 1\n\n    def initialise_gates(self):\n        \"\"\"\n        Initialise the locations of the entrances and exits.\n        \"\"\"\n        self.loc_entrances = self.initialise_gates_generic(self.entrances, 0)\n        self.loc_exits = self.initialise_gates_generic(self.exits, self.width)\n\n    def initialise_gates_generic(self, n_gates, x):\n        \"\"\"\n        General method for initialising gates.\n        Note: This method relies on a lot of class attributes, many of which are\n        not explicitly required in the init method - perhaps we should be\n        careful of this?  Answer: see note cm at top\n        \"\"\"\n        gates = np.zeros((n_gates, 2))\n        gates[:, 0] = x\n        if n_gates == 1:\n            gates[0, 1] = self.height / 2\n        else:\n            gates[:, 1] = np.linspace(self.height / 4, 3 * self.height / 4,\n                                      n_gates)\n        return gates\n\n    def kdtree_build(self):\n        \"\"\"\n        Build kdtree for the model.\n        \"\"\"\n        state = self.agents2state(do_ravel=False)\n        self.tree = cKDTree(state)\n\n    def agents2state(self, do_ravel=True):\n        \"\"\"\n        Convert list of agents in model to state vector.\n        \"\"\"\n        state = [agent.location for agent in self.agents]\n        state = np.ravel(state) if do_ravel else np.array(state)\n        return state\n\n    def state2agents(self, state):\n        \"\"\"\n        Use state vector to set agent locations.\n        \"\"\"\n        for i in range(len(self.agents)):\n            self.agents[i].location = state[2 * i:2 * i + 2]\n\n    def batch(self):\n        \"\"\"\n        Run the model.\n        \"\"\"\n        print(\"Starting batch mode with following parameters:\")\n        print('\\tParameter\\tValue')\n        for k, v in self.params.items():\n            print('\\t{0}:\\t{1}'.format(k, v))\n        print('')\n        for i in range(self.batch_iterations):\n            self.step()\n            if i % 100 == 0:\n                print(\"\\tIterations: \", i)\n            if self.do_ani:\n                self.ani()\n            if self.pop_finished == self.pop_total:\n                print('Everyone made it!')\n                break\n        print(\"Finished at iteration\", i)\n        if self.do_save:\n            self.save_stats()\n            if self.do_plot: self.save_plot()\n\n    def ani(self, agents=None, colour='k', alpha=1, show_separation=True):\n        # Design for use in PF\n        wid = 8  # image size\n        hei = wid * self.height / self.width\n        if show_separation:\n            # the magic formular for marksize scaling\n            magic = 1.8  # dependant on the amount of figure space used\n            markersizescale = magic*72*hei/self.height\n        plt.figure(1, figsize=(wid, hei))\n        plt.clf()\n        plt.axis(np.ravel(self.boundaries, 'F'))\n        plt.axes().set_aspect('equal')\n        for agent in self.agents[:agents]:\n            if agent.active == 1:\n                if show_separation:\n                    plt.plot(*agent.location, marker='s', markersize=markersizescale*self.separation, color=colour, alpha=.05)\n                plt.plot(*agent.location, marker='.', markersize=2, color=colour, alpha=alpha)\n        plt.xlabel('Corridor Width')\n        plt.ylabel('Corridor Height')\n        plt.pause(1 / 30)\n        return\n\n    def save_ani(self):\n        return\n\n    def save_plot(self):\n        \"\"\"\n        Produce plots for model.\n        \"\"\"\n        self.plot_trails()\n        self.plot_agent_times()\n\n    def plot_trails(self):\n        \"\"\"\n        Produce a plot of the trails of each agent in the 2-d corridor.\n        \"\"\"\n        # Trails\n        plt.figure()\n        for agent in self.agents:\n            if agent.active == 0:\n                colour = 'r'\n            elif agent.active == 1:\n                colour = 'b'\n            else:\n                colour = 'm'\n            locs = np.array(agent.history_loc).T\n            plt.plot(locs[0], locs[1], color=colour, linewidth=.5)\n        plt.axis(np.ravel(self.boundaries, 'F'))\n        plt.xlabel('Corridor Width')\n        plt.ylabel('Corridor Height')\n        plt.legend(['Agent trails'])\n        plt.show()\n\n    def plot_agent_times(self):\n        \"\"\"\n        Produce a plot of the time taken by each agent, and the delay of each\n        agent.\n        \"\"\"\n        # Time Taken, Delay Amount\n        plt.figure()\n        plt.hist(self.time_taken, alpha=.5, label='Time taken')\n        plt.hist(self.time_delay, alpha=.5, label='Time delay')\n        plt.xlabel('Time')\n        plt.ylabel('Number of Agents')\n        plt.legend()\n        plt.show()\n\n    def save_stats(self):\n        \"\"\"\n        Print model run stats to console.\n        \"\"\"\n        print()\n        print('Stats:')\n        print('Finish Time: ' + str(self.time_id))\n        print('Active / Finished / Total agents: ' +\n              str(self.pop_active) + '/' + str(self.pop_finished) +\n              '/' + str(self.pop_total))\n        print('Average time taken: {:.2f} steps'.format(np.mean(self.time_taken)))\n        print('Average time delay: {:.2f} steps'.format(np.mean(self.time_delay)))\n\n    def __repr__(self):\n        \"\"\"Print this model's ID and its memory location\"\"\"\n        return \"StationSim [{}]\".format(hex(id(self)))\n\n    @classmethod\n    def run_defaultmodel(cls):\n        \"\"\"\n        Run a model with some common parameters. Mostly used for testing.\n        \"\"\"\n        np.random.seed(42)\n        model_params = {\n            'width': 200,\n            'height': 100,\n            'pop_total': 100,\n            'entrances': 3,\n            'entrance_space': 2,\n            'entrance_speed': 1,\n            'exits': 2,\n            'exit_space': 1,\n            'speed_min': .1,\n            'speed_desire_mean': 1,\n            'speed_desire_std': 1,\n            'separation': 4,\n            'wiggle': 1,\n            'batch_iterations': 10_000,\n            'do_save': True,\n            'do_plot': False,\n            'do_ani': True\n        }\n        # Run the model\n        Model(model_params).batch()\n\n\n# If this is called from the command line then run a default model.\nif __name__ == '__main__':\n    Model.run_defaultmodel()\n", "meta": {"hexsha": "302bfa20df7d78b1d10d3c35e0976763b2e5c5cc", "size": 16832, "ext": "py", "lang": "Python", "max_stars_repo_path": "Projects/ABM_DA/at_risk/StationSim_KM.py", "max_stars_repo_name": "RobertClay/DUST-RC", "max_stars_repo_head_hexsha": "09f7ec9d8d093021d068dff8a7a48c15ea318b86", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2018-11-21T14:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T15:42:09.000Z", "max_issues_repo_path": "Projects/ABM_DA/at_risk/StationSim_KM.py", "max_issues_repo_name": "RobertClay/DUST-RC", "max_issues_repo_head_hexsha": "09f7ec9d8d093021d068dff8a7a48c15ea318b86", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 125, "max_issues_repo_issues_event_min_datetime": "2019-11-06T13:03:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T13:38:33.000Z", "max_forks_repo_path": "Projects/ABM_DA/at_risk/StationSim_KM.py", "max_forks_repo_name": "RobertClay/DUST-RC", "max_forks_repo_head_hexsha": "09f7ec9d8d093021d068dff8a7a48c15ea318b86", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-11-20T15:56:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-08T10:21:06.000Z", "avg_line_length": 38.5171624714, "max_line_length": 191, "alphanum_fraction": 0.595769962, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3242354055108442, "lm_q1q2_score": 0.19943326025804736}}
{"text": "#   Copyright 2020 The PyMC Developers\n#\n#   Licensed under the Apache License, Version 2.0 (the \"License\");\n#   you may not use this file except in compliance with the License.\n#   You may obtain a copy of the License at\n#\n#       http://www.apache.org/licenses/LICENSE-2.0\n#\n#   Unless required by applicable law or agreed to in writing, software\n#   distributed under the License is distributed on an \"AS IS\" BASIS,\n#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#   See the License for the specific language governing permissions and\n#   limitations under the License.\nimport warnings\n\nfrom collections.abc import Mapping\nfrom functools import singledispatch\nfrom typing import Dict, Optional, Union\n\nimport aesara.tensor as at\nimport numpy as np\n\nfrom aeppl import factorized_joint_logprob\nfrom aeppl.transforms import TransformValuesOpt\nfrom aesara import config\nfrom aesara.graph.basic import graph_inputs, io_toposort\nfrom aesara.graph.op import Op, compute_test_value\nfrom aesara.tensor.random.op import RandomVariable\nfrom aesara.tensor.subtensor import (\n    AdvancedIncSubtensor,\n    AdvancedIncSubtensor1,\n    AdvancedSubtensor,\n    AdvancedSubtensor1,\n    IncSubtensor,\n    Subtensor,\n)\nfrom aesara.tensor.var import TensorVariable\n\nfrom pymc.aesaraf import extract_rv_and_value_vars, floatX, rvs_to_value_vars\n\n\n@singledispatch\ndef logp_transform(op: Op):\n    return None\n\n\ndef _get_scaling(total_size, shape, ndim):\n    \"\"\"\n    Gets scaling constant for logp\n\n    Parameters\n    ----------\n    total_size: int or list[int]\n    shape: shape\n        shape to scale\n    ndim: int\n        ndim hint\n\n    Returns\n    -------\n    scalar\n    \"\"\"\n    if total_size is None:\n        coef = floatX(1)\n    elif isinstance(total_size, int):\n        if ndim >= 1:\n            denom = shape[0]\n        else:\n            denom = 1\n        coef = floatX(total_size) / floatX(denom)\n    elif isinstance(total_size, (list, tuple)):\n        if not all(isinstance(i, int) for i in total_size if (i is not Ellipsis and i is not None)):\n            raise TypeError(\n                \"Unrecognized `total_size` type, expected \"\n                \"int or list of ints, got %r\" % total_size\n            )\n        if Ellipsis in total_size:\n            sep = total_size.index(Ellipsis)\n            begin = total_size[:sep]\n            end = total_size[sep + 1 :]\n            if Ellipsis in end:\n                raise ValueError(\n                    \"Double Ellipsis in `total_size` is restricted, got %r\" % total_size\n                )\n        else:\n            begin = total_size\n            end = []\n        if (len(begin) + len(end)) > ndim:\n            raise ValueError(\n                \"Length of `total_size` is too big, \"\n                \"number of scalings is bigger that ndim, got %r\" % total_size\n            )\n        elif (len(begin) + len(end)) == 0:\n            return floatX(1)\n        if len(end) > 0:\n            shp_end = shape[-len(end) :]\n        else:\n            shp_end = np.asarray([])\n        shp_begin = shape[: len(begin)]\n        begin_coef = [floatX(t) / shp_begin[i] for i, t in enumerate(begin) if t is not None]\n        end_coef = [floatX(t) / shp_end[i] for i, t in enumerate(end) if t is not None]\n        coefs = begin_coef + end_coef\n        coef = at.prod(coefs)\n    else:\n        raise TypeError(\n            \"Unrecognized `total_size` type, expected int or list of ints, got %r\" % total_size\n        )\n    return at.as_tensor(floatX(coef))\n\n\nsubtensor_types = (\n    AdvancedIncSubtensor,\n    AdvancedIncSubtensor1,\n    AdvancedSubtensor,\n    AdvancedSubtensor1,\n    IncSubtensor,\n    Subtensor,\n)\n\n\ndef logpt(\n    var: TensorVariable,\n    rv_values: Optional[Union[TensorVariable, Dict[TensorVariable, TensorVariable]]] = None,\n    *,\n    jacobian: bool = True,\n    scaling: bool = True,\n    transformed: bool = True,\n    sum: bool = True,\n    **kwargs,\n) -> TensorVariable:\n    \"\"\"Create a measure-space (i.e. log-likelihood) graph for a random variable\n    or a list of random variables at a given point.\n\n    The input `var` determines which log-likelihood graph is used and\n    `rv_value` is that graph's input parameter.  For example, if `var` is\n    the output of a ``NormalRV`` ``Op``, then the output is a graph of the\n    density function for `var` set to the value `rv_value`.\n\n    Parameters\n    ==========\n    var\n        The `RandomVariable` output that determines the log-likelihood graph.\n        Can also be a list of variables. The final log-likelihood graph will\n        be the sum total of all individual log-likelihood graphs of variables\n        in the list.\n    rv_values\n        A variable, or ``dict`` of variables, that represents the value of\n        `var` in its log-likelihood.  If no `rv_value` is provided,\n        ``var.tag.value_var`` will be checked and, when available, used.\n    jacobian\n        Whether or not to include the Jacobian term.\n    scaling\n        A scaling term to apply to the generated log-likelihood graph.\n    transformed\n        Apply transforms.\n    sum\n        Sum the log-likelihood.\n\n    \"\"\"\n    # TODO: In future when we drop support for tag.value_var most of the following\n    # logic can be removed and logpt can just be a wrapper function that calls aeppl's\n    # joint_logprob directly.\n\n    # If var is not a list make it one.\n    if not isinstance(var, list):\n        var = [var]\n\n    # If logpt isn't provided values and the variable (provided in var)\n    # is an RV, it is assumed that the tagged value var or observation is\n    # the value variable for that particular RV.\n    if rv_values is None:\n        rv_values = {}\n        for _var in var:\n            if isinstance(_var.owner.op, RandomVariable):\n                rv_value_var = getattr(\n                    _var.tag, \"observations\", getattr(_var.tag, \"value_var\", _var)\n                )\n                rv_values = {_var: rv_value_var}\n    elif not isinstance(rv_values, Mapping):\n        # Else if we're given a single value and a single variable we assume a mapping among them.\n        rv_values = (\n            {var[0]: at.as_tensor_variable(rv_values).astype(var[0].type)} if len(var) == 1 else {}\n        )\n\n    # Since the filtering of logp graph is based on value variables\n    # provided to this function\n    if not rv_values:\n        warnings.warn(\"No value variables provided the logp will be an empty graph\")\n\n    if scaling:\n        rv_scalings = {}\n        for _var in var:\n            rv_value_var = getattr(_var.tag, \"observations\", getattr(_var.tag, \"value_var\", _var))\n            rv_scalings[rv_value_var] = _get_scaling(\n                getattr(_var.tag, \"total_size\", None), rv_value_var.shape, rv_value_var.ndim\n            )\n\n    # Unlike aeppl, PyMC's logpt is expected to plug in the values variables to corresponding\n    # RVs automatically unless the values are explicity set to None. Hence we iterate through\n    # the graph to find RVs and construct a new RVs to values dictionary.\n    tmp_rvs_to_values = rv_values.copy()\n    transform_map = {}\n    for node in io_toposort(graph_inputs(var), var):\n        if isinstance(node.op, RandomVariable):\n            curr_var = node.out\n            rv_value_var = getattr(\n                curr_var.tag, \"observations\", getattr(curr_var.tag, \"value_var\", curr_var)\n            )\n            rv_value = rv_values.get(curr_var, rv_value_var)\n            tmp_rvs_to_values[curr_var] = rv_value\n            # Along with value variables we also check for transforms if any.\n            if hasattr(rv_value_var.tag, \"transform\") and transformed:\n                transform_map[rv_value] = rv_value_var.tag.transform\n        # The condition below is a hackish way of excluding the value variable for the\n        # RV being indexed in case of Advanced Indexing of RVs. It gets added by the\n        # logic above but aeppl does not expect us to include it in the dictionary of\n        # {RV:values} given to it.\n        if isinstance(node.op, subtensor_types):\n            curr_var = node.out\n            if (\n                curr_var in tmp_rvs_to_values.keys()\n                and curr_var.owner.inputs[0] in tmp_rvs_to_values.keys()\n            ):\n                tmp_rvs_to_values.pop(curr_var.owner.inputs[0])\n\n    transform_opt = TransformValuesOpt(transform_map)\n    temp_logp_var_dict = factorized_joint_logprob(\n        tmp_rvs_to_values, extra_rewrites=transform_opt, use_jacobian=jacobian, **kwargs\n    )\n\n    # aeppl returns the logpt for every single value term we provided to it. This includes\n    # the extra values we plugged in above so we need to filter those out.\n    logp_var_dict = {}\n    for value_var, _logp in temp_logp_var_dict.items():\n        if value_var in rv_values.values():\n            logp_var_dict[value_var] = _logp\n\n    # If it's an empty dictionary the logp is None\n    if not logp_var_dict:\n        logp_var = None\n    else:\n        # Otherwise apply appropriate scalings and at.add and/or at.sum the\n        # graphs accordingly.\n        if scaling:\n            for _value in logp_var_dict.keys():\n                if _value in rv_scalings:\n                    logp_var_dict[_value] *= rv_scalings[_value]\n\n        if len(logp_var_dict) == 1:\n            logp_var_dict = tuple(logp_var_dict.values())[0]\n            if sum:\n                logp_var = at.sum(logp_var_dict)\n            else:\n                logp_var = logp_var_dict\n        else:\n            if sum:\n                logp_var = at.sum([at.sum(factor) for factor in logp_var_dict.values()])\n            else:\n                logp_var = at.add(*logp_var_dict.values())\n\n        # Recompute test values for the changes introduced by the replacements\n        # above.\n        if config.compute_test_value != \"off\":\n            for node in io_toposort(graph_inputs((logp_var,)), (logp_var,)):\n                compute_test_value(node)\n\n    return logp_var\n\n\ndef logcdfpt(\n    var: TensorVariable,\n    rv_values: Optional[Union[TensorVariable, Dict[TensorVariable, TensorVariable]]] = None,\n    *,\n    scaling: bool = True,\n    sum: bool = True,\n    **kwargs,\n) -> TensorVariable:\n    \"\"\"Create a measure-space (i.e. log-cdf) graph for a random variable at a given point.\n\n    Parameters\n    ==========\n    var\n        The `RandomVariable` output that determines the log-likelihood graph.\n    rv_values\n        A variable, or ``dict`` of variables, that represents the value of\n        `var` in its log-likelihood.  If no `rv_value` is provided,\n        ``var.tag.value_var`` will be checked and, when available, used.\n    jacobian\n        Whether or not to include the Jacobian term.\n    scaling\n        A scaling term to apply to the generated log-likelihood graph.\n    transformed\n        Apply transforms.\n    sum\n        Sum the log-likelihood.\n\n    \"\"\"\n    if not isinstance(rv_values, Mapping):\n        rv_values = {var: rv_values} if rv_values is not None else {}\n\n    rv_var, rv_value_var = extract_rv_and_value_vars(var)\n\n    rv_value = rv_values.get(rv_var, rv_value_var)\n\n    if rv_var is not None and rv_value is None:\n        raise ValueError(f\"No value variable specified or associated with {rv_var}\")\n\n    if rv_value is not None:\n        rv_value = at.as_tensor(rv_value)\n\n        if rv_var is not None:\n            # Make sure that the value is compatible with the random variable\n            rv_value = rv_var.type.filter_variable(rv_value.astype(rv_var.dtype))\n\n        if rv_value_var is None:\n            rv_value_var = rv_value\n\n    rv_node = rv_var.owner\n\n    rng, size, dtype, *dist_params = rv_node.inputs\n\n    # Here, we plug the actual random variable into the log-likelihood graph,\n    # because we want a log-likelihood graph that only contains\n    # random variables.  This is important, because a random variable's\n    # parameters can contain random variables themselves.\n    # Ultimately, with a graph containing only random variables and\n    # \"deterministics\", we can simply replace all the random variables with\n    # their value variables and be done.\n    tmp_rv_values = rv_values.copy()\n    tmp_rv_values[rv_var] = rv_var\n\n    logp_var = _logcdf(rv_node.op, rv_var, tmp_rv_values, *dist_params, **kwargs)\n\n    transform = getattr(rv_value_var.tag, \"transform\", None) if rv_value_var else None\n\n    # Replace random variables with their value variables\n    replacements = rv_values.copy()\n    replacements.update({rv_var: rv_value, rv_value_var: rv_value})\n\n    (logp_var,), _ = rvs_to_value_vars(\n        (logp_var,),\n        apply_transforms=False,\n        initial_replacements=replacements,\n    )\n\n    if sum:\n        logp_var = at.sum(logp_var)\n\n    if scaling:\n        logp_var *= _get_scaling(\n            getattr(rv_var.tag, \"total_size\", None), rv_value.shape, rv_value.ndim\n        )\n\n    # Recompute test values for the changes introduced by the replacements\n    # above.\n    if config.compute_test_value != \"off\":\n        for node in io_toposort(graph_inputs((logp_var,)), (logp_var,)):\n            compute_test_value(node)\n\n    if rv_var.name is not None:\n        logp_var.name = f\"__logp_{rv_var.name}\"\n\n    return logp_var\n\n\ndef logp(var, rv_values, **kwargs):\n    \"\"\"Create a log-probability graph.\"\"\"\n\n    # Attach the value_var to the tag of var when it does not have one\n    if not hasattr(var.tag, \"value_var\"):\n        if isinstance(rv_values, Mapping):\n            value_var = rv_values[var]\n        else:\n            value_var = rv_values\n        var.tag.value_var = at.as_tensor_variable(value_var, dtype=var.dtype)\n\n    return logpt(var, rv_values, **kwargs)\n\n\ndef logcdf(var, rv_values, **kwargs):\n    \"\"\"Create a log-CDF graph.\"\"\"\n\n    # Attach the value_var to the tag of var when it does not have one\n    if not hasattr(var.tag, \"value_var\"):\n        if isinstance(rv_values, Mapping):\n            value_var = rv_values[var]\n        else:\n            value_var = rv_values\n        var.tag.value_var = at.as_tensor_variable(value_var, dtype=var.dtype)\n\n    return logcdfpt(var, rv_values, **kwargs)\n\n\n@singledispatch\ndef _logcdf(op, values, *args, **kwargs):\n    \"\"\"Create a log-CDF graph.\n\n    This function dispatches on the type of `op`, which should be a subclass\n    of `RandomVariable`.  If you want to implement new log-CDF graphs\n    for a `RandomVariable`, register a new function on this dispatcher.\n\n    \"\"\"\n    raise NotImplementedError()\n\n\ndef logpt_sum(*args, **kwargs):\n    \"\"\"Return the sum of the logp values for the given observations.\n\n    Subclasses can use this to improve the speed of logp evaluations\n    if only the sum of the logp values is needed.\n    \"\"\"\n    return logpt(*args, sum=True, **kwargs)\n", "meta": {"hexsha": "e8611c591e79420a6b4a473ef72d98a6f53313ff", "size": 14630, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymc/distributions/logprob.py", "max_stars_repo_name": "michaeloriordan/pymc", "max_stars_repo_head_hexsha": "a099292f1de592447abc54f223ecd6e5d93a95dc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1554, "max_stars_repo_stars_event_min_datetime": "2015-01-03T05:50:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T03:32:29.000Z", "max_issues_repo_path": "pymc/distributions/logprob.py", "max_issues_repo_name": "michaeloriordan/pymc", "max_issues_repo_head_hexsha": "a099292f1de592447abc54f223ecd6e5d93a95dc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 922, "max_issues_repo_issues_event_min_datetime": "2015-01-03T17:51:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:49:44.000Z", "max_forks_repo_path": "pymc/distributions/logprob.py", "max_forks_repo_name": "michaeloriordan/pymc", "max_forks_repo_head_hexsha": "a099292f1de592447abc54f223ecd6e5d93a95dc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 484, "max_forks_repo_forks_event_min_datetime": "2015-01-12T16:44:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:40:01.000Z", "avg_line_length": 35.4237288136, "max_line_length": 100, "alphanum_fraction": 0.6470266576, "include": true, "reason": "import numpy", "num_tokens": 3482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.32423539245106087, "lm_q1q2_score": 0.19943325222513325}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Timothy Berkelbach <tim.berkelbach@gmail.com>\n#         Qiming Sun <osirpt.sun@gmail.com>\n#\n\nimport sys\nimport ctypes\nimport numpy\nfrom pyscf import lib\nfrom pyscf.dft import numint\nfrom pyscf.dft.numint import eval_mat, _dot_ao_ao, _dot_ao_dm\nfrom pyscf.dft.numint import _scale_ao, _contract_rho\nfrom pyscf.dft.numint import _rks_gga_wv0, _rks_gga_wv1\nfrom pyscf.dft.numint import _uks_gga_wv0, _uks_gga_wv1\nfrom pyscf.dft.numint import OCCDROP\nfrom pyscf.pbc.dft.gen_grid import libpbc, make_mask, BLKSIZE\nfrom pyscf.pbc.lib.kpts_helper import is_zero, gamma_point, member\n\n#try:\n### Moderate speedup by caching eval_ao\n#    from pyscf import pbc\n#    from joblib import Memory\n#    memory = Memory(cachedir='./tmp/', mmap_mode='r', verbose=0)\n#    def memory_cache(f):\n#        g = memory.cache(f)\n#        def maybe_cache(*args, **kwargs):\n#            if pbc.DEBUG:\n#                return g(*args, **kwargs)\n#            else:\n#                return f(*args, **kwargs)\n#        return maybe_cache\n#except:\n#    memory_cache = lambda f: f\n\ndef eval_ao(cell, coords, kpt=numpy.zeros(3), deriv=0, relativity=0, shls_slice=None,\n            non0tab=None, out=None, verbose=None):\n    '''Collocate AO crystal orbitals (opt. gradients) on the real-space grid.\n\n    Args:\n        cell : instance of :class:`Cell`\n\n        coords : (nx*ny*nz, 3) ndarray\n            The real-space grid point coordinates.\n\n    Kwargs:\n        kpt : (3,) ndarray\n            The k-point corresponding to the crystal AO.\n        deriv : int\n            AO derivative order.  It affects the shape of the return array.\n            If deriv=0, the returned AO values are stored in a (N,nao) array.\n            Otherwise the AO values are stored in an array of shape (M,N,nao).\n            Here N is the number of grids, nao is the number of AO functions,\n            M is the size associated to the derivative deriv.\n\n    Returns:\n        aoR : ([4,] nx*ny*nz, nao=cell.nao_nr()) ndarray\n            The value of the AO crystal orbitals on the real-space grid by default.\n            If deriv=1, also contains the value of the orbitals gradient in the\n            x, y, and z directions.  It can be either complex or float array,\n            depending on the kpt argument.  If kpt is not given (gamma point),\n            aoR is a float array.\n\n    See Also:\n        pyscf.dft.numint.eval_ao\n\n    '''\n    ao_kpts = eval_ao_kpts(cell, coords, numpy.reshape(kpt, (-1,3)), deriv,\n                           relativity, shls_slice, non0tab, out, verbose)\n    return ao_kpts[0]\n\n\n#@memory_cache\ndef eval_ao_kpts(cell, coords, kpts=None, deriv=0, relativity=0,\n                 shls_slice=None, non0tab=None, out=None, verbose=None, **kwargs):\n    '''\n    Returns:\n        ao_kpts: (nkpts, [comp], ngrids, nao) ndarray\n            AO values at each k-point\n    '''\n    if kpts is None:\n        if 'kpt' in kwargs:\n            sys.stderr.write('WARN: KNumInt.eval_ao function finds keyword '\n                             'argument \"kpt\" and converts it to \"kpts\"\\n')\n            kpts = kwargs['kpt']\n        else:\n            kpts = numpy.zeros((1,3))\n    kpts = numpy.reshape(kpts, (-1,3))\n\n    comp = (deriv+1)*(deriv+2)*(deriv+3)//6\n    if cell.cart:\n        feval = 'GTOval_cart_deriv%d' % deriv\n    else:\n        feval = 'GTOval_sph_deriv%d' % deriv\n    return cell.pbc_eval_gto(feval, coords, comp, kpts,\n                             shls_slice=shls_slice, non0tab=non0tab, out=out)\n\n\ndef eval_rho(cell, ao, dm, non0tab=None, xctype='LDA', hermi=0, verbose=None):\n    '''Collocate the *real* density (opt. gradients) on the real-space grid.\n\n    Args:\n        cell : instance of :class:`Mole` or :class:`Cell`\n\n        ao : ([4,] nx*ny*nz, nao=cell.nao_nr()) ndarray\n            The value of the AO crystal orbitals on the real-space grid by default.\n            If xctype='GGA', also contains the value of the gradient in the x, y,\n            and z directions.\n\n    Returns:\n        rho : ([4,] nx*ny*nz) ndarray\n            The value of the density on the real-space grid. If xctype='GGA',\n            also contains the value of the gradient in the x, y, and z\n            directions.\n\n    See Also:\n        pyscf.dft.numint.eval_rho\n\n    '''\n\n    if xctype == 'LDA' or xctype == 'HF':\n        ngrids, nao = ao.shape\n    else:\n        ngrids, nao = ao[0].shape\n\n    if non0tab is None:\n        non0tab = numpy.empty(((ngrids+BLKSIZE-1)//BLKSIZE, cell.nbas),\n                              dtype=numpy.uint8)\n        non0tab[:] = 0xff\n\n    # complex orbitals or density matrix\n    if numpy.iscomplexobj(ao) or numpy.iscomplexobj(dm):\n        shls_slice = (0, cell.nbas)\n        ao_loc = cell.ao_loc_nr()\n        dm = dm.astype(numpy.complex128)\n# For GGA, function eval_rho returns   real(|\\nabla i> D_ij <j| + |i> D_ij <\\nabla j|)\n#       = real(|\\nabla i> D_ij <j| + |i> D_ij <\\nabla j|)\n#       = real(|\\nabla i> D_ij <j| + conj(|\\nabla j> conj(D_ij) < i|))\n#       = real(|\\nabla i> D_ij <j|) + real(|\\nabla j> conj(D_ij) < i|)\n#       = real(|\\nabla i> [D_ij + (D^\\dagger)_ij] <j|)\n# symmetrization dm (D + D.conj().T) then /2 because the code below computes\n#       2*real(|\\nabla i> D_ij <j|)\n        if not hermi:\n            dm = (dm + dm.conj().T) * .5\n\n        def dot_bra(bra, aodm):\n            #:rho  = numpy.einsum('pi,pi->p', bra.real, aodm.real)\n            #:rho += numpy.einsum('pi,pi->p', bra.imag, aodm.imag)\n            #:return rho\n            return _contract_rho(bra, aodm)\n\n        if xctype == 'LDA' or xctype == 'HF':\n            c0 = _dot_ao_dm(cell, ao, dm, non0tab, shls_slice, ao_loc)\n            rho = dot_bra(ao, c0)\n\n        elif xctype == 'GGA':\n            rho = numpy.empty((4,ngrids))\n            c0 = _dot_ao_dm(cell, ao[0], dm, non0tab, shls_slice, ao_loc)\n            rho[0] = dot_bra(ao[0], c0)\n            for i in range(1, 4):\n                rho[i] = dot_bra(ao[i], c0) * 2\n\n        else:\n            # rho[4] = \\nabla^2 rho, rho[5] = 1/2 |nabla f|^2\n            rho = numpy.empty((6,ngrids))\n            c0 = _dot_ao_dm(cell, ao[0], dm, non0tab, shls_slice, ao_loc)\n            rho[0] = dot_bra(ao[0], c0)\n            rho[5] = 0\n            for i in range(1, 4):\n                rho[i] = dot_bra(ao[i], c0) * 2  # *2 for +c.c.\n                c1 = _dot_ao_dm(cell, ao[i], dm, non0tab, shls_slice, ao_loc)\n                rho[5] += dot_bra(ao[i], c1)\n            XX, YY, ZZ = 4, 7, 9\n            ao2 = ao[XX] + ao[YY] + ao[ZZ]\n            rho[4] = dot_bra(ao2, c0)\n            rho[4] += rho[5]\n            rho[4] *= 2 # *2 for +c.c.\n            rho[5] *= .5\n    else:\n        # real orbitals and real DM\n        rho = numint.eval_rho(cell, ao, dm, non0tab, xctype, hermi, verbose)\n    return rho\n\ndef eval_rho2(cell, ao, mo_coeff, mo_occ, non0tab=None, xctype='LDA',\n              verbose=None):\n    '''Refer to `pyscf.dft.numint.eval_rho2` for full documentation.\n    '''\n    xctype = xctype.upper()\n    if xctype == 'LDA' or xctype == 'HF':\n        ngrids, nao = ao.shape\n    else:\n        ngrids, nao = ao[0].shape\n\n    if non0tab is None:\n        non0tab = numpy.empty(((ngrids+BLKSIZE-1)//BLKSIZE,cell.nbas),\n                             dtype=numpy.uint8)\n        non0tab[:] = 0xff\n\n    # complex orbitals or density matrix\n    if numpy.iscomplexobj(ao) or numpy.iscomplexobj(mo_coeff):\n        def dot(bra, ket):\n            #:rho  = numpy.einsum('pi,pi->p', bra.real, ket.real)\n            #:rho += numpy.einsum('pi,pi->p', bra.imag, ket.imag)\n            #:return rho\n            return _contract_rho(bra, ket)\n\n        shls_slice = (0, cell.nbas)\n        ao_loc = cell.ao_loc_nr()\n        pos = mo_occ > OCCDROP\n        cpos = numpy.einsum('ij,j->ij', mo_coeff[:,pos], numpy.sqrt(mo_occ[pos]))\n\n        if pos.sum() > 0:\n            if xctype == 'LDA' or xctype == 'HF':\n                c0 = _dot_ao_dm(cell, ao, cpos, non0tab, shls_slice, ao_loc)\n                rho = dot(c0, c0)\n            elif xctype == 'GGA':\n                rho = numpy.empty((4,ngrids))\n                c0 = _dot_ao_dm(cell, ao[0], cpos, non0tab, shls_slice, ao_loc)\n                rho[0] = dot(c0, c0)\n                for i in range(1, 4):\n                    c1 = _dot_ao_dm(cell, ao[i], cpos, non0tab, shls_slice, ao_loc)\n                    rho[i] = dot(c0, c1) * 2  # *2 for +c.c.\n            else: # meta-GGA\n                # rho[4] = \\nabla^2 rho, rho[5] = 1/2 |nabla f|^2\n                rho = numpy.empty((6,ngrids))\n                c0 = _dot_ao_dm(cell, ao[0], cpos, non0tab, shls_slice, ao_loc)\n                rho[0] = dot(c0, c0)\n                rho[5] = 0\n                for i in range(1, 4):\n                    c1 = _dot_ao_dm(cell, ao[i], cpos, non0tab, shls_slice, ao_loc)\n                    rho[i] = dot(c0, c1) * 2  # *2 for +c.c.\n                    rho[5]+= dot(c1, c1)\n                XX, YY, ZZ = 4, 7, 9\n                ao2 = ao[XX] + ao[YY] + ao[ZZ]\n                c1 = _dot_ao_dm(cell, ao2, cpos, non0tab, shls_slice, ao_loc)\n                rho[4] = dot(c0, c1)\n                rho[4]+= rho[5]\n                rho[4]*= 2\n                rho[5]*= .5\n        else:\n            if xctype == 'LDA' or xctype == 'HF':\n                rho = numpy.zeros(ngrids)\n            elif xctype == 'GGA':\n                rho = numpy.zeros((4,ngrids))\n            else:\n                rho = numpy.zeros((6,ngrids))\n\n        neg = mo_occ < -OCCDROP\n        if neg.sum() > 0:\n            cneg = numpy.einsum('ij,j->ij', mo_coeff[:,neg], numpy.sqrt(-mo_occ[neg]))\n            if xctype == 'LDA' or xctype == 'HF':\n                c0 = _dot_ao_dm(cell, ao, cneg, non0tab, shls_slice, ao_loc)\n                rho -= dot(c0, c0)\n            elif xctype == 'GGA':\n                c0 = _dot_ao_dm(cell, ao[0], cneg, non0tab, shls_slice, ao_loc)\n                rho[0] -= dot(c0, c0)\n                for i in range(1, 4):\n                    c1 = _dot_ao_dm(cell, ao[i], cneg, non0tab, shls_slice, ao_loc)\n                    rho[i] -= dot(c0, c1) * 2  # *2 for +c.c.\n            else:\n                c0 = _dot_ao_dm(cell, ao[0], cneg, non0tab, shls_slice, ao_loc)\n                rho[0] -= dot(c0, c0)\n                rho5 = 0\n                for i in range(1, 4):\n                    c1 = _dot_ao_dm(cell, ao[i], cneg, non0tab, shls_slice, ao_loc)\n                    rho[i] -= dot(c0, c1) * 2  # *2 for +c.c.\n                    rho5 -= dot(c1, c1)\n                XX, YY, ZZ = 4, 7, 9\n                ao2 = ao[XX] + ao[YY] + ao[ZZ]\n                c1 = _dot_ao_dm(cell, ao2, cneg, non0tab, shls_slice, ao_loc)\n                rho[4] -= dot(c0, c1) * 2\n                rho[4] -= rho5 * 2\n                rho[5] -= rho5 * .5\n    else:\n        rho = numint.eval_rho2(cell, ao, mo_coeff, mo_occ, non0tab, xctype, verbose)\n    return rho\n\n\ndef nr_rks(ni, cell, grids, xc_code, dms, spin=0, relativity=0, hermi=0,\n           kpts=None, kpts_band=None, max_memory=2000, verbose=None):\n    '''Calculate RKS XC functional and potential matrix for given meshgrids and density matrix\n\n    Note: This is a replica of pyscf.dft.numint.nr_rks_vxc with kpts added.\n    This implemented uses slow function in numint, which only calls eval_rho, eval_mat.\n    Faster function uses eval_rho2 which is not yet implemented.\n\n    Args:\n        ni : an instance of :class:`NumInt` or :class:`KNumInt`\n\n        cell : instance of :class:`Mole` or :class:`Cell`\n\n        grids : an instance of :class:`Grids`\n            grids.coords and grids.weights are needed for coordinates and weights of meshgrids.\n        xc_code : str\n            XC functional description.\n            See :func:`parse_xc` of pyscf/dft/libxc.py for more details.\n        dms : 2D/3D array or a list of 2D/3D arrays\n            Density matrices (2D) / density matrices for k-points (3D)\n\n    Kwargs:\n        spin : int\n            spin polarized if spin = 1\n        relativity : int\n            No effects.\n        hermi : int\n            No effects\n        max_memory : int or float\n            The maximum size of cache to use (in MB).\n        verbose : int or object of :class:`Logger`\n            No effects.\n        kpts : (3,) ndarray or (nkpts,3) ndarray\n            Single or multiple k-points sampled for the DM.  Default is gamma point.\n        kpts_band : (3,) ndarray or (*,3) ndarray\n            A list of arbitrary \"band\" k-points at which to evaluate the XC matrix.\n\n    Returns:\n        nelec, excsum, vmat.\n        nelec is the number of electrons generated by numerical integration.\n        excsum is the XC functional value.  vmat is the XC potential matrix in\n        2D array of shape (nao,nao) where nao is the number of AO functions.\n    '''\n    if kpts is None:\n        kpts = numpy.zeros((1,3))\n\n    xctype = ni._xc_type(xc_code)\n    make_rho, nset, nao = ni._gen_rho_evaluator(cell, dms, hermi)\n\n    nelec = numpy.zeros(nset)\n    excsum = numpy.zeros(nset)\n    vmat = [0]*nset\n    if xctype == 'LDA':\n        ao_deriv = 0\n        for ao_k1, ao_k2, mask, weight, coords \\\n                in ni.block_loop(cell, grids, nao, ao_deriv, kpts, kpts_band,\n                                 max_memory):\n            for i in range(nset):\n                rho = make_rho(i, ao_k2, mask, xctype)\n                exc, vxc = ni.eval_xc(xc_code, rho, 0, relativity, 1)[:2]\n                vrho = vxc[0]\n                den = rho*weight\n                nelec[i] += den.sum()\n                excsum[i] += (den*exc).sum()\n                vmat[i] += ni.eval_mat(cell, ao_k1, weight, rho, vxc,\n                                       mask, xctype, 0, verbose)\n    elif xctype == 'GGA':\n        ao_deriv = 1\n        for ao_k1, ao_k2, mask, weight, coords \\\n                in ni.block_loop(cell, grids, nao, ao_deriv, kpts, kpts_band,\n                                 max_memory):\n            for i in range(nset):\n                rho = make_rho(i, ao_k2, mask, xctype)\n                exc, vxc = ni.eval_xc(xc_code, rho, 0, relativity, 1)[:2]\n                den = rho[0]*weight\n                nelec[i] += den.sum()\n                excsum[i] += (den*exc).sum()\n                vmat[i] += ni.eval_mat(cell, ao_k1, weight, rho, vxc,\n                                       mask, xctype, 0, verbose)\n    elif xctype == 'MGGA':\n        if (any(x in xc_code.upper() for x in ('CC06', 'CS', 'BR89', 'MK00'))):\n            raise NotImplementedError('laplacian in meta-GGA method')\n        ao_deriv = 2\n        for ao_k1, ao_k2, mask, weight, coords \\\n                in ni.block_loop(cell, grids, nao, ao_deriv, kpts, kpts_band,\n                                 max_memory):\n            for i in range(nset):\n                rho = make_rho(i, ao_k2, mask, xctype)\n                exc, vxc = ni.eval_xc(xc_code, rho, 0, relativity, 1)[:2]\n                den = rho[0]*weight\n                nelec[i] += den.sum()\n                excsum[i] += (den*exc).sum()\n                vmat[i] += ni.eval_mat(cell, ao_k1, weight, rho, vxc,\n                                       mask, xctype, 0, verbose)\n    if nset == 1:\n        nelec = nelec[0]\n        excsum = excsum[0]\n        vmat = vmat[0]\n    return nelec, excsum, vmat\n\ndef nr_uks(ni, cell, grids, xc_code, dms, spin=1, relativity=0, hermi=0,\n           kpts=None, kpts_band=None, max_memory=2000, verbose=None):\n    '''Calculate UKS XC functional and potential matrix for given meshgrids and density matrix\n\n    Note: This is a replica of pyscf.dft.numint.nr_rks_vxc with kpts added.\n    This implemented uses slow function in numint, which only calls eval_rho, eval_mat.\n    Faster function uses eval_rho2 which is not yet implemented.\n\n    Args:\n        ni : an instance of :class:`NumInt` or :class:`KNumInt`\n\n        cell : instance of :class:`Mole` or :class:`Cell`\n\n        grids : an instance of :class:`Grids`\n            grids.coords and grids.weights are needed for coordinates and weights of meshgrids.\n        xc_code : str\n            XC functional description.\n            See :func:`parse_xc` of pyscf/dft/libxc.py for more details.\n        dms :\n            Density matrices\n\n    Kwargs:\n        spin : int\n            spin polarized if spin = 1\n        relativity : int\n            No effects.\n        hermi : int\n            Input density matrices symmetric or not\n        max_memory : int or float\n            The maximum size of cache to use (in MB).\n        verbose : int or object of :class:`Logger`\n            No effects.\n        kpts : (3,) ndarray or (nkpts,3) ndarray\n            Single or multiple k-points sampled for the DM.  Default is gamma point.\n            kpts_band : (3,) ndarray or (*,3) ndarray\n            A list of arbitrary \"band\" k-points at which to evaluate the XC matrix.\n\n    Returns:\n        nelec, excsum, vmat.\n        nelec is the number of electrons generated by numerical integration.\n        excsum is the XC functional value.  vmat is the XC potential matrix in\n        2D array of shape (nao,nao) where nao is the number of AO functions.\n    '''\n    if kpts is None:\n        kpts = numpy.zeros((1,3))\n\n    xctype = ni._xc_type(xc_code)\n    dma, dmb = _format_uks_dm(dms)\n    nao = dma.shape[-1]\n    make_rhoa, nset = ni._gen_rho_evaluator(cell, dma, hermi)[:2]\n    make_rhob       = ni._gen_rho_evaluator(cell, dmb, hermi)[0]\n\n    nelec = numpy.zeros((2,nset))\n    excsum = numpy.zeros(nset)\n    vmata = [0]*nset\n    vmatb = [0]*nset\n    if xctype == 'LDA':\n        ao_deriv = 0\n        for ao_k1, ao_k2, mask, weight, coords \\\n                in ni.block_loop(cell, grids, nao, ao_deriv, kpts, kpts_band,\n                                 max_memory):\n            for i in range(nset):\n                rho_a = make_rhoa(i, ao_k2, mask, xctype)\n                rho_b = make_rhob(i, ao_k2, mask, xctype)\n                exc, vxc = ni.eval_xc(xc_code, (rho_a, rho_b),\n                                      1, relativity, 1, verbose)[:2]\n                vrho = vxc[0]\n                den = rho_a * weight\n                nelec[0,i] += den.sum()\n                excsum[i] += (den*exc).sum()\n                den = rho_b * weight\n                nelec[1,i] += den.sum()\n                excsum[i] += (den*exc).sum()\n\n                vmata[i] += ni.eval_mat(cell, ao_k1, weight, rho_a, vrho[:,0],\n                                        mask, xctype, 1, verbose)\n                vmatb[i] += ni.eval_mat(cell, ao_k1, weight, rho_b, vrho[:,1],\n                                        mask, xctype, 1, verbose)\n    elif xctype == 'GGA':\n        ao_deriv = 1\n        for ao_k1, ao_k2, mask, weight, coords \\\n                in ni.block_loop(cell, grids, nao, ao_deriv, kpts,\n                                 kpts_band, max_memory):\n            for i in range(nset):\n                rho_a = make_rhoa(i, ao_k2, mask, xctype)\n                rho_b = make_rhob(i, ao_k2, mask, xctype)\n                exc, vxc = ni.eval_xc(xc_code, (rho_a, rho_b),\n                                      1, relativity, 1, verbose)[:2]\n                vrho, vsigma = vxc[:2]\n                den = rho_a[0]*weight\n                nelec[0,i] += den.sum()\n                excsum[i] += (den*exc).sum()\n                den = rho_b[0]*weight\n                nelec[1,i] += den.sum()\n                excsum[i] += (den*exc).sum()\n\n                vmata[i] += ni.eval_mat(cell, ao_k1, weight, (rho_a,rho_b),\n                                        (vrho[:,0], (vsigma[:,0],vsigma[:,1])),\n                                        mask, xctype, 1, verbose)\n                vmatb[i] += ni.eval_mat(cell, ao_k1, weight, (rho_b,rho_a),\n                                        (vrho[:,1], (vsigma[:,2],vsigma[:,1])),\n                                        mask, xctype, 1, verbose)\n    elif xctype == 'MGGA':\n        assert(all(x not in xc_code.upper() for x in ('CC06', 'CS', 'BR89', 'MK00')))\n        ao_deriv = 2\n        for ao_k1, ao_k2, mask, weight, coords \\\n                in ni.block_loop(cell, grids, nao, ao_deriv, kpts, kpts_band,\n                                 max_memory):\n            for i in range(nset):\n                rho_a = make_rhoa(i, ao_k2, mask, xctype)\n                rho_b = make_rhob(i, ao_k2, mask, xctype)\n                exc, vxc = ni.eval_xc(xc_code, (rho_a, rho_b),\n                                      1, relativity, 1, verbose)[:2]\n                vrho, vsigma, vlapl, vtau = vxc\n                den = rho_a[0]*weight\n                nelec[0,i] += den.sum()\n                excsum[i] += (den*exc).sum()\n                den = rho_b[0]*weight\n                nelec[1,i] += den.sum()\n                excsum[i] += (den*exc).sum()\n\n                v = (vrho[:,0], (vsigma[:,0],vsigma[:,1]), None, vtau[:,0])\n                vmata[i] += ni.eval_mat(cell, ao_k1, weight, (rho_a,rho_b), v,\n                                        mask, xctype, 1, verbose)\n                v = (vrho[:,1], (vsigma[:,2],vsigma[:,1]), None, vtau[:,1])\n                vmatb[i] += ni.eval_mat(cell, ao_k1, weight, (rho_b,rho_a), v,\n                                        mask, xctype, 1, verbose)\n                v = None\n\n    if dma.ndim == vmata[0].ndim:  # One set of DMs in the input\n        nelec = nelec[:,0]\n        excsum = excsum[0]\n        vmata = vmata[0]\n        vmatb = vmatb[0]\n    return nelec, excsum, lib.asarray((vmata,vmatb))\n\ndef _format_uks_dm(dms):\n    dma, dmb = dms\n    if getattr(dms, 'mo_coeff', None) is not None:\n#TODO: test whether dm.mo_coeff matching dm\n        mo_coeff = dms.mo_coeff\n        mo_occ = dms.mo_occ\n        if (isinstance(mo_coeff[0], numpy.ndarray) and\n            mo_coeff[0].ndim < dma.ndim): # handle ROKS\n            mo_occa = [numpy.array(occ> 0, dtype=numpy.double) for occ in mo_occ]\n            mo_occb = [numpy.array(occ==2, dtype=numpy.double) for occ in mo_occ]\n            dma = lib.tag_array(dma, mo_coeff=mo_coeff, mo_occ=mo_occa)\n            dmb = lib.tag_array(dmb, mo_coeff=mo_coeff, mo_occ=mo_occb)\n        else:\n            dma = lib.tag_array(dma, mo_coeff=mo_coeff[0], mo_occ=mo_occ[0])\n            dmb = lib.tag_array(dmb, mo_coeff=mo_coeff[1], mo_occ=mo_occ[1])\n    return dma, dmb\n\nnr_rks_vxc = nr_rks\nnr_uks_vxc = nr_uks\n\ndef nr_rks_fxc(ni, cell, grids, xc_code, dm0, dms, relativity=0, hermi=0,\n               rho0=None, vxc=None, fxc=None, kpts=None, max_memory=2000,\n               verbose=None):\n    '''Contract RKS XC kernel matrix with given density matrices\n\n    Args:\n        ni : an instance of :class:`NumInt` or :class:`KNumInt`\n\n        cell : instance of :class:`Mole` or :class:`Cell`\n\n        grids : an instance of :class:`Grids`\n            grids.coords and grids.weights are needed for coordinates and weights of meshgrids.\n        xc_code : str\n            XC functional description.\n            See :func:`parse_xc` of pyscf/dft/libxc.py for more details.\n        dms : 2D/3D array or a list of 2D/3D arrays\n            Density matrices (2D) / density matrices for k-points (3D)\n\n    Kwargs:\n        hermi : int\n            Input density matrices symmetric or not\n        max_memory : int or float\n            The maximum size of cache to use (in MB).\n        rho0 : float array\n            Zero-order density (and density derivative for GGA).  Giving kwargs rho0,\n            vxc and fxc to improve better performance.\n        vxc : float array\n            First order XC derivatives\n        fxc : float array\n            Second order XC derivatives\n\n    Examples:\n\n    '''\n    if kpts is None:\n        kpts = numpy.zeros((1,3))\n    xctype = ni._xc_type(xc_code)\n\n    make_rho, nset, nao = ni._gen_rho_evaluator(cell, dms, hermi)\n    if ((xctype == 'LDA' and fxc is None) or\n        (xctype == 'GGA' and rho0 is None)):\n        make_rho0 = ni._gen_rho_evaluator(cell, dm0, 1)[0]\n\n    ao_loc = cell.ao_loc_nr()\n    vmat = [0] * nset\n    if xctype == 'LDA':\n        ao_deriv = 0\n        ip = 0\n        for ao_k1, ao_k2, mask, weight, coords \\\n                in ni.block_loop(cell, grids, nao, ao_deriv, kpts, None, max_memory):\n            ngrid = weight.size\n            if fxc is None:\n                rho = make_rho0(0, ao_k1, mask, xctype)\n                fxc0 = ni.eval_xc(xc_code, rho, 0, relativity, 2, verbose)[2]\n                frr = fxc0[0]\n            else:\n                frr = fxc[0][ip:ip+ngrid]\n                ip += ngrid\n\n            for i in range(nset):\n                rho1 = make_rho(i, ao_k1, mask, xctype)\n                wv = weight * frr * rho1\n                vmat[i] += ni._fxc_mat(cell, ao_k1, wv, mask, xctype, ao_loc)\n\n    elif xctype == 'GGA':\n        ao_deriv = 1\n        ip = 0\n        for ao_k1, ao_k2, mask, weight, coords \\\n                in ni.block_loop(cell, grids, nao, ao_deriv, kpts, None, max_memory):\n            ngrid = weight.size\n            if rho0 is None:\n                rho = make_rho0(0, ao_k1, mask, xctype)\n            else:\n                rho = numpy.asarray(rho0[:,ip:ip+ngrid], order='C')\n\n            if vxc is None or fxc is None:\n                vxc0, fxc0 = ni.eval_xc(xc_code, rho, 0, relativity, 2, verbose)[1:3]\n            else:\n                vxc0 = (None, vxc[1][ip:ip+ngrid])\n                fxc0 = (fxc[0][ip:ip+ngrid], fxc[1][ip:ip+ngrid], fxc[2][ip:ip+ngrid])\n                ip += ngrid\n\n            for i in range(nset):\n                rho1 = make_rho(i, ao_k1, mask, xctype)\n                wv = _rks_gga_wv1(rho, rho1, vxc0, fxc0, weight)\n                vmat[i] += ni._fxc_mat(cell, ao_k1, wv, mask, xctype, ao_loc)\n\n        # call swapaxes method to swap last two indices because vmat may be a 3D\n        # array (nset,nao,nao) in single k-point mode or a 4D array\n        # (nset,nkpts,nao,nao) in k-points mode\n        for i in range(nset):  # for (\\nabla\\mu) \\nu + \\mu (\\nabla\\nu)\n            vmat[i] = vmat[i] + vmat[i].swapaxes(-2,-1).conj()\n\n    elif xctype == 'MGGA':\n        raise NotImplementedError('meta-GGA')\n\n    if isinstance(dms, numpy.ndarray) and dms.ndim == vmat[0].ndim:\n        # One set of DMs in the input\n        vmat = vmat[0]\n    return lib.asarray(vmat)\n\ndef nr_rks_fxc_st(ni, cell, grids, xc_code, dm0, dms_alpha, relativity=0, singlet=True,\n                  rho0=None, vxc=None, fxc=None, kpts=None, max_memory=2000,\n                  verbose=None):\n    '''Associated to singlet or triplet Hessian\n    Note the difference to nr_rks_fxc, dms_alpha is the response density\n    matrices of alpha spin, alpha+/-beta DM is applied due to singlet/triplet\n    coupling\n\n    Ref. CPL, 256, 454\n    '''\n    if kpts is None:\n        kpts = numpy.zeros((1,3))\n    xctype = ni._xc_type(xc_code)\n\n    make_rho, nset, nao = ni._gen_rho_evaluator(cell, dms_alpha)\n    if ((xctype == 'LDA' and fxc is None) or\n        (xctype == 'GGA' and rho0 is None)):\n        make_rho0 = ni._gen_rho_evaluator(cell, dm0, 1)[0]\n\n    ao_loc = cell.ao_loc_nr()\n    vmat = [0] * nset\n    if xctype == 'LDA':\n        ao_deriv = 0\n        ip = 0\n        for ao_k1, ao_k2, mask, weight, coords \\\n                in ni.block_loop(cell, grids, nao, ao_deriv, kpts, None, max_memory):\n            ngrid = weight.size\n            if fxc is None:\n                rho = make_rho0(0, ao_k1, mask, xctype)\n                rho *= .5  # alpha density\n                fxc0 = ni.eval_xc(xc_code, (rho,rho), 1, deriv=2)[2]\n                u_u, u_d, d_d = fxc0[0].T\n            else:\n                u_u, u_d, d_d = fxc[0][ip:ip+ngrid].T\n                ip += ngrid\n            if singlet:\n                frho = u_u + u_d\n            else:\n                frho = u_u - u_d\n\n            for i in range(nset):\n                rho1 = make_rho(i, ao_k1, mask, xctype)\n                wv = weight * frho * rho1\n                vmat[i] += ni._fxc_mat(cell, ao_k1, wv, mask, xctype, ao_loc)\n\n    elif xctype == 'GGA':\n        ao_deriv = 1\n        ip = 0\n        for ao_k1, ao_k2, mask, weight, coords \\\n                in ni.block_loop(cell, grids, nao, ao_deriv, kpts, None, max_memory):\n            ngrid = weight.size\n            if vxc is None or fxc is None:\n                rho = make_rho0(0, ao_k1, mask, xctype)\n                rho *= .5  # alpha density\n                vxc0, fxc0 = ni.eval_xc(xc_code, (rho,rho), 1, deriv=2)[1:3]\n\n                vsigma = vxc0[1].T\n                u_u, u_d, d_d = fxc0[0].T  # v2rho2\n                u_uu, u_ud, u_dd, d_uu, d_ud, d_dd = fxc0[1].T  # v2rhosigma\n                uu_uu, uu_ud, uu_dd, ud_ud, ud_dd, dd_dd = fxc0[2].T  # v2sigma2\n            else:\n                rho = rho0[0][:,ip:ip+ngrid]\n                vsigma = vxc[1][ip:ip+ngrid].T\n                u_u, u_d, d_d = fxc[0][ip:ip+ngrid].T  # v2rho2\n                u_uu, u_ud, u_dd, d_uu, d_ud, d_dd = fxc[1][ip:ip+ngrid].T  # v2rhosigma\n                uu_uu, uu_ud, uu_dd, ud_ud, ud_dd, dd_dd = fxc[2][ip:ip+ngrid].T  # v2sigma2\n\n            if singlet:\n                fgamma = vsigma[0] + vsigma[1] * .5\n                frho = u_u + u_d\n                fgg = uu_uu + .5*ud_ud + 2*uu_ud + uu_dd\n                frhogamma = u_uu + u_dd + u_ud\n            else:\n                fgamma = vsigma[0] - vsigma[1] * .5\n                frho = u_u - u_d\n                fgg = uu_uu - uu_dd\n                frhogamma = u_uu - u_dd\n\n            for i in range(nset):\n                # rho1[0 ] = |b><j| z_{bj}\n                # rho1[1:] = \\nabla(|b><j|) z_{bj}\n                rho1 = make_rho(i, ao_k1, mask, xctype)\n                wv = _rks_gga_wv1(rho, rho1, (None,fgamma),\n                                  (frho,frhogamma,fgg), weight)\n                vmat[i] += ni._fxc_mat(cell, ao_k1, wv, mask, xctype, ao_loc)\n\n        for i in range(nset):  # for (\\nabla\\mu) \\nu + \\mu (\\nabla\\nu)\n            vmat[i] = vmat[i] + vmat[i].swapaxes(-2,-1).conj()\n\n    elif xctype == 'MGGA':\n        raise NotImplementedError('meta-GGA')\n\n    if isinstance(dms_alpha, numpy.ndarray) and dms_alpha.ndim == vmat[0].ndim:\n        vmat = vmat[0]\n    return lib.asarray(vmat)\n\n\ndef nr_uks_fxc(ni, cell, grids, xc_code, dm0, dms, relativity=0, hermi=0,\n               rho0=None, vxc=None, fxc=None, kpts=None, max_memory=2000,\n               verbose=None):\n    '''Contract UKS XC kernel matrix with given density matrices\n\n    Args:\n        ni : an instance of :class:`NumInt` or :class:`KNumInt`\n\n        cell : instance of :class:`Mole` or :class:`Cell`\n\n        grids : an instance of :class:`Grids`\n            grids.coords and grids.weights are needed for coordinates and weights of meshgrids.\n        xc_code : str\n            XC functional description.\n            See :func:`parse_xc` of pyscf/dft/libxc.py for more details.\n        dms : 2D array a list of 2D arrays\n            Density matrix or multiple density matrices\n\n    Kwargs:\n        hermi : int\n            Input density matrices symmetric or not\n        max_memory : int or float\n            The maximum size of cache to use (in MB).\n        rho0 : float array\n            Zero-order density (and density derivative for GGA).  Giving kwargs rho0,\n            vxc and fxc to improve better performance.\n        vxc : float array\n            First order XC derivatives\n        fxc : float array\n            Second order XC derivatives\n\n    Returns:\n        nelec, excsum, vmat.\n        nelec is the number of electrons generated by numerical integration.\n        excsum is the XC functional value.  vmat is the XC potential matrix in\n        2D array of shape (nao,nao) where nao is the number of AO functions.\n\n    Examples:\n\n    '''\n    if kpts is None:\n        kpts = numpy.zeros((1,3))\n    xctype = ni._xc_type(xc_code)\n\n    dma, dmb = _format_uks_dm(dms)\n    nao = dma.shape[-1]\n    make_rhoa, nset = ni._gen_rho_evaluator(cell, dma, hermi)[:2]\n    make_rhob       = ni._gen_rho_evaluator(cell, dmb, hermi)[0]\n\n    if ((xctype == 'LDA' and fxc is None) or\n        (xctype == 'GGA' and rho0 is None)):\n        dm0a, dm0b = _format_uks_dm(dm0)\n        make_rho0a = ni._gen_rho_evaluator(cell, dm0a, 1)[0]\n        make_rho0b = ni._gen_rho_evaluator(cell, dm0b, 1)[0]\n\n    shls_slice = (0, cell.nbas)\n    ao_loc = cell.ao_loc_nr()\n\n    vmata = [0] * nset\n    vmatb = [0] * nset\n    if xctype == 'LDA':\n        ao_deriv = 0\n        ip = 0\n        for ao_k1, ao_k2, mask, weight, coords \\\n                in ni.block_loop(cell, grids, nao, ao_deriv, kpts, None, max_memory):\n            ngrid = weight.size\n            if fxc is None:\n                rho0a = make_rho0a(0, ao_k1, mask, xctype)\n                rho0b = make_rho0b(0, ao_k1, mask, xctype)\n                fxc0 = ni.eval_xc(xc_code, (rho0a,rho0b), 1, relativity, 2, verbose)[2]\n                u_u, u_d, d_d = fxc0[0].T\n            else:\n                u_u, u_d, d_d = fxc[0][ip:ip+ngrid].T\n                ip += ngrid\n\n            for i in range(nset):\n                rho1a = make_rhoa(i, ao_k1, mask, xctype)\n                rho1b = make_rhob(i, ao_k1, mask, xctype)\n                wv = u_u * rho1a + u_d * rho1b\n                wv *= weight\n                vmata[i] += ni._fxc_mat(cell, ao_k1, wv, mask, xctype, ao_loc)\n                wv = u_d * rho1a + d_d * rho1b\n                wv *= weight\n                vmatb[i] += ni._fxc_mat(cell, ao_k1, wv, mask, xctype, ao_loc)\n\n    elif xctype == 'GGA':\n        ao_deriv = 1\n        ip = 0\n        for ao_k1, ao_k2, mask, weight, coords \\\n                in ni.block_loop(cell, grids, nao, ao_deriv, kpts, None, max_memory):\n            ngrid = weight.size\n            if rho0 is None:\n                rho0a = make_rho0a(0, ao_k1, mask, xctype)\n                rho0b = make_rho0b(0, ao_k1, mask, xctype)\n            else:\n                rho0a = rho0[0][:,ip:ip+ngrid]\n                rho0b = rho0[1][:,ip:ip+ngrid]\n            if vxc is None or fxc is None:\n                vxc0, fxc0 = ni.eval_xc(xc_code, (rho0a,rho0b), 1, relativity, 2, verbose)[1:3]\n            else:\n                vxc0 = (None, vxc[1][ip:ip+ngrid])\n                fxc0 = (fxc[0][ip:ip+ngrid], fxc[1][ip:ip+ngrid], fxc[2][ip:ip+ngrid])\n                ip += ngrid\n\n            for i in range(nset):\n                rho1a = make_rhoa(i, ao_k1, mask, xctype)\n                rho1b = make_rhob(i, ao_k1, mask, xctype)\n                wva, wvb = _uks_gga_wv1((rho0a,rho0b), (rho1a,rho1b),\n                                        vxc0, fxc0, weight)\n                vmata[i] += ni._fxc_mat(cell, ao_k1, wva, mask, xctype, ao_loc)\n                vmatb[i] += ni._fxc_mat(cell, ao_k1, wvb, mask, xctype, ao_loc)\n\n        for i in range(nset):  # for (\\nabla\\mu) \\nu + \\mu (\\nabla\\nu)\n            vmata[i] = vmata[i] + vmata[i].swapaxes(-1,-2).conj()\n            vmatb[i] = vmatb[i] + vmatb[i].swapaxes(-1,-2).conj()\n    elif xctype == 'MGGA':\n        raise NotImplementedError('meta-GGA')\n\n    if dma.ndim == vmata[0].ndim:  # One set of DMs in the input\n        vmata = vmata[0]\n        vmatb = vmatb[0]\n    return lib.asarray((vmata,vmatb))\n\ndef _fxc_mat(cell, ao, wv, non0tab, xctype, ao_loc):\n    shls_slice = (0, cell.nbas)\n\n    if xctype == 'LDA' or xctype == 'HF':\n        #:aow = numpy.einsum('pi,p->pi', ao, wv)\n        aow = _scale_ao(ao, wv)\n        mat = _dot_ao_ao(cell, ao, aow, non0tab, shls_slice, ao_loc)\n    else:\n        #:aow = numpy.einsum('npi,np->pi', ao, wv)\n        aow = _scale_ao(ao, wv)\n        mat = _dot_ao_ao(cell, ao[0], aow, non0tab, shls_slice, ao_loc)\n    return mat\n\ndef cache_xc_kernel(ni, cell, grids, xc_code, mo_coeff, mo_occ, spin=0,\n                    kpts=None, max_memory=2000):\n    '''Compute the 0th order density, Vxc and fxc.  They can be used in TDDFT,\n    DFT hessian module etc.\n    '''\n    if kpts is None:\n        kpts = numpy.zeros((1,3))\n    xctype = ni._xc_type(xc_code)\n    ao_deriv = 0\n    if xctype == 'GGA':\n        ao_deriv = 1\n    elif xctype == 'MGGA':\n        raise NotImplementedError('meta-GGA')\n\n    nao = cell.nao_nr()\n    if spin == 0:\n        rho = []\n        for ao_k1, ao_k2, mask, weight, coords \\\n                in ni.block_loop(cell, grids, nao, ao_deriv, kpts, None, max_memory):\n            rho.append(ni.eval_rho2(cell, ao_k1, mo_coeff, mo_occ, mask, xctype))\n        rho = numpy.hstack(rho)\n    else:\n        rhoa = []\n        rhob = []\n        for ao_k1, ao_k2, mask, weight, coords \\\n                in ni.block_loop(cell, grids, nao, ao_deriv, kpts, None, max_memory):\n            rhoa.append(ni.eval_rho2(cell, ao_k1, mo_coeff[0], mo_occ[0], mask, xctype))\n            rhob.append(ni.eval_rho2(cell, ao_k1, mo_coeff[1], mo_occ[1], mask, xctype))\n        rho = (numpy.hstack(rhoa), numpy.hstack(rhob))\n    vxc, fxc = ni.eval_xc(xc_code, rho, spin, 0, 2, 0)[1:3]\n    return rho, vxc, fxc\n\n\ndef get_rho(ni, cell, dm, grids, kpts=numpy.zeros((1,3)), max_memory=2000):\n    '''Density in real space\n    '''\n    make_rho, nset, nao = ni._gen_rho_evaluator(cell, dm)\n    assert(nset == 1)\n    rho = numpy.empty(grids.weights.size)\n    p1 = 0\n    for ao_k1, ao_k2, mask, weight, coords \\\n            in ni.block_loop(cell, grids, nao, 0, kpts, None, max_memory):\n        p0, p1 = p1, p1 + weight.size\n        rho[p0:p1] = make_rho(0, ao_k1, mask, 'LDA')\n    return rho\n\n\nclass NumInt(numint.NumInt):\n    '''Generalization of pyscf's NumInt class for a single k-point shift and\n    periodic images.\n    '''\n    def eval_ao(self, cell, coords, kpt=numpy.zeros(3), deriv=0, relativity=0,\n                shls_slice=None, non0tab=None, out=None, verbose=None):\n        return eval_ao(cell, coords, kpt, deriv, relativity, shls_slice,\n                       non0tab, out, verbose)\n\n    @lib.with_doc(make_mask.__doc__)\n    def make_mask(self, cell, coords, relativity=0, shls_slice=None,\n                  verbose=None):\n        return make_mask(cell, coords, relativity, shls_slice, verbose)\n\n    @lib.with_doc(eval_rho.__doc__)\n    def eval_rho(self, cell, ao, dm, non0tab=None, xctype='LDA', hermi=0, verbose=None):\n        return eval_rho(cell, ao, dm, non0tab, xctype, hermi, verbose)\n\n    def eval_rho2(self, cell, ao, mo_coeff, mo_occ, non0tab=None, xctype='LDA',\n                  verbose=None):\n        return eval_rho2(cell, ao, mo_coeff, mo_occ, non0tab, xctype, verbose)\n\n    def nr_vxc(self, cell, grids, xc_code, dms, spin=0, relativity=0, hermi=0,\n               kpt=None, kpts_band=None, max_memory=2000, verbose=None):\n        '''Evaluate RKS/UKS XC functional and potential matrix.\n        See :func:`nr_rks` and :func:`nr_uks` for more details.\n        '''\n        if spin == 0:\n            return self.nr_rks(cell, grids, xc_code, dms, hermi,\n                               kpt, kpts_band, max_memory, verbose)\n        else:\n            return self.nr_uks(cell, grids, xc_code, dms, hermi,\n                               kpt, kpts_band, max_memory, verbose)\n\n    @lib.with_doc(nr_rks.__doc__)\n    def nr_rks(self, cell, grids, xc_code, dms, hermi=0,\n               kpt=numpy.zeros(3), kpts_band=None, max_memory=2000, verbose=None):\n        if kpts_band is not None:\n# To compute Vxc on kpts_band, convert the NumInt object to KNumInt object.\n            ni = KNumInt()\n            ni.__dict__.update(self.__dict__)\n            nao = dms.shape[-1]\n            return ni.nr_rks(cell, grids, xc_code, dms.reshape(-1,1,nao,nao),\n                             hermi, kpt.reshape(1,3), kpts_band, max_memory,\n                             verbose)\n        return nr_rks(self, cell, grids, xc_code, dms,\n                      0, 0, hermi, kpt, kpts_band, max_memory, verbose)\n\n    @lib.with_doc(nr_uks.__doc__)\n    def nr_uks(self, cell, grids, xc_code, dms, hermi=0,\n               kpt=numpy.zeros(3), kpts_band=None, max_memory=2000, verbose=None):\n        if kpts_band is not None:\n# To compute Vxc on kpts_band, convert the NumInt object to KNumInt object.\n            ni = KNumInt()\n            ni.__dict__.update(self.__dict__)\n            nao = dms[0].shape[-1]\n            return ni.nr_uks(cell, grids, xc_code, dms.reshape(-1,1,nao,nao),\n                             hermi, kpt.reshape(1,3), kpts_band, max_memory,\n                             verbose)\n        return nr_uks(self, cell, grids, xc_code, dms,\n                      1, 0, hermi, kpt, kpts_band, max_memory, verbose)\n\n    def eval_mat(self, cell, ao, weight, rho, vxc,\n                 non0tab=None, xctype='LDA', spin=0, verbose=None):\n# Guess whether ao is evaluated for kpts_band.  When xctype is LDA, ao on grids\n# should be a 2D array.  For other xc functional, ao should be a 3D array.\n        if ao.ndim == 2 or (xctype != 'LDA' and ao.ndim == 3):\n            mat = eval_mat(cell, ao, weight, rho, vxc, non0tab, xctype, spin, verbose)\n        else:\n            nkpts = len(ao)\n            nao = ao[0].shape[-1]\n            mat = numpy.empty((nkpts,nao,nao), dtype=numpy.complex128)\n            for k in range(nkpts):\n                mat[k] = eval_mat(cell, ao[k], weight, rho, vxc,\n                                  non0tab, xctype, spin, verbose)\n        return mat\n\n    def _fxc_mat(self, cell, ao, wv, non0tab, xctype, ao_loc):\n        return _fxc_mat(cell, ao, wv, non0tab, xctype, ao_loc)\n\n    def block_loop(self, cell, grids, nao, deriv=0, kpt=numpy.zeros(3),\n                   kpts_band=None, max_memory=2000, non0tab=None, blksize=None):\n        '''Define this macro to loop over grids by blocks.\n        '''\n# For UniformGrids, grids.coords does not indicate whehter grids are initialized\n        if grids.non0tab is None:\n            grids.build(with_non0tab=True)\n        grids_coords = grids.coords\n        grids_weights = grids.weights\n        ngrids = grids_coords.shape[0]\n        comp = (deriv+1)*(deriv+2)*(deriv+3)//6\n# NOTE to index grids.non0tab, the blksize needs to be the integer multiplier of BLKSIZE\n        if blksize is None:\n            blksize = int(max_memory*1e6/(comp*2*nao*16*BLKSIZE))*BLKSIZE\n            blksize = max(BLKSIZE, min(blksize, ngrids, BLKSIZE*1200))\n        if non0tab is None:\n            non0tab = grids.non0tab\n        if non0tab is None:\n            non0tab = numpy.empty(((ngrids+BLKSIZE-1)//BLKSIZE,cell.nbas),\n                                  dtype=numpy.uint8)\n            non0tab[:] = 0xff\n        kpt = numpy.reshape(kpt, 3)\n        if kpts_band is None:\n            kpt1 = kpt2 = kpt\n        else:\n            kpt1 = kpts_band\n            kpt2 = kpt\n\n        for ip0 in range(0, ngrids, blksize):\n            ip1 = min(ngrids, ip0+blksize)\n            coords = grids_coords[ip0:ip1]\n            weight = grids_weights[ip0:ip1]\n            non0 = non0tab[ip0//BLKSIZE:]\n            ao_k2 = self.eval_ao(cell, coords, kpt2, deriv=deriv, non0tab=non0)\n            if abs(kpt1-kpt2).sum() < 1e-9:\n                ao_k1 = ao_k2\n            else:\n                ao_k1 = self.eval_ao(cell, coords, kpt1, deriv=deriv)\n            yield ao_k1, ao_k2, non0, weight, coords\n            ao_k1 = ao_k2 = None\n\n    def _gen_rho_evaluator(self, cell, dms, hermi=0):\n        return numint.NumInt._gen_rho_evaluator(self, cell, dms, hermi)\n\n    nr_rks_fxc = nr_rks_fxc\n    nr_uks_fxc = nr_uks_fxc\n    cache_xc_kernel  = cache_xc_kernel\n    get_rho = get_rho\n\n    def rsh_and_hybrid_coeff(self, xc_code, spin=0):\n        omega, alpha, hyb = numint.NumInt.rsh_and_hybrid_coeff(self, xc_code, spin)\n        if abs(omega) > 1e-10:\n            raise NotImplementedError\n        return omega, alpha, hyb\n_NumInt = NumInt\n\n\nclass KNumInt(numint.NumInt):\n    '''Generalization of pyscf's NumInt class for k-point sampling and\n    periodic images.\n    '''\n    def __init__(self, kpts=numpy.zeros((1,3))):\n        numint.NumInt.__init__(self)\n        self.kpts = numpy.reshape(kpts, (-1,3))\n\n    def eval_ao(self, cell, coords, kpts=numpy.zeros((1,3)), deriv=0, relativity=0,\n                shls_slice=None, non0tab=None, out=None, verbose=None, **kwargs):\n        return eval_ao_kpts(cell, coords, kpts, deriv,\n                            relativity, shls_slice, non0tab, out, verbose)\n\n    @lib.with_doc(make_mask.__doc__)\n    def make_mask(self, cell, coords, relativity=0, shls_slice=None,\n                  verbose=None):\n        return make_mask(cell, coords, relativity, shls_slice, verbose)\n\n    def eval_rho(self, cell, ao_kpts, dm_kpts, non0tab=None, xctype='LDA',\n                 hermi=0, verbose=None):\n        '''Collocate the *real* density (opt. gradients) on the real-space grid.\n\n        Args:\n            cell : Mole or Cell object\n            ao_kpts : (nkpts, ngrids, nao) ndarray\n                AO values at each k-point\n            dm_kpts: (nkpts, nao, nao) ndarray\n                Density matrix at each k-point\n\n        Returns:\n           rhoR : (ngrids,) ndarray\n        '''\n        nkpts = len(ao_kpts)\n        rhoR = 0\n        for k in range(nkpts):\n            rhoR += eval_rho(cell, ao_kpts[k], dm_kpts[k], non0tab, xctype,\n                             hermi, verbose)\n        rhoR *= 1./nkpts\n        return rhoR\n\n    def eval_rho2(self, cell, ao_kpts, mo_coeff_kpts, mo_occ_kpts,\n                  non0tab=None, xctype='LDA', verbose=None):\n        nkpts = len(ao_kpts)\n        rhoR = 0\n        for k in range(nkpts):\n            rhoR += eval_rho2(cell, ao_kpts[k], mo_coeff_kpts[k],\n                              mo_occ_kpts[k], non0tab, xctype, verbose)\n        rhoR *= 1./nkpts\n        return rhoR\n\n    def nr_vxc(self, cell, grids, xc_code, dms, spin=0, relativity=0, hermi=0,\n               kpts=None, kpts_band=None, max_memory=2000, verbose=None):\n        '''Evaluate RKS/UKS XC functional and potential matrix.\n        See :func:`nr_rks` and :func:`nr_uks` for more details.\n        '''\n        if spin == 0:\n            return self.nr_rks(cell, grids, xc_code, dms, hermi,\n                               kpts, kpts_band, max_memory, verbose)\n        else:\n            return self.nr_uks(cell, grids, xc_code, dms, hermi,\n                               kpts, kpts_band, max_memory, verbose)\n\n    @lib.with_doc(nr_rks.__doc__)\n    def nr_rks(self, cell, grids, xc_code, dms, hermi=0, kpts=None, kpts_band=None,\n               max_memory=2000, verbose=None, **kwargs):\n        if kpts is None:\n            if 'kpt' in kwargs:\n                sys.stderr.write('WARN: KNumInt.nr_rks function finds keyword '\n                                 'argument \"kpt\" and converts it to \"kpts\"\\n')\n                kpts = kwargs['kpt']\n            else:\n                kpts = self.kpts\n        kpts = kpts.reshape(-1,3)\n\n        return nr_rks(self, cell, grids, xc_code, dms, 0, 0,\n                      hermi, kpts, kpts_band, max_memory, verbose)\n\n    @lib.with_doc(nr_uks.__doc__)\n    def nr_uks(self, cell, grids, xc_code, dms, hermi=0, kpts=None, kpts_band=None,\n               max_memory=2000, verbose=None, **kwargs):\n        if kpts is None:\n            if 'kpt' in kwargs:\n                sys.stderr.write('WARN: KNumInt.nr_uks function finds keyword '\n                                 'argument \"kpt\" and converts it to \"kpts\"\\n')\n                kpts = kwargs['kpt']\n            else:\n                kpts = self.kpts\n        kpts = kpts.reshape(-1,3)\n\n        return nr_uks(self, cell, grids, xc_code, dms, 1, 0,\n                      hermi, kpts, kpts_band, max_memory, verbose)\n\n    def eval_mat(self, cell, ao_kpts, weight, rho, vxc,\n                 non0tab=None, xctype='LDA', spin=0, verbose=None):\n        nkpts = len(ao_kpts)\n        nao = ao_kpts[0].shape[-1]\n        dtype = numpy.result_type(*ao_kpts)\n        mat = numpy.empty((nkpts,nao,nao), dtype=dtype)\n        for k in range(nkpts):\n            mat[k] = eval_mat(cell, ao_kpts[k], weight, rho, vxc,\n                              non0tab, xctype, spin, verbose)\n        return mat\n\n    def _fxc_mat(self, cell, ao_kpts, wv, non0tab, xctype, ao_loc):\n        nkpts = len(ao_kpts)\n        nao = ao_kpts[0].shape[-1]\n        dtype = numpy.result_type(*ao_kpts)\n        mat = numpy.empty((nkpts,nao,nao), dtype=dtype)\n        for k in range(nkpts):\n            mat[k] = _fxc_mat(cell, ao_kpts[k], wv, non0tab, xctype, ao_loc)\n        return mat\n\n    def block_loop(self, cell, grids, nao, deriv=0, kpts=numpy.zeros((1,3)),\n                   kpts_band=None, max_memory=2000, non0tab=None, blksize=None):\n        '''Define this macro to loop over grids by blocks.\n        '''\n        if grids.coords is None:\n            grids.build(with_non0tab=True)\n        grids_coords = grids.coords\n        grids_weights = grids.weights\n        ngrids = grids_coords.shape[0]\n        nkpts = len(kpts)\n        comp = (deriv+1)*(deriv+2)*(deriv+3)//6\n# NOTE to index grids.non0tab, the blksize needs to be the integer multiplier of BLKSIZE\n        if blksize is None:\n            blksize = int(max_memory*1e6/(comp*2*nkpts*nao*16*BLKSIZE))*BLKSIZE\n            blksize = max(BLKSIZE, min(blksize, ngrids, BLKSIZE*1200))\n        if non0tab is None:\n            non0tab = grids.non0tab\n        if non0tab is None:\n            non0tab = numpy.empty(((ngrids+BLKSIZE-1)//BLKSIZE,cell.nbas),\n                                  dtype=numpy.uint8)\n            non0tab[:] = 0xff\n        if kpts_band is not None:\n            kpts_band = numpy.reshape(kpts_band, (-1,3))\n            where = [member(k, kpts) for k in kpts_band]\n            where = [k_id[0] if len(k_id)>0 else None for k_id in where]\n\n        for ip0 in range(0, ngrids, blksize):\n            ip1 = min(ngrids, ip0+blksize)\n            coords = grids_coords[ip0:ip1]\n            weight = grids_weights[ip0:ip1]\n            non0 = non0tab[ip0//BLKSIZE:]\n            ao_k1 = ao_k2 = self.eval_ao(cell, coords, kpts, deriv=deriv, non0tab=non0)\n            if kpts_band is not None:\n                ao_k1 = self.eval_ao(cell, coords, kpts_band, deriv=deriv, non0tab=non0)\n            yield ao_k1, ao_k2, non0, weight, coords\n            ao_k1 = ao_k2 = None\n\n    def _gen_rho_evaluator(self, cell, dms, hermi=0):\n        if getattr(dms, 'mo_coeff', None) is not None:\n            mo_coeff = dms.mo_coeff\n            mo_occ = dms.mo_occ\n            if isinstance(dms[0], numpy.ndarray) and dms[0].ndim == 2:\n                mo_coeff = [mo_coeff]\n                mo_occ = [mo_occ]\n            nao = cell.nao_nr()\n            ndms = len(mo_occ)\n            def make_rho(idm, ao, non0tab, xctype):\n                return self.eval_rho2(cell, ao, mo_coeff[idm], mo_occ[idm],\n                                      non0tab, xctype)\n        else:\n            if isinstance(dms[0], numpy.ndarray) and dms[0].ndim == 2:\n                dms = [numpy.stack(dms)]\n            #if not hermi:\n            # Density (or response of density) is always real for DFT.\n            # Symmetrizing DM for gamma point should not change the value of\n            # density. However, when k-point is considered, unless dm and\n            # dm.conj().transpose produce the same real part of density, the\n            # symmetrization code below may be incorrect (proof is needed).\n            #    # dm.shape = (nkpts, nao, nao)\n            #    dms = [(dm+dm.conj().transpose(0,2,1))*.5 for dm in dms]\n            nao = dms[0].shape[-1]\n            ndms = len(dms)\n            def make_rho(idm, ao_kpts, non0tab, xctype):\n                return self.eval_rho(cell, ao_kpts, dms[idm], non0tab, xctype,\n                                     hermi=hermi)\n        return make_rho, ndms, nao\n\n    nr_rks_fxc = nr_rks_fxc\n    nr_uks_fxc = nr_uks_fxc\n    cache_xc_kernel  = cache_xc_kernel\n    get_rho = get_rho\n\n    def rsh_and_hybrid_coeff(self, xc_code, spin=0):\n        omega, alpha, hyb = numint.NumInt.rsh_and_hybrid_coeff(self, xc_code, spin)\n        if abs(omega) > 1e-10:\n            raise NotImplementedError\n        return omega, alpha, hyb\n_KNumInt = KNumInt\n", "meta": {"hexsha": "9c267b8e26b6887484ca3e1c5f28fc8d09e2adb2", "size": 51943, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/pbc/dft/numint.py", "max_stars_repo_name": "robert-anderson/pyscf", "max_stars_repo_head_hexsha": "cdc56e168cb15f47e8cdc791a92d689fa9b655af", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-05-28T05:25:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-09T02:16:43.000Z", "max_issues_repo_path": "pyscf/pbc/dft/numint.py", "max_issues_repo_name": "robert-anderson/pyscf", "max_issues_repo_head_hexsha": "cdc56e168cb15f47e8cdc791a92d689fa9b655af", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-09-16T17:58:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-22T17:26:01.000Z", "max_forks_repo_path": "pyscf/pbc/dft/numint.py", "max_forks_repo_name": "robert-anderson/pyscf", "max_forks_repo_head_hexsha": "cdc56e168cb15f47e8cdc791a92d689fa9b655af", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-09T02:13:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-09T02:13:16.000Z", "avg_line_length": 41.3558917197, "max_line_length": 95, "alphanum_fraction": 0.5456365632, "include": true, "reason": "import numpy", "num_tokens": 15472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.35220179564702847, "lm_q1q2_score": 0.19935274962228713}}
{"text": "# Copyright 2019-2021 Cambridge Quantum Computing\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Methods to allow tket circuits to be ran on ProjectQ simulator\n\"\"\"\n\nfrom typing import TYPE_CHECKING, Iterable, List, Optional\nfrom uuid import uuid4\nfrom logging import warning\n\nimport numpy as np\nimport projectq  # type: ignore\nfrom projectq import MainEngine\nfrom projectq.backends import Simulator  # type: ignore\nfrom projectq.cengines import ForwarderEngine  # type: ignore\nfrom pytket.circuit import Circuit, OpType  # type: ignore\nfrom pytket.circuit import Qubit  # type: ignore\nfrom pytket.backends import (\n    Backend,\n    CircuitNotRunError,\n    ResultHandle,\n    CircuitStatus,\n    StatusEnum,\n)\nfrom pytket.backends.resulthandle import _ResultIdTuple\nfrom pytket.backends.backendresult import BackendResult\nfrom pytket.passes import (  # type: ignore\n    BasePass,\n    RebaseProjectQ,\n    SequencePass,\n    SynthesiseIBM,\n    FullPeepholeOptimise,\n    DecomposeBoxes,\n    FlattenRegisters,\n)\nfrom pytket.pauli import QubitPauliString  # type: ignore\nfrom pytket.predicates import (  # type: ignore\n    NoSymbolsPredicate,\n    NoMidMeasurePredicate,\n    GateSetPredicate,\n    NoClassicalControlPredicate,\n    NoFastFeedforwardPredicate,\n    DefaultRegisterPredicate,\n    Predicate,\n)\nfrom pytket.extensions.projectq.projectq_convert import tk_to_projectq\nfrom pytket.utils.operators import QubitPauliOperator\nfrom pytket.utils.results import KwargTypes\n\nif TYPE_CHECKING:\n    from pytket.device import Device  # type: ignore\n\n\ndef _default_q_index(q: Qubit) -> int:\n    if q.reg_name != \"q\" or len(q.index) != 1:\n        raise ValueError(\"Non-default qubit register\")\n    return int(q.index[0])\n\n\nclass ProjectQBackend(Backend):\n    \"\"\"Backend for running statevector simulations on the ProjectQ simulator.\"\"\"\n\n    _supports_state = True\n    _supports_expectation = True\n    _expectation_allows_nonhermitian = False\n    _persistent_handles = False\n\n    @property\n    def _result_id_type(self) -> _ResultIdTuple:\n        return (str,)\n\n    @property\n    def device(self) -> \"Optional[Device]\":\n        return None\n\n    @property\n    def required_predicates(self) -> List[Predicate]:\n        return [\n            NoClassicalControlPredicate(),\n            NoFastFeedforwardPredicate(),\n            NoSymbolsPredicate(),\n            NoMidMeasurePredicate(),\n            GateSetPredicate(\n                {\n                    OpType.SWAP,\n                    OpType.CRz,\n                    OpType.CX,\n                    OpType.CZ,\n                    OpType.H,\n                    OpType.X,\n                    OpType.Y,\n                    OpType.Z,\n                    OpType.S,\n                    OpType.T,\n                    OpType.V,\n                    OpType.Rx,\n                    OpType.Ry,\n                    OpType.Rz,\n                    OpType.Barrier,\n                }\n            ),\n            DefaultRegisterPredicate(),\n        ]\n\n    def default_compilation_pass(self, optimisation_level: int = 1) -> BasePass:\n        assert optimisation_level in range(3)\n        if optimisation_level == 0:\n            return SequencePass(\n                [DecomposeBoxes(), FlattenRegisters(), RebaseProjectQ()]\n            )\n        elif optimisation_level == 1:\n            return SequencePass(\n                [\n                    DecomposeBoxes(),\n                    FlattenRegisters(),\n                    SynthesiseIBM(),\n                    RebaseProjectQ(),\n                ]\n            )\n        else:\n            return SequencePass(\n                [\n                    DecomposeBoxes(),\n                    FlattenRegisters(),\n                    FullPeepholeOptimise(),\n                    RebaseProjectQ(),\n                ]\n            )\n\n    def process_circuits(\n        self,\n        circuits: Iterable[Circuit],\n        n_shots: Optional[int] = None,\n        valid_check: bool = True,\n        **kwargs: KwargTypes,\n    ) -> List[ResultHandle]:\n        \"\"\"\n        See :py:meth:`pytket.backends.Backend.process_circuits`.\n        Supported kwargs: `seed`.\n        \"\"\"\n        circuit_list = list(circuits)\n        if valid_check:\n            self._check_all_circuits(circuit_list)\n\n        handle_list = []\n        for circuit in circuit_list:\n            sim = Simulator(rnd_seed=kwargs.get(\"seed\"))\n            fwd = ForwarderEngine(sim)\n            eng = MainEngine(backend=sim, engine_list=[fwd])\n            qureg = eng.allocate_qureg(circuit.n_qubits)\n            tk_to_projectq(eng, qureg, circuit, True)\n            eng.flush()\n            state = np.array(\n                eng.backend.cheat()[1], dtype=complex\n            )  # `cheat()` returns tuple:(a dictionary of qubit indices, statevector)\n            handle = ResultHandle(str(uuid4()))\n            try:\n                phase = float(circuit.phase)\n                coeff = np.exp(phase * np.pi * 1j)\n                state *= coeff\n            except ValueError:\n                warning(\n                    \"Global phase is dependent on a symbolic parameter, so cannot \"\n                    \"adjust for phase\"\n                )\n            implicit_perm = circuit.implicit_qubit_permutation()\n            # reverse qubits as projectq state is dlo\n            res_qubits = [\n                implicit_perm[qb] for qb in sorted(circuit.qubits, reverse=True)\n            ]\n            measures = circuit.n_gates_of_type(OpType.Measure)\n            if measures == 0 and n_shots is not None:\n                backres = self.empty_result(circuit, n_shots=n_shots)\n            else:\n                backres = BackendResult(q_bits=res_qubits, state=state)\n            self._cache[handle] = {\"result\": backres}\n            handle_list.append(handle)\n        return handle_list\n\n    def circuit_status(self, handle: ResultHandle) -> CircuitStatus:\n        if handle in self._cache:\n            return CircuitStatus(StatusEnum.COMPLETED)\n        raise CircuitNotRunError(handle)\n\n    def _expectation_value(\n        self,\n        circuit: Circuit,\n        hamiltonian: projectq.ops.QubitOperator,\n        valid_check: bool = True,\n    ) -> complex:\n        if valid_check and not self.valid_circuit(circuit):\n            raise ValueError(\n                \"Circuits do not satisfy all required predicates for this backend\"\n            )\n        sim = Simulator()\n        fwd = ForwarderEngine(sim)\n        eng = MainEngine(backend=sim, engine_list=[fwd])\n        qureg = eng.allocate_qureg(circuit.n_qubits)\n        tk_to_projectq(eng, qureg, circuit)\n        eng.flush()\n        energy = eng.backend.get_expectation_value(hamiltonian, qureg)\n        return complex(energy)\n\n    def get_pauli_expectation_value(\n        self,\n        state_circuit: Circuit,\n        pauli: QubitPauliString,\n        valid_check: bool = True,\n    ) -> complex:\n        \"\"\"Calculates the expectation value of the given circuit using the built-in\n        ProjectQ functionality\n\n        :param state_circuit: Circuit that generates the desired state\n            :math:`\\\\left|\\\\psi\\\\right>`.\n        :type state_circuit: Circuit\n        :param pauli: Pauli operator\n        :type pauli: QubitPauliString\n        :param valid_check: Explicitly check that the circuit satisfies all required\n            predicates to run on the backend. Defaults to True\n        :type valid_check: bool, optional\n        :return: :math:`\\\\left<\\\\psi | P | \\\\psi \\\\right>`\n        :rtype: complex\n        \"\"\"\n        pauli_tuple = tuple(\n            (_default_q_index(q), p.name) for q, p in pauli.to_dict().items()\n        )\n        return self._expectation_value(\n            state_circuit, projectq.ops.QubitOperator(pauli_tuple), valid_check\n        )\n\n    def get_operator_expectation_value(\n        self,\n        state_circuit: Circuit,\n        operator: QubitPauliOperator,\n        valid_check: bool = True,\n    ) -> complex:\n        \"\"\"Calculates the expectation value of the given circuit with respect to the\n        operator using the built-in ProjectQ functionality\n\n        :param state_circuit: Circuit that generates the desired state\n            :math:`\\\\left|\\\\psi\\\\right>`.\n        :type state_circuit: Circuit\n        :param operator: Operator :math:`H`. Must be Hermitian.\n        :type operator: QubitPauliOperator\n        :param valid_check: Explicitly check that the circuit satisfies all required\n            predicates to run on the backend. Defaults to True\n        :type valid_check: bool, optional\n        :return: :math:`\\\\left<\\\\psi | H | \\\\psi \\\\right>`\n        :rtype: complex\n        \"\"\"\n        ham = projectq.ops.QubitOperator()\n        for term, coeff in operator._dict.items():\n            if type(coeff) is complex and abs(coeff.imag) > 1e-12:\n                raise ValueError(\n                    \"Operator is not Hermitian and cannot be converted to \"\n                    \"`projectq.ops.QubitOperator`.\"\n                )\n            ham += projectq.ops.QubitOperator(\n                tuple((_default_q_index(q), p.name) for q, p in term.to_dict().items()),\n                float(coeff),\n            )\n        return self._expectation_value(state_circuit, ham, valid_check)\n", "meta": {"hexsha": "8261d352dd843f221fbe063b92b423b36f5a341c", "size": 9672, "ext": "py", "lang": "Python", "max_stars_repo_path": "modules/pytket-projectq/pytket/extensions/projectq/backends/projectq_backend.py", "max_stars_repo_name": "isobelhooper/pytket-extensions", "max_stars_repo_head_hexsha": "53e1f40844fff29814a599d70a61963c27f094f2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/pytket-projectq/pytket/extensions/projectq/backends/projectq_backend.py", "max_issues_repo_name": "isobelhooper/pytket-extensions", "max_issues_repo_head_hexsha": "53e1f40844fff29814a599d70a61963c27f094f2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/pytket-projectq/pytket/extensions/projectq/backends/projectq_backend.py", "max_forks_repo_name": "isobelhooper/pytket-extensions", "max_forks_repo_head_hexsha": "53e1f40844fff29814a599d70a61963c27f094f2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.299270073, "max_line_length": 88, "alphanum_fraction": 0.6033912324, "include": true, "reason": "import numpy", "num_tokens": 2130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.19929669723992885}}
{"text": "\"\"\"Define Logger class for logging information to stdout and disk.\"\"\"\nimport collections\nimport os\nimport json\nimport torch\nimport numpy as np\nimport time\nimport torchvision\nfrom os.path import join\n\n\ndef xywh2xyxy(x):\n    y = x.new(x.shape)\n    y[..., 0] = x[..., 0] - x[..., 2] / 2\n    y[..., 1] = x[..., 1] - x[..., 3] / 2\n    y[..., 2] = x[..., 0] + x[..., 2] / 2\n    y[..., 3] = x[..., 1] + x[..., 3] / 2\n    return y\n\n\ndef bbox_iou(box1, box2, x1y1x2y2=True):\n    \"\"\"\n    Returns the IoU of two bounding boxes\n    \"\"\"\n    if not x1y1x2y2:\n        # Transform from center and width to exact coordinates\n        b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2\n        b1_y1, b1_y2 = box1[:, 1] - box1[:, 3] / 2, box1[:, 1] + box1[:, 3] / 2\n        b2_x1, b2_x2 = box2[:, 0] - box2[:, 2] / 2, box2[:, 0] + box2[:, 2] / 2\n        b2_y1, b2_y2 = box2[:, 1] - box2[:, 3] / 2, box2[:, 1] + box2[:, 3] / 2\n    else:\n        # Get the coordinates of bounding boxes\n        b1_x1, b1_y1, b1_x2, b1_y2 = (box1[:, 0], box1[:, 1],\n                                      box1[:, 2], box1[:, 3])\n        b2_x1, b2_y1, b2_x2, b2_y2 = (box2[:, 0], box2[:, 1],\n                                      box2[:, 2], box2[:, 3])\n\n    # get the corrdinates of the intersection rectangle\n    inter_rect_x1 = torch.max(b1_x1, b2_x1)\n    inter_rect_y1 = torch.max(b1_y1, b2_y1)\n    inter_rect_x2 = torch.min(b1_x2, b2_x2)\n    inter_rect_y2 = torch.min(b1_y2, b2_y2)\n    # Intersection area\n    inter_area = (torch.clamp(inter_rect_x2 - inter_rect_x1 + 1, min=0) *\n                  torch.clamp(inter_rect_y2 - inter_rect_y1 + 1, min=0))\n    # Union Area\n    b1_area = (b1_x2 - b1_x1 + 1) * (b1_y2 - b1_y1 + 1)\n    b2_area = (b2_x2 - b2_x1 + 1) * (b2_y2 - b2_y1 + 1)\n\n    iou = inter_area / (b1_area + b2_area - inter_area + 1e-16)\n\n    return iou\n\n\ndef bbox_wh_iou(wh1, wh2):\n    wh2 = wh2.t()\n    w1, h1 = wh1[0], wh1[1]\n    w2, h2 = wh2[0], wh2[1]\n    inter_area = torch.min(w1, w2) * torch.min(h1, h2)\n    union_area = (w1 * h1 + 1e-16) + w2 * h2 - inter_area\n    return inter_area / union_area\n\n\ndef build_targets(pred_boxes, target, anchors, ignore_thres):\n\n    ByteTensor = torch.cuda.ByteTensor if pred_boxes.is_cuda\\\n        else torch.ByteTensor\n    FloatTensor = torch.cuda.FloatTensor if pred_boxes.is_cuda\\\n        else torch.FloatTensor\n\n    nB = pred_boxes.size(0)\n    nA = pred_boxes.size(1)\n    nG = pred_boxes.size(2)\n\n    # Output tensors\n    obj_mask = ByteTensor(nB, nA, nG, nG).fill_(0)\n    noobj_mask = ByteTensor(nB, nA, nG, nG).fill_(1)\n    iou_scores = FloatTensor(nB, nA, nG, nG).fill_(0)\n    tx = FloatTensor(nB, nA, nG, nG).fill_(0)\n    ty = FloatTensor(nB, nA, nG, nG).fill_(0)\n    tw = FloatTensor(nB, nA, nG, nG).fill_(0)\n    th = FloatTensor(nB, nA, nG, nG).fill_(0)\n\n    # Convert to position relative to box\n    target_boxes = target[:, 2:6] * nG\n    gxy = target_boxes[:, :2]\n    gwh = target_boxes[:, 2:]\n    # Get anchors with best iou\n    ious = torch.stack([bbox_wh_iou(anchor, gwh) for anchor in anchors])\n    best_ious, best_n = ious.max(0)\n    # Separate target values\n    b, target_labels = target[:, :2].long().t()\n    gx, gy = gxy.t()\n    gw, gh = gwh.t()\n    gi, gj = gxy.long().t()\n    # Set masks\n    obj_mask[b, best_n, gj, gi] = 1\n    noobj_mask[b, best_n, gj, gi] = 0\n\n    # Set noobj mask to zero where iou exceeds ignore threshold\n    for i, anchor_ious in enumerate(ious.t()):\n        noobj_mask[b[i], anchor_ious > ignore_thres, gj[i], gi[i]] = 0\n\n    # Coordinates\n    tx[b, best_n, gj, gi] = gx - gx.floor()\n    ty[b, best_n, gj, gi] = gy - gy.floor()\n    # Width and height\n    tw[b, best_n, gj, gi] = torch.log(gw / anchors[best_n][:, 0] + 1e-16)\n    th[b, best_n, gj, gi] = torch.log(gh / anchors[best_n][:, 1] + 1e-16)\n\n    iou_scores[b, best_n, gj, gi] = bbox_iou(\n        pred_boxes[b, best_n, gj, gi], target_boxes, x1y1x2y2=False)\n\n    tconf = obj_mask.float()\n    return (iou_scores, obj_mask, noobj_mask,\n            tx, ty, tw, th, tconf)\n\n\ndef slice_boundary(t, width):\n    \"\"\"Assumes shape (B, C, W, H, ...).\"\"\"\n    if not isinstance(width, int):\n        raise ValueError(f\"ignore_width must be an integer. Got {width}.\")\n    if width < 0:\n        raise ValueError(f\"ignore_width must be positive. Got {width}.\")\n    if width > t.shape[2] // 2:\n        raise ValueError(\"ignore_width * 2 must be less than image dim. \" +\n                         f\"Got {width}.\")\n\n    if width != 0:\n        return t[:, :, width:-width, width:-width].contiguous()\n    else:\n        return t\n\n\ndef parse_model_config(path, num_classes=80):\n    \"\"\"Parses the yolo-v3 layer configuration file and returns module definitions\"\"\"\n    file = open(path, 'r')\n    lines = file.read().split('\\n')\n    lines = [x for x in lines if x and not x.startswith('#')]\n    lines = [x.rstrip().lstrip()\n             for x in lines]  # get rid of fringe whitespaces\n    module_defs = []\n    for line in lines:\n        if line.startswith('['):  # This marks the start of a new block\n            module_defs.append({})\n            module_defs[-1]['type'] = line[1:-1].rstrip()\n            if module_defs[-1]['type'] == 'convolutional':\n                module_defs[-1]['batch_normalize'] = 0\n        else:\n            key, value = line.split(\"=\")\n            value = value.strip()\n            module_defs[-1][key.rstrip()] = value.strip()\n\n    # Overwrite number of classes\n    yolo_layers = []\n    for i, module_def in enumerate(module_defs):\n        if module_def['type'] == 'yolo':\n            yolo_layers.append(i)\n            module_defs[i]['classes'] = str(num_classes)\n\n    for i in yolo_layers:\n        module_defs[i - 1]['filters'] = str((num_classes + 5) * 3)\n\n    return module_defs\n\n\ndef parse_data_config(path):\n    \"\"\"Parses the data configuration file\"\"\"\n    options = dict()\n    options['gpus'] = '0,1,2,3'\n    options['num_workers'] = '10'\n    with open(path, 'r') as fp:\n        lines = fp.readlines()\n    for line in lines:\n        line = line.strip()\n        if line == '' or line.startswith('#'):\n            continue\n        key, value = line.split('=')\n        options[key.strip()] = value.strip()\n    return options\n\n\ndef to_cpu(tensor):\n    return tensor.detach().cpu()\n\n\ndef xy_to_cxcy(xy, height, width):\n    return [(xy[0] + xy[2]) / 2 / width,\n            (xy[1] + xy[3]) / 2 / height,\n            (xy[2] - xy[0]) / width,\n            (xy[3] - xy[1]) / height]\n\n\ndef non_max_suppression(\n        prediction,\n        conf_thres=0.25,\n        iou_thres=0.45,\n        classes=None,\n        agnostic=False,\n        labels=()):\n    \"\"\"Performs Non-Maximum Suppression (NMS) on inference results\n    Returns:\n         detections with shape: nx6 (x1, y1, x2, y2, conf, cls)\n    \"\"\"\n\n    nc = prediction.shape[2] - 5  # number of classes\n    xc = prediction[..., 4] > conf_thres  # candidates\n\n    # Settings\n    # (pixels) minimum and maximum box width and height\n    min_wh, max_wh = 2, 4096\n    max_det = 300  # maximum number of detections per image\n    max_nms = 30000  # maximum number of boxes into torchvision.ops.nms()\n    time_limit = 20.0  # seconds to quit after\n    redundant = True  # require redundant detections\n    multi_label = nc > 1  # multiple labels per box (adds 0.5ms/img)\n    merge = False  # use merge-NMS\n\n    t = time.time()\n    output = [torch.zeros((0, 6), device=prediction.device)\n              ] * prediction.shape[0]\n    for xi, x in enumerate(prediction):  # image index, image inference\n        # Apply constraints\n        # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0  #\n        # width-height\n        x = x[xc[xi]]  # confidence\n\n        # Cat apriori labels if autolabelling\n        if labels and len(labels[xi]):\n            l = labels[xi]\n            v = torch.zeros((len(l), nc + 5), device=x.device)\n            v[:, :4] = l[:, 1:5]  # box\n            v[:, 4] = 1.0  # conf\n            v[range(len(l)), l[:, 0].long() + 5] = 1.0  # cls\n            x = torch.cat((x, v), 0)\n\n        # If none remain process next image\n        if not x.shape[0]:\n            continue\n\n        # Compute conf\n        x[:, 5:] *= x[:, 4:5]  # conf = obj_conf * cls_conf\n\n        # Box (center x, center y, width, height) to (x1, y1, x2, y2)\n        box = xywh2xyxy(x[:, :4])\n\n        # Detections matrix nx6 (xyxy, conf, cls)\n        if multi_label:\n            i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T\n            x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)\n        else:  # best class only\n            conf, j = x[:, 5:].max(1, keepdim=True)\n            x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]\n\n        # Filter by class\n        if classes is not None:\n            x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]\n\n        # Apply finite constraint\n        # if not torch.isfinite(x).all():\n        #     x = x[torch.isfinite(x).all(1)]\n\n        # Check shape\n        n = x.shape[0]  # number of boxes\n        if not n:  # no boxes\n            continue\n        elif n > max_nms:  # excess boxes\n            # sort by confidence\n            x = x[x[:, 4].argsort(descending=True)[:max_nms]]\n\n        # Batched NMS\n        c = x[:, 5:6] * (0 if agnostic else max_wh)  # classes\n        boxes, scores = x[:, :4] + c, x[:, 4]  # boxes (offset by class), scores\n        i = torchvision.ops.nms(boxes, scores, iou_thres)  # NMS\n        if i.shape[0] > max_det:  # limit detections\n            i = i[:max_det]\n        if merge and (\n                1 < n < 3E3):  # Merge NMS (boxes merged using weighted mean)\n            # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)\n            iou = box_iou(boxes[i], boxes) > iou_thres  # iou matrix\n            weights = iou * scores[None]  # box weights\n            x[i, :4] = torch.mm(weights, x[:, :4]).float(\n            ) / weights.sum(1, keepdim=True)  # merged boxes\n            if redundant:\n                i = i[iou.sum(1) > 1]  # require redundancy\n\n        output[xi] = x[i]\n        if (time.time() - t) > time_limit:\n            print(f'WARNING: NMS time limit {time_limit}s exceeded')\n            break  # time limit exceeded\n\n    return output\n", "meta": {"hexsha": "db71c12addb9a78b7cb0b03d2dc1424377b12cc7", "size": 10186, "ext": "py", "lang": "Python", "max_stars_repo_path": "detection/models/detection/yolo/utils.py", "max_stars_repo_name": "stanford-policylab/surveilling-surveillance", "max_stars_repo_head_hexsha": "bbb9a147927a6342eecfe07ffa756b3acdb63f35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-05-21T03:38:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T08:32:41.000Z", "max_issues_repo_path": "detection/models/detection/yolo/utils.py", "max_issues_repo_name": "stanford-policylab/surveilling-surveillance", "max_issues_repo_head_hexsha": "bbb9a147927a6342eecfe07ffa756b3acdb63f35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "detection/models/detection/yolo/utils.py", "max_forks_repo_name": "stanford-policylab/surveilling-surveillance", "max_forks_repo_head_hexsha": "bbb9a147927a6342eecfe07ffa756b3acdb63f35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-13T21:49:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T21:49:14.000Z", "avg_line_length": 34.7645051195, "max_line_length": 84, "alphanum_fraction": 0.5511486354, "include": true, "reason": "import numpy", "num_tokens": 3263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.19929669723992885}}
{"text": "from collections import OrderedDict\nfrom numpy import (int64, int32, int16, ndarray)\nfrom scipy.sparse import issparse\n\nfrom ..QuantumToolbox import operators as qOps #pylint: disable=relative-beyond-top-level\nfrom ..QuantumToolbox import linearAlgebra as linAlg #pylint: disable=relative-beyond-top-level\nfrom ..QuantumToolbox import states as qSta #pylint: disable=relative-beyond-top-level\n\nfrom .base import addDecorator, _recurseIfList\nfrom .baseClasses import qBaseSim, paramBoundBase, setAttr\n#from quanguru.classes.exceptions import qSystemInitErrors, qCouplingInitErrors\nfrom .QPro import freeEvolution\n\ndef _initStDec(_createAstate):\n    def wrapper(obj, inp=None):\n        if (issparse(inp) or isinstance(inp, ndarray)):\n            if inp.shape[0] != obj.dimension:\n                raise ValueError('Dimension mismatch')\n            state = inp\n        else:\n            if inp is None:\n                inp = obj.simulation._stateBase__initialStateInput.value\n\n            if isinstance(obj.dimension, int):\n                state = _createAstate(obj, inp)\n            else:\n                state = None\n        return state\n    return wrapper\n\ndef _computeDef(sys, state): # pylint: disable=unused-argument\n    pass\n\ndef _calculateDef(sys): # pylint: disable=unused-argument\n    pass\n\nclass genericQSys(qBaseSim):\n    r\"\"\"\n    Base class for both single (:class:`~qSystem`) and composite (:class:`~compQSystem`) quantum system classes.\n    The ultimate goal is to make those two classes the same by combining them in here. Currently, a proxy\n    :class:`~QuantumSystem` is introduced as a temporary solution.\n    \"\"\"\n    label = 'genericQSys'\n    #: (**class attribute**) number of instances created internally by the library\n    _internalInstances: int = 0\n    #: (**class attribute**) number of instances created explicitly by the user\n    _externalInstances: int = 0\n    #: (**class attribute**) number of total instances = _internalInstances + _externalInstances\n    _instances: int = 0\n\n    __slots__ = ['__unitary', '__dimension', '__dimsBefore', '__dimsAfter', '_inpCoef']\n\n    def __init__(self, **kwargs):\n        super().__init__()\n        #: an internal :class:`~freeEvolution` protocol, this is the default evolution when a simulation is run.\n        self.__unitary = freeEvolution(_internal=True)\n        self._genericQSys__unitary.superSys = self # pylint: disable=no-member\n        self._qBaseSim__simulation.addQSystems(subS=self, Protocol=self._freeEvol) # pylint: disable=no-member\n        #: dimension of Hilbert space of the quantum system\n        self.__dimension = None\n        #: boolean to determine whether initialState inputs contains complex coefficients (the probability amplitudes)\n        #: or the populations\n        self._inpCoef = False\n        self.__dimsBefore = 1\n        self.__dimsAfter = 1\n        self._named__setKwargs(**kwargs) # pylint: disable=no-member\n\n    def __add__(self, other):\n        if isinstance(self, compQSystem) and isinstance(other, qSystem):\n            self.addSubSys(other)\n            newComp = self\n        elif ((isinstance(self, qSystem) and isinstance(other, qSystem)) or  # noqa: W504\n              (isinstance(self, compQSystem) and isinstance(other, compQSystem))):\n            newComp = compQSystem()\n            # FIXME 'stepCount' getter creates problem with None defaults\n            newComp.simulation._copyVals(self.simulation, ['totalTime', 'stepSize', 'delStates'])\n            newComp.compute = _computeDef\n            newComp.simulation.compute = _computeDef\n            #newComp.calculate = _calculateDef\n            #newComp.simulation.calculate = _calculateDef\n            newComp.addSubSys(self)\n            if other is self:\n                newComp.addSubSys(other.copy())\n            else:\n                newComp.addSubSys(other)\n        elif isinstance(self, qSystem) and isinstance(other, compQSystem):\n            other.addSubSys(self)\n            newComp = other\n        elif isinstance(other, (float, int)):\n            newComp = self\n        return newComp\n\n    def __sub__(self, other):\n        self.removeSubSys(other, _exclude=[])\n        return self\n\n    def __rmul__(self, other):\n        newComp = compQSystem()\n        newComp.addSubSys(self)\n        for _ in range(other - 1):\n            newComp.addSubSys(self.copy())\n        return newComp\n\n    def copy(self, **kwargs): # pylint: disable=arguments-differ\n        subSysList = []\n        for sys in self.subSys.values():\n            subSysList.append(sys.copy())\n\n        if isinstance(self, qSystem):\n            newSys = super().copy(dimension=self.dimension, terms=subSysList)\n        elif isinstance(self, compQSystem):\n            newSys = super().copy()\n            for sys in subSysList:\n                newSys.addSubSys(sys)\n\n        if self.simulation._stateBase__initialStateInput._value is not None:\n            newSys.initialState = self.simulation._stateBase__initialStateInput.value\n        newSys._named__setKwargs(**kwargs)\n        return newSys\n\n    @property\n    def ind(self):\n        ind = 0\n        if self.superSys is not None:\n            ind += list(self.superSys.subSys.values()).index(self)\n            if self.superSys.superSys is not None:\n                ind += self.superSys.ind\n        return ind\n\n    @property\n    def _dimsBefore(self):\n        return self._genericQSys__dimsBefore if self._genericQSys__dimsBefore != 0 else 1\n\n    @_dimsBefore.setter\n    def _dimsBefore(self, val):\n        if not isinstance(val, int):\n            raise ValueError('?')\n        oldVal = self._dimsBefore\n        setAttr(self, '_genericQSys__dimsBefore', val)\n        for sys in self.subSys.values():\n            sys.delMatrices(_exclude=[]) # pylint: disable=protected-access\n            if isinstance(sys, genericQSys):\n                sys._dimsBefore = int((sys._dimsBefore*val)/oldVal)\n\n    @property\n    def _dimsAfter(self):\n        return self._genericQSys__dimsAfter if self._genericQSys__dimsAfter != 0 else 1\n\n    @_dimsAfter.setter\n    def _dimsAfter(self, val):\n        if not isinstance(val, int):\n            raise ValueError('?')\n        oldVal = self._dimsAfter\n        setAttr(self, '_genericQSys__dimsAfter', val)\n        for sys in self.subSys.values():\n            sys.delMatrices(_exclude=[]) # pylint: disable=protected-access\n            if isinstance(sys, genericQSys):\n                sys._dimsAfter = int((sys._dimsAfter*val)/oldVal)\n\n    @property\n    def dimension(self):\n        if self._genericQSys__dimension is None:\n            try:\n                dims = self.subSysDimensions\n                self._genericQSys__dimension = 1 # pylint: disable=assigning-non-slot\n                for val in dims:\n                    self._genericQSys__dimension *= val # pylint: disable=assigning-non-slot\n            except AttributeError:\n                print(f'dimension? {self.name}')\n        return self._genericQSys__dimension\n\n    @property\n    def _totalDim(self):\n        return self.dimension * self._dimsBefore * self._dimsAfter#pylint:disable=E1101\n\n    @property\n    def _freeEvol(self):\n        return self._genericQSys__unitary\n\n    @property\n    def unitary(self):\n        unitary = self._genericQSys__unitary.unitary\n        self._paramBoundBase__paramUpdated = False # pylint: disable=assigning-non-slot\n        return unitary\n\n    @qBaseSim.initialState.setter # pylint: disable=no-member\n    def initialState(self, inp):\n        if self.superSys is not None:\n            self.superSys.simulation._stateBase__initialState._value = None\n        self.simulation.initialState = inp # pylint: disable=no-member, protected-access\n        if (isinstance(self, compQSystem) and isinstance(inp, list)):\n            for ind, it in enumerate(inp):\n                list(self.qSystems.values())[ind].initialState = it # pylint: disable=no-member\n\n    def _constructMatrices(self):\n        for sys in self.subSys.values():\n            sys._constructMatrices() # pylint: disable=protected-access\n\n    def addProtocol(self, protocol=None, system=None, protocolRemove=None):\n        if system is None:\n            system = self\n        self.simulation.addProtocol(protocol=protocol, system=system, protocolRemove=protocolRemove)\n\n    def _timeDependency(self, time=None):\n        if time is None:\n            time = self.simulation._currentTime\n        for sys in self.subSys.values():\n            sys._timeDependency(time)\n        return time\n\nclass QuantumSystem(genericQSys):\n    #: (**class attribute**) number of instances created internally by the library\n    _internalInstances: int = 0\n    #: (**class attribute**) number of instances created explicitly by the user\n    _externalInstances: int = 0\n    #: (**class attribute**) number of total instances = _internalInstances + _externalInstances\n    _instances: int = 0\n    def __new__(cls, sysType='composite', **kwargs):\n        singleKeys = ['frequency', 'operator', 'order', 'dimension']\n        for key in singleKeys:\n            if key in kwargs.keys():\n                sysType = 'single'\n\n        if sysType == 'composite':\n            newCls = compQSystem\n        elif sysType == 'single':\n            newCls = qSystem\n        elif sysType == 'system coupling':\n            newCls = qCoupling\n\n        if newCls != cls:\n            instance = newCls(**kwargs)\n        return instance\n\n    __slots__ = []\n\nclass compQSystem(genericQSys):\n    label = 'QuantumSystem'\n    #: (**class attribute**) number of instances created internally by the library\n    _internalInstances: int = 0\n    #: (**class attribute**) number of instances created explicitly by the user\n    _externalInstances: int = 0\n    #: (**class attribute**) number of total instances = _internalInstances + _externalInstances\n    _instances: int = 0\n\n    __slots__ = ['__qCouplings', '__qSystems', 'couplingName']\n\n    def __init__(self, **kwargs):\n        if self.__class__.__name__ == 'compQSystem':\n            compQSystem._externalInstances = qSystem._instances + compQSystem._instances\n        super().__init__()\n        self.__qCouplings = OrderedDict()\n        self.__qSystems = OrderedDict()\n        self.couplingName = None\n\n        self._named__setKwargs(**kwargs) # pylint: disable=no-member\n\n    def _timeDependency(self, time=None):\n        time = super()._timeDependency(time=time)\n        for coupling in self.qCouplings.values():\n            coupling._timeDependency(time)\n\n    @property\n    def subSysDimensions(self):\n        return [sys.dimension for sys in self.subSys.values()]\n\n    @property\n    def freeHam(self):\n        ham = sum([val.totalHam for val in self.qSystems.values()])\n        return ham\n\n    @property\n    def totalHam(self): # pylint: disable=invalid-overridden-method\n        if ((self._paramUpdated) or (self._paramBoundBase__matrix is None)): # pylint: disable=no-member\n            self._paramBoundBase__matrix = self.freeHam + self.couplingHam # pylint: disable=assigning-non-slot\n            self._paramBoundBase__paramUpdated = False # pylint: disable=assigning-non-slot\n        return self._paramBoundBase__matrix # pylint: disable=no-member\n\n    @property\n    def couplingHam(self):\n        cham = sum([val.totalHam for val in self.qCouplings.values()])\n        return cham\n\n    @property\n    def qSystems(self):\n        return self._compQSystem__qSystems # pylint: disable=no-member\n\n    @addDecorator\n    def addSubSys(self, subSys, **kwargs): # pylint: disable=arguments-differ\n        newSys = super().addSubSys(subSys, **kwargs)\n        if isinstance(newSys, qCoupling):\n            self._compQSystem__addCoupling(self._qBase__subSys.pop(newSys.name))  # pylint: disable=no-member\n        elif isinstance(newSys, genericQSys):\n            self._compQSystem__addSub(newSys)\n        else:\n            raise TypeError('?')\n        newSys._paramBoundBase__paramBound[self.name] = self # pylint: disable=protected-access\n        return newSys\n\n    def createSubSys(self, subSysClass, **kwargs):\n        return self.addSubSys(subSysClass, **kwargs)\n\n    def __addSub(self, subSys):\n        for subS in self._compQSystem__qSystems.values():\n            subS._dimsAfter *= subSys.dimension\n            subSys._dimsBefore *= subS.dimension\n\n        if subSys._paramBoundBase__matrix is not None:\n            for sys in subSys.subSys.values():\n                sys._paramBoundBase__matrix = None\n        # TODO big question here\n        subSys.simulation._bound(self.simulation) # pylint: disable=protected-access\n        self._compQSystem__qSystems[subSys.name] = subSys\n        subSys.superSys = self\n        return subSys\n\n    @_recurseIfList\n    def removeSubSys(self, subS, _exclude=[]):#pylint:disable=arguments-differ,dangerous-default-value,too-many-branches\n        if isinstance(subS, str):\n            subS = self.getByNameOrAlias(subS)\n        couplings = list(self.qCouplings.values())\n        for coupling in couplings:\n            coupling.removeSubSys(subS, _exclude=_exclude)\n            if len(coupling._qBase__subSys) == 0: # pylint: disable=protected-access\n                self.qCouplings.pop(coupling.name)\n\n        if subS in list(self.subSys.values()):\n            for qS in self.subSys.values():\n                qS.simulation._stateBase__initialState._value = None\n                if qS.ind < subS.ind:\n                    qS._dimsAfter = int(qS._dimsAfter/subS.dimension)\n                elif qS.ind > subS.ind:\n                    qS._dimsBefore = int(qS._dimsBefore/subS.dimension)\n            self.qSystems.pop(subS.name)\n            _exclude.append(self)\n            super().removeSubSys(subS, _exclude=_exclude)\n        elif subS in self.qCouplings.values():\n            self.qCouplings.pop(subS.name)\n\n        if self not in _exclude:\n            _exclude.append(self)\n            if ((self._dimsAfter != 1) or (self._dimsBefore != 1)):\n                if self.ind < subS.superSys.ind:\n                    self._dimsAfter = int(self._dimsAfter/subS.dimension)\n                elif self.ind > subS.superSys.ind:\n                    self._dimsBefore = int(self._dimsBefore/subS.dimension)\n\n            for sys in self.subSys.values():\n                sys.removeSubSys(subS, _exclude=_exclude)\n                #_exclude.append(sys)\n\n        if self.superSys is not None:\n            self.superSys.removeSubSys(subS, _exclude=_exclude)\n            _exclude.append(self.superSys)\n\n        self.delMatrices(_exclude=[])\n        self.simulation._stateBase__initialState._value = None\n        self._genericQSys__dimension = None # pylint: disable=assigning-non-slot\n\n    @property\n    def qCouplings(self):\n        return self._compQSystem__qCouplings\n\n    def __addCoupling(self, couplingObj):\n        self._compQSystem__qCouplings[couplingObj.name] = couplingObj\n        couplingObj.superSys = self\n        return couplingObj\n\n    def createSysCoupling(self, *args, **kwargs):\n        newCoupling = self.addSubSys(qCoupling, **kwargs)\n        newCoupling.addTerm(*args)\n        return newCoupling\n\n    def addSysCoupling(self, couplingObj):\n        self.addSubSys(couplingObj)\n\n    @_initStDec\n    def _createAstate(self, inp=None):\n        if inp is None:\n            inp = [qsys._createAstate() for qsys in self.subSys.values()]\n        elif isinstance(inp, list):\n            inp = [qsys._createAstate(inp[qsys.ind]) for qsys in self.subSys.values()]\n        else:\n            raise TypeError('?')\n        return linAlg.tensorProd(*inp)\n\n    def _constructMatrices(self):\n        super()._constructMatrices()\n        for sys in self.qCouplings.values():\n            sys._constructMatrices() # pylint: disable=protected-access\n\n    def updateDimension(self, qSys, newDimVal, oldDimVal=None, _exclude=[]):#pylint:disable=dangerous-default-value,too-many-branches\n        # TODO can be combined with removeSubSys by a decorator or another method to simplfy both\n        if oldDimVal is None:\n            oldDimVal = qSys._genericQSys__dimension\n        self._genericQSys__dimension = None # pylint: disable=assigning-non-slot\n        if qSys in self.qSystems.values():\n            _exclude.append(self)\n            qSys._genericQSys__dimension = newDimVal\n            ind = qSys.ind\n            for qS in self.qSystems.values():\n                if qS.ind < ind:\n                    qS._dimsAfter = int((qS._dimsAfter*newDimVal)/oldDimVal)\n                elif qS.ind > ind:\n                    qS._dimsBefore = int((qS._dimsBefore*newDimVal)/oldDimVal)\n\n            #if self.simulation._stateBase__initialStateInput.value is not None: # pylint: disable=no-member\n            #    self.initialState = self.simulation._stateBase__initialStateInput.value # pylint: disable=no-member\n            self._paramUpdated = True\n            #self._constructMatrices()\n            #for sys in self.subSys.values():\n            #    if sys.simulation._stateBase__initialStateInput.value is not None:\n            #        sys.initialState = sys.simulation._stateBase__initialStateInput.value\n\n        if self not in _exclude:\n            _exclude.append(self)\n            if ((self._dimsAfter != 1) or (self._dimsBefore != 1)):\n                if self.ind < qSys.superSys.ind:\n                    self._dimsAfter = int((self._dimsAfter*newDimVal)/oldDimVal)\n                elif self.ind > qSys.superSys.ind:\n                    self._dimsBefore = int((self._dimsBefore*newDimVal)/oldDimVal)\n            else:\n                for sys in self.subSys.values():\n                    if sys not in _exclude:\n                        _exclude.append(sys)\n                        if sys.ind < qSys.superSys.ind:\n                            sys._dimsAfter = int((sys._dimsAfter*newDimVal)/oldDimVal)\n                        elif sys.ind > qSys.superSys.ind:\n                            sys._dimsBefore = int((sys._dimsBefore*newDimVal)/oldDimVal)\n\n        if self.superSys is not None:\n            self.superSys.updateDimension(qSys=qSys, newDimVal=newDimVal, oldDimVal=oldDimVal, _exclude=_exclude)\n        self.delMatrices(_exclude=[])\n        for c in self.qCouplings.values():\n            c.delMatrices(_exclude=[])\n        return qSys\n\nclass termTimeDep(paramBoundBase):\n    label = '_timeDep'\n    #: (**class attribute**) number of instances created internally by the library\n    _internalInstances: int = 0\n    #: (**class attribute**) number of instances created explicitly by the user\n    _externalInstances: int = 0\n    #: (**class attribute**) number of total instances = _internalInstances + _externalInstances\n    _instances: int = 0\n\n    __slots__ = ['timeDependency', '__frequency', '__order', '__operator']\n\n    def __init__(self, **kwargs):\n        super().__init__()\n        self.timeDependency = None\n        self.__frequency = None\n        self.__order = 1\n        self.__operator = None\n        self._named__setKwargs(**kwargs) # pylint: disable=no-member\n\n    def copy(self, **kwargs):  # pylint: disable=arguments-differ\n        newSys = super().copy(frequency=self.frequency, operator=self.operator, order=self.order, **kwargs)\n        return newSys\n\n    @property\n    def operator(self):\n        return self._termTimeDep__operator\n\n    @operator.setter\n    def operator(self, op):\n        self._paramBoundBase__matrix = None # pylint: disable=assigning-non-slot\n        setAttr(self, '_termTimeDep__operator', op)\n\n    @property\n    def order(self):\n        return self._termTimeDep__order\n\n    @order.setter\n    def order(self, ordVal):\n        setAttr(self, '_termTimeDep__order', ordVal)\n        if self._paramBoundBase__matrix is not None: # pylint: disable=no-member\n            self.freeMat = None\n\n    @property\n    def frequency(self):\n        return self._termTimeDep__frequency\n\n    @frequency.setter\n    def frequency(self, freq):\n        freq = 0 if freq == 0.0 else freq\n        setAttr(self, '_termTimeDep__frequency', freq)\n\n    def _constructMatrices(self):\n        pass\n\n    @property\n    def totalHam(self):\n        return self.frequency*self.freeMat\n\n    @property\n    def freeMat(self):\n        #if ((self._paramBoundBase__matrix is None) or (self._paramUpdated)): # pylint: disable=no-member\n        if self._paramBoundBase__matrix is None: # pylint: disable=no-member\n            self.freeMat = None\n            self._paramBoundBase__paramUpdated = False # pylint: disable=assigning-non-slot\n        return self._paramBoundBase__matrix # pylint: disable=no-member\n\n    @freeMat.setter\n    def freeMat(self, qMat):\n        if qMat is not None:\n            self._paramBoundBase__matrix = qMat # pylint: disable=no-member, assigning-non-slot\n        else:\n            #if len(self._qBase__subSys) == 0: # pylint: disable=no-member\n            #    raise ValueError('No operator is given for coupling Hamiltonian')\n            #if self.operator is None:\n            #    raise ValueError('No operator is given for free Hamiltonian')\n            self._constructMatrices()\n\n    def _timeDependency(self, time=None):\n        if time is None:\n            time = self.superSys.simulation._currentTime\n\n        if callable(self.timeDependency):\n            if hasattr(self, 'frequency'):\n                self.frequency = self.timeDependency(self, time) # pylint: disable=assigning-non-slot,not-callable\n            elif hasattr(self, 'couplingStrength'):\n                self.couplingStrength = self.timeDependency(self, time) #pylint:disable=assigning-non-slot,not-callable\n\nclass term(termTimeDep):\n    label = 'term'\n    #: (**class attribute**) number of instances created internally by the library\n    _internalInstances: int = 0\n    #: (**class attribute**) number of instances created explicitly by the user\n    _externalInstances: int = 0\n    #: (**class attribute**) number of total instances = _internalInstances + _externalInstances\n    _instances: int = 0\n\n    __slots__ = []\n\n    @paramBoundBase.superSys.setter\n    def superSys(self, supSys):\n        r\"\"\"\n        Extends superSys setter to also add aliases to self.\n        New aliases are (any name/alias of superSys) + Term + (number of terms)\n        TODO What if there is already a superSys, and also alias list contains user given aliases as well.\n        \"\"\"\n        paramBoundBase.superSys.fset(self, supSys) # pylint: disable=no-member\n        termCount = len(self.superSys.subSys) if self in self.superSys.subSys.values() else len(self.superSys.subSys)+1 # pylint: disable=no-member,line-too-long # noqa: E501\n        self.alias = [na+\"Term\"+str(termCount) for na in self.superSys.name._aliasClass__members()] # pylint: disable=no-member, protected-access,line-too-long # noqa: E501\n\n    @property\n    def _freeMatSimple(self):\n        h = self._constructMatrices(dimsBefore=1, dimsAfter=1, setMat=False)\n        return h\n\n    def _constructMatrices(self, dimsBefore=None, dimsAfter=None, setMat=True): #pylint:disable=arguments-differ\n        if dimsBefore is None:\n            dimsBefore = self.superSys._dimsBefore # pylint: disable=no-member\n\n        if dimsAfter is None:\n            dimsAfter = self.superSys._dimsAfter # pylint: disable=no-member\n\n        if not (isinstance(self.superSys.dimension, (int, int64, int32, int16)) and callable(self.operator)): # pylint: disable=no-member\n            raise TypeError('?')\n\n        dimension = self.superSys._genericQSys__dimension # pylint: disable=no-member\n        if self.operator in [qOps.Jz, qOps.Jy, qOps.Jx, qOps.Jm, qOps.Jp, qOps.Js]:\n            dimension = 0.5*(dimension-1)\n\n        if self.operator not in [qOps.sigmam, qOps.sigmap, qOps.sigmax, qOps.sigmay, qOps.sigmaz]:\n            mat = qOps.compositeOp(self.operator(dimension), #pylint:disable=assigning-non-slot\n                                   dimsBefore, dimsAfter)**self.order\n        else: # pylint: disable=bare-except\n            mat = qOps.compositeOp( # pylint: disable=no-member, assigning-non-slot\n                self.operator(), dimsBefore, dimsAfter)**self.order\n\n        if setMat:\n            self._paramBoundBase__matrix = mat #pylint:disable=assigning-non-slot\n        return mat\n\nclass qSystem(genericQSys):\n    label = 'QuantumSystem'\n    #: (**class attribute**) number of instances created internally by the library\n    _internalInstances: int = 0\n    #: (**class attribute**) number of instances created explicitly by the user\n    _externalInstances: int = 0\n    #: (**class attribute**) number of total instances = _internalInstances + _externalInstances\n    _instances: int = 0\n\n    __slots__ = []\n    #@qSystemInitErrors\n    def __init__(self, **kwargs):\n        if self.__class__.__name__ == 'qSystem':\n            qSystem._externalInstances = qSystem._instances + compQSystem._instances\n        super().__init__()\n        qSysKwargs = ['terms', 'subSys', 'name', 'superSys', 'dimension']\n        for key in qSysKwargs:\n            val = kwargs.pop(key, None)\n            if val is not None:\n                setattr(self, key, val)\n        self._named__setKwargs(**kwargs) # pylint: disable=no-member\n\n        if len(self.subSys) == 0:\n            self.addSubSys(term(superSys=self, **kwargs))\n\n    # @genericQSys.name.setter #pylint: disable=no-member\n    # def name(self, name):\n    #     oldName = self.name\n    #     genericQSys.name.fset(self, name) # pylint: disable=no-member\n    #     for ii, sys in enumerate(self.subSys.values()):\n    #         if sys.name == (oldName + 'term' + str(ii)):\n    #             sys.name = self.superSys.name + 'term' + str(ii+1) # pylint: disable=no-member\n\n    @genericQSys.dimension.setter # pylint: disable=no-member\n    def dimension(self, newDimVal):\n        if not isinstance(newDimVal, (int, int64, int32, int16)):\n            raise ValueError('Dimension is not int')\n\n        oldDimVal = self._genericQSys__dimension # pylint: disable=no-member\n\n        for sys in self.subSys.values():\n            sys.delMatrices(_exclude=[]) # pylint: disable=protected-access\n\n        setAttr(self, '_genericQSys__dimension', newDimVal)\n        # FIXME these should be called only if oldDim != newDim\n        #if self.simulation._stateBase__initialStateInput.value is not None: # pylint: disable=protected-access\n        #    self.initialState = self.simulation._stateBase__initialStateInput.value # pylint: disable=protected-access\n\n        if isinstance(self.superSys, compQSystem):\n            self.superSys.updateDimension(self, newDimVal, oldDimVal, _exclude=[]) # pylint: disable=no-member\n\n    @property\n    def totalHam(self): # pylint: disable=invalid-overridden-method\n        if ((self._paramUpdated) or (self._paramBoundBase__matrix is None)): # pylint: disable=no-member\n            h = sum([(obj.frequency * obj.freeMat) for obj in self.subSys.values()])\n            self._paramBoundBase__matrix = h # pylint: disable=assigning-non-slot\n            self._paramBoundBase__paramUpdated = False # pylint: disable=assigning-non-slot\n        return self._paramBoundBase__matrix # pylint: disable=no-member\n\n    @property\n    def _totalHamSimple(self):\n        return sum([(obj.frequency * obj._freeMatSimple) for obj in self.subSys.values()])#pylint:disable=protected-access\n\n    @property\n    def freeMat(self):\n        return self.firstTerm.freeMat # pylint: disable=no-member\n\n    @freeMat.setter\n    def freeMat(self, qOpsFunc):\n        if callable(qOpsFunc):\n            self.firstTerm.operator = qOpsFunc\n            self.firstTerm._constructMatrices() # pylint: disable=protected-access\n        elif qOpsFunc is not None:\n            self.firstTerm._paramBoundBase__matrix = qOpsFunc  # pylint: disable=assigning-non-slot\n        else:\n            if self.firstTerm.operator is None:\n                raise ValueError('No operator is given for free Hamiltonian')\n            self.firstTerm._constructMatrices() # pylint: disable=protected-access\n\n    @property\n    def operator(self):\n        operators = [obj._termTimeDep__operator for obj in list(self.subSys.values())] # pylint: disable=protected-access\n        return operators if len(operators) > 1 else operators[0]\n\n    @operator.setter\n    def operator(self, op):\n        self.firstTerm.operator = op\n\n    @property\n    def frequency(self):\n        #frequencies = [obj._termTimeDep__frequency for obj in list(self.subSys.values())] # pylint: disable=protected-access\n        #return frequencies if len(frequencies) > 1 else frequencies[0]\n        return self.firstTerm.frequency\n\n    @frequency.setter\n    def frequency(self, freq):\n        self.firstTerm.frequency = freq\n\n    @property\n    def order(self):\n        orders = [obj._termTimeDep__order for obj in list(self.subSys.values())] # pylint: disable=protected-access\n        return orders if len(orders) > 1 else orders[0]\n\n    @order.setter\n    def order(self, ordVal):\n        self.firstTerm.order = ordVal\n\n    @property\n    def firstTerm(self):\n        return list(self.subSys.values())[0]\n\n    @property\n    def terms(self):\n        qSys = list(self.subSys.values())\n        return qSys if len(qSys) > 1 else qSys[0]\n\n    @addDecorator\n    def addSubSys(self, subS, **kwargs):\n        if not isinstance(subS, term):\n            raise TypeError('?')\n        kwargs['superSys'] = self\n        newS = super().addSubSys(subS, **kwargs)\n        # FIXME use setAttr, check also for operator\n        self._paramUpdated = True\n        newS._paramBoundBase__paramBound[self.name] = self # pylint: disable=protected-access\n        return subS\n\n    @_recurseIfList\n    def removeSubSys(self, subS, _exclude=[]): # pylint: disable=arguments-differ, dangerous-default-value\n        if self not in _exclude:\n            _exclude.append(self)\n            if self.superSys is not None:\n                self.superSys.removeSubSys(subS, _exclude=_exclude)\n            super().removeSubSys(subS, _exclude=_exclude)\n\n    @terms.setter\n    def terms(self, subS):\n        genericQSys.subSys.fset(self, subS) # pylint: disable=no-member\n        for sys in self.subSys.values():\n            sys.superSys = self\n\n    def addTerm(self, operator, frequency=0, order=1):\n        newTerm = self.addSubSys(term(operator=operator, frequency=frequency, order=order, superSys=self))\n        return newTerm\n\n    @_recurseIfList\n    def removeTerm(self, termObj):\n        self.removeSubSys(termObj, _exclude=[])\n\n    @_initStDec\n    def _createAstate(self, inp=None):\n        if inp is None:\n            raise ValueError(self.name + ' is not given an initial state')\n        return qSta.superPos(self.dimension, inp, not self._inpCoef)\n\nclass Spin(qSystem): # pylint: disable=too-many-ancestors\n    label = 'Spin'\n    #: (**class attribute**) number of instances created internally by the library\n    _internalInstances: int = 0\n    #: (**class attribute**) number of instances created explicitly by the user\n    _externalInstances: int = 0\n    #: (**class attribute**) number of total instances = _internalInstances + _externalInstances\n    _instances: int = 0\n\n    __slots__ = ['__jValue']\n    def __init__(self, **kwargs):\n        super().__init__(terms=kwargs.pop('terms', None), subSys=kwargs.pop('subSys', None))\n        self.operator = qOps.Jz\n        self.__jValue = None\n        self._named__setKwargs(**kwargs) # pylint: disable=no-member\n\n    @property\n    def jValue(self):\n        return (self._genericQSys__dimension-1)/2 # pylint: disable=no-member\n\n    @jValue.setter\n    def jValue(self, value):\n        self._Spin__jValue = value # pylint: disable=assigning-non-slot\n        self.dimension = int((2*value) + 1)\n\nclass Qubit(Spin): # pylint: disable=too-many-ancestors\n    label = 'Qubit'\n    #: (**class attribute**) number of instances created internally by the library\n    _internalInstances: int = 0\n    #: (**class attribute**) number of instances created explicitly by the user\n    _externalInstances: int = 0\n    #: (**class attribute**) number of total instances = _internalInstances + _externalInstances\n    _instances: int = 0\n\n    __slots__ = []\n    def __init__(self, **kwargs):\n        super().__init__(terms=kwargs.pop('terms', None), subSys=kwargs.pop('subSys', None))\n        kwargs['dimension'] = 2\n        self.operator = qOps.Jz\n        self._named__setKwargs(**kwargs) # pylint: disable=no-member\n\nclass Cavity(qSystem): # pylint: disable=too-many-ancestors\n    label = 'Cavity'\n    #: (**class attribute**) number of instances created internally by the library\n    _internalInstances: int = 0\n    #: (**class attribute**) number of instances created explicitly by the user\n    _externalInstances: int = 0\n    #: (**class attribute**) number of total instances = _internalInstances + _externalInstances\n    _instances: int = 0\n\n    __slots__ = []\n    def __init__(self, **kwargs):\n        super().__init__(terms=kwargs.pop('terms', None), subSys=kwargs.pop('subSys', None))\n        self.operator = qOps.number\n        self._named__setKwargs(**kwargs) # pylint: disable=no-member\n\nclass qCoupling(termTimeDep):\n    label = 'qCoupling'\n    #: (**class attribute**) number of instances created internally by the library\n    _internalInstances: int = 0\n    #: (**class attribute**) number of instances created explicitly by the user\n    _externalInstances: int = 0\n    #: (**class attribute**) number of total instances = _internalInstances + _externalInstances\n    _instances: int = 0\n\n    __slots__ = []\n\n    #@qCouplingInitErrors\n    def __init__(self, *args, **kwargs):\n        super().__init__()\n        self._named__setKwargs(**kwargs) # pylint: disable=no-member\n        self.addTerm(*args)\n\n    # TODO might define setters\n    @property\n    def couplingOperators(self):\n        ops = []\n        for co in self._qBase__subSys.values(): # pylint: disable=no-member\n            ops.append(co[1])\n        return ops\n\n    @property\n    def coupledSystems(self):\n        ops = []\n        for co in self._qBase__subSys.values(): # pylint: disable=no-member\n            ops.append(co[0])\n        return ops\n\n    @property\n    def couplingStrength(self):\n        return self.frequency\n\n    @couplingStrength.setter\n    def couplingStrength(self, strength):\n        self.frequency = strength\n\n    def __coupOrdering(self, qts): # pylint: disable=no-self-use\n        qts = sorted(qts, key=lambda x: x[0], reverse=False)\n        oper = qts[0][1]\n        for ops in range(len(qts)-1):\n            oper = oper @ qts[ops+1][1]\n        return oper\n\n    def _constructMatrices(self):\n        cMats = []\n        for ind in range(len(self._qBase__subSys)): # pylint: disable=no-member\n            qts = []\n            for indx in range(len(list(self._qBase__subSys.values())[ind])): # pylint: disable=no-member\n                sys = list(self._qBase__subSys.values())[ind][0][indx] # pylint: disable=no-member\n                order = sys.ind\n                oper = list(self._qBase__subSys.values())[ind][1][indx] # pylint: disable=no-member\n                if oper in [qOps.sigmam, qOps.sigmap, qOps.sigmax, qOps.sigmay, qOps.sigmaz]:\n                    cHam = qOps.compositeOp(oper(), sys._dimsBefore, sys._dimsAfter)\n                else:\n                    dimension = sys._genericQSys__dimension\n                    if oper in [qOps.Jz, qOps.Jy, qOps.Jx, qOps.Jm, qOps.Jp, qOps.Js]:\n                        dimension = 0.5*(dimension-1)\n                    cHam = qOps.compositeOp(oper(dimension), sys._dimsBefore, sys._dimsAfter)\n                ts = [order, cHam]\n                qts.append(ts)\n            cMats.append(self._qCoupling__coupOrdering(qts))\n        #h = []\n        #if ((self.couplingStrength != 0) or (self.couplingStrength is not None)):\n        #    h = [self.couplingStrength * sum(cMats)]\n        self._paramBoundBase__matrix = sum(cMats) # pylint: disable=assigning-non-slot\n        return self._paramBoundBase__matrix # pylint: disable=no-member\n\n    def __addTerm(self, count, ind, sys, *args):\n        if callable(args[count][ind]):\n            lo = len(self.subSys)\n            self._qBase__subSys[str(lo)] = (sys, tuple(args[count])) # pylint: disable=no-member\n            count += 1\n            if count < len(args):\n                count = self.__addTerm(count, ind, sys, *args)\n        return count\n\n    def addTerm(self, *args):\n        counter = 0\n        while counter in range(len(args)):\n            # TODO write a generalisation for this one\n            if isinstance(args[counter][0], qSystem):\n                qSystems = args[counter]\n                if callable(args[counter+1][1]):\n                    #if tuple(args[counter + 1]) in self._qBase__subSys.keys(): # pylint: disable=no-member\n                    #    print(tuple(args[counter + 1]), 'already exists')\n                    lo = len(self.subSys)\n                    self._qBase__subSys[str(lo)] = (qSystems, tuple(args[counter + 1])) # pylint: disable=no-member\n                    counter += 2\n                # TODO does not have to pass qSystem around\n                if counter < len(args):\n                    counter = self._qCoupling__addTerm(counter, 1, qSystems, *args)\n        self._paramBoundBase__matrix = None # pylint: disable=assigning-non-slot\n        return self\n\n    @_recurseIfList\n    def removeSysCoupling(self, sys):\n        self.removeSubSys(sys, _exclude=[])\n\n    @_recurseIfList\n    def removeSubSys(self, subS, _exclude=[]): # pylint: disable=dangerous-default-value\n        vals = self._qBase__subSys.values() # pylint: disable=no-member\n        for ind, val in enumerate(vals):\n            systs = val[0]\n            if subS in systs:\n                self._qBase__subSys.pop(str(ind)) # pylint: disable=no-member\n", "meta": {"hexsha": "c11757400259207e239c9b553af9aa2b6f7e5285", "size": 37448, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/quanguru/classes/QSys.py", "max_stars_repo_name": "Qfabiolous/QuanGuru", "max_stars_repo_head_hexsha": "285ca44ae857cc61337f73ea2eb600f485a09e32", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/quanguru/classes/QSys.py", "max_issues_repo_name": "Qfabiolous/QuanGuru", "max_issues_repo_head_hexsha": "285ca44ae857cc61337f73ea2eb600f485a09e32", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/quanguru/classes/QSys.py", "max_forks_repo_name": "Qfabiolous/QuanGuru", "max_forks_repo_head_hexsha": "285ca44ae857cc61337f73ea2eb600f485a09e32", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.7480490524, "max_line_length": 174, "alphanum_fraction": 0.6423574023, "include": true, "reason": "from numpy,from scipy", "num_tokens": 8998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.19925680994841813}}
{"text": "'''\n------------------------------------------------------------------------\nLast updated 4/19/2018\n\nThis script produces the tables and figures for the Tax Function\nIntegration Paper\n\n------------------------------------------------------------------------\n'''\n\nimport pickle\nimport numpy as np\nimport scipy.optimize as opt\nimport matplotlib.pyplot as plt\nimport os\nimport xlsxwriter\nimport ogusa\nfrom ogusa.utils import REFORM_DIR, BASELINE_DIR\n\n# Read in tax function parameters\ntax_func_params = {}\ntax_func_list = ['DEP', 'DEP', 'DEP_totalinc', 'DEP_totalinc', 'GS',\n                 'GS']\nage_specific_list = [True, False, True, False, True, False]\nguid_list = ['_DEP_TI_noAge', '_DEP_TI_Age', '_DEP_noAge', '_DEP_Age',\n             '_GS_noAge', '_GS_Age']\ntax_func_params_base = {}\ntax_func_params_reform = {}\ntpi_base = {}\ntpi_reform = {}\nss_base = {}\nss_reform = {}\nfor guid in guid_list:\n        # NOTE TAHT SWITHC BASELINE AND REFORM SINCE TCJA CURRENT LAW\n        reform_path = os.path.join(BASELINE_DIR, guid,\n                                   'TxFuncEst_baseline' + guid + '.pkl')\n        base_path = os.path.join(REFORM_DIR, guid,\n                                 'TxFuncEst_policy' + guid + '.pkl')\n        tax_func_params_base[guid] = pickle.load(\n            open(base_path, 'rb'), encoding='latin')\n        tax_func_params_reform[guid] = pickle.load(\n            open(reform_path, 'rb'), encoding='latin')\n        tpi_reform_path = os.path.join(BASELINE_DIR, guid,\n                                       'TPI/TPI_vars.pkl')\n        tpi_base_path = os.path.join(REFORM_DIR, guid,\n                                     'TPI/TPI_vars.pkl')\n        tpi_base[guid] = pickle.load(\n            open(tpi_base_path, 'rb'), encoding='latin')\n        tpi_reform[guid] = pickle.load(\n            open(tpi_reform_path, 'rb'), encoding='latin')\n        ss_reform_path = os.path.join(BASELINE_DIR, guid,\n                                      'SS/SS_vars.pkl')\n        ss_base_path = os.path.join(REFORM_DIR, guid,\n                                    'SS/SS_vars.pkl')\n        ss_base[guid] = pickle.load(\n            open(ss_base_path, 'rb'), encoding='latin')\n        ss_reform[guid] = pickle.load(\n            open(ss_reform_path, 'rb'), encoding='latin')\n\n'''\n------------------------------------------------------------------------\n    Tables - all tables for paper saved to different worksheets in an\n    Excel workbook\n------------------------------------------------------------------------\n'''\n# open Excel workbook\nworkbook = xlsxwriter.Workbook('TFI_Tables.xlsx',\n                               {'nan_inf_to_errors': True})\n\n# Table 2: variation in phi by age for DEP function\n# create list of list with table info\nrate_labels = ['$ETR$', '$MTRx$', '$MTRy$']\nrate_types = ['etr', 'mtrx', 'mtry']\ntable2 = []\ntable2.append([''])\ntable2[0].extend(('21 to 54', '55 to 65', '66 to 80', 'All ages'))\nfor i, label in enumerate(rate_labels):\n    table2.append([label])\n    table2[i + 1].extend((\n        tax_func_params_base['_DEP_Age']['tfunc_' + rate_types[i] +\n                                         '_params_S'][:34, 0, -1].mean(),\n        tax_func_params_base['_DEP_Age']['tfunc_' + rate_types[i] +\n                                         '_params_S'][34:45, 0, -1].mean(),\n        tax_func_params_base['_DEP_Age']['tfunc_' + rate_types[i] +\n                                         '_params_S'][45:60, 0, -1].mean(),\n        tax_func_params_base['_DEP_Age']['tfunc_' + rate_types[i] +\n                                         '_params_S'][:, 0, -1].mean()))\n# save table of info to Excel\nworksheet = workbook.add_worksheet('Table 2')\nworksheet.merge_range('B1:D1', 'Age ranges')\nfor i, val in enumerate(table2):\n    for j, val2 in enumerate(table2[i]):\n        worksheet.write(i + 1, j, val2)\n\n# Table 3: comparing std errors across tax functions\ntax_func_labels = ['Ratio of polynomials, ETR',\n                   'Ratio of polynomials, vary by age, ETR',\n                   'Ratio of polynomials, vary by income source ETR',\n                   'Ratio of polynomials, vary by age and income source ETR',\n                   'Gouveia and Strauss (1994), ETR',\n                   'Gouveia and Strauss (1994), vary by age, ETR']\ntable3 = []\ntable3.append([''])\ntable3[0].extend(('All ages', '21 to 54', '55 to 65', '66 to 80'))\nfor i, label in enumerate(tax_func_labels):\n    table3.append([label])\n    table3[i + 1].extend((\n        tax_func_params_base[guid_list[i]]['tfunc_etr_sumsq'][:, 0].sum()\n        / tax_func_params_base[guid_list[i]]['tfunc_etr_obs'][:, 0].sum(),\n        tax_func_params_base[guid_list[i]]['tfunc_etr_sumsq'][:34, 0].sum()\n        / tax_func_params_base[guid_list[i]]['tfunc_etr_obs'][:34, 0].sum(),\n        tax_func_params_base[guid_list[i]]['tfunc_etr_sumsq'][34:45, 0].sum()\n        / tax_func_params_base[guid_list[i]]['tfunc_etr_obs'][34:45, 0].sum(),\n        tax_func_params_base[guid_list[i]]['tfunc_etr_sumsq'][45:60, 0].sum()\n        / tax_func_params_base[guid_list[i]]['tfunc_etr_obs'][45:60, 0].sum()))\n# save table of info to Excel\nworksheet = workbook.add_worksheet('Table 3')\nworksheet.merge_range('B1:E1', 'Age ranges')\nfor i, val in enumerate(table3):\n    for j, val2 in enumerate(table3[i]):\n        worksheet.write(i + 1, j, val2)\n\n# Table 4: comparing SSE across tax functions\ntable4 = []\ntable4.append([''])\ntable4[0].extend(('All ages', '21 to 54', '55 to 65', '66 to 80'))\nfor i, label in enumerate(tax_func_labels):\n    table4.append([label])\n    table4[i + 1].extend((\n        tax_func_params_base[guid_list[i]]['tfunc_etr_sumsq'][:, 0].mean(),\n        tax_func_params_base[guid_list[i]]['tfunc_etr_sumsq'][:34, 0].mean(),\n        tax_func_params_base[guid_list[i]]['tfunc_etr_sumsq'][34:45, 0].mean(),\n        tax_func_params_base[guid_list[i]]['tfunc_etr_sumsq'][45:60, 0].mean()))\n# save table of info to Excel\nworksheet = workbook.add_worksheet('Table 4')\nworksheet.merge_range('B1:E1', 'Age ranges')\nfor i, val in enumerate(table4):\n    for j, val2 in enumerate(table4[i]):\n        worksheet.write(i + 1, j, val2)\n\n# Table 5: comparing observations across tax functions\ntable5 = []\ntable5.append([''])\ntable5[0].extend(('All ages', '21 to 54', '55 to 65', '66 to 80'))\nfor i, label in enumerate(tax_func_labels):\n    table5.append([label])\n    table5[i + 1].extend((\n        tax_func_params_base[guid_list[i]]['tfunc_etr_obs'][:, 0].sum(),\n        tax_func_params_base[guid_list[i]]['tfunc_etr_obs'][:34, 0].sum(),\n        tax_func_params_base[guid_list[i]]['tfunc_etr_obs'][34:45, 0].sum(),\n        tax_func_params_base[guid_list[i]]['tfunc_etr_obs'][45:60, 0].sum()))\n# save table of info to Excel\nworksheet = workbook.add_worksheet('Table 5')\nworksheet.merge_range('B1:E1', 'Age ranges')\nfor i, val in enumerate(table5):\n    for j, val2 in enumerate(table5[i]):\n        worksheet.write(i + 1, j, val2)\n\n# Table 6: parameter estimates from baseline and reform for DEP funcs\n# report parameters from function for 42 year old in first year of window\nparam_names = ['$A$', '$B$', '$C$', '$D$', '$max_x$', '$min_x$',\n               '$max_y$', '$min_y$', '$shift_x$', '$shift_y$',\n               '$shift$', '$share$']\ntable6 = []\ntable6.append(['Parameter'])\ntable6[0].extend(tuple(rate_labels * 2))\nfor i, label in enumerate(param_names):\n    table6.append([label])\n    for j, rate in enumerate(rate_types):  # for baseline results\n        table6[i + 1].append(\n            tax_func_params_base['_DEP_Age']['tfunc_' + rate +\n                                             '_params_S'][21, 0, i])\n    for j, rate in enumerate(rate_types):  # for reform results\n        table6[i + 1].append(\n            tax_func_params_reform['_DEP_Age']['tfunc_' + rate +\n                                               '_params_S'][21, 0, i])\ntable6.append(['Obs (N)'])\ntable6.append(['SSE'])\nfor j, rate in enumerate(rate_types):\n    table6[-2].append(\n        tax_func_params_base['_DEP_Age']['tfunc_' + rate +\n                                         '_obs'][21, 0])\n    table6[-1].append(\n        tax_func_params_base['_DEP_Age']['tfunc_' + rate +\n                                         '_sumsq'][21, 0])\nfor j, rate in enumerate(rate_types):\n    table6[-2].append(\n        tax_func_params_reform['_DEP_Age']['tfunc_' + rate +\n                                           '_obs'][21, 0])\n    table6[-1].append(\n        tax_func_params_reform['_DEP_Age']['tfunc_' + rate +\n                                           '_sumsq'][21, 0])\n# save table of info to Excel\nworksheet = workbook.add_worksheet('Table 6')\nworksheet.merge_range('B1:D1', '2017 Law')\nworksheet.merge_range('E1:G1', 'TCJA')\nfor i, val in enumerate(table6):\n    for j, val2 in enumerate(table6[i]):\n        worksheet.write(i + 1, j, val2)\n\n\n# Table 8: GDP changes across tax functions\ntax_func_labels = ['Ratio of polynomials, ETR',\n                   'Ratio of polynomials, vary by age, ETR',\n                   'Ratio of polynomials, vary by income source ETR',\n                   'Ratio of polynomials, vary by age and income source ETR',\n                   'Gouveia and Strauss (1994), ETR',\n                   'Gouveia and Strauss (1994), vary by age, ETR']\ntable8 = []\nfor i, label in enumerate(tax_func_labels):\n    table8.append([label])\n    for y in range(10):\n        table8[i].append(((tpi_reform[guid_list[i]]['Y'][y] -\n                           tpi_base[guid_list[i]]['Y'][y])\n                          / tpi_base[guid_list[i]]['Y'][y]))\n    table8[i].extend((\n        ((tpi_reform[guid_list[i]]['Y'][:11].sum() -\n          tpi_base[guid_list[i]]['Y'][:11].sum())\n         / tpi_base[guid_list[i]]['Y'][:11].sum()),\n        ((ss_reform[guid_list[i]]['Yss'] -\n          ss_base[guid_list[i]]['Yss'])\n         / ss_base[guid_list[i]]['Yss'])))\n# save table of info to Excel\nworksheet = workbook.add_worksheet('Table 8')\nworksheet.write(0, 0, 'Tax Function')\nfor y in range(2018, 2028):\n    worksheet.write(0, y - 2017, str(y))\nworksheet.write(0, 11, '2018-2027')\nworksheet.write(0, 12, 'SS')\nfor i, val in enumerate(table8):\n    for j, val2 in enumerate(table8[i]):\n        worksheet.write(i + 1, j, val2)\n\n# Table 9: Changes in all macro aggregates for DEP only\nresults_labels = ['GDP', 'Conusmption', 'Investment', 'Hours Worked',\n                  'Avg. Wage', 'Interest Rate', 'Total Taxes']\nvar_names = ['Y', 'C', 'I', 'L', 'w', 'r', 'REVENUE']\nss_var_names = ['Yss', 'Css', 'Iss', 'Lss', 'wss', 'rss', 'revenue_ss']\ntable9 = []\nfor i, label in enumerate(results_labels):\n    table9.append([label])\n    for y in range(10):\n        table9[i].append(((tpi_reform['_DEP_Age'][var_names[i]][y] -\n                           tpi_base['_DEP_Age'][var_names[i]][y])\n                          / tpi_base['_DEP_Age'][var_names[i]][y]))\n    table9[i].extend((\n        ((tpi_reform['_DEP_Age'][var_names[i]][:11].sum() -\n          tpi_base['_DEP_Age'][var_names[i]][:11].sum())\n         / tpi_base['_DEP_Age'][var_names[i]][:11].sum()),\n        ((ss_reform['_DEP_Age'][ss_var_names[i]] -\n          ss_base['_DEP_Age'][ss_var_names[i]])\n         / ss_base['_DEP_Age'][ss_var_names[i]])))\n# save table of info to Excel\nworksheet = workbook.add_worksheet('Table 9')\nworksheet.write(0, 0, 'Macroeconomic Variables')\nfor y in range(2018, 2028):\n    worksheet.write(0, y - 2017, str(y))\nworksheet.write(0, 11, '2018-2027')\nworksheet.write(0, 12, 'SS')\nfor i, val in enumerate(table9):\n    for j, val2 in enumerate(table9[i]):\n        worksheet.write(i + 1, j, val2)\n\nworkbook.close()\n\n'''\nFIGURES\n'''\n\n\"\"\"\nThis version: 12 May 2018\nWritten by Kerk Phillips\n\nThis program fits tax functions for \"Integrating Microsimulation Models of Tax\nPolicy into a DGE Macroeconomic Model: A Canonical Example,\" by DeBaker, Evans\nand Phillips.\n\nThis file fits data from Tax Calc to three different functions, compares the\ngoodness-of-fit, and plots the functions against the data.  The data sample\ncan be restricted by the age and the capital income of the individuals.\n\"\"\"\n\n\n\ndef GS(coeffs, *args):\n    '''\n    This is the functional from from Gouveia and Strass (1994) with an\n    additional free parameter\n    '''\n    # unpack coefficients\n    phi0, phi1, phi2 = coeffs\n    # unpack data\n    I, taxes, wgts = args\n    # I = x+y\n    errors = (taxes/I) - ((phi0*(I - (I**(-phi1) + phi2)**(-1/phi1)))/I)\n    wsse = (wgts * (errors ** 2)).sum()\n    print('GS SSE: ', wsse)\n    print('coeffs = ', phi0, phi1, phi2)\n    return wsse\n\n\n'''\nThe functions below call those above and return the square-root of the sum of\nsquared errors (SSE) for each model\n'''\n# load data from pkl file then clean it up (like in txfunc.py)\nmicro_data = pickle.load(open(\"micro_data_2017Law.pkl\", \"rb\"),\n                         encoding='latin1')\ndata_orig = micro_data['2018']\ndata_orig['Total Labor Income'] = \\\n    (data_orig['Wage income'] +\n     data_orig['SE income'])\ndata_orig['Effective Tax Rate'] = \\\n    (data_orig['Total tax liability'] /\n     data_orig[\"Adjusted total income\"])\ndata_orig[\"Total Capital Income\"] = \\\n    (data_orig['Adjusted total income'] -\n     data_orig['Total Labor Income'])\n# use weighted avg for MTR labor - abs value because\n# SE income may be negative\ndata_orig['MTR Labor'] = \\\n    (data_orig['MTR wage income'] * (data_orig['Wage income'] /\n     (data_orig['Wage income'].abs() +\n     data_orig['SE income'].abs())) +\n     data_orig['MTR SE income'] *\n     (data_orig['SE income'].abs() /\n     (data_orig['Wage income'].abs() +\n      data_orig['SE income'].abs())))\ndata = data_orig[['Age', 'MTR Labor', 'MTR capital income',\n                  'Total Labor Income', 'Total Capital Income',\n                  'Adjusted total income', 'Effective Tax Rate',\n                  'Weights']]\n# Clean up the data by dropping outliers\n# drop all obs with ETR > 0.65\ndata_trnc = \\\n    data.drop(data[data['Effective Tax Rate'] > 0.65].index)\n# drop all obs with ETR < -0.15\ndata_trnc = \\\n    data_trnc.drop(data_trnc[data_trnc['Effective Tax Rate']\n                             < -0.15].index)\n# drop all obs with ATI, TLI, TCI < $5\ndata_trnc = data_trnc[(data_trnc['Adjusted total income'] >= 5)\n                      & (data_trnc['Total Labor Income'] >= 5) &\n                      (data_trnc['Total Capital Income'] >= 5)]\n\n# drop all obs with MTR on capital income > 10.99\ndata_trnc = \\\n    data_trnc.drop(data_trnc[data_trnc['MTR capital income']\n                             > 0.99].index)\n# drop all obs with MTR on capital income < -0.45\ndata_trnc = \\\n    data_trnc.drop(data_trnc[data_trnc['MTR capital income']\n                             < -0.45].index)\n# drop all obs with MTR on labor income > 10.99\ndata_trnc = data_trnc.drop(data_trnc[data_trnc['MTR Labor']\n                                     > 0.99].index)\n# drop all obs with MTR on labor income < -0.45\ndata_trnc = data_trnc.drop(data_trnc[data_trnc['MTR Labor']\n                                     < -0.45].index)\ndata_baseline = data_trnc\n\n# calculate total taxes\ndata_baseline['Taxes'] = (data_baseline['Effective Tax Rate'] *\n                          data_baseline['Adjusted total income'])\n\n# get time-series of interest  - for 43 year old in 2017\ndata_to_use = data_baseline[data_baseline['Age'] == 42].copy()\ny = data_to_use['Total Capital Income'].values\nx = data_to_use['Total Labor Income'].values\nI = data_to_use['Adjusted total income'].values\ntaxes = data_to_use['Taxes'].values\nwgts = data_to_use['Weights'].values\netr_data = data_to_use['Effective Tax Rate'].values\ntx_objs = (I, taxes, wgts)\n\n# # set bounds on coefficients\n# Gbounds = ((0, None), (0, None), (0, None))\n#\n# # set starting guesses for coefficients\n# Gguess = np.array([0.3745, 0.7525, 0.7368])\n#\n# # use minimizer to solve for coefficients\n# # Gouveia and Strauss\n# Gout = opt.minimize(GS, Gguess,\n#     args=(tx_objs), method=\"L-BFGS-B\", bounds=Gbounds, tol=1e-15)\n# Gcoeffs = Gout.x\n# G_SSE = Gout.fun\n# print 'GS coeffs, Obs, SSE: ', Gcoeffs, len(taxes), G_SSE\n\n\n# Plot tax function curves in 2D\n# plot GS vs alt function against data for a given year/age\nnpts = len(I)  # points in grid\nmaxinc = 300000.  # upper end of grid\nmininc = 0.  # lower end of grid\nygrid = np.zeros(npts)  # this is just a place holder to pass\nxgrid = np.linspace(mininc, maxinc, npts)\ndatagrid = (ygrid, xgrid)  # tuple to pass to functions\nGcoeffs = np.zeros((3,))\nGcoeffs[0] = (tax_func_params_base['_GS_Age']['tfunc_etr_params_S'][21, 0, 0])\nGcoeffs[1] = (tax_func_params_base['_GS_Age']['tfunc_etr_params_S'][21, 0, 1])\nGcoeffs[2] = (tax_func_params_base['_GS_Age']['tfunc_etr_params_S'][21, 0, 2])\n# put in terms of ETR by dividing by xgrid\nGyfit = ((Gcoeffs[0] * (xgrid - (xgrid ** (-Gcoeffs[1]) + Gcoeffs[2]) **\n                        (-1 / Gcoeffs[1]))) / xgrid)\n\nA = (tax_func_params_base['_DEP_Age']['tfunc_etr_params_S'][21, 0, 0])\nB = (tax_func_params_base['_DEP_Age']['tfunc_etr_params_S'][21, 0, 1])\nC = (tax_func_params_base['_DEP_Age']['tfunc_etr_params_S'][21, 0, 2])\nD = (tax_func_params_base['_DEP_Age']['tfunc_etr_params_S'][21, 0, 3])\nmax_x = (tax_func_params_base['_DEP_Age']['tfunc_etr_params_S'][21, 0, 4])\nmin_x = (tax_func_params_base['_DEP_Age']['tfunc_etr_params_S'][21, 0, 5])\nmax_y = (tax_func_params_base['_DEP_Age']['tfunc_etr_params_S'][21, 0, 6])\nmin_y = (tax_func_params_base['_DEP_Age']['tfunc_etr_params_S'][21, 0, 7])\nshift_x = (tax_func_params_base['_DEP_Age']['tfunc_etr_params_S'][21, 0, 8])\nshift_y = (tax_func_params_base['_DEP_Age']['tfunc_etr_params_S'][21, 0, 9])\nshift = (tax_func_params_base['_DEP_Age']['tfunc_etr_params_S'][21, 0, 10])\nshare = (tax_func_params_base['_DEP_Age']['tfunc_etr_params_S'][21, 0, 11])\nprint('Main spec params = ',\n      tax_func_params_base['_DEP_Age']['tfunc_etr_params_S'][21, 0, :])\n\nX = xgrid.copy()\nY = xgrid.copy()*0.0\nX2 = X ** 2\nY2 = Y ** 2\ntau_x = (((max_x - min_x) * (A * X2 + B * X) / (A * X2 + B * X + 1))\n         + min_x)\ntau_y = (((max_y - min_y) * (C * Y2 + D * Y) / (C * Y2 + D * Y + 1))\n         + min_y)\nDEP_fit_nocapital = ((((tau_x + shift_x) ** share) * ((tau_y + shift_y)\n                                                      ** (1 - share))) +\n                     shift)\n\nX = xgrid.copy() * 0.7\nY = xgrid.copy() * 0.3\nX2 = X ** 2\nY2 = Y ** 2\ntau_x = (((max_x - min_x) * (A * X2 + B * X) / (A * X2 + B * X + 1))\n         + min_x)\ntau_y = (((max_y - min_y) * (C * Y2 + D * Y) / (C * Y2 + D * Y + 1))\n         + min_y)\nDEP_fit_nolabor = (((tau_x + shift_x) ** share) * ((tau_y + shift_y) **\n                                                   (1 - share))) + shift\n\n# plot data\n# plt.plot(I, etr_data, '.b', ms = 1, label='data')\nplt.plot(I, etr_data, '.b', label='data')\nplt.plot(xgrid, Gyfit, 'm-', lw=1, label='GS')\nplt.plot(xgrid, DEP_fit_nocapital, '-', color='orange', lw=1,\n         label='DEP, no y')\nplt.plot(xgrid, DEP_fit_nolabor, '-', color='green', lw=1,\n         label='DEP, mixed')\nplt.xlabel('Total Income')\nplt.ylabel('Effective Tax Rate')\n# set axes range\nplt.xlim(0, 100000)\nplt.ylim(-0.2, 0.32)\nplt.legend(loc='lower right')\nplt.suptitle('Age = 43, Year = 2018')\n# save high quality version to external file\nplt.savefig('Compare_ETR_functions.png')\nplt.show()\n\nplt.plot(I, etr_data, '.b', label='data')\nplt.plot(xgrid, DEP_fit_nocapital, '-', color='orange', lw=1,\n         label='DEP, no y')\nplt.plot(xgrid, DEP_fit_nolabor, '-', color='green', lw=1,\n         label='DEP, mixed')\nplt.xlabel('Total Income')\nplt.ylabel('Effective Tax Rate')\n# set axes range\nplt.xlim(0, 100000)\nplt.ylim(-0.2, 0.32)\nplt.legend(loc='lower right')\nplt.suptitle('Age = 43, Year = 2018')\n# save high quality version to external file\nplt.savefig('Compare_DEP_ETR_functions.png')\nplt.show()\n", "meta": {"hexsha": "a22964165eb8810072fd3ce7134faaec553b196d", "size": 19634, "ext": "py", "lang": "Python", "max_stars_repo_path": "TFI_tables_figures.py", "max_stars_repo_name": "rickecon/TaxFuncIntegr", "max_stars_repo_head_hexsha": "715cc76e3305c00dd64d79521c504bb388c6d87d", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TFI_tables_figures.py", "max_issues_repo_name": "rickecon/TaxFuncIntegr", "max_issues_repo_head_hexsha": "715cc76e3305c00dd64d79521c504bb388c6d87d", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-02T18:24:17.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-02T18:24:17.000Z", "max_forks_repo_path": "TFI_tables_figures.py", "max_forks_repo_name": "rickecon/TaxFuncIntegr", "max_forks_repo_head_hexsha": "715cc76e3305c00dd64d79521c504bb388c6d87d", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-09-18T01:39:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-02T12:54:55.000Z", "avg_line_length": 40.9895615866, "max_line_length": 80, "alphanum_fraction": 0.5987572578, "include": true, "reason": "import numpy,import scipy", "num_tokens": 5729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.19925679704843258}}
{"text": "#!/usr/bin/env python\n\n\"\"\"capture_stats.py: Sensitivity test experiments python program for Doppler shift\"\"\"\n\n__author__ = \"Chakraborty, S.\"\n__copyright__ = \"Copyright 2021, SuperDARN@VT\"\n__credits__ = []\n__license__ = \"MIT\"\n__version__ = \"1.0.\"\n__maintainer__ = \"Chakraborty, S.\"\n__email__ = \"shibaji7@vt.edu\"\n__status__ = \"Research\"\n\nimport os\nimport sys\nsys.path.append(\"../sd/\")\nimport datetime as dt\nimport pandas as pd\nimport argparse\nfrom dateutil import parser as dparser\nimport numpy as np\nfrom netCDF4 import Dataset\nimport time\nimport glob\nfrom scipy.integrate import trapz\nfrom scipy import signal\nfrom scipy.io import loadmat\n\nfrom pysolar.solar import get_altitude\nimport plotlib\n\ndef calculate_sza(d, lats, lons, alt=300):\n    d = d.replace(tzinfo=dt.timezone.utc)\n    szas = []\n    for la, lo in zip(lats, lons):\n        szas.append(90. - get_altitude(la, lo, d))\n    return szas\n\nINT_F = 300\ndef get_freq(dn, rad):\n    f = 12.\n    fname = \"../data/op/{dn}/waccmx/sd_{rad}_data.csv.gz\".format(dn=dn.strftime(\"%Y.%m.%d.%H.%M\"),rad=rad)\n    if os.path.exists(fname):\n        os.system(\"gzip -d \" + fname)\n        du = pd.read_csv(fname.replace(\".gz\", \"\"))\n        os.system(\"gzip \" + fname.replace(\".gz\", \"\"))\n        if len(du) > 0: f = np.median(du.tfreq)/1e3\n    return f\n\ndef get_vdeta(d, rlim, freq):\n    d = d[(d.height>=rlim[0]) & (d.height<rlim[1])]\n    f = trapz(signal.resample(d.dop,INT_F))\n    v = (0.5 * f * 3e8 / (freq * 1e6))\n    return v\n\ndef _estimate_dop_delh_(x, y, freq, phi=0):\n    dh = (np.max(x.height) - np.max(y.height)) * 1000.\n    xf = (-2.*freq*1e6/3e8) * (dh/60.) * np.cos(np.deg2rad(phi))\n    xd = 0.5 * xf * 3e8 / (freq * 1e6)\n    return xd\n\nsim_fname = \"finescale_simulate_total_{kind}.csv\"\nt, T = True, True\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"-v\", \"--verbose\", action=\"store_false\", help=\"Increase output verbosity (default True)\")\n    parser.add_argument(\"-pl\", \"--plot\", action=\"store_true\", help=\"Analyze sensitivity (default False)\")\n    parser.add_argument(\"-t\", \"--type\", default=\"A\", help=\"Flare type (A/X/M)\")\n    parser.add_argument(\"-n\", \"--number\", default=-1, type=int, help=\"Number of radar event\")\n    d_reg, e_reg, f_reg = [60,90], [100,130], [140,300]\n    args = parser.parse_args()\n    model = \"waccmx\"\n    vD, vE, vF, vFh, vT, SZA, E, F = [], [], [], [], [], [], [], []\n    events = pd.read_csv(\"op/radar_event_list.csv\", parse_dates=[\"date\"])\n    T, kind = 1, \"A\"\n    if args.type == \"M\" or args.type == \"X\":\n        events = events[events.type.str.contains(args.type)]\n        T, kind = 0, args.type\n    if args.number >= 0:\n        events = events.iloc[[args.number]]\n        T, kind = 0, events.rad.tolist()[0] + \"_\" + events.date.tolist()[0].strftime(\"%Y-%m-%d-%H-%M\")\n    if not args.plot: \n        ix = 0\n        for d, r in zip(events.date.tolist(), events.rad.tolist()):\n            print(\"Events - \", r, d)\n            if ix >= T: \n                freq = get_freq(d, r)\n                for bm in range(24):\n                    bearing_file = \"../data/op/%s/waccmx/%s/bm.%02d/bearing.mat\"%(d.strftime(\"%Y.%m.%d.%H.%M\"), r, bm)\n                    print(bearing_file)\n                    obj = loadmat(bearing_file)\n                    lat, lon = obj[\"lat\"], obj[\"lon\"]\n                    sza = np.mean(calculate_sza(d, lat, lon))\n                    dic = \"../data/op/{dn}/waccmx/{r}/bm.{bm}/\".format(r=r,bm=\"%02d\"%bm,dn=d.strftime(\"%Y.%m.%d.%H.%M\"))\n                    for i in range(18,19):\n                        i_start, i_end = 16, 30\n                        for elv in np.linspace(i_start, i_end, (i_end-i_start)*2 + 1):\n                            if elv.is_integer(): fname = dic + \"ti(%02d)_elv(%d)_f.csv\"%(i,elv)\n                            else: fname = dic + \"ti(%02d)_elv(%.1f)_f.csv\"%(i,elv)\n                            files = glob.glob(fname)\n                            for f in files:\n                                try:\n                                    T = False\n                                    ff = pd.read_csv(f)\n                                    vd = np.abs(get_vdeta(ff, d_reg, freq))\n                                    ve = np.abs(get_vdeta(ff, e_reg, freq))\n                                    vf = np.abs(get_vdeta(ff, f_reg, freq))\n                                    bf = pd.read_csv(f.replace(\"_f.\",\"_d.\"))\n                                    vfh = np.abs(_estimate_dop_delh_(ff,bf,freq))\n                                    vD.append(vd)\n                                    vE.append(ve)\n                                    vF.append(vf)\n                                    vFh.append(vfh)\n                                    vT.append(vd+ve+vf+vfh)\n                                    SZA.append(sza)\n                                    E.append(elv)\n                                    F.append(freq)\n                                except: pass\n            #if t and T: break\n            ix += 1\n        x = pd.DataFrame()\n        x[\"vD\"], x[\"vE\"], x[\"vF\"], x[\"vFh\"], x[\"vT\"], x[\"sza\"], x[\"elv\"], x[\"freq\"] = vD, vE, vF, vFh, vT, SZA, E, F\n        x = x.round(3)\n        x.to_csv(\"op/\" + sim_fname.format(kind=kind), index=False)\n    else:\n        print(\" Compile plots...\")\n        print(\"op/\"+sim_fname.format(kind=kind))\n        x0 = pd.read_csv(\"op/\"+sim_fname.format(kind=kind))\n        x0 = x0[(np.abs(x0.vT)>30) & (np.abs(x0.vT)<300)]\n        vd0, ve0, vf0 = np.array(x0.vD/x0.vT), np.array(x0.vE/x0.vT), np.array((x0.vF + x0.vFh)/x0.vT)\n        vdn0, vdh0 = np.array((x0.vD + x0.vE + x0.vF)/x0.vT), np.array(x0.vFh/x0.vT)\n        x = pd.read_csv(\"op/finescale_simulate.csv\")\n        x = x[(np.abs(x.vT)>30) & (np.abs(x.vT)<300)]\n        vd, ve, vf = np.array(x.vD/x.vT), np.array(x.vE/x.vT), np.array((x.vF + x.vFh)/x.vT)\n        vdn, vdh = np.array((x.vD + x.vE + x.vF)/x.vT), np.array(x.vFh/x.vT)\n        plotlib.plot_mastogram(vd, ve, vf, vdn, vdh, vd0, ve0, vf0, vdn0, vdh0)\n    if os.path.exists(\"__pycache__/\"):\n        os.system(\"rm -rf __pycache__/\")\n        os.system(\"rm -rf py*.log\")\n", "meta": {"hexsha": "28dc7e1f47c74bcc9de3bf5304ce60fce5ee6eb8", "size": 6080, "ext": "py", "lang": "Python", "max_stars_repo_path": "code_rt_sd/stats/capture_stats.py", "max_stars_repo_name": "shibaji7/Collaboration_NCAR", "max_stars_repo_head_hexsha": "c27e0ad8a1f0c6b2e66fa07e6cf57f98c4389899", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-12T14:40:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T14:40:49.000Z", "max_issues_repo_path": "code_rt_sd/stats/capture_stats.py", "max_issues_repo_name": "shibaji7/Collaboration_NCAR", "max_issues_repo_head_hexsha": "c27e0ad8a1f0c6b2e66fa07e6cf57f98c4389899", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code_rt_sd/stats/capture_stats.py", "max_forks_repo_name": "shibaji7/Collaboration_NCAR", "max_forks_repo_head_hexsha": "c27e0ad8a1f0c6b2e66fa07e6cf57f98c4389899", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4285714286, "max_line_length": 120, "alphanum_fraction": 0.5106907895, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.19925679704843258}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\nvslab2d\n=======\n\nA script for displaying and saving density distribution generated by\nscft_confined/SlabXX2d, where XX stands for the polymer model. For A-B diblock\ncopolymer, XX=AB.\n\nCopyright (C) 2013 Yi-Xin Liu (lyx@fudan.edu.cn)\n\n'''\n\nimport argparse\nimport os\nimport glob\nimport json\nfrom ConfigParser import SafeConfigParser\n\nimport numpy as np\nfrom scipy.io import loadmat, savemat\nimport matplotlib.pylab as plt\n\nfrom chebpy import cheb_barycentric_matrix\n\nfrom scftpy import scft_contourf, SCFTConfig\n\nparser = argparse.ArgumentParser(description='vis_slab2d options')\n\nparser.add_argument('-b', '--batch',\n                    action='store_true',\n                    help='If present or True, perform batch mode.')\nparser.add_argument('-r', '--path',\n                    default='.',\n                    help='Path to be processed, for batch mode use.')\nparser.add_argument('-p', '--param_file',\n                    default='param.ini',\n                    help='SCFT configuration file, *.ini')\nparser.add_argument('-d', '--data_file',\n                    default='scft_out',\n                    help='SCFT generated data file, *.mat')\nparser.add_argument('-s', '--save',\n                    action='store_true',\n                    help='If present or True, save figure.')\nargs = parser.parse_args()\n\n\ndef batch_vis_slab2d(path='.', param='param.ini', data='scft_out'):\n    '''\n    Batch mode vis_slab2d, for all directory in the <path>.\n    Note: ONLY directories in the path will be processed.\n    The input var <data> is the main part of the whole data file name. The\n    suffix is in the form '_XXXX', where XXXX is the max number of time steps.\n    Then the full data file name is 'scft_out_XXXX.mat', the '.mat' can be\n    ignored.\n    Generated figures are stored in the same directory as its data file.\n    Other data, such as H, are stored in the parent path as 'data.mat'.\n    '''\n    is_save = True  # Do not show figure in the batch mode\n\n    var = []\n    F = []\n\n    for f in os.listdir(path):\n        p = os.path.join(path, f)  # path\n        if os.path.isdir(p):\n            pt = os.path.join(p, data+'_*.mat')  # path to be globbed\n            datafiles = glob.glob(pt)\n            fnames = [os.path.basename(x) for x in datafiles]\n            data_name = get_final_datafile(fnames)\n            if data_name == '':\n                print p, ' data file missing.'\n                continue\n            pfile = os.path.join(p, param)\n            if not os.path.exists(pfile):\n                print p, ' configuration file missing.'\n                continue\n            dfile = os.path.join(p, data_name)\n            vis_slab2d(pfile, dfile, is_save)\n            print pfile, dfile\n            v = get_var(pfile)\n            var.append(v)\n            mat = loadmat(dfile)\n            F.append(mat['F'][-1, 0])\n            print v, mat['F'][-1, 0]\n\n    savemat(os.path.join(path, 'data'), {'v': var, 'F': F})\n\n\ndef get_var(param_file):\n    '''\n        Get the main batch variable and its current value.\n    '''\n    cfg = SafeConfigParser(allow_no_value=True)\n    cfg.optionxform = str\n    cfg.read(param_file)\n    section = cfg.get('Batch', 'section')\n    # name list of the batch variable\n    batch_var = json.loads(cfg.get('Batch', 'var'))\n    var_name = batch_var[0]  # the main batch variable is the first one\n    if (var_name == 'BC_coefficients_left'\n            or var_name == 'BC_coefficients_right'):\n        bc = json.loads(cfg.get(section, var_name))\n        var = bc[1]\n    else:\n        var = cfg.getfloat(section, var_name)\n    return var\n\n\ndef get_final_datafile(namelist):\n    '''\n    Each name has the form 'scft_out_XXXX.mat', where XXXX is a number.\n    '''\n    data = ''\n    num = 0  # a number to be compared\n    for f in namelist:\n        name, ext = os.path.splitext(f)  # split into 'scft_out_XXXX', '.mat'\n        fragments = name.split('_')  # split into 'scft', 'out', 'XXXX'\n        n = int(fragments[-1])\n        if n > num:\n            num = n\n            data = name\n    return data\n\n\ndef vis_slab2d(param='param.ini', data='scft_out', is_save=False):\n    '''\n    Visualize 2D data generated by DiskXX, here XX represents the polymer model, e.g. XX = AB stands for A-B diblock copolymers.\n    '''\n    is_show = not is_save\n    path = os.path.dirname(data)\n\n    config = SCFTConfig.from_file(param)\n    Nx, Ny = config.grid.Lx, config.grid.Ly\n    Lx = config.uc.a\n    Ly = config.uc.b\n    print Nx, Ny, Lx, Ly\n    Nxp = Nx + 1\n    Nyp = 2 * Ny\n\n    mat = loadmat(data)\n    phiA = mat['phiA']\n    phiB = mat['phiB']\n    #phiAB = phiA - phiB\n\n    if not (Nx, Ny) == phiA.shape:\n        raise 'Data file does not match param file.'\n\n    # Periodic in x direction, Fourier\n    xxp = np.linspace(0, Lx, Nxp)\n    # Non-periodic in y direction, Chebyshev\n    #ii = np.arange(Ny)\n    #yy = np.cos(np.pi * ii / (Ny-1))  # rr [-1, 1]\n    yyp = np.linspace(0, Ly, Nyp)\n    yp, xp = np.meshgrid(yyp, xxp)\n\n    phiAp = np.zeros([Nxp, Ny])\n    phiBp = np.zeros([Nxp, Ny])\n    phiAp[:-1, :] = phiA\n    phiAp[-1, :] = phiA[0, :]\n    phiBp[:-1, :] = phiB\n    phiBp[-1, :] = phiB[0, :]\n    phiAp = cheb_interp2d_y(phiAp, yyp)\n    phiBp = cheb_interp2d_y(phiBp, yyp)\n    phiABp = phiBp - phiAp\n    if is_show:\n        plt.plot(yyp, phiAp[Nxp/2, :])\n        plt.plot(yyp, phiBp[Nxp/2, :])\n        plt.plot(yyp, phiABp[Nxp/2, :])\n        #scft_contourf(xp, yp, phiAp, show_cbar=True)\n        #scft_contourf(xp, yp, phiBp, show_cbar=True)\n        #scft_contourf(xp, yp, phiABp, show_cbar=True)\n        scft_contourf(xp, yp, phiAp)\n        scft_contourf(xp, yp, phiBp)\n        scft_contourf(xp, yp, phiABp)\n        plt.show()\n    if is_save:\n        figA = os.path.join(path, 'phiA.png')\n        figB = os.path.join(path, 'phiB.png')\n        figAB = os.path.join(path, 'phiAB.png')\n        scft_contourf(xp, yp, phiAp)\n        plt.savefig(figA)\n        scft_contourf(xp, yp, phiBp)\n        plt.savefig(figB)\n        scft_contourf(xp, yp, phiABp)\n        plt.savefig(figAB)\n\n\ndef cheb_interp2d_y(u, vy):\n    '''\n    Use chebyshev interpolation for the last dimension of Cartesian coordinates\n    (x, y).\n    u(x, y): source data\n    vy: vector to be interpolated, size is Nyp.\n    '''\n    Nx, Ny = u.shape\n    Nyp = vy.size\n    uout = np.zeros([Nx, Nyp])\n    vyp = np.linspace(-1, 1, Nyp)\n    T = cheb_barycentric_matrix(vyp, Ny-1)\n    for i in xrange(Nx):\n        uout[i] = np.dot(T, u[i])\n    return uout\n\n\nif __name__ == '__main__':\n    if args.batch:\n        batch_vis_slab2d(args.path, args.param_file, args.data_file)\n    else:\n        vis_slab2d(args.param_file, args.data_file, args.save)\n", "meta": {"hexsha": "930ea05321f333616ac64fc379e97f3e48e19959", "size": 6675, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/vis_slab2d.py", "max_stars_repo_name": "liuyxpp/scftpy", "max_stars_repo_head_hexsha": "c203412b96f679d52759a935a2500705afd827a5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-18T14:04:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T17:19:52.000Z", "max_issues_repo_path": "scripts/vis_slab2d.py", "max_issues_repo_name": "liuyxpp/scftpy", "max_issues_repo_head_hexsha": "c203412b96f679d52759a935a2500705afd827a5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/vis_slab2d.py", "max_forks_repo_name": "liuyxpp/scftpy", "max_forks_repo_head_hexsha": "c203412b96f679d52759a935a2500705afd827a5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-12T12:15:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T12:15:52.000Z", "avg_line_length": 31.4858490566, "max_line_length": 128, "alphanum_fraction": 0.5907116105, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.19923329715255295}}
{"text": "#!/usr/bin/env python\n\nimport os\nimport argparse\nimport numpy as np\nimport uproot\nfrom coffea import hist\nimport awkward as ak\n\nfrom sklearn.metrics import roc_curve, auc\nimport matplotlib.pyplot as plt\nimport mplhep as hep\n\nplt.style.use(hep.style.ROOT)\n\nmass_branch = \"fj_genRes_mass\"\n# mass_branch = 'fj_genH_mass'\n\n\ndef plot_loss(args, name, indir=None):\n    if indir:\n        # save the loss in a numpy file\n        loss_vals_training = np.load(\"%s/loss_vals_training.npy\" % indir)\n        loss_vals_validation = np.load(\"%s/loss_vals_validation.npy\" % indir)\n    else:\n        # or load the loss array manually\n        loss_vals_training = np.array([0.001, 0.0002])\n        loss_vals_validation = np.array([0.001, 0.0002])\n    epochs = np.array(range(len(loss_vals_training)))\n\n    f, ax = plt.subplots(figsize=(10, 10))\n    ax.plot(epochs, loss_vals_training, label=\"Training\")\n    ax.plot(epochs, loss_vals_validation, label=\"Validation\", color=\"green\")\n    leg = ax.legend(loc=\"upper right\", title=name, borderpad=1, frameon=False, fontsize=16)\n    leg._legend_box.align = \"right\"\n    ax.set_ylabel(\"Loss\")\n    ax.set_xlabel(\"Epoch\")\n    ax.set_xlim(0, np.max(epochs))\n    f.savefig(\"%s/Loss_%s.pdf\" % (args.odir, indir.replace(\"/\", \"\")))\n    plt.clf()\n\n\ndef plot_accuracy(args, name, indir=None):\n    if indir:\n        acc_vals_validation = np.load(\"%s/acc_vals_validation.npy\" % indir)\n    else:\n        acc_vals_validation = np.array([0.001, 0.0002])\n    epochs = np.array(range(len(acc_vals_validation)))\n\n    f, ax = plt.subplots(figsize=(10, 10))\n    ax.plot(epochs, acc_vals_validation, label=\"Validation\", color=\"green\")\n    leg = ax.legend(loc=\"upper right\", title=name, borderpad=1, frameon=False, fontsize=16)\n    leg._legend_box.align = \"right\"\n    ax.set_ylabel(\"Accuracy\")\n    ax.set_xlabel(\"Epoch\")\n    ax.set_xlim(0, np.max(epochs))\n    ax.set_ylim(0.8, 0.95)\n    f.savefig(\"%s/Acc_%s.pdf\" % (args.odir, indir.replace(\"/\", \"\")))\n    plt.clf()\n\n\n# return input by classes (signal and background)\ndef roc_input(\n    events, var, label_sig, label_bkg, weight_hist=None, bins=None, sig_mask=None, bkg_mask=None\n):\n    mask_sig = events[label_sig] == 1\n    mask_bkg = events[label_bkg] == 1\n    if sig_mask is not None:\n        mask_sig = (mask_sig) & (sig_mask)\n    if bkg_mask is not None:\n        mask_bkg = (mask_bkg) & (bkg_mask)\n    scores_sig = events[var][mask_sig].to_numpy()\n    scores_bkg = events[var][mask_bkg].to_numpy()\n    predict = np.concatenate((scores_sig, scores_bkg), axis=None)\n    siglabels = np.ones(scores_sig.shape)\n    bkglabels = np.zeros(scores_bkg.shape)\n    truth = np.concatenate((siglabels, bkglabels), axis=None)\n\n    weight = None\n    if weight_hist is not None:\n        weight_sig = weight_hist[np.digitize(events[\"fj_pt\"][mask_sig].to_numpy(), bins) - 1]\n        weight_bkg = np.ones(scores_bkg.shape)\n        weight = np.concatenate((weight_sig, weight_bkg), axis=None)\n\n    return truth, predict, weight\n\n\n# get roc for a table with given scores, a label for signal, and one for background\ndef get_roc(\n    events,\n    score_name,\n    label_sig,\n    label_bkg,\n    weight_hist=None,\n    bins=None,\n    sig_mask=None,\n    bkg_mask=None,\n):\n    truth, predict, weight = roc_input(\n        events, score_name, label_sig, label_bkg, weight_hist, bins, sig_mask, bkg_mask\n    )\n    fprs, tprs, threshold = roc_curve(truth, predict, sample_weight=weight)\n    return fprs, tprs\n\n\n# plot roc\ndef plot_roc(args, label_sig, label_bkg, fprs, tprs, label):\n    fig, axs = plt.subplots(1, 1, figsize=(16, 16))\n\n    def get_round(x_effs, y_effs, to_get=[0.01, 0.02, 0.03]):\n        effs = []\n        for eff in to_get:\n            for i, f in enumerate(x_effs):\n                if round(f, 2) == eff:\n                    effs.append(y_effs[i])\n                    break\n        return effs\n\n    def get_intersections(x_effs, y_effs, to_get=0.01):\n        x_eff = 0\n        for i, f in enumerate(y_effs):\n            if f >= to_get:\n                x_eff = x_effs[i]\n                break\n        return x_eff\n\n    ik = 0\n    markers = [\"v\", \"^\", \"o\", \"s\", \"p\", \"P\", \"h\"]\n    for k, it in fprs.items():\n        leg = k.replace(\"_score\", \"\")\n        axs.plot(\n            tprs[k],\n            fprs[k],\n            lw=2.5,\n            label=r\"{}, AUC = {:.1f}%\".format(leg, auc(fprs[k], tprs[k]) * 100),\n        )\n        y_eff = 0.01\n        x_eff = get_intersections(tprs[k], fprs[k], y_eff)\n        axs.hlines(\n            y=y_eff, xmin=0.00001, xmax=0.99999, linewidth=1, color=\"dimgrey\", linestyle=\"dashed\"\n        )\n        axs.vlines(\n            x=x_eff, ymin=0.00001, ymax=y_eff, linewidth=1, color=\"dimgrey\", linestyle=\"dashed\"\n        )\n        # y_effs = [0.01,0.02,0.03]\n        # x_effs = get_round(fprs[k],tprs[k],y_effs)\n        # print(tprs[k],k)\n        # print(y_effs)\n        # axs.scatter(x_effs,y_effs,s=75,marker=markers[ik],label=leg)\n        ik += 1\n\n    axs.legend(loc=\"upper left\")\n    axs.grid(which=\"minor\", alpha=0.2)\n    axs.grid(which=\"major\", alpha=0.5)\n    axs.set_xlabel(r\"Tagging efficiency %s\" % label_sig[\"legend\"])\n    axs.set_ylabel(r\"Mistagging rate %s\" % label_bkg[\"legend\"])\n    axs.set_ylim(0.0001, 1)\n    axs.set_xlim(0.0001, 1)\n    axs.set_yscale(\"log\")\n    fig.savefig(\"%s/roc_%s_ylog.pdf\" % (args.odir, label))\n    axs.set_yscale(\"linear\")\n    plt.close()\n\n\n# plot rocs for different cuts on mH and pt\ndef plot_roc_by_var(\n    args, vars_to_corr, bin_ranges, bin_widths, events, score_name, sig, bkg, mh=False\n):\n    i = 0\n    fig, axs = plt.subplots(1, len(vars_to_corr.keys()), figsize=(8 * len(vars_to_corr.keys()), 8))\n    for var, varname in vars_to_corr.items():\n        fprs = {}\n        tprs = {}\n        legends = []\n        for j, b in enumerate(bin_ranges[i]):\n            bi = b\n            bf = b + bin_widths[i]\n            tag = \"%i\" % bi\n            if not mh:\n                output = events[\n                    (events[bkg[\"label\"]] == 1)\n                    | (\n                        (events[varname] >= bi)\n                        & (events[varname] <= bf)\n                        & (events[mass_branch] != 125)\n                    )\n                ]\n                # mask_sig = (events[varname]>=bi) & (events[varname]<=bf) & (events[mass_branch]!=125)\n            else:\n                # mask_sig = (events[mass_branch]==125)\n                output = events[\n                    (events[bkg[\"label\"]] == 1)\n                    | (\n                        (events[varname] >= bi)\n                        & (events[varname] <= bf)\n                        & (events[mass_branch] == 125)\n                    )\n                ]\n            fprs[tag], tprs[tag] = get_roc(output, score_name, sig[\"label\"], bkg[\"label\"])\n            legends.append(\"%s %i-%i GeV\" % (var, bi, bf))\n\n        # now plot\n        if len(vars_to_corr.keys()) == 1:\n            axs_1 = axs\n        else:\n            axs_1 = axs[i]\n\n        ik = 0\n        for k, it in fprs.items():\n            axs_1.plot(\n                tprs[k],\n                fprs[k],\n                lw=2.5,\n                label=r\"{}, AUC = {:.1f}%\".format(legends[ik], auc(fprs[k], tprs[k]) * 100),\n            )\n            ik += 1\n        axs_1.legend(loc=\"upper left\")\n        axs_1.grid(which=\"minor\", alpha=0.2)\n        axs_1.grid(which=\"major\", alpha=0.5)\n        axs_1.set_xlabel(r\"Tagging efficiency %s\" % sig[\"legend\"])\n        axs_1.set_ylabel(r\"Mistagging rate %s\" % bkg[\"legend\"])\n        axs_1.set_ylim(0.0001, 1)\n        axs_1.set_yscale(\"log\")\n\n        i += 1\n\n    if not mh:\n        fig.savefig(\"%s/rocs_by_var_%s_ylog.pdf\" % (args.odir, sig[\"label\"]))\n    else:\n        fig.savefig(\"%s/rocs_by_var_%s_mh125_ylog.pdf\" % (args.odir, sig[\"label\"]))\n\n    plt.close()\n\n\n# plot validation\ndef plot_validation(args, hist_val, vars_to_plot, label):\n    for density in [True, False]:\n        fig, axs = plt.subplots(1, len(vars_to_plot), figsize=(len(vars_to_plot) * 8, 8))\n        for i, m in enumerate(vars_to_plot):\n            if len(vars_to_plot) == 1:\n                axs_1 = axs\n            else:\n                axs_1 = axs[i]\n            x = hist_val.sum(*[ax for ax in hist_val.axes() if ax.name not in {\"process\", m}])\n            # print hist values for debugging  (in case hist is empty)\n            # print(x.values())\n            hist.plot1d(x, ax=axs_1, overlay=\"process\", density=density)\n            axs_1.set_ylabel(\"Jets\")\n        fig.tight_layout()\n        if density:\n            fig.savefig(\"%s/%s_density.pdf\" % (args.odir, label))\n        else:\n            fig.savefig(\"%s/%s.pdf\" % (args.odir, label))\n        plt.close()\n\n\n# plot score after selection on variables\n# i.e. how does the score look when cutting on e.g. pt, gmass\ndef plot_score_aftercut(args, hist_val, vars_to_corr, bin_ranges, bin_widths, processes, label):\n    print(\"plot_score_aftercut\")\n    density = True\n    for proc in processes:\n        fig, axs = plt.subplots(1, len(vars_to_corr), figsize=(len(vars_to_corr) * 8, 8))\n        for i, m in enumerate(vars_to_corr):\n            if len(vars_to_corr) == 1:\n                axs_1 = axs\n            else:\n                axs_1 = axs[i]\n            x = hist_val.sum(\n                *[ax for ax in hist_val.axes() if ax.name not in {\"process\", \"score\", m}]\n            ).integrate(\"process\", proc)\n            legends = []\n            for j, b in enumerate(bin_ranges[i]):\n                # print histogram identifiers for debugging\n                # print(x.identifiers(m, overflow='all'))\n                y = x.integrate(m, slice(b, b + bin_widths[i]))\n                legends.append(\"%s %i-%i GeV\" % (m, b, b + bin_widths[i]))\n                # print(b,b+bin_widths[i])\n                # print(y.values())\n                # print(x.values())\n                if j == 0:\n                    hist.plot1d(y, ax=axs_1, density=True)\n                else:\n                    hist.plot1d(y, ax=axs_1, density=True, clear=False)\n            axs_1.set_ylabel(\"Jets\")\n            axs_1.legend(legends, title=m)\n        fig.tight_layout()\n        fig.savefig(\"%s/%s_scores_%s_density.pdf\" % (args.odir, proc, label))\n        plt.close()\n\n\n# compute percentiles\n\"\"\"\ni.e. the cuts that we should make on the tagger score so that we obtain this efficiency in our process after the cut\nuses np.quantile function\n\"\"\"\n\n\ndef computePercentiles(data, percentiles):\n    mincut = 0.0\n    tmp = np.quantile(data, np.array(percentiles))\n    tmpl = [mincut]\n    for x in tmp:\n        tmpl.append(x)\n    perc = [0.0]\n    for x in percentiles:\n        perc.append(x)\n    return perc, tmpl\n\n\n# plot how variables look after a cut on the scores\ndef plot_var_aftercut(args, hist_val, vars_to_plot, processes, label, cuts, percentiles):\n    print(\"plot variable after cut\")\n    for density in [True, False]:\n        for proc in processes:\n            fig, axs = plt.subplots(1, len(vars_to_plot), figsize=(len(vars_to_plot) * 8, 8))\n            for var in vars_to_plot:\n                if len(vars_to_plot) == 1:\n                    axs_1 = axs\n                else:\n                    axs_1 = axs[i]\n                x = hist_val.sum(\n                    *[ax for ax in hist_val.axes() if ax.name not in {\"process\", var, \"score\"}]\n                )\n                x = x.integrate(\"process\", proc)\n                legends = []\n                # now cut on the score\n                if not density:\n                    cuts.pop(0)\n                    percentiles.pop(0)\n                # print('cuts on score ',cuts)\n                for i, cut in enumerate(cuts):\n                    cut = round(cut, 2)\n                    # if i==len(cuts)-1:\n                    # print(slice(cut,1))\n                    y = x.integrate(\"score\", slice(cut, 1))\n                    legends.append(\"%s \" % (percentiles[i]))\n                    if i == 0:\n                        hist.plot1d(y, ax=axs_1, density=density)\n                    else:\n                        hist.plot1d(y, ax=axs_1, density=density, clear=False)\n                axs_1.set_ylabel(\"Jets\")\n                axs_1.legend(legends, title=\"Bkg quantile\")\n            fig.tight_layout()\n            if density:\n                fig.savefig(\"%s/%s_scoresculpting_density.pdf\" % (args.odir, label))\n            else:\n                fig.savefig(\"%s/%s_scoresculpting.pdf\" % (args.odir, label))\n            plt.close()\n\n\ndef main(args):\n\n    # label dictionary\n    label_dict = {\n        \"qcd_old\": {\"legend\": \"QCD\", \"label\": \"fj_isQCD\"},\n        \"qcd\": {\"legend\": \"QCD\", \"label\": \"fj_QCD_label\"},\n        \"qcd_b\": {\"legend\": \"QCDb\", \"label\": \"fj_isQCDb\"},\n        \"qcd_bb\": {\"legend\": \"QCDbb\", \"label\": \"fj_isQCDbb\"},\n        \"qcd_c\": {\"legend\": \"QCDc\", \"label\": \"fj_isQCDc\"},\n        \"qcd_cc\": {\"legend\": \"QCDcc\", \"label\": \"fj_isQCDcc\"},\n        \"qcd_lep\": {\"legend\": \"QCDlep\", \"label\": \"fj_isQCDlep\"},\n        \"qcd_lep\": {\"legend\": \"QCDlep\", \"label\": \"fj_isQCDlep\"},\n        \"top\": {\"legend\": \"Top\", \"label\": \"fj_isTop_label\"},\n        \"top_lep\": {\"legend\": \"Top lep\", \"label\": \"fj_isToplep\"},\n        \"top_merged\": {\"legend\": \"Top merged\", \"label\": \"fj_isTop_merged\"},\n        \"top_semimerged\": {\"legend\": \"Top semi-merged\", \"label\": \"fj_isTop_semimerged\"},\n        \"top_lepmerged\": {\"legend\": \"Top merged lepton\", \"label\": \"fj_isToplep_merged\"},\n        \"hww_4q\": {\"legend\": \"H(WW) all-had\", \"label\": \"fj_H_WW_4q\"},\n        \"hww_4q_merged\": {\"legend\": \"H(WW) 4q\", \"label\": \"fj_H_WW_4q_4q\"},\n        \"hww_3q_merged\": {\"legend\": \"H(WW) 3q\", \"label\": \"fj_H_WW_4q_3q\"},\n        \"hbb\": {\"legend\": \"H(bb)\", \"label\": \"fj_H_bb\"},\n        \"hww_elenuqq\": {\"legend\": \"H(WW) ele\", \"label\": \"fj_H_WW_elenuqq\"},\n        \"hww_munuqq\": {\"legend\": \"H(WW) mu\", \"label\": \"fj_H_WW_munuqq\"},\n        \"hww_taunuqq\": {\"legend\": \"H(WW) tau merged\", \"label\": \"fj_isHWW_taunuqq_merged\"},\n        \"hww_munuqq_merged\": {\"legend\": \"H(WW) mu merged\", \"label\": \"fj_isHWW_munuqq_merged\"},\n        \"hww_munuqq_semimerged\": {\n            \"legend\": \"H(WW) mu semi-merged\",\n            \"label\": \"fj_isHWW_munuqq_semimerged\",\n        },\n        \"hww_elenuqq_merged\": {\"legend\": \"H(WW) ele merged\", \"label\": \"fj_isHWW_elenuqq_merged\"},\n        \"hww_elenuqq_semimerged\": {\n            \"legend\": \"H(WW) ele semi-merged\",\n            \"label\": \"fj_isHWW_elenuqq_semimerged\",\n        },\n        \"hww_taunuqq_merged\": {\"legend\": \"H(WW) tau merged\", \"label\": \"fj_isHWW_taunuqq_merged\"},\n        \"hww_taunuqq_semimerged\": {\n            \"legend\": \"H(WW) tau semi-merged\",\n            \"label\": \"fj_isHWW_taunuqq_semimerged\",\n        },\n    }\n\n    # get signals and backgrounds\n    signals = args.signals.split(\",\")\n    backgrounds = args.bkgs.split(\",\")\n    if len(signals) != len(backgrounds):\n        print(\"Number of signals should be the same as backgrounds!\")\n        exit\n\n    for i, signal in enumerate(signals):\n        bkg = backgrounds[i]\n        bkglabel = label_dict[bkg][\"label\"]\n        siglabel = label_dict[signal][\"label\"]\n\n        # default branches\n        branches = [\"fj_pt\", \"fj_msoftdrop\"]\n        branches += [mass_branch]\n        branches += [siglabel]\n        branches += [\"score_%s\" % siglabel, \"score_%s\" % bkglabel]\n        # add older taggers\n        if signal == \"hww_4q\" or signal == \"hww_4q_merged\" or signal == \"hww_3q_merged\":\n            # branches += [\"fj_deepTagMD_H4qvsQCD\",\"fj_deepTag_HvsQCD\"] # values are always -1000?\n            branches += [\"fj_PN_H4qvsQCD\"]  # when included in observers?\n\n        # add this only if nProngs is saved\n        add_nProngs = False\n        # add_nProngs = True\n        if add_nProngs:\n            branches += [\"fj_nProngs\"]\n\n        # add selection (add selection such that QCD only has gen resonance mass < 0)\n        mask = (\n            \"(fj_pt<1200) &\"\n            \"(fj_pt>300) &\"\n            \"((((fj_isQCDb==1) | (fj_isQCDbb==1) | (fj_isQCDc==1) | (fj_isQCDcc==1) | (fj_isQCDlep==1) | (fj_isQCDothers==1)) & (fj_genRes_mass<0)) |\"\n            \"((%s==1) & (fj_genRes_mass>0) ) )\" % siglabel\n        )\n        if bkg == \"qcd_old\":\n            mask = (\n                \"(fj_pt<1200) & (fj_pt>300) & (((fj_isQCD==1) & (%s<0)) | ((%s==1) & (%s>0) ) )\"\n                % (mass_branch, siglabel, mass_branch)\n            )\n\n        ifile = uproot.open(args.ifile)[\"Events\"]\n        isqcd_separate = False\n        if \"qcd\" in bkg:\n            if bkg == \"qcd\":\n                ibranches = branches + [\n                    \"fj_isQCDb\",\n                    \"fj_isQCDbb\",\n                    \"fj_isQCDc\",\n                    \"fj_isQCDcc\",\n                    \"fj_isQCDlep\",\n                    \"fj_isQCDothers\",\n                ]\n                ibranches.remove(\"score_%s\" % bkglabel)\n                ibranches.extend(\n                    [\n                        \"score_fj_isQCDb\",\n                        \"score_fj_isQCDbb\",\n                        \"score_fj_isQCDc\",\n                        \"score_fj_isQCDcc\",\n                        \"score_fj_isQCDlep\",\n                        \"score_fj_isQCDothers\",\n                    ]\n                )\n                # print(ibranches)\n                events = ifile.arrays(ibranches, mask)\n                events_fj_QCD_label_TrueFalse = (\n                    (events[\"fj_isQCDb\"] == 1)\n                    | (events[\"fj_isQCDbb\"] == 1)\n                    | (events[\"fj_isQCDc\"] == 1)\n                    | (events[\"fj_isQCDcc\"] == 1)\n                    | (events[\"fj_isQCDlep\"] == 1)\n                    | (events[\"fj_isQCDothers\"] == 1)\n                )\n                events[\"fj_QCD_label\"] = ak.values_astype(events_fj_QCD_label_TrueFalse, int)\n                isqcd_separate = True\n                print(\"Added fj_QCD_label to ttree\")\n            else:\n                # ibranches = branches + [\"fj_QCD_label\"]\n                print(branches)\n                ibranches = branches + [\"fj_isQCD\"]\n                events = ifile.arrays(ibranches, mask)\n        elif \"top\" in bkg:\n            ibranches = branches + [\"fj_Top_label\"]\n            events = ifile.arrays(ibranches)\n        else:\n            print(\"not known background\")\n        print(\"List of branches read \", ibranches)\n\n        # compute scores:\n        \"\"\"\n          we expect all scores to sum up to 1, e.g. given two signals in the event (signal 1 and 2) and one background process (background 1):\n          score_signal_1 + score_signal_2 + score_background_1 = 1\n          then nn_signal_1 = score_signal_1 / (score_signal_1 + score_background_1) = score_signal_1 / (1 - score_signal_2)\n        \"\"\"\n        score_name = \"%s_score\" % args.name\n        if isqcd_separate:\n            events[score_name] = events[\"score_%s\" % siglabel] / (\n                events[\"score_%s\" % siglabel]\n                + events[\"score_fj_isQCDb\"]\n                + events[\"score_fj_isQCDbb\"]\n                + events[\"score_fj_isQCDc\"]\n                + events[\"score_fj_isQCDcc\"]\n                + events[\"score_fj_isQCDlep\"]\n                + events[\"score_fj_isQCDothers\"]\n            )\n        else:\n            events[score_name] = events[\"score_%s\" % siglabel] / (\n                events[\"score_%s\" % siglabel] + events[\"score_%s\" % bkglabel]\n            )\n\n        # define and fill coffea histograms\n        hist_features = hist.Hist(\n            \"Jets\",\n            hist.Cat(\"process\", \"Process\"),\n            hist.Bin(\"msd\", r\"fj msoftdrop [GeV]\", 60, 30, 420),\n            hist.Bin(\"pt\", r\"fj $p_T$ [GeV]\", 50, 200, 1200),  # bins of 20\n            hist.Bin(\"score\", r\"Tagger score\", 100, 0, 1),\n        )\n        hist_gmass = hist.Hist(\n            \"genmass\",\n            hist.Cat(\"process\", \"Process\"),\n            hist.Bin(\"score\", r\"Tagger score\", 70, 0, 1),\n            hist.Bin(\"pt\", r\"fj $p_T$ [GeV]\", 50, 200, 1200),  # bins of 20\n            hist.Bin(\"mH\", r\"gen Res mass [GeV]\", 42, 50, 260),  # bins of 5\n        )\n\n        # define processes\n        # add mh125 and mh!=125 as different processes so that we can see dependence\n        processes = [bkg]\n        if \"hww\" in signal or \"hbb\" in signal:\n            processes.append(\"%s-mh125\" % signal)\n            processes.append(\"%s-mhflat\" % signal)\n\n        # loop over processes\n        legends = {}\n        for proc in processes:\n            p = proc.split(\"-\")[0]\n            legend = label_dict[p][\"legend\"]\n            if \"mh125\" in proc:\n                mask_proc = (events[label_dict[p][\"label\"]] == 1) & (events[mass_branch] == 125)\n                legend += \" mh125\"\n            elif \"mhflat\" in proc:\n                # beware of mRes = 175....\n                mask_proc = (events[label_dict[p][\"label\"]] == 1) & (events[mass_branch] != 125)\n                legend += \" mhflat\"\n            else:\n                mask_proc = events[label_dict[p][\"label\"]] == 1\n            legends[proc] = legend\n            # check if events with that mask are not zero\n            if len(events[\"fj_msoftdrop\"][mask_proc]) == 0:\n                processes.remove(proc)\n                continue\n\n            # print legends\n            # print('legend ',legend)\n\n            # fill the features histogram\n            hist_features.fill(\n                process=proc,\n                msd=events[\"fj_msoftdrop\"][mask_proc],\n                pt=events[\"fj_pt\"][mask_proc],\n                score=events[score_name][mask_proc],\n            )\n\n            # only fill the gen mass histogram for signal\n            if signal in proc:\n                hist_gmass.fill(\n                    process=proc,\n                    mH=events[mass_branch][mask_proc],\n                    score=events[score_name][mask_proc],\n                    pt=events[\"fj_pt\"][mask_proc],\n                )\n\n        # get pt histograms\n        # define log bins as: np.round(np.exp(np.linspace(np.log(MIN), np.log(MAX), NUM_BINS))).astype('int').tolist()\n        # ptbins = [200, 239, 286, 342, 409, 489, 585, 699, 836, 1000, 2500]\n        ptbins = [200, 251, 316, 398, 501, 630, 793, 997, 1255, 1579, 1987, 2500]\n        mask_proc_sigmh125 = (events[label_dict[signal][\"label\"]] == 1) & (\n            events[mass_branch] == 125\n        )\n        mask_proc_sig = (events[label_dict[signal][\"label\"]] == 1) & (events[mass_branch] != 125)\n        pthistsigmh, bin_edges = np.histogram(\n            events[\"fj_pt\"][mask_proc_sigmh125].to_numpy(), bins=ptbins\n        )\n        pthistsig, bin_edges = np.histogram(events[\"fj_pt\"][mask_proc_sig].to_numpy(), bins=ptbins)\n        pthist = pthistsigmh / pthistsig\n\n        # plot weight histogram\n        weight_sig = pthist[np.digitize(events[\"fj_pt\"][mask_proc_sig].to_numpy(), ptbins) - 1]\n        fig, axs = plt.subplots(1, 1)\n        axs.hist(events[\"fj_pt\"][mask_proc_sig], bins=ptbins, histtype=\"step\")\n        axs.hist(events[\"fj_pt\"][mask_proc_sig], bins=ptbins, weights=weight_sig, histtype=\"step\")\n        axs.set_xlabel(\"pT (GeV)\")\n        axs.legend([\"Unweighted\", \"Weighted\"])\n        fig.savefig(\"%s/ptweights_%s.pdf\" % (args.odir, label_dict[signal][\"label\"]))\n        fig, axs = plt.subplots(1, 1)\n        axs.hist(events[\"fj_pt\"][mask_proc_sig], bins=ptbins, histtype=\"step\", density=True)\n        axs.hist(\n            events[\"fj_pt\"][mask_proc_sig],\n            bins=ptbins,\n            weights=weight_sig,\n            histtype=\"step\",\n            density=True,\n        )\n        axs.set_xlabel(\"pT (GeV)\")\n        axs.legend([\"Unweighted\", \"Weighted\"])\n        fig.savefig(\"%s/ptweights_%s_density.pdf\" % (args.odir, label_dict[signal][\"label\"]))\n        plt.close()\n\n        # masks\n        mask_flat = events[mass_branch] != 125\n        mask_mh125 = events[mass_branch] == 125\n        mask_proc_mh120130 = (\n            (events[mass_branch] >= 120)\n            & (events[mass_branch] <= 130)\n            & (events[\"fj_pt\"] <= 600)\n            & mask_flat\n        )\n\n        # get ROC\n        fprs = {}\n        tprs = {}\n        fprs[score_name], tprs[score_name] = get_roc(events, score_name, siglabel, bkglabel)\n\n        # get ROC for flat sample with pt weights\n        fprs[score_name + \"flat_weight\"], tprs[score_name + \"flat_weight\"] = get_roc(\n            events,\n            score_name,\n            siglabel,\n            bkglabel,\n            weight_hist=pthist,\n            bins=ptbins,\n            sig_mask=mask_flat,\n        )\n        fprs[score_name + \"flat\"], tprs[score_name + \"flat\"] = get_roc(\n            events, score_name, siglabel, bkglabel, weight_hist=None, bins=None, sig_mask=mask_flat\n        )\n\n        # get ROC for flat sample with mass around mass of higgs\n        (\n            fprs[score_name + \"flat_mh120130-pt200600\"],\n            tprs[score_name + \"flat_mh120130-pt200600\"],\n        ) = get_roc(\n            events,\n            score_name,\n            siglabel,\n            bkglabel,\n            weight_hist=None,\n            bins=None,\n            sig_mask=mask_proc_mh120130,\n        )\n        (\n            fprs[score_name + \"flat_mh120130-pt200600-weight\"],\n            tprs[score_name + \"flat_mh120130-pt200600-weight\"],\n        ) = get_roc(\n            events,\n            score_name,\n            siglabel,\n            bkglabel,\n            weight_hist=pthist,\n            bins=ptbins,\n            sig_mask=mask_proc_mh120130,\n        )\n\n        # get ROC for Particle Net if 3q/4q\n        if signal == \"hww_4q\" or signal == \"hww_4q_merged\" or signal == \"hww_3q_merged\":\n            # fprs['DeepAK8_H4q_MD_flat'], tprs['DeepAK8_H4q_MD_flat'] = get_roc(events, \"fj_deepTagMD_H4qvsQCD\", siglabel, bkglabel,sig_mask=mask_flat)\n            # fprs['DeepAK8_H_flat'], tprs['DeepAK8_H_flat'] = get_roc(events, \"fj_deepTag_HvsQCD\", siglabel, bkglabel,sig_mask=mask_flat)\n            fprs[\"PN_H4q_flat\"], tprs[\"PN_H4q_flat\"] = get_roc(\n                events, \"fj_PN_H4qvsQCD\", siglabel, bkglabel, sig_mask=mask_flat\n            )\n\n            # get ROCs for score but for 3q/4q independently\n            if add_nProngs:\n                mask_proc_3q = (events[\"fj_nProngs\"] == 3) & mask_flat\n                mask_proc_4q = (events[\"fj_nProngs\"] == 4) & mask_flat\n                fprs[score_name + \"_flat_3q\"], tprs[score_name + \"_flat_3q\"] = get_roc(\n                    events,\n                    score_name,\n                    siglabel,\n                    bkglabel,\n                    weight_hist=None,\n                    bins=None,\n                    sig_mask=mask_proc_3q,\n                )\n                fprs[score_name + \"_flat_4q\"], tprs[score_name + \"_flat_4q\"] = get_roc(\n                    events,\n                    score_name,\n                    siglabel,\n                    bkglabel,\n                    weight_hist=None,\n                    bins=None,\n                    sig_mask=mask_proc_4q,\n                )\n\n        # plot ROCs\n        plot_roc(\n            args, label_dict[signal], label_dict[bkg], fprs, tprs, label=label_dict[signal][\"label\"]\n        )\n\n        # plot features for this signal and background combination (i.e. all the processes)\n        vars_to_plot = [\"pt\", \"msd\", \"score\"]\n        plt_label = \"validation_%svs%s\" % (siglabel, bkglabel)\n        plot_validation(args, hist_features, vars_to_plot, plt_label)\n\n        # plot how the score looks after cuts on variables\n        vars_to_corr = [\"mH\", \"pt\"]\n        bin_ranges = [list(range(60, 240, 20)), list(range(200, 1200, 200))]\n        bin_widths = [10, 200]\n        proc_to_corr = [\"%s-mhflat\" % signal]\n        plt_label = \"%svs%s\" % (siglabel, bkglabel)\n        # plot_score_aftercut(args,hist_gmass,vars_to_corr,bin_ranges,bin_widths,proc_to_corr,plt_label)\n\n        # plot roc for different cuts on mH and pt\n        vars_to_corr = {\"mH\": mass_branch, \"pt\": \"fj_pt\"}\n        plot_roc_by_var(\n            args,\n            vars_to_corr,\n            bin_ranges,\n            bin_widths,\n            events,\n            score_name,\n            label_dict[signal],\n            label_dict[bkg],\n        )\n\n        # accumulate rocs for summary\n        fprs_summary = {}\n        tprs_summary = {}\n        fprs_summary[\"flat\"] = fprs[score_name + \"flat\"]\n        tprs_summary[\"flat\"] = tprs[score_name + \"flat\"]\n        fprs_summary[\"flat-mhptSM\"] = fprs[score_name + \"flat_mh120130-pt200600-weight\"]\n        tprs_summary[\"flat-mhptSM\"] = tprs[score_name + \"flat_mh120130-pt200600-weight\"]\n        if signal == \"hww_4q\" or signal == \"hww_4q_merged\" or signal == \"hww_3q_merged\":\n            fprs_summary[\"flat-PN4q\"] = fprs[\"PN_H4q_flat\"]\n            tprs_summary[\"flat-PN4q\"] = tprs[\"PN_H4q_flat\"]\n\n        # plot roc for mh=125\n        fprs = {}  # reset fprs\n        mask_mh125_100150 = (\n            mask_mh125 & (events[\"fj_msoftdrop\"] >= 100) & (events[\"fj_msoftdrop\"] <= 150)\n        )\n        mask_100150 = (events[\"fj_msoftdrop\"] >= 100) & (events[\"fj_msoftdrop\"] <= 150)\n        fprs[score_name + \"_mh125\"], tprs[score_name + \"_mh125\"] = get_roc(\n            events, score_name, siglabel, bkglabel, weight_hist=None, bins=None, sig_mask=mask_mh125\n        )\n        # fprs[score_name+'_mh125_msd100-150'], tprs[score_name+'_mh125_msd100-150'] = get_roc(events,  score_name, siglabel, bkglabel, weight_hist=None, bins=None, sig_mask=mask_mh125_100150, bkg_mask=mask_100150)\n        if signal == \"hww_4q\" or signal == \"hww_4q_merged\" or signal == \"hww_3q_merged\":\n            fprs[\"PN_H4q_mh125-nonMD\"], tprs[\"PN_H4q_mh125-nonMD\"] = get_roc(\n                events, \"fj_PN_H4qvsQCD\", siglabel, bkglabel, sig_mask=mask_mh125\n            )\n            fprs[\"PN_H4q_mh125_msd100-150\"], tprs[\"PN_H4q_mh125_msd100-150\"] = get_roc(\n                events,\n                \"fj_PN_H4qvsQCD\",\n                siglabel,\n                bkglabel,\n                sig_mask=mask_mh125_100150,\n                bkg_mask=mask_100150,\n            )\n            if add_nProngs:\n                mask_proc_3q = (events[\"fj_nProngs\"] == 3) & mask_mh125\n                mask_proc_4q = (events[\"fj_nProngs\"] == 4) & mask_mh125\n                fprs[score_name + \"_mh125_4q\"], tprs[score_name + \"_mh125_4q\"] = get_roc(\n                    events,\n                    score_name,\n                    siglabel,\n                    bkglabel,\n                    weight_hist=None,\n                    bins=None,\n                    sig_mask=mask_proc_4q,\n                )\n                fprs[score_name + \"_mh125_3q\"], tprs[score_name + \"_mh125_3q\"] = get_roc(\n                    events,\n                    score_name,\n                    siglabel,\n                    bkglabel,\n                    weight_hist=None,\n                    bins=None,\n                    sig_mask=mask_proc_3q,\n                )\n                fprs[\"PN_H4q_mh125-nonMD_4q\"], tprs[\"PN_H4q_mh125-nonMD_4q\"] = get_roc(\n                    events, \"fj_PN_H4qvsQCD\", siglabel, bkglabel, sig_mask=mask_proc_4q\n                )\n                fprs[\"PN_H4q_mh125-nonMD_3q\"], tprs[\"PN_H4q_mh125-nonMD_3q\"] = get_roc(\n                    events, \"fj_PN_H4qvsQCD\", siglabel, bkglabel, sig_mask=mask_proc_3q\n                )\n        plot_roc(\n            args,\n            label_dict[signal],\n            label_dict[bkg],\n            fprs,\n            tprs,\n            label=label_dict[signal][\"label\"] + \"_mh125_all\",\n        )\n\n        # more rocs for summary\n        fprs_summary[\"SM\"] = fprs[score_name + \"_mh125\"]\n        tprs_summary[\"SM\"] = tprs[score_name + \"_mh125\"]\n        if signal == \"hww_4q\" or signal == \"hww_4q_merged\" or signal == \"hww_3q_merged\":\n            fprs_summary[\"SM-PN4q-msd100-150\"] = fprs[\"PN_H4q_mh125_msd100-150\"]\n            tprs_summary[\"SM-PN4q-msd100-150\"] = tprs[\"PN_H4q_mh125_msd100-150\"]\n\n        # plot roc summary\n        plot_roc(\n            args,\n            label_dict[signal],\n            label_dict[bkg],\n            fprs_summary,\n            tprs_summary,\n            label=label_dict[signal][\"label\"] + \"_summary\",\n        )\n\n        # xcheck plot for mh=125\n        vars_to_corr = {\"mH\": mass_branch, \"pt\": \"fj_pt\"}\n        bin_ranges = [[125, 125], list(range(200, 1200, 200))]\n        bin_widths = [4, 200]\n        plot_roc_by_var(\n            args,\n            vars_to_corr,\n            bin_ranges,\n            bin_widths,\n            events,\n            score_name,\n            label_dict[signal],\n            label_dict[bkg],\n            True,\n        )\n\n        # plot how variables look after cut on classifier (tagger score)\n        vars_to_corr = [\"msd\"]\n        proc_to_corr = [bkg]\n        plt_label = \"aftercuts_%svs%s\" % (siglabel, bkglabel)\n        # first compute percentiles on bkg (or maybe other process?)\n        percentiles, cuts = computePercentiles(\n            events[score_name][(events[bkglabel] == 1)].to_numpy(), [0.97, 0.99, 0.995]\n        )\n        plot_var_aftercut(\n            args, hist_features, vars_to_corr, proc_to_corr, plt_label, cuts, percentiles\n        )\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--ifile\", help=\"input file(s)\")\n    parser.add_argument(\"--odir\", required=True, help=\"output dir\")\n    parser.add_argument(\"--name\", required=True, help=\"name of the model(s)\")\n    parser.add_argument(\"--signals\", default=\"hww_4q_merged\", help=\"signals\")\n    parser.add_argument(\n        \"--bkgs\",\n        default=\"qcd\",\n        help=\"backgrounds (if qcd_label then assume that you only have one qcd label)\",\n    )\n    args = parser.parse_args()\n\n    import os\n\n    os.system(\"mkdir -p %s\" % args.odir)\n\n    main(args)\n", "meta": {"hexsha": "3563c9a963db5ecc96ca8fbe9c5771172e5edad5", "size": 33319, "ext": "py", "lang": "Python", "max_stars_repo_path": "plot_classification_fromoutput.py", "max_stars_repo_name": "rkansal47/weaver", "max_stars_repo_head_hexsha": "7e9d3d8c9ee43acb2a95f2d3f76c384822e04699", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-25T19:19:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T20:31:56.000Z", "max_issues_repo_path": "plot_classification_fromoutput.py", "max_issues_repo_name": "rkansal47/weaver", "max_issues_repo_head_hexsha": "7e9d3d8c9ee43acb2a95f2d3f76c384822e04699", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-07-02T03:56:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-04T07:40:41.000Z", "max_forks_repo_path": "plot_classification_fromoutput.py", "max_forks_repo_name": "rkansal47/weaver", "max_forks_repo_head_hexsha": "7e9d3d8c9ee43acb2a95f2d3f76c384822e04699", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-08-26T21:14:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T14:58:01.000Z", "avg_line_length": 39.060961313, "max_line_length": 214, "alphanum_fraction": 0.537981332, "include": true, "reason": "import numpy", "num_tokens": 9313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.19923329715255295}}
{"text": "# Copyright 2019 The Cirq Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import Any, Iterable, Iterator, List, Optional, Sequence, Tuple, Union\n\nimport numpy as np\n\nimport cirq\nfrom cirq import ops, linalg, value\nfrom cirq.interop.quirk.cells.cell import Cell, CellMaker\n\n\n@value.value_equality\nclass InputRotationCell(Cell):\n    \"\"\"Applies an operation that depends on an input gate.\"\"\"\n\n    def __init__(\n        self,\n        identifier: str,\n        register: Optional[Sequence['cirq.Qid']],\n        base_operation: 'cirq.Operation',\n        exponent_sign: int,\n    ):\n        self.identifier = identifier\n        self.register = None if register is None else tuple(register)\n        self.base_operation = base_operation\n        self.exponent_sign = exponent_sign\n\n    def _value_equality_values_(self) -> Any:\n        return (\n            self.identifier,\n            self.register,\n            self.base_operation,\n            self.exponent_sign,\n        )\n\n    def __repr__(self) -> str:\n        return (\n            f'cirq.interop.quirk.cells.input_rotation_cells.InputRotationCell('\n            f'\\n    {self.identifier!r},'\n            f'\\n    {self.register!r},'\n            f'\\n    {self.base_operation!r},'\n            f'\\n    {self.exponent_sign!r})'\n        )\n\n    def gate_count(self) -> int:\n        return 1\n\n    def with_line_qubits_mapped_to(self, qubits: List['cirq.Qid']) -> 'Cell':\n        return InputRotationCell(\n            self.identifier,\n            None if self.register is None else Cell._replace_qubits(self.register, qubits),\n            self.base_operation.with_qubits(\n                *Cell._replace_qubits(self.base_operation.qubits, qubits)\n            ),\n            exponent_sign=self.exponent_sign,\n        )\n\n    def with_input(self, letter: str, register: Union[Sequence['cirq.Qid'], int]) -> 'Cell':\n        # Parameterized rotations use input A as their parameter.\n        if self.register is None and letter == 'a':\n            if isinstance(register, int):\n                raise ValueError(\n                    'Dependent operation requires known length '\n                    'input; classical constant not allowed.'\n                )\n            return InputRotationCell(\n                self.identifier, register, self.base_operation, self.exponent_sign\n            )\n        return self\n\n    def controlled_by(self, qubit: 'cirq.Qid'):\n        return InputRotationCell(\n            self.identifier,\n            self.register,\n            self.base_operation.controlled_by(qubit),\n            self.exponent_sign,\n        )\n\n    def operations(self) -> 'cirq.OP_TREE':\n        if self.register is None:\n            raise ValueError(f\"Missing input 'a'\")\n        return QuirkInputRotationOperation(\n            self.identifier, self.register, self.base_operation, self.exponent_sign\n        )\n\n\n@value.value_equality\nclass QuirkInputRotationOperation(ops.Operation):\n    \"\"\"Operates on target qubits in a way that varies based on an input qureg.\"\"\"\n\n    def __init__(\n        self,\n        identifier: str,\n        register: Iterable['cirq.Qid'],\n        base_operation: 'cirq.Operation',\n        exponent_sign: int,\n    ):\n        if exponent_sign not in [-1, +1]:\n            raise ValueError('exponent_sign not in [-1, +1]')\n        self.identifier = identifier\n        self.register = tuple(register)\n        self.base_operation = base_operation\n        self.exponent_sign = exponent_sign\n\n    def _value_equality_values_(self) -> Any:\n        return (\n            self.identifier,\n            self.register,\n            self.base_operation,\n            self.exponent_sign,\n        )\n\n    @property\n    def qubits(self) -> Tuple['cirq.Qid', ...]:\n        return tuple(self.base_operation.qubits) + self.register\n\n    def with_qubits(self, *new_qubits):\n        k = len(self.base_operation.qubits)\n        new_op_qubits = new_qubits[:k]\n        new_register = new_qubits[k:]\n        return QuirkInputRotationOperation(\n            self.identifier,\n            new_register,\n            self.base_operation.with_qubits(*new_op_qubits),\n            self.exponent_sign,\n        )\n\n    def _circuit_diagram_info_(self, args: 'cirq.CircuitDiagramInfoArgs'):\n        sub_result = cirq.circuit_diagram_info(self.base_operation)\n        sign_char = '-' if self.exponent_sign == -1 else ''\n        symbols = list(sub_result.wire_symbols)\n        symbols.extend(f'A{i}' for i in range(len(self.register)))\n        return cirq.CircuitDiagramInfo(\n            tuple(symbols),\n            exponent=f'({sign_char}A/2^{len(self.register)})',\n            exponent_qubit_index=sub_result.exponent_qubit_index or 0,\n            auto_exponent_parens=False,\n        )\n\n    def _has_unitary_(self) -> bool:\n        return True\n\n    def _apply_unitary_(self, args: 'cirq.ApplyUnitaryArgs'):\n        transposed_args = args.with_axes_transposed_to_start()\n\n        target_axes = transposed_args.axes[: len(self.base_operation.qubits)]\n        control_axes = transposed_args.axes[len(self.base_operation.qubits) :]\n        control_max = np.prod([q.dimension for q in self.register], dtype=np.int64).item()\n\n        for i in range(control_max):\n            operation = self.base_operation ** (self.exponent_sign * i / control_max)\n            control_index = linalg.slice_for_qubits_equal_to(control_axes, big_endian_qureg_value=i)\n            sub_args = cirq.ApplyUnitaryArgs(\n                transposed_args.target_tensor[control_index],\n                transposed_args.available_buffer[control_index],\n                target_axes,\n            )\n            sub_result = cirq.apply_unitary(operation, sub_args)\n\n            if sub_result is not sub_args.target_tensor:\n                sub_args.target_tensor[...] = sub_result\n\n        return args.target_tensor\n\n    def __repr__(self) -> str:\n        return (\n            f'cirq.interop.quirk.QuirkInputRotationOperation('\n            f'identifier={self.identifier!r}, '\n            f'register={self.register!r}, '\n            f'base_operation={self.base_operation!r}, '\n            f'exponent_sign={self.exponent_sign!r})'\n        )\n\n\ndef generate_all_input_rotation_cell_makers() -> Iterator[CellMaker]:\n    yield _input_rotation_gate(\"X^(A/2^n)\", ops.X, +1)\n    yield _input_rotation_gate(\"Y^(A/2^n)\", ops.Y, +1)\n    yield _input_rotation_gate(\"Z^(A/2^n)\", ops.Z, +1)\n    yield _input_rotation_gate(\"X^(-A/2^n)\", ops.X, -1)\n    yield _input_rotation_gate(\"Y^(-A/2^n)\", ops.Y, -1)\n    yield _input_rotation_gate(\"Z^(-A/2^n)\", ops.Z, -1)\n\n\ndef _input_rotation_gate(identifier: str, gate: 'cirq.Gate', exponent_sign: int) -> CellMaker:\n    return CellMaker(\n        identifier,\n        gate.num_qubits(),\n        lambda args: InputRotationCell(\n            identifier=identifier,\n            register=None,\n            base_operation=gate.on(args.qubits[0]),\n            exponent_sign=exponent_sign,\n        ),\n    )\n", "meta": {"hexsha": "53a8c2bd41dd92240d4d4717fba773f1840495ea", "size": 7417, "ext": "py", "lang": "Python", "max_stars_repo_path": "cirq-core/cirq/interop/quirk/cells/input_rotation_cells.py", "max_stars_repo_name": "peterse/Cirq", "max_stars_repo_head_hexsha": "31daa9410a0e1e1ac3da38109aa8ce3a15aed17b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3326, "max_stars_repo_stars_event_min_datetime": "2018-07-18T23:17:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:28:24.000Z", "max_issues_repo_path": "cirq-core/cirq/interop/quirk/cells/input_rotation_cells.py", "max_issues_repo_name": "peterse/Cirq", "max_issues_repo_head_hexsha": "31daa9410a0e1e1ac3da38109aa8ce3a15aed17b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3443, "max_issues_repo_issues_event_min_datetime": "2018-07-18T21:07:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:23:21.000Z", "max_forks_repo_path": "cirq-core/cirq/interop/quirk/cells/input_rotation_cells.py", "max_forks_repo_name": "peterse/Cirq", "max_forks_repo_head_hexsha": "31daa9410a0e1e1ac3da38109aa8ce3a15aed17b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 865, "max_forks_repo_forks_event_min_datetime": "2018-07-18T23:30:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:43:23.000Z", "avg_line_length": 35.8309178744, "max_line_length": 100, "alphanum_fraction": 0.629904274, "include": true, "reason": "import numpy", "num_tokens": 1672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.19923329715255295}}
{"text": "import copy\nimport os\nimport sys\nimport subprocess\nimport argparse\nimport time\nimport random\nimport numpy as np\n\nimport torch\nfrom torch.utils.data import DataLoader\n\nimport log\nfrom models import MLP_300_100, VGG11, PreActResNet18\nfrom utils import (train_loop, eval_loop, kaiming_init, get_cifar10_loader,\n                   get_cifar10_loader_gpu, get_mnist_sets)\nfrom pruning import get_mask_iteratively, mask_net\n\n\nDATA_PATH = os.path.join(os.environ['SLURM_TMPDIR'], 'data')\nXP_PATH = os.path.join(os.environ['SLURM_TMPDIR'], 'results')\n\n\ndef get_model(args):\n    # Build network\n    log.log_comment('Building Model')\n    if args.arch == 'MLP':\n        net = MLP_300_100()\n    elif args.arch == 'VGG11':\n        net = VGG11()\n    elif args.arch == 'PreActResNet18':\n        net = PreActResNet18()\n    else:\n        raise NotImplementedError\n    net.to('cuda')\n    # Initialize it\n    kaiming_init(net)\n    # Print it\n    log.log_comment('Network:')\n    for s in str(net).split('\\n'):\n        log.log_comment(s)\n    n = sum(p.numel() for p in net.parameters() if p.requires_grad)\n    log.log_comment('  - Number of parameters: %i' % n)\n    return net\n\n\ndef main():\n    # -------------------------------------------------------------------------\n    # Argumet Parser\n\n    parser = argparse.ArgumentParser(description='SNIP on CIFAR10')\n\n    # Lottery Ticket\n    parser.add_argument('--pr', type=float, default=0.956,\n                        help='Pruning ratio')\n    parser.add_argument('--pm', type=str, default='MP',\n                        choices=['MP', 'LM', 'QM', 'OBD'],\n                        help='Pruning method')\n    parser.add_argument('--pi', type=int, default=1,\n                        help='Number of iterations of pruning.')\n    parser.add_argument('--pe', type=int, default=0,\n                        help='Iteration before which we prune.')\n    parser.add_argument('--reg', type=float, default=0.0,\n                        help='Regularization parameter for snip and obsn.')\n    parser.add_argument('--nex', type=int, default=1000,\n                        help='Number of examples for pruning algorithms')\n    parser.add_argument('--exp', action='store_true',\n                        help='Use eponential pruning steps')\n\n    # Model\n    parser.add_argument('--arch', default='VGG11', type=str,\n                        choices=['MLP', 'VGG11', 'PreActResNet18'],\n                        help='Model achitecture.')\n    parser.add_argument('--model_0', type=str, default=None,\n                        help='Path to a saved network.')\n\n    # Optimizer\n    parser.add_argument('--lr', default=0.01, type=float,\n                        help='Learning rate.')\n    parser.add_argument('--dec', default=1., type=float,\n                        help='Learning rate decay (exponential).')\n    parser.add_argument('--dec_every', default=1, type=int,\n                        help='Number of epochs between decay.')\n    parser.add_argument('--l2', default=0.0005, type=float,\n                        help='L2 regularization.')\n\n    # Experiment Management\n    parser.add_argument('--path', type=str, default=XP_PATH,\n                        help='Path for experiment')\n    parser.add_argument('--data_path', default=DATA_PATH, type=str,\n                        help='Path for the data')\n    parser.add_argument('--num_workers', default=4, type=int,\n                        help='Number of workers to prepare data.')\n    parser.add_argument('--nepochs', default=200, type=int,\n                        help='Number of epochs to run.')\n    parser.add_argument('--seed', default=1111, type=int,\n                        help='Seed of the random number generators.')\n    args = parser.parse_args()\n\n    assert torch.cuda.is_available()  # Only train on GPU\n    torch.manual_seed(args.seed)\n    torch.cuda.manual_seed_all(args.seed)\n    random.seed(args.seed)\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = False\n\n    # -------------------------------------------------------------------------\n    # Preparing Paths and Log\n\n    name = ''\n    for k, v in sorted(args.__dict__.items(), key=lambda a: a[0]):\n        if k not in ['path', 'data_path', 'num_workers']:\n            if k == 'model_0' and v is not None:\n                v = True\n            name += '%s=%s,' % (k, str(v))\n    name = name[:-1]\n\n    if args.path is not None:\n        xp_path = os.path.join(args.path, name)\n        if not os.path.isdir(xp_path):\n            os.makedirs(xp_path)\n        else:\n            sys.exit('Experiment already exists!')\n        log_path = os.path.join(xp_path, 'log.txt')\n    else:\n        log_path = None\n    log.prepare_log(log_path)\n    log.log_comment('Pruning Experiment')\n    try:\n        repo = subprocess.check_output(['git', 'rev-parse', 'HEAD'],\n                                       encoding='utf-8').strip()\n    except:\n        repo = 'None'\n    log.log_comment('Git commit: ' + repo)\n    log.log_comment('Arguments:')\n    for k in sorted(args.__dict__.keys()):\n        log.log_comment('  - %s %s' % (k, str(args.__dict__[k])))\n\n    # -------------------------------------------------------------------------\n    # Preparing Data Streams\n\n    log.log_comment('Preparing data')\n    if args.arch == 'MLP':\n        train_set, valid_set, test_set = get_mnist_sets(args.seed,\n                                                        args.data_path)\n        train_loader = DataLoader(train_set, batch_size=100, shuffle=True)\n        valid_loader = (valid_set.tensors,)\n        test_loader = (test_set.tensors,)\n        fisher_loader = DataLoader(train_set, batch_size=args.nex,\n                                   shuffle=True)\n    else:\n        train_loader = get_cifar10_loader('train', 100, args.num_workers, True,\n                                          args.data_path)\n        valid_loader = get_cifar10_loader_gpu('valid', 5000, args.num_workers,\n                                              False, args.data_path)\n        test_loader = get_cifar10_loader_gpu('test', 5000, args.num_workers,\n                                              False, args.data_path)\n        fisher_loader = get_cifar10_loader_gpu('train', 100, args.num_workers,\n                                               True, args.data_path,\n                                               which_transform='valid')\n\n    # -------------------------------------------------------------------------\n    # Preparing Model and Optimizer\n\n    if args.model_0 is not None:\n        net = torch.load(args.model_0)\n    else:\n        net = get_model(args)\n    mask = None\n    optimizer = torch.optim.SGD(net.parameters(), lr=args.lr, momentum=0.9,\n                                weight_decay=args.l2)\n    scheduler = torch.optim.lr_scheduler.StepLR(optimizer,\n                                                step_size=args.dec_every,\n                                                gamma=args.dec,\n                                                last_epoch=-1)\n\n    # -------------------------------------------------------------------------\n    # Main Loop\n\n    form = ['%i', '%.5f', '%.5f', '%.5f', '%.5f', '%.5f', '%.5f', '%.2f']\n    head = ['n', 'train_l', 'train_m', 'valid_l', 'valid_m', 'test_l',\n            'test_m', 'time']\n    log.log_head(head, form)\n    best_err = float('inf')\n    best_net = copy.deepcopy(net)\n\n    for epoch in range(0, args.nepochs):\n        torch.manual_seed(args.seed + epoch)\n        torch.cuda.manual_seed_all(args.seed + epoch)\n        random.seed(args.seed + epoch)\n\n        if epoch == args.pe:\n            net = best_net\n\n            log.log_comment('Performances before pruning')\n            timer = time.time()\n            train_l, train_m = eval_loop(net, fisher_loader)\n            valid_l, valid_m = eval_loop(net, valid_loader)\n            test_l, test_m = eval_loop(net, test_loader)\n            log.log_comment('\\t'.join(form) % (epoch, train_l, train_m,\n                                               valid_l, valid_m, test_l,\n                                               test_m, time.time() - timer))\n\n            log.log_comment('Pruning network!')\n            timer = time.time()\n\n            # Compute pruning ratios\n            if args.exp:\n\n                def get_prs(pr, pi, p0=0):\n                    r = 1 - (1 - (pr - p0)) ** (1 / pi)\n                    p = [0]\n                    for i in range(pi):\n                        p.append(p[-1] + (1 - p[-1]) * r)\n                    return [p0 + pp for pp in p[1:]]\n\n                prunings = get_prs(args.pr, args.pi)\n                log.log_comment('Final pruning: ' + str(prunings[-1]))\n            else:\n                prunings = [args.pr / args.pi * (i + 1) for i in range(args.pi)] \n\n            mask = get_mask_iteratively(args.pm, net, prunings,\n                                        loader=fisher_loader, n=args.nex,\n                                        reg=args.reg)\n            mask_net(net, mask, False)\n\n            log.log_comment('Performances after pruning')\n            train_l, train_m = eval_loop(net, fisher_loader)\n            valid_l, valid_m = eval_loop(net, valid_loader)\n            test_l, test_m = eval_loop(net, test_loader)\n            log.log_comment('\\t'.join(form) % (epoch, train_l, train_m,\n                                               valid_l, valid_m, test_l,\n                                               test_m, time.time() - timer))\n\n            optimizer = torch.optim.SGD(net.parameters(), lr=args.lr, momentum=0.9,\n                                        weight_decay=args.l2)\n            scheduler = torch.optim.lr_scheduler.StepLR(optimizer,\n                                                        step_size=args.dec_every,\n                                                        gamma=args.dec,\n                                                        last_epoch=-1)\n\n        # Actual training and validation loops\n        timer = time.time()\n        train_l, train_m = train_loop(net, optimizer, train_loader, mask)\n        valid_l, valid_m = eval_loop(net, valid_loader)\n        test_l, test_m = eval_loop(net, test_loader)\n\n        to_log = [epoch, train_l, train_m, valid_l, valid_m, test_l, test_m,\n                  time.time() - timer]\n        log.log_values(to_log)\n\n        # Early stopping if not working properly\n        if np.isnan(train_l):\n            sys.exit()\n\n        # Learning Rate Decay\n        scheduler.step()\n\n        # Saving net\n        if valid_m < best_err:\n            log.log_comment('Best model so far.')\n            best_err = valid_m\n            net.zero_grad()\n            best_net = copy.deepcopy(net)\n            torch.save(net, os.path.join(xp_path, 'best_model.pt'))\n    net.zero_grad()\n    torch.save(net, os.path.join(xp_path, 'last_model.pt'))\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "a1e308c101a6f9e30085cd2f73caf9c6f19a662f", "size": 10797, "ext": "py", "lang": "Python", "max_stars_repo_path": "experiments.py", "max_stars_repo_name": "Thrandis/loss-models-pruning", "max_stars_repo_head_hexsha": "b784b84cd2494e59673849dfd3b3e45e996a7e7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experiments.py", "max_issues_repo_name": "Thrandis/loss-models-pruning", "max_issues_repo_head_hexsha": "b784b84cd2494e59673849dfd3b3e45e996a7e7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "experiments.py", "max_forks_repo_name": "Thrandis/loss-models-pruning", "max_forks_repo_head_hexsha": "b784b84cd2494e59673849dfd3b3e45e996a7e7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6948529412, "max_line_length": 83, "alphanum_fraction": 0.5187552098, "include": true, "reason": "import numpy", "num_tokens": 2318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.19923329715255292}}
{"text": "#!/usr/bin/env python\nfrom string import *\nimport os, commands, getopt, sys, exceptions\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass search_failed(exceptions.Exception):\n    def __init__(self,args=None):\n        self.args=args\nclass eof(exceptions.Exception):\n    def __init__(self,args=None):\n        self.args=args\n\n\n\n#\n# look for key1.  if we find key2 instead, raise error\n#\ndef lookfor1(fid,key1,key2=\"\",allow_eof=0):\n    line=fid.readline()\n    while line:\n        pos=find(line,key1)\n        if (-1 <> pos ):\n            sline = line[pos+len(key1):-1]\n            return sline\n        if (len(key2)>0):\n           pos=find(line,key2)\n           if (-1 <> pos ):\n               print \"error looking for: \"+key1\n               raise search_failed,\"run not complete, found: \"+key2\n        line=fid.readline()\n\n    if (allow_eof==1):\n        raise eof,\"EOF\"\n#    raise search_failed,\"Search failed  string='\"+key1+\"'\"\n    raise search_failed,\"Search failed  string=\"+key1\n    return 0\n\n    \n\nmumin=[]\nmumax=[]\nKE=[]\nIE=[]\nPE=[]\nKEdiss=[]\nIEdiss=[]\nPEdiss=[]\nIPEdiss=[]\nDELE=[]\ntime=[]\ntry:\n    startstr=\"number of MPI processes:\"\n    str = lookfor1(sys.stdin,startstr,\"\",0)\n    str=split(str)\n    ncpu=atoi(str[0])\n\n    str = lookfor1(sys.stdin,\"theta_hydrostatic_mode \",\"\",0)\n    str=split(str)\n    hydrostatic_mode  = (str[1]==\"T\")\n\n    str = lookfor1(sys.stdin,\"tstep \",\"\",0)\n    str=split(str)\n    tstep=atof(str[1])\n    print 'NCPU = %i tstep=%f' % (ncpu, tstep)\n    while 1:\n        # nstep=           3  time=  1.041666666666667E-002  [day]\n        str = lookfor1(sys.stdin,\"nstep=\",\"\",1)\n        str=split(str)\n        n=atoi(str[0])\n     \n        time.extend([n*tstep/(24*3600)])\n\n        if ( ~hydrostatic_mode ):\n            str = lookfor1(sys.stdin,\"mu    =\",\"\",0)\n            str=split(str)\n            mumin.extend([atof(str[0])])\n            mumax.extend([atof(str[3])])\n\n        # KE,d/dt,diss:\n        # IE,d/dt,diss:\n        # PE,d/dt,diss:\n        str = lookfor1(sys.stdin,\"KE,d/dt\",\"\",0)\n        str=split(str)\n        KE.extend([atof(str[1])])\n        if (len(str) >= 4):\n           KEdiss.extend([atof(str[3])])\n\n        str = lookfor1(sys.stdin,\"IE,d/dt\",\"\",0)\n        str=split(str)\n        IE.extend([atof(str[1])])\n        if (len(str) >= 4):\n           IEdiss.extend([atof(str[3])])\n\n        str = lookfor1(sys.stdin,\"PE,d/dt\",\"\",0)\n        str=split(str)\n        PE.extend([atof(str[1])])\n        if (len(str) >= 4):\n           PEdiss.extend([atof(str[3])])\n\n        if ( hydrostatic_mode ):\n           str = lookfor1(sys.stdin,\"I+P,d/dt\",\"\",0)\n           str=split(str)\n           IPEdiss.extend([atof(str[3])])\n\n        str = lookfor1(sys.stdin,\" E,d/dt\",\"\",0)\n        str=split(str)\n        DELE.extend([atof(str[2])])\n\n        #print 'parsed nstep=%i' % ( n)\n\n        \nexcept search_failed,e:\n    print \"search failed\"\n    print \"\".join(e)\n    sys.exit(1)\n    \nexcept eof,e:\n    print 'plotting energy...'\n    KE2= np.array(KE)\n    nlen=KE2.size\n    print 'data parsed size=%i' % (nlen)\n    time=time[0:nlen]\n    KE2=KE2*1e3\n    PE2= np.array(PE)\n    IE2= np.array(IE)\n    plt.figure()\n    plt.plot(time,KE2,label='KE*1e3')\n    plt.plot(time,PE2,label='PE')\n    plt.plot(time,IE2,label='IE')\n    #plt.axis([0, 500, 0, 2.5e9])\n    plt.grid(True)\n    plt.legend()\n    plt.savefig(\"HS-E.png\")\n\n    print 'plotting dissipation rates...'    \n    print 'data parsed size=%i' % (len(IPEdiss))\n    plt.figure()\n    if (len(IPEdiss)>0):\n       print 'plotting Hydrostatic I+P,d/dt,diss data'\n       plt.plot(time,IPEdiss,label='IE+PE dissipation')\n\n    if (len(IEdiss)>0):\n       print 'plotting NH data, sum of IEdiss and PEdiss'\n       IPEdiss = np.array(PEdiss) + np.array(IEdiss)       \n       plt.plot(time,IPEdiss,label='IE+PE dissipation')\n\n    if (len(KEdiss)>0): \n       plt.plot(time,KEdiss,label='KE dissipation')\n\n    plt.plot(time,DELE,label='TOT E dissipation')\n\n    plt.axis([0, 500, -.5, .1])\n    #plt.axis([0, 500, -.1, .1])\n    #plt.axis([1600, 1700, -.4, .2])\n    plt.grid(True)\n    plt.legend()\n    plt.savefig(\"HS-diss.png\")\n\n    if ( ~hydrostatic_mode ):\n        plt.figure()\n        print ('plotting mu...std min,max=%f %f' % (np.std(mumin),np.std(mumax)))\n        legend1=(\"min avg: %.3f std: %.4f\" % (sum(mumin)/len(mumin),np.std(mumin)) )\n        plt.plot(time,mumin,label=legend1)\n        legend1=(\"min avg: %.3f std: %.4f\" % (sum(mumax)/len(mumax),np.std(mumax)) )\n        plt.plot(time,mumax,label=legend1)\n        plt.axis([min(time), max(min(time)+200,max(time)), -0.,2.0])\n        plt.grid(True)\n        plt.legend()\n        plt.savefig(\"mu.png\")\n    \n\n    plt.show()\n    sys.exit(0)\n\n", "meta": {"hexsha": "fd4a0c8edf69edf205cd6eb8c1ee9bf3ece9a3af", "size": 4656, "ext": "py", "lang": "Python", "max_stars_repo_path": "components/homme/test/held_suarez0/parseE.py", "max_stars_repo_name": "jingxianwen/E3SM", "max_stars_repo_head_hexsha": "bced6ba5e9247d6db6c8445b5fb828772a929b1b", "max_stars_repo_licenses": ["zlib-acknowledgement", "RSA-MD", "FTL"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-02-24T21:58:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-29T23:06:45.000Z", "max_issues_repo_path": "components/homme/test/held_suarez0/parseE.py", "max_issues_repo_name": "jingxianwen/E3SM", "max_issues_repo_head_hexsha": "bced6ba5e9247d6db6c8445b5fb828772a929b1b", "max_issues_repo_licenses": ["zlib-acknowledgement", "RSA-MD", "FTL"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2019-09-27T02:16:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-01T17:51:12.000Z", "max_forks_repo_path": "components/homme/test/held_suarez0/parseE.py", "max_forks_repo_name": "jingxianwen/E3SM", "max_forks_repo_head_hexsha": "bced6ba5e9247d6db6c8445b5fb828772a929b1b", "max_forks_repo_licenses": ["zlib-acknowledgement", "RSA-MD", "FTL"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-05-24T15:09:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-24T15:17:27.000Z", "avg_line_length": 26.4545454545, "max_line_length": 84, "alphanum_fraction": 0.5487542955, "include": true, "reason": "import numpy", "num_tokens": 1438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.19923329715255292}}
{"text": "from __future__ import absolute_import\nfrom __future__ import print_function\nimport os\nimport glob\nimport logging\nimport copy\nimport pickle\nimport math\nimport time\nimport numpy as np\nfrom scipy.stats import norm\nimport getdist\nfrom getdist import chains, types, covmat, ParamInfo, IniFile, ParamNames\nfrom getdist.densities import Density1D, Density2D, DensityND\nfrom getdist.densities import getContourLevels as getOtherContourLevels\nfrom getdist.chains import Chains, chainFiles, lastModified\nfrom getdist.convolve import convolve1D, convolve2D\nimport getdist.kde_bandwidth as kde\nfrom getdist.parampriors import ParamBounds\nimport six\n\npickle_version = 21\n\n\nclass MCSamplesError(Exception):\n    \"\"\"\n    An Exception that is raised when there is an error inside the MCSamples class.\n    \"\"\"\n    pass\n\n\nclass SettingError(MCSamplesError):\n    \"\"\"\n    An Exception that indicates bad settings.\n    \"\"\"\n    pass\n\n\nclass ParamError(MCSamplesError):\n    \"\"\"\n    An Exception that indicates a bad parameter.\n    \"\"\"\n    pass\n\n\ndef loadMCSamples(file_root, ini=None, jobItem=None, no_cache=False, settings={}, dist_settings={}):\n    \"\"\"\n    Loads a set of samples from a file or files.\n\n    Sample files are plain text (*file_root.txt*) or a set of files (*file_root_1.txt*, *file_root_2.txt*, etc.).\n\n    Auxiliary files **file_root.paramnames** gives the parameter names\n    and (optionally) **file_root.ranges** gives hard prior parameter ranges.\n\n    For a description of the various analysis settings and default values see\n    `analysis_defaults.ini <http://getdist.readthedocs.org/en/latest/analysis_settings.html>`_.\n\n    :param file_root: The root name of the files to read (no extension)\n    :param ini: The name of a .ini file with analysis settings to use\n    :param jobItem: an optional grid jobItem instance for a CosmoMC grid output\n    :param no_cache: Indicates whether or not we should cache loaded samples in a pickle\n    :param settings: dictionary of analysis settings to override defaults\n    :param dist_settings: (old) alias for settings\n    :return: The :class:`MCSamples` instance\n    \"\"\"\n    if settings and dist_settings: raise ValueError('Use settings or dist_settings')\n    if dist_settings: settings = dist_settings\n    files = chainFiles(file_root)\n    path, name = os.path.split(file_root)\n    path = getdist.cache_dir or path\n    if not os.path.exists(path): os.mkdir(path)\n    cachefile = os.path.join(path, name) + '.py_mcsamples'\n    samples = MCSamples(file_root, jobItem=jobItem, ini=ini, settings=settings)\n    if os.path.isfile(file_root + '.paramnames'):\n        allfiles = files + [file_root + '.ranges', file_root + '.paramnames', file_root + '.properties.ini']\n    else:  # new format (txt+yaml)\n        mid = \"\" if file_root.endswith(\"/\") else \"__\"\n        allfiles = files + [file_root + mid + ending for ending in ['input.yaml', 'full.yaml']]\n    if not no_cache and os.path.exists(cachefile) and lastModified(allfiles) < os.path.getmtime(cachefile):\n        try:\n            with open(cachefile, 'rb') as inp:\n                cache = pickle.load(inp)\n            if cache.version == pickle_version and samples.ignore_rows == cache.ignore_rows \\\n                    and samples.min_weight_ratio == cache.min_weight_ratio:\n                changed = len(samples.contours) != len(cache.contours) or \\\n                          np.any(np.array(samples.contours) != np.array(cache.contours))\n                cache.updateSettings(ini=ini, settings=settings, doUpdate=changed)\n                return cache\n        except Exception as e:\n            pass\n    if not len(files):\n        raise IOError('No chains found: ' + file_root)\n    samples.readChains(files)\n    samples.savePickle(cachefile)\n    return samples\n\n\ndef loadCobayaSamples(info, collections, name_tag=None,\n                      ignore_rows=0, ini=None, settings={}):\n    \"\"\"\n    Loads a set of samples from Cobaya's output.\n    Parameter names, ranges and labels are taken from the \"info\" dictionary\n    (always use the \"full\", updated one generated by `cobaya.run`).\n\n    For a description of the various analysis settings and default values see\n    `analysis_defaults.ini <http://getdist.readthedocs.org/en/latest/analysis_settings.html>`_.\n\n    :param collections: collection(s) of samples from Cobaya\n    :param info: info dictionary, common to all collections\n                 (use the \"updated\" one, returned by `cobaya.run`)\n    :param name_tag: name for this sample to be shown in the plots' legend\n    :param ignore_rows: initial samples to skip, number (`int>=1`) or fraction (`float<1`)\n    :param ini: The name of a .ini file with analysis settings to use\n    :param settings: dictionary of analysis settings to override defaults\n    :return: The :class:`MCSamples` instance\n    \"\"\"\n    if not hasattr(info, \"keys\"):\n        raise TypeError(\"Cannot regonise arguments. Are you sure you are calling \"\n                        \"with (info, collections, ...) in that order?\")\n    if hasattr(collections, \"data\"):\n        collections = [collections]\n    # Check consistency between collections\n    columns = list(collections[0].data)\n    if not all([list(c.data) == columns for c in collections[1:]]):\n        raise ValueError(\"The given collections don't have the same columns.\")\n    from getdist.yaml_format_tools import _p_label, _p_renames, _weight, _minuslogpost\n    from getdist.yaml_format_tools import get_info_params, get_range, is_derived_param\n    # Check consistency with info\n    info_params = get_info_params(info)\n    assert set(columns[2:]) == set(info_params.keys()), (\n            \"Info and collection(s) are not compatible, because their parameters differ: \"\n            \"the collection(s) have %r and the info has %r. \" % (\n                columns[2:], list(info_params.keys())) +\n            \"Are you sure that you are using an *updated* info dictionary \"\n            \"(i.e. the output of `cobaya.run`)?\")\n    # We need to use *collection* sorting, not info sorting!\n    names = [p + (\"*\" if is_derived_param(info_params[p]) else \"\")\n             for p in columns[2:]]\n    labels = [(info_params[p] or {}).get(_p_label, p) for p in columns[2:]]\n    ranges = {p: get_range(info_params[p]) for p in columns[2:]}\n    renames = {p: info_params.get(p, {}).get(_p_renames, []) for p in columns[2:]}\n    samples = [c[c.data.columns[2:]].values for c in collections]\n    weights = [c[_weight].values for c in collections]\n    loglikes = [-c[_minuslogpost].values for c in collections]\n    return MCSamples(samples=samples, weights=weights, loglikes=loglikes,\n                     names=names, labels=labels, ranges=ranges, renames=renames,\n                     ignore_rows=ignore_rows, name_tag=name_tag, ini=ini,\n                     settings=settings)\n\n\nclass Kernel1D(object):\n    def __init__(self, winw, h):\n        self.winw = winw\n        self.h = h\n        self.x = np.arange(-winw, winw + 1)\n        Win = np.exp(-(self.x / h) ** 2 / 2.)\n        self.Win = Win / np.sum(Win)\n\n\n# =============================================================================\n\nclass MCSamples(Chains):\n    \"\"\"\n    The main high-level class for a collection of parameter samples.\n\n    Derives from :class:`.chains.Chains`, adding high-level functions including Kernel Density estimates, parameter ranges and custom settings.\n    \"\"\"\n\n    def __init__(self, root=None, jobItem=None, ini=None, settings=None, ranges=None,\n                 samples=None, weights=None, loglikes=None, **kwargs):\n        \"\"\"\n        For a description of the various analysis settings and default values see\n        `analysis_defaults.ini <http://getdist.readthedocs.org/en/latest/analysis_settings.html>`_.\n\n\n        :param root: A root file name when loading from file\n        :param jobItem: Optional paramgrid.batchjob.jobItem instance if a member of a parameter grid\n        :param ini: a .ini file to use for custom analysis settings\n        :param settings: a dictionary of custom analysis settings\n        :param ranges: a dictionary giving any additional hard prior bounds for parameters, eg. {'x':[0, 1], 'y':[None,2]}\n        :param samples: if not loading from file, array of parameter values for each sample, passed to :meth:`setSamples`,\n                        or list of arrays if more than one chain\n        :param weights: array of weights for samples, or list of arrays if more than one chain\n        :param loglikes: array of -log(Likelihood) for samples, or list of arrays if more than one chain\n\n        :param kwargs: keyword arguments passed to inherited classes, e.g. to manually make a samples object from sample arrays in memory:\n\n               - **paramNamesFile**: optional name of .paramnames file with parameter names\n               - **names**: list of names for the parameters,\n                            or list of arrays if more than one chain\n               - **labels**: list of latex labels for the parameters\n               - **renames**: dictionary of parameter aliases\n               - **ignore_rows**:\n\n                     - if int >=1: The number of rows to skip at the file in the beginning of the file\n                     - if float <1: The fraction of rows to skip at the beginning of the file\n               - **name_tag**: a name tag for this instance\n        \"\"\"\n        Chains.__init__(self, root, jobItem=jobItem, **kwargs)\n\n        self.version = pickle_version\n\n        self.markers = {}\n\n        self.ini = ini\n        if self.jobItem:\n            self.batch_path = self.jobItem.batchPath\n        else:\n            self.batch_path = ''\n\n        self._readRanges()\n        if ranges:\n            self.setRanges(ranges)\n\n        # Other variables\n        self.range_ND_contour = 1\n        self.range_confidence = 0.001\n        self.num_bins = 128\n        self.fine_bins = 1024\n        self.num_bins_2D = 40\n        self.fine_bins_2D = 256\n        self.smooth_scale_1D = -1.\n        self.smooth_scale_2D = -1.\n        self.num_bins_ND = 12\n        self.boundary_correction_order = 1\n        self.mult_bias_correction_order = 1\n        self.max_corr_2D = 0.95\n        self.contours = np.array([0.68, 0.95])\n        self.max_scatter_points = 2000\n        self.credible_interval_threshold = 0.05\n\n        self.shade_likes_is_mean_loglikes = False\n\n        self.likeStats = None\n        self.max_mult = 0\n        self.mean_mult = 0\n        self.plot_data_dir = \"\"\n        if root:\n            self.rootname = os.path.basename(root)\n        else:\n            self.rootname = \"\"\n\n        self.rootdirname = \"\"\n        self.indep_thin = 0\n        if 'ignore_rows' in kwargs:\n            if settings is None: settings = {}\n            settings['ignore_rows'] = kwargs['ignore_rows']\n        self.ignore_rows = float(kwargs.get('ignore_rows', 0))\n        self.subplot_size_inch = 4.0\n        self.subplot_size_inch2 = self.subplot_size_inch\n        self.subplot_size_inch3 = 6.0\n        self.plot_output = getdist.default_plot_output\n        self.out_dir = \"\"\n        self.no_warning_params = []\n        self.no_warning_chi2_params = True\n\n        self.max_split_tests = 4\n        self.force_twotail = False\n\n        self.corr_length_thin = 0\n        self.corr_length_steps = 15\n        self.converge_test_limit = 0.95\n\n        self.done_1Dbins = False\n        self.density1D = dict()\n\n        self.updateSettings(ini=ini, settings=settings)\n\n        if root and os.path.exists(root + '.properties.ini'):\n            # any settings in properties.ini override settings for this specific chain\n            self.properties = IniFile(root + '.properties.ini')\n            self._setBurnOptions(self.properties)\n            if self.properties.bool('burn_removed', False):\n                self.ignore_frac = 0.\n                self.ignore_lines = 0\n        else:\n            self.properties = None\n\n        if samples is not None:\n            self.readChains(samples, weights, loglikes)\n\n    def setRanges(self, ranges):\n        \"\"\"\n        Sets the ranges parameters, e.g. hard priors on positivity etc.\n        If a min or max value is None, then it is assumed to be unbounded.\n\n        :param ranges: A list or a tuple of [min,max] values for each parameter,\n                       or a dictionary giving [min,max] values for specific parameter names\n        \"\"\"\n        if isinstance(ranges, (list, tuple)):\n            for i, minmax in enumerate(ranges):\n                self.ranges.setRange(self.parName(i), minmax)\n        elif isinstance(ranges, dict):\n            for key, value in six.iteritems(ranges):\n                self.ranges.setRange(key, value)\n        elif isinstance(ranges, ParamBounds):\n            self.ranges = copy.deepcopy(ranges)\n        else:\n            raise ValueError('MCSamples ranges parameter must be list or dict')\n        self.needs_update = True\n\n    def parName(self, i, starDerived=False):\n        \"\"\"\n        Gets the name of i'th parameter\n\n        :param i: The index of the parameter\n        :param starDerived: add a star at the end of the name if the parameter is derived\n        :return: The name of the parameter (string)\n        \"\"\"\n        return self.paramNames.name(i, starDerived)\n\n    def parLabel(self, i):\n        \"\"\"\n        Gets the latex label of the parameter\n\n        :param i: The index or name of a parameter.\n        :return: The parameter's label.\n        \"\"\"\n        if isinstance(i, six.string_types):\n            return self.paramNames.parWithName(i).label\n        else:\n            return self.paramNames.names[i].label\n\n    def _setBurnOptions(self, ini):\n        \"\"\"\n        Sets the ignore_rows value from configuration.\n\n        :param ini: The :class:`.inifile.IniFile` to be used\n        \"\"\"\n        ini.setAttr('ignore_rows', self)\n        self.ignore_lines = int(self.ignore_rows)\n        if not self.ignore_lines:\n            self.ignore_frac = self.ignore_rows\n        else:\n            self.ignore_frac = 0\n        ini.setAttr('min_weight_ratio', self)\n\n    def initParameters(self, ini):\n        \"\"\"\n        Initializes settings.\n        Gets parameters from :class:`~.inifile.IniFile`.\n\n        :param ini:  The :class:`~.inifile.IniFile` to be used\n        \"\"\"\n        self._setBurnOptions(ini)\n\n        ini.setAttr('range_ND_contour', self)\n        ini.setAttr('range_confidence', self)\n        ini.setAttr('num_bins', self)\n        ini.setAttr('fine_bins', self)\n\n        ini.setAttr('num_bins_2D', self)\n        ini.setAttr('fine_bins_2D', self)\n\n        ini.setAttr('smooth_scale_1D', self)\n        ini.setAttr('smooth_scale_2D', self)\n\n        ini.setAttr('boundary_correction_order', self, 1)\n        ini.setAttr('mult_bias_correction_order', self, 1)\n\n        ini.setAttr('num_bins_ND', self)\n\n        ini.setAttr('max_scatter_points', self)\n        ini.setAttr('credible_interval_threshold', self)\n\n        ini.setAttr('subplot_size_inch', self)\n        ini.setAttr('subplot_size_inch2', self)\n        ini.setAttr('subplot_size_inch3', self)\n        ini.setAttr('plot_output', self)\n\n        ini.setAttr('force_twotail', self)\n        if self.force_twotail: logging.warning('Computing two tail limits')\n        ini.setAttr('max_corr_2D', self)\n\n        if ini.hasKey('contours'):\n            ini.setAttr('contours', self)\n        elif ini.hasKey('num_contours'):\n            num_contours = ini.int('num_contours', 2)\n            self.contours = np.array([ini.float('contour' + str(i + 1)) for i in range(num_contours)])\n        # how small the end bin must be relative to max to use two tail\n        self.max_frac_twotail = []\n        for i, contour in enumerate(self.contours):\n            max_frac = np.exp(-1.0 * math.pow(norm.ppf((1 - contour) / 2), 2) / 2)\n            if ini:\n                max_frac = ini.float('max_frac_twotail' + str(i + 1), max_frac)\n            self.max_frac_twotail.append(max_frac)\n\n        ini.setAttr('converge_test_limit', self, self.contours[-1])\n        ini.setAttr('corr_length_thin', self)\n        ini.setAttr('corr_length_steps', self)\n        ini.setAttr('no_warning_params', self, [])\n        ini.setAttr('no_warning_chi2_params', self, True)\n        self.batch_path = ini.string('batch_path', self.batch_path, allowEmpty=False)\n\n    def _initLimits(self, ini=None):\n        bin_limits = \"\"\n        if ini: bin_limits = ini.string('all_limits', '')\n\n        self.markers = {}\n\n        for par in self.paramNames.names:\n            if bin_limits:\n                line = bin_limits\n            else:\n                line = ''\n                if ini and 'limits[%s]' % par.name in ini.params:\n                    line = ini.string('limits[%s]' % par.name)\n            if line:\n                limits = line.split()\n                if len(limits) == 2:\n                    self.ranges.setRange(par.name, limits)\n\n            par.limmin = self.ranges.getLower(par.name)\n            par.limmax = self.ranges.getUpper(par.name)\n            par.has_limits_bot = par.limmin is not None\n            par.has_limits_top = par.limmax is not None\n\n            if ini and 'marker[%s]' % par.name in ini.params:\n                line = ini.string('marker[%s]' % par.name)\n                if line:\n                    self.markers[par.name] = float(line)\n\n    def updateSettings(self, settings=None, ini=None, doUpdate=True):\n        \"\"\"\n        Updates settings from a .ini file or dictionary\n\n        :param settings: The a dict containing settings to set, taking preference over any values in ini\n        :param ini: The name of .ini file to get settings from, or an :class:`~.inifile.IniFile` instance; by default uses current settings\n        :param doUpdate: True if should update internal computed values, False otherwise (e.g. if want to make other changes first)\n        \"\"\"\n        assert (settings is None or isinstance(settings, dict))\n        if not ini:\n            ini = self.ini\n        elif isinstance(ini, six.string_types):\n            ini = IniFile(ini)\n        else:\n            ini = copy.deepcopy(ini)\n        if not ini: ini = IniFile(getdist.default_getdist_settings)\n        if settings:\n            ini.params.update(settings)\n        self.ini = ini\n        if ini: self.initParameters(ini)\n        if doUpdate and self.samples is not None: self.updateBaseStatistics()\n\n    def readChains(self, files_or_samples, weights=None, loglikes=None):\n        \"\"\"\n        Loads samples from a list of files or array(s), removing burn in,\n        deleting fixed parameters, and combining into one self.samples array\n\n        :param files_or_samples: The list of file names to read, samples or list of samples\n        :param weights: array of weights if setting from arrays\n        :param loglikes: array of -2 log(likelihood) if setting from arrays\n        :return: self.\n        \"\"\"\n        self.loadChains(self.root, files_or_samples, weights=weights, loglikes=loglikes)\n\n        if self.ignore_frac and (\n                not self.jobItem or (not self.jobItem.isImportanceJob and not self.jobItem.isBurnRemoved())):\n            self.removeBurnFraction(self.ignore_frac)\n            if chains.print_load_details: print('Removed %s as burn in' % self.ignore_frac)\n        elif not int(self.ignore_rows):\n            if chains.print_load_details: print('Removed no burn in')\n\n        self.deleteFixedParams()\n\n        # Make a single array for chains\n        if self.chains is not None: self.makeSingle()\n\n        self.updateBaseStatistics()\n\n        return self\n\n    def updateBaseStatistics(self):\n        \"\"\"\n        Updates basic computed statistics (means, covariance etc), e.g. after a change in samples or weights\n\n        :return: self\n        \"\"\"\n        super(MCSamples, self).updateBaseStatistics()\n        mult_max = (self.mean_mult * self.numrows) / min(self.numrows // 2, 500)\n        outliers = np.sum(self.weights > mult_max)\n        if outliers != 0:\n            logging.warning('outlier fraction %s ', float(outliers) / self.numrows)\n\n        self.indep_thin = 0\n        self._setCov()\n        self.done_1Dbins = False\n        self.density1D = dict()\n\n        self._initLimits(self.ini)\n\n        # Get ND confidence region\n        self._setLikeStats()\n        return self\n\n    def makeSingleSamples(self, filename=\"\", single_thin=None):\n        \"\"\"\n        Make file of weight-1 samples by choosing samples\n        with probability given by their weight.\n\n        :param filename: The filename to write to, leave empty if no output file is needed\n        :param single_thin: factor to thin by; if not set generates as many samples as it can up to self.max_scatter_points\n        :return: numpy array of selected weight-1 samples\n        \"\"\"\n        if single_thin is None:\n            single_thin = max(1, self.norm / self.max_mult / self.max_scatter_points)\n        rand = np.random.random_sample(self.numrows)\n\n        if filename:\n            with open(filename, 'w') as f:\n                for i, r in enumerate(rand):\n                    if r <= self.weights[i] / self.max_mult / single_thin:\n                        f.write(\"%16.7E\" % 1.0)\n                        f.write(\"%16.7E\" % (self.loglikes[i]))\n                        for j in range(self.n):\n                            f.write(\"%16.7E\" % (self.samples[i][j]))\n                        f.write(\"\\n\")\n        else:\n            # return data\n            return self.samples[rand <= self.weights / (self.max_mult * single_thin)]\n\n    def writeThinData(self, fname, thin_ix, cool=1):\n        \"\"\"\n        Writes samples at thin_ix to file\n\n        :param fname: The filename to write to.\n        :param thin_ix: Indices of the samples to write\n        :param cool: if not 1, cools the samples by this factor\n        \"\"\"\n        nparams = self.samples.shape[1]\n        if cool != 1: logging.info('Cooled thinned output with temp: %s', cool)\n        MaxL = np.max(self.loglikes)\n        with open(fname, 'w') as f:\n            i = 0\n            for thin in thin_ix:\n                if cool != 1:\n                    newL = self.loglikes[thin] * cool\n                    f.write(\"%16.7E\" % (\n                        np.exp(-(newL - self.loglikes[thin]) - MaxL * (1 - cool))))\n                    f.write(\"%16.7E\" % newL)\n                    for j in range(nparams):\n                        f.write(\"%16.7E\" % (self.samples[i][j]))\n                else:\n                    f.write(\"%f\" % 1.)\n                    f.write(\"%f\" % (self.loglikes[thin]))\n                    for j in range(nparams):\n                        f.write(\"%16.7E\" % (self.samples[i][j]))\n                i += 1\n        print('Wrote ', len(thin_ix), ' thinned samples')\n\n    def getCovMat(self):\n        \"\"\"\n        Gets the CovMat instance containing covariance matrix for all the non-derived parameters\n        (for example useful for subsequent MCMC runs to orthogonalize the parameters)\n\n        :return: A :class:`~.covmat.CovMat` object holding the covariance\n        \"\"\"\n        nparamNonDerived = self.paramNames.numNonDerived()\n        return covmat.CovMat(matrix=self.fullcov[:nparamNonDerived, :nparamNonDerived],\n                             paramNames=self.paramNames.list()[:nparamNonDerived])\n\n    def writeCovMatrix(self, filename=None):\n        \"\"\"\n        Writes the covrariance matrix of non-derived parameters to a file.\n\n        :param filename: The filename to write to; default is file_root.covmat\n        \"\"\"\n        filename = filename or self.rootdirname + \".covmat\"\n        self.getCovMat().saveToFile(filename)\n\n    def writeCorrelationMatrix(self, filename=None):\n        \"\"\"\n        Write the correlation matrix to a file\n\n        :param filename: The file to write to, If none writes to file_root.corr\n        \"\"\"\n        filename = filename or self.rootdirname + \".corr\"\n        np.savetxt(filename, self.getCorrelationMatrix(), fmt=\"%15.7E\")\n\n    def getFractionIndices(self, weights, n):\n        \"\"\"\n        Calculates the indices of weights that split the weights into sets of equal 1/n fraction of the total weight\n\n        :param weights: array of weights\n        :param n: number of groups to split in to\n        :return: array of indices of the boundary rows in the weights array\n        \"\"\"\n        cumsum = np.cumsum(weights)\n        fraction_indices = np.append(np.searchsorted(cumsum, np.linspace(0, 1, n, endpoint=False) * self.norm),\n                                     self.weights.shape[0])\n        return fraction_indices\n\n    def PCA(self, params, param_map=None, normparam=None, writeDataToFile=False, filename=None,\n            conditional_params=[], n_best_only=None):\n        \"\"\"\n        Perform principle component analysis (PCA). In other words,\n        get eigenvectors and eigenvalues for normalized variables\n        with optional (log modulus) mapping to find power law fits.\n\n        :param params: List of names of the parameters to use\n        :param param_map: A transformation to apply to parameter values;\n                        A list or string containing either N (no transformation) or L (for log transform) for each parameter.\n                        By default uses log if no parameter values cross zero\n\n        :param normparam: optional name of parameter to normalize result (i.e. this parameter will have unit power)\n        :param writeDataToFile: True if should write the output to file.\n        :param filename: The filename to write, by default root_name.PCA.\n        :param conditional_params: optional list of parameters to treat as fixed, i.e. for PCA conditional on fixed values of these parameters\n        :param n_best_only: return just the short summary constraint for the tightest n_best_only constraints\n        :return: a string description of the output of the PCA\n        \"\"\"\n        logging.info('Doing PCA for %s parameters', len(params))\n        if len(conditional_params): logging.info('conditional %u fixed parameters', len(conditional_params))\n\n        PCAtext = 'PCA for parameters:\\n'\n\n        params = [name for name in params if self.paramNames.parWithName(name)]\n        nparams = len(params)\n        indices = [self.index[param] for param in params]\n        conditional_params = [self.index[param] for param in conditional_params]\n        indices += conditional_params\n\n        if normparam:\n            if normparam in params:\n                normparam = params.index(normparam)\n            else:\n                normparam = -1\n        else:\n            normparam = -1\n\n        n = len(indices)\n        PCdata = self.samples[:, indices].copy()\n        PClabs = []\n\n        PCmean = np.zeros(n)\n        sd = np.zeros(n)\n        newmean = np.zeros(n)\n        newsd = np.zeros(n)\n        if param_map is None:\n            param_map = ''\n            for par in self.paramNames.parsWithNames(params):\n                self._initParamRanges(par.name)\n                if par.param_max < 0 or par.param_min < (par.param_max - par.param_min) / 10:\n                    param_map += 'N'\n                else:\n                    param_map += 'L'\n\n        doexp = False\n        for i, parix in enumerate(indices):\n            if i < nparams:\n                label = self.parLabel(parix)\n                if param_map[i] == 'L':\n                    doexp = True\n                    PCdata[:, i] = np.log(PCdata[:, i])\n                    PClabs.append(\"ln(\" + label + \")\")\n                elif param_map[i] == 'M':\n                    doexp = True\n                    PCdata[:, i] = np.log(-1.0 * PCdata[:, i])\n                    PClabs.append(\"ln(-\" + label + \")\")\n                else:\n                    PClabs.append(label)\n                PCAtext += \"%10s :%s\\n\" % (str(parix + 1), str(PClabs[i]))\n\n            PCmean[i] = np.dot(self.weights, PCdata[:, i]) / self.norm\n            PCdata[:, i] -= PCmean[i]\n            sd[i] = np.sqrt(np.dot(self.weights, PCdata[:, i] ** 2) / self.norm)\n            if sd[i] != 0: PCdata[:, i] /= sd[i]\n\n        PCAtext += \"\\n\"\n        PCAtext += 'Correlation matrix for reduced parameters\\n'\n        correlationMatrix = np.ones((n, n))\n        for i in range(n):\n            for j in range(i):\n                correlationMatrix[j][i] = np.dot(self.weights, PCdata[:, i] * PCdata[:, j]) / self.norm\n                correlationMatrix[i][j] = correlationMatrix[j][i]\n        for i in range(nparams):\n            PCAtext += '%12s :' % params[i]\n            for j in range(n):\n                PCAtext += '%8.4f' % correlationMatrix[j][i]\n            PCAtext += '\\n'\n\n        if len(conditional_params):\n            u = np.linalg.inv(correlationMatrix)\n            u = u[np.ix_(list(range(len(params))), list(range(len(params))))]\n            u = np.linalg.inv(u)\n            n = nparams\n            PCdata = PCdata[:, :nparams]\n        else:\n            u = correlationMatrix\n        evals, evects = np.linalg.eig(u)\n        isorted = evals.argsort()\n        u = np.transpose(evects[:, isorted])  # redefining u\n\n        PCAtext += '\\n'\n        PCAtext += 'e-values of correlation matrix\\n'\n        for i in range(n):\n            isort = isorted[i]\n            PCAtext += 'PC%2i: %8.4f\\n' % (i + 1, evals[isort])\n\n        PCAtext += '\\n'\n        PCAtext += 'e-vectors\\n'\n        for j in range(n):\n            PCAtext += '%3i:' % (indices[j] + 1)\n            for i in range(n):\n                isort = isorted[i]\n                PCAtext += '%8.4f' % (evects[j][isort])\n            PCAtext += '\\n'\n\n        if normparam != -1:\n            # Set so parameter normparam has exponent 1\n            for i in range(n):\n                u[i, :] = u[i, :] / u[i, normparam] * sd[normparam]\n        else:\n            # Normalize so main component has exponent 1\n            for i in range(n):\n                maxi = np.abs(u[i, :]).argmax()\n                u[i, :] = u[i, :] / u[i, maxi] * sd[maxi]\n\n        nrows = PCdata.shape[0]\n        for i in range(nrows):\n            PCdata[i, :] = np.dot(u, PCdata[i, :])\n            if doexp: PCdata[i, :] = np.exp(PCdata[i, :])\n\n        PCAtext += '\\n'\n        PCAtext += 'Principle components\\n'\n        PCAmodeTexts = []\n        for i in range(n):\n            isort = isorted[i]\n            summary = 'PC%i (e-value: %f)\\n' % (i + 1, evals[isort])\n            for j in range(n):\n                label = self.parLabel(indices[j])\n                if param_map[j] in ['L', 'M']:\n                    expo = \"%f\" % (1.0 / sd[j] * u[i][j])\n                    if param_map[j] == \"M\":\n                        div = \"%f\" % (-np.exp(PCmean[j]))\n                    else:\n                        div = \"%f\" % (np.exp(PCmean[j]))\n                    summary += '[%f]  (%s/%s)^{%s}\\n' % (u[i][j], label, div, expo)\n                else:\n                    expo = \"%f\" % (sd[j] / u[i][j])\n                    if doexp:\n                        summary += '[%f]   exp((%s-%f)/%s)\\n' % (u[i][j], label, PCmean[j], expo)\n                    else:\n                        summary += '[%f]   (%s-%f)/%s)\\n' % (u[i][j], label, PCmean[j], expo)\n            newmean[i] = self.mean(PCdata[:, i])\n            newsd[i] = np.sqrt(self.mean((PCdata[:, i] - newmean[i]) ** 2))\n            summary += '          = %f +- %f\\n' % (newmean[i], newsd[i])\n            summary += '\\n'\n            PCAmodeTexts += [summary]\n            PCAtext += summary\n\n        # Find out how correlated these components are with other parameters\n        PCAtext += 'Correlations of principle components\\n'\n        l = [\"%8i\" % i for i in range(1, n + 1)]\n        PCAtext += '%s\\n' % (\"\".join(l))\n\n        for i in range(n):\n            PCdata[:, i] = (PCdata[:, i] - newmean[i]) / newsd[i]\n\n        for j in range(n):\n            PCAtext += 'PC%2i' % (j + 1)\n            for i in range(n):\n                PCAtext += '%8.3f' % (self.mean(PCdata[:, i] * PCdata[:, j]))\n            PCAtext += '\\n'\n\n        for j in range(self.n):\n            PCAtext += '%4i' % (j + 1)\n            for i in range(n):\n                PCAtext += '%8.3f' % (\n                        np.sum(self.weights * PCdata[:, i]\n                               * (self.samples[:, j] - self.means[j]) / self.sddev[j]) / self.norm)\n\n            PCAtext += '   (%s)\\n' % (self.parLabel(j))\n\n        if writeDataToFile:\n            with open(filename or self.rootdirname + \".PCA\", \"w\") as f:\n                f.write(PCAtext)\n        if n_best_only:\n            if n_best_only == 1:\n                return PCAmodeTexts[0]\n            return PCAmodeTexts[:n_best_only]\n        else:\n            return PCAtext\n\n    def getNumSampleSummaryText(self):\n        \"\"\"\n        Returns a summary text describing numbers of parameters and samples,\n        and various measures of the effective numbers of samples.\n\n        :return: The summary text as a string.\n        \"\"\"\n        lines = 'using %s rows, %s parameters; mean weight %s, tot weight %s\\n' % (\n            self.numrows, self.paramNames.numParams(), self.mean_mult, self.norm)\n        if self.indep_thin != 0:\n            lines += 'Approx indep samples (N/corr length): %s\\n' % (round(self.norm / self.indep_thin))\n        lines += 'Equiv number of single samples (sum w)/max(w): %s\\n' % (round(self.norm / self.max_mult))\n        lines += 'Effective number of weighted samples (sum w)^2/sum(w^2): %s\\n' % (\n            int(self.norm ** 2 / np.dot(self.weights, self.weights)))\n        return lines\n\n    def getConvergeTests(self, test_confidence=0.95, writeDataToFile=False,\n                         what=['MeanVar', 'GelmanRubin', 'SplitTest', 'RafteryLewis', 'CorrLengths'],\n                         filename=None, feedback=False):\n        \"\"\"\n        Do convergence tests.\n\n        :param test_confidence: confidence limit to test for convergence (two-tail, only applies to some tests)\n        :param writeDataToFile: True if should write output to a file\n        :param what: The tests to run. Should be a list of any of the following:\n\n            - 'MeanVar': Gelman-Rubin sqrt(var(chain mean)/mean(chain var)) test in individual parameters (multiple chains only)\n            - 'GelmanRubin':  Gelman-Rubin test for the worst orthogonalized parameter (multiple chains only)\n            - 'SplitTest': Crude test for variation in confidence limits when samples are split up into subsets\n            - 'RafteryLewis': `Raftery-Lewis test <http://www.stat.washington.edu/tech.reports/raftery-lewis2.ps>`_ (integer weight samples only)\n            - 'CorrLengths': Sample correlation lengths\n        :param filename: The filename to write to, default is file_root.converge\n        :param feedback: If set to True, Prints the output as well as returning it.\n        :return: text giving the output of the tests\n        \"\"\"\n        lines = ''\n        nparam = self.n\n\n        chainlist = self.getSeparateChains()\n        num_chains_used = len(chainlist)\n        if num_chains_used > 1 and feedback:\n            print('Number of chains used = ', num_chains_used)\n        for chain in chainlist: chain.setDiffs()\n        parForm = self.paramNames.parFormat()\n        parNames = [parForm % self.parName(j) for j in range(nparam)]\n        limits = np.array([1 - (1 - test_confidence) / 2, (1 - test_confidence) / 2])\n\n        if 'CorrLengths' in what:\n            lines += \"Parameter autocorrelation lengths (effective number of samples N_eff = tot weight/weight length)\\n\"\n            lines += \"\\n\"\n            lines += parForm % \"\" + '%15s %15s %15s\\n' % ('Weight Length', 'Sample length', 'N_eff')\n            maxoff = np.min([chain.weights.size // 10 for chain in chainlist])\n            maxN = 0\n            for j in range(nparam):\n                corr = np.zeros(maxoff + 1)\n                for chain in chainlist:\n                    corr += chain.getAutocorrelation(j, maxoff, normalized=False) * chain.norm\n                corr /= self.norm * self.vars[j]\n                ix = np.argmin(corr > 0.05 * corr[0])\n                N = corr[0] + 2 * np.sum(corr[1:ix])\n                maxN = max(N, maxN)\n                form = '%15.2E'\n                if self.mean_mult > 1: form = '%15.2f'\n                lines += parNames[j] + form % N + ' %15.2f %15i\\n' % (N / self.mean_mult, self.norm / N)\n            self.indep_thin = maxN\n            lines += \"\\n\"\n\n        if num_chains_used > 1 and 'MeanVar' in what:\n            lines += \"\\n\"\n            lines += \"mean convergence stats using remaining chains\\n\"\n            lines += \"param sqrt(var(chain mean)/mean(chain var))\\n\"\n            lines += \"\\n\"\n\n            between_chain_var = np.zeros(nparam)\n            in_chain_var = np.zeros(nparam)\n            for chain in chainlist:\n                between_chain_var += (chain.means - self.means) ** 2\n            between_chain_var /= (num_chains_used - 1)\n\n            for j in range(nparam):\n                # Get stats for individual chains - the variance of the means over the mean of the variances\n                for chain in chainlist:\n                    in_chain_var[j] += np.dot(chain.weights, chain.diffs[j] ** 2)\n\n                in_chain_var[j] /= self.norm\n                lines += parNames[j] + \"%10.4f  %s\\n\" % (\n                    math.sqrt(between_chain_var[j] / in_chain_var[j]), self.parLabel(j))\n            lines += \"\\n\"\n\n        nparamMC = self.paramNames.numNonDerived()\n        if num_chains_used > 1 and nparamMC > 0 and 'GelmanRubin' in what:\n\n            D = self.getGelmanRubinEigenvalues(chainlist=chainlist)\n            if D is not None:\n                self.GelmanRubin = np.max(D)\n                lines += \"var(mean)/mean(var) for eigenvalues of covariance of means of orthonormalized parameters\\n\"\n                for jj, Di in enumerate(D):\n                    lines += \"%3i%13.5f\\n\" % (jj + 1, Di)\n                GRSummary = \" var(mean)/mean(var), remaining chains, worst e-value: R-1 = %13.5F\" % self.GelmanRubin\n            else:\n                self.GelmanRubin = None\n                GRSummary = logging.warning('Gelman-Rubin covariance not invertible (parameter not moved?)')\n            if feedback: print(GRSummary)\n            lines += \"\\n\"\n\n        if 'SplitTest' in what:\n            # Do tests for robustness under using splits of the samples\n            # Return the rms ([change in upper/lower quantile]/[standard deviation])\n            # when data split into 2, 3,.. sets\n            lines += \"Split tests: rms_n([delta(upper/lower quantile)]/sd) n={2,3,4}, limit=%.0f%%:\\n\" % (\n                    100 * self.converge_test_limit)\n            lines += \"i.e. mean sample splitting change in the quantiles in units of the st. dev.\\n\"\n            lines += \"\\n\"\n\n            frac_indices = []\n            for i in range(self.max_split_tests - 1):\n                frac_indices.append(self.getFractionIndices(self.weights, i + 2))\n            for j in range(nparam):\n                split_tests = np.zeros((self.max_split_tests - 1, 2))\n                confids = self.confidence(self.samples[:, j], limits)\n                for ix, frac in enumerate(frac_indices):\n                    split_n = 2 + ix\n                    for f1, f2 in zip(frac[:-1], frac[1:]):\n                        split_tests[ix, :] += (self.confidence(self.samples[:, j], limits, start=f1,\n                                                               end=f2) - confids) ** 2\n\n                    split_tests[ix, :] = np.sqrt(split_tests[ix, :] / split_n) / self.sddev[j]\n                for endb, typestr in enumerate(['upper', 'lower']):\n                    lines += parNames[j]\n                    for ix in range(self.max_split_tests - 1):\n                        lines += \"%9.4f\" % (split_tests[ix, endb])\n                    lines += \" %s\\n\" % typestr\n            lines += \"\\n\"\n\n        class LoopException(Exception):\n            pass\n\n        if np.all(np.abs(self.weights - self.weights.astype(np.int)) < 1e-4 / self.max_mult):\n            if 'RafteryLewis' in what:\n                # Raftery and Lewis method\n                # See http://www.stat.washington.edu/tech.reports/raftery-lewis2.ps\n                # Raw non-importance sampled chains only\n                thin_fac = np.empty(num_chains_used, dtype=np.int)\n                epsilon = 0.001\n\n                nburn = np.zeros(num_chains_used, dtype=np.int)\n                markov_thin = np.zeros(num_chains_used, dtype=np.int)\n                hardest = -1\n                hardestend = 0\n                for ix, chain in enumerate(chainlist):\n                    thin_fac[ix] = int(round(np.max(chain.weights)))\n                    try:\n                        for j in range(nparamMC):\n                            # Get binary chain depending on whether above or below confidence value\n                            confids = self.confidence(chain.samples[:, j], limits, weights=chain.weights)\n                            for endb in [0, 1]:\n                                u = confids[endb]\n                                while True:\n                                    thin_ix = self.thin_indices(thin_fac[ix], chain.weights)\n                                    thin_rows = len(thin_ix)\n                                    if thin_rows < 2: break\n                                    binchain = np.ones(thin_rows, dtype=np.int)\n                                    binchain[chain.samples[thin_ix, j] >= u] = 0\n                                    indexes = binchain[:-2] * 4 + binchain[1:-1] * 2 + binchain[2:]\n                                    # Estimate transitions probabilities for 2nd order process\n                                    tran = np.bincount(indexes, minlength=8).reshape((2, 2, 2))\n                                    # tran[:, :, :] = 0\n                                    # for i in range(2, thin_rows):\n                                    #                                        tran[binchain[i - 2]][binchain[i - 1]][binchain[i]] += 1\n\n                                    # Test whether 2nd order is better than Markov using BIC statistic\n                                    g2 = 0\n                                    for i1 in [0, 1]:\n                                        for i2 in [0, 1]:\n                                            for i3 in [0, 1]:\n                                                if tran[i1][i2][i3] != 0:\n                                                    fitted = float(\n                                                        (tran[i1][i2][0] + tran[i1][i2][1]) *\n                                                        (tran[0][i2][i3] + tran[1][i2][i3])) \\\n                                                             / float(tran[0][i2][0] + tran[0][i2][1] +\n                                                                     tran[1][i2][0] + tran[1][i2][1])\n                                                    focus = float(tran[i1][i2][i3])\n                                                    g2 += math.log(focus / fitted) * focus\n                                    g2 *= 2\n\n                                    if g2 - math.log(float(thin_rows - 2)) * 2 < 0: break\n                                    thin_fac[ix] += 1\n\n                                # Get Markov transition probabilities for binary processes\n                                if np.sum(tran[:, 0, 1]) == 0 or np.sum(tran[:, 1, 0]) == 0:\n                                    thin_fac[ix] = 0\n                                    raise LoopException()\n\n                                alpha = np.sum(tran[:, 0, 1]) / float(np.sum(tran[:, 0, 0]) + np.sum(tran[:, 0, 1]))\n                                beta = np.sum(tran[:, 1, 0]) / float(np.sum(tran[:, 1, 0]) + np.sum(tran[:, 1, 1]))\n                                probsum = alpha + beta\n                                tmp1 = math.log(probsum * epsilon / max(alpha, beta)) / math.log(abs(1.0 - probsum))\n                                if int(tmp1 + 1) * thin_fac[ix] > nburn[ix]:\n                                    nburn[ix] = int(tmp1 + 1) * thin_fac[ix]\n                                    hardest = j\n                                    hardestend = endb\n\n                        markov_thin[ix] = thin_fac[ix]\n\n                        # Get thin factor to have independent samples rather than Markov\n                        hardest = max(hardest, 0)\n                        u = self.confidence(self.samples[:, hardest], (1 - test_confidence) / 2, hardestend == 0)\n\n                        while True:\n                            thin_ix = self.thin_indices(thin_fac[ix], chain.weights)\n                            thin_rows = len(thin_ix)\n                            if thin_rows < 2: break\n                            binchain = np.ones(thin_rows, dtype=np.int)\n                            binchain[chain.samples[thin_ix, hardest] >= u] = 0\n                            indexes = binchain[:-1] * 2 + binchain[1:]\n                            # Estimate transitions probabilities for 2nd order process\n                            tran2 = np.bincount(indexes, minlength=4).reshape(2, 2)\n                            # tran2[:, :] = 0\n                            # for i in range(1, thin_rows):\n                            # tran2[binchain[i - 1]][binchain[i]] += 1\n\n                            # Test whether independence is better than Markov using BIC statistic\n                            g2 = 0\n                            for i1 in [0, 1]:\n                                for i2 in [0, 1]:\n                                    if tran2[i1][i2] != 0:\n                                        fitted = float(\n                                            (tran2[i1][0] + tran2[i1][1]) *\n                                            (tran2[0][i2] + tran2[1][i2])) / float(thin_rows - 1)\n                                        focus = float(tran2[i1][i2])\n                                        if fitted <= 0 or focus <= 0:\n                                            print('Raftery and Lewis estimator had problems')\n                                            return\n                                        g2 += np.log(focus / fitted) * focus\n                            g2 *= 2\n\n                            if g2 - np.log(float(thin_rows - 1)) < 0: break\n\n                            thin_fac[ix] += 1\n                    except LoopException:\n                        pass\n                    except:\n                        thin_fac[ix] = 0\n                    if thin_fac[ix] and thin_rows < 2: thin_fac[ix] = 0\n\n                lines += \"Raftery&Lewis statistics\\n\"\n                lines += \"\\n\"\n                lines += \"chain  markov_thin  indep_thin    nburn\\n\"\n\n                for ix in range(num_chains_used):\n                    if thin_fac[ix] == 0:\n                        lines += \"%4i      Failed/not enough samples\\n\" % ix\n                    else:\n                        lines += \"%4i%12i%12i%12i\\n\" % (\n                            ix, markov_thin[ix], thin_fac[ix], nburn[ix])\n\n                self.RL_indep_thin = np.max(thin_fac)\n\n                if feedback:\n                    if not np.all(thin_fac != 0):\n                        print('RL: Not enough samples to estimate convergence stats')\n                    else:\n                        print('RL: Thin for Markov: ', np.max(markov_thin))\n                        print('RL: Thin for indep samples:  ', str(self.RL_indep_thin))\n                        print('RL: Estimated burn in steps: ', np.max(nburn), ' (',\n                              int(round(np.max(nburn) / self.mean_mult)), ' rows)')\n                lines += \"\\n\"\n\n            if 'CorrSteps' in what:\n                # Get correlation lengths. We ignore the fact that there are jumps between chains, so slight underestimate\n                lines += \"Parameter auto-correlations as function of step separation\\n\"\n                lines += \"\\n\"\n                if self.corr_length_thin != 0:\n                    autocorr_thin = self.corr_length_thin\n                else:\n                    if self.indep_thin == 0:\n                        autocorr_thin = 20\n                    elif self.indep_thin <= 30:\n                        autocorr_thin = 5\n                    else:\n                        autocorr_thin = int(5 * (self.indep_thin / 30))\n\n                thin_ix = self.thin_indices(autocorr_thin)\n                thin_rows = len(thin_ix)\n                maxoff = int(min(self.corr_length_steps, thin_rows // (2 * num_chains_used)))\n\n                if maxoff > 0:\n                    if False:\n                        # ignore ends of chains\n                        corrs = np.zeros([maxoff, nparam])\n                        for j in range(nparam):\n                            diff = self.samples[thin_ix, j] - self.means[j]\n                            for off in range(1, maxoff + 1):\n                                corrs[off - 1][j] = np.dot(diff[off:], diff[:-off]) / (thin_rows - off) / self.vars[j]\n                        lines += parForm % \"\"\n                        for i in range(maxoff):\n                            lines += \"%8i\" % ((i + 1) * autocorr_thin)\n                        lines += \"\\n\"\n                        for j in range(nparam):\n                            label = self.parLabel(j)\n                            lines += parNames[j]\n                            for i in range(maxoff):\n                                lines += \"%8.3f\" % corrs[i][j]\n                            lines += \" %s\\n\" % label\n                    else:\n                        corrs = np.zeros([maxoff, nparam])\n                        for chain in chainlist:\n                            thin_ix = chain.thin_indices(autocorr_thin)\n                            thin_rows = len(thin_ix)\n                            maxoff = min(maxoff, thin_rows // autocorr_thin)\n                            for j in range(nparam):\n                                diff = chain.diffs[j][thin_ix]\n                                for off in range(1, maxoff + 1):\n                                    corrs[off - 1][j] += np.dot(diff[off:], diff[:-off]) / (thin_rows - off) / \\\n                                                         self.vars[j]\n                        corrs /= len(chainlist)\n\n                        lines += parForm % \"\"\n                        for i in range(maxoff):\n                            lines += \"%8i\" % ((i + 1) * autocorr_thin)\n                        lines += \"\\n\"\n                        for j in range(nparam):\n                            label = self.parLabel(j)\n                            lines += parNames[j]\n                            for i in range(maxoff):\n                                lines += \"%8.3f\" % corrs[i][j]\n                            lines += \" %s\\n\" % label\n\n        if writeDataToFile:\n            with open(filename or (self.rootdirname + '.converge'), 'w') as f:\n                f.write(lines)\n        return lines\n\n    def _get1DNeff(self, par, param):\n        N_eff = getattr(par, 'N_eff_kde', None)\n        if N_eff is None:\n            par.N_eff_kde = self.getEffectiveSamplesGaussianKDE(param, scale=par.sigma_range)\n            N_eff = par.N_eff_kde\n        return N_eff\n\n    def getAutoBandwidth1D(self, bins, par, param, mult_bias_correction_order=None, kernel_order=1, N_eff=None):\n        \"\"\"\n        Get optimized kernel density bandwidth (in units of the range of the bins)\n        Based on optimal Improved Sheather-Jones bandwidth for basic Parzen kernel, then scaled if higher-order method being used.\n        For details see the `notes <http://cosmologist.info/notes/GetDist.pdf>`_.\n\n        :param bins: numpy array of binned weights for the samples\n        :param par: A :class:`~.paramnames.ParamInfo` instance for the parameter to analyse\n        :param param: index of the parameter to use\n        :param mult_bias_correction_order: order of multiplicative bias correction (0 is basic Parzen kernel); by default taken from instance settings.\n        :param kernel_order: order of the kernel (0 is Parzen, 1 does linear boundary correction, 2 is a higher-order kernel)\n        :param N_eff: effective number of samples. If not specified estimated using weights, autocorrelations, and fiducial bandwidth\n        :return: kernel density bandwidth (in units the range of the bins)\n        \"\"\"\n        if N_eff is None:\n            N_eff = self._get1DNeff(par, param)\n        h = kde.gaussian_kde_bandwidth_binned(bins, Neff=N_eff)\n        bin_range = max(par.param_max, par.range_max) - min(par.param_min, par.range_min)\n        if h is None or h < 0.01 * N_eff ** (-1. / 5) * (par.range_max - par.range_min) / bin_range:\n            hnew = 1.06 * par.sigma_range * N_eff ** (-1. / 5) / bin_range\n            if par.name not in self.no_warning_params \\\n                    and (not self.no_warning_chi2_params or 'chi2_' not in par.name):\n                logging.warning(\n                    'auto bandwidth for %s very small or failed (h=%s,N_eff=%s). Using fallback (h=%s)' % (\n                        par.name, h, N_eff, hnew))\n            h = hnew\n\n        par.kde_h = h\n        m = mult_bias_correction_order\n        if m is None: m = self.mult_bias_correction_order\n        if kernel_order > 1: m = max(m, 1)\n        if m:\n            # higher order method\n            # e.g.  http://biomet.oxfordjournals.org/content/82/2/327.full.pdf+html\n            # some prefactors given in  http://eprints.whiterose.ac.uk/42950/6/taylorcc2%5D.pdf\n            # Here we just take unit prefactor relative to Gaussian\n            # and rescale the optimal h for standard KDE to accounts for higher order scaling\n            # Should be about 1.3 x larger for Gaussian, but smaller in some other cases\n            return h * N_eff ** (1. / 5 - 1. / (4 * m + 5))\n        else:\n            return h\n\n    def getAutoBandwidth2D(self, bins, parx, pary, paramx, paramy, corr, rangex, rangey, base_fine_bins_2D,\n                           mult_bias_correction_order=None, min_corr=0.2, N_eff=None):\n        \"\"\"\n        Get optimized kernel density bandwidth matrix in parameter units, using Improved Sheather Jones method in sheared parameters.\n        For details see the `notes <http://cosmologist.info/notes/GetDist.pdf>`_.\n\n        :param bins: 2D numpy array of binned weights\n        :param parx: A :class:`~.paramnames.ParamInfo` instance for the x parameter\n        :param pary: A :class:`~.paramnames.ParamInfo` instance for the y parameter\n        :param paramx: index of the x parameter\n        :param paramy: index of the y parameter\n        :param corr: correlation of the samples\n        :param rangex: scale in the x parameter\n        :param rangey: scale in the y parameter\n        :param base_fine_bins_2D: number of bins to use for re-binning in rotated parameter space\n        :param mult_bias_correction_order: multiplicative bias correction order (0 is Parzen kernel); by default taken from instance settings\n        :param min_corr: minimum correlation value at which to bother de-correlating the parameters\n        :param N_eff: effective number of samples. If not specified, currently uses crude estimate from effective numbers in x and y separately\n        :return: kernel density bandwidth matrix in parameter units\n        \"\"\"\n        if N_eff is None:\n            N_eff = max(self._get1DNeff(parx, paramx), self._get1DNeff(pary, paramy))  # todo: write _get2DNeff\n        logging.debug('%s %s AutoBandwidth2D: N_eff=%s, corr=%s', parx.name, pary.name, N_eff, corr)\n        has_limits = parx.has_limits or pary.has_limits\n        do_correlated = not parx.has_limits or not pary.has_limits\n\n        def fallback_widths():\n            logging.warning('2D kernel density bandwidth optimizer failed for %s, %s. Using fallback width.' % (\n                parx.name, pary.name))\n            c = max(min(corr, self.max_corr_2D), -self.max_corr_2D)\n            hx = parx.sigma_range / N_eff ** (1. / 6)\n            hy = pary.sigma_range / N_eff ** (1. / 6)\n            return hx, hy, c\n\n        if min_corr < abs(corr) <= self.max_corr_2D and do_correlated:\n            # 'shear' the data so fairly uncorrelated, making sure shear keeps any bounds on one parameter unchanged\n            # the binning step will rescale to make roughly isotropic as assumed by the 2D kernel optimizer psi_{ab} derivatives\n            i, j = paramx, paramy\n            imax, imin = None, None\n            if parx.has_limits_bot:\n                imin = parx.range_min\n            if parx.has_limits_top:\n                imax = parx.range_max\n            if pary.has_limits:\n                i, j = j, i\n                if pary.has_limits_bot:\n                    imin = pary.range_min\n                if pary.has_limits_top:\n                    imax = pary.range_max\n\n            cov = self.getCov(pars=[i, j])\n            S = np.linalg.cholesky(cov)\n            ichol = np.linalg.inv(S)\n            S *= ichol[0, 0]\n            r = ichol[1, :] / ichol[0, 0]\n            p1 = self.samples[:, i]\n            p2 = r[0] * self.samples[:, i] + r[1] * self.samples[:, j]\n\n            bin1, R1 = kde.bin_samples(p1, nbins=base_fine_bins_2D, range_min=imin, range_max=imax)\n            bin2, R2 = kde.bin_samples(p2, nbins=base_fine_bins_2D)\n            rotbins, _ = self._make2Dhist(bin1, bin2, base_fine_bins_2D, base_fine_bins_2D)\n            try:\n                opt = kde.KernelOptimizer2D(rotbins, N_eff, 0, do_correlation=not has_limits)\n                hx, hy, c = opt.get_h()\n                hx *= R1\n                hy *= R2\n                kernelC = S.dot(np.array([[hx ** 2, hx * hy * c], [hx * hy * c, hy ** 2]])).dot(S.T)\n                hx, hy, c = np.sqrt(kernelC[0, 0]), np.sqrt(kernelC[1, 1]), kernelC[0, 1] / np.sqrt(\n                    kernelC[0, 0] * kernelC[1, 1])\n                if pary.has_limits:\n                    hx, hy = hy, hx\n                    # print 'derotated pars', hx, hy, c\n            except ValueError:\n                hx, hy, c = fallback_widths()\n        elif abs(corr) > self.max_corr_2D or not do_correlated and corr > 0.8:\n            c = max(min(corr, self.max_corr_2D), -self.max_corr_2D)\n            hx = parx.sigma_range / N_eff ** (1. / 6)\n            hy = pary.sigma_range / N_eff ** (1. / 6)\n        else:\n            try:\n                opt = kde.KernelOptimizer2D(bins, N_eff, corr, do_correlation=not has_limits)\n                hx, hy, c = opt.get_h()\n                hx *= rangex\n                hy *= rangey\n            except ValueError:\n                hx, hy, c = fallback_widths()\n\n        if mult_bias_correction_order is None: mult_bias_correction_order = self.mult_bias_correction_order\n        logging.debug('hx/sig, hy/sig, corr =%s, %s, %s', hx / parx.err, hy / pary.err, c)\n        if mult_bias_correction_order:\n            scale = 1.1 * N_eff ** (1. / 6 - 1. / (2 + 4 * (1 + mult_bias_correction_order)))\n            hx *= scale\n            hy *= scale\n            logging.debug('hx/sig, hy/sig, corr, scale =%s, %s, %s, %s', hx / parx.err, hy / pary.err, c, scale)\n        return hx, hy, c\n\n    def _initParamRanges(self, j, paramConfid=None):\n        if isinstance(j, six.string_types): j = self.index[j]\n        paramVec = self.samples[:, j]\n        return self._initParam(self.paramNames.names[j], paramVec, self.means[j], self.sddev[j], paramConfid)\n\n    def _initParam(self, par, paramVec, mean=None, sddev=None, paramConfid=None):\n        if mean is None: mean = paramVec.mean()\n        if sddev is None: sddev = paramVec.std()\n        par.err = sddev\n        par.mean = mean\n        par.param_min = np.min(paramVec)\n        par.param_max = np.max(paramVec)\n        paramConfid = paramConfid or self.initParamConfidenceData(paramVec)\n        # sigma_range is estimate related to shape of structure in the distribution = std dev for Gaussian\n        # search for peaks using quantiles, e.g. like simplified version of Janssen 95 (http://dx.doi.org/10.1080/10485259508832654)\n        confid_points = np.linspace(0.1, 0.9, 9)\n        confids = self.confidence(paramConfid,\n                                  np.array([self.range_confidence, 1 - self.range_confidence] + list(confid_points)))\n        par.range_min, par.range_max = confids[0:2]\n        confids[1:-1] = confids[2:]\n        confids[0] = par.param_min\n        confids[-1] = par.param_max\n        diffs = confids[4:] - confids[:-4]\n        scale = np.min(diffs) / 1.049\n        if np.all(diffs > par.err * 1.049) and np.all(diffs < scale * 1.5):\n            # very flat, can use bigger\n            par.sigma_range = scale\n        else:\n            par.sigma_range = min(par.err, scale)\n        if self.range_ND_contour >= 0 and self.likeStats:\n            if self.range_ND_contour >= par.ND_limit_bot.size:\n                raise SettingError(\"range_ND_contour should be -1 (off), or 0, 1 for first or second contour level\")\n            par.range_min = min(max(par.range_min - par.err, par.ND_limit_bot[self.range_ND_contour]), par.range_min)\n            par.range_max = max(max(par.range_max + par.err, par.ND_limit_top[self.range_ND_contour]), par.range_max)\n\n        smooth_1D = par.sigma_range * 0.4\n\n        if par.has_limits_bot:\n            if par.range_min - par.limmin > 2 * smooth_1D and par.param_min - par.limmin > smooth_1D:\n                # long way from limit\n                par.has_limits_bot = False\n            else:\n                par.range_min = par.limmin\n\n        if par.has_limits_top:\n            if par.limmax - par.range_max > 2 * smooth_1D and par.limmax - par.param_max > smooth_1D:\n                par.has_limits_top = False\n            else:\n                par.range_max = par.limmax\n\n        if not par.has_limits_bot:\n            par.range_min -= smooth_1D * 2\n\n        if not par.has_limits_top:\n            par.range_max += smooth_1D * 2\n\n        par.has_limits = par.has_limits_top or par.has_limits_bot\n\n        return par\n\n    def _binSamples(self, paramVec, par, num_fine_bins, borderfrac=0.1):\n\n        # High resolution density (sampled many times per smoothing scale). First and last bins are half width\n\n        border = (par.range_max - par.range_min) * borderfrac\n        binmin = min(par.param_min, par.range_min)\n        if not par.has_limits_bot:\n            binmin -= border\n        binmax = max(par.param_max, par.range_max)\n        if not par.has_limits_top:\n            binmax += border\n        fine_width = (binmax - binmin) / (num_fine_bins - 1)\n        ix = ((paramVec - binmin) / fine_width + 0.5).astype(np.int)\n        return ix, fine_width, binmin, binmax\n\n    def get1DDensity(self, name, **kwargs):\n        \"\"\"\n        Returns a :class:`~.densities.Density1D` instance for parameter with given name. Result is cached.\n\n        :param name: name of the parameter\n        :param kwargs: arguments for :func:`~MCSamples.get1DDensityGridData`\n        :return: A :class:`~.densities.Density1D` instance for parameter with given name\n        \"\"\"\n        if self.needs_update: self.updateBaseStatistics()\n        if not kwargs:\n            density = self.density1D.get(name, None)\n            if density is not None: return density\n        return self.get1DDensityGridData(name, get_density=True, **kwargs)\n\n    def get1DDensityGridData(self, j, writeDataToFile=False, get_density=False, paramConfid=None, meanlikes=False,\n                             **kwargs):\n        \"\"\"\n        Low-level function to get a :class:`~.densities.Density1D` instance for the marginalized 1D density of a parameter. Result is not cached.\n\n        :param j: a name or index of the parameter\n        :param writeDataToFile: True if should write to text file.\n        :param get_density: return a :class:`~.densities.Density1D` instance only, does not write out or calculate mean likelihoods for plots\n        :param paramConfid: optional cached :class:`ParamConfidenceData` instance\n        :param meanlikes: include mean likelihoods\n        :param kwargs: optional settings to override instance settings of the same name (see `analysis_settings`):\n\n               - **smooth_scale_1D**\n               - **boundary_correction_order**\n               - **mult_bias_correction_order**\n               - **fine_bins**\n               - **num_bins**\n        :return: A :class:`~.densities.Density1D` instance\n        \"\"\"\n\n        if self.needs_update: self.updateBaseStatistics()\n        j = self._parAndNumber(j)[0]\n        if j is None: return None\n\n        par = self._initParamRanges(j, paramConfid)\n        num_bins = kwargs.get('num_bins', self.num_bins)\n        smooth_scale_1D = kwargs.get('smooth_scale_1D', self.smooth_scale_1D)\n        boundary_correction_order = kwargs.get('boundary_correction_order', self.boundary_correction_order)\n        mult_bias_correction_order = kwargs.get('mult_bias_correction_order', self.mult_bias_correction_order)\n        fine_bins = kwargs.get('fine_bins', self.fine_bins)\n\n        paramrange = par.range_max - par.range_min\n        if paramrange <= 0: raise MCSamplesError('Parameter range is <= 0: ' + par.name)\n        width = paramrange / (num_bins - 1)\n\n        bin_indices, fine_width, binmin, binmax = self._binSamples(self.samples[:, j], par, fine_bins)\n        bins = np.bincount(bin_indices, weights=self.weights, minlength=fine_bins)\n\n        if meanlikes:\n            if self.shade_likes_is_mean_loglikes:\n                w = self.weights * self.loglikes\n            else:\n                w = self.weights * np.exp((self.mean_loglike - self.loglikes))\n            finebinlikes = np.bincount(bin_indices, weights=w, minlength=fine_bins)\n\n        if smooth_scale_1D <= 0:\n            # Set automatically.\n            smooth_1D = self.getAutoBandwidth1D(bins, par, j, mult_bias_correction_order, boundary_correction_order) \\\n                        * (binmax - binmin) * abs(smooth_scale_1D) / fine_width\n\n        elif smooth_scale_1D < 1.0:\n            smooth_1D = smooth_scale_1D * par.err / fine_width\n        else:\n            smooth_1D = smooth_scale_1D * width / fine_width\n\n        if smooth_1D < 2:\n            logging.warning('fine_bins not large enough to well sample smoothing scale - ' + par.name)\n\n        smooth_1D = min(max(1., smooth_1D), fine_bins // 2)\n\n        logging.debug(\"%s 1D sigma_range, std: %s, %s; smooth_1D_bins: %s \", par.name, par.sigma_range, par.err,\n                      smooth_1D)\n\n        winw = min(int(round(2.5 * smooth_1D)), fine_bins // 2 - 2)\n        Kernel = Kernel1D(winw, smooth_1D)\n\n        cache = {}\n        conv = convolve1D(bins, Kernel.Win, 'same', cache=cache)\n        fine_x = np.linspace(binmin, binmax, fine_bins)\n        density1D = Density1D(fine_x, P=conv, view_ranges=[par.range_min, par.range_max])\n\n        if meanlikes: rawbins = conv.copy()\n\n        if par.has_limits and boundary_correction_order >= 0:\n            # correct for cuts allowing for normalization over window\n            prior_mask = np.ones(fine_bins + 2 * winw)\n            if par.has_limits_bot:\n                prior_mask[winw] = 0.5\n                prior_mask[: winw] = 0\n            if par.has_limits_top:\n                prior_mask[-(winw + 1)] = 0.5\n                prior_mask[-winw:] = 0\n            a0 = convolve1D(prior_mask, Kernel.Win, 'valid', cache=cache)\n            ix = np.nonzero(a0 * density1D.P)\n            a0 = a0[ix]\n            normed = density1D.P[ix] / a0\n            if boundary_correction_order == 0:\n                density1D.P[ix] = normed\n            elif boundary_correction_order <= 2:\n                # linear boundary kernel, e.g. Jones 1993, Jones and Foster 1996\n                # www3.stat.sinica.edu.tw/statistica/oldpdf/A6n414.pdf after Eq 1b, expressed for general prior mask\n                # cf arXiv:1411.5528\n                xWin = Kernel.Win * Kernel.x\n                a1 = convolve1D(prior_mask, xWin, 'valid', cache=cache)[ix]\n                a2 = convolve1D(prior_mask, xWin * Kernel.x, 'valid', cache=cache, cache_args=[1])[ix]\n                xP = convolve1D(bins, xWin, 'same', cache=cache)[ix]\n                if boundary_correction_order == 1:\n                    corrected = (density1D.P[ix] * a2 - xP * a1) / (a0 * a2 - a1 ** 2)\n                else:\n                    # quadratic correction\n                    a3 = convolve1D(prior_mask, xWin * Kernel.x ** 2, 'valid', cache=cache, cache_args=[1])[ix]\n                    a4 = convolve1D(prior_mask, xWin * Kernel.x ** 3, 'valid', cache=cache, cache_args=[1])[ix]\n                    x2P = convolve1D(bins, xWin * Kernel.x, 'same', cache=cache, cache_args=[1])[ix]\n                    denom = a4 * a2 * a0 - a4 * a1 ** 2 - a2 ** 3 - a3 ** 2 * a0 + 2 * a1 * a2 * a3\n                    A = a4 * a2 - a3 ** 2\n                    B = a2 * a3 - a4 * a1\n                    C = a3 * a1 - a2 ** 2\n                    corrected = (density1D.P[ix] * A + xP * B + x2P * C) / denom\n                density1D.P[ix] = normed * np.exp(np.minimum(corrected / normed, 4) - 1)\n            else:\n                raise SettingError('Unknown boundary_correction_order (expected 0, 1, 2)')\n        elif boundary_correction_order == 2:\n            # higher order kernel\n            # eg. see http://www.jstor.org/stable/2965571\n            xWin2 = Kernel.Win * Kernel.x ** 2\n            x2P = convolve1D(bins, xWin2, 'same', cache=cache)\n            a2 = np.sum(xWin2)\n            a4 = np.dot(xWin2, Kernel.x ** 2)\n            corrected = (density1D.P * a4 - a2 * x2P) / (a4 - a2 ** 2)\n            ix = density1D.P > 0\n            density1D.P[ix] *= np.exp(np.minimum(corrected[ix] / density1D.P[ix], 2) - 1)\n\n        if mult_bias_correction_order:\n            prior_mask = np.ones(fine_bins)\n            if par.has_limits_bot:\n                prior_mask[0] *= 0.5\n            if par.has_limits_top:\n                prior_mask[-1] *= 0.5\n            a0 = convolve1D(prior_mask, Kernel.Win, 'same', cache=cache, cache_args=[2])\n            for _ in range(mult_bias_correction_order):\n                # estimate using flattened samples to remove second order biases\n                # mostly good performance, see http://www.jstor.org/stable/2965571 method 3,1 for first order\n                prob1 = density1D.P.copy()\n                prob1[prob1 == 0] = 1\n                fine = bins / prob1\n                conv = convolve1D(fine, Kernel.Win, 'same', cache=cache, cache_args=[2])\n                density1D.setP(density1D.P * conv)\n                density1D.P /= a0\n\n        density1D.normalize('max', in_place=True)\n        if not kwargs: self.density1D[par.name] = density1D\n\n        if get_density: return density1D\n\n        if meanlikes:\n            ix = density1D.P > 0\n            finebinlikes[ix] /= density1D.P[ix]\n            binlikes = convolve1D(finebinlikes, Kernel.Win, 'same', cache=cache, cache_args=[2])\n            binlikes[ix] *= density1D.P[ix] / rawbins[ix]\n            if self.shade_likes_is_mean_loglikes:\n                maxbin = np.min(binlikes)\n                binlikes = np.where((binlikes - maxbin) < 30, np.exp(-(binlikes - maxbin)), 0)\n                binlikes[rawbins == 0] = 0\n            binlikes /= np.max(binlikes)\n            density1D.likes = binlikes\n        else:\n            density1D.likes = None\n\n        if writeDataToFile:\n            # get thinner grid over restricted range for plotting\n            x = par.range_min + np.arange(num_bins) * width\n            bincounts = density1D.Prob(x)\n\n            if meanlikes:\n                likeDensity = Density1D(fine_x, P=binlikes)\n                likes = likeDensity.Prob(x)\n            else:\n                likes = None\n\n            fname = self.rootname + \"_p_\" + par.name\n            filename = os.path.join(self.plot_data_dir, fname + \".dat\")\n            with open(filename, 'w') as f:\n                for xval, binval in zip(x, bincounts):\n                    f.write(\"%16.7E%16.7E\\n\" % (xval, binval))\n\n            if meanlikes:\n                filename_like = os.path.join(self.plot_data_dir, fname + \".likes\")\n                with open(filename_like, 'w') as f:\n                    for xval, binval in zip(x, likes):\n                        f.write(\"%16.7E%16.7E\\n\" % (xval, binval))\n\n            density = Density1D(x, bincounts)\n            density.likes = likes\n            return density\n        else:\n            return density1D\n\n    def _setEdgeMask2D(self, parx, pary, prior_mask, winw, alledge=False):\n        if parx.has_limits_bot:\n            prior_mask[:, winw] /= 2\n            prior_mask[:, :winw] = 0\n        if parx.has_limits_top:\n            prior_mask[:, -(winw + 1)] /= 2\n            prior_mask[:, -winw:] = 0\n        if pary.has_limits_bot:\n            prior_mask[winw, :] /= 2\n            prior_mask[:winw:] = 0\n        if pary.has_limits_top:\n            prior_mask[-(winw + 1), :] /= 2\n            prior_mask[-winw:, :] = 0\n        if alledge:\n            prior_mask[:, :winw] = 0\n            prior_mask[:, -winw:] = 0\n            prior_mask[:winw:] = 0\n            prior_mask[-winw:, :] = 0\n\n    def _getScaleForParam(self, par):\n        # Also ensures that the 1D limits are initialized\n        density = self.get1DDensity(par)\n        mn, mx, lim_bot, lim_top = density.getLimits(0.5, accuracy_factor=1)\n        if lim_bot or lim_top:\n            scale = (mx - mn) / 0.675\n        else:\n            scale = (mx - mn) / (2 * 0.675)\n        return scale\n\n    def _parAndNumber(self, name):\n        if isinstance(name, ParamInfo): name = name.name\n        if isinstance(name, six.string_types):\n            name = self.index.get(name, None)\n            if name is None: return None, None\n        if isinstance(name, six.integer_types):\n            return name, self.paramNames.names[name]\n        raise ParamError(\"Unknown parameter type %s\" % name)\n\n    def _make2Dhist(self, ixs, iys, xsize, ysize):\n        flatix = ixs + iys * xsize\n        # note arrays are indexed y,x\n\n        return np.bincount(flatix, weights=self.weights,\n                           minlength=xsize * ysize).reshape((ysize, xsize)), flatix\n\n    def get2DDensity(self, x, y, normalized=False, **kwargs):\n        \"\"\"\n        Returns a :class:`~.densities.Density2D` instance with marginalized 2D density.\n\n        :param x: index or name of x parameter\n        :param y: index or name of y parameter\n        :param kwargs: keyword arguments for the :func:`get2DDensityGridData` function\n        :param normalized: if False, is normalized so the maximum is 1, if True, density is normalized\n        :return: :class:`~.densities.Density2D` instance\n        \"\"\"\n        if self.needs_update: self.updateBaseStatistics()\n        density = self.get2DDensityGridData(x, y, get_density=True, **kwargs)\n        if normalized:\n            density.normalize(in_place=True)\n        return density\n\n    def get2DDensityGridData(self, j, j2, writeDataToFile=False,\n                             num_plot_contours=None, get_density=False, meanlikes=False, **kwargs):\n        \"\"\"\n        Low-level function to get 2D plot marginalized density and optional additional plot data.\n\n        :param j: name or index of the x parameter\n        :param j2: name or index of the y parameter.\n        :param writeDataToFile: True if should write data to file\n        :param num_plot_contours: number of contours to calculate and return in density.contours\n        :param get_density: only get the 2D marginalized density, no additional plot data\n        :param meanlikes: calculate mean likelihoods as well as marginalized density (returned as array in density.likes)\n        :param kwargs: optional settings to override instance settings of the same name (see `analysis_settings`):\n\n            - **fine_bins_2D**\n            - **boundary_correction_order**\n            - **mult_bias_correction_order**\n            - **smooth_scale_2D**\n        :return: a :class:`~.densities.Density2D` instance\n        \"\"\"\n        if self.needs_update: self.updateBaseStatistics()\n        start = time.time()\n        j, parx = self._parAndNumber(j)\n        j2, pary = self._parAndNumber(j2)\n        if j is None or j2 is None: return None\n\n        self._initParamRanges(j)\n        self._initParamRanges(j2)\n\n        base_fine_bins_2D = kwargs.get('fine_bins_2D', self.fine_bins_2D)\n        boundary_correction_order = kwargs.get('boundary_correction_order', self.boundary_correction_order)\n        mult_bias_correction_order = kwargs.get('mult_bias_correction_order', self.mult_bias_correction_order)\n        smooth_scale_2D = float(kwargs.get('smooth_scale_2D', self.smooth_scale_2D))\n\n        has_prior = parx.has_limits or pary.has_limits\n\n        corr = self.getCorrelationMatrix()[j2][j]\n        if corr == 1: logging.warning('Parameters are 100%% correlated: %s, %s', parx.name, pary.name)\n\n        logging.debug('Doing 2D: %s - %s', parx.name, pary.name)\n        logging.debug('sample x_err, y_err, correlation: %s, %s, %s', parx.err, pary.err, corr)\n\n        # keep things simple unless obvious degeneracy\n        if abs(self.max_corr_2D) > 1: raise SettingError('max_corr_2D cannot be >=1')\n        if abs(corr) < 0.1: corr = 0.\n\n        # for tight degeneracies increase bin density\n        angle_scale = max(0.2, np.sqrt(1 - min(self.max_corr_2D, abs(corr)) ** 2))\n\n        nbin2D = int(round(self.num_bins_2D / angle_scale))\n        fine_bins_2D = base_fine_bins_2D\n        if corr:\n            scaled = 192 * int(3 / angle_scale) // 3\n            if base_fine_bins_2D < scaled and int(1 / angle_scale) > 1:\n                fine_bins_2D = scaled\n\n        ixs, finewidthx, xbinmin, xbinmax = self._binSamples(self.samples[:, j], parx, fine_bins_2D)\n        iys, finewidthy, ybinmin, ybinmax = self._binSamples(self.samples[:, j2], pary, fine_bins_2D)\n\n        xsize = fine_bins_2D\n        ysize = fine_bins_2D\n\n        histbins, flatix = self._make2Dhist(ixs, iys, xsize, ysize)\n\n        if meanlikes:\n            likeweights = self.weights * np.exp(self.mean_loglike - self.loglikes)\n            finebinlikes = np.bincount(flatix, weights=likeweights,\n                                       minlength=xsize * ysize).reshape((ysize, xsize))\n\n        # smooth_x and smooth_y should be in rotated bin units\n        if smooth_scale_2D < 0:\n\n            rx, ry, corr = self.getAutoBandwidth2D(histbins, parx, pary, j, j2, corr, xbinmax - xbinmin,\n                                                   ybinmax - ybinmin,\n                                                   base_fine_bins_2D,\n                                                   mult_bias_correction_order=mult_bias_correction_order)\n\n            rx = rx * abs(smooth_scale_2D) / finewidthx\n            ry = ry * abs(smooth_scale_2D) / finewidthy\n        elif smooth_scale_2D < 1.0:\n            rx = smooth_scale_2D * parx.err / finewidthx\n            ry = smooth_scale_2D * pary.err / finewidthy\n        else:\n            rx = smooth_scale_2D * fine_bins_2D / nbin2D\n            ry = smooth_scale_2D * fine_bins_2D / nbin2D\n\n        smooth_scale = float(max(rx, ry))\n        logging.debug('corr, rx, ry: %s, %s, %s', corr, rx, ry)\n\n        if smooth_scale < 2:\n            logging.warning('fine_bins_2D not large enough for optimal density')\n\n        winw = int(round(2.5 * smooth_scale))\n\n        Cinv = np.linalg.inv(np.array([[ry ** 2, rx * ry * corr], [rx * ry * corr, rx ** 2]]))\n        ix1, ix2 = np.mgrid[-winw:winw + 1, -winw:winw + 1]\n        Win = np.exp(-(ix1 ** 2 * Cinv[0, 0] + ix2 ** 2 * Cinv[1, 1] + 2 * Cinv[1, 0] * ix1 * ix2) / 2)\n        Win /= np.sum(Win)\n\n        logging.debug('time 2D binning and bandwidth: %s ; bins: %s', time.time() - start, fine_bins_2D)\n        start = time.time()\n        cache = {}\n        convolvesize = xsize + 2 * winw + Win.shape[0]\n        bins2D = convolve2D(histbins, Win, 'same', largest_size=convolvesize, cache=cache)\n\n        if meanlikes:\n            bin2Dlikes = convolve2D(finebinlikes, Win, 'same', largest_size=convolvesize, cache=cache, cache_args=[2])\n            if mult_bias_correction_order:\n                ix = bin2Dlikes > 0\n                finebinlikes[ix] /= bin2Dlikes[ix]\n                likes2 = convolve2D(finebinlikes, Win, 'same', largest_size=convolvesize, cache=cache, cache_args=[2])\n                likes2[ix] *= bin2Dlikes[ix]\n                bin2Dlikes = likes2\n            del finebinlikes\n            mx = 1e-4 * np.max(bins2D)\n            bin2Dlikes[bins2D > mx] /= bins2D[bins2D > mx]\n            bin2Dlikes[bins2D <= mx] = 0\n        else:\n            bin2Dlikes = None\n\n        if has_prior and boundary_correction_order >= 0:\n            # Correct for edge effects\n            prior_mask = np.ones((ysize + 2 * winw, xsize + 2 * winw))\n            self._setEdgeMask2D(parx, pary, prior_mask, winw)\n            a00 = convolve2D(prior_mask, Win, 'valid', largest_size=convolvesize, cache=cache)\n            ix = a00 * bins2D > np.max(bins2D) * 1e-8\n            a00 = a00[ix]\n            normed = bins2D[ix] / a00\n            if boundary_correction_order == 1:\n                # linear boundary correction\n                indexes = np.arange(-winw, winw + 1)\n                y = np.empty(Win.shape)\n                for i in range(Win.shape[0]):\n                    y[:, i] = indexes\n                winx = Win * indexes\n                winy = Win * y\n                a10 = convolve2D(prior_mask, winx, 'valid', largest_size=convolvesize, cache=cache)[ix]\n                a01 = convolve2D(prior_mask, winy, 'valid', largest_size=convolvesize, cache=cache)[ix]\n                a20 = \\\n                    convolve2D(prior_mask, winx * indexes, 'valid', largest_size=convolvesize, cache=cache,\n                               cache_args=[1])[\n                        ix]\n                a02 = convolve2D(prior_mask, winy * y, 'valid', largest_size=convolvesize, cache=cache, cache_args=[1])[\n                    ix]\n                a11 = \\\n                    convolve2D(prior_mask, winy * indexes, 'valid', largest_size=convolvesize, cache=cache,\n                               cache_args=[1])[\n                        ix]\n                xP = convolve2D(histbins, winx, 'same', largest_size=convolvesize, cache=cache)[ix]\n                yP = convolve2D(histbins, winy, 'same', largest_size=convolvesize, cache=cache)[ix]\n                denom = (a20 * a01 ** 2 + a10 ** 2 * a02 - a00 * a02 * a20 + a11 ** 2 * a00 - 2 * a01 * a10 * a11)\n                A = a11 ** 2 - a02 * a20\n                Ax = a10 * a02 - a01 * a11\n                Ay = a01 * a20 - a10 * a11\n                corrected = (bins2D[ix] * A + xP * Ax + yP * Ay) / denom\n                bins2D[ix] = normed * np.exp(np.minimum(corrected / normed, 4) - 1)\n            elif boundary_correction_order == 0:\n                # simple boundary correction by normalization\n                bins2D[ix] = normed\n            else:\n                raise SettingError('unknown boundary_correction_order (expected 0 or 1)')\n\n        if mult_bias_correction_order:\n            prior_mask = np.ones((ysize + 2 * winw, xsize + 2 * winw))\n            self._setEdgeMask2D(parx, pary, prior_mask, winw, alledge=True)\n            a00 = convolve2D(prior_mask, Win, 'valid', largest_size=convolvesize, cache=cache, cache_args=[2])\n            for _ in range(mult_bias_correction_order):\n                box = histbins.copy()\n                ix2 = bins2D > np.max(bins2D) * 1e-8\n                box[ix2] /= bins2D[ix2]\n                bins2D *= convolve2D(box, Win, 'same', largest_size=convolvesize, cache=cache, cache_args=[2])\n                bins2D /= a00\n\n        x = np.linspace(xbinmin, xbinmax, xsize)\n        y = np.linspace(ybinmin, ybinmax, ysize)\n        density = Density2D(x, y, bins2D,\n                            view_ranges=[(parx.range_min, parx.range_max), (pary.range_min, pary.range_max)])\n        density.normalize('max', in_place=True)\n        if get_density: return density\n\n        ncontours = len(self.contours)\n        if num_plot_contours: ncontours = min(num_plot_contours, ncontours)\n        contours = self.contours[:ncontours]\n\n        logging.debug('time 2D convolutions: %s', time.time() - start)\n\n        # Get contour containing contours(:) of the probability\n        density.contours = density.getContourLevels(contours)\n\n        # now make smaller num_bins grid between ranges for plotting\n        # x = parx.range_min + np.arange(nbin2D + 1) * widthx\n        # y = pary.range_min + np.arange(nbin2D + 1) * widthy\n        # bins2D = density.Prob(x, y)\n        # bins2D[bins2D < 1e-30] = 0\n\n        if meanlikes:\n            bin2Dlikes /= np.max(bin2Dlikes)\n            density.likes = bin2Dlikes\n        else:\n            density.likes = None\n\n        if writeDataToFile:\n            # note store things in confusing transpose form\n            # if meanlikes:\n            # filedensity = Density2D(x, y, bin2Dlikes)\n            #                bin2Dlikes = filedensity.Prob(x, y)\n\n            plotfile = self.rootname + \"_2D_%s_%s\" % (parx.name, pary.name)\n            filename = os.path.join(self.plot_data_dir, plotfile)\n            np.savetxt(filename, bins2D.T, \"%16.7E\")\n            np.savetxt(filename + \"_y\", x, \"%16.7E\")\n            np.savetxt(filename + \"_x\", y, \"%16.7E\")\n            np.savetxt(filename + \"_cont\", np.atleast_2d(density.contours), \"%16.7E\")\n            if meanlikes:\n                np.savetxt(filename + \"_likes\", bin2Dlikes.T, \"%16.7E\")\n                #       res = Density2D(x, y, bins2D)\n                #       res.contours = density.contours\n                #       res.likes = bin2Dlikes\n        return density\n\n    def _setRawEdgeMaskND(self, parv, prior_mask):\n        ndim = len(parv)\n        vrap = parv[::-1]\n        mskShape = prior_mask.shape\n\n        if len(mskShape) != ndim:\n            raise ValueError(\"parv and prior_mask or different sizes!\")\n\n        # create a slice object iterating over everything\n        mskSlices = [slice(None) for _ in range(ndim)]\n\n        for i in range(ndim):\n            if vrap[i].has_limits_bot:\n                mskSlices[i] = 0\n                prior_mask[mskSlices] /= 2\n                mskSlices[i] = slice(None)\n\n            if vrap[i].has_limits_top:\n                mskSlices[i] = mskShape[i] - 1\n                prior_mask[mskSlices] /= 2\n                mskSlices[i] = slice(None)\n\n    def _flattenValues(self, ixs, xsizes):\n        ndim = len(ixs)\n\n        q = ixs[0]\n        for i in range(1, ndim):\n            q = q + np.prod(xsizes[0:i]) * ixs[i]\n        return q\n\n    def _unflattenValues(self, q, xsizes):\n        ndim = len(xsizes)\n\n        ixs = list([np.array(q) for _ in range(ndim)])\n\n        if ndim == 1:\n            ixs[0] = q\n            return ixs\n\n        ixs[ndim - 1] = q / np.prod(xsizes[0:ndim - 1])\n\n        acc = 0\n        for k in range(ndim - 2, -1, -1):\n            acc = acc + ixs[k + 1] * np.prod(xsizes[0:k + 1])\n            if k > 0:\n                ixs[k] = (q - acc) / np.prod(xsizes[0:k])\n            else:\n                ixs[k] = q - acc\n\n        return ixs\n\n    def _makeNDhist(self, ixs, xsizes):\n\n        if len(ixs) != len(xsizes):\n            raise ValueError('index and size arrays are of unequal length')\n\n        flatixv = self._flattenValues(ixs, xsizes)\n\n        # to be removed debugging only\n        if np.count_nonzero(np.asarray(ixs) - self._unflattenValues(flatixv, xsizes)) != 0:\n            raise ValueError('ARG!!! flatten/unflatten screwed')\n\n        # note arrays are indexed y,x\n        return np.bincount(flatixv, weights=self.weights,\n                           minlength=np.prod(xsizes)).reshape(xsizes[::-1], order='C'), flatixv\n\n    def getRawNDDensity(self, xs, normalized=False, **kwargs):\n        \"\"\"\n        Returns a :class:`~.densities.DensityND` instance with marginalized ND density.\n\n        :param xs: indices or names of x_i parameters\n        :param kwargs: keyword arguments for the :func:`getNDDensityGridData` function\n        :param normalized: if False, is normalized so the maximum is 1, if True, density is normalized\n        :return: :class:`~.densities.DensityND` instance\n        \"\"\"\n        if self.needs_update: self.updateBaseStatistics()\n        density = self.getRawNDDensityGridData(xs, get_density=True, **kwargs)\n        if normalized:\n            density.normalize(in_place=True)\n        return density\n\n    def getRawNDDensityGridData(self, js, writeDataToFile=False,\n                                num_plot_contours=None, get_density=False,\n                                meanlikes=False, maxlikes=False, **kwargs):\n        \"\"\"\n        Low-level function to get unsmooth ND plot marginalized\n        density and optional additional plot data.\n\n        :param js: vector of names or indices of the x_i parameters\n        :param writeDataToFile: True if should write data to file\n        :param num_plot_contours: number of contours to calculate and return in density.contours\n        :param get_density: only get the ND marginalized density, no additional plot data, no contours.\n        :param meanlikes: calculate mean likelihoods as well as marginalized density (returned as array in density.likes)\n        :param maxlikes: calculate the profile likelihoods in addition to the others (returned as array in density.maxlikes)\n        :param kwargs: optional settings to override instance settings of the same name (see `analysis_settings`):\n\n        :return: a :class:`~.densities.DensityND` instance\n        \"\"\"\n\n        if self.needs_update: self.updateBaseStatistics()\n\n        ndim = len(js)\n\n        jv, parv = zip(*[self._parAndNumber(j) for j in js])\n\n        if None in jv: return None\n\n        [self._initParamRanges(j) for j in jv]\n\n        boundary_correction_order = kwargs.get('boundary_correction_order', self.boundary_correction_order)\n        has_prior = np.any([parv[i].has_limits for i in range(ndim)])\n\n        nbinsND = kwargs.get('num_bins_ND', self.num_bins_ND)\n        ixv, widthv, xminv, xmaxv = zip(*[self._binSamples(self.samples[:, jv[i]],\n                                                           parv[i], nbinsND) for i in range(ndim)])\n\n        # could also be non-equals over the dimensions\n        xsizev = nbinsND * np.ones(ndim, dtype=np.int)\n\n        binsND, flatixv = self._makeNDhist(ixv, xsizev)\n\n        if has_prior and boundary_correction_order >= 0:\n            # Correct for edge effects\n            prior_mask = np.ones(xsizev[::-1])\n            self._setRawEdgeMaskND(parv, prior_mask)\n            binsND /= prior_mask\n\n        if meanlikes:\n            likeweights = self.weights * np.exp(self.mean_loglike - self.loglikes)\n            binNDlikes = np.bincount(flatixv, weights=likeweights,\n                                     minlength=np.prod(xsizev)).reshape(xsizev[::-1], order='C')\n        else:\n            binNDlikes = None\n\n        if maxlikes:\n            binNDmaxlikes = np.zeros(binsND.shape)\n            ndindex = zip(*[ixv[i] for i in range(ndim)[::-1]])\n            bestfit = np.max(-self.loglikes)\n\n            for irec in range(len(self.loglikes)):\n                binNDmaxlikes[ndindex[irec]] = max(binNDmaxlikes[ndindex[irec]],\n                                                   np.exp(-bestfit - self.loglikes[irec]))\n        else:\n            binNDmaxlikes = None\n\n        xv = [np.linspace(xminv[i], xmaxv[i], xsizev[i]) for i in range(ndim)]\n        views = [(parv[i].range_min, parv[i].range_max) for i in range(ndim)]\n\n        density = DensityND(xv, binsND, view_ranges=views)\n\n        # density.normalize('integral', in_place=True)\n        density.normalize('max', in_place=True)\n        if get_density: return density\n\n        ncontours = len(self.contours)\n        if num_plot_contours: ncontours = min(num_plot_contours, ncontours)\n        contours = self.contours[:ncontours]\n\n        # Get contour containing contours(:) of the probability\n        density.contours = density.getContourLevels(contours)\n\n        if meanlikes:\n            binNDlikes /= np.max(binNDlikes)\n            density.likes = binNDlikes\n        else:\n            density.likes = None\n\n        if maxlikes:\n            density.maxlikes = binNDmaxlikes\n            density.maxcontours = getOtherContourLevels(binNDmaxlikes, contours, half_edge=False)\n        else:\n            density.maxlikes = None\n\n        if writeDataToFile:\n            # note store things in confusing transpose form\n\n            postfile = self.rootname + \"_posterior\" + \"_%sD.dat\" % ndim\n            contfile = self.rootname + \"_posterior\" + \"_%sD_cont.dat\" % ndim\n\n            allND = [np.array(binsND) for _ in range(ndim + 1)]\n            allND[0] = np.ravel(binsND, order='C')\n            for i in range(ndim):\n                # [index[::-1] for column-major order\n                allND[i + 1] = [xv[i][index[::-1][i]] for index in np.ndindex(binsND.shape)]\n\n            filename = os.path.join(self.plot_data_dir, postfile)\n            np.savetxt(filename, np.transpose(allND), \"%16.7E\")\n\n            filename = os.path.join(self.plot_data_dir, contfile)\n            np.savetxt(filename, np.atleast_2d(density.contours), \"%16.7E\")\n\n            if meanlikes:\n                allND[0] = np.ravel(binNDlikes, order='C')\n                likefile = self.rootname + \"_meanlike\" + \"_%sD.dat\" % ndim\n                filename = os.path.join(self.plot_data_dir, likefile)\n                np.savetxt(filename, np.transpose(allND), \"%16.7E\")\n\n            if maxlikes:\n                allND[0] = np.ravel(binNDmaxlikes, order='C')\n                likefile = self.rootname + \"_maxlike\" + \"_%sD.dat\" % ndim\n                filename = os.path.join(self.plot_data_dir, likefile)\n                np.savetxt(filename, np.transpose(allND), \"%16.7E\")\n\n        return density\n\n    def _setLikeStats(self):\n        \"\"\"\n        Get and store LikeStats (see :func:`MCSamples.getLikeStats`)\n        \"\"\"\n        if self.loglikes is None:\n            self.likeStats = None\n            return None\n        m = types.LikeStats()\n        bestfit_ix = np.argmin(self.loglikes)\n        maxlike = self.loglikes[bestfit_ix]\n        m.logLike_sample = maxlike\n        if np.max(self.loglikes) - maxlike < 30:\n            m.logMeanInvLike = np.log(self.mean(np.exp(self.loglikes - maxlike))) + maxlike\n        else:\n            m.logMeanInvLike = None\n\n        m.meanLogLike = self.mean_loglike\n        m.logMeanLike = -np.log(self.mean(np.exp(-(self.loglikes - maxlike)))) + maxlike\n        # assuming maxlike is well determined\n        m.complexity = 2 * (self.mean_loglike - maxlike)\n\n        m.names = self.paramNames.names\n\n        # get N-dimensional confidence region\n        indexes = self.loglikes.argsort()\n        cumsum = np.cumsum(self.weights[indexes])\n        m.ND_cont1, m.ND_cont2 = np.searchsorted(cumsum, self.norm * self.contours[0:2])\n\n        for j, par in enumerate(self.paramNames.names):\n            region1 = self.samples[indexes[:m.ND_cont1], j]\n            region2 = self.samples[indexes[:m.ND_cont2], j]\n            par.ND_limit_bot = np.array([np.min(region1), np.min(region2)])\n            par.ND_limit_top = np.array([np.max(region1), np.max(region2)])\n            par.bestfit_sample = self.samples[bestfit_ix][j]\n\n        self.likeStats = m\n        return m\n\n    def _readRanges(self):\n        if self.root:\n            ranges_file_classic = self.root + '.ranges'\n            ranges_file_new = (\n                    self.root + ('' if self.root.endswith('/') else '__') + 'full.yaml')\n            for ranges_file in [ranges_file_classic, ranges_file_new]:\n                if os.path.isfile(ranges_file):\n                    self.ranges = ParamBounds(ranges_file)\n                    return\n        self.ranges = ParamBounds()\n\n    def getBounds(self):\n        \"\"\"\n        Returns the bounds in the form of a :class:`~.parampriors.ParamBounds` instance, for example for determining plot ranges\n\n        Bounds are not  the same as self.ranges, as if samples are not near the range boundary, the bound is set to None\n\n        :return: a :class:`~.parampriors.ParamBounds` instance\n        \"\"\"\n        bounds = ParamBounds()\n        bounds.names = self.paramNames.list()\n        for par in self.paramNames.names:\n            if par.has_limits_bot:\n                bounds.lower[par.name] = par.limmin\n            if par.has_limits_top:\n                bounds.upper[par.name] = par.limmax\n        return bounds\n\n    def getUpper(self, name):\n        \"\"\"\n        Return the upper limit of the parameter with the given name.\n\n        :param name: parameter name\n        :return: The upper limit if name exists, None otherwise.\n        \"\"\"\n        par = self.paramNames.parWithName(name)\n        if par:\n            return getattr(par, 'limmax', None)\n        return None\n\n    def getLower(self, name):\n        \"\"\"\n        Return the lower limit of the parameter with the given name.\n\n        :param name: parameter name\n        :return: The lower limit if name exists, None otherwise.\n        \"\"\"\n        par = self.paramNames.parWithName(name)\n        if par:\n            return getattr(par, 'limmin', None)\n        return None\n\n    def getBestFit(self):\n        bf_file = self.root + '.minimum'\n        if os.path.exists(bf_file):\n            return types.BestFit(bf_file)\n        else:\n            raise MCSamplesError(\n                'Best fit can only be included if loaded from file and file_root.minimum exists (cannot be calculated from samples)')\n\n    def getMargeStats(self, include_bestfit=False):\n        \"\"\"\n        Returns a :class:`~.types.MargeStats` object with marginalized 1D parameter constraints\n\n        :param include_bestfit: if True, set best fit values by loading from root_name.minimum file (assuming it exists)\n        :return: A :class:`~.types.MargeStats` instance\n        \"\"\"\n        self._setDensitiesandMarge1D()\n        m = types.MargeStats()\n        m.hasBestFit = False\n        m.limits = self.contours\n        m.names = self.paramNames.names\n        if include_bestfit:\n            m.addBestFit(self.getBestFit())\n        return m\n\n    def getLikeStats(self):\n        \"\"\"\n        Get best fit sample and n-D confidence limits, and various likelihood based statistics\n\n        :return: a :class:`~.types.LikeStats` instance storing N-D limits for parameter i in result.names[i].ND_limit_top,\n                 result.names[i].ND_limit_bot, and best-fit sample value in result.names[i].bestfit_sample\n        \"\"\"\n        return self.likeStats or self._setLikeStats()\n\n    def getTable(self, columns=1, include_bestfit=False, **kwargs):\n        \"\"\"\n        Creates and returns a :class:`~.types.ResultTable` instance. See also :func:`~MCSamples.getInlineLatex`.\n\n        :param columns: number of columns in the table\n        :param include_bestfit: True if should include the bestfit parameter values (assuming set)\n        :param kwargs: arguments for :class:`~.types.ResultTable` constructor.\n        :return: A :class:`~.types.ResultTable` instance\n        \"\"\"\n        return types.ResultTable(columns, [self.getMargeStats(include_bestfit)], **kwargs)\n\n    def getLatex(self, params=None, limit=1, err_sig_figs=None):\n        \"\"\"\n        Get tex snippet for constraints on a list of parameters\n\n        :param params: list of parameter names, or a single parameter name\n        :param limit: which limit to get, 1 is the first (default 68%), 2 is the second (limits array specified by self.contours)\n        :param err_sig_figs: significant figures in the error\n        :return: labels, texs: a list of parameter labels, and a list of tex snippets, or for a single parameter, the latex snippet.\n        \"\"\"\n        if isinstance(params, six.string_types):\n            return self.getInlineLatex(params, limit, err_sig_figs)\n\n        marge = self.getMargeStats()\n        if params is None: params = marge.list()\n\n        formatter = types.NoLineTableFormatter()\n        if err_sig_figs: formatter.numberFormatter.err_sf = err_sig_figs\n        texs = []\n        labels = []\n        for par in params:\n            tex = marge.texValues(formatter, par, limit=limit)\n            if tex is not None:\n                texs.append(tex[0])\n                labels.append(marge.parWithName(par).getLabel())\n            else:\n                texs.append(None)\n                labels.append(None)\n\n        return labels, texs\n\n    def getInlineLatex(self, param, limit=1, err_sig_figs=None):\n        r\"\"\"\n        Get snippet like: A=x\\\\pm y. Will adjust appropriately for one and two tail limits.\n\n        :param param: The name of the parameter\n        :param limit: which limit to get, 1 is the first (default 68%), 2 is the second (limits array specified by self.contours)\n        :param err_sig_figs: significant figures in the error\n        :return: The tex snippet.\n        \"\"\"\n        labels, texs = self.getLatex([param], limit, err_sig_figs)\n        if texs[0] is None: raise ValueError('parameter %s not found' % param)\n        if not texs[0][0] in ['<', '>']:\n            return labels[0] + ' = ' + texs[0]\n        else:\n            return labels[0] + ' ' + texs[0]\n\n    def _setDensitiesandMarge1D(self, max_frac_twotail=None, writeDataToFile=False, meanlikes=False):\n        \"\"\"\n        Get all the 1D densities; result is cached.\n\n        :param max_frac_twotail: optional override for self.max_frac_twotail\n        :param writeDataToFile: True if should write to file\n        :param meanlikes: include mean likelihoods\n        \"\"\"\n        if self.done_1Dbins: return\n\n        for j in range(self.n):\n            paramConfid = self.initParamConfidenceData(self.samples[:, j])\n            self.get1DDensityGridData(j, writeDataToFile, get_density=not writeDataToFile, paramConfid=paramConfid,\n                                      meanlikes=meanlikes)\n            self._setMargeLimits(self.paramNames.names[j], paramConfid, max_frac_twotail)\n\n        self.done_1Dbins = True\n\n    def _setMargeLimits(self, par, paramConfid, max_frac_twotail=None, density1D=None):\n        \"\"\"\n        Get limits, one or two tail depending on whether posterior\n        goes to zero at the limits or not\n\n        :param par:  The :class:`~.paramnames.ParamInfo` to set limits for\n        :param paramConfid: :class:`~.chains.ParamConfidenceData` instance\n        :param max_frac_twotail: optional override for self.max_frac_twotail\n        :param density1D: any existing density 1D instance to use\n        \"\"\"\n        if max_frac_twotail is None:\n            max_frac_twotail = self.max_frac_twotail\n        par.limits = []\n        density1D = density1D or self.get1DDensity(par.name)\n        interpGrid = None\n        for ix1, contour in enumerate(self.contours):\n\n            marge_limits_bot = par.has_limits_bot and \\\n                               not self.force_twotail and density1D.P[0] > max_frac_twotail[ix1]\n            marge_limits_top = par.has_limits_top and \\\n                               not self.force_twotail and density1D.P[-1] > max_frac_twotail[ix1]\n\n            if not marge_limits_bot or not marge_limits_top:\n                # give limit\n                if not interpGrid: interpGrid = density1D.initLimitGrids()\n                tail_limit_bot, tail_limit_top, marge_limits_bot, marge_limits_top = density1D.getLimits(contour,\n                                                                                                         interpGrid)\n                limfrac = 1 - contour\n\n                if marge_limits_bot:\n                    # fix to end of prior range\n                    tail_limit_bot = par.range_min\n                elif marge_limits_top:\n                    # 1 tail limit\n                    tail_limit_bot = self.confidence(paramConfid, limfrac, upper=False)\n                else:\n                    # 2 tail limit\n                    tail_confid_bot = self.confidence(paramConfid, limfrac / 2, upper=False)\n\n                if marge_limits_top:\n                    tail_limit_top = par.range_max\n                elif marge_limits_bot:\n                    tail_limit_top = self.confidence(paramConfid, limfrac, upper=True)\n                else:\n                    tail_confid_top = self.confidence(paramConfid, limfrac / 2, upper=True)\n\n                if not marge_limits_bot and not marge_limits_top:\n                    # Two tail, check if limits are at very different density\n                    if (math.fabs(density1D.Prob(tail_confid_top) -\n                                  density1D.Prob(tail_confid_bot)) < self.credible_interval_threshold):\n                        tail_limit_top = tail_confid_top\n                        tail_limit_bot = tail_confid_bot\n\n                lim = [tail_limit_bot, tail_limit_top]\n            else:\n                # no limit\n                lim = [par.range_min, par.range_max]\n\n            if marge_limits_bot and marge_limits_top:\n                tag = 'none'\n            elif marge_limits_bot:\n                tag = '>'\n            elif marge_limits_top:\n                tag = '<'\n            else:\n                tag = 'two'\n            par.limits.append(types.ParamLimit(lim, tag))\n\n    def getCorrelatedVariable2DPlots(self, num_plots=12, nparam=None):\n        \"\"\"\n        Gets a list of most correlated variable pair names.\n\n        :param num_plots: The number of plots\n        :param nparam: maximum number of pairs to get\n        :return: list of [x,y] pair names\n        \"\"\"\n        nparam = nparam or self.paramNames.numNonDerived()\n        try_t = 1e5\n        x, y = 0, 0\n        cust2DPlots = []\n        correlationMatrix = self.correlationMatrix\n        for _ in range(num_plots):\n            try_b = -1e5\n            for ix1 in range(nparam):\n                for ix2 in range(ix1 + 1, nparam):\n                    if try_b < abs(correlationMatrix[ix1][ix2]) < try_t:\n                        try_b = abs(correlationMatrix[ix1][ix2])\n                        x, y = ix1, ix2\n            if try_b == -1e5:\n                break\n            try_t = try_b\n            cust2DPlots.append([self.parName(x), self.parName(y)])\n\n        return cust2DPlots\n\n    def addDerived(self, paramVec, name, label='', comment='', range=None):\n        \"\"\"\n        Adds a new derived parameter\n\n        :param paramVec: The vector of parameter values to add. For example a combination of parameter arrays from MCSamples.getParams()\n        :param name: The name for the new parameter\n        :param label: optional latex label for the parameter\n        :param comment: optional comment describing the parameter\n        :param range: if specified, a tuple of min, max values for the new parameter hard prior bounds (either can be None for one-side bound)\n        :return: The added parameter's :class:`~.paramnames.ParamInfo` object\n        \"\"\"\n\n        if range is not None:\n            self.ranges.setRange(name, range)\n        return super(MCSamples, self).addDerived(paramVec, name, label=label, comment=comment)\n\n    def getParamBestFitDict(self):\n        \"\"\"\n        Gets a dictionary of parameter values for the best fit point, assuming .minimum best fit file exists\n        :return: dictionary of parameter values\n        \"\"\"\n        res = self.getBestFit().getParamDict()\n        res.update(self.ranges.fixedValueDict())\n        return res\n\n    def getParamSampleDict(self, ix):\n        \"\"\"\n        Gets a dictionary of parameter values for sample number ix\n        :return: dictionary of parameter values\n        \"\"\"\n        res = super(MCSamples, self).getParamSampleDict(ix)\n        res.update(self.ranges.fixedValueDict())\n        return res\n\n    def getCombinedSamplesWithSamples(self, samps2, sample_weights=[1, 1]):\n        \"\"\"\n        Make a new  :class:`MCSamples` instance by appending samples from samps2 for parameters which are in common.\n        By default they are weighted so that the probability mass of each set of samples is the same,\n        independent of tha actual sample sizes. The Weights parameter can be adjusted to change the\n        relative weighting.\n        :param samps2:  :class:`MCSamples` instance to merge\n        :param sample_weights: relative weights for combining the samples. Set to None to just directly append samples.\n        :return: a new  :class:`MCSamples` instance with the combined samples\n        \"\"\"\n\n        params = ParamNames()\n        params.names = [ParamInfo(name=p.name, label=p.label, derived=p.isDerived) for p in samps2.paramNames.names if\n                        p.name in self.paramNames.list()]\n        if self.loglikes is not None and samps2.loglikes is not None:\n            loglikes = np.concatenate([self.loglikes, samps2.loglikes])\n        else:\n            loglikes = None\n        if sample_weights is None:\n            fac = 1\n            sample_weights = [1, 1]\n        else:\n            fac = np.sum(self.weights) / np.sum(samps2.weights)\n        weights = np.concatenate([self.weights * sample_weights[0], samps2.weights * sample_weights[1] * fac])\n        p1 = self.getParams()\n        p2 = samps2.getParams()\n        samples = np.array([np.concatenate([getattr(p1, name), getattr(p2, name)]) for name in params.list()]).T\n        samps = MCSamples(samples=samples, weights=weights, loglikes=loglikes, paramNamesFile=params, ignore_rows=0,\n                          ranges=self.ranges, settings=copy.deepcopy(self.ini.params))\n        return samps\n\n    def saveAsText(self, root, chain_index=None, make_dirs=False):\n        \"\"\"\n        Saves samples as text file, including .ranges and .paramnames.\n\n        :param root: The root file name to use.\n        :param chain_index: optional index to be used for the filename.\n        :param make_dirs: True if should create the directories\n        \"\"\"\n        super(MCSamples, self).saveAsText(root, chain_index, make_dirs)\n        if not chain_index:\n            self.ranges.saveToFile(root + '.ranges')\n\n    def saveChainsAsText(self, root, make_dirs=False, properties={}):\n        if self.chains is None:\n            chains = self.getSeparateChains()\n        else:\n            chains = self.chains\n        for i, chain in enumerate(chains):\n            chain.saveAsText(root, i, make_dirs)\n        self.ranges.saveToFile(root + '.ranges')\n        self.paramNames.saveAsText(root + '.paramnames')\n        if properties:\n            ini_name = root + '.properties.ini'\n            if os.path.exists(ini_name):\n                ini = IniFile(ini_name)\n            else:\n                ini = IniFile()\n            ini.params.update(properties)\n            ini.saveFile(ini_name)\n\n    # Write functions for GetDist.py\n    def writeScriptPlots1D(self, filename, plotparams=None, ext=None):\n        \"\"\"\n        Write a script that generates a 1D plot. Only intended for use by GetDist.py script.\n\n        :param filename: The filename to write to.\n        :param plotparams: The list of parameters to plot (default: all)\n        :param ext: The extension for the filename, Default if None\n        \"\"\"\n        text = 'markers = ' + (str(self.markers) if self.markers else 'None') + '\\n'\n        if plotparams:\n            text += 'g.plots_1d(roots,[' + \",\".join(['\\'' + par + '\\'' for par in plotparams]) + '], markers=markers)'\n        else:\n            text += 'g.plots_1d(roots, markers=markers)'\n        self._WritePlotFile(filename, self.subplot_size_inch, text, '', ext)\n\n    def writeScriptPlots2D(self, filename, plot_2D_param=None, cust2DPlots=[], writeDataToFile=False, ext=None,\n                           shade_meanlikes=False):\n        \"\"\"\n        Write script that generates a 2 dimensional plot. Only intended for use by GetDist.py script.\n\n        :param filename: The filename to write to.\n        :param plot_2D_param: parameter to plot other variables against\n        :param cust2DPlots: list of parts of parameter names to plot\n        :param writeDataToFile: True if should write to file\n        :param ext: The extension for the filename, Default if None\n        :param shade_meanlikes: shade by mean likelihoods\n        :return: A dictionary indexed by pairs of parameters where 2D densities have been calculated\n        \"\"\"\n        done2D = {}\n        text = 'pairs=[]\\n'\n        plot_num = 0\n        if len(cust2DPlots):\n            cuts = [par1 + '__' + par2 for par1, par2 in cust2DPlots]\n        for j, par1 in enumerate(self.paramNames.list()):\n            if plot_2D_param or cust2DPlots:\n                if par1 == plot_2D_param: continue\n                j2min = 0\n            else:\n                j2min = j + 1\n\n            for j2 in range(j2min, self.n):\n                par2 = self.parName(j2)\n                if plot_2D_param and par2 != plot_2D_param: continue\n                if len(cust2DPlots) and (par1 + '__' + par2) not in cuts: continue\n                if (par1, par2) not in done2D:\n                    plot_num += 1\n                    done2D[(par1, par2)] = True\n                    if writeDataToFile:\n                        self.get2DDensityGridData(j, j2, writeDataToFile=True, meanlikes=shade_meanlikes)\n                    text += \"pairs.append(['%s','%s'])\\n\" % (par1, par2)\n        if shade_meanlikes:\n            text += 'g.plots_2d(roots,param_pairs=pairs,shaded=True)'\n        else:\n            text += 'g.plots_2d(roots,param_pairs=pairs,filled=True)'\n        self._WritePlotFile(filename, self.subplot_size_inch2, text, '_2D', ext)\n        return done2D\n\n    def writeScriptPlotsTri(self, filename, triangle_params, ext=None):\n        \"\"\"\n        Write a script that generates a triangle plot. Only intended for use by GetDist.py script.\n\n        :param filename: The filename to write to.\n        :param triangle_params: list of parameter names to plot\n        :param ext: The extension for the filename, Default if None\n        \"\"\"\n        text = 'g.triangle_plot(roots, %s)' % triangle_params\n        self._WritePlotFile(filename, self.subplot_size_inch, text, '_tri', ext)\n\n    def writeScriptPlots3D(self, filename, plot_3D, ext=None):\n        \"\"\"\n        Writes a script that generates a 3D (coloured-scatter) plot. Only intended for use by GetDist.py script.\n\n        :param filename: The filename to write to\n        :param plot_3D: list of [x,y,z] parameters for the 3 Dimensional plots\n        :param ext: The extension for the filename, Default if None\n        \"\"\"\n        text = 'sets=[]\\n'\n        for pars in plot_3D:\n            text += \"sets.append(['%s','%s','%s'])\\n\" % tuple(pars)\n        text += 'g.plots_3d(roots,sets)'\n        self._WritePlotFile(filename, self.subplot_size_inch3, text, '_3D', ext)\n\n    def _WritePlotFile(self, filename, subplot_size, text, tag, ext=None):\n        \"\"\"\n        Write plot file.\n        Used by other functions\n\n        :param filename: The filename to write to\n        :param subplot_size: The size of the subplot.\n        :param text: The text to write after the headers.\n        :param tag: Tag used for the filename the created file will export to.\n        :param ext: The extension for the filename, Default if None\n        \"\"\"\n        with open(filename, 'w') as f:\n            f.write(\"import getdist.plots as plots, os\\n\")\n            if self.plot_data_dir:\n                f.write(\"g=plots.GetDistPlotter(plot_data=r'%s')\\n\" % self.plot_data_dir)\n            else:\n                f.write(\"g=plots.GetDistPlotter(chain_dir=r'%s')\\n\" % (self.batch_path or os.path.dirname(self.root)))\n\n            f.write(\"g.settings.setWithSubplotSize(%s)\\n\" % subplot_size)\n            f.write(\"roots = ['%s']\\n\" % self.rootname)\n            f.write(text + '\\n')\n            ext = ext or self.plot_output\n            fname = self.rootname + tag + '.' + ext\n            f.write(\"g.export(os.path.join(r'%s',r'%s'))\\n\" % (self.out_dir, fname))\n\n\n# ==============================================================================\n\n# Useful functions\n\ndef GetChainRootFiles(rootdir):\n    \"\"\"\n    Gets the root names of all chain files in a directory.\n\n    :param rootdir: The root directory to check\n    :return:  The root names\n    \"\"\"\n    pattern = os.path.join(rootdir, '*.paramnames')\n    files = [os.path.splitext(f)[0] for f in glob.glob(pattern)]\n    ending = 'full.yaml'\n    pattern = os.path.join(rootdir, \"*\" + ending)\n    files += [f[:-len(ending)].rstrip(\"_\") for f in glob.glob(pattern)]\n    files.sort()\n    return files\n\n\ndef GetRootFileName(rootdir):\n    \"\"\"\n    Gets the root name of chains in given directory (assuming only one set of chain files).\n\n    :param rootdir: The directory to check\n    :return: The root file name.\n    \"\"\"\n    rootFileName = \"\"\n    pattern = os.path.join(rootdir, '*_*.txt')\n    chain_files = glob.glob(pattern)\n    chain_files.sort()\n    if chain_files:\n        chain_file0 = chain_files[0]\n        rindex = chain_file0.rindex('_')\n        rootFileName = chain_file0[:rindex]\n    return rootFileName\n\n# ==============================================================================\n", "meta": {"hexsha": "8a144464c2d3826e221c104310c9f13129341cec", "size": 116386, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/getdist/mcsamples.py", "max_stars_repo_name": "sfu-cosmo/MagCosmoMC", "max_stars_repo_head_hexsha": "11031bf16fa42b26e16e4caf1ed04b566a2ca436", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/getdist/mcsamples.py", "max_issues_repo_name": "sfu-cosmo/MagCosmoMC", "max_issues_repo_head_hexsha": "11031bf16fa42b26e16e4caf1ed04b566a2ca436", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/getdist/mcsamples.py", "max_forks_repo_name": "sfu-cosmo/MagCosmoMC", "max_forks_repo_head_hexsha": "11031bf16fa42b26e16e4caf1ed04b566a2ca436", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.4810472841, "max_line_length": 151, "alphanum_fraction": 0.5673878302, "include": true, "reason": "import numpy,from scipy", "num_tokens": 28391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.19923329715255292}}
{"text": "\"\"\"\nBase classes\n   \n.. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de> \n\"\"\"\n\nfrom abc import ABCMeta, abstractmethod\nimport logging\nfrom typing import Callable, Dict, Optional, TYPE_CHECKING  # @UnusedImport\n\nimport numpy as np\n\nfrom ..fields.base import FieldBase\nfrom ..trackers.base import TrackerCollectionDataType\nfrom ..tools.numba import jit\n\n\nif TYPE_CHECKING:\n    from ..solvers.controller import TRangeType  # @UnusedImport\n\n\n\nclass PDEBase(metaclass=ABCMeta):\n    \"\"\" base class for solving partial differential equations \"\"\"\n\n    explicit_time_dependence: Optional[bool] = None\n\n\n    def __init__(self, noise: float = 0):\n        \"\"\"\n        Args:\n            noise (float):\n                Magnitude of the additive Gaussian white noise that is supported\n                by default. If set to zero, a determinitics partial differential\n                equation will be solved. If another noise structure is required\n                the respective methods need to be overwritten.\n        \"\"\"\n        self._logger = logging.getLogger(self.__class__.__name__)\n        self.noise = noise\n\n\n    @property\n    def is_sde(self) -> bool:\n        \"\"\" flag indicating whether this is a stochastic differential equation\n        \n        The :class:`BasePDF` class supports additive Gaussian white noise, whose\n        magnitude is controlled by the `noise` property. In this case, `is_sde`\n        is `True` if `self.noise != 0`.\n        \"\"\"\n        # check for self.noise, in case __init__ is not called in a subclass\n        return hasattr(self, 'noise') and self.noise != 0\n\n\n    @abstractmethod\n    def evolution_rate(self, field: FieldBase, t: float = 0) \\\n        -> FieldBase: pass\n\n\n    def _make_pde_rhs_numba(self, state: FieldBase) -> Callable:\n        \"\"\" create a compiled function for evaluating the right hand side \"\"\"\n        raise NotImplementedError\n\n\n    def make_pde_rhs(self, state: FieldBase, backend: str = 'auto') -> Callable:\n        \"\"\" return a function for evaluating the right hand side of the PDE\n        \n        Args:\n            state (:class:`~pde.fields.FieldBase`):\n                An example for the state from which the grid and other\n                information can be extracted\n            backend (str): Determines how the function is created. Accepted \n                values are 'python` and 'numba'. Alternatively, 'auto' lets the\n                code decide for the most optimal backend.\n                \n        Returns:\n            Function determining the right hand side of the PDE\n        \"\"\"\n        if backend == 'auto':\n            try:\n                result = self._make_pde_rhs_numba(state)\n            except NotImplementedError:\n                backend = 'numpy'\n            else:\n                result._backend = 'numba'  # type: ignore\n                return result\n             \n        if backend == 'numba':\n            result = self._make_pde_rhs_numba(state)\n            result._backend = 'numba'  # type: ignore\n                \n        elif backend == 'numpy':\n            state = state.copy()\n            \n            def evolution_rate_numpy(state_data, t: float):\n                \"\"\" evaluate the rhs given only a state without the grid \"\"\"\n                state.data = state_data\n                return self.evolution_rate(state, t).data\n        \n            result = evolution_rate_numpy\n            result._backend = 'numpy'  # type: ignore\n            \n        else:\n            raise ValueError(f'Unknown backend `{backend}`')\n        \n        return result\n            \n            \n    def noise_realization(self, state: FieldBase, t: float = 0) -> FieldBase:\n        \"\"\" returns a realization for the noise\n        \n        Args:\n            state (:class:`~pde.fields.ScalarField`):\n                The scalar field describing the concentration distribution\n            t (float): The current time point\n            \n        Returns:\n            :class:`~pde.fields.ScalarField`:\n            Scalar field describing the evolution rate of the PDE \n        \"\"\"\n        if self.noise:\n            data = np.random.normal(scale=self.noise, size=state.data.shape)\n            return state.copy(data=data, label='Noise realization')\n        else:\n            return state.copy(data=0, label='Noise realization')\n\n       \n    def _make_noise_realization_numba(self, state: FieldBase) -> Callable:            \n        \"\"\" return a function for evaluating the noise term of the PDE\n        \n        Args:\n            state (:class:`~pde.fields.FieldBase`):\n                An example for the state from which the grid and other\n                information can be extracted\n                \n        Returns:\n            Function determining the right hand side of the PDE\n        \"\"\"\n        if self.noise:        \n            noise_strength = float(self.noise)\n            data_shape = state.data.shape\n            \n            @jit\n            def noise_realization(state_data: np.ndarray, t: float):\n                \"\"\" compiled helper function returning a noise realization \"\"\" \n                return noise_strength * np.random.randn(*data_shape)\n            \n        else:\n            @jit\n            def noise_realization(state_data: np.ndarray, t: float):\n                \"\"\" compiled helper function returning a noise realization \"\"\" \n                return None\n        \n        return noise_realization  # type: ignore    \n            \n       \n    def _make_sde_rhs_numba(self, state: FieldBase) -> Callable:            \n        \"\"\" return a function for evaluating the noise term of the PDE\n        \n        Args:\n            state (:class:`~pde.fields.FieldBase`):\n                An example for the state from which the grid and other\n                information can be extracted\n                \n        Returns:\n            Function determining the right hand side of the PDE\n        \"\"\"\n        evolution_rate = self._make_pde_rhs_numba(state)\n        noise_realization = self._make_noise_realization_numba(state)\n        \n        @jit\n        def sde_rhs(state_data: np.ndarray, t: float):\n            \"\"\" compiled helper function returning a noise realization \"\"\" \n            return (evolution_rate(state_data, t),\n                    noise_realization(state_data, t))\n        \n        return sde_rhs  # type: ignore    \n    \n                        \n    def make_sde_rhs(self, state: FieldBase, backend: str = 'auto') \\\n            -> Callable:\n        \"\"\" return a function for evaluating the right hand side of the SDE\n        \n        Args:\n            state (:class:`~pde.fields.FieldBase`):\n                An example for the state from which the grid and other\n                information can be extracted\n            backend (str): Determines how the function is created. Accepted \n                values are 'python` and 'numba'. Alternatively, 'auto' lets the\n                code decide for the most optimal backend.\n                \n        Returns:\n            Function determining the deterministic part of the right hand side\n            of the PDE together with a noise realization.\n        \"\"\"\n        if backend == 'auto':\n            try:\n                sde_rhs = self._make_sde_rhs_numba(state)\n            except NotImplementedError:\n                backend = 'numpy'\n            else:\n                sde_rhs._backend = 'numba'  # type: ignore\n                return sde_rhs\n             \n        if backend == 'numba':\n            sde_rhs = self._make_sde_rhs_numba(state)\n            sde_rhs._backend = 'numba'  # type: ignore\n                \n        elif backend == 'numpy':\n            state = state.copy()\n            \n            def sde_rhs(state_data, t: float):\n                \"\"\" evaluate the rhs given only a state without the grid \"\"\"\n                state.data = state_data\n                return (self.evolution_rate(state, t).data,\n                        self.noise_realization(state, t).data)\n        \n            sde_rhs._backend = 'numpy'  # type: ignore\n            \n        else:\n            raise ValueError(f'Unknown backend `{backend}`')\n        \n        return sde_rhs\n            \n\n    def solve(self, state: FieldBase,\n              t_range: \"TRangeType\",\n              dt: float = None,\n              tracker: TrackerCollectionDataType = ['progress', 'consistency'],\n              method: str = 'auto',\n              **kwargs):\n        \"\"\" convenience method for solving the partial differential equation \n        \n        The method constructs a suitable solver\n        (:class:`~pde.solvers.base.SolverBase`) and controller\n        (:class:`~pde.controller.Controller`) to advance the state over the\n        temporal range specified by `t_range`. To obtain full flexibility, it is\n        advisable to construct these classes explicitly. \n\n        Args:\n            state (:class:`~pde.fields.base.FieldBase`):\n                The initial state (which also defines the grid)\n            t_range (float or tuple):\n                Sets the time range for which the PDE is solved. If only a\n                single value `t_end` is given, the time range is assumed to be \n                `[0, t_end]`.\n            dt (float):\n                Time step of the chosen stepping scheme. If `None`, a default\n                value based on the stepper will be chosen.\n            tracker:\n                Defines a tracker that process the state of the simulation at\n                fixed time intervals. Multiple trackers can be specified as a\n                list. The default value is ['progress', 'consistency'], which\n                displays a progress bar and checks the state for consistency,\n                aborting the simulation when not-a-number values appear.\n            method (:class:`~pde.solvers.base.SolverBase` or str):\n                Specifies a method for solving the differential equation. This\n                can either be an instance of\n                :class:`~pde.solvers.base.SolverBase` or a descriptive name\n                like 'explicit' or 'scipy'. The valid names are given by\n                :meth:`pde.solvers.base.SolverBase.registered_solvers`.\n            **kwargs:\n                Additional keyword arguments are forwarded to the solver class\n                \n        Returns:\n            :class:`~pde.fields.base.FieldBase`:\n            The state at the final time point.\n        \"\"\"\n        from ..solvers.base import SolverBase\n        \n        if method == 'auto':\n            method = 'scipy' if dt is None else 'explicit'\n        \n        # create solver\n        if callable(method):\n            solver = method(pde=self, **kwargs)\n            if not isinstance(solver, SolverBase):\n                self._logger.warn('Solver is not an instance of `SolverBase`. '\n                                  'Specified wrong method?')\n        else:\n            solver = SolverBase.from_name(method, pde=self, **kwargs)\n        \n        # create controller\n        from ..solvers import Controller\n        controller = Controller(solver, t_range=t_range, tracker=tracker)\n        \n        # run the simulation\n        return controller.run(state, dt)\n                ", "meta": {"hexsha": "9cf1ac5b1fae6171c9a2c5dc4a00496021f9c523", "size": 11150, "ext": "py", "lang": "Python", "max_stars_repo_path": "pde/pdes/base.py", "max_stars_repo_name": "xuanxu/py-pde", "max_stars_repo_head_hexsha": "de33d938aea8680eff872ae1b64569895662a248", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pde/pdes/base.py", "max_issues_repo_name": "xuanxu/py-pde", "max_issues_repo_head_hexsha": "de33d938aea8680eff872ae1b64569895662a248", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pde/pdes/base.py", "max_forks_repo_name": "xuanxu/py-pde", "max_forks_repo_head_hexsha": "de33d938aea8680eff872ae1b64569895662a248", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7152777778, "max_line_length": 86, "alphanum_fraction": 0.5658295964, "include": true, "reason": "import numpy", "num_tokens": 2222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.19923329715255286}}
{"text": "##############################################################################\n# Copyright 2016-2017 Rigetti Computing\n#\n#    Licensed under the Apache License, Version 2.0 (the \"License\");\n#    you may not use this file except in compliance with the License.\n#    You may obtain a copy of the License at\n#\n#        http://www.apache.org/licenses/LICENSE-2.0\n#\n#    Unless required by applicable law or agreed to in writing, software\n#    distributed under the License is distributed on an \"AS IS\" BASIS,\n#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#    See the License for the specific language governing permissions and\n#    limitations under the License.\n##############################################################################\n\nimport pyquil.api as api\nimport pyquil.quil as pq\nimport numpy as np\nfrom collections import Counter\nfrom pyquil.gates import STANDARD_GATES, RX, RY\nfrom pyquil.paulis import PauliTerm, PauliSum\nimport funcsigs\n\n\nclass OptResults(dict):\n    \"\"\"\n    Object for holding optimization results from VQE.\n    \"\"\"\n    def __getattr__(self, name):\n        try:\n            return self[name]\n        except KeyError:\n            raise AttributeError(name)\n\n    __setattr__ = dict.__setitem__\n    __delattr__ = dict.__delitem__\n\n\nclass VQE(object):\n    \"\"\"\n    The Variational-Quantum-Eigensolver algorithm\n\n    VQE is an object that encapsulates the VQE algorithm (functional\n    minimization). The main components of the VQE algorithm are a minimizer\n    function for performing the functional minimization, a function that takes a\n    vector of parameters and returns a pyQuil program, and a\n    Hamiltonian of which to calculate the expectation value.\n\n    Using this object:\n\n        1) initialize with `inst = VQE(minimizer)` where `minimizer` is a\n        function that performs a gradient free minization--i.e\n        scipy.optimize.minimize(. , ., method='Nelder-Mead')\n\n        2) call `inst.vqe_run(variational_state_evolve, hamiltonian,\n        initial_parameters)`. Returns the optimal parameters and minimum\n        expecation\n\n    :param minimizer: function that minimizes objective f(obj, param). For\n                      example the function scipy.optimize.minimize() needs\n                      at least two parameters, the objective and an initial\n                      point for the optimization.  The args for minimizer\n                      are the cost function (provided by this class),\n                      initial parameters (passed to vqe_run() method, and\n                      jacobian (defaulted to None).  kwargs can be passed\n                      in below.\n    :param minimizer_args: (list) arguments for minimizer function. Default=None\n    :param minimizer_kwargs: (dict) arguments for keyword args.\n                              Default=None\n\n    \"\"\"\n\n    def __init__(self, minimizer, minimizer_args=[], minimizer_kwargs={}):\n        self.minimizer = minimizer\n        self.minimizer_args = minimizer_args\n        self.minimizer_kwargs = minimizer_kwargs\n        self.n_qubits = None\n\n    def vqe_run(self, variational_state_evolve, hamiltonian, initial_params,\n                gate_noise=None, measurement_noise=None,\n                jacobian=None, qvm=None, disp=None, samples=None, return_all=False):\n        \"\"\"\n        functional minimization loop.\n\n        :param variational_state_evolve: function that takes a set of parameters\n                                        and returns a pyQuil program.\n        :param hamiltonian: (PauliSum) object representing the hamiltonian of\n                            which to take the expectation value.\n        :param initial_params: (ndarray) vector of initial parameters for the\n                               optimization\n        :param gate_noise: list of Px, Py, Pz probabilities of gate being\n                           applied to every gate after each get application\n        :param measurement_noise: list of Px', Py', Pz' probabilities of a X, Y\n                                  or Z being applied before a measurement.\n        :param jacobian: (optional) method of generating jacobian for parameters\n                         (Default=None).\n        :param qvm: (optional, QVM) forest connection object.\n        :param disp: (optional, bool) display level. If True then each iteration\n                     expectation and parameters are printed at each\n                     optimization iteration.\n        :param samples: (int) Number of samples for calculating the expectation\n                        value of the operators.  If `None` then faster method\n                        ,dotting the wave function with the operator, is used.\n                        Default=None.\n        :param return_all: (optional, bool) request to return all intermediate\n                           parameters determined during the optimization.\n        :return: (vqe.OptResult()) object :func:`OptResult <vqe.OptResult>`.\n                 The following fields are initialized in OptResult:\n                 -x: set of w.f. ansatz parameters\n                 -fun: scalar value of the objective function\n\n                 -iteration_params: a list of all intermediate parameter vectors. Only\n                                    returned if 'return_all=True' is set as a vqe_run()\n                                    option.\n\n                 -expectation_vals: a list of all intermediate expectation values. Only\n                                    returned if 'return_all=True' is set as a\n                                    vqe_run() option.\n        \"\"\"\n        self._disp_fun = disp if disp is not None else lambda x: None\n        iteration_params = []\n        expectation_vals = []\n        self._current_expectation = None\n        if samples is None:\n            print(\"\"\"WARNING: Fast method for expectation will be used. Noise\n                     models will be ineffective\"\"\")\n\n        if qvm is None:\n            qvm = api.QVMConnection(\n                    gate_noise=gate_noise,\n                    measurement_noise=measurement_noise)\n        else:\n            self.qvm = qvm\n\n        def objective_function(params):\n            \"\"\"\n            closure representing the functional\n\n            :param params: (ndarray) vector of parameters for generating the\n                           the function of the functional.\n            :return: (float) expectation value\n            \"\"\"\n            pyquil_prog = variational_state_evolve(params)\n            mean_value = self.expectation(pyquil_prog, hamiltonian, samples, qvm)\n            self._current_expectation = mean_value  # store for printing\n            return mean_value\n\n        def print_current_iter(iter_vars):\n            self._disp_fun(\"\\tParameters: {} \".format(iter_vars))\n            if jacobian is not None:\n                grad = jacobian(iter_vars)\n                self._disp_fun(\"\\tGrad-L1-Norm: {}\".format(np.max(np.abs(grad))))\n                self._disp_fun(\"\\tGrad-L2-Norm: {} \".format(np.linalg.norm(grad)))\n\n            self._disp_fun(\"\\tE => {}\".format(self._current_expectation))\n            if return_all:\n                iteration_params.append(iter_vars)\n                expectation_vals.append(self._current_expectation)\n\n        # using self.minimizer\n        arguments = funcsigs.signature(self.minimizer).parameters.keys()\n\n        if disp is not None and 'callback' in arguments:\n            self.minimizer_kwargs['callback'] = print_current_iter\n\n        args = [objective_function, initial_params]\n        args.extend(self.minimizer_args)\n        if 'jac' in arguments:\n            self.minimizer_kwargs['jac'] = jacobian\n\n        result = self.minimizer(*args, **self.minimizer_kwargs)\n\n        if hasattr(result, 'status'):\n            if result.status != 0:\n                self._disp_fun(\"Classical optimization exited with an error index: %i\"\n                               % result.status)\n\n        results = OptResults()\n        if hasattr(result, 'x'):\n            results.x = result.x\n            results.fun = result.fun\n        else:\n            results.x = result\n\n        if return_all:\n            results.iteration_params = iteration_params\n            results.expectation_vals = expectation_vals\n        return results\n\n    @staticmethod\n    def expectation(pyquil_prog, pauli_sum, samples, qvm):\n        \"\"\"\n        Computes the expectation value of pauli_sum over the distribution\n        generated from pyquil_prog.\n\n        :param pyquil_prog: (pyQuil program)\n        :param pauli_sum: (PauliSum, ndarray) PauliSum representing the\n                          operator of which to calculate the expectation value\n                          or a numpy matrix representing the Hamiltonian\n                          tensored up to the appropriate size.\n        :param samples: (int) number of samples used to calculate the\n                        expectation value.  If samples is None then the expectation\n                        value is calculated by calculating <psi|O|psi> on the\n                        QVM.  Error models will not work if samples is None.\n\n        :param qvm: (qvm connection)\n\n        :returns: (float) representing the expectation value of pauli_sum given\n                  given the distribution generated from quil_prog.\n        \"\"\"\n        if isinstance(pauli_sum, np.ndarray):\n            # debug mode by passing an array\n            wf = qvm.wavefunction(pyquil_prog)\n            wf = np.reshape(wf.amplitudes, (-1, 1))\n            average_exp = np.conj(wf).T.dot(pauli_sum.dot(wf)).real\n            return average_exp\n        else:\n            if not isinstance(pauli_sum, (PauliTerm, PauliSum)):\n                raise TypeError(\"pauli_sum variable must be a PauliTerm or\"\n                                \"PauliSum object\")\n\n            if isinstance(pauli_sum, PauliTerm):\n                pauli_sum = PauliSum([pauli_sum])\n\n            if samples is None:\n                operator_progs = []\n                operator_coeffs = []\n                for p_term in pauli_sum.terms:\n                    op_prog = pq.Program()\n                    for qindex, op in p_term:\n                        op_prog.inst(STANDARD_GATES[op](qindex))\n                    operator_progs.append(op_prog)\n                    operator_coeffs.append(p_term.coefficient)\n\n                result_overlaps = qvm.expectation(pyquil_prog,\n                                                  operator_programs=operator_progs)\n                result_overlaps = list(result_overlaps)\n                assert len(result_overlaps) == len(operator_progs), \"\"\"Somehow we\n                didn't get the correct number of results back from the QVM\"\"\"\n                expectation = sum(list(map(lambda x: x[0]*x[1],\n                                           zip(result_overlaps, operator_coeffs))))\n                return expectation.real\n            else:\n                if not isinstance(samples, int):\n                    raise TypeError(\"samples variable must be an integer\")\n                if samples <= 0:\n                    raise ValueError(\"samples variable must be a postive integer\")\n\n                # normal execution via fake sampling\n                # stores the sum of contributions to the energy from each operator term\n                expectation = 0.0\n                for j, term in enumerate(pauli_sum.terms):\n                    meas_basis_change = pq.Program()\n                    qubits_to_measure = []\n                    if term.id() == \"\":\n                        meas_outcome = 1.0\n                    else:\n                        for index, gate in term:\n                            qubits_to_measure.append(index)\n                            if gate == 'X':\n                                meas_basis_change.inst(RY(-np.pi / 2, index))\n                            elif gate == 'Y':\n                                meas_basis_change.inst(RX(np.pi / 2, index))\n\n                            meas_outcome = \\\n                                expectation_from_sampling(pyquil_prog + meas_basis_change,\n                                                          qubits_to_measure,\n                                                          qvm,\n                                                          samples)\n\n                    expectation += term.coefficient * meas_outcome\n\n                return expectation.real\n\n\ndef parity_even_p(state, marked_qubits):\n    \"\"\"\n    Calculates the parity of elements at indexes in marked_qubits\n\n    Parity is relative to the binary representation of the integer state.\n\n    :param state: The wavefunction index that corresponds to this state.\n    :param marked_qubits: The indexes to be considered in the parity sum.\n    :returns: A boolean corresponding to the parity.\n    \"\"\"\n    assert isinstance(state, int), \"{} is not an integer. Must call \" \\\n                                   \"parity_even_p with an integer \" \\\n                                   \"state.\".format(state)\n    mask = 0\n    for q in marked_qubits:\n        mask |= 1 << q\n    return bin(mask & state).count(\"1\") % 2 == 0\n\n\ndef expectation_from_sampling(pyquil_program, marked_qubits, qvm, samples):\n    \"\"\"\n    Calculation of Z_{i} at marked_qubits\n\n    Given a wavefunctions, this calculates the expectation value of the Zi\n    operator where i ranges over all the qubits given in marked_qubits.\n\n    :param pyquil_program: pyQuil program generating some state\n    :param marked_qubits: The qubits within the support of the Z pauli\n                          operator whose expectation value is being calculated\n    :param qvm: A QVM connection.\n    :param samples: Number of bitstrings collected to calculate expectation\n                    from sampling.\n    :returns: The expectation value as a float.\n    \"\"\"\n    # construct program to measure\n    for qindex in marked_qubits:\n        pyquil_program.measure(qindex, qindex)\n\n    bitstring_samples = qvm.run(pyquil_program, range(max(marked_qubits) + 1), trials=samples)\n    bitstring_tuples = list(map(tuple, bitstring_samples))\n\n    freq = Counter(bitstring_tuples)\n\n    # perform weighted average\n    expectation = 0\n    for bitstring, count in freq.items():\n        bitstring_int = int(\"\".join([str(x) for x in bitstring[::-1]]), 2)\n        if parity_even_p(bitstring_int, marked_qubits):\n            expectation += float(count)/samples\n        else:\n            expectation -= float(count)/samples\n    return expectation\n", "meta": {"hexsha": "c490beca5d9b530d7502b987dabd095a2cad32a2", "size": 14455, "ext": "py", "lang": "Python", "max_stars_repo_path": "grove/pyvqe/vqe.py", "max_stars_repo_name": "msohaibalam/grove", "max_stars_repo_head_hexsha": "8c27a5d12923d6ace57956db6a249e8d01e33f35", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-15T15:40:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-15T15:40:49.000Z", "max_issues_repo_path": "grove/pyvqe/vqe.py", "max_issues_repo_name": "msohaibalam/grove", "max_issues_repo_head_hexsha": "8c27a5d12923d6ace57956db6a249e8d01e33f35", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grove/pyvqe/vqe.py", "max_forks_repo_name": "msohaibalam/grove", "max_forks_repo_head_hexsha": "8c27a5d12923d6ace57956db6a249e8d01e33f35", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-27T16:20:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-27T16:20:00.000Z", "avg_line_length": 43.9361702128, "max_line_length": 94, "alphanum_fraction": 0.5834659287, "include": true, "reason": "import numpy", "num_tokens": 2858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.19923329715255286}}
{"text": "import collections\nimport logging\nimport random\nfrom dataclasses import dataclass\nfrom typing import Any, List, Tuple, cast\n\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow.keras as keras\nfrom srl.base.define import RLObservationType\nfrom srl.base.env.base import EnvRun\nfrom srl.base.rl.algorithms.discrete_action import DiscreteActionConfig, DiscreteActionWorker\nfrom srl.base.rl.base import RLParameter, RLTrainer\nfrom srl.base.rl.registration import register\nfrom srl.base.rl.remote_memory import PriorityExperienceReplay\nfrom srl.rl.functions.common import (\n    create_beta_list,\n    create_epsilon_list,\n    create_gamma_list,\n    inverse_rescaling,\n    render_discrete_action,\n    rescaling,\n)\nfrom srl.rl.functions.dueling_network import create_dueling_network_layers\nfrom srl.rl.functions.model import ImageLayerType, create_input_layers\nfrom tensorflow.keras import layers as kl\n\nlogger = logging.getLogger(__name__)\n\n\"\"\"\nDQN\n    window_length       : o (config selection)\n    Target Network      : o\n    Huber loss function : o\n    Delay update Target Network: o\n    Experience Replay   : o\n    Frame skip          : -\n    Annealing e-greedy  : x\n    Reward clip         : x\n    Image preprocessor  : -\nRainbow\n    Double DQN               : o (config selection)\n    Priority Experience Reply: o (config selection)\n    Dueling Network          : o (config selection)\n    Multi-Step learning      : x\n    Noisy Network            : x\n    Categorical DQN          : x\nRecurrent Replay Distributed DQN(R2D2)\n    LSTM                     : x\n    Value function rescaling : o\nNever Give Up(NGU)\n    Intrinsic Reward : o\n    UVFA             : TODO\n    Retrace          : x\nAgent57\n    Meta controller(sliding-window UCB) : o\n    Intrinsic Reward split              : o\nOther\n    invalid_actions : TODO\n\"\"\"\n\n\n# ------------------------------------------------------\n# config\n# ------------------------------------------------------\n@dataclass\nclass Config(DiscreteActionConfig):\n\n    # test\n    test_epsilon: float = 0\n    test_beta: float = 0\n\n    # model\n    window_length: int = 1\n    hidden_layer_sizes: Tuple[int, ...] = (512,)\n    activation: str = \"relu\"\n    image_layer_type: ImageLayerType = ImageLayerType.DQN\n    batch_size: int = 32\n    q_ext_lr: float = 0.001\n    q_int_lr: float = 0.001\n    target_model_update_interval: int = 100\n\n    # double dqn\n    enable_double_dqn: bool = True\n\n    # DuelingNetwork\n    enable_dueling_network: bool = True\n    dueling_network_type: str = \"average\"\n\n    # Priority Experience Replay\n    capacity: int = 100_000\n    memory_name: str = \"RankBaseMemory\"\n    memory_warmup_size: int = 1000\n    memory_alpha: float = 0.6\n    memory_beta_initial: float = 0.4\n    memory_beta_steps: int = 1_000_000\n\n    # ucb(160,0.5 or 3600,0.01)\n    actor_num: int = 32\n    ucb_window_size: int = 160  # UCB上限\n    ucb_epsilon: float = 0.5  # UCBを使う確率\n    ucb_beta: float = 1  # UCBのβ\n\n    # episodic\n    episodic_lr: float = 0.0005\n    episodic_count_max: int = 10  # k\n    episodic_epsilon: float = 0.001\n    episodic_cluster_distance: float = 0.008\n    episodic_memory_capacity: int = 30000\n    episodic_pseudo_counts: float = 0.1  # 疑似カウント定数\n\n    # lifelong\n    lifelong_lr: float = 0.00001\n    lifelong_max: float = 5.0  # L\n\n    dummy_state_val: float = 0.0\n\n    def __post_init__(self):\n        super().__init__()\n\n    @property\n    def observation_type(self) -> RLObservationType:\n        return RLObservationType.CONTINUOUS\n\n    @staticmethod\n    def getName() -> str:\n        return \"Agent57_light\"\n\n    def assert_params(self) -> None:\n        super().assert_params()\n        assert self.window_length > 0\n        assert self.memory_warmup_size < self.capacity\n        assert self.batch_size < self.memory_warmup_size\n        assert len(self.hidden_layer_sizes) > 0\n\n\nregister(\n    Config,\n    __name__ + \":RemoteMemory\",\n    __name__ + \":Parameter\",\n    __name__ + \":Trainer\",\n    __name__ + \":Worker\",\n)\n\n\n# ------------------------------------------------------\n# RemoteMemory\n# ------------------------------------------------------\nclass RemoteMemory(PriorityExperienceReplay):\n    def __init__(self, *args):\n        super().__init__(*args)\n        self.config = cast(Config, self.config)\n\n        self.init(\n            self.config.memory_name,\n            self.config.capacity,\n            self.config.memory_alpha,\n            self.config.memory_beta_initial,\n            self.config.memory_beta_steps,\n        )\n\n\n# ------------------------------------------------------\n# network\n# ------------------------------------------------------\nclass _QNetwork(keras.Model):\n    def __init__(self, config: Config):\n        super().__init__()\n\n        in_state, c = create_input_layers(\n            config.window_length,\n            config.observation_shape,\n            config.env_observation_type,\n            config.image_layer_type,\n        )\n\n        for i in range(len(config.hidden_layer_sizes) - 1):\n            c = kl.Dense(\n                config.hidden_layer_sizes[i],\n                activation=config.activation,\n                kernel_initializer=\"he_normal\",\n            )(c)\n\n        if config.enable_dueling_network:\n            c = create_dueling_network_layers(\n                c,\n                config.nb_actions,\n                config.hidden_layer_sizes[-1],\n                config.dueling_network_type,\n                activation=config.activation,\n            )\n        else:\n            c = kl.Dense(config.hidden_layer_sizes[-1], activation=config.activation, kernel_initializer=\"he_normal\")(\n                c\n            )\n            c = kl.Dense(\n                config.nb_actions, kernel_initializer=\"truncated_normal\", bias_initializer=\"truncated_normal\"\n            )(c)\n\n        self.model = keras.Model(in_state, c)\n\n        # 重みを初期化\n        dummy_state = np.zeros(shape=(1, config.window_length) + config.observation_shape, dtype=np.float32)\n        val = self(dummy_state)\n        assert val.shape == (1, config.nb_actions)\n\n    def call(self, state):\n        return self.model(state)\n\n\n# ------------------------------------------------------\n# エピソード記憶部(episodic_reward)\n# ------------------------------------------------------\nclass _EmbeddingNetwork(keras.Model):\n    def __init__(self, config: Config):\n        super().__init__()\n\n        in_state, c = create_input_layers(\n            config.window_length,\n            config.observation_shape,\n            config.env_observation_type,\n            config.image_layer_type,\n        )\n\n        c = kl.Dense(\n            32, activation=\"relu\", kernel_initializer=\"he_normal\", bias_initializer=keras.initializers.constant(0.001)\n        )(c)\n        self.model = keras.Model(in_state, c)\n\n        # out layer\n        self.concatenate = kl.Concatenate()\n        self.d1 = kl.Dense(128, activation=\"relu\", kernel_initializer=\"he_normal\")\n        c = kl.LayerNormalization()(c)\n        self.out = kl.Dense(config.nb_actions, activation=\"softmax\")\n\n        # 重みを初期化\n        dummy_state = np.zeros(shape=(1, config.window_length) + config.observation_shape, dtype=np.float32)\n        val = self(dummy_state, dummy_state)\n        assert val.shape == (1, config.nb_actions)\n\n    def call(self, state1, state2):\n        c1 = self.model(state1)\n        c2 = self.model(state2)\n        c = self.concatenate([c1, c2])\n        c = self.d1(c)\n        c = self.out(c)\n        return c\n\n    def predict(self, state):\n        return self.model(state)\n\n\n# ------------------------------------------------------\n# 生涯記憶部(life long novelty module)\n# ------------------------------------------------------\nclass _LifelongNetwork(keras.Model):\n    def __init__(self, config: Config):\n        super().__init__()\n\n        in_state, c = create_input_layers(\n            config.window_length,\n            config.observation_shape,\n            config.env_observation_type,\n            config.image_layer_type,\n        )\n\n        c = kl.Dense(\n            128,\n            activation=\"relu\",\n            kernel_initializer=\"he_normal\",\n            bias_initializer=\"he_normal\",\n        )(c)\n        c = kl.LayerNormalization()(c)\n        self.model = keras.Model(in_state, c)\n\n        # 重みを初期化\n        dummy_state = np.zeros(shape=(1, config.window_length) + config.observation_shape, dtype=np.float32)\n        val = self(dummy_state)\n        assert val.shape == (1, 128)\n\n    def call(self, state):\n        return self.model(state)\n\n\n# ------------------------------------------------------\n# Parameter\n# ------------------------------------------------------\nclass Parameter(RLParameter):\n    def __init__(self, *args):\n        super().__init__(*args)\n        self.config = cast(Config, self.config)\n\n        self.q_ext_online = _QNetwork(self.config)\n        self.q_ext_target = _QNetwork(self.config)\n        self.q_int_online = _QNetwork(self.config)\n        self.q_int_target = _QNetwork(self.config)\n        self.emb_network = _EmbeddingNetwork(self.config)\n        self.lifelong_target = _LifelongNetwork(self.config)\n        self.lifelong_train = _LifelongNetwork(self.config)\n\n    def restore(self, data: Any) -> None:\n        self.q_ext_online.set_weights(data[0])\n        self.q_ext_target.set_weights(data[0])\n        self.q_int_online.set_weights(data[1])\n        self.q_int_target.set_weights(data[1])\n        self.emb_network.set_weights(data[2])\n        self.lifelong_target.set_weights(data[3])\n        self.lifelong_train.set_weights(data[4])\n\n    def backup(self):\n        d = [\n            self.q_ext_online.get_weights(),\n            self.q_int_online.get_weights(),\n            self.emb_network.get_weights(),\n            self.lifelong_target.get_weights(),\n            self.lifelong_train.get_weights(),\n        ]\n        return d\n\n    def summary(self):\n        self.q_ext_online.model.summary()\n        self.emb_network.summary()\n        self.lifelong_target.model.summary()\n\n    # ---------------------------------\n\n    def calc_target_q(\n        self,\n        q_online,\n        q_target,\n        rewards,\n        n_states,\n        done_list,\n        gamma_list,\n    ):\n        n_q = q_online(n_states).numpy()\n        n_q_target = q_target(n_states).numpy()\n\n        target_q = np.zeros(len(rewards))\n        for i in range(len(rewards)):\n            if done_list[i]:\n                gain = rewards[i]\n            else:\n                # DoubleDQN: indexはonlineQから選び、値はtargetQを選ぶ\n                if self.config.enable_double_dqn:\n                    n_act_idx = np.argmax(n_q[i])\n                else:\n                    n_act_idx = np.argmax(n_q_target[i])\n                maxq = n_q_target[i][n_act_idx]\n                gain = rewards[i] + gamma_list[i] * inverse_rescaling(maxq)\n            gain = rescaling(gain)\n            target_q[i] = gain\n\n        return target_q\n\n\n# ------------------------------------------------------\n# Trainer\n# ------------------------------------------------------\nclass Trainer(RLTrainer):\n    def __init__(self, *args):\n        super().__init__(*args)\n        self.config = cast(Config, self.config)\n        self.parameter = cast(Parameter, self.parameter)\n        self.remote_memory = cast(RemoteMemory, self.remote_memory)\n\n        self.q_ext_optimizer = keras.optimizers.Adam(learning_rate=self.config.q_ext_lr)\n        self.q_int_optimizer = keras.optimizers.Adam(learning_rate=self.config.q_int_lr)\n        self.q_loss = keras.losses.Huber()\n\n        self.emb_optimizer = keras.optimizers.Adam(learning_rate=self.config.episodic_lr)\n        self.emb_loss = keras.losses.MeanSquaredError()\n\n        self.lifelong_optimizer = keras.optimizers.Adam(learning_rate=self.config.lifelong_lr)\n        self.lifelong_loss = keras.losses.MeanSquaredError()\n\n        self.beta_list = create_beta_list(self.config.actor_num)\n        self.gamma_list = create_gamma_list(self.config.actor_num)\n        self.epsilon_list = create_epsilon_list(self.config.actor_num)\n\n        self.train_count = 0\n\n    def get_train_count(self):\n        return self.train_count\n\n    def train(self):\n\n        if self.remote_memory.length() < self.config.memory_warmup_size:\n            return {}\n\n        indices, batchs, weights = self.remote_memory.sample(self.train_count, self.config.batch_size)\n        td_error, info = self._train_on_batchs(batchs, weights)\n        priorities = abs(td_error) + 0.0001\n        self.remote_memory.update(indices, batchs, priorities)\n\n        # targetと同期\n        if self.train_count % self.config.target_model_update_interval == 0:\n            self.parameter.q_ext_target.set_weights(self.parameter.q_ext_online.get_weights())\n            self.parameter.q_int_target.set_weights(self.parameter.q_int_online.get_weights())\n\n        self.train_count += 1\n        info[\"priority\"] = np.mean(priorities)\n        return info\n\n    def _train_on_batchs(self, batchs, weights):\n\n        # データ形式を変形\n        states = []\n        actions = []\n        n_states = []\n        rewards_ext = []\n        rewards_int = []\n        done_list = []\n        gamma_list = []\n        beta_list = []\n        for b in batchs:\n            states.append(b[\"states\"][:-1])\n            actions.append(b[\"action\"])\n            n_states.append(b[\"states\"][1:])\n            rewards_ext.append(b[\"reward_ext\"])\n            rewards_int.append(b[\"reward_int\"])\n            done_list.append(b[\"done\"])\n            gamma_list.append(self.gamma_list[b[\"actor\"]])\n            beta_list.append(self.beta_list[b[\"actor\"]])\n\n        states = np.asarray(states)\n        n_states = np.asarray(n_states)\n        rewards_ext = np.asarray(rewards_ext)\n        rewards_int = np.asarray(rewards_int)\n\n        actions_onehot = tf.one_hot(actions, self.config.nb_actions)\n\n        # ----------------------------------------\n        # Q network\n        # ----------------------------------------\n        _params = [\n            states,\n            n_states,\n            actions_onehot,\n            done_list,\n            weights,\n            gamma_list,\n        ]\n        td_error_ext, loss_ext = self._update_q(\n            self.parameter.q_ext_online,\n            self.parameter.q_ext_target,\n            self.q_ext_optimizer,\n            rewards_ext,\n            *_params,\n        )\n        td_error_int, loss_int = self._update_q(\n            self.parameter.q_int_online,\n            self.parameter.q_int_target,\n            self.q_int_optimizer,\n            rewards_int,\n            *_params,\n        )\n        td_errors = td_error_ext\n        # td_errors = td_error_ext + beta_list * td_error_int\n\n        # ----------------------------------------\n        # embedding network\n        # ----------------------------------------\n        with tf.GradientTape() as tape:\n            actions_probs = self.parameter.emb_network(states, n_states)\n            emb_loss = self.emb_loss(actions_probs, actions_onehot)\n\n        grads = tape.gradient(emb_loss, self.parameter.emb_network.trainable_variables)\n        self.emb_optimizer.apply_gradients(zip(grads, self.parameter.emb_network.trainable_variables))\n\n        # ----------------------------------------\n        # lifelong network\n        # ----------------------------------------\n        lifelong_target_val = self.parameter.lifelong_target(states)\n        with tf.GradientTape() as tape:\n            lifelong_train_val = self.parameter.lifelong_train(states)\n            lifelong_loss = self.lifelong_loss(lifelong_target_val, lifelong_train_val)\n\n        grads = tape.gradient(lifelong_loss, self.parameter.lifelong_train.trainable_variables)\n        self.lifelong_optimizer.apply_gradients(zip(grads, self.parameter.lifelong_train.trainable_variables))\n\n        return td_errors, {\n            \"loss_ext\": loss_ext,\n            \"loss_int\": loss_int,\n            \"emb_loss\": emb_loss.numpy(),\n            \"lifelong_loss\": lifelong_loss.numpy(),\n        }\n\n    def _update_q(\n        self,\n        q_online,\n        q_target,\n        optimizer,\n        rewards,\n        #\n        states,\n        n_states,\n        actions_onehot,\n        done_list,\n        weights,\n        gamma_list,\n    ):\n        target_q = self.parameter.calc_target_q(\n            q_online,\n            q_target,\n            rewards,\n            n_states,\n            done_list,\n            gamma_list,\n        )\n\n        with tf.GradientTape() as tape:\n            q = q_online(states)\n            q = tf.reduce_sum(q * actions_onehot, axis=1)\n            loss = self.q_loss(target_q * weights, q * weights)\n\n        grads = tape.gradient(loss, q_online.trainable_variables)\n        optimizer.apply_gradients(zip(grads, q_online.trainable_variables))\n\n        td_error = (target_q - q).numpy()\n        loss = loss.numpy()\n\n        return td_error, loss\n\n\n# ------------------------------------------------------\n# Worker\n# ------------------------------------------------------\nclass Worker(DiscreteActionWorker):\n    def __init__(self, *args):\n        super().__init__(*args)\n        self.config = cast(Config, self.config)\n        self.parameter = cast(Parameter, self.parameter)\n        self.remote_memory = cast(RemoteMemory, self.remote_memory)\n\n        self.dummy_state = np.full(self.config.observation_shape, self.config.dummy_state_val, dtype=np.float32)\n\n        # actor\n        self.beta_list = create_beta_list(self.config.actor_num)\n        self.epsilon_list = create_epsilon_list(self.config.actor_num)\n        self.gamma_list = create_gamma_list(self.config.actor_num)\n\n        # ucb\n        self.actor_index = -1\n        self.ucb_recent = []\n        self.ucb_actors_count = [1 for _ in range(self.config.actor_num)]  # 1回は保証\n        self.ucb_actors_reward = [0.0 for _ in range(self.config.actor_num)]\n\n    def call_on_reset(self, state: np.ndarray, invalid_actions: List[int]) -> None:\n        if self.training:\n            # エピソード毎に actor を決める\n            self.actor_index = self._calc_actor_index()\n            self.beta = self.beta_list[self.actor_index]\n            self.epsilon = self.epsilon_list[self.actor_index]\n            self.gamma = self.gamma_list[self.actor_index]\n\n        else:\n            self.epsilon = self.config.test_epsilon\n            self.beta = self.config.test_beta\n\n        self.recent_states = [self.dummy_state for _ in range(self.config.window_length + 1)]\n        self.recent_states.pop(0)\n        self.recent_states.append(state)\n        self.invalid_actions = invalid_actions\n\n        # Q値取得用\n        self.onehot_actor_idx = tf.one_hot(np.array(self.actor_index), self.config.actor_num)[np.newaxis, ...]\n\n        # sliding-window UCB 用に報酬を保存\n        self.episode_reward = 0.0\n\n        # エピソードメモリ(エピソード毎に初期化)\n        self.episodic_memory = collections.deque(maxlen=self.config.episodic_memory_capacity)\n\n    # (sliding-window UCB)\n    def _calc_actor_index(self) -> int:\n\n        # UCB計算用に保存\n        if self.actor_index != -1:\n            self.ucb_recent.append(\n                (\n                    self.actor_index,\n                    self.episode_reward,\n                )\n            )\n            self.ucb_actors_count[self.actor_index] += 1\n            self.ucb_actors_reward[self.actor_index] += self.episode_reward\n            if len(self.ucb_recent) >= self.config.ucb_window_size:\n                d = self.ucb_recent.pop(0)\n                self.ucb_actors_count[d[0]] -= 1\n                self.ucb_actors_reward[d[0]] -= d[1]\n\n        N = len(self.ucb_recent)\n\n        # 全て１回は実行\n        if N < self.config.actor_num:\n            return N\n\n        # ランダムでactorを決定\n        if random.random() < self.config.ucb_epsilon:\n            return random.randint(0, self.config.actor_num - 1)\n\n        # UCB値を計算\n        ucbs = []\n        for i in range(self.config.actor_num):\n            n = self.ucb_actors_count[i]\n            u = self.ucb_actors_reward[i] / n\n            ucb = u + self.config.ucb_beta * np.sqrt(np.log(N) / n)\n            ucbs.append(ucb)\n\n        # UCB値最大のポリシー（複数あればランダム）\n        return random.choice(np.where(ucbs == np.max(ucbs))[0])\n\n    def call_policy(self, _state: np.ndarray, invalid_actions: List[int]) -> int:\n        state = np.asarray([self.recent_states[1:]])\n\n        q_ext = self.parameter.q_ext_online(state)[0].numpy()\n        q_int = self.parameter.q_int_online(state)[0].numpy()\n        q = q_ext + self.beta * q_int\n\n        if random.random() < self.epsilon:\n            self.action = random.choice([a for a in range(self.config.nb_actions) if a not in invalid_actions])\n        else:\n            # valid actions以外は -inf にする\n            q = [(-np.inf if a in invalid_actions else v) for a, v in enumerate(q)]\n\n            # 最大値を選ぶ（複数はほぼないので無視）\n            self.action = int(np.argmax(q))\n\n        self.q_ext = q_ext[self.action]\n        self.q = q[self.action]\n        return self.action\n\n    def call_on_step(\n        self,\n        next_state: np.ndarray,\n        reward_ext: float,\n        done: bool,\n        next_invalid_actions: List[int],\n    ):\n        self.episode_reward += reward_ext\n\n        self.recent_states.pop(0)\n        self.recent_states.append(next_state)\n        self.invalid_actions = next_invalid_actions\n\n        # 内部報酬\n        n_s = np.asarray([self.recent_states[1:]])\n        episodic_reward = self._calc_episodic_reward(n_s)\n        lifelong_reward = self._calc_lifelong_reward(n_s)\n        reward_int = episodic_reward * lifelong_reward\n\n        _info = {\n            \"episodic\": episodic_reward,\n            \"lifelong\": lifelong_reward,\n            \"reward_int\": reward_int,\n        }\n        if not self.training:\n            return _info\n\n        batch = {\n            \"states\": self.recent_states[:],\n            \"action\": self.action,\n            \"reward_ext\": reward_ext,\n            \"reward_int\": reward_int,\n            \"done\": done,\n            \"actor\": self.actor_index,\n            \"next_invalid_actions\": next_invalid_actions,\n        }\n\n        # priority\n        if self.config.memory_name == \"ReplayMemory\":\n            priority = 0\n        elif not self.distributed:\n            priority = 0\n        else:\n            _params = [\n                n_s,\n                [done],\n                [self.gamma],\n            ]\n            target_q_ext = self.parameter.calc_target_q(\n                self.parameter.q_ext_online,\n                self.parameter.q_ext_target,\n                [reward_ext],\n                *_params,\n            )\n            if True:\n                priority = abs(target_q_ext - self.q_ext) + 0.0001\n            else:\n                target_q_int = self.parameter.calc_target_q(\n                    self.parameter.q_int_online,\n                    self.parameter.q_int_target,\n                    [reward_int],\n                    *_params,\n                )\n                priority = abs((target_q_ext + self.beta * target_q_int) - self.q) + 0.0001\n\n        self.remote_memory.add(batch, priority)\n\n        _info[\"priority\"] = priority\n        return _info\n\n    def _calc_episodic_reward(self, state):\n        k = self.config.episodic_count_max\n        epsilon = self.config.episodic_epsilon\n        cluster_distance = self.config.episodic_cluster_distance\n        c = self.config.episodic_pseudo_counts\n\n        # 埋め込み関数から制御可能状態を取得\n        cont_state = self.parameter.emb_network.predict(state)[0].numpy()\n\n        # 初回\n        if len(self.episodic_memory) == 0:\n            self.episodic_memory.append(cont_state)\n            return 1 / c\n\n        # エピソードメモリ内の全要素とユークリッド距離を求める\n        euclidean_list = [np.linalg.norm(m - cont_state, ord=2) for m in self.episodic_memory]\n\n        # エピソードメモリに制御可能状態を追加\n        self.episodic_memory.append(cont_state)\n\n        # 近いk個を対象\n        euclidean_list = np.sort(euclidean_list)[:k]\n\n        # 上位k個の移動平均を出す\n        mode_ave = np.mean(euclidean_list)\n        if mode_ave == 0.0:\n            # ユークリッド距離は正なので平均0は全要素0のみ\n            dn = euclidean_list\n        else:\n            dn = euclidean_list / mode_ave  # 正規化\n\n        # 一定距離以下を同じ状態とする\n        dn = np.maximum(dn - cluster_distance, 0)\n\n        # 訪問回数を計算(Dirac delta function の近似)\n        dn = epsilon / (dn + epsilon)\n        N = np.sum(dn)\n\n        # 報酬の計算\n        reward = 1 / (np.sqrt(N) + c)\n        return reward\n\n    def _calc_lifelong_reward(self, state):\n        # RND取得\n        rnd_target_val = self.parameter.lifelong_target(state)[0]\n        rnd_train_val = self.parameter.lifelong_train(state)[0]\n\n        # MSE\n        error = np.square(rnd_target_val - rnd_train_val).mean()\n        reward = 1 + error\n\n        if reward < 1:\n            reward = 1\n        if reward > self.config.lifelong_max:\n            reward = self.config.lifelong_max\n\n        return reward\n\n    def call_render(self, env: EnvRun) -> None:\n        state = np.asarray([self.recent_states[1:]])\n        q_ext = self.parameter.q_ext_online(state)[0].numpy()\n        q_int = self.parameter.q_int_online(state)[0].numpy()\n        q = q_ext + self.beta * q_int\n        invalid_actions = self.get_invalid_actions(env)\n\n        maxa = np.argmax(q)\n\n        def _render_sub(a: int) -> str:\n            return f\"{q[a]:5.3f} = {q_ext[a]:5.3f} + {self.beta} * {q_int[a]:5.3f}\"\n\n        render_discrete_action(invalid_actions, maxa, env, _render_sub)\n", "meta": {"hexsha": "f014cfcd5d40e79af7426edcf87e88a7a0709041", "size": 25155, "ext": "py", "lang": "Python", "max_stars_repo_path": "srl/rl/agent57_light.py", "max_stars_repo_name": "pocokhc/simple_rl", "max_stars_repo_head_hexsha": "765f12f392f87e6897027905d74f1bced6a2b7bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-01T09:16:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T09:16:57.000Z", "max_issues_repo_path": "srl/rl/agent57_light.py", "max_issues_repo_name": "pocokhc/simple_rl", "max_issues_repo_head_hexsha": "765f12f392f87e6897027905d74f1bced6a2b7bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "srl/rl/agent57_light.py", "max_forks_repo_name": "pocokhc/simple_rl", "max_forks_repo_head_hexsha": "765f12f392f87e6897027905d74f1bced6a2b7bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4580645161, "max_line_length": 118, "alphanum_fraction": 0.5783740807, "include": true, "reason": "import numpy", "num_tokens": 5898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.19923329715255286}}
{"text": "#!/usr/bin/env python\n\n__author__ = \"Geoffroy Hautier, Bharat Medasani,  Danny Broberg\"\n__copyright__ = \"Copyright 2014, The Materials Project\"\n__version__ = \"1.0\"\n__maintainer__ = \"Geoffroy Hautier, Bharat Medasani\"\n__email__ = \"geoffroy@uclouvain.be, mbkumar@gmail.com\"\n__status__ = \"Development\"\n__date__ = \"November 4, 2012\"\n\nfrom math import sqrt, pi, exp\nfrom collections import defaultdict \nfrom itertools import combinations\n\nimport os\nimport numpy as np\n\nfrom pymatgen.core import Element\nfrom pymatgen.core.structure import PeriodicSite, Structure\nfrom pymatgen.entries.computed_entries import ComputedStructureEntry\nfrom pymatgen.symmetry.analyzer import SpacegroupAnalyzer\n\nfrom pycdt.corrections.finite_size_charge_correction import get_correction_freysoldt, get_correction_kumagai\nfrom pycdt.utils.parse_calculations import SingleDefectParser\nfrom pycdt.utils.units import kb, conv, hbar\n\nimport warnings\nwarnings.simplefilter('default')\n\n\ndef freysoldt_correction_from_paths( defect_file_path, bulk_file_path, dielectric,\n                                     defect_charge, plot=False):\n    \"\"\"\n    A function for performing the Freysoldt correction with a set of file paths.\n    If this correction is used, please reference Freysoldt's original paper.\n    doi: 10.1103/PhysRevLett.102.016402\n\n    Does not require transformation.json file to exist in file path.\n\n    :param defect_file_path (str): file path to defect folder of interest\n    :param bulk_file_path (str): file path to bulk folder of interest\n    :param dielectric (float or 3x3 matrix): Dielectric constant (or tensor) for the structure\n    :param defect_charge (int): charge of defect structure of interest\n    :param plot (bool): allow for plotting electrostatic potential\n    :return:\n        Dictionary of Freysoldt Correction for defect\n    \"\"\"\n    sdp = SingleDefectParser.from_paths( defect_file_path, bulk_file_path, dielectric, defect_charge)\n    _ = sdp.freysoldt_loader()\n    plt_title = os.path.join( defect_file_path,\n                             \"{}_chg_{}\".format(sdp.defect_entry.name, defect_charge)) if plot else None\n    correction = get_correction_freysoldt(sdp.defect_entry,\n                                          dielectric,\n                                          title=plt_title)\n\n    return correction\n\ndef kumagai_correction_from_paths( defect_file_path, bulk_file_path, dielectric,\n                                   defect_charge, plot=False):\n    \"\"\"\n    A function for performing the Kumagai correction with a set of file paths.\n    If this correction is used, please reference Kumagai and Oba's original paper\n    (doi: 10.1103/PhysRevB.89.195205) as well as Freysoldt's original\n    paper (doi: 10.1103/PhysRevLett.102.016402\n\n    Does not require transformation.json file to exist in file path.\n\n    :param defect_file_path (str): file path to defect folder of interest\n    :param bulk_file_path (str): file path to bulk folder of interest\n    :param dielectric (float or 3x3 matrix): Dielectric constant (or tensor) for the structure\n    :param defect_charge (int): charge of defect structure of interest\n    :param plot (bool): allow for plotting electrostatic potential\n    :return:\n        Dictionary of Kumagai Correction for defect\n    \"\"\"\n    sdp = SingleDefectParser.from_paths( defect_file_path, bulk_file_path, dielectric, defect_charge)\n    _ = sdp.kumagai_loader()\n    plt_title = os.path.join( defect_file_path,\n                             \"{}_chg_{}\".format(sdp.defect_entry.name, defect_charge)) if plot else None\n    correction = get_correction_kumagai(sdp.defect_entry,\n                                          dielectric,\n                                          title=plt_title)\n\n    return correction\n\n\n\nwarnings.warn(\"Replaced PyCDT usage of ComputedDefect objects with \"\n              \"DefectEntry objects from pymatgen.analysis.defects.core\\n\"\n              \"Will remove ComputedDefect with Version 2.5 of PyCDT.\",\n              DeprecationWarning)\nclass ComputedDefect(object):\n    \"\"\"\n    Holds all the info concerning a defect computation: \n    composition+structure, energy, correction on energy and name\n    \"\"\"\n    def __init__(self, entry_defect, site_in_bulk, multiplicity=None,\n                 supercell_size=(1, 1, 1), charge=0.0,\n                 charge_correction=0.0, other_correction=0.0, name=None):\n        \"\"\"\n        Args:\n            entry_defect: \n                An ComputedStructureEntry object corresponding to the \n                defect supercell\n            site_in_bulk: \n                Site of the defect in bulk supercell. Defect positions\n                are often required to perform posteriori corrections\n            multiplicity:\n                Multiplicity of defect site in a cell. Useful to \n                evaluate defect concentrations\n            supercell_size: \n                Size of the defect supercell in terms of unit cell\n            charge: \n                The charge of the defect\n            charge_correction: \n                Correction to the energy due to charge\n            other_correction:\n                Correction to the energy due to other factors\n            name: \n                The name of the defect\n        \"\"\"\n\n        self.entry = entry_defect\n        self.site = site_in_bulk\n        self.multiplicity = multiplicity\n        self.supercell_size = supercell_size\n        self.charge = charge\n        self.charge_correction = charge_correction # Can be added after initialization\n        self.other_correction = other_correction\n        self.name = name\n        if self.name:\n            self.full_name = self.name + \"_\" + str(charge)\n        else:\n            self.full_name = \"defect_\" + str(charge)\n\n    def as_dict(self):\n        return {'entry': self.entry.as_dict(),\n                'site': self.site.as_dict(),\n                'multiplicity': self.multiplicity,\n                'supercell_size': self.supercell_size,\n                'charge': self.charge,\n                'charge_correction': self.charge_correction,\n                'other_correction': self.other_correction,\n                'name': self.name,\n                'full_name': self.full_name,\n                '@module': self.__class__.__module__,\n                '@class': self.__class__.__name__}\n\n    @classmethod\n    def from_dict(cls, d):\n        return cls(\n                ComputedStructureEntry.from_dict(d['entry']), \n                PeriodicSite.from_dict(d['site']),\n                multiplicity=d.get('multiplicity', None),\n                supercell_size=d.get('supercell_size', [1,1,1]),\n                charge=d.get('charge', 0.0),\n                charge_correction=d.get('charge_correction', 0.0),\n                other_correction=d.get('other_correction', 0.0),\n                name=d.get('name', None))\n\n\nwarnings.warn(\"Replaced PyCDT usage of DefectsAnalyzer objects with \"\n              \"DefectPhaseDiagram objects from pymatgen.analysis.defects.thermodynamics\\n\"\n              \"Will remove DefectsAnalyzer with Version 2.5 of PyCDT.\",\n              DeprecationWarning)\nclass DefectsAnalyzer(object):\n    \"\"\"\n    a class aimed at performing standard analysis of defects\n    \"\"\"\n    def __init__(self, entry_bulk, e_vbm, mu_elts, band_gap):\n        \"\"\"\n        Args:\n            entry_bulk:\n                the bulk data as an Entry\n            e_vbm:\n                the energy of the vbm (in eV)\n            mu_elts:\n                a dictionnary of {Element:value} giving the chemical\n                potential of each element\n            band_gap:\n                the band gap (in eV)\n        \"\"\"\n        self._entry_bulk = entry_bulk\n        self._e_vbm = e_vbm\n        self._mu_elts = mu_elts\n        self._band_gap = band_gap\n        self._defects = []\n        self._formation_energies = []\n\n    def as_dict(self):\n        d = {'entry_bulk': self._entry_bulk.as_dict(),\n             'e_vbm': self._e_vbm,\n             'mu_elts': {k.symbol:v for k,v in self._mu_elts.items()},\n             'band_gap': self._band_gap,\n             'defects': [d.as_dict() for d in self._defects],\n             'formation_energies': self._formation_energies,\n             \"@module\": self.__class__.__module__,\n             \"@class\": self.__class__.__name__}\n        return d\n\n    @classmethod\n    def from_dict(cls, d):\n        struct = d['entry_bulk']['structure']\n        struct = struct if isinstance(struct, Structure) \\\n            else Structure.from_dict(struct)\n        entry_bulk = ComputedStructureEntry(struct, d['entry_bulk']['energy'])\n        analyzer = DefectsAnalyzer(\n            entry_bulk, d['e_vbm'], \n            {Element(el): d['mu_elts'][el] for el in d['mu_elts']}, d['band_gap'])\n        for ddict in d['defects']:\n            analyzer.add_computed_defect(ComputedDefect.from_dict(ddict))\n        return analyzer\n\n    def add_computed_defect(self, defect):\n        \"\"\"\n        add a parsed defect to the analyzer\n        Args:\n            defect:\n                a ComputedDefect object\n        \"\"\"\n        self._defects.append(defect)\n        self._compute_form_en()\n\n    def change_charge_correction(self, i, correction):\n        \"\"\"\n        Change the charge correction for defect at index i\n        Args:\n            i:\n                Index of defects\n            correction:\n                New correction to be applied for defect\n        \"\"\"\n        self._defects[i].charge_correction = correction\n        self._compute_form_en()\n\n    def change_other_correction(self, i, correction):\n        \"\"\"\n        Change the charge correction for defect at index i\n        Args:\n            i:\n                Index of defects\n            correction:\n                New correction to be applied for defect\n        \"\"\"\n        self._defects[i].other_correction = correction\n        self._compute_form_en()\n\n    def _get_all_defect_types(self):\n        to_return = []\n        for d in self._defects:\n            if d.name not in to_return: to_return.append(d.name)\n        return to_return\n\n    def _compute_form_en(self):\n        \"\"\"\n        compute the formation energies for all defects in the analyzer\n        \"\"\"\n        self._formation_energies = []\n        for d in self._defects:\n            #compensate each element in defect with the chemical potential\n            mu_needed_coeffs = {}\n            for elt in d.entry.composition.elements:\n                el_def_comp = d.entry.composition[elt] \n                el_blk_comp = self._entry_bulk.composition[elt]\n                mu_needed_coeffs[Element(elt)] = el_blk_comp - el_def_comp\n\n            sum_mus = 0.0\n            for elt in mu_needed_coeffs:\n                sum_mus += mu_needed_coeffs[elt] * self._mu_elts[elt]\n\n            self._formation_energies.append(\n                    d.entry.energy - self._entry_bulk.energy + \\\n                            sum_mus + d.charge*self._e_vbm + \\\n                            d.charge_correction + d.other_correction)\n\n    def correct_bg_simple(self, vbm_correct, cbm_correct):\n        \"\"\"\n        correct the band gap in the analyzer.\n        We assume the defects level remain the same when moving the \n        band edges\n        Args:\n            vbm_correct:\n                The correction on the vbm as a positive number. e.g., \n                if the VBM goes 0.1 eV down vbm_correct=0.1\n            cbm_correct:\n                The correction on the cbm as a positive number. e.g., \n                if the CBM goes 0.1 eV up cbm_correct=0.1\n\n        \"\"\"\n        self._band_gap = self._band_gap + cbm_correct + vbm_correct\n        self._e_vbm = self._e_vbm - vbm_correct\n        self._compute_form_en()\n\n    def get_transition_levels(self):\n        \"\"\"\n        Charge transition levels are computed\n        :return: Transition levels for each pair of the defects.\n        If any pair is missing, the transition level for that pair is\n        not within the band gap.\n        \"\"\"\n        xlim = (-0.5, self._band_gap+1.5)\n        nb_steps = 1000\n        x = np.arange(xlim[0], xlim[1], (xlim[1]-xlim[0])/nb_steps)\n \n        y = defaultdict(defaultdict)\n        for i, dfct in enumerate(self._defects):\n            yval = self._formation_energies[i] + dfct.charge*x\n            y[dfct.name][dfct.charge] = yval\n\n        transit_levels = defaultdict(defaultdict)\n        for dfct_name in y:\n            q_ys = y[dfct_name]\n            for qpair in combinations(q_ys.keys(), 2):\n                qpair_s = tuple(sorted(list(qpair)))\n                y_absdiff = abs(q_ys[qpair_s[1]] - q_ys[qpair_s[0]])\n                if y_absdiff.min() < 0.4:\n                    transit_levels[dfct_name][qpair_s] = x[np.argmin(y_absdiff)]\n        return transit_levels\n\n    def _get_form_energy(self, ef, i):\n        return self._formation_energies[i] + self._defects[i].charge*ef\n\n    def get_formation_energies(self, ef=0.0):\n        \"\"\"\n        Get the defect formation energies for a given Fermi level\n        Args:\n            ef:\n                the fermi level in eV (with respect to the VBM)\n        Returns:\n            a list of dict of {'name': defect name, 'charge': defect charge\n                               'energy': defect formation energy in eV}\n        \"\"\"\n        energies = []\n        i = 0\n        for i, d in enumerate(self._defects):\n            energies.append({\n                'name': d.name,\n                'charge': d.charge,\n                'energy': self._get_form_energy(ef, i)\n                })\n        return energies\n\n    def get_defects_concentration(self, temp=300, ef=0.0):\n        \"\"\"\n        Get the defect concentration for a temperature and Fermi level.\n        Note: This method has an approximation and can fail\n        [Ref: PRB 86, 144109 (2012)]\n        Args:\n            temp:\n                the temperature in K\n            Ef:\n                the fermi level in eV (with respect to the VBM)\n        Returns:\n            A list of dict of {'name': defect name, 'charge': defect charge\n                               'conc': defects concentration in m-3}\n        \"\"\"\n        conc = []\n        struct = self._entry_bulk.structure\n        for i, d in enumerate(self._defects):\n            cell_multiplier = np.prod(d.supercell_size)\n            n = d.multiplicity * cell_multiplier * 1e30 / struct.volume\n            conc.append({'name': d.name, 'charge': d.charge,\n                         'conc': n*exp(\n                             -self._get_form_energy(ef, i)/(kb*temp))})\n\n        return conc\n\n    def get_defects_concentration_old(self, temp=300, ef=0.0):\n        \"\"\"\n        get the defect concentration for a temperature and Fermi level\n        Written when the site multiplicity is not supplied with ComputedDefect\n        Args:\n            temp:\n                the temperature in K\n            Ef:\n                the fermi level in eV (with respect to the VBM)\n        Returns:\n            a list of dict of {'name': defect name, 'charge': defect charge\n                               'conc': defects concentration in m-3}\n        \"\"\"\n        conc=[]\n        spga = SpacegroupAnalyzer(self._entry_bulk.structure, symprec=1e-1)\n        struct = spga.get_symmetrized_structure()\n        i = 0\n        for d in self._defects:\n            df_coords = d.site.frac_coords\n            target_site=None\n            for s in struct.sites:\n                sf_coords = s.frac_coords\n                if abs(s.frac_coords[0]-df_coords[0]) < 0.1 \\\n                        and abs(s.frac_coords[1]-df_coords[1]) < 0.1 \\\n                        and abs(s.frac_coords[2]-df_coords[2]) < 0.1:\n                    target_site=s\n                    break\n            equiv_site_no = len(struct.find_equivalent_sites(target_site))\n            n = equiv_site_no * 1e30 / struct.volume\n            conc.append({'name': d.name, 'charge': d.charge,\n                         'conc': n*exp(\n                             -self._get_form_energy(ef, i)/(kb*temp))})\n            i += 1\n        return conc\n\n    def _get_dos(self, e, m1, m2, m3, e_ext):\n        return sqrt(2) / (pi**2*hbar**3) * sqrt(m1*m2*m3) * sqrt(e-e_ext)\n\n    def _get_dos_fd_elec(self, e, ef, t, m1, m2, m3):\n        return conv * (2.0/(exp((e-ef)/(kb*t))+1)) * \\\n               (sqrt(2)/(pi**2)) * sqrt(m1*m2*m3) * \\\n               sqrt(e-self._band_gap)\n\n    def _get_dos_fd_hole(self, e, ef, t, m1, m2, m3):\n        return conv * (exp((e-ef)/(kb*t))/(exp((e-ef)/(kb*t))+1)) * \\\n               (2.0 * sqrt(2)/(pi**2)) * sqrt(m1*m2*m3) * \\\n               sqrt(-e)\n\n    def _get_qd(self, ef, t):\n        summation = 0.0\n        for d in self.get_defects_concentration(t, ef):\n            summation += d['charge'] * d['conc']\n        return summation\n\n    def get_qi(self, ef, t, m_elec, m_hole):\n        from scipy import integrate as intgrl\n\n        elec_den_fn = lambda e: self._get_dos_fd_elec(\n                e, ef, t, m_elec[0], m_elec[1], m_elec[2])\n        hole_den_fn = lambda e: self._get_dos_fd_hole(\n                e, ef, t, m_hole[0], m_hole[1], m_hole[2])\n\n        bg = self._band_gap\n        elec_count = -intgrl.quad(elec_den_fn, bg, bg+5)[0]\n        hole_count = intgrl.quad(hole_den_fn, -5, 0.0)[0]\n\n        return elec_count + hole_count\n\n    def _get_qtot(self, ef, t, m_elec, m_hole):\n        return self._get_qd(ef, t) + self.get_qi(ef, t, m_elec, m_hole)\n\n    def get_eq_ef(self, t, m_elec, m_hole):\n        \"\"\"\n        access to equilibrium values of Fermi level and concentrations \n        in defects and carriers obtained by self-consistent solution of \n        charge balance + defect and carriers concentrations\n        Args:\n            t: temperature in K\n            m_elec: electron effective mass as a 3 value list \n                    (3 eigenvalues for the tensor)\n            m_hole:: hole effective mass as a 3 value list \n                    (3 eigenvalues for the tensor)\n        Returns:\n            a dict with {\n                'ef':eq fermi level,\n                'Qi': the concentration of carriers\n                      (positive for holes, negative for e-) in m^-3,\n                'conc': the concentration of defects as a list of dicts\n                }\n        \"\"\"\n        from scipy.optimize import bisect\n        e_vbm = self._e_vbm\n        e_cbm = self._e_vbm+self._band_gap\n        ef = bisect(lambda e:self._get_qtot(e,t,m_elec,m_hole), 0, \n                self._band_gap)\n        return {'ef': ef, 'Qi': self.get_qi(ef, t, m_elec, m_hole),\n                'QD': self._get_qd(ef,t), \n                'conc': self.get_defects_concentration(t, ef)}\n\n    def get_non_eq_ef(self, tsyn, teq, m_elec, m_hole):\n        \"\"\"\n        access to the non-equilibrium values of Fermi level and \n        concentrations in defects and carriers obtained by \n        self-consistent solution of charge balance + defect and \n        carriers concentrations\n\n        Implemented following Sun, R., Chan, M. K. Y., Kang, S., \n        and Ceder, G. (2011). doi:10.1103/PhysRevB.84.035212\n\n        Args:\n            tsyn: the synthesis temperature in K\n            teq: the temperature of use in K\n            m_elec: electron effective mass as a 3 value list \n                    (3 eigenvalues for the tensor)\n            m_hole: hole effective mass as a 3 value list \n                    (3 eigenvalues for the tensor)\n        Returns:\n            a dict with {\n                'ef':eq fermi level,\n                'Qi': the concentration of carriers\n                      (positive for holes, negative for e-) in m^-3,\n                'conc': the concentration of defects as a list of dict\n                }\n        \"\"\"\n        from scipy.optimize import bisect\n        eqsyn = self.get_eq_ef(tsyn, m_elec, m_hole)\n        cd = {}\n        for c in eqsyn['conc']:\n            if c['name'] in cd:\n                cd[c['name']] += c['conc']\n            else:\n                cd[c['name']] = c['conc']\n        ef = bisect(lambda e:self._get_non_eq_qtot(cd, e, teq, m_elec, m_hole),\n                    -1.0, self._band_gap+1.0)\n        return {'ef':ef, 'Qi':self.get_qi(ef, teq, m_elec, m_hole),\n                'conc_syn':eqsyn['conc'],\n                'conc':self._get_non_eq_conc(cd, ef, teq)}\n\n    def _get_non_eq_qd(self, cd, ef, t):\n        sum_tot = 0.0\n        for n in cd:\n            sum_d = 0.0\n            sum_q = 0.0\n            i = 0\n            for d in self._defects:\n                if d.name == n:\n                    sum_d += exp(-self._get_form_energy(ef, i)/(kb*t))\n                    sum_q += d.charge * exp(\n                            -self._get_form_energy(ef, i)/(kb*t))\n                i += 1\n            sum_tot += cd[n]*sum_q/sum_d\n        return sum_tot\n\n    def _get_non_eq_conc(self, cd, ef, t):\n        sum_tot = 0.0\n        res=[]\n        for n in cd:\n            sum_tot = 0\n            i = 0\n            for d in self._defects:\n                if d.name == n:\n                    sum_tot += exp(-self._get_form_energy(ef,i)/(kb*t))\n                i += 1\n            i=0\n            for d in self._defects:\n                if d.name == n:\n                    res.append({'name':d.name,'charge':d.charge,\n                                'conc':cd[n]*exp(-self._get_form_energy(\n                                    ef,i)/(kb*t))/sum_tot})\n                i += 1\n        return res\n\n    def _get_non_eq_qtot(self, cd, ef, t, m_elec, m_hole):\n        return self._get_non_eq_qd(cd, ef, t) + \\\n               self.get_qi(ef, t, m_elec, m_hole)\n\n    def correct_bg(self, dict_levels, vbm_correct, cbm_correct):\n        \"\"\"\n        NOTE from developers: This code uses deprecated concepts and\n            will not be used or maintained going forward (as of 12/15/2017).\n            However, we are keeping function here to allow for\n            current users to make use of it...\n\n        correct the band gap in the analyzer and make sure the levels move\n        accordingly.\n        There are two types of defects vbm_like and cbm_like and we need\n        to provide a formal oxidation state\n        The vbm-like will follow the vbm and the cbm_like the cbm. If nothing\n        is specified the defect transition level does not move\n        Args:\n            dict_levels: a dictionary of type {defect_name:\n            {'type':type_of_defect,'q*':formal_ox_state}}\n            Where type_of_defect is a string: 'vbm_like' or 'cbm_like'\n        \"\"\"\n        self._band_gap = self._band_gap + cbm_correct + vbm_correct\n        self._e_vbm = self._e_vbm - vbm_correct\n        self._compute_form_en()\n        for i in range(len(self._defects)):\n            name = self._defects[i].name\n            if not name in dict_levels:\n                continue\n\n            if dict_levels[name]['type'] == 'vbm_like':\n                z = self._defects[i].charge - dict_levels[name]['q*']\n                self._formation_energies[i] += z * vbm_correct\n            if dict_levels[name]['type'] == 'cbm_like':\n                z = dict_levels[name]['q*'] - self._defects[i].charge\n                self._formation_energies[i] +=  z * cbm_correct\n\n    def get_defect_occupancies(self):\n        \"\"\"\n        NOTE from developers: This code uses deprecated concepts and\n            will not be used or maintained going forward (as of 12/15/2017).\n            However, we are keeping function here to allow for\n            current users to make use of it...\n\n        Defect occupancies with respect to defect chargest.\n        The assumption is that the highest charge of defect numerically\n        has zero occupancy:\n        Ex: In Cr2O3, V_O has 0 occupancy for +2 q and 2 occupancy for 0 q.\n            V_{Cr} has 0 occupancy for 0 q and 3 occupancy for -3 q\n        Caution: Didn't check for semiconductor with large # of defect q's.\n        Returns:\n            Defect occupancies as a nested dict\n        \"\"\"\n        charges = defaultdict(list)\n        for dfct in self._defects:\n            charges[dfct.name].append(dfct.charge)\n\n        occupancies = defaultdict(lambda: defaultdict(int))\n        for dfct_name in charges:\n            for i, q in enumerate(sorted(charges[dfct_name], reverse=True)):\n                occupancies[dfct_name][q] = i\n            occupancies[dfct_name]['0_occupancy'] = \\\n                    sorted(charges[dfct_name], reverse=True)[0]\n        return occupancies\n", "meta": {"hexsha": "775c5ab0b3655311a7fbb59199654a007e4e92d1", "size": 24259, "ext": "py", "lang": "Python", "max_stars_repo_path": "pycdt/core/defects_analyzer.py", "max_stars_repo_name": "hitarth64/pycdt", "max_stars_repo_head_hexsha": "0b07915e9e1e78c1a5206fa8bc7b4399813f22f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2019-05-10T21:09:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T15:40:55.000Z", "max_issues_repo_path": "pycdt/core/defects_analyzer.py", "max_issues_repo_name": "hitarth64/pycdt", "max_issues_repo_head_hexsha": "0b07915e9e1e78c1a5206fa8bc7b4399813f22f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2019-05-10T21:22:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-26T13:40:35.000Z", "max_forks_repo_path": "pycdt/core/defects_analyzer.py", "max_forks_repo_name": "hitarth64/pycdt", "max_forks_repo_head_hexsha": "0b07915e9e1e78c1a5206fa8bc7b4399813f22f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2019-05-11T21:23:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:43:02.000Z", "avg_line_length": 40.1639072848, "max_line_length": 108, "alphanum_fraction": 0.5781771714, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.32766830082071396, "lm_q1q2_score": 0.19911196298672507}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 29 12:31:30 2022\n\n@author: LENOVO\n\"\"\"\n\nimport biosteam as bst\nimport thermosteam as tmo\nimport numpy as np\nfrom chaospy import distributions as shape\nimport biosteam as bst\nimport numpy as np\n# All units are explicitly defined here for transparency and easy reference\n# Naming conventions:\n#     D = Distillation column\n#     M = Mixer\n#     E = Multi effect evaporator\n#     C = Crystalliser\n#     H = Heat exchange\n#     L = Liquid-liquid extraction unit (Multi stage Mixer settlers)\n#     P = Pump (including conveying belt)\n#     R = Reactor\n#     S = Splitter (including solid/liquid separator)\n#     T = Tank or bin for storage\n#     U = Other units\n#     PS = Process specificiation, not physical units, but for adjusting streams\n#     MT = Mixing Tank\n    \n# Processes:\n#     100: Conversion\n#     200: PrimarySeparation\n#     300: SecondarySeparation\n#     400: Wastewater\n#     500: Facilities\n\n#Defining chemicals\n#ref:lactic acid code\n#Chemicals used\nWater = tmo.Chemical('Water')\n#New chemical\n#FFA = C18H34O2\n#C18H34O2 + CH3OH → C19H36O2 + H2O\n#FAME (C19H36O2)\n#WCO\n#C27H54O2 + 3CH3OH → C3H8O3 ​+ ​FAME\n#Triglyceride considered is triolein\n\n#all_chemicals.set_synonym('Tripalmitin' ,'Oil1')\n# Oil2 = tmo.Chemical()\nOil2 = tmo.Chemical('TAG', search_ID='122-32-7', phase = 'l')\n\nOil2.copy_models_from(tmo.Chemical('Water'), ['mu'])\nOil2.Hf = -1607.83*1000\n\nGlycerol = tmo.Chemical('Glycerol', search_ID='56-81-5')\nGlycerol_missing_properties = Glycerol.get_missing_properties()\nFurfural = tmo.Chemical('Furfural')\nFurfural_missing_properties = Furfural.get_missing_properties()\nfor i in Glycerol_missing_properties:\n    try:\n        Glycerol.copy_models_from(Furfural,[i])\n    except: pass\n\nCaO = tmo.Chemical('Calcium_oxide', phase = 's')\nCalcium_Sulphate = tmo.Chemical('Calcium_Sulphate', phase = 's')\n\nall_chemicals = tmo.Chemicals(['Water',\n                               'Sulphuric_acid',\n                               'Sodium_Hydroxide',\n                               'Oleic_acid',\n                               #'Tripalmitin',\n                               'Methyl_oleate',\n                                'Methanol',\n                                Oil2,\n                                CaO,\n                                Calcium_Sulphate,\n                                #'Methyl_palmitate',\n                                '112-62-9',\n                                Glycerol,\n                                ])\n\n\nall_chemicals.compile()\nall_chemicals.show()\nall_chemicals.set_synonym('Oleic_acid' ,'FFA') \nall_chemicals.set_synonym('56-81-5' ,'Glycerol') \nall_chemicals.set_synonym('122-32-7' ,'Oil2') \n#all_chemicals.set_synonym('Methyl_palmitate' ,'fame1')\nall_chemicals.set_synonym('112-62-9' ,'fame2') \n\n\n##############################Settings#########################################3\nbst.settings.set_thermo(all_chemicals)\nbst.Stream.display_units.flow = 'kg/hr'\nbst.Stream.display_units.composition = True\nGWP = 'GWP 100yr'\nbst.settings.define_impact_indicator(key=GWP, units='kg*CO2e')\nCalcium_oxide = bst.Chemical('Calcium_oxide')\nCalcium_oxide.at_state('s')\n### TODO.xxx\nCalcium_oxide.V.add_model(1e-6)\n#############################UNITS#############################################\nclass PReactor(bst.BatchBioreactor):\n    _N_ins = 1\n    _N_outs = 1\n    \n    @property\n    def effluent(self):\n        return self.outs[0]    \n    @effluent.setter\n    def effluent(self,effluent):\n        self.outs[0]=effluent       \n    \n    def __init__(self, ID='', ins=None, outs=(), thermo=None,\n                  tau=None, N=None, V=None, T= 65 + 275, P=101325,\n                  Nmin=2, Nmax=36):\n               \n        bst.BatchBioreactor.__init__(self, ID, ins, outs, thermo,\n                                    tau = tau , N = N, V = V, T = T, \n                                    P = P ,Nmin = Nmin , Nmax = Nmax)              \n        self.PR_conversion = 0.999\n    \n    def _setup(self):\n        self.reactions = tmo.SeriesReaction([\n            tmo.Rxn('Oleic_acid + Methanol -> Methyl_oleate + Water ',\n                'Oleic_acid', X =  self.PR_conversion )\n        ])\n    # def _cost(self):\n    #     density_in_kg_per_m3 =   913  \n    #     batch_vol = self.design_results['Reactor volume'] * self.V_wf\n    #     R = (batch_vol/(0.002))**0.33 #here 2 is 2L\n    #     N2 = 600*((1/R)**(2/3))\n    #     D2 = 0.4*((batch_vol*4/3.14)**0.33)\n    #     Np = 1.27\n    #     power = Np * density_in_kg_per_m3*(N2**3)*(D2**5)\n    #     self.power_utility(power)\n        \n    def _run(self):\n        feed = self.ins[0]\n        effluent = self.outs[0]        \n        effluent.copy_like(feed)              \n        self.reactions(effluent) \n        effluent.T = self.T\n        effluent.P = self.P\n        \n# Calcium oxide addition for Glycerol recovery\nclass Glycerol_recovery(bst.BatchBioreactor):\n    _N_ins = 1\n    _N_outs = 1\n    \n    @property\n    def effluent(self):\n        return self.outs[0]    \n    @effluent.setter\n    def effluent(self,effluent):\n        self.outs[0]=effluent       \n    \n    def __init__(self, ID='', ins=None, outs=(), thermo=None,\n                  tau=None, N=None, V=None, T= 60 + 275, P=101325,\n                  Nmin=2, Nmax=36):\n               \n        bst.BatchBioreactor.__init__(self, ID, ins, outs, thermo,\n                                    tau = tau , N = N, V = V, T = T, \n                                    P = P ,Nmin = Nmin , Nmax = Nmax)              \n          \n    def _setup(self):\n            self.reactions = tmo.SeriesReaction([\n                tmo.Rxn('Calcium_oxide + Sulphuric_acid -> Calcium_Sulphate + Water',\n                          'Sulphuric_acid', X = 0.999)])\n    # def _cost(self):\n    #    density_in_kg_per_m3 = 873.9  \n    #    batch_vol = self.design_results['Reactor volume'] * self.V_wf\n    #    R = (batch_vol/(0.002))**0.33 #here 2 is 2L\n    #    N2 = 600*((1/R)**(2/3))\n    #    D2 = 0.4*((batch_vol*4/3.14)**0.33)\n    #    Np = 1.27\n    #    power = Np * density_in_kg_per_m3*(N2**3)*(D2**5)\n    #    self.power_utility(power)\n       \n        \n    def _run(self):\n        feed = self.ins[0]\n        effluent = self.outs[0]        \n        effluent.copy_like(feed)              \n        self.reactions(effluent) \n        effluent.T = self.T\n        effluent.P = self.P\n        \n# Transesterification reactor\nclass TReactor(bst.BatchBioreactor):\n    _N_ins = 1\n    _N_outs = 1\n    \n    @property\n    def effluent(self):\n        return self.outs[0]    \n    @effluent.setter\n    def effluent(self,effluent):\n        self.outs[0]=effluent       \n    \n    def __init__(self, ID='', ins=None, outs=(), thermo=None,\n                  tau=None, N=None, V=None, T= 60 + 275, P=101325,\n                  Nmin=2, Nmax=36):\n               \n        bst.BatchBioreactor.__init__(self, ID, ins, outs, thermo,\n                                    tau = tau , N = N, V = V, T = T, \n                                    P = P ,Nmin = Nmin , Nmax = Nmax)              \n        self.TR_conversion = 0.999  \n    def _setup(self):\n            self.reactions = tmo.ParallelReaction([\n                # tmo.Rxn('Tripalmitin + 3Methanol -> Methyl_palmitate + Glycerol',\n                #         'Tripalmitin', \n                #         X = 0.9),\n                tmo.Rxn('Oil2 + 3Methanol -> Methyl_oleate + Glycerol',\n                        'Oil2', X = self.TR_conversion)\n            ])\n    \n    # def _cost(self):\n    #      density_in_kg_per_m3 =   913  \n    #      batch_vol = self.design_results['Reactor volume'] * self.V_wf\n    #      R = (batch_vol/(0.002))**0.33 #here 2 is 2L\n    #      N2 = 600*((1/R)**(2/3))\n    #      D2 = 0.4*((batch_vol*4/3.14)**0.33)\n    #      Np = 1.27\n    #      power = Np * density_in_kg_per_m3*(N2**3)*(D2**5)\n    #      self.power_utility(power)\n        \n    def _run(self):\n        feed = self.ins[0]\n        effluent = self.outs[0]        \n        effluent.copy_like(feed)              \n        self.reactions(effluent) \n        effluent.T = self.T\n        effluent.P = self.P           \n############################ STREAMS ##########################################  \nWCO_range = [4947,5038,5128,\n             5219,5310,5400,\n             5491,5581,5672,\n             5763,5853,5944,\n             6035,6125,6216,\n             6307,6397,6488,\n             6579,6669]\nGWP_obtained = [68.03354950443708, -18.60145643725397,]\nTotal_Collected_WCO = 6669\n#Three values 4800,5525,6475\nFFA = tmo.Chemical('Oleic_acid')\n# Oil1 = tmo.Chemical('Tripalmitin')\nOil2 = all_chemicals['Oil2']\n# FFA content is 6% of the total Oil\nCollected_WCO = bst.Stream('Collected_WCO',\n                            #Oil1 = 940/2 ,\n                            Oil2 = 940,\n                            FFA = 60, \n                            units = 'kg/hr')\n# http://dx.doi.org/10.17576/jkukm-2018-si1(2)-10\n\nCollected_WCO.set_total_flow(Total_Collected_WCO,\n                              units='kg/hr')\nFresh_water = bst.Stream('Fresh_water')\nWashed_WCO = bst.Stream('Washed_WCO')   \n#TODO.xxx change this depending on the scale up ratios\nFresh_Methanol_1 = bst.Stream('Methanol1')   \nFresh_Methanol_2 = bst.Stream('Methanol2')                 \nFresh_Sulacid = bst.Stream('Sulphuric_acid')\nFresh_Glycerol = bst.Stream('Glycerol')              \nRecycled_Methanol = bst.Stream('Recycled_Methanol')\nFresh_CaO = bst.Stream('Fresh_CaO')\n                        \n# Calcium_Sulphate = bst.Chemical('Calcium_Sulphate')\nCalcium_Sulphate.at_state('s')\nCalcium_Sulphate.V.add_model(1e-6)\nReuse_Calcium_Sulphate = bst.Stream('Reuse_Calcium_Sulphate')\n\n\n############################# SYSTEMS ##########################################\n#Tank to store Collected WCO and Water\nT101 = bst.StorageTank('T101_WCO',\n                        ins = (Collected_WCO),\n                        outs = 'WCO_to_pump')\n# P101 = bst.Pump('P101_WCO', \n#                   ins = T101-0, \n#                   outs = 'WCO_for_waterwash')\n\nT102 = bst.StorageTank('T102_Water',\n                        ins = Fresh_water,\n                        outs = 'Washing_water_to_pump')\nP102 = bst.Pump('P102_Water',\n                  ins = T102-0,\n                  outs = 'water_for_wash')\n\n# T103 = bst.MixTank('T103_Methanol',\n#                     ins = (Fresh_Methanol),\n#                     outs = 'Methanol_to_pump')\n# #TODO.xxx Check \n# P103 = bst.Pump('P103_Methanol', \n#                   ins = T103-0,\n#                   outs ='Methanol_to_reactor')\n\n# M103_Methanol = bst.Mixer('M103_Methanol_mixing',\n#                    ins = (Fresh_Methanol_1,Fresh_Methanol_2),\n#                    outs = ('Methanol_to_splitter'))\n                 \n# S1031 = bst.Splitter('S1031',\n#                       ins = M103_Methanol-0,\n#                       outs = ('Methanol_for_pretreatment',\n#                             'Methanol_for_transesterification'),\n#                       split = 0.5)\n\nT104 = bst.StorageTank('T104_Sulacid',\n                        ins = Fresh_Sulacid,\n                        outs='Sulacid_to_pump')\n\nP104 = bst.Pump('P104_Sulacid',\n                  ins = T104-0, \n                  outs='Sulacid_to_reactor')\n\nT105 = bst.StorageTank('T105_Glycerol',\n                        ins = Fresh_Glycerol,\n                        outs = 'Glycerol_to_pump')\n\nP105 = bst.Pump('P105_Glycerol',\n                  P = 110300,\n                  ins = T105-0, \n                  outs = 'Glycerol_to_scrubber')\n\n# T106 = bst.StorageTank('T106_CaO',\n#                         ins = Fresh_CaO, \n#                         vessel_type='Field erected',\n#                         outs = 'CaO_to_pump')\n\n# P106 = bst.Pump('P106_CaO',\n#                   ins = Fresh_CaO,\n#                   outs = 'CaO_for_deacidification')\n\n#############################SYTEMS AND UNITS########################\n#Mixtank to mix WCO and water\nM101 = bst.MixTank('M101', ins = (T101-0,P102-0),\n                    outs = 'Mixedfeed_for_waterwashing' )\n\n@M101.add_specification(run=True)\ndef adjust_Washing_water_flow():      \n        Fresh_water.imass['Water'] = 10 * Collected_WCO.F_mass\n\n#Splitter to seperate the water slurry from the effluent\n#Considers 2% loss of oil\nS101 = bst.units.Splitter('S101', ins=M101-0,\n                    outs=('Water_slurry',\n                          'WCO_pretreatment', \n                          ),\n                    split={'Water': 1,\n                            'Oleic_acid': 0,\n                            #'Oil1': 0.01,\n                            'Oil2': 0.02,                       \n                            }) \n\n#Mixer to mix all the streams before adding the stream to the reactor        \nM102 = bst.Mixer('M102',\n                 ins = (S101-1,Fresh_Methanol_1,P104-0),\n                 outs = 'mixedfeed_to_pretreatment') \nSul_acid_ratio = 0.0015\n#######################################################################\n@M102.add_specification(run=True)\ndef adjust_methanol():\n    b = S101.ins[0].imass['Oleic_acid'] \n    Fresh_Methanol_1.imass['Methanol'] = 3*b\n    Fresh_Sulacid.imass['Sulphuric_acid'] = Sul_acid_ratio * S101.outs[1].F_mass\n    \n#Reactor for the first esterification to reduce FFA content\n#Assumes 90% conversion  \n\nR101 = PReactor('R101',\n                  ins = M102.outs[0],\n                  outs = 'feed_to_Glycerol_scrubber', \n                  N = 4,\n                  T =  48.5 + 273.15,\n                  P = 400000,\n                  tau = 2\n                  )\n\n#Glycerol scrubber to scrub Sulacid, Methanol and Water         \nL101_H = bst.units.HXutility('L101_H',\n                              ins = R101-0,\n                              outs ='feed_to_Glycerol_scrubber',\n                              T = 65+273)     \n\nL101 = bst.MultiStageMixerSettlers('L101_Glycerol_scrubber',\n                            ins = (L101_H-0,P105-0),\n                            outs=('Methanol_extract',\n                                  'raffinate_with_pretreated_WCO',\n                                  ), \n                            N_stages = 2,                                                         \n                                  )\n@L101.add_specification(run=True)\ndef adjust_glycerol():\n    b = M102.outs[0].imass['Methanol'] \n    Fresh_Glycerol.imass['Glycerol'] = 0.547*b\n\n#Methanol recovery\nD101 = bst.units.ShortcutColumn('D101',\n                                    ins = L101-0,\n                                    outs = ('Recycled_methanol',\n                                            'Glycerol_for_recovery'),\n                                    LHK = ('Methanol','Water'),\n                                    k = 2,\n                                    P = 90000,\n                                    #P = 101325./20,\n                                    Lr = 0.99, \n                                    Hr = 0.99,\n                                    partial_condenser= False,\n                                    )\n\n@D101.add_specification\ndef D101_spec():\n    oil_mol = D101.ins[0].imol['122-32-7']\n    D101.ins[0].imol['122-32-7'] = 0\n    D101._run()\n    # D101.ins[0].imol['122-32-7'] = oil_mol\n    # D101.outs[1].imol['122-32-7'] = oil_mol\n    \nM103 = bst.Mixer('M103',\n                  ins = (D101-1,\n                         Fresh_CaO),\n                  outs = 'mixedfeed_for_deacidification'\n                  )  \n\n@M103.add_specification(run = True)\ndef adjust_CaO():\n    c = D101.outs[1].imass['Sulphuric_acid']\n    print(c)\n    # P106.outs[0].imass['Calcium_oxide'] = 5.4*c\n    Fresh_CaO.imass['Calcium_oxide'] = 5.4*c\n    \nv_for_Calcium_sulphate_prod = 1.2* M103.outs[0].F_vol\n#5.4 Kg of CaO/Kg of Sul acid\n\nR102 = Glycerol_recovery('R102',\n                          ins = M103-0,\n                          outs='effluent_to_splitter',                                 \n                          T =  50 + 273.15,\n                          tau = 3,\n                          N = 3\n                          )\n# Splitter to remove Calcium sulphate\nS103 = bst.units.Splitter('S103',\n                          R102-0,\n                          ['Reuse_Calcium_Sulphate',\n                            'Glycerol_for_recovery'],\n                      split={'Calcium_Sulphate': 1,\n                              'Methanol': 0,\n                              'Glycerol': 0,\n                              'Sulphuric_acid': 0,\n                              'Calcium_oxide': 0,\n                              'Water': 0,}\n                          )\n\nT107 = bst.StorageTank('T107_Calcium_Sulphate',\n                        ins = S103-0, \n                        outs ='co_product_CaSO4')\n\n#Reactor for transesterification\n\nM104 = bst.Mixer('M104',\n                 ins = (L101-1,D101-0,Fresh_Methanol_2),  \n                 outs = 'feed_to_transesterification')\n                 \n\nR103 = TReactor('R103',\n                 ins = M104.outs[0],\n                 outs = 'mixedfeed_to_biodiesel_rectification',                               \n                 T =  50 + 273.15,\n                 tau = 4,\n                 N = 3\n                )\n   \n@M104.add_specification(run = True)\ndef adjust_methanol_for_transesterification():\n    b =  M104.ins[0].imass['Oil2'] + M104.ins[1].imass['Oil2'] #M104.ins[0].imass['Tripalmitin'] + M104.ins[1].imass['Tripalmitin'] + \n    a = M104.ins[0].imass['Methanol'] / b\n    if a < 1.25:             \n        c = 1.25/a\n        Fresh_Methanol_2.imass['Methanol'] = c*b\n        \n#Methanol recovery after transesterification\n#TODO.xxx check how to recycle\nD102 = bst.units.ShortcutColumn('D102',\n                                ins = R103-0,\n                                outs = ('Recycled_methanol',\n                                        'Biodiesel_for_rectification'),\n                                LHK = ('Methanol','Water'),\n                                k = 4.6,\n                                # P = 80000,\n                                P = 101325/20,\n                                Lr = 0.99999, \n                                Hr = 0.99999,\n                                partial_condenser= False,\n                                    )\n\n#Splitter to remove glycerol from the biodisel\nS104 = bst.units.Splitter('S104',\n                          D102-1,\n                          ['FAME_for_recovery',\n                            'Glycerol_for_recovery'],\n                      split={'Water':0,\n                              'Sulphuric_acid':0,\n                              'Oleic_acid':1,\n                              #'Tripalmitin':1,\n                              'Methyl_oleate':1,\n                              #'Methyl_palmitate':1,\n                              'Methanol':0,\n                              '122-32-7':1,\n                              'Glycerol':1})\n\nD103_H = bst.units.HXutility('Heat_exchanger_for_biodiesel_rectification',\n                        ins = S104-0, T = 460\n                        )\n\nD103 = bst.units.ShortcutColumn('D103',\n                               ins = D103_H-0,\n                               outs = ('Glycerol_for_recovery',\n                                       'BIODIESEL',\n                                       ),\n                               LHK = ('Glycerol',\n                                        'Methyl_oleate'),\n                               k = 2,  \n                               # P = 80000,\n                               P=101325/20,\n                               Lr = 0.95, \n                               Hr = 0.9,\n                               partial_condenser= False\n                                  )\n# Splitter_Final = bst.units.Splitter('S_final',\n#                                     D103-1,\n#                                     ['Biodiesel',\n#                                      'Waste_oil'],\n#                                     split={'Water':0,\n#                                            'Sulphuric_acid':0,\n#                                            'Oleic_acid':0,\n#                                            #'Tripalmitin':1,\n#                                            'Methyl_oleate':1,\n#                                            #'Methyl_palmitate':1,\n#                                            'Methanol':0,\n#                                            '122-32-7':0,\n#                                            'Glycerol':0})\n\n##################################STORAGE TANKS ###############################\nT108 = bst.MixTank('Waste_Glycerol',ins=(D103-0,S103-1))\nT109 = bst.MixTank('Waste_Methanol',ins= (D102-0,S104-1))\nT110 = bst.units.StorageTank('Biodiesel',ins=D103-1)\n#################################System simulation ############################\nWCO_sys = bst.main_flowsheet.create_system('WCO_sys')\nWCO_sys.operating_hours = 345 * 24\nWCO_sys.diagram(number=True)\nWCO_sys.simulate()\n\n#############################Characterisation_factors###########################\n#Collected waste cooking oil impact\n#https://v36.ecoquery.ecoinvent.org/Details/LCIA/d1f82144-4856-44f2-a56a-f01a40cc4d51/290c1f85-4cc4-4fa1-b0c8-2cb7f4276dce\nCollected_WCO.set_CF(GWP, 0.26797)\n#Sulphuric_acid impact\nFresh_Sulacid.set_CF(GWP,0.084321)\n#Water\n#https://v36.ecoquery.ecoinvent.org/Details/LCIA/979d50d1-eca2-4399-9805-e9fb36c9e463/290c1f85-4cc4-4fa1-b0c8-2cb7f4276dce\nFresh_water.set_CF(GWP, 0.00079796)\n#Methanol_GWP\nFresh_Methanol_1.set_CF(GWP,0.65534)\n##above is an assump\nFresh_Methanol_2.set_CF(GWP,0.65534)\n#Electricity impact from biosteam\nbst.PowerUtility.set_CF(GWP,0.38) \n#STEAM: https://v36.ecoquery.ecoinvent.org/Details/LCIA/50cb253a-839c-494a-b98e-5ac2f3dc8e07/290c1f85-4cc4-4fa1-b0c8-2cb7f4276dce\nbst.HeatUtility.set_CF('low_pressure_steam', GWP, 88.44, basis='MMBtu')\n# NaOH GWP\n#NaOH.set_CF(GWP,1.3106)\n#CaO GWO\n#below is an assum\nFresh_CaO.set_CF(GWP,0.1396)\n#Waste_gypsum CF = 0.0091162\n#Wastewater_CF =  11.432\n#Glycerol GWP\t\nFresh_Glycerol.set_CF(GWP, 0.2588)\n\nwaste_methanol_value = 0.65534*WCO_sys.get_mass_flow(T109.outs[0])\n\nwaste_Glycerol_value = 0.2588*WCO_sys.get_mass_flow(T108.outs[0])\n\n#https://v36.ecoquery.ecoinvent.org/Details/LCIA/f38b101d-77d0-4940-b775-5a3cd38f9f6d/290c1f85-4cc4-4fa1-b0c8-2cb7f4276dce\n#https://v36.ecoquery.ecoinvent.org/Details/LCIA/ddf1244d-1051-47b3-96a3-5404d1036524/290c1f85-4cc4-4fa1-b0c8-2cb7f4276dce\nwaste_Water_value = 4.186* WCO_sys.get_mass_flow(S101.outs[0])\nwaste_CaSO4_value = 0.1396*WCO_sys.get_mass_flow(T107.outs[0])\ntotal_out_mass = WCO_sys.get_mass_flow(D103.outs[1])\nnet_waste_GWP = waste_methanol_value + waste_Glycerol_value + waste_Water_value #+ waste_CaSO4_value\nWCO_sys_net = WCO_sys.get_net_electricity_impact(GWP) + WCO_sys.get_total_feeds_impact(GWP)+WCO_sys.get_net_heat_utility_impact('low_pressure_steam', GWP)\nGWP_total_displacement = WCO_sys_net - net_waste_GWP\nGWP_total_transport = 127*4\na = GWP_total_displacement + GWP_total_transport\nb = a/total_out_mass\nprint(b)\n  \n#b = 0.035435\n# print(GWP_total_displacement/total_out_mass)\n# print('GWP/mmBTU:',a/b)\n\n#Biodiesel from WCO 37.3 (MJ/Kg)\n#1 MJ equals 947.82 BTU\n#Calorific value of 1 Kg WCO based biodiesel is 35448.36 BTU\n#Biodiesel calorific value is  0.035435 mmBTU/Kg\n#\n#B100: 119,550 Btu/ga\n#1 gal is 3.31Kg\n#119550/3.31\n\n#Residential #6 Oil; 166.7 lb/mmBtu \n#166.7*0.45360.4536/mmBtu \n# # # ####################################UNCERTAINITY ANALYSIS ########################################3\n\n# model = bst.Model(WCO_sys)\n   \n# # @model.parameter(name='Total_input_WCO',\n# #                   distribution=shape.Uniform(5000, 6000))\n# # def set_value(X):\n# #     Total_Collected_WCO = X\n# @model.parameter(name='Pretreatment_conversion',\n#                   distribution=shape.Uniform(0.9997, 0.9999))\n# def set_conversion(X):\n#     R101.PR_conversion = X\n# @model.parameter(name='Transesterification_conversion',\n#                   distribution=shape.Uniform(0.9997, 0.9999))\n# def set_conversion(X):\n#     R103.TR_conversion = X\n#     # reactor is the object, reactant conversion is not defined\n \n# @model.parameter(name='Sulphuric_acid_ratio',\n#                   distribution=shape.Uniform(0.0015, 0.003))\n# def set_SULACID_VALUE(X):\n#     Sul_acid_ratio = X\n\n# @model.metric(name = 'total_GWP_value')\n# def LCA():\n#     waste_Water_value = 4.186* WCO_sys.get_mass_flow(S101.outs[0])\n#     waste_CaSO4_value = 0.1396*WCO_sys.get_mass_flow(T107.outs[0])\n#     total_out_mass = WCO_sys.get_mass_flow(D103.outs[1])\n#     net_waste_GWP = waste_methanol_value + waste_Glycerol_value + waste_Water_value #+ waste_CaSO4_value\n#     WCO_sys_net = WCO_sys.get_net_electricity_impact(GWP) + WCO_sys.get_total_feeds_impact(GWP)+WCO_sys.get_net_heat_utility_impact('low_pressure_steam', GWP)\n#     GWP_total_displacement = WCO_sys_net - net_waste_GWP\n#     GWP_total_transport = 127*2\n#     a = GWP_total_displacement + GWP_total_transport\n#     b = a/total_out_mass\n#     return(b)\n  \n\n# np.random.seed(1234) # For consistent results\n# N_samples = 50\n# rule = 'L' # For Latin-Hypercube sampling\n# samples = model.sample(N_samples, rule)\n# model.load_samples(samples)\n# model.evaluate()\n# model.table # All evaluations are stored as a pandas DataFrame\n# print(model.table)\n\n# df_rho, df_p = model.spearman_r()\n# bst.plots.plot_spearman_1d(df_rho['Biorefinery', 'total_GWP_value'],\n#                             index=[i.describe() for i in model.parameters],\n#                             name= 'total_GWP_value') \n# =============================================================================\n#Residential fuel oil GWP 100: 0.44\n# https://v36.ecoquery.ecoinvent.org/Details/LCIA/ed9b5526-d54a-4129-bbe0-52a36f02ae99/290c1f85-4cc4-4fa1-b0c8-2cb7f4276dce\n\n\n#Calculating yield\n#MW of AA = Actual yield/Theoritical yield(188 * 3.54)\n#Density of WCO\n#1 kilogram / cubic meter = 0.001 kilograms / liter\n", "meta": {"hexsha": "b14aa20f866794af0c969fca0dbec3ac8849906a", "size": 25665, "ext": "py", "lang": "Python", "max_stars_repo_path": "BioSTEAM 2.x.x/biorefineries/ozonolysis/SUD_project.py", "max_stars_repo_name": "yoelcortes/Bioindustrial-Complex", "max_stars_repo_head_hexsha": "d39edfec88e443ef7a62218ca0215e3b105f4b96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-03T21:04:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-09T01:15:48.000Z", "max_issues_repo_path": "BioSTEAM 2.x.x/biorefineries/ozonolysis/SUD_project.py", "max_issues_repo_name": "yoelcortes/Bioindustrial-Complex", "max_issues_repo_head_hexsha": "d39edfec88e443ef7a62218ca0215e3b105f4b96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-01-03T21:31:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-28T13:53:56.000Z", "max_forks_repo_path": "BioSTEAM 2.x.x/biorefineries/ozonolysis/SUD_project.py", "max_forks_repo_name": "yoelcortes/Bioindustrial-Complex", "max_forks_repo_head_hexsha": "d39edfec88e443ef7a62218ca0215e3b105f4b96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-07T14:04:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-08T23:05:25.000Z", "avg_line_length": 38.0786350148, "max_line_length": 160, "alphanum_fraction": 0.5157218001, "include": true, "reason": "import numpy", "num_tokens": 7228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521102, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.1991059714885994}}
{"text": "##############################################################################\n#\n# Copyright (c) 2003-2018 by The University of Queensland\n# http://www.uq.edu.au\n#\n# Primary Business: Queensland, Australia\n# Licensed under the Apache License, version 2.0\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Development until 2012 by Earth Systems Science Computational Center (ESSCC)\n# Development 2012-2013 by School of Earth Sciences\n# Development from 2014 by Centre for Geoscience Computing (GeoComp)\n#\n##############################################################################\n\n\"\"\"Base classes for forward models\"\"\"\n\nfrom __future__ import division, print_function\n\n__copyright__=\"\"\"Copyright (c) 2003-2018 by The University of Queensland\nhttp://www.uq.edu.au\nPrimary Business: Queensland, Australia\"\"\"\n__license__=\"\"\"Licensed under the Apache License, version 2.0\nhttp://www.apache.org/licenses/LICENSE-2.0\"\"\"\n__url__=\"https://launchpad.net/escript-finley\"\n\n__all__ = ['ForwardModel','ForwardModelWithPotential']\n\nfrom esys.downunder.coordinates import makeTransformation\nfrom esys.escript.linearPDEs import LinearSinglePDE\nfrom esys.escript.util import *\nimport numpy as np\n\nclass ForwardModel(object):\n    \"\"\"\n    An abstract forward model that can be plugged into a cost function.\n    Subclasses need to implement `getDefect()`, `getGradient()`, and possibly\n    `getArguments()` and 'getCoordinateTransformation'.\n    \"\"\"\n    def __init__(self):\n        pass\n\n    def getArguments(self, x):\n        return ()\n\n    def getCoordinateTransformation(self):\n        return None\n\n    def getDefect(self, x, *args):\n        raise NotImplementedError\n\n    def getGradient(self, x, *args):\n        raise NotImplementedError\n\n\nclass ForwardModelWithPotential(ForwardModel):\n    \"\"\"\n    Base class for a forward model using a potential such as magnetic or\n    gravity. It defines a cost function:\n\n        defect = 1/2 sum_s integrate( ( weight_i[s] * ( r_i - data_i[s] ) )**2 )\n\n    where s runs over the survey, weight_i are weighting factors, data_i are\n    the data, and r_i are the results produced by the forward model.\n    It is assumed that the forward model is produced through postprocessing\n    of the solution of a potential PDE.\n    \"\"\"\n    def __init__(self, domain, w, data,  coordinates=None,\n                                 fixPotentialAtBottom=False,\n                                 tol=1e-8):\n        \"\"\"\n        initializes a new forward model with potential.\n\n        :param domain: domain of the model\n        :type domain: `Domain`\n        :param w: data weighting factors\n        :type w: ``Vector`` or list of ``Vector``\n        :param data: data\n        :type data: ``Vector`` or list of ``Vector``\n        :param coordinates: defines coordinate system to be used\n        :type coordinates: `ReferenceSystem` or `SpatialCoordinateTransformation`\n        :param fixPotentialAtBottom: if true potential is fixed to zero at the bottom of the domain\n                                     in addition to the top.\n        :type fixPotentialAtBottom: ``bool``\n        :param tol: tolerance of underlying PDE\n        :type tol: positive ``float``\n        \"\"\"\n        super(ForwardModelWithPotential, self).__init__()\n        self.__domain = domain\n        self.__trafo = makeTransformation(domain, coordinates)\n\n        try:\n            n=len(w)\n            m=len(data)\n            if not m == n:\n                raise ValueError(\"Length of weight and data must be the same.\")\n            self.__weight = w\n            self.__data = data\n        except TypeError:\n            self.__weight = [w]\n            self.__data = [data]\n\n        BX = boundingBox(domain)\n        DIM = domain.getDim()\n        x = domain.getX()\n        self.__pde=LinearSinglePDE(domain)\n        self.__pde.getSolverOptions().setTolerance(tol)\n        self.__pde.setSymmetryOn()\n        z=x[DIM-1]\n        q0=whereZero(z-BX[DIM-1][1])\n        if fixPotentialAtBottom: q0+=whereZero(z-BX[DIM-1][0])\n        self.__pde.setValue(q=q0)\n\n        self.edge_lengths=np.asarray(boundingBoxEdgeLengths(domain))\n        self.diameter=1./sqrt(sum(1./self.edge_lengths**2))\n\n        self.__origweight=[]\n        for s in range(len(self.__weight)):\n            # save a copy of the original weights in case of rescaling\n            self.__origweight.append(1.*self.__weight[s])\n\n        if not self.__trafo.isCartesian():\n            fd=1./self.__trafo.getScalingFactors()\n            fw=self.__trafo.getScalingFactors()*sqrt(self.__trafo.getVolumeFactor())\n            for s in range(len(self.__weight)):\n                self.__weight[s] = fw * self.__weight[s]\n                self.__data[s]   = fd * self.__data[s]\n\n    def _rescaleWeights(self, scale=1., fetch_factor=1.):\n        \"\"\"\n        rescales the weights such that\n\n        *sum_s integrate( ( weight_i[s] *data_i[s]) (weight_j[s]*1/L_j) * L**2 * fetch_factor )=scale*\n        \"\"\"\n        if not scale > 0:\n             raise ValueError(\"Value for scale must be positive.\")\n        A=0\n        # copy back original weights before rescaling\n        self.__weight=[1.*ow for ow in self.__origweight]\n\n        for s in range(len(self.__weight)):\n            if self.__data[s].getShape() == ():\n               ff=self.__weight[s]**2*self.__data[s]/length(self.edge_lengths)\n            else:\n               ff=inner(self.__weight[s], self.__data[s]) * inner(self.__weight[s], 1/self.edge_lengths)\n            A += integrate(abs(ff * fetch_factor))\n        if A > 0:\n            A=sqrt(scale/A)/self.diameter\n            if not self.__trafo.isCartesian():\n                A*=self.__trafo.getScalingFactors()*sqrt(self.__trafo.getVolumeFactor())\n            for s in range(len(self.__weight)):\n                self.__weight[s]*=A\n        else:\n            raise ValueError(\"Rescaling of weights failed.\")\n\n    def getDomain(self):\n        \"\"\"\n        Returns the domain of the forward model.\n\n        :rtype: `Domain`\n        \"\"\"\n        return self.__domain\n\n    def getMisfitWeights(self):\n        \"\"\"\n        Returns the weights of the misfit function\n          \n        :rtype: ``list`` of ``Data``\n        \"\"\"\n        return self.__weight\n\n    def getData(self):\n        \"\"\"\n        Returns the data\n\n        :rtype: ``list`` of ``Data``\n        \"\"\"\n        return self.__data\n    def getDataFunctionSpace(self):\n        \"\"\"\n        Returns the ``FunctionSpace`` of the data\n\n        :rtype: ``FunctionSpace``\n        \"\"\"\n        return self.getData()[0].getFunctionSpace()\n        \n    def getCoordinateTransformation(self):\n        \"\"\"\n        returns the coordinate transformation being used\n\n        :rtype: ``CoordinateTransformation``\n        \"\"\"\n        return self.__trafo\n\n    def getPDE(self):\n        \"\"\"\n        Return the underlying PDE.\n\n        :rtype: `LinearPDE`\n        \"\"\"\n        return self.__pde\n\n    def _getDefect(self, result):\n        \"\"\"\n        Returns the defect value.\n\n        :param result: a result vector\n        :type result: `Vector`\n        :rtype: ``float``\n        \"\"\"\n        A=0.\n        for s in range(len(self.__weight)):\n            A += integrate( inner(self.__weight[s], self.__data[s]-result)**2 )\n        return A/2\n\n    def getDefectGradient(self, result):\n        Y=0.\n        for s in range(len(self.__weight)):\n            Y = inner(self.__weight[s], self.__data[s]-result) * self.__weight[s] + Y\n        return Y\n\n    def getSurvey(self, index=None):\n        \"\"\"\n        Returns the pair (data_index, weight_index), where data_i is the data\n        of survey i, weight_i is the weighting factor for survey i.\n        If index is None, all surveys will be returned in a pair of lists.\n        \"\"\"\n        if index is None:\n            return self.__data, self.__weight\n        if index>=len(self.__data):\n            raise IndexError(\"Forward model only has %d surveys\"%len(self.__data))\n        return self.__data[index], self.__weight[index]\n\n", "meta": {"hexsha": "f67f8f89abc5023bf794a2501036b0ecab7f3b47", "size": 7939, "ext": "py", "lang": "Python", "max_stars_repo_path": "downunder/py_src/forwardmodels/base.py", "max_stars_repo_name": "markendr/esys-escript.github.io", "max_stars_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "downunder/py_src/forwardmodels/base.py", "max_issues_repo_name": "markendr/esys-escript.github.io", "max_issues_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-01-14T03:07:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-14T03:07:43.000Z", "max_forks_repo_path": "downunder/py_src/forwardmodels/base.py", "max_forks_repo_name": "markendr/esys-escript.github.io", "max_forks_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9273504274, "max_line_length": 104, "alphanum_fraction": 0.5969265651, "include": true, "reason": "import numpy", "num_tokens": 1810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.19908995650653943}}
{"text": "import numpy as np\nimport pymc3 as pm\nimport pandas as pd\n#import pickle\n#import wandb\n#import yaml\nimport warnings\nfrom sklearn.cluster import k_means\nfrom scipy.special import softmax, logsumexp, loggamma\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom .constants import * \nimport pkg_resources\n\n# constants\n#C=32\n#M=3\n#P=2\n\ndef dirichlet(node_name, a, shape, scale=1, testval = None):\n    # dirichlet reparameterized here because of stickbreaking bug\n    # https://github.com/pymc-devs/pymc3/issues/4733\n    X = pm.Gamma(f'gamma_{node_name}', mu = a, sigma = scale, shape = shape, testval = testval)\n    Y = pm.Deterministic(node_name, (X/X.sum(axis = (X.ndim-1))[...,None]))\n    return Y\n\n\ndef load_config(config_fp):\n\n    # load the yaml file \n    with open(config_fp, 'r') as f:\n        config = yaml.safe_load(f)\n        print(f\"Loaded configuration file {config_fp}\")\n\n    # remove any parameters not applicable to selected data source\n    ds = config.pop('dataset')\n    ds[ds['dataset_sel']].update({'dataset_sel': ds['dataset_sel']})\n\n    # update dataset args to subsetted list\n    config.update({'dataset': ds[ds['dataset_sel']]})\n    \n    ## handle seeding\n    #config['dataset'].update({'data_rng': np.random.default_rng(config['dataset']['data_seed'])})\n    #config['model'].update({'model_rng': np.random.default_rng(config['model']['model_seed'])})\n    \n    return config['dataset'], config['model'], config['pymc3']\n    \ndef detect_naming_style(fp):\n\n    # first column must have type at minimum\n    df = pd.read_csv(fp, index_col=0, sep = None, engine = 'python')\n    naming_style = 'unrecognized'\n    \n    # check if index is type style\n    if df.index.isin(mut96).any(): naming_style = 'type'\n\n    # check if index is type/subtype style\n    else:\n        df = df.reset_index()\n        df = df.set_index(list(df.columns[0:2]))\n        if df.index.isin(idx96).any(): naming_style = 'type/subtype'\n\n    assert naming_style == 'type' or naming_style == 'type/subtype', \\\n            'Mutation type naming style could not be identified.\\n'\\\n            '\\tExpected either two column type/subtype (ex. C>A,ACA) or\\n'\\\n            '\\tsingle column type (ex A[C>A]A). See examples at COSMIC database.'\n    \n    return naming_style\n\ndef load_sigs(fp):\n    warnings.warn(\"load_sigs is deprecated, see Damuta class\", DeprecationWarning)\n\n    naming_style = detect_naming_style(fp)\n\n    if naming_style == 'type':\n        # read in sigs\n        sigs = pd.read_csv(fp, index_col = 0, sep = None, engine = 'python').reindex(mut96)\n        # sanity check for matching mut96, should have no NA \n        sel = (~sigs.isnull()).all(axis = 1)\n        assert sel.all(), f'invalid signature definitions: null entry for types {list(sigs.index[~sel])}' \n        # convert to pcawg convention\n        sigs = sigs.set_index(idx96)\n        \n    elif naming_style == 'type/subtype':\n        # read in sigs\n        sigs = pd.read_csv(fp, index_col = (0,1), header=0).reindex(idx96)\n        # sanity check for idx, should have no NA\n        sel = (~sigs.isnull()).all(axis = 1)\n        assert sel.all(), f'invalid signature definitions: null entry for types {list(sigs.index[~sel])}' \n    \n    # check colsums are 1\n    sel = np.isclose(sigs.sum(axis=0), 1)\n    assert sel.all(), f'invalid signature definitions: does not sum to 1 in columns {list(sigs.columns[~sel])}' \n\n    assert all(sigs.index == idx96) or all(sigs.index == mut96), 'signature defintions failed to be read correctly'\n    \n    # force Jx96 and mut96 convention\n    sigs = sigs.T\n    sigs.columns = mut96\n    \n    return sigs\n\ndef load_counts(counts_fp):\n    warnings.warn(\"load_counts is deprecated, see Damuta class\", DeprecationWarning)\n    counts = pd.read_csv(counts_fp, index_col = 0, header = 0)[mut96]\n    assert counts.ndim == 2, 'Mutation counts failed to load. Check column names are mutation type (ex. A[C>A]A). See COSMIC database for more.'\n    assert counts.shape[1] == 96, f'Expected 96 mutation types, got {counts.shape[1]}'\n    return counts\n\ndef subset_samples(dataset, annotation, annotation_subset, sel_idx = 0):\n    # subset sample ids by matching to annotation_subset\n    # expect annotation_subset to be pd dataframe with ids as index\n\n    if annotation_subset is None:\n        return dataset, annotation\n\n    # stop string being auto cast to list\n    if type(annotation_subset) == str:\n        annotation_subset = [annotation_subset]\n    \n    if annotation.ndim > 2:\n        warnings.warn(f\"More than one annotation is available per sample, selection index {sel_idx}\", UserWarning)\n        \n    # annotation ids should match sample ids\n    assert dataset.index.isin(annotation.index).any(), 'No sample ID matches found in dataset for the provided annotation'\n\n    # reoder annotation (with gaps) to match dataset\n    annotation = annotation.reindex(dataset.index)\n\n    # partial matches allowed\n    sel = np.fromiter((map(any, zip(*[annotation[annotation.columns[sel_idx]].str.contains(x) for x in annotation_subset] ))), dtype = bool)\n        \n    # type should appear in the type column of the lookup \n    assert sel.any(), 'Cancer type subsetting yielded no selection. Check keywords?'\n\n    dataset = dataset.loc[annotation.index[sel]]\n    annotation = annotation.loc[annotation.index[sel]]\n    return dataset, annotation\n\ndef save_checkpoint(fp, model, trace, dataset_args, model_args, pymc3_args, run_id): \n    with open(f'{fp}', 'wb') as buff:\n        pickle.dump({'model': model, 'trace': trace, 'dataset_args': dataset_args, \n                     'model_args': model_args, 'pymc3_args': pymc3_args, 'run_id': run_id}, buff)\n    print(f'checkpoint saved to {fp}') \n       \ndef load_checkpoint(fn):\n    with open(fn, 'rb') as buff:\n        data = pickle.load(buff)\n        print(f'checkpoint loaded from {fn}') \n        wandb.init(id=data['run_id'], resume='allow')\n        return data['model'], data['trace'], data['dataset_args'], data['model_args'], data['pymc3_args'], data['run_id'] \n\ndef load_dataset(dataset_sel, counts_fp=None, annotation_fp=None, annotation_subset=None, seed=None,\n                 data_seed = None, sig_defs_fp=None, sim_S=None, sim_N=None, sim_I=None, sim_tau_hyperprior=None,\n                 sim_J=None, sim_K=None, sim_alpha_bias=None, sim_psi_bias=None, sim_gamma_bias=None, sim_beta_bias=None):\n    # load counts, or simulated data - as specified by dataset_sel\n    # seed -> rng as per https://albertcthomas.github.io/good-practices-random-number-generators/\n    \n    if dataset_sel == 'load_counts':\n        dataset = load_counts(counts_fp)\n        annotation = pd.read_csv(annotation_fp, index_col = 0, header = 0)\n        dataset, annotation = subset_samples(dataset, annotation, annotation_subset)\n        return dataset, annotation\n        \n    elif dataset_sel == 'sim_from_sigs':\n        sig_defs = load_sigs(sig_defs_fp)\n        dataset, sim_params = sim_from_sigs(sig_defs, sim_tau_hyperprior, sim_S, sim_N, sim_I, seed)\n        return dataset, sim_params\n    \n    elif dataset_sel == 'sim_parametric':\n        dataset, sim_params = sim_parametric(sim_J,sim_K,sim_S,sim_N,sim_alpha_bias,sim_psi_bias,sim_gamma_bias,sim_beta_bias,seed)\n        return dataset, sim_params\n    \n    else:\n        assert False, 'dataset selection not recognized'\n    \ndef load_datasets(dataset_args):\n    yargs = dataset_args.copy()\n    ca = [load_dataset(counts_fp = j[0], annotation_fp = j[1], **yargs) for j in zip(yargs.pop('counts_fp'), yargs.pop('annotation_fp'))]\n    counts = pd.concat([c[0] for c in ca ])\n    annotation = pd.concat([a[1] for a in ca])\n    return counts, annotation\n\ndef split_by_count(data, fraction, rng):\n    # assumes data is a pandas df\n\n    frac1 = data.apply(lambda r: rng.choice( np.repeat(np.arange(96), r), int(fraction*r.sum()), replace = False) , axis = 1)\n    frac1 = pd.DataFrame(frac1.apply(lambda r: np.histogram(r, bins=96, range=(0, 96))[0]).to_list(), \n                         index = data.index, columns = data.columns)\n    #frac1 = (data * fraction).astype(int)\n    #frac1 = frac1.apply(lambda r: np.histogram(r, bins=96, range=(0, 96))[0], axis = 1, result_type='expand')\n    #frac1.columns = data.columns\n    frac2 = data - frac1\n    assert all(frac2 >= 0) and all(frac1 >= 0)\n    assert np.all(data == frac1 + frac2), 'Splitting failed'\n    return frac1, frac2\n\ndef split_by_S(data, fraction, rng):\n    # assumes data is a pandas df with an index\n    frac1 = data.sample(frac=fraction, random_state=np.random.RandomState(rng.bit_generator))\n    frac2 = data.drop(frac1.index)\n    return frac1, frac2\n\ndef split_data(counts, S_frac = 0.9, c_frac = 0.8, rng=np.random.default_rng()):\n    # get train/val/test split\n    trn, tst = split_by_S(counts, S_frac, rng)\n    trn, val = split_by_count(trn, c_frac, rng)\n    tst1, tst2 = split_by_count(tst, c_frac, rng)\n    return trn, val, tst1, tst2\n\ndef get_tau(phi, eta):\n    assert len(phi.shape) == 2 and len(eta.shape) == 3\n    tau =  np.einsum('jpc,kpm->jkpmc', phi.reshape((-1,2,16)), eta).reshape((-1,96))\n    return tau\n\ndef get_phi(sigs):\n    # for each signature in sigs, get the corresponding phi\n    wrapped = sigs.reshape(-1, 2, 3, 16)\n    phi = wrapped.sum(2).reshape(-1,32)\n    return phi\n\ndef get_eta(sigs):\n    # for each signature in sigs, get the corresponding eta \n    wrapped = sigs.reshape(-1, 6, 16)\n    eta = wrapped.sum(2).reshape(-1,3)\n    # notrmalize such that etaC and etaT sum to 1 respectively.\n    eta = (eta/eta.sum(1)[:,None]).reshape(-1,6)\n    return eta\n\ndef flatten_eta(eta): # eta pkm -> kc\n    warnings.warn('Eta no longer constructed as pkm - use reshape instead', DeprecationWarning)\n    return np.moveaxis(eta,0,1).reshape(-1, 6)\n\ndef alr(x, e=1e-12):\n    '''\n    additive log ratio\n    x is a NxD matrix\n    >>> x = np.array([.1, .3, .4, .2])\n    >>> alr(x)\n    array([ 1.09861229,  1.38629436,  0.69314718])\n    '''\n    # add small value for stability in log\n    x = x + e\n    return (np.log(x) - np.log(x[...,-1]).reshape(-1,1))[:,0:-1]\n\ndef alr_inv(y):\n    '''\n    inverse alr transform\n    y is a Nx(D-1) matrix\n    >>> x = np.array([.1, .3, .4, .2])\n    >>> alr_inv(alr(x))\n    array([ 0.1,  0.3,  0.4,  0.2])\n    '''\n    if y.ndim == 1: y = y.reshape(1,-1)\n    return softmax(np.hstack([y, np.zeros((y.shape[0], 1)) ]), axis = 1)\n\ndef kmeans_alr(data, nsig, rng=np.random.default_rng()):\n    #https://github.com/scikit-learn/scikit-learn/issues/16988#issuecomment-817375063\n    km = k_means(alr(data), nsig, random_state=np.random.RandomState(rng.bit_generator))\n    return alr_inv(km[0])\n\ndef alp_B(data, B):\n    return (data * np.log(B)).sum() / data.sum()\n\ndef mult_ll(x, p):\n    # x and p should both be same dimensions; Sx96\n    return loggamma(x.sum(1) + 1) - loggamma(x+1).sum(1) + (x * np.log(p)).sum(1)\n\ndef lap_B(data, Bs):\n    # Bs should be shape DxSx96 where D is the number of posterior samples\n    # use logsumexp for stability\n    assert Bs.ndim == 3, 'expected multiple trials for B'\n    return logsumexp(np.vstack([mult_ll(data, B) for B in Bs]).sum(1)) - np.log(Bs.shape[0])\n\ndef profile_sigs(sigs, refsigs, thresh = 0.9, refidx = None):\n    # return mapping of sigs to similar refsigs\n    \n    if isinstance(refsigs, pd.core.frame.DataFrame) and refsigs.index is not None:\n        refidx = refsigs.index\n    elif refidx is None:\n        refidx = pd.Index([f'refsig_{i}' for i in range(0,refsigs.shape[0])])\n    \n    sim = cosine_similarity(sigs, refsigs)\n    closest_dist = np.max(sim, axis=1)\n    closest = refidx[np.argmax(sim, axis=1)]\n    above_thresh = [str(refidx[x].to_numpy()) for x in sim > thresh]\n    \n    df=pd.DataFrame.from_dict({'inferred signature': [f'sig_{i}' for i in range(0,sigs.shape[0])],\n                               'closest reference signature':closest, \n                               'dist to closest': closest_dist,\n                               f'reference signatures with >{thresh} similarity': above_thresh\n                              })\n    df.index = [f'sig_{i}' for i in range(0,sigs.shape[0])]\n    return df\n\ndef load_cosmic_V3():\n    \"\"\"Return a dataframe of COSMIC V3 signature definitions\n\n    Contains:\n        96 mutation type columns of non-null float64\n        78 rows of signature definitions, rows sum to 1\n\n    \"\"\"\n    # This is a stream-like object. If you want the actual info, call\n    # stream.read()\n    f = pkg_resources.resource_filename(__name__, 'data/COSMIC_v3.2_SBS_GRCh37.txt')\n    return load_sigs(f)\n\ndef load_default_config():\n    \"\"\"Return a default configuration dict\n\n    Contains:\n        96 mutation type columns of non-null float64\n        78 rows of signature definitions, rows sum to 1\n\n    \"\"\"\n    # This is a stream-like object. If you want the actual info, call\n    # stream.read()\n    f = pkg_resources.resource_filename(__name__, 'config/default.yaml')\n    return load_config(f)\n\n", "meta": {"hexsha": "2224b5c934b53e1210212e23dce166a567667d23", "size": 12846, "ext": "py", "lang": "Python", "max_stars_repo_path": "damuta/utils.py", "max_stars_repo_name": "morrislab/damuta", "max_stars_repo_head_hexsha": "48e3146b610397e1c3020b26f0d010b38901452b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-02T19:56:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T19:15:48.000Z", "max_issues_repo_path": "damuta/utils.py", "max_issues_repo_name": "morrislab/damuta", "max_issues_repo_head_hexsha": "48e3146b610397e1c3020b26f0d010b38901452b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "damuta/utils.py", "max_forks_repo_name": "morrislab/damuta", "max_forks_repo_head_hexsha": "48e3146b610397e1c3020b26f0d010b38901452b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-29T01:13:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T01:13:51.000Z", "avg_line_length": 40.0186915888, "max_line_length": 144, "alphanum_fraction": 0.6574809279, "include": true, "reason": "import numpy,from scipy,import pymc3", "num_tokens": 3505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.19908994865170865}}
{"text": "import errno              # handle errors\nimport logging            # log errors\nimport os\nimport sys\nfrom pathlib import Path  # filesystem related stuff\nimport re                 # regular expression to find resolution from\n\nimport numpy as np\nfrom astropy.wcs import WCS    # handle astronomic coordinates\nfrom astropy.io import fits    # read data from .fits files.\nfrom astropy.io import ascii\nfrom astropy.coordinates import SkyCoord, match_coordinates_sky, Angle\nfrom reproject import reproject_interp\n\nfrom astropy.visualization import simple_norm\nimport matplotlib.pyplot as plt\n\nfrom .constants import two_column, arcsec_to_pixel\n\n\nlogger = logging.getLogger(__name__)\n\nclass ParameterClass:\n    def __init__(self,name,**kwargs):\n        self.name     = name\n        for k,v in kwargs.items():\n            setattr(self,k,v)\n\nclass ReadLineMaps:\n    '''load a fits file from the PHANGS--MUSE DAP (the line maps)\n    \n    Read the linemaps from the PHANGS-MUSE DAP. You only need to specify\n    the folder and the name of the galaxy. The function will pick the \n    correct file and read all the specified extensions. If the file is \n    from the copt, it will detect the resolution from the filename and\n    save it. \n\n    It will also try to read some auxiliary files that should be in \n    folder named `AUXILIARY` (next to `folder`). This folder should \n    contain star masks, PSF maps (FWHM of each pointing) and an alternative\n    [OIII]5007 map (not measured from a fit).\n    '''\n    \n    def __init__(self,folder,name,extensions=[],**kwargs):\n        '''\n        Parameters\n        ----------\n        \n        folder : string\n            name of the folder with the data for one object. This folder\n            must contain a file with name \"FolderName_MAPS.fits\" and \n            possibly some additional files\n\n        extensions : list\n            list of extensions that are read. Each element must be a valid \n            extension in the previously defined fits file (the actual name\n            of the extension is `ExtensionName_FLUX` and \n            `ExtensionName_FLUX_ERR` but they are automaticly completed).\n\n        **kwargs : \n            any additional properties of the galaxy (like E(B-V) or \n            parameters used during the analysis). They are saved as an \n            attribute under the given name.\n        '''\n        \n        # we simply use the first file in the folder that starts with name\n        self.name     = name\n        self.filename = next(folder.glob(f'{name}*.fits'))\n        self.copt_res = np.float(next(iter(re.findall('-(.*)asec',self.filename.stem)), 'nan'))\n\n        logger.info(f'loading {self.filename.name}')\n\n\n        self.lines    = []\n        \n        # we save the additional parameters\n        for k,v in kwargs.items():\n            setattr(self,k,v)\n\n        if not self.filename.is_file():\n            raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), self.filename)\n        \n        # make sure lines is a list\n        lines = [extensions] if not isinstance(extensions, list) else extensions\n        \n        #==============================================================\n        # load the main DAP products\n        #==============================================================\n        with fits.open(self.filename) as hdul:\n            \n            # if no lines are given, we read in all lines\n            if len(lines)==0:\n                lst = hdul.info(output=False)\n                lines = [x[1].split('_')[0] for x in lst if x[1].endswith('_FLUX')]\n\n            # save the white-light image\n            header = hdul[f'FLUX'].header\n            setattr(self,'header',header)\n            setattr(self,'wcs',WCS(header))\n            setattr(self,'shape',(header['NAXIS2'],header['NAXIS1']))\n            setattr(self,'V_STARS',hdul['V_STARS'].data)\n            setattr(self,'stellar_mass',hdul['STELLAR_MASS_DENSITY'].data)\n            setattr(self,'stellar_mass_err',hdul['STELLAR_MASS_DENSITY_err'].data)\n            setattr(self,'Ebv_stars',hdul['EBV_STARS'].data)\n            setattr(self,'whitelight',hdul['FLUX'].data)\n            setattr(self,'whitelight_err',hdul['SNR'].data)\n\n            for line in lines:\n                # save the main data and the associated error\n                setattr(self,line,hdul[f'{line}_FLUX'].data)\n                setattr(self,f'{line}_err',hdul[f'{line}_FLUX_ERR'].data)                \n                setattr(self,f'{line}_SIGMA',np.sqrt(hdul[f'{line}_SIGMA'].data**2 - hdul[f'{line}_SIGMA_CORR'].data**2))\n                setattr(self,f'{line}_SIGMA_ERR',hdul[f'{line}_SIGMA_ERR'])\n\n                # append to list of available lines\n                self.lines.append(line)\n\n        #==============================================================\n        # load auxiliary maps\n        #==============================================================\n        \n        # and one where OIII is not measured by fitting\n        OIII_map_file = folder.parent / 'AUXILIARY' / 'oiii_from_cubes' / f'{self.name}_oiii_flux.fits'\n        if OIII_map_file.is_file():\n            logger.info(f'replacing OIII5006 map')\n            # replace the old line maps with the new one\n            setattr(self,'OIII5006_DAP',getattr(self,'OIII5006'))\n            setattr(self,'OIII5006_DAP_err',getattr(self,'OIII5006_err'))\n            data = fits.getdata(OIII_map_file,0)\n            setattr(self,'OIII5006',data)\n        else:\n            logger.warn(f'\"{self.name}_oiii_flux.fits\" does not exists.')\n\n        # star mask and seeing map (for PSF)\n        star_mask_file = folder.parent / 'AUXILIARY' / 'starmasks' / f'{self.name}_starmask.fits'\n        seeing_map_file = folder.parent / 'AUXILIARY' / 'seeing_maps' / f'{self.name}_seeing.fits'\n\n        for filename, description in zip([star_mask_file,seeing_map_file],[\"star_mask\",\"PSF\"]):\n\n            if filename.is_file():\n                with fits.open(filename) as hdul:\n                    data   = hdul[0].data\n                    \n                    if self.shape != data.shape: \n                        logger.warning(f'{description} map has different shape. Reprojecting')\n                        data,_ = reproject_interp(hdul,self.header)\n\n                        # star_mask ist 0 or 1 (even for interpolated pixels)\n                        if description=='star_mask':\n                            data = np.round(data,0)\n                        elif description=='PSF':\n                            data = np.round(data,2)\n\n                    setattr(self,description,data)\n\n            else:\n                logger.warning(f'no {description} available')\n\n        if not hasattr(self,'star_mask'):\n            self.star_mask = np.zeros_like(self.OIII5006)\n\n        if not hasattr(self,'PSF'):\n            # for DR2 galaxies where no PSF data exists we assume FWHM=1\" for all pointings\n            logger.warning('creating 1\" seeing map')\n            self.PSF = np.ones_like(self.OIII5006)\n            self.PSF[np.isnan(self.OIII5006)] = np.nan\n        self.PSF *= arcsec_to_pixel \n        logger.info(f'galaxy has {len(np.unique(self.PSF[~np.isnan(self.PSF)]))} pointings')\n\n        logger.info(f'file loaded with {len(self.lines)} extensions')\n\n    def __repr__(self):\n        '''create an overview of the available attributes'''\n        \n        string = ''\n        for k,v in self.__dict__.items():\n            if type(v) in [str,int,float]:\n                string += f'{k}: {v}\\n'\n            else:\n                string += k + '\\n'\n                \n        return string\n\n    def plot(self,line):\n        '''plot a single emission line'''\n\n        if not hasattr(self,line):\n            raise AttributeError(f'Object has no map {line}')\n        \n        data = getattr(self,line)\n\n        fig = plt.figure(figsize=(two_column,two_column/1.618))\n        ax  = fig.add_subplot(projection=self.wcs)\n\n        norm = simple_norm(data,clip=False,percent=99)\n        ax.imshow(data,norm=norm)\n        plt.show()\n        \n        #return fig \n\n# save lines to individual .fits file\ndef split_fits(filename,extensions):\n    '''\n    \n    Parameters\n    ----------\n    filename: \n        a fits file containing lines in multiple extensions\n\n    extensions: \n        the extensions to save as single files\n    '''\n    \n    # make sure lines is a list\n    extensions = [extensions] if not isinstance(extensions, list) else extensions\n    \n    if not os.path.isfile(filename):\n        raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), filename)\n    print(f'splitting {filename} into seperate files')\n    \n    with fits.open(filename) as hdul:\n        for ext in extensions:\n            data = hdul[f'{ext}']\n            data.writeto(f'{ext}.fits',overwrite=True)\n            \n    print(f'{len(extensions)} extension(s) saved to seperate file(s)')\n\n\nclass ReadMosaicFiles:\n\n    def __init__(self,filename):\n        '''open the large MOSAIC files in python\n\n        the MOSAIC files contain the full spectral information \n        '''\n\n        logger.warning('not yet implemented')\n        sys.exit()\n\n        with fits.open(filename,memmap=True,mode='denywrite') as hdul:\n            wcs = WCS(hdul[1].header)\n            data = hdul[1].data\n                \n            print(data.shape)\n            print(hdul[1].header)\n            #data = hdul[f'{line}_FLUX']\n            #data.writeto(f'{line}.fits',overwrite=True)\n\n\ndef write_table(table,name,filename):\n    '''write the table to a file\n\n    this will create a `.tex` file and a machine readable file\n\n    to read this file use\n    f = basedir / 'data' / 'catalogues' / f'{galaxy.name}_{typ}_candidates.txt'\n    ascii.read(f,format='fixed_width_two_line',position_char='=')\n    '''\n\n    threshold = '0.7\"'\n\n    table['RA'],table['DEC'] = zip(*[x.split(' ') for x in table['SkyCoord'].to_string(style='hmsdms',precision=2)])\n    table['Galaxy'] = name\n\n    if name =='NGC0628':\n        logging.info('comparing to existing studies')\n        from .load_references import NGC628\n        cat = {'Kreckel PN':'K17;','Herrmann PN':'H08;','Kreckel SNR':'K17s;'}\n        ID, angle, Quantity  = match_coordinates_sky(NGC628['SkyCoord'],table['SkyCoord'])\n        table['match'] = np.empty(len(table),dtype='U12')\n        for i,a,row in zip(ID,angle,NGC628):\n            if a.__lt__(Angle('0.8\"')):\n                table['match'][i] += cat[row['source']]\n\n    if name =='NGC3351':\n        logging.info('comparing to existing studies')\n        from .load_references import pn_NGC3351_ciardullo\n        ID, angle, Quantity  = match_coordinates_sky(pn_NGC3351_ciardullo['SkyCoord'],table['SkyCoord'])\n        table['match'] = np.empty(len(table),dtype='U12')\n        for i,a,row in zip(ID,angle,pn_NGC3351_ciardullo):\n            if a.__lt__(Angle('0.8\"')):\n                table['match'][i] += 'C02;'\n\n    if name =='NGC3627':\n        logging.info('comparing to existing studies')\n        from .load_references import pn_NGC3627_ciardullo\n        ID, angle, Quantity  = match_coordinates_sky(pn_NGC3627_ciardullo['SkyCoord'],table['SkyCoord'])\n        table['match'] = np.empty(len(table),dtype='U12')\n        for i,a,row in zip(ID,angle,pn_NGC3627_ciardullo):\n            if a.__lt__(Angle('0.8\"')):\n                table['match'][i] += 'C02;'\n\n    if name =='NGC5068':\n        logging.info('comparing to existing studies')\n        from .load_references import pn_NGC5068_herrmann\n        ID, angle, Quantity  = match_coordinates_sky(pn_NGC5068_herrmann['SkyCoord'],table['SkyCoord'])\n        table['match'] = np.empty(len(table),dtype='U12')\n        for i,a,row in zip(ID,angle,pn_NGC5068_herrmann):\n            if a.__lt__(Angle('0.8\"')):\n                table['match'][i] += 'H08;'\n\n    for col in ['OIII5006','HA6562','NII6583','SII']:\n        table[col][np.where(table[col]<table[f'{col}_err'])] = table[f'{col}_err'][np.where(table[col]<table[f'{col}_err'])] \n\n    table['OIII/Ha']   = table['OIII5006']/table['HA6562']\n    table['d(OIII/Ha)']= table['OIII5006'] / table['HA6562'] * np.sqrt( (table['HA6562_err'] / table['HA6562'])**2 + (table['OIII5006_err'] / table['OIII5006'])**2)\n\n    table['Ha/NII']    = table['HA6562']/table['NII6583']\n    table['d(Ha/NII)'] = table['HA6562'] / table['NII6583'] * np.sqrt( (table['NII6583_err'] / table['NII6583'])**2 + (table['HA6562_err'] / table['HA6562'])**2)\n\n    table['Ha/SII']    = table['HA6562']/table['SII']\n    table['d(Ha/SII)'] = table['HA6562'] / table['SII'] * np.sqrt( (table['SII_err'] / table['SII'])**2 + (table['HA6562_err'] / table['HA6562'])**2)\n\n    for col in ['mOIII','dmOIII','v_SIGMA','OIII/Ha','d(OIII/Ha)','Ha/NII','d(Ha/NII)','Ha/SII','d(Ha/SII)']:\n        table[col].info.format = '%.2f' \n\n    # \n    for typ in ['PN','SNR']:\n\n        tbl_out = table[table['type']==typ]\n\n        if typ == 'PN':\n            n = 'Planetary Nebula'\n        if typ == 'SNR':\n            n = 'Supernova Remnants'  \n\n        tbl_out.sort('mOIII')\n        tbl_out['name'] = np.arange(1,len(tbl_out)+1)\n\n        # add marker for existing study or excluded object\n        notes = []\n        for i,row in enumerate(tbl_out):\n            note = ''\n            if name == 'NGC0628' or name=='NGC3351' or name=='NGC3627' or name=='NGC5068':\n                note += row['match']\n            if row['overluminous']:\n                note += 'OL;'\n            if row['SNRorPN']:\n                note += 'PN;'\n            notes.append(note)        \n        tbl_out['notes'] = [x.strip(';') for x in notes]\n      \n\n        tbl_out.rename_columns(['name','RA','DEC','v_SIGMA'],['ID','R.A.','Dec.','sigmaV'])\n        tbl_out = tbl_out[['Galaxy','ID','notes','R.A.','Dec.','mOIII','dmOIII','OIII/Ha','d(OIII/Ha)',\n                           'Ha/NII','d(Ha/NII)','Ha/SII','d(Ha/SII)','sigmaV']]\n\n        with open((filename / f'{name}_{typ}_candidates').with_suffix('.txt'),'w',newline='\\n') as f:\n            ascii.write(tbl_out,f,format='fixed_width_two_line',overwrite=True,delimiter_pad=' ',position_char='=')\n\n\n        with open((filename / f'{name}_{typ}_candidates').with_suffix('.tex'),'w',newline='\\n') as f:\n            ascii.write(tbl_out,f,Writer=ascii.Latex,overwrite=True)\n\n        \n    logger.info(f'table saved to files (for {name})')\n\n\ndef write_LaTeX_old(table,galaxy,filename):\n    '''write the table to a file\n\n    this will create a `.tex` file and a machine readable file\n\n    to read this file use\n    f = basedir / 'data' / 'catalogues' / f'{galaxy.name}_{typ}_candidates.txt'\n    ascii.read(f,format='fixed_width_two_line',position_char='=')\n    '''\n\n    threshold = '0.7\"'\n\n    table['SkyCoord'] = SkyCoord.from_pixel(table['x'],table['y'],galaxy.wcs)\n    table['RA'],table['DEC'] = zip(*[x.split(' ') for x in table['SkyCoord'].to_string(style='hmsdms',precision=2)])\n\n    if galaxy.name =='NGC0628':\n        print('comparing to existing studies')\n        from .load_references import NGC628\n        cat = {'Kreckel PN':'K17','Herrmann PN':'H08','Kreckel SNR':'K17s'}\n        ID, angle, Quantity  = match_coordinates_sky(NGC628['SkyCoord'],table['SkyCoord'])\n        table['match'] = np.empty(len(table),dtype='U12')\n        for i,a,row in zip(ID,angle,NGC628):\n            if a.__lt__(Angle('0.8\"')):\n                table['match'][i] += cat[row['source']]\n\n\n    if galaxy.name =='NGC3351':\n        print('comparing to existing studies')\n        from .load_references import pn_NGC3351_ciardullo\n        ID, angle, Quantity  = match_coordinates_sky(pn_NGC3351_ciardullo['SkyCoord'],table['SkyCoord'])\n        table['match'] = np.empty(len(table),dtype='U12')\n        for i,a,row in zip(ID,angle,pn_NGC3351_ciardullo):\n            if a.__lt__(Angle('0.8\"')):\n                table['match'][i] += 'C02'\n\n    if galaxy.name =='NGC3627':\n        print('comparing to existing studies')\n        from .load_references import pn_NGC3627_ciardullo\n        ID, angle, Quantity  = match_coordinates_sky(pn_NGC3627_ciardullo['SkyCoord'],table['SkyCoord'])\n        table['match'] = np.empty(len(table),dtype='U12')\n        for i,a,row in zip(ID,angle,pn_NGC3627_ciardullo):\n            if a.__lt__(Angle('0.8\"')):\n                table['match'][i] += 'C02'\n\n    if galaxy.name =='NGC5068':\n        print('comparing to existing studies')\n        from .load_references import pn_NGC5068_herrmann\n        ID, angle, Quantity  = match_coordinates_sky(pn_NGC5068_herrmann['SkyCoord'],table['SkyCoord'])\n        table['match'] = np.empty(len(table),dtype='U12')\n        for i,a,row in zip(ID,angle,pn_NGC5068_herrmann):\n            if a.__lt__(Angle('0.8\"')):\n                table['match'][i] += 'H08'\n\n    for typ in ['PN','SNR']:\n\n        if typ == 'PN':\n            n = 'Planetary Nebula'\n        if typ == 'SNR':\n            n = 'Supernova Remnants'\n        if typ == 'HII':\n            n = '\\\\HII-regions'    \n\n\n        latexdict = {'tabletype': 'table*',\n        'header_start': '\\\\toprule\\\\toprule',\n        'header_end': '\\\\midrule',\n        'data_end': '\\\\bottomrule',\n        'caption': f'{n} Identifications',\n        'units': {'R.A.':'(J2000)','Dec.':'(J2000)','$m_\\\\OIII$':'mag','d$m_\\\\OIII$':'mag','$\\sigma_V$':'\\\\si{\\\\km \\per \\\\second}'},\n        'preamble': '\\\\centering',\n        'tablefoot': f'\\\\label{{tbl:{typ}_Identifications}}'\n                    }\n\n        tbl_out = table[table['type']==typ]\n        tbl_out['Galaxy'] = galaxy.name\n        tbl_out.sort('mOIII')\n\n        tbl_out['OIII/Ha']   = np.empty(len(tbl_out),dtype='U8')\n        tbl_out['Ha/NII']    = np.empty(len(tbl_out),dtype='U8') \n        tbl_out['Ha/SII']    = np.empty(len(tbl_out),dtype='U8')\n        tbl_out['d(OIII/Ha)']= np.empty(len(tbl_out),dtype='U8')\n        tbl_out['d(Ha/NII)'] = np.empty(len(tbl_out),dtype='U8')\n        tbl_out['d(Ha/SII)'] = np.empty(len(tbl_out),dtype='U8')\n\n        # add marker for existing study or excluded object\n        names = np.arange(1,len(tbl_out)+1)\n        notes = []\n        for i,row in enumerate(tbl_out):\n            notes = ''\n            if galaxy.name == 'NGC0628' or galaxy.name=='NGC3351' or galaxy.name=='NGC3627' or galaxy.name=='NGC5068':\n                name += row['match']\n            if row['overluminous']:\n                name += '+'\n            if row['SNRorPN']:\n                name += 'PN'\n\n            names.append(name)        \n        tbl_out['name'] = names\n        tbl_out['notes'] = notes\n\n        # calculate line ratios with limits (> sign)\n        for i,row in enumerate(tbl_out):\n            if not row['HA6562_detection']:\n                row['OIII/Ha'] += '>'\n            row['OIII/Ha'] += f\"{row['OIII5006'] / row['HA6562']:.2f}\"\n            row['d(OIII/Ha)'] = f\"{row['OIII5006'] / row['HA6562'] * np.sqrt( (row['HA6562_err'] / row['HA6562'])**2 + (row['OIII5006_err'] / row['OIII5006'])**2):.2f}\"\n\n            if not row['HA6562_detection'] and not row['NII6583_detection']:\n                row['Ha/NII'] = '...'\n                row['d(Ha/NII)'] = '...'\n            elif not row['HA6562_detection']:\n                row['Ha/NII'] = '<'\n                row['Ha/NII'] += f\"{row['HA6562'] / row['NII6583']:.2f}\"\n                row['d(Ha/NII)'] = f\"{row['HA6562'] / row['NII6583'] * np.sqrt( (row['NII6583_err'] / row['NII6583'])**2 + (row['HA6562_err'] / row['HA6562'])**2):.2f}\"\n            elif not row['NII6583_detection']:\n                row['Ha/NII'] = '>'\n                row['Ha/NII'] += f\"{row['HA6562'] / row['NII6583']:.2f}\"\n                row['d(Ha/NII)'] = f\"{row['HA6562'] / row['NII6583'] * np.sqrt( (row['NII6583_err'] / row['NII6583'])**2 + (row['HA6562_err'] / row['HA6562'])**2):.2f}\"\n            else:\n                row['Ha/NII'] += f\"{row['HA6562'] / row['NII6583']:.2f}\"\n                row['d(Ha/NII)'] = f\"{row['HA6562'] / row['NII6583'] * np.sqrt( (row['NII6583_err'] / row['NII6583'])**2 + (row['HA6562_err'] / row['HA6562'])**2):.2f}\"\n\n            if not row['HA6562_detection'] and not row['SII_detection']:\n                row['Ha/SII'] = '...'\n                row['d(Ha/SII)'] = '...'\n            elif not row['HA6562_detection']:\n                row['Ha/SII'] += '<'\n                row['Ha/SII'] += f\"{row['HA6562'] / row['SII']:.2f}\"\n                row['d(Ha/SII)'] = f\"{row['HA6562'] / row['SII'] * np.sqrt( (row['HA6562_err'] / row['HA6562'])**2 + (row['SII_err'] / row['SII'])**2):.2f}\"\n            elif not row['SII_detection']:\n                row['Ha/SII'] += '>'\n                row['Ha/SII'] += f\"{row['HA6562'] / row['SII']:.2f}\"\n                row['d(Ha/SII)'] = f\"{row['HA6562'] / row['SII'] * np.sqrt( (row['HA6562_err'] / row['HA6562'])**2 + (row['SII_err'] / row['SII'])**2):.2f}\"\n            else:\n                row['Ha/SII'] += f\"{row['HA6562'] / row['SII']:.2f}\"\n                row['d(Ha/SII)'] = f\"{row['HA6562'] / row['SII'] * np.sqrt( (row['HA6562_err'] / row['HA6562'])**2 + (row['SII_err'] / row['SII'])**2):.2f}\"\n\n\n        tbl_out['mOIII'].info.format = '%.2f' \n        tbl_out['dmOIII'].info.format = '%.2f' \n        tbl_out['v_SIGMA'].info.format = '%.2f' \n\n        tbl_out.rename_columns(['name','RA','DEC','v_SIGMA'],['ID','R.A.','Dec.','sigmaV'])\n        tbl_out = tbl_out[['Galaxy','ID','R.A.','Dec.','mOIII','dmOIII','OIII/Ha','d(OIII/Ha)',\n                           'Ha/NII','d(Ha/NII)','Ha/SII','d(Ha/SII)','sigmaV']]\n\n        with open((filename / f'{galaxy.name}_{typ}_candidates').with_suffix('.txt'),'w',newline='\\n') as f:\n            ascii.write(tbl_out,f,format='fixed_width_two_line',overwrite=True,delimiter_pad=' ',position_char='=')\n\n        \n        mOIII  = []\n        OIIIHA = []\n        HANII  = []\n        HASII  = []\n        for row in tbl_out:\n            if row[\"mOIII\"] == '...':\n                mOIII.append('...')\n            else:\n                mOIII.append(f'{row[\"mOIII\"]:.2f} $\\pm$ {row[\"dmOIII\"]:.2f}')\n            if row[\"OIII/Ha\"] == '...':\n                OIIIHA.append('...')\n            else:\n                OIIIHA.append(f'{row[\"OIII/Ha\"]} $\\pm$ {row[\"d(OIII/Ha)\"]}')\n            if row[\"Ha/NII\"] == '...':\n                HANII.append('...')\n            else:\n               HANII.append(f'{row[\"Ha/NII\"]} $\\pm$ {row[\"d(Ha/NII)\"]}')\n            if row[\"Ha/SII\"] == '...':\n                HASII.append('...')\n            else:\n               HASII.append(f'{row[\"Ha/SII\"]} $\\pm$ {row[\"d(Ha/SII)\"]}')\n        \n        tbl_out['$m_\\\\OIII$'] = mOIII\n        tbl_out['$\\\\OIII/\\\\HA$'] = OIIIHA\n        tbl_out['$\\\\HA/\\\\NII$'] = HANII\n        tbl_out['$\\\\HA/\\\\SII$'] = HASII\n        tbl_out.rename_column('sigmaV',f'$\\sigma_V$')\n        tbl_out = tbl_out[['ID','R.A.','Dec.','$m_\\\\OIII$','$\\\\OIII/\\\\HA$',\n                           '$\\\\HA/\\\\NII$','$\\\\HA/\\\\SII$',f'$\\sigma_V$']]\n\n        with open((filename / f'{galaxy.name}_{typ}_candidates').with_suffix('.tex'),'w',newline='\\n') as f:\n            ascii.write(tbl_out,f,Writer=ascii.Latex, latexdict=latexdict,overwrite=True)\n\n\n        # shorten column names for machine readable table\n        #for col in tbl_out.colnames:\n        #    tbl_out.rename_column(col,col.translate({ord(s): None for s in '$\\_'}))\n\n\n        \n    logger.info(f'table saved to files (for {galaxy.name})')\n\n\ndef read_catalogue(filename):\n\n    catalogue = ascii.read(filename,format='fixed_width_two_line',delimiter_pad=' ',position_char='=')\n    catalogue['SkyCoord'] = SkyCoord(catalogue['R.A.'],catalogue['Dec.'])\n\n    return catalogue", "meta": {"hexsha": "d818b650506c0904451588e0d448e21ad3b277ac", "size": 23333, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/pnlf/io.py", "max_stars_repo_name": "fschmnn/pymuse", "max_stars_repo_head_hexsha": "91e97d03a3eb1ccc02131f4e731e6bb5df66772c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-09T21:24:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-27T15:11:31.000Z", "max_issues_repo_path": "src/pnlf/io.py", "max_issues_repo_name": "fschmnn/pymuse", "max_issues_repo_head_hexsha": "91e97d03a3eb1ccc02131f4e731e6bb5df66772c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pnlf/io.py", "max_forks_repo_name": "fschmnn/pymuse", "max_forks_repo_head_hexsha": "91e97d03a3eb1ccc02131f4e731e6bb5df66772c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.8904847397, "max_line_length": 168, "alphanum_fraction": 0.5515364505, "include": true, "reason": "import numpy,from astropy", "num_tokens": 6385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.19908343851403734}}
{"text": "# -*- coding: utf-8 -*-\n# @Author  : Daniel Ordonez\n# @email   : daniels.ordonez@gmail.com\n\nfrom typing import Optional\n\nimport numpy as np\nfrom numpy import ndarray\n\nfrom .slip_model import SlipModel, THETA, X\n\n\nclass SlipGaitCycle(object):\n\n    def __init__(self, slip_model: SlipModel, t_flight: ndarray, flight_cartesian_traj: ndarray, t_stance: ndarray,\n                 stance_polar_traj: ndarray, target_to_state: Optional[ndarray] = None,\n                 optimization_cost: Optional[float] = np.NaN):\n        \"\"\"\n        Class representing a Slip gait cycle composed of:\n         - a flight phase: starting with the take-off (TO) event of a previous gait cycle and ending at the present cycle\n          touch-down (TD) event. And,\n         - a stance phase: starting at the present cycle TD event and ending with the cycle's TO event.\n        It is assumed the gait cycle starts with a flight phase and ends with the stance phase.\n        :param slip_model: SLIP model providing the `m`, `k` and `r0` parameters.\n        :param t_flight: (F,) Discrete time array during flight phase\n        :param flight_cartesian_traj: (6, F) Cartesian state [x, x', x'', z, z', z''] of the SLIP CoM at each time\n        during the flight phase\n        :param t_stance: (S,) Discrete time array during flight phase\n        :param stance_polar_traj: (4, S) Polar state [theta,theta',r,r'] of the SLIP CoM at each time during\n        the stance phase, in a reference frame centered at the foot contact point with the ground.\n        :param target_to_state: (6,) Optional cartesian target take-off state, used for control. Use np.NaN in the\n        dimensions of the cartesian state that are irrelevant for control (e.g. z''=np.NaN)\n        :param optimization_cost: Optional scalar indicating the optimization cost of the gait cycle. By default is set \n        to be the euclidean norm of the error between the real TO state and the target TO state (ignoring np.NaNs dims) \n        \"\"\"\n        self.slip_model = slip_model\n        if not flight_cartesian_traj.shape[0] == 6:\n            raise AssertionError(\"Expected cartesian trajectory [x, x', x'', z, z', z'']\")\n        else:\n            if not len(t_flight) == flight_cartesian_traj.shape[1]:\n                raise AssertionError('Invalid flight trajectory')\n            else:\n                self.t_flight = t_flight\n                self.flight_cartesian_traj = flight_cartesian_traj\n                assert stance_polar_traj.shape[0] == 4, \"Expected stance polar trajectory [theta, theta', r, r']\"\n                assert len(t_stance) == stance_polar_traj.shape[1], 'Invalid flight trajectory'\n            self.t_stance = t_stance\n            self.stance_polar_traj = stance_polar_traj\n            self._stance_cartesian_traj = None\n            self.touch_down_angle = self.stance_polar_traj[(THETA, 0)]\n            self.take_off_angle = self.stance_polar_traj[(THETA, -1)]\n            self.foot_contact_pos = self.flight_cartesian_traj[(X, -1)] - self.slip_model.r0 * np.cos(\n                self.touch_down_angle)\n            assert self.t_flight[(-1)] == self.t_stance[\n                0], 'Touch down state should be in flight and stance trajectories'\n        self.target_to_state = np.array(target_to_state) if target_to_state is not None else np.ones((6,)) * np.NaN\n        self.optimization_cost = optimization_cost\n        if not np.all(np.isnan(self.target_to_state)):\n            self.target_to_state = np.ma.array((self.target_to_state), mask=(np.isnan(self.target_to_state)))\n            if np.isnan(optimization_cost):\n                self.optimization_cost = np.linalg.norm(self.take_off_state - target_to_state)\n\n    @property\n    def stance_cartesian_traj(self) -> ndarray:\n        if self._stance_cartesian_traj is None:\n            self._stance_cartesian_traj = self.slip_model.polar_to_cartesian(trajectory=(self.stance_polar_traj),\n                                                                             foot_contact_pos=(self.foot_contact_pos))\n        return self._stance_cartesian_traj\n\n    @property\n    def take_off_state(self) -> ndarray:\n        if self._stance_cartesian_traj is None:\n            return self.slip_model.polar_to_cartesian((self.stance_polar_traj[:, -1]),\n                                                      foot_contact_pos=(self.foot_contact_pos))\n        else:\n            return np.array(self.stance_cartesian_traj[:, -1])\n\n    @property\n    def take_off_state_polar(self):\n        return np.array(self.stance_polar_traj[:, -1])\n\n    @property\n    def touch_down_state(self):\n        if self._stance_cartesian_traj is None:\n            return self.slip_model.polar_to_cartesian((self.stance_polar_traj[:, 0]),\n                                                      foot_contact_pos=(self.foot_contact_pos))\n        else:\n            return np.array(self.stance_cartesian_traj[:, 0])\n\n    @property\n    def touch_down_state_polar(self):\n        return np.array(self.stance_polar_traj[:, 0])\n\n    @property\n    def prev_take_off_state(self):\n        return np.array(self.flight_cartesian_traj[:, 0])\n\n    @property\n    def start_time(self):\n        return float(self.t_flight[0])\n\n    @property\n    def end_time(self):\n        return float(self.t_stance[(-1)])\n\n    def offset_initial_time(self, time_offset):\n        self.t_flight += time_offset\n        self.t_stance += time_offset\n\n    def __str__(self):\n        return 'Cost:%.2f TD:%.1f[deg] TO:%.1f[deg] time:[%.2f, %.2f]' % (\n            self.optimization_cost, np.rad2deg(self.touch_down_angle), np.rad2deg(self.take_off_angle),\n            self.start_time, self.end_time)\n\n    def __repr__(self):\n        return str(self)\n\n\nclass SlipGaitCycleCtrl(SlipGaitCycle):\n\n    def __init__(self, slip_model, t_flight, flight_cartesian_traj, t_stance, stance_passive_polar_traj=None,\n                 stance_ctrl_polar_traj=None, control_signal=None, target_to_state=None, optimization_cost=np.NaN,\n                 ctrl_kwargs=None):\n        \"\"\"\n        Class representing a Controlled Slip gait Cycle. This assumes the SLIP model is an actuated extended version\n        (see \"Learning to run naturally: Guiding policies with the Spring-Loaded Inverted Pendulum\" Chap 4.1) where the\n        control inputs are a resting leg length displacement `r_delta` (axial force control) and a hip torque `tau_hip`.\n        The main difference with the parent class it that `SlipGaitCycleCtrl` stores also a `control_signal` and if\n        provided an additional `SlipGaitCycle` instance representing the passive dynamical response of SLIP (useful for\n        plotting animation and intuition).\n        :param slip_model: SLIP model providing the `m`, `k` and `r0` parameters.\n        :param t_flight: (F,) Discrete time array during flight phase\n        :param flight_cartesian_traj: (6, F) Cartesian state [x,x',x'',z,z',z''] of the SLIP CoM at each time during\n        the flight phase\n        :param t_stance: (S,) Discrete time array during flight phase\n        :param stance_passive_polar_traj: (4, S) Passive Polar state [theta,theta',r,r'] of the SLIP CoM at each time \n        during the stance phase, in a reference frame centered at the foot contact point with the ground.\n        :param stance_ctrl_polar_traj: (4, S) Controlled Polar state [theta,theta',r,r'] of the SLIP CoM at each time \n        during the stance phase, in a reference frame centered at the foot contact point with the ground.\n        :param control_signal: (2, S) Control input signal assumed to hold ()\n        :param target_to_state: (6,) Optional cartesian target take-off state, used for control. Use np.NaN in the\n        dimensions of the cartesian state that are irrelevant for control (e.g. z''=np.NaN)\n        :param optimization_cost: Optional scalar indicating the optimization cost of the gait cycle. By default is set\n        to be the euclidean norm of the error between the real TO state and the target TO state (ignoring np.NaNs dims)\n        :param ctrl_kwargs: Dictionary holding controller-related keyword arguments.\n        \"\"\"\n        self.control_signal = control_signal\n        self.optimization_cost = optimization_cost\n        self.control_signal = control_signal\n        self.ctrl_kwargs = ctrl_kwargs\n        super(SlipGaitCycleCtrl, self).__init__(slip_model, t_flight, flight_cartesian_traj, t_stance,\n                                                stance_polar_traj=stance_ctrl_polar_traj,\n                                                target_to_state=target_to_state)\n        if stance_passive_polar_traj is not None:\n            self.passive_gait_cycle = SlipGaitCycle(slip_model, t_flight, flight_cartesian_traj, t_stance,\n                                                    stance_polar_traj=stance_passive_polar_traj)\n        else:\n            self.passive_gait_cycle = None\n\n    @property\n    def stance_cartesian_traj(self) -> ndarray:\n        if self._stance_cartesian_traj is None:\n            self._stance_cartesian_traj = self.slip_model.polar_to_cartesian(trajectory=self.stance_polar_traj,\n                                                                             control_signal=self.control_signal,\n                                                                             foot_contact_pos=self.foot_contact_pos)\n        return self._stance_cartesian_traj\n\n    @property\n    def take_off_state(self) -> ndarray:\n        if self._stance_cartesian_traj is None:\n            return self.slip_model.polar_to_cartesian(self.stance_polar_traj[:, -1],\n                                                      control_signal=self.control_signal[:, -1],\n                                                      foot_contact_pos=self.foot_contact_pos)\n        else:\n            return np.array(self.stance_cartesian_traj[:, -1])\n\n    @property\n    def touch_down_state(self):\n        if self._stance_cartesian_traj is None:\n            return self.slip_model.polar_to_cartesian(self.stance_polar_traj[:, 0],\n                                                      control_signal=self.control_signal[:, 0],\n                                                      foot_contact_pos=self.foot_contact_pos)\n        else:\n            return np.array(self.stance_cartesian_traj[:, 0])\n", "meta": {"hexsha": "b46c22be194037c776296cf2f12f02000bf41c98", "size": 10233, "ext": "py", "lang": "Python", "max_stars_repo_path": "slip_control/slip/slip_gait_cycle.py", "max_stars_repo_name": "Danfoa/slip_control", "max_stars_repo_head_hexsha": "66dd4f33fefc51548a9461cdda75be95fb76c7b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-26T16:04:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T16:04:15.000Z", "max_issues_repo_path": "slip_control/slip/slip_gait_cycle.py", "max_issues_repo_name": "Danfoa/slip_control", "max_issues_repo_head_hexsha": "66dd4f33fefc51548a9461cdda75be95fb76c7b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slip_control/slip/slip_gait_cycle.py", "max_forks_repo_name": "Danfoa/slip_control", "max_forks_repo_head_hexsha": "66dd4f33fefc51548a9461cdda75be95fb76c7b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-19T12:48:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T12:48:36.000Z", "avg_line_length": 55.3135135135, "max_line_length": 121, "alphanum_fraction": 0.6442880876, "include": true, "reason": "import numpy,from numpy", "num_tokens": 2273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.19908343851403734}}
{"text": "# -*- coding: utf-8 -*-\nimport theano\nimport theano.tensor as T\nimport numpy as np\nimport pandas as pd\nfrom collections import OrderedDict\n\nINIT_RANGE = 0.01\n\n\ndef uniform(lb, ub, size):\n    \"\"\"\n\n    :param lb: lower bound\n    :param ub: upper bound\n    :param size: tensor shape\n    :return:\n    \"\"\"\n    return np.array(np.random.uniform(low=lb, high=ub, size=size), dtype='float32')\n\n\ndef glorot_uniform(size):\n    \"\"\"\n    glorot uniform initializer\n    \"\"\"\n    if len(size) == 1:\n        values = np.zeros_like(size)\n    else:\n        scale = np.sqrt(6.0 / np.sum(size))\n        values = np.random.uniform(low=-scale, high=scale, size=size)\n    return values.astype('float32')\n\n\ndef orthogonal(size):\n    \"\"\"\n    equivalent to orthogonal_init but return numpy array\n    \"\"\"\n    if len(size) == 1:\n        values = np.zeros_like(size)\n    else:\n        a = np.random.normal(loc=0.0, scale=1.0, size=size)\n        # reconstruction based on reduced SVD\n        u, _, v = np.linalg.svd(a, full_matrices=False)\n        q = u if u.shape == size else v\n        q = q.reshape(size)\n        values = q\n    return values.astype(\"float32\")\n\n\ndef zeros(size):\n    \"\"\"\n    generate zero vector / tensor\n    :param size: size\n    :return:\n    \"\"\"\n    return np.array(np.zeros(shape=size), dtype='float32')\n\n\ndef ones(size):\n    \"\"\"\n    generate one vector / tensor\n    :param size:\n    :return:\n    \"\"\"\n    return np.array(np.zeros(shape=size), dtype='float32')\n\n\ndef lstm_init(n_in, n_out, component=\"LSTM\"):\n    \"\"\"\n\n    :param n_in: input size\n    :param n_out: hidden size\n    :param component: component name\n    :return:\n    \"\"\"\n    if True:\n        print(\"Initialize LSTM weights from uniform distribution...\")\n        W_values = np.concatenate([uniform(lb=-INIT_RANGE, ub=INIT_RANGE, size=(n_in, n_out)),\n                                   uniform(lb=-INIT_RANGE, ub=INIT_RANGE, size=(n_in, n_out)),\n                                   uniform(lb=-INIT_RANGE, ub=INIT_RANGE, size=(n_in, n_out)),\n                                   uniform(lb=-INIT_RANGE, ub=INIT_RANGE, size=(n_in, n_out))], axis=1)\n\n        U_values = np.concatenate([uniform(lb=-INIT_RANGE, ub=INIT_RANGE, size=(n_out, n_out)),\n                                   uniform(lb=-INIT_RANGE, ub=INIT_RANGE, size=(n_out, n_out)),\n                                   uniform(lb=-INIT_RANGE, ub=INIT_RANGE, size=(n_out, n_out)),\n                                   uniform(lb=-INIT_RANGE, ub=INIT_RANGE, size=(n_out, n_out))], axis=1)\n        b_values = np.concatenate([zeros(n_out),\n                                   zeros(n_out),\n                                   zeros(n_out),\n                                   zeros(n_out)])\n    else:\n        print(\"Initialize LSTM weights from glorot uniform + glorot uniform...\")\n        W_values = np.concatenate([glorot_uniform(size=(n_in, n_out)),\n                                  glorot_uniform(size=(n_in, n_out)),\n                                  glorot_uniform(size=(n_in, n_out)),\n                                  glorot_uniform(size=(n_in, n_out))], axis=1)\n\n        U_values = np.concatenate([glorot_uniform(size=(n_out, n_out)),\n                                   glorot_uniform(size=(n_out, n_out)),\n                                   glorot_uniform(size=(n_out, n_out)),\n                                   glorot_uniform(size=(n_out, n_out))], axis=1)\n        b_values = np.concatenate([zeros(n_out),\n                                   ones(n_out),  # set forget gate to 1.0\n                                   zeros(n_out),\n                                   zeros(n_out)])\n    W = theano.shared(value=W_values, name='%s_W' % component)\n    U = theano.shared(value=U_values, name='%s_U' % component)\n    b = theano.shared(value=b_values, name='%s_b' % component)\n    return W, U, b\n\n\ndef reverse_tensor(tensor):\n    \"\"\"\n\n    :param tensor: input tensor, shape: (bs, seq_len, n_in)\n    :return:\n    \"\"\"\n    new_tensor = tensor.dimshuffle(1, 0, 2)\n    return new_tensor[::-1].dimshuffle(1, 0, 2)\n\n\ndef adam(cost, params, max_norm=3.0, lr=0.001, beta1=0.9, beta2=0.999, epsilon=1e-8):\n    \"\"\"\n    adam optimizer, default learning rate is 0.001\n    \"\"\"\n\n    grads = T.grad(cost, params)\n    t_prev = theano.shared(value=np.float32(0.0))\n    updates = OrderedDict()\n\n    t = t_prev + 1\n    one = T.constant(1, dtype='float32')\n\n    a_t = lr * T.sqrt(one - beta2 ** t) / (one - beta1 ** t)\n\n    for p, g in zip(params, grads):\n        value = p.get_value(borrow=True)\n        m_prev = theano.shared(np.zeros(value.shape, dtype=value.dtype),\n                               broadcastable=p.broadcastable)\n        v_prev = theano.shared(np.zeros(value.shape, dtype=value.dtype),\n                               broadcastable=p.broadcastable)\n\n        m_t = beta1 * m_prev + (one - beta1) * g\n        v_t = beta2 * v_prev + (one - beta2) * g ** 2\n\n        step = a_t * m_t / (T.sqrt(v_t) + epsilon)\n\n        stepped_p = p - step\n        updates[m_prev] = m_t\n        updates[v_prev] = v_t\n        # add max norm constraint on the W_hidden\n        # if p.name == 'W_hidden':\n        #\tcol_norms = T.sqrt(T.sum(T.sqr(stepped_p), axis=0))\n        #\tdesired_norms = T.clip(col_norms, 0, max_norm)\n        #\tscale = desired_norms / (1e-7 + col_norms)\n        #\tupdates[p] = stepped_p * scale\n        # else:\n        #\tupdates[p] = stepped_p\n        updates[p] = stepped_p\n    updates[t_prev] = t\n    return updates\n\n\ndef sgd_momentum(cost, params, lr=0.01, momentum=0.9):\n    \"\"\"\n    sgd with momentum\n    :param cost: training loss\n    :param params: parameters\n    :param lr: learning rate\n    :param momentum: amount of momentum to apply\n    :return:\n    \"\"\"\n    grads = T.grad(cost, params)\n    updates = OrderedDict()\n    for p, g in zip(params, grads):\n        updates[p] = p - lr * g\n    for p in params:\n        value = p.get_value(borrow=True)\n        velocity = theano.shared(np.zeros(value.shape, dtype=value.dtype), broadcastable=p.broadcastable)\n        x = momentum * velocity + updates[p]\n        updates[velocity] = x - p\n        updates[p] = x\n    return updates\n\ndef get_batch_input(max_sequence_length, dataset, bs, idx):\n    \"\"\"\n\n    :param dataset: dataset\n    :param bs: batch size\n    :param idx: batch index\n    :return:\n    \"\"\"\n    batch_input = dataset[idx*bs:(idx+1)*bs]\n    #print(batch_input)\n    batch_data = pd.DataFrame.from_dict(batch_input)\n    #print(batch_data)\n    #print(batch_data)\n    target_fields = ['wids', 'tids', 'y', 'pw']\n    batch_input_var = []\n    for key in target_fields:\n        #print(\"for %s data\" % key)\n        data = list(batch_data[key].values)\n        #print(data[0])\n        #print(data[5])\n        if key == 'pw':\n            # for position weights\n            #batch_input_var.append(theano.shared(value=np.array(data, dtype='float32')))\n            batch_input_var.append(np.array(data, dtype='float32'))\n        else:\n            #batch_input_var.append(theano.shared(value=np.array(data, dtype='int32')))\n            batch_input_var.append(np.array(data, dtype='int32'))\n    batch_input_var.append(list(batch_data['sent'].values))\n\n    graph_data = list(batch_data['graphsage_embedding'].values)\n    graph_data = np.array(graph_data, dtype='float32')\n    graphsage_embedding = []\n\n    for s in range(len(batch_input_var[0])):\n        graph_embedding = []\n        for i in range(max_sequence_length):\n            graph_embedding.append(graph_data[s]) \n        graphsage_embedding.append(graph_embedding)\n\n    graphsage_embedding = np.array(graphsage_embedding, dtype=np.float32)\n    batch_input_var.append(graphsage_embedding)\n\n    return batch_input_var\n", "meta": {"hexsha": "937b9c8cf7a9fb5fc1ccb38c644aaacedd91598e", "size": 7618, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/alsc/ar-tnet/nn_utils_sentence_GraphSAGE.py", "max_stars_repo_name": "mainuliitkgp/AR-BERT", "max_stars_repo_head_hexsha": "d6d5e8542a3a1c76edac49cec9e99ebda6395725", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-03-06T17:41:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T08:42:58.000Z", "max_issues_repo_path": "src/alsc/ar-tnet/nn_utils_sentence_GraphSAGE.py", "max_issues_repo_name": "mainuliitkgp/AR-BERT", "max_issues_repo_head_hexsha": "d6d5e8542a3a1c76edac49cec9e99ebda6395725", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/alsc/ar-tnet/nn_utils_sentence_GraphSAGE.py", "max_forks_repo_name": "mainuliitkgp/AR-BERT", "max_forks_repo_head_hexsha": "d6d5e8542a3a1c76edac49cec9e99ebda6395725", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-19T14:04:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T14:04:42.000Z", "avg_line_length": 33.4122807018, "max_line_length": 105, "alphanum_fraction": 0.5741664479, "include": true, "reason": "import numpy,import theano", "num_tokens": 1893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.1990834329050347}}
{"text": "#!/usr/bin/env python\n\"\"\"Pre-calculate a grid of 5-sigma limiting mags for all times, filters, and DDF fields\n\"\"\"\n\n# imports\nimport sys\nimport warnings\nimport logging\nfrom argparse import ArgumentParser\n\nimport yaml\nimport numpy as np\nimport pandas as pd\nfrom astropy.coordinates import SkyCoord\nimport astropy.coordinates\nfrom astropy.time import Time\n\nimport lsst.sims.utils\nfrom lsst.sims.downtimeModel import ScheduledDowntimeData\nfrom lsst.sims.skybrightness_pre import SkyModelPre\nfrom lsst.sims.seeingModel import SeeingModel\n\n# constants\n\nDEFAULT_CONFIG = {\n    \"start_time\": \"2022-11-01T16:00:00Z\",\n    \"end_time\": \"2033-11-01T16:00:00Z\",\n    \"time_freq\": \"10min\",\n    \"site_name\": \"LSST\",\n    \"fields\": {\n        \"Elias S1\": SkyCoord(\"00h37m48s\", \"-44d00m00s\"),\n        \"XMM-LSS\": SkyCoord(\"02h22m50s\", \"-04d45m00s\"),\n        \"ECDFS\": SkyCoord(\"03h32m30s\", \"-28d06m00s\"),\n        \"COSMOS\": SkyCoord(\"10h00m24s\", \"+02d10m55s\"),\n        \"Euclid 1\": SkyCoord(\"03h55m52.8s\", \"-49d16m48s\"),\n        \"Euclid 2\": SkyCoord(\"04h14m24s\", \"-47d36m00s\"),\n    },\n    \"max_sun_alt_deg\": -18.0,\n    \"max_field_airmass\": 2.6,\n}\n\nSKY_MODEL = SkyModelPre()\n\n# exception classes\n\n# interface functions\n\n\ndef calc_m5(config=None):\n    \"\"\"Calculate the 5-sigma limiting magnitudes for a set of fields\n\n    Parameters\n    ----------\n    config : `dict'\n        Configuration parameters, with the following contents:\n        start_time : `str` or period-like, default None\n            Start of time range\n        end_time : `str` or period-like, default None\n            End of time range\n        time_freq : `str`\n            Time frequency, designated by a pandas frequency string\n        fields : `dict` [`str`, ~astropy.coordinates.SkyCoord`]\n            The pointings for which to calculate limiting mags.\n        site_name : `str`\n            The name of the observatory site.\n        max_sun_alt_deg: `float`\n            Maximum altitude of sun for observing time, in degrees\n        max_field_airmass: `float`\n            Maximum airmass at which to observe\n\n    Returns\n    -------\n    m5limits : `pandas.DataFrame`\n        A `pandas.Series` of the 5 sigma limiting magnitudes, indexed by the `mjd` and field name.\n\n    Notes\n    -----\n\n    For more on pandas frequency strings, see `the pandas documentation\n<https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.\n\n    \"\"\"\n\n    config = DEFAULT_CONFIG if config is None else config\n\n    # Work around bug in lsst.sims.utils.Site, which compares by reference\n    # rather than equivilence\n    site_name = \"LSST\" if config[\"site_name\"] == \"LSST\" else config[\"site_name\"]\n    site = lsst.sims.utils.Site(site_name)\n    location = astropy.coordinates.EarthLocation(\n        lat=site.latitude, lon=site.longitude, height=site.height\n    )\n\n    periods = _init_periods(config, location)\n\n    field_coords = _init_field_coords(config)\n\n    logger.debug(\"Building the sampled_fields DataFrame\")\n    # Cross join using the hacky pandas method\n    periods[\"dummy\"] = True\n    field_coords[\"dummy\"] = True\n    sampled_fields = (\n        periods.merge(field_coords, on=\"dummy\", how=\"outer\")\n        .drop(columns=[\"dummy\"])\n        .set_index([\"field_name\", \"period\"], drop=False)\n    )\n    sampled_fields.query(\"observing\", inplace=True)\n\n    logger.debug(\"Calculating field airmass and filtering\")\n    field_zd_rad = np.pi / 2 - (\n        SkyCoord(\n            ra=sampled_fields.field_ra,\n            dec=sampled_fields.field_decl,\n            frame=\"icrs\",\n            unit=\"deg\",\n        )\n        .transform_to(\n            astropy.coordinates.AltAz(\n                location=location, obstime=Time(sampled_fields[\"mjd\"], format=\"mjd\")\n            )\n        )\n        .alt.rad\n    )\n    sampled_fields[\"field_airmass\"] = 1.0 / np.cos(field_zd_rad)\n    max_field_airmass = config[\"max_field_airmass\"]\n    sampled_fields.query(f\"field_airmass < {max_field_airmass}\", inplace=True)\n\n    logger.debug(\"Calculating field angle with the moon\")\n    sampled_fields[\"moon_angle\"] = (\n        SkyCoord(\n            ra=sampled_fields[\"field_ra\"],\n            dec=sampled_fields[\"field_decl\"],\n            frame=\"icrs\",\n            unit=\"deg\",\n        ).separation(\n            SkyCoord(\n                ra=sampled_fields[\"moon_ra\"],\n                dec=sampled_fields[\"moon_decl\"],\n                frame=\"icrs\",\n                unit=\"deg\",\n            )\n        )\n    ).deg\n\n    logger.debug(\"Calculating sky brightness\")\n    sampled_fields = sampled_fields.groupby(\"mjd\").apply(_get_sky_mags)\n\n    sampled_fields = sampled_fields.groupby(\"band\").apply(_compute_band_fwhms)\n\n    sampled_fields = sampled_fields.groupby(\"band\").apply(_compute_band_m5)\n\n    sampled_fields.set_index([\"field_name\", \"period\"], drop=False, inplace=True)\n\n    logger.debug(\"Finished constructing the m5 DataFrame\")\n    return sampled_fields\n\n\n# classes\n\n# internal functions & classes\n\n\ndef _init_periods(config, location):\n\n    logger.debug(\"Laying down time period boundries\")\n    period_index = pd.period_range(\n        config[\"start_time\"],\n        config[\"end_time\"],\n        freq=config[\"time_freq\"],\n        name=\"period\",\n    )\n    times = Time(\n        pd.to_datetime(period_index.to_timestamp()),  # pylint: disable=no-member\n        location=location,\n    )\n\n    logger.debug(\"Calculating solar ephemeris\")\n    sun_coords = astropy.coordinates.get_sun(times)\n\n    logger.debug(\"Calculating lunar ephemeris\")\n    moon_coords = astropy.coordinates.get_moon(times)\n    moon_elongation = moon_coords.separation(sun_coords)\n\n    logger.debug(\"Converting solar and lunar coordinates to horizon system\")\n    horizon_coordinate_system = astropy.coordinates.AltAz(location=location)\n    sun_hzn = sun_coords.transform_to(horizon_coordinate_system)\n    moon_hzn = moon_coords.transform_to(horizon_coordinate_system)\n\n    logger.debug(\"Building the period DataFrame\")\n    periods = pd.DataFrame(\n        {\n            \"mjd\": times.mjd,\n            \"time\": times,\n            \"lst\": times.sidereal_time(\"mean\"),\n            \"sun_ra\": sun_coords.ra.deg,\n            \"sun_decl\": sun_coords.dec.deg,\n            \"sun_alt\": sun_hzn.alt.deg,\n            \"moon_ra\": moon_coords.ra.deg,\n            \"moon_decl\": moon_coords.dec.deg,\n            \"moon_alt\": moon_hzn.alt.deg,\n            \"moon_elongation\": moon_elongation.deg,\n        },\n        index=period_index,\n    )\n\n    periods[\"moon_waxing\"] = (\n        periods[\"moon_elongation\"].shift(-1) > periods[\"moon_elongation\"]\n    )\n\n    previous_waxing = periods[\"moon_waxing\"].shift(\n        1, fill_value=periods.iloc[0][\"moon_waxing\"]\n    )\n    periods[\"new_moon\"] = periods[\"moon_waxing\"] & ~previous_waxing\n    periods[\"lunation\"] = periods[\"new_moon\"].cumsum()\n\n    mean_local_solar_jd = 2400000.5 + periods[\"mjd\"] + (location.lon.deg / 360.0)\n    night_local_solar_jd = np.floor(mean_local_solar_jd).astype(int)\n    periods[\"night\"] = night_local_solar_jd - np.min(night_local_solar_jd) + 1\n\n    # Mark daytime periods\n    periods[\"observing\"] = periods.sun_alt <= config[\"max_sun_alt_deg\"]\n\n    # Mark scheduled downtime\n    periods.reset_index(inplace=True)\n    periods.set_index(\"mjd\", inplace=True)\n    for down_time in ScheduledDowntimeData(times.min())():\n        periods.loc[down_time[\"start\"].mjd : down_time[\"end\"].mjd, \"observing\"] = False\n    periods.reset_index(inplace=True)\n    periods.set_index(\"period\", drop=False, inplace=True)\n    return periods\n\n\ndef _init_field_coords(config):\n    fields = config[\"fields\"]\n\n    logger.debug(\"Building the fields DataFrame\")\n    field_coords = (\n        pd.DataFrame(\n            {\n                fld: {\n                    \"field_name\": fld,\n                    \"field_ra\": fields[fld].ra.deg,\n                    \"field_decl\": fields[fld].dec.deg,\n                }\n                for fld in fields\n            }\n        )\n        .T.set_index(\"field_name\")\n        .apply(pd.to_numeric)\n        .reset_index()\n    )\n\n    logger.debug(\"Adding healpix to field coordinates\")\n    field_coords[\"field_hpix32\"] = lsst.sims.utils.raDec2Hpid(\n        32, field_coords.field_ra, field_coords.field_decl\n    )\n\n    return field_coords\n\n\ndef _get_sky_mags(sampled_fields_mjd):\n    mjd = sampled_fields_mjd.mjd[0]\n    assert np.all(mjd == sampled_fields_mjd[\"mjd\"])\n\n    mags = SKY_MODEL.returnMags(mjd, sampled_fields_mjd.field_hpix32, badval=-np.inf)\n    sampled_fields_band_mjds = []\n    for band in mags:\n        sampled_fields_band_mjd = sampled_fields_mjd.copy()\n        sampled_fields_band_mjd[\"band\"] = band\n        sampled_fields_band_mjd[\"sky_mag\"] = mags[band]\n        sampled_fields_band_mjds.append(sampled_fields_band_mjd)\n    out_sampled_fields_mjd = pd.concat(sampled_fields_band_mjds)\n    return out_sampled_fields_mjd\n\n\ndef _compute_band_fwhms(sampled_fields_band):\n    band = sampled_fields_band[\"band\"][0]\n    assert np.all(band == sampled_fields_band[\"band\"])\n\n    logger.debug(\"Calculating the model seeing in %s\", band)\n    seeing_model = SeeingModel()\n\n    band_idx = [\"u\", \"g\", \"r\", \"i\", \"z\", \"y\"].index(band)\n    sampled_fields_band = sampled_fields_band.copy()\n    sampled_fields_band[\"fwhm\"] = seeing_model(\n        0.7, sampled_fields_band[\"field_airmass\"].values\n    )[\"fwhmEff\"][band_idx]\n    return sampled_fields_band\n\n\ndef _compute_band_m5(sampled_fields_band):\n    band = sampled_fields_band[\"band\"][0]\n    assert np.all(band == sampled_fields_band[\"band\"])\n\n    logger.debug(\"Calculating the 5-sigma magnitude limit in %s\", band)\n    sampled_fields_band = sampled_fields_band.copy()\n    sampled_fields_band[\"m5\"] = lsst.sims.utils.m5_flat_sed(\n        band,\n        sampled_fields_band[\"sky_mag\"],\n        sampled_fields_band[\"fwhm\"],\n        30.0,\n        sampled_fields_band[\"field_airmass\"],\n        nexp=1.0,\n    )\n    return sampled_fields_band\n\n\ndef read_config(fname):\n    \"\"\"Read m5 configuration file\n\n    Parameters\n    ----------\n    fname: `str`\n        The name of the file to read configuration from.\n\n    Return\n    ------\n    config: `dict`\n        Dictionary of configuration values\n    \"\"\"\n    logger.debug(\"Reading configuration from %s\", fname)\n\n    with open(fname, \"r\") as config_file:\n        config = yaml.load(config_file.read(), Loader=yaml.FullLoader)\n\n    # Convert field coordinates into astroy.SkyCoord objects\n    for field in config[\"fields\"]:\n        config[\"fields\"][field] = SkyCoord(**config[\"fields\"][field])\n\n    return config\n\n\ndef main():\n    \"\"\"Parse command line arguments and config file, and run\"\"\"\n    parser = ArgumentParser()\n    parser.add_argument(\"config\", help=\"configuration file\")\n    parser.add_argument(\"output\", help=\"file in which to write results\")\n\n    args = parser.parse_args()\n    config_fname = args.config\n    output_fname = args.output\n\n    warnings.filterwarnings(\n        \"ignore\",\n        message=\".*Tried to .* for times after IERS data is valid.*\",\n        category=astropy.utils.exceptions.AstropyWarning,\n    )\n    warnings.filterwarnings(\n        \"ignore\",\n        message=\".*dubious year.*\",\n        category=astropy.utils.exceptions.AstropyWarning,\n    )\n\n    config = read_config(config_fname)\n\n    m5_limits = calc_m5(config)\n\n    (\n        m5_limits.set_index([\"field_name\", \"mjd\"])\n        .drop(columns=[\"period\"])\n        .to_hdf(output_fname, \"m5\")\n    )\n\n    return 0\n\n\ndef _init_logger(log_level=logging.DEBUG):\n    \"\"\"Create the ddfpresched logger and set initial configuration\"\"\"\n    ddfpresched_logger = logging.getLogger(\"ddfpresched\")\n    ddfpresched_logger.setLevel(log_level)\n    handler = logging.StreamHandler()\n    handler.setLevel(log_level)\n    formatter = logging.Formatter(\"%(asctime)s\\t%(name)s\\t%(levelname)s\\t%(message)s\")\n    handler.setFormatter(formatter)\n    ddfpresched_logger.addHandler(handler)\n    return ddfpresched_logger\n\n\nif __name__ == \"__main__\":\n    logger = _init_logger()\n    status = main()  # pylint: disable=invalid-name\n    sys.exit(status)\n", "meta": {"hexsha": "8eae7cb028974bb6ce27e791a6d71814acb871cb", "size": 11943, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/m5.py", "max_stars_repo_name": "lsst/rtn-014", "max_stars_repo_head_hexsha": "773e470c06371fffb3c9844923065a9f0e0e70bf", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/m5.py", "max_issues_repo_name": "lsst/rtn-014", "max_issues_repo_head_hexsha": "773e470c06371fffb3c9844923065a9f0e0e70bf", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/m5.py", "max_forks_repo_name": "lsst/rtn-014", "max_forks_repo_head_hexsha": "773e470c06371fffb3c9844923065a9f0e0e70bf", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.182767624, "max_line_length": 98, "alphanum_fraction": 0.6546931257, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 2965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.1990834329050347}}
{"text": "from typing import ClassVar, Dict, List, Optional, Sequence, Union, Tuple, Any, Type\nfrom dataclasses import dataclass, field\nimport numpy as np\nfrom pygmsh.common import bspline\nfrom ..common import Pointer\nfrom pygmsh.geo import Geometry\nfrom math import ceil, floor, sqrt\nfrom geomdl import BSpline\nimport gmsh  # To do some low level creation\n\n\"\"\"\nNM: Abbreviation for 'not mine'. Used to denote codes that are took from pyiges\n\"\"\"\n\n\"\"\"\nOmitted entity type list\n202: Angular Dimension Entity, \n210: General Label Entity, 212: General Note Entity, 214: Leader Arrow Entity, \n216: Linear Dimension Entity, 218: Ordimate Dimension Entity, \n\"\"\"\n\nParameter = Union[str, float]\n\n\n@dataclass\nclass Entity:\n    type_number: int\n    # parameter data pointer\n    pd_pointer: int\n    structure: int\n    line_font_pattern: int\n    level: int\n    view: int\n    transformation_pointer: int\n    label_display_associativity: int\n\n    status_number: int\n    # instead of using the sequence number, use the index of entity\n    # sequence_number: int\n    line_weight: int\n    color: int\n    parameter_line_count: int\n    form: int\n    entity_label: str\n    subscript: int\n    # instead of just [], below is required\n    # because mutable default is not allowed\n    parameters: List[Parameter] = field(default_factory=list)\n\n    _geometry: Optional[Any] = None\n    _render: ClassVar[bool] = True\n\n    @staticmethod\n    def parse_status_number(x: str) -> int:\n        \"\"\"\n        inputs\n            x: A candidate status number in string\n        output\n            status number in integer\n        \"\"\"\n        numbers = x.split(\" \")\n        numbers = [n.zfill(2) for n in numbers]\n        return int(\"\".join(numbers))\n\n    def add_parameters(self, *args: List[Parameter]):\n        self.parameters += args\n\n    def to_vtk(self, entities: Dict[Pointer, \"Entity\"], geometry: Geometry, lcar: float = 0.1):\n        \"\"\"Transforms this entity into a vtk object\"\"\"\n        raise NotImplementedError\n\n    def to_vtk_operator(self) -> Any:\n        \"\"\"\n        Transforms this entity into a vtk operator.\n        Not an actual object itself, but used to manipulate other vtk objects.\n        \"\"\"\n        raise NotImplementedError\n\n\n@dataclass\nclass Point(Entity):  # 116\n\n    def add_parameters(self, *args: Tuple[float]):\n        self.pos = np.array(args[:3])\n\n    def to_vtk(self, entities: Dict[Pointer, \"Entity\"], geometry: Geometry, lcar: float = 0.1):\n        if not self._render:\n            return\n        _point = self.pos\n\n        if self.transformation_pointer:\n            T = entities[self.transformation_pointer]\n            point = T.transform(_point.T)\n        else:\n            point = _point\n\n        geometry.add_point(point)\n\n\n@dataclass\nclass Line(Entity):  # 110\n\n    def add_parameters(self, *args: Tuple[float]):\n        self.start = args[:3]\n        self.end = args[3:6]\n\n    def to_vtk(self, entities: Dict[Pointer, \"Entity\"], geometry: Geometry, lcar: float = 0.1):\n        if not self._render:\n            return\n\n        point1 = np.array(self.start)\n        point2 = np.array(self.end)\n\n        if self.transformation_pointer:\n            transformation = entities[self.transformation_pointer]\n            point1 = transformation.transform(point1)\n            point2 = transformation.transform(point2)\n\n        point1 = geometry.add_point(point1, lcar)\n        point2 = geometry.add_point(point2, lcar)\n\n        self._geometry = geometry.add_line(point1, point2)\n\n\n@dataclass\nclass CopiousData(Entity):  # 106\n    \"\"\"\n    Definition of set of points. Type specifies 1: couples, 2: triples, 3: sextuplets\n\n    if type is 1, then 2nd parameter is the common z value for all the other\n    xy pairs\n    \"\"\"\n\n    TYPE2PARSE_LENGTH = {1: 2, 2: 3, 3: 6}\n\n    def add_parameters(self, *args: List[Parameter]):\n        self.tuple_type: int = int(args[0])\n\n        if self.tuple_type == 1:  # couples\n            self.common_z = args[1]\n            coordinates = args[2:]\n        else:\n            self.common_z = None\n            coordinates = args[1:]\n\n        length = self.TYPE2PARSE_LENGTH[self.tuple_type]\n        self.point_list: List[List] = self.parse_tuple(coordinates, length)\n\n    def parse_tuple(self, args: List[Parameter], length: int) -> List[Tuple]:\n        tuple_list: List[List] = []\n\n        # /2 because 2 floats in a couple\n        if self.common_z:\n            for tuple_idx in range(int(len(args)/length)):\n                start = tuple_idx*length\n                end = (tuple_idx+1)*length\n                tuple_list.append(\n                    [*args[start: end], self.common_z])\n\n        else:\n            for tuple_idx in range(int(len(args)/length)):\n                start = tuple_idx*length\n                end = (tuple_idx+1)*length\n                tuple_list.append(args[start: end])\n\n        return tuple_list\n\n    def to_vtk(self, entities: Dict[Pointer, \"Entity\"], geometry: Geometry, lcar: float = 0.1):\n        if not self._render:\n            return\n        \"\"\"\n        Not a mesh, so this can be discarded\n        \"\"\"\n        for tuple_point in self.point_list:\n            geometry.add_point(tuple_point)\n\n\n@dataclass\nclass CircularArc(Entity):  # 100\n    \"\"\"\n    Simple circular arc of constant radius. Usually defined with a Transformation Matrix Entity (Type 124).\n    \"\"\"\n\n    def add_parameters(self, *args: List[Parameter]):\n        self.z, self.x, self.y, self.x1, self.y1, self.x2, self.y2 = args[:7]\n\n    def to_vtk(self, entities: Dict[Pointer, \"Entity\"], geometry: Geometry, lcar: float = 0.1):\n        if not self._render:\n            return\n\n        start = np.array([self.x1, self.y1, self.z])\n        end = np.array([self.x2, self.y2, self.z])\n        center = np.array([self.x, self.y, self.z])\n\n        if self.transformation_pointer:\n            transfomation = entities[self.transformation_pointer]\n\n            start = transfomation.transform(start)[0]\n            end = transfomation.transform(end)[0]\n            center = transfomation.transform(center)[0]\n\n        start = geometry.add_point(start, lcar)\n        end = geometry.add_point(end, lcar)\n        center = geometry.add_point(center, lcar)\n\n        geometry.add_circle_arc(start, center, end)\n\n\n@dataclass\nclass ConicArc(Entity):  # 124\n    \"\"\"\n    Arc defined by the equation: Axt^2 + Bxtyt + Cyt^2 + Dxt + Eyt + F = 0, with a Transformation Matrix (Entity 124). Can define an ellipse, parabola, or hyperbola.\n\n    The definitions of the terms ellipse, parabola, and hyperbola are given in terms of the quantities Q1,Q2, andQ3. These quantities are:\n\n            |  A   B/2  D/2 |        |  A   B/2 | \n        Q1= | B/2   C   E/2 |   Q2 = | B/2   C  |   Q3 = A + C \n            | D/2  E/2   F  | \n    A parent conic curve is:\n\n    An ellipse if Q2 > 0 and Q1Q3 < 0.\n    A hyperbola if Q2 < 0 and Q1 != 0.\n    A parabola if Q2 = 0 and Q1 != 0.\n\n    +@ from https://en.wikipedia.org/wiki/Matrix_representation_of_conic_sections\n    center: \n    |xc| = | (BE - 2CD)/(4AC - B^2) |\n    |yc| = | (DB - 2AE)/(4AC - B^2) |\n    \"\"\"\n\n    def add_parameters(self, *args: List[Parameter]):\n        self.a, self.b, self.c, self.d, self.e, self.f, \\\n            self.x1, self.y1, self.z1, self.x2, self.y2, self.z2 = args[:12]\n\n    def to_vtk(self, entities: Dict[Pointer, \"Entity\"], geometry: Geometry, lcar: float = 0.1):\n        if not self._render:\n            return\n\n        start = np.array([self.x1, self.y1, self.z1])\n        end = np.array([self.x2, self.y2, self.z2])\n        center = np.array([0, 0, 0])\n\n        a = self.get_major_raidus(\n            self.a, self.b, self.c, self.d, self.e, self.f)\n        point_on_major = np.array([a, 0, 0])\n\n        if self.transformation_pointer:\n            t = entities[self.transformation_pointer]\n\n            start = t.transform(start)[0]\n            end = t.transform(end)[0]\n            center = t.transform(center)[0]\n            point_on_major = t.transform(point_on_major)[0]\n\n        start = geometry.add_point(start, lcar)\n        end = geometry.add_point(end, lcar)\n        center = geometry.add_point(center, lcar)\n        point_on_major = geometry.add_point(point_on_major, lcar)\n\n        geometry.add_ellipse_arc(start, center, point_on_major, end)\n\n    @staticmethod\n    def get_x_range(start_pos: np.ndarray, end_pos: np.ndarray, step: float) -> np.ndarray:\n\n        pos = np.arange(start=start_pos[0], stop=end_pos[0]+step, step=step)\n        neg = np.array([x * -1 for x in np.flip(pos)])\n        return np.hstack((neg, pos))\n\n    @staticmethod\n    def get_major_raidus(a, b, c, d, e, f) -> np.float:\n        \"\"\"\n        For an ellipse or hyperbola, you can find the canonical form \n        from the general form. \n        We only need `a`, the major radius so `b` is not calculated\n        Reference: https://en.wikipedia.org/wiki/Conic_section#Matrix_notation \n        \"\"\"\n        sol = np.array([[a, b/2], [b/2, c]])\n        conic_matrix = np.array([[a, b/2, d/2], [b/2, c, e/2], [d/2, e/2, f]])\n\n        eig = np.linalg.eigvals(sol)\n        l1, l2 = eig  # lambda 1 and lambda 2\n        S = np.linalg.det(conic_matrix)\n\n        canonical_a = -S/(l1**2 * l2)\n        return canonical_a\n\n    @staticmethod\n    def get_y_positive(a, b, c, d, e, f, x) -> Tuple[float, float]:\n        \"\"\"\n        Solve general form for `x`. Given x calculate y the positive version.\n        Equations found using `sympy solve`.\n        \"\"\"\n        y_positive = (-b*x - d + sqrt(-4*a*c*x**2 - 4*a*e*x -\n                                      4*a*f + b**2*x**2 + 2*b*d*x + d**2))/(2*a)\n\n        return y_positive\n\n    @staticmethod\n    def get_y_negative(a, b, c, d, e, f, x) -> Tuple[float, float]:\n        y_negative = -(b*x + d + sqrt(-4*a*c*x**2 - 4*a*e*x -\n                                      4*a*f + b**2*x**2 + 2*b*d*x + d**2))/(2*a)\n\n        return y_negative\n\n\n@dataclass\nclass Transformation(Entity):  # 124\n    \"\"\"\n    new E = RE + T (E: Entity coordinate)\n\n        | r11 r12 r13 |       | T1 |\n    R = | r21 r22 r23 |   T = | T2 |\n        | r31 r32 r33 |       | T3 |\n\n    \"\"\"\n\n    def add_parameters(self, *args: List[float]):\n        r11, r12, r13, t1, \\\n            r21, r22, r23, t2, \\\n            r31, r32, r33, t3 = (args[:12])\n\n        self.r = np.array([[r11, r12, r13],\n                           [r21, r22, r23],\n                           [r31, r32, r33]])\n        self.t = np.array([[t1, t2, t3]])\n\n    def transform(self, coordinate: np.array) -> np.array:\n\n        return self.r.dot(coordinate) + self.t\n\n    def to_vtk(self, entities: Dict[Pointer, \"Entity\"], geometry: Geometry, lcar: float = 0.1):\n        if not self._render:\n            return\n        # does nothing by itself\n        pass\n\n\n@dataclass\nclass SubfigureDefinition(Entity):  # 308\n\n    def add_parameters(self, *args: List[Parameter]):\n        self.depth = int(args[0])\n        self.name = args[1]\n        self.length = int(args[2])\n        self.figures = [int(pointer) for pointer in args[3:]]\n\n    def to_vtk(self, entities: Dict[Pointer, \"Entity\"], geometry: Geometry, lcar: float = 0.1):\n        if not self._render:\n            return\n\n        if self.transformation_pointer:\n            raise NotImplementedError\n        pass\n\n\n@dataclass\nclass SingularSubfigureInstance(Entity):  # 408\n\n    def add_parameters(self, *args: List[Parameter]):\n        self.pointer = int(args[0])\n        self.translation = np.array(args[1:4])\n        self.scale_factor = args[4]\n\n\n@dataclass\nclass RationalBSplineCurve(Entity):\n    \"\"\"\n    Composes analytic curves.\n    Form: 0=Determined by data 1=Line 2=Circular arc 3=Eliptic arc 4=Parabolic arc 5=Hyperbolic arc\n    \"\"\"\n\n    def add_parameters(self, *args: List[Parameter]):\n        self.K, self.degree, self.flag1, self.flag2, self.flag3, self.flag4 \\\n            = map(lambda x: int(x), args[:6])\n\n        weight_start_idx = 8 + self.K + self.degree\n        control_start_idx = weight_start_idx + self.K + 1\n        etc_start_idx = control_start_idx + 3 * self.K + 3\n        knot_range = range(6, weight_start_idx)\n        weight_range = range(weight_start_idx, control_start_idx)\n\n        self.v0, self.v1, self.xn, self.yn, self.zn = args[etc_start_idx:]\n\n        self.knots = [args[i] for i in knot_range]\n        self.weights = [args[i] for i in weight_range]\n        temp_control_points = args[control_start_idx:etc_start_idx]\n        self.control_points = [temp_control_points[i:i + 3] for i in range(0, len(temp_control_points), 3)]\n\n    def to_vtk(self, entities: Dict[Pointer, \"Entity\"], geometry: Geometry, lcar: float = 0.1):\n        if not self._render:\n            return\n\n        curve = BSpline.Curve()\n        curve.degree = self.degree\n        curve.ctrlpts = self.control_points\n        curve.knotvector = self.knots\n        curve.delta = lcar\n\n        _points = curve.evalpts\n\n        points = []\n        for point in _points:\n\n            if self.transformation_pointer:\n                transfomation = entities[self.transformation_pointer]\n\n                point = transfomation.transform(point)[0]\n\n            point = geometry.add_point(point, lcar)\n            points.append(point)\n\n        spline = geometry.add_bspline(points)\n\n\n@dataclass\nclass RationalBSplineSurface(Entity):\n    \"\"\"\n    This is a surface entity defined by multiple surfaces. The form number describes the general type: 0=determined from data, 1=Plane, 2=Right circular cylinder, 3=Cone, 4=Sphere, 5=Torus, 6=Surface of revolution, 7=Tabulated cylinder, 8=Ruled surface, 9=General quadratic surface.\n\n    Takes up most of the time saving.\n    \"\"\"\n\n    def add_parameters(self, *args: List[Parameter]):\n        start_idx = 9\n        self.k1, self.k2, self.m1, self.m2, \\\n            self.flag1, self.flag2, self.flag3, self.flag4, self.flag5 \\\n            = map(lambda x: int(x), args[:start_idx])\n\n        knot2_start = start_idx + self.k2 + self.m1 + 2\n        weight_start = knot2_start + self.k1 + self.m2 + 2\n        self.knot1 = args[start_idx: knot2_start]\n        self.knot2 = args[knot2_start: weight_start]\n\n        weight_count = (self.k2 + 1) * (self.k1 + 1)\n        control_start = weight_start + weight_count\n        self.weights = args[weight_start: control_start]\n\n        etc_start = control_start + 3 * weight_count\n\n        self.control_points: List[List] = []\n\n        i = control_start\n        while i < etc_start:\n            self.control_points.append(np.array(args[i: i+3]))\n            i += 3\n\n        self.control_points = np.array(\n            self.control_points).reshape(self.k2+1, self.k1 + 1, 3)\n\n        self.U0, self.U1, self.V0, self.V1 = args[etc_start:]\n\n        assert len(self.knot1) == (2 + self.k2 + self.m1)\n        assert len(self.knot2) == (2 + self.k1 + self.m2)\n        assert len(self.weights) == weight_count\n        assert self.control_points.size == (weight_count * 3)\n\n    def to_vtk(self, entities: Dict[Pointer, \"Entity\"], geometry: Geometry, lcar: float = 0.1):\n        if not self._render:\n            return\n\n        rows, cols, z = self.control_points.shape\n        # The id have to match, not just coordinates\n        top = []\n        for i in range(0, cols):\n            point = self.control_points[0, i]\n            top.append(geometry.add_point(point, lcar))\n        top_spline = geometry.add_bspline(top)\n\n        right = [top[-1]]\n        for i in range(1, rows):\n            point = self.control_points[i, cols-1]\n            right.append(geometry.add_point(point, lcar))\n        right_spline = geometry.add_bspline(right)\n\n        bottom = [right[-1]]\n        for i in range(cols-2, -1, -1):\n            point = self.control_points[rows-1, i]\n            bottom.append(geometry.add_point(point, lcar))\n        bottom_spline = geometry.add_bspline(bottom)\n\n        left = [bottom[-1]]\n        for i in range(rows-2, 0, -1):\n            point = self.control_points[i, 0]\n            left.append(geometry.add_point(point, lcar))\n        left.append(top[0])\n        left_spline = geometry.add_bspline(left)\n\n        loop = geometry.add_curve_loop(\n            [top_spline, right_spline, bottom_spline, left_spline])\n        surface = geometry.add_surface(loop)\n\n\n@dataclass\nclass Face(Entity):\n    \"\"\"\n    Defines a bound portion of three dimensional space (R^3) which has a finite area. Used to construct B-Rep Geometries\n    \"\"\"\n\n    def add_parameters(self, *args: List[Parameter]):\n        self.pointer = int(args[0])\n        self.loop_count = int(args[1])\n        self.loop_flag = int(args[2])\n\n        self.loops = [args[i] for i in range(3, 2 + self.loop_count)]\n\n\n@dataclass\nclass LoopEdge:\n    \"\"\"Represents edge in a loop. NOT AN ENTITY\"\"\"\n\n    type: int\n    pointer: int\n    index: int\n    flag: bool\n    curves: List[Tuple[bool, int]]\n\n\n@dataclass\nclass Loop(Entity):\n    \"\"\"Defines a loop, specifying a bounded face, for B-Rep Geometries.\"\"\"\n\n    def add_parameters(self, *args: List[Parameter]):\n        self.edge_count = int(args[0])\n        self.edges: List[LoopEdge] = []\n\n        edge_idx = 0\n        arg_idx = 1\n        while edge_idx < self.edge_count:\n            edge_type = int(args[arg_idx])\n            edge_list_pointer = int(args[arg_idx + 1])\n            edge_index = int(args[arg_idx + 2])\n            flag = bool(args[arg_idx + 3])\n            curve_count = int(args[arg_idx + 4])\n            arg_idx += 5\n\n            curves = []\n            for i in range(curve_count):\n                iso = bool(args[arg_idx])\n                psc = int(args[arg_idx + 1])\n                curves.append((iso, psc))\n                arg_idx += 2\n\n            edge = LoopEdge(edge_type, edge_list_pointer,\n                            edge_index, flag, curves)\n            self.edges.append(edge)\n\n            edge_idx += 1\n\n\n@dataclass\nclass Edge:\n    curve: int\n    start_vertex_list: int\n    start_vertex_index: int\n    end_vertex_list: int\n    end_vertex_index: int\n\n\n@dataclass\nclass EdgeList(Entity):\n\n    def add_parameters(self, *args: List[Parameter]):\n        edge_count = int(args[0])\n\n        edge_index = 0\n        arg_index = 1\n        self.edges: List[Edge] = []\n\n        while edge_index < edge_count:\n            e = Edge(*map(lambda x: int(x), args[arg_index:arg_index+5]))\n            self.edges.append(e)\n\n            arg_index += 5\n            edge_index += 1\n\n\n@dataclass\nclass Vertex:\n    x: float\n    y: float\n    z: float\n\n\n@dataclass\nclass VertexList(Entity):\n\n    def add_parameters(self, *args: List[Parameter]):\n        vertex_count = int(args[0])\n\n        vertex_index = 0\n        arg_index = 1\n        self.vertices: List[Vertex] = []\n\n        while vertex_index < vertex_count:\n            v = Vertex(*args[arg_index: arg_index + 3])\n            self.vertices.append(v)\n            arg_index += 3\n            vertex_index += 1\n\n\n@dataclass\nclass SurfaceOfRevolution(Entity):  # 120\n\n    def add_parameters(self, *args: List[Parameter]):\n        self.axis_line = Pointer(args[0])\n        self.target = Pointer(args[1])\n        self.start_angle, self.end_angle = args[2:4]  # radian\n\n    def to_vtk(self, entities: Dict[Pointer, \"Entity\"], geometry: Geometry, lcar: float = 0.1):\n        if not self._render:\n            return\n        line = entities[self.axis_line]\n        target = entities[self.target]\n        if not target._geometry:\n            # this entity is dependent on another entity,\n            # if the other entity is not rendered, this will not work\n            # so enable it for this\n            old_render = target._render\n            target._render = True\n            target.to_vtk(entities, geometry, lcar)\n            target._render = old_render\n        target_geometry = target._geometry\n\n        geometry.revolve(target_geometry, line.start, line.end, 3.14)\n\n\n@dataclass\nclass CompositeCurve(Entity):  # 102\n\n    def add_parameters(self, *args: List[Parameter]):\n        curve_count = int(args[0])\n        self.curves: List[Pointer] = list(map(Pointer, args[1:]))\n\n    def to_vtk(self, entities: Dict[Pointer, \"Entity\"], geometry: Geometry, lcar: float = 0.1):\n        if not self._render:\n            return\n\n\n# todo\n# Surface Revolution Type 120\n# Composite Curve 102\n# Trimmed Surface 144\n# Curve on Parametric Surface 142\n", "meta": {"hexsha": "550a3e80b94c249496955d8f4e93f236d3fed15e", "size": 20141, "ext": "py", "lang": "Python", "max_stars_repo_path": "iges2vtk/iges/entity.py", "max_stars_repo_name": "bullgom/igs2vtk", "max_stars_repo_head_hexsha": "6f6d8e443430217309e18a9ec766dcb7b72f4942", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-27T08:58:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T02:52:08.000Z", "max_issues_repo_path": "iges2vtk/iges/entity.py", "max_issues_repo_name": "bullgom/igs2vtk", "max_issues_repo_head_hexsha": "6f6d8e443430217309e18a9ec766dcb7b72f4942", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "iges2vtk/iges/entity.py", "max_forks_repo_name": "bullgom/igs2vtk", "max_forks_repo_head_hexsha": "6f6d8e443430217309e18a9ec766dcb7b72f4942", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2748447205, "max_line_length": 282, "alphanum_fraction": 0.5981331612, "include": true, "reason": "import numpy", "num_tokens": 5278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19908342729603198}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug  5 19:48:34 2017\n\n@author: max\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom math import pi, sqrt\nfrom collections import namedtuple\nfrom .Functions.CalcIOLMaxwellian import calc_iol_maxwellian\nfrom .Functions.CalcIOLMonoEn import calc_iol_mono_en\nfrom .Functions.CalcIOLBeams import calc_iol_beams\nfrom GT3.utilities.PlotBase import PlotBase\nimport sys\nimport GT3.constants as constants\nfrom GT3 import Core\n\nm_d = constants.deuteron_mass\nm_t = constants.triton_mass\nm_c = constants.carbon_mass\nm_a = constants.alpha_mass\n\n\nclass IOL(PlotBase):\n    \"\"\"\n    \"\"\"\n\n    def __init__(self, inp, core: Core):\n        super().__init__()\n        sys.dont_write_bytecode = True\n        np.warnings.filterwarnings('ignore')\n\n        numcos = inp.numcos  # TODO: Clean this up\n        angles = np.linspace(-1, 1, inp.numcos + 1)\n        self.coslist = ((angles + np.roll(angles, -1)) / 2)[:-1]\n        self.rho = core.rho\n        self.set_plot_rho1d(self.rho[:, 0])\n        self.calc_iol_beams = calc_iol_beams\n        polpts = len(core.rho[-1])\n        radpts = len(core.rho.T[-1])\n\n        # THE FOLLOWING ARRAYS ARE 4-DIMENSIONAL ARRAYS\n        # [ LAUNCH THETA POSITION , LAUNCH ANGLE COSINE, LAUNCH r  , EXIT THETA POSITION  ]\n\n        # NOTE TO FUTURE DEVELOPERS: IF YOU TRY TO LOOP OVER THE PLASMA POINTS, LAUNCH ANGLES, AND\n        # EXIT LOCATIONS IN PYTHON THE WAY YOU WOULD IN C OR FORTRAN, IT'S GOING TO TAKE FOREVER.\n        # ALTHOUGH THESE ARRAYS TAKE MORE MEMORY THAT I'D LIKE, IT'S CURRENTLY NECESSARY TO DO IT THIS WAY.\n        # MAYBE SOMETHING TO IMPROVE ON IN THE FUTURE.\n\n        # CREATE ARRAYS FOR LAUNCH POINTS IN THE PLASMA\n        r0 = np.broadcast_arrays(np.ones(polpts)[:, None, None, None],\n                                 np.ones(inp.numcos)[:, None, None],\n                                 core.rho)[-1]\n\n        B0 = np.broadcast_arrays(np.ones(polpts)[:, None, None, None],\n                                 np.ones(inp.numcos)[:, None, None],\n                                 core.B.tot.val)[-1]\n\n        f0 = np.broadcast_arrays(np.ones(polpts)[:, None, None, None],\n                                 np.ones(inp.numcos)[:, None, None],\n                                 core.f_phi)[-1]\n\n        psi0 = np.broadcast_arrays(np.ones(polpts)[:, None, None, None],\n                                   np.ones(inp.numcos)[:, None, None],\n                                   core.psi.psi)[-1]\n\n        phi0 = np.broadcast_arrays(np.ones(polpts)[:, None, None, None],\n                                   np.ones(inp.numcos)[:, None, None],\n                                   core.E_pot.val)[-1]  # * 1E3  # now in volts\n\n        zeta0 = np.broadcast_arrays(np.ones(polpts)[:, None, None, None],\n                                    self.coslist[:, None, None],\n                                    np.ones(core.R.shape))[1]\n\n        # CREATE ARRAYS FOR DESTINATION POINTS ALONG THE SEPERATRIX\n        R1 = np.broadcast_arrays(np.ones(polpts)[:, None, None, None],\n                                 np.ones(inp.numcos)[:, None, None],\n                                 np.ones(radpts)[:, None],\n                                 np.ones(polpts)[:],\n                                 core.R[-1][:, None, None, None])[-1]\n\n        f1 = np.broadcast_arrays(np.ones(polpts)[:, None, None, None],\n                                 np.ones(inp.numcos)[:, None, None],\n                                 np.ones(radpts)[:, None], np.ones(polpts)[:],\n                                 core.f_phi[-1][:, None, None, None])[-1]\n\n        B1 = np.broadcast_arrays(np.ones(polpts)[:, None, None, None],\n                                 np.ones(inp.numcos)[:, None, None],\n                                 np.ones(radpts)[:, None],\n                                 np.ones(polpts)[:],\n                                 core.B.tot.val[-1][:, None, None, None])[-1]\n\n        psi1 = np.broadcast_arrays(np.ones(polpts)[:, None, None, None],\n                                   np.ones(inp.numcos)[:, None, None],\n                                   np.ones(radpts)[:, None],\n                                   np.ones(polpts)[:],\n                                   core.psi.psi[-1][:, None, None, None])[-1]\n\n        phi1 = np.broadcast_arrays(np.ones(polpts)[:, None, None, None],\n                                   np.ones(inp.numcos)[:, None, None],\n                                   np.ones(radpts)[:, None],\n                                   np.ones(polpts)[:],\n                                   core.E_pot.val[-1][:, None, None, None])[-1]  # * 1E3  # now in volts\n\n        Tprofile = namedtuple('Tprofile', 'i C')(\n            core.T.i.kev.val.T[0],\n            core.T.C.kev.val.T[0]\n        )\n\n        # iol_params = {}\n        # iol_params['r0'] = r0\n        # iol_params['B0'] = B0\n        # iol_params['f0'] = f0\n        # iol_params['psi0'] = psi0\n        # iol_params['phi0'] = phi0\n        # iol_params['zeta0'] = zeta0\n        # iol_params['R1'] = R1\n        # iol_params['f1'] = f1\n        # iol_params['B1'] = B1\n        # iol_params['psi1'] = psi1\n        # iol_params['phi1'] = phi1\n        # iol_params['Tprofile'] = Tprofile\n\n        # convert iol_params to namedtuple so individual parameters can be accessed as normal attributes\n        self.iol_p = namedtuple('iol_p', 'r0 B0 f0 psi0 phi0 zeta0 R1 f1 B1 psi1 phi1')(\n            r0,\n            B0,\n            f0,\n            psi0,\n            phi0,\n            zeta0,\n            R1,\n            f1,\n            B1,\n            psi1,\n            phi1\n        )\n\n        # Calculate IOL for thermal deuterium\n        forb_d_therm, morb_d_therm, eorb_d_therm = calc_iol_maxwellian(1,\n                                                                       m_d,\n                                                                       self.iol_p,\n                                                                       core.thetapts,\n                                                                       Tprofile.i,\n                                                                       self.coslist,\n                                                                       numcos)\n        self.forb_d_therm = inp.R_loss * forb_d_therm\n        self.morb_d_therm = inp.R_loss * morb_d_therm\n        self.eorb_d_therm = inp.R_loss * eorb_d_therm\n        self.forb_d_therm_1D = self.forb_d_therm[:, 0]\n        self.morb_d_therm_1D = self.morb_d_therm[:, 0]\n        self.eorb_d_therm_1D = self.eorb_d_therm[:, 0]\n\n        # Calculate IOL for thermal tritium\n        forb_t_therm, morb_t_therm, eorb_t_therm = calc_iol_maxwellian(1,\n                                                                       m_t,\n                                                                       self.iol_p,\n                                                                       core.thetapts,\n                                                                       Tprofile.i,\n                                                                       self.coslist,\n                                                                       numcos)\n        self.forb_t_therm = inp.R_loss * forb_t_therm\n        self.morb_t_therm = inp.R_loss * morb_t_therm\n        self.eorb_t_therm = inp.R_loss * eorb_t_therm\n        self.forb_t_therm_1D = self.forb_t_therm[:, 0]\n        self.morb_t_therm_1D = self.morb_t_therm[:, 0]\n        self.eorb_t_therm_1D = self.eorb_t_therm[:, 0]\n\n        # Calculate IOL for thermal carbon\n        forb_c_therm, morb_c_therm, eorb_c_therm = calc_iol_maxwellian(6,\n                                                                       m_c,\n                                                                       self.iol_p,\n                                                                       core.thetapts,\n                                                                       Tprofile.C,\n                                                                       self.coslist,\n                                                                       numcos)\n        self.forb_c_therm = inp.R_loss * forb_c_therm\n        self.morb_c_therm = inp.R_loss * morb_c_therm\n        self.eorb_c_therm = inp.R_loss * eorb_c_therm\n        self.forb_c_therm_1D = self.forb_c_therm[:, 0]\n        self.morb_c_therm_1D = self.morb_c_therm[:, 0]\n        self.eorb_c_therm_1D = self.eorb_c_therm[:, 0]\n\n        # Calculate IOL for thermal alphas\n        forb_a_therm, morb_a_therm, eorb_a_therm = calc_iol_maxwellian(2,\n                                                                       m_a,\n                                                                       self.iol_p,\n                                                                       core.thetapts,\n                                                                       Tprofile.i,\n                                                                       self.coslist,\n                                                                       numcos)\n        self.forb_a_therm = inp.R_loss * forb_a_therm\n        self.morb_a_therm = inp.R_loss * morb_a_therm\n        self.eorb_a_therm = inp.R_loss * eorb_a_therm\n        self.forb_a_therm_1D = self.forb_a_therm[:, 0]\n        self.morb_a_therm_1D = self.morb_a_therm[:, 0]\n        self.eorb_a_therm_1D = self.eorb_a_therm[:, 0]\n\n        # Calculate IOL for fast, monoenergetic alphas\n        v_alpha = sqrt(2 * 3.5E6 * 1.6021E-19 / m_a)\n        forb_a_fast, morb_a_fast, eorb_a_fast = calc_iol_mono_en(2,\n                                                                 m_a,\n                                                                 self.iol_p,\n                                                                 core.thetapts,\n                                                                 v_alpha,\n                                                                 self.coslist,\n                                                                 numcos)\n\n        # currently applying R_loss to fast alphas as well as thermal, although I'm skeptical of this. -MH\n        self.forb_a_fast = inp.R_loss * forb_a_fast\n        self.morb_a_fast = inp.R_loss * morb_a_fast\n        self.eorb_a_fast = inp.R_loss * eorb_a_fast\n        self.forb_a_fast_1D = self.forb_a_fast[:, 0]\n        self.morb_a_fast_1D = self.morb_a_fast[:, 0]\n        self.eorb_a_fast_1D = self.eorb_a_fast[:, 0]\n\n        # Calculate IOL for neutral deuterium beams\n        v_beam = sqrt(2 * 80.0E3 * 1.6021E-19 / m_d)\n        zeta_beam = -0.96\n        forb_d_nbi, morb_d_nbi, eorb_d_nbi = self.calc_iol_beams(1,\n                                                                 m_d,\n                                                                 self.iol_p,\n                                                                 core.thetapts,\n                                                                 v_beam,\n                                                                 zeta_beam,\n                                                                 self.coslist)\n        # currently applying R_loss to fast alphas as well as thermal, although I'm skeptical of this. -MH\n        self.forb_d_nbi = inp.R_loss * forb_d_nbi\n        self.morb_d_nbi = inp.R_loss * morb_d_nbi\n        self.eorb_d_nbi = inp.R_loss * eorb_d_nbi\n        self.forb_d_nbi_1D = self.forb_d_nbi[:, 0]\n        self.morb_d_nbi_1D = self.morb_d_nbi[:, 0]\n        self.eorb_d_nbi_1D = self.eorb_d_nbi[:, 0]\n\n    def plot_F_i(self, edge=True):\n        \"\"\"\n        Plots the 1D GT3.IOL differential ion number loss fraction\n        \"\"\"\n        fig = self._plot_base(self.forb_d_therm_1D, yLabel=r'$F(\\rho)$',\n                              title=\"GT3.IOL differential ion number loss fraction\", edge=edge, color='blue')\n        return fig\n\n    def plot_M_i(self, edge=True):\n        \"\"\"\n        Plots the 1D GT3.IOL differential ion momentum loss fraction\n        \"\"\"\n        fig = self._plot_base(self.morb_d_therm_1D, yLabel=r'$M(\\rho)$',\n                              title=\"GT3.IOL differential ion momentum loss fraction\", edge=edge, color='green')\n        return fig\n\n    def plot_E_i(self, edge=True):\n        \"\"\"\n        Plots the 1D GT3.IOL differential ion energy loss fraction\n        \"\"\"\n        fig = self._plot_base(self.eorb_d_therm_1D, yLabel=r'$E(\\rho)$',\n                              title=\"GT3.IOL differential ion energy loss fraction\", edge=edge, color='red')\n        return fig\n\n    def plot_all_i(self):\n        plot = plt.figure()\n        fig1 = plot.add_subplot(111)\n        fig1.set_xlabel(r'$\\rho$', fontsize=20)\n        fig1.set_ylabel(r'$\\frac{\\partial F}{\\partial r}$', fontsize=25)\n        fig1.set_title('Ion number loss fraction')\n        fig1.scatter(self.rho, self.forb_d_therm_1D, marker='o', color='blue')\n\n        fig2 = plot.add_subplot(121)\n        fig2.set_xlabel(r'$\\rho$', fontsize=20)\n        fig2.set_ylabel(r'$\\frac{\\partial E}{\\partial r}$', fontsize=25)\n        fig2.set_title('Ion energy loss fraction')\n        fig2.scatter(self.rho, self.eorb_d_therm_1D, marker='o', color='red')\n\n        fig3 = plot.add_subplot(131)\n        fig3.set_xlabel(r'$\\rho$', fontsize=20)\n        fig3.set_ylabel(r'$\\frac{\\partial M}{\\partial r}$', fontsize=25)\n        fig3.set_title('Ion momentum loss fraction')\n        fig3.scatter(self.rho, self.morb_d_therm_1D, marker='o', color='green')\n\n        return plot\n\n    def plot_F_C(self, edge=True):\n        \"\"\"\n        Plots the 1D GT3.IOL differential carbon number loss fraction\n        \"\"\"\n        fig = self._plot_base(self.forb_c_therm_1D, yLabel=r'$\\frac{\\partial F}{\\partial r}$',\n                              title=\"GT3.IOL differential carbon number loss fraction\", edge=edge, color='blue')\n        return fig\n\n    def plot_M_C(self, edge=True):\n        \"\"\"\n        Plots the 1D GT3.IOL differential carbon momentum loss fraction\n        \"\"\"\n        fig = self._plot_base(self.morb_c_therm_1D, yLabel=r'$\\frac{\\partial M}{\\partial r}$',\n                              title=\"GT3.IOL differential carbon momentum loss fraction\", edge=edge, color='green')\n        return fig\n\n    def plot_E_C(self, edge=True):\n        \"\"\"\n        Plots the 1D GT3.IOL differential carbon energy loss fraction\n        \"\"\"\n        fig = self._plot_base(self.eorb_c_therm_1D, yLabel=r'$\\frac{\\partial E}{\\partial r}$',\n                              title=\"GT3.IOL differential carbon energy loss fraction\", edge=edge, color='green')\n        return fig\n\n\n    def plot_all_C(self):\n        plot = plt.figure()\n        fig1 = plot.add_subplot(111)\n        fig1.set_xlabel(r'$\\rho$', fontsize=20)\n        fig1.set_ylabel(r'$\\frac{\\partial F}{\\partial r}$', fontsize=25)\n        fig1.set_title('Carbon number loss fraction')\n        fig1.scatter(self.rho, self.forb_c_therm_1D, marker='o', color='blue')\n\n        fig2 = plot.add_subplot(121)\n        fig2.set_xlabel(r'$\\rho$', fontsize=20)\n        fig2.set_ylabel(r'$\\frac{\\partial E}{\\partial r}$', fontsize=25)\n        fig2.set_title('Carbon energy loss fraction')\n        fig2.scatter(self.rho, self.eorb_c_therm_1D, marker='o', color='red')\n\n        fig3 = plot.add_subplot(131)\n        fig3.set_xlabel(r'$\\rho$', fontsize=20)\n        fig3.set_ylabel(r'$\\frac{\\partial M}{\\partial r}$', fontsize=25)\n        fig3.set_title('Carbon momentum loss fraction')\n        fig3.scatter(self.rho, self.morb_c_therm_1D, marker='o', color='green')\n\n        return plot\n\n    def plot_F_i_fast(self, edge=True):\n        \"\"\"\n        Plots the 1D GT3.IOL differential fast ion number loss fraction\n        \"\"\"\n        fig = self._plot_base(self.forb_d_nbi_1D, yLabel=r'$\\frac{\\partial F}{\\partial r}$',\n                              title=\"GT3.IOL differential fast ion number loss fraction\", edge=edge, color='blue')\n        return fig\n\n    def plot_M_i_fast(self,edge=True):\n        \"\"\"\n        Plots the 1D GT3.IOL differential fast ion momentum loss fraction\n        \"\"\"\n        fig = self._plot_base(self.morb_d_nbi_1D, yLabel=r'$\\frac{\\partial M}{\\partial r}$',\n                              title=\"GT3.IOL differential fast ion momentum loss fraction\", edge=edge, color='green')\n        return fig\n\n    def plot_E_i_fast(self, edge=True):\n        \"\"\"\n        Plots the 1D GT3.IOL differential fast ion energy loss fraction\n        \"\"\"\n        fig = self._plot_base(self.eorb_d_nbi_1D, yLabel=r'$\\frac{\\partial E}{\\partial r}$',\n                              title=\"GT3.IOL differential fast ion energy loss fraction\", edge=edge, color='red')\n        return fig\n\n\n    def plot_all_i_fast(self):\n        plot = plt.figure()\n        fig1 = plot.add_subplot(111)\n        fig1.set_xlabel(r'$\\rho$', fontsize=20)\n        fig1.set_ylabel(r'$\\frac{\\partial F}{\\partial r}$', fontsize=25)\n        fig1.set_title('Fast ion number loss fraction')\n        fig1.scatter(self.rho, self.forb_d_nbi_1D, marker='o', color='blue')\n\n        fig2 = plot.add_subplot(121)\n        fig2.set_xlabel(r'$\\rho$', fontsize=20)\n        fig2.set_ylabel(r'$\\frac{\\partial E}{\\partial r}$', fontsize=25)\n        fig2.set_title('Fast ion energy loss fraction')\n        fig2.scatter(self.rho, self.eorb_d_nbi_1D, marker='o', color='red')\n\n        fig3 = plot.add_subplot(131)\n        fig3.set_xlabel(r'$\\rho$', fontsize=20)\n        fig3.set_ylabel(r'$\\frac{\\partial M}{\\partial r}$', fontsize=25)\n        fig3.set_title('Fast ion momentum loss fraction')\n        fig3.scatter(self.rho, self.morb_d_nbi_1D, marker='o', color='green')\n\n        return plot", "meta": {"hexsha": "bfb53a6781bcaffa1d8b0e8214269fd65fe9aca0", "size": 17474, "ext": "py", "lang": "Python", "max_stars_repo_path": "GT3/IOL/iol.py", "max_stars_repo_name": "gt-frc/gt3", "max_stars_repo_head_hexsha": "1b27d6ca68b182413be23efeb0282f4a9075212f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-10-10T00:11:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-08T20:15:16.000Z", "max_issues_repo_path": "GT3/IOL/iol.py", "max_issues_repo_name": "gt-frc/gt3", "max_issues_repo_head_hexsha": "1b27d6ca68b182413be23efeb0282f4a9075212f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2018-05-02T22:16:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:53:38.000Z", "max_forks_repo_path": "GT3/IOL/iol.py", "max_forks_repo_name": "gt-frc/gt3", "max_forks_repo_head_hexsha": "1b27d6ca68b182413be23efeb0282f4a9075212f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-06-06T16:07:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-03T11:46:23.000Z", "avg_line_length": 46.5973333333, "max_line_length": 117, "alphanum_fraction": 0.4985120751, "include": true, "reason": "import numpy", "num_tokens": 4234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.2782567877172032, "lm_q1q2_score": 0.19907158629917762}}
{"text": "import time\nimport torch\nimport math\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport utils\nimport numpy as np\n\ndef build_targets(pred_boxes, target, anchors, num_anchors, num_classes, nH, nW, noobject_scale, object_scale, sil_thresh, seen):\n    nB = target.size(0)\n    nA = num_anchors\n    nC = num_classes\n    anchor_step = len(anchors)//num_anchors\n    conf_mask  = torch.ones(nB, nA, nH, nW) * noobject_scale\n    conf_mask = conf_mask.view(nB, -1)\n    coord_mask = torch.zeros(nB, nA, nH, nW)\n    cls_mask   = torch.zeros(nB, nA, nH, nW)\n    tx         = torch.zeros(nB, nA, nH, nW)\n    ty         = torch.zeros(nB, nA, nH, nW)\n    tw         = torch.zeros(nB, nA, nH, nW)\n    th         = torch.zeros(nB, nA, nH, nW)\n    tconf      = torch.zeros(nB, nA, nH, nW)\n    tcls       = torch.zeros(nB, nA, nH, nW)\n\n    nAnchors = nA*nH*nW\n    nPixels  = nH*nW\n    for b in range(nB):\n        cur_pred_boxes = pred_boxes[b*nAnchors:(b+1)*nAnchors].t()\n        cur_ious = torch.zeros(nAnchors)\n        for t in range(50):\n            if target[b][t*5+1] == 0:\n                break\n            gx = target[b][t*5+1]*nW\n            gy = target[b][t*5+2]*nH\n            gw = target[b][t*5+3]*nW\n            gh = target[b][t*5+4]*nH\n            cur_gt_boxes = torch.FloatTensor([gx,gy,gw,gh]).repeat(nAnchors,1).t()\n            cur_ious = torch.max(cur_ious, utils.bbox_ious(cur_pred_boxes, cur_gt_boxes, x1y1x2y2=False))\n        conf_mask[b][cur_ious>sil_thresh] = 0\n    if seen < 12800:\n       if anchor_step == 4:\n           tx = torch.FloatTensor(anchors).view(nA, anchor_step).index_select(1, torch.LongTensor([2])).view(1,nA,1,1).repeat(nB,1,nH,nW)\n           ty = torch.FloatTensor(anchors).view(num_anchors, anchor_step).index_select(1, torch.LongTensor([2])).view(1,nA,1,1).repeat(nB,1,nH,nW)\n       else:\n           tx.fill_(0.5)\n           ty.fill_(0.5)\n       tw.zero_()\n       th.zero_()\n       coord_mask.fill_(1)\n\n    conf_mask = conf_mask.view(nB, nA, nH, nW)\n\n    nGT = 0\n    nCorrect = 0\n    for b in range(nB):\n        for t in range(50):\n            if target[b][t*5+1] == 0:\n                break\n            nGT = nGT + 1\n            best_iou = 0.0\n            best_n = -1\n            min_dist = 10000\n            gx = target[b][t*5+1] * nW\n            gy = target[b][t*5+2] * nH\n            gi = int(gx)\n            gj = int(gy)\n            gw = target[b][t*5+3]*nW\n            gh = target[b][t*5+4]*nH\n            gt_box = [0, 0, gw, gh]\n            for n in range(nA):\n                aw = anchors[anchor_step*n]\n                ah = anchors[anchor_step*n+1]\n                anchor_box = [0, 0, aw, ah]\n                iou  = utils.bbox_iou(anchor_box, gt_box, x1y1x2y2=False)\n                if anchor_step == 4:\n                    ax = anchors[anchor_step*n+2]\n                    ay = anchors[anchor_step*n+3]\n                    dist = pow(((gi+ax) - gx), 2) + pow(((gj+ay) - gy), 2)\n                if iou > best_iou:\n                    best_iou = iou\n                    best_n = n\n                elif anchor_step==4 and iou == best_iou and dist < min_dist:\n                    best_iou = iou\n                    best_n = n\n                    min_dist = dist\n\n            gt_box = [gx.cuda(), gy.cuda(), gw.cuda(), gh.cuda()]\n            pred_box = pred_boxes[b*nAnchors+best_n*nPixels+gj*nW+gi].cuda()\n\n            coord_mask[b][best_n][gj][gi] = 1\n            cls_mask[b][best_n][gj][gi] = 1\n            conf_mask[b][best_n][gj][gi] = object_scale\n            tx[b][best_n][gj][gi] = target[b][t*5+1] * nW - gi\n            ty[b][best_n][gj][gi] = target[b][t*5+2] * nH - gj\n            tw[b][best_n][gj][gi] = math.log(gw/anchors[anchor_step*best_n])\n            th[b][best_n][gj][gi] = math.log(gh/anchors[anchor_step*best_n+1])\n            iou = utils.bbox_ious(gt_box, pred_box, x1y1x2y2=False) # best_iou\n            tconf[b][best_n][gj][gi] = iou\n            tcls[b][best_n][gj][gi] = target[b][t*5]\n            if iou > 0.5:\n                nCorrect = nCorrect + 1\n\n    return nGT, nCorrect, coord_mask, conf_mask, cls_mask, tx, ty, tw, th, tconf, tcls\n    \nclass YoloLayer(nn.Module):\n    def __init__(self, anchor_mask=[], num_classes=0, anchors=[], num_anchors=1):\n        super(YoloLayer, self).__init__()\n        self.anchor_mask = anchor_mask\n        self.num_classes = num_classes\n        self.anchors = anchors\n        self.num_anchors = num_anchors\n        self.anchor_step = len(anchors)/num_anchors\n        self.coord_scale = 1\n        self.noobject_scale = 1\n        self.object_scale = 5\n        self.class_scale = 1\n        self.thresh = 0.6\n        self.stride = 32\n        self.seen = 0\n\n    def forward(self, output, target=None):\n        if self.training:\n            #output : BxAs*(4+1+num_classes)*H*W\n            losses = []\n#            for o_ind, output in enumerate(outputs):\n            t0 = time.time()\n            nB = output.size(0)\n#            nA = self.num_anchors//3\n            #nA = self.num_anchors\n            nA = len(self.anchor_mask)\n            nC = self.num_classes\n            nH = output.size(2)\n            nW = output.size(3)\n            anchors = []\n            for am in self.anchor_mask:\n                anchors.append(self.anchors[2*am])\n                anchors.append(self.anchors[2*am + 1])\n\n            output   = output.view(nB, nA, (5+nC), nH, nW)\n            x    = output.index_select(2, Variable(torch.cuda.LongTensor([0]))).view(nB, nA, nH, nW)\n            x    = F.sigmoid(x)\n            y    = output.index_select(2, Variable(torch.cuda.LongTensor([1]))).view(nB, nA, nH, nW)\n            y    = F.sigmoid(y)\n            width= output.index_select(2, Variable(torch.cuda.LongTensor([2]))).view(nB, nA, nH, nW) / 416\n            height= output.index_select(2, Variable(torch.cuda.LongTensor([3]))).view(nB, nA, nH, nW) / 416\n            conf = output.index_select(2, Variable(torch.cuda.LongTensor([4]))).view(nB, nA, nH, nW)\n            conf = F.sigmoid(conf)\n            cls  = output.index_select(2, Variable(torch.linspace(5,5+nC-1,nC)).long().cuda())\n            cls  = cls.view(nB*nA, nC, nH*nW).transpose(1,2).contiguous().view(nB*nA*nH*nW, nC)\n            t1 = time.time()\n\n            pred_boxes = torch.cuda.FloatTensor(4, nB*nA*nH*nW)\n            grid_x = torch.linspace(0, nW-1, nW).repeat(nH,1).repeat(nB*nA, 1, 1).view(nB*nA*nH*nW).cuda()\n            grid_y = torch.linspace(0, nH-1, nH).repeat(nW,1).t().repeat(nB*nA, 1, 1).view(nB*nA*nH*nW).cuda()\n#            anchor_w = torch.Tensor(self.anchors[o_ind*nA*2:(o_ind+1)*nA*2]).view(nA, self.anchor_step).index_select(1, torch.LongTensor([0])).cuda()\n#            anchor_h = torch.Tensor(self.anchors[o_ind*nA*2:(o_ind+1)*nA*2]).view(nA, self.anchor_step).index_select(1, torch.LongTensor([1])).cuda()\n#            anchor_w = torch.Tensor(self.anchors).view(nA, self.anchor_step).index_select(1, torch.LongTensor([0])).cuda()\n#            anchor_h = torch.Tensor(self.anchors).view(nA, self.anchor_step).index_select(1, torch.LongTensor([1])).cuda()\n            anchor_w = torch.Tensor(anchors).view(nA, self.anchor_step).index_select(1, torch.LongTensor([0])).cuda()\n            anchor_h = torch.Tensor(anchors).view(nA, self.anchor_step).index_select(1, torch.LongTensor([1])).cuda()\n\n            anchor_w = anchor_w.repeat(nB, 1).repeat(1, 1, nH*nW).view(nB*nA*nH*nW)\n            anchor_h = anchor_h.repeat(nB, 1).repeat(1, 1, nH*nW).view(nB*nA*nH*nW)\n            pred_boxes[0] = x.view(-1) + grid_x\n            pred_boxes[1] = y.view(-1) + grid_y\n            pred_boxes[2] = torch.exp(width).view(-1) * anchor_w\n            pred_boxes[3] = torch.exp(height).view(-1) * anchor_h\n            pred_boxes = utils.convert2cpu(pred_boxes.transpose(0,1).contiguous().view(-1,4))\n            t2 = time.time()\n\n            nGT, nCorrect, coord_mask, conf_mask, cls_mask,\\\n            tx, ty, tw, th, tconf, tcls = \\\n            build_targets(pred_boxes, target, anchors, # self.anchors\n                          nA, nC, nH, nW,\n                          self.noobject_scale, self.object_scale,\n                          self.thresh, self.seen)\n            cls_mask = (cls_mask == 1)\n            nProposals = int((conf > 0.25).sum())\n\n            tx    = Variable(tx.cuda())\n            ty    = Variable(ty.cuda())\n            tw    = Variable(tw.cuda())\n            th    = Variable(th.cuda())\n            tconf = Variable(tconf.cuda())\n            tcls  = Variable(tcls[cls_mask].long().cuda())\n\n            coord_mask = Variable(coord_mask.cuda())\n            conf_mask  = Variable(conf_mask.cuda().sqrt())\n            cls_mask   = Variable(cls_mask.view(-1, 1).repeat(1,nC).cuda())\n            cls        = cls[cls_mask].view(-1, nC)\n\n            t3 = time.time()\n\n            loss_x = self.coord_scale * nn.MSELoss(size_average=True)(x*coord_mask, tx*coord_mask)/2.0\n            loss_y = self.coord_scale * nn.MSELoss(size_average=True)(y*coord_mask, ty*coord_mask)/2.0\n            loss_w = self.coord_scale * nn.MSELoss(size_average=True)(width*coord_mask, tw*coord_mask)/2.0\n            loss_h = self.coord_scale * nn.MSELoss(size_average=True)(height*coord_mask, th*coord_mask)/2.0\n            loss_conf = nn.MSELoss(size_average=True)(conf*conf_mask, tconf*conf_mask)/2.0\n            loss_cls = self.class_scale * nn.CrossEntropyLoss(size_average=True)(cls, tcls)\n            loss = loss_x + loss_y + loss_w + loss_h + loss_conf + loss_cls\n            t4 = time.time()\n            if False:\n                print('-----------------------------------')\n                print('        activation : %f' % (t1 - t0))\n                print(' create pred_boxes : %f' % (t2 - t1))\n                print('     build targets : %f' % (t3 - t2))\n                print('       create loss : %f' % (t4 - t3))\n                print('             total : %f' % (t4 - t0))\n            print('%d: nGT %d, recall %d, proposals %d, loss: x %f, y %f, w %f, h %f, conf %f, cls %f, total %f' % (self.seen, nGT, nCorrect, nProposals, loss_x.item(), loss_y.item(), loss_w.item(), loss_h.item(), loss_conf.item(), loss_cls.item(), loss.item()))\n            return loss\n#            losses.append(loss)\n#            return sum(losses).cuda()\n        else:\n            masked_anchors = []\n            for m in self.anchor_mask:\n                masked_anchors += self.anchors[m*self.anchor_step:(m+1)*self.anchor_step]\n            masked_anchors = [anchor/self.stride for anchor in masked_anchors]\n            boxes = utils.get_region_boxes(output.data, self.thresh, self.num_classes, masked_anchors, len(self.anchor_mask))\n            return boxes\n\n\nclass YoloLayer2(nn.Module):\n    def __init__(self, num_classes, anchors, masked_anchors, max_boxes,\n                 net_width, net_height):\n        super(YoloLayer2, self).__init__()\n        \n        self.num_classes = num_classes\n        self.bbox_attribs = 5 + num_classes\n        self.net_width = net_width\n        self.net_height = net_height\n        self.ignore_thresh = 0.5\n        # anchors and masked anchors\n        self.num_anchors = int(len(anchors)/2)\n        self.anchors = anchors\n\n        self.masked_anchor_inds = masked_anchors\n        masked_anchors = []\n        for i in self.masked_anchor_inds:\n            masked_anchors.append(self.anchors[2*i])\n            masked_anchors.append(self.anchors[2*i+1])\n        self.masked_anchors = masked_anchors\n        self.mask_size = int(len(masked_anchors)/2)\n        \n        self.max_boxes = max_boxes\n        #self.truths = max_boxes * (4 + 1) probably dont need it\n        #self.all_losses = self.batch_size * self.lwidth * self.lheight * self.lfilters # maximum number of losses to pay attention to, for a detection layer\n        self.cls_loss = nn.BCELoss(size_average=False, reduce=False)\n        self.l1_loss = nn.L1Loss(size_average=False, reduce=False)\n        \n        \n    \n    def forward(self, input, targets=None):\n        # layer sizes\n        batch_size = input.size(0)\n        lwidth = input.size(3)\n        lheight = input.size(2)\n        lfilters = input.size(1)\n        \n        # reshape predictions to batch * 3 * 25 (for voc) * grid_x * grid_y\n        prediction = input.view(batch_size, self.mask_size, self.bbox_attribs,\n                                lheight, lwidth)\n        # permute to have information on the last dimension\n        prediction = prediction.permute(0,1,3,4,2).contiguous()\n        \n        x = torch.sigmoid(prediction[...,0])\n        y = torch.sigmoid(prediction[...,1])\n        width = prediction[...,2]\n        height = prediction[...,3]\n        conf = torch.sigmoid(prediction[..., 4])\n        pred_cls = torch.sigmoid(prediction[..., 5:])\n        \n        if targets is not None:\n            yolo_boxes = self.get_yolo_boxes(x, y, width, height, self.masked_anchors)\n            targets = targets.view(batch_size, -1, 5)                        \n \n            loss_objectness = torch.zeros(batch_size, self.mask_size, lheight, lwidth).cuda()\n            for b in range(batch_size):\n                preds = yolo_boxes[b]\n                best_ious = torch.zeros(batch_size, self.mask_size, lheight, lwidth).cuda()\n                for t in targets[b]:\n                    if t.sum() == 0:\n                        continue\n                    ious = utils.bbox_ious(preds.permute(3,0,1,2), t[1:], False)\n                    best_ious = torch.max(best_ious, ious)\n                loss_objectness[b] = -conf[b] # we want loss to be 1 when a box is not with 100% confidence and 0 \n            \n            loss_x = torch.zeros(1).cuda()\n            loss_y = torch.zeros(1).cuda()\n            loss_width = torch.zeros(1).cuda()\n            loss_height = torch.zeros(1).cuda()\n            loss_cls = torch.zeros(1).cuda()\n            \n            num_truths = 0\n            for b in range(batch_size):\n                for t in targets[b]:\n                    if t.sum() == 0:\n                        continue\n                    num_truths += 1\n                    \n                    gt_i = int(t[1] * lwidth)\n                    gt_j = int(t[2] * lheight)\n                    \n                    truth = torch.tensor([0, 0, t[3], t[4]]).cuda()\n                    best_anchor = -1\n                    best_iou = 0\n                    for anc in range(len(self.anchors)//2):\n                        anchor_box = torch.tensor([0,0,\n                                                   self.anchors[2*anc]/self.net_width,\n                                                   self.anchors[2*anc+1]/self.net_height]).cuda()\n                        iou = utils.bbox_ious(truth, anchor_box, False)\n                        if iou > best_iou:\n                            best_iou = iou\n                            best_anchor = anc\n                    if best_anchor in self.masked_anchor_inds:\n                        best_anchor_norm = best_anchor % self.mask_size\n                        target_pred = yolo_boxes[b][best_anchor_norm][gt_j][gt_i]\n                        iou = utils.bbox_ious(t[1:], target_pred, False)\n                        \n                        tx = t[1]*lwidth - gt_i\n                        ty = t[2]*lheight - gt_j\n                        tw = torch.log(t[3]*self.net_width/self.anchors[2*best_anchor_norm])\n                        th = torch.log(t[4]*self.net_height/self.anchors[2*best_anchor_norm+1])\n                        scale = 2 * t[2] * t[3]\n                        \n#                        loss_x += scale * (tx - x[b][best_anchor_norm][gt_j][gt_i])\n#                        loss_y += scale * (ty - y[b][best_anchor_norm][gt_j][gt_i])\n#                        loss_width += scale * (tw - width[b][best_anchor_norm][gt_j][gt_i])\n#                        loss_height += scale * (th - height[b][best_anchor_norm][gt_j][gt_i])\n                        loss_x += scale * self.l1_loss(x[b][best_anchor_norm][gt_j][gt_i], tx)\n                        loss_y += scale * self.l1_loss(y[b][best_anchor_norm][gt_j][gt_i], ty)\n                        loss_width += scale * self.l1_loss(width[b][best_anchor_norm][gt_j][gt_i], tw)\n                        loss_height += scale * self.l1_loss(height[b][best_anchor_norm][gt_j][gt_i], th)\n                        \n                        loss_objectness[b][best_anchor_norm][gt_j][gt_i] = 1 - conf[b][best_anchor_norm][gt_j][gt_i]\n                        \n                        one_hot = torch.zeros(self.num_classes).cuda()\n                        one_hot[int(t[0])] = 1.\n                        for c in range(self.num_classes):\n                            loss_cls += self.cls_loss(pred_cls[b][best_anchor_norm][gt_j][gt_i][c], one_hot[c])\n                 \n            print(\"Loss x {}, loss y {}, loss w {}, loss h {}, loss_cls {}\".format(loss_x/num_truths, loss_y/num_truths, loss_width/num_truths, loss_height/num_truths, loss_cls))\n            return torch.sum(-loss_objectness) + loss_x/num_truths + loss_y/num_truths + loss_width/num_truths + loss_height/num_truths + loss_cls\n        else:\n            yolo_boxes = self.get_yolo_boxes(x, y, width, height, self.masked_anchors)\n            \n            output = torch.cat(\n                    (\n                            yolo_boxes.view(batch_size, -1, 4),\n                            conf.view(batch_size, -1, 1),\n                            pred_cls.view(batch_size, -1, self.num_classes),\n                    ),\n                    -1,\n                    )\n            return output\n            \n#            FloatTensor = torch.cuda.FloatTensor if x.is_cuda else torch.FloatTensor\n#            LongTensor = torch.cuda.LongTensor if x.is_cuda else torch.LongTensor\n#            \n#            stride_w = self.net_width/lwidth\n#            stride_h = self.net_height/lheight\n#            \n#            # Calculate offsets for each grid\n#            grid_x = torch.linspace(0, lwidth-1, lwidth).repeat(lwidth, 1).repeat(\n#                        batch_size * self.mask_size, 1, 1).view(x.shape).type(FloatTensor)\n#            grid_y = torch.linspace(0, lheight-1, lheight).repeat(lheight, 1).t().repeat(\n#                        batch_size * self.mask_size, 1, 1).view(y.shape).type(FloatTensor)\n#\n#            scaled_anchors = FloatTensor([(a_w / stride_w, a_h / stride_h) for a_w, a_h in np.array(self.masked_anchors).reshape(-1,2)])\n#\n#            # Calculate anchor w, h\n#            anchor_w = FloatTensor(scaled_anchors).index_select(1, LongTensor([0]))\n#            anchor_h = FloatTensor(scaled_anchors).index_select(1, LongTensor([1]))\n#            anchor_w = anchor_w.repeat(batch_size, 1).repeat(1, 1, lheight * lwidth).view(width.shape)\n#            anchor_h = anchor_h.repeat(batch_size, 1).repeat(1, 1, lheight * lwidth).view(height.shape)\n#            # Add offset and scale with anchors\n#            pred_boxes = FloatTensor(prediction[..., :4].shape)\n#            pred_boxes[..., 0] = x.data + grid_x\n#            pred_boxes[..., 1] = y.data + grid_y\n#            pred_boxes[..., 2] = torch.exp(width.data) * anchor_w\n#            pred_boxes[..., 3] = torch.exp(height.data) * anchor_h\n#            # Results\n#            _scale = torch.Tensor([stride_w, stride_h] * 2).type(FloatTensor)\n#            output = torch.cat((pred_boxes.view(batch_size, -1, 4) * _scale,\n#                                conf.view(batch_size, -1, 1), pred_cls.view(batch_size, -1, self.num_classes)), -1)\n#            \n#            return output.data\n            \n            \n            \n    def get_yolo_box(self, i, j, x, y, width, height, grid_width, grid_height, net_width, net_height, anchor_x, anchor_y):\n        yolo_x = (i + x)/grid_width\n        yolo_y = (j + y)/grid_height\n        yolo_width = torch.exp(width) * anchor_x / net_width\n        yolo_height = torch.exp(height) * anchor_y / net_height\n        return torch.tensor([yolo_x, yolo_y, yolo_width, yolo_height]).cuda()\n    \n    def get_yolo_boxes(self, x, y, width, height, masked_anchors):\n        assert x.shape == y.shape == width.shape == height.shape\n        net_width = self.net_width\n        net_height = self.net_height\n        \n        batches, num_anchors, grid_w, grid_h = x.shape\n        boxes = []\n        for b in range(batches):\n            for a in range(num_anchors):\n                for j in range(grid_h):\n                    for i in range(grid_w):\n                        new_x = (i + x[b][a][j][i])/grid_w\n                        new_y = (j + y[b][a][j][i])/grid_h\n                        new_width = torch.exp(width[b][a][j][i]) * masked_anchors[a] / net_width\n                        new_height = torch.exp(height[b][a][j][i]) * masked_anchors[a+1] / net_height\n                        boxes.append([new_x, new_y, new_width, new_height])\n        return torch.tensor(boxes).view(batches, num_anchors, grid_w, grid_h, 4).cuda()", "meta": {"hexsha": "9169891a6e60f8a6951319e6091b6c4ea23f0e63", "size": 20780, "ext": "py", "lang": "Python", "max_stars_repo_path": "yolo_layer.py", "max_stars_repo_name": "georkap/yolo3.pytorch", "max_stars_repo_head_hexsha": "c19b8677b7fe5024244f8ed56d6f41736c08b509", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "yolo_layer.py", "max_issues_repo_name": "georkap/yolo3.pytorch", "max_issues_repo_head_hexsha": "c19b8677b7fe5024244f8ed56d6f41736c08b509", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "yolo_layer.py", "max_forks_repo_name": "georkap/yolo3.pytorch", "max_forks_repo_head_hexsha": "c19b8677b7fe5024244f8ed56d6f41736c08b509", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-02T10:19:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-02T10:19:25.000Z", "avg_line_length": 50.193236715, "max_line_length": 262, "alphanum_fraction": 0.5362848893, "include": true, "reason": "import numpy", "num_tokens": 5607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.3106943704494217, "lm_q1q2_score": 0.19904195360680924}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nName: Open source Intelligent Dasymetric Mapping (IDM) script\n\nAuthor: Anam Khan\n\nDate: 5/1/19\n\nDescription: Intelligent Dasymetric Mapping (IDM) disaggregates population \ncounts enumerated by vector source units to the spatial resolution of a \ncategorical ancillary raster containing classes that are indicative of the \nspatial distribution of population within the source units. This script is \nan open source version of the EnviroAtlas IDM toolbox developed by \nTorrin Hultgren for ArcMap: https://www.epa.gov/enviroatlas/dasymetric-toolbox.\nThis version follows the publication by Mennis and Hultgren (2006) with the\nexception that class densities for unsampled ancillary classes are calculated\nusing census polygons where the population estimated for sampled/preset \nancillary classes did not exceed the census population.\n\"\"\"\n\nimport os, sys, json\nfrom osgeo import gdal, ogr\nimport numpy as np\nimport pandas as pd\nimport geopandas as gp\nimport argparse as ap\n\n\n#IDM function\ndef dasy_map (popFeat_path, popCountField, popKeyField, ancRaster_path, \n              out_dir,  popAreaMin = 1, sampleMin = 3, percent = 0.95, \n              uninhab_path = False, anc_nd = 0, pop_nd = 0):\n    '''\n    Prepare population density rasters given population and ancillary data \n    through intelligent dasymetric mapping. -popFeat_path: The path to the \\\n    census polygons with unique identifiers and a count of the population for \\\n    each polygon. - popCountField: The field in the population_features that \\\n    stores the polygon's populations.- popKeyField: The unique identifier \\\n    field for each polygon in population_features. -ancRaster_path: The path \\\n    to the land cover raster that is used for dasymetric population mapping. \\\n    -out_dir: The directory where all outputs will be saved. \\\n    -popAreaMin: The minimum number of raster cells in a source polygon for \\\n    it to be considered representative of a class (default = 1). -sampleMin: \\\n    The minimum number of source units to ensure a representative sample for \\\n    a land cover class (default = 3). -percent: The minimum percent of a \\\n    source polygon's area that an ancillary class must cover in order for the \\\n    source polygon to be considered representative of that class. Enter as a \\\n    decimal (default = 0.95). -uninhab_path: An optional shapefile containing \\\n    uninhabited areas. -anc_nd: The NoData value for the ancillary raster \\\n    (default = 0). -pop_nd: The NoData value for the population \\\n    raster (default = 0)   \n    '''\n    #Set config.json file in the script's directory to presetTable\n    if __name__ == '__main__':\n        presetTable = os.path.join(sys.path[0], \"config.json\")\n    else:\n        presetTable = os.path.join(sys.path[-1], \"config.json\")\n    \n    print ('population_features path: {0}'.format(popFeat_path))\n    print ('population_count_field: {0}'.format(popCountField))\n    print ('population_key_field: {0}'.format(popKeyField))\n    print ('ancillary_raster: {0}'.format(ancRaster_path))\n    print ('uninhabited_file: {0}'.format(uninhab_path))\n    print ('The minimum populated area of a representative unit is ' + str(popAreaMin))\n    print ('The minimum sample size is ' + str(sampleMin))\n    print ('The percent is ' + str(percent))\n    print ('The NoData value for the population raster is ' + str(pop_nd))\n    print ('The NoData value for the ancillary raster is ' + str(anc_nd))\n\n    #Set file names for outputs\n    popRaster = os.path.join(out_dir, \"PopRaster.tif\")\n    popWorkTable = os.path.join(out_dir, \"PopTable.csv\")\n    dasyRaster = os.path.join(out_dir, \"DasyRaster.tif\")\n    dasyWorkTable = os.path.join(out_dir, \"DasyWorkTable.csv\")\n    densityRaster = os.path.join(out_dir, \"DensityRaster.tif\")\n    \n    \"\"\"\n    Set driver for raster creation and read in census population features and \n    ancillary raster\n    \"\"\"\n    rast_driver = gdal.GetDriverByName('GTiff')\n    ancRaster = gdal.Open(ancRaster_path)\n    popFeatures = ogr.Open(popFeat_path)\n    popLayer = popFeatures.GetLayer()\n    \n    '''\n    Get GeoTransform from ancillary raster: rows, columns, \n    coordinates of upperleft corner for north up images, and projection.\n    '''\n    rows = ancRaster.RasterYSize\n    cols = ancRaster.RasterXSize\n    ulx = ancRaster.GetGeoTransform()[0]\n    uly = ancRaster.GetGeoTransform()[3]\n    anc_proj = ancRaster.GetProjection()\n    \n    \"\"\"\n    Create population raster from census population features using the \n    GeoTransform from the ancillary raster. Set pop_nd as the NoData value \n    for the population raster. \n    \"\"\"\n    print (\"Creating population raster...\")\n    popRast = rast_driver.Create(popRaster, cols, rows, 1, \n                                gdal.GDT_Float32, options=[\"COMPRESS=LZW\"])\n    popRast.SetGeoTransform((ulx, ancRaster.GetGeoTransform()[1], 0, \n                             uly, 0, ancRaster.GetGeoTransform()[5]))\n    popRast.SetProjection(anc_proj)\n    popRast.GetRasterBand(1).SetNoDataValue(pop_nd)\n    gdal.RasterizeLayer(popRast, [1], popLayer, \n                        options = [\"ATTRIBUTE=\" + popKeyField])\n    popRast = None\n    \n    \"\"\"\n    Burn the NoData value from the ancillary raster into the pixels that \n    overlap uninhabited areas\n    \"\"\"\n    if uninhab_path:\n        uninhab_ds = ogr.Open(uninhab_path)\n        uninhabLayer = uninhab_ds.GetLayer()\n        uninhab_anc = os.path.join(out_dir, \"uninhab_landcover.tif\")\n        uninhab_rast = rast_driver.CreateCopy(uninhab_anc, \n                                              gdal.Open(ancRaster_path), \n                                              options=['COMPRESS=LZW'])\n        gdal.RasterizeLayer(uninhab_rast, [1], uninhabLayer, \n                            burn_values = [anc_nd])\n        uninhab_rast = None\n        uninhab_ds = None\n        ancRaster = gdal.Open(uninhab_anc)\n    \n    print (\"Creating dasymetric units...\")\n    #Read ancillary raster and population raster as array\n    anc_arr = ancRaster.GetRasterBand(1).ReadAsArray().astype(np.uint64)\n    popRast = gdal.Open(popRaster)\n    pop_arr = popRast.GetRasterBand(1).ReadAsArray().astype(np.uint64)\n    \n    \"\"\"\n    Convert pixel values of ancillary raster that do not overlap with census \n    polygons to NoData.\n    \"\"\"\n    anc_arr[pop_arr == pop_nd] = anc_nd\n    \n    \"\"\"\n    Combine the ancillary raster and the population raster using Cantor's \n    pairing function to return a unique integer value for a pair(x,y)\n    \"\"\"\n    comb_arr = 0.5 * (pop_arr + anc_arr) * (pop_arr + anc_arr + 1) + anc_arr \n    \n    \"\"\"\n    Write the combine array to the dasymetric raster using the GeoTransform \n    from the ancillary raster\n    \"\"\"\n    dasyRast = rast_driver.Create(dasyRaster, cols, rows, 1, \n                            gdal.GDT_Float64, options=['COMPRESS=LZW'])\n    dasyRast.SetGeoTransform((ulx, ancRaster.GetGeoTransform()[1], 0, \n                              uly, 0, ancRaster.GetGeoTransform()[5]))\n    dasyRast.SetProjection(anc_proj)\n    dasyRast_b1 =dasyRast.GetRasterBand(1)\n    dasyRast_b1.WriteArray(comb_arr)\n    \n    \"\"\"\n    Set the NoData value for the dasymetric raster band by running the same \n    Cantor's pairing function on the NoData values from the population raster \n    and ancillary raster.\n    \"\"\"\n    dasy_nd = 0.5 * (pop_nd + anc_nd) * (pop_nd + anc_nd + 1) + anc_nd\n    dasyRast_b1.SetNoDataValue(dasy_nd)\n    dasyRast = None\n    \n    \"\"\"\n    Make the population DataFrame and the dasymetric DataFrame: collect the \n    unique values and counts, rearrange the array via transpose, convert to \n    DataFrame, and rename columns.\n    \"\"\"\n    dasy_ar_un = np.array(np.unique(comb_arr, return_counts = True)).T\n    dasy_df = pd.DataFrame(dasy_ar_un, columns = (\"Value\", \"Count\"))\n    \n    pop_ar_un = np.array(np.unique(pop_arr, return_counts = True)).T\n    pop_df = pd.DataFrame(pop_ar_un, columns = (\"Value\", \"Count\"))\n    \n    '''\n    Inverse of Cantor's pairing to get the polygon ID and ancillary class \n    associated with each dasy unit.\n    w = (sqrt(8 * dasy_df['Value'] + 1) - 1) // 2\n    '''\n    num = 8*dasy_df['Value'] + 1\n    dasy_df['w'] = (num.pow(1./2) - 1) // 2\n    dasy_df['t'] = (dasy_df['w'].pow(2) + dasy_df['w']) / 2\n    dasy_df['ancID'] = dasy_df['Value'] - dasy_df['t'] \n    dasy_df['polyID'] = dasy_df['w'] - dasy_df['ancID']\n\n    #get rid of unnecessary columns and NoData values\n    dasy_df = dasy_df[dasy_df['Value'] != dasy_nd].drop(columns = ['w','t'])\n    pop_df = pop_df[pop_df['Value'] != pop_nd]\n\n    #Set variables for DataFrame columns\n    popIDField = 'polyID'\n    ancCatName = 'ancID'\n    dasyAreaField = 'Count'\n\n    #Make lists to use later\n    #All ancillary categories in study area\n    inAncCatList = list(np.unique(dasy_df[ancCatName]).astype(int))\n    \n    '''            \n    This list will be populated with ancillary categories that are not sampled \n    and do not have preset class densities.\n    '''\n    unSampledList = []\n                \n    #Preset class densities from config.json file\n    presetData = json.load(open(presetTable))\n    \n    '''\n    Uninhabited classes: ancially classes where people do not live. Classes with\n    a preset class density of 0\n    '''\n    unInhabList = [int(presetCat) for presetCat,presetVal in presetData.items()\n                    if float(presetVal) == 0]\n    \n    #Ancillary classes where people can live\n    InhabList = [cat for cat in inAncCatList if cat not in unInhabList]\n    \n    '''\n    Join the census population counts to the dasymetric DataFrame and calculate \n    population density for the polygon. \n    '''\n    print (\"Calculating populated area...\")\n    #Read the source population shapefile with the population count field.\n    popfeat_df = gp.read_file(popFeat_path)\n\n    '''\n    Set the polygon ID field provided by the user as an index for the \n    population features DataFrame and the population DataFrame for joining and \n    transfering the population count field.\n    '''\n    popfeat_df.index = popfeat_df[popKeyField]\n    pop_df.index = pop_df[\"Value\"]\n    \n    '''\n    Join population counts from popfeat_df to the dasymetric DataFrame and the \n    population DataFrame. Rename the field to \"POP_COUNT\" in the dasymetric \n    DataFrame.\n    '''\n    dasy_df = dasy_df.join(popfeat_df[popCountField], \n                           on = popIDField).rename(\n                                   columns = {popCountField: \"POP_COUNT\"}\n                                   )\n    pop_df = pop_df.join(popfeat_df[popCountField])\n\n    '''\n    Group the dasymetric units that are associated with inhabitable classes by \n    the census polygon ID and take the sum of the dasymetric area in each \n    group. Rename the column as \"POP_AREA\".\n    POP_AREA = sum(pixels) for inhabitable classes\n    '''\n    popAreaSum = dasy_df[\n            dasy_df[ancCatName].isin(InhabList)\n            ].groupby(popIDField)[dasyAreaField].sum().rename(\"POP_AREA\")\n\n    '''\n    Transfer \"POP_AREA\" from popAreaSum to the dasymetric DataFrame and the \n    population DataFrame.\n    '''      \n    dasy_df[\"POP_AREA\"] = dasy_df.join(popAreaSum, on = popIDField)[\"POP_AREA\"]\n    pop_df = pop_df.join(popAreaSum).fillna(0)\n\n    '''\n    Calculate population density for census polygons where poulated area is \n    greater than 0.\n    '''\n    print (\"Calculating population density...\")           \n    pop_densMask = pop_df[\"POP_AREA\"] > 0\n    pop_df.loc[pop_densMask, \"POP_DENS\"] = pop_df.loc[\n            pop_densMask, popCountField] / pop_df.loc[pop_densMask, \"POP_AREA\"]\n    #replace NaN with 0\n    pop_df = pop_df.fillna(0)\n    \n    '''\n    Calculate representative population density for ancillary classes that have \n    enough representative samples in the study area.\n    '''\n    print (\"Selecting representative units...\")\n    #Create column for the ancillary class that a polygon is representative of \n    pop_df[\"REP_CAT\"] = 0\n\n    '''\n    For each inhabitable ancillary class, collect polygon IDs of census \n    polygons that meet the user-define criteria for being representative of an \n    ancillary class.\n    '''        \n    for inAncCat in InhabList:\n        repUnits_mask = (\n                dasy_df[\"POP_AREA\"] > float(popAreaMin)\n                ) & (\n                        dasy_df[ancCatName] == inAncCat\n                        )\n        repUnits = dasy_df.loc[\n                repUnits_mask, [\n                        dasyAreaField, popIDField, ancCatName, \"POP_AREA\"\n                        ]\n                ]\n        repUnits[\"PERCENT\"] = repUnits[dasyAreaField] / repUnits[\"POP_AREA\"]                \n        repUnits = list(\n                repUnits[repUnits[\"PERCENT\"] >= float(percent)][popIDField]\n                )\n                \n        if len(repUnits) >= float(sampleMin):\n            pop_df.loc[pop_df['Value'].isin(repUnits), \"REP_CAT\"] = inAncCat\n            print (\"Class \" \n                   + str(inAncCat) \n                   + \" was sufficiently sampled with \" \n                   + str(len(repUnits)) \n                   + \" representative source units.\")\n            \n            '''\n            #If ancillary category has no representative polygons and it does \n            not have a preset class density, then add it to the list of \n            unsampled classes.\n            '''\n        elif str(inAncCat) not in list(presetData):\n            unSampledList.append(int(inAncCat))\n            print (\"Class \" \n                   + str(inAncCat) \n                   + \" was not sufficiently sampled with only \" \n                   + str(len(repUnits)) \n                   + \" representative source units.\")\n            \n    #Calculate statistics and make sampling summary table\n    print (\n            \"Calculating representative population density for selected\" \\\n            \" classes...\"\n            )\n    \n    '''\n    Create a mask for rows in the dasymetric DataFrame where REP_CAT =! 0. \n    We only want to create summaries for these dasymetric rows because they are \n    associated with representative polygons.\n    '''\n    rep_mask = pop_df[\"REP_CAT\"] != 0\n\n    '''\n    Calculate sum of census population counts and sum of populated area for \n    each sampled ancillary class.\n    '''\n    classDens_df = pop_df[rep_mask].groupby(\"REP_CAT\")[\n            [popCountField, 'POP_AREA']\n            ].sum().rename(\n            columns = {popCountField: \"SUM_\" + popCountField, \n                       \"POP_AREA\": \"SUM_POP_AREA\"}\n            )\n            \n    #Calculate sample density for sampled classes\n    classDens_df[\"SAMPLEDENS\"] = classDens_df[\n            \"SUM_\" + popCountField\n            ] / classDens_df[\"SUM_POP_AREA\"]\n    classDens_df[\"METHOD\"] = \"Sampled\"\n    classDens_df[\"CLASSDENS\"] = classDens_df[\"SAMPLEDENS\"]\n                    \n    #Add preset densities to summary table\n    if presetTable:\n        print (\"Adding preset values to the summary table...\")\n        for preset_cat in list(presetData):\n            classDens_df.loc[int(preset_cat), \"CLASSDENS\"] = presetData[\n                    preset_cat\n                    ]\n            classDens_df.loc[int(preset_cat), \"METHOD\"] = 'Preset'\n            \n    # For all sampled and preset classes, calculate a population estimate.\n    print (\n            \"Calculating population estimate for sampled and preset classes...\"\n            )            \n    #Get representative population densities from class density DataFrame.\n    dasy_df = dasy_df.join(classDens_df['CLASSDENS'], on = ancCatName).fillna(0)\n    \n    '''\n    #Set mask for dasy_df that will limit ancillary categories to those in the \n    class density DataFrame.\n    '''\n    popEst_mask = dasy_df[ancCatName].isin(classDens_df.index)\n    \n    '''\n    POP_EST = area of the dasymetric unit \n    * the representative population density of the ancillary class associated \n    with the dasymetric unit\n    '''\n    dasy_df[\"POP_EST\"] = 0\n    dasy_df.loc[popEst_mask, \"POP_EST\"] = dasy_df.loc[\n            popEst_mask, dasyAreaField\n            ] * dasy_df.loc[\n                    popEst_mask, 'CLASSDENS'\n                    ]\n    \n    # Intelligent areal weighting for unsampled classes            \n    print (\"Performing intelligent areal weighting for unsampled classes...\")\n    if unSampledList:\n        '''\n        Calculate representative population densities for unsampled ancillary \n        classes using IAW\n        '''\n        unsampled_mask = dasy_df[ancCatName].isin(unSampledList)\n        \n        '''\n        Populate remainining area of each dasymetric unit as the area of \n        dasymetric units associated with unsampled classes and 0 everywhere \n        else.\n        '''\n        dasy_df[\"REM_AREA\"] = 0\n        dasy_df.loc[unsampled_mask, \"REM_AREA\"] = dasy_df.loc[\n                unsampled_mask, dasyAreaField\n                ]\n        \n        '''                          \n        For each polygon, sum the remaining area and sum the population that \n        has already been estimated for sampled/preset classes.\n        '''\n        popEstSum = dasy_df.groupby(popIDField)[\n                [\"POP_EST\", \"REM_AREA\"]\n                ].sum()\n        \n        '''\n        Join popEstSum to dasy_df to transfer the sum of population estimates \n        and the sum of remaining area to the dasymetric DataFrame.\n        '''\n        dasy_df = dasy_df.join(popEstSum[\"POP_EST\"], on = popIDField, \n                               rsuffix = \"poly\")\n        dasy_df = dasy_df.join(popEstSum[\"REM_AREA\"], on = popIDField, \n                               rsuffix = \"poly\")\n        \n        '''\n        Calcualte a population difference between the census population and the \n        population estimated for sampled/preset ancillary classes.\n        '''\n        dasy_df[\"POP_DIFF\"] = dasy_df[\"POP_COUNT\"] - dasy_df[\"POP_ESTpoly\"]\n        \n        '''\n        Calculate an initial population estimate for dasymetric units \n        associated with unsampled ancillary classes and polygons where the \n        sampled/preset population estimates did not exceed the census \n        population count. \n        '''\n        diff_mask = (dasy_df[ancCatName].isin(unSampledList) &\n                     dasy_df['REM_AREApoly'] !=0 )\n        dasy_df.loc[diff_mask, \"POP_EST\"] = (\n                dasy_df.loc[diff_mask, \"POP_DIFF\"].clip(0) * \n                dasy_df.loc[diff_mask, \"REM_AREA\"] / \n                dasy_df.loc[diff_mask, \"REM_AREApoly\"])\n        '''\n        Sum total initial population estimates and remaining area for \n        dasymetric units used to calculate initial population estimates for \n        unsampled ancillary classes.\n        '''\n        ancCat_sum = dasy_df[diff_mask].groupby(ancCatName)[\n                [\"POP_EST\" , \"REM_AREA\"]\n                ].sum()\n        \n        '''\n        Calculate the representative population density for unsampled classes \n        using ancCat_sum and update the class density DataFrame.\n        '''\n        for cat in ancCat_sum.index:\n            classDens_df.loc[cat, \"CLASSDENS\"] = ancCat_sum.loc[cat, \n                            \"POP_EST\"] / ancCat_sum.loc[cat, \n                                           \"REM_AREA\"]\n            classDens_df.loc[cat, \"METHOD\"] = \"IAW\"   \n        \n        '''\n        Add representative population densities for unsampled classes in the \n        dasymetric DataFrame.\n        '''\n        dasy_df.loc[unsampled_mask, 'CLASSDENS'] = dasy_df.loc[\n                unsampled_mask\n                ].join(classDens_df.loc[\n                        ancCat_sum.index, 'CLASSDENS'\n                        ], \n                on = ancCatName, rsuffix = \"_classDens\")['CLASSDENS_classDens']\n        \n        '''\n        Calculate new population estimates using representative population \n        densities for unsampled classes.\n        POP_EST = dasymetric area * class density\n        '''\n        dasy_df.loc[unsampled_mask, \"POP_EST\"] = dasy_df.loc[unsampled_mask, \n                   dasyAreaField] * dasy_df.loc[unsampled_mask, \n                               'CLASSDENS']\n                               \n        # End of intelligent areal weighting\n             \n    # Perform final calculations to ensure pycnophylactic integrity\n    print (\n            \"Performing final calculations to ensure pycnophylactic\" \\\n            \" integrity...\"\n            )\n    '''\n    For each dasymetric unit, use the ratio of the estimated population to the \n    total population estimated for the polygon associated with the dasymetric \n    unit to redistribute the census population.\n    '''\n\n    '''\n    if the sum of population densities within the source unit is equal to 0\n    set the POP_EST for those to 1 (i.e., area weighting (equation 5))\n    '''\n\n    idx = (dasy_df\n            .groupby(popIDField)\n            .filter(\n                lambda s: s['POP_EST'].sum() == 0 and\n                          s['POP_COUNT'].sum() > 0\n                    ).index\n            )\n\n    dasy_df.loc[idx, 'POP_EST'] = 1\n    \n    #Sum population estimates by polygon.\n    popEstsum = dasy_df.groupby(popIDField)[\"POP_EST\"].sum()\n    \n    dasy_df[\"TOTALFRACT\"] = dasy_df[\"POP_EST\"] / dasy_df.join(popEstsum, \n           on = popIDField, rsuffix = \"SUM\")[\"POP_ESTSUM\"]\n    dasy_df[\"NEW_POP\"] = dasy_df[\"TOTALFRACT\"] * dasy_df[\"POP_COUNT\"]\n    dasy_df[\"NEWDENSITY\"] = dasy_df[\"NEW_POP\"] / dasy_df[dasyAreaField]\n    \n    #Replace nan with 0\n    dasy_df = dasy_df.fillna(0)\n    \n    #export dasy table to .csv\n    dasy_df.to_csv(dasyWorkTable, header = True)\n               \n    #export pop_df to .csv\n    pop_df.fillna(0).to_csv(popWorkTable, header = True)\n            \n    #export classDens_df to sampling summary table\n    classDens_df.to_csv(os.path.join(out_dir, \"SamplingSummaryTable.csv\"), \n                        header = True)\n    \n    #Create final population density raster.\n    print (\"Creating population density raster...\")\n    #Create population density array.\n    dasy_lut = dasy_df[['Value', 'NEWDENSITY']].set_index('Value')\n    dasy_lut.loc[dasy_nd, 'NEWDENSITY'] = -999 #NoData value from comb_arr\n    dens_df = pd.DataFrame(np.ravel(comb_arr)).join(dasy_lut, on = 0)\n    dens_ar = np.array(\n            dens_df['NEWDENSITY']\n            ).reshape(\n                    (comb_arr.shape[0], comb_arr.shape[1])\n                    )\n    \n    #Write array to population density raster.\n    densRast = rast_driver.Create(densityRaster, cols, rows, 1, \n                                  gdal.GDT_Float32, options=['COMPRESS=LZW'])\n    densRast.SetGeoTransform((ulx, ancRaster.GetGeoTransform()[1], 0, \n                              uly, 0, ancRaster.GetGeoTransform()[5]))\n    densRast.SetProjection(anc_proj)\n    densRast_b1 =densRast.GetRasterBand(1)\n    densRast_b1.WriteArray(dens_ar)\n    densRast_b1.SetNoDataValue(-999)\n    densRast = None\n    \n    print (\"All outputs from this tool can be found in \" + out_dir)\n\n#------------------------------------------------------------------------------\n#Get arguments to run dasy_pop from command line\nif __name__ == '__main__':\n    #create ArgumentParser\n    parser = ap.ArgumentParser(description='This script accepts population \\\n                               and ancillary datasets for preparing \\\n                               population density rasters using intelligent \\\n                               dasymetric mapping.')\n    \n    #add arguments\n    parser.add_argument('population_features', type = str, \n                        help = 'The census polygons with unique identifiers \\\n                        and a count of the population for each polygon')\n    parser.add_argument('population_count_field', type = str, \n                        help = \"The field in the population_features that \\\n                        stores the polygon's populations\")\n    parser.add_argument('population_key_field', type = str, \n                        help = \"The unique identifier field for each polygon \\\n                        in population_features\")\n    parser.add_argument('ancillary_raster', type = str, \n                        help = \"The land cover raster that is used for \\\n                        dasymetric population mapping\")\n    parser.add_argument('output_directory', type = str, \n                        help = \"The directory where all outputs from the \\\n                        script will be saved.\")\n    parser.add_argument('--uninhabited_file', type = str, nargs='?', \n                        help = \"An optional feature class containing \\\n                        uninhabited areas\")\n    parser.add_argument('--minimum_sampling_area', type = int, \n                        nargs='?',default = 1, \n                        help = \"The minimum number of raster cells in a \\\n                        source polygon for it to be considered representative \\\n                        of a class - default = 1\")\n    parser.add_argument('--minimum_sample', type = int, nargs='?', default = 3, \n                        help = \"The minimum number of source units to ensure \\\n                        a representative sample for a land cover class \\\n                        - default = 3\")\n    parser.add_argument('--percent', type = float, nargs='?', default = 0.95, \n                        help = \"The minimum percent of a source polygon's \\\n                        area that an ancillary class must cover in order for \\\n                        the source polygon to be considered representative of \\\n                        that class. Please enter as a decimal \\\n                        - default = 0.95\")\n    parser.add_argument('--pop_nodata', type = int, nargs='?', default = 0, \n                        help = \"The population_features will be converted to \\\n                        raster and this will be the NoData value \\\n                        - default = 0\")\n    parser.add_argument('--anc_nodata', type = int, nargs='?', default = 0, \n                        help = \"The NoData value for the ancillary raster \\\n                        - default = 0\")   \n\n    #get args\n    args = parser.parse_args()\n        \n    #run function\n    dasy_map(\n            popFeat_path = args.population_features, \n            popCountField = args.population_count_field, \n            popKeyField = args.population_key_field, \n            ancRaster_path = args.ancillary_raster, \n            popAreaMin = args.minimum_sampling_area, \n            sampleMin = args.minimum_sample,\n            percent = args.percent, \n            uninhab_path = args.uninhabited_file,\n            out_dir = args.output_directory,\n            anc_nd = args.pop_nodata,\n            pop_nd = args.anc_nodata\n            )\n", "meta": {"hexsha": "19a33ab0b517ebb338137ffedfbf338ef1dad059", "size": 26586, "ext": "py", "lang": "Python", "max_stars_repo_path": "idm.py", "max_stars_repo_name": "USEPA/Dasymetric-Toolbox-OpenSource", "max_stars_repo_head_hexsha": "d57c6c06b265b85eb3c4c62140d917405e37d161", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-12-17T16:34:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:31:30.000Z", "max_issues_repo_path": "idm.py", "max_issues_repo_name": "USEPA/Dasymetric-Toolbox-OpenSource", "max_issues_repo_head_hexsha": "d57c6c06b265b85eb3c4c62140d917405e37d161", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "idm.py", "max_forks_repo_name": "USEPA/Dasymetric-Toolbox-OpenSource", "max_forks_repo_head_hexsha": "d57c6c06b265b85eb3c4c62140d917405e37d161", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-28T07:35:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-28T07:35:08.000Z", "avg_line_length": 42.4019138756, "max_line_length": 92, "alphanum_fraction": 0.6103964493, "include": true, "reason": "import numpy", "num_tokens": 6194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.542863297964157, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.19900812077304933}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"Randk-Order-Based clustering algorithm.\n\nI combine Approximate-Rank-Order algorithm and Chinese-Whispers algorithm\n in ROCWClustering class.\n\"\"\"\n# Author: Soroush Moazed <soroush.moazed@gmail.com>\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport itertools\n\nimport numpy as np\nfrom sklearn.neighbors import NearestNeighbors\n\n\nclass BaseClustering:\n\n    def __init__(self):\n        pass\n\n    def fit_predict(self, X):\n        pass\n\n    def score(self, X, y_true):\n        y_pred = self.fit_predict(X)\n        pairwise_precision = self._calc_pw_precision(y_pred, y_true)\n        pairwise_recall = self._calc_pw_recall(y_pred, y_true)\n        pairwise_f_measure = 2 * (pairwise_precision * pairwise_recall)\\\n            / (pairwise_precision + pairwise_recall)\n        return pairwise_f_measure, pairwise_precision, pairwise_recall\n\n    @staticmethod\n    def _calc_pw_precision(y_pred, y_true):\n        unique_clusters = np.unique(y_pred)\n        n_pairs = 0\n        n_same_class_pairs = 0\n        for cluster in unique_clusters:\n            sample_indices = np.where(y_pred == cluster)[0]\n            combs = np.array(list(itertools.combinations(sample_indices, 2)), dtype=np.int64)\n            if not np.any(combs):\n                continue\n            combs_classes = y_true[combs]\n            same_class_pairs = np.where(combs_classes[:, 0] == combs_classes[:, 1])[0]\n            n_pairs += len(combs)\n            n_same_class_pairs += len(same_class_pairs)\n        pw_precision = n_same_class_pairs / n_pairs\n        return pw_precision\n\n    @staticmethod\n    def _calc_pw_recall(y_pred, y_true):\n        unique_classes = np.unique(y_true)\n        n_pairs = 0\n        n_same_cluster_pairs = 0\n        for clss in unique_classes:\n            sample_indices = np.where(y_true == clss)[0]\n            combs = np.array(list(itertools.combinations(sample_indices, 2)), dtype=np.int64)\n            if not np.any(combs):\n                continue\n            combs_clusters = y_pred[combs]\n            same_cluster_pairs = np.where(combs_clusters[:, 0] == combs_clusters[:, 1])[0]\n            n_pairs += len(combs)\n            n_same_cluster_pairs += len(same_cluster_pairs)\n        pw_recall = n_same_cluster_pairs / n_pairs\n        return pw_recall\n\n\nclass ROCWClustering(BaseClustering):\n\n    \"\"\"Approximated rank-order clustering implemented using Chinese Whispers algorithm.\n\n    Using rank-order distances generate a graph, and feed this graph to ChineseWhispers\n     algorithm for clustering.\n    \"\"\"\n\n    def __init__(self, k, metric, n_iteration, algorithm):\n        super().__init__()\n        self.k = k\n        self.metric = metric\n        self.n_iteration = n_iteration\n        self.knn_algorithm = algorithm\n\n    def fit_predict(self, X):\n        if len(X) > self.k:\n            graph = ROGraph(self.k, self.metric, algorithm=self.knn_algorithm)\n        else:\n            graph = ROGraph(len(X), self.metric, algorithm=self.knn_algorithm)\n        adjacency_mat = graph.generate_graph(X)\n        clusterer = ChineseWhispersClustering(self.n_iteration)\n        labels = clusterer.fit_predict(adjacency_mat)\n        return labels\n\n\nclass ChineseWhispersClustering:\n\n    def __init__(self, n_iteration=5):\n        self.n_iteration = n_iteration\n        self.adjacency_mat_ = None\n        self.labels_ = None\n\n    def fit_predict(self, adjacency_mat):\n\n        \"\"\"Fits and returns labels for samples\"\"\"\n\n        n_nodes = adjacency_mat.shape[0]\n        indices = np.arange(n_nodes)\n        labels_mat = np.arange(n_nodes)\n        for _ in range(self.n_iteration):\n            np.random.shuffle(indices)\n            for ind in indices:\n                weights = adjacency_mat[ind]\n                winner_label = self._find_winner_label(weights, labels_mat)\n                labels_mat[ind] = winner_label\n        self.adjacency_mat_ = adjacency_mat\n        self.labels_ = labels_mat\n        return labels_mat\n\n    @staticmethod\n    def _find_winner_label(node_weights, labels_mat):\n        adjacent_nodes_indices = np.where(node_weights > 0)[0]\n        adjacent_nodes_labels = labels_mat[adjacent_nodes_indices]\n        unique_labels = np.unique(adjacent_nodes_labels)\n        label_weights = np.zeros(len(unique_labels))\n        for ind, label in enumerate(unique_labels):\n            indices = np.where(adjacent_nodes_labels == label)\n            weight = np.sum(node_weights[adjacent_nodes_indices[indices]])\n            label_weights[ind] = weight\n        winner_label = unique_labels[np.argmax(label_weights)]\n        return winner_label\n\n\nclass ROGraph:\n\n    def __init__(self, k, metric, algorithm):\n\n        self.k = k\n        self.metric = metric\n        self.knn_algorithm = algorithm\n        self.adjacency_mat_ = None\n\n    @property\n    def adjacency_mat(self):\n        return self.adjacency_mat_\n\n    def generate_graph(self, X):\n        order_lists = self._get_knns(X)\n        pw_distances = self._generate_normalized_pw_distances(order_lists)\n        adjacency_mat = self._generate_adjacency_mat(pw_distances)\n        return adjacency_mat\n\n    def _get_knns(self, X):\n\n        \"\"\"Generates order lists and absolute distances of k-nearest-neighbors\n            for each data point.\n        \"\"\"\n\n        nbrs = NearestNeighbors(n_neighbors=self.k,\n                                algorithm=self.knn_algorithm,\n                                metric=self.metric).fit(X)\n        _, order_lists = nbrs.kneighbors(X)\n        return order_lists\n\n    def _generate_normalized_pw_distances(self, order_lists):\n        n_samples = len(order_lists)\n        combs = itertools.combinations([i for i in range(n_samples)], 2)\n        pw_distances = np.zeros((n_samples, n_samples))\n        for ind1, ind2 in combs:\n            order_list_1, order_list_2 = order_lists[ind1], order_lists[ind2]\n            pw_dist = self._calc_pw_dist(ind1, ind2, order_list_1, order_list_2)\n            pw_distances[ind1, ind2] = pw_dist\n        pw_distances = pw_distances / pw_distances.max()\n        pw_distances = pw_distances + pw_distances.T\n        return pw_distances\n\n    def _generate_adjacency_mat(self, pw_distances):\n        adjacency_mat = self._dist2adjacency(pw_distances)\n        self.adjacency_mat_ = adjacency_mat\n        return adjacency_mat\n\n    @staticmethod\n    def _dist2adjacency(distances):\n        mask_mat = np.zeros(distances.shape)\n        mask_mat[np.where(distances > 0)] = 1\n        adjacency_mat = (1 - distances) * mask_mat\n        return adjacency_mat\n\n    def _calc_pw_dist(self, ind_a, ind_b, order_list_a, order_list_b):\n        pw_dist = 0.0\n        if np.any(np.intersect1d(order_list_a, order_list_b)):\n            order_b_in_a, order_a_in_b = self._calc_orders(ind_a, ind_b, order_list_a, order_list_b)\n            d_m_ab = self._calc_dm(order_list_a, order_list_b, order_b_in_a)\n            d_m_ba = self._calc_dm(order_list_b, order_list_a, order_a_in_b)\n            min_of_two = min(order_a_in_b, order_b_in_a)\n            pw_dist = (d_m_ab + d_m_ba) / min_of_two\n        return pw_dist\n\n    def _calc_orders(self, ind_a, ind_b, order_list_a, order_list_b):\n        order_b_in_a = np.where(order_list_a == ind_b)[0]\n        if not np.any(order_b_in_a):\n            order_b_in_a = self.k\n        else:\n            order_b_in_a = order_b_in_a[0]\n        order_a_in_b = np.where(order_list_b == ind_a)[0]\n        if not np.any(order_a_in_b):\n            order_a_in_b = self.k\n        else:\n            order_a_in_b = order_a_in_b[0]\n        return order_b_in_a, order_a_in_b\n\n    def _calc_dm(self, order_list_a, order_list_b, order_b_in_a):\n        dist = 0\n        for i in range(min(self.k, order_b_in_a)):\n            sample_index = order_list_a[i]\n            if np.any(order_list_b == sample_index):\n                dist += 1 / self.k\n            else:\n                dist += 1\n        return dist\n", "meta": {"hexsha": "22d26fbce1e7aeed0b6a50da449c9753f965bb4c", "size": 7887, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/clustering.py", "max_stars_repo_name": "iamsoroush/facekoo", "max_stars_repo_head_hexsha": "d8569fe188628d35e8b2f39e1e753fa91141144d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/clustering.py", "max_issues_repo_name": "iamsoroush/facekoo", "max_issues_repo_head_hexsha": "d8569fe188628d35e8b2f39e1e753fa91141144d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/clustering.py", "max_forks_repo_name": "iamsoroush/facekoo", "max_forks_repo_head_hexsha": "d8569fe188628d35e8b2f39e1e753fa91141144d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.85, "max_line_length": 100, "alphanum_fraction": 0.6480284012, "include": true, "reason": "import numpy", "num_tokens": 1834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725053, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.19900811535058147}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n##############\n# GPathFinder: Identification of ligand pathways by a multi-objective\n# genetic algorithm\n# \n# https://github.com/insilichem/gpathfinder\n#\n# Copyright 2019 José-Emilio Sánchez Aparicio, Giuseppe Sciortino,\n# Daniel Villadrich Herrmannsdoerfer, Pablo Orenes Chueca, \n# Jaime Rodríguez-Guerra Pedregal and Jean-Didier Maréchal\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n#      http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n##############\n\n\"\"\"\nThis script complements the Gpath gene by generating a refined pathway from the \nframes it provides. The new interpolated frames avoid high clashscore conformations\nthrough a RRT path planning algorithm.\n\"\"\"\n\nimport time\nimport random\nimport math\nimport copy\nimport heapq\nimport shutil\nimport yaml\nimport zipfile\nfrom argparse import ArgumentParser\n\nimport pychimera\npychimera.patch_environ()\npychimera.enable_chimera()\n\nfrom Combine import combine\nimport chimera\nimport mdtraj\nimport numpy as np\nimport Matrix as M\nimport itertools, operator\nimport os\n\nfrom FitMap.search import random_rotation\nfrom Molecule import atom_positions\n\nimport pprint\npp = pprint.PrettyPrinter(4)\n\nimport gpath\nfrom gpath import base\nfrom gpath.genes import path_normalmodes\nfrom gpath.genes import molecule\nfrom gpath.genes import path_torsion as torsion\nfrom gpath.genes import path_rotamers as rotamers\nfrom gpath.objectives import contacts\n\n\ndef parse_rotamers(chi_groups,node):\n\t\"\"\"\n\tSlices rotamer angles into a list of lists for all chi angles in a given rotamer.\n\n\tParameters\n\t----------\n\tchi_groups : \n\t    unparsed list of rotmaer angles\n\tnode : TYPE\n\t    Description\n\t\n\tReturns\n\t-------\n\tTYPE\n\t    Description\n\t\"\"\"\n\tparsed_chi_groups=[]\n\tchi_groups = sorted(chi_groups, key=operator.itemgetter(2))\n\tfor residue, group in itertools.groupby(chi_groups, operator.itemgetter(2)):\n\t\tg_list=list(group)\n\t\tchis=[item[3] for item in g_list]\n\t\tparsed_chi_groups.append([residue,chis])\n\n\tchi_num=[len(chi_item[1]) for chi_item in parsed_chi_groups]\n\tit = iter(node['rotamers'])\n\tsliced =[list(itertools.islice(it, 0, i)) for i in chi_num]\n\n\tparsed_chi_groups=[ [residue,node_chis] for (residue,__), node_chis in zip(parsed_chi_groups,sliced) ]\n\treturn parsed_chi_groups\n\ndef merge_two_dicts(residue_dict_start, residue_dict_end):\n\t\"\"\"Merge two dictionaries into one.\n\t\n\tParameters\n\t----------\n\tresidue_dict_start : dict\n\tresidue_dict_end : dict\n\t\n\tReturns\n\t-------\n\tresidue_dict_merged: dict\n\t\"\"\"\n\tresidue_dict_merged = residue_dict_start.copy()\n\tresidue_dict_merged.update(residue_dict_end)\n\treturn residue_dict_merged\n\ndef slerp(p0, p1, t):\n\t\"\"\"\n\tComputes slerp interpolation of the quaternions associated with the rotation matrices of the ligand.\n\t\n\tParameters\n\t----------\n\tp0 : list\n\t\tInitial quaternion\n\tp1 : list\n\t\tEnd quaternion\n\tt : float\n\t\tinterpolation fraction\n\t\n\tReturns\n\t-------\n\tlist\n\t\tinterpolated quaternion as list of floats\n\t\"\"\"\n\tdot = np.dot(p0 / np.linalg.norm(p0), p1 / np.linalg.norm(p1))\n\n\tdot_threshold = 0.9995\n\tif dot > dot_threshold:\n\t\tresult = p0 + t * (p1 - p0)\n\t\tresult = result / np.linalg.norm(result)\n\t\tresult = result / np.linalg.norm(result)\n\t\treturn result\n\n\tomega = np.arccos(dot)\n\tso = np.sin(omega)\n\tresult = np.sin((1.0 - t) * omega) / so * p0 + np.sin(t * omega) / so * p1\n\tresult = result / np.linalg.norm(result)\n\treturn result\n\ndef correct_geometry(v):\n\t\"\"\"\n\n\tIf needed, identifies expanded angles with a corresponding one in the range (-180,180)\n\t\n\tParameters\n\t----------\n\tv : list\n\t\ttorsion or rotamer angle list that needs to be corrected to the range (-180,180)\n\t\n\tReturns\n\t-------\n\tlist\n\t\tcorrected list of rotamer angles\n\t\"\"\"\n\n\tfor v_comp in v:\n\t\tif v_comp > 180.0:\n\t\t\tv_comp = v_comp - 360.0\n\t\tif v_comp < -180.0:\n\t\t\tv_comp = v_comp + 360.0\n\treturn v\n\n\ndef correct_quaternion_geometry(node1, node2):\n\t\"\"\"\n\tEnsure that the dot product of two quaterions is always positive as required by the slerp method\n\t\n\tParameters\n\t----------\n\tnode1 : dict\n\tnode2 : dict\n\t\"\"\"\n\tif sum([node1_comp * node2_comp for node1_comp, node2_comp in zip(node1['rotation'], node2['rotation'])]) < 0:\n\t\tnode2['rotation'] = [-node2_comp for node2_comp in node2['rotation']]\n\n\ndef diff_node(node1, node2):\n\t\"\"\"\n\tCompute the difference of two nodes. Used to obtain the direction of expansion towards the nearest node\n\tand to compute the distance between two nodes. Also applies the required geometric corrections\n\tcorrect_geometry and correct_quaternion_geometry\n\t\n\tParameters\n\t----------\n\tnode1 : dict\n\tnode2 : dict\n\t\n\tReturns\n\t-------\n\tdiff_dict : dict\n\t\tdictionary of node attributes, with values equal to the difference of the attributes of the two nodes\n\t\"\"\"\n\tdiff_dict = {}\n\n\tfor key in node1.keys():\n\t\tif key == 'mode':\n\t\t\tdiff_dict[key] = [node2_comp - node1_comp for node2_comp, node1_comp in\n\t\t\t\t\t\t\t\t\t\t  zip(node2[key],node1[key])]\n\t\tif key == 'torsions':\n\t\t\tdiff_dict[key] = [node2_comp - node1_comp for node2_comp,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  node1_comp in\n\t\t\t\t\t\t\t\t\t\t  zip(node2[key],node1[key])]\n\t\t\tcorrect_geometry(diff_dict[key])\n\t\tif key == 'rotamers':\n\t\t\tdiff_dict[key] = [node2_comp - node1_comp for node2_comp,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  node1_comp in\n\t\t\t\t\t\t\t\t\t\t  zip(node2[key],node1[key])]\n\t\t\tcorrect_geometry(diff_dict[key])\n\t\tif key == 'rotation':\n\t\t\tcorrect_quaternion_geometry(node1, node2)\n\t\t\tdiff_dict[key] = [node2_comp - node1_comp for node2_comp,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  node1_comp in\n\t\t\t\t\t\t\t\t\t\t  zip(node2[key],node1[key])]\n\t\tif key == 'translation':\n\t\t\tdiff_dict[key] = [node2_comp - node1_comp for node2_comp,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  node1_comp in\n\t\t\t\t\t\t\t\t\t\t  zip(node2[key],node1[key])]\n\treturn diff_dict\n\ndef make_norm_dict(node1, node2):\n\t\"\"\"\n\tCreates a dictionary of the distance of each attribute of two nodes\n\tUsed in order to normalize the expansion vector created in expand()\n\t\n\tParameters\n\t----------\n\tnode1 : dict\n\tnode2 : dict\n\t\n\tReturns\n\t-------\n\tnorm_dict : dict\n\t\tdictionary of distances\n\t\"\"\"\n\tdiff_dict = diff_node(node1, node2)\n\tnorm_dict = {}\n\tfor key in diff_dict.keys():\n\t\tif key == 'mode':\n\t\t\tnorm_dict[key] = math.sqrt(\n\t\t\t\tsum([dx_comp * dx_comp for dx_comp in diff_dict[key]]))\n\t\tif key == 'torsions':\n\t\t\tnorm_dict[key] = math.sqrt(\n\t\t\t\tsum([dx_comp * dx_comp for dx_comp in diff_dict[key]]))\n\t\tif key == 'rotamers':\n\t\t\tnorm_dict[key] = math.sqrt(\n\t\t\t\tsum([dx_comp * dx_comp for dx_comp in diff_dict[key]]))\n\t\tif key == 'rotation':\n\t\t\tnorm_dict[key] = math.sqrt(\n\t\t\t\tsum([dx_comp * dx_comp for dx_comp in diff_dict[key]]))\n\t\tif key == 'translation':\n\t\t\tnorm_dict[key] = math.sqrt(\n\t\t\t\tsum([dx_comp * dx_comp for dx_comp in diff_dict[key]]))\n\treturn norm_dict\n\n\ndef weighted_norm(node1, node2):\n\t\"\"\"\n\tApply weights to the norm dictionary from norm_dict to give equal\n\tweight to all attributes of the node\n\t\n\tParameters\n\t----------\n\tnode1 : dict\n\tnode2 : dict\n\t\n\tReturns\n\t-------\n\tfloat\n\t\tweighted norm between two nodes\n\t\"\"\"\n\n\tnorm_dict = make_norm_dict(node1, node2)\n\tweight_norm_dict={}\n\tfor key in norm_dict.keys():\n\t\tif key == 'mode':\n\t\t\tweight_norm_dict[key] = norm_dict[key] / 1.0\n\t\tif key == 'torsions':\n\t\t\tweight_norm_dict[key] = norm_dict[key] / 360.0\n\t\tif key == 'rotamers':\n\t\t\tweight_norm_dict[key] = norm_dict[key] / 360.0\n\t\tif key == 'rotation':\n\t\t\tweight_norm_dict[key] = norm_dict[key] / 1.0\n\t\tif key == 'translation':\n\t\t\tweight_norm_dict[key] = norm_dict[key] / 1.0\n\n\tnorm=sum(norm_dict.values())\n\treturn norm\n\n\ndef get_nearest_list_index(node_list, guide_node):\n\t\"\"\"\n\tFinds nearest nodes among node_list, using the metric given by weighted_norm\n\tand chooses one of them at random.\n\t\n\tParameters\n\t----------\n\tnode_list : list\n\t\tlist of nodes corresponding to one of the two search trees growing towards each other.\n\tguide_node : dict\n\t\tnode that has been randomly chosen to expand towards\n\t\n\tReturns\n\t-------\n\tmin_ind : int\n\t\tindex of the chosen node\n\tmin_dist_choice : float\n\t\tdistance between the chosen node and the guide_node\n\t\"\"\"\n\tk_nearest = int(len(node_list) / 100) + 1\n\tdlist = [weighted_norm(node, guide_node) for node in node_list]\n\tk_min_dist_list = heapq.nsmallest(k_nearest, dlist)\n\tmin_dist_choice = random.choice(k_min_dist_list)\n\tmin_ind = dlist.index(min_dist_choice)\n\n\treturn min_ind, min_dist_choice\n\n\nclass RRT:\n\t\"\"\"\n\tContains the express algorithm to generate the path and all the objects needed for it\n\t(the self.protein, the ligand, etc.)\n\t_start configurations correspond to the state at the frame frame_num, _end at frame frame_num+1\n\t\n\t\"\"\"\n\tdef __init__(self, input_path, output_path, path_num, frame_num, greed=10, max_iter=10000,\n\t\t\t\t relax_clashscore=True, max_clashscore=100.0,step_num=10):#74.96\n\t\t\"\"\"Summary\n\t\t\n\t\tParameters\n\t\t----------\n\t\tinput_path : str\n\t\t\tdirectory path from which to gather the input files\n\t\toutput_path : str\n\t\t\tpath to the directory in which the result files will be placed\n\t\tpath_num : int\n\t\t    path number of the .zip file in the directory\n\t\tframe_num : int\n\t\t\tframe number used as the starting frame. the end frame is taken as frame_num+1\n\t\tgreed : int, optional\n\t\t\tgreed parameter of the RRT-algorithm\n\t\tmax_iter : int, optional\n\t\t\tmaximum number of iterations\n\t\trelax_clashscore : bool, optional\n\t\t\tOptional argument to allow steadily increasing clashscore values or use the maximum permitted value from the start\n\t\tmax_clashscore : float, optional\n\t\t\tvalue of the maximal permitted clashscore\n\t\tstep_num : int, optional\n\t\t\texpected number of interpolation steps between the start and end configuration.\n\t\t\"\"\"\n\t\tself.input_path = input_path\n\t\tself.output_path = output_path\n\t\tself.frame_num = frame_num\n\t\tself.greed = greed\n\t\tself.max_iter = max_iter\n\t\tself.relax_clashscore = relax_clashscore\n\t\tself.max_clashscore = max_clashscore\n\t\tself.step_num = step_num\n\t\tself.path_num=path_num\n\n\tdef ready(self):\n\t\t\"\"\"\n\t\t\n\t\tAttributes\n\t\t----------\n\t\tclash_diff : float\n\t\t    Difference between the clashscore of the start node as measured by the refinement script and the one saved from the Gpath results\n\t\t    refinement clashscore can be higher since it may include more rotamers from frame_num and frame_num+1 as part of the interpolation \n\t\tconfig_end : dict\n\t\t    start node configuration corresponding to the state at frame frame_num+1\n\t\tconfig_start : dict\n\t\t    start node configuration corresponding to the state at frame frame_num\n\t\tcontacts_objective : gpath objective\n\t\t    \n\t\tframe_vdw_volume : float\n\t\t    total Van der Wals volume of the ligand and active rotamers \n\t\tgoal: bool\n\t\t\trecords whether the algorithm has been able to connect the initial and final configurations\n\t\tind : gpath individual\n\t\t  \n\t\titeration_counter : int\n\t\t    counter that will keep track of the total number of iterations of the RRT-algorithm\n\t\tligand : chimera molecule\n\n\t\tligand_gene : gpath gene\n\n\t\tnext_normal_mode_sample : numpy array\n\t\t    atom coordiantes corresponding to the normal mode deformation of the frame framenum+1\n\t\tnext_sample_number : int\n\t\t    normal modes sample number for the frame frame_number+1\n\t\tnm_gene : gpath gene\n\t\t    Description\n\t\tnormal_mode_sample : numpy array\n\t\t    atom coordinates corresponding to the normal mode deformation of the frame framenum\n\t\tpath : list\n\t\t    list of nodes connecting the start and end configuration\n\t\tprotein : chimera molecule\n\t\t    \n\t\tprotein_gene : gpath gene\n\t\t   \n\t\trotamer_gene : gpath gene\n\t\t    \n\t\trotamer_start : list\n\t\t    list of rotamer angles with values corresponding to their start configuration\n\t\tsample_number : int\n\t\t    normal modes sample number for the frame frame_number\n\t\tto_zero : tuple\n\t\t    matrix that centers the ligand to the origin before applying the second transformation to set it in the right location\n\t\ttorsion_gene : gpath gene\n\n\n\n\t\t\"\"\"\n\t\tself.config_end = {}\n\t\tself.config_start = {}\n\n\t\tmodes_path = os.path.join(self.input_path, 'modes.nmd')\n\t\tsamples_path = os.path.join(self.input_path, 'samples.samples')\n\n\t\tfor file in os.listdir(self.input_path):\n\t\t\tif str(self.path_num).zfill(3)+'.zip' in file:\n\t\t\t\tgpathzip = file\n\n\t\tzip_path = os.path.join(self.input_path, gpathzip)\n\n\t\twith zipfile.ZipFile(zip_path) as myzip:\n\t\t\tfor file_name in myzip.namelist():\n\t\t\t\tif 'Protein' in file_name:\n\t\t\t\t\tprotein_path = myzip.extract(\n\t\t\t\t\t\tfile_name, path=self.output_path)\n\n\t\t\t\tif 'Ligand' in file_name:\n\t\t\t\t\tligand_path = myzip.extract(\n\t\t\t\t\t\tfile_name, path=self.output_path)\n\n\t\t\t\tif '.zip' in file_name:\n\t\t\t\t\tpathway_zip_path = myzip.extract(\n\t\t\t\t\t\tfile_name, path=self.output_path)\n\n\t\twith zipfile.ZipFile(pathway_zip_path) as myzip:\n\t\t\tallele_path = myzip.extract('allele.txt', self.output_path)\n\t\t\tscores_path = myzip.extract('scores.txt', self.output_path)\n\t\t\tyaml_path=os.path.join(self.input_path,os.path.basename(self.input_path)+'.yaml')\n\t\t\tframe_path = myzip.extract('frame_{:03d}.pdb'.format(self.frame_num), self.output_path)\n\t\t\tframep1_path = myzip.extract('frame_{:03d}.pdb'.format(self.frame_num + 1), self.output_path)\n\n\t\twith open(allele_path, 'r') as allele_file:\n\t\t\ttry:\n\t\t\t\tpoints=eval(allele_file.read())\n\t\t\texcept:\n\t\t\t\tprint('allele_file load error')\n\n\t\twith open(scores_path, 'r') as scores_file:\n\t\t\ttry:\n\t\t\t\tscores=eval(scores_file.read())\n\t\t\texcept:\n\t\t\t\tprint('scores_file load error')\n\n\t\twith open(yaml_path, 'r') as yaml_file:\n\t\t\ttry:\n\t\t\t\tsettings_dict=yaml.load(yaml_file)\n\t\t\t\tgene_settings={}\n\t\t\t\tfor gene in settings_dict['genes']:\n\t\t\t\t\tif 'torsion' in gene['module']:\n\t\t\t\t\t\tgene_settings['torsions']=gene\n\t\t\t\t\t\tgene_settings['torsions'].pop('module')\n\t\t\t\t\t\tgene_settings['torsions'].pop('name')\n\t\t\t\t\t\tgene_settings['torsions'].pop('target')\n\t\t\t\t\t\tgene_settings['torsions'].pop('anchor')\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif 'rotamers' in gene['module']:\n\t\t\t\t\t\tgene_settings['rotamers']=gene\n\t\t\t\t\t\tgene_settings['rotamers'].pop('module')\n\t\t\t\t\t\tgene_settings['rotamers'].pop('name')\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif 'normalmodes' in gene['module']:\n\t\t\t\t\t\tgene_settings['normalmodes']=gene\n\t\t\t\t\t\tgene_settings['normalmodes'].pop('module')\n\t\t\t\t\t\tgene_settings['normalmodes'].pop('name')\n\t\t\t\t\t\tgene_settings['normalmodes'].pop('target')\n\t\t\t\t\t\tcontinue\n\t\t\texcept yaml.YAMLError as exc:\n\t\t\t\tprint(exc)\n\n\t\tif 'torsions' in points:\n\t\t\ttorsion_list = points['torsions']\n\t\t\ttorsion_anchor = points['torsion_anchor']\n\n\t\txf_list = zip(points['positions'], points['rotations'])\n\n\t\tself.ind = base.MolecularIndividual()\n\n\t\tself.ligand_gene = molecule.Molecule(path=ligand_path, parent=self.ind)\n\t\tself.ind.genes['Ligand'] = self.ligand_gene\n\t\tself.ligand_gene.express()\n\t\tself.ligand = self.ligand_gene.compound.mol\n\n\t\tor_x, or_y, or_z = np.average(atom_positions(self.ligand.atoms), axis=0)\n\t\tself.to_zero = ((1.0, 0.0, 0.0, -or_x),\n\t\t\t\t\t\t(0.0, 1.0, 0.0, -or_y),\n\t\t\t\t\t\t(0.0, 0.0, 1.0, -or_z))\n\n\t\tself.protein_gene = molecule.Molecule(path=protein_path, parent=self.ind)\n\t\tself.ind.genes['Protein'] = self.protein_gene\n\t\tself.protein_gene.express()\n\t\tself.protein = self.protein_gene.compound.mol\n\n\t\tif 'torsions' in points:\n\t\t\tself.torsion_gene = torsion.Torsion('Ligand', parent=self.ligand_gene.parent, anchor=torsion_anchor,**gene_settings['torsions'])\n\n\t\tif 'normal_modes' in points:\n\t\t\tself.nm_gene = path_normalmodes.NormalModes(target='Protein', parent=self.ind, path=modes_path, samples_path=samples_path,**gene_settings['torsions'])\n\t\t\tself.ind.genes['NM'] = self.nm_gene\n\t\telse:\n\t\t\tprint('No normal modes in allele.txt')\n\n\t\t# parse rotamer information from allele.txt and frame_00x.pdb, if allele.txt used rotamers\n\t\tif 'rotamers' in points:\n\t\t\tif points['rotamers'][0] is not []:\n\t\t\t\tframe = chimera.openModels.open(frame_path)\n\t\t\t\tframe_protein = frame[0]\n\t\t\t\tframep1 = chimera.openModels.open(framep1_path)\n\t\t\t\tframep1_protein = framep1[0]\n\t\t\t\tresidues = points['rotamers']\n\t\t\t\tchi_init, residue_init = residues[self.frame_num][0], residues[self.frame_num][1]\n\t\t\t\tchi_end, residue_end = residues[self.frame_num + 1][0], residues[self.frame_num + 1][1]\n\t\t\t\tresidue_dict_start = dict(zip(chi_init, residue_init))\n\t\t\t\tresidue_dict_end = dict(zip(chi_end, residue_end))\n\t\t\t\tresidue_dict_zero = merge_two_dicts(residue_dict_start, residue_dict_end)\n\t\t\t\tresidue_dict_zero = residue_dict_zero.fromkeys(residue_dict_zero, 0.0)\n\n\t\t\t\tresidue_dict_start = merge_two_dicts(\n\t\t\t\t\tresidue_dict_zero, residue_dict_start)\n\t\t\t\tresidue_dict_end = merge_two_dicts(\n\t\t\t\t\tresidue_dict_zero, residue_dict_end)\n\n\t\t\t\tresidues=[residue.split('/') for residue in residue_dict_start.keys()]\n\t\t\t\tresidues=[[residue[0],int(residue[1])] for residue in residues]\n\t\t\t\tself.rotamer_gene= rotamers.Rotamers(residues=residues,parent=self.protein_gene.parent,**gene_settings['rotamers'])\n\t\t\t\tself.ind.genes['Rotamers'] = self.rotamer_gene\n\t\t\t\tself.ind.__ready__()\n\t\t\t\tself.rotamer_gene.__ready__()\n\t\t\t\tself.rotamer_start = []\n\t\t\t\trotamer_end = []\n\t\t\t\tfor rot in residue_dict_start.keys():\n\t\t\t\t\tres_num = int(rot.split('/')[1])\n\n\t\t\t\t\tresidue_dict_start[res_num] = residue_dict_start[rot]\n\t\t\t\t\tresidue_dict_end[res_num] = residue_dict_end[rot]\n\t\t\t\t\tdel residue_dict_end[rot]\n\t\t\t\t\tdel residue_dict_start[rot]\n\n\t\t\t\t\tfor rotamer,protein in zip([self.rotamer_start,rotamer_end],[frame_protein,framep1_protein]):\t\t\n\t\t\t\t\t\tresidue = protein.findResidue(res_num - 1)\n\t\t\t\t\t\tfor chi_num in range(1, 5):\n\t\t\t\t\t\t\tchi_value = getattr(residue, 'chi' + str(chi_num))\n\t\t\t\t\t\t\tif chi_value is not None:\n\t\t\t\t\t\t\t\trotamer.append([res_num, chi_num, self.protein.findResidue(res_num - 1), chi_value])\n\n\t\t\t\tchimera.openModels.close(frame)\n\t\t\t\tchimera.openModels.close(framep1)\n\t\t\t\tself.rotamer_start.sort()\n\t\t\t\trotamer_end.sort()\n\n\t\t\t\trotamer_start_values = [item[3] for item in self.rotamer_start]\n\t\t\t\trotamer_end_values = [item[3] for item in rotamer_end]\n\t\t\t\tself.config_start['rotamers'] = rotamer_start_values\n\t\t\t\tself.config_end['rotamers'] = rotamer_end_values\n\t\t\telse:\n\t\t\t\tprint('No rotamers in frame %s' % self.frame_num)\n\t\telse:\n\t\t\tprint('No rotamers in allele.txt')\n\n\t\t# initialize self.protein normal modes\n\t\tif 'normal_modes' in points:\n\t\t\tself.sample_number = points['normal_modes'][self.frame_num]\n\t\t\tself.next_sample_number = points['normal_modes'][self.frame_num + 1]\n\t\t\tif self.frame_num == 0:\n\t\t\t\tself.normal_mode_sample = np.asarray(\n\t\t\t\t\tself.nm_gene._original_coords)\n\t\t\telse:\n\t\t\t\tself.normal_mode_sample = np.asarray(\n\t\t\t\t\tself.nm_gene.NORMAL_MODES_SAMPLES[self.sample_number])\n\n\t\t\tself.next_normal_mode_sample = np.asarray(\n\t\t\t\tself.nm_gene.NORMAL_MODES_SAMPLES[self.next_sample_number])\n\t\t\t\n\t\t\tself.config_start['mode'] = [0.0]\n\t\t\tself.config_end['mode'] = [1.0]\n\n\t\trotamer_residues = [item[2] for item in self.rotamer_start]\n\t\tself.contacts_objective = contacts.Contacts(['Ligand'], which='clashes', rotamer_residues=rotamer_residues)\n\n\t\tself.config_start['rotation'] = list(M.chimera_xform(xf_list[self.frame_num][1]).getQuaternion())\n\t\tself.config_end['rotation'] = list(M.chimera_xform(xf_list[self.frame_num + 1][1]).getQuaternion())\n\t\tself.config_start['translation'] = [xf_list[self.frame_num][0][i][3] for i in range(3)]\n\t\tself.config_end['translation'] = [xf_list[self.frame_num+1][0][i][3] for i in range(3)]\n\t\t\n\t\tif 'torsions' in points:\n\t\t\ttorsion_list[0] = [0.0 for i in range(\n\t\t\t\tlen(self.torsion_gene.rotatable_bonds))]\n\t\t\tself.config_start['torsions'] = torsion_list[self.frame_num]\n\t\t\tself.config_end['torsions'] = torsion_list[self.frame_num + 1]\n\n\n\t\tself.config_start['clashscore'] = None\n\t\tself.config_end['clashscore'] = None\n\n\t\tself.config_start['iteration_counter'] = None\n\t\tself.config_end['iteration_counter'] = None\n\n\t\tself.config_start['parent'] = None\n\t\tself.config_end['parent'] = None\n\n\t\tself.iteration_counter = -2\n\t\tself.collision_check(self.config_start)\n\n\t\tself.iteration_counter = -3\n\t\tself.collision_check(self.config_end)\n\n\t\tself.max_clashscore=max(self.max_clashscore,self.config_start['clashscore'],self.config_end['clashscore'])\n\n\t\tself.path=[]\n\n\t\tlig_vdw=[4/3*np.pi*lig_atom.defaultRadius**3 for lig_atom in self.ligand.atoms]\n\t\tres_atoms=[]\n\t\tfor item in self.rotamer_start:\n\t\t\tres_atoms.extend(item[2].atoms)\n\t\tres_vdw=[4/3*np.pi*res_atom.defaultRadius**3 for res_atom in res_atoms]\n\t\tself.frame_vdw_volume=sum(lig_vdw+res_vdw)\n\n\tdef save_connect_nodes(self,iteration, node_list, guide_node):\n\t\t\"\"\"\n\n\t\tSaves the nodes from each RRT-tree nearest to each other\n\t\t\n\t\tParameters\n\t\t----------\n\t\titeration : int\n\t\t\tcurrent iteration of the RRT-method\n\t\tnode_list : list\n\t\t\tlist of nodes to be expanded on\n\t\tguide_node : dict\n\t\t\t\n\t\tReturns\n\t\t-------\n\t\tconnect_node_start : dict\n\t\t\tnode of the start tree\n\t\tconnect_node_end : dict\n\t\t\tnode of the end tree\n\t\t    Description\n\t\t\"\"\"\n\t\tif iteration % 2 == 1:\n\t\t\tconnect_node_start = node_list[-1]\n\t\t\tconnect_node_end = guide_node\n\t\telse:\n\t\t\tconnect_node_start = guide_node\n\t\t\tconnect_node_end = node_list[-1]\n\n\t\treturn \tconnect_node_start,connect_node_end\n\n\tdef expand(self, new_node, guide_node,step_size_dict):\n\t\t\"\"\"\n\t\texpand towards guide_node from nearest_node\n\t\t\n\t\tParameters\n\t\t----------\n\t\tnew_node : dict\n\t\t\tnew node to be added to the current tree being expanded\n\t\tguide_node : dict\n\t\t\tnode from the opposite tree that gives the guiding direction\n\t\tstep_size_dict : dict\n\t\t    dictionary of step size values vor each component of the coordinate vector\n\t\t\"\"\"\n\t\tnorm_dict = make_norm_dict(new_node, guide_node)\n\t\tdiff_dict=diff_node(new_node,guide_node)\n\t\tnew_node_dict=new_node\n\n\t\tfor key in new_node_dict.keys():\n\t\t\tif key == 'mode':\n\t\t\t\tif norm_dict[key] != 0:\n\t\t\t\t\tnew_node_dict[key] = [new_comp + step_size_dict[key] * diff_comp / norm_dict[key]\n\t\t\t\t\t\tfor new_comp, diff_comp in zip(new_node_dict[key], diff_dict[key])]\n\t\t\tif key == 'torsions':\n\t\t\t\tif norm_dict[key] != 0:\n\t\t\t\t\tnew_node_dict[key] = [new_comp + step_size_dict[key] * diff_comp / norm_dict[key]\n\t\t\t\t\t\tfor new_comp, diff_comp in zip(new_node_dict[key], diff_dict[key])]\n\t\t\t\t\tcorrect_geometry(new_node_dict[key])\n\t\t\tif key == 'rotamers':\n\t\t\t\tif norm_dict[key] != 0:\n\t\t\t\t\tnew_node_dict[key] = [new_comp + step_size_dict[key] * diff_comp / norm_dict[key]\n\t\t\t\t\t\tfor new_comp, diff_comp in zip(new_node_dict[key], diff_dict[key])]\n\t\t\t\t\tcorrect_geometry(new_node_dict[key])\n\t\t\tif key == 'rotation':\n\t\t\t\tif norm_dict[key] != 0:\n\t\t\t\t\tnew_node_dict[key] = list(slerp(np.asarray(new_node_dict[key]), np.asarray(\n\t\t\t\t\t\tguide_node['rotation']), step_size_dict[key] / (norm_dict[key])))\n\t\t\tif key == 'translation':\n\t\t\t\tif norm_dict[key] != 0:\n\t\t\t\t\tnew_node_dict[key] = [new_comp + step_size_dict[key] * diff_comp / norm_dict[key]\n\t\t\t\t\t\tfor new_comp, diff_comp in zip(new_node_dict[key], diff_dict[key])]\n\n\t\tnew_node=new_node_dict\n\n\tdef apply_node_config(self, node):\n\t\t\"\"\"\n\t\tApply the rotamers, torsions, normal modes and rotations of the given node to the ligand\n\t\tand the protein\n\t\t\n\t\tParameters\n\t\t----------\n\t\tnode : dict\n\t\t\n\t\t\"\"\"\n\t\tquaternion_vector = node['rotation']\n\t\ttranslation = node['translation']\n\n\t\tif 'torsions' in self.config_start:\n\t\t\tself.torsion_gene.allele = node['torsions']\n\t\t\tself.torsion_gene.express()\n\n\t\tif 'mode' in self.config_start:\n\t\t\tif self.frame_num == 0:\n\t\t\t\tself.normal_mode_sample = self.nm_gene._original_coords\n\t\t\telse:\n\t\t\t\tself.normal_mode_sample = np.asarray(\n\t\t\t\t\tself.nm_gene.NORMAL_MODES_SAMPLES[self.sample_number])\n\t\t\tself.next_normal_mode_sample = np.asarray(\n\t\t\t\tself.nm_gene.NORMAL_MODES_SAMPLES[self.next_sample_number])\n\t\t\tinterpol_mode = (1.0 - node['mode'][0]) * self.normal_mode_sample + node['mode'][0] * self.next_normal_mode_sample\n\t\t\tself.nm_gene.allele = interpol_mode\n\t\t\tself.nm_gene._need_express = True\n\t\t\tself.nm_gene.express()\n\n\t\tif 'rotamers' in self.config_start:\n\t\t\tparsed_rotamers=parse_rotamers(self.rotamer_start,node)\n\t\t\tfor residue,chis in parsed_rotamers:\n\t\t\t\tif residue.type not in self.rotamer_gene._residues_without_rotamers:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tself.rotamer_gene.update_rotamer(residue,chis)\n\t\t\t\t\texcept NoResidueRotamersError:  # ALA, GLY...\n\t\t\t\t\t\tprint('no rotamers')\n\t\t\t\t\t\tself.rotamer_gene._residues_without_rotamers.add(residue.type)\n\n\t\t#apply rotation and translation matrix onto the ligand\n\t\trotation_matrix = M.xform_matrix(chimera.Xform().quaternion(*quaternion_vector))\n\t\ttranslation_matrix = M.translation_matrix(translation)\n\t\tmatrices = (translation_matrix,) + (rotation_matrix,) + (self.to_zero,)\n\t\tmatrices = M.multiply_matrices(*matrices)\n\t\tself.ligand.openState.xform = M.chimera_xform(matrices)\n\n\tdef collision_check(self, node):\n\t\t\"\"\"\n\t\tChecks if the node surpasses the maximum clashscore value,\n\t\tif it doesn't it adds the clashscore value as an attribute of the node\n\t\t\n\t\tParameters\n\t\t----------\n\t\tnode : dict\n\t\t\tNode to be checked for collision state\n\t\t\n\t\tReturns\n\t\t-------\n\t\tBoolean\n\t\t\tReturns True in case the clashscore value exceeds the the maximum clashscore\n\t\t\tvalue, False otherwise.\n\t\t\"\"\"\n\t\tself.iteration_counter += 1\n\t\tself.apply_node_config(node)\n\t\tclashscore = self.contacts_objective.evaluate_clashes(self.ind)\n\t\tif self.iteration_counter>0 and clashscore > self.max_clashscore:\n\t\t\t\n\t\t\treturn True  # collision\n\t\telse:\n\t\t\tnode['clashscore'] = clashscore\n\t\t\tnode['iteration_counter'] = self.iteration_counter\n\n\t\t\treturn False  # no collision, safe\n\n\tdef write_refinement(self):\n\t\t\"\"\"\n\t\tApplies the transformation specified for each node in the generated path and writes\n\t\tthe protein and ligand molecule objects as a trajectoryxxx.pdb file, that will be later\n\t\tconverted to an MD Traj .pdb file\n\t\t\"\"\"\n\t\tos.chdir(self.output_path)\n\t\tfor node_num, node in enumerate(self.path):\n\t\t\tself.apply_node_config(node)\n\t\t\tclashscore_written = self.contacts_objective.evaluate_clashes(self.ind)\n\n\n\t\t\ttotalnum = str(self.frame_num).zfill(3) + str(node_num).zfill(3)\n\t\t\tif node_num==0:\n\t\t\t\tchimera.pdbWrite([self.ligand, self.protein], chimera.Xform(),'check%s.pdb' % totalnum)\n\t\t\t\tself.clash_diff=clashscore_written-node['clashscore']\n\n\t\t\tprint(clashscore_written, 'Clashscore of interpol%s.pdb' % totalnum, 'vs stored:',\n\t\t\t\t  node['clashscore'], node['iteration_counter'])\n\n\t\t\tcombination = combine([self.ligand, self.protein], self.protein)\n\t\t\tchimera.pdbWrite([combination], chimera.Xform(),\n\t\t\t\t\t\t\t 'trajectory%s.pdb' % totalnum)\n\n\t\t\tcombination.destroy()\n\t\tif 'normal_modes' in self.config_start:\n\t\t\tself.nm_gene.unexpress()\n\t\tif 'torsions' in self.config_start:\n\t\t\tself.torsion_gene.unexpress()\n\n\t\tself.ligand_gene.unexpress()\n\t\tself.protein_gene.unexpress()\n\n\tdef nodeadder(self):\n\t\t\"\"\"\n\t\tAlternatively expands one of the two RRT trees For a number of max_iter iterations\n\t\t\n\t\tReturns\n\t\t-------\n\t\tgoal : bool\n\t\t\twhether the algorithm has been able to connect the initial and final node or not\n\t\t\"\"\"\n\t\tminimal_distance = 1000\n\t\tself.iteration_counter=0\n\t\tconnect_node_start = self.config_start\n\t\tconnect_node_end = self.config_end\n\t\tnode_list_start = [self.config_start]\n\t\tnode_list_end = [self.config_end]\n\t\tnorm_start_end_dict = make_norm_dict(self.config_start, self.config_end)\n\t\tnorm_start_end_nearest = weighted_norm(self.config_start, self.config_end)\n\t\thalt_step = norm_start_end_nearest / self.step_num\n\t\tmin_clashscore = max(self.config_start['clashscore'],self.config_end['clashscore'])\n\t\trelax_stepsize = (self.max_clashscore - min_clashscore) / self.max_iter\n\t\tstep_size_dict = {}\n\t\tfor key in norm_start_end_dict.keys():\n\t\t\tstep_size_dict[key] = norm_start_end_dict[key] / self.step_num\n\n\t\tcenter_trans = [np.mean((config_start_comp,config_end_comp)) for config_start_comp, config_end_comp\n\t\t\t\t\t\tin zip(self.config_start['translation'], self.config_end['translation'])]\n\n\t\tnode_list = node_list_start\n\t\tother_node_list = node_list_end\n\n\t\tfor iteration in range(self.max_iter):\n\n\t\t\tnode_list,other_node_list = other_node_list,node_list\n\n\t\t\tif self.relax_clashscore:\n\t\t\t\tself.max_clashscore = relax_stepsize * iteration + min_clashscore\n\n\t\t\tguide_dict = {}\n\t\t\tfor key in self.config_start.keys():\n\n\t\t\t\tif key == 'mode':\n\t\t\t\t\tguide_dict[key] = [random.uniform(-1, 2)]\n\t\t\t\tif key == 'torsions':\n\t\t\t\t\tguide_dict[key] = [\n\t\t\t\t\t\trandom.uniform(-180, 180) for i in range(0, len(self.config_end['torsions']))]\n\t\t\t\tif key == 'rotamers':\n\t\t\t\t\tguide_dict[key] = [\n\t\t\t\t\t\trandom.uniform(-180, 180) for i in range(0, len(self.config_end['rotamers']))]\n\t\t\t\tif key == 'rotation':\n\t\t\t\t\tguide_dict[key] = list(M.chimera_xform(\n\t\t\t\t\t\trandom_rotation()).getQuaternion())\n\t\t\t\tif key == 'translation':\n\n\t\t\t\t\tguide_dict[key] = [random.uniform(trans_comp - 2 * norm_start_end_dict['translation'],\n\t\t\t\t\t\t\t\t\t\t\t\t\t  trans_comp + 2 * norm_start_end_dict['translation']) for\n\t\t\t\t\t\t\t\t\t   trans_comp in center_trans]\n\t\t\tguide_node = guide_dict\n\n\t\t\t[min_ind, node_distance] = get_nearest_list_index(node_list, guide_node)\n\t\t\tnearest_node = node_list[min_ind]\n\n\t\t\tnew_node = copy.deepcopy(nearest_node)\n\n\t\t\tself.expand(new_node, guide_node,step_size_dict)\n\t\t\tif not self.collision_check(new_node):\n\t\t\t\tnew_node['parent'] = min_ind\n\t\t\t\tnode_list.append(copy.deepcopy(new_node))\n\t\t\t\tprint(node_distance,minimal_distance,halt_step,'node distance')\n\t\t\t\tif random.randint(0, 100) < self.greed:\n\t\t\t\t\tmin_ind, min_dist = get_nearest_list_index(other_node_list, new_node)\n\t\t\t\t\tguide_node = other_node_list[min_ind]\n\n\t\t\t\t\tself.expand(new_node, guide_node,step_size_dict)\n\t\t\t\t\twhile not self.collision_check(new_node):\n\n\t\t\t\t\t\tnew_node['parent'] = len(node_list) - 1\n\t\t\t\t\t\tnode_list.append(copy.deepcopy(new_node))\n\n\t\t\t\t\t\tnode_distance = weighted_norm(new_node, guide_node)\n\t\t\t\t\t\tprint(node_distance,minimal_distance,halt_step,'node distance')\n\t\t\t\t\t\tif weighted_norm(new_node, guide_node) < minimal_distance:\n\t\t\t\t\t\t\tminimal_distance = node_distance\n\t\t\t\t\t\t\tprint(minimal_distance,halt_step, 'min norm VS reached')\n\t\t\t\t\t\t\tconnect_node_start,connect_node_end=self.save_connect_nodes(iteration, node_list, guide_node)\n\n\t\t\t\t\t\tif weighted_norm(new_node, guide_node) < halt_step:\n\t\t\t\t\t\t\tprint('goal reached!')\n\t\t\t\t\t\t\tconnect_node_start,connect_node_end=self.save_connect_nodes(iteration, node_list, guide_node)\n\n\t\t\t\t\t\t\treturn True,connect_node_start,connect_node_end,node_list_start,node_list_end\n\t\t\t\t\t\tself.expand(new_node, guide_node,step_size_dict)\n\n\t\tprint('not reached... ')\n\t\treturn False,connect_node_start,connect_node_end,node_list_start,node_list_end\n\n\tdef express(self):\n\t\t\"\"\"\n\t\tFunction that will construct the random tree and when finished return the found path between two frames\n\t\t\"\"\"\n\t\tself.ready()\n\t\tself.goal,connect_node_start,connect_node_end,node_list_start,node_list_end = self.nodeadder()\n\n\t\tpath_start = [connect_node_start]\n\t\tpath_end = [connect_node_end]\n\n\t\tfor path,node_list in zip([path_start,path_end],[node_list_start,node_list_end]):\n\t\t\tlast_index = path[0]['parent']\n\t\t\twhile last_index is not None:\n\t\t\t\tnode = node_list[last_index]\n\t\t\t\tpath.append(node)\n\t\t\t\tlast_index = node['parent']\n\n\t\tpath_start.reverse()\n\t\tself.path = path_start + path_end\n\t\tself.write_refinement()\n\ndef Refinement(directory, path_num, frame_start, frame_end):\n\t\"\"\"\n\tCreates the output path, runs the RRT-algorithm and saves the resulting path .pdb\n\tfiles as a MDtraj file\n\t\n\tParameters\n\t----------\n\tdirectory : str\n\t\tdirectory from which the files are \n\tpath_num : TYPE\n\t    Description\n\tframe_start : int\n\n\tframe_end : int\n\t\"\"\"\n\n\tinit_path = os.getcwd()\n\tinput_path = os.path.join(os.getcwd(), 'refinement_input_files', directory)\n\toutput_path = os.path.join(os.getcwd(), 'refinement_output_files', directory,\n\t\t\t\t\t\t\t   'refinement' + '_' + str(frame_start).zfill(3) + '_' + str(frame_end).zfill(3) + '_' + str(time.time()))\n\n\tif os.path.exists(output_path):\n\t\tshutil.rmtree(output_path)\n\t\tos.makedirs(output_path)\n\telse:\n\t\tos.makedirs(output_path)\n\n\tframerange = range(frame_start, frame_end)\n\tlogfile = open(os.path.join(output_path, 'logfile' + '.txt'), 'w+')\n\tlog_dict_list = []\n\trefined_frame_num=1\n\tfor frame_num in framerange:\n\t\tstart_time = time.time()\n\t\trrt = RRT(input_path, output_path,path_num, frame_num)\n\t\trrt.express()\n\t\tend_time = time.time()\n\n\t\tlog_dict = {}\n\t\tlog_dict['1_frame_num'] = rrt.frame_num\n\t\tlog_dict['2_goal_reached'] = rrt.goal\n\t\tlog_dict['3_iterations'] = rrt.iteration_counter\n\t\tlog_dict['4_time'] = end_time - start_time\n\t\tlog_dict['5_clash_diff'] = rrt.clash_diff\n\t\tlog_dict['6_clashscore_iteration'] = [(node,refined_frame_num+i) for i,node in enumerate(rrt.path)]\n\t\tlog_dict['7_frame_vdw_volume'] = rrt.frame_vdw_volume\n\t\tlog_dict_list.append(log_dict)\n\t\trefined_frame_num+=len(rrt.path)\n\tlogfile.write(pp.pformat(log_dict_list))\n\n\tos.chdir(output_path)\n\tfile_list = []\n\ttrajectory_list = [output_file for output_file in os.listdir(\n\t\toutput_path) if 'trajectory' in output_file]\n\ttrajectory_list.sort(key=lambda f: int(filter(str.isdigit, f)))\n\n\tfor the_file in trajectory_list:\n\t\tfile_path = os.path.join(output_path, the_file)\n\t\tfile_list.append(file_path)\n\tmd_trajectory = mdtraj.load(file_list)\n\tmd_trajectory.save(os.path.join(output_path, 'refinement.pdb'))\n\n\tfor the_file in trajectory_list:\n\t\tfile_path = os.path.join(output_path, the_file)\n\t\ttry:\n\t\t\tif os.path.isfile(file_path):\n\t\t\t\tos.unlink(file_path)\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\tos.chdir(init_path)\n\tchimera.closeSession()\n\ndef parse_cli():\n\t\"\"\"\n\tCli input parser\n\t\"\"\"\n\tp = ArgumentParser()\n\tp.add_argument('directory', type=str,\n\t\t\t\t   help='directory containing the results from the Gpath inside refinement_test_input_files')\n\tp.add_argument('path_num', type=int,\n\t\t\t\t   help='path number of the .zip file in the directory')\n\tp.add_argument('frame_start', type=int,\n\t\t\t\t   help='frame number from which the interpolation has to be done')\n\tp.add_argument('frame_end', type=int,\n\t\t\t\t   help='frame number until which the interpolation has to be done')\n\treturn p.parse_args()\n\nif __name__ == '__main__':\n\n\targs = parse_cli()\n\tdirectory=args.directory\n\tframe_start=args.frame_start\n\tframe_end=args.frame_end\n\tpath_num=args.path_num\n\n\toutput_path=os.path.join(os.getcwd(),'examples','refinement_output_files',directory)\n\tRefinement(directory,path_num,frame_start,frame_end)\n", "meta": {"hexsha": "ef1f8efc641b7ffad64e61202e7713fa6e814fbf", "size": 34005, "ext": "py", "lang": "Python", "max_stars_repo_path": "refinement.py", "max_stars_repo_name": "insilichem/gpathfinder", "max_stars_repo_head_hexsha": "e6c7df14d473857acb007efbae3cc7b4fee1b330", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-03-22T20:21:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T07:50:25.000Z", "max_issues_repo_path": "refinement.py", "max_issues_repo_name": "insilichem/gpathfinder", "max_issues_repo_head_hexsha": "e6c7df14d473857acb007efbae3cc7b4fee1b330", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-04-09T10:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T04:37:27.000Z", "max_forks_repo_path": "refinement.py", "max_forks_repo_name": "insilichem/gpathfinder", "max_forks_repo_head_hexsha": "e6c7df14d473857acb007efbae3cc7b4fee1b330", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9186834463, "max_line_length": 153, "alphanum_fraction": 0.7223055433, "include": true, "reason": "import numpy", "num_tokens": 8953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.19900811535058138}}
{"text": "#!/usr/bin/env python\n\"\"\"\nVariational Bayes method to solve phylgoenetic HMM for histone modifications\n\nNeed to:\n* Preprocess\n** load each dataset\n** call significant sites for each dataset (vs. one control dataset)\n** save out resulting histogrammed data\n\n* Learn\n** Init parameters randomly\n** E step:  optimize each q_{ij} for fixed \\Theta\n** M step:  optimize \\Theta for fixed Q\n\n\nfor a complete hg19, we have:\n  T = 15,478,482\n  I = 9\n  K = 15\n  L = 9\n  \\Theta is:\n    e = K * 2**L\n    \\theta = K**2 * K\n    \\alpha = K * K\n    \\beta = K * K\n    \\gamma = K\n  X = I * T * L  * 1 byte for bool => 2050 MB RAM\n\n  for mf:\n  Q = I * T * K  * 4 bytes for float64  =>\n                15181614 * 9 * 15 * (4 bytes) / 1e6 = 8198 MB RAM\n  \\therefore should be okay for 12GB RAM\n\n  for poc:\n  \\Theta = T * K * K * 4 bytes  => 30 GB RAM\n  Q = I * T * K  * 4 bytes => 24 GB RAM\n  Q_pairs = I * T * K * K * 4 bytes => :(\n\n  Chromosome 1:\n    T = 1246254\n      =>  Q = .9 GB\n      =>  Q_pairs = 8.9 GB\n      =>  X = .1 GB\n\n\"\"\"\nimport argparse\nimport sys\nimport operator\nimport glob\nimport urllib\nimport os\nimport hashlib\nimport multiprocessing\nimport time\nimport cPickle as pickle\nimport copy\nimport re\nimport tarfile\nfrom cStringIO import StringIO\nimport time\nimport random\n\ntry:\n    import pysam\nexcept ImportError:\n    print 'pysam not installed.  Cannot convert data'\nimport scipy as sp\nfrom scipy.stats import poisson\nimport scipy.io\nimport scipy.signal\ntry:\n    import matplotlib\n    matplotlib.use('Agg', warn=False)\n    #matplotlib.rc('text', usetex=True)\n    #matplotlib.rc('ps', usedistiller='xpdf')\n    from matplotlib import pyplot\n    allow_plots = True\nexcept ImportError:\n    allow_plots = False\n    print 'matplotlib not installed.  Cannot plot!'\n\nsp.seterr(all='raise')\nsp.seterr(under='print')\n#sp.random.seed([5])\n\n\nfrom treehmm.static import valid_species, valid_marks, mark_avail, phylogeny, inference_types, float_type\n\nfrom treehmm import vb_mf\nfrom treehmm import vb_prodc\n#import loopy_bp\nfrom treehmm import loopy_bp\nfrom treehmm import clique_hmm\n#import concatenate_hmm\nfrom treehmm import vb_gmtkExact_continuous as vb_gmtkExact\nfrom treehmm import vb_independent\nfrom treehmm.plot import plot_params, plot_data, plot_Q, plot_energy, plot_energy_comparison\n\nfrom treehmm.do_parallel import do_parallel_inference\n\n\n\n\ndef main(argv=sys.argv[1:]):\n    \"\"\"run a variational EM algorithm\"\"\"\n    # parse arguments, then call convert_data or do_inference\n    parser = make_parser()\n    args = parser.parse_args(argv)\n    if not hasattr(args, 'mark_avail'):\n        args.mark_avail = mark_avail\n    elif isinstance(args.mark_avail, basestring):\n        args.mark_avail = sp.load(args.mark_avail)\n    if args.func == do_inference:\n        # allow patterns on the command line\n        global phylogeny\n        args.phylogeny = eval(args.phylogeny)\n        phylogeny = args.phylogeny\n\n        all_obs = []\n        for obs_pattern in args.observe_matrix:\n            obs_files = glob.glob(obs_pattern)\n            if len(obs_files) == 0:\n                parser.error('No files matched the pattern %s' % obs_pattern)\n            all_obs.extend(obs_files)\n        args.observe_matrix = all_obs\n\n        if args.approx == 'gmtk':\n            args.subtask = False\n            obs_mat = args.observe_matrix\n            args.observe_matrix = args.observe_matrix[0]\n            init_args_for_inference(args)\n            args.observe_matrix = obs_mat\n            del args.func\n            vb_gmtkExact.mark_avail = args.mark_avail\n            vb_gmtkExact.run_gmtk_lineagehmm(args)\n            return\n\n        if len(args.observe_matrix) > 1:\n            print 'parallel inference on %s jobs' % len(args.observe_matrix)\n            args.func = do_parallel_inference\n        else:\n            args.subtask = False\n            args.observe_matrix = args.observe_matrix[0]\n            args.observe = os.path.split(args.observe_matrix)[1]\n            args.func = do_inference\n        if args.range_k is not None:\n            out_template = args.out_dir + \"_rangeK\"\n            for args.K in eval(args.range_k):\n                print 'trying K=', args.K\n                args.out_dir = out_template\n                args.func(args)\n            return\n\n    args.func(args)  # do inference, downloading, or data conversion\n\ndef do_inference(args):\n    \"\"\"Perform the type of inference specified in args\"\"\"\n    # set up\n    if args.quiet_mode:\n        sys.stdout = open('log_%s.log' , 'a')\n    init_args_for_inference(args)\n    print 'done making args'\n    args.out_dir = args.out_dir.format(timestamp=time.strftime('%x_%X').replace('/','-'), **args.__dict__)\n\n    try:\n        print 'making', args.out_dir\n        os.makedirs(args.out_dir)\n    except OSError:\n        pass\n\n    if not args.subtask:\n        args.iteration = '0_initial'\n        plot_params(args)\n        if args.plot_iter >= 2:\n            plot_data(args)\n\n    for i in xrange(1, args.max_iterations+1):\n        if not args.subtask:\n            args.iteration = i\n        print 'iteration', i\n\n        # run a few times rather than checking free energy\n        for j in xrange(1, args.max_E_iter+1 if args.approx != 'clique' else 2):\n            args.update_q_func(args)\n            if args.approx !='loopy':\n                f = args.free_energy_func(args)\n                print 'free energy after %s E steps' % j, f\n                try:\n                    print abs(args.last_free_energy - f) / args.last_free_energy\n                    if abs(abs(args.last_free_energy - f) / args.last_free_energy) < args.epsilon_e:\n                        args.last_free_energy = f\n                        break\n                    args.last_free_energy = f\n                except:  # no previous free energy\n                    args.last_free_energy = f\n            else:\n                print 'loopy %s E steps' %j\n                if loopy_bp.bp_check_convergence(args):\n                    args.last_free_energy = f = abs(args.free_energy_func(args))\n                    break\n        print '# saving Q distribution'\n        if args.continuous_observations:\n            for k in range(args.K):\n                print 'means[%s,:] = ' % k, args.means[k,:]\n                print 'stdev[%s,:] = ' % k, sp.sqrt(args.variances[k,:])\n        if args.save_Q >= 2:\n            for p in args.Q_to_save:\n                sp.save(os.path.join(args.out_dir,\n                            args.out_params.format(param=p, **args.__dict__)),\n                        args.__dict__[p])\n\n\n        if args.subtask:\n            # save the weights without renormalizing\n            print 'saving weights for parameters'\n            args.update_param_func(args, renormalize=False)\n            #plot_Q(args)\n            args.free_energy.append(args.last_free_energy)\n            for p in args.params_to_save:\n                sp.save(os.path.join(args.out_dir, args.out_params.format(param=p, **args.__dict__)),\n                    args.__dict__[p])\n            break\n        else:\n            # optimize parameters with new Q\n            args.update_param_func(args)\n            f = args.free_energy_func(args)\n            try:\n                if args.approx != 'clique':\n                    print abs(args.last_free_energy - f) / args.last_free_energy\n                    if abs(abs(args.last_free_energy - f) / args.last_free_energy) < args.epsilon:\n                        args.last_free_energy = f\n                        break\n                    args.last_free_energy = f\n            except:  # no previous free energy\n                args.last_free_energy = f\n            #args.last_free_energy = args.free_energy_func(args)\n            args.free_energy.append(args.last_free_energy)\n            print 'free energy after M-step', args.free_energy[-1]\n            # save current parameter state\n            for p in args.params_to_save:\n                sp.save(os.path.join(args.out_dir,\n                            args.out_params.format(param=p, **args.__dict__)),\n                        args.__dict__[p])\n\n            if args.plot_iter != 0 and i % args.plot_iter == 0:\n                plot_params(args)\n                plot_energy(args)\n                if args.plot_iter >= 2:\n                    plot_Q(args)\n            #import ipdb; ipdb.set_trace()\n            if args.compare_inf is not None:\n                args.log_obs_mat = sp.zeros((args.I,args.T,args.K), dtype=float_type)\n                vb_mf.make_log_obs_matrix(args)\n                if 'mf' in args.compare_inf:\n                    tmpargs = copy.deepcopy(args)\n                    tmpargs.Q = vb_mf.mf_random_q(args.I,args.T,args.K)\n                    print 'comparing '\n                    for j in xrange(1, args.max_E_iter+1):\n                        vb_mf.mf_update_q(tmpargs)\n                        if vb_mf.mf_check_convergence(tmpargs):\n                            break\n                    print 'mf convergence after %s iterations' % j\n                    e = vb_mf.mf_free_energy(tmpargs)\n                    args.cmp_energy['mf'].append(e)\n                if 'poc' in args.compare_inf:\n                    tmpargs = copy.deepcopy(args)\n                    if args.approx != 'poc':\n                        tmpargs.Q, tmpargs.Q_pairs = vb_prodc.prodc_initialize_qs(args.theta, args.alpha, args.beta,\n                                            args.gamma, args.emit_probs, args.X, args.log_obs_mat)\n                    for j in xrange(1, args.max_E_iter+1):\n                        vb_prodc.prodc_update_q(tmpargs)\n                        if vb_mf.mf_check_convergence(tmpargs):\n                            break\n                    print 'poc convergence after %s iterations' % j\n                    e = vb_prodc.prodc_free_energy(tmpargs)\n                    args.cmp_energy['poc'].append(e)\n                    #sp.io.savemat(os.path.join(args.out_dir, 'Artfdata_poc_inferred_params_K{K}_{T}.mat'.format(K=args.K, T=args.max_bins)), dict(alpha = args.alpha, theta=args.theta, beta=args.beta, gamma=args.gamma, emit_probs=args.emit_probs))\n                if 'pot' in args.compare_inf:\n                    #del args.cmp_energy['pot']\n                    pass\n                if 'concat' in args.compare_inf:\n                    #del args.cmp_energy['concat']\n                    pass\n                if 'clique' in args.compare_inf:\n                    tmpargs = copy.deepcopy(args)\n                    if args.approx != 'clique':\n                        clique_hmm.clique_init_args(tmpargs)\n                    for j in xrange(1):\n                        clique_hmm.clique_update_q(tmpargs)\n                    e = clique_hmm.clique_likelihood(tmpargs)\n                    args.cmp_energy['clique'].append(-e)\n                if 'loopy' in args.compare_inf:\n                    tmpargs = copy.deepcopy(args)\n                    if args.approx != 'loopy':\n                        tmpargs.lmds, tmpargs.pis = loopy_bp.bp_initialize_msg(args.I, args.T, args.K, args.vert_children)\n                    for j in xrange(1, args.max_E_iter+1):\n                        loopy_bp.bp_update_msg_new(tmpargs)\n                        if loopy_bp.bp_check_convergence(tmpargs):\n                            break\n                    print 'loopy convergence after %s iterations' % j\n                    #e = loopy_bp.bp_bethe_free_energy(tmpargs)\n                    e = loopy_bp.bp_mf_free_energy(tmpargs)\n                    args.cmp_energy['loopy'].append(e)\n                if args.plot_iter != 0:\n                    plot_energy_comparison(args)\n\n    # save the final parameters and free energy to disk\n    print 'done iteration'\n    if args.save_Q >= 1:\n        for p in args.Q_to_save:\n            sp.save(os.path.join(args.out_dir,\n                        args.out_params.format(param=p, **args.__dict__)),\n                    args.__dict__[p])\n    for p in args.params_to_save:\n        sp.save(os.path.join(args.out_dir, args.out_params.format(param=p, **args.__dict__)),\n                args.__dict__[p])\n\n    #pickle.dump(args, os.path.join(args.out_dir, args.out_params.format(param='args', **args.__dict__)))\n    print 'done savin'\n    if not args.subtask and args.plot_iter != 0:\n        plot_energy(args)\n        plot_params(args)\n        plot_Q(args)\n        #scipy.io.savemat('poc_inferred_params_K{K}_{T}.mat'.format(K=args.K, T=args.max_bins), dict(alpha = args.alpha, theta=args.theta, beta=args.beta, gamma=args.gamma, emit_probs=args.emit_probs))\n\n\ndef init_args_for_inference(args):\n    \"\"\"Initialize args with inference variables according to learning method\"\"\"\n    # read in the datafiles to X array\n    print '# loading observations'\n    X = sp.load(args.observe_matrix)\n    if args.max_bins is not None:\n        X = X[:, :args.max_bins, :]\n    if args.max_species is not None:\n        X = X[:args.max_species, :, :]\n    args.X = X\n    args.I, args.T, args.L = X.shape\n    if args.X.dtype != scipy.int8:\n        args.continuous_observations = True\n        print 'Inference for continuous observations'\n        args.X = X.astype(float_type)\n        #args.means = sp.rand(args.K, args.L)\n        #args.variances = sp.rand(args.K, args.L)\n        args.means, args.variances = initialize_mean_variance(args)\n    else:\n        args.continuous_observations = False\n        print 'Inference for discrete observations'\n    match = re.search(r'\\.i(\\d+)\\.', args.observe_matrix)\n    args.real_species_i = int(match.groups()[0]) if match and args.I == 1 else None\n    args.free_energy = []\n\n    make_tree(args)\n    args.Q_to_save = ['Q']\n    #if args.approx == 'poc':\n    #    args.Q_to_save += ['Q_pairs']\n    #elif args.approx == 'clique':\n    #    args.Q_to_save += ['clq_Q', 'clq_Q_pairs']\n\n    args.params_to_save = ['free_energy', 'alpha', 'gamma', 'last_free_energy']\n    if True: #args.approx not in ['clique', 'concat']:\n        args.params_to_save += ['theta', 'beta']\n    if args.continuous_observations:\n        args.params_to_save += ['means', 'variances']\n    else:\n        args.params_to_save += ['emit_probs', 'emit_sum']\n\n    if args.compare_inf is not None:\n        if 'all' in args.compare_inf:\n            args.compare_inf = inference_types\n        args.cmp_energy = dict((inf, []) for inf in args.compare_inf if inf not in ['pot', 'concat'])\n        args.params_to_save += ['cmp_energy']\n\n    if args.warm_start:  # need to load params\n        print '# loading previous params for warm start from %s' % args.warm_start\n        tmpargs = copy.deepcopy(args)\n        tmpargs.out_dir = args.warm_start\n        #tmpargs.observe = 'all.npy'\n        args.free_energy, args.theta, args.alpha, args.beta, args.gamma, args.emit_probs, args.emit_sum = load_params(tmpargs)\n        try:\n            args.free_energy = list(args.free_energy)\n        except TypeError: # no previous free energy\n            args.free_energy = []\n        print 'done'\n    elif args.subtask:  # params in args already\n        print '# using previous params from parallel driver'\n    else:\n        print '# generating random parameters'\n        (args.theta, args.alpha, args.beta, args.gamma, args.emit_probs) = \\\n                                                    random_params(args.I, args.K, args.L, args.separate_theta)\n        if args.continuous_observations:\n            del args.emit_probs\n\n\n    if args.approx == 'mf':  # mean-field approximation\n        if not args.subtask or args.iteration == 0:\n            args.Q = vb_mf.mf_random_q(args.I,args.T,args.K)\n        #else:\n        #    q_path = os.path.join(args.out_dir, args.out_params.format(param='Q', **args.__dict__))\n        #    print 'loading previous Q from %s' % q_path\n        #    args.Q = sp.load(q_path)\n        args.log_obs_mat = sp.zeros((args.I,args.T,args.K), dtype=float_type)\n        vb_mf.make_log_obs_matrix(args)\n\n        args.update_q_func = vb_mf.mf_update_q\n        args.update_param_func = vb_mf.mf_update_params\n        args.free_energy_func = vb_mf.mf_free_energy\n        args.converged_func = vb_mf.mf_check_convergence\n    elif args.approx == 'poc':  # product-of-chains approximation\n        if not args.separate_theta:\n            import vb_prodc\n        else:\n            import vb_prodc_sepTheta as vb_prodc\n        args.log_obs_mat = sp.zeros((args.I,args.T,args.K), dtype=float_type)\n        if args.continuous_observations:\n            vb_mf.make_log_obs_matrix_gaussian(args)\n        else:\n            vb_mf.make_log_obs_matrix(args)\n\n        if not args.subtask or args.iteration == 0:\n            print '# generating Qs'\n            args.Q, args.Q_pairs = vb_prodc.prodc_initialize_qs(args.theta, args.alpha, args.beta,\n                                            args.gamma, args.X, args.log_obs_mat)\n        #else:\n        #    q_path = os.path.join(args.out_dir, args.out_params.format(param='Q', **args.__dict__))\n        #    print 'loading previous Q from %s' % q_path\n        #    args.Q = sp.load(q_path)\n        #    args.Q_pairs = sp.load(os.path.join(args.out_dir, args.out_params.format(param='Q_pairs', **args.__dict__)))\n\n        args.update_q_func = vb_prodc.prodc_update_q\n        args.update_param_func = vb_prodc.prodc_update_params\n        args.free_energy_func = vb_prodc.prodc_free_energy\n        args.converged_func = vb_mf.mf_check_convergence\n    elif args.approx == 'indep':  # completely independent chains\n        args.log_obs_mat = sp.zeros((args.I, args.T, args.K), dtype=float_type)\n        if args.continuous_observations:\n            vb_mf.make_log_obs_matrix_gaussian(args)\n        else:\n            vb_mf.make_log_obs_matrix(args)\n\n        if not args.subtask or args.iteration == 0:\n            print '# generating Qs'\n            args.Q = sp.zeros((args.I, args.T, args.K), dtype=float_type)\n            args.Q_pairs = sp.zeros((args.I, args.T, args.K, args.K), dtype=float_type)\n            vb_independent.independent_update_qs(args)\n        #else:\n        #    q_path = os.path.join(args.out_dir, args.out_params.format(param='Q', **args.__dict__))\n        #    print 'loading previous Q from %s' % q_path\n        #    args.Q = sp.load(q_path)\n        #    args.Q_pairs = sp.load(os.path.join(args.out_dir, args.out_params.format(param='Q_pairs', **args.__dict__)))\n\n        args.update_q_func = vb_independent.independent_update_qs\n        args.update_param_func = vb_independent.independent_update_params\n        args.free_energy_func = vb_independent.independent_free_energy\n        args.converged_func = vb_mf.mf_check_convergence\n    elif args.approx == 'pot':  # product-of-trees approximation\n        raise NotImplementedError(\"Product of Trees is not implemented yet!\")\n    elif args.approx == 'clique':\n        if args.separate_theta:\n           raise RuntimeError('separate_theta not implemented yet for clique')\n        print 'making cliqued Q'\n        args.Q = sp.zeros((args.I, args.T, args.K), dtype=float_type)\n        clique_hmm.clique_init_args(args)\n        args.update_q_func = clique_hmm.clique_update_q\n        args.update_param_func = clique_hmm.clique_update_params\n        args.free_energy_func = clique_hmm.clique_likelihood\n        args.converged_func = vb_mf.mf_check_convergence\n    elif args.approx == 'concat':\n        raise NotImplementedError(\"Concatenated HMM is not implemented yet!\")\n    elif args.approx == 'loopy':\n        if args.separate_theta:\n           raise RuntimeError('separate_theta not implemented yet for clique')\n        if not args.subtask or args.iteration == 0:\n            args.Q = vb_mf.mf_random_q(args.I, args.T, args.K)\n        #else:\n        #    q_path = os.path.join(args.out_dir, args.out_params.format(param='Q', **args.__dict__))\n        #    print 'loading previous Q from %s' % q_path\n        #    args.Q = sp.load(q_path)\n        args.lmds, args.pis = loopy_bp.bp_initialize_msg(args)\n        args.log_obs_mat = sp.zeros((args.I,args.T,args.K), dtype=float_type)\n        vb_mf.make_log_obs_matrix(args)\n\n        args.update_q_func = loopy_bp.bp_update_msg_new\n        args.update_param_func = loopy_bp.bp_update_params_new\n        #args.free_energy_func = loopy_bp.bp_bethe_free_energy\n        args.free_energy_func = loopy_bp.bp_mf_free_energy\n        args.converged_func = loopy_bp.bp_check_convergence\n    elif args.approx == 'gmtk':\n        pass\n    else:\n        raise RuntimeError('%s not recognized as valid inference method!' % args.approx)\n\ndef distance(x1, x2):\n    return scipy.sqrt((x1 - x2) * (x1 - x2)).sum()\n\ndef initialize_mean_variance(args):\n    \"\"\"Initialize the current mean and variance values semi-intelligently.\n\n    Inspired by the kmeans++ algorithm: iteratively choose new centers from the data\n    by weighted sampling, favoring points that are distant from those already chosen\n    \"\"\"\n    X = args.X.reshape(args.X.shape[0] * args.X.shape[1], args.X.shape[2])\n\n    # kmeans++ inspired choice\n    centers = [random.choice(X)]\n    min_dists = scipy.array([distance(centers[-1], x) for x in X])\n    for l in range(1, args.K):\n        weights = min_dists * min_dists\n        new_center = weighted_sample(zip(weights, X), 1).next()\n        centers.append(new_center)\n\n        min_dists = scipy.fmin(min_dists, scipy.array([distance(centers[-1], x) for x in X]))\n\n    means = scipy.array(centers)\n\n    # for the variance, get the variance of the data in this cluster\n    variances = []\n    for c in centers:\n        idxs = tuple(i for i, (x, m) in enumerate(zip(X, min_dists)) if distance(c, x) == m)\n        v = scipy.var(X[idxs, :], axis=0)\n        variances.append(v)\n    variances = scipy.array(variances) + args.pseudocount\n\n    #import pdb; pdb.set_trace()\n    #for k in range(args.K):\n    #    print sp.sqrt(variances[k,:])\n    variances[variances < .1] = .1\n\n    return means, variances\n\n\ndef weighted_sample(items, n):\n    total = float(sum(w for w, v in items))\n    i = 0\n    w, v = items[0]\n    while n:\n        x = total * (1 - random.random() ** (1.0 / n))\n        total -= x\n        while x > w:\n            x -= w\n            i += 1\n            w, v = items[i]\n        w -= x\n        yield v\n        n -= 1\n\n\ndef make_parser():\n    \"\"\"Make a parser for variational inference\"\"\"\n    parser = argparse.ArgumentParser()\n    tasks_parser = parser.add_subparsers()\n\n    # parameters for converting datasets from BAM to observation matrix\n    convert_parser = tasks_parser.add_parser('convert', help='Convert BAM reads'\n                                             ' into a matrix of observations')\n    convert_parser.add_argument('--download_first', action='store_true',\n                                help='Download the raw sequence data from UCSC,'\n                                ' then convert it.')\n    convert_parser.add_argument('--base_url', default='http://hgdownload.cse.ucsc.edu/goldenPath/hg19/encodeDCC/wgEncodeBroadHistone/%s',\n                                help='When downloading, string-format the template into this url.')\n    convert_parser.add_argument('--species', nargs='+', default=valid_species,\n                                help='The set of species with observations. By '\n                                'default, use all species: %(default)s')\n    convert_parser.add_argument('--marks', nargs='+', default=valid_marks,\n                                help='The set of marks with observations. By '\n                                'default, use all histone marks: %(default)s')\n    convert_parser.add_argument('--windowsize', type=int, default=200,\n                        help='histogram bin size used in conversion')\n    convert_parser.add_argument('--chromosomes', nargs='+', default='all',\n                                help='which chromosomes to convert. By default,'\n                                ' convert all autosomes')\n    convert_parser.add_argument('--min_reads', type=float, default=.5,\n                              help='The minimum number of reads for a region to be included. default: %(default)s')\n    convert_parser.add_argument('--min_size', type=int, default=25,\n                              help='The minimum length (in bins) to include a chunk. default: %(default)s')\n    convert_parser.add_argument('--max_pvalue', type=float, default=1e-4,\n                        help='p-value threshold to consider the read count'\n                        ' significant, using a local poisson rate defined by'\n                        ' the control data')\n    convert_parser.add_argument('--outfile', default='observations.{chrom}.npy',\n                                help='Where to save the binarized reads')\n    #convert_parser.add_argument('--bam_template', help='bam file template.',\n    #                default='wgEncodeBroadHistone{species}{mark}StdAlnRep*.bam')\n    convert_parser.add_argument('--bam_template', help='bam file template. default: %(default)s',\n                default='wgEncode*{species}{mark}StdAlnRep{repnum}.bam')\n    convert_parser.set_defaults(func=convert_data)\n\n    # # to trim off telomeric regions\n    # trim_parser = tasks_parser.add_parser('trim', help='trim off regions without'\n    #                                       'any observations in them')\n    # trim_parser.add_argument('observe_matrix', nargs='+',\n    #                     help='Files to be trimmed (converted from bam'\n    #                     ' using \"%(prog)s convert\" command).')\n    # trim_parser.set_defaults(func=trim_data)\n\n    # to split a converted dataset into pieces\n    split_parser = tasks_parser.add_parser('split', help='split observations '\n                            'into smaller pieces, retaining only regions with '\n                            'a smoothed minimum read count.')\n    split_parser.add_argument('observe_matrix', nargs='+',\n                        help='Files containing observed data (converted from bam'\n                        ' using \"%(prog)s convert\" command). If multiple files '\n                        'are specified, each is treated as its own chain but '\n                        'the parameters are shared across all chains')\n    split_parser.add_argument('start_positions', help='start_positions.pkl file generated during `convert` step.')\n    #split_parser.add_argument('--chunksize', type=int, default=100000,\n    #                          help='the number of bins per chunk. default: %(default)s')\n    split_parser.add_argument('--min_reads', type=float, default=.5,\n                              help='The minimum number of reads for a region to be included. default: %(default)s')\n    split_parser.add_argument('--gauss_window_size', type=int, default=200,\n                              help='The size of the gaussian smoothing window. default: %(default)s')\n    split_parser.add_argument('--min_size', type=int, default=25,\n                              help='The minimum length (in bins) to include a chunk. default: %(default)s')\n    split_parser.set_defaults(func=split_data)\n\n    # parameters for learning and inference with converted observations\n    infer_parser = tasks_parser.add_parser('infer')\n    infer_parser.add_argument('K', type=int, help='The number of hidden states'\n                              ' to infer')\n    infer_parser.add_argument('observe_matrix', nargs='+',\n                        help='Files containing observed data (converted from bam'\n                        ' using \"%(prog)s convert\" command). If multiple files '\n                        'are specified, each is treated as its own chain but '\n                        'the parameters are shared across all chains')\n    infer_parser.add_argument('--approx', choices=inference_types,\n                              default='mf',\n                              help='Which approximation to make in inference')\n    infer_parser.add_argument('--out_params', default='{approx}_{param}_{observe}',\n                           help='Where to save final parameters')\n    infer_parser.add_argument('--epsilon', type=float, default=1e-4,\n                              help='Convergence criteria: change in Free energy'\n                              ' during M step must be < epsilon')\n    infer_parser.add_argument('--epsilon_e', type=float, default=1e-3,\n                              help='Convergence criteria: change in Free energy'\n                              ' during E step must be < epsilon')\n    infer_parser.add_argument('--max_iterations', type=int, default=50,\n                              help='Maximum number of EM steps before stopping')\n    infer_parser.add_argument('--max_E_iter', type=int, default=10,\n                              help='Maximum number of E steps per M step')\n    infer_parser.add_argument('--max_bins', default=None, type=int,\n                                help='Restrict the total number of bins (T)')\n    infer_parser.add_argument('--max_species', default=None, type=int,\n                                help='Restrict the total number of species (I)')\n    infer_parser.add_argument('--pseudocount', type=float_type, default=1e-6,\n                              help='pseudocount to add to each parameter matrix')\n    infer_parser.add_argument('--plot_iter', type=int, default=1,\n                              help='draw a plot per *plot_iter* iterations.'\n                              '0 => plot only at the end. Default is %(default)s')\n    infer_parser.add_argument('--out_dir', type=str, default='{run_name}_out/{approx}/I{I}_K{K}_T{T}_{timestamp}',\n                              help='Output parameters and plots in this directory'\n                              ' (default: %(default)s')\n    infer_parser.add_argument('--run_name', type=str, default='infer',\n                              help='name of current run type (default: %(default)s')\n    infer_parser.add_argument('--num_processes', type=int, default=None,\n                              help='Maximum number of processes to use '\n                              'simultaneously (default: all)')\n    infer_parser.add_argument('--warm_start', type=str, default=None,\n                              help=\"Resume iterations using parameters and Q's \"\n                              \"from a previous run. Q's that are not found are \"\n                              \"regenerated\")\n    infer_parser.add_argument('--compare_inf', nargs='+', type=str, default=None, choices=inference_types + ['all'],\n                              help=\"While learning using --approx method, \"\n                              \"compare the inferred hidden states and energies \"\n                              \"from these inference methods.\")\n    infer_parser.add_argument('--range_k', type=str, default=None,\n                              help=\"perform inference over a range of K values. Argument is passed as range(*arg*)\")\n    infer_parser.add_argument('--save_Q', type=int, choices=[0,1,2,3], default=1,\n                              help=\"Whether to save the inferred marginals for hidden variables. 0 => no saving, 1 => save at end, 2 => save at each iteration. 3 => for parallel jobs, reconstruct the chromsomal Q distribution at each iteration. Default: %(default)s\")\n    infer_parser.add_argument('--quiet_mode', action='store_true', help=\"Turn off printing for this run\")\n    infer_parser.add_argument('--run_local', action='store_true', help=\"Force parallel jobs to run on the local computer, even when SGE is available\")\n    infer_parser.add_argument('--separate_theta', action='store_true', help='use a separate theta matrix for each node of the tree (only works for GMTK)')\n    infer_parser.add_argument('--mark_avail', help='npy matrix of available marks',\n                                default=mark_avail)\n    infer_parser.add_argument('--phylogeny', help='the phylogeny connecting each species, as a python dictionary with children for keys and parents for values. Note: this does not have to be a singly-rooted or even a bifurcating phylogeny!  You may specify multiple trees, chains, stars, etc, but should not have loops in the phylogeny.',\n                                default=str(phylogeny))\n    infer_parser.add_argument('--chunksize', help='The number of chunks (for convert+split data) or chromosomes (for convert only) to submit to each runner.  When running on SGE, you should set this number relatively high (in 100s?) since each job has a very slow startup time. When running locally, this is the number of chunks each subprocess will handle at a time.',\n                                default=1)\n    infer_parser.set_defaults(func=do_inference)\n\n\n    bed_parser = tasks_parser.add_parser('q_to_bed')\n    bed_parser.add_argument('q_root_dir', help='Root directory for the Q outputs to convert. '\n                            'Should look something like: infer_out/mf/<timestamp>/')\n    bed_parser.add_argument('start_positions', help='the pickled offsets generated by `tree-hmm convert` or `tree-hmm split`.',)\n    bed_parser.add_argument('--bed_template', help='template for bed output files. Default: %(default)s',\n                            default='treehmm_states.{species}.state{state}.bed')\n    bed_parser.add_argument('--save_probs', action='store_true', help='Instead of saving the most likely state for each bin, record the probability of being in that state at each position. NOTE: this will greatly increase the BED file size!')\n    bed_parser.set_defaults(func=q_to_bed)\n    return parser\n\n\ndef q_to_bed(args):\n    attrs = pickle.load(open(args.start_positions))\n    windowsize = attrs['windowsize']\n    start_positions = attrs['start_positions']\n    valid_species = attrs['valid_species']\n    valid_marks = attrs['valid_marks']\n    \n    outfiles = {}\n    for f in glob.glob(os.path.join(args.q_root_dir, '*_Q_*.npy')):\n        Q = scipy.load(f)\n        if not args.save_probs:\n            best_states = Q.argmax(axis=2)\n        obs = f.split('_Q_')[1]\n        I, T, K = Q.shape\n        chrom, bin_offset = start_positions[obs]\n        for i in range(I):\n            for t in range(T):\n                if args.save_probs:\n                    for k in range(K):\n                        bedline = '\\t'.join([chrom, str((bin_offset + t) * windowsize),\n                                             str((bin_offset + t + 1) * windowsize),\n                                             '{species}.state{k}'.format(species=valid_species[i], k=k), \n                                             str(Q[i,t,k]), '+']) + '\\n'\n                        if (i,k) not in outfiles:\n                            outfiles[(i,k)] = open(args.bed_template.format(species=valid_species[i], state=k), 'w')\n                        outfiles[(i,k)].write(bedline)\n                else:\n                    k = best_states[i,t]\n                    bedline = '\\t'.join([chrom, str((bin_offset + t) * windowsize),\n                                         str((bin_offset + t + 1) * windowsize),\n                                         '{species}.state{k}'.format(species=valid_species[i], k=k), \n                                         str(Q[i,t,k]), '+']) + '\\n'\n                    if (i,k) not in outfiles:\n                        outfiles[(i,k)] = open(args.bed_template.format(species=valid_species[i], state=k), 'w')\n                    outfiles[(i,k)].write(bedline)\n\n\ndef load_params(args):\n    #print args.out_params\n    #print args.__dict__.keys()\n    #print 'loading from', os.path.join(args.out_dir, args.out_params.format(param='last_free_energy', **args.__dict__))\n    free_energy = sp.load(os.path.join(args.out_dir, args.out_params.format(param='free_energy', **args.__dict__)))\n\n    #print 'loading from', os.path.join(args.out_dir, args.out_params.format(param='theta', **args.__dict__))\n    theta = sp.load(os.path.join(args.out_dir, args.out_params.format(param='theta', **args.__dict__)))\n    if len(theta.shape)==3 and args.separate_theta:\n        tmp = sp.zeros((args.I-1, args.K, args.K, args.K), dtype=float_type)\n        for i in range(args.I-1):\n            tmp[i,:,:,:] = theta\n        theta = tmp\n    #print 'loading from', os.path.join(args.out_dir, args.out_params.format(param='alpha', **args.__dict__))\n    alpha = sp.load(os.path.join(args.out_dir, args.out_params.format(param='alpha', **args.__dict__)))\n\n    #print 'loading from', os.path.join(args.out_dir, args.out_params.format(param='beta', **args.__dict__))\n    beta = sp.load(os.path.join(args.out_dir, args.out_params.format(param='beta', **args.__dict__)))\n\n    #print 'loading from', os.path.join(args.out_dir, args.out_params.format(param='gamma', **args.__dict__))\n    gamma = sp.load(os.path.join(args.out_dir, args.out_params.format(param='gamma', **args.__dict__)))\n\n    #print 'loading from', os.path.join(args.out_dir, args.out_params.format(param='emit_probs', **args.__dict__))\n    emit_probs = sp.load(os.path.join(args.out_dir, args.out_params.format(param='emit_probs', **args.__dict__)))\n\n    #print 'loading from', os.path.join(args.out_dir, args.out_params.format(param='emit_sum', **args.__dict__))\n    emit_sum = sp.load(os.path.join(args.out_dir, args.out_params.format(param='emit_sum', **args.__dict__)))\n\n    return free_energy, theta, alpha, beta, gamma, emit_probs, emit_sum\n\n\n\ndef make_tree(args):\n    \"\"\"build a tree from the vertical parents specified in args\"\"\"\n    I = args.I\n    # define the tree structure\n    #tree_by_parents = {0:sp.inf, 1:0, 2:0}  # 3 species, 2 with one parent\n    #tree_by_parents = {0:sp.inf, 1:0}  # 3 species, 2 with one parent\n    #tree_by_parents = dict((args.species.index(k), args.species.index(v)) for k, v in phylogeny.items())\n    tree_by_parents = dict((valid_species.index(k), valid_species.index(v)) \n                            for k, v in args.phylogeny.items() if \n                                valid_species.index(k) in xrange(I) and \n                                valid_species.index(v) in xrange(I))\n    tree_by_parents[0] = sp.inf #'Null'\n    print tree_by_parents.keys()\n    # [inf, parent(1), parent(2), ...]\n    global vert_parent\n    #I = max(tree_by_parents) + 1\n\n    vert_parent = sp.array([tree_by_parents[c] if c > 0 else I for c in\n                                    xrange(I)], dtype=sp.int8)  # error if 0's parent is accessed\n    args.vert_parent = vert_parent\n\n    print 'vert_parent', vert_parent\n#    args.vert_parent = tree_by_parents\n    # {inf:0, 0:[1,2], 1:[children(1)], ...}\n    global vert_children\n    vert_children = dict((pa, []) for pa in\n                            tree_by_parents.keys())# + tree_by_parents.values())\n    for pa in tree_by_parents.values():\n        for ch in tree_by_parents.keys():\n            if tree_by_parents[ch] == pa:\n                if pa not in vert_children:\n                    vert_children[pa] = []\n                if ch not in vert_children[pa]:\n                    vert_children[pa].append(ch)\n    del vert_children[sp.inf]\n    for pa in vert_children:\n        vert_children[pa] = sp.array(vert_children[pa], dtype=sp.int32)\n    args.vert_children = vert_children\n\n#    vert_children = sp.ones(I,  dtype = 'object')\n#    for pa in range(I):\n#        vert_children[pa] = []\n#        for child, parent in tree_by_parents.items():\n#            if pa == parent:\n#                vert_children[pa].append(child)\n#    print vert_children\n#    args.vert_children = vert_children\n\ndef random_params(I, K, L, separate_theta):\n    \"\"\"Create and normalize random parameters for inference\"\"\"\n    #sp.random.seed([5])\n    if separate_theta:\n        theta = sp.rand(I-1, K, K, K).astype(float_type)\n    else:\n        theta = sp.rand(K, K, K).astype(float_type)\n    alpha = sp.rand(K, K).astype(float_type)\n    beta = sp.rand(K, K).astype(float_type)\n    gamma = sp.rand(K).astype(float_type)\n    emit_probs = sp.rand(K, L).astype(float_type)\n    vb_mf.normalize_trans(theta, alpha, beta, gamma)\n    return theta, alpha, beta, gamma, emit_probs\n\n# def trim_data(args):\n#     \"\"\"Trim regions without any observations from the start and end of the\n#     obervation matrices\n#     \"\"\"\n#     for f in args.observe_matrix:\n#         print '# trimming ', f, 'start is ',\n#         X = sp.load(f).astype(sp.int8)\n#         S = X.cumsum(axis=0).cumsum(axis=2)  # any species has any observation\n#         for start_t in xrange(X.shape[1]):\n#             if S[-1, start_t, -1] > 0:\n#                 break\n#         for end_t in xrange(X.shape[1] - 1, -1, -1):\n#             if S[-1, end_t, -1] > 0:\n#                 break\n#         tmpX = X[:, start_t:end_t, :]\n#         print start_t\n#         sp.save(os.path.splitext(f)[0] + '.trimmed', tmpX)\n\ndef split_data(args):\n    \"\"\"Split the given observation matrices into smaller chunks\"\"\"\n    sizes = []\n    total_size = 0\n    covered_size = 0\n    attrs = pickle.load(open(args.start_positions))\n    valid_species = attrs['valid_species']\n    valid_marks = attrs['valid_marks']\n    windowsize = attrs['windowsize']\n    old_starts = attrs['start_positions']\n    start_positions = {}\n    for f in args.observe_matrix:\n        print '# splitting ', f\n        chrom = old_starts[os.path.split(f)[1]][0]\n\n        X = sp.load(f).astype(sp.int8)\n        total_size += X.shape[1]\n        #start_ts = xrange(0, X.shape[1], args.chunksize)\n        #end_ts = xrange(args.chunksize, X.shape[1] + args.chunksize, args.chunksize)\n\n        density = X.sum(axis=0).sum(axis=1)  # sumation over I, then L\n        #from ipdb import set_trace; set_trace()\n        gk = _gauss_kernel(args.gauss_window_size)\n        smoothed_density = scipy.signal.convolve(density, gk, mode='same')\n        regions_to_keep = smoothed_density >= args.min_reads\n\n        # find the regions where a transition is made from no reads to reads, and reads to no reads\n        start_ts = sp.where(sp.diff(regions_to_keep.astype(sp.int8)) > 0)[0]\n        end_ts = sp.where(sp.diff(regions_to_keep.astype(sp.int8)) < 0)[0]\n\n        cur_regions = [r for r in zip(start_ts, end_ts) if r[1] - r[0] >= args.min_size]\n        sizes.extend([end_t - start_t for start_t, end_t in cur_regions])\n\n        print 'saving %s regions' % len(sizes)\n        for chunknum, (start_t, end_t) in enumerate(cur_regions):\n            covered_size += end_t - start_t\n            tmpX = X[:, start_t:end_t, :]\n            name = os.path.splitext(f)[0] + '.chunk%s.npy' % chunknum\n            sp.save(name, tmpX)\n            fname = os.path.split(name)[1]\n            start_positions[fname] = (chrom, start_t)\n    print '# plotting size distribution'\n    pyplot.figure()\n    pyplot.figtext(.5,.01,'%s regions; %s bins total; %s bins covered; coverage = %.3f' % (len(sizes),total_size, covered_size, covered_size / float(total_size)), ha='center')\n    pyplot.hist(sizes, bins=100)\n    pyplot.title('chunk sizes for all chroms, min_reads %s, min_size %s, gauss_window_size %s' % (args.min_reads, args.min_size, args.gauss_window_size))\n    pyplot.savefig('chunk_sizes.minreads%s.minsize%s.windowsize%s.png' % (args.min_reads, args.min_size, args.gauss_window_size))\n\n    with open('start_positions_split.pkl', 'w') as outfile:\n        attrs = dict(windowsize=windowsize, start_positions=start_positions, \n                     valid_species=valid_species, valid_marks=valid_marks)\n        pickle.dump(attrs, outfile, -1)\n    # --min_reads .5 --min_size 25 --window_size 200;\n\n\n\n# def extract_local_features(args):\n#     \"\"\"extract some local features from the given data, saving an X array with extra dimensions\"\"\"\n#     sizes = []\n#     total_size = 0\n#     covered_size = 0\n#     start_positions = {}\n#     for f in args.observe_matrix:\n#         print '# features on ', f\n#         X = sp.load(f).astype(sp.int8)\n#         total_size += X.shape[1]\n#         #start_ts = xrange(0, X.shape[1], args.chunksize)\n#         #end_ts = xrange(args.chunksize, X.shape[1] + args.chunksize, args.chunksize)\n\n#         density = X.sum(axis=0).sum(axis=1)  # summation over I, then L\n#         #from ipdb import set_trace; set_trace()\n#         gk = _gauss_kernel(args.window_size)\n#         smoothed_density = scipy.signal.convolve(density, gk, mode='same')\n#         regions_to_keep = smoothed_density >= args.min_reads\n\n#         # find the regions where a transition is made from no reads to reads, and reads to no reads\n#         start_ts = sp.where(sp.diff(regions_to_keep.astype(sp.int8)) > 0)[0]\n#         end_ts = sp.where(sp.diff(regions_to_keep.astype(sp.int8)) < 0)[0]\n\n#         cur_regions = [r for r in zip(start_ts, end_ts) if r[1] - r[0] >= args.min_size]\n#         sizes.extend([end_t - start_t for start_t, end_t in cur_regions])\n\n#         print 'saving %s regions' % len(sizes)\n#         for chunknum, (start_t, end_t) in enumerate(cur_regions):\n#             covered_size += end_t - start_t\n#             tmpX = X[:, start_t:end_t, :]\n#             name = os.path.splitext(f)[0] + '.chunk%s.npy' % chunknum\n#             sp.save(name, tmpX)\n#             start_positions[name] = start_t\n#     print '# plotting size distribution'\n#     pyplot.figure()\n#     pyplot.figtext(.5,.01,'%s regions; %s bins total; %s bins covered; coverage = %.3f' % (len(sizes),total_size, covered_size, covered_size / float(total_size)), ha='center')\n#     pyplot.hist(sizes, bins=100)\n#     pyplot.title('chunk sizes for all chroms, min_reads %s, min_size %s, window_size %s' % (args.min_reads, args.min_size, args.window_size))\n#     pyplot.savefig('chunk_sizes.minreads%s.minsize%s.windowsize%s.png' % (args.min_reads, args.min_size, args.window_size))\n\n#     pickle.dump(start_positions, open('start_positions.pkl', 'w'))\n#     # --min_reads .5 --min_size 25 --window_size 200;\n\n\n\n# def convert_data_continuous_features_and_split(args):\n#     \"\"\"histogram both treatment and control data as specified by args\n#     This saves the complete X matrix\n\n#     This version doesn't binarize the data, smooths out the read signal (gaussian convolution)\n#     and adds derivative information\n#     \"\"\"\n#     if args.download_first:\n#         download_data(args)\n#     I = len(args.species)\n#     L = len(args.marks)\n#     final_data = None\n#     total_size = 0\n#     covered_size = 0\n#     start_positions = {}\n#     # make sure all the data is present...\n#     for species in args.species:\n#         for mark in args.marks:\n#             d_files = [f for f in glob.glob(args.bam_template.format(\n#                                                 species=species, mark=mark))]\n#             if len(d_files) == 0:\n#                 print(\"No histone data for species %s mark %s Expected: %s\" %\n#                               (species, mark, args.bam_template.format(\n#                                                 species=species, mark=mark)))\n\n#     for i, species in enumerate(args.species):\n#         for l, mark in enumerate(args.marks):\n#             d_obs = {}\n#             d_files = [f for f in glob.glob(args.bam_template.format(\n#                                                 species=species, mark=mark))]\n#             if len(d_files) == 0:\n#                 args.mark_avail[i, l] = 0\n#             else:\n#                 args.mark_avail[i, l] = 1\n#                 for mark_file in d_files:\n#                     read_counts = histogram_reads(mark_file, args.windowsize, args.chromosomes)\n\n#                         # d_obs.append(histogram_reads(mark_file, args.windowsize,\n#                         #                             args.chromosomes))\n#                 for \n#                 d_obs = reduce(operator.add, d_obs)  # add all replicants together\n#                 #print 'before per million:', d_obs.sum()\n#                 #d_obs /= (d_obs.sum() / 1e7)  # convert to reads mapping per ten million\n#                 # convert to a binary array with global poisson\n#                 #genome_rate = d_obs / (d_obs.sum() / 1e6)\n\n#                 if final_data is None:\n#                     final_data = sp.zeros((I, len(d_obs), L), dtype=sp.float32)\n#                 final_data[i, :, l] = d_obs\n#                 total_size = final_data.shape[1]\n\n\n#     regions_to_keep = (final_data[:, :, tuple(range(L))].sum(axis=0).sum(axis=1) >= args.min_reads).astype(sp.int8)\n#     # find the regions where a transition is made from no reads to reads, and reads to no reads\n#     start_ts = sp.where(sp.diff(regions_to_keep) > 0)[0]\n#     end_ts = sp.where(sp.diff(regions_to_keep) < 0)[0]\n\n#     cur_regions = [r for r in zip(start_ts, end_ts) if r[1] - r[0] >= args.min_size]\n#     sizes = [end_t - start_t for start_t, end_t in cur_regions]\n\n#     print 'saving %s regions' % len(sizes)\n#     tarout = tarfile.open(args.outfile + '.tar.gz', 'w:gz')\n#     for chunknum, (start_t, end_t) in enumerate(cur_regions):\n#         covered_size += end_t - start_t\n#         tmpX = final_data[:, start_t:end_t, :]\n\n#         print 'adding chunk', chunknum, 'of', len(cur_regions)\n#         s = StringIO()\n#         sp.save(s, tmpX)\n#         name = args.outfile + '.chunk%s.npy' % chunknum\n#         info = tarfile.TarInfo(name)\n#         info.size = s.tell(); info.mtime = time.time()\n#         s.seek(0)\n#         tarout.addfile(info, s)\n#         start_positions[name] = start_t\n\n#     print '# plotting size distribution'\n#     pyplot.figure()\n#     pyplot.figtext(.5,.01,'%s regions; %s bins total; %s bins covered; coverage = %.3f' % (len(sizes),total_size, covered_size, covered_size / float(total_size)), ha='center')\n#     pyplot.hist(sizes, bins=100)\n#     pyplot.title('chunk sizes for all chroms, min_reads %s, min_size %s, windowsize %s' % (args.min_reads, args.min_size, args.windowsize))\n#     pyplot.savefig('chunk_sizes.minreads%s.minsize%s.windowsize%s.png' % (args.min_reads, args.min_size, args.windowsize))\n\n#     s = StringIO()\n#     pyplot.savefig(s)\n#     info = tarfile.TarInfo('chunk_sizes.minreads%s.minsize%s.windowsize%s.png' % (args.min_reads, args.min_size, args.windowsize))\n#     info.size = s.tell(); info.mtime = time.time()\n#     s.seek(0)\n#     tarout.addfile(info, s)\n\n#     s = StringIO()\n#     pickle.dump(start_positions, s)\n#     info = tarfile.TarInfo('start_positions.pkl')\n#     info.size = s.tell(); info.mtime = time.time()\n#     s.seek(0)\n#     tarout.addfile(info, s)\n#     pickle.dump(start_positions, open('start_positions.pkl', 'w'))\n#     # --min_reads .5 --min_size 25 --window_size 200;\n\n\n#     s = StringIO()\n#     sp.save(s, args.mark_avail)\n#     info = tarfile.TarInfo('available_marks.npy')\n#     info.size = s.tell(); info.mtime = time.time()\n#     s.seek(0)\n#     tarout.addfile(info, s)\n#     pickle.dump(start_positions, open('start_positions.pkl', 'w'))\n#     # --min_reads .5 --min_size 25 --window_size 200;\n\n#     tarout.close()\n\n\n#     print \"output file:\", args.outfile\n#     print 'available marks:', args.mark_avail\n#     #with open(args.outfile, 'wb') as outfile:\n#     #    sp.save(outfile, final_data)\n#     with open(args.outfile + '.available_marks', 'wb') as outfile:\n#         sp.save(outfile, args.mark_avail)\n\n\n\n\n# def convert_data_continuous_features_and_split_old(args):\n#     \"\"\"histogram both treatment and control data as specified by args\n#     This saves the complete X matrix\n\n#     This version doesn't binarize the data, smooths out the read signal (gaussian convolution)\n#     and adds derivative information\n#     \"\"\"\n#     if args.download_first:\n#         download_data(args)\n#     I = len(args.species)\n#     L = len(args.marks)\n#     final_data = None\n#     total_size = 0\n#     covered_size = 0\n#     start_positions = {}\n#     # make sure all the data is present...\n#     for species in args.species:\n#         for mark in args.marks:\n#             d_files = [f for f in glob.glob(args.bam_template.format(\n#                                                 species=species, mark=mark))]\n#             if len(d_files) == 0:\n#                 print(\"No histone data for species %s mark %s Expected: %s\" %\n#                               (species, mark, args.bam_template.format(\n#                                                 species=species, mark=mark)))\n\n#     for i, species in enumerate(args.species):\n#         for l, mark in enumerate(args.marks):\n#             l = l * 3\n#             d_obs = []\n#             d_files = [f for f in glob.glob(args.bam_template.format(\n#                                                 species=species, mark=mark))]\n#             if len(d_files) == 0:\n#                 args.mark_avail[i, l] = 0\n#                 args.mark_avail[i, l+1] = 0\n#                 args.mark_avail[i, l+2] = 0\n#             else:\n#                 args.mark_avail[i, l] = 1\n#                 args.mark_avail[i, l+1] = 1\n#                 args.mark_avail[i, l+2] = 1\n#                 for mark_file in d_files:\n#                     try:\n#                         d_obs.append(histogram_reads(mark_file, args.windowsize,\n#                                                     args.chromosomes))\n#                     except ValueError as e:\n#                         print e.message\n#                     print d_obs[-1].sum()\n#                     print d_obs[-1].shape\n#                 d_obs = reduce(operator.add, d_obs)  # add all replicants together\n#                 #print 'before per million:', d_obs.sum()\n#                 #d_obs /= (d_obs.sum() / 1e7)  # convert to reads mapping per ten million\n#                 # convert to a binary array with global poisson\n#                 genome_rate = d_obs / (d_obs.sum() / 1e6)\n\n#                 if final_data is None:\n#                     final_data = sp.zeros((I, len(d_obs), L * 3), dtype=sp.float32)\n#                 asinh_obs = sp.log(genome_rate + sp.sqrt(genome_rate * genome_rate + 1))\n#                 gk = _gauss_kernel(3)\n#                 smoothed_obs = scipy.signal.convolve(asinh_obs, gk, mode='same')\n#                 smooth_deriv = sp.gradient(smoothed_obs)\n#                 smooth_deriv2 = sp.gradient(smooth_deriv)\n#                 final_data[i, :, l] = smoothed_obs\n#                 final_data[i, :, l + 1] = smooth_deriv\n#                 final_data[i, :, l + 2] = smooth_deriv2\n#                 total_size = final_data.shape[1]\n\n\n#     regions_to_keep = (final_data[:, :, tuple(range(0, L * 3, 3))].sum(axis=0).sum(axis=1) >= args.min_reads).astype(sp.int8)\n#     # find the regions where a transition is made from no reads to reads, and reads to no reads\n#     start_ts = sp.where(sp.diff(regions_to_keep) > 0)[0]\n#     end_ts = sp.where(sp.diff(regions_to_keep) < 0)[0]\n\n#     cur_regions = [r for r in zip(start_ts, end_ts) if r[1] - r[0] >= args.min_size]\n#     sizes = [end_t - start_t for start_t, end_t in cur_regions]\n\n#     print 'saving %s regions' % len(sizes)\n#     tarout = tarfile.open(args.outfile + '.tar.gz', 'w:gz')\n#     for chunknum, (start_t, end_t) in enumerate(cur_regions):\n#         covered_size += end_t - start_t\n#         tmpX = final_data[:, start_t:end_t, :]\n\n#         print 'adding chunk', chunknum, 'of', len(cur_regions)\n#         s = StringIO()\n#         sp.save(s, tmpX)\n#         name = args.outfile + '.chunk%s.npy' % chunknum\n#         info = tarfile.TarInfo(name)\n#         info.size = s.tell(); info.mtime = time.time()\n#         s.seek(0)\n#         tarout.addfile(info, s)\n#         start_positions[name] = start_t\n\n#     print '# plotting size distribution'\n#     pyplot.figure()\n#     pyplot.figtext(.5,.01,'%s regions; %s bins total; %s bins covered; coverage = %.3f' % (len(sizes),total_size, covered_size, covered_size / float(total_size)), ha='center')\n#     pyplot.hist(sizes, bins=100)\n#     pyplot.title('chunk sizes for all chroms, min_reads %s, min_size %s, windowsize %s' % (args.min_reads, args.min_size, args.windowsize))\n#     pyplot.savefig('chunk_sizes.minreads%s.minsize%s.windowsize%s.png' % (args.min_reads, args.min_size, args.windowsize))\n\n#     s = StringIO()\n#     pyplot.savefig(s)\n#     info = tarfile.TarInfo('chunk_sizes.minreads%s.minsize%s.windowsize%s.png' % (args.min_reads, args.min_size, args.windowsize))\n#     info.size = s.tell(); info.mtime = time.time()\n#     s.seek(0)\n#     tarout.addfile(info, s)\n\n#     s = StringIO()\n#     pickle.dump(start_positions, s)\n#     info = tarfile.TarInfo('start_positions.pkl')\n#     info.size = s.tell(); info.mtime = time.time()\n#     s.seek(0)\n#     tarout.addfile(info, s)\n#     pickle.dump(start_positions, open('start_positions.pkl', 'w'))\n#     # --min_reads .5 --min_size 25 --window_size 200;\n\n\n#     s = StringIO()\n#     sp.save(s, args.mark_avail)\n#     info = tarfile.TarInfo('available_marks.npy')\n#     info.size = s.tell(); info.mtime = time.time()\n#     s.seek(0)\n#     tarout.addfile(info, s)\n#     pickle.dump(start_positions, open('start_positions.pkl', 'w'))\n#     # --min_reads .5 --min_size 25 --window_size 200;\n\n#     tarout.close()\n\n\n#     print \"output file:\", args.outfile\n#     print 'available marks:', args.mark_avail\n#     #with open(args.outfile, 'wb') as outfile:\n#     #    sp.save(outfile, final_data)\n#     with open(args.outfile + '.available_marks', 'wb') as outfile:\n#         sp.save(outfile, args.mark_avail)\n\n\ndef _gauss_kernel(winsize):\n    x = sp.mgrid[-int(winsize):int(winsize)+1]\n    g = sp.exp(-(x**2/float(winsize)))\n    return g / g.sum()\n\ndef convert_data(args):\n    \"\"\"histogram both treatment and control data as specified by args\n    This saves the complete X matrix\n    \"\"\"\n    if args.download_first:\n        download_data(args)\n    I = len(args.species)\n    L = len(args.marks)\n    final_data = None\n    start_positions = {}\n    # make sure all the data is present...\n    for species in args.species:\n        for mark in args.marks:\n            d_files = [f for f in glob.glob(args.bam_template.format(\n                                                species=species, mark=mark, repnum='*'))]\n            if len(d_files) == 0:\n                raise RuntimeError(\"No histone data for species %s mark %s Expected: %s\" %\n                              (species, mark, args.bam_template.format(\n                                                species=species, mark=mark, repnum='*')))\n\n    for i, species in enumerate(args.species):\n        for l, mark in enumerate(args.marks):\n\n            d_obs = {}\n            d_files = [f for f in glob.glob(args.bam_template.format(\n                                                species=species, mark=mark, repnum='*'))]\n            if len(d_files) == 0:\n                pass\n            else:\n                for mark_file in d_files:\n                    read_counts = histogram_reads(mark_file, args.windowsize, args.chromosomes) \n                    # d_obs.append(histogram_reads(mark_file, args.windowsize,\n                    #                              args.chromosomes))\n                    for chrom in read_counts:\n                        d_obs.setdefault(chrom, []).append(read_counts[chrom])\n                for chrom in d_obs:\n                    d_obs[chrom] = reduce(operator.add, d_obs[chrom])  # add all replicants together\n                #print 'before per million:', d_obs.sum()\n                #d_obs /= (d_obs.sum() / 1e7)  # convert to reads mapping per ten million\n                # convert to a binary array with global poisson\n                num_reads = sum(x.sum() for x in d_obs.values())\n                num_bins = float(sum(len(x) for x in d_obs.values()))\n                genome_rate = num_reads / num_bins\n                print 'after per million', num_reads, num_bins, genome_rate\n                if final_data is None:\n                    final_data = {}\n                for chrom in d_obs:\n                    d_obs[chrom] = call_significant_sites(d_obs[chrom], genome_rate, args.max_pvalue)\n                    if chrom not in final_data:\n                        final_data[chrom] = sp.zeros((I, len(d_obs[chrom]), L), dtype=sp.int8)\n                    final_data[chrom][i, :, l] = d_obs[chrom]\n    for chrom in final_data:\n        start_positions[os.path.split(args.outfile.format(chrom=chrom))[1]] = (chrom, 0)\n        print \"output file:\", args.outfile.format(chrom=chrom)\n        with open(args.outfile.format(chrom=chrom), 'wb') as outfile:\n            sp.save(outfile, final_data[chrom])\n    with open('start_positions.pkl', 'w') as outfile:\n        pickle.dump(dict(windowsize=args.windowsize, valid_species=valid_species,\n                        valid_marks=valid_marks, start_positions=start_positions),\n                    outfile, -1)\n\ndef download_data(args):\n    \"\"\"Download any missing histone modification data from UCSC and check md5s.\n    \"\"\"\n    md5s = urllib.urlopen(args.base_url % 'md5sum.txt').read().strip().split('\\n')\n    md5s = dict(reversed(l.strip().split()) for l in md5s)\n    for species in args.species:\n        for mark in args.marks:\n            for rep in range(10):\n                fname = args.bam_template.format(species=species,\n                                            mark=mark, repnum=rep)\n                if fname not in md5s:\n                    continue\n                if os.path.exists(fname):\n                    #m = hashlib.md5(open(fname, 'rb').read()).hexdigest()\n                    #if m != md5s[fname]:  # destroy if md5 doesn't match\n                    #    print 'removing incomplete file: %s' % fname\n                    #    print m, md5s[fname]\n                    #    os.unlink(fname)\n                    #else:\n                        print 'skipping already downloaded %s' % fname\n                        continue\n                with open(fname, 'wb') as outfile:\n                    try:\n                        print 'downloading %s' % fname\n                        page = urllib.urlopen(args.base_url % fname)\n                        while True:\n                            data = page.read(81920)\n                            if not data:\n                                break\n                            outfile.write(data)\n                    except RuntimeError as e:\n                        print 'Skipping...', e.message\n\n\n\ndef histogram_reads(bam_file, windowsize, chromosomes='all', exclude_chroms=['chrM', 'chrY', 'chrX'],\n                    skip_qc_fail=True):\n    \"\"\"Histogram the counts along bam_file, resulting in a vector.\n\n    This will concatenate all chromosomes, together, so to get the\n    counts for a particular chromosome, pass it as a list, a la\n    >>> histogram_reads(my_bam_file, chromosomes=['chr1'])\n    \"\"\"\n    print 'histogramming', bam_file\n    reads_bam = pysam.Samfile(bam_file, 'rb')\n    # get the chromosome name and lengths for our subset\n    if chromosomes == 'all':\n        chromosomes = filter(lambda c: c not in exclude_chroms,\n                             reads_bam.references)\n        chrom_set = set(chromosomes)\n        chrom_lengths = {c : reads_bam.lengths[reads_bam.references.index(c)]\n                                       for c in chromosomes}\n    else:\n        chromosomes = filter(lambda c: c not in exclude_chroms,\n                             chromosomes)\n        chrom_lengths = {c : reads_bam.lengths[reads_bam.references.index(c)]\n                                       for c in chromosomes if c not in\n                                                    exclude_chroms}\n        chrom_set = set(chromosomes)\n    # # offset of each chromosome into concatenated chrom bins\n    # chrom_ends = list(((sp.array(chrom_lengths) // windowsize) + 1).cumsum())\n    # chrom_starts = dict(zip(chromosomes, [0] + chrom_ends[:-1]))\n\n    read_counts = {}\n    # create the histogram: 1 x sum(lengths) array\n    # read_counts = sp.zeros(chrom_ends[-1], dtype=float_type)\n\n    # count the reads in the input\n    for read in reads_bam:\n        if skip_qc_fail and (read.is_qcfail or read.is_unmapped or read.is_secondary or\n               read.is_duplicate or read.mapq == 0):\n           continue  # filter out non-mapping reads\n        chrom = reads_bam.references[read.tid]\n        if chrom in chrom_set:  # chrom requested?\n            # offset = chrom_starts[chrom]\n            offset = 0\n            if read.is_paired:\n                if read.is_proper_pair:\n                    # add at the middle of the mates\n                    bin = offset + ((read.pos + read.mpos +\n                                     read.rlen) / 2) // windowsize\n                    # read_counts[min(chrom_ends[-1] - 1, bin)] += 1.\n                    if chrom not in read_counts:\n                        read_counts[chrom] = sp.zeros(chrom_lengths[chrom] // windowsize, dtype=float_type)\n                    read_counts[chrom][min(chrom_lengths[chrom] // windowsize - 1, bin)] += 1.\n            else:\n                # add at the middle of the fragment\n                bin = offset + (read.pos + 100) // windowsize\n                if chrom not in read_counts:\n                    read_counts[chrom] = sp.zeros(chrom_lengths[chrom] // windowsize, dtype=float_type)\n                read_counts[chrom][min(chrom_lengths[chrom] // windowsize - 1, bin)] += 1.\n    return read_counts\n\n\ndef call_significant_sites(fg_counts, bg_counts, max_pvalue):\n    \"\"\"binarize fg_counts (significant=1) using bg_counts as a local poisson\n    rate. the poisson survival must be < sig_level.\n    \"\"\"\n    print 'most reads in a bin:', fg_counts.max(), 'poisson expected rate:', bg_counts\n    print 'read count vs binary present:' , {i: poisson.sf(i, bg_counts) < max_pvalue for i in range(20)}\n    return poisson.sf(fg_counts, bg_counts) < max_pvalue\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "6a5058a8af999853fe6ff14d7f5ba63915bfba25", "size": 65101, "ext": "py", "lang": "Python", "max_stars_repo_path": "treehmm/__init__.py", "max_stars_repo_name": "uci-cbcl/tree-hmm", "max_stars_repo_head_hexsha": "e401f5f0fc107d89c03638695db79319db411d48", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2015-04-22T19:04:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T13:52:56.000Z", "max_issues_repo_path": "treehmm/__init__.py", "max_issues_repo_name": "uci-cbcl/tree-hmm", "max_issues_repo_head_hexsha": "e401f5f0fc107d89c03638695db79319db411d48", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-05-16T01:37:46.000Z", "max_issues_repo_issues_event_max_datetime": "2016-11-04T15:09:46.000Z", "max_forks_repo_path": "treehmm/__init__.py", "max_forks_repo_name": "uci-cbcl/tree-hmm", "max_forks_repo_head_hexsha": "e401f5f0fc107d89c03638695db79319db411d48", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2015-04-23T13:42:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-03T16:06:24.000Z", "avg_line_length": 47.553688824, "max_line_length": 369, "alphanum_fraction": 0.5905439241, "include": true, "reason": "import scipy,from scipy", "num_tokens": 15377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.19900810032380006}}
{"text": "from __future__ import print_function\nimport argparse\nimport wandb\nimport os\nimport random\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nimport torch.utils.data\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport torchvision.utils as vutils\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--dataset', required=True, help='cifar10 | lsun | mnist |imagenet | folder | lfw | fake')\nparser.add_argument('--model', required=True, help='gramnet | gan')\nparser.add_argument('--dataroot', required=True, help='path to dataset')\nparser.add_argument('--workers', type=int, help='number of data loading workers', default=2)\nparser.add_argument('--batchSize', type=int, default=100, help='input batch size')\nparser.add_argument('--showSize', type=int, default=100, help='size of display batch')\nparser.add_argument('--imageSize', type=int, default=64, help='the height / width of the input image to network')\nparser.add_argument('--nz', type=int, default=100, help='size of the latent z vector')\nparser.add_argument('--nk', type=int, default=200, help='size of the projected k vector')\nparser.add_argument('--ngf', type=int, default=64)\nparser.add_argument('--ncf', type=int, default=64)\nparser.add_argument('--n_epochs', type=int, default=25, help='number of epochs to train for')\nparser.add_argument('--lr', type=float, default=0.0002, help='learning rate, default=0.0002')\nparser.add_argument('--beta1', type=float, default=0.5, help='beta1 for adam. default=0.5')\nparser.add_argument('--clip_ratio', action='store_true', help='apply ratio clipping (suggested by reviewer 1)')\nparser.add_argument('--eps_ratio', type=float, default=0.001, help='add eps to the diagonal before solving')\nparser.add_argument('--cuda', action='store_true', help='enables cuda')\nparser.add_argument('--gpu_id', type=int, default=0, help='default GPU ID to use')\nparser.add_argument('--ngpu', type=int, default=1, help='number of GPUs to use')\nparser.add_argument('--netG', default='', help=\"path to netG (to continue training)\")\nparser.add_argument('--netD', default='', help=\"path to netD (to continue training)\")\nparser.add_argument('--netF', default='', help=\"path to netF (to continue training)\")\nparser.add_argument('--outf', default='.', help='folder to output images and model checkpoints')\nparser.add_argument('--monitor_heuristic', action='store_true', help='monitor heuristic σ')\nparser.add_argument('--manualSeed', type=int, help='manual seed')\nparser.add_argument('--nowandb', action='store_true', help='disables wandb')\nparser.add_argument('--classes', default='bedroom', help='comma separated list of classes for the lsun data set')\n\nopt = parser.parse_args()\nprint(opt)\nif not opt.nowandb:\n    wandb.init(project=\"gramtorch\", config=opt)\n\ntry:\n    os.makedirs(opt.outf)\nexcept OSError:\n    pass\n\nif opt.manualSeed is None:\n    opt.manualSeed = random.randint(1, 10000)\nprint(\"Random Seed: \", opt.manualSeed)\nrandom.seed(opt.manualSeed)\ntorch.manual_seed(opt.manualSeed)\n\ncudnn.benchmark = True\n\nif torch.cuda.is_available() and not opt.cuda:\n    print(\"WARNING: You have a CUDA device, so you should probably run with --cuda\")\n\nif opt.dataset in ['imagenet', 'folder', 'lfw']:\n    # folder dataset\n    dataset = dset.ImageFolder(root=opt.dataroot,\n                               transform=transforms.Compose([\n                                   transforms.Resize(opt.imageSize),\n                                   transforms.CenterCrop(opt.imageSize),\n                                   transforms.ToTensor(),\n                                   transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n                               ]))\n    nc=3\nelif opt.dataset == 'lsun':\n    classes = [ c + '_train' for c in opt.classes.split(',')]\n    dataset = dset.LSUN(root=opt.dataroot, classes=classes,\n                        transform=transforms.Compose([\n                            transforms.Resize(opt.imageSize),\n                            transforms.CenterCrop(opt.imageSize),\n                            transforms.ToTensor(),\n                            transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n                        ]))\n    nc=3\nelif opt.dataset == 'cifar10':\n    dataset = dset.CIFAR10(root=opt.dataroot, download=True,\n                           transform=transforms.Compose([\n                               transforms.Resize(opt.imageSize),\n                               transforms.ToTensor(),\n                               transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n                           ]))\n    nc=3\n\nelif opt.dataset == 'mnist':\n        dataset = dset.MNIST(root=opt.dataroot, download=True,\n                           transform=transforms.Compose([\n                               transforms.Resize(opt.imageSize),\n                               transforms.ToTensor(),\n                               transforms.Normalize((0.5,), (0.5,)),\n                           ]))\n        nc=1\n\nelif opt.dataset == 'fake':\n    dataset = dset.FakeData(image_size=(3, opt.imageSize, opt.imageSize),\n                            transform=transforms.ToTensor())\n    nc=3\n\nassert dataset\ndataloader = torch.utils.data.DataLoader(dataset, batch_size=opt.batchSize,\n                                         shuffle=True, num_workers=int(opt.workers))\n\ndevice = torch.device(f\"cuda:{opt.gpu_id}\" if opt.cuda else \"cpu\")\nngpu = int(opt.ngpu)\nnz = int(opt.nz)\nnk = int(opt.nk)\nngf = int(opt.ngf)\nncf = int(opt.ncf)\n\n\n# custom weights initialization called on netG and netD\ndef weights_init(m):\n    classname = m.__class__.__name__\n    if classname.find('Conv') != -1:\n        m.weight.data.normal_(0.0, 0.02)\n    elif classname.find('BatchNorm') != -1:\n        m.weight.data.normal_(1.0, 0.02)\n        m.bias.data.fill_(0)\n\ndef save_img(x_data, x_gen, epoch):\n    vutils.save_image(\n        x_data[0:opt.showSize],\n        f'{opt.outf}/{opt.dataset}-{opt.model}-data.png',\n        normalize=True\n    )\n    vutils.save_image(\n        x_gen[0:opt.showSize],\n        f'{opt.outf}/{opt.dataset}-{opt.model}-samples-epoch={epoch:03d}.png',\n        normalize=True\n    )\n    if not opt.nowandb:\n        wandb.log({\"samples\" : [wandb.Image(i) for i in x_gen[0:opt.showSize]]}, commit=False)\n\nclass Generator(nn.Module):\n    def __init__(self, ngpu):\n        super(Generator, self).__init__()\n        self.ngpu = ngpu\n        self.main = nn.Sequential(\n            # input is Z, going into a convolution\n            nn.ConvTranspose2d(     nz, ngf * 8, 4, 1, 0, bias=False),\n            nn.BatchNorm2d(ngf * 8),\n            nn.ReLU(True),\n            # state size. (ngf*8) x 4 x 4\n            nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False),\n            nn.BatchNorm2d(ngf * 4),\n            nn.ReLU(True),\n            # state size. (ngf*4) x 8 x 8\n            nn.ConvTranspose2d(ngf * 4, ngf * 2, 4, 2, 1, bias=False),\n            nn.BatchNorm2d(ngf * 2),\n            nn.ReLU(True),\n            # state size. (ngf*2) x 16 x 16\n            nn.ConvTranspose2d(ngf * 2,     ngf, 4, 2, 1, bias=False),\n            nn.BatchNorm2d(ngf),\n            nn.ReLU(True),\n            # state size. (ngf) x 32 x 32\n            nn.ConvTranspose2d(    ngf,      nc, 4, 2, 1, bias=False),\n            nn.Tanh()\n            # state size. (nc) x 64 x 64\n        )\n\n    def forward(self, input):\n        if input.is_cuda and self.ngpu > 1:\n            output = nn.parallel.data_parallel(self.main, input, range(self.ngpu))\n        else:\n            output = self.main(input)\n        return output\n\n\nclass Critic(nn.Module):\n    def __init__(self, ngpu, nout):\n        super(Critic, self).__init__()\n        self.ngpu = ngpu\n        self.nout = nout\n        self.main = nn.Sequential(\n            # input is (nc) x 64 x 64\n            nn.Conv2d(nc, ncf, 4, 2, 1, bias=False),\n            nn.LeakyReLU(0.2, inplace=True),\n            # state size. (ncf) x 32 x 32\n            nn.Conv2d(ncf, ncf * 2, 4, 2, 1, bias=False),\n            nn.BatchNorm2d(ncf * 2),\n            nn.LeakyReLU(0.2, inplace=True),\n            # state size. (ncf*2) x 16 x 16\n            nn.Conv2d(ncf * 2, ncf * 4, 4, 2, 1, bias=False),\n            nn.BatchNorm2d(ncf * 4),\n            nn.LeakyReLU(0.2, inplace=True),\n            # state size. (ncf*4) x 8 x 8\n            nn.Conv2d(ncf * 4, ncf * 8, 4, 2, 1, bias=False),\n            nn.BatchNorm2d(ncf * 8),\n            nn.LeakyReLU(0.2, inplace=True),\n            # state size. (ncf*8) x 4 x 4\n        )\n        final = nn.Linear(ncf * 8 * 4 * 4, nout)\n        if nout == 1:\n            final = nn.Sequential(final, nn.Sigmoid())\n        self.final = final\n\n    def forward(self, input):\n        if input.is_cuda and self.ngpu > 1:\n            output = nn.parallel.data_parallel(self.main, input, range(self.ngpu))\n            output = output.view(-1, ncf * 8 * 4 * 4)\n            output = nn.parallel.data_parallel(self.final, output, range(self.ngpu))\n        else:\n            output = self.main(input)\n            output = output.view(-1, ncf * 8 * 4 * 4)\n            output = self.final(output)\n        if self.nout == 1:\n            output = output.view(-1, 1).squeeze(1)\n        return output\n\n\nclass GAN:\n    def __init__(self, ngpu):\n        netG = Generator(ngpu).to(device)\n        netG.apply(weights_init)\n        if opt.netG != '':\n            netG.load_state_dict(torch.load(opt.netG))\n        print(netG)\n        \n        netD = Critic(ngpu, 1).to(device)\n        netD.apply(weights_init)\n        if opt.netD != '':\n            netD.load_state_dict(torch.load(opt.netD))\n        print(netD)\n\n        self.netG = netG\n        self.netD = netD\n\n    def train(self):\n        netG = self.netG\n        netD = self.netD\n\n        criterion = nn.BCELoss()\n\n        fixed_noise = torch.randn(opt.showSize, nz, 1, 1, device=device)\n        real_label = 1\n        fake_label = 0\n\n        # setup optimizer\n        optimizerD = optim.Adam(netD.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))\n        optimizerG = optim.Adam(netG.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))\n\n        for epoch in range(opt.n_epochs):\n            for i, data in enumerate(dataloader, 0):\n                ############################\n                # (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))\n                ###########################\n                # train with real\n                netD.zero_grad()\n                real_cpu = data[0].to(device)\n                batch_size = real_cpu.size(0)\n                label = torch.full((batch_size,), real_label, device=device)\n\n                output = netD(real_cpu)\n                errD_real = criterion(output, label)\n                errD_real.backward()\n                D_x = output.mean().item()\n\n                # train with fake\n                noise = torch.randn(batch_size, nz, 1, 1, device=device)\n                fake = netG(noise)\n                label.fill_(fake_label)\n                output = netD(fake.detach())\n                errD_fake = criterion(output, label)\n                errD_fake.backward()\n                D_G_z1 = output.mean().item()\n                errD = errD_real + errD_fake\n                optimizerD.step()\n\n                ############################\n                # (2) Update G network: maximize log(D(G(z)))\n                ###########################\n                netG.zero_grad()\n                label.fill_(real_label)  # fake labels are real for generator cost\n                output = netD(fake)\n                errG = criterion(output, label)\n                errG.backward()\n                D_G_z2 = output.mean().item()\n                optimizerG.step()\n\n                print('[%d/%d][%d/%d] Loss_D: %.4f Loss_G: %.4f D(x): %.4f D(G(z)): %.4f / %.4f'\n                    % (epoch, opt.n_epochs, i, len(dataloader),\n                        errD.item(), errG.item(), D_x, D_G_z1, D_G_z2))\n                if i % 100 == 0:\n                    netG.train(False)\n                    save_img(real_cpu, netG(fixed_noise).detach(), epoch)\n                    netG.train(True)\n                if not opt.nowandb:\n                    wandb.log({\n                        \"lossG\" : errG, \"lossF\" : errD, \n                        \"D(x)\" : D_G_z1, \"D(G(z))\" : D_G_z2,\n                    })\n\n            # do checkpointing\n            torch.save(netG.state_dict(), f'{opt.outf}/{opt.model}-netG-epoch={epoch}.pth')\n            torch.save(netD.state_dict(), f'{opt.outf}/{opt.model}-netD-epoch={epoch}.pth')\n\n\n### MMD utilities\n\ndef euclidsq(x, y):\n    return torch.pow(torch.cdist(x, y), 2)\n\ndef gaussian_gramian(esq, σ):\n    return torch.exp(torch.div(-esq, 2 * σ**2))\n\ndef prepare(x_de, x_nu):\n    return euclidsq(x_de, x_de), euclidsq(x_de, x_nu), euclidsq(x_nu, x_nu)\n\nUSE_SOLVE = True\n\ndef kmm_ratios(Kdede, Kdenu, λ):\n    n_de, n_nu = Kdenu.shape\n    if λ > 0:\n        A = Kdede + λ * torch.eye(n_de).to(device)\n    else:\n        A = Kdede\n    # Equivalent implement based on 1) solver and 2) matrix inversion\n    if USE_SOLVE:\n        B = torch.sum(Kdenu, 1, keepdim=True)\n        return (n_de / n_nu) * torch.solve(B, A).solution\n    else:\n        B = Kdenu\n        return torch.matmul(torch.matmul(torch.inverse(A), B), torch.ones(n_nu, 1).to(device))\n\ndef mmdsq_of(Kdede, Kdenu, Knunu):\n    return torch.mean(Kdede) - 2 * torch.mean(Kdenu) + torch.mean(Knunu)\n\ndef estimate_ratio_compute_mmd(x_de, x_nu, σs):\n    dsq_dede, dsq_denu, dsq_nunu = prepare(x_de, x_nu)\n    if len(σs) == 0:\n        # A heuristic is to use the median of pairwise distances as σ, suggested by Sugiyama's book\n        sigma = torch.sqrt(\n            torch.median(\n                torch.cat([dsq_dede.squeeze(), dsq_denu.squeeze(), dsq_nunu.squeeze()], 1)\n            )\n        ).item()\n        if not opt.nowandb:\n            wandb.log({\"heuristic_sigma\" : sigma})\n        elif opt.monitor_heuristic:\n            print(\"heuristic sigma: \", sigma)\n        # Use [sigma / 5, sigma / 3, sigma, sigma * 3, sigma * 5] if nothing provided\n        if len(σs) == 0:\n            σs.append(sigma)\n            σs.append(sigma * 0.333)\n            σs.append(sigma * 0.2)\n            σs.append(sigma / 0.2)\n            σs.append(sigma / 0.333)\n    \n    is_first = True\n    ratio = None\n    mmdsq = None\n    for σ in σs:\n        Kdede = gaussian_gramian(dsq_dede, σ)\n        Kdenu = gaussian_gramian(dsq_denu, σ)\n        Knunu = gaussian_gramian(dsq_nunu, σ)\n        if is_first:\n            ratio = kmm_ratios(Kdede, Kdenu, opt.eps_ratio)\n            mmdsq = mmdsq_of(Kdede, Kdenu, Knunu)\n            is_first = False\n        else:\n            ratio += kmm_ratios(Kdede, Kdenu, opt.eps_ratio)\n            mmdsq += mmdsq_of(Kdede, Kdenu, Knunu)\n    \n    ratio = ratio / len(σs)\n    ratio = torch.relu(ratio) if opt.clip_ratio else ratio\n    mmd = torch.sqrt(torch.relu(mmdsq))\n    \n    return ratio, mmd\n\ndef extract_grad(m):\n    gs = []\n    for p in m.parameters():\n        gs.append(p.grad.clone())\n    return gs\n\ndef assign_grad(m, gs):\n    for p, g in zip(m.parameters(), gs):\n        p.grad = g\n\ndef sim_step(optimizer1, optimizer2, m1, m2, loss1, loss2):\n    loss1.backward(retain_graph=True)\n    gs1 = extract_grad(m1)\n    m1.zero_grad()\n    m2.zero_grad()\n    loss2.backward()\n    optimizer2.step()\n    assign_grad(m1, gs1)\n    optimizer1.step()\n\nclass GRAMnet:\n    def __init__(self, ngpu):\n        netG = Generator(ngpu).to(device)\n        netG.apply(weights_init)\n        if opt.netG != '':\n            netG.load_state_dict(torch.load(opt.netG))\n        print(netG)\n        \n        netF = Critic(ngpu, nk).to(device)\n        netF.apply(weights_init)\n        if opt.netF != '':\n            netF.load_state_dict(torch.load(opt.netF))\n        print(netF)\n\n        self.netG = netG\n        self.netF = netF\n\n        if opt.dataset == \"mnist\":\n            sigma_list = np.sqrt([0.01, 1, 100, 10000])\n        elif opt.dataset == \"cifar10\":\n            sigma_list = [1, 10, 100, 1000]\n        else:\n            sigma_list = [] # this will trigger automatic choice of sigma\n        self.sigma_list = sigma_list\n\n    def train(self):\n\n        netG = self.netG\n        netF = self.netF\n\n        fixed_noise = torch.rand(opt.showSize, nz, 1, 1, device=device)\n\n        # setup optimizer\n        optimizerF = optim.Adam(netF.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))\n        optimizerG = optim.Adam(netG.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))\n\n        for epoch in range(opt.n_epochs):\n            for i, data in enumerate(dataloader, 0):\n                x_data = data[0].to(device)\n                batch_size = x_data.size(0)\n\n                netF.zero_grad()\n                netG.zero_grad()\n                # Generate samples\n                noise = torch.rand(batch_size, nz, 1, 1, device=device)\n                x_gen = netG(noise)\n                # Project to low-dimensional space\n                fx_data = netF(x_data)\n                fx_gen = netF(x_gen)\n                # Compute ratio and mmd\n                ratio, mmd = estimate_ratio_compute_mmd(\n                    fx_gen, fx_data, list(self.sigma_list)  # `list` is need to make a copy of sigmas\n                )\n                pearson_divergence = torch.mean(torch.pow(ratio - 1, 2))\n                lossG = mmd\n                lossF = -pearson_divergence\n                # Add positivity regularizer if not clipping\n                if not opt.clip_ratio:  \n                    lossF -= torch.sum(ratio)\n                # Update G and F simultaneously\n                sim_step(optimizerG, optimizerF, netG, netF, lossG, lossF)\n\n                print('[%d/%d][%d/%d] Loss_F: %.4f Loss_G: %.4f'\n                    % (epoch, opt.n_epochs, i, len(dataloader), lossF.item(), lossG.item()))\n                if i % 100 == 0:\n                    netG.train(False)\n                    save_img(x_data, netG(fixed_noise).detach(), epoch)\n                    netG.train(True)\n                if not opt.nowandb:\n                    wandb.log({\n                        \"lossG\" : lossG, \"lossF\" : lossF, \"mmd\" : mmd,\n                        \"pearson_divergence\" : pearson_divergence,\n                    })\n\n            # do checkpointing\n            torch.save(netG.state_dict(), f'{opt.outf}/{opt.model}-netG-epoch={epoch}.pth')\n            torch.save(netF.state_dict(), f'{opt.outf}/{opt.model}-netF-epoch={epoch}.pth')\n\n\nif opt.model == \"gan\":\n    model = GAN(ngpu)\nelif opt.model == \"gramnet\":\n    model = GRAMnet(ngpu)\n\nmodel.train()\n", "meta": {"hexsha": "e6cac3de9d065ac696025795ca69b9e94902498c", "size": 18547, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "GRAM-nets/GRAMTorch", "max_stars_repo_head_hexsha": "c790f19f0ebb37098871c5c204ee39a277781f4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-04-08T08:27:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T09:43:55.000Z", "max_issues_repo_path": "main.py", "max_issues_repo_name": "GRAM-nets/PyGRAM", "max_issues_repo_head_hexsha": "c790f19f0ebb37098871c5c204ee39a277781f4c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.py", "max_forks_repo_name": "GRAM-nets/PyGRAM", "max_forks_repo_head_hexsha": "c790f19f0ebb37098871c5c204ee39a277781f4c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-30T11:19:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-28T17:24:15.000Z", "avg_line_length": 38.0841889117, "max_line_length": 113, "alphanum_fraction": 0.5561546342, "include": true, "reason": "import numpy", "num_tokens": 4876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.19900810032380006}}
{"text": "# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------------\n# (C) British Crown Copyright 2017-2021 Met Office.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n#   list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n#   this list of conditions and the following disclaimer in the documentation\n#   and/or other materials provided with the distribution.\n#\n# * Neither the name of the copyright holder nor the names of its\n#   contributors may be used to endorse or promote products derived from\n#   this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\"\"\"Reliability calibration plugins.\"\"\"\n\nimport operator\nimport warnings\n\nimport iris\nimport numpy as np\nimport scipy\n\nfrom improver import BasePlugin, PostProcessingPlugin\nfrom improver.calibration.utilities import (\n    check_forecast_consistency,\n    create_unified_frt_coord,\n    filter_non_matching_cubes,\n)\nfrom improver.metadata.probabilistic import (\n    find_threshold_coordinate,\n    probability_is_above_or_below,\n)\nfrom improver.metadata.utilities import generate_mandatory_attributes\nfrom improver.utilities.cube_manipulation import MergeCubes, collapsed\n\n\nclass ConstructReliabilityCalibrationTables(BasePlugin):\n\n    \"\"\"A plugin for creating and populating reliability calibration tables.\"\"\"\n\n    def __init__(\n        self,\n        n_probability_bins=5,\n        single_value_lower_limit=False,\n        single_value_upper_limit=False,\n    ):\n        \"\"\"\n        Initialise class for creating reliability calibration tables. These\n        tables include data columns entitled observation_count,\n        sum_of_forecast_probabilities, and forecast_count, defined below.\n\n        n_probability_bins (int):\n            The total number of probability bins required in the reliability\n            tables. If single value limits are turned on, these are included in\n            this total.\n        single_value_lower_limit (bool):\n            Mandates that the lowest bin should be single valued,\n            with a small precision tolerance, defined as 1.0E-6.\n            The bin is thus 0 to 1.0E-6.\n        single_value_upper_limit (bool):\n            Mandates that the highest bin should be single valued,\n            with a small precision tolerance, defined as 1.0E-6.\n            The bin is thus (1 - 1.0E-6) to 1.\n        \"\"\"\n        self.single_value_tolerance = 1.0e-6\n        self.probability_bins = self._define_probability_bins(\n            n_probability_bins, single_value_lower_limit, single_value_upper_limit\n        )\n        self.table_columns = np.array(\n            [\"observation_count\", \"sum_of_forecast_probabilities\", \"forecast_count\"]\n        )\n        self.expected_table_shape = (len(self.table_columns), n_probability_bins)\n\n    def __repr__(self):\n        \"\"\"Represent the configured plugin instance as a string.\"\"\"\n        bin_values = \", \".join(\n            [\"[{:1.2f} --> {:1.2f}]\".format(*item) for item in self.probability_bins]\n        )\n        result = \"<ConstructReliabilityCalibrationTables: \" \"probability_bins: {}>\"\n        return result.format(bin_values)\n\n    def _define_probability_bins(\n        self, n_probability_bins, single_value_lower_limit, single_value_upper_limit\n    ):\n        \"\"\"\n        Define equally sized probability bins for use in a reliability table.\n        The range 0 to 1 is divided into ranges to give n_probability bins.\n        If single_value_lower_limit and / or single_value_upper_limit are True,\n        additional bins corresponding to values of 0 and / or 1 will be created,\n        each with a width defined by self.single_value_tolerance.\n\n        Args:\n            n_probability_bins (int):\n                The total number of probability bins desired in the\n                reliability tables. This number includes the extrema bins\n                (equals 0 and equals 1) if single value limits are turned on,\n                in which case the minimum number of bins is 3.\n            single_value_lower_limit (bool):\n                Mandates that the lowest bin should be single valued,\n                with a small precision tolerance, defined as 1.0E-6.\n                The bin is thus 0 to 1.0E-6.\n            single_value_upper_limit (bool):\n                Mandates that the highest bin should be single valued,\n                with a small precision tolerance, defined as 1.0E-6.\n                The bin is thus (1 - 1.0E-6) to 1.\n        Returns:\n            numpy.ndarray:\n                An array of 2-element arrays that contain the bounds of the\n                probability bins. These bounds are non-overlapping, with\n                adjacent bin boundaries spaced at the smallest representable\n                interval.\n        Raises:\n            ValueError: If trying to use both single_value_lower_limit and\n                        single_value_upper_limit with 2 or fewer probability bins.\n        \"\"\"\n        if single_value_lower_limit and single_value_upper_limit:\n            if n_probability_bins <= 2:\n                msg = (\n                    \"Cannot use both single_value_lower_limit and \"\n                    \"single_value_upper_limit with 2 or fewer \"\n                    \"probability bins.\"\n                )\n                raise ValueError(msg)\n            n_probability_bins = n_probability_bins - 2\n        elif single_value_lower_limit or single_value_upper_limit:\n            n_probability_bins = n_probability_bins - 1\n\n        bin_lower = np.linspace(0, 1, n_probability_bins + 1, dtype=np.float32)\n        bin_upper = np.nextafter(bin_lower, 0, dtype=np.float32)\n        bin_upper[-1] = 1.0\n        bins = np.stack([bin_lower[:-1], bin_upper[1:]], 1).astype(np.float32)\n\n        if single_value_lower_limit:\n            bins[0, 0] = np.nextafter(self.single_value_tolerance, 1, dtype=np.float32)\n            lowest_bin = np.array([0, self.single_value_tolerance], dtype=np.float32)\n            bins = np.vstack([lowest_bin, bins]).astype(np.float32)\n\n        if single_value_upper_limit:\n            bins[-1, 1] = np.nextafter(\n                1.0 - self.single_value_tolerance, 0, dtype=np.float32\n            )\n            highest_bin = np.array(\n                [1.0 - self.single_value_tolerance, 1], dtype=np.float32\n            )\n            bins = np.vstack([bins, highest_bin]).astype(np.float32)\n\n        return bins\n\n    def _create_probability_bins_coord(self):\n        \"\"\"\n        Construct a dimension coordinate describing the probability bins\n        of the reliability table.\n\n        Returns:\n            iris.coords.DimCoord:\n                A dimension coordinate describing probability bins.\n        \"\"\"\n        values = np.mean(self.probability_bins, axis=1, dtype=np.float32)\n        probability_bins_coord = iris.coords.DimCoord(\n            values, long_name=\"probability_bin\", units=1, bounds=self.probability_bins\n        )\n        return probability_bins_coord\n\n    def _create_reliability_table_coords(self):\n        \"\"\"\n        Construct coordinates that describe the reliability table rows. These\n        are observation_count, sum_of_forecast_probabilities, and\n        forecast_count. The order used here is the order in which the table\n        data is populated, so these must remain consistent with the\n        _populate_reliability_bins function.\n\n        Returns:\n            (tuple): tuple containing:\n                **index_coord** (iris.coords.DimCoord):\n                    A numerical index dimension coordinate.\n                **name_coord** (iris.coords.AuxCoord):\n                    An auxiliary coordinate that assigns names to the index\n                    coordinates, where these names correspond to the\n                    reliability table rows.\n        \"\"\"\n        index_coord = iris.coords.DimCoord(\n            np.arange(len(self.table_columns), dtype=np.int32),\n            long_name=\"table_row_index\",\n            units=1,\n        )\n        name_coord = iris.coords.AuxCoord(\n            self.table_columns, long_name=\"table_row_name\", units=1\n        )\n        return index_coord, name_coord\n\n    @staticmethod\n    def _define_metadata(forecast_slice):\n        \"\"\"\n        Define metadata that is specifically required for reliability table\n        cubes, whilst ensuring any mandatory attributes are also populated.\n\n        Args:\n            forecast_slice (iris.cube.Cube):\n                The source cube from which to get pre-existing metadata of use.\n        Returns:\n            dict:\n                A dictionary of attributes that are appropriate for the\n                reliability table cube.\n        \"\"\"\n        attributes = generate_mandatory_attributes([forecast_slice])\n        attributes[\"title\"] = \"Reliability calibration data table\"\n        return attributes\n\n    def _create_reliability_table_cube(self, forecast, threshold_coord):\n        \"\"\"\n        Construct a reliability table cube and populate it with the provided\n        data. The returned cube will include a cycle hour coordinate, which\n        describes the model cycle hour at which the forecast data was produced.\n        It will further include the forecast period, threshold coordinate,\n        and spatial coordinates from the forecast cube.\n\n        Args:\n            forecast (iris.cube.Cube):\n                A cube slice across the spatial dimensions of the forecast\n                data. This slice provides the time and threshold values that\n                relate to the reliability_table_data.\n            threshold_coord (iris.coords.DimCoord):\n                The threshold coordinate.\n        Returns:\n            iris.cube.Cube:\n                A reliability table cube.\n        \"\"\"\n\n        def _get_coords_and_dims(coord_names):\n            \"\"\"Obtain the requested coordinates and their dimension index from\n            the forecast slice cube.\"\"\"\n            coords_and_dims = []\n            leading_coords = [probability_bins_coord, reliability_index_coord]\n            for coord_name in coord_names:\n                crd = forecast_slice.coord(coord_name)\n                crd_dim = forecast_slice.coord_dims(crd)\n                crd_dim = crd_dim[0] + len(leading_coords) if crd_dim else ()\n                coords_and_dims.append((crd, crd_dim))\n            return coords_and_dims\n\n        forecast_slice = next(forecast.slices_over([\"time\", threshold_coord]))\n        expected_shape = self.expected_table_shape + forecast_slice.shape\n        dummy_data = np.zeros((expected_shape))\n\n        diagnostic = find_threshold_coordinate(forecast).name()\n        attributes = self._define_metadata(forecast)\n\n        # Define reliability table specific coordinates\n        probability_bins_coord = self._create_probability_bins_coord()\n        (\n            reliability_index_coord,\n            reliability_name_coord,\n        ) = self._create_reliability_table_coords()\n        frt_coord = create_unified_frt_coord(forecast.coord(\"forecast_reference_time\"))\n\n        # List of required non-spatial coordinates from the forecast\n        non_spatial_coords = [\"forecast_period\", diagnostic]\n\n        # Construct a list of coordinates in the desired order\n        dim_coords = [forecast.coord(axis=dim).name() for dim in [\"x\", \"y\"]]\n        dim_coords_and_dims = _get_coords_and_dims(dim_coords)\n        aux_coords_and_dims = _get_coords_and_dims(non_spatial_coords)\n        dim_coords_and_dims.append((reliability_index_coord, 0))\n        aux_coords_and_dims.append((reliability_name_coord, 0))\n        dim_coords_and_dims.append((probability_bins_coord, 1))\n\n        reliability_cube = iris.cube.Cube(\n            dummy_data,\n            units=1,\n            attributes=attributes,\n            dim_coords_and_dims=dim_coords_and_dims,\n            aux_coords_and_dims=aux_coords_and_dims,\n        )\n        reliability_cube.add_aux_coord(frt_coord)\n        reliability_cube.rename(\"reliability_calibration_table\")\n\n        return reliability_cube\n\n    def _populate_reliability_bins(self, forecast, truth):\n        \"\"\"\n        For an x-y slice at a single validity time and threshold, populate\n        a reliability table using the provided truth.\n\n        Args:\n            forecast (numpy.ndarray or numpy.ma.MaskedArray):\n                An array containing data over an xy slice for a single validity\n                time and threshold.\n            truth (numpy.ndarray or numpy.ma.MaskedArray):\n                An array containing a thresholded gridded truth at an\n                equivalent validity time to the forecast array.\n        Returns:\n            numpy.ma.MaskedArray:\n                An array containing reliability table data for a single time\n                and threshold. The leading dimension corresponds to the rows\n                of a calibration table, the second dimension to the number of\n                probability bins, and the trailing dimensions are the spatial\n                dimensions of the forecast and truth cubes (which are\n                equivalent).\n        \"\"\"\n        observation_counts = []\n        forecast_probabilities = []\n        forecast_counts = []\n\n        for bin_min, bin_max in self.probability_bins:\n            observation_mask = (\n                ((forecast >= bin_min) & (forecast <= bin_max)) & (np.isclose(truth, 1))\n            ).astype(int)\n            forecast_mask = ((forecast >= bin_min) & (forecast <= bin_max)).astype(int)\n            forecasts_probability_values = forecast * forecast_mask\n\n            observation_counts.append(observation_mask)\n            forecast_probabilities.append(forecasts_probability_values)\n            forecast_counts.append(forecast_mask)\n\n        reliability_table = np.ma.stack(\n            [\n                np.ma.stack(observation_counts),\n                np.ma.stack(forecast_probabilities),\n                np.ma.stack(forecast_counts),\n            ]\n        )\n\n        return reliability_table.astype(np.float32)\n\n    def _populate_masked_reliability_bins(self, forecast, truth):\n        \"\"\"\n        Support populating the reliability table bins with a masked truth. If a\n        masked truth is provided, a masked reliability table is returned.\n\n        Args:\n            forecast (numpy.ndarray):\n                An array containing data over an xy slice for a single validity\n                time and threshold.\n            truth (numpy.ma.MaskedArray):\n                An array containing a thresholded gridded truth at an\n                equivalent validity time to the forecast array.\n        Returns:\n            numpy.ma.MaskedArray:\n                An array containing reliability table data for a single time\n                and threshold. The leading dimension corresponds to the rows\n                of a calibration table, the second dimension to the number of\n                probability bins, and the trailing dimensions are the spatial\n                dimensions of the forecast and truth cubes (which are\n                equivalent).\n        \"\"\"\n        forecast = np.ma.masked_where(np.ma.getmask(truth), forecast)\n        table = self._populate_reliability_bins(forecast, truth)\n        # Zero data underneath mask to support bitwise addition of masks.\n        table.data[table.mask] = 0\n        return table\n\n    def _add_reliability_tables(self, forecast, truth, threshold_reliability):\n        \"\"\"\n        Add reliability tables. The presence of a masked truth is handled\n        separately to ensure support for a mask that changes with validity time.\n\n        Args:\n            forecast (numpy.ndarray):\n                An array containing data over an xy slice for a single validity\n                time and threshold.\n            truth (numpy.ndarray or numpy.ma.MaskedArray):\n                An array containing a thresholded gridded truth at an\n                equivalent validity time to the forecast array.\n            threshold_reliability (numpy.ndarray or numpy.ma.MaskedArray):\n                The current reliability table that will be added to.\n        Returns:\n            numpy.ndarray or numpy.ma.MaskedArray:\n                An array containing reliability table data for a single time\n                and threshold. The leading dimension corresponds to the rows\n                of a calibration table, the second dimension to the number of\n                probability bins, and the trailing dimensions are the spatial\n                dimensions of the forecast and truth cubes (which are\n                equivalent).\n        \"\"\"\n        if np.ma.is_masked(truth.data):\n            table = self._populate_masked_reliability_bins(forecast.data, truth.data)\n            # Bitwise addition of masks. This ensures that only points that are\n            # masked in both the existing and new reliability tables are kept\n            # as being masked within the resulting reliability table.\n            mask = threshold_reliability.mask & table.mask\n            threshold_reliability = np.ma.array(\n                threshold_reliability.data + table.data, mask=mask, dtype=np.float32,\n            )\n        else:\n            np.add(\n                threshold_reliability,\n                self._populate_reliability_bins(forecast.data, truth.data),\n                out=threshold_reliability,\n                dtype=np.float32,\n            )\n        return threshold_reliability\n\n    def process(self, historic_forecasts, truths):\n        \"\"\"\n        Slice data over threshold and time coordinates to construct reliability\n        tables. These are summed over time to give a single table for each\n        threshold, constructed from all the provided historic forecasts and\n        truths. If a masked truth is provided, a masked reliability table is\n        returned. If the mask within the truth varies at different timesteps,\n        any point that is unmasked for at least one timestep will have\n        unmasked values within the reliability table. Therefore historic\n        forecast points will only be used if they have a corresponding valid\n        truth point for each timestep.\n\n        .. See the documentation for an example of the resulting reliability\n           table cube.\n        .. include:: extended_documentation/calibration/\n           reliability_calibration/reliability_calibration_examples.rst\n\n        Note that the forecast and truth data used is probabilistic, i.e. has\n        already been thresholded relative to the thresholds of interest, using\n        the equality operator required. As such this plugin is agnostic as to\n        whether the data is thresholded below or above a given diagnostic\n        threshold.\n\n        Args:\n            historic_forecasts (iris.cube.Cube):\n                A cube containing the historical forecasts used in calibration.\n                These are expected to all have a consistent cycle hour, that is\n                the hour in the forecast reference time.\n            truths (iris.cube.Cube):\n                A cube containing the thresholded gridded truths used in\n                calibration.\n        Returns:\n            iris.cube.CubeList:\n                A cubelist of reliability table cubes, one for each threshold\n                in the historic forecast cubes.\n        Raises:\n            ValueError: If the forecast and truth cubes have differing\n                        threshold coordinates.\n        \"\"\"\n        historic_forecasts, truths = filter_non_matching_cubes(\n            historic_forecasts, truths\n        )\n\n        threshold_coord = find_threshold_coordinate(historic_forecasts)\n        truth_threshold_coord = find_threshold_coordinate(truths)\n        if not threshold_coord == truth_threshold_coord:\n            msg = \"Threshold coordinates differ between forecasts and truths.\"\n            raise ValueError(msg)\n\n        time_coord = historic_forecasts.coord(\"time\")\n\n        check_forecast_consistency(historic_forecasts)\n        reliability_cube = self._create_reliability_table_cube(\n            historic_forecasts, threshold_coord\n        )\n\n        populate_bins_func = self._populate_reliability_bins\n        if np.ma.is_masked(truths.data):\n            populate_bins_func = self._populate_masked_reliability_bins\n\n        reliability_tables = iris.cube.CubeList()\n        threshold_slices = zip(\n            historic_forecasts.slices_over(threshold_coord),\n            truths.slices_over(threshold_coord),\n        )\n        for forecast_slice, truth_slice in threshold_slices:\n\n            time_slices = zip(\n                forecast_slice.slices_over(time_coord),\n                truth_slice.slices_over(time_coord),\n            )\n            forecast, truth = next(time_slices)\n            threshold_reliability = populate_bins_func(forecast.data, truth.data)\n\n            for forecast, truth in time_slices:\n                threshold_reliability = self._add_reliability_tables(\n                    forecast, truth, threshold_reliability\n                )\n\n            reliability_entry = reliability_cube.copy(data=threshold_reliability)\n            reliability_entry.replace_coord(forecast_slice.coord(threshold_coord))\n            reliability_tables.append(reliability_entry)\n\n        return MergeCubes()(reliability_tables, copy=False)\n\n\nclass AggregateReliabilityCalibrationTables(BasePlugin):\n\n    \"\"\"This plugin enables the aggregation of multiple reliability calibration\n    tables, and/or the aggregation over coordinates in the tables.\"\"\"\n\n    def __repr__(self):\n        \"\"\"Represent the configured plugin instance as a string.\"\"\"\n        return \"<AggregateReliabilityCalibrationTables>\"\n\n    @staticmethod\n    def _check_frt_coord(cubes):\n        \"\"\"\n        Check that the reliability calibration tables do not have overlapping\n        forecast reference time bounds. If these coordinates overlap in time it\n        indicates that some of the same forecast data has contributed to more\n        than one table, thus aggregating them would double count these\n        contributions.\n\n        Args:\n            cubes (iris.cube.CubeList):\n                The list of reliability calibration tables for which the\n                forecast reference time coordinates should be checked.\n        Raises:\n            ValueError: If the bounds overlap.\n        \"\"\"\n        lower_bounds = []\n        upper_bounds = []\n        for cube in cubes:\n            lower_bounds.append(cube.coord(\"forecast_reference_time\").bounds[0][0])\n            upper_bounds.append(cube.coord(\"forecast_reference_time\").bounds[0][1])\n        if not all(x < y for x, y in zip(upper_bounds, lower_bounds[1:])):\n            raise ValueError(\n                \"Reliability calibration tables have overlapping \"\n                \"forecast reference time bounds, indicating that \"\n                \"the same forecast data has contributed to the \"\n                \"construction of both tables. Cannot aggregate.\"\n            )\n\n    def process(self, cubes, coordinates=None):\n        \"\"\"\n        Aggregate the input reliability calibration table cubes and return the\n        result.\n\n        Args:\n            cubes (list or iris.cube.CubeList):\n                The cube or cubes containing the reliability calibration tables\n                to aggregate.\n            coordinates (list or None):\n                A list of coordinates over which to aggregate the reliability\n                calibration table using summation. If the argument is None and\n                a single cube is provided, this cube will be returned\n                unchanged.\n        \"\"\"\n        coordinates = [] if coordinates is None else coordinates\n\n        try:\n            (cube,) = cubes\n        except ValueError:\n            cubes = iris.cube.CubeList(cubes)\n            self._check_frt_coord(cubes)\n            cube = cubes.merge_cube()\n            coordinates.append(\"forecast_reference_time\")\n        else:\n            if not coordinates:\n                return cube\n\n        result = collapsed(cube, coordinates, iris.analysis.SUM)\n        frt = create_unified_frt_coord(cube.coord(\"forecast_reference_time\"))\n        result.replace_coord(frt)\n        return result\n\n\nclass ManipulateReliabilityTable(BasePlugin):\n    \"\"\"\n    A plugin to manipulate the reliability tables before they are used to\n    calibrate a forecast. x and y coordinates on the reliability table must be\n    collapsed.\n    The result is a reliability diagram with monotonic observation frequency.\n\n    Steps taken are:\n\n    1. If any bin contains less than the minimum forecast count then try\n    combining this bin with whichever neighbour has the lowest sample count.\n    This process is repeated for all bins that are below the minimum forecast\n    count criterion.\n\n    2. If non-monotonicity of the observation frequency is detected, try\n    combining a pair of bins that appear non-monotonic. Only a single pair of\n    bins are combined.\n\n    3. If non-monotonicity of the observation frequency remains after trying\n    to combine a single pair of bins, replace non-monotonic bins by assuming a\n    constant observation frequency.\n    \"\"\"\n\n    def __init__(self, minimum_forecast_count=200):\n        \"\"\"\n        Initialise class for manipulating a reliability table.\n\n        Args:\n            minimum_forecast_count (int):\n                The minimum number of forecast counts in a forecast probability\n                bin for it to be used in calibration.\n                The default value of 200 is that used in Flowerdew 2014.\n        Raises:\n            ValueError: If minimum_forecast_count is less than 1.\n        References:\n            Flowerdew J. 2014. Calibrating ensemble reliability whilst\n            preserving spatial structure. Tellus, Ser. A Dyn. Meteorol.\n            Oceanogr. 66.\n        \"\"\"\n        if minimum_forecast_count < 1:\n            raise ValueError(\n                \"The minimum_forecast_count must be at least 1 as empty \"\n                \"bins in the reliability table are not handled.\"\n            )\n\n        self.minimum_forecast_count = minimum_forecast_count\n\n    @staticmethod\n    def _extract_reliability_table_components(reliability_table):\n        \"\"\"Extract reliability table components from cube\n\n        Args:\n            reliability_table (iris.cube.Cube):\n                A reliability table to be manipulated.\n\n        Returns:\n            Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray, iris.coords.DimCoord]:\n                Tuple containing the updated observation count,\n                forecast probability sum, forecast count and probability bin\n                coordinate.\n        \"\"\"\n        observation_count = reliability_table.extract(\n            iris.Constraint(table_row_name=\"observation_count\")\n        ).data\n        forecast_probability_sum = reliability_table.extract(\n            iris.Constraint(table_row_name=\"sum_of_forecast_probabilities\")\n        ).data\n        forecast_count = reliability_table.extract(\n            iris.Constraint(table_row_name=\"forecast_count\")\n        ).data\n        probability_bin_coord = reliability_table.coord(\"probability_bin\")\n        return (\n            observation_count,\n            forecast_probability_sum,\n            forecast_count,\n            probability_bin_coord,\n        )\n\n    @staticmethod\n    def _sum_pairs(array, upper):\n        \"\"\"\n        Returns a new array where a pair of values in the original array have\n        been replaced by their sum. Combines the value in the upper index with\n        the value in the upper-1 index.\n\n        Args:\n            array (numpy.ndarray):\n                Array to be modified.\n            upper (int):\n                Upper index of pair.\n\n        Returns:\n            numpy.ndarray:\n                Array where a pair of values has been replaced by their sum.\n        \"\"\"\n        result = array.copy()\n        result[upper - 1] = np.sum(array[upper - 1 : upper + 1])\n        return np.delete(result, upper)\n\n    @staticmethod\n    def _create_new_bin_coord(probability_bin_coord, upper):\n        \"\"\"\n        Create a new probability_bin coordinate by combining two adjacent\n        points on the probability_bin coordinate. This matches the combination\n        of the data for the two bins.\n\n        Args:\n            probability_bin_coord (iris.coords.DimCoord):\n                Original probability bin coordinate.\n            upper (int):\n                Upper index of pair.\n\n        Returns:\n            iris.coords.DimCoord:\n                Probability bin coordinate with updated points and bounds where\n                a pair of bins have been combined to create a single bin.\n        \"\"\"\n        old_bounds = probability_bin_coord.bounds\n        new_bounds = np.concatenate(\n            (\n                old_bounds[0 : upper - 1],\n                np.array([[old_bounds[upper - 1, 0], old_bounds[upper, 1]]]),\n                old_bounds[upper + 1 :],\n            )\n        )\n        new_points = np.mean(new_bounds, axis=1, dtype=np.float32)\n        new_bin_coord = iris.coords.DimCoord(\n            new_points, long_name=\"probability_bin\", units=1, bounds=new_bounds\n        )\n        return new_bin_coord\n\n    def _combine_undersampled_bins(\n        self,\n        observation_count,\n        forecast_probability_sum,\n        forecast_count,\n        probability_bin_coord,\n    ):\n        \"\"\"\n        Combine bins that are under-sampled i.e. that have a lower forecast\n        count than the minimum_forecast_count, so that information from these\n        poorly-sampled bins can contribute to the calibration. If multiple\n        bins are below the minimum forecast count, the bin closest to\n        meeting the minimum_forecast_count criterion is combined with whichever\n        neighbour has the lowest sample count. A new bin is then created by\n        summing the neighbouring pair of bins. This process is repeated for all\n        bins that are below the minimum forecast count criterion.\n\n        Args:\n            observation_count (numpy.ndarray):\n                Observation count extracted from reliability table.\n            forecast_probability_sum (numpy.ndarray):\n                Forecast probability sum extracted from reliability table.\n            forecast_count (numpy.ndarray):\n                Forecast count extracted from reliability table.\n            probability_bin_coord (iris.coords.DimCoord):\n                Original probability bin coordinate.\n        Returns:\n            Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray, iris.coords.DimCoord]\n                Tuple containing the updated observation count,\n                forecast probability sum, forecast count and probability bin\n                coordinate.\n\n        \"\"\"\n        while (\n            any(x < self.minimum_forecast_count for x in forecast_count)\n            and len(forecast_count) > 1\n        ):\n            forecast_count_copy = forecast_count.copy()\n\n            # Find index of the bin with the highest forecast count that is\n            # below the minimum_forecast_count by setting forecast counts\n            # greater than the minimum_forecast_count to NaN.\n            forecast_count_copy[forecast_count >= self.minimum_forecast_count] = np.nan\n            # Note for multiple occurrences of the maximum,\n            # the index of the first occurrence is returned.\n            index = np.int32(np.nanargmax(forecast_count_copy))\n\n            # Determine the upper index of the pair of bins to be combined.\n            if index == 0:\n                # Must use higher bin\n                upper = index + 1\n            elif index + 1 == len(forecast_count):\n                # Index already defines the upper bin\n                upper = index\n            else:\n                # Define upper index to include bin with lowest sample count.\n                if forecast_count[index + 1] > forecast_count[index - 1]:\n                    upper = index\n                else:\n                    upper = index + 1\n\n            forecast_count = self._sum_pairs(forecast_count, upper)\n            observation_count = self._sum_pairs(observation_count, upper)\n            forecast_probability_sum = self._sum_pairs(forecast_probability_sum, upper)\n            probability_bin_coord = self._create_new_bin_coord(\n                probability_bin_coord, upper\n            )\n\n        return (\n            observation_count,\n            forecast_probability_sum,\n            forecast_count,\n            probability_bin_coord,\n        )\n\n    def _combine_bin_pair(\n        self,\n        observation_count,\n        forecast_probability_sum,\n        forecast_count,\n        probability_bin_coord,\n    ):\n        \"\"\"\n        Combine a pair of bins when non-monotonicity of the observation\n        frequency is detected. Iterate top-down from the highest forecast\n        probability bin to the lowest probability bin when combining the bins.\n        Only allow a single pair of bins to be combined.\n\n        Args:\n            observation_count (numpy.ndarray):\n                Observation count extracted from reliability table.\n            forecast_probability_sum (numpy.ndarray):\n                Forecast probability sum extracted from reliability table.\n            forecast_count (numpy.ndarray):\n                Forecast count extracted from reliability table.\n            probability_bin_coord (iris.coords.DimCoord):\n                Original probability bin coordinate.\n\n        Returns:\n            Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray, iris.coords.DimCoord]\n                Tuple containing the updated observation count,\n                forecast probability sum, forecast count and probability bin\n                coordinate.\n        \"\"\"\n        observation_frequency = np.array(observation_count / forecast_count)\n        for upper in np.arange(len(observation_frequency) - 1, 0, -1):\n            (diff,) = np.diff(\n                [observation_frequency[upper - 1], observation_frequency[upper]]\n            )\n            if diff < 0:\n                forecast_count = self._sum_pairs(forecast_count, upper)\n                observation_count = self._sum_pairs(observation_count, upper)\n                forecast_probability_sum = self._sum_pairs(\n                    forecast_probability_sum, upper\n                )\n                probability_bin_coord = self._create_new_bin_coord(\n                    probability_bin_coord, upper\n                )\n                break\n        return (\n            observation_count,\n            forecast_probability_sum,\n            forecast_count,\n            probability_bin_coord,\n        )\n\n    @staticmethod\n    def _assume_constant_observation_frequency(observation_count, forecast_count):\n        \"\"\"\n        Decide which end bin (highest probability bin or lowest probability\n        bin) has the highest sample count. Iterate through the observation\n        frequency from the end bin with the highest sample count to the end bin\n        with the lowest sample count. Whilst iterating, compare each pair of\n        bins and, if a pair is non-monotonic, replace the value of the bin\n        closer to the lowest sample count end bin with the value of the\n        bin that is closer to the higher sample count end bin. Then calculate\n        the new observation count required to give a monotonic observation\n        frequency.\n\n        Args:\n            observation_count (numpy.ndarray):\n                Observation count extracted from reliability table.\n            forecast_count (numpy.ndarray):\n                Forecast count extracted from reliability table.\n\n        Returns:\n            numpy.ndarray:\n                Observation count computed from a monotonic observation frequency.\n\n        \"\"\"\n        observation_frequency = np.array(observation_count / forecast_count)\n\n        iterator = observation_frequency\n        operation = operator.lt\n        # Top down if forecast count is lower for lowest probability bin,\n        # than for highest probability bin.\n        if forecast_count[0] < forecast_count[-1]:\n            # Reverse array to iterate from top to bottom.\n            iterator = observation_frequency[::-1]\n            operation = operator.gt\n\n        for index, lower_bin in enumerate(iterator[:-1]):\n            (diff,) = np.diff([lower_bin, iterator[index + 1]])\n            if operation(diff, 0):\n                iterator[index + 1] = lower_bin\n\n        observation_frequency = iterator\n        if forecast_count[0] < forecast_count[-1]:\n            # Re-reverse array from bottom to top to ensure original ordering.\n            observation_frequency = iterator[::-1]\n\n        observation_count = observation_frequency * forecast_count\n        return observation_count\n\n    @staticmethod\n    def _update_reliability_table(\n        reliability_table,\n        observation_count,\n        forecast_probability_sum,\n        forecast_count,\n        probability_bin_coord,\n    ):\n        \"\"\"\n        Update the reliability table data and the probability bin coordinate.\n\n        Args:\n            reliability_table (iris.cube.Cube):\n                A reliability table to be manipulated.\n            observation_count (numpy.ndarray):\n                Observation count extracted from reliability table.\n            forecast_probability_sum (numpy.ndarray):\n                Forecast probability sum extracted from reliability table.\n            forecast_count (numpy.ndarray):\n                Forecast count extracted from reliability table.\n            probability_bin_coord (iris.coords.DimCoord):\n                Original probability bin coordinate.\n\n        Returns:\n            iris.cube.Cube:\n                Updated reliability table.\n        \"\"\"\n        final_data = np.stack(\n            [observation_count, forecast_probability_sum, forecast_count]\n        )\n        nrows, ncols = final_data.shape\n        reliability_table = reliability_table[0:nrows, 0:ncols].copy(data=final_data)\n        reliability_table.replace_coord(probability_bin_coord)\n        return reliability_table\n\n    def process(self, reliability_table):\n        \"\"\"\n        Apply the steps needed to produce a reliability diagram with a\n        monotonic observation frequency.\n\n        Args:\n            reliability_table (iris.cube.Cube):\n                A reliability table to be manipulated. The only coordinates\n                expected on this cube are a threshold coordinate,\n                a table_row_index coordinate and corresponding table_row_name\n                coordinate and a probability_bin coordinate.\n\n        Returns:\n            iris.cube.CubeList:\n                Containing a reliability table cube for each threshold in the\n                input reliablity table. For tables where monotonicity has been\n                enforced the probability_bin coordinate will have one less\n                bin than the tables that were already monotonic. If\n                under-sampled bins have been combined, then the probability_bin\n                coordinate will have been reduced until all bins have more than\n                the minimum_forecast_count if possible; a single under-sampled\n                bin will be returned if combining all bins is still insufficient\n                to reach the minimum_forecast_count.\n        \"\"\"\n        threshold_coord = find_threshold_coordinate(reliability_table)\n        reliability_table_cubelist = iris.cube.CubeList()\n        for rel_table_slice in reliability_table.slices_over(threshold_coord):\n            (\n                observation_count,\n                forecast_probability_sum,\n                forecast_count,\n                probability_bin_coord,\n            ) = self._extract_reliability_table_components(rel_table_slice)\n\n            if np.any(forecast_count < self.minimum_forecast_count):\n                (\n                    observation_count,\n                    forecast_probability_sum,\n                    forecast_count,\n                    probability_bin_coord,\n                ) = self._combine_undersampled_bins(\n                    observation_count,\n                    forecast_probability_sum,\n                    forecast_count,\n                    probability_bin_coord,\n                )\n                rel_table_slice = self._update_reliability_table(\n                    rel_table_slice,\n                    observation_count,\n                    forecast_probability_sum,\n                    forecast_count,\n                    probability_bin_coord,\n                )\n\n            # If the observation frequency is non-monotonic adjust the\n            # reliability table\n            observation_frequency = np.array(observation_count / forecast_count)\n            if not np.all(np.diff(observation_frequency) >= 0):\n                (\n                    observation_count,\n                    forecast_probability_sum,\n                    forecast_count,\n                    probability_bin_coord,\n                ) = self._combine_bin_pair(\n                    observation_count,\n                    forecast_probability_sum,\n                    forecast_count,\n                    probability_bin_coord,\n                )\n                observation_count = self._assume_constant_observation_frequency(\n                    observation_count, forecast_count\n                )\n                rel_table_slice = self._update_reliability_table(\n                    rel_table_slice,\n                    observation_count,\n                    forecast_probability_sum,\n                    forecast_count,\n                    probability_bin_coord,\n                )\n            reliability_table_cubelist.append(rel_table_slice)\n        return reliability_table_cubelist\n\n\nclass ApplyReliabilityCalibration(PostProcessingPlugin):\n\n    \"\"\"\n    A plugin for the application of reliability calibration to probability\n    forecasts. This calibration is designed to improve the reliability of\n    probability forecasts without significantly degrading their resolution.\n\n    The method implemented here is described in Flowerdew J. 2014. Calibration\n    is always applied as long as there are at least two bins within the input\n    reliability table.\n\n    References:\n    Flowerdew J. 2014. Calibrating ensemble reliability whilst\n    preserving spatial structure. Tellus, Ser. A Dyn. Meteorol.\n    Oceanogr. 66.\n    \"\"\"\n\n    def __init__(self):\n        \"\"\"\n        Initialise class for applying reliability calibration.\n\n        \"\"\"\n        self.threshold_coord = None\n\n    @staticmethod\n    def _extract_matching_reliability_table(forecast, reliability_table):\n        \"\"\"\n        Extract the reliability table with a threshold coordinate\n        matching the forecast cube.\n        If no matching reliability table is found raise an exception.\n\n        Args:\n            forecast (iris.cube.Cube):\n                The forecast to be calibrated.\n            reliability_table (iris.cube.CubeList):\n                The reliability table to use for applying calibration.\n        Returns:\n            iris.cube.Cube:\n                A reliability table who's threshold coordinate matches\n                the forecast cube.\n        Raises:\n            ValueError: If no matching reliability table is found.\n        \"\"\"\n        threshold_coord = find_threshold_coordinate(forecast)\n        coord_values = {threshold_coord.name(): threshold_coord.points}\n        constr = iris.Constraint(coord_values=coord_values)\n        if isinstance(reliability_table, iris.cube.Cube):\n            extracted = reliability_table.extract(constr)\n        else:\n            extracted = reliability_table.extract(constr, strict=True)\n        if not extracted:\n            raise ValueError(\n                \"No reliability table found to match threshold \"\n                f\"{find_threshold_coordinate(forecast).points[0]}.\"\n            )\n        return extracted\n\n    def _ensure_monotonicity_across_thresholds(self, cube):\n        \"\"\"\n        Ensures that probabilities change monotonically relative to thresholds\n        in the expected order, e.g. exceedance probabilities always remain the\n        same or decrease as the threshold values increase, below threshold\n        probabilities always remain the same or increase as the threshold\n        values increase.\n\n        Args:\n            cube (iris.cube.Cube):\n                The probability cube for which monotonicity is to be checked\n                and enforced. This cube is modified in place.\n        Raises:\n            ValueError: Threshold coordinate lacks the\n                        spp__relative_to_threshold attribute.\n        Warns:\n            UserWarning: If the probabilities must be sorted to reinstate\n                         expected monotonicity following calibration.\n        \"\"\"\n        (threshold_dim,) = cube.coord_dims(self.threshold_coord)\n        thresholding = probability_is_above_or_below(cube)\n        if thresholding is None:\n            msg = (\n                \"Cube threshold coordinate does not define whether \"\n                \"thresholding is above or below the defined thresholds.\"\n            )\n            raise ValueError(msg)\n\n        if (\n            thresholding == \"above\"\n            and not (np.diff(cube.data, axis=threshold_dim) <= 0).all()\n        ):\n            msg = (\n                \"Exceedance probabilities are not decreasing monotonically \"\n                \"as the threshold values increase. Forced back into order.\"\n            )\n            warnings.warn(msg)\n            cube.data = np.sort(cube.data, axis=threshold_dim)[::-1]\n\n        if (\n            thresholding == \"below\"\n            and not (np.diff(cube.data, axis=threshold_dim) >= 0).all()\n        ):\n            msg = (\n                \"Below threshold probabilities are not increasing \"\n                \"monotonically as the threshold values increase. Forced \"\n                \"back into order.\"\n            )\n            warnings.warn(msg)\n            cube.data = np.sort(cube.data, axis=threshold_dim)\n\n    def _calculate_reliability_probabilities(self, reliability_table):\n        \"\"\"\n        Calculates forecast probabilities and observation frequencies from the\n        reliability table. If fewer than two bins are provided, Nones are\n        returned as no calibration can be applied. Fewer than two bins can occur\n        due to repeated combination of undersampled probability bins,\n        please see :class:`.ManipulateReliabilityTable`.\n\n        Args:\n            reliability_table (iris.cube.Cube):\n                A reliability table for a single threshold from which to\n                calculate the forecast probabilities and observation\n                frequencies.\n        Returns:\n            Optional[Tuple[numpy.ndarray, numpy.ndarray]]:\n                Tuple containing forecast probabilities calculated by dividing\n                the sum of forecast probabilities by the forecast count and\n                observation frequency calculated by dividing the observation\n                count by the forecast count.\n        \"\"\"\n        observation_count = reliability_table.extract(\n            iris.Constraint(table_row_name=\"observation_count\")\n        ).data\n        forecast_count = reliability_table.extract(\n            iris.Constraint(table_row_name=\"forecast_count\")\n        ).data\n        forecast_probability_sum = reliability_table.extract(\n            iris.Constraint(table_row_name=\"sum_of_forecast_probabilities\")\n        ).data\n\n        # If there are fewer than two bins, no calibration can be applied.\n        if len(np.atleast_1d(forecast_count)) < 2:\n            return None, None\n\n        forecast_probability = np.array(forecast_probability_sum / forecast_count)\n        observation_frequency = np.array(observation_count / forecast_count)\n\n        return forecast_probability, observation_frequency\n\n    @staticmethod\n    def _interpolate(\n        forecast_threshold, reliability_probabilities, observation_frequencies\n    ):\n        \"\"\"\n        Perform interpolation of the forecast probabilities using the\n        reliability table data to produce the calibrated forecast. Where\n        necessary linear extrapolation will be applied. Any mask in place on\n        the forecast_threshold data is removed and reapplied after calibration.\n\n        Args:\n            forecast_threshold (numpy.ndarray):\n                The forecast probabilities to be calibrated.\n            reliability_probabilities (numpy.ndarray):\n                Probabilities taken from the reliability tables.\n            observation_frequencies (numpy.ndarray):\n                Observation frequencies that relate to the reliability\n                probabilities, taken from the reliability tables.\n\n        Returns:\n            numpy.ndarray:\n                The calibrated forecast probabilities. The final results are\n                clipped to ensure any extrapolation has not yielded\n                probabilities outside the range 0 to 1.\n        \"\"\"\n        shape = forecast_threshold.shape\n        mask = forecast_threshold.mask if np.ma.is_masked(forecast_threshold) else None\n\n        forecast_probabilities = np.ma.getdata(forecast_threshold).flatten()\n\n        interpolation_function = scipy.interpolate.interp1d(\n            reliability_probabilities, observation_frequencies, fill_value=\"extrapolate\"\n        )\n        interpolated = interpolation_function(forecast_probabilities.data)\n\n        interpolated = interpolated.reshape(shape).astype(np.float32)\n\n        if mask is not None:\n            interpolated = np.ma.masked_array(interpolated, mask=mask)\n\n        return np.clip(interpolated, 0, 1)\n\n    def process(self, forecast, reliability_table):\n        \"\"\"\n        Apply reliability calibration to a forecast. The reliability table\n        and the forecast cube must share an identical threshold coordinate.\n\n        Args:\n            forecast (iris.cube.Cube):\n                The forecast to be calibrated.\n            reliability_table (iris.cube.Cube or iris.cube.CubeList):\n                The reliability table to use for applying calibration.\n                x and y dimensions must be collapsed.\n        Returns:\n            iris.cube.Cube:\n                The forecast cube following calibration.\n        \"\"\"\n        self.threshold_coord = find_threshold_coordinate(forecast)\n\n        forecast_thresholds = forecast.slices_over(self.threshold_coord)\n\n        uncalibrated_thresholds = []\n        calibrated_cubes = iris.cube.CubeList()\n        for forecast_threshold in forecast_thresholds:\n            reliability_threshold = self._extract_matching_reliability_table(\n                forecast_threshold, reliability_table\n            )\n            (\n                reliability_probabilities,\n                observation_frequencies,\n            ) = self._calculate_reliability_probabilities(reliability_threshold)\n\n            if reliability_probabilities is None:\n                calibrated_cubes.append(forecast_threshold)\n                uncalibrated_thresholds.append(\n                    forecast_threshold.coord(self.threshold_coord).points[0]\n                )\n                continue\n\n            interpolated = self._interpolate(\n                forecast_threshold.data,\n                reliability_probabilities,\n                observation_frequencies,\n            )\n\n            calibrated_cubes.append(forecast_threshold.copy(data=interpolated))\n\n        calibrated_forecast = calibrated_cubes.merge_cube()\n        self._ensure_monotonicity_across_thresholds(calibrated_forecast)\n\n        if uncalibrated_thresholds:\n            msg = (\n                \"The following thresholds were not calibrated due to \"\n                \"insufficient forecast counts in reliability table bins: \"\n                \"{}\".format(uncalibrated_thresholds)\n            )\n            warnings.warn(msg)\n\n        return calibrated_forecast\n", "meta": {"hexsha": "fe25dc30488839283891e2160c5358e1a154ecf4", "size": 52804, "ext": "py", "lang": "Python", "max_stars_repo_path": "improver/calibration/reliability_calibration.py", "max_stars_repo_name": "cgsandford/improver", "max_stars_repo_head_hexsha": "3cfbf3323d3a693a9c61fec13350295b85d03676", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-02T21:17:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-02T21:17:18.000Z", "max_issues_repo_path": "improver/calibration/reliability_calibration.py", "max_issues_repo_name": "NMC-DAVE/improver", "max_issues_repo_head_hexsha": "b56379f8bd236ddf2bab31ef64af8345de856cc1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-01-24T11:29:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-11T15:16:21.000Z", "max_forks_repo_path": "improver/calibration/reliability_calibration.py", "max_forks_repo_name": "cgsandford/improver", "max_forks_repo_head_hexsha": "3cfbf3323d3a693a9c61fec13350295b85d03676", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-02T21:17:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-02T21:17:19.000Z", "avg_line_length": 42.6871463217, "max_line_length": 88, "alphanum_fraction": 0.6368646315, "include": true, "reason": "import numpy,import scipy", "num_tokens": 9753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19886229715274967}}
{"text": "\"\"\"\nOperation representation classes for the `statevec_slow` evolution type.\n\"\"\"\n#***************************************************************************************************\n# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).\n# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights\n# in this software.\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n# in compliance with the License.  You may obtain a copy of the License at\n# http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory.\n#***************************************************************************************************\n\nimport itertools as _itertools\nimport copy as _copy\n\nimport numpy as _np\nfrom scipy.sparse.linalg import LinearOperator\n\nfrom .statereps import StateRepDensePure as _StateRepDensePure\nfrom .. import basereps as _basereps\nfrom pygsti.baseobjs.statespace import StateSpace as _StateSpace\nfrom ...tools import basistools as _bt\nfrom ...tools import internalgates as _itgs\nfrom ...tools import optools as _ot\n\n\nclass OpRep(_basereps.OpRep):\n    def __init__(self, state_space):\n        self.state_space = state_space\n\n    @property\n    def dim(self):\n        return self.state_space.udim\n\n    def acton(self, state):\n        raise NotImplementedError()\n\n    def adjoint_acton(self, state):\n        raise NotImplementedError()\n\n    def aslinearoperator(self):\n        def mv(v):\n            if v.ndim == 2 and v.shape[1] == 1: v = v[:, 0]\n            in_state = _StateRepDensePure(_np.ascontiguousarray(v, complex), self.state_space, basis=None)\n            return self.acton(in_state).to_dense('Hilbert')\n\n        def rmv(v):\n            if v.ndim == 2 and v.shape[1] == 1: v = v[:, 0]\n            in_state = _StateRepDensePure(_np.ascontiguousarray(v, complex), self.state_space, basis=None)\n            return self.adjoint_acton(in_state).to_dense('Hilbert')\n        return LinearOperator((self.dim, self.dim), matvec=mv, rmatvec=rmv)  # transpose, adjoint, dot, matmat?\n\n    def copy(self):\n        return _copy.deepcopy(self)\n\n\nclass OpRepDenseUnitary(OpRep):\n    def __init__(self, mx, basis, state_space):\n        state_space = _StateSpace.cast(state_space)\n        if mx is None:\n            mx = _np.identity(state_space.udim, complex)\n        assert(mx.ndim == 2 and mx.shape[0] == state_space.udim)\n        self.basis = basis\n        self.base = _np.require(mx, requirements=['OWNDATA', 'C_CONTIGUOUS'])\n        super(OpRepDenseUnitary, self).__init__(state_space)\n\n    def base_has_changed(self):\n        pass\n\n    def to_dense(self, on_space):\n        if on_space in ('minimal', 'Hilbert'):\n            return self.base\n        elif on_space == 'HilbertSchmidt':\n            return _ot.unitary_to_superop(self.base, self.basis)\n        else:\n            raise ValueError(\"Invalid `on_space` argument: %s\" % str(on_space))\n\n    def acton(self, state):\n        return _StateRepDensePure(_np.dot(self.base, state.data), state.state_space, state.basis)\n\n    def adjoint_acton(self, state):\n        return _StateRepDensePure(_np.dot(_np.conjugate(self.base.T), state.data),\n                                  state.state_space, state.basis)\n\n    def __str__(self):\n        return \"OpRepDenseUnitary:\\n\" + str(self.base)\n\n\nclass OpRepStandard(OpRepDenseUnitary):\n    def __init__(self, name, basis, state_space):\n        std_unitaries = _itgs.standard_gatename_unitaries()\n        self.name = name\n        if self.name not in std_unitaries:\n            raise ValueError(\"Name '%s' not in standard unitaries\" % self.name)\n\n        U = std_unitaries[self.name]\n        state_space = _StateSpace.cast(state_space)\n        assert(U.shape[0] == state_space.udim)\n\n        super(OpRepStandard, self).__init__(U, basis, state_space)\n\n\n#class OpRepStochastic(OpRepDense):\n# - maybe we could add this, but it wouldn't be a \"dense\" op here,\n#   perhaps we need to change API?\n\n\nclass OpRepComposed(OpRep):\n    # exactly the same as densitymx case\n    def __init__(self, factor_op_reps, state_space):\n        #assert(len(factor_op_reps) > 0), \"Composed gates must contain at least one factor gate!\"\n        self.factors_reps = factor_op_reps\n        super(OpRepComposed, self).__init__(state_space)\n\n    def acton(self, state):\n        \"\"\" Act this gate map on an input state \"\"\"\n        for gate in self.factor_reps:\n            state = gate.acton(state)\n        return state\n\n    def adjoint_acton(self, state):\n        \"\"\" Act the adjoint of this operation matrix on an input state \"\"\"\n        for gate in reversed(self.factor_reps):\n            state = gate.adjoint_acton(state)\n        return state\n\n    def reinit_factor_op_reps(self, new_factor_op_reps):\n        self.factors_reps = new_factor_op_reps\n\n\nclass OpRepSum(OpRep):\n    # exactly the same as densitymx case\n    def __init__(self, factor_reps, state_space):\n        #assert(len(factor_reps) > 0), \"Composed gates must contain at least one factor gate!\"\n        self.factor_reps = factor_reps\n        super(OpRepSum, self).__init__(state_space)\n\n    def acton(self, state):\n        \"\"\" Act this gate map on an input state \"\"\"\n        output_state = _StateRepDensePure(_np.zeros(state.data.shape, complex), state.state_space, state.basis)\n        for f in self.factor_reps:\n            output_state.data += f.acton(state).data\n        return output_state\n\n    def adjoint_acton(self, state):\n        \"\"\" Act the adjoint of this operation matrix on an input state \"\"\"\n        output_state = _StateRepDensePure(_np.zeros(state.data.shape, complex), state.state_space, state.basis)\n        for f in self.factor_reps:\n            output_state.data += f.adjoint_acton(state).data\n        return output_state\n\n\nclass OpRepEmbedded(OpRep):\n\n    def __init__(self, state_space, target_labels, embedded_rep):\n\n        state_space = _StateSpace.cast(state_space)\n        iTensorProdBlks = [state_space.label_tensor_product_block_index(label) for label in target_labels]\n        # index of tensor product block (of state space) a bit label is part of\n        if len(set(iTensorProdBlks)) != 1:\n            raise ValueError(\"All qubit labels of a multi-qubit operation must correspond to the\"\n                             \" same tensor-product-block of the state space -- checked previously\")  # pragma: no cover # noqa\n\n        iTensorProdBlk = iTensorProdBlks[0]  # because they're all the same (tested above) - this is \"active\" block\n        tensorProdBlkLabels = state_space.tensor_product_block_labels(iTensorProdBlk)\n        # count possible *state-vector-space* indices of each component of the tensor product block\n        numBasisEls = _np.array([state_space.label_udimension(l) for l in tensorProdBlkLabels], _np.int64)\n\n        # Separate the components of the tensor product that are not operated on, i.e. that our\n        # final map just acts as identity w.r.t.\n        labelIndices = [tensorProdBlkLabels.index(label) for label in target_labels]\n        actionInds = _np.array(labelIndices, _np.int64)\n        assert(_np.product([numBasisEls[i] for i in actionInds]) == embedded_rep.dim), \\\n            \"Embedded operation has dimension (%d) inconsistent with the given target labels (%s)\" % (\n                embedded_rep.dim, str(target_labels))\n\n        #dim = state_space.udim\n        nBlocks = state_space.num_tensor_product_blocks\n        iActiveBlock = iTensorProdBlk\n        nComponents = len(state_space.tensor_product_block_labels(iActiveBlock))\n        embeddedDim = embedded_rep.dim  # a *unitary* dim - see .dim property above\n        blocksizes = _np.array([_np.product(state_space.tensor_product_block_udimensions(k))\n                                for k in range(nBlocks)], _np.int64)\n\n        self.target_labels = target_labels\n        self.embedded_rep = embedded_rep\n        self.num_basis_els = numBasisEls\n        self.action_inds = actionInds\n        self.blocksizes = blocksizes\n\n        num_basis_els_noop_blankaction = self.num_basis_els.copy()\n        for i in self.action_inds: num_basis_els_noop_blankaction[i] = 1\n        self.basisInds_noop_blankaction = [list(range(n)) for n in num_basis_els_noop_blankaction]\n\n        # multipliers to go from per-label indices to tensor-product-block index\n        # e.g. if map(len,basisInds) == [1,4,4] then multipliers == [ 16 4 1 ]\n        self.multipliers = _np.array(_np.flipud(_np.cumprod([1] + list(\n            reversed(list(self.num_basis_els[1:]))))), _np.int64)\n        self.basisInds_action = [list(range(self.num_basis_els[i])) for i in self.action_inds]\n\n        self.embeddedDim = embeddedDim\n        self.ncomponents = nComponents  # number of components in \"active\" block\n        self.active_block_index = iActiveBlock\n        self.nblocks = nBlocks\n        self.offset = sum(blocksizes[0:self.active_block_index])\n        super(OpRepEmbedded, self).__init__(state_space)\n\n    def _acton_other_blocks_trivially(self, output_state, state):\n        offset = 0\n        for iBlk, blockSize in enumerate(self.blocksizes):\n            if iBlk != self.active_block_index:\n                output_state.data[offset:offset + blockSize] = state.data[offset:offset + blockSize]  # identity op\n            offset += blockSize\n\n    def acton(self, state):\n        output_state = _StateRepDensePure(_np.zeros(state.data.shape, complex), state.state_space, state.basis)\n        offset = self.offset  # if rel_to_block else self.offset (rel_to_block == False here)\n\n        for b in _itertools.product(*self.basisInds_noop_blankaction):  # zeros in all action-index locations\n            vec_index_noop = _np.dot(self.multipliers, tuple(b))\n            inds = []\n            for op_b in _itertools.product(*self.basisInds_action):\n                vec_index = vec_index_noop\n                for i, bInd in zip(self.action_inds, op_b):\n                    #b[i] = bInd #don't need to do this; just update vec_index:\n                    vec_index += self.multipliers[i] * bInd\n                inds.append(offset + vec_index)\n            embedded_instate = _StateRepDensePure(state.data[inds],\n                                                  state.state_space.create_subspace(self.target_labels), basis=None)\n            embedded_outstate = self.embedded_rep.acton(embedded_instate)\n            output_state.data[inds] += embedded_outstate.data\n\n        #act on other blocks trivially:\n        self._acton_other_blocks_trivially(output_state, state)\n        return output_state\n\n    def adjoint_acton(self, state):\n        \"\"\" Act the adjoint of this gate map on an input state \"\"\"\n        #NOTE: Same as acton except uses 'adjoint_acton(...)' below\n        output_state = _StateRepDensePure(_np.zeros(state.data.shape, complex), state.state_space, state.basis)\n        offset = self.offset  # if rel_to_block else self.offset (rel_to_block == False here)\n\n        for b in _itertools.product(*self.basisInds_noop_blankaction):  # zeros in all action-index locations\n            vec_index_noop = _np.dot(self.multipliers, tuple(b))\n            inds = []\n            for op_b in _itertools.product(*self.basisInds_action):\n                vec_index = vec_index_noop\n                for i, bInd in zip(self.action_inds, op_b):\n                    #b[i] = bInd #don't need to do this; just update vec_index:\n                    vec_index += self.multipliers[i] * bInd\n                inds.append(offset + vec_index)\n            embedded_instate = _StateRepDensePure(state.data[inds],\n                                                  state.state_space.create_subspace(self.target_labels), basis=None)\n            embedded_outstate = self.embedded_rep.adjoint_acton(embedded_instate)\n            output_state.data[inds] += embedded_outstate.data\n\n        #act on other blocks trivially:\n        self._acton_other_blocks_trivially(output_state, state)\n        return output_state\n\n\nclass OpRepExpErrorgen(OpRep):\n\n    def __init__(self, errorgen_rep):\n        state_space = errorgen_rep.state_space\n        self.errorgen_rep = errorgen_rep\n        super(OpRepExpErrorgen, self).__init__(state_space)\n\n    def errgenrep_has_changed(self, onenorm_upperbound):\n        pass\n\n    def acton(self, state):\n        raise AttributeError(\"Cannot currently act with statevec.OpRepExpErrorgen - for terms only!\")\n\n    def adjoint_acton(self, state):\n        raise AttributeError(\"Cannot currently act with statevec.OpRepExpErrorgen - for terms only!\")\n\n\nclass OpRepRepeated(OpRep):\n    def __init__(self, rep_to_repeat, num_repetitions, state_space):\n        state_space = _StateSpace.cast(state_space)\n        self.repeated_rep = rep_to_repeat\n        self.num_repetitions = num_repetitions\n        super(OpRepRepeated, self).__init__(state_space)\n\n    def acton(self, state):\n        \"\"\" Act this gate map on an input state \"\"\"\n        for i in range(self.num_repetitions):\n            state = self.repeated_rep.acton(state)\n        return state\n\n    def adjoint_acton(self, state):\n        \"\"\" Act the adjoint of this operation matrix on an input state \"\"\"\n        for i in range(self.num_repetitions):\n            state = self.repeated_rep.adjoint_acton(state)\n        return state\n\n\nclass OpRepLindbladErrorgen(OpRep):\n    def __init__(self, lindblad_coefficient_blocks, state_space):\n        super(OpRepLindbladErrorgen, self).__init__(state_space)\n        self.Lterms = None\n        self.Lterm_coeffs = None\n        self.lindblad_coefficient_blocks = lindblad_coefficient_blocks\n", "meta": {"hexsha": "87e939e0d06c16868eef6b3ffbd30d7266dd7636", "size": 13560, "ext": "py", "lang": "Python", "max_stars_repo_path": "pygsti/evotypes/statevec_slow/opreps.py", "max_stars_repo_name": "pyGSTi-Developers/pyGSTi", "max_stars_repo_head_hexsha": "bfedc1de4d604f14b0f958615776fb80ddb59e33", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pygsti/evotypes/statevec_slow/opreps.py", "max_issues_repo_name": "pyGSTi-Developers/pyGSTi", "max_issues_repo_head_hexsha": "bfedc1de4d604f14b0f958615776fb80ddb59e33", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pygsti/evotypes/statevec_slow/opreps.py", "max_forks_repo_name": "pyGSTi-Developers/pyGSTi", "max_forks_repo_head_hexsha": "bfedc1de4d604f14b0f958615776fb80ddb59e33", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.4590163934, "max_line_length": 126, "alphanum_fraction": 0.6619469027, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.19886229715274964}}
{"text": "# This File is for all encoder models\r\nfrom torch import nn\r\nfrom torch.nn import functional as F\r\nimport torch\r\nimport numpy as np\r\n\r\n\r\n# Encoder for AutoEncoder\r\nclass Encoder_AE(nn.Module):\r\n    def __init__(self, M, P):\r\n        super(Encoder_AE, self).__init__()\r\n        self.M = M  # The number of RF nodes\r\n        self.N = int(M*(M-1))  # The number of links\r\n        self.P = P  # Each node has P measurement positions\r\n        # input size (CxWxH) = (NxPxP)\r\n        self.conv1 = self.conv_layer(self.N, 32, 3, padding='same')\r\n        self.conv2 = self.conv_layer(32, 64, 3, padding='same')\r\n        self.conv3 = self.conv_layer(64, 128, 3, padding='same')  # shape: [batch_size, 128, P, P]\r\n        self.conv4 = self.conv_layer(128, 128, 3, padding='valid')  # shape: [batch_size, 128, P-2, P-2]\r\n        self.conv5 = self.conv_layer(128, self.N, 1, padding='valid', activation='Linear',\r\n                                     batch_norm=False)  # shape: [batch_size, N, P-2, P-2]\r\n\r\n    def conv_layer(self, in_channels, out_channels, kernel_size, stride=1, padding=0, activation='LeakyReLU',\r\n                   batch_norm=True):\r\n        layer_out = []\r\n        bias = True\r\n        if batch_norm:\r\n            bias = False\r\n        layer_out.append(nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, bias=bias))\r\n        if batch_norm:\r\n            layer_out.append(nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.01))\r\n        if activation == 'LeakyReLU':\r\n            layer_out.append(nn.LeakyReLU(0.3))\r\n        elif activation == 'ReLU':\r\n            layer_out.append(nn.ReLU())\r\n        elif activation == 'Linear':\r\n            pass\r\n        elif activation == 'Sigmoid':\r\n            layer_out.append(nn.Sigmoid())\r\n        else:\r\n            raise NotImplementedError('Activation Function {} not understood.'.format(activation))\r\n        return nn.Sequential(*layer_out)\r\n\r\n    def forward(self, x):\r\n        out = self.conv1(x)\r\n        out = self.conv2(out)\r\n        out = self.conv3(out)\r\n        out = self.conv4(out)\r\n        out = self.conv5(out)\r\n        return out\r\n\r\n\r\n# Encoder for Gaussian VAE\r\nclass Encoder_GVAE(nn.Module):\r\n    def __init__(self, M, P):\r\n        super(Encoder_GVAE, self).__init__()\r\n        self.M = M  # The number of RF nodes\r\n        self.N = int(M*(M-1))  # The number of links\r\n        self.P = P  # Each node has P measurement positions\r\n        # input size (CxWxH) = (NxPxP)\r\n        self.conv1 = self.conv_layer(self.N, 32, 3, padding='same')\r\n        self.conv2 = self.conv_layer(32, 64, 3, padding='same')\r\n        self.conv3 = self.conv_layer(64, 128, 3, padding='same')  # shape: [batch_size, 128, P, P]\r\n        self.conv4 = self.conv_layer(128, 128, 3, padding='valid')  # shape: [batch_size, 128, P-2, P-2]\r\n        self.conv5_mu = self.conv_layer(128, self.N, 1, padding='valid', activation='Linear',\r\n                                        batch_norm=False)  # shape: [batch_size, N, P-2, P-2]\r\n        self.conv5_logvar = self.conv_layer(128, self.N, 1, padding='valid', activation='Linear',\r\n                                            batch_norm=False)  # shape: [batch_size, N, P-2, P-2]\r\n\r\n    def conv_layer(self, in_channels, out_channels, kernel_size, stride=1, padding=0, activation='LeakyReLU',\r\n                   batch_norm=True):\r\n        layer_out = []\r\n        bias = True\r\n        if batch_norm:\r\n            bias = False\r\n        layer_out.append(nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, bias=bias))\r\n        if batch_norm:\r\n            layer_out.append(nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.01))\r\n        if activation == 'LeakyReLU':\r\n            layer_out.append(nn.LeakyReLU(0.3))\r\n        elif activation == 'ReLU':\r\n            layer_out.append(nn.ReLU())\r\n        elif activation == 'Linear':\r\n            pass\r\n        elif activation == 'Sigmoid':\r\n            layer_out.append(nn.Sigmoid())\r\n        else:\r\n            raise NotImplementedError('Activation Function {} not understood.'.format(activation))\r\n        return nn.Sequential(*layer_out)\r\n\r\n    def encode(self, x):\r\n        out = self.conv1(x)\r\n        out = self.conv2(out)\r\n        out = self.conv3(out)\r\n        out = self.conv4(out)\r\n        mu = self.conv5_mu(out)\r\n        logvar = self.conv5_logvar(out)\r\n        return mu, logvar\r\n\r\n    def reparameterize(self, mu, logvar):\r\n        std = torch.exp(0.5 * logvar)\r\n        eps = torch.randn_like(std)\r\n        return mu + eps * std\r\n\r\n    def kl_div(self, mu, logvar):\r\n        # KL  = 1/2(- logvar + var + m^2  - 1 )\r\n        kld = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())\r\n        kld = kld/(self.N * (self.P - 2) * (self.P - 2))\r\n        return kld\r\n\r\n    def forward(self, x):\r\n        mu, logvar = self.encode(x)\r\n        z = self.reparameterize(mu, logvar)\r\n        kld = self.kl_div(mu, logvar)\r\n        return z, kld, mu, logvar\r\n\r\n\r\n# Encoder for Laplacian VAE\r\nclass Encoder_LVAE(nn.Module):\r\n    def __init__(self, M, P):\r\n        super(Encoder_LVAE, self).__init__()\r\n        self.M = M  # The number of RF nodes\r\n        self.N = int(M*(M-1))  # The number of links\r\n        self.P = P  # Each node has P measurement positions\r\n        # input size (CxWxH) = (NxPxP)\r\n        self.conv1 = self.conv_layer(self.N, 32, 3, padding='same')\r\n        self.conv2 = self.conv_layer(32, 64, 3, padding='same')\r\n        self.conv3 = self.conv_layer(64, 128, 3, padding='same')  # shape: [batch_size, 128, P, P]\r\n        self.conv4 = self.conv_layer(128, 128, 3, padding='valid')  # shape: [batch_size, 128, P-2, P-2]\r\n        self.conv5_mu = self.conv_layer(128, self.N, 1, padding='valid', activation='Linear',\r\n                                        batch_norm=False)  # shape: [batch_size, N, P-2, P-2]\r\n        self.conv5_logb = self.conv_layer(128, self.N, 1, padding='valid', activation='Linear',\r\n                                          batch_norm=False)  # shape: [batch_size, N, P-2, P-2]\r\n\r\n    def conv_layer(self, in_channels, out_channels, kernel_size, stride=1, padding=0, activation='LeakyReLU',\r\n                   batch_norm=True):\r\n        layer_out = []\r\n        bias = True\r\n        if batch_norm:\r\n            bias = False\r\n        layer_out.append(nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, bias=bias))\r\n        if batch_norm:\r\n            layer_out.append(nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.01))\r\n        if activation == 'LeakyReLU':\r\n            layer_out.append(nn.LeakyReLU(0.3))\r\n        elif activation == 'ReLU':\r\n            layer_out.append(nn.ReLU())\r\n        elif activation == 'Linear':\r\n            pass\r\n        elif activation == 'Sigmoid':\r\n            layer_out.append(nn.Sigmoid())\r\n        else:\r\n            raise NotImplementedError('Activation Function {} not understood.'.format(activation))\r\n        return nn.Sequential(*layer_out)\r\n\r\n    def encode(self, x):\r\n        out = self.conv1(x)\r\n        out = self.conv2(out)\r\n        out = self.conv3(out)\r\n        out = self.conv4(out)\r\n        mu = self.conv5_mu(out)\r\n        logb = self.conv5_logb(out)\r\n        return mu, logb\r\n\r\n    def reparameterize(self, mu, logb):\r\n        eps1 = torch.rand_like(mu)\r\n        eps2 = torch.rand_like(mu)\r\n        eps = -torch.log(eps1 + 1e-10) - (-torch.log(eps2 + 1e-10))\r\n        sample = mu + eps * logb.exp()  # Laplace(mu, b)\r\n        return sample\r\n\r\n    def kl_div(self, mu, logb):\r\n        b = logb.exp()\r\n        # KL: sqrt(2)*b*exp(-|mu|/b) + sqrt(2)*|mu| - log(b) - log(2)/2 - 1\r\n        kld = torch.sum(2 ** 0.5 * b * torch.exp(-mu.abs() / b) + 2 ** 0.5 * mu.abs() - logb - 0.5 * np.log(2) - 1.0)\r\n        kld = kld / (self.N * (self.P - 2) * (self.P - 2))\r\n        return kld\r\n\r\n    def forward(self, x):\r\n        mu, logb = self.encode(x)\r\n        z = self.reparameterize(mu, logb)\r\n        kld = self.kl_div(mu, logb)\r\n        return z, kld, mu, logb\r\n\r\n\r\n# Encoder for Gaussian Mixture VAE\r\nclass Encoder_GMVAE(nn.Module):\r\n    def __init__(self, M, P):\r\n        super(Encoder_GMVAE, self).__init__()\r\n        self.M = M  # The number of RF nodes\r\n        self.N = int(M*(M-1))  # The number of links\r\n        self.P = P  # Each node has P measurement positions\r\n        self.n_classes = 3  # Number of noise levels\r\n        # input size (CxWxH) = (NxPxP)\r\n        # encode input RSS\r\n        self.conv1 = self.conv_layer(self.N, 32, 3, padding='same')\r\n        self.conv2 = self.conv_layer(32, 64, 3, padding='same')\r\n        self.conv3 = self.conv_layer(64, 128, 3, padding='same')  # shape: [batch_size, 128, P, P]\r\n        self.conv4 = self.conv_layer(128, 128, 3, padding='valid')  # shape: [batch_size, 128, P-2, P-2]\r\n        # Generate h, w and c\r\n        self.conv5_h_mu = self.conv_layer(128, self.N, 1, padding='valid', activation='Linear',\r\n                                          batch_norm=False)  # shape: [batch_size, N, P-2, P-2]\r\n        self.conv5_h_logvar = self.conv_layer(128, self.N, 1, padding='valid', activation='Linear',\r\n                                              batch_norm=False)  # shape: [batch_size, N, P-2, P-2]\r\n        self.conv5_w_mu = self.conv_layer(128, 32, 3, padding='valid', activation='Linear',\r\n                                          batch_norm=False)  # shape: [batch_size, 32, P-4, P-4]\r\n        self.conv5_w_logvar = self.conv_layer(128, 32, 3, padding='valid', activation='Linear',\r\n                                              batch_norm=False)  # shape: [batch_size, 32, P-4, P-4]\r\n        self.qc = nn.Linear(128*(self.P-2)*(self.P-2), self.n_classes)   # [batch_size, n_classes]\r\n        # prior generator\r\n        self.deconv1 = self.deconv_layer(32, 16, 3, padding=0)  # shape: [batch_size, 16, P-2, P-2]\r\n        # prior h for each cluster\r\n        self.conv_ph_mu = nn.ModuleList(\r\n            [nn.Conv2d(16, self.N, 1, padding='valid', bias=True) for i in range(self.n_classes)])  # shape: [batch_size, N, P-2, P-2]\r\n        self.conv_ph_logvar = nn.ModuleList(\r\n            [nn.Conv2d(16, self.N, 1, padding='valid', bias=True) for i in range(self.n_classes)])  # shape: [batch_size, N, P-2, P-2]\r\n\r\n    def conv_layer(self, in_channels, out_channels, kernel_size, stride=1, padding=0, activation='LeakyReLU',\r\n                   batch_norm=True):\r\n        layer_out = []\r\n        bias = True\r\n        if batch_norm:\r\n            bias = False\r\n        layer_out.append(nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, bias=bias))\r\n        if batch_norm:\r\n            layer_out.append(nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.01))\r\n        if activation == 'LeakyReLU':\r\n            layer_out.append(nn.LeakyReLU(0.3))\r\n        elif activation == 'ReLU':\r\n            layer_out.append(nn.ReLU())\r\n        elif activation == 'Linear':\r\n            pass\r\n        elif activation == 'Sigmoid':\r\n            layer_out.append(nn.Sigmoid())\r\n        else:\r\n            raise NotImplementedError('Activation Function {} not understood.'.format(activation))\r\n        return nn.Sequential(*layer_out)\r\n\r\n    def deconv_layer(self, in_channels, out_channels, kernel_size, stride=1, padding=0, activation='LeakyReLU',\r\n                     batch_norm=True):\r\n        layer_out = []\r\n        bias = True\r\n        if batch_norm:\r\n            bias = False\r\n        layer_out.append(nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride, padding, bias=bias))\r\n        if batch_norm:\r\n            layer_out.append(nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.01))\r\n        if activation == 'LeakyReLU':\r\n            layer_out.append(nn.LeakyReLU(0.3))\r\n        elif activation == 'ReLU':\r\n            layer_out.append(nn.ReLU())\r\n        elif activation == 'Linear':\r\n            pass\r\n        elif activation == 'Sigmoid':\r\n            layer_out.append(nn.Sigmoid())\r\n        else:\r\n            raise NotImplementedError('Activation Function {} not understood.'.format(activation))\r\n        return nn.Sequential(*layer_out)\r\n\r\n    def encode1(self, x):\r\n        out = self.conv1(x)\r\n        out = self.conv2(out)\r\n        out = self.conv3(out)\r\n        out = self.conv4(out)\r\n        return out\r\n\r\n    def infer_h(self, x):\r\n        h_mu = self.conv5_h_mu(x)\r\n        h_logvar = self.conv5_h_logvar(x)\r\n        return h_mu, h_logvar\r\n\r\n    def infer_w(self, x):\r\n        w_mu = self.conv5_w_mu(x)\r\n        w_logvar = self.conv5_w_logvar(x)\r\n        return w_mu, w_logvar\r\n\r\n    def infer_c(self, x):\r\n        x = torch.flatten(x, start_dim=1)\r\n        qc = F.softmax(self.qc(x), dim=-1)\r\n        return qc\r\n\r\n    def q_net(self, x):\r\n        out = self.encode1(x)\r\n        h_mu, h_logvar = self.infer_h(out)\r\n        w_mu, w_logvar = self.infer_w(out)\r\n        qc = self.infer_c(out)\r\n        return h_mu, h_logvar, w_mu, w_logvar, qc\r\n\r\n    def reparameterize(self, mu, logvar):\r\n        std = torch.exp(0.5 * logvar)\r\n        eps = torch.randn_like(std)\r\n        return mu + eps * std\r\n\r\n    def priorGenerator(self, w_sample):\r\n        # w_sample: [batch_size, 32, P-4, P-4]\r\n        batchSize = w_sample.size(0)\r\n        h = self.deconv1(w_sample)\r\n        ph_mu = torch.empty((batchSize, self.N, self.P-2, self.P-2, self.n_classes), device=w_sample.get_device(), requires_grad=False)\r\n        ph_logvar = torch.empty((batchSize, self.N, self.P-2, self.P-2, self.n_classes), device=w_sample.get_device(), requires_grad=False)\r\n        for i in range(self.n_classes):\r\n            ph_mu[:, :, :, :, i] = self.conv_ph_mu[i](h)\r\n            ph_logvar[:, :, :, :, i] = self.conv_ph_logvar[i](h)\r\n        return ph_mu, ph_logvar\r\n\r\n    def kl_w_loss(self, w_mu, w_logvar):\r\n        # w_mu, w_logvar: [batch_size, 32, P-4, P-4]\r\n        # KL  = 1/2(- logvar + var + m^2  - 1 )\r\n        kl = -0.5 * torch.sum(1 + w_logvar - w_mu.pow(2) - w_logvar.exp())/(32 * (self.P-4) * (self.P-4))\r\n        return kl\r\n\r\n    def kl_c_loss(self, prob_c):\r\n        # prob_c [batch_size, n_classes]\r\n        kl = torch.sum(prob_c * (torch.log(self.n_classes * prob_c + 1e-10)))\r\n        kl = torch.max(kl, torch.as_tensor(0.5, device=prob_c.get_device()))\r\n        return kl\r\n\r\n    def kl_h_loss(self, h_mu, h_logvar, ph_mu, ph_logvar, prob_c):\r\n        # h_mu, h_logvar: [batch_size, N, P-2, P-2]\r\n        # ph_mu, ph_logvar: [batch_size, N, P-2, P-2, n_classes]\r\n        # prob_c: [batch_size, n_classes]\r\n        h_mu = h_mu.unsqueeze(-1)\r\n        h_mu = h_mu.expand(-1, self.N, self.P-2, self.P-2, self.n_classes)\r\n        h_logvar = h_logvar.unsqueeze(-1)\r\n        h_logvar = h_logvar.expand(-1, self.N, self.P-2, self.P-2, self.n_classes)\r\n        # KL  = 1/2 * (logvar2 - logvar1 + (var1 + (m1-m2)^2)/var2  - 1)\r\n        # KL(h||ph)\r\n        # shape: [batch_size, N, P-2, P-2, n_classes]\r\n        KLD_QX_PX = 0.5 * (ph_logvar - h_logvar + (h_logvar.exp() + (h_mu - ph_mu).pow(2)) / ph_logvar.exp() - 1)\r\n        # shape: [batch_size, n_classes]\r\n        KLD_QX_PX = torch.sum(KLD_QX_PX, dim=(1, 2, 3))\r\n        kl = torch.sum(KLD_QX_PX * prob_c)/(self.N * (self.P-2) * (self.P-2))\r\n        return kl\r\n\r\n    def forward(self, x):\r\n        h_mu, h_logvar, w_mu, w_logvar, prob_c = self.q_net(x)\r\n        h_sample = self.reparameterize(h_mu, h_logvar)    # h_sample: [batch_size, N, P-2, P-2]\r\n        w_sample = self.reparameterize(w_mu, w_logvar)    # w_sample: [batch_size, 32, P-4, P-4]\r\n        ph_mu, ph_logvar = self.priorGenerator(w_sample)  # ph_mu, ph_logvar: [batch_size, N, P-2, P-2, n_classes]\r\n        kl_loss_w = self.kl_w_loss(w_mu, w_logvar)\r\n        kl_loss_c = self.kl_c_loss(prob_c)\r\n        kl_loss_h = self.kl_h_loss(h_mu, h_logvar, ph_mu, ph_logvar, prob_c)\r\n        kld = kl_loss_w + kl_loss_c + kl_loss_h\r\n        return h_sample, kld, kl_loss_w, kl_loss_h, kl_loss_c\r\n\r\n\r\n# Encoder for Laplacian Mixture VAE\r\nclass Encoder_LMVAE(nn.Module):\r\n    def __init__(self, M, P):\r\n        super(Encoder_LMVAE, self).__init__()\r\n        self.M = M  # The number of RF nodes\r\n        self.N = int(M*(M-1))  # The number of links\r\n        self.P = P  # Each node has P measurement positions\r\n        self.n_classes = 3  # Number of noise levels\r\n        # input size (CxWxH) = (NxPxP)\r\n        # encode input RSS\r\n        self.conv1 = self.conv_layer(self.N, 32, 3, padding='same')\r\n        self.conv2 = self.conv_layer(32, 64, 3, padding='same')\r\n        self.conv3 = self.conv_layer(64, 128, 3, padding='same')  # shape: [batch_size, 128, P, P]\r\n        self.conv4 = self.conv_layer(128, 128, 3, padding='valid')  # shape: [batch_size, 128, P-2, P-2]\r\n        # Generate h, w and c\r\n        self.conv5_h_mu = self.conv_layer(128, self.N, 1, padding='valid', activation='Linear',\r\n                                          batch_norm=False)  # shape: [batch_size, N, P-2, P-2]\r\n        self.conv5_h_logb = self.conv_layer(128, self.N, 1, padding='valid', activation='Linear',\r\n                                            batch_norm=False)  # shape: [batch_size, N, P-2, P-2]\r\n        self.conv5_w_mu = self.conv_layer(128, 32, 3, padding='valid', activation='Linear',\r\n                                          batch_norm=False)  # shape: [batch_size, 32, P-4, P-4]\r\n        self.conv5_w_logb = self.conv_layer(128, 32, 3, padding='valid', activation='Linear',\r\n                                            batch_norm=False)  # shape: [batch_size, 32, P-4, P-4]\r\n        self.qc = nn.Linear(128*(self.P-2)*(self.P-2), self.n_classes)   # [batch_size, n_classes]\r\n        # prior generator\r\n        self.deconv1 = self.deconv_layer(32, 16, 3, padding=0)  # shape: [batch_size, 16, P-2, P-2]\r\n        # prior h for each cluster\r\n        self.conv_ph_mu = nn.ModuleList(\r\n            [nn.Conv2d(16, self.N, 1, padding='valid', bias=True) for i in range(self.n_classes)])  # shape: [batch_size, N, P-2, P-2]\r\n        self.conv_ph_logb = nn.ModuleList(\r\n            [nn.Conv2d(16, self.N, 1, padding='valid', bias=True) for i in range(self.n_classes)])  # shape: [batch_size, N, P-2, P-2]\r\n\r\n    def conv_layer(self, in_channels, out_channels, kernel_size, stride=1, padding=0, activation='LeakyReLU',\r\n                   batch_norm=True):\r\n        layer_out = []\r\n        bias = True\r\n        if batch_norm:\r\n            bias = False\r\n        layer_out.append(nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, bias=bias))\r\n        if batch_norm:\r\n            layer_out.append(nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.01))\r\n        if activation == 'LeakyReLU':\r\n            layer_out.append(nn.LeakyReLU(0.3))\r\n        elif activation == 'ReLU':\r\n            layer_out.append(nn.ReLU())\r\n        elif activation == 'Linear':\r\n            pass\r\n        elif activation == 'Sigmoid':\r\n            layer_out.append(nn.Sigmoid())\r\n        else:\r\n            raise NotImplementedError('Activation Function {} not understood.'.format(activation))\r\n        return nn.Sequential(*layer_out)\r\n\r\n    def deconv_layer(self, in_channels, out_channels, kernel_size, stride=1, padding=0, activation='LeakyReLU',\r\n                     batch_norm=True):\r\n        layer_out = []\r\n        bias = True\r\n        if batch_norm:\r\n            bias = False\r\n        layer_out.append(nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride, padding, bias=bias))\r\n        if batch_norm:\r\n            layer_out.append(nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.01))\r\n        if activation == 'LeakyReLU':\r\n            layer_out.append(nn.LeakyReLU(0.3))\r\n        elif activation == 'ReLU':\r\n            layer_out.append(nn.ReLU())\r\n        elif activation == 'Linear':\r\n            pass\r\n        elif activation == 'Sigmoid':\r\n            layer_out.append(nn.Sigmoid())\r\n        else:\r\n            raise NotImplementedError('Activation Function {} not understood.'.format(activation))\r\n        return nn.Sequential(*layer_out)\r\n\r\n    def encode1(self, x):\r\n        out = self.conv1(x)\r\n        out = self.conv2(out)\r\n        out = self.conv3(out)\r\n        out = self.conv4(out)\r\n        return out\r\n\r\n    def infer_h(self, x):\r\n        h_mu = self.conv5_h_mu(x)\r\n        h_logb = self.conv5_h_logb(x)\r\n        return h_mu, h_logb\r\n\r\n    def infer_w(self, x):\r\n        w_mu = self.conv5_w_mu(x)\r\n        w_logb = self.conv5_w_logb(x)\r\n        return w_mu, w_logb\r\n\r\n    def infer_c(self, x):\r\n        x = torch.flatten(x, start_dim=1)\r\n        qc = F.softmax(self.qc(x), dim=-1)\r\n        return qc\r\n\r\n    def q_net(self, x):\r\n        out = self.encode1(x)\r\n        h_mu, h_logb = self.infer_h(out)\r\n        w_mu, w_logb = self.infer_w(out)\r\n        qc = self.infer_c(out)\r\n        return h_mu, h_logb, w_mu, w_logb, qc\r\n\r\n    def reparameterize(self, mu, logb):\r\n        eps1 = torch.rand_like(mu)\r\n        eps2 = torch.rand_like(mu)\r\n        eps = -torch.log(eps1 + 1e-10) - (-torch.log(eps2 + 1e-10))\r\n        sample = mu + eps * logb.exp()  # Laplace(mu, b)\r\n        return sample\r\n\r\n    def priorGenerator(self, w_sample):\r\n        # w_sample: [batch_size, 32, P-4, P-4]\r\n        batchSize = w_sample.size(0)\r\n        h = self.deconv1(w_sample)\r\n        ph_mu = torch.empty((batchSize, self.N, self.P-2, self.P-2, self.n_classes), device=w_sample.get_device(), requires_grad=False)\r\n        ph_logb = torch.empty((batchSize, self.N, self.P-2, self.P-2, self.n_classes), device=w_sample.get_device(), requires_grad=False)\r\n        for i in range(self.n_classes):\r\n            ph_mu[:, :, :, :, i] = self.conv_ph_mu[i](h)\r\n            ph_logb[:, :, :, :, i] = self.conv_ph_logb[i](h)\r\n        return ph_mu, ph_logb\r\n\r\n    def kl_w_loss(self, w_mu, w_logb):\r\n        b = w_logb.exp()\r\n        logb = w_logb\r\n        mu = w_mu\r\n        # KL: sqrt(2)*b*exp(-|mu|/b) + sqrt(2)*|mu| - log(b) - log(2)/2 - 1\r\n        kl = torch.sum(2 ** 0.5 * b * torch.exp(-mu.abs() / b) + 2 ** 0.5 * mu.abs() - logb - 0.5 * np.log(2) - 1.0)/(32 * (self.P-4) * (self.P-4))\r\n        return kl\r\n\r\n    def kl_c_loss(self, prob_c):\r\n        # prob_c [batch_size, n_classes]\r\n        kl = torch.sum(prob_c * (torch.log(self.n_classes * prob_c + 1e-10)))\r\n        kl = torch.max(kl, torch.as_tensor(0.5, device=prob_c.get_device()))\r\n        return kl\r\n\r\n    def kl_h_loss(self, h_mu, h_logb, ph_mu, ph_logb, prob_c):\r\n        # h_mu, h_logb: [batch_size, N, P-2, P-2]\r\n        # ph_mu, ph_logb: [batch_size, N, P-2, P-2, n_classes]\r\n        # prob_c: [batch_size, n_classes]\r\n        h_mu = h_mu.unsqueeze(-1)\r\n        h_mu = h_mu.expand(-1, self.N, self.P-2, self.P-2, self.n_classes)\r\n        h_logb = h_logb.unsqueeze(-1)\r\n        h_logb = h_logb.expand(-1, self.N, self.P-2, self.P-2, self.n_classes)\r\n        mu1 = h_mu\r\n        mu2 = ph_mu\r\n        b1 = h_logb.exp()\r\n        b2 = ph_logb.exp()\r\n        logb1 = h_logb\r\n        logb2 = ph_logb\r\n        # KL: (b1*exp(-|mu1-mu2|/b1)+|mu1-mu2|)/b2 + log(b2/b1) - 1\r\n        # KL(h||ph)\r\n        # shape: [batch_size, N, P-2, P-2, n_classes]\r\n        KLD_QX_PX = (b1 * torch.exp(-torch.abs(mu1 - mu2) / b1) + torch.abs(mu1 - mu2)) / b2 + logb2 - logb1 - 1.0\r\n        KLD_QX_PX = torch.sum(KLD_QX_PX, dim=(1, 2, 3))\r\n        kl = torch.sum(KLD_QX_PX * prob_c)/(self.N * (self.P-2) * (self.P-2))\r\n        return kl\r\n\r\n    def forward(self, x):\r\n        h_mu, h_logb, w_mu, w_logb, prob_c = self.q_net(x)\r\n        h_sample = self.reparameterize(h_mu, h_logb)    # h_sample: [batch_size, N, P-2, P-2]\r\n        w_sample = self.reparameterize(w_mu, w_logb)    # w_sample: [batch_size, 32, P-4, P-4]\r\n        ph_mu, ph_logb = self.priorGenerator(w_sample)  # ph_mu, ph_logb: [batch_size, N, P-2, P-2, n_classes]\r\n        kl_loss_w = self.kl_w_loss(w_mu, w_logb)\r\n        kl_loss_c = self.kl_c_loss(prob_c)\r\n        kl_loss_h = self.kl_h_loss(h_mu, h_logb, ph_mu, ph_logb, prob_c)\r\n        kld = kl_loss_w + kl_loss_c + kl_loss_h\r\n        return h_sample, kld, kl_loss_w, kl_loss_h, kl_loss_c\r\n", "meta": {"hexsha": "68b9fd1e8ac07f0d9692ff11d85caecde7025412", "size": 23817, "ext": "py", "lang": "Python", "max_stars_repo_path": "Multi-task AE/model/Encoder.py", "max_stars_repo_name": "ZiyHe/SLF_Estimate", "max_stars_repo_head_hexsha": "9ff2ed6d7de2ca63455e31db0adf0b8daf68606a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Multi-task AE/model/Encoder.py", "max_issues_repo_name": "ZiyHe/SLF_Estimate", "max_issues_repo_head_hexsha": "9ff2ed6d7de2ca63455e31db0adf0b8daf68606a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Multi-task AE/model/Encoder.py", "max_forks_repo_name": "ZiyHe/SLF_Estimate", "max_forks_repo_head_hexsha": "9ff2ed6d7de2ca63455e31db0adf0b8daf68606a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.4269005848, "max_line_length": 148, "alphanum_fraction": 0.567031952, "include": true, "reason": "import numpy", "num_tokens": 6838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19886229715274964}}
{"text": "#This software is a free software. Thus, it is licensed under GNU General Public License.\n#Python implementation to Smith-Waterman Algorithm for Homework 1 of Bioinformatics class.\n#Forrest Bao, Sept. 26 <http://fsbao.net> <forrest.bao aT gmail.com>\n\nimport sys, string\nfrom numpy import *\n\ndef readFasta(infile):\n    saved = None\n    while 1:\n        if saved is not None:\n            line = saved\n            saved = None\n        else:\n            line = infile.readline()\n            if not line:\n                return\n        if line.isspace():\n            continue\n        if not line.startswith(\">\"):\n            raise TypeError(\n                \"The title line must start with a '>': %r\" % line)    \n        title = line.rstrip()\n        sequences = []\n        while 1:\n            line = infile.readline()\n            if not line or line.isspace():\n                break\n            if line.startswith(\">\"):\n                saved = line\n                break\n            sequences.append(line.rstrip(\"\\n\"))                    \n        yield  \"\".join(sequences)   \n    infile.close()\n    \n    \n    \ndef getFmax(score,m,n):\n    Fmax = 0\n    position = (0,0)\n    m = m -1\n    n = n -1 \n    for i in xrange(1,n):\n        if(score[i][m] > Fmax):\n            Fmax = score[i][m]    \n            position = (i,m)\n    for j in xrange(1,m):\n        if(score[n][j] > Fmax):\n            Fmax = score[n][j]\n            position = (n,j)\n    return position\n\n#read the first sequence\nf1=open(sys.argv[1], 'r')\nseq1=readFasta(f1).next()\n\n#read the second sequence\nf2=open(sys.argv[2], 'r')\nseq2=readFasta(f2).next()\n\n\nm,n =  len(seq1)+1,len(seq2)+1    #length of two sequences\n\npenalty=-4;            #define the gap penalty\n\n#generate DP table and traceback path pointer matrix\nscore=zeros((m+1,n+1))         #the DP table\npointer=zeros((m+1,n+1))     #to store the traceback path\n\n#score = [0]*m\n#for i in range(n):\n#    score[i] = [0] * n\n#pointer = [0]*m\n#for i in range(n):\n#    pointer[i] = [0] * n\n    \nP=0;\n\ndef match_score(alpha,beta):    #the function to find match/dismatch score from BLOSUM62 by letters of AAs\n    if(alpha==beta):\n        return 2\n    else:\n        return -1\n\nmax_score=P;        #initial maximum score in DP table\n\n#calculate DP table and mark pointers\nfor i in range(1,m):\n    for j in range(1,n):\n        score_up=score[i-1][j]+penalty;\n        score_down=score[i][j-1]+penalty;\n        score_diagonal=score[i-1][j-1]+match_score(seq1[i-1],seq2[j-1]);\n        #score[i][j]=max(0,score_up,score_down,score_diagonal);\n        score[i][j]=max(score_up,score_down,score_diagonal);\n        if score[i][j]==0:\n            pointer[i][j]=0; #0 means end of the path\n        if score[i][j]==score_up:\n            pointer[i][j]=1; #1 means trace up\n        if score[i][j]==score_down:\n            pointer[i][j]=2; #2 means trace left\n        if score[i][j]==score_diagonal:\n            pointer[i][j]=3; #3 means trace diagonal\n        if score[i][j]>=max_score:\n            max_i=i;\n            max_j=j;\n            max_score=score[i][j];\n#END of DP table\n\n\nalign1,align2='','';    #initial sequences\n\ni,j=max_i,max_j;    #indices of path starting point\n\n#traceback, follow pointers\nwhile pointer[i][j]!=0:\n\n    if pointer[i][j]==3:\n        align1=align1+seq1[i-1];\n        align2=align2+seq2[j-1];\n        i=i-1;\n        j=j-1;\n    elif pointer[i][j]==2:\n        align1=align1+'-';\n        align2=align2+seq2[j-1];\n        j=j-1;\n    elif pointer[i][j]==1:\n        align1=align1+seq1[i-1];\n        align2=align2+'-';\n        i=i-1;\n#END of traceback\n\nalign1=align1[::-1];    #reverse sequence 1\nalign2=align2[::-1];    #reverse sequence 2\n\n\nprint \"Length1: \" + str(len(align1)) + \" Length2: \" + str(len(align2))          \nprint align1\nprint align2        \n\n\n\n", "meta": {"hexsha": "8e1098fc368bb4dd65c4a9b748faddfd489f38d9", "size": 3776, "ext": "py", "lang": "Python", "max_stars_repo_path": "AB1/src/pp.py", "max_stars_repo_name": "jfnavarro/old_python_courses", "max_stars_repo_head_hexsha": "fb500e8eeae6c5d10bf77e1ff52725627527222a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-02-20T03:26:35.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-20T03:26:35.000Z", "max_issues_repo_path": "AB1/src/pp.py", "max_issues_repo_name": "jfnavarro/BioInfo_ML_courses", "max_issues_repo_head_hexsha": "fb500e8eeae6c5d10bf77e1ff52725627527222a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AB1/src/pp.py", "max_forks_repo_name": "jfnavarro/BioInfo_ML_courses", "max_forks_repo_head_hexsha": "fb500e8eeae6c5d10bf77e1ff52725627527222a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5915492958, "max_line_length": 106, "alphanum_fraction": 0.5487288136, "include": true, "reason": "from numpy", "num_tokens": 1079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.31742625913050115, "lm_q1q2_score": 0.1987482508996909}}
{"text": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Quantization module for generating quantized (INT8) models from FP32 models.\"\"\"\n\nimport abc\nimport ctypes\nimport logging\nimport os\nimport warnings\nimport numpy as np\nimport mxnet as mx\nfrom ..base import _LIB, check_call, py_str\nfrom ..base import c_array, c_str, mx_uint, mx_real_t, c_str_array\nfrom ..base import SymbolHandle\nfrom ..symbol import Symbol\nfrom .. import ndarray\nfrom ..io import DataDesc\nfrom ..device import cpu, Device\nfrom ..util import is_np_array, wrap_ctx_to_device_func\n\n\ndef _quantize_params(qsym, params, min_max_dict):\n    \"\"\"Given a quantized symbol and a dict of params that have not been quantized,\n    generate quantized params. Currently only supports quantizing the arg_params\n    with names of `weight` or `bias`, not aux_params. If `qsym` contains symbols\n    that are excluded from being quantized, their corresponding params will\n    not be quantized, but saved together with quantized params of the symbols that\n    have been quantized.\n\n    Parameters\n    ----------\n    qsym : Symbol\n        Quantized symbol from FP32 symbol.\n    params : dict of str->NDArray\n    min_max_dict: dict of min/max pairs of layers' output\n    \"\"\"\n    inputs_name = qsym.list_arguments()\n    quantized_params = {}\n    if is_np_array():\n        quantize_fn = mx.npx.contrib_quantize\n        min_fn = lambda arr: mx.np.array([mx.np.min(arr)])\n        max_fn = lambda arr: mx.np.array([mx.np.max(arr)])\n        array_cls = mx.np\n    else:\n        quantize_fn = mx.nd.contrib.quantize\n        min_fn = mx.nd.min\n        max_fn = mx.nd.max\n        array_cls = mx.nd\n\n    for name in inputs_name:\n        if name.endswith(('weight_quantize', 'bias_quantize')):\n            original_name = name[:-len('_quantize')]\n            param = params[original_name]\n            # pylint: disable=unbalanced-tuple-unpacking\n            param_min = min_fn(param)\n            param_max = max_fn(param)\n            val, vmin, vmax = quantize_fn(data=param,\n                                          min_range=param_min,\n                                          max_range=param_max,\n                                          out_type='int8')\n            quantized_params[name] = val\n            quantized_params[name+'_min'] = vmin\n            quantized_params[name+'_max'] = vmax\n        elif name in params:\n            quantized_params[name] = params[name]\n        elif name.endswith(('_min')):\n            output = name[: - len('_min')]\n            if output in min_max_dict:\n                quantized_params[name] = array_cls.array([min_max_dict[output][0]])\n        elif name.endswith(('_max')):\n            output = name[: - len('_min')]\n            if output in min_max_dict:\n                quantized_params[name] = array_cls.array([min_max_dict[output][1]])\n    return quantized_params\n\n\ndef _quantize_symbol(sym, device, excluded_symbols=None, excluded_operators=None,\n                     offline_params=None, quantized_dtype='int8', quantize_mode='smart',\n                     quantize_granularity='tensor-wise'):\n    \"\"\"Given a symbol object representing a neural network of data type FP32,\n    quantize it into a INT8 network.\n\n    Parameters\n    ----------\n    sym : Symbol\n        FP32 neural network symbol.\n    device : Device\n        Defines the device that users want to run quantized symbol.\n    excluded_symbols : list of strings\n        A list of strings representing the names of the symbols that users want to excluding\n        from being quantized.\n    excluded_operators : list of strings\n        A list of strings representing the names of the operators that users want to excluding\n        from being quantized.\n    offline_params : list of strs\n        Names of the parameters that users want to quantize offline. It's always recommended to\n        quantize parameters offline so that quantizing parameters during the inference can be\n        avoided.\n    quantized_dtype: str\n        The quantized destination type for input data.\n    quantize_mode: str\n        The mode that quantization pass to apply.\n    quantize_granularity: str\n        The granularity of quantization, currently supports 'tensor-wise' and 'channel-wise'\n        quantization. The default value is 'tensor-wise'.\n    \"\"\"\n    num_excluded_symbols = 0\n    if excluded_symbols is not None:\n        assert isinstance(excluded_symbols, list)\n        num_excluded_symbols = len(excluded_symbols)\n    else:\n        excluded_symbols = []\n\n    num_excluded_ops = 0\n    if excluded_operators is not None:\n        assert isinstance(excluded_operators, list)\n        num_excluded_ops = len(excluded_operators)\n    else:\n        excluded_operators = []\n\n    num_offline = 0\n    offline = []\n    if offline_params is not None:\n        num_offline = len(offline_params)\n        for k in offline_params:\n            offline.append(c_str(k))\n\n    out = SymbolHandle()\n    size = mx_uint()\n    calib_str = ctypes.POINTER(ctypes.c_char_p)()\n    check_call(_LIB.MXQuantizeSymbol(sym.handle,\n                                     ctypes.byref(out),\n                                     ctypes.byref(ctypes.c_int(device.device_typeid)),\n                                     mx_uint(num_excluded_symbols),\n                                     c_str_array(excluded_symbols),\n                                     mx_uint(num_excluded_ops),\n                                     c_str_array(excluded_operators),\n                                     mx_uint(num_offline),\n                                     c_array(ctypes.c_char_p, offline),\n                                     c_str(quantized_dtype),\n                                     ctypes.c_bool(True),\n                                     c_str(quantize_mode),\n                                     c_str(quantize_granularity),\n                                     ctypes.byref(size),\n                                     ctypes.byref(calib_str)))\n    calib_layers = []\n    calib_layers = [py_str(calib_str[i]) for i in range(size.value)]\n    return Symbol(out), calib_layers\n\n\nclass CalibrationCollector(object):\n    \"\"\"Base class for all other collectors used with quantization\"\"\"\n    __metaclass__ = abc.ABCMeta\n\n    def __init__(self):\n        self.include_layers = None\n        self.min_max_dict = {}\n\n    @abc.abstractmethod\n    def collect(self, name, op_name, arr):\n        \"\"\"Function which is registered to Block as monitor callback. Names of layers\n        requiring calibration are stored in `self.include_layers` variable.\n            Parameters\n            ----------\n            name : str\n                Node name from which collected data comes from\n            op_name : str\n                Operator name from which collected data comes from. Single operator\n                can have multiple inputs/ouputs nodes - each should have different name\n            arr : NDArray\n                NDArray containing data of monitored node\n        \"\"\"\n\n    def post_collect(self):\n        \"\"\" Function called after collecting parameters. Returns dictionary of min and max values\n        for each calibrated layer. If not overriden, returns content of `self.min_max_dict`.\n        \"\"\"\n        return self.min_max_dict\n\n\nclass _LayerHistogramCollector(CalibrationCollector):\n    \"\"\"Saves layer histogram in a dict with layer names as keys and lists of NDArrays as\n    values. The collected histogram will be used for calculating the optimal thresholds for\n    quantization using KL divergence.\n    \"\"\"\n    def __init__(self, quantized_dtype, num_bins=8001, include_layers=None, logger=None):\n        super(_LayerHistogramCollector, self).__init__()\n        self.hist_dict = {}\n        self.num_bins = num_bins\n        self.include_layers = include_layers\n        self.logger = logger\n        self.quantized_dtype = quantized_dtype\n\n    def collect(self, name, op_name, arr):\n        \"\"\"Callback function for collecting layer output NDArrays.\"\"\"\n        if name not in self.include_layers:\n            return\n        arr = arr.copyto(cpu()).asnumpy()\n        if self.logger:\n            self.logger.debug(\"Collecting layer %s histogram of shape %s\" % (name, arr.shape))\n        min_range = np.min(arr)\n        max_range = np.max(arr)\n        th = max(abs(min_range), abs(max_range))\n        if name in self.hist_dict:\n            self.hist_dict[name] = self.combine_histogram(self.hist_dict[name], arr, min_range, max_range, th)\n        else:\n            hist, hist_edges = np.histogram(arr, bins=self.num_bins, range=(-th, th))\n            self.hist_dict[name] = (hist, hist_edges, min_range, max_range, th)\n\n    def post_collect(self):\n        min_max_dict = self.get_optimal_thresholds(self.hist_dict, self.quantized_dtype, logger=self.logger)\n        return min_max_dict\n\n    @staticmethod\n    def combine_histogram(old_hist, arr, new_min, new_max, new_th):\n        \"\"\" Collect layer histogram for arr and combine it with old histogram.\n        \"\"\"\n        (old_hist, old_hist_edges, old_min, old_max, old_th) = old_hist\n        if new_th <= old_th:\n            hist, _ = np.histogram(arr, bins=len(old_hist), range=(-old_th, old_th))\n            return (old_hist + hist, old_hist_edges, min(old_min, new_min), max(old_max, new_max), old_th)\n        else:\n            # Need to generate new histogram with new_th\n            old_num_bins = len(old_hist)\n            old_step = 2 * old_th / old_num_bins\n            half_increased_bins = int((new_th - old_th) // old_step + 1)\n            new_num_bins = half_increased_bins * 2 + old_num_bins\n            new_th = half_increased_bins * old_step + old_th\n            hist, hist_edges = np.histogram(arr, bins=new_num_bins, range=(-new_th, new_th))\n            hist[half_increased_bins:new_num_bins - half_increased_bins] += old_hist\n            return (hist, hist_edges, min(old_min, new_min), max(old_max, new_max), new_th)\n\n    # pylint: disable=line-too-long\n    @staticmethod\n    def get_optimal_threshold(hist_data, quantized_dtype, num_quantized_bins=255):\n        \"\"\"Given a dataset, find the optimal threshold for quantizing it.\n        The reference distribution is `q`, and the candidate distribution is `p`.\n        `q` is a truncated version of the original distribution.\n\n        Ref: http://on-demand.gputechconf.com/gtc/2017/presentation/s7310-8-bit-inference-with-tensorrt.pdf\n        \"\"\"\n        (hist, hist_edges, min_val, max_val, _) = hist_data\n        num_bins = len(hist)\n        assert (num_bins % 2 == 1)\n        if min_val >= 0 and quantized_dtype in ['auto', 'uint8']:\n            # We need to move negative bins to positive bins to fit uint8 range.\n            num_quantized_bins = num_quantized_bins * 2 + 1\n        hist = ndarray.array(hist, ctx=cpu())\n        hist_edges = ndarray.array(hist_edges, ctx=cpu())\n        threshold, divergence = ndarray.contrib.calibrate_entropy(hist=hist,\n                                                                  hist_edges=hist_edges,\n                                                                  num_quantized_bins=num_quantized_bins)\n        threshold = threshold.asnumpy()\n        divergence = divergence.asnumpy()\n        return min_val, max_val, threshold, divergence\n    # pylint: enable=line-too-long\n\n    @staticmethod\n    def get_optimal_thresholds(hist_dict, quantized_dtype, num_quantized_bins=255, logger=None):\n        \"\"\"Given a ndarray dict, find the optimal threshold for quantizing each value of the key.\"\"\"\n        assert isinstance(hist_dict, dict)\n        if logger is not None:\n            logger.info('Calculating optimal thresholds for quantization using KL divergence'\n                        ' with num_quantized_bins=%d' % num_quantized_bins)\n        th_dict = {}\n        # copy hist_dict keys since the keys() only returns a view in python3\n        layer_names = list(hist_dict.keys())\n        for name in layer_names:\n            assert name in hist_dict\n            min_val, max_val, th, divergence = \\\n                _LayerHistogramCollector.get_optimal_threshold(hist_dict[name], quantized_dtype,\n                                                               num_quantized_bins=num_quantized_bins)\n            if min_val >= 0 and quantized_dtype in ['auto', 'uint8']:\n                th_dict[name] = (0, th)\n            else:\n                th_dict[name] = (-th, th)\n            del hist_dict[name]  # release the memory\n            if logger:\n                logger.debug(f\"layer={name}, min_val={min_val}, max_val={max_val}, th={th}, divergence={divergence}\")\n        return th_dict\n\n\nclass _LayerOutputMinMaxCollector(CalibrationCollector):\n    \"\"\"Saves layer output min and max values in a dict with layer names as keys.\n    The collected min and max values will be directly used as thresholds for quantization.\n    \"\"\"\n    def __init__(self, quantized_dtype, include_layers=None, logger=None):\n        super(_LayerOutputMinMaxCollector, self).__init__()\n        self.min_max_dict = {}\n        self.quantized_dtype = quantized_dtype\n        self.include_layers = include_layers\n        self.logger = logger\n\n    def collect(self, name, op_name, arr):\n        \"\"\"Callback function for collecting min and max values from an NDArray.\"\"\"\n        if name not in self.include_layers:\n            return\n        arr = arr.copyto(cpu()).asnumpy()\n        min_range = np.min(arr)\n        max_range = np.max(arr)\n        if name in self.min_max_dict:\n            cur_min_max = self.min_max_dict[name]\n            self.min_max_dict[name] = (min(cur_min_max[0], min_range),\n                                       max(cur_min_max[1], max_range))\n        else:\n            self.min_max_dict[name] = (min_range, max_range)\n        if self.logger:\n            self.logger.debug(\"Collecting layer %s min_range=%f, max_range=%f\"\n                              % (name, min_range, max_range))\n\n\ndef _calibrate_quantized_sym(qsym, min_max_dict):\n    \"\"\"Given a dictionary containing the thresholds for quantizing the layers,\n    set the thresholds into the quantized symbol as the params of requantize operators.\n    \"\"\"\n    if min_max_dict is None or len(min_max_dict) == 0:\n        return qsym\n    num_layer_outputs = len(min_max_dict)\n    layer_output_names = []\n    min_vals = []\n    max_vals = []\n    for k, v in min_max_dict.items():\n        layer_output_names.append(k)\n        min_vals.append(v[0])\n        max_vals.append(v[1])\n\n    calibrated_sym = SymbolHandle()\n    check_call(_LIB.MXSetCalibTableToQuantizedSymbol(qsym.handle,\n                                                     mx_uint(num_layer_outputs),\n                                                     c_str_array(layer_output_names),\n                                                     c_array(ctypes.c_float, min_vals),\n                                                     c_array(ctypes.c_float, max_vals),\n                                                     ctypes.byref(calibrated_sym)))\n    return Symbol(calibrated_sym)\n\n\ndef _collect_layer_statistics(sym_block, data, collector, num_inputs, num_calib_batches=None, logger=None):\n    if not isinstance(data, mx.gluon.data.DataLoader):\n        raise ValueError('Only supports data as a type of DataLoader, while received type %s'\n                         % str(type(data)))\n    sym_block.register_op_hook(collector.collect, monitor_all=True)\n    num_batches = 0\n    for batch in data:\n        if not isinstance(batch, list):\n            batch = [batch]\n        batch = [b.as_in_context(mx.cpu()) for b in batch]\n        sym_block(*batch[:num_inputs])\n        num_batches += 1\n        if num_calib_batches is not None and num_batches >= num_calib_batches:\n            break\n    if logger is not None:\n        logger.info(\"Collected statistics from %d batches\" % (num_batches))\n    return num_batches\n\n\ndef _generate_list_of_data_desc(data_shapes, data_types):\n    \"\"\"\"Convert list ot tuples to list of DataDesc.\"\"\"\n    if isinstance(data_shapes, list):\n        if all(isinstance(x, DataDesc) for x in data_shapes):\n            return data_shapes\n        if all(isinstance(x, tuple) for x in data_shapes):\n            if len(data_shapes) == 1:\n                data_shapes = [DataDesc(name='data', shape=data_shapes[0], dtype=data_types[0])]\n            else:\n                data_shapes = [DataDesc(name='data' + str(i), shape=data_shapes[i],\n                                        dtype=data_types[i]) for i in range(len(data_shapes))]\n            return data_shapes\n    raise ValueError('data_shapes must be either a list of DataDesc or a list of Tuple')\n\n\n@wrap_ctx_to_device_func\ndef quantize_model(sym, arg_params, aux_params, data_names=('data',),\n                   device=cpu(), excluded_sym_names=None, excluded_op_names=None, calib_mode='entropy',\n                   calib_data=None, num_calib_batches=None,\n                   quantized_dtype='int8', quantize_mode='smart',\n                   quantize_granularity='tensor-wise', logger=None):\n    \"\"\"User-level API for generating a quantized model from a FP32 model w/ or w/o calibration.\n    The backend quantized operators are only enabled for Linux systems. Please do not run\n    inference using the quantized models on Windows for now.\n    The quantization implementation adopts the TensorFlow's approach:\n    https://www.tensorflow.org/performance/quantization.\n    The calibration implementation borrows the idea of Nvidia's 8-bit Inference with TensorRT:\n    http://on-demand.gputechconf.com/gtc/2017/presentation/s7310-8-bit-inference-with-tensorrt.pdf\n    and adapts the method to MXNet.\n\n    .. _`quantize_model_params`:\n    Parameters\n    ----------\n    sym : str or Symbol\n        Defines the structure of a neural network for FP32 data types.\n    arg_params : dict\n        Dictionary of name to `NDArray`.\n    aux_params : dict\n        Dictionary of name to `NDArray`.\n    data_names : a list of strs\n        Data names required for creating a Module object to run forward propagation on the\n        calibration dataset.\n    device : Device\n        Defines the device that users want to run forward propagation on the calibration\n        dataset for collecting layer output statistics. Currently, only supports single device.\n    excluded_sym_names : list of strings\n        A list of strings representing the names of the symbols that users want to excluding\n        from being quantized.\n    excluded_op_names : list of strings\n        A list of strings representing the names of the operators that users want to excluding\n        from being quantized.\n    calib_mode : str\n        If calib_mode='none', no calibration will be used and the thresholds for\n        requantization after the corresponding layers will be calculated at runtime by\n        calling min and max operators. The quantized models generated in this\n        mode are normally 10-20% slower than those with calibrations during inference.\n        If calib_mode='naive', the min and max values of the layer outputs from a calibration\n        dataset will be directly taken as the thresholds for quantization.\n        If calib_mode='entropy' (default mode), the thresholds for quantization will be\n        derived such that the KL divergence between the distributions of FP32 layer outputs and\n        quantized layer outputs is minimized based upon the calibration dataset.\n    calib_data : DataLoader\n        A DataLoader initialized by the calibration dataset.\n    num_calib_batches : int or None\n        The maximum number of batches that user would like to use for calibration. If not provided,\n        the whole calibration dataset will be used.\n    quantized_dtype : str\n        The quantized destination type for input data. Currently support 'int8', 'uint8' and 'auto'.\n        'auto' means automatically select output type according to calibration result.\n        Default value is 'int8'.\n    quantize_mode : str\n        The mode that quantization pass to apply. Support 'full' and 'smart'.\n        'full' means quantize all operator if possible.\n        'smart' means quantization pass will smartly choice which operator should be quantized.\n    quantize_granularity: str\n        The granularity of quantization, currently supports 'tensor-wise' and 'channel-wise'\n        quantization. The default value is 'tensor-wise'.\n    logger : Object\n        A logging object for printing information during the process of quantization.\n\n    Returns\n    -------\n    quantized_model: tuple\n        A tuple of quantized symbol, quantized arg_params, and aux_params.\n    \"\"\"\n    warnings.warn('WARNING: This will be deprecated please use quantize_net with Gluon models')\n    if excluded_sym_names is None:\n        excluded_sym_names = []\n    if not isinstance(excluded_sym_names, list):\n        raise ValueError('excluded_sym_names must be a list of strings representing'\n                         ' the names of the symbols that will not be quantized,'\n                         ' while received type %s' % str(type(excluded_sym_names)))\n\n    if excluded_op_names is None:\n        excluded_op_names = []\n    if not isinstance(excluded_op_names, list):\n        raise ValueError('excluded_op_names must be a list of strings representing'\n                         ' the names of the operators that will not be quantized,'\n                         ' while received type %s' % str(type(excluded_op_names)))\n\n    if logger:\n        os.environ['MXNET_QUANTIZATION_VERBOSE'] = '1'\n        logger.info('Quantizing symbol')\n    if quantized_dtype not in ('int8', 'uint8', 'auto'):\n        raise ValueError('unknown quantized_dtype %s received,'\n                         ' expected `int8`, `uint8` or `auto`' % quantized_dtype)\n    if quantize_granularity not in ('tensor-wise', 'channel-wise'):\n        raise ValueError('unkonwn quantize_granularity %s received,'\n                         ' expected `tensor-wise` or `channel-wise`.' % quantize_granularity)\n    qsym, calib_layers = _quantize_symbol(sym, device, excluded_symbols=excluded_sym_names,\n                                          excluded_operators=excluded_op_names,\n                                          offline_params=list(arg_params.keys()),\n                                          quantized_dtype=quantized_dtype,\n                                          quantize_mode=quantize_mode,\n                                          quantize_granularity=quantize_granularity)\n    min_max_dict = {}\n    if calib_mode is not None and calib_mode != 'none':\n        if not isinstance(device, Device):\n            raise ValueError('currently only supports single device, while received %s' % str(device))\n        if calib_data is None:\n            raise ValueError('calib_data must be provided when calib_mode=%s' % calib_mode)\n        if not isinstance(calib_data, mx.gluon.data.DataLoader):\n            raise ValueError('calib_data must be of DataLoader type when calib_mode=%s,'\n                             ' while received type %s' % (calib_mode, str(type(calib_data))))\n\n        inputs = [mx.sym.var(dname) for dname in data_names]\n        param_dict = arg_params\n        param_dict.update(aux_params)\n        sym_block = mx.gluon.SymbolBlock(sym, inputs)\n        sym_block.load_dict(param_dict)\n\n        if calib_mode == 'entropy':\n            collector = _LayerHistogramCollector(quantized_dtype=quantized_dtype,\n                                                 include_layers=calib_layers,\n                                                 logger=logger)\n        elif calib_mode == 'naive':\n            collector = _LayerOutputMinMaxCollector(quantized_dtype=quantized_dtype,\n                                                    include_layers=calib_layers,\n                                                    logger=logger)\n\n        else:\n            raise ValueError('unknown calibration mode %s received,'\n                             ' expected `none`, `naive`, or `entropy`' % calib_mode)\n\n        num_batches = _collect_layer_statistics(sym_block, calib_data, collector,\n                                                len(inputs), num_calib_batches, logger)\n        if logger:\n            logger.info('Collected layer output min/max values from FP32 model using %d batches'\n                        % num_batches)\n            logger.info('Performing calibration post collecting operations')\n\n        min_max_dict = collector.post_collect()\n        qsym = _calibrate_quantized_sym(qsym, min_max_dict)\n\n    if logger:\n        logger.info('Quantizing parameters')\n    qarg_params = _quantize_params(qsym, arg_params, min_max_dict)\n\n    if is_np_array():\n        qsym = qsym.as_np_ndarray()\n\n    return qsym, qarg_params, aux_params\n\n@wrap_ctx_to_device_func\ndef quantize_model_onednn(sym, arg_params, aux_params, data_names=('data',),\n                          device=cpu(), excluded_sym_names=None, excluded_op_names=None,\n                          calib_mode='entropy', calib_data=None, num_calib_batches=None,\n                          quantized_dtype='int8', quantize_mode='smart',\n                          quantize_granularity='tensor-wise', logger=None):\n    \"\"\"User-level API for generating a fusion + quantized model from a FP32 model\n    w/ or w/o calibration with oneDNN.\n    The backend quantized operators are only enabled for Linux systems. Please do not run\n    inference using the quantized models on Windows for now.\n\n    Parameters\n    ----------\n    all\n        :ref:`As in quantize_model<quantize_model_params>`\n\n\n    Returns\n    -------\n    quantized_model: tuple\n        A tuple of quantized symbol, quantized arg_params, and aux_params.\n    \"\"\"\n    if not isinstance(device, Device):\n        raise ValueError('currently only supports single device, while received %s' % str(device))\n    if device.device_type != 'cpu':\n        raise ValueError(\n            'quantize_model_onednn only support Intel cpu platform with oneDNN Backend')\n\n    sym = sym.optimize_for(backend='ONEDNN_QUANTIZE')\n\n    qsym, qarg_params, aux_params = quantize_model(sym=sym, arg_params=arg_params, aux_params=aux_params,\n                                                   data_names=data_names, device=device,\n                                                   excluded_sym_names=excluded_sym_names,\n                                                   excluded_op_names=excluded_op_names,\n                                                   calib_mode=calib_mode, calib_data=calib_data,\n                                                   num_calib_batches=num_calib_batches,\n                                                   quantized_dtype=quantized_dtype, quantize_mode=quantize_mode,\n                                                   quantize_granularity=quantize_granularity, logger=logger)\n\n    qsym = qsym.optimize_for(backend='ONEDNN_QUANTIZE')\n\n    return qsym, qarg_params, aux_params\n\ndef quantize_graph(sym, arg_params, aux_params, device=cpu(),\n                   excluded_sym_names=None, excluded_op_names=None,\n                   calib_mode='entropy', quantized_dtype='int8',\n                   quantize_mode='full', quantize_granularity='tensor-wise',\n                   LayerOutputCollector=None, logger=None):\n    \"\"\"User-level API for generating a quantized model from a FP32 model w/o calibration\n    and a collector for naive or entropy calibration.\n    The backend quantized operators are only enabled for Linux systems. Please do not run\n    inference using the quantized models on Windows for now.\n    Parameters\n    ----------\n    sym : str or Symbol\n        Defines the structure of a neural network for FP32 data types.\n    device : Device\n        Defines the device that users want to run forward propagation on the calibration\n        dataset for collecting layer output statistics. Currently, only supports single device.\n    arg_params : dict\n        Dictionary of name to `NDArray`.\n    aux_params : dict\n        Dictionary of name to `NDArray`.\n    excluded_sym_names : list of strings\n        A list of strings representing the names of the symbols that users want to excluding\n        from being quantized.\n    excluded_op_names : list of strings\n        A list of strings representing the names of the operators that users want to excluding\n    calib_mode : str\n        If calib_mode='none', no calibration will be used and the thresholds for\n        requantization after the corresponding layers will be calculated at runtime by\n        calling min and max operators. The quantized models generated in this\n        mode are normally 10-20% slower than those with calibrations during inference.\n        If calib_mode='naive', the min and max values of the layer outputs from a calibration\n        dataset will be directly taken as the thresholds for quantization.\n        If calib_mode='entropy' (default mode), the thresholds for quantization will be\n        derived such that the KL divergence between the distributions of FP32 layer outputs and\n        quantized layer outputs is minimized based upon the calibration dataset.\n    quantized_dtype : str\n        The quantized destination type for input data. Currently support 'int8'\n        , 'uint8' and 'auto'. 'auto' means automatically select output type according to calibration result.\n        Default value is 'int8'.\n    quantize_mode : str\n        The mode that quantization pass to apply. Support 'full' and 'smart'.\n        'full' means quantize all operator if possible.\n        'smart' means quantization pass will smartly choice which operator should be quantized.\n    quantize_granularity: str\n        The granularity of quantization, currently supports 'tensor-wise' and 'channel-wise'\n        quantization. The default value is 'tensor-wise'.\n    LayerOutputCollector : subclass of CalibrationCollector\n        For custom calibration method usage.\n        Passed object's include_layers attribute will be feed with names of layers which needs calibration\n    logger : Object\n        A logging object for printing information during the process of quantization.\n    Returns\n    -------\n    quantized_model : tuple\n        A tuple of quantized symbol, quantized arg_params, aux_params and collector.\n    \"\"\"\n    if excluded_sym_names is None:\n        excluded_sym_names = []\n    if not isinstance(excluded_sym_names, list):\n        raise ValueError('excluded_sym_names must be a list of strings representing'\n                         ' the names of the symbols that will not be quantized,'\n                         ' while received type %s' % str(type(excluded_sym_names)))\n    if not isinstance(device, Device):\n        raise ValueError('currently only supports single device, while received %s' % str(device))\n    if logger:\n        os.environ['MXNET_QUANTIZATION_VERBOSE'] = '1'\n        logger.info('Quantizing graph')\n    if quantized_dtype not in ('int8', 'uint8', 'auto'):\n        raise ValueError('unknown quantized_dtype %s received,'\n                         ' expected `int8`, `uint8` or `auto`' % quantized_dtype)\n    if quantize_granularity not in ('tensor-wise', 'channel-wise'):\n        raise ValueError('unkonwn quantize_granularity %s received,'\n                         ' expected `tensor-wise` or `channel-wise`.' % quantize_granularity)\n    qsym, calib_layers = _quantize_symbol(sym, device, excluded_symbols=excluded_sym_names,\n                                          excluded_operators=excluded_op_names,\n                                          offline_params=list(arg_params.keys()),\n                                          quantized_dtype=quantized_dtype,\n                                          quantize_mode=quantize_mode,\n                                          quantize_granularity=quantize_granularity)\n\n    collector = None\n    if calib_mode is not None and calib_mode != 'none':\n        if calib_mode == 'entropy':\n            collector = _LayerHistogramCollector(quantized_dtype=quantized_dtype,\n                                                 include_layers=calib_layers, logger=logger)\n            if logger:\n                logger.info(\n                    'Create a layer output collector for entropy calibration.')\n        elif calib_mode == 'naive':\n            collector = _LayerOutputMinMaxCollector(quantized_dtype=quantized_dtype,\n                                                    include_layers=calib_layers, logger=logger)\n            if logger:\n                logger.info(\n                    'Create a layer output minmax collector for naive calibration')\n        elif calib_mode == 'custom' and LayerOutputCollector is not None:\n            if not isinstance(LayerOutputCollector, CalibrationCollector):\n                raise ValueError('LayerOutputCollecotr must be a subclass of a CalibrationCollector class,'\n                                 ' but it is %s' % LayerOutputCollector.__class__)\n            collector = LayerOutputCollector\n\n            # Inject layer names that need calibration to collector\n            if hasattr(collector, \"include_layers\"):\n                if collector.include_layers is not None:\n                    logger.info('Custom collector has set include_layers attribute. '\n                                'Calibration layers not passed')\n                else:\n                    collector.include_layers = calib_layers\n            if logger:\n                logger.info(\n                    'Create a custom layer output minmax collector for calibration')\n        else:\n            raise ValueError('unknown calibration mode %s received,'\n                             ' expected `none`, `naive`, `entropy` or `custom`' % calib_mode)\n        if logger:\n            logger.info('Collector created, please use set_monitor_callback'\n                        ' to collect calibration information.')\n\n    if logger:\n        logger.info('Quantizing parameters')\n    qarg_params = _quantize_params(qsym, arg_params, min_max_dict={})\n\n    if is_np_array():\n        qsym = qsym.as_np_ndarray()\n\n    return qsym, qarg_params, aux_params, collector, calib_layers\n\ndef calib_graph(qsym, arg_params, aux_params, collector,\n                calib_mode='entropy', logger=logging):\n    \"\"\"User-level API for calibrating a quantized model using a filled collector.\n    The backend quantized operators are only enabled for Linux systems. Please do not run\n    inference using the quantized models on Windows for now.\n    Parameters\n    ----------\n    qsym : str or Symbol\n        Defines the structure of a neural network for INT8 data types.\n    arg_params : dict\n        Dictionary of name to `NDArray`.\n    aux_params : dict\n        Dictionary of name to `NDArray`.\n    collector : function\n        layer collector for naive or entropy calibration.\n    calib_mode : str\n        If calib_mode='none', no calibration will be used and the thresholds for\n        requantization after the corresponding layers will be calculated at runtime by\n        calling min and max operators. The quantized models generated in this\n        mode are normally 10-20% slower than those with calibrations during inference.\n        If calib_mode='naive', the min and max values of the layer outputs from a calibration\n        dataset will be directly taken as the thresholds for quantization.\n        If calib_mode='entropy' (default mode), the thresholds for quantization will be\n        derived such that the KL divergence between the distributions of FP32 layer outputs and\n        quantized layer outputs is minimized based upon the calibration dataset.\n    quantized_dtype : str\n        The quantized destination type for input data. Currently support 'int8'\n        , 'uint8' and 'auto'. 'auto' means automatically select output type according to calibration result.\n        Default value is 'int8'.\n    logger : Object\n        A logging object for printing information during the process of quantization.\n    Returns\n    -------\n    quantized_model : tuple\n        A tuple of calibrated symbol, quantized arg_params, aux_params.\n    \"\"\"\n    min_max_dict = {}\n    if calib_mode is not None and calib_mode != 'none':\n        if calib_mode in ('entropy', 'naive', 'custom'):\n            min_max_dict = collector.post_collect()\n\n        else:\n            raise ValueError('unknown calibration mode %s received,'\n                             ' expected `none`, `naive`, `entropy` or `custom`' % calib_mode)\n        qsym = _calibrate_quantized_sym(qsym, min_max_dict)\n    else:\n        raise ValueError('Please set calibration mode to naive, entropy or custom (with custom CalibrationCollector)')\n\n    if logger:\n        logger.info('Quantizing parameters')\n    qarg_params = _quantize_params(qsym, arg_params, min_max_dict)\n\n    if is_np_array():\n        qsym = qsym.as_np_ndarray()\n\n    return qsym, qarg_params, aux_params\n\n@wrap_ctx_to_device_func\ndef quantize_net(network, quantized_dtype='auto', quantize_mode='full', quantize_granularity='tensor-wise',\n                 exclude_layers=None, exclude_layers_match=None, exclude_operators=None,\n                 calib_data=None, data_shapes=None, calib_mode='none',\n                 num_calib_batches=None, device=cpu(), LayerOutputCollector=None, logger=None):\n    \"\"\"User-level API for Gluon users to generate a quantized SymbolBlock from a FP32 HybridBlock w/ or w/o calibration.\n    The backend quantized operators are only enabled for Linux systems. Please do not run\n    inference using the quantized models on Windows for now.\n\n    Parameters\n    ----------\n    network : Gluon HybridBlock\n        Defines the structure of a neural network for FP32 data types.\n    quantized_dtype : str\n        The quantized destination type for input data. Currently support 'int8'\n        , 'uint8' and 'auto'. 'auto' means automatically select output type according to calibration result.\n        Default value is 'int8'.\n    quantize_mode : str\n        The mode that quantization pass to apply. Support 'full' and 'smart'.\n        'full' means quantize all operator if possible.\n        'smart' means quantization pass will smartly choice which operator should be quantized.\n    quantize_granularity: str\n        The granularity of quantization, currently supports 'tensor-wise' and 'channel-wise'\n        quantization. The default value is 'tensor-wise'.\n    exclude_layers : list of strings\n        A list of strings representing the names of the symbols that users want to excluding\n    exclude_layers_match : list of strings\n        A list of strings wildcard matching the names of the symbols that users want to excluding\n        from being quantized.\n    exclude_operators : list of strings\n        A list of strings representing the names of the operators that users want to excluding\n    calib_data : gluon.DataLoader\n        A iterable data loading object.\n    data_shapes : list of DataDesc or list of tuple\n        A list of data shapes. Required if calib_data is not provided. In case of tuples,\n        the names of inputs are generated.\n    calib_mode : str\n        If calib_mode='none', no calibration will be used and the thresholds for\n        requantization after the corresponding layers will be calculated at runtime by\n        calling min and max operators. The quantized models generated in this\n        mode are normally 10-20% slower than those with calibrations during inference.\n        If calib_mode='naive', the min and max values of the layer outputs from a calibration\n        dataset will be directly taken as the thresholds for quantization.\n        If calib_mode='entropy' (default mode), the thresholds for quantization will be\n        derived such that the KL divergence between the distributions of FP32 layer outputs and\n        quantized layer outputs is minimized based upon the calibration dataset.\n        If calib_mode='custom', the provided LayerOutputCollector will be used to determine\n        the thresholds for quantization. For more information refer to CalibrationCollector\n        documentation.\n    num_calib_batches : int or None\n        The maximum number of batches that user would like to use for calibration. If not provided,\n        the whole calibration dataset will be used.\n    device : Device\n        Defines the device that users want to run forward propagation on the calibration\n        dataset for collecting layer output statistics. Currently, only supports single device.\n    LayerOutputCollector : subclass of CalibrationCollector\n        For `custom` calibration method usage.\n        Passed object's include_layers attribute will be feed with names of layers which needs calibration\n    logger : Object\n        A logging object for printing information during the process of quantization.\n\n    Returns\n    -------\n    network : Gluon SymbolBlock\n        Defines the structure of a neural network for INT8 data types.\n    \"\"\"\n    from ..gluon import SymbolBlock\n\n    if device != mx.cpu():\n        raise ValueError('Quantization currently supports only CPU device')\n    backend = 'ONEDNN_QUANTIZE'\n\n    network.hybridize(static_alloc=False, static_shape=False)\n    data_types = None\n    if data_shapes is None:\n        if calib_data is None:\n            raise ValueError('At least one of data_shapes or calib_data has to be provided.')\n\n        if isinstance(calib_data, mx.gluon.data.DataLoader):\n            x = iter(calib_data)\n            batch = next(x)\n            if isinstance(batch, list):\n                data_shapes = [b.shape for b in batch]\n                data_types = [b.dtype for b in batch]\n            else:\n                data_shapes = [batch.shape]\n                data_types = [batch.dtype]\n        else:\n            raise ValueError('calib_data expects mx.gluon.data.DataLoader')\n\n    if data_types is None:\n        data_types = [mx_real_t] * len(data_shapes)\n    data_descs = _generate_list_of_data_desc(data_shapes, data_types)\n\n    num_inputs = len(data_descs)\n    data_nd = []\n    for desc in data_descs:\n        if is_np_array():\n            data_nd.append(mx.np.zeros(shape=desc.shape, dtype=desc.dtype))\n        else:\n            data_nd.append(mx.nd.zeros(shape=desc.shape, dtype=desc.dtype))\n    while True:\n        try:\n            network(*data_nd)\n        except (ValueError, TypeError) as err:\n            if logger:\n                logger.warning(err)\n                logger.warning(\"Deduced input data descriptors failed to run forward pass.\"\n                               \" Trying again with one less input.\")\n            del data_nd[-1]\n            num_inputs -= 1\n            data_shapes = [b.shape for b in data_nd]\n            data_types = [b.dtype for b in data_nd]\n            data_descs = _generate_list_of_data_desc(data_shapes, data_types)\n            continue\n        else:\n            break\n\n    symnet, params = network.export(None)\n    symnet = symnet.optimize_for(backend=backend)\n\n    if is_np_array():\n        symnet = symnet.as_np_ndarray()\n\n    args, auxs = dict(), dict()\n    for k, v in params.items():\n        ptype, pname = k[:3], k[4:]\n        if ptype == \"arg\":\n            args[pname] = v\n        else:\n            auxs[pname] = v\n\n    if exclude_layers is None:\n        exclude_layers = []\n    if exclude_layers_match is None:\n        exclude_layers_match = []\n    if exclude_operators is None:\n        exclude_operators = []\n    for name_match in exclude_layers_match:\n        for layers in list(symnet.get_internals()):\n            if layers.name.find(name_match) != -1:\n                exclude_layers.append(layers.name)\n    if logger:\n        logger.info('These layers have been excluded %s' % exclude_layers)\n\n    qsym, qarg_params, aux_params, collector, _ = quantize_graph(\n        sym=symnet, arg_params=args, aux_params=auxs, device=device,\n        excluded_sym_names=exclude_layers, excluded_op_names=exclude_operators,\n        calib_mode=calib_mode, quantized_dtype=quantized_dtype, quantize_mode=quantize_mode,\n        quantize_granularity=quantize_granularity, LayerOutputCollector=LayerOutputCollector,\n        logger=logger)\n\n    if calib_mode is not None and calib_mode != 'none':\n        if not isinstance(device, Device):\n            raise ValueError(\n                'currently only supports single device, while received %s' % str(device))\n        if calib_data is None:\n            raise ValueError(\n                'calib_data must be provided when calib_mode=%s' % calib_mode)\n        if calib_mode in ['naive', 'entropy', 'custom']:\n            inputs = [mx.sym.var(desc.name) for desc in data_descs]\n            calib_net = SymbolBlock(symnet, inputs)\n            calib_net.load_dict(params, cast_dtype=True, dtype_source='saved')\n            calib_net.hybridize(static_alloc=False, static_shape=False)\n            num_batches = _collect_layer_statistics(calib_net, calib_data, collector, num_inputs,\n                                                    num_calib_batches, logger)\n\n            if logger:\n                logger.info('Collected layer output values from FP32 model using %d batches'\n                            % num_batches)\n\n            qsym, qarg_params, aux_params = calib_graph(\n                qsym=qsym, arg_params=args, aux_params=auxs, collector=collector,\n                calib_mode=calib_mode, logger=logger)\n        else:\n            raise ValueError('calib_mode has to be one of: naive, entropy, custom')\n    elif calib_mode is not None and calib_mode == 'none':\n        inputs = [mx.sym.var(desc.name) for desc in data_descs]\n\n    net = SymbolBlock(qsym, inputs)\n    all_params = {('arg:%s' % k): v.as_in_context(cpu()) for k, v in qarg_params.items()}\n    all_params.update({('aux:%s' % k): v.as_in_context(cpu()) for k, v in aux_params.items()})\n    net.load_dict(all_params, cast_dtype=True, dtype_source='saved')\n    net.optimize_for(data_nd, backend=backend, skip_infer=True)\n    return net\n", "meta": {"hexsha": "be0282fe8a81eb40f7ff06700cd7a13194b9dc9b", "size": 46392, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/mxnet/contrib/quantization.py", "max_stars_repo_name": "Hunter-Zolomon/incubator-mxnet", "max_stars_repo_head_hexsha": "3b5a1f901872958971dca4cd3358a6418826cb04", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-09T01:40:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T01:40:17.000Z", "max_issues_repo_path": "python/mxnet/contrib/quantization.py", "max_issues_repo_name": "Hunter-Zolomon/incubator-mxnet", "max_issues_repo_head_hexsha": "3b5a1f901872958971dca4cd3358a6418826cb04", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/mxnet/contrib/quantization.py", "max_forks_repo_name": "Hunter-Zolomon/incubator-mxnet", "max_forks_repo_head_hexsha": "3b5a1f901872958971dca4cd3358a6418826cb04", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-07-19T00:43:30.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-19T00:43:30.000Z", "avg_line_length": 49.1440677966, "max_line_length": 120, "alphanum_fraction": 0.6437101224, "include": true, "reason": "import numpy", "num_tokens": 9716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.331119752830196, "lm_q1q2_score": 0.19873421643383807}}
{"text": "from abc import ABCMeta, abstractmethod\nfrom collections import Iterable\nfrom numbers import Integral, Real\nfrom warnings import warn\n\nfrom six import add_metaclass\nimport numpy as np\n\nfrom .function import Tabulated1D, INTERPOLATION_SCHEME\nfrom openmc.stats.univariate import Univariate, Tabular, Discrete, Mixture\nimport openmc.checkvalue as cv\nfrom openmc.mixin import EqualityMixin\nfrom .data import EV_PER_MEV\nfrom .endf import get_tab1_record, get_tab2_record\n\n\n@add_metaclass(ABCMeta)\nclass EnergyDistribution(EqualityMixin):\n    \"\"\"Abstract superclass for all energy distributions.\"\"\"\n    def __init__(self):\n        pass\n\n    @abstractmethod\n    def to_hdf5(self, group):\n        pass\n\n    @staticmethod\n    def from_hdf5(group):\n        \"\"\"Generate energy distribution from HDF5 data\n\n        Parameters\n        ----------\n        group : h5py.Group\n            HDF5 group to read from\n\n        Returns\n        -------\n        openmc.data.EnergyDistribution\n            Energy distribution\n\n        \"\"\"\n        energy_type = group.attrs['type'].decode()\n        if energy_type == 'maxwell':\n            return MaxwellEnergy.from_hdf5(group)\n        elif energy_type == 'evaporation':\n            return Evaporation.from_hdf5(group)\n        elif energy_type == 'watt':\n            return WattEnergy.from_hdf5(group)\n        elif energy_type == 'madland-nix':\n            return MadlandNix.from_hdf5(group)\n        elif energy_type == 'discrete_photon':\n            return DiscretePhoton.from_hdf5(group)\n        elif energy_type == 'level':\n            return LevelInelastic.from_hdf5(group)\n        elif energy_type == 'continuous':\n            return ContinuousTabular.from_hdf5(group)\n        else:\n            raise ValueError(\"Unknown energy distribution type: {}\"\n                             .format(energy_type))\n\n    @staticmethod\n    def from_endf(file_obj, params):\n        \"\"\"Generate energy distribution from an ENDF evaluation\n\n        Parameters\n        ----------\n        file_obj : file-like object\n            ENDF file positioned at the start of a section for an energy\n            distribution.\n        params : list\n            List of parameters at the start of the energy distribution that\n            includes the LF value indicating what type of energy distribution is\n            present.\n\n        Returns\n        -------\n        openmc.data.EnergyDistribution\n            A sub-class of :class:`openmc.data.EnergyDistribution`\n\n        \"\"\"\n        lf = params[3]\n        if lf == 1:\n            return ArbitraryTabulated.from_endf(file_obj, params)\n        elif lf == 5:\n            return GeneralEvaporation.from_endf(file_obj, params)\n        elif lf == 7:\n            return MaxwellEnergy.from_endf(file_obj, params)\n        elif lf == 9:\n            return Evaporation.from_endf(file_obj, params)\n        elif lf == 11:\n            return WattEnergy.from_endf(file_obj, params)\n        elif lf == 12:\n            return MadlandNix.from_endf(file_obj, params)\n\n\nclass ArbitraryTabulated(EnergyDistribution):\n    r\"\"\"Arbitrary tabulated function given in ENDF MF=5, LF=1 represented as\n\n    .. math::\n         f(E \\rightarrow E') = g(E \\rightarrow E')\n\n    Parameters\n    ----------\n    energy : numpy.ndarray\n        Array of incident neutron energies\n    pdf : list of openmc.data.Tabulated1D\n        Tabulated outgoing energy distribution probability density functions\n\n    Attributes\n    ----------\n    energy : numpy.ndarray\n        Array of incident neutron energies\n    pdf : list of openmc.data.Tabulated1D\n        Tabulated outgoing energy distribution probability density functions\n\n    \"\"\"\n\n    def __init__(self, energy, pdf):\n        super(ArbitraryTabulated, self).__init__()\n        self.energy = energy\n        self.pdf = pdf\n\n    def to_hdf5(self, group):\n        raise NotImplementedError\n\n    @classmethod\n    def from_endf(cls, file_obj, params):\n        \"\"\"Generate arbitrary tabulated distribution from an ENDF evaluation\n\n        Parameters\n        ----------\n        file_obj : file-like object\n            ENDF file positioned at the start of a section for an energy\n            distribution.\n        params : list\n            List of parameters at the start of the energy distribution that\n            includes the LF value indicating what type of energy distribution is\n            present.\n\n        Returns\n        -------\n        openmc.data.ArbitraryTabulated\n            Arbitrary tabulated distribution\n\n        \"\"\"\n        params, tab2 = get_tab2_record(file_obj)\n        n_energies = params[5]\n\n        energy = np.zeros(n_energies)\n        pdf = []\n        for j in range(n_energies):\n            params, func = get_tab1_record(file_obj)\n            energy[j] = params[1]\n            pdf.append(func)\n        return cls(energy, pdf)\n\n\nclass GeneralEvaporation(EnergyDistribution):\n    r\"\"\"General evaporation spectrum given in ENDF MF=5, LF=5 represented as\n\n    .. math::\n        f(E \\rightarrow E') = g(E'/\\theta(E))\n\n    Parameters\n    ----------\n    theta : openmc.data.Tabulated1D\n        Tabulated function of incident neutron energy :math:`E`\n    g : openmc.data.Tabulated1D\n        Tabulated function of :math:`x = E'/\\theta(E)`\n    u : float\n        Constant introduced to define the proper upper limit for the final\n        particle energy such that :math:`0 \\le E' \\le E - U`\n\n    Attributes\n    ----------\n    theta : openmc.data.Tabulated1D\n        Tabulated function of incident neutron energy :math:`E`\n    g : openmc.data.Tabulated1D\n        Tabulated function of :math:`x = E'/\\theta(E)`\n    u : float\n        Constant introduced to define the proper upper limit for the final\n        particle energy such that :math:`0 \\le E' \\le E - U`\n\n    \"\"\"\n\n    def __init__(self, theta, g, u):\n        super(GeneralEvaporation, self).__init__()\n        self.theta = theta\n        self.g = g\n        self.u = u\n\n    def to_hdf5(self, group):\n        raise NotImplementedError\n\n    @classmethod\n    def from_ace(cls, ace, idx=0):\n        raise NotImplementedError\n\n    @classmethod\n    def from_endf(cls, file_obj, params):\n        \"\"\"Generate general evaporation spectrum from an ENDF evaluation\n\n        Parameters\n        ----------\n        file_obj : file-like object\n            ENDF file positioned at the start of a section for an energy\n            distribution.\n        params : list\n            List of parameters at the start of the energy distribution that\n            includes the LF value indicating what type of energy distribution is\n            present.\n\n        Returns\n        -------\n        openmc.data.GeneralEvaporation\n            General evaporation spectrum\n\n        \"\"\"\n        u = params[0]\n        params, theta = get_tab1_record(file_obj)\n        params, g = get_tab1_record(file_obj)\n        return cls(theta, g, u)\n\n\nclass MaxwellEnergy(EnergyDistribution):\n    r\"\"\"Simple Maxwellian fission spectrum represented as\n\n    .. math::\n        f(E \\rightarrow E') = \\frac{\\sqrt{E'}}{I} e^{-E'/\\theta(E)}\n\n    Parameters\n    ----------\n    theta : openmc.data.Tabulated1D\n        Tabulated function of incident neutron energy\n    u : float\n        Constant introduced to define the proper upper limit for the final\n        particle energy such that :math:`0 \\le E' \\le E - U`\n\n    Attributes\n    ----------\n    theta : openmc.data.Tabulated1D\n        Tabulated function of incident neutron energy\n    u : float\n        Constant introduced to define the proper upper limit for the final\n        particle energy such that :math:`0 \\le E' \\le E - U`\n\n    \"\"\"\n\n    def __init__(self, theta, u):\n        super(MaxwellEnergy, self).__init__()\n        self.theta = theta\n        self.u = u\n\n    @property\n    def theta(self):\n        return self._theta\n\n    @property\n    def u(self):\n        return self._u\n\n    @theta.setter\n    def theta(self, theta):\n        cv.check_type('Maxwell theta', theta, Tabulated1D)\n        self._theta = theta\n\n    @u.setter\n    def u(self, u):\n        cv.check_type('Maxwell restriction energy', u, Real)\n        self._u = u\n\n    def to_hdf5(self, group):\n        \"\"\"Write distribution to an HDF5 group\n\n        Parameters\n        ----------\n        group : h5py.Group\n            HDF5 group to write to\n\n        \"\"\"\n\n        group.attrs['type'] = np.string_('maxwell')\n        group.attrs['u'] = self.u\n        self.theta.to_hdf5(group, 'theta')\n\n    @classmethod\n    def from_hdf5(cls, group):\n        \"\"\"Generate Maxwell distribution from HDF5 data\n\n        Parameters\n        ----------\n        group : h5py.Group\n            HDF5 group to read from\n\n        Returns\n        -------\n        openmc.data.MaxwellEnergy\n            Maxwell distribution\n\n        \"\"\"\n        theta = Tabulated1D.from_hdf5(group['theta'])\n        u = group.attrs['u']\n        return cls(theta, u)\n\n    @classmethod\n    def from_ace(cls, ace, idx=0):\n        \"\"\"Create a Maxwell distribution from an ACE table\n\n        Parameters\n        ----------\n        ace : openmc.data.ace.Table\n            An ACE table\n        idx : int\n            Offset to read from in XSS array (default of zero)\n\n        Returns\n        -------\n        openmc.data.MaxwellEnergy\n            Maxwell distribution\n\n        \"\"\"\n        # Read nuclear temperature -- since units are MeV, convert to eV\n        theta = Tabulated1D.from_ace(ace, idx)\n        theta.y *= EV_PER_MEV\n\n        # Restriction energy\n        nr = int(ace.xss[idx])\n        ne = int(ace.xss[idx + 1 + 2*nr])\n        u = ace.xss[idx + 2 + 2*nr + 2*ne]*EV_PER_MEV\n\n        return cls(theta, u)\n\n    @classmethod\n    def from_endf(cls, file_obj, params):\n        \"\"\"Generate Maxwell distribution from an ENDF evaluation\n\n        Parameters\n        ----------\n        file_obj : file-like object\n            ENDF file positioned at the start of a section for an energy\n            distribution.\n        params : list\n            List of parameters at the start of the energy distribution that\n            includes the LF value indicating what type of energy distribution is\n            present.\n\n        Returns\n        -------\n        openmc.data.MaxwellEnergy\n            Maxwell distribution\n\n        \"\"\"\n        u = params[0]\n        params, theta = get_tab1_record(file_obj)\n        return cls(theta, u)\n\n\nclass Evaporation(EnergyDistribution):\n    r\"\"\"Evaporation spectrum represented as\n\n    .. math::\n        f(E \\rightarrow E') = \\frac{E'}{I} e^{-E'/\\theta(E)}\n\n    Parameters\n    ----------\n    theta : openmc.data.Tabulated1D\n        Tabulated function of incident neutron energy\n    u : float\n        Constant introduced to define the proper upper limit for the final\n        particle energy such that :math:`0 \\le E' \\le E - U`\n\n    Attributes\n    ----------\n    theta : openmc.data.Tabulated1D\n        Tabulated function of incident neutron energy\n    u : float\n        Constant introduced to define the proper upper limit for the final\n        particle energy such that :math:`0 \\le E' \\le E - U`\n\n    \"\"\"\n\n    def __init__(self, theta, u):\n        super(Evaporation, self).__init__()\n        self.theta = theta\n        self.u = u\n\n    @property\n    def theta(self):\n        return self._theta\n\n    @property\n    def u(self):\n        return self._u\n\n    @theta.setter\n    def theta(self, theta):\n        cv.check_type('Evaporation theta', theta, Tabulated1D)\n        self._theta = theta\n\n    @u.setter\n    def u(self, u):\n        cv.check_type('Evaporation restriction energy', u, Real)\n        self._u = u\n\n    def to_hdf5(self, group):\n        \"\"\"Write distribution to an HDF5 group\n\n        Parameters\n        ----------\n        group : h5py.Group\n            HDF5 group to write to\n\n        \"\"\"\n\n        group.attrs['type'] = np.string_('evaporation')\n        group.attrs['u'] = self.u\n        self.theta.to_hdf5(group, 'theta')\n\n    @classmethod\n    def from_hdf5(cls, group):\n        \"\"\"Generate evaporation spectrum from HDF5 data\n\n        Parameters\n        ----------\n        group : h5py.Group\n            HDF5 group to read from\n\n        Returns\n        -------\n        openmc.data.Evaporation\n            Evaporation spectrum\n\n        \"\"\"\n        theta = Tabulated1D.from_hdf5(group['theta'])\n        u = group.attrs['u']\n        return cls(theta, u)\n\n    @classmethod\n    def from_ace(cls, ace, idx=0):\n        \"\"\"Create an evaporation spectrum from an ACE table\n\n        Parameters\n        ----------\n        ace : openmc.data.ace.Table\n            An ACE table\n        idx : int\n            Offset to read from in XSS array (default of zero)\n\n        Returns\n        -------\n        openmc.data.Evaporation\n            Evaporation spectrum\n\n        \"\"\"\n        # Read nuclear temperature -- since units are MeV, convert to eV\n        theta = Tabulated1D.from_ace(ace, idx)\n        theta.y *= EV_PER_MEV\n\n        # Restriction energy\n        nr = int(ace.xss[idx])\n        ne = int(ace.xss[idx + 1 + 2*nr])\n        u = ace.xss[idx + 2 + 2*nr + 2*ne]*EV_PER_MEV\n\n        return cls(theta, u)\n\n    @classmethod\n    def from_endf(cls, file_obj, params):\n        \"\"\"Generate evaporation spectrum from an ENDF evaluation\n\n        Parameters\n        ----------\n        file_obj : file-like object\n            ENDF file positioned at the start of a section for an energy\n            distribution.\n        params : list\n            List of parameters at the start of the energy distribution that\n            includes the LF value indicating what type of energy distribution is\n            present.\n\n        Returns\n        -------\n        openmc.data.Evaporation\n            Evaporation spectrum\n\n        \"\"\"\n        u = params[0]\n        params, theta = get_tab1_record(file_obj)\n        return cls(theta, u)\n\n\nclass WattEnergy(EnergyDistribution):\n    r\"\"\"Energy-dependent Watt spectrum represented as\n\n    .. math::\n        f(E \\rightarrow E') = \\frac{e^{-E'/a}}{I} \\sinh \\left ( \\sqrt{bE'}\n        \\right )\n\n    Parameters\n    ----------\n    a, b : openmc.data.Tabulated1D\n        Energy-dependent parameters tabulated as function of incident neutron\n        energy\n    u : float\n        Constant introduced to define the proper upper limit for the final\n        particle energy such that :math:`0 \\le E' \\le E - U`\n\n    Attributes\n    ----------\n    a, b : openmc.data.Tabulated1D\n        Energy-dependent parameters tabulated as function of incident neutron\n        energy\n    u : float\n        Constant introduced to define the proper upper limit for the final\n        particle energy such that :math:`0 \\le E' \\le E - U`\n\n    \"\"\"\n\n    def __init__(self, a, b, u):\n        super(WattEnergy, self).__init__()\n        self.a = a\n        self.b = b\n        self.u = u\n\n    @property\n    def a(self):\n        return self._a\n\n    @property\n    def b(self):\n        return self._b\n\n    @property\n    def u(self):\n        return self._u\n\n    @a.setter\n    def a(self, a):\n        cv.check_type('Watt a', a, Tabulated1D)\n        self._a = a\n\n    @b.setter\n    def b(self, b):\n        cv.check_type('Watt b', b, Tabulated1D)\n        self._b = b\n\n    @u.setter\n    def u(self, u):\n        cv.check_type('Watt restriction energy', u, Real)\n        self._u = u\n\n    def to_hdf5(self, group):\n        \"\"\"Write distribution to an HDF5 group\n\n        Parameters\n        ----------\n        group : h5py.Group\n            HDF5 group to write to\n\n        \"\"\"\n\n        group.attrs['type'] = np.string_('watt')\n        group.attrs['u'] = self.u\n        self.a.to_hdf5(group, 'a')\n        self.b.to_hdf5(group, 'b')\n\n    @classmethod\n    def from_hdf5(cls, group):\n        \"\"\"Generate Watt fission spectrum from HDF5 data\n\n        Parameters\n        ----------\n        group : h5py.Group\n            HDF5 group to read from\n\n        Returns\n        -------\n        openmc.data.WattEnergy\n            Watt fission spectrum\n\n        \"\"\"\n        a = Tabulated1D.from_hdf5(group['a'])\n        b = Tabulated1D.from_hdf5(group['b'])\n        u = group.attrs['u']\n        return cls(a, b, u)\n\n    @classmethod\n    def from_ace(cls, ace, idx):\n        \"\"\"Create a Watt fission spectrum from an ACE table\n\n        Parameters\n        ----------\n        ace : openmc.data.ace.Table\n            An ACE table\n        idx : int\n            Offset to read from in XSS array (default of zero)\n\n        Returns\n        -------\n        openmc.data.WattEnergy\n            Watt fission spectrum\n\n        \"\"\"\n        # Energy-dependent a parameter -- units are MeV, convert to eV\n        a = Tabulated1D.from_ace(ace, idx)\n        a.y *= EV_PER_MEV\n\n        # Advance index\n        nr = int(ace.xss[idx])\n        ne = int(ace.xss[idx + 1 + 2*nr])\n        idx += 2 + 2*nr + 2*ne\n\n        # Energy-dependent b parameter -- units are MeV^-1\n        b = Tabulated1D.from_ace(ace, idx)\n        b.y /= EV_PER_MEV\n\n        # Advance index\n        nr = int(ace.xss[idx])\n        ne = int(ace.xss[idx + 1 + 2*nr])\n        idx += 2 + 2*nr + 2*ne\n\n        # Restriction energy\n        u = ace.xss[idx]*EV_PER_MEV\n\n        return cls(a, b, u)\n\n    @classmethod\n    def from_endf(cls, file_obj, params):\n        \"\"\"Generate Watt fission spectrum from an ENDF evaluation\n\n        Parameters\n        ----------\n        file_obj : file-like object\n            ENDF file positioned at the start of a section for an energy\n            distribution.\n        params : list\n            List of parameters at the start of the energy distribution that\n            includes the LF value indicating what type of energy distribution is\n            present.\n\n        Returns\n        -------\n        openmc.data.WattEnergy\n            Watt fission spectrum\n\n        \"\"\"\n        u = params[0]\n        params, a = get_tab1_record(file_obj)\n        params, b = get_tab1_record(file_obj)\n        return cls(a, b, u)\n\n\nclass MadlandNix(EnergyDistribution):\n    r\"\"\"Energy-dependent fission neutron spectrum (Madland and Nix) given in\n    ENDF MF=5, LF=12 represented as\n\n    .. math::\n        f(E \\rightarrow E') = \\frac{1}{2} [ g(E', E_F(L)) + g(E', E_F(H))]\n\n    where\n\n    .. math::\n        g(E',E_F) = \\frac{1}{3\\sqrt{E_F T_M}} \\left [ u_2^{3/2} E_1 (u_2) -\n        u_1^{3/2} E_1 (u_1) + \\gamma \\left ( \\frac{3}{2}, u_2 \\right ) - \\gamma\n        \\left ( \\frac{3}{2}, u_1 \\right ) \\right ] \\\\ u_1 = \\left ( \\sqrt{E'} -\n        \\sqrt{E_F} \\right )^2 / T_M \\\\ u_2 = \\left ( \\sqrt{E'} + \\sqrt{E_F}\n        \\right )^2 / T_M.\n\n    Parameters\n    ----------\n    efl, efh : float\n        Constants which represent the average kinetic energy per nucleon of the\n        fission fragment (efl = light, efh = heavy)\n    tm : openmc.data.Tabulated1D\n        Parameter tabulated as a function of incident neutron energy\n\n    Attributes\n    ----------\n    efl, efh : float\n        Constants which represent the average kinetic energy per nucleon of the\n        fission fragment (efl = light, efh = heavy)\n    tm : openmc.data.Tabulated1D\n        Parameter tabulated as a function of incident neutron energy\n\n    \"\"\"\n\n    def __init__(self, efl, efh, tm):\n        super(MadlandNix, self).__init__()\n        self.efl = efl\n        self.efh = efh\n        self.tm = tm\n\n    @property\n    def efl(self):\n        return self._efl\n\n    @property\n    def efh(self):\n        return self._efh\n\n    @property\n    def tm(self):\n        return self._tm\n\n    @efl.setter\n    def efl(self, efl):\n        name = 'Madland-Nix light fragment energy'\n        cv.check_type(name, efl, Real)\n        cv.check_greater_than(name, efl, 0.)\n        self._efl = efl\n\n    @efh.setter\n    def efh(self, efh):\n        name = 'Madland-Nix heavy fragment energy'\n        cv.check_type(name, efh, Real)\n        cv.check_greater_than(name, efh, 0.)\n        self._efh = efh\n\n    @tm.setter\n    def tm(self, tm):\n        cv.check_type('Madland-Nix maximum temperature', tm, Tabulated1D)\n        self._tm = tm\n\n    def to_hdf5(self, group):\n        \"\"\"Write distribution to an HDF5 group\n\n        Parameters\n        ----------\n        group : h5py.Group\n            HDF5 group to write to\n\n        \"\"\"\n\n        group.attrs['type'] = np.string_('madland-nix')\n        group.attrs['efl'] = self.efl\n        group.attrs['efh'] = self.efh\n        self.tm.to_hdf5(group)\n\n    @classmethod\n    def from_hdf5(cls, group):\n        \"\"\"Generate Madland-Nix fission spectrum from HDF5 data\n\n        Parameters\n        ----------\n        group : h5py.Group\n            HDF5 group to read from\n\n        Returns\n        -------\n        openmc.data.MadlandNix\n            Madland-Nix fission spectrum\n\n        \"\"\"\n        efl = group.attrs['efl']\n        efh = group.attrs['efh']\n        tm = Tabulated1D.from_hdf5(group['tm'])\n        return cls(efl, efh, tm)\n\n    @classmethod\n    def from_endf(cls, file_obj, params):\n        \"\"\"Generate Madland-Nix fission spectrum from an ENDF evaluation\n\n        Parameters\n        ----------\n        file_obj : file-like object\n            ENDF file positioned at the start of a section for an energy\n            distribution.\n        params : list\n            List of parameters at the start of the energy distribution that\n            includes the LF value indicating what type of energy distribution is\n            present.\n\n        Returns\n        -------\n        openmc.data.MadlandNix\n            Madland-Nix fission spectrum\n\n        \"\"\"\n        params, tm = get_tab1_record(file_obj)\n        efl, efh = params[0:2]\n        return cls(efl, efh, tm)\n\n\n\nclass DiscretePhoton(EnergyDistribution):\n    \"\"\"Discrete photon energy distribution\n\n    Parameters\n    ----------\n    primary_flag : int\n        Indicator of whether the photon is a primary or non-primary photon.\n    energy : float\n        Photon energy (if lp==0 or lp==1) or binding energy (if lp==2).\n    atomic_weight_ratio : float\n        Atomic weight ratio of the target nuclide responsible for the emitted\n        particle\n\n    Attributes\n    ----------\n    primary_flag : int\n        Indicator of whether the photon is a primary or non-primary photon.\n    energy : float\n        Photon energy (if lp==0 or lp==1) or binding energy (if lp==2).\n    atomic_weight_ratio : float\n        Atomic weight ratio of the target nuclide responsible for the emitted\n        particle\n\n    \"\"\"\n\n    def __init__(self, primary_flag, energy, atomic_weight_ratio):\n        super(DiscretePhoton, self).__init__()\n        self.primary_flag = primary_flag\n        self.energy = energy\n        self.atomic_weight_ratio = atomic_weight_ratio\n\n    @property\n    def primary_flag(self):\n        return self._primary_flag\n\n    @property\n    def energy(self):\n        return self._energy\n\n    @property\n    def atomic_weight_ratio(self):\n        return self._atomic_weight_ratio\n\n    @primary_flag.setter\n    def primary_flag(self, primary_flag):\n        cv.check_type('discrete photon primary_flag', primary_flag, Integral)\n        self._primary_flag = primary_flag\n\n    @energy.setter\n    def energy(self, energy):\n        cv.check_type('discrete photon energy', energy, Real)\n        self._energy = energy\n\n    @atomic_weight_ratio.setter\n    def atomic_weight_ratio(self, atomic_weight_ratio):\n        cv.check_type('atomic weight ratio', atomic_weight_ratio, Real)\n        self._atomic_weight_ratio = atomic_weight_ratio\n\n    def to_hdf5(self, group):\n        \"\"\"Write distribution to an HDF5 group\n\n        Parameters\n        ----------\n        group : h5py.Group\n            HDF5 group to write to\n\n        \"\"\"\n\n        group.attrs['type'] = np.string_('discrete_photon')\n        group.attrs['primary_flag'] = self.primary_flag\n        group.attrs['energy'] = self.energy\n        group.attrs['atomic_weight_ratio'] = self.atomic_weight_ratio\n\n    @classmethod\n    def from_hdf5(cls, group):\n        \"\"\"Generate discrete photon energy distribution from HDF5 data\n\n        Parameters\n        ----------\n        group : h5py.Group\n            HDF5 group to read from\n\n        Returns\n        -------\n        openmc.data.DiscretePhoton\n            Discrete photon energy distribution\n\n        \"\"\"\n        primary_flag = group.attrs['primary_flag']\n        energy = group.attrs['energy']\n        awr = group.attrs['atomic_weight_ratio']\n        return cls(primary_flag, energy, awr)\n\n    @classmethod\n    def from_ace(cls, ace, idx):\n        \"\"\"Generate discrete photon energy distribution from an ACE table\n\n        Parameters\n        ----------\n        ace : openmc.data.ace.Table\n            An ACE table\n        idx : int\n            Offset to read from in XSS array (default of zero)\n\n        Returns\n        -------\n        openmc.data.DiscretePhoton\n            Discrete photon energy distribution\n\n        \"\"\"\n        primary_flag = int(ace.xss[idx])\n        energy = ace.xss[idx + 1]*EV_PER_MEV\n        return cls(primary_flag, energy, ace.atomic_weight_ratio)\n\n\nclass LevelInelastic(EnergyDistribution):\n    r\"\"\"Level inelastic scattering\n\n    Parameters\n    ----------\n    threshold : float\n        Energy threshold in the laboratory system, :math:`(A + 1)/A * |Q|`\n    mass_ratio : float\n        :math:`(A/(A + 1))^2`\n\n    Attributes\n    ----------\n    threshold : float\n        Energy threshold in the laboratory system, :math:`(A + 1)/A * |Q|`\n    mass_ratio : float\n        :math:`(A/(A + 1))^2`\n\n    \"\"\"\n\n    def __init__(self, threshold, mass_ratio):\n        super(LevelInelastic, self).__init__()\n        self.threshold = threshold\n        self.mass_ratio = mass_ratio\n\n    @property\n    def threshold(self):\n        return self._threshold\n\n    @property\n    def mass_ratio(self):\n        return self._mass_ratio\n\n    @threshold.setter\n    def threshold(self, threshold):\n        cv.check_type('level inelastic threhsold', threshold, Real)\n        self._threshold = threshold\n\n    @mass_ratio.setter\n    def mass_ratio(self, mass_ratio):\n        cv.check_type('level inelastic mass ratio', mass_ratio, Real)\n        self._mass_ratio = mass_ratio\n\n    def to_hdf5(self, group):\n        \"\"\"Write distribution to an HDF5 group\n\n        Parameters\n        ----------\n        group : h5py.Group\n            HDF5 group to write to\n\n        \"\"\"\n\n        group.attrs['type'] = np.string_('level')\n        group.attrs['threshold'] = self.threshold\n        group.attrs['mass_ratio'] = self.mass_ratio\n\n    @classmethod\n    def from_hdf5(cls, group):\n        \"\"\"Generate level inelastic distribution from HDF5 data\n\n        Parameters\n        ----------\n        group : h5py.Group\n            HDF5 group to read from\n\n        Returns\n        -------\n        openmc.data.LevelInelastic\n            Level inelastic scattering distribution\n\n        \"\"\"\n        threshold = group.attrs['threshold']\n        mass_ratio = group.attrs['mass_ratio']\n        return cls(threshold, mass_ratio)\n\n    @classmethod\n    def from_ace(cls, ace, idx):\n        \"\"\"Generate level inelastic distribution from an ACE table\n\n        Parameters\n        ----------\n        ace : openmc.data.ace.Table\n            An ACE table\n        idx : int\n            Offset to read from in XSS array (default of zero)\n\n        Returns\n        -------\n        openmc.data.LevelInelastic\n            Level inelastic scattering distribution\n\n        \"\"\"\n        threshold = ace.xss[idx]*EV_PER_MEV\n        mass_ratio = ace.xss[idx + 1]\n        return cls(threshold, mass_ratio)\n\n\nclass ContinuousTabular(EnergyDistribution):\n    \"\"\"Continuous tabular distribution\n\n    Parameters\n    ----------\n    breakpoints : Iterable of int\n        Breakpoints defining interpolation regions\n    interpolation : Iterable of int\n        Interpolation codes\n    energy : Iterable of float\n        Incoming energies at which distributions exist\n    energy_out : Iterable of openmc.stats.Univariate\n        Distribution of outgoing energies corresponding to each incoming energy\n\n    Attributes\n    ----------\n    breakpoints : Iterable of int\n        Breakpoints defining interpolation regions\n    interpolation : Iterable of int\n        Interpolation codes\n    energy : Iterable of float\n        Incoming energies at which distributions exist\n    energy_out : Iterable of openmc.stats.Univariate\n        Distribution of outgoing energies corresponding to each incoming energy\n\n    \"\"\"\n\n    def __init__(self, breakpoints, interpolation, energy, energy_out):\n        super(ContinuousTabular, self).__init__()\n        self.breakpoints = breakpoints\n        self.interpolation = interpolation\n        self.energy = energy\n        self.energy_out = energy_out\n\n    @property\n    def breakpoints(self):\n        return self._breakpoints\n\n    @property\n    def interpolation(self):\n        return self._interpolation\n\n    @property\n    def energy(self):\n        return self._energy\n\n    @property\n    def energy_out(self):\n        return self._energy_out\n\n    @breakpoints.setter\n    def breakpoints(self, breakpoints):\n        cv.check_type('continuous tabular breakpoints', breakpoints,\n                      Iterable, Integral)\n        self._breakpoints = breakpoints\n\n    @interpolation.setter\n    def interpolation(self, interpolation):\n        cv.check_type('continuous tabular interpolation', interpolation,\n                      Iterable, Integral)\n        self._interpolation = interpolation\n\n    @energy.setter\n    def energy(self, energy):\n        cv.check_type('continuous tabular incoming energy', energy,\n                      Iterable, Real)\n        self._energy = energy\n\n    @energy_out.setter\n    def energy_out(self, energy_out):\n        cv.check_type('continuous tabular outgoing energy', energy_out,\n                      Iterable, Univariate)\n        self._energy_out = energy_out\n\n    def to_hdf5(self, group):\n        \"\"\"Write distribution to an HDF5 group\n\n        Parameters\n        ----------\n        group : h5py.Group\n            HDF5 group to write to\n\n        \"\"\"\n\n        group.attrs['type'] = np.string_('continuous')\n\n        dset = group.create_dataset('energy', data=self.energy)\n        dset.attrs['interpolation'] = np.vstack((self.breakpoints,\n                                                 self.interpolation))\n\n        # Determine total number of (E,p) pairs and create array\n        n_pairs = sum(len(d) for d in self.energy_out)\n        pairs = np.empty((3, n_pairs))\n\n        # Create array for offsets\n        offsets = np.empty(len(self.energy_out), dtype=int)\n        interpolation = np.empty(len(self.energy_out), dtype=int)\n        n_discrete_lines = np.empty(len(self.energy_out), dtype=int)\n        j = 0\n\n        # Populate offsets and pairs array\n        for i, eout in enumerate(self.energy_out):\n            n = len(eout)\n            offsets[i] = j\n\n            if isinstance(eout, Mixture):\n                discrete, continuous = eout.distribution\n                n_discrete_lines[i] = m = len(discrete)\n                interpolation[i] = 1 if continuous.interpolation == 'histogram' else 2\n                pairs[0, j:j+m] = discrete.x\n                pairs[1, j:j+m] = discrete.p\n                pairs[2, j:j+m] = discrete.c\n                pairs[0, j+m:j+n] = continuous.x\n                pairs[1, j+m:j+n] = continuous.p\n                pairs[2, j+m:j+n] = continuous.c\n            else:\n                if isinstance(eout, Tabular):\n                    n_discrete_lines[i] = 0\n                    interpolation[i] = 1 if eout.interpolation == 'histogram' else 2\n                elif isinstance(eout, Discrete):\n                    n_discrete_lines[i] = n\n                    interpolation[i] = 1\n                pairs[0, j:j+n] = eout.x\n                pairs[1, j:j+n] = eout.p\n                pairs[2, j:j+n] = eout.c\n            j += n\n\n        # Create dataset for distributions\n        dset = group.create_dataset('distribution', data=pairs)\n\n        # Write interpolation as attribute\n        dset.attrs['offsets'] = offsets\n        dset.attrs['interpolation'] = interpolation\n        dset.attrs['n_discrete_lines'] = n_discrete_lines\n\n    @classmethod\n    def from_hdf5(cls, group):\n        \"\"\"Generate continuous tabular distribution from HDF5 data\n\n        Parameters\n        ----------\n        group : h5py.Group\n            HDF5 group to read from\n\n        Returns\n        -------\n        openmc.data.ContinuousTabular\n            Continuous tabular energy distribution\n\n        \"\"\"\n        interp_data = group['energy'].attrs['interpolation']\n        energy_breakpoints = interp_data[0, :]\n        energy_interpolation = interp_data[1, :]\n        energy = group['energy'].value\n\n        data = group['distribution']\n        offsets = data.attrs['offsets']\n        interpolation = data.attrs['interpolation']\n        n_discrete_lines = data.attrs['n_discrete_lines']\n\n        energy_out = []\n        n_energy = len(energy)\n        for i in range(n_energy):\n            # Determine length of outgoing energy distribution and number of\n            # discrete lines\n            j = offsets[i]\n            if i < n_energy - 1:\n                n = offsets[i+1] - j\n            else:\n                n = data.shape[1] - j\n            m = n_discrete_lines[i]\n\n            # Create discrete distribution if lines are present\n            if m > 0:\n                eout_discrete = Discrete(data[0, j:j+m], data[1, j:j+m])\n                eout_discrete.c = data[2, j:j+m]\n                p_discrete = eout_discrete.c[-1]\n\n            # Create continuous distribution\n            if m < n:\n                interp = INTERPOLATION_SCHEME[interpolation[i]]\n                eout_continuous = Tabular(data[0, j+m:j+n], data[1, j+m:j+n], interp)\n                eout_continuous.c = data[2, j+m:j+n]\n\n            # If both continuous and discrete are present, create a mixture\n            # distribution\n            if m == 0:\n                eout_i = eout_continuous\n            elif m == n:\n                eout_i = eout_discrete\n            else:\n                eout_i = Mixture([p_discrete, 1. - p_discrete],\n                                 [eout_discrete, eout_continuous])\n            energy_out.append(eout_i)\n\n        return cls(energy_breakpoints, energy_interpolation,\n                   energy, energy_out)\n\n    @classmethod\n    def from_ace(cls, ace, idx, ldis):\n        \"\"\"Generate continuous tabular energy distribution from ACE data\n\n        Parameters\n        ----------\n        ace : openmc.data.ace.Table\n            ACE table to read from\n        idx : int\n            Index in XSS array of the start of the energy distribution data\n            (LDIS + LOCC - 1)\n        ldis : int\n            Index in XSS array of the start of the energy distribution block\n            (e.g. JXS[11])\n\n        Returns\n        -------\n        openmc.data.ContinuousTabular\n            Continuous tabular energy distribution\n\n        \"\"\"\n        # Read number of interpolation regions and incoming energies\n        n_regions = int(ace.xss[idx])\n        n_energy_in = int(ace.xss[idx + 1 + 2*n_regions])\n\n        # Get interpolation information\n        idx += 1\n        if n_regions > 0:\n            breakpoints = ace.xss[idx:idx + n_regions].astype(int)\n            interpolation = ace.xss[idx + n_regions:idx + 2*n_regions].astype(int)\n        else:\n            breakpoints = np.array([n_energy_in])\n            interpolation = np.array([2])\n\n        # Incoming energies at which distributions exist\n        idx += 2*n_regions + 1\n        energy = ace.xss[idx:idx + n_energy_in]*EV_PER_MEV\n\n        # Location of distributions\n        idx += n_energy_in\n        loc_dist = ace.xss[idx:idx + n_energy_in].astype(int)\n\n        # Initialize variables\n        energy_out = []\n\n        # Read each outgoing energy distribution\n        for i in range(n_energy_in):\n            idx = ldis + loc_dist[i] - 1\n\n            # intt = interpolation scheme (1=hist, 2=lin-lin)\n            INTTp = int(ace.xss[idx])\n            intt = INTTp % 10\n            n_discrete_lines = (INTTp - intt)//10\n            if intt not in (1, 2):\n                warn(\"Interpolation scheme for continuous tabular distribution \"\n                     \"is not histogram or linear-linear.\")\n                intt = 2\n\n            n_energy_out = int(ace.xss[idx + 1])\n            data = ace.xss[idx + 2:idx + 2 + 3*n_energy_out].copy()\n            data.shape = (3, n_energy_out)\n            data[0,:] *= EV_PER_MEV\n\n            # Create continuous distribution\n            eout_continuous = Tabular(data[0][n_discrete_lines:],\n                                      data[1][n_discrete_lines:]/EV_PER_MEV,\n                                      INTERPOLATION_SCHEME[intt])\n            eout_continuous.c = data[2][n_discrete_lines:]\n\n            # If discrete lines are present, create a mixture distribution\n            if n_discrete_lines > 0:\n                eout_discrete = Discrete(data[0][:n_discrete_lines],\n                                         data[1][:n_discrete_lines])\n                eout_discrete.c = data[2][:n_discrete_lines]\n                if n_discrete_lines == n_energy_out:\n                    eout_i = eout_discrete\n                else:\n                    p_discrete = min(sum(eout_discrete.p), 1.0)\n                    eout_i = Mixture([p_discrete, 1. - p_discrete],\n                                     [eout_discrete, eout_continuous])\n            else:\n                eout_i = eout_continuous\n\n            energy_out.append(eout_i)\n\n        return cls(breakpoints, interpolation, energy, energy_out)\n", "meta": {"hexsha": "c3740beaf0c9e9bbd8bafab8e3891433190617f3", "size": 37230, "ext": "py", "lang": "Python", "max_stars_repo_path": "openmc/data/energy_distribution.py", "max_stars_repo_name": "ethanio12345/OpenMC", "max_stars_repo_head_hexsha": "3b0c044974c59773dac4e3ce261a87e18fc53de5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "openmc/data/energy_distribution.py", "max_issues_repo_name": "ethanio12345/OpenMC", "max_issues_repo_head_hexsha": "3b0c044974c59773dac4e3ce261a87e18fc53de5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openmc/data/energy_distribution.py", "max_forks_repo_name": "ethanio12345/OpenMC", "max_forks_repo_head_hexsha": "3b0c044974c59773dac4e3ce261a87e18fc53de5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0859375, "max_line_length": 86, "alphanum_fraction": 0.5788611335, "include": true, "reason": "import numpy", "num_tokens": 8648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.19873421324659063}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nThis module allows the analysis of surface-based molecular cavities in various\nvolumes. To do so, a volume and a list of atom positions and their cutoff radii\nis required. The following example shows reading the first frame of a ``xyz``\nfile (using the ``pybel`` module), defining a hexagonal volume and moving all\natoms into this volume.\n\n.. code-block:: python\n   :emphasize-lines: 7,10\n\n   import pybel\n\n   atoms = pybel.readfile(\"xyz\", \"hexagonal.xyz\").next().atoms\n   num_atoms = len(atoms)\n   atom_positions = [atom.coords for atom in atoms]\n\n   volume = volumes.HexagonalVolume(17.68943, 22.61158)\n   for atom_index in range(num_atoms):\n       atom_positions[atom_index] = volume.get_equivalent_point(atom_positions[atom_index])\n   atoms = Atoms(atom_positions, [2.8]*num_atoms)\n\nAfter this, a discretization of the volume is needed. This module supports\ncaching of these with the ``DiscretizationCache`` class.\n\n.. code-block:: python\n\n   discretization_cache = DiscretizationCache('cache.hdf5')\n   discretization = discretization_cache.get_discretization(volume, 192)\n\nUsing this ``discretization`` and the ``Atoms`` object created above, the atom\npositions and their cutoff radii are also discretized.\n\n.. code-block:: python\n\n   atom_discretization = AtomDiscretization(atoms, discretization)\n\nWith these objects created, all preparations are complete and the domain and\ncavity calculation can be done:\n\n.. code-block:: python\n\n   domain_calculation = DomainCalculation(discretization, atom_discretization)\n   cavity_calculation = CavityCalculation(domain_calculation)\n\nAdditionally, calculation of center-based cavities is possible by passing an\nadditional parameter to the CavityCalculation:\n\n.. code-block:: python\n\n   cavity_calculation = CavityCalculation(domain_calculation,\n                                          use_surface_points=False)\n\nThe FakeDomainCalculation class provides a drop-in replacement for the\ndomain_calculation object in case the results of a previous calculation need to\nbe used (this is possible as only those attributes which are stored are\nactually used during center-based cavity calculation, which is not the case for\nsurface-based cavity calculations, which at least require the surface point\nlists).\n\nThe CalculationResults class provides a container for the results and allows\nstorage to and retrieval from HDF5 files. These files have several groups which\ncontain the relevant information.\n\nAuthor: Florian Rhiem <f.rhiem@fz-juelich.de>\n\"\"\"\nfrom math import pi as PI\nimport sys\nimport numpy as np\n\nfrom computation.split_and_merge.pipeline import start_split_and_merge_pipeline\nfrom computation.split_and_merge.algorithm import ObjectType\nfrom core.calculation.gyrationtensor import calculate_gyration_tensor_parameters\nfrom util.message import print_message\nfrom extension import atomstogrid, mark_cavities, cavity_triangles, cavity_intersections\n\n\ndimension = 3\ndimensions = range(dimension)\n\n\nclass DomainCalculation:\n    \"\"\"\n    Cavity domain calulation is performed by the following steps:\n     1. A grid is created with the resolution defined in the volume\n        discretization and filled with zeros.\n     2. For each atom, all points in the grid closer to this atom than the\n        discrete cavity cutoff radius are set to a point indicating the atom\n        index (atom_index+1).\n     3. At this point, every point in the grid which is inside of the volume\n        and still has a value of zero is part of a cavity domain. To find these\n        domains, an optimized split and merge algorithm is applied to the whole\n        grid. It returns the center and surface points of each cavity domain\n        (points with a neighbor outside of the cavity domain) stored in lists.\n        Points inside of a domain are marked with a negative value indicating\n        which domain they are part of.\n    \"\"\"\n\n    def __init__(self, discretization, atom_discretization):\n        # step 1\n        self.discretization = discretization\n        self.atom_discretization = atom_discretization\n        self.grid = np.zeros(self.discretization.d, dtype=np.int64)\n\n        # step 2\n        atomstogrid(self.grid,\n                    self.atom_discretization.discrete_positions,\n                    self.atom_discretization.atoms.radii_as_indices,\n                    self.atom_discretization.sorted_discrete_radii,\n                    [(0, 0, 0)] + self.discretization.combined_translation_vectors,\n                    self.discretization.grid)\n        # step 3\n        result = start_split_and_merge_pipeline(self.grid,\n                                                self.discretization.grid,\n                                                self.atom_discretization.discrete_positions,\n                                                self.discretization.combined_translation_vectors,\n                                                self.discretization.get_translation_vector,\n                                                ObjectType.DOMAIN)\n        self.centers, translated_areas, non_translated_areas, self.surface_point_list, self.cyclic_area_indices = result\n        print_message(\"Number of domains:\", len(self.centers))\n\n        self.domain_volumes = []\n        self.critical_domains = []   # count of very small domains -> domains that can disappear on cutoff radius changes\n        for domain_index in range(len(self.centers)):\n            current_cell_sum = (self.grid == -(domain_index + 1)).sum()\n            if current_cell_sum == 1:\n                self.critical_domains.append(domain_index)\n            domain_volume = current_cell_sum * (self.discretization.s_step ** 3)\n            self.domain_volumes.append(domain_volume)\n\n        self.characteristic_radii = [(0.75 * volume / PI)**(1.0/3.0) for volume in self.domain_volumes]\n\n        if translated_areas:\n            gyration_tensor_parameters = tuple(calculate_gyration_tensor_parameters(area) for area in translated_areas)\n            (self.mass_centers, self.squared_gyration_radii, self.asphericities,\n             self.acylindricities, self.anisotropies) = zip(*gyration_tensor_parameters)\n            self.mass_centers = [self.discretization.discrete_to_continuous(point, result_inside_volume=True)\n                                 for point in self.mass_centers]\n            self.squared_gyration_radii = [self.discretization.discrete_to_continuous(value, unit_exponent=2)\n                                           for value in self.squared_gyration_radii]\n        else:\n            (self.mass_centers, self.squared_gyration_radii, self.asphericities,\n             self.acylindricities, self.anisotropies) = 5*([], )\n\n        self.triangles()\n\n    def triangles(self):\n        if hasattr(self, \"domain_triangles\"):\n            return self.domain_triangles\n        number_of_domains = len(self.centers)\n        print_message(\"Number of domains:\", number_of_domains)\n        triangles = []\n        surface_areas = []\n        step = (self.discretization.s_step,) * 3\n        offset = self.discretization.discrete_to_continuous((0, 0, 0))\n        for domain_index in range(number_of_domains):\n            print_message(\"Calculating triangles for domain\", domain_index)\n            vertices, normals, surface_area = cavity_triangles(\n                    self.grid,\n                    [domain_index],\n                    1, step, offset,\n                    self.discretization.grid)\n            triangles.append((vertices, normals))\n            surface_areas.append(surface_area)\n\n        self.domain_triangles = triangles\n        self.domain_surface_areas = surface_areas\n        return triangles\n\n\nclass CavityCalculation:\n    \"\"\"\n    Cavity domain calulation is performed by the following steps:\n     1. The discrete volume grid is divided into subgrid cells with a side\n        length based on the maximum discrete cavity cutoff radius. For each\n        subgrid, a tuple of three lists is stored (in self.sg).\n     2. The first list for each subgrid cell is filled with the atoms inside\n        the cell (their 'real' positions, which might be outside of the\n        volume).\n     3. The second and third lists are filled with surface points and their\n        domain index. (These might also be moved with the translation vectors\n        and might thereby also be outside of the volume.)\n     4. A new grid is created (grid3) and each point in this grid is set to\n        zero if it is outside of the volume or part inside of the cavity cutoff\n        radius of an atom, or a negative value if it is part of a cavity domain\n        (see the domain calculation step 2 for this).\n     5. For each point which is inside the cavity cutoff radius of an\n        atom, the nearest atom and the nearest domain surface point are found\n        by using the neighbor subgrid cells. If a domain surface point is\n        nearer than the nearest atom, than the point belongs to the cavity\n        which this surface point belonged to and is marked with a negative\n        value.\n     6. At this point, two cavities constructed from two cavity domains might\n        actually be one multicavity. In this step, these are found and a list\n        of multicavities is created.\n\n    About the subgrid cells:\n    If a point inside a subgrid cell was marked as 'near an atom' during the\n    domain calculation, then the position of this atom must be either in the\n    same cell or in one of the cell's neighbors. This is guaranteed, because\n    the atom must be at most its on cavity cutoff radius away, and the subgrid\n    cell size is the maximum cavity cutoff radius.\n\n\n    To calculate center-based cavities, use a grid filled with zeros instead of\n    resuing some values from the domain calculation grid and then iterate over\n    the domain centers instead of the domain surface points.\n    \"\"\"\n\n    def __init__(self, domain_calculation, use_surface_points=True, gyration_tensor_parameters=False):\n        self.domain_calculation = domain_calculation\n        if use_surface_points:\n            self.grid = self.domain_calculation.grid\n            num_surface_points = sum(map(len, self.domain_calculation.surface_point_list))\n            print_message(\"Number of surface points:\", num_surface_points)\n        else:\n            self.grid = None\n\n        self.sg_cube_size = self.domain_calculation.atom_discretization.sorted_discrete_radii[0]\n        if use_surface_points:\n            domain_seed_point_lists = self.domain_calculation.surface_point_list\n        else:\n            domain_seed_point_lists = [[center] for center in self.domain_calculation.centers]\n\n        discretization = self.domain_calculation.discretization\n        atom_discretization = self.domain_calculation.atom_discretization\n\n        # steps 1 to 5\n        self.grid3 = mark_cavities(self.grid,\n                                   discretization.grid,\n                                   discretization.d,\n                                   self.sg_cube_size,\n                                   atom_discretization.discrete_positions,\n                                   [(0, 0, 0)] + discretization.combined_translation_vectors,\n                                   domain_seed_point_lists,\n                                   use_surface_points)\n\n        if gyration_tensor_parameters:\n            result = start_split_and_merge_pipeline(self.grid3,\n                                                    discretization.grid,\n                                                    atom_discretization.discrete_positions,\n                                                    discretization.combined_translation_vectors,\n                                                    discretization.get_translation_vector,\n                                                    ObjectType.CAVITY)\n            translated_areas, non_translated_areas, cyclic_area_indices = result\n\n        num_domains = len(self.domain_calculation.centers)\n        grid_volume = (discretization.grid == 0).sum()\n        self.cavity_volumes = []\n        for domain_index in range(num_domains):\n            self.cavity_volumes.append(1.0 * (self.grid3 == -(domain_index + 1)).sum() * (discretization.s_step ** 3))\n        self.characteristic_radii = [(0.75 * volume / PI)**(1.0/3.0) for volume in self.cavity_volumes]\n\n        # step 6\n        intersection_table = cavity_intersections(self.grid3, num_domains)\n        multicavities = []\n        cavity_to_neighbors = num_domains * [None]\n        for domain in range(num_domains):\n            current_neighbors = set([domain])\n            for neighbor in range(num_domains):\n                if intersection_table[domain][neighbor] == 1:\n                    current_neighbors.add(neighbor)\n            for multicavity in multicavities[:]:\n                if any([neighbor in multicavity for neighbor in current_neighbors]):\n                    current_neighbors = current_neighbors | multicavity\n                    multicavities.remove(multicavity)\n            multicavities.append(current_neighbors)\n            for neighbor in current_neighbors:\n                cavity_to_neighbors[neighbor] = current_neighbors\n        self.multicavities = multicavities\n        self.multicavity_volumes = []\n        for multicavity in multicavities:\n            self.multicavity_volumes.append(sum(self.cavity_volumes[cavity_index] for cavity_index in multicavity))\n        print_message(\"Multicavity volumes:\", self.multicavity_volumes)\n\n        if gyration_tensor_parameters:\n            def key_func(cavity_index):\n                cavity_area = non_translated_areas[cavity_index]\n                a_single_cavity_index = -self.grid3[cavity_area[0]] - 1\n                max_neighbor_index = max(cavity_to_neighbors[a_single_cavity_index])\n                return max_neighbor_index\n            sorted_area_indices = sorted(range(len(self.multicavities)), key=key_func)\n            sorted_translated_areas = [translated_areas[i] for i in sorted_area_indices]\n            sorted_cyclic_area_indices = [i for i, index in enumerate(sorted_area_indices)\n                                        if index in cyclic_area_indices]\n            self.cyclic_area_indices = sorted_cyclic_area_indices\n\n            if sorted_translated_areas:\n                gyration_tensor_parameters = tuple(calculate_gyration_tensor_parameters(area)\n                                                for area in sorted_translated_areas)\n                (self.mass_centers, self.squared_gyration_radii, self.asphericities,\n                self.acylindricities, self.anisotropies) = zip(*gyration_tensor_parameters)\n                self.mass_centers = [discretization.discrete_to_continuous(point, result_inside_volume=True)\n                                    for point in self.mass_centers]\n                self.squared_gyration_radii = [discretization.discrete_to_continuous(value, unit_exponent=2)\n                                            for value in self.squared_gyration_radii]\n            else:\n                (self.mass_centers, self.squared_gyration_radii, self.asphericities,\n                self.acylindricities, self.anisotropies) = 5*([], )\n\n        self.triangles()\n\n    def squared_distance(self, a, b):\n        '''\n        Calculates the squared distance between two points while taking the\n        translation vectors into account.\n        '''\n        sqd = sys.maxint\n        for v in self.domain_calculation.discretization.combined_translation_vectors + [(0, 0, 0)]:\n            sqd = min(sqd, sum([(a[i] - b[i] + v[i]) * (a[i] - b[i] + v[i]) for i in dimensions]))\n        return sqd\n\n    def triangles(self):\n        if hasattr(self, \"cavity_triangles\"):\n            return self.cavity_triangles\n        step = (self.domain_calculation.discretization.s_step,) * 3\n        offset = self.domain_calculation.discretization.discrete_to_continuous((0, 0, 0))\n        triangles = []\n        surface_areas = []\n        for i, multicavity in enumerate(self.multicavities):\n            print_message(\"Generating triangles for multicavity:\", i+1)\n            vertices, normals, surface_area = cavity_triangles(\n                    self.grid3,\n                    multicavity,\n                    4, step, offset,\n                    self.domain_calculation.discretization.grid)\n            triangles.append((vertices, normals))\n            surface_areas.append(surface_area)\n\n        self.cavity_triangles = triangles\n        self.cavity_surface_areas = surface_areas\n        return cavity_triangles\n\n    def __getattr__(self, attr):\n        optional_attributes = ('mass_centers', 'squared_gyration_radii', 'asphericities', 'acylindricities',\n                               'anisotropies', 'characteristic_radii', 'cyclic_area_indices')\n        if attr in optional_attributes:\n            return None\n        else:\n            return super(CavityCalculation, self).__getattr__(attr)\n\n\nclass FakeDomainCalculation(object):\n    '''\n    When calculating center-based cavities, a DomainCalculation object is\n    required. This has to provide the domain central points, but not the surface\n    points (as those are only needed for surface-based cavity calculation).\n    Objects of this class can be used as a drop-in for 'real'\n    DomainCalculations, e.g. when the required data is loaded from a file.\n    '''\n\n    def __init__(self, discretization, atom_discretization, results):\n        self.centers = results.domains.centers\n        self.discretization = discretization\n        self.atom_discretization = atom_discretization\n", "meta": {"hexsha": "40f6e2e43bb045ad79a01e4c52916c17f32459c6", "size": 17511, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/core/calculation/algorithm.py", "max_stars_repo_name": "sciapp/pyMolDyn", "max_stars_repo_head_hexsha": "fba6ea91cb185f916b930cd25b4b1d28a22fb4c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2016-10-25T09:48:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-30T18:59:50.000Z", "max_issues_repo_path": "src/core/calculation/algorithm.py", "max_issues_repo_name": "sciapp/pyMolDyn", "max_issues_repo_head_hexsha": "fba6ea91cb185f916b930cd25b4b1d28a22fb4c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-09-19T06:03:36.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-28T11:29:23.000Z", "max_forks_repo_path": "src/core/calculation/algorithm.py", "max_forks_repo_name": "sciapp/pyMolDyn", "max_forks_repo_head_hexsha": "fba6ea91cb185f916b930cd25b4b1d28a22fb4c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.1882022472, "max_line_length": 121, "alphanum_fraction": 0.6639826395, "include": true, "reason": "import numpy", "num_tokens": 3595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.19873420928498609}}
{"text": "#!/usr/bin/env python\n\nimport datetime\nimport json\nimport math\nimport random\nimport sys\nfrom ipaddress import ip_address, ip_network\n\nimport numpy as np\nimport pytricia\nimport yaml\n\nimport networkx\n\nip_prefixes = pytricia.PyTricia()\n\nseed = hash(datetime.datetime.now())\nglobal_policy = {}\n\n\ndef read_topo(filename, local_policy=None):\n    data = yaml.load(open(filename))\n    G = networkx.Graph()\n    nodes = data[\"nodes\"]\n    links = data[\"links\"]\n    for n in nodes:\n        nid = nodes[n]['id']\n        G.add_node(nid, name=n, **nodes[n])\n        G.node[nid]['type'] = nodes[n]['type']\n        G.node[nid]['ip-prefix'] = nodes[n].get('ip-prefix', [])\n        G.node[nid]['routing'] = pytricia.PyTricia()\n        G.node[nid]['fine_grained'] = pytricia.PyTricia()\n        for prefix in nodes[n].get('ip-prefix', []):\n            ip_prefixes[prefix] = nid\n    for l in links:\n        G.add_edge(*l)\n    return G\n\n\nbgp_general_policy = networkx.shortest_path\n\n\n# FIXME: The generation algorithm does not make sense\n# Refer to the evaluation part of SDX and SIDR\ndef generate_local_policy(G, **args):\n    \"\"\"\n    Generate the local policy for each node in G.\n\n    Args:\n        G: graph.\n        args: additional arguments to config the generation algorithm.\n\n    Returns:\n        The mapping from node id to a local_policy table.\n        local_policy_table ::= Trie<prefix, Map<port, next_hop>>\n    \"\"\"\n    global global_policy\n    random.seed(seed)\n    policies = dict()\n    max_ports = 30\n    for node in G.nodes():\n        if node not in policies:\n            policies[node] = pytricia.PyTricia()\n        # FIXME: select prefix by following a distribution\n        for prefix in G.node[node][\"ip-prefix\"]:\n            # FIXME: select ports by following a distribution\n            ports = set([\n                random.randint(10000, 60000)\n                for _ in range(random.randint(1, max_ports))\n            ])\n            for port in ports:\n                policies[node][port] = random.choice(\n                    [i for i in G.neighbors(node)] + [None])\n    global_policy = policies\n\n\nDEFAULT_SERVICE_TYPES = {21: 0.1, 80: 0.1, 2801: 0.2, 8444: 0.3, 8445: 0.3}\n\n\n# TODO: Some key points\n# - What's the distribution for policy type (blackhole/deflection) selection\n# - What's the distribution for node selection\n# - How many network we need to fwd\n# - What's the distribution for the tcp port selection\ndef generate_random_policy(G,\n                           service_types=DEFAULT_SERVICE_TYPES,\n                           network_ratio=0.5,\n                           prefix_ratio=0.2,\n                           policy_place='transit',\n                           policy_type='both',\n                           **args):\n    \"\"\"\n    Randomly setup black-hole or deflection policies in transit network\n\n    Args:\n        G: Topology\n        service_types: supported service port distribution.\n        network_ratio: how many networks is selected. default 0.5\n        prefix_ratio: how many prefix is seleted. default: 0.2\n        policy_place: transit, edge or both. default: 'transit'\n        policy_type: blackhole, deflection or both. default: 'both'\n        args: additional arguments.\n\n    Returns:\n        global local policy table.\n    \"\"\"\n    edge_networks = [\n        n for n in G.nodes() if G.node[n].get('type', '') == 'edge'\n    ]\n    transit_networks = [\n        n for n in G.nodes() if G.node[n].get('type', '') == 'transit'\n    ]\n    policies = {}\n    if policy_place == 'transit':\n        policy_networks = transit_networks\n    elif policy_place == 'edge':\n        policy_networks = edge_networks\n    else:\n        policy_networks = G.nodes()\n    for d in policy_networks:\n        if d not in policies:\n            policies[d] = pytricia.PyTricia()\n        for dest in random.sample([n for n in edge_networks if n != d],\n                                  math.ceil(\n                                      len(edge_networks) * float(network_ratio))):\n            node_prefixes = G.node[dest]['ip-prefix']\n            for prefix in random.sample(\n                    node_prefixes, math.ceil(\n                        len(node_prefixes) * float(prefix_ratio))):\n                policies[d][prefix] = {\n                    port: gen_single_policy(G, d, dest, policy_type)\n                    for port in random.sample(service_types.keys(),\n                                              random.randint(1, 4))\n                }\n    return policies\n\n\ndef gen_single_policy(G, d, dest, policy_type):\n    if policy_type == 'both':\n        return random.choice([None, random_deflection(G, d, dest)])\n    elif policy_type == 'deflection':\n        return random_deflection(G, d, dest)\n    return None\n\n\ndef random_deflection(G, d, dest):\n    next_hop = networkx.shortest_path(G, d, dest)[1]\n    subG = G.copy()\n    subG.remove_edge(d, next_hop)\n    if dest not in networkx.descendants(subG, d):\n        return None\n    else:\n        return networkx.shortest_path(subG, d, dest)[1]\n\n\ndef get_local_policy(node):\n    \"\"\"\n    local_policy is not a simple prefix based routing.\n\n    For simplicity, assume the format of local_policy for each node is:\n\n    local_policy ::= Trie<prefix, Map<port, next_hop>>\n    \"\"\"\n    global global_policy\n    return global_policy.get(node, pytricia.PyTricia())\n\n\ndef default_routing_policy(node,\n                           dst_ip,\n                           dst_port=None,\n                           src_ip=None,\n                           src_port=None,\n                           protocol='tcp',\n                           **args):\n    \"\"\"\n    Default routing policy for networks.\n\n    Args:\n        node: node id for the network.\n        dst_ip: destination ip address.\n        dst_port: optional.\n        src_ip: optional.\n        src_port: optional.\n        protocol: optional.\n        args: additional flow spec.\n\n    Returns:\n        The next hop of the give flow spec from this node.\n    \"\"\"\n    for prefix in node.get('ip-prefix', []):\n        if ip_address(dst_ip) in ip_network(prefix):\n            return None\n    local_policy = get_local_policy(node['id'])\n    if dst_ip in local_policy:\n        local_policy_for_ip = local_policy[dst_ip]\n        if dst_port in local_policy_for_ip:\n            return local_policy_for_ip[dst_port]\n    fg_routing = node['fine_grained']\n    if dst_ip in fg_routing:\n        fg_routing_for_ip = fg_routing[dst_ip]\n        if dst_port in fg_routing_for_ip:\n            return fg_routing_for_ip[dst_port]\n    if dst_ip in node['routing']:\n        return node['routing'][dst_ip]\n\n\ndef fp_bgp_convergence(G):\n    \"\"\"\n    False-positive BGP Convergence. node[\"routing\"] is the table of  {ip-prefix -> next hop node}\n    \"\"\"\n    paths = networkx.shortest_path(G)\n    for src in G.nodes:\n        for dst in G.nodes:\n            if src != dst:\n                try:\n                    path = paths[src].get(dst)\n                except KeyError:\n                    path = None\n                if path:\n                    prefixes = G.node[dst]['ip-prefix']\n                    for hop, next_hop in zip(path[:-1], path[1:]):\n                        for prefix in prefixes:\n                            G.node[hop][\"routing\"][prefix] = next_hop\n\n\ndef all_fg_nodes(G, prefix):\n    \"\"\"\n    Let's assume the local_policy is generated from the prefixes of nodes first.\n    \"\"\"\n    # FIXME: If the granularity of prefixes in local_policy is different from ones in node, it will conduct error.\n    fg_nodes = []\n    for node in G.nodes:\n        local = get_local_policy(node)\n        if local.get(prefix):\n            fg_nodes.append(node)\n    return fg_nodes\n\n\ndef correct_bgp_convergence(G):\n    \"\"\"\n    Correct BGP Convergence\n    \"\"\"\n    for dst in G.nodes:\n        prefixes = G.node[dst]['ip-prefix']\n        for prefix in prefixes:\n            H = G.copy()\n            for node in all_fg_nodes(G, prefix):\n                H.remove_node(node)\n            paths = networkx.shortest_path(H)\n            for src in H.nodes:\n                if src != dst:\n                    # path = paths[src][dst]\n                    path = paths[src].get(dst, [])\n                    for hop, next_hop in zip(path[:-1], path[1:]):\n                        G.node[hop][\"routing\"][prefix] = next_hop\n\n\ndef find_fine_grained_routes(G, prefix_port):\n    for prefix, ports in prefix_port.items():\n        for port in ports:\n            delete_nodes = set()\n            delete_links = set()\n            H = G.copy()  # A copy of directed graph to modify links and nodes\n            # Step 1: Remove unused links for <prefix, port>\n            for node in H.nodes:\n                action = get_local_policy(node).get(prefix)\n                if action and (port in action):\n                    action = action[port]\n                    if action:\n                        for neig in H.neighbors(node):\n                            if action != neig:\n                                delete_links.add((node, neig))\n                    else:\n                        delete_nodes.add(node)\n            for edge in delete_links:\n                H.remove_edge(*edge)\n            for node in delete_nodes:\n                H.remove_node(node)\n            # Step 2: Find shortest path (Is it possible to be not found?)\n            dst = ip_prefixes[prefix]\n            paths = networkx.shortest_path(H, target=dst)\n            # Step 3: Traverse the shortest path\n            for src in H.nodes:\n                if src != dst:\n                    path = paths.get(src)\n                    if path:\n                        for hop, next_hop in zip(path[:-1], path[1:]):\n                            if prefix not in G.node[hop][\"fine_grained\"]:\n                                G.node[hop][\"fine_grained\"][prefix] = dict()\n                            G.node[hop][\"fine_grained\"][prefix][port] = next_hop\n\n    # Step 4: BGP shortest path in all nodes\n    fp_bgp_convergence(G)\n    return G\n\n\ndef fine_grained_announcement(G):\n    for node in G.nodes:\n        del G.node[node][\"routing\"]\n        del G.node[node][\"fine_grained\"]\n    G = G.to_directed()\n    for node in G.nodes:\n        G.node[node][\"routing\"] = pytricia.PyTricia()\n        G.node[node][\"fine_grained\"] = pytricia.PyTricia()\n    prefix_port = dict()  # type: dict{str, set{int}}\n    for node in G.nodes:\n        local = get_local_policy(node)\n        for prefix in local:\n            ports_actions = local[prefix]\n            if prefix not in prefix_port:\n                prefix_port[prefix] = set()\n            for port in ports_actions:\n                prefix_port[prefix].add(port)\n    return find_fine_grained_routes(G, prefix_port)\n\n\ndef read_flows(filename, port_dist=DEFAULT_SERVICE_TYPES):\n    \"\"\"\n    Examples:\n        [{\n            \"src_ip\": \"10.0.0.1\",\n            \"src_port\": 22,\n            \"dst_ip\": \"10.0.10.1\",\n            \"dst_port\": 80,\n            \"protocol\": \"tcp\",\n            \"start_time\": 1516292713,\n            \"end_time\": 1516313885,\n            \"volume\": 4089456904\n        }]\n\n        required: src_ip, dst_ip, start_time, end_time, volume\n        optional: src_port, dst_port, protocol\n    \"\"\"\n    data = json.load(open(filename))\n    for d in data:\n        if not d.get('dst_port', None):\n            d['dst_port'] = int(np.random.choice(\n                list(port_dist.keys()), p=list(port_dist.values())))\n        # (d['src_ip'], d['dst_ip']) = (d['dst_ip'], d['src_ip'])\n    return data\n\n\nstatistic_as_length = {}\n\n\ndef coarse_grained_correct_bgp(G, F):\n    \"\"\"\n    The principle of Correct BGP is very simple:\n\n    For a specific IP p, compute the subgraph G' of G in which every node with local_policy covering p will not show.\n    The final path of p is the shortest_path of subgraph G'.\n\n    The Correct BGP MUST guarantee the local_policy NEVER be triggered.\n    \"\"\"\n    for flow in F:\n        node = G.node[ip_prefixes[flow[\"src_ip\"]]]\n        if node is not None:\n            as_length = [node]\n            prefixes = [ip_network(p) for p in node['ip-prefix']]\n            while ip_address(flow[\"dst_ip\"]) not in prefixes:\n                if len(node[\"fine_grained\"]) > 0:\n                    try:\n                        next_hop = node[\"fine_grained\"][flow[\"dst_ip\"]][\n                            \"dst_port\"]\n                        in_fg = True  # In fine grained policy\n                    except KeyError:\n                        in_fg = False\n                if not in_fg:\n                    next_hop = node[\"routing\"][flow[\"dst_ip\"]]\n                as_length.append(next_hop)\n        print(\"AS Length: %d\" % len(as_length))\n        if len(as_length) not in statistic_as_length:\n            statistic_as_length[len(as_length)] = 0\n        statistic_as_length[len(as_length)] += 1\n\n\n# def match(ip, prefix):\n#     return ip in prefix\n\n# TODO: No need, merge it with routing_policy\n# def compute_next_hop(flow, rib):\n#     \"\"\"\n#     Compute the next hop of the flow from  RIB.\n#\n#     Args:\n#         flow: flow spec.\n#         rib: the RIB table from the Graph node.\n#\n#     Returns:\n#         the next hop. (None if no route.)\n#     \"\"\"\n#     for rule in rib:\n#         if match(flow['dst-ip'], rule):\n#             return rib[rule]\n#     return None\n\n\ndef check_path(flow, G, routing_policy=default_routing_policy, debug=False):\n    \"\"\"\n    Check the path of a given flow in the topology.\n\n    Args:\n        flow: The flow spec to check.\n        G: The topology object.\n\n    Returns:\n        the AS-PATH length of the route.\n        nan - no route\n        inf - there is a loop\n    \"\"\"\n    if debug:\n        path = []\n    loop_remover = {}\n    src = ip_prefixes[flow['src_ip']]\n    dst = ip_prefixes[flow['dst_ip']]\n    if src == dst:\n        if debug:\n            return 1, [src]\n        return 1\n    d = src\n    if debug:\n        path = [src]\n    dn = routing_policy(G.node[src], **flow)\n    path_len = 1\n    while dn:\n        loop_remover[d] = loop_remover.get(d, 0) + 1\n        # print d, p, loop_remover\n        if loop_remover[d] > 1:\n            if debug:\n                return math.inf, []\n            return math.inf\n        d = dn\n        if debug:\n            path.append(dn)\n        dn = routing_policy(G.node[d], **flow)\n        path_len += 1\n    if d != dst:\n        if debug:\n            return math.nan, []\n        return math.nan\n    if debug:\n        return path_len, path\n    return path_len\n\n\ndebug_dict = {}\n\n\ndef check_reachability(G, F, max_len=10, debug=False, debug_num=None):\n    as_length_dist = {}\n    success_volume = 0\n    unsuccess_volume = 0\n    R_F = []\n    for f in F:\n        if debug:\n            global debug_dict\n            result, path = check_path(f, G, debug=True)\n            if debug_num not in debug_dict:\n                debug_dict[debug_num] = dict()\n            debug_dict[debug_num][(f[\"src_ip\"], f[\"dst_ip\"], f[\"start_time\"],\n                                   f[\"end_time\"], f[\"volume\"])] = (result, path)\n        else:\n            result = check_path(f, G)\n        as_length_dist[result] = as_length_dist.get(result, 0) + 1\n        if type(result) == float:\n            unsuccess_volume += f['volume']\n        elif result > 1:\n            success_volume += f['volume']\n            R_F.append(f)\n    # print 'block_policies', 'deflection_policies'\n    # print '%d\\t%d' % policy_summary(G)\n    if debug:\n        as_len_nan = as_length_dist.pop(math.nan) if math.nan in as_length_dist else 0\n        as_lens = sorted(as_length_dist.keys())\n        as_lens.append(math.nan)\n        as_length_dist[math.nan] = as_len_nan\n        print('\\t'.join([str(l) for l in as_lens]))\n        print('\\t'.join([str(as_length_dist[l]) for l in as_lens]))\n    as_len_pdf = []\n    for al in range(max_len - 1):\n        as_len_pdf.append(as_length_dist.get(al + 2, 0))\n    as_len_pdf.append(as_length_dist.get(math.inf, 0))\n    as_len_pdf.append(as_length_dist.get(math.nan, 0))\n    as_len_pdf.append(success_volume)\n    as_len_pdf.append(unsuccess_volume)\n    # Format: flow_num from 2 to max_len, inf, nan, success_volume, unsuccess_volume\n    print('\\t'.join([str(a) for a in as_len_pdf]))\n    return R_F\n\n\nif __name__ == '__main__':\n    if len(sys.argv) < 2:\n        print(\"%s topo-filename flow-filename mode\" % sys.argv[0])\n    topo_filename = sys.argv[1]\n    flow_filename = sys.argv[2]\n    mode = sys.argv[3]\n    args = dict([tuple(k.split('=')) for k in sys.argv[4:]])\n\n    G = read_topo(topo_filename)\n    F = read_flows(flow_filename)\n    # generate_local_policy(G)\n    # global_policy = generate_random_policy(G, network_ratio=0.1, prefix_ratio=0.1, policy_type='blackhole')\n    global_policy = generate_random_policy(G, **args)\n\n    if '1' in mode:\n        H = G.copy()\n        fp_bgp_convergence(H)\n        # print(\"FP_BGP:\")\n        check_reachability(H, F)\n    if '2' in mode:\n        H = G.copy()\n        correct_bgp_convergence(H)\n        # print(\"C_BGP:\")\n        R_F = check_reachability(H, F, debug=False, debug_num=2)\n    if '3' in mode:\n        H = G.copy()\n        H = fine_grained_announcement(H)\n        # print(\"SFP:\")\n        check_reachability(H, F, debug=False, debug_num=3)\n    if '4' in mode:\n        H = G.copy()\n        H = fine_grained_announcement(H)\n        # print(\"Reachable-SFP:\")\n        check_reachability(H, R_F, debug=False, debug_num=4)\n\n    if len(debug_dict) > 0:\n        flow_diff = list()\n        for flow in debug_dict[3]:\n            if debug_dict[3][flow][0] == math.nan and debug_dict[2][flow][0] != math.nan:\n                print(str(flow))\n        with open(\"debug.json\", 'w') as f:\n            f.write(debug_dict.__str__())\n\n    # coarse_grained_correct_bgp(G, F)\n    # print(\"AS Length statistics: %d\" % statistic_as_length)\n", "meta": {"hexsha": "52cd8bc2905b88f6273e86ea5a908bc020e636a3", "size": 17666, "ext": "py", "lang": "Python", "max_stars_repo_path": "sfp_eval/bin/announcement_sim.py", "max_stars_repo_name": "openalto/network-simulator-data", "max_stars_repo_head_hexsha": "09706e5ab6e266ee5ef5b71cd32f10eea5a1975e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sfp_eval/bin/announcement_sim.py", "max_issues_repo_name": "openalto/network-simulator-data", "max_issues_repo_head_hexsha": "09706e5ab6e266ee5ef5b71cd32f10eea5a1975e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sfp_eval/bin/announcement_sim.py", "max_forks_repo_name": "openalto/network-simulator-data", "max_forks_repo_head_hexsha": "09706e5ab6e266ee5ef5b71cd32f10eea5a1975e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8975791434, "max_line_length": 117, "alphanum_fraction": 0.5618702593, "include": true, "reason": "import numpy,import networkx", "num_tokens": 4223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.33111972642778714, "lm_q1q2_score": 0.19873420532338149}}
{"text": "#!/usr/bin/env python3\n# coding: utf-8\n\n__author__ = 'cleardusk'\n\n\"\"\"\nThe pipeline of 3DDFA prediction: given one image, predict the 3d face vertices, 68 landmarks and visualization.\n\n[todo]\n1. CPU optimization: https://pmchojnacki.wordpress.com/2018/10/07/slow-pytorch-cpu-performance\n\"\"\"\n\nimport torch\nimport torchvision.transforms as transforms\nimport mobilenet_v1\nimport numpy as np\nimport cv2\nimport os\nimport math\nfrom tqdm import tqdm\nimport time\n# import face_alignment\n# import single_align\nfrom utils.ddfa import ToTensorGjz, NormalizeGjz, str2bool\nimport scipy.io as sio\nfrom utils.inference import get_suffix, parse_roi_box_from_landmark, crop_img, predict_68pts, dump_to_ply, dump_vertex, \\\n    draw_landmarks, predict_dense, parse_roi_box_from_bbox, get_colors, write_obj_with_colors, get_aligned_param, parse_quality_list_part\nfrom utils.cv_plot import plot_pose_box\nfrom utils.estimate_pose import parse_pose\nfrom utils.params import param_mean, param_std\nfrom utils.render import get_depths_image, cget_depths_image, cpncc, crender_colors\nfrom utils.paf import gen_img_paf\nimport argparse\nimport torch.backends.cudnn as cudnn\nfrom simple_dataset import McDataset\nfrom torch.utils.data import DataLoader\n\nSTD_SIZE = 120\n\n\ndef main(args):\n    # 1. load pre-tained model\n    checkpoint_fp = 'models/phase1_wpdc_vdc.pth.tar'\n    arch = 'mobilenet_1'\n\n    checkpoint = torch.load(checkpoint_fp, map_location=lambda storage, loc: storage)['state_dict']\n    model = getattr(mobilenet_v1, arch)(num_classes=62)  # 62 = 12(pose) + 40(shape) +10(expression)\n\n    model_dict = model.state_dict()\n    # because the model is trained by multiple gpus, prefix module should be removed\n    for k in checkpoint.keys():\n        model_dict[k.replace('module.', '')] = checkpoint[k]\n    model.load_state_dict(model_dict)\n    if args.mode == 'gpu':\n        cudnn.benchmark = True\n        model = model.cuda()\n    model.eval()\n\n    tri = sio.loadmat('visualize/tri.mat')['tri']\n    transform = transforms.Compose([ToTensorGjz(), NormalizeGjz(mean=127.5, std=128)])\n\n    if not os.path.exists(args.save_dir):\n        os.mkdir(args.save_dir)\n\n    # 2. parse images list and landmark\n    lmk_file = args.lmk_file\n    ts = time.time()\n    rank_land, rank_img_list, start, end = parse_quality_list_part(lmk_file, args.world_size, args.rank, args.resume_idx)\n    print('parse land file in {:.3f} seconds'.format(time.time() - ts))\n\n    # for batch processing\n    print('World size {}, rank {}, start from {}, end with {}'.format(args.world_size, args.rank, start, end))\n    dataset = McDataset(rank_img_list, rank_land, transform=transform, std_size=STD_SIZE)\n    dataloader = DataLoader(dataset, batch_size=args.batch_size, shuffle=False, num_workers=2, pin_memory=True)\n\n    for img_idx, (inputs, ori_imgs, img_fps, roi_boxes) in enumerate(tqdm(dataloader)):\n\n        # forward: one step\n        with torch.no_grad():\n            if args.mode == 'gpu':\n                inputs = inputs.cuda()\n            params = model(inputs)\n            params = params.cpu().numpy()\n\n        roi_boxes = roi_boxes.numpy()\n        outputs_roi_boxes = roi_boxes\n        if args.bbox_init == 'two':\n            step_two_ori_imgs = []\n            step_two_roi_boxes = []\n            ori_imgs = ori_imgs.numpy()\n            for ii in range(params.shape[0]):\n                # 68 pts\n                pts68 = predict_68pts(params[ii], roi_boxes[ii])\n\n                # two-step for more accurate bbox to crop face\n                roi_box = parse_roi_box_from_landmark(pts68)\n                img_step2 = crop_img(ori_imgs[ii], roi_box)\n                img_step2 = cv2.resize(img_step2, dsize=(STD_SIZE, STD_SIZE), interpolation=cv2.INTER_LINEAR)\n                # input = transform(img_step2).unsqueeze(0)\n                step_two_ori_imgs.append(transform(img_step2))\n                step_two_roi_boxes.append(roi_box)\n            with torch.no_grad():\n                step_two_ori_imgs = torch.stack(step_two_ori_imgs, dim=0)\n                inputs = step_two_ori_imgs\n                if args.mode == 'gpu':\n                    inputs = inputs.cuda()\n                params = model(inputs)\n                params = params.cpu().numpy()\n            outputs_roi_boxes = step_two_roi_boxes\n\n        # dump results\n        if args.dump_param:\n            for img_fp, param, roi_box in zip(img_fps, params, outputs_roi_boxes):\n                split = img_fp.split('/')\n                save_name = os.path.join(args.save_dir, '{}.txt'.format(os.path.splitext(split[-1])[0]))\n                this_param = param * param_std + param_mean\n                this_param = np.concatenate((this_param, roi_box))\n                this_param.tofile(save_name, sep=' ')\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(description='3DDFA inference pipeline')\n    parser.add_argument('-m', '--mode', default='gpu', type=str, help='gpu or cpu mode')\n    parser.add_argument('--bbox_init', default='two', type=str,\n                        help='one|two: one-step bbox initialization or two-step')\n    parser.add_argument('--dump_2d_img', default='false', type=str2bool, help='whether to save 3d rendered image')\n    parser.add_argument('--dump_param', default='true', type=str2bool, help='whether to save param')\n    parser.add_argument('--save_dir', default='results', type=str, help='dir to save result')\n    parser.add_argument('--lmk_file', default='quality_list', type=str, help='landmarks file')\n    parser.add_argument('--rank', default=0, type=int, help='used when parallel run')\n    parser.add_argument('--world_size', default=1, type=int, help='used when parallel run')\n    parser.add_argument('--resume_idx', default=0, type=int)\n    parser.add_argument('--batch_size', default=80, type=int, help='batch size')\n\n    args = parser.parse_args()\n    main(args)\n\n", "meta": {"hexsha": "bbd297447fe0ebcb64071769bfca425f51a4a104", "size": 5835, "ext": "py", "lang": "Python", "max_stars_repo_path": "3ddfa/test.py", "max_stars_repo_name": "bruinxiong/Rotate-and-Render", "max_stars_repo_head_hexsha": "135d2b7b02ca4b3bdf7961b260466ff8b64bdb59", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 397, "max_stars_repo_stars_event_min_datetime": "2020-03-18T06:45:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T12:43:25.000Z", "max_issues_repo_path": "3ddfa/test.py", "max_issues_repo_name": "bruinxiong/Rotate-and-Render", "max_issues_repo_head_hexsha": "135d2b7b02ca4b3bdf7961b260466ff8b64bdb59", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 39, "max_issues_repo_issues_event_min_datetime": "2020-03-18T17:11:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T08:55:55.000Z", "max_forks_repo_path": "3ddfa/test.py", "max_forks_repo_name": "bruinxiong/Rotate-and-Render", "max_forks_repo_head_hexsha": "135d2b7b02ca4b3bdf7961b260466ff8b64bdb59", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2020-03-18T11:54:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T10:22:54.000Z", "avg_line_length": 42.2826086957, "max_line_length": 137, "alphanum_fraction": 0.6742073693, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.19873420058742006}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\nimport os\nimport sys\nimport subprocess\n\nfrom pathlib import Path\n\nimport csv\n\nimport numpy as np\n\nimport itk\nfrom itk import TubeTK as tube\n\n\ndef scv_is_bundled():\n    return getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS')\n\ndef scv_get_perfusion_toolbox_path():\n    if scv_is_bundled():\n        return os.path.join(sys._MEIPASS, 'StroCoVess', 'perfusion_toolbox')\n    return os.path.join(os.path.dirname(os.path.realpath(__file__)),\n        'perfusion_toolbox')\n\n#################\n#################\n#################\n#################\n#################\ndef scv_convert_ctp_to_cta(filenames,\n                           report_progress=print,\n                           debug=False,\n                           output_dirname=\".\"):\n\n    filenames.sort()\n    num_images = len(filenames)\n\n    base_im = itk.imread(filenames[num_images//2],itk.F)\n    base_spacing = base_im.GetSpacing()\n\n    progress_percent = 10\n    report_progress(\"Reading images\",progress_percent)\n\n    Dimension = 3\n    PixelType = itk.ctype('float')\n    ImageType = itk.Image[PixelType,Dimension]\n\n    imdatamax = itk.GetArrayFromImage(base_im)\n    imdatamin = imdatamax\n\n    if output_dirname!=None and not os.path.exists(output_dirname):\n        os.mkdir(output_dirname)\n\n    progress_percent = 20\n    progress_per_file = 70/num_images\n    for imNum in range(num_images):\n        imMoving = itk.imread(filenames[imNum],itk.F)\n        if imMoving.shape != base_im.shape:\n            resample = tube.ResampleImage.New(Input=imMoving)\n            resample.SetMatchImage(base_im)\n            resample.Update()\n            imMovingIso = resample.GetOutput()\n            progress_label = \"Resampling \"+str(imNum)+\" of \"+str(num_images)\n            report_progress(progress_label,progress_percent)\n        else:\n            imMovingIso = imMoving\n        imdataTmp = itk.GetArrayFromImage(imMovingIso)\n        imdatamax = np.maximum(imdatamax,imdataTmp)\n        imdataTmp = np.where(imdataTmp==-1024,imdatamin,imdataTmp)\n        imdatamin = np.minimum(imdatamin,imdataTmp)\n        progress_percent += progress_per_file\n        progress_label = \"Integrating \"+str(imNum)+\" of \"+str(num_images)\n        report_progress(progress_label,progress_percent)\n    \n    report_progress(\"Generating CT, CTA, and CTP\",90)\n\n    ct = itk.GetImageFromArray(imdatamin)\n    ct.CopyInformation(base_im)\n\n    cta = itk.GetImageFromArray(imdatamax)\n    cta.CopyInformation(base_im)\n\n    diff = imdatamax-imdatamin\n    diff[:4,:,:] = 0\n    diff[-4:,:,:] = 0\n    diff[:,:4,:] = 0\n    diff[:,-4:,:] = 0\n    diff[:,:,:4] = 0\n    diff[:,:,-4:] = 0\n    dsa = itk.GetImageFromArray(diff)\n    dsa.CopyInformation(base_im)\n\n    report_progress(\"Done\",100)\n    return ct,cta,dsa\n\n\n#################\n#################\n#################\n#################\n#################\ndef scv_segment_brain_from_ct(ct_image,\n                               report_progress=print,\n                               debug=False):\n\n    ImageType = itk.Image[itk.F,3]\n    LabelMapType = itk.Image[itk.UC,3]\n\n    report_progress(\"Threshold\",5)\n    thresh = tube.ImageMath.New(Input=ct_image)\n    thresh.IntensityWindow(-50,6000,0,6000)\n    imgt = thresh.GetOutput()\n    thresh.ReplaceValuesOutsideMaskRange(imgt,1,6000,0)\n    thresh.ReplaceValuesOutsideMaskRange(imgt,0,700,1)\n    tmpimg = thresh.GetOutput()\n    thresh.ReplaceValuesOutsideMaskRange(tmpimg,0,1,2)\n    ct_tmp = thresh.GetOutput()\n\n    report_progress(\"Initial Mask\",10)\n    maskMath = tube.ImageMath.New(Input=ct_tmp)\n    # remove skin\n    maskMath.Dilate(15,0,1)\n    # shrink brain\n    maskMath.Erode(6,2,0)\n    # restore skull\n    maskMath.ReplaceValueWithinMaskRange(ct_tmp,1,1,0,1)\n    # shrink skull\n    maskMath.Dilate(3,1,0)\n    maskMath.Erode(1,1,0)\n    comboSeed = maskMath.GetOutputUChar()\n    \n    report_progress(\"Connected Component\",20)\n    segmenter = tube.SegmentConnectedComponentsUsingParzenPDFs[ImageType,\n                    LabelMapType].New()\n    segmenter.SetFeatureImage( ct_image )\n    segmenter.SetInputLabelMap( comboSeed )\n    segmenter.SetObjectId( 2 )\n    segmenter.AddObjectId( 1 )\n    segmenter.SetVoidId( 0 )\n    segmenter.SetErodeDilateRadius( 20 )\n    segmenter.SetHoleFillIterations( 40 )\n    segmenter.Update()\n    segmenter.ClassifyImages()\n    brainMaskRaw = segmenter.GetOutputLabelMap()\n\n    report_progress(\"Masking\",60)\n\n    maskMath = itk.CastImageFilter[LabelMapType, ImageType].New()\n    maskMath.SetInput(brainMaskRaw)\n    maskMath.Update()\n    brainMaskF = maskMath.GetOutput()\n    maskMath = tube.ImageMath.New(Input = brainMaskF)\n    maskMath.Threshold(2,2,1,0)\n    maskMath.Dilate(2,1,0)\n    maskMath.Erode(3,1,0)\n    brainMaskRaw2 = maskMath.GetOutputUChar()\n\n    connComp = tube.SegmentConnectedComponents.New(Input=brainMaskRaw2)\n    connComp.SetKeepOnlyLargestComponent(True)\n    connComp.Update()\n    brainMask = connComp.GetOutput()\n\n    report_progress(\"Finishing\",90)\n    cast = itk.CastImageFilter[LabelMapType,ImageType].New()\n    cast.SetInput(brainMask)\n    cast.Update()\n    brainMaskF = cast.GetOutput()\n\n    brainMath = tube.ImageMath[ImageType].New(Input=ct_image)\n    brainMath.ReplaceValuesOutsideMaskRange( brainMaskF,1,1,-1024)\n    ct_brain_image = brainMath.GetOutput()\n\n    report_progress(\"Done\",100)\n    return ct_brain_image, brainMask\n\n\n#################\n#################\n#################\n#################\n#################\ndef scv_enhance_vessels_in_cta(cta_image,\n                               cta_roi_image,\n                               report_progress=print,\n                               debug=False ):\n\n    ImageType = itk.Image[itk.F,3]\n    LabelMapType = itk.Image[itk.UC,3]\n\n    report_progress(\"Masking\",5)\n    imMath = tube.ImageMath.New(Input=cta_roi_image)\n    imMath.Threshold( 0.00001,4000,1,0)\n    imMath.Erode(10,1,0)\n    imBrainMaskErode = imMath.GetOutput()\n    imMath.SetInput(cta_roi_image)\n    imMath.IntensityWindow(0,300,0,300)\n    imMath.ReplaceValuesOutsideMaskRange(imBrainMaskErode,0.5,1.5,0)\n    imBrainErode = imMath.GetOutput()\n\n    spacing = cta_image.GetSpacing()[0]\n\n    report_progress(\"Blurring\",10)\n    imMath = tube.ImageMath[ImageType].New()\n    imMath.SetInput(imBrainErode)\n    imMath.Blur(1.5*spacing)\n    imBlur = imMath.GetOutput()\n    imBlurArray = itk.GetArrayViewFromImage(imBlur)\n\n    report_progress(\"Generating Seeds\",20)\n    numSeeds = 15\n    seedCoverage = 20\n    seedCoord = np.zeros([numSeeds,3])\n    for i in range(numSeeds):\n        seedCoord[i] = np.unravel_index(np.argmax(imBlurArray,\n                           axis=None),imBlurArray.shape)\n        indx = [int(seedCoord[i][0]),int(seedCoord[i][1]),\n                int(seedCoord[i][2])]\n        minX = max(indx[0]-seedCoverage,0)\n        maxX = max(indx[0]+seedCoverage,imBlurArray.shape[0])\n        minY = max(indx[1]-seedCoverage,0)\n        maxY = max(indx[1]+seedCoverage,imBlurArray.shape[1])\n        minZ = max(indx[2]-seedCoverage,0)\n        maxZ = max(indx[2]+seedCoverage,imBlurArray.shape[2])\n        imBlurArray[minX:maxX,minY:maxY,minZ:maxZ]=0\n        indx.reverse()\n        seedCoord[:][i] = cta_roi_image.TransformIndexToPhysicalPoint(indx)\n\n    report_progress(\"Segmenting Initial Vessels\",30)\n    vSeg = tube.SegmentTubes.New(Input=cta_roi_image)\n    vSeg.SetVerbose(debug)\n    vSeg.SetMinRoundness(0.4)\n    vSeg.SetMinCurvature(0.002)\n    vSeg.SetRadiusInObjectSpace( 1 )\n    for i in range(numSeeds):\n        progress_label = \"Vessel \"+str(i)+\" of \"+str(numSeeds)\n        progress_percent = i/numSeeds*20+30\n        report_progress(progress_label,progress_percent)\n        vSeg.ExtractTubeInObjectSpace( seedCoord[i],i )\n    tubeMaskImage = vSeg.GetTubeMaskImage()\n\n    imMath.SetInput(tubeMaskImage)\n    imMath.AddImages(cta_roi_image,200,1)\n    blendIm = imMath.GetOutput()\n\n    report_progress(\"Computing Training Mask\",50)\n    trMask = tube.ComputeTrainingMask[ImageType,LabelMapType].New()\n    trMask.SetInput( tubeMaskImage )\n    trMask.SetGap( 4 )\n    trMask.SetObjectWidth( 1 )\n    trMask.SetNotObjectWidth( 1 )\n    trMask.Update()\n    fgMask = trMask.GetOutput()\n\n    report_progress(\"Enhancing Image\",70)\n    enhancer = tube.EnhanceTubesUsingDiscriminantAnalysis[ImageType,\n                   LabelMapType].New()\n    enhancer.AddInput( cta_image )\n    enhancer.SetLabelMap( fgMask )\n    enhancer.SetRidgeId( 255 )\n    enhancer.SetBackgroundId( 128 )\n    enhancer.SetUnknownId( 0 )\n    enhancer.SetTrainClassifier(True)\n    enhancer.SetUseIntensityOnly(True)\n    enhancer.SetScales([0.75*spacing,2*spacing,6*spacing])\n    enhancer.Update()\n    enhancer.ClassifyImages()\n\n    report_progress(\"Finalizing\",90)\n    imMath = tube.ImageMath[ImageType].New()\n    imMath.SetInput(enhancer.GetClassProbabilityImage(0))\n    imMath.Blur(0.5*spacing)\n    prob0 = imMath.GetOutput()\n    imMath.SetInput(enhancer.GetClassProbabilityImage(1))\n    imMath.Blur(0.5*spacing)\n    prob1 = imMath.GetOutput()\n    cta_vess = itk.SubtractImageFilter(Input1=prob0, Input2=prob1)\n\n    imMath.SetInput(cta_roi_image)\n    imMath.Threshold(0.0000001,2000,1,0)\n    imMath.Erode(2,1,0)\n    imBrainE = imMath.GetOutput()\n\n    imMath.SetInput(cta_vess)\n    imMath.ReplaceValuesOutsideMaskRange(imBrainE,1,1,-0.001)\n    cta_roi_vess = imMath.GetOutput()\n\n    report_progress(\"Done\",100)\n    return cta_vess,cta_roi_vess\n\n\n#################\n#################\n#################\n#################\n#################\ndef scv_extract_vessels_from_cta(cta_image,\n                                 cta_roi_vessels_image,\n                                 report_progress=print,\n                                 debug=False,\n                                 output_dirname=\".\"):\n\n    if output_dirname!=None and not os.path.exists(output_dirname):\n        os.mkdir(output_dirname)\n\n    spacing = cta_image.GetSpacing()[0]\n\n    report_progress(\"Thresholding\",5)\n    imMath = tube.ImageMath.New(cta_roi_vessels_image)\n    imMath.MedianFilter(1)\n    imMath.Threshold(0.00000001,9999,1,0)\n    vess_mask_im = imMath.GetOutputShort()\n\n    if debug and output_dirname!=None:\n        itk.imwrite(vess_mask_im,\n            output_dirname+\"/extract_vessels_mask.mha\",\n            compression=True)\n\n    report_progress(\"Connecting\",10)\n    ccSeg = tube.SegmentConnectedComponents.New(vess_mask_im)\n    ccSeg.SetMinimumVolume(50)\n    ccSeg.Update()\n    vess_mask_cc_im = ccSeg.GetOutput()\n\n    if debug and output_dirname!=None:\n        itk.imwrite(vess_mask_cc_im,\n            output_dirname+\"/extract_vessels_mask_cc.mha\",\n            compression=True)\n\n    imMathSS = tube.ImageMath.New(vess_mask_cc_im)\n    imMathSS.Threshold(0,0,1,0)\n    vess_mask_inv_im = imMathSS.GetOutputFloat()\n    \n    report_progress(\"Filling in\",20)\n    distFilter = itk.DanielssonDistanceMapImageFilter.New(vess_mask_inv_im)\n    distFilter.Update()\n    dist_map_im = distFilter.GetOutput()\n\n    report_progress(\"Generating seeds\",30)\n    imMath.SetInput(dist_map_im)\n    imMath.Blur(0.5*spacing)\n    tmp = imMath.GetOutput()\n    # Distance map's distances are in index units, not spacing\n    imMath.ReplaceValuesOutsideMaskRange(tmp,0.333,10,0)\n    initial_radius_im = imMath.GetOutput()\n    \n    if debug and output_dirname!=None:\n        itk.imwrite(initial_radius_im,\n            output_dirname+\"/vessel_extraction_initial_radius.mha\",\n            compression=True)\n\n    report_progress(\"Generating input\",30)\n    imMath.SetInput(cta_image)\n    imMath.ReplaceValuesOutsideMaskRange(cta_roi_vessels_image,0,1000,0)\n    imMath.Blur(0.4*spacing)\n    imMath.NormalizeMeanStdDev()\n    imMath.IntensityWindow(-4,4,0,1000)\n    input_im = imMath.GetOutput()\n\n    if debug and output_dirname!=None:\n        itk.imwrite(input_im,\n            output_dirname+\"/vessel_extraction_input.mha\",\n            compression=True)\n\n    report_progress(\"Extracting vessels\",40)\n    vSeg = tube.SegmentTubes.New(Input=input_im)\n    vSeg.SetVerbose(debug)\n    vSeg.SetMinCurvature(0.0001) #0\n    vSeg.SetMinRoundness(0.02)\n    vSeg.SetMinRidgeness(0.5)\n    vSeg.SetMinLevelness(0.0)\n    vSeg.SetRadiusInObjectSpace( 0.8*spacing )\n    vSeg.SetBorderInIndexSpace(3)\n    vSeg.SetSeedMask( initial_radius_im )\n    #vSeg.SetSeedRadiusMask( initial_radius_im )\n    vSeg.SetOptimizeRadius(True)\n    vSeg.SetUseSeedMaskAsProbabilities(True)\n    vSeg.SetSeedExtractionMinimumProbability(0.95) #0.99\n    vSeg.ProcessSeeds()\n\n    report_progress(\"Finalizing\",90)\n    tubeMaskImage = vSeg.GetTubeMaskImage()\n\n    if debug and output_dirname!=None:\n        itk.imwrite(tubeMaskImage,\n            output_dirname+\"/vessel_extraction_output.mha\",\n            compression=True)\n\n    report_progress(\"Done\",100)\n    return tubeMaskImage,vSeg.GetTubeGroup()\n\n#################\n#################\n#################\n#################\n#################\ndef scv_register_ctp_images(fixed_image_filename,\n                        moving_image_filenames,\n                        output_dirname,\n                        report_progress=print,\n                        debug=False):\n    ImageType = itk.Image[itk.F,3]\n\n    num_images = len(moving_image_filenames)\n    progress_percent = 10\n    progress_per_file = 70/num_images\n\n    fixed_im = itk.imread(fixed_image_filename,itk.F)\n    fixed_im_spacing = fixed_im.GetSpacing()\n    if fixed_im_spacing[0] != fixed_im_spacing[1] or \\\n       fixed_im_spacing[1] != fixed_im_spacing[2]:\n        report_progress(\"Resampling\",progress_percent)\n        resample = tube.ResampleImage.New(Input=fixed_im)\n        resample.SetMakeIsotropic(True)\n        resample.Update()\n        fixed_im = resample.GetOutput()\n        if debug:\n            progress_label = \"DEBUG: Resampling to \"+str(\n                fixed_im.GetSpacing())\n            report_progress(progress_label,progress_percent)\n\n    imMath = tube.ImageMath.New(fixed_im)\n    imMath.Threshold(150,800,1,0)\n    imMath.Dilate(10,1,0)\n    mask_im = imMath.GetOutputUChar()\n    mask_array = itk.GetArrayViewFromImage(mask_im)\n    mask_array[:4,:,:] = 0\n    mask_array[-4:,:,:] = 0\n    mask_obj = itk.ImageMaskSpatialObject[3].New()\n    mask_obj.SetImage(mask_im)\n    mask_obj.Update()\n\n    for imNum in range(num_images):\n        progress_percent += progress_per_file\n        progress_label = \"Registering \"+str(imNum)+\" of \"+str(num_images)\n        report_progress(progress_label,progress_percent)\n    \n        if moving_image_filenames[imNum] != fixed_image_filename:\n            moving_im = itk.imread(moving_image_filenames[imNum],itk.F)\n    \n            imreg = tube.RegisterImages[ImageType].New()\n            imreg.SetFixedImage(fixed_im)\n            imreg.SetMovingImage(moving_im)\n            imreg.SetRigidMaxIterations(100)\n            imreg.SetRegistration(\"RIGID\")\n            imreg.SetExpectedOffsetMagnitude(5)\n            imreg.SetExpectedRotationMagnitude(0.05)\n            imreg.SetFixedImageMaskObject(mask_obj)\n            imreg.SetUseEvolutionaryOptimization(False)\n            if debug:\n                imreg.SetReportProgress(True)\n            imreg.Update()\n    \n            tfm = imreg.GetCurrentMatrixTransform()\n            moving_reg_im = imreg.ResampleImage(\"SINC_INTERPOLATION\",\n                                                moving_im,tfm,-1024)\n            if output_dirname!=None:\n                pname,fname = os.path.split(moving_image_filenames[imNum])\n                rename_file_fname = os.path.splitext(fname)\n                new_fname = str(rename_file_fname[0])+\"_reg.nii\"\n                new_filename = os.path.join(output_dirname,new_fname)\n                itk.imwrite(moving_reg_im,new_filename,compression=True)\n        elif output_dirname!=None:\n            pname,fname = os.path.split(moving_image_filenames[imNum])\n            rename_file_fname = os.path.splitext(fname)\n            new_fname = str(rename_file_fname[0])+\"_reg.nii\"\n            new_filename = os.path.join(output_dirname,new_fname)\n            itk.imwrite(moving_reg_im,new_filename,compression=True)\n    report_progress(\"Done\",100)\n\n#################\n#################\n#################\n#################\n#################\ndef scv_register_atlas_to_image(atlas_im, atlas_mask_im, in_im):\n    ImageType = itk.Image[itk.F,3]\n\n    regAtlasToIn = tube.RegisterImages[ImageType].New(FixedImage=in_im,\n        MovingImage=atlas_im)\n    regAtlasToIn.SetReportProgress(True)\n    regAtlasToIn.SetRegistration(\"PIPELINE_AFFINE\")\n    regAtlasToIn.SetMetric(\"MATTES_MI_METRIC\")\n    regAtlasToIn.SetInitialMethodEnum(\"INIT_WITH_IMAGE_CENTERS\")\n    regAtlasToIn.Update()\n    atlas_reg_im = regAtlasToIn.ResampleImage()\n    atlas_mask_reg_im = regAtlasToIn.ResampleImage(\"NEAREST_NEIGHBOR\",\n        atlas_mask_im)\n\n    return atlas_reg_im,atlas_mask_reg_im\n\n#################\n#################\n#################\n#################\n#################\ndef scv_compute_atlas_region_stats(atlas_im,\n                                   time_im,\n                                   vess_im,\n                                   number_of_time_bins=100,\n                                   report_progress=print,\n                                   debug=False):\n\n    atlas_arr = itk.GetArrayFromImage(atlas_im)\n    time_arr = itk.GetArrayFromImage(time_im)\n    vess_arr = itk.GetArrayFromImage(vess_im)\n\n    num_regions = int(atlas_arr.max())\n    time_max = float(time_arr.max())\n    time_min = float(time_arr.min())\n    nbins = int(number_of_time_bins)\n    time_factor = (time_max-time_min)/(nbins+1)\n    print(\"Time range =\",time_min,\"-\",time_max)\n\n    bin_value = np.zeros([num_regions,nbins])\n    bin_count = np.zeros([num_regions,nbins])\n\n    for atlas_region in range(num_regions):\n        report_progress(\"Masking\",(atlas_region+1)*(100/num_regions))\n        indx_arr = np.where(atlas_arr==atlas_region)\n        indx_list = list(zip(indx_arr[0],indx_arr[1],indx_arr[2]))\n        for indx in indx_list:\n            time_bin = int((time_arr[indx]-time_min)/time_factor)\n            time_bin = min(max(0,time_bin),nbins-1)\n            if np.isnan(vess_arr[indx]) == False:\n                bin_count[atlas_region,time_bin] += 1\n                bin_value[atlas_region,time_bin] += vess_arr[indx]\n\n    bin_label = np.arange(nbins) * time_factor - time_min\n    bin_value = np.divide(bin_value,bin_count,where=bin_count!=0)\n\n    report_progress(\"Done\",100)\n    return bin_label,bin_value,bin_count\n\n#################\n#################\n#################\n#################\n#################\ndef scv_convert_3d_files_to_4d_file(in_filenames,out_filename):\n    num_3d_files = len(in_filenames)\n\n    ImageType = itk.Image[itk.F, 3]\n    Write4D = tube.Write4DImageFrom3DImages[ImageType].New()\n    Write4D.SetNumberOfInputImages(num_3d_files)\n    Write4D.SetFileName(out_filename)\n    for i,file in enumerate(in_filenames):\n        img = itk.imread(file,itk.F)\n        Write4D.SetNthInputImage(i, img)\n    Write4D.Update()\n\n#################\n#################\n#################\n#################\n#################\ndef scv_prepare_3d_for_perfusion_toolbox(prep_3d_in_filenames,\n                                         prep_3d_out_dirname,\n                                         report_progress=print,\n                                         report_subprogress=print,\n                                         debug=False):\n    num_3d_files = len(prep_3d_in_filenames)\n\n    reg_fixed_image = prep_3d_in_filenames[num_3d_files//2]\n    reg_in_filenames = prep_3d_in_filenames\n    report_progress(\"Registering CTP\",40)\n    scv_register_ctp_images(reg_fixed_image,\n        reg_in_filenames,\n        output_dirname=prep_3d_out_dirname,\n        report_progress=report_subprogress,\n        debug=debug)\n\n    # update filenames to registered ctp\n    report_progress(\"Saving 4D CTP\",60)\n    new_ctp_3d_filenames = []\n    for i in range(num_3d_files):\n        file_path,file_name = os.path.split(prep_3d_in_filenames[i])\n        rename_file_name = os.path.splitext(str(file_name))\n        new_ctp_3d_filenames.append( os.path.realpath(os.path.join(\n            prep_3d_out_dirname, str(rename_file_name[0]) + \"_reg.nii\")))\n\n    # Write 4D ctp registered\n    file_path,file_name = os.path.split(prep_3d_in_filenames[0])\n    rename_file_name = os.path.splitext(str(file_name))\n    ctp_base_filename = str(rename_file_name[0])\n\n    ctp_filename = ctp_base_filename + \"-4D_reg.nii\"\n    ctp_4d_out_filename = os.path.realpath(os.path.join(\n        prep_3d_out_dirname, ctp_filename))\n    scv_convert_3d_files_to_4d_file(new_ctp_3d_filenames,\n        ctp_4d_out_filename)\n    \n    # Compute CT, CTA, DSA\n    report_progress(\"Computing CT, CTA, DSA\",70)\n    ct_im,cta_im,dsa_im = scv_convert_ctp_to_cta(new_ctp_3d_filenames,\n        report_progress = report_subprogress,\n        debug=debug,\n        output_dirname=prep_3d_out_dirname)\n    ct_filename = ctp_base_filename + \"_ct.nii\"\n    ct_out_filename = os.path.realpath(os.path.join(\n        prep_3d_out_dirname, ct_filename))\n    itk.imwrite(ct_im, ct_out_filename,compression=True)\n    cta_filename = ctp_base_filename + \"_cta.nii\"\n    cta_out_filename = os.path.realpath(os.path.join(\n        prep_3d_out_dirname, cta_filename))\n    itk.imwrite(cta_im, cta_out_filename,compression=True)\n    dsa_filename = ctp_base_filename + \"_dsa.nii\"\n    dsa_out_filename = os.path.realpath(os.path.join(\n        prep_3d_out_dirname, dsa_filename))\n    itk.imwrite(dsa_im, dsa_out_filename,compression=True)\n\n    # Segment brain from CT\n    report_progress(\"Segmenting Brain\",80)\n    ct_brain,mask_brain = scv_segment_brain_from_ct(ct_im,\n        report_progress = report_subprogress,\n        debug=debug)\n    rename_file_ct = str(ct_filename)\n    rename_file_ct = os.path.splitext(rename_file_ct)\n    mask_brain_filename = str(rename_file_ct[0]) + \"_brain_mask.nii\"\n    mask_brain_out_filename = os.path.realpath(os.path.join(\n        prep_3d_out_dirname, mask_brain_filename))\n    itk.imwrite(mask_brain, mask_brain_out_filename)\n\n    report_progress(\"Done\",100)\n\n    return ctp_4d_out_filename, ct_out_filename, \\\n        cta_out_filename, dsa_out_filename, \\\n        mask_brain_out_filename\n\n#################\n#################\n#################\n#################\n#################\ndef scv_prepare_4d_for_perfusion_toolbox(prep_4d_in_filename,\n                                         prep_4d_out_dirname,\n                                         report_progress=print,\n                                         report_subprogress=print,\n                                         debug=False):\n    # convert 4D ctp to 3D images\n    ctp_dirname,ctp_filename = os.path.split(prep_4d_in_filename)\n\n    rename_file_ctp = os.path.splitext(str(ctp_filename))\n\n    report_progress(\"Reading image\",10)\n\n    img4d_im = itk.imread(prep_4d_in_filename, itk.F)\n    img4d_array = itk.GetArrayFromImage(img4d_im)\n    img4d_shape = img4d_array.shape\n    img4d_spacing = np.array(img4d_im.GetSpacing())\n    img4d_direction = np.array(img4d_im.GetDirection())\n    img4d_origin = np.array(img4d_im.GetOrigin())\n    img3d_spacing = img4d_spacing[0:3]\n    img3d_origin = img4d_origin[0:3]\n    img3d_direction = img4d_direction[0:3, 0:3]\n    num_3d_files = img4d_shape[0]\n    new_filenames = [] \n    report_progress(\"Creating CTP\",15)\n    subprogress = 15\n    subprogress_per_file = 100 / num_3d_files\n    for i in range(num_3d_files):\n        report_subprogress(\"Writing\",\n            subprogress+subprogress_per_file*i)\n        tmp_filename = f'CTP_{i:03}.mha'\n        new_filename = os.path.join(prep_4d_out_dirname,tmp_filename)\n        img3d_array = img4d_im[i,:,:,:]\n        img3d_im = itk.GetImageFromArray(img3d_array)\n        img3d_im.SetSpacing(img3d_spacing)\n        img3d_im.SetOrigin(img3d_origin)\n        img3d_im.SetDirection(img3d_direction)\n        itk.imwrite(img3d_im,new_filename,compression=True)\n        new_filenames.append(new_filename)\n\n    results = [new_filenames]\n    results += scv_prepare_3d_for_perfusion_toolbox( new_filenames, \\\n        prep_4d_out_dirname, report_progress, report_subprogress, debug)\n\n    return results\n\n#################\n#################\n#################\n#################\n#################\ndef scv_fix_image_info(filename, match_image):\n    im = itk.imread(filename,itk.F)\n    im.SetSpacing(match_image.GetSpacing())\n    im.SetOrigin(match_image.GetOrigin())\n    im.SetDirection(match_image.GetDirection())\n    itk.imwrite(im,filename,compression=True) \n    \n#################\n#################\n#################\n#################\n#################\n#matlab -r \"addpath('./perfusion_toolbox');DSC_report('/data/UNC-Stroke/UNC/CTP/CTAT-001-PTO/CTAT-001-Perf-4D_reg.nii','/data/UNC-Stroke/UNC/CTP/CTAT-001-PTO/CTAT-001-Perf-4D_reg_ct_brain_mask.nii','./test');quit\"\ndef scv_run_perfusion_toolbox(ctp_4d_in_filename,\n                              ctp_mask_filename,\n                              perfusion_out_dirname):\n    cmd = \"addpath('\"+scv_get_perfusion_toolbox_path()+\"');DSC_report('\"+ \\\n          ctp_4d_in_filename+\"','\"+ctp_mask_filename+\"','\"+ \\\n          perfusion_out_dirname+\"');quit\"\n    subprocess.run([\"matlab\", \"-wait\", \"-r\", cmd])\n\n    mask_image = itk.imread(ctp_mask_filename,itk.F)\n    cbf_filename = os.path.join(perfusion_out_dirname,\"CBF_SVD.nii\")\n    scv_fix_image_info(cbf_filename,mask_image)\n\n    cbv_filename = os.path.join(perfusion_out_dirname, \"CBV.nii\")\n    scv_fix_image_info(cbv_filename,mask_image)\n\n    cbv_lc_filename = os.path.join(perfusion_out_dirname, \"CBV_LC.nii\")\n    scv_fix_image_info(cbv_lc_filename,mask_image)\n\n    mtt_filename = os.path.join(perfusion_out_dirname, \"MTT_SVD.nii\")\n    scv_fix_image_info(mtt_filename,mask_image)\n\n    tmax_filename = os.path.join(perfusion_out_dirname, \"Tmax_SVD.nii\")\n    scv_fix_image_info(tmax_filename,mask_image)\n\n    ttp_filename = os.path.join(perfusion_out_dirname, \"TTP.nii\")\n    scv_fix_image_info(ttp_filename,mask_image)\n    \n    return cbf_filename,cbv_filename,mtt_filename,tmax_filename,ttp_filename\n\n \n#################\n#################\n#################\n#################\n#################\ndef scv_generate_vessel_report(ctp_3d_filenames,\n                               ctp_4d_filename,\n                               ct_filename,\n                               cta_fielname,\n                               dsa_filename,\n                               mask_brain_filename,\n                               atlas_path,\n                               report_out_dirname,\n                               report_progress=print,\n                               report_subprogress=print,\n                               debug=False):\n    new_ctp_filenames = []\n    base_3d_image = itk.imread(ctp_3d_filenames[0], itk.F)\n    ImageMath = tube.ImageMath.New(base_3d_image)\n    for filename in ctp_3d_filenames:\n        img = itk.imread(filename, itk.F)\n        ImageMath.SetInput(img)\n        ImageMath.Blur(0.5)\n        ImageMath.BlurOrder(2.0,0,2)\n        new_img = ImageMath.GetOutput()\n        Resample = tube.ResampleImage.New(Input=new_img)\n        Resample.SetSpacing([1.5,1.5,5])\n        Resample.SetInterpolator(\"Sinc\")\n        Resample.Update()\n        img = Resample.GetOutput()\n        filename_path,filename_name = os.path.split(filename)\n        org_filename = os.path.splitext(filename_name)\n        base_filename = os.path.join(report_out_dirname,org_filename[0])\n        new_filename = str(base_filename)+'_15x15x5.nii'\n        itk.imwrite(img,new_filename,compression=True)\n        new_ctp_filenames.append(new_filename)\n    \n    filename_path,filename_name = os.path.split(ctp_4d_filename)\n    org_filename = os.path.splitext(filename_name)\n    base_filename = os.path.join(report_out_dirname,org_filename[0])\n    new_ctp_4d_filename = str(base_filename)+'_15x15x5.nii'\n    scv_convert_3d_files_to_4d_file(new_ctp_filenames,\n        new_ctp_4d_filename)\n\n    match_image = itk.imread(new_ctp_filenames[0], itk.UC)\n    mask = itk.imread(mask_brain_filename,itk.UC)\n    ResampleMask = tube.ResampleImage.New(Input=mask)\n    ResampleMask.SetMatchImage(match_image)\n    ResampleMask.SetInterpolator(\"NearestNeighbor\")\n    ResampleMask.Update()\n    new_mask = ResampleMask.GetOutput()\n    filename_path,filename_name = os.path.split(mask_brain_filename)\n    org_filename = os.path.splitext(filename_name)\n    base_filename = os.path.join(report_out_dirname,org_filename[0])\n    new_mask_filename = str(base_filename)+'_15x15x5.nii'\n    itk.imwrite(new_mask,new_mask_filename,compression=True)\n\n    # Call matlab and pass it the 4D ctp filename and the output directory\n    cbf_filename,cbv_filename,mtt_filename,tmax_filename,ttp_filename = \\\n        scv_run_perfusion_toolbox(new_ctp_4d_filename, \\\n            new_mask_filename, report_out_dirname)\n\n    # Vessel enhancement and extraction\n    in_im = itk.imread(dsa_filename, itk.F)\n\n    in_filename_base = str(os.path.splitext(dsa_filename)[0])\n\n    brain_mask_im = itk.imread(mask_brain_filename, itk.F)\n    ImageMath.SetInput(in_im)\n    ImageMath.ReplaceValuesOutsideMaskRange(brain_mask_im,0.9,1.1,0)\n    in_brain_im = ImageMath.GetOutput()\n\n    report_progress(\"Enhancing vessels\",40)\n    # Enhancing vessels creates an image in which intensity is\n    #    related to \"vesselness\" instead of being related to the\n    #    amount of contrast agent in the vessel.  This simplifies\n    #    subsequent vessel seeding and traversal stopping criteria.\n    in_vess_im,in_brain_vess_im = scv_enhance_vessels_in_cta(\n        in_im,\n        in_brain_im,\n        report_progress=report_subprogress,\n        debug=debug)\n    itk.imwrite(in_vess_im,\n        os.path.join(report_out_dirname,\n            in_filename_base+\"_vessels_enhanced.mha\"),\n        compression=True)\n    itk.imwrite(in_brain_vess_im,\n        os.path.join(report_out_dirname,\n            in_filename_base+\"_brain_vessels_enhanced.mha\"),\n        compression=True)\n\n    report_progress(\"Extracting vessels\",60)\n    vess_mask_im,vess_so = scv_extract_vessels_from_cta(\n        in_vess_im,\n        in_brain_vess_im,\n        report_progress=report_subprogress,\n        debug=debug,\n        output_dirname=report_out_dirname)\n\n    itk.imwrite(in_brain_vess_im,\n        os.path.join(report_out_dirname,\n            in_filename_base+\"_vessels_extracted.mha\"),\n        compression=True)\n\n    SOWriter = itk.SpatialObjectWriter[3].New()\n    SOWriter.SetInput(vess_so)\n    SOWriter.SetBinaryPoints(True)\n    SOWriter.SetFileName(os.path.join(report_out_dirname,\n        in_filename_base+\"_vessels_extracted.tre\"))\n    SOWriter.Update()\n\n    VTPWriter = itk.WriteTubesAsPolyData.New()\n    VTPWriter.SetInput(vess_so)\n    VTPWriter.SetFileName(os.path.join(report_out_dirname,\n        in_filename_base+\"_vessels_extracted.vtp\"))\n    VTPWriter.Update()\n \n    report_progress(\"Generating Perfusion Stats\",80)\n\n    script_dirname = os.path.dirname(os.path.realpath(__file__))\n    atlas_im = itk.imread(\n        os.path.join(atlas_path,'atlas_brainweb.mha'), itk.F)\n    atlas_mask_im = itk.imread(\n        os.path.join(atlas_path,'atlas_brainweb_mask.mha'), itk.F)\n    atlas_reg_im,atlas_mask_reg_im = scv_register_atlas_to_image(\n        atlas_im,\n        atlas_mask_im,\n        in_brain_im)\n    ImageMath = tube.ImageMath.New(Input=atlas_mask_reg_im)\n    ImageMath.ReplaceValuesOutsideMaskRange(vess_mask_im,\n        0.000001,9999,4)\n    ImageMath.ReplaceValuesOutsideMaskRange(in_brain_im,\n        0.000001,9999,0)\n    vess_atlas_mask_im = ImageMath.GetOutput()\n    itk.imwrite(vess_atlas_mask_im,\n        os.path.join(report_out_dirname,\n            in_filename_base+\"_vessels_atlas_mask.mha\"),\n        compression=True)\n\n    TubeMath = tube.TubeMath[3,itk.F].New()\n    TubeMath.SetInputTubeGroup(vess_so)\n    TubeMath.SetUseAllTubes()\n    TubeMath.ComputeTubeRegions(vess_atlas_mask_im)\n    \n    graph_label = None\n    graph_data = None\n    ttp_im = None\n    if len(ttp_filename) > 0:\n        report_progress(\"Generating TTP Graphs\",92)\n        ttp_im = itk.imread(ttp_filename, itk.F)\n        Resample = tube.ResampleImage.New(Input=ttp_im)\n        Resample.SetMatchImage(vess_atlas_mask_im)\n        Resample.Update()\n        fit_ttp_im = Resample.GetOutput()\n        TubeMath.SetPointValuesFromImage(fit_ttp_im, \"TTP\")\n        TubeMath.SetPointValuesFromTubeRegions(fit_ttp_im,\n            \"TTP_Tissue\",\n            1.5,\n            4)\n        TubeMath.SmoothTubeProperty(\"TTP\",4)\n        TubeMath.SmoothTubeProperty(\"TTP_Tissue\",16)\n        time_bin,ttp_bin,ttp_count = scv_compute_atlas_region_stats(\n            vess_atlas_mask_im,\n            fit_ttp_im,\n            fit_ttp_im,\n            100,\n            report_subprogress)\n        graph_label = [\"Bin_Num\"]\n        graph_data = np.arange(len(time_bin))\n        graph_label = np.append(graph_label,\"TPP\")\n        graph_data = np.stack((graph_data,time_bin))\n        for r in range(1,ttp_bin.shape[0]):\n            graph_label = np.append(graph_label,\n                \"Count_Region_\"+str(r))\n            graph_data = np.concatenate((graph_data,\n                [ttp_count[r,:]]))\n\n    if len(cbf_filename) > 0:\n        report_progress(\"Generating CBF Graphs\",94)\n        cbf_im = itk.imread(cbf_filename, itk.F)\n        Resample = tube.ResampleImage.New(Input=cbf_im)\n        Resample.SetMatchImage(vess_atlas_mask_im)\n        Resample.Update()\n        fit_cbf_im = Resample.GetOutput()\n        TubeMath.SetPointValuesFromImage(fit_cbf_im, \"CBF\")\n        TubeMath.SetPointValuesFromTubeRegions(fit_cbf_im,\n            \"CBF_Tissue\",\n            1.5,\n            4)\n        TubeMath.SmoothTubeProperty(\"CBF\",4)\n        TubeMath.SmoothTubeProperty(\"CBF_Tissue\",16)\n        if ttp_im!=None:\n            time_bin,cbf_bin,cbf_count = scv_compute_atlas_region_stats(\n                vess_atlas_mask_im,\n                fit_ttp_im,\n                fit_cbf_im,\n                100,\n                report_subprogress)\n            for r in range(1,cbf_bin.shape[0]):\n                graph_label = np.append(graph_label,\n                    \"CBF_Region\"+str(r))\n                graph_data = np.concatenate((graph_data,\n                    [cbf_bin[r,:]]))\n\n    if len(cbv_filename) > 0:\n        report_progress(\"Generating CBV Graphs\",96)\n        cbv_im = itk.imread(cbv_filename, itk.F)\n        Resample = tube.ResampleImage.New(Input=cbv_im)\n        Resample.SetMatchImage(vess_atlas_mask_im)\n        Resample.Update()\n        fit_cbv_im = Resample.GetOutput()\n        TubeMath.SetPointValuesFromImage(fit_cbv_im, \"CBV\")\n        TubeMath.SetPointValuesFromTubeRegions(fit_cbv_im,\n            \"CBV_Tissue\",\n            1.5,\n            4)\n        TubeMath.SmoothTubeProperty(\"CBV\",4)\n        TubeMath.SmoothTubeProperty(\"CBV_Tissue\",16)\n        if ttp_im!=None:\n            time_bin,cbv_bin,cbv_count = scv_compute_atlas_region_stats(\n                vess_atlas_mask_im,\n                fit_ttp_im,\n                fit_cbv_im,\n                100,\n                report_subprogress)\n            for r in range(1,cbv_bin.shape[0]):\n                graph_label = np.append(graph_label,\n                    \"CBV_Region\"+str(r))\n                graph_data = np.concatenate((graph_data,\n                    [cbv_bin[r,:]]))\n    if len(tmax_filename) > 0:\n        report_progress(\"Generating TMax Graphs\",98)\n        tmax_im = itk.imread(tmax_filename, itk.F)\n        Resample = tube.ResampleImage.New(Input=tmax_im)\n        Resample.SetMatchImage(vess_atlas_mask_im)\n        Resample.Update()\n        fit_tmax_im = Resample.GetOutput()\n        TubeMath.SetPointValuesFromImage(fit_tmax_im, \"TMax\")\n        TubeMath.SetPointValuesFromTubeRegions(fit_tmax_im,\n            \"TMax_Tissue\",\n            1.5,\n            4)\n        TubeMath.SmoothTubeProperty(\"TMax\",4)\n        TubeMath.SmoothTubeProperty(\"TMax_Tissue\",16)\n        if ttp_im!=None:\n            time_bin,tmax_bin,tmax_count = scv_compute_atlas_region_stats(\n                vess_atlas_mask_im,\n                fit_ttp_im,\n                fit_tmax_im,\n                100,\n                report_subprogress)\n            for r in range(1,tmax_bin.shape[0]):\n                graph_label = np.append(graph_label,\n                    \"TMax_Region\"+str(r))\n                graph_data = np.concatenate((graph_data,\n                    [tmax_bin[r,:]]))\n\n    report_progress(\"Saving results\",99)\n    SOWriter = itk.SpatialObjectWriter[3].New()\n    SOWriter.SetInput(vess_so)\n    SOWriter.SetBinaryPoints(True)\n    SOWriter.SetFileName(os.path.join(report_out_dirname,\n        in_filename_base+\"_vessels_extracted_perf.tre\"))\n    SOWriter.Update()\n\n    VTPWriter = itk.WriteTubesAsPolyData.New()\n    VTPWriter.SetInput(vess_so)\n    VTPWriter.SetFileName(os.path.join(report_out_dirname,\n        in_filename_base+\"_vessels_extracted_perf.vtp\"))\n    VTPWriter.Update()\n\n    csvfilename = os.path.join(report_out_dirname,\n        in_filename_base+\"_vessels_extracted_perf.csv\")\n    csvfile = open(csvfilename,'w',newline='')\n    csvwriter = csv.writer(csvfile, dialect='excel',\n        quoting=csv.QUOTE_NONE)\n    csvwriter.writerow(graph_label)\n    for r in range(graph_data.shape[1]):\n        csvwriter.writerow(['{:f}'.format(x) for x in graph_data[:,r]])\n    csvfile.close()\n    report_progress(\"Done\",100)\n\n\n#################\n#################\n#################\n#################\n#################\ndef scv_generate_4d_ctp_vessel_report(ctp_4d_filename,\n                                      atlas_path,\n                                      report_out_dirname,\n                                      report_progress=print,\n                                      report_subprogress=print,\n                                      debug=False):\n\n    ctp_3d_filenames,ctp_4d_filename,ct_filename, \\\n        cta_filename,dsa_filename,mask_brain_filename \\\n            = scv_prepare_4d_for_perfusion_toolbox( \\\n                ctp_4d_filename, report_out_dirname, \\\n                report_progress, report_subprogress, debug)\n\n\n    scv_generate_vessel_report(ctp_3d_filenames, \\\n        ctp_4d_filename,ct_filename, \\\n        cta_filename,dsa_filename, \\\n        mask_brain_filename,atlas_path,report_out_dirname, \\\n        report_progress,report_subprogress,debug)\n\n\n#################\n#################\n#################\n#################\n#################\ndef scv_generate_3d_ctp_vessel_report(ctp_3d_filenames,\n                                      atlas_path,\n                                      report_out_dirname,\n                                      report_progress=print,\n                                      report_subprogress=print,\n                                      debug=False):\n    ctp_4d_filename,ct_filename, \\\n        cta_filename,dsa_filename,mask_brain_filename \\\n            = scv_prepare_3d_for_perfusion_toolbox( \\\n                ctp_3d_filenames, report_out_dirname, \\\n                report_progress, report_subprogress, debug)\n\n    scv_generate_vessel_report(ctp_3d_filenames, \\\n        ctp_4d_filename,ct_filename, \\\n        cta_filename,dsa_filename, \\\n        mask_brain_filename,atlas_path,report_out_dirname, \\\n        report_progress,report_subprogress,debug)\n\n", "meta": {"hexsha": "016174205817146f177b9a3ccf351927971c965e", "size": 38951, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/StroCoVess_Lib.py", "max_stars_repo_name": "aylward/ITKTubeTK-StrokeCollateralVessels", "max_stars_repo_head_hexsha": "70379e65127b8a065e07d8a1ccb3cac8a7e6192e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/StroCoVess_Lib.py", "max_issues_repo_name": "aylward/ITKTubeTK-StrokeCollateralVessels", "max_issues_repo_head_hexsha": "70379e65127b8a065e07d8a1ccb3cac8a7e6192e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-01-11T16:49:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-26T12:38:06.000Z", "max_forks_repo_path": "lib/StroCoVess_Lib.py", "max_forks_repo_name": "aylward/ITKTubeTK-StrokeCollateralVessels", "max_forks_repo_head_hexsha": "70379e65127b8a065e07d8a1ccb3cac8a7e6192e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-22T17:28:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T13:55:36.000Z", "avg_line_length": 36.7115928369, "max_line_length": 213, "alphanum_fraction": 0.6422684912, "include": true, "reason": "import numpy", "num_tokens": 9738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.19867636757988238}}
{"text": "\"\"\"\nModule containing customized antenna classes for ARA.\n\nMany of the methods here mirror methods used in the antennas in AraSim, to\nensure that AraSim results can be matched.\n\n\"\"\"\n\nimport logging\nimport os.path\nimport pickle\nimport numpy as np\nimport scipy.constants\nimport scipy.signal\nfrom pyrex.internal_functions import (normalize, complex_bilinear_interp,\n                                      complex_interp)\nfrom pyrex.signals import Signal, FunctionSignal\nfrom pyrex.antenna import Antenna\nfrom pyrex.detector import AntennaSystem\n\nlogger = logging.getLogger(__name__)\n\n\ndef _read_arasim_antenna_data(filename):\n    \"\"\"\n    Gather antenna directionality data from an AraSim-formatted data file.\n\n    The data file should have columns for theta, phi, dB gain, non-dB gain, and\n    phase (in degrees). This should be divided into sections for each frequency\n    with a header line \"freq : X MHz\", optionally followed by a second line\n    \"SWR : Y\".\n\n    Parameters\n    ----------\n    filename : str\n        Name of the data file.\n\n    Returns\n    -------\n    response : ndarray\n        3-D array of complex-valued voltage gains as a function of frequency\n        along axis 0, zenith along axis 1, and azimuth along axis 2.\n    frequencies : ndarray\n        Frequencies (Hz) corresponding to axis 0 of `response`.\n    thetas : ndarray\n        Zenith angles (degrees) corresponding to axis 1 of `response`.\n    phis : ndarray\n        Azimuth angles (degrees) corresponding to axis 2 of `response`.\n\n    \"\"\"\n    data = {}\n    freqs = set()\n    thetas = set()\n    phis = set()\n    freq = 0\n    with open(filename) as f:\n        for line in f:\n            words = line.split()\n            if line.startswith('freq'):\n                freq = 1\n                if words[-1]==\"Hz\":\n                    pass\n                elif words[-1]==\"kHz\":\n                    freq *= 1e3\n                elif words[-1]==\"MHz\":\n                    freq *= 1e6\n                elif words[-1]==\"GHz\":\n                    freq *= 1e9\n                else:\n                    raise ValueError(\"Cannot parse line: '\"+line+\"'\")\n                freq *= float(words[-2])\n                freqs.add(freq)\n            elif line.startswith('SWR'):\n                swr = float(words[-1])\n            elif len(words)==5 and words[0]!=\"Theta\":\n                theta = int(words[0])\n                thetas.add(theta)\n                phi = int(words[1])\n                phis.add(phi)\n                db_gain = float(words[2])\n                # AraSim actually only seems to use the sqrt of the gain\n                # (must be gain in power, not voltage)\n                # gain = np.sqrt(float(words[3]))\n                gain = np.sqrt(10**(db_gain/10))\n                phase = np.radians(float(words[4]))\n                data[(freq, theta, phi)] = (gain, phase)\n\n    # Convert data dictionary into 3-D array of responses\n    response = np.empty((len(freqs), len(thetas), len(phis)),\n                        dtype=np.complex_)\n    for i, freq in enumerate(sorted(freqs)):\n        for j, theta in enumerate(sorted(thetas)):\n            for k, phi in enumerate(sorted(phis)):\n                gain, phase = data[(freq, theta, phi)]\n                response[i, j, k] = gain * np.exp(1j*phase)\n\n    response_data = (response, np.array(sorted(freqs)),\n                     np.array(sorted(thetas)), np.array(sorted(phis)))\n    return _fix_response_wrapping(response_data)\n\n\n# If the antenna responses don't go all the way to phi=360, add the extra\n# column for the sake of the interpolators\ndef _fix_response_wrapping(response_data):\n    \"\"\"\n    Add phi=360 degrees column to antenna response data.\n\n    The interpolators require that the full azimuth range of the antennas is\n    described, so this function duplicates the phi=0 column of the antenna\n    response into a phi=360 column, as long as it matches with the rest of\n    the phi spacings.\n\n    Parameters\n    ----------\n    response_data : tuple of ndarray\n        Tuple containing the response data for the antenna. The first element\n        should contain a 3-D array of the antenna response model as a function\n        of frequency (axis 0), zenith (axis 1), and azimuth (axis 2). The\n        remaining elements should be the values of the frequency, zenith, and\n        azimuth axes, respectively.\n\n    Returns\n    -------\n    response : ndarray\n        Corrected 3-D array of antenna response values, including the phi=360\n        degree column if possible.\n    frequencies : ndarray\n        Frequencies (Hz) corresponding to axis 0 of `response`.\n    thetas : ndarray\n        Zenith angles (degrees) corresponding to axis 1 of `response`.\n    phis : ndarray\n        Azimuth angles (degrees) corresponding to axis 2 of `response`.\n\n    \"\"\"\n    response, freqs, thetas, phis = response_data\n    if phis[-1]==360:\n        return response_data\n    if phis[0]==0 and phis[-1]==360-phis[1]:\n        phis = np.concatenate((phis, [360]))\n        response = np.concatenate((response, response[:, :, 0:1]), axis=2)\n    return response, freqs, thetas, phis\n\n\ndef _read_arasim_antenna_pickle(filename):\n    \"\"\"\n    Gather antenna directional response data from a pickled data file.\n\n    The data file should be a pickled file containing the antenna directional\n    response data from an AraSim-formatted data file as returned by the\n    `_read_arasim_antenna_data` function.\n\n    Parameters\n    ----------\n    filename : str\n        Name of the data file without the ``.pkl`` extension.\n\n    Returns\n    -------\n    response : ndarray\n        3-D array of complex-valued voltage gains as a function of frequency\n        along axis 0, zenith along axis 1, and azimuth along axis 2.\n    frequencies : ndarray\n        Frequencies (Hz) corresponding to axis 0 of `response`.\n    thetas : ndarray\n        Zenith angles (degrees) corresponding to axis 1 of `response`.\n    phis : ndarray\n        Azimuth angles (degrees) corresponding to axis 2 of `response`.\n\n    See Also\n    --------\n    _read_arasim_antenna_data : Gather antenna directionality data from an\n                                AraSim-formatted data file.\n\n    \"\"\"\n    # Quick fix for filenames with one of the approved extensions already\n    # (just strip it)\n    if filename.endswith(\".txt\") or filename.endswith(\".pkl\"):\n        filename = filename[:-4]\n\n    # If there is no pickle file, read the response data using the\n    # _read_arasim_antenna_data function, and then make a pickle file\n    if not os.path.isfile(filename+\".pkl\"):\n        logger.warning(\"Antenna model file %s.pkl not found. \"+\n                       \"Generating a new file now\", filename)\n        response_data = _read_arasim_antenna_data(filename+\".txt\")\n        with open(filename+\".pkl\", 'wb') as f:\n            pickle.dump(response_data, f)\n        return response_data\n\n    # Otherwise, read from the pickle file\n    else:\n        with open(filename+\".pkl\", 'rb') as f:\n            return pickle.load(f)\n\n\ndef _read_filter_data(filename):\n    \"\"\"\n    Gather frequency-dependent filtering data from a data file.\n\n    The data file should have columns for frequency, non-dB gain, and phase\n    (in radians).\n\n    Parameters\n    ----------\n    filename : str\n        Name of the data file.\n\n    Returns\n    -------\n    gains : ndarray\n        Complex-valued voltage gains as a function of frequency.\n    frequencies : ndarray\n        Frequencies (Hz) corresponding to the values of `gains`.\n\n    \"\"\"\n    gains = []\n    freqs = []\n    freq_scale = 0\n    with open(filename) as f:\n        for line in f:\n            words = line.split()\n            if line.startswith('Freq'):\n                _, scale = words[0].split(\"(\")\n                scale = scale.rstrip(\")\")\n                if scale==\"Hz\":\n                    freq_scale = 1\n                elif scale==\"kHz\":\n                    freq_scale = 1e3\n                elif scale==\"MHz\":\n                    freq_scale = 1e6\n                elif scale==\"GHz\":\n                    freq_scale = 1e9\n                else:\n                    raise ValueError(\"Cannot parse line: '\"+line+\"'\")\n            elif len(words)==3 and words[0]!=\"Total\":\n                f, g, p = line.split(\",\")\n                freq = float(f) * freq_scale\n                gain = float(g)\n                phase = float(p)\n                freqs.append(freq)\n                gains.append(gain * np.exp(1j*phase))\n\n    return np.array(gains), np.array(freqs)\n\n\nARA_DATA_DIR = os.path.join(os.path.dirname(__file__), \"data\")\nVPOL_DATA_FILE = os.path.join(ARA_DATA_DIR,\n                              \"Vpol_original_CrossFeed_150mmHole_Ice_ARASim.txt\")\nHPOL_DATA_FILE = os.path.join(ARA_DATA_DIR,\n                              \"Hpol_original_150mmHole_Ice_ARASim.txt\")\nFILT_DATA_FILE = os.path.join(ARA_DATA_DIR,\n                              \"ARA_Electronics_TotalGain_TwoFilters.txt\")\n# Vpol data file contains only the theta responses\nVPOL_THETA_RESPONSE_DATA = _read_arasim_antenna_pickle(VPOL_DATA_FILE)\nVPOL_RESPONSE_DATA = (\n    VPOL_THETA_RESPONSE_DATA[0],\n    np.zeros(VPOL_THETA_RESPONSE_DATA[0].shape),\n    *VPOL_THETA_RESPONSE_DATA[1:]\n)\n# Hpol data file contains only the phi responses\nHPOL_PHI_RESPONSE_DATA = _read_arasim_antenna_pickle(HPOL_DATA_FILE)\nHPOL_RESPONSE_DATA = (\n    np.zeros(HPOL_PHI_RESPONSE_DATA[0].shape),\n    *HPOL_PHI_RESPONSE_DATA\n)\nALL_FILTERS_DATA = _read_filter_data(FILT_DATA_FILE)\n\n\n\nclass ARAAntenna(Antenna):\n    \"\"\"\n    Antenna class to be used for ARA antennas.\n\n    Stores the attributes of an antenna as well as handling receiving,\n    processing, and storing signals and adding noise. Antenna response based on\n    provided models.\n\n    Parameters\n    ----------\n    response_data : tuple of array_like\n        Tuple containing the response data for the antenna along the theta\n        and phi polarization directions. The first and second elements should\n        contain 3-D arrays of the antenna response model in the theta and phi\n        polarizations, respectively, as a function of frequency (axis 0),\n        zenith (axis 1), and azimuth (axis 2). The remaining elements should be\n        the values of the frequency, zenith, and azimuth axes, respectively.\n    position : array_like\n        Vector position of the antenna.\n    center_frequency : float\n        Frequency (Hz) at the center of the antenna's frequency range.\n    bandwidth : float\n        Bandwidth (Hz) of the antenna.\n    temperature : float\n        The noise temperature (K) of the antenna. Used in combination with\n        `resistance` to calculate the RMS voltage of the antenna noise.\n    resistance : float\n        The noise resistance (ohm) of the antenna. Used in combination with\n        `temperature` to calculate the RMS voltage of the antenna noise.\n    orientation : array_like, optional\n        Vector direction of the z-axis of the antenna.\n    efficiency : float, optional\n        Antenna efficiency applied to incoming signal values.\n    noisy : boolean, optional\n        Whether or not the antenna should add noise to incoming signals.\n    unique_noise_waveforms : int, optional\n        The number of expected noise waveforms needed for each received signal\n        to have its own noise.\n\n    Attributes\n    ----------\n    position : array_like\n        Vector position of the antenna.\n    z_axis : ndarray\n        Vector direction of the z-axis of the antenna.\n    x_axis : ndarray\n        Vector direction of the x-axis of the antenna.\n    antenna_factor : float\n        Antenna factor used for converting fields to voltages.\n    efficiency : float\n        Antenna efficiency applied to incoming signal values.\n    noisy : boolean\n        Whether or not the antenna should add noise to incoming signals.\n    unique_noises : int\n        The number of expected noise waveforms needed for each received signal\n        to have its own noise.\n    freq_range : array_like\n        The frequency band in which the antenna operates (used for noise\n        production).\n    temperature : float or None\n        The noise temperature (K) of the antenna. Used in combination with\n        `resistance` to calculate the RMS voltage of the antenna noise.\n    resistance : float or None\n        The noise resistance (ohm) of the antenna. Used in combination with\n        `temperature` to calculate the RMS voltage of the antenna noise.\n    noise_rms : float or None\n        The RMS voltage (V) of the antenna noise. If not ``None``, this value\n        will be used instead of the RMS voltage calculated from the values of\n        `temperature` and `resistance`.\n    signals : list of Signal\n        The signals which have been received by the antenna.\n    is_hit\n    is_hit_mc_truth\n    waveforms\n    all_waveforms\n\n    See Also\n    --------\n    pyrex.Antenna : Base class for antennas.\n\n    \"\"\"\n    def __init__(self, response_data, position, center_frequency, bandwidth,\n                 temperature, resistance, orientation=(0,0,1), efficiency=1,\n                 noisy=True, unique_noise_waveforms=10):\n        # Parse the response data\n        self._theta_response = response_data[0]\n        self._phi_response = response_data[1]\n        self._response_freqs = response_data[2]\n        self._response_zens = response_data[3]\n        self._response_azis = response_data[4]\n\n        # Get the critical frequencies in Hz\n        f_low = center_frequency - bandwidth/2\n        f_high = center_frequency + bandwidth/2\n\n        # Get arbitrary x-axis orthogonal to orientation\n        tmp_vector = np.zeros(3)\n        while np.array_equal(np.cross(orientation, tmp_vector), (0,0,0)):\n            tmp_vector = np.random.rand(3)\n        ortho = np.cross(orientation, tmp_vector)\n        # Note: ortho is not normalized, but will be normalized by Antenna's init\n\n        super().__init__(position=position, z_axis=orientation, x_axis=ortho,\n                         efficiency=efficiency, freq_range=(f_low, f_high),\n                         temperature=temperature, resistance=resistance,\n                         noisy=noisy,\n                         unique_noise_waveforms=unique_noise_waveforms)\n\n    def directional_gain(self, theta, phi):\n        raise NotImplementedError(\"Directional gain is not defined for \"+\n                                  self.__class__.__name__+\". Use the \"+\n                                  \"directional_response method instead.\")\n\n    def polarization_gain(self, polarization):\n        raise NotImplementedError(\"Polarization gain is not defined for \"+\n                                  self.__class__.__name__+\". Use the \"+\n                                  \"directional_response method instead.\")\n\n    def directional_response(self, theta, phi, polarization):\n        \"\"\"\n        Generate the (complex) frequency-dependent directional response.\n\n        For given angles and polarization direction, use the model of the\n        directional and polarization gains of the antenna to generate a\n        function for the interpolated response of the antenna with respect to\n        frequency. Used with the `frequency_response` method to calculate\n        effective heights.\n\n        Parameters\n        ----------\n        theta : float\n            Polar angle (radians) from which a signal is arriving.\n        phi : float\n            Azimuthal angle (radians) from which a signal is arriving.\n        polarization : array_like\n            Normalized polarization vector in the antenna coordinate system.\n\n        Returns\n        -------\n        function\n            A function which returns complex-valued voltage gains for given\n            frequencies, using the values of incoming angle and polarization.\n\n        See Also\n        --------\n        ARAAntenna.frequency_response : Calculate the (complex) frequency\n                                        response of the antenna.\n\n        \"\"\"\n        e_theta = [np.cos(theta) * np.cos(phi),\n                   np.cos(theta) * np.sin(phi),\n                   -np.sin(theta)]\n        e_phi = [-np.sin(phi), np.cos(phi), 0]\n        theta_factor = np.dot(polarization, e_theta)\n        phi_factor = np.dot(polarization, e_phi)\n        theta_gains = complex_bilinear_interp(\n            x=np.degrees(theta), y=np.degrees(phi),\n            xp=self._response_zens,\n            yp=self._response_azis,\n            fp=self._theta_response,\n            method='cartesian'\n        )\n        phi_gains = complex_bilinear_interp(\n            x=np.degrees(theta), y=np.degrees(phi),\n            xp=self._response_zens,\n            yp=self._response_azis,\n            fp=self._phi_response,\n            method='cartesian'\n        )\n        freq_interpolator = lambda frequencies: complex_interp(\n            x=frequencies, xp=self._response_freqs,\n            fp=theta_factor*theta_gains + phi_factor*phi_gains,\n            method='euler', outer=0\n        )\n        return freq_interpolator\n\n    def frequency_response(self, frequencies):\n        \"\"\"\n        Calculate the (complex) frequency response of the antenna.\n\n        Rather than handling the entire frequency response of the antenna, this\n        method is being used to convert the frequency-dependent gains from the\n        `directional_response` method into effective heights.\n\n        Parameters\n        ----------\n        frequencies : array_like\n            1D array of frequencies (Hz) at which to calculate gains.\n\n        Returns\n        -------\n        array_like\n            Complex gains in voltage for the given `frequencies`.\n\n        See Also\n        --------\n        ARAAntenna.directional_response : Generate the (complex) frequency\n                                          dependent directional response.\n\n        \"\"\"\n        # From AraSim GaintoHeight function, with gain calculation moved to\n        # the directional_response method.\n        # gain=4*pi*A_eff/lambda^2 and h_eff=2*sqrt(A_eff*Z_rx/Z_air)\n        # Then 0.5 to calculate power with heff (cancels 2 above)\n        heff = np.zeros(len(frequencies))\n        # The index of refraction in this calculation should be the index of\n        # the ice used in the production of the antenna model.\n        n = 1.78\n        heff[frequencies!=0] = np.sqrt((scipy.constants.c\n                                        /frequencies[frequencies!=0]/n)**2\n                                       * n*50/377 /(4*np.pi))\n        return heff\n\n\n    def apply_response(self, signal, direction=None, polarization=None,\n                       force_real=True):\n        \"\"\"\n        Process the complete antenna response for an incoming signal.\n\n        Processes the incoming signal according to the frequency response of\n        the antenna, the efficiency, and the antenna factor. May also apply the\n        directionality and the polarization gain depending on the provided\n        parameters. Subclasses may wish to overwrite this function if the\n        full antenna response cannot be divided nicely into the described\n        pieces.\n\n        Parameters\n        ----------\n        signal : Signal\n            Incoming ``Signal`` object to process.\n        direction : array_like, optional\n            Vector denoting the direction of travel of the signal as it reaches\n            the antenna (in the global coordinate frame). If ``None`` no\n            directional response will be applied.\n        polarization : array_like, optional\n            Vector denoting the signal's polarization direction (in the global\n            coordinate frame). If ``None`` no polarization gain will be applied.\n        force_real : boolean, optional\n            Whether or not the frequency response should be redefined in the\n            negative-frequency domain to keep the values of the filtered signal\n            real.\n\n        Returns\n        -------\n        Signal\n            Processed ``Signal`` object after the complete antenna response has\n            been applied. Should have a ``value_type`` of ``voltage``.\n\n        Raises\n        ------\n        ValueError\n            If the given `signal` does not have a ``value_type`` of ``voltage``\n            or ``field``.\n\n        See Also\n        --------\n        pyrex.Signal : Base class for time-domain signals.\n\n        \"\"\"\n        new_signal = signal.copy()\n        new_signal.value_type = Signal.Type.voltage\n        freq_response = self.frequency_response\n\n        if direction is not None and polarization is not None:\n            # Calculate theta and phi relative to the orientation\n            origin = self.position - normalize(direction)\n            r, theta, phi = self._convert_to_antenna_coordinates(origin)\n            # Calculate polarization vector in the antenna coordinates\n            y_axis = np.cross(self.z_axis, self.x_axis)\n            transformation = np.array([self.x_axis, y_axis, self.z_axis])\n            ant_pol = np.dot(transformation, normalize(polarization))\n            # Calculate directional response as a function of frequency\n            directive_response = self.directional_response(theta, phi, ant_pol)\n            freq_response = lambda f: (self.frequency_response(f)\n                                       * directive_response(f))\n\n        elif (direction is not None and polarization is None\n              or direction is None and polarization is not None):\n            raise ValueError(\"Direction and polarization must be specified together\")\n\n        # Apply (combined) frequency response\n        new_signal.filter_frequencies(freq_response, force_real=force_real)\n\n        signal_factor = self.efficiency\n\n        if signal.value_type==Signal.Type.voltage:\n            pass\n        elif signal.value_type==Signal.Type.field:\n            signal_factor /= self.antenna_factor\n        else:\n            raise ValueError(\"Signal's value type must be either \"\n                             +\"voltage or field. Given \"+str(signal.value_type))\n\n        new_signal *= signal_factor\n\n        return new_signal\n\n    # Redefine receive method to use force_real as True by default\n    def receive(self, signal, direction=None, polarization=None,\n                force_real=True):\n        \"\"\"\n        Process and store one or more incoming (polarized) signals.\n\n        Processes the incoming signal(s) according to the ``apply_response``\n        method, then stores the total processed signal to the signals list. If\n        more than one signal is given, they should be logically connected as\n        separately polarized portions of the same signal.\n\n        Parameters\n        ----------\n        signal : Signal or array_like\n            Incoming ``Signal`` object(s) to process and store. May be separate\n            polarization representations, but therefore should have the same\n            times.\n        direction : array_like, optional\n            Vector denoting the direction of travel of the signal(s) as they\n            reach the antenna (in the global coordinate frame). If ``None`` no\n            directional gain will be applied.\n        polarization : array_like, optional\n            Vector(s) denoting the signal's polarization direction (in the\n            global coordinate frame). Number of vectors should match the number\n            of elements in `signal` argument. If ``None`` no polarization gain\n            will be applied.\n        force_real : boolean, optional\n            Whether or not the frequency response should be redefined in the\n            negative-frequency domain to keep the values of the filtered signal\n            real.\n\n        Raises\n        ------\n        ValueError\n            If the number of polarizations does not match the number of signals.\n            Or if the signals do not have the same `times` array.\n\n        See Also\n        --------\n        pyrex.Signal : Base class for time-domain signals.\n\n        \"\"\"\n        super().receive(signal=signal, direction=direction,\n                        polarization=polarization,\n                        force_real=force_real)\n\n\n\nclass ARAAntennaSystem(AntennaSystem):\n    \"\"\"\n    Antenna system extending base ARA antenna with front-end processing.\n\n    Applies as the front end a filter representing the full ARA electronics\n    chain (including amplification) and signal clipping. Additionally provides\n    a method for passing a signal through the tunnel diode.\n\n    Parameters\n    ----------\n    response_data : tuple of array_like\n        Tuple containing the response data for the antenna along the theta\n        and phi polarization directions. The first and second elements should\n        contain 3-D arrays of the antenna response model in the theta and phi\n        polarizations, respectively, as a function of frequency (axis 0),\n        zenith (axis 1), and azimuth (axis 2). The remaining elements should be\n        the values of the frequency, zenith, and azimuth axes, respectively.\n    name : str\n        Name of the antenna.\n    position : array_like\n        Vector position of the antenna.\n    power_threshold : float\n        Power threshold for trigger condition. Antenna triggers if a signal\n        passed through the tunnel diode exceeds this threshold times the noise\n        RMS of the tunnel diode.\n    orientation : array_like, optional\n        Vector direction of the z-axis of the antenna.\n    amplification : float, optional\n        Amplification to be applied to the signal pre-clipping. Note that the\n        usual ARA electronics amplification is already applied without this.\n    amplifier_clipping : float, optional\n        Voltage (V) above which the amplified signal is clipped (in positive\n        and negative values).\n    noisy : boolean, optional\n        Whether or not the antenna should add noise to incoming signals.\n    unique_noise_waveforms : int, optional\n        The number of expected noise waveforms needed for each received signal\n        to have its own noise.\n\n    Attributes\n    ----------\n    antenna : Antenna\n        ``Antenna`` object extended by the front end.\n    name : str\n        Name of the antenna.\n    position : array_like\n        Vector position of the antenna.\n    power_threshold : float\n        Power threshold for trigger condition. Antenna triggers if a signal\n        passed through the tunnel diode exceeds this threshold times the noise\n        RMS of the tunnel diode.\n    amplification : float\n        Amplification to be applied to the signal pre-clipping. Note that the\n        usual ARA electronics amplification is already applied without this.\n    amplifier_clipping : float\n        Voltage (V) above which the amplified signal is clipped (in positive\n        and negative values).\n    lead_in_time : float\n        Lead-in time (s) required for the front end to equilibrate.\n        Automatically added in before calculation of signals and waveforms.\n    is_hit\n    is_hit_mc_truth\n    signals\n    waveforms\n    all_waveforms\n\n    See Also\n    --------\n    pyrex.AntennaSystem : Base class for antenna system with front-end\n                          processing.\n    ARAAntenna : Antenna class to be used for ARA antennas.\n\n    \"\"\"\n    lead_in_time = 5e-9\n\n    def __init__(self, response_data, name, position, power_threshold,\n                 orientation=(0,0,1), amplification=1, amplifier_clipping=1,\n                 noisy=True, unique_noise_waveforms=10,\n                 **kwargs):\n        super().__init__(ARAAntenna)\n\n        self.name = str(name)\n        self.position = position\n\n        self.amplification = amplification\n        self.amplifier_clipping = amplifier_clipping\n\n        self.setup_antenna(response_data=response_data,\n                           orientation=orientation, noisy=noisy,\n                           unique_noise_waveforms=unique_noise_waveforms,\n                           **kwargs)\n\n        self.power_threshold = power_threshold\n        self._power_mean = None\n        self._power_std = None\n\n        self._filter_response = ALL_FILTERS_DATA[0]\n        self._filter_freqs = ALL_FILTERS_DATA[1]\n\n    @property\n    def _metadata(self):\n        \"\"\"Metadata dictionary for writing `ARAAntennaSystem` information.\"\"\"\n        meta = super()._metadata\n        meta.update({\n            \"name\": self.name,\n            \"lead_in_time\": self.lead_in_time,\n            \"amplification\": self.amplification,\n            \"amplifier_clipping\": self.amplifier_clipping,\n            \"power_threshold\": self.power_threshold,\n        })\n        return meta\n\n    def setup_antenna(self, response_data, center_frequency=500e6,\n                      bandwidth=800e6, temperature=325, resistance=50,\n                      orientation=(0,0,1), efficiency=1, noisy=True,\n                      unique_noise_waveforms=10, **kwargs):\n        \"\"\"\n        Setup the antenna by passing along its init arguments.\n\n        Any arguments passed to this method are directly passed to the\n        ``__init__`` methods of the ``antenna``'s class.\n\n        Parameters\n        ----------\n        response_data : tuple of array_like\n            Tuple containing the response data for the antenna along the theta\n            and phi polarization directions. The first and second elements\n            should contain 3-D arrays of the antenna response model in the\n            theta and phi polarizations, respectively, as a function of\n            frequency (axis 0), zenith (axis 1), and azimuth (axis 2). The\n            remaining elements should be the values of the frequency, zenith,\n            and azimuth axes, respectively.\n        center_frequency : float, optional\n            Frequency (Hz) at the center of the antenna's frequency range.\n        bandwidth : float, optional\n            Bandwidth (Hz) of the antenna.\n        temperature : float, optional\n            The noise temperature (K) of the antenna. Used in combination with\n            `resistance` to calculate the RMS voltage of the antenna noise.\n        resistance : float, optional\n            The noise resistance (ohm) of the antenna. Used in combination with\n            `temperature` to calculate the RMS voltage of the antenna noise.\n        orientation : array_like, optional\n            Vector direction of the z-axis of the antenna.\n        efficiency : float, optional\n            Antenna efficiency applied to incoming signal values.\n        noisy : boolean, optional\n            Whether or not the antenna should add noise to incoming signals.\n        unique_noise_waveforms : int, optional\n            The number of expected noise waveforms needed for each received\n            signal to have its own noise.\n\n        \"\"\"\n        # Noise rms should be about 40 mV (after filtering with gain of ~5000).\n        # This is mostly satisfied by using the default noise temperature from\n        # AraSim, 325 K, along with a 50 ohm resistance\n        # Additionally, the bandwidth of the antenna is set slightly larger\n        # than the nominal bandwidth of the true ARA antenna system (700 MHz),\n        # but the extra frequencies should be killed by the front-end filter\n        super().setup_antenna(response_data=response_data,\n                              position=self.position,\n                              center_frequency=center_frequency,\n                              bandwidth=bandwidth,\n                              temperature=temperature,\n                              resistance=resistance,\n                              orientation=orientation,\n                              efficiency=efficiency,\n                              noisy=noisy,\n                              unique_noise_waveforms=unique_noise_waveforms,\n                              **kwargs)\n\n    # Tunnel diode response functions pulled from arasim\n    _td_args = {\n        'down1': (-0.8, 15e-9, 2.3e-9, 0),\n        'down2': (-0.2, 15e-9, 4e-9, 0),\n        'up': (1, 18e-9, 7e-9, 1e9)\n    }\n    # Set td_args['up'][0] based on the other args, like in arasim\n    _td_args['up'] = (-np.sqrt(2*np.pi) *\n                      (_td_args['down1'][0]*_td_args['down1'][2] +\n                       _td_args['down2'][0]*_td_args['down2'][2]) /\n                      (2e18*_td_args['up'][2]**3),) + _td_args['up'][1:]\n\n    # Set \"down\" and \"up\" functions as in arasim\n    @classmethod\n    def _td_fdown1(cls, x):\n        return (cls._td_args['down1'][3] + cls._td_args['down1'][0] *\n                np.exp(-(x-cls._td_args['down1'][1])**2 /\n                       (2*cls._td_args['down1'][2]**2)))\n\n    @classmethod\n    def _td_fdown2(cls, x):\n        return (cls._td_args['down2'][3] + cls._td_args['down2'][0] *\n                np.exp(-(x-cls._td_args['down2'][1])**2 /\n                       (2*cls._td_args['down2'][2]**2)))\n\n    @classmethod\n    def _td_fup(cls, x):\n        return (cls._td_args['up'][0] *\n                (cls._td_args['up'][3] * (x-cls._td_args['up'][1]))**2 *\n                np.exp(-(x-cls._td_args['up'][1])/cls._td_args['up'][2]))\n\n    def tunnel_diode(self, signal):\n        \"\"\"\n        Calculate a signal as processed by the tunnel diode.\n\n        The given signal is convolved with the tunnel diode response as in\n        AraSim.\n\n        Parameters\n        ----------\n        signal : Signal\n            Signal to be processed by the tunnel diode.\n\n        Returns\n        -------\n        Signal\n            Signal output of the tunnel diode for the input `signal`.\n\n        Raises\n        ------\n        ValueError\n            If the input `signal` doesn't have a ``value_type`` of ``voltage``.\n\n        Notes\n        -----\n        The tunnel diode response is based on the response parameterized in\n        AraSim, as developed by ANITA [1]_.\n\n        References\n        ----------\n        .. [1] A. Connolly & R. Nichol, ANITA Note #411, \"A Power-Based Time\n            Domain Trigger Simulation.\"\n            https://elog.phys.hawaii.edu/elog/anita_notes/080827_041639/powertrigger.pdf\n\n        \"\"\"\n        if signal.value_type!=Signal.Type.voltage:\n            raise ValueError(\"Tunnel diode only accepts voltage signals\")\n        t_max = 1e-7\n        n_pts = int(t_max/signal.dt)\n        times = np.linspace(0, t_max, n_pts+1)\n        diode_resp = self._td_fdown1(times) + self._td_fdown2(times)\n        t_slice = times>self._td_args['up'][1]\n        diode_resp[t_slice] += self._td_fup(times[t_slice])\n        conv = scipy.signal.convolve(signal.values**2 / self.antenna.resistance,\n                                     diode_resp, mode='full')\n        # Signal class will automatically only take the first part of conv,\n        # which is what we want.\n        # conv multiplied by dt so that the amplitude stays constant for\n        # varying dts (determined empirically, see ARZAskaryanSignal comments)\n        output = Signal(signal.times, conv*signal.dt,\n                        value_type=Signal.Type.power)\n        return output\n\n    def interpolate_filter(self, frequencies):\n        \"\"\"\n        Generate interpolated filter values for given frequencies.\n\n        Calculate the interpolated values of the antenna system's filter gain\n        data for some frequencies.\n\n        Parameters\n        ----------\n        frequencies : array_like\n            1D array of frequencies (Hz) at which to calculate gains.\n\n        Returns\n        -------\n        array_like\n            Complex filter gain in voltage for the given `frequencies`.\n\n        \"\"\"\n        return complex_interp(\n            x=frequencies, xp=self._filter_freqs, fp=self._filter_response,\n            method='euler', outer=0\n        )\n\n    def front_end(self, signal):\n        \"\"\"\n        Apply front-end processes to a signal and return the output.\n\n        The front-end consists of the full ARA electronics chain (including\n        amplification) and signal clipping.\n\n        Parameters\n        ----------\n        signal : Signal\n            ``Signal`` object on which to apply the front-end processes.\n\n        Returns\n        -------\n        Signal\n            Signal processed by the antenna front end.\n\n        \"\"\"\n        base_signal = signal.copy()\n        base_signal.filter_frequencies(self.interpolate_filter,\n                                       force_real=True)\n        # Apply sqrt(2) for 3dB splitter for TURF, SURF\n        base_signal *= self.amplification / np.sqrt(2)\n        clip_values = lambda times: np.clip(\n            base_signal.with_times(times).values,\n            a_min=-self.amplifier_clipping,\n            a_max=self.amplifier_clipping\n        )\n        return FunctionSignal(signal.times, clip_values,\n                              value_type=signal.value_type)\n\n    def trigger(self, signal):\n        \"\"\"\n        Check if the antenna system triggers on a given signal.\n\n        Passes the signal through the tunnel diode. Then compares the maximum\n        and minimum values to a tunnel diode noise signal. Triggers if one of\n        the maximum or minimum values exceed the noise mean +/- the noise rms\n        times the power threshold.\n\n        Parameters\n        ----------\n        signal : Signal\n            ``Signal`` object on which to test the trigger condition.\n\n        Returns\n        -------\n        boolean\n            Whether or not the antenna triggers on `signal`.\n\n        \"\"\"\n        if self._power_mean is None or self._power_std is None:\n            # Prepare for antenna trigger by finding mean and standard\n            # deviation of the full noise waveform convolved with the tunnel\n            # diode response\n            if len(self.antenna.signals)>0:\n                times = self.antenna.signals[0].times\n            else:\n                times = signal.times\n            n = len(times)\n            dt = times[1]-times[0]\n            duration = times[-1]-times[0] + dt\n            full_times = np.linspace(0, duration*self.antenna.unique_noises,\n                                     n*self.antenna.unique_noises)\n            if self.antenna._noise_master is None:\n                # Make sure the noise_master has the appropriate length\n                # (automatically gets set to N*len(times) the first time it is\n                # called, so make sure the first `times` is not the expanded\n                # array but the single-signal array)\n                self.antenna.make_noise(times)\n            long_noise = self.antenna.make_noise(full_times)\n            power_noise = self.tunnel_diode(self.front_end(long_noise))\n            self._power_mean = np.mean(power_noise.values)\n            self._power_std = np.std(power_noise.values)\n\n        power_signal = self.tunnel_diode(signal)\n        # Use the absolute value of the power_threshold value so that the value\n        # can be specified as positive or negative (compatible with AraSim\n        # which only works with negative values, resulting in some confusion)\n        low_trigger = (self._power_mean -\n                       self._power_std*np.abs(self.power_threshold))\n        return np.min(power_signal.values)<low_trigger\n\n    # Redefine receive method to use force_real as True by default\n    def receive(self, signal, direction=None, polarization=None,\n                force_real=True):\n        \"\"\"\n        Process and store one or more incoming (polarized) signals.\n\n        Processes the incoming signal(s) according to the ``apply_response``\n        method, then stores the total processed signal to the signals list. If\n        more than one signal is given, they should be logically connected as\n        separately polarized portions of the same signal.\n\n        Parameters\n        ----------\n        signal : Signal or array_like\n            Incoming ``Signal`` object(s) to process and store. May be separate\n            polarization representations, but therefore should have the same\n            times.\n        direction : array_like, optional\n            Vector denoting the direction of travel of the signal(s) as they\n            reach the antenna (in the global coordinate frame). If ``None`` no\n            directional gain will be applied.\n        polarization : array_like, optional\n            Vector(s) denoting the signal's polarization direction (in the\n            global coordinate frame). Number of vectors should match the number\n            of elements in `signal` argument. If ``None`` no polarization gain\n            will be applied.\n        force_real : boolean, optional\n            Whether or not the frequency response should be redefined in the\n            negative-frequency domain to keep the values of the filtered signal\n            real.\n\n        Raises\n        ------\n        ValueError\n            If the number of polarizations does not match the number of signals.\n            Or if the signals do not have the same `times` array.\n\n        See Also\n        --------\n        pyrex.Signal : Base class for time-domain signals.\n\n        \"\"\"\n        super().receive(signal=signal, direction=direction,\n                        polarization=polarization,\n                        force_real=force_real)\n\n\n\nclass HpolAntenna(ARAAntennaSystem):\n    \"\"\"\n    ARA Hpol (\"quad-slot\") antenna system with front-end processing.\n\n    Applies as the front end a filter representing the full ARA electronics\n    chain (including amplification) and signal clipping. Additionally provides\n    a method for passing a signal through the tunnel diode.\n\n    Parameters\n    ----------\n    name : str\n        Name of the antenna.\n    position : array_like\n        Vector position of the antenna.\n    power_threshold : float\n        Power threshold for trigger condition. Antenna triggers if a signal\n        passed through the tunnel diode exceeds this threshold times the noise\n        RMS of the tunnel diode.\n    amplification : float, optional\n        Amplification to be applied to the signal pre-clipping. Note that the\n        usual ARA electronics amplification is already applied without this.\n    amplifier_clipping : float, optional\n        Voltage (V) above which the amplified signal is clipped (in positive\n        and negative values).\n    noisy : boolean, optional\n        Whether or not the antenna should add noise to incoming signals.\n    unique_noise_waveforms : int, optional\n        The number of expected noise waveforms needed for each received signal\n        to have its own noise.\n\n    Attributes\n    ----------\n    antenna : Antenna\n        ``Antenna`` object extended by the front end.\n    name : str\n        Name of the antenna.\n    position : array_like\n        Vector position of the antenna.\n    power_threshold : float\n        Power threshold for trigger condition. Antenna triggers if a signal\n        passed through the tunnel diode exceeds this threshold times the noise\n        RMS of the tunnel diode.\n    amplification : float\n        Amplification to be applied to the signal pre-clipping. Note that the\n        usual ARA electronics amplification is already applied without this.\n    amplifier_clipping : float\n        Voltage (V) above which the amplified signal is clipped (in positive\n        and negative values).\n    is_hit\n    is_hit_mc_truth\n    signals\n    waveforms\n    all_waveforms\n\n    See Also\n    --------\n    ARAAntennaSystem : Antenna system extending base ARA antenna with front-end\n                       processing.\n\n    \"\"\"\n    def __init__(self, name, position, power_threshold,\n                 amplification=1, amplifier_clipping=1, noisy=True,\n                 unique_noise_waveforms=10):\n        super().__init__(response_data=HPOL_RESPONSE_DATA,\n                         name=name, position=position,\n                         power_threshold=power_threshold,\n                         orientation=(0,0,1),\n                         amplification=amplification,\n                         amplifier_clipping=amplifier_clipping,\n                         noisy=noisy,\n                         unique_noise_waveforms=unique_noise_waveforms)\n\n\nclass VpolAntenna(ARAAntennaSystem):\n    \"\"\"\n    ARA Vpol (\"bicone\" or \"birdcage\") antenna system with front-end processing.\n\n    Applies as the front end a filter representing the full ARA electronics\n    chain (including amplification) and signal clipping. Additionally provides\n    a method for passing a signal through the tunnel diode.\n\n    Parameters\n    ----------\n    name : str\n        Name of the antenna.\n    position : array_like\n        Vector position of the antenna.\n    power_threshold : float\n        Power threshold for trigger condition. Antenna triggers if a signal\n        passed through the tunnel diode exceeds this threshold times the noise\n        RMS of the tunnel diode.\n    amplification : float, optional\n        Amplification to be applied to the signal pre-clipping. Note that the\n        usual ARA electronics amplification is already applied without this.\n    amplifier_clipping : float, optional\n        Voltage (V) above which the amplified signal is clipped (in positive\n        and negative values).\n    noisy : boolean, optional\n        Whether or not the antenna should add noise to incoming signals.\n    unique_noise_waveforms : int, optional\n        The number of expected noise waveforms needed for each received signal\n        to have its own noise.\n\n    Attributes\n    ----------\n    antenna : Antenna\n        ``Antenna`` object extended by the front end.\n    name : str\n        Name of the antenna.\n    position : array_like\n        Vector position of the antenna.\n    power_threshold : float\n        Power threshold for trigger condition. Antenna triggers if a signal\n        passed through the tunnel diode exceeds this threshold times the noise\n        RMS of the tunnel diode.\n    amplification : float\n        Amplification to be applied to the signal pre-clipping. Note that the\n        usual ARA electronics amplification is already applied without this.\n    amplifier_clipping : float\n        Voltage (V) above which the amplified signal is clipped (in positive\n        and negative values).\n    is_hit\n    is_hit_mc_truth\n    signals\n    waveforms\n    all_waveforms\n\n    See Also\n    --------\n    ARAAntennaSystem : Antenna system extending base ARA antenna with front-end\n                       processing.\n\n    \"\"\"\n    def __init__(self, name, position, power_threshold,\n                 amplification=1, amplifier_clipping=1, noisy=True,\n                 unique_noise_waveforms=10):\n        super().__init__(response_data=VPOL_RESPONSE_DATA,\n                         name=name, position=position,\n                         power_threshold=power_threshold,\n                         orientation=(0,0,1),\n                         amplification=amplification,\n                         amplifier_clipping=amplifier_clipping,\n                         noisy=noisy,\n                         unique_noise_waveforms=unique_noise_waveforms)\n", "meta": {"hexsha": "051520ea767227e80acef3462dd06207ec4a7320", "size": 46571, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyrex/custom/ara/antenna.py", "max_stars_repo_name": "abigailbishop/pyrex", "max_stars_repo_head_hexsha": "10ba2e9f4c8820f4fcf5f00bd866927dacb0b2b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-06-19T16:01:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-21T20:02:53.000Z", "max_issues_repo_path": "pyrex/custom/ara/antenna.py", "max_issues_repo_name": "bhokansonfasig/pyrex", "max_issues_repo_head_hexsha": "8b2abc954f2cf4945424042f33847b783c72dcfa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-01-19T14:52:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T17:20:07.000Z", "max_forks_repo_path": "pyrex/custom/ara/antenna.py", "max_forks_repo_name": "abigailbishop/pyrex", "max_forks_repo_head_hexsha": "10ba2e9f4c8820f4fcf5f00bd866927dacb0b2b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-01-19T14:49:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-21T12:34:59.000Z", "avg_line_length": 39.9065981148, "max_line_length": 88, "alphanum_fraction": 0.6212664534, "include": true, "reason": "import numpy,import scipy", "num_tokens": 9732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.34864514886966624, "lm_q1q2_score": 0.19867636248606282}}
{"text": "# connected component analysis of segmentation compared to ground truth\nimport numpy as np\nfrom scipy import ndimage\n\n_thresh = 0.50\n_smooth = 1\n\n_LESION_UNC_VA = {\n    'bald': {'ymin': -304332.435036, 'ymax': -165.66824439, 'xmin': -287025.719183, 'xmax': -60.0155142638},\n    'ent': {'ymin': -264211.01785, 'ymax': -120.603669105, 'xmin': -246545.542156, 'xmax': -42.3070650557},\n    'prdvar': {'ymin': -77261.4, 'ymax': -63.0317, 'xmin': -73166.6, 'xmax': -32.3993},\n    'varmcs': {'ymin': -357833.52626, 'ymax': -254.615228264, 'xmin': -340539.075182, 'xmax': -92.6999732885}}\n\n\ndef remove_tiny_les(lesion_image, nvox=2):\n    labels, nles = ndimage.label(lesion_image)\n    for i in range(1, nles + 1):\n        nb_vox = np.sum(lesion_image[labels == i])\n        if nb_vox <= nvox:\n            lesion_image[labels == i] = 0\n    return lesion_image\n\n\ndef global_dice(h, t):\n    h = h.flatten()\n    t = t.flatten()\n    intersection = np.sum(h * t)\n    union = np.sum(h) + np.sum(t)\n    dice = (2. * intersection + _smooth) / (union + _smooth)\n    return dice\n\n\ndef get_lesion_bin(nvox):\n    if 3 <= nvox <= 10:\n        return 'small'\n    elif 11 <= nvox <= 50:\n        return 'med'\n    elif nvox >= 51:\n        return 'large'\n    else:\n        return \"small\"\n\n\ndef cca_img_bin(h, t, u, uth, metric):\n    t = remove_tiny_les(t, nvox=2)\n    h0 = h.copy()\n    h = ndimage.binary_dilation(h, structure=ndimage.generate_binary_structure(3, 2))\n    t_unc_labels = get_unc_labels(t, u, metric, 'y')\n    h_unc_labels = get_unc_labels(h0, u, metric, 'x')\n\n    labels = {}\n    nles = {}\n    labels['h'], nles['h'] = ndimage.label(h)\n    labels['t'], nles['t'] = ndimage.label(t)\n    found_h = np.ones(nles['h'], np.int16)\n    ntp = {'all': 0, 'small': 0, 'med': 0, 'large': 0}\n    nfp = {'all': 0, 'small': 0, 'med': 0, 'large': 0}\n    nfn = {'all': 0, 'small': 0, 'med': 0, 'large': 0}\n    nb_les = {'all': 0, 'small': 0, 'med': 0, 'large': 0}\n    nles_gt = {'all': nles['t'], 'small': 0, 'med': 0, 'large': 0}\n    for i in range(1, nles['t'] + 1):\n        t_unc = np.max(t_unc_labels[labels['t'] == i])\n        lesion_size = np.sum(t[labels['t'] == i])\n        nles_gt[get_lesion_bin(lesion_size)] += 1\n        if t_unc < uth:\n            # list of detected lesions in this area\n            h_lesions = np.unique(labels['h'][labels['t'] == i])\n            # all the voxels in this area contribute to detecting the lesion\n            nb_overlap = h[labels['t'] == i].sum()\n            nb_les[get_lesion_bin(lesion_size)] += 1\n            if nb_overlap >= 3 or nb_overlap >= 0.5 * lesion_size:\n                ntp[get_lesion_bin(lesion_size)] += 1\n                for h_lesion in h_lesions:\n                    if h_lesion != 0:\n                        found_h[h_lesion - 1] = 0\n            else:\n                nfn[get_lesion_bin(lesion_size)] += 1\n\n    for i in range(1, nles['h'] + 1):\n        if found_h[i - 1] == 1:\n            h_unc = np.max(h_unc_labels[labels['h'] == i])\n            if h_unc < uth:\n                nb_vox = np.sum(h0[labels['h'] == i])\n                nfp[get_lesion_bin(nb_vox)] += 1\n\n    nb_les['all'] = nb_les['small'] + nb_les['med'] + nb_les['large']\n    ntp['all'] = ntp['small'] + ntp['med'] + ntp['large']\n    nfp['all'] = nfp['small'] + nfp['med'] + nfp['large']\n    nfn['all'] = nfn['small'] + nfn['med'] + nfn['large']\n\n    tpr = {}\n    fdr = {}\n    for s in ntp.keys():\n        # tpr (sensitivity)\n        if nb_les[s] != 0:\n            tpr[s] = ntp[s] / nb_les[s]\n        elif nb_les[s] == 0 and ntp[s] == 0:\n            tpr[s] = 1\n        else:\n            tpr[s] = 0\n        # ppv (1-fdr)\n        if ntp[s] + nfp[s] != 0:\n            ppv = ntp[s] / (ntp[s] + nfp[s])\n        else:\n            ppv = 1\n        fdr[s] = 1 - ppv\n\n    return {'ntp': ntp, 'nfp': nfp, 'nfn': nfn, 'fdr': fdr, 'tpr': tpr, 'nles': nb_les, 'nles_gt': nles_gt}\n\n\ndef cca_img(h, t, u, uth, metric):\n    t = remove_tiny_les(t, nvox=2)\n    h0 = h.copy()\n    h = ndimage.binary_dilation(h, structure=ndimage.generate_binary_structure(3, 2))\n    t_unc_labels = get_unc_labels(t, u, metric, 'y')\n    h_unc_labels = get_unc_labels(h0, u, metric, 'x')\n\n    labels = {}\n    nles = {}\n    labels['h'], nles['h'] = ndimage.label(h)\n    labels['t'], nles['t'] = ndimage.label(t)\n    found_h = np.ones(nles['h'], np.int16)\n    ntp = {'all': 0, 'small': 0, 'med': 0, 'large': 0}\n    nfp = {'all': 0, 'small': 0, 'med': 0, 'large': 0}\n    nfn = {'all': 0, 'small': 0, 'med': 0, 'large': 0}\n    nb_les = {'all': 0, 'small': 0, 'med': 0, 'large': 0}\n    nles_gt = {'all': nles['t'], 'small': 0, 'med': 0, 'large': 0}\n    for i in range(1, nles['t'] + 1):\n        t_unc = np.max(t_unc_labels[labels['t'] == i])\n        lesion_size = np.sum(t[labels['t'] == i])\n        nles_gt[get_lesion_bin(lesion_size)] += 1\n        if t_unc < uth:\n            # list of detected lesions in this area\n            h_lesions = np.unique(labels['h'][labels['t'] == i])\n            # all the voxels in this area contribute to detecting the lesion\n            nb_overlap = h[labels['t'] == i].sum()\n            nb_les[get_lesion_bin(lesion_size)] += 1\n            if nb_overlap >= 3 or nb_overlap >= 0.5 * lesion_size:\n                ntp[get_lesion_bin(lesion_size)] += 1\n                for h_lesion in h_lesions:\n                    if h_lesion != 0:\n                        found_h[h_lesion - 1] = 0\n            else:\n                nfn[get_lesion_bin(lesion_size)] += 1\n\n    for i in range(1, nles['h'] + 1):\n        if found_h[i - 1] == 1:\n            h_unc = np.max(h_unc_labels[labels['h'] == i])\n            if h_unc < uth:\n                nb_vox = np.sum(h0[labels['h'] == i])\n                nfp[get_lesion_bin(nb_vox)] += 1\n\n    nb_les['all'] = nb_les['small'] + nb_les['med'] + nb_les['large']\n    ntp['all'] = ntp['small'] + ntp['med'] + ntp['large']\n    nfp['all'] = nfp['small'] + nfp['med'] + nfp['large']\n    nfn['all'] = nfn['small'] + nfn['med'] + nfn['large']\n\n    tpr = {}\n    fdr = {}\n    for s in ntp.keys():\n        # tpr (sensitivity)\n        if nb_les[s] != 0:\n            tpr[s] = ntp[s] / nb_les[s]\n        elif nb_les[s] == 0 and ntp[s] == 0:\n            tpr[s] = 1\n        else:\n            tpr[s] = 0\n        # ppv (1-fdr)\n        if ntp[s] + nfp[s] != 0:\n            ppv = ntp[s] / (ntp[s] + nfp[s])\n        else:\n            ppv = 1\n        fdr[s] = 1 - ppv\n\n    return {'ntp': ntp, 'nfp': nfp, 'nfn': nfn, 'fdr': fdr, 'tpr': tpr, 'nles': nb_les, 'nles_gt': nles_gt}\n\n\ndef cca_img_no_unc(bbox, t, th):\n    \"\"\"\n    Connected component analysis of between prediction `h` and ground truth `t` across lesion bin sizes.\n    :param h: network output on range [0,1], shape=(NxMxO)\n    :type h: float16, float32, float64\n    :param t: ground truth labels, shape=(NxMxO)\n    :type t: int16\n    :param th: threshold to binarize prediction `h`\n    :type th: float16, float32, float64\n    :return: dict\n    \"\"\"\n    h[h >= th] = 1\n    h[h < th] = 0\n    h = h.astype(np.int16)\n\n    t = remove_tiny_les(t, nvox=2)\n    h = ndimage.binary_dilation(h, structure=ndimage.generate_binary_structure(3, 2))\n\n    labels = {}\n    nles = {}\n    labels['h'], nles['h'] = ndimage.label(h)\n    labels['t'], nles['t'] = ndimage.label(t)\n    found_h = np.ones(nles['h'], np.int16)\n    ntp = {'all': 0, 'small': 0, 'med': 0, 'large': 0}\n    nfp = {'all': 0, 'small': 0, 'med': 0, 'large': 0}\n    nfn = {'all': 0, 'small': 0, 'med': 0, 'large': 0}\n    nb_les = {'all': 0, 'small': 0, 'med': 0, 'large': 0}\n    nles_gt = {'all': nles['t'], 'small': 0, 'med': 0, 'large': 0}\n    for i in range(1, nles['t'] + 1):\n        lesion_size = np.sum(t[labels['t'] == i])\n        nles_gt[get_lesion_bin(lesion_size)] += 1\n        # list of detected lesions in this area\n        h_lesions = np.unique(labels['h'][labels['t'] == i])\n        # all the voxels in this area contribute to detecting the lesion\n        nb_overlap = h[labels['t'] == i].sum()\n        nb_les[get_lesion_bin(lesion_size)] += 1\n        if nb_overlap >= 3 or nb_overlap >= 0.5 * lesion_size:\n            ntp[get_lesion_bin(lesion_size)] += 1\n            for h_lesion in h_lesions:\n                if h_lesion != 0:\n                    found_h[h_lesion - 1] = 0\n        else:\n            nfn[get_lesion_bin(lesion_size)] += 1\n\n    for i in range(1, nles['h'] + 1):\n        if found_h[i - 1] == 1:\n            nb_vox = np.sum(h[labels['h'] == i])\n            nfp[get_lesion_bin(nb_vox)] += 1\n\n    nb_les['all'] = nb_les['small'] + nb_les['med'] + nb_les['large']\n    ntp['all'] = ntp['small'] + ntp['med'] + ntp['large']\n    nfp['all'] = nfp['small'] + nfp['med'] + nfp['large']\n    nfn['all'] = nfn['small'] + nfn['med'] + nfn['large']\n\n    tpr = {}\n    fdr = {}\n    for s in ntp.keys():\n        # tpr (sensitivity)\n        if nb_les[s] != 0:\n            tpr[s] = ntp[s] / nb_les[s]\n        elif nb_les[s] == 0 and ntp[s] == 0:\n            tpr[s] = 1\n        else:\n            tpr[s] = 0\n        # ppv (1-fdr)\n        if ntp[s] + nfp[s] != 0:\n            ppv = ntp[s] / (ntp[s] + nfp[s])\n        else:\n            ppv = 1\n        fdr[s] = 1 - ppv\n\n    return {'ntp': ntp, 'nfp': nfp, 'nfn': nfn, 'fdr': fdr, 'tpr': tpr, 'nles': nb_les, 'nles_gt': nles_gt}\n\n\ndef get_unc_labels(x, unc, metric, xy):\n    x_big = ndimage.binary_dilation(x, structure=ndimage.generate_binary_structure(3, 2))\n    labels, nles = ndimage.label(x_big)\n    unc_labels = np.zeros_like(unc)\n    for i in range(1, nles + 1):\n        unc_labels[labels == i] = np.sum(np.log(unc[labels == i] + 1e-5))\n\n    unc_labels[unc_labels != 0] = (unc_labels[unc_labels != 0] - _LESION_UNC_VA[metric][xy + 'min']) / (\n        _LESION_UNC_VA[metric][xy + 'max'] - _LESION_UNC_VA[metric][xy + 'min'])\n    return unc_labels\n\n    \n    \ndef paint_cca_img(h, t):\n    TP_COLOUR=1\n    FP_COLOUR=2\n    FN_COLOUR=3\n\n    h_paint = h.copy() # this should be the un-connected labels\n\n    t = remove_tiny_les(t)\n\n    # get the 18 neighbourhood of the hypothesis\n    neighbourhood18 = ndimage.generate_binary_structure(3, 2)\n    h = ndimage.binary_dilation(h, structure=neighbourhood18)\n\n    labels = {}\n    nles = {}\n    labels['h'], nles['h'] = ndimage.label(h)\n    labels['t'], nles['t'] = ndimage.label(t)\n    ntp = 0; nfp = 0; nfn = 0\n    found_h = np.ones(nles['h'], np.int16)\n\n    for i in range(1,nles['t']+1):\n        got_les = False\n        h_lesions = np.unique(labels['h'][labels['t']==i])\n        for h_lesion in h_lesions:\n            if h_lesion != 0:\n                nb_overlap = h[labels['h']==h_lesion].sum()\n                if nb_overlap >= 3 or nb_overlap >= 0.5*np.sum(t[labels['t']==i]):\n                    # this is a a true positive\n                    h_paint[labels['h']==h_lesion] *= TP_COLOUR\n                    found_h[h_lesion-1] = 0\n                    got_les = True\n        # if we didn't get it --> false negative\n        if not got_les:\n            h_paint[labels['t']==i] = FN_COLOUR\n\n    # any remaining that we found are false positivse\n    for i, fp in enumerate(found_h):\n        if fp:\n            h_paint[labels['h']==(i+1)] *= FP_COLOUR\n\n    labels_hpaint, nles = ndimage.label(h_paint)\n    for i in range(1,nles+1):\n        nb_vox = np.size(labels_hpaint[labels_hpaint==i])\n        if nb_vox < 3:\n            h_paint[labels_hpaint==i] = 0\n    return h_paint    \n\n\ndef ohe(x):\n    ohe = np.zeros_like(x)\n    ohe = np.repeat(np.expand_dims(x,-1),3,-1)\n    ohe[:,:,:,0][x!=2] = 0 # red --> FP(2)\n    ohe[:,:,:,1][x!=1] = 0 # gre --> TP(1)\n    ohe[:,:,:,2][x!=3] = 0 # blu --> FN(3)\n    ohe[ohe>0]=1\n    return ohe\n    \n# def cca_img(h, t, thresh, read_img=True):\n#     \"\"\"\n#     1. binarize segmentation 'h' based on sigmoid 0.5 thresh\n#     2. generate blob (18 neighbourhood) of the 'h'\n#     3. remove tiny lesions in truth 't' (<=2 voxels in size)\n#     4. count true positives:\n#         for lesion in t:\n#             overlap  = _get_overlap(h, t)\n#             if overap >= voxels:\n#                 tp ++\n#             else if ( overlap > 0.5 * size(lesion))\n#                 tp ++\n#             else:\n#                 fn ++\n\n#     5. count false positives:\n#         for lesion in h:\n#             overlap  = _get_overlap(h, t)\n#             if overlap == 0:\n#                 fp ++\n#     \"\"\"\n#     if read_img:\n#         h, header = nrrd.read(h)\n#         t, header = nrrd.read(t)\n\n#     h[h < thresh] = 0\n#     h[h >= thresh] = 1\n#     t = t.astype(np.int16)\n#     h = h.astype(np.int16)\n\n#     t = remove_tiny_les(t)\n\n#     # get the 18 neighbourhood of the hypothesis\n#     neighbourhood18 = ndimage.generate_binary_structure(3, 2)\n#     h = ndimage.binary_dilation(h, structure=neighbourhood18)\n\n#     labels = {}\n#     nles = {}\n#     labels['h'], nles['h'] = ndimage.label(h)\n#     labels['t'], nles['t'] = ndimage.label(t)\n\n#     ntp = 0; nfp = 0; nfn = 0\n#     found_h = np.ones(nles['h'], np.int16)\n\n#     for i in range(1,nles['t']):\n#         got_les = False\n#         h_lesions = np.unique(labels['h'][labels['t']==i])\n#         for h_lesion in h_lesions:\n#             if h_lesion != 0:\n#                 nb_overlap = np.size(labels['h']==h_lesion)\n#                 if nb_overlap >= 3 or nb_overlap >= 0.5*np.sum(t[labels['t']==i]):\n#                     got_les = True\n#                     found_h[h_lesion-1] = 0\n#         if got_les:\n#             ntp += 1\n#         else:\n#             nfn += 1\n\n#     nfp = np.sum(found_h)\n\n#     # tpr\n#     if nles['t']!= 0:\n#         tpr = ntp / nles['t']\n#     elif nles['t']==0 and ntp ==0:\n#         tpr = 1\n#     else:\n#         tpr = 0\n\n#     # ppv, fdr\n#     if ntp+nfp != 0:\n#         ppv = ntp / (ntp+nfp)\n#     else:\n#         ppv = 1\n\n#     # fdr\n#     # if ntp+nfp != 0:\n#     #     fdr = nfp / (ntp+nfp)\n#     # else:\n#     #     fdr = 0        \n\n#     # f1 score\n#     # denom = (2*ntp + nfp + nfn)\n#     # if denom != 0:\n#     #     f1_score = 2*ntp / denom\n#     # else:\n#     #     f1_score = 1\n\n#     return {'ntp':ntp, 'nfp':nfp, 'nfn':nfn, 'ppv':ppv, 'tpr':tpr, 'fdr':1-ppv}\n", "meta": {"hexsha": "c1cc08af778309f1185821b0ecfe91b1a0bd2f91", "size": 13980, "ext": "py", "lang": "Python", "max_stars_repo_path": "tools/cca.py", "max_stars_repo_name": "thomaschristinck/detection_net", "max_stars_repo_head_hexsha": "c199abf9bd53b115a67e9e2c8da3da9894789f3e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-02-15T17:15:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-26T06:11:48.000Z", "max_issues_repo_path": "tools/cca.py", "max_issues_repo_name": "thomaschristinck/detection_net", "max_issues_repo_head_hexsha": "c199abf9bd53b115a67e9e2c8da3da9894789f3e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-03-24T16:11:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T23:30:39.000Z", "max_forks_repo_path": "tools/cca.py", "max_forks_repo_name": "thomaschristinck/lesion-detection-net", "max_forks_repo_head_hexsha": "c199abf9bd53b115a67e9e2c8da3da9894789f3e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0975609756, "max_line_length": 110, "alphanum_fraction": 0.5108726753, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.19867635986651594}}
{"text": "#\n# Copyright 2020 Antoine Sanner\n#           2020 Lars Pastewka\n#\n# ### MIT license\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n\n\"\"\"\nDefines the interface for Adhesion systems\n\"\"\"\n\nimport numpy as np\n\nimport Adhesion\nimport ContactMechanics\nimport SurfaceTopography\nfrom ContactMechanics.Tools import compare_containers\nfrom ContactMechanics.Systems import IncompatibleResolutionError, SystemBase\n\n\nclass SmoothContactSystem(SystemBase):\n    \"\"\"\n    For smooth contact mechanics (i.e. the ones for which optimization is only\n    kinda-hell\n    \"\"\"\n\n    def __init__(self, substrate, interaction, surface):\n        \"\"\" Represents a contact problem\n        Parameters\n        ----------\n        substrate: An instance of HalfSpace.\n            Defines the solid mechanics in the substrate\n        interaction: Adhesion.Interactions.SoftWall\n            Defines the contact formulation.\n            If this computes interaction energies, forces etc,\n            these are supposed to be expressed per unit area in whatever units\n             you use. The conversion is performed by the system\n        surface: SurfaceTopography.Topography\n            Defines the profile.\n        \"\"\"\n        if surface.has_undefined_data:\n            raise ValueError(\"The topography you provided contains undefined \"\n                             \"data\")\n        super().__init__(substrate=substrate, surface=surface)\n        self.interaction = interaction\n        if not compare_containers(surface.nb_grid_pts, substrate.nb_grid_pts):\n            raise IncompatibleResolutionError(\n                (\"the substrate ({}) and the surface ({}) have incompatible \"\n                 \"nb_grid_ptss.\").format(\n                    substrate.nb_grid_pts, surface.nb_grid_pts))  # nopep8\n        self.dim = len(self.substrate.nb_grid_pts)\n        self.energy = None\n        self.force = None\n        self.force_h = None\n        self.interaction_energy = None\n        self.interaction_force = None\n        self.heights_k = None\n        self.engine = self.substrate.fftengine\n\n        if hasattr(substrate.fftengine, \"register_halfcomplex_field\") and self.engine.communicator.size == 1:\n            # avoids the initialization to fail if we use an fftengine without these hcffts implemnented\n            # preconditionning is not parallelized yet, this we have no parallelized wrapper for hcfft in muFFT yet\n            self.real_buffer = self.engine.register_halfcomplex_field(\"hc-real-space\", 1)\n            self.fourier_buffer = self.engine.register_halfcomplex_field(\"hc-fourier-space\", 1)\n\n            self.stiffness_k = self._compute_stiffness_k()\n\n    @property\n    def nb_grid_pts(self):\n        return self.surface.nb_grid_pts\n\n    @staticmethod\n    def handles(substrate_type, interaction_type, surface_type, comm):\n        is_ok = True\n        # any periodic type of substrate formulation should do\n        is_ok &= issubclass(substrate_type,\n                            ContactMechanics.Substrate)\n\n        # only soft interactions allowed\n        is_ok &= issubclass(interaction_type,\n                            Adhesion.SoftWall)\n\n        # any surface should do\n        is_ok &= issubclass(surface_type,\n                            SurfaceTopography.UniformTopographyInterface)\n        return is_ok\n\n    def compute_repulsive_force(self):\n        \"computes and returns the sum of all repulsive forces\"\n        return self.reduction.sum(np.where(\n            self.interaction_force > 0, self.interaction_force, 0\n        ))\n\n    def compute_attractive_force(self):\n        \"computes and returns the sum of all attractive forces\"\n        return self.reduction.sum(np.where(\n            self.interaction_force < 0, self.interaction_force, 0\n        ))\n\n    def _compute_stiffness_k(self):\n        \"\"\"\n        computes and returns the wavevectors q that exist for the surfaces\n        physical_sizes and nb_grid_pts as one vector of components per\n        dimension\n        \"\"\"\n\n        vectors = []\n        q = []\n        nb_dims = len(self.substrate.nb_grid_pts)\n        # if nb_dims == 1:\n        #     nb_grid_pts = [self.substrate.nb_grid_pts]\n        #     physical_sizes = [self.substrate.physical_sizes]\n        for dim in range(nb_dims):\n            vectors.append(2 * np.pi * np.fft.fftfreq(\n                self.substrate.nb_grid_pts[dim],\n                self.substrate.physical_sizes[dim] /\n                self.substrate.nb_grid_pts[dim]))\n        if nb_dims == 1:\n            q = vectors[0]\n            q[0] = q[1]\n        elif nb_dims == 2:\n            qx = vectors[0]\n            qy = vectors[1]\n            q = np.sqrt(\n                (qx * qx).reshape((-1, 1)) + (qy * qy).reshape((1, -1)))\n            q[0, 0] = (q[0, 1] + q[1, 0]) / 2\n\n        return 0.5 * self.substrate.contact_modulus * abs(q)\n\n    def compute_normal_force(self):\n        \"computes and returns the sum of all forces\"\n        return self.reduction.sum(self.interaction_force)\n\n    def compute_repulsive_contact_area(self):\n        \"computes and returns the area where contact pressure is repulsive\"\n        return self.compute_nb_repulsive_pts() * self.area_per_pt\n\n    def compute_attractive_contact_area(self):\n        \"computes and returns the are where contact pressure is attractive\"\n        return self.compute_nb_attractive_pts() * self.area_per_pt\n\n    def compute_nb_contact_pts(self):\n        \"\"\"\n        compute and return the number of contact points. Note that this is of\n        no physical interest, as it is a purely numerical artefact\n        \"\"\"\n        return self.reduction.sum(\n            np.where(self.interaction_force != 0., 1., 0.))\n\n    def compute_nb_repulsive_pts(self):\n        \"\"\"\n        compute and return the number of contact points under repulsive\n        pressure. Note that this is of no physical interest, as it is a\n        purely numerical artefact\n        \"\"\"\n        return self.reduction.sum(\n            np.where(self.interaction_force > 0., 1., 0.))\n\n    def compute_nb_attractive_pts(self):\n        \"\"\"\n        compute and return the number of contact points under attractive\n        pressure. Note that this is of no physical interest, as it is a\n        purely numerical artefact\n        \"\"\"\n        return self.reduction.sum(\n            np.where(self.interaction_force < 0., 1., 0.))\n\n    def compute_repulsive_coordinates(self):\n        \"\"\"\n        returns an array of all coordinates, where contact pressure is\n        repulsive. Useful for evaluating the number of contact islands etc.\n        \"\"\"\n        return np.argwhere(self.interaction_force > 0.)\n\n    def compute_attractive_coordinates(self):\n        \"\"\"\n        returns an array of all coordinates, where contact pressure is\n        attractive. Useful for evaluating the number of contact islands etc.\n        \"\"\"\n        return np.argwhere(self.interaction_force < 0.)\n\n    def compute_mean_gap(self):\n        \"\"\"\n        mean of the gap in the the physical domain (means excluding padding\n        region for the FreeFFTElasticHalfspace)\n        \"\"\"\n        return self.reduction.sum(self.gap) / np.prod(self.nb_grid_pts)\n\n    def logger_input(self):\n        \"\"\"\n\n        Returns\n        -------\n        headers: list of strings\n        values: list\n        \"\"\"\n        tot_nb_grid_pts = np.prod(self.nb_grid_pts)\n        rel_rep_area = self.compute_nb_repulsive_pts() / tot_nb_grid_pts\n        rel_att_area = self.compute_nb_attractive_pts() / tot_nb_grid_pts\n        # TODO: eventually put a flag to turn\n        #  reductions off since this is an additional communication.\n        return (['energy',\n                 'max. abs. grad.',\n                 'mean gap',\n                 'frac. rep. area',\n                 'frac. att. area',\n                 'frac. int. area', 'substrate force', 'interaction force'],\n                [self.energy,\n                 self.reduction.max(np.abs(self.force)),\n                 self.compute_mean_gap(),\n                 rel_rep_area,\n                 rel_att_area,\n                 rel_rep_area + rel_att_area,\n                 -self.reduction.sum(self.substrate.force),\n                 self.reduction.sum(self.interaction_force)])\n\n    def evaluate(self, disp, offset, pot=True, forces=False, logger=None):\n        \"\"\"\n        Compute the energies and forces in the system for a given displacement\n        field\n\n        Parameters:\n        -----------\n        disp: ndarray\n            displacement field, in the shape of\n            system.substrate.nb_subdomain_grid_pts\n        offset: float\n            determines indentation depth,\n            constant value added to the heights (system.topography)\n        pot: bool, optional\n            Wether to evaluate the energy, default True\n        forces: bool, optional\n            Wether to evaluate the forces, default False\n        logger: ContactMechanics.Tools.Logger\n            informations of current state of the system will be passed to\n            logger at every evaluation\n        \"\"\"\n        # attention: the substrate may have a higher nb_grid_pts than the gap\n        # and the interaction (e.g. FreeElasticHalfSpace)\n        self.gap = self.compute_gap(disp, offset)\n        interaction_energies, self.interaction_force, _ = \\\n            self.interaction.evaluate(self.gap,\n                                      potential=pot,\n                                      gradient=forces,\n                                      curvature=False)\n\n        self.interaction_energy = \\\n            self.reduction.sum(interaction_energies) * self.area_per_pt\n\n        self.substrate.compute(disp, pot, forces)\n        self.energy = (self.interaction_energy +\n                       self.substrate.energy\n                       if pot else None)\n        if forces:\n            self.interaction_force *= -self.area_per_pt\n            #                       ^ gradient to force per pixel\n            self.force = self.substrate.force.copy()\n            self.force[self.comp_slice] += \\\n                self.interaction_force\n        else:\n            self.force = None\n\n        if logger is not None:\n            logger.st(*self.logger_input())\n        return (self.energy, self.force)\n\n    def objective(self, offset, disp0=None, gradient=False, disp_scale=1.,\n                  logger=None):\n        r\"\"\"\n        This helper method exposes a scipy.optimize-friendly interface to the\n        evaluate() method. Use this for optimization purposes, it makes sure\n        that the shape of disp is maintained and lets you set the offset and\n        'forces' flag without using scipy's cumbersome argument passing\n        interface. Returns a function of only disp\n\n        Parameters:\n        -----------\n        disp0: ndarray\n            unused variable, present only for interface compatibility\n            with inheriting classes\n        offset: float\n            determines indentation depth,\n            constant value added to the heights (system.topography)\n        gradient: bool, optional\n            Wether to evaluate the gradient, default False\n        disp_scale : float, optional\n            (default 1.) allows to specify a scaling of the\n            dislacement before evaluation. This can be necessary when\n            using dumb minimizers with hardcoded convergence criteria\n            such as scipy's L-BFGS-B.\n        logger: ContactMechanics.Tools.Logger\n            informations of current state of the system will be passed to\n            logger at every evaluation\n\n        Returns:\n            function(disp)\n                Parameters:\n                disp: an ndarray of shape\n                      `system.substrate.nb_subdomain_grid_pts`\n                      displacements\n                Returns:\n                    energy or energy, gradient\n        \"\"\"\n        res = self.substrate.nb_subdomain_grid_pts\n        if gradient:\n            def fun(disp):\n                # pylint: disable=missing-docstring\n                try:\n                    self.evaluate(\n                        disp_scale * disp.reshape(res), offset, forces=True,\n                        logger=logger)\n                except ValueError as err:\n                    raise ValueError(\n                        \"{}: disp.shape: {}, res: {}\".format(\n                            err, disp.shape, res))\n                return (self.energy, -self.force.reshape(-1) * disp_scale)\n        else:\n            def fun(disp):\n                # pylint: disable=missing-docstring\n                return self.evaluate(\n                    disp_scale * disp.reshape(res), offset, forces=False,\n                    logger=logger)[0]\n\n        return fun\n\n    def primal_evaluate(self, disp, gap, pot=True, forces=False, logger=None):\n        \"\"\"\n        Compute the energies and forces in the system for a given\n        displacement and gap..\n\n        Parameters:\n        -----------\n        disp: ndarray\n            displacement field, in the shape of\n            system.substrate.nb_subdomain_grid_pts\n        gap: ndarray\n            gap , in the shape of\n            system.substrate.nb_subdomain_grid_pts\n        pot: bool, optional\n            Whether to evaluate the energy, default True\n        forces: bool, optional\n            Whether to evaluate the forces, default False\n        logger: ContactMechanics.Tools.Logger\n            information of current state of the system will be\n            passed to\n            logger at every evaluation\n        \"\"\"\n        # attention: the substrate may have a higher nb_grid_pts than the gap\n        # and the interaction (e.g. FreeElasticHalfSpace)\n\n        self.gap = gap\n        interaction_energies, self.interaction_force, _ = \\\n            self.interaction.evaluate(self.gap,\n                                      potential=pot,\n                                      gradient=forces,\n                                      curvature=False)\n\n        self.interaction_energy = \\\n            self.reduction.sum(interaction_energies) * self.area_per_pt\n\n        self.substrate.compute(disp, pot, forces)\n        self.energy = (self.interaction_energy +\n                       self.substrate.energy\n                       if pot else None)\n        if forces:\n            self.interaction_force *= -self.area_per_pt\n            #                       ^ gradient to force per pixel\n            self.force = self.substrate.force.copy()\n\n            self.force[self.comp_slice] += self.interaction_force\n        else:\n            self.force = None\n\n        if logger is not None:\n            logger.st(*self.logger_input())\n\n        return (self.energy, self.force)\n\n    def primal_objective(self, offset, disp0=None, gradient=False,\n                         logger=None):\n        r\"\"\"To solve the primal objective using gap as the variable.\n        Can be fed directly to standard solvers ex: scipy solvers etc\n        and returns the elastic energy and it's gradient (negative of\n        the forces) as a function of the gap.\n\n        Parameters\n        __________\n\n        gap : float\n              gap between the contact surfaces.\n        offset : float\n                constant value to add to the surface heights\n        pot : (default False)\n\n        gradient : (default True)\n\n        Returns\n        _______\n        energy : float\n                value of energy(scalar value).\n        force : float,array\n                value of force(array).\n\n        Notes\n        _____\n\n        Objective:\n\n        .. math ::\n\n            \\min_u f = \\frac{1}{2} u_i K_{ij} u_j + \\phi (u_{ij})\\\\\n            \\\\\n            \\nabla f = K_{ij} u_j + \\phi^{\\prime} \\text{    which is the force} \\\\\n\n        \"\"\"\n\n        res = self.substrate.nb_subdomain_grid_pts\n        if gradient:\n            def fun(gap):\n                disp = gap.reshape(res) + self.surface.heights() + offset\n                try:\n                    self.primal_evaluate(\n                        disp, gap.reshape(res), forces=True, logger=logger)\n                except ValueError as err:\n                    raise ValueError(\n                        \"{}: gap.shape: {}, res: {}\".format(\n                            err, gap.shape, res))\n                return (self.energy, -self.force.reshape(-1))\n        else:\n            def fun(gap):\n                disp = gap.reshape(res) + self.surface.heights() + offset\n                return self.primal_evaluate(\n                    disp, gap.reshape(res), forces=False, logger=logger)[0]\n\n        return fun\n\n    def primal_hessian_product(self, gap, des_dir):\n        \"\"\"Returns the hessian product of the primal_objective function.\n        \"\"\"\n        _, _, adh_curv = self.interaction.evaluate(gap, curvature=True)\n\n        hessp_val = - self.substrate.evaluate_force(\n            des_dir.reshape(self.substrate.nb_subdomain_grid_pts)\n        ).reshape(np.shape(des_dir)) \\\n            + adh_curv * des_dir * self.substrate.area_per_pt\n\n        return hessp_val.reshape(des_dir.shape)\n\n    def hessian_product_function(self, offset):\n        def hessp(disp, des_dir):\n            gap = disp.reshape(self.substrate.nb_subdomain_grid_pts\n                               )[self.comp_slice] \\\n                  - (self.surface.heights() + offset)\n            _, _, adh_curv = self.interaction.evaluate(gap, curvature=True)\n            hessp_val = - self.substrate.evaluate_force(\n                des_dir.reshape(self.substrate.nb_subdomain_grid_pts)\n            )\n\n            hessp_val[self.comp_slice] += adh_curv \\\n                * des_dir.reshape(\n                self.substrate.nb_subdomain_grid_pts)[self.comp_slice] * \\\n                self.substrate.area_per_pt\n            return hessp_val.reshape(des_dir.shape)\n\n        return hessp\n\n    def _fourier_coefficients(self):\n        \"\"\"\n        Returns the coefficients for elasticity matrix when working in fourier\n        space for both 1D and 2D system.\n        \"\"\"\n\n        nx = self.substrate.nb_grid_pts[0]\n        nb_dims = len(self.substrate.nb_grid_pts)\n\n        if nb_dims == 2:\n            ny = self.substrate.nb_grid_pts[1]\n            coeffs = np.zeros(self.substrate.nb_grid_pts)\n            if np.logical_and((nx % 2 == 0), (ny % 2 == 0)):\n                coeffs[0, 0] = 1 / (nx * ny)\n                coeffs[0, 1:ny // 2] = 2 / (nx * ny)\n                coeffs[0, ny // 2 + 1:] = 2 / (nx * ny)\n                coeffs[1:nx // 2, 0] = 2 / (nx * ny)\n                coeffs[nx // 2 + 1:, 0] = 2 / (nx * ny)\n                coeffs[:nx // 2, ny // 2] = 2 / (nx * ny)\n                coeffs[nx // 2 + 1:, ny // 2] = 2 / (nx * ny)\n                coeffs[nx // 2, :ny // 2] = 2 / (nx * ny)\n                coeffs[nx // 2, ny // 2 + 1:] = 2 / (nx * ny)\n                coeffs[1:nx // 2, 1:ny // 2] = 4 / (nx * ny)\n                coeffs[nx // 2 + 1:, 1:ny // 2] = 4 / (nx * ny)\n                coeffs[1:nx // 2, ny // 2 + 1:] = 4 / (nx * ny)\n                coeffs[nx // 2 + 1:, ny // 2 + 1:] = 4 / (nx * ny)\n                coeffs[nx // 2, ny // 2] = 1 / (nx * ny)\n                coeffs[nx // 2, 0] = 1 / (nx * ny)\n                coeffs[0, ny // 2] = 1 / (nx * ny)\n            else:\n                coeffs[0, 0] = 1 / (nx * ny)\n                coeffs[0, 1:] = 2 / (nx * ny)\n                coeffs[1:, 0] = 2 / (nx * ny)\n                coeffs[1:, 1:] = 4 / (nx * ny)\n        elif nb_dims == 1:\n            coeffs = np.zeros(self.substrate.nb_grid_pts)\n            if (nx % 2 == 0):\n                coeffs[0] = 1 / nx\n                coeffs[1:nx // 2] = 2 / nx\n                coeffs[nx // 2 + 1:] = 2 / nx\n                coeffs[nx // 2] = 1 / nx\n            else:\n                coeffs[0] = 1 / nx\n                coeffs[1:] = 2 / nx\n\n        return coeffs\n\n    def evaluate_k(self, disp_k, gap, offset, mw=False, pot=True, forces=False,\n                   logger=None):\n\n        \"\"\"\n        Compute the energies and forces in the system for a given displacement\n        field in fourier space.\n\n        Parameters\n        -----------\n\n        disp_k: ndarray\n            displacement field in fourier space.\n        gap:  ndarray\n            displacement field in real space, in the shape of\n            system.substrate.nb_subdomain_grid_pts\n        offset: float\n            determines indentation depth,\n            constant value added to the heights (system.topography)\n        mw: bool, optional\n            when mass weighting is required then set this to TRUE.\n        pot: bool, optional\n            Wether to evaluate the energy, default True\n        forces: bool, optional\n            Wether to evaluate the forces, default False\n        logger: ContactMechanics.Tools.Logger\n            informations of current state of the system will be passed to\n            logger at every evaluation.\n        \"\"\"\n\n        # self.gap = self.compute_gap(disp, offset)\n        self.gap = gap\n        interaction_energies, self.interaction_force, _ = \\\n            self.interaction.evaluate(self.gap,\n                                      potential=pot,\n                                      gradient=forces,\n                                      curvature=False)\n        self.interaction_energy = \\\n            self.reduction.sum(interaction_energies) * self.area_per_pt\n\n        self.grad_k = np.zeros(self.substrate.nb_grid_pts)\n\n        coeff = self._fourier_coefficients()\n\n        if mw:\n            self.grad_k = disp_k * coeff\n        else:\n            self.grad_k = disp_k * coeff * self.stiffness_k\n\n        self.grad_k *= self.area_per_pt\n\n        # ENERGY FROM SUBSTRATE\n        self.energy = 0.5 * (np.sum(self.grad_k * disp_k))\n\n        self.substrate.energy = self.energy\n\n        self.force_h = -self.grad_k\n\n        # TOTAL ENERGY\n        self.energy += self.interaction_energy\n\n        if forces:\n            self.interaction_force *= -self.area_per_pt\n            #                     ^ gradient to force per pixel\n\n            self.real_buffer.array()[...] = self.interaction_force\n            self.engine.hcfft(self.real_buffer, self.fourier_buffer)\n            interaction_force_float_k = self.fourier_buffer.array()[...].copy()\n\n            adh_coeffs = self._fourier_coefficients()\n            interaction_force_float_k *= adh_coeffs\n\n            if mw:\n                k = np.sqrt(self.stiffness_k.copy() * self.area_per_pt)\n                interaction_force_float_k = interaction_force_float_k * (1 / k)\n\n            self.force_h += interaction_force_float_k\n        else:\n            self.force_h = None\n\n        if logger is not None:\n            disp_real = self.gap + self.surface.heights().copy() + offset\n            force_real = self.substrate.evaluate_force(disp_real)\n            force_real = force_real + self.interaction_force\n            logger.st(*(['energy',\n                         'max. abs. grad.',\n                         'max. abs. grad. real'],\n                        [self.energy,\n                         self.reduction.max(np.abs(self.force_h)),\n                         self.reduction.max(np.abs(force_real))\n                         ]))\n\n        return (self.energy, self.force_h)\n\n    # def hessian_product_k(self, dispk, des_dir_k):\n    #     \"\"\"Returns the hessian product of the fourier space\n    #     objective_k function.\n    #     \"\"\"\n    #     self.substrate.fourier_buffer.array()[...] = dispk.copy()\n    #     self.substrate.fftengine.ifft(self.substrate.fourier_buffer,\n    #                                   self.substrate.real_buffer)\n    #     disp = self.substrate.real_buffer.array()[...].copy() \\\n    #         * self.substrate.fftengine.normalisation\n    #\n    #     gap = self.compute_gap(disp)\n    #     _, _, adh_curv = self.interaction.evaluate(gap, curvature=True)\n    #\n    #     self.substrate.real_buffer.array()[...] = adh_curv.reshape(\n    #         self.substrate.nb_grid_pts).copy()\n    #     self.substrate.fftengine.fft(self.substrate.real_buffer,\n    #                                  self.substrate.fourier_buffer)\n    #     adh_curv_k = self.substrate.fourier_buffer.array()[...].copy()\n    #\n    #     hessp_val_k = -self.substrate.evaluate_k_force_k(des_dir_k) + \\\n    #         adh_curv_k * des_dir_k * self.substrate.area_per_pt\n    #\n    #     return hessp_val_k\n\n    # def hessian_product_preconditioned(self, offset):\n\n    #     def hessp_precond(disp_h, des_dir):\n    #\n    #         self.real_buffer.array()[...] = offset\n    #         self.engine.hcfft(self.real_buffer, self.fourier_buffer)\n    #         offset_k = self.fourier_buffer.array()[...].copy()\n    #\n    #         self.real_buffer.array()[...] = self.surface.heights().copy()\n    #         self.engine.hcfft(self.real_buffer, self.fourier_buffer)\n    #         self.heights_k_float = self.fourier_buffer.array()[...].copy()\n    #\n    #         disp_float_k = disp_h.copy()\n    #         disp_float_k = disp_float_k.reshape(self.substrate.nb_grid_pts)\n    #         gap_float_k = (disp_float_k / np.sqrt(self.stiffness_k *\n    #                                               self.area_per_pt)) - \\\n    #                       self.heights_k_float - offset_k\n    #\n    #         self.fourier_buffer.array()[...] = gap_float_k.copy()\n    #         self.engine.ihcfft(self.fourier_buffer, self.real_buffer)\n    #         gap = self.real_buffer.array()[...].copy() * \\\n    #               self.engine.normalisation\n    #\n    #         _, _, adh_curv = \\\n    #             self.interaction.evaluate(gap,\n    #                                       curvature=True)\n    #\n    #         coeff = self._fourier_coefficients()\n    #\n    #         el_hess_k = coeff @ coeff\n    #         el_hess_k *= self.area_per_pt\n    #\n    #         orig_shape = np.shape(des_dir)\n    #\n    #         el_hess_k *= des_dir #.reshape(el_hess_k)\n    #\n    #         adh_curv *= self.area_per_pt\n    #\n    #         self.real_buffer.array()[...] = adh_curv\n    #         self.engine.hcfft(self.real_buffer, self.fourier_buffer)\n    #         adh_curv_float_k = self.fourier_buffer.array()[...].copy()\n    #\n    #         adh_curv_float_k *= coeff @ coeff\n    #\n    #         k = np.sqrt(self.stiffness_k.copy() * self.area_per_pt)\n    #\n    #         adh_hess_k = adh_curv_float_k * des_dir * (1 / k) * (1 / k)\n    #\n    #         hess_k = el_hess_k.reshape(orig_shape) + \\\n    #                  adh_hess_k.reshape(orig_shape)\n    #\n    #         return hess_k\n    #\n    #     return hessp_precond\n\n    def preconditioned_objective(self, offset, gradient=False, logger=None):\n        r\"\"\"\n        This helper method interface to the evaluate_k() method with\n        preconditioning active. That is, it tries to solve a simpler problem\n        formulated using,\n\n        original problem:\n\n        .. math ::\n\n            \\frac{1}{2(n_x n_y)} \\tilde{u}\\tilde{K} \\bar{\\tilde{u}} +\n            \\phi(F^{-1}(\\tilde{u} - \\tilde{h}))\n\n        preconditioned problem:\n\n        .. math ::\n             \\tilde{v} = \\tilde{k}^{\\frac{1}{2}} \\tilde{u} \\\\\n\n             \\frac{1}{2(n_x n_y)} \\tilde{v}\\bar{\\tilde{v}} +\n            \\phi(F^{-1}(\\frac{\\tilde{v}}{\\tilde{k}^{\\frac{1}{2}}} - \\tilde{h}))\n\n        we solve for variable :math:`\\tilde{v}`.\n\n        Parameters:\n        -----------\n\n        offset: float\n            determines indentation depth,\n            constant value added to the heights (system.topography)\n        gradient: bool, optional\n            Whether to evaluate the gradient, default False\n        logger: ContactMechanics.Tools.Logger\n            information of current state of the system will be passed to\n            logger at every evaluation\n\n        Returns\n        _______\n\n            function(disp_k)\n\n                Parameters\n                __________\n\n                disp_k: an ndarray in fourier halfcomplex space\n\n                Returns\n                _______\n\n                energy: scalar\n                        energy of the system\n\n                force_h: an halfcomplex array of shape(disp_k)\n                        force of the system\n        \"\"\"\n\n        # TODO: fourier transforming the offset is useless\n        self.real_buffer.array()[...] = offset\n        self.engine.hcfft(self.real_buffer, self.fourier_buffer)\n        offset_k = self.fourier_buffer.array()[...].copy()\n\n        self.real_buffer.array()[...] = self.surface.heights().copy()\n        self.engine.hcfft(self.real_buffer, self.fourier_buffer)\n        self.heights_k_float = self.fourier_buffer.array()[...].copy()\n\n        if gradient:\n            def fun(disp_):\n                disp_float_k = disp_.copy()\n                orig_shape = np.shape(disp_float_k)\n                disp_float_k = disp_float_k.reshape(self.substrate.nb_grid_pts)\n                gap_float_k = (disp_float_k / np.sqrt(self.stiffness_k *\n                                                      self.area_per_pt)) - \\\n                    self.heights_k_float - offset_k\n\n                self.fourier_buffer.array()[...] = gap_float_k.copy()\n                self.engine.ihcfft(self.fourier_buffer, self.real_buffer)\n                gap = self.real_buffer.array()[...].copy() * self.engine.normalisation\n\n                self.energy, self.force_h = self.evaluate_k(disp_float_k,\n                                                            gap, offset,\n                                                            mw=True,\n                                                            forces=True,\n                                                            logger=logger\n                                                            )\n\n                return (self.energy, -self.force_h.reshape(orig_shape))\n        else:\n            raise NotImplementedError\n\n        return fun\n\n    def objective_k_float(self, offset, gradient=False, logger=None):\n        r\"\"\"\n\n        Returns callable objective as needed by scipy minimizers.\n\n        The optimisation varialbe is the halfcomplex fourier transform of the gap.\n\n        This helper method interface to the evaluate_k() method without\n        preconditioning active.\n\n        .. math ::\n\n            \\frac{1}{2(n_x n_y)} \\tilde{u}\\tilde{K} \\bar{\\tilde{u}} +\n            \\phi(F^{-1}(\\tilde{u} - \\tilde{h}))  \\\\\n\n        preconditioned problem:\n\n        .. math ::\n\n             \\tilde{v} = \\tilde{k}^{\\frac{1}{2}} \\tilde{u} \\\\\n\n             \\frac{1}{2(n_x n_y)} \\tilde{v} \\bar{\\tilde{v}} +\n            \\phi(F^{-1}(\\frac{\\tilde{v}}{\\tilde{k}^{\\frac{1}{2}}} - \\tilde{h}))\n        \\\\\n        we solve for variable :math:`\\tilde{v}`.\n\n        Parameters:\n        -----------\n\n        offset: float\n            determines indentation depth,\n            constant value added to the heights (system.topography)\n        gradient: bool, optional\n            Whether to evaluate the gradient, default False\n        logger: ContactMechanics.Tools.Logger\n            information of current state of the system will be passed to\n            logger at every evaluation\n\n        Returns\n        _______\n\n            function(disp_k)\n\n                Parameters\n                __________\n\n                disp_k: an ndarray in fourier space\n\n                Returns\n                _______\n\n                    energy, gradient_k_float\n        \"\"\"\n\n        self.real_buffer.array()[...] = offset\n        self.engine.hcfft(self.real_buffer, self.fourier_buffer)\n        offset_k = self.fourier_buffer.array()[...].copy()\n\n        self.real_buffer.array()[...] = self.surface.heights().copy()\n        self.engine.hcfft(self.real_buffer, self.fourier_buffer)\n        self.heights_k_float = self.fourier_buffer.array()[...].copy()\n\n        if gradient:\n            def fun(disp_k):\n                disp_float_k = disp_k.copy()\n                orig_shape = np.shape(disp_float_k)\n                disp_float_k = disp_float_k.reshape(self.substrate.nb_grid_pts)\n                gap_float_k = disp_float_k - self.heights_k_float - offset_k\n                self.fourier_buffer.array()[...] = gap_float_k.copy()\n                self.engine.ihcfft(self.fourier_buffer, self.real_buffer)\n                gap = self.real_buffer.array()[...].copy() \\\n                    * self.engine.normalisation\n\n                self.energy, self.force_h = self.evaluate_k(disp_float_k,\n                                                            gap, offset,\n                                                            forces=True,\n                                                            logger=logger\n                                                            )\n                return (self.energy, -self.force_h.reshape(orig_shape))\n        else:\n            def fun(disp_k):\n                # pylint: disable=missing-docstring\n                disp_float_k = disp_k.copy()\n                disp_float_k = disp_float_k.reshape(self.substrate.nb_grid_pts)\n                gap_float_k = disp_float_k - self.heights_k_float - offset_k\n                self.fourier_buffer.array()[...] = gap_float_k.copy()\n                self.engine.ihcfft(self.fourier_buffer, self.real_buffer)\n                gap = self.real_buffer.array()[...].copy() \\\n                    * self.engine.normalisation\n\n                return self.evaluate_k(disp_float_k, gap, offset, forces=True,\n                                       logger=logger)[0]\n\n        return fun\n\n    def callback(self, force=False):\n        \"\"\"\n        Simple callback function that can be handed over to scipy's minimize to\n        get updates during minimisation\n        Parameters:\n        ----------\n        force: bool, optional\n            whether to include the norm of the force\n            vector in the update message\n            (default False)\n        \"\"\"\n        counter = 0\n        if force:\n            def fun(dummy):\n                \"includes the force norm in its output\"\n                nonlocal counter\n                counter += 1\n                print(\"at it {}, e = {}, |f| = {}\".format(\n                    counter, self.energy,\n                    np.linalg.norm(np.ravel(self.force))))\n        else:\n            def fun(dummy):\n                \"prints messages without force information\"\n                nonlocal counter\n                counter += 1\n                print(\"at it {}, e = {}\".format(\n                    counter, self.energy))\n        return fun\n\n\nclass BoundedSmoothContactSystem(SmoothContactSystem):\n    @staticmethod\n    def handles(*args, **kwargs):  # FIXME work around, see issue #208\n        return False\n\n    def compute_nb_contact_pts(self):\n        \"\"\"\n        compute and return the number of contact points.\n        \"\"\"\n        return self.reduction.sum(np.where(self.gap == 0., 1., 0.))\n\n    def logger_input(self):\n        \"\"\"\n\n        Returns\n        -------\n        headers: list of strings\n        values: list\n        \"\"\"\n        tot_nb_grid_pts = np.prod(self.nb_grid_pts)\n        rel_rep_area = self.compute_nb_repulsive_pts() / tot_nb_grid_pts\n        rel_att_area = self.compute_nb_attractive_pts() / tot_nb_grid_pts\n        # TODO: eventually put a flag to turn\n        #  reductions off since this is an additional communication.\n\n        contacting_points = self.gap == 0.\n        mask = np.ones(self.substrate.nb_subdomain_grid_pts)\n        mask[self.substrate.local_topography_subdomain_slices][\n            contacting_points] = 0\n        max_proj_grad = self.reduction.max(abs(mask * self.force))\n\n        return (['energy',\n                 'max. proj. grad.',\n                 'mean gap',\n                 'frac. cont. area',\n                 'frac. rep. area',\n                 'frac. att. area',\n                 'frac. int. area',\n                 'substrate force',\n                 'interaction force'],\n                [self.energy,\n                 max_proj_grad,\n                 self.compute_mean_gap(),\n                 self.compute_nb_contact_pts() / np.prod(self.nb_grid_pts),\n                 rel_rep_area,\n                 rel_att_area,\n                 rel_rep_area + rel_att_area,\n                 -self.reduction.sum(self.substrate.force),\n                 self.reduction.sum(self.interaction_force)])\n\n    def compute_normal_force(self):\n        \"computes and returns the sum of all forces\"\n\n        # sum of the jacobian in the contact area (Lagrange multiplier)\n        # and the ineraction forces.\n        # can also be computed easily from the substrate forces,\n        # what we do here\n        return self.reduction.sum(\n            - self.substrate.force[self.substrate.local_topography_subdomain_slices])\n\n    def compute_repulsive_force(self):\n        \"\"\"computes and returns the sum of all repulsive forces\n\n        Assumptions: there\n        \"\"\"\n        return self.reduction.sum(\n            np.where(\n                - self.substrate.force[\n                    self.substrate.local_topography_subdomain_slices] > 0,\n                - self.substrate.force[\n                    self.substrate.local_topography_subdomain_slices], 0.))\n\n    def compute_attractive_force(self):\n        \"computes and returns the sum of all attractive forces\"\n        return self.reduction.sum(\n            np.where(\n                - self.substrate.force[\n                    self.substrate.local_topography_subdomain_slices] < 0,\n                - self.substrate.force[\n                    self.substrate.local_topography_subdomain_slices],\n                0.))\n\n    def compute_nb_repulsive_pts(self):\n        \"\"\"\n        compute and return the number of contact points under repulsive\n        pressure.\n\n        \"\"\"\n        return self.reduction.sum(\n            np.where(\n                np.logical_and(\n                    self.gap == 0.,\n                    - self.substrate.force[\n                        self.substrate.local_topography_subdomain_slices] > 0),\n                1., 0.))\n\n    def compute_nb_attractive_pts(self):\n        \"\"\"\n        compute and return the number of contact points under attractive\n        pressure.\n        \"\"\"\n\n        # Compute points where substrate force is negative\n        # or there is no contact\n        pts = np.logical_or(- self.substrate.force[\n            self.substrate.local_topography_subdomain_slices] < 0,\n                            self.gap > 0.)\n\n        # exclude points where there is no contact\n        # and the interaction force is 0.\n        pts[np.logical_and(self.gap > 0.,\n                           self.interaction_force == 0.)] = 0.\n\n        return self.reduction.sum(pts)\n\n    def compute_repulsive_coordinates(self):\n        \"\"\"\n        returns an array of all coordinates, where contact pressure is\n        repulsive. Useful for evaluating the number of contact islands etc.\n        \"\"\"\n        return np.argwhere(\n            np.logical_and(\n                self.gap == 0.,\n                - self.substrate.force[\n                    self.substrate.local_topography_subdomain_slices]\n                > 0))\n\n    def compute_attractive_coordinates(self):\n        \"\"\"\n        returns an array of all coordinates, where contact pressure is\n        attractive. Useful for evaluating the number of contact islands etc.\n        \"\"\"\n\n        # Compute points where substrate force is negative\n        # or there is no contact\n        pts = np.logical_or(\n            - self.substrate.force[self.substrate.local_topography_subdomain_slices]\n            < 0,\n            self.gap > 0.)\n\n        # exclude points where there is no contact\n        # and the interaction force is 0.\n        pts[np.logical_and(self.gap > 0.,\n                           self.interaction_force == 0.)] = 0.\n\n        return np.argwhere(pts)\n", "meta": {"hexsha": "aaae22364375859e9852d098d2a426159f9912b6", "size": 40460, "ext": "py", "lang": "Python", "max_stars_repo_path": "Adhesion/System/Systems.py", "max_stars_repo_name": "ContactEngineering/Adhesion", "max_stars_repo_head_hexsha": "acc46ad9bfe49fec667cb9a116ebde426faa38c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Adhesion/System/Systems.py", "max_issues_repo_name": "ContactEngineering/Adhesion", "max_issues_repo_head_hexsha": "acc46ad9bfe49fec667cb9a116ebde426faa38c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-08-18T07:30:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T11:05:09.000Z", "max_forks_repo_path": "Adhesion/System/Systems.py", "max_forks_repo_name": "ContactEngineering/Adhesion", "max_forks_repo_head_hexsha": "acc46ad9bfe49fec667cb9a116ebde426faa38c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9906103286, "max_line_length": 115, "alphanum_fraction": 0.5575135937, "include": true, "reason": "import numpy", "num_tokens": 8708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.34864512856608565, "lm_q1q2_score": 0.19867635600983283}}
{"text": "\"\"\"\nCode to export from yt to Sunrise\n\n\n\n\"\"\"\nfrom __future__ import print_function\n\n#-----------------------------------------------------------------------------\n# Copyright (c) 2013, yt Development Team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n#-----------------------------------------------------------------------------\n\ntry:\n    import pyfits\nexcept ImportError: \n    pass\n\nimport time\nimport numpy as np\nfrom yt.funcs import *\nimport yt.utilities.lib.api as amr_utils\nfrom yt.utilities.physical_constants import \\\n    kpc_per_cm, \\\n    sec_per_year\nfrom yt.mods import *\n\ndef export_to_sunrise(ds, fn, star_particle_type, fc, fwidth, ncells_wide=None,\n        debug=False,dd=None,**kwargs):\n    r\"\"\"Convert the contents of a dataset to a FITS file format that Sunrise\n    understands.\n\n    This function will accept a dataset, and from that dataset\n    construct a depth-first octree containing all of the data in the parameter\n    file.  This octree will be written to a FITS file.  It will probably be\n    quite big, so use this function with caution!  Sunrise is a tool for\n    generating synthetic spectra, available at\n    http://sunrise.googlecode.com/ .\n\n    Parameters\n    ----------\n    ds : `Dataset`\n       The dataset to convert.\n    fn : string\n       The filename of the output FITS file.\n    fc : array\n       The center of the extraction region\n    fwidth  : array  \n       Ensure this radius around the center is enclosed\n       Array format is (nx,ny,nz) where each element is floating point\n       in unitary position units where 0 is leftmost edge and 1\n       the rightmost. \n\n    Notes\n    -----\n\n    Note that the process of generating simulated images from Sunrise will\n    require substantial user input; see the Sunrise wiki at\n    http://sunrise.googlecode.com/ for more information.\n\n    \"\"\"\n    fc = np.array(fc)\n    fwidth = np.array(fwidth)\n    \n    #we must round the dle,dre to the nearest root grid cells\n    ile,ire,super_level,ncells_wide= \\\n            round_ncells_wide(ds.domain_dimensions,fc-fwidth,fc+fwidth,nwide=ncells_wide)\n\n    assert np.all((ile-ire)==(ile-ire)[0])\n    mylog.info(\"rounding specified region:\")\n    mylog.info(\"from [%1.5f %1.5f %1.5f]-[%1.5f %1.5f %1.5f]\"%(tuple(fc-fwidth)+tuple(fc+fwidth)))\n    mylog.info(\"to   [%07i %07i %07i]-[%07i %07i %07i]\"%(tuple(ile)+tuple(ire)))\n    fle,fre = ile*1.0/ds.domain_dimensions, ire*1.0/ds.domain_dimensions\n    mylog.info(\"to   [%1.5f %1.5f %1.5f]-[%1.5f %1.5f %1.5f]\"%(tuple(fle)+tuple(fre)))\n\n    #Create a list of the star particle properties in PARTICLE_DATA\n    #Include ID, parent-ID, position, velocity, creation_mass, \n    #formation_time, mass, age_m, age_l, metallicity, L_bol\n    particle_data,nstars = prepare_star_particles(ds,star_particle_type,fle=fle,fre=fre,\n                                           dd=dd,**kwargs)\n\n    #Create the refinement hilbert octree in GRIDSTRUCTURE\n    #For every leaf (not-refined) cell we have a column n GRIDDATA\n    #Include mass_gas, mass_metals, gas_temp_m, gas_teff_m, cell_volume, SFR\n    #since the octree always starts with one cell, an our 0-level mesh\n    #may have many cells, we must create the octree region sitting \n    #ontop of the first mesh by providing a negative level\n    output, refinement,dd,nleaf = prepare_octree(ds,ile,start_level=super_level,\n            debug=debug,dd=dd,center=fc)\n\n    create_fits_file(ds,fn, refinement,output,particle_data,fle,fre)\n\n    return fle,fre,ile,ire,dd,nleaf,nstars\n\ndef export_to_sunrise_from_halolist(ds,fni,star_particle_type,\n                                        halo_list,domains_list=None,**kwargs):\n    \"\"\"\n    Using the center of mass and the virial radius\n    for a halo, calculate the regions to extract for sunrise.\n    The regions are defined on the root grid, and so individual\n    octs may span a large range encompassing many halos\n    and subhalos. Instead of repeating the oct extraction for each\n    halo, arrange halos such that we only calculate what we need to.\n\n    Parameters\n    ----------\n    ds : `Dataset`\n        The dataset to convert. We use the root grid to specify the domain.\n    fni : string\n        The filename of the output FITS file, but depends on the domain. The\n        dle and dre are appended to the name.\n    particle_type : int\n        The particle index for stars\n    halo_list : list of halo objects\n        The halo list objects must have halo.CoM and halo.Rvir,\n        both of which are assumed to be in unitary length units.\n    frvir (optional) : float\n        Ensure that CoM +/- frvir*Rvir is contained within each domain\n    domains_list (optiona): dict of halos\n        Organize halos into a dict of domains. Keys are DLE/DRE tuple\n        values are a list of halos\n    \"\"\"\n    dn = ds.domain_dimensions\n    if domains_list is None:\n        domains_list = domains_from_halos(ds,halo_list,**kwargs)\n    if fni.endswith('.fits'):\n        fni = fni.replace('.fits','')\n\n    for (num_halos, domain, halos) in domains_list:\n        dle,dre = domain\n        print('exporting: ')\n        print(\"[%03i %03i %03i] -\"%tuple(dle), end=' ')\n        print(\"[%03i %03i %03i] \"%tuple(dre), end=' ')\n        print(\" with %i halos\"%num_halos)\n        dle,dre = domain\n        dle, dre = np.array(dle),np.array(dre)\n        fn = fni \n        fn += \"%03i_%03i_%03i-\"%tuple(dle)\n        fn += \"%03i_%03i_%03i\"%tuple(dre)\n        fnf = fn + '.fits'\n        fnt = fn + '.halos'\n        if os.path.exists(fnt):\n            os.remove(fnt)\n        fh = open(fnt,'w')\n        for halo in halos:\n            fh.write(\"%i \"%halo.ID)\n            fh.write(\"%6.6e \"%(halo.CoM[0]*ds['kpc']))\n            fh.write(\"%6.6e \"%(halo.CoM[1]*ds['kpc']))\n            fh.write(\"%6.6e \"%(halo.CoM[2]*ds['kpc']))\n            fh.write(\"%6.6e \"%(halo.Mvir))\n            fh.write(\"%6.6e \\n\"%(halo.Rvir*ds['kpc']))\n        fh.close()\n        export_to_sunrise(ds, fnf, star_particle_type, dle*1.0/dn, dre*1.0/dn)\n\ndef domains_from_halos(ds,halo_list,frvir=0.15):\n    domains = {}\n    dn = ds.domain_dimensions\n    for halo in halo_list:\n        fle, fre = halo.CoM-frvir*halo.Rvir,halo.CoM+frvir*halo.Rvir\n        dle,dre = np.floor(fle*dn), np.ceil(fre*dn)\n        dle,dre = tuple(dle.astype('int')),tuple(dre.astype('int'))\n        if (dle,dre) in domains.keys():\n            domains[(dle,dre)] += halo,\n        else:\n            domains[(dle,dre)] = [halo,]\n    #for niceness, let's process the domains in order of \n    #the one with the most halos\n    domains_list = [(len(v),k,v) for k,v in domains.iteritems()]\n    domains_list.sort() \n    domains_list.reverse() #we want the most populated domains first\n    return domains_list\n\ndef prepare_octree(ds,ile,start_level=0,debug=True,dd=None,center=None):\n    if dd is None:\n        #we keep passing dd around to not regenerate the data all the time\n        dd = ds.all_data()\n    try:\n        dd['MetalMass']\n    except KeyError:\n        add_fields() #add the metal mass field that sunrise wants\n    def _temp_times_mass(field, data):\n        return data[\"Temperature\"]*data[\"CellMassMsun\"]\n    add_field(\"TemperatureTimesCellMassMsun\", function=_temp_times_mass)\n    fields = [\"CellMassMsun\",\"TemperatureTimesCellMassMsun\", \n              \"MetalMass\",\"CellVolumeCode\"]\n    \n    #gather the field data from octs\n    pbar = get_pbar(\"Retrieving field data\",len(fields))\n    field_data = [] \n    for fi,f in enumerate(fields):\n        field_data += dd[f],\n        pbar.update(fi)\n    pbar.finish()\n    del field_data\n\n    #first we cast every cell as an oct\n    #ngrids = np.max([g.id for g in ds._grids])\n    grids = {}\n    levels_all = {} \n    levels_finest = {}\n    for l in range(100): \n        levels_finest[l]=0\n        levels_all[l]=0\n    pbar = get_pbar(\"Initializing octs \",len(ds.index.grids))\n    for gi,g in enumerate(ds.index.grids):\n        ff = np.array([g[f] for f in fields])\n        og = amr_utils.OctreeGrid(\n                g.child_index_mask.astype('int32'),\n                ff.astype(\"float64\"),\n                g.LeftEdge.astype(\"float64\"),\n                g.ActiveDimensions.astype(\"int32\"),\n                np.ones(1,dtype=\"float64\")*g.dds[0],\n                g.Level,\n                g.id)\n        grids[g.id] = og\n        #how many refinement cells will we have?\n        #measure the 'volume' of each mesh, but many\n        #cells do not exist. an overstimate\n        levels_all[g.Level] += g.ActiveDimensions.prod()\n        #how many leaves do we have?\n        #this overestimates. a child of -1 means no child,\n        #but that cell may still be expanded on a submesh because\n        #(at least in ART) the meshes are inefficient.\n        g.clear_data()\n        pbar.update(gi)\n    pbar.finish()\n    \n    #create the octree grid list\n    #oct_list =  amr_utils.OctreeGridList(grids)\n    \n    #initialize arrays to be passed to the recursion algo\n    o_length = np.sum(levels_all.values())\n    r_length = np.sum(levels_all.values())\n    output   = np.zeros((o_length,len(fields)), dtype='float64')\n    refined  = np.zeros(r_length, dtype='int32')\n    levels   = np.zeros(r_length, dtype='int32')\n    ids      = np.zeros(r_length, dtype='int32')\n    pos = position()\n    hs       = hilbert_state()\n    start_time = time.time()\n    if debug:\n        printing = lambda x: print_oct(x)\n    else:\n        printing = None\n    pbar = get_pbar(\"Building Hilbert DFO octree\",len(refined))\n    RecurseOctreeDepthFirstHilbert(\n            ile,\n            pos,\n            grids[0], #we always start on the root grid\n            hs, \n            output,refined,levels,\n            grids,\n            start_level,\n            ids,\n            debug=printing,\n            tracker=pbar)\n    pbar.finish()\n    #by time we get it here the 'current' position is actually \n    #for the next spot, so we're off by 1\n    print('took %1.2e seconds'%(time.time()-start_time))\n    print('refinement tree # of cells %i, # of leaves %i'%(pos.refined_pos,pos.output_pos)) \n    print('first few entries :',refined[:12])\n    output  = output[:pos.output_pos]\n    refined = refined[:pos.refined_pos] \n    levels = levels[:pos.refined_pos] \n    return output,refined,dd,pos.refined_pos\n\ndef print_oct(data,nd=None,nc=None):\n    ci = data['cell_index']\n    l  = data['level']\n    g  = data['grid']\n    o  = g.offset\n    fle = g.left_edges+g.dx*ci\n    fre = g.left_edges+g.dx*(ci+1)\n    if nd is not None:\n        fle *= nd\n        fre *= nd\n        if nc is not None:\n            fle -= nc\n            fre -= nc\n    txt  = '%+1i '\n    txt += '%+1i '\n    txt += '%+1.3f '*3+'- '\n    txt += '%+1.3f '*3\n    if l<2:\n        print(txt%((l,)+(o,)+tuple(fle)+tuple(fre)))\n\ndef RecurseOctreeDepthFirstHilbert(cell_index, #integer (rep as a float) on the [grid_index]\n                            pos, #the output hydro data position and refinement position\n                            grid,  #grid that this oct lives on (not its children)\n                            hilbert,  #the hilbert state\n                            output, #holds the hydro data\n                            refined, #holds the refinement status  of Octs, 0s and 1s\n                            levels, #For a given Oct, what is the level\n                            grids, #list of all patch grids available to us\n                            level, #starting level of the oct (not the children)\n                            ids, #record the oct ID\n                            debug=None,tracker=True):\n    if tracker is not None:\n        if pos.refined_pos%1000 == 500 : tracker.update(pos.refined_pos)\n    if debug is not None: \n        debug(vars())\n    child_grid_index = grid.child_indices[cell_index[0],cell_index[1],cell_index[2]]\n    #record the refinement state\n    levels[pos.refined_pos]  = level\n    is_leaf = (child_grid_index==-1) and (level>0)\n    refined[pos.refined_pos] = not is_leaf #True is oct, False is leaf\n    ids[pos.refined_pos] = child_grid_index #True is oct, False is leaf\n    pos.refined_pos+= 1 \n    if is_leaf: #never subdivide if we are on a superlevel\n        #then we have hit a leaf cell; write it out\n        for field_index in range(grid.fields.shape[0]):\n            output[pos.output_pos,field_index] = \\\n                    grid.fields[field_index,cell_index[0],cell_index[1],cell_index[2]]\n        pos.output_pos+= 1 \n    else:\n        assert child_grid_index>-1\n        #find the grid we descend into\n        #then find the eight cells we break up into\n        subgrid = grids[child_grid_index]\n        #calculate the floating point LE of the children\n        #then translate onto the subgrid integer index \n        parent_fle  = grid.left_edges + cell_index*grid.dx\n        subgrid_ile = np.floor((parent_fle - subgrid.left_edges)/subgrid.dx)\n        for (vertex, hilbert_child) in hilbert:\n            #vertex is a combination of three 0s and 1s to \n            #denote each of the 8 octs\n            if level < 0:\n                subgrid = grid #we don't actually descend if we're a superlevel\n                #child_ile = cell_index + np.array(vertex)*2**(-level)\n                child_ile = cell_index + np.array(vertex)*2**(-(level+1))\n                child_ile = child_ile.astype('int')\n            else:\n                child_ile = subgrid_ile+np.array(vertex)\n                child_ile = child_ile.astype('int')\n\n            RecurseOctreeDepthFirstHilbert(child_ile,pos,\n                subgrid,hilbert_child,output,refined,levels,grids,\n                level+1,ids = ids,\n                debug=debug,tracker=tracker)\n\n\n\ndef create_fits_file(ds,fn, refined,output,particle_data,fle,fre):\n    #first create the grid structure\n    structure = pyfits.Column(\"structure\", format=\"B\", array=refined.astype(\"bool\"))\n    cols = pyfits.ColDefs([structure])\n    st_table = pyfits.new_table(cols)\n    st_table.name = \"GRIDSTRUCTURE\"\n    st_table.header.update(\"hierarch lengthunit\", \"kpc\", comment=\"Length unit for grid\")\n    fdx = fre-fle\n    for i,a in enumerate('xyz'):\n        st_table.header.update(\"min%s\" % a, fle[i] * ds['kpc'])\n        st_table.header.update(\"max%s\" % a, fre[i] * ds['kpc'])\n        st_table.header.update(\"n%s\" % a, fdx[i])\n        st_table.header.update(\"subdiv%s\" % a, 2)\n    st_table.header.update(\"subdivtp\", \"OCTREE\", \"Type of grid subdivision\")\n\n    #not the hydro grid data\n    fields = [\"CellMassMsun\",\"TemperatureTimesCellMassMsun\", \n              \"MetalMass\",\"CellVolumeCode\"]\n    fd = {}\n    for i,f in enumerate(fields): \n        fd[f]=output[:,i]\n    del output\n    col_list = []\n    size = fd[\"CellMassMsun\"].size\n    tm = fd[\"CellMassMsun\"].sum()\n    col_list.append(pyfits.Column(\"mass_gas\", format='D',\n                    array=fd['CellMassMsun'], unit=\"Msun\"))\n    col_list.append(pyfits.Column(\"mass_metals\", format='D',\n                    array=fd['MetalMass'], unit=\"Msun\"))\n    # col_list.append(pyfits.Column(\"mass_stars\", format='D',\n    #                 array=np.zeros(size,dtype='D'),unit=\"Msun\"))\n    # col_list.append(pyfits.Column(\"mass_stellar_metals\", format='D',\n    #                 array=np.zeros(size,dtype='D'),unit=\"Msun\"))\n    # col_list.append(pyfits.Column(\"age_m\", format='D',\n    #                 array=np.zeros(size,dtype='D'),unit=\"yr*Msun\"))\n    # col_list.append(pyfits.Column(\"age_l\", format='D',\n    #                 array=np.zeros(size,dtype='D'),unit=\"yr*Msun\"))\n    # col_list.append(pyfits.Column(\"L_bol\", format='D',\n    #                 array=np.zeros(size,dtype='D')))\n    # col_list.append(pyfits.Column(\"L_lambda\", format='D',\n    #                 array=np.zeros(size,dtype='D')))\n    # The units for gas_temp are really K*Msun. For older Sunrise versions\n    # you must set the unit to just K  \n    col_list.append(pyfits.Column(\"gas_temp_m\", format='D',\n                    array=fd['TemperatureTimesCellMassMsun'], unit=\"K*Msun\"))\n    col_list.append(pyfits.Column(\"gas_teff_m\", format='D',\n                    array=fd['TemperatureTimesCellMassMsun'], unit=\"K*Msun\"))\n    col_list.append(pyfits.Column(\"cell_volume\", format='D',\n                    array=fd['CellVolumeCode'].astype('float64')*ds['kpc']**3.0,\n                    unit=\"kpc^3\"))\n    col_list.append(pyfits.Column(\"SFR\", format='D',\n                    array=np.zeros(size, dtype='D')))\n    cols = pyfits.ColDefs(col_list)\n    mg_table = pyfits.new_table(cols)\n    mg_table.header.update(\"M_g_tot\", tm)\n    mg_table.header.update(\"timeunit\", \"yr\")\n    mg_table.header.update(\"tempunit\", \"K\")\n    mg_table.name = \"GRIDDATA\"\n\n    # Add a dummy Primary; might be a better way to do this!\n    col_list = [pyfits.Column(\"dummy\", format=\"F\", array=np.zeros(1, dtype='float32'))]\n    cols = pyfits.ColDefs(col_list)\n    md_table = pyfits.new_table(cols)\n    md_table.header.update(\"snaptime\", ds.current_time*ds['years'])\n    md_table.name = \"YT\"\n\n    phdu = pyfits.PrimaryHDU()\n    phdu.header.update('nbodycod','yt')\n    hls = [phdu, st_table, mg_table,md_table]\n    hls.append(particle_data)\n    hdus = pyfits.HDUList(hls)\n    hdus.writeto(fn, clobber=True)\n\ndef nearest_power(x):\n    #round to the nearest power of 2\n    x-=1\n    x |= x >> 1\n    x |= x >> 2 \n    x |= x >> 4\n    x |= x >> 8\n    x |= x >> 16\n    x+=1 \n    return x\n\ndef round_ncells_wide(dds,fle,fre,nwide=None):\n    fc = (fle+fre)/2.0\n    assert np.all(fle < fc)\n    assert np.all(fre > fc)\n    ic = np.rint(fc*dds) #nearest vertex to the center\n    ile,ire = ic.astype('int'),ic.astype('int')\n    cfle,cfre = fc.copy(),fc.copy()\n    idx = np.array([0,0,0]) #just a random non-equal array\n    width = 0.0\n    if nwide is None:\n        #expand until borders are included and\n        #we have an equaly-sized, non-zero box\n        idxq,out=False,True\n        while not out or not idxq:\n            cfle,cfre = fc-width, fc+width\n            ile = np.rint(cfle*dds).astype('int')\n            ire = np.rint(cfre*dds).astype('int')\n            idx = ire-ile\n            width += 0.1/dds\n            #quit if idxq is true:\n            idxq = idx[0]>0 and np.all(idx==idx[0])\n            out  = np.all(fle>cfle) and np.all(fre<cfre) \n            out &= abs(np.log2(idx[0])-np.rint(np.log2(idx[0])))<1e-5 #nwide should be a power of 2\n            assert width[0] < 1.1 #can't go larger than the simulation volume\n        nwide = idx[0]\n    else:\n        #expand until we are nwide cells span\n        while not np.all(idx==nwide):\n            assert np.any(idx<=nwide)\n            cfle,cfre = fc-width, fc+width\n            ile = np.rint(cfle*dds).astype('int')\n            ire = np.rint(cfre*dds).astype('int')\n            idx = ire-ile\n            width += 1e-2*1.0/dds\n    assert np.all(idx==nwide)\n    assert idx[0]>0\n    maxlevel = -np.rint(np.log2(nwide)).astype('int')\n    assert abs(np.log2(nwide)-np.rint(np.log2(nwide)))<1e-5 #nwide should be a power of 2\n    return ile,ire,maxlevel,nwide\n\ndef round_nearest_edge(ds,fle,fre):\n    dds = ds.domain_dimensions\n    ile = np.floor(fle*dds).astype('int')\n    ire = np.ceil(fre*dds).astype('int') \n    \n    #this is the number of cells the super octree needs to expand to\n    #must round to the nearest power of 2\n    width = np.max(ire-ile)\n    width = nearest_power(width)\n    \n    maxlevel = -np.rint(np.log2(width)).astype('int')\n    return ile,ire,maxlevel\n\ndef prepare_star_particles(ds,star_type,pos=None,vel=None, age=None,\n                          creation_time=None,initial_mass=None,\n                          current_mass=None,metallicity=None,\n                          radius = None,\n                          fle=[0.,0.,0.],fre=[1.,1.,1.],\n                          dd=None):\n    if dd is None:\n        dd = ds.all_data()\n    idxst = dd[\"particle_type\"] == star_type\n\n    #make sure we select more than a single particle\n    assert na.sum(idxst)>0\n    if pos is None:\n        pos = np.array([dd[\"particle_position_%s\" % ax]\n                        for ax in 'xyz']).transpose()\n    idx = idxst & np.all(pos>fle,axis=1) & np.all(pos<fre,axis=1)\n    assert np.sum(idx)>0\n    pos = pos[idx]*ds['kpc'] #unitary units -> kpc\n    if age is None:\n        age = dd[\"particle_age\"][idx]*ds['years'] # seconds->years\n    if vel is None:\n        vel = np.array([dd[\"particle_velocity_%s\" % ax][idx]\n                        for ax in 'xyz']).transpose()\n        # Velocity is cm/s, we want it to be kpc/yr\n        #vel *= (ds[\"kpc\"]/ds[\"cm\"]) / (365*24*3600.)\n        vel *= kpc_per_cm * sec_per_year\n    if initial_mass is None:\n        #in solar masses\n        initial_mass = dd[\"particle_mass_initial\"][idx]*ds['Msun']\n    if current_mass is None:\n        #in solar masses\n        current_mass = dd[\"particle_mass\"][idx]*ds['Msun']\n    if metallicity is None:\n        #this should be in dimensionless units, metals mass / particle mass\n        metallicity = dd[\"particle_metallicity\"][idx]\n        assert np.all(metallicity>0.0)\n    if radius is None:\n        radius = initial_mass*0.0+10.0/1000.0 #10pc radius\n    formation_time = ds.current_time*ds['years']-age\n    #create every column\n    col_list = []\n    col_list.append(pyfits.Column(\"ID\", format=\"J\", array=np.arange(current_mass.size).astype('int32')))\n    col_list.append(pyfits.Column(\"parent_ID\", format=\"J\", array=np.arange(current_mass.size).astype('int32')))\n    col_list.append(pyfits.Column(\"position\", format=\"3D\", array=pos, unit=\"kpc\"))\n    col_list.append(pyfits.Column(\"velocity\", format=\"3D\", array=vel, unit=\"kpc/yr\"))\n    col_list.append(pyfits.Column(\"creation_mass\", format=\"D\", array=initial_mass, unit=\"Msun\"))\n    col_list.append(pyfits.Column(\"formation_time\", format=\"D\", array=formation_time, unit=\"yr\"))\n    col_list.append(pyfits.Column(\"radius\", format=\"D\", array=radius, unit=\"kpc\"))\n    col_list.append(pyfits.Column(\"mass\", format=\"D\", array=current_mass, unit=\"Msun\"))\n    col_list.append(pyfits.Column(\"age\", format=\"D\", array=age,unit='yr'))\n    #For particles, Sunrise takes \n    #the dimensionless metallicity, not the mass of the metals\n    col_list.append(pyfits.Column(\"metallicity\", format=\"D\",\n        array=metallicity,unit=\"Msun\")) \n    \n    #make the table\n    cols = pyfits.ColDefs(col_list)\n    pd_table = pyfits.new_table(cols)\n    pd_table.name = \"PARTICLEDATA\"\n    \n    #make sure we have nonzero particle number\n    assert pd_table.data.shape[0]>0\n    return pd_table,na.sum(idx)\n\n\ndef add_fields():\n    \"\"\"Add three Eulerian fields Sunrise uses\"\"\"\n    def _MetalMass(field, data):\n        return data[\"Metallicity\"] * data[\"CellMassMsun\"]\n        \n    def _convMetalMass(data):\n        return 1.0\n    add_field(\"MetalMass\", function=_MetalMass,\n              convert_function=_convMetalMass)\n    def _initial_mass_cen_ostriker(field, data):\n        # SFR in a cell. This assumes stars were created by the Cen & Ostriker algorithm\n        # Check Grid_AddToDiskProfile.C and star_maker7.src\n        star_mass_ejection_fraction = data.ds.get_parameter(\"StarMassEjectionFraction\",float)\n        star_maker_minimum_dynamical_time = 3e6 # years, which will get divided out\n        dtForSFR = star_maker_minimum_dynamical_time / data.ds[\"years\"]\n        xv1 = ((data.ds[\"InitialTime\"] - data[\"creation_time\"])\n                / data[\"dynamical_time\"])\n        xv2 = ((data.ds[\"InitialTime\"] + dtForSFR - data[\"creation_time\"])\n                / data[\"dynamical_time\"])\n        denom = (1.0 - star_mass_ejection_fraction * (1.0 - (1.0 + xv1)*np.exp(-xv1)))\n        minitial = data[\"ParticleMassMsun\"] / denom\n        return minitial\n\n    add_field(\"InitialMassCenOstriker\", function=_initial_mass_cen_ostriker)\n\n\nclass position:\n    def __init__(self):\n        self.output_pos = 0\n        self.refined_pos = 0\n\nclass hilbert_state():\n    def __init__(self,dim=None,sgn=None,octant=None):\n        if dim is None: dim = [0,1,2]\n        if sgn is None: sgn = [1,1,1]\n        if octant is None: octant = 5\n        self.dim = dim\n        self.sgn = sgn\n        self.octant = octant\n    def flip(self,i):\n        self.sgn[i]*=-1\n    def swap(self,i,j):\n        temp = self.dim[i]\n        self.dim[i]=self.dim[j]\n        self.dim[j]=temp\n        axis = self.sgn[i]\n        self.sgn[i] = self.sgn[j]\n        self.sgn[j] = axis\n    def reorder(self,i,j,k):\n        ndim = [self.dim[i],self.dim[j],self.dim[k]] \n        nsgn = [self.sgn[i],self.sgn[j],self.sgn[k]]\n        self.dim = ndim\n        self.sgn = nsgn\n    def copy(self):\n        return hilbert_state([self.dim[0],self.dim[1],self.dim[2]],\n                             [self.sgn[0],self.sgn[1],self.sgn[2]],\n                             self.octant)\n    def descend(self,o):\n        child = self.copy()\n        child.octant = o\n        if o==0:\n            child.swap(0,2)\n        elif o==1:\n            child.swap(1,2)\n        elif o==2:\n            pass\n        elif o==3:\n            child.flip(0)\n            child.flip(2)\n            child.reorder(2,0,1)\n        elif o==4:\n            child.flip(0)\n            child.flip(1)\n            child.reorder(2,0,1)\n        elif o==5:\n            pass\n        elif o==6:\n            child.flip(1)\n            child.flip(2)\n            child.swap(1,2)\n        elif o==7:\n            child.flip(0)\n            child.flip(2)\n            child.swap(0,2)\n        return child\n\n    def __iter__(self):\n        vertex = [0,0,0]\n        j=0\n        for i in range(3):\n            vertex[self.dim[i]] = 0 if self.sgn[i]>0 else 1\n        yield vertex, self.descend(j)\n        vertex[self.dim[0]] += self.sgn[0]\n        j+=1\n        yield vertex, self.descend(j)\n        vertex[self.dim[1]] += self.sgn[1] \n        j+=1\n        yield vertex, self.descend(j)\n        vertex[self.dim[0]] -= self.sgn[0] \n        j+=1\n        yield vertex, self.descend(j)\n        vertex[self.dim[2]] += self.sgn[2] \n        j+=1\n        yield vertex, self.descend(j)\n        vertex[self.dim[0]] += self.sgn[0] \n        j+=1\n        yield vertex, self.descend(j)\n        vertex[self.dim[1]] -= self.sgn[1] \n        j+=1\n        yield vertex, self.descend(j)\n        vertex[self.dim[0]] -= self.sgn[0] \n        j+=1\n        yield vertex, self.descend(j)\n\n", "meta": {"hexsha": "3f2de4defd15d4e47404349602332f549a256bc8", "size": 26090, "ext": "py", "lang": "Python", "max_stars_repo_path": "yt/analysis_modules/sunrise_export/sunrise_exporter.py", "max_stars_repo_name": "danielgrassinger/yt_new_frontend", "max_stars_repo_head_hexsha": "5f91d2fb8721c4c5da0af543a6256ed979cd9fc9", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "yt/analysis_modules/sunrise_export/sunrise_exporter.py", "max_issues_repo_name": "danielgrassinger/yt_new_frontend", "max_issues_repo_head_hexsha": "5f91d2fb8721c4c5da0af543a6256ed979cd9fc9", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-04-05T22:30:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-05T22:30:14.000Z", "max_forks_repo_path": "yt/analysis_modules/sunrise_export/sunrise_exporter.py", "max_forks_repo_name": "danielgrassinger/yt_new_frontend", "max_forks_repo_head_hexsha": "5f91d2fb8721c4c5da0af543a6256ed979cd9fc9", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-05T05:51:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-05T05:51:09.000Z", "avg_line_length": 39.3514328808, "max_line_length": 111, "alphanum_fraction": 0.5972019931, "include": true, "reason": "import numpy", "num_tokens": 7106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.34864512179822543, "lm_q1q2_score": 0.1986763470593305}}
{"text": "# -*- coding: utf-8 -*-\n\n# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is\n# holder of all proprietary rights on this computer program.\n# You can only use this computer program if you have closed\n# a license agreement with MPG or you get the right to use the computer\n# program from someone who is authorized to grant you that right.\n# Any use of the computer program without a valid license is prohibited and\n# liable to prosecution.\n#\n# Copyright©2019 Max-Planck-Gesellschaft zur Förderung\n# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute\n# for Intelligent Systems. All rights reserved.\n#\n# Contact: ps-license@tuebingen.mpg.de\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport numpy as np\n\nimport torch\nimport torch.nn.functional as F\n\n\ndef rot_mat_to_euler(rot_mats):\n    # Calculates rotation matrix to euler angles\n    # Careful for extreme cases of eular angles like [0.0, pi, 0.0]\n\n    sy = torch.sqrt(rot_mats[:, 0, 0] * rot_mats[:, 0, 0] +\n                    rot_mats[:, 1, 0] * rot_mats[:, 1, 0])\n    return torch.atan2(-rot_mats[:, 2, 0], sy)\n\n\ndef find_dynamic_lmk_idx_and_bcoords(vertices, pose, dynamic_lmk_faces_idx,\n                                     dynamic_lmk_b_coords,\n                                     neck_kin_chain, dtype=torch.float32):\n    ''' Compute the faces, barycentric coordinates for the dynamic landmarks\n\n\n        To do so, we first compute the rotation of the neck around the y-axis\n        and then use a pre-computed look-up table to find the faces and the\n        barycentric coordinates that will be used.\n\n        Special thanks to Soubhik Sanyal (soubhik.sanyal@tuebingen.mpg.de)\n        for providing the original TensorFlow implementation and for the LUT.\n\n        Parameters\n        ----------\n        vertices: torch.tensor BxVx3, dtype = torch.float32\n            The tensor of input vertices\n        pose: torch.tensor Bx(Jx3), dtype = torch.float32\n            The current pose of the body model\n        dynamic_lmk_faces_idx: torch.tensor L, dtype = torch.long\n            The look-up table from neck rotation to faces\n        dynamic_lmk_b_coords: torch.tensor Lx3, dtype = torch.float32\n            The look-up table from neck rotation to barycentric coordinates\n        neck_kin_chain: list\n            A python list that contains the indices of the joints that form the\n            kinematic chain of the neck.\n        dtype: torch.dtype, optional\n\n        Returns\n        -------\n        dyn_lmk_faces_idx: torch.tensor, dtype = torch.long\n            A tensor of size BxL that contains the indices of the faces that\n            will be used to compute the current dynamic landmarks.\n        dyn_lmk_b_coords: torch.tensor, dtype = torch.float32\n            A tensor of size BxL that contains the indices of the faces that\n            will be used to compute the current dynamic landmarks.\n    '''\n\n    batch_size = vertices.shape[0]\n\n    aa_pose = torch.index_select(pose.view(batch_size, -1, 3), 1,\n                                 neck_kin_chain)\n    rot_mats = batch_rodrigues(\n        aa_pose.view(-1, 3), dtype=dtype).view(batch_size, -1, 3, 3)\n\n    rel_rot_mat = torch.eye(\n        3, device=vertices.device, dtype=dtype).unsqueeze_(dim=0).repeat(\n        batch_size, 1, 1)\n    for idx in range(len(neck_kin_chain)):\n        rel_rot_mat = torch.bmm(rot_mats[:, idx], rel_rot_mat)\n\n    y_rot_angle = torch.round(\n        torch.clamp(-rot_mat_to_euler(rel_rot_mat) * 180.0 / np.pi,\n                    max=39)).to(dtype=torch.long)\n    neg_mask = y_rot_angle.lt(0).to(dtype=torch.long)\n    mask = y_rot_angle.lt(-39).to(dtype=torch.long)\n    neg_vals = mask * 78 + (1 - mask) * (39 - y_rot_angle)\n    y_rot_angle = (neg_mask * neg_vals +\n                   (1 - neg_mask) * y_rot_angle)\n\n    dyn_lmk_faces_idx = torch.index_select(dynamic_lmk_faces_idx,\n                                           0, y_rot_angle)\n    dyn_lmk_b_coords = torch.index_select(dynamic_lmk_b_coords,\n                                          0, y_rot_angle)\n\n    return dyn_lmk_faces_idx, dyn_lmk_b_coords\n\n\ndef vertices2landmarks(vertices, faces, lmk_faces_idx, lmk_bary_coords):\n    ''' Calculates landmarks by barycentric interpolation\n\n        Parameters\n        ----------\n        vertices: torch.tensor BxVx3, dtype = torch.float32\n            The tensor of input vertices\n        faces: torch.tensor Fx3, dtype = torch.long\n            The faces of the mesh\n        lmk_faces_idx: torch.tensor L, dtype = torch.long\n            The tensor with the indices of the faces used to calculate the\n            landmarks.\n        lmk_bary_coords: torch.tensor Lx3, dtype = torch.float32\n            The tensor of barycentric coordinates that are used to interpolate\n            the landmarks\n\n        Returns\n        -------\n        landmarks: torch.tensor BxLx3, dtype = torch.float32\n            The coordinates of the landmarks for each mesh in the batch\n    '''\n    # Extract the indices of the vertices for each face\n    # BxLx3\n    batch_size, num_verts = vertices.shape[:2]\n    device = vertices.device\n\n    lmk_faces = torch.index_select(faces, 0, lmk_faces_idx.view(-1)).view(\n        batch_size, -1, 3)\n\n    lmk_faces += torch.arange(\n        batch_size, dtype=torch.long, device=device).view(-1, 1, 1) * num_verts\n\n    lmk_vertices = vertices.view(-1, 3)[lmk_faces].view(\n        batch_size, -1, 3, 3)\n\n    landmarks = torch.einsum('blfi,blf->bli', [lmk_vertices, lmk_bary_coords])\n    return landmarks\n\n\ndef joints2bones(joints, parents):\n    ''' Decompose joints location to bone length and direction.\n\n        Parameters\n        ----------\n        joints: torch.tensor Bx24x3\n    '''\n    assert joints.shape[1] == parents.shape[0]\n    bone_dirs = torch.zeros_like(joints)\n    bone_lens = torch.zeros_like(joints[:, :, :1])\n\n    for c_id in range(parents.shape[0]):\n        p_id = parents[c_id]\n        if p_id == -1:\n            # Parent node\n            bone_dirs[:, c_id] = joints[:, c_id]\n        else:\n            # Child node\n            # (B, 3)\n            diff = joints[:, c_id] - joints[:, p_id]\n            length = torch.norm(diff, dim=1, keepdim=True) + 1e-8\n            direct = diff / length\n\n            bone_dirs[:, c_id] = direct\n            bone_lens[:, c_id] = length\n\n    return bone_dirs, bone_lens\n\n\ndef bones2joints(bone_dirs, bone_lens, parents):\n    ''' Recover bone length and direction to joints location.\n\n        Parameters\n        ----------\n        bone_dirs: torch.tensor 1x24x3\n        bone_lens: torch.tensor Bx24x1\n    '''\n    batch_size = bone_lens.shape[0]\n    joints = torch.zeros_like(bone_dirs).expand(batch_size, 24, 3)\n\n    for c_id in range(parents.shape[0]):\n        p_id = parents[c_id]\n        if p_id == -1:\n            # Parent node\n            joints[:, c_id] = bone_dirs[:, c_id]\n        else:\n            # Child node\n            joints[:, c_id] = joints[:, p_id] + bone_dirs[:, c_id] * bone_lens[:, c_id]\n\n    return joints\n\n\ndef lbs(betas, pose, v_template, shapedirs, posedirs, J_regressor, J_regressor_h36m, parents,\n        lbs_weights, pose2rot=True, dtype=torch.float32):\n    ''' Performs Linear Blend Skinning with the given shape and pose parameters\n\n        Parameters\n        ----------\n        betas : torch.tensor BxNB\n            The tensor of shape parameters\n        pose : torch.tensor Bx(J + 1) * 3\n            The pose parameters in axis-angle format\n        v_template torch.tensor BxVx3\n            The template mesh that will be deformed\n        shapedirs : torch.tensor 1xNB\n            The tensor of PCA shape displacements\n        posedirs : torch.tensor Px(V * 3)\n            The pose PCA coefficients\n        J_regressor : torch.tensor JxV\n            The regressor array that is used to calculate the joints from\n            the position of the vertices\n        parents: torch.tensor J\n            The array that describes the kinematic tree for the model\n        lbs_weights: torch.tensor N x V x (J + 1)\n            The linear blend skinning weights that represent how much the\n            rotation matrix of each part affects each vertex\n        pose2rot: bool, optional\n            Flag on whether to convert the input pose tensor to rotation\n            matrices. The default value is True. If False, then the pose tensor\n            should already contain rotation matrices and have a size of\n            Bx(J + 1)x9\n        dtype: torch.dtype, optional\n\n        Returns\n        -------\n        verts: torch.tensor BxVx3\n            The vertices of the mesh after applying the shape and pose\n            displacements.\n        joints: torch.tensor BxJx3\n            The joints of the model\n        rot_mats: torch.tensor BxJx3x3\n            The rotation matrics of each joints\n    '''\n    batch_size = max(betas.shape[0], pose.shape[0])\n    device = betas.device\n\n    # Add shape contribution\n    v_shaped = v_template + blend_shapes(betas, shapedirs)\n\n    # Get the joints\n    # NxJx3 array\n    J = vertices2joints(J_regressor, v_shaped)\n\n    # 3. Add pose blend shapes\n    # N x J x 3 x 3\n    ident = torch.eye(3, dtype=dtype, device=device)\n    if pose2rot:\n        if pose.numel() == batch_size * 24 * 4:\n            rot_mats = quat_to_rotmat(pose.reshape(batch_size * 24, 4)).reshape(batch_size, 24, 3, 3)\n        else:\n            rot_mats = batch_rodrigues(\n                pose.view(-1, 3), dtype=dtype).view([batch_size, -1, 3, 3])\n\n        pose_feature = (rot_mats[:, 1:, :, :] - ident).view([batch_size, -1])\n        # (N x P) x (P, V * 3) -> N x V x 3\n        pose_offsets = torch.matmul(pose_feature, posedirs) \\\n            .view(batch_size, -1, 3)\n    else:\n        pose_feature = pose[:, 1:].view(batch_size, -1, 3, 3) - ident\n        rot_mats = pose.view(batch_size, -1, 3, 3)\n\n        pose_offsets = torch.matmul(pose_feature.view(batch_size, -1),\n                                    posedirs).view(batch_size, -1, 3)\n\n    v_posed = pose_offsets + v_shaped\n    # 4. Get the global joint location\n    J_transformed, A = batch_rigid_transform(rot_mats, J, parents[:24], dtype=dtype)\n\n    # 5. Do skinning:\n    # W is N x V x (J + 1)\n    W = lbs_weights.unsqueeze(dim=0).expand([batch_size, -1, -1])\n    # (N x V x (J + 1)) x (N x (J + 1) x 16)\n    num_joints = J_regressor.shape[0]\n    T = torch.matmul(W, A.view(batch_size, num_joints, 16)) \\\n        .view(batch_size, -1, 4, 4)\n\n    homogen_coord = torch.ones([batch_size, v_posed.shape[1], 1],\n                               dtype=dtype, device=device)\n    v_posed_homo = torch.cat([v_posed, homogen_coord], dim=2)\n    v_homo = torch.matmul(T, torch.unsqueeze(v_posed_homo, dim=-1))\n\n    verts = v_homo[:, :, :3, 0]\n\n    J_from_verts = vertices2joints(J_regressor_h36m, verts)\n\n    return verts, J_transformed, rot_mats, J_from_verts\n\n\ndef hybrik(betas, global_orient, pose_skeleton, phis,\n           v_template, shapedirs, posedirs, J_regressor, J_regressor_h36m, parents, children,\n           lbs_weights, dtype=torch.float32, train=False, leaf_thetas=None):\n    ''' Performs Linear Blend Skinning with the given shape and skeleton joints\n\n        Parameters\n        ----------\n        betas : torch.tensor BxNB\n            The tensor of shape parameters\n        global_orient : torch.tensor Bx3\n            The tensor of global orientation\n        pose_skeleton : torch.tensor BxJ*3\n            The pose skeleton in (X, Y, Z) format\n        phis : torch.tensor BxJx2\n            The rotation on bone axis parameters\n        v_template torch.tensor BxVx3\n            The template mesh that will be deformed\n        shapedirs : torch.tensor 1xNB\n            The tensor of PCA shape displacements\n        posedirs : torch.tensor Px(V * 3)\n            The pose PCA coefficients\n        J_regressor : torch.tensor JxV\n            The regressor array that is used to calculate the joints from\n            the position of the vertices\n        J_regressor_h36m : torch.tensor 17xV\n            The regressor array that is used to calculate the 17 Human3.6M joints from\n            the position of the vertices\n        parents: torch.tensor J\n            The array that describes the kinematic parents for the model\n        children: dict\n            The dictionary that describes the kinematic chidrens for the model\n        lbs_weights: torch.tensor N x V x (J + 1)\n            The linear blend skinning weights that represent how much the\n            rotation matrix of each part affects each vertex\n        dtype: torch.dtype, optional\n\n        Returns\n        -------\n        verts: torch.tensor BxVx3\n            The vertices of the mesh after applying the shape and pose\n            displacements.\n        joints: torch.tensor BxJx3\n            The joints of the model\n        rot_mats: torch.tensor BxJx3x3\n            The rotation matrics of each joints\n    '''\n    batch_size = max(betas.shape[0], pose_skeleton.shape[0])\n    device = betas.device\n\n    # 1. Add shape contribution\n    v_shaped = v_template + blend_shapes(betas, shapedirs)\n\n    # 2. Get the rest joints\n    # NxJx3 array\n    if leaf_thetas is not None:\n        rest_J = vertices2joints(J_regressor, v_shaped)\n    else:\n        rest_J = torch.zeros((v_shaped.shape[0], 29, 3), dtype=dtype, device=device)\n        rest_J[:, :24] = vertices2joints(J_regressor, v_shaped)\n\n        leaf_number = [411, 2445, 5905, 3216, 6617]\n        leaf_vertices = v_shaped[:, leaf_number].clone()\n        rest_J[:, 24:] = leaf_vertices\n\n    # 3. Get the rotation matrics\n    rot_mats, rotate_rest_pose = batch_inverse_kinematics_transform(\n        pose_skeleton, global_orient, phis,\n        rest_J.clone(), children, parents, dtype=dtype, train=train,\n        leaf_thetas=leaf_thetas)\n\n    test_joints = True\n    if test_joints:\n        J_transformed, A = batch_rigid_transform(rot_mats, rest_J[:, :24].clone(), parents[:24], dtype=dtype)\n    else:\n        J_transformed = None\n\n    # assert torch.mean(torch.abs(rotate_rest_pose - J_transformed)) < 1e-5\n    # 4. Add pose blend shapes\n    # rot_mats: N x (J + 1) x 3 x 3\n    ident = torch.eye(3, dtype=dtype, device=device)\n    pose_feature = (rot_mats[:, 1:] - ident).view([batch_size, -1])\n    pose_offsets = torch.matmul(pose_feature, posedirs) \\\n        .view(batch_size, -1, 3)\n\n    v_posed = pose_offsets + v_shaped\n\n    # 5. Do skinning:\n    # W is N x V x (J + 1)\n    W = lbs_weights.unsqueeze(dim=0).expand([batch_size, -1, -1])\n    # (N x V x (J + 1)) x (N x (J + 1) x 16)\n    num_joints = J_regressor.shape[0]\n    T = torch.matmul(W, A.view(batch_size, num_joints, 16)) \\\n        .view(batch_size, -1, 4, 4)\n\n    homogen_coord = torch.ones([batch_size, v_posed.shape[1], 1],\n                               dtype=dtype, device=device)\n    v_posed_homo = torch.cat([v_posed, homogen_coord], dim=2)\n    v_homo = torch.matmul(T, torch.unsqueeze(v_posed_homo, dim=-1))\n\n    verts = v_homo[:, :, :3, 0]\n    J_from_verts_h36m = vertices2joints(J_regressor_h36m, verts)\n\n    return verts, J_transformed, rot_mats, J_from_verts_h36m\n\n\ndef vertices2joints(J_regressor, vertices):\n    ''' Calculates the 3D joint locations from the vertices\n\n    Parameters\n    ----------\n    J_regressor : torch.tensor JxV\n        The regressor array that is used to calculate the joints from the\n        position of the vertices\n    vertices : torch.tensor BxVx3\n        The tensor of mesh vertices\n\n    Returns\n    -------\n    torch.tensor BxJx3\n        The location of the joints\n    '''\n\n    return torch.einsum('bik,ji->bjk', [vertices, J_regressor])\n\n\ndef blend_shapes(betas, shape_disps):\n    ''' Calculates the per vertex displacement due to the blend shapes\n\n\n    Parameters\n    ----------\n    betas : torch.tensor Bx(num_betas)\n        Blend shape coefficients\n    shape_disps: torch.tensor Vx3x(num_betas)\n        Blend shapes\n\n    Returns\n    -------\n    torch.tensor BxVx3\n        The per-vertex displacement due to shape deformation\n    '''\n\n    # Displacement[b, m, k] = sum_{l} betas[b, l] * shape_disps[m, k, l]\n    # i.e. Multiply each shape displacement by its corresponding beta and\n    # then sum them.\n    blend_shape = torch.einsum('bl,mkl->bmk', [betas, shape_disps])\n    return blend_shape\n\n\ndef batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32):\n    ''' Calculates the rotation matrices for a batch of rotation vectors\n        Parameters\n        ----------\n        rot_vecs: torch.tensor Nx3\n            array of N axis-angle vectors\n        Returns\n        -------\n        R: torch.tensor Nx3x3\n            The rotation matrices for the given axis-angle parameters\n    '''\n\n    batch_size = rot_vecs.shape[0]\n    device = rot_vecs.device\n\n    angle = torch.norm(rot_vecs + 1e-8, dim=1, keepdim=True)\n    rot_dir = rot_vecs / angle\n\n    cos = torch.unsqueeze(torch.cos(angle), dim=1)\n    sin = torch.unsqueeze(torch.sin(angle), dim=1)\n\n    # Bx1 arrays\n    rx, ry, rz = torch.split(rot_dir, 1, dim=1)\n    K = torch.zeros((batch_size, 3, 3), dtype=dtype, device=device)\n\n    zeros = torch.zeros((batch_size, 1), dtype=dtype, device=device)\n    K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \\\n        .view((batch_size, 3, 3))\n\n    ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0)\n    rot_mat = ident + sin * K + (1 - cos) * torch.bmm(K, K)\n    return rot_mat\n\n\ndef transform_mat(R, t):\n    ''' Creates a batch of transformation matrices\n        Args:\n            - R: Bx3x3 array of a batch of rotation matrices\n            - t: Bx3x1 array of a batch of translation vectors\n        Returns:\n            - T: Bx4x4 Transformation matrix\n    '''\n    # No padding left or right, only add an extra row\n    return torch.cat([F.pad(R, [0, 0, 0, 1]),\n                      F.pad(t, [0, 0, 0, 1], value=1)], dim=2)\n\n\ndef batch_rigid_transform(rot_mats, joints, parents, dtype=torch.float32):\n    \"\"\"\n    Applies a batch of rigid transformations to the joints\n\n    Parameters\n    ----------\n    rot_mats : torch.tensor BxNx3x3\n        Tensor of rotation matrices\n    joints : torch.tensor BxNx3\n        Locations of joints. (Template Pose)\n    parents : torch.tensor BxN\n        The kinematic tree of each object\n    dtype : torch.dtype, optional:\n        The data type of the created tensors, the default is torch.float32\n\n    Returns\n    -------\n    posed_joints : torch.tensor BxNx3\n        The locations of the joints after applying the pose rotations\n    rel_transforms : torch.tensor BxNx4x4\n        The relative (with respect to the root joint) rigid transformations\n        for all the joints\n    \"\"\"\n    joints = torch.unsqueeze(joints, dim=-1)\n    rel_joints = joints.clone()\n    rel_joints[:, 1:] -= joints[:, parents[1:]].clone()\n\n    # (B, K + 1, 4, 4)\n    transforms_mat = transform_mat(\n        rot_mats.reshape(-1, 3, 3),\n        rel_joints.reshape(-1, 3, 1)).reshape(-1, joints.shape[1], 4, 4)\n\n    transform_chain = [transforms_mat[:, 0]]\n    for i in range(1, parents.shape[0]):\n        # Subtract the joint location at the rest pose\n        # No need for rotation, since it's identity when at rest\n        # (B, 4, 4) x (B, 4, 4)\n        curr_res = torch.matmul(transform_chain[parents[i]],\n                                transforms_mat[:, i])\n        transform_chain.append(curr_res)\n\n    # (B, K + 1, 4, 4)\n    transforms = torch.stack(transform_chain, dim=1)\n\n    # The last column of the transformations contains the posed joints\n    posed_joints = transforms[:, :, :3, 3]\n\n    # The last column of the transformations contains the posed joints\n    posed_joints = transforms[:, :, :3, 3]\n\n    joints_homogen = F.pad(joints, [0, 0, 0, 1])\n\n    rel_transforms = transforms - F.pad(\n        torch.matmul(transforms, joints_homogen), [3, 0, 0, 0, 0, 0, 0, 0])\n\n    return posed_joints, rel_transforms\n\n\ndef batch_inverse_kinematics_transform(\n        pose_skeleton, global_orient,\n        phis,\n        rest_pose,\n        children, parents, dtype=torch.float32, train=False,\n        leaf_thetas=None):\n    \"\"\"\n    Applies a batch of inverse kinematics transfoirm to the joints\n\n    Parameters\n    ----------\n    pose_skeleton : torch.tensor BxNx3\n        Locations of estimated pose skeleton.\n    global_orient : torch.tensor Bx1x3x3\n        Tensor of global rotation matrices\n    phis : torch.tensor BxNx2\n        The rotation on bone axis parameters\n    rest_pose : torch.tensor Bx(N+1)x3\n        Locations of rest_pose. (Template Pose)\n    children: dict\n        The dictionary that describes the kinematic chidrens for the model\n    parents : torch.tensor Bx(N+1)\n        The kinematic tree of each object\n    dtype : torch.dtype, optional:\n        The data type of the created tensors, the default is torch.float32\n\n    Returns\n    -------\n    rot_mats: torch.tensor Bx(N+1)x3x3\n        The rotation matrics of each joints\n    rel_transforms : torch.tensor Bx(N+1)x4x4\n        The relative (with respect to the root joint) rigid transformations\n        for all the joints\n    \"\"\"\n    batch_size = pose_skeleton.shape[0]\n    device = pose_skeleton.device\n\n    rel_rest_pose = rest_pose.clone()\n    rel_rest_pose[:, 1:] -= rest_pose[:, parents[1:]].clone()\n    rel_rest_pose = torch.unsqueeze(rel_rest_pose, dim=-1)\n\n    # rotate the T pose\n    rotate_rest_pose = torch.zeros_like(rel_rest_pose)\n    # set up the root\n    rotate_rest_pose[:, 0] = rel_rest_pose[:, 0]\n\n    rel_pose_skeleton = torch.unsqueeze(pose_skeleton.clone(), dim=-1).detach()\n    rel_pose_skeleton[:, 1:] = rel_pose_skeleton[:, 1:] - rel_pose_skeleton[:, parents[1:]].clone()\n    rel_pose_skeleton[:, 0] = rel_rest_pose[:, 0]\n\n    # the predicted final pose\n    final_pose_skeleton = torch.unsqueeze(pose_skeleton.clone(), dim=-1)\n    final_pose_skeleton = final_pose_skeleton - final_pose_skeleton[:, 0:1] + rel_rest_pose[:, 0:1]\n\n    rel_rest_pose = rel_rest_pose\n    rel_pose_skeleton = rel_pose_skeleton\n    final_pose_skeleton = final_pose_skeleton\n    rotate_rest_pose = rotate_rest_pose\n\n    assert phis.dim() == 3\n    phis = phis / (torch.norm(phis, dim=2, keepdim=True) + 1e-8)\n\n    # TODO\n    if train:\n        global_orient_mat = batch_get_pelvis_orient(\n            rel_pose_skeleton.clone(), rel_rest_pose.clone(), parents, children, dtype)\n    else:\n        global_orient_mat = batch_get_pelvis_orient_svd(\n            rel_pose_skeleton.clone(), rel_rest_pose.clone(), parents, children, dtype)\n\n    rot_mat_chain = [global_orient_mat]\n    rot_mat_local = [global_orient_mat]\n    # leaf nodes rot_mats\n    if leaf_thetas is not None:\n        leaf_cnt = 0\n        leaf_rot_mats = leaf_thetas.view([batch_size, 5, 3, 3])\n\n    for i in range(1, parents.shape[0]):\n        if children[i] == -1:\n            # leaf nodes\n            if leaf_thetas is not None:\n                rot_mat = leaf_rot_mats[:, leaf_cnt, :, :]\n                leaf_cnt += 1\n\n                rotate_rest_pose[:, i] = rotate_rest_pose[:, parents[i]] + torch.matmul(\n                    rot_mat_chain[parents[i]],\n                    rel_rest_pose[:, i]\n                )\n\n                rot_mat_chain.append(torch.matmul(\n                    rot_mat_chain[parents[i]],\n                    rot_mat))\n                rot_mat_local.append(rot_mat)\n        elif children[i] == -3:\n            # three children\n            rotate_rest_pose[:, i] = rotate_rest_pose[:, parents[i]] + torch.matmul(\n                rot_mat_chain[parents[i]],\n                rel_rest_pose[:, i]\n            )\n\n            spine_child = []\n            for c in range(1, parents.shape[0]):\n                if parents[c] == i and c not in spine_child:\n                    spine_child.append(c)\n\n            # original\n            spine_child = []\n            for c in range(1, parents.shape[0]):\n                if parents[c] == i and c not in spine_child:\n                    spine_child.append(c)\n\n            children_final_loc = []\n            children_rest_loc = []\n            for c in spine_child:\n                temp = final_pose_skeleton[:, c] - rotate_rest_pose[:, i]\n                children_final_loc.append(temp)\n\n                children_rest_loc.append(rel_rest_pose[:, c].clone())\n\n            rot_mat = batch_get_3children_orient_svd(\n                children_final_loc, children_rest_loc,\n                rot_mat_chain[parents[i]], spine_child, dtype)\n\n            rot_mat_chain.append(\n                torch.matmul(\n                    rot_mat_chain[parents[i]],\n                    rot_mat)\n            )\n            rot_mat_local.append(rot_mat)\n        else:\n            # (B, 3, 1)\n            rotate_rest_pose[:, i] = rotate_rest_pose[:, parents[i]] + torch.matmul(\n                rot_mat_chain[parents[i]],\n                rel_rest_pose[:, i]\n            )\n            # (B, 3, 1)\n            child_final_loc = final_pose_skeleton[:, children[i]] - rotate_rest_pose[:, i]\n\n            if not train:\n                orig_vec = rel_pose_skeleton[:, children[i]]\n                template_vec = rel_rest_pose[:, children[i]]\n                norm_t = torch.norm(template_vec, dim=1, keepdim=True)\n                orig_vec = orig_vec * norm_t / torch.norm(orig_vec, dim=1, keepdim=True)\n\n                diff = torch.norm(child_final_loc - orig_vec, dim=1, keepdim=True)\n                big_diff_idx = torch.where(diff > 15 / 1000)[0]\n\n                child_final_loc[big_diff_idx] = orig_vec[big_diff_idx]\n\n            child_final_loc = torch.matmul(\n                rot_mat_chain[parents[i]].transpose(1, 2),\n                child_final_loc)\n\n            child_rest_loc = rel_rest_pose[:, children[i]]\n            # (B, 1, 1)\n            child_final_norm = torch.norm(child_final_loc, dim=1, keepdim=True)\n            child_rest_norm = torch.norm(child_rest_loc, dim=1, keepdim=True)\n\n            child_final_norm = torch.norm(child_final_loc, dim=1, keepdim=True)\n\n            # (B, 3, 1)\n            axis = torch.cross(child_rest_loc, child_final_loc, dim=1)\n            axis_norm = torch.norm(axis, dim=1, keepdim=True)\n\n            # (B, 1, 1)\n            cos = torch.sum(child_rest_loc * child_final_loc, dim=1, keepdim=True) / (child_rest_norm * child_final_norm + 1e-8)\n            sin = axis_norm / (child_rest_norm * child_final_norm + 1e-8)\n\n            # (B, 3, 1)\n            axis = axis / (axis_norm + 1e-8)\n\n            # Convert location revolve to rot_mat by rodrigues\n            # (B, 1, 1)\n            rx, ry, rz = torch.split(axis, 1, dim=1)\n            zeros = torch.zeros((batch_size, 1, 1), dtype=dtype, device=device)\n\n            K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \\\n                .view((batch_size, 3, 3))\n            ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0)\n            rot_mat_loc = ident + sin * K + (1 - cos) * torch.bmm(K, K)\n\n            # Convert spin to rot_mat\n            # (B, 3, 1)\n            spin_axis = child_rest_loc / child_rest_norm\n            # (B, 1, 1)\n            rx, ry, rz = torch.split(spin_axis, 1, dim=1)\n            zeros = torch.zeros((batch_size, 1, 1), dtype=dtype, device=device)\n            K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \\\n                .view((batch_size, 3, 3))\n            ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0)\n            # (B, 1, 1)\n            cos, sin = torch.split(phis[:, i - 1], 1, dim=1)\n            cos = torch.unsqueeze(cos, dim=2)\n            sin = torch.unsqueeze(sin, dim=2)\n            rot_mat_spin = ident + sin * K + (1 - cos) * torch.bmm(K, K)\n            rot_mat = torch.matmul(rot_mat_loc, rot_mat_spin)\n\n            rot_mat_chain.append(torch.matmul(\n                rot_mat_chain[parents[i]],\n                rot_mat))\n            rot_mat_local.append(rot_mat)\n\n    # (B, K + 1, 3, 3)\n    rot_mats = torch.stack(rot_mat_local, dim=1)\n\n    return rot_mats, rotate_rest_pose.squeeze(-1)\n\n\ndef batch_get_pelvis_orient_svd(rel_pose_skeleton, rel_rest_pose, parents, children, dtype):\n    pelvis_child = [int(children[0])]\n    for i in range(1, parents.shape[0]):\n        if parents[i] == 0 and i not in pelvis_child:\n            pelvis_child.append(i)\n\n    rest_mat = []\n    target_mat = []\n    for child in pelvis_child:\n        rest_mat.append(rel_rest_pose[:, child].clone())\n        target_mat.append(rel_pose_skeleton[:, child].clone())\n\n    rest_mat = torch.cat(rest_mat, dim=2)\n    target_mat = torch.cat(target_mat, dim=2)\n    S = rest_mat.bmm(target_mat.transpose(1, 2))\n\n    mask_zero = S.sum(dim=(1, 2))\n\n    S_non_zero = S[mask_zero != 0].reshape(-1, 3, 3)\n\n    U, _, V = torch.svd(S_non_zero)\n\n    rot_mat = torch.zeros_like(S)\n    rot_mat[mask_zero == 0] = torch.eye(3, device=S.device)\n\n    rot_mat_non_zero = torch.bmm(V, U.transpose(1, 2))\n    rot_mat[mask_zero != 0] = rot_mat_non_zero\n\n    assert torch.sum(torch.isnan(rot_mat)) == 0, ('rot_mat', rot_mat)\n\n    return rot_mat\n\n\ndef batch_get_pelvis_orient(rel_pose_skeleton, rel_rest_pose, parents, children, dtype):\n    batch_size = rel_pose_skeleton.shape[0]\n    device = rel_pose_skeleton.device\n\n    assert children[0] == 3\n    pelvis_child = [int(children[0])]\n    for i in range(1, parents.shape[0]):\n        if parents[i] == 0 and i not in pelvis_child:\n            pelvis_child.append(i)\n\n    spine_final_loc = rel_pose_skeleton[:, int(children[0])].clone()\n    spine_rest_loc = rel_rest_pose[:, int(children[0])].clone()\n    spine_norm = torch.norm(spine_final_loc, dim=1, keepdim=True)\n    spine_norm = spine_final_loc / (spine_norm + 1e-8)\n\n    rot_mat_spine = vectors2rotmat(spine_rest_loc, spine_final_loc, dtype)\n\n    assert torch.sum(torch.isnan(rot_mat_spine)\n                     ) == 0, ('rot_mat_spine', rot_mat_spine)\n    center_final_loc = 0\n    center_rest_loc = 0\n    for child in pelvis_child:\n        if child == int(children[0]):\n            continue\n        center_final_loc = center_final_loc + rel_pose_skeleton[:, child].clone()\n        center_rest_loc = center_rest_loc + rel_rest_pose[:, child].clone()\n    center_final_loc = center_final_loc / (len(pelvis_child) - 1)\n    center_rest_loc = center_rest_loc / (len(pelvis_child) - 1)\n\n    center_rest_loc = torch.matmul(rot_mat_spine, center_rest_loc)\n\n    center_final_loc = center_final_loc - torch.sum(center_final_loc * spine_norm, dim=1, keepdim=True) * spine_norm\n    center_rest_loc = center_rest_loc - torch.sum(center_rest_loc * spine_norm, dim=1, keepdim=True) * spine_norm\n\n    center_final_loc_norm = torch.norm(center_final_loc, dim=1, keepdim=True)\n    center_rest_loc_norm = torch.norm(center_rest_loc, dim=1, keepdim=True)\n\n    # (B, 3, 1)\n    axis = torch.cross(center_rest_loc, center_final_loc, dim=1)\n    axis_norm = torch.norm(axis, dim=1, keepdim=True)\n\n    # (B, 1, 1)\n    cos = torch.sum(center_rest_loc * center_final_loc, dim=1, keepdim=True) / (center_rest_loc_norm * center_final_loc_norm + 1e-8)\n    sin = axis_norm / (center_rest_loc_norm * center_final_loc_norm + 1e-8)\n\n    assert torch.sum(torch.isnan(cos)\n                     ) == 0, ('cos', cos)\n    assert torch.sum(torch.isnan(sin)\n                     ) == 0, ('sin', sin)\n    # (B, 3, 1)\n    axis = axis / (axis_norm + 1e-8)\n\n    # Convert location revolve to rot_mat by rodrigues\n    # (B, 1, 1)\n    rx, ry, rz = torch.split(axis, 1, dim=1)\n    zeros = torch.zeros((batch_size, 1, 1), dtype=dtype, device=device)\n\n    K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \\\n        .view((batch_size, 3, 3))\n    ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0)\n    rot_mat_center = ident + sin * K + (1 - cos) * torch.bmm(K, K)\n\n    rot_mat = torch.matmul(rot_mat_center, rot_mat_spine)\n\n    return rot_mat\n\n\ndef batch_get_3children_orient_svd(rel_pose_skeleton, rel_rest_pose, rot_mat_chain_parent, children_list, dtype):\n    rest_mat = []\n    target_mat = []\n    for c, child in enumerate(children_list):\n        if isinstance(rel_pose_skeleton, list):\n            target = rel_pose_skeleton[c].clone()\n            template = rel_rest_pose[c].clone()\n        else:\n            target = rel_pose_skeleton[:, child].clone()\n            template = rel_rest_pose[:, child].clone()\n\n        target = torch.matmul(\n            rot_mat_chain_parent.transpose(1, 2),\n            target)\n\n        target_mat.append(target)\n        rest_mat.append(template)\n\n    rest_mat = torch.cat(rest_mat, dim=2)\n    target_mat = torch.cat(target_mat, dim=2)\n    S = rest_mat.bmm(target_mat.transpose(1, 2))\n\n    U, _, V = torch.svd(S)\n\n    rot_mat = torch.bmm(V, U.transpose(1, 2))\n    assert torch.sum(torch.isnan(rot_mat)) == 0, ('3children rot_mat', rot_mat)\n    return rot_mat\n\n\ndef vectors2rotmat(vec_rest, vec_final, dtype):\n    batch_size = vec_final.shape[0]\n    device = vec_final.device\n\n    # (B, 1, 1)\n    vec_final_norm = torch.norm(vec_final, dim=1, keepdim=True)\n    vec_rest_norm = torch.norm(vec_rest, dim=1, keepdim=True)\n\n    # (B, 3, 1)\n    axis = torch.cross(vec_rest, vec_final, dim=1)\n    axis_norm = torch.norm(axis, dim=1, keepdim=True)\n\n    # (B, 1, 1)\n    cos = torch.sum(vec_rest * vec_final, dim=1, keepdim=True) / (vec_rest_norm * vec_final_norm + 1e-8)\n    sin = axis_norm / (vec_rest_norm * vec_final_norm + 1e-8)\n\n    # (B, 3, 1)\n    axis = axis / (axis_norm + 1e-8)\n\n    # Convert location revolve to rot_mat by rodrigues\n    # (B, 1, 1)\n    rx, ry, rz = torch.split(axis, 1, dim=1)\n    zeros = torch.zeros((batch_size, 1, 1), dtype=dtype, device=device)\n\n    K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \\\n        .view((batch_size, 3, 3))\n    ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0)\n    rot_mat_loc = ident + sin * K + (1 - cos) * torch.bmm(K, K)\n\n    return rot_mat_loc\n\n\ndef rotmat_to_quat(rotmat):\n    \"\"\"Convert rotation matrix to quaternion coefficients.\n    Args:\n        rotmat: size is [B, 3, 3]\n    Returns:\n        Quaternion: size is [B, 4] <===> (w, x, y, z)\n    \"\"\"\n    quaternion = torch.zeros([rotmat.size(0), 4], device=rotmat.device)\n    trace = rotmat[:, 0, 0] + rotmat[:, 1, 1] + rotmat[:, 2, 2]\n    flag = 1 + trace > 0\n    s = torch.zeros_like(trace)\n\n    # pos\n    s[flag] = 2 * torch.sqrt(1 + trace[flag]) + 1e-16\n    s_pos = s[flag]\n    quaternion[flag, 0] = s_pos / 4\n    quaternion[flag, 1] = (rotmat[flag, 2, 1] - rotmat[flag, 1, 2]) / s_pos\n    quaternion[flag, 2] = (rotmat[flag, 0, 2] - rotmat[flag, 2, 0]) / s_pos\n    quaternion[flag, 3] = (rotmat[flag, 1, 0] - rotmat[flag, 0, 1]) / s_pos\n\n    # neg\n    diag = torch.stack([rotmat[:, 0, 0], rotmat[:, 1, 1], rotmat[:, 2, 2]])\n    max_val, max_ind = torch.max(diag, dim=0)\n\n    s[~flag] = 2 * torch.sqrt(1 - trace[~flag] + 2 * max_val[~flag]) + 1e-16\n\n    f0 = ~flag * (max_ind == 0)\n    s0 = s[f0]\n    quaternion[f0, 0] = (rotmat[f0, 2, 1] - rotmat[f0, 1, 2]) / s0\n    quaternion[f0, 1] = s0 / 4\n    quaternion[f0, 2] = (rotmat[f0, 0, 1] + rotmat[f0, 1, 0]) / s0\n    quaternion[f0, 3] = (rotmat[f0, 0, 2] + rotmat[f0, 2, 0]) / s0\n\n    f1 = ~flag * (max_ind == 1)\n    s1 = s[f1]\n    quaternion[f1, 0] = (rotmat[f1, 0, 2] - rotmat[f1, 2, 0]) / s1\n    quaternion[f1, 1] = (rotmat[f1, 0, 1] + rotmat[f1, 1, 0]) / s1\n    quaternion[f1, 2] = s1 / 4\n    quaternion[f1, 3] = (rotmat[f1, 1, 2] + rotmat[f1, 2, 1]) / s1\n\n    f2 = ~flag * (max_ind == 2)\n    s2 = s[f2]\n    quaternion[f2, 0] = (rotmat[f2, 1, 0] - rotmat[f2, 0, 1]) / s2\n    quaternion[f2, 1] = (rotmat[f2, 0, 2] + rotmat[f2, 2, 0]) / s2\n    quaternion[f2, 2] = (rotmat[f2, 1, 2] + rotmat[f2, 2, 1]) / s2\n    quaternion[f2, 3] = s2 / 4\n\n    return quaternion\n\n\ndef quat_to_rotmat(quat):\n    \"\"\"Convert quaternion coefficients to rotation matrix.\n    Args:\n        quat: size = [B, 4] 4 <===>(w, x, y, z)\n    Returns:\n        Rotation matrix corresponding to the quaternion -- size = [B, 3, 3]\n    \"\"\"\n    norm_quat = quat\n    norm_quat = norm_quat / (norm_quat.norm(p=2, dim=1, keepdim=True) + 1e-8)\n    w, x, y, z = norm_quat[:, 0], norm_quat[:, 1], norm_quat[:, 2], norm_quat[:, 3]\n\n    B = quat.size(0)\n\n    w2, x2, y2, z2 = w.pow(2), x.pow(2), y.pow(2), z.pow(2)\n    wx, wy, wz = w * x, w * y, w * z\n    xy, xz, yz = x * y, x * z, y * z\n\n    rotMat = torch.stack([w2 + x2 - y2 - z2, 2 * xy - 2 * wz, 2 * wy + 2 * xz,\n                          2 * wz + 2 * xy, w2 - x2 + y2 - z2, 2 * yz - 2 * wx,\n                          2 * xz - 2 * wy, 2 * wx + 2 * yz, w2 - x2 - y2 + z2], dim=1).view(B, 3, 3)\n    return rotMat\n", "meta": {"hexsha": "3c6fbfec7934efec5e325a9d3596e4af10e43093", "size": 36374, "ext": "py", "lang": "Python", "max_stars_repo_path": "hybrik/models/layers/smpl/lbs.py", "max_stars_repo_name": "uyoung-jeong/HybrIK", "max_stars_repo_head_hexsha": "aff6aeda06e627fc48f7d7c2bffb2245393d7584", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 287, "max_stars_repo_stars_event_min_datetime": "2020-11-30T12:45:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:03:45.000Z", "max_issues_repo_path": "hybrik/models/layers/smpl/lbs.py", "max_issues_repo_name": "pengyun1314123/HybrIK", "max_issues_repo_head_hexsha": "ae1bc3cea0cc5aa98fb512eeb295c3478b0c598f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 62, "max_issues_repo_issues_event_min_datetime": "2021-01-08T02:06:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T11:55:58.000Z", "max_forks_repo_path": "hybrik/models/layers/smpl/lbs.py", "max_forks_repo_name": "pengyun1314123/HybrIK", "max_forks_repo_head_hexsha": "ae1bc3cea0cc5aa98fb512eeb295c3478b0c598f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2021-03-04T07:18:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T06:06:28.000Z", "avg_line_length": 36.9279187817, "max_line_length": 132, "alphanum_fraction": 0.6111783142, "include": true, "reason": "import numpy", "num_tokens": 10158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.1986763419655114}}
{"text": "#!/usr/bin/python\n\"\"\"\nDo MCMC runs to fit FG models to simulated data, over a grid of \n(nu_min, nu_max) values.\n\"\"\"\nimport numpy as np\nimport models\nimport model_list\nimport fitting\nfrom utils import rj2cmb, bands_log\nimport sys, time, os, copy\n#from multiprocessing import Pool\nfrom mpi4py import MPI\n\n# Set-up MPI\ncomm = MPI.COMM_WORLD\nmyid = comm.Get_rank()\nnproc = comm.Get_size()\n\n# Prefix for output files\nPREFIX = \"paper01\"\nNBURN = 500\nNSTEPS = 10000\nNWALKERS = 100\n\n# Reference noise curve (assumes noise file contains sigma_P=sigma_Q=sigma_U \n# in uK_CMB.deg for a given experiment)\nNOISE_FILE = \"data/noise_coreplus_extended.dat\"\n#NOISE_FILE = \"data/core_plus_extended_noise.dat\"\n\n# Band parameter definitions\nnbands = 7\nnthreads = 2\n\n# Set random seed\nSEED = 10\nif len(sys.argv) > 1:\n    SEED = int(sys.argv[1])\nprint \"SEED =\", SEED\nnp.random.seed(SEED)\n\n# Lists of input and output models\nin_list = ['cmb', ]; fit_list = ['cmb', ]\n\n# Define input models and their amplitudes/parameters\nallowed_comps = model_list.model_dict\ncmb_model = model_list.cmb_model\n\n# Parse args to define input and output models\nif len(sys.argv) > 2:\n    in_list += sys.argv[2].split(\",\")\n    fit_list += sys.argv[3].split(\",\")\nelse:\n    in_list = ['cmb', 'synch', 'mbb']\n    fit_list = ['cmb', 'synch', 'mbb']\n\n# Make sure models are of known types\nfor item in in_list:\n    if item not in allowed_comps.keys():\n        raise ValueError(\"Unknown component type '%s'\" % item)\nfor item in fit_list:\n    if item not in allowed_comps.keys():\n        raise ValueError(\"Unknown component type '%s'\" % item)\n\n# Print recognised models and specify name\nprint \"Input components:\", in_list\nprint \"Fitting components:\", fit_list\nname_in = \"-\".join(in_list)\nname_fit = \"-\".join(fit_list)\n\n# Frequency ranges\nnumin_vals = [20., 30., 40.]\nnumax_vals = [300., 400., 500., 600., 700., 800.]\n#numin_vals = [20., ]\n#numax_vals = [300., 700.]\n\n# Temperature/polarisation noise rms for all bands, as a fraction of T_cmb\nfsigma_T = 1e4 #1. / np.sqrt(2.)\nfsigma_P = 1.\n\n# Collect components into lists and set input amplitudes\nmods_in = [allowed_comps[comp] for comp in in_list]\nmods_fit = [allowed_comps[comp] for comp in fit_list]\namps_in = np.array([m.amps() for m in mods_in])\nparams_in = np.array([m.params() for m in mods_in])\n\n# Expand into all combinations of nu_min,max\nnu_min, nu_max = np.meshgrid(numin_vals, numax_vals)\nnu_params = np.column_stack((nu_min.flatten(), nu_max.flatten()))\n\n# Prepare output files for writing\nfilename = \"output/%s_summary_%s.%s_nb%d_seed%d\" \\\n             % (PREFIX, name_in, name_fit, nbands, SEED)\ncut_range = np.arange(NSTEPS, step=200)\nfor cut in cut_range:\n    fname = filename + \"_cut%d.dat\" % cut\n    f = open(fname, 'w')\n    f.close()\n\n\ndef model_test(nu, D_vec, Ninv, models_fit, initial_vals=None, burn=500, \n               steps=1000, nwalkers=100, cmb_amp_in=None, sample_file=None):\n    \"\"\"\n    Generate simulated data given an input model, and perform MCMC fit using \n    another model.\n    \"\"\"\n    # Collect together data and noise/instrument model\n    beam_mat = np.identity(3*len(nu)) # Beam model\n    data_spec = (nu, D_vec, Ninv, beam_mat)\n    \n    # Get a list of amplitude/parameter names and initial values\n    amp_names = []; amp_vals = []; param_names = []; param_vals = []\n    amp_parent_model = []; param_parent_model = []\n    for mod in models_fit:\n        # Parameter names\n        amp_names += [\"%s_%s\" % (mod.model, pol) for pol in \"IQU\"]\n        param_names += mod.param_names\n        \n        # Parameter values\n        amp_vals = np.concatenate( (amp_vals, mod.amps()) )\n        param_vals = np.concatenate( (param_vals, mod.params()) )\n        \n        # Parent model list\n        amp_parent_model.append(mod)\n        param_parent_model.append(mod)\n    \n    # Concatenate parameter lists\n    pnames = amp_names + param_names\n    pvals = np.concatenate((amp_vals, param_vals))\n    parent_model = amp_parent_model + param_parent_model\n    \n    # Use 'guess' as the initial point for the MCMC if specified        \n    if initial_vals is None: initial_vals = pvals\n    \n    # Collect names, initial values, and parent components for the parameters\n    param_spec = (pnames, initial_vals, parent_model)\n    \n    # Run MCMC sampler on this model\n    t0 = time.time()\n    pnames, samples, logp = fitting.joint_mcmc(data_spec, models_fit, param_spec, \n                                               burn=burn, steps=steps, \n                                               nwalkers=nwalkers, \n                                               nthreads=nthreads,\n                                               sample_file=sample_file)\n    print \"MCMC run in %d sec.\" % (time.time() - t0)\n    \n    # Return parameter names and samples\n    return pnames, samples, logp, initial_vals\n\n\ndef run_model(nu_params):\n    # Get band definition\n    nu_min, nu_max = nu_params\n    print \"nu_min = %d GHz, nu_max = %d GHz\" % (nu_min, nu_max)\n    nu = bands_log(nu_min, nu_max, nbands)\n    label = str(nu_min) + '_' + str(nu_max)\n    \n    # Make copies of models\n    my_mods_in = mods_in\n    my_mods_fit = mods_fit\n    \n    # Name of sample file\n    #fname_samples = \"output/%s_samples_%s.%s_nb%d_seed%d_%s.dat\" \\\n    #              % (PREFIX, name_in, name_fit, nbands, SEED, label)\n    fname_samples = None\n    \n    # Simulate data and run MCMC fit\n    D_vec, Ninv = fitting.generate_data(nu, fsigma_T, fsigma_P, \n                                        components=my_mods_in, \n                                        noise_file=NOISE_FILE)\n                                        \n    pnames, samples, logp, ini = model_test(nu, D_vec, Ninv, my_mods_fit, \n                                            burn=NBURN, steps=NSTEPS, \n                                            nwalkers=NWALKERS,\n                                            cmb_amp_in=cmb_model.amps(),\n                                            sample_file=fname_samples)\n    # Calculate best-fit chisq.\n    chisq = -2.*logp\n    dof = D_vec.size - len(pnames)\n    \n    # Get best-fit (max. prob.) parameter values\n    maxl_idx = np.argmax(logp)\n    bf_params = samples[:, maxl_idx]\n    \n    \n    # Reshape sample array into (Nparams, Nwalkers, Nsamples)\n    samples = samples.reshape((samples.shape[0], \n                               NWALKERS, \n                               samples.shape[1]/NWALKERS))\n    \n    # Loop over different burn-in cuts to produce summary stats\n    for n, cut in enumerate(cut_range):\n        \n        # Set output filename\n        fname = filename + \"_cut%d.dat\" % cut\n        \n        # Output mean and bias\n        summary_data = [nu_min, nu_max, np.min(chisq), maxl_idx]\n        header = \"nu_min nu_max chi2_min maxlike_idx \"\n        \n        # Loop over parameter names\n        for i in range(len(pnames)):\n            \n            # Mean, std. dev., and fractional shift from true value \n            # (for mean, median, and max. likelihood param values)\n            _mean = np.mean(samples[i,:,cut:])\n            _std = np.std(samples[i,:,cut:])\n            _fracbias = (np.mean(samples[i,:,cut:]) - ini[i]) \\\n                      / np.std(samples[i,:,cut:])\n            _med_fracbias = (np.median(samples[i,:,cut:]) - ini[i]) \\\n                          / np.std(samples[i,:,cut:])\n            _ml_fracbias = (bf_params[i] - ini[i]) / np.std(samples[i,:,cut:])\n            \n            stats = [_mean, _std, _fracbias, _med_fracbias, _ml_fracbias]\n            \n            # Keep summary stats, to be written to file\n            summary_data += stats\n            header += \"mean_%s std_%s Delta_%s MedDelta_%s MLDelta_%s \" \\\n                    % (pnames[i], pnames[i], pnames[i], pnames[i], pnames[i])\n            \n            # Only output summary stats once\n            if n == 0:\n                print \"%14s: %+3.3e +/- %3.3e [Delta = %+3.3f, MLDelta = %+3.3f]\" \\\n                      % (pnames[i], stats[0], stats[1], stats[2], stats[3])\n        \n        # If file is empty, set flag to write header when saving output\n        has_header = False if os.stat(fname).st_size == 0 else True\n        \n        # Append summary statistics to file\n        f = open(fname, 'a')\n        if has_header:\n            np.savetxt(f, np.atleast_2d(summary_data))\n        else:\n            np.savetxt(f, np.atleast_2d(summary_data), header=header[:-1])\n        f.close()\n\n# Run pool of processes\n#pool = Pool(NPROC)\n#pool.map(run_model, nu_params)\n\nfor i in range(len(nu_params)):\n    if i % nproc != myid: continue\n    \n    # Run the model for this set of params\n    run_model(nu_params[i])\n\n", "meta": {"hexsha": "247e8f29eb9ecd6f3e060188ad8b302c0d6294fb", "size": 8600, "ext": "py", "lang": "Python", "max_stars_repo_path": "run_joint_mcmc.py", "max_stars_repo_name": "philbull/SinglePixel", "max_stars_repo_head_hexsha": "0cd3dba84a0a36ab672707154d3cf8dde903872b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "run_joint_mcmc.py", "max_issues_repo_name": "philbull/SinglePixel", "max_issues_repo_head_hexsha": "0cd3dba84a0a36ab672707154d3cf8dde903872b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "run_joint_mcmc.py", "max_forks_repo_name": "philbull/SinglePixel", "max_forks_repo_head_hexsha": "0cd3dba84a0a36ab672707154d3cf8dde903872b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8178137652, "max_line_length": 83, "alphanum_fraction": 0.5979069767, "include": true, "reason": "import numpy", "num_tokens": 2231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.19863873458294368}}
{"text": "from typing import List, Tuple, Optional, Any\nimport time\nimport numba\nimport numpy as np\nimport cv2\nimport reeds_shepp\nfrom .debugger import Debugger\n\n\nclass RRTStar(object):\n    def __init__(self):\n        self.debug = False\n        self.vertices = None  # type: Optional[List[RRTStar.StateNode]]\n        self.root = None  # type: Optional[RRTStar.StateNode]\n        self.gain = None  # type: Optional[RRTStar.StateNode]\n        self.x_best = None  # type: Optional[RRTStar.StateNode]\n        self.epsilon = 1e-6\n\n        self.check_res = 0.3  # type: Optional[float]\n        self.check_poly = None  # type: Optional[np.ndarray]\n        self.exist_res = 0.1\n        self.maximum_curvature = 0.2  # type: Optional[float]\n\n        self.start = None  # type: Optional[RRTStar.StateNode]\n        self.goal = None  # type: Optional[RRTStar.StateNode]\n        self.grid_map = None  # type: Optional[np.ndarray]\n        self.grid_res = None  # type: Optional[float]\n        self.grid_ori = None  # type: Optional[RRTStar.StateNode]\n        self.obstacle = None  # type: Optional[int]\n        self.heuristic = None  # type: Optional[List[(Tuple[float], Tuple[float], Tuple[float])]]\n\n    def set_vehicle(self, check_poly, check_res, maximum_curvature):\n        # type: (np.ndarray, float, float) -> RRTStar\n        \"\"\"\n        set parameter of the vehicle\n        :param check_poly: contour of the vehicle for collision check. cv2.contour.\n        :param check_res: the resolution of curve interpolation.\n        :param maximum_curvature: equal to 1/minimum_turning_radius of the vehicle.\n        \"\"\"\n        self.check_poly, self.check_res, self.maximum_curvature = check_poly, check_res, maximum_curvature\n        return self\n\n    def preset(self, start, goal, grid_map, grid_res, grid_ori, obstacle, heuristic):\n        # type: (StateNode, StateNode, np.ndarray, float, StateNode, int, Any) -> RRTStar\n        \"\"\"\n        initialize the parameters for planning: Start State, Goal State and other needs.\n        :param start: the start state.\n        :param goal: the goal state.\n        :param grid_map: occupancy grid map.\n        :param grid_res: resolution of grid map.\n        :param grid_ori: the center point of the occupancy grid map.\n        :param obstacle: the value of pixels of the obstacles region.\n        :param heuristic: [(state, biasing)], sampling heuristic path.\n            state: state (x_o, y_o, a_o) of the point of the path.\n            biasing = (x_mu, x_sigma), (y_mu, y_sigma), (a_mu, a_sigma).\n        :return: RRTStar object\n        \"\"\"\n        self.grid_map, self.grid_res, self.grid_ori, self.obstacle = grid_map, grid_res, grid_ori, obstacle\n        self.heuristic = heuristic\n        self.start, self.goal = start, goal\n        self.start.g, self.start.hl = 0, self.cost(start, goal)\n        self.start.hu = self.start.hl if self.collision_free(start, goal) else np.inf\n        self.start.fl, self.start.fu = self.start.g + self.start.hl, self.start.g + self.start.hu\n        self.root, self.gain = self.start, self.goal\n        self.vertices, self.x_best = [self.root], self.root\n        return self\n\n    def planning(self, times, repeat=10, optimize=False, debug=False):\n        \"\"\"main flow.\"\"\"\n        self.debug = debug\n        past = time.time()\n        for i in range(times):\n            x_new = self.sample_free(i, repeat)\n            x_nearest = self.nearest(x_new) if not optimize else self.least(x_new)\n            if x_nearest and self.benefit(x_new) and self.collision_free(x_nearest, x_new):\n                self.attach(x_nearest, x_new)\n                self.rewire(x_new)\n                self.x_best = self.best()\n                self.branch_and_bound()\n            Debugger().debug_planned_path(self, i, switch=self.debug)\n            Debugger().debug_planning_hist(self, i, (time.time() - past), switch=True)\n\n    def branch_and_bound(self, space=None):\n        def out(x):\n            vertices.remove(x)\n            x.remove()\n        vertices = space if space else self.vertices\n        vs = filter(lambda x: x.fl > self.x_best.fu + self.epsilon, vertices)\n        map(out, vs)\n        Debugger().debug_branch_and_bound(vs, switch=self.debug)\n\n    def sample_free(self, n, repeat=10, default=((2., .5), (0., np.pi / 4.), (0, np.pi / 6.))):\n        \"\"\"sample a state from free configuration space.\"\"\"\n\n        def is_free(state):\n            contour = self.transform(self.check_poly, state[0], state[1], state[2])\n            contour = np.floor(contour / self.grid_res + self.grid_map.shape[0] / 2.).astype(int)\n            mask = np.zeros_like(self.grid_map, dtype=np.uint8)\n            cv2.fillPoly(mask, [contour], 255)\n            result = np.bitwise_and(mask, self.grid_map)\n            Debugger().breaker('sample free: {}'.format(np.all(result < self.obstacle)), self.debug)\n            return np.all(result < self.obstacle)\n\n        def exist(state):\n            def key(y):\n                dxy = np.fabs(y.state[:-1] - s[:-1])\n                da = ((y.state[-1] + np.pi) % (2 * np.pi) - np.pi) - ((s[-1] + np.pi) % (2 * np.pi) - np.pi)\n                return dxy[0] < self.exist_res and dxy[1] < self.exist_res and da < self.exist_res\n            s = np.array(state)\n            result = filter(key, self.vertices)\n            Debugger.breaker('sample exclusive: {}'.format(result == []), switch=self.debug)\n            return result\n\n        def emerge():\n            if self.heuristic:\n                i = n % len(self.heuristic)\n                state, biasing = self.heuristic[i]\n                rand = [state[0], state[1], state[2]]  # [x_o, y_o, a_o]\n                (x_mu, x_sigma), (y_mu, y_sigma), (a_mu, a_sigma) = biasing\n                rand[0] += np.random.normal(x_mu, x_sigma)\n                rand[1] += np.random.normal(y_mu, y_sigma)\n                rand[2] += np.random.normal(a_mu, a_sigma)\n                return rand\n            else:\n                Debugger().debug_no_heuristic(vertex.state, default, self.debug)\n                rand = [vertex.state[0], vertex.state[1], vertex.state[2]]\n                (r_mu, r_sigma), (t_mu, t_sigma), (a_mu, a_sigma) = default\n                r, theta = np.random.normal(r_mu, r_sigma), np.random.normal(t_mu, t_sigma) + rand[2]\n                rand[0] += r * np.cos(theta)\n                rand[1] += r * np.sin(theta)\n                rand[2] += np.random.normal(a_mu, a_sigma)\n                return rand\n\n        vertex = np.random.choice(self.vertices)\n        for i in range(repeat):\n            x_rand = emerge()\n            Debugger().debug_sampling(x_rand, self.check_poly, switch=self.debug)\n            if is_free(x_rand):\n                if not exist(x_rand):\n                    return self.StateNode(tuple(x_rand))\n        return self.StateNode(tuple(x_rand))\n\n    def nearest(self, x_rand):  # type: (StateNode) -> StateNode\n        \"\"\"find the state in the tree which is nearest to the sampled state.\n        And fill the g, hl and fl properties of the sampled state.\n        \"\"\"\n\n        def replenish(x_n, x_r):\n            x_r.g, x_r.hl = x_n.g + self.cost(x_n, x_r), self.cost(x_r, self.gain)\n            x_r.fl = x_r.g + x_r.hl\n\n        # quick shot\n        if self.collision_free(self.root, x_rand):\n            x_nearest = self.root\n        else:\n            costs = list(map(lambda x: self.cost(x, x_rand), self.vertices))\n            x_nearest = self.vertices[int(np.argmin(costs))]\n        replenish(x_nearest, x_rand)\n        Debugger().debug_nearest_searching(x_nearest.state, switch=self.debug)\n        return x_nearest\n\n    def least(self, x_rand):  # type: (StateNode) -> StateNode\n        def replenish(x_n, x_r):\n            x_r.g, x_r.hl = x_n.g + self.cost(x_n, x_r), self.cost(x_r, self.gain)\n            x_r.fl = x_r.g + x_r.hl\n\n        # quick shot\n        if self.collision_free(self.root, x_rand):\n            x_least = self.root\n        else:\n            nodes = filter(lambda x: self.collision_free(x, x_rand), self.vertices)\n            if nodes:\n                costs = list(map(lambda x: x.g + self.cost(x, x_rand), nodes))\n                x_least = nodes[int(np.argmin(costs))]\n            else:\n                x_least = None\n        if x_least:\n            replenish(x_least, x_rand)\n            Debugger().debug_nearest_searching(x_least.state, switch=self.debug)\n        return x_least\n\n    def benefit(self, x_new):\n        words = 'Benefit: {}/ ({}, {})'.format(x_new.fl <= self.x_best.fu, x_new.fl, self.x_best.fu)\n        Debugger.breaker(words, switch=self.debug)\n        return x_new.fl < self.x_best.fu\n\n    def collision_free(self, x_from, x_to):  # type: (StateNode, StateNode) -> bool\n        \"\"\"check if the path from one state to another state collides with any obstacles or not.\"\"\"\n        # making contours of the curve\n        states = reeds_shepp.path_sample(x_from.state, x_to.state, 1. / self.maximum_curvature, 0.3)\n        # states.append(tuple(x_to.state))  # include the end point\n        contours = [self.transform(self.check_poly, s[0], s[1], s[2]) for s in states]\n        contours = [np.floor(con / self.grid_res + self.grid_map.shape[0] / 2.).astype(int) for con in contours]\n        # making mask\n        mask = np.zeros_like(self.grid_map, dtype=np.uint8)\n        [cv2.fillPoly(mask, [con], 255) for con in contours]\n        # checking\n        result = np.bitwise_and(mask, self.grid_map)\n        Debugger().debug_collision_checking(states, self.check_poly, np.all(result < self.obstacle), switch=self.debug)\n        return np.all(result < self.obstacle)\n\n    @staticmethod\n    @numba.njit\n    def transform(poly, x, y, a):\n        pts = poly.transpose()\n        xyo = np.array([[x], [y]])\n        rot = np.array([[np.cos(a), -np.sin(a)], [np.sin(a), np.cos(a)]])\n        return (np.dot(rot, pts) + xyo).transpose()\n\n    def attach(self, x_nearest, x_new):  # type: (StateNode, StateNode) -> None\n        \"\"\"add the new state to the tree and complement other values.\n        And fill the hu and fu properties of x_new.\n        \"\"\"\n        x_new.match(x_nearest)\n        available = self.collision_free(x_new, self.gain)\n        x_new.hu = x_new.hl if available else np.inf\n        x_new.fu = x_new.g + x_new.hu\n        x_new.status = 0 if available else 1\n        self.vertices.append(x_new)\n        Debugger().debug_attaching(x_nearest, x_new, 1. / self.maximum_curvature, switch=self.debug)\n\n    def rewire(self, x_new, gamma=0.2):  # type: (StateNode, float) -> None\n        \"\"\"rewiring tree by the new state.\"\"\"\n\n        def recheck(x):\n            available, cost = self.collision_free(x_new, x), self.cost(x_new, x)\n            if available and x.g > x_new.g + cost:\n                Debugger().debug_rewiring(x, x_new.g + cost, switch=self.debug)\n                x.g = x_new.g + cost\n                x.fu, x.fl = x.g + x.hu, x.g + x.hl\n                x.rematch(x_new)\n\n        xs = filter(lambda x: x.g > x_new.g + gamma, self.vertices)\n        Debugger().debug_rewiring_check(xs, x_new, switch=self.debug)\n        map(recheck, xs)\n\n    def cost(self, x_from, x_to):  # type: (StateNode, StateNode) -> float\n        \"\"\"calculate the cost from one state to another state\"\"\"\n        return reeds_shepp.path_length(x_from.state, x_to.state, 1. / self.maximum_curvature)\n\n    def best(self):\n        return sorted(self.vertices, key=lambda x: x.fu)[0]\n\n    def spare(self, space=None):\n        return sorted(self.vertices if not space else space, key=lambda x: x.hl)[0]\n\n    def path(self):  # type: () -> List[RRTStar.StateNode]\n        \"\"\"extract the planning result. including the goal state if the the goal is available\"\"\"\n        x_best = self.best()\n        if x_best.fu < np.inf:\n            p = x_best.trace()\n            self.gain.g = self.gain.fu = x_best.fu\n            p.append(self.gain)\n            return p\n        else:\n            x_spare = self.spare()\n            return x_spare.trace()\n\n    def trajectory(self, a_cc=4, v_max=10, res=0.1):\n        \"\"\"\n        planning velocity for a path to generate a trajectory.\n        \"\"\"\n\n        def interpolate(q_ori, segment_type, length, radius):\n            x0, y0, a0 = q_ori[0], q_ori[1], q_ori[2]\n            transfer = np.array([[np.cos(a0), -np.sin(a0), 0., x0], [np.sin(a0), np.cos(a0), 0., y0], [0., 0., 1., a0]])\n            sign, phi = np.sign(length), np.fabs(length) / radius\n            if segment_type == 1:\n                r = 2 * radius * np.sin(phi / 2.)\n                x_lcs = np.array([[r * sign * np.cos(phi / 2.)], [r * np.sin(phi / 2.)], [sign * phi], [1]])\n            elif segment_type == 3:\n                r = 2 * radius * np.sin(phi / 2.)\n                x_lcs = np.array([[r * sign * np.cos(phi / 2.)], [- r * np.sin(phi / 2.)], [- sign * phi], [1]])\n            else:\n                x_lcs = np.array([[length], [0], [0], [1]])\n            x_tar = np.dot(transfer, x_lcs)\n            return x_tar[0, 0], x_tar[1, 0], x_tar[2, 0]\n\n        def extract_segments(q_from, q_to):\n            segments.extend(reeds_shepp.path_type(q_from, q_to, 1. / self.maximum_curvature))\n            return q_to\n\n        def extract_discontinuities(q0, sgs):\n            sg0, sg1 = sgs[0], sgs[1]\n            q1 = interpolate(q0, sg0[0], sg0[1], 1. / self.maximum_curvature)\n            if sg0[1] * sg1[1] < 0:\n                discontinuities2.append(self.Configuration(q1, v=0))\n            else:\n                discontinuities2.append(self.Configuration(q1))\n            return q1\n\n        def plan_motions(index_sec):\n            motion = []\n            v0, v1 = 0, 0\n            seg = discontinuities2[index_sec[0]:index_sec[1]+1]\n            seg = list(zip(seg[:-1], seg[1:]))\n            extent = 0\n            for sec in seg:\n                s0, s1 = sec[0].state, sec[1].state\n                extent += np.abs(reeds_shepp.path_length(s0, s1, 1. / self.maximum_curvature))\n            samples = []\n            for sec in seg:\n                s0, s1 = sec[0].state, sec[1].state\n                samples.extend(reeds_shepp.path_sample(s0, s1, 1. / self.maximum_curvature, res))\n\n            acc = min([(v_max ** 2 - v1 ** 2) / extent, a_cc])\n            vcc = np.sqrt(v1 ** 2 + acc * extent)\n            for i, sample in enumerate(samples):\n                if i * res < extent / 2.:\n                    vt = min([np.sqrt(v0 ** 2 + 2 * acc * (i * res)), vcc])\n                else:\n                    vt = min([np.sqrt(v1 ** 2 + 2 * acc * np.abs(extent - i * res)), vcc])\n                motion.append(self.Configuration(sample[:3], k=sample[3], v=np.sign(sample[4]) * vt))\n            return motion\n\n        segments = []  # type: List[(float, float)]\n        path = [tuple(node.state) for node in self.path()]\n        reduce(extract_segments, path)\n        segments = list(zip(segments[:-1], segments[1:]))  # type: List[(Tuple[float], Tuple[float])]\n\n        discontinuities2 = []  # type: List[(Tuple[float], float)]\n        segments.insert(0, tuple(self.root.state))\n        reduce(extract_discontinuities, segments)\n\n        discontinuities2.append(self.Configuration().from_state_node(self.gain))\n        discontinuities2.insert(0, self.Configuration().from_state_node(self.root))\n        discontinuity_indexes = []\n        for j, dis in enumerate(discontinuities2):\n            if dis.v == 0:\n                discontinuity_indexes.append(j)\n\n        motions = []\n        sector_indexes = list(zip(discontinuity_indexes[:-1], discontinuity_indexes[1:]))\n        for sector_index in sector_indexes:\n            motions.extend(plan_motions(sector_index))\n        motions.append(self.Configuration(state=self.gain.state, v=self.gain.v, k=motions[-1].k))\n        return motions\n\n    class Configuration(object):\n        def __init__(self, state=(), v=None, k=None):\n            self.state = np.array(state)\n            self.v, self.k = v, k\n\n        def from_state_node(self, state_node):\n            # type: (RRTStar.StateNode) -> RRTStar.Configuration\n            self.state = state_node.state\n            self.v, self.k = state_node.v, state_node.k\n            return self\n\n    class StateNode(object):\n        def __init__(self, state=()):\n            # type: (tuple) -> None\n            self.state = np.array(state)  # state of the Node, a tuple (x, y, orientation)\n            self.g = np.inf  # cost from root to here.\n            self.hu = np.inf  # cost from here to goal if available.\n            self.hl = np.inf  # cost from here to goal if not available.\n            self.fu = self.g + self.hu\n            self.fl = self.g + self.hl\n            self.parent = None  # type: Optional[RRTStar.StateNode]\n            self.children = []  # type: List[RRTStar.StateNode]\n            self.status = 0  # 0 for safe, 1 for dangerous.\n            self.v, self.k = 0, None  # velocity of the state, curvature of the state (related to the steering angle)\n\n        def match(self, x_parent):\n            # type: (RRTStar.StateNode) -> None\n            \"\"\"\n            add a state as parent.\n            \"\"\"\n            self.parent = x_parent\n            x_parent.children.append(self)\n\n        def remove(self):\n            if self.parent:\n                self.parent.children.remove(self)\n                self.parent = None\n\n        def rematch(self, x_new_parent):\n            if self.parent:\n                self.parent.children.remove(self)\n                self.match(x_new_parent)\n\n        def trace(self):  # type: ()->List[RRTStar.StateNode]\n            p, ptr = [self], self.parent\n            while ptr:\n                p.append(ptr)\n                ptr = ptr.parent\n            p.reverse()\n            return p\n\n        def lcs2gcs(self, origin):\n            # type: (RRTStar.StateNode) -> RRTStar.StateNode\n            \"\"\"\n            transform self's coordinate from local coordinate system (LCS) to global coordinate system (GCS)\n            :param origin: the tuple the coordinate (in GCS) of the origin of LCS.\n            \"\"\"\n            xo, yo, ao = origin[0], origin[1], origin[2]\n            x = self.state[0] * np.cos(ao) - self.state[1] * np.sin(ao) + xo\n            y = self.state[0] * np.sin(ao) + self.state[1] * np.cos(ao) + yo\n            a = self.state[2] + ao\n            self.state = np.array((x, y, a))\n            return self\n\n        def gcs2lcs(self, origin):\n            # type: (RRTStar.StateNode) -> RRTStar.StateNode\n            \"\"\"\n            transform self's coordinate from global coordinate system (LCS) to local coordinate system (GCS)\n            :param origin: the circle-node contains the coordinate (in GCS) of the origin of LCS.\n            \"\"\"\n            xo, yo, ao = origin[0], origin[1], origin[2]\n            x = (self.state[0] - xo) * np.cos(ao) + (self.state[1] - yo) * np.sin(ao)\n            y = -(self.state[0] - xo) * np.sin(ao) + (self.state[1] - yo) * np.cos(ao)\n            a = self.state[2] - ao\n            self.state = np.array((x, y, a))\n            return self\n\n\nclass BiRRTStar(RRTStar):\n    def __init__(self):\n        super(BiRRTStar, self).__init__()\n        self.s_vertices = None\n        self.g_vertices = None\n\n    def preset(self, start, goal, grid_map, grid_res, grid_ori, obstacle, heuristic):\n        self.grid_map, self.grid_res, self.grid_ori, self.obstacle = grid_map, grid_res, grid_ori, obstacle\n        self.heuristic = heuristic\n        self.start, self.goal = start, goal\n\n        self.start.g, self.start.hl = 0, self.cost(start, goal)\n        self.start.hu = self.start.hl if self.collision_free(start, goal) else np.inf\n        self.start.fl, self.start.fu = self.start.g + self.start.hl, self.start.g + self.start.hu\n\n        self.goal.g, self.goal.hl = 0, self.cost(goal, start)\n        self.goal.hu = self.goal.hl if self.collision_free(goal, start) else np.inf\n        self.goal.fl, self.goal.fu = self.goal.g + self.goal.hl, self.goal.g + self.goal.hu\n\n        self.root, self.gain = self.start, self.goal\n        self.s_vertices = [self.start]\n        self.g_vertices = [self.goal]\n        self.x_best = self.root\n        return self\n\n    def swap(self, i):\n        self.branch_and_bound(self.g_vertices)\n        self.branch_and_bound(self.s_vertices)\n        if self.root is self.start:\n            self.root = self.goal\n            self.gain = self.start\n            self.vertices = self.g_vertices\n            n = -((i/2) % len(self.heuristic)) - 1 if self.heuristic else i\n            Debugger.breaker('swap: goal -> start, {}, {}'.format(i, n), self.debug)\n            return n\n        else:\n            self.root = self.start\n            self.gain = self.goal\n            self.vertices = self.s_vertices\n            n = (i/2) % len(self.heuristic) if self.heuristic else i\n            Debugger.breaker('swap: start -> goal, {}, {}'.format(i, n), self.debug)\n            return n\n\n    def planning(self, times, repeat=10, optimize=True, debug=False):\n        \"\"\"main flow.\"\"\"\n        self.debug = debug\n        past = time.time()\n        for i in range(times):\n            n = self.swap(i)\n            x_new = self.sample_free(n, repeat)\n            x_nearest = self.nearest(x_new) if not optimize else self.least(x_new)\n            if x_nearest and self.benefit(x_new) and self.collision_free(x_nearest, x_new):\n                self.attach(x_nearest, x_new)\n                self.rewire(x_new)\n                self.x_best = self.best_of_all()\n                self.connect_graphs(x_new)\n            Debugger().debug_planned_path(self, i, switch=self.debug)\n            Debugger().debug_planning_hist(self, i, (time.time() - past), switch=True)\n\n    def best_of_all(self):\n        x_new_best = self.best()\n        return x_new_best if x_new_best.fu < self.x_best.fu else self.x_best\n\n    def connect_graphs(self, x_new):\n        if self.root is self.start:\n            vs = self.g_vertices\n        else:\n            vs = self.s_vertices\n        costs = map(lambda x: self.cost(x_new, x), vs)\n        x_nearest, cost = vs[int(np.argmin(costs))], np.min(costs)\n        Debugger().debug_connect_graphs(x_nearest.state, x_new.g+cost+x_nearest.g, self.x_best.fu, switch=self.debug)\n        if x_new.g + cost + x_nearest.g < self.x_best.fu:\n            if self.collision_free(x_new, x_nearest):\n                x_nearest.fu = x_new.fu = x_new.g + cost + x_nearest.g\n                x_new.hu = x_new.fu - x_new.g\n                x_nearest.hu = x_nearest.fu - x_nearest.g\n                x_new.neighbor = x_nearest\n                x_nearest.neighbor = x_new\n                self.x_best = x_new\n\n    def path(self):\n        x_best = self.x_best\n        if x_best.fu < np.inf:\n            p = x_best.trace()\n            if hasattr(x_best, 'neighbor') and x_best.neighbor:\n                p1 = x_best.neighbor.trace()\n                p1.reverse()\n                p.extend(p1)\n                if p[-1] is self.start:\n                    p.reverse()\n                return p\n            else:\n                if p[0] is self.start:\n                    p.append(self.gain)\n                else:\n                    p.append(self.start)\n                    p.reverse()\n                return p\n        else:\n            x_spare = self.spare(space=self.s_vertices)\n            return x_spare.trace()\n", "meta": {"hexsha": "0189d6f5efa3678b3557715b1622255ae7812795", "size": 23160, "ext": "py", "lang": "Python", "max_stars_repo_path": "rrts/planner.py", "max_stars_repo_name": "liespace/pyRRTs", "max_stars_repo_head_hexsha": "11bfefad99218bc9eccd97040355c61d34a1181d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-22T09:12:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-06T14:22:05.000Z", "max_issues_repo_path": "rrts/planner.py", "max_issues_repo_name": "liespace/pyRRTs", "max_issues_repo_head_hexsha": "11bfefad99218bc9eccd97040355c61d34a1181d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rrts/planner.py", "max_forks_repo_name": "liespace/pyRRTs", "max_forks_repo_head_hexsha": "11bfefad99218bc9eccd97040355c61d34a1181d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.7104247104, "max_line_length": 120, "alphanum_fraction": 0.5687392055, "include": true, "reason": "import numpy,import numba", "num_tokens": 5893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.19863873458294368}}
{"text": "r\"\"\":mod:`mirgecom.inviscid` provides helper functions for inviscid flow.\n\nInviscid Flux Calculation\n^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. autofunction:: inviscid_flux\n.. autofunction:: inviscid_facial_flux\n\nInviscid Time Step Computation\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. autofunction:: get_inviscid_timestep\n.. autofunction:: get_inviscid_cfl\n\"\"\"\n\n__copyright__ = \"\"\"\nCopyright (C) 2020 University of Illinois Board of Trustees\n\"\"\"\n\n__license__ = \"\"\"\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\n\nimport numpy as np\nfrom meshmode.dof_array import thaw\nfrom grudge.trace_pair import TracePair\nfrom mirgecom.flux import divergence_flux_lfr\nfrom mirgecom.fluid import make_conserved\n\n\ndef inviscid_flux(state):\n    r\"\"\"Compute the inviscid flux vectors from fluid conserved vars *cv*.\n\n    The inviscid fluxes are\n    $(\\rho\\vec{V},(\\rho{E}+p)\\vec{V},\\rho(\\vec{V}\\otimes\\vec{V})\n    +p\\mathbf{I}, \\rho{Y_s}\\vec{V})$\n\n    .. note::\n\n        The fluxes are returned as a :class:`mirgecom.fluid.ConservedVars`\n        object with a *dim-vector* for each conservation equation. See\n        :class:`mirgecom.fluid.ConservedVars` for more information about\n        how the fluxes are represented.\n\n    Parameters\n    ----------\n    state: :class:`~mirgecom.gas_model.FluidState`\n\n        Full fluid conserved and thermal state.\n\n    Returns\n    -------\n    :class:`~mirgecom.fluid.ConservedVars`\n\n        A CV object containing the inviscid flux vector for each\n        conservation equation.\n    \"\"\"\n    mass_flux = state.momentum_density\n    energy_flux = state.velocity * (state.energy_density + state.pressure)\n    mom_flux = (\n        state.mass_density * np.outer(state.velocity, state.velocity)\n        + np.eye(state.dim)*state.pressure\n    )\n    species_mass_flux = \\\n        state.velocity*state.species_mass_density.reshape(-1, 1)\n\n    return make_conserved(state.dim, mass=mass_flux, energy=energy_flux,\n                          momentum=mom_flux, species_mass=species_mass_flux)\n\n\ndef inviscid_facial_flux(discr, state_tpair, local=False):\n    r\"\"\"Return the flux across a face given the solution on both sides *q_tpair*.\n\n    This flux is currently hard-coded to use a Rusanov-type  local Lax-Friedrichs\n    (LFR) numerical flux at element boundaries. The numerical inviscid flux $F^*$ is\n    calculated as:\n\n    .. math::\n\n        \\mathbf{F}^{*}_{\\mathtt{LFR}} = \\frac{1}{2}(\\mathbf{F}(q^-)\n        +\\mathbf{F}(q^+)) \\cdot \\hat{n} + \\frac{\\lambda}{2}(q^{-} - q^{+}),\n\n    where $q^-, q^+$ are the fluid solution state on the interior and the\n    exterior of the face on which the LFR flux is to be calculated, $\\mathbf{F}$ is\n    the inviscid fluid flux, $\\hat{n}$ is the face normal, and $\\lambda$ is the\n    *local* maximum fluid wavespeed.\n\n    Parameters\n    ----------\n    discr: :class:`~grudge.eager.EagerDGDiscretization`\n\n        The discretization collection to use\n\n    state_tpair: :class:`~grudge.trace_pair.TracePair`\n\n        Trace pair of :class:`~mirgecom.gas_model.FluidState` for the face upon\n        which the flux calculation is to be performed\n\n    local: bool\n\n        Indicates whether to skip projection of fluxes to \"all_faces\" or not. If\n        set to *False* (the default), the returned fluxes are projected to\n        \"all_faces.\"  If set to *True*, the returned fluxes are not projected to\n        \"all_faces\"; remaining instead on the boundary restriction.\n\n    Returns\n    -------\n    :class:`~mirgecom.fluid.ConservedVars`\n\n        A CV object containing the scalar numerical fluxes at the input faces.\n        The returned fluxes are scalar because they've already been dotted with\n        the face normals as required by the divergence operator for which they\n        are being computed.\n    \"\"\"\n    actx = state_tpair.int.array_context\n    dd = state_tpair.dd\n    dd_all_faces = dd.with_dtag(\"all_faces\")\n\n    flux_tpair = TracePair(dd,\n                           interior=inviscid_flux(state_tpair.int),\n                           exterior=inviscid_flux(state_tpair.ext))\n\n    # This calculates the local maximum eigenvalue of the flux Jacobian\n    # for a single component gas, i.e. the element-local max wavespeed |v| + c.\n    w_int = state_tpair.int.speed_of_sound + state_tpair.int.speed\n    w_ext = state_tpair.ext.speed_of_sound + state_tpair.ext.speed\n    lam = actx.np.maximum(w_int, w_ext)\n\n    normal = thaw(actx, discr.normal(dd))\n    cv_tpair = TracePair(dd,\n                         interior=state_tpair.int.cv,\n                         exterior=state_tpair.ext.cv)\n\n    # todo: user-supplied flux routine\n    flux_weak = divergence_flux_lfr(cv_tpair, flux_tpair, normal=normal, lam=lam)\n\n    if local is False:\n        return discr.project(dd, dd_all_faces, flux_weak)\n\n    return flux_weak\n\n\ndef get_inviscid_timestep(discr, state):\n    \"\"\"Return node-local stable timestep estimate for an inviscid fluid.\n\n    The maximum stable timestep is computed from the acoustic wavespeed.\n\n    Parameters\n    ----------\n    discr: grudge.eager.EagerDGDiscretization\n\n        the discretization to use\n\n    state: :class:`~mirgecom.gas_model.FluidState`\n\n        Full fluid conserved and thermal state\n\n    Returns\n    -------\n    class:`~meshmode.dof_array.DOFArray`\n\n        The maximum stable timestep at each node.\n    \"\"\"\n    from grudge.dt_utils import characteristic_lengthscales\n    return (\n        characteristic_lengthscales(state.array_context, discr)\n        / state.wavespeed\n    )\n\n\ndef get_inviscid_cfl(discr, state, dt):\n    \"\"\"Return node-local CFL based on current state and timestep.\n\n    Parameters\n    ----------\n    discr: :class:`~grudge.eager.EagerDGDiscretization`\n\n        the discretization to use\n\n    dt: float or :class:`~meshmode.dof_array.DOFArray`\n\n        A constant scalar dt or node-local dt\n\n    state: :class:`~mirgecom.gas_model.FluidState`\n\n        The full fluid conserved and thermal state\n\n    Returns\n    -------\n    :class:`~meshmode.dof_array.DOFArray`\n\n        The CFL at each node.\n    \"\"\"\n    return dt / get_inviscid_timestep(discr, state=state)\n", "meta": {"hexsha": "a60cddd9521a5783014b20dc855e0080557f1f4d", "size": 7025, "ext": "py", "lang": "Python", "max_stars_repo_path": "mirgecom/inviscid.py", "max_stars_repo_name": "dreamer2368/mirgecom", "max_stars_repo_head_hexsha": "dc79645af040510a7e2b11d3f93db4c34ad39228", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mirgecom/inviscid.py", "max_issues_repo_name": "dreamer2368/mirgecom", "max_issues_repo_head_hexsha": "dc79645af040510a7e2b11d3f93db4c34ad39228", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mirgecom/inviscid.py", "max_forks_repo_name": "dreamer2368/mirgecom", "max_forks_repo_head_hexsha": "dc79645af040510a7e2b11d3f93db4c34ad39228", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2938388626, "max_line_length": 84, "alphanum_fraction": 0.689252669, "include": true, "reason": "import numpy", "num_tokens": 1725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.1986387321847691}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov  1 14:27:54 2018\n\n@author: dkorff\n\"\"\"\n\nimport numpy as np\nimport cantera as ct\n\nfrom li_ion_battery_p2d_inputs import Inputs\n\n# Import Cantera objects:\nanode_obj = ct.Solution(Inputs.ctifile,Inputs.anode_phase)\nelyte_obj = ct.Solution(Inputs.ctifile,Inputs.elyte_phase)\ncathode_obj = ct.Solution(Inputs.ctifile,Inputs.cathode_phase)\nconductor_obj = ct.Solution(Inputs.ctifile,Inputs.metal_phase)\n\nanode_surf_obj = ct.Interface(Inputs.ctifile,Inputs.anode_surf_phase,\n    [anode_obj,elyte_obj,conductor_obj])\ncathode_surf_obj = ct.Interface(Inputs.ctifile,Inputs.cathode_surf_phase,\n    [cathode_obj,elyte_obj,conductor_obj])\n\n\n# Anode initial conditions:\nLiC6_0 = Inputs.SOC_0; C6_0 = 1 - LiC6_0\nX_an_init = '{}:{}, {}:{}'.format(Inputs.Li_species_anode, LiC6_0,\n    Inputs.Vac_species_anode, C6_0)\n\n# Set Cantera object states\nanode_obj.X = X_an_init\nanode_obj.TP = Inputs.T, ct.one_atm\nelyte_obj.TP = Inputs.T, ct.one_atm\nanode_surf_obj.TP = Inputs.T, ct.one_atm\n\nX_an_0 = anode_obj.X\n\nif hasattr(Inputs, 'X_elyte_init'):\n    elyte_obj.X = X_elyte_init\n\n\n\n# Initial conditions: UPDATE TO GENERALIZE FOR MULT. SPECIES - DK 8/31/18\nLiCoO2_0 = 1- Inputs.SOC_0; CoO2_0 = 1 - LiCoO2_0\nX_ca_init = '{}:{}, {}:{}'.format(Inputs.Li_species_cathode, LiCoO2_0,\n        Inputs.Vac_species_cathode, CoO2_0)\n\ncathode_obj.X = X_ca_init\ncathode_obj.TP = Inputs.T, ct.one_atm\ncathode_surf_obj.TP = Inputs.T, ct.one_atm\n\nX_ca_0 = cathode_obj.X\nX_elyte_0 = elyte_obj.X\n\n\n\"\"\"=========================================================================\"\"\"\n\"\"\"=========================================================================\"\"\"\n\"\"\"=========================================================================\"\"\"\n\nclass anode():\n\n    # Set flag so solver knows whether to implement the anode:\n    flag = Inputs.flag_anode\n\n    # Number of nodes in the y-direction:\n    npoints = Inputs.npoints_anode\n\n    # Number of \"shells\" in anode particle:\n    nshells = Inputs.nshells_anode\n\n    # Initial conditions: UPDATE TO GENERALIZE FOR MULT. SPEC - DK 8/31/18\n\n    # Anode variables for a given volume include X_Li for each shell, Phi_an,\n    #       Phi_elyte, and rho_k_elyte for all elyte species.\n    nVars = nshells + 2 + elyte_obj.n_species\n\n    # Pointers\n    ptr = {}\n    ptr['iFar'] = 1\n    ptr['X_ed'] = np.arange(0, Inputs.nshells_anode)\n    ptr['rho_k_elyte'] = nshells + np.arange(0,elyte_obj.n_species)\n    ptr['Phi_ed'] = nshells + elyte_obj.n_species\n    ptr['Phi_dl'] = nshells + elyte_obj.n_species + 1\n\n    # Anode/elyte interface area per unit volume\n    #   [m^2 interface / m_3 total electrode volume]\n    # For spherical particles, the total surface area per unit volume can be\n    #   calculated from the geometry. Since some particles will overlap, we\n    #   multiply by an 'overlap' input parameter.\n    A_surf = (1-Inputs.overlap_an)*6*Inputs.eps_solid_an/Inputs.d_part_an\n\n    # Set up solution vector\n    nSV = npoints*nVars\n\n    # Array of offsets to point to each node's variable:\n    offsets = np.arange(0,int(nSV),int(nVars))\n\n    # Store parameters as class object attributes:\n    T = Inputs.T\n    C_dl = Inputs.C_dl_an\n    X_Li_max = Inputs.SOC_max\n    X_Li_min = Inputs.SOC_min\n    D_Li_ed = Inputs.D_Li_an\n\n    # Geometric parameters:\n    eps_ed = Inputs.eps_solid_an\n    eps_elyte = 1 - Inputs.eps_solid_an\n    tau_ed = Inputs.tau_an\n    r_pore = Inputs.r_p_an\n    d_part = Inputs.d_part_an\n    dyInv = npoints/Inputs.H_an\n    dr = d_part*0.5/nshells\n\n    # Calculate the current density [A/m^2] corresponding to a C_rate of 1:\n    oneC = eps_ed*anode_obj.density_mole*Inputs.H_an*ct.faraday/3600\n\n    # Calculate the percent volume of a single graphite particle that exists in\n    #   each 'shell'. I.e. for shell j, what is the volume of that shell,\n    #   relative to the total particle volume? The radius of the volume is\n    #   currently discretized evenly (i.e. 'dr' the differential radius is\n    #   constant). Certainly other discretizations (such as constant\n    #   differential volume) are possible (and perhaps better).\n    #\n    #   Because the volume is 4/3 pi*r^3, the volume of the shell relative to\n    #   the total volume is (r_shell/r_particle)^3, and the differential volume\n    #   relative to the total, for shell 'j' is:\n    #       (r_shell(j+1)^3 - r_shell(j)^3)/r_particle^3\n    #   Because the radius is discretized evenly, the radius of shell j, r_j,\n    #   relative to the total radius r_particle, is:\n    #       r_j/r_particle = j/nshells\n\n    V_shell = np.zeros([nshells])\n    nsr3 = 1/nshells/nshells/nshells\n    for j in np.arange(0, nshells, 1):\n        V_shell[j] = ((j+1)**3 - (j)**3)*nsr3\n\n    # Electronic conductivity of the electrode phase:\n    sigma_eff_ed = Inputs.sigma_an*eps_ed/tau_ed**3\n    # Species mobilities of the electrolyte phase.  Converted from user input\n    #   diffusion coefficients:\n    u_Li_elyte = (Inputs.D_Li_elyte*eps_elyte/ct.gas_constant\n          /Inputs.T/tau_ed**3)\n\n    t_flag = []\n\n\n    \"\"\"=========================================================================\"\"\"\n    \"\"\"=========================================================================\"\"\"\n    \"\"\"=========================================================================\"\"\"\n\nclass separator():\n    # Set a flag to let the solver know whether to implement this class:\n    flag = Inputs.flag_sep\n\n    # Number of nodes in the y-direction\n    npoints = Inputs.npoints_elyte\n\n    # Number of variables per node:\n    nVars = 1 + elyte_obj.n_species\n\n    H = Inputs.H_elyte  # Separator thickness [m]\n\n    tau_sep = Inputs.tau_sep  # Tortuosity of separator\n\n    # Geometric parameters:\n    eps_elyte = Inputs.eps_elyte_sep\n    dyInv = npoints/H\n    tau_sep = tau_sep\n\n    ptr = {}\n    ptr['rho_k_elyte'] = np.arange(0,elyte_obj.n_species)\n    ptr['Phi'] = elyte_obj.n_species\n\n    # Set up the solution vector\n    nSV = npoints*nVars\n\n    # Array of offsets to point to each node's variable:\n    offsets = np.arange(int(anode.nSV),int(anode.nSV)+int(nSV),int(nVars))\n\n\n\"\"\"=========================================================================\"\"\"\n\"\"\"=========================================================================\"\"\"\n\"\"\"=========================================================================\"\"\"\n\nclass cathode():\n    # Set flag so solver knows it's looking at the anode class\n    flag = Inputs.flag_cathode\n\n    # Number of nodes in the y-direction:\n    npoints = Inputs.npoints_cathode\n\n    # Number of \"shells\" in the cathode particle\n    nshells = Inputs.n_shells_cathode\n\n    # Number of state variables per node:\n    nVars = nshells + 2 + elyte_obj.n_species\n\n    # Pointers\n    ptr = {}\n    ptr['iFar'] = 0\n    ptr['X_ed'] = np.arange(0, nshells)\n    ptr['rho_k_elyte'] = nshells + np.arange(0,elyte_obj.n_species)\n    ptr['Phi_ed'] = nshells + elyte_obj.n_species\n    ptr['Phi_dl'] = nshells + elyte_obj.n_species + 1\n\n    # Cathode/elyte interface area per unit volume\n    #   [m^2 interface / m_3 total electrode volume]\n    # For spherical particles, the total surface area per unit volume can be\n    #   calculated from the geometry. Since some particles will overlap, we\n    #   multiply by an 'overlap' input parameter.\n    A_surf = (1-Inputs.overlap_ca)*6*Inputs.eps_solid_ca/Inputs.d_part_ca\n\n    # Set up the solution vector\n    nSV = npoints*nVars\n\n    # Array of offsets to point to each node's variable:\n    offsets = np.arange(int(anode.nSV + separator.nSV), \\\n                    int(anode.nSV + separator.nSV)+int(nSV),int(nVars))\n\n    #  Store Parameters in the Class object:\n    T = Inputs.T\n    C_dl = Inputs.C_dl_ca\n    X_Li_max = Inputs.SOC_max\n    X_Li_min = Inputs.SOC_min\n    D_Li_ed = Inputs.D_Li_ca\n\n    # Geometric parameters:\n    eps_ed = Inputs.eps_solid_ca\n    eps_elyte = 1 - Inputs.eps_solid_ca\n    tau_ed = Inputs.tau_ca\n    r_p = Inputs.r_p_ca\n    d_part = Inputs.d_part_ca\n    dyInv = npoints/Inputs.H_ca\n    dr = d_part*0.5/nshells\n\n    # Calculate the current density [A/m^2] corresponding to a C_rate of 1:\n    oneC = eps_ed*cathode_obj.density_mole*Inputs.H_ca*ct.faraday/3600\n\n    # Calculate the percent volume of a single graphite particle that exists in\n    #   each 'shell'. I.e. for shell j, what is the volume of that shell,\n    #   relative to the total particle volume? The radius of the volume is\n    #   currently discretized evenly (i.e. 'dr' the differential radius is\n    #   constant). Certainly other discretizations (such as constant\n    #   differential volume) are possible (and perhaps better).\n    #\n    #   Because the volume is 4/3 pi*r^3, the volume of the shell relative to\n    #   the total volume is (r_shell/r_particle)^3, and the differential volume\n    #   relative to the total, for shell 'j' is:\n    #       (r_shell(j+1)^3 - r_shell(j)^3)/r_particle^3\n    #   Because the radius is discretized evenly, the radius of shell j, r_j,\n    #   relative to the total radius r_particle, is:\n    #       r_j/r_particle = j/nshells\n\n    V_shell = np.zeros([nshells])\n    nsr3 = 1/nshells/nshells/nshells\n    for j in np.arange(0, nshells, 1):\n        V_shell[j] = ((j+1)**3 - (j)**3)*nsr3\n\n    sigma_eff_ed = Inputs.sigma_ca*eps_ed/tau_ed**3\n    u_Li_elyte = (Inputs.D_Li_elyte*eps_elyte/ct.gas_constant\n          /Inputs.T/tau_ed**3)\n\n    t_flag = []\n\n\"\"\"=========================================================================\"\"\"\n\"\"\"=========================================================================\"\"\"\n\"\"\"=========================================================================\"\"\"\n\n\n\n# Calculate the actual current density:\n# The minus sign is because we begin with the charging reaction, which\n#   delivers negative charge to the anode:\ni_ext = -Inputs.C_rate*min(anode.oneC,cathode.oneC)\n\nSV_0 = np.zeros([anode.nSV+separator.nSV+cathode.nSV])\n\n# Set up algebraic variable vector:\nalgvar = np.zeros_like(SV_0)\n\noffsets = anode.offsets\nptr = anode.ptr\nfor j in range(anode.npoints):\n    SV_0[offsets[j] + ptr['X_ed']] = \\\n        np.ones([anode.nshells])*X_an_0[0]\n    algvar[offsets[j] + ptr['X_ed']] = 1\n\n    SV_0[offsets[j] + ptr['rho_k_elyte']] = \\\n        elyte_obj.Y*elyte_obj.density_mass\n    algvar[offsets[j] + ptr['rho_k_elyte']] = 1\n\n    SV_0[offsets[j] + ptr['Phi_ed']] = \\\n        Inputs.Phi_anode_init\n\n    SV_0[offsets[j] + ptr['Phi_dl']] = \\\n        Inputs.Phi_elyte_init - Inputs.Phi_anode_init\n    algvar[offsets[j] + ptr['Phi_dl']] = 1\n\noffsets = separator.offsets\nptr = separator.ptr\nfor j in np.arange(0, separator.npoints):\n    SV_0[offsets[j] + ptr['rho_k_elyte']] = \\\n        elyte_obj.Y*elyte_obj.density_mass\n    algvar[offsets[j] + ptr['rho_k_elyte']] = 1\n\n    SV_0[offsets[j] + ptr['Phi']] = \\\n        Inputs.Phi_elyte_init\n\noffsets = cathode.offsets\nptr = cathode.ptr\nfor j in range(cathode.npoints):\n    SV_0[offsets[j] + ptr['X_ed']] = \\\n        np.ones([cathode.nshells])*X_ca_0[0]\n    algvar[offsets[j] + ptr['X_ed']] = 1\n\n    SV_0[offsets[j] + ptr['rho_k_elyte']] = \\\n        elyte_obj.Y*elyte_obj.density_mass\n    algvar[offsets[j] + ptr['rho_k_elyte']] = 1\n\n    SV_0[offsets[j] + ptr['Phi_ed']] = \\\n        Inputs.Phi_anode_init + Inputs.Delta_Phi_init\n\n    SV_0[offsets[j] + ptr['Phi_dl']] = \\\n        Inputs.Phi_elyte_init - (Inputs.Phi_anode_init + Inputs.Delta_Phi_init)\n    algvar[offsets[j] + ptr['Phi_dl']] = 1\n", "meta": {"hexsha": "8e0dc3533bfe076a774c615993b166a49a69ba46", "size": 11347, "ext": "py", "lang": "Python", "max_stars_repo_path": "li_ion_battery_p2d_init.py", "max_stars_repo_name": "coresresearch/p2d_li_ion_battery", "max_stars_repo_head_hexsha": "7ea1a2332eb885bea65e47e82ea231f80d28ca18", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-02-05T04:53:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T01:50:51.000Z", "max_issues_repo_path": "li_ion_battery_p2d_init.py", "max_issues_repo_name": "coresresearch/p2d_li_ion_battery", "max_issues_repo_head_hexsha": "7ea1a2332eb885bea65e47e82ea231f80d28ca18", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "li_ion_battery_p2d_init.py", "max_forks_repo_name": "coresresearch/p2d_li_ion_battery", "max_forks_repo_head_hexsha": "7ea1a2332eb885bea65e47e82ea231f80d28ca18", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-03-21T21:06:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-05T09:06:15.000Z", "avg_line_length": 34.8067484663, "max_line_length": 83, "alphanum_fraction": 0.6232484357, "include": true, "reason": "import numpy", "num_tokens": 3293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3557749003442964, "lm_q1q2_score": 0.19863873076919839}}
{"text": "import numpy as np\r\nfrom argparse import ArgumentParser\r\nfrom collections import defaultdict\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\nfrom utils import CEVAE_mod, load_data\r\n\r\nparser = ArgumentParser()\r\nparser.add_argument('-lr', type=float, default=0.0005)\r\nparser.add_argument('-hDim', type=int, default=50)\r\nparser.add_argument('-nTest', type=int, default=1000)\r\nparser.add_argument('-nTrain', type=int, default=1000)\r\nparser.add_argument('-zDim', type=int, default=5)\r\nparser.add_argument('-rep', type=int, default=20)\r\nparser.add_argument('-nIter', type=int, default=10001)\r\nparser.add_argument('-batchSize', type=int, default=512)\r\nparser.add_argument('-nSamplesZ', type=int, default=1)\r\nparser.add_argument('-evalIter', type=int, default=500)\r\nparser.add_argument('-device', type=str, default='cpu')\r\nparser.add_argument('-comment', type=str, default='')\r\nargs = parser.parse_args()\r\n\r\n\r\n# Model class for auxiliary model\r\nclass aux_m(nn.Module):\r\n    def __init__(self, input_dim=20, h_dim_f=100, out_dim=1):\r\n        super().__init__()\r\n        # init network\r\n        self.lin1 = nn.Linear(input_dim, h_dim_f)\r\n        self.lin2 = nn.Linear(h_dim_f, out_dim)\r\n\r\n    def forward(self, z_in):\r\n        h1 = F.elu(self.lin1(z_in))\r\n        out = torch.sigmoid(self.lin2(h1))\r\n        return out\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n    acc_list = defaultdict(list)\r\n    stat_par_y1a0 = defaultdict(list)\r\n    stat_par_y1a1 = defaultdict(list)\r\n\r\n    # repeat whole training process to observe stability\r\n    for rep_i in range(args.rep):\r\n        print('rep: %i' % rep_i)\r\n        # data loader:\r\n        # order of packed data: data = [y, x_con, x_bin, r, b, a]\r\n        train_data, test_data, cat_bin_dict = load_data(n_test=args.nTest)\r\n\r\n        # unpack train x in order to init in right shapes\r\n        train_data = [data[:args.nTrain] for data in train_data]\r\n        y_tr, x_tr_con, x_tr_bin, r_tr, b_tr, a_tr = train_data\r\n        x_tr = np.hstack((x_tr_bin, x_tr_con))\r\n\r\n        CEVAE = CEVAE_mod(args=args, dim_x=x_tr.shape[1], dim_b=b_tr.shape[1], dim_a=1, dim_x_con=x_tr_con.shape[1],\r\n                          dim_x_bin=cat_bin_dict, dim_z=args.zDim, dim_r=r_tr.shape[1], dim_q_h=args.hDim,\r\n                          dim_p_h=args.hDim).to(args.device)\r\n\r\n        model = './model_path.pt'\r\n        CEVAE.load_state_dict(torch.load(model))\r\n\r\n        # init Causal Path Enabler (auxiliary -fair- models)\r\n        path_combinations = ['z', 'zb', 'zbr', 'zbrx', 'zbrxa']\r\n        AUX = dict()\r\n        AUX['z'] = aux_m(input_dim=args.zDim, h_dim_f=100)\r\n        AUX['zb'] = aux_m(input_dim=args.zDim + b_tr.shape[1], h_dim_f=100)\r\n        AUX['zbr'] = aux_m(input_dim=args.zDim + b_tr.shape[1] + r_tr.shape[1], h_dim_f=100)\r\n        AUX['zbrx'] = aux_m(input_dim=args.zDim + b_tr.shape[1] + r_tr.shape[1] + x_tr.shape[1], h_dim_f=100)\r\n        AUX['zbrxa'] = aux_m(input_dim=args.zDim + b_tr.shape[1] + r_tr.shape[1] + x_tr.shape[1] + a_tr.shape[1],\r\n                             h_dim_f=100)\r\n\r\n        # init optimizer\r\n        optimizer = dict()\r\n        for combination in path_combinations:\r\n            optimizer[combination] = torch.optim.RMSprop(AUX[combination].parameters(), lr=args.lr)\r\n\r\n        # Maintain loss development for monitoring\r\n        loss_dict = defaultdict(list)\r\n\r\n        # training loop\r\n        for i in range(args.nIter):\r\n            # select random batch\r\n            batch_idx = np.random.choice(a=range(x_tr.shape[0]), size=args.batchSize, replace=False)\r\n            batch_data = [torch.Tensor(g[batch_idx]).to(args.device) for g in train_data]\r\n\r\n            y_batch, x_batch_con, x_batch_bin, r_batch, b_batch, a_batch = batch_data\r\n            # INFER distribution over z, using inference network of CEVAE\r\n            z_infer = CEVAE.q_z.forward(\r\n                observations=torch.cat((x_batch_con, x_batch_bin, r_batch, b_batch, a_batch), 1))\r\n            # No need to store derivative to CEVAE\r\n            z_sample = z_infer.sample().detach()\r\n\r\n            aux_output = dict()\r\n            aux_output['z'] = AUX['z'].forward(z_sample)\r\n            aux_output['zb'] = AUX['zb'].forward(torch.cat((z_sample, b_batch), 1))\r\n            # use R(x,Z,B,A) below instead in order to exclude A->X->R->Y\r\n            aux_output['zbr'] = AUX['zbr'].forward(torch.cat((z_sample, b_batch, r_batch), 1))\r\n            aux_output['zbrx'] = AUX['zbrx'].forward(\r\n                torch.cat((z_sample, b_batch, r_batch, x_batch_con, x_batch_bin), 1))\r\n            aux_output['zbrxa'] = AUX['zbrxa'].forward(\r\n                torch.cat((z_sample, b_batch, r_batch, x_batch_con, x_batch_bin, a_batch), 1))\r\n\r\n            # calculate loss and update step\r\n            objective = dict()\r\n            for combination in path_combinations:\r\n                objective[combination] = torch.mean((aux_output[combination] - y_batch) ** 2)\r\n                optimizer[combination].zero_grad()\r\n                objective[combination].backward()\r\n                optimizer[combination].step()\r\n\r\n                loss_dict[combination].append(float(objective[combination].cpu().detach().numpy()))\r\n\r\n        # test on test set\r\n        batch_data = [torch.Tensor(g).to(args.device) for g in test_data]\r\n\r\n        y_batch, x_batch_con, x_batch_bin, r_batch, b_batch, a_batch = batch_data\r\n        # INFER distribution over z, using inference network of CEVAE\r\n        z_infer = CEVAE.q_z.forward(observations=torch.cat((x_batch_con, x_batch_bin, r_batch, b_batch, a_batch), 1))\r\n        # No need to store derivative to CEVAE\r\n        z_sample = z_infer.sample().detach()\r\n\r\n        aux_output = dict()\r\n        aux_output['z'] = AUX['z'].forward(z_sample)\r\n        aux_output['zb'] = AUX['zb'].forward(torch.cat((z_sample, b_batch), 1))\r\n        aux_output['zbr'] = AUX['zbr'].forward(torch.cat((z_sample, b_batch, r_batch), 1))\r\n        aux_output['zbrx'] = AUX['zbrx'].forward(torch.cat((z_sample, b_batch, r_batch, x_batch_con, x_batch_bin), 1))\r\n        aux_output['zbrxa'] = AUX['zbrxa'].forward(\r\n            torch.cat((z_sample, b_batch, r_batch, x_batch_con, x_batch_bin, a_batch), 1))\r\n\r\n        # ------ Test Statistical parity -----\r\n        mask_a0 = (a_batch == 0).squeeze()\r\n        mask_a1 = (a_batch == 1).squeeze()\r\n\r\n        for combination in path_combinations:\r\n            y_predict = torch.round(aux_output[combination])\r\n            accuracy = torch.sum(y_predict == y_batch).cpu().detach().numpy() / y_batch.shape[0]\r\n            acc_list[combination].append(accuracy)\r\n            p_y1_a0 = y_predict[mask_a0].sum() / mask_a0.sum()\r\n            p_y1_a1 = y_predict[mask_a1].sum() / mask_a1.sum()\r\n            stat_par_y1a0[combination].append(p_y1_a0.cpu().detach().numpy())\r\n            stat_par_y1a1[combination].append(p_y1_a1.cpu().detach().numpy())\r\n\r\n    np.save('accuracy_dict.npy', acc_list)\r\n    np.save('stat_par_y1a0_dict.npy', stat_par_y1a0)\r\n    np.save('stat_par_y1a1_dict.npy', stat_par_y1a1)\r\n", "meta": {"hexsha": "de2cff90ae8eada520b1132dca0cb5a4aa287557", "size": 7002, "ext": "py", "lang": "Python", "max_stars_repo_path": "social_welfare_experiment/train_aux.py", "max_stars_repo_name": "rik-helwegen/FairTrade", "max_stars_repo_head_hexsha": "649506d9e46b9fd7faaa08dc44b01229ffa4d066", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-09-06T08:14:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T09:17:39.000Z", "max_issues_repo_path": "social_welfare_experiment/train_aux.py", "max_issues_repo_name": "rik-helwegen/FairTrade", "max_issues_repo_head_hexsha": "649506d9e46b9fd7faaa08dc44b01229ffa4d066", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "social_welfare_experiment/train_aux.py", "max_forks_repo_name": "rik-helwegen/FairTrade", "max_forks_repo_head_hexsha": "649506d9e46b9fd7faaa08dc44b01229ffa4d066", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.68, "max_line_length": 119, "alphanum_fraction": 0.6226792345, "include": true, "reason": "import numpy", "num_tokens": 1840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3557748935136303, "lm_q1q2_score": 0.19863872695545312}}
{"text": "#\n#    Licensed under the Apache License, Version 2.0 (the \"License\");\n#    you may not use this file except in compliance with the License.\n#    You may obtain a copy of the License at\n#\n#        http://www.apache.org/licenses/LICENSE-2.0\n#\n#    Unless required by applicable law or agreed to in writing, software\n#    distributed under the License is distributed on an \"AS IS\" BASIS,\n#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#    See the License for the specific language governing permissions and\n#    limitations under the License.\n\n\"\"\"\n==================================================================================\n  Compute Interference caused by a grant for all the incumbent types\n  APIs in this file are used by IAP and Aggregate Interference Reference Models\n\n  The main routines are:\n\n    computeInterference\n    computeInterferencePpaGwpzPoint\n    computeInterferenceEsc\n    computeInterferenceFssCochannel\n    computeInterferenceFssBlocking\n    getEffectiveSystemEirp\n\n  The common utility APIs are:\n\n    findOverlappingGrantsInsideNeighborhood\n    getProtectedChannels\n\n  The routines return a interference caused by a grant in the neighborhood of\n  FSS/GWPZ/PPA/ESC incumbent types\n==================================================================================\n\"\"\"\nfrom collections import namedtuple\nimport numpy as np\n\nfrom reference_models.common import data\nfrom reference_models.antenna import antenna\nfrom reference_models.geo import vincenty\nfrom reference_models.propagation import wf_itm\nfrom reference_models.propagation import wf_hybrid\n\n# Set constant parameters based on requirements in the WINNF-TS-0112\n# [R2-SGN-16]\nGWPZ_NEIGHBORHOOD_DIST = 40  # neighborhood distance from a CBSD to a given protection\n# point (in km) in GWPZ protection area\nPPA_NEIGHBORHOOD_DIST = 40  # neighborhood distance from a CBSD to a given protection\n# point (in km) in PPA protection area\n\nFSS_CO_CHANNEL_NEIGHBORHOOD_DIST = 150  # neighborhood distance from a CBSD to FSS for\n# co-channel protection\n\nFSS_BLOCKING_NEIGHBORHOOD_DIST = 40  # neighborhood distance from a CBSD to FSS\n# blocking protection\n\nESC_NEIGHBORHOOD_DIST_A = 40  # neighborhood distance from a ESC to category A CBSD\n\nESC_NEIGHBORHOOD_DIST_B = 80  # neighborhood distance from a ESC to category B CBSD\n\n# Frequency used in propagation model (in MHz) [R2-SGN-04]\nFREQ_PROP_MODEL_MHZ = 3625.0\n\n# CBRS Band Frequency Range (Hz)\nCBRS_LOW_FREQ_HZ = 3550.e6\nCBRS_HIGH_FREQ_HZ = 3700.e6\n\n# FSS Passband low frequency range  (Hz)\nFSS_LOW_FREQ_HZ = 3600.e6\n\n# FSS Passband for TT&C (Hz)\nFSS_TTC_LOW_FREQ_HZ = 3700.e6\nFSS_TTC_HIGH_FREQ_HZ = 4200.e6\n\n# ESC IAP for Out-of-Band Category A CBSDs in Frequency Range (Hz)\nESC_CAT_A_LOW_FREQ_HZ = 3550.e6\nESC_CAT_A_HIGH_FREQ_HZ = 3660.e6\n\n# ESC Passband Frequency Range (Hz)\nESC_LOW_FREQ_HZ = 3550.e6\nESC_HIGH_FREQ_HZ = 3680.e6\n\n# ESC Channel 21 Centre Frequency\nESC_CH21_CF_HZ = 3652.5e6\n\n# One Mega Hertz\nMHZ = 1.e6\n\n# Channel bandwidth over which SASs execute the aggregate interference and\n# IAP process\nRBW_HZ = 5.e6\n\n# GWPZ and PPA height (m)\nGWPZ_PPA_HEIGHT = 1.5\n\n# In-band insertion loss\nIN_BAND_INSERTION_LOSS = 0.5\n\n# Global container to store neighborhood distance type of all the protection\n_DISTANCE_PER_PROTECTION_TYPE = {\n    data.ProtectedEntityType.GWPZ_AREA :  (GWPZ_NEIGHBORHOOD_DIST, GWPZ_NEIGHBORHOOD_DIST),\n    data.ProtectedEntityType.PPA_AREA : ( PPA_NEIGHBORHOOD_DIST,  PPA_NEIGHBORHOOD_DIST),\n    data.ProtectedEntityType.FSS_CO_CHANNEL : ( FSS_CO_CHANNEL_NEIGHBORHOOD_DIST,  FSS_CO_CHANNEL_NEIGHBORHOOD_DIST),\n    data.ProtectedEntityType.FSS_BLOCKING : ( FSS_BLOCKING_NEIGHBORHOOD_DIST,  FSS_BLOCKING_NEIGHBORHOOD_DIST),\n    data.ProtectedEntityType.ESC: (ESC_NEIGHBORHOOD_DIST_A, ESC_NEIGHBORHOOD_DIST_B)\n}\n\n\ndef dbToLinear(x):\n  \"\"\"This function returns dBm to mW converted value\"\"\"\n  return 10**(x / 10.)\n\n\ndef linearToDb(x):\n  \"\"\"This function returns mW to dBm converted value\"\"\"\n  return 10 * np.log10(x)\n\n\ndef getProtectedChannels(low_freq_hz, high_freq_hz):\n  \"\"\"Gets protected channels list.\n\n  Performs 5MHz IAP channelization and returns a list of tuple containing\n  (low_freq,high_freq)\n\n  Args:\n    low_freq_hz: Low frequency of the protected entity(Hz).\n    high_freq_hz: High frequency of the protected entity(Hz)\n  Returns:\n    An array of protected channel frequency range tuple\n    (low_freq_hz,high_freq_hz).\n  \"\"\"\n  if low_freq_hz >= high_freq_hz:\n    raise ValueError('Low frequency is greater than high frequency')\n  # Align the low_freq to multiple of 5MHZ\n  low_freq_hz = int(low_freq_hz / (5*MHZ)) * (5*MHZ)\n  channels = np.arange( max(low_freq_hz, 3550*MHZ), min(high_freq_hz, 3700*MHZ), 5*MHZ)\n  return [(low, high) for low, high in zip(channels, channels+5*MHZ)]\n\n\ndef findGrantsInsideNeighborhood(grants, protection_point, entity_type):\n  \"\"\"Finds grants inside protection entity neighborhood.\n\n  Args:\n    grants: An iterable of CBSD grants of type |data.CbsdGrantInfo|.\n    protection_point: The location of a protected entity as (longitude, latitude) tuple.\n    entity_type: The entity type (|data.ProtectedEntityType|).\n  Returns:\n    grants_inside: a list of grants, each one being a namedtuple of type\n                   |data.CbsdGrantInfo|, of all CBSDs inside the neighborhood\n                   of the protection constraint.\n  \"\"\"\n  # Initialize an empty list\n  grants_inside = []\n\n  # Loop over each CBSD grant\n  for grant in grants:\n    # Compute distance from CBSD location to protection constraint location\n    dist_km, _, _ = vincenty.GeodesicDistanceBearing(grant.latitude,\n                      grant.longitude, protection_point[1], protection_point[0])\n\n    # Check if CBSD is inside the neighborhood of protection constraint\n    if dist_km <= _DISTANCE_PER_PROTECTION_TYPE[entity_type][grant.cbsd_category == 'B']:\n      grants_inside.append(grant)\n\n  return grants_inside\n\n\ndef grantFrequencyOverlapCheck(grant, ch_low_freq, ch_high_freq, protection_ent_type):\n  \"\"\"Checks if grant frequency overlaps with protection constraint frequency range.\n\n  Args:\n    grant: A CBSD grant of type |data.CbsdGrantInfo|.\n    ch_low_freq: The low frequency of protection channel.\n    ch_high_freq: The high frequency of protection channel.\n    protection_ent_type: An enum of type |data.ProtectedEntityType|.\n  Returns:\n    True if grant frequency overlaps with protection constraint frequency range,\n    False otherwise.\n  \"\"\"\n  # Special case of ESC: ESC Passband is 3550-3680MHz\n  # Category A CBSD grants are considered in the neighborhood only for\n  # constraint frequency range 3550-3660MHz\n  if (protection_ent_type == data.ProtectedEntityType.ESC and\n      grant.cbsd_category == 'A' and\n      (grant.low_frequency >= ESC_CAT_A_HIGH_FREQ_HZ or\n       ch_low_freq >= ESC_CAT_A_HIGH_FREQ_HZ)):\n    return False\n\n  # Check frequency range overlap\n  overlapping_bw = (min(grant.high_frequency, ch_high_freq)\n                    - max(grant.low_frequency, ch_low_freq))\n  return (overlapping_bw > 0)\n\n\ndef findOverlappingGrants(grants, constraint):\n  \"\"\"Finds grants overlapping with protection entity.\n\n  Grants overlapping with frequency range of the protection entity are\n  considered as overlapping grants.\n\n  Args:\n    grants: An iterable of CBSD grants of type |data.CbsdGrantInfo|.\n    constraint: A protection constraint of type |data.ProtectionConstraint|.\n  Returns:\n    grants_overlap: a list of |data.CbsdGrantInfo| grants of all CBSDs inside\n      the neighborhood of the protection constraint.\n  \"\"\"\n  grants_overlap = [grant for grant in grants\n                    if grantFrequencyOverlapCheck(\n                        grant, constraint.low_frequency ,\n                        constraint.high_frequency, constraint.entity_type)]\n  return grants_overlap\n\n\ndef computeInterferencePpaGwpzPoint(cbsd_grant, constraint, h_inc_ant,\n                                    max_eirp, region_type='SUBURBAN'):\n  \"\"\"Computes interference that a grant causes to GWPZ or PPA protection area.\n\n  Routine to compute interference neighborhood grant causes to protection\n  point within GWPZ or PPA protection area.\n\n  Args:\n    cbsd_grant: A CBSD grant of type |data.CbsdGrantInfo|.\n    constraint: The protection constraint of type |data.ProtectionConstraint|.\n    h_inc_ant: The reference incumbent antenna height (in meters).\n    max_eirp: The maximum EIRP allocated to the grant during IAP procedure\n    region_type: Region type of the GWPZ or PPA area:\n                    'URBAN', 'SUBURBAN' or 'RURAL'.\n  Returns:\n    The interference contribution (dBm).\n  \"\"\"\n  # Get the propagation loss and incident angles for area entity\n  db_loss, incidence_angles, _ = wf_hybrid.CalcHybridPropagationLoss(\n                                     cbsd_grant.latitude, cbsd_grant.longitude,\n                                     cbsd_grant.height_agl, constraint.latitude,\n                                     constraint.longitude, h_inc_ant,\n                                     cbsd_grant.indoor_deployment,\n                                     reliability=-1,\n                                     freq_mhz=FREQ_PROP_MODEL_MHZ,\n                                     region=region_type)\n\n  # Compute CBSD antenna gain in the direction of protection point\n  ant_gain = antenna.GetStandardAntennaGains(incidence_angles.hor_cbsd,\n               cbsd_grant.antenna_azimuth, cbsd_grant.antenna_beamwidth,\n               cbsd_grant.antenna_gain)\n\n  # Get the exact overlap of the grant over the GWPZ area channels\n  if constraint.entity_type == data.ProtectedEntityType.GWPZ_AREA:\n    grant_overlap_bandwidth = min(cbsd_grant.high_frequency, constraint.high_frequency) \\\n        - max(cbsd_grant.low_frequency, constraint.low_frequency)\n  else:\n    grant_overlap_bandwidth = RBW_HZ\n\n  # Get the interference value for area entity\n  eirp = getEffectiveSystemEirp(max_eirp, cbsd_grant.antenna_gain,\n                   ant_gain, grant_overlap_bandwidth)\n\n  interference = eirp - db_loss\n  return interference\n\n\ndef getEscMaskLoss(constraint):\n  \"\"\"Returns the ESC mask loss (in dB).\n\n  Note: This routine assumes that the constraint bandwidth is 5MHz-aligned and\n  fully contained in the CBSD grant so there is no partial overlap across the\n  3650MHz ESC pass-band edge. This condition is realized in current framework.\n\n  Args:\n    constraint: The protection constraint of type |data.ProtectionConstraint|.\n  \"\"\"\n  if constraint.high_frequency <= 3650*MHZ:\n    return IN_BAND_INSERTION_LOSS\n  if constraint.low_frequency < 3650*MHZ:\n    raise ValueError('ESC mask loss: inconsistent protection channel %r' % constraint)\n  freqs = np.arange(constraint.low_frequency + 0.5*MHZ, constraint.high_frequency, MHZ)\n  attens = freqs/MHZ - 3650. + IN_BAND_INSERTION_LOSS\n  atten = -linearToDb(np.mean(dbToLinear(-attens)))\n  return atten\n\n\ndef computeInterferenceEsc(cbsd_grant, constraint, esc_antenna_info, max_eirp):\n  \"\"\"Computes interference that a grant causes to a ESC protection point.\n\n  Routine to compute interference neighborhood grant causes to ESC protection\n  point.\n\n  Args:\n    cbsd_grant: A CBSD grant of type |data.CbsdGrantInfo|.\n    constraint: The protection constraint of type |data.ProtectionConstraint|.\n    esc_antenna_info: ESC antenna information of type |data.EscInformation|.\n    max_eirp: The maximum EIRP allocated to the grant during IAP procedure\n  Returns:\n    The interference contribution(dBm).\n  \"\"\"\n  # Get the propagation loss and incident angles for ESC entity\n  db_loss, incidence_angles, _ = wf_itm.CalcItmPropagationLoss(\n      cbsd_grant.latitude, cbsd_grant.longitude, cbsd_grant.height_agl,\n      constraint.latitude, constraint.longitude, esc_antenna_info.antenna_height,\n      cbsd_grant.indoor_deployment, reliability=-1,\n      freq_mhz=FREQ_PROP_MODEL_MHZ)\n\n  # Compute CBSD antenna gain in the direction of protection point\n  ant_gain = antenna.GetStandardAntennaGains(\n      incidence_angles.hor_cbsd, cbsd_grant.antenna_azimuth,\n      cbsd_grant.antenna_beamwidth, cbsd_grant.antenna_gain)\n\n  # Compute ESC antenna gain in the direction of CBSD\n  esc_ant_gain = antenna.GetAntennaPatternGains(\n      incidence_angles.hor_rx,\n      esc_antenna_info.antenna_azimuth,\n      esc_antenna_info.antenna_gain_pattern)\n\n  # Get the total antenna gain by summing the antenna gains from CBSD to ESC\n  # and ESC to CBSD\n  effective_ant_gain = ant_gain + esc_ant_gain\n\n  # Compute the interference value for ESC entity\n  eirp = getEffectiveSystemEirp(max_eirp, cbsd_grant.antenna_gain,\n                                effective_ant_gain)\n  interference = eirp - db_loss - getEscMaskLoss(constraint)\n  return interference\n\n\ndef computeInterferenceFssCochannel(cbsd_grant, constraint, fss_info, max_eirp):\n  \"\"\"Computes interference that a grant causes to a FSS protection point.\n\n  Routine to compute interference neighborhood grant causes to FSS protection\n  point for co-channel passband.\n\n  Args:\n    cbsd_grant: A CBSD grant of type |data.CbsdGrantInfo|.\n    constraint: The protection constraint of type |data.ProtectionConstraint|.\n    fss_info: The FSS information of type |data.FssInformation|.\n    max_eirp: The maximum EIRP allocated to the grant during IAP procedure.\n  Returns:\n    The interference contribution(dBm).\n  \"\"\"\n  # Get the propagation loss and incident angles for FSS entity_type\n  db_loss, incidence_angles, _ = wf_itm.CalcItmPropagationLoss(cbsd_grant.latitude,\n                                   cbsd_grant.longitude, cbsd_grant.height_agl,\n                                   constraint.latitude, constraint.longitude,\n                                   fss_info.height_agl, cbsd_grant.indoor_deployment,\n                                   reliability=-1, freq_mhz=FREQ_PROP_MODEL_MHZ)\n\n  # Compute CBSD antenna gain in the direction of protection point\n  ant_gain = antenna.GetStandardAntennaGains(incidence_angles.hor_cbsd,\n               cbsd_grant.antenna_azimuth, cbsd_grant.antenna_beamwidth,\n               cbsd_grant.antenna_gain)\n\n  # Compute FSS antenna gain in the direction of CBSD\n  fss_ant_gain = antenna.GetFssAntennaGains(incidence_angles.hor_rx,\n                   incidence_angles.ver_rx, fss_info.pointing_azimuth,\n                   fss_info.pointing_elevation, fss_info.max_gain_dbi)\n\n  # Get the total antenna gain by summing the antenna gains from CBSD to FSS\n  # and FSS to CBSD\n  effective_ant_gain = ant_gain + fss_ant_gain\n\n  # Compute the interference value for Fss co-channel entity\n  eff_bandwidth = (min(cbsd_grant.high_frequency, constraint.high_frequency)\n                   - max(cbsd_grant.low_frequency, constraint.low_frequency))\n  if eff_bandwidth <= 0:\n    raise ValueError('Computing FSS co-channel on grant fully outside FSS passband')\n\n  eirp = getEffectiveSystemEirp(max_eirp, cbsd_grant.antenna_gain,\n                                effective_ant_gain, eff_bandwidth)\n  interference = eirp - db_loss - IN_BAND_INSERTION_LOSS\n  return interference\n\n\ndef getFssMaskLoss(cbsd_grant, constraint):\n  \"\"\"Gets the FSS mask loss for a FSS blocking protection constraint.\n\n  Args:\n    cbsd_grant: A CBSD grant of type |data.CbsdGrantInfo|.\n    constraint: The protection constraint of type |data.ProtectionConstraint|.\n      The constraint defines the FSS out of band left part, so typically\n      [3550, min_passband_freq] or [3550, 3700].\n  \"\"\"\n  # Sanity checks\n  if (cbsd_grant.low_frequency >= cbsd_grant.high_frequency or\n      cbsd_grant.low_frequency >= constraint.high_frequency):\n    raise ValueError('CBSD grant frequencies incorrect')\n\n  # Find the 50MHz edge and its rounded version\n  edge_freq = constraint.high_frequency - 50*MHZ\n  edge_freq_round = int(edge_freq/MHZ +0.5)*MHZ\n  # Part of grant in closest mask segment\n  seg1 = (max(cbsd_grant.low_frequency, edge_freq_round),\n          min(cbsd_grant.high_frequency, constraint.high_frequency))\n  # Part of grant in farther mask segment\n  seg2 = (cbsd_grant.low_frequency,\n          min(cbsd_grant.high_frequency, edge_freq_round))\n\n  # Now compute the attenuation\n  freqs1 = np.arange(seg1[0] + 0.5*MHZ, seg1[1], MHZ)\n  freqs2 = np.arange(seg2[0] + 0.5*MHZ, seg2[1], MHZ)\n  attens1 = (constraint.high_frequency - freqs1)/MHZ * 0.6 + 0.5\n  attens2 = (edge_freq - freqs2)/MHZ * 0.25 + 30.5\n  attens = np.concatenate((attens1, attens2))\n  fss_mask_attenuation = -linearToDb(np.mean(dbToLinear(-attens)))\n  return fss_mask_attenuation\n\n\ndef computeInterferenceFssBlocking(cbsd_grant, constraint, fss_info, max_eirp):\n  \"\"\"Computes interference that a grant causes to a FSS protection point.\n\n  Routine to compute interference neighborhood grant causes to FSS protection\n  point for blocking passband\n\n  Args:\n    cbsd_grant: A CBSD grant of type |data.CbsdGrantInfo|.\n    constraint: The protection constraint of type |data.ProtectionConstraint|.\n    fss_info: The FSS information of type |data.FssInformation|.\n    max_eirp: The maximum EIRP allocated to the grant during IAP procedure.\n\n  Returns:\n    The interference contribution(dBm).\n  \"\"\"\n  # Get the propagation loss and incident angles for FSS entity\n  # blocking channels\n  db_loss, incidence_angles, _ = wf_itm.CalcItmPropagationLoss(\n                                   cbsd_grant.latitude, cbsd_grant.longitude,\n                                   cbsd_grant.height_agl, constraint.latitude,\n                                   constraint.longitude, fss_info.height_agl,\n                                   cbsd_grant.indoor_deployment, reliability=-1,\n                                   freq_mhz=FREQ_PROP_MODEL_MHZ)\n\n  # Compute CBSD antenna gain in the direction of protection point\n  ant_gain = antenna.GetStandardAntennaGains(incidence_angles.hor_cbsd,\n               cbsd_grant.antenna_azimuth, cbsd_grant.antenna_beamwidth,\n               cbsd_grant.antenna_gain)\n\n  # Compute FSS antenna gain in the direction of CBSD\n  fss_ant_gain = antenna.GetFssAntennaGains(incidence_angles.hor_rx,\n                   incidence_angles.ver_rx, fss_info.pointing_azimuth,\n                   fss_info.pointing_elevation, fss_info.max_gain_dbi)\n\n  # Get the total antenna gain by summing the antenna gains from CBSD to FSS\n  # and FSS to CBSD\n  effective_ant_gain = ant_gain + fss_ant_gain\n\n  # Compute EIRP of CBSD grant inside the frequency range of\n  # protection constraint\n  eff_bandwidth = (min(cbsd_grant.high_frequency, constraint.high_frequency)\n                   - cbsd_grant.low_frequency)\n  if eff_bandwidth <= 0:\n    raise ValueError('Computing FSS blocking on grant fully inside FSS passband')\n  eirp = getEffectiveSystemEirp(max_eirp, cbsd_grant.antenna_gain,\n                                effective_ant_gain, eff_bandwidth)\n  # Calculate the interference contribution\n  interference = eirp - getFssMaskLoss(cbsd_grant, constraint) - db_loss\n\n  return interference\n\n\ndef getEffectiveSystemEirp(max_eirp, cbsd_max_ant_gain, effective_ant_gain,\n                           reference_bandwidth=RBW_HZ):\n  \"\"\"Calculates effective EIRP caused by a grant.\n\n  Utility API to get effective EIRP caused by a grant in the\n  neighborhood of the protected entity FSS/ESC/PPA/GWPZ.\n\n  Args:\n    max_eirp: The maximum EIRP allocated to the grant during IAP procedure.\n    cbsd_max_ant_gain: The nominal antenna gain of the CBSD.\n    effective_ant_gain: The actual total antenna gains at the CBSD and protected\n      entity. This takes into account the actual antenna patterns.\n    reference_bandwidth: Reference bandwidth over which effective EIRP is calculated.\n  Returns:\n    The effective EIRP of the CBSD(dBm)\n  \"\"\"\n\n  eirp_cbsd = ((max_eirp - cbsd_max_ant_gain) + effective_ant_gain +\n               linearToDb(reference_bandwidth / MHZ))\n\n  return eirp_cbsd\n\n\ndef computeInterference(grant, eirp, constraint,\n                        fss_info=None, esc_antenna_info=None, region_type=None):\n  \"\"\"Calculates interference caused by a grant.\n\n  Utility API to get interference caused by a grant in the\n  neighborhood of the protected entity FSS/ESC/PPA/GWPZ.\n\n  Args:\n    grant: A CBSD grant of type |data.CbsdGrantInfo|.\n    eirp: The EIRP of the grant.\n    constraint: A protection constraint of type |data.ProtectionConstraint|.\n    fss_info: The FSS information of type |data.FssInformation|.\n    esc_antenna_info: ESC antenna information of type |data.EscInformation|.\n    region_type: Region type of the GWPZ or PPA area:\n                   'URBAN', 'SUBURBAN' or 'RURAL'.\n  Returns:\n    interference: Interference caused by a grant(dBm)\n  \"\"\"\n  # Compute interference to FSS Co-channel protection constraint\n  if constraint.entity_type is data.ProtectedEntityType.FSS_CO_CHANNEL:\n    interference = computeInterferenceFssCochannel(\n                     grant, constraint, fss_info, eirp)\n\n  # Compute interference to FSS Blocking protection constraint\n  elif constraint.entity_type is data.ProtectedEntityType.FSS_BLOCKING:\n    interference = computeInterferenceFssBlocking(\n                     grant, constraint, fss_info, eirp)\n\n  # Compute interference to ESC protection constraint\n  elif constraint.entity_type is data.ProtectedEntityType.ESC:\n    interference = computeInterferenceEsc(\n                     grant, constraint, esc_antenna_info, eirp)\n\n  # Compute interference to GWPZ or PPA protection constraint\n  else:\n    interference = computeInterferencePpaGwpzPoint(\n                     grant, constraint, GWPZ_PPA_HEIGHT,\n                     eirp, region_type)\n\n  return interference\n", "meta": {"hexsha": "ad6e8c556690923208f25c0deef9664dd2b447ec", "size": 21426, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/harness/reference_models/interference/interference.py", "max_stars_repo_name": "nirajankeybridge/Spectrum-Access-System", "max_stars_repo_head_hexsha": "e4e157f3b8fc9f29cb6fbb283acc3a7cbb1212e1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/harness/reference_models/interference/interference.py", "max_issues_repo_name": "nirajankeybridge/Spectrum-Access-System", "max_issues_repo_head_hexsha": "e4e157f3b8fc9f29cb6fbb283acc3a7cbb1212e1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/harness/reference_models/interference/interference.py", "max_forks_repo_name": "nirajankeybridge/Spectrum-Access-System", "max_forks_repo_head_hexsha": "e4e157f3b8fc9f29cb6fbb283acc3a7cbb1212e1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9674952199, "max_line_length": 117, "alphanum_fraction": 0.726080463, "include": true, "reason": "import numpy", "num_tokens": 5254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3557748935136303, "lm_q1q2_score": 0.19863872695545312}}
{"text": "\"\"\"\nTodo's\n\"\"\"\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport copy\nimport numpy as np\nimport uncertainties as uct\nfrom uncertainties import unumpy as unp\nfrom ..etc import isuncertainties\n\nc_map = cm.jet  # mpl.cm.inferno #mpl.cm.CMRmap_r # mpl.cm.brg #mpl.cm.gray_r #\n\n\ndef thermal_data(data, figsize=(12, 4), ms_data=50,\n                 v_label='Unit-cell volume $(\\mathrm{\\AA}^3)$',\n                 pdf_filen=None, title='P-V-T data'):\n    \"\"\"\n    plot P-V-T data before fitting\n\n    :param data: {'p': unumpy array, 'v': unumpy array, 'temp': unumpy array}\n    :param eoscurves: {'v': unumpy array, '300': unumpy array\n            at the temperature ....}\n    :param v_label: label for volume axis\n    :param figsize: figure size\n    :param ms_data: marker size for data points\n    :param pdf_filen: name of pdf output file\n    :param title: title of the figure\n    :return: None\n    \"\"\"\n    # basic figure setup\n    f, ax = plt.subplots(1, 2, figsize=figsize, sharex=True)\n\n    # read data to plot\n    if isuncertainties([data['p'], data['v'], data['temp']]):\n        p = unp.nominal_values(data['p'])\n        v = unp.nominal_values(data['v'])\n        temp = unp.nominal_values(data['temp'])\n        sp = unp.std_devs(data['p'])\n        sv = unp.std_devs(data['v'])\n        stemp = unp.std_devs(data['temp'])\n        ax[0].errorbar(p, v, xerr=sp, yerr=sv, marker=' ',\n                       c='k', ms=0, mew=0, linestyle='None',\n                       capsize=0, lw=0.5, zorder=1)\n        ax[1].errorbar(p, temp, xerr=sp, yerr=stemp, marker=' ',\n                       c='k', ms=0, mew=0, linestyle='None',\n                       capsize=0, lw=0.5, zorder=1)\n    else:\n        p = data['p']\n        v = data['v']\n        temp = data['temp']\n    points = ax[0].scatter(p, v, marker='o', s=ms_data, c=temp,\n                           cmap=c_map, vmin=300., vmax=temp.max(), zorder=2)\n    points = ax[1].scatter(p, temp, marker='o', s=ms_data, c=temp,\n                           cmap=c_map, vmin=300., vmax=temp.max(), zorder=2)\n\n    ax[0].set_xlabel('Pressure (GPa)')\n    ax[1].set_xlabel('Pressure (GPa)')\n    ax[0].set_ylabel(v_label)\n    ax[1].set_ylabel('Temperature (K)')\n    f.suptitle(title)\n    # the parameters are the specified position you set\n    position = f.add_axes([0.92, 0.11, .01, 0.75])\n    f.colorbar(points, orientation=\"vertical\", cax=position)\n    # position.text(150., 0.5, 'Temperature (K)', fontsize=10,\n    # rotation=270, va='center')\n    if pdf_filen is not None:\n        f.savefig(pdf_filen)\n\n\nc_map = cm.jet\n\n\ndef thermal_fit_result(fit_result, v_residual=None,\n                       v_label='Unit-cell volume $(\\mathrm{\\AA}^3)$',\n                       temp_fitline=np.asarray(\n                           [300., 1000., 1500., 2000., 2500., 3000.]),\n                       figsize=(5, 5), height_ratios=(3, 1), ms_data=50,\n                       p_err=None, v_err=None, cbar_loc=(0.99, 0.1, .01, 0.82),\n                       pdf_filen=None, title='Fit result'):\n    \"\"\"\n    plot P-V-T EOS curve fitting result\n\n    :param fit_result: lmfit result object, see example jnb file for detail\n    :param v_label: label for volume axis\n    :param temp_fitline: temperatures to calculate isothermal compression\n        curves, default = [300., 1000., 1500., 2000., 2500., 3000.]\n    :param figsize: figure size, default = (7,7)\n    :param height_ratios: height ratio between the main and residue plots,\n        default = (3,1)\n    :param ms_data: marker size for data points\n    :param p_err: pressure error bar\n    :param v_err: volume error bar\n    :param cbar_loc: location of color bar\n    :param pdf_filen: name of pdf output file\n    :param title: title of the figure\n    :return: None\n    \"\"\"\n    # basic figure setup\n    f, ax = plt.subplots(2, 1, sharex=True, figsize=figsize,\n                         gridspec_kw={'height_ratios': height_ratios})\n    for ax_i in ax:\n        ax_i.tick_params(direction='in')\n    # read data to plot\n    v_data = fit_result.userkws['v']\n    temp_data = fit_result.userkws['temp']\n    p_data = fit_result.data\n    p_datafit = fit_result.best_fit\n    v0 = uct.ufloat(fit_result.params['st_v0'].value,\n                    fit_result.params['st_v0'].stderr)\n    sm = plt.cm.ScalarMappable(cmap=c_map,\n                               norm=plt.Normalize(\n                                   vmin=300., vmax=temp_data.max()))\n    a = sm.to_rgba(temp_fitline)\n    v_fitline = np.linspace(v0.n, min(v_data), 1000)\n    fitmodel_copy = copy.deepcopy(fit_result)\n    for a_i, temp_i in zip(a, temp_fitline):\n        p_fitline = fitmodel_copy.eval(v=v_fitline,\n                                       temp=np.ones_like(v_fitline) * temp_i)\n        ax[0].plot(p_fitline, v_fitline, c=a_i)\n    # error range here does not make a lot sense, so not supported\n    # if (p_err is not None) and (v_err is not None):\n    ax[0].errorbar(p_data, v_data, xerr=p_err, yerr=v_err, fmt=' ', c='k',\n                   capsize=0, elinewidth=0.5, label='Data', zorder=0)\n    points = ax[0].scatter(p_data, v_data, marker='o', s=ms_data, c=temp_data,\n                           cmap=c_map, vmin=300., vmax=temp_data.max(),\n                           zorder=1)\n    if v_residual is None:\n        ax[1].scatter(p_data, p_data - p_datafit, marker='o', s=ms_data,\n                      c=temp_data, cmap=c_map, vmin=300.,\n                      vmax=temp_data.max(), zorder=1)\n        ax[1].errorbar(p_data, p_data - p_datafit, yerr=p_err, fmt=' ', c='k',\n                       capsize=0, elinewidth=0.5, label='Data', zorder=0)\n        ax[1].set_ylabel('$P_{obs} - P_{fit}$')\n    else:\n        ax[1].scatter(p_data, v_residual, marker='o', s=ms_data, c=temp_data,\n                      cmap=c_map, vmin=300., vmax=temp_data.max(), zorder=1)\n        ax[1].errorbar(p_data, v_residual, yerr=p_err, fmt=' ', c='k',\n                       capsize=0, elinewidth=0.5, label='Data', zorder=0)\n        ax[1].set_ylabel('$V_{obs} - V_{fit}$')\n    # ax[0].legend()\n    position = f.add_axes(cbar_loc)\n    f.colorbar(points, orientation=\"vertical\", cax=position,\n               ticks=temp_fitline)\n    ax[1].axhline(0, c='k', ls='--')\n    ax[1].set_xlabel('Pressure (GPa)')\n    ax[0].set_ylabel(v_label)\n    ax[0].set_title(title)\n    plt.tight_layout()\n    if pdf_filen is not None:\n        f.savefig(pdf_filen)\n", "meta": {"hexsha": "d6f7b7d3fb0f3dcebeef6d82aebb459dc1616bcd", "size": 6356, "ext": "py", "lang": "Python", "max_stars_repo_path": "pytheos/plot/thermal_fit.py", "max_stars_repo_name": "SHDShim/pytheos", "max_stars_repo_head_hexsha": "be079624405e92fbec60c5ead253eb5917e55237", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-06-23T03:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-02T01:06:50.000Z", "max_issues_repo_path": "pytheos/plot/thermal_fit.py", "max_issues_repo_name": "SHDShim/pytheos", "max_issues_repo_head_hexsha": "be079624405e92fbec60c5ead253eb5917e55237", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-03-06T00:07:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-18T17:42:26.000Z", "max_forks_repo_path": "pytheos/plot/thermal_fit.py", "max_forks_repo_name": "SHDShim/pytheos", "max_forks_repo_head_hexsha": "be079624405e92fbec60c5ead253eb5917e55237", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-07-11T19:40:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-12T02:20:39.000Z", "avg_line_length": 41.8157894737, "max_line_length": 79, "alphanum_fraction": 0.5797671492, "include": true, "reason": "import numpy", "num_tokens": 1829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.1986387269554531}}
{"text": "\"\"\"\nThis class implements simple policy gradient algorithm for\nbiasing the generation of molecules towards desired values of\nproperties aka Reinforcement Learninf for Structural Evolution (ReLeaSE)\nas described in \nPopova, M., Isayev, O., & Tropsha, A. (2018). \nDeep reinforcement learning for de novo drug design. \nScience advances, 4(7), eaap7885.\n\"\"\"\n\nimport torch\nimport torch.nn.functional as F\nimport numpy as np\nfrom rdkit import Chem\n\n\nclass Reinforcement(object):\n    #def __init__(self, generator, predictor, get_reward):\n    def __init__(self, generator, get_reward):\n        \"\"\"\n        Constructor for the Reinforcement object.\n\n        Parameters\n        ----------\n        generator: object of type StackAugmentedRNN\n            generative model that produces string of characters (trajectories)\n\n        predictor: object of any predictive model type\n            predictor accepts a trajectory and returns a numerical\n            prediction of desired property for the given trajectory\n\n        get_reward: function\n            custom reward function that accepts a trajectory, predictor and\n            any number of positional arguments and returns a single value of\n            the reward for the given trajectory\n            Example:\n            reward = get_reward(trajectory=my_traj, predictor=my_predictor,\n                                custom_parameter=0.97)\n\n        Returns\n        -------\n        object of type Reinforcement used for biasing the properties estimated\n        by the predictor of trajectories produced by the generator to maximize\n        the custom reward function get_reward.\n        \"\"\"\n\n        super(Reinforcement, self).__init__()\n        self.generator = generator\n        #self.predictor = predictor\n        self.get_reward = get_reward\n\n    def policy_gradient(self, data, n_batch=10, gamma=0.97,\n                        std_smiles=False, grad_clipping=None, **kwargs):\n        \"\"\"\n        Implementation of the policy gradient algorithm.\n\n        Parameters:\n        -----------\n\n        data: object of type GeneratorData\n            stores information about the generator data format such alphabet, etc\n\n        n_batch: int (default 10)\n            number of trajectories to sample per batch. When training on GPU\n            setting this parameter to to some relatively big numbers can result\n            in out of memory error. If you encountered such an error, reduce\n            n_batch.\n\n        gamma: float (default 0.97)\n            factor by which rewards will be discounted within one trajectory.\n            Usually this number will be somewhat close to 1.0.\n\n\n        std_smiles: bool (default False)\n            boolean parameter defining whether the generated trajectories will\n            be converted to standardized SMILES before running policy gradient.\n            Leave this parameter to the default value if your trajectories are\n            not SMILES.\n\n        grad_clipping: float (default None)\n            value of the maximum norm of the gradients. If not specified,\n            the gradients will not be clipped.\n\n        kwargs: any number of other positional arguments required by the\n            get_reward function.\n\n        Returns\n        -------\n        total_reward: float\n            value of the reward averaged through n_batch sampled trajectories\n\n        rl_loss: float\n            value for the policy_gradient loss averaged through n_batch sampled\n            trajectories\n\n        \"\"\"\n        rl_loss = 0\n        self.generator.optimizer.zero_grad()\n        total_reward = 0\n        \n        for _ in range(n_batch):\n\n            # Sampling new trajectory\n            reward = 0\n            trajectory = '<>'\n            while reward == 0:\n                trajectory = self.generator.evaluate(data)\n                if std_smiles:\n                    try:\n                        mol = Chem.MolFromSmiles(trajectory[1:-1])\n                        trajectory = '<' + Chem.MolToSmiles(mol) + '>'\n                        #reward = self.get_reward(trajectory[1:-1], \n                        #                         self.predictor, \n                        #                         **kwargs)\n                        reward = self.get_reward(trajectory[1:-1])\n                    except:\n                        reward = 0\n                else:\n                    #reward = self.get_reward(trajectory[1:-1],\n                    #                         self.predictor, \n                    #                         **kwargs)\n                    reward = self.get_reward(trajectory[1:-1])\n\n            # Converting string of characters into tensor\n            trajectory_input = data.char_tensor(trajectory)\n            discounted_reward = reward\n            total_reward += reward\n\n            # Initializing the generator's hidden state\n            hidden = self.generator.init_hidden()\n            if self.generator.has_cell:\n                cell = self.generator.init_cell()\n                hidden = (hidden, cell)\n            if self.generator.has_stack:\n                stack = self.generator.init_stack()\n            else:\n                stack = None\n\n            # \"Following\" the trajectory and accumulating the loss\n            for p in range(len(trajectory)-1):\n                output, hidden, stack = self.generator(trajectory_input[p], \n                                                       hidden, \n                                                       stack)\n                log_probs = F.log_softmax(output, dim=1)\n                top_i = trajectory_input[p+1]\n                rl_loss -= (log_probs[0, top_i]*discounted_reward)\n                discounted_reward = discounted_reward * gamma\n\n        # Doing backward pass and parameters update\n        rl_loss = rl_loss / n_batch\n        total_reward = total_reward / n_batch\n        rl_loss.backward()\n        if grad_clipping is not None:\n            torch.nn.utils.clip_grad_norm_(self.generator.parameters(), \n                                           grad_clipping)\n\n        self.generator.optimizer.step()\n        \n        return total_reward, rl_loss.item()\n", "meta": {"hexsha": "4ad3230cca928e3ee576d783d9b1370b0596baf1", "size": 6134, "ext": "py", "lang": "Python", "max_stars_repo_path": "release/reinforcement.py", "max_stars_repo_name": "flyyufelix/ReLeaSE", "max_stars_repo_head_hexsha": "a13e50072193eb3c2f931fb968d68f71a4c636ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "release/reinforcement.py", "max_issues_repo_name": "flyyufelix/ReLeaSE", "max_issues_repo_head_hexsha": "a13e50072193eb3c2f931fb968d68f71a4c636ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "release/reinforcement.py", "max_forks_repo_name": "flyyufelix/ReLeaSE", "max_forks_repo_head_hexsha": "a13e50072193eb3c2f931fb968d68f71a4c636ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3375, "max_line_length": 81, "alphanum_fraction": 0.5743397457, "include": true, "reason": "import numpy", "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.3557748935136304, "lm_q1q2_score": 0.19863872172613714}}
{"text": "\"\"\"Implements a factored random geometric graph\n\nA factored random geometric graph is special representation of a random\ngeometric graph, for the case when the configuration space is the\nCartesian product of a numbor of component manifolds. The particular\ncase of interest is the manifold of configurations of K objects, which\nis the Cartesian product of K copies SE(2) (in two dimensions) or SE(3)\nin three dimensions.\n\nThe vertices can be represented by length-K tuples, where each element\nis an index into a sequence of configurations in one of the component\nmanifolds. The precise form of edges required to ensure probabilistic\ncompleteness and asymptotic optimality is an object of ongoing research.\n\nThe classes in this module take objects parameterizing dynamics and\ngeometry, and do the bookkeeping necessary to maintain a factored random\ngeometric graph.\n\"\"\"\nimport math\nimport itertools\n\nimport numpy\nfrom scipy.spatial import cKDTree\n\nimport metis\nfrom metis.abstract_graphs import UndirectedGraph\n\nclass NoObjectContactBlacklist(object):\n    def __init__(self, robot='robot'):\n        super(NoObjectContactBlacklist, self).__init__()\n        self.robot = robot\n\n    def __contains__(self, pair):\n        return pair[0] != self.robot and pair[1] is not None\n\ndef apply_transform(tfA, tfB):\n    \"\"\"Return the result of applying tfA to tfB\n\n    Args:\n        tfA (tuple): a transform, represented as an (x, y, theta) tuple\n        tfB (tuple): a transform, represented as an (x, y, theta) tuple\n\n    Returns:\n        tuple: (x, y, theta) representing a transform with the same\n            effect as first applying 'tfB' and then applying 'tfA'. If\n            the transforms were represented as matrices, this would be\n            tfA * tfB.\n    \"\"\"\n    return (tfA[0] + numpy.cos(tfA[2]) * tfB[0] - numpy.sin(tfA[2]) * tfB[1],\n            tfA[1] + numpy.sin(tfA[2]) * tfB[0] + numpy.cos(tfA[2]) * tfB[1],\n            tfA[2] + tfB[2])\n\ndef apply_inverse_transform(tfA, tfB):\n    \"\"\"Return the result of applying tfA to the inverse of tfB\n\n    Args:\n        tfA (tuple): a transform, represented as an (x, y, theta) tuple\n        tfB (tuple): a transform, represented as an (x, y, theta) tuple\n\n    Returns:\n        tuple: (x, y, theta) representing a transform with the same\n            effect as first applying the inverse of 'tfB' and then\n            applying 'tfA'. If the transforms were represented as\n            matrices, this would be tfA / tfB.\n    \"\"\"\n    dtf = tfA - tfB\n    return (numpy.cos(tfB[2]) * dtf[0] + numpy.sin(tfB[2]) * dtf[1],\n            -numpy.sin(tfB[2]) * dtf[0] + numpy.cos(tfB[2]) * dtf[1],\n            dtf[2])\n\nclass Manifold(object):\n    def __init__(self, samples):\n        self.samples = numpy.array(samples)\n        assert self.samples.ndim == 2, \"Data must be a sequence of samples\"\n\n    def __len__(self):\n        return len(self.samples)\n\n    def __iter__(self):\n        return iter(xrange(len(self.samples)))\n\n    def __contains__(self, index):\n        return 0 <= index < len(self.samples)\n\n    def __getitem__(self, index):\n        return self.samples[index]\n\n    def nearest_samples(self, point, k):\n        \"\"\"Return then indices of the samples near the query pose\"\"\"\n        pass\n\n    def nearby_samples(self, point, r):\n        \"\"\"Return then indices of the samples near the query pose\"\"\"\n        pass\n\n\n    def neighbors(self, index):\n        \"\"\"Return the neighbors of the specified sample index\"\"\"\n        pass\n\n\nclass SE2Manifold(Manifold):\n    \"\"\"Random disc graph on a manifold\n\n    A random disc graph has vertices sampled from an n dimensional\n    manifold, and an edge between all vertices with minimal geodesic\n    distance less than a fixed constant. We take that constant to be the\n    critical distance derived in Karaman and Frazzoli (2011), which is\n    minimal distance required to ensure the resulting graph includes an\n    optimal path.\n\n    Vertex labels are just indices of an array of points, so any integer\n    between 0 and `count-1`.\n\n    Args:\n        samples (array-like): if supplied, include these\n            configurations as vertices in the graph, in addition to\n            `count` random configurations.\n        epsilon (float): positive scalar multiplier by which to\n            approximate nearest neighbor search (larger is faster but\n            less accurate)\n        eta (float): positive scalar multiplier by which to inflate the\n            distance threshhold defining the graph (larger is slower but\n            more accurate; graph is asymptotically optimal iff eta>=1)\n\n    Attributes:\n        geometry (metis.geometry.Geometry): object describing problem geometry\n        configurations (numpy.array): array of samples corresponding to\n            vertices. Each row is a sample from the configuration space\n            defined by geometry.\n        epsilon (float): positive scalar multiplier by which to\n            approximate nearest neighbor search (larger is faster but\n            less accurate)\n        eta (float): positive scalar multiplier by which to inflate the\n            distance threshhold defining the graph (larger is slower but\n            more accurate; graph is asymptotically optimal iff eta>=1)\n        mu_free (float); positive scalar approximating the Lebesgue\n            measure of free space in the configuration\n        search_radius (float): positive scalar defining maximum distance\n            between vertices for which an edge may exist\n        nearby_configurations (list(list)): list of lists of neighboring\n            vertices for each vertex in the graph. Precomputed for speed\n    \"\"\"\n    def __init__(self, samples, scale=1., epsilon=0., search_radius=None, eta=1.):\n        super(SE2Manifold, self).__init__(samples)\n        assert self.samples.shape[1] == 3, \\\n            \"Data must be 'x, y, theta' sequences\"\n\n        self.scale = scale\n        self.epsilon = epsilon\n        self.eta = eta\n\n        if search_radius is None:\n            count, dim = self.samples.shape\n            d_inv = 1. / float(dim)\n            zeta_d = math.pi**(dim/2) / math.gamma(dim/2 + 1)\n\n            mu_free = (numpy.prod(numpy.ptp(self.samples[:,:-1], axis=0))\n                       * 2 * numpy.pi * scale)\n            self.search_radius = 2 * self.eta * (\n                d_inv * (mu_free / zeta_d) * (math.log(count) / float(count))\n                )**d_inv\n        else:\n            self.search_radius = search_radius\n\n        self._search = cKDTree(numpy.concatenate(\n            (self.samples[:, :-1],\n             self.scale * numpy.cos(self.samples[:, -1:]),\n             self.scale * numpy.sin(self.samples[:, -1:])), axis=1))\n        self._neighbors = self._search.query_ball_tree(\n            self._search, (1 + epsilon) * self.search_radius, eps=epsilon)\n\n    def nearest_samples(self, point, k):\n        \"\"\"Return the indices of the k samples nearest the query point\n\n        Args:\n            point: query location, represented as an (x, y, theta) tuple\n\n        Returns:\n            list: list of tuples (d, i), where d is the distance between\n                sample i and the query point\n        \"\"\"\n        query = (point[0], point[1],\n                 self.scale * numpy.cos(point[2]),\n                 self.scale * numpy.sin(point[2]))\n        return zip(*self._search.query(query, k))\n\n    def nearby_samples(self, point, r):\n        \"\"\"Return the indices of the samples near the query point\n\n        Args:\n            point: query location, represented as an (x, y, theta) tuple\n            r: search radius\n\n        Returns:\n            list: list of indices of samples within distance r of the\n                query point\n        \"\"\"\n        query = (point[0], point[1],\n                 self.scale * numpy.cos(point[2]),\n                 self.scale * numpy.sin(point[2]))\n        return self._search.query_ball_point(\n            query, (1+self.epsilon)*r, eps=self.epsilon)\n\n    def neighbors(self, vertex):\n        \"\"\"Generate all vertices less than threshhold from vertex\n\n        This is computationally inexpensive due to precomputation.\n        Note:\n            Does not perform collision detection; some edges returned\n            here may not be collision free. Collision detection is\n            performed when the cost of an edge is evaluated.\n\n        Args:\n            vertex (int): index of a vertex in the graph\n\n        Returns:\n            generator(int): generates all neighbors of vertex\n        \"\"\"\n        return (n for n in self._neighbors[vertex] if n != vertex)\n\n    def distance(self, pose1, pose2):\n        point1 = numpy.array((pose1[0], pose1[1],\n                              self.scale * numpy.cos(pose1[2]),\n                              self.scale * numpy.sin(pose1[2])))\n        point2 = numpy.array((pose2[0], pose2[1],\n                              self.scale * numpy.cos(pose2[2]),\n                              self.scale * numpy.sin(pose2[2])))\n        return numpy.sqrt(numpy.sum((point1-point2)**2))\n\nclass FactoredRandomGeometricGraph(UndirectedGraph):\n    \"\"\"Factored random geometric graph for manipulation\n\n    The vertices of this graph are hashable dict-like structures mapping\n    object names to tuples of (parent name, transform index), where\n    parent_name is the name of the object relative to which the\n    transform of the object name is computed. A vertex can be unpacked into\n    configurations using the notation graph[vertex]. The graph is\n    immutable after construction; vertex data cannot be changed or\n    deleted.\n\n    Args:\n        geometry (ManyShapeGeometry): object describing problem geometry\n        dynamics: used to determine how each object can move\n        robot (str): the identifier of the object to consider the\n            robot for planning purposes\n        geometry (metis.geometry.ManyShapeGeometry): object describing\n            problem geometry\n        counts (dict): maps manifolds, specified as (object, object)\n            2-tuples, to the number of random samples to draw from that\n            manifold\n        default_count (int): number of poses of each object to sample.\n            This value is used for any manifold not specified in counts,\n            and is overridden by any manifold specified in counts.\n        configurations (dict): if supplied, include these\n            configurations in the component set for the supplied\n            objects, in addition to `count` random configurations.\n        epsilon (float): positive scalar multiplier by which to\n            approximate nearest neighbor search (larger is faster but\n            less accurate)\n        eta (float): positive scalar multiplier by which to inflate the\n            distance threshhold defining the graph (larger is slower but\n            more accurate; graph is asymptotically optimal iff eta>=1)\n\n    Attributes:\n        geometry (ManyShapeGeometry): object describing problem geometry\n        dynamics: used to determine how each object can move\n        robot (str): the identifier of the object to consider the\n            robot for planning purposes\n        manifolds (dict): maps manifold names to structures defining the\n            manifolds themselves\n        epsilon (float): positive scalar multiplier by which to\n            approximate nearest neighbor search (larger is faster but\n            less accurate)\n        eta (float): positive scalar multiplier by which to inflate the\n            distance threshhold defining the graph (larger is slower but\n            more accurate; graph is asymptotically optimal iff eta>=1)\n    \"\"\"\n    def __init__(self, geometry, dynamics, counts=None, default_count=0,\n                 configurations=None, blacklist=(), robot='robot',\n                 epsilon=0., eta=1.):\n        # pylint: disable=too-many-arguments\n        assert robot in geometry.bodies\n\n        # Rebind default mutable arguments\n        if counts is None:\n            counts = {}\n        if configurations is None:\n            configurations = {}\n\n        # Declare members\n        self.geometry = geometry\n        self.dynamics = dynamics\n        self.names = [name for name in geometry.bodies]\n        self.samples = {}\n        self.robot = robot\n        self.epsilon = epsilon\n        self.eta = eta\n\n        for name in self.names:\n            transforms = configurations.get((name, None), [])\n            count = counts.get((name, None), default_count)\n            transforms += [geometry.sample_object_configuration(name)\n                           for _ in xrange(count)]\n            self.samples[(name, None)] = SE2Manifold(transforms, epsilon=epsilon, eta=eta)\n\n            # Sample poses relative to other objects\n            for other in self.names:\n                if name != other and (name, other) not in blacklist:\n                    count = counts.get((name, other), default_count)\n                    poses = list(dynamics.sample_from_manifold((name, other), count))\n                    self.samples[(name, other)] = SE2Manifold(\n                        [pose for pose in poses])\n                else:\n                    self.samples[(name, other)] = Manifold([[]])\n\n    @staticmethod\n    def is_acyclic(vertex):\n        \"\"\"Determine if a directed chain graph is acyclic\n\n        An acyclic chain is one name for a directed graph where each\n        vertex is the source of at most one outward edge, and there are\n        no cycles of directed edges. So for vertices (A, B, C), A=>B=>C\n        would be an acyclic chain, while A=>B=>C=>A would not.\n\n        Args:\n            vertex (dict): maps vertex labels to a tuple (parent, None),\n                describing the unique edge beginning at the vertex. A\n                missing edge is denoted as an edge back to the vertex,\n                so `{name: (name, None)}` describes a vertex with label\n                `name` and no outgoing edge. The choice to represent an\n                edge as a tuple with second value None was made for\n                uniformity with the vertex representation, which uses\n                the second argument to specify an index.\n\n        Yields:\n            bool: true if the graph has no cycles\n        \"\"\"\n        todo = set(vertex.iterkeys())\n        while todo:\n            name = todo.pop()\n            chain = set()\n            while True:\n                parent, _ = vertex[name]\n                chain.add(name)\n                if parent is None:\n                    # We've found a root node.\n                    break\n                elif parent in chain:\n                    return False\n                elif parent in todo:\n                    # If we haven't already confirmed this node is not\n                    # part of a cycle, continue searching this chain\n                    name = parent\n                else:\n                    # If we haven't already confirmed this node is not\n                    # part of a cycle, continue searching this chain\n                    break\n            todo -= chain\n        return True\n\n    @staticmethod\n    def acyclic_chains(names):\n        \"\"\"Generate the acyclic chains with labels drawn from names\n\n        An acyclic chain is one name for a directed graph where each\n        vertex is the source of at most one outward edge, and there are\n        no cycles of directed edges. So for vertices (A, B, C), A=>B=>C\n        would be an acyclic chain, while A=>B=>C=>A would not.\n\n        Note there are very many acyclic chains: if there are $n$ names,\n        there are at least $n!$ acyclic chains, and at most $n^n$. This\n        function computes the acyclic chains by sequentially generating\n        all directed graphs with maximal outdegree 1, then rejecting\n        those graphs with cycles. The running time of this function is\n        thus `O(len(names)^len(names))`, also known as really really\n        slow.\n\n        Args:\n            names (list): list of vertex labels\n\n        Yields:\n            dict: maps each name to a tuple (parent, None), where parent\n                is the sink of its unique edge. A missing edge is\n                denoted as an edge back to the vertex, so `{name: (name,\n                None)}` describes a vertex with label `name` and no\n                outgoing edge. The choice to represent an edge as a\n                tuple with second value None was made for uniformity\n                with the vertex representation, which uses the second\n                argument to specify an index..\n        \"\"\"\n        for combination in  itertools.product(*(\n                [(a, b if b != a else None) for b in names]\n                for a in names)):\n            vertex = {name: (parent, None) for name, parent in combination}\n            if FactoredRandomGeometricGraph.is_acyclic(vertex):\n                yield vertex\n\n    def __contains__(self, vertex):\n        \"\"\"Check if the graph contains a vertex\n\n        The graph contains a vertex if the keys are all the object\n        names, the values are tuples (parent, index), the index is a key\n        for the (object, parent) sample set, and the directed graph\n        formed with edges between each object and its parent is acyclic.\n        \"\"\"\n        for name in self.names:\n            if name not in vertex:\n                return False\n            (parent, index) = vertex[name]\n            if (name, parent) not in self.samples:\n                return False\n            if index not in self.samples[(name, parent)]:\n                return False\n        if not self.is_acyclic(vertex):\n            return False\n        return True\n\n    def __len__(self):\n        \"\"\"Check if the graph contains a vertex\n\n        The graph contains a vertex if the keys are all the object\n        names, the values are tuples (parent, index), the index is a key\n        for the (object, parent) sample set, and the directed graph\n        formed with edges between each object and its parent is acyclic.\n        \"\"\"\n        total = 0\n        for vertex in self.acyclic_chains(self.names):\n            prod = 1\n            for name, (parent, _) in vertex.iteritems():\n                prod *= len(self.samples[(name, parent)])\n            total += prod\n        return total\n\n    def __iter__(self):\n        \"\"\"Iterate over all vertices in the graph\n\n        Vertices are generated by sequentially generating acyclic\n        chains, then generating all combinations of vertex indices for\n        those acyclic chains. Note that the size of the graph is\n        superexponential in the number of objects, so it can take a very\n        long time to iterate over all vertices, even for small,\n        low-resolution graphs.\n        \"\"\"\n        for vertex in self.acyclic_chains(self.names):\n            for indices in itertools.product(*(\n                    iter(self.samples[(name, parent)])\n                    for name, (parent, _) in vertex.iteritems())):\n                yield {name: (parent, index)\n                       for (name, (parent, _)), index\n                       in zip(vertex.iteritems(), indices)}\n\n    def get_pose_of(self, vertex, name):\n        \"\"\"Recursively compute the pose of an object at a vertex\"\"\"\n        parent, index = vertex[name]\n        transform = self.samples[(name, parent)][index]\n        if parent is None:\n            return transform\n        else:\n            return apply_transform(self.get_pose_of(vertex, parent), transform)\n\n    def __getitem__(self, vertex):\n        \"\"\"Compute the configuration associated with a vertex\n\n        Because vertices represent the pose of each object relative to\n        the pose of another object, computing the absolute pose of each\n        object requires first computing a topological ordering on the\n        chain, then propagating an absolute pose down the ordering. This\n        could be done by maintaining the vertex structure in a way that\n        makes it easy to identify root poses; however, that would\n        increase the size and complexity of the vertex representation.\n        Instead, we compute the topological ordering implicity by\n        iterating over the objects in an arbitrary order and keeping a\n        'to-do list' of objects discovered whose parents had not yet\n        been grounded.\n\n        Args:\n            vertex (dict)\n\n        Returns:\n            dict: maps object names to (x, y, theta) tuples\n        \"\"\"\n        todo = {}\n        result = {}\n        for name in vertex:\n            parent, index = vertex[name]\n            if parent is None:\n                result[name] = self.samples[(name, parent)][index]\n            elif parent in result:\n                transform = self.samples[(name, parent)][index]\n                result[name] = apply_transform(result[parent], transform)\n            else:\n                todo.setdefault(parent, set()).add(name)\n\n            if name in todo:\n                for child in todo[name]:\n                    expected_name, index = vertex[child]\n                    assert expected_name == name\n                    transform = self.samples[(child, name)][index]\n                    result[child] = apply_transform(result[name], transform)\n        return result\n\n    def __getstate__(self):\n        state = self.__dict__.copy()\n        del state['geometry']\n        del state['dynamics']\n        return state\n\n    def __setstate__(self, state):\n        self.__dict__.update(state)\n        self.geometry = None\n        self.dynamics = None\n\n    def nearest(self, configuration):\n        \"\"\"Return the closest collision-free vertex to configuration\n\n        Distance is the sum of the Euclidean distances between the pose\n        of each object in the configuration and in the vertex. This is\n        computed in a reasonably efficient way using dynamic programming.\n\n        Args:\n            configuration (dict): maps object names to poses\n\n        Returns:\n            dict: a dictionary representing the closest collision-free\n                vertex to configuration\n        \"\"\"\n        def expand_queue(name, k):\n            \"\"\"Return a sorted list of (distance, index) tuples\"\"\"\n            return sorted(self.samples[(name, None)].nearest_samples(\n                configuration[name], k))\n\n        initial_k = 8\n        sample_queues = {}\n        for name in configuration:\n            sample_queues[name] = expand_queue(name, initial_k)\n\n        distance = lambda v: sum(sample_queues[name][v[name]][0]\n                                 for name in configuration)\n        start = metis.hashdict.hashdict({name: 0 for name in configuration})\n        queue = metis.queue.PriorityQueue([(start, distance(start))])\n\n        searched = 0\n        while searched < len(self):\n            current = queue.pop()\n            current_vertex = metis.hashdict.hashdict({\n                name: (None, sample_queues[name][index][1])\n                for name, index in current.iteritems()})\n            searched += 1\n            if self.geometry.configuration_is_free(\n                    self[current_vertex], skip_static=True):\n                return current_vertex\n            else:\n                for name in current:\n                    child = current + {name: current[name] + 1}\n                    k = len(sample_queues[name])\n                    if child[name] == k:\n                        k = min(len(self.samples[(name, None)]), k * 2)\n                        sample_queues[name] = expand_queue(name, k)\n                    if child not in queue:\n                        queue[child] = distance(child)\n\n    def neighbors(self, vertex):\n        \"\"\"Generate neighbors of vertex\n\n        We can construct the adjacent vertices by considering all\n        reachable acyclic chains, then identifying within each chain all\n        configurations within a distance of search_radius from the\n        current vertex.\n\n        Args:\n            vertex (dict): maps object names to tuples (parent, i), with\n                i an index in the sample set (name, parent)\n\n        Yields:\n            hashdict: neighboring vertices on the factored graph\n        \"\"\"\n        # Check if the configuration encoded in the vertex dict is free\n        if not self.geometry.configuration_is_free(\n                self[vertex], skip_static=True):\n            raise StopIteration\n\n        result = metis.hashdict.hashdict(vertex)\n\n        # TODO: Many things in this function should be in the dynamics.\n        # Instead they are hard-coded for convenience\n\n        # Identify the parent and the root of the current vertex (the\n        # root is the ancestor of 'robot' whose parent is None)\n        parent, _ = vertex[self.robot]\n        root_parent = root = self.robot\n        while root_parent is not None:\n            root = root_parent\n            root_parent, root_index = vertex[root]\n\n        # Generate neighbors on the current manifold [D]\n        for sample in self.samples[(root, None)].neighbors(root_index):\n            neighbor = result + {root: (None, sample)}\n            if self.geometry.configuration_is_free(\n                    self[neighbor], skip_static=True):\n                yield neighbor\n\n        # Generate neighbors on adjacent manifolds.  The adjacent\n        # acyclic chains are hard-coded as the chains for which only the\n        # robot changes its parent relative to the chain described in\n        # vertex.\n\n        # We always move through free space to change parents, so use\n        # the search radius for free space\n        radius = self.samples[(self.robot, None)].search_radius\n        if self.robot != root:\n            # The robot is not a root pose: it is currently in contact\n            # with something. Look for poses not in contact with\n            # anything\n            pose = self.get_pose_of(vertex, self.robot)\n            manifold = self.samples[(self.robot, None)]\n            for sample in manifold.nearby_samples(pose, radius):\n                neighbor = result + {self.robot: (None, sample)}\n                if self.geometry.configuration_is_free(\n                        self[neighbor], skip_static=True):\n                    yield neighbor\n\n        for new_parent in self.names:\n            # Consider changing parent to non-root poses\n            if new_parent == self.robot or new_parent == parent:\n                continue\n            else:\n                # Now we find nearby poses in this cycle. Translate the\n                # current pose to a pose relative to the new parent\n                pose = self.get_pose_of(vertex, self.robot)\n                parent_pose = self.get_pose_of(vertex, new_parent)\n                relative_pose = apply_inverse_transform(pose, parent_pose)\n\n                # Search for neighbors near the absolute pose\n                manifold = self.samples[(self.robot, new_parent)]\n                for sample in manifold.nearby_samples(relative_pose, radius):\n                    neighbor = result + {self.robot: (new_parent, sample)}\n                    if self.geometry.configuration_is_free(\n                            self[neighbor], skip_static=True):\n                        yield neighbor\n\n    def cost(self, parent, child):\n        parent_configuration = self[parent]\n        child_configuration = {self.robot: self.get_pose_of(child, self.robot)}\n        holding = child[self.robot][0]\n        if holding is not None:\n            child_configuration[holding] = self.get_pose_of(child, holding)\n        was_holding = parent[self.robot][0]\n        if was_holding is not None:\n            child_configuration[was_holding] = self.get_pose_of(child, was_holding)\n        # child_configuration = {\n        #     name: self.get_pose_of(child, name)\n        #     for name in child if parent[name] != child[name]}\n\n        # TODO: this does not check for collision between objects. I\n        # *think* what we want is for any object that doesn't move to be\n        # treated as part of the background, and any object that does\n        # move to be ignored for collision detection. Not sure how to\n        # accomplish that.\n        if self.geometry.path_is_free(parent_configuration,\n                                      child_configuration,\n                                      skip_configuration=True):\n            return self.dynamics.cost(parent_configuration, child_configuration)\n        else:\n            return float('inf')\n\n\n", "meta": {"hexsha": "64ae7df43fba45d938a58c4e45c57866d301e411", "size": 28257, "ext": "py", "lang": "Python", "max_stars_repo_path": "metis/factored_random_geometric_graphs.py", "max_stars_repo_name": "robustrobotics/forgg", "max_stars_repo_head_hexsha": "97fc0896dfe4522156a42b8eddb641216149c5ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-12-06T19:23:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T07:06:24.000Z", "max_issues_repo_path": "metis/factored_random_geometric_graphs.py", "max_issues_repo_name": "robustrobotics/forgg", "max_issues_repo_head_hexsha": "97fc0896dfe4522156a42b8eddb641216149c5ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "metis/factored_random_geometric_graphs.py", "max_forks_repo_name": "robustrobotics/forgg", "max_forks_repo_head_hexsha": "97fc0896dfe4522156a42b8eddb641216149c5ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.3008982036, "max_line_length": 90, "alphanum_fraction": 0.6078847719, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.19863871932796276}}
{"text": "\"\"\"\nSimplex optimization.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport copy\nimport collections\nimport logging\nimport logging.config\nimport numpy as np\nimport re\nimport sqlite3\nimport textwrap\n\nimport calculate\nimport compare\nimport constants as co\nimport datatypes\nimport opt\nimport parameters\n\nlogger = logging.getLogger(__name__)\n\nclass Simplex(opt.Optimizer):\n    \"\"\"\n    Optimizes force field parameters using an in-house version of the simplex\n    method. See `Optimizer` for repeated documentation.\n\n    Attributes\n    ----------\n    _max_cycles_wo_change : int\n                            End the simplex optimization early if there have\n                            been this many consecutive simplex steps without\n                            improvement in the objective function.\n    do_massive_contraction : bool\n                             If True, allows massive contractions to be\n                             performed, contracting all parameters at once.\n    do_weighted_reflection : bool\n                             If True, weights parameter sets based on their\n                             objective function score when determining the\n                             reflection point.\n    max_cycles : int\n                 Maximum number of simplex cycles.\n\n    max_params : int\n                 Maximum number of parameters used in a single simplex cycle.\n    \"\"\"\n    def __init__(self,\n                 direc=None,\n                 ff=None,\n                 ff_lines=None,\n                 args_ff=None,\n                 args_ref=None):\n        super(Simplex, self).__init__(\n            direc, ff, ff_lines, args_ff, args_ref)\n        self._max_cycles_wo_change = None\n        self.do_massive_contraction = True\n        self.do_weighted_reflection = True\n        self.max_cycles = 100\n        self.max_params = 3\n    @property\n    def best_ff(self):\n        # Typically, self.new_ffs would include the original FF, self.ff,\n        # but this can be changed by massive contractions.\n        if self.new_ffs:\n            self.new_ffs = sorted(self.new_ffs, key=lambda x: x.score)\n            # I think this is necessary after massive contraction.\n            # Massive contraction can potentially make eveything worse.\n            # No, it can't!!! The best FF is always retained! /Per-Ola\n            # Yep, he's right. /Eric\n            if self.new_ffs[0].score < self.ff.score:\n                best_ff = self.new_ffs[0]\n                best_ff = restore_simp_ff(best_ff, self.ff)\n                return best_ff\n            else:\n                return self.ff\n        else:\n            return self.ff\n    @opt.catch_run_errors\n    def run(self, r_data=None):\n        \"\"\"\n        Once all attributes are setup as you so desire, run this method to\n        optimize the parameters.\n\n        Returns\n        -------\n        `datatypes.FF` (or subclass)\n            Contains the best parameters.\n        \"\"\"\n        if r_data is None:\n            r_data = opt.return_ref_data(self.args_ref)\n\n        if self.ff.score is None:\n            logger.log(20, '~~ CALCULATING INITIAL FF SCORE ~~'.rjust(79, '~'))\n            self.ff.export_ff()\n            # Could store data on self.ff.data if we wanted. Not necessary for\n            # simplex. If simplex yielded no improvements, it would return this\n            # FF, and then we might want the data such taht we don't have to\n            # recalculate it in gradient. Let's hope simplex generally yields\n            # improvements.\n            data = calculate.main(self.args_ff)\n            #deprecated\n            #self.ff.score = compare.compare_data(r_data, data)\n            r_dict = compare.data_by_type(r_data)\n            c_dict = compare.data_by_type(data)\n            r_dict, c_dict = compare.trim_data(r_dict,c_dict)\n            self.ff.score = compare.compare_data(r_dict, c_dict)\n        else:\n            logger.log(20, '  -- Reused existing score and data for initial FF.')\n\n        logger.log(20, '~~ SIMPLEX OPTIMIZATION ~~'.rjust(79, '~'))\n        logger.log(20, 'INIT FF SCORE: {}'.format(self.ff.score))\n        opt.pretty_ff_results(self.ff, level=20)\n\n        # Here's what we do if there are too many parameters.\n        if self.max_params and len(self.ff.params) > self.max_params:\n            logger.log(20, '  -- More parameters than the maximum allowed.')\n            logger.log(5, 'CURRENT PARAMS: {}'.format(len(self.ff.params)))\n            logger.log(5, 'MAX PARAMS: {}'.format(self.max_params))\n            # Here we select the parameters that have the lowest 2nd\n            # derivatives.\n\n            # Could fail when simplex finds improvements but restores other\n            # parameters.\n            # if self.ff.params[0].d1:\n\n            if None in [x.d1 for x in self.ff.params]:\n                logger.log(15, '  -- Calculating new parameter derivatives.')\n                # Do central differentiation so we can calculate derivatives.\n                # Another option would be to write code to determine\n                # derivatives only from forward differentiation.\n                ffs = opt.differentiate_ff(self.ff, central=True)\n                # We have to score to get the derivatives.\n                for ff in ffs:\n                    ff.export_ff(path=self.ff.path, lines=self.ff_lines)\n                    logger.log(20, '  -- Calculating {}.'.format(ff))\n                    data = calculate.main(self.args_ff)\n                    #deprecated\n                    #ff.score = compare.compare_data(r_data, data)\n                    r_dict = compare.data_by_type(r_data)\n                    c_dict = compare.data_by_type(data)\n                    r_dict, c_dict = compare.trim_data(r_dict,c_dict)\n                    ff.score = compare.compare_data(r_dict, c_dict)\n                    opt.pretty_ff_results(ff)\n                # Add the derivatives to your original FF.\n                opt.param_derivs(self.ff, ffs)\n                # Only keep the forward differentiated FFs.\n                ffs = opt.extract_forward(ffs)\n                logger.log(5, '  -- Keeping {} forward differentiated '\n                           'FFs.'.format(len(ffs)))\n            else:\n                logger.log(15, '  -- Reusing existing parameter derivatives.')\n                # Differentiate all parameters forward. Yes, I know this is\n                # counter-intuitive because we are going to only use subset of\n                # the forward differentiated FFs. However, this is very\n                # computationally inexpensive because we're not scoring them\n                # now. We will remove the forward differentiated FFs we don't\n                # want before scoring.\n                ffs = opt.differentiate_ff(self.ff, central=False)\n\n            # This sorts the parameters based upon their 2nd derivative.\n            # It keeps the ones with lowest 2nd derivatives.\n\n            # SCHEDULED FOR CHANGES. NOT A GOOD SORTING CRITERION.\n            params = select_simp_params_on_derivs(\n                self.ff.params, max_params=self.max_params)\n            # From the entire list of forward differentiated FFs, pick\n            # out the ones that have the lowest 2nd derivatives.\n            self.new_ffs = opt.extract_ff_by_params(ffs, params)\n            logger.log(1, '>>> len(self.new_ffs): {}'.format(len(self.new_ffs)))\n\n            # Reduce number of parameters.\n            # Will need an option that's not MM3* specific in the future.\n            ff_rows = [x.mm3_row for x in params]\n            ff_cols = [x.mm3_col for x in params]\n            for ff in self.new_ffs:\n                new_params = []\n                for param in ff.params:\n                    if param.mm3_row in ff_rows and param.mm3_col in ff_cols:\n                        new_params.append(param)\n                ff.params = new_params\n            # Make a copy of your original FF that has less parameters.\n            ff_copy = copy.deepcopy(self.ff)\n            new_params = []\n            for param in ff.params:\n                if param.mm3_row in ff_rows and param.mm3_col in ff_cols:\n                    new_params.append(param)\n            ff_copy.params = new_params\n        else:\n            # In this case it's simple. Just forward differentiate each\n            # parameter.\n            self.new_ffs = opt.differentiate_ff(self.ff, central=False)\n            logger.log(1, '>>> len(self.new_ffs): {}'.format(len(self.new_ffs)))\n            # Still make that FF copy.\n            ff_copy = copy.deepcopy(self.ff)\n        # Double check and make sure they're all scored.\n        for ff in self.new_ffs:\n            if ff.score is None:\n                ff.export_ff(path=self.ff.path, lines=self.ff_lines)\n                logger.log(20, '  -- Calculating {}.'.format(ff))\n                data = calculate.main(self.args_ff)\n                #deprecated\n                #ff.score = compare.compare_data(r_data, data)\n                r_dict = compare.data_by_type(r_data)\n                c_dict = compare.data_by_type(data)\n                r_dict, c_dict = compare.trim_data(r_dict,c_dict)\n                ff.score = compare.compare_data(r_dict, c_dict)\n                opt.pretty_ff_results(ff)\n\n        # Add your copy of the orignal to FF to the forward differentiated FFs.\n        self.new_ffs = sorted(self.new_ffs + [ff_copy], key=lambda x: x.score)\n        # Allow 3 cycles w/o change for each parameter present. Remember that\n        # the initial FF was added here, hence the minus one.\n        self._max_cycles_wo_change = 3 * (len(self.new_ffs) - 1)\n        wrapper = textwrap.TextWrapper(width=79)\n        # Shows all FFs parameters.\n        opt.pretty_ff_params(self.new_ffs)\n\n        # Start the simplex cycles.\n        current_cycle = 0\n        cycles_wo_change = 0\n        while current_cycle < self.max_cycles \\\n                and cycles_wo_change < self._max_cycles_wo_change:\n            current_cycle += 1\n\n            # Save the last best in case some accidental sort goes on.\n            # Plus it makes reading the code a litle easier.\n            last_best_ff = copy.deepcopy(self.new_ffs[0])\n            logger.log(20, '~~ START SIMPLEX CYCLE {} ~~'.format(\n                    current_cycle).rjust(79, '~'))\n            logger.log(20, 'ORDERED FF SCORES:')\n            logger.log(20, wrapper.fill('{}'.format(\n                    ' '.join('{:15.4f}'.format(x.score) for x in self.new_ffs))))\n\n            inv_ff = self.ff.__class__()\n            if self.do_weighted_reflection:\n                inv_ff.method = 'WEIGHTED INVERSION'\n            else:\n                inv_ff.method = 'INVERSION'\n            inv_ff.params = copy.deepcopy(last_best_ff.params)\n            ref_ff = self.ff.__class__()\n            ref_ff.method = 'REFLECTION'\n            ref_ff.params = copy.deepcopy(last_best_ff.params)\n            # Need score difference sum for weighted inversion.\n            # Calculate this value before going into loop.\n            if self.do_weighted_reflection:\n                # If zero, should break.\n                score_diff_sum = sum([x.score - self.new_ffs[-1].score\n                                      for x in self.new_ffs[:-1]])\n                if score_diff_sum == 0.:\n                    logger.warning(\n                        'No difference between force field scores. '\n                        'Exiting simplex.')\n                    # We want to raise opt.OptError such that\n                    # opt.catch_run_errors will write the best FF obtained thus\n                    # far.\n                    raise opt.OptError(\n                        'No difference between force field scores. '\n                        'Exiting simplex.')\n            for i in range(0, len(last_best_ff.params)):\n                if self.do_weighted_reflection:\n                    inv_val = (\n                        sum([x.params[i].value *\n                             (x.score - self.new_ffs[-1].score)\n                             for x in self.new_ffs[:-1]])\n                        / score_diff_sum)\n                else:\n                    inv_val = (\n                        sum([x.params[i].value for x in self.new_ffs[:-1]])\n                        /\n                        len(self.new_ffs[:-1]))\n                inv_ff.params[i].value = inv_val\n                ref_ff.params[i].value = (\n                    2 * inv_val - self.new_ffs[-1].params[i].value)\n            # The inversion point does not need to be scored.\n            # Calculate score for reflected parameters.\n            ref_ff.export_ff(path=self.ff.path, lines=self.ff.lines)\n            data = calculate.main(self.args_ff)\n            #deprecated\n            #ref_ff.score = compare.compare_data(r_data, data)\n            r_dict = compare.data_by_type(r_data)\n            c_dict = compare.data_by_type(data)\n            r_dict, c_dict = compare.trim_data(r_dict,c_dict)\n            ref_ff.score = compare.compare_data(r_dict, c_dict)\n            opt.pretty_ff_results(ref_ff)\n            if ref_ff.score < last_best_ff.score:\n                logger.log(20, '~~ ATTEMPTING EXPANSION ~~'.rjust(79, '~'))\n                exp_ff = self.ff.__class__()\n                exp_ff.method = 'EXPANSION'\n                exp_ff.params = copy.deepcopy(last_best_ff.params)\n                for i in range(0, len(last_best_ff.params)):\n                    exp_ff.params[i].value = (\n                        3 * inv_ff.params[i].value -\n                        2 * self.new_ffs[-1].params[i].value)\n                exp_ff.export_ff(path=self.ff.path, lines=self.ff.lines)\n                data = calculate.main(self.args_ff)\n                #deprecated\n                #exp_ff.score = compare.compare_data(r_data, data)\n                r_dict = compare.data_by_type(r_data)\n                c_dict = compare.data_by_type(data)\n                r_dict, c_dict = compare.trim_data(r_dict,c_dict)\n                exp_ff.score = compare.compare_data(r_dict, c_dict)\n                opt.pretty_ff_results(exp_ff)\n                if exp_ff.score < ref_ff.score:\n                    self.new_ffs[-1] = exp_ff\n                    logger.log(\n                        20, '  -- Expansion succeeded. Keeping expanded '\n                        'parameters.')\n                else:\n                    self.new_ffs[-1] = ref_ff\n                    logger.log(\n                        20, '  -- Expansion failed. Keeping reflected parameters.')\n            elif ref_ff.score < self.new_ffs[-2].score:\n                logger.log(20, '  -- Keeping reflected parameters.')\n                self.new_ffs[-1] = ref_ff\n            else:\n                logger.log(20, '~~ ATTEMPTING CONTRACTION ~~'.rjust(79, '~'))\n                con_ff = self.ff.__class__()\n                con_ff.method = 'CONTRACTION'\n                con_ff.params = copy.deepcopy(last_best_ff.params)\n                for i in range(0, len(last_best_ff.params)):\n                    if ref_ff.score > self.new_ffs[-1].score:\n                        con_val = (\n                            (inv_ff.params[i].value +\n                             self.new_ffs[-1].params[i].value) / 2)\n                    else:\n                        con_val = (\n                            (3 * inv_ff.params[i].value -\n                             self.new_ffs[-1].params[i].value) / 2)\n                    con_ff.params[i].value = con_val\n                self.ff.export_ff(params=con_ff.params)\n                data = calculate.main(self.args_ff)\n                #deprecated\n                #con_ff.score = compare.compare_data(r_data, data)\n                r_dict = compare.data_by_type(r_data)\n                c_dict = compare.data_by_type(data)\n                r_dict, c_dict = compare.trim_data(r_dict,c_dict)\n                con_ff.score = compare.compare_data(r_dict, c_dict)\n                opt.pretty_ff_results(con_ff)\n                # This change was made to reflect the 1998 Q2MM publication.\n                # if con_ff.score < self.new_ffs[-1].score:\n                if con_ff.score < self.new_ffs[-2].score:\n                    logger.log(20, '  -- Contraction succeeded.')\n                    self.new_ffs[-1] = con_ff\n                elif self.do_massive_contraction:\n                    logger.log(\n                        20, '~~ DOING MASSIVE CONTRACTION ~~'.rjust(79, '~'))\n                    for ff_num, ff in enumerate(self.new_ffs[1:]):\n                        for i in range(0, len(last_best_ff.params)):\n                            ff.params[i].value = (\n                                (ff.params[i].value +\n                                 self.new_ffs[0].params[i].value) / 2)\n                        self.ff.export_ff(params=ff.params)\n                        data = calculate.main(self.args_ff)\n                        #deprecated\n                        #ff.score = compare.compare_data(r_data, data)\n                        r_dict = compare.data_by_type(r_data)\n                        c_dict = compare.data_by_type(data)\n                        r_dict, c_dict = compare.trim_data(r_dict,c_dict)\n                        ff.score = compare.compare_data(r_dict, c_dict)\n                        ff.method += ' MC'\n                        opt.pretty_ff_results(ff)\n                else:\n                    logger.log(\n                        20, '  -- Contraction failed. Keeping parmaeters '\n                        'anyway.')\n                    self.new_ffs[-1] = con_ff\n            self.new_ffs = sorted(self.new_ffs, key=lambda x: x.score)\n            # Keep track of the number of cycles without change. If there's\n            # improvement, reset the counter.\n            if self.new_ffs[0].score < last_best_ff.score:\n                cycles_wo_change = 0\n            else:\n                cycles_wo_change += 1\n                logger.log(20, '  -- {} cycles without improvement out of {} '\n                           'allowed.'.format(\n                        cycles_wo_change, self._max_cycles_wo_change))\n            logger.log(20, 'BEST:')\n            opt.pretty_ff_results(self.new_ffs[0], level=20)\n            logger.log(20, '~~ END SIMPLEX CYCLE {} ~~'.format(\n                    current_cycle).rjust(79, '~'))\n\n        # This sort is likely unnecessary because it should be done at the end\n        # of the last loop cycle, but I put it here just in case.\n        self.new_ffs = sorted(self.new_ffs, key=lambda x: x.score)\n        best_ff = self.new_ffs[0]\n        if best_ff.score < self.ff.score:\n            logger.log(20, '~~ SIMPLEX FINISHED WITH IMPROVEMENTS ~~'.rjust(\n                    79, '~'))\n            best_ff = restore_simp_ff(best_ff, self.ff)\n        else:\n            logger.log(20, '~~ SIMPLEX FINISHED WITHOUT IMPROVEMENTS ~~'.rjust(\n                    79, '~'))\n            # This restores the inital parameters, so no need to use\n            # restore_simp_ff here.\n            best_ff = self.ff\n        opt.pretty_ff_results(self.ff, level=20)\n        opt.pretty_ff_results(best_ff, level=20)\n        logger.log(20, '  -- Writing best force field from simplex.')\n        best_ff.export_ff(best_ff.path)\n        return best_ff\n\ndef calc_simp_var(params):\n    \"\"\"\n    Simplex variable is calculated: (2nd der.) / (1st der.)**2\n    \"\"\"\n    logger.log(1, '>>> params: {}'.format(params))\n    logger.log(1, '>>> 1st ders.: {}'.format([x.d1 for x in params]))\n    logger.log(1, '>>> 2nd ders.: {}'.format([x.d2 for x in params]))\n    for param in params:\n        param.simp_var = param.d2 / param.d1**2.\n\n# Sorting based upon the 2nd derivative isn't such a good criterion. This should\n# be updated soon.\ndef select_simp_params_on_derivs(params, max_params=10):\n    \"\"\"\n    Sorts parameter sets from lowest to highest second\n    derivatives of their score in the objective function.\n\n    Parameters\n    ----------\n    params : list of subclasses of `datatypes.Param`\n    \"\"\"\n    calc_simp_var(params)\n    keep = sorted(params, key=lambda x: x.simp_var)\n    logger.log(1, '>>> x.simp_var: {}'.format([x.simp_var for x in keep]))\n\n    # Eliminate all where simp_var is greater than 1. This means that the\n    # correct value is bracketed by the differentiation, so gradient\n    # optimization should work.\n    # keep = [x for x in keep if x.simp_var < 1.]\n\n    # Old sorting method.\n    # keep = sorted(params, key=lambda x: x.d2)\n\n    keep = keep[:max_params]\n    logger.log(1, '>>> x.simp_var: {}'.format([x.simp_var for x in keep]))\n    logger.log(20, 'KEEPING PARAMS FOR SIMPLEX:\\n{}'.format(\n            ' '.join([str(x) for x in keep])))\n    return keep\n\ndef restore_simp_ff(new_ff, old_ff):\n    \"\"\"\n    The old FF has properties that we need to copy to the new FF. We also need\n    to grab all the extra parameters included in old FF and add them to the new\n    FF.\n    \"\"\"\n    old_ff.copy_attributes(new_ff)\n    if len(old_ff.params) > len(new_ff.params):\n        logger.log(15, '  -- Restoring {} parameters to new FF.'.format(\n                len(old_ff.params) - len(new_ff.params)))\n\n        logger.log(1, '>>> old_ff.params:')\n        logger.log(1, old_ff.params)\n        logger.log(1, [x.d1 for x in old_ff.params])\n        logger.log(1, [x.d2 for x in old_ff.params])\n        opt.pretty_derivs(old_ff.params, level=1)\n        logger.log(1, '>>> new_ff.params:')\n        logger.log(1, new_ff.params)\n        logger.log(1, [x.d1 for x in new_ff.params])\n        logger.log(1, [x.d2 for x in new_ff.params])\n        opt.pretty_derivs(new_ff.params, level=1)\n\n        # Backup new parameters.\n        new_params = copy.deepcopy(new_ff.params)\n        # Copy over all old parameters.\n        new_ff.params = copy.deepcopy(old_ff.params)\n        # Replace the old with the new.\n        for i, param_o in enumerate(old_ff.params):\n            for param_n in new_params:\n                # Should replace this with a general index scheme.\n                if param_o.mm3_row == param_n.mm3_row and \\\n                        param_o.mm3_col == param_n.mm3_col:\n                    new_ff.params[i] = copy.deepcopy(param_n)\n    return new_ff\n", "meta": {"hexsha": "67c4f38f4a3ab791e1f68bc503238fa42d8613d7", "size": 22084, "ext": "py", "lang": "Python", "max_stars_repo_path": "q2mm/simplex.py", "max_stars_repo_name": "jesswahlers/q2mm", "max_stars_repo_head_hexsha": "71247cd4e7ba644edbe9f55eacd5c88da2e77183", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2015-02-26T20:59:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-11T21:33:32.000Z", "max_issues_repo_path": "q2mm/simplex.py", "max_issues_repo_name": "jesswahlers/q2mm", "max_issues_repo_head_hexsha": "71247cd4e7ba644edbe9f55eacd5c88da2e77183", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44, "max_issues_repo_issues_event_min_datetime": "2016-06-03T07:34:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-13T19:24:00.000Z", "max_forks_repo_path": "q2mm/simplex.py", "max_forks_repo_name": "jesswahlers/q2mm", "max_forks_repo_head_hexsha": "71247cd4e7ba644edbe9f55eacd5c88da2e77183", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2015-03-24T19:52:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-23T18:57:23.000Z", "avg_line_length": 46.2976939203, "max_line_length": 83, "alphanum_fraction": 0.5519833364, "include": true, "reason": "import numpy", "num_tokens": 4750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.19863871932796273}}
{"text": "import os\nimport numpy\nfrom operator import itemgetter\n\nfrom amuse.community import *\nfrom amuse.community.interface.se import StellarEvolution, StellarEvolutionInterface, \\\n    InternalStellarStructure, InternalStellarStructureInterface\n\nfrom amuse.units.quantities import VectorQuantity\nfrom amuse.support.interface import InCodeComponentImplementation\nfrom amuse.support.options import option\n\nclass MESAInterface(CodeInterface, LiteratureReferencesMixIn, StellarEvolutionInterface, \n        InternalStellarStructureInterface, CodeWithDataDirectories): \n    \"\"\"\n    The software project MESA (Modules for Experiments in Stellar Astrophysics, \n    http://mesa.sourceforge.net/), aims to provide state-of-the-art, robust, \n    and efficient open source modules, usable singly or in combination for a \n    wide range of applications in stellar astrophysics. The AMUSE interface to \n    MESA can create and evolve stars using the MESA/STAR module. If you order a \n    metallicity you haven't used before, starting models will be computed \n    automatically and saved in the `mesa/src/data/star_data/starting_models` \n    directory (please be patient...). All metallicities are supported, even the \n    interesting case of Z=0. The supported stellar mass range is from \n    about 0.1 to 100 Msun.\n    \n    References:\n        .. [#] Paxton, Bildsten, Dotter, Herwig, Lesaffre & Timmes 2011, ApJS, arXiv:1009.1622 [2011ApJS..192....3P]\n        .. [#] http://mesa.sourceforge.net/\n    \"\"\"\n    def __init__(self, **options):\n        CodeInterface.__init__(self, name_of_the_worker=\"mesa_worker\", **options)\n        LiteratureReferencesMixIn.__init__(self)\n        CodeWithDataDirectories.__init__(self)\n    \n    @property\n    def default_path_to_inlist(self):\n        return os.path.join(self.get_data_directory(), 'AMUSE_inlist')\n\n    @option(type=\"string\", sections=('data'))\n    def default_path_to_MESA_data(self):\n        return os.path.join(self.amuse_root_directory, 'src', 'amuse', 'community', 'mesa', 'src', 'mesa', 'data')\n    \n    @legacy_function\n    def set_MESA_paths():\n        \"\"\"\n        Set the paths to the MESA inlist and data directories.\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.addParameter('inlist_path', dtype='string', direction=function.IN,\n            description = \"Path to the inlist file.\")\n        function.addParameter('MESA_data_path', dtype='string', direction=function.IN,\n            description = \"Path to the data directory.\")\n        function.addParameter('local_data_path', dtype='string', direction=function.IN,\n            description = \"Path to the data directory.\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            Current value was set\n        -1 - ERROR\n            Directory does not exist\n        \"\"\"\n        return function\n    \n    @legacy_function\n    def get_maximum_number_of_stars():\n        \"\"\"\n        Retrieve the maximum number of stars that can be\n        handled by this instance.\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.addParameter('maximum_number_of_stars', dtype='int32', direction=function.OUT,\n            description = \"The current value of the maximum number of stars\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            Current value of was retrieved\n        \"\"\"\n        return function\n    \n    @legacy_function\n    def new_zams_model():\n        function = LegacyFunctionSpecification()  \n        function.addParameter('status', dtype='int32', direction=function.OUT)\n        return function\n        \n    @legacy_function   \n    def new_pre_ms_particle():\n        \"\"\"\n        Define a new pre-main-sequence star in the code. The star will start with the given mass.\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.can_handle_array = True\n        function.addParameter('index_of_the_star', dtype='int32', direction=function.OUT\n            , description=\"The new index for the star. This index can be used to refer to this star in other functions\")\n        function.addParameter('mass', dtype='float64', direction=function.IN\n            , description=\"The initial mass of the star\")\n        function.result_type = 'int32'\n        return function\n        \n    @legacy_function\n    def set_time_step():\n        function = LegacyFunctionSpecification() \n        function.can_handle_array = True\n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN\n            , description=\"The index of the star to get the value of\")\n        function.addParameter('time_step', dtype='float64', direction=function.IN\n            , description=\"The next timestep for the star.\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            The value has been set.\n        -1 - ERROR\n            A star with the given index was not found.\n        \"\"\"\n        return function\n    \n    \n    @legacy_function   \n    def get_core_mass():\n        \"\"\"\n        Retrieve the current core mass of the star, where hydrogen abundance is <= h1_boundary_limit\n        \"\"\"\n        function = LegacyFunctionSpecification() \n        function.can_handle_array = True \n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN\n            , description=\"The index of the star to get the value of\")\n        function.addParameter('core_mass', dtype='float64', direction=function.OUT\n            , description=\"The current core mass of the star, where hydrogen abundance is <= h1_boundary_limit\")\n        function.result_type = 'int32'\n        return function\n    \n    @legacy_function   \n    def get_mass_loss_rate():\n        \"\"\"\n        Retrieve the current mass loss rate of the star. (positive for winds, negative for accretion)\n        \"\"\"\n        function = LegacyFunctionSpecification() \n        function.can_handle_array = True \n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN\n            , description=\"The index of the star to get the value of\")\n        function.addParameter('mass_loss_rate', dtype='float64', direction=function.OUT\n            , description=\"The current mass loss rate of the star. (positive for winds, negative for accretion)\")\n        function.result_type = 'int32'\n        return function\n    \n    @legacy_function   \n    def get_manual_mass_transfer_rate():\n        \"\"\"\n        Retrieve the current user-specified mass transfer rate of the star. (negative for winds, positive for accretion)\n        \"\"\"\n        function = LegacyFunctionSpecification() \n        function.can_handle_array = True \n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN\n            , description=\"The index of the star to get the value of\")\n        function.addParameter('mass_change', dtype='float64', direction=function.OUT\n            , description=\"The current user-specified mass transfer rate of the star. (negative for winds, positive for accretion)\")\n        function.result_type = 'int32'\n        return function\n    \n    @legacy_function   \n    def set_manual_mass_transfer_rate():\n        \"\"\"\n        Set a new user-specified mass transfer rate of the star. (negative for winds, positive for accretion)\n        \"\"\"\n        function = LegacyFunctionSpecification() \n        function.can_handle_array = True \n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN\n            , description=\"The index of the star to get the value of\")\n        function.addParameter('mass_change', dtype='float64', direction=function.IN\n            , description=\"The new user-specified mass transfer rate of the star. (negative for winds, positive for accretion)\")\n        function.result_type = 'int32'\n        return function\n    \n    @legacy_function\n    def get_accrete_same_as_surface():\n        function = LegacyFunctionSpecification()\n        function.can_handle_array = True\n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN)\n        function.addParameter('accrete_same_as_surface_flag', dtype='int32', direction=function.OUT)\n        function.result_type = 'int32'\n        return function\n    @legacy_function\n    def set_accrete_same_as_surface():\n        function = LegacyFunctionSpecification()\n        function.can_handle_array = True\n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN)\n        function.addParameter('accrete_same_as_surface_flag', dtype='int32', direction=function.IN)\n        function.result_type = 'int32'\n        return function\n    @legacy_function\n    def get_accrete_composition_non_metals():\n        function = LegacyFunctionSpecification()\n        function.can_handle_array = True\n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN)\n        function.addParameter('h1', dtype='float64', direction=function.OUT)\n        function.addParameter('h2', dtype='float64', direction=function.OUT)\n        function.addParameter('he3', dtype='float64', direction=function.OUT)\n        function.addParameter('he4', dtype='float64', direction=function.OUT)\n        function.result_type = 'int32'\n        return function\n    @legacy_function\n    def set_accrete_composition_non_metals():\n        function = LegacyFunctionSpecification()\n        function.can_handle_array = True\n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN)\n        function.addParameter('h1', dtype='float64', direction=function.IN)\n        function.addParameter('h2', dtype='float64', direction=function.IN)\n        function.addParameter('he3', dtype='float64', direction=function.IN)\n        function.addParameter('he4', dtype='float64', direction=function.IN)\n        function.result_type = 'int32'\n        return function\n    @legacy_function\n    def get_accrete_composition_metals_identifier():\n        function = LegacyFunctionSpecification()\n        function.can_handle_array = True\n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN)\n        function.addParameter('accrete_composition_metals_identifier', dtype='int32', direction=function.OUT)\n        function.result_type = 'int32'\n        return function\n    @legacy_function\n    def set_accrete_composition_metals_identifier():\n        function = LegacyFunctionSpecification()\n        function.can_handle_array = True\n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN)\n        function.addParameter('accrete_composition_metals_identifier', dtype='int32', direction=function.IN)\n        function.result_type = 'int32'\n        return function\n    @legacy_function\n    def get_accrete_composition_metals():\n        function = LegacyFunctionSpecification()\n        function.can_handle_array = True\n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN)\n        function.addParameter('li', dtype='float64', direction=function.OUT)\n        function.addParameter('be', dtype='float64', direction=function.OUT)\n        function.addParameter('b', dtype='float64', direction=function.OUT)\n        function.addParameter('c', dtype='float64', direction=function.OUT)\n        function.addParameter('n', dtype='float64', direction=function.OUT)\n        function.addParameter('o', dtype='float64', direction=function.OUT)\n        function.addParameter('f', dtype='float64', direction=function.OUT)\n        function.addParameter('ne', dtype='float64', direction=function.OUT)\n        function.addParameter('na', dtype='float64', direction=function.OUT)\n        function.addParameter('mg', dtype='float64', direction=function.OUT)\n        function.addParameter('al', dtype='float64', direction=function.OUT)\n        function.addParameter('si', dtype='float64', direction=function.OUT)\n        function.addParameter('p', dtype='float64', direction=function.OUT)\n        function.addParameter('s', dtype='float64', direction=function.OUT)\n        function.addParameter('cl', dtype='float64', direction=function.OUT)\n        function.addParameter('ar', dtype='float64', direction=function.OUT)\n        function.addParameter('k', dtype='float64', direction=function.OUT)\n        function.addParameter('ca', dtype='float64', direction=function.OUT)\n        function.addParameter('sc', dtype='float64', direction=function.OUT)\n        function.addParameter('ti', dtype='float64', direction=function.OUT)\n        function.addParameter('v', dtype='float64', direction=function.OUT)\n        function.addParameter('cr', dtype='float64', direction=function.OUT)\n        function.addParameter('mn', dtype='float64', direction=function.OUT)\n        function.addParameter('fe', dtype='float64', direction=function.OUT)\n        function.addParameter('co', dtype='float64', direction=function.OUT)\n        function.addParameter('ni', dtype='float64', direction=function.OUT)\n        function.addParameter('cu', dtype='float64', direction=function.OUT)\n        function.addParameter('zn', dtype='float64', direction=function.OUT)\n        function.result_type = 'int32'\n        return function\n    @legacy_function\n    def set_accrete_composition_metals():\n        function = LegacyFunctionSpecification()\n        function.can_handle_array = True\n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN)\n        function.addParameter('li', dtype='float64', direction=function.IN)\n        function.addParameter('be', dtype='float64', direction=function.IN)\n        function.addParameter('b', dtype='float64', direction=function.IN)\n        function.addParameter('c', dtype='float64', direction=function.IN)\n        function.addParameter('n', dtype='float64', direction=function.IN)\n        function.addParameter('o', dtype='float64', direction=function.IN)\n        function.addParameter('f', dtype='float64', direction=function.IN)\n        function.addParameter('ne', dtype='float64', direction=function.IN)\n        function.addParameter('na', dtype='float64', direction=function.IN)\n        function.addParameter('mg', dtype='float64', direction=function.IN)\n        function.addParameter('al', dtype='float64', direction=function.IN)\n        function.addParameter('si', dtype='float64', direction=function.IN)\n        function.addParameter('p', dtype='float64', direction=function.IN)\n        function.addParameter('s', dtype='float64', direction=function.IN)\n        function.addParameter('cl', dtype='float64', direction=function.IN)\n        function.addParameter('ar', dtype='float64', direction=function.IN)\n        function.addParameter('k', dtype='float64', direction=function.IN)\n        function.addParameter('ca', dtype='float64', direction=function.IN)\n        function.addParameter('sc', dtype='float64', direction=function.IN)\n        function.addParameter('ti', dtype='float64', direction=function.IN)\n        function.addParameter('v', dtype='float64', direction=function.IN)\n        function.addParameter('cr', dtype='float64', direction=function.IN)\n        function.addParameter('mn', dtype='float64', direction=function.IN)\n        function.addParameter('fe', dtype='float64', direction=function.IN)\n        function.addParameter('co', dtype='float64', direction=function.IN)\n        function.addParameter('ni', dtype='float64', direction=function.IN)\n        function.addParameter('cu', dtype='float64', direction=function.IN)\n        function.addParameter('zn', dtype='float64', direction=function.IN)\n        function.result_type = 'int32'\n        return function\n    \n    @legacy_function\n    def get_number_of_backups_in_a_row():\n        \"\"\"\n        Retrieve the number_of_backups_in_a_row of the star.\n        \"\"\"\n        function = LegacyFunctionSpecification() \n        function.can_handle_array = True \n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN\n            , description=\"The index of the star to get the value of number_of_backups_in_a_row\")\n        function.addParameter('n_backup', dtype='int32', direction=function.OUT\n            , description=\"The current number_of_backups_in_a_row of the star.\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            The number_of_backups_in_a_row was retrieved.\n        -1 - ERROR\n            A star with the given index was not found.\n        \"\"\"\n        return function\n    \n    @legacy_function\n    def reset_number_of_backups_in_a_row():\n        \"\"\"\n        Reset number_of_backups_in_a_row of the star.\n        \"\"\"\n        function = LegacyFunctionSpecification() \n        function.can_handle_array = True \n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN\n            , description=\"The index of the star to reset the value of number_of_backups_in_a_row\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            The number_of_backups_in_a_row was reset.\n        -1 - ERROR\n            A star with the given index was not found.\n        \"\"\"\n        return function\n    \n    @legacy_function\n    def get_mass_fraction_at_zone():\n        \"\"\"\n        Retrieve the mass fraction at the specified zone/mesh-cell of the star.\n        \"\"\"\n        function = LegacyFunctionSpecification() \n        function.can_handle_array = True \n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN\n            , description=\"The index of the star to get the value of\")\n        function.addParameter('zone', dtype='int32', direction=function.IN\n            , description=\"The zone/mesh-cell of the star to get the value of\")\n        function.addParameter('dq_i', dtype='float64', direction=function.OUT\n            , description=\"The mass fraction at the specified zone/mesh-cell of the star.\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            The value was retrieved.\n        -1 - ERROR\n            A star with the given index was not found.\n        -2 - ERROR\n            A zone with the given index was not found.\n        \"\"\"\n        return function\n    \n    @legacy_function\n    def set_mass_fraction_at_zone():\n        \"\"\"\n        Set the mass fraction at the specified zone/mesh-cell of the star.\n        \"\"\"\n        function = LegacyFunctionSpecification() \n        function.can_handle_array = True \n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN\n            , description=\"The index of the star to set the value of\")\n        function.addParameter('zone', dtype='int32', direction=function.IN\n            , description=\"The zone/mesh-cell of the star to set the value of\")\n        function.addParameter('dq_i', dtype='float64', direction=function.IN\n            , description=\"The mass fraction at the specified zone/mesh-cell of the star.\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            The value was set.\n        -1 - ERROR\n            A star with the given index was not found.\n        -2 - ERROR\n            A zone with the given index was not found.\n        \"\"\"\n        return function\n    \n    @legacy_function\n    def get_luminosity_at_zone():\n        \"\"\"\n        Retrieve the luminosity at the specified zone/mesh-cell of the star.\n        \"\"\"\n        function = LegacyFunctionSpecification() \n        function.can_handle_array = True \n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN\n            , description=\"The index of the star to get the value of\")\n        function.addParameter('zone', dtype='int32', direction=function.IN\n            , description=\"The zone/mesh-cell of the star to get the value of\")\n        function.addParameter('lum_i', dtype='float64', direction=function.OUT\n            , description=\"The luminosity at the specified zone/mesh-cell of the star.\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            The value was retrieved.\n        -1 - ERROR\n            A star with the given index was not found.\n        -2 - ERROR\n            A zone with the given index was not found.\n        \"\"\"\n        return function\n    \n    @legacy_function\n    def set_luminosity_at_zone():\n        \"\"\"\n        Set the luminosity at the specified zone/mesh-cell of the star.\n        \"\"\"\n        function = LegacyFunctionSpecification() \n        function.can_handle_array = True \n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN\n            , description=\"The index of the star to set the value of\")\n        function.addParameter('zone', dtype='int32', direction=function.IN\n            , description=\"The zone/mesh-cell of the star to set the value of\")\n        function.addParameter('lum_i', dtype='float64', direction=function.IN\n            , description=\"The luminosity at the specified zone/mesh-cell of the star.\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            The value was set.\n        -1 - ERROR\n            A star with the given index was not found.\n        -2 - ERROR\n            A zone with the given index was not found.\n        \"\"\"\n        return function\n    \n    @legacy_function\n    def get_entropy_at_zone():\n        \"\"\"\n        Retrieve the entropy at the specified zone/mesh-cell of the star.\n        \"\"\"\n        function = LegacyFunctionSpecification() \n        function.can_handle_array = True \n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN\n            , description=\"The index of the star to get the value of\")\n        function.addParameter('zone', dtype='int32', direction=function.IN\n            , description=\"The zone/mesh-cell of the star to get the value of\")\n        function.addParameter('S_i', dtype='float64', direction=function.OUT\n            , description=\"The specific entropy at the specified zone/mesh-cell of the star.\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            The value was retrieved.\n        -1 - ERROR\n            A star with the given index was not found.\n        -2 - ERROR\n            A zone with the given index was not found.\n        \"\"\"\n        return function    \n\n    @legacy_function\n    def get_thermal_energy_at_zone():\n        \"\"\"\n        Retrieve the entropy at the specified zone/mesh-cell of the star.\n        \"\"\"\n        function = LegacyFunctionSpecification() \n        function.can_handle_array = True \n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN\n            , description=\"The index of the star to get the value of\")\n        function.addParameter('zone', dtype='int32', direction=function.IN\n            , description=\"The zone/mesh-cell of the star to get the value of\")\n        function.addParameter('E_i', dtype='float64', direction=function.OUT\n            , description=\"The specific thermal energy at the specified zone/mesh-cell of the star.\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            The value was retrieved.\n        -1 - ERROR\n            A star with the given index was not found.\n        -2 - ERROR\n            A zone with the given index was not found.\n        \"\"\"\n        return function    \n    \n    @legacy_function\n    def get_brunt_vaisala_frequency_squared_at_zone():\n        \"\"\"\n        Retrieve the Brunt-Vaisala frequency squared at the specified zone/mesh-cell of the star.\n        \"\"\"\n        function = LegacyFunctionSpecification() \n        function.can_handle_array = True \n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN, unit=INDEX)\n        function.addParameter('zone', dtype='int32', direction=function.IN, unit=NO_UNIT)\n        function.addParameter('brunt_N2', dtype='float64', direction=function.OUT, unit=units.s**-2)\n        function.result_type = 'int32'\n        return function\n    \n    @legacy_function\n    def get_id_of_species():\n        \"\"\"\n        Retrieve the chem_ID of the chemical abundance variable of the star.\n        \"\"\"\n        function = LegacyFunctionSpecification() \n        function.can_handle_array = True \n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN\n            , description=\"The index of the star to get the value of\")\n        function.addParameter('species', dtype='int32', direction=function.IN\n            , description=\"The species of the star to get the name of\")\n        function.addParameter('species_id', dtype='int32', direction=function.OUT\n            , description=\"The chem_ID of the chemical abundance variable of the star.\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            The value was retrieved.\n        -1 - ERROR\n            A star with the given index was not found.\n        \"\"\"\n        return function\n    \n    @legacy_function\n    def get_mass_of_species():\n        \"\"\"\n        Retrieve the mass number of the chemical abundance variable of the star.\n        \"\"\"\n        function = LegacyFunctionSpecification() \n        function.can_handle_array = True \n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN\n            , description=\"The index of the star to get the value of\")\n        function.addParameter('species', dtype='int32', direction=function.IN\n            , description=\"The species of the star to get the mass number of\")\n        function.addParameter('species_mass', dtype='float64', direction=function.OUT\n            , description=\"The mass number of the chemical abundance variable of the star.\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            The value was retrieved.\n        -1 - ERROR\n            A star with the given index was not found.\n        \"\"\"\n        return function\n    \n    @legacy_function\n    def erase_memory():\n        \"\"\"\n        Erase memory of the star, i.e. copy the current structure over the memory of \n        the structure of the previous steps. Useful after setting the stucture of \n        the star, to prevent backup steps to undo changes\n        \"\"\"\n        function = LegacyFunctionSpecification() \n        function.can_handle_array = True\n        function.addParameter('index_of_the_star', dtype='int32', direction=function.IN\n            , description=\"The index of the star to get the value of\")\n        function.result_type = 'int32'\n        return function\n    \n    @legacy_function\n    def get_max_age_stop_condition():\n        \"\"\"\n        Retrieve the current maximum age stop condition of this instance (in years).\n        Evolution will stop once the star has reached this maximum age.\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.addParameter('max_age_stop_condition', dtype='float64', direction=function.OUT\n            , description=\"The current maximum age stop condition of this instance (in years).\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            Current value was retrieved\n        -1 - ERROR\n            The code could not retrieve the value.\n        \"\"\"\n        return function\n    \n    @legacy_function\n    def set_max_age_stop_condition():\n        \"\"\"\n        Set the new maximum age stop condition of this instance (in years).\n        Evolution will stop once the star has reached this maximum age.\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.addParameter('max_age_stop_condition', dtype='float64', direction=function.IN\n            , description=\"The new maximum age stop condition of this instance (in years).\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            The value has been set.\n        -1 - ERROR\n            The code could not set the value.\n        \"\"\"\n        return function\n        \n    @legacy_function\n    def get_min_timestep_stop_condition():\n        \"\"\"\n        Retrieve the current minimum timestep stop condition of this instance (in years).\n        Evolution will stop if the timestep required by the solver in order to converge\n        has decreased below this minimum timestep.\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.addParameter('min_timestep_stop_condition', dtype='float64', direction=function.OUT\n            , description=\"The current minimum timestep stop condition of this instance (in years).\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            Current value was retrieved\n        -1 - ERROR\n            The code could not retrieve the value.\n        \"\"\"\n        return function\n    \n    @legacy_function\n    def set_min_timestep_stop_condition():\n        \"\"\"\n        Set the new minimum timestep stop condition of this instance (in years).\n        Evolution will stop if the timestep required by the solver in order to converge\n        has decreased below this minimum timestep.\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.addParameter('min_timestep_stop_condition', dtype='float64', direction=function.IN\n            , description=\"The new minimum timestep stop condition of this instance (in years).\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            The value has been set.\n        -1 - ERROR\n            The code could not set the value.\n        \"\"\"\n        return function\n        \n    @legacy_function\n    def get_max_iter_stop_condition():\n        \"\"\"\n        Retrieve the current maximum number of iterations of this instance. (Negative means no maximum)\n        Evolution will stop after this number of iterations.\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.addParameter('max_iter_stop_condition', dtype='int32', direction=function.OUT\n            , description=\"The current maximum number of iterations of this instance.\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            Current value was retrieved\n        -1 - ERROR\n            The code could not retrieve the value.\n        \"\"\"\n        return function\n    \n    @legacy_function\n    def set_max_iter_stop_condition():\n        \"\"\"\n        Set the new maximum number of iterations of this instance. (Negative means no maximum)\n        Evolution will stop after this number of iterations.\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.addParameter('max_iter_stop_condition', dtype='int32', direction=function.IN\n            , description=\"The new maximum number of iterations of this instance.\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            The value has been set.\n        -1 - ERROR\n            The code could not set the value.\n        \"\"\"\n        return function\n    \n    @legacy_function\n    def get_convective_overshoot_parameter():\n        function = LegacyFunctionSpecification()  \n        function.addParameter('convective_overshoot_parameter', dtype='float64', direction=function.OUT,\n            description=\"The current value of the convective overshoot parameter.\")\n        function.result_type = 'int32'\n        return function\n    \n    @legacy_function\n    def set_convective_overshoot_parameter():\n        function = LegacyFunctionSpecification()  \n        function.addParameter('convective_overshoot_parameter', dtype='float64', direction=function.IN,\n            description=\"The new value of the convective overshoot parameter.\")\n        function.result_type = 'int32'\n        return function\n    \n    @legacy_function\n    def get_mixing_length_ratio():\n        \"\"\"\n        Retrieve the current value of the mixing length ratio.\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.addParameter('mixing_length_ratio', dtype='float64', direction=function.OUT\n            , description=\"The current value of the mixing length ratio.\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            Current value was retrieved\n        -1 - ERROR\n            The code could not retrieve the value.\n        \"\"\"\n        return function\n    \n    @legacy_function\n    def set_mixing_length_ratio():\n        \"\"\"\n        Set the value of the mixing length ratio.\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.addParameter('mixing_length_ratio', dtype='float64', direction=function.IN\n            , description=\"The new value of the mixing length ratio.\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            The value has been set.\n        -1 - ERROR\n            The code could not set the value.\n        \"\"\"\n        return function\n        \n    @legacy_function\n    def get_semi_convection_efficiency():\n        \"\"\"\n        Retrieve the current value of the efficiency of semi-convection,\n        after Heger, Langer, & Woosley 2000 (ApJ), which goes back to \n        Langer, Sugimoto & Fricke 1983 (A&A).\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.addParameter('semi_convection_efficiency', dtype='float64', direction=function.OUT\n            , description=\"The current value of the efficiency of semi-convection.\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            Current value was retrieved\n        -1 - ERROR\n            The code could not retrieve the value.\n        \"\"\"\n        return function\n    \n    @legacy_function\n    def set_semi_convection_efficiency():\n        \"\"\"\n        Set the value of the efficiency of semi-convection,\n        after Heger, Langer, & Woosley 2000 (ApJ), which goes back to \n        Langer, Sugimoto & Fricke 1983 (A&A).\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.addParameter('semi_convection_efficiency', dtype='float64', direction=function.IN\n            , description=\"The new value of the efficiency of semi-convection.\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            The value has been set.\n        -1 - ERROR\n            The code could not set the value.\n        \"\"\"\n        return function\n    \n    @legacy_function\n    def get_RGB_wind_scheme():\n        \"\"\"\n        Retrieve the current wind (mass loss) scheme for RGB stars:\n        No automatic wind (0)\n        Reimers (1): e.g. see: Baschek, Kegel, Traving (eds), Springer, Berlin, 1975, p. 229.\n        Blocker (2): T. Blocker, A&A 297, 727-738 (1995)\n        de Jager (3): de Jager, C., Nieuwenhuijzen, H., & van der Hucht, K. A. 1988, A&AS, 72, 259\n        Dutch (4): Glebbeek et al 2009, Vink et al 2001, Nugis & Lamers 2000, de Jager 1990\n        Mattsson (5)\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.addParameter('RGB_wind_scheme', dtype='int32', direction=function.OUT\n            , description=\"The current wind (mass loss) scheme for RGB stars of this instance.\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            Current value was retrieved\n        -1 - ERROR\n            The code could not retrieve the value.\n        \"\"\"\n        return function\n    \n    @legacy_function\n    def set_RGB_wind_scheme():\n        \"\"\"\n        Set the new wind (mass loss) scheme for RGB stars:\n        No automatic wind (0)\n        Reimers (1): e.g. see: Baschek, Kegel, Traving (eds), Springer, Berlin, 1975, p. 229.\n        Blocker (2): T. Blocker, A&A 297, 727-738 (1995)\n        de Jager (3): de Jager, C., Nieuwenhuijzen, H., & van der Hucht, K. A. 1988, A&AS, 72, 259\n        Dutch (4): Glebbeek et al 2009, Vink et al 2001, Nugis & Lamers 2000, de Jager 1990\n        Mattsson (5)\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.addParameter('RGB_wind_scheme', dtype='int32', direction=function.IN\n            , description=\"The new wind (mass loss) scheme for RGB stars of this instance.\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            The value has been set.\n        -1 - ERROR\n            The code could not set the value.\n        \"\"\"\n        return function\n    \n    @legacy_function\n    def get_AGB_wind_scheme():\n        \"\"\"\n        Retrieve the current wind (mass loss) scheme for AGB stars:\n        No automatic wind (0)\n        Reimers (1): e.g. see: Baschek, Kegel, Traving (eds), Springer, Berlin, 1975, p. 229.\n        Blocker (2): T. Blocker, A&A 297, 727-738 (1995)\n        de Jager (3): de Jager, C., Nieuwenhuijzen, H., & van der Hucht, K. A. 1988, A&AS, 72, 259\n        Dutch (4): Glebbeek et al 2009, Vink et al 2001, Nugis & Lamers 2000, de Jager 1990\n        Mattsson (5)\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.addParameter('AGB_wind_scheme', dtype='int32', direction=function.OUT\n            , description=\"The current wind (mass loss) scheme for AGB stars of this instance.\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            Current value was retrieved\n        -1 - ERROR\n            The code could not retrieve the value.\n        \"\"\"\n        return function\n    \n    @legacy_function\n    def set_AGB_wind_scheme():\n        \"\"\"\n        Set the new wind (mass loss) scheme for AGB stars:\n        No automatic wind (0)\n        Reimers (1): e.g. see: Baschek, Kegel, Traving (eds), Springer, Berlin, 1975, p. 229.\n        Blocker (2): T. Blocker, A&A 297, 727-738 (1995)\n        de Jager (3): de Jager, C., Nieuwenhuijzen, H., & van der Hucht, K. A. 1988, A&AS, 72, 259\n        Dutch (4): Glebbeek et al 2009, Vink et al 2001, Nugis & Lamers 2000, de Jager 1990\n        Mattsson (5)\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.addParameter('AGB_wind_scheme', dtype='int32', direction=function.IN\n            , description=\"The new wind (mass loss) scheme for AGB stars of this instance.\")\n        function.result_type = 'int32'\n        function.result_doc = \"\"\"\n        0 - OK\n            The value has been set.\n        -1 - ERROR\n            The code could not set the value.\n        \"\"\"\n        return function\n    \n    @legacy_function\n    def get_reimers_wind_efficiency():\n        function = LegacyFunctionSpecification()  \n        function.addParameter('reimers_wind_efficiency', dtype='float64', direction=function.OUT)\n        function.result_type = 'int32'\n        return function\n    \n    @legacy_function\n    def set_reimers_wind_efficiency():\n        function = LegacyFunctionSpecification()  \n        function.addParameter('reimers_wind_efficiency', dtype='float64', direction=function.IN)\n        function.result_type = 'int32'\n        return function\n    \n    @legacy_function\n    def get_blocker_wind_efficiency():\n        function = LegacyFunctionSpecification()  \n        function.addParameter('blocker_wind_efficiency', dtype='float64', direction=function.OUT)\n        function.result_type = 'int32'\n        return function\n    \n    @legacy_function\n    def set_blocker_wind_efficiency():\n        function = LegacyFunctionSpecification()  \n        function.addParameter('blocker_wind_efficiency', dtype='float64', direction=function.IN)\n        function.result_type = 'int32'\n        return function\n    \n    @legacy_function\n    def get_de_jager_wind_efficiency():\n        function = LegacyFunctionSpecification()  \n        function.addParameter('de_jager_wind_efficiency', dtype='float64', direction=function.OUT)\n        function.result_type = 'int32'\n        return function\n    \n    @legacy_function\n    def set_de_jager_wind_efficiency():\n        function = LegacyFunctionSpecification()  \n        function.addParameter('de_jager_wind_efficiency', dtype='float64', direction=function.IN)\n        function.result_type = 'int32'\n        return function\n    \n    @legacy_function\n    def get_dutch_wind_efficiency():\n        function = LegacyFunctionSpecification()  \n        function.addParameter('dutch_wind_efficiency', dtype='float64', direction=function.OUT)\n        function.result_type = 'int32'\n        return function\n    \n    @legacy_function\n    def set_dutch_wind_efficiency():\n        function = LegacyFunctionSpecification()  \n        function.addParameter('dutch_wind_efficiency', dtype='float64', direction=function.IN)\n        function.result_type = 'int32'\n        return function\n    \n    @legacy_function\n    def get_stabilize_new_stellar_model_flag():\n        function = LegacyFunctionSpecification()  \n        function.addParameter('stabilize_new_stellar_model_flag', dtype='int32', direction=function.OUT)\n        function.result_type = 'int32'\n        return function\n    \n    @legacy_function\n    def set_stabilize_new_stellar_model_flag():\n        function = LegacyFunctionSpecification()  \n        function.addParameter('stabilize_new_stellar_model_flag', dtype='int32', direction=function.IN)\n        function.result_type = 'int32'\n        return function\n    \n    @legacy_function   \n    def new_stellar_model():\n        \"\"\"\n        Define a new star model in the code. The star needs to be finalized \n        before it can evolve, see 'finalize_stellar_model'.\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.must_handle_array = True\n        for par in ['d_mass', 'radius', 'rho', 'temperature', 'luminosity', \n                'X_H', 'X_He', 'X_C', 'X_N', 'X_O', 'X_Ne', 'X_Mg', 'X_Si', 'X_Fe']:\n            function.addParameter(par, dtype='float64', direction=function.IN)\n        function.addParameter('n', 'int32', function.LENGTH)\n        function.result_type = 'int32'\n        return function\n    \n    @legacy_function   \n    def finalize_stellar_model():\n        \"\"\"\n        Finalize the new star model defined by 'new_stellar_model'.\n        \"\"\"\n        function = LegacyFunctionSpecification()  \n        function.addParameter('index_of_the_star', dtype='int32', \n            direction=function.OUT, description = \"The new index for the star. \"\n            \"This index can be used to refer to this star in other functions\")\n        function.addParameter('age_tag', dtype='float64', direction=function.IN, \n            description = \"The initial age of the star\")\n        function.result_type = 'int32'\n        return function\n\nclass MESA(StellarEvolution, InternalStellarStructure):\n    \n    def __init__(self, **options):\n        InCodeComponentImplementation.__init__(self, MESAInterface(**options), **options)\n        \n        output_dir = self.get_output_directory()\n        if not self.channel_type == 'distributed':\n            self.ensure_data_directory_exists(os.path.join(output_dir, 'star_data', 'starting_models'))\n        \n        self.set_MESA_paths(\n            self.default_path_to_inlist, \n            self.default_path_to_MESA_data, \n            output_dir\n        )\n        self.model_time = 0.0 | units.yr\n        \n    \n    def define_parameters(self, handler):\n        \n        handler.add_method_parameter(\n            \"get_metallicity\",\n            \"set_metallicity\",\n            \"metallicity\", \n            \"Metallicity of all stars\", \n            default_value = 0.02\n        )\n        \n        handler.add_method_parameter(\n            \"get_max_age_stop_condition\",\n            \"set_max_age_stop_condition\",\n            \"max_age_stop_condition\", \n            \"The maximum age stop condition of this instance.\",\n            default_value = 1.0e36 | units.yr\n        )\n        \n        handler.add_method_parameter(\n            \"get_min_timestep_stop_condition\",\n            \"set_min_timestep_stop_condition\",\n            \"min_timestep_stop_condition\", \n            \"The minimum timestep stop condition of this instance.\",\n            default_value = 1.0e-6 | units.s\n        )\n        \n        handler.add_method_parameter(\n            \"get_max_iter_stop_condition\",\n            \"set_max_iter_stop_condition\",\n            \"max_iter_stop_condition\", \n            \"The maximum number of iterations of this instance. (Negative means no maximum)\",\n            default_value = -1111\n        )\n        \n        handler.add_method_parameter(\n            \"get_convective_overshoot_parameter\",\n            \"set_convective_overshoot_parameter\",\n            \"herwig_convective_overshoot_parameter\", \n            \"The convective overshoot parameter (Herwig 2000), f=0.016 is argued to be a reasonable value.\",\n            default_value = 0.0\n        )\n        \n        handler.add_method_parameter(\n            \"get_mixing_length_ratio\",\n            \"set_mixing_length_ratio\",\n            \"mixing_length_ratio\", \n            \"The mixing-length ratio (alpha).\",\n            default_value = 2.0\n        )\n        \n        handler.add_method_parameter(\n            \"get_semi_convection_efficiency\",\n            \"set_semi_convection_efficiency\",\n            \"semi_convection_efficiency\", \n            \"The efficiency of semi-convection, after Heger, Langer, & Woosley 2000 (ApJ), \"\n               \"which goes back to Langer, Sugimoto & Fricke 1983 (A&A).\",\n            default_value = 0.0\n        )\n        \n        handler.add_method_parameter(\n            \"get_RGB_wind_scheme\",\n            \"set_RGB_wind_scheme\",\n            \"RGB_wind_scheme\", \n            \"The mass loss scheme for RGB stars: none (0), Reimers (1), \"\n                \"Blocker (2), de Jager (3), Dutch (4), Mattsson (5)\",\n            default_value = 1\n        )\n        \n        handler.add_method_parameter(\n            \"get_AGB_wind_scheme\",\n            \"set_AGB_wind_scheme\",\n            \"AGB_wind_scheme\", \n            \"The mass loss scheme for AGB stars: none (0), Reimers (1), \"\n                \"Blocker (2), de Jager (3), Dutch (4), Mattsson (5)\",\n            default_value = 1\n        )\n        \n        handler.add_method_parameter(\n            \"get_reimers_wind_efficiency\",\n            \"set_reimers_wind_efficiency\",\n            \"reimers_wind_efficiency\", \n            \"The Reimers mass loss efficiency. Only used if (RGB/AGB_wind_scheme == 1).\",\n            default_value = 0.5\n        )\n        handler.add_method_parameter(\n            \"get_blocker_wind_efficiency\",\n            \"set_blocker_wind_efficiency\",\n            \"blocker_wind_efficiency\", \n            \"The Blocker mass loss efficiency. Only used if (RGB/AGB_wind_scheme == 2).\",\n            default_value = 0.1\n        )\n        handler.add_method_parameter(\n            \"get_de_jager_wind_efficiency\",\n            \"set_de_jager_wind_efficiency\",\n            \"de_jager_wind_efficiency\", \n            \"The de Jager mass loss efficiency. Only used if (RGB/AGB_wind_scheme == 3).\",\n            default_value = 0.8\n        )\n        handler.add_method_parameter(\n            \"get_dutch_wind_efficiency\",\n            \"set_dutch_wind_efficiency\",\n            \"dutch_wind_efficiency\", \n            \"The Dutch mass loss efficiency. Only used if (RGB/AGB_wind_scheme == 4).\",\n            default_value = 0.8\n        )\n        handler.add_boolean_parameter(\n            \"get_stabilize_new_stellar_model_flag\",\n            \"set_stabilize_new_stellar_model_flag\",\n            \"stabilize_new_stellar_model_flag\",\n            \"Flag specifying whether to stabilize any loaded stellar models first.\",\n            default_value = True\n        )\n        \n        \n        \n    def define_particle_sets(self, handler):\n        handler.define_super_set('particles', ['native_stars', 'imported_stars', 'pre_ms_stars'], \n            index_to_default_set = 0)\n        \n        handler.define_set('imported_stars', 'index_of_the_star')\n        handler.set_new('imported_stars', 'finalize_stellar_model')\n        handler.set_delete('imported_stars', 'delete_star')\n        \n        handler.define_set('native_stars', 'index_of_the_star')\n        handler.set_new('native_stars', 'new_particle')\n        handler.set_delete('native_stars', 'delete_star')\n        \n        handler.define_set('pre_ms_stars', 'index_of_the_star')\n        handler.set_new('pre_ms_stars', 'new_pre_ms_particle')\n        handler.set_delete('pre_ms_stars', 'delete_star')\n        \n        for particle_set_name in ['native_stars', 'imported_stars', 'pre_ms_stars']:\n            handler.add_getter(particle_set_name, 'get_radius', names = ('radius',))\n            handler.add_getter(particle_set_name, 'get_stellar_type', names = ('stellar_type',))\n            handler.add_getter(particle_set_name, 'get_mass', names = ('mass',))\n            handler.add_setter(particle_set_name, 'set_mass', names = ('mass',))\n            handler.add_getter(particle_set_name, 'get_core_mass', names = ('core_mass',))\n            handler.add_getter(particle_set_name, 'get_mass_loss_rate', names = ('wind',))\n            handler.add_getter(particle_set_name, 'get_age', names = ('age',))\n            handler.add_getter(particle_set_name, 'get_time_step', names = ('time_step',))\n            handler.add_setter(particle_set_name, 'set_time_step', names = ('time_step',))\n            handler.add_getter(particle_set_name, 'get_luminosity', names = ('luminosity',))\n            handler.add_getter(particle_set_name, 'get_temperature', names = ('temperature',))\n            \n            handler.add_getter(particle_set_name, 'get_manual_mass_transfer_rate', names = ('mass_change',))\n            handler.add_setter(particle_set_name, 'set_manual_mass_transfer_rate', names = ('mass_change',))\n            \n            handler.add_method(particle_set_name, 'get_accrete_same_as_surface')\n            handler.add_method(particle_set_name, 'set_accrete_same_as_surface')\n            handler.add_method(particle_set_name, 'get_accrete_composition_non_metals')\n            handler.add_method(particle_set_name, 'set_accrete_composition_non_metals')\n            handler.add_method(particle_set_name, 'get_accrete_composition_metals_identifier')\n            handler.add_method(particle_set_name, 'set_accrete_composition_metals_identifier')\n            handler.add_method(particle_set_name, 'get_accrete_composition_metals')\n            handler.add_method(particle_set_name, 'set_accrete_composition_metals')\n            \n            handler.add_method(particle_set_name, 'evolve_one_step')\n            handler.add_method(particle_set_name, 'evolve_for')\n            InternalStellarStructure.define_particle_sets(\n                self, \n                handler, \n                set_name = particle_set_name\n            )\n            handler.add_method(particle_set_name, 'get_mass_profile')\n            handler.add_method(particle_set_name, 'set_mass_profile')\n            handler.add_method(particle_set_name, 'get_cumulative_mass_profile')\n            handler.add_method(particle_set_name, 'get_luminosity_profile')\n            handler.add_method(particle_set_name, 'set_luminosity_profile')\n            handler.add_method(particle_set_name, 'get_entropy_profile')\n            handler.add_method(particle_set_name, 'get_thermal_energy_profile')\n            handler.add_method(particle_set_name, 'get_brunt_vaisala_frequency_squared_profile')\n            handler.add_method(particle_set_name, 'get_IDs_of_species')\n            handler.add_method(particle_set_name, 'get_masses_of_species')\n            handler.add_method(particle_set_name, 'get_number_of_backups_in_a_row')\n            handler.add_method(particle_set_name, 'reset_number_of_backups_in_a_row')\n            \n    def define_state(self, handler):\n        StellarEvolution.define_state(self, handler)\n        handler.add_method('EDIT', 'new_pre_ms_particle')\n        handler.add_method('UPDATE', 'new_pre_ms_particle')\n        handler.add_transition('RUN', 'UPDATE', 'new_pre_ms_particle', False)\n        handler.add_method('EDIT', 'finalize_stellar_model')\n        handler.add_method('UPDATE', 'finalize_stellar_model')\n        handler.add_transition('RUN', 'UPDATE', 'finalize_stellar_model', False)\n    \n    def define_errorcodes(self, handler):\n        InternalStellarStructure.define_errorcodes(self, handler)\n        handler.add_errorcode(-1, 'Something went wrong...')\n        handler.add_errorcode(-4, 'Not implemented.')\n        handler.add_errorcode(-11, 'Evolve terminated: Unspecified stop condition reached.')\n        handler.add_errorcode(-12, 'Evolve terminated: Maximum age reached.')\n        handler.add_errorcode(-13, 'Evolve terminated: Maximum number of iterations reached.')\n        handler.add_errorcode(-14, 'Evolve terminated: Maximum number of backups reached.')\n        handler.add_errorcode(-15, 'Evolve terminated: Minimum timestep limit reached.')\n    \n    def define_methods(self, handler):\n        InternalStellarStructure.define_methods(self, handler)\n        StellarEvolution.define_methods(self, handler)\n        handler.add_method(\n            \"new_pre_ms_particle\",\n            (units.MSun),\n            (handler.INDEX, handler.ERROR_CODE)\n        )\n        handler.add_method(\n            \"set_time_step\", \n            (handler.INDEX, units.yr), \n            (handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            \"get_core_mass\",\n            (handler.INDEX,),\n            (units.MSun, handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            \"get_mass_loss_rate\",\n            (handler.INDEX,),\n            (units.g / units.s, handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            \"get_manual_mass_transfer_rate\",\n            (handler.INDEX,),\n            (units.MSun / units.yr, handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            \"set_manual_mass_transfer_rate\",\n            (handler.INDEX, units.MSun / units.yr),\n            (handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            \"get_number_of_backups_in_a_row\", \n            (handler.INDEX,), \n            (handler.NO_UNIT, handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            \"reset_number_of_backups_in_a_row\", \n            (handler.INDEX,), \n            (handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            \"get_mass_fraction_at_zone\", \n            (handler.INDEX,handler.NO_UNIT,), \n            (handler.NO_UNIT, handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            \"set_mass_fraction_at_zone\", \n            (handler.INDEX, handler.NO_UNIT, handler.NO_UNIT,), \n            (handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            \"get_luminosity_at_zone\", \n            (handler.INDEX,handler.NO_UNIT,), \n            (units.erg/units.s, handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            \"set_luminosity_at_zone\", \n            (handler.INDEX, handler.NO_UNIT, units.erg/units.s,), \n            (handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            \"get_entropy_at_zone\", \n            (handler.INDEX,handler.NO_UNIT,), \n            (units.erg/units.K, handler.ERROR_CODE,)\n        )        \n        handler.add_method(\n            \"get_thermal_energy_at_zone\", \n            (handler.INDEX,handler.NO_UNIT,), \n            (units.erg/units.g, handler.ERROR_CODE,)\n        )        \n        handler.add_method(\n            \"get_id_of_species\", \n            (handler.INDEX,handler.NO_UNIT,), \n            (handler.NO_UNIT, handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            \"get_mass_of_species\", \n            (handler.INDEX,handler.NO_UNIT,), \n            (units.amu, handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            \"erase_memory\", \n            (handler.INDEX,), \n            (handler.ERROR_CODE,),\n            public_name = \"_erase_memory\"\n        )\n        handler.add_method(\n            \"new_stellar_model\", \n            (units.MSun, units.cm, units.g / units.cm**3, units.K, units.erg / units.s, \n                handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, \n                handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT,), \n            (handler.ERROR_CODE,)\n        )\n        handler.add_method(\n            \"finalize_stellar_model\", \n            (units.yr,), \n            (handler.INDEX, handler.ERROR_CODE,)\n        )\n        \n        handler.add_method(\n            \"get_max_age_stop_condition\", \n            (), \n            (units.yr, handler.ERROR_CODE,)\n        )\n        \n    \n        handler.add_method(\n            \"set_max_age_stop_condition\", \n            (units.yr, ), \n            (handler.ERROR_CODE,)\n        )\n        \n    \n        handler.add_method(\n            \"get_min_timestep_stop_condition\", \n            (), \n            (units.s, handler.ERROR_CODE,)\n        )\n        \n    \n        handler.add_method(\n            \"set_min_timestep_stop_condition\", \n            (units.s, ), \n            (handler.ERROR_CODE,)\n        )\n        \n    \n        handler.add_method(\n            \"get_max_iter_stop_condition\", \n            (), \n            (handler.NO_UNIT, handler.ERROR_CODE,)\n        )\n        \n    \n        handler.add_method(\n            \"set_max_iter_stop_condition\", \n            (handler.NO_UNIT, ), \n            (handler.ERROR_CODE,)\n        )\n        \n    \n        handler.add_method(\n            \"get_mixing_length_ratio\", \n            (), \n            (handler.NO_UNIT, handler.ERROR_CODE,)\n        )\n        \n    \n        handler.add_method(\n            \"set_mixing_length_ratio\", \n            (handler.NO_UNIT, ), \n            (handler.ERROR_CODE,)\n        )\n        \n    \n        handler.add_method(\n            \"get_semi_convection_efficiency\", \n            (), \n            (handler.NO_UNIT, handler.ERROR_CODE,)\n        )\n        \n    \n        handler.add_method(\n            \"set_semi_convection_efficiency\", \n            (handler.NO_UNIT, ), \n            (handler.ERROR_CODE,)\n        )\n        \n    \n        handler.add_method(\n            \"get_RGB_wind_scheme\", \n            (), \n            (handler.NO_UNIT, handler.ERROR_CODE,)\n        )\n        \n    \n        handler.add_method(\n            \"set_RGB_wind_scheme\", \n            (handler.NO_UNIT, ), \n            (handler.ERROR_CODE,)\n        )\n        \n    \n        handler.add_method(\n            \"get_AGB_wind_scheme\", \n            (), \n            (handler.NO_UNIT, handler.ERROR_CODE,)\n        )\n        \n    \n        handler.add_method(\n            \"set_AGB_wind_scheme\", \n            (handler.NO_UNIT, ), \n            (handler.ERROR_CODE,)\n        )\n        \n    \n        handler.add_method(\n            \"get_reimers_wind_efficiency\", \n            (), \n            (handler.NO_UNIT, handler.ERROR_CODE,)\n        )\n        \n    \n        handler.add_method(\n            \"set_reimers_wind_efficiency\", \n            (handler.NO_UNIT, ), \n            (handler.ERROR_CODE,)\n        )\n        \n    \n        handler.add_method(\n            \"get_blocker_wind_efficiency\", \n            (), \n            (handler.NO_UNIT, handler.ERROR_CODE,)\n        )\n        \n    \n        handler.add_method(\n            \"set_blocker_wind_efficiency\", \n            (handler.NO_UNIT, ), \n            (handler.ERROR_CODE,)\n        )\n        \n    \n        handler.add_method(\n            \"get_de_jager_wind_efficiency\", \n            (), \n            (handler.NO_UNIT, handler.ERROR_CODE,)\n        )\n        \n    \n        handler.add_method(\n            \"set_de_jager_wind_efficiency\", \n            (handler.NO_UNIT, ), \n            (handler.ERROR_CODE,)\n        )\n        \n    \n        handler.add_method(\n            \"get_dutch_wind_efficiency\", \n            (), \n            (handler.NO_UNIT, handler.ERROR_CODE,)\n        )\n        \n    \n        handler.add_method(\n            \"set_dutch_wind_efficiency\", \n            (handler.NO_UNIT, ), \n            (handler.ERROR_CODE,)\n        )\n        \n    \n    def initialize_module_with_default_parameters(self):\n        self.parameters.set_defaults()\n        self.initialize_code()\n        \n    def initialize_module_with_current_parameters(self):\n        self.initialize_code()\n    \n    def commit_parameters(self):\n        self.parameters.send_not_set_parameters_to_code()\n        self.parameters.send_cached_parameters_to_code()\n        self.overridden().commit_parameters()\n        \n    def get_mass_profile(self, indices_of_the_stars, number_of_zones = None):\n        indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string = \"Querying mass profiles\")\n        if number_of_zones is None:\n            number_of_zones = self.get_number_of_zones(indices_of_the_stars)\n        return self.get_mass_fraction_at_zone([indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none)\n    \n    def get_cumulative_mass_profile(self, indices_of_the_stars, number_of_zones = None):\n        frac_profile = self.get_mass_profile(indices_of_the_stars, number_of_zones = number_of_zones)\n        return frac_profile.cumsum()\n    \n    def set_mass_profile(self, indices_of_the_stars, values, number_of_zones = None):\n        indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string = \"Setting mass profiles\")\n        if number_of_zones is None:\n            number_of_zones = self.get_number_of_zones(indices_of_the_stars)\n        self._check_supplied_values(len(values), number_of_zones)\n        self.set_mass_fraction_at_zone([indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none, values)\n        if hasattr(self, \"_erase_memory\"):\n            self._erase_memory(indices_of_the_stars)\n    \n    def get_luminosity_profile(self, indices_of_the_stars, number_of_zones = None):\n        indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string = \"Querying luminosity profiles\")\n        if number_of_zones is None:\n            number_of_zones = self.get_number_of_zones(indices_of_the_stars)\n        return self.get_luminosity_at_zone([indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none)\n    \n    def set_luminosity_profile(self, indices_of_the_stars, values, number_of_zones = None):\n        indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string = \"Setting luminosity profiles\")\n        if number_of_zones is None:\n            number_of_zones = self.get_number_of_zones(indices_of_the_stars)\n        self._check_supplied_values(len(values), number_of_zones)\n        self.set_luminosity_at_zone([indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none, values)\n        if hasattr(self, \"_erase_memory\"):\n            self._erase_memory(indices_of_the_stars)\n\n    def get_entropy_profile(self, indices_of_the_stars, number_of_zones = None):\n        indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string = \"Querying entropy profiles\")\n        if number_of_zones is None:\n            number_of_zones = self.get_number_of_zones(indices_of_the_stars)\n        return self.get_entropy_at_zone([indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none)\n    \n    def get_thermal_energy_profile(self, indices_of_the_stars, number_of_zones = None):\n        indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string = \"Querying thermal energy profiles\")\n        if number_of_zones is None:\n            number_of_zones = self.get_number_of_zones(indices_of_the_stars)\n        return self.get_thermal_energy_at_zone([indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none)\n\n    def get_brunt_vaisala_frequency_squared_profile(self, indices_of_the_stars, number_of_zones = None):\n        indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string = \"Querying brunt-vaisala-frequency-squared profiles\") \n        if number_of_zones is None:\n            number_of_zones = self.get_number_of_zones(indices_of_the_stars)\n        return self.get_brunt_vaisala_frequency_squared_at_zone([indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none)\n    \n    def get_IDs_of_species(self, indices_of_the_stars, number_of_species = None):\n        indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string = \"Querying chemical abundance IDs\")\n        if number_of_species is None:\n            number_of_species = self.get_number_of_species(indices_of_the_stars)\n        return list(self.get_id_of_species(\n            [indices_of_the_stars]*number_of_species, \n            list(range(1,number_of_species+1)) \n        ))\n    \n    def get_masses_of_species(self, indices_of_the_stars, number_of_species = None):\n        indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string = \"Querying chemical abundance mass numbers\")\n        if number_of_species is None:\n            number_of_species = self.get_number_of_species(indices_of_the_stars)\n        return self.get_mass_of_species(\n            [indices_of_the_stars]*number_of_species, \n            list(range(1,number_of_species+1))\n        )\n    \n    def new_particle_from_model(self, internal_structure, current_age=0|units.Myr, key=None):\n        if isinstance(internal_structure, dict):\n            if \"dmass\" in internal_structure:\n                mass_profile = internal_structure['dmass'][::-1]\n            else:\n                cumulative_mass_profile = [0.0] | units.MSun\n                cumulative_mass_profile.extend(internal_structure['mass'])\n                mass_profile = (cumulative_mass_profile[1:] - cumulative_mass_profile[:-1])[::-1]\n            self.new_stellar_model(\n                mass_profile,\n                internal_structure['radius'][::-1],\n                internal_structure['rho'][::-1],\n                internal_structure['temperature'][::-1],\n                internal_structure['luminosity'][::-1],\n                internal_structure['X_H'][::-1],\n                internal_structure['X_He'][::-1],\n                internal_structure['X_C'][::-1],\n                internal_structure['X_N'][::-1],\n                internal_structure['X_O'][::-1],\n                internal_structure['X_Ne'][::-1],\n                internal_structure['X_Mg'][::-1],\n                internal_structure['X_Si'][::-1],\n                internal_structure['X_Fe'][::-1]\n            )\n        else:\n            if hasattr(internal_structure, \"dmass\"):\n                mass_profile = internal_structure.dmass[::-1]\n            else:\n                cumulative_mass_profile = [0.0] | units.MSun\n                cumulative_mass_profile.extend(internal_structure.mass)\n                mass_profile = (cumulative_mass_profile[1:] - cumulative_mass_profile[:-1])[::-1]\n            self.new_stellar_model(\n                mass_profile,\n                internal_structure.radius[::-1],\n                internal_structure.rho[::-1],\n                internal_structure.temperature[::-1],\n                internal_structure.luminosity[::-1],\n                internal_structure.X_H[::-1],\n                internal_structure.X_He[::-1],\n                internal_structure.X_C[::-1],\n                internal_structure.X_N[::-1],\n                internal_structure.X_O[::-1],\n                internal_structure.X_Ne[::-1],\n                internal_structure.X_Mg[::-1],\n                internal_structure.X_Si[::-1],\n                internal_structure.X_Fe[::-1]\n            )\n        tmp_star = datamodel.Particle(key=key)\n        tmp_star.age_tag = current_age\n        return self.imported_stars.add_particle(tmp_star)\n\n\n\nMesa = MESA\n", "meta": {"hexsha": "f7fb8f7c89b788e21fd08b45e00aa759617eaa13", "size": 67639, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/amuse/community/mesa/interface.py", "max_stars_repo_name": "rknop/amuse", "max_stars_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 131, "max_stars_repo_stars_event_min_datetime": "2015-06-04T09:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T12:11:29.000Z", "max_issues_repo_path": "src/amuse/community/mesa/interface.py", "max_issues_repo_name": "rknop/amuse", "max_issues_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 690, "max_issues_repo_issues_event_min_datetime": "2015-10-17T12:18:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:15:58.000Z", "max_forks_repo_path": "src/amuse/community/mesa/interface.py", "max_forks_repo_name": "rieder/amuse", "max_forks_repo_head_hexsha": "3ac3b6b8f922643657279ddee5c8ab3fc0440d5e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 102, "max_forks_repo_forks_event_min_datetime": "2015-01-22T10:00:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:29:43.000Z", "avg_line_length": 43.7509702458, "max_line_length": 152, "alphanum_fraction": 0.6351217493, "include": true, "reason": "import numpy", "num_tokens": 14421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.1986063489461212}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nSignal processing functions for RtMemory objects.\n\nFor sequential packet processing that requires memory (which includes recursive\nfiltering), each processing function (e.g., :mod:`obspy.realtime.signal`)\nneeds to manage the initialization and update of\n:class:`~obspy.realtime.rtmemory.RtMemory` object(s), and needs to know when\nand how to get values from this memory.\n\nFor example: Boxcar smoothing: For each new data point available past the end\nof the boxcar, the original, un-smoothed data point value at the beginning of\nthe boxcar has to be subtracted from the running boxcar sum, this value may be\nin a previous packet, so has to be retrieved from memory see\n:func:`obspy.realtime.signal.boxcar`.\n\n:copyright:\n    The ObsPy Development Team (devs@obspy.org), Anthony Lomax & Alessia Maggi\n:license:\n    GNU Lesser General Public License, Version 3\n    (https://www.gnu.org/copyleft/lesser.html)\n\"\"\"\nfrom __future__ import (absolute_import, division, print_function,\n                        unicode_literals)\nfrom future.builtins import *  # NOQA\n\nimport math\nimport sys\n\nimport numpy as np\n\nfrom obspy.core.trace import Trace, UTCDateTime\nfrom obspy.realtime.rtmemory import RtMemory\n\n\n_PI = math.pi\n_TWO_PI = 2.0 * math.pi\n_MIN_FLOAT_VAL = 1.0e-20\n\n\ndef offset(trace, offset=0.0, rtmemory_list=None):  # @UnusedVariable\n    \"\"\"\n    Add the specified offset to the data.\n\n    :type trace: :class:`~obspy.core.trace.Trace`\n    :param trace: :class:`~obspy.core.trace.Trace` object to append to this\n        RtTrace\n    :type offset: float, optional\n    :param offset: offset (default is 0.0)\n    :type rtmemory_list: list of :class:`~obspy.realtime.rtmemory.RtMemory`,\n        optional\n    :param rtmemory_list: Persistent memory used by this process for specified\n        trace\n    :rtype: NumPy :class:`numpy.ndarray`\n    :return: Processed trace data from appended Trace object\n    \"\"\"\n\n    if not isinstance(trace, Trace):\n        msg = \"Trace parameter must be an obspy.core.trace.Trace object.\"\n        raise ValueError(msg)\n\n    trace.data += offset\n    return trace.data\n\n\ndef scale(trace, factor=1.0, rtmemory_list=None):  # @UnusedVariable\n    \"\"\"\n    Scale array data samples by specified factor.\n\n    :type trace: :class:`~obspy.core.trace.Trace`\n    :param trace:  :class:`~obspy.core.trace.Trace` object to append to this\n        RtTrace\n    :type factor: float, optional\n    :param factor: Scale factor (default is 1.0).\n    :type rtmemory_list: list of :class:`~obspy.realtime.rtmemory.RtMemory`,\n        optional\n    :param rtmemory_list: Persistent memory used by this process for specified\n        trace.\n    :rtype: NumPy :class:`numpy.ndarray`\n    :return: Processed trace data from appended Trace object.\n    \"\"\"\n    if not isinstance(trace, Trace):\n        msg = \"trace parameter must be an obspy.core.trace.Trace object.\"\n        raise ValueError(msg)\n    # XXX not sure how this should be for realtime analysis, here\n    # I assume, we do not want to change the underlying dtype\n    trace.data *= np.array(factor, dtype=trace.data.dtype)\n    return trace.data\n\n\ndef integrate(trace, rtmemory_list=None):\n    \"\"\"\n    Apply simple rectangular integration to array data.\n\n    :type trace: :class:`~obspy.core.trace.Trace`\n    :param trace:  :class:`~obspy.core.trace.Trace` object to append to this\n        RtTrace\n    :type rtmemory_list: list of :class:`~obspy.realtime.rtmemory.RtMemory`,\n        optional\n    :param rtmemory_list: Persistent memory used by this process for specified\n        trace.\n    :rtype: NumPy :class:`numpy.ndarray`\n    :return: Processed trace data from appended Trace object.\n    \"\"\"\n    if not isinstance(trace, Trace):\n        msg = \"trace parameter must be an obspy.core.trace.Trace object.\"\n        raise ValueError(msg)\n\n    if not rtmemory_list:\n        rtmemory_list = [RtMemory()]\n\n    sample = trace.data\n    if np.size(sample) < 1:\n        return sample\n\n    delta_time = trace.stats.delta\n\n    rtmemory = rtmemory_list[0]\n\n    # initialize memory object\n    if not rtmemory.initialized:\n        memory_size_input = 0\n        memory_size_output = 1\n        rtmemory.initialize(sample.dtype, memory_size_input,\n                            memory_size_output, 0, 0)\n\n    sum_ = rtmemory.output[0]\n\n    for i in range(np.size(sample)):\n        sum_ += sample[i] * delta_time\n        sample[i] = sum_\n\n    rtmemory.output[0] = sum_\n\n    return sample\n\n\ndef differentiate(trace, rtmemory_list=None):\n    \"\"\"\n    Apply simple differentiation to array data.\n\n    :type trace: :class:`~obspy.core.trace.Trace`\n    :param trace:  :class:`~obspy.core.trace.Trace` object to append to this\n        RtTrace\n    :type rtmemory_list: list of :class:`~obspy.realtime.rtmemory.RtMemory`,\n        optional\n    :param rtmemory_list: Persistent memory used by this process for specified\n        trace.\n    :rtype: NumPy :class:`numpy.ndarray`\n    :return: Processed trace data from appended Trace object.\n    \"\"\"\n    if not isinstance(trace, Trace):\n        msg = \"trace parameter must be an obspy.core.trace.Trace object.\"\n        raise ValueError(msg)\n\n    if not rtmemory_list:\n        rtmemory_list = [RtMemory()]\n\n    sample = trace.data\n    if np.size(sample) < 1:\n        return(sample)\n\n    delta_time = trace.stats.delta\n\n    rtmemory = rtmemory_list[0]\n\n    # initialize memory object\n    if not rtmemory.initialized:\n        memory_size_input = 1\n        memory_size_output = 0\n        rtmemory.initialize(sample.dtype, memory_size_input,\n                            memory_size_output, 0, 0)\n        # avoid large diff value for first output sample\n        rtmemory.input[0] = sample[0]\n\n    previous_sample = rtmemory.input[0]\n\n    for i in range(np.size(sample)):\n        diff = (sample[i] - previous_sample) / delta_time\n        previous_sample = sample[i]\n        sample[i] = diff\n\n    rtmemory.input[0] = previous_sample\n\n    return sample\n\n\ndef boxcar(trace, width, rtmemory_list=None):\n    \"\"\"\n    Apply boxcar smoothing to data in array sample.\n\n    :type trace: :class:`~obspy.core.trace.Trace`\n    :param trace:  :class:`~obspy.core.trace.Trace` object to append to this\n        RtTrace\n    :type width: int\n    :param width: Width in number of sample points for filter.\n    :type rtmemory_list: list of :class:`~obspy.realtime.rtmemory.RtMemory`,\n        optional\n    :param rtmemory_list: Persistent memory used by this process for specified\n        trace.\n    :rtype: NumPy :class:`numpy.ndarray`\n    :return: Processed trace data from appended Trace object.\n    \"\"\"\n    if not isinstance(trace, Trace):\n        msg = \"trace parameter must be an obspy.core.trace.Trace object.\"\n        raise ValueError(msg)\n\n    if not width > 0:\n        msg = \"width parameter not specified or < 1.\"\n        raise ValueError(msg)\n\n    if not rtmemory_list:\n        rtmemory_list = [RtMemory()]\n\n    sample = trace.data\n\n    rtmemory = rtmemory_list[0]\n\n    # initialize memory object\n    if not rtmemory.initialized:\n        memory_size_input = width\n        memory_size_output = 0\n        rtmemory.initialize(sample.dtype, memory_size_input,\n                            memory_size_output, 0, 0)\n\n    # initialize array for time-series results\n    new_sample = np.zeros(np.size(sample), sample.dtype)\n\n    i = 0\n    i1 = i - width\n    i2 = i  # causal boxcar of width width\n    sum_ = 0.0\n    icount = 0\n    for i in range(np.size(sample)):\n        value = 0.0\n        if (icount == 0):  # first pass, accumulate sum\n            for n in range(i1, i2 + 1):\n                if (n < 0):\n                    value = rtmemory.input[width + n]\n                else:\n                    value = sample[n]\n                sum_ += value\n                icount = icount + 1\n        else:  # later passes, update sum\n            if ((i1 - 1) < 0):\n                value = rtmemory.input[width + (i1 - 1)]\n            else:\n                value = sample[(i1 - 1)]\n            sum_ -= value\n            if (i2 < 0):\n                value = rtmemory.input[width + i2]\n            else:\n                value = sample[i2]\n            sum_ += value\n        if (icount > 0):\n            new_sample[i] = (float)(sum_ / float(icount))\n        else:\n            new_sample[i] = 0.0\n        i1 = i1 + 1\n        i2 = i2 + 1\n\n    rtmemory.update_input(sample)\n\n    return new_sample\n\n\ndef tauc(trace, width, rtmemory_list=None):\n    \"\"\"\n    Calculate instantaneous period in a fixed window (Tau_c).\n\n    .. seealso::\n\n        Implements equations 1-3 in [Allen2003]_ except use a fixed width\n        window instead of decay function.\n\n    :type trace: :class:`~obspy.core.trace.Trace`\n    :param trace:  :class:`~obspy.core.trace.Trace` object to append to this\n        RtTrace\n    :type width: int\n    :param width: Width in number of sample points for tauc window.\n    :type rtmemory_list: list of :class:`~obspy.realtime.rtmemory.RtMemory`,\n        optional\n    :param rtmemory_list: Persistent memory used by this process for specified\n        trace.\n    :rtype: NumPy :class:`numpy.ndarray`\n    :return: Processed trace data from appended Trace object.\n    \"\"\"\n    if not isinstance(trace, Trace):\n        msg = \"trace parameter must be an obspy.core.trace.Trace object.\"\n        raise ValueError(msg)\n\n    if not width > 0:\n        msg = \"tauc: width parameter not specified or < 1.\"\n        raise ValueError(msg)\n\n    if not rtmemory_list:\n        rtmemory_list = [RtMemory(), RtMemory()]\n\n    sample = trace.data\n    delta_time = trace.stats.delta\n\n    rtmemory = rtmemory_list[0]\n    rtmemory_dval = rtmemory_list[1]\n\n    sample_last = 0.0\n\n    # initialize memory object\n    if not rtmemory.initialized:\n        memory_size_input = width\n        memory_size_output = 1\n        rtmemory.initialize(sample.dtype, memory_size_input,\n                            memory_size_output, 0, 0)\n        sample_last = sample[0]\n    else:\n        sample_last = rtmemory.input[width - 1]\n\n    # initialize memory object\n    if not rtmemory_dval.initialized:\n        memory_size_input = width\n        memory_size_output = 1\n        rtmemory_dval.initialize(sample.dtype, memory_size_input,\n                                 memory_size_output, 0, 0)\n\n    new_sample = np.zeros(np.size(sample), sample.dtype)\n    deriv = np.zeros(np.size(sample), sample.dtype)\n\n    # sample_last = rtmemory.input[width - 1]\n    sample_d = 0.0\n    deriv_d = 0.0\n    xval = rtmemory.output[0]\n    dval = rtmemory_dval.output[0]\n\n    for i in range(np.size(sample)):\n\n        sample_d = sample[i]\n        deriv_d = (sample_d - sample_last) / delta_time\n        index_begin = i - width\n        if (index_begin >= 0):\n            xval = xval - (sample[index_begin]) * (sample[index_begin]) \\\n                + sample_d * sample_d\n            dval = dval - deriv[index_begin] * deriv[index_begin] \\\n                + deriv_d * deriv_d\n        else:\n            index = i\n            xval = xval - rtmemory.input[index] * rtmemory.input[index] \\\n                + sample_d * sample_d\n            dval = dval \\\n                - rtmemory_dval.input[index] * rtmemory_dval.input[index] \\\n                + deriv_d * deriv_d\n        deriv[i] = deriv_d\n        sample_last = sample_d\n        # if (xval > _MIN_FLOAT_VAL &  & dval > _MIN_FLOAT_VAL) {\n        if (dval > _MIN_FLOAT_VAL):\n            new_sample[i] = _TWO_PI * math.sqrt(xval / dval)\n        else:\n            new_sample[i] = 0.0\n\n    # update memory\n    rtmemory.output[0] = xval\n    rtmemory.update_input(sample)\n    rtmemory_dval.output[0] = dval\n    rtmemory_dval.update_input(deriv)\n\n    return new_sample\n\n\n# memory object indices for storing specific values\n_AMP_AT_PICK = 0\n_HAVE_USED_MEMORY = 1\n_FLAG_COMPETE_MWP = 2\n_INT_INT_SUM = 3\n_POLARITY = 4\n_MEMORY_SIZE_OUTPUT = 5\n\n\ndef mwpintegral(trace, max_time, ref_time, mem_time=1.0, gain=1.0,\n                rtmemory_list=None):\n    \"\"\"\n    Calculate Mwp integral on a displacement trace.\n\n    .. seealso:: [Tsuboi1999]_ and [Tsuboi1995]_\n\n    :type trace: :class:`~obspy.core.trace.Trace`\n    :param trace:  :class:`~obspy.core.trace.Trace` object to append to this\n        RtTrace\n    :type max_time: float\n    :param max_time: Maximum time in seconds after ref_time to apply Mwp\n        integration.\n    :type ref_time: :class:`~obspy.core.utcdatetime.UTCDateTime`\n    :param ref_time: Reference date and time of the data sample\n        (e.g. P pick time) at which to begin Mwp integration.\n    :type mem_time: float, optional\n    :param mem_time: Length in seconds of data memory (must be much larger\n        than maximum delay between pick declaration and pick time). Defaults\n        to ``1.0``.\n    :type gain: float, optional\n    :param gain: Nominal gain to convert input displacement trace to meters\n        of ground displacement. Defaults to ``1.0``.\n    :type rtmemory_list: list of :class:`~obspy.realtime.rtmemory.RtMemory`,\n        optional\n    :param rtmemory_list: Persistent memory used by this process for specified\n        trace.\n    :rtype: NumPy :class:`numpy.ndarray`\n    :return: Processed trace data from appended Trace object.\n    \"\"\"\n    if not isinstance(trace, Trace):\n        msg = \"trace parameter must be an obspy.core.trace.Trace object.\"\n        raise ValueError(msg)\n\n    if not isinstance(ref_time, UTCDateTime):\n        msg = \"ref_time must be an obspy.core.utcdatetime.UTCDateTime object.\"\n        raise ValueError(msg)\n\n    if not max_time >= 0:\n        msg = \"max_time parameter not specified or < 0.\"\n        raise ValueError(msg)\n\n    if not rtmemory_list:\n        rtmemory_list = [RtMemory()]\n\n    sample = trace.data\n    delta_time = trace.stats.delta\n\n    rtmemory = rtmemory_list[0]\n\n    # initialize memory object\n    if not rtmemory.initialized:\n        memory_size_input = int(0.5 + mem_time * trace.stats.sampling_rate)\n        memory_size_output = _MEMORY_SIZE_OUTPUT\n        rtmemory.initialize(sample.dtype, memory_size_input,\n                            memory_size_output, 0, 0)\n\n    new_sample = np.zeros(np.size(sample), sample.dtype)\n\n    ioffset_pick = int(round(\n                       (ref_time - trace.stats.starttime) *\n                       trace.stats.sampling_rate))\n    ioffset_mwp_min = ioffset_pick\n\n    # set reference amplitude\n    if ioffset_mwp_min >= 0 and ioffset_mwp_min < trace.data.size:\n        # value in trace data array\n        rtmemory.output[_AMP_AT_PICK] = trace.data[ioffset_mwp_min]\n    elif ioffset_mwp_min >= -(np.size(rtmemory.input)) and ioffset_mwp_min < 0:\n        # value in memory array\n        index = ioffset_mwp_min + np.size(rtmemory.input)\n        rtmemory.output[_AMP_AT_PICK] = rtmemory.input[index]\n    elif ioffset_mwp_min < -(np.size(rtmemory.input)) \\\n            and not rtmemory.output[_HAVE_USED_MEMORY]:\n        msg = \"mem_time not large enough to buffer required input data.\"\n        raise ValueError(msg)\n    if ioffset_mwp_min < 0 and rtmemory.output[_HAVE_USED_MEMORY]:\n        ioffset_mwp_min = 0\n    else:\n        rtmemory.output[_HAVE_USED_MEMORY] = 1\n    # set Mwp end index corresponding to maximum duration\n    mwp_end_index = int(round(max_time / delta_time))\n    ioffset_mwp_max = mwp_end_index + ioffset_pick\n    if ioffset_mwp_max < trace.data.size:\n        rtmemory.output[_FLAG_COMPETE_MWP] = 1  # will complete\n    if ioffset_mwp_max > trace.data.size:\n        ioffset_mwp_max = trace.data.size\n    # apply double integration, check for extrema\n    mwp_amp_at_pick = rtmemory.output[_AMP_AT_PICK]\n    mwp_int_int_sum = rtmemory.output[_INT_INT_SUM]\n    polarity = rtmemory.output[_POLARITY]\n    amplitude = 0.0\n    for n in range(ioffset_mwp_min, ioffset_mwp_max):\n        if n >= 0:\n            amplitude = trace.data[n]\n        elif n >= -(np.size(rtmemory.input)):\n            # value in memory array\n            index = n + np.size(rtmemory.input)\n            amplitude = rtmemory.input[index]\n        else:\n            msg = \"Error: Mwp: attempt to access rtmemory.input array of \" + \\\n                \"size=%d at invalid index=%d: this should not happen!\" % \\\n                (np.size(rtmemory.input), n + np.size(rtmemory.input))\n            print(msg)\n            continue  # should never reach here\n        disp_amp = amplitude - mwp_amp_at_pick\n        # check displacement polarity\n        if disp_amp >= 0.0:  # pos\n            # check if past extremum\n            if polarity < 0:  # passed from neg to pos displacement\n                mwp_int_int_sum *= -1.0\n                mwp_int_int_sum = 0\n            polarity = 1\n        elif disp_amp < 0.0:  # neg\n            # check if past extremum\n            if polarity > 0:  # passed from pos to neg displacement\n                mwp_int_int_sum = 0\n            polarity = -1\n        mwp_int_int_sum += (amplitude - mwp_amp_at_pick) * delta_time / gain\n        new_sample[n] = mwp_int_int_sum\n\n    rtmemory.output[_INT_INT_SUM] = mwp_int_int_sum\n    rtmemory.output[_POLARITY] = polarity\n\n    # update memory\n    rtmemory.update_input(sample)\n\n    return new_sample\n\n\nMWP_INVALID = -9.9\n# 4.213e19 - Tsuboi 1995, 1999\nMWP_CONST = 4.0 * _PI  # 4 PI\nMWP_CONST *= 3400.0  # rho\nMWP_CONST *= 7900.0 * 7900.0 * 7900.0  # Pvel**3\nMWP_CONST *= 2.0  # FP average radiation pattern\nMWP_CONST *= (10000.0 / 90.0)  # distance deg -> km\nMWP_CONST *= 1000.0  # distance km -> meters\n# https://mail.python.org/pipermail/python-list/2010-February/567089.html, ff.\ntry:\n    FLOAT_MIN = sys.float_info.min\nexcept AttributeError:\n    FLOAT_MIN = 1.1e-37\n\n\ndef calculate_mwp_mag(peak, epicentral_distance):\n    \"\"\"\n    Calculate Mwp magnitude.\n\n    .. seealso:: [Tsuboi1999]_ and [Tsuboi1995]_\n\n    :type peak: float\n    :param peak: Peak value of integral of displacement seismogram.\n    :type epicentral_distance: float\n    :param epicentral_distance: Great-circle epicentral distance from station\n        in degrees.\n    :rtype: float\n    :returns: Calculated Mwp magnitude.\n    \"\"\"\n    moment = MWP_CONST * peak * epicentral_distance\n    mwp_mag = MWP_INVALID\n    if moment > FLOAT_MIN:\n        mwp_mag = (2.0 / 3.0) * (math.log10(moment) - 9.1)\n    return mwp_mag\n\n\ndef kurtosis(trace, win=3.0, rtmemory_list=None):\n    \"\"\"\n    Apply recursive kurtosis calculation on data.\n\n    Recursive kurtosis is computed using the [ChassandeMottin2002]_\n    formulation adjusted to give the kurtosis of a Gaussian distribution = 0.0.\n\n    :type trace: :class:`~obspy.core.trace.Trace`\n    :param trace: :class:`~obspy.core.trace.Trace` object to append to this\n        RtTrace\n    :type win: float, optional\n    :param win: window length in seconds for the kurtosis (default is 3.0 s)\n    :type rtmemory_list: list of :class:`~obspy.realtime.rtmemory.RtMemory`,\n        optional\n    :param rtmemory_list: Persistent memory used by this process for specified\n        trace\n    :rtype: NumPy :class:`numpy.ndarray`\n    :return: Processed trace data from appended Trace object\n    \"\"\"\n    if not isinstance(trace, Trace):\n        msg = \"Trace parameter must be an obspy.core.trace.Trace object.\"\n        raise ValueError(msg)\n\n    # if this is the first appended trace, the rtmemory_list will be None\n    if not rtmemory_list:\n        rtmemory_list = [RtMemory(), RtMemory(), RtMemory()]\n\n    # deal with case of empty trace\n    sample = trace.data\n    if np.size(sample) < 1:\n        return sample\n\n    # get simple info from trace\n    npts = len(sample)\n    dt = trace.stats.delta\n\n    # set some constants for the kurtosis calculation\n    c_1 = dt / float(win)\n    a1 = 1.0 - c_1\n    c_2 = (1.0 - a1 * a1) / 2.0\n    bias = -3 * c_1 - 3.0\n\n    # prepare the output array\n    kappa4 = np.empty(npts, sample.dtype)\n\n    # initialize the real-time memory needed to store\n    # the recursive kurtosis coefficients until the\n    # next bloc of data is added\n    rtmemory_mu1 = rtmemory_list[0]\n    rtmemory_mu2 = rtmemory_list[1]\n    rtmemory_k4_bar = rtmemory_list[2]\n\n    # there are three memory objects, one for each \"last\" coefficient\n    # that needs carrying over\n    # initialize mu1_last to 0\n    if not rtmemory_mu1.initialized:\n        memory_size_input = 1\n        memory_size_output = 0\n        rtmemory_mu1.initialize(sample.dtype, memory_size_input,\n                                memory_size_output, 0, 0)\n\n    # initialize mu2_last (sigma) to 1\n    if not rtmemory_mu2.initialized:\n        memory_size_input = 1\n        memory_size_output = 0\n        rtmemory_mu2.initialize(sample.dtype, memory_size_input,\n                                memory_size_output, 1, 0)\n\n    # initialize k4_bar_last to 0\n    if not rtmemory_k4_bar.initialized:\n        memory_size_input = 1\n        memory_size_output = 0\n        rtmemory_k4_bar.initialize(sample.dtype, memory_size_input,\n                                   memory_size_output, 0, 0)\n\n    mu1_last = rtmemory_mu1.input[0]\n    mu2_last = rtmemory_mu2.input[0]\n    k4_bar_last = rtmemory_k4_bar.input[0]\n\n    # do recursive kurtosis\n    for i in range(npts):\n        mu1 = a1 * mu1_last + c_1 * sample[i]\n        dx2 = (sample[i] - mu1_last) * (sample[i] - mu1_last)\n        mu2 = a1 * mu2_last + c_2 * dx2\n        dx2 = dx2 / mu2_last\n        k4_bar = (1 + c_1 - 2 * c_1 * dx2) * k4_bar_last + c_1 * dx2 * dx2\n        kappa4[i] = k4_bar + bias\n        mu1_last = mu1\n        mu2_last = mu2\n        k4_bar_last = k4_bar\n\n    rtmemory_mu1.input[0] = mu1_last\n    rtmemory_mu2.input[0] = mu2_last\n    rtmemory_k4_bar.input[0] = k4_bar_last\n\n    return kappa4\n", "meta": {"hexsha": "5c52eb8b2334fc94e8da12fb82b6ef5b1a82e7ef", "size": 21435, "ext": "py", "lang": "Python", "max_stars_repo_path": "IRIS_data_download/IRIS_download_support/obspy/realtime/signal.py", "max_stars_repo_name": "earthinversion/Fnet_IRIS_data_automated_download", "max_stars_repo_head_hexsha": "09a6e0c992662feac95744935e038d1c68539fa1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-05T01:03:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-17T05:04:07.000Z", "max_issues_repo_path": "IRIS_data_download/IRIS_download_support/obspy/realtime/signal.py", "max_issues_repo_name": "earthinversion/Fnet_IRIS_data_automated_download", "max_issues_repo_head_hexsha": "09a6e0c992662feac95744935e038d1c68539fa1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-03-31T19:25:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:32:46.000Z", "max_forks_repo_path": "IRIS_data_download/IRIS_download_support/obspy/realtime/signal.py", "max_forks_repo_name": "earthinversion/Fnet_IRIS_data_automated_download", "max_forks_repo_head_hexsha": "09a6e0c992662feac95744935e038d1c68539fa1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-08T19:33:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-05T09:47:50.000Z", "avg_line_length": 33.5971786834, "max_line_length": 79, "alphanum_fraction": 0.6428271519, "include": true, "reason": "import numpy", "num_tokens": 5685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.1986063489461212}}
{"text": "\"\"\"\nThe default unit symbol lookup table.\n\n\n\"\"\"\n\n#-----------------------------------------------------------------------------\n# Copyright (c) 2013, yt Development Team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n#-----------------------------------------------------------------------------\n\nfrom yt.units import dimensions\nfrom yt.utilities.physical_ratios import \\\n    cm_per_pc, cm_per_ly, cm_per_au, cm_per_rsun, cm_per_m, \\\n    mass_sun_grams, sec_per_year, sec_per_day, sec_per_hr, \\\n    sec_per_min, temp_sun_kelvin, luminosity_sun_ergs_per_sec, \\\n    metallicity_sun, erg_per_eV, amu_grams, mass_electron_grams, \\\n    cm_per_ang, jansky_cgs, mass_jupiter_grams, mass_earth_grams, \\\n    kelvin_per_rankine, speed_of_light_cm_per_s, planck_length_cm, \\\n    planck_charge_esu, planck_energy_erg, planck_mass_grams, \\\n    planck_temperature_K, planck_time_s, mass_hydrogen_grams, \\\n    grams_per_pound, standard_gravity_cm_per_s2, pascal_per_atm, \\\n    newton_cgs, cm_per_rearth, cm_per_rjup\nimport numpy as np\n\n# Lookup a unit symbol with the symbol string, and provide a tuple with the\n# conversion factor to cgs and dimensionality.\n\ndefault_unit_symbol_lut = {\n    # base\n    \"g\":  (1.0, dimensions.mass, 0.0, r\"\\rm{g}\"),\n    \"s\":  (1.0, dimensions.time, 0.0, r\"\\rm{s}\"),\n    \"K\":  (1.0, dimensions.temperature, 0.0, r\"\\rm{K}\"),\n    \"radian\": (1.0, dimensions.angle, 0.0, r\"\\rm{radian}\"),\n\n    # other cgs\n    \"dyne\": (1.0, dimensions.force, 0.0, r\"\\rm{dyn}\"),\n    \"erg\":  (1.0, dimensions.energy, 0.0, r\"\\rm{erg}\"),\n    \"esu\":  (1.0, dimensions.charge_cgs, 0.0, r\"\\rm{esu}\"),\n    \"gauss\": (1.0, dimensions.magnetic_field_cgs, 0.0, r\"\\rm{G}\"),\n    \"degC\": (1.0, dimensions.temperature, -273.15, r\"^\\circ\\rm{C}\"),\n    \"statA\": (1.0, dimensions.current_cgs, 0.0, r\"\\rm{statA}\"),\n    \"statV\": (1.0, dimensions.electric_potential_cgs, 0.0, r\"\\rm{statV}\"),\n    \"statohm\": (1.0, dimensions.resistance_cgs, 0.0, r\"\\rm{statohm}\"),\n\n    # some SI\n    \"m\": (1.0e2, dimensions.length, 0.0, r\"\\rm{m}\"),\n    \"J\": (1.0e7, dimensions.energy, 0.0, r\"\\rm{J}\"),\n    \"W\": (1.0e7, dimensions.power, 0.0, r\"\\rm{W}\"),\n    \"Hz\": (1.0, dimensions.rate, 0.0, r\"\\rm{Hz}\"),\n    \"N\": (1.0e5, dimensions.force, 0.0, r\"\\rm{N}\"),\n    \"C\": (1.0, dimensions.charge_mks, 0.0, r\"\\rm{C}\"),\n    \"A\": (1.0, dimensions.current_mks, 0.0, r\"\\rm{A}\"),\n    \"T\": (1000.0, dimensions.magnetic_field_mks, 0.0, r\"\\rm{T}\"),\n    \"Pa\": (10.0, dimensions.pressure, 0.0, r\"\\rm{Pa}\"),\n    \"V\": (1.0e7, dimensions.electric_potential_mks, 0.0, r\"\\rm{V}\"),\n    \"ohm\": (1.0e7, dimensions.resistance_mks, 0.0, r\"\\Omega\"),\n\n    # Imperial and other non-metric units\n    \"ft\": (30.48, dimensions.length, 0.0, r\"\\rm{ft}\"),\n    \"mile\": (160934, dimensions.length, 0.0, r\"\\rm{mile}\"),\n    \"degF\": (kelvin_per_rankine, dimensions.temperature, -459.67,\n             \"^\\circ\\rm{F}\"),\n    \"R\": (kelvin_per_rankine, dimensions.temperature, 0.0, r\"^\\circ\\rm{R}\"),\n    \"lbf\": (grams_per_pound*standard_gravity_cm_per_s2, dimensions.force, 0.0, r\"\\rm{lbf}\"),\n    \"lbm\": (grams_per_pound, dimensions.mass, 0.0, r\"\\rm{lbm}\"),\n    \"atm\": (pascal_per_atm*10., dimensions.pressure, 0.0, r\"\\rm{atm}\"),\n\n    # dimensionless stuff\n    \"h\": (1.0, dimensions.dimensionless, 0.0, r\"h\"),  # needs to be added for rho_crit_now\n    \"dimensionless\": (1.0, dimensions.dimensionless, 0.0, r\"\"),\n\n    # times\n    \"min\": (sec_per_min, dimensions.time, 0.0, r\"\\rm{min}\"),\n    \"hr\":  (sec_per_hr, dimensions.time, 0.0, r\"\\rm{hr}\"),\n    \"day\": (sec_per_day, dimensions.time, 0.0, r\"\\rm{d}\"),\n    \"d\":   (sec_per_day, dimensions.time, 0.0, r\"\\rm{d}\"),\n    \"yr\":  (sec_per_year, dimensions.time, 0.0, r\"\\rm{yr}\"),\n\n    # Velocities\n    \"c\": (speed_of_light_cm_per_s, dimensions.velocity, 0.0, r\"\\rm{c}\"),\n\n    # Solar units\n    \"Msun\": (mass_sun_grams, dimensions.mass, 0.0, r\"M_\\odot\"),\n    \"msun\": (mass_sun_grams, dimensions.mass, 0.0, r\"M_\\odot\"),\n    \"Rsun\": (cm_per_rsun, dimensions.length, 0.0, r\"R_\\odot\"),\n    \"rsun\": (cm_per_rsun, dimensions.length, 0.0, r\"R_\\odot\"),\n    \"R_sun\": (cm_per_rsun, dimensions.length, 0.0, r\"R_\\odot\"),\n    \"r_sun\": (cm_per_rsun, dimensions.length, 0.0, r\"R_\\odot\"),\n    \"Lsun\": (luminosity_sun_ergs_per_sec, dimensions.power, 0.0, r\"L_\\odot\"),\n    \"Tsun\": (temp_sun_kelvin, dimensions.temperature, 0.0, r\"T_\\odot\"),\n    \"Zsun\": (metallicity_sun, dimensions.dimensionless, 0.0, r\"Z_\\odot\"),\n    \"Mjup\": (mass_jupiter_grams, dimensions.mass, 0.0, r\"M_{\\rm{Jup}}\"),\n    \"Mearth\": (mass_earth_grams, dimensions.mass, 0.0, r\"M_\\oplus\"),\n\n    # astro distances\n    \"AU\": (cm_per_au, dimensions.length, 0.0, r\"\\rm{AU}\"),\n    \"au\": (cm_per_au, dimensions.length, 0.0, r\"\\rm{AU}\"),\n    \"ly\": (cm_per_ly, dimensions.length, 0.0, r\"\\rm{ly}\"),\n    \"pc\": (cm_per_pc, dimensions.length, 0.0, r\"\\rm{pc}\"),\n\n    # angles\n    \"degree\": (np.pi/180., dimensions.angle, 0.0, r\"\\rm{deg}\"),  # degrees\n    \"arcmin\": (np.pi/10800., dimensions.angle, 0.0,\n               r\"\\rm{arcmin}\"),  # arcminutes\n    \"arcsec\": (np.pi/648000., dimensions.angle, 0.0,\n               r\"\\rm{arcsec}\"),  # arcseconds\n    \"mas\": (np.pi/648000000., dimensions.angle, 0.0,\n            r\"\\rm{mas}\"),  # milliarcseconds\n    \"hourangle\": (np.pi/12., dimensions.angle, 0.0, r\"\\rm{HA}\"),  # hour angle\n    \"steradian\": (1.0, dimensions.solid_angle, 0.0, r\"\\rm{sr}\"),\n    \"lat\": (-np.pi/180.0, dimensions.angle, 90.0, r\"\\rm{Latitude}\"),\n    \"lon\": (np.pi/180.0, dimensions.angle, -180.0, r\"\\rm{Longitude}\"),\n\n    # misc\n    \"eV\": (erg_per_eV, dimensions.energy, 0.0, r\"\\rm{eV}\"),\n    \"amu\": (amu_grams, dimensions.mass, 0.0, r\"\\rm{amu}\"),\n    \"angstrom\": (cm_per_ang, dimensions.length, 0.0, r\"\\AA\"),\n    \"Jy\": (jansky_cgs, dimensions.specific_flux, 0.0, r\"\\rm{Jy}\"),\n    \"counts\": (1.0, dimensions.dimensionless, 0.0, r\"\\rm{counts}\"),\n    \"photons\": (1.0, dimensions.dimensionless, 0.0, r\"\\rm{photons}\"),\n    \"me\": (mass_electron_grams, dimensions.mass, 0.0, r\"m_e\"),\n    \"mp\": (mass_hydrogen_grams, dimensions.mass, 0.0, r\"m_p\"),\n    \"mol\": (1.0/amu_grams, dimensions.dimensionless, 0.0, r\"\\rm{mol}\"),\n    'Sv': (cm_per_m**2, dimensions.specific_energy, 0.0, r\"\\rm{Sv}\"),\n    \"rayleigh\": (0.25e6/np.pi, dimensions.count_intensity, 0.0, r\"\\rm{R}\"),\n\n    # for AstroPy compatibility\n    \"solMass\": (mass_sun_grams, dimensions.mass, 0.0, r\"M_\\odot\"),\n    \"solRad\": (cm_per_rsun, dimensions.length, 0.0, r\"R_\\odot\"),\n    \"solLum\": (luminosity_sun_ergs_per_sec, dimensions.power, 0.0, r\"L_\\odot\"),\n    \"dyn\": (1.0, dimensions.force, 0.0, r\"\\rm{dyn}\"),\n    \"sr\": (1.0, dimensions.solid_angle, 0.0, r\"\\rm{sr}\"),\n    \"rad\": (1.0, dimensions.angle, 0.0, r\"\\rm{rad}\"),\n    \"deg\": (np.pi/180., dimensions.angle, 0.0, r\"\\rm{deg}\"),\n    \"Fr\":  (1.0, dimensions.charge_cgs, 0.0, r\"\\rm{Fr}\"),\n    \"G\": (1.0, dimensions.magnetic_field_cgs, 0.0, r\"\\rm{G}\"),\n    \"Angstrom\": (cm_per_ang, dimensions.length, 0.0, r\"\\AA\"),\n    \"statC\": (1.0, dimensions.charge_cgs, 0.0, r\"\\rm{statC}\"),\n\n    # Planck units\n    \"m_pl\": (planck_mass_grams, dimensions.mass, 0.0, r\"m_{\\rm{P}}\"),\n    \"l_pl\": (planck_length_cm, dimensions.length, 0.0, r\"\\ell_\\rm{P}\"),\n    \"t_pl\": (planck_time_s, dimensions.time, 0.0, r\"t_{\\rm{P}}\"),\n    \"T_pl\": (planck_temperature_K, dimensions.temperature, 0.0, r\"T_{\\rm{P}}\"),\n    \"q_pl\": (planck_charge_esu, dimensions.charge_cgs, 0.0, r\"q_{\\rm{P}}\"),\n    \"E_pl\": (planck_energy_erg, dimensions.energy, 0.0, r\"E_{\\rm{P}}\"),\n\n    # Geometrized units\n    \"m_geom\": (mass_sun_grams, dimensions.mass, 0.0, r\"M_\\odot\"),\n    \"l_geom\": (newton_cgs*mass_sun_grams/speed_of_light_cm_per_s**2, dimensions.length, 0.0, r\"M_\\odot\"),\n    \"t_geom\": (newton_cgs*mass_sun_grams/speed_of_light_cm_per_s**3, dimensions.time, 0.0, r\"M_\\odot\"),\n\n    # Some Solar System units\n    \"R_earth\": (cm_per_rearth, dimensions.length, 0.0, r\"R_\\oplus\"),\n    \"r_earth\": (cm_per_rearth, dimensions.length, 0.0, r\"R_\\oplus\"),\n    \"R_jup\": (cm_per_rjup, dimensions.length, 0.0, r\"R_\\mathrm{Jup}\"),\n    \"r_jup\": (cm_per_rjup, dimensions.length, 0.0, r\"R_\\mathrm{Jup}\"),\n}\n\n# This dictionary formatting from magnitude package, credit to Juan Reyero.\nunit_prefixes = {\n    'Y': 1e24,   # yotta\n    'Z': 1e21,   # zetta\n    'E': 1e18,   # exa\n    'P': 1e15,   # peta\n    'T': 1e12,   # tera\n    'G': 1e9,    # giga\n    'M': 1e6,    # mega\n    'k': 1e3,    # kilo\n    'd': 1e1,    # deci\n    'c': 1e-2,   # centi\n    'm': 1e-3,   # mili\n    'u': 1e-6,   # micro\n    'n': 1e-9,   # nano\n    'p': 1e-12,  # pico\n    'f': 1e-15,  # femto\n    'a': 1e-18,  # atto\n    'z': 1e-21,  # zepto\n    'y': 1e-24,  # yocto\n}\n\nlatex_prefixes = {\n    \"u\": r\"\\mu\",\n    }\n\nprefixable_units = [\n    \"m\",\n    \"pc\",\n    \"mcm\",\n    \"pccm\",\n    \"g\",\n    \"eV\",\n    \"s\",\n    \"yr\",\n    \"K\",\n    \"dyne\",\n    \"erg\",\n    \"esu\",\n    \"J\",\n    \"Hz\",\n    \"W\",\n    \"gauss\",\n    \"G\",\n    \"Jy\",\n    \"N\",\n    \"T\",\n    \"A\",\n    \"C\",\n    \"statA\",\n    \"Pa\",\n    \"V\",\n    \"statV\",\n    \"ohm\",\n    \"statohm\",\n    \"Sv\",\n]\n\ndefault_base_units = {\n    dimensions.mass: 'g',\n    dimensions.length: 'cm',\n    dimensions.time: 's',\n    dimensions.temperature: 'K',\n    dimensions.angle: 'radian',\n    dimensions.current_mks: 'A',\n}\n", "meta": {"hexsha": "e091e8e29602bdf49399c3926a79a62978cef790", "size": 9149, "ext": "py", "lang": "Python", "max_stars_repo_path": "yt/units/unit_lookup_table.py", "max_stars_repo_name": "kastalpes/yt", "max_stars_repo_head_hexsha": "b1e197ca84433fbd61eaf44b28ff5cdb37981d4c", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-02T18:59:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-02T18:59:50.000Z", "max_issues_repo_path": "yt/units/unit_lookup_table.py", "max_issues_repo_name": "kastalpes/yt", "max_issues_repo_head_hexsha": "b1e197ca84433fbd61eaf44b28ff5cdb37981d4c", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-04-13T23:03:42.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-08T17:50:43.000Z", "max_forks_repo_path": "yt/units/unit_lookup_table.py", "max_forks_repo_name": "kastalpes/yt", "max_forks_repo_head_hexsha": "b1e197ca84433fbd61eaf44b28ff5cdb37981d4c", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-16T15:29:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-22T10:17:08.000Z", "avg_line_length": 39.7782608696, "max_line_length": 105, "alphanum_fraction": 0.5938353918, "include": true, "reason": "import numpy", "num_tokens": 3515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19860634153415052}}
{"text": "\"\"\"!\nAdopted from https://github.com/ujscjj/DPTNet\nModified by Yi Luo {yl3364@columbia.edu}\n\"\"\"\n\nimport numpy as np\nimport os\nimport copy\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch.nn.modules.module import Module\nfrom torch.nn.modules.activation import MultiheadAttention\nfrom torch.nn.modules.container import ModuleList\nfrom torch.nn.init import xavier_uniform_\nfrom torch.nn.modules.dropout import Dropout\nfrom torch.nn.modules.linear import Linear\nfrom torch.nn.modules.rnn import LSTM\nfrom torch.nn.modules.normalization import LayerNorm\n\nclass TransformerOptimizer(object):\n    \"\"\"A simple wrapper class for learning rate scheduling\"\"\"\n\n    def __init__(self, optimizer, k, d_model, warmup_steps=4000):\n        self.optimizer = optimizer\n        self.k = k\n        self.init_lr = d_model ** (-0.5)\n        self.warmup_steps = warmup_steps\n        self.step_num = 0\n        self.epoch = 0\n        self.visdom_lr = None\n\n    def zero_grad(self):\n        self.optimizer.zero_grad()\n\n    def step(self, epoch):\n        self._update_lr(epoch)\n        # self._visdom()\n        self.optimizer.step()\n\n    def _update_lr(self, epoch):\n        self.step_num += 1\n        if self.step_num <= self.warmup_steps:\n            lr = self.k * self.init_lr * min(self.step_num ** (-0.5),\n                                             self.step_num * (self.warmup_steps ** (-1.5)))\n        else:\n            lr = 0.0004 * (0.98 ** ((epoch-1)//2))\n\n        for param_group in self.optimizer.param_groups:\n            param_group['lr'] = lr\n\n    def load_state_dict(self, state_dict):\n        self.optimizer.load_state_dict(state_dict)\n\n    def state_dict(self):\n        return self.optimizer.state_dict()\n\n    def set_k(self, k):\n        self.k = k\n\n    def set_visdom(self, visdom_lr, vis):\n        self.visdom_lr = visdom_lr  # Turn on/off visdom of learning rate\n        self.vis = vis  # visdom enviroment\n        self.vis_opts = dict(title='Learning Rate',\n                             ylabel='Leanring Rate', xlabel='step')\n        self.vis_window = None\n        self.x_axis = torch.LongTensor()\n        self.y_axis = torch.FloatTensor()\n\n    def _visdom(self):\n        if self.visdom_lr is not None:\n            self.x_axis = torch.cat(\n                [self.x_axis, torch.LongTensor([self.step_num])])\n            self.y_axis = torch.cat(\n                [self.y_axis, torch.FloatTensor([self.optimizer.param_groups[0]['lr']])])\n            if self.vis_window is None:\n                self.vis_window = self.vis.line(X=self.x_axis, Y=self.y_axis,\n                                                opts=self.vis_opts)\n            else:\n                self.vis.line(X=self.x_axis, Y=self.y_axis, win=self.vis_window,\n                              update='replace')\n\nclass TransformerEncoderLayer(nn.Module):\n    r\"\"\"TransformerEncoderLayer is made up of self-attn and feedforward network.\n    This standard encoder layer is based on the paper \"Attention Is All You Need\".\n    Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez,\n    Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in\n    Neural Information Processing Systems, pages 6000-6010. Users may modify or implement\n    in a different way during application.\n    Args:\n        d_model: the number of expected features in the input (required).\n        nhead: the number of heads in the multiheadattention models (required).\n        dim_feedforward: the dimension of the feedforward network model (default=2048).\n        dropout: the dropout value (default=0.1).\n        activation: the activation function of intermediate layer, relu or gelu (default=relu).\n    Examples::\n        >>> encoder_layer = nn.TransformerEncoderLayer(d_model=512, nhead=8)\n        >>> src = torch.rand(10, 32, 512)\n        >>> out = encoder_layer(src)\n    \"\"\"\n\n    def __init__(self, d_model, nhead, dim_feedforward=256, dropout=0, activation=\"relu\"):\n        super(TransformerEncoderLayer, self).__init__()\n        self.self_attn = MultiheadAttention(d_model, nhead, dropout=dropout)\n        # Implementation of Feedforward model\n        # self.linear1 = Linear(d_model, dim_feedforward)\n        self.linear1 = LSTM(d_model, d_model*2, 1, bidirectional=True)\n        self.dropout = Dropout(dropout)\n        # self.linear2 = Linear(dim_feedforward, d_model)\n        self.linear2 = Linear(d_model*2*2, d_model)\n\n        self.norm1 = LayerNorm(d_model)\n        self.norm2 = LayerNorm(d_model)\n        self.dropout1 = Dropout(dropout)\n        self.dropout2 = Dropout(dropout)\n\n        self.activation = _get_activation_fn(activation)\n\n    def __setstate__(self, state):\n        if 'activation' not in state:\n            state['activation'] = F.relu\n        super(TransformerEncoderLayer, self).__setstate__(state)\n\n    def forward(self, src, src_mask=None, src_key_padding_mask=None):\n        # type: (Tensor, Optional[Tensor], Optional[Tensor]) -> Tensor\n        r\"\"\"Pass the input through the encoder layer.\n        Args:\n            src: the sequnce to the encoder layer (required).\n            src_mask: the mask for the src sequence (optional).\n            src_key_padding_mask: the mask for the src keys per batch (optional).\n        Shape:\n            see the docs in Transformer class.\n        \"\"\"\n        src2 = self.self_attn(src, src, src, attn_mask=src_mask,\n                              key_padding_mask=src_key_padding_mask)[0]\n        src = src + self.dropout1(src2)\n        src = self.norm1(src)\n        # src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))\n        src2 = self.linear2(self.dropout(self.activation(self.linear1(src)[0])))\n        src = src + self.dropout2(src2)\n        src = self.norm2(src)\n        return src\n\n\ndef _get_clones(module, N):\n    return ModuleList([copy.deepcopy(module) for i in range(N)])\n\n\ndef _get_activation_fn(activation):\n    if activation == \"relu\":\n        return F.relu\n    elif activation == \"gelu\":\n        return F.gelu\n\n    raise RuntimeError(\"activation should be relu/gelu, not {}\".format(activation))\n    \nclass SingleTransformer(nn.Module):\n\n    def __init__(self, input_size, dim_feedforward):\n        super(SingleTransformer, self).__init__()\n\n        self.transformer = TransformerEncoderLayer(d_model=input_size, nhead=4, dim_feedforward=dim_feedforward, dropout=0)\n\n    def forward(self, input):\n        # input shape: batch, seq, dim\n        output = input\n        output = self.transformer(output.permute(1, 0, 2).contiguous()).permute(1, 0, 2).contiguous()\n        return output\n    \n# dual-path Transformer\nclass DPTNet(nn.Module):\n    def __init__(self, input_size, hidden_size, output_size, \n                 dropout=0, num_layers=1):\n        super(DPTNet, self).__init__()\n        \n        self.input_size = input_size\n        self.output_size = output_size\n        self.hidden_size = hidden_size\n        \n        # dual-path Transformer\n        self.row_xfmr = nn.ModuleList([])\n        self.col_xfmr = nn.ModuleList([])\n        for i in range(num_layers):\n            self.row_xfmr.append(SingleTransformer(input_size=input_size, dim_feedforward=hidden_size))\n            self.col_xfmr.append(SingleTransformer(input_size=input_size, dim_feedforward=hidden_size))\n            \n        self.output = nn.Conv2d(input_size, output_size, 1)\n            \n    def forward(self, input):\n        # input shape: batch, N, dim1, dim2\n        # apply RNN on dim1 first and then dim2\n        \n        batch_size, _, dim1, dim2 = input.shape\n        output = input\n        for i in range(len(self.row_xfmr)):\n            row_input = output.permute(0,3,2,1).contiguous().view(batch_size*dim2, dim1, -1)  # B*dim2, dim1, N\n            row_output = self.row_xfmr[i](row_input)  # B*dim2, dim1, H\n            row_output = row_output.view(batch_size, dim2, dim1, -1).permute(0,3,2,1).contiguous()  # B, N, dim1, dim2\n            output = output + row_output\n            \n            col_input = output.permute(0,2,3,1).contiguous().view(batch_size*dim1, dim2, -1)  # B*dim1, dim2, N\n            col_output = self.col_xfmr[i](col_input)  # B*dim1, dim2, H\n            col_output = col_output.view(batch_size, dim1, dim2, -1).permute(0,3,1,2).contiguous()  # B, N, dim1, dim2\n            output = output + col_output\n            \n        output = self.output(output)\n            \n        return output", "meta": {"hexsha": "96be258db69da3ce5652b05580c0e8766bdf15d2", "size": 8442, "ext": "py", "lang": "Python", "max_stars_repo_path": "utility/DPTNet.py", "max_stars_repo_name": "yluo42/GC3", "max_stars_repo_head_hexsha": "3ae841395be99d0378852092c0b6e885a7bff9a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2020-12-15T07:29:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:09:55.000Z", "max_issues_repo_path": "utility/DPTNet.py", "max_issues_repo_name": "yluo42/GC3", "max_issues_repo_head_hexsha": "3ae841395be99d0378852092c0b6e885a7bff9a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-06T11:59:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-06T11:59:57.000Z", "max_forks_repo_path": "utility/DPTNet.py", "max_forks_repo_name": "yluo42/GC3", "max_forks_repo_head_hexsha": "3ae841395be99d0378852092c0b6e885a7bff9a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2021-01-28T11:36:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T13:06:53.000Z", "avg_line_length": 40.3923444976, "max_line_length": 123, "alphanum_fraction": 0.635631367, "include": true, "reason": "import numpy", "num_tokens": 2047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19860634153415052}}
{"text": "'''\nSome tools to conveniently transform lmfit.Parameters into GalSim.Image's.\n'''\n\nimport copy\n\nimport numpy as np\nfrom scipy.optimize import newton\nimport galsim\nimport lmfit\n\nimport chroma\n\nclass GalTool(object):\n    ''' Some generic utilities for drawing ringtest images using GalSim and measuring second moment\n    radii.\n    '''\n    def __init__(self):\n        # Subclasses of GalTool must initialize the following:\n        #\n        #   attributes\n        #   ----------\n        #   stamp_size - Integer number of pixels in which to draw images\n        #   pixel_scale - arcsec / pixel\n        #   PSF - either a ChromaticObject or an effective PSF as a GSObject.\n        #   offset - tuple defining subpixel offset of image origin from center\n        #   gsparams - galsim.GSParams instance defining parameters for GalSim.\n        #\n        #   methods\n        #   -------\n        #   _gparam_to_galsim - turn lmfit.Parameters into a galsim.GSObject or\n        #                       galsim.ChromaticObject\n        raise NotImplementedError(\"ABC GalTool must be instatiated through a subclass.\")\n\n    def get_image(self, gparam, ring_beta=None, ring_shear=None, oversample=1):\n        ''' Draw a galaxy image using GalSim.  Potentially rotate and shear the galaxy as part of a\n        ring test.  Optionally draw a high-resolution image.\n\n        @param gparam      An lmfit.Parameters object that will be used to initialize a GalSim\n                           object.\n        @param ring_beta   Angle around ellipticity ring in ring test.\n        @param ring_shear  galsim.Shear to apply after rotation as part of ring test.\n        @param oversample  Integer factor by which to scale output image resolution and size.\n        @returns  galsim.Image\n        '''\n        # Setup image\n        stamp_size = self.stamp_size * oversample\n        pixel_scale = self.pixel_scale / float(oversample)\n        im = galsim.ImageD(stamp_size, stamp_size, scale=pixel_scale)\n        # Get GalSim parameterization of the galaxy.\n        gal = self._gparam_to_galsim(gparam)\n        # Rotate and shear the galaxy as per the ring test specifications.\n        if ring_beta is not None:\n            gal = gal.rotate(ring_beta / 2.0 * galsim.radians)\n        if ring_shear is not None:\n            gal = gal.shear(ring_shear)\n        # Convolve with the (chromatic, or effective) PSF.  This will need to be different for the\n        # double Sersic case.\n        final = galsim.Convolve(gal, self.PSF)\n        # And draw the image.\n        if isinstance(final, galsim.ChromaticObject):\n            final.drawImage(self.bandpass, image=im, offset=self.offset)\n        elif isinstance(final, galsim.GSObject):\n            final.drawImage(image=im, offset=self.offset)\n        else:\n            raise ValueError(\"Don't recognize galaxy object type in GalTool.\")\n        return im\n\n    def get_PSF_image(self, oversample=1, method='auto'):\n        ''' Draw an image of the effective PSF.  Note that the returned PSF includes convolution\n        by the pixel response function by default, though this can be overriden using the method\n        keywords (e.g., method='fft').\n\n        @param oversample  Integer factor by which to scale output image resolution and size.\n        @param method      Method string to pass to galsim drawImage command.\n        @returns  galsim.Image\n        '''\n        stamp_size = self.stamp_size * oversample\n        pixel_scale = self.pixel_scale / float(oversample)\n        im = galsim.ImageD(stamp_size, stamp_size, scale=pixel_scale)\n        if isinstance(self.PSF, galsim.ChromaticObject):\n            star = galsim.Gaussian(fwhm=1.e-8) * self.SED\n            final = galsim.Convolve(star, self.PSF)\n            final.drawImage(self.bandpass, image=im, method=method)\n        elif isinstance(self.PSF, galsim.GSObject):\n            self.PSF.drawImage(image=im, method=method)\n        else:\n            raise ValueError(\"Don't recognize galaxy object type.\")\n        return im\n\n    def get_r2(self, gparam, oversample=1):\n        ''' Compute object second moment radius sqrt(r^2) directly from image.  This may be biased\n        if the object wings are significant or the postage stamp size is too small.\n\n        @param gparam   An lmfit.Parameters object that will be used to initialize a GalSim object.\n        @returns        Second moment radius (in arcsec)\n        '''\n        im = self.get_image(gparam, oversample=oversample)\n        mx, my, mxx, myy, mxy = chroma.moments(im)\n        return np.sqrt(mxx + myy)\n\n    def get_uncvl_image(self, gparam, ring_beta=None, ring_shear=None, oversample=1, center=False):\n        ''' Draw a galaxy image, not convolved with a PSF, using GalSim.  Potentially rotate and\n        shear the galaxy as part of a ring test.  Optionally draw a high-resolution image.\n\n        @param gparam      An lmfit.Paramters object that will be used to initialize a GalSim object.\n        @param ring_beta   Angle around ellipticity ring in ring test.\n        @param ring_shear  Shear to apply after rotation as part of ring test. (type=?)\n        @param oversample  Integer factor by which to scale output image resolution and size.\n        @param center      Force center of profile to (0,0).\n        @returns  galsim.Image\n        '''\n        stamp_size = self.stamp_size * oversample\n        pixel_scale = self.pixel_scale / float(oversample)\n        im = galsim.ImageD(stamp_size, stamp_size, scale=pixel_scale)\n        gal = self._gparam_to_galsim(gparam)\n        if center:\n            centroid = gal.centroid(self.bandpass)\n            gal = gal.shift(-centroid)\n        if ring_beta is not None:\n            gal = gal.rotate(ring_beta / 2.0 * galsim.radians)\n        if ring_shear is not None:\n            gal = gal.shear(ring_shear)\n        if isinstance(gal, galsim.ChromaticObject):\n            gal.drawImage(self.bandpass, image=im, offset=self.offset)\n        elif isinstance(gal, galsim.GSObject):\n            gal.drawImage(image=im, offset=self.offset)\n        else:\n            raise ValueError(\"Don't recognize galaxy object type in GalTool.\")\n        return im\n\n    def get_uncvl_r2(self, gparam, oversample=1):\n        ''' Compute object second moment radius directly from image.  This may be biased if the\n        object wings are significant or the postage stamp size is too small.\n\n        @param gparam   An lmfit.Parameters object that will be used to initialize a GalSim object.\n        @returns        Second moment radius (in arcsec)\n        '''\n        im = self.get_uncvl_image(gparam, oversample=oversample)\n        mx, my, mxx, myy, mxy = chroma.moments(im)\n        return np.sqrt(mxx + myy)\n\n    def compute_AHM(self, gparam, oversample=4):\n        ''' Compute the area above half maximum of the convolved image.\n        '''\n        original_offset = self.offset\n        original_scale = self.pixel_scale\n        ahms = []\n        for i in range(10):\n            itry = 0\n            while itry < 10:\n                xdither = np.random.uniform(-0.5, 0.5, 1)[0]\n                ydither = np.random.uniform(-0.5, 0.5, 1)[0]\n                rescale = np.random.uniform(0.9, 1.1, 1)[0]\n                self.offset = (xdither, ydither)\n                self.pixel_scale = original_scale * rescale\n                try:\n                    im = self.get_image(gparam, oversample=oversample)\n                except RuntimeError:\n                    itry += 1\n                else:\n                    break\n            if itry >= 10:\n                raise RuntimeError(\"Unable to create image to estimate AHM\")\n            mx = im.array.max()\n            ahms.append(self.pixel_scale**2 * (im.array > mx/2.0).sum() / oversample**2)\n        self.offset = original_offset\n        self.pixel_scale = original_scale\n        return np.mean(ahms), np.std(ahms)/np.sqrt(len(ahms))\n\n    def compute_FWHM(self, gparam, oversample=4):\n        ''' Compute FWHM of the convolved galaxy image.\n        '''\n        ahm, err = self.compute_AHM(gparam, oversample=oversample)\n        fwhm = np.sqrt(4.0/np.pi * ahm)\n        return fwhm, fwhm * err/ahm * 0.5\n\n    def compute_PSF_AHM(self, oversample=4):\n        ''' Compute the area above half maximum of the PSF.\n        '''\n        original_offset = self.offset\n        original_scale = self.pixel_scale\n        ahms = []\n        for i in range(10):\n            itry = 0\n            while itry < 10:\n                xdither = np.random.uniform(-0.5, 0.5, 1)[0]\n                ydither = np.random.uniform(-0.5, 0.5, 1)[0]\n                rescale = np.random.uniform(0.9, 1.1, 1)[0]\n                self.offset = (xdither, ydither)\n                self.pixel_scale = original_scale * rescale\n                try:\n                    im = self.get_PSF_image(oversample=oversample)\n                except RuntimeError:\n                    itry += 1\n                else:\n                    break\n            if itry >= 10:\n                raise RuntimeError(\"Unable to create image to estimate AHM\")\n            if isinstance(im, list):\n                im = sum(im)\n            mx = im.array.max()\n            ahms.append(self.pixel_scale**2 * (im.array > mx/2.0).sum() / oversample**2)\n        self.offset = original_offset\n        self.pixel_scale = original_scale\n        return np.mean(ahms), np.std(ahms)/np.sqrt(len(ahms))\n\n    def compute_PSF_FWHM(self, oversample=4):\n        ''' Compute FWHM of the PSF.\n        '''\n        ahm, err = self.compute_PSF_AHM(oversample=oversample)\n        fwhm = np.sqrt(4.0/np.pi * ahm)\n        return fwhm, fwhm * err/ahm * 0.5\n\n    def compute_HLA(self, gparam, oversample=4, flux=None):\n        ''' Compute the half-light-area of the PSF-convolved galaxy image.\n        I.e., the area of the contour containing half the image light.\n        '''\n        im = self.get_image(gparam, oversample=oversample)\n        if flux is None:\n            flux = im.array.sum()\n        pixel_values = im.array.ravel()\n        pixel_values.sort()\n        cumulative_sum = np.cumsum(pixel_values[::-1])\n        npix = np.interp(0.5, cumulative_sum, np.arange(len(cumulative_sum)))\n        return npix * self.pixel_scale**2 / oversample**2\n\n    def compute_HLR(self, gparam, oversample=4, flux=None):\n        ''' Compute the half-light-radius of the PSF-convolved galaxy image.\n        '''\n        return np.sqrt(1.0/np.pi * self.compute_HLA(gparam, oversample, flux))\n\n    def compute_uncvl_HLA(self, gparam, oversample=4, flux=None):\n        ''' Compute the half-light-area of the unconvolved galaxy image.\n        I.e., the area of the contour containing half the image light.\n        '''\n        im = self.get_uncvl_image(gparam, oversample=oversample)\n        if flux is None:\n            flux = im.array.sum()\n        pixel_values = im.array.ravel()\n        pixel_values.sort()\n        cumulative_sum = np.cumsum(pixel_values[::-1])\n        npix = np.interp(0.5, cumulative_sum, np.arange(len(cumulative_sum)))\n        return npix * self.pixel_scale**2 / oversample**2\n\n    def compute_uncvl_HLR(self, gparam, oversample=4, flux=None):\n        ''' Compute the half-light-radius of the unconvolved galaxy image.\n        '''\n        return np.sqrt(1.0/np.pi * self.compute_uncvl_HLA(gparam, oversample, flux))\n\n\nclass SersicTool(GalTool):\n    def __init__(self, PSF, stamp_size, pixel_scale, offset=(0,0),\n                 SED=1.0, bandpass=None, gsparams=None):\n        self.PSF = PSF\n        self.stamp_size = stamp_size\n        self.pixel_scale = pixel_scale\n        self.offset = offset\n        self.gsparams = gsparams\n        self.SED = SED\n        self.bandpass = bandpass\n\n    def _gparam_to_galsim(self, gparam):\n        # Turn lmfit.Parameters into a galsim.ChromaticObject\n        gal = galsim.Sersic(n=gparam['n'].value,\n                            half_light_radius=gparam['hlr'].value,\n                            gsparams=self.gsparams)\n        gal = gal.shear(g=gparam['g'].value, beta=gparam['phi'].value * galsim.radians)\n        gal = gal.shift(gparam['x0'].value, gparam['y0'].value)\n        gal = gal.withFlux(gparam['flux'].value) * self.SED\n        return gal\n\n    def set_FWHM(self, gparam, FWHM, oversample=4):\n        ''' Set the galaxy PSF-convolved FWHM.\n        '''\n        def FWHM_resid(scale):\n            g1 = copy.deepcopy(gparam)\n            g1['hlr'].value *= scale\n            current_FWHM = self.compute_FWHM(g1, oversample=oversample)\n            return current_FWHM[0] - FWHM\n        scale = newton(FWHM_resid, 1.0, tol=0.001)\n        gparam['hlr'].value *= scale\n        return gparam\n\n    def set_r2(self, gparam, r2, oversample=4):\n        ''' Set the second moment radius sqrt(r^2).\n\n        @param gparam      lmfit.Parameters object describing galaxy.\n        @param r2          Target second moment radius sqrt(r^2)\n        @param oversample  Factor by which to oversample drawn image for computation.\n        @returns           New lmfit.Parameters object.\n        '''\n        def r2_resid(scale):\n            g1 = copy.deepcopy(gparam)\n            g1['hlr'].value *= scale\n            current_r2 = self.get_r2(g1, oversample=oversample)\n            return current_r2 - r2\n        scale = newton(r2_resid, 1.0)\n        gparam['hlr'].value *= scale\n        return gparam\n\n    def get_uncvl_r2(self, gparam):\n        ''' Get second moment radius sqrt(r^2) of pre-PSF-convolved profile using polynomial\n        approximation.\n        @gparam   lmfit.Parameters\n        '''\n        return gparam['hlr'].value * chroma.Sersic_r2_over_hlr(gparam['n'].value)\n\n    def set_uncvl_r2(self, gparam, r2):\n        ''' Set the second moment radius sqrt(r^2) of the pre-PSF-convolved profile using\n        polynomial approximation.\n\n        @param gparam      lmfit.Parameters object describing galaxy.\n        @param r2          Target second moment square radius\n        @param oversample  Factor by which to oversample drawn image for r2 computation.\n        @returns           New lmfit.Parameters object.\n        '''\n        gparam1 = copy.deepcopy(gparam)\n        r2_now = self.get_uncvl_r2(gparam)\n        scale = r2 / r2_now\n        gparam1['hlr'].value = gparam['hlr'].value * scale\n        return gparam1\n\n    def get_ring_params(self, gparam, ring_beta, ring_shear):\n        ''' Compute initial guess parameters for given angle around ellipticity ring during a ring\n        test.\n\n        @param gparam      lmfit.Parameters object describing galaxy.\n        @param ring_beta   Angle around ellipticity ring in ring test.\n        @param ring_shear  Shear to apply after rotation as part of ring test. (type=?)\n        @returns           New lmfit.Parameters object.\n        '''\n        gparam1 = copy.deepcopy(gparam)\n        rot_phi = gparam['phi'].value + ring_beta/2.0\n        # complex ellipticity\n        c_ellip = gparam['g'].value * complex(np.cos(2.0 * rot_phi), np.sin(2.0 * rot_phi))\n        c_gamma = ring_shear.g1 + 1j * ring_shear.g2\n        # sheared complex ellipticity\n        s_c_ellip = chroma.apply_shear(c_ellip, c_gamma)\n        s_g = abs(s_c_ellip)\n        s_phi = np.angle(s_c_ellip) / 2.0\n\n        gparam1['x0'].value \\\n          = gparam['x0'].value * np.cos(ring_beta / 2.0) \\\n          - gparam['y0'].value * np.sin(ring_beta / 2.0)\n        gparam1['y0'].value \\\n          = gparam['x0'].value * np.sin(ring_beta / 2.0) \\\n          + gparam['y0'].value * np.cos(ring_beta / 2.0)\n        gparam1['g'].value = s_g\n        gparam1['phi'].value = s_phi\n        return gparam1\n\n    @staticmethod\n    def default_galaxy():\n        '''Setup lmfit.Parameters to represent a single Sersic galaxy.  Pick some default\n        parameter values.  Parameters defining the single Sersic galaxy are:\n        x0   - the x-coordinate of the galaxy center\n        y0   - the y-coordinate of the galaxy center\n        n    - the Sersic index.  0.5 gives a Gaussian profile, 1.0 gives an exponential profile,\n               4.0 gives a de Vaucouleurs profile.\n        hlr  - the galaxy half-light-radius.  This is strictly speaking the half light radius of\n               a circularly symmetric profile of the given Sersic index `n`.\n        g    - the magnitude of the galaxy ellipticity given in `g` units as used by GalSim.  In\n               this convention, the major/minor axis ratio is given by: b/a = (1 - g) / (1 + g)\n        phi  - the position angle of the galaxy major axis in radians.  0 indicates that the major\n               axis is along the x-axis.\n        '''\n        gparam = lmfit.Parameters()\n        gparam.add('x0', value=0.0)\n        gparam.add('y0', value=0.0)\n        gparam.add('n', value=4.0, vary=False)\n        gparam.add('hlr', value=0.27)\n        gparam.add('flux', value=1.0, vary=False)\n        gparam.add('g', value=0.2, min=0.0, max=1.0)\n        gparam.add('phi', value=0.0)\n        return gparam\n\n    def use_effective_PSF(self):\n        ''' Integrate a chromatic PSF over wavelength to yield an effective PSF.  Galsim is doing\n        this internally anyway, but we do this explicitly here so that it happens only once, instead\n        of every time a .drawImage command is executed.\n        '''\n        star = galsim.Gaussian(fwhm=1.e-8) * self.SED\n        prof = galsim.Convolve(star, self.PSF)\n        prof0 = prof.evaluateAtWavelength(self.bandpass.effective_wavelength)\n        scale = prof0.nyquistScale()\n        N = prof0.SBProfile.getGoodImageSize(scale, 1.0)\n        im = galsim.ImageD(N, N, scale=scale)\n        # careful, don't want to convolve by pixel twice!\n        prof.drawImage(self.bandpass, image=im, method='no_pixel')\n        self.PSF = galsim.InterpolatedImage(im) # remember the effective PSF\n\n    def apply_perturbative_correction(self, r2byr2=1.0, Vstar=1.e-8, Vgal=1.e-8,\n                                      parang=0.0*galsim.degrees):\n        if isinstance(self.PSF, galsim.ChromaticObject):\n            star = galsim.Gaussian(fwhm=1.e-8) * self.SED\n            prof = galsim.Convolve(star, self.PSF)\n        elif isinstance(self.PSF, galsim.GSObject):\n            prof = self.PSF\n        else:\n            raise ValueError(\"Don't recognize galaxy object type.\")\n\n        #-----------------------\n        # Stellar DCR correction\n\n        # `q` is the axis ratio of a 2D Gaussian representing the 1D DCR kernel. In principle, this\n        # should be 0.0, but we need to set it to some small value for computability.\n        q = 1.e-4\n        sigma = (q * Vstar)**0.5\n        kernel = galsim.Gaussian(sigma=sigma)\n        kernel = kernel.shear(g1=-(1-q)/(1+q))\n        kernel = kernel.rotate(parang)\n        prof = galsim.Convolve(galsim.Deconvolve(kernel), prof)\n\n        #----------------------------\n        # Chromatic Seeing correction\n        prof = prof.dilate(np.sqrt(r2byr2))\n\n        #------------------------\n        # Galactic DCR correction\n        sigma = (q * Vgal)**0.5\n        kernel = galsim.Gaussian(sigma=sigma)\n        kernel = kernel.shear(g1=-(1-q)/(1+q))\n        kernel = kernel.rotate(parang)\n        prof = galsim.Convolve(kernel, prof)\n\n        # and draw into an InterpolatedImage\n        prof0 = prof.evaluateAtWavelength(self.bandpass.effective_wavelength)\n        scale = prof0.nyquistScale()\n        N = prof0.SBProfile.getGoodImageSize(scale, 1.0)\n        im = galsim.ImageD(N*9, N*9, scale=scale*0.3)\n        if isinstance(prof, galsim.ChromaticObject):\n            prof.drawImage(self.bandpass, image=im, method='no_pixel')\n        else:\n            prof.drawImage(image=im, method='no_pixel')\n        self.PSF = galsim.InterpolatedImage(im)\n\n\n# Note that DoubleSersicTool and FastDoubleSersicTool are both currently untested.\nclass DoubleSersicTool(GalTool):\n    ''' A GalTool to represent a sum of two chroma Sersic profiles.\n    '''\n    def __init__(self, PSF, stamp_size, pixel_scale, offset=(0,0), SED1=1.0, SED2=1.0,\n                 bandpass=None, gsparams=None):\n        ''' Initialize a single Sersic profile chromatic galaxy.\n\n        @param PSF          galsim.ChromaticObject representing chromatic PSF\n        @param stamp_size   Draw images this many pixels square\n        @param pixel_scale  Pixels are this wide in arcsec.\n        @param offset       Offset the center of the profile by this amount\n        @param SED1         Optional galsim.SED galaxy spectrum for first component\n        @param SED2         Optional galsim.SED galaxy spectrum for second component\n        @param bandpass     Optional galsim.Bandpass to represent filter being imaged through.\n        '''\n        self.SED1 = SED1\n        self.SED2 = SED2\n        self.bandpass = bandpass\n        self.PSF = PSF\n        self.stamp_size = stamp_size\n        self.pixel_scale = pixel_scale\n        self.offset = offset\n        self.gsparams = gsparams\n        self.sersictools = [SersicTool(PSF, stamp_size, pixel_scale, offset=offset,\n                                       SED=SED1, bandpass=bandpass, gsparams=gsparams),\n                            SersicTool(PSF, stamp_size, pixel_scale, offset=offset,\n                                       SED=SED2, bandpass=bandpass, gsparams=gsparams)]\n\n    def indiv_gparam(self, gparam, icomp):\n        out = lmfit.Parameters()\n        search_string = \"_{}\".format(icomp+1)\n        for p in gparam:\n            if p.endswith(search_string):\n                out.add(p.replace(search_string, ''), value=gparam[p].value)\n        return out\n\n    def get_image(self, gparam, ring_beta=None, ring_shear=None, oversample=1, icomp=None):\n        ''' Draw a galaxy image using GalSim.  Potentially rotate and shear the galaxy as part of a\n        ring test.  Optionally draw a high-resolution image.\n\n        @param gparam      An lmfit.Parameters object that will be used to initialize a GalSim\n                           object.\n        @param ring_beta   Angle around ellipticity ring in ring test.\n        @param ring_shear  galsim.Shear to apply after rotation as part of ring test.\n        @param oversample  Integer factor by which to scale output image resolution and size.\n        @param icomp       Which component to return the image of.\n        @returns           galsim.Image\n        '''\n        if icomp is not None:\n            return self.sersictools[icomp].get_image(\n                self.indiv_gparam(gparam, icomp), ring_beta, ring_shear, oversample)\n        else:\n            im1 = self.sersictools[0].get_image(self.indiv_gparam(gparam, 0), ring_beta, ring_shear,\n                                                oversample)\n            im2 = self.sersictools[1].get_image(self.indiv_gparam(gparam, 1), ring_beta, ring_shear,\n                                                oversample)\n            return im1+im2\n\n    def use_effective_PSF(self):\n        ''' Integrate chromatic PSF over wavelength to yield effective PSFs.  GalSim is doing\n        this internally anyway, but we do this explicitly here so that it happens only once, instead\n        of every time a .drawImage() command is executed.\n        '''\n        for s in self.sersictools:\n            s.use_effective_PSF()\n        self.PSF = [s.PSF for s in self.sersictools]\n\n    def get_PSF_image(self, oversample=1, method='auto', icomp=None):\n        ''' Draw an image of both effective PSFs.  Note that the returned PSFs include convolution\n        by the pixel response function, by default, though this can be overriden using the method\n        keyword (e.g., method='fft').\n\n        @param oversample  Integer factor by which to scale output image resolution and size.\n        @returns (im1, im2)  Both effective PSFs corresponding to both component SEDs.\n        '''\n        if icomp is not None:\n            return self.sersictools[icomp].get_PSF_image(oversample, method)\n        else:\n            return [s.get_PSF_image(oversample, method) for s in self.sersictools]\n\n    def set_FWHM(self, gparam, FWHM, oversample=4, icomp=None):\n        ''' Set the galaxy PSF-convolved FWHM.\n        '''\n        if icomp is not None:\n            igparam = self.sersictools[icomp].set_FWHM(indiv_gparam(gparam, icomp), FWHM,\n                                                       oversample)\n            gparam = self.set_indiv_gparam('hlr', icomp, igparam['hlr'].value)\n            return gparam\n        else:\n            def FWHM_resid(scale):\n                g1 = copy.deepcopy(gparam)\n                g1['hlr_1'].value *= scale\n                g1['hlr_2'].value *= scale\n                current_FWHM = self.compute_FWHM(g1, oversample=oversample)\n                return current_FWHM[0] - FWHM\n            scale = newton(FWHM_resid, 1.0, tol=0.01)\n            gparam['hlr_1'].value *= scale\n            gparam['hlr_2'].value *= scale\n            return gparam\n\n    def set_r2(self, gparam, r2, oversample=4):\n        ''' Set the second moment radius sqrt(r^2).\n\n        @param gparam      lmfit.Parameters object describing galaxy.\n        @param r2          Target second moment radius sqrt(r^2)\n        @param oversample  Factor by which to oversample drawn image for r2 computation.\n        @returns           New lmfit.Parameters object.\n        '''\n        def r2_resid(scale):\n            g1 = copy.deepcopy(gparam)\n            g1['hlr_1'].value *= scale\n            g1['hlr_2'].value *= scale\n            current_r2 = self.get_r2(g1, oversample=oversample)\n            return current_r2 - r2\n        scale = newton(r2_resid, 1.0)\n        gparam['hlr_1'].value *= scale\n        gparam['hlr_2'].value *= scale\n        return gparam\n\n    def get_uncvl_r2(self, gparam):\n        ''' Get second moment radius of pre-PSF-convolved profile using polynomial approximation.\n        @gparam   lmfit.Parameters\n        '''\n        return chroma.component_Sersic_r2([gparam['n_1'].value, gparam['n_2'].value],\n                                          [gparam['flux_1'].value, gparam['flux_2'].value],\n                                          [gparam['hlr_1'].value, gparam['hlr_2'].value])\n\n    def set_uncvl_r2(self, gparam, r2):\n        ''' Set the second moment square radius of the pre-PSF-convolved profile using polynomial\n        approximation.\n\n        @param gparam      lmfit.Parameters object describing galaxy.\n        @param r2          Target second moment radius sqrt(r^2)\n        @param oversample  Factor by which to oversample drawn image for computation.\n        @returns           New lmfit.Parameters object.\n        '''\n        gparam1 = copy.deepcopy(gparam)\n        r2_now = self.get_uncvl_r2(gparam)\n        scale = r2 / r2_now\n        gparam1['hlr_1'].value *= scale\n        gparam1['hlr_2'].value *= scale\n        return gparam1\n\n    def get_ring_params(self, gparam, ring_beta, ring_shear):\n        ''' Compute initial guess parameters for given angle around ellipticity ring during a ring\n        test.\n\n        @param gparam      lmfit.Parameters object describing galaxy.\n        @param ring_beta   Angle around ellipticity ring in ring test.\n        @param ring_shear  Shear to apply after rotation as part of ring test. (type=?)\n        @returns           New lmfit.Parameters object.\n        '''\n        gparam1 = copy.deepcopy(gparam)\n\n        rot_phi1 = gparam['phi_1'].value + ring_beta/2.0\n        # complex ellipticity\n        c_ellip1 = gparam['g_1'].value * complex(np.cos(2.0 * rot_phi1), np.sin(2.0 * rot_phi1))\n        c_gamma1 = ring_shear.g1 + 1j * ring_shear.g2\n        # sheared complex ellipticity\n        s_c_ellip1 = chroma.apply_shear(c_ellip1, c_gamma1)\n        s_g1 = abs(s_c_ellip1)\n        s_phi1 = np.angle(s_c_ellip1) / 2.0\n\n        gparam1['x0_1'].value \\\n          = gparam['x0_1'].value * np.cos(ring_beta / 2.0) \\\n          - gparam['y0_1'].value * np.sin(ring_beta / 2.0)\n        gparam1['y0_1'].value \\\n          = gparam['x0_1'].value * np.sin(ring_beta / 2.0) \\\n          + gparam['y0_1'].value * np.cos(ring_beta / 2.0)\n        gparam1['g_1'].value = s_g1\n        gparam1['phi_1'].value = s_phi1\n\n        rot_phi2 = gparam['phi_2'].value + ring_beta/2.0\n        # complex ellipticity\n        c_ellip2 = gparam['g_2'].value * \\\n          complex(np.cos(2.0 * rot_phi2), np.sin(2.0 * rot_phi2))\n        c_gamma2 = ring_shear.g2 + 1j * ring_shear.g2\n        # sheared complex ellipticity\n        s_c_ellip2 = chroma.apply_shear(c_ellip2, c_gamma2)\n        s_g2 = abs(s_c_ellip2)\n        s_phi2 = np.angle(s_c_ellip2) / 2.0\n\n        gparam1['x0_2'].value \\\n          = gparam['x0_2'].value * np.cos(ring_beta / 2.0) \\\n          - gparam['y0_2'].value * np.sin(ring_beta / 2.0)\n        gparam1['y0_2'].value \\\n          = gparam['x0_2'].value * np.sin(ring_beta / 2.0) \\\n          + gparam['y0_2'].value * np.cos(ring_beta / 2.0)\n        gparam1['g_2'].value = s_g2\n        gparam1['phi_2'].value = s_phi2\n\n        return gparam1\n\n    @staticmethod\n    def default_galaxy():\n        '''Setup lmfit.Parameters to represent a double Sersic galaxy.  Pick some default\n        parameter values.  Parameters for each Sersic galaxy component are:\n        x0   - the x-coordinate of the galaxy center\n        y0   - the y-coordinate of the galaxy center\n        n    - the Sersic index.  0.5 gives a Gaussian profile, 1.0 gives an exponential profile,\n               4.0 gives a de Vaucouleurs profile.\n        hlr  - the galaxy half-light-radius.  This is strictly speaking the half light radius of\n               a circularly symmetric profile of the given Sersic index `n`.\n        g    - the magnitude of the galaxy ellipticity given in `g` units as used by GalSim.  In\n               this convention, the major/minor axis ratio is given by: b/a = (1 - g) / (1 + g)\n        phi  - the position angle of the galaxy major axis in radians.  0 indicates that the major\n               axis is along the x-axis.\n        Parameters for the first component will have suffix _1, parameters for the second component\n        will have suffix _2.  By default, the two components are constrained to by concentric and\n        coelliptical.  Similar to the single Sersic case, the total flux and both Sersic indices are\n        fixed by default.\n        '''\n        gparam = lmfit.Parameters()\n        # bulge first\n        gparam.add('x0_1', value=0.0)\n        gparam.add('y0_1', value=0.0)\n        gparam.add('n_1', value=4.0, vary=False)\n        gparam.add('hlr_1', value=0.3, min=0.0)\n        gparam.add('flux_1', value=0.25, min=0.0, max=1.0)\n        gparam.add('g_1', value=0.2, min=0.0, max=1.0)\n        gparam.add('phi_1', value=0.0)\n        # then disk\n        gparam.add('x0_2', expr='x0_1')\n        gparam.add('y0_2', expr='y0_1')\n        gparam.add('n_2', value=1.0, vary=False)\n        gparam.add('hlr_2', value=0.4, min=0.0)\n        gparam.add('flux_2', expr='1.0 - flux_1')\n        gparam.add('g_2', expr='g_1')\n        gparam.add('phi_2', expr='phi_1')\n        #initialize constrained variables\n        dummyfit = lmfit.Minimizer(lambda x: 0, gparam)\n        dummyfit.prepare_fit()\n        return gparam\n", "meta": {"hexsha": "bd7064e576274114972b84bf8a105fb07e2242a1", "size": 30855, "ext": "py", "lang": "Python", "max_stars_repo_path": "chroma/galtool.py", "max_stars_repo_name": "DarkEnergyScienceCollaboration/chroma", "max_stars_repo_head_hexsha": "64fc123a065334b307654f29b3bea52885b46ec8", "max_stars_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-10-22T14:57:27.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-25T08:16:02.000Z", "max_issues_repo_path": "chroma/galtool.py", "max_issues_repo_name": "DarkEnergyScienceCollaboration/chroma", "max_issues_repo_head_hexsha": "64fc123a065334b307654f29b3bea52885b46ec8", "max_issues_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-08-28T14:42:46.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-28T16:08:37.000Z", "max_forks_repo_path": "chroma/galtool.py", "max_forks_repo_name": "DarkEnergyScienceCollaboration/chroma", "max_forks_repo_head_hexsha": "64fc123a065334b307654f29b3bea52885b46ec8", "max_forks_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.8469539376, "max_line_length": 101, "alphanum_fraction": 0.6080700049, "include": true, "reason": "import numpy,from scipy", "num_tokens": 8098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.19856297148517218}}
{"text": "'''\nSoft Actor-Critic version 2\nusing target Q instead of V net: 2 Q net, 2 target Q net, 1 policy net\nadd alpha loss compared with version 1\npaper: https://arxiv.org/pdf/1812.05905.pdf\n'''\n\n\nimport math\nimport random\n\n# import gym\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.distributions import Normal\nfrom torch.utils.tensorboard import SummaryWriter\n\n# from IPython.display import clear_output\n# import matplotlib.pyplot as plt\n# from matplotlib import animation\n# from IPython.display import display\n# from reacher import Reacher\n\nimport argparse\nimport time\n\nimport simulation as sim\nfrom Environment import Environment\n\nimport actuator_array as act\nfrom init import action_dim,state_dim\n\n\nGPU = True\ndevice_idx = 2\nif GPU:\n    device = torch.device(\"cuda:\" + str(device_idx) if torch.cuda.is_available() else \"cpu\")\nelse:\n    device = torch.device(\"cpu\")\nprint(device)\n\n\nparser = argparse.ArgumentParser(description='Train or test neural net motor controller.')\nparser.add_argument('--train', dest='train', action='store_true', default=False)\nparser.add_argument('--test', dest='test', action='store_true', default=False)\n\nargs = parser.parse_args()\n\n\nclass ReplayBuffer:\n    def __init__(self, capacity):\n        self.capacity = capacity\n        self.buffer = []\n        self.position = 0\n    \n    def push(self, state, action, reward, next_state, done):\n        if len(self.buffer) < self.capacity:\n            self.buffer.append(None)\n        self.buffer[self.position] = (state, action, reward, next_state, done)\n        self.position = int((self.position + 1) % self.capacity)  # as a ring buffer\n    \n    def sample(self, batch_size):\n        batch = random.sample(self.buffer, batch_size)\n        state, action, reward, next_state, done = map(np.stack, zip(*batch)) # stack for each element\n        ''' \n        the * serves as unpack: sum(a,b) <=> batch=(a,b), sum(*batch) ;\n        zip: a=[1,2], b=[2,3], zip(a,b) => [(1, 2), (2, 3)] ;\n        the map serves as mapping the function on each list element: map(square, [2,3]) => [4,9] ;\n        np.stack((1,2)) => array([1, 2])\n        '''\n        return state, action, reward, next_state, done\n    \n    def __len__(self):\n        return len(self.buffer)\n\n\nclass SoftQNetwork(nn.Module):\n    def __init__(self, num_inputs, num_actions, hidden_size, init_w=3e-3):\n        super(SoftQNetwork, self).__init__()\n        \n        self.linear1 = nn.Linear(num_inputs + num_actions, hidden_size)\n        self.linear2 = nn.Linear(hidden_size, hidden_size)\n        self.linear3 = nn.Linear(hidden_size, hidden_size)\n        self.linear4 = nn.Linear(hidden_size, 1)\n        \n        self.linear4.weight.data.uniform_(-init_w, init_w)\n        self.linear4.bias.data.uniform_(-init_w, init_w)\n        \n    def forward(self, state, action):\n        x = torch.cat([state, action], 1) # the dim 0 is number of samples\n        x = F.relu(self.linear1(x))\n        x = F.relu(self.linear2(x))\n        x = F.relu(self.linear3(x))\n        x = self.linear4(x)\n        return x\n        \n        \nclass PolicyNetwork(nn.Module):\n    def __init__(self, num_inputs, num_actions, hidden_size, action_range=1., init_w=3e-3, log_std_min=-20, log_std_max=2):\n        super(PolicyNetwork, self).__init__()\n        \n        self.log_std_min = log_std_min\n        self.log_std_max = log_std_max\n        \n        self.linear1 = nn.Linear(num_inputs, hidden_size)\n        self.linear2 = nn.Linear(hidden_size, hidden_size)\n        self.linear3 = nn.Linear(hidden_size, hidden_size)\n        self.linear4 = nn.Linear(hidden_size, hidden_size)\n\n        self.mean_linear = nn.Linear(hidden_size, num_actions)\n        self.mean_linear.weight.data.uniform_(-init_w, init_w)\n        self.mean_linear.bias.data.uniform_(-init_w, init_w)\n        \n        self.log_std_linear = nn.Linear(hidden_size, num_actions)\n        self.log_std_linear.weight.data.uniform_(-init_w, init_w)\n        self.log_std_linear.bias.data.uniform_(-init_w, init_w)\n\n        self.action_range = action_range\n        self.num_actions = num_actions\n\n        \n    def forward(self, state):\n        x = F.relu(self.linear1(state))\n        x = F.relu(self.linear2(x))\n        x = F.relu(self.linear3(x))\n        x = F.relu(self.linear4(x))\n\n        mean    = (self.mean_linear(x))\n        # mean    = F.leaky_relu(self.mean_linear(x))\n        log_std = self.log_std_linear(x)\n        log_std = torch.clamp(log_std, self.log_std_min, self.log_std_max)\n        \n        return mean, log_std\n    \n    def evaluate(self, state, epsilon=1e-6):\n        '''\n        generate sampled action with state as input wrt the policy network;\n        '''\n        mean, log_std = self.forward(state)\n        std = log_std.exp() # no clip in evaluation, clip affects gradients flow\n        \n        normal = Normal(0, 1)\n        z      = normal.sample(mean.shape) \n        action_0 = torch.tanh(mean + std*z.to(device)) # TanhNormal distribution as actions; reparameterization trick\n        action = self.action_range*action_0 + 30                ### 加偏置\n        # The log-likelihood here is for the TanhNorm distribution instead of only Gaussian distribution. \\\n        # The TanhNorm forces the Gaussian with infinite action range to be finite. \\\n        # For the three terms in this log-likelihood estimation: \\\n        # (1). the first term is the log probability of action as in common \\\n        # stochastic Gaussian action policy (without Tanh); \\\n        # (2). the second term is the caused by the Tanh(), \\\n        # as shown in appendix C. Enforcing Action Bounds of https://arxiv.org/pdf/1801.01290.pdf, \\\n        # the epsilon is for preventing the negative cases in log; \\\n        # (3). the third term is caused by the action range I used in this code is not (-1, 1) but with \\\n        # an arbitrary action range, which is slightly different from original paper.\n        log_prob = Normal(mean, std).log_prob(mean+ std*z.to(device)) - torch.log((1. - action_0.pow(2))/2 + epsilon)\n        # both dims of normal.log_prob and -log(1-a**2) are (N,dim_of_action); \n        # the Normal.log_prob outputs the same dim of input features instead of 1 dim probability, \n        # needs sum up across the features dim to get 1 dim prob; or else use Multivariate Normal.\n        log_prob = log_prob.sum(dim=1, keepdim=True)\n        return action, log_prob, z, mean, log_std\n        \n    \n    def get_action(self, state, deterministic):\n        state = torch.FloatTensor(state).unsqueeze(0).to(device)\n        mean, log_std = self.forward(state)\n        std = log_std.exp()\n        \n        normal = Normal(0, 1)\n        z      = normal.sample(mean.shape).to(device)\n        action = self.action_range* torch.tanh(mean + std*z)\n        \n        action = self.action_range* torch.tanh(mean).detach().cpu().numpy()[0] if deterministic else action.detach().cpu().numpy()[0]\n        action = action + 30\n        return action\n\n\n    def sample_action(self,):\n        a=torch.FloatTensor(self.num_actions).uniform_(-1, 1)\n        return self.action_range*a.numpy()\n\n\nclass SAC_Trainer():\n    def __init__(self, replay_buffer, hidden_dim, action_range):\n        self.replay_buffer = replay_buffer\n\n        self.soft_q_net1 = SoftQNetwork(state_dim, action_dim, hidden_dim).to(device)\n        self.soft_q_net2 = SoftQNetwork(state_dim, action_dim, hidden_dim).to(device)\n        self.target_soft_q_net1 = SoftQNetwork(state_dim, action_dim, hidden_dim).to(device)\n        self.target_soft_q_net2 = SoftQNetwork(state_dim, action_dim, hidden_dim).to(device)\n        self.policy_net = PolicyNetwork(state_dim, action_dim, hidden_dim, action_range).to(device)\n        self.log_alpha = torch.zeros(1, dtype=torch.float32, requires_grad=True, device=device)\n        print('Soft Q Network (1,2): ', self.soft_q_net1)\n        print('Policy Network: ', self.policy_net)\n\n        for target_param, param in zip(self.target_soft_q_net1.parameters(), self.soft_q_net1.parameters()):\n            target_param.data.copy_(param.data)\n        for target_param, param in zip(self.target_soft_q_net2.parameters(), self.soft_q_net2.parameters()):\n            target_param.data.copy_(param.data)\n\n        self.soft_q_criterion1 = nn.MSELoss()\n        self.soft_q_criterion2 = nn.MSELoss()\n\n        soft_q_lr = 3e-4\n        policy_lr = 3e-4\n        alpha_lr  = 3e-4\n\n        self.soft_q_optimizer1 = optim.Adam(self.soft_q_net1.parameters(), lr=soft_q_lr)\n        self.soft_q_optimizer2 = optim.Adam(self.soft_q_net2.parameters(), lr=soft_q_lr)\n        self.policy_optimizer = optim.Adam(self.policy_net.parameters(), lr=policy_lr)\n        self.alpha_optimizer = optim.Adam([self.log_alpha], lr=alpha_lr)\n\n    \n    def update(self, batch_size, reward_scale=10., auto_entropy=True, target_entropy=-2, gamma=0.99,soft_tau=1e-2):\n        state, action, reward, next_state, done = self.replay_buffer.sample(batch_size)\n        # print('sample:', state, action,  reward, done)\n\n        state      = torch.FloatTensor(state).to(device)\n        next_state = torch.FloatTensor(next_state).to(device)\n        action     = torch.FloatTensor(action).to(device)\n        reward     = torch.FloatTensor(reward).unsqueeze(1).to(device)  # reward is single value, unsqueeze() to add one dim to be [reward] at the sample dim;\n        done       = torch.FloatTensor(np.float32(done)).unsqueeze(1).to(device)\n\n        action = action / 60\n        reward = reward / 20\n\n        predicted_q_value1 = self.soft_q_net1(state, action)\n        predicted_q_value2 = self.soft_q_net2(state, action)\n        new_action, log_prob, z, mean, log_std = self.policy_net.evaluate(state)\n        new_next_action, next_log_prob, _, _, _ = self.policy_net.evaluate(next_state)\n\n        new_action = new_action / 60\n        new_next_action = new_next_action / 60\n\n        # reward = reward_scale * (reward - reward.mean(dim=0)) / (reward.std(dim=0) + 1e-6) # normalize with batch mean and std; plus a small number to prevent numerical problem\n    # Updating alpha wrt entropy\n        # alpha = 0.0  # trade-off between exploration (max entropy) and exploitation (max Q) \n        if auto_entropy is True:\n            alpha_loss = -(self.log_alpha * (log_prob + target_entropy).detach()).mean()\n            # print('alpha loss: ',alpha_loss)\n            self.alpha_optimizer.zero_grad()\n            alpha_loss.backward()\n            self.alpha_optimizer.step()\n            self.alpha = self.log_alpha.exp()\n        else:\n            self.alpha = 1.\n            alpha_loss = 0\n\n    # Training Q Function\n        target_q_min = torch.min(self.target_soft_q_net1(next_state, new_next_action),self.target_soft_q_net2(next_state, new_next_action)) - self.alpha * next_log_prob\n        target_q_value = reward + (1 - done) * gamma * target_q_min # if done==1, only reward\n        q_value_loss1 = self.soft_q_criterion1(predicted_q_value1, target_q_value.detach())  # detach: no gradients for the variable\n        q_value_loss2 = self.soft_q_criterion2(predicted_q_value2, target_q_value.detach())\n\n\n        self.soft_q_optimizer1.zero_grad()\n        q_value_loss1.backward()\n        self.soft_q_optimizer1.step()\n\n        self.soft_q_optimizer2.zero_grad()\n        q_value_loss2.backward()\n        self.soft_q_optimizer2.step()  \n\n    # Training Policy Function\n        predicted_new_q_value = torch.min(self.soft_q_net1(state, new_action),self.soft_q_net2(state, new_action))\n        policy_loss = (self.alpha * log_prob - predicted_new_q_value).mean()\n\n        self.policy_optimizer.zero_grad()\n        policy_loss.backward()\n        self.policy_optimizer.step()\n        \n        # print('q loss: ', q_value_loss1, q_value_loss2)\n        # print('policy loss: ', policy_loss )\n\n\n    # Soft update the target value net\n        for target_param, param in zip(self.target_soft_q_net1.parameters(), self.soft_q_net1.parameters()):\n            target_param.data.copy_(  # copy data value into target parameters\n                target_param.data * (1.0 - soft_tau) + param.data * soft_tau\n            )\n        for target_param, param in zip(self.target_soft_q_net2.parameters(), self.soft_q_net2.parameters()):\n            target_param.data.copy_(  # copy data value into target parameters\n                target_param.data * (1.0 - soft_tau) + param.data * soft_tau\n            )\n        return predicted_new_q_value.mean().item(),q_value_loss1.item(),q_value_loss2.item(),policy_loss.item(),self.alpha.item()\n\n    def save_model(self, path):\n        torch.save(self.soft_q_net1.state_dict(), path+'_q1')\n        torch.save(self.soft_q_net2.state_dict(), path+'_q2')\n        torch.save(self.policy_net.state_dict(), path+'_policy')\n\n    def load_model(self, path):\n        self.soft_q_net1.load_state_dict(torch.load(path+'_q1'))\n        self.soft_q_net2.load_state_dict(torch.load(path+'_q2'))\n        self.policy_net.load_state_dict(torch.load(path+'_policy'))\n\n        self.soft_q_net1.eval()\n        self.soft_q_net2.eval()\n        self.policy_net.eval()\n\n\n\n\nreplay_buffer_size = 1e6\nreplay_buffer = ReplayBuffer(replay_buffer_size)\n\n# choose env\nENV = ['Reacher', 'Pendulum-v0', 'HalfCheetah-v2'][2]\n\nact_array = act.Actuator_array() \nenv = Environment()\naction_space = [action_dim]\nstate_space = [state_dim]\naction_range = 30\n\n# hyper-parameters for RL training\nmax_episodes  = 5e6\nmax_steps   = 1e3   # Pendulum needs 150 steps per episode to learn well, cannot handle 20\nframe_idx   = 0\nbatch_size  = 64       \nexplore_steps = -1  # for random action sampling in the beginning of training\nupdate_itr = 1\nAUTO_ENTROPY=True\nDETERMINISTIC=False\nhidden_dim = 512\nrewards     = []\nmodel_path = './model/SAC_1_28_3'\n\n\nq_value_episode = np.array([])\nq_value_loss1_episode = np.array([])\nq_value_loss2_episode = np.array([])\npolicy_loss_episode = np.array([])\nalpha_log_episode = np.array([])\nwriter = SummaryWriter('./logs/SAC_1_28_3')\ntmp_avg_reward = 0\n\nsac_trainer=SAC_Trainer(replay_buffer, hidden_dim=hidden_dim, action_range=action_range  )\n\n\nif __name__ == '__main__':\n    if 1:\n        # training loop\n        for eps in range(int(max_episodes)):\n            if ENV == 'Reacher':\n                state = env.reset(SCREEN_SHOT)\n            else:\n                state =  env.reset()\n            episode_reward = 0\n            \n\n            for step in range(int(max_steps)):\n                if frame_idx > explore_steps:\n                    action = sac_trainer.policy_net.get_action(state, deterministic = DETERMINISTIC)\n                else:\n                    action = sac_trainer.policy_net.sample_action()\n                if ENV ==  'Reacher':\n                    next_state, reward, done, _ = env.step(action, SPARSE_REWARD, SCREEN_SHOT)\n                else:\n                    next_state, reward, done = env.step(action)\n                    # env.render()       \n                    \n                done = 0\n                replay_buffer.push(state, action, reward, next_state, done)\n                \n                state = next_state\n                episode_reward += reward\n                frame_idx += 1\n                \n                \n                if len(replay_buffer) > batch_size:\n                    for i in range(update_itr):\n                        q_value,q_value_loss1,q_value_loss2,policy_loss,alpha_log = sac_trainer.update(batch_size, reward_scale=10., auto_entropy=AUTO_ENTROPY, target_entropy=-1.*action_dim)\n                        q_value_episode = np.append(q_value_episode,q_value)\n                        q_value_loss1_episode = np.append(q_value_loss1_episode,q_value_loss1)\n                        q_value_loss2_episode = np.append(q_value_loss2_episode,q_value_loss2)\n                        policy_loss_episode = np.append(policy_loss_episode,policy_loss)\n                        alpha_log_episode = np.append(alpha_log_episode,alpha_log)\n                # if done:\n                #     break\n\n            writer.add_scalar('train/reward', episode_reward, eps)\n            writer.add_scalar('train/q_value', q_value_episode.mean(), eps)\n            writer.add_scalar('loss/critic_1', q_value_loss1_episode.mean(), eps)\n            writer.add_scalar('loss/critic_2', q_value_loss2_episode.mean(), eps)\n            writer.add_scalar('loss/policy', policy_loss_episode.mean(), eps)\n            writer.add_scalar('train/alpha', alpha_log_episode.mean(), eps)\n\n            print('Episode: ', eps, '| Episode Reward: ', episode_reward)\n            # rewards.append(episode_reward)\n\n            if eps % 100 == 0 and eps>0: # 100个episode测试一次如果大于上一次的测试结果，储存下来\n                avg_reward = 0.\n                episodes = 3\n                cal_dist_set = []\n                state = env.reset()\n\n                for _  in range(episodes):\n                    episode_reward = 0\n                    done = False\n                    for i in range(1000):\n                        action = sac_trainer.policy_net.get_action(state, deterministic = DETERMINISTIC)\n\n                        next_state, reward, done = env.step(action)\n                        episode_reward += reward\n                            \n                        state = next_state\n                        if done:                         ## 实际中不可能reset包裹  \n                            # state = env.reset()\n                            pass\n                            \n                        if env.evl_flag == 1:       ## 有包裹过线\n                            cal_dist_set.append(env.cal_dist)\n                            env.evl_flag = 0\n\n                    avg_reward += episode_reward\n                episode_reward = 0\n                avg_reward /= episodes\n                state = env.reset()             ### 每个episode前都要reset,reset后需要加mask        之前忘记在测试完成后加reset了\n                cal_dist_set = np.array(cal_dist_set)\n                dist_success = cal_dist_set[cal_dist_set>=150]\n                dist_fail = cal_dist_set[cal_dist_set<150]\n\n                writer.add_scalar('avg_reward/test', avg_reward, eps)\n                try:\n                    writer.add_histogram('delta_dist_success', dist_success, eps, bins = 500)         # 看delta T是否收敛到设定值\n                except:\n                    pass\n                try:\n                    writer.add_histogram('delta_dist_fail', dist_fail, eps, bins = 500)         # 看delta T是否收敛到设定值\n                except:\n                    pass\n                print(\"----------------------------------------\")\n                print(\"Test Episodes: {}, Avg. Reward: {}, Avg. delta_dist: {}\".format(eps, round(avg_reward, 2),np.mean(cal_dist_set)))\n                print(\"----------------------------------------\")\n                if avg_reward > tmp_avg_reward:     # 变大后保存模型\n                    tmp_avg_reward = avg_reward\n                    sac_trainer.save_model(model_path)          ## 每次test完成后修改mode，及时测试避免错误\n                    print(\"saving model and highest average reward: {}\".format(tmp_avg_reward))\n                \n\n    # if args.test:\n    #     sac_trainer.load_model(model_path)\n    #     for eps in range(10):\n    #         if ENV == 'Reacher':\n    #             state = env.reset(SCREEN_SHOT)\n    #         else:\n    #             state =  env.reset()\n    #         episode_reward = 0\n\n    #         for step in range(max_steps):\n    #             action = sac_trainer.policy_net.get_action(state, deterministic = DETERMINISTIC)\n    #             if ENV ==  'Reacher':\n    #                 next_state, reward, done, _ = env.step(action, SPARSE_REWARD, SCREEN_SHOT)\n    #             else:\n    #                 next_state, reward, done, _ = env.step(action)\n    #                 env.render()   \n\n\n    #             episode_reward += reward\n    #             state=next_state\n\n    #         print('Episode: ', eps, '| Episode Reward: ', episode_reward)\n", "meta": {"hexsha": "fc09eedc72dd52bbb25ff2f4efabaea4368b7216", "size": 19814, "ext": "py", "lang": "Python", "max_stars_repo_path": "baseline/Deepset-SAC/SAC.py", "max_stars_repo_name": "rxlqn/Reinforcement-Learning-Based-Parcel-Singulation-with-Variable-State-Space-Dimension", "max_stars_repo_head_hexsha": "22b0ded9807dbc50d2da9852e80cda55fdc1d04c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-02T10:54:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-07T07:59:33.000Z", "max_issues_repo_path": "S3-SAC/SAC.py", "max_issues_repo_name": "rxlqn/Reinforcement-Learning-Based-Parcel-Singulation-with-Variable-State-Space-Dimension", "max_issues_repo_head_hexsha": "22b0ded9807dbc50d2da9852e80cda55fdc1d04c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-15T06:03:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-15T12:12:47.000Z", "max_forks_repo_path": "baseline/Deepset-SAC/SAC.py", "max_forks_repo_name": "rxlqn/Reinforcement-Learning-Based-Parcel-Singulation-with-Variable-State-Space-Dimension", "max_forks_repo_head_hexsha": "22b0ded9807dbc50d2da9852e80cda55fdc1d04c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.3376068376, "max_line_length": 190, "alphanum_fraction": 0.6165842334, "include": true, "reason": "import numpy", "num_tokens": 4613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3415825128436339, "lm_q1q2_score": 0.19856297042605522}}
{"text": "#!/usr/bin/env python\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport numpy as np\nfrom astropy.io import fits, ascii\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import AutoMinorLocator\nimport smart\n#import splat\n#import splat.model as spmd\n\n#def _constructModelName(teff, logg, metal, en, order, path=None):\n#    \"\"\"\n#    Return the full name of the BT-Settl model.\n#    \"\"\"\n#    if path is None:\n#        path  = '/Users/dinohsu/projects/Models/models/btsettl08/' + \\\n#        'NIRSPEC-O' + str(order) + '-RAW/'\n#    else:\n#        path  = path + '/NIRSPEC-O' + str(order) + '-RAW/'\n#    full_name = path + 'btsettl08_t'+ str(teff) + '_g' + \\\n#    '{0:.2f}'.format(float(logg)) + '_z-' + '{0:.2f}'.format(float(metal)) + \\\n#    '_en' + '{0:.2f}'.format(float(en)) + '_NIRSPEC-O' + str(order) + '-RAW.txt'\n#    \n#    return full_name\n\nclass Model():\n    \"\"\"\n    The Model class reads in the BT-SETTL or PHOENIXACES models. \n    The unit of wavelength is in Angstrom and the unit of the model flux is in erg/s/cm^2/Angstrom.\n    (The models in the libraries have the unit of micron, which differed by 10^4 in flux)\n\n    Parameters\n    ----------\n    1. Read in a BT-Settl model or PHOENIXACES model.\n    teff : float \n          The effective temperature in Kelvins.\n    logg : float\n          The log(gravity), given in two decimal digits. \n          Ex: logg=4.50\n    metal  : float\n           The metalicity, given in two decimal digits. \n           Ex. metal=0.00\n    en   : float\n           alpha enhancement. given in two decimal digits. \n           Ex. en=0.00\n\n    modelset: str\n            available models are \n            NIRSPEC: 'btsettl08', 'SONORA_2018'\n            APOGEE: 'btsettl08', 'marcs-apogee-dr15', 'phoenix-aces-agss-cond-2011', 'phoenix-btsettl-cifist2011-2015'\n\n    order: int\n           This is only for the Keck/NIRSPEC. The order of the model, given from 29 to 80\n\n    path : str\n           The path to the model\n\n    2. Creat a model instance with given wavelengths and fluxes\n    flux : astropy.table.column.Column\n           The input flux.\n    wave : astropy.table.column.Column\n           The input wavelength.\n\n    Returns\n    -------\n    flux : astropy.table.column.Column\n           The flux retrieved from the model. Our default unit is erg/s/cm^2/Angstrom.\n    wave : astropy.table.column.Column\n           The wavelength retrieved from the model. Our default unit is Angstrom.\n\n    Examples\n    --------\n    >>> import smart\n    >>> model = smart.Model(teff=2300, logg=5.5, order=33, path='/path/to/models')\n    >>> model.plot()\n    \"\"\"\n    def __init__(self, **kwargs):\n        self.path  = kwargs.get('path')\n        self.order = kwargs.get('order')\n        self.instrument = kwargs.get('instrument','nirspec')\n\n        if self.order != None and self.instrument == 'nirspec':\n            self.teff     = kwargs.get('teff', 2500)\n            self.logg     = kwargs.get('logg', 5.00)\n            self.metal    = kwargs.get('metal', 0.00)\n            self.en       = kwargs.get('en', 0.00)\n            self.modelset = kwargs.get('modelset', 'btsettl08')\n\n            wave, flux = smart.forward_model.InterpolateModel.InterpModel(self.teff, self.logg, self.metal, self.en,\n                                                                          modelset=self.modelset, order=self.order, instrument=self.instrument)\n            #elif self.metal != 0.0:\n            #    wave, flux = smart.forward_model.InterpolateModel.InterpModel(Teff=self.teff, Logg=self.logg, Metal=self.metal,\n            #    modelset=self.modelset, order=self.order, instrument=self.instrument)\n            \n            if self.modelset == 'btsettl08':\n                self.wave = wave * 10000 #convert to Angstrom\n                self.flux = flux / 10000 #convert from erg/s/cm^2/micron to erg/s/cm^2/Angstrom\n            else:\n                self.wave = wave\n                self.flux = flux\n\n        elif self.instrument == 'apogee':\n            self.teff     = kwargs.get('teff', 2500)\n            self.logg     = kwargs.get('logg', 5.00)\n            self.metal    = kwargs.get('metal', 0.00)\n            self.en       = kwargs.get('en', 0.00)\n            self.modelset = kwargs.get('modelset', 'btsettl08')\n\n            #wave, flux = smart.forward_model.InterpolateModel.InterpModel(self.teff, self.logg,\n            #    modelset=self.modelset, order=self.order, instrument=self.instrument)\n\n            wave, flux = smart.forward_model.InterpolateModel.InterpModel(self.teff, self.logg, self.metal, self.en,\n                                                                          modelset=self.modelset, order=self.order, instrument=self.instrument)\n\n            if self.modelset == 'btsettl08':\n                self.wave = wave * 10000 #convert to Angstrom\n                self.flux = flux / 10000 #convert from erg/s/cm^2/micron to erg/s/cm^2/Angstrom \n\n            else:\n                self.wave = wave # Angstrom\n                self.flux = flux # erg/s/cm^2/Angstrom\n\n        else:\n            self.wave   = kwargs.get('wave', [])\n            self.flux   = kwargs.get('flux', [])\n        \n\n    def plot(self, **kwargs):\n        \"\"\"\n        Plot the model spectrum.\n        \"\"\"\n        if self.order != None:\n            name = str(_constructModelName(self.teff, self.logg, \n                self.metal, self.en, self.order, self.path))\n            output = kwargs.get('output', str(name) + '.pdf')\n            ylim = kwargs.get('yrange', [min(self.flux)-.2, max(self.flux)+.2])\n            title  = kwargs.get('title')\n            save   = kwargs.get('save', False)\n        \n            plt.figure(figsize=(16,6))\n            plt.plot(self.wave, self.flux, color='k', \n                alpha=.8, linewidth=1, label=name)\n            plt.legend(loc='upper right', fontsize=12)\n            plt.ylim(ylim)    \n    \n            minor_locator = AutoMinorLocator(5)\n            #ax.xaxis.set_minor_locator(minor_locator)\n            # plt.grid(which='minor') \n    \n            plt.xlabel(r'$\\lambda$ [$\\mathring{A}$]', fontsize=18)\n            plt.ylabel(r'$Flux$', fontsize=18)\n            #plt.ylabel(r'$F_{\\lambda}$ [$erg/s \\cdot cm^{2}$]', fontsize=18)\n            if title != None:\n                plt.title(title, fontsize=20)\n            plt.tight_layout()\n\n            if save == True:\n                plt.savefig(output)\n            plt.show()\n            plt.close()\n\n        else:\n            output = kwargs.get('output'+ '.pdf')\n            ylim   = kwargs.get('yrange', [min(self.flux)-.2, max(self.flux)+.2])\n            title  = kwargs.get('title')\n            save   = kwargs.get('save', False)\n        \n            plt.figure(figsize=(16,6))\n            plt.plot(self.wave, self.flux, color='k', alpha=.8, linewidth=1)\n            plt.legend(loc='upper right', fontsize=12)\n            plt.ylim(ylim)\n    \n            minor_locator = AutoMinorLocator(5)\n            #ax.xaxis.set_minor_locator(minor_locator)\n            # plt.grid(which='minor') \n    \n            plt.xlabel(r'$\\lambda$ [$\\mathring{A}$]', fontsize=18)\n            plt.ylabel(r'$Flux$', fontsize=18)\n            #plt.ylabel(r'$F_{\\lambda}$ [$erg/s \\cdot cm^{2}$]', fontsize=18)\n            if title != None:\n                plt.title(title, fontsize=20)\n            plt.tight_layout()\n\n            if save == True:\n                plt.savefig(output)\n            plt.show()\n            plt.close()\n\n\n", "meta": {"hexsha": "9d4e9e5be670b11d464ac4a610308ada1e6f72ae", "size": 7425, "ext": "py", "lang": "Python", "max_stars_repo_path": "smart/forward_model/classModel.py", "max_stars_repo_name": "Lingfeng-Wei/smart", "max_stars_repo_head_hexsha": "2316e50bfb6f050d5dcdd0ee1e5eab6831e8a669", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-01-21T09:09:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T18:24:02.000Z", "max_issues_repo_path": "smart/forward_model/classModel.py", "max_issues_repo_name": "Lingfeng-Wei/smart", "max_issues_repo_head_hexsha": "2316e50bfb6f050d5dcdd0ee1e5eab6831e8a669", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-02-07T19:03:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T01:21:56.000Z", "max_forks_repo_path": "smart/forward_model/classModel.py", "max_forks_repo_name": "Lingfeng-Wei/smart", "max_forks_repo_head_hexsha": "2316e50bfb6f050d5dcdd0ee1e5eab6831e8a669", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-22T21:54:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-11T05:16:53.000Z", "avg_line_length": 38.8743455497, "max_line_length": 143, "alphanum_fraction": 0.5511111111, "include": true, "reason": "import numpy,from astropy", "num_tokens": 1880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.1985629675888961}}
{"text": "\"\"\"\nThe crux of ``coronagraph`` noise modeling is to determine the photon count rate\nincident upon the detector due to both the target planet and an assortment of\ndifferent telescope, instrumental, and astrophysical noise sources.\nThe following classes and functions serve as your interface to the photon count\nrate calculations. The core function for these calculations is\n:func:`count_rates`, but it may be accessed using the :class:`CoronagraphNoise`\nobject.\n\"\"\"\n\nfrom __future__ import (division as _, print_function as _,\n                absolute_import as _, unicode_literals as _)\n\n# Import dependent modules\nimport numpy as np\nimport sys, os\nimport matplotlib.pyplot as plt\n\nfrom .degrade_spec import downbin_spec\nfrom .convolve_spec import convolve_spec\nfrom .noise_routines import Fstar, Fplan, FpFs, cplan, czodi, cezodi, cspeck, \\\n    cdark, cread, ctherm, ccic, f_airy, ctherm_earth, construct_lam, \\\n    set_quantum_efficiency, set_read_noise, set_dark_current, set_lenslet, \\\n    set_throughput, set_atmos_throughput, \\\n    exptime_element, get_sky_flux\nfrom .teleplanstar import Telescope, Planet, Star\n\n__all__ = ['count_rates', 'CoronagraphNoise']\n\nclass CoronagraphNoise(object):\n    \"\"\"\n    The primary interface for ``coronagraph`` noise modeling. This object wraps\n    around the functionality of :func:`count_rates`. Simply instantiate a\n    `CoronagraphNoise` object by passing it :class:`telescope`, :class:`planet`,\n    and :class:`star` objects, and then call\n    :func:`CoronagraphNoise.run_count_rates` to perform the photon count rate\n    calculation.\n\n    Parameters\n    ----------\n    telescope : Telescope\n        Initialized object containing ``Telescope`` parameters\n    planet : Planet\n        Initialized object containing ``Planet`` parameters\n    star : Star\n        Initialized object containing ``Star`` parameters\n    texp : float\n        Exposure time for which to generate synthetic data [hours]\n    wantsnr : float, optional\n        Desired signal-to-noise ratio in each pixel\n    FIX_OWA : bool, optional\n        Set to fix OWA at ``OWA*lammin/D``, as would occur if lenslet array is\n        limiting the OWA\n    COMPUTE_LAM : bool, optional\n        Set to compute lo-res wavelength grid, otherwise the grid input as\n        variable ``lam`` is used\n    SILENT : bool, optional\n        Set to suppress print statements\n    NIR : bool, optional\n        Re-adjusts pixel size in NIR, as would occur if a second instrument\n        was designed to handle the NIR\n    THERMAL : bool, optional\n        Set to compute thermal photon counts due to telescope temperature\n    GROUND : bool, optional\n        Set to simulate ground-based observations through atmosphere\n    vod : bool, optional\n        \"Valley of Death\" red QE parameterization from Robinson et al. (2016)\n    set_fpa : float, optional\n        Specify the fraction of planetary signal in Airy pattern, default will\n        calculate it from the photometric aperture size `X`\n    roll_maneuver : bool, optional\n        This assumes an extra factor of 2 hit to the background noise due to a\n        telescope roll maneuver needed to subtract out the background. See\n        Brown (2005) for more details.\n\n    Note\n    ----\n    The results of the coronagraph noise calculation will become available as\n    attributes of the :class:`CoronagraphNoise` object after\n    :func:`CoronagraphNoise.run_count_rates` is called.\n    \"\"\"\n    def __init__(self, telescope = Telescope(), planet = Planet(),\n                 star = Star(), texp = 10.0, wantsnr=10.0, FIX_OWA = False,\n                 COMPUTE_LAM = False, SILENT = False, NIR = False,\n                 THERMAL = True, GROUND = False, vod=False, set_fpa=None,\n                 roll_maneuver = True):\n        \"\"\"\n        \"\"\"\n        self.telescope = telescope\n        self.planet = planet\n        self.star = star\n        self.texp = texp\n        self.wantsnr = wantsnr\n        self.FIX_OWA = FIX_OWA\n        self.COMOUTE_LAM = COMPUTE_LAM\n        self.SILENT = SILENT\n        self.NIR = NIR\n        self.THERMAL = THERMAL\n        self.GROUND = GROUND\n        self.vod = vod\n        self.set_fpa = set_fpa\n        self.roll_maneuver = roll_maneuver\n\n        self._computed = False\n\n        return\n\n    def run_count_rates(self, Ahr, lamhr, solhr):\n        \"\"\"\n        Calculate the photon count rates and signal to noise on a\n        coronagraph observation given a wavelength-dependent planetary\n        geometric albedo and stellar flux density.\n\n        Parameters\n        ----------\n        Ahr : array\n            High-res, wavelength-dependent planetary geometric albedo\n        lamhr : array\n            High-res wavelength grid  [um]\n        solhr : array\n            High-res TOA solar spectrum [W/m**2/um]\n\n\n        Calling ``run_count_rates()`` creates the following attributes for\n        the ``CoronagraphNoise`` instance:\n\n        Attributes\n        ----------\n        Ahr : array\n            High-res, wavelength-dependent planetary geometric albedo\n        lamhr : array\n            High-res wavelength grid  [um]\n        solhr : array\n            High-res TOA solar spectrum [W/m**2/um]\n        lam : array\n            Observed wavelength grid [$\\mu$m]\n        dlam : array\n            Observed wavelength grid widths [$\\mu$m]\n        A : array\n            Planetary geometric albedo at observed resolution\n        Cratio : array\n            Planet-to-star flux contrast ratio\n        cp : array\n            Planetary photon count rate [photons/s]\n        csp : array\n            Speckle count rate [photons/s]\n        cz : array\n            Zodi photon count rate [photons/s]\n        cez : array\n            Exo-zodi photon count rate [photons/s]\n        cth : array\n            Thermal photon count rate [photons/s]\n        cD : array\n            Dark current photon count rate [photons/s]\n        cR : array\n            Read noise photon count rate [photons/s]\n        cc : array\n            Clock induced charge photon count rate [photons/s]\n        cb : array\n            Total background photon noise count rate [photons/s]\n        DtSNR : array\n            Integration time to ``wantsnr`` [hours]\n        SNRt : array\n            S/N in a ``texp`` hour exposure\n        Aobs : array\n            Observed albedo with noise\n        Asig : array\n            Observed uncertainties on albedo\n        Cobs : array\n            Observed Fp/Fs with noise\n        Csig : array\n            Observed uncertainties on Fp/Fs\n        \"\"\"\n\n        # Save input arrays\n        self.Ahr = Ahr\n        self.lamhr = lamhr\n        self.solhr = solhr\n\n        # Aperture logic\n        accepted_circular = [\"circular\", \"circ\", \"c\"]\n        accepted_square = [\"square\", \"s\"]\n        if self.telescope.aperture.lower() in accepted_circular:\n            CIRC = True\n        elif self.telescope.aperture.lower() in accepted_square:\n            CIRC = False\n        else:\n            assert False, \"telescope.aperture is invalid\"\n\n        # Call count_rates\n        lam, dlam, A, q, Cratio, cp, csp, cz, cez, cD, cR, cth, cc, DtSNR = \\\n            count_rates(Ahr, lamhr, solhr,\n                        alpha = self.planet.alpha,\n                        Phi = self.planet.Phi,\n                        Rp = self.planet.Rp,\n                        Teff = self.star.Teff,\n                        Rs = self.star.Rs,\n                        r = self.planet.a,\n                        d = self.planet.distance,\n                        Nez = self.planet.Nez,\n                        mode = self.telescope.mode,\n                        filter_wheel = self.telescope.filter_wheel,\n                        lammin = self.telescope.lammin,\n                        lammax = self.telescope.lammax,\n                        Res    = self.telescope.resolution,\n                        diam   = self.telescope.diameter,\n                        Tput   = self.telescope.throughput,\n                        C      = self.telescope.contrast,\n                        IWA    = self.telescope.IWA,\n                        OWA    = self.telescope.OWA,\n                        Tsys   = self.telescope.Tsys,\n                        Tdet   = self.telescope.Tdet,\n                        emis   = self.telescope.emissivity,\n                        De     = self.telescope.darkcurrent,\n                        DNHpix = self.telescope.DNHpix,\n                        Re     = self.telescope.readnoise,\n                        Rc     = self.telescope.Rc,\n                        Dtmax  = self.telescope.Dtmax,\n                        X      = self.telescope.X,\n                        qe     = self.telescope.qe,\n                        MzV    = self.planet.MzV,\n                        MezV   = self.planet.MezV,\n                        A_collect = self.telescope.A_collect,\n                        diam_circumscribed = self.telescope.diam_circumscribed,\n                        diam_inscribed = self.telescope.diam_inscribed,\n                        lam    = self.telescope.lam,\n                        dlam   = self.telescope.dlam,\n                        Tput_lam = self.telescope.Tput_lam,\n                        qe_lam = self.telescope.qe_lam,\n                        lammin_lenslet = self.telescope.lammin_lenslet,\n                        NIR    = self.NIR,\n                        GROUND = self.GROUND,\n                        THERMAL = self.THERMAL,\n                        CIRC = CIRC,\n                        roll_maneuver = self.roll_maneuver,\n                        SILENT = self.SILENT,\n                        wantsnr = self.wantsnr\n                    )\n\n        # Save output arrays\n        self.lam     = lam\n        self.dlam    = dlam\n        self.A       = A\n        self.Cratio  = Cratio\n        self.cp      = cp\n        self.csp     = csp\n        self.cz      = cz\n        self.cez     = cez\n        self.cD      = cD\n        self.cR      = cR\n        self.cth     = cth\n        self.cc      = cc\n        self.cb      = cz + cez + csp + cD + cR + cth + cc\n        self.DtSNR   = DtSNR\n\n        # Flip the switch\n        self._computed = True\n\n        # Make an initial set of fake data\n        self.make_fake_data()\n\n        return\n\n    def make_fake_data(self, texp = None):\n        \"\"\"\n        Make a fake/synthetic dataset by sampling from a Gaussian.\n\n        Parameters\n        ----------\n        texp : float, optional\n            Exposure time [hours]. If not provided, the ``CoronagraphNoise.texp``\n            will be used by default.\n\n\n        Calling ``make_fake_data()`` creates the following attributes for\n        the ``CoronagraphNoise`` instance:\n\n        Attributes\n        ----------\n        SNRt : array\n            S/N in a ``texp`` hour exposure\n        Aobs : array\n            Observed albedo with noise\n        Asig : array\n            Observed uncertainties on albedo\n        Cobs : array\n            Observed Fp/Fs with noise\n        Csig : array\n            Observed uncertainties on Fp/Fs\n        \"\"\"\n\n        # Ensure that simulation has been run\n        assert self._computed\n\n        # Allow new exposure time\n        if texp is not None:\n            self.texp = texp\n\n        # Convert exposure time to seconds\n        Dt = 3600. * self.texp\n\n        # Use telescope roll maneuver\n        if self.roll_maneuver:\n            # assuming background subtraction (the \"2\")\n            roll_factor = 2.0\n        else:\n            # standard background noise\n            roll_factor = 1.0\n\n        # Calculate signal-to-noise\n        SNRt  = self.cp * Dt / np.sqrt((self.cp + roll_factor*self.cb) * Dt)\n\n        # Calculate 1-sigma errors on contrast ratio and albedo\n        Csig = self.Cratio/SNRt\n        Asig = self.A/SNRt\n\n        # Calculate Gaussian noise\n        gaus = np.random.randn(len(self.Cratio))\n\n        # Add gaussian noise to observed data\n        Cobs = self.Cratio + Csig * gaus\n        Aobs = self.A + Asig * gaus\n\n        # Save attributes\n        self.SNRt = SNRt\n        self.Asig = Asig\n        self.Aobs = Aobs\n        self.Csig = Csig\n        self.Cobs = Cobs\n\n        return\n\n    def plot_spectrum(self, SNR_threshold = 1.0, Nsig = 6.0, ax0 = None,\n                      err_kws = {\"fmt\" : \".\", \"c\" : \"k\", \"alpha\" : 1},\n                      plot_kws = {\"lw\" : 1.0, \"c\" : \"C4\", \"alpha\" : 0.5},\n                      draw_box = True):\n        \"\"\"\n        Plot noised direct-imaging spectrum.\n\n        Parameters\n        ----------\n        SNR_threshold : float\n            Threshold SNR below which do not plot\n        Nsig : float\n            Number of standard deviations about median observed points to set\n            yaxis limits\n        ax0 : `matplotlib.axes`\n            Optional axis to provide\n        err_kws : dic\n            Keyword arguments for `errorbar`\n        plot_kws : dic\n            Keyword arguments for `plot`\n        draw_box : bool\n            Draw important quantities in a box?\n\n        Returns\n        -------\n        fig : `matplotlib.figure.Figure`\n            Returns a figure if `ax0` is `None`\n        ax : `matplotlib.axes`\n            Returns an axis if `ax0` is `None`\n\n        Note\n        ----\n        Only returns `fig` and `ax` is ``ax0 is None``\n        \"\"\"\n\n        m = [self.SNRt > SNR_threshold]\n\n        scale = 1\n\n        if ax0 is None:\n            # Create Plot\n            fig, ax = plt.subplots(figsize = (10,8))\n            ax.set_xlabel(r\"Wavelength [$\\mu$m]\")\n            ax.set_ylabel(\"Geometic Albedo\")\n        else:\n            ax = ax0\n\n        #ax.plot(lam, scale*RpRs2, alpha = 1.0, ls = \"steps-mid\")\n        ax.errorbar(self.lam[m], scale*self.Aobs[m], yerr=scale*self.Asig[m], zorder = 100, **err_kws)\n        #ax.set_yscale(\"log\")\n\n        # Set ylim\n        mederr = scale*np.median(self.Asig)\n        medy = scale*np.median(self.Aobs)\n        ax.set_ylim([medy - Nsig*mederr, medy + Nsig*mederr])\n\n        ylims = ax.get_ylim()\n        xlims = ax.get_xlim()\n\n        ax.plot(self.lamhr, scale*self.Ahr, **plot_kws)\n\n        ax.set_ylim(ylims)\n        ax.set_xlim(xlims)\n\n\n        if draw_box:\n            # Set string for plot text\n            if self.texp > 2.0:\n                timestr = \"{:.0f}\".format(self.texp)+' hours'\n            else:\n                timestr = \"{:.0f}\".format(self.texp*60)+' mins'\n            plot_text = r'Distance = '+\"{:.1f}\".format(self.planet.distance)+' pc'+\\\n            '\\n Integration time = '+timestr\n            ax.text(0.02, 0.975, plot_text, transform=ax.transAxes, ha = \"left\", va = \"top\",\n                    bbox=dict(boxstyle=\"square\", fc=\"w\", ec=\"k\", alpha=0.9), zorder=101)\n\n        #ax.legend()\n\n        if ax0 is None:\n            return fig, ax\n        else:\n            return\n\n    def plot_SNR(self, ax0 = None, plot_kws = {\"ls\" : \"steps-mid\"}):\n        \"\"\"\n        Plot the S/N on the planet as a function of wavelength.\n\n        Parameters\n        ----------\n        ax0 : `matplotlib.axes`\n            Optional axis to provide\n        plot_kws : dic\n            Keyword arguments for `plot`\n\n        Returns\n        -------\n        fig : `matplotlib.figure.Figure`\n            Returns a figure if `ax0` is `None`\n        ax : `matplotlib.axes`\n            Returns an axis if `ax0` is `None`\n\n        Note\n        ----\n        Only returns `fig` and `ax` is ``ax0 is None``\n        \"\"\"\n        if ax0 is None:\n            # Create Plot\n            fig, ax = plt.subplots(figsize = (10,8))\n        else:\n            ax = ax0\n\n        ax.plot(self.lam, self.SNRt, **plot_kws)\n        #ax.set_yscale(\"log\")\n        ax.set_xlabel(r\"Wavelength [$\\mu$m]\")\n        ax.set_ylabel(\"S/N on Planet Spectrum in %.1f hrs\" %self.texp)\n        #ax.legend()\n\n        if ax0 is None:\n            return fig, ax\n        else:\n            return\n\n    def plot_time_to_wantsnr(self, ax0 = None, plot_kws = {\"ls\" : \"steps-mid\", \"alpha\" : 1.0}):\n        \"\"\"\n        Plot the exposure time to get a SNR on the planet spectrum.\n\n        Parameters\n        ----------\n        ax0 : `matplotlib.axes`\n            Optional axis to provide\n        plot_kws : dic\n            Keyword arguments for `plot`\n\n        Returns\n        -------\n        fig : `matplotlib.figure.Figure`\n            Returns a figure if `ax0` is `None`\n        ax : `matplotlib.axes`\n            Returns an axis if `ax0` is `None`\n\n        Note\n        ----\n        Only returns `fig` and `ax` is ``ax0 is None``\n        \"\"\"\n\n        if ax0 is None:\n            # Create Plot\n            fig, ax = plt.subplots(figsize = (10,8))\n            ax.set_xlabel(r\"Wavelength [$\\mu$m]\")\n            ax.set_ylabel(\"Hours to S/N = %i on Planet Spectrum\" %self.wantsnr)\n            ax.set_yscale(\"log\")\n        else:\n            ax = ax0\n\n        ax.plot(self.lam, self.DtSNR, **plot_kws)\n\n        if ax0 is None:\n            return fig, ax\n        else:\n            return\n\ndef count_rates(Ahr, lamhr, solhr,\n                alpha, Phi, Rp, Teff, Rs, r, d, Nez,\n                mode   = \"IFS\",\n                filter_wheel = None,\n                lammin = 0.4,\n                lammax = 2.5,\n                Res    = 70.0,\n                diam   = 10.0,\n                Tput   = 0.20,\n                C      = 1e-10,\n                IWA    = 3.0,\n                OWA    = 20.0,\n                Tsys   = 260.0,\n                Tdet   = 50.0,\n                emis   = 0.9,\n                De     = 1e-4,\n                DNHpix = 3.0,\n                Re     = 0.1,\n                Rc     = 0.0,\n                Dtmax  = 1.0,\n                X      = 1.5,\n                qe     = 0.9,\n                MzV    = 23.0,\n                MezV   = 22.0,\n                A_collect = None,\n                diam_circumscribed = None,\n                diam_inscribed = None,\n                lam    = None,\n                dlam   = None,\n                Tput_lam = None,\n                qe_lam = None,\n                lammin_lenslet = None,\n                wantsnr=10.0, FIX_OWA = False, COMPUTE_LAM = False,\n                SILENT = False, NIR = False, THERMAL = False, GROUND = False,\n                vod=False, set_fpa=None, CIRC = True, roll_maneuver = True):\n    \"\"\"\n    Runs coronagraph model (Robinson et al., 2016) to calculate planet and noise\n    photon count rates for specified telescope and system parameters.\n\n    Parameters\n    ----------\n    Ahr : array\n        High-res, wavelength-dependent planetary geometric albedo\n    lamhr : array\n        High-res wavelength grid  [um]\n    solhr : array\n        High-res TOA solar spectrum [W/m**2/um]\n    alpha : float\n        Planet phase angle [deg]\n    Phi : float\n        Planet phase function\n    Rp : float\n        Planet radius [R_earth]\n    Teff : float\n        Stellar effective temperature [K]\n    Rs : float\n        Stellar radius [R_sun]\n    r : float\n        Planet semi-major axis [AU]\n    d : float\n        Distance to observed star-planet system [pc]\n    Nez : float\n        Number of exozodis in exoplanetary disk\n    mode : str, optional\n        Telescope observing mode: \"IFS\" or \"Imaging\"\n    filter_wheel : Wheel, optional\n        Wheel object containing imaging filters\n    lammin : float, optional\n        Minimum wavelength [um]\n    lammax : float, optional\n        Maximum wavelength [um]\n    Res : float, optional\n        Instrument spectral resolution (``lam / dlam``)\n    diam : float, optional\n        Telescope diameter [m]\n    Tput : float, optional\n        Telescope and instrument throughput\n    C : float, optional\n        Coronagraph design contrast\n    IWA : float, optional\n        Coronagraph Inner Working Angle (``lam / diam``)\n    OWA : float, optional\n        Coronagraph Outer Working Angle (``lam / diam``)\n    Tsys  : float, optional\n        Telescope mirror temperature [K]\n    Tdet  : float, optional\n        Telescope detector temperature [K]\n    emis : float, optional\n        Effective emissivity for the observing system (of order unity)\n    De : float, optional\n        Dark current [counts/s]\n    DNHpix : float, optional\n        Number of horizontal/spatial pixels for dispersed spectrum\n    Re : float, optional\n        Read noise counts per pixel\n    Rc : float, optional\n        Clock induced charge [counts/pixel/photon]\n    Dtmax : float, optional\n        Detector maximum exposure time [hours]\n    X : float, optional\n        Width of photometric aperture (``lam / diam``)\n    qe : float, optional\n        Detector quantum efficiency\n    MzV : float, optional\n        V-band zodiacal light surface brightness [mag/arcsec**2]\n    MezV : float, optional\n        V-band exozodiacal light surface brightness [mag/arcsec**2]\n    A_collect : float, optional\n        Mirror collecting area (m**2) (uses :math:`\\pi(D/2)^2` by default)\n    diam_circumscribed : float, optional\n        Circumscribed telescope diameter [m] used for IWA and OWA (uses `diam`\n        if `None` provided)\n    diam_inscribed : float, optional\n        Inscribed telescope diameter [m] used for lenslet calculations\n        (uses `diam` if `None` provided)\n    lam : array-like, optional\n        Wavelength grid for spectrograph [microns] (uses ``lammin``, ``lammax``,\n        and ``resolution`` to determine if ``None`` provided)\n    dlam : array-like, optional\n        Wavelength grid `widths` for spectrograph [microns] (uses ``lammin``, ``lammax``,\n        and ``resolution`` to determine if ``None`` provided)\n    Tput_lam : tuple of arrays\n        Wavelength-dependent throughput e.g. ``(wls, tputs)``\n    qe_lam : tuple of arrays\n        Wavelength-dependent throughput e.g. ``(wls, qe)``\n    lammin_lenslet : float, optional\n        Minimum wavelength to use for lenslet calculation (default is ``lammin``)\n    wantsnr : float, optional\n        Desired signal-to-noise ratio in each pixel\n    FIX_OWA : bool, optional\n        Set to fix OWA at ``OWA*lammin/D``, as would occur if lenslet array is\n        limiting the OWA\n    COMPUTE_LAM : bool, optional\n        Set to compute lo-res wavelength grid, otherwise the grid input as\n        variable ``lam`` is used\n    SILENT : bool, optional\n        Set to suppress print statements\n    NIR : bool, optional\n        Re-adjusts pixel size in NIR, as would occur if a second instrument\n        was designed to handle the NIR\n    THERMAL : bool, optional\n        Set to compute thermal photon counts due to telescope temperature\n    GROUND : bool, optional\n        Set to simulate ground-based observations through atmosphere\n    vod : bool, optional\n        \"Valley of Death\" red QE parameterization from Robinson et al. (2016)\n    set_fpa : float, optional\n        Specify the fraction of planetary signal in Airy pattern, default will\n        calculate it from the photometric aperture size `X`\n    CIRC : bool, optional\n        Set to use a circular aperture\n    roll_maneuver : bool, optional\n        This assumes an extra factor of 2 hit to the background noise due to a\n        telescope roll maneuver needed to subtract out the background. See\n        Brown (2005) for more details.\n\n    Returns\n    -------\n    lam : ndarray\n        Observational wavelength grid [um]\n    dlam : ndarray\n        Observational spectral element width [um]\n    A : ndarray\n        Planetary geometric albedo on lam grid\n    q : ndarray\n        Quantum efficiency grid\n    Cratio : ndarray\n        Planet-star contrast ratio\n    cp : ndarray\n        Planetary photon count rate on detector [1/s]\n    csp : ndarray\n        Speckle photon count rate on detector [1/s]\n    cz : ndarray\n        Zodiacal photon count rate on detector [1/s]\n    cez : ndarray\n        Exozodiacal photon count rate on detector [1/s]\n    cD : ndarray\n        Dark current photon count rate on detector [1/s]\n    cR : ndarray\n        Read noise photon count rate on detector [1/s]\n    cth : ndarray\n        Instrument thermal photon count rate on detector [1/s]\n    cc : ndarray\n        Clock induced charge photon count rate [1/s]\n    DtSNR : ndarray\n        Exposure time required to get desired S/N (wantsnr) [hours]\n    \"\"\"\n\n    convolution_function = downbin_spec\n    #convolution_function = degrade_spec\n\n    # Define a diameter for IWA (circumscribed),\n    # collecting area, and lenslet (inscribed)\n    if diam_inscribed is None:\n        # Defaults to diam\n        diam_inscribed = diam\n    if A_collect is None:\n        # Defaults to diam\n        diam_collect = diam\n    else:\n        # Calculated from provided collecting area\n        diam_collect = 2. * (A_collect / np.pi)**0.5\n    if diam_circumscribed is None:\n        # Defaults to diam\n        diam_circumscribed = diam\n\n    # Configure for different telescope observing modes\n    if mode == 'Imaging':\n        filters = filter_wheel\n        IMAGE = True\n        COMPUTE_LAM = False\n        # sorted filter dict by bandcenters\n        tdict = sorted(filters.__dict__.items(), key=lambda x: x[1].bandcenter)\n        # Construct array of wavelengths\n        lam = np.array([x[1].bandcenter for x in tdict])\n        # Construct array of wavelength bin widths (FWHM)\n        dlam = np.array([x[1].FWHM for x in tdict])\n        Nlam = len(lam)\n    elif mode == 'IFS':\n        IMAGE = False\n        COMPUTE_LAM = True\n    else:\n        print(\"Invalid telescope observing mode. Select 'IFS', or 'Imaging'.\")\n        sys.exit()\n\n    # fraction of planetary signal in Airy pattern\n    if set_fpa is None:\n        fpa = f_airy(X)\n    else:\n        fpa = set_fpa * f_airy(X)\n\n    # Set wavelength grid\n    # GENERALIZE THIS:\n    if COMPUTE_LAM:\n        if (lam is None) or (dlam is None):\n            lam, dlam = construct_lam(lammin, lammax, Res)\n    elif IMAGE:\n        pass\n    else:\n        # Throw error\n        print(\"Error in make_noise: Not computing wavelength grid or providing filters!\")\n        return None\n\n    # Set Quantum Efficiency\n    q = set_quantum_efficiency(lam, qe, NIR=NIR, vod=vod)\n\n    # Set Dark current and Read noise\n    De = set_dark_current(lam, De, lammax, Tdet, NIR=NIR)\n    Re = set_read_noise(lam, Re, NIR=NIR)\n\n    # Set Angular size of lenslet\n    if lammin_lenslet is None: lammin_lenslet = lammin\n    theta = set_lenslet(lam, lammin_lenslet, diam_inscribed, X, NIR=True)\n\n    # Set throughput (for inner and outer working angle cutoffs)\n    sep  = r/d*np.sin(alpha*np.pi/180.)*np.pi/180./3600. # separation in radians\n    T = set_throughput(lam, Tput, diam_circumscribed, sep, IWA, OWA, lammin, FIX_OWA=FIX_OWA, SILENT=SILENT)\n\n    # Apply wavelength-dependent throuput, if needed\n    if Tput_lam is not None:\n        # Bin input throughput curve to native res\n        Tlam = np.interp(lam, Tput_lam[0], Tput_lam[1])\n        # Multiply into regular throughput\n        T = T * Tlam\n\n    # Apply wavelength-dependent quantum efficiency, if needed\n    if qe_lam is not None:\n        # Bin input QE curve to native res\n        qlam = np.interp(lam, qe_lam[0], qe_lam[1])\n        # Multiply into regular QE\n        q = q * qlam\n\n    # Modify throughput by atmospheric transmission if GROUND-based\n    if GROUND:\n        #if GROUND == \"ESO\":\n            # Use ESO SKYCALC\n        #    pass\n        #else:\n        # Use SMART calc\n        Tatmos = set_atmos_throughput(lam, dlam, convolution_function)\n        # Multiply telescope throughput by atmospheric throughput\n        T = T * Tatmos\n\n    # Degrade albedo and stellar spectrum\n    if COMPUTE_LAM:\n        A = convolution_function(Ahr, lamhr, lam, dlam=dlam)\n        Fs = convolution_function(solhr, lamhr, lam, dlam=dlam)\n    elif IMAGE:\n        # Convolve with filter response\n        A = convolve_spec(Ahr, lamhr, filters)\n        Fs = convolve_spec(solhr, lamhr, filters)\n    else:\n        A = Ahr\n        Fs = solhr\n\n    # Compute fluxes\n    #Fs = Fstar(lam, Teff, Rs, r, AU=True) # stellar flux on planet\n    Fp = Fplan(A, Phi, Fs, Rp, d)         # planet flux at telescope\n    Cratio = FpFs(A, Phi, Rp, r)\n\n    ##### Compute count rates #####\n    cp     =  cplan(q, fpa, T, lam, dlam, Fp, diam_collect)                          # planet count rate\n    cz     =  czodi(q, X, T, lam, dlam, diam_collect, MzV)                           # solar system zodi count rate\n    cez    =  cezodi(q, X, T, lam, dlam, diam_collect, r, \\\n        Fstar(lam, Teff, Rs,1. , AU=True), Nez, MezV)                                    # exo-zodi count rate\n    csp    =  cspeck(q, T, C, lam, dlam, Fstar(lam,Teff,Rs,d), diam_collect)         # speckle count rate\n    cD     =  cdark(De, X, lam, diam_collect, theta, DNHpix, IMAGE=IMAGE)            # dark current count rate\n    cR     =  cread(Re, X, lam, diam_collect, theta, DNHpix, Dtmax, IMAGE=IMAGE)     # readnoise count rate\n    if THERMAL:\n        cth    =  ctherm(q, X, T, lam, dlam, diam_collect, Tsys, emis)               # internal thermal count rate\n    else:\n        cth = np.zeros_like(cp)\n\n    # Add earth thermal photons if GROUND\n    if GROUND:\n        # Use ESO SKCALC\n        wl_sky, Isky = get_sky_flux()\n        # Convolve to instrument resolution\n        Itherm = convolution_function(Isky, wl_sky, lam, dlam=dlam)\n        # Compute Earth thermal photon count rate\n        cthe = ctherm_earth(q, X, T, lam, dlam, diam_collect, Itherm)\n        # Add earth thermal photon counts to telescope thermal counts\n        cth = cth + cthe\n        '''\n        if True:\n            import matplotlib.pyplot as plt;\n            fig2, ax1 = plt.subplots(figsize=(8,6))\n            ax1.plot(lam, cthe, c=\"blue\", ls=\"steps-mid\", label=\"Earth Thermal\")\n            ax1.plot(lam, cth, c=\"red\", ls=\"steps-mid\", label=\"Telescope Thermal\")\n            ax1.plot(lam, cp, c=\"k\", ls=\"steps-mid\", label=\"Planet\")\n            ax1.set_ylabel(\"Photon Count Rate [1/s]\")\n            ax1.set_xlabel(\"Wavelength [um]\")\n            ax1.legend()\n            plt.show()\n        '''\n\n    # Clock induced charge photon count rate\n    # Calculate photon count rate in the scene (everything except read noise)\n    cscene = cp + cz + cez + csp + cD + cth\n    # Calculate the clock induced charge photon count rate\n    cc = ccic(Rc, cscene, X, lam, diam_collect, theta, DNHpix, Dtmax,\n              IMAGE=IMAGE, CIRC=CIRC)\n\n    # Calculate total background counts\n    cb = (cz + cez + csp + cD + cR + cth + cc)\n\n    # Use telescope roll maneuver\n    if roll_maneuver:\n        # assuming background subtraction (the \"2\")\n        roll_factor = 2.0\n    else:\n        # standard background noise\n        roll_factor = 1.0\n\n    # Calculate total noise\n    cnoise =  cp + roll_factor*cb\n\n    # Calculate total counts\n    ctot = cp + cz + cez + csp + cD + cR + cth + cc\n\n    '''\n    Giada: where does the factor of 2 come from [above]?\n\n    Ty (Via email): That's due to \"background subtraction\".\n    If you were to take a single exposure, and had the ability\n    to post-process the image to the Poisson noise limit, you\n    wouldn't have the factor of two.  However, it's not yet\n    clear that we'll be able to reach the Poisson, single observation limit.\n    Instead, the current idea is that you take two observations (with\n    exposure time Delta t/2), with the telescope rotated by a\n    small amount between exposures, and then subtract the two images.\n    So, for a fixed exoplanet count (cp), the roll technique would\n    give you 2x as many noise counts due to background sources as\n    would the single-observation technique.\n    See also the top of page 4 of Brown (2005).\n    '''\n\n    # Exposure time to SNR\n    DtSNR = exptime_element(lam, cp, cnoise, wantsnr)\n\n    return lam, dlam, A, q, Cratio, cp, csp, cz, cez, cD, cR, cth, cc, DtSNR\n", "meta": {"hexsha": "533df616aaa809b534acf6c73cec28de44f13b49", "size": 31441, "ext": "py", "lang": "Python", "max_stars_repo_path": "coronagraph/count_rates.py", "max_stars_repo_name": "jlustigy/coronagraph", "max_stars_repo_head_hexsha": "b321693512422343b08ada7e246413e1f4bae4cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-05-25T07:48:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T00:40:57.000Z", "max_issues_repo_path": "coronagraph/count_rates.py", "max_issues_repo_name": "jlustigy/coronagraph", "max_issues_repo_head_hexsha": "b321693512422343b08ada7e246413e1f4bae4cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-04-12T22:17:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-07T00:01:11.000Z", "max_forks_repo_path": "coronagraph/count_rates.py", "max_forks_repo_name": "jlustigy/coronagraph", "max_forks_repo_head_hexsha": "b321693512422343b08ada7e246413e1f4bae4cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-11-14T06:46:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-31T06:50:55.000Z", "avg_line_length": 35.9325714286, "max_line_length": 115, "alphanum_fraction": 0.5720237906, "include": true, "reason": "import numpy", "num_tokens": 7945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.19856296263350307}}
{"text": "\"\"\"\nDetector class\n\n----\n\n.. include license and copyright\n.. include:: ../include/copy.rst\n\n----\n\n.. include common links, assuming primary doc root is up one directory\n.. include:: ../include/links.rst\n\n\"\"\"\n\nimport os\nimport numpy\n\nfrom .efficiency import Efficiency\n\nclass Detector(Efficiency):\n    \"\"\"\n    Define the detector statistics.\n\n    Args:\n        shape (:obj:`tuple`, optional):\n            Dimensions of the detector in number of pixels along the\n            spectral axis and number of pixels along the spatial\n            axis. Can be None, but limits use if it is.\n        pixelsize (:obj:`float`, optional):\n            The size of the (square) detector pixels in *micron*.\n        rn (:obj:`float`, optional):\n            Read-noise in electrons.\n        dark (:obj:`float`, optional):\n            Dark current in electrons per second.\n        gain (:obj:`float`, optional):\n            Gain of detector amplifier in e- per ADU.\n        fullwell (:obj:`float`, optional):\n            The full well of the pixels in e-.\n        nonlinear (:obj:`float`, optional):\n            The fraction of the fullwell above which the detector\n            response is nonlinear.\n        qe (:obj:`float`, :class:`Efficiency`, optional):\n            Detector quantum efficiency.\n    \"\"\"\n    # TODO: Allow for multiple amplifiers per detector? Would also need\n    # to define amplifier section.\n    # TODO: Define overscan and data sections\n    def __init__(self, shape=None, pixelsize=15., rn=1., dark=0., gain=1., fullwell=1e4,\n                 nonlinear=1., qe=0.9):\n        if shape is not None and len(shape) != 2:\n            raise ValueError('Shape must contain two integers.')\n        self.shape = shape\n        self.pixelsize = pixelsize\n        self.rn = rn\n        self.dark = dark\n        self.gain = gain\n        self.fullwell = fullwell\n        self.nonlinear = nonlinear\n        if not isinstance(qe, (Efficiency, float)):\n            raise TypeError('Provided quantum efficiency must be type `float` or `Efficiency`.')\n        if isinstance(qe, float):\n            super(Detector, self).__init__(qe)\n        else:\n            super(Detector, self).__init__(qe.eta, wave=qe.wave)\n", "meta": {"hexsha": "d006f4f188d56dc1e59e6e40e197982d5fd55357", "size": 2198, "ext": "py", "lang": "Python", "max_stars_repo_path": "enyo/etc/detector.py", "max_stars_repo_name": "Keck-FOBOS/enyo", "max_stars_repo_head_hexsha": "82dd4324083d456c78bcbafdd081bee53f0c7ba9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "enyo/etc/detector.py", "max_issues_repo_name": "Keck-FOBOS/enyo", "max_issues_repo_head_hexsha": "82dd4324083d456c78bcbafdd081bee53f0c7ba9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "enyo/etc/detector.py", "max_forks_repo_name": "Keck-FOBOS/enyo", "max_forks_repo_head_hexsha": "82dd4324083d456c78bcbafdd081bee53f0c7ba9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.303030303, "max_line_length": 96, "alphanum_fraction": 0.6087352138, "include": true, "reason": "import numpy", "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.19856295873722707}}
{"text": "# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n#    Project: Azimuthal integration\n#             https://github.com/silx-kit/pyFAI\n#\n#    Copyright (C) 2013-2020 European Synchrotron Radiation Facility, Grenoble, France\n#\n#  Permission is hereby granted, free of charge, to any person obtaining a copy\n#  of this software and associated documentation files (the \"Software\"), to deal\n#  in the Software without restriction, including without limitation the rights\n#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n#  copies of the Software, and to permit persons to whom the Software is\n#  furnished to do so, subject to the following conditions:\n#  .\n#  The above copyright notice and this permission notice shall be included in\n#  all copies or substantial portions of the Software.\n#  .\n#  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n#  THE SOFTWARE.\n\n__author__ = \"Jérôme Kieffer\"\n__contact__ = \"Jerome.Kieffer@ESRF.eu\"\n__license__ = \"MIT\"\n__copyright__ = \"European Synchrotron Radiation Facility, Grenoble, France\"\n__date__ = \"06/07/2020\"\n__status__ = \"development\"\n\nimport logging\nimport threading\nimport os\nimport numpy\nlogger = logging.getLogger(__name__)\nfrom math import ceil, floor\nfrom . import detectors\nfrom .opencl import ocl\nif ocl:\n    from .opencl import azim_lut as ocl_azim_lut\n    from .opencl import azim_csr as ocl_azim_csr\nelse:\n    ocl_azim_lut = ocl_azim_csr = None\nfrom .third_party import six\n\ntry:\n    from .ext import _distortion\n    from .ext import sparse_utils\nexcept ImportError:\n    logger.debug(\"Backtrace\", exc_info=True)\n    logger.warning(\"Import _distortion cython implementation failed ... pure python version is terribly slow !!!\")\n    _distortion = None\n\ntry:\n    from scipy.sparse import linalg, csr_matrix, identity\nexcept IOError:\n    logger.warning(\"Scipy is missing ... uncorrection will be handled the old way\")\n    linalg = None\nelse:\n    import scipy\n    v = tuple(int(i) for i in scipy.version.short_version.split(\".\") if i.isdigit())\n    if v < (0, 11):\n        logger.warning(\"Scipy is too old ... uncorrection will be handled the old way\")\n        linalg = None\n\n\ndef resize_image_2D_numpy(image, shape_in):\n    \"numpy implementation of resize_image_2D\"\n    new_img = numpy.zeros(shape_in, dtype=image.dtype)\n    common_shape = [min(i, j) for i, j in zip(image.shape, shape_in)]\n    new_img[:common_shape[0], :common_shape[1]] = image[:common_shape[0], :common_shape[1]]\n    return new_img\n\nif _distortion is None:\n    resize_image_2D = resize_image_2D_numpy\nelse:\n    from .ext._distortion import resize_image_2D\n\n\nclass Distortion(object):\n    \"\"\"\n    This class applies a distortion correction on an image.\n\n    New version compatible both with CSR and LUT...\n    \"\"\"\n    def __init__(self, detector=\"detector\", shape=None, resize=False, empty=0,\n                 mask=None, method=\"CSR\", device=None, workgroup=32):\n        \"\"\"\n        :param detector: detector instance or detector name\n        :param shape: shape of the output image\n        :param resize: allow the output shape to be different from the input shape\n        :param empty: value to be given for empty bins\n        :param method: \"lut\" or \"csr\", the former is faster\n        :param device: Name of the device: None for OpenMP, \"cpu\" or \"gpu\" or the id of the OpenCL device a 2-tuple of integer\n        :param workgroup: workgroup size for CSR on OpenCL\n        \"\"\"\n        self._shape_out = None\n        if isinstance(detector, six.string_types):\n            self.detector = detectors.detector_factory(detector)\n        else:  # we assume it is a Detector instance\n            self.detector = detector\n        self.shape_in = self.detector.shape\n        if mask is None:\n            self.mask = numpy.ascontiguousarray(self.detector.mask, numpy.int8)\n        elif mask is False:\n            self.mask = numpy.zeros(self.detector.mask.shape, numpy.int8)\n        else:\n            self.mask = numpy.ascontiguousarray(mask, numpy.int8)\n        self.resize = resize\n        if shape is not None:\n            self._shape_out = tuple([int(i) for i in shape])\n        elif not self.resize:\n            if self.detector.shape is not None:\n                self._shape_out = self.detector.shape\n            else:\n                raise RuntimeError(\"You need to provide either the detector or its shape\")\n\n        self._sem = threading.Semaphore()\n        self.bin_size = None\n        self.max_size = None\n        self.pos = None\n        if not method:\n            self.method = \"lut\"\n        else:\n            self.method = method.lower()\n        if (self.detector.uniform_pixel and self.detector.IS_FLAT):\n            csr = identity(numpy.prod(self.detector.shape),\n                           dtype=numpy.float32,\n                           format=\"csr\")\n            if self.detector.mask is not None:\n                masked = numpy.where(self.detector.mask)\n                csr[masked] = 0.0\n            if self.method == \"lut\":\n                self.lut = sparse_utils.CSR_to_LUT(csr.data, csr.indices, csr.indptr)\n            else:\n                self.lut = csr.data, csr.indices, csr.indptr\n        else:\n            #initialize the LUT later\n            self.lut = None\n        self.delta1 = self.delta2 = None  # max size of an pixel on a regular grid ...\n        self.offset1 = self.offset2 = 0  # position of the first bin\n        self.integrator = None\n        self.empty = empty  # \"dummy\" value for empty bins\n        self.device = device\n        if not workgroup:\n            self.workgroup = 1\n        else:\n            self.workgroup = int(workgroup)\n\n    def __repr__(self):\n        return os.linesep.join([\"Distortion correction %s on device %s for detector shape %s:\" % (self.method, self.device, self._shape_out),\n                                self.detector.__repr__()])\n\n    def reset(self, method=None, device=None, workgroup=None, prepare=True):\n        \"\"\"\n        reset the distortion correction and re-calculate the look-up table\n\n        :param method: can be \"lut\" or \"csr\", \"lut\" looks faster\n        :param device: can be None, \"cpu\" or \"gpu\" or the id as a 2-tuple of integer\n        :param worgroup: enforce the workgroup size for CSR.\n        :param prepare: set to false to only reset and not re-initialize\n        \"\"\"\n        with self._sem:\n            self.max_size = None\n            self.pos = None\n            self.lut = None\n            self.delta1 = self.delta2 = None\n            self.offset1 = self.offset2 = 0\n            self.integrator = None\n            if method is not None:\n                self.method = method.lower()\n            if device is not None:\n                self.device = device\n            if workgroup is not None:\n                self.workgroup = int(workgroup)\n        if prepare:\n            self.calc_init()\n\n    @property\n    def shape_out(self):\n        \"\"\"\n        Calculate/cache the output shape\n\n        :return: output shape\n        \"\"\"\n        if self._shape_out is None:\n            self.calc_pos()\n        return self._shape_out\n\n    def calc_pos(self, use_cython=True):\n        \"\"\"Calculate the pixel boundary position on the regular grid\n\n        :return: pixel corner positions (in pixel units) on the regular grid\n        :rtype: ndarray of shape (nrow, ncol, 4, 2)\n        \"\"\"\n        if self.delta1 is None:\n            with self._sem:\n                if self.delta1 is None:\n                    # TODO: implement equivalent in Cython\n                    if _distortion and use_cython:\n                        self.pos, self.delta1, self.delta2, shape_out, offset = _distortion.calc_pos(self.detector.get_pixel_corners(), self.detector.pixel1, self.detector.pixel2, self._shape_out)\n                        if self._shape_out is None:\n                            self.offset1, self.offset2 = offset\n                            self._shape_out = shape_out\n                    else:\n                        pixel_size = numpy.array([self.detector.pixel1, self.detector.pixel2], dtype=numpy.float32)\n                        # make it a 4D array\n                        pixel_size.shape = 1, 1, 1, 2\n                        pixel_size.strides = 0, 0, 0, pixel_size.strides[-1]\n                        self.pos = self.detector.get_pixel_corners()[..., 1:] / pixel_size\n                        if self._shape_out is None:\n                            # if defined, it is probably because resize=False\n                            corner_pos = self.pos.view()\n                            corner_pos.shape = -1, 2\n                            pos1_min, pos2_min = corner_pos.min(axis=0)\n                            pos1_max, pos2_max = corner_pos.max(axis=0)\n                            self._shape_out = (int(ceil(pos1_max - pos1_min)),\n                                               int(ceil(pos2_max - pos2_min)))\n                            self.offset1, self.offset2 = pos1_min, pos2_min\n                        pixel_delta = self.pos.view()\n                        pixel_delta.shape = -1, 4, 2\n                        self.delta1, self.delta2 = ((numpy.ceil(pixel_delta.max(axis=1)) - numpy.floor(pixel_delta.min(axis=1))).max(axis=0)).astype(int)\n        return self.pos\n\n    def calc_size(self, use_cython=True):\n        \"\"\"Calculate the number of pixels falling into every single bin and\n\n        :return: max of pixel falling into a single bin\n\n        Considering the \"half-CCD\" spline from ID11 which describes a (1025,2048) detector,\n        the physical location of pixels should go from:\n        [-17.48634 : 1027.0543, -22.768829 : 2028.3689]\n        We chose to discard pixels falling outside the [0:1025,0:2048] range with a lose of intensity\n        \"\"\"\n        if self.pos is None:\n            pos = self.calc_pos()\n        else:\n            pos = self.pos\n        if self.max_size is None:\n            with self._sem:\n                if self.max_size is None:\n                    if _distortion and use_cython:\n                        self.bin_size = _distortion.calc_size(self.pos, self._shape_out, self.mask, (self.offset1, self.offset2))\n                    else:\n                        mask = self.mask\n                        pos0min = (numpy.floor(pos[:, :, :, 0].min(axis=-1) - self.offset1).astype(numpy.int32)).clip(0, self._shape_out[0])\n                        pos1min = (numpy.floor(pos[:, :, :, 1].min(axis=-1) - self.offset2).astype(numpy.int32)).clip(0, self._shape_out[1])\n                        pos0max = (numpy.ceil(pos[:, :, :, 0].max(axis=-1) - self.offset1 + 1).astype(numpy.int32)).clip(0, self._shape_out[0])\n                        pos1max = (numpy.ceil(pos[:, :, :, 1].max(axis=-1) - self.offset2 + 1).astype(numpy.int32)).clip(0, self._shape_out[1])\n                        self.bin_size = numpy.zeros(self._shape_out, dtype=numpy.int32)\n                        for i in range(self.shape_in[0]):\n                            for j in range(self.shape_in[1]):\n                                if (mask is not None) and mask[i, j]:\n                                    continue\n                                self.bin_size[pos0min[i, j]:pos0max[i, j], pos1min[i, j]:pos1max[i, j]] += 1\n                    self.max_size = self.bin_size.max()\n        return self.bin_size\n\n    def calc_init(self):\n        \"\"\"Initialize all arrays\n        \"\"\"\n        self.calc_pos()\n        self.calc_size()\n        self.calc_LUT()\n        if ocl and self.device is not None:\n            if \"lower\" in dir(self.device):\n                self.device = self.device.lower()\n                if self.method == \"lut\":\n                    self.integrator = ocl_azim_lut.OCL_LUT_Integrator(self.lut,\n                                                                      self._shape_out[0] * self._shape_out[1],\n                                                                      devicetype=self.device)\n                else:\n                    self.integrator = ocl_azim_csr.OCL_CSR_Integrator(self.lut,\n                                                                      self._shape_out[0] * self._shape_out[1],\n                                                                      devicetype=self.device,\n                                                                      block_size=self.workgroup)\n                    self.integrator.workgroup_size[\"csr_integrate4\"] = 1,\n            else:\n                if self.method == \"lut\":\n                    self.integrator = ocl_azim_lut.OCL_LUT_Integrator(self.lut,\n                                                                      self._shape_out[0] * self._shape_out[1],\n                                                                      platformid=self.device[0],\n                                                                      deviceid=self.device[1])\n                else:\n                    self.integrator = ocl_azim_csr.OCL_CSR_Integrator(self.lut,\n                                                                      self._shape_out[0] * self._shape_out[1],\n                                                                      platformid=self.device[0], deviceid=self.device[1],\n                                                                      block_size=self.workgroup)\n                    self.integrator.workgroup_size[\"csr_integrate4\"] = 1,\n\n    def calc_LUT(self, use_common=True):\n        \"\"\"Calculate the Look-up table\n\n        :return: look up table either in CSR or LUT format depending on serl.method\n        \"\"\"\n        if self.pos is None:\n            self.calc_pos()\n\n        if self.max_size is None and not use_common:\n            self.calc_size()\n        if self.lut is None:\n            with self._sem:\n                if self.lut is None:\n                    mask = self.mask\n                    if _distortion:\n                        if use_common:\n                            self.lut = _distortion.calc_sparse(self.pos, self._shape_out, max_pixel_size=(self.delta1, self.delta2), format=self.method)\n                        else:\n                            if self.method == \"lut\":\n                                self.lut = _distortion.calc_LUT(self.pos, self._shape_out, self.bin_size, max_pixel_size=(self.delta1, self.delta2))\n                            else:\n                                self.lut = _distortion.calc_CSR(self.pos, self._shape_out, self.bin_size, max_pixel_size=(self.delta1, self.delta2))\n                    else:\n                        lut = numpy.recarray(shape=(self._shape_out[0], self._shape_out[1], self.max_size), dtype=[(\"idx\", numpy.uint32), (\"coef\", numpy.float32)])\n                        lut[:, :, :].idx = 0\n                        lut[:, :, :].coef = 0.0\n                        outMax = numpy.zeros(self._shape_out, dtype=numpy.uint32)\n                        idx = 0\n                        buffer_ = numpy.empty((self.delta1, self.delta2))\n                        quad = Quad(buffer_)\n                        for i in range(self._shape_out[0]):\n                            for j in range(self._shape_out[1]):\n                                if (mask is not None) and mask[i, j]:\n                                    continue\n                                # i,j, idx are indexes of the raw image uncorrected\n                                quad.reinit(*list(self.pos[i, j, :, :].ravel()))\n                                # print(self.pos[i, j, 0, :], self.pos[i, j, 1, :], self.pos[i, j, 2, :], self.pos[i, j, 3, :]\n                                try:\n                                    quad.populate_box()\n                                except Exception as error:\n                                    print(\"error in quad.populate_box of pixel %i, %i: %s\" % (i, j, error))\n                                    print(\"calc_area_vectorial\", quad.calc_area_vectorial())\n                                    print(self.pos[i, j, 0, :], self.pos[i, j, 1, :], self.pos[i, j, 2, :], self.pos[i, j, 3, :])\n                                    print(quad)\n                                    raise\n                #                box = quad.get_box()\n                                for ms in range(quad.get_box_size0()):\n                                    ml = ms + quad.get_offset0()\n                                    if ml < 0 or ml >= self._shape_out[0]:\n                                        continue\n                                    for ns in range(quad.get_box_size1()):\n                                        # ms,ns are indexes of the corrected image in short form, ml & nl are the same\n                                        nl = ns + quad.get_offset1()\n                                        if nl < 0 or nl >= self._shape_out[1]:\n                                            continue\n                                        val = quad.get_box(ms, ns)\n                                        if val <= 0:\n                                            continue\n                                        k = outMax[ml, nl]\n                                        lut[ml, nl, k].idx = idx\n                                        lut[ml, nl, k].coef = val\n                                        outMax[ml, nl] = k + 1\n                                idx += 1\n                        lut.shape = (self._shape_out[0] * self._shape_out[1]), self.max_size\n                        self.lut = lut\n        return self.lut\n\n    def correct(self, image, dummy=None, delta_dummy=None):\n        \"\"\"\n        Correct an image based on the look-up table calculated ...\n\n        :param image: 2D-array with the image\n        :param dummy: value suggested for bad pixels\n        :param delta_dummy: precision of the dummy value\n        :return: corrected 2D image\n        \"\"\"\n        if image.ndim == 2:\n            image = resize_image_2D(image, self.shape_in)\n        else:  # assume 2d+nchanel\n            if _distortion:\n                image = _distortion.resize_image_3D(image, self.shape_in)\n            else:\n                assert image.ndim == 3, \"image is 3D\"\n                shape_in0, shape_in1 = self.shape_in\n                shape_img0, shape_img1, nchan = image.shape\n                if not ((shape_img0 == shape_in0) and (shape_img1 == shape_in1)):\n                    new_image = numpy.zeros((shape_in0, shape_in1, nchan), dtype=numpy.float32)\n                    if shape_img0 < shape_in0:\n                        if shape_img1 < shape_in1:\n                            new_image[:shape_img0, :shape_img1, :] = image\n                        else:\n                            new_image[:shape_img0, :, :] = image[:, :shape_in1, :]\n                    else:\n                        if shape_img1 < shape_in1:\n                            new_image[:, :shape_img1, :] = image[:shape_in0, :, :]\n                        else:\n                            new_image[:, :, :] = image[:shape_in0, :shape_in1, :]\n                    logger.warning(\"Patching image of shape %ix%i on expected size of %ix%i\",\n                                   shape_img1, shape_img0, shape_in1, shape_in0)\n                image = new_image\n        if self.device:\n            if self.integrator is None:\n                self.calc_init()\n            out = self.integrator.integrate(image)[1]\n        else:\n            if self.lut is None:\n                self.calc_LUT()\n            if _distortion is not None:\n                out = _distortion.correct(image, self.shape_in, self._shape_out, self.lut,\n                                          dummy=dummy or self.empty, delta_dummy=delta_dummy)\n            else:\n                if self.method == \"lut\":\n                    big = image.ravel().take(self.lut.idx) * self.lut.coef\n                    out = big.sum(axis=-1)\n                elif self.method == \"csr\":\n                    big = self.lut[0] * image.ravel().take(self.lut[1])\n                    indptr = self.lut[2]\n                    out = numpy.zeros(indptr.size - 1)\n                    for i in range(indptr.size - 1):\n                        out[i] = big[indptr[i]:indptr[i + 1]].sum()\n        try:\n            if image.ndim == 2:\n                out.shape = self._shape_out\n            else:\n                for ds in out:\n                    if ds.ndim == 2:\n                        ds.shape = self._shape_out\n                    else:\n                        ds.shape = self._shape_out + ds.shape[2:]\n\n        except ValueError as _err:\n            logger.error(\"Requested in_shape=%s out_shape=%s and \", self.shape_in, self.shape_out)\n            raise\n        return out\n\n    def correct_ng(self, image,\n                   variance=None,\n                   dark=None,\n                   flat=None,\n                   solidangle=None,\n                   polarization=None,\n                   dummy=None,\n                   delta_dummy=None,\n                   normalization_factor=1.0):\n        \"\"\"\n        Correct an image based on the look-up table calculated ...\n        Like the integrate_ng it provides\n        * Dark current correction\n        * Normalisation with flatfield (or solid angle, polarization, absorption, ...)\n        * Error propagation\n\n        :param image: 2D-array with the image\n        :param variance: 2D-array with the associated image\n        :param dark: array with dark-current values\n        :param flat: array with values for a flat image\n        :param solidangle: solid-angle array\n        :param polarization: numpy array with 2D polarization corrections\n        :param dummy: value suggested for bad pixels\n        :param delta_dummy: precision of the dummy value\n        :param normalization_factor: multiply all normalization with this value\n        :return: corrected 2D image\n        \"\"\"\n        assert image.ndim == 2\n        if variance is not None:\n            assert variance.shape == image.shape\n\n        if image.shape != self.shape_in:\n            logger.warning(\"The image shape %s is not the same as the detector %s\", image.shape, self.shape_in)\n            image = resize_image_2D(image, self.shape_in)\n            if variance is not None:\n                variance = resize_image_2D(variance, self.shape_in)\n            if dark is not None:\n                dark = resize_image_2D(dark, self.shape_in)\n\n        if self.device:\n            if self.integrator is None:\n                self.calc_init()\n            res = self.integrator.integrate_ng(image,\n                                               variance=variance,\n                                               flat=flat,\n                                               dark=dark,\n                                               solidangle=solidangle,\n                                               polarization=polarization,\n                                               dummy=dummy,\n                                               delta_dummy=delta_dummy,\n                                               normalization_factor=normalization_factor,\n                                               out_merged=False\n                                               )\n            if variance is not None:\n                if image.ndim == 2:\n                    out = res.intensity.reshape(self._shape_out)\n                else:\n                    out = res.intensity\n            else:\n                if image.ndim == 2:\n                    out = (res.intensity.reshape(self._shape_out), res.error.reshape(self._shape_out))\n                else:\n                    out = (res.intensity, res.error)\n        else:\n            if self.lut is None:\n                self.calc_LUT()\n            if _distortion is not None:\n                out = _distortion.correct(image, self.shape_in, self._shape_out, self.lut,\n                                          dummy=dummy or self.empty, delta_dummy=delta_dummy)\n            else:\n                if self.method == \"lut\":\n                    big = image.ravel().take(self.lut.idx) * self.lut.coef\n                    out = big.sum(axis=-1)\n                elif self.method == \"csr\":\n                    big = self.lut[0] * image.ravel().take(self.lut[1])\n                    indptr = self.lut[2]\n                    out = numpy.zeros(indptr.size - 1)\n                    for i in range(indptr.size - 1):\n                        out[i] = big[indptr[i]:indptr[i + 1]].sum()\n            try:\n                if image.ndim == 2:\n                    out.shape = self._shape_out\n                else:\n                    for ds in out:\n                        if ds.ndim == 2:\n                            ds.shape = self._shape_out\n                        else:\n                            ds.shape = self._shape_out + ds.shape[2:]\n\n            except ValueError as _err:\n                logger.error(\"Requested in_shape=%s out_shape=%s and \", self.shape_in, self.shape_out)\n                raise\n        return out\n\n\n    def uncorrect(self, image, use_cython=False):\n        \"\"\"\n        Take an image which has been corrected and transform it into it's raw (with loss of information)\n\n        :param image: 2D-array with the image\n        :return: uncorrected 2D image\n\n        Nota: to retrieve the input mask on can do:\n\n        >>> msk =  dis.uncorrect(numpy.ones(dis._shape_out)) <= 0\n        \"\"\"\n        assert image.shape == self._shape_out\n        if self.lut is None:\n            self.calc_LUT()\n        if (linalg is not None) and (use_cython is False):\n            if self.method == \"lut\":\n                csr = csr_matrix(sparse_utils.LUT_to_CSR(self.lut))\n            else:\n                csr = csr_matrix(self.lut)\n            res = linalg.lsmr(csr, image.ravel())\n            out = res[0].reshape(self.shape_in)\n        else:  # This is deprecated and does not work with resise=True\n            if self.method == \"lut\":\n                if _distortion is not None:\n                    out, _mask = _distortion.uncorrect_LUT(image, self.shape_in, self.lut)\n                else:\n                    out = numpy.zeros(self.shape_in, dtype=numpy.float32)\n                    lout = out.ravel()\n                    lin = image.ravel()\n                    tot = self.lut.coef.sum(axis=-1)\n                    for idx in range(self.lut.shape[0]):\n                        t = tot[idx]\n                        if t <= 0:\n                            continue\n                        val = lin[idx] / t\n                        lout[self.lut[idx].idx] += val * self.lut[idx].coef\n            elif self.method == \"csr\":\n                if _distortion is not None:\n                    out, _mask = _distortion.uncorrect_CSR(image, self.shape_in, self.lut)\n            else:\n                raise NotImplementedError()\n        return out\n\n\nclass Quad(object):\n    \"\"\"\n    Quad modelisation.\n\n    .. image:: ../img/quad_model.svg\n        :alt: Modelization of the quad\n    \"\"\"\n    def __init__(self, buffer):\n        self.box = buffer\n        self.A0 = self.A1 = None\n        self.B0 = self.B1 = None\n        self.C0 = self.C1 = None\n        self.D0 = self.D1 = None\n        self.offset0 = self.offset1 = None\n        self.box_size0 = self.box_size1 = None\n        self.pAB = self.pBC = self.pCD = self.pDA = None\n        self.cAB = self.cBC = self.cCD = self.cDA = None\n        self.area = None\n\n    def get_idx(self, i, j):\n        pass\n\n    def get_box(self, i, j):\n        return self.box[i, j]\n\n    def get_offset0(self):\n        return self.offset0\n\n    def get_offset1(self):\n        return self.offset1\n\n    def get_box_size0(self):\n        return self.box_size0\n\n    def get_box_size1(self):\n        return self.box_size1\n\n    def reinit(self, A0, A1, B0, B1, C0, C1, D0, D1):\n        self.box[:, :] = 0.0\n        self.A0 = A0\n        self.A1 = A1\n        self.B0 = B0\n        self.B1 = B1\n        self.C0 = C0\n        self.C1 = C1\n        self.D0 = D0\n        self.D1 = D1\n        self.offset0 = int(floor(min(self.A0, self.B0, self.C0, self.D0)))\n        self.offset1 = int(floor(min(self.A1, self.B1, self.C1, self.D1)))\n        self.box_size0 = int(ceil(max(self.A0, self.B0, self.C0, self.D0))) - self.offset0\n        self.box_size1 = int(ceil(max(self.A1, self.B1, self.C1, self.D1))) - self.offset1\n        self.A0 -= self.offset0\n        self.A1 -= self.offset1\n        self.B0 -= self.offset0\n        self.B1 -= self.offset1\n        self.C0 -= self.offset0\n        self.C1 -= self.offset1\n        self.D0 -= self.offset0\n        self.D1 -= self.offset1\n        self.pAB = self.pBC = self.pCD = self.pDA = None\n        self.cAB = self.cBC = self.cCD = self.cDA = None\n        self.area = None\n\n    def __repr__(self):\n        return os.linesep.join([\"offset %i,%i size %i, %i\" % (self.offset0, self.offset1, self.box_size0, self.box_size1), \"box: %s\" % self.box[:self.box_size0, :self.box_size1]])\n\n    def init_slope(self):\n        if self.pAB is None:\n            if self.B0 == self.A0:\n                self.pAB = numpy.inf\n            else:\n                self.pAB = (self.B1 - self.A1) / (self.B0 - self.A0)\n            if self.C0 == self.B0:\n                self.pBC = numpy.inf\n            else:\n                self.pBC = (self.C1 - self.B1) / (self.C0 - self.B0)\n            if self.D0 == self.C0:\n                self.pCD = numpy.inf\n            else:\n                self.pCD = (self.D1 - self.C1) / (self.D0 - self.C0)\n            if self.A0 == self.D0:\n                self.pDA = numpy.inf\n            else:\n                self.pDA = (self.A1 - self.D1) / (self.A0 - self.D0)\n            self.cAB = self.A1 - self.pAB * self.A0\n            self.cBC = self.B1 - self.pBC * self.B0\n            self.cCD = self.C1 - self.pCD * self.C0\n            self.cDA = self.D1 - self.pDA * self.D0\n\n    def calc_area_AB(self, I1, I2):\n        if numpy.isfinite(self.pAB):\n            return 0.5 * (I2 - I1) * (self.pAB * (I2 + I1) + 2 * self.cAB)\n        else:\n            return 0\n\n    def calc_area_BC(self, J1, J2):\n        if numpy.isfinite(self.pBC):\n            return 0.5 * (J2 - J1) * (self.pBC * (J1 + J2) + 2 * self.cBC)\n        else:\n            return 0\n\n    def calc_area_CD(self, K1, K2):\n        if numpy.isfinite(self.pCD):\n            return 0.5 * (K2 - K1) * (self.pCD * (K2 + K1) + 2 * self.cCD)\n        else:\n            return 0\n\n    def calc_area_DA(self, L1, L2):\n\n        if numpy.isfinite(self.pDA):\n            return 0.5 * (L2 - L1) * (self.pDA * (L1 + L2) + 2 * self.cDA)\n        else:\n            return 0\n\n    def calc_area_old(self):\n        if self.area is None:\n            if self.pAB is None:\n                self.init_slope()\n            self.area = -(self.calc_area_AB(self.A0, self.B0) +\n                          self.calc_area_BC(self.B0, self.C0) +\n                          self.calc_area_CD(self.C0, self.D0) +\n                          self.calc_area_DA(self.D0, self.A0))\n        return self.area\n\n    def calc_area_vectorial(self):\n        if self.area is None:\n            self.area = numpy.cross([self.C0 - self.A0, self.C1 - self.A1], [self.D0 - self.B0, self.D1 - self.B1]) / 2.0\n        return self.area\n    calc_area = calc_area_vectorial\n\n    def populate_box(self):\n        if self.pAB is None:\n            self.init_slope()\n        self.integrateAB(self.B0, self.A0, self.calc_area_AB)\n        self.integrateAB(self.A0, self.D0, self.calc_area_DA)\n        self.integrateAB(self.D0, self.C0, self.calc_area_CD)\n        self.integrateAB(self.C0, self.B0, self.calc_area_BC)\n        if (self.box / self.calc_area()).min() < 0:\n            print(self.box)\n            self.box[:, :] = 0\n            print(\"AB\")\n            self.integrateAB(self.B0, self.A0, self.calc_area_AB)\n            print(self.box)\n            self.box[:, :] = 0\n            print(\"DA\")\n            self.integrateAB(self.A0, self.D0, self.calc_area_DA)\n            print(self.box)\n            self.box[:, :] = 0\n            print(\"CD\")\n            self.integrateAB(self.D0, self.C0, self.calc_area_CD)\n            print(self.box)\n            self.box[:, :] = 0\n            print(\"BC\")\n            self.integrateAB(self.C0, self.B0, self.calc_area_BC)\n            print(self.box)\n            print(self)\n            raise RuntimeError()\n        self.box /= self.calc_area_vectorial()\n\n    def integrateAB(self, start, stop, calc_area):\n        h = 0\n#        print(start, stop, calc_area(start, stop)\n        if start < stop:  # positive contribution\n            P = ceil(start)\n            dP = P - start\n#            print(\"Integrate\", start, P, stop, calc_area(start, stop)\n            if P > stop:  # start and stop are in the same unit\n                A = calc_area(start, stop)\n                if A != 0:\n                    AA = abs(A)\n                    sign = A / AA\n                    dA = (stop - start)  # always positive\n#                    print(AA, sign, dA\n                    h = 0\n                    while AA > 0:\n                        if dA > AA:\n                            dA = AA\n                            AA = -1\n                        self.box[int(floor(start)), h] += sign * dA\n                        AA -= dA\n                        h += 1\n            else:\n                if dP > 0:\n                    A = calc_area(start, P)\n                    if A != 0:\n                        AA = abs(A)\n                        sign = A / AA\n                        h = 0\n                        dA = dP\n                        while AA > 0:\n                            if dA > AA:\n                                dA = AA\n                                AA = -1\n                            self.box[int(floor(P)) - 1, h] += sign * dA\n                            AA -= dA\n                            h += 1\n                # subsection P1->Pn\n                for i in range(int(floor(P)), int(floor(stop))):\n                    A = calc_area(i, i + 1)\n                    if A != 0:\n                        AA = abs(A)\n                        sign = A / AA\n\n                        h = 0\n                        dA = 1.0\n                        while AA > 0:\n                            if dA > AA:\n                                dA = AA\n                                AA = -1\n                            self.box[i, h] += sign * dA\n                            AA -= dA\n                            h += 1\n                # Section Pn->B\n                P = floor(stop)\n                dP = stop - P\n                if dP > 0:\n                    A = calc_area(P, stop)\n                    if A != 0:\n                        AA = abs(A)\n                        sign = A / AA\n                        h = 0\n                        dA = abs(dP)\n                        while AA > 0:\n                            if dA > AA:\n                                dA = AA\n                                AA = -1\n                            self.box[int(floor(P)), h] += sign * dA\n                            AA -= dA\n                            h += 1\n        elif start > stop:  # negative contribution. Nota is start=stop: no contribution\n            P = floor(start)\n            if stop > P:  # start and stop are in the same unit\n                A = calc_area(start, stop)\n                if A != 0:\n                    AA = abs(A)\n                    sign = A / AA\n                    dA = (start - stop)  # always positive\n                    h = 0\n                    while AA > 0:\n                        if dA > AA:\n                            dA = AA\n                            AA = -1\n                        self.box[int(floor(start)), h] += sign * dA\n                        AA -= dA\n                        h += 1\n            else:\n                dP = P - start\n                if dP < 0:\n                    A = calc_area(start, P)\n                    if A != 0:\n                        AA = abs(A)\n                        sign = A / AA\n                        h = 0\n                        dA = abs(dP)\n                        while AA > 0:\n                            if dA > AA:\n                                dA = AA\n                                AA = -1\n                            self.box[int(floor(P)), h] += sign * dA\n                            AA -= dA\n                            h += 1\n                # subsection P1->Pn\n                for i in range(int(start), int(ceil(stop)), -1):\n                    A = calc_area(i, i - 1)\n                    if A != 0:\n                        AA = abs(A)\n                        sign = A / AA\n                        h = 0\n                        dA = 1\n                        while AA > 0:\n                            if dA > AA:\n                                dA = AA\n                                AA = -1\n                            self.box[i - 1, h] += sign * dA\n                            AA -= dA\n                            h += 1\n                # Section Pn->B\n                P = ceil(stop)\n                dP = stop - P\n                if dP < 0:\n                    A = calc_area(P, stop)\n                    if A != 0:\n                        AA = abs(A)\n                        sign = A / AA\n                        h = 0\n                        dA = abs(dP)\n                        while AA > 0:\n                            if dA > AA:\n                                dA = AA\n                                AA = -1\n                            self.box[int(floor(stop)), h] += sign * dA\n                            AA -= dA\n                            h += 1\n", "meta": {"hexsha": "0c3ff6709b98b27b367b1e5adfddc922030956cc", "size": 37655, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyFAI/distortion.py", "max_stars_repo_name": "weninc/pyFAI", "max_stars_repo_head_hexsha": "4d857851ade2888f5aee5eab0fc973775e43bb77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyFAI/distortion.py", "max_issues_repo_name": "weninc/pyFAI", "max_issues_repo_head_hexsha": "4d857851ade2888f5aee5eab0fc973775e43bb77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyFAI/distortion.py", "max_forks_repo_name": "weninc/pyFAI", "max_forks_repo_head_hexsha": "4d857851ade2888f5aee5eab0fc973775e43bb77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.7340301974, "max_line_length": 196, "alphanum_fraction": 0.4741734165, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 8422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.19856295873722707}}
{"text": "#!/usr/bin/env python\n\n\nfrom astropy.io import fits as pyfits\nimport numpy as np\nimport os\nimport argparse\nfrom scipy.ndimage import filters\n\n\nif __name__ == '__main__':\n    \n    p   = argparse.ArgumentParser(                                \n        description='''\n        Group pha files using optimum binning based on the instrument\n        resoluions, or using the formula in Kaastra+Bleeker 16,\n        with the addition of a signal to noise constraint.\n        The input spectrum is assumed to have the RESPFILE and \n        BACKFILE keywords\n        ''',            \n        formatter_class=argparse.ArgumentDefaultsHelpFormatter ) \n\n    p.add_argument(\"spec_file\"  , metavar=\"spec_file\", type=str,\n            help=\"The name of the input spectrum file.\")\n    p.add_argument(\"out_file\"  , metavar=\"out_file\", type=str,\n            help=\"The name of the output spectrum file.\")\n    p.add_argument('-s', '--snr', metavar='min_snr', \n            type=float, default=3,\n            help='The minimum signal to noise ration per bin. -1 to ignore')\n    p.add_argument('-c', '--counts', metavar='min_counts', \n            type=float, default=-1,\n            help='The minimum counts per bin. -1 to ignore')\n    p.add_argument('-f', '--osample_fac', metavar='osample_fac', \n            type=float, default=3,\n            help='The oversampling factor in units of the local FWHM')\n    p.add_argument(\"--use_formula\", action='store_true', default=False,\n            help=('Calculate the oversampling factor using formula 36-37 '\n                  'in Kaastra & Bleeker 2016'))\n    p.add_argument(\"--write_chan\", action='store_true', default=False,\n            help=('Write grouping file, then use standard grppha.'\n                  'This requires heasoft and ngroups < 100'))\n\n\n    # process input #\n    args        = p.parse_args()\n    spec_file   = args.spec_file\n    out_file    = args.out_file\n    min_snr     = args.snr\n    min_counts  = args.counts\n    osample_fac = args.osample_fac\n    use_formula = args.use_formula\n    write_chan  = args.write_chan\n\n\n    # some defaults #\n    if osample_fac < 0: osample_fac = 1\n\n\n\n\n\n    # ------------------------------------------- #\n    # Read the response and background file names #\n    with pyfits.open(spec_file) as fp:\n        src_c  = np.array(fp['SPECTRUM'].data.field(1), np.double)\n        src_ex = fp['SPECTRUM'].header['EXPOSURE'] \n        try:\n            src_bs = fp['SPECTRUM'].header['BACKSCAL'] \n        except:\n            src_bs = 1.0\n        try:\n            rsp_file = fp['SPECTRUM'].header['RESPFILE']\n        except:\n            raise ValueError('No RESPFILE key in spectrum header')\n        try:\n            bgd_file = fp['SPECTRUM'].header['BACKFILE']\n        except:\n            bgd_file = None\n            #raise ValueError('No BACKFILE key in spectrum header; Set to none if needed')\n    # ------------------------------------------- #\n\n\n\n    # --------------------- #\n    # get background counts #\n    bgd_c = np.zeros_like(src_c)\n    if not bgd_file in [None, 'none', 'NONE']:\n        with pyfits.open(bgd_file) as fp:\n            bgd_c  = np.array(fp['SPECTRUM'].data.field(1), np.double)\n            bgd_ex = fp['SPECTRUM'].header['EXPOSURE'] \n            try:\n                bgd_bs = fp['SPECTRUM'].header['BACKSCAL'] \n            except:\n                bgd_bs = 1.0\n        bgd_c *= (src_bs/bgd_bs) * (src_ex/bgd_ex)\n    # --------------------- #\n\n\n    # ------------------------- #\n    # energy-channel conversion #\n    with pyfits.open(rsp_file) as fp:\n        edata  = fp['EBOUNDS'].data\n        chan   = edata.field(0)\n        energy = (edata.field(1)+edata.field(2)) / 2.\n        try:\n            matrix = fp['MATRIX'].data\n        except:\n            matrix = fp['SPECRESP MATRIX'].data\n        nchan  = len(chan)\n        nen    = len(matrix)\n    men = np.array([(m[1]+m[0])/2 for m in matrix])\n    # ------------------------- #\n\n\n\n    # --------------------- #\n    # loop through channels #\n    ibin = np.zeros(nchan) - 1\n    ich, ibin[0] = 0, 1\n    smooth = nen * 1. / nchan\n    while ich < nchan:\n\n        # get the response curve at ich #\n        ie = np.argmin(np.abs(men - energy[ich]))\n        istart, ilen = matrix[ie][3], matrix[ie][4]\n        if not isinstance(istart, (list, np.ndarray)):\n            istart, ilen = [istart], [ilen]\n        if len(istart) == 0 or len(ilen) == 0:\n            ich += 1\n            continue\n        iarr = np.concatenate([np.arange(i1, i1+i2) for i1,i2 in zip(istart, ilen)])\n        rarr = matrix[ie][5]\n        rarr = filters.gaussian_filter1d(rarr, smooth)\n\n\n        # work out fwhm at ich #\n        if not np.allclose(rarr, 0) and nchan > 100:\n            imax = np.argmax(rarr)\n\n            # limits of fwhm in energy grid units\n            ic1 = np.argmin(np.abs(rarr[:imax]-rarr[imax]/2.)) if imax !=0 else 0\n            ic2 = np.argmin(np.abs(rarr[imax:]-rarr[imax]/2.)) + imax\n            width = ic2 - ic1\n            \n        else:\n            #width = nchan - ich\n            width = 1\n\n\n        # get oversampling factor if we use_formula is requested #\n        if use_formula:\n            width = np.max([1, width])\n            ind = range(ich, ich+width)\n            if ind[-1] >= nchan:\n                ind = range(ich, nchan)\n            counts = np.max([sum(src_c[ind] - bgd_c[ind]), 1e-10] )\n            counts *= 1./width # per resolution element\n            x = np.log(counts*(1 + 0.20 *np.log(width)))\n            osample_fac = 1. if x<2.119 else (0.08+7./x + 1.8/x**2)/(1+5.9/x)\n            osample_fac = 1. / osample_fac\n        # ----- #\n\n\n        # bin width in channel units using oversample_fac\n        width = np.int(np.round(np.max([1, width*1./osample_fac])))\n        ind   = range(ich, np.min([ich+width, nchan]) )\n\n        \n        # increase width until snr > min_snr #\n        if min_snr:\n            snr = sum(src_c[ind] - bgd_c[ind])\n            while snr < 1 and ich+width<=nchan:\n                width += 1\n                ind = range(ich, min(ich+width, nchan) )\n                snr = sum(src_c[ind] - bgd_c[ind])\n            if snr > 0:\n                snr /= np.sqrt(sum(src_c[ind] + bgd_c[ind]))\n            while (snr < min_snr) and (ich+width < nchan):\n                ind = range(ich, ich+width)\n                if ind[-1] >= nchan:\n                    ind = range(ich, nchan)\n                    break\n\n                snr = sum(src_c[ind] - bgd_c[ind])\n                if snr <= 0:\n                    width += 1; continue\n                snr /= np.sqrt(sum(src_c[ind] + bgd_c[ind]))\n                width += 1\n       \n        # do we have a min_counts requirement? # \n        if min_counts:\n            counts = sum(src_c[ind] - bgd_c[ind])\n            while (counts < min_counts) and (ich+width < nchan):\n                ind = range(ich, ich+width)\n                if ind[-1] >= nchan:\n                    ind = range(ich, nchan)\n                    break\n                counts = sum(src_c[ind] - bgd_c[ind])\n                width += 1\n        ich += len(ind)\n        if ich < nchan: ibin[ich] = 1\n    # --------------------- #\n\n\n    # ------------------ #\n    # write the grouping #\n    \n    if write_chan:\n        # write an ascii file and use grppha #\n        ichan = np.arange(nchan)[ibin==1]\n        if ichan[-1] < nchan-1:\n            ichan = np.append(ichan, nchan)\n        bins = []\n        for ich in range(len(ichan)-1):\n            bins.append([ichan[ich], ichan[ich+1]-1, ichan[ich+1]-ichan[ich]])\n        txt = '\\n'.join(['{} {} {}'.format(*x) for x in bins])\n        with open('tmp_chans.dat', 'w') as fp: fp.write(txt)\n        os.system('rm {0} &> /dev/null'.format(out_file))\n        os.system('grppha {} {} \"group tmp_chans.dat&exit\"'.format(spec_file, out_file))\n    else:\n        # modify the file with pyfits #\n        os.system('rm {} &> /dev/null'.format(out_file))\n        os.system('grppha {} {} \"group min 20&exit\" &> /dev/null'.format(spec_file, out_file))\n        with pyfits.open(out_file) as fp:\n            hdu = fp['SPECTRUM']\n            orig_cols = hdu.columns\n            orig_cols['GROUPING'].array = np.array(ibin, np.int) \n            cols = pyfits.ColDefs(orig_cols)\n            tbl = pyfits.BinTableHDU.from_columns(cols)\n            hdu.header.update(tbl.header.copy())\n            tbl.header = hdu.header.copy()\n            grp = pyfits.HDUList([fp[0],tbl])\n            #os.system('rm {0} &> /dev/null'.format(out_file))\n            grp.writeto(out_file, overwrite=True)\n        print('Grouped file {} written sucessfully'.format(out_file))\n    # ------------------ #\n", "meta": {"hexsha": "ba049e1be8f325c3cc2702815c2b04ac2f1d7cd1", "size": 8588, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/ogrppha.py", "max_stars_repo_name": "abduzoghbi/aztools", "max_stars_repo_head_hexsha": "949cc2ec0dbb4426be0d39c5c9832243c4dbde43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/ogrppha.py", "max_issues_repo_name": "abduzoghbi/aztools", "max_issues_repo_head_hexsha": "949cc2ec0dbb4426be0d39c5c9832243c4dbde43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/ogrppha.py", "max_forks_repo_name": "abduzoghbi/aztools", "max_forks_repo_head_hexsha": "949cc2ec0dbb4426be0d39c5c9832243c4dbde43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2362869198, "max_line_length": 94, "alphanum_fraction": 0.5163018165, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 2306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.1985179476967386}}
{"text": "import itertools\nimport logging\nimport math\nimport os\nimport string\nimport subprocess\nimport tempfile\nfrom collections import defaultdict, Counter\nfrom dataclasses import dataclass, field\nfrom typing import Dict, Iterable, List, Tuple, Optional, Set\n\nimport numpy\n\nfrom eltetrado.model import Atom3D, Structure3D, Structure2D, BasePair3D, Residue3D, GlycosidicBond, ONZ, \\\n    GbaTetradClassification, Ion, Direction, LoopType, ONZM, GbaQuadruplexClassification, LoopClassification\n\nlogging.basicConfig(level=os.environ.get(\"LOGLEVEL\", \"INFO\"))\n\n\n@dataclass(order=True)\nclass Tetrad:\n    @staticmethod\n    def is_valid(nt1: Residue3D, nt2: Residue3D, nt3: Residue3D, nt4: Residue3D,\n                 pair_dictionary: Dict[Tuple[Residue3D, Residue3D], BasePair3D]) -> bool:\n        lw1 = pair_dictionary[(nt1, nt2)].lw\n        lw2 = pair_dictionary[(nt2, nt3)].lw\n        lw3 = pair_dictionary[(nt3, nt4)].lw\n        lw4 = pair_dictionary[(nt4, nt1)].lw\n        for lw_i, lw_j in ((lw1, lw4), (lw2, lw1), (lw3, lw2), (lw4, lw3)):\n            if lw_i.name[1] == lw_j.name[2]:\n                return False\n        return True\n\n    nt1: Residue3D\n    nt2: Residue3D\n    nt3: Residue3D\n    nt4: Residue3D\n    pair_12: BasePair3D\n    pair_23: BasePair3D\n    pair_34: BasePair3D\n    pair_41: BasePair3D\n    onz: ONZ = field(init=False)\n    gba_class: Optional[GbaTetradClassification] = field(init=False)\n    planarity_deviation: float = field(init=False)\n    ions_channel: List[Atom3D] = field(default_factory=list)\n    ions_outside: Dict[Residue3D, List[Atom3D]] = field(default_factory=dict)\n\n    def __post_init__(self):\n        self.reorder_to_match_5p_3p()\n        self.planarity_deviation = self.__calculate_planarity_deviation()\n\n    def reorder_to_match_5p_3p(self):\n        # transform into (0, 1, 2, 3)\n        ni, nj, nk, nl = map(lambda nt: nt.index, self.nucleotides)\n        indices = sorted((ni, nj, nk, nl))\n        ni, nj, nk, nl = (indices.index(x) for x in (ni, nj, nk, nl))\n\n        nmin = min(ni, nj, nk, nl)\n        if nmin == ni:\n            pass\n        elif nmin == nj:\n            self.nt1, self.nt2, self.nt3, self.nt4 = self.nt2, self.nt3, self.nt4, self.nt1\n            self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23, self.pair_34, self.pair_41, self.pair_12\n        elif nmin == nk:\n            self.nt1, self.nt2, self.nt3, self.nt4 = self.nt3, self.nt4, self.nt1, self.nt2\n            self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34, self.pair_41, self.pair_12, self.pair_23\n        else:\n            self.nt1, self.nt2, self.nt3, self.nt4 = self.nt4, self.nt1, self.nt2, self.nt3\n            self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41, self.pair_12, self.pair_23, self.pair_34\n\n        # flip order if necessary\n        if self.pair_12.score() > self.pair_41.reverse().score():\n            self.nt1, self.nt2, self.nt3, self.nt4 = self.nt1, self.nt4, self.nt3, self.nt2\n            self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse()\n\n        # ONZ and da Silva's classification are valid in 5'-3' order\n        self.onz = self.__classify_onz()\n        self.gba_class = self.__classify_by_gba()\n\n    def reorder_to_match_other_tetrad(self, order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D]):\n        if order == (self.nt1, self.nt2, self.nt3, self.nt4):\n            pass\n        elif order == (self.nt2, self.nt3, self.nt4, self.nt1):\n            self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23, self.pair_34, self.pair_41, self.pair_12\n        elif order == (self.nt3, self.nt4, self.nt1, self.nt2):\n            self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34, self.pair_41, self.pair_12, self.pair_23\n        elif order == (self.nt4, self.nt1, self.nt2, self.nt3):\n            self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41, self.pair_12, self.pair_23, self.pair_34\n        elif order == (self.nt4, self.nt3, self.nt2, self.nt1):\n            self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse()\n        elif order == (self.nt3, self.nt2, self.nt1, self.nt4):\n            self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_23.reverse(), self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse()\n        elif order == (self.nt2, self.nt1, self.nt4, self.nt3):\n            self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_12.reverse(), self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse()\n        elif order == (self.nt1, self.nt4, self.nt3, self.nt2):\n            self.pair_12, self.pair_23, self.pair_34, self.pair_41 = self.pair_41.reverse(), self.pair_34.reverse(), self.pair_23.reverse(), self.pair_12.reverse()\n        else:\n            raise RuntimeError(f'Cannot apply order: {order}')\n\n        self.nt1, self.nt2, self.nt3, self.nt4 = order\n\n    def __classify_onz(self) -> ONZ:\n        # transform into (0, 1, 2, 3)\n        ni, nj, nk, nl = (nt.index for nt in self.nucleotides)\n        indices = sorted((ni, nj, nk, nl))\n        ni, nj, nk, nl = (indices.index(x) for x in (ni, nj, nk, nl))\n\n        while ni != 0:\n            ni, nj, nk, nl = nl, ni, nj, nk\n\n        order = (nj, nk, nl)\n        if order == (1, 2, 3):\n            return ONZ.O_PLUS\n        elif order == (3, 2, 1):\n            return ONZ.O_MINUS\n        elif order == (1, 3, 2):\n            return ONZ.N_PLUS\n        elif order == (2, 3, 1):\n            return ONZ.N_MINUS\n        elif order == (2, 1, 3):\n            return ONZ.Z_PLUS\n        elif order == (3, 1, 2):\n            return ONZ.Z_MINUS\n\n        raise RuntimeError(f'Impossible combination: {ni} {nj} {nk} {nl}')\n\n    def __classify_by_gba(self) -> Optional[GbaTetradClassification]:\n        \"\"\"\n        See: Webba da Silva, M. (2007). Geometric Formalism for DNA Quadruplex Folding.\n        Chemistry - A European Journal, 13(35), 9738–9745. https://doi.org/10.1002/chem.200701255\n\n        :return: Classification according to Webba da Silva or n/a\n        \"\"\"\n        # without all nucleotides having a valid syn/anti, this classification is impossible\n        if not all([nt.chi_class in (GlycosidicBond.syn, GlycosidicBond.anti) for nt in self.nucleotides]):\n            return None\n\n        # this will create a 4-letter string made of 's' for syn or 'a' for anti\n        fingerprint = ''.join([nt.chi_class.value[0] for nt in self.nucleotides])\n\n        # this dict has all classes mapped to fingerprints\n        gba_classes = {\n            'aass': GbaTetradClassification.Ia,\n            'ssaa': GbaTetradClassification.Ib,\n            'asas': GbaTetradClassification.IIa,\n            'sasa': GbaTetradClassification.IIb,\n            'asaa': GbaTetradClassification.IIIa,\n            'sass': GbaTetradClassification.IIIb,\n            'aaas': GbaTetradClassification.IVa,\n            'sssa': GbaTetradClassification.IVb,\n            'aasa': GbaTetradClassification.Va,\n            'ssas': GbaTetradClassification.Vb,\n            'assa': GbaTetradClassification.VIa,\n            'saas': GbaTetradClassification.VIb,\n            'asss': GbaTetradClassification.VIIa,\n            'saaa': GbaTetradClassification.VIIb,\n            'aaaa': GbaTetradClassification.VIIIa,\n            'ssss': GbaTetradClassification.VIIIb\n        }\n\n        if fingerprint not in gba_classes:\n            logging.error(f'Impossible combination of syn/anti: {[nt.chi_class for nt in self.nucleotides]}')\n            return None\n        return gba_classes[fingerprint]\n\n    def __calculate_planarity_deviation(self) -> float:\n        outer = [nt.outermost_atom for nt in self.nucleotides]\n        inner = [nt.innermost_atom for nt in self.nucleotides]\n        return numpy.linalg.norm(center_of_mass(outer) - center_of_mass(inner))\n\n    @property\n    def nucleotides(self) -> Tuple[Residue3D, Residue3D, Residue3D, Residue3D]:\n        return self.nt1, self.nt2, self.nt3, self.nt4\n\n    def __hash__(self):\n        return hash(frozenset([self.nt1, self.nt2, self.nt3, self.nt4]))\n\n    def __str__(self):\n        return f'    ' \\\n               f'{self.nt1.full_name} {self.nt2.full_name} {self.nt3.full_name} {self.nt4.full_name} ' \\\n               f'{self.pair_12.lw.value} {self.pair_23.lw.value} {self.pair_34.lw.value} {self.pair_41.lw.value} ' \\\n               f'{self.onz.value} {self.gba_class.value} ' \\\n               f'planarity={round(self.planarity_deviation, 2)} ' \\\n               f'{self.__ions_channel_str()} ' \\\n               f'{self.__ions_outside_str()}\\n'\n\n    def chains(self) -> Set[str]:\n        return set([nt.chain for nt in self.nucleotides])\n\n    def is_disjoint(self, other) -> bool:\n        return frozenset(self.nucleotides).isdisjoint(frozenset(other.nucleotides))\n\n    def center(self) -> numpy.ndarray:\n        return center_of_mass(self.outer_and_inner_atoms())\n\n    def outer_and_inner_atoms(self) -> List[Atom3D]:\n        return list(map(lambda residue: residue.outermost_atom, self.nucleotides)) + \\\n               list(map(lambda residue: residue.innermost_atom, self.nucleotides))\n\n    def __ions_channel_str(self) -> str:\n        if self.ions_channel:\n            return 'ions_channel=' + ','.join([atom.atomName for atom in self.ions_channel])\n        return ''\n\n    def __ions_outside_str(self) -> str:\n        if self.ions_outside:\n            result = []\n            for residue, ions in self.ions_outside.items():\n                result.append(f'{residue.full_name}: [{\",\".join([ion.atomName for ion in ions])}]')\n            return 'ions_outside=' + ' '.join(result)\n        return ''\n\n\n@dataclass\nclass TetradPair:\n    tetrad1: Tetrad\n    tetrad2: Tetrad\n    stacked: Dict[Residue3D, Residue3D]\n    tetrad2_nts_best_order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D] = field(init=False)\n    direction: Direction = field(init=False)\n    rise: float = field(init=False)\n    twist: float = field(init=False)\n\n    def __post_init__(self):\n        self.tetrad2_nts_best_order = (\n            self.stacked[self.tetrad1.nt1], self.stacked[self.tetrad1.nt2],\n            self.stacked[self.tetrad1.nt3], self.stacked[self.tetrad1.nt4]\n        )\n        self.direction = self.__determine_direction()\n        self.rise = self.__calculate_rise()\n        self.twist = self.__calculate_twist()\n\n    def __determine_direction(self) -> Direction:\n        indices1 = list(map(lambda nt: nt.index, self.tetrad1.nucleotides))\n        indices2 = list(map(lambda nt: nt.index, self.tetrad2_nts_best_order))\n\n        # count directions 5' -> 3' as +1 or -1\n        counter = Counter(1 if j - i > 0 else -1 for i, j in zip(indices1, indices2))\n        direction, count = counter.most_common()[0]\n\n        if count == 4:\n            # all in the same direction\n            return Direction.parallel\n        elif count == 2:\n            # two in +, one in - direction\n            return Direction.antiparallel\n\n        return Direction.hybrid\n\n    def __calculate_rise(self) -> float:\n        t1 = self.tetrad1.outer_and_inner_atoms()\n        t2 = self.tetrad2.outer_and_inner_atoms()\n        return numpy.linalg.norm(center_of_mass(t1) - center_of_mass(t2))\n\n    def __calculate_twist(self) -> float:\n        nt1_1, nt1_2, _, _ = self.tetrad1.nucleotides\n        nt2_1, nt2_2, _, _ = self.tetrad2_nts_best_order\n\n        v1 = nt1_1.find_atom(\"C1'\").coordinates() - nt1_2.find_atom(\"C1'\").coordinates()\n        v1 = v1 / numpy.linalg.norm(v1)\n        v2 = nt2_1.find_atom(\"C1'\").coordinates() - nt2_2.find_atom(\"C1'\").coordinates()\n        v2 = v2 / numpy.linalg.norm(v2)\n        return math.degrees(numpy.arccos(numpy.clip(numpy.dot(v1, v2), -1.0, 1.0)))\n\n    def __str__(self):\n        return f'      direction={self.direction.value} rise={round(self.rise, 2)} twist={round(self.twist, 2)}\\n'\n\n\n@dataclass\nclass Tract:\n    nucleotides: List[Residue3D]\n\n    def __str__(self):\n        return f'      {\", \".join(map(lambda nt: nt.full_name, self.nucleotides))}'\n\n\n@dataclass\nclass Loop:\n    nucleotides: List[Residue3D]\n    loop_type: Optional[LoopType]\n\n    def __str__(self):\n        return f'      {self.loop_type.value if self.loop_type else \"n/a\"} ' \\\n               f'{\", \".join(map(lambda nt: nt.full_name, self.nucleotides))}'\n\n\n@dataclass\nclass Quadruplex:\n    tetrads: List[Tetrad]\n    tetrad_pairs: List[TetradPair]\n    structure3d: Structure3D\n    onzm: Optional[ONZM] = field(init=False)\n    gba_classes: List[GbaQuadruplexClassification] = field(init=False)\n    tracts: List[Tract] = field(init=False)\n    loops: List[Loop] = field(init=False)\n    loop_class: Optional[LoopClassification] = field(init=False)\n\n    def __post_init__(self):\n        self.onzm = self.__classify_onzm()\n        self.gba_classes = self.__classify_by_gba()\n        self.tracts = self.__find_tracts()\n        self.loops = self.__find_loops()\n        self.loop_class = self.__classify_by_loops()\n\n    def __classify_onzm(self) -> Optional[ONZM]:\n        if len(self.tetrads) == 1:\n            return None\n        if any([t.onz is None for t in self.tetrads]):\n            return None\n\n        counter = Counter([t.onz.value[0] for t in self.tetrads])\n        onz, support = counter.most_common()[0]\n        if support != len(self.tetrads):\n            onz = 'M'\n\n        counter = Counter([tp.direction.value[0] for tp in self.tetrad_pairs])\n        direction, support = counter.most_common()[0]\n        if support != len(self.tetrad_pairs):\n            direction = 'h'\n\n        counter = Counter([t.onz.value[1] for t in self.tetrads])\n        plus_minus, support = counter.most_common()[0]\n        if support != len(self.tetrads):\n            plus_minus = '*'\n\n        return ONZM.from_value(f'{onz}{direction}{plus_minus}')\n\n    def __classify_by_gba(self) -> List[GbaQuadruplexClassification]:\n        gbas = set()\n        for t in self.tetrads:\n            gba = t.gba_class\n            if gba is not None:\n                gbas.add(gba.value[:-1])  # discard 'a' or 'b' subvariant\n        roman_numerals = {'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5, 'VI': 6, 'VII': 7, 'VIII': 8}\n        gbas = sorted(gbas, key=lambda gba: roman_numerals.get(gba, 100))\n        return list(map(lambda x: GbaQuadruplexClassification[x], gbas))\n\n    def __find_tracts(self) -> List[Tract]:\n        tracts = [[self.tetrads[0].nt1], [self.tetrads[0].nt2], [self.tetrads[0].nt3], [self.tetrads[0].nt4]]\n        if len(self.tetrad_pairs) > 0:\n            for tetrad_pair in self.tetrad_pairs:\n                nt_dict = {\n                    tetrad_pair.tetrad1.nt1: tetrad_pair.tetrad2_nts_best_order[0],\n                    tetrad_pair.tetrad1.nt2: tetrad_pair.tetrad2_nts_best_order[1],\n                    tetrad_pair.tetrad1.nt3: tetrad_pair.tetrad2_nts_best_order[2],\n                    tetrad_pair.tetrad1.nt4: tetrad_pair.tetrad2_nts_best_order[3],\n                }\n                for i in range(4):\n                    tracts[i].append(nt_dict[tracts[i][-1]])\n        return [Tract(nts) for nts in tracts]\n\n    def __find_loops(self) -> List[Loop]:\n        if len(self.tetrads) == 1:\n            return []\n\n        loops = []\n        tetrad_nucleotides = sorted([nt for tetrad in self.tetrads for nt in tetrad.nucleotides],\n                                    key=lambda nt: nt.index)\n\n        for i in range(1, len(tetrad_nucleotides)):\n            nprev = tetrad_nucleotides[i - 1]\n            ncur = tetrad_nucleotides[i]\n            if ncur.index - nprev.index > 1 and ncur.chain == nprev.chain:\n                for tract in self.tracts:\n                    if nprev in tract.nucleotides and ncur in tract.nucleotides:\n                        break\n                else:\n                    nts = list(filter(lambda nt: nprev.index < nt.index < ncur.index, self.structure3d.residues))\n                    loop_type = self.__detect_loop_type(nprev, ncur)\n                    loops.append(Loop(nts, loop_type))\n        return loops\n\n    def __detect_loop_type(self, nt_first: Residue3D, nt_last: Residue3D) -> Optional[LoopType]:\n        tetrad_with_first = self.__find_tetrad_with_nt(nt_first)\n        tetrad_with_last = self.__find_tetrad_with_nt(nt_last)\n\n        if tetrad_with_first is None or tetrad_with_last is None:\n            logging.warning(f'Failed to classify the loop between {nt_first} and {nt_last}')\n            return None\n\n        if tetrad_with_first == tetrad_with_last:\n            # diagonal or laterals happen when first and last nt of a loop is in the same tetrad\n            sign = self.__detect_loop_sign(nt_first, nt_last, tetrad_with_first)\n            if sign is not None:\n                return LoopType.from_value(f'lateral{sign}')\n            return LoopType.diagonal\n\n        tract_with_last = self.__find_tract_with_nt(nt_last)\n        if tract_with_last is not None:\n            # search along the tract to check what pairs with nt_first\n            for nt in tract_with_last.nucleotides:\n                if nt in tetrad_with_first.nucleotides:\n                    sign = self.__detect_loop_sign(nt_first, nt, tetrad_with_first)\n                    if sign is not None:\n                        return LoopType.from_value(f'propeller{sign}')\n        logging.warning(f'Failed to classify the loop between {nt_first} and {nt_last}')\n        return None\n\n    def __find_tetrad_with_nt(self, nt: Residue3D) -> Optional[Tetrad]:\n        for tetrad in self.tetrads:\n            if nt in tetrad.nucleotides:\n                return tetrad\n        return None\n\n    def __find_tract_with_nt(self, nt: Residue3D) -> Optional[Tract]:\n        for tract in self.tracts:\n            if nt in tract.nucleotides:\n                return tract\n        return None\n\n    def __detect_loop_sign(self, first: Residue3D, last: Residue3D, tetrad: Tetrad) -> Optional[str]:\n        for pair in [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]:\n            # main check\n            if pair.nt1 == first and pair.nt2 == last:\n                if pair.score() < pair.reverse().score():\n                    return '-'\n                return '+'\n            # reverse check\n            if pair.nt1 == last and pair.nt2 == first:\n                if pair.score() < pair.reverse().score():\n                    return '+'\n                return '-'\n        return None\n\n    def __classify_by_loops(self) -> Optional[LoopClassification]:\n        if len(self.loops) != 3 or any([loop.loop_type is None for loop in self.loops]):\n            return None\n\n        loop_classes = {\n            'ppp': '1',\n            'ppl': '2',\n            'plp': '3',\n            'lpp': '4',\n            'pdp': '5',\n            'lll': '6',\n            'llp': '7',\n            'lpl': '8',\n            'pll': '9',\n            'pdl': '10',\n            'ldl': '11',\n            'dpd': '12',\n            'ldp': '13'\n        }\n        fingerprint = ''.join([loop.loop_type.value[0] for loop in self.loops])\n        if fingerprint not in loop_classes:\n            logging.error(f'Unknown loop classification: {fingerprint}')\n            return None\n        subtype = 'a' if self.loops[0 if fingerprint != 'dpd' else 1].loop_type.value[-1] == '-' else 'b'\n        return LoopClassification.from_value(f'{loop_classes[fingerprint]}{subtype}')\n\n    def __str__(self):\n        builder = ''\n        if len(self.tetrads) == 1:\n            builder += '  single tetrad\\n'\n            builder += str(self.tetrads[0])\n        else:\n            builder += f'  {self.onzm.value if self.onzm is not None else \"R\"}'\n            builder += f' {\",\".join(map(lambda gba: gba.value, self.gba_classes))}'\n            if self.loop_class:\n                builder += f' {self.loop_class.value} {self.loop_class.loop_progression()}'\n            else:\n                builder += f' n/a'\n            builder += f' quadruplex with {len(self.tetrads)} tetrads\\n'\n            builder += str(self.tetrad_pairs[0].tetrad1)\n            for tetrad_pair in self.tetrad_pairs:\n                builder += str(tetrad_pair)\n                builder += str(tetrad_pair.tetrad2)\n            if self.tracts:\n                builder += '\\n    Tracts:\\n'\n                for tract in self.tracts:\n                    builder += f'{tract}\\n'\n            if self.loops:\n                builder += '\\n    Loops:\\n'\n                for loop in self.loops:\n                    builder += f'{loop}\\n'\n            builder += '\\n'\n        return builder\n\n\n@dataclass\nclass Helix:\n    tetrads: List[Tetrad]\n    tetrad_pairs: List[TetradPair]\n    structure3d: Structure3D\n    quadruplexes: List[Quadruplex] = field(init=False)\n\n    def __post_init__(self):\n        self.quadruplexes = self.__find_quadruplexes()\n\n    def __find_quadruplexes(self):\n        if len(self.tetrad_pairs) == 0:\n            return [Quadruplex(self.tetrads, [], self.structure3d)]\n\n        quadruplexes = list()\n        tetrads = list()\n\n        for tetrad in [self.tetrad_pairs[0].tetrad1] + [tetrad_pair.tetrad2 for tetrad_pair in self.tetrad_pairs]:\n            if tetrads:\n                if tetrad.chains().isdisjoint(tetrads[-1].chains()):\n                    quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d))\n                    tetrads = list()\n            tetrads.append(tetrad)\n\n        quadruplexes.append(Quadruplex(tetrads, self.__filter_tetrad_pairs(tetrads), self.structure3d))\n\n        return quadruplexes\n\n    def __filter_tetrad_pairs(self, tetrads: List[Tetrad]) -> List[TetradPair]:\n        chains = set()\n        for tetrad in tetrads:\n            chains.update(tetrad.chains())\n\n        def check_tetrad(t: Tetrad) -> bool:\n            return not t.chains().isdisjoint(chains)\n\n        def check_pair(tp: TetradPair) -> bool:\n            return check_tetrad(tp.tetrad1) and check_tetrad(tp.tetrad2)\n\n        return list(filter(check_pair, self.tetrad_pairs))\n\n    def __str__(self):\n        builder = ''\n        if len(self.tetrads) > 1:\n            builder += f'n4-helix with {len(self.tetrads)} tetrads\\n'\n            for quadruplex in self.quadruplexes:\n                builder += str(quadruplex)\n        elif len(self.tetrads) == 1:\n            builder += 'single tetrad without stacking\\n'\n            builder += str(self.tetrads[0])\n        return builder\n\n\n@dataclass\nclass Analysis:\n    structure2d: Structure2D\n    structure3d: Structure3D\n    strict: bool\n    no_reorder: bool\n    stacking_mismatch: int\n    base_pairs: List[BasePair3D] = field(init=False)\n    base_pair_graph: Dict[Residue3D, List[Residue3D]] = field(init=False)\n    base_pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] = field(init=False)\n    stacking_graph: Dict[Residue3D, List[Residue3D]] = field(init=False)\n    tetrads: List[Tetrad] = field(init=False)\n    tetrad_scores: Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple, Tuple]]] = field(init=False)\n    tetrad_pairs: List[TetradPair] = field(init=False)\n    helices: List[Helix] = field(init=False)\n    ions: List[Atom3D] = field(init=False)\n    sequence: str = field(init=False)\n    line1: str = field(init=False)\n    line2: str = field(init=False)\n    shifts: Dict[Residue3D, int] = field(init=False)\n\n    def __post_init__(self):\n        self.base_pairs = self.structure3d.base_pairs(self.structure2d)\n        self.base_pair_graph = self.structure3d.base_pair_graph(self.structure2d, self.strict)\n        self.base_pair_dict = self.structure3d.base_pair_dict(self.structure2d, self.strict)\n        self.stacking_graph = self.structure3d.stacking_graph(self.structure2d)\n        self.tetrads = self.__find_tetrads(self.no_reorder)\n        self.tetrad_scores = self.__calculate_tetrad_scores()\n        self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch)\n        self.helices = self.__find_helices()\n\n        if not self.no_reorder:\n            self.__find_best_chain_order()\n\n        self.sequence, self.line1, self.line2, self.shifts = self.__generate_twoline_dotbracket()\n        self.ions = self.__find_ions()\n        self.__assign_ions_to_tetrads()\n\n    def __find_tetrads(self, no_reorder=False) -> List[Tetrad]:\n        # search for a tetrad: i -> j -> k -> l\n        #                      ^--------------^\n        tetrads = []\n        for i in self.base_pair_graph:\n            for j in filter(lambda x: x != i, self.base_pair_graph[i]):\n                for k in filter(lambda x: x not in (i, j), self.base_pair_graph[j]):\n                    for l in filter(lambda x: x not in (i, j, k) and i in self.base_pair_graph[x],\n                                    self.base_pair_graph[k]):\n                        if Tetrad.is_valid(i, j, k, l, self.base_pair_dict):\n                            pair_12 = self.base_pair_dict[(i, j)]\n                            pair_23 = self.base_pair_dict[(j, k)]\n                            pair_34 = self.base_pair_dict[(k, l)]\n                            pair_41 = self.base_pair_dict[(l, i)]\n                            tetrads.append(Tetrad(i, j, k, l, pair_12, pair_23, pair_34, pair_41))\n\n        # build graph of tetrads\n        while tetrads:\n            graph = defaultdict(list)\n            for (ti, tj) in itertools.combinations(tetrads, 2):\n                if not ti.is_disjoint(tj):\n                    graph[ti].append(tj)\n                    graph[tj].append(ti)\n\n            # remove tetrad which conflicts the most with others\n            # in case of a tie, remove one which has the worst planarity deviation\n            candidates = sorted(tetrads, key=lambda t: (len(graph[t]), t.planarity_deviation),\n                                reverse=True)\n            if len(graph[candidates[0]]) > 0:\n                tetrads.remove(candidates[0])\n            else:\n                break\n\n        return sorted(tetrads, key=lambda t: min(map(lambda nt: nt.index, t.nucleotides)))\n\n    def __calculate_tetrad_scores(self) \\\n            -> Dict[Tetrad, Dict[Tetrad, Tuple[int, Tuple, Tuple]]]:\n        def is_next_by_stacking(nt1: Residue3D, nt2: Residue3D) -> bool:\n            return nt2 in self.stacking_graph.get(nt1, [])\n\n        def is_next_sequentially(nt1: Residue3D, nt2: Residue3D) -> bool:\n            return nt1.chain == nt2.chain and abs(nt1.index - nt2.index) == 1\n\n        tetrad_scores = defaultdict(dict)\n\n        for ti, tj in itertools.combinations(self.tetrads, 2):\n            nts1 = ti.nucleotides\n            best_score = 0\n            best_score_sequential = 0\n            best_score_stacking = 0\n            best_order = tj.nucleotides\n\n            n1, n2, n3, n4 = tj.nucleotides\n            viable_permutations = [(n1, n2, n3, n4), (n2, n3, n4, n1), (n3, n4, n1, n2), (n4, n1, n2, n3),\n                                   (n1, n4, n3, n2), (n4, n3, n2, n1), (n3, n2, n1, n4), (n2, n1, n4, n3)]\n\n            for nts2 in viable_permutations:\n                score_stacking = [1 if is_next_by_stacking(nts1[i], nts2[i]) else 0 for i in range(4)]\n                score_sequential = [1 if is_next_sequentially(nts1[i], nts2[i]) else 0 for i in range(4)]\n                score = sum([max(score_stacking[i], score_sequential[i]) for i in range(4)])\n                score_sequential = sum(score_sequential)\n                score_stacking = sum(score_stacking)\n\n                if (score, score_sequential, score_stacking) > (best_score, best_score_sequential, best_score_stacking):\n                    best_score, best_score_sequential, best_score_stacking = score, score_sequential, score_stacking\n                    best_order = nts2\n                if best_score == 4:\n                    break\n\n            tetrad_scores[ti][tj] = (best_score, nts1, best_order)\n            tetrad_scores[tj][ti] = (best_score, best_order, nts1)\n\n        return tetrad_scores\n\n    def __find_tetrad_pairs(self, stacking_mismatch: int) -> List[TetradPair]:\n        tetrads = list(self.tetrads)\n        best_score = 0\n        best_order = tetrads\n\n        for ti in tetrads:\n            score = 0\n            order = [ti]\n            candidates = set(self.tetrads) - {ti}\n\n            while candidates:\n                tj = max([tj for tj in candidates], key=lambda tk: self.tetrad_scores[ti][tk][0])\n                score += self.tetrad_scores[ti][tj][0]\n                order.append(tj)\n                candidates.remove(tj)\n                ti = tj\n\n            if score > best_score:\n                best_score = score\n                best_order = order\n\n            if best_score == (len(self.tetrads) - 1) * 4:\n                break\n\n        tetrad_pairs = []\n\n        for i in range(1, len(best_order)):\n            ti, tj = best_order[i - 1], best_order[i]\n            score = self.tetrad_scores[ti][tj][0]\n\n            if score >= (4 - stacking_mismatch):\n                nts1, nts2 = self.tetrad_scores[ti][tj][1:]\n                stacked = {nts1[i]: nts2[i] for i in range(4)}\n                stacked.update({v: k for k, v in stacked.items()})\n                tetrad_pairs.append(TetradPair(ti, tj, stacked))\n                order = (stacked[ti.nt1], stacked[ti.nt2], stacked[ti.nt3], stacked[ti.nt4])\n                tj.reorder_to_match_other_tetrad(order)\n\n        return tetrad_pairs\n\n    def __find_helices(self):\n        helices = []\n        helix_tetrads = []\n        helix_tetrad_pairs = []\n\n        for tp in self.tetrad_pairs:\n            ti, tj = tp.tetrad1, tp.tetrad2\n            if not helix_tetrads:\n                helix_tetrads.append(ti)\n            score = self.tetrad_scores[helix_tetrads[-1]][tj][0]\n            if score >= (4 - self.stacking_mismatch):\n                helix_tetrads.append(tj)\n                helix_tetrad_pairs.append(tp)\n            else:\n                helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d))\n                helix_tetrads = [ti, tj]\n                helix_tetrad_pairs = [tp]\n\n        if helix_tetrads:\n            helices.append(Helix(helix_tetrads, helix_tetrad_pairs, self.structure3d))\n\n        for tetrad in self.tetrads:\n            if not any([tetrad in helix.tetrads for helix in helices]):\n                helices.append(Helix([tetrad], [], self.structure3d))\n\n        return helices\n\n    def __find_best_chain_order(self):\n        chain_groups = self.__group_related_chains()\n        final_order = []\n\n        for chains in chain_groups:\n            best_permutation, best_score = chains, (1e10, 1e10)\n\n            if len(chains) > 1:\n                for permutation in itertools.permutations(chains):\n                    self.__reorder_chains(permutation)\n                    classifications = [t.onz for h in self.helices for t in h.tetrads]\n                    logging.debug(\n                        f'Checking reorder: {\" \".join(permutation)} {\" \".join(map(lambda c: c.value, classifications))}')\n\n                    onz_score = sum(c.score() for c in classifications)\n                    chain_order_score = self.__chain_order_score(permutation)\n                    score = (onz_score, chain_order_score)\n\n                    if score < best_score:\n                        best_score = score\n                        best_permutation = permutation\n                    elif score == best_score:\n                        # in case of a tie, pick permutation earlier in lexicographical sense\n                        if permutation < best_permutation:\n                            best_permutation = permutation\n\n            final_order.extend(best_permutation)\n\n        if len(final_order) > 1:\n            self.__reorder_chains(final_order)\n            classifications = [t.onz for h in self.helices for t in h.tetrads]\n            logging.debug(f'Selected chain order: {\" \".join(final_order)} '\n                          f'{\" \".join(map(lambda onz: onz.value, classifications))}')\n\n            self.tetrads = self.__find_tetrads(True)\n            self.tetrad_scores = self.__calculate_tetrad_scores()\n            self.tetrad_pairs = self.__find_tetrad_pairs(self.stacking_mismatch)\n            self.helices = self.__find_helices()\n\n    def __group_related_chains(self) -> List[List[str]]:\n        candidates = set()\n\n        for h in self.helices:\n            for t in h.tetrads:\n                candidates.add(frozenset([t.nt1.chain, t.nt2.chain, t.nt3.chain, t.nt4.chain]))\n\n        candidates = [set(c) for c in candidates]\n        changed = True\n\n        while changed:\n            changed = False\n\n            for i, j in itertools.combinations(range(len(candidates)), 2):\n                qi, qj = candidates[i], candidates[j]\n\n                if not qi.isdisjoint(qj):\n                    qi.update(qj)\n                    del candidates[j]\n                    changed = True\n                    break\n\n        candidates = sorted(candidates, key=lambda x: len(x), reverse=True)\n        groups = []\n\n        for candidate in candidates:\n            if any([group.issuperset(candidate) for group in groups]):\n                continue\n            groups.append(candidate)\n\n        return sorted([sorted(group) for group in groups], key=lambda x: x[0])\n\n    def __reorder_chains(self, chain_order: Iterable[str]):\n        i = 1\n        for chain in chain_order:\n            for nt in self.structure3d.residues:\n                if nt.chain == chain:\n                    nt.index = i\n                    i += 1\n        for nt in self.structure3d.residues:\n            if nt.chain not in chain_order:\n                nt.index = i\n                i += 1\n\n        if len(self.tetrad_pairs) > 0:\n            self.tetrad_pairs[0].tetrad1.reorder_to_match_5p_3p()\n            for tp in self.tetrad_pairs:\n                order = (tp.stacked[tp.tetrad1.nt1], tp.stacked[tp.tetrad1.nt2],\n                         tp.stacked[tp.tetrad1.nt3], tp.stacked[tp.tetrad1.nt4])\n                tp.tetrad2.reorder_to_match_5p_3p()  # this is required to recalculate ONZ\n                tp.tetrad2.reorder_to_match_other_tetrad(order)\n\n    def __chain_order_score(self, chain_order: Tuple[str, ...]) -> int:\n        chain_pairs = []\n        for h in self.helices:\n            for t in h.tetrads:\n                for p in [t.pair_12, t.pair_23, t.pair_34, t.pair_41]:\n                    c1 = p.nt1.chain\n                    c2 = p.nt2.chain\n                    if c1 != c2 and c1 in chain_order and c2 in chain_order:\n                        chain_pairs.append([c1, c2])\n        sum_sq = 0\n        for c1, c2 in chain_pairs:\n            sum_sq += (chain_order.index(c1) - chain_order.index(c2)) ** 2\n        return sum_sq\n\n    def __find_ions(self) -> List[Atom3D]:\n        metal_atom_names = set([ion.value.upper() for ion in Ion])\n        ions = []\n        used = set()\n        for residue in self.structure3d.residues:\n            for atom in residue.atoms:\n                if atom.atomName.upper() in metal_atom_names:\n                    coordinates = tuple(atom.coordinates())\n                    if coordinates not in used:\n                        ions.append(atom)\n                        used.add(coordinates)\n        return ions\n\n    def __assign_ions_to_tetrads(self) \\\n            -> Tuple[Dict[Tetrad, List[Atom3D]], Dict[Tuple[Tetrad, Residue3D], List[Atom3D]]]:\n        if len(self.tetrads) == 0:\n            return {}, {}\n\n        ions_channel = defaultdict(list)\n        ions_outside = defaultdict(list)\n\n        for ion in self.ions:\n            min_distance = math.inf\n            min_tetrad = self.tetrads[0]\n\n            for tetrad in self.tetrads:\n                distance = numpy.linalg.norm(ion.coordinates() - tetrad.center())\n                if distance < min_distance:\n                    min_distance = distance\n                    min_tetrad = tetrad\n\n            # TODO: verify threshold of 6A between an ion and tetrad channel\n            if min_distance < 6.0:\n                ions_channel[min_tetrad].append(ion)\n                continue\n\n            min_distance = math.inf\n            min_tetrad = self.tetrads[0]\n            min_nt = min_tetrad.nt1\n\n            for tetrad in self.tetrads:\n                for nt in tetrad.nucleotides:\n                    for atom in nt.atoms:\n                        distance = numpy.linalg.norm(ion.coordinates() - atom.coordinates())\n                        if distance < min_distance:\n                            min_distance = distance\n                            min_tetrad = tetrad\n                            min_nt = nt\n\n            # TODO: verify threshold of 3A between an ion and an atom\n            if min_distance < 3.0:\n                ions_outside[(min_tetrad, min_nt)].append(ion)\n                continue\n\n            logging.debug(f'Skipping an ion, because it is too far from any tetrad (distance={min_distance})')\n\n        for tetrad, ions in ions_channel.items():\n            tetrad.ions_channel = ions\n        for pair, ions in ions_outside.items():\n            tetrad, residue = pair\n            tetrad.ions_outside[residue] = ions\n\n    def __generate_twoline_dotbracket(self) -> Tuple[str, str, str, Dict[Residue3D, int]]:\n        layer1, layer2 = [], []\n        for tetrad in self.tetrads:\n            layer1.extend([tetrad.pair_12, tetrad.pair_34])\n            layer2.extend([tetrad.pair_23, tetrad.pair_41])\n        sequence, line1, shifts = self.__elimination_conflicts(layer1)\n        _, line2, _ = self.__elimination_conflicts(layer2)\n        return sequence, line1, line2, shifts\n\n    def __elimination_conflicts(self, pairs: List[BasePair3D]) -> Tuple[str, str, Dict[Residue3D, int]]:\n        orders = dict()\n        order = 0\n        queue = list(pairs)\n        removed = []\n\n        while queue:\n            conflicts = defaultdict(list)\n            for pi, pj in itertools.combinations(queue, 2):\n                if pi.conflicts_with(pj):\n                    conflicts[pi].append(pj)\n                    conflicts[pj].append(pi)\n            if conflicts:\n                pair, _ = max(conflicts.items(), key=lambda x: (len(x[1]), x[0].nt1))\n                removed.append(pair)\n                queue.remove(pair)\n            else:\n                orders.update({pair: order for pair in queue})\n                queue, removed = removed, []\n                order += 1\n\n        opening = '([{<' + string.ascii_uppercase\n        closing = ')]}>' + string.ascii_lowercase\n        dotbracket = dict()\n        for pair, order in orders.items():\n            nt1, nt2 = sorted([pair.nt1, pair.nt2])\n            dotbracket[nt1] = opening[order]\n            dotbracket[nt2] = closing[order]\n\n        sequence = ''\n        structure = ''\n        shifts = dict()\n        shift_value = 0\n        chain = None\n        for nt in sorted(filter(lambda nt: nt.is_nucleotide, self.structure3d.residues), key=lambda nt: nt.index):\n            if chain and chain != nt.chain:\n                sequence += '-'\n                structure += '-'\n                shift_value += 1\n            sequence += nt.one_letter_name\n            structure += dotbracket.get(nt, '.')\n            shifts[nt] = shift_value\n            chain = nt.chain\n        return sequence, structure, shifts\n\n    def __str__(self):\n        builder = f'Chain order: {\" \".join(self.__chain_order())}\\n'\n        for helix in self.helices:\n            builder += str(helix)\n        builder += f'{self.sequence}\\n{self.line1}\\n{self.line2}'\n        return builder\n\n    def __chain_order(self) -> List[str]:\n        only_nucleic_acids = filter(lambda nt: nt.is_nucleotide, self.structure3d.residues)\n        return list({nt.chain: 0 for nt in sorted(only_nucleic_acids, key=lambda nt: nt.index)}.keys())\n\n    def canonical(self) -> List[BasePair3D]:\n        return [base_pair for base_pair in self.base_pairs if base_pair.is_canonical()]\n\n\n@dataclass\nclass Visualizer:\n    analysis: Analysis\n    tetrads: List[Tetrad]\n    complete2d: bool\n    onz_dict: Dict[BasePair3D, ONZ] = field(init=False)\n\n    def __post_init__(self):\n        self.onz_dict = {pair: tetrad.onz for tetrad in self.tetrads for pair in\n                         [tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pair_41]}\n\n    def visualize(self, prefix: str, suffix: str):\n        fasta = tempfile.NamedTemporaryFile('w+', suffix='.fasta')\n        fasta.write(f'>{prefix}-{suffix}\\n')\n        fasta.write(self.analysis.sequence)\n        fasta.flush()\n\n        layer1, layer2 = [], []\n        for tetrad in self.tetrads:\n            layer1.extend([tetrad.pair_12, tetrad.pair_34])\n            layer2.extend([tetrad.pair_23, tetrad.pair_41])\n        helix1 = self.__to_helix(layer1, self.analysis.canonical() if self.complete2d else [])\n        helix2 = self.__to_helix(layer2)\n\n        currdir = os.path.dirname(os.path.realpath(__file__))\n        output_pdf = f'{prefix}-{suffix}.pdf'\n        run = subprocess.run([os.path.join(currdir, 'quadraw.R'), fasta.name, helix1.name, helix2.name, output_pdf],\n                             stdout=subprocess.PIPE,\n                             stderr=subprocess.PIPE)\n        if run.returncode == 0:\n            print('\\nPlot:', output_pdf)\n        else:\n            logging.error(f'Failed to prepare visualization, reason:\\n  {run.stderr.decode()}')\n\n    def __to_helix(self, layer: List[BasePair3D],\n                   canonical: Optional[List[BasePair3D]] = None) -> tempfile.NamedTemporaryFile():\n        onz_value = {ONZ.O_PLUS: 1, ONZ.O_MINUS: 2, ONZ.N_PLUS: 3, ONZ.N_MINUS: 4, ONZ.Z_PLUS: 5, ONZ.Z_MINUS: 6}\n        nucleotides = self.analysis.structure3d.residues\n        shifts = self.analysis.shifts\n\n        helix = tempfile.NamedTemporaryFile('w+', suffix='.helix')\n        helix.write(f'#{len(self.analysis.sequence) + 1}\\n')\n        helix.write('i\\tj\\tlength\\tvalue\\n')\n\n        for pair in layer:\n            x, y = pair.nt1, pair.nt2\n            x, y = nucleotides.index(x) + 1 + shifts[x], nucleotides.index(y) + 1 + shifts[y]\n            onz = self.onz_dict[pair]\n            helix.write(f'{x}\\t{y}\\t1\\t{onz_value.get(onz, 7)}\\n')\n        if canonical:\n            for pair in canonical:\n                x, y = pair.nt1, pair.nt2\n                x, y = nucleotides.index(x) + 1 + shifts[x], nucleotides.index(y) + 1 + shifts[y]\n                helix.write(f'{x}\\t{y}\\t1\\t8\\n')\n\n        helix.flush()\n        return helix\n\n\nclass AnalysisSimple:\n    def __init__(self, structure2d: Structure2D, structure3d: Structure3D):\n        self.pairs: List[BasePair3D] = structure3d.base_pairs(structure2d)\n        self.graph: Dict[Residue3D, List[Residue3D]] = structure3d.base_pair_graph(structure2d)\n        self.pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] = structure3d.base_pair_dict(structure2d)\n\n    def has_tetrads(self):\n        tetrads = set()\n        for i in self.graph:\n            for j in filter(lambda x: x != i, self.graph[i]):\n                for k in filter(lambda x: x not in (i, j), self.graph[j]):\n                    for l in filter(lambda x: x not in (i, j, k) and x in self.graph[i], self.graph[k]):\n                        if Tetrad.is_valid(i, j, k, l, self.pair_dict):\n                            tetrads.add(frozenset([i, j, k, l]))\n                        if len(tetrads) > 1:\n                            return True\n        return False\n\n\ndef center_of_mass(atoms):\n    coords = [atom.coordinates() for atom in atoms]\n    xs = (coord[0] for coord in coords)\n    ys = (coord[1] for coord in coords)\n    zs = (coord[2] for coord in coords)\n    return numpy.array((sum(xs) / len(coords), sum(ys) / len(coords), sum(zs) / len(coords)))\n\n\ndef eltetrado(structure2d: Structure2D, structure3d: Structure3D, strict: bool, no_reorder: bool,\n              stacking_mismatch: int) -> Analysis:\n    return Analysis(structure2d, structure3d, strict, no_reorder, stacking_mismatch)\n\n\ndef has_tetrad(structure2d: Structure2D, structure3d: Structure3D) -> bool:\n    structure = AnalysisSimple(structure2d, structure3d)\n    return structure.has_tetrads()\n", "meta": {"hexsha": "de49973926bf957773166d4a7786ff49e43be172", "size": 43892, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/eltetrado/analysis.py", "max_stars_repo_name": "tzok/el_tetrado", "max_stars_repo_head_hexsha": "b1890f9bc39d815e5b535047fca5500117e3f8f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/eltetrado/analysis.py", "max_issues_repo_name": "tzok/el_tetrado", "max_issues_repo_head_hexsha": "b1890f9bc39d815e5b535047fca5500117e3f8f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eltetrado/analysis.py", "max_forks_repo_name": "tzok/el_tetrado", "max_forks_repo_head_hexsha": "b1890f9bc39d815e5b535047fca5500117e3f8f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.122840691, "max_line_length": 163, "alphanum_fraction": 0.5900164039, "include": true, "reason": "import numpy", "num_tokens": 11689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19846836749957103}}
{"text": "\"\"\"\r\n-------------------------------------------------\r\n   File Name:    Losses.py\r\n   Author:       Zhonghao Huang\r\n   Date:         2019/10/21\r\n   Description:  Module implementing various loss functions\r\n                 Copy from: https://github.com/akanimax/pro_gan_pytorch\r\n-------------------------------------------------\r\n\"\"\"\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nfrom torch.nn import BCEWithLogitsLoss\r\nimport numpy as np\r\nfrom utils import gradient_penalty\r\n\r\n# =============================================================\r\n# Interface for the losses\r\n# =============================================================\r\n\r\nclass GANLoss:\r\n    \"\"\" Base class for all losses\r\n        @args:\r\n        disc: Discriminator used for calculating the loss\r\n             Note this must be a part of the GAN framework\r\n    \"\"\"\r\n\r\n    def __init__(self, disc):\r\n        self.disc = disc\r\n\r\n    def disc_loss(self, real_samps, fake_samps, alpha, height):\r\n        \"\"\"\r\n        calculate the discriminator loss using the following data\r\n        :param real_samps: batch of real samples\r\n        :param fake_samps: batch of generated (fake) samples\r\n        :param height: current height at which training is going on\r\n        :param alpha: current value of the fader alpha\r\n        :return: loss => calculated loss Tensor\r\n        \"\"\"\r\n        raise NotImplementedError(\"disc_loss method has not been implemented\")\r\n\r\n    def gen_loss(self, real_samps, fake_samps, alpha, height):\r\n        \"\"\"\r\n        calculate the generator loss\r\n        :param real_samps: batch of real samples\r\n        :param fake_samps: batch of generated (fake) samples\r\n        :param height: current height at which training is going on\r\n        :param alpha: current value of the fader alpha\r\n        :return: loss => calculated loss Tensor\r\n        \"\"\"\r\n        raise NotImplementedError(\"gen_loss method has not been implemented\")\r\n\r\n\r\nclass ConditionalGANLoss:\r\n    \"\"\" Base class for all conditional losses \"\"\"\r\n\r\n    def __init__(self, disc):\r\n        self.disc = disc\r\n\r\n    def disc_loss(self, real_samps, fake_samps, labels, alpha, height):\r\n        raise NotImplementedError(\"disc_loss method has not been implemented\")\r\n\r\n    def gen_loss(self, real_samps, fake_samps, labels, alpha, height):\r\n        raise NotImplementedError(\"gen_loss method has not been implemented\")\r\n\r\n\r\n# =============================================================\r\n# Normal versions of the Losses:\r\n# =============================================================\r\n\r\nclass StandardGAN(GANLoss):\r\n\r\n    def __init__(self, disc):\r\n        super().__init__(disc)\r\n        # define the criterion and activation used for object\r\n        self.criterion = BCEWithLogitsLoss()\r\n\r\n    def disc_loss(self, real_samps, fake_samps, alpha, height):\r\n        # small assertion:\r\n        assert real_samps.device == fake_samps.device, \\\r\n            \"Real and Fake samples are not on the same device\"\r\n\r\n        # device for computations:\r\n        device = fake_samps.device\r\n\r\n        # predictions for real images and fake images separately :\r\n        r_preds = self.disc(real_samps, alpha, height)\r\n        f_preds = self.disc(fake_samps, alpha, height)\r\n\r\n        # calculate the real loss:\r\n        real_loss = self.criterion(\r\n            torch.squeeze(r_preds),\r\n            torch.ones(real_samps.shape[0]).to(device))\r\n\r\n        # calculate the fake loss:\r\n        fake_loss = self.criterion(\r\n            torch.squeeze(f_preds),\r\n            torch.zeros(fake_samps.shape[0]).to(device))\r\n\r\n        # return final losses\r\n        return (real_loss + fake_loss) / 2\r\n\r\n    def gen_loss(self, _, fake_samps, alpha, height):\r\n        preds, _, _ = self.disc(fake_samps, alpha, height)\r\n        return self.criterion(\r\n            torch.squeeze(preds),\r\n            torch.ones(fake_samps.shape[0]).to(fake_samps.device))\r\n\r\n\r\nclass WGAN_GP(GANLoss):\r\n\r\n    def __init__(self, disc, LAMBDA_GP=10):\r\n        super().__init__(disc)\r\n        self.LAMBDA_GP = LAMBDA_GP\r\n\r\n    def disc_loss(self, real_samps, fake_samps, alpha, height):\r\n        critic_real = self.disc(real_samps, alpha, height)\r\n        critic_fake = self.disc(fake_samps, alpha, height)\r\n        gp = gradient_penalty(self.disc, real_samps, fake_samps, alpha, height, device=real_samps.device)\r\n        loss = (\r\n            -(torch.mean(critic_real) - torch.mean(critic_fake))\r\n            + self.LAMBDA_GP * gp\r\n            + (0.001 * torch.mean(critic_real ** 2))\r\n        )\r\n        return loss\r\n\r\n    def gen_loss(self, _, fake_samps, alpha, height):\r\n        return -torch.mean(self.disc(fake_samps, alpha, height))\r\n\r\n\r\nclass HingeGAN(GANLoss):\r\n\r\n    def __init__(self, disc):\r\n        super().__init__(disc)\r\n\r\n    def disc_loss(self, real_samps, fake_samps, alpha, height):\r\n        r_preds = self.disc(real_samps, alpha, height)\r\n        f_preds = self.disc(fake_samps, alpha, height)\r\n\r\n        loss = (torch.mean(nn.ReLU()(1 - r_preds)) +\r\n                torch.mean(nn.ReLU()(1 + f_preds)))\r\n\r\n        return loss\r\n\r\n    def gen_loss(self, _, fake_samps, alpha, height):\r\n        return -torch.mean(self.disc(fake_samps, alpha, height))\r\n\r\n\r\nclass RelativisticAverageHingeGAN(GANLoss):\r\n\r\n    def __init__(self, disc):\r\n        super().__init__(disc)\r\n\r\n    def disc_loss(self, real_samps, fake_samps, alpha, height):\r\n        # Obtain predictions\r\n        r_preds = self.disc(real_samps, alpha, height)\r\n        f_preds = self.disc(fake_samps, alpha, height)\r\n\r\n        # difference between real and fake:\r\n        r_f_diff = r_preds - torch.mean(f_preds)\r\n\r\n        # difference between fake and real samples\r\n        f_r_diff = f_preds - torch.mean(r_preds)\r\n\r\n        # return the loss\r\n        loss = (torch.mean(nn.ReLU()(1 - r_f_diff))\r\n                + torch.mean(nn.ReLU()(1 + f_r_diff)))\r\n\r\n        return loss\r\n\r\n    def gen_loss(self, real_samps, fake_samps, alpha, height):\r\n        # Obtain predictions\r\n        r_preds = self.disc(real_samps, alpha, height)\r\n        f_preds = self.disc(fake_samps, alpha, height)\r\n\r\n        # difference between real and fake:\r\n        r_f_diff = r_preds - torch.mean(f_preds)\r\n\r\n        # difference between fake and real samples\r\n        f_r_diff = f_preds - torch.mean(r_preds)\r\n\r\n        # return the loss\r\n        return (torch.mean(nn.ReLU()(1 + r_f_diff))\r\n                + torch.mean(nn.ReLU()(1 - f_r_diff)))\r\n\r\n\r\nclass LogisticGAN(GANLoss):\r\n    def __init__(self, disc):\r\n        super().__init__(disc)\r\n\r\n    # gradient penalty\r\n    def R1Penalty(self, real_img, alpha, height):\r\n\r\n        # TODO: use_loss_scaling, for fp16\r\n        apply_loss_scaling = lambda x: x * torch.exp(x * torch.Tensor([np.float32(np.log(2.0))]).to(real_img.device))\r\n        undo_loss_scaling = lambda x: x * torch.exp(-x * torch.Tensor([np.float32(np.log(2.0))]).to(real_img.device))\r\n\r\n        real_img = torch.autograd.Variable(real_img, requires_grad=True)\r\n        real_logit = self.disc(real_img, alpha, height)\r\n        # real_logit = apply_loss_scaling(torch.sum(real_logit))\r\n        real_grads = torch.autograd.grad(outputs=real_logit, inputs=real_img,\r\n                                         grad_outputs=torch.ones(real_logit.size()).to(real_img.device),\r\n                                         create_graph=True, retain_graph=True)[0].view(real_img.size(0), -1)\r\n        # real_grads = undo_loss_scaling(real_grads)\r\n        r1_penalty = torch.sum(torch.mul(real_grads, real_grads))\r\n        return r1_penalty\r\n\r\n    def disc_loss(self, real_samps, fake_samps, alpha, height, r1_gamma=10.0):\r\n        # Obtain predictions\r\n        r_preds = self.disc(real_samps, alpha, height)\r\n        f_preds = self.disc(fake_samps, alpha, height)\r\n\r\n        loss = torch.mean(nn.Softplus()(f_preds)) + torch.mean(nn.Softplus()(-r_preds))\r\n\r\n        if r1_gamma != 0.0:\r\n            r1_penalty = self.R1Penalty(real_samps.detach(), alpha, height) * (r1_gamma * 0.5)\r\n            loss += r1_penalty\r\n\r\n        return loss\r\n\r\n    def gen_loss(self, _, fake_samps, alpha, height):\r\n        f_preds = self.disc(fake_samps, alpha, height)\r\n\r\n        return torch.mean(nn.Softplus()(-f_preds))", "meta": {"hexsha": "2541272dc85d56e44acb51ffb5cc5ef6e5e4c682", "size": 8159, "ext": "py", "lang": "Python", "max_stars_repo_path": "loss_fn.py", "max_stars_repo_name": "vkmavani/StyleGAN", "max_stars_repo_head_hexsha": "953fad62632c6ec1662cac18ad1502d1517cee3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-18T04:43:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T04:43:15.000Z", "max_issues_repo_path": "loss_fn.py", "max_issues_repo_name": "vkmavani/StyleGAN", "max_issues_repo_head_hexsha": "953fad62632c6ec1662cac18ad1502d1517cee3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "loss_fn.py", "max_forks_repo_name": "vkmavani/StyleGAN", "max_forks_repo_head_hexsha": "953fad62632c6ec1662cac18ad1502d1517cee3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4241071429, "max_line_length": 118, "alphanum_fraction": 0.5941904645, "include": true, "reason": "import numpy", "num_tokens": 1839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19846836749957103}}
{"text": "\"\"\"\nFrank-Wolfe algorithm.\n\"\"\"\n# 2015-04-15\n#\n# We place this in its own module since using:\n#\n#   from __future__ import division\n#\n# seems to cause some issues with `cvxopt.matrix`, causing a TypeError.\n#\n# >>> from cvxopt import matrix\n# >>> x = matrix([[1,2],[3,5]])\n# >>> x / 3\n# TypeError: unsupported operand type(s) for /: 'cvxopt.base.matrix' and 'int'\n\nfrom debtcollector import removals\n\nimport logging\nimport numpy as np\n\nfrom dit.utils import basic_logger\n\n\n__all__ = (\n    'frank_wolfe',\n)\n\n\n@removals.remove(message=\"Please see methods in dit.algorithms.distribution_optimizers.py.\",\n                 version='1.0.1')\ndef frank_wolfe(objective, gradient, A, b, initial_x,\n                maxiters=2000, tol=1e-4, clean=True, verbose=None):\n    \"\"\"\n    Uses the Frank--Wolfe algorithm to minimize the convex objective.\n\n    Minimization is subject to the linear equality constraint: :math:`A x = b`.\n\n    Assumes x should be nonnegative.\n\n    Parameters\n    ----------\n    objective : callable\n        The objective function. It would receive a ``cvxopt`` matrix for the\n        input `x` and return the value of the objective function.\n    gradient : callable\n        The gradient function. It should receive a ``cvxopt`` matrix for the\n        input `x` and return the value of the gradient evaluated at `x`.\n    A : matrix\n        A ``cvxopt`` matrix specifying the LHS linear equality constraints.\n    b : matrix\n        A ``cvxopt`` matrix specifying the RHS linear equality constraints.\n    initial_x : matrix\n        A ``cvxopt`` matrix specifying the initial `x` to use.\n    maxiters : int\n        The maximum number of iterations to perform. If convergence was not\n        reached after the last iteration, a warning is issued and the current\n        value of `x` is returned.\n    tol : float\n        The tolerance used to determine when we have converged to the optimum.\n    clean : bool\n        Occasionally, the iteration process will take nonnegative values to be\n        ever so slightly negative. If ``True``, then we forcibly make such\n        values equal to zero and renormalize the vector. This is an application\n        specific decision and is probably not more generally useful.\n    verbose : int\n        An integer representing the logging level ala the ``logging`` module.\n        If `None`, then (effectively) the log level is set to `WARNING`. For\n        a bit more information, set this to `logging.INFO`. For a bit less,\n        set this to `logging.ERROR`, or perhaps 100.\n\n    \"\"\"\n    # Function level import to avoid circular import.\n    from dit.algorithms.optutil import op_runner\n\n    # Function level import to keep cvxopt dependency optional.\n    # All variables should be cvxopt variables, not NumPy arrays\n    from cvxopt.modeling import variable\n\n    # Set up a custom logger.\n    logger = basic_logger('dit.frankwolfe', verbose)\n\n    # Set cvx info level based on logging.DEBUG level.\n    if logger.isEnabledFor(logging.DEBUG):\n        show_progress = True\n    else:\n        show_progress = False\n\n    assert (A.size[1] == initial_x.size[0])\n\n    n = initial_x.size[0]\n    x = initial_x\n    xdiff = 0\n\n    TOL = 1e-7\n    verbosechunk = maxiters / 10\n    for i in range(maxiters):\n        obj = objective(x)\n        grad = gradient(x)\n\n        xbar = variable(n)\n\n        new_objective = grad.T * xbar\n        constraints = []\n        constraints.append((xbar >= 0))\n        constraints.append((-TOL <= A * xbar - b))\n        constraints.append((A * xbar - b <= TOL))\n\n        logger.debug('FW Iteration: {}'.format(i))\n        opt = op_runner(new_objective, constraints, show_progress=show_progress)\n        if opt.status != 'optimal':\n            msg = '\\tFrank-Wolfe: Did not find optimal direction on '\n            msg += 'iteration {}: {}'\n            msg = msg.format(i, opt.status)\n            logger.info(msg)\n\n        # Calculate optimality gap\n        xbar_opt = opt.variables()[0].value\n        opt_bd = grad.T * (xbar_opt - x)\n\n        msg = \"i={:6}  obj={:10.7f}  opt_bd={:10.7f}  xdiff={:12.10f}\"\n        if logger.isEnabledFor(logging.DEBUG):\n            logger.debug(msg.format(i, obj, opt_bd[0, 0], xdiff))\n            logger.debug(\"\")\n        elif i % verbosechunk == 0:\n            logger.info(msg.format(i, obj, opt_bd[0, 0], xdiff))\n\n        xnew = (i * x + 2 * xbar_opt) / (i + 2)\n        xdiff = np.linalg.norm(xnew - x)\n        x = xnew\n\n        if xdiff < tol:\n            obj = objective(x)\n            break\n    else:\n        msg = \"Only converged to xdiff={:12.10f} after {} iterations. \"\n        msg += \"Desired: {}\"\n        logger.warn(msg.format(xdiff, maxiters, tol))\n\n    xopt = np.array(x)\n\n    if clean:\n        xopt[np.abs(xopt) < tol] = 0\n        xopt /= xopt.sum()\n\n    return xopt, obj\n", "meta": {"hexsha": "21ee2171c692ffec646bf1c900eb3f7d7e1304ee", "size": 4779, "ext": "py", "lang": "Python", "max_stars_repo_path": "dit/algorithms/frankwolfe.py", "max_stars_repo_name": "Ejjaffe/dit", "max_stars_repo_head_hexsha": "c9d206f03d1de5a0a298b1d0ea9d79ea5e789ee1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-13T10:30:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-13T10:30:11.000Z", "max_issues_repo_path": "dit/algorithms/frankwolfe.py", "max_issues_repo_name": "Ejjaffe/dit", "max_issues_repo_head_hexsha": "c9d206f03d1de5a0a298b1d0ea9d79ea5e789ee1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dit/algorithms/frankwolfe.py", "max_forks_repo_name": "Ejjaffe/dit", "max_forks_repo_head_hexsha": "c9d206f03d1de5a0a298b1d0ea9d79ea5e789ee1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5102040816, "max_line_length": 92, "alphanum_fraction": 0.6239799121, "include": true, "reason": "import numpy", "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.198468367499571}}
{"text": "\"\"\"All main functions for et_module\n\"\"\"\nimport os\nimport sys\nimport csv\nimport logging\nimport numpy as np\nimport pandas as pd\n\nfrom et_module import diffusion_functions\n\ndef load_curve_assignement(\n        curr_yr,\n        base_yr,\n        yr_until_changed,\n        et_service_demand_yh,\n        load_profiles,\n        regions,\n        charging_scenario,\n        diffusion='linear'\n    ):\n    \"\"\"Assign input electrictiy demand (given as \"tranport service\"\n    for every hour in a year) to an hourly energy demand load profile\n    depending (see documentation for more information).\n\n    Arguments\n    =========\n    curr_yr : int\n        Current simulation year\n    base_yr : int\n        Base year of simulation\n    yr_until_changed : int\n        Year until changed is fully implemented\n    et_service_demand_yh : dict\n        Transport energy demand for every region (hourly demand)\n    load_profiles : list\n        Load profile objects\n    regions : list\n        All region names\n    charging_scenario : str\n        Scenario\n\n            'sheduled' :\n\n            'sheduled' : \n            TODO\n\n    diffusion : str\n        Type of diffusion between base year and end year load profile\n\n            'linear':   Linear change over time towards future load profile\n\n            'sigmoid':  Sigmoid change over time towards future load profile\n\n    Returns\n    =========\n    et_demand_yh : array\n        Houlry demand, np.array(reg_array_nr, 8760 timesteps)\n    \"\"\"\n    et_demand_yh = np.zeros((len(regions), 365 * 24), dtype=float)\n\n    # -------------------\n    # Calculate diffusion\n    # -------------------\n    if diffusion == 'linear':\n        simulation_year_p = diffusion_functions.linear_diff(\n            base_yr=base_yr,\n            curr_yr=curr_yr,\n            value_start=0,\n            value_end=1,\n            yr_until_changed=yr_until_changed)\n\n    elif diffusion == 'sigmoid':\n        # Default sigmoid parameters\n        simulation_year_p = diffusion_functions.sigmoid_diffusion(\n            base_yr=base_yr,\n            curr_yr=curr_yr,\n            end_yr=yr_until_changed,\n            sig_midpoint=0,\n            sig_steeppness=1)\n    else:\n        sys.exit(\"Error: No diffusion option is selected\")\n    # --------------------------------------------------------------------\n    # Calculate current year profile with base year and profile from 2015\n    # --------------------------------------------------------------------\n\n    # Get base year load profile\n    for load_profile in load_profiles:\n        if load_profile.name == 'av_lp_2015.csv':\n            profile_yh_by = load_profile.shape_yh\n\n    # Get future year load profile\n    for load_profile in load_profiles:\n\n        if charging_scenario == 'unsheduled':\n\n            # Unsheduled load profile (same as base year)\n            if load_profile.name == 'av_lp_2015.csv':\n                profile_yh_ey = load_profile.shape_yh\n\n        elif charging_scenario == 'sheduled':\n\n            # Sheduled load profile\n            if load_profile.name == 'av_lp_2050.csv':\n                profile_yh_ey = load_profile.shape_yh\n    \n    if base_yr == curr_yr:\n        profile_yh_cy = profile_yh_by\n    elif curr_yr == yr_until_changed or curr_yr > yr_until_changed:\n        profile_yh_cy = profile_yh_ey\n    else:\n\n        # Calculate difference between by and ey\n        diff_profile = profile_yh_ey - profile_yh_by\n\n        # Calculate difference up to cy\n        diff_profile_cy = diff_profile * simulation_year_p\n\n        # Add difference to by\n        profile_yh_cy = profile_yh_by + diff_profile_cy\n\n    assert round(np.sum(profile_yh_cy), 3) == 1\n\n    # ----------\n    # Plotting\n    # ----------\n    #from et_module import plotting_functions\n    #fig_lp.plot_lp_dh(profile_yh_cy, day=2)\n\n    # ------------------------------------\n    # Disaggregate for every region\n    # ------------------------------------\n    for region_array_nr, region in enumerate(regions):\n\n        # Sum total service demand to annual demand\n        et_service_demand_y = np.sum(et_service_demand_yh[region])\n\n        # Multiply the annual total service demand with yh load profile\n        reg_profile_yh = et_service_demand_y * profile_yh_cy\n\n        logging.debug(\n            \"Assinging new shape {}  {} {}\".format(\n                region, et_service_demand_y, np.sum(profile_yh_cy)))\n\n        # Reshape (365 days, 24hours) into 8760 timesteps\n        et_demand_yh[region_array_nr] = reg_profile_yh.reshape(8760)\n\n    return et_demand_yh\n\ndef get_load_profiles(path):\n    \"\"\"Read in all load profiles from csv files and store in\n    `LoadProfile`.\n\n    Arguments\n    =========\n    path : str\n        Path where load profiles are stored\n\n    Returns\n    =======\n    load_profiles : list\n        All load profiles objects\n    \"\"\"\n    load_profiles = []\n\n    # Name of load profiles to load\n    names = [\n        'av_lp_2015.csv',\n        'av_lp_2050.csv']\n\n    for name in names:\n\n        # Create path to csv file\n        path_to_csv = os.path.join(path, name)\n\n        # Read in csv load profile\n        lp_dh = read_load_shape(path_to_csv)\n\n        lp_dh_p = lp_dh / 100 # convert percentage to fraction\n\n        # Shape for every hour in a year (Assign same profile to every day)\n        shape_yd = np.full((365), 1/365)\n\n        # Shape for every hour in a year (365) * (24)\n        shape_yh = shape_yd[:, np.newaxis]  * lp_dh_p\n\n        # Create load profile\n        load_profile = LoadProfile(\n            name=name,\n            year=name[-8:-4],\n            shape_yd=shape_yd,\n            shape_yh=shape_yh)\n\n        load_profiles.append(load_profile)\n\n    return load_profiles\n\ndef read_load_shape(path_to_csv):\n    \"\"\"This function reads in a load profile from\n    a csv file of a single day.\n\n    Arguments\n    =========\n    path_to_csv : str\n        Path to csv file\n\n    Returns\n    =======\n    shape_dh : array (24)\n        Load profile\n    \"\"\"\n    with open(path_to_csv, 'r') as csvfile:\n        read_lines = csv.reader(csvfile, delimiter=',')\n        _headings = next(read_lines) # Skip first row\n\n        for row in read_lines:\n            shape_dh = np.zeros((24), dtype=float)\n            for cnt, row_entry in enumerate(row):\n                shape_dh[int(_headings[cnt])] = float(row_entry)\n\n    return shape_dh\n\nclass LoadProfile(object):\n    \"\"\"Class to store load profiles\n\n    Arguments\n    ----------\n    name : str\n        Name of load profile\n    year : int\n        Year of load profile\n    shape_yd : array\n        Yearly load profile\n    shape yh : array\n        Daily load profile\n\n    Note\n    ====\n    -   `Yearly load profile (yd)` can be used to derive the energy demand\n        of all days in year. This is achieved by multiplying total\n        annual demand with this _yd array with the array shape (365)\n\n    -   `Daily load profile (yh)` can be used to derive the energy demand\n        of all hours in a year. This is achieved by multiplying total\n        annual demand with the this _yh array with the array shape (365, 24).\n    \"\"\"\n    def __init__(\n            self,\n            name,\n            year,\n            shape_yd,\n            shape_yh\n        ):\n        \"\"\"Constructor\n        \"\"\"\n        self.name = name\n        self.year = year\n        self.shape_yd = shape_yd\n        self.shape_yh = shape_yh\n", "meta": {"hexsha": "464bf96075ca19346e75ffb3cb782e43b42bf49a", "size": 7303, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/et_module/main_functions.py", "max_stars_repo_name": "nismod/et_module", "max_stars_repo_head_hexsha": "eb1a32aed1e0f7d85a9b2191d5b6c0a395510cdd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/et_module/main_functions.py", "max_issues_repo_name": "nismod/et_module", "max_issues_repo_head_hexsha": "eb1a32aed1e0f7d85a9b2191d5b6c0a395510cdd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-02-09T09:33:50.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-11T13:34:34.000Z", "max_forks_repo_path": "src/et_module/main_functions.py", "max_forks_repo_name": "nismod/et_module", "max_forks_repo_head_hexsha": "eb1a32aed1e0f7d85a9b2191d5b6c0a395510cdd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0884615385, "max_line_length": 77, "alphanum_fraction": 0.5920854443, "include": true, "reason": "import numpy", "num_tokens": 1694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.198468367499571}}
{"text": "import numpy as np\nimport sys\nimport warnings\nimport argparse\nfrom fit import do_fit\nfrom output import *\nfrom input import get_input,get_imax\nwarnings.simplefilter(\"error\")\n\ndef get_args():\n\n    args_parser = argparse.ArgumentParser()\n    \n    # Data files arguments\n    args_parser.add_argument(\n        '--vmcfile',\n        help='Local path to vmc data',\n        required=True,\n        type=str\n    )\n    \n    \n    args_parser.add_argument(\n        '--dmcfile',\n        help='Local path to dmc data',\n        required=True,\n        type=str\n    )\n\n    args_parser.add_argument(\n        '--rfile',\n        help='Local path to dmc data',\n        required=True,\n        type=str\n    )\n\n    args_parser.add_argument(\n        '--max-pol',\n        help='Maximum polynomial order.',\n        required=False,\n        type=int,\n        default=3\n    )\n\n    args_parser.add_argument(\n        '--min-pol',\n        help='Minimum polynomial order.',\n        required=False,\n        type=int,\n        default=3\n    )\n    \n    args_parser.add_argument(\n        '--plot',\n        help='BOOL. Produce plot of the PCFs. 0 (default) FALSE. 1 TRUE. ',\n        required=False,\n        type=int,\n        default=0\n    )\n    \n    args_parser.add_argument(\n        '--num-e',\n        help='Total Number of electrons',\n        required=False,\n        type=int,\n        default=3\n    )\n    \n    args_parser.add_argument(\n        '--lat-vec',\n        help='Maximum polynomial order.',\n        required=True,\n        type=float\n    )\n\n\n    args_parser.add_argument(\n        '--fit-range',\n        help='Maximum polynomial order.',\n        required=True,\n        type=float\n    )\n\n    args_parser.add_argument(\n        '--opt-method',\n\thelp='lm,trf or dogbox',\n\trequired=False,\n        type=str,\n        default='lm'\n    )\n    \n    args_parser.add_argument(\n        '--volume',\n        help='Volume of the simulation cell.',\n        required=True,\n        type=float\n    )\n\n    args_parser.add_argument(\n        '--metal',\n        help='System is metallic (1) or not (0). Affects to the scaling of the extrapolated PCF. Default: 0.',\n        required=False,\n        type=int,\n        default=0\n    )\n    \n    args_parser.add_argument(\n        '--verbosity',\n        help='Controls the amount of info printed.',\n        required=False,\n        type=int,\n        default=0\n    )\n\n\n    args_parser.add_argument(\n\t'--omit_pcf',\n        help='skip pcfs.',\n        required=False,\n        nargs='+',\n\ttype=int,\n        default=[-1]\n    )\n\n    args_parser.add_argument(\n        '--corepart',\n        help='tau_valence/tau_total.',\n        type=float,\n        default=1.0\n    )\n\n    args_parser.add_argument(\n\t'--table',\n        help='Printout table in latex.',\n        required=False,\n\ttype=int,\n        default=[-1]\n    )\n\n    args_parser.add_argument(\n        '--cross-val',\n        help='Perform a cross-validation over the fits.',\n        required=False,\n        type=int,\n        default=[-1]\n    )\n\n    return args_parser.parse_args()\n                    \ndef fit_statistics(args,fits,g,r):\n\n    # The dimensions of our current experiment\n    Nx=len(r)\n    Npcf=len(g)\n    p_degs=np.arange(args.min_pol,args.max_pol+1,2)\n    N_degs = len(p_degs)\n    bond_distance=args.fit_range*args.lat_vec\n    \n    # Averages of the PCFs and fits\n    fit_average=np.zeros((Nx,N_degs))\n    g_average=np.zeros((Nx,))\n    for i in range(Npcf):\n        g_average[:]=g_average[:]+g[i]\n        for d in range(N_degs):\n            fit_average[:,d]=fit_average[:,d]+fits[:,i,d]\n\n    g_average=g_average/Npcf\n    fit_average=fit_average/Npcf\n            \n    # Compute the fitting error\n    fit_errors=np.zeros((N_degs,))\n    fit_sqerrors=np.zeros((N_degs,))\n    imax=get_imax(r,2)\n    for i in range(N_degs):\n        for j in range(imax):\n            fit_errors[i]=fit_errors[i]+np.absolute(np.exp(fit_average[j,i])-g_average[j])\n            fit_sqerrors[i]=fit_sqerrors[i]+(np.exp(fit_average[j,i])-g_average[j])**2\n    fit_errors=fit_errors/imax\n    fit_sqerrors=fit_sqerrors/imax\n\n    \n    if args.plot == 1:\n        plot_results(p_degs,N_degs,g_average,fit_average,r,imax)\n\n    return fit_errors,fit_sqerrors\n\ndef mean_and_error(g):\n    '''\n    Input: (N_pcf,N_degs)-order matrix of PCF-zeroes.\n    Output: \n      * Means over separate PCF's.\n      * Mean average errors of PCF's.\n      * Standard deviations of PCF's.\n\n    \n    '''\n    gmean=np.mean(g,axis=0)\n    mean_error=np.mean(np.absolute(gmean-g),axis=0)\n    standard_deviation=np.std(g,axis=0)/np.sqrt(g.shape[0])#np.sqrt(np.mean((gmean-g)**2,axis=0))/np.sqrt(g.shape[0])\n        \n    return gmean,mean_error,standard_deviation\n\n\ndef main():\n\n    args=get_args()\n    \n    r,r_ex,gex,glogex=get_input(args)\n\n    r_range=args.fit_range*args.lat_vec\n    \n    # Fitting\n    fits,opt_pol_coeff=do_fit(r,r_ex,r_range,glogex,args)\n\n    # Fitting statistics\n    fe,fsqe=fit_statistics(args,fits,gex,r)\n    \n    # Get g(0) values and statistics\n    gzeros=np.exp(fits[0,:,:])\n    m,e,std=mean_and_error(gzeros)\n    \n    # Lifetime statistics\n    lifetimes=1000.0*(100.617/2*args.num_e/args.volume*gzeros)**-1\n    mt,et,stdt=mean_and_error(lifetimes)\n\n    if(args.table==1):\n        make_table(args,m,mt,fe,fsqe,e,std,stdt,gzeros,lifetimes)\n    else:\n        print_output(args,m,mt,fe,fsqe,e,std,stdt,gzeros,lifetimes)\n        \n    sys.exit('All done.')\n\nif __name__ == '__main__':\n    main()\n        \n", "meta": {"hexsha": "083217f3d6fbdb392598c793e6c42cb81a114c02", "size": 5405, "ext": "py", "lang": "Python", "max_stars_repo_path": "casino/positron_utils/pcf_fit/plyfit.py", "max_stars_repo_name": "JMuff22/Scripts", "max_stars_repo_head_hexsha": "1cbc431031584c50e918e90be1b44715833e3f32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "casino/positron_utils/pcf_fit/plyfit.py", "max_issues_repo_name": "JMuff22/Scripts", "max_issues_repo_head_hexsha": "1cbc431031584c50e918e90be1b44715833e3f32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "casino/positron_utils/pcf_fit/plyfit.py", "max_forks_repo_name": "JMuff22/Scripts", "max_forks_repo_head_hexsha": "1cbc431031584c50e918e90be1b44715833e3f32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9025423729, "max_line_length": 117, "alphanum_fraction": 0.5874190564, "include": true, "reason": "import numpy", "num_tokens": 1362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.198468367499571}}
{"text": "#!/usr/bin/python3\n\n\"\"\"Calculate the RMSD between structures.\"\"\"\n\nimport argparse\n\nimport numpy as np\n\n# Inspired by\n# https://github.com/cclib/cclib/blob/master/cclib/parser/utils.py#L159\nelement = [\n    None,\n    \"H\",\n    \"He\",\n    \"Li\",\n    \"Be\",\n    \"B\",\n    \"C\",\n    \"N\",\n    \"O\",\n    \"F\",\n    \"Ne\",\n    \"Na\",\n    \"Mg\",\n    \"Al\",\n    \"Si\",\n    \"P\",\n    \"S\",\n    \"Cl\",\n    \"Ar\",\n    \"K\",\n    \"Ca\",\n    \"Sc\",\n    \"Ti\",\n    \"V\",\n    \"Cr\",\n    \"Mn\",\n    \"Fe\",\n    \"Co\",\n    \"Ni\",\n    \"Cu\",\n    \"Zn\",\n    \"Ga\",\n    \"Ge\",\n    \"As\",\n    \"Se\",\n    \"Br\",\n    \"Kr\",\n    \"Rb\",\n    \"Sr\",\n    \"Y\",\n    \"Zr\",\n    \"Nb\",\n    \"Mo\",\n    \"Tc\",\n    \"Ru\",\n    \"Rh\",\n    \"Pd\",\n    \"Ag\",\n    \"Cd\",\n    \"In\",\n    \"Sn\",\n    \"Sb\",\n    \"Te\",\n    \"I\",\n    \"Xe\",\n    \"Cs\",\n    \"Ba\",\n    \"La\",\n    \"Ce\",\n    \"Pr\",\n    \"Nd\",\n    \"Pm\",\n    \"Sm\",\n    \"Eu\",\n    \"Gd\",\n    \"Tb\",\n    \"Dy\",\n    \"Ho\",\n    \"Er\",\n    \"Tm\",\n    \"Yb\",\n    \"Lu\",\n    \"Hf\",\n    \"Ta\",\n    \"W\",\n    \"Re\",\n    \"Os\",\n    \"Ir\",\n    \"Pt\",\n    \"Au\",\n    \"Hg\",\n    \"Tl\",\n    \"Pb\",\n    \"Bi\",\n    \"Po\",\n    \"At\",\n    \"Rn\",\n    \"Fr\",\n    \"Ra\",\n    \"Ac\",\n    \"Th\",\n    \"Pa\",\n    \"U\",\n    \"Np\",\n    \"Pu\",\n    \"Am\",\n    \"Cm\",\n    \"Bk\",\n    \"Cf\",\n    \"Es\",\n    \"Fm\",\n    \"Md\",\n    \"No\",\n    \"Lr\",\n    \"Rf\",\n    \"Db\",\n    \"Sg\",\n    \"Bh\",\n    \"Hs\",\n    \"Mt\",\n    \"Ds\",\n    \"Rg\",\n    \"Cn\",\n    \"Nh\",\n    \"Fl\",\n    \"Mc\",\n    \"Lv\",\n    \"Ts\",\n    \"Og\",\n]\n\n# Inspired by\n# https://github.com/cclib/cclib/blob/master/cclib/parser/utils.py#L159\natomic_number = {\n    \"H\": 1,\n    \"He\": 2,\n    \"Li\": 3,\n    \"Be\": 4,\n    \"B\": 5,\n    \"C\": 6,\n    \"N\": 7,\n    \"O\": 8,\n    \"F\": 9,\n    \"Ne\": 10,\n    \"Na\": 11,\n    \"Mg\": 12,\n    \"Al\": 13,\n    \"Si\": 14,\n    \"P\": 15,\n    \"S\": 16,\n    \"Cl\": 17,\n    \"Ar\": 18,\n    \"K\": 19,\n    \"Ca\": 20,\n    \"Sc\": 21,\n    \"Ti\": 22,\n    \"V\": 23,\n    \"Cr\": 24,\n    \"Mn\": 25,\n    \"Fe\": 26,\n    \"Co\": 27,\n    \"Ni\": 28,\n    \"Cu\": 29,\n    \"Zn\": 30,\n    \"Ga\": 31,\n    \"Ge\": 32,\n    \"As\": 33,\n    \"Se\": 34,\n    \"Br\": 35,\n    \"Kr\": 36,\n    \"Rb\": 37,\n    \"Sr\": 38,\n    \"Y\": 39,\n    \"Zr\": 40,\n    \"Nb\": 41,\n    \"Mo\": 42,\n    \"Tc\": 43,\n    \"Ru\": 44,\n    \"Rh\": 45,\n    \"Pd\": 46,\n    \"Ag\": 47,\n    \"Cd\": 48,\n    \"In\": 49,\n    \"Sn\": 50,\n    \"Sb\": 51,\n    \"Te\": 52,\n    \"I\": 53,\n    \"Xe\": 54,\n    \"Cs\": 55,\n    \"Ba\": 56,\n    \"La\": 57,\n    \"Ce\": 58,\n    \"Pr\": 59,\n    \"Nd\": 60,\n    \"Pm\": 61,\n    \"Sm\": 62,\n    \"Eu\": 63,\n    \"Gd\": 64,\n    \"Tb\": 65,\n    \"Dy\": 66,\n    \"Ho\": 67,\n    \"Er\": 68,\n    \"Tm\": 69,\n    \"Yb\": 70,\n    \"Lu\": 71,\n    \"Hf\": 72,\n    \"Ta\": 73,\n    \"W\": 74,\n    \"Re\": 75,\n    \"Os\": 76,\n    \"Ir\": 77,\n    \"Pt\": 78,\n    \"Au\": 79,\n    \"Hg\": 80,\n    \"Tl\": 81,\n    \"Pb\": 82,\n    \"Bi\": 83,\n    \"Po\": 84,\n    \"At\": 85,\n    \"Rn\": 86,\n    \"Fr\": 87,\n    \"Ra\": 88,\n    \"Ac\": 89,\n    \"Th\": 90,\n    \"Pa\": 91,\n    \"U\": 92,\n    \"Np\": 93,\n    \"Pu\": 94,\n    \"Am\": 95,\n    \"Cm\": 96,\n    \"Bk\": 97,\n    \"Cf\": 98,\n    \"Es\": 99,\n    \"Fm\": 100,\n    \"Md\": 101,\n    \"No\": 102,\n    \"Lr\": 103,\n    \"Rf\": 104,\n    \"Db\": 105,\n    \"Sg\": 106,\n    \"Bh\": 107,\n    \"Hs\": 108,\n    \"Mt\": 109,\n    \"Ds\": 110,\n    \"Rg\": 111,\n    \"Cn\": 112,\n    \"Nh\": 113,\n    \"Fl\": 114,\n    \"Mc\": 115,\n    \"Lv\": 116,\n    \"Ts\": 117,\n    \"Og\": 118,\n}\n\n\ndef read_xyz(path_file_or_str):\n    \"\"\"Read a xyz file and return structures.\n\n    Parameters\n    ----------\n    path_file_or_str : str\n\n    Returns\n    -------\n    atomnos : array-like\n    comments : str\n    atomcoords : array-like\n    \"\"\"\n\n    def _process(lines):\n        natom = int(lines[0])\n        m = 2 + natom\n        nstruct = len(lines) // m\n\n        atomnos = []\n        comments = []\n        atomcoords = []\n        for i in range(nstruct):\n            nos = []\n            coords = []\n            initial = i * m + 2\n            for j in range(initial, initial + natom):\n                fields = lines[j].split()\n                nos.append(atomic_number[fields[0]])\n                coords.append([float(x) for x in fields[1:]])\n            atomnos.append(np.array(nos))\n            comments.append(lines[i * m + 1].strip(\"\\n\"))\n            atomcoords.append(np.array(coords))\n        return atomnos, comments, atomcoords\n\n    try:\n        with open(path_file_or_str, \"r\") as xyz_file:\n            return _process(xyz_file.readlines())\n    except TypeError:\n        return _process(path_file_or_str.readlines())\n    except FileNotFoundError:\n        return _process(path_file_or_str.split(\"\\n\"))\n\n\ndef write_xyz(atomnos, atomcoords, comment=\"\"):\n    \"\"\"Format a string as xyz coordinates.\n\n    Parameters\n    ----------\n    atomnos, atomcoords : array-like\n\n    Returns\n    -------\n    str\n    \"\"\"\n    lines = []\n    for no, coord in zip(atomnos, atomcoords):\n        lines.append(\n            f\"{element[no]:2s} {coord[0]:12.6f} {coord[1]:12.6f} {coord[2]:12.6f}\"\n        )\n\n    lines = \"\\n\".join(lines)\n    return f\"{len(atomnos)}\\n{comment}\\n{lines}\"\n\n\ndef calc_rmsd(P, Q, translate=True):\n    \"\"\"Calculate the RMSD between P and Q using Kabsch algorithm.\n\n    Parameters\n    ----------\n    P, Q : array-like\n    translate : bool\n\n    Returns\n    -------\n    float\n\n    Notes\n    -----\n    If structures are not comparable, np.inf is returned.\n\n    Examples\n    --------\n    >>> P = [[0, 0, 0],\n    ...      [1, 1, 1]]\n    >>> calc_rmsd(P, P)\n    0.0\n    >>> Q = [[1, 1, 1],\n    ...      [2, 2, 2]]\n    >>> calc_rmsd(P, Q)\n    0.0\n    >>> P = [[-3.652796902, 0.000000000, -4.445975658],\n    ...      [-3.527558151, 0.000000000, -3.430150234],\n    ...      [-4.501637325, 0.000000000, -3.833697320]]\n    >>> Q = [[ 1.885538972, 0.000000000, -0.577489796],\n    ...      [ 0.911459798, 0.000000000,  0.201773543],\n    ...      [ 1.165525626, 1.078706033, -0.490031274]]\n    >>> calc_rmsd(P, Q)\n    0.140663071340813\n    \"\"\"\n    P, Q = np.asanyarray(P), np.asanyarray(Q)\n    if translate:\n        P = P - P.mean(axis=0)\n        Q = Q - Q.mean(axis=0)\n\n    try:\n        V, s, W = np.linalg.svd(P.T @ Q)\n    except ValueError:\n        return np.inf\n    if np.linalg.det(V) * np.linalg.det(W) < 0:\n        s[-1] = -s[-1]\n        V[:, -1] = -V[:, -1]\n\n    U = V @ W\n    P = P @ U\n    return np.sqrt(np.sum((P - Q) ** 2) / len(P))\n\n\ndef main():\n    \"\"\"Run main procedure.\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"xyz_files\", type=argparse.FileType(\"r\"), default=\"-\", nargs=\"+\"\n    )\n    args = parser.parse_args()\n\n    coords = []\n    names = []\n    for xyz_file in args.xyz_files:\n        coords.append(read_xyz(xyz_file)[2])\n        names.append(xyz_file.name)\n\n    print(\"RMSD:\")\n    for i in range(len(coords)):\n        for j in range(i):\n            rmsd = calc_rmsd(coords[j][-1], coords[i][-1])\n            print(f\"{names[j]:14s} ~ {names[i]:14s} = {rmsd:6.4f} Å\")\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "778544d590d9493870dc9d2000cce66ab64ae960", "size": 6690, "ext": "py", "lang": "Python", "max_stars_repo_path": "rmsd.py", "max_stars_repo_name": "schneiderfelipe/scripts", "max_stars_repo_head_hexsha": "43bb3d02d0b043f80a4840f4cc222944aad683c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rmsd.py", "max_issues_repo_name": "schneiderfelipe/scripts", "max_issues_repo_head_hexsha": "43bb3d02d0b043f80a4840f4cc222944aad683c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rmsd.py", "max_forks_repo_name": "schneiderfelipe/scripts", "max_forks_repo_head_hexsha": "43bb3d02d0b043f80a4840f4cc222944aad683c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.8090452261, "max_line_length": 82, "alphanum_fraction": 0.4137518685, "include": true, "reason": "import numpy", "num_tokens": 2507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.198468367499571}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport os \nimport sys\nimport glob\nimport numpy as np\nimport itk\nfrom itk import TubeTK as ttk\n#from itkwidgets import view\n\n\n# In[2]:\n\nif len(sys.argv) != 2:\n  print(\"ctp-head-CombinedScript.py <ctp-directory>\")\n  print(\"   <ctp-directory> format = C:/Data/unc/HighRes-005-ctp\")\n  sys.exit()\n\n# NRRD Study Name\nprint(\"Directory = \", sys.argv[1])\nstudyname = sys.argv[1] #'C:/Users/steph/Desktop/Data/unc/HighRes-005-ctp'\n\n\n# NRRD Files\ndirectory = (studyname + '/')\n\n# Saved NRRD Files \ndirectory2 = (studyname + '-Reg/')\ntry:\n    os.mkdir(directory2)\nexcept OSError as error:\n    print(error)\n\n# Mask Creation and Location\ndirectory3 = (studyname + '-MinMax/')\ntry:\n    os.mkdir(directory3)\nexcept OSError as error:\n    print(error)\n\npic_folder = os.listdir(directory)\npic_folder = [pic_folder for pic_folder in pic_folder if \".nii\" in pic_folder]\npic_folder.sort()\nprint(pic_folder)\nnum_images = len(pic_folder)\n\nim0Tmp = itk.imread(directory + pic_folder[int(num_images/2)], itk.F)\n\nresample = ttk.ResampleImage.New(Input=im0Tmp,MakeIsotropic=True)\nresample.Update()\nim0 = resample.GetOutput()\nimmath = ttk.ImageMath.New(Input=im0)\nimmath.Blur(1)\nim0Blur = immath.GetOutput()\n\nimmath.Threshold(150, 800, 1, 0)\nimmath.Dilate(10, 1, 0)\nmask0 = immath.GetOutputUChar()\nmask0Tmp = itk.GetArrayViewFromImage(mask0)\nmask0Tmp[0:4,:,:] = 0\nsizeZ = mask0Tmp.shape[0]\nmask0Tmp[sizeZ-4:sizeZ,:,:] = 0   #No need to update mask0 since mask0Tmp is a view of mask0 (shared memory)\n\nitk.imwrite(mask0, directory3 + 'mask.mha', compression=True)\nmaskObj = itk.ImageMaskSpatialObject[3].New()\nmaskObj.SetImage(mask0)\nmaskObj.Update()\n\n\n# In[3]:\n\n\n#view(mask0)\n\n\n# In[ ]:\n\n\nDimension = 3\nPixelType = itk.ctype('float')\nImageType = itk.Image[PixelType, Dimension]\n\nimdatamax = itk.GetArrayFromImage(im0)\nimdatamin = imdatamax\nimdatamax2 = imdatamax\nimdatamin2 = imdatamax\nimdatamax3 = imdatamax\nimdatamin3 = imdatamax\n\nimFixedBlur = im0Blur\n\nfor imNum in range(num_images):\n    imMoving = itk.imread( directory + pic_folder[imNum], itk.F )\n    \n    immath.SetInput(imMoving)\n    immath.Blur(1)\n    imMovingBlur = immath.GetOutput()\n    \n    imreg = ttk.RegisterImages[ImageType].New()\n    imreg.SetFixedImage(imFixedBlur)\n    imreg.SetMovingImage(imMovingBlur)\n    \n    imreg.SetRigidMaxIterations(3000)\n    imreg.SetRegistration(\"RIGID\")\n    imreg.SetExpectedOffsetMagnitude(20)\n    imreg.SetExpectedRotationMagnitude(0.3)\n    imreg.SetMetric(\"MEAN_SQUARED_ERROR_METRIC\")\n    \n    imreg.SetFixedImageMaskObject(maskObj)\n    #imreg.SetSampleFromOverlap(True)\n\n    imreg.SetReportProgress(True)\n    imreg.Update()\n    \n    tfm = imreg.GetCurrentMatrixTransform()\n    #imFixedBlur = imreg.GetFinalMovingImage(\"LINEAR_INTERPOLATION\", -1024)\n    imMovingReg = imreg.ResampleImage(\"LINEAR_INTERPOLATION\", imMoving, tfm, -1024)\n    \n    itk.imwrite( imMovingReg, directory2 + pic_folder[imNum], compression=True )\n    \n    print(tfm)\n    \n    imdataTmp = itk.GetArrayFromImage(imMovingReg)\n    \n    imdatamax = np.maximum(imdatamax,imdataTmp)\n    imdatamin = np.minimum(imdatamin,imdataTmp)\n    imdataTmp[np.where(imdataTmp==imdatamax)] = 0\n    imdataTmp[np.where(imdataTmp==imdatamin)] = 0\n    imdatamax2 = np.maximum(imdatamax2,imdataTmp)\n    imdatamin2 = np.minimum(imdatamin2,imdataTmp)\n    imdataTmp[np.where(imdataTmp==imdatamax)] = 0\n    imdataTmp[np.where(imdataTmp==imdatamin)] = 0\n    imdatamax3 = np.maximum(imdatamax3,imdataTmp)\n    imdatamin3 = np.minimum(imdatamin3,imdataTmp)\n    \n    #out = itk.GetImageFromArray(imdatamax)\n    #out.CopyInformation(im0)\n    #itk.imwrite(out, (directory3 + 'max_' + str(imNum) + '.nrrd'))\n    \n    #out = itk.GetImageFromArray(imdatamax3)\n    #out.CopyInformation(im0)\n    #itk.imwrite(out, (directory3 + 'max3_' + str(imNum) + '.nrrd'))\n    \n    percent = (imNum + 1) / num_images * 100\n    print(str(round(percent)) + '% : ' + pic_folder[imNum])\n    \nprint('Done')    \n\n\n# In[ ]:\n\n\nout = itk.GetImageFromArray(imdatamax3)\nout.CopyInformation(im0)\nitk.imwrite(out, (directory3 + 'max3.nrrd'), compression=True)\n\nout = itk.GetImageFromArray(imdatamin3)\nout.CopyInformation(im0)\nitk.imwrite(out, (directory3 + 'min3.nrrd'), compression=True)\n\nout = itk.GetImageFromArray(imdatamax3 - imdatamin3)\nout.CopyInformation(im0)\nitk.imwrite(out, (directory3 + 'diff3.nrrd'), compression=True)\n\nprint('Done3')\n\n\n# In[ ]:\n\n\nout = itk.GetImageFromArray(imdatamax)\nout.CopyInformation(im0)\nitk.imwrite(out, (directory3 + 'max.nrrd'), compression=True)\n\nout = itk.GetImageFromArray(imdatamin)\nout.CopyInformation(im0)\nitk.imwrite(out, (directory3 + 'min.nrrd'), compression=True)\n\nout = itk.GetImageFromArray(imdatamax - imdatamin)\nout.CopyInformation(im0)\nitk.imwrite(out, (directory3 + 'diff.nrrd'), compression=True)\n\nprint('Done')\n\n\n# In[ ]:\n\n\n#out = itk.GetImageFromArray(imdatamax)\n#view(out)\n\n\n# In[ ]:\n\n\n#!/usr/bin/env python\n# coding: utf-8\n\n# This notebook is intended to demonstrate how select registration, segmentation, and image mathematical methods of ITKTubeTK can be combined to perform multi-channel brain extraction (aka. skull stripping for patient data containing multiple MRI sequences).\n# \n# There are many other (probably more effective) brain extraction methods available as open-source software such as BET and BET2 in the FSL package (albeit such methods are only for single channel data).   If you need to perform brain extraction for a large collection of scans that do not contain major pathologies, please use one of those packages.   This notebook is meant to show off the capabilities of specific ITKTubeTK methods, not to demonstration how to \"solve\" brain extraction.\n\n# In[1]:\n\n\n#import itk\n#from itk import TubeTK as ttk\n\n#from itkwidgets import view\n\n#import numpy as np\n\n\n# In[2]:\n\n\nImageType = itk.Image[itk.F, 3]\n\nInputBaseName = studyname + \"-MinMax/max3\"\n\nfilename = InputBaseName + \".nrrd\"\nim1iso = itk.imread(filename, itk.F)\n\n\n# In[3]:\n\n\nN = 8\nreaderList = [\"003\", \"010\", \"026\", \"034\", \"045\", \"056\", \"063\", \"071\"]\n\nimBase = []\nimBaseB = []\nfor i in range(0,N):\n    name = \"../Data/Normal\"+readerList[i]+\"-FLASH.mha\"\n    nameB = \"../Data/Normal\"+readerList[i]+\"-FLASH-Brain.mha\"\n    imBaseTmp = itk.imread(name, itk.F)\n    imBaseBTmp = itk.imread(nameB, itk.F)\n    imBase.append(imBaseTmp)\n    imBaseB.append(imBaseBTmp)\n\n\n# In[4]:\n\n\n#view(im1iso)\n\n\n# In[5]:\n\n\n#view(imBase[0])\n\n\n# In[6]:\n\n\nimMath = ttk.ImageMath.New(Input=im1iso)\n#imMath.Threshold(-4000,-500,1,0)\n#headMask = imMath.GetOutput()\nimMath.SetInput(im1iso)\n#imMath.IntensityWindow(0,1000,1000,0)\n#imMath.ReplaceValuesOutsideMaskRange(headMask,-0.5,0.5,-500)\nimMath.Blur(1)\nimMath.NormalizeMeanStdDev()\nimMath.IntensityWindow(-5,5,-500,500)\nim1isoBlur = imMath.GetOutput()\n#view(im1isoBlur)\n\n\n# In[7]:\n\n\nRegisterImagesType = ttk.RegisterImages[ImageType]\nregB = []\nregBB = []\nfor i in range(0,N):\n    imMath.SetInput(imBase[i])\n    imMath.Blur(1)\n    imMath.NormalizeMeanStdDev()\n    imMath.IntensityWindow(-5,5,-500,500)\n    imBaseBlur = imMath.GetOutput()\n    \n    #regBTo1 = RegisterImagesType.New(FixedImage=im1isoBlur, MovingImage=imBaseBlur)\n    regBTo1 = RegisterImagesType.New(FixedImage=imBaseBlur, MovingImage=im1isoBlur)\n    regBTo1.SetReportProgress(True)\n    \n    regBTo1.SetRigidMaxIterations(3000)\n    regBTo1.SetAffineMaxIterations(3000)\n    \n    regBTo1.SetExpectedRotationMagnitude(0.2)\n    regBTo1.SetExpectedScaleMagnitude(0.25)\n    regBTo1.SetExpectedSkewMagnitude(0.01)\n    regBTo1.SetExpectedOffsetMagnitude(40) \n\n    regBTo1.SetRigidSamplingRatio(0.1)\n    regBTo1.SetAffineSamplingRatio(0.1)\n    \n    regBTo1.SetSampleFromOverlap(True)\n    \n    regBTo1.SetInitialMethodEnum(\"INIT_WITH_IMAGE_CENTERS\")\n    regBTo1.SetRegistration(\"PIPELINE_AFFINE\")\n    regBTo1.SetMetric(\"MATTES_MI_METRIC\")\n    \n    regBTo1.Update()\n    \n    tfm = regBTo1.GetCurrentMatrixTransform()\n    tfmInv = tfm.GetInverseTransform()\n    print(tfm)\n    \n    resm = ttk.ResampleImage.New(Input=imBase[i])\n    resm.SetMatchImage(im1iso)\n    resm.SetTransform(tfmInv)\n    resm.SetLoadTransform(True)\n    resm.Update()\n    img = resm.GetOutput()\n    regB.append( img )\n\n    resm = ttk.ResampleImage.New(Input=imBaseB[i])\n    resm.SetMatchImage(im1iso)\n    resm.SetTransform(tfmInv)\n    resm.SetLoadTransform(True)\n    resm.Update()\n    img = resm.GetOutput()\n    regBB.append( img )\n\n\n# In[8]:\n\n\nimMath.SetInput(regB[1])\nimMath.AddImages(im1iso,20,1)\nimg = imMath.GetOutput()\n#view( img )\n\n\n# In[9]:\n\n\nregBBT = []\nfor i in range(0,N):\n    imMath.SetInput(regBB[i])\n    imMath.Threshold(0,1,0,1)\n    img = imMath.GetOutput()\n    if i==0:\n        imMath.SetInput( img )\n        imMath.AddImages( img, 1.0/N, 0 )\n        sumBBT = imMath.GetOutput()\n    else:\n        imMath.SetInput( sumBBT )\n        imMath.AddImages( img, 1, 1.0/N )\n        sumBBT = imMath.GetOutput()\n        \n#view(sumBBT)\n\n\n# In[10]:\n\n\nimMath.SetInput(sumBBT)\nimMath.Threshold(0.85,1.1,1,0)\nimMath.Dilate(5,1,0)\nimMath.Erode(25,1,0)\nbrainInside = imMath.GetOutput()\n\nimMath.SetInput( sumBBT )\nimMath.Threshold(0,0,1,0)\nimMath.Erode(1,1,0)\nbrainOutsideAll = imMath.GetOutput()\nimMath.Erode(20,1,0)\nimMath.AddImages(brainOutsideAll, -1, 1)\nbrainOutside = imMath.GetOutput()\n\nimMath.AddImages(brainInside,1,2)\nbrainCombinedMask = imMath.GetOutputUChar()\nbrainCombinedMaskF = imMath.GetOutput()\n\n\n# In[11]:\n\n\nimMath.SetInput(brainCombinedMaskF)\nimMath.AddImages(im1iso, 100, 1)\nbrainCombinedMaskView = imMath.GetOutput()\n#view(brainCombinedMaskView)\n\n\n# In[12]:\n\n\nLabelMapType = itk.Image[itk.UC,3]\n\nsegmenter = ttk.SegmentConnectedComponentsUsingParzenPDFs[ImageType,LabelMapType].New()\nsegmenter.SetFeatureImage( im1iso )\nsegmenter.SetInputLabelMap( brainCombinedMask )\nsegmenter.SetObjectId( 2 )\nsegmenter.AddObjectId( 1 )\nsegmenter.SetVoidId( 0 )\nsegmenter.SetErodeDilateRadius( 10 )\nsegmenter.SetHoleFillIterations( 40 )\nsegmenter.Update()\nsegmenter.ClassifyImages()\nbrainCombinedMaskClassified = segmenter.GetOutputLabelMap()\n\n\n# In[13]:\n\n\n#view(brainCombinedMaskClassified)\n\n\n# In[14]:\n\n\ncast = itk.CastImageFilter[LabelMapType, ImageType].New()\ncast.SetInput(brainCombinedMaskClassified)\ncast.Update()\nbrainMaskF = cast.GetOutput()\n\nbrainMath = ttk.ImageMath[ImageType,ImageType].New(Input = brainMaskF)\nbrainMath.Threshold(2,2,1,0)\nbrainMath.Erode(1,1,0)\nbrainMaskD = brainMath.GetOutput()\nbrainMath.SetInput( im1iso )\nbrainMath.ReplaceValuesOutsideMaskRange( brainMaskD, 1, 1, 0)\nbrain = brainMath.GetOutput()\n\n\n# In[15]:\n\n\n#view(brain)\n\n\n# In[16]:\n\n\nwriter = itk.ImageFileWriter[ImageType].New(Input = brain)\nfilename = InputBaseName + \"-Brain.nrrd\"\nwriter.SetFileName(filename)\nwriter.SetUseCompression(True)\nwriter.Update()\n\n\n# In[ ]:\n\n\n\n#!/usr/bin/env python\n# coding: utf-8\n\n# This notebook is intended to demonstrate how select registration, segmentation, and image mathematical methods of ITKTubeTK can be combined to perform multi-channel brain extraction (aka. skull stripping for patient data containing multiple MRI sequences).\n# \n# There are many other (probably more effective) brain extraction methods available as open-source software such as BET and BET2 in the FSL package (albeit such methods are only for single channel data).   If you need to perform brain extraction for a large collection of scans that do not contain major pathologies, please use one of those packages.   This notebook is meant to show off the capabilities of specific ITKTubeTK methods, not to demonstration how to \"solve\" brain extraction.\n\n# In[1]:\n\n\n#import itk\n#from itk import TubeTK as ttk\n\n#from itkwidgets import view\n\n#import numpy as np\n\n# In[2]:\n\nInputBaseDir = studyname \n\nCTPMaxFilename = InputBaseDir + \"-MinMax/max.nrrd\"\nCTPMinFilename = InputBaseDir + \"-MinMax/min.nrrd\"\nCTPBrainFilename = InputBaseDir + \"-MinMax/max3-Brain.nrrd\"\n\nimMax = itk.imread(CTPMaxFilename, itk.F)\nimMin = itk.imread(CTPMinFilename, itk.F)\nimBrain = itk.imread(CTPBrainFilename, itk.F)\n\n\n# In[3]:\n\n\n#view(imBrain)\n\n\n# In[4]:\n\n\nImageType = itk.Image[itk.F, 3]\n\nimMath = ttk.ImageMath.New(Input=imBrain)\nimMath.Threshold( 0.00001, 2000, 1, 0)\nimMath.Erode(10,1,0)\nimBrainMaskErode = imMath.GetOutput()\n\nimMath.SetInput(imMax)\nimMath.AddImages(imMin,1,-1)\nimDiff = imMath.GetOutput()\nimMath.ReplaceValuesOutsideMaskRange(imBrain, 0.0001, 2000, 0)\nimDiffBrain = imMath.GetOutput()\nimMath.ReplaceValuesOutsideMaskRange(imBrainMaskErode, 0.5, 1.5, 0)\nimDiffBrainErode = imMath.GetOutput()\n\n\n# In[5]:\n\n\ntmpA = itk.GetArrayViewFromImage(imDiffBrain)\ntmpAE = itk.GetArrayViewFromImage(imDiffBrainErode)\nzMax = tmpA.shape[0]\nclip = 0\nwhile((np.amax(tmpA[clip:clip+1,:,:])>1000) | (np.amax(tmpA[clip:clip+1,:,:])==0)):\n    clip += 1\nif(clip>0):\n    tmpA[0:clip,:,:]=0\n    tmpAE[0:clip,:,:]=0\nclip = 1\nwhile((np.amax(tmpA[zMax-clip:zMax-clip+1,:,:])>1000) | (np.amax(tmpA[zMax-clip:zMax-clip+1,:,:])==0)):\n    clip += 1\nprint(clip, np.amax(tmpA[zMax-clip:zMax-clip+1,:,:]))\nclip = clip - 1\nif(clip>0):\n    tmpA[zMax-clip:zMax,:,:]=0  #Happens to imDiffBrain since this array is a view of an itk image\n    tmpAE[zMax-clip:zMax,:,:]=0  #Happens to imDiffBrain since this array is a view of an itk image\n\n\n# In[6]:\n\n\n#view(imDiffBrain)\n\n\n# In[7]:\n\n\nimMath = ttk.ImageMath[ImageType,ImageType].New()\nimMath.SetInput(imDiffBrainErode)\nimMath.Blur(1.5)\nimBlur = imMath.GetOutput()\nimBlurArray = itk.GetArrayViewFromImage(imBlur)\n\nnumSeeds = 15\nseedCoverage = 20\nseedCoord = np.zeros([numSeeds,3])\nfor i in range(numSeeds):\n    seedCoord[i] = np.unravel_index(np.argmax(imBlurArray, axis=None), imBlurArray.shape)\n    indx = [int(seedCoord[i][0]),int(seedCoord[i][1]),int(seedCoord[i][2])]\n    minX = max(indx[0]-seedCoverage,0)\n    maxX = max(indx[0]+seedCoverage,imBlurArray.shape[0])\n    minY = max(indx[1]-seedCoverage,0)\n    maxY = max(indx[1]+seedCoverage,imBlurArray.shape[1])\n    minZ = max(indx[2]-seedCoverage,0)\n    maxZ = max(indx[2]+seedCoverage,imBlurArray.shape[2])\n    imBlurArray[minX:maxX,minY:maxY,minZ:maxZ]=0\n    indx.reverse()\n    seedCoord[:][i] = imDiffBrain.TransformIndexToPhysicalPoint(indx)\nprint(seedCoord)\n\n\n# In[8]:\n\n\n# Manually extract a few vessels to form an image-specific training set\nvSeg = ttk.SegmentTubes.New(Input=imDiffBrain)\nvSeg.SetVerbose(True)\nvSeg.SetMinRoundness(0.4)\nvSeg.SetMinCurvature(0.002)\nvSeg.SetRadiusInObjectSpace( 1 )\nfor i in range(numSeeds):\n    print(\"**** Processing seed \" + str(i) + \" : \" + str(seedCoord[i]))\n    vSeg.ExtractTubeInObjectSpace( seedCoord[i], i )\n    \ntubeMaskImage = vSeg.GetTubeMaskImage()\n\n\n# In[9]:\n\n\nimMath.SetInput(tubeMaskImage)\nimMath.AddImages(imDiffBrain, 200, 1)\nblendIm = imMath.GetOutput()\n#view(blendIm)\n\n\n# In[10]:\n\n\nLabelMapType = itk.Image[itk.UC,3]\n\ntrMask = ttk.ComputeTrainingMask[ImageType,LabelMapType].New()\ntrMask.SetInput( tubeMaskImage )\ntrMask.SetGap( 4 )\ntrMask.SetObjectWidth( 1 )\ntrMask.SetNotObjectWidth( 1 )\ntrMask.Update()\nfgMask = trMask.GetOutput()\n\n\n# In[11]:\n\n\n#view(fgMask)\n\n\n# In[12]:\n\n\nenhancer = ttk.EnhanceTubesUsingDiscriminantAnalysis[ImageType,LabelMapType].New()\nenhancer.AddInput( imDiff )\nenhancer.SetLabelMap( fgMask )\nenhancer.SetRidgeId( 255 )\nenhancer.SetBackgroundId( 128 )\nenhancer.SetUnknownId( 0 )\nenhancer.SetTrainClassifier(True)\nenhancer.SetUseIntensityOnly(True)\nenhancer.SetScales([0.43,1.29,3.01])\nenhancer.Update()\nenhancer.ClassifyImages()\n\n\n# In[13]:\n\n\nim1vess = itk.SubtractImageFilter( Input1=enhancer.GetClassProbabilityImage(0), Input2=enhancer.GetClassProbabilityImage(1))\n\nimMath.SetInput(imDiffBrain)\nimMath.Threshold(0.0001,2000,1,0)\nimMath.Erode(2,1,0)\nimBrainE = imMath.GetOutput()\n\nimMath.SetInput(im1vess)\nimMath.ReplaceValuesOutsideMaskRange(imBrainE, 1, 1, -0.001)\nim1vessBrain = imMath.GetOutput()\n#view(enhancer.GetClassProbabilityImage(0))\n#view(im1vessBrain)\n\n\n# In[14]:\n\n\nitk.imwrite( im1vess, InputBaseDir + \"-MinMax/diff-VesselEnhanced.nrrd\", compression=True)\n\nitk.imwrite( im1vessBrain, InputBaseDir + \"-MinMax/Brain-VesselEnhanced.nrrd\", compression=True)\n\n\n# In[ ]:\n\n\n#!/usr/bin/env python\n# coding: utf-8\n\n# This notebook is intended to demonstrate how vessel segmentation methods of ITKTubeTK can be applied to multi-channel MRI (MRA + T1, T2, etc).\n\n# In[1]:\n\n\n#import itk\n#from itk import TubeTK as ttk\n\n#from itkwidgets import view\n\n#import numpy as np\n\n\n# In[2]:\n\n\nImageType = itk.Image[itk.F, 3]\n\nimDir = studyname + \"-MinMax/\"\n\nim1iso = itk.imread(imDir + \"diff3.nrrd\")\nim1BrainVess = itk.imread(imDir + \"Brain-VesselEnhanced.nrrd\")\n\n\n# In[3]:\n\n\nimMath = ttk.ImageMath.New(im1BrainVess)\nimMath.MedianFilter(1)\nimMath.Threshold(0.000001, 1, 1, 0)\nim1VessMask = imMath.GetOutputShort()\n\nccSeg = ttk.SegmentConnectedComponents.New(im1VessMask)\nccSeg.SetMinimumVolume(10)\nccSeg.Update()\nim1VessMaskCC = ccSeg.GetOutput()\n\n\n# In[4]:\n\n\n#view(im1VessMaskCC)\n\n\n# In[5]:\n\n\nimMathSS = ttk.ImageMath.New(im1VessMaskCC)\nimMathSS.Threshold(0,0,1,0)\nim1VessMaskInv = imMathSS.GetOutputFloat()\n\ndistFilter = itk.DanielssonDistanceMapImageFilter.New(im1VessMaskInv)\ndistFilter.Update()\ndist = distFilter.GetOutput()\n\nimMath.SetInput(dist)\nimMath.Blur(0.4)\ntmp = imMath.GetOutput()\nimMath.ReplaceValuesOutsideMaskRange(tmp, 0.1, 10, 0)\nim1SeedRadius = imMath.GetOutput()\n\nitk.imwrite(im1SeedRadius, imDir+\"VesselsSeedRadius.mha\")\n\n\n# In[6]:\n\n\n#view(im1SeedRadius)\n\n\n# In[7]:\n\n\nimMath.SetInput(im1iso)\nimMath.ReplaceValuesOutsideMaskRange(im1BrainVess, 0, 1000, 0)\nimMath.Blur(0.4)\nimMath.IntensityWindow(0.5,1000,0,1000)\nim1Input = imMath.GetOutput()\n\nitk.imwrite(im1iso, imDir+\"VesselsInput.mha\")\n\n#view(im1Input)\n\n\n# In[8]:\n\n\nnumSeeds = 40\n\nvSeg = ttk.SegmentTubes.New(Input=im1Input)\n#vSeg.SetVerbose(True)\nvSeg.SetMinCurvature(0)#.0001)\nvSeg.SetMinRoundness(0.02)\nvSeg.SetMinRidgeness(0.5)\nvSeg.SetMinLevelness(0.0)\nvSeg.SetRadiusInObjectSpace( 0.8 )\nvSeg.SetBorderInIndexSpace(3)\nvSeg.SetSeedMask( im1SeedRadius )\nvSeg.SetSeedRadiusMask( im1SeedRadius )\nvSeg.SetOptimizeRadius(False)\nvSeg.SetUseSeedMaskAsProbabilities(True)\nvSeg.SetSeedExtractionMinimumProbability(0.4)\n#vSeg.SetSeedMaskMaximumNumberOfPoints( numSeeds )\nvSeg.ProcessSeeds()\n\n\n# In[9]:\n\n\ntubeMaskImage = vSeg.GetTubeMaskImage()\n#view(tubeMaskImage)\n\n\n# In[10]:\n\n\nSOWriter = itk.SpatialObjectWriter[3].New()\nSOWriter.SetInput(vSeg.GetTubeGroup())\nSOWriter.SetBinaryPoints(True)\nSOWriter.SetFileName( imDir+\"Vessels.tre\" )\nSOWriter.Update()\n\n\n# In[ ]:\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "901b7f97bef927192211c6c7d6ab962f9f49a74c", "size": 18295, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/CTP-Head/ctp-head-CombinedScript.py", "max_stars_repo_name": "kian-weimer/ITKTubeTK", "max_stars_repo_head_hexsha": "88da3195bfeca017745e7cddfe04f82571bd00ee", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2020-04-06T17:23:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T13:25:52.000Z", "max_issues_repo_path": "examples/CTP-Head/ctp-head-CombinedScript.py", "max_issues_repo_name": "kian-weimer/ITKTubeTK", "max_issues_repo_head_hexsha": "88da3195bfeca017745e7cddfe04f82571bd00ee", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-04-09T00:23:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T13:02:35.000Z", "max_forks_repo_path": "examples/CTP-Head/ctp-head-CombinedScript.py", "max_forks_repo_name": "kian-weimer/ITKTubeTK", "max_forks_repo_head_hexsha": "88da3195bfeca017745e7cddfe04f82571bd00ee", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-04-03T03:56:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T07:51:32.000Z", "avg_line_length": 23.2465057179, "max_line_length": 489, "alphanum_fraction": 0.7300901886, "include": true, "reason": "import numpy", "num_tokens": 5625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.198468367499571}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*\n\n\"\"\"\ntools module\n\"\"\"\n\n__author__ = 'Dr. Janus Juul Eriksen, University of Bristol, UK'\n__maintainer__ = 'Dr. Janus Juul Eriksen'\n__email__ = 'janus.eriksen@bristol.ac.uk'\n__status__ = 'Development'\n\nimport sys\nimport os\nimport copy\nimport numpy as np\ntry:\n    import opt_einsum as oe\n    OE_AVAILABLE = True\nexcept ImportError:\n    OE_AVAILABLE = False\nfrom subprocess import Popen, PIPE\nfrom pyscf import gto, scf, dft, symm, lib\nfrom pyscf import tools as pyscf_tools\nfrom typing import Tuple, List, Dict, Union\n\nMAX_CYCLE = 100\nNATORB_THRES = 1.e-12\n\nclass Logger(object):\n        \"\"\"\n        this class pipes all write statements to both stdout and output_file\n        \"\"\"\n        def __init__(self, output_file, both=True) -> None:\n            \"\"\"\n            init Logger\n            \"\"\"\n            self.terminal = sys.stdout\n            self.log = open(output_file, 'a')\n            self.both = both\n\n        def write(self, message) -> None:\n            \"\"\"\n            define write\n            \"\"\"\n            self.log.write(message)\n            if self.both:\n                self.terminal.write(message)\n\n        def flush(self) -> None:\n            \"\"\"\n            define flush\n            \"\"\"\n            pass\n\n\ndef git_version() -> str:\n        \"\"\"\n        this function returns the git revision as a string\n        \"\"\"\n        def _minimal_ext_cmd(cmd):\n            env = {}\n            for k in ['SYSTEMROOT', 'PATH', 'HOME']:\n                v = os.environ.get(k)\n                if v is not None:\n                    env[k] = v\n            # LANGUAGE is used on win32\n            env['LANGUAGE'] = 'C'\n            env['LANG'] = 'C'\n            env['LC_ALL'] = 'C'\n            out = Popen(cmd, stdout=PIPE, env=env, \\\n                        cwd=os.path.dirname(__file__)).communicate()[0]\n            return out\n\n        try:\n            out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])\n            GIT_REVISION = out.strip().decode('ascii')\n        except OSError:\n            GIT_REVISION = \"Unknown\"\n\n        return GIT_REVISION\n\n\ndef dim(mo_occ: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n        \"\"\"\n        determine molecular dimensions\n        \"\"\"\n        return np.where(np.abs(mo_occ[0]) > 0.)[0], np.where(np.abs(mo_occ[1]) > 0.)[0]\n\n\ndef mf_info(mf: Union[scf.hf.SCF, dft.rks.KohnShamDFT]) -> Tuple[Tuple[np.ndarray, np.ndarray], \\\n                                                                 Tuple[np.ndarray, np.ndarray]]:\n        \"\"\"\n        retrieve mf information (mo coefficients & occupations)\n        \"\"\"\n        # mo occupations\n        if np.asarray(mf.mo_occ).ndim == 1:\n            mo_occ = (np.ones(np.count_nonzero(0. < mf.mo_occ)), np.ones(np.count_nonzero(1. < mf.mo_occ)))\n        else:\n            mo_occ = (mf.mo_occ[0][np.nonzero(mf.mo_occ[0])], mf.mo_occ[1][np.nonzero(mf.mo_occ[1])])\n        # dimensions\n        alpha, beta = dim(mo_occ)\n        # mo coefficients\n        if np.asarray(mf.mo_coeff).ndim == 2:\n            mo_coeff = (mf.mo_coeff[:, alpha], mf.mo_coeff[:, beta])\n        else:\n            mo_coeff = (mf.mo_coeff[0][:, alpha], mf.mo_coeff[1][:, beta])\n\n        return mo_coeff, mo_occ\n\n\ndef orbsym(mol, mo_coeff):\n        \"\"\"\n        this functions returns orbital symmetries\n        \"\"\"\n        if isinstance(mo_coeff, np.ndarray):\n            if mo_coeff.ndim == 2:\n                try:\n                    orbsymm = symm.label_orb_symm(mol, mol.irrep_name, mol.symm_orb, mo_coeff)\n                except:\n                    orbsymm = np.array(['A'] * mo_coeff.shape[1])\n            else:\n                try:\n                    orbsymm = np.array([symm.label_orb_symm(mol, mol.irrep_name, mol.symm_orb, c) for c in mo_coeff])\n                except:\n                    orbsymm = np.array([['A'] * c.shape[1] for c in mo_coeff])\n        else:\n            try:\n                orbsymm = np.array([symm.label_orb_symm(mol, mol.irrep_name, mol.symm_orb, c) for c in mo_coeff])\n            except:\n                orbsymm = np.array([['A'] * c.shape[1] for c in mo_coeff])\n\n        return orbsymm\n\n\ndef make_rdm1(mo: np.ndarray, occup: np.ndarray) -> np.ndarray:\n        \"\"\"\n        this function returns an 1-RDM (in ao basis) corresponding to given mo(s)\n        \"\"\"\n        return contract('ip,jp->ij', occup * mo, mo)\n\n\ndef make_natorb(mol: gto.Mole, mo_coeff: np.ndarray, \\\n                rdm1: np.ndarray, thres: float = NATORB_THRES) -> Tuple[Tuple[np.ndarray, np.ndarray], \\\n                                                                        Tuple[np.ndarray, np.ndarray]]:\n        \"\"\"\n        this function returns no coefficients and occupations corresponding\n        to given mo coefficients and rdm1\n        \"\"\"\n        # reshape mo_coeff and rdm1\n        if mo_coeff.ndim == 2:\n            c = np.asarray((mo_coeff,) * 2)\n        else:\n            c = mo_coeff\n        if rdm1.ndim == 2:\n            d = np.array([rdm1, rdm1]) * .5\n        else:\n            d = rdm1\n        # overlap matrix\n        s = mol.intor_symmetric('int1e_ovlp')\n        # ao to mo transformation of dm\n        rdm1_mo = contract('xpi,pq,xqr,rs,xsj->xij', c, s, d, s, c)\n        # diagonalize rdm1_mo\n        occ_no, u = np.linalg.eigh(rdm1_mo)\n        # transform to no basis\n        mo_no = contract('xip,xpj->xij', c, u)\n        # retain only significant nos\n        return (mo_no[0][:, np.where(np.abs(occ_no[0]) >= thres)[0]], mo_no[1][:, np.where(np.abs(occ_no[1]) >= thres)[0]]), \\\n               (occ_no[0][np.where(np.abs(occ_no[0]) >= thres)], occ_no[1][np.where(np.abs(occ_no[1]) >= thres)])\n\n\ndef write_rdm1(mol: gto.Mole, part: str, \\\n               mo_coeff: np.ndarray, mo_occ: np.ndarray, fmt: str, \\\n               weights: List[np.ndarray], \\\n               suffix: str = '') -> None:\n        \"\"\"\n        this function writes a 1-RDM as a numpy or cube (default) file\n        \"\"\"\n        # assertion\n        assert part == 'atoms', '`write_rdm1` function only implemented for `atoms` partitioning'\n        assert fmt in ['cube', 'numpy'], 'fmt arg to `write_rdm1` must be `cube` or `numpy`'\n        # molecular dimensions\n        alpha, beta = dim(mo_occ)\n        # compute total 1-RDM (AO basis)\n        rdm1_tot = np.array([make_rdm1(mo_coeff[0], mo_occ[0]), make_rdm1(mo_coeff[1], mo_occ[1])])\n        # loop over atoms\n        for a in range(mol.natm):\n            # atom-specific rdm1\n            rdm1_atom = np.zeros_like(rdm1_tot)\n            # loop over spins\n            for i, spin_mo in enumerate((alpha, beta)):\n                # loop over spin-orbitals\n                for m, j in enumerate(spin_mo):\n                    # get orbital(s)\n                    orb = mo_coeff[i][:, j].reshape(mo_coeff[i].shape[0], -1)\n                    # orbital-specific rdm1\n                    rdm1_orb = make_rdm1(orb, mo_occ[i][j])\n                    # weighted contribution to rdm1_atom\n                    rdm1_atom[i] += rdm1_orb * weights[i][m][a]\n            if fmt == 'cube':\n                # write rdm1_atom as cube file\n                pyscf_tools.cubegen.density(mol, f'atom_{mol.atom_symbol(a).upper():s}{a:d}_rdm1{suffix:}.cube', \\\n                                            np.sum(rdm1_atom, axis=0))\n            else:\n                # write rdm1_atom as numpy file\n                np.save(f'atom_{mol.atom_symbol(a).upper():s}{a:d}_rdm1{suffix:}.npy', np.sum(rdm1_atom, axis=0))\n\n\ndef res_add(res_a, res_b):\n        \"\"\"\n        this function adds two result dictionaries\n        \"\"\"\n        return {key: res_a[key] + res_b[key] for key in res_a.keys()}\n\n\ndef res_sub(res_a, res_b):\n        \"\"\"\n        this function subtracts two result dictionaries\n        \"\"\"\n        return {key: res_a[key] - res_b[key] for key in res_a.keys()}\n\n\ndef contract(eqn, *tensors):\n        \"\"\"\n        interface to optimized einsum operation\n        \"\"\"\n        if OE_AVAILABLE:\n            return oe.contract(eqn, *tensors)\n        else:\n            return np.einsum(eqn, *tensors, optimize=True)\n\n\n", "meta": {"hexsha": "4404ab7f872b125d775084569215a89c507428c5", "size": 8037, "ext": "py", "lang": "Python", "max_stars_repo_path": "decodense/tools.py", "max_stars_repo_name": "luna-component/decodense", "max_stars_repo_head_hexsha": "2579b7a3b7500b32ab231ebacb35c91e87e96735", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "decodense/tools.py", "max_issues_repo_name": "luna-component/decodense", "max_issues_repo_head_hexsha": "2579b7a3b7500b32ab231ebacb35c91e87e96735", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "decodense/tools.py", "max_forks_repo_name": "luna-component/decodense", "max_forks_repo_head_hexsha": "2579b7a3b7500b32ab231ebacb35c91e87e96735", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4935622318, "max_line_length": 126, "alphanum_fraction": 0.5283065821, "include": true, "reason": "import numpy", "num_tokens": 2094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.198468367499571}}
{"text": "import numpy as np\nfrom cppdefs import *\nfrom pom.modules_old import RLEN, bfm_lwp, LOGUNIT, seconds_per_day\n\n\nclass TimeInfo:\n\n    def __init__(self, date0, time0, timeEnd, step0, timestep, stepnow, stepEnd):\n        self.date0 = date0\n        self.time0 = time0\n        self.timeEnd = timeEnd\n        self.step0 = step0\n        self.timestep = timestep\n        self.stepnow = stepnow\n        self.stepEnd = stepEnd\n\n\n# PUBLIC DATA MEMBERS:\ntimestr = ' ' * 19\nstart = '2000-01-01 00:00:00'\nstop = ' ' * 19\n\n# PRIVATE DATA MEMBERS\njul0 = -1\nsecs0 = -1\n\n\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n#\n# # ROUTINE: INITIALIZE THE TIME SYSTEM\n#\n# DESCRIPTION:  The subroutine {\\tt init\\_time()} initialises the time module by reading\n#               a namelist and take actions according to the specifications.\n#               On exit from this subroutine the two variables MinN and MaxN have well\n#               defined values and can be used in the time loop.\n#\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\ndef initialize_time_system(MinN,MaxN,timestep,timefmt,simdays,start,stop):\n\n    \"\"\"\n    Description: Initializes the time module by reading a namelist.\n                 Takes actions accrding to the specifications.\n\n    :param MinN: minimum number of time steps\n    :param MaxN: maximum number of time steps\n    :param timestep: size of time step\n    :param timefmt: time format\n    :param simdays: number of days for simulation\n    :param start: start date\n    :param stop: end date\n    :return:\n    \"\"\"\n\n    jul1 = -1\n    secs1 = -1\n\n    # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n    #   READ TIME SPECIFIC THINGS FROM THE NAMELIST\n    # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n    LEVEL1(); print('initialize_time_system')\n\n    # CALCULATE MaxN -> MinN IS 1 IF NOT CHANGED BY HOTSTART\n    MinN = 1\n    LEVEL2(); print('Time step:      ', timestep, ' seconds')\n    LEVEL2(); print('Time format:    ', timefmt)\n\n    if timefmt == 1:\n        HasRealTime = False\n        LEVEL2(); print('# of timesteps: ', MaxN)\n        # start = '2000-01-01 00:00:00'\n        LEVEL2(); print('Fake start:     ', start)\n\n    elif timefmt == 2:\n        HasRealTime = True\n        LEVEL2(); print('Start:          ', start)\n        LEVEL2(); print('Stop:           ', stop)\n        jul1, secs1 = read_time_string(start)\n        jul2, secs2 = read_time_string(stop)\n\n        nsecs = time_diff(jul2, secs2, jul1, secs1)\n        MaxN = round(nsecs / timestep)\n\n        ndays = jul2 - jul1\n        if nsecs < 86400 and jul1 != jul2:\n            ndays = ndays - 1\n\n        nsecs = nsecs - 86400 * ndays\n        string = '  ==> ' + str(ndays) + ' day(s) and ' + str(nsecs) + ' seconds ==> ' + str(MaxN) + ' time steps'\n        STDERR(string)\n\n    elif timefmt == 3:\n        HasRealTime = True\n        LEVEL2(); print('Start:          ', start)\n        LEVEL2(); print('# of timesteps: ', MaxN)\n\n        jul1, secs1 = read_time_string(start)\n\n        nsecs = np.rint(MaxN * timestep) + secs1\n        ndays = nsecs / 86400\n        jul2 = jul1 + ndays\n        secs2 = nsecs % 86400\n\n        write_time_string(jul2, secs2)\n        LEVEL2(); print('Stop:           ', stop)\n\n    elif timefmt == 4:\n        HasRealTime = False\n        nsecs = simdays * 86400\n        MaxN = np.rint(nsecs / timestep)\n        LEVEL2(); print('# of timesteps: ', MaxN)\n        # start = '2000-01-01 00:00:00'\n        LEVEL2(); print('Fake start:     ', start)\n\n    else:\n        STDERR('Fatal error: A non valid input format has been chosen')\n        return\n\n    jul0 = jul1\n    secs0 = secs1\n\n    julianday = jul0\n    secondsofday = secs0\n\n    simtime = timestep * (MaxN - MinN + 1)\n\n    # SET BFM TIME\n    jday = float(jul0)\n    yy, mm, dd, hh, nn = calendar_date(jday)\n\n    bfmtime = TimeInfo(str(yy) + '-' + str(mm) + '-' + str(dd) + ' ' + str(hh) + ':' + str(nn),\n                       jday,\n                       jday + (float(MaxN) * timestep) / seconds_per_day,\n                       MinN - 1,\n                       timestep,\n                       MinN - 1,\n                       MaxN)\n\n    LEVEL2(); print('bfmtime : ', bfmtime)\n\n    return bfmtime\n\n\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n#\n# # ROUTINE: CONVERT TRUE JULIAN DAY TO CALENDAR DATE\n#\n# DESCRIPTION:  Converts a Julian day to a calendar date --- year, month and day.\n#               Based on a similar routine in \\emph{Numerical Recipes}.\n#\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\ndef calendar_date(julian):\n\n    \"\"\"\n    Description: Converts a Julian day to a calender date --- year, month, and day\n\n    :param julian: Julian day\n    :return: calender date\n    \"\"\"\n\n    # LOCAL VARIABLES\n    IGREG = 2299161\n\n    # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n    jday = np.floor(julian)\n    if jday >= IGREG:\n        x = ((jday - 1867216) - 0.25) / 36524.25\n        ja = jday + 1 + int(x) - int(0.25 * x)\n    else:\n        ja = jday\n\n    jb = ja + 1524\n    jc = int(6680 + ((jb - 2439870) - 122.1) / 365.25)\n    jd = int(365 * jc + (0.25 * jc))\n    je = int((jb - jd) / 30.6001)\n\n    dd = jb - jd - int(30.6001 * je)\n    mm = je - 1\n\n    if mm > 12:\n        mm = mm - 12\n\n    yyyy = jc - 4715\n\n    if mm > 2:\n        yyyy = yyyy - 1\n\n    if yyyy <= 0:\n        yyyy = yyyy - 1\n\n    res = julian - float(jday)\n    hh = np.floor(res * 24)\n    nn = np.floor(((res * 24) - float(hh)) * 60)\n\n    return yyyy, mm, dd, hh, nn\n\n\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n#\n# # ROUTINE: CONVERT CALENDAR DATE TO JULIAN DAY\n#\n# DESCRIPTION:  Converts a calendar date to a Julian day.\n#               Based on a similar routine in \\emph{Numerical Recipes}.\n#\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\ndef julian_day(yyyy,mm,dd,hh,nn):\n\n    \"\"\"\n    Description: Converts a calender date to a Julian day.\n\n    :param yyyy: year\n    :param mm: month\n    :param dd: day\n    :param hh: hour\n    :param nn: minute\n    :return: Julian day\n    \"\"\"\n\n    # LOCAL VARIABLES\n    IGREG = 15 + 31 * (10 + 12 * 1582)\n\n    # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n    jy = yyyy\n    if jy < 0:\n        jy = jy + 1\n\n    if mm > 2:\n        jm = mm + 1\n    else:\n        jy = jy - 1\n        jm = mm + 13\n\n    jday = int(np.floor(365.25 * jy) + np.floor(30.6001 * jm) + dd + 1720995)\n    if dd + 31 * (mm + 12 * yyyy) >= IGREG:\n        ja = int(0.01 * jy)\n        jday = jday + 2 - ja + int(0.25 * ja)\n\n    jh = hh\n    jn = nn\n\n    if jn >= 60:\n        jh = jh + 1\n        jn = jn - 60\n\n    if jh >= 24:\n        jday = jday + 1\n        jh = jh - 24\n\n    julian = float(jday) + float(jh) / 24 + float(jn) / (24 * 60)\n\n    return julian\n\n\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n#\n# # ROUTINE: KEEP TRACK OF TIME (JULIAN DAYS AND SECONDS)\n#\n# DESCRIPTION:  Based on a starting time this routine calculates the actual time\n#               in a model integration using the number of time steps, {\\tt n},\n#               and the size of the time step, {\\tt timestep}. More public variables\n#               can be updated here if necessary.\n#\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\ndef update_time(n,timestep,secs0):\n\n    \"\"\"\n    Description: Based on a starting time this routine calculates the actual time in a model integration\n                 using the number of time steps and the size of the time step.\n\n    :param n: number of time steps\n    :param timestep: size of time step\n    :param secs0:\n    :return: actual time in a model integration\n    \"\"\"\n\n    nsecs = np.rint(n * timestep) + secs0\n    fsecs = n * timestep + secs0\n    julianday = jul0 + nsecs / 86400\n    secondsofday = nsecs % 86400\n\n    return fsecs, julianday, secondsofday\n\n\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n#\n# # ROUTINE: CONVERT A TIME STRING TO JULIAN DAY AND SECONDS\n#\n# DESCRIPTION:  Converts a time string to the true Julian day and seconds of that day.\n#               The format of the time string must be: {\\tt yyyy-mm-dd hh:hh:ss }.\n#\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\ndef read_time_string(timestr):\n\n    \"\"\"\n    Description: Converts a time string to the true Julian day and the seconds of that day.\n\n    :param timestr: time string\n    :return: Julian day and seconds of that day\n    \"\"\"\n\n    yy = timestr[0:4]\n    mm = timestr[5:7]\n    dd = timestr[8:10]\n    hh = timestr[11:13]\n    mins = timestr[14:16]\n    ss = timestr[17:19]\n\n    julian, jday = julian_day(yy,mm,dd,0,0)\n    jul = int(jday)\n    secs = 3600*hh + 60*mins + ss\n\n    return jul, secs\n\n\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n#\n# # ROUTINE: CONVERT JULIAN DAY AND SECONDS TO A TIME STRING\n#\n# DESCRIPTION:  Formats Julian day and seconds of that day to a nice looking\n#               character string.\n#\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n\ndef write_time_string(jul,secs):\n\n    \"\"\"\n    Description: Formats Julian day and seconds of that day into a character string.\n\n    :param jul: Julian day\n    :param secs: seconds of Julian day\n    :return: time string\n    \"\"\"\n\n    jday = float(jul)\n    yy, mm, dd, hh, nn = calendar_date(jday)\n\n    hh = secs / 3600\n    mins = (secs - hh * 3600) / 60\n    ss = secs - 3600 * hh - 60 * mins\n\n    timestr = str(yy) + '-' + str(mm) + '-' + str(dd) + ' ' + str(hh) + ':' + str(mins) + ':' + str(ss)\n\n    return timestr\n\n\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n#\n# # ROUTINE: RETURN THE TIME DIFFERENCE IN SECONDS\n#\n# DESCRIPTION:  This functions returns the time difference between two\n#               dates in seconds. The dates are given as Julian day and seconds\n#               of that day.\n#\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\ndef time_diff(jul2,secs2,jul1,secs1):\n\n    \"\"\"\n    Description: Returns the time difference between two dates in seconds.\n\n    :param jul2: Julian day 2\n    :param secs2: seconds of julian day 2\n    :param jul1: Julian day 1\n    :param secs1: seconds of julian day 1\n    :return: difference between Julian day 2 and Julian day 1\n    \"\"\"\n\n    time_diff = 86400*(jul2-jul1) + (secs2-secs1)\n\n    return time_diff\n\n\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n#\n# # ROUTINE: CONVERT A CALENDAR DATE TO TRUE JULIAN DAY\n#\n# DESCRIPTION:  Converts a Julian day to the day number in the current year\n#\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\ndef dayofyear(julian,yy):\n\n    \"\"\"\n    Description: Converts a Julian day to the day number in the curent year.\n\n    :param julian: Julian day\n    :param yy: current year\n    :return: day number of the current year\n    \"\"\"\n\n    jday = float(julian)\n    calendar_date(jday)\n    julian0, jday = julian_day(yy,1,1,0,0)\n\n    ddyear = julian - int(julian0) + 1\n\n    return ddyear\n\n\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n#\n# # ROUTINE:\n#\n# DESCRIPTION:\n#\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\ndef eomdays(Year,Month):\n\n    \"\"\"\n    Description: Provides system with the number of days in a given month.\n                 Accounts for leap year using Year input.\n\n    :param Year: current year\n    :param Month: current month\n    :return: numbr of days in current month\n    \"\"\"\n\n    eomdays = 0\n    if Month < 1 or Month > 12:\n        print('eomdays: Invalid Month!!')\n    elif Month in [1,3,4,7,8,10,12]:  # Jan, Mar, May, July, Aug, Oct, Dec\n        eomdays = 31\n    elif Month == 2:  # Feb\n        eomdays = 28\n        if Year % 4 == 0:  # Leap Year\n            eomdays = 29\n    else:  # Apr, June, Sep, Nov\n        eomdays = 30\n\n    return eomdays\n\n\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n#\n# # ROUTINE:\n#\n# DESCRIPTION:\n#\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n\ndef yeardays(Year):\n\n    \"\"\"\n    Description: Provides system with the number of days in the current year.\n\n    :param Year: current year\n    :return: number of days in current year\n    \"\"\"\n\n    yeardays = 0\n    for i in range(0,12):\n        yeardays = yeardays + float(eomdays(Year,i))\n\n    if yeardays == 0 or yeardays > 366:\n        print('yeardays out of bounds!!')\n\n    return yeardays\n\n\n\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n#   Copyright by the GOTM-team under the GNU Public License - www.gnu.org\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n", "meta": {"hexsha": "f2e3c50f61302c0601f5171365c956e5f760e110", "size": 13966, "ext": "py", "lang": "Python", "max_stars_repo_path": "share/time.py", "max_stars_repo_name": "MalikJordan/pyPOM1D", "max_stars_repo_head_hexsha": "196e5f52e4fb770a938f977a092d7eac77f61565", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "share/time.py", "max_issues_repo_name": "MalikJordan/pyPOM1D", "max_issues_repo_head_hexsha": "196e5f52e4fb770a938f977a092d7eac77f61565", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "share/time.py", "max_forks_repo_name": "MalikJordan/pyPOM1D", "max_forks_repo_head_hexsha": "196e5f52e4fb770a938f977a092d7eac77f61565", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-17T19:50:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-17T19:50:00.000Z", "avg_line_length": 29.4641350211, "max_line_length": 120, "alphanum_fraction": 0.4500214807, "include": true, "reason": "import numpy", "num_tokens": 3590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.198468367499571}}
{"text": "\"\"\"Inception_ResNet 1D models in Tensorflow-Keras.\nReference - [Rethinking the Inception Architecture for Computer Vision](http://arxiv.org/abs/1512.00567)\nInception_ResNet Review: https://towardsdatascience.com/review-inception-v4-evolved-from-googlenet-merged-with-resnet-idea-image-classification-5e8c339d18bc\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\n\n\ndef Conv_1D_Block(x, model_width, kernel, strides=1, padding=\"same\"):\n    # 1D Convolutional Block with BatchNormalization\n    x = tf.keras.layers.Conv1D(model_width, kernel, strides=strides, padding=padding, kernel_initializer=\"he_normal\")(x)\n    x = tf.keras.layers.BatchNormalization()(x)\n    x = tf.keras.layers.Activation('relu')(x)\n\n    return x\n\n\ndef classifier(inputs, class_number):\n    # Construct the Classifier Group\n    # inputs       : input vector\n    # class_number : number of output classes\n    out = tf.keras.layers.Dense(class_number, activation='softmax')(inputs)\n    return out\n\n\ndef regressor(inputs, feature_number):\n    # Construct the Regressor Group\n    # inputs         : input vector\n    # feature_number : number of output features\n    out = tf.keras.layers.Dense(feature_number, activation='linear')(inputs)\n    return out\n\n\ndef SE_Block(inputs, num_filters, ratio):\n    squeeze = tf.keras.layers.GlobalAveragePooling1D()(inputs)\n\n    excitation = tf.keras.layers.Dense(units=num_filters/ratio)(squeeze)\n    excitation = tf.keras.layers.Activation('relu')(excitation)\n    excitation = tf.keras.layers.Dense(units=num_filters)(excitation)\n    excitation = tf.keras.layers.Activation('sigmoid')(excitation)\n    excitation = tf.keras.layers.Reshape([1, num_filters])(excitation)\n\n    scale = inputs * excitation\n\n    return scale\n\n\ndef Inception_ResNet_Module_A(inputs, filterB1_1, filterB2_1, filterB2_2, filterB3_1, filterB3_2, filterB3_3, filterB4_1, i):\n    # Inception ResNet Module A - Block i\n    branch1x1 = Conv_1D_Block(inputs, filterB1_1, 1)\n\n    branch3x3 = Conv_1D_Block(inputs, filterB2_1, 1)\n    branch3x3 = Conv_1D_Block(branch3x3, filterB2_2, 3)\n\n    branch3x3dbl = Conv_1D_Block(inputs, filterB3_1, 1)\n    branch3x3dbl = Conv_1D_Block(branch3x3dbl, filterB3_2, 3)\n    branch3x3dbl = Conv_1D_Block(branch3x3dbl, filterB3_3, 3)\n\n    branch_concat = tf.keras.layers.concatenate([branch1x1, branch3x3, branch3x3dbl], axis=-1)\n    branch1x1_ln = tf.keras.layers.Conv1D(filterB4_1, 1, activation='linear', strides=1, padding='same', kernel_initializer=\"he_normal\")(branch_concat)\n\n    x = tf.keras.layers.Add(name='Inception_ResNet_Block_A'+str(i))([inputs, branch1x1_ln])\n    x = tf.keras.layers.BatchNormalization()(x)\n    out = tf.keras.layers.Activation('relu')(x)\n\n    return out\n\n\ndef Inception_ResNet_Module_B(inputs, filterB1_1, filterB2_1, filterB2_2, filterB2_3, filterB3_1, i):\n    # Inception ResNet Module B - Block i\n    branch1x1 = Conv_1D_Block(inputs, filterB1_1, 1)\n\n    branch7x7 = Conv_1D_Block(inputs, filterB2_1, 1)\n    branch7x7 = Conv_1D_Block(branch7x7, filterB2_2, 7)\n    branch7x7 = Conv_1D_Block(branch7x7, filterB2_3, 7)\n\n    branch_concat = tf.keras.layers.concatenate([branch1x1, branch7x7], axis=-1)\n    branch1x1_ln = tf.keras.layers.Conv1D(filterB3_1, 1, activation='linear', strides=1, padding='same', kernel_initializer=\"he_normal\")(branch_concat)\n\n    x = tf.keras.layers.Add(name='Inception_ResNet_Block_B'+str(i))([inputs, branch1x1_ln])\n    x = tf.keras.layers.BatchNormalization()(x)\n    out = tf.keras.layers.Activation('relu')(x)\n\n    return out\n\n\ndef Inception_ResNet_Module_C(inputs, filterB1_1, filterB2_1, filterB2_2, filterB2_3, filterB3_1, i):\n    # Inception ResNet Module C - Block i\n    branch1x1 = Conv_1D_Block(inputs, filterB1_1, 1)\n\n    branch3x3 = Conv_1D_Block(inputs, filterB2_1, 1)\n    branch3x3 = Conv_1D_Block(branch3x3, filterB2_2, 3)\n    branch3x3 = Conv_1D_Block(branch3x3, filterB2_3, 3)\n\n    branch_concat = tf.keras.layers.concatenate([branch1x1, branch3x3], axis=-1)\n    branch1x1_ln = tf.keras.layers.Conv1D(filterB3_1, 1, activation='linear', strides=1, padding='same', kernel_initializer=\"he_normal\")(branch_concat)\n\n    x = tf.keras.layers.Add(name='Inception_ResNet_Block_C'+str(i))([inputs, branch1x1_ln])\n    x = tf.keras.layers.BatchNormalization()(x)\n    out = tf.keras.layers.Activation('relu')(x)\n\n    return out\n\n\ndef Reduction_Block_A(inputs, filterB1_1, filterB2_1, filterB2_2, filterB2_3):\n    # Reduction Block A\n    branch_pool = tf.keras.layers.MaxPooling1D(pool_size=3, strides=2)(inputs)\n\n    branch3x3 = Conv_1D_Block(inputs, filterB1_1, 3, strides=2, padding='valid')\n\n    branch3x3dbl = Conv_1D_Block(inputs, filterB2_1, 1)\n    branch3x3dbl = Conv_1D_Block(branch3x3dbl, filterB2_2, 3)\n    branch3x3dbl = Conv_1D_Block(branch3x3dbl, filterB2_3, 3, strides=2, padding='valid')\n\n    x = tf.keras.layers.concatenate([branch_pool, branch3x3, branch3x3dbl], axis=-1, name='Reduction_Block_A')\n    x = tf.keras.layers.BatchNormalization()(x)\n    out = tf.keras.layers.Activation('relu')(x)\n\n    return out\n\n\ndef Reduction_Block_B(inputs, filterB1_1, filterB1_2, filterB2_1, filterB2_2, filterB3_1, filterB3_2, filterB3_3):\n    # Reduction Block B\n    branch_pool = tf.keras.layers.MaxPooling1D(pool_size=3, strides=2)(inputs)\n\n    branch3x3 = Conv_1D_Block(inputs, filterB1_1, 1)\n    branch3x3 = Conv_1D_Block(branch3x3, filterB1_2, 3, strides=2, padding='valid')\n\n    branch3x3_2 = Conv_1D_Block(inputs, filterB2_1, 1)\n    branch3x3_2 = Conv_1D_Block(branch3x3_2, filterB2_2, 3, strides=2, padding='valid')\n\n    branch3x3dbl = Conv_1D_Block(inputs, filterB3_1, 1)\n    branch3x3dbl = Conv_1D_Block(branch3x3dbl, filterB3_2, 3)\n    branch3x3dbl = Conv_1D_Block(branch3x3dbl, filterB3_3, 3, strides=2, padding='valid')\n\n    x = tf.keras.layers.concatenate([branch_pool, branch3x3, branch3x3_2, branch3x3dbl], axis=-1)\n    x = tf.keras.layers.BatchNormalization()(x)\n    out = tf.keras.layers.Activation('relu')(x)\n\n    return out\n\n\nclass SEInception_ResNet:\n    def __init__(self, length, num_channel, num_filters, ratio=4, problem_type='Regression',\n                 output_nums=1, pooling='avg', dropout_rate=False, auxilliary_outputs=False):\n        # length: Input Signal Segments Length\n        # model_depth: Depth of the Model\n        # model_width: Width of the Model\n        # kernel_size: Kernel or Filter Size of the Input Convolutional Layer\n        # num_channel: Number of Channels of the Input Predictor Signals\n        # problem_type: Regression or Classification\n        # output_nums: Number of Output Classes in Classification mode and output features in Regression mode\n        # pooling: Choose either 'max' for MaxPooling or 'avg' for Averagepooling\n        # dropout_rate: If turned on, some layers will be dropped out randomly based on the selected proportion\n        # auxilliary_outputs: Two extra Auxullary outputs for the Inception models, acting like Deep Supervision\n        self.length = length\n        self.num_channel = num_channel\n        self.num_filters = num_filters\n        self.ratio = ratio\n        self.problem_type = problem_type\n        self.output_nums = output_nums\n        self.pooling = pooling\n        self.dropout_rate = dropout_rate\n        self.auxilliary_outputs = auxilliary_outputs\n\n    def MLP(self, x):\n        if self.pooling == 'avg':\n            x = tf.keras.layers.GlobalAveragePooling1D()(x)\n        elif self.pooling == 'max':\n            x = tf.keras.layers.GlobalMaxPooling1D()(x)\n        x = tf.keras.layers.Flatten()(x)\n        if self.dropout_rate:\n            x = tf.keras.layers.Dropout(self.dropout_rate)(x)\n        outputs = tf.keras.layers.Dense(self.output_nums, activation='linear')(x)\n        if self.problem_type == 'Classification':\n            outputs = tf.keras.layers.Dense(self.output_nums, activation='softmax')(x)\n\n        return outputs\n\n    def SEInception_ResNet_v1(self):\n        inputs = tf.keras.Input((self.length, self.num_channel))  # The input tensor\n        # Stem\n        x = Conv_1D_Block(inputs, 32, 3, strides=2, padding='valid')\n        x = Conv_1D_Block(x, 32, 3, padding='valid')\n        x = Conv_1D_Block(x, 64, 3)\n        x = tf.keras.layers.MaxPooling1D(3, strides=2)(x)\n        x = Conv_1D_Block(x, 80, 1)\n        x = Conv_1D_Block(x, 192, 3, padding='valid')\n        x = Conv_1D_Block(x, 256, 3, strides=2, padding='valid')\n\n        # 5x Inception ResNet A Blocks - 35 x 35 x 256\n        for i in range(5):\n            x = Inception_ResNet_Module_A(x, 32, 32, 32, 32, 32, 32, 256, i)\n            x = SE_Block(x, int(np.shape(x)[-1]), self.ratio)\n\n        aux_output_0 = []\n        if self.auxilliary_outputs:\n            # Auxilliary Output 0\n            aux_pool = tf.keras.layers.AveragePooling1D(pool_size=5, strides=3)(x)\n            aux_conv = Conv_1D_Block(aux_pool, 128, 1)\n            aux_conv = Conv_1D_Block(aux_conv, 768, 5, padding='valid')\n            aux_output_0 = self.MLP(aux_conv)\n\n        x = Reduction_Block_A(x, 384, 192, 224, 256)  # Reduction Block A: 17 x 17 x 768\n\n        # 10x Inception ResNet B Blocks - 17 x 17 x 768\n        for i in range(10):\n            x = Inception_ResNet_Module_B(x, 128, 128, 128, 128, 896, i)\n            x = SE_Block(x, int(np.shape(x)[-1]), self.ratio)\n\n        aux_output_1 = []\n        if self.auxilliary_outputs:\n            # Auxilliary Output 1\n            aux_pool = tf.keras.layers.AveragePooling1D(pool_size=5, strides=3, padding='valid')(x)\n            aux_conv = Conv_1D_Block(aux_pool, 128, 1)\n            aux_conv = Conv_1D_Block(aux_conv, 768, 5, padding='valid')\n            aux_output_1 = self.MLP(aux_conv)\n\n        x = Reduction_Block_B(x, 256, 384, 256, 256, 256, 256, 256)  # Reduction Block B: 8 x 8 x 1280\n\n        # 5x Inception ResNet C Blocks - 8 x 8 x 1280\n        for i in range(5):\n            x = Inception_ResNet_Module_C(x, 128, 192, 192, 192, 1792, i)\n            x = SE_Block(x, int(np.shape(x)[-1]), self.ratio)\n\n        # Final Dense MLP Layer for the outputs\n        final_output = self.MLP(x)\n        # Create model.\n        model = tf.keras.Model(inputs, final_output, name='Inception_v4')\n        if self.auxilliary_outputs:\n            model = tf.keras.Model(inputs, outputs=[final_output, aux_output_0, aux_output_1], name='Inception_ResNet_v1')\n\n        return model\n\n    def SEInception_ResNet_v2(self):\n        inputs = tf.keras.Input((self.length, self.num_channel))  # The input tensor\n        # Stem\n        x = Conv_1D_Block(inputs, 32, 3, strides=2, padding='valid')\n        x = Conv_1D_Block(x, 32, 3, padding='valid')\n        x = Conv_1D_Block(x, 64, 3)\n        #\n        branch1 = Conv_1D_Block(x, 96, 3, strides=2, padding='valid')\n        branch2 = tf.keras.layers.MaxPooling1D(3, strides=2)(x)\n        x = tf.keras.layers.concatenate([branch1, branch2], axis=-1)\n        #\n        branch1 = Conv_1D_Block(x, 64, 1)\n        branch1 = Conv_1D_Block(branch1, 96, 3, padding='valid')\n        branch2 = Conv_1D_Block(x, 64, 1)\n        branch2 = Conv_1D_Block(branch2, 64, 7)\n        branch2 = Conv_1D_Block(branch2, 96, 3, padding='valid')\n        x = tf.keras.layers.concatenate([branch1, branch2], axis=-1)\n        #\n        branch1 = Conv_1D_Block(x, 192, 3, padding='valid')\n        branch2 = tf.keras.layers.MaxPooling1D(3, strides=1)(x)\n        x = tf.keras.layers.concatenate([branch1, branch2], axis=-1)\n\n        # 5x Inception ResNet A Blocks - 35 x 35 x 256\n        for i in range(10):\n            x = Inception_ResNet_Module_A(x, 32, 32, 32, 32, 48, 64, 384, i)\n            x = SE_Block(x, int(np.shape(x)[-1]), self.ratio)\n\n        aux_output_0 = []\n        if self.auxilliary_outputs:\n            # Auxilliary Output 0\n            aux_pool = tf.keras.layers.AveragePooling1D(pool_size=5, strides=3, padding='valid')(x)\n            aux_conv = Conv_1D_Block(aux_pool, 96, 1)\n            aux_output_0 = self.MLP(aux_conv)\n\n        x = Reduction_Block_A(x, 384, 192, 224, 256)  # Reduction Block A: 17 x 17 x 768\n\n        # 10x Inception ResNet B Blocks - 17 x 17 x 768\n        for i in range(20):\n            x = Inception_ResNet_Module_B(x, 192, 128, 160, 192, 1024, i)\n            x = SE_Block(x, int(np.shape(x)[-1]), self.ratio)\n\n        aux_output_1 = []\n        if self.auxilliary_outputs:\n            # Auxilliary Output 1\n            aux_pool = tf.keras.layers.AveragePooling1D(pool_size=5, strides=3, padding='valid')(x)\n            aux_conv = Conv_1D_Block(aux_pool, 128, 1)\n            aux_conv = Conv_1D_Block(aux_conv, 768, 5)\n            aux_output_1 = self.MLP(aux_conv)\n\n        x = Reduction_Block_B(x, 256, 384, 256, 288, 256, 288, 320)  # Reduction Block B: 8 x 8 x 1280\n\n        # 5x Inception ResNet C Blocks - 8 x 8 x 1280\n        for i in range(10):\n            x = Inception_ResNet_Module_C(x, 192, 192, 224, 256, 2016, i)\n            x = SE_Block(x, int(np.shape(x)[-1]), self.ratio)\n\n        # Final Dense MLP Layer for the outputs\n        final_output = self.MLP(x)\n        # Create model.\n        model = tf.keras.Model(inputs, final_output)\n        if self.auxilliary_outputs:\n            model = tf.keras.Model(inputs, outputs=[final_output, aux_output_0, aux_output_1])\n\n        return model\n\n\nif __name__ == '__main__':\n    # Configurations\n    length = 1024  # Length of each segment\n    model_name = 'SEInceptionResNetV1'  # DenseNet Models\n    model_width = 64 # Width of the Initial Layer, subsequent layers start from here\n    num_channel = 1  # Number of Input Channels in the Model\n    problem_type = 'Regression' # Classification or Regression\n    output_nums = 1  # Number of Class for Classification Problems, always '1' for Regression Problems\n    reduction_ratio = 8  # Reduction Ratio or Cardinality for the Squeeze and Excite Block\n    #\n    Model = SEInception_ResNet(length, num_channel, model_width, ratio=reduction_ratio, problem_type=problem_type, output_nums=output_nums,\n                      pooling='avg', dropout_rate=False, auxilliary_outputs=False).SEInception_ResNet_v1()\n    Model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.0003), loss=tf.keras.losses.MeanAbsoluteError(), metrics=tf.keras.metrics.MeanSquaredError())\n    Model.summary()\n", "meta": {"hexsha": "6a540390a0bd8017d9405b93578eff58f1a96d99", "size": 14122, "ext": "py", "lang": "Python", "max_stars_repo_path": "Codes/SE_Inception_ResNet_1DCNN.py", "max_stars_repo_name": "Sakib1263/Inception-InceptionResNet-SEInception-SEInceptionResNet-1D-2D-Tensorflow-Keras", "max_stars_repo_head_hexsha": "022b1bd1ef70adbfebb8bfa751e7c4bf87296f87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-27T13:24:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T13:24:29.000Z", "max_issues_repo_path": "Codes/SE_Inception_ResNet_1DCNN.py", "max_issues_repo_name": "Sakib1263/Inception-InceptionResNet-SEInception-SEInceptionResNet-1D-2D-Tensorflow-Keras", "max_issues_repo_head_hexsha": "022b1bd1ef70adbfebb8bfa751e7c4bf87296f87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Codes/SE_Inception_ResNet_1DCNN.py", "max_forks_repo_name": "Sakib1263/Inception-InceptionResNet-SEInception-SEInceptionResNet-1D-2D-Tensorflow-Keras", "max_forks_repo_head_hexsha": "022b1bd1ef70adbfebb8bfa751e7c4bf87296f87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.6898734177, "max_line_length": 162, "alphanum_fraction": 0.6768871265, "include": true, "reason": "import numpy", "num_tokens": 4192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.19844911265311882}}
{"text": "# MIT License\n#\n# Copyright (c) 2016-2017 Anders Steen Christensen, Lars Andersen Bratholm\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport numpy as np\nimport copy\n\nfrom arad import ARAD\nfrom aras import ARAS\n\nfrom data import NUCLEAR_CHARGE\n\nfrom representations import fgenerate_coulomb_matrix\nfrom representations import fgenerate_unsorted_coulomb_matrix\nfrom representations import fgenerate_local_coulomb_matrix\nfrom representations import fgenerate_atomic_coulomb_matrix\n\nHOF_DFTB3 = dict()\nHOF_DFTB3[\"H\"] = -172.3145\nHOF_DFTB3[\"C\"] = -906.4342\nHOF_DFTB3[\"N\"] = -1327.2991\nHOF_DFTB3[\"O\"] = -1936.6161\nHOF_DFTB3[\"S\"] = -1453.3907\n\n\nclass Molecule(object):\n    \"\"\" Implemented molecular descriptors:\n        1. Sorted Coulomb Matrix\n        2. Unsorted Coulomb Matrix\n        3. Sorted Coulomb Matrix Eigenvalues\n        4. Reduced Coulomb Matrix\n        5. Bag of Bonds\n\n        Implemented local descriptors:\n        1. Local Coulomb Matrix\n        2. Atomic Coulomb Matrix\n        3. ARAD\n        4. ARAS\n\n        Implemented periodic descriptors\n        1. ARAD\n        2. ARAS\n    \"\"\"\n\n    def __init__(self):\n        self.natoms = -1\n        self.energy = float(\"nan\")\n        self.molid = -1\n        self.name = None\n        self.dftb3_energy = float(\"nan\")\n        self.dftb3_hof = float(\"nan\")\n\n        self.atomtypes = []\n        self.nuclear_charges = []\n        self.coordinates = []\n        self.active_atoms = []\n        self.unit_cell = None\n\n        # Container for misc properties\n        self.properties = []\n        self.properties2 = []\n\n    def generate_coulomb_matrix(self, size=23):\n        self.descriptor = fgenerate_coulomb_matrix(self.nuclear_charges, \\\n                self.coordinates, self.natoms, size)\n\n    def generate_bob(self, size = 23, asize = {\"O\":3, \"C\":7, \"N\":3, \"H\":16, \"S\":1}):\n        coulomb_matrix = fgenerate_unsorted_coulomb_matrix(self.nuclear_charges,\n                self.coordinates, self.natoms, size)\n        coulomb_matrix = vector_to_matrix(coulomb_matrix)\n        self.descriptor = []\n        self.atomtypes = np.asarray(self.atomtypes)\n        for atom1, size1 in asize.items():\n            pos1 = np.where(self.atomtypes == atom1)[0]\n            feature_vector = np.zeros(size1)\n            feature_vector[:pos1.size] = np.diag(coulomb_matrix)[pos1]\n            feature_vector.sort()\n            self.descriptor.append(feature_vector[:])\n            for atom2, size2 in asize.items():\n                if atom1 > atom2:\n                    continue\n                if atom1 == atom2:\n                    size = size1*(size1-1)/2\n                    feature_vector = np.zeros(size)\n                    sub_matrix = coulomb_matrix[np.ix_(pos1,pos1)]\n                    feature_vector[:pos1.size*(pos1.size-1)/2] = sub_matrix[np.triu_indices(pos1.size, 1)]\n                    feature_vector.sort()\n                    self.descriptor.append(feature_vector[:])\n                else:\n                    pos2 = np.where(self.atomtypes == atom2)[0]\n                    feature_vector = np.zeros(size1*size2)\n                    feature_vector[:pos1.size*pos2.size] = coulomb_matrix[np.ix_(pos1,pos2)].ravel()\n                    feature_vector.sort()\n                    self.descriptor.append(feature_vector[:])\n\n        self.descriptor = np.concatenate(self.descriptor)\n\n    def generate_eigenvalue_coulomb_matrix(self, size=23):\n        coulomb_matrix = fgenerate_coulomb_matrix(self.nuclear_charges, \\\n                self.coordinates, self.natoms, size)\n        self.descriptor = np.linalg.eigh(vector_to_matrix(coulomb_matrix))[0]\n\n    def generate_reduced_coulomb_matrix(self, size=23):\n        coulomb_matrix = fgenerate_coulomb_matrix(self.nuclear_charges, \\\n                self.coordinates, self.natoms, size)\n        coulomb_matrix = vector_to_matrix(coulomb_matrix)\n        self.descriptor = np.concatenate([np.diag(coulomb_matrix), coulomb_matrix[1:,0]])\n\n    def generate_unsorted_coulomb_matrix(self, size=23):\n        self.descriptor = fgenerate_unsorted_coulomb_matrix(self.nuclear_charges, \\\n                self.coordinates, self.natoms, size)\n\n    def generate_local_coulomb_matrix(self, calc=\"all\",size=23):\n        self.local_descriptor = fgenerate_local_coulomb_matrix( \\\n                self.nuclear_charges, self.coordinates, self.natoms, size)\n\n    def generate_atomic_coulomb_matrix(self, size = 23, cutoff = 8.0):\n        self.local_descriptor = fgenerate_atomic_coulomb_matrix( \\\n                self.nuclear_charges, self.coordinates, self.natoms, size, cutoff)\n\n    def generate_atomic_unsorted_coulomb_matrix(self, size = 23, cutoff = 8.0):\n        self.local_descriptor = fgenerate_atomic_unsorted_coulomb_matrix( \\\n                self.nuclear_charges, self.coordinates, self.natoms, size, cutoff)\n\n    def generate_arad_descriptor(self, size=23):\n        arad_object = ARAD(maxMolSize=size,maxAts=size)\n        self.arad_descriptor = arad_object.describe(np.array(self.coordinates), \\\n                np.array(self.nuclear_charges))\n\n        assert (self.arad_descriptor).shape[0] == size, \"ERROR: Check ARAD descriptor size!\"\n        assert (self.arad_descriptor).shape[2] == size, \"ERROR: Check ARAD descriptor size!\"\n\n    def generate_arad_descriptor_periodic(self, size=23, unit_cell=None):\n\n        if unit_cell is None:\n            unit_cell = self.unit_cell\n\n        arad_object = ARAD(maxMolSize=size,maxAts=size)\n        self.arad_descriptor = arad_object.describe(np.array(self.coordinates), \\\n                np.array(self.nuclear_charges), cell=unit_cell)\n\n        assert (self.arad_descriptor).shape[0] == size, \"ERROR: Check ARAD descriptor size!\"\n        assert (self.arad_descriptor).shape[2] == size, \"ERROR: Check ARAD descriptor size!\"\n\n    def generate_aras_descriptor(self, size=23):\n        aras_object = ARAS(maxMolSize=size,maxAts=size)\n        self.aras_descriptor = aras_object.describe(np.array(self.coordinates), \\\n                np.array(self.nuclear_charges))\n\n        assert (self.aras_descriptor).shape[0] == size, \"ERROR: Check ARAS descriptor size!\"\n        assert (self.aras_descriptor).shape[2] == size, \"ERROR: Check ARAS descriptor size!\"\n\n    def read_xyz(self, filename):\n\n        f = open(filename, \"r\")\n        lines = f.readlines()\n        f.close()\n\n        self.natoms = int(lines[0])\n\n        for line in lines[2:]:\n            tokens = line.split()\n\n            if len(tokens) < 4:\n                break\n\n            self.atomtypes.append(tokens[0])\n            self.nuclear_charges.append(NUCLEAR_CHARGE[tokens[0]])\n\n            x = float(tokens[1])\n            y = float(tokens[2])\n            z = float(tokens[3])\n\n            self.coordinates.append(np.array([x, y, z]))\n\n        self.coordinates = np.array(self.coordinates)\n\ndef get_lines(filename):\n\n    f = open(filename, \"r\")\n    lines = f.readlines()\n    f.close()\n\n    return lines\n\ndef parse_molecules(filename):\n\n    lines = get_lines(filename)\n\n    mols = []\n\n    mol = Molecule()\n\n    for line in lines:\n\n        tokens = line.split()\n\n        if len(tokens) == 1:\n\n            if mol.natoms > 0:\n                mols.append(mol)\n\n            mol = Molecule()\n            mol.natoms = int(tokens[0])\n\n        if len(tokens) == 2:\n            mol.molid = int(tokens[0])\n            mol.energy = float(tokens[1])\n            mol.dftb3_energy = parse_dft3_energy(mol.molid)\n\n\n        if len(tokens) == 7:\n\n            atom_type = tokens[0]\n            mol.atomtypes.append(atom_type)\n            mol.nuclear_charges.append(NUCLEAR_CHARGE[atom_type])\n            x = float(tokens[4])\n            y = float(tokens[5])\n            z = float(tokens[6])\n\n            mol.coordinates.append(np.array([x, y, z]))\n\n            mol.dftb3_hof = 0.0\n            mol.dftb3_hof += mol.dftb3_energy\n\n            for atom in [\"H\", \"C\", \"N\", \"O\", \"S\"]:\n\n                n = mol.atomtypes.count(atom)\n                mol.dftb3_hof -= n * HOF_DFTB3[atom]\n\n    mol.atomtypes = np.asarray(mol.atomtypes)\n    mol.coordinates = np.asarray(mol.coordinates)\n    mol.nuclear_charges = np.asarray(mol.nuclear_charges)\n\n    return mols\n\ndef parse_dft3_energy(molid):\n\n    filename = \"../logfiles/\" + str(molid) + \".log\"\n    f = open(filename, \"r\")\n    lines = f.readlines()\n    f.close()\n\n    energy = float(\"nan\")\n    for line in lines:\n        if \"Total Energy\" in line:\n            tokens = line.split()\n            energy = float(tokens[2]) * 627.51\n\n    return energy\n\ndef vector_to_matrix(v):\n    if not (np.sqrt(8*v.shape[0]+1) == int(np.sqrt(8*v.shape[0]+1))):\n        print \"ERROR: Can not make a square matrix.\"\n        exit(1)\n\n    n = v.shape[0]\n    l = (-1 + int(np.sqrt(8*n+1)))/2\n    M = np.empty((l,l))\n\n    index = 0\n    for i in range(l):\n        for j in range(l):\n            if j > i:\n                continue\n\n            M[i,j] = v[index]\n            M[j,i] = M[i,j]\n\n            index += 1\n    return M\n", "meta": {"hexsha": "48354efc09edb4e6a49876d6320e0a1381b58a23", "size": 9919, "ext": "py", "lang": "Python", "max_stars_repo_path": "fml/fml.py", "max_stars_repo_name": "larsbratholm/ml_clustering", "max_stars_repo_head_hexsha": "dec3386676f8b22054f18643b1ae7d3e44c65527", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fml/fml.py", "max_issues_repo_name": "larsbratholm/ml_clustering", "max_issues_repo_head_hexsha": "dec3386676f8b22054f18643b1ae7d3e44c65527", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fml/fml.py", "max_forks_repo_name": "larsbratholm/ml_clustering", "max_forks_repo_head_hexsha": "dec3386676f8b22054f18643b1ae7d3e44c65527", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2034482759, "max_line_length": 106, "alphanum_fraction": 0.6256679101, "include": true, "reason": "import numpy", "num_tokens": 2443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.19844909975660466}}
{"text": "\"\"\"Bader calculation methods.\n\nThis module is has __contains__ due to @njit hiding the names of the functions.\nAll functions in this module should have the same arguments as to help be called\nby bader_calc in the thread_handlers module.\n\"\"\"\nimport numpy as np\nfrom numba import njit\n\nfrom .utils import array_assign, volume_extend\n\n__contains__ = ['ongrid', 'neargrid']\n\n\n@njit(cache=True, nogil=True)\ndef ongrid(density, volumes, idx, dist_mat, T_grad, i_c):\n    \"\"\"Parallel implementation of the ongrid Bader maximum searching.\n\n    The ongrid method for Bader maximum searching based on W. Tang, E. Sanville,\n    and G. Henkelman A grid-based Bader analysis algorithm without lattice bias,\n    J. Phys.: Condens. Matter 21, 084204 (2009). Can be passed a volumes array\n    of smaller size than density to reduce the active area for parallelisation\n    purposes.\n\n    args:\n        density: read-only array of reference charge density\n        volumes: array same shape as density to store bader volume indicators\n        idx: the offset of the origin for the chunk (threading)\n        dist_mat: rank-3 tensor of distances for moving in index direction\n        T_grad: unused, kept for argument matching with neargrid method\n        i_c: index counter for tqdm bar.\n    returns:\n        volumes: the updated volumes array\n        bader_max: array containing location of Bader maxima\n        edge_max: array containing location of edge crossings\n    \"\"\"\n    # get shapes\n    vol_shape = np.zeros(3, dtype=np.int64)\n    vx, vy, vz = volumes.shape\n    # thread stuff\n    extend = np.zeros(3, dtype=np.int64)\n    positive_len = np.zeros(3, dtype=np.int64)\n    new_positive_len = np.zeros(3, dtype=np.int64)\n    negative_len = np.zeros(3, dtype=np.int64)\n    new_negative_len = np.zeros(3, dtype=np.int64)\n    for j in range(3):\n        vol_shape[j] = volumes.shape[j]\n        extend[j] = volumes.shape[j]\n        positive_len[j] = volumes.shape[j]\n        new_positive_len[j] = volumes.shape[j]\n    # init array length counters\n    bader_num = 0\n    edge_num = 0\n    path_num = 0\n    # init arrays for bader maxima, edge crossings and current path\n    # idx is type set for the maximum int that can be stored here\n    bader_max = np.zeros((vx, 3), dtype=np.int64)\n    edge_max = np.zeros((vx, 3), dtype=np.int64)\n    path = np.zeros((vx, 3), dtype=np.int64)\n    # init position arrays\n    p = np.zeros(3, dtype=np.int64)\n    pt = np.zeros(3, dtype=np.int64)\n    pd = np.zeros(3, dtype=np.int64)\n    pv = np.zeros(3, dtype=np.int64)\n    # keep track of the lead index for filling the progress bar\n    lead_idx = 0\n    # for index in range of the volume size\n    for i in np.ndindex(vx, vy, vz):\n        if i[0] != lead_idx:\n            lead_idx += 1\n            i_c[0] += 1\n        # skip if volume has been visited\n        if volumes[i] != 0:\n            continue\n        # init p for current point, pv for next point in volume space\n        # pd for next point in density space\n        for j in range(3):\n            p[j] = i[j] + idx[j]\n            pv[j] = i[j]\n            pd[j] = p[j]\n            path[0][j] = pv[j]\n        # path size is now 1 and max_val is current point\n        path_num = 1\n        max_val = density[p[0], p[1], p[2]]\n        ctr_val = max_val\n        while True:\n            for ix in range(-1, 2):\n                # shift p_x into density space and adjust for pbc\n                pt[0] = p[0] + ix\n                if pt[0] < 0:\n                    pt[0] += density.shape[0]\n                elif pt[0] >= density.shape[0]:\n                    pt[0] -= density.shape[0]\n                for iy in range(-1, 2):\n                    # shift p_y into density space and adjust for pbc\n                    pt[1] = p[1] + iy\n                    if pt[1] < 0:\n                        pt[1] += density.shape[1]\n                    elif pt[1] >= density.shape[1]:\n                        pt[1] -= density.shape[1]\n                    for iz in range(-1, 2):\n                        # shift p_z into density space and adjust for pbc\n                        pt[2] = p[2] + iz\n                        if pt[2] < 0:\n                            pt[2] += density.shape[2]\n                        elif pt[2] >= density.shape[2]:\n                            pt[2] -= density.shape[2]\n                        # check for new maxima, save density and index\n                        pd_tmp = density[pt[0], pt[1], pt[2]]\n                        pd_val = (pd_tmp - ctr_val) * dist_mat[ix, iy, iz]\n                        pd_val += ctr_val\n                        if pd_val > max_val:\n                            max_val = pd_val\n                            new_density = pd_tmp\n                            for j in range(3):\n                                pd[j] = pt[j]\n                                pv[j] = pd[j] - idx[j]\n            # check if new pv is same as p or outside of volume space\n            break_flag = True\n            extend_flag = False\n            for j in range(3):\n                # outside volume to left\n                if pv[j] < negative_len[j]:\n                    upper = pv[j] + density.shape[j] - positive_len[j] + 1\n                    lower = (pv[j] - negative_len[j]) * -1\n                    if upper <= 0:\n                        pv[j] += density.shape[j]\n                    elif upper > lower:\n                        new_negative_len[j] -= vol_shape[j] // 2\n                        extend[j] += vol_shape[j] // 2\n                        extend_flag = True\n                    else:\n                        new_positive_len[j] += vol_shape[j] // 2\n                        extend[j] += vol_shape[j] // 2\n                        pv[j] += density.shape[j]\n                        extend_flag = True\n                elif pv[j] >= positive_len[j]:\n                    upper = pv[j] - positive_len[j] + 1\n                    lower = (pv[j] - density.shape[j] - negative_len[j]) * -1\n                    if lower <= 0:\n                        pv[j] -= density.shape[j]\n                    elif upper > lower:\n                        new_negative_len[j] -= vol_shape[j] // 2\n                        extend[j] += vol_shape[j] // 2\n                        pv[j] -= density.shape[j]\n                        extend_flag = True\n                    else:\n                        new_positive_len[j] += vol_shape[j] // 2\n                        extend[j] += vol_shape[j] // 2\n                        extend_flag = True\n                if break_flag and pd[j] != p[j]:\n                    break_flag = False\n            if extend_flag:\n                for j in range(3):\n                    if extend[j] > density.shape[j]:\n                        extend[j] = density.shape[j]\n                volumes = volume_extend(volumes, positive_len, extend)\n                for j in range(3):\n                    if volumes.shape[j] == density.shape[j]:\n                        positive_len[j] = density.shape[j]\n                        negative_len[j] = 0\n                    else:\n                        positive_len[j] = new_positive_len[j]\n                        negative_len[j] = new_negative_len[j]\n            # if known break without updating p\n            if volumes[pv[0], pv[1], pv[2]] != 0:\n                vol_num = volumes[pv[0], pv[1], pv[2]]\n                break\n            elif break_flag:\n                # store maxima/edge in density space\n                vol_num = 0\n                for k in range(3):\n                    if pv[k] >= vol_shape[k]:\n                        vol_num = -2\n                    elif pv[k] < 0:\n                        vol_num = -2\n                break\n            # no break condition so add point to path\n            else:\n                if path_num >= path.shape[0]:\n                    path = array_assign(\n                        path, path.shape[0], path.shape[0] + vx)\n                for j in range(3):\n                    p[j] = pd[j]\n                    path[path_num][j] = pv[j]\n                path_num += 1\n                # set new density values for max and control\n                ctr_val = new_density\n                max_val = new_density\n        # if the volume is empty then create a new one\n        if vol_num == -2:\n            if edge_num >= edge_max.shape[0]:\n                edge_max = array_assign(edge_max, edge_max.shape[0],\n                                        edge_max.shape[0] + vx)\n            # add max to bader_max list add one to len counter\n            for j in range(3):\n                edge_max[edge_num][j] = pd[j]\n            edge_num += 1\n            vol_num = -2 - edge_num  # -1 is vacuum, -2 is maxima flag\n        # we are at a maxima\n        elif vol_num == 0:\n            if bader_num >= bader_max.shape[0]:\n                bader_max = array_assign(bader_max, bader_max.shape[0],\n                                         bader_max.shape[0] + vx)\n            # add max to bader_max list add one to len counter\n            for j in range(3):\n                bader_max[bader_num][j] = pd[j]\n            bader_num += 1\n            vol_num = bader_num\n        # assign bader_num to volumes\n        for j in range(path_num):\n            for k in range(3):\n                pv[k] = path[j][k]\n            volumes[pv[0], pv[1], pv[2]] = vol_num\n    # reduce size of bader_max and edge_max arrays to fit contents\n    bader_max = array_assign(bader_max, bader_num, bader_num)\n    edge_max = array_assign(edge_max, edge_num, edge_num)\n    i_c[0] += 1\n    return volumes, bader_max, edge_max\n\n\n@njit(cache=True, nogil=True)\ndef neargrid(density, volumes, idx, dist_mat, T_grad, i_c):\n    \"\"\"Parallel implementation of the neargrid Bader maximum searching.\n\n    The neargrid method for Bader maximum searching based on W. Tang,\n    E. Sanville, and G. Henkelman A grid-based Bader analysis algorithm without\n    lattice bias, J. Phys.: Condens. Matter 21, 084204 (2009). Can be passed a\n    volumes array of smaller size than density to reduce the active area for\n    parallelisation purposes.\n\n    args:\n        density: read-only array of reference charge density\n        volumes: array same shape as density to store bader volume indicators\n        idx: the offset of the origin for the chunk (threading)\n        dist_mat: rank-3 tensor of distances for moving in index direction\n        T_grad: transform matrix for converting gradient to direct basis\n        i_c: index counter for tqdm bar\n    returns:\n        volumes: the updated volumes array.\n        bader_max: array containing location of Bader maxima.\n        edge_max: array containing location of edge crossings.\n    \"\"\"\n    # get shapes\n    vol_shape = np.zeros(3, dtype=np.int64)\n    vx, vy, vz = volumes.shape\n    # thread stuff\n    extend = np.zeros(3, dtype=np.int64)\n    positive_len = np.zeros(3, dtype=np.int64)\n    new_positive_len = np.zeros(3, dtype=np.int64)\n    negative_len = np.zeros(3, dtype=np.int64)\n    new_negative_len = np.zeros(3, dtype=np.int64)\n    for j in range(3):\n        vol_shape[j] = volumes.shape[j]\n        extend[j] = volumes.shape[j]\n        positive_len[j] = volumes.shape[j]\n        new_positive_len[j] = volumes.shape[j]\n    # init array length counters\n    bader_num = 0\n    edge_num = 0\n    path_num = 0\n    # init arrays for bader maxima, edge crossings and current path\n    # idx is type set for the maximum int that can be stored here\n    bader_max = np.zeros((vx, 3), dtype=np.int64)\n    edge_max = np.zeros((vx, 3), dtype=np.int64)\n    path = np.zeros((vx, 3), dtype=np.int64)\n    # init position arrays\n    p = np.zeros(3, dtype=np.int64)\n    pd = np.zeros(3, dtype=np.int64)\n    pv = np.zeros(3, dtype=np.int64)\n    pt = np.zeros(3, dtype=np.int64)\n    dr = np.zeros(3, dtype=np.float64)\n    density_t = np.zeros(2, dtype=np.float64)\n    grad = np.zeros(3, dtype=np.float64)\n    grad_dir = np.zeros(3, dtype=np.float64)\n    max_grad = np.float64(0.)\n    known = np.zeros((vx, vy, vz), dtype=np.int8)\n    # keep track of the lead index for filling the progress bar\n    lead_idx = 0\n    # for index in range of the volume size\n    for i in np.ndindex(vx, vy, vz):\n        if i[0] != lead_idx:\n            lead_idx += 1\n            i_c[0] += 1\n        # skip if volume has been visited\n        if volumes[i] == -1:\n            continue\n        elif known[i] == 2:\n            continue\n        # we've visited the point\n        known[i] = 1\n        # init p for current point, pv for next point in volume space\n        # pd for next point in density space\n        for j in range(3):\n            p[j] = i[j] + idx[j]\n            pd[j] = p[j]\n            path[0][j] = i[j]\n            dr[j] = 0.\n        # path size is now 1 and max_val is current point\n        path_num = 1\n        while True:\n            max_val = density[p[0], p[1], p[2]]\n            # calculate density of heptacube around point\n            for j in range(3):\n                # convert to density space\n                pd[j] += 1\n                # wrap in pbc\n                if pd[j] < 0:\n                    pd[j] += density.shape[j]\n                elif pd[j] >= density.shape[j]:\n                    pd[j] -= density.shape[j]\n                # store density at p+1\n                density_t[0] = density[pd[0], pd[1], pd[2]]\n                pd[j] -= 2\n                # rewrap\n                if pd[j] < 0:\n                    pd[j] += density.shape[j]\n                elif pd[j] >= density.shape[j]:\n                    pd[j] -= density.shape[j]\n                # store density of p-1\n                density_t[1] = density[pd[0], pd[1], pd[2]]\n                # if p is max in this axis grad is zero\n                # else grad is density[p+1] - density[p-1] / 2\n                if density_t[0] <= max_val >= density_t[1]:\n                    grad[j] = 0.\n                else:\n                    grad[j] = (density_t[0] - density_t[1]) / 2.\n                # reset current pd\n                pd[j] = p[j]\n            # convert grad to direct coords\n            max_grad = 0.\n            for j in range(3):\n                grad_dir[j] = ((T_grad[j, 0] * grad[0])\n                               + (T_grad[j, 1] * grad[1])\n                               + (T_grad[j, 2] * grad[2]))\n                if grad_dir[j] > max_grad:\n                    max_grad = grad_dir[j]\n                elif -grad_dir[j] > max_grad:\n                    max_grad = -grad_dir[j]\n            # max grad is zero then do ongrid step\n            if max_grad < 1E-14:\n                for j in range(3):\n                    pv[j] = pd[j] - idx[j]\n            else:\n                for j in range(3):\n                    grad_dir[j] /= max_grad\n                    if grad_dir[j] > 0:\n                        int_grad = np.int64(grad_dir[j] + .5)\n                    else:\n                        int_grad = np.int64(grad_dir[j] - .5)\n                    pd[j] = p[j] + int_grad\n                    dr[j] += grad_dir[j] - int_grad\n                    if dr[j] > 0:\n                        int_dr = np.int64(dr[j] + .5)\n                    else:\n                        int_dr = np.int64(dr[j] - .5)\n                    pd[j] += int_dr\n                    dr[j] -= int_dr\n                    if pd[j] >= density.shape[j]:\n                        pd[j] -= density.shape[j]\n                    elif pd[j] < 0:\n                        pd[j] += density.shape[j]\n                    pv[j] = pd[j] - idx[j]\n            # check if pv is outside of volume space and either extend volume\n            # space or wrap back in\n            extend_flag = False\n            for j in range(3):\n                # outside volume to left\n                if pv[j] < negative_len[j]:\n                    upper = pv[j] + density.shape[j] - positive_len[j] + 1\n                    lower = (pv[j] - negative_len[j]) * -1\n                    if upper <= 0:\n                        pv[j] += density.shape[j]\n                    elif upper > lower:\n                        new_negative_len[j] -= vol_shape[j] // 2\n                        extend[j] += vol_shape[j] // 2\n                        extend_flag = True\n                    else:\n                        new_positive_len[j] += vol_shape[j] // 2\n                        extend[j] += vol_shape[j] // 2\n                        pv[j] += density.shape[j]\n                        extend_flag = True\n                elif pv[j] >= positive_len[j]:\n                    upper = pv[j] - positive_len[j] + 1\n                    lower = (pv[j] - density.shape[j] - negative_len[j]) * -1\n                    if lower <= 0:\n                        pv[j] -= density.shape[j]\n                    elif upper > lower:\n                        new_negative_len[j] -= vol_shape[j] // 2\n                        extend[j] += vol_shape[j] // 2\n                        pv[j] -= density.shape[j]\n                        extend_flag = True\n                    else:\n                        new_positive_len[j] += vol_shape[j] // 2\n                        extend[j] += vol_shape[j] // 2\n                        extend_flag = True\n            if extend_flag:\n                for j in range(3):\n                    if extend[j] > density.shape[j]:\n                        extend[j] = density.shape[j]\n                volumes = volume_extend(volumes, positive_len, extend)\n                known = volume_extend(known, positive_len, extend)\n                for j in range(3):\n                    if volumes.shape[j] == density.shape[j]:\n                        positive_len[j] = density.shape[j]\n                        negative_len[j] = 0\n                    else:\n                        positive_len[j] = new_positive_len[j]\n                        negative_len[j] = new_negative_len[j]\n            # already been here this path\n            if known[pv[0], pv[1], pv[2]] == 1:\n                for j in range(3):\n                    dr[j] = 0.\n                    pd[j] = p[j]\n                    pv[j] = p[j] - idx[j]\n                max_val = density[p[0], p[1], p[2]]\n                ctr_val = max_val\n                for ix in range(-1, 2):\n                    # shift p_x into density space and adjust for pbc\n                    pt[0] = p[0] + ix\n                    if pt[0] < 0:\n                        pt[0] += density.shape[0]\n                    elif pt[0] >= density.shape[0]:\n                        pt[0] -= density.shape[0]\n                    for iy in range(-1, 2):\n                        # shift p_y into density space and adjust for pbc\n                        pt[1] = p[1] + iy\n                        if pt[1] < 0:\n                            pt[1] += density.shape[1]\n                        elif pt[1] >= density.shape[1]:\n                            pt[1] -= density.shape[1]\n                        for iz in range(-1, 2):\n                            # shift p_z into density space and adjust for pbc\n                            pt[2] = p[2] + iz\n                            if pt[2] < 0:\n                                pt[2] += density.shape[2]\n                            elif pt[2] >= density.shape[2]:\n                                pt[2] -= density.shape[2]\n                            # check for new maxima, save density and index\n                            pd_val = density[pt[0], pt[1], pt[2]]\n                            pd_val = (pd_val - ctr_val) * dist_mat[ix, iy, iz]\n                            pd_val += ctr_val\n                            if pd_val > max_val:\n                                max_val = pd_val\n                                for j in range(3):\n                                    pd[j] = pt[j]\n                                    pv[j] = pd[j] - idx[j]\n                extend_flag = False\n                break_flag = True\n                for j in range(3):\n                    # outside volume to left\n                    if pv[j] < negative_len[j]:\n                        upper = pv[j] + density.shape[j] - positive_len[j] + 1\n                        lower = (pv[j] - negative_len[j]) * -1\n                        if upper <= 0:\n                            pv[j] += density.shape[j]\n                        elif upper > lower:\n                            new_negative_len[j] -= vol_shape[j] // 2\n                            extend[j] += vol_shape[j] // 2\n                            extend_flag = True\n                        else:\n                            new_positive_len[j] += vol_shape[j] // 2\n                            extend[j] += vol_shape[j] // 2\n                            pv[j] += density.shape[j]\n                            extend_flag = True\n                    elif pv[j] >= positive_len[j]:\n                        upper = pv[j] - positive_len[j] + 1\n                        lower = (pv[j] - density.shape[j] - negative_len[j])\n                        lower *= -1\n                        if lower <= 0:\n                            pv[j] -= density.shape[j]\n                        elif upper > lower:\n                            new_negative_len[j] -= vol_shape[j] // 2\n                            extend[j] += vol_shape[j] // 2\n                            pv[j] -= density.shape[j]\n                            extend_flag = True\n                        else:\n                            new_positive_len[j] += vol_shape[j] // 2\n                            extend[j] += vol_shape[j] // 2\n                            extend_flag = True\n                    if break_flag and pd[j] != p[j]:\n                        break_flag = False\n                if extend_flag:\n                    for j in range(3):\n                        if extend[j] > density.shape[j]:\n                            extend[j] = density.shape[j]\n                    volumes = volume_extend(volumes, positive_len, extend)\n                    known = volume_extend(known, positive_len, extend)\n                    for j in range(3):\n                        if volumes.shape[j] == density.shape[j]:\n                            positive_len[j] = density.shape[j]\n                            negative_len[j] = 0\n                        else:\n                            positive_len[j] = new_positive_len[j]\n                            negative_len[j] = new_negative_len[j]\n                if break_flag:\n                    # store maxima/edge in density space\n                    vol_num = 0\n                    if volumes[pv[0], pv[1], pv[2]] != 0:\n                        vol_num = volumes[pv[0], pv[1], pv[2]]\n                    else:\n                        for k in range(3):\n                            if pv[k] >= vol_shape[k]:\n                                vol_num = -2\n                            elif pv[k] < 0:\n                                vol_num = -2\n                    break\n            # if known break without updating p\n            if known[pv[0], pv[1], pv[2]] == 2:\n                vol_num = volumes[pv[0], pv[1], pv[2]]\n                break\n            # no break condition so add point to path\n            else:\n                if path_num >= path.shape[0]:\n                    path = array_assign(\n                        path, path.shape[0], path.shape[0] + vx)\n                for j in range(3):\n                    p[j] = pd[j]\n                    path[path_num][j] = pv[j]\n                path_num += 1\n                known[pv[0], pv[1], pv[2]] = 1\n        # if the volume is empty then create a new one\n        if vol_num == -2:\n            if edge_num >= edge_max.shape[0]:\n                edge_max = array_assign(edge_max, edge_max.shape[0],\n                                        edge_max.shape[0] + vx)\n            # add max to bader_max list add one to len counter\n            for j in range(3):\n                edge_max[edge_num][j] = pd[j]\n            edge_num += 1\n            vol_num = -2 - edge_num  # -1 is vacuum, -2 is maxima flag\n        # we are at a maxima\n        elif vol_num == 0:\n            if bader_num >= bader_max.shape[0]:\n                bader_max = array_assign(bader_max, bader_max.shape[0],\n                                         bader_max.shape[0] + vx)\n            # add max to bader_max list add one to len counter\n            for j in range(3):\n                bader_max[bader_num][j] = pd[j]\n            bader_num += 1\n            vol_num = bader_num\n        # assign bader_num to volumes and adjust known\n        for j in range(path_num):\n            for k in range(3):\n                p[k] = path[j][k]\n                pv[k] = p[k]\n                pt[k] = p[k]\n            volumes[p[0], p[1], p[2]] = vol_num\n            # this should never == 2 ?\n            if known[p[0], p[1], p[2]] != 2:\n                known[p[0], p[1], p[2]] = 0\n            for k in range(3):\n                pv[k] += 1\n                pt[k] += 1\n                # pv[k] check is in bounds, if not we havent been there so skip\n                if negative_len[k] <= pv[k] < positive_len[k]:\n                    known_flag = True\n                    vol_temp = volumes[pv[0], pv[1], pv[2]]\n                    if not (-2 < vol_temp < 1):\n                        for h in range(3):\n                            pt[h] += 1\n                            if not (negative_len[h] <= pt[h] < positive_len[h]):\n                                known_flag = False\n                                break\n                            elif vol_temp != volumes[pt[0], pt[1], pt[2]]:\n                                known_flag = False\n                                break\n                            pt[h] -= 2\n                            if not (negative_len[h] <= pt[h] < positive_len[h]):\n                                known_flag = False\n                                break\n                            elif vol_temp != volumes[pt[0], pt[1], pt[2]]:\n                                known_flag = False\n                                break\n                            pt[h] += 1\n                        if known_flag:\n                            known[pv[0], pv[1], pv[2]] = 2\n                pv[k] -= 2\n                for h in range(3):\n                    pt[h] = pv[h]\n                if negative_len[k] <= pv[k] < positive_len[k]:\n                    # pv[k] check in bounds, if not we havent been there so skip\n                    known_flag = True\n                    vol_temp = volumes[pv[0], pv[1], pv[2]]\n                    if not (-2 < vol_temp < 1):\n                        for h in range(3):\n                            pt[h] += 1\n                            if not (negative_len[h] <= pt[h] < positive_len[h]):\n                                known_flag = False\n                                break\n                            elif vol_temp != volumes[pt[0], pt[1], pt[2]]:\n                                known_flag = False\n                                break\n                            pt[h] -= 2\n                            if not (negative_len[h] <= pt[h] < positive_len[h]):\n                                known_flag = False\n                                break\n                            elif vol_temp != volumes[pt[0], pt[1], pt[2]]:\n                                known_flag = False\n                                break\n                            pt[h] += 1\n                        if known_flag:\n                            known[pv[0], pv[1], pv[2]] = 2\n                pv[k] += 1\n                for h in range(3):\n                    pt[h] = pv[h]\n    # reduce size of bader_max and edge_max arrays to fit contents\n    bader_max = array_assign(bader_max, bader_num, bader_num)\n    edge_max = array_assign(edge_max, edge_num, edge_num)\n    i_c[0] += 1\n    return volumes, bader_max, edge_max\n", "meta": {"hexsha": "5af74e1b4af36ab088c2df907efc0cc4d53122da", "size": 27471, "ext": "py", "lang": "Python", "max_stars_repo_path": "pybader/methods.py", "max_stars_repo_name": "adam-kerrigan/pybader", "max_stars_repo_head_hexsha": "1d675ae69ab64fe336b936b00990681e01258031", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-30T20:15:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-20T18:24:23.000Z", "max_issues_repo_path": "pybader/methods.py", "max_issues_repo_name": "kerrigoon/pybader", "max_issues_repo_head_hexsha": "1d675ae69ab64fe336b936b00990681e01258031", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pybader/methods.py", "max_forks_repo_name": "kerrigoon/pybader", "max_forks_repo_head_hexsha": "1d675ae69ab64fe336b936b00990681e01258031", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-18T13:39:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-18T13:39:53.000Z", "avg_line_length": 44.887254902, "max_line_length": 80, "alphanum_fraction": 0.4403552838, "include": true, "reason": "import numpy,from numba", "num_tokens": 6374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.33458945452352534, "lm_q1q2_score": 0.19829999439294463}}
{"text": "import numpy as np\nimport ctypes\nfrom ctypes import POINTER, pointer, c_int, c_long, c_char, c_char_p, c_double\n\nimport larch\nfrom larch.larchlib import get_dll\nfrom larch.xray import  atomic_mass\n\nF8LIB = None\n\nFEFF_maxpts = 150  # nex\nFEFF_maxpot = 11   # nphx\nFEFF_maxleg = 9    # legtot\nBOHR = 0.52917721067\nRYDBERG = 13.605698\n\ndef with_phase_file(fcn):\n    \"\"\"decorator to ensure that the wrapped function either\n    has a non-None 'phase_file' argument or that that\n    self.phase_file is not None\n    \"\"\"\n    errmsg = \"function '%s' needs a non-None phase_file\"\n    def wrapper(*args, **keywords):\n        \"needs phase_file\"\n        phase_file = keywords.get('phase_file', None)\n        if phase_file is None:\n            phase_file = getattr(args[0], 'phase_file', None)\n            if phase_file is None:\n                raise AttributeError(errmsg % fcn.__name__)\n        else:\n            setattr(args[0], 'phase_file', phase_file)\n        # raise Warning(errmsg % fcn.__name__)\n        return fcn(*args, **keywords)\n    wrapper.__doc__ = fcn.__doc__\n    wrapper.__name__ = fcn.__name__\n    wrapper.__filename__ = fcn.__code__.co_filename\n    wrapper.__dict__.update(fcn.__dict__)\n    return wrapper\n\nclass Feff8L_XAFSPath(object):\n    \"\"\"Feff8 Scattering Path calculation\n\n    A calculation requires a Potentials and Phase Shift calculation\n    in PAD format from Feff8L, and a list of scattering paths\n\n    Usage:\n    ------\n       # create path\n       path  = Feff8L_XAFSPath(phase_file='phase.pad')\n\n       # list 'ipot' and labels for absorber, scatterers\n       path.list_scatterers()\n\n       # set coords for absorbing atom\n       path.set_absorber(x=0., y=0., z=0.)\n\n       # add scattering atom\n       path.add_scatterer(x=1.5, y=1.5, z=1.5, ipot=1)\n\n       # calculate basic (unaltered) XAFS contributions\n       path.calcuate_xafs()\n\n    \"\"\"\n    def __init__(self, phase_file=None, title=''):\n        global F8LIB\n        if F8LIB is None:\n            try:\n                F8LIB = get_dll('feff8lpath')\n            except:\n                pass\n        self.reset(phase_file=phase_file, title=title)\n\n    def reset(self, phase_file=None, title=''):\n        \"\"\"reset all path data\"\"\"\n        self.phase_file = None\n        if phase_file is not None:\n            self.phase_file = phase_file\n        self.index   = 9999\n        self.degen   = 1.\n        self.nnnn_out = False\n        self.json_out = False\n        self.verbose  = False\n        self.ipol   = 0\n        self.ellip  = 0.\n        self.nepts  = 0\n        self.genfmt_order = 2\n        self.version= \"\"\n        self.exch   = \"\"\n        self.title  = title\n        self.filename  = \"%s_%s\" % (self.phase_file, self.title)\n        self.rs_int = 0.\n        self.vint   = 0.\n        self.mu     = 0.\n        self.edge   = 0.\n        self.kf     = 0.\n        self.rnorman = 0.\n        self.gam_ch = 0.\n        self.nepts  = FEFF_maxpts\n\n        dargs = dict(dtype=np.float64, order='F')\n        largs = dict(dtype=np.int32, order='F')\n\n        self.evec   = np.zeros(3, **dargs)\n        self.xivec  = np.zeros(3, **dargs)\n        self.ipot   = np.zeros(1+FEFF_maxleg, **largs)\n        self.beta   = np.zeros(1+FEFF_maxleg, **dargs)\n        self.eta    = np.zeros(2+FEFF_maxleg, **dargs)\n        self.ri     = np.zeros(FEFF_maxleg, **dargs)\n        self.rat    = np.zeros((3, 2+FEFF_maxleg), **dargs)\n        self.iz     = np.zeros(1+FEFF_maxpot, **largs)\n        self.k      = np.zeros(FEFF_maxpts, **dargs)\n        self.real_phc = np.zeros(FEFF_maxpts, **dargs)\n        self.mag_feff = np.zeros(FEFF_maxpts, **dargs)\n        self.pha_feff = np.zeros(FEFF_maxpts, **dargs)\n        self.red_fact = np.zeros(FEFF_maxpts, **dargs)\n        self.lam      = np.zeros(FEFF_maxpts, **dargs)\n        self.rep      = np.zeros(FEFF_maxpts, **dargs)\n        self.nleg = 1\n        self.atoms = []\n\n        if self.phase_file is not None:\n            self.read_atoms()\n            self.set_absorber()\n\n    @with_phase_file\n    def read_atoms(self):\n        \"\"\"read atoms ipot, iz, symbol\"\"\"\n        self.atoms = []\n        with open(self.phase_file,'r') as fh:\n            line1_words = fh.readline().strip().split()\n            text = fh.readlines()\n        npots = int(line1_words[4])\n        for line in text[4:]:\n            if not line.startswith('$'):\n                words = line.split()\n                self.atoms.append((int(words[1]), words[2]))\n            if len(self.atoms) > npots:\n                break\n\n    @with_phase_file\n    def list_atoms(self):\n        \"\"\"list Feff Potentials atoms ('ipots') fo phase file\"\"\"\n        if len(self.atoms) < 1:\n            self.read_atoms()\n        out = [\"# Potential   Z   Symbol\"]\n        for ipot, atom in enumerate(self.atoms):\n            out.append(\"    %2i      %3i     %s\" % (ipot, atom[0], atom[1]))\n        return \"\\n\".join(out)\n\n    @with_phase_file\n    def set_absorber(self, x=0., y=0., z=0., phase_file=None):\n        \"\"\"set coordinates for absorbing atom ('ipot'=0)\"\"\"\n        self.rat[0, 0] = x\n        self.rat[1, 0] = y\n        self.rat[2, 0] = z\n        self.rat[0, self.nleg] = self.rat[0, 0]\n        self.rat[1, self.nleg] = self.rat[1, 0]\n        self.rat[2, self.nleg] = self.rat[2, 0]\n        self.ipot[self.nleg]   = self.ipot[0]\n\n    @with_phase_file\n    def add_scatterer(self, x=0., y=0., z=0., ipot=1, phase_file=None):\n        self.rat[0, self.nleg] = x\n        self.rat[1, self.nleg] = y\n        self.rat[2, self.nleg] = z\n        self.ipot[self.nleg] = ipot\n        self.nleg += 1\n        # set final atom coords to same as absorber\n        self.rat[0, self.nleg] = self.rat[0, 0]\n        self.rat[1, self.nleg] = self.rat[1, 0]\n        self.rat[2, self.nleg] = self.rat[2, 0]\n        self.ipot[self.nleg]   = self.ipot[0]\n\n    @with_phase_file\n    def calculate_xafs(self, phase_file=None):\n        if F8LIB is None:\n            raise ValueError(\"Feff8 Dynamic library not found\")\n\n        if len(self.atoms) < 1:\n            self.read_atoms()\n\n        class args:\n            pass\n\n        # strings / char*.  Note fixed length to match Fortran\n        args.phase_file     = (self.phase_file + ' '*256)[:256]\n        args.exch_label     = ' '*8\n        args.genfmt_version = ' '*30\n\n        # integers, including booleans\n        for attr in ('index', 'nleg', 'genfmt_order', 'ipol', 'nnnn_out',\n                     'json_out', 'verbose', 'nepts'):\n            setattr(args, attr, pointer(c_long(int(getattr(self, attr)))))\n\n        # doubles\n        for attr in ('degen', 'rs_int', 'vint', 'mu', 'edge', 'kf', 'rnorman',\n                     'gam_ch', 'ellip'):\n            setattr(args, attr, pointer(c_double(getattr(self, attr))))\n\n        # integer arrays\n        args.ipot = self.ipot.ctypes.data_as(POINTER(self.ipot.size*c_int))\n        args.iz = self.iz.ctypes.data_as(POINTER(self.iz.size*c_int))\n\n        # double arrays\n        # print(\" Rat 0  \", self.rat)\n        for attr in ('evec', 'xivec', 'ri', 'beta', 'eta',\n                     'k', 'real_phc', 'mag_feff', 'pha_feff',\n                     'red_fact', 'lam', 'rep'):\n            arr = getattr(self, attr)\n            cdata = arr.ctypes.data_as(POINTER(arr.size*c_double))\n            setattr(args, attr, cdata)\n        # handle rat (in atomic units)\n        rat_atomic = self.rat/BOHR\n        args.rat = (rat_atomic).ctypes.data_as(POINTER(rat_atomic.size*c_double))\n\n        onepath = F8LIB.onepath_\n        # print(\" Calc with onepath \", onepath, rat_atomic)\n        # print(\" args rat = \", args.rat.contents[:])\n        x = onepath(args.phase_file, args.index, args.nleg, args.degen,\n                    args.genfmt_order, args.exch_label, args.rs_int, args.vint,\n                    args.mu, args.edge, args.kf, args.rnorman,\n                    args.gam_ch, args.genfmt_version, args.ipot, args.rat,\n                    args.iz, args.ipol, args.evec, args.ellip, args.xivec,\n                    args.nnnn_out, args.json_out, args.verbose, args.ri,\n                    args.beta, args.eta, args.nepts, args.k,\n                    args.real_phc, args.mag_feff, args.pha_feff,\n                    args.red_fact, args.lam, args.rep)\n\n        self.exch   = args.exch_label.strip()\n        self.version = args.genfmt_version.strip()\n        # print(\" Calc with onepath done\")\n        # unpack integers/floats\n        for attr in ('index', 'nleg', 'genfmt_order', 'degen', 'rs_int',\n                     'vint', 'mu', 'edge', 'kf', 'rnorman', 'gam_ch',\n                     'ipol', 'ellip', 'nnnn_out', 'json_out', 'verbose',\n                     'nepts'):\n            setattr(self, attr, getattr(args, attr).contents.value)\n\n        # some data needs recasting, reformatting\n        self.mu *= (2*RYDBERG)\n        self.nnnn_out = bool(self.nnnn_out)\n        self.json_out = bool(self.json_out)\n        self.verbose  = bool(self.verbose)\n\n        # unpck energies\n        for attr in ('evec', 'xivec'):\n            cdata = getattr(args, attr).contents[:]\n            setattr(self, attr, np.array(cdata))\n\n        nleg = self.nleg\n        nepts = self.nepts\n\n        # arrays of length 'nepts'\n        for attr in ('k', 'real_phc', 'mag_feff', 'pha_feff',\n                     'red_fact', 'lam', 'rep'):\n            cdata = getattr(args, attr).contents[:nepts]\n            setattr(self, attr, np.array(cdata))\n        self.pha = self.real_phc + self.pha_feff\n        self.amp = self.red_fact * self.mag_feff\n\n        # unpack arrays of length 'nleg':\n        for attr in ('ipot', 'beta', 'eta', 'ri'):\n            cdata = getattr(args, attr).contents[:]\n            setattr(self, attr, np.array(cdata))\n\n        # rat is sort of special, and calculate reff too:\n        rat = args.rat.contents[:]\n        rat = np.array(rat).reshape(2+FEFF_maxleg, 3).transpose()\n        self.rat = BOHR*rat\n\n        _rat = self.rat.T\n        reff = 0.\n        for i, atom in enumerate(_rat[1:]):\n            prev = _rat[i,:]\n            reff += np.sqrt( (prev[0]-atom[0])**2 +\n                             (prev[1]-atom[1])**2 +\n                             (prev[2]-atom[2])**2 )\n        self.reff = reff /2.0\n\n        self.geom = []\n        rmass  = 0.\n        for i in range(nleg):\n            ipot = int(self.ipot[i])\n            iz, sym = self.atoms[ipot]\n            mass = atomic_mass(iz)\n\n            x, y, z = _rat[i][0], _rat[i][1], _rat[i][2]\n            self.geom.append((str(sym), iz, ipot, x, y, z))\n            rmass += 1.0/max(1.0, mass)\n\n        self.rmass = 1./rmass\n\n\ndef feff8_xafs(phase_file):\n    return Feff8L_XAFSPath(phase_file=phase_file)\n\n\n\n## def initializeLarchPlugin(_larch=None):\n#     \"\"\"initialize F8LIB\"\"\"\n#     if _larch is not None:\n#         global F8LIB\n#         if F8LIB is None:\n#             try:\n#                 F8LIB = get_dll('feff8lpath')\n#             except:\n#                 pass\n##\n", "meta": {"hexsha": "8c9e428998d26e3be68aca1e748b5e96a61d9cdd", "size": 10838, "ext": "py", "lang": "Python", "max_stars_repo_path": "larch/xafs/feff8lpath.py", "max_stars_repo_name": "Bob620/xraylarch", "max_stars_repo_head_hexsha": "f8d38e6122cc0e8c990b0f024db3b503a5fbf057", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "larch/xafs/feff8lpath.py", "max_issues_repo_name": "Bob620/xraylarch", "max_issues_repo_head_hexsha": "f8d38e6122cc0e8c990b0f024db3b503a5fbf057", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "larch/xafs/feff8lpath.py", "max_forks_repo_name": "Bob620/xraylarch", "max_forks_repo_head_hexsha": "f8d38e6122cc0e8c990b0f024db3b503a5fbf057", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.074433657, "max_line_length": 81, "alphanum_fraction": 0.5482561358, "include": true, "reason": "import numpy", "num_tokens": 3093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.19829998652805772}}
{"text": "\"\"\"\nSet of functions used by the PyRSM class to compute detection maps and optimize the parameters\nof the RSM algorithm and PSF-subtraction techniques via the auto-RSM and auto-S/N frameworks\n\"\"\"\n__author__ = 'Carl-Henrik Dahlqvist'\n\nfrom scipy.interpolate import Rbf\nimport pandas as pd\nimport numpy.linalg as la\nfrom vip_hci.var import get_annulus_segments, frame_center,prepare_matrix\nfrom vip_hci.preproc.derotation import _define_annuli\nimport numpy as np\nfrom vip_hci.preproc import cube_derotate, cube_collapse, check_pa_vector,check_scal_vector\nfrom vip_hci.preproc.derotation import _find_indices_adi\nfrom vip_hci.preproc.rescaling import _find_indices_sdi\nimport scipy as sp\nfrom multiprocessing import cpu_count\nfrom vip_hci.conf.utils_conf import pool_map, iterable\nfrom vip_hci.pca.svd import get_eigenvectors\nfrom vip_hci.llsg.llsg import _patch_rlrps\nfrom vip_hci.preproc import cube_rescaling_wavelengths as scwave\nimport vip_hci as vip\nfrom sklearn.decomposition import NMF as NMF_sklearn\n \ndef check_delta_sep(scale_list,delta_sep,minradius,fwhm,c):\n    wl = np.asarray(scale_list)\n    wl_ref = wl[len(wl)//2]\n    sep_lft = (wl_ref - wl) / wl_ref * ((minradius + fwhm * delta_sep) / fwhm)\n    sep_rgt = (wl - wl_ref) / wl_ref * ((minradius - fwhm * delta_sep) / fwhm)\n    map_lft = sep_lft >= delta_sep\n    map_rgt = sep_rgt >= delta_sep\n    indices = np.nonzero(map_lft | map_rgt)[0]\n\n    if indices.size == 0:\n        raise RuntimeError((\"No frames left after radial motion threshold for cube {}. Try \"\n                           \"decreasing the value of `delta_sep`\").format(c))   \n                                        \ndef rot_scale(step,cube,cube_scaled,angle_list,scale_list, imlib, interpolation):\n    \n    \"\"\"\n    Function used to rescale the frames when relying on ADI+SDI before the computation the reference PSF\n    (step='ini') and rescale and derotate the frames to generate the cube of residuals used by the RSM \n    algorithm (step='fin').\n        \n        Parameters\n        ----------\n\n        step: str\n            'ini' before the reference PSF computation and 'fin' after PSF subtraction.\n        cube: numpy ndarray, 3d or 4d\n            Original cube\n        cube_scaled: numpy ndarray, 3d\n            Cube of residuals to be rescaled and derotated (None for the step='ini')\n        angle_list : numpy ndarray, 1d\n            Parallactic angles for each frame of the ADI sequences. \n        scale_list: numpy ndarray, 1d, optional\n            Scaling factors in case of IFS data (ADI+mSDI cube). Usually, the\n            scaling factors are the central channel wavelength divided by the\n            shortest wavelength in the cube (more thorough approaches can be used\n            to get the scaling factors). This scaling factors are used to re-scale\n            the spectral channels and align the speckles. Default is None\n        imlib : str, optional\n            See the documentation of the ``vip_hci.preproc.frame_rotate`` function.\n        interpolation : str, optional\n            See the documentation of the ``vip_hci.preproc.frame_rotate`` function.\n    \"\"\"\n    \n    if cube.ndim == 4:\n        \n        z, n, y_in, x_in = cube.shape\n        scale_list = check_scal_vector(scale_list)\n        \n        if step=='ini':\n        # rescaled cube, aligning speckles for SDI\n            for i in range(n):\n                if i==0:\n                    fin_cube = scwave(cube[:, i, :, :], scale_list,\n                                      imlib=imlib, interpolation=interpolation)[0]\n                    fin_pa=np.repeat(angle_list[i],z)\n                    fin_scale=scale_list\n                else: \n                    \n                    fin_cube = np.append(fin_cube,scwave(cube[:, i, :, :], scale_list,\n                                      imlib=imlib, interpolation=interpolation)[0],axis=0)\n                    fin_pa=np.append(fin_pa,np.repeat(angle_list[i],z),axis=0)\n                    fin_scale=np.append(fin_scale,scale_list,axis=0)\n                    \n            return fin_cube,fin_pa,fin_scale\n                \n\n        elif step=='fin':  \n            \n                cube_fin=np.zeros((n,y_in, x_in))\n                                \n                cube_rescaled = scwave(cube_scaled, scale_list, \n                                full_output=True, inverse=True,\n                                y_in=y_in, x_in=x_in, imlib=imlib,\n                                interpolation=interpolation)[0]\n                \n                cube_derotated=cube_derotate(cube_rescaled,angle_list, interpolation=interpolation,imlib=imlib)\n\n                 \n                for i in range(n):\n                    \n                    cube_fin[i]=np.mean(cube_derotated[(i*z):((i+1)*z),:,:],axis=0)\n                                    \n                return cube_fin\n                \n    if cube.ndim == 3:\n        \n        if step=='ini':\n     \n            return cube,angle_list,None\n        \n        elif step=='fin':    \n\n            cube_derotated=cube_derotate(cube_scaled,angle_list, interpolation=interpolation,imlib=imlib)\n            \n            return cube_derotated\n    \n    \ndef remove_outliers(time_s, range_sel, k=5, t0=3):\n    \"\"\"\n    Hampel Filter to remove potential outliers in the set of selected parameters \n    for the annular mode of the auto-RSM framework\n    \"\"\"\n    vals=pd.DataFrame(data=time_s[range_sel])\n    L= 1.4826\n    rolling_median=vals.rolling(k).median()\n    difference=np.abs(rolling_median-vals)\n    median_abs_deviation=difference.rolling(k).median()\n    threshold= t0 *L * median_abs_deviation\n    outlier_idx=difference>threshold\n    vals[outlier_idx]=threshold[outlier_idx]\n    return(vals.to_numpy().reshape(-1))\n       \ndef interpolation(time_s,range_sel): \n    \n    \"\"\"\n    Interpolation algorithm for the RSM parameters \n    for the annular mode of the auto-RSM framework\n    \"\"\"\n    \n    time_series=time_s.copy()\n    time_series[range_sel]=remove_outliers(time_series,range_sel)\n    fit = Rbf(range_sel,time_s[range_sel])\n    inter_point = np.linspace(range_sel[0],range_sel[-1]+1, num=(range_sel[-1]-range_sel[0]+1), endpoint=True)\n    return fit(inter_point)\n\ndef poly_fit(time_s,range_sel,poly_n):\n    \n    \"\"\"\n    Smoothing procedure for the computation of the final radial thresholds\n    which are subtracted from the final RSM detection map in the final step\n    of the auto-RSM framework\n    \"\"\"\n    \n    time_series=time_s.copy()\n    time_series[range_sel]=remove_outliers(time_series,range_sel)\n    fit_p=np.poly1d(np.polyfit(range_sel,time_series[range_sel], poly_n))\n    time_series=fit_p(range(len(time_series)))\n    return time_series\n\ndef get_time_series(mcube,ann_center):\n    \n        \"\"\"\n        Function defining and ordering (anti-clockwise) the pixels composing\n        an annulus at a radial distance of ann_center for an ADI sequence mcube\n        \"\"\"\n        if mcube.ndim == 4:\n            indices = get_annulus_segments(mcube[0,0,:,:], ann_center,1,4,90)\n        else:\n            indices = get_annulus_segments(mcube[0], ann_center,1,4,90)\n\n        tempind=np.vstack((indices[0][0],indices[0][1]))\n        ind = np.lexsort((tempind[0], tempind[1]))\n\n        indicesy=tempind[0,ind[::-1]]\n        indicesx=tempind[1,ind[::-1]] \n\n        tempind=np.vstack((indices[1][0],indices[1][1]))\n        ind = np.lexsort((-tempind[0], tempind[1]))\n\n        indicesy=np.hstack((indicesy,tempind[0,ind[::-1]]))\n        indicesx=np.hstack((indicesx,tempind[1,ind[::-1]]))\n\n        tempind=np.vstack((indices[2][0],indices[2][1]))\n        ind = np.lexsort((tempind[0], tempind[1]))\n\n        indicesy=np.hstack((indicesy,tempind[0,ind]))\n        indicesx=np.hstack((indicesx,tempind[1,ind])) \n\n        tempind=np.vstack((indices[3][0],indices[3][1]))\n        ind = np.lexsort((-tempind[0], tempind[1]))\n\n        indicesy=np.hstack((indicesy,tempind[0,ind]))\n        indicesx=np.hstack((indicesx,tempind[1,ind]))\n            \n        return indicesy,indicesx\n \ndef perturb(frame,model_matrix,numbasis,evals_matrix, evecs_matrix, KL_basis_matrix,sci_mean_sub_matrix,refs_mean_sub_matrix, angle_list, fwhm, pa_threshold, ann_center):\n    \n\n    \"\"\"\n    Function allowing the estimation of the PSF forward model when relying on KLIP\n    for the computation of the speckle field. The code is based on the PyKLIP library\n     considering only the ADI case with a singlle number of principal components considered.\n    For more details about the code, consider the PyKLIP library or the originall articles\n    (Pueyo, L. 2016, ApJ, 824, 117 or\n     Ruffio, J.-B., Macintosh, B., Wang, J. J., & Pueyo, L. 2017, ApJ, 842)\n    \"\"\"\n    \n    #Selection of the reference library based on the given parralactic angle threshold\n\n    if pa_threshold != 0:\n        indices_left = _find_indices_adi(angle_list, frame,\n                                             pa_threshold, truncate=False)\n\n        models_ref = model_matrix[indices_left]\n\n    else:\n        models_ref = model_matrix\n\n\n    #Computation of the self-subtraction and over-subtraction for the current frame\n    \n    model_sci = model_matrix[frame]  \n    KL_basis=KL_basis_matrix[frame]\n    sci_mean_sub=sci_mean_sub_matrix[frame]\n    refs_mean_sub=refs_mean_sub_matrix[frame]\n    evals=evals_matrix[frame]\n    evecs=evecs_matrix[frame]\n\n    max_basis = KL_basis.shape[0]\n    N_pix = KL_basis.shape[1]\n\n    models_mean_sub = models_ref - np.nanmean(models_ref, axis=1)[:,None] \n    models_mean_sub[np.where(np.isnan(models_mean_sub))] = 0\n    \n    model_sci_mean_sub = model_sci- np.nanmean(model_sci)\n    model_sci_mean_sub[np.where(np.isnan(model_sci_mean_sub))] = 0\n    model_sci_mean_sub_rows = np.reshape(model_sci_mean_sub,(1,N_pix))\n    sci_mean_sub_rows = np.reshape(sci_mean_sub,(1,N_pix))\n    \n    delta_KL = np.zeros([max_basis, N_pix])\n\n    models_mean_sub_X_refs_mean_sub_T = models_mean_sub.dot(refs_mean_sub.transpose())\n\n    for k in range(max_basis):\n        Zk = np.reshape(KL_basis[k,:],(1,KL_basis[k,:].size))\n        Vk = (evecs[:,k])[:,None]\n\n\n        diagVk_X_models_mean_sub_X_refs_mean_sub_T = (Vk.T).dot(models_mean_sub_X_refs_mean_sub_T)\n        models_mean_sub_X_refs_mean_sub_T_X_Vk = models_mean_sub_X_refs_mean_sub_T.dot(Vk)\n        DeltaZk = -(1/(2*np.sqrt(evals[k])))*(diagVk_X_models_mean_sub_X_refs_mean_sub_T.dot(Vk) + ((Vk.T).dot(models_mean_sub_X_refs_mean_sub_T_X_Vk))).dot(Zk)+(Vk.T).dot(models_mean_sub)\n\n\n        for j in range(k):\n            Zj = KL_basis[j, :][None,:]\n            Vj = evecs[:, j][:,None]\n            DeltaZk += np.sqrt(evals[j])/(evals[k]-evals[j])*(diagVk_X_models_mean_sub_X_refs_mean_sub_T.dot(Vj) + ((Vj.T).dot(models_mean_sub_X_refs_mean_sub_T_X_Vk))).dot(Zj)\n        for j in range(k+1, max_basis):\n            Zj = KL_basis[j, :][None,:]\n            Vj = evecs[:, j][:,None]\n            DeltaZk += np.sqrt(evals[j])/(evals[k]-evals[j])*(diagVk_X_models_mean_sub_X_refs_mean_sub_T.dot(Vj) + ((Vj.T).dot(models_mean_sub_X_refs_mean_sub_T_X_Vk))).dot(Zj)\n\n        delta_KL[k] = DeltaZk/np.sqrt(evals[k])\n        \n    oversubtraction_inner_products = np.dot(model_sci_mean_sub_rows, KL_basis.T)  \n    \n    selfsubtraction_1_inner_products = np.dot(sci_mean_sub_rows, delta_KL.T)\n    selfsubtraction_2_inner_products = np.dot(sci_mean_sub_rows, KL_basis.T)\n\n    oversubtraction_inner_products[max_basis::] = 0\n    klipped_oversub = np.dot(oversubtraction_inner_products, KL_basis)\n    \n    selfsubtraction_1_inner_products[0,max_basis::] = 0\n    selfsubtraction_2_inner_products[0,max_basis::] = 0\n    klipped_selfsub = np.dot(selfsubtraction_1_inner_products, KL_basis) + \\\n                          np.dot(selfsubtraction_2_inner_products, delta_KL)\n\n    return model_sci[None,:] - klipped_oversub - klipped_selfsub   \n        \n\n\n\ndef KLIP(cube, angle_list, nann=None, local=False, fwhm=4, asize=2, n_segments=1,delta_rot=1, ncomp=1,min_frames_lib=2, max_frames_lib=200,imlib='opencv',nframes=None, interpolation='lanczos4', collapse='median',full_output=False, verbose=1):\n\n    \"\"\"\n    Function allowing the estimation of the cube of residuals after\n    the subtraction of the speckle field modeled via the KLIP framework \n    \"\"\"\n    \n    array = cube\n    if array.ndim != 3:\n        raise TypeError('Input array is not a cube or 3d array')\n    if array.shape[0] != angle_list.shape[0]:\n        raise TypeError('Input vector or parallactic angles has wrong length')\n\n    n, y, _ = array.shape\n    \n    angle_list = check_pa_vector(angle_list)\n    \n    if asize is None:\n        annulus_width = int(np.ceil(2 * fwhm))\n    elif isinstance(asize, int):\n        annulus_width = asize\n        \n    # Annulus parametrization \n    \n    radius_int=fwhm\n    if local==True:\n            if nann> 2*annulus_width:\n                n_annuli = 5\n                radius_int=(nann//annulus_width-2)*annulus_width \n            else:\n                n_annuli = 4 \n                radius_int=(nann//annulus_width-1)*annulus_width\n    else:\n            n_annuli = int((y / 2 - radius_int) / asize)\n            \n    # Definition of the number of segment for the diifferent annuli\n\n    if isinstance(n_segments, int):\n        n_segments = [n_segments for _ in range(n_annuli)]\n    elif n_segments == 'auto':\n        n_segments = list()\n        n_segments.append(2)  \n        n_segments.append(3)  \n        ld = 2 * np.tan(360 / 4 / 2) * asize\n        for i in range(2, n_annuli):  \n            radius = i * asize\n            ang = np.rad2deg(2 * np.arctan(ld / (2 * radius)))\n            n_segments.append(int(np.ceil(360 / ang)))\n\n    if verbose:\n        msg = '# annuli = {}, Ann width = {}, FWHM = {:.3f}'\n        print(msg.format(n_annuli, asize, fwhm))\n        print('PCA per annulus (or annular sectors):')\n\n\n    # Definition of the annuli and the corresmponding parralactic angle threshold \n    \n    cube_out = np.zeros_like(array)\n    for ann in range(n_annuli):\n        if isinstance(ncomp, list) or isinstance(ncomp, np.ndarray):\n            if len(ncomp) == n_annuli:\n                ncompann = ncomp[ann]\n            else:\n                msge = 'If ncomp is a list, it must match the number of annuli'\n                raise TypeError(msge)\n        else:\n            ncompann = ncomp\n\n        \n        inner_radius = radius_int + ann * annulus_width\n        n_segments_ann = n_segments[ann]\n\n\n        if verbose:\n            print('{} : in_rad={}, n_segm={}'.format(ann+1, inner_radius,\n                                                     n_segments_ann))\n\n\n        theta_init = 90\n        res_ann_par = _define_annuli(angle_list, ann, int((y / 2 - radius_int) / asize), fwhm,radius_int, annulus_width, delta_rot,n_segments_ann, verbose)\n        pa_thr, inner_radius, ann_center = res_ann_par\n        indices = get_annulus_segments(array[0], inner_radius, annulus_width,n_segments_ann,theta_init)\n        \n        # Computation of the speckle field for the different frames and estimation of the cube of residuals\n        \n        for j in range(n_segments_ann):\n\n            for k in range(array.shape[0]):\n                \n                res =KLIP_patch(k,array[:, indices[j][0], indices[j][1]], ncompann, angle_list, fwhm, pa_thr, ann_center,nframes=nframes)\n                cube_out[k,indices[j][0], indices[j][1]] = res[3]\n\n\n    # Cube is derotated according to the parallactic angle and collapsed\n    \n    cube_der = cube_derotate(cube_out, angle_list, imlib=imlib,interpolation=interpolation)\n    frame = cube_collapse(cube_der, mode=collapse)\n\n    if full_output:\n        return cube_out, cube_der, frame\n    else:\n        return frame\n    \ndef KLIP_patch(frame, matrix, numbasis, angle_list, fwhm, pa_threshold, ann_center,nframes=None):\n\n    \"\"\"          \n    Function allowing the computation via KLIP of the speckle field for a \n    given sub-region of the original ADI sequence. Code inspired by the PyKLIP librabry\n    \"\"\"\n    \n    max_frames_lib=200\n    \n    if pa_threshold != 0:\n        if ann_center > fwhm*20:\n            indices_left = _find_indices_adi(angle_list,frame,pa_threshold, truncate=True,max_frames=max_frames_lib)\n        else:\n            indices_left = _find_indices_adi(angle_list, frame,pa_threshold, truncate=False,nframes=nframes)\n\n        refs = matrix[indices_left]\n        \n    else:\n        refs = matrix\n\n    sci = matrix[frame]\n    sci_mean_sub = sci - np.nanmean(sci)\n    #sci_mean_sub[np.where(np.isnan(sci_mean_sub))] = 0\n    refs_mean_sub = refs- np.nanmean(refs, axis=1)[:, None]\n    #refs_mean_sub[np.where(np.isnan(refs_mean_sub))] = 0\n\n    # Covariance matrix definition\n    covar_psfs = np.cov(refs_mean_sub)\n    covar_psfs *= (np.size(sci)-1)\n\n    tot_basis = covar_psfs.shape[0]\n\n    numbasis = np.clip(numbasis - 1, 0, tot_basis-1)\n    max_basis = np.max(numbasis) + 1\n\n    #Computation of the eigenvectors/values of the covariance matrix\n    evals, evecs = la.eigh(covar_psfs)\n    evals = np.copy(evals[int(tot_basis-max_basis):int(tot_basis)])\n    evecs = np.copy(evecs[:,int(tot_basis-max_basis):int(tot_basis)])\n    evals = np.copy(evals[::-1])\n    evecs = np.copy(evecs[:,::-1])\n\n    # Computation of the principal components\n    \n    KL_basis = np.dot(refs_mean_sub.T,evecs)\n    KL_basis = KL_basis * (1. / np.sqrt(evals))[None,:]\n    KL_basis = KL_basis.T \n\n    N_pix = np.size(sci_mean_sub)\n    sci_rows = np.reshape(sci_mean_sub, (1,N_pix))\n    \n    inner_products = np.dot(sci_rows, KL_basis.T)\n    inner_products[0,int(max_basis)::]=0\n\n    #Projection of the science image on the selected prinicpal component\n    #to generate the speckle field model\n\n    klip_reconstruction = np.dot(inner_products, KL_basis)\n\n    # Subtraction of the speckle field model from the riginal science image\n    #to obtain the residual frame\n    \n    sub_img_rows = sci_rows - klip_reconstruction \n\n    return evals,evecs,KL_basis,np.reshape(sub_img_rows, (N_pix)),refs_mean_sub,sci_mean_sub\n\n\ndef LOCI_FM(cube, psf, ann_center, angle_list,scale_list, asize,fwhm, Tol,delta_rot,delta_sep):\n\n\n    \"\"\"\n    Computation of the optimal factors weigthing the linear combination of reference\n    frames used to obtain the modeled speckle field for each frame and allowing the \n    determination of the forward modeled PSF. Estimation of the cube \n    of residuals based on the modeled speckle field.\n    \"\"\"\n\n\n    cube_res = np.zeros_like(cube)\n    ceny, cenx = frame_center(cube[0])\n    radius_int=ann_center-int(1.5*asize)\n    if radius_int<=0:\n        radius_int=1\n            \n    for ann in range(3):\n        n_segments_ann = 1\n        inner_radius_ann = radius_int + ann*asize\n        pa_threshold = _define_annuli(angle_list, ann, 3, asize,\n                                      radius_int, asize, delta_rot,\n                                      n_segments_ann, verbose=False)[0]\n        \n        indices = get_annulus_segments(cube[0], inner_radius=inner_radius_ann,\n                                       width=asize, nsegm=n_segments_ann)\n        ind_opt = get_annulus_segments(cube[0], inner_radius=inner_radius_ann,\n                                       width=asize, nsegm=n_segments_ann,\n                                       optim_scale_fact=2)\n        \n        ayxyx = [inner_radius_ann,pa_threshold, indices[0][0], indices[0][1],\n                   ind_opt[0][0], ind_opt[0][1]]\n                \n        matrix_res, ind_ref, coef, yy, xx = _leastsq_patch(ayxyx,\n                         angle_list,scale_list,fwhm,cube,ann_center,'manhattan', 100,delta_sep,\n                         'lstsq', Tol,formod=True,psf=psf)\n        \n        if ann==1:\n            ind_ref_list=ind_ref\n            coef_list=coef\n        \n        cube_res[:, yy, xx] = matrix_res\n    \n    return cube_res, ind_ref_list,coef_list\n\n\ndef nmf_adisdi(cube, angle_list,scale_list=None, cube_ref=None, ncomp=1, scaling=None, max_iter=100,\n        random_state=None, mask_center_px=None, imlib='opencv',\n        interpolation='lanczos4', collapse='median', full_output=False,\n        verbose=True, **kwargs):\n    \"\"\" Non Negative Matrix Factorization for ADI or ADI+SDI sequences.This function embeds the \n    scikit-learn NMF algorithm solved through coordinate descent method.     \n    \"\"\"\n    \n    array,angle_list_t,scale_list_t=rot_scale('ini',cube,None,angle_list,scale_list,imlib, interpolation)\n            \n\n\n    n, y, x = array.shape\n    \n    matrix = prepare_matrix(array, scaling, mask_center_px, mode='fullfr',\n                            verbose=verbose)\n    matrix += np.abs(matrix.min())\n    if cube_ref is not None:\n        matrix_ref = prepare_matrix(cube_ref, scaling, mask_center_px,\n                                    mode='fullfr', verbose=verbose)\n        matrix_ref += np.abs(matrix_ref.min())\n           \n    mod = NMF_sklearn(n_components=ncomp, alpha=0, solver='cd', init='nndsvd', \n              max_iter=max_iter, random_state=random_state, **kwargs) \n    \n    # H [ncomp, n_pixels]: Non-negative components of the data\n    if cube_ref is not None:\n        H = mod.fit(matrix_ref).components_\n    else:\n        H = mod.fit(matrix).components_          \n    \n    # W: coefficients [n_frames, ncomp]\n    W = mod.transform(matrix)\n        \n    reconstructed = np.dot(W, H)\n    residuals = matrix - reconstructed\n               \n    array_out = np.zeros_like(array)\n    for i in range(n):\n        array_out[i] = residuals[i].reshape(y,x)\n            \n    cube_der=rot_scale('fin',cube,array_out,angle_list_t,scale_list_t, imlib, interpolation)\n    frame_fin = cube_collapse(cube_der, mode=collapse)\n    \n    return cube_der,frame_fin\n\n\ndef annular_NMF(cube, angle_list, nann=None, local=False, fwhm=4, asize=2, n_segments=1, ncomp=20,imlib='opencv', interpolation='lanczos4', collapse='median',max_iter=100,\n        random_state=None,full_output=False, verbose=False):\n   \n    \"\"\"\n    Function allowing the estimation of the cube of residuals after\n    the subtraction of the speckle field modeled via the NMF framework.\n    This codes is an adaptation of the VIP NMF function to the case of annular\n    computation of the modeled speckle fields\n    (only full-frame estimation in Gonzalez et al. AJ, 154:7,2017)\n    \"\"\"\n    \n    array = cube\n    if array.ndim != 3:\n        raise TypeError('Input array is not a cube or 3d array')\n    if array.shape[0] != angle_list.shape[0]:\n        raise TypeError('Input vector or parallactic angles has wrong length')\n\n    n, y, _ = array.shape\n    \n    angle_list = check_pa_vector(angle_list)\n    \n    if asize is None:\n        annulus_width = int(np.ceil(2 * fwhm))\n    elif isinstance(asize, int):\n        annulus_width = asize\n        \n    # Annulus parametrization \n    \n    radius_int=fwhm\n    if local==True:\n            if nann> 2*annulus_width:\n                n_annuli = 5\n                radius_int=(nann//annulus_width-2)*annulus_width \n            else:\n                n_annuli = 4 \n                radius_int=(nann//annulus_width-1)*annulus_width\n    else:\n            n_annuli = int((y / 2 - radius_int) / asize)\n            \n\n    # Definition of the annuli and the corresponding parralactic angle threshold \n    \n    cube_out = np.zeros_like(array)\n    for ann in range(n_annuli):\n\n\n        inner_radius = radius_int + ann * annulus_width\n\n\n        if verbose:\n            print('{} : in_rad={}'.format(ann+1, inner_radius))\n\n        theta_init = 90\n        indices = get_annulus_segments(array[0], inner_radius, annulus_width,n_segments,theta_init)\n        \n        # Computation of the speckle field for the different frames and estimation of the cube of residuals\n        \n        for j in range(n_segments):\n\n            \n            cube_out[:,indices[j][0], indices[j][1]] =NMF_patch(array[:, indices[j][0], indices[j][1]], ncomp, max_iter,random_state,verbose)\n\n\n    # Cube is derotated according to the parallactic angle and collapsed\n    \n    cube_der = cube_derotate(cube_out, angle_list, imlib=imlib,interpolation=interpolation)\n    frame = cube_collapse(cube_der, mode=collapse)\n\n    if full_output:\n        return cube_out, cube_der, frame\n    else:\n        return frame\n    \n\ndef NMF_patch(matrix, ncomp, max_iter,random_state,sklearn=False):\n\n    \"\"\"\n    Function allowing the computation via NMF of the speckle field for a \n    given sub-region of the original ADI sequence. The code is a partial reproduction of\n    the VIP function NMF_patch (Gonzalez et al. AJ, 154:7,2017)\n    \"\"\"\n\n    refs = matrix+ np.abs(matrix.min())\n    \n    if sklearn==True:\n        \n        mod = NMF_sklearn(n_components=ncomp, alpha=0, solver='cd', init='nndsvd', \n                  max_iter=max_iter, random_state=random_state) \n        \n        # H [ncomp, n_pixels]: Non-negative components of the data\n        \n        H = mod.fit(refs).components_          \n    \n        W = mod.transform(refs)\n            \n        reconstructed = np.dot(W, H)\n    \n    else:\n        \n        mod = NMF(X=refs, n_components=ncomp)\n        \n        mod.SolveNMF(maxiters=max_iter, tol=0.001)\n    \n    \n        H=mod.H\n        W=mod.W\n        reconstructed = np.dot(W, H)\n        \n    residuals = refs - reconstructed\n\n    return residuals\n\ndef NMF_patch_range(matrix, ncomp_range, max_iter,random_state,verbose):\n\n    \"\"\"\n    Function allowing the computation via NMF of the speckle field for a range of principal \n    components ncomp_range and a given sub-region of the original ADI sequence. The code is a\n    partial reproduction of the VIP function NMF_patch (Gonzalez et al. AJ, 154:7,2017)\n    \"\"\"\n\n\n    refs = matrix+ np.abs(matrix.min())\n\n    mod = NMF(X=refs, n_components=ncomp_range[len(ncomp_range)-1])\n    \n    mod.SolveNMF(maxiters=max_iter, tol=0.001)\n\n    if verbose:  \n        print('Done NMF with sklearn.NMF.')\n\n    residuals=[]\n    for i in ncomp_range:\n        H=mod.H[ncomp_range[0]:i,:]\n        W=mod.W[:,ncomp_range[0]:i]\n        reconstructed = np.dot(W, H)\n        residuals.append(refs - reconstructed)\n\n    return residuals\n\ndef annular_pca_adisdi(cube, angle_list,scale_list=None, radius_int=0, fwhm=4, asize=2, n_segments=1,\n                 delta_rot=1,delta_sep=0.1, ncomp=1, svd_mode='lapack', nproc=None,\n                 min_frames_lib=2, max_frames_lib=200, tol=1e-1, scaling=None,\n                 imlib='opencv', interpolation='lanczos4', collapse='median',\n                 full_output=False, verbose=False, cube_ref=None, weights=None):\n    \"\"\" PCA exploiting angular and spectral variability (ADI or ADI+SDI fashion).\n    \"\"\"\n\n    array,angle_list_t,scale_list_t=rot_scale('ini',cube,None,angle_list,scale_list,imlib, interpolation)\n            \n    n, y, _ = array.shape\n\n    angle_list_t = check_pa_vector(angle_list_t)\n    n_annuli = int((y / 2 - radius_int) / asize)\n\n    if isinstance(delta_rot, tuple):\n        delta_rot = np.linspace(delta_rot[0], delta_rot[1], num=n_annuli)\n    elif isinstance(delta_rot, (int, float)):\n        delta_rot = [delta_rot] * n_annuli\n\n    if isinstance(n_segments, int):\n        n_segments = [n_segments for _ in range(n_annuli)]\n    elif n_segments == 'auto':\n        n_segments = list()\n        n_segments.append(2)  # for first annulus\n        n_segments.append(3)  # for second annulus\n        ld = 2 * np.tan(360 / 4 / 2) * asize\n        for i in range(2, n_annuli):  # rest of annuli\n            radius = i * asize\n            ang = np.rad2deg(2 * np.arctan(ld / (2 * radius)))\n            n_segments.append(int(np.ceil(360 / ang)))\n\n    if verbose:\n        msg = 'N annuli = {}, FWHM = {:.3f}'\n        print(msg.format(n_annuli, fwhm))\n        print('PCA per annulus (or annular sectors):')\n\n    if nproc is None:   # Hyper-threading \"duplicates\" the cores -> cpu_count/2\n        nproc = cpu_count() // 2\n\n    # The annuli are built, and the corresponding PA thresholds for frame\n    # rejection are calculated (at the center of the annulus)\n    cube_out = np.zeros_like(array)\n    for ann in range(n_annuli):\n        if isinstance(ncomp, tuple) or isinstance(ncomp, np.ndarray):\n            if len(ncomp) == n_annuli:\n                ncompann = ncomp[ann]\n            else:\n                raise TypeError('If `ncomp` is a tuple, it must match the '\n                                'number of annuli')\n        else:\n            ncompann = ncomp\n\n        n_segments_ann = n_segments[ann]\n        res_ann_par = _define_annuli(angle_list_t, ann, n_annuli, fwhm,\n                                     radius_int, asize, delta_rot[ann],\n                                     n_segments_ann, verbose)\n        pa_thr, inner_radius, ann_center = res_ann_par\n        indices = get_annulus_segments(array[0], inner_radius, asize,\n                                       n_segments_ann)\n        # Library matrix is created for each segment and scaled if needed\n        for j in range(n_segments_ann):\n            yy = indices[j][0]\n            xx = indices[j][1]\n            matrix_segm = array[:, yy, xx]  # shape [nframes x npx_segment]\n\n            if cube_ref is not None:\n                matrix_segm_ref = cube_ref[:, yy, xx]\n            else:\n                matrix_segm_ref = None\n\n            res = pool_map(nproc, do_pca_patch, matrix_segm, iterable(range(n)),\n                           angle_list_t,scale_list_t, fwhm, pa_thr,delta_sep, ann_center, svd_mode,\n                           ncompann, min_frames_lib, max_frames_lib, tol,\n                           matrix_segm_ref)\n\n            res = np.array(res)\n            residuals = np.array(res[:, 0])\n\n            for fr in range(n):\n                cube_out[fr][yy, xx] = residuals[fr]\n\n\n    # Cube is derotated according to the parallactic angle and collapsed\n    cube_der=rot_scale('fin',cube,cube_out,angle_list_t,scale_list_t, imlib, interpolation)\n    \n    frame = cube_collapse(cube_der, mode=collapse)\n\n    return cube_der, frame\n   \ndef do_pca_patch(matrix, frame, angle_list,scale_list, fwhm, pa_threshold, delta_sep, ann_center,\n                 svd_mode, ncomp, min_frames_lib, max_frames_lib, tol,\n                 matrix_ref):\n    \n    \"\"\" \n    Function  doing the SVD/PCA for each frame patch. The code is a partial reproduction of\n    the VIP function do_pca_patch (Gonzalez et al. AJ, 154:7,2017)  \n    \"\"\"\n\n\n    if scale_list is not None:\n    \n        indices_left = np.intersect1d(_find_indices_adi(angle_list, frame,\n                                             pa_threshold, truncate=False),_find_indices_sdi(scale_list, ann_center, frame,\n                                             fwhm, delta_sep))\n    else:\n        indices_left = _find_indices_adi(angle_list, frame,\n                                             pa_threshold, truncate=False)\n    \n\n    data_ref = matrix[indices_left]\n    if matrix_ref is not None:\n        # Stacking the ref and the target ref (pa thresh) libraries\n        data_ref = np.vstack((matrix_ref, data_ref))\n\n    curr_frame = matrix[frame]  # current frame\n    V = get_eigenvectors(ncomp, data_ref, svd_mode, noise_error=tol)\n    transformed = np.dot(curr_frame, V.T)\n    reconstructed = np.dot(transformed.T, V)\n    residuals = curr_frame - reconstructed\n    return residuals, V.shape[0], data_ref.shape[0]\n\n\ndef do_pca_patch_range(matrix, frame, angle_list,scale_list, fwhm, pa_threshold,delta_sep, ann_center,\n                 svd_mode, ncomp_range, min_frames_lib, max_frames_lib, tol,\n                 matrix_ref):\n    \"\"\" \n    Function  doing the SVD/PCA for each frame patch for a range of principal\n    component ncomp_range. The code is a partial reproduction of\n    the VIP function do_pca_patch (Gonzalez et al. AJ, 154:7,2017)  \n    \"\"\"\n\n    if scale_list is not None:\n    \n        indices_left = np.intersect1d(_find_indices_adi(angle_list, frame,\n                                             pa_threshold, truncate=False),_find_indices_sdi(scale_list, ann_center, frame,\n                                             fwhm, delta_sep))\n    else:\n        indices_left = _find_indices_adi(angle_list, frame,\n                                             pa_threshold, truncate=False)\n\n    data_ref = matrix[indices_left]\n    if matrix_ref is not None:\n        # Stacking the ref and the target ref (pa thresh) libraries\n        data_ref = np.vstack((matrix_ref, data_ref))\n\n    curr_frame = matrix[frame]  # current frame\n    V = get_eigenvectors(ncomp_range[len(ncomp_range)-1], data_ref, svd_mode, noise_error=tol)\n    residuals=[]\n    for i in ncomp_range:\n        V_trunc=V[ncomp_range[0]:i,:]\n        transformed = np.dot(curr_frame, V_trunc.T)\n        reconstructed = np.dot(transformed.T, V_trunc)\n        residuals.append(curr_frame - reconstructed)\n        \n    return residuals, V.shape[0], data_ref.shape[0]\n\n         \ndef loci_adisdi(cube, angle_list,scale_list=None, fwhm=4, metric='manhattan',\n                 dist_threshold=50, delta_rot=0.5,delta_sep=0.1, radius_int=0, asize=4,\n                 n_segments=1, nproc=1, solver='lstsq', tol=1e-3,\n                 optim_scale_fact=1, imlib='opencv', interpolation='lanczos4',\n                 collapse='median', nann=None,local=False, verbose=True, full_output=False):\n    \"\"\" Least-squares model PSF subtraction for ADI or ADI+SDI. This code is an adaptation of the VIP\n    xloci function to provide, if required, the residuals after speckle field subtraction\n    for a given annulus.\n    \"\"\"\n    \n    cube_rot_scale,angle_list_t,scale_list_t=rot_scale('ini',cube,None,angle_list,scale_list,imlib, interpolation)\n            \n            \n    y = cube_rot_scale.shape[1]\n    if not asize < y // 2:\n        raise ValueError(\"asize is too large\")\n\n    angle_list = check_pa_vector(angle_list)\n    if local==True:\n            n_annuli = 3 \n            radius_int=nann-asize\n    else:\n            n_annuli= int((y / 2 - radius_int) / asize)\n    if verbose:\n        print(\"Building {} annuli:\".format(n_annuli))\n\n    if isinstance(delta_rot, tuple):\n        delta_rot = np.linspace(delta_rot[0], delta_rot[1], num=n_annuli)\n    elif isinstance(delta_rot, (int, float)):\n        delta_rot = [delta_rot] * n_annuli\n\n    if nproc is None:\n        nproc = cpu_count() // 2        # Hyper-threading doubles the # of cores\n\n    annulus_width = asize\n    if isinstance(n_segments, int):\n        n_segments = [n_segments]*n_annuli\n    elif n_segments == 'auto':\n        n_segments = list()\n        n_segments.append(2)    # for first annulus\n        n_segments.append(3)    # for second annulus\n        ld = 2 * np.tan(360/4/2) * annulus_width\n        for i in range(2, n_annuli):    # rest of annuli\n            radius = i * annulus_width\n            ang = np.rad2deg(2 * np.arctan(ld / (2 * radius)))\n            n_segments.append(int(np.ceil(360/ang)))\n\n    # annulus-wise least-squares combination and subtraction\n    cube_res = np.zeros_like(cube_rot_scale)\n\n    ayxyx = []  # contains per-segment data\n\n    for ann in range(n_annuli):\n        n_segments_ann = n_segments[ann]\n        inner_radius_ann = radius_int + ann*annulus_width\n\n        # angles\n        pa_threshold = _define_annuli(angle_list, ann, n_annuli, fwhm,\n                                      radius_int, asize, delta_rot[ann],\n                                      n_segments_ann, verbose)[0]\n\n        # indices\n        indices = get_annulus_segments(cube_rot_scale[0], inner_radius=inner_radius_ann,\n                                       width=asize, nsegm=n_segments_ann)\n        ind_opt = get_annulus_segments(cube_rot_scale[0], inner_radius=inner_radius_ann,\n                                       width=asize, nsegm=n_segments_ann,\n                                       optim_scale_fact=optim_scale_fact)\n\n        # store segment data for multiprocessing\n        ayxyx += [(inner_radius_ann+asize//2,pa_threshold, indices[nseg][0], indices[nseg][1],\n                   ind_opt[nseg][0], ind_opt[nseg][1]) for nseg in\n                  range(n_segments_ann)]\n\n\n\n    msg = 'Patch-wise least-square combination and subtraction:'\n    # reverse order of processing, as outer segments take longer\n    res_patch = pool_map(nproc, _leastsq_patch, iterable(ayxyx[::-1]),\n                         angle_list_t,scale_list_t,fwhm,cube_rot_scale, None, metric, dist_threshold,delta_sep,\n                         solver, tol, verbose=verbose, msg=msg,\n                         progressbar_single=True)\n\n    for patch in res_patch:\n        matrix_res, yy, xx = patch\n        cube_res[:, yy, xx] = matrix_res\n        \n    cube_der=rot_scale('fin',cube,cube_res,angle_list_t,scale_list_t, imlib, interpolation)\n    frame_der_median = cube_collapse(cube_der, collapse)\n\n    if verbose:\n        print('Done processing annuli')\n\n    return cube_der, frame_der_median\n\n\ndef _leastsq_patch(ayxyx, angle_list,scale_list,fwhm,cube, nann,metric, dist_threshold,delta_sep,\n                   solver, tol,formod=False,psf=None):\n\n    \"\"\"\n    Function allowing th estimation of the optimal factors for the modeled speckle field\n    estimation via the LOCI framework. The code has been developped based on the VIP \n    python function _leastsq_patch, but return additionnaly the set of coefficients used for\n    the speckle field computation.\n    \"\"\"\n    \n    ann_center,pa_threshold, yy, xx, yy_opti, xx_opti = ayxyx\n    \n    ind_ref_list=[]\n    coef_list=[]\n    \n    yy_opt=[]\n    xx_opt=[]\n        \n    for j in range(0,len(yy_opti)):\n        if not any(x in np.where(yy==yy_opti[j])[0] for x in np.where(xx==xx_opti[j])[0]):\n            xx_opt.append(xx_opti[j])\n            yy_opt.append(yy_opti[j])\n    \n\n    values = cube[:, yy, xx]  \n    matrix_res = np.zeros((values.shape[0], yy.shape[0]))\n    values_opt = cube[:, yy_opti, xx_opti]\n    n_frames = cube.shape[0]\n\n\n    for i in range(n_frames):\n        \n        if scale_list is not None:\n    \n            ind_fr_i = np.intersect1d(_find_indices_adi(angle_list, i,\n                                                 pa_threshold, truncate=False),_find_indices_sdi(scale_list, ann_center, i,\n                                                 fwhm, delta_sep))\n        else:\n            ind_fr_i = _find_indices_adi(angle_list, i,\n                                                 pa_threshold, truncate=False)\n        if len(ind_fr_i) > 0:\n            A = values_opt[ind_fr_i]\n            b = values_opt[i]\n            if solver == 'lstsq':\n                coef = np.linalg.lstsq(A.T, b, rcond=tol)[0]     # SVD method\n            elif solver == 'nnls':\n                coef = sp.optimize.nnls(A.T, b)[0]\n            elif solver == 'lsq':   \n                coef = sp.optimize.lsq_linear(A.T, b, bounds=(0, 1),\n                                              method='trf',\n                                              lsq_solver='lsmr')['x']\n            else:\n                raise ValueError(\"`solver` not recognized\")\n        else:\n            msg = \"No frames left in the reference set. Try increasing \"\n            msg += \"`dist_threshold` or decreasing `delta_rot`.\"\n            raise RuntimeError(msg)\n\n\n        if formod==True:\n            ind_ref_list.append(ind_fr_i)\n            coef_list.append(coef)       \n            \n        recon = np.dot(coef, values[ind_fr_i])\n        matrix_res[i] = values[i] - recon\n    \n    if formod==True:\n        return matrix_res,ind_ref_list,coef_list, yy, xx,\n    else:\n        return matrix_res, yy,xx\n    \n      \ndef llsg_adisdi(cube, angle_list,scale_list, fwhm, rank=10, thresh=1, max_iter=10,\n         low_rank_ref=False, low_rank_mode='svd', auto_rank_mode='noise',\n         residuals_tol=1e-1, cevr=0.9, thresh_mode='soft', nproc=1,\n         asize=None, n_segments=4, azimuth_overlap=None, radius_int=None,\n         random_seed=None, imlib='opencv', interpolation='lanczos4',\n         high_pass=None, collapse='median', full_output=True, verbose=True,\n         debug=False):\n    \n    \"\"\" Local low rank plus Gaussian PSF subtraction for ADI or ADI+SDI. This \n    code is an adaptation of the VIP llsg function.\n    \"\"\"\n    \n    cube_rot_scale,angle_list_t,scale_list_t=rot_scale('ini',cube,None,angle_list,scale_list,imlib, interpolation)\n    \n    list_l, list_s, list_g, f_l, frame_fin, f_g = vip.llsg.llsg(cube_rot_scale, angle_list_t, fwhm, rank=rank,asize=asize, thresh=1,n_segments=n_segments, max_iter=40, random_seed=10, nproc=nproc,full_output=True,verbose=False)\n    res_s=np.array(list_s)\n    residuals_cube_=cube_derotate(res_s[0],-angle_list_t)\n    cube_der=rot_scale('fin',cube,residuals_cube_,angle_list_t,scale_list_t, imlib, interpolation)\n    frame_fin=cube_collapse(cube_der, collapse)\n    return cube_der,frame_fin\n    \n\ndef _decompose_patch(indices, i_patch,cube_init, n_segments_ann, rank, low_rank_ref,\n                     low_rank_mode, thresh, thresh_mode, max_iter,\n                     auto_rank_mode, cevr, residuals_tol, random_seed,\n                     debug=False, full_output=False):\n    \n\n    \"\"\" Patch decomposition from the LLSG VIP function.\n    \"\"\"\n    \n    j = i_patch\n    yy = indices[j][0]\n    xx = indices[j][1]\n    data_segm = cube_init[:, yy, xx]\n\n    if low_rank_ref:\n        ref_segments = list(range(n_segments_ann))\n        ref_segments.pop(j)\n        for m, n in enumerate(ref_segments):\n            if m == 0:\n                yy_ref = indices[n][0]\n                xx_ref = indices[n][1]\n            else:\n                yy_ref = np.hstack((yy_ref, indices[n][0]))\n                xx_ref = np.hstack((xx_ref, indices[n][1]))\n        data_ref = cube_init[:, yy_ref, xx_ref]\n    else:\n        data_ref = data_segm\n\n    patch = _patch_rlrps(data_segm, data_ref, rank, low_rank_ref,\n                         low_rank_mode, thresh, thresh_mode,\n                         max_iter, auto_rank_mode, cevr,\n                         residuals_tol, random_seed, debug=debug,\n                         full_output=full_output)\n    return patch\n\n_largenumber = 1E100\n_smallnumber = 1E-5\n\nclass NMF:\n    \"\"\"\n    Nonnegative Matrix Factorization - Build a set of nonnegative basis components given \n    a dataset with Heteroscedastic uncertainties and missing data with a vectorized update rule.\n    Algorithm:\n      -- Iterative multiplicative update rule\n    Input: \n      -- X: m x n matrix, the dataset\n    Optional Input/Output: \n      -- n_components: desired size of the basis set, default 5\n      -- V: m x n matrix, the weight, (usually) the inverse variance\n      -- M: m x n binary matrix, the mask, False means missing/undesired data\n      -- H: n_components x n matrix, the H matrix, usually interpreted as the coefficients\n      -- W: m x n_components matrix, the W matrix, usually interpreted as the basis set\n    Comments:\n      -- Between W and H, which one is the basis set and which one is the coefficient \n         depends on how you interpret the data, because you can simply transpose everything\n         as in X-WH versus X^T - (H^T)(W^T)\n      -- Everything needs to be non-negative\n    References:\n      -- Guangtun Ben Zhu, 2016\n         A Vectorized Algorithm for Nonnegative Matrix Factorization with \n         Heteroskedastic Uncertainties and Missing Data\n         AJ/PASP, (to be submitted)\n      -- Blanton, M. and Roweis, S. 2007\n         K-corrections and Filter Transformations in the Ultraviolet, Optical, and Near-infrared\n         The Astronomical Journal, 133, 734\n      -- Lee, D. D., & Seung, H. S., 2001\n         Algorithms for non-negative matrix factorization\n         Advances in neural information processing systems, pp. 556-562\n    \"\"\"\n\n    def __init__(self, X, W=None, H=None, V=None, M=None, n_components=5):\n        \"\"\"\n        Initialization\n        \n        Required Input:\n          X -- the input data set\n        Optional Input/Output:\n          -- n_components: desired size of the basis set, default 5\n          -- V: m x n matrix, the weight, (usually) the inverse variance\n          -- M: m x n binary matrix, the mask, False means missing/undesired data\n          -- H: n_components x n matrix, the H matrix, usually interpreted as the coefficients\n          -- W: m x n_components matrix, the W matrix, usually interpreted as the basis set\n        \"\"\"\n\n        # I'm making a copy for the safety of everything; should not be a bottleneck\n        self.X = np.copy(X) \n        if (np.count_nonzero(self.X<0)>0):\n            print(\"There are negative values in X. Setting them to be zero...\", flush=True)\n            self.X[self.X<0] = 0.\n\n        self.n_components = n_components\n        self.maxiters = 100\n        self.tol = _smallnumber\n        np.random.seed(10)\n        if (W is None):\n            self.W = np.random.rand(self.X.shape[0], self.n_components)\n        else:\n            if (W.shape != (self.X.shape[0], self.n_components)):\n                raise ValueError(\"Initial W has wrong shape.\")\n            self.W = np.copy(W)\n        if (np.count_nonzero(self.W<0)>0):\n            print(\"There are negative values in W. Setting them to be zero...\", flush=True)\n            self.W[self.W<0] = 0.\n\n        if (H is None):\n            self.H = np.random.rand(self.n_components, self.X.shape[1])\n        else:\n            if (H.shape != (self.n_components, self.X.shape[1])):\n                raise ValueError(\"Initial H has wrong shape.\")\n            self.H = np.copy(H)\n        if (np.count_nonzero(self.H<0)>0):\n            print(\"There are negative values in H. Setting them to be zero...\", flush=True)\n            self.H[self.H<0] = 0.\n\n        if (V is None):\n            self.V = np.ones(self.X.shape)\n        else:\n            if (V.shape != self.X.shape):\n                raise ValueError(\"Initial V(Weight) has wrong shape.\")\n            self.V = np.copy(V)\n        if (np.count_nonzero(self.V<0)>0):\n            print(\"There are negative values in V. Setting them to be zero...\", flush=True)\n            self.V[self.V<0] = 0.\n\n        if (M is None):\n            self.M = np.ones(self.X.shape, dtype=np.bool)\n        else:\n            if (M.shape != self.X.shape):\n                raise ValueError(\"M(ask) has wrong shape.\")\n            if (M.dtype != np.bool):\n                raise TypeError(\"M(ask) needs to be boolean.\")\n            self.M = np.copy(M)\n\n        # Set masked elements to be zero\n        self.V[(self.V*self.M)<=0] = 0\n        self.V_size = np.count_nonzero(self.V)\n\n    @property\n    def cost(self):\n        \"\"\"\n        Total cost of a given set s\n        \"\"\"\n        diff = self.X - np.dot(self.W, self.H)\n        chi2 = np.einsum('ij,ij', self.V*diff, diff)/self.V_size\n        return chi2\n\n    def SolveNMF(self, W_only=False, H_only=False, maxiters=None, tol=None):\n        \"\"\"\n        Construct the NMF basis\n        Keywords:\n            -- W_only: Only update W, assuming H is known\n            -- H_only: Only update H, assuming W is known\n               -- Only one of them can be set\n        Optional Input:\n            -- tol: convergence criterion, default 1E-5\n            -- maxiters: allowed maximum number of iterations, default 1000\n        Output: \n            -- chi2: reduced final cost\n            -- time_used: time used in this run\n        \"\"\"\n\n\n        if (maxiters is not None): \n            self.maxiters = maxiters\n        if (tol is not None):\n            self.tol = tol\n\n        chi2 = self.cost\n        oldchi2 = _largenumber\n\n        if (W_only and H_only):\n            return (chi2, 0.)\n\n        V = np.copy(self.V)\n        VT = V.T\n\n        #XV = self.X*self.V\n        XV = np.multiply(V, self.X)\n        XVT = np.multiply(VT, self.X.T)\n\n        niter = 0\n\n        while (niter < self.maxiters) and ((oldchi2-chi2)/oldchi2 > self.tol):\n\n            # Update H\n            if (not W_only):\n                H_up = np.dot(XVT, self.W)\n                WHVT = np.multiply(VT, np.dot(self.W, self.H).T)\n                H_down = np.dot(WHVT, self.W)\n                self.H = self.H*H_up.T/H_down.T\n\n            # Update W\n            if (not H_only):\n                W_up = np.dot(XV, self.H.T)\n                WHV = np.multiply(V, np.dot(self.W, self.H))\n                W_down = np.dot(WHV, self.H.T)\n                self.W = self.W*W_up/W_down\n\n            # chi2\n            oldchi2 = chi2\n            chi2 = self.cost\n\n        return\n    \n\n", "meta": {"hexsha": "733a0eff21e557f8f32c9d92815d4f668db0c2d8", "size": 47930, "ext": "py", "lang": "Python", "max_stars_repo_path": "PyRSM/utils.py", "max_stars_repo_name": "chdahlqvist/RSMmap", "max_stars_repo_head_hexsha": "53984967d612eaf4feb90ba4972109638f6cf70a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-05-18T16:40:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T15:32:31.000Z", "max_issues_repo_path": "PyRSM/utils.py", "max_issues_repo_name": "chdahlqvist/RSMmap", "max_issues_repo_head_hexsha": "53984967d612eaf4feb90ba4972109638f6cf70a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PyRSM/utils.py", "max_forks_repo_name": "chdahlqvist/RSMmap", "max_forks_repo_head_hexsha": "53984967d612eaf4feb90ba4972109638f6cf70a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-19T11:04:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T11:04:21.000Z", "avg_line_length": 38.5909822866, "max_line_length": 242, "alphanum_fraction": 0.6145420405, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 12057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.1982999865280577}}
{"text": "\"\"\"\nContains numerical kernel for Seismic FDFD class\n\"\"\"\n\nimport numpy\nimport scipy\nimport scipy.sparse\nimport SimPEG\nimport shutil, os, errno\nfrom IPython.parallel import require, interactive, Reference\n\nDEFAULT_FREESURF_BOUNDS = [False, False, False, False]\nDEFAULT_PML_SIZE = 10\nDEFAULT_IREG = 4\nDEFAULT_DTYPE = 'double'\n\ntry:\n    from pymatsolver import MumpsSolver\n    DEFAULT_SOLVER = MumpsSolver\nexcept:\n    DEFAULT_SOLVER = SimPEG.SolverWrapD(scipy.sparse.linalg.splu)\n\nclass SeisFDFDKernel(object):\n\n    # source array ref\n\n    # receiver array ref\n\n    mesh = None\n    freq = None\n    Solver = lambda: None\n\n\n    def __init__(self, systemConfig, **kwargs):\n\n        if systemConfig.get('cache', False):\n            try:\n                from tempfile import mkdtemp\n                from joblib import Memory\n            except ImportError:\n                pass\n            else:\n                if 'cacheDir' in systemConfig:\n                    cacheDir = systemConfig['cacheDir']\n                    try:\n                        os.makedirs(cacheDir)\n                    except OSError as e:\n                        if e.errno == errno.EEXIST and os.path.isdir(cacheDir):\n                            pass\n                        else:\n                            raise\n                else:\n                    cacheDir = mkdtemp()\n\n                self._mem = Memory(cachedir=cacheDir, verbose=0)\n\n                # Cache outputs of these methods\n                self.forward = self._mem.cache(self.forward)\n                self.backprop = self._mem.cache(self.backprop)\n\n        hx = [(systemConfig['dx'], systemConfig['nx']-1)]\n        hz = [(systemConfig['dz'], systemConfig['nz']-1)]\n        self.mesh = SimPEG.Mesh.TensorMesh([hx, hz], '00')\n\n        self.mesh.ireg = systemConfig.get('ireg', DEFAULT_IREG)\n        self.mesh.freeSurf = systemConfig.get('freeSurf', DEFAULT_FREESURF_BOUNDS)\n\n        initMap = {\n        #   Argument        Rename to Property\n            'c':            'cR',\n            'Q':            None,\n            'rho':          None,\n            'nPML':         None,\n            'freeSurf':     None,\n            'freq':         None,\n            'ky':           None,\n            'kyweight':     None,\n            'Solver':       None,\n            'dx':           None,\n            'dz':           None,\n            'dtype':        None,\n        }\n\n        for key in initMap.keys():\n            if key in systemConfig:\n                if initMap[key] is None:\n                    setattr(self, key, systemConfig[key])\n                else:\n                    setattr(self, initMap[key], systemConfig[key])\n\n    def __del__(self):\n        if hasattr(self, '_mem'):\n            self._mem.clear()\n            cacheDir = self._mem.cachedir\n            del self._mem\n            shutil.rmtree(cacheDir)\n\n\n    # Model properties\n\n    @property\n    def c(self):\n        return self.cR + self.cI\n    @c.setter\n    def c(self, value):\n        self._cR = value.real\n        self._cI = value.imag\n        self._invalidateMatrix()\n\n    @property\n    def rho(self):\n        if getattr(self, '_rho', None) is None:\n            self._rho = 310 * self.c**0.25\n        return self._rho\n    @rho.setter\n    def rho(self, value):\n        self._rho = value\n        self._invalidateMatrix()\n\n    @property\n    def Q(self):\n        if getattr(self, '_Q', None) is None:\n            self._Q = numpy.inf\n        return self._Q\n    @Q.setter\n    def Q(self, value):\n        self._Q = value\n        self._invalidateMatrix()\n\n    @property\n    def cR(self):\n        return self._cR\n    @cR.setter\n    def cR(self, value):\n        self._cR = value\n        self._invalidateMatrix()\n    \n    @property\n    def cI(self):\n        if self.Q is numpy.inf:\n            return 0\n        else:\n            return 1j * self.cR / (2*self.Q)\n    @cI.setter\n    def cI(self, value):\n        if (value == 0).all():\n            self._Q = numpy.inf\n        else:\n            self._Q = 1j * self.cR / (2*value)\n        self._invalidateMatrix()\n\n    # Modelling properties\n\n    @property\n    def nPML(self):\n        if getattr(self, '_nPML', None) is None:\n            self._nPML = DEFAULT_PML_SIZE\n        return self._nPML\n    @nPML.setter\n    def nPML(self, value):\n        self._nPML = value\n        self._invalidateMatrix()\n\n    @property\n    def ky(self):\n        if getattr(self, '_ky', None) is None:\n            self._ky = 0.\n        return self._ky\n    @ky.setter\n    def ky(self, value):\n        self._ky = value\n        self._invalidateMatrix()\n\n    @property\n    def kyweight(self):\n        if getattr(self, '_kyweight', None) is None:\n            self._kyweight = 1.\n        return self._kyweight\n    @kyweight.setter\n    def kyweight(self, value):\n        self._kyweight = value\n        self._invalidateMatrix()\n\n    # Clever matrix setup properties\n\n    @property\n    def Solver(self):\n        if getattr(self, '_Solver', None) is None:\n            self._Solver = DEFAULT_SOLVER\n        return self._Solver\n    @Solver.setter\n    def Solver(self, value):\n        self._Solver = value\n\n    @property\n    def A(self):\n        if getattr(self, '_A', None) is None:\n            self._A = self._initHelmholtzNinePoint()\n        return self._A\n\n    @property\n    def Ainv(self):\n        if getattr(self, '_Ainv', None) is None:\n            self._mfact()\n        return self._Ainv\n\n    def _invalidateMatrix(self):\n        if getattr(self, '_A', None) is not None:\n            del(self._A)\n        if getattr(self, '_Ainv', None) is not None:\n            del(self._Ainv)\n        if getattr(self, '_mem', None) is not None:\n            self._mem.clear()\n\n    @property\n    def dtypeReal(self):\n        if self.dtype == 'float':\n            return numpy.float32\n        elif self.dtype == 'double':\n            return numpy.float64\n        else:\n            raise NotImplementedError('Unknown dtype: %s'%self.dtype)\n\n    @property\n    def dtypeComplex(self):\n        if self.dtype == 'float':\n            return numpy.complex64\n        elif self.dtype == 'double':\n            return numpy.complex128\n        else:\n            raise NotImplementedError('Unknown dtype: %s'%self.dtype)\n\n    @property\n    def dtype(self):\n        return getattr(self, '_dtype', DEFAULT_DTYPE)\n    @dtype.setter\n    def dtype(self, value):\n        # Currently this doesn't work because all the solvers assume doubles\n        # if value in ['float', 'double']:\n        if value in ['double']:\n            self._dtype = value\n        else:\n            raise NotImplementedError('Unknown dtype: %s'%value)\n\n    # ------------------------------------------------------------------------\n    # Matrix setup\n\n    def _mfact(self):\n        self._Ainv = self.Solver(self.A)\n\n    def _initHelmholtzNinePoint(self):\n        \"\"\"\n        An attempt to reproduce the finite-difference stencil and the\n        general behaviour of OMEGA by Pratt et al. The stencil is a 9-point\n        second-order version based on work by a number of people in the mid-90s\n        including Ivan Stekl. The boundary conditions are based on the PML\n        implementation by Steve Roecker in fdfdpml.f.\n        \"\"\"\n\n        # Set up SimPEG mesh\n        dims = (self.mesh.nNy, self.mesh.nNx)\n        # mAve = self.mesh.aveN2CC\n\n        # c = (mAve.T * self.c.ravel()).reshape(dims)\n        # rho = (mAve.T * self.rho.ravel()).reshape(dims)\n\n        c = self.c\n        rho = self.rho\n\n        # fast --> slow is x --> y --> z as Fortran\n\n        # Set up physical properties in matrices with padding\n        omega   = 2 * numpy.pi * self.freq \n        cPad    = numpy.pad(c, pad_width=1, mode='edge')\n        rhoPad  = numpy.pad(rho, pad_width=1, mode='edge')\n\n        aky = 2*numpy.pi*self.ky\n\n        # Model parameter M\n        K = ((omega**2 / cPad**2) - aky**2) / rhoPad\n\n        # Horizontal, vertical and diagonal geometry terms\n        dx  = self.mesh.hx[0]\n        dz  = self.mesh.hy[0]\n        dxx = dx**2\n        dzz = dz**2\n        dxz = dx*dz\n        dd  = numpy.sqrt(dxz)\n\n        # PML decay terms\n        # NB: Arrays are padded later, but 'c' in these lines\n        #     comes from the original (un-padded) version\n\n        nPML    = self.nPML\n\n        pmldx   = dx*(nPML - 1)\n        pmldz   = dz*(nPML - 1)\n        pmlr    = 1e-3\n        pmlfx   = 3.0 * numpy.log(1/pmlr)/(2*pmldx**3)\n        pmlfz   = 3.0 * numpy.log(1/pmlr)/(2*pmldz**3)\n\n        dpmlx   = numpy.zeros(dims, dtype=self.dtypeComplex)\n        dpmlz   = numpy.zeros(dims, dtype=self.dtypeComplex)\n        isnx    = numpy.zeros(dims, dtype=self.dtypeReal)\n        isnz    = numpy.zeros(dims, dtype=self.dtypeReal)\n\n        # Only enable PML if the free surface isn't set\n\n        freeSurf = self.mesh.freeSurf\n\n        if freeSurf[0]:    \n            isnz[-nPML:,:] = -1 # Top\n\n        if freeSurf[1]:\n            isnx[:,-nPML:] = -1 # Right Side\n\n        if freeSurf[2]:\n            isnz[:nPML,:] = 1 # Bottom\n\n        if freeSurf[3]:\n            isnx[:,:nPML] = 1 # Left side\n\n        dpmlx[:,:nPML] = (numpy.arange(nPML, 0, -1)*dx).reshape((1,nPML))\n        dpmlx[:,-nPML:] = (numpy.arange(1, nPML+1, 1)*dx).reshape((1,nPML))\n        dnx     = pmlfx*c*dpmlx**2\n        ddnx    = 2*pmlfx*c*dpmlx\n        denx    = dnx + 1j*omega\n        r1x     = 1j*omega / denx\n        r1xsq   = r1x**2\n        r2x     = isnx*r1xsq*ddnx/denx\n\n        dpmlz[:nPML,:] = (numpy.arange(nPML, 0, -1)*dz).reshape((nPML,1))\n        dpmlz[-nPML:,:] = (numpy.arange(1, nPML+1, 1)*dz).reshape((nPML,1))\n        dnz     = pmlfz*c*dpmlz**2\n        ddnz    = 2*pmlfz*c*dpmlz\n        denz    = dnz + 1j*omega\n        r1z     = 1j*omega / denz\n        r1zsq   = r1z**2\n        r2z     = isnz*r1zsq*ddnz/denz\n\n        # Visual key for finite-difference terms\n        # (per Pratt and Worthington, 1990)\n        #\n        #   This         Original\n        # AF FF CF  vs.  AD DD CD\n        # AA BE CC  vs.  AA BE CC\n        # AD DD CD  vs.  AF FF CF\n\n        # Set of keys to index the dictionaries\n        keys = ['AD', 'DD', 'CD', 'AA', 'BE', 'CC', 'AF', 'FF', 'CF']\n\n        # Diagonal offsets for the sparse matrix formation\n        offsets = {\n            'AD':   (-1) * dims[1] + (-1), \n            'DD':   (-1) * dims[1] + ( 0),\n            'CD':   (-1) * dims[1] + (+1),\n            'AA':   ( 0) * dims[1] + (-1),\n            'BE':   ( 0) * dims[1] + ( 0),\n            'CC':   ( 0) * dims[1] + (+1),\n            'AF':   (+1) * dims[1] + (-1),\n            'FF':   (+1) * dims[1] + ( 0),\n            'CF':   (+1) * dims[1] + (+1),\n        }\n\n        # Buoyancies\n        bMM = 1. / rhoPad[0:-2,0:-2] # bottom left\n        bME = 1. / rhoPad[0:-2,1:-1] # bottom centre\n        bMP = 1. / rhoPad[0:-2,2:  ] # bottom right\n        bEM = 1. / rhoPad[1:-1,0:-2] # middle left\n        bEE = 1. / rhoPad[1:-1,1:-1] # middle centre\n        bEP = 1. / rhoPad[1:-1,2:  ] # middle right\n        bPM = 1. / rhoPad[2:  ,0:-2] # top    left\n        bPE = 1. / rhoPad[2:  ,1:-1] # top    centre\n        bPP = 1. / rhoPad[2:  ,2:  ] # top    right\n\n        # Initialize averaged buoyancies on most of the grid\n        bMM = (bEE + bMM) / 2 # a2\n        bME = (bEE + bME) / 2 # d1\n        bMP = (bEE + bMP) / 2 # d2\n        bEM = (bEE + bEM) / 2 # a1\n        # ... middle\n        bEP = (bEE + bEP) / 2 # c1\n        bPM = (bEE + bPM) / 2 # f2\n        bPE = (bEE + bPE) / 2 # f1\n        bPP = (bEE + bPP) / 2 # c2\n\n        # Reset the buoyancies on the outside edges\n        # bMM[ 0, :] = bEE[ 0, :]\n        # bMM[ :, 0] = bEE[ :, 0]\n        # bME[ 0, :] = bEE[ 0, :]\n        # bMP[ 0, :] = bEE[ 0, :]\n        # bMP[ :,-1] = bEE[ :,-1]\n        # bEM[ :, 0] = bEE[ :, 0]\n        # bEP[ :,-1] = bEE[ :,-1]\n        # bPM[-1, :] = bEE[-1, :]\n        # bPM[ :, 0] = bEE[ :, 0]\n        # bPE[-1, :] = bEE[-1, :]\n        # bPP[-1, :] = bEE[-1, :]\n        # bPP[ :,-1] = bEE[ :,-1]\n\n        # K = omega^2/(c^2 . rho)\n        kMM = K[0:-2,0:-2] # bottom left\n        kME = K[0:-2,1:-1] # bottom centre\n        kMP = K[0:-2,2:  ] # bottom centre\n        kEM = K[1:-1,0:-2] # middle left\n        kEE = K[1:-1,1:-1] # middle centre\n        kEP = K[1:-1,2:  ] # middle right\n        kPM = K[2:  ,0:-2] # top    left\n        kPE = K[2:  ,1:-1] # top    centre\n        kPP = K[2:  ,2:  ] # top    right\n\n        # 9-point fd star\n        acoef   = 0.5461\n        bcoef   = 0.4539\n        ccoef   = 0.6248\n        dcoef   = 0.09381\n        ecoef   = 0.000001297\n\n        # 5-point fd star\n        # acoef = 1.0\n        # bcoef = 0.0\n        # ecoef = 0.0\n\n        # NB: bPM and bMP here are switched relative to S. Roecker's version\n        #     in OMEGA. This is because the labelling herein is always ?ZX.\n\n        diagonals = {\n            'AD':   ecoef*kMM\n                    + bcoef*bMM*((r1zsq+r1xsq)/(4*dxz) - (r2z+r2x)/(4*dd)),\n            'DD':   dcoef*kME\n                    + acoef*bME*(r1zsq/dz - r2z/2)/dz\n                    + bcoef*(r1zsq-r1xsq)*(bMP+bMM)/(4*dxz),\n            'CD':   ecoef*kMP\n                    + bcoef*bMP*((r1zsq+r1xsq)/(4*dxz) - (r2z+r2x)/(4*dd)),\n            'AA':   dcoef*kEM\n                    + acoef*bEM*(r1xsq/dx - r2x/2)/dx\n                    + bcoef*(r1xsq-r1zsq)*(bPM+bMM)/(4*dxz),\n            'BE':   ccoef*kEE\n                    + acoef*(r2x*(bEM-bEP)/(2*dx) + r2z*(bME-bPE)/(2*dz) - r1xsq*(bEM+bEP)/dxx - r1zsq*(bME+bPE)/dzz)\n                    + bcoef*(((r2x+r2z)*(bMM-bPP) + (r2z-r2x)*(bMP-bPM))/(4*dd) - (r1xsq+r1zsq)*(bMM+bPP+bPM+bMP)/(4*dxz)),\n            'CC':   dcoef*kEP\n                    + acoef*bEP*(r1xsq/dx + r2x/2)/dx\n                    + bcoef*(r1xsq-r1zsq)*(bMP+bPP)/(4*dxz),\n            'AF':   ecoef*kPM\n                    + bcoef*bPM*((r1zsq+r1xsq)/(4*dxz) - (r2z+r2x)/(4*dd)),\n            'FF':   dcoef*kPE\n                    + acoef*bPE*(r1zsq/dz - r2z/2)/dz\n                    + bcoef*(r1zsq-r1xsq)*(bPM+bPP)/(4*dxz),\n            'CF':   ecoef*kPP\n                    + bcoef*bPP*((r1zsq+r1xsq)/(4*dxz) - (r2z+r2x)/(4*dd)),\n        }\n\n        diagonals['AD'] = diagonals['AD'].ravel()[dims[1]+1:          ]\n        diagonals['DD'] = diagonals['DD'].ravel()[dims[1]  :          ]\n        diagonals['CD'] = diagonals['CD'].ravel()[dims[1]-1:          ]\n        diagonals['AA'] = diagonals['AA'].ravel()[        1:          ]\n        diagonals['BE'] = diagonals['BE'].ravel()[         :          ]\n        diagonals['CC'] = diagonals['CC'].ravel()[         :-1        ]\n        diagonals['AF'] = diagonals['AF'].ravel()[         :-dims[1]+1]\n        diagonals['FF'] = diagonals['FF'].ravel()[         :-dims[1]  ]\n        diagonals['CF'] = diagonals['CF'].ravel()[         :-dims[1]-1]\n\n        # self._setupBoundary(diagonals, freeSurf)\n        if any(freeSurf):\n            raise NotImplementedError('Free surface not implemented!')\n\n        # for key in diagonals.keys():\n        #     print('%s:\\t%d\\t%d'%(key, diagonals[key].size, offsets[key]))\n\n        diagonals = [diagonals[key] for key in keys]\n        offsets = [offsets[key] for key in keys]\n\n        A = scipy.sparse.diags(diagonals, offsets, shape=(self.mesh.nN, self.mesh.nN), format='csr', dtype=self.dtypeComplex)#, shape=(self.mesh.nN, self.mesh.nN))#, self.mesh.nN, self.mesh.nN, format='csr')\n\n        return A\n\n    # def _setupBoundary(self, diagonals, freeSurf):\n    #     \"\"\"\n    #     Function to set up boundary regions for the Seismic FDFD problem\n    #     using the 9-point finite-difference stencil from OMEGA/FULLWV.\n    #     \"\"\"\n\n    #     keys = diagonals.keys()\n    #     pickDiag = lambda x: -1. if freeSurf[x] else 1.\n\n    #     # Left\n    #     for key in keys:\n    #         if key is 'BE':\n    #             diagonals[key][:,0] = pickDiag(3)\n    #         else:\n    #             diagonals[key][:,0] = 0.\n\n    #     # Right\n    #     for key in keys:\n    #         if key is 'BE':\n    #             diagonals[key][:,-1] = pickDiag(1)\n    #         else:\n    #             diagonals[key][:,-1] = 0.\n\n    #     # Bottom\n    #     for key in keys:\n    #         if key is 'BE':\n    #             diagonals[key][0,:] = pickDiag(2)\n    #         else:\n    #             diagonals[key][0,:] = 0.\n\n    #     # Top\n    #     for key in keys:\n    #         if key is 'BE':\n    #             diagonals[key][-1,:] = pickDiag(0)\n    #         else:\n    #             diagonals[key][-1,:] = 0.\n\n    # ------------------------------------------------------------------------\n    # Externally-callable functions\n\n    def clear(self):\n        self._invalidateMatrix()\n    \n    # What about @caching decorators?\n    def forward(self, src, dOnly=True):\n\n        q = self.kyweight * src.getq(self.mesh)\n        u = self.Ainv * q\n\n        d = numpy.array([numpy.dot(P,u) for P in src.getP(self.mesh, self.ky)]).ravel()\n\n        if dOnly:\n            return d\n        else:\n            return u, d\n\n    def backprop(self, src, dresid=1.):\n\n        qr = self.kyweight * src.getqback(self.mesh, dresid, self.ky)\n        u = self.Ainv * qr\n\n        return u\n\n    # def gradient(self, isrc, sterm, dresid):\n\n    #     uF, d = self.forward(isrc, False, sterm)\n    #     uB = self.backprop(isrc, dresid)\n\n    #     return uF * uB\n\n", "meta": {"hexsha": "69677cefec1956aff7802dd8ff84abd8b7d57fb1", "size": 17157, "ext": "py", "lang": "Python", "max_stars_repo_path": "zephyr/Kernel.py", "max_stars_repo_name": "bsmithyman/zephyr", "max_stars_repo_head_hexsha": "ef74caadd74cc357b503560c3800e26c49587e61", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-06T18:31:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-06T18:31:16.000Z", "max_issues_repo_path": "zephyr/Kernel.py", "max_issues_repo_name": "bsmithyman/zephyr", "max_issues_repo_head_hexsha": "ef74caadd74cc357b503560c3800e26c49587e61", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "zephyr/Kernel.py", "max_forks_repo_name": "bsmithyman/zephyr", "max_forks_repo_head_hexsha": "ef74caadd74cc357b503560c3800e26c49587e61", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2015-02-24T15:03:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-08T20:18:56.000Z", "avg_line_length": 31.365630713, "max_line_length": 207, "alphanum_fraction": 0.4851081191, "include": true, "reason": "import numpy,import scipy", "num_tokens": 5234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.19823168203304917}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun  6 09:37:12 2019\n\n@author: bressler\n\"\"\"\n\nimport SBCcode as sbc\nfrom os import listdir\nfrom os.path import isfile,join\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy\nfrom gaincalc import get_gain\nimport pulse_integrator as pi\nfrom runlistscatalogue import *\nimport gc\n\nCONVERSION_TO_CHARGE = (125.0/128)*(1/50.0)*(1/1000.0)*(1/(1.602e-19))\n\ndef trig_difference(runs):\n    pmtdiffs = []\n    pmtnobubdiffs = []\n    dubbubdiffs = []\n    for run in runs:\n        print(run)\n        runrawpath = \"/bluearc/storage/SBC-17-data/%s/\"%run\n        runreconpath = \"/pnfs/coupp/persistent/grid_output/SBC-17/output/%s/\"%run\n        acousticfilename = runreconpath+\"AcousticAnalysis_%s.bin\"%run\n        getbubfile = \"/coupp/data/home/coupp/HumanGetBub_output_SBC-17/HumanGetBub_%s.bin\"%run\n        a = sbc.DataHandling.ReadBinary.ReadBlock(acousticfilename)\n        c = sbc.DataHandling.ReadBinary.ReadBlock(getbubfile)\n        eventn = c[\"ev\"]\n        bubt0 = a[\"bubble_t0\"]\n        #events = [evnt for evnt in listdir(runrawpath) if not isfile(join(runrawpath,evnt))]\n        #for x in events:\n        for x in range(101):\n            gc.collect()\n            try:\n                e = sbc.DataHandling.GetSBCEvent.GetEvent(runrawpath,x,'fastDAQ','PMTtraces')\n                cgate = e[\"fastDAQ\"][\"CAMgate\"]\n                dcam = np.diff(cgate)\n                fdt = e[\"fastDAQ\"][\"time\"]\n                camOffTimes = [fdt[i] for i in range(len(dcam)) if dcam[i] > 0.5]\n                pmttracetime = e[\"PMTtraces\"][\"t0_sec\"][:,0]+e[\"PMTtraces\"][\"t0_frac\"][:,0]\n                d=sbc.AnalysisModules.PMTfastDAQalignment.PMTandFastDAQalignment(e)\n                pmtalign = d[\"PMT_trigt0_sec\"]+d[\"PMT_trigt0_frac\"]\n                tracetimes = pmttracetime - pmtalign\n                \n                at0 = bubt0[int(x),0]\n                for t in (tracetimes-at0):\n                    if t<0 and t>-500e-6:\n                        lastCamOff = 0\n                        for k in range(len(camOffTimes)):\n                            if t+at0 > camOffTimes[k]:\n                                lastCamOff = camOffTimes[k]\n                            elif t+at0 < camOffTimes[k]:\n                                break\n                        if t+at0-lastCamOff > 25e-6:\n                            if list(eventn).count(int(x)) == 2:\n                                pmtdiffs.append(t)\n                            elif list(eventn).count(int(x)) == 1:\n                                pmtnobubdiffs.append(t)\n                            elif list(eventn).count(int(x)) == 3:\n                                print(3)\n                            elif list(eventn).count(int(x)) == 4:\n                                dubbubdiffs.append(t)\n            except:\n                print(\"Last event: %d\"%(x-1))\n                break\n\n    return [pmtnobubdiffs,pmtdiffs,dubbubdiffs]\n    \n\ndef zdependence(runs, m):\n    #m = 1e7\n\n    #m=get_gain(\"/bluearc/storage/SBC-17-data/\",runs[0])\n    \n    Ncoinc = [0,0]\n    ntotcoinc = [0,0]\n    totevents = [0,0]\n    totbub = [0,0]\n    diffs = [[],[]]\n    goodz=[[],[]]\n    pmtdiffs = [[],[]]\n    coincspec = [[],[]]\n\n    allxyzfname = \"/pnfs/coupp/persistent/grid_output/SBC-17/output/SimpleXYZ_all.bin\"\n    xyzf = sbc.DataHandling.ReadBinary.ReadBlock(allxyzfname)\n    for run in runs:\n        print(\"zdependence processing run \"+run)\n        indices = [i for i,x in enumerate(xyzf[\"runid\"]) if str(x[0])+\"_\"+str(x[1]) == run]\n        runposreco = {\"ev\":[xyzf[\"ev\"][indices]],\"x\":[xyzf[\"bubX\"][indices]],\n                      \"y\":[xyzf[\"bubY\"][indices]],\"z\":[xyzf[\"bubZ\"][indices]]}\n        runrawpath = \"/bluearc/storage/SBC-17-data/%s/\"%run\n        runreconpath = \"/pnfs/coupp/persistent/grid_output/SBC-17/output/%s/\"%run\n        acousticfilename = runreconpath+\"AcousticAnalysis_%s.bin\"%run\n        a = sbc.DataHandling.ReadBinary.ReadBlock(acousticfilename)\n        #c = sbc.DataHandling.ReadBinary.ReadBlock(getbubfile)\n        bubt0 = a[\"bubble_t0\"]\n        events = [evnt for evnt in listdir(runrawpath) if not isfile(join(runrawpath,evnt))]\n        for j in [0,1]:\n            with open(\"/nashome/b/bressler/sbcoutput/%s_PMTmatching_ch%s.txt\"%(run,str(j)),\"w+\") as f, open(\"/nashome/b/bressler/sbcoutput/%s_muonCoincidences.txt\"%run,'w+') as fmu:\n                f.write(\"run event PMT_t0_index PMT_t0_-at0_us PMT_t0 at0 phe z\\n\")\n                fmu.write(\"run event phe\\n\")\n                for x in events:\n                    yes = False\n                    if int(x)<len(runposreco[\"z\"][0])-1:\n                        yes=True\n                    totevents[j] += 1\n                    if yes and not np.isnan(runposreco[\"z\"][0][int(x)]):\n                        totbub[j] += 1\n                        e = sbc.DataHandling.GetSBCEvent.GetEvent(runrawpath,x)\n                        veto = e[\"fastDAQ\"][\"VetoCoinc\"]\n                        cgate = e[\"fastDAQ\"][\"CAMgate\"]\n                        dcam = np.diff(cgate)\n                        fdt = e[\"fastDAQ\"][\"time\"]\n                        camOffTimes = [fdt[i] for i in range(len(dcam)) if dcam[i] > 0.5]\n                        muon = False\n                        pmttracetime = e[\"PMTtraces\"][\"t0_sec\"][:,0]+e[\"PMTtraces\"][\"t0_frac\"][:,0]\n                        d=sbc.AnalysisModules.PMTfastDAQalignment.PMTandFastDAQalignment(e)\n                        pmtalign = d[\"PMT_trigt0_sec\"]+d[\"PMT_trigt0_frac\"]\n                        tracetimes = pmttracetime - pmtalign\n                        at0 = bubt0[int(x),j]\n                        i=0 # to match the indexing of the pre-made code I had 1???\n                        candidate = 0\n                        candidate_time = 0\n                        candidate_PMTtime = 0\n                        candidate_index = 0\n                        for t in (tracetimes-at0):\n                            # loop through every PMT trace for the event\n                            \n                            if t<-150e-6 and t>-600e-6: \n                                # if the trace time is within 500 microsec before acoustic t0\n                                if max(veto)>0.1:\n                                    if fdt[list(veto).index(max(veto))]-at0<0 and fdt[list(veto).index(max(veto))]-at0>-500e-6:\n                                        print(\"Veto Coincidence: event \"+run+\"-\"+str(x))\n                                        muon = True\n                                        \n                                #lastCamOff = 0\n                                #for k in range(len(camOffTimes)):\n                                #    if t+at0 > camOffTimes[k]:\n                                #        lastCamOff = camOffTimes[k]\n                                #    elif t+at0 < camOffTimes[k]:\n                                #        break\n                                #if t+at0-lastCamOff > 25e-6:\n                                    # if the trace time is more than 25 microseconds away from a camera gate rise\n                                    #but not doing it this way anymore because we'll check for the LED being on later during the merge\n                                ntotcoinc[j]+=1\n                                pmtdiffs.append(t)\n                                \n                                #take abs to get positive area:\n                                trace = np.fabs(e[\"PMTtraces\"][\"traces\"][i][0]) \n                                #if ch0 saturated, stitch in low res channel:\n                                if max(trace) == 128:\n                                    trace = pi.stitchTraces(trace,np.fabs(e[\"PMTtraces\"][\"traces\"][i][1]))\n                                dt = e[\"PMTtraces\"][\"dt\"][i][0]\n                                \n                                #subtract baseline:\n                                #Actually this gets done in pulse_integrator anyway\n                                #baseline = np.mean(trace[0:50])\n                                #trace -= baseline \n                                                            \n                                #integrate and convert to phe:\n                                [phe,n,totInt,pktimes] = pi.SBC_pulse_integrator_bressler(trace,dt) \n                                if phe != None:\n                                    phe /= m\n                                    #keep track of largest candidate:\n                                    if phe > candidate:\n                                        candidate = phe\n                                        candidate_time = t\n                                        candidate_PMTtime = t+at0\n                                        candidate_index = i\n                                #else:\n                                #    candidate = -1.0\n                            i+=1\n                        #i.e. if there is a candidate PMT trace with area greater than zero\n                        if candidate > 0:\n                            Ncoinc[j] += 1\n                            ind = candidate_index\n                            pmtt = candidate_PMTtime\n                            diffs[j].append(candidate_time)\n                            goodz[j].append(runposreco[\"z\"][0][int(x)])\n                            coincspec[j].append(candidate)\n                            f.write(\"%s %s %d %f %f %f %f %f\\n\"%(run,x,ind,\n                                                              candidate_time*1e6,\n                                                              pmtt,at0,candidate,\n                                                              runposreco[\"z\"][0][int(x)]))\n                        if muon:\n                            fmu.write(\"%s %s %f\\n\"%(run,x,candidate))\n                    gc.collect()\n            print(\"run \"+run+\" file %s written\"%str(j))\n                        #pmtdiffs.append(candidate_times[candidates.index(max(candidates))])\n    print(\"total number of events: \"+str(totevents))\n    print(\"total number of bubbles: \"+str(totbub))               \n    print(\"total coincident triggers: \"+str(ntotcoinc))\n    print(\"total coincident bubbles with scintillation greater than 0phe: \"+str(Ncoinc))\n    print(\"fraction of bubbles with a coincident scintillation signal greater than 0phe: \"+str(sum(Ncoinc)*100/sum(totbub))+\"%\")\n    \n    return [goodz,diffs,coincspec,Ncoinc,ntotcoinc,totevents,totbub]\n    \n\n    \ndef main():\n    bgruns = bgOct10and11\n    \n    biberuns = BiBeSept23and24\n    \n    \"\"\"\n    ch1 files made for:\n        \"20171003_4\",\"20171003_5\",\n        \"20171004_0\",\"20171004_1\",\"20171004_2\",\"20171004_3\",\"20171004_4\",\n        \"20171005_0\",\"20171005_1\",\"20171005_2\",\"20171005_3\",\"20171005_4\",\n        \"20171006_0\",\"20171006_1\"\n        \n    ch0 files made for:\n        \"20171003_4\",\"20171003_5\",\n        \"20171004_0\",\"20171004_1\",\"20171004_2\",\"20171004_3\",\"20171004_4\",\n        \"20171005_0\",\"20171005_1\",\"20171005_2\",\"20171005_3\",\"20171005_4\",\n        \"20171006_0\",\"20171006_1\"\n        \n    \"\"\"\n    \n    BiAlruns = []\n    \n    \"\"\"\n    ch1 files made for:\n        \"20171006_2\",\"20171006_3\",\"20171006_4\",\"20171006_5\",\"20171007_0\",\n        \"20171007_1\",\"20171007_2\",\"20171007_4\",\"20171007_5\",\n        \"20171007_6\",\"20171008_0\",\"20171008_1\",\"20171008_4\",\"20171008_6\",\n        \"20171008_7\",\"20171009_0\",\"20171009_1\",\"20171009_2\"\n    \n    ch0 files made for:\n        \"20171006_2\",\"20171006_3\",\"20171006_4\",\"20171006_5\",\"20171007_0\",\n        \"20171007_1\",\"20171007_2\",\"20171007_4\",\"20171007_5\",\n        \"20171007_6\",\"20171008_0\",\"20171008_1\",\"20171008_4\",\"20171008_6\",\n        \"20171008_7\",\"20171009_0\",\"20171009_1\",\"20171009_2\"\n    \"\"\"\n\n    cfruns = [\"20170711_15\",\"20170711_16\"]\n    \"\"\"\n    ch0 files made for:\n        \"20170707_6\",\"20170707_7\",\"20170707_8\",\"20170707_9\",\"20170707_10\",\"20170708_0\",\n            \"20170708_1\",\"20170708_3\",\"20170708_5\",\"20170708_6\",\"20170708_7\",\n            \"20170708_8\",\"20170708_9\",\"20170709_0\",\"20170709_1\",\"20170709_2\",\n            \"20170709_3\",\"20170709_4\",\"20170709_6\",\"20170709_7\",\"20170709_8\",\n            \"20170710_0\",\"20170710_1\",\"20170710_2\",\"20170710_3\",\"20170710_4\",\n            \"20170710_5\",\"20170710_6\",\"20170710_7\",\"20170710_8\",\"20170710_9\",\n            \"20170711_0\",\"20170711_14\",\"20170711_16\"\n    \n    ch1 files made for:\n        \n            \"20170707_6\",\"20170707_7\",\"20170707_8\",\"20170707_9\",\"20170707_10\",\"20170708_0\",\n            \"20170708_1\",\"20170708_3\",\"20170708_4\",\"20170708_5\",\"20170708_6\",\n            \"20170708_7\",\"20170708_8\",\"20170708_9\",\"20170709_0\",\"20170709_1\",\"20170709_2\",\n            \"20170709_3\",\"20170709_4\",\"20170709_6\",20170709_7\",\"20170709_8\",\n            \"20170710_0\",\"20170710_1\",\"20170710_2\",\"20170710_3\",\"20170710_4\",\n            \"20170710_5\",\"20170710_6\",\"20170710_7\",\"20170710_8\", \"20170710_9\",\"20170711_0\",\n            \"20170711_14\",\"20170711_15\",\"20170711_16\"\n            \n            \n    \n    bad AcousticAnalysis_ .bin files:\n        \"20170708_2\",\"20170708_4\",\n    \"\"\"\n    \n    pmtnobubdiffs,pmtdiffs,dubbubdiffs = trig_difference(biberuns)\n    goodz,diffs,coincspec,Ncoinc,ntotcoinc,totevents,totbub = zdependence(biberuns)\n    \n    bgpmtnobubdiffs,bgpmtdiffs,bgdubbubdiffs = trig_difference(bgruns)\n    bggoodz,bgdiffs,bgcoincspec,bgNcoinc,bgntotcoinc,bgtotevents,bgtotbub = zdependence(bgruns)\n    \n    \"\"\"\n    plt.figure()\n    _,bins,_=plt.hist(pmtdiffs,150,histtype='step',label=\"one bubble\",lw=4)\n    plt.hist(diffs,200,histtype='step')\n    plt.hist(pmtnobubdiffs,bins,histtype='step', label = \"no bubble\",lw=4)\n    plt.hist(dubbubdiffs,bins,histtype='step', label=\"two bubbles\",lw=4)\n    plt.xlabel(\"PMT trigger times minus acoustic t_0\",fontsize=25)\n    #plt.xlim([-100e-6,300e-6])\n    plt.yscale('log')\n    plt.legend(fontsize=18)\n    plt.show\n    \"\"\"\n    def ft(x,m,b):\n        return m*x +b\n        \n    params,params_cov = scipy.optimize.curve_fit(ft,goodz,diffs)\n    p1 = params[0]\n    p0 = params[1]\n    print(\"the slope is\"+str(p1))\n    print(\"The speed of sound is \"+str((1/np.fabs(p1))/100)+\" m/s\")\n    \n    plt.figure()\n    plt.scatter(goodz,diffs)\n    plt.plot(np.arange(-3,0.1,0.1),p0+p1*np.arange(-3,0.1,0.1),lw=3)\n    plt.ylim([-500e-6, 0])\n    plt.xlabel(\"z position (cm)\")\n    plt.ylabel(\"time difference (seconds)\")\n    plt.show\n    \n    \n    \n    plt.figure()\n    vals,bins,_=plt.hist(coincspec,np.ceil(max(coincspec)),histtype='step',color='r')\n    bgvals,_,_ = plt.hist(bgcoincspec,bins,histtype='step')\n    plt.xlabel(\"spectrum of PMT pulse areas within 500 microseconds before acoustic t_0 (photoelectrons)\")\n    plt.show\n\n    plt.figure()\n    plt.bar(bins[:(len(vals))],[v/totbub for v in vals],1,color='r',linewidth=0,label=\"californium\")\n    plt.bar(bins[:len(vals)],[v/bgtotbub for v in bgvals],0.7,color='b',linewidth = 0,label=\"background\")\n    plt.xlabel(\"spectrum of PMT pulse areas within 500 microseconds before acoustic t_0 (photoelectrons)\",fontsize=25)\n    plt.ylabel(\"probability of a scintillation pulse of this area per bubble\",fontsize=25)\n    plt.legend(fontsize=18)\n    plt.show\n    \nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "03d348f3ae8a55ae87004a3989bf9fc87b9aec28", "size": 15070, "ext": "py", "lang": "Python", "max_stars_repo_path": "UserCode/bressler/coincidentbubblescintillation.py", "max_stars_repo_name": "cericdahl/SBCcode", "max_stars_repo_head_hexsha": "90a7841a5c1208d64f71a332289d9005a011aa21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-08-27T18:02:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-09T21:19:04.000Z", "max_issues_repo_path": "UserCode/bressler/coincidentbubblescintillation.py", "max_issues_repo_name": "SBC-Collaboration/SBC-Analysis", "max_issues_repo_head_hexsha": "90a7841a5c1208d64f71a332289d9005a011aa21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "UserCode/bressler/coincidentbubblescintillation.py", "max_forks_repo_name": "SBC-Collaboration/SBC-Analysis", "max_forks_repo_head_hexsha": "90a7841a5c1208d64f71a332289d9005a011aa21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-06-20T21:36:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T17:23:14.000Z", "avg_line_length": 46.801242236, "max_line_length": 181, "alphanum_fraction": 0.5122096881, "include": true, "reason": "import numpy,import scipy", "num_tokens": 4141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3242353989809524, "lm_q1q2_score": 0.19823167804079106}}
{"text": "from __future__ import absolute_import\r\nfrom __future__ import print_function\r\n\r\nimport copy\r\nfrom collections import defaultdict\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom tqdm import tqdm\r\nfrom six.moves import xrange\r\nimport sys\r\nsys.path.append('../../.')\r\nfrom cleverhans.utils import other_classes\r\nfrom cleverhans.utils_tf import model_argmax\r\nfrom cleverhans.evaluation import batch_eval\r\nfrom cleverhans.attacks_tf import (jacobian_graph, jacobian,\r\n                                   apply_perturbations, saliency_map)\r\nimport keras.backend as K\r\nimport os\r\nimport pickle\r\n\r\ndef adaptive_fgsm(x, predictions, eps, clip_min=None, clip_max=None,\r\n                  log_dir=None, y=None, model_logits = None,\r\n                  alpha = None, dataset=None\r\n                  ):\r\n    \"\"\"\r\n    Computes symbolic TF tensor for the adversarial samples. This must\r\n    be evaluated with a session.run call.\r\n    :param x: the input placeholder\r\n    :param predictions: the model's output tensor\r\n    :param eps: the epsilon (input variation parameter)\r\n    :param clip_min: optional parameter that can be used to set a minimum\r\n                    value for components of the example returned\r\n    :param clip_max: optional parameter that can be used to set a maximum\r\n                    value for components of the example returned\r\n    :param y: the output placeholder. Use None (the default) to avoid the\r\n            label leaking effect.\r\n    :return: a tensor for the adversarial example\r\n    \"\"\"\r\n\r\n    # Compute loss]\r\n    logits, = predictions.op.inputs\r\n\r\n    fingerprint_dir = log_dir\r\n    fixed_dxs = pickle.load(open(os.path.join(fingerprint_dir, \"fp_inputs_dx.pkl\"), \"rb\"))\r\n    fixed_dys = pickle.load(open(os.path.join(fingerprint_dir, \"fp_outputs.pkl\"), \"rb\"))\r\n\r\n    if y is None:\r\n        # In this case, use model predictions as ground truth\r\n        y = tf.to_float(\r\n            tf.equal(predictions,\r\n                     tf.reduce_max(predictions, 1, keep_dims=True)))\r\n\r\n    output = logits\r\n    pred_class = tf.argmax(y,axis=1)\r\n    loss_fp = 0\r\n    [a,b,c] = np.shape(fixed_dys)\r\n    num_dx = b\r\n    target_dys = tf.convert_to_tensor(fixed_dys)\r\n    target_dys = (tf.gather(target_dys,pred_class))\r\n    norms = tf.sqrt(tf.reduce_sum(tf.square(output), axis=1, keep_dims=True))\r\n    norm_logits = output/norms\r\n\r\n    for i in range(num_dx):\r\n        logits_p = model_logits(x + fixed_dxs[i])\r\n        p_norm = tf.sqrt(tf.reduce_sum(tf.square(logits_p), axis=1, keep_dims=True))\r\n        logits_p_norm = logits_p/p_norm\r\n        loss_fp = loss_fp + tf.losses.mean_squared_error((logits_p_norm - norm_logits),target_dys[:,i,:])\r\n        #self appropriate fingerprint\r\n\r\n\r\n    y = y / tf.reduce_sum(y, 1, keep_dims=True)\r\n    loss_ce = tf.reduce_mean(\r\n        tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y)\r\n    )\r\n    ## Tune this alpha!!\r\n\r\n    loss = loss_ce - alpha*loss_fp\r\n\r\n    # Define gradient of loss wrt input\r\n    grad, = tf.gradients(loss, x)\r\n\r\n    # Take sign of gradient\r\n    signed_grad = tf.sign(grad)\r\n\r\n    # Multiply by constant epsilon\r\n    scaled_signed_grad = eps * signed_grad\r\n\r\n    # Add perturbation to original example to obtain adversarial example\r\n    adv_x = tf.stop_gradient(x + scaled_signed_grad)\r\n\r\n    # If clipping is needed, reset all values outside of [clip_min, clip_max]\r\n    if (clip_min is not None) and (clip_max is not None):\r\n        adv_x = tf.clip_by_value(adv_x, clip_min, clip_max)\r\n\r\n    return adv_x\r\n\r\n\r\ndef adaptive_fast_gradient_sign_method(sess, model, X, Y, eps, clip_min=None,\r\n                              clip_max=None, batch_size=256, log_dir = None,\r\n                                       model_logits = None, binary_steps = 2,\r\n                                        dataset=\"cifar\"):\r\n    \"\"\"\r\n    TODO\r\n    :param sess:\r\n    :param model: predictions or after-softmax\r\n    :param X:\r\n    :param Y:\r\n    :param eps:\r\n    :param clip_min:\r\n    :param clip_max:\r\n    :param batch_size:\r\n    :return:\r\n    \"\"\"\r\n    # Define TF placeholders for the input and output\r\n    x = tf.placeholder(tf.float32, shape=(None,) + X.shape[1:])\r\n    y = tf.placeholder(tf.float32, shape=(None,) + Y.shape[1:])\r\n    alpha = tf.placeholder(tf.float32, shape=(None,) + (1,))\r\n    num_samples = np.shape(X)[0]\r\n    ALPHA = 0.1*np.ones((num_samples,1))\r\n    ub = 10.0*np.ones(num_samples)\r\n    lb = 0.0*np.ones(num_samples)\r\n    Best_X_adv = None\r\n    for i in range(binary_steps):\r\n        adv_x = adaptive_fgsm(\r\n            x, model(x), eps=eps,\r\n            clip_min=clip_min,\r\n            clip_max=clip_max, y=y,\r\n            log_dir= log_dir,\r\n            model_logits = model_logits,\r\n            alpha = alpha\r\n        )\r\n\r\n        X_adv = batch_eval(\r\n            sess, [x, y, alpha], [adv_x],\r\n            [X, Y, ALPHA], feed={},\r\n            args={'batch_size': batch_size}\r\n        )\r\n        X_adv = np.array(X_adv[0])\r\n        if(i==0):\r\n            Best_X_adv = X_adv\r\n\r\n        ALPHA, Best_X_adv = binary_refinement(sess,Best_X_adv,\r\n                      X_adv, Y, ALPHA, ub, lb, model, dataset)\r\n\r\n    return Best_X_adv\r\n\r\n\r\ndef binary_refinement(sess,Best_X_adv,\r\n                      X_adv, Y, ALPHA, ub, lb, model, dataset='cifar'):\r\n    num_samples = np.shape(X_adv)[0]\r\n    print(dataset)\r\n    if(dataset==\"mnist\"):\r\n        X_place = tf.placeholder(tf.float32, shape=[1, 1, 28, 28])\r\n    else:\r\n        X_place = tf.placeholder(tf.float32, shape=[1, 3, 32, 32])\r\n\r\n    pred = model(X_place)\r\n    for i in range(num_samples):\r\n        logits_op = sess.run(pred,feed_dict={X_place:X_adv[i:i+1,:,:,:]})\r\n        if(not np.argmax(logits_op) == np.argmax(Y[i,:])):\r\n            # Success, increase alpha\r\n            Best_X_adv[i,:,:,:] = X_adv[i,:,:,]\r\n            lb[i] = ALPHA[i,0]\r\n        else:\r\n            ub[i] = ALPHA[i,0]\r\n        ALPHA[i] = 0.5*(lb[i] + ub[i])\r\n    return ALPHA, Best_X_adv\r\n\r\ndef adaptive_basic_iterative_method(sess, model, X, Y, eps, eps_iter, nb_iter=50,\r\n                           clip_min=None, clip_max=None, batch_size=256,\r\n                           log_dir = None, model_logits = None,\r\n                                     binary_steps =2, attack_type = \"bim-b\",\r\n                                     dataset=\"cifar\"):\r\n    \"\"\"\r\n    TODO\r\n    :param sess:\r\n    :param model: predictions or after-softmax\r\n    :param X:\r\n    :param Y:\r\n    :param eps:\r\n    :param eps_iter:\r\n    :param nb_iter:\r\n    :param clip_min:\r\n    :param clip_max:\r\n    :param batch_size:\r\n    :return:\r\n    \"\"\"\r\n    print(\"nb_iter\",nb_iter)\r\n    # Define TF placeholders for the input and output\r\n    x = tf.placeholder(tf.float32, shape=(None,)+X.shape[1:])\r\n    y = tf.placeholder(tf.float32, shape=(None,)+Y.shape[1:])\r\n    alpha = tf.placeholder(tf.float32, shape=(None,) + (1,))\r\n    num_samples = np.shape(X)[0]\r\n    ALPHA = 0.1*np.ones((num_samples,1))\r\n    ub = 10.0*np.ones(num_samples)\r\n    lb = 0.0*np.ones(num_samples)\r\n    Best_X_adv = None\r\n\r\n    results = np.zeros((nb_iter, X.shape[0],) + X.shape[1:])\r\n    # Initialize adversarial samples as the original samples, set upper and\r\n    # lower bounds\r\n    X_adv = X\r\n    X_min = X_adv - eps\r\n    X_max = X_adv + eps\r\n    print('Running BIM iterations...')\r\n    # \"its\" is a dictionary that keeps track of the iteration at which each\r\n    # sample becomes misclassified. The default value will be (nb_iter-1), the\r\n    # very last iteration.\r\n    def f(val):\r\n        return lambda: val\r\n    its = defaultdict(f(nb_iter-1))\r\n    # Out keeps track of which samples have already been misclassified\r\n    out = set()\r\n    for j in range(binary_steps):\r\n\r\n        for i in tqdm(range(nb_iter)):\r\n            adv_x = adaptive_fgsm(\r\n                x, model(x), eps=eps_iter,\r\n                clip_min=clip_min, clip_max=clip_max, y=y,\r\n                log_dir= log_dir,\r\n                model_logits = model_logits,\r\n                alpha = alpha\r\n            )\r\n            X_adv, = batch_eval(\r\n                sess, [x, y, alpha], [adv_x],\r\n                [X_adv, Y, ALPHA], feed={K.learning_phase(): 0},\r\n                args={'batch_size': batch_size}\r\n            )\r\n            X_adv = np.maximum(np.minimum(X_adv, X_max), X_min)\r\n            results[i] = X_adv\r\n            # check misclassifieds\r\n            predictions = model.predict_classes(X_adv, batch_size=512, verbose=0)\r\n            misclassifieds = np.where(predictions != Y.argmax(axis=1))[0]\r\n            for elt in misclassifieds:\r\n                if elt not in out:\r\n                    its[elt] = i\r\n                    out.add(elt)\r\n            print(i)\r\n\r\n        X_adv = results[-1]\r\n        if(j==0):\r\n            Best_X_adv = X_adv\r\n        ALPHA, Best_X_adv = binary_refinement(sess,Best_X_adv,\r\n                      X_adv, Y, ALPHA, ub, lb, model, dataset)\r\n    return Best_X_adv\r\n", "meta": {"hexsha": "45cd8cd79b7985a77b217cfc932114de4167b993", "size": 8854, "ext": "py", "lang": "Python", "max_stars_repo_path": "third_party/lid_adversarial_subspace_detection/adaptive_attacks.py", "max_stars_repo_name": "ptrcarta/neural-fingerprinting", "max_stars_repo_head_hexsha": "01fa8cb592f6fa7497c6884861adf7680ffa7f29", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2018-03-10T04:33:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T13:03:37.000Z", "max_issues_repo_path": "third_party/lid_adversarial_subspace_detection/adaptive_attacks.py", "max_issues_repo_name": "ptrcarta/neural-fingerprinting", "max_issues_repo_head_hexsha": "01fa8cb592f6fa7497c6884861adf7680ffa7f29", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-07-22T20:59:01.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-17T07:00:00.000Z", "max_forks_repo_path": "third_party/lid_adversarial_subspace_detection/adaptive_attacks.py", "max_forks_repo_name": "StephanZheng/neural-fingerprinting", "max_forks_repo_head_hexsha": "57e93e487ef324427456b14d1d81bc9e08483d27", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2018-03-14T14:01:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T19:19:56.000Z", "avg_line_length": 35.9918699187, "max_line_length": 106, "alphanum_fraction": 0.5834651005, "include": true, "reason": "import numpy", "num_tokens": 2164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.19810702581556874}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n### Example of use\n###, L. Darme 02/07/2019\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n# Importing additional user-defined function\n\nimport UsefulFunctions as uf\nimport Amplitudes as am\nimport Production as br\nimport Detection as de\nimport LimitsList as lim\n#############################################################################\n###############        Several limits example    ##############################\n#############################################################################\n\n\n# This example loads a list of limits, recast them and save them in the Output folder, then plot some of them\n\nif __name__ == \"__main__\":\n\n    geffem={\"gu11\":2/3.,\"gu22\":2/3.,\"gd11\":-1/3.,\"gd22\":-1/3.,\"gd33\":-1/3.,\"gl11\":-1.,\"gl22\":-1.}\n\n    ExperimentsList=np.array([\"lsnd_decay\",\"charm_decay\",\"seaquest_phase2_decay\",\"faser_decay\",\"ship_decay\", \\\n                              \"babar_monogam\",\"belle2_monogam\", \\\n                              \"miniboone_scattering\",\"sbnd_scattering\",\"ship_scattering\",\"nova_scattering\", \\\n                              \"sn1987_low_cooling\",\"sn1987_high_cooling\", \\\n                              \"na62_invisibledecayPi0\",\"bes_invisibledecayJPsi\",\"babar_invisibledecayUpsilon\",\\\n                              \"atlas_monojet_down\",\"atlas_monojet_up\",\"lep_monogam\"])\n\n    Lim,LabelLimit = lim.GetLimits(ExperimentsList,10,geffem,\"V\",True)\n\n\n    fig=plt.figure(1)\n    s = fig.add_subplot(1, 1, 1)\n    yup = 1e4;xup=5\n    ydown = 10;xdown=0.005\n    s.set_xlim((xdown,xup))\n    s.set_ylim((ydown,yup))\n    xbasic=np.linspace(xdown,xup,75)\n    s.set_xscale(\"log\", nonposx='clip')\n    s.set_yscale(\"log\", nonposy='clip')\n\n    s.loglog(Lim['lsnd_decay'][0],Lim['lsnd_decay'][1],linestyle='-',linewidth=1.5,color='xkcd:green',zorder=15)\n    s.fill_between(Lim['lsnd_decay'][0],ydown,Lim['lsnd_decay'][1],color='xkcd:green',alpha=0.5, zorder=15)\n    s.loglog(Lim['ship_decay'][0],Lim['ship_decay'][1],linestyle='--',linewidth=1.5,color='xkcd:orange',zorder=15)\n    s.loglog(Lim['charm_decay'][0],Lim['charm_decay'][1],linestyle='-',linewidth=1.5,color='xkcd:darkgreen',zorder=15)\n    s.fill_between(Lim['charm_decay'][0],ydown,Lim['charm_decay'][1],color='xkcd:darkgreen',alpha=0.5, zorder=15)\n    s.loglog(Lim['seaquest_phase2_decay'][0],Lim['seaquest_phase2_decay'][1],linestyle='--',linewidth=1.5,color='xkcd:red',zorder=15)\n    s.loglog(Lim['faser_decay'][0],Lim['faser_decay'][1],linestyle='-.',linewidth=1.5,color='xkcd:indigo',zorder=15)\n\n    # -------- Mono photon at LEP\n    s.fill_between(Lim['lep_monogam'][0],200,Lim['lep_monogam'][1],color='xkcd:blue',alpha=0.25, zorder=15)\n    s.axhline(200,linestyle='--',linewidth=1.,color='xkcd:blue',zorder=15)\n    s.loglog(Lim['lep_monogam'][0],Lim['lep_monogam'][1],linestyle='--',linewidth=1.5,color='xkcd:blue',zorder=15)\n\n    # -------- Missing energy searches\n    s.loglog(Lim['babar_monogam'][0],Lim['babar_monogam'][1],linestyle='-',linewidth=2,color='xkcd:grey',zorder=15)\n    s.fill_between(Lim['babar_monogam'][0],ydown,Lim['babar_monogam'][1],color='xkcd:grey',alpha=0.5, zorder=15)\n    s.loglog(Lim['belle2_monogam'][0],Lim['belle2_monogam'][1],linestyle='--',linewidth=1.5,color='xkcd:black',zorder=15)\n\n    # ------ Self consistency\n    s.loglog(xbasic,2*xbasic,linestyle='-',linewidth=1.5,color='xkcd:grey',zorder=15)\n    s.fill_between(xbasic,ydown,2*xbasic,color='xkcd:grey',alpha=0.5, zorder=15)\n\n    # -------- SN bounds\n    gp=np.logical_and(Lim['sn1987_high_cooling'][1]>1.1*Lim['sn1987_low_cooling'][1],Lim['sn1987_high_cooling'][1]>1)\n    s.loglog(Lim['sn1987_high_cooling'][0][gp],Lim['sn1987_high_cooling'][1][gp],linestyle='-',linewidth=1,color='xkcd:purple',zorder=15)\n    s.loglog(Lim['sn1987_low_cooling'][0][gp],Lim['sn1987_low_cooling'][1][gp],linestyle='--',linewidth=0.5,color='xkcd:purple',zorder=15)\n    s.fill_between(Lim['sn1987_low_cooling'][0][gp],Lim['sn1987_low_cooling'][1][gp],Lim['sn1987_high_cooling'][1][gp],color='xkcd:purple',alpha=0.15, zorder=15)\n\n    # ----- Invisible decay of Upsilon\n\n    s.loglog(Lim['babar_invisibledecayUpsilon'][0],Lim['babar_invisibledecayUpsilon'][1],linestyle='-',linewidth=1.1,color='xkcd:dark grey',zorder=15)\n    s.fill_between(Lim['babar_invisibledecayUpsilon'][0],ydown,Lim['babar_invisibledecayUpsilon'][1],color='xkcd:grey',alpha=0.25, zorder=15)\n\n    s.text(0.08,220,r'FASER',fontsize=10,color='xkcd:indigo', zorder=40,rotation=40)\n    s.text(1.1,52,r'BaBar' ,fontsize=10, zorder=50)\n    s.text(1.1,110,r'Belle II ($50$ ab${}^{-1}$)' ,fontsize=10, zorder=50)\n    s.text(1.1,220,r'LEP (DELPHI)' ,color='xkcd:darkblue',fontsize=10, zorder=50)\n    s.text(0.01,2500,r'SN1987 (Cooling)' ,color='xkcd:purple',fontsize=10, zorder=50,rotation=0)\n    s.text(0.015,70,r'LSND',fontsize=10,color='xkcd:darkgreen', zorder=50,rotation=20)\n    s.text(0.15,610,r'SeaQuest',fontsize=10,color='xkcd:red', zorder=40,rotation=35)\n    s.text(0.28,510,r'CHARM',fontsize=10,color='xkcd:darkgreen', zorder=40,rotation=35)\n    s.text(1.,4.e3,'SHIP',fontsize=10,color='xkcd:rust', zorder=50,rotation=30)\n    s.text(1.1,160,r'BaBar ($\\Upsilon \\to$ inv)' ,fontsize=10, zorder=50)\n    s.text(0.02,0.94,r'$g_e:g_d:g_u = -1:-\\frac{1}{3}:\\frac{2}{3}$', style='italic',fontsize=14,transform = s.transAxes, zorder=20)\n    #----Adjusting the labels and color bar\n    s.set_xlabel(r'$M_{\\chi_2}$  [GeV]',fontsize=18)\n    s.set_ylabel(r'$\\Lambda$  / $\\sqrt{g}$ [GeV]',fontsize=18)\n\n    #---- Saving and showing on screen the Figure\n    plt.tight_layout()\n    plt.savefig('Output/Example2.pdf')\n    plt.show()\n", "meta": {"hexsha": "e110c8abc1298d05fb3ceff0dadd93c2e0384a25", "size": 5586, "ext": "py", "lang": "Python", "max_stars_repo_path": "Examples/Example2.py", "max_stars_repo_name": "Luc-Darme/DarkEFT", "max_stars_repo_head_hexsha": "f4be14742ced9a1447dbcab40a6c7b18e61cb001", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Examples/Example2.py", "max_issues_repo_name": "Luc-Darme/DarkEFT", "max_issues_repo_head_hexsha": "f4be14742ced9a1447dbcab40a6c7b18e61cb001", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/Example2.py", "max_forks_repo_name": "Luc-Darme/DarkEFT", "max_forks_repo_head_hexsha": "f4be14742ced9a1447dbcab40a6c7b18e61cb001", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-09T06:43:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-09T06:43:46.000Z", "avg_line_length": 56.4242424242, "max_line_length": 161, "alphanum_fraction": 0.6451843895, "include": true, "reason": "import numpy", "num_tokens": 1921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.19810701837912795}}
{"text": "import os\nimport pickle\nimport warnings\n\nimport numpy as np\nfrom shutil import copyfile\n\nfrom astropy import units as u\nfrom astropy.table import Table, Column\n\nfrom .kinematic_distance import KinematicDistance\n\n\nclass BayesianDistance(object):\n    def __init__(self, filename=None):\n        \"\"\"\n        initializes the BayesianDistance class\n\n        Parameters\n        ----------\n        path_to_bdc : file path to the Bayesian distance program\n        path_to_input_table : file path of a table containing information of the\n            Gaussian decompositions\n        verbose : The default is 'True'. Prints status messages to the\n            terminal.\n        \"\"\"\n        self.path_to_bdc = None\n        self.version = '2.4'\n        self.path_to_input_table = None\n        self.path_to_output_table = None\n        self.input_table = None\n        self.verbose = True\n        self.add_kinematic_distance = True\n        self.add_galactocentric_distance = True\n        self.check_for_kda_solutions = True\n        self.prior_velocity_dispersion = False\n        self.colname_lon, self.colname_lat, self.colname_vel,\\\n            self.colname_e_vel, self.colname_kda, self.colname_name,\\\n            self.colname_vel_disp = (None for i in range(7))\n        self.colnr_lon, self.colnr_lat, self.colnr_vel,\\\n            self.colnr_e_vel, self.colnr_kda, self.colnr_name,\\\n            self.colnr_vel_disp = (None for i in range(7))\n        self.prob_sa, self.prob_kd, self.prob_gl, self.prob_ps, self.prob_pm =\\\n            (None for _ in range(5))\n        self.table_format = 'ascii'\n        self.save_temporary_files = False\n        self.max_e_vel = 5.0\n        self.default_e_vel = 5.0\n        self.kda_info_tables = []\n        self.exclude_kda_info_tables = []\n        self.kda_weight = 1\n\n        self.random_seed = 177\n        self.sample = 1000\n        self.beam = None\n        self.size_linewidth_index = 0.5\n        self.size_linewidth_e_index = 0.1\n        self.size_linewidth_sigma_0 = 0.7\n        self.size_linewidth_e_sigma_0 = 0.1\n\n        self.use_ncpus = None\n        self.plot_probability = False\n\n        self._p = {\n            '1.0': {\n                'bdc_fortran': 'Bayesian_distance_v1.0.f',\n                'summary_suffix': '.prt',\n                'fct_extract': self.extract_results_v1p0,\n                'R_0': 8.34},\n            '2.4': {\n                'bdc_fortran': 'Bayesian_distance_2019_fromlist_v2.4.f',\n                'summary_suffix': 'summary.prt',\n                'fct_extract': self.extract_results_v2p4,\n                'R_0': 8.15}\n        }\n\n    def say(self, message, end=None):\n        \"\"\"Diagnostic messages.\"\"\"\n        if self.verbose:\n            print(message, end=end)\n\n    def check_settings(self):\n        self.initialize_bdc()\n        self.initialize_table()\n        self.set_probability_controls()\n        if self.check_for_kda_solutions:\n            self.initialize_kda_tables()\n        if self.prior_velocity_dispersion:\n            self.initialize_prior_velocity_dispersion()\n\n        text = 'Python wrapper for Bayesian distance calculator v{}'.format(\n            self.version)\n        border = len(text) * '='\n        heading = '\\n{a}\\n{b}\\n{a}\\n'.format(a=border, b=text)\n        self.say(heading)\n\n    def initialize_bdc(self):\n        if self.version is None:\n            raise Exception(\"Need to specify 'version'\")\n\n        path_script = os.path.dirname(\n            os.path.dirname(os.path.realpath(__file__)))\n\n        self.path_to_bdc = os.path.join(\n            path_script, 'BDC', 'v' + self.version)\n        path_to_file = os.path.join(\n            self.path_to_bdc, self._p[self.version]['bdc_fortran'])\n\n        with open(path_to_file, \"r\") as fin:\n            self.bdc_script = fin.readlines()\n\n    def initialize_table(self):\n        if self.path_to_output_table is not None:\n            self.path_to_table = self.path_to_output_table\n\n        if self.path_to_table is None:\n            errorMessage = str(\"specify 'path_to_output_table'\")\n            raise Exception(errorMessage)\n\n        self.dirname_table = os.path.dirname(self.path_to_table)\n        if len(self.dirname_table) == 0:\n            self.dirname_table = os.getcwd()\n        self.table_file = os.path.basename(self.path_to_table)\n        self.table_filename, self.table_file_extension =\\\n            os.path.splitext(self.table_file)\n        if not os.path.exists(self.dirname_table):\n            os.makedirs(self.dirname_table)\n\n    def initialize_kda_tables(self):\n        dirname = os.path.dirname(\n            os.path.dirname(os.path.realpath(__file__)))\n        if not self.kda_info_tables:\n            files = os.listdir(os.path.join(dirname, 'KDA_info'))\n            self.kda_info_tables = [\n                name[:-4] for name in files if name.endswith('.ini')]\n\n        if self.exclude_kda_info_tables:\n            self.kda_info_tables = [\n                table for table in self.kda_info_tables\n                if table not in self.exclude_kda_info_tables]\n\n        self._kda_tables = []\n        keys = ['GLON', 'GLAT', 'VLSR', 'd_VLSR', 'p_far',\n                'cos_pa', 'sin_pa', 'aa', 'bb']\n        for tablename in self.kda_info_tables:\n            table = Table.read(os.path.join(\n                dirname, 'KDA_info', tablename + '.dat'), format='ascii')\n            table = table[keys]\n\n            self._kda_tables.append(table)\n\n    def initialize_prior_velocity_dispersion(self):\n        try:\n            self.beam = self.beam.to(u.rad).value\n        except AttributeError:\n            err_msg = \"'beam' needs to be specified as valid astropy unit\"\n            raise Exception(err_msg)\n\n        self.kd = KinematicDistance()\n        self.kd.initialize()\n\n        np.random.seed = self.random_seed\n        self._indices = self.size_linewidth_index + np.random.randn(\n            self.sample) * self.size_linewidth_e_index\n        self._sigma_0 = self.size_linewidth_sigma_0 + np.random.randn(\n            self.sample) * self.size_linewidth_e_sigma_0\n\n    def set_probability_controls(self):\n        s = '      '\n\n        default_vals = {\n            '1.0': {'SA': 0.5, 'KD': 1.0, 'GL': 1.0, 'PS': 0.25, 'PM': None},\n            '2.4': {'SA': 0.85, 'KD': 0.85, 'GL': 0.85, 'PS': 0.15, 'PM': 0.85}\n            }\n\n        if self.prob_sa is None:\n            self.prob_sa = default_vals[self.version]['SA']\n        if self.prob_kd is None:\n            self.prob_kd = default_vals[self.version]['KD']\n        if self.prob_gl is None:\n            self.prob_gl = default_vals[self.version]['GL']\n        if self.prob_ps is None:\n            self.prob_ps = default_vals[self.version]['PS']\n        if self.prob_pm is None:\n            self.prob_pm = default_vals[self.version]['PM']\n\n        cwd = os.getcwd()\n        os.chdir(self.path_to_bdc)\n\n        with open(os.path.join(\n                self.path_to_bdc, 'probability_controls.inp'), 'r') as fin:\n            file_content = fin.readlines()\n        with open(os.path.join(\n                self.path_to_bdc, 'probability_controls.inp'), 'w') as fout:\n            for line in file_content:\n                if not line.startswith('!'):\n                    line = '{s}{a}{s}{b}{s}{c}{s}{d}'.format(\n                        s=s, a=self.prob_sa, b=self.prob_kd, c=self.prob_gl,\n                        d=self.prob_ps)\n                    if self.prob_pm is not None:\n                        line += '{s}{a}'.format(s=s, a=self.prob_pm)\n                fout.write(line)\n        os.chdir(cwd)\n\n        string = str(\"prob_sa: {a}\\nprob_kd: {b}\\n\"\n                     \"prob_gl: {c}\\nprob_ps: {d}\\n\".format(\n                         a=self.prob_sa, b=self.prob_kd, c=self.prob_gl,\n                         d=self.prob_ps))\n        if self.version == '2.4':\n            string += 'prob_pm: {}\\n'.format(self.prob_pm)\n        self.say(\"setting probability controls to the following values:\")\n        self.say(string)\n\n    def determine_column_indices(self):\n        self.colnr_lon = self.input_table.colnames.index(self.colname_lon)\n        self.colnr_lat = self.input_table.colnames.index(self.colname_lat)\n        self.colnr_vel = self.input_table.colnames.index(self.colname_vel)\n        if self.colname_e_vel is not None:\n            if not isinstance(self.colname_e_vel, list):\n                self.colname_e_vel = [self.colname_e_vel]\n            self.colnr_e_vel = [self.input_table.colnames.index(colname)\n                                for colname in self.colname_e_vel]\n        if self.colname_kda is not None:\n            self.colnr_kda = self.input_table.colnames.index(self.colname_kda)\n        if self.colname_vel_disp is not None:\n            self.colnr_vel_disp = self.input_table.colnames.index(\n                self.colname_vel_disp)\n        if self.colname_name is not None:\n            self.colnr_name = self.input_table.colnames.index(self.colname_name)\n\n    def make_fortran_out(self, source):\n        \"\"\"Create a fortran executable for the source.\n\n        Replaces the default input file in the fortran script of the Bayesian\n        distance calculator with the input file of the source, then creates a\n        Fortran executable file.\n        \"\"\"\n        with open(\"{}.f\".format(self.path_to_source), \"w\") as fout:\n            for line in self.bdc_script:\n                fout.write(line.replace('sources_info.inp',\n                                        '{}_sources_info.inp'.format(source)))\n        os.system('gfortran {}.f -o {}.out'.format(\n                self.path_to_source, self.path_to_source))\n\n    def extract_string(self, s, first, last, incl=False):\n        \"\"\"Search for a substring inside a string.\n\n        Parameters\n        ----------\n        s : string that is searched for the substring\n        first : first characters of the substring\n        last : last characters of the substring\n        incl : defines if the `first` and `last` characters are still part of\n            the substring that will be returned. The default is `False`\n            (`first` and `last` are not part of the returned substring)\n\n        Returns\n        -------\n        substring of s\n\n        \"\"\"\n        try:\n            if incl is True:\n                start = s.index(first)\n                end = s.index(last) + len(last)\n            else:\n                start = s.index(first) + len(first)\n                end = s.index(last, start)\n            return s[start:end]\n        except ValueError:\n            return \"\"\n\n    def extract_probability_info(self, line, lon, lat, p_far):\n        \"\"\"\n        Extract the distance results from the corresponding string in\n        the output file of the Bayesian distance calculator tool.\n        \"\"\"\n        deleteString = self.extract_string(\n                line, 'Probability component', ':', incl=True)\n        replaceString = self.extract_string(\n                line, 'Probability component', ':')\n        line = line.replace(deleteString, replaceString)\n        line = line.replace('\\n', '')\n        comp, dist, err, prob, arm = line.split()\n        c_u, c_v, c_w = self.get_cartesian_coords(lon, lat, float(dist))\n        # if np.isnan(dist) is True:\n        #     dist, err, prob = (0.0 for i in range(3))\n        return [comp, dist, err, prob, arm, c_u, c_v, c_w, p_far]\n\n    def extract_results_v1p0(self, input_file_content, result_file_content,\n                             kin_dist=None, kda_ref=None):\n        \"\"\"\n        Loop through the lines of the output file of the Bayesian distance\n        calculator tool and search for the distance results.\n\n        Parameters\n        ----------\n        result_file_content : List containing read-in lines of the output file\n            ({source_name}.prt) of the Bayesian distance calculator tool\n        \"\"\"\n        results = []\n        flag = False\n        for line in result_file_content:\n            if flag:\n                params = line.split()\n                lon, lat, p_far =\\\n                    float(params[1]), float(params[2]), float(params[4])\n                flag = False\n            if 'Extra_info' in line:\n                flag = True\n            searchString = 'Probability component'\n            if searchString in line:\n                result = self.extract_probability_info(line, lon, lat, p_far)\n\n                if kda_ref is not None:\n                    result += [kda_ref]\n\n                if kin_dist is not None:\n                    result += kin_dist\n\n                results.append(result)\n        return results\n\n    def extract_kinematic_distances(self, result_file_content):\n        \"\"\"\"\"\"\n        kinDist = [np.NAN, np.NAN]\n\n        flag = 'one'\n        for line in result_file_content:\n            searchString = 'Kinematic distance(s):'\n            if searchString in line:\n                if flag == 'one':\n                    kinDist[0] = self.extract_kinematic_info(line)\n                    flag = 'two'\n                elif flag == 'two':\n                    kinDist[1] = self.extract_kinematic_info(line)\n        return kinDist\n\n    def extract_kinematic_info(self, line):\n        \"\"\"\n        Extract the distance results from the corresponding string in\n        the output file of the Bayesian distance calculator tool.\n        \"\"\"\n        line = line.replace('Kinematic distance(s):', '')\n        line = line.replace('\\n', '')\n        return float(line)\n\n    def extract_results_v2p4(self, input_file_content, result_file_content,\n                             kin_dist=None, kda_ref=None):\n        for line in input_file_content:\n            if line.startswith('!'):\n                continue\n            params = line.split()\n            p_far = params[5]\n\n        for line in result_file_content:\n            if line.startswith('!'):\n                continue\n            params = line.split()\n\n            n_params = len(params)\n\n            lon, lat, vlsr, e_vlsr = params[:4]\n\n            results = []\n\n            for i in range(1, int(n_params / 4)):\n                comp = int(n_params / 4) - 1\n                dist, e_dist, prob, arm = params[i*4:(i + 1)*4]\n                c_u, c_v, c_w = self.get_cartesian_coords(\n                    float(lon), float(lat), float(dist))\n\n                result = [comp, dist, e_dist, prob, arm, c_u, c_v, c_w, p_far]\n\n                if kda_ref is not None:\n                    result += [kda_ref]\n\n                if kin_dist is not None:\n                    result += kin_dist\n\n                results.append(result)\n        return results\n\n    def delete_all_temporary_files(self, source):\n        for filename in [f for f in os.listdir(self.path_to_bdc) if f.startswith(source)]:\n            os.remove(os.path.join(self.path_to_bdc, filename))\n\n    def get_results(self, source, kda_ref=None, name=None):\n        \"\"\"\n        Extract the distance results from the output file ({source_name}.prt)\n        of the Bayesian distance calculator tool.\n        \"\"\"\n        suffix = self._p[self.version]['summary_suffix']\n        for filename in [f for f in os.listdir(self.path_to_bdc)\n                         if f.startswith(source) and f.endswith(suffix)]:\n            with open(os.path.join(self.path_to_bdc, filename), 'r') as fin:\n                result_file_content = fin.readlines()\n\n        for filename in [f for f in os.listdir(self.path_to_bdc)\n                         if f.startswith(source) and f.endswith(\"info.inp\")]:\n            with open(os.path.join(self.path_to_bdc, filename), 'r') as fin:\n                input_file_content = fin.readlines()\n\n        if self.add_kinematic_distance:\n            if self.version == '1.0':\n                kd_content = result_file_content.copy()\n            elif self.version == '2.4':\n                with open(os.path.join(self.path_to_bdc, source + '.prt'), 'r') as fin:\n                    kd_content = fin.readlines()\n            kinDist = self.extract_kinematic_distances(kd_content)\n        else:\n            kinDist = None\n\n        results = self._p[self.version]['fct_extract'](\n            input_file_content, result_file_content, kin_dist=kinDist, kda_ref=kda_ref)\n\n        if self.plot_probability:\n            if self.save_temporary_files:\n                for filename in [f for f in os.listdir(self.path_to_bdc) if f.startswith(source)]:\n                    src = os.path.join(self.path_to_bdc, filename)\n                    if name is not None:\n                        filename = filename.replace(source, name)\n                    dst = os.path.join(\n                        os.path.dirname(self.path_to_output_table), filename)\n                    copyfile(src, dst)\n\n            self.plot_probability_density(\n                source, results, input_file_content, name=name)\n\n        self.delete_all_temporary_files(source)\n\n        return results\n\n    def run_bdc_script(self, source, input_string):\n        self.path_to_source = os.path.join(self.path_to_bdc, source)\n        filepath = '{}_sources_info.inp'.format(self.path_to_source)\n        with open(filepath, 'w') as fin:\n            fin.write(input_string)\n        self.make_fortran_out(source)\n        cwd = os.getcwd()\n        os.chdir(self.path_to_bdc)\n        os.system('./{}.out'.format(source))\n        os.chdir(cwd)\n\n    def bdc_calculation_ok(self, source):\n        \"\"\"Check if BDC yielded any distance results.\"\"\"\n        suffix = self._p[self.version]['summary_suffix']\n        for filename in [f for f in os.listdir(self.path_to_bdc)\n                         if f.startswith(source) and f.endswith(suffix)]:\n            with open(os.path.join(self.path_to_bdc, filename), 'r') as fin:\n                result_file_content = fin.readlines()\n        for line in result_file_content:\n            if not line.startswith('!'):\n                return True\n\n        return False\n\n    def determine_e_vel(self, row):\n        \"\"\"Determine uncertainty for vlsr value.\"\"\"\n        e_vel = None\n\n        if self.colnr_e_vel is not None:\n            e_vel = max([row[colnr] for colnr in self.colnr_e_vel])\n            if abs(float(e_vel)) > self.max_e_vel:  # abs(float(vel)):\n                e_vel = None\n\n        if self.version == '1.0':\n            plusminus = ''\n        elif self.version == '2.4':\n            # TODO: implement minimum error for velocity\n            if e_vel is not None:\n                plusminus = '{}\\t'.format(e_vel)\n            else:\n                plusminus = '{}\\t'.format(self.default_e_vel)\n\n        return plusminus\n\n    def determine_p_far_and_kda_ref(self, row, lon, lat, vel):\n        \"\"\"Determine KDA prior and corresponding literature reference.\"\"\"\n        p_far = 0.5\n        kda_ref = None\n\n        if self.colnr_kda is not None:\n            if row[self.colnr_kda] == 'F':\n                p_far = 0.5 + 0.5 * self.kda_weight\n            elif row[self.colnr_kda] == 'N':\n                p_far = 0.5 - 0.5 * self.kda_weight\n            elif isinstance(row[self.colnr_kda], float):\n                warnings.warn(\n                    \"KDA solutions need to be given as strings ('N', 'F')\")\n                p_far = row[self.colnr_kda] * self.kda_weight\n        elif self.check_for_kda_solutions:\n            p_far, kda_ref = self.check_KDA(lon, lat, vel)\n\n        return round(p_far, 2), kda_ref\n\n    def get_expected_vel_disp(self, distance):\n        size = self.beam * distance * 1e3\n        sigma_exp = self._sigma_0 * (size)**(self._indices)\n        return np.mean(sigma_exp), np.std(sigma_exp)\n\n    def normalized_gauss(self, mean, sigma, x):\n        return np.exp(-0.5 * ((x - mean) / sigma)**2)\n\n    def check_limit(self, mean, sigma, vel_disp, prob, limit=0.01):\n        limit_prob = None\n        if prob < limit:\n            if (vel_disp - mean) > 0:\n                limit_prob = 'higher'\n            else:\n                limit_prob = 'lower'\n        return limit_prob\n\n    def determine_pfar_from_vel_disp(self, dist_n, dist_f, vel_disp):\n        sigma_exp_mean, sigma_exp_std = self.get_expected_vel_disp(dist_n)\n        prob_near = self.normalized_gauss(\n            sigma_exp_mean, sigma_exp_std, vel_disp)\n        limit_n = self.check_limit(\n            sigma_exp_mean, sigma_exp_std, vel_disp, prob_near)\n\n        sigma_exp_mean, sigma_exp_std = self.get_expected_vel_disp(dist_f)\n        prob_far = self.normalized_gauss(\n            sigma_exp_mean, sigma_exp_std, vel_disp)\n        limit_f = self.check_limit(\n            sigma_exp_mean, sigma_exp_std, vel_disp, prob_far)\n\n        if (limit_f == 'lower') and (limit_n != 'higher'):\n            pfar = 0\n        else:\n            pfar = (-prob_near + prob_far) * 0.5 + 0.5\n\n        return pfar\n\n    def determine_p_far_from_velocity_dispersion(self, row, lon, lat, vel):\n        dist_n, dist_f = self.kd.calc_kinematic_distance(lon, lat, vel)\n        vel_disp = row[self.colnr_vel_disp]\n        p_far = self.determine_pfar_from_vel_disp(dist_n, dist_f, vel_disp)\n        return round(p_far, 2)\n\n    def determine(self, row, idx):\n        \"\"\"Determine distance of lbv data point via the BDC.\"\"\"\n        row = list(row)\n\n        source = \"SRC{}\".format(str(idx).zfill(9))\n        lon, lat, vel =\\\n            row[self.colnr_lon], row[self.colnr_lat], row[self.colnr_vel]\n\n        name = None\n        if self.colnr_name is not None:\n            name = row[self.colnr_name]\n\n        plusminus = self.determine_e_vel(row)\n        p_far, kda_ref = self.determine_p_far_and_kda_ref(row, lon, lat, vel)\n        condition = ((p_far == 0.5) and\n                     self.prior_velocity_dispersion and\n                     (self.colnr_vel_disp is not None))\n        if condition:\n            p_far = self.determine_p_far_from_velocity_dispersion(\n                row, lon, lat, vel)\n\n        input_string = \"{a}\\t{b}\\t{c}\\t{d}\\t{e}{f}\\t-\\n\".format(\n            a=source, b=lon, c=lat, d=vel, e=plusminus, f=p_far)\n\n        self.run_bdc_script(source, input_string)\n\n        #  rerun BDC calculation with p_far = 0.5 if chosen p_far value did not yield distance results\n        if (self.version == '2.4') and (p_far != 0.5):\n            if not self.bdc_calculation_ok(source):\n                self.delete_all_temporary_files(source)\n\n                p_far = 0.5\n                input_string = \"{a}\\t{b}\\t{c}\\t{d}\\t{e}{f}\\t-\\n\".format(\n                    a=source, b=lon, c=lat, d=vel, e=plusminus, f=p_far)\n                self.run_bdc_script(source, input_string)\n\n        rows = []\n        results = self.get_results(source, kda_ref=kda_ref, name=name)\n        for result in results:\n            rows.append(row + result)\n\n        return rows\n\n    def get_values_from_init_file(self, init_file):\n        \"\"\"Read in values from init file.\"\"\"\n        import ast\n        import configparser\n        config = configparser.ConfigParser()\n        config.read(init_file)\n\n        for key, value in config['DEFAULT'].items():\n            try:\n                setattr(self, '_' + key, ast.literal_eval(value))\n            except ValueError:\n                raise Exception('Could not parse parameter {} from config file'.format(key))\n\n    def gaussian_weight(self, x, std=False):\n        \"\"\"Calculate the Gaussian weight.\n\n        Gaussian function: amp * np.exp(-4. * np.log(2) * (x-mean)**2 / fwhm**2)\n        mean = 0\n\n        Renormalization factor for amplitude, so that Gaussian function is 1 at the fwhm/2; scale = 1 / (np.exp(-np.log(2)) = np.exp(np.log(2)\n        fwhm_factor = 2 * np.sqrt(2 * np.log(2)) = 2.354820045\n        \"\"\"\n        if std:\n            return np.exp((1 - x**2) / 2)  # = np.exp(0.5) * np.exp(-4. * np.log(2) * (x / 2.354820045)**2)\n        else:\n            return np.exp(np.log(2) * (1 - 4. * x**2))  # np.exp(np.log(2)) * np.exp(-4. * np.log(2) * x**2)\n\n    def point_in_ellipse(self, table, lon, lat):\n        \"\"\"Adapted from: https://stackoverflow.com/questions/7946187/\n        See also: https://math.stackexchange.com/questions/426150/\"\"\"\n        cos_pa = table['cos_pa'].data\n        sin_pa = table['sin_pa'].data\n        glon = table['GLON'].data\n        glat = table['GLAT'].data\n        aa = table['aa'].data\n        bb = table['bb'].data\n\n        a = (cos_pa * (lon - glon) + sin_pa * (lat - glat))**2\n        b = (sin_pa * (lon - glon) - cos_pa * (lat - glat))**2\n        epsilon = (a / aa) + (b / bb)\n\n        std = False\n        if self._size == 'std':\n            std = True\n        else:\n            epsilon = epsilon / 4\n\n        weight = self.gaussian_weight(np.sqrt(epsilon), std=std)\n        weight[weight > 1] = 1\n\n        return weight >= self._threshold_spatial, weight\n\n    def get_weight_velocity(self, table, vel):\n        \"\"\"Calculate the weight for the velocity association.\n\n        Parameters\n        ----------\n        table : astropy.table.table.Table\n            Table containing sources with solved kinematic distance ambiguities.\n        vel : float\n            vlsr position of the coordinate.\n\n        Returns\n        -------\n        mask : numpy.ndarray\n            Mask that is true for each weight that exceeds _threshold_spectral.\n        weight : numpy.ndarray\n            Array of the weight values.\n\n        \"\"\"\n        vlsr = table['VLSR'].data.data\n        dvlsr = table['d_VLSR'].data.data\n\n        x = np.abs(vlsr - vel) / dvlsr\n\n        # fwhm_factor = 2.354820045\n        # if fwhm:\n        #     x = np.abs((vlsr - vel) / (dvlsr))\n        # else:\n        #     x = np.abs((vlsr - vel) / (dvlsr)) / (2 * fwhm_factor)\n\n        std = False\n        if self._linewidth == 'std':\n            std = True\n\n        weight = self.gaussian_weight(x, std=std)\n        weight[weight > 1] = 1\n\n        return weight >= self._threshold_spectral, weight\n\n    def get_kda(self, weights_kda, refs):\n        if len(weights_kda) == 0:\n            return 0, '--'\n\n        if len(weights_kda) == 1:\n            return weights_kda[0], refs[0]\n\n        weights_kda_abs = [abs(x) for x in weights_kda]\n        max_weight = max(weights_kda_abs)\n\n        indices = np.argwhere(weights_kda_abs == max_weight).flatten().tolist()\n\n        if len(indices) == 1:\n            i = indices[0]\n            return weights_kda[i], refs[i]\n\n        if sum(weights_kda[indices]) == 0:\n            return 0, '--'\n        else:\n            list_weights_kda = weights_kda[indices].tolist()\n            weight = max(list_weights_kda, key=list_weights_kda.count)\n            i = np.argwhere(weights_kda == weight).flatten()[0]\n            return weight, refs[i]\n\n    def check_KDA(self, lon, lat, vel):\n        weights_kda, refs = np.array([]), []\n        dirname = os.path.dirname(\n            os.path.dirname(os.path.realpath(__file__)))\n\n        for table, tablename in zip(self._kda_tables, self.kda_info_tables):\n            path_to_ini = os.path.join(dirname, 'KDA_info', tablename + '.ini')\n            self.get_values_from_init_file(path_to_ini)\n            mask_pp, weight_pp = self.point_in_ellipse(table, lon, lat)\n            mask_vlsr, weight_vlsr = self.get_weight_velocity(table, vel)\n\n            mask_total = np.logical_and(mask_pp, mask_vlsr)\n            weight_total = weight_pp * weight_vlsr\n            weight_total = weight_total[mask_total]\n            p_far_values = table['p_far'].data\n            p_far_values = p_far_values[mask_total]\n\n            n_values = np.count_nonzero(mask_total)\n            if n_values == 0:\n                continue\n            elif n_values == 1:\n                weights_kda = np.append(\n                    weights_kda, self._weight_cat * p_far_values * weight_total)\n                refs.append(self._reference)\n            else:\n                weights_kda = np.append(weights_kda, self._weight_cat * (np.average(\n                    p_far_values * weight_total, weights=weight_total)))\n                refs.append(self._reference)\n\n        weight_kda, ref = self.get_kda(weights_kda, refs)\n        p_far = 0.5 + weight_kda\n\n        return round(float(p_far), 2), ref\n\n    def get_cartesian_coords(self, lon, lat, dist):\n        from astropy.coordinates import SkyCoord\n        from astropy import units as u\n\n        c = SkyCoord(l=lon*u.degree,\n                     b=lat*u.degree,\n                     distance=dist*u.kpc,\n                     frame='galactic')\n        c.representation_type = 'cartesian'\n        c_u = round(c.u.value, 4)\n        c_v = round(c.v.value, 4)\n        c_w = round(c.w.value, 4)\n\n        return c_u, c_v, c_w\n\n    def calculate_distances(self):\n        self.check_settings()\n        self.say('calculating Bayesian distance...')\n\n        if self.input_table is None:\n            self.input_table = Table.read(\n                self.path_to_input_table, format=self.table_format)\n            #  TESTING:\n            # self.input_table = self.input_table[62000:62001]\n        self.determine_column_indices()\n\n        condition = (self.prior_velocity_dispersion and\n                     (self.colnr_vel_disp is None))\n        if condition:\n            self.colnr_vel_disp = False\n            warnings.warn(str(\"Did not specify 'colnr_vel_disp' or 'colname_vel_disp'. Setting 'prior_velocity_dispersion=False'.\"))\n\n        from . import BD_multiprocessing\n        BD_multiprocessing.init([self, self.input_table])\n        results_list = BD_multiprocessing.func(use_ncpus=self.use_ncpus)\n        print('SUCCESS\\n')\n\n        for i, item in enumerate(results_list):\n            if not isinstance(item, list):\n                self.say(\"Error for distance with index {}: {}\".format(i, item))\n                del results_list[i]\n                continue\n\n        results_list = np.array([item for sublist in results_list\n                                 for item in sublist])\n\n        if self.save_temporary_files:\n            filepath = os.path.join(\n                os.path.dirname(self.path_to_table),\n                '_bdc_results_list.pickle')\n            with open(filepath, 'wb') as p_file:\n                pickle.dump(results_list, p_file)\n\n        self.create_astropy_table(results_list)\n\n    def galactocentric_distance(self, glon, dist_los, glat=None):\n        \"\"\"Calculate galactocentric distance.\n\n        Parameters\n        ----------\n        glon : float [radians]\n            Galactic longitude angle of the line of sight. Has to be supplied in [radians].\n        dist_los : float [kpc]\n            Distance along the line of sight. Has to be supplied in [kpc].\n        glat : float [radians]\n            Galactic latitude angle of the line of sight. Has to be supplied in [radians].\n\n        Returns\n        -------\n        Galactocentric distance in [kpc].\n\n        \"\"\"\n        if glat is not None:\n            dist_los = dist_los * np.cos(glat)\n        R_0 = self._p[self.version]['R_0']\n        return np.sqrt(R_0**2 + dist_los**2 - 2*R_0*dist_los*np.cos(glon))\n\n    def create_astropy_table(self, results):\n        self.say('creating Astropy table...')\n\n        added_colnames = ['comp', 'dist', 'e_dist', 'prob', 'arm',\n                          'c_u', 'c_v', 'c_w', 'p_far']\n\n        dtypeinput_table = []\n        for name, dtype in self.input_table.dtype.descr:\n            dtypeinput_table.append(dtype)\n        added_dtype = ['i4', 'f4', 'f4', 'f4', 'object',\n                       'f4', 'f4', 'f4', 'f4']\n\n        if self.check_for_kda_solutions and (self.colname_kda is None):\n            added_colnames += ['KDA_ref']\n            added_dtype += ['object']\n        if self.add_kinematic_distance:\n            added_colnames += ['kDist_1', 'kDist_2']\n            added_dtype += ['f4', 'f4']\n\n        names = self.input_table.colnames + added_colnames\n        dtype = dtypeinput_table + added_dtype\n\n        self.table_results = Table(data=results, names=names, dtype=dtype)\n\n        if self.add_galactocentric_distance:\n            rgal = self.galactocentric_distance(\n                np.radians(self.table_results[self.colname_lon].data),\n                self.table_results['dist'].data,\n                glat=np.radians(self.table_results[self.colname_lat].data))\n            self.table_results.add_column(Column(data=rgal, name='rgal'))\n\n        for key in ['c_u', 'c_v', 'c_w', 'rgal']:\n            if key in self.table_results.colnames:\n                self.table_results[key].format = \"{0:.3f}\"\n        for key in ['dist', 'e_dist', 'prob', 'p_far', 'kDist_1', 'kDist_2']:\n            if key in self.table_results.colnames:\n                self.table_results[key].format = \"{0:.2f}\"\n\n        self.say(\">> saved table '{}' in {}\\n\".format(\n                 self.table_file, self.dirname_table))\n\n        self.table_results.write(self.path_to_table, format=self.table_format,\n                                 overwrite=True)\n\n    def choose_distance(self, probabilities, distances, dist_errors):\n        \"\"\"Choose distance from alternative solutions.\n\n        Flags for the chosen distance:\n        - 0: only 1 distance solution existed\n        - 1: only distance solution for which associated Gaussian fit had amplitude above three standard deviations of flat distance probability density\n        - 2: distance solution had the highest probability\n        - 3: distance solutions were tied in their probabilites; chosen distance had the lowest distance error\n        - 4: distance solutions were tied in their probabilites and distance errors; chosen distance is the near distance\n\n        fwhm_factor = 2 * np.sqrt(2 * np.log(2)) = 2.354820045\n\n        Calculate the integrated area of the Gaussian function:\n        area_gauss = amp * fwhm / ((1. / np.sqrt(2*np.pi)) * 2*np.sqrt(2*np.log(2)))\n\n        combining all constants yields a factor of 0.93943727869965132\n        \"\"\"\n        if len(probabilities) == 1:\n            return [], 0\n\n        #  check if one of the components had a probability of 1; this implies\n        #  that the remaining components have a probability of zero. This can #  happen as v2.4 of the BDC by default always returns two components\n        if 1 in probabilities:\n            remove = np.where(probabilities != 1)[0]\n            return remove, 0\n\n        #  to get from integrated intensity (= probabilities) and std (= dist_errors) to amplitude\n        amps = probabilities * 0.93943727869965132 / (2.354820045 * dist_errors)\n        remove = np.where(amps < 3 * 0.04)[0]\n        if len(remove) == 1:\n            return remove, 1\n\n        remove = np.where(probabilities == min(probabilities))[0]\n        if len(remove) == 1:\n            return remove, 2\n\n        remove = np.where(dist_errors == max(dist_errors))[0]\n        if len(remove) == 1:\n            return remove, 3\n\n        remove = np.argmax(distances)\n        return remove, 4\n\n    def get_table_distance_max_probability(self, save=True):\n        from tqdm import tqdm\n        self.say('creating Astropy table containing only distance results '\n                 'with the highest probability...')\n\n        remove_rows, choice_flags = np.array([]), np.array([])\n\n        if self.version == '1.0':\n            for idx, component in tqdm(enumerate(self.table_results['comp'])):\n                if idx == 0:\n                    comps_indices = np.array([idx])\n                else:\n                    if (component == 1):\n                        if comps_indices.size > 1:\n                            sort_indices_highest_probability = np.argsort(\n                                self.table_results['prob'][comps_indices])[::-1]\n                            remove = sort_indices_highest_probability[1:]\n                            remove_rows = np.append(remove_rows, comps_indices[remove])\n                        comps_indices = np.array([idx])\n                    else:\n                        comps_indices = np.append(comps_indices, idx)\n\n            #  take care of the last distance results in the list\n            sort_indices_highest_probability = np.argsort(\n                self.table_results['prob'][comps_indices])[::-1]\n            remove = sort_indices_highest_probability[1:]\n            remove_rows = np.append(remove_rows, comps_indices[remove])\n        elif self.version == '2.4':\n            comps_indices = np.array([], dtype='int')\n\n            for idx, component in tqdm(enumerate(self.table_results['comp'])):\n                comps_indices = np.append(comps_indices, idx)\n\n                if len(comps_indices) == component:\n                    remove, flag = self.choose_distance(\n                        self.table_results['prob'][comps_indices],\n                        self.table_results['dist'][comps_indices],\n                        self.table_results['e_dist'][comps_indices]\n                        )\n                    remove_rows = np.append(remove_rows, comps_indices[remove])\n                    choice_flags = np.append(choice_flags, flag)\n                    comps_indices = np.array([], dtype='int')\n\n        remove_rows = remove_rows.astype(int)\n        self.table_results.remove_rows(remove_rows)\n\n        if self.version == '2.4':\n            self.table_results.add_column(\n                Column(data=choice_flags, name='flag', dtype='int'))\n\n        if save:\n            self.table_file = '{}{}{}'.format(self.table_filename, '_p_max',\n                                              self.table_file_extension)\n            self.path_to_table = os.path.join(\n                self.dirname_table, self.table_file)\n\n            self.say(\">> saved table '{}' in {}\".format(\n                     self.table_file, self.dirname_table))\n\n            self.table_results.write(self.path_to_table,\n                                     format=self.table_format,\n                                     overwrite=True)\n\n    def find_index_max_probability(self, indices, arm=False):\n        idx = [i for i in indices]\n        prob = [self.table['prob'][i] for i in indices]\n        max_idx = prob.index(max(prob))\n\n        if arm:\n            arms = [self.table['arm'][i] for i in indices]\n            return idx[max_idx], arms[max_idx]\n        else:\n            return idx[max_idx]\n\n    def order_distances(self, results):\n        indices = list(range(len(results)))\n\n        distances = np.array([float(result[1]) for result in results])\n        dist_errors = np.array([float(result[2]) for result in results])\n        probabilities = np.array([float(result[3]) for result in results])\n\n        remove, _ = self.choose_distance(probabilities, distances, dist_errors)\n\n        first_choice = [i for i in indices if i not in remove]\n        choices = first_choice + remove.tolist()\n        results = [results[i] for i in choices]\n        return results\n\n    def plot_probability_density(self, source, results, input_file_content,\n                                 name=None):\n        import matplotlib.pyplot as plt\n\n        def get_maximum_distance(distance, probability, max_dist=None):\n            try:\n                prob_threshold = 0.05\n                distance_cutoff = distance[probability > prob_threshold][-1]\n                return max(max_dist, int(distance_cutoff + 1))\n            except IndexError:\n                return max_dist\n\n        distKD, probKD = np.loadtxt(\n            os.path.join(self.path_to_bdc, '{}_kinematic_distance_pdf.dat'.format(source)),\n            usecols=(0, 1), skiprows=2, unpack=True)\n\n        if self.version == '1.0':\n            distGL, probGL = np.loadtxt(\n                os.path.join(self.path_to_bdc, '{}_latitude_pdf.dat'.format(source)),\n                usecols=(0, 1), skiprows=2, unpack=True)\n\n            distSA, probSA = np.loadtxt(\n                os.path.join(self.path_to_bdc, '{}_spiral_arm_pdf.dat'.format(source)),\n                usecols=(0, 1), skiprows=2, unpack=True)\n        elif self.version == '2.4':\n            distSA, probSA = np.loadtxt(\n                os.path.join(self.path_to_bdc, '{}_arm_latitude_pdf.dat'.format(source)),\n                usecols=(0, 1), skiprows=2, unpack=True)\n\n            distGL, probGL = distSA, probSA\n\n        arm_ranges_lower, arm_ranges_upper = np.loadtxt(\n            os.path.join(self.path_to_bdc, '{}_arm_ranges.dat'.format(source)),\n            usecols=(0, 1), skiprows=2, unpack=True)\n\n        spiral_arms = np.genfromtxt(\n            os.path.join(self.path_to_bdc, '{}_arm_ranges.dat'.format(source)),\n            skip_header=2, usecols=2, dtype='str')\n\n        skip_spiral_arm_ranges = False\n        if spiral_arms.size == 2:\n            arm_ranges_lower = [arm_ranges_lower[1]]\n            arm_ranges_upper = [arm_ranges_upper[1]]\n            spiral_arms = [spiral_arms[1]]\n        elif spiral_arms.size > 2:\n            arm_ranges_lower = arm_ranges_lower[1:]\n            arm_ranges_upper = arm_ranges_upper[1:]\n            spiral_arms = spiral_arms[1:]\n        else:\n            skip_spiral_arm_ranges = True\n\n        distPS, probPS = np.loadtxt(\n            os.path.join(self.path_to_bdc, '{}_parallaxes_pdf.dat'.format(source)),\n            usecols=(0, 1), skiprows=2, unpack=True)\n\n        distFD, probFD = np.loadtxt(\n            os.path.join(self.path_to_bdc, '{}_final_distance_pdf.dat'.format(source)),\n            usecols=(0, 1), skiprows=2, unpack=True)\n\n        max_dist = 0\n        for dist, prob in zip(\n                [distKD, distGL, distSA, distPS], [probKD, probGL, probSA, probPS]):\n            max_dist = get_maximum_distance(dist, prob, max_dist=max_dist)\n\n        fig = plt.figure(figsize=(10, 7.5))\n        ax = fig.add_subplot(1, 1, 1)\n\n        ax.set_xlabel('Distance [kpc]', size=20)\n        ax.set_ylabel('Probability density [kpc$^{-1}$]', size=20)\n\n        ax.tick_params(axis='both', labelsize=16, pad=8)\n        ax.tick_params(axis='both', which='major', direction='out',\n                       width=1.25, length=10, pad=8)\n        ax.tick_params(axis='both', which='minor', direction='out',\n                       width=1.25, length=5)\n\n        ax.plot(distKD, probKD, label='KD', lw=2.5, ls='solid', c='dodgerblue', alpha=0.75)\n        ax.plot(distGL, probGL, label='GL', lw=2.5, ls='dotted', c='orange', alpha=1.0)\n        ax.plot(distSA, probSA, label='SA', lw=2.5, ls='--', c='indianred', alpha=1.0)\n        ax.plot(distPS, probPS, label='PS', lw=2.5, ls='-.', c='forestgreen', alpha=1.0)\n        ax.plot(distFD, probFD, label='combined', lw=2, ls='solid', c='black', alpha=1.0)\n\n        if not skip_spiral_arm_ranges:\n            for lower, upper, text in zip(\n                    arm_ranges_lower, arm_ranges_upper, spiral_arms):\n                if lower > max_dist:\n                    continue\n                horizontalalignment = 'center'\n                if text == 'AqR':\n                    horizontalalignment = 'left'\n                ax.axvspan(lower, upper, alpha=0.15, color='indianred')\n                ax.text((upper + lower)/2, ax.get_ylim()[1] * 0.99, text, size=14, color='indianred', horizontalalignment=horizontalalignment, verticalalignment='top')\n\n        box = ax.get_position()\n        ax.set_position([box.x0, box.y0,\n                         box.width, box.height * 0.9])\n        # Put a legend below current axis\n        leg1 = ax.legend(\n            loc='upper center', bbox_to_anchor=(0.5, 1.08),\n            fancybox=False, shadow=False, ncol=5,\n            fontsize=14, numpoints=1, frameon=0)\n\n        markers, texts = [], []\n\n        if self.version == '2.4':\n            results = self.order_distances(results)\n        for i, result in enumerate(results):\n            dist = float(result[1])\n            if dist <= 0:\n                continue\n            e_dist = float(result[2])\n            prob = float(result[3])\n            index = 'D$_{{\\\\mathregular{{{}}}}}$'.format(i + 1)\n            text = '{a}={b:.1f}$\\\\pm${c:.1f} kpc ({d:.0%})'.format(\n                a=index, b=dist, c=e_dist, d=prob)\n            marker = ax.scatter(dist, 0 - i*0.01)\n            markers.append(marker)\n            texts.append(text)\n            ax.errorbar(dist, 0 - i*0.01, xerr=e_dist)\n\n        leg2 = ax.legend(\n            markers, texts,\n            loc='upper center', bbox_to_anchor=(0.5, 1.135),\n            fancybox=False, shadow=False, ncol=len(results),\n            fontsize=14, numpoints=1, frameon=0)\n\n        for line in input_file_content:\n            if line.startswith('!'):\n                continue\n            params = line.split()\n            glon, glat, vlsr, e_vlsr, p_far = params[1:6]\n            break\n\n        text = str('$\\\\ell$={} deg, $b$={} deg, '\n                   'V$_{{\\\\mathregular{{LSR}}}}$={} $\\\\pm$ {} km/s, '\n                   'P$_{{\\\\mathregular{{far}}}}$={}'. format(\n                       glon, glat, vlsr, e_vlsr, p_far))\n        plt.title(text, fontsize=14, pad=50)\n\n        ax.set_xlim([0, max_dist])\n\n        ax.add_artist(leg1)\n\n        if name is not None:\n            source = name\n\n        path_to_file = os.path.join(self.dirname_table, source + '.pdf')\n        plt.savefig(path_to_file, bbox_inches='tight')\n        plt.close()\n", "meta": {"hexsha": "7a025a4bb7916bb978c1eb385bc9bc0f1f46bd8e", "size": 44641, "ext": "py", "lang": "Python", "max_stars_repo_path": "BD_wrapper/BD_wrapper.py", "max_stars_repo_name": "mriener/BD_wrapper", "max_stars_repo_head_hexsha": "e61a27c67420359db557329457fff586700d8001", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-29T11:35:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-29T11:35:21.000Z", "max_issues_repo_path": "BD_wrapper/BD_wrapper.py", "max_issues_repo_name": "mriener/BD_wrapper", "max_issues_repo_head_hexsha": "e61a27c67420359db557329457fff586700d8001", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BD_wrapper/BD_wrapper.py", "max_forks_repo_name": "mriener/BD_wrapper", "max_forks_repo_head_hexsha": "e61a27c67420359db557329457fff586700d8001", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-09T00:37:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-09T00:37:19.000Z", "avg_line_length": 39.4355123675, "max_line_length": 167, "alphanum_fraction": 0.5703277256, "include": true, "reason": "import numpy,from astropy", "num_tokens": 10532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.19810701837912792}}
{"text": "__copyright__ = \"\"\"\nCopyright (C) 2020 Xiaoyu Wei\n\"\"\"\n\n__license__ = \"\"\"\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\n\nimport itertools\nimport numpy as np\nimport pyopencl as cl\nimport loopy as lp\nfrom pytools import memoize_method, ProcessLogger\nfrom pytools.obj_array import make_obj_array\nfrom boxtree.tools import DeviceDataRecord\nfrom meshmode.array_context import PyOpenCLArrayContext\nfrom meshmode.dof_array import unflatten, flatten, thaw\nfrom volumential.volume_fmm import interpolate_volume_potential\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\n__doc__ = r\"\"\"\n.. currentmodule:: volumential\n\nFrom :mod:`meshmode`\n-------------------------\n\nInterpolation from functions given by DoF vectors of :mod:`meshmode`.\nThe underlying mesh on the :mod:`meshmode` side must be discretizing the\nsame bounding box.\n\nThe intersection testing assumes a boundedness property for the supported\nelement types: each element is bounded inside the smallest :math:`l^\\infty`\nball that is centered at the element's center and covers all its vertices.\nThis property might be broken, for example, by high order elements that\nwarp the element boundary too much.\n\n.. autoclass:: ElementsToSourcesLookup\n\n.. autoclass:: LeavesToNodesLookup\n\n.. autofunction:: interpolate_from_meshmode\n\nTo :mod:`meshmode`\n---------------------------\n\n\"\"\"\n\n\n# {{{ output\n\nclass ElementsToSourcesLookup(DeviceDataRecord):\n    \"\"\"\n    .. attribute:: tree\n\n        The :class:`boxtree.Tree` instance representing the box mesh.\n\n    .. attribute:: discr\n\n        The :class:`meshmode.discretization.Discretization` instance\n        representing the external mesh and DoF distribution.\n\n    .. attribute:: sources_in_element_starts\n\n        Indices into :attr:`sources_in_element_lists`.\n\n        .. code-block:: python\n\n            sources_in_element_lists[\n                sources_in_element_starts[global_iel]\n                :sources_in_element_starts[global_iel] + 1\n                ]\n\n        contains the list of source nodes residing in the given element.\n\n        .. note:: ``global_iel`` is the global element id in `meshmode`.\n            ``global_iel = mesh.groups[igrp].element_nr_base + iel``.\n\n    .. attribute:: sources_in_element_lists\n\n        Indices into :attr:`tree.sources`.\n\n    .. automethod:: get\n    \"\"\"\n\n\nclass LeavesToNodesLookup(DeviceDataRecord):\n    \"\"\"\n    .. attribute:: trav\n\n        The :class:`boxtree.FMMTraversalInfo` instance representing the\n        box mesh with metadata needed for interpolation. It contains a\n        reference to the underlying tree as `trav.tree`.\n\n    .. attribute:: discr\n\n        The :class:`meshmode.discretization.Discretization` instance\n        representing the external mesh and DoF distribution.\n\n    .. attribute:: nodes_in_leaf_starts\n\n        Indices into :attr:`nodes_in_leaf_lists`.\n\n        .. code-block:: python\n\n            nodes_in_leaf_lists[\n                nodes_in_leaf_starts[box_id]:nodes_in_leaf_starts[box_id] + 1]\n\n        contains the list of discretization nodes residing in the given leaf box.\n\n        .. note:: Only leaf boxes have non-empty entries in this table.\n            Nonetheless, this list is indexed by the global box index.\n\n    .. attribute:: nodes_in_leaf_lists\n\n        Indices into :attr:`discr.nodes()`.\n\n        .. note:: Unlike :class:`ElementsToSourcesLookup`, lists are not disjoint\n            in the leaves-to-nodes lookup. :mod:`volumential` automatically computes\n            the average contribution from overlapping boxes.\n\n    .. automethod:: get\n    \"\"\"\n\n# }}} End output\n\n\n# {{{ elements-to-sources lookup builder\n\nclass ElementsToSourcesLookupBuilder:\n    \"\"\"Given a :mod:`meshmod` mesh and a :mod:`boxtree.Tree`, both discretizing\n    the same bounding box, this class helps to build a look-up table from\n    element to source nodes that are positioned inside the element.\n    \"\"\"\n\n    def __init__(self, context, tree, discr):\n        \"\"\"\n        :arg tree: a :class:`boxtree.Tree`\n        :arg discr: a :class: `meshmode.discretization.Discretization`\n\n        Boxes and elements can be non-aligned as long as the domains\n        (bounding boxes) are the same.\n        \"\"\"\n        assert tree.dimensions == discr.dim\n        self.dim = discr.dim\n        self.context = context\n        self.tree = tree\n        self.discr = discr\n\n        from pyopencl.algorithm import KeyValueSorter\n        self.key_value_sorter = KeyValueSorter(context)\n\n        from boxtree.area_query import AreaQueryBuilder\n        self.area_query_builder = AreaQueryBuilder(self.context)\n\n    # {{{ kernel generation\n\n    @memoize_method\n    def codegen_get_dimension_specific_snippets(self):\n        \"\"\"Dimension-dependent code loopy instructions.\n        \"\"\"\n        import sympy as sp\n        axis_names = [\"x\", \"y\", \"z\"]\n        axis_names = axis_names[:self.dim]\n\n        # tolerance\n        tol = -1e-12\n\n        def make_sympy_vec(comp_names):\n            comps = []\n            for cn in comp_names:\n                comps.append(sp.var(cn))\n            return sp.Matrix(comps)\n\n        def get_simplex_measure(vtx_names):\n            mat0 = sp.ones(self.dim + 1)\n            for iv, v in enumerate(vtx_names):\n                vtx = sp.Matrix([sp.var(f\"{v}{comp}\") for comp in axis_names])\n                mat0[iv, :-1] = vtx.T\n            return str(mat0.det())\n\n        if self.dim == 2:\n\n            # {{{ 2d\n\n            code_get_simplex = \\\n                \"\"\"\n                <> Ax = mesh_vertices_0[mesh_vertex_indices[iel, 0]]\n                <> Ay = mesh_vertices_1[mesh_vertex_indices[iel, 0]]\n                <> Bx = mesh_vertices_0[mesh_vertex_indices[iel, 1]]\n                <> By = mesh_vertices_1[mesh_vertex_indices[iel, 1]]\n                <> Cx = mesh_vertices_0[mesh_vertex_indices[iel, 2]]\n                <> Cy = mesh_vertices_1[mesh_vertex_indices[iel, 2]]\n                \"\"\"\n            code_get_point = \\\n                \"\"\"\n                <> Px = source_points_0[source_id]\n                <> Py = source_points_1[source_id]\n                \"\"\"\n            # simplex measures\n            code_s0 = get_simplex_measure([\"P\", \"B\", \"C\"])\n            code_s1 = get_simplex_measure([\"A\", \"P\", \"C\"])\n            code_s2 = get_simplex_measure([\"A\", \"B\", \"P\"])\n            code_compute_simplex_measures = \\\n                f\"\"\"\n                <> s0 = {code_s0}\n                <> s1 = {code_s1}\n                <> s2 = {code_s2}\n                \"\"\"\n            code_measures_have_common_sign = \" and \".join([\n                f\"s{c1} * s{c2} >= {tol}\"\n                for c1, c2 in itertools.combinations([\"0\", \"1\"], 2)])\n\n            # }}} End 2d\n\n        elif self.dim == 3:\n\n            # {{{ 3d\n\n            code_get_simplex = \\\n                \"\"\"\n                <> Ax = mesh_vertices_0[mesh_vertex_indices[iel, 0]]\n                <> Ay = mesh_vertices_1[mesh_vertex_indices[iel, 0]]\n                <> Az = mesh_vertices_2[mesh_vertex_indices[iel, 0]]\n                <> Bx = mesh_vertices_0[mesh_vertex_indices[iel, 1]]\n                <> By = mesh_vertices_1[mesh_vertex_indices[iel, 1]]\n                <> Bz = mesh_vertices_2[mesh_vertex_indices[iel, 1]]\n                <> Cx = mesh_vertices_0[mesh_vertex_indices[iel, 2]]\n                <> Cy = mesh_vertices_1[mesh_vertex_indices[iel, 2]]\n                <> Cz = mesh_vertices_2[mesh_vertex_indices[iel, 2]]\n                <> Dx = mesh_vertices_0[mesh_vertex_indices[iel, 3]]\n                <> Dy = mesh_vertices_1[mesh_vertex_indices[iel, 3]]\n                <> Dz = mesh_vertices_2[mesh_vertex_indices[iel, 3]]\n                \"\"\"\n            code_get_point = \\\n                \"\"\"\n                <> Px = source_points_0[source_id]\n                <> Py = source_points_1[source_id]\n                <> Pz = source_points_2[source_id]\n                \"\"\"\n            # simplex measures\n            code_s0 = get_simplex_measure([\"P\", \"B\", \"C\", \"D\"])\n            code_s1 = get_simplex_measure([\"A\", \"P\", \"C\", \"D\"])\n            code_s2 = get_simplex_measure([\"A\", \"B\", \"P\", \"D\"])\n            code_s3 = get_simplex_measure([\"A\", \"B\", \"C\", \"P\"])\n            code_compute_simplex_measures = \\\n                f\"\"\"\n                <> s0 = {code_s0}\n                <> s1 = {code_s1}\n                <> s2 = {code_s2}\n                <> s3 = {code_s3}\n                \"\"\"\n            code_measures_have_common_sign = \" and \".join([\n                f\"s{c1} * s{c2} >= {tol}\"\n                for c1, c2 in itertools.combinations([\"0\", \"1\", \"2\"], 2)])\n\n            # }}} End 3d\n\n        else:\n            raise NotImplementedError()\n\n        return {\"code_get_simplex\": code_get_simplex,\n                \"code_get_point\": code_get_point,\n                \"code_compute_simplex_measures\": code_compute_simplex_measures,\n                \"code_measures_have_common_sign\": code_measures_have_common_sign,\n                }\n\n    @memoize_method\n    def get_simplex_lookup_kernel(self):\n        \"\"\"Returns a loopy kernel that computes a potential vector\n        representing the (q_point --> element_id) relationship.\n        When a source q_point lies on the element boundary, it will be\n        assigned an element depending on code scheduling. This ensures\n        that the resulting lookup lists are disjoint.\n\n        The kernel assumes that the mesh uses one single group of simplex elements.\n        Also, the test only works for affine elements.\n        \"\"\"\n        logger.debug(\"start building elements-to-sources lookup kernel\")\n\n        snippets = self.codegen_get_dimension_specific_snippets()\n        loopy_knl = lp.make_kernel(\n            [\"{ [ iel ]: 0 <= iel < nelements }\",\n             \"{ [ ineighbor ]: nearby_leaves_beg <= ineighbor < nearby_leaves_end }\",\n             \"{ [ isrc ]: 0 <= isrc < n_box_sources }\"\n             ],\n            [\"\"\"\n            for iel\n                <> nearby_leaves_beg = leaves_near_ball_starts[iel]\n                <> nearby_leaves_end = leaves_near_ball_starts[iel + 1]\n\n                {code_get_simplex}\n\n                for ineighbor\n                    <> ileaf = leaves_near_ball_lists[ineighbor]\n                    <> box_source_beg = box_source_starts[ileaf]\n                    <> n_box_sources = box_source_counts_cumul[ileaf]\n\n                    for isrc\n                        <> source_id = box_source_beg + isrc\n\n                        {code_get_point}\n                        {code_compute_simplex_measures}\n\n                        result[source_id] = if(\n                            {code_measures_have_common_sign},\n                            iel,\n                            result[source_id])  {{atomic}}\n                    end\n                end\n            end\n            \"\"\".format(**snippets)],\n            [lp.ValueArg(\"nelements, dim, nboxes, nsources\", np.int32),\n             lp.GlobalArg(\"mesh_vertex_indices\", np.int32, \"nelements, dim+1\"),\n             lp.GlobalArg(\"box_source_starts\", np.int32, \"nboxes\"),\n             lp.GlobalArg(\"box_source_counts_cumul\", np.int32, \"nboxes\"),\n             lp.GlobalArg(\"leaves_near_ball_lists\", np.int32, None),\n             lp.GlobalArg(\"result\", np.int32, \"nsources\", for_atomic=True),\n             \"...\"],\n            name=\"build_sources_in_simplex_lookup\",\n            lang_version=(2018, 2),\n        )\n\n        logger.debug(\"done building elements-to-sources lookup kernel\")\n        return loopy_knl\n\n    # }}} End kernel generation\n\n    def compute_short_lists(self, actx, wait_for=None):\n        \"\"\"balls --> overlapping leaves\n        \"\"\"\n        if not isinstance(actx, PyOpenCLArrayContext):\n            if isinstance(actx, cl.CommandQueue):\n                from warnings import warn\n                warn(\"Command queue passed to the interpolator. \"\n                     \"Supply an array context to enable proper caching.\")\n                actx = PyOpenCLArrayContext(actx)\n            else:\n                raise ValueError\n\n        mesh = self.discr.mesh\n        if len(mesh.groups) > 1:\n            raise NotImplementedError(\"Mixed elements not supported\")\n        melgrp = mesh.groups[0]\n        ball_centers_host = (np.max(melgrp.nodes, axis=2)\n                             + np.min(melgrp.nodes, axis=2)) / 2\n        ball_radii_host = np.max(\n                np.max(melgrp.nodes, axis=2) - np.min(melgrp.nodes, axis=2),\n                axis=0) / 2\n\n        ball_centers = make_obj_array([\n            cl.array.to_device(actx.queue, center_coord_comp)\n            for center_coord_comp in ball_centers_host])\n        ball_radii = cl.array.to_device(actx.queue, ball_radii_host)\n\n        area_query_result, evt = self.area_query_builder(\n            actx.queue, self.tree, ball_centers, ball_radii,\n            peer_lists=None, wait_for=wait_for)\n        return area_query_result, evt\n\n    def __call__(self, actx, balls_to_leaves_lookup=None, wait_for=None):\n        \"\"\"\n        :arg queue: a :class:`pyopencl.CommandQueue`\n        \"\"\"\n        if not isinstance(actx, PyOpenCLArrayContext):\n            if isinstance(actx, cl.CommandQueue):\n                from warnings import warn\n                warn(\"Command queue passed to the interpolator. \"\n                     \"Supply an array context to enable proper caching.\")\n                actx = PyOpenCLArrayContext(actx)\n            else:\n                raise ValueError\n\n        slk_plog = ProcessLogger(logger, \"element-to-source lookup: run area query\")\n\n        if balls_to_leaves_lookup is None:\n            balls_to_leaves_lookup, evt = \\\n                self.compute_short_lists(actx.queue, wait_for=wait_for)\n            wait_for = [evt]\n\n        # -----------------------------------------------------------------\n        # Refine the area query using point-in-simplex test\n\n        logger.debug(\"element-to-source lookup: refine starts\")\n\n        element_lookup_kernel = self.get_simplex_lookup_kernel()\n\n        vertices_dev = make_obj_array([\n            cl.array.to_device(actx.queue, verts)\n            for verts in self.discr.mesh.vertices])\n\n        mesh_vertices_kwargs = {\n            f\"mesh_vertices_{iaxis}\": vertices_dev[iaxis]\n            for iaxis in range(self.dim)}\n\n        source_points_kwargs = {\n            f\"source_points_{iaxis}\": self.tree.sources[iaxis]\n            for iaxis in range(self.dim)}\n\n        evt, res = element_lookup_kernel(\n            actx.queue, dim=self.dim, nboxes=self.tree.nboxes,\n            nelements=self.discr.mesh.nelements, nsources=self.tree.nsources,\n            result=cl.array.zeros(actx.queue,\n                                  self.tree.nsources, dtype=np.int32) - 1,\n            mesh_vertex_indices=self.discr.mesh.groups[0].vertex_indices,\n            box_source_starts=self.tree.box_source_starts,\n            box_source_counts_cumul=self.tree.box_source_counts_cumul,\n            leaves_near_ball_starts=balls_to_leaves_lookup.leaves_near_ball_starts,\n            leaves_near_ball_lists=balls_to_leaves_lookup.leaves_near_ball_lists,\n            wait_for=wait_for, **mesh_vertices_kwargs, **source_points_kwargs)\n\n        source_to_element_lookup, = res\n\n        wait_for = [evt]\n\n        # elements = source_to_element_lookup.get()\n        # for idx in [362,  365,  874,  877, 1386, 1389, 1898, 1901])\n\n        # -----------------------------------------------------------------\n        # Invert the source-to-element lookup by a key-value sort\n\n        logger.debug(\"element-to-source lookup: key-value sort\")\n\n        sources_in_element_starts, sources_in_element_lists, evt = \\\n            self.key_value_sorter(\n                actx.queue,\n                keys=source_to_element_lookup,\n                values=cl.array.arange(\n                    actx.queue, self.tree.nsources, dtype=self.tree.box_id_dtype),\n                nkeys=self.discr.mesh.nelements,\n                starts_dtype=self.tree.box_id_dtype,\n                wait_for=wait_for)\n\n        slk_plog.done()\n\n        return ElementsToSourcesLookup(\n            tree=self.tree, discr=self.discr,\n            sources_in_element_starts=sources_in_element_starts,\n            sources_in_element_lists=sources_in_element_lists), evt\n\n# }}} End elements-to-sources lookup builder\n\n\n# {{{ leaves-to-nodes lookup builder\n\nclass LeavesToNodesLookupBuilder:\n    \"\"\"Given a :mod:`meshmod` mesh and a :mod:`boxtree.Tree`, both discretizing\n    the same bounding box, this class helps to build a look-up table from\n    leaf boxes to mesh nodes that are positioned inside the box.\n    \"\"\"\n\n    def __init__(self, context, trav, discr):\n        \"\"\"\n        :arg trav: a :class:`boxtree.FMMTraversalInfo`\n        :arg discr: a :class: `meshmode.discretization.Discretization`\n\n        Boxes and elements can be non-aligned as long as the domains\n        (bounding boxes) are the same.\n        \"\"\"\n        assert trav.tree.dimensions == discr.dim\n        self.dim = discr.dim\n        self.context = context\n        self.trav = trav\n        self.discr = discr\n\n        from boxtree.area_query import LeavesToBallsLookupBuilder\n        self.leaves_to_balls_lookup_builder = \\\n            LeavesToBallsLookupBuilder(self.context)\n\n    def __call__(self, actx, tol=1e-12, wait_for=None):\n        \"\"\"\n        :arg queue: a :class:`pyopencl.CommandQueue`\n        :tol: nodes close enough to the boundary will be treated as\n            lying on the boundary, whose interpolated values are averaged.\n        \"\"\"\n        if not isinstance(actx, PyOpenCLArrayContext):\n            if isinstance(actx, cl.CommandQueue):\n                from warnings import warn\n                warn(\"Command queue passed to the interpolator. \"\n                     \"Supply an array context to enable proper caching.\")\n                actx = PyOpenCLArrayContext(actx)\n            else:\n                raise ValueError\n\n        nodes = flatten(thaw(actx, self.discr.nodes()))\n        radii = cl.array.zeros_like(nodes[0]) + tol\n\n        lbl_lookup, evt = self.leaves_to_balls_lookup_builder(\n            actx.queue, self.trav.tree, nodes, radii, wait_for=wait_for)\n\n        return LeavesToNodesLookup(\n            trav=self.trav, discr=self.discr,\n            nodes_in_leaf_starts=lbl_lookup.balls_near_box_starts,\n            nodes_in_leaf_lists=lbl_lookup.balls_near_box_lists), evt\n\n# }}} End leaves-to-nodes lookup builder\n\n\n# {{{ transform helper\n\ndef compute_affine_transform(source_simplex, target_simplex):\n    \"\"\"Computes A and b for the affine transform :math:`y = A x + b`\n    that maps ``source_simplex`` to ``target_simplex``.\n\n    :param source_simplex: a dim-by-(dim+1) :mod:`numpy` array\n    :param target_simplex: a dim-by-(dim+1) :mod:`numpy: array\n    \"\"\"\n    assert source_simplex.shape == target_simplex.shape\n    dim = source_simplex.shape[0]\n\n    if dim == 2:\n        assert source_simplex.shape == (2, 3)\n        mat = np.zeros([6, 6])\n        mat[:3, :2] = source_simplex.T\n        mat[-3:, 2:4] = source_simplex.T\n        mat[:3, -2] = 1\n        mat[-3:, -1] = 1\n        rhs = target_simplex.reshape(-1)\n        solu = np.linalg.solve(mat, rhs)\n        return solu[:4].reshape(2, 2), solu[-2:]\n\n    elif dim == 3:\n        assert source_simplex.shape == (3, 4)\n        mat = np.zeros([12, 12])\n        mat[:4, :3] = source_simplex.T\n        mat[4:8, 3:6] = source_simplex.T\n        mat[-4:, 6:9] = source_simplex.T\n        mat[:4, -3] = 1\n        mat[4:8, -2] = 1\n        mat[-4:, -1] = 1\n        rhs = target_simplex.reshape(-1)\n        solu = np.linalg.solve(mat, rhs)\n        return solu[:9].reshape(3, 3), solu[-3:]\n\n    else:\n        raise NotImplementedError()\n\n\ndef invert_affine_transform(mat_a, disp_b):\n    \"\"\"Inverts an affine transform given by :math:`y = A x + b`.\n\n    :param mat_A: a dim*(dim+1)-by-dim*(dim+1) :mod:`numpy` array\n    :param disp_b: a dim*(dim+1) :mod:`numpy` array\n    \"\"\"\n    iva = np.linalg.inv(mat_a)\n    ivb = - iva @ disp_b\n    return iva, ivb\n\n# }}} End transform helper\n\n\n# {{{ from meshmode interpolation\n\ndef interpolate_from_meshmode(actx, dof_vec, elements_to_sources_lookup,\n                              order=\"tree\"):\n    \"\"\"Interpolate a DoF vector from :mod:`meshmode`.\n\n    :arg dof_vec: a DoF vector representing a field in :mod:`meshmode`\n        of shape ``(..., nnodes)``.\n    :arg elements_to_sources_lookup: a :class:`ElementsToSourcesLookup`.\n    :arg order: order of the output potential, either \"tree\" or \"user\".\n\n    .. note:: This function currently supports meshes with just one element\n        group. Also, the element group must be simplex-based.\n\n    .. note:: This function does some heavy-lifting computation in Python,\n        which we intend to optimize in the future. In particular, we plan\n        to shift the batched linear solves and basis evaluations to\n        :mod:`loopy`.\n\n    TODO: make linear solvers available as :mod:`loopy` callables.\n    TODO: make :mod:`modepy` emit :mod:`loopy` callables for basis evaluation.\n    \"\"\"\n    if not isinstance(dof_vec, cl.array.Array):\n        raise TypeError(\"non-array passed to interpolator\")\n\n    if not isinstance(actx, PyOpenCLArrayContext):\n        if isinstance(actx, cl.CommandQueue):\n            from warnings import warn\n            warn(\"Command queue passed to the interpolator. \"\n                 \"Supply an array context to enable proper caching.\")\n            actx = PyOpenCLArrayContext(actx)\n        else:\n            raise ValueError\n\n    assert len(elements_to_sources_lookup.discr.groups) == 1\n    assert len(elements_to_sources_lookup.discr.mesh.groups) == 1\n    degroup = elements_to_sources_lookup.discr.groups[0]\n    megroup = elements_to_sources_lookup.discr.mesh.groups[0]\n\n    if not degroup.is_affine:\n        raise ValueError(\n            \"interpolation requires global-to-local map, \"\n            \"which is only available for affinely mapped elements\")\n\n    mesh = elements_to_sources_lookup.discr.mesh\n    dim = elements_to_sources_lookup.discr.dim\n    template_simplex = mesh.groups[0].vertex_unit_coordinates().T\n\n    # -------------------------------------------------------\n    # Inversely map source points with a global-to-local map.\n    #\n    # 1. For each element, solve for the affine map.\n    #\n    # 2. Apply the map to corresponding source points.\n    #\n    # This step computes `unit_sources`, the list of inversely\n    # mapped source points.\n\n    sources_in_element_starts = \\\n        elements_to_sources_lookup.sources_in_element_starts.get(actx.queue)\n    sources_in_element_lists = \\\n        elements_to_sources_lookup.sources_in_element_lists.get(actx.queue)\n    tree = elements_to_sources_lookup.tree.get(actx.queue)\n\n    unit_sources_host = make_obj_array(\n            [np.zeros_like(srccrd) for srccrd in tree.sources])\n\n    for iel in range(degroup.nelements):\n        vertex_ids = megroup.vertex_indices[iel]\n        vertices = mesh.vertices[:, vertex_ids]\n        afa, afb = compute_affine_transform(vertices, template_simplex)\n\n        beg = sources_in_element_starts[iel]\n        end = sources_in_element_starts[iel + 1]\n        source_ids_in_el = sources_in_element_lists[beg:end]\n        sources_in_el = np.vstack(\n            [tree.sources[iaxis][source_ids_in_el] for iaxis in range(dim)])\n\n        ivmapped_el_sources = afa @ sources_in_el + afb.reshape([dim, 1])\n        for iaxis in range(dim):\n            unit_sources_host[iaxis][source_ids_in_el] = \\\n                ivmapped_el_sources[iaxis, :]\n\n    unit_sources = make_obj_array(\n        [cl.array.to_device(actx.queue, usc) for usc in unit_sources_host])\n\n    # -----------------------------------------------------\n    # Carry out evaluations in the local (template) frames.\n    #\n    # 1. Assemble a resampling matrix for each element, with\n    #    the basis functions and the local source points.\n    #\n    # 2. For each element, perform matvec on the resampling\n    #    matrix and the local DoF coefficients.\n    #\n    # This step assumes `unit_sources` computed on device, so\n    # that the previous step can be swapped with a kernel without\n    # interrupting the followed computation.\n\n    mapped_sources = np.vstack(\n        [usc.get(actx.queue) for usc in unit_sources])\n\n    basis_funcs = degroup.basis()\n\n    dof_vec_view = unflatten(\n            actx, elements_to_sources_lookup.discr, dof_vec)[0]\n    dof_vec_view = dof_vec_view.get()\n\n    sym_shape = dof_vec.shape[:-1]\n    source_vec = np.zeros(sym_shape + (tree.nsources, ))\n\n    for iel in range(degroup.nelements):\n        beg = sources_in_element_starts[iel]\n        end = sources_in_element_starts[iel + 1]\n        source_ids_in_el = sources_in_element_lists[beg:end]\n        mapped_sources_in_el = mapped_sources[:, source_ids_in_el]\n        local_dof_vec = dof_vec_view[..., iel, :]\n\n        # resampling matrix built from Vandermonde matrices\n        import modepy as mp\n        rsplm = mp.resampling_matrix(\n                basis=basis_funcs,\n                new_nodes=mapped_sources_in_el,\n                old_nodes=degroup.unit_nodes)\n\n        if len(sym_shape) == 0:\n            local_coeffs = local_dof_vec\n            source_vec[source_ids_in_el] = rsplm @ local_coeffs\n        else:\n            from pytools import indices_in_shape\n            for sym_id in indices_in_shape(sym_shape):\n                source_vec[sym_id + (source_ids_in_el, )] = \\\n                    rsplm @ local_dof_vec[sym_id]\n\n    source_vec = cl.array.to_device(actx.queue, source_vec)\n\n    if order == \"tree\":\n        pass  # no need to do anything\n    elif order == \"user\":\n        source_vec = source_vec[tree.sorted_target_ids]  # into user order\n    else:\n        raise ValueError(f\"order must be 'tree' or 'user' (got {order}).\")\n\n    return source_vec\n\n# }}} End from meshmode interpolation\n\n\n# {{{ to meshmode interpolation\n\ndef interpolate_to_meshmode(actx, potential, leaves_to_nodes_lookup,\n                            order=\"tree\"):\n    \"\"\"\n    :arg potential: a DoF vector representing a field in :mod:`volumential`,\n        in tree order.\n    :arg leaves_to_nodes_lookup: a :class:`LeavesToNodesLookup`.\n    :arg order: order of the input potential, either \"tree\" or \"user\".\n\n    :returns: a :class:`pyopencl.Array` of shape (nnodes, 1) containing the\n        interpolated data.\n    \"\"\"\n    if order == \"tree\":\n        potential_in_tree_order = True\n    elif order == \"user\":\n        potential_in_tree_order = False\n    else:\n        raise ValueError(f\"order must be 'tree' or 'user' (got {order}).\")\n\n    if not isinstance(actx, PyOpenCLArrayContext):\n        if isinstance(actx, cl.CommandQueue):\n            from warnings import warn\n            warn(\"Command queue passed to the interpolator. \"\n                 \"Supply an array context to enable proper caching.\")\n            actx = PyOpenCLArrayContext(actx)\n        else:\n            raise ValueError\n\n    target_points = flatten(thaw(actx, leaves_to_nodes_lookup.discr.nodes()))\n\n    traversal = leaves_to_nodes_lookup.trav\n    tree = leaves_to_nodes_lookup.trav.tree\n\n    dim = tree.dimensions\n\n    # infer q_order from tree\n    pts_per_box = tree.ntargets // traversal.ntarget_boxes\n    assert pts_per_box * traversal.ntarget_boxes == tree.ntargets\n\n    # allow for +/- 0.25 floating point error\n    q_order = int(pts_per_box**(1 / dim) + 0.25)\n    assert q_order**dim == pts_per_box\n\n    interp_p = interpolate_volume_potential(\n            target_points=target_points, traversal=traversal,\n            wrangler=None, potential=potential,\n            potential_in_tree_order=potential_in_tree_order,\n            dim=dim, tree=tree, queue=actx.queue, q_order=q_order,\n            dtype=potential.dtype, lbl_lookup=None,\n            balls_near_box_starts=leaves_to_nodes_lookup.nodes_in_leaf_starts,\n            balls_near_box_lists=leaves_to_nodes_lookup.nodes_in_leaf_lists)\n\n    return interp_p\n\n# }}} End to meshmode interpolation\n", "meta": {"hexsha": "7330118979cf854a4a5d4f3e276b267ec45c005c", "size": 28760, "ext": "py", "lang": "Python", "max_stars_repo_path": "volumential/interpolation.py", "max_stars_repo_name": "xywei/volumential", "max_stars_repo_head_hexsha": "07c6ca8c623acf24fb8deddf93baa1035234db58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-21T23:57:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T22:02:50.000Z", "max_issues_repo_path": "volumential/interpolation.py", "max_issues_repo_name": "inducer/volumential", "max_issues_repo_head_hexsha": "290a5943d3f47958dcab6736bc2b758525471570", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:41:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-26T15:42:21.000Z", "max_forks_repo_path": "volumential/interpolation.py", "max_forks_repo_name": "inducer/volumential", "max_forks_repo_head_hexsha": "290a5943d3f47958dcab6736bc2b758525471570", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-21T21:23:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-21T21:23:39.000Z", "avg_line_length": 37.157622739, "max_line_length": 85, "alphanum_fraction": 0.6173157163, "include": true, "reason": "import numpy,import sympy", "num_tokens": 6645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3812195803163617, "lm_q1q2_score": 0.19805170031997832}}
{"text": "#! /usr/bin/env python\n\n\"LiDAR ground algorithm\"\n\nimport os, glob, argparse, time, math\nimport numpy as np\nfrom laspy.file import File\nimport sqlite3\nimport ConfigParser\n\ndef getArgs():\n\tparser = argparse.ArgumentParser(\n\t\tdescription=\"LiDAR ground and canopy classification.\"\n\t)\n\tparser.add_argument(\n\t\t\"-c\",\n\t\t\"--config\",\n\t\ttype=str,\n\t\trequired=True,\n\t\thelp=\"Configuration File.\"\n\t)\n\tparser.add_argument(\n\t\t\"-g\",\n\t\t\"--ground\",\n\t\taction = \"store_true\",\n\t\thelp=\"Ground classification.\"\n\n\t)\n\tparser.add_argument(\n\t\t\"-t\",\n\t\t\"--toc\",\n\t\taction = \"store_true\",\n\t\thelp=\"Canopy classification.\"\n\n\t)\n\tparser.add_argument(\n\t\t\"-v\",\n\t\t\"--verbose\",\n\t\taction = \"store_true\",\n\t\thelp=\"Print status to screen.\"\n\n\t)\n\n\treturn parser.parse_args()\n\ndef getConfigs(configFile):\n\tConfigs={}\n\ttry:\n\t\tconfig = ConfigParser.ConfigParser()\n\t\tconfig.read(configFile)\n\t\tConfigs[\"paths\"]=dict(config.items(\"paths\"))\n\t\tConfigs[\"vars\"]=dict(config.items(\"vars\"))\n\texcept Exception as e:\n\t\tprint \"Problem parsing configuration file: {}.\".format(configFile)\n\t\traise e\n\treturn Configs\n\nclass Points(object):\n\tdef __init__(self, points, configs, filename):\n\t\tself.points = points\n\t\tself.configs = configs\n\t\tself.filename = filename\n\n\tdef getParams(self):\n\t\t\"\"\"\n\t\t\"\"\"\n\t\tindirs = self.configs[\"paths\"][\"input\"]\n\t\tindir = indirs.split(\":\")[0]\n\t\tos.chdir(indir)\n\t\tinfile=glob.glob(\"*.las\")[0]\n\t\tdata = File(infile, mode=\"r\")\n\t\tself.header = data.header\n\t\t#print self.header\n\t\tself.dtype = data.points.dtype\n\n\tdef write(self):\n\t\toutput = self.configs[\"paths\"][\"output\"]\n\t\tpoints = np.array(self.points, dtype=self.dtype)\n\t\t#print self.header\n\t\toutfile = File(output + self.filename, mode=\"w\", header=self.header)\n\t\toutfile.points = points\n\t\toutfile.close()\n\ndef setGround(pt):\n\tpt = list(pt)\n\tpt[5]=2\n\treturn tuple(pt)\n\ndef setCanopy(pt):\n\tpt = list(pt)\n\tpt[5]=1\n\treturn tuple(pt)\n\ndef height(dz, thresh=1.5):\n\treturn dz < 1.5\n\ndef angle(dX, dY, dZ, thresh=5.5, eps=0.000000001):\n\thyp = math.sqrt((dX)**2+(dY)**2+(dZ)**2)\n\t# Use epsilon equality for floats\n\tif hyp < eps:\n\t\treturn False\n\tdegrees = math.asin(dZ/hyp)*(180/math.pi)\n\treturn degrees < thresh\n\n\ndef groundFilter(seed, pt):\n\tX0=seed[0]*0.001\n\tY0=seed[1]*0.001\n\tZ0=seed[2]*0.001\n\tX1=pt[0]*0.001\n\tY1=pt[1]*0.001\n\tZ1=pt[2]*0.001\n\tdX = X1-X0\n\tdY = Y1-Y0\n\tdZ = Z1-Z0\n\t# skip duplicated point\n\tif seed == pt:\n\t\treturn False\n\treturn height(dZ) and angle(dX, dY, dZ)\n\n\n\n\ndef groundClassifier(configs):\n\t\"\"\"\n\t\"\"\"\n\tt_i = time.time()\n\tpoints = []\n\n\tdatabase = configs[\"paths\"][\"db\"]\n\tconn = sqlite3.connect(database)\n\tc = conn.cursor()\n\tminZs = c.execute(\"\"\"SELECT distinct(hash10), min(Z) FROM pointcloud \n\t\t\t\t\t\t\tWHERE num_returns=return_number\n\t\t\t\t\t\t\tGROUP BY hash10;\"\"\"\n\t).fetchall()\n\tminZs = list(minZs)\n\tprint minZs\n\tcount = 0\n\tfor h, z in minZs:\n\t\tseed = c.execute(\"\"\"\n\t\t\tSELECT\n\t\t\t\tX,\n\t\t\t\tY,\n\t\t\t\tZ,\n\t\t\t\tintensity,\n\t\t\t\tflag_byte,\n\t\t\t\traw_classification,\n\t\t\t\tscan_angle_rank,\n\t\t\t\tuser_data,\n\t\t\t\tpt_src_id,\n\t\t\t\tgps_time\n\t\t\tFROM pointcloud\n\t\t\tWHERE Z=? and hash10=?;\n\t\t\t\"\"\", (z, h)).fetchall()[0]\n\t\tprint seed\n\t\tseed = setGround(seed)\n\t\tpoints.append((seed,))\n\t\tputative_grounds = c.execute(\"\"\"\n\t\t\tSELECT\n\t\t\t\tX,\n\t\t\t\tY,\n\t\t\t\tZ,\n\t\t\t\tintensity,\n\t\t\t\tflag_byte,\n\t\t\t\traw_classification,\n\t\t\t\tscan_angle_rank,\n\t\t\t\tuser_data,\n\t\t\t\tpt_src_id,\n\t\t\t\tgps_time\n\t\t\tFROM pointcloud\n\t\t\tWHERE hash10=? AND num_returns=return_number;\n\t\t\t\"\"\", (h,)).fetchall()\n\t\tfor putative_ground in putative_grounds:\n\t\t\tif groundFilter(seed, putative_ground):\n\t\t\t\tputative_ground=setGround(putative_ground)\n\t\t\t\tpoints.append((putative_ground,))\n\t\tcount += 1\n\t\tprint \"Finished {}; block hash {}.\".format(count, h)\n\tconn.close()\n\tt_f = time.time()\n\tprint \"Ground classifier took {} minutes.\".format((t_f-t_i)/60.0)\n\treturn points\n\n\ndef canopyClassifier(configs):\n\t\"\"\"\n\t\"\"\"\n\tt_i = time.time()\n\tpoints = []\n\tscale = float(configs[\"vars\"][\"scale\"])\n\theight_max = float(configs[\"vars\"][\"height_max\"])/scale # depends on scale\n\tdatabase = configs[\"paths\"][\"db\"]\n\tconn = sqlite3.connect(database)\n\tc = conn.cursor()\n\n\thashmap_list = c.execute(\"SELECT distinct(hash1),hash10 FROM pointcloud;\").fetchall()\n\thashmap = {}\n\tfor k,v in hashmap_list:\n\t\thashmap[k]=v\n\t\n\tminZ_list = c.execute(\"\"\"SELECT distinct(hash10), min(Z) FROM pointcloud\n\t\t\t\t\t\t\tGROUP BY hash10\"\"\"\n\t).fetchall()\n\tmin_z = {}\n\tfor k,v in minZ_list:\n\t\tmin_z[k]=v\n\n\tmaxZs = c.execute(\"\"\"SELECT distinct(hash1), max(Z) FROM pointcloud \n\t\t\t\t\t\t\tWHERE return_number=1\n\t\t\t\t\t\t\tGROUP BY hash1\"\"\"\t\n\t).fetchall()\n\tcount = 0\n\tfor h1,h10 in hashmap.iteritems():\n\t\tz_max = min_z[h10] + height_max\n\t\tresults = c.execute(\"\"\"\n\t\t\tSELECT\n\t\t\t\tX,\n\t\t\t\tY,\n\t\t\t\tZ,\n\t\t\t\tintensity,\n\t\t\t\tflag_byte,\n\t\t\t\traw_classification,\n\t\t\t\tscan_angle_rank,\n\t\t\t\tuser_data,\n\t\t\t\tpt_src_id,\n\t\t\t\tgps_time\n\t\t\tFROM pointcloud\n\t\t\tWHERE Z<? and hash1=?;\n\t\t\t\"\"\", (z_max, h1)).fetchall()\n\t\theights={}\n\t\tfor result in results:\n\t\t\tZ = result[2]\n\t\t\theights[Z]=result\n\t\tif len(heights)>0:\n\t\t\tTOC = heights[max(heights)]\n\t\t\tTOC = setCanopy(TOC)\n\t\t\tpoints.append((TOC,))\n\t\t\tcount += 1\n\t\t\tprint \"Finished {}; block hash {}.\".format(count, h1)\n\tconn.close()\n\tt_f = time.time()\n\tprint \"Canopy classifier took {} minutes.\".format((t_f-t_i)/60.0)\n\treturn points\n\ndef main():\n\tt_i = time.time()\n\targs=getArgs()\n\tif args.verbose:\n\t\tprint args\n\t#base = os.getcwd()\n\tconfigs = getConfigs(args.config)\n\tif args.verbose:\n\t\tprint configs\n\tif args.ground:\n\t\tpoints = groundClassifier(configs)\n\t\tprint points\n\t\tgroundPoints = Points(points, configs, \"ground.las\")\n\t\tgroundPoints.getParams()\n\t\tgroundPoints.write()\n\t\tdel points\n\tif args.toc:\n\t\tpoints = canopyClassifier(configs)\n\t\tprint points\n\t\tcanopyPoints = Points(points, configs, \"canopy.las\")\n\t\tcanopyPoints.getParams()\n\t\tcanopyPoints.write()\n\t\tdel points\n\tt_f = time.time()\n\tif args.verbose:\n\t\tprint \"Total elapsed time {} minutes.\".format((t_f-t_i)/60)\n\n\n\n\n\n\t\t\t#list_data.append((window_index, data_text))\n\t\t#c.executemany('INSERT INTO pointcloud VALUES (?,?)', list_data)\n\n\n\t#data = group(args.input)\n\t#os.chdir(base)\n\t#print data\n\n\n\n\n\n\nif __name__ == \"__main__\":\n\tmain()", "meta": {"hexsha": "7daab047b080a3dc6a21a1c71ad53e5d45bf589e", "size": 5985, "ext": "py", "lang": "Python", "max_stars_repo_path": "classify.py", "max_stars_repo_name": "africker/lidargc", "max_stars_repo_head_hexsha": "421c21b7a0b6a678d4200007b9b5b5c0629bf6fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2015-02-06T03:51:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-08T14:57:07.000Z", "max_issues_repo_path": "classify.py", "max_issues_repo_name": "africker/lidargc", "max_issues_repo_head_hexsha": "421c21b7a0b6a678d4200007b9b5b5c0629bf6fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "classify.py", "max_forks_repo_name": "africker/lidargc", "max_forks_repo_head_hexsha": "421c21b7a0b6a678d4200007b9b5b5c0629bf6fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-22T09:53:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-28T07:07:10.000Z", "avg_line_length": 20.5670103093, "max_line_length": 86, "alphanum_fraction": 0.6604845447, "include": true, "reason": "import numpy", "num_tokens": 1746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305398, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.19805169868735353}}
{"text": "# Copyright (c) 2019 - The Procedural Generation for Gazebo authors\n# For information on the respective copyright owner see the NOTICE file\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom ...parsers.sdf import create_sdf_element\nimport collections\nimport numpy as np\nfrom copy import deepcopy\nfrom .pose import Pose\n\n\nclass Inertial(object):\n    def __init__(self, mass=0, ixx=0, iyy=0, izz=0, ixy=0, ixz=0, iyz=0):        \n        self._mass = mass\n        self._pose = Pose()\n        self._ixx = ixx\n        self._iyy = iyy\n        self._izz = izz\n        self._ixy = ixy\n        self._iyz = iyz\n        self._ixz = ixz\n\n    def __str__(self):\n        pose = self._pose.position + self._pose.rpy\n        msg = 'Mass [Kg]={}\\n'.format(self._mass)\n        msg += 'Pose={}\\n'.format(pose)\n        msg += 'I =\\n'\n        msg += '\\tIxx={}\\n'.format(self._ixx)\n        msg += '\\tIyy={}\\n'.format(self._iyy)\n        msg += '\\tIzz={}\\n'.format(self._izz)\n        msg += '\\tIxy={}\\n'.format(self._ixy)\n        msg += '\\tIxz={}\\n'.format(self._ixz)\n        msg += '\\tIyz={}\\n'.format(self._iyz)\n        return msg\n\n    @property\n    def mass(self):\n        return self._mass\n\n    @mass.setter\n    def mass(self, value):\n        assert value > 0, 'Mass must be greater than zero'\n        self._mass = value\n\n    @property\n    def pose(self):\n        return self._pose\n\n    @pose.setter\n    def pose(self, vec):\n        if isinstance(vec, Pose):\n            self._pose = vec\n        else:\n            assert isinstance(vec, collections.Iterable), \\\n                'Input pose vector must be iterable'\n            assert len(vec) == 6 or len(vec) == 7, \\\n                'Pose must be given as position and Euler angles (x, y, z, ' \\\n                'roll, pitch, yaw) or position and quaternions (x, y, z, ' \\\n                'qx, qy, qz, qw)'\n            for item in vec:\n                assert isinstance(item, float) or isinstance(item, int), \\\n                    'All elements in pose vector must be a float or an integer'        \n            \n            self._pose = Pose(pos=vec[0:3], rot=vec[3::])\n            \n    @property\n    def ixx(self):\n        return self._ixx\n\n    @ixx.setter\n    def ixx(self, value):\n        assert isinstance(value, float) or isinstance(value, int), \\\n            'Input value must be a float or an integer, provided={}'.format(type(value))\n        self._ixx = value\n\n    @property\n    def iyy(self):\n        return self._iyy\n\n    @iyy.setter\n    def iyy(self, value):\n        assert isinstance(value, float) or isinstance(value, int), \\\n            'Input value must be a float or an integer, provided={}'.format(type(value))\n        self._iyy= value\n\n    @property\n    def izz(self):\n        return self._izz\n\n    @izz.setter\n    def izz(self, value):\n        assert isinstance(value, float) or isinstance(value, int), \\\n            'Input value must be a float or an integer, provided={}'.format(type(value))\n        self._izz = value\n\n    @property\n    def ixy(self):\n        return self._ixy\n\n    @ixy.setter\n    def ixy(self, value):\n        assert isinstance(value, float) or isinstance(value, int), \\\n            'Input value must be a float or an integer, provided={}'.format(type(value))\n        self._ixy = value\n\n    @property\n    def ixz(self):\n        return self._ixz\n\n    @ixz.setter\n    def ixz(self, value):\n        assert isinstance(value, float) or isinstance(value, int), \\\n            'Input value must be a float or an integer, provided={}'.format(type(value))\n        self._ixz = value\n\n    @property\n    def iyz(self):\n        return self._iyz\n\n    @iyz.setter\n    def iyz(self, value):\n        assert isinstance(value, float) or isinstance(value, int), \\\n            'Input value must be a float or an integer, provided={}'.format(type(value))\n        self._iyz = value\n\n    @property\n    def moi(self):\n        return np.array([\n            [self.ixx, self.ixy, self.ixz],\n            [-self.ixy, self.iyy, self.iyz],\n            [-self.ixz, -self.iyz, self.izz]])\n\n    @staticmethod\n    def create_inertia(inertia_type, **kwargs):\n        if inertia_type == 'solid_sphere':\n            return Inertial.create_solid_sphere_inertia(**kwargs)\n        elif inertia_type == 'hollow_sphere':\n            return Inertial.create_hollow_sphere_inertia(**kwargs)\n        elif inertia_type == 'ellipsoid':\n            return Inertial.create_ellipsoid_inertia(**kwargs)\n        elif inertia_type == 'cuboid':\n            return Inertial.create_cuboid_inertia(**kwargs)\n        elif inertia_type == 'centered_rod':\n            return Inertial.create_centered_rod_inertia(**kwargs)\n        elif inertia_type == 'solid_cylinder':\n            return Inertial.create_solid_cylinder_inertia(**kwargs)\n        elif inertia_type == 'custom':\n            return Inertial(**kwargs)\n        else:\n            return None\n\n    @staticmethod\n    def create_solid_sphere_inertia(mass, radius):\n        assert mass > 0, 'Mass must be greater than zero'\n        assert radius > 0, 'Radius must be greater than zero'\n        inertia = Inertial()\n\n        fac = 2. / 5\n        inertia.mass = mass\n        inertia.ixx = fac * mass * radius**2\n        inertia.iyy = fac * mass * radius**2\n        inertia.izz = fac * mass * radius**2\n\n        return inertia\n\n    @staticmethod\n    def create_hollow_sphere_inertia(mass, radius):\n        assert mass > 0, 'Mass must be greater than zero'\n        assert radius > 0, 'Radius must be greater than zero'\n        inertia = Inertial()\n\n        fac = 2. / 3\n        inertia.mass = mass\n        inertia.ixx = fac * mass * radius**2\n        inertia.iyy = fac * mass * radius**2\n        inertia.izz = fac * mass * radius**2\n\n        return inertia\n\n    @staticmethod\n    def create_ellipsoid_inertia(mass, axis_length_x, axis_length_y, axis_length_z):\n        assert mass > 0\n        assert axis_length_x > 0\n        assert axis_length_y > 0\n        assert axis_length_z > 0\n        inertia = Inertial()\n\n        fac = 1. / 5\n\n        inertia.mass = mass\n        inertia.ixx = fac * mass * (axis_length_y**2 + axis_length_z**2)\n        inertia.iyy = fac * mass * (axis_length_x**2 + axis_length_z**2)\n        inertia.izz = fac * mass * (axis_length_x**2 + axis_length_y**2)\n\n        return inertia\n\n    @staticmethod\n    def create_cuboid_inertia(mass, length_x, length_y, length_z):\n        assert mass > 0\n        assert length_x > 0\n        assert length_y > 0\n        assert length_z > 0\n        inertia = Inertial()\n\n        fac = 1. / 12\n\n        inertia.mass = mass\n        inertia.ixx = fac * mass * (length_y**2 + length_z**2)\n        inertia.iyy = fac * mass * (length_x**2 + length_z**2)\n        inertia.izz = fac * mass * (length_x**2 + length_y**2)\n\n        return inertia\n\n    @staticmethod\n    def create_centered_rod_inertia(mass, length, axis):\n        assert mass > 0\n        assert length > 0\n        assert isinstance(axis, list)\n        assert len(axis) == 3\n        assert sum(axis) == 1\n        assert axis[0] == 1 or axis[1] == 1 or axis[2] == 1\n        inertia = Inertial()\n\n        fac = 1. / 12\n        inertia.mass = mass\n        inertia.ixx = axis[0] * fac * mass * length**2\n        inertia.iyy = axis[1] * fac * mass * length**2\n        inertia.izz = axis[2] * fac * mass * length**2\n\n        return inertia\n\n    @staticmethod\n    def create_solid_cylinder_inertia(mass, radius, length, axis):\n        assert mass > 0, 'Mass must be greater than zero'\n        assert length > 0, 'Length must be greater than zero'\n        assert radius > 0, 'Radius must be greater than zero'\n        assert isinstance(axis, list), 'Axis vector must be provided as a list'\n        assert len(axis) == 3, 'Axis vector must have three elements'\n        assert sum(axis) == 1, 'Axis vector must be a unit vector'\n        assert axis[0] == 1 or axis[1] == 1 or axis[2] == 1\n        inertia = Inertial()\n\n        fac = 1. / 12\n        inertia.mass = mass\n        i_axis = 0.5 * mass * radius**2\n        i_side = 1. / 12 * mass * (3 * radius**2 + length**2)\n\n        inertia.ixx = i_side\n        inertia.iyy = i_side\n        inertia.izz = i_side\n\n        if axis[0] == 1:\n            inertia.ixx = i_axis\n        elif axis[1] == 1:\n            inertia.iyy = i_axis\n        else:\n            inertia.izz = i_axis\n\n        return inertia\n\n    def to_sdf(self):\n        sdf = create_sdf_element('inertial')\n        sdf.mass = self._mass\n        sdf.pose = self._pose.to_sdf()        \n        sdf.inertia.ixx = self._ixx\n        sdf.inertia.iyy = self._iyy\n        sdf.inertia.izz = self._izz\n        sdf.inertia.ixy = self._ixy\n        sdf.inertia.ixz = self._ixz\n        sdf.inertia.iyz = self._iyz\n        return sdf\n\n    @staticmethod\n    def from_sdf(sdf):\n        assert sdf._NAME == 'inertial', 'Input SDF element must be of type inertial'\n        inertial = Inertial()\n        inertial.mass = sdf.mass.value\n        inertial._pose = Pose.from_sdf(sdf.pose)\n        inertial.ixx = sdf.inertia.ixx.value\n        inertial.iyy = sdf.inertia.iyy.value\n        inertial.izz = sdf.inertia.izz.value\n        inertial.ixy = sdf.inertia.ixy.value\n        inertial.ixz = sdf.inertia.ixz.value\n        inertial.iyz = sdf.inertia.iyz.value\n        return inertial", "meta": {"hexsha": "4a7805c84e1f605f23846cec94e6c48c159ec0e8", "size": 9730, "ext": "py", "lang": "Python", "max_stars_repo_path": "pcg_libraries/src/pcg_gazebo/simulation/properties/inertial.py", "max_stars_repo_name": "boschresearch/pcg_gazebo_pkgs", "max_stars_repo_head_hexsha": "1c112d01847ca4f8da61ce9b273e13d13bc7eb73", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 42, "max_stars_repo_stars_event_min_datetime": "2019-06-26T09:46:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T17:56:26.000Z", "max_issues_repo_path": "pcg_libraries/src/pcg_gazebo/simulation/properties/inertial.py", "max_issues_repo_name": "boschresearch/pcg_gazebo_pkgs", "max_issues_repo_head_hexsha": "1c112d01847ca4f8da61ce9b273e13d13bc7eb73", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-07-18T10:36:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-02T15:26:32.000Z", "max_forks_repo_path": "pcg_libraries/src/pcg_gazebo/simulation/properties/inertial.py", "max_forks_repo_name": "boschresearch/pcg_gazebo_pkgs", "max_forks_repo_head_hexsha": "1c112d01847ca4f8da61ce9b273e13d13bc7eb73", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-11-01T03:20:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-15T23:23:44.000Z", "avg_line_length": 32.8716216216, "max_line_length": 88, "alphanum_fraction": 0.5882836588, "include": true, "reason": "import numpy", "num_tokens": 2607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19805169301539852}}
{"text": "\"\"\"\nModule for snow masking\n\nCredits:\nCopyright (c) 2017-2022 Matej Aleksandrov, Matej Batič, Grega Milčinski, Domagoj Korais, Matic Lubej (Sinergise)\nCopyright (c) 2017-2022 Žiga Lukšič, Devis Peressutti, Nejc Vesel, Jovan Višnjić, Anže Zupanc (Sinergise)\nCopyright (c) 2019-2020 Jernej Puc, Lojze Žust (Sinergise)\nCopyright (c) 2017-2019 Blaž Sovdat, Andrej Burja, Eva Erzin (Sinergise)\n\nThis source code is licensed under the MIT license found in the LICENSE\nfile in the root directory of this source tree.\n\"\"\"\n\nimport logging\nimport itertools\n\nimport numpy as np\nfrom skimage.morphology import disk, binary_dilation\n\nfrom eolearn.core import EOTask, FeatureType\nfrom .utils import resize_images\n\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass BaseSnowMaskTask(EOTask):\n    \"\"\"Base class for snow detection and masking\"\"\"\n\n    def __init__(self, data_feature, band_indices, dilation_size=0, undefined_value=0, mask_name=\"SNOW_MASK\"):\n        \"\"\"\n        :param data_feature: EOPatch feature represented by a tuple in the form of `(FeatureType, 'feature_name')`\n        :type data_feature: tuple(FeatureType, str)\n        :param band_indices: A list containing the indices at which the required bands can be found in the data_feature.\n        :type band_indices: list(int)\n        :param dilation_size: Size of the disk in pixels for performing dilation. Value 0 means do not perform\n            this post-processing step.\n        :type dilation_size: int\n        \"\"\"\n        self.bands_feature = self.parse_feature(data_feature)\n        self.band_indices = band_indices\n        self.dilation_size = dilation_size\n        self.undefined_value = undefined_value\n        self.mask_feature = (FeatureType.MASK, mask_name)\n\n    def _apply_dilation(self, snow_masks):\n        \"\"\"Apply binary dilation for each mask in the series\"\"\"\n        if self.dilation_size:\n            snow_masks = np.array([binary_dilation(mask, disk(self.dilation_size)) for mask in snow_masks])\n        return snow_masks\n\n    def execute(self, eopatch):\n        raise NotImplementedError\n\n\nclass SnowMaskTask(BaseSnowMaskTask):\n    \"\"\"The task calculates the snow mask using the given thresholds.\n\n    The default values were optimised based on the Sentinel-2 L1C processing level. Values might not be optimal for L2A\n    processing level\n    \"\"\"\n\n    NDVI_THRESHOLD = 0.1\n\n    def __init__(self, data_feature, band_indices, ndsi_threshold=0.4, brightness_threshold=0.3, **kwargs):\n        \"\"\"\n        :param data_feature: EOPatch feature represented by a tuple in the form of `(FeatureType, 'feature_name')`\n            containing the bands 2, 3, 7, 11, i.e. (FeatureType.DATA, 'BANDS')\n        :type data_feature: tuple(FeatureType, str)\n        :param band_indices: A list containing the indices at which the required bands can be found in the data_feature.\n            The required bands are B03, B04, B08 and B11 and the indices should be provided in this order. If the\n            'BANDS' array contains all 13 L1C bands, then `band_indices=[2, 3, 7, 11]`. If the 'BANDS' are the 12 bands\n            with L2A values, then `band_indices=[2, 3, 7, 10]`\n        :type band_indices: list(int)\n        :param ndsi_threshold: Minimum value of the NDSI required to classify the pixel as snow\n        :type ndsi_threshold: float\n        :param brightness_threshold: Minimum value of the red band for a pixel to be classified as bright\n        :type brightness_threshold: float\n        \"\"\"\n        super().__init__(data_feature, band_indices, **kwargs)\n        self.ndsi_threshold = ndsi_threshold\n        self.brightness_threshold = brightness_threshold\n\n    def execute(self, eopatch):\n        bands = eopatch[self.bands_feature][..., self.band_indices]\n        with np.errstate(divide=\"ignore\"):\n            # (B03 - B11) / (B03 + B11)\n            ndsi = (bands[..., 0] - bands[..., 3]) / (bands[..., 0] + bands[..., 3])\n            # (B08 - B04) / (B08 + B04)\n            ndvi = (bands[..., 2] - bands[..., 1]) / (bands[..., 2] + bands[..., 1])\n\n        ndsi_invalid, ndvi_invalid = ~np.isfinite(ndsi), ~np.isfinite(ndvi)\n        ndsi[ndsi_invalid] = self.undefined_value\n        ndvi[ndvi_invalid] = self.undefined_value\n\n        snow_mask = np.where(\n            np.logical_and(\n                np.logical_or(\n                    ndsi >= self.ndsi_threshold, np.abs(ndvi - self.NDVI_THRESHOLD) < self.NDVI_THRESHOLD / 2\n                ),\n                bands[..., 0] >= self.brightness_threshold,\n            ),\n            1,\n            0,\n        )\n\n        snow_mask = self._apply_dilation(snow_mask)\n\n        snow_mask[np.logical_or(ndsi_invalid, ndvi_invalid)] = self.undefined_value\n\n        eopatch[self.mask_feature] = snow_mask[..., np.newaxis].astype(bool)\n        return eopatch\n\n\nclass TheiaSnowMaskTask(BaseSnowMaskTask):\n    \"\"\"Task to add a snow mask to an EOPatch. The input data is either Sentinel-2 L1C or L2A level\n\n    Original implementation and documentation available at https://gitlab.orfeo-toolbox.org/remote_modules/let-it-snow\n\n    ATBD https://gitlab.orfeo-toolbox.org/remote_modules/let-it-snow/blob/master/doc/atbd/ATBD_CES-Neige.pdf\n\n    This task computes a snow mask for the input EOPatch. The `data_feature` to be used as input to the\n    classifier is a mandatory argument. If all of the needed features exist already, the classifier is run.\n    `linear` interpolation is used for resampling of the `data_feature` and cloud probability map, while `nearest`\n    interpolation is used to upsample the binary cloud mask.\n    \"\"\"\n\n    B10_THR = 0.015\n    DEM_FACTOR = 0.00001\n\n    def __init__(\n        self,\n        data_feature,\n        band_indices,\n        cloud_mask_feature,\n        dem_feature,\n        dem_params=(100, 0.1),\n        red_params=(12, 0.3, 0.1, 0.2, 0.040),\n        ndsi_params=(0.4, 0.15, 0.001),\n        b10_index=None,\n        **kwargs,\n    ):\n        \"\"\"\n        :param data_feature: EOPatch feature represented by a tuple in the form of `(FeatureType, 'feature_name')`\n            containing the bands B3, B4, and B11\n\n            Example: `(FeatureType.DATA, 'ALL-BANDS')`\n        :type data_feature: tuple(FeatureType, str)\n        :param band_indices: A list containing the indices at which the required bands can be found in the bands\n            feature. If all L1C band values are provided, `band_indices=[2, 3, 11]`. If all L2A band values are\n            provided, then `band_indices=[2, 3, 10]`\n        :type band_indices: list(int)\n        :param cloud_mask_feature: EOPatch CLM feature represented by a tuple in the form of\n            `(FeatureType, 'feature_name')` containing the cloud mask\n        :type cloud_mask_feature: tuple(FeatureType, str)\n        :param dem_feature: EOPatch DEM feature represented by a tuple in the form of `(FeatureType, 'feature_name')`\n            containing the digital elevation model\n        :type dem_feature: tuple(FeatureType, str)\n        :param b10_index: Array index where the B10 band is stored in the bands feature. This is used to refine the\n            initial cloud mask\n        :type b10_index: int\n        :param dem_params: Tuple with parameters pertaining DEM processing. The first value specifies the bin size\n            used to group DEM values, while the second value specifies the minimum snow fraction in an elevation band\n            to define z_s. With reference to the ATBD, the tuple is (d_z, f_t)\n        :type dem_params: (float, float)\n        :param red_params: Tuple specifying parameters to process the B04 red band. The first parameter defines the\n            scaling factor for down-sampling the red band, the second parameter is the maximum value of the\n            down-sampled red band for a dark cloud pixel, the third parameter is the minimum value\n            to return a non-snow pixel to the cloud mask, the fourth is the minimum reflectance value to pass the 1st\n            snow test, and the fifth is the minimum reflectance value to pass the 2nd snow test. With reference to the\n            ATBD, the tuple is (r_f, r_d, r_b, r_1, r_2)\n        :type red_params: (float, float, float, float, float)\n        :param ndsi_params: Tuple specifying parameters for the NDSI. First parameter is the minimum value to pass the\n            1st snow test, the second parameter is the minimum value to pass the 2nd snow test, and the third parameter\n            is the minimum snow fraction in the image to activate the pass 2 snow test. With reference to the\n            ATBD, the tuple is (n_1, n_2, f_s)\n        :type ndsi_params: (float, float, float)\n        \"\"\"\n        super().__init__(data_feature, band_indices, **kwargs)\n        self.dem_feature = self.parse_feature(dem_feature)\n        self.clm_feature = self.parse_feature(cloud_mask_feature)\n        self.dem_params = dem_params\n        self.red_params = red_params\n        self.ndsi_params = ndsi_params\n        self.b10_index = b10_index\n        self._validate_params()\n\n    def _validate_params(self):\n        \"\"\"Check length of parameters defining threshold values\"\"\"\n        for params, n_params in [(self.dem_params, 2), (self.red_params, 5), (self.ndsi_params, 3)]:\n            if not isinstance(params, (tuple, list)) or len(params) != n_params:\n                raise ValueError(\n                    f\"Incorrect format or number of parameters for {params}. Has to be a tuple of length {n_params}\"\n                )\n\n    def _resample_red(self, input_array):\n        \"\"\"Method to resample the values of the red band\n\n        The input array is first down-scaled using bicubic interpolation and up-scaled back using nearest neighbour\n        interpolation\n\n        :param input_array: input values\n        :return: resampled values\n        \"\"\"\n        height, width = input_array.shape[1:]\n        size = (height // self.red_params[0], width // self.red_params[0])\n        return resize_images(\n            resize_images(input_array[..., np.newaxis], new_size=size), new_size=(height, width)\n        ).squeeze()\n\n    def _adjust_cloud_mask(self, bands, cloud_mask, dem, b10):\n        \"\"\"Adjust existing cloud mask using cirrus band if L1C data and resampled red band\n\n        Add to the existing cloud mask pixels found thresholding down-sampled red band and cirrus band/DEM\n        \"\"\"\n        clm_b10 = (\n            np.where(b10 > self.B10_THR + self.DEM_FACTOR * dem, 1, 0)\n            if b10 is not None\n            else np.ones(shape=cloud_mask.shape, dtype=np.uint8)\n        )\n        return np.logical_or(\n            np.where(np.logical_and(cloud_mask == 1, self._resample_red(bands[..., 1]) > self.red_params[1]), 1, 0),\n            clm_b10,\n        ).astype(np.uint8)\n\n    def _apply_first_pass(self, bands, ndsi, clm, dem, clm_temp):\n        \"\"\"Apply first pass of snow detection\"\"\"\n        snow_mask_pass1 = np.where(\n            np.logical_and(\n                np.logical_not(clm_temp), np.logical_and(ndsi > self.ndsi_params[0], bands[..., 1] > self.red_params[3])\n            ),\n            1,\n            0,\n        )\n\n        clm_pass1 = np.where(\n            np.logical_or(clm_temp, (bands[..., 1] > self.red_params[2]) & np.logical_not(snow_mask_pass1) & clm), 1, 0\n        )\n\n        dem_edges = np.linspace(\n            np.min(dem), np.max(dem), int(np.ceil((np.max(dem) - np.min(dem)) / self.dem_params[0]))\n        )\n        nbins = len(dem_edges) - 1\n        dem_hist_clear_pixels, snow_frac = None, None\n        if nbins > 0:\n            snow_frac = np.zeros(shape=(bands.shape[0], nbins))\n            dem_hist_clear_pixels = np.array(\n                [np.histogram(dem[np.logical_not(mask)], bins=dem_edges)[0] for mask in clm_pass1]\n            )\n\n            for date, nbin in itertools.product(range(bands.shape[0]), range(nbins)):\n                if dem_hist_clear_pixels[date, nbin] > 0:\n                    dem_mask = np.logical_and(dem_edges[nbin] <= dem, dem < dem_edges[nbin + 1])\n                    in_dem_range_clear = np.where(np.logical_and(dem_mask, np.logical_not(clm_pass1[date])))\n                    snow_frac[date, nbin] = (\n                        np.sum(snow_mask_pass1[date][in_dem_range_clear]) / dem_hist_clear_pixels[date, nbin]\n                    )\n        return snow_mask_pass1, snow_frac, dem_edges\n\n    def _apply_second_pass(self, bands, ndsi, dem, clm_temp, snow_mask_pass1, snow_frac, dem_edges):\n        \"\"\"Second pass of snow detection\"\"\"\n        _, height, width, _ = bands.shape\n        total_snow_frac = np.sum(snow_mask_pass1, axis=(1, 2)) / (height * width)\n        snow_mask_pass2 = np.zeros(snow_mask_pass1.shape)\n        for date in range(bands.shape[0]):\n            if (total_snow_frac[date] > self.ndsi_params[2]) and (\n                snow_frac is not None and np.any(snow_frac[date] > self.dem_params[1])\n            ):\n                z_s = dem_edges[max(np.argmax(snow_frac[date] > self.dem_params[1]) - 2, 0)]\n                snow_mask_pass2[date, :, :] = np.where(\n                    np.logical_and(\n                        dem > z_s,\n                        np.logical_and(\n                            np.logical_not(clm_temp[date]),\n                            np.logical_and(ndsi[date] > self.ndsi_params[1], bands[date, ..., 1] > self.red_params[-1]),\n                        ),\n                    ),\n                    1,\n                    0,\n                )\n        return snow_mask_pass2\n\n    def execute(self, eopatch):\n        \"\"\"Run multi-pass snow detection\"\"\"\n        bands = eopatch[self.bands_feature][..., self.band_indices]\n        b10 = eopatch[self.bands_feature][..., self.b10_index] if self.b10_index is not None else None\n        dem = eopatch[self.dem_feature][..., 0]\n        clm = eopatch[self.clm_feature][..., 0]\n\n        with np.errstate(divide=\"ignore\"):\n            # (B03 - B11) / (B03 + B11)\n            ndsi = (bands[..., 0] - bands[..., 2]) / (bands[..., 0] + bands[..., 2])\n\n        ndsi_invalid = ~np.isfinite(ndsi)\n        ndsi[ndsi_invalid] = self.undefined_value\n\n        clm_temp = self._adjust_cloud_mask(bands, clm, dem, b10)\n\n        snow_mask_pass1, snow_frac, dem_edges = self._apply_first_pass(bands, ndsi, clm, dem, clm_temp)\n\n        snow_mask_pass2 = self._apply_second_pass(bands, ndsi, dem, clm_temp, snow_mask_pass1, snow_frac, dem_edges)\n\n        snow_mask = self._apply_dilation(np.logical_or(snow_mask_pass1, snow_mask_pass2))\n\n        eopatch[self.mask_feature] = snow_mask[..., np.newaxis].astype(bool)\n\n        return eopatch\n", "meta": {"hexsha": "fc629f2bf06d61a9139716c538f85d6d522a7a54", "size": 14458, "ext": "py", "lang": "Python", "max_stars_repo_path": "mask/eolearn/mask/snow_mask.py", "max_stars_repo_name": "chorng/eo-learn", "max_stars_repo_head_hexsha": "a1a3c6fa5568d398f5e43f5ad5aecdfeb05e8d3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mask/eolearn/mask/snow_mask.py", "max_issues_repo_name": "chorng/eo-learn", "max_issues_repo_head_hexsha": "a1a3c6fa5568d398f5e43f5ad5aecdfeb05e8d3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mask/eolearn/mask/snow_mask.py", "max_forks_repo_name": "chorng/eo-learn", "max_forks_repo_head_hexsha": "a1a3c6fa5568d398f5e43f5ad5aecdfeb05e8d3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.9415584416, "max_line_length": 120, "alphanum_fraction": 0.638539217, "include": true, "reason": "import numpy", "num_tokens": 3634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19805169301539852}}
{"text": "import hashlib\nimport logging\nimport subprocess\nfrom abc import abstractmethod\nfrom collections import namedtuple\nfrom os.path import exists, getsize\nfrom typing import Any, Dict, NamedTuple, Optional, Tuple\n\nimport casadi as cas\nimport numpy as np\nfrom jax import jit, vmap\n\nimport lumos.numpy as lnp\nfrom lumos.optimal_control.nlp import MappedConstraints, JaxConstraints, CasConstraints\nfrom lumos.models.composition import CompositeModel\nfrom lumos.optimal_control.nlp import CasConstraints, JaxConstraints\n\nlogger = logging.getLogger(__name__)\n\n\n# Convert from names and arrays to dictionary\ndef _array_to_dict(names, values):\n    # We could do dict(zip(names, values)), but unfortunately this does NOT work\n    # for casadi as casadi matrices are designed to be non-iterable\n    # see: https://github.com/casadi/casadi/issues/2278\n    return {name: values[idx] for idx, name in enumerate(names)}\n\n\n# We use namedtuple to make the io names immutable after generation. They will be used\n# for two types of names:\n# the direct names: which are fully defined by the model itself\n# the 'names': which is the eventual IO taking into consideration submodels and etc.\nModelIO = namedtuple(\"BaseIO\", (\"inputs\", \"outputs\", \"residuals\"))\nStateSpaceIO = namedtuple(\n    \"StateSpaceIO\",\n    (\"states\", \"states_dot\", \"inputs\", \"outputs\", \"con_outputs\", \"residuals\"),\n)\n\n\ndef model_io(\n    inputs: Tuple[str] = (), outputs: Tuple[str] = (), residuals: Tuple[str] = (),\n):\n    \"\"\"Decorator to set the input and output names of a stateless model.\"\"\"\n\n    def wrapper(cls):\n        cls._direct_names = ModelIO(inputs=inputs, outputs=outputs, residuals=residuals)\n        return cls\n\n    return wrapper\n\n\ndef state_space_io(\n    states: Tuple[str] = (),\n    inputs: Tuple[str] = (),\n    outputs: Tuple[str] = (),\n    con_outputs: Tuple[str] = (),\n    residuals: Tuple[str] = (),\n):\n    \"\"\"Decorator to set the input and output names of a StateSpaceModel\"\"\"\n\n    def wrapper(cls):\n\n        # TODO: an issue with using a decorator instead of directly in the class is that\n        # the decorator is executed during import time, which might be harder to debug.\n        if not issubclass(cls, StateSpaceModel):\n            raise RuntimeError(\n                \"state_space_io can only be used for setting the io for \"\n                \"StateSpaceModel. Use model_io for other models\"\n            )\n\n        cls._direct_names = StateSpaceIO(\n            states=states,\n            states_dot=states,  # use the same name as states for the states_dot\n            inputs=inputs,\n            outputs=outputs,\n            con_outputs=con_outputs,\n            residuals=residuals,\n        )\n\n        return cls\n\n    return wrapper\n\n\nclass ModelReturn(NamedTuple):\n    \"\"\"Return data structure for a static model.\"\"\"\n\n    outputs: Dict = {}\n    residuals: Dict = {}\n\n\nclass StateSpaceModelReturn(NamedTuple):\n    \"\"\"Return data structure for state space model.\"\"\"\n\n    states_dot: Dict = {}\n    outputs: Dict = {}\n    con_outputs: Dict = {}\n    residuals: Dict = {}\n\n\nclass ArrayModelReturn(NamedTuple):\n    \"\"\"Return data structure for a static model in array forms.\"\"\"\n\n    outputs: lnp.ndarray = np.array([])\n    residuals: lnp.ndarray = np.array([])\n\n\nclass ArrayStateSpaceModelReturn(NamedTuple):\n    \"\"\"Return data structure for state space model in array forms.\"\"\"\n\n    # NOTE: we use np empty array instead of lnp.array([]) here because the type is\n    # not really affected by user backend choice as it's determined already during the\n    # import time as the default values.\n    states_dot: lnp.ndarray = np.array([])\n    outputs: lnp.ndarray = np.array([])\n    con_outputs: lnp.ndarray = np.array([])\n    residuals: lnp.ndarray = np.array([])\n\n\nclass Model(CompositeModel):\n    \"\"\"Abstract class for mathematical models of the simplest form.\"\"\"\n\n    # parameters of the model.\n    # TODO: need to constrain this more.\n    _params: Dict[str, Any]\n\n    # TODO: not designed yet\n    model_config: Dict[str, Any]\n\n    def __init__(\n        self, model_config: Dict[str, Any] = {}, params: Dict[str, Any] = {},\n    ):\n        super().__init__(model_config=model_config, params=params)\n\n        # Build instance specific name attributes\n        self._construct_io_names()\n\n    @abstractmethod\n    def forward(self, *args, **kwargs):\n        \"\"\"Abstract method for calling the model.\n\n        We name the method to 'forward' to emphasis it's the forward execution of a\n        model.h\n        \"\"\"\n        pass\n\n    def apply_and_forward(self, inputs, params):\n        self.set_recursive_params(params)\n        return self.forward(inputs)\n\n    def apply_and_forward_with_arrays(self, inputs, params):\n        self.set_recursive_params(params)\n        return self.forward_with_array(inputs)\n\n    def _construct_io_names(self):\n        \"\"\"Create model io names while also taking into account submodels compositoin\"\"\"\n\n        self.names = ModelIO(\n            inputs=self._direct_names.inputs,\n            residuals=self._direct_names.residuals,\n            outputs=self._direct_names.outputs\n            + tuple(self._collect_children_outputs()),\n        )\n\n    def _collect_children_outputs(self):\n        \"\"\"Collect all children outputs and prefix them with submodel_name\n        \n        \n        eg: the 'power' output of the 'engine' submodel becomes 'engine.power'\n        \"\"\"\n        children_outputs = []\n        if not self.is_leaf():\n            for submodel_name, model in self._submodels.items():\n                children_outputs += [\n                    submodel_name + \".\" + n for n in model.names.outputs\n                ]\n        return children_outputs\n\n    def combine_submodel_outputs(self, **kwargs):\n        \"\"\"combine the outputs from submodels into large dictionary\n        \n        kwargs: {name_of_submodel: vector_of_outputs}\n        \"\"\"\n        combined_dict = {}\n        for submodel_name, submodel_outputs in kwargs.items():\n            # TODO: maybe we could convert the following to a helper method?\n            combined_dict.update(\n                {submodel_name + \".\" + n: v for n, v in submodel_outputs.items()}\n            )\n\n        return combined_dict\n\n    @classmethod\n    def get_direct_group_names(cls, group: str) -> Tuple[str, ...]:\n        \"\"\"Return the direct names of variables inside an IO group.\"\"\"\n\n        return getattr(cls._direct_names, group)\n\n    def get_group_names(self, group: str) -> Tuple[str, ...]:\n        \"\"\"Return the names of variables inside an IO group.\"\"\"\n\n        return getattr(self.names, group)\n\n    def get_var_index(self, group: str, name: str) -> int:\n        if name not in self.get_group_names(group):\n            raise KeyError(\n                f\"{name} doesnot exist in group: {group}. Valid names are {self.get_group_names(group)} \"\n            )\n        return self.get_group_names(group).index(name)\n\n    def get_var_index_in_flat(self, group: str, name: str) -> int:\n        \"\"\"Return variable index in the flat input\"\"\"\n\n        # offset before the group\n        offsets = np.cumsum([self.get_num_vars(g) for g in self._implicit_inputs])[:-1]\n        offsets = dict(zip(self._implicit_inputs, np.insert(offsets, 0, 0)))\n\n        return self.get_var_index(group=group, name=name) + offsets[group]\n\n    def get_group_indices_in_flat(self, group: str) -> np.ndarray:\n        \"\"\"Return the indices for a group of varialbes in the flat input.\"\"\"\n        return np.array(\n            [self.get_var_index_in_flat(group, n) for n in self.get_group_names(group)],\n            dtype=np.int32,\n        )\n\n    def get_num_vars(self, group: str) -> int:\n        return len(self.get_group_names(group))\n\n    # TODO: these are convenience methods. Can we dynamically generate them?\n    def get_input(self, inputs: lnp.ndarray, name: str) -> float:\n        return inputs[self.get_var_index(group=\"inputs\", name=name)]\n\n    def get_output(self, outputs: lnp.ndarray, name: str) -> float:\n        return outputs[self.get_var_index(group=\"outputs\", name=name)]\n\n    def forward_with_arrays(self, inputs):\n        inputs = _array_to_dict(self.names.inputs, inputs)\n        model_return = self.forward(inputs)\n\n        # Convert from dictionary to arrays for the outputs\n        kwargs = {\n            g: self.make_vector(g, **getattr(model_return, g))\n            for g in model_return._fields\n        }\n\n        return ArrayModelReturn(**kwargs)\n\n    @property\n    def num_inputs(self):\n        return self.get_num_vars(group=\"inputs\")\n\n    @property\n    def num_outputs(self):\n        return self.get_num_vars(group=\"outputs\")\n\n    @property\n    def num_residuals(self):\n        return self.get_num_vars(group=\"residuals\")\n\n    @property\n    def num_con_outputs(self):\n        return self.get_num_vars(group=\"con_outputs\")\n\n    def make_const_vector(self, group: str, val: float = 0.0):\n        \"\"\"Create an array of constant value representing a group.\"\"\"\n\n        return np.ones(self.get_num_vars(group=group)) * val\n\n    def make_random_vector(self, group: str):\n        \"\"\"Create a random vector representing a group\n\n        We make all the values positive for now.\n        \"\"\"\n        return np.abs(np.random.randn(self.get_num_vars(group=group)))\n\n    def _check_keys(self, group, kwargs):\n        # check missing names\n        input_set = set(kwargs.keys())\n        expected_set = set(self.get_group_names(group))\n        if not input_set == expected_set:\n            if expected_set.issubset(input_set):\n                logger.warning(\n                    f\"{input_set - expected_set} are not valid {group} names.\"\n                    \" These values are ignored.\"\n                )\n            else:\n                raise ValueError(\n                    f\"Missing {group} values for {expected_set - input_set}\"\n                )\n\n    def make_vector(self, group: str, **kwargs) -> lnp.ndarray:\n        \"\"\"Create a state vector from kwargs. All values must be provided.\"\"\"\n        self._check_keys(group, kwargs)\n        return lnp.array(list(kwargs[name] for name in self.get_group_names(group)))\n\n    def make_dict(self, group: str, **kwargs) -> Dict[str, Any]:\n        \"\"\"Create a dictionary from kwargs. All values must be provided.\n        \n        This is actually just a thing wrapper on the standard dictionary construction,\n        but it additionally checks if all the necessary keys exist\n        \"\"\"\n        self._check_keys(group, kwargs)\n        return kwargs\n\n    def make_const_dict(self, group, value: float) -> Dict[str, Any]:\n        \"\"\"Create a dictionary for a group filled with constant values.\"\"\"\n        return {n: value for n in self.get_group_names(group)}\n\n    def plot(self, *args, **kwargs):\n        raise NotImplementedError\n\n\nclass StateSpaceModel(Model):\n    \"\"\"Compare to a standard model, now we have states.\"\"\"\n\n    # We name the inputs to the system simply \"inputs\" instead of \"controls\" in control\n    # literature. This is so that StateSpaceModel can be naturally seen as a child of\n    # the standard Model, where the only difference is the addition of states.\n\n    # TODO: maybe we need a better name for this as this is now only used for the\n    # flat input calls which is then used in ocp\n    # Maybe explicit_inputs, and implicit_inputs? But for explicit formulation, we also\n    # need the outputs defined, so it's not just 'inputs'\n    _implicit_inputs: Tuple[str, str, str, str] = (\n        \"states\",\n        \"inputs\",\n        \"states_dot\",\n        \"con_outputs\",\n    )\n\n    def __init__(\n        self, params: Dict[str, Any] = {}, model_config: Dict[str, Any] = {},\n    ):\n        super().__init__(model_config=model_config, params=params)\n        self._check_names()\n\n    @abstractmethod\n    def forward(\n        self, states: lnp.ndarray, inputs: lnp.ndarray, mesh: float\n    ) -> StateSpaceModelReturn:\n        \"\"\"The canonical form.\n\n        x_dot = f(x, u, t, p)\n        y     = g(x, u, t, p)\n        \"\"\"\n        pass\n\n    def apply_and_forward(self, states, inputs, mesh, params):\n        self.set_recursive_params(params)\n        return self.forward(states, inputs, mesh)\n\n    def apply_and_forward_with_arrays(self, states, inputs, mesh, params):\n        self.set_recursive_params(params)\n        return self.forward_with_arrays(states, inputs, mesh)\n\n    def make_state_space_model_return(\n        self,\n        states_dot: lnp.ndarray,\n        outputs: lnp.ndarray = None,\n        residuals: lnp.ndarray = None,\n    ) -> StateSpaceModelReturn:\n        \"\"\"Thin wrapper for StateSpaceModelReturn to handle con_outputs automatically.\"\"\"\n        kwargs = {\"states_dot\": states_dot}\n        if outputs is not None:\n            kwargs[\"outputs\"] = outputs\n\n        if residuals is not None:\n            kwargs[\"residuals\"] = residuals\n\n        return StateSpaceModelReturn(**kwargs)\n\n    def _construct_io_names(self):\n        \"\"\"Create model io names while also taking into account submodels compositoin.\n        \n        Similar to Model._construct_io_names, but now needs to operate on more groups\n        for state space model.\n        \"\"\"\n\n        self.names = StateSpaceIO(\n            inputs=self._direct_names.inputs,\n            states=self._direct_names.states,\n            states_dot=self._direct_names.states_dot,\n            con_outputs=self._direct_names.con_outputs,\n            residuals=self._direct_names.residuals,\n            outputs=self._direct_names.outputs\n            + tuple(self._collect_children_outputs()),\n        )\n\n    def _check_names(self):\n        # Ensure con_outputs all exist\n        for c in self.get_group_names(\"con_outputs\"):\n            if c not in self.get_group_names(\"outputs\"):\n                raise ValueError(f\"constraint outputs {c} not found in outputs\")\n\n    def _extract_con_outputs(self, outputs: Dict[str, Any]) -> Dict[str, Any]:\n        return {c: outputs[c] for c in self.get_group_names(\"con_outputs\")}\n\n    @property\n    def num_implicit_res(self):\n        return self.num_states + self.num_con_outputs + self.num_residuals\n\n    @property\n    def num_implicit_var(self):\n        return sum([self.get_num_vars(g) for g in self._implicit_inputs])\n\n    @property\n    def num_states(self):\n        return self.get_num_vars(group=\"states\")\n\n    def get_state(self, states: lnp.ndarray, name: str) -> float:\n        return states[self.get_var_index(group=\"states\", name=name)]\n\n    def forward_with_arrays(self, states, inputs, mesh):\n\n        states = _array_to_dict(self.names.states, states)\n        inputs = _array_to_dict(self.names.inputs, inputs)\n        model_return = self.forward(states, inputs, mesh)\n\n        # Convert from dictionary to arrays for the outputs\n        kwargs = {\n            g: self.make_vector(g, **getattr(model_return, g))\n            for g in model_return._fields\n            if g != \"con_outputs\"\n        }\n\n        kwargs[\"con_outputs\"] = self.make_vector(\n            \"con_outputs\", **self._extract_con_outputs(model_return.outputs)\n        )\n\n        return ArrayStateSpaceModelReturn(**kwargs)\n\n    def implicit(\n        self,\n        states: lnp.ndarray,\n        inputs: lnp.ndarray,\n        states_dot: lnp.ndarray,\n        con_outputs: lnp.ndarray,\n        mesh: float,\n    ) -> lnp.ndarray:\n        \"\"\"Implicit form: f(x, u, t, x_dot, y, p) = 0\n\n        This is the base class method for models with a forward method to be turned into\n        an implicit model.\n\n        For models that are really implicit, the user should implement the implicit form\n        directly.\n\n        the order of the outputs should be: [states_dot, con_outputs, residuals]. This\n        is a hard-coded limitation of the current design.\n        \"\"\"\n\n        model_return = self.forward_with_arrays(states, inputs, mesh)\n\n        # TODO: here we return an array, but maybe we should at least always check\n        # (especially for user-defined ones) that the residual size is correct.\n        #\n        # TODO: maybe we should also refer to constraints by name, just like what we did\n        # for the decision variables.\n\n        # Assemble scaled residuals. We could move scales outside of the residual\n        # functions so the scales are no longer compiled into the residual calls. But\n        # that would require manually scaling the jacobian and hessian as well -- Doable\n        # but not necessary for now.\n\n        res = lnp.vector_concat(\n            [\n                model_return.states_dot - states_dot,\n                model_return.con_outputs - con_outputs,\n                model_return.residuals,\n            ]\n        )\n        return res\n\n    def _split_flat_vars(self, flat_vars: lnp.ndarray):\n        split_indices = list(\n            np.cumsum([self.get_num_vars(g) for g in self._implicit_inputs])[:-1]\n        )\n        list_vars = lnp.vector_split(flat_vars, split_indices)\n\n        return dict(zip(self._implicit_inputs, list_vars))\n\n    def _apply_and_flat_implicit(\n        self, flat_vars: lnp.ndarray, mesh: float, params,\n    ) -> lnp.ndarray:\n        self.set_recursive_params(params)\n        dict_vars = self._split_flat_vars(flat_vars)\n\n        return self.implicit(**dict_vars, mesh=mesh)\n\n    def _implicit_jac(self, flat_vars, mesh, params):\n        raise NotImplementedError(\n            \"_implicit_jac and _implicit_jacobianstructure needs to be implemented to \"\n            \"use custom jacobians\"\n        )\n\n    def _implicit_jacobianstructure(self):\n        raise NotImplementedError(\n            \"_implicit_jac and _implicit_jacobianstructure needs to be implemented to \"\n            \"use custom jacobians\"\n        )\n\n    def _implicit_hess(self, flat_vars, mesh, params, mult):\n        raise NotImplementedError(\n            \"_implicit_hess and _implicit_hessianstructure needs to be implemented to \"\n            \"use custom hessian\"\n        )\n\n    def _implicit_hessianstructure(self):\n        raise NotImplementedError(\n            \"_implicit_hess and _implicit_hessianstructure needs to be implemented to \"\n            \"use custom hessian\"\n        )\n\n    def batched_forward(\n        self,\n        states: lnp.ndarray,\n        inputs: lnp.ndarray,\n        mesh: float,\n        params: Optional[Dict[str, Any]] = None,\n    ) -> StateSpaceModelReturn:\n        return self._batched_forward(states, inputs, mesh, params)\n\n    def make_model_algebra_cons(self, backend: str):\n        \"\"\"Create the model_algebra constraints that are needed for the OCP.\n\n        FIXME: currently we also require this function to formulate the _batched_forward\n        function, which we should probaly consider moving somewhere else.\n        \"\"\"\n        if backend == \"casadi\":\n            self._make_casadi_model_algebra_cons()\n        elif backend == \"jax\":\n            self._make_jax_model_algebra_cons()\n        elif backend == \"custom\":\n            self._make_custom_model_algebra_cons()\n        else:\n            raise ValueError(\n                f\"{backend} is not supported. Only 'jax', 'casadi' and 'custom' backends are supported.\"\n            )\n\n    def _model_algebra_jacobianstructure(self):\n        \"\"\"A pessimistic estimate for the jacobian structure of model algebra.\n\n        NOTE: Here we rely on a few dangerous assumptions:\n        1) the implicit form is a explicit turned into implicit (see model.implicit),\n        with states_dot and con_outputs only acting as linear variables.\n        2) the ordering of constraints are assumed to be defined by self.implicit\n\n        TODO: if we really want to, we could use casadi to get the symbolic jac struct\n        and then apply it to jax functions (and potentially other backend).\n        \"\"\"\n        # states and inputs are involved in all constraints\n        # FIXME: this relies on the ordering of the constraints\n        rows = np.stack(\n            [np.arange(self.num_implicit_res)] * (self.num_states + self.num_inputs)\n        ).T.ravel()\n        cols = np.stack(\n            [\n                np.concatenate(\n                    [\n                        self.get_group_indices_in_flat(\"states\"),\n                        self.get_group_indices_in_flat(\"inputs\"),\n                    ]\n                )\n            ]\n            * self.num_implicit_res\n        ).ravel()\n\n        # states_dot part\n        # FIXME: this relies on both the ordering of the constraints and the variables\n        states_dot_rows = np.arange(self.num_states)\n        states_dot_cols = self.get_group_indices_in_flat(\"states_dot\")\n\n        # con_outputs part\n        # FIXME: this relies on both the ordering of the constraints and the variables\n        con_outputs_rows = self.num_states + np.arange(self.num_con_outputs)\n        con_outputs_cols = self.get_group_indices_in_flat(\"con_outputs\")\n\n        rows = np.concatenate([rows, states_dot_rows, con_outputs_rows])\n        cols = np.concatenate([cols, states_dot_cols, con_outputs_cols])\n\n        return rows, cols\n\n    def _model_algebra_hessianstructure(self):\n        \"\"\"A pessimistic estimate for the hessian structure of model algebra.\n\n        NOTE: states_dot and con_outputs are only linear, so no hessian entries for\n        them, but for truely implicit equations where states_dot or con_outputs are\n        algebraic variables they could become nonlinear! But in those case, the\n        condensed approach also won't work. (because it has no explicit ODE to work on)\n\n        TODO: if we really want to, we could use casadi to get the symbolic jac struct\n        and then apply it to jax functions (and potentially other backend).\n        \"\"\"\n\n        rows, cols = np.nonzero(np.ones((self.num_implicit_var, self.num_implicit_var)))\n\n        # remove those related to states_dot and con_outputs\n        idx_remove = np.hstack(\n            [\n                self.get_group_indices_in_flat(\"states_dot\"),\n                self.get_group_indices_in_flat(\"con_outputs\"),\n            ]\n        )\n\n        keep_rows = np.array([r not in idx_remove for r in rows])\n        keep_cols = np.array([c not in idx_remove for c in cols])\n        keep = keep_rows & keep_cols\n\n        return rows[keep], cols[keep]\n\n    def _make_jax_model_algebra_cons(self):\n        # For jax, we rely on jac and hessian to compute the constraints at a later\n        # stage. See JaxConstraints\n        implicit_functions = {\n            \"constraints\": self._apply_and_flat_implicit,\n        }\n\n        # TODO: _stage_hessianstructure not yet implemented\n        self.model_algebra = JaxConstraints(\n            num_in=self.num_implicit_var,\n            num_con=self.num_implicit_res,\n            **implicit_functions,\n            jacobian_structure=self._model_algebra_jacobianstructure(),\n            hessian_structure=self._model_algebra_hessianstructure(),\n        )\n\n        # FIXME: handle batched_forward better\n        self._batched_forward = lnp.use_backend(\"jax\")(\n            jit(vmap(self.apply_and_forward_with_arrays, in_axes=[0, 0, 0, None]))\n        )\n\n    def _make_custom_model_algebra_cons(self):\n        implicit_functions = {\n            \"constraints\": self._apply_and_flat_implicit,\n            \"jacobian\": self._implicit_jac,\n            \"jacobian_structure\": self._implicit_jacobianstructure(),\n            \"hessian\": self._implicit_hess,\n            \"hessian_structure\": self._implicit_hessianstructure(),\n        }\n\n        self.model_algebra = MappedConstraints(\n            num_in=self.num_implicit_var,\n            num_con=self.num_implicit_res,\n            **implicit_functions,\n        )\n\n        def custom_batched_forward(_states, _inputs, _mesh, _params):\n            self.set_recursive_params(_params)\n            out = lnp.lmap(self.forward)(_states, _inputs, _mesh)\n            return StateSpaceModelReturn(*out)\n\n        self._batched_forward = custom_batched_forward\n\n    def _make_casadi_model_algebra_cons(self, CasType: type = cas.MX):\n        # NOTE: for large linear operations, like those in FC layers, MX is much faster\n        # than SX both for compilation and executtion\n        params = self.get_recursive_params()\n        flat_params, unravel = params.tree_ravel()\n\n        cas_flat_params = CasType.sym(\"params\", len(flat_params))\n        cas_dict_params = unravel(cas_flat_params)\n\n        mesh = CasType.sym(\"distance\")\n        states = CasType.sym(\"states\", self.num_states)\n        inputs = CasType.sym(\"inputs\", self.num_inputs)\n        stage_vars = CasType.sym(\"stage_vars\", self.num_implicit_var)\n        mult = CasType.sym(\"mult\", self.num_implicit_res)\n\n        # Only the model calls need to go inside the context manager.\n        with lnp.use_backend(\"casadi\"):\n            model_return = self.apply_and_forward_with_arrays(\n                states, inputs, mesh, cas_dict_params\n            )\n            res = self._apply_and_flat_implicit(stage_vars, mesh, cas_dict_params)\n            lagrange = lnp.dot(mult, res)\n\n        jac = cas.jacobian(res, stage_vars)\n        lagrange_hessian, lagrange_gradient = cas.hessian(lagrange, stage_vars)\n\n        # Generate code\n        filename = \"nlpfunctions\"\n        cfile = filename + \".c\"\n        # FIXME: path management, currently local directory only\n        codegen = cas.CodeGenerator(cfile)\n\n        codegen.add(\n            cas.Function(\n                \"forward\", [states, inputs, mesh, cas_flat_params], [*model_return]\n            )\n        )\n        codegen.add(\n            cas.Function(\"implicit_con\", [stage_vars, mesh, cas_flat_params], [res])\n        )\n        codegen.add(\n            cas.Function(\"implicit_jac\", [stage_vars, mesh, cas_flat_params], [jac])\n        )\n        codegen.add(\n            cas.Function(\n                \"implicit_hess\",\n                [stage_vars, mesh, cas_flat_params, mult],\n                [lagrange_hessian],\n            )\n        )\n        codegen.generate()\n\n        logger.info(f\"Generated c-code with {getsize(cfile)} lines: \")\n        # Call compiler if no library exists already\n        with open(cfile, \"rb\") as f:\n            file_hash = hashlib.md5()\n            for chunk in iter(lambda: f.read(8192), b\"\"):\n                file_hash.update(chunk)\n\n        library_name = file_hash.hexdigest()\n        library_path = \"./\" + library_name + \".so\"\n\n        if exists(library_path):\n            logger.info(f\"{library_path} already exists, no compliation is needed.\")\n        else:\n            logger.info(f\"Compiling casadi library {library_path}\")\n            cmd = [\"gcc\", \"-fPIC\", \"-o2\", \"-shared\", cfile, \"-o\", library_path]\n            p = subprocess.Popen(cmd)\n            p.wait()\n\n        # Wrap the functions to take in dict params\n        # FIXME: fixed thread number\n        _mapped_forward = lnp.cmap(\n            cas.external(\"forward\", library_path),\n            num_workers=32,\n            in_axes=[0, 0, 0, None],\n        )\n\n        def cas_batched_forward(_states, _inputs, _mesh, _params):\n            _flat_params, _ = _params.tree_ravel()\n            out = _mapped_forward(_states, _inputs, _mesh, _flat_params)\n            return StateSpaceModelReturn(*out)\n\n        self._batched_forward = cas_batched_forward\n\n        # add sparsity structure\n        # Can we not get this from the symbolic SX? eg, jac.sparsity(), but then what?\n        # This get_triplet interface almost looks like a bug...\n        # [*row_indices, [*col_indices]] is what is returned\n        # see: http://casadi.sourceforge.net/api/html/d5/da8/classcasadi_1_1Sparsity.html#a1f3eed93488c3cf121f47bec4956927f\n        *jac_rows, jac_cols = jac.sparsity().get_triplet()\n        *hess_rows, hess_cols = lagrange_hessian.sparsity().get_triplet()\n\n        implicit_functions = {\n            \"constraints\": cas.external(\"implicit_con\", library_path),\n            \"jacobian\": cas.external(\"implicit_jac\", library_path),\n            \"hessian\": cas.external(\"implicit_hess\", library_path),\n            \"jacobian_structure\": (np.array(jac_rows), np.array(jac_cols)),\n            \"hessian_structure\": (np.array(hess_rows), np.array(hess_cols)),\n        }\n\n        self.model_algebra = CasConstraints(\n            num_in=self.num_implicit_var,\n            num_con=self.num_implicit_res,\n            **implicit_functions,\n        )\n\n    def export_c_mex(self, cfile: str, CasType: type = cas.MX):\n        \"\"\"Export a state space model into c-code that is ready for mex.\n\n        The exported function has the following API:\n\n        states_dot, outputs, con_outputs, residuals = function(states, inputs, mesh, params)\n        where each I/O is an array of the corresponding size.\n\n        Args:\n            cfile (str): path of the c-file for export, includg .c extension. Limited to\n                current working directory only.\n            CasType (type, optional): casadi type to use, SX or MX. Defaults to MX.\n\n        \"\"\"\n        # FIXME: path management, currently local directory only, which is a limitation\n        # that comes from casadi\n        params = self.get_recursive_params()\n        flat_params, unravel = params.tree_ravel()\n\n        cas_flat_params = CasType.sym(\"params\", len(flat_params))\n        cas_dict_params = unravel(cas_flat_params)\n\n        mesh = CasType.sym(\"distance\")\n        states = CasType.sym(\"states\", self.num_states)\n        inputs = CasType.sym(\"inputs\", self.num_inputs)\n\n        # Only the model calls need to go inside the context manager.\n        with lnp.use_backend(\"casadi\"):\n            model_return = self.apply_and_forward_with_arrays(\n                states, inputs, mesh, cas_dict_params\n            )\n\n        # Generate code\n        codegen = cas.CodeGenerator(cfile, dict(mex=True, main=True))\n\n        codegen.add(\n            cas.Function(\n                \"forward\", [states, inputs, mesh, cas_flat_params], [*model_return]\n            )\n        )\n\n        codegen.generate()\n\n        # Need to set the parameters back to the original params, as they were replaced\n        # with casadi variables during the apply_and_forward_with_arrays\n        # TODO: the same also happens to other casadi export and also jax tracing right?\n        # Can we generalize this problem?\n        self.set_recursive_params(params)\n", "meta": {"hexsha": "eaf6acdbdfb38e9670dbea83acd93cb2590f2d76", "size": 30010, "ext": "py", "lang": "Python", "max_stars_repo_path": "lumos/models/base.py", "max_stars_repo_name": "numagic/lumos", "max_stars_repo_head_hexsha": "f729354613fec84957384323da6d0b69e00ed7cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-15T14:25:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T14:25:23.000Z", "max_issues_repo_path": "lumos/models/base.py", "max_issues_repo_name": "numagic/lumos", "max_issues_repo_head_hexsha": "f729354613fec84957384323da6d0b69e00ed7cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lumos/models/base.py", "max_forks_repo_name": "numagic/lumos", "max_forks_repo_head_hexsha": "f729354613fec84957384323da6d0b69e00ed7cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.049382716, "max_line_length": 123, "alphanum_fraction": 0.6385871376, "include": true, "reason": "import numpy,from jax", "num_tokens": 6559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.38121955219593834, "lm_q1q2_score": 0.1980516857108188}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nsRGB Colourspace\n================\n\nDefines the *sRGB* colourspace:\n\n-   :attr:`colour.models.RGB_COLOURSPACE_sRGB`.\n\nReferences\n----------\n-   :cite:`InternationalElectrotechnicalCommission1999a` : International\n    Electrotechnical Commission. (1999). IEC 61966-2-1:1999 - Multimedia\n    systems and equipment - Colour measurement and management - Part 2-1:\n    Colour management - Default RGB colour space - sRGB (p. 51).\n    https://webstore.iec.ch/publication/6169\n-   :cite:`InternationalTelecommunicationUnion2015i` : International\n    Telecommunication Union. (2015). Recommendation ITU-R BT.709-6 - Parameter\n    values for the HDTV standards for production and international programme\n    exchange BT Series Broadcasting service (pp. 1-32).\n    https://www.itu.int/dms_pubrec/itu-r/rec/bt/\\\nR-REC-BT.709-6-201506-I!!PDF-E.pdf\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\n\nfrom colour.colorimetry import CCS_ILLUMINANTS\nfrom colour.models.rgb import RGB_Colourspace, eotf_inverse_sRGB, eotf_sRGB\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2020 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-developers@colour-science.org'\n__status__ = 'Production'\n\n__all__ = [\n    'PRIMARIES_sRGB', 'WHITEPOINT_NAME_sRGB', 'CCS_WHITEPOINT_sRGB',\n    'MATRIX_sRGB_TO_XYZ', 'MATRIX_XYZ_TO_sRGB', 'RGB_COLOURSPACE_sRGB'\n]\n\nPRIMARIES_sRGB = np.array([\n    [0.6400, 0.3300],\n    [0.3000, 0.6000],\n    [0.1500, 0.0600],\n])\n\"\"\"\n*sRGB* colourspace primaries.\n\nPRIMARIES_sRGB : ndarray, (3, 2)\n\"\"\"\n\nWHITEPOINT_NAME_sRGB = 'D65'\n\"\"\"\n*sRGB* colourspace whitepoint name.\n\nCCS_WHITEPOINT_sRGB : unicode\n\"\"\"\n\nCCS_WHITEPOINT_sRGB = (CCS_ILLUMINANTS['CIE 1931 2 Degree Standard Observer'][\n    WHITEPOINT_NAME_sRGB])\n\"\"\"\n*sRGB* colourspace whitepoint chromaticity coordinates.\n\nCCS_WHITEPOINT_sRGB : ndarray\n\"\"\"\n\nMATRIX_sRGB_TO_XYZ = np.array([\n    [0.4124, 0.3576, 0.1805],\n    [0.2126, 0.7152, 0.0722],\n    [0.0193, 0.1192, 0.9505],\n])\n\"\"\"\n*sRGB* colourspace to *CIE XYZ* tristimulus values matrix.\n\nMATRIX_sRGB_TO_XYZ : array_like, (3, 3)\n\"\"\"\n\nMATRIX_XYZ_TO_sRGB = np.array([\n    [3.2406, -1.5372, -0.4986],\n    [-0.9689, 1.8758, 0.0415],\n    [0.0557, -0.2040, 1.0570],\n])\n\"\"\"\n*CIE XYZ* tristimulus values to *sRGB* colourspace matrix.\n\nMATRIX_XYZ_TO_sRGB : array_like, (3, 3)\n\"\"\"\n\nRGB_COLOURSPACE_sRGB = RGB_Colourspace(\n    'sRGB',\n    PRIMARIES_sRGB,\n    CCS_WHITEPOINT_sRGB,\n    WHITEPOINT_NAME_sRGB,\n    MATRIX_sRGB_TO_XYZ,\n    MATRIX_XYZ_TO_sRGB,\n    eotf_inverse_sRGB,\n    eotf_sRGB,\n)\nRGB_COLOURSPACE_sRGB.__doc__ = \"\"\"\n*sRGB* colourspace.\n\nReferences\n----------\n:cite:`InternationalElectrotechnicalCommission1999a`,\n:cite:`InternationalTelecommunicationUnion2015i`\n\nRGB_COLOURSPACE_sRGB : RGB_Colourspace\n\"\"\"\n", "meta": {"hexsha": "6ac9d2e23e75d1033ee504e564bdf981305df283", "size": 2892, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/models/rgb/datasets/srgb.py", "max_stars_repo_name": "wenh06/colour", "max_stars_repo_head_hexsha": "445fdad2711ae39c95b4375166905568d24a95f4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-09T01:53:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T01:53:40.000Z", "max_issues_repo_path": "colour/models/rgb/datasets/srgb.py", "max_issues_repo_name": "wenh06/colour", "max_issues_repo_head_hexsha": "445fdad2711ae39c95b4375166905568d24a95f4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/models/rgb/datasets/srgb.py", "max_forks_repo_name": "wenh06/colour", "max_forks_repo_head_hexsha": "445fdad2711ae39c95b4375166905568d24a95f4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8214285714, "max_line_length": 78, "alphanum_fraction": 0.7209543568, "include": true, "reason": "import numpy", "num_tokens": 920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.3040416686603661, "lm_q1q2_score": 0.19803901994311407}}
{"text": "# Functions needed to run Excalibur\n# Data munging in separate file\nfrom os.path import basename\nimport numpy as np\nfrom astropy.time import Time\nfrom scipy import interpolate, optimize\nfrom tqdm.auto import trange\n\nimport warnings\nwarnings.simplefilter('ignore', np.RankWarning)\n\n\n###########################################################\n# PCA Patching\n###########################################################\n\ndef pcaPatch(x_values, mask, K=2, num_iters=50):\n    \"\"\"\n    Iterative PCA patching, where bad values are replaced\n    with denoised values.\n    \n    Parameters\n    ----------\n    x_values : 2D array\n        List of values we want to denoise\n    mask : 2D array\n        Mask for x_values that is true for values that\n        we would like to denoise\n    K : int, optional (default: 2)\n        Number of principal components used for denoising\n    num_iters : int, optional (default: 50)\n        Number of iterations to run iterative PCA patching\n    \n    Returns\n    -------\n    x_values : 2D ndarray\n        x_values with bad values replaced by denoised values\n    mean_x_values : 2D ndarray\n        Mean of x_values over all exposures.\n        Used as fiducial model of line positions\n        PCA is done over deviations from this fiducial model\n    denoised_xs : 2D ndarray\n        Denoised x values from PCA reconstruction\n    uu, ss, vv : ndarrays\n        Arrays from single value decomposition.  Used to \n        reconstruct principal components and their corresponding\n        coefficients\n    \"\"\"\n    K = int(K)\n    \n    for i in range(num_iters):\n        # There should be no more NaN values in x_values\n        assert np.sum(np.isnan(x_values)) == 0\n        # Redefine mean\n        mean_x_values = np.mean(x_values,axis=0)\n        \n        # Run PCA\n        uu,ss,vv = np.linalg.svd(x_values-mean_x_values, full_matrices=False)\n\n        # Repatch bad data with K PCA reconstruction\n        denoised_xs = mean_x_values + np.dot((uu*ss)[:,:K],vv[:K])\n        x_values[mask] = denoised_xs[mask]\n    \n    return x_values, mean_x_values, denoised_xs, uu, ss, vv\n\n\ndef patchAndDenoise(x_values, orders, waves,\n                    x_errors=None, times=None, file_list=None,\n                    K=2, num_iters=50, running_window=9,\n                    line_cutoff=0.5, file_cutoff=0.5,\n                    outlier_cut=0, verbose=False):\n    \"\"\"\n    - Vet for bad lines/exposures\n    - Initial patch of bad data with running mean\n    - Iterative patch with PCA for specified number of iterations\n    - Optional second round of interative PCA patching to catch outliers\n    \n    \n    Parameters\n    ----------\n    x_values, x_errors : 2D ndarray\n        Array of line positions for all lines for each exposure and errors\n    orders : 1D ndarray\n        Array of orders for each line\n    waves : 1D ndarray\n        Array of wavelengths for each line\n    times : 1D ndarray, optional\n        Time stamps for each exposure\n        Just written into the returned patch dictionary\n        (not explicitely used for this code, but helps with evalWaveSol)\n    K : int, optional (default: 2)\n        Number of principal components used for denoising\n    num_iters : int, optional (default: 50)\n        Number of iterations to run iterative PCA patching\n    running_window ; int, optional (default: 9)\n        Window size of running mean used to initialize pixel values\n        for lines missing measured pixel values\n    line_cutoff, file_cutoff : float [0,1], optional (default: 0.5)\n        Cutoff for bad lines or files, respectively.\n        i.e. defaults cut lines that show up in less than 50% of exposure\n        and files that contain less than 50% of all lines\n    outlier_cut : float, optional (default: 0)\n        Sigma cut used to identify outliers following first round of\n        iterative PCA.\n        Note: 0 means this process isn't done.\n    \n    Returns\n    -------\n    patch : dict\n        Dictionary containing all the useful information from this process\n        (among, very many uselss information!)\n        Needed for evalWaveSol function\n    \"\"\"\n    # Arrays that aren't needed, but are helpful to have in returned dictionary\n    if times is None:\n        times = np.zeros_like(file_list)\n    if x_errors is None:\n        x_errors = np.zeros_like(x_errors)\n    if file_list is None:\n        file_list = np.zeros_like(times)\n    \n    ### Vetting\n    # Find where there is no line information\n    x_values[np.nan_to_num(x_values) < 1] = np.nan\n    \n    # Mask out of order lines\n    out_of_order = np.zeros_like(x_values,dtype=bool)\n    for m in np.unique(orders):\n        I = orders==m\n        wave_sort = np.argsort(waves[I])\n        for i, exp in enumerate(x_values):\n            exp_sort = exp[I][wave_sort]\n            exp_diff = np.diff(exp_sort)\n            left_diff = np.insert(exp_diff<0,0,False)\n            right_diff = np.append(exp_diff<0,False)\n            exp_mask = np.logical_or(left_diff,right_diff)\n            out_of_order[i,I] = exp_mask.copy()\n    x_values[out_of_order] = np.nan\n    if verbose:\n        num_bad = np.sum(out_of_order)\n        num_total = out_of_order.size\n        print('{:.3}% of lines masked'.format(\n             (num_bad)/num_total*100))\n            \n    # Get rid of bad lines\n    good_lines = np.mean(np.isnan(x_values),axis=0) < line_cutoff\n    # Trim everything\n    orders = orders[good_lines]\n    waves  = waves[good_lines]\n    x_values = x_values[:,good_lines]\n    x_errors = x_errors[:,good_lines]\n    if verbose:\n        num_good = np.sum(good_lines)\n        num_total = good_lines.size\n        print('{} of {} lines cut ({:.3}%)'.format(\n            (num_total - num_good),num_total,\n            (num_total - num_good)/num_total*100))\n    \n    # Get rid of bad files\n    good_files = np.mean(np.isnan(x_values),axis=1) < file_cutoff\n    # Trim everything\n    x_values = x_values[good_files]\n    x_errors = x_errors[good_files]\n    file_names = file_list[good_files]\n    file_times = times[good_files]\n    if verbose:\n        num_good = np.sum(good_files)\n        num_total = good_files.size\n        print('{} of {} files cut ({:.3}%)'.format(\n            (num_total - num_good),num_total,\n            (num_total - num_good)/num_total*100))\n        print('Files that were cut:')\n        print(file_list[~good_files])\n    \n    ### Patching\n    # Initial patch of bad data with mean\n    bad_mask = np.isnan(x_values) # mask to identify patched x_values\n    if running_window > 0:\n        half_size = int(running_window//2)\n        counter = 6\n        while np.sum(np.isnan(x_values)) > 0:\n            for i in range(x_values.shape[0]):\n                # Identify files in window\n                file_range = [max((i-half_size,0)), min((i+half_size+1,x_values.shape[1]))]\n                # Find mean of non-NaN values\n                run_med = np.nanmean(x_values[file_range[0]:file_range[1],:],axis=0)\n                # Patch NaN values with mean for center file\n                x_values[i][bad_mask[i,:]] = run_med[bad_mask[i,:]]\n            counter -= 1\n            if counter < 0:\n                print(\"Persistant NaNs with running mean.\")\n                print(\"Replacing remaining NaNs with global mean.\")\n                tot_mean = np.nanmean(x_values,axis=0)[None,...]*np.ones_like(x_values)\n                x_values[np.isnan(x_values)] = tot_mean[np.isnan(x_values)]\n                break\n    else: # don't bother with running mean\n        mean_values = np.nanmean(x_values,axis=0)\n        mean_patch = np.array([mean_values for _ in range(x_values.shape[0])])\n        x_values[bad_mask] = mean_patch[bad_mask]\n    \n    # Iterative PCA\n    pca_results = pcaPatch(x_values, bad_mask, K=K, num_iters=num_iters)\n    x_values, mean_x_values, denoised_xs, uu, ss, vv = pca_results\n    \n    # Mask line center outliers\n    if outlier_cut > 0:\n        x_resids  = x_values-denoised_xs\n        out_mask  = abs(x_resids-np.mean(x_resids)) > (outlier_cut*np.nanstd(x_resids))\n        if verbose:\n            num_out = np.sum(out_mask)\n            num_total = out_mask.size\n            num_bad = np.sum(np.logical_and(out_mask,bad_mask))\n            print('{:.3}% of lines marked as Outliers'.format(\n                 (num_out)/num_total*100))\n            print('{:.3}% of lines marked as Outliers that were PCA Patched'.format(\n                 (num_bad)/num_total*100))\n        pca_results = pcaPatch(x_values, np.logical_or(bad_mask,out_mask),\n                               K=K, num_iters=num_iters)\n        x_values, mean_x_values, denoised_xs, uu, ss, vv = pca_results\n    \n    # Load in all relevant information into dictionary\n    patch_dict = {}\n    patch_dict['K'] = K\n    # Exposure Information\n    patch_dict['files']  = file_names.copy()\n    patch_dict['times']  = file_times.copy()\n    min_date = Time(file_times.min(),format='mjd').isot.split('T')[0]\n    yr, mn, dy = min_date.split('-')\n    patch_dict['min_date'] = yr[2:]+mn+dy\n    min_date = Time(file_times.max(),format='mjd').isot.split('T')[0]\n    yr, mn, dy = min_date.split('-')\n    patch_dict['max_date'] = yr[2:]+mn+dy\n    # Line Information\n    patch_dict['orders'] = orders.copy()\n    patch_dict['waves']  = waves.copy()\n    # Line Measurement Information\n    patch_dict['x_values'] = x_values.copy()\n    patch_dict['x_errors'] = x_errors.copy()\n    patch_dict['denoised_xs'] = denoised_xs.copy()\n    patch_dict['mean_xs']  = mean_x_values.copy()\n    patch_dict['bad_mask'] = bad_mask.copy()\n    # PCA Information\n    patch_dict['u'] = uu.copy()\n    patch_dict['s'] = ss.copy()\n    patch_dict['v'] = vv.copy()\n    patch_dict['ec'] = (uu*ss)[:,:K]\n    # Outlier Information\n    if outlier_cut > 0:\n        patch_dict['out_mask'] = out_mask.copy()\n    \n    return patch_dict\n\n# Functions for recovering the date of an exposure\ndef isot2date(isot_time):\n    yr, mn, dy = isot_time.split('T')[0].split('-')\n    return str(int(yr[2:]+mn+dy))\n\ndef mjds2dates(times):\n    return np.array([isot2date(Time(t, format='mjd').isot) for t in times]).astype(str)\n\ndef files2dates(files):\n    dates = []\n    for file_name in files:\n        date = basename(file_name).split('_')[-1].split('.')[0]\n        dates.append(date)\n    return np.array(dates).astype(str)\n\ndef interpPCA(new_interps, patch_dict, intp_deg=1, interp_key='times'):\n    \"\"\"\n    Interpolate eigen coefficients with respect to chosen interp_key.\n    \n    Parameters\n    ----------\n    new_interps : 1D array or float\n        New values for which we want principal component coefficients\n    patch_dict : dictionary\n        Result of patchAndDenoise function\n    intp_deg : int, optional (default: 1)\n        Degree of inteprolation\n    interp_key : str, optional (default: 'times')\n        Key in patch_dict of value we want to interpolate the principal\n        component coeficients with respect to.\n    \n    Returns\n    -------\n    denoised_xs : 1D ndarray\n        Pixel positions for calibration lines defined by order and \n        wavelength in the provided patch.\n    \"\"\"\n    try:\n        len(new_interps)\n        unravel = False\n    except TypeError:\n        new_interps = [new_interps]\n        unravel = True\n    K  = patch_dict['K']\n    vv = patch_dict['v']\n    \n    # Set up nightly code if needed\n    if intp_deg=='poly':\n        new_dates = mjds2dates(new_interps)\n        cal_dates = files2dates(patch_dict['files'])\n    \n    # Interpolate eigen coefficients\n    new_ecs = np.empty((len(new_interps),K),dtype=float)\n    for i in range(K):\n        if intp_deg=='poly':\n            for date in np.unique(new_dates):\n                new_date_mask = new_dates==date\n                cal_date_mask = cal_dates==date\n                if np.sum(cal_date_mask) < 5:\n                    continue\n                \n                z = np.polyfit(patch_dict['times'][cal_date_mask][3:],\n                               patch_dict['ec'][cal_date_mask][3:,i],3)\n                new_ecs[new_date_mask,i] = np.poly1d(z)(new_interps[new_date_mask])\n        \n        elif intp_deg==0:\n            # Find nearest time for each time\n            # IS THERE A WAY TO DO THIS NOT ONE BY ONE???\n            for i_idx, i in enumerate(new_interps):\n                idx = np.abs(patch_dict[interp_key]-i).argmin()\n                new_ecs[i_idx,i] = patch_dict['ec'][idx,i]\n            \n        elif intp_deg==1: # Default\n            f = interpolate.interp1d(patch_dict[interp_key],patch_dict['ec'][:,i],kind='linear',\n                                 bounds_error=False,fill_value=np.nan)\n            new_ecs[:,i] = f(new_interps)\n            \n        elif intp_deg==3:\n            f = interpolate.interp1d(patch_dict[interp_key],patch_dict['ec'][:,i],kind='cubic',\n                                 bounds_error=False,fill_value=np.nan)\n            new_ecs[:,i] = f(new_interps)\n            \n        else:\n            tck = interpolate.splrep(patch_dict[interp_key],patch_dict['ec'][:,i],k=interp_deg)\n            new_ecs[:,i] = interpolate.splev(new_interps,tck)\n            \n    # Construct x values for that period of time\n    denoised_xs = np.dot(new_ecs,vv[:K]) + patch_dict['mean_xs']\n    \n    if unravel:\n        return denoised_xs[0]\n    else:\n        return denoised_xs\n\n\n###########################################################\n# Interpolation Code\n###########################################################\n\ndef interpWaveSol(newx, newm, x, m, data, interp_deg='pchip'):\n    \"\"\"\n    Interpolate from known lines to construct a wavelength solution\n    over new pixels and orders.  Proceeds order by order.\n    \n    Parameters\n    ----------\n    newx, newm : 1D arrays\n        Line centers and matching orders for which to return wavelengths\n    x, m, data : 1D arrays\n        Line centers, matching orders, and known wavelengths for\n        calibration lines\n    interp_deg : str or int (1), optional (default: 'pchip')\n        Specifies the type of interpolation\n        - 'pchip', default, cubic spline with inforced monotonicity\n        - 'inverse', fit wave vs. line position with a cubic spline\n          (the idea was the constrain the cubic to be a function,\n           but pchip does a better job and does it faster)\n        - 1, linear interplation (I forget why this is still an option)\n        - any other int, spline interpolation of specified degree\n    \n    Returns\n    -------\n    prediction : 1D ndarray\n        Wavelengths for the input newx and newm\n    \"\"\"\n    \n    # Make all the searches match-able\n    newm = np.array(newm,dtype=int)\n    m = np.array(m,dtype=int)\n    \n    # Initialize prediction array\n    prediction = np.zeros_like(newx)\n    prediction[:] = np.nan\n    # Go order by order\n    for r in np.unique(m):\n        Inew = newm == r\n        I = m==r\n        if (np.sum(Inew)>0) and (np.sum(I)>0):\n            # Sort lines in increasing wavelength\n            wave_sort = np.argsort(data[I])\n            ord_xs = x[I][wave_sort]\n            ord_data = data[I][wave_sort]\n            # Make sure the lines are in order\n            assert np.all(np.diff(ord_xs) > 0.),print(r,ord_xs[1:][np.argmin(np.diff(ord_xs))])\n        \n            # Interpolate\n            if interp_deg==1: # linear interpolation\n                prediction[Inew] = np.interp(newx[Inew], ord_xs, ord_data,\n                                             left=np.nan,right=np.nan,k=interp_deg)\n            elif interp_deg == 'pchip': # PCHIP interpolator\n                f = interpolate.PchipInterpolator(ord_xs,ord_data,extrapolate=False)\n                prediction[Inew] = f(newx[Inew])\n            elif interp_deg == 'inverse': # Interpolating wave vs. pixel\n                f = interpolate.interp1d(ord_data, ord_xs, kind='cubic',\n                                         bounds_error=False,fill_value=0)\n                inv_f = lambda x, a: f(x)-a\n                \n                f0 = interpolate.UnivariateSpline(ord_xs,ord_data,ext=1)\n                \n                predict = np.zeros(np.sum(Inew),dtype=float)\n                for i,pix in enumerate(newx[Inew]):\n                    if (pix <= ord_xs.min()) or (pix >= ord_xs.max()): # No extrapolation\n                        predict[i] = np.nan\n                    else:\n                        try:\n                            x0 = f0(pix)\n                            predict[i] = optimize.newton(inv_f,x0,args=(pix,))\n                        except RuntimeError:\n                            predict[i] = np.nan\n                prediction[Inew] = predict\n            else: # spline interpolation\n                tck = interpolate.splrep(ord_xs, ord_data, k=interp_deg)\n                predict = interpolate.splev(newx[Inew],tck,ext=1)\n                predict[predict==0] = np.nan\n                prediction[Inew] = predict\n    return prediction", "meta": {"hexsha": "47c089ba659b2420d8a14587abd1d4f4d3c229a4", "size": 16713, "ext": "py", "lang": "Python", "max_stars_repo_path": "py/excalibur.py", "max_stars_repo_name": "lilyling27/excalibur", "max_stars_repo_head_hexsha": "0d64c89d9613a412c033affbc145920534c4d4ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-07T14:05:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-07T14:05:56.000Z", "max_issues_repo_path": "py/excalibur.py", "max_issues_repo_name": "davidwhogg/EPRVCalibration", "max_issues_repo_head_hexsha": "e3627366af176f738e1fea7b2701158863889bf6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "py/excalibur.py", "max_forks_repo_name": "davidwhogg/EPRVCalibration", "max_forks_repo_head_hexsha": "e3627366af176f738e1fea7b2701158863889bf6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0490654206, "max_line_length": 96, "alphanum_fraction": 0.5940884342, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 4051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.19801615651800752}}
{"text": "import json\nimport logging\nimport os\nimport traceback\nfrom itertools import compress\n\nimport numpy as np\nimport pymbar\nimport pytraj as pt\nfrom openff.units import unit\nfrom pymbar import timeseries\nfrom scipy.interpolate import Akima1DInterpolator\n\nfrom paprika.io import PaprikaDecoder, PaprikaEncoder\nfrom paprika.utils import check_unit\n\nlogger = logging.getLogger(__name__)\n\n\nclass fe_calc(object):\n    \"\"\"\n    Computes the free energy for an APR transformation. After calling ``compute_free_energy()``, the\n    results are stored in a dictionary called ``results`` in units of kcal/mol.\n\n    To get the binding free energy at standard state (ΔG°), we have used the following sign convention:\n\n    .. math ::\n        ΔG° = ΔG_{attach} + ΔG_{pull} - ΔG_{release} + ΔG_{reference}\n\n    .. note ::\n        It would be great to add unit support here from ``pint``.\n\n    .. warning ::\n        This class really ought to be split into a few smaller classes that sublcass a ``BaseAnalysis`` class. There\n        could be separate ``MBARAnalysis`` and ``TIAnalysis`` classes, for example. This would make it much more modular\n        and easy to test where TI and MBAR disagree. This could also be used to benchmark autocorrelation-based and\n        blocking-analysis-based methods for evaluating the statistical inefficiency.\n\n    \"\"\"\n\n    @property\n    def temperature(self):\n        \"\"\"float or unit.Quantity: The temperature used during the simulation. This will update β (1/kT) as well.\"\"\"\n        return self._temperature\n\n    @temperature.setter\n    def temperature(self, new_temperature):\n        \"\"\"Update temperature and β with a new temperature.\"\"\"\n        self._temperature = check_unit(new_temperature, base_unit=unit.kelvin)\n        self.beta = 1 / (self.k_B * self._temperature)\n\n    @property\n    def topology(self):\n        \"\"\"\n        os.PathLike: The topology (prmtop or pdb) file used for the analysis.\n        This should match the topology used for the simulation.\n        \"\"\"\n        return self._topology\n\n    @topology.setter\n    def topology(self, value):\n        self._topology = value\n\n    @property\n    def trajectory(self):\n        \"\"\"\n        os.PathLike: File name of the trajectories to be analyzed in each window (can include a wildcard).\n        \"\"\"\n        return self._trajectory\n\n    @trajectory.setter\n    def trajectory(self, value):\n        self._trajectory = value\n\n    @property\n    def path(self):\n        \"\"\"\n        os.PathLike: The parent directory that contains the simulation windows.\n        \"\"\"\n        return self._path\n\n    @path.setter\n    def path(self, value):\n        self._path = value\n\n    @property\n    def restraint_list(self):\n        \"\"\"\n        list: The list of restraints to be used for analysis.\n        \"\"\"\n        return self._restraint_list\n\n    @restraint_list.setter\n    def restraint_list(self, value):\n        self._restraint_list = value\n\n    @property\n    def changing_restraints(self):\n        \"\"\"\n        dict: Dictionary containing which restraints change during which phase of the calculation.\n\n        .. note ::\n            This should probably be a private attribute, as this property is determined automatically.\n\n        \"\"\"\n        return self._changing_restraints\n\n    @changing_restraints.setter\n    def changing_restraints(self, value):\n        self._changing_restraints = value\n\n    @property\n    def orders(self):\n        \"\"\"\n        The sorted order of windows for analysis. In principle, windows could be out-of-order if subsequent additional\n        sampling was requested.\n\n        .. note ::\n            As far as I know, we have not tested analysis on windows out of order. We imagined that one could add additional\n            λ windows through multiple runs by modifying existing restraints (e.g., restraint values of [0, 0.5, 1.0, 0.8])\n            and this module would be able to correctly sort the simulation directories and restraint targets.\n\n        .. note ::\n            This should probably be a private attribute, as this property is determined automatically.\n\n        \"\"\"\n        return self._orders\n\n    @orders.setter\n    def orders(self, value):\n        self._orders = value\n\n    @property\n    def simulation_data(self):\n        \"\"\"\n        dict: Dictionary containing collected trajectory values for the relevant restraints and windows\n\n        .. note ::\n            This should probably be a private attribute, as this property is determined automatically.\n\n        \"\"\"\n        return self._simulation_data\n\n    @simulation_data.setter\n    def simulation_data(self, value):\n        self._simulation_data = value\n\n    @property\n    def methods(self):\n        \"\"\"\n        list: List of analysis methods to be performed. This is a combination of free energy method (e.g., MBAR, TI, ...)\n        and de-correlation method (blocking, autocorrelation, ...).\n\n        Implemented methods are:\n\n            - ``mbar-autoc``\n            - ``mbar-block``\n            - ``ti-block``\n\n        .. note ::\n            This is really fragile. We should definitely use something like an ``ENUM`` here to check for the few combinations\n            that we support.\n\n        .. todo ::\n            - Add ``ti-autoc``.\n            - Add ``wham-block``.\n            - Add ``wham-autoc``.\n            - Clarify naming.\n            - Look into using ``pymbar`` for decorrelation.\n\n        \"\"\"\n        return self._methods\n\n    @methods.setter\n    def methods(self, value):\n        self._methods = value\n\n    @property\n    def conservative_subsample(self):\n        \"\"\"\n        bool: Whether the statistical inefficiency is rounded up to the nearest integer. If ``False``, a non-integer\n        value\n        is used.\n        \"\"\"\n        return self._conservative_subsample\n\n    @conservative_subsample.setter\n    def conservative_subsample(self, value):\n        self._conservative_subsample = value\n\n    @property\n    def bootcycles(self) -> int:\n        \"\"\"\n        int: The number of bootstrap iterations for the TI methods.\n\n        **Default**: ``1000``\n        \"\"\"\n        return self._bootcycles\n\n    @bootcycles.setter\n    def bootcycles(self, value):\n        self._bootcycles = value\n\n    @property\n    def compute_roi(self) -> bool:\n        \"\"\"\n        bool: Whether to compute the return on investment (ROI) value for each window. The more negative the ROI, the\n        better the return on investment of computing more frames for this particular window.\n        \"\"\"\n        return self._compute_roi\n\n    @compute_roi.setter\n    def compute_roi(self, value):\n        self._compute_roi = value\n\n    @property\n    def compute_largest_neighbor(self):\n        \"\"\"\n        bool: Whether to find and store the maximum SEM to the neighbor windows. This is useful if using the \"scale_w\"\n        approach which is described in Equation (1) in: https://pubs.acs.org/doi/10.1021/acs.jctc.9b00748.\n        \"\"\"\n        return self._compute_largest_neighbor\n\n    @compute_largest_neighbor.setter\n    def compute_largest_neighbor(self, value):\n        self._compute_largest_neighbor = value\n\n    @property\n    def ti_matrix(self):\n        \"\"\"\n        str: If ``full``, the TI mean and SEM free energy is computed between all windows (i.e., the energy differences between\n        all windows and all other windows). If ``diagonal``, the mean and SEM of the free energy is computed between the\n        first window and all other windows, as well as between all neighboring windows. If ``endpoints``, the mean and\n        SEM free energy is computed between only the first and the last window.\n\n        For most cases, ``diagonal`` should be sufficient and ``full`` is overkill.\n\n        .. note ::\n            This is fragile and we should be checking for the valid strings supported.\n\n        \"\"\"\n        return self._ti_matrix\n\n    @ti_matrix.setter\n    def ti_matrix(self, value):\n\n        if value not in [\"full\", \"diagonal\", \"endpoints\"]:\n            raise ValueError(f\"{value} is not a supported integration scheme.\")\n\n        self._ti_matrix = value\n\n    @property\n    def exact_sem_each_ti_fraction(self):\n        \"\"\"\n        bool: Whether the SEM is computed once for the full data set and then the SEM for each fraction is estimated\n        based on the total SEM and the fractional number of uncorrelated data points. If ``True``, the SEM will be recomputed\n        each fraction using just that fraction of the raw data.\n        \"\"\"\n        return self._exact_sem_each_ti_fraction\n\n    @exact_sem_each_ti_fraction.setter\n    def exact_sem_each_ti_fraction(self, value):\n        self._exact_sem_each_ti_fraction = value\n\n    @property\n    def fractions(self) -> list:\n        \"\"\"\n        list: A list of fractions of the total data for which a free energy will be computed. Default is [1.0].\n        \"\"\"\n        return self._fractions\n\n    @fractions.setter\n    def fractions(self, value):\n\n        for fraction in value:\n            if fraction < 0.0 or fraction > 1.0:\n                raise ValueError(\n                    f\"Unable to calculation fraction of the data: {fraction}.\"\n                )\n\n        self._fractions = value\n\n    @property\n    def results(self):\n        \"\"\"\n        dict: A dictionary containing the results. The results dictionary is indexed first by phase, and then by\n        method. That is, ``results[\"attach\"][\"mbar-block\"]`` will contain the results from analyzing the attach\n        phase with the MBAR free energy estimator and blocking analysis used to estimate the SEM.\n\n        The final free energy and uncertainty estimate is specified in the ``fe`` and ``sem`` keys.\n\n        If multiple fractions of the data are specified, the free energy and SEM from each fraction are stored in a nested\n        dictionary under the keys ``fraction_fe`` and ``fractrion_sem``. The number of frames analyzed for each fraciton\n        is stored under ``fraction_n_frames``.\n\n        The full free energy matrix (window-to-window free energy differences) is stored in the ``fe_matrix`` entry.\n        Likewise, the full SEM matrix (window-to-window free energy SEMs) is stored in the ``sem_matrix`` entry.\n\n        The work to release the guest to standard concentration is stored under ``ref_state_work``, and is\n        negative by convention.\n\n        The format of a typical dictionary will resemble this (where I have a omitted the values in the matrices for\n        clarity):\n\n        ::\n\n            {'attach': {'mbar-block': {'fe': 13.019994367423227,\n                                       'fe_matrix': array(),\n                                       'fraction_fe': {'1.0': 13.019994367423227},\n                                       'fraction_fe_matrix': {'1.0': array()},\n                                       'fraction_n_frames': {'1.0': 2280000},\n                                       'fraction_sem': {'1.0': 0.12783177525365627},\n                                       'fraction_sem_matrix': {'1.0': array()},\n                                       'n_frames': 2280000,\n                                       'sem': 0.12783177525365627,\n                                       'sem_matrix': array()},\n                        'window_order': array([ 0,  1,  2, ..., 12, 13, 14])},\n             'pull': {'mbar-block': {'fe': 5.367885925413715,\n                                     'fe_matrix': array(),\n                                     'fraction_fe': {'1.0': 5.367885925413715},\n                                     'fraction_fe_matrix': {'1.0': array()},\n                                     'fraction_n_frames': {'1.0': 2900000},\n                                     'fraction_sem': {'1.0': 0.21231171453084993},\n                                     'fraction_sem_matrix': {'1.0': array()},\n                                     'n_frames': 2900000,\n                                     'sem': 0.21231171453084993,\n                                     'sem_matrix': array()},\n                      'window_order': array([ 0,  1,  2, ..., 43, 44, 45])},\n             'ref_state_work': -7.141514582862005}\n\n        .. note ::\n            This will be automatically populated with the outcome of the analysis. Do not directly modify these values.\n\n\n        \"\"\"\n        return self._results\n\n    @results.setter\n    def results(self, value):\n        self._results = value\n\n    @property\n    def energy_unit(self):\n        \"\"\"pint.unit: The based unit for energy.\"\"\"\n        return self._energy_unit\n\n    @energy_unit.setter\n    def energy_unit(self, value: unit.Quantity):\n        self._energy_unit = value\n\n    @property\n    def distance_unit(self):\n        \"\"\"pint.unit: The base unit for distance.\"\"\"\n        return self._distance_unit\n\n    @distance_unit.setter\n    def distance_unit(self, value: unit.Quantity):\n        self._distance_unit = value\n\n    @property\n    def angle_unit(self):\n        \"\"\"pint.unit: The base unit for angles.\"\"\"\n        return self._angle_unit\n\n    @angle_unit.setter\n    def angle_unit(self, value: unit.Quantity):\n        self._angle_unit = value\n\n    @property\n    def temperature_unit(self):\n        \"\"\"pint.unit: The base unit for temperature.\"\"\"\n        return self._temperature_unit\n\n    @temperature_unit.setter\n    def temperature_unit(self, value: unit.Quantity):\n        self._temperature_unit = value\n\n    def __init__(self):\n\n        self._energy_unit = unit.kcal / unit.mole\n        self._distance_unit = unit.angstrom\n        self._angle_unit = unit.degrees\n        self._temperature_unit = unit.kelvin\n\n        self._temperature = 298.15 * self._temperature_unit\n        self.k_B = 1.987204118e-3 * self._energy_unit / self._temperature_unit\n        self.beta = 1 / (self.k_B * self._temperature)\n        self._topology = None\n        self._trajectory = None\n        self._path = None\n        self._restraint_list = []\n        self._changing_restraints = None\n        self._orders = None\n        self._simulation_data = None\n        self._methods = [\"mbar-block\"]\n        self._conservative_subsample = False\n        self._bootcycles = 1000\n        self._compute_roi = False\n        self._compute_largest_neighbor = False\n        self._ti_matrix = \"full\"\n        self._exact_sem_each_ti_fraction = False\n        self._fractions = [1.0]\n        self._results = {}\n\n    def collect_data(self, single_topology=False):\n        \"\"\"\n        Gather simulation data on the distance, angle, and torsion restraints that change during the simulation.\n\n        Parameters\n        ----------\n        single_topology: bool\n            Whether a single `topology` file is read for all windows\n        \"\"\"\n\n        self.changing_restraints = self.identify_changing_restraints()\n        self.orders = self.determine_window_order()\n        self.simulation_data = self.read_trajectories(single_topology=single_topology)\n\n    def collect_data_from_json(self, filepath):\n        \"\"\"\n        Read in simulation data from a JSON file.\n\n        Parameters\n        ----------\n        filepath: os.PathLike\n            The name of the JSON file.\n        \"\"\"\n        with open(filepath, \"r\") as f:\n            json_data = f.read()\n            data = json.loads(json_data, cls=PaprikaDecoder)\n\n        self.changing_restraints = data[\"changing_restraints\"]\n        self.orders = data[\"orders\"]\n        self.simulation_data = data[\"simulation_data\"]\n\n    def identify_changing_restraints(self):\n        \"\"\"Figure out which restraints change during each phase of the calculation.\n\n        Returns\n        -------\n        changing_restraints : dict\n            A dictionary containing which restraints change during which phase of the calculation\n        \"\"\"\n\n        changing_restraints = {\"attach\": [], \"pull\": [], \"release\": []}\n\n        for phase in [\"attach\", \"pull\", \"release\"]:\n            if phase == \"attach\" or phase == \"release\":\n                changing_parameter = \"force_constants\"\n            else:\n                changing_parameter = \"targets\"\n            for restraint in self.restraint_list:\n                if restraint.phase[phase][changing_parameter] is not None:\n                    static = all(\n                        np.isclose(x, restraint.phase[phase][changing_parameter][0])\n                        for x in restraint.phase[phase][changing_parameter]\n                    )\n                else:\n                    static = True\n\n                changing_restraints[phase].append(not static)\n\n        return changing_restraints\n\n    def determine_window_order(self):\n        \"\"\"Order the trajectories (i.e., simulation windows) in terms of increasing force constants and\n        targets for each restraint.\n\n        Returns\n        -------\n        orders : dict\n            The sorted order of windows for analysis\n        \"\"\"\n\n        orders = {\"attach\": [], \"pull\": [], \"release\": []}\n        active_attach_restraints = list(\n            compress(self.restraint_list, self.changing_restraints[\"attach\"])\n        )\n        active_pull_restraints = list(\n            compress(self.restraint_list, self.changing_restraints[\"pull\"])\n        )\n        active_release_restraints = list(\n            compress(self.restraint_list, self.changing_restraints[\"release\"])\n        )\n\n        attach_orders = []\n        pull_orders = []\n        release_orders = []\n\n        for restraint in active_attach_restraints:\n            attach_orders.append(\n                np.argsort(restraint.phase[\"attach\"][\"force_constants\"])\n            )\n        if not all([np.array_equal(attach_orders[0], i) for i in attach_orders]):\n            raise Exception(\n                \"The order of increasing force constants is not the same in all restraints.\"\n            )\n        elif attach_orders:\n            orders[\"attach\"] = attach_orders[0]\n        else:\n            orders[\"attach\"] = np.empty(0)\n\n        for restraint in active_pull_restraints:\n            pull_orders.append(np.argsort(restraint.phase[\"pull\"][\"targets\"]))\n        if not all([np.array_equal(pull_orders[0], i) for i in pull_orders]):\n            raise Exception(\n                \"The order of increasing target distances is not the same in all restraints.\"\n            )\n        elif pull_orders:\n            orders[\"pull\"] = pull_orders[0]\n        else:\n            orders[\"pull\"] = np.empty(0)\n\n        for restraint in active_release_restraints:\n            release_orders.append(\n                np.argsort(restraint.phase[\"release\"][\"force_constants\"])\n            )\n        if not all([np.array_equal(release_orders[0], i) for i in release_orders]):\n            raise Exception(\n                \"The order of increasing force constants is not the same in all restraints.\"\n            )\n        elif release_orders:\n            orders[\"release\"] = release_orders[0]\n        else:\n            orders[\"release\"] = np.empty(0)\n\n        return orders\n\n    def read_trajectories(self, single_topology=False):\n        \"\"\"For each each phase and window, and for each non-static restraint, parse the trajectories to\n        get the restraint values.\n\n        Parameters\n        ----------\n        single_topology : bool\n            Whether a single `topology` file is read for all windows\n\n        Returns\n        -------\n        data : dict\n            Dictionary containing restraint values for analysis\n        \"\"\"\n\n        data = {\"attach\": [], \"pull\": [], \"release\": []}\n\n        ordered_attach_windows = [\n            os.path.join(self.path, \"a{:03d}\".format(i))\n            for i in self.orders[\"attach\"]\n            if i is not None\n        ]\n        ordered_pull_windows = [\n            os.path.join(self.path, \"p{:03d}\".format(i))\n            for i in self.orders[\"pull\"]\n            if i is not None\n        ]\n        ordered_release_windows = [\n            os.path.join(self.path, \"r{:03d}\".format(i))\n            for i in self.orders[\"release\"]\n            if i is not None\n        ]\n\n        active_attach_restraints = np.asarray(self.restraint_list)[\n            self.changing_restraints[\"attach\"]\n        ]\n        active_pull_restraints = np.asarray(self.restraint_list)[\n            self.changing_restraints[\"pull\"]\n        ]\n        active_release_restraints = np.asarray(self.restraint_list)[\n            self.changing_restraints[\"release\"]\n        ]\n\n        # Niel: I'm just checking if *one* restraint is `continuous_apr`,\n        # which should be the same value for all restraints.\n        if len(active_attach_restraints) > 0:\n            if (\n                active_attach_restraints[0].continuous_apr\n                and self.orders[\"attach\"].size > 0\n                and self.orders[\"pull\"].size > 0\n            ):\n                logger.debug(\n                    \"Replacing {} with {} in {} for `continuous_apr`...\".format(\n                        ordered_attach_windows[-1],\n                        ordered_pull_windows[0],\n                        ordered_attach_windows,\n                    )\n                )\n                ordered_attach_windows[-1] = ordered_pull_windows[0]\n\n        if len(active_release_restraints) > 0:\n            if (\n                active_release_restraints[0].continuous_apr\n                and self.orders[\"release\"].size > 0\n                and self.orders[\"pull\"].size > 0\n            ):\n                logger.debug(\n                    \"Replacing {} with {} in {} for `continuous_apr`...\".format(\n                        ordered_release_windows[-1],\n                        ordered_pull_windows[-1],\n                        ordered_release_windows,\n                    )\n                )\n                ordered_release_windows[-1] = ordered_pull_windows[-1]\n\n        for window_index, window in enumerate(ordered_attach_windows):\n            phase = \"attach\"\n            data[phase].append([])\n            traj = load_trajectory(\n                window, self.trajectory, self.topology, single_topology\n            )\n            for restraint_index, restraint in enumerate(active_attach_restraints):\n                data[phase][window_index].append([])\n                data[phase][window_index][restraint_index] = read_restraint_data(\n                    traj, restraint\n                )\n\n        for window_index, window in enumerate(ordered_pull_windows):\n            phase = \"pull\"\n            data[phase].append([])\n            traj = load_trajectory(\n                window, self.trajectory, self.topology, single_topology\n            )\n            for restraint_index, restraint in enumerate(active_pull_restraints):\n                data[phase][window_index].append([])\n                data[phase][window_index][restraint_index] = read_restraint_data(\n                    traj, restraint\n                )\n\n        for window_index, window in enumerate(ordered_release_windows):\n            phase = \"release\"\n            data[phase].append([])\n            traj = load_trajectory(\n                window, self.trajectory, self.topology, single_topology\n            )\n            for restraint_index, restraint in enumerate(active_release_restraints):\n                data[phase][window_index].append([])\n                data[phase][window_index][restraint_index] = read_restraint_data(\n                    traj, restraint\n                )\n\n        return data\n\n    def prepare_data(self, phase):\n        number_of_windows = len(self.simulation_data[phase])\n        data_points = [len(np.asarray(x).T) for x in self.simulation_data[phase]]\n        max_data_points = max(data_points)\n        active_restraints = list(\n            compress(self.restraint_list, self.changing_restraints[phase])\n        )\n        force_constants = [\n            np.copy(i.phase[phase][\"force_constants\"]) for i in active_restraints\n        ]\n        targets = [i.phase[phase][\"targets\"] for i in active_restraints]\n\n        ordered_force_constants = [i[self.orders[phase]] for i in force_constants]\n        ordered_targets = [i[self.orders[phase]] for i in targets]\n\n        return (\n            number_of_windows,\n            data_points,\n            max_data_points,\n            active_restraints,\n            ordered_force_constants,\n            ordered_targets,\n            self.simulation_data[phase],\n        )\n\n    def run_mbar(self, phase, prepared_data, method, verbose=False):\n        \"\"\"\n        Compute the free energy matrix for a series of windows. We'll follow the pymbar nomenclature for data structures.\n\n        Parameters\n        ----------\n        phase: str\n            The phase of the calculation to analyze.\n        prepared_data: :class:`np.array`\n            The list of \"prepared data\" including the number of windows, data points, which restraints are changing,\n            their force constants and targets, and well as the order of the windows. This probably ought to be\n            redesigned.\n        method: str\n            The method used to calculate the SEM.\n        verbose: bool, optional\n            Whether to set the `verbose` option on pyMBAR.\n        \"\"\"\n\n        # Unpack the prepared data\n        (\n            num_win,\n            data_points,\n            max_data_points,\n            active_rest,\n            force_constants,\n            targets,\n            ordered_values,\n        ) = prepared_data\n\n        # Number of data points in each restraint value array\n        N_k = np.array(data_points)\n\n        # Setup the reduced potential energy array. ie, the potential of each window's\n        # coordinates in each window's potential function\n        u_kln = np.zeros([num_win, num_win, max_data_points], np.float64)\n\n        # Transpose force_constants and targets into \"per window\" format, instead of\n        # the \"per restraint\" format.\n        target_units = np.array([targets[r][0].units for r in range(len(active_rest))])\n        force_units = np.array(\n            [force_constants[r][0].units for r in range(len(active_rest))]\n        )\n\n        force_constants_T = np.asarray(force_constants).T * force_units\n        targets_T = np.asarray(targets).T * target_units\n\n        # Note, the organization of k = coordinate windows, l = potential windows\n        # seems to be opposite of the documentation. But I got wrong numbers\n        # the other way around.\n        for k in range(num_win):  # Coordinate windows\n            for l in range(num_win):  # Potential Windows\n\n                for r, rest in enumerate(active_rest):  # Restraints\n                    # If this is a dihedral, we need to shift around restraint value\n                    # on the periodic axis to make sure the lowest potential is\n                    # used.\n                    if rest.mask3 is not None and rest.mask4 is not None:\n                        target = targets_T[l, r]\n                        # Coords from coord window, k\n                        bool_list = ordered_values[k][r] < target - 180.0 * unit.degrees\n                        ordered_values[k][r][bool_list] += 360.0 * unit.degrees\n                        bool_list = ordered_values[k][r] > target + 180.0 * unit.degrees\n                        ordered_values[k][r][bool_list] -= 360.0 * unit.degrees\n\n                # Compute the potential ... for each frame, sum the contributions for each restraint\n                # Note, we multiply by beta, and do some extra [l,:,None] to\n                # get the math operation correct.\n                u_kln[k, l, 0 : N_k[k]] = sum(\n                    [\n                        self.beta * k * (val - eq) ** 2\n                        for k, val, eq in zip(\n                            force_constants_T[l], ordered_values[k], targets_T[l]\n                        )\n                    ]\n                ).magnitude\n\n        g_k = np.ones([num_win], np.float64)\n        # Should I subsample based on the restraint coordinate values? Here I'm\n        # doing it on the potential.  Should be pretty close ....\n        if method == \"mbar-block\":\n            # We want to use all possible data to get the free energy estimates Deltaf_ij,\n            # but for uncertainty estimates we'll subsample to create\n            # uncorrelated data.\n            for k in range(num_win):\n                l = k\n                # If the potential is zero everywhere, we can't estimate the uncertainty, so\n                # check the next *potential* window which probably had non-zero\n                # force constants\n                while not u_kln[k, l, 0 : N_k[k]].any():\n                    l += 1\n                # Now compute statistical inefficiency: g = N*(SEM**2)/variance\n                nearest_max = get_nearest_max(N_k[k])\n                sem = get_block_sem(u_kln[k, l, 0:nearest_max])\n                variance = np.var(u_kln[k, l, 0 : N_k[k]])\n                g_k[k] = N_k[k] * (sem ** 2) / variance\n\n        if method == \"mbar-autoc\":\n            for k in range(num_win):\n                [t0, g_k[k], Neff_max] = timeseries.detectEquilibration(\n                    N_k[k]\n                )  # compute indices of uncorrelated\n                # timeseries\n\n        # Create subsampled indices and count their lengths. If g=1, ie no correlation,\n        # then subsampling will return identical indices to original\n        # (hopefully)\n        ss_indices = []\n        N_ss = np.zeros([num_win], np.int32)  # N_subsample\n        for k in range(num_win):\n            ss_indices.append(\n                get_subsampled_indices(\n                    N_k[k], g_k[k], conservative=self.conservative_subsample\n                )\n            )\n            N_ss[k] = len(ss_indices[k])\n\n        self.results[phase][method][\"fraction_fe_matrix\"] = {}\n        self.results[phase][method][\"fraction_sem_matrix\"] = {}\n        self.results[phase][method][\"fraction_fe_Neffective\"] = {}\n        self.results[phase][method][\"fraction_sem_Neffective\"] = {}\n\n        for fraction in self.fractions:\n            # Setup mbar calc, and get matrix of free energies, uncertainties\n            # To estimate the free energy, we won't do subsampling.  We'll do\n            # another MBAR calculation later with subsampling to estimate the\n            # uncertainty.\n            frac_N_k = np.array([int(fraction * n) for n in N_k], dtype=np.int32)\n\n            mbar = pymbar.MBAR(u_kln, frac_N_k, verbose=verbose)\n            mbar_results = mbar.getFreeEnergyDifferences(\n                compute_uncertainty=True, return_dict=True\n            )\n\n            Deltaf_ij = mbar_results[\"Delta_f\"]\n            dDeltaf_ij = mbar_results[\"dDelta_f\"]\n\n            Deltaf_ij_N_eff = mbar.computeEffectiveSampleNumber()\n\n            if method == \"mbar-block\" or \"mbar-autoc\":\n                # Create subsampled indices and count their lengths\n                frac_N_ss = np.array([int(fraction * n) for n in N_ss], dtype=np.int32)\n\n                # Create a new potential array for the uncertainty calculation\n                # (are we using too much memory?)\n                u_kln_err = np.zeros([num_win, num_win, np.max(frac_N_ss)], np.float64)\n\n                # Populate the subsampled array, drawing the appropriate\n                # fraction of subsamples from the original\n                for k in range(num_win):\n                    for l in range(num_win):\n                        u_kln_err[k, l, 0 : frac_N_ss[k]] = u_kln[\n                            k, l, ss_indices[k][0 : frac_N_ss[k]]\n                        ]\n\n                # We toss junk_Deltaf_ij, because we got a better estimate for it from above using all data.\n                # But dDeltaf_ij will replace the previous, because it correctly accounts for the\n                # correlation in the data.\n                mbar = pymbar.MBAR(u_kln_err, frac_N_ss, verbose=verbose)\n                mbar_results = mbar.getFreeEnergyDifferences(\n                    compute_uncertainty=True, return_dict=True\n                )\n                dDeltaf_ij = mbar_results[\"dDelta_f\"]\n                dDeltaf_ij_N_eff = mbar.computeEffectiveSampleNumber()\n\n            # Put back into kcal/mol\n            Deltaf_ij /= self.beta\n            dDeltaf_ij /= self.beta\n\n            self.results[phase][method][\"fraction_fe_matrix\"][fraction] = Deltaf_ij\n            self.results[phase][method][\"fraction_fe_Neffective\"][\n                fraction\n            ] = Deltaf_ij_N_eff\n            self.results[phase][method][\"fraction_sem_matrix\"][fraction] = dDeltaf_ij\n            self.results[phase][method][\"fraction_sem_Neffective\"][\n                fraction\n            ] = dDeltaf_ij_N_eff\n\n    def run_ti(self, phase, prepared_data, method):\n        \"\"\"\n        Compute the free energy using the TI method.\n\n        We compute the partial derivative of the potential (i.e., forces), for each frame, with respect to the\n        changing parameter, either a lambda or target value. The force constants are scaled by the λ parameter which\n        controls their strength: ``0`` to ``fc_max``.\n\n        Potential:\n          U = λ × fc_max × (values - target)²\n        Forces during attach:\n          dU/dλ = fc_max × (values - target)²\n        Forces during pull:\n          dU/d(target) = 2 × λ × fc_max × (values - target)\n        Forces during release:\n          (same as attach)\n\n        Then we integrate over the interval covered by λ or target.\n\n        Parameters\n        ----------\n        phase: str\n            The phase of the calculation to analyze.\n        prepared_data: :class:`np.array`\n            The list of \"prepared data\" including the number of windows, data points, which restraints are changing,\n            their force constants and targets, and well as the order of the windows. This probably ought to be\n            redesigned.\n        method: str\n            The method used to calculate the SEM.\n\n        .. note ::\n            ``phase`` and ``method`` should be `enum` types and tied to class attributes.\n\n        .. warning ::\n            We have only considered whether this will work for the case where the pull phase is a single distance\n            restraint with a changing target value. This has not been tested for a changing angle or dihedral.\n\n        \"\"\"\n\n        # Unpack the prepared data\n        (\n            num_win,\n            data_points,\n            max_data_points,\n            active_rest,\n            force_constants,\n            targets,\n            ordered_values,\n        ) = prepared_data\n\n        # Number of data points in each restraint value array\n        N_k = np.array(data_points)\n\n        # The dU array to store the partial derivative of the potential with respect lambda or target,\n        # depending on the whether attach/release or pull. Data stored for each frame.  This just a\n        # temporary storage space.\n        dU = np.zeros([num_win, max_data_points], np.float64)\n\n        # The mean, SEM, standard deviation, and number of uncorrelated dU values for each window.\n        dU_avgs = np.zeros([num_win], np.float64)\n        dU_sems = np.zeros([num_win], np.float64)\n        dU_stdv = np.zeros([num_win], np.float64)\n        dU_Nunc = np.zeros([num_win], np.float64)\n        # The statistical inefficiency\n        g = np.zeros([num_win], np.float64)\n\n        # Array for values of the changing coordinate (x-axis), either lambda or target.\n        # I'll name them dl_vals for dlambda values.\n        dl_vals = np.zeros([num_win], np.float64)\n\n        # Setup interpolation array for the dLambda (dl) coordinate. We're gonna create\n        # this progressively by appending ...\n        dl_intp = np.zeros([0], np.float64)\n\n        # Get units\n        target_units = np.array([targets[r][0].units for r in range(len(active_rest))])\n        force_units = np.array(\n            [force_constants[r][0].units for r in range(len(active_rest))]\n        )\n\n        # Store the max force constant value for each restraint.\n        max_force_constants = (\n            np.array(\n                [np.max(force_constants[r]).magnitude for r in range(len(active_rest))]\n            )\n            * force_units\n        )\n\n        # Transpose force_constants and targets into \"per window\" format, instead of\n        # the \"per restraint\" format.\n        # print(targets)\n        force_constants_T = np.asarray(force_constants).T * force_units\n        targets_T = np.asarray(targets).T * target_units\n\n        # For each window: do dihedral wrapping, compute forces, append dl_intp\n        for k in range(num_win):  # Coordinate windows\n\n            # Wrap dihedrals so we get the right potential\n            for r, rest in enumerate(active_rest):  # Restraints\n                # If this is a dihedral, we need to shift around restraint value\n                # on the periodic axis to make sure the lowest potential is used.\n\n                if rest.mask3 is not None and rest.mask4 is not None:\n                    target = targets_T[k, r]\n                    bool_list = ordered_values[k][r] < target - 180.0 * unit.degrees\n                    ordered_values[k][r][bool_list] += 360.0 * unit.degrees\n                    bool_list = ordered_values[k][r] > target + 180.0 * unit.degrees\n                    ordered_values[k][r][bool_list] -= 360.0 * unit.degrees\n\n            # Compute forces and store the values of the changing coordinate,\n            # either lambda or target\n            if phase == \"attach\" or phase == \"release\":\n                dU[k, 0 : N_k[k]] = (\n                    sum(\n                        [\n                            (k * (val - eq) ** 2)\n                            for k, val, eq in zip(\n                                max_force_constants, ordered_values[k], targets_T[k]\n                            )\n                        ]\n                    )\n                    .to(self.energy_unit)\n                    .magnitude\n                )\n\n                # this is lambda. assume the same scaling for all restraints\n                dl_vals[k] = force_constants_T[k, 0] / max_force_constants[0]\n            else:\n                dU[k, 0 : N_k[k]] = (\n                    sum(\n                        [\n                            2.0 * k * (val - eq)\n                            for k, val, eq in zip(\n                                max_force_constants, ordered_values[k], targets_T[k]\n                            )\n                        ]\n                    )\n                    .to(self.energy_unit / self.distance_unit)\n                    .magnitude\n                )\n\n                # Currently assuming a single distance restraint\n                dl_vals[k] = targets_T[k, 0].to(self.distance_unit).magnitude\n\n            # Compute standard deviations and SEMs, unless we're going to do\n            # exact_sem_each_ti_fraction\n            dU_avgs[k] = np.mean(dU[k, 0 : N_k[k]])\n            dU_stdv[k] = np.std(dU[k, 0 : N_k[k]])\n            if method == \"ti-block\":\n                nearest_max = get_nearest_max(N_k[k])\n                dU_sems[k] = get_block_sem(dU[k, 0:nearest_max])\n                # Rearrange SEM = StdDev/sqrt(N) to get N_uncorrelated\n                dU_Nunc[k] = (dU_stdv[k] / dU_sems[k]) ** 2\n            elif method == \"ti-nocor\":\n                dU_sems[k] = dU_stdv[k] / np.sqrt(N_k[k])\n                dU_Nunc[k] = N_k[k]\n            g[k] = N_k[k] / dU_Nunc[k]\n\n            # Create the interpolation by appending 100 points between each window.\n            # Start with k=1 so we don't double count.\n            if k > 0:\n                dl_intp = np.append(\n                    dl_intp,\n                    np.linspace(dl_vals[k - 1], dl_vals[k], num=100, endpoint=False),\n                )\n\n        # Tack on the final value to the dl interpolation\n        dl_intp = np.append(dl_intp, dl_vals[-1])\n\n        logger.debug(\"Running bootstrap calculations...\")\n\n        # Setup fractions. For simplicity, we'll always do this, even\n        # if we're doing the total data, ie self.fractions=[1.0].\n        self.results[phase][method][\"fraction_fe_matrix\"] = {}\n        self.results[phase][method][\"fraction_sem_matrix\"] = {}\n\n        for fraction in self.fractions:\n\n            logger.debug(\"Working on fraction ... {}\".format(fraction))\n\n            # Compute means for this fraction.\n            frac_dU_avgs = np.array(\n                [np.mean(dU[k, 0 : int(fraction * n)]) for k, n in enumerate(N_k)]\n            )\n\n            # If self.exact_sem_each_ti_fraction, we're gonna recompute the SEM for each fraction\n            # rather than estimating it from the standard deviation (dU_stdv) and number of\n            # uncorrelated data points (dU_Nunc) from the total data set.\n            if method == \"ti-block\" and self.exact_sem_each_ti_fraction:\n                frac_dU_sems = np.zero([k], np.float64)\n                for k in range(num_win):\n                    nearest_max = get_nearest_max(int(fraction * N_k[k]))\n                    frac_dU_sems[k] = get_block_sem(dU[k, 0:nearest_max])\n            elif method == \"ti-nocor\" and self.exact_sem_each_ti_fraction:\n                frac_dU_sems = np.zero([k], np.float64)\n                for k in range(num_win):\n                    frac_dU_sems[k] = np.std(\n                        dU[k, 0 : int(fraction * N_k[k])]\n                    ) / np.sqrt(int(fraction * N_k[k]))\n            else:\n                frac_dU_sems = dU_stdv / np.sqrt(fraction * dU_Nunc)\n\n            dU_samples = np.random.normal(\n                frac_dU_avgs, frac_dU_sems, size=(self.bootcycles, frac_dU_avgs.size)\n            )\n\n            # Run bootstraps\n            (\n                self.results[phase][method][\"fraction_fe_matrix\"][fraction],\n                self.results[phase][method][\"fraction_sem_matrix\"][fraction],\n            ) = integrate_bootstraps(\n                dl_vals, dU_samples, x_intp=dl_intp, matrix=self.ti_matrix\n            )\n\n            # Put units back on\n            self.results[phase][method][\"fraction_fe_matrix\"][\n                fraction\n            ] *= self.energy_unit\n            self.results[phase][method][\"fraction_sem_matrix\"][\n                fraction\n            ] *= self.energy_unit\n\n            # The attach/release work (integration) yields appropriately positive work, but\n            # the pull work needs a negative multiplier. Think W = −Force × distance type thing.\n            if phase == \"pull\":\n                self.results[phase][method][\"fraction_fe_matrix\"][fraction] *= -1.0\n\n        if self.compute_roi:\n            logger.info(phase + \": computing ROI for \" + method)\n            # Do ROI calc\n            max_fraction = np.max(self.fractions)\n            # If we didn't compute fe/sem for fraction 1.0 already, do it now\n            dU_samples = np.random.normal(\n                dU_avgs, dU_sems, size=(self.bootcycles, dU_avgs.size)\n            )\n            if not np.isclose(max_fraction, 1.0):\n                junk_fe, total_sem_matrix = integrate_bootstraps(\n                    dl_vals, dU_samples, x_intp=dl_intp, matrix=self.ti_matrix\n                )\n            else:\n                total_sem_matrix = self.results[phase][method][\"fraction_sem_matrix\"][\n                    max_fraction\n                ].magnitude\n            self.results[phase][method][\"roi\"] = np.zeros([num_win], np.float64)\n\n            for k in range(num_win):\n                # Compute overall integrated SEM with 10% smaller SEM for dU[k]\n                cnvg_dU_samples = np.array(dU_samples)\n                cnvg_dU_samples[:, k] = np.random.normal(\n                    dU_avgs[k], 0.9 * dU_sems[k], self.bootcycles\n                )\n                junk_fe, cnvg_sem_matrix = integrate_bootstraps(\n                    dl_vals, cnvg_dU_samples, x_intp=dl_intp, matrix=self.ti_matrix\n                )\n\n                #         d( dG_sem )      d( dUdl_sem )\n                # ROI = --------------- * ---------------\n                #        d( dUdl_sem )     d( n_frames )\n                #\n                # Deriv1----^---^---^        ^---^---^----Deriv2\n\n                # Deriv1:\n                deriv1 = (cnvg_sem_matrix[0, -1] - total_sem_matrix[0, -1]) / (\n                    -0.1 * dU_sems[k]\n                )\n\n                # Deriv2:\n                #\n                # dUdl_sem = dUdl_stddev / sqrt(n_frames/g)\n                #\n                # d( dUdl_sem )              dUdl_stddev\n                # -------------- =  - --------------------------\n                # d( n_frames )          2g * (n_frames/g)**3/2\n\n                deriv2 = (\n                    -1.0 * dU_stdv[k] / (2.0 * g[k] * (N_k[k] / g[k]) ** (3.0 / 2.0))\n                )\n\n                # ROI\n                self.results[phase][method][\"roi\"][k] = deriv1 * deriv2\n\n    def compute_free_energy(self, phases=[\"attach\", \"pull\", \"release\"], seed=None):\n        \"\"\"\n        Compute the free energy of binding from a simulation. This function populates the ``results`` dictionary\n        of the :class:`fe_calc` object.\n\n        Parameters\n        ----------\n        phases: list\n            Which phases of the calculation to analyze.\n        seed: int\n            Random number seed.\n        \"\"\"\n\n        for fraction in self.fractions:\n            if fraction <= 0.0 or fraction > 1.0:\n                raise Exception(\n                    \"The fraction of data to analyze must be 0 < fraction ≤ 1.0.\"\n                )\n\n        for phase in phases:\n            self.results[phase] = {}\n            self.results[phase][\"window_order\"] = self.orders[phase]\n\n            for method in self.methods:\n                if seed is not None:\n                    np.random.seed(seed)\n                    logger.debug(f\"Setting random number seed = {seed}\")\n\n                self.results[phase][method] = {}\n\n                # Prepare data\n                if sum(self.changing_restraints[phase]) == 0:\n                    logger.debug(\"Skipping free energy calculation for %s\" % phase)\n                    continue\n                prepared_data = self.prepare_data(phase)\n                self.results[phase][method][\"n_frames\"] = np.sum(prepared_data[1])\n\n                logger.debug(\n                    \"Running {} analysis on {} phase ...\".format(method, phase)\n                )\n\n                if method == \"mbar-block\" or method == \"mbar-autoc\":\n                    self.run_mbar(phase, prepared_data, method)\n                elif method == \"ti-block\":\n                    self.run_ti(phase, prepared_data, method)\n                else:\n                    raise NotImplementedError(\n                        f\"Method ({method}) is not implemented yet.\"\n                    )\n\n                # Store endpoint free energy and SEM for each fraction\n                self.results[phase][method][\"fraction_n_frames\"] = {}\n                self.results[phase][method][\"fraction_fe\"] = {}\n                self.results[phase][method][\"fraction_sem\"] = {}\n\n                for fraction in self.fractions:\n                    self.results[phase][method][\"fraction_n_frames\"][fraction] = int(\n                        fraction * self.results[phase][method][\"n_frames\"]\n                    )\n\n                    self.results[phase][method][\"fraction_fe\"][fraction] = self.results[\n                        phase\n                    ][method][\"fraction_fe_matrix\"][fraction][0, -1]\n\n                    self.results[phase][method][\"fraction_sem\"][\n                        fraction\n                    ] = self.results[phase][method][\"fraction_sem_matrix\"][fraction][\n                        0, -1\n                    ]\n\n                # Set these higher level (total) values, which will be slightly\n                # easier to access\n                max_fraction = np.max(self.fractions)\n                self.results[phase][method][\"fe_matrix\"] = self.results[phase][method][\n                    \"fraction_fe_matrix\"\n                ][max_fraction]\n                self.results[phase][method][\"sem_matrix\"] = self.results[phase][method][\n                    \"fraction_sem_matrix\"\n                ][max_fraction]\n                self.results[phase][method][\"fe\"] = self.results[phase][method][\n                    \"fe_matrix\"\n                ][0, -1]\n                self.results[phase][method][\"sem\"] = self.results[phase][method][\n                    \"sem_matrix\"\n                ][0, -1]\n\n                if self.compute_largest_neighbor:\n                    # Store convergence values, which are helpful for running\n                    # simulations\n                    windows = len(self.results[phase][method][\"sem_matrix\"])\n                    self.results[phase][method][\"largest_neighbor\"] = unit.Quantity(\n                        np.ones([windows], np.float64) * -1.0,\n                        units=self.energy_unit,\n                    )\n                    logger.info(f\"{phase}: computing largest_neighbor for {method}...\")\n\n                    for i in range(windows):\n                        if i == 0:\n                            self.results[phase][method][\"largest_neighbor\"][\n                                i\n                            ] = self.results[phase][method][\"sem_matrix\"][i][i + 1]\n                        elif i == windows - 1:\n                            self.results[phase][method][\"largest_neighbor\"][\n                                i\n                            ] = self.results[phase][method][\"sem_matrix\"][i][i - 1]\n                        else:\n                            left = self.results[phase][method][\"sem_matrix\"][i][i - 1]\n                            right = self.results[phase][method][\"sem_matrix\"][i][i + 1]\n                            if left > right:\n                                max_val = left\n                            elif right > left:\n                                max_val = right\n                            else:\n                                max_val = right\n                            self.results[phase][method][\"largest_neighbor\"][i] = max_val\n\n    def compute_ref_state_work(self, restraints):\n        \"\"\"\n        Compute the work to place a molecule at standard reference state conditions\n        starting from a state defined by up to six restraints. These are Boresch-style restraints.\n\n        Parameters\n        ----------\n        restraints : list\n            A list of :class:`paprika.restraints.DAT_restraint` objects in order of the six translational and\n            orientational restraints needed to describe the configuration of one molecule\n            relative to another. The six restraints are: r, theta, phi, alpha, beta, gamma and they should be passed to\n            this function in that order. If any of these coordinates is not being restrained, use a `None` in place of a\n            :class:`paprika.restraints.DAT_restraint` object.\n\n            See :meth:`paprika.analysis.ref_state_work` for details on the calculation.\n        \"\"\"\n\n        if not restraints or restraints[0] is None:\n            raise ValueError(\n                \"At minimum, a single distance restraint is necesarry to compute the work of releasing\"\n                \" the guest to standard state.\"\n            )\n\n        fcs = []\n        targs = []\n\n        for restraint in restraints:\n            if restraint is None:\n                fcs.append(None)\n                targs.append(None)\n            elif restraint.phase[\"release\"][\"force_constants\"] is not None:\n                fcs.append(np.sort(restraint.phase[\"release\"][\"force_constants\"])[-1])\n                targs.append(np.sort(restraint.phase[\"release\"][\"targets\"])[-1])\n            elif restraint.phase[\"pull\"][\"force_constants\"] is not None:\n                fcs.append(np.sort(restraint.phase[\"pull\"][\"force_constants\"])[-1])\n                targs.append(np.sort(restraint.phase[\"pull\"][\"targets\"])[-1])\n            else:\n                raise ValueError(\n                    \"Restraints should have pull or release values initialized in order to compute_ref_state_work\"\n                )\n\n        self.results[\"ref_state_work\"] = ref_state_work(\n            self.temperature,\n            fcs[0],\n            targs[0],\n            fcs[1],\n            targs[1],\n            fcs[2],\n            targs[2],\n            fcs[3],\n            targs[3],\n            fcs[4],\n            targs[4],\n            fcs[5],\n            targs[5],\n        )\n\n    def save_results(self, filepath=\"results.json\", overwrite=False):\n        \"\"\"\n        Save the analysis results to a JSON file.\n\n        Parameters\n        ----------\n        filepath: os.PathLike\n            The name of the JSON file to write to.\n        overwrite: bool\n            Option to whether overwrite file if already exist.\n        \"\"\"\n        if overwrite and os.path.isfile(filepath):\n            raise FileExistsError(f\"File `{filepath}` exists, will not overwrite.\")\n\n        with open(filepath, \"w\") as f:\n            dumped = json.dumps(self.results, cls=PaprikaEncoder)\n            f.write(dumped)\n\n    @staticmethod\n    def load_results(filepath):\n        \"\"\"\n        Read in a JSON file for the results.\n\n        Parameters\n        ----------\n        filepath: os.PathLike\n            The name of the JSON file to read.\n        \"\"\"\n        with open(filepath, \"r\") as f:\n            data = f.read()\n\n        return json.loads(data, cls=PaprikaDecoder)\n\n    def save_data(self, filepath=\"simulation_data.json\", overwrite=False):\n        \"\"\"\n        Save the simulation data (DAT values) to a JSON file.\n\n        Parameters\n        ----------\n        filepath: os.PathLike\n            The name of the JSON file to write to.\n        overwrite: bool\n            Option to whether overwrite file if already exist.\n        \"\"\"\n        if overwrite and os.path.isfile(filepath):\n            raise FileExistsError(f\"File `{filepath}` exists, will not overwrite.\")\n\n        with open(filepath, \"w\") as f:\n            dumped = json.dumps(\n                {\n                    \"simulation_data\": self.simulation_data,\n                    \"changing_restraints\": self.changing_restraints,\n                    \"orders\": self.orders,\n                },\n                cls=PaprikaEncoder,\n            )\n            f.write(dumped)\n\n\ndef get_factors(n):\n    \"\"\"\n    Return a list of integer factors for a number.\n\n    Parameters\n    ----------\n    n: int or float\n        Number to factor\n\n    Returns\n    -------\n    sorted: list\n        A list of sorted factors.\n\n    \"\"\"\n    factors = []\n    sqrt_n = int(round(np.sqrt(n) + 0.5))\n    i = 1\n    while i <= sqrt_n:\n        if n % i == 0:\n            factors.append(int(i))\n            j = n / i\n            if j != i:\n                factors.append(int(j))\n        i += 1\n    return sorted(factors, key=int)\n\n\ndef get_nearest_max(n):\n    \"\"\"\n    Return the number with the largest number of factors between n − 100 and n.\n\n    Parameters\n    ----------\n    n: int\n        Desired number to factor.\n\n    Returns\n    -------\n    most_factors: int\n        The number with the most factors.\n\n    \"\"\"\n    max_factors = 0\n    if n % 2 == 0:\n        beg = n - 100\n        end = n\n    else:\n        beg = n - 101\n        end = n - 1\n    if beg < 0:\n        beg = 0\n    for i in range(beg, end + 2, 2):\n        num_factors = len(get_factors(i))\n        if num_factors >= max_factors:\n            max_factors = num_factors\n            most_factors = i\n    return most_factors\n\n\ndef get_block_sem(data_array):\n    \"\"\"\n    Compute the standard error of the mean (SEM) using the blocking method.\n\n    Note\n    ----\n        This is a conservative approach. Here, we report the maximum SEM determined from blocking analysis (cf. the\n        \"plateau\" on the blocking curve).\n\n    Parameters\n    ----------\n    data_array: :class:`np.array`\n        Array containing data values.\n\n    Returns\n    -------\n    np.max(sems): float\n        The maximum SEM obtained from te blocking curve.\n\n    \"\"\"\n    # Get the integer factors for the number of data points. These\n    # are equivalent to the block sizes we will check.\n    block_sizes = get_factors(len(data_array))\n\n    # An array to store means for each block ... make it bigger than we need.\n    block_means = np.zeros([block_sizes[-1]], np.float64)\n\n    # Store the SEM for each block size, except the last two size for which\n    # there will only be two or one blocks total and thus very noisy.\n    sems = np.zeros([len(block_sizes) - 2], np.float64)\n\n    # Check each block size except the last two.\n    for size_idx in range(len(block_sizes) - 2):\n        # Check each block, the number of which is conveniently found as\n        # the other number of the factor pair in block_sizes\n        num_blocks = block_sizes[-size_idx - 1]\n        for blk_idx in range(num_blocks):\n            # Find the index for beg and end of data points for each block\n            data_beg_idx = blk_idx * block_sizes[size_idx]\n            data_end_idx = (blk_idx + 1) * block_sizes[size_idx]\n            # Compute the mean of this block and store in array\n            block_means[blk_idx] = np.mean(data_array[data_beg_idx:data_end_idx])\n        # Compute the standard deviation across all blocks, devide by\n        # num_blocks-1 for SEM\n        sems[size_idx] = np.std(block_means[0:num_blocks], ddof=0) / np.sqrt(\n            num_blocks - 1\n        )\n        # Hmm or should ddof=1? I think 0, see Flyvbjerg -----^\n\n    return np.max(sems)\n\n\ndef get_subsampled_indices(N, g, conservative=False):\n    \"\"\"Get the indices of independent (subsampled) frames. This is adapted from the implementation in `pymbar`.\n\n    Parameters\n    ----------\n    N: int\n        The length of the array to be indexed.\n    g: int\n        The statistical inefficiency of the data.\n    conservative: bool, optional, default=False\n        Whether `g` should be rounded up to the nearest integer.\n\n    Returns\n    -------\n    indices: list\n        A list of indices that can be used to pull out de-correlated frames from a time series.\n\n    \"\"\"\n\n    # g should not be less than 1.0\n    if g < 1.0:\n        g = 1.0\n\n    # if conservative, assume integer g and round up\n    if conservative:\n        g = np.ceil(g)\n\n    # initialize\n    indices = [0]\n    g_idx = 1.0\n    int_step = int(np.round(g_idx * g))\n\n    while int_step < N:\n        indices.append(int_step)\n        g_idx += 1.0\n        int_step = int(np.round(g_idx * g))\n\n    return indices\n\n\ndef load_trajectory(window, trajectory, topology, single_topology=False):\n    \"\"\"Load a trajectory (or trajectories) and return a pytraj ``trajectory`` object.\n\n    Parameters\n    ----------\n    window: str\n        The simulation window to analyze\n    trajectory: str or list\n        The name or names of the trajectory\n    topology: str or :class:`parmed.Structure`\n        The topology the simulation\n    single_topology: bool\n        Whether a single topology is read for all windows\n\n    Returns\n    -------\n    traj: pytraj.trajectory\n        The trajectory of stored as a pytraj object.\n    \"\"\"\n\n    logger.debug(\"Load trajectories from {}/{}...\".format(window, trajectory))\n    if isinstance(trajectory, str):\n        trajectory_path = os.path.join(window, trajectory)\n    elif isinstance(trajectory, list):\n        trajectory_path = [os.path.join(window, i) for i in trajectory]\n        logger.debug(\"Received list of trajectories: {}\".format(trajectory_path))\n    else:\n        raise RuntimeError(\"Trajectory path should be a `str` or `list`.\")\n\n    if isinstance(topology, str) and not single_topology:\n        if not os.path.isfile(os.path.join(window, topology)):\n            raise FileNotFoundError(\n                f\"Cannot find `topology` file: {os.path.join(window, topology)}\"\n            )\n        logger.debug(f\"Loading {os.path.join(window, topology)} and {trajectory_path}\")\n        try:\n            traj = pt.iterload(trajectory_path, os.path.join(window, topology))\n        except ValueError as e:\n            formatted_exception = traceback.format_exception(None, e, e.__traceback__)\n            logger.info(\n                f\"Failed trying to load {os.path.join(window, topology)} and {trajectory_path}: \"\n                f\"{formatted_exception}\"\n            )\n    elif isinstance(topology, str) and single_topology:\n        traj = pt.iterload(trajectory_path, os.path.join(topology))\n    else:\n        try:\n            traj = pt.iterload(trajectory_path, topology)\n        except BaseException:\n            raise Exception(\"Tried to load `topology` object directly and failed.\")\n\n    logger.debug(\"Loaded {} frames...\".format(traj.n_frames))\n\n    return traj\n\n\ndef read_restraint_data(traj, restraint):\n    \"\"\"Given a trajectory and restraint, read the restraint and return the DAT values.\n\n    Parameters\n    ----------\n    traj: :class:`pytraj.trajectory`\n        A trajectory, probably loaded by load_trajectory\n    restraint: :class:`DAT_restraint`\n        The restraint to analyze\n\n    Returns\n    -------\n    data: :class:`np.array`\n        The values for this restraint in this window\n    \"\"\"\n\n    if (\n        restraint.mask1\n        and restraint.mask2\n        and not restraint.mask3\n        and not restraint.mask4\n    ):\n        data = unit.Quantity(\n            pt.distance(traj, \" \".join([restraint.mask1, restraint.mask2]), image=True),\n            units=unit.angstrom,\n        )\n\n    elif (\n        restraint.mask1 and restraint.mask2 and restraint.mask3 and not restraint.mask4\n    ):\n        data = unit.Quantity(\n            pt.angle(\n                traj, \" \".join([restraint.mask1, restraint.mask2, restraint.mask3])\n            ),\n            units=unit.degrees,\n        )\n\n    elif restraint.mask1 and restraint.mask2 and restraint.mask3 and restraint.mask4:\n        data = unit.Quantity(\n            pt.dihedral(\n                traj,\n                \" \".join(\n                    [restraint.mask1, restraint.mask2, restraint.mask3, restraint.mask4]\n                ),\n            ),\n            units=unit.degrees,\n        )\n\n    return data\n\n\ndef ref_state_work(\n    temperature,\n    r_fc,\n    r_tg,\n    th_fc,\n    th_tg,\n    ph_fc,\n    ph_tg,\n    a_fc,\n    a_tg,\n    b_fc,\n    b_tg,\n    g_fc,\n    g_tg,\n):\n    \"\"\"\n    Computes the free energy to release a molecule from some restrained translational\n    and orientational configuration (relative to another molecule or lab frame) into\n    the reference configuration: standard concentration (1.0/1660.5392 Å³) and\n    unrestrained orientational freedom (8π²).\n\n    The Wikipedia entry on Euler angles is useful.\n\n    Assume two molecules (H and G). Three translational and three orientational degrees\n    of freedom define their relative configuration. In order to match experimentally\n    reported free energies, we often need to compute the work (free energy) of moving\n    a molecule (G) from a restrained configuration relative to H into the experimental\n    reference state (usually defined as 1 M, or 1 molecule per 1660.5 Å³)\n\n    ::\n\n        H3\n          \\        [a1]                [a2]\n           H2-------H1-------<d1>-------G1-------G2\n              {t1}           {t2}           {t3}   \\\n                                                   G3\n\n        Degrees of Freedom\n        -----------------------------------------------------------------\n         id   atoms        type, spherical coordinate/Euler angle\n        -----------------------------------------------------------------\n        <d1>: H1-G1         distance, r\n        [a1]: H2-H1-G1      angle, theta\n        {t1}: H3-H2-H1-G1   torsion, phi\n        {t2}: H2-H1-G1-G2   torsion, alpha\n        [a2]: H1-G1-G2      angle, beta\n        {t3}: H1-G1-G2-G3   torsion, gamma\n\n    Parameters\n    ----------\n    temperature : unit.Quantity\n        The temperature (in Kelvin) at which the reference state calculation will take place.\n    r_fc: unit.Quantity\n        The distance, :math:`r`, restraint force constant (kcal/mol-Å²).\n    r_tg : unit.Quantity\n        The distance, :math:`r`, restraint target values (Å). The target range is 0 to infinity.\n    th_fc : unit.Quantity\n        The angle, :math:`θ`, restraint force constant (kcal/mol-radian²).\n    th_tg : unit.Quantity\n        The angle, :math:`θ`, restraint target values (radian). The target range is 0 to π.\n    ph_fc : unit.Quantity\n        The torsion, :math:`\\\\phi`, restraint force constant (kcal/mol-radian²).\n    ph_tg : unit.Quantity\n        The torsion, :math:`\\\\phi`, restraint target values (radian). The target range is 0 to 2π.\n    a_fc : unit.Quantity\n        The torsion, :math:`α`, restraint force constant (kcal/mol-radian²).\n    a_tg: unit.Quantity\n        The torsion, :math:`α`, restraint target values (radian). The target range is 0 to 2π.\n    b_fc : unit.Quantity\n        The angle, :math:`β`, restraint force (kcal/mol-radian²).\n    b_tg : unit.Quantity\n        The angle, :math:`β`, restraint target values (radian). The target range is 0 to π.\n    g_fc: unit.Quantity\n        The angle, :math:`γ`, restraint force (kcal/mol-radian²).\n    g_tg: unit.Quantity\n        The angle, :math:`γ`, restraint target values (radian). The target range is 0 to 2π.\n\n    Returns\n    -------\n    RT * np.log(trans * orient): float\n        The free energy associated with releasing the restraints (in kcal/mol Pint units).\n    \"\"\"\n\n    R = 1.987204118e-3 * unit.kcal / unit.mole / unit.kelvin\n    RT = R * temperature\n\n    # Distance Integration Function\n    def dist_int(RT, fc, targ):\n        def potential(arange, RT, fc, targ):\n            return (arange ** 2) * np.exp((-1.0 / RT) * fc * (arange - targ) ** 2)\n\n        arange = np.arange(0.0, 100.0, 0.0001) * unit.angstrom\n        return np.trapz(potential(arange, RT, fc, targ), arange)\n\n    # Angle Integration Function\n    def ang_int(RT, fc, targ):\n        def potential(arange, RT, fc, targ):\n            return np.sin(arange) * np.exp((-1.0 / RT) * fc * (arange - targ) ** 2)\n\n        arange = np.arange(0.0, np.pi, 0.00005) * unit.radians\n        return np.trapz(potential(arange, RT, fc, targ), arange)\n\n    # Torsion Integration Function\n    def tors_int(RT, fc, targ):\n        def potential(arange, RT, fc, targ):\n            return np.exp((-1.0 / RT) * fc * (arange - targ) ** 2)\n\n        # Note, because of periodicity, I'm gonna wrap +/- pi around target for integration.\n        arange = np.arange(targ - np.pi, targ + np.pi, 0.00005) * unit.radians\n        return np.trapz(potential(arange, RT, fc, targ), arange)\n\n    # Distance restraint, r\n    if None in [r_fc, r_tg]:\n        raise Exception(\"Distance restraint info (r_fc, r_tg) must be specified\")\n    else:\n        r_int = dist_int(RT, r_fc, r_tg)\n\n    # Angle restraint, theta\n    if None in [th_fc, th_tg]:\n        th_int = 2.0\n    else:\n        th_int = ang_int(RT, th_fc, th_tg)\n\n    # Torsion restraint, phi\n    if None in [ph_fc, ph_tg]:\n        ph_int = 2.0 * np.pi * unit.radians\n    else:\n        ph_int = tors_int(RT, ph_fc, ph_tg)\n\n    # Torsion restraint, alpha\n    if None in [a_fc, a_tg]:\n        a_int = 2.0 * np.pi * unit.radians\n    else:\n        a_int = tors_int(RT, a_fc, a_tg)\n\n    # Angle restraint, beta\n    if None in [b_fc, b_tg]:\n        b_int = 2.0\n    else:\n        b_int = ang_int(RT, b_fc, b_tg)\n\n    # Torsion restraint, gamma\n    if None in [g_fc, g_tg]:\n        g_int = 2.0 * np.pi * unit.radians\n    else:\n        g_int = tors_int(RT, g_fc, g_tg)\n\n    # Concentration term\n    V0 = 1660.5392 * unit.angstrom ** 3\n    translational = r_int * th_int * ph_int * (1.0 / V0)  # C^o = 1/V^o\n\n    # Orientational term\n    rotational_volume = 8.0 * np.pi ** 2\n    orientational = a_int * b_int * g_int / rotational_volume\n\n    # Return the free energy\n    return RT * np.log(translational * orientational)\n\n\ndef integrate_bootstraps(x, ys, x_intp=None, matrix=\"full\"):\n    \"\"\"\n    Integrate splines created via bootstrapping.\n\n    Parameters\n    ----------\n    x: :class:`np.array`\n        The x coordinate of the curve to be integrated.\n    ys: :class:`np.array`\n        Two dimensional array in which the first dimension is bootcycles and the second\n        dimension contains the arrays of y values which correspond to the x values and will\n        be used for integration. The shape of this is :code:`(bootcycles, len(x))`.\n    x_intp: :class:`np.array`, optional, default=None\n        An array which finely interpolates the x values. If not provided, it will be generated\n        by adding 100 evenly spaced points between each x value. Default: None.\n    matrix: str, optional, default='full`\n        If ``full``, the mean and SEM integration is computed between x values. If ``diagonal``,\n        the mean and SEM integration is computed between the first value and all other values,\n        as well as the neighboring values to each value. If ``endpoints``, the integration\n        is computed between only the first and last x value.\n\n    Returns\n    -------\n    avg_matrix: :class:`np.array`\n        Matrix of the integration mean between each x value (as specified by 'matrix')\n    sem_matrix: :class:`np.array`\n        Matrix of the uncertainty (SEM) between each x value (as specified by 'matrix')\n\n    \"\"\"\n\n    num_x = len(x)\n\n    # Prepare to store the index location of the x values in the x_intp array\n    x_idxs = np.zeros([num_x], np.int32)\n\n    # If not provided, generate x interpolation with 100 inpolated points between\n    # each x value. Store the index locations of the x values in the x_intp\n    # array.\n    if x_intp is None:\n        x_intp = np.zeros([0], np.float64)\n        for i in range(1, num_x):\n            x_intp = np.append(\n                x_intp, np.linspace(x[i - 1], x[i], num=100, endpoint=False)\n            )\n            x_idxs = len(x_intp)\n        # Tack on the final value onto the interpolation\n        x_intp = np.append(x_intp, x[-1])\n    # If x_intp is provided, find the locations of x values in x_intp\n    else:\n        i = 0\n        for j in range(len(x_intp)):\n            if np.isclose(x[i], x_intp[j]):\n                x_idxs[i] = j\n                i += 1\n        if i != num_x:\n            raise Exception(\n                \"One or more x values seem to be missing in the x_intp array,\"\n                + \" or one of the lists is not monotonically increasing!\"\n            )\n\n    cycles = len(ys)\n\n    # Setup array to store integration bootstraps\n    int_matrix = np.zeros([num_x, num_x, cycles], np.float64)\n\n    # Do the integration bootstraps. Originally, I had matrix=endpoints in the loop\n    # below with everthing else, but I'll split it out here in case that's faster\n    # due to avoiding the if statements.\n    if matrix == \"endpoints\":\n        for cycle in range(cycles):\n            intp_func = Akima1DInterpolator(x, ys[cycle])\n            y_intp = intp_func(x_intp)\n            #            for i in range(0, num_x):\n            #                for j in range(i+1, num_x):\n            #                    int_matrix[i, j, cycle] = np.trapz( y_intp, x_intp )\n            int_matrix[0, num_x - 1, cycle] = np.trapz(y_intp, x_intp)\n    else:\n        for cycle in range(cycles):\n            intp_func = Akima1DInterpolator(x, ys[cycle])\n            y_intp = intp_func(x_intp)\n            for i in range(0, num_x):\n                for j in range(i + 1, num_x):\n                    if matrix == \"diagonal\" and i != 0 and j - i > 1:\n                        continue\n                    beg = x_idxs[i]\n                    end = x_idxs[j]\n                    int_matrix[i, j, cycle] = np.trapz(y_intp[beg:end], x_intp[beg:end])\n\n    # Setup matrices to store the average/sem values.\n    # Is it bad that the default is 0.0 rather than None?\n    avg_matrix = np.zeros([num_x, num_x], np.float64)\n    sem_matrix = np.zeros([num_x, num_x], np.float64)\n\n    # Second pass to compute the mean and standard deviation.\n    for i in range(0, num_x):\n        for j in range(i + 1, num_x):\n            # If quick_ti_matrix, only populate first row and neighbors in\n            # matrix\n            if matrix == \"diagonal\" and i != 0 and j - i > 1:\n                continue\n            if matrix == \"endpoints\" and i != 0 and j != num_x - 1:\n                continue\n            avg_matrix[i, j] = np.mean(int_matrix[i, j])\n            avg_matrix[j, i] = -1.0 * avg_matrix[i, j]\n            sem_matrix[i, j] = np.std(int_matrix[i, j])\n            sem_matrix[j, i] = sem_matrix[i, j]\n\n    return avg_matrix, sem_matrix\n", "meta": {"hexsha": "0c712cbc452a9b38dee2ffd4affa53facd4941f6", "size": 72017, "ext": "py", "lang": "Python", "max_stars_repo_path": "paprika/analysis.py", "max_stars_repo_name": "slochower/pAPRika", "max_stars_repo_head_hexsha": "50a6c148f88db896e94bd5f03c4f4bebb129b0f1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-04-19T23:46:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T19:47:02.000Z", "max_issues_repo_path": "paprika/analysis.py", "max_issues_repo_name": "slochower/pAPRika", "max_issues_repo_head_hexsha": "50a6c148f88db896e94bd5f03c4f4bebb129b0f1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 154, "max_issues_repo_issues_event_min_datetime": "2017-04-20T16:05:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T21:07:18.000Z", "max_forks_repo_path": "paprika/analysis.py", "max_forks_repo_name": "slochower/pAPRika", "max_forks_repo_head_hexsha": "50a6c148f88db896e94bd5f03c4f4bebb129b0f1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2017-07-06T07:55:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T05:05:44.000Z", "avg_line_length": 38.2458842273, "max_line_length": 127, "alphanum_fraction": 0.5671994113, "include": true, "reason": "import numpy,from scipy", "num_tokens": 16059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.19799956925998322}}
{"text": "\"\"\"Contains classes for transformer architecture within CrabNet.\"\"\"\nfrom os.path import join, dirname\n\nimport numpy as np\nimport pandas as pd\n\nimport torch\nfrom torch import nn\nfrom collections import OrderedDict\n\nRNG_SEED = 42\ntorch.manual_seed(RNG_SEED)\nnp.random.seed(RNG_SEED)\ndata_type_torch = torch.float32\n\n\n# %%\nclass ResidualNetwork(nn.Module):\n    \"\"\"\n    Feed forward Residual Neural Network as seen in Roost.\n\n    https://doi.org/10.1038/s41467-020-19964-7\n    \"\"\"\n\n    def __init__(self, input_dim, output_dim, hidden_layer_dims, bias=False):\n        \"\"\"Instantiate a ResidualNetwork model.\n\n        Parameters\n        ----------\n        input_dim : int\n            Input dimensions for the Residual Network, specified in SubCrab() model class, by default 512\n        output_dim : int\n            Output dimensions for Residual Network, by default 3\n        hidden_layer_dims : list(int)\n            Hidden layer architecture for the Residual Network, by default [1024, 512, 256, 128]\n        bias : bool\n            Whether to bias the linear network, by default False\n        \"\"\"\n        super(ResidualNetwork, self).__init__()\n        dims = [input_dim] + hidden_layer_dims\n        self.fcs = nn.ModuleList(\n            [nn.Linear(dims[i], dims[i + 1]) for i in range(len(dims) - 1)]\n        )\n        self.res_fcs = nn.ModuleList(\n            [\n                nn.Linear(dims[i], dims[i + 1], bias=bias)\n                if (dims[i] != dims[i + 1])\n                else nn.Identity()\n                for i in range(len(dims) - 1)\n            ]\n        )\n        self.acts = nn.ModuleList([nn.LeakyReLU() for _ in range(len(dims) - 1)])\n        self.fc_out = nn.Linear(dims[-1], output_dim)\n\n    def forward(self, fea):\n        \"\"\"Propagate Residual Network weights forward.\n\n        Parameters\n        ----------\n        fea : torch.tensor (n_dim)\n            Tensor output of self attention block\n        Returns\n        -------\n        fc_out\n            The output of the Residual Network\n        \"\"\"\n        for fc, res_fc, act in zip(self.fcs, self.res_fcs, self.acts):\n            fea = act(fc(fea)) + res_fc(fea)\n        return self.fc_out(fea)\n\n    def __repr__(self):\n        \"\"\"Return the class name.\"\"\"\n        return f\"{self.__class__.__name__}\"\n\n\nclass TransferNetwork(nn.Module):\n    \"\"\"Learn extended representations of materials during transfer learning.\n\n    This network was designed to have little impact on predictions during\n    training and enhance learning with the inclusion of extended features.\n    \"\"\"\n\n    def __init__(self, input_dims, output_dims):\n        \"\"\"Instantiate a TransferNetwork to learn extended representations.\n\n        Parameters\n        ----------\n        input_dims : int\n            Dimensions of input layer\n\n        output_dims : int\n            Dimensions of output layer\n        \"\"\"\n        super().__init__()\n        self.layers = nn.Sequential(\n            OrderedDict(\n                [\n                    (\"fc1\", nn.Linear(input_dims, 512)),\n                    (\"leakyrelu1\", nn.LeakyReLU()),\n                    (\"fc2\", nn.Linear(512, output_dims)),\n                    (\"leakyrelu2\", nn.LeakyReLU()),\n                ]\n            )\n        )\n\n    def forward(self, x):\n        \"\"\"Perform a forward pass of the TransferNetwork.\n\n        Parameters\n        ----------\n        x : _type_\n            _description_\n\n        Returns\n        -------\n        _type_\n            _description_\n        \"\"\"\n        x = self.layers(x)\n        return x\n\n\nclass Embedder(nn.Module):\n    \"\"\"Perform composition-based embeddings of elemental features.\"\"\"\n\n    def __init__(\n        self,\n        d_model: int,\n        compute_device: str = None,\n        elem_prop: str = \"mat2vec\",\n    ):\n        \"\"\"Embed elemental features, similar to CBFV.\n\n        Parameters\n        ----------\n        d_model : int\n            Row dimenions of elemental emeddings, by default 512\n        compute_device : str\n            Name of device which the model will be run on\n        elem_prop : str\n            Which elemental feature vector to use. Possible values are \"jarvis\",\n            \"magpie\", \"mat2vec\", \"oliynyk\", \"onehot\", \"ptable\", and \"random_200\", by\n            default \"mat2vec\"\n        \"\"\"\n        super().__init__()\n        self.d_model = d_model\n        self.compute_device = compute_device\n\n        elem_dir = join(dirname(__file__), \"data\", \"element_properties\")\n        # # Choose what element information the model receives\n        mat2vec = join(elem_dir, elem_prop + \".csv\")  # element embedding\n        # mat2vec = f'{elem_dir}/onehot.csv'  # onehot encoding (atomic number)\n        # mat2vec = f'{elem_dir}/random_200.csv'  # random vec for elements\n\n        cbfv = pd.read_csv(mat2vec, index_col=0).values\n        feat_size = cbfv.shape[-1]\n        self.fc_mat2vec = nn.Linear(feat_size, d_model).to(self.compute_device)\n        zeros = np.zeros((1, feat_size))\n        cat_array = np.concatenate([zeros, cbfv])\n        cat_array = torch.as_tensor(cat_array, dtype=data_type_torch)\n        # NOTE: Parameters within nn.Embedding\n        self.cbfv = nn.Embedding.from_pretrained(cat_array).to(\n            self.compute_device, dtype=data_type_torch\n        )\n\n    def forward(self, src):\n        \"\"\"Compute forward call for embedder class to perform elemental embeddings.\n\n        Parameters\n        ----------\n        src : torch.tensor\n            Tensor containing element numbers corresponding to elements in compound\n\n        Returns\n        -------\n        torch.tensor\n            Tensor containing elemental embeddings for compounds, reduced to d_model dimensions\n        \"\"\"\n        mat2vec_emb = self.cbfv(src)\n        x_emb = self.fc_mat2vec(mat2vec_emb)\n        return x_emb\n\n\n# %%\nclass FractionalEncoder(nn.Module):\n    \"\"\"Encode element fractional amount using a \"fractional encoding\".\n\n    This is inspired by the positional encoder discussed by Vaswani.\n    https://arxiv.org/abs/1706.03762\n    \"\"\"\n\n    def __init__(self, d_model, resolution=100, log10=False, compute_device=None):\n        \"\"\"Instantiate the FractionalEncoder.\n\n        Parameters\n        ----------\n        d_model : int\n            Model size, see paper, by default 512\n        resolution : int\n            Number of discretizations for the fractional prevalence encoding, by default 100\n        log10 : bool\n            Whether to apply a log operation to fraction prevalence encoding, by default False\n        compute_device : str\n            The compute device to store and run the FractionalEncoder class\n        \"\"\"\n        super().__init__()\n        self.d_model = d_model // 2\n        self.resolution = resolution\n        self.log10 = log10\n        self.compute_device = compute_device\n\n        x = torch.linspace(\n            0, self.resolution - 1, self.resolution, requires_grad=False\n        ).view(self.resolution, 1)\n        fraction = (\n            torch.linspace(0, self.d_model - 1, self.d_model, requires_grad=False)\n            .view(1, self.d_model)\n            .repeat(self.resolution, 1)\n        )\n\n        pe = torch.zeros(self.resolution, self.d_model)\n        pe[:, 0::2] = torch.sin(x / torch.pow(50, 2 * fraction[:, 0::2] / self.d_model))\n        pe[:, 1::2] = torch.cos(x / torch.pow(50, 2 * fraction[:, 1::2] / self.d_model))\n        pe = self.register_buffer(\"pe\", pe)\n\n    def forward(self, x):\n        \"\"\"Perform the forward pass of the fractional encoding.\n\n        Parameters\n        ----------\n        x : torch.tensor\n            Tensor of linear spaced values based on defined resolution\n\n        Returns\n        -------\n        out\n            Sinusoidal expansions of elemental fractions\n        \"\"\"\n        x = x.clone()\n        if self.log10:\n            x = 0.0025 * (torch.log2(x)) ** 2\n            x[x > 1] = 1\n            # x = 1 - x  # for sinusoidal encoding at x=0\n        x[x < 1 / self.resolution] = 1 / self.resolution\n        frac_idx = torch.round(x * (self.resolution)).to(dtype=torch.long) - 1\n        out = self.pe[frac_idx]\n\n        return out\n\n\n# %%\nclass Encoder(nn.Module):\n    \"\"\"Create elemental descriptor matrix via element embeddings and frac. encodings.\n\n    See the CrabNet paper for further details:\n    https://www.nature.com/articles/s41524-021-00545-1\n    \"\"\"\n\n    def __init__(\n        self,\n        d_model,\n        N,\n        heads,\n        extend_features=None,\n        fractional=True,\n        attention=True,\n        compute_device=None,\n        pe_resolution=5000,\n        ple_resolution=5000,\n        elem_prop=\"mat2vec\",\n        emb_scaler=1.0,\n        pos_scaler=1.0,\n        pos_scaler_log=1.0,\n        dim_feedforward=2048,\n        dropout=0.1,\n    ):\n        \"\"\"Instantiate the Encoder class to create elemental descriptor matrix (EDM).\n\n        Parameters\n        ----------\n        d_model : _type_\n            _description_\n        N : int, optional\n            Number of encoder layers, by default 3\n        heads : int, optional\n            Number of attention heads to use, by default 4\n        extend_features : Optional[List[str]]\n            Additional features to grab from columns of the other DataFrames (e.g. state\n            variables such as temperature or applied load), by default None\n        fractional : bool, optional\n            Whether to weight each element by its fractional contribution, by default True.\n        attention : bool, optional\n            Whether to perform self attention, by default True\n        pe_resolution : int, optional\n            Number of discretizations for the prevalence encoding, by default 5000\n        ple_resolution : int, optional\n            Number of discretizations for the prevalence log encoding, by default 5000\n        elem_prop : str, optional\n            Which elemental feature vector to use. Possible values are \"jarvis\",\n            \"magpie\", \"mat2vec\", \"oliynyk\", \"onehot\", \"ptable\", and \"random_200\", by\n            default \"mat2vec\"\n        emb_scaler : float, optional\n            _description_, by default 1.0\n        pos_scaler : float, optional\n            Scaling factor applied to fractional encoder, by default 1.0\n        pos_scaler_log : float, optional\n            Scaling factor applied to log fractional encoder, by default 1.0\n        dim_feedforward : int, optional\n            Dimenions of the feed forward network following transformer, by default 2048\n        dropout : float, optional\n            Percent dropout in the feed forward network following the transformer, by default 0.1\n        \"\"\"\n        super().__init__()\n        self.d_model = d_model\n        self.N = N\n        self.heads = heads\n        self.extend_features = extend_features\n        self.fractional = fractional\n        self.attention = attention\n        self.compute_device = compute_device\n        self.pe_resolution = pe_resolution\n        self.ple_resolution = ple_resolution\n        self.elem_prop = elem_prop\n        self.embed = Embedder(d_model=self.d_model, compute_device=self.compute_device)\n        self.prevalence_encoder = FractionalEncoder(\n            self.d_model, resolution=pe_resolution, log10=False\n        )\n        self.prevalence_log_encoder = FractionalEncoder(\n            self.d_model, resolution=ple_resolution, log10=True\n        )\n\n        self.emb_scaler = nn.parameter.Parameter(torch.tensor([emb_scaler]))\n        self.pos_scaler = nn.parameter.Parameter(torch.tensor([pos_scaler]))\n        self.pos_scaler_log = nn.parameter.Parameter(torch.tensor([pos_scaler_log]))\n\n        if self.attention:\n            encoder_layer = nn.TransformerEncoderLayer(\n                self.d_model,\n                nhead=self.heads,\n                dim_feedforward=dim_feedforward,\n                dropout=dropout,\n            )\n            self.transformer_encoder = nn.TransformerEncoder(\n                encoder_layer, num_layers=self.N\n            )\n\n    def forward(self, src, frac, extra_features=None):\n        \"\"\"Compute the forward pass for encoding the elemental descriptor matrix.\n\n        Parameters\n        ----------\n        src : torch.tensor\n            Tensor containing integers corresponding to elements in compound\n        frac : torch.tensor\n            Tensor containing the fractions of each element in compound\n        extra_features : bool, optional\n            Whether to append extra features after encoding, by default None\n\n        Returns\n        -------\n        torch.tensor\n            Tensor containing flattened transformer representations of compounds\n            concatenated with extended features.\n        \"\"\"\n        x = self.embed(src) * self.emb_scaler  # * 2 ** self.emb_scaler\n\n        pe = torch.zeros_like(x)\n        ple = torch.zeros_like(x)\n        pe_scaler = self.pos_scaler\n        ple_scaler = self.pos_scaler_log\n        pe[:, :, : self.d_model // 2] = self.prevalence_encoder(frac) * pe_scaler\n        ple[:, :, self.d_model // 2 :] = self.prevalence_log_encoder(frac) * ple_scaler\n\n        mask = frac.unsqueeze(dim=-1)\n        mask = torch.matmul(mask, mask.transpose(-2, -1))\n        mask[mask != 0] = 1\n        src_mask = mask[:, 0] != 1\n\n        if self.attention:\n            x_src = x + pe + ple\n            x_src = x_src.transpose(0, 1)\n            x = self.transformer_encoder(x_src, src_key_padding_mask=src_mask)\n            x = x.transpose(0, 1)\n\n        if self.fractional:\n            x = x * frac.unsqueeze(2).repeat(1, 1, self.d_model)\n\n        hmask = mask[:, :, 0:1].repeat(1, 1, self.d_model)\n        if mask is not None:\n            x = x.masked_fill(hmask == 0, 0)\n\n        if self.extend_features is not None:\n            n_elements = x.shape[1]\n            X_extra = extra_features.repeat(1, 1, n_elements).permute([1, 2, 0])\n            x = torch.concat((x, X_extra), axis=2)\n\n        return x\n\n\n# %%\nclass SubCrab(nn.Module):\n    \"\"\"SubCrab model class which implements the transformer architecture.\"\"\"\n\n    def __init__(\n        self,\n        out_dims=3,\n        d_model=512,\n        extend_features=None,\n        d_extend=0,\n        N=3,\n        heads=4,\n        fractional=False,\n        attention=True,\n        compute_device=None,\n        out_hidden=[1024, 512, 256, 128],\n        pe_resolution=5000,\n        ple_resolution=5000,\n        elem_prop=\"mat2vec\",\n        bias=False,\n        emb_scaler=1.0,\n        pos_scaler=1.0,\n        pos_scaler_log=1.0,\n        dim_feedforward=2048,\n        dropout=0.1,\n    ):\n        \"\"\"Instantiate a SubCrab class to be used within CrabNet.\n\n        Parameters\n        ----------\n        out_dims : int, optional\n            Output dimensions for Residual Network, by default 3\n        d_model : int, optional\n            Model size. See paper, by default 512\n        extend_features : _type_, optional\n            Additional features to grab from columns of the other DataFrames (e.g. state\n            variables such as temperature or applied load), by default None\n        d_extend : int, optional\n            Number of extended features, by default 0\n        N : int, optional\n            Number of attention layers, by default 3\n        heads : int, optional\n            Number of attention heads, by default 4\n        frac : bool, optional\n            Whether to multiply `x` by the fractional amounts for each element, by default False\n        attn : bool, optional\n            Whether to perform self attention, by default True\n        compute_device : _type_, optional\n            Computing device to run model on, by default None\n        out_hidden : list(int), optional\n            Architecture of hidden layers in the Residual Network, by default [1024, 512, 256, 128]\n        pe_resolution : int, optional\n            Number of discretizations for the prevalence encoding, by default 5000\n        ple_resolution : int, optional\n            Number of discretizations for the prevalence log encoding, by default 5000\n        elem_prop : str, optional\n            Which elemental feature vector to use. Possible values are \"jarvis\", \"magpie\",\n            \"mat2vec\", \"oliynyk\", \"onehot\", \"ptable\", and \"random_200\", by default \"mat2vec\"\n        bias : bool, optional\n            Whether to bias the Residual Network, by default False\n        emb_scaler : float, optional\n            Float value by which to scale the elemental embeddings, by default 1.0\n        pos_scaler : float, optional\n            Float value by which to scale the fractional encodings, by default 1.0\n        pos_scaler_log : float, optional\n            Float value by which to scale the log fractional encodings, by default 1.0\n        dim_feedforward : int, optional\n            Dimenions of the feed forward network following transformer, by default 2048\n        dropout : float, optional\n            Percent dropout in the feed forward network following the transformer, by default 0.1\n        \"\"\"\n        super().__init__()\n        self.avg = True\n        self.out_dims = out_dims\n        self.d_model = d_model\n        self.extend_features = extend_features\n        self.d_extend = d_extend\n        self.N = N\n        self.heads = heads\n        self.fractional = fractional\n        self.attention = attention\n        self.compute_device = compute_device\n        self.bias = bias\n        self.encoder = Encoder(\n            d_model=self.d_model,\n            N=self.N,\n            heads=self.heads,\n            attention=self.attention,\n            compute_device=self.compute_device,\n            pe_resolution=pe_resolution,\n            ple_resolution=ple_resolution,\n            elem_prop=elem_prop,\n            emb_scaler=emb_scaler,\n            pos_scaler=pos_scaler,\n            pos_scaler_log=pos_scaler_log,\n            dim_feedforward=dim_feedforward,\n            dropout=dropout,\n        )\n\n        self.out_hidden = out_hidden\n        self.output_nn = ResidualNetwork(\n            self.d_model + self.d_extend,\n            self.out_dims,\n            self.out_hidden,\n            self.bias,\n        )\n\n    def forward(self, src, frac, extra_features=None):\n        \"\"\"Compute forward pass of the SubCrab model class (i.e. transformer).\n\n        Parameters\n        ----------\n        src : torch.tensor\n            Tensor containing element numbers corresponding to elements in compound\n        frac : torch.tensor\n            Tensor containing fractional amounts of each element in compound\n        extra_features : bool, optional\n            Whether to append extra features after encoding, by default None\n\n        Returns\n        -------\n        torch.tensor\n            Model output containing predicted value and uncertainty for that value\n        \"\"\"\n        output = self.encoder(src, frac, extra_features)\n        # output = self.transfer_nn(output)\n\n        # average the \"element contribution\", mask so you only average \"elements\" (i.e.\n        # not padded zero values)\n        elem_pad_mask = (src == 0).unsqueeze(-1).repeat(1, 1, self.out_dims)\n        output = self.output_nn(output)  # simple linear\n        if self.avg:\n            output = output.masked_fill(elem_pad_mask, 0)\n            output = output.sum(dim=1) / (~elem_pad_mask).sum(dim=1)\n            output, logits = output.chunk(2, dim=-1)\n            probability = torch.ones_like(output)\n            probability[:, : logits.shape[-1]] = torch.sigmoid(logits)\n            output = output * probability\n\n        return output\n\n\n# %%\nif __name__ == \"__main__\":\n    model = SubCrab()\n", "meta": {"hexsha": "5a6b1dfdd2b875de3ec445e229aa66abdf26a9f0", "size": 19393, "ext": "py", "lang": "Python", "max_stars_repo_path": "crabnet/kingcrab.py", "max_stars_repo_name": "sgbaird/CrabNet", "max_stars_repo_head_hexsha": "9b3966cb7238dd688b84eb3fae9f2c6ae3a4ae47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-10-30T09:29:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T12:11:13.000Z", "max_issues_repo_path": "crabnet/kingcrab.py", "max_issues_repo_name": "sparks-baird/CrabNet", "max_issues_repo_head_hexsha": "9b3966cb7238dd688b84eb3fae9f2c6ae3a4ae47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2022-03-09T07:51:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T18:52:04.000Z", "max_forks_repo_path": "crabnet/kingcrab.py", "max_forks_repo_name": "sparks-baird/CrabNet", "max_forks_repo_head_hexsha": "9b3966cb7238dd688b84eb3fae9f2c6ae3a4ae47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-21T04:47:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-21T04:47:24.000Z", "avg_line_length": 35.5834862385, "max_line_length": 105, "alphanum_fraction": 0.599494663, "include": true, "reason": "import numpy", "num_tokens": 4341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.19799955262525035}}
{"text": "\"\"\"\nTrade exit triggers\n\n\"\"\"\n\nimport numpy as np\n\nclass TradeTargets():\n    \"\"\"\n    Calculate profit targets, stop loss levels etc.\n\n    \"\"\"\n    @classmethod\n    def exit_and_stop_targets(\n            cls, prices, params, trade_price_dict):\n        \"\"\"\n        Calculate exit and stop targets.\n\n        Parameters\n        ----------\n        prices : DataFrame\n            The OHLC data.\n        exit_amount : Float\n            The dollar exit amount. The default is $1000.00.\n        stop_amount : Float\n            The dollar stop amount. The default is $500.00.\n        position_size : Int, optional\n            The number of units to trade. The default is based on equity.\n        trade_price_dict : Dict\n            Dictionary of trade entry/high/low/close series.\n\n        Returns\n        -------\n        prices : DataFrame\n            The OHLC data.\n\n        \"\"\"\n\n        if params['exit_type'] is not None:\n            prices = cls._exit_targets(\n                prices=prices,\n                exit_amount=params['exit_amount'],\n                trade_price_dict=trade_price_dict,\n                params=params)\n\n        if params['stop_type'] is not None:\n            prices = cls._stop_targets(\n                prices=prices,\n                stop_amount=params['stop_amount'],\n                trade_price_dict=trade_price_dict,\n                params=params)\n\n        return prices\n\n\n    @classmethod\n    def _exit_targets(\n            cls, prices, exit_amount, trade_price_dict, params):\n        \"\"\"\n        Create 4 series of exit targets\n\n        Parameters\n        ----------\n        prices : DataFrame\n            The OHLC data.\n        exit_amount : Float\n            The dollar exit amount. The default is $1000.00.\n        position_size : Int, optional\n            The number of units to trade. The default is based on equity.\n        trade_price_dict : Dict\n            Dictionary of trade entry/high/low/close series.\n\n        Returns\n        -------\n        prices : DataFrame\n            The OHLC data..\n\n        \"\"\"\n        # Generate profit targets / trailing stops\n        prices['exit_profit_target'], prices['exit_initial_dollar_loss'], \\\n            prices['exit_trailing_close'], \\\n                prices['exit_trailing_high_low'] = cls._pnl_targets(\n                    prices=prices, dollar_amount=exit_amount,\n                    trade_price_dict=trade_price_dict,\n                    params=params)\n\n        return prices\n\n\n    @classmethod\n    def _stop_targets(\n            cls, prices, stop_amount, trade_price_dict, params):\n        \"\"\"\n        Create 4 series of stop targets\n\n        Parameters\n        ----------\n        prices : DataFrame\n            The OHLC data.\n        stop_amount : Float\n            The dollar stop amount. The default is $500.00.\n        position_size : Int, optional\n            The number of units to trade. The default is based on equity.\n        trade_price_dict : Dict\n            Dictionary of trade entry/high/low/close series.\n\n        Returns\n        -------\n        prices : DataFrame\n            The OHLC data.\n\n        \"\"\"\n        # Generate profit targets / trailing stops\n        prices['stop_profit_target'], prices['stop_initial_dollar_loss'], \\\n            prices['stop_trailing_close'], \\\n                prices['stop_trailing_high_low'] = cls._pnl_targets(\n                    prices=prices, dollar_amount=stop_amount,\n                    trade_price_dict=trade_price_dict,\n                    params=params)\n\n        return prices\n\n\n    @staticmethod\n    def _pnl_targets(\n            prices, dollar_amount, trade_price_dict, params):\n        \"\"\"\n        Create profit and loss stop and exit points\n\n        Parameters\n        ----------\n        prices : DataFrame\n            The OHLC data.\n        exit_amount : Float\n            The dollar exit amount. The default is $1000.00.\n        position_size : Int\n            The number of units of the chosen ticker to trade.\n        trade_number : Series\n            Array of trade numbers.\n        end_of_day_position : Series\n            The number of units of position held at the end of day.\n        trade_entry_price : Series\n            The entry price for each trade.\n        trade_high_price : Series\n            The high price for each trade.\n        trade_low_price : Series\n            The low price for each trade.\n        trade_close_high_price : Series\n            The highest closing price for each trade.\n        trade_close_low_price : Series\n            The lowest closing price for each trade.\n\n        Returns\n        -------\n        profit_target : Series\n            The exit levels for each trade based on a dollar loss from the\n            entry level.\n        initial_dollar_loss : Series\n            The exit levels for each trade based on a profit target\n        trailing_close : Series\n            The exit levels for each trade based on the trailing close.\n        trailing_high_low : Series\n            The exit levels for each trade based on the trailing high / low.\n\n        \"\"\"\n\n        # Create empty arrays to store the values\n        trade_target = np.array([0.0]*len(prices))\n        profit_target = np.array([0.0]*len(prices))\n        initial_dollar_loss = np.array([0.0]*len(prices))\n        trailing_close = np.array([0.0]*len(prices))\n        trailing_high_low = np.array([0.0]*len(prices))\n\n        end_of_day_position = prices['raw_end_of_day_position']\n        position_size = prices['position_size']\n\n        # For each row in the data\n        for row in range(1, len(prices)):\n\n            # Calculate the trade target (distance that price has to change) by\n            # dividing the dollar amount by the number of units making up the\n            # position size\n            if position_size[row] == 0:\n                trade_target[row] = 0\n            else:\n                trade_target[row] = np.round(\n                    (dollar_amount / params['contract_point_value'])\n                    / position_size[row], 2)\n\n            # If there is a trade on\n            if prices['raw_trade_number'][row] != 0:\n\n                # If there is a long position\n                if end_of_day_position[row] > 0:\n\n                    # Set the profit target to the trade entry price plus the\n                    # trade target\n                    profit_target[row] = (\n                        trade_price_dict['trade_entry_price'][row]\n                        + trade_target[row])\n\n                    # Set the initial dollar loss target to the trade entry\n                    # price minus the trade target\n                    initial_dollar_loss[row] = (\n                        trade_price_dict['trade_entry_price'][row]\n                        - trade_target[row])\n\n                    # Set the trailing close target to the closing high price\n                    # of the trade minus the trade target\n                    trailing_close[row] = (\n                        trade_price_dict['trade_close_high_price'][row]\n                        - trade_target[row])\n\n                    # Set the trailing high/low target to the high price\n                    # of the trade minus the trade target\n                    trailing_high_low[row] = (\n                        trade_price_dict['trade_high_price'][row]\n                        - trade_target[row])\n\n                # If there is a short position\n                else:\n                    # Set the profit target to the trade entry price minus the\n                    # trade target\n                    profit_target[row] = (\n                        trade_price_dict['trade_entry_price'][row]\n                        - trade_target[row])\n\n                    # Set the initial dollar loss target to the trade entry\n                    # price plus the trade target\n                    initial_dollar_loss[row] = (\n                        trade_price_dict['trade_entry_price'][row]\n                        + trade_target[row])\n\n                    # Set the trailing close target to the closing low price\n                    # of the trade plus the trade target\n                    trailing_close[row] = (\n                        trade_price_dict['trade_close_low_price'][row]\n                        + trade_target[row])\n\n                    # Set the trailing high/low target to the low price\n                    # of the trade minus the trade target\n                    trailing_high_low[row] = (\n                        trade_price_dict['trade_low_price'][row]\n                        + trade_target[row])\n\n        return profit_target, initial_dollar_loss, trailing_close, \\\n            trailing_high_low\n", "meta": {"hexsha": "2e90949acd1822b21e3c6bab5d7f5ddb71aef9a4", "size": 8639, "ext": "py", "lang": "Python", "max_stars_repo_path": "tradingsystems/targets.py", "max_stars_repo_name": "GBERESEARCH/tradingsystems", "max_stars_repo_head_hexsha": "5158d41d32b48d35db34a6e132c7fa2f259987c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-10T04:28:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T04:28:37.000Z", "max_issues_repo_path": "tradingsystems/targets.py", "max_issues_repo_name": "GBERESEARCH/tradingsystems", "max_issues_repo_head_hexsha": "5158d41d32b48d35db34a6e132c7fa2f259987c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tradingsystems/targets.py", "max_forks_repo_name": "GBERESEARCH/tradingsystems", "max_forks_repo_head_hexsha": "5158d41d32b48d35db34a6e132c7fa2f259987c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-10T04:28:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T04:28:38.000Z", "avg_line_length": 34.8346774194, "max_line_length": 79, "alphanum_fraction": 0.5449704827, "include": true, "reason": "import numpy", "num_tokens": 1654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301064, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.19797945500546638}}
{"text": "import numpy as np\n\nfrom .libfft import FFT\nfrom .pencil import Pencil\nfrom .pencil import Subcomm\n\n\nclass Transform(object):\n    \"\"\"Class for performing any parallel transform, forward or backward\n\n    Parameters\n    ----------\n    xfftn : list of serial transform objects\n    transfer : list of global redistribution objects\n    pencil : list of two pencil objects\n        The two pencils represent the input and final output configuration of\n        the distributed global arrays\n\n    \"\"\"\n    def __init__(self, xfftn, transfer, pencil):\n        assert len(xfftn) == len(transfer) + 1 and len(pencil) == 2\n        self._xfftn = tuple(xfftn)\n        self._transfer = tuple(transfer)\n        self._pencil = tuple(pencil)\n\n    @property\n    def input_array(self):\n        \"\"\"Return input array of Transform\"\"\"\n        return self._xfftn[0].input_array\n\n    @property\n    def output_array(self):\n        \"\"\"Return output array of Transform\"\"\"\n        return self._xfftn[-1].output_array\n\n    @property\n    def input_pencil(self):\n        \"\"\"Return input pencil of Transform\"\"\"\n        return self._pencil[0]\n\n    @property\n    def output_pencil(self):\n        \"\"\"Return output pencil of Transform\"\"\"\n        return self._pencil[1]\n\n    def __call__(self, input_array=None, output_array=None, **kw):\n        \"\"\"Compute transform\n\n        Parameters\n        ----------\n        input_array : array, optional\n        output_array : array, optional\n        kw : dict\n            parameters to serial transforms\n            Note in particular that the keyword 'normalize'=True/False can be\n            used to turn normalization on or off. Default is to enable\n            normalization for forward transforms and disable it for backward.\n\n        Note\n        ----\n        If input_array/output_array are not given, then use predefined arrays\n        as planned with serial transform object _xfftn.\n\n        \"\"\"\n        if input_array is not None:\n            self.input_array[...] = input_array\n\n        for i in range(len(self._transfer)):\n            self._xfftn[i](**kw)\n            arrayA = self._xfftn[i].output_array\n            arrayB = self._xfftn[i+1].input_array\n            self._transfer[i](arrayA, arrayB)\n        self._xfftn[-1](**kw)\n\n        if output_array is not None:\n            output_array[...] = self.output_array\n            return output_array\n        else:\n            return self.output_array\n\n\nclass PFFT(object):\n    \"\"\"Base class for parallel FFT transforms\n\n    Parameters\n    ----------\n    comm : MPI communicator\n    shape : sequence of ints, optional\n        shape of input array planned for\n    axes : None, int, sequence of ints or sequence of sequence of ints, optional\n        axes to transform over.\n\n        - None -> All axes are transformed\n        - int -> Just one axis to transform over\n        - sequence of ints -> e.g., (0, 1, 2) or (0, 2, 1)\n        - sequence of sequence of ints -> e.g., ((0,), (1,)) or ((0,), (1, 2))\n          For seq. of seq. of ints all but the last transformed sequence\n          may be longer than 1. This corresponds to collapsing axes, where\n          serial FFTs are performed for all collapsed axes in one single call\n    dtype : np.dtype, optional\n        Type of input array\n    grid : sequence of ints, optional\n        Define processor grid sizes. Non positive values act as wildcards to\n        allow MPI compute optimal decompositions. The sequence is padded with\n        ones to match the global transform dimension.\n        Use ``(-1,)`` to get a slab decomposition on the first axis.\n        Use ``(1, -1)`` to get a slab decomposition  on the second axis.\n        Use ``(P, Q)`` or ``(P, Q, 1)`` to get a 3D transform with 2D-pencil\n        decomposition on a PxQ processor grid with the last axis non distributed.\n        Use ``(P, 1, Q)`` to get a 3D transform with 2D-pencil decomposition on\n        a PxQ processor grid with the second to last axis non distributed.\n    padding : bool, number or sequence of numbers, optional\n        If False, then no padding. If number, then apply this number as padding\n        factor for all axes. If sequence of numbers, then each number gives the\n        padding for each axis. Must be same length as axes.\n    collapse : bool, optional\n        If True try to collapse several serial transforms into one\n    backend : str, optional\n        Choose backend for serial transforms (``fftw``, ``pyfftw``, ``numpy``,\n        ``scipy``, ``mkl_fft``). Default is ``fftw``\n    transforms : None or dict, optional\n        Dictionary of axes to serial transforms (forward and backward) along\n        those axes. For example::\n\n            {(0, 1): (dctn, idctn), (2, 3): (dstn, idstn)}\n\n        If missing the default is to use rfftn/irfftn for real input arrays and\n        fftn/ifftn for complex input arrays. Real-to-real transforms can be\n        configured using this dictionary and real-to-real transforms from the\n        :mod:`.fftw.xfftn` module. See Examples.\n\n    Other Parameters\n    ----------------\n    darray : DistArray object, optional\n        Create PFFT using information contained in ``darray``, neglecting most\n        optional Parameters above\n    slab : bool or int, optional\n        DEPRECATED. If True then distribute only one axis of the global array.\n\n    Methods\n    -------\n    forward(input_array=None, output_array=None, **kw)\n        Parallel forward transform. The method is an instance of the\n        :class:`.Transform` class. See :meth:`.Transform.__call__`\n\n        Parameters\n        ----------\n        input_array : array, optional\n        output_array : array, optional\n        kw : dict\n            parameters to serial transforms\n\n        Returns\n        -------\n        output_array : array\n\n    backward(input_array=None, output_array=None, **kw)\n        Parallel backward transform. The method is an instance of the\n        :class:`.Transform` class. See :meth:`.Transform.__call__`\n\n        Parameters\n        ----------\n        input_array : array, optional\n        output_array : array, optional\n        kw : dict\n            parameters to serial transforms\n\n        Returns\n        -------\n        output_array : array\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> from mpi4py import MPI\n    >>> from mpi4py_fft import PFFT, newDistArray\n    >>> N = np.array([12, 14, 15], dtype=int)\n    >>> fft = PFFT(MPI.COMM_WORLD, N, axes=(0, 1, 2))\n    >>> u = newDistArray(fft, False)\n    >>> u[:] = np.random.random(u.shape).astype(u.dtype)\n    >>> u_hat = fft.forward(u)\n    >>> uj = np.zeros_like(u)\n    >>> uj = fft.backward(u_hat, uj)\n    >>> assert np.allclose(uj, u)\n\n    Now configure with real-to-real discrete cosine transform type 3\n\n    >>> from mpi4py_fft.fftw import rfftn, irfftn, dctn, idctn\n    >>> import functools\n    >>> dct = functools.partial(dctn, type=3)\n    >>> idct = functools.partial(idctn, type=3)\n    >>> transforms = {(1, 2): (dct, idct)}\n    >>> r2c = PFFT(MPI.COMM_WORLD, N, axes=((0,), (1, 2)), transforms=transforms)\n    >>> u = newDistArray(r2c, False)\n    >>> u[:] = np.random.random(u.shape).astype(u.dtype)\n    >>> u_hat = r2c.forward(u)\n    >>> uj = np.zeros_like(u)\n    >>> uj = r2c.backward(u_hat, uj)\n    >>> assert np.allclose(uj, u)\n\n    \"\"\"\n    def __init__(self, comm, shape=None, axes=None, dtype=float, grid=None,\n                 padding=False, collapse=False, backend='fftw',\n                 transforms=None, darray=None, **kw):\n        # pylint: disable=too-many-locals\n        # pylint: disable=too-many-branches\n        # pylint: disable=too-many-statements\n\n        if shape is None:\n            assert darray is not None\n            shape = darray.pencil.shape\n\n        if axes is not None:\n            axes = list(axes) if np.ndim(axes) else [axes]\n        else:\n            axes = list(range(len(shape)))\n            if darray is not None:\n                # Make sure aligned axis of darray is transformed first\n                axes = list(np.roll(axes, len(shape)-1-darray.alignment))\n\n        for i, ax in enumerate(axes):\n            if isinstance(ax, (int, np.integer)):\n                if ax < 0:\n                    ax += len(shape)\n                axes[i] = (ax,)\n            else:\n                assert isinstance(ax, (tuple, list))\n                ax = list(ax)\n                for j, a in enumerate(ax):\n                    assert isinstance(a, int)\n                    if a < 0:\n                        a += len(shape)\n                        ax[j] = a\n                axes[i] = ax\n            assert min(axes[i]) >= 0\n            assert max(axes[i]) < len(shape)\n            assert 0 < len(axes[i]) <= len(shape)\n            assert sorted(axes[i]) == sorted(set(axes[i]))\n\n        self.axes = axes\n        shape = list(shape)\n\n        if darray is None:\n            dtype = np.dtype(dtype)\n            assert dtype.char in 'fdgFDG'\n\n            if padding is not False:\n                assert len(padding) == len(shape)\n                for ax in axes:\n                    if len(ax) == 1 and padding[ax[0]] > 1.0+1e-6:\n                        old = float(shape[ax[0]])\n                        shape[ax[0]] = int(np.floor(shape[ax[0]]*padding[ax[0]]))\n                        padding[ax[0]] = shape[ax[0]] / old\n\n            self._input_shape = tuple(shape)\n            assert len(shape) > 0\n            assert min(shape) > 0\n\n            slab = kw.pop('slab', False)\n\n            if grid is not None:\n                assert not isinstance(comm, Subcomm)\n                assert slab is False\n                grid = tuple(grid)\n                assert len(grid) <= len(shape)\n                dims = list(grid) + [1] * (len(shape) - len(grid))\n                comm = Subcomm(comm, dims)\n\n            if isinstance(comm, Subcomm):\n                assert slab is False\n                assert len(comm) == len(shape)\n                assert np.all([comm[ax].Get_size() == 1 for ax in axes[-1]])\n                self.subcomm = comm\n            else:\n                if slab is False or slab is None:\n                    dims = [0] * len(shape)\n                    for ax in axes[-1]:\n                        dims[ax] = 1\n                else: #pragma: no cover\n                    if slab is True:\n                        axis = (axes[-1][-1] + 1) % len(shape)\n                    else:\n                        axis = slab\n                        if axis < 0:\n                            axis = axis + len(shape)\n                        assert 0 <= axis < len(shape)\n                    dims = [1] * len(shape)\n                    dims[axis] = comm.Get_size()\n\n                self.subcomm = Subcomm(comm, dims)\n        else:\n            dtype = darray.dtype\n            self.subcomm = darray.subcomm\n            self._input_shape = tuple(shape)\n            commsizes = darray.commsizes\n            assert np.all([commsizes[ax] == 1 for ax in axes[-1]]), \"Set keyword axes such that axes to transform first are aligned\"\n\n        self.collapse = collapse\n        if collapse is True:\n            groups = [[]]\n            for ax in reversed(axes):\n                if np.all([self.subcomm[axis].Get_size() == 1 for axis in ax]):\n                    [groups[0].insert(0, axis) for axis in reversed(ax)]\n                else:\n                    groups.insert(0, ax)\n            axes = groups\n\n        self.axes = tuple(map(tuple, axes))\n        self.xfftn = []\n        self.transfer = []\n        self.pencil = [None, None]\n\n        axes = self.axes[-1]\n        pencil = Pencil(self.subcomm, shape, axes[-1])\n        xfftn = FFT(pencil.subshape, axes, dtype, padding, backend=backend,\n                    transforms=transforms, **kw)\n        self.xfftn.append(xfftn)\n        self.pencil[0] = pencilA = pencil\n        if not shape[axes[-1]] == xfftn.forward.output_array.shape[axes[-1]]:\n            dtype = xfftn.forward.output_array.dtype\n            shape[axes[-1]] = xfftn.forward.output_array.shape[axes[-1]]\n            pencilA = Pencil(self.subcomm, shape, axes[-1])\n\n        for axes in reversed(self.axes[:-1]):\n            pencilB = pencilA.pencil(axes[-1])\n            transAB = pencilA.transfer(pencilB, dtype)\n            xfftn = FFT(pencilB.subshape, axes, dtype, padding, backend=backend,\n                        transforms=transforms, **kw)\n            self.xfftn.append(xfftn)\n            self.transfer.append(transAB)\n            pencilA = pencilB\n            if not shape[axes[-1]] == xfftn.forward.output_array.shape[axes[-1]]:\n                dtype = xfftn.forward.output_array.dtype\n                shape[axes[-1]] = xfftn.forward.output_array.shape[axes[-1]]\n                pencilA = Pencil(pencilB.subcomm, shape, axes[-1])\n\n        self.pencil[1] = pencilA\n        self._output_shape = tuple(shape)\n\n        self.forward = Transform(\n            [o.forward for o in self.xfftn],\n            [o.forward for o in self.transfer],\n            self.pencil)\n        self.backward = Transform(\n            [o.backward for o in self.xfftn[::-1]],\n            [o.backward for o in self.transfer[::-1]],\n            self.pencil[::-1])\n\n    def destroy(self):\n        if isinstance(self.subcomm, Subcomm):\n            self.subcomm.destroy()\n        for trans in self.transfer:\n            trans.destroy()\n\n    def shape(self, forward_output=True):\n        \"\"\"The local (to each processor) shape of data\n\n        Parameters\n        ----------\n        forward_output : bool, optional\n            Return shape of output array (spectral space) if True, else return\n            shape of input array (physical space)\n        \"\"\"\n        if forward_output is not True:\n            return self.forward.input_pencil.subshape\n        return self.backward.input_pencil.subshape\n\n    def local_slice(self, forward_output=True):\n        \"\"\"The local view into the global data\n\n        Parameters\n        ----------\n        forward_output : bool, optional\n            Return local slices of output array (spectral space) if True, else\n            return local slices of input array (physical space)\n\n        \"\"\"\n        if forward_output is not True:\n            ip = self.forward.input_pencil\n            s = [slice(start, start+shape) for start, shape in zip(ip.substart,\n                                                                   ip.subshape)]\n        else:\n            ip = self.backward.input_pencil\n            s = [slice(start, start+shape) for start, shape in zip(ip.substart,\n                                                                   ip.subshape)]\n        return tuple(s)\n\n    def global_shape(self, forward_output=False):\n        \"\"\"Return global shape of associated tensors\n\n        Parameters\n        ----------\n        forward_output : bool, optional\n            If True then return global shape of spectral space, i.e., the input\n            to a backward transfer. If False then return shape of physical\n            space, i.e., the input to a forward transfer.\n        \"\"\"\n        if forward_output:\n            return self._output_shape\n        return self._input_shape\n\n    @property\n    def dimensions(self):\n        \"\"\"The number of dimensions for transformed arrays\"\"\"\n        return len(self.forward.input_array.shape)\n\n    def dtype(self, forward_output=False):\n        \"\"\"The type of transformed arrays\n\n        Parameters\n        ----------\n        forward_output : bool, optional\n            If True then return dtype of an array that is the result of a\n            forward transform. Otherwise, return the dtype of an array that\n            is input to a forward transform.\n        \"\"\"\n        if forward_output:\n            return self.forward.output_array.dtype\n        return self.forward.input_array.dtype\n", "meta": {"hexsha": "b379102d6380ce96d4e6e85184f5ed5253c542a5", "size": 15684, "ext": "py", "lang": "Python", "max_stars_repo_path": "mpi4py_fft/mpifft.py", "max_stars_repo_name": "spectralDNS/mpi4pt-fft", "max_stars_repo_head_hexsha": "ac510f8398f138bb860ed9f2580343e8b98cf799", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2019-03-29T20:20:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T10:54:54.000Z", "max_issues_repo_path": "mpi4py_fft/mpifft.py", "max_issues_repo_name": "spectralDNS/mpi4pt-fft", "max_issues_repo_head_hexsha": "ac510f8398f138bb860ed9f2580343e8b98cf799", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2019-05-02T07:53:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T03:10:00.000Z", "max_forks_repo_path": "mpi4py_fft/mpifft.py", "max_forks_repo_name": "spectralDNS/mpi4py-fft", "max_forks_repo_head_hexsha": "ac510f8398f138bb860ed9f2580343e8b98cf799", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-26T21:22:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T21:22:10.000Z", "avg_line_length": 37.3428571429, "max_line_length": 132, "alphanum_fraction": 0.5608263198, "include": true, "reason": "import numpy", "num_tokens": 3578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.19797944341334375}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2019 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#         James D. McClain\n#         Timothy Berkelbach <tim.berkelbach@gmail.com>\n#\n\n\nimport numpy as np\n\nfrom pyscf import lib\nfrom pyscf import ao2mo\nfrom pyscf.lib import logger\nfrom pyscf.cc import ccsd\nfrom pyscf.cc import rintermediates as imd\nfrom pyscf import __config__\n\n\ndef kernel(eom, nroots=1, koopmans=False, guess=None, left=False,\n           eris=None, imds=None, **kwargs):\n    cput0 = (logger.process_clock(), logger.perf_counter())\n    log = logger.Logger(eom.stdout, eom.verbose)\n    if eom.verbose >= logger.WARN:\n        eom.check_sanity()\n    eom.dump_flags()\n\n    if imds is None:\n        imds = eom.make_imds(eris)\n\n    matvec, diag = eom.gen_matvec(imds, left=left, **kwargs)\n\n    size = eom.vector_size()\n    nroots = min(nroots, size)\n    if guess is not None:\n        user_guess = True\n        for g in guess:\n            assert g.size == size\n    else:\n        user_guess = False\n        guess = eom.get_init_guess(nroots, koopmans, diag)\n\n    def precond(r, e0, x0):\n        return r/(e0-diag+1e-12)\n\n    # GHF or customized RHF/UHF may be of complex type\n    real_system = (eom._cc._scf.mo_coeff[0].dtype == np.double)\n\n    eig = lib.davidson_nosym1\n    if user_guess or koopmans:\n        assert len(guess) == nroots\n        def eig_close_to_init_guess(w, v, nroots, envs):\n            x0 = lib.linalg_helper._gen_x0(envs['v'], envs['xs'])\n            s = np.dot(np.asarray(guess).conj(), np.asarray(x0).T)\n            snorm = np.einsum('pi,pi->i', s.conj(), s)\n            idx = np.argsort(-snorm)[:nroots]\n            return lib.linalg_helper._eigs_cmplx2real(w, v, idx, real_system)\n        conv, es, vs = eig(matvec, guess, precond, pick=eig_close_to_init_guess,\n                           tol=eom.conv_tol, max_cycle=eom.max_cycle,\n                           max_space=eom.max_space, nroots=nroots, verbose=log)\n    else:\n        def pickeig(w, v, nroots, envs):\n            real_idx = np.where(abs(w.imag) < 1e-3)[0]\n            return lib.linalg_helper._eigs_cmplx2real(w, v, real_idx, real_system)\n        conv, es, vs = eig(matvec, guess, precond, pick=pickeig,\n                           tol=eom.conv_tol, max_cycle=eom.max_cycle,\n                           max_space=eom.max_space, nroots=nroots, verbose=log)\n\n    if eom.verbose >= logger.INFO:\n        for n, en, vn, convn in zip(range(nroots), es, vs, conv):\n            r1, r2 = eom.vector_to_amplitudes(vn)\n            if isinstance(r1, np.ndarray):\n                qp_weight = np.linalg.norm(r1)**2\n            else: # for EOM-UCCSD\n                r1 = np.hstack([x.ravel() for x in r1])\n                qp_weight = np.linalg.norm(r1)**2\n            logger.info(eom, 'EOM-CCSD root %d E = %.16g  qpwt = %.6g  conv = %s',\n                        n, en, qp_weight, convn)\n        log.timer('EOM-CCSD', *cput0)\n    if nroots == 1:\n        return conv[0], es[0].real, vs[0]\n    else:\n        return conv, es.real, vs\n\n\nclass EOM(lib.StreamObject):\n    def __init__(self, cc):\n        self.mol = cc.mol\n        self._cc = cc\n        self.verbose = cc.verbose\n        self.stdout = cc.stdout\n        self.max_memory = cc.max_memory\n\n        self.max_space = getattr(__config__, 'eom_rccsd_EOM_max_space', 20)\n        self.max_cycle = getattr(__config__, 'eom_rccsd_EOM_max_cycle', cc.max_cycle)\n        self.conv_tol = getattr(__config__, 'eom_rccsd_EOM_conv_tol', cc.conv_tol)\n        self.partition = getattr(__config__, 'eom_rccsd_EOM_partition', None)\n\n##################################################\n# don't modify the following attributes, they are not input options\n        self.e = None\n        self.v = None\n        self.nocc = cc.nocc\n        self.nmo = cc.nmo\n        self._keys = set(self.__dict__.keys())\n\n    def dump_flags(self, verbose=None):\n        logger.info(self, '')\n        logger.info(self, '******** %s ********', self.__class__)\n        logger.info(self, 'max_space = %d', self.max_space)\n        logger.info(self, 'max_cycle = %d', self.max_cycle)\n        logger.info(self, 'conv_tol = %s', self.conv_tol)\n        logger.info(self, 'partition = %s', self.partition)\n        #logger.info(self, 'nocc = %d', self.nocc)\n        #logger.info(self, 'nmo = %d', self.nmo)\n        logger.info(self, 'max_memory %d MB (current use %d MB)',\n                    self.max_memory, lib.current_memory()[0])\n        return self\n\n    def reset(self, mol=None):\n        self._cc.reset(mol)\n        return self\n\n\ndef _sort_left_right_eigensystem(eom, right_converged, right_evals, right_evecs,\n                                 left_converged, left_evals, left_evecs, tol=1e-6):\n    '''Ensures the left and right eigenvectors correspond to the same eigenvalue.\n\n    Note:\n        Useful for perturbative methods that need both eigenstates.  Right now, just\n        simply checks for equality between left and right eigenvalues, but can be\n        extended to make sure the overlap between states is sufficiently large.\n\n    Kwargs:\n        eom : :class:`EOM`\n            Class holding EOM results.\n        right_converged : array-like of bool\n            Whether the right eigenstates converged.\n        right_evals : array-like\n            Eigenvalues of right eigenstates.\n        right_evecs : array-like of ndarray\n            Eigenvectors of right eigenstates.\n        left_converged : array-like of bool\n            Whether the left eigenstates converged.\n        left_evals : array-like\n            Eigenvalues of left eigenstates.\n        left_evecs : array-like of ndarray\n            Eigenvectors of left eigenstates.\n        tol : float\n            Tolerance for determining whether a left and right eigenvalue\n            should be considered equal.\n    '''\n    log = logger.Logger(eom.stdout, eom.verbose)\n\n    right_evecs, left_evecs = [np.atleast_2d(x) for x in [right_evecs, left_evecs]]\n    right_evals, left_evals = [np.atleast_1d(x) for x in [right_evals, left_evals]]\n    right_converged, left_converged = [np.atleast_1d(x) for x in [right_converged, left_converged]]\n\n    srt_right_idx = []\n    srt_left_idx = []\n    left_idx = [idx for idx in range(len(left_evals)) if left_converged[idx]]\n    right_idx = [idx for idx in range(len(right_evals)) if right_converged[idx]]\n    if len(right_idx) != len(left_idx):\n        log.warn('Number of converged left and right eigenvalues are not equal.\\n'\n                 '    No. Left = %3d, No. Right = %3d.' %\n                 (len(left_idx), len(right_idx)))\n\n    for ir_idx, ir in enumerate(right_idx):\n        found = False\n        for il_idx, il in enumerate(left_idx):\n            if abs(right_evals[ir] - left_evals[il]) < tol:\n                found = True\n                srt_right_idx.append(ir)\n                srt_left_idx.append(il)\n                break\n        if found:\n            left_idx.pop(il_idx)\n        else:\n            log.warn('No converged left eigenvalue corresponding to right eigenvalue '\n                     '%.6g (right idx=%3d).\\nWill not perform perturbation on this state.'\n                     % (right_evals[ir], ir))\n\n    log.info('Resulting left/right eigenstates:')\n    log.info('Left Eigen (idx) <-> Right Eigen (idx)')\n    for il, ir in zip(srt_left_idx, srt_right_idx):\n        log.info('%10.6g (%3d)      %10.6g (%3d)',\n                 left_evals[il], il, right_evals[ir], ir)\n    return (right_evals[srt_right_idx], right_evecs[srt_right_idx], left_evecs[srt_left_idx])\n\n\ndef perturbed_ccsd_kernel(eom, nroots=1, koopmans=False, right_guess=None,\n                          left_guess=None, eris=None, imds=None):\n    '''Wrapper for running perturbative excited-states that require both left\n    and right amplitudes.'''\n    if imds is None:\n        imds = eom.make_imds(eris=eris)\n\n    # Right eigenvectors\n    r_converged, r_e, r_v = \\\n               kernel(eom, nroots, koopmans=koopmans, guess=right_guess, left=False,\n                      eris=eris, imds=imds)\n    # Left eigenvectors\n    l_converged, l_e, l_v = \\\n               kernel(eom, nroots, koopmans=koopmans, guess=right_guess, left=True,\n                      eris=eris, imds=imds)\n\n    e, r_v, l_v = _sort_left_right_eigensystem(eom, r_converged, r_e, r_v, l_converged, l_e, l_v)\n    e_star = eom.ccsd_star_contract(e, r_v, l_v, imds=imds)\n    return e_star\n\n\n########################################\n# EOM-IP-CCSD\n########################################\n\ndef ipccsd(eom, nroots=1, left=False, koopmans=False, guess=None,\n           partition=None, eris=None, imds=None):\n    '''Calculate (N-1)-electron charged excitations via IP-EOM-CCSD.\n\n    Kwargs:\n        nroots : int\n            Number of roots (eigenvalues) requested\n        partition : bool or str\n            Use a matrix-partitioning for the doubles-doubles block.\n            Can be None, 'mp' (Moller-Plesset, i.e. orbital energies on the diagonal),\n            or 'full' (full diagonal elements).\n        koopmans : bool\n            Calculate Koopmans'-like (quasiparticle) excitations only, targeting via\n            overlap.\n        guess : list of ndarray\n            List of guess vectors to use for targeting via overlap.\n    '''\n    if partition is not None:\n        eom.partition = partition.lower()\n        assert eom.partition in ['mp','full']\n    eom.converged, eom.e, eom.v \\\n            = kernel(eom, nroots, koopmans, guess, left, eris=eris, imds=imds)\n    return eom.e, eom.v\n\ndef ipccsd_star(eom, nroots=1, koopmans=False, right_guess=None,\n                left_guess=None, eris=None, imds=None):\n    \"\"\"Calculates CCSD* perturbative correction.\n\n    Simply calls the relevant `kernel()` function and `perturb_star` of the\n    `eom` class.\n\n    Returns:\n        e_t_a_star (list of float):\n            The IP-CCSD* energy.\n    \"\"\"\n    return perturbed_ccsd_kernel(eom, nroots=nroots, koopmans=koopmans,\n                                 right_guess=right_guess, left_guess=left_guess, eris=eris,\n                                 imds=imds)\n\ndef vector_to_amplitudes_ip(vector, nmo, nocc):\n    nvir = nmo - nocc\n    r1 = vector[:nocc].copy()\n    r2 = vector[nocc:].copy().reshape(nocc,nocc,nvir)\n    return r1, r2\n\ndef amplitudes_to_vector_ip(r1, r2):\n    vector = np.hstack((r1, r2.ravel()))\n    return vector\n\ndef ipccsd_matvec(eom, vector, imds=None, diag=None):\n    # Ref: Nooijen and Snijders, J. Chem. Phys. 102, 1681 (1995) Eqs.(8)-(9)\n    if imds is None: imds = eom.make_imds()\n    nocc = eom.nocc\n    nmo = eom.nmo\n    r1, r2 = vector_to_amplitudes_ip(vector, nmo, nocc)\n\n    # 1h-1h block\n    Hr1 = -np.einsum('ki,k->i', imds.Loo, r1)\n    #1h-2h1p block\n    Hr1 += 2*np.einsum('ld,ild->i', imds.Fov, r2)\n    Hr1 +=  -np.einsum('kd,kid->i', imds.Fov, r2)\n    Hr1 += -2*np.einsum('klid,kld->i', imds.Wooov, r2)\n    Hr1 +=    np.einsum('lkid,kld->i', imds.Wooov, r2)\n\n    # 2h1p-1h block\n    Hr2 = -np.einsum('kbij,k->ijb', imds.Wovoo, r1)\n    # 2h1p-2h1p block\n    if eom.partition == 'mp':\n        fock = imds.eris.fock\n        foo = fock[:nocc,:nocc]\n        fvv = fock[nocc:,nocc:]\n        Hr2 += lib.einsum('bd,ijd->ijb', fvv, r2)\n        Hr2 += -lib.einsum('ki,kjb->ijb', foo, r2)\n        Hr2 += -lib.einsum('lj,ilb->ijb', foo, r2)\n    elif eom.partition == 'full':\n        diag_matrix2 = vector_to_amplitudes_ip(diag, nmo, nocc)[1]\n        Hr2 += diag_matrix2 * r2\n    else:\n        Hr2 += lib.einsum('bd,ijd->ijb', imds.Lvv, r2)\n        Hr2 += -lib.einsum('ki,kjb->ijb', imds.Loo, r2)\n        Hr2 += -lib.einsum('lj,ilb->ijb', imds.Loo, r2)\n        Hr2 +=  lib.einsum('klij,klb->ijb', imds.Woooo, r2)\n        Hr2 += 2*lib.einsum('lbdj,ild->ijb', imds.Wovvo, r2)\n        Hr2 +=  -lib.einsum('kbdj,kid->ijb', imds.Wovvo, r2)\n        Hr2 +=  -lib.einsum('lbjd,ild->ijb', imds.Wovov, r2) #typo in Ref\n        Hr2 +=  -lib.einsum('kbid,kjd->ijb', imds.Wovov, r2)\n        tmp = 2*np.einsum('lkdc,kld->c', imds.Woovv, r2)\n        tmp += -np.einsum('kldc,kld->c', imds.Woovv, r2)\n        Hr2 += -np.einsum('c,ijcb->ijb', tmp, imds.t2)\n\n    vector = amplitudes_to_vector_ip(Hr1, Hr2)\n    return vector\n\ndef lipccsd_matvec(eom, vector, imds=None, diag=None):\n    '''For left eigenvector'''\n    # Note this is not the same left EA equations used by Nooijen and Bartlett.\n    # Small changes were made so that the same type L2 basis was used for both the\n    # left EA and left IP equations.  You will note more similarity for these\n    # equations to the left IP equations than for the left EA equations by Nooijen.\n    if imds is None: imds = eom.make_imds()\n    nocc = eom.nocc\n    nmo = eom.nmo\n    r1, r2 = vector_to_amplitudes_ip(vector, nmo, nocc)\n\n    # 1h-1h block\n    Hr1 = -np.einsum('ki,i->k', imds.Loo, r1)\n    #1h-2h1p block\n    Hr1 += -np.einsum('kbij,ijb->k', imds.Wovoo, r2)\n\n    # 2h1p-1h block\n    Hr2 = -np.einsum('kd,l->kld', imds.Fov, r1)\n    Hr2 += 2.*np.einsum('ld,k->kld', imds.Fov, r1)\n    Hr2 += -np.einsum('klid,i->kld', 2.*imds.Wooov-imds.Wooov.transpose(1,0,2,3), r1)\n    # 2h1p-2h1p block\n    if eom.partition == 'mp':\n        fock = imds.eris.fock\n        foo = fock[:nocc,:nocc]\n        fvv = fock[nocc:,nocc:]\n        Hr2 += lib.einsum('bd,klb->kld', fvv, r2)\n        Hr2 += -lib.einsum('ki,ild->kld', foo, r2)\n        Hr2 += -lib.einsum('lj,kjd->kld', foo, r2)\n    elif eom.partition == 'full':\n        diag_matrix2 = vector_to_amplitudes_ip(diag, nmo, nocc)[1]\n        Hr2 += diag_matrix2 * r2\n    else:\n        Hr2 += lib.einsum('bd,klb->kld', imds.Lvv, r2)\n        Hr2 += -lib.einsum('ki,ild->kld', imds.Loo, r2)\n        Hr2 += -lib.einsum('lj,kjd->kld', imds.Loo, r2)\n        Hr2 += lib.einsum('lbdj,kjb->kld', 2.*imds.Wovvo-imds.Wovov.transpose(0,1,3,2), r2)\n        Hr2 += -lib.einsum('kbdj,ljb->kld', imds.Wovvo, r2)\n        Hr2 += lib.einsum('klij,ijd->kld', imds.Woooo, r2)\n        Hr2 += -lib.einsum('kbid,ilb->kld', imds.Wovov, r2)\n        tmp = np.einsum('ijcb,ijb->c', imds.t2, r2)\n        Hr2 += -np.einsum('lkdc,c->kld', 2.*imds.Woovv-imds.Woovv.transpose(1,0,2,3), tmp)\n\n    vector = amplitudes_to_vector_ip(Hr1, Hr2)\n    return vector\n\ndef ipccsd_diag(eom, imds=None):\n    if imds is None: imds = eom.make_imds()\n    t1, t2 = imds.t1, imds.t2\n    dtype = np.result_type(t1, t2)\n    nocc, nvir = t1.shape\n    fock = imds.eris.fock\n    foo = fock[:nocc,:nocc]\n    fvv = fock[nocc:,nocc:]\n\n    Hr1 = -np.diag(imds.Loo)\n    Hr2 = np.zeros((nocc,nocc,nvir), dtype)\n    for i in range(nocc):\n        for j in range(nocc):\n            for b in range(nvir):\n                if eom.partition == 'mp':\n                    Hr2[i,j,b] += fvv[b,b]\n                    Hr2[i,j,b] += -foo[i,i]\n                    Hr2[i,j,b] += -foo[j,j]\n                else:\n                    Hr2[i,j,b] += imds.Lvv[b,b]\n                    Hr2[i,j,b] += -imds.Loo[i,i]\n                    Hr2[i,j,b] += -imds.Loo[j,j]\n                    Hr2[i,j,b] +=  imds.Woooo[i,j,i,j]\n                    Hr2[i,j,b] +=2*imds.Wovvo[j,b,b,j]\n                    Hr2[i,j,b] += -imds.Wovvo[i,b,b,i]*(i==j)\n                    Hr2[i,j,b] += -imds.Wovov[j,b,j,b]\n                    Hr2[i,j,b] += -imds.Wovov[i,b,i,b]\n                    Hr2[i,j,b] += -2*np.dot(imds.Woovv[j,i,b,:], t2[i,j,:,b])\n                    Hr2[i,j,b] += np.dot(imds.Woovv[i,j,b,:], t2[i,j,:,b])\n\n    vector = amplitudes_to_vector_ip(Hr1, Hr2)\n    return vector\n\ndef ipccsd_star_contract(eom, ipccsd_evals, ipccsd_evecs, lipccsd_evecs, imds=None):\n    from pyscf.cc.ccsd_t import _sort_eri, _sort_t2_vooo_\n    cpu1 = (logger.process_clock(), logger.perf_counter())\n    log = logger.Logger(eom.stdout, eom.verbose)\n    if imds is None:\n        imds = eom.make_imds()\n    t1, t2 = imds.t1, imds.t2\n    eris = imds.eris\n\n    nocc, nvir = t1.shape\n    nmo = nocc + nvir\n\n    dtype = np.result_type(t1, t2, eris.ovoo.dtype)\n    if eom._cc.incore_complete:\n        ftmp = None\n        eris_vvop = np.zeros((nvir,nvir,nocc,nmo), dtype)\n    else:\n        ftmp = lib.H5TmpFile()\n        eris_vvop = ftmp.create_dataset('vvop', (nvir,nvir,nocc,nmo), dtype)\n\n    orbsym = _sort_eri(eom._cc, eris, nocc, nvir, eris_vvop, log)\n    mo_energy, t1T, t2T, vooo, fvo, restore_t2_inplace = \\\n            _sort_t2_vooo_(eom._cc, orbsym, t1, t2, eris)\n\n    cpu1 = log.timer_debug1('CCSD(T) sort_eri', *cpu1)\n\n    mem_now = lib.current_memory()[0]\n    max_memory = max(0, eom.max_memory - mem_now)\n    blksize = min(nvir, max(ccsd.BLKMIN, int(max_memory*1e6/8/(nocc**3*6))))\n\n    mo_e_occ = np.asarray(mo_energy[:nocc])\n    mo_e_vir = np.asarray(mo_energy[nocc:])\n\n    def contract_l2p(l1, l2, a0, a1, b0, b1, cache_vvop, out=None):\n        '''Create perturbed l2.'''\n        if out is None:\n            out = np.zeros((nocc,)*3 + (a1-a0,b1-b0), dtype=dtype)\n        out += 0.5*np.einsum('abij,k->ijkab', cache_vvop[:,:,:,:nocc].conj(), l1)\n        out += lib.einsum('abie,jke->ijkab', cache_vvop[:,:,:,nocc:].conj(), l2)\n        out += -lib.einsum('bjkm,ima->ijkab', vooo[b0:b1], l2[:,:,a0:a1])\n        out += -lib.einsum('bjim,mka->ijkab', vooo[b0:b1], l2[:,:,a0:a1])\n        return out\n\n    def contract_pl2p(l1, l2, a0, a1, b0, b1, cache_vvop_a, cache_vvop_b):\n        '''Create P(ia|jb) of perturbed l2.'''\n        out = contract_l2p(l1, l2, a0, a1, b0, b1, cache_vvop_a)\n        out += contract_l2p(l1, l2, b0, b1, a0, a1, cache_vvop_b).transpose(1,0,2,4,3)  # P(ia|jb)\n        return out\n\n    def contract_r2p(r1, r2, a0, a1, b0, b1, cache_vvop, out=None):\n        '''Create perturbed r2.'''\n        if out is None:\n            out = np.zeros((nocc,)*3 + (a1-a0,b1-b0), dtype=dtype)\n        tmp = np.einsum('mkbe,m->bke', eris.oovv[:,:,b0:b1,:], r1)\n        out += -lib.einsum('bke,aeji->ijkab', tmp, t2T[a0:a1])\n        tmp = np.einsum('mebj,m->bej', eris.ovvo[:,:,b0:b1,:], r1)\n        out += -lib.einsum('bej,aeki->ijkab', tmp, t2T[a0:a1])\n        tmp = np.einsum('mjnk,n->mjk', eris.oooo, r1)\n        out += lib.einsum('mjk,abmi->ijkab', tmp, t2T[a0:a1,b0:b1])\n        out += lib.einsum('abie,kje->ijkab', cache_vvop[:,:,:,nocc:], r2)\n        out += -lib.einsum('bjkm,mia->ijkab', vooo[b0:b1].conj(), r2[:,:,a0:a1])\n        out += -lib.einsum('bjim,kma->ijkab', vooo[b0:b1].conj(), r2[:,:,a0:a1])\n        return out\n\n    def contract_pr2p(r1, r2, a0, a1, b0, b1, cache_vvop_a, cache_vvop_b):\n        '''Create P(ia|jb) of perturbed r2.'''\n        out = contract_r2p(r1, r2, a0, a1, b0, b1, cache_vvop_a)\n        out += contract_r2p(r1, r2, b0, b1, a0, a1, cache_vvop_b).transpose(1,0,2,4,3)  # P(ia|jb)\n        return out\n\n    ipccsd_evecs  = np.array(ipccsd_evecs)\n    lipccsd_evecs = np.array(lipccsd_evecs)\n    e = []\n    ipccsd_evecs, lipccsd_evecs = [np.atleast_2d(x) for x in [ipccsd_evecs, lipccsd_evecs]]\n    ipccsd_evals = np.atleast_1d(ipccsd_evals)\n    for eval_, evec_, levec_ in zip(ipccsd_evals, ipccsd_evecs, lipccsd_evecs):\n        l1, l2 = eom.vector_to_amplitudes(levec_)\n        r1, r2 = eom.vector_to_amplitudes(evec_)\n        ldotr = np.dot(l1, r1) + np.dot(l2.ravel(), r2.ravel())\n        l1 /= ldotr\n        l2 /= ldotr\n        l2 = 1./3*(l2 + 2.*l2.transpose(1,0,2))\n\n        deltaE = 0.0\n        eijk = (mo_e_occ[:,None,None,None,None] +\n                mo_e_occ[None,:,None,None,None] +\n                mo_e_occ[None,None,:,None,None] + eval_)\n        for a0, a1 in lib.prange_tril(0, nvir, blksize):\n            b0, b1 = 0, a1\n            eijkab = (eijk - mo_e_vir[a0:a1][None,None,None,:,None] -\n                      mo_e_vir[b0:b1][None,None,None,None,:])\n            eijkab = 1./eijkab\n            vvov_a = eris_vvop[a0:a1,b0:b1,:,:]\n            vvov_b = eris_vvop[b0:b1,a0:a1,:,:]\n            lijkab = contract_pl2p(l1, l2, a0, a1, b0, b1, vvov_a, vvov_b)\n            rijkab = contract_pr2p(r1, r2, a0, a1, b0, b1, vvov_a, vvov_b)\n\n            lijkab = 4.*lijkab \\\n                   - 2.*lijkab.transpose(1,0,2,3,4) \\\n                   - 2.*lijkab.transpose(2,1,0,3,4) \\\n                   - 2.*lijkab.transpose(0,2,1,3,4) \\\n                   + 1.*lijkab.transpose(1,2,0,3,4) \\\n                   + 1.*lijkab.transpose(2,0,1,3,4)\n\n            # Symmetry factors (1 for a == b, 2 for a < b)\n            fac = 2*np.ones_like(rijkab, dtype=int)\n            triu_idx = np.triu_indices(a1-a0, a0+1, m=b1-b0)\n            fac[:,:,:,triu_idx[0],triu_idx[1]] = 0\n            fac[:,:,:,np.arange(a1-a0),np.arange(a0,b1)] = 1\n            eijkab *= fac\n\n            deltaE += np.einsum('ijkab,ijkab,ijkab', lijkab, rijkab, eijkab)\n        deltaE = 0.5*deltaE.real\n        logger.info(eom, \"ipccsd energy, star energy, delta energy = %16.12f, %16.12f, %16.12f\",\n                    eval_, eval_+deltaE, deltaE)\n        e.append(eval_+deltaE)\n    t2 = restore_t2_inplace(t2T)\n    return e\n\nclass EOMIP(EOM):\n    def get_init_guess(self, nroots=1, koopmans=True, diag=None):\n        size = self.vector_size()\n        dtype = getattr(diag, 'dtype', np.double)\n        nroots = min(nroots, size)\n        guess = []\n        if koopmans:\n            for n in range(nroots):\n                g = np.zeros(int(size), dtype)\n                g[self.nocc-n-1] = 1.0\n                guess.append(g)\n        else:\n            idx = diag.argsort()[:nroots]\n            for i in idx:\n                g = np.zeros(int(size), dtype)\n                g[i] = 1.0\n                guess.append(g)\n        return guess\n\n    kernel = ipccsd\n    ipccsd = ipccsd\n    ipccsd_star = ipccsd_star\n\n    matvec = ipccsd_matvec\n    l_matvec = lipccsd_matvec\n    get_diag = ipccsd_diag\n    ccsd_star_contract = ipccsd_star_contract\n\n    def ipccsd_star_contract(self, ipccsd_evals, ipccsd_evecs, lipccsd_evecs, imds=None):\n        return self.ccsd_star_contract(ipccsd_evals, ipccsd_evecs, lipccsd_evecs, imds=imds)\n\n    def gen_matvec(self, imds=None, left=False, **kwargs):\n        if imds is None: imds = self.make_imds()\n        diag = self.get_diag(imds)\n        if left:\n            matvec = lambda xs: [self.l_matvec(x, imds, diag) for x in xs]\n        else:\n            matvec = lambda xs: [self.matvec(x, imds, diag) for x in xs]\n        return matvec, diag\n\n    def vector_to_amplitudes(self, vector, nmo=None, nocc=None):\n        if nmo is None: nmo = self.nmo\n        if nocc is None: nocc = self.nocc\n        return vector_to_amplitudes_ip(vector, nmo, nocc)\n\n    def amplitudes_to_vector(self, r1, r2):\n        return amplitudes_to_vector_ip(r1, r2)\n\n    def vector_size(self):\n        nocc = self.nocc\n        nvir = self.nmo - nocc\n        return nocc + nocc*nocc*nvir\n\n    def make_imds(self, eris=None):\n        imds = _IMDS(self._cc, eris=eris)\n        imds.make_ip(self.partition)\n        return imds\n\n    @property\n    def eip(self):\n        return self.e\n\n\nclass EOMIP_Ta(EOMIP):\n    '''Class for EOM IPCCSD(T)*(a) method by Matthews and Stanton.'''\n    def make_imds(self, eris=None):\n        imds = _IMDS(self._cc, eris=eris)\n        imds.make_t3p2_ip(self._cc, self.partition)\n        return imds\n\n########################################\n# EOM-EA-CCSD\n########################################\n\ndef eaccsd(eom, nroots=1, left=False, koopmans=False, guess=None,\n           partition=None, eris=None, imds=None):\n    '''Calculate (N+1)-electron charged excitations via EA-EOM-CCSD.\n\n    Args:\n        See also ipccd()\n    '''\n    return ipccsd(eom, nroots, left, koopmans, guess, partition, eris, imds)\n\ndef eaccsd_star(eom, nroots=1, koopmans=False, right_guess=None,\n                left_guess=None, eris=None, imds=None, **kwargs):\n    \"\"\"Calculates CCSD* perturbative correction.\n\n    Args:\n        See also ipccd_star()\n    \"\"\"\n    return perturbed_ccsd_kernel(eom, nroots=nroots, koopmans=koopmans,\n                                 right_guess=right_guess, left_guess=left_guess, eris=eris,\n                                 imds=imds)\n\ndef vector_to_amplitudes_ea(vector, nmo, nocc):\n    nvir = nmo - nocc\n    r1 = vector[:nvir].copy()\n    r2 = vector[nvir:].copy().reshape(nocc,nvir,nvir)\n    return r1, r2\n\ndef amplitudes_to_vector_ea(r1, r2):\n    vector = np.hstack((r1, r2.ravel()))\n    return vector\n\ndef eaccsd_matvec(eom, vector, imds=None, diag=None):\n    # Ref: Nooijen and Bartlett, J. Chem. Phys. 102, 3629 (1995) Eqs.(30)-(31)\n    if imds is None: imds = eom.make_imds()\n    nocc = eom.nocc\n    nmo = eom.nmo\n    nvir = nmo - nocc\n    r1, r2 = vector_to_amplitudes_ea(vector, nmo, nocc)\n\n    # Eq. (37)\n    # 1p-1p block\n    Hr1 =  np.einsum('ac,c->a', imds.Lvv, r1)\n    # 1p-2p1h block\n    Hr1 += np.einsum('ld,lad->a', 2.*imds.Fov, r2)\n    Hr1 += np.einsum('ld,lda->a',   -imds.Fov, r2)\n    Hr1 += np.einsum('alcd,lcd->a', 2.*imds.Wvovv-imds.Wvovv.transpose(0,1,3,2), r2)\n    # Eq. (38)\n    # 2p1h-1p block\n    Hr2 = np.einsum('abcj,c->jab', imds.Wvvvo, r1)\n    # 2p1h-2p1h block\n    if eom.partition == 'mp':\n        fock = imds.eris.fock\n        foo = fock[:nocc,:nocc]\n        fvv = fock[nocc:,nocc:]\n        Hr2 +=  lib.einsum('ac,jcb->jab', fvv, r2)\n        Hr2 +=  lib.einsum('bd,jad->jab', fvv, r2)\n        Hr2 += -lib.einsum('lj,lab->jab', foo, r2)\n    elif eom.partition == 'full':\n        diag_matrix2 = vector_to_amplitudes_ea(diag, nmo, nocc)[1]\n        Hr2 += diag_matrix2 * r2\n    else:\n        Hr2 +=  lib.einsum('ac,jcb->jab', imds.Lvv, r2)\n        Hr2 +=  lib.einsum('bd,jad->jab', imds.Lvv, r2)\n        Hr2 += -lib.einsum('lj,lab->jab', imds.Loo, r2)\n        Hr2 += lib.einsum('lbdj,lad->jab', 2.*imds.Wovvo-imds.Wovov.transpose(0,1,3,2), r2)\n        Hr2 += -lib.einsum('lajc,lcb->jab', imds.Wovov, r2)\n        Hr2 += -lib.einsum('lbcj,lca->jab', imds.Wovvo, r2)\n        for a in range(nvir):\n            Hr2[:,a,:] += lib.einsum('bcd,jcd->jb', imds.Wvvvv[a], r2)\n        tmp = np.einsum('klcd,lcd->k', 2.*imds.Woovv-imds.Woovv.transpose(0,1,3,2), r2)\n        Hr2 += -np.einsum('k,kjab->jab', tmp, imds.t2)\n\n    vector = amplitudes_to_vector_ea(Hr1,Hr2)\n    return vector\n\ndef leaccsd_matvec(eom, vector, imds=None, diag=None):\n    # Note this is not the same left EA equations used by Nooijen and Bartlett.\n    # Small changes were made so that the same type L2 basis was used for both the\n    # left EA and left IP equations.  You will note more similarity for these\n    # equations to the left IP equations than for the left EA equations by Nooijen.\n    if imds is None: imds = eom.make_imds()\n    nocc = eom.nocc\n    nmo = eom.nmo\n    nvir = nmo - nocc\n    r1, r2 = vector_to_amplitudes_ea(vector, nmo, nocc)\n\n    # Eq. (30)\n    # 1p-1p block\n    Hr1 = np.einsum('ac,a->c', imds.Lvv, r1)\n    # 1p-2p1h block\n    Hr1 += np.einsum('abcj,jab->c', imds.Wvvvo, r2)\n    # Eq. (31)\n    # 2p1h-1p block\n    Hr2 = 2.*np.einsum('c,ld->lcd', r1, imds.Fov)\n    Hr2 +=  -np.einsum('d,lc->lcd', r1, imds.Fov)\n    Hr2 += np.einsum('a,alcd->lcd', r1, 2.*imds.Wvovv-imds.Wvovv.transpose(0,1,3,2))\n    # 2p1h-2p1h block\n    if eom.partition == 'mp':\n        fock = imds.eris.fock\n        foo = fock[:nocc,:nocc]\n        fvv = fock[nocc:,nocc:]\n        Hr2 += lib.einsum('lad,ac->lcd', r2, fvv)\n        Hr2 += lib.einsum('lcb,bd->lcd', r2, fvv)\n        Hr2 += -lib.einsum('jcd,lj->lcd', r2, foo)\n    elif eom.partition == 'full':\n        diag_matrix2 = vector_to_amplitudes_ea(diag, nmo, nocc)[1]\n        Hr2 += diag_matrix2 * r2\n    else:\n        Hr2 += lib.einsum('lad,ac->lcd', r2, imds.Lvv)\n        Hr2 += lib.einsum('lcb,bd->lcd', r2, imds.Lvv)\n        Hr2 += -lib.einsum('jcd,lj->lcd', r2, imds.Loo)\n        Hr2 += lib.einsum('jcb,lbdj->lcd', r2, 2.*imds.Wovvo-imds.Wovov.transpose(0,1,3,2))\n        Hr2 += -lib.einsum('lajc,jab->lcb', imds.Wovov, r2)\n        Hr2 += -lib.einsum('lbcj,jab->lca', imds.Wovvo, r2)\n        for a in range(nvir):\n            Hr2 += lib.einsum('lb,bcd->lcd', r2[:,a,:], imds.Wvvvv[a])\n        tmp = np.einsum('ijcb,ibc->j', imds.t2, r2)\n        Hr2 += -np.einsum('kjfe,j->kef', 2.*imds.Woovv-imds.Woovv.transpose(0,1,3,2),tmp)\n\n    vector = amplitudes_to_vector_ea(Hr1,Hr2)\n    return vector\n\ndef eaccsd_diag(eom, imds=None):\n    if imds is None: imds = eom.make_imds()\n    t1, t2 = imds.t1, imds.t2\n    dtype = np.result_type(t1, t2)\n    nocc, nvir = t1.shape\n\n    fock = imds.eris.fock\n    foo = fock[:nocc,:nocc]\n    fvv = fock[nocc:,nocc:]\n\n    Hr1 = np.diag(imds.Lvv)\n    Hr2 = np.zeros((nocc,nvir,nvir), dtype)\n    for a in range(nvir):\n        if eom.partition != 'mp':\n            _Wvvvva = np.array(imds.Wvvvv[a])\n        for b in range(nvir):\n            for j in range(nocc):\n                if eom.partition == 'mp':\n                    Hr2[j,a,b] += fvv[a,a]\n                    Hr2[j,a,b] += fvv[b,b]\n                    Hr2[j,a,b] += -foo[j,j]\n                else:\n                    Hr2[j,a,b] += imds.Lvv[a,a]\n                    Hr2[j,a,b] += imds.Lvv[b,b]\n                    Hr2[j,a,b] += -imds.Loo[j,j]\n                    Hr2[j,a,b] += 2*imds.Wovvo[j,b,b,j]\n                    Hr2[j,a,b] += -imds.Wovov[j,b,j,b]\n                    Hr2[j,a,b] += -imds.Wovov[j,a,j,a]\n                    Hr2[j,a,b] += -imds.Wovvo[j,b,b,j]*(a==b)\n                    Hr2[j,a,b] += _Wvvvva[b,a,b]\n                    Hr2[j,a,b] += -2*np.dot(imds.Woovv[:,j,a,b], t2[:,j,a,b])\n                    Hr2[j,a,b] += np.dot(imds.Woovv[:,j,b,a], t2[:,j,a,b])\n\n    vector = amplitudes_to_vector_ea(Hr1,Hr2)\n    return vector\n\ndef eaccsd_star_contract(eom, eaccsd_evals, eaccsd_evecs, leaccsd_evecs, imds=None):\n    cpu1 = (logger.process_clock(), logger.perf_counter())\n    log = logger.Logger(eom.stdout, eom.verbose)\n    if imds is None:\n        imds = eom.make_imds()\n    t1, t2 = imds.t1, imds.t2\n    eris = imds.eris\n\n    nocc, nvir = t1.shape\n    dtype = np.result_type(t1, t2, eris.ovoo.dtype)\n    # Notice we do not use `sort_eri` as compared to the eaccsd_star.\n    # The sort_eri does not produce eri's that are read-in quickly for the current contraction\n    # scheme.  Here, we have that the block loop is over occupied indices whereas in the\n    # sort_eri it is done over virtual indices (due to the permutation over occupied indices\n    # in ipccsd_star versus virtual indices in eaccsd_star).\n    cpu1 = log.timer_debug1('CCSD(T) sort_eri', *cpu1)  # Left if new sort_eri implemented\n\n    mem_now = lib.current_memory()[0]\n    max_memory = max(0, eom.max_memory - mem_now)\n    blksize = min(nocc, max(ccsd.BLKMIN, int(max_memory*1e6/8/(nvir**3*6))))\n\n    mo_energy = np.asarray(eris.mo_energy)\n    mo_e_occ = np.asarray(mo_energy[:nocc])\n    mo_e_vir = np.asarray(mo_energy[nocc:])\n\n    def contract_l2p(l1, l2, i0, i1, j0, j1, cache_ovvv_i, cache_ovvv_j, out=None):\n        '''Create perturbed l2.'''\n        if out is None:\n            out = np.zeros((i1-i0,j1-j0) + (nvir,)*3, dtype=dtype)\n        out += -0.5*np.einsum('iajb,c->ijabc', eris.ovov[i0:i1,:,j0:j1], l1)\n        out += lib.einsum('iajm,mbc->ijabc', eris.ovoo[i0:i1,:,j0:j1], l2)\n        out -= lib.einsum('iaeb,jec->ijabc', cache_ovvv_i, l2[j0:j1])\n        out -= lib.einsum('jbec,iae->ijabc', cache_ovvv_j, l2[i0:i1])\n        return out\n\n    def contract_pl2p(l1, l2, i0, i1, j0, j1, cache_ovvv_i, cache_ovvv_j):\n        '''Create P(ia|jb) of perturbed l2.'''\n        out = contract_l2p(l1, l2, i0, i1, j0, j1, cache_ovvv_i, cache_ovvv_j)\n        tmp = contract_l2p(l1, l2, j0, j1, i0, i1, cache_ovvv_j, cache_ovvv_i)\n        tmp = tmp.transpose(1,0,3,2,4)  # P(ia|jb)\n        out = out + tmp\n        return out\n\n    def _get_vvvv(eris):\n        if eris.vvvv is None and getattr(eris, 'vvL', None) is not None:  # DF eris\n            vvL = np.asarray(eris.vvL)\n            nvir = int(np.sqrt(eris.vvL.shape[0]*2))\n            return ao2mo.restore(1, lib.dot(vvL, vvL.T), nvir)\n        elif eris.vvvv.ndim == 2:\n            nvir = int(np.sqrt(eris.vvvv.shape[0]*2))\n            return ao2mo.restore(1, np.asarray(eris.vvvv), nvir)\n        else:\n            return eris.vvvv\n\n    def contract_r2p(r1, r2, i0, i1, j0, j1, cache_ovvv_i, cache_ovvv_j, out=None):\n        '''Create perturbed r2.'''\n        if out is None:\n            out = np.zeros((i1-i0,j1-j0) + (nvir,)*3, dtype=dtype)\n        tmp = np.einsum('becf,f->bce', _get_vvvv(eris), r1)\n        out += -lib.einsum('bce,ijae->ijabc', tmp, t2[i0:i1,j0:j1])\n        tmp = np.einsum('mjce,e->mcj', eris.oovv[:,j0:j1], r1)\n        out += lib.einsum('mcj,imab->ijabc', tmp, t2[i0:i1])\n        tmp = np.einsum('jbem,e->mbj', eris.ovvo[j0:j1], r1)\n        out += lib.einsum('mbj,imac->ijabc', tmp, t2[i0:i1])\n        out += lib.einsum('iajm,mbc->ijabc', eris.ovoo[i0:i1,:,j0:j1].conj(), r2)\n        out += -lib.einsum('iaeb,jec->ijabc', cache_ovvv_i.conj(), r2[j0:j1])\n        out += -lib.einsum('jbec,iae->ijabc', cache_ovvv_j.conj(), r2[i0:i1])\n        return out\n\n    def contract_pr2p(r1, r2, i0, i1, j0, j1, cache_ovvv_i, cache_ovvv_j):\n        '''Create P(ia|jb) of perturbed r2.'''\n        out = contract_r2p(r1, r2, i0, i1, j0, j1, cache_ovvv_i, cache_ovvv_j)\n        tmp = contract_r2p(r1, r2, j0, j1, i0, i1, cache_ovvv_j, cache_ovvv_i)\n        tmp = tmp.transpose(1,0,3,2,4)  # P(ia|jb)\n        out = out + tmp\n        return out\n\n    eaccsd_evecs  = np.array(eaccsd_evecs)\n    leaccsd_evecs = np.array(leaccsd_evecs)\n    e = []\n    eaccsd_evecs, leaccsd_evecs = [np.atleast_2d(x) for x in [eaccsd_evecs, leaccsd_evecs]]\n    eaccsd_evals = np.atleast_1d(eaccsd_evals)\n    for eval_, evec_, levec_ in zip(eaccsd_evals, eaccsd_evecs, leaccsd_evecs):\n        l1, l2 = eom.vector_to_amplitudes(levec_)\n        r1, r2 = eom.vector_to_amplitudes(evec_)\n        ldotr = np.dot(l1, r1) + np.dot(l2.ravel(),r2.ravel())\n        l1 /= ldotr\n        l2 /= ldotr\n        l2 = 1./3*(1.*l2 + 2.*l2.transpose(0,2,1))\n        r2 = r2.transpose(0,2,1)\n\n        deltaE = 0.0\n        eabc = (mo_e_vir[None,None,:,None,None] +\n                mo_e_vir[None,None,None,:,None] +\n                mo_e_vir[None,None,None,None,:] - eval_)\n\n        for i0, i1 in lib.prange_tril(0, nocc, blksize):\n            j0, j1 = 0, i1\n            eijabc = (mo_e_occ[i0:i1][:,None,None,None,None] +\n                      mo_e_occ[j0:j1][None,:,None,None,None] - eabc)\n            eijabc = 1./eijabc\n            cache_ovvv_i = eris.get_ovvv(slice(i0,i1))\n            cache_ovvv_j = eris.get_ovvv(slice(j0,j1))\n            lijabc = contract_pl2p(l1, l2, i0, i1, j0, j1, cache_ovvv_i, cache_ovvv_j)\n            rijabc = contract_pr2p(r1, r2, i0, i1, j0, j1, cache_ovvv_i, cache_ovvv_j)\n\n            lijabc =  4.*lijabc \\\n                    - 2.*lijabc.transpose(0,1,3,2,4) \\\n                    - 2.*lijabc.transpose(0,1,4,3,2) \\\n                    - 2.*lijabc.transpose(0,1,2,4,3) \\\n                    + 1.*lijabc.transpose(0,1,3,4,2) \\\n                    + 1.*lijabc.transpose(0,1,4,2,3)\n\n            # Symmetry factors (1 for a == b, 2 for a < b)\n            fac = 2*np.ones_like(rijabc, dtype=int)\n            triu_idx = np.triu_indices(i1-i0,i0+1,m=j1-j0)\n            fac[triu_idx[0],triu_idx[1],:,:,:] = 0\n            fac[np.arange(i1-i0),np.arange(i0,j1)] = 1\n            eijabc *= fac\n\n            deltaE += np.einsum('ijabc,ijabc,ijabc',lijabc,rijabc,eijabc)\n        deltaE = 0.5*deltaE.real\n        logger.info(eom, \"eaccsd energy, star energy, delta energy = %16.12f, %16.12f, %16.12f\",\n                    eval_, eval_+deltaE, deltaE)\n        e.append(eval_+deltaE)\n    return e\n\n\nclass EOMEA(EOM):\n    def get_init_guess(self, nroots=1, koopmans=True, diag=None):\n        size = self.vector_size()\n        dtype = getattr(diag, 'dtype', np.double)\n        nroots = min(nroots, size)\n        guess = []\n        if koopmans:\n            for n in range(nroots):\n                g = np.zeros(size, dtype)\n                g[n] = 1.0\n                guess.append(g)\n        else:\n            idx = diag.argsort()[:nroots]\n            for i in idx:\n                g = np.zeros(size, dtype)\n                g[i] = 1.0\n                guess.append(g)\n        return guess\n\n    kernel = eaccsd\n    eaccsd = eaccsd\n    eaccsd_star = eaccsd_star\n\n    matvec = eaccsd_matvec\n    l_matvec = leaccsd_matvec\n    get_diag = eaccsd_diag\n    ccsd_star_contract = eaccsd_star_contract\n\n    def eaccsd_star_contract(self, eaccsd_evals, eaccsd_evecs, leaccsd_evecs, imds=None):\n        return self.ccsd_star_contract(eaccsd_evals, eaccsd_evecs, leaccsd_evecs, imds=imds)\n\n    def gen_matvec(self, imds=None, left=False, **kwargs):\n        if imds is None: imds = self.make_imds()\n        diag = self.get_diag(imds)\n        if left:\n            matvec = lambda xs: [self.l_matvec(x, imds, diag) for x in xs]\n        else:\n            matvec = lambda xs: [self.matvec(x, imds, diag) for x in xs]\n        return matvec, diag\n\n    def vector_to_amplitudes(self, vector, nmo=None, nocc=None):\n        if nmo is None: nmo = self.nmo\n        if nocc is None: nocc = self.nocc\n        return vector_to_amplitudes_ea(vector, nmo, nocc)\n\n    def amplitudes_to_vector(self, r1, r2):\n        return amplitudes_to_vector_ea(r1, r2)\n\n    def vector_size(self):\n        nocc = self.nocc\n        nvir = self.nmo - nocc\n        return nvir + nocc*nvir*nvir\n\n    def make_imds(self, eris=None):\n        imds = _IMDS(self._cc, eris=eris)\n        imds.make_ea(self.partition)\n        return imds\n\n    @property\n    def eea(self):\n        return self.e\n\n\nclass EOMEA_Ta(EOMEA):\n    '''Class for EOM EACCSD(T)*(a) method by Matthews and Stanton.'''\n    def make_imds(self, eris=None):\n        imds = _IMDS(self._cc, eris=eris)\n        imds.make_t3p2_ea(self._cc, self.partition)\n        return imds\n\n########################################\n# EOM-EE-CCSD\n########################################\n\n#TODO: double spin-flip EOM-EE\n\ndef eeccsd(eom, nroots=1, koopmans=False, guess=None, eris=None, imds=None):\n    '''Calculate N-electron neutral excitations via EOM-EE-CCSD.\n\n    Kwargs:\n        nroots : int\n            Number of roots (eigenvalues) requested\n        koopmans : bool\n            Calculate Koopmans'-like (1p1h) excitations only, targeting via\n            overlap.\n        guess : list of ndarray\n            List of guess vectors to use for targeting via overlap.\n    '''\n    if eris is None: eris = eom._cc.ao2mo()\n    if imds is None: imds = eom.make_imds(eris)\n\n    spinvec_size = eom.vector_size()\n    nroots = min(nroots, spinvec_size)\n\n    diag_eeS, diag_eeT, diag_sf = eom.get_diag(imds)\n    guess_eeS = []\n    guess_eeT = []\n    guess_sf = []\n    if guess:\n        for g in guess:\n            if g is None: # beta->alpha spin-flip excitation\n                pass\n            elif g.size == diag_eeS.size:\n                guess_eeS.append(g)\n            elif g.size == diag_eeT.size:\n                guess_eeT.append(g)\n            else:\n                guess_sf.append(g)\n        nroots_eeS = len(guess_eeS)\n        nroots_eeT = len(guess_eeT)\n        nroots_sf = len(guess_sf)\n        if len(guess) != nroots:\n            logger.warn(eom, 'Number of states in initial guess %d does not '\n                        'equal to nroots %d.', len(guess), nroots)\n    else:\n        deeS = np.sort(diag_eeS)[:nroots]\n        deeT = np.sort(diag_eeT)[:nroots]\n        dsf = np.sort(diag_sf)[:nroots]\n        dmax = np.sort(np.hstack([deeS,deeT,dsf,dsf]))[nroots-1]\n        nroots_eeS = np.count_nonzero(deeS <= dmax)\n        nroots_eeT = np.count_nonzero(deeT <= dmax)\n        nroots_sf = np.count_nonzero(dsf <= dmax)\n        guess_eeS = guess_eeT = guess_sf = None\n\n    def eomee_sub(cls, nroots, guess, diag):\n        ee_sub = cls(eom._cc)\n        ee_sub.__dict__.update(eom.__dict__)\n        e, v = ee_sub.kernel(nroots, koopmans, guess, eris, imds, diag=diag)\n        if nroots == 1:\n            e, v = [e], [v]\n            ee_sub.converged = [ee_sub.converged]\n        return list(ee_sub.converged), list(e), list(v)\n\n    e0 = e1 = e2 = []\n    v0 = v1 = v2 = []\n    conv0 = conv1 = conv2 = []\n    if nroots_eeS > 0:\n        conv0, e0, v0 = eomee_sub(EOMEESinglet, nroots_eeS, guess_eeS, diag_eeS)\n    if nroots_eeT > 0:\n        conv2, e2, v2 = eomee_sub(EOMEETriplet, nroots_eeT, guess_eeT, diag_eeT)\n    if nroots_sf > 0:\n        conv1, e1, v1 = eomee_sub(EOMEESpinFlip, nroots_sf, guess_sf, diag_sf)\n        # The associated solutions of beta->alpha excitations\n        e1 = e1 + e1\n        conv1 = conv1 + conv1\n        v1 = v1 + [None] * len(v1)\n# beta->alpha spin-flip excitations, the coefficients are (-r1, (-r2[0], r2[1]))\n# as below.  The EOMEESpinFlip class only handles alpha->beta excitations.\n# Setting beta->alpha to None to bypass the vectors in initial guess\n        #for i in range(nroots_sf):\n        #    r1, r2 = vector_to_amplitudes_eomsf(v1[i], eom.nmo, eom.nocc)\n        #    v1.append(amplitudes_to_vector_eomsf(-r1, (-r2[0], r2[1])))\n\n    e = np.hstack([e0,e2,e1])\n    idx = e.argsort()\n    e = e[idx]\n    conv = conv0 + conv2 + conv1\n    conv = [conv[x] for x in idx]\n    v = v0 + v2 + v1\n    v = [v[x] for x in idx]\n\n    if nroots == 1:\n        conv = conv[0]\n        e = e[0]\n        v = v[0]\n    eom.converged = conv\n    eom.e = e\n    eom.v = v\n    return eom.e, eom.v\n\n\ndef eomee_ccsd_singlet(eom, nroots=1, koopmans=False, guess=None,\n                       eris=None, imds=None, diag=None):\n    '''EOM-EE-CCSD singlet\n    '''\n    eom.converged, eom.e, eom.v \\\n            = kernel(eom, nroots, koopmans, guess, eris=eris, imds=imds, diag=diag)\n    return eom.e, eom.v\n\ndef eomee_ccsd_triplet(eom, nroots=1, koopmans=False, guess=None,\n                       eris=None, imds=None, diag=None):\n    '''EOM-EE-CCSD triplet\n    '''\n    return eomee_ccsd_singlet(eom, nroots, koopmans, guess, eris, imds, diag)\n\ndef eomsf_ccsd(eom, nroots=1, koopmans=False, guess=None,\n               eris=None, imds=None, diag=None):\n    '''Spin flip EOM-EE-CCSD\n    '''\n    return eomee_ccsd_singlet(eom, nroots, koopmans, guess, eris, imds, diag)\n\nvector_to_amplitudes_ee = vector_to_amplitudes_singlet = ccsd.vector_to_amplitudes\namplitudes_to_vector_ee = amplitudes_to_vector_singlet = ccsd.amplitudes_to_vector\n\ndef amplitudes_to_vector_eomsf(t1, t2, out=None):\n    nocc, nvir = t1.shape\n    t2baaa, t2aaba = t2\n    otril = np.tril_indices(nocc, k=-1)\n    vtril = np.tril_indices(nvir, k=-1)\n    baaa = np.take(t2baaa.reshape(nocc*nocc,nvir*nvir),\n                   vtril[0]*nvir+vtril[1], axis=1)\n    vector = np.hstack((t1.ravel(), baaa.ravel(), t2aaba[otril].ravel()))\n    return vector\n\ndef vector_to_amplitudes_eomsf(vector, nmo, nocc):\n    nvir = nmo - nocc\n    t1 = vector[:nocc*nvir].reshape(nocc,nvir).copy()\n    pvec = vector[t1.size:]\n\n    nbaaa = nocc*nocc*nvir*(nvir-1)//2\n    naaba = nocc*(nocc-1)//2*nvir*nvir\n    t2baaa = np.zeros((nocc*nocc,nvir*nvir), dtype=vector.dtype)\n    t2aaba = np.zeros((nocc*nocc,nvir*nvir), dtype=vector.dtype)\n    otril = np.tril_indices(nocc, k=-1)\n    vtril = np.tril_indices(nvir, k=-1)\n\n    v = pvec[:nbaaa].reshape(nocc*nocc,nvir*(nvir-1)//2)\n    t2baaa[:,vtril[0]*nvir+vtril[1]] = v\n    t2baaa[:,vtril[1]*nvir+vtril[0]] = -v\n\n    v = pvec[nbaaa:nbaaa+naaba].reshape(-1,nvir*nvir)\n    t2aaba[otril[0]*nocc+otril[1]] = v\n    t2aaba[otril[1]*nocc+otril[0]] = -v\n\n    t2baaa = t2baaa.reshape(nocc,nocc,nvir,nvir)\n    t2aaba = t2aaba.reshape(nocc,nocc,nvir,nvir)\n    return t1, (t2baaa, t2aaba)\n\ndef amplitudes_to_vector_triplet(t1, t2, out=None):\n    t2aa, t2ab = t2\n    dtype = np.result_type(t1, t2aa, t2ab)\n    nocc, nvir = t1.shape\n    nov = nocc * nvir\n    size1 = nov + nocc*(nocc-1)//2*nvir*(nvir-1)//2\n    size = size1 + nov*(nov+1)//2\n    vector = np.ndarray(size, dtype, buffer=out)\n    ccsd.amplitudes_to_vector_s4(t1, t2[0], out=vector)\n    t2ab = t2[1].transpose(0,2,1,3).reshape(nov,nov)\n    lib.pack_tril(t2ab, out=vector[size1:])\n    return vector\n\ndef vector_to_amplitudes_triplet(vector, nmo, nocc):\n    nvir = nmo - nocc\n    nov = nocc * nvir\n    size1 = nov + nocc*(nocc-1)//2*nvir*(nvir-1)//2\n    size = size1 + nov*(nov+1)//2\n    t1, t2aa = ccsd.vector_to_amplitudes_s4(vector[:size1], nmo, nocc)\n    t2ab = lib.unpack_tril(vector[size1:size], filltriu=2)\n    t2ab = t2ab.reshape(nocc,nvir,nocc,nvir).transpose(0,2,1,3).copy()\n    return t1, (t2aa, t2ab)\n\ndef eeccsd_matvec_singlet(eom, vector, imds=None):\n    if imds is None: imds = eom.make_imds()\n    nocc = eom.nocc\n    nmo = eom.nmo\n    nvir = nmo - nocc\n\n    r1, r2 = vector_to_amplitudes_singlet(vector, nmo, nocc)\n    t1, t2, eris = imds.t1, imds.t2, imds.eris\n    nocc, nvir = t1.shape\n\n    Hr1  = lib.einsum('ae,ie->ia', imds.Fvv, r1)\n    Hr1 -= lib.einsum('mi,ma->ia', imds.Foo, r1)\n    Hr1 += np.einsum('me,imae->ia',imds.Fov, r2) * 2\n    Hr1 -= np.einsum('me,imea->ia',imds.Fov, r2)\n\n    #:eris_vvvv = ao2mo.restore(1,np.asarray(eris.vvvv), t1.shape[1])\n    #:Hr2 += lib.einsum('ijef,aebf->ijab', tau2, eris_vvvv) * .5\n    tau2 = _make_tau(r2, r1, t1, fac=2)\n    Hr2 = eom._cc._add_vvvv(None, tau2, eris, with_ovvv=False, t2sym='jiba')\n\n    woOoO = np.asarray(imds.woOoO)\n    Hr2 += lib.einsum('mnij,mnab->ijab', woOoO, r2)\n    Hr2 *= .5\n    woOoO = None\n\n    Hr2 += lib.einsum('be,ijae->ijab', imds.Fvv   , r2)\n    Hr2 -= lib.einsum('mj,imab->ijab', imds.Foo   , r2)\n\n    mem_now = lib.current_memory()[0]\n    max_memory = max(0, eom.max_memory - mem_now - Hr2.size*8e-6)\n    blksize = min(nocc, max(ccsd.BLKMIN, int(max_memory*1e6/8/(nvir**3*3))))\n    for p0,p1 in lib.prange(0, nocc, blksize):\n        ovvv = eris.get_ovvv(slice(p0,p1))  # ovvv = eris.ovvv[p0:p1]\n        theta = r2[p0:p1] * 2 - r2[p0:p1].transpose(0,1,3,2)\n        Hr1 += lib.einsum('mfae,mife->ia', ovvv, theta)\n        theta = None\n        tmp = lib.einsum('meaf,ijef->maij', ovvv, tau2)\n        Hr2 -= lib.einsum('ma,mbij->ijab', t1[p0:p1], tmp)\n        tmp  = lib.einsum('meaf,me->af', ovvv, r1[p0:p1]) * 2\n        tmp -= lib.einsum('mfae,me->af', ovvv, r1[p0:p1])\n        Hr2 += lib.einsum('af,ijfb->ijab', tmp, t2)\n        ovvv = tmp = None\n    tau2 = None\n    Hr2 -= lib.einsum('mbij,ma->ijab', imds.woVoO, r1)\n\n    blksize = min(nvir, max(ccsd.BLKMIN, int(max_memory*1e6/8/(nocc*nvir**2*2))))\n    for p0, p1 in lib.prange(0, nvir, nocc):\n        Hr2 += lib.einsum('ejab,ie->ijab', np.asarray(imds.wvOvV[p0:p1]), r1[:,p0:p1])\n\n    woVVo = np.asarray(imds.woVVo)\n    tmp = lib.einsum('mbej,imea->jiab', woVVo, r2)\n    Hr2 += tmp\n    tmp *= .5\n    Hr2 += tmp.transpose(0,1,3,2)\n    tmp = None\n\n    woVvO = woVVo * .5\n    woVVo = None\n    woVvO += np.asarray(imds.woVvO)\n    theta = r2*2 - r2.transpose(0,1,3,2)\n    Hr1 += np.einsum('maei,me->ia', woVvO, r1) * 2\n    Hr2 += lib.einsum('mbej,imae->ijab', woVvO, theta)\n    woVvO = None\n\n    woOoV = np.asarray(imds.woOoV)\n    Hr1-= lib.einsum('mnie,mnae->ia', woOoV, theta)\n    tmp = lib.einsum('nmie,me->ni', woOoV, r1) * 2\n    tmp-= lib.einsum('mnie,me->ni', woOoV, r1)\n    Hr2 -= lib.einsum('ni,njab->ijab', tmp, t2)\n    tmp = woOoV = None\n\n    eris_ovov = np.asarray(eris.ovov)\n    tmp  = np.einsum('mfne,mf->en', eris_ovov, r1) * 2\n    tmp -= np.einsum('menf,mf->en', eris_ovov, r1)\n    tmp  = np.einsum('en,nb->eb', tmp, t1)\n    tmp += lib.einsum('menf,mnbf->eb', eris_ovov, theta)\n    Hr2 -= lib.einsum('eb,ijea->jiab', tmp, t2)\n    tmp = None\n\n    tmp = lib.einsum('nemf,imef->ni', eris_ovov, theta)\n    Hr1 -= lib.einsum('na,ni->ia', t1, tmp)\n    Hr2 -= lib.einsum('mj,miab->ijba', tmp, t2)\n    tmp = theta = None\n\n    tau2 = _make_tau(r2, r1, t1, fac=2)\n    tmp = lib.einsum('menf,ijef->mnij', eris_ovov, tau2)\n    tau2 = None\n\n    tau = _make_tau(t2, t1, t1)\n    tau *= .5\n    Hr2 += lib.einsum('mnij,mnab->ijab', tmp, tau)\n    tau = tmp = eris_ovov = None\n\n    Hr2 = Hr2 + Hr2.transpose(1,0,3,2)\n    vector = amplitudes_to_vector_ee(Hr1, Hr2)\n    return vector\n\ndef eeccsd_matvec_triplet(eom, vector, imds=None):\n    if imds is None: imds = eom.make_imds()\n    nocc = eom.nocc\n    nmo = eom.nmo\n    nvir = nmo - nocc\n\n    r1, r2 = vector_to_amplitudes_triplet(vector, nmo, nocc)\n    r2aa, r2ab = r2\n    t1, t2, eris = imds.t1, imds.t2, imds.eris\n    nocc, nvir = t1.shape\n\n    Hr1  = lib.einsum('ae,ie->ia', imds.Fvv, r1)\n    Hr1 -= lib.einsum('mi,ma->ia', imds.Foo, r1)\n    Hr1 += np.einsum('me,imae->ia',imds.Fov, r2aa)\n    Hr1 += np.einsum('ME,iMaE->ia',imds.Fov, r2ab)\n\n    tau2ab = np.einsum('ia,jb->ijab', r1, t1)\n    tau2ab-= np.einsum('ia,jb->ijab', t1, r1)\n    tau2ab+= r2ab\n    tau2aa = np.einsum('ia,jb->ijab', r1, t1)\n    tau2aa-= np.einsum('ia,jb->jiab', r1, t1)\n    tau2aa = tau2aa - tau2aa.transpose(0,1,3,2)\n    tau2aa+= r2aa\n\n    #:eris_vvvv = ao2mo.restore(1,np.asarray(eris.vvvv), t1.shape[1])\n    #:Hr2aa += lib.einsum('ijef,aebf->ijab', tau2aa, eris_vvvv) * .25\n    #:Hr2ab += lib.einsum('ijef,aebf->ijab', tau2ab, eris_vvvv) * .5\n    Hr2aa = eom._cc._add_vvvv(None, tau2aa, eris, with_ovvv=False, t2sym='jiba')\n    Hr2ab = eom._cc._add_vvvv(None, tau2ab, eris, with_ovvv=False, t2sym='-jiba')\n\n    woOoO = np.asarray(imds.woOoO)\n    Hr2aa += lib.einsum('mnij,mnab->ijab', woOoO, r2aa)\n    Hr2ab += lib.einsum('mNiJ,mNaB->iJaB', woOoO, r2ab)\n    Hr2aa *= .25\n    Hr2ab *= .5\n    woOoO = None\n\n    Hr2aa += lib.einsum('be,ijae->ijab', imds.Fvv*.5, r2aa)\n    Hr2aa -= lib.einsum('mj,imab->ijab', imds.Foo*.5, r2aa)\n    Hr2ab += lib.einsum('BE,iJaE->iJaB', imds.Fvv, r2ab)\n    Hr2ab -= lib.einsum('MJ,iMaB->iJaB', imds.Foo, r2ab)\n\n    mem_now = lib.current_memory()[0]\n    max_memory = max(0, eom.max_memory - mem_now - Hr2aa.size*8e-6)\n    blksize = min(nocc, max(ccsd.BLKMIN, int(max_memory*1e6/8/(nvir**3*3))))\n    tmp1 = np.zeros((nvir,nvir), dtype=r1.dtype)\n    for p0,p1 in lib.prange(0, nocc, blksize):\n        ovvv = eris.get_ovvv(slice(p0,p1))  # ovvv = eris.ovvv[p0:p1]\n        theta = r2aa[:,p0:p1] + r2ab[:,p0:p1]\n        Hr1 += lib.einsum('mfae,imef->ia', ovvv, theta)\n        theta = None\n        tmpaa = lib.einsum('meaf,ijef->maij', ovvv, tau2aa)\n        tmpab = lib.einsum('meAF,iJeF->mAiJ', ovvv, tau2ab)\n        tmp1 += lib.einsum('mfae,me->af', ovvv, r1[p0:p1])\n        Hr2aa+= lib.einsum('mb,maij->ijab', t1[p0:p1]*.5, tmpaa)\n        Hr2ab-= lib.einsum('mb,mAiJ->iJbA', t1[p0:p1], tmpab)\n        ovvv = tmpaa = tmpab = None\n    tau2aa = tau2ab = None\n\n    woVVo = np.asarray(imds.woVVo)\n    Hr1 += np.einsum('maei,me->ia', woVVo, r1)\n    Hr2aa += lib.einsum('mbej,imae->ijba', woVVo, r2ab)\n    Hr2ab += lib.einsum('MBEJ,iMEa->iJaB', woVVo, r2aa)\n    Hr2ab += lib.einsum('MbeJ,iMeA->iJbA', woVVo, r2ab)\n\n    woVVo = woVVo + np.asarray(imds.woVvO)\n    theta = r2aa + r2ab\n    tmp = lib.einsum('mbej,imae->ijab', woVVo, theta)\n    woVVo = None\n\n    woOoV = np.asarray(imds.woOoV)\n    Hr1 -= lib.einsum('mnie,mnae->ia', woOoV, theta)\n    tmpa = lib.einsum('mnie,me->ni', woOoV, r1)\n    tmp += lib.einsum('ni,njab->ijab', tmpa, t2)\n    tmp -= lib.einsum('af,ijfb->ijab', tmp1, t2)\n    tmp -= lib.einsum('mbij,ma->ijab', imds.woVoO, r1)\n\n    blksize = min(nvir, max(ccsd.BLKMIN, int(max_memory*1e6/8/(nocc*nvir**2*2))))\n    for p0,p1 in lib.prange(0, nvir, blksize):\n        tmp += lib.einsum('ejab,ie->ijab', np.asarray(imds.wvOvV[p0:p1]), r1[:,p0:p1])\n\n    Hr2aa += tmp\n    Hr2ab += tmp\n    tmp = woOoV = None\n\n    eris_ovov = np.asarray(eris.ovov)\n    tmpa = -lib.einsum('menf,imfe->ni', eris_ovov, theta)\n    Hr1 += lib.einsum('na,ni->ia', t1, tmpa)\n    tmp  = lib.einsum('mj,imab->ijab', tmpa, t2)\n    tmp1 = np.einsum('menf,mf->en', eris_ovov, r1)\n    tmpa = lib.einsum('en,nb->eb', tmp1, t1)\n    tmpa-= lib.einsum('menf,mnbf->eb', eris_ovov, theta)\n    tmp += lib.einsum('eb,ijae->ijab', tmpa, t2)\n    Hr2aa += tmp\n    Hr2ab -= tmp\n    tmp = theta = tmp1 = tmpa = None\n\n    tau2aa = np.einsum('ia,jb->ijab', r1, t1)\n    tau2aa-= np.einsum('ia,jb->jiab', r1, t1)\n    tau2aa = tau2aa - tau2aa.transpose(0,1,3,2)\n    tau2aa+= r2aa\n    tmpaa = lib.einsum('menf,ijef->mnij', eris_ovov, tau2aa)\n    tau2aa = None\n    tmpaa *= .25\n    tau = _make_tau(t2, t1, t1)\n    Hr2aa += lib.einsum('mnij,mnab->ijab', tmpaa, tau)\n    tmpaa = tau = None\n\n    tau2ab = np.einsum('ia,jb->ijab', r1, t1)\n    tau2ab-= np.einsum('ia,jb->ijab', t1, r1)\n    tau2ab+= r2ab\n    tmpab = lib.einsum('meNF,iJeF->mNiJ', eris_ovov, tau2ab)\n    tau2ab = None\n    tmpab *= .5\n    tau = _make_tau(t2, t1, t1)\n    Hr2ab += lib.einsum('mNiJ,mNaB->iJaB', tmpab, tau)\n    tmpab = tau = None\n    eris_ovov = None\n\n    Hr2aa = Hr2aa - Hr2aa.transpose(0,1,3,2)\n    Hr2aa = Hr2aa - Hr2aa.transpose(1,0,2,3)\n    Hr2ab = Hr2ab - Hr2ab.transpose(1,0,3,2)\n    vector = amplitudes_to_vector_triplet(Hr1, (Hr2aa,Hr2ab))\n    return vector\n\ndef eeccsd_matvec_sf(eom, vector, imds=None):\n    '''Spin flip EOM-CCSD'''\n    if imds is None: imds = eom.make_imds()\n    nocc = eom.nocc\n    nmo = eom.nmo\n    nvir = nmo - nocc\n\n    t1, t2, eris = imds.t1, imds.t2, imds.eris\n    r1, r2 = vector_to_amplitudes_eomsf(vector, nmo, nocc)\n    r2baaa, r2aaba = r2\n    nocc, nvir = t1.shape\n\n    Hr1  = np.einsum('ae,ie->ia', imds.Fvv, r1)\n    Hr1 -= np.einsum('mi,ma->ia', imds.Foo, r1)\n    Hr1 += np.einsum('me,imae->ia', imds.Fov, r2baaa)\n    Hr1 += np.einsum('me,imae->ia', imds.Fov, r2aaba)\n\n    tau2baaa = np.einsum('ia,jb->ijab', r1, t1)\n    tau2baaa += r2baaa * .5\n    tau2baaa = tau2baaa - tau2baaa.transpose(0,1,3,2)\n    tau2aaba = np.einsum('ia,jb->ijab', r1, t1)\n    tau2aaba += r2aaba * .5\n    tau2aaba = tau2aaba - tau2aaba.transpose(1,0,2,3)\n\n    #:eris_vvvv = ao2mo.restore(1,np.asarray(eris.vvvv), t1.shape[1])\n    #:Hr2baaa += .5*lib.einsum('ijef,aebf->ijab', tau2baaa, eris_vvvv)\n    #:Hr2aaba += .5*lib.einsum('ijef,aebf->ijab', tau2aaba, eris_vvvv)\n    Hr2aaba = eom._cc._add_vvvv(None, tau2aaba, eris, with_ovvv=False, t2sym='-jiab')\n    Hr2baaa = eom._cc._add_vvvv(None, tau2baaa, eris, with_ovvv=False, t2sym=False)\n\n    woOoO = np.asarray(imds.woOoO)\n    Hr2baaa += lib.einsum('mnij,mnab->ijab', woOoO, r2baaa)\n    Hr2aaba += lib.einsum('mnij,mnab->ijab', woOoO, r2aaba)\n    Hr2aaba *= .5\n    Hr2baaa *= .5\n    woOoO = None\n\n    Hr2baaa -= lib.einsum('mj,imab->ijab', imds.Foo*.5, r2baaa)\n    Hr2aaba -= lib.einsum('mj,imab->ijab', imds.Foo*.5, r2aaba)\n    Hr2baaa -= lib.einsum('mj,miab->jiab', imds.Foo*.5, r2baaa)\n    Hr2aaba -= lib.einsum('mj,miab->jiab', imds.Foo*.5, r2aaba)\n    Hr2baaa += lib.einsum('be,ijae->ijab', imds.Fvv*.5, r2baaa)\n    Hr2aaba += lib.einsum('be,ijae->ijab', imds.Fvv*.5, r2aaba)\n    Hr2baaa += lib.einsum('be,ijea->ijba', imds.Fvv*.5, r2baaa)\n    Hr2aaba += lib.einsum('be,ijea->ijba', imds.Fvv*.5, r2aaba)\n\n    mem_now = lib.current_memory()[0]\n    max_memory = max(0, eom.max_memory - mem_now - Hr2aaba.size*8e-6)\n    blksize = min(nocc, max(ccsd.BLKMIN, int(max_memory*1e6/8/(nvir**3*3))))\n    for p0,p1 in lib.prange(0, nocc, blksize):\n        ovvv = eris.get_ovvv(slice(p0,p1))  # ovvv = eris.ovvv[p0:p1]\n        theta = r2baaa[:,p0:p1] + r2aaba[:,p0:p1]\n        Hr1 += lib.einsum('mfae,imef->ia', ovvv, theta)\n        theta = None\n\n        tmp1aaba = lib.einsum('meaf,ijef->maij', ovvv, tau2baaa)\n        Hr2baaa -= lib.einsum('mb,maij->ijba', t1[p0:p1]*.5, tmp1aaba)\n        tmp1aaba = tmp1baaa = tmp1abaa = tmp2aaba = None\n\n        tmp2aaba = lib.einsum('meaf,ijfe->maij', ovvv, tau2baaa)\n        Hr2baaa -= lib.einsum('mb,maij->ijab', t1[p0:p1]*.5, tmp2aaba)\n        tmp1aaba = tmp1baaa = tmp1abaa = tmp2aaba = None\n\n        tmp1baaa = lib.einsum('meaf,ijef->maij', ovvv, tau2aaba)\n        Hr2aaba -= lib.einsum('mb,maij->ijba', t1[p0:p1]*.5, tmp1baaa)\n        tmp1aaba = tmp1baaa = tmp1abaa = tmp2aaba = None\n\n        tmp1abaa = lib.einsum('meaf,ijfe->maij', ovvv, tau2aaba)\n        Hr2aaba -= lib.einsum('mb,maij->ijab', t1[p0:p1]*.5, tmp1abaa)\n        tmp1aaba = tmp1baaa = tmp1abaa = tmp2aaba = None\n\n        tmp = lib.einsum('mfae,me->af', ovvv, r1[p0:p1])\n        tmp = lib.einsum('af,jibf->ijab', tmp, t2)\n        Hr2baaa -= tmp\n        Hr2aaba -= tmp\n        tmp = ovvv = None\n    tau2aaba = tau2baaa = None\n\n    tmp = lib.einsum('mbij,ma->ijab', imds.woVoO, r1)\n    Hr2baaa -= tmp\n    Hr2aaba -= tmp\n    tmp = None\n\n    woOoV = np.asarray(imds.woOoV)\n    Hr1 -= lib.einsum('mnie,mnae->ia', woOoV, r2aaba)\n    Hr1 -= lib.einsum('mnie,mnae->ia', woOoV, r2baaa)\n    tmp = lib.einsum('mnie,me->ni', woOoV, r1)\n    tmp = lib.einsum('ni,njab->ijab', tmp, t2)\n    Hr2baaa += tmp\n    Hr2aaba += tmp\n    tmp = woOoV = None\n\n    for p0,p1 in lib.prange(0, nvir, nocc):\n        tmp = lib.einsum('ejab,ie->ijab', np.asarray(imds.wvOvV[p0:p1]), r1[:,p0:p1])\n        Hr2baaa += tmp\n        Hr2aaba += tmp\n        tmp = None\n\n    woVVo = np.asarray(imds.woVVo)\n    Hr1 += np.einsum('maei,me->ia', woVVo, r1)\n    Hr2baaa += lib.einsum('mbej,miea->jiba', woVVo, r2baaa)\n    Hr2aaba += lib.einsum('mbej,miea->jiba', woVVo, r2aaba)\n    woVVo = None\n    woVvO = np.asarray(imds.woVvO)\n    Hr2baaa += lib.einsum('mbej,imae->ijab', woVvO, r2aaba)\n    Hr2aaba += lib.einsum('mbej,imae->ijab', woVvO, r2baaa)\n    woVvO = woVvO + np.asarray(imds.woVVo)\n    Hr2baaa += lib.einsum('mbej,imae->ijab', woVvO, r2baaa)\n    Hr2aaba += lib.einsum('mbej,imae->ijab', woVvO, r2aaba)\n    woVvO = None\n\n    eris_ovov = np.asarray(eris.ovov)\n    theta = r2aaba + r2baaa\n    tmp = lib.einsum('nfme,imfe->ni', eris_ovov, theta)\n    Hr1 -= np.einsum('na,ni->ia', t1, tmp)\n    Hr2baaa -= lib.einsum('mj,imba->jiab', tmp, t2)\n    Hr2aaba -= lib.einsum('mj,imba->jiab', tmp, t2)\n\n    tmp = np.einsum('menf,mf->en', eris_ovov, r1)\n    tmp = np.einsum('en,nb->eb', tmp, t1)\n    tmp-= lib.einsum('menf,mnbf->eb', eris_ovov, theta)\n    Hr2baaa += lib.einsum('ea,ijbe->jiab', tmp, t2)\n    Hr2aaba += lib.einsum('ea,ijbe->jiab', tmp, t2)\n    theta = tmp = None\n\n    tau2baaa = np.einsum('ia,jb->ijab', r1, t1)\n    tau2baaa += r2baaa * .5\n    tau2baaa = tau2baaa - tau2baaa.transpose(0,1,3,2)\n    tau = _make_tau(t2, t1, t1)\n    tmp1aaba = lib.einsum('menf,ijef->mnij', eris_ovov, tau2baaa)\n    tau2baaa = None\n    Hr2baaa += .5*lib.einsum('mnij,mnab->ijab', tmp1aaba, tau)\n    tau = tmp1aaba = None\n\n    tau2aaba = np.einsum('ia,jb->ijab', r1, t1)\n    tau2aaba += r2aaba * .5\n    tau2aaba = tau2aaba - tau2aaba.transpose(1,0,2,3)\n    tau = _make_tau(t2, t1, t1)\n    tmp1baaa = lib.einsum('menf,ijef->mnij', eris_ovov, tau2aaba)\n    tau2aaba = None\n    Hr2aaba += .5*lib.einsum('mnij,mnab->ijab', tmp1baaa, tau)\n    tau = tmp1baaa = None\n    eris_ovov = None\n\n    Hr2baaa = Hr2baaa - Hr2baaa.transpose(0,1,3,2)\n    Hr2aaba = Hr2aaba - Hr2aaba.transpose(1,0,2,3)\n    vector = amplitudes_to_vector_eomsf(Hr1, (Hr2baaa,Hr2aaba))\n    return vector\n\ndef eeccsd_diag(eom, imds=None):\n    if imds is None: imds = eom.make_imds()\n    eris = imds.eris\n    t1, t2 = imds.t1, imds.t2\n    dtype = np.result_type(t1, t2)\n    tau = _make_tau(t2, t1, t1)\n    nocc, nvir = t1.shape\n\n    Fo = imds.Foo.diagonal()\n    Fv = imds.Fvv.diagonal()\n    Wovab = np.einsum('iaai->ia', imds.woVVo)\n    Wovaa = Wovab + np.einsum('iaai->ia', imds.woVvO)\n\n    eia = lib.direct_sum('-i+a->ia', Fo, Fv)\n    Hr1aa = eia + Wovaa\n    Hr1ab = eia + Wovab\n\n    eris_ovov = np.asarray(eris.ovov)\n    Wvvab = np.einsum('mnab,manb->ab', tau, eris_ovov)\n    Wvvaa = .5*Wvvab - .5*np.einsum('mnba,manb->ab', tau, eris_ovov)\n    ijb = np.einsum('iejb,ijeb->ijb', eris_ovov, t2)\n    Hr2ab = lib.direct_sum('iJB+a->iJaB',-ijb, Fv)\n    jab = np.einsum('kajb,kjab->jab', eris_ovov, t2)\n    Hr2ab+= lib.direct_sum('-i-jab->ijab', Fo, jab)\n\n    jib = np.einsum('iejb,ijbe->jib', eris_ovov, t2)\n    jib = jib + jib.transpose(1,0,2)\n    jib-= ijb + ijb.transpose(1,0,2)\n    jba = np.einsum('kajb,jkab->jba', eris_ovov, t2)\n    jba = jba + jba.transpose(0,2,1)\n    jba-= jab + jab.transpose(0,2,1)\n    Hr2aa = lib.direct_sum('jib+a->jiba', jib, Fv)\n    Hr2aa+= lib.direct_sum('-i+jba->ijba', Fo, jba)\n    eris_ovov = None\n\n    Hr2baaa = lib.direct_sum('ijb+a->ijba',-ijb, Fv)\n    Hr2baaa += Wovaa.reshape(1,nocc,1,nvir)\n    Hr2baaa += Wovab.reshape(nocc,1,1,nvir)\n    Hr2baaa = Hr2baaa + Hr2baaa.transpose(0,1,3,2)\n    Hr2baaa+= lib.direct_sum('-i+jab->ijab', Fo, jba)\n    Hr2baaa-= Fo.reshape(1,-1,1,1)\n    Hr2aaba = lib.direct_sum('-i-jab->ijab', Fo, jab)\n    Hr2aaba += Wovaa.reshape(1,nocc,1,nvir)\n    Hr2aaba += Wovab.reshape(1,nocc,nvir,1)\n    Hr2aaba = Hr2aaba + Hr2aaba.transpose(1,0,2,3)\n    Hr2aaba+= lib.direct_sum('ijb+a->ijab', jib, Fv)\n    Hr2aaba+= Fv.reshape(1,1,1,-1)\n    Hr2ab += Wovaa.reshape(1,nocc,1,nvir)\n    Hr2ab += Wovab.reshape(nocc,1,1,nvir)\n    Hr2ab = Hr2ab + Hr2ab.transpose(1,0,3,2)\n    Hr2aa += Wovaa.reshape(1,nocc,1,nvir) * 2\n    Hr2aa = Hr2aa + Hr2aa.transpose(0,1,3,2)\n    Hr2aa = Hr2aa + Hr2aa.transpose(1,0,2,3)\n    Hr2aa *= .5\n\n    Wooab = np.einsum('ijij->ij', imds.woOoO)\n    Wooaa = Wooab - np.einsum('ijji->ij', imds.woOoO)\n    Hr2aa += Wooaa.reshape(nocc,nocc,1,1)\n    Hr2ab += Wooab.reshape(nocc,nocc,1,1)\n    Hr2baaa += Wooab.reshape(nocc,nocc,1,1)\n    Hr2aaba += Wooaa.reshape(nocc,nocc,1,1)\n\n    #:eris_ovvv = lib.unpack_tril(np.asarray(eris.ovvv).reshape(nocc*nvir,nvir**2)).reshape(nocc,nvir,nvir,nvir)\n    #:tmp = np.einsum('mb,mbaa->ab', t1, eris_ovvv)\n    #:Wvvaa += np.einsum('mb,maab->ab', t1, eris_ovvv)\n    mem_now = lib.current_memory()[0]\n    max_memory = max(0, eom.max_memory - mem_now)\n    blksize = min(nocc, max(ccsd.BLKMIN, int(max_memory*1e6/8/(nvir**3*3))))\n    tmp = np.zeros((nvir,nvir), dtype=dtype)\n    for p0,p1 in lib.prange(0, nocc, blksize):\n        ovvv = eris.get_ovvv(slice(p0,p1))  # ovvv = eris.ovvv[p0:p1]\n        tmp += np.einsum('mb,mbaa->ab', t1[p0:p1], ovvv)\n        Wvvaa += np.einsum('mb,maab->ab', t1[p0:p1], ovvv)\n        ovvv = None\n    Wvvaa -= tmp\n    Wvvab -= tmp\n    Wvvab -= tmp.T\n    Wvvaa = Wvvaa + Wvvaa.T\n    if eris.vvvv is None: # AO-direct CCSD, vvvv is not generated.\n        pass\n    elif eris.vvvv.ndim == 4:\n        eris_vvvv = ao2mo.restore(1,np.asarray(eris.vvvv), t1.shape[1])\n        tmp = np.einsum('aabb->ab', eris_vvvv)\n        Wvvaa += tmp\n        Wvvaa -= np.einsum('abba->ab', eris_vvvv)\n        Wvvab += tmp\n    else:\n        for i in range(nvir):\n            i0 = i*(i+1)//2\n            vvv = lib.unpack_tril(np.asarray(eris.vvvv[i0:i0+i+1]))\n            tmp = np.einsum('bb->b', vvv[i])\n            Wvvaa[i] += tmp\n            Wvvab[i] += tmp\n            tmp = np.einsum('bb->b', vvv[:,:i+1,i])\n            Wvvaa[i,:i+1] -= tmp\n            Wvvaa[:i  ,i] -= tmp[:i]\n            vvv = None\n\n    Hr2aa += Wvvaa.reshape(1,1,nvir,nvir)\n    Hr2ab += Wvvab.reshape(1,1,nvir,nvir)\n    Hr2baaa += Wvvaa.reshape(1,1,nvir,nvir)\n    Hr2aaba += Wvvab.reshape(1,1,nvir,nvir)\n\n    vec_eeS = amplitudes_to_vector_singlet(Hr1aa, Hr2ab)\n    vec_eeT = amplitudes_to_vector_triplet(Hr1aa, (Hr2aa,Hr2ab))\n    vec_sf = amplitudes_to_vector_eomsf(Hr1ab, (Hr2baaa,Hr2aaba))\n    return vec_eeS, vec_eeT, vec_sf\n\n\nclass EOMEE(EOM):\n    def get_init_guess(self, nroots=1, koopmans=True, diag=None):\n        if koopmans:\n            nocc = self.nocc\n            nvir = self.nmo - nocc\n            idx = diag[:nocc*nvir].argsort()\n        else:\n            idx = diag.argsort()\n\n        size = self.vector_size()\n        dtype = getattr(diag, 'dtype', np.double)\n        nroots = min(nroots, size)\n        guess = []\n        for i in idx[:nroots]:\n            g = np.zeros(size, dtype)\n            g[i] = 1.0\n            guess.append(g)\n        return guess\n\n    kernel = eeccsd\n    eeccsd = eeccsd\n    get_diag = eeccsd_diag\n\n    def vector_size(self):\n        '''size of the vector based on spin-orbital basis'''\n        nocc = self.nocc\n        nvir = self.nmo - nocc\n        return nocc*nvir + nocc*nocc*nvir*nvir\n\n    def make_imds(self, eris=None):\n        imds = _IMDS(self._cc, eris=eris)\n        imds.make_ee()\n        return imds\n\n    @property\n    def eee(self):\n        return self.e\n\n\nclass EOMEESinglet(EOMEE):\n    kernel = eomee_ccsd_singlet\n    eomee_ccsd_singlet = eomee_ccsd_singlet\n    matvec = eeccsd_matvec_singlet\n\n    def gen_matvec(self, imds=None, diag=None, **kwargs):\n        if imds is None: imds = self.make_imds()\n        if diag is None: diag = self.get_diag(imds)[0]\n        matvec = lambda xs: [self.matvec(x, imds) for x in xs]\n        return matvec, diag\n\n    def vector_to_amplitudes(self, vector, nmo=None, nocc=None):\n        if nmo is None: nmo = self.nmo\n        if nocc is None: nocc = self.nocc\n        return vector_to_amplitudes_singlet(vector, nmo, nocc)\n\n    def amplitudes_to_vector(self, r1, r2):\n        return amplitudes_to_vector_singlet(r1, r2)\n\n    def vector_size(self):\n        nocc = self.nocc\n        nvir = self.nmo - nocc\n        nov = nocc * nvir\n        return nov + nov*(nov+1)//2\n\n\nclass EOMEETriplet(EOMEE):\n    kernel = eomee_ccsd_triplet\n    eomee_ccsd_triplet = eomee_ccsd_triplet\n    matvec = eeccsd_matvec_triplet\n\n    def gen_matvec(self, imds=None, diag=None, **kwargs):\n        if imds is None: imds = self.make_imds()\n        if diag is None: diag = self.get_diag(imds)[1]\n        matvec = lambda xs: [self.matvec(x, imds) for x in xs]\n        return matvec, diag\n\n    def vector_to_amplitudes(self, vector, nmo=None, nocc=None):\n        if nmo is None: nmo = self.nmo\n        if nocc is None: nocc = self.nocc\n        return vector_to_amplitudes_triplet(vector, nmo, nocc)\n\n    def amplitudes_to_vector(self, r1, r2):\n        return amplitudes_to_vector_triplet(r1, r2)\n\n    def vector_size(self):\n        nocc = self.nocc\n        nvir = self.nmo - nocc\n        nov = nocc * nvir\n        return nov + nocc*(nocc-1)//2*nvir*(nvir-1)//2 + nov*(nov+1)//2\n\n\nclass EOMEESpinFlip(EOMEE):\n    kernel = eomsf_ccsd\n    eomsf_ccsd = eomsf_ccsd\n    matvec = eeccsd_matvec_sf\n\n    def gen_matvec(self, imds=None, diag=None, **kwargs):\n        if imds is None: imds = self.make_imds()\n        if diag is None: diag = self.get_diag(imds)[2]\n        matvec = lambda xs: [self.matvec(x, imds) for x in xs]\n        return matvec, diag\n\n    def vector_to_amplitudes(self, vector, nmo=None, nocc=None):\n        if nmo is None: nmo = self.nmo\n        if nocc is None: nocc = self.nocc\n        return vector_to_amplitudes_eomsf(vector, nmo, nocc)\n\n    def amplitudes_to_vector(self, r1, r2):\n        return amplitudes_to_vector_eomsf(r1, r2)\n\n    def vector_size(self):\n        nocc = self.nocc\n        nvir = self.nmo - nocc\n        nbaaa = nocc*nocc*nvir*(nvir-1)//2\n        naaba = nocc*(nocc-1)//2*nvir*nvir\n        return nocc*nvir + nbaaa + naaba\n\n#TODO: Check whether EOM methods works with rccsd.RCCSD when orbitals are complex\nccsd.CCSD.EOMIP         = lib.class_as_method(EOMIP)\nccsd.CCSD.EOMIP_Ta      = lib.class_as_method(EOMIP_Ta)\nccsd.CCSD.EOMEA         = lib.class_as_method(EOMEA)\nccsd.CCSD.EOMEA_Ta      = lib.class_as_method(EOMEA_Ta)\nccsd.CCSD.EOMEE         = lib.class_as_method(EOMEE)\nccsd.CCSD.EOMEESinglet  = lib.class_as_method(EOMEESinglet)\nccsd.CCSD.EOMEETriplet  = lib.class_as_method(EOMEETriplet)\nccsd.CCSD.EOMEESpinFlip = lib.class_as_method(EOMEESpinFlip)\n\n\nclass _IMDS:\n    def __init__(self, cc, eris=None):\n        self.verbose = cc.verbose\n        self.stdout = cc.stdout\n        self.max_memory = cc.max_memory\n        self.t1 = cc.t1\n        self.t2 = cc.t2\n        if eris is None:\n            eris = cc.ao2mo()\n        self.eris = eris\n        self._made_shared_2e = False\n\n    def _make_shared_1e(self):\n        cput0 = (logger.process_clock(), logger.perf_counter())\n\n        t1, t2, eris = self.t1, self.t2, self.eris\n        self.Loo = imd.Loo(t1, t2, eris)\n        self.Lvv = imd.Lvv(t1, t2, eris)\n        self.Fov = imd.cc_Fov(t1, t2, eris)\n\n        logger.timer_debug1(self, 'EOM-CCSD shared one-electron '\n                            'intermediates', *cput0)\n        return self\n\n    def _make_shared_2e(self):\n        cput0 = (logger.process_clock(), logger.perf_counter())\n        log = logger.Logger(self.stdout, self.verbose)\n\n        t1, t2, eris = self.t1, self.t2, self.eris\n        # 2 virtuals\n        self.Wovov = imd.Wovov(t1, t2, eris)\n        self.Wovvo = imd.Wovvo(t1, t2, eris)\n        self.Woovv = np.asarray(eris.ovov).transpose(0,2,1,3)\n\n        self._made_shared_2e = True\n        log.timer_debug1('EOM-CCSD shared two-electron intermediates', *cput0)\n        return self\n\n    def make_ip(self, ip_partition=None):\n        self._make_shared_1e()\n        if not self._made_shared_2e and ip_partition != 'mp':\n            self._make_shared_2e()\n\n        cput0 = (logger.process_clock(), logger.perf_counter())\n        log = logger.Logger(self.stdout, self.verbose)\n\n        t1, t2, eris = self.t1, self.t2, self.eris\n\n        # 0 or 1 virtuals\n        if ip_partition != 'mp':\n            self.Woooo = imd.Woooo(t1, t2, eris)\n        self.Wooov = imd.Wooov(t1, t2, eris)\n        self.Wovoo = imd.Wovoo(t1, t2, eris)\n        log.timer_debug1('EOM-CCSD IP intermediates', *cput0)\n        return self\n\n    def make_t3p2_ip(self, cc, ip_partition=None):\n        assert(ip_partition is None)\n        cput0 = (logger.process_clock(), logger.perf_counter())\n\n        t1, t2, eris = cc.t1, cc.t2, self.eris\n        delta_E_corr, pt1, pt2, Wovoo, Wvvvo = \\\n            imd.get_t3p2_imds_slow(cc, t1, t2, eris)\n        self.t1 = pt1\n        self.t2 = pt2\n\n        self._made_shared_2e = False  # Force update\n        self.make_ip()  # Make after t1/t2 updated\n        self.Wovoo = self.Wovoo + Wovoo\n\n        logger.timer_debug1(self, 'EOM-CCSD(T)a IP intermediates', *cput0)\n        return self\n\n\n    def make_ea(self, ea_partition=None):\n        self._make_shared_1e()\n        if not self._made_shared_2e and ea_partition != 'mp':\n            self._make_shared_2e()\n\n        cput0 = (logger.process_clock(), logger.perf_counter())\n        log = logger.Logger(self.stdout, self.verbose)\n\n        t1, t2, eris = self.t1, self.t2, self.eris\n\n        # 3 or 4 virtuals\n        self.Wvovv = imd.Wvovv(t1, t2, eris)\n        if ea_partition == 'mp':\n            self.Wvvvo = imd.Wvvvo(t1, t2, eris)\n        else:\n            self.Wvvvv = imd.Wvvvv(t1, t2, eris)\n            self.Wvvvo = imd.Wvvvo(t1, t2, eris, self.Wvvvv)\n        log.timer_debug1('EOM-CCSD EA intermediates', *cput0)\n        return self\n\n    def make_t3p2_ea(self, cc, ea_partition=None):\n        assert(ea_partition is None)\n        cput0 = (logger.process_clock(), logger.perf_counter())\n\n        t1, t2, eris = cc.t1, cc.t2, self.eris\n        delta_E_corr, pt1, pt2, Wovoo, Wvvvo = \\\n            imd.get_t3p2_imds_slow(cc, t1, t2, eris)\n        self.t1 = pt1\n        self.t2 = pt2\n\n        self._made_shared_2e = False  # Force update\n        self.make_ea()  # Make after t1/t2 updated\n        self.Wvvvo = self.Wvvvo + Wvvvo\n\n        logger.timer_debug1(self, 'EOM-CCSD(T)a EA intermediates', *cput0)\n        return self\n\n\n    def make_ee(self):\n        cput0 = (logger.process_clock(), logger.perf_counter())\n        log = logger.Logger(self.stdout, self.verbose)\n\n        t1, t2, eris = self.t1, self.t2, self.eris\n        dtype = np.result_type(t1, t2)\n        if np.iscomplexobj(t2):\n            raise NotImplementedError('Complex integrals are not supported in EOM-EE-CCSD')\n\n        nocc, nvir = t1.shape\n\n        fswap = lib.H5TmpFile()\n        self.saved = lib.H5TmpFile()\n        self.wvOvV = self.saved.create_dataset('wvOvV', (nvir,nocc,nvir,nvir), dtype.char)\n        self.woVvO = self.saved.create_dataset('woVvO', (nocc,nvir,nvir,nocc), dtype.char)\n        self.woVVo = self.saved.create_dataset('woVVo', (nocc,nvir,nvir,nocc), dtype.char)\n        self.woOoV = self.saved.create_dataset('woOoV', (nocc,nocc,nocc,nvir), dtype.char)\n\n        foo = eris.fock[:nocc,:nocc]\n        fov = eris.fock[:nocc,nocc:]\n        fvv = eris.fock[nocc:,nocc:]\n\n        self.Fov = np.zeros((nocc,nvir), dtype=dtype)\n        self.Foo = np.zeros((nocc,nocc), dtype=dtype)\n        self.Fvv = np.zeros((nvir,nvir), dtype=dtype)\n\n        #:eris_ovvv = lib.unpack_tril(np.asarray(eris.ovvv).reshape(nocc*nvir,nvir**2)).reshape(nocc,nvir,nvir,nvir)\n        #:self.Fvv  = np.einsum('mf,mfae->ae', t1, eris_ovvv) * 2\n        #:self.Fvv -= np.einsum('mf,meaf->ae', t1, eris_ovvv)\n        #:self.woVvO = lib.einsum('jf,mebf->mbej', t1, eris_ovvv)\n        #:self.woVVo = lib.einsum('jf,mfbe->mbej',-t1, eris_ovvv)\n        #:tau = _make_tau(t2, t1, t1)\n        #:self.woVoO  = 0.5 * lib.einsum('mebf,ijef->mbij', eris_ovvv, tau)\n        #:self.woVoO += 0.5 * lib.einsum('mfbe,ijfe->mbij', eris_ovvv, tau)\n        eris_ovoo = np.asarray(eris.ovoo)\n        woVoO = np.empty((nocc,nvir,nocc,nocc), dtype=dtype)\n        tau = _make_tau(t2, t1, t1)\n        theta = t2*2 - t2.transpose(0,1,3,2)\n\n        mem_now = lib.current_memory()[0]\n        max_memory = max(0, self.max_memory - mem_now)\n        blksize = min(nocc, max(ccsd.BLKMIN, int(max_memory*1e6/8/(nvir**3*3))))\n        for seg, (p0,p1) in enumerate(lib.prange(0, nocc, blksize)):\n            ovvv = eris.get_ovvv(slice(p0,p1))  # ovvv = eris.ovvv[p0:p1]\n            # transform integrals (ia|bc) -> (ac|ib)\n            fswap['ebmf/%d'%seg] = np.einsum('mebf->ebmf', ovvv)\n\n            self.Fvv += np.einsum('mf,mfae->ae', t1[p0:p1], ovvv) * 2\n            self.Fvv -= np.einsum('mf,meaf->ae', t1[p0:p1], ovvv)\n            woVoO[p0:p1] = lib.einsum('mebf,ijef->mbij', ovvv, tau)\n            woVvO = lib.einsum('jf,mebf->mbej', t1, ovvv)\n            woVVo = lib.einsum('jf,mfbe->mbej',-t1, ovvv)\n            ovvv = None\n\n            eris_ovov = np.asarray(eris.ovov[p0:p1])\n            woOoV = lib.einsum('if,mfne->mnie', t1, eris_ovov)\n            woOoV+= eris_ovoo[:,:,p0:p1].transpose(2,0,3,1)\n            self.woOoV[p0:p1] = woOoV\n            woOoV = None\n\n            tmp = lib.einsum('njbf,mfne->mbej', t2, eris_ovov)\n            woVvO -= tmp * .5\n            woVVo += tmp\n\n            ovoo = lib.einsum('menf,jf->menj', eris_ovov, t1)\n            woVvO -= lib.einsum('nb,menj->mbej', t1, ovoo)\n            ovoo = lib.einsum('mfne,jf->menj', eris_ovov, t1)\n            woVVo += lib.einsum('nb,menj->mbej', t1, ovoo)\n            ovoo = None\n\n            ovov = eris_ovov * 2 - eris_ovov.transpose(0,3,2,1)\n            woVvO += lib.einsum('njfb,menf->mbej', theta, ovov) * .5\n\n            self.Fov[p0:p1] = np.einsum('nf,menf->me', t1, ovov)\n            tilab = np.einsum('ia,jb->ijab', t1[p0:p1], t1) * .5\n            tilab += t2[p0:p1]\n            self.Foo += lib.einsum('mief,menf->ni', tilab, ovov)\n            self.Fvv -= lib.einsum('mnaf,menf->ae', tilab, ovov)\n            eris_ovov = ovov = tilab = None\n\n            woVvO -= lib.einsum('nb,menj->mbej', t1, eris_ovoo[p0:p1,:,:])\n            woVVo += lib.einsum('nb,nemj->mbej', t1, eris_ovoo[:,:,p0:p1])\n\n            woVvO += np.asarray(eris.ovvo[p0:p1]).transpose(0,2,1,3)\n            woVVo -= np.asarray(eris.oovv[p0:p1]).transpose(0,2,3,1)\n\n            self.woVvO[p0:p1] = woVvO\n            self.woVVo[p0:p1] = woVVo\n\n        self.Foo += foo + 0.5*np.einsum('me,ie->mi', self.Fov+fov, t1)\n        self.Fvv += fvv - 0.5*np.einsum('me,ma->ae', self.Fov+fov, t1)\n\n        # 0 or 1 virtuals\n        woOoO = lib.einsum('je,nemi->mnij', t1, eris_ovoo)\n        woOoO = woOoO + woOoO.transpose(1,0,3,2)\n        woOoO += np.asarray(eris.oooo).transpose(0,2,1,3)\n\n        tmp = lib.einsum('meni,jneb->mbji', eris_ovoo, t2)\n        woVoO -= tmp.transpose(0,1,3,2) * .5\n        woVoO -= tmp\n        tmp = None\n        ovoo = eris_ovoo*2 - eris_ovoo.transpose(2,1,0,3)\n        woVoO += lib.einsum('nemi,njeb->mbij', ovoo, theta) * .5\n        self.Foo += np.einsum('ne,nemi->mi', t1, ovoo)\n        ovoo = None\n\n        eris_ovov = np.asarray(eris.ovov)\n        woOoO += lib.einsum('ijef,menf->mnij', tau, eris_ovov)\n        self.woOoO = self.saved['woOoO'] = woOoO\n        woVoO -= lib.einsum('nb,mnij->mbij', t1, woOoO)\n        woOoO = None\n\n        tmpoovv = lib.einsum('njbf,nemf->ejmb', t2, eris_ovov)\n        ovov = eris_ovov*2 - eris_ovov.transpose(0,3,2,1)\n        eris_ovov = None\n\n        tmpovvo = lib.einsum('nifb,menf->eimb', theta, ovov)\n        ovov = None\n\n        tmpovvo *= -.5\n        tmpovvo += tmpoovv * .5\n        woVoO -= lib.einsum('ie,ejmb->mbij', t1, tmpovvo)\n        woVoO -= lib.einsum('ie,ejmb->mbji', t1, tmpoovv)\n        woVoO += eris_ovoo.transpose(3,1,2,0)\n\n        # 3 or 4 virtuals\n        eris_ovvo = np.asarray(eris.ovvo)\n        tmpovvo -= eris_ovvo.transpose(1,3,0,2)\n        fswap['ovvo'] = tmpovvo\n        tmpovvo = None\n\n        eris_oovv = np.asarray(eris.oovv)\n        tmpoovv -= eris_oovv.transpose(3,1,0,2)\n        fswap['oovv'] = tmpoovv\n        tmpoovv = None\n\n        woVoO += lib.einsum('mebj,ie->mbij', eris_ovvo, t1)\n        woVoO += lib.einsum('mjbe,ie->mbji', eris_oovv, t1)\n        woVoO += lib.einsum('me,ijeb->mbij', self.Fov, t2)\n        self.woVoO = self.saved['woVoO'] = woVoO\n        woVoO = eris_ovvo = eris_oovv = None\n\n        #:theta = t2*2 - t2.transpose(0,1,3,2)\n        #:eris_ovvv = lib.unpack_tril(np.asarray(eris.ovvv).reshape(nocc*nvir,nvir**2)).reshape(nocc,nvir,nvir,nvir)\n        #:ovvv = eris_ovvv*2 - eris_ovvv.transpose(0,3,2,1)\n        #:tmpab = lib.einsum('mebf,miaf->eiab', eris_ovvv, t2)\n        #:tmpab = tmpab + tmpab.transpose(0,1,3,2) * .5\n        #:tmpab-= lib.einsum('mfbe,mifa->eiba', ovvv, theta) * .5\n        #:self.wvOvV += eris_ovvv.transpose(2,0,3,1).conj()\n        #:self.wvOvV -= tmpab\n        nsegs = len(fswap['ebmf'])\n        def load_ebmf(slice):\n            dat = [fswap['ebmf/%d'%i][slice] for i in range(nsegs)]\n            return np.concatenate(dat, axis=2)\n\n        mem_now = lib.current_memory()[0]\n        max_memory = max(0, self.max_memory - mem_now)\n        blksize = min(nocc, max(ccsd.BLKMIN, int(max_memory*1e6/8/(nocc*nvir**2*4))))\n        for p0, p1 in lib.prange(0, nvir, blksize):\n            #:wvOvV  = lib.einsum('mebf,miaf->eiab', ovvv, t2)\n            #:wvOvV += lib.einsum('mfbe,miaf->eiba', ovvv, t2)\n            #:wvOvV -= lib.einsum('mfbe,mifa->eiba', ovvv, t2)*2\n            #:wvOvV += lib.einsum('mebf,mifa->eiba', ovvv, t2)\n\n            ebmf = load_ebmf(slice(p0, p1))\n            wvOvV = lib.einsum('ebmf,miaf->eiab', ebmf, t2)\n            wvOvV = -.5 * wvOvV.transpose(0,1,3,2) - wvOvV\n\n            # Using the permutation symmetry (em|fb) = (em|bf)\n            efmb = load_ebmf((slice(None), slice(p0, p1)))\n            wvOvV += np.einsum('ebmf->bmfe', efmb.conj())\n\n            # tmp = (mf|be) - (me|bf)*.5\n            tmp = -.5 * ebmf\n            tmp += efmb.transpose(1,0,2,3)\n            ebmf = None\n            wvOvV += lib.einsum('efmb,mifa->eiba', tmp, theta)\n            tmp = None\n\n            wvOvV += lib.einsum('meni,mnab->eiab', eris_ovoo[:,p0:p1], tau)\n            wvOvV -= lib.einsum('me,miab->eiab', self.Fov[:,p0:p1], t2)\n            wvOvV += lib.einsum('ma,eimb->eiab', t1, fswap['ovvo'][p0:p1])\n            wvOvV += lib.einsum('ma,eimb->eiba', t1, fswap['oovv'][p0:p1])\n\n            self.wvOvV[p0:p1] = wvOvV\n\n        self.made_ee_imds = True\n        log.timer('EOM-CCSD EE intermediates', *cput0)\n        return self\n\ndef _make_tau(t2, t1, r1, fac=1, out=None):\n    tau = np.einsum('ia,jb->ijab', t1, r1)\n    tau = tau + tau.transpose(1,0,3,2)\n    tau *= fac * .5\n    tau += t2\n    return tau\n\ndef _cp(a):\n    return np.array(a, copy=False, order='C')\n\n\nif __name__ == '__main__':\n    from pyscf import scf\n    from pyscf import gto\n    from pyscf.cc import rccsd\n\n    mol = gto.Mole()\n    mol.atom = [\n        [8 , (0. , 0.     , 0.)],\n        [1 , (0. , -0.757 , 0.587)],\n        [1 , (0. , 0.757  , 0.587)]]\n    mol.basis = 'cc-pvdz'\n    mol.verbose = 0\n    mol.spin = 0\n    mol.build()\n    mf = scf.RHF(mol).run(conv_tol=1e-14)\n\n    mycc = rccsd.RCCSD(mf)\n    ecc, t1, t2 = mycc.kernel()\n    print(ecc - -0.21334326214236796)\n\n    myeom = EOMIP(mycc)\n    print(\"IP energies... (right eigenvector)\")\n    e,v = ipccsd(myeom, nroots=3)\n    print(e[0] - 0.43356041409195489)\n    print(e[1] - 0.51876598058509493)\n    print(e[2] - 0.6782879569941862 )\n\n    print(\"IP energies... (left eigenvector)\")\n    le,lv = ipccsd(myeom, nroots=3,left=True)\n    print(le[0] - 0.43356040428879794)\n    print(le[1] - 0.51876597800180335)\n    print(le[2] - 0.67828755013874864)\n\n    e = myeom.ipccsd_star_contract(e, v, lv)\n    print(e[0] - 0.43793202073189047)\n    print(e[1] - 0.52287073446559729)\n    print(e[2] - 0.67994597948852287)\n\n    myeom = EOMEA(mycc)\n    print(\"EA energies... (right eigenvector)\")\n    e,v = eaccsd(myeom, nroots=3)\n    print(e[0] - 0.16737886282063008)\n    print(e[1] - 0.24027622989542635)\n    print(e[2] - 0.51006796667905585)\n\n    print(\"EA energies... (left eigenvector)\")\n    le,lv = eaccsd(myeom, nroots=3, left=True)\n    print(le[0] - 0.16737896537079733)\n    print(le[1] - 0.24027634198123343)\n    print(le[2] - 0.51006809015066612)\n\n    e = myeom.eaccsd_star_contract(e,v,lv)\n    print(e[0] - 0.16656250953550664)\n    print(e[1] - 0.23944144521387614)\n    print(e[2] - 0.41399436888830721)\n\n    myeom = EOMEESpinFlip(mycc)\n    np.random.seed(1)\n    v = np.random.random(myeom.vector_size())\n    r1, r2 = vector_to_amplitudes_eomsf(v, myeom.nmo, myeom.nocc)\n    print(lib.finger(r1)    - 0.017703197938757409)\n    print(lib.finger(r2[0]) --21.605764517401415)\n    print(lib.finger(r2[1]) - 6.5857056438834842)\n    print(abs(amplitudes_to_vector_eomsf(r1, r2) - v).max())\n\n    myeom = EOMEE(mycc)\n    e,v = myeom.eeccsd(nroots=1)\n    print(e - 0.2757159395886167)\n\n    e,v = myeom.eeccsd(nroots=4)\n    print(e[0] - 0.2757159395886167)\n    print(e[1] - 0.2757159395886167)\n    print(e[2] - 0.2757159395886167)\n    print(e[3] - 0.3005716731825082)\n\n    e,v = myeom.eeccsd(nroots=4, koopmans=True)\n    print(e[0] - 0.2757159395886167)\n    print(e[1] - 0.2757159395886167)\n    print(e[2] - 0.2757159395886167)\n    print(e[3] - 0.3005716731825082)\n\n    e,v = myeom.eeccsd(nroots=4, guess=v[:4])\n    print(e[0] - 0.2757159395886167)\n    print(e[1] - 0.2757159395886167)\n    print(e[2] - 0.2757159395886167)\n    print(e[3] - 0.3005716731825082)\n\n\n    mycc = ccsd.CCSD(mf)\n    ecc, t1, t2 = mycc.kernel()\n    print(ecc - -0.21334326214236796)\n\n    myeom = EOMIP(mycc)\n    print(\"IP energies... (right eigenvector)\")\n    e,v = ipccsd(myeom, nroots=3)\n    print(e[0] - 0.43356041409195489)\n    print(e[1] - 0.51876598058509493)\n    print(e[2] - 0.6782879569941862 )\n\n    print(\"IP energies... (left eigenvector)\")\n    le,lv = ipccsd(myeom, nroots=3,left=True)\n    print(le[0] - 0.43356040428879794)\n    print(le[1] - 0.51876597800180335)\n    print(le[2] - 0.67828755013874864)\n\n    e = myeom.ipccsd_star_contract(e, v, lv)\n    print(e[0] - 0.43793202073189047)\n    print(e[1] - 0.52287073446559729)\n    print(e[2] - 0.67994597948852287)\n\n    myeom = EOMEA(mycc)\n    print(\"EA energies... (right eigenvector)\")\n    e,v = eaccsd(myeom, nroots=3)\n    print(e[0] - 0.16737886282063008)\n    print(e[1] - 0.24027622989542635)\n    print(e[2] - 0.51006796667905585)\n\n    print(\"EA energies... (left eigenvector)\")\n    le,lv = eaccsd(myeom, nroots=3, left=True)\n    print(le[0] - 0.16737896537079733)\n    print(le[1] - 0.24027634198123343)\n    print(le[2] - 0.51006809015066612)\n\n    e = myeom.eaccsd_star_contract(e,v,lv)\n    print(e[0] - 0.16656250953550664)\n    print(e[1] - 0.23944144521387614)\n    print(e[2] - 0.41399436888830721)\n\n    myeom = EOMEE(mycc)\n    e,v = myeom.eeccsd(nroots=1)\n    print(e - 0.2757159395886167)\n\n    e,v = myeom.eeccsd(nroots=4)\n    print(e[0] - 0.2757159395886167)\n    print(e[1] - 0.2757159395886167)\n    print(e[2] - 0.2757159395886167)\n    print(e[3] - 0.3005716731825082)\n\n    e,v = myeom.eeccsd(nroots=4, koopmans=True)\n    print(e[0] - 0.2757159395886167)\n    print(e[1] - 0.2757159395886167)\n    print(e[2] - 0.2757159395886167)\n    print(e[3] - 0.3005716731825082)\n\n    e,v = myeom.eeccsd(nroots=4, guess=v[:4])\n    print(e[0] - 0.2757159395886167)\n    print(e[1] - 0.2757159395886167)\n    print(e[2] - 0.2757159395886167)\n    print(e[3] - 0.3005716731825082)\n", "meta": {"hexsha": "48e9b493f9b1b4cf9dabf6da422e040a92a41289", "size": 83813, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/cc/eom_rccsd.py", "max_stars_repo_name": "QuESt-Calculator/pyscf", "max_stars_repo_head_hexsha": "0ed03633b699505c7278f1eb501342667d0aa910", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 501, "max_stars_repo_stars_event_min_datetime": "2018-12-06T23:48:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:53:18.000Z", "max_issues_repo_path": "pyscf/cc/eom_rccsd.py", "max_issues_repo_name": "QuESt-Calculator/pyscf", "max_issues_repo_head_hexsha": "0ed03633b699505c7278f1eb501342667d0aa910", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 710, "max_issues_repo_issues_event_min_datetime": "2018-11-26T22:04:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:53:12.000Z", "max_forks_repo_path": "pyscf/cc/eom_rccsd.py", "max_forks_repo_name": "QuESt-Calculator/pyscf", "max_forks_repo_head_hexsha": "0ed03633b699505c7278f1eb501342667d0aa910", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 273, "max_forks_repo_forks_event_min_datetime": "2018-11-26T10:10:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:25:28.000Z", "avg_line_length": 38.1314831665, "max_line_length": 116, "alphanum_fraction": 0.588775011, "include": true, "reason": "import numpy", "num_tokens": 31175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.19797943954930294}}
{"text": "# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.\n#\n# This work is licensed under the Creative Commons Attribution-NonCommercial\n# 4.0 International License. To view a copy of this license, visit\n# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to\n# Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.\n\nimport numpy as np\nimport tensorflow as tf\n\nimport tfutil\n\n#----------------------------------------------------------------------------\n# Convenience func that casts all of its arguments to tf.float32.\n\ndef fp32(*values):\n    if len(values) == 1 and isinstance(values[0], tuple):\n        values = values[0]\n    values = tuple(tf.cast(v, tf.float32) for v in values)\n    return values if len(values) >= 2 else values[0]\n\n#----------------------------------------------------------------------------\n# Generator loss function used in the paper (WGAN + AC-GAN).\n\ndef G_wgan_acgan(G, D, opt, training_set, minibatch_size, unlabeled_reals,\n    cond_weight = 0.0): # Weight of the conditioning term.\n    '''\n    Calculating the feature matching loss for the generator\n    '''\n    # get generated samples\n    latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:])\n    # get random labels for the generated samples\n    rand_gen_labels = training_set.get_random_labels_tf(minibatch_size)\n    # use the generator to deconvolve the latents into images\n    fake_images_out = G.get_output_for(latents, rand_gen_labels, is_training=True)\n\n    # use the discriminator to get the features from the last convolution layer as well as the logits\n    fake_logits_out, _, fake_features_out = fp32(D.get_output_for(fake_images_out, is_training=False))\n    # Pass the unlabeled real data to the discriminator and grab the real features out from the last convolutional layer\n    _, _, real_features_out = fp32(D.get_output_for(unlabeled_reals, is_training=False))\n\n    # calculate feature-matching loss\n    # mean squared error of fake and real features\n    feat_diff = tf.math.reduce_mean(fake_features_out, axis=0) - tf.math.reduce_mean(real_features_out, axis=0)\n    loss = tf.math.reduce_mean(tf.math.square(feat_diff))\n\n    loss = tfutil.autosummary('Loss/G_feat_match_loss', loss)\n\n    # if D.output_shapes[1][1] > 0:\n    #     with tf.name_scope('LabelPenalty'):\n    #         # pass fake logits and labels to a softmax layer\n    #         label_penalty_fakes = tf.nn.softmax_cross_entropy_with_logits_v2(labels=rand_gen_labels, logits=fake_logits_out)\n    #     loss += label_penalty_fakes * cond_weight\n    # loss = tfutil.autosummary('Loss/G_feat_match_loss_post_LabelPenalty', loss)\n    return loss\n\n\ndef G_pggan_loss(G, D, opt, training_set, minibatch_size,\n    cond_weight = 1.0): # Weight of the conditioning term.\n\n    latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:])\n    labels = training_set.get_random_labels_tf(minibatch_size)\n    fake_images_out = G.get_output_for(latents, labels, is_training=True)\n    fake_labels_out, fake_scores_out, _ = fp32(D.get_output_for(fake_images_out, is_training=True))\n    loss = -fake_scores_out\n\n    return loss\n\n#----------------------------------------------------------------------------\n# Discriminator loss function used in the paper (WGAN-GP + AC-GAN).\n\ndef D_wgangp_acgan(G, D, opt, training_set, minibatch_size, reals, labels, unlabeled_reals,\n    wgan_lambda     = 0.0,      # Weight for the gradient penalty term.\n    wgan_epsilon    = 0.0,      # Weight for the epsilon term, \\epsilon_{drift}.\n    wgan_target     = 0.1,      # Target value for gradient magnitudes.\n    cond_weight     = 0.0):     # Weight of the conditioning terms.\n\n    # Generate latents and pass through the generator to decolvolve into fake images\n    latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:])\n    fake_images_out = G.get_output_for(latents, labels, is_training=True)\n\n    # REALS\n    output_before_softmax_lab, real_flogit_out, _ = fp32(D.get_output_for(reals, is_training=True))\n    # UNLABELED REALS\n    output_before_softmax_unl, _, _ = fp32(D.get_output_for(unlabeled_reals, is_training=True))\n    # GENERATED\n    output_before_softmax_fake, fake_flogit_out, _ = fp32(D.get_output_for(fake_images_out, is_training=True))\n\n    # Direct port labeled loss from Tim Salimans et al. https://arxiv.org/pdf/1606.03498.pdf\n    # no support for tensor indexing, so no work\n    #simple_labels = tf.argmax(labels, axis=1)\n    #z_exp_lab = tf.math.reduce_mean(tf.math.reduce_logsumexp(output_before_softmax_lab, axis=1))\n    #l_lab = output_before_softmax_lab[tf.range(minibatch_size), simple_labels]\n    #loss_lab = -tf.math.reduce_mean(l_lab) + tf.math.reduce_mean(z_exp_lab)\n\n    train_err = tf.math.reduce_mean(tf.cast(tf.math.not_equal(tf.math.argmax(output_before_softmax_lab, axis=1),\n                                                              tf.math.argmax(labels, axis=1)), tf.float32))\n    train_err = tfutil.autosummary('Loss/D_train_err', train_err)\n\n    # labeled sample loss is equivalent to cross entropy w/ softmax (I think?)\n    loss_lab = tf.math.reduce_sum(tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels, logits=output_before_softmax_lab))\n\n    # Another implementation of Salimans code ported to TF (NOT WORKING the tf.gather is wrong)\n    #l_lab = tf.gather(output_before_softmax_lab, tf.range(minibatch_size),labels)\n    #loss_lab = -tf.math.reduce_sum(l_lab) + tf.math.reduce_sum(tf.math.reduce_sum(tf.math.reduce_logsumexp(output_before_softmax_lab)))\n\n    # Direct port of unlabeled loss and fake loss. from Tim Salimans et al. https://arxiv.org/pdf/1606.03498.pdf\n    # Code reference https://github.com/openai/improved-gan/blob/master/mnist_svhn_cifar10/train_cifar_feature_matching.py#L87\n    #z_exp_unl = tf.math.reduce_mean(tf.math.reduce_logsumexp(output_before_softmax_unl, axis=1))\n    loss_unl = -0.5*tf.math.reduce_mean(tf.math.reduce_logsumexp(output_before_softmax_unl, axis=1)) + \\\n               0.5*tf.math.reduce_mean(tf.math.softplus(tf.math.reduce_logsumexp(output_before_softmax_unl, axis=1)))\n    loss_fake = 0.5*tf.math.reduce_mean(tf.math.softplus(tf.math.reduce_logsumexp(output_before_softmax_fake, axis=1)))\n\n    # Using autosummary for tensorboard\n    loss_lab = tfutil.autosummary('Loss/D_loss_lab', loss_lab)\n    loss_unl = tfutil.autosummary('Loss/D_loss_unl', loss_unl)\n    loss_fake = tfutil.autosummary('Loss/D_loss_fake', loss_fake)\n\n    # combine losses\n    loss = loss_lab + loss_unl + loss_fake + (train_err*0)\n\n    loss = tfutil.autosummary('Loss/D_combined_loss', loss)\n\n    # with tf.name_scope('GradientPenalty'):\n    #     mixing_factors = tf.random_uniform([minibatch_size, 1, 1, 1], 0.0, 1.0, dtype=fake_images_out.dtype)\n    #     mixed_images_out = tfutil.lerp(tf.cast(reals, fake_images_out.dtype), fake_images_out, mixing_factors)\n    #     mixed_scores_out, mixed_labels_out, _ = fp32(D.get_output_for(mixed_images_out, is_training=True))\n    #     mixed_scores_out = tfutil.autosummary('Loss/mixed_scores', mixed_scores_out)\n    #     mixed_loss = opt.apply_loss_scaling(tf.reduce_sum(mixed_scores_out))\n    #     mixed_grads = opt.undo_loss_scaling(fp32(tf.gradients(mixed_loss, [mixed_images_out])[0]))\n    #     mixed_norms = tf.sqrt(tf.reduce_sum(tf.square(mixed_grads), axis=[1,2,3]))\n    #     mixed_norms = tfutil.autosummary('Loss/mixed_norms', mixed_norms)\n    #     gradient_penalty = tf.square(mixed_norms - wgan_target)\n    # loss += gradient_penalty * (wgan_lambda / (wgan_target**2))\n\n    # with tf.name_scope('EpsilonPenalty'):\n    #     epsilon_penalty = tfutil.autosummary('Loss/epsilon_penalty', tf.square(real_flogit_out))\n    # loss += epsilon_penalty * wgan_epsilon\n\n    # if D.output_shapes[1][1] > 0:\n    #     with tf.name_scope('LabelPenalty'):\n    #         label_penalty_reals = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels, logits=output_before_softmax_lab)\n    #         label_penalty_fakes = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels, logits=output_before_softmax_fake)\n    #         label_penalty_reals = tfutil.autosummary('Loss/label_penalty_reals', label_penalty_reals)\n    #         label_penalty_fakes = tfutil.autosummary('Loss/label_penalty_fakes', label_penalty_fakes)\n    #     loss += (label_penalty_reals + label_penalty_fakes) * cond_weight\n\n    # loss = tfutil.autosummary('Loss/D_combined_loss_post_penalties', loss)\n    return loss\n\n\ndef D_pggan_loss(G, D, opt, training_set, minibatch_size, unlabeled_reals,\n    wgan_lambda     = 10.0,     # Weight for the gradient penalty term.\n    wgan_epsilon    = 0.001,    # Weight for the epsilon term, \\epsilon_{drift}.\n    wgan_target     = 1.0,      # Target value for gradient magnitudes.\n    cond_weight     = 1.0):     # Weight of the conditioning terms.\n\n    latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:])\n    labels = training_set.get_random_labels_tf(minibatch_size)\n    fake_images_out = G.get_output_for(latents, labels, is_training=True)\n    real_labels_out, real_scores_out, _ = fp32(D.get_output_for(unlabeled_reals, is_training=True))\n    fake_labels_out, fake_scores_out, _ = fp32(D.get_output_for(fake_images_out, is_training=True))\n    real_scores_out = tfutil.autosummary('Loss/D_pggan_real_scores', real_scores_out)\n    fake_scores_out = tfutil.autosummary('Loss/D_pggan_fake_scores', fake_scores_out)\n    loss = fake_scores_out - real_scores_out\n\n    with tf.name_scope('GradientPenalty'):\n        mixing_factors = tf.random_uniform([minibatch_size, 1, 1, 1], 0.0, 1.0, dtype=fake_images_out.dtype)\n        mixed_images_out = tfutil.lerp(tf.cast(unlabeled_reals, fake_images_out.dtype), fake_images_out, mixing_factors)\n        mixed_labels_out, mixed_scores_out, _ = fp32(D.get_output_for(mixed_images_out, is_training=True))\n        mixed_scores_out = tfutil.autosummary('Loss/D_pggan_mixed_scores', mixed_scores_out)\n        mixed_loss = opt.apply_loss_scaling(tf.reduce_sum(mixed_scores_out))\n        mixed_grads = opt.undo_loss_scaling(fp32(tf.gradients(mixed_loss, [mixed_images_out])[0]))\n        mixed_norms = tf.sqrt(tf.reduce_sum(tf.square(mixed_grads), axis=[1,2,3]))\n        mixed_norms = tfutil.autosummary('Loss/D_pggan_mixed_norms', mixed_norms)\n        gradient_penalty = tf.square(mixed_norms - wgan_target)\n    loss += gradient_penalty * (wgan_lambda / (wgan_target**2))\n\n    with tf.name_scope('EpsilonPenalty'):\n        epsilon_penalty = tfutil.autosummary('Loss/D_pggan_epsilon_penalty', tf.square(real_scores_out))\n    loss += epsilon_penalty * wgan_epsilon\n    return loss\n\n#----------------------------------------------------------------------------\n\n\n", "meta": {"hexsha": "f1be11ab85c110747b3af97d2b0f18fdd0bc8514", "size": 10631, "ext": "py", "lang": "Python", "max_stars_repo_path": "loss.py", "max_stars_repo_name": "ACK-J/SSL-PG-GAN", "max_stars_repo_head_hexsha": "95287db6dda3340acf2417a026c030fea506957e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "loss.py", "max_issues_repo_name": "ACK-J/SSL-PG-GAN", "max_issues_repo_head_hexsha": "95287db6dda3340acf2417a026c030fea506957e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "loss.py", "max_forks_repo_name": "ACK-J/SSL-PG-GAN", "max_forks_repo_head_hexsha": "95287db6dda3340acf2417a026c030fea506957e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-09T04:19:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-09T04:19:54.000Z", "avg_line_length": 56.8502673797, "max_line_length": 136, "alphanum_fraction": 0.7127269307, "include": true, "reason": "import numpy", "num_tokens": 2710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.34510526422232046, "lm_q1q2_score": 0.19797943335173293}}
{"text": "#! /usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\n    TO DO:\n    map to healpix grid\n\"\"\"\n\n\n__author__ = 'Alan Loh, Julien Girard'\n__copyright__ = 'Copyright 2019, nenupytv'\n__credits__ = ['Alan Loh', 'Julien Girard']\n__maintainer__ = 'Alan'\n__email__ = 'alan.loh@obspm.fr'\n__status__ = 'Production'\n__all__ = [\n    'Grid',\n    'Grid_Simple',\n    'Grid_HPX'\n    ]\n\n\n# import healpy as hp\nimport numpy as np\nimport astropy.units as un\n\nfrom nenupytv.image import AAFilter\n\n\n# ============================================================= #\n# ---------------------------- Grid --------------------------- #\n# ============================================================= #\nclass Grid(object):\n    \"\"\" Gridding class\n\n        :param vis: Visibilities\n        :type vis: `~np.ndarray`\n        :param uvw: UVW coordinates\n        :type uvw: `~np.ndarray`\n        :param fov: Field of view radius in degrees\n        :type fov: float\n        :param freq: Observing frequency\n        :type freq: float\n        :param filter: Convolution filter to apply\n        :type filter: `~nenupytv.image.AAFilter`\n        :param cellsize: Cell size in degrees\n        :type cellsize: float\n    \"\"\"\n\n    def __init__(\n        self,\n        vis,\n        uvw,\n        freq,\n        fov,\n        conv_filter=AAFilter(),\n        cellsize=None,\n        robust=0.\n        ):\n        self.nsize = None\n        self.fov = fov\n        self.vis = vis\n        self.uvw = uvw\n        self.freq = freq\n        self.filter = conv_filter\n        self.cellsize = cellsize\n        self.robust = robust\n\n\n    # --------------------------------------------------------- #\n    # --------------------- Getter/Setter --------------------- #\n    @property\n    def _ovsmpl(self):\n        \"\"\" Filter oversampling\n        \"\"\"\n        return self.filter.oversample\n\n\n    @property\n    def _hsup(self):\n        \"\"\" Filter Half_sup\n        \"\"\"\n        return self.filter.half_sup\n\n\n    @property\n    def _filter_idx(self):\n        \"\"\" Filter indices\n        \"\"\"\n        return np.arange(-self._hsup, self._hsup + 1)\n\n\n    @property\n    def _ftaps(self):\n        \"\"\"\n        \"\"\"\n        return self.filter.filter_taps\n\n\n    @property\n    def vis(self):\n        return self._vis\n    @vis.setter\n    def vis(self, v):\n        x, y = np.tril_indices(v.shape[0], 0)\n        xx = np.hstack((x[x!=y], y[x!=y]))\n        yy = np.hstack((y[x!=y], x[x!=y]))\n        self._vis = v[xx, yy, ...] + v[yy, xx, ...].conj()\n        return\n\n\n    @property\n    def uvw(self):\n        return self._uvw\n    @uvw.setter\n    def uvw(self, u):\n        x, y = np.tril_indices(u.shape[0], 0)\n        xx = np.hstack((x[x!=y], y[x!=y]))\n        yy = np.hstack((y[x!=y], x[x!=y]))\n        self._uvw = u[xx, yy, ...]\n\n        maxu = np.max(np.abs(self._uvw[..., 0]))\n        maxv = np.max(np.abs(self._uvw[..., 1]))\n        self.resol = 1. / (5 * 2 * np.max((maxu, maxv))) * un.rad\n        # self.resol = 1. / (10 * 2 * np.max((maxu, maxv))) * un.rad\n        resol = self.resol.to(un.deg).value\n        self.nsize = int(np.round(self.fov / resol))\n        return\n\n\n    @property\n    def nsize(self):\n        return self._nsize\n    @nsize.setter\n    def nsize(self, n):\n        if n is None:\n            self._nsize = None\n        else:\n            self._nsize = n\n            self.measurement = np.zeros(\n                (self.vis.shape[1], self.nsize, self.nsize),\n                dtype='complex64'\n            )\n            self._meas_w = np.zeros(\n                (self.nsize, self.nsize),\n                dtype='float'\n            )\n            # for deconvolution the PSF should be 2x size of the image (see \n            # Hogbom CLEAN for details), one grid for the sampling function:\n            self.sampling = np.zeros(\n                (2*self.nsize, 2*self.nsize),\n                dtype='complex64'\n            )\n            self._samp_w = np.zeros(\n                (2*self.nsize, 2*self.nsize),\n                dtype='float'\n            )\n\n\n    # --------------------------------------------------------- #\n    # ------------------------ Methods ------------------------ #\n    def populate(self):\n        \"\"\"\n        \"\"\"\n        # if self.uvw.shape[0] != 1:\n        #     raise ValueError(\n        #         'UVW need to be averaged in time'\n        #     )\n        # if self.uvw.shape[1] != 1:\n        #     raise ValueError(\n        #         'UVW need to be averaged in frequency'\n        #     )\n        # iter over number of baselines in the triangular inferior\n        # matrix (i.e. not autocorr), divided by 3 because (u, v, w)\n        for vis_bl in range(int(self.uvw.size / 3)):\n            u = self.uvw[vis_bl, 0] * np.radians(self.fov)\n            v = self.uvw[vis_bl, 1] * np.radians(self.fov)\n\n            if np.ma.is_masked(u) or np.ma.is_masked(v):\n                continue\n\n            du = int(np.round(u))\n            dv = int(np.round(v))\n            fu_offset = int(\n                    (1 + self._hsup + (-u + du)) * self._ovsmpl\n                )\n            fv_offset = int(\n                    (1 + self._hsup + (-v + dv)) * self._ovsmpl\n                )\n\n            du_psf = int(np.round(u*2))\n            dv_psf = int(np.round(v*2))\n            fu_offset_psf = int(\n                    (1 + self._hsup + (-u*2 + du_psf)) * self._ovsmpl\n                )\n            fv_offset_psf = int(\n                    (1 + self._hsup + (-v*2 + dv_psf)) * self._ovsmpl\n            )\n\n            if (dv + self.nsize // 2 + self._hsup >= self.nsize or\n                du + self.nsize // 2 + self._hsup >= self.nsize or\n                dv + self.nsize // 2 - self._hsup < 0 or\n                du + self.nsize // 2 - self._hsup < 0):\n                continue\n\n            for conv_v in self._filter_idx:\n                v_tap = self._ftaps[conv_v * self._ovsmpl + fv_offset]\n                v_tap_psf = self._ftaps[conv_v * self._ovsmpl + fv_offset_psf]\n\n                grid_v = dv + conv_v + self.nsize // 2\n                grid_v_psf = dv_psf + conv_v + self.nsize\n                \n                for conv_u in self._filter_idx:\n                    u_tap = self._ftaps[conv_u * self._ovsmpl + fu_offset]\n                    u_tap_psf = self._ftaps[conv_u * self._ovsmpl + fu_offset_psf]\n                    \n                    grid_u = du + conv_u + self.nsize // 2\n                    grid_u_psf = du_psf + conv_u + self.nsize\n\n                    conv_weight = v_tap * u_tap\n                    conv_weight_psf = v_tap_psf * u_tap_psf\n                    \n                    # for p in range(self.vis.shape[3]):\n                    #     self.measurement[p, grid_v, grid_u] += self.vis[0, 0, vis_bl, p] * conv_weight\n                    for p in range(self.vis.shape[1]):\n                        self.measurement[p, grid_v, grid_u] += self.vis[vis_bl, p] * conv_weight\n                        # self._meas_w[grid_v, grid_u] += 1\n                        self._meas_w[grid_v, grid_u] += 1. * conv_weight\n                    # assuming the PSF is the same for different correlations:\n                    self.sampling[grid_v_psf, grid_u_psf] += (1+0.0j) * conv_weight_psf\n                    # self._samp_w[grid_v_psf, grid_u_psf] += 1\n                    self._samp_w[grid_v_psf, grid_u_psf] += 1. * conv_weight_psf\n\n        self._compute_weights()\n        return\n\n    # --------------------------------------------------------- #\n    # ----------------------- Internal ------------------------ #\n    def _compute_weights(self):\n        \"\"\"\n        \"\"\"\n        # nbsl = self.uvw.size / 3\n        # bsl_time = (2.*nbsl*1) # one time step\n        # num = (5.*10.**(-self.robust))**2.*bsl_time\n        # meas_f = num/np.sum(self._meas_w**2.)\n        # samp_f = num/np.sum(self._samp_w**2.)\n\n        # self.meas_weighted = self._meas_w / (1 + self._meas_w * meas_f)\n        # self.samp_weighted = self._samp_w / (1 + self._samp_w * samp_f)\n\n        factor = (5. * 10.**(-self.robust) )**2\n        f = factor / (np.sum(self._meas_w**2.) / np.sum(self._meas_w))\n        self.meas_weights = self._meas_w / (1 + self._meas_w * f)\n        self.meas_weights /= self.meas_weights.max()\n\n        f = factor / (np.sum(self._samp_w**2.) / np.sum(self._samp_w))\n        self.samp_weights = self._samp_w / (1 + self._samp_w * f)\n        self.samp_weights /= self.samp_weights.max()\n        return\n# ============================================================= #\n\n\n\n# ============================================================= #\n# ---------------------------- Grid --------------------------- #\n# ============================================================= #\nclass Grid_Simple(object):\n    \"\"\"\n    \"\"\"\n\n    def __init__(\n        self,\n        vis,\n        uvw,\n        freq,\n        fov,\n        cellsize=None,\n        robust=0.,\n        convolution=None\n        ):\n        self.nsize = None\n        self.fov = fov\n        self.vis = vis\n        self.uvw = uvw\n        self.freq = freq\n        self.cellsize = cellsize\n        self.robust = robust\n        self.convolution = convolution\n\n\n    # --------------------------------------------------------- #\n    # --------------------- Getter/Setter --------------------- #\n    @property\n    def vis(self):\n        return self._vis\n    @vis.setter\n    def vis(self, v):\n        x, y = np.tril_indices(v.shape[0], 0)\n        xx = np.hstack((x[x!=y], y[x!=y]))\n        yy = np.hstack((y[x!=y], x[x!=y]))\n        self._vis = v[xx, yy, ...] + v[yy, xx, ...].conj()\n        return\n\n\n    @property\n    def uvw(self):\n        return self._uvw\n    @uvw.setter\n    def uvw(self, u):\n        x, y = np.tril_indices(u.shape[0], 0)\n        xx = np.hstack((x[x!=y], y[x!=y]))\n        yy = np.hstack((y[x!=y], x[x!=y]))\n        self._uvw = u[xx, yy, ...]\n\n        maxu = np.max(np.abs(self._uvw[..., 0]))\n        maxv = np.max(np.abs(self._uvw[..., 1]))\n        self.resol = 1. / (5 * 2 * np.max((maxu, maxv))) * un.rad\n        resol = self.resol.to(un.deg).value\n        self.nsize = int(np.round(self.fov / resol))\n        return\n\n\n    @property\n    def nsize(self):\n        return self._nsize\n    @nsize.setter\n    def nsize(self, n):\n        if n is None:\n            self._nsize = None\n        else:\n            self._nsize = n\n            self.measurement = np.zeros(\n                (self.vis.shape[1], self.nsize, self.nsize),\n                dtype='complex64'\n            )\n            self._meas_w = np.zeros(\n                (self.nsize, self.nsize),\n                dtype='float'\n            )\n            # for deconvolution the PSF should be 2x size of the image (see \n            # Hogbom CLEAN for details), one grid for the sampling function:\n            self.sampling = np.zeros(\n                (2*self.nsize, 2*self.nsize),\n                dtype='complex64'\n            )\n            self._samp_w = np.zeros(\n                (2*self.nsize, 2*self.nsize),\n                dtype='float'\n            )\n\n\n    # --------------------------------------------------------- #\n    # ------------------------ Methods ------------------------ #\n    def populate(self):\n        \"\"\"\n        \"\"\"\n        for vis_bl in range(int(self.uvw.size / 3)):\n            u = self.uvw[vis_bl, 0] * np.radians(self.fov)\n            v = self.uvw[vis_bl, 1] * np.radians(self.fov)\n\n            if np.ma.is_masked(u) or np.ma.is_masked(v):\n                continue\n\n            du = int(np.round(u)) + self.nsize // 2\n            dv = int(np.round(v)) + self.nsize // 2\n            du_psf = int(np.round(u*2)) + self.nsize\n            dv_psf = int(np.round(v*2)) + self.nsize\n            \n            for p in range(self.vis.shape[1]):\n                self.measurement[p, dv, du] += self.vis[vis_bl, p]\n            self._meas_w[dv, du] += 1.\n            # assuming the PSF is the same for different correlations:\n            self.sampling[dv_psf, du_psf] += (1+0.0j)\n            self._samp_w[dv_psf, du_psf] += 1.\n\n        self._convolve()\n\n        self._compute_weights()\n        return\n\n\n    # --------------------------------------------------------- #\n    # ----------------------- Internal ------------------------ #\n    def _compute_weights(self):\n        \"\"\"\n        \"\"\"\n        factor = (5. * 10.**(-self.robust) )**2\n        f = factor / (np.sum(self._meas_w**2.) / np.sum(self._meas_w))\n        self.meas_weights = self._meas_w / (1 + self._meas_w * f)\n        self.meas_weights /= self.meas_weights.max()\n\n        f = factor / (np.sum(self._samp_w**2.) / np.sum(self._samp_w))\n        self.samp_weights = self._samp_w / (1 + self._samp_w * f)\n        self.samp_weights /= self.samp_weights.max()\n        return\n\n\n    def _convolve(self):\n        \"\"\"\n        \"\"\"\n        if self.convolution is None:\n            return\n        elif self.convolution.lower() == 'gaussian':\n            from scipy.ndimage import gaussian_filter\n            def _scipy_gauss(im, sig=0.25):\n                if im.dtype == np.complex64:\n                    im_re = gaussian_filter(\n                        input=im.real,\n                        sigma=sig,\n                        order=0,\n                        output=None,\n                        mode='reflect',\n                        cval=0.0,\n                        truncate=4.0\n                    )\n                    im_im = gaussian_filter(\n                        input=im.imag,\n                        sigma=sig,\n                        order=0,\n                        output=None,\n                        mode='reflect',\n                        cval=0.0,\n                        truncate=4.0\n                    )\n                    return im_re + 1.j*im_im\n                else:\n                    return gaussian_filter(\n                        input=im,\n                        sigma=sig,\n                        order=0,\n                        output=None,\n                        mode='reflect',\n                        cval=0.0,\n                        truncate=4.0\n                    )\n            for p in range(self.measurement.shape[0]):\n                self.measurement[p, ...] = _scipy_gauss(self.measurement[p, ...])\n            self.sampling = _scipy_gauss(self.sampling)\n            self._meas_w = _scipy_gauss(self._meas_w)\n            self._samp_w = _scipy_gauss(self._samp_w)\n        else:\n            raise Exception(\n                'Convolution kernel {} not implemented.'.format(self.convolution)\n            )\n# ============================================================= #\n\n\n\n# ============================================================= #\n# -------------------------- Grid_HPX ------------------------- #\n# ============================================================= #\nclass Grid_HPX(object):\n    \"\"\"\n    \"\"\"\n\n    def __init__(self, resolution):\n        self.nside = None\n        self.resol = resolution\n        self.ra, self.dec = self._hpx_radec()\n\n\n    # --------------------------------------------------------- #\n    # --------------------- Getter/Setter --------------------- #\n    @property\n    def resol(self):\n        \"\"\" Resolution of the cell in degrees\n        \"\"\"\n        return self._resol\n    @resol.setter\n    def resol(self, r):\n        nsides = 2**np.arange(1, 12)\n        resol_rad = hp.nside2resol(\n            nside=nsides,\n            arcmin=False\n            )\n        resol_deg = np.degrees(resol_rad)\n        idx = (np.abs(resol_deg - r)).argmin()\n        self._resol = resol_deg[idx]\n        self.nside = nsides[idx]\n        return\n\n\n    @property\n    def nside(self):\n        return self._nside\n    @nside.setter\n    def nside(self, n):\n        if n is None:\n            self._nside = None\n        else:\n            self.npix = hp.nside2npix(n)\n            self._nside = n\n        return\n\n\n    # --------------------------------------------------------- #\n    # ------------------------ Methods ------------------------ #\n\n\n    # --------------------------------------------------------- #\n    # ----------------------- Internal ------------------------ #\n    def _hpx_radec(self):\n        \"\"\"\n        \"\"\"\n        ra, dec = hp.pix2ang(\n            nside=self.nside,\n            ipix=np.arange(self.npix),\n            lonlat=True,\n            nest=False\n            )\n        return ra, dec\n\n# ============================================================= #\n\n\n\n\n# class ImgWPlus(aipy.img.ImgW):\n#     \"\"\"\n#     Sub-class of the aipy.img.ImgW class that adds support for different \n#     visibility weighting scheme and uv plane tapering.  This class also\n#     adds in a couple of additional methods that help determine the size of\n#     the field of view and the pixels near the phase center.\n#     \"\"\"\n#     def __init__(self, size=100, res=1, wres=.5, mf_order=0):\n#         \"\"\"size = number of wavelengths which the UV matrix spans (this \n#         determines the image resolution).\n#         res = resolution of the UV matrix (determines image field of view).\n#         wres: the gridding resolution of sqrt(w) when projecting to w=0.\"\"\"\n#         self.res = float(res)\n#         self.size = float(size)\n#         ## Small change needed to work with Numpy 1.12+\n#         dim = numpy.int64(numpy.round(self.size / self.res))\n#         self.shape = (dim,dim)\n#         self.uv = numpy.zeros(shape=self.shape, dtype=numpy.complex64)\n#         self.bm = []\n#         for i in range(mf_order+1):\n#             self.bm.append(numpy.zeros(shape=self.shape, dtype=numpy.complex64))\n#         self.wres = float(wres)\n#         self.wcache = {}\n#     def put(self, uvw, data, wgts=None, invker2=None):\n#         \"\"\"Same as Img.put, only now the w component is projected to the w=0\n#         plane before applying the data to the UV matrix.\"\"\"\n#         u, v, w = uvw\n#         if len(u) == 0: return\n#         if wgts is None:\n#             wgts = []\n#             for i in range(len(self.bm)):\n#                 if i == 0:\n#                     wgts.append(numpy.ones_like(data))\n#                 else:\n#                     wgts.append(numpy.zeros_like(data))\n#         if len(self.bm) == 1 and len(wgts) != 1:\n#             wgts = [wgts]\n#         assert(len(wgts) == len(self.bm))\n#         # Sort uvw in order of w\n#         order = numpy.argsort(w)\n#         u = u.take(order)\n#         v = v.take(order)\n#         w = w.take(order)\n#         data = data.take(order)\n#         wgts = [wgt.take(order) for wgt in wgts]\n#         sqrt_w = numpy.sqrt(numpy.abs(w)) * numpy.sign(w)\n#         i = 0\n#         while True:\n#             # Grab a chunk of uvw's that grid w to same point.\n#             j = sqrt_w.searchsorted(sqrt_w[i]+self.wres)\n#             print('%d/%d datums' % (j, len(w)))\n#             avg_w = numpy.average(w[i:j])\n#             # Put all uv's down on plane for this gridded w point\n#             wgtsij = [wgt[i:j] for wgt in wgts]\n#             uv,bm = aipy.img.Img.put(self, (u[i:j],v[i:j],w[i:j]),\n#                 data[i:j], wgtsij, apply=False)\n#             # Convolve with the W projection kernel\n#             invker = numpy.fromfunction(lambda u,v: self.conv_invker(u,v,avg_w),\n#                 uv.shape)\n#             if not invker2 is None:\n#                 invker *= invker2\n#             self.uv += ifft2Function(fft2Function(uv) * invker)\n#             #self.uv += uv\n#             for b in range(len(self.bm)):\n#                 self.bm[b] += ifft2Function(fft2Function(bm[b]) * invker)\n#                 #self.bm[b] += numpy.array(bm)[0,:,:]\n#             if j >= len(w):\n#                 break\n#             i = j\n", "meta": {"hexsha": "67e1e005fb8488423fc16e3eb51d6e0a89115edf", "size": 19435, "ext": "py", "lang": "Python", "max_stars_repo_path": "nenupytv/image/grid.py", "max_stars_repo_name": "AlanLoh/nenupy-tv", "max_stars_repo_head_hexsha": "9c33652521293eaba726f02fdb2331ae32dda6f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nenupytv/image/grid.py", "max_issues_repo_name": "AlanLoh/nenupy-tv", "max_issues_repo_head_hexsha": "9c33652521293eaba726f02fdb2331ae32dda6f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2019-11-12T09:48:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-28T17:02:54.000Z", "max_forks_repo_path": "nenupytv/image/grid.py", "max_forks_repo_name": "AlanLoh/nenupy-tv", "max_forks_repo_head_hexsha": "9c33652521293eaba726f02fdb2331ae32dda6f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-09T17:40:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-09T17:40:58.000Z", "avg_line_length": 33.0527210884, "max_line_length": 104, "alphanum_fraction": 0.4442500643, "include": true, "reason": "import numpy,from scipy,import astropy", "num_tokens": 4888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.1979794333517329}}
{"text": "#!/usr/bin/env python3\nimport sys\nimport time\nimport numpy.linalg\nimport numpy.random\nimport random\n\n\nVK_SPREAD = [\n    [-24, 58.0], [-23, 36.0], [-22, 20.0], [-21, 17.0],\n    [-20, 16.0], [-19, 19.0], [-18, 24.0], [-17, 36.0],\n    [-16, 45.0], [-15, 55.0], [-14, 60.0], [-13, 70.0],\n    [-12, 75.0], [-11, 79.0], [-10, 83.0], [-9, 87.0],\n    [-8, 92.0], [-7, 96.0], [-6, 100.0], [-5, 105.0],\n    [-4, 108.0], [-3, 105.0], [-2, 96.0], [-1, 80.0],\n    [0, 58.0], [1, 36.0], [2, 20.0], [3, 17.0],\n    [4, 16.0], [5, 19.0], [6, 24.0], [7, 36.0],\n    [8, 45.0], [9, 55.0], [10, 60.0], [11, 70.0],\n    [12, 75.0], [13, 79.0], [14, 83.0], [15, 87.0],\n    [16, 92.0], [17, 96.0], [18, 100.0], [19, 105.0],\n    [20, 108.0], [21, 105.0], [22, 96.0], [23, 80.0],\n    [24, 58.0], [25, 36.0], [26, 20.0], [27, 17.0],\n    [28, 16.0], [29, 19.0], [30, 24.0], [31, 36.0],\n    [32, 45.0], [33, 55.0], [34, 60.0], [35, 70.0],\n    [36, 75.0], [37, 79.0], [38, 83.0], [39, 87.0],\n    [40, 92.0], [41, 96.0], [42, 100.0], [43, 105.0],\n    [44, 108.0], [45, 105.0], [46, 96.0], [47, 80.0],\n    [48, 58.0],\n]\n\n\ndef WR_params(date, f=1):\n    \"\"\"\n        Generates params for WeightRandom class\n    \"\"\"\n    tm = time.localtime(date)\n    date = (tm.tm_hour * 60 + tm.tm_min) * 60 + tm.tm_sec\n    return [\n        [date, 0.0],\n        [date + (3600 + 600) / f, 3200],\n        [date + (2 * 3600) / f, 1850]\n    ]\n\n\nclass PyWeightRandom:\n    \"\"\"\n        use post date and time of publish\n        to generate weight random method()\n        it emulates when user creates reposts/likes\n    \"\"\"\n\n    def __init__(self, data):\n        \"\"\"\n            data = [\n              [ x0 , y0 ] , - левая точка нуля пораболы\n              [ x1 , y1 ] , - пик\n              [ x2 , y2 ] - точка после точки пика через ( x1-x0 )\n            ]\n            endpoint = mun of second that:\n             1. > x0\n             2. <= x0 + 86000\n        \"\"\"\n        # p = [ x0 , x1 , y1 , y2]\n        self.p = [data[0][0], data[1][0], data[1][1], data[2][1]]\n        mm = [\n            [self.p[0]**2, self.p[0], 1],\n            [self.p[1]**2, self.p[1], 1],\n            [(2 * self.p[1] - self.p[0])**2, (2 * self.p[1] - self.p[0]), 1]\n        ]\n        abc = list(numpy.linalg.solve(mm, [0, self.p[2], 0]))\n        self.a = abc[0]\n        self.b = abc[1]\n        self.c = abc[2]\n        mm = [\n            [1.0, -self.p[2]],\n            [1.0, -self.p[3]]\n        ]\n        dk = numpy.linalg.solve(mm, [self.p[2] * self.p[1], self.p[3] * (2 * self.p[1] - self.p[0])])\n        self.d = dk[0]\n        self.k = dk[1]\n\n        self.data = {}\n        self._fill()\n\n        self._weight = list(self.data.values())\n        self._m = sum(self._weight)\n        self.elem = list(self.data.keys())\n        self.weight = list(map(lambda x: float(x) / float(self._m), self._weight))\n\n    # ==========================================================================\n    #                            INTERNAL METHODS\n    # ==========================================================================\n\n    def spread(self, x):\n        \"\"\"\n            формула распределения случайно величиный\n            p = [\n             0 - start point (flaot)\n             1 - X where max of Y (float)\n             2 - max of Y (float)\n             3 - Y when x = ( 2*p[1]-p[0] )\n            ]\n        \"\"\"\n        if self.p[0] + 1 <= x <= self.p[1] + 1:\n            res = self.a * (x**2) + self.b * x + self.c\n        elif self.p[1] <= x:\n            res = (self.d / (x + self.k))\n        else:\n            res = self.spread(x + 3600 * 24)\n        return res\n\n    def _fill(self):\n        \"\"\"\n            should fill self.data with values of spread function in interesing range\n            return None\n        \"\"\"\n        end = 86400 + (i := self.p[0])\n        while i < end:\n            self.data[i % 86400] = self.spread(i)\n            i += 1\n\n    def random(self, y=1):\n        \"\"\"\n            return random number using spread function\n        \"\"\"\n        if y <= 1:\n            x = random.random()\n            i = 0\n            while x > 0.0:\n                x -= self.weight[i]\n                i += 1\n            return [i - 1]\n        else:\n            k = float(self._m) / float(y)\n            x = []\n            y = k\n            for i in range(len(ww := list(self._weight))):\n                while ww[i] > 0.0:\n                    y -= (z := min(y, ww[i]))\n                    ww[i] -= z\n                    if y <= 0.0:\n                        y = k\n                        x.append(ww[i])\n            return x\n\n    def destruct(self):\n        \"\"\"\n            really do nothing (here)\n        \"\"\"\n        pass\n\n    def will_be(self, count_now, now):\n        \"\"\"\n            predict now many obj will be in 24 hours\n        \"\"\"\n        def en(_time):\n            tm = time.localtime(_time)\n            return (tm.tm_hour * 60 + tm.tm_min) * 60 + tm.tm_sec\n        if (now := en(now)) < self.p[0]:\n            now += 24 * 3600\n\n        return (\n            (count_now * sum(self.weight) / s)\n            if (\n                s := sum(\n                    self.weight[i]\n                    for i in range(len(self.weight))\n                    if self.p[0] < i < now\n                )\n            ) > 0 else\n            0\n        )\n\n\ndef py__interpolice(ff, x):\n    \"\"\"\n        real interpolice method\n        USE ONLY BY INTERPOLICE\n    \"\"\"\n    res = 0.0\n    for i in ff:\n        if not(-12 < (i[0] - x) < 12):\n            continue\n        li = 1.0\n        for j in ff:\n            if not(-12 < (j[0] - x) < 12):\n                continue\n            if i[0] != j[0]:\n                z = (i[0] - j[0])\n                li *= ((x - j[0]) / z)\n        res += li * i[1]\n    return res\n\n\nboo = False\nif sys.platform in {'linux', 'darwin'} and '--no-c' not in sys.argv[1:]:\n    try:\n        from .ext import interpolice as __interpolice\n        from .ext import CWeightRandom as WeightRandom\n        boo = True\n    except Exception:\n        pass\n\nif not boo:\n    WeightRandom = PyWeightRandom\n    __interpolice = py__interpolice\n\n\ndef interpolice(x, ff=None):\n    \"\"\"\n        takes as x float() - number of hours\n          13:30 - 13.5\n        return float from [0..1]\n        ff = [\n         [x0 , f(x0)],\n         [x1 , f(x1)],\n        ]\n    \"\"\"\n    if ff is None:\n        ff = VK_SPREAD\n        _max = 108.0\n    else:\n        _max = float(max(i[1] for i in ff))\n    return __interpolice(ff, x) / _max\n", "meta": {"hexsha": "590b1ad4a335ac3514b6d0c96f1225e4ab5c7a19", "size": 6420, "ext": "py", "lang": "Python", "max_stars_repo_path": "logic/rank/wr.py", "max_stars_repo_name": "moff4/gladius", "max_stars_repo_head_hexsha": "773a4e81fcfca7376292c8f9ba601b62324a65f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "logic/rank/wr.py", "max_issues_repo_name": "moff4/gladius", "max_issues_repo_head_hexsha": "773a4e81fcfca7376292c8f9ba601b62324a65f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "logic/rank/wr.py", "max_forks_repo_name": "moff4/gladius", "max_forks_repo_head_hexsha": "773a4e81fcfca7376292c8f9ba601b62324a65f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5333333333, "max_line_length": 101, "alphanum_fraction": 0.4035825545, "include": true, "reason": "import numpy", "num_tokens": 2142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.2974699426047947, "lm_q1q2_score": 0.19793964071903913}}
{"text": "# -*- coding: utf-8 -*-\n# ---------------------\n\nimport numpy as np\nimport ergonomics.utils as utils\n\n\nclass RebaScore:\n    '''\n    Class to compute REBA metrics\n\n    Pose:\n          [0]: Head\n          [1]: Neck\n          [2, 3, 4, 14]: Left arm + (optional)left hand\n          [5, 6, 7, 15]: Right arm + (optional)right hand\n          [8, 9, 10]: Left leg\n          [11, 12, 13]: Right leg\n    '''\n    def __init__(self):\n        # Table A ( Neck X Trunk X Legs)\n        self.table_a = np.zeros((3, 5, 4))\n        # Table B ( UpperArm X LowerArm X Wrist)\n        self.table_b = np.zeros((6, 2, 3))\n        # Table C ( ScoreA X ScoreB)\n        self.table_c = np.zeros((12, 12))\n\n        # Body Params\n        self.body = {'neck_angle': 0, 'neck_side': False,\n                     'trunk_angle': 0, 'trunk_side': False,\n                     'legs_walking': False, 'legs_angle': 0,\n                     'load': 0}\n\n        # Arms Params\n        self.arms = {'upper_arm_angle': 0, 'shoulder_raised': False, 'arm_abducted': False, 'leaning': False,\n                     'lower_arm_angle': 0,\n                     'wrist_angle': 0, 'wrist_twisted': False}\n\n        # Init lookup tables\n        self.init_table_a()\n        self.init_table_b()\n        self.init_table_c()\n\n\n    def init_table_a(self):\n        '''\n        Table used to compute upper body score\n\n        :return: None\n        '''\n        self.table_a = np.array([\n                                [[1, 2, 3, 4], [2, 3, 4, 5], [2, 4, 5, 6], [3, 5, 6, 7], [4, 6, 7, 8]],\n                                [[1, 2, 3, 4], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9]],\n                                [[3, 3, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 9]]\n                                ])\n\n    def init_table_b(self):\n        '''\n        Table used to computer lower body score\n\n        :return: None\n        '''\n        self.table_b = np.array([\n                                [[1, 2, 2], [1, 2, 3]],\n                                [[1, 2, 3], [2, 3, 4]],\n                                [[3, 4, 5], [4, 5, 5]],\n                                [[4, 5, 5], [5, 6, 7]],\n                                [[6, 7, 8], [7, 8, 8]],\n                                [[7, 8, 8], [8, 9, 9]],\n                                ])\n\n    def init_table_c(self):\n        '''\n        Table to compute score_c\n\n        :return: None\n        '''\n        self.table_c = np.array([\n                                [1, 1, 1, 2, 3, 3, 4, 5, 6, 7, 7, 7],\n                                [1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 7, 8],\n                                [2, 3, 3, 3, 4, 5, 6, 7, 7, 8, 8, 8],\n                                [3, 4, 4, 4, 5, 6, 7, 8, 8, 9, 9, 9],\n                                [4, 4, 4, 5, 6, 7, 8, 8, 9, 9, 9, 9],\n                                [6, 6, 6, 7, 8, 8, 9, 9, 10, 10, 10, 10],\n                                [7, 7, 7, 8, 9, 9, 9, 10, 10, 11, 11, 11],\n                                [8, 8, 8, 9, 10, 10, 10, 10, 10, 11, 11, 11],\n                                [9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 12],\n                                [10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 12],\n                                [11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12],\n                                [12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12],\n                                ])\n\n    def set_body(self, values):\n        # type: (np.ndarray) -> None\n        '''\n        Set body params\n\n        :param values: [neck_angle, neck_side, trunk_angle, trunk_side,\n                        legs_walking, legs_angle, load]\n\n        :return: None\n        '''\n        assert len(values) == len(self.body)\n\n        for i, (key, _) in enumerate(self.body.items()):\n            self.body[key] = values[i]\n\n    def set_arms(self, values):\n        # type: (np.ndarray) -> None\n        '''\n        Set arms params\n\n        :param values:  [upper_arm_angle, shoulder_raised, arm_abducted, leaning,\n                        lower_arm_angle, wrist_angle, wrist_twisted]\n\n        :return: None\n        '''\n        assert len(values) == len(self.arms)\n\n        for i, (key, _) in enumerate(self.arms.items()):\n            self.arms[key] = values[i]\n\n    def compute_score_a(self):\n        # type: (RebaScore) -> (np.ndarray, np.ndarray)\n        '''\n        Compute score A\n        >>> rebascore = RebaScore()\n        >>> rebascore.set_body(np.array([10, 0, 20, 0, 1, 50, 0]))\n        >>> rebascore.compute_score_a()\n        (4, array([1, 2, 3]))\n\n        :return: Score A, [neck_score, trunk_score, leg_score]\n        '''\n        neck_score, trunk_score, leg_score, load_score = 0, 0, 0, 0\n\n        # Neck position\n        if 10 <= self.body['neck_angle'] <= 20 :\n            neck_score +=1\n        else:\n            neck_score +=2\n        # Neck adjust\n        neck_score +=1 if self.body['neck_side'] else 0\n\n        # Trunk position\n        if 0 <= self.body['trunk_angle'] <= 1:\n            trunk_score +=1\n        elif self.body['trunk_angle'] <= 20:\n            trunk_score +=2\n        elif 20 <= self.body['trunk_angle'] <= 60:\n            trunk_score +=3\n        elif self.body['trunk_angle'] > 60:\n            trunk_score +=4\n        # Trunk adjust\n        trunk_score += 1 if self.body['trunk_side'] else 0\n\n        # Legs position\n        leg_score += 2 if self.body['legs_walking'] else 1\n        # Legs adjust\n        if 30 <= self.body['legs_angle'] <= 60:\n            leg_score += 1\n        elif self.body['legs_angle'] > 60:\n            leg_score += 2\n\n        # Load\n        if 5 <= self.body['load'] <= 10:\n            load_score += 1\n        elif self.body['load'] > 10:\n            load_score += 2\n\n        assert neck_score > 0 and trunk_score > 0 and leg_score > 0\n\n        score_a = self.table_a[neck_score-1][trunk_score-1][leg_score-1]\n        return score_a, np.array([neck_score, trunk_score, leg_score])\n\n    def compute_score_b(self):\n        # type: (RebaScore) -> (np.ndarray, np.ndarray)\n        '''\n        Compute score B\n        >>> rebascore = RebaScore()\n        >>> rebascore.set_arms(np.array([45, 0, 0, 0, 70, 0, 1]))\n        >>> rebascore.compute_score_b()\n        (2, array([2, 1, 2]))\n\n        :return: scoreB, [upper_arm_score, lower_arm_score, wrist_score]\n        '''\n        upper_arm_score, lower_arm_score, wrist_score = 0, 0, 0\n\n        # Upper arm position\n        if -20 <= self.arms['upper_arm_angle'] <= 20:\n            upper_arm_score +=1\n        elif self.arms['upper_arm_angle'] <= 45:\n            upper_arm_score +=2\n        elif 45 <= self.arms['upper_arm_angle'] <= 90:\n            upper_arm_score +=3\n        elif self.arms['upper_arm_angle'] > 90:\n            upper_arm_score +=4\n\n        # Upper arm adjust\n        upper_arm_score += 1 if self.arms['shoulder_raised'] else 0\n        upper_arm_score += 1 if self.arms['arm_abducted'] else 0\n        upper_arm_score -= 1 if self.arms['leaning'] else 0\n\n        # Lower arm position\n        if 60 <= self.arms['lower_arm_angle'] <= 100:\n            lower_arm_score += 1\n        else:\n            lower_arm_score += 2\n\n        # Wrist position\n        if -15 <= self.arms['wrist_angle'] <= 15:\n            wrist_score += 1\n        else:\n            wrist_score += 2\n\n        # Wrist adjust\n        wrist_score += 1 if self.arms['wrist_twisted'] else 0\n\n        assert lower_arm_score > 0 and wrist_score > 0\n\n        score_b = self.table_b[upper_arm_score-1][lower_arm_score-1][wrist_score-1]\n        return score_b, np.array([upper_arm_score, lower_arm_score, wrist_score])\n\n    def compute_score_c(self, score_a, score_b):\n        # type: (np.ndarray, np.ndarray) -> (np.ndarray, str)\n        '''\n        Compute score C\n\n        :param score_a:  Score A\n        :param score_b:  Score B\n\n        :return: Score C, caption\n        '''\n        reba_scoring = ['Negligible Risk',\n                         'Low Risk. Change may be needed',\n                         'Medium Risk. Further Investigate. Change Soon',\n                         'High Risk. Investigate and Implement Change',\n                         'Very High Risk. Implement Change'\n                         ]\n\n        score_c = self.table_c[score_a-1][score_b-1]\n        ix = self.score_c_to_5_classes(score_c)\n        caption = reba_scoring[ix]\n\n        return score_c, caption\n\n    @staticmethod\n    def score_c_to_5_classes(score_c):\n        # type: (np.ndarray) -> int\n        '''\n        Score C to 5 risk-classes\n\n        :param score_c:  Score C\n        :return: Risk-class\n        '''\n        if score_c == 1:\n            ret = 0\n        elif 2 <= score_c <= 3:\n            ret = 1\n        elif 4 <= score_c <= 7:\n            ret = 2\n        elif 8 <= score_c <= 10:\n            ret = 3\n        else:\n            ret = 4\n\n        return ret\n\n    @staticmethod\n    def get_body_angles_from_pose_left(pose, verbose=False):\n        # type: (np.ndarray, bool) -> np.ndarray\n        '''\n        Get body angles from pose (look at left)\n\n        :param pose: Pose (Joints coordinates)\n        :param verbose: If true show each pose for debugging\n\n        :return: Body params (neck_angle, neck_side, trunk_angle, trunk_side,\n                legs_walking, legs_angle, load)\n        '''\n\n        pose = np.expand_dims(np.copy(pose), 0)\n\n        neck_angle, neck_side, trunk_angle, trunk_side, \\\n        legs_walking, legs_angle, load = 0, 0, 0, 0, 0, 0, 0\n\n        if verbose:\n            utils.show_skeleton(pose, title=\"GT pose\")\n            _pose, _ = utils.rotate_pose(np.copy(pose), rotation_joint=8)\n            utils.show_skeleton(_pose, title=\"GT pose left\")\n\n        # Trunk position\n        pose, _ = utils.rotate_pose(pose, rotation_joint=8)\n        pose -= (pose[:, 8] + pose[:, 11]) /2\n\n        if quad(pose[0, 1]) < 3:\n            trunk_angle = np.rad2deg(np.arctan2(pose[0, 1, 1], pose[0, 1, 0]) - (np.pi / 2))\n        else:\n            trunk_angle = 270 + np.rad2deg(np.arctan2(pose[0, 1, 1], pose[0, 1, 0]))\n\n        if verbose:\n            utils.show_skeleton(pose, title=\"Trunk angle: \" + str(round(trunk_angle, 2)))\n\n        # Trunk bending\n        pose, _ = utils.rotate_pose(pose, rotation_joint=8, m_coeff=np.pi/2)\n\n        angle = np.pi /2 if quad(pose[0, 1]) > 2 else -np.pi/2\n        trunk_side_angle = abs(np.rad2deg(np.arctan2(pose[0, 1, 1], pose[0, 1, 0]) + angle))\n        trunk_side = 1 if trunk_side_angle > 30 else 0\n\n        if verbose:\n            utils.show_skeleton(pose, title=\"Trunk side angle: \" + str(round(trunk_side_angle, 2)))\n\n        # Neck position\n        pose, _ = utils.rotate_pose(pose, rotation_joint=8, m_coeff=-np.pi/2)\n        pose -= pose[:, 1]\n\n        if quad(pose[0, 0]) < 3:\n            neck_angle = np.rad2deg(np.arctan2(pose[0, 0, 1], pose[0, 0, 0]) - (np.pi / 2)) - trunk_angle\n        else:\n            neck_angle = 270 + np.rad2deg(np.arctan2(pose[0, 0, 1], pose[0, 0, 0])) - trunk_angle\n\n        if verbose:\n            utils.show_skeleton(pose, title=\"Neck angle: \" + str(round(neck_angle, 2)))\n\n        # Neck bending\n        pose, _ = utils.rotate_pose(pose, rotation_joint=8, m_coeff=np.pi / 2)\n        angle = np.pi /2 if quad(pose[0, 0]) > 2 else -np.pi/2\n        neck_side_angle = abs(np.rad2deg(np.arctan2(pose[0, 0, 1], pose[0, 0, 0]) + angle)) - trunk_side_angle\n        neck_side = 1 if neck_side_angle > 20 else 0\n\n        if verbose:\n            utils.show_skeleton(pose, title=\"Neck side angle: \" + str(round(neck_side_angle, 2)))\n\n        # Legs position\n        pose, _ = utils.rotate_pose(pose, rotation_joint=8, m_coeff=-np.pi / 2)\n        pose -= pose[:, 8]\n\n        if quad(pose[0, 9]) > 2:\n            legs_angle = -np.rad2deg(np.arctan2(pose[0, 9, 1], pose[0, 9, 0]) + (np.pi/2))\n        else:\n            legs_angle = 270 - np.rad2deg(np.arctan2(pose[0, 9, 1], pose[0, 9, 0]))\n\n        step_size = abs(np.linalg.norm(pose[0, 10, :2] - pose[0, 13, :2]))\n        legs_walking = 1 if step_size > 0.1 else 0\n\n        if verbose:\n            title = \"Leg angle: \" + str(round(legs_angle, 2)) + \" Step size: \" + str(round(step_size, 2))\n            utils.show_skeleton(pose, title=title)\n\n        return np.array([neck_angle, neck_side, trunk_angle, trunk_side,\n                           legs_walking, legs_angle, load])\n\n\n    @staticmethod\n    def get_body_angles_from_pose_right(pose, verbose=False):\n        # type: (np.ndarray, bool) -> np.ndarray\n        '''\n        Get body angles from pose (look at right)\n\n        :param pose: Pose (Joints coordinates)\n        :param verbose: If true show each pose for debugging\n\n        :return: Body params (neck_angle, neck_side, trunk_angle, trunk_side,\n                              legs_walking, legs_angle, load)\n        '''\n        pose = np.expand_dims(np.copy(pose), 0)\n\n        neck_angle, neck_side, trunk_angle, trunk_side, \\\n        legs_walking, legs_angle, load = 0, 0, 0, 0, 0, 0, 0\n\n        if verbose:\n            utils.show_skeleton(pose, title=\"GT pose\")\n            _pose, _ = utils.rotate_pose(np.copy(pose), rotation_joint=8)\n            _pose, _ = utils.rotate_pose(_pose, rotation_joint=8, m_coeff=np.pi)\n            utils.show_skeleton(_pose, title=\"GT pose Right\")\n\n        pose, _ = utils.rotate_pose(pose, rotation_joint=8)\n\n        # Trunk position\n        pose, _ = utils.rotate_pose(pose, rotation_joint=8, m_coeff=np.pi)\n        pose -= (pose[:, 8] + pose[:, 11]) / 2\n        trunk_angle = np.rad2deg((np.pi / 2)  - np.arctan2(pose[0, 1, 1], pose[0, 1, 0]))\n\n        if verbose:\n            utils.show_skeleton(pose, title=\"Trunk angle: \" + str(round(trunk_angle, 2)))\n\n        # Trunk bending\n        pose, _ = utils.rotate_pose(pose, rotation_joint=8, m_coeff=np.pi / 2)\n        trunk_side_angle = abs(np.rad2deg(np.arctan2(pose[0, 1, 1], pose[0, 1, 0]) - (np.pi / 2)))\n        trunk_side = 1 if trunk_side_angle > 30 else 0\n\n        if verbose:\n            utils.show_skeleton(pose, title=\"Trunk side angle: \" + str(round(trunk_side_angle, 2)))\n\n        # Neck position\n        pose, _ = utils.rotate_pose(pose, rotation_joint=8, m_coeff=-np.pi / 2)\n        pose -= pose[:, 1]\n        neck_angle = np.rad2deg((np.pi / 2) - np.arctan2(pose[0, 0, 1], pose[0, 0, 0])) - trunk_angle\n\n        if verbose:\n            utils.show_skeleton(pose, title=\"Neck angle: \" + str(round(neck_angle, 2)))\n\n        # Neck bending\n        pose, _ = utils.rotate_pose(pose, rotation_joint=8, m_coeff=np.pi / 2)\n        neck_side_angle = np.abs(np.rad2deg(np.abs(np.arctan2(pose[0, 0, 1], pose[0, 0, 0])) - (np.pi / 2)))\n        neck_side = 1 if neck_side_angle > 20 else 0\n\n        if verbose:\n            utils.show_skeleton(pose, title=\"Neck side angle: \" + str(round(neck_side_angle, 2)))\n\n        # Legs position\n        pose, _ = utils.rotate_pose(pose, rotation_joint=8, m_coeff=-np.pi / 2)\n        pose -= pose[:, 11]\n        legs_angle = np.rad2deg((np.pi / 2) + np.arctan2(pose[0, 12, 1], pose[0, 12, 0]))\n        step_size = abs(np.linalg.norm(pose[0, 10, :2] - pose[0, 13, :2]))\n        legs_walking = 1 if step_size > 0.1 else 0\n\n        if verbose:\n            title = \"Leg angle: \" + str(round(legs_angle, 2)) + \" Step size: \" + str(round(step_size, 2))\n            utils.show_skeleton(pose, title=title)\n\n        return np.array([neck_angle, neck_side, trunk_angle, trunk_side,\n                legs_walking, legs_angle, load])\n\n    @staticmethod\n    def get_arms_angles_from_pose_left(pose, verbose=False):\n        # type: (np.ndarray, bool) -> np.ndarray\n        '''\n        Get arms angles from pose (look at left)\n\n        :param pose: Pose (Joints coordinates)\n        :param verbose: If true show each pose for debugging\n\n        :return: Body params (upper_arm_angle, shoulder_raised, arm_abducted, leaning,\n                              lower_arm_angle, wrist_angle, wrist_twisted)\n        '''\n        pose = np.expand_dims(np.copy(pose), 0)\n        if verbose:\n            utils.show_skeleton(pose, title=\"GT pose\")\n\n        # Leaning\n        pose, _ = utils.rotate_pose(pose, rotation_joint=8)\n        pose -= (pose[:, 8] + pose[:, 11]) / 2\n\n        if quad(pose[0, 1]) < 3:\n            trunk_angle = np.rad2deg(np.arctan2(pose[0, 1, 1], pose[0, 1, 0]) - (np.pi / 2))\n        else:\n            trunk_angle = 270 + np.rad2deg(np.arctan2(pose[0, 1, 1], pose[0, 1, 0]))\n\n        leaning = 1 if trunk_angle > 30 else 0\n\n        if verbose:\n            utils.show_skeleton(pose, title=\"Leaning angle: \" + str(round(trunk_angle, 2)))\n\n        # Upper Arm position\n        pose, _ = utils.rotate_pose(pose, rotation_joint=8)\n        pose -= pose[:, 2]\n\n        if quad(pose[0, 3]) > 2:\n            upper_arm_angle = -np.rad2deg(np.arctan2(pose[0, 3, 1], pose[0, 3, 0]) + (np.pi / 2))\n        else:\n            upper_arm_angle = 270 - np.rad2deg(np.arctan2(pose[0, 3, 1], pose[0, 3, 0]))\n\n\n        upper_arm_angle += trunk_angle\n\n        if verbose:\n            utils.show_skeleton(pose, title=\"Upper Arms angle: \" + str(round(upper_arm_angle, 2)))\n\n        # Upper Arm Adjust\n        pose, _ = utils.rotate_pose(pose, rotation_joint=8, m_coeff=np.pi/2)\n        shoulder_step = pose[:, 2, 1] - pose[:, 1, 1]\n\n        if quad(pose[0, 3]) > 2:\n            arm_abducted_angle = -np.rad2deg(np.arctan2(pose[0, 3, 1], pose[0, 3, 0]) + (np.pi / 2))\n        else:\n            arm_abducted_angle = 270 - np.rad2deg(np.arctan2(pose[0, 3, 1], pose[0, 3, 0]))\n\n        shoulder_raised = 1 if shoulder_step > 0.02 else 0\n        arm_abducted = 1 if arm_abducted_angle > 45 else 0\n\n        if verbose:\n            print(shoulder_raised)\n            utils.show_skeleton(pose, title=\"Upper Arms abducted: \" + str(round(arm_abducted_angle, 2)))\n\n        # Lower Arm position\n        pose, _ = utils.rotate_pose(pose, rotation_joint=8, m_coeff=-np.pi/2)\n        pose -= pose[:, 3]\n\n        if quad(pose[0, 4]) > 2:\n            lower_arm_angle = -np.rad2deg(np.arctan2(pose[0, 4, 1], pose[0, 4, 0]) + (np.pi / 2))\n        else:\n            lower_arm_angle = 270 - np.rad2deg(np.arctan2(pose[0, 4, 1], pose[0, 4, 0]))\n\n        lower_arm_angle = lower_arm_angle + trunk_angle - upper_arm_angle\n\n        if verbose:\n            utils.show_skeleton(pose, title=\"Lower Arms angle: \" + str(round(lower_arm_angle, 2)))\n\n        # Wrist position\n        wrist_angle = 0\n        wrist_twisted = 0\n\n        if pose.shape[1] > 14:\n            pose -= pose[:, 4]\n            wrist_angle = np.rad2deg(np.arctan2(pose[0, 14, 1], pose[0, 14, 0]) - (np.pi / 2) )\n\n            if verbose:\n                utils.show_skeleton(pose, title=\"Wrist Angle: \" + str(round(wrist_angle, 2)))\n\n            pose, _ = utils.rotate_pose(pose, rotation_joint=8, m_coeff=-np.pi / 2)\n            wrist_twisted_angle = abs(np.rad2deg(np.arctan2(pose[0, 14, 1], pose[0, 14, 0]) - (np.pi / 2)))\n            wrist_twisted = 1 if wrist_twisted_angle > 30 else 0\n\n        return np.array([upper_arm_angle, shoulder_raised, arm_abducted, leaning,\n                lower_arm_angle, wrist_angle, wrist_twisted])\n\n\n    @staticmethod\n    def get_arms_angles_from_pose_right(pose, verbose=False):\n        # type: (np.ndarray, bool) -> np.ndarray\n        '''\n        Get arms angles from pose (look at right)\n\n        :param pose: Pose (Joints coordinates)\n        :param verbose: If true show each pose for debugging\n\n        :return: Body params (upper_arm_angle, shoulder_raised, arm_abducted, leaning,\n                               lower_arm_angle, wrist_angle, wrist_twisted)\n        '''\n        pose = np.expand_dims(np.copy(pose), 0)\n        if verbose:\n            utils.show_skeleton(pose, title=\"GT pose\")\n\n        pose, _ = utils.rotate_pose(pose, rotation_joint=8)\n        pose, _ = utils.rotate_pose(pose, rotation_joint=8, m_coeff=np.pi)\n\n        # Leaning\n        pose -= (pose[:, 8] + pose[:, 11]) / 2\n        trunk_angle = np.rad2deg((np.pi / 2) - np.arctan2(pose[0, 1, 1], pose[0, 1, 0]))\n        leaning = 1 if trunk_angle > 60 else 0\n\n        if verbose:\n            utils.show_skeleton(pose, title=\"Leaning angle: \" + str(round(trunk_angle, 2)))\n\n        # Upper Arm position\n        pose -= pose[:, 5]\n        if quad(pose[0, 6]) == 2:\n            upper_arm_angle = -(270 - np.rad2deg(np.arctan2(pose[0, 6, 1], pose[0, 6, 0])) - trunk_angle)\n        else:\n            upper_arm_angle = np.rad2deg((np.pi /2) + np.arctan2(pose[0, 6, 1], pose[0, 6, 0])) + trunk_angle\n\n        if verbose:\n            utils.show_skeleton(pose, title=\"Upper Arms angle: \" + str(round(upper_arm_angle, 2)))\n\n        # Upper Arm Adjust\n        pose, _ = utils.rotate_pose(pose, rotation_joint=8, m_coeff=np.pi / 2)\n        shoulder_step = pose[:, 5, 1] - pose[:, 1, 1]\n        arm_abducted_angle = abs(np.rad2deg((np.pi / 2) + np.arctan2(pose[0, 6, 1], pose[0, 6, 0])))\n        shoulder_raised = 1 if shoulder_step > 0.02 else 0\n        arm_abducted = 1 if arm_abducted_angle > 45 else 0\n\n        if verbose:\n            print(shoulder_raised)\n            utils.show_skeleton(pose, title=\"Upper Arms abducted: \" + str(round(arm_abducted_angle, 2)))\n\n        # Lower Arm position\n        pose, _ = utils.rotate_pose(pose, rotation_joint=8, m_coeff=-np.pi / 2)\n        pose -= pose[:, 6]\n        lower_arm_angle = np.rad2deg((np.pi / 2) + np.arctan2(pose[0, 7, 1], pose[0, 7, 0]) ) + trunk_angle - upper_arm_angle\n\n        if verbose:\n            utils.show_skeleton(pose, title=\"Lower Arms angle: \" + str(round(lower_arm_angle, 2)))\n\n        # Wrist position\n        wrist_angle = 0\n        wrist_twisted = 0\n\n        if pose.shape[1] > 14:\n            pose -= pose[:, 7]\n            wrist_angle = np.rad2deg((np.pi / 2) + np.arctan2(pose[0, 15, 1], pose[0, 15, 0]))\n\n            if verbose:\n                utils.show_skeleton(pose, title=\"Wrist Angle: \" + str(round(wrist_angle, 2)))\n\n            pose, _ = utils.rotate_pose(pose, rotation_joint=8, m_coeff=-np.pi / 2)\n            wrist_twisted_angle = abs(np.rad2deg((np.pi / 2) + np.arctan2(pose[0, 15, 1], pose[0, 15, 0])))\n            wrist_twisted = 1 if wrist_twisted_angle > 30 else 0\n\n\n        return np.array([upper_arm_angle, shoulder_raised, arm_abducted, leaning,\n                         lower_arm_angle, wrist_angle, wrist_twisted])\n\ndef quad(coord):\n    q = 0\n    if coord[0] >= 0 and coord[1] >= 0:\n        q = 1\n    elif coord[0] <= 0 and coord[1] >= 0:\n        q = 2\n    elif coord[0] <= 0 and coord[1] <= 0:\n        q = 3\n    elif coord[0] >= 0 and coord[1] <= 0:\n        q = 4\n    return q\n\nif __name__ == '__main__':\n\n    import doctest\n    doctest.testmod()\n\n    sample_pose = np.array([[ 0.08533354,  1.03611605,  0.09013124],\n                      [ 0.15391247,  0.91162637, -0.00353906],\n                      [ 0.22379057,  0.87361878,  0.11541229],\n                      [ 0.4084777 ,  0.69462843,  0.1775224 ],\n                      [ 0.31665226,  0.46389668,  0.16556387],\n                      [ 0.1239769 ,  0.82994377, -0.11715403],\n                      [ 0.08302169,  0.58146328, -0.19830338],\n                      [-0.06767788,  0.53928527, -0.00511249],\n                      [ 0.11368726,  0.49372503,  0.21275574],\n                      [ 0.069179  ,  0.07140968,  0.26841402],\n                      [ 0.10831762, -0.36339359,  0.34032449],\n                      [ 0.11368726,  0.41275504, -0.01171348],\n                      [ 0.        ,  0.        ,  0.        ],\n                      [ 0.02535541, -0.43954643,  0.04373671],\n                      [ 0.26709431,  0.33643749,  0.17985192],\n                      [-0.15117603,  0.49462711,  0.02703403]])\n\n    rebaScore = RebaScore()\n\n    body_params = rebaScore.get_body_angles_from_pose_right(sample_pose)\n    arms_params = rebaScore.get_arms_angles_from_pose_right(sample_pose)\n\n    rebaScore.set_body(body_params)\n    score_a, partial_a = rebaScore.compute_score_a()\n\n    rebaScore.set_arms(arms_params)\n    score_b, partial_b = rebaScore.compute_score_b()\n\n    score_c, caption = rebaScore.compute_score_c(score_a, score_b)\n\n    print(\"Score A: \", score_a, \"Partial: \", partial_a)\n    print(\"Score A: \", score_b, \"Partial: \", partial_b)\n    print(\"Score C: \", score_c, caption)\n", "meta": {"hexsha": "f05fff30d8ff945767e5a54e9eaea0fb23df0144", "size": 24071, "ext": "py", "lang": "Python", "max_stars_repo_path": "ergonomics/reba.py", "max_stars_repo_name": "rs9000/ergonomics", "max_stars_repo_head_hexsha": "78a41799c53b0fb3afbc09d30f0039104e739f80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-01T21:27:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-01T21:27:03.000Z", "max_issues_repo_path": "ergonomics/reba.py", "max_issues_repo_name": "rs9000/ergonomics", "max_issues_repo_head_hexsha": "78a41799c53b0fb3afbc09d30f0039104e739f80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-13T16:10:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-13T16:24:12.000Z", "max_forks_repo_path": "ergonomics/reba.py", "max_forks_repo_name": "rs9000/ergonomics", "max_forks_repo_head_hexsha": "78a41799c53b0fb3afbc09d30f0039104e739f80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-01T21:27:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T17:10:22.000Z", "avg_line_length": 37.3773291925, "max_line_length": 125, "alphanum_fraction": 0.5303061776, "include": true, "reason": "import numpy", "num_tokens": 7446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.19792188571386873}}
{"text": "# ======================================================================\n#\n#                           Brad T. Aagaard\n#                        U.S. Geological Survey\n#\n# ======================================================================\n#\n\nimport os\nimport logging\nfrom importlib import import_module\nimport numpy\n\nfrom . import analysis_utils\nfrom . import gdalraster\n\nclass CostSavings(object):\n    \"\"\"Cost savings weighted by area and population.\n    \"\"\"\n    \n    def __init__(self, config):\n        self.config = config\n        return\n\n    def compute(self, event, shakemap, alerts, shakingTime, populationDensity, magAlertThreshold, mmiAlertThreshold, plotAlertMaps=False):\n\n        functionPath = self.config.get(\"mmi_predicted\", \"function\").split(\".\")\n        fn = getattr(import_module(\".\".join(functionPath[:-1])), functionPath[-1])\n            \n        shape = shakemap.data[\"mmi\"].shape\n        warningTimeZero = numpy.zeros((1,), dtype=\"timedelta64[us]\")\n        warningTime = gdalraster.NO_DATA_VALUE * 1.0e+6 * numpy.ones(shape, dtype=\"timedelta64[us]\")\n        mmiPred = gdalraster.NO_DATA_VALUE * numpy.ones(shape, numpy.float32)\n\n        gmpe = self.config.get(\"mmi_predicted\", \"gmpe\")\n        gmice = self.config.get(\"mmi_predicted\", \"gmice\")\n        alertLatency = numpy.timedelta64(int(self.config.getfloat(\"alerts\", \"alert_latency_sec\")*1.0e+3), \"ms\")\n        if gmice == \"default\":\n            gmice = shakemap.gmiceGrid\n        \n        thresholdReached = False\n        for alert in alerts:\n            alertTime = numpy.datetime64(alert[\"timestamp\"]) + alertLatency\n\n            if alertTime > numpy.max(shakingTime):\n                # Skip alerts with no positive warning times in\n                # domain. Changes in estimated earthquake location\n                # could result in later alerts having positive warning\n                # times.\n                logging.getLogger(__name__).debug(\"Skipping alert version {ver} with no positive warning times.\".format(ver=alert[\"version\"]))\n                continue\n            if not thresholdReached and alert[\"magnitude\"] < magAlertThreshold:\n                continue\n            else:\n                if not thresholdReached:\n                    wtime = analysis_utils.timedelta_to_seconds(alertTime - numpy.datetime64(event[\"origin_time\"]))\n                    msg = \"Alert threshold reached at {tstamp}, {wtime:.1f}s after origin time.\".format(tstamp=alertTime, wtime=wtime)\n                    logging.getLogger(__name__).info(msg)\n                    thresholdReached = True\n                \n            mmiPredCur = fn(alert, shakemap.data, gmpe, gmice)\n            warningTimeCur = shakingTime - alertTime\n            \n            if plotAlertMaps:\n                plotsDir = self.config.get(\"files\", \"plots_dir\")\n                if not os.path.isdir(plotsDir):\n                    os.makedirs(plotsDir)\n                filename = analysis_utils.analysis_event_label(self.config, self.eqId, magAlertThreshold, mmiAlertThreshold)+\"_alert_snapshot.tiff\"\n                values = [\n                    (\"mmi_pred\", mmiPredCur,),\n                    (\"warning_time\", analysis_utils.timedelta_to_seconds(warningTimeCur),),\n                ]\n                gdalraster.write(filename, values, shakemap.num_lon(), shakemap.num_lat(), shakemap.spatial_ref(), shakemap.geo_transform())\n                mapPanels = maps.MapPanels(self.config)\n                mapPanels.load_data(event[\"event_id\"], alert=alert)\n                tafterOT = analysis_utils.timedelta_to_seconds(alertTime-numpy.datetime64(event[\"origin_time\"]))\n                mapPanels.mmi_warning_time(tafterOT)\n            \n            # Update alert time if greater than previous\n            maskAlert = numpy.bitwise_and(warningTimeCur > warningTime, mmiPredCur >= mmiAlertThreshold)\n            warningTime[maskAlert] = warningTimeCur[maskAlert]\n\n            # Update predicted MMI if greater than previous AND\n            # positive warning time. Assumes action will be taken if\n            # alert threshold is reached (cannot be undone if later\n            # updates reduce predicted MMI).\n            maskMMI = numpy.bitwise_and(mmiPredCur > mmiPred, warningTimeCur >= warningTimeZero)\n            mmiPred[maskMMI] = mmiPredCur[maskMMI]\n\n        filename = \"analysis_\" + analysis_utils.analysis_event_label(self.config, event[\"event_id\"], magAlertThreshold, mmiAlertThreshold) + \".tiff\"\n        metrics = self._cost(mmiPred, shakemap, warningTime, populationDensity, mmiAlertThreshold, filename)\n        return metrics\n\n    def _cost(self, mmiPred, shakemap, warningTime, populationDensity, mmiAlertThreshold, filename):\n        \"\"\"Compute cost savings metrics.\n        \"\"\"\n        mmiObs = shakemap.data[\"mmi\"]\n        \n        # Compute costNoEEW, costEEW, costPerfectEEW, costSavings\n        objectPath = self.config.get(\"fragility_curves\", \"object\").split(\".\")\n        fragilityOptions = dict(self.config.items(\"fragility_curves\"))\n        fragilityOptions.pop(\"object\")\n        fragilityOptions.pop(\"label\")\n        fragilityOptions = {k: float(v) for k,v in fragilityOptions.items()}\n        fragility = getattr(import_module(\".\".join(objectPath[:-1])), objectPath[-1])(**fragilityOptions)\n        \n        costDamage = fragility.cost_damage(mmiObs)\n        costActionObs = fragility.cost_action(mmiObs)\n        costNoEEW = costDamage\n        costPerfectEEW = costDamage*(costDamage < costActionObs) + costActionObs*(costDamage >= costActionObs)\n        costEEW = fragility.cost_action(mmiPred)*(mmiPred >= mmiAlertThreshold) + costDamage*(mmiPred < mmiAlertThreshold)\n\n        pixelArea = shakemap.pixel_area(self.config.get(\"shakemap\", \"projection\"))\n        areaCostNoEEW = numpy.sum(pixelArea * costNoEEW)\n        areaCostPerfectEEW = numpy.sum(pixelArea * costPerfectEEW)\n        areaCostEEW = numpy.sum(pixelArea * costEEW)\n        areaDamage = numpy.sum(pixelArea * (costDamage > 0.0))\n        areaAlert = numpy.sum(pixelArea * (mmiPred >= mmiAlertThreshold))\n        areaAlertPerfect = numpy.sum(pixelArea * (costDamage > costActionObs))\n        \n        popCostNoEEW = numpy.sum(populationDensity * pixelArea * costNoEEW)\n        popCostPerfectEEW = numpy.sum(populationDensity * pixelArea * costPerfectEEW)\n        popCostEEW = numpy.sum(populationDensity * pixelArea * costEEW)\n        popDamage = numpy.sum(pixelArea * populationDensity * (costDamage > 0.0))\n        popAlert = numpy.sum(pixelArea * populationDensity * (mmiPred >= mmiAlertThreshold))\n        popAlertPerfect = numpy.sum(pixelArea * populationDensity * (costDamage > costActionObs))\n\n        # Alert categories TN(0),FN(1),FP(2),TP(3)\n        alertCategory = numpy.zeros(costDamage.shape)\n        maskTN = numpy.bitwise_and(mmiPred < mmiAlertThreshold, costDamage < costActionObs)\n        maskFN = numpy.bitwise_and(mmiPred < mmiAlertThreshold, costDamage >= costActionObs)\n        maskFP = numpy.bitwise_and(mmiPred >= mmiAlertThreshold, costDamage < costActionObs)\n        maskTP = numpy.bitwise_and(mmiPred >= mmiAlertThreshold, costDamage >= costActionObs)\n        alertCategory = maskTN*0.0 + maskFN*1.0 + maskFP*2.0 + maskTP*3.0\n\n        values = [\n            (\"mmi_obs\", mmiObs,),\n            (\"mmi_pred\", mmiPred,),\n            (\"warning_time\", analysis_utils.timedelta_to_seconds(warningTime),),\n            (\"population_density\", populationDensity,),\n            (\"cost_no_eew\", costNoEEW,),\n            (\"cost_perfect_eew\", costPerfectEEW,),\n            (\"cost_eew\", costEEW,),\n            (\"alert_category\", alertCategory,),\n            (\"pixel_area\", pixelArea,),\n            ]\n        cacheDir = self.config.get(\"files\", \"analysis_cache_dir\")\n        if not os.path.isdir(cacheDir):\n            os.makedirs(cacheDir)\n        gdalraster.write(os.path.join(cacheDir, filename), values, shakemap.num_lon(), shakemap.num_lat(), shakemap.spatial_ref(), shakemap.geo_transform())\n\n        metrics = {\n            \"area_damage\": areaDamage,\n            \"area_alert\": areaAlert,\n            \"area_alert_perfect\": areaAlertPerfect,\n            \"area_costsavings_eew\": areaCostNoEEW - areaCostEEW,\n            \"area_costsavings_perfecteew\": areaCostNoEEW - areaCostPerfectEEW,\n            \"population_damage\": popDamage,\n            \"population_alert\": popAlert,\n            \"population_alert_perfect\": popAlertPerfect,\n            \"population_costsavings_eew\": popCostNoEEW - popCostEEW,\n            \"population_costsavings_perfecteew\": popCostNoEEW - popCostPerfectEEW,\n            }\n        return metrics\n\n# End of file\n", "meta": {"hexsha": "d71388e654d77c12a75599d7934ed88f1d5d5d77", "size": 8563, "ext": "py", "lang": "Python", "max_stars_repo_path": "eewperformance/perfmetrics.py", "max_stars_repo_name": "baagaard-usgs/eew-analyze", "max_stars_repo_head_hexsha": "5f9ec7d6eecd693fc0a3147d2695c957da64d4b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-05-24T01:41:46.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-24T01:41:46.000Z", "max_issues_repo_path": "eewperformance/perfmetrics.py", "max_issues_repo_name": "baagaard-usgs/eew-performance", "max_issues_repo_head_hexsha": "5f9ec7d6eecd693fc0a3147d2695c957da64d4b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eewperformance/perfmetrics.py", "max_forks_repo_name": "baagaard-usgs/eew-performance", "max_forks_repo_head_hexsha": "5f9ec7d6eecd693fc0a3147d2695c957da64d4b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.2754491018, "max_line_length": 156, "alphanum_fraction": 0.6303865468, "include": true, "reason": "import numpy", "num_tokens": 1954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.19786854901222004}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport abc\nimport copy\nimport inspect\nimport logging\nfrom collections.abc import Sequence\nimport numpy as np\nimport scipy.interpolate\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\nfrom astropy.io import fits\nfrom astropy.table import Column, Table, hstack\nfrom astropy.utils import lazyproperty\nfrom gammapy.utils.interpolation import interpolation_scale\nfrom .utils import INVALID_INDEX, edges_from_lo_hi, find_bands_hdu, find_hdu\n\n__all__ = [\"MapCoord\", \"Geom\", \"MapAxis\", \"MapAxes\"]\n\nlog = logging.getLogger(__name__)\n\n\ndef flat_if_equal(array):\n    if array.ndim == 2:\n        return array[0]\n    else:\n        return array\n\ndef get_shape(param):\n    if param is None:\n        return tuple()\n\n    if not isinstance(param, tuple):\n        param = [param]\n\n    return max([np.array(p, ndmin=1).shape for p in param])\n\n\ndef skycoord_to_lonlat(skycoord, frame=None):\n    \"\"\"Convert SkyCoord to lon, lat, frame.\n\n    Returns\n    -------\n    lon : `~numpy.ndarray`\n        Longitude in degrees.\n    lat : `~numpy.ndarray`\n        Latitude in degrees.\n    \"\"\"\n    if frame:\n        skycoord = skycoord.transform_to(frame)\n\n    return skycoord.data.lon.deg, skycoord.data.lat.deg, skycoord.frame.name\n\n\ndef pix_tuple_to_idx(pix):\n    \"\"\"Convert a tuple of pixel coordinate arrays to a tuple of pixel indices.\n\n    Pixel coordinates are rounded to the closest integer value.\n\n    Parameters\n    ----------\n    pix : tuple\n        Tuple of pixel coordinates with one element for each dimension\n\n    Returns\n    -------\n    idx : `~numpy.ndarray`\n        Array of pixel indices\n    \"\"\"\n    idx = []\n    for p in pix:\n        p = np.array(p, ndmin=1)\n        if np.issubdtype(p.dtype, np.integer):\n            idx += [p]\n        else:\n            p_idx = np.rint(p).astype(int)\n            p_idx[~np.isfinite(p)] = INVALID_INDEX.int\n            idx += [p_idx]\n\n    return tuple(idx)\n\n\ndef coord_to_pix(edges, coord, interp=\"lin\"):\n    \"\"\"Convert axis to pixel coordinates for given interpolation scheme.\"\"\"\n    scale = interpolation_scale(interp)\n\n    interp_fn = scipy.interpolate.interp1d(\n        scale(edges), np.arange(len(edges), dtype=float), fill_value=\"extrapolate\"\n    )\n\n    return interp_fn(scale(coord))\n\n\ndef pix_to_coord(edges, pix, interp=\"lin\"):\n    \"\"\"Convert pixel to grid coordinates for given interpolation scheme.\"\"\"\n    scale = interpolation_scale(interp)\n\n    interp_fn = scipy.interpolate.interp1d(\n        np.arange(len(edges), dtype=float), scale(edges), fill_value=\"extrapolate\"\n    )\n\n    return scale.inverse(interp_fn(pix))\n\n\nclass MapAxes(Sequence):\n    \"\"\"MapAxis container class.\n\n    Parameters\n    ----------\n    axes : list of `MapAxis`\n        List of map axis objects.\n    \"\"\"\n\n    def __init__(self, axes, n_spatial_axes=None):\n        unique_names = []\n\n        for ax in axes:\n            if ax.name in unique_names:\n                raise (\n                    ValueError(f\"Axis names must be unique, got: '{ax.name}' twice.\")\n                )\n            unique_names.append(ax.name)\n\n        self._axes = axes\n        self._n_spatial_axes = n_spatial_axes\n\n    @property\n    def reverse(self):\n        \"\"\"Reverse axes order\"\"\"\n        return MapAxes(self[::-1])\n\n    @property\n    def iter_with_reshape(self):\n        \"\"\"Iterate by shape\"\"\"\n        for idx, axis in enumerate(self):\n            # Extract values for each axis, default: nodes\n            shape = [1] * len(self)\n            shape[idx] = -1\n            if self._n_spatial_axes:\n                shape = shape[::-1] + [1, ] * self._n_spatial_axes\n            yield tuple(shape), axis\n\n    def get_coord(self, mode=\"center\", axis_name=None):\n        \"\"\"Get axes coordinates\n\n        Parameters\n        ----------\n        mode : {\"center\", \"edges\"}\n            Coordinate center or edges\n        axis_name : str\n            Axis name for which mode='edges' applies\n\n        Returns\n        -------\n        coords : dict of `~astropy.units.Quanity`\n            Map coordinates\n        \"\"\"\n        coords = {}\n\n        for shape, axis in self.iter_with_reshape:\n            if mode == \"edges\" and axis.name == axis_name:\n                coord = axis.edges\n            else:\n                coord = axis.center\n            coords[axis.name] = coord.reshape(shape)\n\n        return coords\n\n    def bin_volume(self):\n        \"\"\"Bin axes volume\n\n        Returns\n        -------\n        bin_volume : `~astropy.units.Quantity`\n            Bin volume\n        \"\"\"\n        bin_volume = np.array(1)\n\n        for shape, axis in self.iter_with_reshape:\n            bin_volume = bin_volume * axis.bin_width.reshape(shape)\n\n        return bin_volume\n\n    @property\n    def shape(self):\n        \"\"\"Shape of the axes\"\"\"\n        return tuple([ax.nbin for ax in self])\n\n    @property\n    def names(self):\n        \"\"\"Names of the axes\"\"\"\n        return [ax.name for ax in self]\n\n    def index(self, axis_name):\n        \"\"\"Get index in list\"\"\"\n        return self.names.index(axis_name)\n\n    def index_data(self, axis_name):\n        \"\"\"Get data index of the axes\n\n        Parameters\n        ----------\n        axis_name : str\n            Name of the axis.\n\n        Returns\n        -------\n        idx : int\n            Data index\n        \"\"\"\n        idx = self.names.index(axis_name)\n        return len(self) - idx - 1\n\n    def __len__(self):\n        return len(self._axes)\n\n    def __add__(self, other):\n        return self.__class__(list(self) + list(other))\n\n    def upsample(self, factor, axis_name):\n        \"\"\"Upsample axis by a given factor\n\n        Parameters\n        ----------\n        factor : int\n            Upsampling factor.\n        axis_name : str\n            Axis to upsample.\n\n        Returns\n        -------\n        axes : `MapAxes`\n            Map axes\n        \"\"\"\n        axes = []\n\n        for ax in self:\n            if ax.name == axis_name:\n                ax = ax.upsample(factor=factor)\n\n            axes.append(ax.copy())\n\n        return self.__class__(axes=axes)\n\n    def replace(self, axis):\n        \"\"\"Replace a give axis\n\n        Parameters\n        ----------\n        axis : `MapAxis`\n            Map axis\n\n        Returns\n        -------\n        axes : MapAxes\n            Map axe\n        \"\"\"\n        axes = []\n\n        for ax in self:\n            if ax.name == axis.name:\n                ax = axis\n\n            axes.append(ax)\n\n        return self.__class__(axes=axes)\n\n    def resample(self, axis):\n        \"\"\"Resample axis binning.\n\n        This method groups the existing bins into a new binning.\n\n        Parameters\n        ----------\n        axis : `MapAxis`\n            New map axis.\n\n        Returns\n        -------\n        axes : `MapAxes`\n            Axes object with resampled axis.\n        \"\"\"\n        axis_self = self[axis.name]\n        groups = axis_self.group_table(axis.edges)\n\n        # Keep only normal bins\n        groups = groups[groups[\"bin_type\"] == \"normal   \"]\n\n        edges = edges_from_lo_hi(\n            groups[axis.name + \"_min\"].quantity, groups[axis.name + \"_max\"].quantity,\n        )\n\n        axis_resampled = MapAxis.from_edges(\n            edges=edges, interp=axis.interp, name=axis.name\n        )\n\n        axes = []\n        for ax in self:\n            if ax.name == axis.name:\n                axes.append(axis_resampled)\n            else:\n                axes.append(ax.copy())\n\n        return self.__class__(axes=axes)\n\n    def downsample(self, factor, axis_name):\n        \"\"\"Downsample axis by a given factor\n\n        Parameters\n        ----------\n        factor : int\n            Upsampling factor.\n        axis_name : str\n            Axis to upsample.\n\n        Returns\n        -------\n        axes : `MapAxes`\n            Map axes\n\n        \"\"\"\n        axes = []\n\n        for ax in self:\n            if ax.name == axis_name:\n                ax = ax.downsample(factor=factor)\n\n            axes.append(ax.copy())\n\n        return self.__class__(axes=axes)\n\n    def squash(self, axis_name):\n        \"\"\"Squash axis.\n\n        Parameters\n        ----------\n        axis_name : str\n            Axis to squash.\n\n        Returns\n        -------\n        axes : `MapAxes`\n            Axes with squashed axis.\n        \"\"\"\n        axes = []\n\n        for ax in self:\n            if ax.name == axis_name:\n                ax = ax.squash()\n            axes.append(ax.copy())\n\n        return self.__class__(axes=axes)\n\n    def pad(self, axis_name, pad_width):\n        \"\"\"Pad axes\n\n        Parameters\n        ----------\n        axis_name : str\n            Name of the axis to pad.\n        pad_width : int or tuple of int\n            Pad width\n\n        Returns\n        -------\n        axes : `MapAxes`\n            Axes with squashed axis.\n\n        \"\"\"\n        axes = []\n\n        for ax in self:\n            if ax.name == axis_name:\n                ax = ax.pad(pad_width=pad_width)\n            axes.append(ax)\n\n        return self.__class__(axes=axes)\n\n    def drop(self, axis_name):\n        \"\"\"Drop an axis.\n\n        Parameters\n        ----------\n        axis_name : str\n            Name of the axis to remove.\n\n        Returns\n        -------\n        axes : `MapAxes`\n            Axes with squashed axis.\n        \"\"\"\n        axes = []\n        for ax in self:\n            if ax.name == axis_name:\n                continue\n            axes.append(ax.copy())\n\n        return self.__class__(axes=axes)\n\n    def __getitem__(self, idx):\n        if isinstance(idx, (int, slice)):\n            return self._axes[idx]\n        elif isinstance(idx, str):\n            for ax in self._axes:\n                if ax.name == idx:\n                    return ax\n            raise KeyError(f\"No axes: {idx!r}\")\n        elif isinstance(idx, list):\n            axes = []\n            for name in idx:\n                axes.append(self[name])\n\n            return self.__class__(axes=axes)\n        else:\n            raise TypeError(f\"Invalid type: {type(idx)!r}\")\n\n    def coord_to_idx(self, coord, clip=True):\n        \"\"\"Transform from axis to pixel indices.\n\n        Parameters\n        ----------\n        coord : dict of `~numpy.ndarray` or `MapCoord`\n            Array of axis coordinate values.\n\n        Returns\n        -------\n        pix : tuple of `~numpy.ndarray`\n            Array of pixel indices values.\n        \"\"\"\n        return tuple([ax.coord_to_idx(coord[ax.name], clip=clip) for ax in self])\n\n    def coord_to_pix(self, coord):\n        \"\"\"Transform from axis to pixel coordinates.\n\n        Parameters\n        ----------\n        coord : dict of `~numpy.ndarray`\n            Array of axis coordinate values.\n\n        Returns\n        -------\n        pix : tuple of `~numpy.ndarray`\n            Array of pixel coordinate values.\n        \"\"\"\n        return tuple([ax.coord_to_pix(coord[ax.name]) for ax in self])\n\n    def pix_to_coord(self, pix):\n        \"\"\"Convert pixel coordinates to map coordinates.\n\n        Parameters\n        ----------\n        pix : tuple\n            Tuple of pixel coordinates.\n\n        Returns\n        -------\n        coords : tuple\n            Tuple of map coordinates.\n        \"\"\"\n        return tuple([ax.pix_to_coord(p) for ax, p in zip(self, pix)])\n\n    def pix_to_idx(self, pix, clip=False):\n        \"\"\"Convert pix to idx\n\n        Parameters\n        ----------\n        pix : tuple of `~numpy.ndarray`\n            Pixel coordinates.\n        clip : bool\n            Choose whether to clip indices to the valid range of the\n            axis.  If false then indices for coordinates outside\n            the axi range will be set -1.\n\n        Returns\n        -------\n        idx : tuple `~numpy.ndarray`\n            Pixel indices.\n        \"\"\"\n        idx = []\n\n        for pix_array, ax in zip(pix, self):\n            idx.append(ax.pix_to_idx(pix_array, clip=clip))\n\n        return tuple(idx)\n\n    def slice_by_idx(self, slices):\n        \"\"\"Create a new geometry by slicing the non-spatial axes.\n\n        Parameters\n        ----------\n        slices : dict\n            Dict of axes names and integers or `slice` object pairs. Contains one\n            element for each non-spatial dimension. For integer indexing the\n            corresponding axes is dropped from the map. Axes not specified in the\n            dict are kept unchanged.\n\n        Returns\n        -------\n        geom : `~Geom`\n            Sliced geometry.\n        \"\"\"\n        axes = []\n        for ax in self:\n            ax_slice = slices.get(ax.name, slice(None))\n\n            # in the case where isinstance(ax_slice, int) the axes is dropped\n            if isinstance(ax_slice, slice):\n                ax_sliced = ax.slice(ax_slice)\n                axes.append(ax_sliced.copy())\n\n        return self.__class__(axes=axes)\n\n    def to_header(self, format=\"gadf\"):\n        \"\"\"Convert axes to FITS header\n\n        Parameters\n        ----------\n        format : {\"gadf\"}\n            Header format\n\n        Returns\n        -------\n        header : `~astropy.io.fits.Header`\n            FITS header.\n        \"\"\"\n        header = fits.Header()\n\n        for idx, ax in enumerate(self, start=1):\n            header_ax = ax.to_header(format=format, idx=idx)\n            header.update(header_ax)\n\n        return header\n\n    def to_table(self, format=\"gadf\"):\n        \"\"\"Convert axes to table\n\n        Parameters\n        ----------\n        format : {\"gadf\", \"gadf-dl3\", \"fgst-ccube\", \"fgst-template\", \"ogip\", \"ogip-sherpa\", \"ogip-arf\", \"ogip-arf-sherpa\"}\n            Format to use.\n\n        Returns\n        -------\n        table : `~astropy.table.Table`\n            Table with axis data\n        \"\"\"\n        if format == \"gadf-dl3\":\n            tables = []\n\n            for ax in self:\n                tables.append(ax.to_table(format=format))\n\n            table = hstack(tables)\n        elif format in [\"gadf\", \"fgst-ccube\", \"fgst-template\"]:\n            table = Table()\n            table[\"CHANNEL\"] = np.arange(np.prod(self.shape))\n\n            axes_ctr = np.meshgrid(*[ax.center for ax in self])\n            axes_min = np.meshgrid(*[ax.edges[:-1] for ax in self])\n            axes_max = np.meshgrid(*[ax.edges[1:] for ax in self])\n\n            for idx, ax in enumerate(self):\n                name = ax.name.upper()\n\n                if name == \"ENERGY\":\n                    colnames = [\"ENERGY\", \"E_MIN\", \"E_MAX\"]\n                else:\n                    colnames = [name, name + \"_MIN\", name + \"_MAX\"]\n\n                for colname, v in zip(colnames, [axes_ctr, axes_min, axes_max]):\n                    table[colname] = np.ravel(v[idx]).astype(np.float32)\n        elif format in [\"ogip\", \"ogip-sherpa\", \"ogip\", \"ogip-arf\"]:\n            energy_axis = self[\"energy\"]\n            table = energy_axis.to_table(format=format)\n        else:\n            raise ValueError(f\"Unsupported format: '{format}'\")\n\n        return table\n\n    def to_table_hdu(self, format=\"gadf\", hdu_bands=None):\n        \"\"\"Make FITS table columns for map axes.\n\n        Parameters\n        ----------\n        format : {\"gadf\", \"fgst-ccube\", \"fgst-template\"}\n            Format to use.\n        hdu_bands : str\n            Name of the bands HDU to use.\n\n        Returns\n        -------\n        hdu : `~astropy.io.fits.BinTableHDU`\n            Bin table HDU.\n        \"\"\"\n        # FIXME: Check whether convention is compatible with\n        #  dimensionality of geometry and simplify!!!\n\n        if format in [\"fgst-ccube\", \"ogip\", \"ogip-sherpa\"]:\n            hdu_bands = \"EBOUNDS\"\n        elif format == \"fgst-template\":\n            hdu_bands = \"ENERGIES\"\n        elif format == \"gadf\" or format is None:\n            if hdu_bands is None:\n                hdu_bands = \"BANDS\"\n        else:\n            raise ValueError(f\"Unknown format {format}\")\n\n        table = self.to_table(format=format)\n        header = self.to_header(format=format)\n        return fits.BinTableHDU(table, name=hdu_bands, header=header)\n\n    @classmethod\n    def from_table_hdu(cls, hdu, format=\"gadf\"):\n        \"\"\"Create MapAxes from BinTableHDU\n\n        Parameters\n        ----------\n        hdu : `~astropy.io.fits.BinTableHDU`\n            Bin table HDU\n\n\n        Returns\n        -------\n        axes : `MapAxes`\n            Map axes object\n        \"\"\"\n        if hdu is None:\n            return cls([])\n\n        table = Table.read(hdu)\n        return cls.from_table(table, format=format)\n\n    @classmethod\n    def from_table(cls, table, format=\"gadf\"):\n        \"\"\"Create MapAxes from BinTableHDU\n\n        Parameters\n        ----------\n        table : `~astropy.table.Table`\n            Bin table HDU\n        format : {\"gadf\", \"gadf-dl3\", \"fgst-ccube\", \"fgst-template\", \"fgst-bexcube\", \"ogip-arf\"}\n            Format to use.\n\n        Returns\n        -------\n        axes : `MapAxes`\n            Map axes object\n        \"\"\"\n        from gammapy.irf.io import IRF_DL3_AXES_SPECIFICATION\n\n        axes = []\n\n        # Formats that support only one energy axis\n        if format in [\n            \"fgst-ccube\",\n            \"fgst-template\",\n            \"fgst-bexpcube\",\n            \"ogip\",\n            \"ogip-arf\",\n        ]:\n            axes.append(MapAxis.from_table(table, format=format))\n        elif format == \"gadf\":\n            # This limits the max number of axes to 5\n            for idx in range(5):\n                axcols = table.meta.get(\"AXCOLS{}\".format(idx + 1))\n                if axcols is None:\n                    break\n\n                axis = MapAxis.from_table(table, format=format, idx=idx)\n                axes.append(axis)\n        elif format == \"gadf-dl3\":\n            for column_prefix in IRF_DL3_AXES_SPECIFICATION.keys():\n                try:\n                    axis = MapAxis.from_table(\n                        table, format=format, column_prefix=column_prefix\n                    )\n                except KeyError:\n                    continue\n                axes.append(axis)\n        else:\n            raise ValueError(f\"Unsupported format: '{format}'\")\n\n        return cls(axes)\n\n    @classmethod\n    def from_default(cls, axes, n_spatial_axes=None):\n        \"\"\"Make a sequence of `~MapAxis` objects.\"\"\"\n        if axes is None:\n            return cls([])\n\n        axes_out = []\n        for idx, ax in enumerate(axes):\n            if isinstance(ax, np.ndarray):\n                ax = MapAxis(ax)\n\n            if ax.name == \"\":\n                ax.name = f\"axis{idx}\"\n\n            axes_out.append(ax)\n\n        return cls(axes_out, n_spatial_axes=n_spatial_axes)\n\n    def assert_names(self, required_names):\n        \"\"\"Assert required axis names and order\n\n        Parameters\n        ----------\n        required_names : list of str\n            Required\n        \"\"\"\n        message = (\"Incorrect axis order or names. Expected axis \"\n                   f\"order: {required_names}, got: {self.names}.\")\n\n        if not len(self) == len(required_names):\n            raise ValueError(message)\n\n        try:\n            for ax, required_name in zip(self, required_names):\n                ax.assert_name(required_name)\n\n        except ValueError:\n            raise ValueError(message)\n\n    @property\n    def center_coord(self):\n        \"\"\"Center coordinates\"\"\"\n        return tuple([ax.pix_to_coord((float(ax.nbin) - 1.0) / 2.0) for ax in self])\n\n\nclass MapAxis:\n    \"\"\"Class representing an axis of a map.\n\n    Provides methods for\n    transforming to/from axis and pixel coordinates.  An axis is\n    defined by a sequence of node values that lie at the center of\n    each bin.  The pixel coordinate at each node is equal to its index\n    in the node array (0, 1, ..).  Bin edges are offset by 0.5 in\n    pixel coordinates from the nodes such that the lower/upper edge of\n    the first bin is (-0.5,0.5).\n\n    Parameters\n    ----------\n    nodes : `~numpy.ndarray` or `~astropy.units.Quantity`\n        Array of node values.  These will be interpreted as either bin\n        edges or centers according to ``node_type``.\n    interp : str\n        Interpolation method used to transform between axis and pixel\n        coordinates.  Valid options are 'log', 'lin', and 'sqrt'.\n    name : str\n        Axis name\n    node_type : str\n        Flag indicating whether coordinate nodes correspond to pixel\n        edges (node_type = 'edge') or pixel centers (node_type =\n        'center').  'center' should be used where the map values are\n        defined at a specific coordinate (e.g. differential\n        quantities). 'edge' should be used where map values are\n        defined by an integral over coordinate intervals (e.g. a\n        counts histogram).\n    unit : str\n        String specifying the data units.\n    \"\"\"\n\n    # TODO: Cache an interpolation object?\n    def __init__(self, nodes, interp=\"lin\", name=\"\", node_type=\"edges\", unit=\"\"):\n        self._name = name\n\n        if len(nodes) != len(np.unique(nodes)):\n            raise ValueError(\"MapAxis: node values must be unique\")\n\n        if ~(np.all(nodes == np.sort(nodes)) or np.all(nodes[::-1] == np.sort(nodes))):\n            raise ValueError(\"MapAxis: node values must be sorted\")\n\n        if len(nodes) == 1 and node_type == \"center\":\n            raise ValueError(\"Single bins can only be used with node-type 'edges'\")\n\n        if isinstance(nodes, u.Quantity):\n            unit = nodes.unit if nodes.unit is not None else \"\"\n            nodes = nodes.value\n        else:\n            nodes = np.array(nodes)\n\n        self._unit = u.Unit(unit)\n        self._nodes = nodes.astype(float)\n        self._node_type = node_type\n        self._interp = interp\n\n        if (self._nodes < 0).any() and interp != \"lin\":\n            raise ValueError(\n                f\"Interpolation scaling {interp!r} only support for positive node values.\"\n            )\n\n        # Set pixel coordinate of first node\n        if node_type == \"edges\":\n            self._pix_offset = -0.5\n            nbin = len(nodes) - 1\n        elif node_type == \"center\":\n            self._pix_offset = 0.0\n            nbin = len(nodes)\n        else:\n            raise ValueError(f\"Invalid node type: {node_type!r}\")\n\n        self._nbin = nbin\n\n    def assert_name(self, required_name):\n        \"\"\"Assert axis name if a specific one is required.\n\n        Parameters\n        ----------\n        required_name : str\n            Required\n        \"\"\"\n        if self.name != required_name:\n            raise ValueError(\n                \"Unexpected axis name,\"\n                f' expected \"{required_name}\", got: \"{self.name}\"'\n            )\n\n    def is_aligned(self, other, atol=2e-2):\n        \"\"\"Check if other map axis is aligned.\n\n        Two axes are aligned if their center coordinate values map to integers\n        on the other axes as well and if the interpolation modes are equivalent.\n\n        Parameters\n        ----------\n        other : `MapAxis`\n            Other map axis.\n        atol : float\n            Absolute numerical tolerance for the comparison measured in bins.\n\n        Returns\n        -------\n        aligned : bool\n            Whether the axes are aligned\n        \"\"\"\n        pix = self.coord_to_pix(other.center)\n        pix_other = other.coord_to_pix(self.center)\n        pix_all = np.append(pix, pix_other)\n        aligned = np.allclose(np.round(pix_all) - pix_all, 0, atol=atol)\n        return aligned and self.interp == other.interp\n\n    def __eq__(self, other):\n        if not isinstance(other, self.__class__):\n            return NotImplemented\n\n        # TODO: implement an allclose method for MapAxis and call it here\n        if self.edges.shape != other.edges.shape:\n            return False\n        if self.unit.is_equivalent(other.unit) is False:\n            return False\n        return (\n            np.allclose(\n                self.edges.to(other.unit).value, other.edges.value, atol=1e-6, rtol=1e-6\n            )\n            and self._node_type == other._node_type\n            and self._interp == other._interp\n            and self.name.upper() == other.name.upper()\n        )\n\n    def __ne__(self, other):\n        return not self.__eq__(other)\n\n    def __hash__(self):\n        return id(self)\n\n    @property\n    def is_energy_axis(self):\n        return self.name in [\"energy\", \"energy_true\"]\n\n    @property\n    def interp(self):\n        \"\"\"Interpolation scale of the axis.\"\"\"\n        return self._interp\n\n    @property\n    def name(self):\n        \"\"\"Name of the axis.\"\"\"\n        return self._name\n\n    @name.setter\n    def name(self, value):\n        \"\"\"Name of the axis.\"\"\"\n        self._name = value\n\n    @lazyproperty\n    def edges(self):\n        \"\"\"Return array of bin edges.\"\"\"\n        pix = np.arange(self.nbin + 1, dtype=float) - 0.5\n        return u.Quantity(self.pix_to_coord(pix), self._unit, copy=False)\n\n    @property\n    def as_xerr(self):\n        \"\"\"Return tuple of xerr to be used with plt.errorbar()\"\"\"\n        return (\n            self.center - self.edges[:-1],\n            self.edges[1:] - self.center,\n        )\n\n    @property\n    def iter_by_edges(self):\n        \"\"\"Iterate by intervals defined by the edges\"\"\"\n        for value_min, value_max in zip(self.edges[:-1], self.edges[1:]):\n            yield (value_min, value_max)\n\n    @lazyproperty\n    def center(self):\n        \"\"\"Return array of bin centers.\"\"\"\n        pix = np.arange(self.nbin, dtype=float)\n        return u.Quantity(self.pix_to_coord(pix), self._unit, copy=False)\n\n    @lazyproperty\n    def bin_width(self):\n        \"\"\"Array of bin widths.\"\"\"\n        return np.diff(self.edges)\n\n    @property\n    def nbin(self):\n        \"\"\"Return number of bins.\"\"\"\n        return self._nbin\n\n    @property\n    def nbin_per_decade(self):\n        \"\"\"Return number of bins.\"\"\"\n        if self.interp != \"log\":\n            raise ValueError(\"Bins per decade can only be computed for log-spaced axes\")\n\n        if self.node_type == \"edges\":\n            values = self.edges\n        else:\n            values = self.center\n\n        ndecades = np.log10(values.max() / values.min())\n        return (self._nbin / ndecades).value\n\n    @property\n    def node_type(self):\n        \"\"\"Return node type ('center' or 'edge').\"\"\"\n        return self._node_type\n\n    @property\n    def unit(self):\n        \"\"\"Return coordinate axis unit.\"\"\"\n        return self._unit\n\n    @classmethod\n    def from_bounds(cls, lo_bnd, hi_bnd, nbin, **kwargs):\n        \"\"\"Generate an axis object from a lower/upper bound and number of bins.\n\n        If node_type = 'edge' then bounds correspond to the\n        lower and upper bound of the first and last bin.  If node_type\n        = 'center' then bounds correspond to the centers of the first\n        and last bin.\n\n        Parameters\n        ----------\n        lo_bnd : float\n            Lower bound of first axis bin.\n        hi_bnd : float\n            Upper bound of last axis bin.\n        nbin : int\n            Number of bins.\n        interp : {'lin', 'log', 'sqrt'}\n            Interpolation method used to transform between axis and pixel\n            coordinates.  Default: 'lin'.\n        \"\"\"\n        nbin = int(nbin)\n        interp = kwargs.setdefault(\"interp\", \"lin\")\n        node_type = kwargs.setdefault(\"node_type\", \"edges\")\n\n        if node_type == \"edges\":\n            nnode = nbin + 1\n        elif node_type == \"center\":\n            nnode = nbin\n        else:\n            raise ValueError(f\"Invalid node type: {node_type!r}\")\n\n        if interp == \"lin\":\n            nodes = np.linspace(lo_bnd, hi_bnd, nnode)\n        elif interp == \"log\":\n            nodes = np.exp(np.linspace(np.log(lo_bnd), np.log(hi_bnd), nnode))\n        elif interp == \"sqrt\":\n            nodes = np.linspace(lo_bnd ** 0.5, hi_bnd ** 0.5, nnode) ** 2.0\n        else:\n            raise ValueError(f\"Invalid interp: {interp}\")\n\n        return cls(nodes, **kwargs)\n\n    @classmethod\n    def from_energy_edges(cls, energy_edges, unit=None, name=None, interp=\"log\"):\n        \"\"\"Make an energy axis from adjacent edges.\n\n        Parameters\n        ----------\n        energy_edges : `~astropy.units.Quantity`, float\n            Energy edges\n        unit : `~astropy.units.Unit`\n            Energy unit\n        name : str\n            Name of the energy axis, either 'energy' or 'energy_true'\n        interp: str\n            interpolation mode. Default is 'log'.\n\n        Returns\n        -------\n        axis : `MapAxis`\n            Axis with name \"energy\" and interp \"log\".\n        \"\"\"\n        energy_edges = u.Quantity(energy_edges, unit)\n\n        if unit is None:\n            unit = energy_edges.unit\n            energy_edges = energy_edges.to(unit)\n\n        if name is None:\n            name = \"energy\"\n\n        if name not in [\"energy\", \"energy_true\"]:\n            raise ValueError(\"Energy axis can only be named 'energy' or 'energy_true'\")\n\n        return cls.from_edges(energy_edges, unit=unit, interp=interp, name=name)\n\n    @classmethod\n    def from_energy_bounds(\n        cls,\n        energy_min,\n        energy_max,\n        nbin,\n        unit=None,\n        per_decade=False,\n        name=None,\n        node_type=\"edges\",\n    ):\n        \"\"\"Make an energy axis.\n\n        Used frequently also to make energy grids, by making\n        the axis, and then using ``axis.center`` or ``axis.edges``.\n\n        Parameters\n        ----------\n        energy_min, energy_max : `~astropy.units.Quantity`, float\n            Energy range\n        nbin : int\n            Number of bins\n        unit : `~astropy.units.Unit`\n            Energy unit\n        per_decade : bool\n            Whether `nbin` is given per decade.\n        name : str\n            Name of the energy axis, either 'energy' or 'energy_true'\n\n        Returns\n        -------\n        axis : `MapAxis`\n            Axis with name \"energy\" and interp \"log\".\n        \"\"\"\n        energy_min = u.Quantity(energy_min, unit)\n        energy_max = u.Quantity(energy_max, unit)\n\n        if unit is None:\n            unit = energy_max.unit\n            energy_min = energy_min.to(unit)\n\n        if per_decade:\n            nbin = np.ceil(np.log10(energy_max / energy_min).value * nbin)\n\n        if name is None:\n            name = \"energy\"\n\n        if name not in [\"energy\", \"energy_true\"]:\n            raise ValueError(\"Energy axis can only be named 'energy' or 'energy_true'\")\n\n        return cls.from_bounds(\n            energy_min.value,\n            energy_max.value,\n            nbin=nbin,\n            unit=unit,\n            interp=\"log\",\n            name=name,\n            node_type=node_type,\n        )\n\n    @classmethod\n    def from_nodes(cls, nodes, **kwargs):\n        \"\"\"Generate an axis object from a sequence of nodes (bin centers).\n\n        This will create a sequence of bins with edges half-way\n        between the node values.  This method should be used to\n        construct an axis where the bin center should lie at a\n        specific value (e.g. a map of a continuous function).\n\n        Parameters\n        ----------\n        nodes : `~numpy.ndarray`\n            Axis nodes (bin center).\n        interp : {'lin', 'log', 'sqrt'}\n            Interpolation method used to transform between axis and pixel\n            coordinates.  Default: 'lin'.\n        \"\"\"\n        if len(nodes) < 1:\n            raise ValueError(\"Nodes array must have at least one element.\")\n\n        return cls(nodes, node_type=\"center\", **kwargs)\n\n    @classmethod\n    def from_edges(cls, edges, **kwargs):\n        \"\"\"Generate an axis object from a sequence of bin edges.\n\n        This method should be used to construct an axis where the bin\n        edges should lie at specific values (e.g. a histogram).  The\n        number of bins will be one less than the number of edges.\n\n        Parameters\n        ----------\n        edges : `~numpy.ndarray`\n            Axis bin edges.\n        interp : {'lin', 'log', 'sqrt'}\n            Interpolation method used to transform between axis and pixel\n            coordinates.  Default: 'lin'.\n        \"\"\"\n        if len(edges) < 2:\n            raise ValueError(\"Edges array must have at least two elements.\")\n\n        return cls(edges, node_type=\"edges\", **kwargs)\n\n    def append(self, axis):\n        \"\"\"Append another map axis to this axis\n\n        Name, interp type and node type must agree between the axes. If the node\n        type is \"edges\", the edges must be contiguous and non-overlapping.\n\n        Parameters\n        ----------\n        axis : `MapAxis`\n            Axis to append.\n\n        Returns\n        -------\n        axis : `MapAxis`\n            Appended axis\n        \"\"\"\n        if self.node_type != axis.node_type:\n            raise ValueError(\n                f\"Node type must agree, got {self.node_type} and {axis.node_type}\"\n            )\n\n        if self.name != axis.name:\n            raise ValueError(f\"Names must agree, got {self.name} and {axis.name} \")\n\n        if self.interp != axis.interp:\n            raise ValueError(\n                f\"Interp type must agree, got {self.interp} and {axis.interp}\"\n            )\n\n        if self.node_type == \"edges\":\n            edges = np.append(self.edges, axis.edges[1:])\n            return self.from_edges(edges=edges, interp=self.interp, name=self.name)\n        else:\n            nodes = np.append(self.center, axis.center)\n            return self.from_nodes(nodes=nodes, interp=self.interp, name=self.name)\n\n    def pad(self, pad_width):\n        \"\"\"Pad axis by a given number of pixels\n\n        Parameters\n        ----------\n        pad_width : int or tuple of int\n            A single int pads in both direction of the axis, a tuple specifies,\n            which number of bins to pad at the low and high edge of the axis.\n\n        Returns\n        -------\n        axis : `MapAxis`\n            Padded axis\n        \"\"\"\n        if isinstance(pad_width, tuple):\n            pad_low, pad_high = pad_width\n        else:\n            pad_low, pad_high = pad_width, pad_width\n\n        if self.node_type == \"edges\":\n            pix = np.arange(-pad_low, self.nbin + pad_high + 1) - 0.5\n            edges = self.pix_to_coord(pix)\n            return self.from_edges(edges=edges, interp=self.interp, name=self.name)\n        else:\n            pix = np.arange(-pad_low, self.nbin + pad_high)\n            nodes = self.pix_to_coord(pix)\n            return self.from_nodes(nodes=nodes, interp=self.interp, name=self.name)\n\n    @classmethod\n    def from_stack(cls, axes):\n        \"\"\"Create a map axis by merging a list of other map axes.\n\n        If the node type is \"edges\" the bin edges in the provided axes must be\n        contiguous and non-overlapping.\n\n        Parameters\n        ----------\n        axes : list of `MapAxis`\n            List of map axis to merge.\n\n        Returns\n        -------\n        axis : `MapAxis`\n            Merged axis\n        \"\"\"\n        ax_stacked = axes[0]\n\n        for ax in axes[1:]:\n            ax_stacked = ax_stacked.append(ax)\n\n        return ax_stacked\n\n    def pix_to_coord(self, pix):\n        \"\"\"Transform from pixel to axis coordinates.\n\n        Parameters\n        ----------\n        pix : `~numpy.ndarray`\n            Array of pixel coordinate values.\n\n        Returns\n        -------\n        coord : `~numpy.ndarray`\n            Array of axis coordinate values.\n        \"\"\"\n        pix = pix - self._pix_offset\n        values = pix_to_coord(self._nodes, pix, interp=self._interp)\n        return u.Quantity(values, unit=self.unit, copy=False)\n\n    def pix_to_idx(self, pix, clip=False):\n        \"\"\"Convert pix to idx\n\n        Parameters\n        ----------\n        pix : `~numpy.ndarray`\n            Pixel coordinates.\n        clip : bool\n            Choose whether to clip indices to the valid range of the\n            axis.  If false then indices for coordinates outside\n            the axi range will be set -1.\n\n        Returns\n        -------\n        idx : `~numpy.ndarray`\n            Pixel indices.\n        \"\"\"\n        if clip:\n            idx = np.clip(pix, 0, self.nbin - 1)\n        else:\n            condition = (pix < 0) | (pix >= self.nbin)\n            idx = np.where(condition, -1, pix)\n\n        return idx\n\n    def coord_to_pix(self, coord):\n        \"\"\"Transform from axis to pixel coordinates.\n\n        Parameters\n        ----------\n        coord : `~numpy.ndarray`\n            Array of axis coordinate values.\n\n        Returns\n        -------\n        pix : `~numpy.ndarray`\n            Array of pixel coordinate values.\n        \"\"\"\n        coord = u.Quantity(coord, self.unit, copy=False).value\n        pix = coord_to_pix(self._nodes, coord, interp=self._interp)\n        return np.array(pix + self._pix_offset, ndmin=1)\n\n    def coord_to_idx(self, coord, clip=False):\n        \"\"\"Transform from axis coordinate to bin index.\n\n        Parameters\n        ----------\n        coord : `~numpy.ndarray`\n            Array of axis coordinate values.\n        clip : bool\n            Choose whether to clip the index to the valid range of the\n            axis.  If false then indices for values outside the axis\n            range will be set -1.\n\n        Returns\n        -------\n        idx : `~numpy.ndarray`\n            Array of bin indices.\n        \"\"\"\n        coord = u.Quantity(coord, self.unit, copy=False, ndmin=1).value\n        edges = self.edges.value\n        idx = np.digitize(coord, edges) - 1\n\n        if clip:\n            idx = np.clip(idx, 0, self.nbin - 1)\n        else:\n            with np.errstate(invalid=\"ignore\"):\n                idx[coord > edges[-1]] = INVALID_INDEX.int\n\n        idx[~np.isfinite(coord)] = INVALID_INDEX.int\n\n        return idx\n\n    def slice(self, idx):\n        \"\"\"Create a new axis object by extracting a slice from this axis.\n\n        Parameters\n        ----------\n        idx : slice\n            Slice object selecting a subselection of the axis.\n\n        Returns\n        -------\n        axis : `~MapAxis`\n            Sliced axis object.\n        \"\"\"\n        center = self.center[idx].value\n        idx = self.coord_to_idx(center)\n        # For edge nodes we need to keep N+1 nodes\n        if self._node_type == \"edges\":\n            idx = tuple(list(idx) + [1 + idx[-1]])\n\n        nodes = self._nodes[(idx,)]\n        return MapAxis(\n            nodes,\n            interp=self._interp,\n            name=self._name,\n            node_type=self._node_type,\n            unit=self._unit,\n        )\n\n    def squash(self):\n        \"\"\"Create a new axis object by squashing the axis into one bin.\n\n        Returns\n        -------\n        axis : `~MapAxis`\n            Sliced axis object.\n        \"\"\"\n        # TODO: Decide on handling node_type=center\n        # See https://github.com/gammapy/gammapy/issues/1952\n        return MapAxis.from_bounds(\n            lo_bnd=self.edges[0].value,\n            hi_bnd=self.edges[-1].value,\n            nbin=1,\n            interp=self._interp,\n            name=self._name,\n            unit=self._unit,\n        )\n\n    def __repr__(self):\n        str_ = self.__class__.__name__\n        str_ += \"\\n\\n\"\n        fmt = \"\\t{:<10s} : {:<10s}\\n\"\n        str_ += fmt.format(\"name\", self.name)\n        str_ += fmt.format(\"unit\", \"{!r}\".format(str(self.unit)))\n        str_ += fmt.format(\"nbins\", str(self.nbin))\n        str_ += fmt.format(\"node type\", self.node_type)\n        vals = self.edges if self.node_type == \"edges\" else self.center\n        str_ += fmt.format(f\"{self.node_type} min\", \"{:.1e}\".format(vals.min()))\n        str_ += fmt.format(f\"{self.node_type} max\", \"{:.1e}\".format(vals.max()))\n        str_ += fmt.format(\"interp\", self._interp)\n        return str_\n\n    def _init_copy(self, **kwargs):\n        \"\"\"Init map axis instance by copying missing init arguments from self.\n        \"\"\"\n        argnames = inspect.getfullargspec(self.__init__).args\n        argnames.remove(\"self\")\n\n        for arg in argnames:\n            value = getattr(self, \"_\" + arg)\n            kwargs.setdefault(arg, copy.deepcopy(value))\n\n        return self.__class__(**kwargs)\n\n    def copy(self, **kwargs):\n        \"\"\"Copy `MapAxis` instance and overwrite given attributes.\n\n        Parameters\n        ----------\n        **kwargs : dict\n            Keyword arguments to overwrite in the map axis constructor.\n\n        Returns\n        -------\n        copy : `MapAxis`\n            Copied map axis.\n        \"\"\"\n        return self._init_copy(**kwargs)\n\n    def round(self, coord, clip=False):\n        \"\"\"Round coord to nearest axis edge.\n\n        Parameters\n        ----------\n        coord : `~astropy.units.Quantity`\n            Coordinates\n        clip : bool\n            Choose whether to clip indices to the valid range of the axis.\n\n        Returns\n        -------\n        coord : `~astropy.units.Quantity`\n            Rounded coordinates\n        \"\"\"\n        edges_pix = self.coord_to_pix(coord)\n\n        if clip:\n            edges_pix = np.clip(edges_pix, -0.5, self.nbin - 0.5)\n\n        edges_idx = np.round(edges_pix + 0.5) - 0.5\n        return self.pix_to_coord(edges_idx)\n\n    def group_table(self, edges):\n        \"\"\"Compute bin groups table for the map axis, given coarser bin edges.\n\n        Parameters\n        ----------\n        edges : `~astropy.units.Quantity`\n            Group bin edges.\n\n        Returns\n        -------\n        groups : `~astropy.table.Table`\n            Map axis group table.\n        \"\"\"\n        # TODO: try to simplify this code\n        if not self.node_type == \"edges\":\n            raise ValueError(\"Only edge based map axis can be grouped\")\n\n        edges_pix = self.coord_to_pix(edges)\n        edges_pix = np.clip(edges_pix, -0.5, self.nbin - 0.5)\n        edges_idx = np.round(edges_pix + 0.5) - 0.5\n        edges_idx = np.unique(edges_idx)\n        edges_ref = self.pix_to_coord(edges_idx)\n\n        groups = Table()\n        groups[f\"{self.name}_min\"] = edges_ref[:-1]\n        groups[f\"{self.name}_max\"] = edges_ref[1:]\n\n        groups[\"idx_min\"] = (edges_idx[:-1] + 0.5).astype(int)\n        groups[\"idx_max\"] = (edges_idx[1:] - 0.5).astype(int)\n\n        if len(groups) == 0:\n            raise ValueError(\"No overlap between reference and target edges.\")\n\n        groups[\"bin_type\"] = \"normal   \"\n\n        edge_idx_start, edge_ref_start = edges_idx[0], edges_ref[0]\n        if edge_idx_start > 0:\n            underflow = {\n                \"bin_type\": \"underflow\",\n                \"idx_min\": 0,\n                \"idx_max\": edge_idx_start,\n                f\"{self.name}_min\": self.pix_to_coord(-0.5),\n                f\"{self.name}_max\": edge_ref_start,\n            }\n            groups.insert_row(0, vals=underflow)\n\n        edge_idx_end, edge_ref_end = edges_idx[-1], edges_ref[-1]\n\n        if edge_idx_end < (self.nbin - 0.5):\n            overflow = {\n                \"bin_type\": \"overflow\",\n                \"idx_min\": edge_idx_end + 1,\n                \"idx_max\": self.nbin - 1,\n                f\"{self.name}_min\": edge_ref_end,\n                f\"{self.name}_max\": self.pix_to_coord(self.nbin - 0.5),\n            }\n            groups.add_row(vals=overflow)\n\n        group_idx = Column(np.arange(len(groups)))\n        groups.add_column(group_idx, name=\"group_idx\", index=0)\n        return groups\n\n    def upsample(self, factor):\n        \"\"\"Upsample map axis by a given factor.\n\n        When up-sampling for each node specified in the axis, the corresponding\n        number of sub-nodes are introduced and preserving the initial nodes. For\n        node type \"edges\" this results in nbin * factor new bins. For node type\n        \"center\" this results in (nbin - 1) * factor + 1 new bins.\n\n        Parameters\n        ----------\n        factor : int\n            Upsampling factor.\n\n        Returns\n        -------\n        axis : `MapAxis`\n            Usampled map axis.\n\n        \"\"\"\n        if self.node_type == \"edges\":\n            pix = self.coord_to_pix(self.edges)\n            nbin = int(self.nbin * factor) + 1\n            pix_new = np.linspace(pix.min(), pix.max(), nbin)\n            edges = self.pix_to_coord(pix_new)\n            return self.from_edges(edges, name=self.name, interp=self.interp)\n        else:\n            pix = self.coord_to_pix(self.center)\n            nbin = int((self.nbin - 1) * factor) + 1\n            pix_new = np.linspace(pix.min(), pix.max(), nbin)\n            nodes = self.pix_to_coord(pix_new)\n            return self.from_nodes(nodes, name=self.name, interp=self.interp)\n\n    def downsample(self, factor):\n        \"\"\"Downsample map axis by a given factor.\n\n        When down-sampling each n-th (given by the factor) bin is selected from\n        the axis while preserving the axis limits. For node type \"edges\" this\n        requires nbin to be dividable by the factor, for node type \"center\" this\n        requires nbin - 1 to be dividable by the factor.\n\n        Parameters\n        ----------\n        factor : int\n            Downsampling factor.\n\n\n        Returns\n        -------\n        axis : `MapAxis`\n            Downsampled map axis.\n        \"\"\"\n        if self.node_type == \"edges\":\n            nbin = self.nbin / factor\n\n            if np.mod(nbin, 1) > 0:\n                raise ValueError(\n                    f\"Number of {self.name} bins is not divisible by {factor}\"\n                )\n\n            edges = self.edges[::factor]\n            return self.from_edges(edges, name=self.name, interp=self.interp)\n        else:\n            nbin = (self.nbin - 1) / factor\n\n            if np.mod(nbin, 1) > 0:\n                raise ValueError(\n                    f\"Number of {self.name} bins - 1 is not divisible by {factor}\"\n                )\n\n            nodes = self.center[::factor]\n            return self.from_nodes(nodes, name=self.name, interp=self.interp)\n\n    def to_header(self, format=\"ogip\", idx=0):\n        \"\"\"Create FITS header\n\n        Parameters\n        ----------\n        format : {\"ogip\"}\n            Format specification\n        idx : int\n            Column index of the axis.\n\n        Returns\n        -------\n        header : `~astropy.io.fits.Header`\n            Header to extend.\n        \"\"\"\n        header = fits.Header()\n\n        if format in [\"ogip\", \"ogip-sherpa\"]:\n            header[\"EXTNAME\"] = \"EBOUNDS\", \"Name of this binary table extension\"\n            header[\"TELESCOP\"] = \"DUMMY\", \"Mission/satellite name\"\n            header[\"INSTRUME\"] = \"DUMMY\", \"Instrument/detector\"\n            header[\"FILTER\"] = \"None\", \"Filter information\"\n            header[\"CHANTYPE\"] = \"PHA\", \"Type of channels (PHA, PI etc)\"\n            header[\"DETCHANS\"] = self.nbin, \"Total number of detector PHA channels\"\n            header[\"HDUCLASS\"] = \"OGIP\", \"Organisation devising file format\"\n            header[\"HDUCLAS1\"] = \"RESPONSE\", \"File relates to response of instrument\"\n            header[\"HDUCLAS2\"] = \"EBOUNDS\", \"This is an EBOUNDS extension\"\n            header[\"HDUVERS\"] = \"1.2.0\", \"Version of file format\"\n        elif format in [\"gadf\", \"fgst-ccube\", \"fgst-template\"]:\n            key = f\"AXCOLS{idx}\"\n            name = self.name.upper()\n\n            if self.name == \"energy\" and self.node_type == \"edges\":\n                header[key] = \"E_MIN,E_MAX\"\n            elif self.name == \"energy\" and self.node_type == \"center\":\n                header[key] = \"ENERGY\"\n            elif self.node_type == \"edges\":\n                header[key] = f\"{name}_MIN,{name}_MAX\"\n            elif self.node_type == \"center\":\n                header[key] = name\n            else:\n                raise ValueError(f\"Invalid node type {self.node_type!r}\")\n\n            key_interp = f\"INTERP{idx}\"\n            header[key_interp] = self.interp\n\n        else:\n            raise ValueError(f\"Unknown format {format}\")\n\n        return header\n\n    def to_table(self, format=\"ogip\"):\n        \"\"\"Convert `~astropy.units.Quantity` to OGIP ``EBOUNDS`` extension.\n\n        See https://heasarc.gsfc.nasa.gov/docs/heasarc/caldb/docs/memos/cal_gen_92_002/cal_gen_92_002.html#tth_sEc3.2\n\n        The 'ogip-sherpa' format is equivalent to 'ogip' but uses keV energy units.\n\n        Parameters\n        ----------\n        format : {\"ogip\", \"ogip-sherpa\", \"gadf-dl3\", \"gtpsf\"}\n            Format specification\n\n        Returns\n        -------\n        table : `~astropy.table.Table`\n            Table HDU\n        \"\"\"\n        table = Table()\n        edges = self.edges\n\n        if format in [\"ogip\", \"ogip-sherpa\"]:\n            self.assert_name(\"energy\")\n\n            if format == \"ogip-sherpa\":\n                edges = edges.to(\"keV\")\n\n            table[\"CHANNEL\"] = np.arange(self.nbin, dtype=np.int16)\n            table[\"E_MIN\"] = edges[:-1]\n            table[\"E_MAX\"] = edges[1:]\n        elif format in [\"ogip-arf\", \"ogip-arf-sherpa\"]:\n            self.assert_name(\"energy_true\")\n\n            if format == \"ogip-arf-sherpa\":\n                edges = edges.to(\"keV\")\n\n            table[\"ENERG_LO\"] = edges[:-1]\n            table[\"ENERG_HI\"] = edges[1:]\n        elif format == \"gadf-dl3\":\n            from gammapy.irf.io import IRF_DL3_AXES_SPECIFICATION\n\n            if self.name == \"energy\":\n                column_prefix = \"ENERG\"\n            else:\n                for column_prefix, spec in IRF_DL3_AXES_SPECIFICATION.items():\n                    if spec[\"name\"] == self.name:\n                        break\n\n            if self.node_type == \"edges\":\n                edges_hi, edges_lo = edges[:-1], edges[1:]\n            else:\n                edges_hi, edges_lo = self.center, self.center\n\n            table[f\"{column_prefix}_LO\"] = edges_hi[np.newaxis]\n            table[f\"{column_prefix}_HI\"] = edges_lo[np.newaxis]\n        elif format == \"gtpsf\":\n            if self.name == \"energy_true\":\n                table[\"Energy\"] = self.center.to(\"MeV\")\n            elif self.name == \"rad\":\n                table[\"Theta\"] = self.center.to(\"deg\")\n            else:\n                raise ValueError(\n                    \"Can only convert true energy or rad axis to\"\n                    f\"'gtpsf' format, got {self.name}\"\n                )\n        else:\n            raise ValueError(f\"{format} is not a valid format\")\n\n        return table\n\n    def to_table_hdu(self, format=\"ogip\"):\n        \"\"\"Convert `~astropy.units.Quantity` to OGIP ``EBOUNDS`` extension.\n\n        See https://heasarc.gsfc.nasa.gov/docs/heasarc/caldb/docs/memos/cal_gen_92_002/cal_gen_92_002.html#tth_sEc3.2\n\n        The 'ogip-sherpa' format is equivalent to 'ogip' but uses keV energy units.\n\n        Parameters\n        ----------\n        format : {\"ogip\", \"ogip-sherpa\", \"gtpsf\"}\n            Format specification\n\n        Returns\n        -------\n        hdu : `~astropy.io.fits.BinTableHDU`\n            Table HDU\n        \"\"\"\n        table = self.to_table(format=format)\n\n        if format == \"gtpsf\":\n            name = \"THETA\"\n        else:\n            name = None\n\n        hdu = fits.BinTableHDU(table, name=name)\n\n        if format in [\"ogip\", \"ogip-sherpa\"]:\n            hdu.header.update(self.to_header(format=format))\n\n        return hdu\n\n    @classmethod\n    def from_table(cls, table, format=\"ogip\", idx=0, column_prefix=\"\"):\n        \"\"\"Instanciate MapAxis from table HDU\n\n        Parameters\n        ----------\n        table : `~astropy.table.Table`\n            Table\n        format : {\"ogip\", \"ogip-arf\", \"fgst-ccube\", \"fgst-template\", \"gadf\", \"gadf-dl3\"}\n            Format specification\n        idx : int\n            Column index of the axis.\n        column_prefix : str\n            Column name prefix of the axis, used for creating the axis.\n\n        Returns\n        -------\n        axis : `MapAxis`\n            Map Axis\n        \"\"\"\n        if format in [\"ogip\", \"fgst-ccube\"]:\n            energy_min = table[\"E_MIN\"].quantity\n            energy_max = table[\"E_MAX\"].quantity\n            energy_edges = (\n                np.append(energy_min.value, energy_max.value[-1]) * energy_min.unit\n            )\n            axis = cls.from_edges(energy_edges, name=\"energy\", interp=\"log\")\n\n        elif format == \"ogip-arf\":\n            energy_min = table[\"ENERG_LO\"].quantity\n            energy_max = table[\"ENERG_HI\"].quantity\n            energy_edges = (\n                np.append(energy_min.value, energy_max.value[-1]) * energy_min.unit\n            )\n            axis = cls.from_edges(energy_edges, name=\"energy_true\", interp=\"log\")\n\n        elif format in [\"fgst-template\", \"fgst-bexpcube\"]:\n            allowed_names = [\"Energy\", \"ENERGY\", \"energy\"]\n            for colname in table.colnames:\n                if colname in allowed_names:\n                    tag = colname\n                    break\n\n            nodes = table[tag].data\n            axis = cls.from_nodes(\n                nodes=nodes, name=\"energy_true\", unit=\"MeV\", interp=\"log\"\n            )\n\n        elif format == \"gadf\":\n            axcols = table.meta.get(\"AXCOLS{}\".format(idx + 1))\n            colnames = axcols.split(\",\")\n            node_type = \"edges\" if len(colnames) == 2 else \"center\"\n\n            # TODO: check why this extra case is needed\n            if colnames[0] == \"E_MIN\":\n                name = \"energy\"\n            else:\n                name = colnames[0].replace(\"_MIN\", \"\").lower()\n                # this is need for backward compatibility\n                if name == \"theta\":\n                    name = \"rad\"\n\n            interp = table.meta.get(\"INTERP{}\".format(idx + 1), \"lin\")\n\n            if node_type == \"center\":\n                nodes = np.unique(table[colnames[0]].quantity)\n            else:\n                edges_min = np.unique(table[colnames[0]].quantity)\n                edges_max = np.unique(table[colnames[1]].quantity)\n                nodes = edges_from_lo_hi(edges_min, edges_max)\n\n            axis = MapAxis(nodes=nodes, node_type=node_type, interp=interp, name=name)\n\n        elif format == \"gadf-dl3\":\n            from gammapy.irf.io import IRF_DL3_AXES_SPECIFICATION\n\n            spec = IRF_DL3_AXES_SPECIFICATION[column_prefix]\n            name, interp = spec[\"name\"], spec[\"interp\"]\n\n            # background models are stored in reconstructed energy\n            hduclass = table.meta.get(\"HDUCLAS2\")\n            if hduclass == \"BKG\" and column_prefix == \"ENERG\":\n                name = \"energy\"\n\n            edges_lo = table[f\"{column_prefix}_LO\"].quantity[0]\n            edges_hi = table[f\"{column_prefix}_HI\"].quantity[0]\n\n            if np.allclose(edges_hi, edges_lo):\n                axis = MapAxis.from_nodes(edges_hi, interp=interp, name=name)\n            else:\n                edges = edges_from_lo_hi(edges_lo, edges_hi)\n                axis = MapAxis.from_edges(edges, interp=interp, name=name)\n        elif format == \"gtpsf\":\n            try:\n                energy = table[\"Energy\"].data * u.MeV\n                axis = MapAxis.from_nodes(energy, name=\"energy_true\", interp=\"log\")\n            except KeyError:\n                rad = table[\"Theta\"].data * u.deg\n                axis = MapAxis.from_nodes(rad, name=\"rad\")\n        elif format == \"gadf-sed\":\n            sed_type = table.meta.get(\"SED_TYPE\")\n            if sed_type in [\"dnde\", \"e2dnde\"]:\n                e_ref = flat_if_equal(table[\"e_ref\"].quantity)\n                axis = MapAxis.from_nodes(e_ref, name=\"energy\", interp=\"log\")\n            else:\n                e_min = flat_if_equal(table[\"e_min\"].quantity)\n                e_max = flat_if_equal(table[\"e_max\"].quantity)\n                edges = edges_from_lo_hi(e_min, e_max)\n                axis = MapAxis.from_energy_edges(edges)\n        else:\n            raise ValueError(f\"Format '{format}' not supported\")\n\n        return axis\n\n    @classmethod\n    def from_table_hdu(cls, hdu, format=\"ogip\", idx=0):\n        \"\"\"Instanciate MapAxis from table HDU\n\n        Parameters\n        ----------\n        hdu : `~astropy.io.fits.BinTableHDU`\n            Table HDU\n        format : {\"ogip\", \"ogip-arf\", \"fgst-ccube\", \"fgst-template\"}\n            Format specification\n        idx : int\n            Column index of the axis.\n\n        Returns\n        -------\n        axis : `MapAxis`\n            Map Axis\n        \"\"\"\n        table = Table.read(hdu)\n        return cls.from_table(table, format=format, idx=idx)\n\n\nclass MapCoord:\n    \"\"\"Represents a sequence of n-dimensional map coordinates.\n\n    Contains coordinates for 2 spatial dimensions and an arbitrary\n    number of additional non-spatial dimensions.\n\n    For further information see :ref:`mapcoord`.\n\n    Parameters\n    ----------\n    data : `dict` of `~numpy.ndarray`\n        Dictionary of coordinate arrays.\n    frame : {\"icrs\", \"galactic\", None}\n        Spatial coordinate system.  If None then the coordinate system\n        will be set to the native coordinate system of the geometry.\n    match_by_name : bool\n        Match coordinates to axes by name?\n        If false coordinates will be matched by index.\n    \"\"\"\n\n    def __init__(self, data, frame=None, match_by_name=True):\n        if \"lon\" not in data or \"lat\" not in data:\n            raise ValueError(\"data dictionary must contain axes named 'lon' and 'lat'.\")\n\n        self._data = {k: np.atleast_1d(v) for k, v in data.items()}\n        self._frame = frame\n        self._match_by_name = match_by_name\n\n    def __getitem__(self, key):\n        if isinstance(key, str):\n            return self._data[key]\n        else:\n            return list(self._data.values())[key]\n\n    def __iter__(self):\n        return iter(self._data.values())\n\n    @property\n    def ndim(self):\n        \"\"\"Number of dimensions.\"\"\"\n        return len(self._data)\n\n    @property\n    def shape(self):\n        \"\"\"Coordinate array shape.\"\"\"\n        arrays = [_ for _ in self._data.values()]\n        return np.broadcast(*arrays).shape\n\n    @property\n    def size(self):\n        return np.prod(self.shape)\n\n    @property\n    def lon(self):\n        \"\"\"Longitude coordinate in degrees.\"\"\"\n        return self._data[\"lon\"]\n\n    @property\n    def lat(self):\n        \"\"\"Latitude coordinate in degrees.\"\"\"\n        return self._data[\"lat\"]\n\n    @property\n    def theta(self):\n        \"\"\"Theta co-latitude angle in radians.\"\"\"\n        theta = u.Quantity(self.lat, unit=\"deg\", copy=False).to_value(\"rad\")\n        return np.pi / 2.0 - theta\n\n    @property\n    def phi(self):\n        \"\"\"Phi longitude angle in radians.\"\"\"\n        phi = u.Quantity(self.lon, unit=\"deg\", copy=False).to_value(\"rad\")\n        return phi\n\n    @property\n    def frame(self):\n        \"\"\"Coordinate system (str).\"\"\"\n        return self._frame\n\n    @property\n    def match_by_name(self):\n        \"\"\"Boolean flag: axis lookup by name (True) or index (False).\"\"\"\n        return self._match_by_name\n\n    @property\n    def skycoord(self):\n        return SkyCoord(self.lon, self.lat, unit=\"deg\", frame=self.frame)\n\n    @classmethod\n    def _from_lonlat(cls, coords, frame=None, axis_names=None):\n        \"\"\"Create a `~MapCoord` from a tuple of coordinate vectors.\n\n        The first two elements of the tuple should be longitude and latitude in degrees.\n\n        Parameters\n        ----------\n        coords : tuple\n            Tuple of `~numpy.ndarray`.\n\n        Returns\n        -------\n        coord : `~MapCoord`\n            A coordinates object.\n        \"\"\"\n        if axis_names is None:\n            axis_names = [f\"axis{idx}\" for idx in range(len(coords) - 2)]\n\n        if isinstance(coords, (list, tuple)):\n            coords_dict = {\"lon\": coords[0], \"lat\": coords[1]}\n            for name, c in zip(axis_names, coords[2:]):\n                coords_dict[name] = c\n        else:\n            raise ValueError(\"Unrecognized input type.\")\n\n        return cls(coords_dict, frame=frame, match_by_name=False)\n\n    @classmethod\n    def _from_tuple(cls, coords, frame=None, axis_names=None):\n        \"\"\"Create from tuple of coordinate vectors.\"\"\"\n        if isinstance(coords[0], (list, np.ndarray)) or np.isscalar(coords[0]):\n            return cls._from_lonlat(coords, frame=frame, axis_names=axis_names)\n        elif isinstance(coords[0], SkyCoord):\n            lon, lat, frame = skycoord_to_lonlat(coords[0], frame=frame)\n            coords = (lon, lat) + coords[1:]\n            return cls._from_lonlat(coords, frame=frame, axis_names=axis_names)\n        else:\n            raise TypeError(f\"Type not supported: {type(coords)!r}\")\n\n    @classmethod\n    def _from_dict(cls, coords, frame=None):\n        \"\"\"Create from a dictionary of coordinate vectors.\"\"\"\n        if \"lon\" in coords and \"lat\" in coords:\n            return cls(coords, frame=frame)\n        elif \"skycoord\" in coords:\n            lon, lat, frame = skycoord_to_lonlat(coords[\"skycoord\"], frame=frame)\n            coords_dict = {\"lon\": lon, \"lat\": lat}\n            for k, v in coords.items():\n                if k == \"skycoord\":\n                    continue\n                coords_dict[k] = v\n            return cls(coords_dict, frame=frame)\n        else:\n            raise ValueError(\"coords dict must contain 'lon'/'lat' or 'skycoord'.\")\n\n    @classmethod\n    def create(cls, data, frame=None, axis_names=None):\n        \"\"\"Create a new `~MapCoord` object.\n\n        This method can be used to create either unnamed (with tuple input)\n        or named (via dict input) axes.\n\n        Parameters\n        ----------\n        data : tuple, dict, `MapCoord` or `~astropy.coordinates.SkyCoord`\n            Object containing coordinate arrays.\n        frame : {\"icrs\", \"galactic\", None}, optional\n            Set the coordinate system for longitude and latitude. If\n            None longitude and latitude will be assumed to be in\n            the coordinate system native to a given map geometry.\n        axis_names : list of str\n            Axis names use if a tuple is provided\n\n        Examples\n        --------\n        >>> from astropy.coordinates import SkyCoord\n        >>> from gammapy.maps import MapCoord\n\n        >>> lon, lat = [1, 2], [2, 3]\n        >>> skycoord = SkyCoord(lon, lat, unit='deg')\n        >>> energy = [1000]\n        >>> c = MapCoord.create((lon,lat))\n        >>> c = MapCoord.create((skycoord,))\n        >>> c = MapCoord.create((lon,lat,energy))\n        >>> c = MapCoord.create(dict(lon=lon,lat=lat))\n        >>> c = MapCoord.create(dict(lon=lon,lat=lat,energy=energy))\n        >>> c = MapCoord.create(dict(skycoord=skycoord,energy=energy))\n        \"\"\"\n        if isinstance(data, cls):\n            if data.frame is None or frame == data.frame:\n                return data\n            else:\n                return data.to_frame(frame)\n        elif isinstance(data, dict):\n            return cls._from_dict(data, frame=frame)\n        elif isinstance(data, (list, tuple)):\n            return cls._from_tuple(data, frame=frame, axis_names=axis_names)\n        elif isinstance(data, SkyCoord):\n            return cls._from_tuple((data,), frame=frame, axis_names=axis_names)\n        else:\n            raise TypeError(f\"Unsupported input type: {type(data)!r}\")\n\n    def to_frame(self, frame):\n        \"\"\"Convert to a different coordinate frame.\n\n        Parameters\n        ----------\n        frame : {\"icrs\", \"galactic\"}\n            Coordinate system, either Galactic (\"galactic\") or Equatorial (\"icrs\").\n\n        Returns\n        -------\n        coords : `~MapCoord`\n            A coordinates object.\n        \"\"\"\n        if frame == self.frame:\n            return copy.deepcopy(self)\n        else:\n            lon, lat, frame = skycoord_to_lonlat(self.skycoord, frame=frame)\n            data = copy.deepcopy(self._data)\n            if isinstance(self.lon, u.Quantity):\n                lon = u.Quantity(lon, unit=\"deg\", copy=False)\n\n            if isinstance(self.lon, u.Quantity):\n                lat = u.Quantity(lat, unit=\"deg\", copy=False)\n\n            data[\"lon\"] = lon\n            data[\"lat\"] = lat\n            return self.__class__(data, frame, self._match_by_name)\n\n    def apply_mask(self, mask):\n        \"\"\"Return a masked copy of this coordinate object.\n\n        Parameters\n        ----------\n        mask : `~numpy.ndarray`\n            Boolean mask.\n\n        Returns\n        -------\n        coords : `~MapCoord`\n            A coordinates object.\n        \"\"\"\n        try:\n            data = {k: v[mask] for k, v in self._data.items()}\n        except IndexError:\n            data = {}\n\n            for name, coord in self._data.items():\n                if name in [\"lon\", \"lat\"]:\n                    data[name] = np.squeeze(coord)[mask]\n                else:\n                    data[name] = np.squeeze(coord, axis=-1)\n\n        return self.__class__(data, self.frame, self._match_by_name)\n\n    @property\n    def flat(self):\n        \"\"\"Return flattened, valid coordinates\"\"\"\n        coords = self.broadcasted\n        is_finite = np.isfinite(coords[0])\n        return coords.apply_mask(is_finite)\n\n    @property\n    def broadcasted(self):\n        \"\"\"Return broadcasted coords\"\"\"\n        vals = np.broadcast_arrays(*self._data.values(), subok=True)\n        data = dict(zip(self._data.keys(), vals))\n        return self.__class__(data=data, frame=self.frame, match_by_name=self._match_by_name)\n\n    def copy(self):\n        \"\"\"Copy `MapCoord` object.\"\"\"\n        return copy.deepcopy(self)\n\n    def __repr__(self):\n        return (\n            f\"{self.__class__.__name__}\\n\\n\"\n            f\"\\taxes     : {list(self._data.keys())}\\n\"\n            f\"\\tshape    : {self.shape[::-1]}\\n\"\n            f\"\\tndim     : {self.ndim}\\n\"\n            f\"\\tframe : {self.frame}\\n\"\n        )\n\n\nclass Geom(abc.ABC):\n    \"\"\"Map geometry base class.\n\n    See also: `~gammapy.maps.WcsGeom` and `~gammapy.maps.HpxGeom`\n    \"\"\"\n\n    @property\n    @abc.abstractmethod\n    def data_shape(self):\n        \"\"\"Shape of the Numpy data array matching this geometry.\"\"\"\n        pass\n\n    def data_nbytes(self, dtype=\"float32\"):\n        \"\"\"Estimate memory usage in megabytes of the Numpy data array\n        matching this geometry depending on the given type.\n\n        Parameters\n        ----------\n        dtype : data-type\n            The desired data-type for the array. Default is \"float32\"\n            \n        Returns\n        -------\n        memory : `~astropy.units.Quantity`\n            Estimated memory usage in megabytes (MB)\n        \"\"\"\n        return (np.empty(self.data_shape, dtype).nbytes * u.byte).to(\"MB\")\n\n    @property\n    @abc.abstractmethod\n    def is_allsky(self):\n        pass\n\n    @property\n    @abc.abstractmethod\n    def center_coord(self):\n        pass\n\n    @property\n    @abc.abstractmethod\n    def center_pix(self):\n        pass\n\n    @property\n    @abc.abstractmethod\n    def center_skydir(self):\n        pass\n\n    @classmethod\n    def from_hdulist(cls, hdulist, hdu=None, hdu_bands=None):\n        \"\"\"Load a geometry object from a FITS HDUList.\n\n        Parameters\n        ----------\n        hdulist :  `~astropy.io.fits.HDUList`\n            HDU list containing HDUs for map data and bands.\n        hdu : str\n            Name or index of the HDU with the map data.\n        hdu_bands : str\n            Name or index of the HDU with the BANDS table.  If not\n            defined this will be inferred from the FITS header of the\n            map HDU.\n\n        Returns\n        -------\n        geom : `~Geom`\n            Geometry object.\n        \"\"\"\n        if hdu is None:\n            hdu = find_hdu(hdulist)\n        else:\n            hdu = hdulist[hdu]\n\n        if hdu_bands is None:\n            hdu_bands = find_bands_hdu(hdulist, hdu)\n\n        if hdu_bands is not None:\n            hdu_bands = hdulist[hdu_bands]\n\n        return cls.from_header(hdu.header, hdu_bands)\n\n    def to_bands_hdu(self, hdu_bands=None, format=\"gadf\"):\n        table_hdu = self.axes.to_table_hdu(format=format, hdu_bands=hdu_bands)\n        cols = table_hdu.columns.columns\n        cols.extend(self._make_bands_cols())\n        return fits.BinTableHDU.from_columns(\n            cols, header=table_hdu.header, name=table_hdu.name\n        )\n\n    @abc.abstractmethod\n    def _make_bands_cols(self):\n        pass\n\n    @abc.abstractmethod\n    def get_idx(self, idx=None, local=False, flat=False):\n        \"\"\"Get tuple of pixel indices for this geometry.\n\n        Returns all pixels in the geometry by default. Pixel indices\n        for a single image plane can be accessed by setting ``idx``\n        to the index tuple of a plane.\n\n        Parameters\n        ----------\n        idx : tuple, optional\n            A tuple of indices with one index for each non-spatial\n            dimension.  If defined only pixels for the image plane with\n            this index will be returned.  If none then all pixels\n            will be returned.\n        local : bool\n            Flag to return local or global pixel indices.  Local\n            indices run from 0 to the number of pixels in a given\n            image plane.\n        flat : bool, optional\n            Return a flattened array containing only indices for\n            pixels contained in the geometry.\n\n        Returns\n        -------\n        idx : tuple\n            Tuple of pixel index vectors with one vector for each\n            dimension.\n        \"\"\"\n        pass\n\n    @abc.abstractmethod\n    def get_coord(self, idx=None, flat=False):\n        \"\"\"Get the coordinate array for this geometry.\n\n        Returns a coordinate array with the same shape as the data\n        array.  Pixels outside the geometry are set to NaN.\n        Coordinates for a single image plane can be accessed by\n        setting ``idx`` to the index tuple of a plane.\n\n        Parameters\n        ----------\n        idx : tuple, optional\n            A tuple of indices with one index for each non-spatial\n            dimension.  If defined only coordinates for the image\n            plane with this index will be returned.  If none then\n            coordinates for all pixels will be returned.\n        flat : bool, optional\n            Return a flattened array containing only coordinates for\n            pixels contained in the geometry.\n\n        Returns\n        -------\n        coords : tuple\n            Tuple of coordinate vectors with one vector for each\n            dimension.\n        \"\"\"\n        pass\n\n    @abc.abstractmethod\n    def coord_to_pix(self, coords):\n        \"\"\"Convert map coordinates to pixel coordinates.\n\n        Parameters\n        ----------\n        coords : tuple\n            Coordinate values in each dimension of the map.  This can\n            either be a tuple of numpy arrays or a MapCoord object.\n            If passed as a tuple then the ordering should be\n            (longitude, latitude, c_0, ..., c_N) where c_i is the\n            coordinate vector for axis i.\n\n        Returns\n        -------\n        pix : tuple\n            Tuple of pixel coordinates in image and band dimensions.\n        \"\"\"\n        pass\n\n    def coord_to_idx(self, coords, clip=False):\n        \"\"\"Convert map coordinates to pixel indices.\n\n        Parameters\n        ----------\n        coords : tuple or `~MapCoord`\n            Coordinate values in each dimension of the map.  This can\n            either be a tuple of numpy arrays or a MapCoord object.\n            If passed as a tuple then the ordering should be\n            (longitude, latitude, c_0, ..., c_N) where c_i is the\n            coordinate vector for axis i.\n        clip : bool\n            Choose whether to clip indices to the valid range of the\n            geometry.  If false then indices for coordinates outside\n            the geometry range will be set -1.\n\n        Returns\n        -------\n        pix : tuple\n            Tuple of pixel indices in image and band dimensions.\n            Elements set to -1 correspond to coordinates outside the\n            map.\n        \"\"\"\n        pix = self.coord_to_pix(coords)\n        return self.pix_to_idx(pix, clip=clip)\n\n    @abc.abstractmethod\n    def pix_to_coord(self, pix):\n        \"\"\"Convert pixel coordinates to map coordinates.\n\n        Parameters\n        ----------\n        pix : tuple\n            Tuple of pixel coordinates.\n\n        Returns\n        -------\n        coords : tuple\n            Tuple of map coordinates.\n        \"\"\"\n        pass\n\n    @abc.abstractmethod\n    def pix_to_idx(self, pix, clip=False):\n        \"\"\"Convert pixel coordinates to pixel indices.\n\n        Returns -1 for pixel coordinates that lie outside of the map.\n\n        Parameters\n        ----------\n        pix : tuple\n            Tuple of pixel coordinates.\n        clip : bool\n            Choose whether to clip indices to the valid range of the\n            geometry.  If false then indices for coordinates outside\n            the geometry range will be set -1.\n\n        Returns\n        -------\n        idx : tuple\n            Tuple of pixel indices.\n        \"\"\"\n        pass\n\n    @abc.abstractmethod\n    def contains(self, coords):\n        \"\"\"Check if a given map coordinate is contained in the geometry.\n\n        Parameters\n        ----------\n        coords : tuple or `~gammapy.maps.MapCoord`\n            Tuple of map coordinates.\n\n        Returns\n        -------\n        containment : `~numpy.ndarray`\n            Bool array.\n        \"\"\"\n        pass\n\n    def contains_pix(self, pix):\n        \"\"\"Check if a given pixel coordinate is contained in the geometry.\n\n        Parameters\n        ----------\n        pix : tuple\n            Tuple of pixel coordinates.\n\n        Returns\n        -------\n        containment : `~numpy.ndarray`\n            Bool array.\n        \"\"\"\n        idx = self.pix_to_idx(pix)\n        return np.all(np.stack([t != INVALID_INDEX.int for t in idx]), axis=0)\n\n    def slice_by_idx(self, slices):\n        \"\"\"Create a new geometry by slicing the non-spatial axes.\n\n        Parameters\n        ----------\n        slices : dict\n            Dict of axes names and integers or `slice` object pairs. Contains one\n            element for each non-spatial dimension. For integer indexing the\n            corresponding axes is dropped from the map. Axes not specified in the\n            dict are kept unchanged.\n\n        Returns\n        -------\n        geom : `~Geom`\n            Sliced geometry.\n        \"\"\"\n        axes = self.axes.slice_by_idx(slices)\n        return self._init_copy(axes=axes)\n\n    @property\n    def as_energy_true(self):\n        \"\"\"If the geom contains an energy axis rename it to energy true\"\"\"\n        energy_axis = self.axes[\"energy\"].copy(name=\"energy_true\")\n        return self.to_image().to_cube([energy_axis])\n\n    @property\n    def has_energy_axis(self):\n        \"\"\"Whether geom has an energy axis\"\"\"\n        return (\"energy\" in self.axes.names) ^ (\"energy_true\" in self.axes.names)\n\n    @abc.abstractmethod\n    def to_image(self):\n        \"\"\"Create 2D image geometry (drop non-spatial dimensions).\n\n        Returns\n        -------\n        geom : `~Geom`\n            Image geometry.\n        \"\"\"\n        pass\n\n    @abc.abstractmethod\n    def to_cube(self, axes):\n        \"\"\"Append non-spatial axes to create a higher-dimensional geometry.\n\n        This will result in a new geometry with\n        N+M dimensions where N is the number of current dimensions and\n        M is the number of axes in the list.\n\n        Parameters\n        ----------\n        axes : list\n            Axes that will be appended to this geometry.\n\n        Returns\n        -------\n        geom : `~Geom`\n            Map geometry.\n        \"\"\"\n        pass\n\n    def squash(self, axis_name):\n        \"\"\"Squash geom axis.\n\n        Parameters\n        ----------\n        axis_name : str\n            Axis to squash.\n\n        Returns\n        -------\n        geom : `Geom`\n            Geom with squashed axis.\n        \"\"\"\n        axes = self.axes.squash(axis_name=axis_name)\n        return self.to_image().to_cube(axes=axes)\n\n    def drop(self, axis_name):\n        \"\"\"Drop an axis from the geom.\n\n        Parameters\n        ----------\n        axis_name : str\n            Name of the axis to remove.\n\n        Returns\n            -------\n        geom : `Geom`\n            New geom with the axis removed.\n        \"\"\"\n        axes = self.axes.drop(axis_name=axis_name)\n        return self.to_image().to_cube(axes=axes)\n\n    def pad(self, pad_width, axis_name):\n        \"\"\"\n        Pad the geometry at the edges.\n\n        Parameters\n        ----------\n        pad_width : {sequence, array_like, int}\n            Number of values padded to the edges of each axis.\n        axis_name : str\n            Name of the axis to pad.\n\n        Returns\n        -------\n        geom : `~Geom`\n            Padded geometry.\n        \"\"\"\n        if axis_name is None:\n            return self._pad_spatial(pad_width)\n        else:\n            axes = self.axes.pad(axis_name=axis_name, pad_width=pad_width)\n            return self.to_image().to_cube(axes)\n\n    @abc.abstractmethod\n    def _pad_spatial(self, pad_width):\n        pass\n\n    @abc.abstractmethod\n    def crop(self, crop_width):\n        \"\"\"\n        Crop the geometry at the edges.\n\n        Parameters\n        ----------\n        crop_width : {sequence, array_like, int}\n            Number of values cropped from the edges of each axis.\n\n        Returns\n        -------\n        geom : `~Geom`\n            Cropped geometry.\n        \"\"\"\n        pass\n\n    @abc.abstractmethod\n    def downsample(self, factor, axis_name):\n        \"\"\"Downsample the spatial dimension of the geometry by a given factor.\n\n        Parameters\n        ----------\n        factor : int\n            Downsampling factor.\n        axis_name : str\n            Axis to downsample.\n\n        Returns\n        -------\n        geom : `~Geom`\n            Downsampled geometry.\n\n        \"\"\"\n        pass\n\n    @abc.abstractmethod\n    def upsample(self, factor, axis_name):\n        \"\"\"Upsample the spatial dimension of the geometry by a given factor.\n\n        Parameters\n        ----------\n        factor : int\n            Upsampling factor.\n        axis_name : str\n            Axis to upsample.\n\n        Returns\n        -------\n        geom : `~Geom`\n            Upsampled geometry.\n\n        \"\"\"\n        pass\n\n    def resample_axis(self, axis):\n        \"\"\"Resample geom to a new axis binning.\n\n        This method groups the existing bins into a new binning.\n\n        Parameters\n        ----------\n        axis : `MapAxis`\n            New map axis.\n\n        Returns\n        -------\n        map : `Geom`\n            Geom with resampled axis.\n        \"\"\"\n        axes = self.axes.resample(axis=axis)\n        return self._init_copy(axes=axes)\n\n    @abc.abstractmethod\n    def solid_angle(self):\n        \"\"\"Solid angle (`~astropy.units.Quantity` in ``sr``).\"\"\"\n        pass\n\n    @property\n    def is_image(self):\n        \"\"\"Whether the geom is an image without extra dimensions.\"\"\"\n        if self.axes is None:\n            return True\n        return len(self.axes) == 0\n\n    @property\n    def is_flat(self):\n        \"\"\"Whether the geom non spatial axes have length 1, i.e. if the geom is equivalent to an image.\"\"\"\n        if self.is_image:\n            return True\n        else:\n            valid = True\n            for axis in self.axes:\n                valid = valid and (axis.nbin == 1)\n            return valid\n\n    def _init_copy(self, **kwargs):\n        \"\"\"Init map geom instance by copying missing init arguments from self.\n        \"\"\"\n        argnames = inspect.getfullargspec(self.__init__).args\n        argnames.remove(\"self\")\n\n        for arg in argnames:\n            value = getattr(self, \"_\" + arg)\n            kwargs.setdefault(arg, copy.deepcopy(value))\n\n        return self.__class__(**kwargs)\n\n    def copy(self, **kwargs):\n        \"\"\"Copy and overwrite given attributes.\n\n        Parameters\n        ----------\n        **kwargs : dict\n            Keyword arguments to overwrite in the map geometry constructor.\n\n        Returns\n        -------\n        copy : `Geom`\n            Copied map geometry.\n        \"\"\"\n        return self._init_copy(**kwargs)\n\n    def energy_mask(self, energy_min=None, energy_max=None, round_to_edge=False):\n        \"\"\"Create a mask for a given energy range.\n\n        The energy bin must be fully contained to be included in the mask.\n\n        Parameters\n        ----------\n        energy_min, energy_max : `~astropy.units.Quantity`\n            Energy range\n\n        Returns\n        -------\n        mask : `~numpy.ndarray`\n            Energy mask\n        \"\"\"\n        from . import Map\n\n        # get energy axes and values\n        energy_axis = self.axes[\"energy\"]\n\n        if round_to_edge:\n            energy_min, energy_max = energy_axis.round([energy_min, energy_max])\n\n        # TODO: make this more general\n        shape = (-1, 1) if self.is_hpx else (-1, 1, 1)\n        energy_edges = energy_axis.edges.reshape(shape)\n\n        # set default values\n        energy_min = energy_min if energy_min is not None else energy_edges[0]\n        energy_max = energy_max if energy_max is not None else energy_edges[-1]\n\n        mask = (energy_edges[:-1] >= energy_min) & (energy_edges[1:] <= energy_max)\n        data = np.broadcast_to(mask, shape=self.data_shape)\n        return Map.from_geom(geom=self, data=data)\n", "meta": {"hexsha": "5dea069bdb729f1d6b97d7b608c2d0038d8ba620", "size": 80294, "ext": "py", "lang": "Python", "max_stars_repo_path": "gammapy/maps/geom.py", "max_stars_repo_name": "Devot1on/gammapy", "max_stars_repo_head_hexsha": "6a5255cd7221f50079d36250888ca8cc763ebaf7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gammapy/maps/geom.py", "max_issues_repo_name": "Devot1on/gammapy", "max_issues_repo_head_hexsha": "6a5255cd7221f50079d36250888ca8cc763ebaf7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gammapy/maps/geom.py", "max_forks_repo_name": "Devot1on/gammapy", "max_forks_repo_head_hexsha": "6a5255cd7221f50079d36250888ca8cc763ebaf7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2881931347, "max_line_length": 122, "alphanum_fraction": 0.5470396294, "include": true, "reason": "import numpy,import scipy,from astropy", "num_tokens": 18020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.1978685452344274}}
{"text": "#!/usr/bin/env python3\n\nimport argparse\nfrom collections import Counter\nfrom multiprocessing import set_start_method\nimport pdb\nimport re\nimport sys\nimport time\nimport copy\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch import optim\nimport torch.nn.functional as F\nimport torch.multiprocessing as mp\n\nimport data_producer\n\nfrom word2atoms import skipgram_atoms, trivial_atoms, morpheme_split\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--train\", type=str, default=\"\", help=\"training file\")\nparser.add_argument(\"--output\", type=str, default=\"vectors.txt\", help=\"output word embedding file\")\nparser.add_argument(\"--atomoutput\", type=str, default=\"atomvectors.txt\", help=\"output atom embedding file\")\nparser.add_argument(\"--ctxoutput\", type=str, default=\"atomvectors.txt\", help=\"context vectors file\")\nparser.add_argument(\"--ctxatomoutput\", type=str, default=\"atomvectors.txt\", help=\"context atom vectors file\")\nparser.add_argument(\"--losslog\", type=str, default=\"all_losses.txt\", help=\"log of training losses\")\nparser.add_argument(\"--opt\", type=str, default=\"SGD\", help=\"optimiser to use\")\nparser.add_argument(\"--size\", type=int, default=300, help=\"word embedding dimension\")\nparser.add_argument(\"--cbow\", type=int, default=1, help=\"1 for cbow, 0 for skipgram\")\nparser.add_argument(\"--window\", type=int, default=5, help=\"context window size\")\nparser.add_argument(\"--sample\", type=float, default=1e-4, help=\"subsample threshold\")\nparser.add_argument(\"--negative\", type=int, default=10, help=\"number of negative samples\")\nparser.add_argument(\"--min_count\", type=int, default=5, help=\"minimum frequency of a word\")\nparser.add_argument(\"--processes\", type=int, default=4, help=\"number of processes\")\nparser.add_argument(\"--num_workers\", type=int, default=6, help=\"number of workers for data processsing\")\nparser.add_argument(\"--iter\", type=int, default=5, help=\"number of iterations\")\nparser.add_argument(\"--lr\", type=float, default=-1.0, help=\"initial learning rate\")\nparser.add_argument(\"--momentum\", type=float, default=0.0, help=\"momentum\")\nparser.add_argument(\"--batch_size\", type=int, default=100, help=\"(max) batch size\")\nparser.add_argument(\"--megabatch_size\", type=int, default=100000, help=\"(max) megabatch size\")\nparser.add_argument(\"--cuda\", action='store_true', default=False, help=\"enable cuda\")\nparser.add_argument(\"--output_ctx\", action='store_true', default=False, help=\"output context embeddings\")\nparser.add_argument(\"--anneal\", action='store_true', default=False, help=\"anneal the learning rate linearly to 0\")\nparser.add_argument(\"--shuffle\", action='store_true', default=False, help=\"shuffle the training data points\")\nparser.add_argument(\"--atomizer\", type=str, choices=['fasttext', 'morphoseg', 'word2vec'], default=\"word2vec\", help=\"atomizer to use (vanilla word2vec by default, can also choose fasttext or morphoseg)\")\nparser.add_argument(\"--minL\", type=int, default=5, help=\"minimum possible length of n-grams to take when atomizing\")\nparser.add_argument(\"--maxL\", type=int, default=5, help=\"maximum possible length of n-grams to take when atomizing\")\nparser.add_argument(\"--halfletters\", action='store_true', default=False, help=\"whether to use half-letters/raw Unicode characters when taking n-grams, or whole Tamil letters\")\n\nMAX_SENT_LEN = 1000\n\n# Build the vocabulary.\ndef file_split(f, delim=' \\t\\n', bufsize=1024):\n    prev = ''\n    while True:\n        s = f.read(bufsize)\n        if not s:\n            break\n        tokens = re.split('['+delim+']{1,}', s)\n        if len(tokens) > 1:\n            yield prev + tokens[0]\n            prev = tokens[-1]\n            for x in tokens[1:-1]:\n                yield x\n        else:\n            prev += s\n    if prev:\n        yield prev\n\ndef build_vocab(args):\n    vocab = Counter()\n    word_count = 0\n    for word in file_split(open(args.train)):\n        vocab[word] += 1\n        word_count += 1\n        if word_count % 10000 == 0:\n            sys.stdout.write('%d\\r' % len(vocab))\n    freq = {k:v for k,v in vocab.items() if v >= args.min_count}\n    word_count = sum([freq[k] for k in freq])\n    word_list = sorted(freq, key=freq.get, reverse=True)\n    word2idx = {}\n    for i,w in enumerate(word_list):\n        word2idx[w] = i\n\n    print(\"Vocab size: %ld\" % len(word2idx))\n    print(\"Words in train file: %ld\" % word_count)\n    vars(args)['vocab_size'] = len(word2idx)\n    vars(args)['train_words'] = word_count\n\n    \"\"\" for i, word in enumerate(word_list):\n        if word[-1] == '0':\n            print(i, word)\n        if i == 1761:\n            print(word) \"\"\"\n    #print(\"Initial mattrum count\")\n    #print(freq['மற்றும்'])\n    return word2idx, word_list, freq\n\ndef build_morph(args, word2idx, word_list, freq, atomiser):\n    morph_list = []\n    morph2idx = {}\n    word2morph = []\n    #total_morphperword = 0\n    max_morphperword = 0\n    #total_freq = 0\n    for i, word in enumerate(word_list):\n        idxs = []\n        cnt = 0\n        for morph in atomiser(word):\n            if morph in morph2idx:\n                idx = morph2idx[morph]\n            else:\n                idx = len(morph_list)\n                morph_list.append(morph)\n                morph2idx[morph] = idx\n            idxs.append(idx)\n            cnt += 1\n        #total_morphperword += freq[word] * cnt\n        #total_freq += freq[word]\n        if cnt > max_morphperword:\n            max_morphperword = cnt\n        word2morph.append(torch.LongTensor(idxs))\n        if i % 100 == 0:\n            sys.stdout.write('%d\\r' % i)\n    \n    # actual padding index\n    word2morph.append(torch.LongTensor([len(morph2idx)]))\n\n    word2morphfinal = torch.zeros((len(word2morph), max_morphperword), dtype=torch.long)\n    word2morphfinal = word2morphfinal.fill_(len(morph2idx) +1)\n    for i in range(len(word2morph)):\n        row = word2morph[i]\n        word2morphfinal[i, :row.shape[0]] = row\n\n    #print(word2morphfinal.shape)\n    #print(freq[word_list[0]])\n    \"\"\" indices = [0]\n    for index in indices:\n        print(word_list[index])\n        print(' '.join([morph_list[j] for j in word2morph[index]]))\n    print(word2morph[816])\n    print(word2morph[0])\n    print(word2morph[10520]) \"\"\"\n\n    print(\"Morpheme size: %ld\" % len(morph2idx))\n    #print(\"Average morphemes per word: %f\" % (float(total_morphperword)/total_freq))\n    print(\"Max morphemes per word: %d\" % max_morphperword)\n    #vars(args)['morph_size'] = len(morph2idx)\n    #vars(args)['word2morph'] = word2morph\n\n    return morph2idx, morph_list, word2morphfinal\n\nclass CBOWMean(torch.autograd.Function):\n    @staticmethod\n    def forward(ctx, x, lens):\n        ctx.save_for_backward(x)\n        x = torch.sum(x, 1, keepdim=True)\n        x = x.permute(1,2,0) / lens\n        return x.permute(2,0,1)\n    @staticmethod\n    def backward(ctx, g):\n        x, = ctx.saved_variables\n        return g.expand_as(x), None\n\nclass CBOW(nn.Module):\n    def __init__(self, args):\n        super(CBOW, self).__init__()\n        self.emb0_lookup = nn.Embedding(args.vocab_size+1, args.size, padding_idx=args.vocab_size, sparse=True)\n        self.emb1_lookup = nn.Embedding(args.vocab_size, args.size, sparse=True)\n        self.emb0_lookup.weight.data.uniform_(-0.5/args.size, 0.5/args.size)\n        self.emb0_lookup.weight.data[args.vocab_size].fill_(0)\n        self.emb1_lookup.weight.data.uniform_(-0.5/args.size, 0.5/args.size)\n        self.window = args.window\n        self.negative = args.negative\n        self.pad_idx = args.vocab_size\n\n    def forward(self, data):\n        ctx_indices = data[:, 0:2*self.window]\n        ctx_lens = data[:, 2*self.window].float()\n        word_idx = data[:, 2*self.window+1]\n        neg_indices = data[:, 2*self.window+2:2*self.window+2+self.negative]\n        neg_mask = data[:, 2*self.window+2+self.negative:].float()\n\n        c_embs = self.emb0_lookup(ctx_indices)\n        w_embs = self.emb1_lookup(word_idx)\n        n_embs = self.emb1_lookup(neg_indices)\n\n        c_embs = CBOWMean.apply(c_embs, ctx_lens)\n\n        pos_ips = torch.sum(c_embs[:,0,:] * w_embs, 1)\n        neg_ips = torch.bmm(n_embs, c_embs.permute(0,2,1))[:,:,0]\n\n        # Neg Log Likelihood\n        pos_loss = torch.sum( -F.logsigmoid(torch.clamp(pos_ips,max=10,min=-10)) )\n        neg_loss = torch.sum( -F.logsigmoid(torch.clamp(-neg_ips,max=10,min=-10)) * neg_mask )\n\n        return pos_loss + neg_loss\n\nclass SG(nn.Module):\n    def __init__(self, args):\n        super(SG, self).__init__()\n        self.emb0morph_lookup = nn.Embedding(args.morph_size+2, args.size, padding_idx=args.morph_size, sparse=True)\n        self.emb1morph_lookup = nn.Embedding(args.ctxmorph_size+2, args.size, padding_idx=args.ctxmorph_size, sparse=True)\n\n        #self.emb0_lookup = nn.Embedding(args.vocab_size+1, args.size, padding_idx=args.vocab_size, sparse=True)\n        #self.emb1_lookup = nn.Embedding(args.vocab_size, args.size, sparse=True)\n\n        self.emb0morph_lookup.weight.data.uniform_(-0.5/args.size, 0.5/args.size)\n        self.emb0morph_lookup.weight.data[args.morph_size+1].fill_(0)\n        # randomly initialise context vectors\n        #self.emb1morph_lookup.weight.data.uniform_(-0.5/args.size, 0.5/args.size)\n        #self.emb1morph_lookup.weight.data[args.ctxmorph_size+1].fill_(0)\n\n        # OR zero initialise them as usual\n        self.emb1morph_lookup.weight.data.zero_()\n\n        #self.emb0_lookup.weight.data.uniform_(-0.5/args.size, 0.5/args.size)\n        #self.emb1_lookup.weight.data.zero_()\n        #self.emb1morph_lookup.weight.data.zero_()\n\n        #self.emb0morph_lookup.weight.data[args.morph_size+1].requires_grad = False\n\n        self.window = args.window\n        self.negative = args.negative\n        self.pad_idx = args.vocab_size\n        self.morph_size = args.morph_size\n\n    def forward(self, data, word2morph, word2morph_mask, ctx2morph, ctx2morph_mask):\n        word_idx = data[:, 0]\n        ctx_idx = data[:, 1]\n        neg_indices = data[:, 2:2+self.negative]\n        neg_mask = data[:, 2+self.negative:].float()\n\n        #print(word2morph.shape)\n        #print(word2morph_mask.shape)\n\n        #print(torch.max(word2morph))\n        #print(\"MORPHEMES\")\n        #print(word2morph[3])\n        #print(torch.norm(self.emb0morph_lookup.weight.data[-1]))\n        #print(torch.norm(torch.squeeze(word2morph_mask), dim=0)) # should start nonzero, then eventually be 0\n\n        #print((self.emb0morph_lookup(word2morph[:, 0]) * word2morph_mask[:, 0]).shape)\n        #t = self.emb0morph_lookup(word2morph) * word2morph_mask\n        #print(t.shape)\n        #print(torch.sum(t, dim=1).shape)\n        w_embs = torch.sum(self.emb0morph_lookup(word2morph) * word2morph_mask, dim=1)\n        #w_embs = self.emb0_lookup(word_idx)\n\n        #t = self.emb1morph_lookup(ctx2morph[:, 0]) * ctx2morph_mask[:, 0]\n        #print(t.shape)\n        #print(torch.sum(t, dim=1).shape)\n        #print((self.emb0morph_lookup(word2morph[:, 1]) * word2morph_mask[:, 1]).shape)\n        c_embs = torch.sum(self.emb1morph_lookup(ctx2morph[:, 0]) * ctx2morph_mask[:, 0], dim=1)\n        #c_embs = self.emb1_lookup(ctx_idx)\n        \n        #t = self.emb1morph_lookup(ctx2morph[:, 1:1+self.negative]) * ctx2morph_mask[:, 1:1+self.negative]\n        #print(t.shape)\n        #print(torch.sum(t, dim=2).shape)\n        #print((self.emb0morph_lookup(word2morph[:, 2:2+self.negative]) * word2morph_mask[:, 2:2+self.negative]).shape)\n        n_embs = torch.sum(self.emb1morph_lookup(ctx2morph[:, 1:1+self.negative]) * ctx2morph_mask[:, 1:1+self.negative], dim=2)\n        #n_embs = self.emb1_lookup(neg_indices)\n\n        pos_ips = torch.sum(w_embs * c_embs, 1)\n        neg_ips = torch.bmm(n_embs, torch.unsqueeze(w_embs,1).permute(0,2,1))[:,:,0]\n\n        # Neg Log Likelihood\n        pos_loss = torch.sum( -F.logsigmoid(torch.clamp(pos_ips,max=10,min=-10)) )\n        neg_loss = torch.sum( -F.logsigmoid(torch.clamp(-neg_ips,max=10,min=-10)) * neg_mask )\n\n        return pos_loss + neg_loss\n\n# Initialize model.\ndef init_net(args):\n    if args.cbow == 1:\n        if args.lr == -1.0:\n            vars(args)['lr'] = 0.05\n        return CBOW(args)\n    elif args.cbow == 0:\n        if args.lr == -1.0:\n            vars(args)['lr'] = 0.025\n        return SG(args)\n\n# Training\ndef train_process_sent_producer(p_id, data_queue, word_count_actual, word2idx, word_list, freq, args):\n    if args.negative > 0:\n        table_ptr_val = data_producer.init_unigram_table(word_list, freq, args.train_words)\n\n    train_file = open(args.train)\n    file_pos = args.file_size * p_id // args.processes\n    train_file.seek(file_pos, 0)\n    while True:\n        try:\n            train_file.read(1)\n        except UnicodeDecodeError:\n            file_pos -= 1\n            train_file.seek(file_pos, 0)\n        else:\n            train_file.seek(file_pos, 0)\n            break\n\n    batch_count = 0\n    if args.cbow == 1:\n        batch_placeholder = np.zeros((args.megabatch_size, 2*args.window+2+2*args.negative), 'int64')\n    else:\n        batch_placeholder = np.zeros((args.megabatch_size, 2+2*args.negative), 'int64')\n    #mattrum_cnt = 0\n    for it in range(args.iter):\n        train_file.seek(file_pos, 0)\n\n        last_word_cnt = 0\n        word_cnt = 0\n        sentence = []\n        prev = ''\n        eof = False\n        while True:\n            if eof or train_file.tell() > file_pos + args.file_size / args.processes:\n                break\n\n            while True:\n                s = train_file.read(1)\n                if not s:\n                    eof = True\n                    break\n                elif s == ' ' or s == '\\t':\n                    if prev in word2idx:\n                        sentence.append(prev)\n                    prev = ''\n                    if len(sentence) >= MAX_SENT_LEN:\n                        break\n                elif s == '\\n':\n                    if prev in word2idx:\n                        sentence.append(prev)\n                    prev = ''\n                    break\n                else:\n                    prev += s\n\n            if len(sentence) > 0:\n                #print(\"Full sentence\")\n                #print(' '.join(sentence))\n                # subsampling\n                sent_id = []\n                trimmed = []\n                if args.sample != 0:\n                    sent_len = len(sentence)\n                    i = 0\n                    while i < sent_len:\n                        word = sentence[i]\n                        f = freq[word] / args.train_words\n                        pb = (np.sqrt(f / args.sample) + 1) * args.sample / f\n\n                        if pb > np.random.random_sample():\n                            sent_id.append( word2idx[word] )\n                            \"\"\" if word2idx[word] == 'மற்றும்' and mattrum_cnt % 1000 == 0:\n                                print(\"Hit another 1000 mattrums\")\n                                mattrum_cnt += 1\n                        else:\n                            trimmed.append(word) \"\"\"\n                        i += 1\n\n                if len(sent_id) < 2:\n                    word_cnt += len(sentence)\n                    sentence.clear()\n                    continue\n                \n                #print(\"Killed words\")\n                #print(' '.join(trimmed))\n                #print(\"Trimmed sentence\")\n                #print(' '.join([word_list[index] for index in sent_id]))\n\n                next_random = (2**24) * np.random.randint(0, 2**24) + np.random.randint(0, 2**24)\n                if args.cbow == 1: # train CBOW\n                    chunk = data_producer.cbow_producer(sent_id, len(sent_id), table_ptr_val,\n                                args.window, args.negative, args.vocab_size, args.batch_size, next_random)\n                elif args.cbow == 0: # train skipgram\n                    chunk = data_producer.sg_producer(sent_id, len(sent_id), table_ptr_val,\n                                args.window, args.negative, args.vocab_size, args.batch_size, next_random)\n                \n                #print(\"Data points\")\n                #print(chunk)\n                \n                chunk_pos = 0\n                while chunk_pos < chunk.shape[0]:\n                    remain_space = args.megabatch_size - batch_count\n                    remain_chunk = chunk.shape[0] - chunk_pos\n\n                    if remain_chunk < remain_space:\n                        take_from_chunk = remain_chunk\n                    else:\n                        take_from_chunk = remain_space\n\n                    batch_placeholder[batch_count:batch_count+take_from_chunk, :] = chunk[chunk_pos:chunk_pos+take_from_chunk, :]\n                    batch_count += take_from_chunk\n\n                    if batch_count == args.megabatch_size:\n                        if args.shuffle:\n                            p = torch.randperm(batch_count)\n                            batch_placeholder = batch_placeholder[p]\n\n                        start = 0\n                        while start < batch_count:\n                            data_queue.put(batch_placeholder[start : min(start + args.batch_size, batch_count)])\n                            start += args.batch_size\n                        #print(\"Batch placeholder\")\n                        #print(batch_placeholder)\n                        batch_count = 0\n\n                    chunk_pos += take_from_chunk\n\n                word_cnt += len(sentence)\n                if word_cnt - last_word_cnt > 10000:\n                    with word_count_actual.get_lock():\n                        word_count_actual.value += word_cnt - last_word_cnt\n                    last_word_cnt = word_cnt\n                sentence.clear()\n\n        with word_count_actual.get_lock():\n            word_count_actual.value += word_cnt - last_word_cnt\n\n    #print(\"Total occurrences of mattrum: \" + str(mattrum_cnt))\n    #print(\"Total non-occurrences of mattrum: \" + str(non_mattrum_cnt))\n    if batch_count > 0:\n        if args.shuffle:\n            p = torch.randperm(batch_count)\n            batch_placeholder[:batch_count] = batch_placeholder[p]\n\n        start = 0\n        while start < batch_count:\n            data_queue.put(batch_placeholder[start : min(start + args.batch_size, batch_count)])\n            start += args.batch_size\n        #print(\"Batch placeholder\")\n        #print(batch_placeholder)\n        batch_count = 0\n    data_queue.put(None)\n\ndef train_process(p_id, word_count_actual, word2idx, word_list, freq, args, model, word2morph, word2morph_mask, ctx2morph, ctx2morph_mask):\n    data_queue = mp.SimpleQueue()\n\n    if args.opt == \"Adagrad\":\n        optimizer = optim.Adagrad(model.parameters(), lr=args.lr)\n    elif args.opt == \"SGD\":\n        optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum)\n    elif args.opt == 'SparseAdam':\n        optimizer = optim.SparseAdam(model.parameters(), lr=args.lr)\n\n    t = mp.Process(target=train_process_sent_producer, args=(p_id, data_queue, word_count_actual, word2idx, word_list, freq, args))\n    t.start()\n\n    # get from data_queue and feed to model\n    prev_word_cnt = 0\n    losses_cnt = 0\n    total_loss = 0.0\n    losses_file = open(args.losslog, 'w')\n    lr = args.lr\n    #mattrum_cnt = 0\n    #non_mattrum_cnt = 0\n    while True:\n        d = data_queue.get()\n        if d is None:\n            break\n        else:\n            # lr anneal\n            if args.anneal:\n                if word_count_actual.value - prev_word_cnt > 10000:\n                    lr = args.lr * (1 - word_count_actual.value / (args.iter * args.train_words))\n                    if lr < 0.0001 * args.lr:\n                        lr = 0.0001 * args.lr\n                    for param_group in optimizer.param_groups:\n                        param_group['lr'] = lr\n            else:\n                lr = args.lr\n\n            if args.cuda:\n                data = Variable(torch.LongTensor(d).cuda(), requires_grad=False)\n            else:\n                data = Variable(torch.LongTensor(d), requires_grad=False)\n\n            if args.cbow == 1:\n                optimizer.zero_grad()\n                loss = model(data)\n                loss.backward()\n                optimizer.step()\n                model.emb0_lookup.weight.data[args.vocab_size].fill_(0)\n            elif args.cbow == 0:\n                optimizer.zero_grad()\n                #print(\"WORD\")\n                #print(data[3][0])\n                loss = model(data, word2morph[data[:, 0]], word2morph_mask[data[:, 0]], ctx2morph[data[:, 1:2+args.negative]], ctx2morph_mask[data[:, 1:2+args.negative]])\n                loss.backward()\n                #model.emb0morph_lookup.weight.data.grad[args.morph_size+1].fill_(0)\n                optimizer.step()\n                #model.emb0morph_lookup.weight.data[args.morph_size+1].zero_()\n            \n            losses_cnt += data.shape[0]\n            total_loss += loss\n\n            # output\n            if word_count_actual.value - prev_word_cnt > 10000:\n                avg_loss = total_loss/losses_cnt\n                sys.stdout.write(\"\\rAlpha: %0.8f, Loss: %0.8f, Progress: %0.2f, Words/sec: %f\" % (lr, avg_loss, word_count_actual.value / (args.iter * args.train_words) * 100, word_count_actual.value / (time.monotonic() - args.t_start)))\n                sys.stdout.flush()\n                prev_word_cnt = word_count_actual.value\n                losses_cnt = 0\n                total_loss = 0.0\n                losses_file.write(str(avg_loss.item()) + '\\n')\n\n    losses_file.close()\n    t.join()\n\nif __name__ == '__main__':\n    set_start_method('forkserver')\n\n    args = parser.parse_args()\n    print(\"Starting training using file %s\" % args.train)\n    train_file = open(args.train)\n    train_file.seek(0, 2)\n    vars(args)['file_size'] = train_file.tell()\n\n    word2idx, word_list, freq = build_vocab(args)\n    # constructing and applying atomizer to all words\n    minL = args.minL\n    maxL = args.maxL\n    use_listify = not args.halfletters\n    if args.atomizer == 'word2vec':\n        atomizer = lambda w: trivial_atoms(w)\n    elif args.atomizer == 'fasttext':\n        atomizer = lambda w: skipgram_atoms(w, minL=minL, maxL=maxL)\n    elif args.atomizer == 'morphoseg':\n        atomizer = lambda w: morpheme_split(w, minL=minL, maxL=maxL, use_listify=use_listify, to_stem=True)\n    \n    morph2idx, morph_list, word2morph = build_morph(args, word2idx, word_list, freq, atomizer)\n    vars(args)['morph_size'] = len(morph2idx)\n\n    ctxmorph2idx, ctxmorph_list, ctx2morph = build_morph(args, word2idx, word_list, freq, trivial_atoms)\n    vars(args)['ctxmorph_size'] = len(ctxmorph2idx)\n\n    #print(word2morph.shape)\n    #print(ctx2morph.shape)\n    \n\n    \"\"\" idx = 200\n    word = word_list[idx]\n    print(\"Word: \" + word)\n    print(\"Index should be: \" + str(word2idx[word]))\n    all_morphs = word2morph[idx]\n    for midx in all_morphs:\n        print(\"Morpheme: \" + morph_list[midx])\n        print(\"Index used for lookup: \" + str(midx))\n        print(\"Index retrieved: \" + str(morph2idx[morph_list[midx]])) \"\"\"\n\n    word_count_actual = mp.Value('L', 0)\n\n    model = init_net(args)\n    model.share_memory()\n    word2morph_mask = torch.unsqueeze((word2morph <= args.morph_size), dim=2).type(model.emb0morph_lookup.weight.data.dtype)\n    ctx2morph_mask = torch.unsqueeze((ctx2morph <= args.ctxmorph_size), dim=2).type(model.emb1morph_lookup.weight.data.dtype)\n    \n    if args.cuda:\n        model.cuda()\n        word2morph = word2morph.cuda()\n        word2morph_mask = word2morph_mask.cuda()\n        ctx2morph = ctx2morph.cuda()\n        ctx2morph_mask = ctx2morph_mask.cuda()\n\n    #print(word2morph_mask.shape)\n    #print(ctx2morph_mask.shape)\n\n    vars(args)['t_start'] = time.monotonic()\n    processes = []\n    for p_id in range(args.processes):\n        p = mp.Process(target=train_process, args=(p_id, word_count_actual, word2idx, word_list, freq, args, model, word2morph, word2morph_mask, ctx2morph, ctx2morph_mask))\n        p.start()\n        processes.append(p)\n\n    for p in processes:\n        p.join()\n\n    torch.cuda.empty_cache()\n\n    # print out the atom input vectors\n    if args.cuda:\n        embs = model.emb0morph_lookup.weight.data.cpu().numpy()\n    else:\n        embs = model.emb0morph_lookup.weight.data.numpy()\n    \n    #print(embs.shape)\n    data_producer.write_embs(args.atomoutput, morph_list, embs, args.morph_size, args.size)\n    del embs\n    torch.cuda.empty_cache()\n\n    wordembs = np.zeros((word2morph.shape[0], args.size), dtype=np.float32)\n    print(wordembs.shape)\n    # word input vectors\n    if args.cuda:\n        numpieces = 5\n        cnt = word2morph.shape[0] // numpieces\n        print(\"Need to handle \" + str(word2morph.shape[0]) + \" words\")\n        for j in range(numpieces):\n            start = j * cnt\n            end = start + cnt\n            if j == numpieces - 1:\n                end = word2morph.shape[0]\n            print(\"Handling all words from \" + str(start) + \" to \" + str(end))\n            wordembs[start:end] = torch.sum(model.emb0morph_lookup(word2morph[start:end]) * word2morph_mask[start:end], dim=1).detach().cpu().numpy()\n    else:\n        wordembs = torch.sum(model.emb0morph_lookup(word2morph) * word2morph_mask, dim=1).detach().numpy()\n\n    #print(wordembs.shape)\n    data_producer.write_embs(args.output, word_list, wordembs, args.vocab_size, args.size)\n    del wordembs\n    torch.cuda.empty_cache()\n\n    # atom context vectors\n    if args.cuda:\n        atembs = model.emb1morph_lookup.weight.data.cpu().numpy()\n    else:\n        atembs = model.emb1morph_lookup.weight.data.numpy()\n    \n    #print(atembs.shape)\n    data_producer.write_embs(args.ctxatomoutput, ctxmorph_list, atembs, args.ctxmorph_size, args.size)\n    del atembs\n    torch.cuda.empty_cache()\n\n    # word context vectors\n    ctxembs = np.zeros((ctx2morph.shape[0], args.size), dtype=np.float32)\n    print(ctxembs.shape)\n    if args.cuda:\n        numpieces = 5\n        cnt = ctx2morph.shape[0] // numpieces\n        print(\"Need to handle \" + str(ctx2morph.shape[0]) + \" words\")\n        for j in range(numpieces):\n            start = j * cnt\n            end = start + cnt\n            if j == numpieces - 1:\n                end = ctx2morph.shape[0]\n            print(\"Handling all words from \" + str(start) + \" to \" + str(end))\n            ctxembs[start:end] = torch.sum(model.emb1morph_lookup(ctx2morph[start:end]) * ctx2morph_mask[start:end], dim=1).detach().cpu().numpy()\n    else:\n        ctxembs = torch.sum(model.emb1morph_lookup(ctx2morph) * ctx2morph_mask, dim=1).detach().numpy()\n\n    #print(ctxembs.shape)\n    data_producer.write_embs(args.ctxoutput, word_list, ctxembs, args.vocab_size, args.size)\n    del ctxembs\n    torch.cuda.empty_cache()\n\n    print(\"\")\n\n", "meta": {"hexsha": "94633901f9dd9fe9d6453b2bb827bffd3f1c2613", "size": 26576, "ext": "py", "lang": "Python", "max_stars_repo_path": "pytorch-word2vec-master/.ipynb_checkpoints/main-checkpoint.py", "max_stars_repo_name": "arjun-sai-krishnan/tamil-morpho-embeddings", "max_stars_repo_head_hexsha": "a33bcb427d635dba3b1857f26ea7ab287e1a44c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-11T18:25:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T03:48:52.000Z", "max_issues_repo_path": "pytorch-word2vec-master/.ipynb_checkpoints/main-checkpoint.py", "max_issues_repo_name": "arjun-sai-krishnan/tamil-morpho-embeddings", "max_issues_repo_head_hexsha": "a33bcb427d635dba3b1857f26ea7ab287e1a44c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pytorch-word2vec-master/.ipynb_checkpoints/main-checkpoint.py", "max_forks_repo_name": "arjun-sai-krishnan/tamil-morpho-embeddings", "max_forks_repo_head_hexsha": "a33bcb427d635dba3b1857f26ea7ab287e1a44c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6983154671, "max_line_length": 237, "alphanum_fraction": 0.6038154726, "include": true, "reason": "import numpy", "num_tokens": 6726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.35936413829896496, "lm_q1q2_score": 0.19786854145663482}}
{"text": "###################################\n# Script : \n# 1) Contains class to validate models\n# built using SAS datasets\n#\n# ganesans - Salilab - UCSF\n# ganesans@salilab.org\n###################################\nimport pandas as pd\nimport sys,os,math\nimport numpy as np\nimport pandas as pd\nimport re,pickle,requests,json\nfrom sklearn.linear_model import LinearRegression\nfrom decimal import Decimal\nfrom validation import get_input_information \nfrom subprocess import run, call, PIPE\nfrom decouple import config\n\n\n\nclass sas_validation(get_input_information):\n    def __init__(self,mmcif_file):\n        super().__init__(mmcif_file)\n        self.ID=str(get_input_information.get_id(self))\n        self.nos=get_input_information.get_number_of_models(self)\n        self.dataset=get_input_information.get_dataset_comp(self) \n        self.imagepath='../static/images/'\n        self.saslink='https://www.sasbdb.org/media/sascif/sascif_files/'\n        self.sasentry='https://www.sasbdb.org/rest-api/entry/summary/'\n    \n    def get_SASBDB_code(self)->list:\n        '''\n        function to get all SASBDB codes used in the model,\n        returns a list of SASBDB codes\n        '''\n        SAS_db_codes=[]\n        for indx,datatype in enumerate(self.dataset['Dataset type']):\n            if 'SAS' in str(datatype):\n                SAS_db_codes.append(self.dataset['Data access code'][indx])\n        return SAS_db_codes\n\n    def clean_SASBDB_code(self)->list:\n        '''\n        function to clean SASBDB list of codes\n        as some might have 'None' or can be repetitive \n        '''\n        codes=list(set(self.get_SASBDB_code()))\n        cleaned_code=[i for i in codes if i != 'None']\n        return cleaned_code\n\n    def get_data_from_SASBDB(self)->dict:\n        '''\n        get data from JSON\n        '''\n        data_dic={}\n        for code in self.get_SASBDB_code():\n            if 'None' not in str(code):\n                url_f=self.sasentry+code+'.json'\n                response=requests.get(url_f, data={'key':'value'});\n                if response.status_code!=200:\n                    print (\"Error....unable to fetch data from SASBDB, please check the entry ID\")\n                data_dic[code]=response.json();\n                with open (code+'.json', 'w') as f:\n                    formatted_data=json.dumps(response.json(), indent = 4, sort_keys=True);\n                    f.write(formatted_data);\n        return data_dic\n\n    def get_sascif_file(self):\n        '''\n        get data from SASCIF files\n        '''\n        for code in self.get_SASBDB_code():\n            if 'None' not in str(code):\n                url_f=self.saslink+code+'.sascif'\n                response=requests.get(url_f);\n                if response.status_code!=200:\n                    print (\"Error....unable to fetch data from SASBDB, please check the entry ID\")\n                with open (code+'.sascif', 'w') as f:\n                    f.write(response.text);\n\n    def get_all_sascif(self,sasbdb)->list:\n        '''\n        get a list of all lines in a SASCIF file\n        '''\n        if 'None' not in str(sasbdb):\n            file=open(sasbdb+'.sascif','r')\n            all_lines=[data.strip().split() for indx,data in enumerate(file.readlines())]\n        return all_lines\n\n    def get_intensities(self)->dict:\n        '''\n        get intensity data from SASCIF file\n        if SASCIF file is not present, this information will not be present/used in the report\n        JSON file typically has raw data \n        '''\n        self.get_sascif_file()\n        Int_dict={}\n        for code in self.clean_SASBDB_code():\n            #Int_dict={}\n            all_lines=self.get_all_sascif(code)\n            data={}\n            for indx,sascifline in enumerate(all_lines):\n                if len(sascifline)<2 and len(sascifline)>0 and 'scan_intensity' in sascifline[0]:\n                    data[(sascifline[0].split('.')[1])]=[]\n                if len(sascifline)>2 and len(all_lines[indx-1])>0 and'scan_intensity' in all_lines[indx-1][0]:\n                    for indx_sub,sascifline_sub in enumerate(all_lines[indx:]):\n                        if len(sascifline_sub)>2 and '#' not in sascifline_sub and 'sas' not in sascifline_sub[0] :  \n                            for num,key in enumerate(list(data.keys())):\n                                data[key].append(sascifline_sub[num])\n                        else:\n                            break        \n            I_df=pd.DataFrame(list(data.values()),index=list(data.keys())).T\n            I_df_re=I_df[['momentum_transfer','intensity','intensity_su_counting']]\n            I_df_re.rename(columns={'momentum_transfer':'Q','intensity':'I','intensity_su_counting':'E'},inplace=True)\n            Int_dict[code]=I_df_re\n        return Int_dict\n\n    def modify_intensity(self)->dict:\n        '''\n        modify intensity data to calcualte errors and log values\n        '''\n        Int_dict=self.get_intensities()\n        Int_dict_modify={}\n        rg_and_io=self.get_rg_and_io()\n        for key,val in Int_dict.items():\n            Rg=rg_and_io[key][0]\n            IO=rg_and_io[key][1]\n            dim_num=Rg*Rg/IO\n            I_df=val.astype({'Q':float,'I':float,'E':float})\n            I_df=I_df[I_df['I']-I_df['E']>0]\n            I_df['Q']=I_df['Q']*10\n            I_df['err_x']=I_df.apply(lambda row: (row['Q'],row['Q']), axis=1) \n            I_df['err_y']=I_df.apply(lambda row: (np.log(row['I']-row['E']),np.log(row['I']+row['E'])),axis=1)\n            I_df['logI']=np.log(I_df['I'])\n            I_df['logQ']=np.log(I_df['Q'])\n            I_df['logX']=I_df.apply(lambda row: (row['logQ'],row['logQ']), axis=1)\n            I_df['Ky']=I_df['Q']*I_df['Q']*I_df['I']*dim_num\n            I_df['Kx']=I_df['Q']*Rg\n            I_df['Px']=I_df['Q']**4\n            I_df['Px'].round(3)\n            I_df['Py']=I_df['Px']*I_df['I']\n            Int_dict_modify[key]=I_df\n        return Int_dict_modify\n\n    def modify_intensity_dep(self)->dict:\n        '''\n        depreciated function to get intensities from JSON/raw data\n        '''\n        Int_dict=self.get_intensities()\n        Int_dict_modify={}\n        for key,val in Int_dict.items():\n            I_df=val.astype({'Q':float,'I':float,'E':float})\n            I_df.head()\n            I_df=I_df[I_df['I']-I_df['E']>0]\n            I_df['Q']=I_df['Q']*10\n            I_df['err_x']=I_df.apply(lambda row: (row['Q'],row['Q']), axis=1) \n            I_df['err_y']=I_df.apply(lambda row: (np.log(row['I']-row['E']),np.log(row['I']+row['E'])),axis=1)\n            I_df['logI']=np.log(I_df['I'])\n            I_df['logQ']=np.log(I_df['Q'])\n            I_df['logX']=I_df.apply(lambda row: (row['logQ'],row['logQ']), axis=1)\n            I_df['Ky']=I_df['Q']*I_df['Q']*I_df['I']\n            I_df['Px']=I_df['Q']**4\n            I_df['Px'].round(3)\n            I_df['Py']=I_df['Px']*I_df['I']\n            Int_dict_modify[key]=I_df\n        return Int_dict_modify\n\n    def get_rg_for_plot(self)->dict:\n        '''\n        get Rg values from SASCIF file, if unavailabel, get it from JSON\n        '''\n        self.get_sascif_file()\n        Rg_dict={}\n        for code in self.clean_SASBDB_code():\n            rg={};\n            all_lines=self.get_all_sascif(code)\n            for indx,sascifline in enumerate(all_lines):\n                if len(sascifline)<3 and len(sascifline)>0 and 'sas_result.Rg_from_PR' in sascifline[0] and'sas_result.Rg_from_PR_' not in sascifline[0] :\n                    rg[sascifline[0].split('.')[1]]=float(sascifline[1])\n                if len(sascifline)<3 and len(sascifline)>0 and 'sas_result.Rg_from_Guinier' in sascifline[0] and'sas_result.Rg_from_Guinier_' not in sascifline[0] :\n                    rg[sascifline[0].split('.')[1]]=float(sascifline[1])\n            Rg_dict[code]=list(rg.values())\n\n        if len(list(rg.values()))<1:\n            data_dic=self.get_data_from_SASBDB()\n            for key,val in data_dic.items():\n                Rg_dict[key]=[]\n                Rg_dict[key].append(round(float(val['guinier_rg']),2))\n                Rg_dict[key].append(round(float(val['pddf_rg']),2))\n        return Rg_dict\n\n    def get_rg_and_io(self)->dict:\n        '''\n        get rg information from SASCIF file\n        '''\n        self.get_sascif_file()\n        rg_and_io={}\n        for code in self.clean_SASBDB_code():\n            all_lines=self.get_all_sascif(code)\n            for indx,sascifline in enumerate(all_lines):\n                if len(sascifline)<3 and len(sascifline)>0 and 'sas_result.Rg_from_PR' in sascifline[0] and'sas_result.Rg_from_PR_' not in sascifline[0] :\n                    rg=float(sascifline[1])\n                if len(sascifline)<3 and len(sascifline)>0 and '_sas_result.I0_from_PR' in sascifline[0] and'_sas_result.I0_from_PR_' not in sascifline[0] :\n                    io=float(sascifline[1])\n            rg_and_io[code]=(rg,io)\n        return rg_and_io\n\n    def get_rg_table_many(self)->dict:\n        '''\n        get rg information from multiple SASCIF files\n        '''\n        data_dic=self.get_data_from_SASBDB()\n        rg_table={'SASDB ID':[],'Rg':[],'Rg error':[],'MW':[],'MW error':[]}        \n        for key,val in data_dic.items():\n            rg_table['Rg'].append(str(round(float(val['guinier_rg']),2))+ ' nm')\n            try:\n                rg_table['Rg error'].append(val['guinier_rg_error']+ ' nm')\n            except:\n                rg_table['Rg error'].append('N/A')\n            try:\n                rg_table['MW'].append(val['guinier_i0_mw']+ ' nm')\n            except:\n                rg_table['MW'].append('N/A')\n            try:\n                rg_table['MW error'].append(val['guinier_i0_mw_error']+ ' nm')\n            except:\n                rg_table['MW error'].append('N/A')\n            rg_table['SASDB ID'].append(key)\n        return rg_table\n\n\n    def get_fits_for_plot(self)->dict:\n        '''\n        get chi-squared values from SASCIF files\n        '''\n        self.get_sascif_file()\n        fit_dict={}\n        for code in self.clean_SASBDB_code():\n            fits=[];\n            all_lines=self.get_all_sascif(code)\n            for indx,sascifline in enumerate(all_lines):\n                if (len(sascifline)<3) and (len(sascifline)>0) and ('sas_model_fitting_details.chi_square' in sascifline[0]) and (float(sascifline[1])>0.00000):\n                    fits.append(round(float(sascifline[1]),2))\n            if len(fits)>0:\n                fit_dict[code]=fits\n        return fit_dict\n\n    def get_pofr(self)->dict:\n        '''\n        get pair-dist distribution from SASCIF files\n        '''\n        pofr_dict={}\n        for code in self.clean_SASBDB_code():\n            all_lines=self.get_all_sascif(code)\n            data={}\n            for indx,sascifline in enumerate(all_lines):\n                if len(sascifline)<2 and len(sascifline)>0 and 'sas_p_of_R.' in sascifline[0]:\n                    data[(sascifline[0].split('.')[1])]=[]\n                if len(sascifline)>2 and len(all_lines[indx-1])>0 and 'sas_p_of_R.' in all_lines[indx-1][0]:\n                    for subindx,subval in enumerate(all_lines[indx:]):\n                        if len(subval)>2 and '#' not in subval and 'sas' not in subval[0] :\n                            for num,key in enumerate(list(data.keys())):\n                                data[key].append(subval[num])\n                        else:\n                            break\n            pdf=pd.DataFrame(list(data.values()),index=list(data.keys())).T\n            pdf_re=pdf[['r','P','P_error']]\n            pdf_re.rename(columns={'r':'R','P':'P','P_error':'E'},inplace=True)\n            pofr_dict[code]=pdf_re\n        return pofr_dict\n\n    def get_pvals(self)->dict:\n        '''\n        get p-values from ATSAS \n        '''\n        data_dic=self.get_data_from_SASBDB()\n        num_of_fits=self.get_number_of_fits()\n        pval_table={'SASDB ID':[],'Model':[],'p-value':[]}        \n        for key,val in data_dic.items():\n            num=num_of_fits[key]\n            if num>0:\n                for fitnum in range(0,num):\n                    pval_table['SASDB ID'].append(key)\n                    pval_table['Model'].append(fitnum+1)\n                    target_url=val['fits'][fitnum]['fit_data']      \n                    fit = requests.get(target_url);\n                    if fit.status_code !=200:\n                        print (\"Error....unable to fetch data from SASBDB, please check the entry ID\")\n                    fname=key+str(fitnum)+'fit.csv'\n                    with open (fname,'w') as f:\n                        f.write(fit.text)\n                    f_df=pd.read_csv(fname, skiprows=3,delim_whitespace=True, names=['Q','Ie','Ib','E'])\n                    if abs(f_df.iloc[22,2]-f_df.iloc[22,1])>abs(f_df.iloc[22,3]-f_df.iloc[22,1]):\n                        f_df.rename(columns={'Q':'Q','Ie':'Ie','Ib':'E','E':'Ib'},inplace=True)\n                    fit_1=f_df[['Q','Ie']]\n                    fit_1.to_csv('fit1.csv',header=False,index=False)\n                    fit_2=f_df[['Q','Ib']]\n                    fit_2.to_csv('fit2.csv',header=False,index=False)\n                    f1=open('pval.txt','w+')\n                    with f1 as outfile:\n                        run([config('ATSAS'),'fit1.csv','fit2.csv'],stdout=outfile)\n                    f2=open('pval.txt','r')\n                    all_lines=[j.strip().split() for i,j in enumerate(f2.readlines())]\n                    p_val=[all_lines[i+1][4] for i,j in enumerate(all_lines) if 'adj' in j][0]\n                    pval_table['p-value'].append('%.2E' % Decimal(p_val))\n            else:\n                pval_table['SASDB ID'].append(key)\n                pval_table['Model'].append('N/A')\n                pval_table['p-value'].append('N/A')\n        return pval_table\n\n    def get_pofr_ext(self)->dict:\n        '''\n        get pair-distance details from SASCIF files\n        '''\n        pofr_dict={}\n        for code in self.clean_SASBDB_code():\n            all_lines=self.get_all_sascif(code)\n            data={}\n            for indx,sascifline in enumerate(all_lines):\n                if len(sascifline)<2 and len(sascifline)>0 and '_sas_p_of_R_extrapolated_intensity.' in sascifline[0]:\n                    data[(sascifline[0].split('.')[1])]=[]\n                if len(sascifline)>2 and len(all_lines[indx-1])>0 and '_sas_p_of_R_extrapolated_intensity.' in all_lines[indx-1][0]:\n                    for subindx,subval in enumerate(all_lines[indx:]):\n                        if len(subval)>2 and '#' not in subval and 'sas' not in subval[0] :\n                            for num,key in enumerate(list(data.keys())):\n                                data[key].append(subval[num])\n                        else:\n                            break\n            pdf=pd.DataFrame(list(data.values()),index=list(data.keys())).T\n            pdf_re=pdf[['momentum_transfer','intensity_reg']]\n            pdf_re.rename(columns={'momentum_transfer':'Q','intensity_reg':'I'},inplace=True)\n            pdf_re=pdf_re.astype({'Q':float,'I':float})\n            pdf_re['Q']=pdf_re['Q']*10\n            pdf_re['logI']=np.log(pdf_re['I'])\n            pofr_dict[code]=pdf_re\n        return pofr_dict\n\n    def get_pofr_errors(self)->dict:\n        '''\n        get pair-distance details and errors from JSON files\n        '''\n        pofr_dict=self.get_pofr_ext()\n        Int_dict=self.modify_intensity()\n        compiled_dict={}\n        for code in self.clean_SASBDB_code():\n            I_df=Int_dict[code]\n            I_df_dict= dict(zip(I_df.Q, I_df.I))\n            I_df_err_dict= dict(zip(I_df.Q, I_df.E))\n            p_df=pofr_dict[code]\n            p_df_dict=dict(zip(p_df.Q, p_df.I))\n            errors=[]\n            for Q,I in p_df_dict.items():\n                data_Q=self.findMinDiff(list(I_df_dict.keys()),Q)\n                if data_Q != 9999:\n                    data_I=I_df_dict[data_Q]\n                    delta_I=(I-data_I)\n                    if I_df_err_dict[data_Q] != 0:\n                        wt_delta_I=delta_I/I_df_err_dict[data_Q]\n                    else:\n                        wt_delta_I=0\n                    errors.append([Q,delta_I,wt_delta_I])\n            errors_df=pd.DataFrame(errors,columns=['Q','R','WR'])\n            compiled_dict[code]=errors_df\n        return compiled_dict\n\n    def findMinDiff(self,listn: list, num: int)-> int: \n        '''\n        quick min diff operation for calculating errors\n        '''\n        list_sub=[(i,abs(j-num)) for i,j in enumerate(listn)]\n        list_sort=sorted(list_sub, key=lambda x: x[1])\n        if list_sort[0][1]<0.00001:\n            return listn[list_sort[0][0]]\n        else:\n            return 9999  \n\n    def get_Guinier_data(self)->(dict,dict):\n        '''\n        get Guinier plot data from JSON files\n        '''\n        Int_dict=self.get_intensities()\n        data_dic=self.get_data_from_SASBDB()\n        Guinier_dict={};Guinier_score={}\n        for key,val in Int_dict.items():\n            G_df=val.astype({'Q':float,'I':float,'E':float})\n            G_df['logI']=np.log(G_df['I'])\n            rg=float(data_dic[key]['pddf_rg'])\n            dmax=float(data_dic[key]['pddf_dmax'])\n            index_low=int(data_dic[key]['guinier_point_first'])\n            index_high=int(data_dic[key]['guinier_point_last'])\n            q_min=math.pi/(dmax*10)\n            q_max=1.3/(rg*10)\n            G_df_range=G_df[G_df['Q']<q_max].copy()\n            G_df_range['Q']=G_df['Q']*10\n            G_df_range['Q2']=G_df_range['Q']**2\n            X=G_df_range[['Q2']].values\n            y=G_df_range['logI'].values\n            regression=LinearRegression(fit_intercept=True)\n            regression.fit(X,y)\n            G_df_range['y_pred']=regression.predict(X)\n            G_df_range['res']=y-regression.predict(X)\n            G_df_range['Q2A']=G_df_range['Q2']*100\n            score='%.2f' %regression.score(X,y)\n            Guinier_score[key]=score\n            Guinier_dict[key]=G_df_range\n        return Guinier_score,Guinier_dict\n\n    def get_parameters_vol_many_dep(self)->dict:\n        '''\n        get volume parameters from JSON files \n        '''\n        data_dic=self.get_data_from_SASBDB()\n        parameter_table={'SASDB ID':[],'Estimated volume':[],'Estimated volume method':[],'Porod volume':[]}\n        for key,val in data_dic.items():\n            try:\n                if parameter_table['Estimated volume'] is None:\n                    parameter_table['Estimated volume'].append('N/A')\n                else:\n                    parameter_table['Estimated volume'].append(val['estimated_volume'])\n                if parameter_table['Estimated volume method'] is None:\n                    parameter_table['Estimated volume method'].append('N/A')\n                else:\n                    parameter_table['Estimated volume method'].append(val['estimated_volume_method'])\n            except:\n                parameter_table['Estimated volume'].append('N/A')\n                parameter_table['Estimated volume method'].append('N/A')\n            try:\n                parameter_table['Porod volume'].append(val['porod_volume']+' nm\\u00b3')\n            except:\n                parameter_table['Porod volume'].append('N/A')\n            parameter_table['SASDB ID'].append(key)\n        return parameter_table\n\n    def get_parameters_vol_many(self)->dict:\n        '''\n        get volume details from SASCIF files\n        '''\n        self.get_sascif_file()\n        parameter_table={'SASDB ID':[],'Estimated Volume':[],'Porod Volume':[],'Specific Volume':[],\n        'Sample Contrast':[],'Sample Concentration':[]}   \n        for code in self.clean_SASBDB_code():\n            parameter_table['SASDB ID'].append(code)\n            all_lines=self.get_all_sascif(code)\n            for indx,sascifline in enumerate(all_lines):\n                if len(sascifline)<3 and len(sascifline)>0 and '_sas_sample.specimen_concentration' in sascifline[0]:\n                    if len(sascifline[1])>1:\n                        parameter_table['Sample Concentration'].append(str(round(float(sascifline[1]),2))+' mg/ml')\n                    else:\n                        parameter_table['Sample Concentration'].append('N/A')\n                if len(sascifline)<3 and len(sascifline)>0 and '_sas_sample.contrast' in sascifline[0] :\n                    if len(sascifline[1])>1:\n                        parameter_table['Sample Contrast'].append(str(round(float(sascifline[1]),2)))\n                    else:\n                        parameter_table['Sample Contrast'].append('N/A')\n                if len(sascifline)<3 and len(sascifline)>0 and '_sas_sample.specific_vol' in sascifline[0]:\n                    if len(sascifline[1])>1:\n                        parameter_table['Specific Volume'].append(str(round(float(sascifline[1]),2))+' nm\\u00b3')\n                    else:\n                        parameter_table['Specific Volume'].append('N/A')\n                if len(sascifline)<3 and len(sascifline)>0 and '_sas_result.Porod_volume' in sascifline[0] and '_sas_result.Porod_volume_error' not in sascifline[0]:\n                    if len(sascifline[1])>1:\n                        parameter_table['Porod Volume'].append(str(round(float(sascifline[1]),2))+' nm\\u00b3')\n                    else:\n                        parameter_table['Porod Volume'].append('N/A')\n                if len(sascifline)<3 and len(sascifline)>0 and '_sas_result.estimated_volume' in sascifline[0] and '_sas_result.estimated_volume_error' not in sascifline[0]:\n                    if len(sascifline[1])>1:\n                        parameter_table['Estimated Volume'].append(str(round(float(sascifline[1]),2))+' nm\\u00b3')\n                    else:\n                        parameter_table['Estimated Volume'].append('N/A')\n        return parameter_table\n\n\n    def get_parameters_mw_many(self)->dict:\n        '''\n        get MW details from SASCIF files\n        '''\n        self.get_sascif_file()\n        parameter_table={'SASDB ID':[],'Chemical composition MW':[],'Standard MW':[],'Porod Volume/MW':[]}   \n        for code in self.clean_SASBDB_code():\n            parameter_table['SASDB ID'].append(code)\n            all_lines=self.get_all_sascif(code)\n            for indx,sascifline in enumerate(all_lines):\n                if len(sascifline)<3 and len(sascifline)>0 and '_sas_result.experimental_MW' in sascifline[0] and '_sas_result.experimental_MW_error' not in sascifline[0]:\n                    if len(sascifline[1])>1:\n                        parameter_table['Chemical composition MW'].append(str(round(float(sascifline[1]),2))+' kDa')\n                    else:\n                        parameter_table['Chemical composition MW'].append('N/A')\n                if len(sascifline)<3 and len(sascifline)>0 and '_sas_result.MW_standard' in sascifline[0] and '_sas_result.MW_standard_error' not in sascifline[0]:\n                    if len(sascifline[1])>1:\n                        parameter_table['Standard MW'].append(str(round(float(sascifline[1]),2))+' kDa')\n                    else:\n                        parameter_table['Standard MW'].append('N/A')\n                if len(sascifline)<3 and len(sascifline)>0 and '_sas_result.MW_Porod' in sascifline[0] and '_sas_result.MW_Porod_error' not in sascifline[0]:\n                    if len(sascifline[1])>1:\n                        Porod_MW=round(float(sascifline[1]),2)\n                    else:\n                        Porod_MW=0\n                if len(sascifline)<3 and len(sascifline)>0 and '_sas_result.Porod_volume' in sascifline[0] and '_sas_result.Porod_volume_error' not in sascifline[0]:\n                    if len(sascifline[1])>1 and Porod_MW>0:\n                        Porod_V=round(float(sascifline[1]),2)/Porod_MW\n                        parameter_table['Porod Volume/MW'].append(str(round(Porod_V,2))+' nm \\u00b3/kDa')\n                    else:\n                        parameter_table['Porod Volume/MW'].append('N/A')\n\n        return parameter_table\n\n    def get_parameters_mw_many_dep(self)->dict:\n        '''\n        depreciated function on getting MW from JSON\n        '''\n        data_dic=self.get_data_from_SASBDB()\n        #MW based on chemical composition\n        parameter_table={'SASDB ID':[],'Sequence MW':[],'Experimental MW':[],'Porod MW':[]}        \n        for key,val in data_dic.items():\n            try:\n                parameter_table['Experimental MW'].append(list(data_dic.values())[0]['experimental_mw']+' kDa')\n            except:\n                parameter_tabel['Experimental MW'].append('N/A')\n            try:\n                parameter_table['Porod MW'].append(list(data_dic.values())[0]['porod_mw']+' kDa')\n            except:\n                parameter_table['Porod MW'].append('N/A')\n            try:\n                parameter_table['Sequence MW'].append(list(data_dic.values())[0]['experiment']['sample']['molecule'][0]['total_mw']+' kDa')\n            except:\n                parameter_table['Sequence MW'].append('N/A')\n            parameter_table['SASDB ID'].append(key)\n        return parameter_table\n    \n    def get_pddf(self)->dict:\n        '''\n        get p(r) data from JSON\n        '''\n        data_dic=self.get_data_from_SASBDB()\n        pofr_dic=self.get_pofr()\n        pddf_dic={}\n        for key,val in pofr_dic.items():\n            pd_df=val.astype({'P':float,'R':float,'E':float})\n            pd_df['R']=pd_df['R']/10;\n            pd_df['err_x']=pd_df.apply(lambda row: (row['R'],row['R']), axis=1)\n            pd_df['err_y']=pd_df.apply(lambda row: (row['P']-row['E'],row['P']+row['E']),axis=1)\n            pddf_dic[key]=pd_df\n        return pddf_dic\n\n    def get_pddf_info(self)->dict:\n        '''\n        get p(r) related info from JSON\n        '''\n        data_dic=self.get_data_from_SASBDB()\n        pddf_info={'SASDB ID':[],'Software used':[],'Dmax':[],'Dmax error':[],'Rg':[],'Rg error':[]}\n        for key,val in data_dic.items():\n            pddf_info['Software used'].append(str(val['pddf_software']))\n            try:\n                pddf_info['Dmax'].append(str(val['pddf_dmax'])+' nm')\n            except: \n                pddf_info['Dmax'].append('N/A')\n            try:\n                pddf_info['Rg'].append(str(val['pddf_rg'])+' nm')\n            except:\n                pddf_info['Rg'].append('N/A')\n            try:\n                if val['pddf_dmax_error'] is None:\n                    pddf_info['Dmax error'].append('N/A')\n                else:\n                    pddf_info['Dmax error'].append(str(val['pddf_dmax_error'])+' nm')\n            except:\n                pddf_info['Dmax error'].append('N/A')\n            try:\n                pddf_info['Rg error'].append(str(val['pddf_rg_error'])+' nm')\n            except:\n                pddf_info['Rg error'].append('N/A')\n            pddf_info['SASDB ID'].append(key)\n        return pddf_info\n\n    def get_number_of_fits(self)->dict:\n        '''\n        get number of fits from JSON, deprecated\n        '''\n        data_dic=self.get_data_from_SASBDB()\n        num_of_fits={}\n        for key,val in data_dic.items():\n            num_of_fits[key]=len(val['fits'])\n        return num_of_fits\n\n    def get_chi_table(self)->dict:\n        '''\n        get chi value from JSON, deprecated\n        '''\n        data_dic=self.get_data_from_SASBDB()\n        chi_table={'SASDB ID':[],'Model':[],'\\u03C7\\u00b2':[]}        \n        for key,val in data_dic.items():\n            numoffits=self.get_number_of_fits()[key]\n            if numoffits>0:\n                for fitnum in range(0,numoffits):\n                    count=fitnum+1\n                    chi_table['SASDB ID'].append(key)            \n                    chi_table['Model'].append(str(count))\n                    chi_value=val['fits'][fitnum]['chi_square_value']\n                    chi_value_round=round(chi_value,2)\n                    chi_table['\\u03C7'+'\\u00b2'].append(chi_value_round)\n            else:\n                chi_table['SASDB ID'].append(key)\n                chi_table['Model'].append('N/A')\n                chi_table['\\u03C7'+'\\u00b2'].append('N/A')\n        return chi_table\n\n    def get_sasdb_code_fits(self)->list:\n        '''\n        get number of fits per SASBDB ID\n        '''\n        fit_dict=self.get_number_of_fits()\n        return list(fit_dict.values())\n\n    def get_fit_data(self)->dict:\n        '''\n        get fit information to make plots, from JSON\n        '''\n        data_dic=self.get_data_from_SASBDB()\n        num_of_fits=self.get_number_of_fits()\n        data_fit={}\n        for key,val in data_dic.items():\n            num=num_of_fits[key]\n            fits={}\n            if num>0:\n                for fitnum in range(0,num):\n                    target_url=val['fits'][fitnum]['fit_data']      \n                    fit = requests.get(target_url);\n                    if fit.status_code !=200:\n                        print (\"Error....unable to fetch data from SASBDB, please check the entry ID\")\n                    \n                    fname=key+str(fitnum)+'fit.csv'\n                    with open (fname,'w') as f:\n                        f.write(fit.text)\n                    \n                    f_df=pd.read_csv(fname, skiprows=3,delim_whitespace=True, names=['Q','Ie','Ib','E'])\n                    if abs(f_df.iloc[22,2]-f_df.iloc[22,1])>abs(f_df.iloc[22,3]-f_df.iloc[22,1]):\n                        f_df.rename(columns={'Q':'Q','Ie':'Ie','Ib':'E','E':'Ib'},inplace=True)\n                    f_df['logIe']=np.log(f_df['Ie'])\n                    f_df['logIb']=np.log(f_df['Ib'])\n                    f_df['r']=f_df['Ie']-f_df['Ib']\n                    \n                    if f_df['E'].isnull().values.any():\n                        f_df['rsigma']=0\n                    else:\n                        f_df['rsigma']=f_df['r']/f_df['E']\n                    #f_df['rsigma']=f_df['r']/f_df['E']\n                    f_df['logr']=f_df['logIe']-f_df['logIb']\n                    f_df['r2a']=(f_df['Ib']-f_df['Ie'].mean())**2\n                    f_df['r2b']=(f_df['Ie']-f_df['Ie'].mean())**2\n                    fits[fitnum]=(self.get_fit_r2(f_df),f_df)\n            else:\n                fits[0]=(0,pd.DataFrame())\n                #data_fit=None\n            data_fit[key]=fits \n        return data_fit\n\n    def get_fit_r2(self,df:pd.DataFrame)->int:\n        rsquared=df['r2a'].sum()/df['r2b'].sum()\n        return round(rsquared,2)\n    \n    def get_total_fits(self)->int:\n        '''\n        get number of fits\n        '''\n        data_dic=self.get_data_from_SASBDB()\n        num_of_fits=0\n        for key,val in data_dic.items():\n            num_of_fits += len(val['fits'])\n        return num_of_fits\n\n    def get_fit_image(self):\n        '''\n        get fit image from fit, deprecated\n        '''\n        data_dic=self.get_data_from_SASBDB()\n        num_of_fits=self.get_number_of_fits()\n        data_fit={}\n        for key,val in data_dic.items():\n            num=num_of_fits[key]\n            if num>0:\n                for fitnum in range(0,num):    \n                    target_url=val['fits'][fitnum]['models'][0]['model_plot']\n                    fitdata = requests.get(target_url);\n                    if fitdata.status_code !=200:\n                        print (\"Error....unable to fetch data from SASBDB, please check the entry ID\")\n                    dirname=os.path.dirname(os.path.abspath(__file__))\n                    filename = os.path.abspath(os.path.join(os.getcwd(),self.imagepath,self.ID+key+str(fitnum)+'fit.png'))\n                    with open (filename,'wb') as f:\n                        f.write(fitdata.content)\n\n", "meta": {"hexsha": "479caf2c5d286ebaca5605766b6cf358e7740e82", "size": 31453, "ext": "py", "lang": "Python", "max_stars_repo_path": "master/pyext/src/validation/sas.py", "max_stars_repo_name": "salilab/IHMValidation", "max_stars_repo_head_hexsha": "ddf1a080a4b7f66c2f067312f5f4a5c6584848d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "master/pyext/src/validation/sas.py", "max_issues_repo_name": "salilab/IHMValidation", "max_issues_repo_head_hexsha": "ddf1a080a4b7f66c2f067312f5f4a5c6584848d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2020-12-09T22:27:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T18:01:43.000Z", "max_forks_repo_path": "master/pyext/src/validation/sas.py", "max_forks_repo_name": "salilab/IHMValidation", "max_forks_repo_head_hexsha": "ddf1a080a4b7f66c2f067312f5f4a5c6584848d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-21T22:55:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T22:55:24.000Z", "avg_line_length": 45.3867243867, "max_line_length": 173, "alphanum_fraction": 0.5382952342, "include": true, "reason": "import numpy", "num_tokens": 7862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.1978685376788423}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nPackage: mesxr.calibration\nModule: trimscan\nAuthor: Patrick VanMeter\nAffiliation: Department of Physics, University of Wisconsin-Madison\nLast Updated: November 2018\n\nDescription:\n    This module is a significant overhaul to the overiginal ME-SXR calibration software. The\n    goals of the re-write are to improve usability and transperency, and to more naturally\n    facilitate features which were added on to the original code. \nAcknowledgements:\n    - Novimir Pablant and Jacob Maddox, for the original calibration code.\n    - Luis Felipe Delgado-Aparicio, for heading the PPPL/MST collaboration.\n    - Daniel Den Hartog and Lisa Reusch, for advising me.\n\"\"\"\nimport copy\nimport os\nimport multiprocessing as mp\nimport numpy as np\nimport scipy as sp\nfrom scipy.optimize import curve_fit\nfrom scipy.special import erf\nimport mesxr.calibration.utilities as utilities\n\n\ndef calibrate_mp(pixel):\n    \"\"\"\n    This is a helper function in order to use multiprocessing to invoke the calibrate() method for an array\n    of Pilatus_Pixel objects.\n    \"\"\"\n    pixel.calibrate()\n    return copy.copy(pixel)\n\ndef calibrate_module_mp(chip):\n    \"\"\"\n    This helper function is used to calibrate an entire module using multiprocessing. This ensures that each individual chip does\n    not itself attempt to spawn additional processes.\n    \"\"\"\n    chip.calibrate(num_cores=1)\n    return copy.copy(chip)\n\nclass Pilatus_Pixel(object):\n    \"\"\"\n    Description:\n        TBD\n    Arguments:\n        - calibration_data = (list of np.array) Contains the calibration data for this pixel. The list should have\n                a number of entries equal to the length of self.energies, and each entry should be an array with a\n                length equal to the length of the corresponding entry in self.trimbits.\n        - calibration_energies = (np.array) The photon energy for each calibration source element.\n        - elements = (list) Each entry should be a string which identifies the element corresponding to the\n                same index in calibration_energies.\n        - trimbits = (list of np.array) Identifies the trimbit values which correspond to the arrays in calibration_data.\n                This allows the user to remove certain trimbit settings from the calibration, if necessary.\n        - coords = (tuple of ints) The global (x,y) coordinates of this pixel.\n        - size = (tuple of float) The physical dimensions (x,y) of the pixel, in micrometers.\n    \"\"\"\n    def __init__(self, calibration_data, calibration_energies, elements, trimbits, coords, chip_number, module_number, size=(172.0, 172.0)):\n        # Physical parameters\n        self.data = calibration_data\n        self.energies = calibration_energies\n        self.elements = elements\n        self.trimbits = trimbits\n        self.coords = coords\n        self.chip = chip_number\n        self.module = module_number\n        self.size = size\n        self.edge_pixel = False\n\n        # Calibration parameters to be fit to the data\n        self.num_elements = len(self.elements)\n        self.trimfit_params = np.zeros([self.num_elements, 6])\n        self.trimfit_cov    = np.zeros([self.num_elements, 6, 6])\n\n        self.enfit_params = np.zeros(3)\n        self.enfit_cov    = np.zeros([3, 3])\n\n        self.trimfit_chi2 = np.zeros(self.num_elements)\n        self.enfit_chi2 = 0.0\n\n        # Keep track of failed fits\n        self.good_trimfits = np.array([False for x in range(self.num_elements)])\n        self.good_enfit = False\n\n    def __str__(self):\n        return str(self.coords)\n\n    def s_curve(self, trim, A0, A1, A2, A3, A4, A5):\n        \"\"\"\n        This function parameterizes the detector response to a given trimbit setting. This returns the predicted\n        photon counts given the calibration parameters and supplied trimbit value. This function permits non-integer\n        trimbit values, which in reality must be rounded to the nearest integer.\n        \"\"\"\n        return 0.5*(erf( -1*(trim - A0)/(np.sqrt(2)*A1) ) + 1.)*(A2 + A3*(trim - A0)) + A4 + A5*(trim - A0)\n\n    def s_curve_model(self, element, trim):\n        \"\"\"\n        Use the fit results to return values from the analytic model for the S-curve fit.\n        \"\"\"\n        elem_index = self.elements.index(element)\n        return self.s_curve(trim, *self.trimfit_params[elem_index, :])\n\n    def en_curve(self, energy, C0, C1, C2):\n        \"\"\"\n        This function parameterizes the mapping between the trimbit of the S-curve inflection point and the calibration\n        line energies.\n        \"\"\"\n        return C0*energy**2 + C1*energy + C2\n\n    def en_curve_model(self, energy):\n        \"\"\"\n        Use the fit results to return values from the analytic model for the energy fit.\n        \"\"\"\n        return self.en_curve(energy, *self.enfit_params)\n\n    def en_curve_uncertainty(self, energy):\n        \"\"\"\n        Returns the uncertainty in the trimbit required to set the threshold to a given energy, based on the\n        energy fit results.\n        \"\"\"\n        var_2 = (energy**4)*self.enfit_cov[0,0] + (energy**2)*self.enfit_cov[1,1] + self.enfit_cov[2,2]\n        cov_2 = 2*energy*( (energy**2)*self.enfit_cov[0,1] + energy*self.enfit_cov[0,2] + self.enfit_cov[1,2] )\n        return np.sqrt(var_2 + cov_2)\n\n    def trimbit_from_threshold(self, energy):\n        \"\"\"\n        This is just a wrapper for the en_curve_model function which provides a more consistent notation for some\n        use cases.\n        \"\"\"\n        return self.en_curve_model(energy)\n\n    def trimbit_uncertainty(self, energy):\n        \"\"\"\n        This is just a wrapper for the en_curve_model function which provides a more consistent notation for some\n        use cases.\n        \"\"\"\n        return self.en_curve_uncertainty(energy)\n    \n    def threshold_from_trimbit(self, trimbit):\n        \"\"\"\n        Invert the threshold fit. That is, get the lower threshold energy corresponding to a specific trimbit value. This\n        is useful when considering the impact of trimbit rounding.\n        \"\"\"\n        c0, c1, c2 = self.enfit_params\n        return (-c1 + np.sqrt(c1**2 - 4*c0*(c2 - trimbit))) / (2*c0)\n\n    def threshold_uncertainty(self, trimbit):\n        \"\"\"\n        \"\"\"\n        return 0\n\n    def exclude_trimbits(self, remove_bits):\n        \"\"\"\n        Remove the given trimbits and corresponding data so that they will not be used in the calibration.\n        \"\"\"\n        for elem_index in range(self.num_elements):\n            if set(remove_bits).issubset(set(self.trimbits[elem_index])):\n                exclude_indices = [np.where(tbit == self.trimbits[elem_index])[0][0] for tbit  in remove_bits]\n                slice_indices = [i for i in range(len(self.trimbits[elem_index])) if i not in exclude_indices]\n                self.trimbits[elem_index] = self.trimbits[elem_index][slice_indices]\n                self.data[elem_index] = self.data[elem_index][slice_indices]\n\n    def exclude_elements(self, remove_elem):\n        \"\"\"\n         Remove the given elements and corresponding data so that they will not be used in the calibration.\n        \"\"\"\n        # Determine the indices of the entries to keep\n        try:\n            remove_indices = [self.elements.index(elem) for elem in remove_elem]\n        except:\n            print('ERROR: Supplied element(s) not in the elements array.')\n            remove_indices = []\n\n        slice_indices = [i for i in range(len(self.elements)) if i not in remove_indices]\n\n        # Remove the unwanted elements\n        self.elements = [self.elements[i] for i in slice_indices]\n        self.data = [self.data[i] for i in slice_indices]\n        self.trimbits = [self.trimbits[i] for i in slice_indices]\n        self.energies = self.energies[slice_indices]\n        self.num_elements = len(self.elements)\n\n        # Remake the calibration result arrays which depend on the number of elements\n        self.trimfit_params = np.zeros([self.num_elements, 6])\n        self.trimfit_cov    = np.zeros([self.num_elements, 6, 6])\n        self.trimfit_chi2   = np.zeros(self.num_elements)\n        self.good_trimfits  = np.array([False for x in range(self.num_elements)])\n    \n    # Calibration functions\n    def trimbit_fit(self):\n        \"\"\"\n        Use the calibration data to determine the best-fit parameters and covariance matrix for this pixel.\n        \"\"\"\n        for elem_index in range(self.num_elements):\n            # Use a gradient method to guess the trimbit of the inflection point\n            data_slope = np.gradient(self.data[elem_index], 1)\n            index = np.argmin(data_slope) + self.trimbits[elem_index][0]\n\n            # Initial guesses\n            p0 = [float(index),                     # A0 - Inflection trimbit\n                1.0,                              # A1 - S-curve width\n                np.amax(self.data[elem_index]),   # A2 - Response amplitude\n                0.0,                              # A3 - CX slope\n                np.amin(self.data[elem_index]),   # A4 - BG amplitude\n                0.0]                              # A5 - BG CX slope\n\n            # Do the fit\n            bounds = (np.array([-np.inf, -np.inf, -np.inf, -np.inf, -np.inf, -np.inf]),   # Lower bounds\n                      np.array([np.inf, np.inf, np.inf, 0.0, np.inf, 0.0]))               # Upper bounds\n\n            sigma = np.sqrt(self.data[elem_index])\n\n            try:\n                self.trimfit_params[elem_index, :], self.trimfit_cov[elem_index, :, :] = curve_fit(self.s_curve, self.trimbits[elem_index], self.data[elem_index],\n                                                                                                p0=p0, bounds=bounds, sigma=sigma, absolute_sigma=True)\n\n                # Determine the reduced Chi^2 of the fit\n                model_data = self.s_curve(self.trimbits[elem_index], *self.trimfit_params[elem_index, :])\n                self.trimfit_dof = len(self.data[elem_index]) - 6.0\n                self.trimfit_chi2[elem_index] = np.sum( (self.data[elem_index] - model_data)**2/(sigma**2) )\n\n                self.good_trimfits[elem_index] = True\n            except:\n                # The fit did not work - consider including fallback options here\n                self.good_trimfits[elem_index] = False\n                self.trimfit_params[elem_index, :] = np.nan\n                self.trimfit_cov[elem_index, :, :] = np.nan\n                self.trimfit_chi2[elem_index] = np.nan\n                self.trimfit_dof = np.nan\n\n    def energy_fit(self):\n        \"\"\"\n        Use the results of the trimbit_fit to fit the en_curve.\n        \"\"\"\n        # Only use the successful fits\n        if np.sum(self.good_trimfits) >= 4:\n            trim_data = self.trimfit_params[self.good_trimfits, 0]\n            trim_sigma = np.sqrt(self.trimfit_cov[self.good_trimfits, 0, 0])\n            trim_energies = self.energies[self.good_trimfits]\n\n            #self.enfit_params, self.enfit_cov = np.polyfit(self.energies, trim_data, 2, w=1/trim_sigma, cov=True)\n            p0 = [np.mean(trim_data), 0.0, 0.0]\n\n            try:\n                self.enfit_params[:], self.enfit_cov[:,:] = curve_fit(self.en_curve, trim_energies, trim_data, p0=p0,\n                                                                      sigma=trim_sigma, absolute_sigma=True)\n\n                # Determine the Chi^2 of the fit\n                trim_model = self.en_curve(trim_energies, *self.enfit_params)\n                self.enfit_dof = len(trim_data) - 3.0\n                self.enfit_chi2 = np.sum( (trim_data - trim_model)**2/(trim_sigma**2) )\n                self.good_enfit = True\n            except:\n                # The fit did not work - consider including fallback options here\n                self.good_enfit = False\n                self.enfit_params[:] = np.nan\n                self.enfit_cov[:] = np.nan\n                self.enfit_chi2 = np.nan\n                self.enfit_dof = np.nan\n        else:\n            # There is too little good data for a reliable fit\n            self.good_enfit = False\n            self.enfit_params[:] = np.nan\n            self.enfit_cov[:,:] = np.nan\n            self.enfit_chi2 = np.nan\n            self.enfit_dof = np.nan\n\n    def calibrate(self):\n        \"\"\"\n        Performs both the trimbit fit and the energy fit in a single command.\n        \"\"\"\n        self.trimbit_fit()\n        self.energy_fit()\n\n\nclass Pilatus_Null_Pixel(Pilatus_Pixel):\n    \"\"\"\n    This class exists to allow the creation of placeholder Pixel objects which do nothing and hold no data, but share the\n    same methods. This is useful as a placeholder and for representing the empty row between pixels.\n    \"\"\"\n    def __init__(self):\n        self.coords = (-1,-1)\n        self.chip = -1\n        self.module = -1\n        self.edge_pixel = False\n\n        # Calibration parameters to be fit to the data\n        self.elements       = ['none']\n        self.num_elements   = len(self.elements)\n        self.trimfit_params = np.array([[np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]])\n        self.trimfit_cov    = np.zeros([1,6,6])\n        self.trimfit_cov[:,:,:] = np.nan\n\n        self.enfit_params   = np.array([np.nan, np.nan, np.nan])\n        self.enfit_cov      = np.nan\n\n        self.trimfit_chi2   = np.array([np.nan])\n        self.enfit_chi2     = np.nan\n        \n        self.good_trimfits = np.array([False])\n        self.good_enfit = False\n\n    def s_curve_model(self, element, trim):\n        return -1.0\n\n    def en_curve_model(self, energy):\n        return -1.0\n    \n    def trimbit_fit(self):\n        pass\n\n    def energy_fit(self):\n        pass\n\n\nclass Pilatus_Chip(object):\n    \"\"\"\n    Description:\n        The chip is the basic organizational unit for pixels in the PILATUS series of X-ray detectors. Chips essentially\n        consist of an array of pixels and some additional properties.\n    Inputs:\n        - pixel_dims = (tuple of int) The size n x m of the array of pixels on the chip.\n        - chip_number = (int) ID number for the chip.\n        - calibration_data = (list of np.array) Each array in the list corresponds to the calibration data for the\n                corresponding entry in elements. The arrays are 3D with indices corresponding to [x, y, trimbit].\n        - calibration_energies = (np.array) The photon energy for each calibration source element.\n        - elements = (list) Each entry should be a string which identifies the element corresponding to the\n                same index in calibration_energies.\n        - trimbits = (list of np.array) The trimbits to include for the calibration of this chip. This is expected to vary\n                on a chip-by-chip basis. This should be the same length as the third axis of each element in the\n                calibration_data list.\n        - pixel_coords = (np.array) This array assigns the global coordinates for each pixel on the chip. The array\n                is indexed by [x, y, coord] where coord=0 gives the global X coordinate and coord=1 gives the global Y.\n                The indices x,y refer to the local (chip-level) coordinates.\n        - vcmp = (float) The Vcmp value for this chip. This is the global value with the offset applied.\n    \"\"\"\n    def __init__(self, pixel_dims, chip_number, module_number, calibration_data, calibration_energies, elements, trimbits, pixel_coords, vcmp):\n        self.pixel_dims = pixel_dims\n        self.number = chip_number\n        self.module = module_number\n        self.trimbits = trimbits\n\n        # Create the array of pixels\n        self.pixels = np.empty(self.pixel_dims, dtype=object)\n\n        for y in range(self.pixel_dims[1]):\n            for x in range(self.pixel_dims[0]):\n                self.pixels[x, y] = Pilatus_Pixel([data[x, y, :] for data in calibration_data], calibration_energies,\n                                                  elements, copy.copy(self.trimbits), tuple(pixel_coords[x,y,:]), self.number, self.module)\n                \n                if x == 0 or y == 0 or x == self.pixel_dims[0]-1 or y == self.pixel_dims[1]-1:\n                    self.pixels[x, y].edge_pixel = True\n\n        # Store chip-level detector properties\n        self.vcmp = vcmp\n\n    def __str__(self):\n        return str(self.number)\n\n    def exclude_trimbits(self, remove_bits):\n        \"\"\"\n        Remove the specified trimbits and associated data for all pixels on the chip.\n        \"\"\"\n        for pixel in self.pixels.ravel():\n            pixel.exclude_trimbits(remove_bits)\n\n    def remove_elements(self, remove_elem):\n        \"\"\"\n        Remove the specified elements and associated data for all pixels on the chip.\n        \"\"\"\n        for pixel in self.pixels.ravel():\n            pixel.exclude_elements(remove_elem)\n    \n    def calibrate(self, num_cores=16):\n        \"\"\"\n        Calibrate all pixels on a chip. Returns the reduced chi^2 metric for the energy fits. This is mostly of interest when\n        investigating individual modules. Otherwise, see the detector-level calibrate() function.\n        \"\"\"\n        if num_cores == 1:\n            [pixel.calibrate() for pixel in self.pixels.ravel()]\n        else:\n            pool = mp.Pool(num_cores)\n            pixels = pool.map(calibrate_mp, self.pixels.ravel())\n            self.pixels = np.array(pixels).reshape(self.pixel_dims)\n\n\nclass Pilatus_Module(object):\n    \"\"\"\n    Description:\n        TBD\n    Inputs:\n        - chip_dims = (tuple of int) The global (X, Y) layout of chips on the module.\n        - pixel_dims = (tuple of int) The local layout (x,y) of pixels on a chip.\n        - module_number = (int) Identifier for the module. This is important for multi-module detectors.\n        - calibration_data = (list of np.array) Each array in the list corresponds to the calibration data for the\n                corresponding entry in elements. The arrays are 3D with indices corresponding to [X, Y, trimbit], where\n                (X,Y) are the pixel coordinates in the module frame. It is assumed that no trimbit data has been dropped\n        - calibration_energies = (np.array) The photon energy for each calibration source element.\n        - elements = (list) Each entry should be a string which identifies the element corresponding to the\n                same index in calibration_energies.\n        - trimbit_start = (np.array) The trimbit to start the scan for each element for each module. This array is indexed\n                by [elem, chip_num]. Any value above zero will cause some data to be omitted from the calibration procedure.\n        - chip_coords = (np.array) Entries in this array define the starting pixel (upper-left) for each chip. This is indexed\n                by [chip_num, dim] where dim=0 is x and dim=1 is y. For example, on the Pilatus3 chip 0 start with pixel (0,0)\n                and chip 1 starts with (61, 0) so chip_coords[0,:] = [0,0] and chip_coords[1,:] = [61,0].\n        - num_trimbits = [keyword](int) Specify the number of trimbits available to each pixel.\n    \"\"\"\n    def __init__(self, chip_dims, pixel_dims, module_number, calibration_data, calibration_energies, elements,\n                 trimbit_start, chip_coords, num_trimbits=64):\n        self.number = module_number\n        self.chip_dims = chip_dims\n        self.pixel_dims = pixel_dims\n        self.num_trimbits = num_trimbits\n\n        # Initialize the chips on the module\n        self.chips = np.empty(self.chip_dims, dtype=object)\n        chip_num = 0\n\n        for y in range(self.chip_dims[1]):\n            for x in range(self.chip_dims[0]):\n                vcmp = 0\n\n                # Determine the pixel coordinates based on the supplied dimensions and the start coordinates\n                pixel_coords = np.zeros([self.pixel_dims[0], self.pixel_dims[1], 2], dtype=int)\n                for pix_x in range(self.pixel_dims[0]):\n                    for pix_y in range(self.pixel_dims[1]):\n                        pixel_coords[pix_x, pix_y, :] = chip_coords[chip_num, :] + [pix_x, pix_y]\n                \n                # Trim the calibration data to the appropriate size\n                trimbits = [np.arange(trimbit_start[elem, chip_num], self.num_trimbits) for elem in range(len(elements))]\n\n                start_x = chip_coords[chip_num, 0]\n                end_x   = chip_coords[chip_num, 0]+self.pixel_dims[0]\n                start_y = chip_coords[chip_num, 1]\n                end_y   = chip_coords[chip_num, 1]+self.pixel_dims[1]\n                pixel_data = [calibration_data[elem][start_x:end_x, start_y:end_y, trimbits[elem][0]:] for elem in range(len(elements))]\n\n                self.chips[x, y] = Pilatus_Chip(self.pixel_dims, chip_num, self.number, pixel_data, calibration_energies, elements,\n                                                trimbits, pixel_coords, vcmp)\n                chip_num += 1\n\n    def __str__(self):\n        return str(self.number)\n\n    def get_pixels(self):\n        \"\"\"\n        Return an array with all pixels organized by module coordinates.\n        \"\"\"\n        x_dim = 487\n        y_dim = 195\n        pixels_mod = np.array([[Pilatus_Null_Pixel() for y in range(y_dim)] for x in range(x_dim)])\n\n        for chip in self.chips.ravel():\n            for pixel in chip.pixels.ravel():\n                pixels_mod[pixel.coords] = pixel\n\n        return pixels_mod\n\n    def calibrate(self, num_cores=16):\n        \"\"\"\n        Use multiprocessing to calibrate all pixels. If possible it is advisable to set num_cores equal to the\n        number of chips on the module.\n        \"\"\"\n        if num_cores == 1:\n            chips = [chip.calibrate() for chip in self.chips.ravel()]\n        else:\n            pool = mp.Pool(num_cores)\n            chips = pool.map(calibrate_module_mp, self.chips.ravel())\n\n        self.chips = np.array(chips).reshape(self.chip_dims)\n\n\nclass Pilatus_Detector(object):\n    \"\"\"\n    Description:\n        A detector is an object which holds an array of Modules and the associated global settings. Objects\n        of this class also provide methods for initiating the calibration process.\n    Usage:\n        This class is intended to be inhereted by classes representing the implementation of specific Pilatus\n        detectors. As such, direct instances of this class will be of limited use. For an example implementation,\n        see the Pilatus3_100k class below.\n    Parameters:\n        - TBD\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        # Detector properties\n        self.global_pixel_dims = (0, 0)     # Dimensions of all pixels on the detector face, including fake pixels\n        self.num_chips    = 0               # The number of chips which compose the module\n        self.module_dims  = (0, 0)          # The layout of modules on the detector\n        self.chip_dims    = (0, 0)          # The layout of chips on the module\n        self.pixel_dims   = (0, 0)          # The layout of pixels on a chip\n        self.num_trimbits = 0               # The number of trimbits available to each pixel\n        self.trimbit_start = [[0]]          # Value to start trimbit data at, indexed by [elem, chip_num]\n        self.calibrated = False             # Flag to tell whether the detector has been calibrated already\n        self.bad_pixels = []                # Keep track of which pixels are problematic\n\n        # Initialize the modules and global settings\n        self.load_trimscan_data([], [])\n        self.load_global_settings(0)\n        self.init_modules()\n\n        # Make pixels easily accessible by global coordinates\n        self.pixels = self.get_pixels()\n\n    def init_modules(self):\n        \"\"\"\n        Run this to initialize the modules which compose the detector. This is separated out from the __init__ method\n        since it does generally not need to be overwritten for inhereted classes.\n        \"\"\"\n        self.modules = np.empty(self.module_dims, dtype=object)\n        module_number = 0\n\n        for y in range(self.module_dims[1]):\n            for x in range(self.module_dims[0]):\n                self.modules[x,y] = Pilatus_Module(self.chip_dims, self.pixel_dims, module_number, self.trimscan_data, self.trimscan_energy,\n                                                   self.elements, self.trimbit_start, self.get_chip_coords(module_number),\n                                                   num_trimbits=self.num_trimbits)\n                module_number += 1\n\n    def load_global_settings(self, settings_path):\n        \"\"\"\n        Load the detector settings in from the data file. This may require slight modification for multi-module\n        detectors since I do not know which settings are shared across modules. I have separated out the VCMP settings\n        due to its unique chip-level variation.\n        \"\"\"\n        self.vcmp = np.zeros(self.num_chips)\n        self.settings = {}\n\n        # Load the settings data from the file\n        if settings_path != 0:\n            try:\n                fname = os.path.join(settings_path, 'setdacs_b01_m01.dat')\n                settings_file = open(fname, 'r')\n\n                for line in settings_file.readlines():\n                    line_elems = line.split()\n                    if line_elems[0] == 'set':\n                        key = line_elems[1].split('_')[2]\n                        self.settings[key] = float(line_elems[2])\n\n                settings_file.close()\n\n                # Pull out the VCMP settings\n                for key in self.settings.keys():\n                    if 'VCMP' in key:\n                        index = int(key.split('VCMP')[1])\n                        self.vcmp[index] = self.settings[key]\n            \n            except:\n                print('ERROR: Failed to load supplied settings file. Check path name.')\n        else:\n            pass\n\n    def load_trimscan_data(self, elements, trimscan_paths):\n        \"\"\"\n        \"\"\"\n        self.elements = elements\n\n        self.trimscan_data = [np.zeros([self.global_pixel_dims[0], self.global_pixel_dims[1], self.num_trimbits]) for i in self.elements]\n        self.trimscan_energy = utilities.get_line_energy(self.elements)\n        self.trimbits = [np.arange(self.num_trimbits) for elem in self.elements]\n        \n        for elem, fname in enumerate(trimscan_paths):\n            self.trimscan_data[elem] = utilities.load_calibration_data(fname)\n\n    def generate_settings_file(self, output_path):\n        \"\"\"\n        Used to generate the settings file for use in ME-SXR operation. This removes the requirement of keeping\n        up with the original file used in the calibration procedure.\n        \"\"\"\n        pass\n\n    def pixel_mapping(self, x, y):\n        \"\"\"\n        Returns the mapping between between global (x,y) coordinates and local (mod_num, chip_num, (pix_x, pix_y))\n        coordinates. This is important for mapping the trimbit scan data to the Detector data structure.\n        \"\"\"\n        return (0, 0, (x, y))\n\n    def get_chip_coords(self, mod_number):\n        \"\"\"\n        Override to set the global coordinates for the first (upper-left) pixel on each chip.\n        \"\"\"\n        return np.array([[0,0]])\n\n    def get_pixels(self):\n        \"\"\"\n        Return an array of all pixel objects following the global coordinates.\n        \"\"\"\n        pass\n\n    def calibrate(self, num_cores=16):\n        \"\"\"\n        Use multiprocessing to calibrate all pixels. \n        \"\"\"\n        pass\n\n    def determine_bad_pixels(self, include=[]):\n        \"\"\"\n        Update the list of bad pixels. This should generally be called immediately after calibration. Use\n        the 'include' keyword to manually add points, even if the fit did not fail. This keyword accepts a\n        list of tuples.\n        \"\"\"\n        # Ensure that the specified fits are marked as bad\n        for coords in include:\n            if coords not in self.bad_pixels:\n                self.pixels[coords].good_enfit = False\n\n        # Now add all remaining pixels for which a fit was not found\n        for pixel in self.pixels.ravel():\n            if not pixel.good_enfit and type(pixel) != Pilatus_Null_Pixel:\n                if pixel.coords not in self.bad_pixels:\n                    self.bad_pixels.append(pixel.coords)\n    \n    def get_trimbit_map(self, threshold_map):\n        \"\"\"\n        Returns the trimbit values for the supplied threshold map (in keV).\n        \"\"\"\n        if self.calibrated:\n            trimbit_map = np.zeros(self.global_pixel_dims, dtype=int)\n\n            for x in range(self.global_pixel_dims[0]):\n                for y in range(self.global_pixel_dims[1]):\n                    # Ensure that the trimbit is within the valid range\n                    tbit = self.pixels[x,y].trimbit_from_threshold(threshold_map[x,y])\n                    if tbit < 0 or np.isnan(tbit):\n                        tbit = 0\n                    elif tbit > self.num_trimbits - 1:\n                        tbit = self.num_trimbits - 1\n                    else:\n                        tbit = int(round(tbit))\n                    \n                    trimbit_map[x,y] = tbit\n        else:\n            print('Detector is not yet calibrated.')\n            trimbit_map = -1*np.ones(self.global_pixel_dims, dtype=int)\n        return trimbit_map\n\n# ---------------------------------------- Specific Detector Implementations ----------------------------------------\n\nclass Pilatus3_100k(Pilatus_Detector):\n    \"\"\"\n    Description:\n        This is a specific implementation of the Pilatus_Detector which integrates the appropraite pixel geometry\n        and device settings. The PILATUS3 100K detector, produced by DECTRIS Ltd., is composed of a single module\n        with approximately 100,000 total pixels.\n    \"\"\"\n    def __init__(self, elements, trimscan_paths, settings_path, trimbit_start=0, omit_trimbits=False, calib_name='MST'):\n        # Pilatus3 pixel properties\n        self.global_pixel_dims = (487, 195)\n        self.num_chips         = 16\n        self.module_dims       = (  1,   1)\n        self.chip_dims         = (  8,   2)\n        self.pixel_dims        = ( 60,  97)\n        self.num_trimbits      = 64\n        self.calibrated        = False\n        self.bad_pixels        = []\n        self.name              = calib_name\n\n        if not omit_trimbits:\n            self.trimbit_start = np.zeros([len(elements), self.num_chips], dtype=int)\n        else:\n            self.trimbit_start = trimbit_start\n\n        # Pilatus3 physical characteristics\n\n        # Load modules and settings\n        self.load_trimscan_data(elements, trimscan_paths)\n        self.load_global_settings(settings_path)\n        self.init_modules()\n\n        # Make pixels easily accessible by global coordinates\n        self.pixels = self.get_pixels()\n\n    def pixel_mapping(self, x, y):\n        \"\"\"\n        Implement the proper mapping for the PILATUS3 100K detector. This is most easily done using the pre-existing\n        mapping function from Novi.\n        \"\"\"\n        chip_num, chip_x, chip_y = utilities.get_chip_coords(x, y)\n        return (0, chip_num, (chip_x, chip_y))\n\n    def get_chip_coords(self, mod_number):\n        \"\"\"\n        Returns the global coordinates for the first (upper-left) pixel on each chip for the PILATUS3 100K.\n        \"\"\"\n        dx = 61\n        dy = 98\n        chip_coords = np.array([[0*dx, 0], [1*dx, 0], [2*dx, 0], [3*dx, 0], [4*dx, 0], [5*dx, 0], [6*dx, 0], [7*dx, 0],\n                                [0*dx,dy], [1*dx,dy], [2*dx,dy], [3*dx,dy], [4*dx,dy], [5*dx,dy], [6*dx,dy], [7*dx,dy]])\n        return chip_coords\n\n    def write_settings_file(self, filepath):\n        \"\"\"\n        Writes the settings used to generate the trimscan back out to a file.\n        \"\"\"\n        # Format the settings into a string with linebreaks\n        settings = '# /dev/shm/setdacs_b01_m01.dat\\n'\n        settings += 'set B01_M01_VTRM {0: 2.4f}\\n'.format(self.settings['VTRM'])\n\n        for vcmp in range(self.num_chips):\n            vcmp_str = 'VCMP{0:}'.format(vcmp)\n            settings += 'set B01_M01_{0:} {1: 2.4f}\\n'.format(vcmp_str, self.settings[vcmp_str])\n\n        for key in ['VCCA', 'VRF', 'VRFS', 'VCAL', 'VDEL', 'VADJ']:\n            settings += 'set B01_M01_{0:} {1: 2.4f}\\n'.format(key, self.settings[key])\n\n        # Remove the final unwanted newline\n        settings = settings[:-1]\n\n        with open(os.path.join(filepath, 'setdacs_b01_m01.dat'), 'wb') as f:\n            f.write(settings)\n\n        print('Settings file written to {0:}.'.format(filepath))\n\n    def write_autotrim_files(self, threshold_map, filepath, filename='autotrim'):\n        \"\"\"\n        Generate autotrim files given a specified threshold map using the calibration.\n        \"\"\"\n        trimbit_map = self.get_trimbit_map(threshold_map)\n        trimbit_sorted = np.zeros([self.num_chips, self.pixel_dims[0], self.pixel_dims[1]])\n\n        for g_x in range(self.global_pixel_dims[0]):\n            for g_y in range(self.global_pixel_dims[1]):\n                cn, cx, cy = utilities.get_chip_coords(g_x, g_y)\n                if cn != -1:\n                    trimbit_sorted[cn, cx, cy] = trimbit_map[g_x, g_y]\n        \n        for cn in range(self.num_chips):\n            trim_string = '# AUTOTRIM files for PILATUS3 100K by UW Madison code\\n'\n            trim_string += 'set B01_M01_CHSEL{0:} 1\\n'.format(cn)\n\n            for cx in range(self.pixel_dims[0]):\n                for cy in range(self.pixel_dims[1]):\n                    trim_string += 'trim {0:} {1:} {2:}\\n'.format(cx, cy, hex(int(trimbit_sorted[cn, cx, cy])))\n\n            trim_string += 'settrims'\n\n            # Write the output file\n            fname = '{0:}_b01_m01_c{1:02d}.dat'.format(filename, cn)\n            with open(os.path.join(filepath, fname), 'wb') as f:\n                f.write(trim_string)\n\n            print('Saved {0:} to file.'.format(fname))\n\n    def write_bad_pixels_file(self, filepath):\n        \"\"\"\n        Outputs a CSV file containing all of the bad pixels. This is useful in later analysis.\n        \"\"\"\n        fname = 'bad_pixels.csv'\n        np.savetxt(os.path.join(filepath, fname), self.bad_pixels, delimiter=',', fmt='%d')\n\n    def get_pixels(self):\n        \"\"\"\n        Since this detector has only one module, just call that module's get_pixels() method.\n        \"\"\"\n        return self.modules[0,0].get_pixels()\n\n    def calibrate(self, num_cores=16, bad_pix=[]):\n        \"\"\"\n        Since this detector has only one module, just call that module's calibrate() method. Use the 'bad_pix'\n        to manually ensure that the specified pixels get marked as bad, even if the fit does not fail.\n        \"\"\"\n        self.modules[0,0].calibrate(num_cores=num_cores)\n        self.calibrated = True\n        self.pixels = self.get_pixels()\n        self.determine_bad_pixels(include=bad_pix)", "meta": {"hexsha": "dbb45cdd56d39a91bd3a3b25791a67b077f5b063", "size": 34614, "ext": "py", "lang": "Python", "max_stars_repo_path": "mesxr/calibration/trimscan.py", "max_stars_repo_name": "pdvanmeter/meSXR", "max_stars_repo_head_hexsha": "c281e15c5fd01591bba9e0c1510f83c5f7ef771a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mesxr/calibration/trimscan.py", "max_issues_repo_name": "pdvanmeter/meSXR", "max_issues_repo_head_hexsha": "c281e15c5fd01591bba9e0c1510f83c5f7ef771a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mesxr/calibration/trimscan.py", "max_forks_repo_name": "pdvanmeter/meSXR", "max_forks_repo_head_hexsha": "c281e15c5fd01591bba9e0c1510f83c5f7ef771a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.9532467532, "max_line_length": 162, "alphanum_fraction": 0.6105910903, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 7914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.29421497216298875, "lm_q1q2_score": 0.1978100560216682}}
{"text": "#!/usr/bin/env python\n\n\"\"\"@package docstring\nFile: me_solver.py\nAuthor: Adam Lamson\nEmail: adam.lamson@colorado.edu\nDescription:\n\"\"\"\n\nimport time\nimport numpy as np\nfrom scipy.integrate import solve_ivp\nfrom .choose_me_evolver import choose_me_evolver\nfrom .solver import Solver\nfrom .non_dimensionalizer import NonDimensionalizer\nfrom .rod_steric_forces import get_min_dist_vec\n\n\nclass MomentExpansionSolver(Solver):\n\n    \"\"\"!Solve the evolution of two rods by expanding the Fokker - Planck equation\n        in a series of moments of motor end positions on rods.\n    \"\"\"\n\n    def __init__(self, pfile=None, pdict=None):\n        \"\"\"!Set parameters for ODE to be solved including initial conditions.\n\n        @param pfile: yaml parameter file name\n        @param pdict: parameter dictionary\n        \"\"\"\n        print(\"Init MomentExpansionSolver ->\", end=\" \")\n        Solver.__init__(self, pfile, pdict)\n\n    def ParseParams(self):\n        \"\"\"!Collect parameters from yaml file or dictionary then calculate\n        some necessary parameters if not defined. Also non-dimensionalize parameters.\n        @return: void\n        \"\"\"\n        Solver.ParseParams(self)\n\n        self.dt = self._params[\"dt\"]  # Time step\n        if \"nt\" not in self._params:\n            print(\"!!! Warning: nt not defined. Using nsteps and dt to find \",\n                  \"total time. nsteps and dt are not used in this calculation.\")\n            self.nsteps = int(self._params[\"nsteps\"])\n            self.nt = self.nsteps * self.dt\n            self._params[\"nt\"] = self.nt\n        else:\n            self.nt = self._params[\"nt\"]\n\n        if \"nwrite\" not in self._params:\n            self.twrite = self._params[\"twrite\"]\n            self.nwrite = int(self.twrite / self.dt)\n        elif \"twrite\" not in self._params:\n            self.nwrite = self._params[\"nwrite\"]\n            self.twrite = float(self.nwrite * self.dt)\n        else:\n            print(\"!!! Warning: Write parameters over defined,\",\n                  \"using twrite to calculate number of steps between write out.\")\n            self.twrite = self._params[\"twrite\"]\n            self.nwrite = int(self.twrite / self.dt)\n\n        self.non_dimmer = self.non_dimensionalize()\n        # Rod orientation vectors\n        self.R1_vec = np.asarray(self._params['R1_vec'])\n        self.R2_vec = np.asarray(self._params['R2_vec'])\n        # Make sure to renormalize\n        self.R1_vec /= np.linalg.norm(self.R1_vec)\n        self.R2_vec /= np.linalg.norm(self.R2_vec)\n\n        # Check to see if steric forces should be used\n        self.steric_flag = self._params.get('steric_interactions', None)\n        if self.steric_flag == 'constrained':\n            self.constr_vec = get_min_dist_vec(self.R2_pos - self.R1_pos,\n                                               self.R1_vec, self.R2_vec)\n            self.constr_vec /= np.linalg.norm(self.constr_vec)\n\n        print(\"R1_vec = \", self.R1_vec)\n        print(\"R2_vec = \", self.R2_vec)\n\n        self.t_eval = np.linspace(0, self.nt, int(self.nt / self.twrite) + 1)\n        self._nframes = self.t_eval.size\n\n        # Set integration method for solver\n        self.method = self._params.get('method', 'LSODA')\n        self._params['method'] = self.method\n        print(\"Solving method = \", self.method)\n\n        # Specify the ODE type\n        self.ODE_type = self._params.get('ODE_type', 'zrl')\n        self._params['ODE_type'] = self.ODE_type\n        print(\"ODE type = \", self.ODE_type)\n\n    def setInitialConditions(self):\n        \"\"\"!Set the initial conditions for the system of ODEs\n        @return: void\n        \"\"\"\n        self.sol_init = np.zeros(26)\n        # Set all geometric variables\n        self.sol_init[:12] = np.concatenate(\n            (self.R1_pos, self.R2_pos, self.R1_vec, self.R2_vec))\n        print(\"=== Initial conditions ===\")\n        print(self.sol_init)\n        # TODO Allow for different initial conditions of moments besides zero\n\n        # Set solver once you set initial conditions\n        # Add kwargs\n        self.ode_solver = choose_me_evolver(self.sol_init, self)\n\n    def makeDataframe(self):\n        \"\"\"!Create data frame to be written out\n        @return: TODO\n        \"\"\"\n        t_arr = self.non_dimmer.dim_val(self.t_eval, ['time'])\n        print(\"Evaluated at:\", t_arr)\n        if not self.data_frame_made:\n            self._time_dset = self._h5_data.create_dataset('time',\n                                                           data=t_arr,\n                                                           dtype=np.float32)\n            self._xl_grp = self._h5_data.create_group('xl_data')\n            self._rod_grp = self._h5_data.create_group('rod_data')\n\n            Solver.makeDataframe(self)\n            self.data_frame_made = True\n\n    def Run(self):\n        \"\"\"!Run algorithm to solve system of ODEs\n        @return: TODO\n        \"\"\"\n\n        t0 = time.time()\n        self.sol = solve_ivp(self.ode_solver, [0, self.nt], self.sol_init,\n                             t_eval=self.t_eval, method=self.method,)\n        # min_step=self.dt, atol=1e-6)\n        self.cpu_time = time.time() - t0\n        print(\n            r\" --- Total simulation time {:.4f} seconds ---\".format(self.cpu_time))\n\n        self.Write()\n\n    def make_rod_dataset(self):\n        \"\"\"!Initialize dataframe with empty rod configuration data\n        @return: void\n\n        \"\"\"\n        self._R1_pos_dset = self._rod_grp.create_dataset(\n            'R1_pos', data=self.sol.y[: 3, :].T)\n        self._R2_pos_dset = self._rod_grp.create_dataset(\n            'R2_pos', data=self.sol.y[3: 6, :].T)\n        self._R1_vec_dset = self._rod_grp.create_dataset(\n            'R1_vec', data=self.sol.y[6: 9, :].T)\n        self._R2_vec_dset = self._rod_grp.create_dataset(\n            'R2_vec', data=self.sol.y[9: 12, :].T)\n\n    def make_xl_moment_dataset(self):\n        \"\"\"!Initialize dataframe with empty crosslinker moment data\n        @return: void\n\n        \"\"\"\n        self._mu0_dset = self._xl_grp.create_dataset('zeroth_moment',\n                                                     data=self.sol.y[12, :].T,\n                                                     dtype=np.float32)\n        self._mu1_dset = self._xl_grp.create_dataset('first_moments',\n                                                     data=self.sol.y[13: 15, :].T,\n                                                     dtype=np.float32)\n        self._mu2_dset = self._xl_grp.create_dataset('second_moments',\n                                                     data=self.sol.y[15:18, :].T,\n                                                     dtype=np.float32)\n        self._B0_dset = self._xl_grp.create_dataset('zeroth_boundary_terms',\n                                                    data=self.sol.y[18:20, :].T,\n                                                    dtype=np.float32)\n        self._B1_dset = self._xl_grp.create_dataset('first_boundary_terms',\n                                                    data=self.sol.y[20:22, :].T,\n                                                    dtype=np.float32)\n        self._B2_dset = self._xl_grp.create_dataset('second_boundary_terms',\n                                                    data=self.sol.y[22:24, :].T,\n                                                    dtype=np.float32)\n        self._B3_dset = self._xl_grp.create_dataset('third_boundary_terms',\n                                                    data=self.sol.y[24:26, :].T,\n                                                    dtype=np.float32)\n\n    def Write(self):\n        \"\"\"!Write out data\n        @return: void\n\n        \"\"\"\n        self.redimensionalize()\n        self.make_xl_moment_dataset()\n        self.make_rod_dataset()\n        # Store how long the simulation took\n        self._h5_data.attrs['cpu_time'] = self.cpu_time\n\n    def non_dimensionalize(self):\n        \"\"\"!Non-dimensionalize parameters to reduce error in calculations.\n        @return: non dimensionalizer\n\n        \"\"\"\n        # non_dim_dict = {'time': 1. / self._params['ko'],\n        #                 # 'length': max(self._params['L1'], self._params['L2']),\n        #                 'length': self._params['fs'] / self._params['ks'],\n        #                 'energy': 1. / self._params['beta']}\n        # NonDimensionalizer not working currently\n        non_dim_dict = {'time': 1.,\n                        'length': float(max(self._params['L1'],\n                                            self._params['L2'])),\n                        # 'length': 1.,\n                        'energy': 1.}\n        non_dimmer = NonDimensionalizer(**non_dim_dict)\n        # non_dimmer.calc_new_dim('force', ['energy', 'length'], [1, -1])\n\n        self.beta = non_dimmer.non_dim_val(self._params['beta'],\n                                           ['energy'], [-1])\n        self.visc = non_dimmer.non_dim_val(self._params['viscosity'],\n                                           ['energy', 'time', 'length'],\n                                           [1, 1, -3])\n        self.L_i = non_dimmer.non_dim_val(self._params['L1'], ['length'])\n        self.L_j = non_dimmer.non_dim_val(self._params['L2'], ['length'])\n        self.R1_pos = non_dimmer.non_dim_val(\n            self._params['R1_pos'], ['length'])\n        self.R2_pos = non_dimmer.non_dim_val(\n            self._params['R2_pos'], ['length'])\n        self.rod_diam = non_dimmer.non_dim_val(self._params['rod_diameter'],\n                                               ['length'])\n        self.dt = non_dimmer.non_dim_val(self.dt, ['time'])\n        self.nt = non_dimmer.non_dim_val(self.nt, ['time'])\n        self.twrite = non_dimmer.non_dim_val(self.twrite, ['time'])\n        self.ko = non_dimmer.non_dim_val(self._params['ko'], ['time'], [-1])\n        self.co = non_dimmer.non_dim_val(self._params['co'], ['length'], [-2])\n        self.ks = non_dimmer.non_dim_val(self._params['ks'],\n                                         ['energy', 'length'], [1, -2])\n        self.ho = non_dimmer.non_dim_val(self._params['ho'], ['length'])\n        self.vo = non_dimmer.non_dim_val(self._params['vo'],\n                                         ['length', 'time'], [1, -1])\n        self.fs = non_dimmer.non_dim_val(\n            self._params['fs'], ['energy', 'length'], [1, -1])\n        return non_dimmer\n\n    def redimensionalize(self):\n        \"\"\"!Redimensionalize data arrays\n        @return: void\n\n        \"\"\"\n        # Redimensionalize rod positions\n        self.sol.y[:6, :] = self.non_dimmer.dim_val(self.sol.y[:6, :],\n                                                    ['length'])\n        # Redimensionalize first moments\n        self.sol.y[13:15, :] = self.non_dimmer.dim_val(self.sol.y[13: 15, :],\n                                                       ['length'])\n        # Redimensionalize second moments\n        self.sol.y[15:18, :] = self.non_dimmer.dim_val(self.sol.y[15:18, :],\n                                                       ['length'], [2])\n        self.sol.y[20:22, :] = self.non_dimmer.dim_val(self.sol.y[20:22, :],\n                                                       ['length'])\n        self.sol.y[22:24, :] = self.non_dimmer.dim_val(self.sol.y[22:24, :],\n                                                       ['length'], [2])\n        self.sol.y[24:26, :] = self.non_dimmer.dim_val(self.sol.y[24:26, :],\n                                                       ['length'], [3])\n", "meta": {"hexsha": "d3e1056675968ca30c675087f516b5c6bed24348", "size": 11376, "ext": "py", "lang": "Python", "max_stars_repo_path": "foxlink/me_solver.py", "max_stars_repo_name": "lamsoa729/FoXlink", "max_stars_repo_head_hexsha": "3c061b02968cdab1def752d5c145a6df4615504b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "foxlink/me_solver.py", "max_issues_repo_name": "lamsoa729/FoXlink", "max_issues_repo_head_hexsha": "3c061b02968cdab1def752d5c145a6df4615504b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "foxlink/me_solver.py", "max_forks_repo_name": "lamsoa729/FoXlink", "max_forks_repo_head_hexsha": "3c061b02968cdab1def752d5c145a6df4615504b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-06-18T16:48:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-20T23:50:02.000Z", "avg_line_length": 44.0930232558, "max_line_length": 85, "alphanum_fraction": 0.5259317862, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.19780932335418258}}
{"text": "import numpy as np\n\ntry:\n    import classy\n    HAVE_CLASS = True\nexcept ImportError:\n    HAVE_CLASS = False\n\ntry:\n    import camb\n    import camb.model\n    HAVE_CAMB = True\nexcept ImportError:\n    HAVE_CAMB = False\n\ntry:\n    import isitgr  # noqa: F401\nexcept ImportError:\n    pass  # prevent nans from isitgr\n\nfrom . import ccllib as lib\nfrom .pyutils import check\nfrom .pk2d import Pk2D\nfrom .errors import CCLError\n\n\ndef get_camb_pk_lin(cosmo, nonlin=False):\n    \"\"\"Run CAMB and return the linear power spectrum.\n\n    Args:\n        cosmo (:class:`~pyccl.core.Cosmology`): Cosmological\n            parameters. The cosmological parameters with\n            which to run CAMB.\n        nonlin (:obj:`bool`, optional): Whether to compute and return the\n            non-linear power spectrum as well.\n\n    Returns:\n        :class:`~pyccl.pk2d.Pk2D`: Power spectrum object. The linear power \\\n            spectrum. If ``nonlin=True``, returns a tuple \\\n            ``(pk_lin, pk_nonlin)``.\n    \"\"\"\n\n    # Comment from Jarvis: TODO clean up this and other assert\n    # anti-patterns in this file\n    assert HAVE_CAMB, (\n        \"You must have the `camb` python package \"\n        \"installed to run CCL with CAMB!\")\n\n    # Get extra CAMB parameters that were specified\n    extra_camb_params = {}\n    try:\n        extra_camb_params = cosmo[\"extra_parameters\"][\"camb\"]\n    except (KeyError, TypeError):\n        pass\n\n    # z sampling from CCL parameters\n    na = lib.get_pk_spline_na(cosmo.cosmo)\n    status = 0\n    a_arr, status = lib.get_pk_spline_a(cosmo.cosmo, na, status)\n    check(status)\n    a_arr = np.sort(a_arr)\n    zs = 1.0 / a_arr - 1\n    zs = np.clip(zs, 0, np.inf)\n\n    # deal with normalization\n    if np.isfinite(cosmo[\"A_s\"]):\n        A_s_fid = cosmo[\"A_s\"]\n    elif np.isfinite(cosmo[\"sigma8\"]):\n        # in this case, CCL will internally normalize for us when we init\n        # the linear power spectrum - so we just get close\n        A_s_fid = 2.43e-9 * (cosmo[\"sigma8\"] / 0.87659)**2\n    else:\n        raise CCLError(\n            \"Could not normalize the linear power spectrum! \"\n            \"A_s = %f, sigma8 = %f\" % (\n                cosmo['A_s'], cosmo['sigma8']))\n\n    # init camb params\n    cp = camb.model.CAMBparams()\n\n    # turn some stuff off\n    cp.WantCls = False\n    cp.DoLensing = False\n    cp.Want_CMB = False\n    cp.Want_CMB_lensing = False\n    cp.Want_cl_2D_array = False\n    cp.WantTransfer = True\n\n    # basic background stuff\n    h2 = cosmo['h']**2\n    cp.H0 = cosmo['h'] * 100\n    cp.ombh2 = cosmo['Omega_b'] * h2\n    cp.omch2 = cosmo['Omega_c'] * h2\n    cp.omk = cosmo['Omega_k']\n\n    # \"constants\"\n    cp.TCMB = cosmo['T_CMB']\n\n    # neutrinos\n    # We maually setup the CAMB neutrinos to match the adjustments CLASS\n    # makes to their temperatures.\n    cp.share_delta_neff = False\n    cp.omnuh2 = cosmo['Omega_nu_mass'] * h2\n    cp.num_nu_massless = cosmo['N_nu_rel']\n    cp.num_nu_massive = int(cosmo['N_nu_mass'])\n    cp.nu_mass_eigenstates = int(cosmo['N_nu_mass'])\n\n    delta_neff = cosmo['Neff'] - 3.046  # used for BBN YHe comps\n\n    # CAMB defines a neutrino degeneracy factor as T_i = g^(1/4)*T_nu\n    # where T_nu is the standard neutrino temperature from first order\n    # computations\n    # CLASS defines the temperature of each neutrino species to be\n    # T_i_eff = TNCDM * T_cmb where TNCDM is a fudge factor to get the\n    # total mass in terms of eV to match second-order computations of the\n    # relationship between m_nu and Omega_nu.\n    # We are trying to get both codes to use the same neutrino temperature.\n    # thus we set T_i_eff = T_i = g^(1/4) * T_nu and solve for the right\n    # value of g for CAMB. We get g = (TNCDM / (11/4)^(-1/3))^4\n    g = np.power(\n        lib.cvar.constants.TNCDM / np.power(11.0/4.0, -1.0/3.0),\n        4.0)\n\n    if cosmo['N_nu_mass'] > 0:\n        nu_mass_fracs = cosmo['m_nu'][:cosmo['N_nu_mass']]\n        nu_mass_fracs = nu_mass_fracs / np.sum(nu_mass_fracs)\n\n        cp.nu_mass_numbers = np.ones(cosmo['N_nu_mass'], dtype=np.int)\n        cp.nu_mass_fractions = nu_mass_fracs\n        cp.nu_mass_degeneracies = np.ones(int(cosmo['N_nu_mass'])) * g\n    else:\n        cp.nu_mass_numbers = []\n        cp.nu_mass_fractions = []\n        cp.nu_mass_degeneracies = []\n\n    # get YHe from BBN\n    cp.bbn_predictor = camb.bbn.get_predictor()\n    cp.YHe = cp.bbn_predictor.Y_He(\n        cp.ombh2 * (camb.constants.COBE_CMBTemp / cp.TCMB) ** 3,\n        delta_neff)\n\n    camb_de_models = ['DarkEnergyPPF', 'ppf', 'DarkEnergyFluid', 'fluid']\n    camb_de_model = extra_camb_params.get('dark_energy_model', 'fluid')\n    if camb_de_model not in camb_de_models:\n        raise ValueError(\"The only dark energy models CCL supports with\"\n                         \" camb are fluid and ppf.\")\n    cp.set_classes(\n        dark_energy_model=camb_de_model\n    )\n\n    if camb_de_model not in camb_de_models[:2] and cosmo['wa'] and \\\n            (cosmo['w0'] < -1 - 1e-6 or\n                1 + cosmo['w0'] + cosmo['wa'] < - 1e-6):\n        raise ValueError(\"If you want to use w crossing -1,\"\n                         \" then please set the dark_energy_model to ppf.\")\n    cp.DarkEnergy.set_params(\n        w=cosmo['w0'],\n        wa=cosmo['wa']\n    )\n\n    if nonlin:\n        cp.NonLinearModel = camb.nonlinear.Halofit()\n        halofit_version = extra_camb_params.get(\"halofit_version\", \"mead\")\n        options = {k: extra_camb_params[k] for k in\n                   [\"HMCode_A_baryon\",\n                    \"HMCode_eta_baryon\",\n                    \"HMCode_logT_AGN\"] if k in extra_camb_params}\n        cp.NonLinearModel.set_params(halofit_version=halofit_version,\n                                     **options)\n\n    cp.set_matter_power(\n        redshifts=[_z for _z in zs],\n        kmax=extra_camb_params.get(\"kmax\", 10.0),\n        nonlinear=nonlin)\n    if not nonlin:\n        assert cp.NonLinear == camb.model.NonLinear_none\n\n    cp.set_for_lmax(extra_camb_params.get(\"lmax\", 5000))\n    cp.InitPower.set_params(\n        As=A_s_fid,\n        ns=cosmo['n_s'])\n\n    # run CAMB and get results\n    camb_res = camb.get_results(cp)\n    k, z, pk = camb_res.get_linear_matter_power_spectrum(\n        hubble_units=True, nonlinear=False)\n\n    # convert to non-h inverse units\n    k *= cosmo['h']\n    pk /= (h2 * cosmo['h'])\n\n    # now build interpolant\n    nk = k.shape[0]\n    lk_arr = np.log(k)\n    a_arr = 1.0 / (1.0 + z)\n    na = a_arr.shape[0]\n    sinds = np.argsort(a_arr)\n    a_arr = a_arr[sinds]\n    ln_p_k_and_z = np.zeros((na, nk), dtype=np.float64)\n    for i, sind in enumerate(sinds):\n        ln_p_k_and_z[i, :] = np.log(pk[sind, :])\n\n    pk_lin = Pk2D(\n        pkfunc=None,\n        a_arr=a_arr,\n        lk_arr=lk_arr,\n        pk_arr=ln_p_k_and_z,\n        is_logp=True,\n        extrap_order_lok=1,\n        extrap_order_hik=2,\n        cosmo=cosmo)\n\n    if not nonlin:\n        return pk_lin\n    else:\n        k, z, pk = camb_res.get_linear_matter_power_spectrum(\n            hubble_units=True, nonlinear=True)\n\n        # convert to non-h inverse units\n        k *= cosmo['h']\n        pk /= (h2 * cosmo['h'])\n\n        # now build interpolant\n        nk = k.shape[0]\n        lk_arr = np.log(k)\n        a_arr = 1.0 / (1.0 + z)\n        na = a_arr.shape[0]\n        sinds = np.argsort(a_arr)\n        a_arr = a_arr[sinds]\n        ln_p_k_and_z = np.zeros((na, nk), dtype=np.float64)\n        for i, sind in enumerate(sinds):\n            ln_p_k_and_z[i, :] = np.log(pk[sind, :])\n\n        pk_nonlin = Pk2D(\n            pkfunc=None,\n            a_arr=a_arr,\n            lk_arr=lk_arr,\n            pk_arr=ln_p_k_and_z,\n            is_logp=True,\n            extrap_order_lok=1,\n            extrap_order_hik=2,\n            cosmo=cosmo)\n\n        return pk_lin, pk_nonlin\n\n\ndef get_isitgr_pk_lin(cosmo):\n    \"\"\"Run ISiTGR-CAMB and return the linear power spectrum.\n\n    Args:\n        cosmo (:class:`~pyccl.core.Cosmology`): Cosmological\n            parameters. The cosmological parameters with\n            which to run ISiTGR-CAMB.\n\n    Returns:\n        :class:`~pyccl.pk2d.Pk2D`: Power spectrum \\\n            object. The linear power spectrum.\n    \"\"\"\n\n    try:\n        import isitgr  # noqa: F811\n        import isitgr.model\n    except ImportError as e:\n        e.args = (\n            \"You must have the `isitgr` python package \"\n            \"installed to run CCL with ISiTGR-CAMB!\",\n            *e.args)\n        raise\n\n    # Get extra CAMB parameters that were specified\n    extra_camb_params = {}\n    try:\n        extra_camb_params = cosmo[\"extra_parameters\"][\"camb\"]\n    except (KeyError, TypeError):\n        pass\n\n    # z sampling from CCL parameters\n    na = lib.get_pk_spline_na(cosmo.cosmo)\n    status = 0\n    a_arr, status = lib.get_pk_spline_a(cosmo.cosmo, na, status)\n    check(status)\n    a_arr = np.sort(a_arr)\n    zs = 1.0 / a_arr - 1\n    zs = np.clip(zs, 0, np.inf)\n\n    # deal with normalization\n    if np.isfinite(cosmo[\"A_s\"]):\n        A_s_fid = cosmo[\"A_s\"]\n    elif np.isfinite(cosmo[\"sigma8\"]):\n        # in this case, CCL will internally normalize for us when we init\n        # the linear power spectrum - so we just get close\n        A_s_fid = 2.43e-9 * (cosmo[\"sigma8\"] / 0.87659)**2\n    else:\n        raise CCLError(\n            \"Could not normalize the linear power spectrum! \"\n            \"A_s = %f, sigma8 = %f\" % (\n                cosmo['A_s'], cosmo['sigma8']))\n\n    # init isitgr params\n    cp = isitgr.model.CAMBparams()\n\n    # turn some stuff off\n    cp.WantCls = False\n    cp.DoLensing = False\n    cp.Want_CMB = False\n    cp.Want_CMB_lensing = False\n    cp.Want_cl_2D_array = False\n    cp.WantTransfer = True\n\n    # basic background stuff\n    h2 = cosmo['h']**2\n    cp.H0 = cosmo['h'] * 100\n    cp.ombh2 = cosmo['Omega_b'] * h2\n    cp.omch2 = cosmo['Omega_c'] * h2\n    cp.omk = cosmo['Omega_k']\n#   cp.GR = 1 means GR modified!\n    cp.GR = 1\n    cp.ISiTGR_muSigma = True\n    cp.mu0 = cosmo['mu_0']\n    cp.Sigma0 = cosmo['sigma_0']\n    cp.c1 = cosmo['c1_mg']\n    cp.c2 = cosmo['c2_mg']\n    cp.Lambda = cosmo['lambda_mg']\n\n    # \"constants\"\n    cp.TCMB = cosmo['T_CMB']\n\n    # neutrinos\n    # We maually setup the CAMB neutrinos to match the adjustments CLASS\n    # makes to their temperatures.\n    cp.share_delta_neff = False\n    cp.omnuh2 = cosmo['Omega_nu_mass'] * h2\n    cp.num_nu_massless = cosmo['N_nu_rel']\n    cp.num_nu_massive = int(cosmo['N_nu_mass'])\n    cp.nu_mass_eigenstates = int(cosmo['N_nu_mass'])\n\n    delta_neff = cosmo['Neff'] - 3.046  # used for BBN YHe comps\n\n    # ISiTGR built on CAMB which defines a neutrino degeneracy\n    # factor as T_i = g^(1/4)*T_nu\n    # where T_nu is the standard neutrino temperature from first order\n    # computations\n    # CLASS defines the temperature of each neutrino species to be\n    # T_i_eff = TNCDM * T_cmb where TNCDM is a fudge factor to get the\n    # total mass in terms of eV to match second-order computations of the\n    # relationship between m_nu and Omega_nu.\n    # We are trying to get both codes to use the same neutrino temperature.\n    # thus we set T_i_eff = T_i = g^(1/4) * T_nu and solve for the right\n    # value of g for CAMB. We get g = (TNCDM / (11/4)^(-1/3))^4\n    g = np.power(\n        lib.cvar.constants.TNCDM / np.power(11.0/4.0, -1.0/3.0),\n        4.0)\n\n    if cosmo['N_nu_mass'] > 0:\n        nu_mass_fracs = cosmo['m_nu'][:cosmo['N_nu_mass']]\n        nu_mass_fracs = nu_mass_fracs / np.sum(nu_mass_fracs)\n\n        cp.nu_mass_numbers = np.ones(cosmo['N_nu_mass'], dtype=np.int)\n        cp.nu_mass_fractions = nu_mass_fracs\n        cp.nu_mass_degeneracies = np.ones(int(cosmo['N_nu_mass'])) * g\n    else:\n        cp.nu_mass_numbers = []\n        cp.nu_mass_fractions = []\n        cp.nu_mass_degeneracies = []\n\n    # get YHe from BBN\n    cp.bbn_predictor = isitgr.bbn.get_predictor()\n    cp.YHe = cp.bbn_predictor.Y_He(\n        cp.ombh2 * (isitgr.constants.COBE_CMBTemp / cp.TCMB) ** 3,\n        delta_neff)\n\n    camb_de_models = ['DarkEnergyPPF', 'ppf', 'DarkEnergyFluid', 'fluid']\n    camb_de_model = extra_camb_params.get('dark_energy_model', 'fluid')\n    if camb_de_model not in camb_de_models:\n        raise ValueError(\"The only dark energy models CCL supports with\"\n                         \" camb are fluid and ppf.\")\n    cp.set_classes(\n        dark_energy_model=camb_de_model\n    )\n    if camb_de_model not in camb_de_models[:2] and cosmo['wa'] and \\\n            (cosmo['w0'] < -1 - 1e-6 or\n                1 + cosmo['w0'] + cosmo['wa'] < - 1e-6):\n        raise ValueError(\"If you want to use w crossing -1,\"\n                         \" then please set the dark_energy_model to ppf.\")\n    cp.DarkEnergy.set_params(\n        w=cosmo['w0'],\n        wa=cosmo['wa']\n    )\n    # cp.set_cosmology()\n    cp.set_matter_power(\n        redshifts=[_z for _z in zs],\n        kmax=10,\n        nonlinear=False)\n    assert cp.NonLinear == isitgr.model.NonLinear_none\n\n    cp.set_for_lmax(5000)\n    cp.InitPower.set_params(\n        As=A_s_fid,\n        ns=cosmo['n_s'])\n\n    # run ISITGR and get results\n    isitgr_res = isitgr.get_results(cp)\n    k, z, pk = isitgr_res.get_linear_matter_power_spectrum(\n        hubble_units=True, nonlinear=False)\n\n    # convert to non-h inverse units\n    k *= cosmo['h']\n    pk /= (h2 * cosmo['h'])\n\n    # now build interpolant\n    nk = k.shape[0]\n    lk_arr = np.log(k)\n    a_arr = 1.0 / (1.0 + z)\n    na = a_arr.shape[0]\n    sinds = np.argsort(a_arr)\n    a_arr = a_arr[sinds]\n    ln_p_k_and_z = np.zeros((na, nk), dtype=np.float64)\n    for i, sind in enumerate(sinds):\n        ln_p_k_and_z[i, :] = np.log(pk[sind, :])\n\n    pk_lin = Pk2D(\n        pkfunc=None,\n        a_arr=a_arr,\n        lk_arr=lk_arr,\n        pk_arr=ln_p_k_and_z,\n        is_logp=True,\n        extrap_order_lok=1,\n        extrap_order_hik=2,\n        cosmo=cosmo)\n    return pk_lin\n\n\ndef get_class_pk_lin(cosmo):\n    \"\"\"Run CLASS and return the linear power spectrum.\n\n    Args:\n        cosmo (:class:`~pyccl.core.Cosmology`): Cosmological\n            parameters. The cosmological parameters with\n            which to run CLASS.\n\n    Returns:\n        :class:`~pyccl.pk2d.Pk2D`: Power spectrum object.\\\n            The linear power spectrum.\n    \"\"\"\n\n    assert HAVE_CLASS, (\n        \"You must have the python wrapper for CLASS \"\n        \"installed to run CCL with CLASS!\")\n\n    params = {\n        \"output\": \"mPk\",\n        \"non linear\": \"none\",\n        \"P_k_max_1/Mpc\": cosmo.cosmo.spline_params.K_MAX_SPLINE,\n        \"z_max_pk\": 1.0/cosmo.cosmo.spline_params.A_SPLINE_MINLOG_PK-1.0,\n        \"modes\": \"s\",\n        \"lensing\": \"no\",\n        \"h\": cosmo[\"h\"],\n        \"Omega_cdm\": cosmo[\"Omega_c\"],\n        \"Omega_b\": cosmo[\"Omega_b\"],\n        \"Omega_k\": cosmo[\"Omega_k\"],\n        \"n_s\": cosmo[\"n_s\"]}\n\n    # cosmological constant?\n    # set Omega_Lambda = 0.0 if w !=-1 or wa != 0\n    if cosmo['w0'] != -1 or cosmo['wa'] != 0:\n        params[\"Omega_Lambda\"] = 0\n        params['w0_fld'] = cosmo['w0']\n        params['wa_fld'] = cosmo['wa']\n\n    # neutrino parameters\n    # massless neutrinos\n    if cosmo[\"N_nu_rel\"] > 1e-4:\n        params[\"N_ur\"] = cosmo[\"N_nu_rel\"]\n    else:\n        params[\"N_ur\"] = 0.0\n\n    # massive neutrinos\n    if cosmo[\"N_nu_mass\"] > 0:\n        params[\"N_ncdm\"] = cosmo[\"N_nu_mass\"]\n        masses = lib.parameters_get_nu_masses(cosmo._params, 3)\n        params[\"m_ncdm\"] = \", \".join(\n            [\"%g\" % m for m in masses[:cosmo[\"N_nu_mass\"]]])\n\n    params[\"T_cmb\"] = cosmo[\"T_CMB\"]\n\n    # if we have sigma8, we need to find A_s\n    if np.isfinite(cosmo[\"A_s\"]):\n        params[\"A_s\"] = cosmo[\"A_s\"]\n    elif np.isfinite(cosmo[\"sigma8\"]):\n        # in this case, CCL will internally normalize for us when we init\n        # the linear power spectrum - so we just get close\n        A_s_fid = 2.43e-9 * (cosmo[\"sigma8\"] / 0.87659)**2\n        params[\"A_s\"] = A_s_fid\n    else:\n        raise CCLError(\n            \"Could not normalize the linear power spectrum! \"\n            \"A_s = %f, sigma8 = %f\" % (\n                cosmo['A_s'], cosmo['sigma8']))\n\n    model = None\n    try:\n        model = classy.Class()\n        model.set(params)\n        model.compute()\n\n        # Set k and a sampling from CCL parameters\n        nk = lib.get_pk_spline_nk(cosmo.cosmo)\n        na = lib.get_pk_spline_na(cosmo.cosmo)\n        status = 0\n        a_arr, status = lib.get_pk_spline_a(cosmo.cosmo, na, status)\n        check(status)\n\n        # FIXME - getting the lowest CLASS k value from the python interface\n        # appears to be broken - setting to 1e-5 which is close to the\n        # old value\n        lk_arr = np.log(np.logspace(\n            -5,\n            np.log10(cosmo.cosmo.spline_params.K_MAX_SPLINE), nk))\n\n        # we need to cut this to the max value used for calling CLASS\n        msk = lk_arr < np.log(cosmo.cosmo.spline_params.K_MAX_SPLINE)\n        nk = int(np.sum(msk))\n        lk_arr = lk_arr[msk]\n\n        # now do interp by hand\n        ln_p_k_and_z = np.zeros((na, nk), dtype=np.float64)\n        for aind in range(na):\n            z = max(1.0 / a_arr[aind] - 1, 1e-10)\n            for kind in range(nk):\n                ln_p_k_and_z[aind, kind] = np.log(\n                    model.pk_lin(np.exp(lk_arr[kind]), z))\n    finally:\n        if model is not None:\n            model.struct_cleanup()\n            model.empty()\n\n    params[\"P_k_max_1/Mpc\"] = cosmo.cosmo.spline_params.K_MAX_SPLINE\n\n    # make the Pk2D object\n    pk_lin = Pk2D(\n        pkfunc=None,\n        a_arr=a_arr,\n        lk_arr=lk_arr,\n        pk_arr=ln_p_k_and_z,\n        is_logp=True,\n        extrap_order_lok=1,\n        extrap_order_hik=2,\n        cosmo=cosmo)\n\n    return pk_lin\n", "meta": {"hexsha": "1681c445b64739489b775a5971292d1badbeadb4", "size": 17528, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyccl/boltzmann.py", "max_stars_repo_name": "Jappenn/CCL", "max_stars_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 91, "max_stars_repo_stars_event_min_datetime": "2017-07-14T02:45:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:55:54.000Z", "max_issues_repo_path": "pyccl/boltzmann.py", "max_issues_repo_name": "Jappenn/CCL", "max_issues_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 703, "max_issues_repo_issues_event_min_datetime": "2017-07-07T16:27:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:40:10.000Z", "max_forks_repo_path": "pyccl/boltzmann.py", "max_forks_repo_name": "Jappenn/CCL", "max_forks_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 54, "max_forks_repo_forks_event_min_datetime": "2017-07-12T13:08:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T13:12:10.000Z", "avg_line_length": 31.8112522686, "max_line_length": 76, "alphanum_fraction": 0.5977863989, "include": true, "reason": "import numpy", "num_tokens": 5279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.19780931945203}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nfrom __future__ import absolute_import, division, print_function\nimport os\nimport json\nimport copy\nimport pprint\nimport logging\nimport numpy as np\nfrom astropy.io import fits\nfrom astropy.coordinates import SkyCoord\nfrom astropy.table import Table, Column\nfrom gammapy.maps import WcsNDMap, MapCoord\nimport fermipy.config\nfrom fermipy import utils\nfrom fermipy import defaults\nfrom fermipy import wcs_utils\nfrom fermipy import fits_utils\nfrom fermipy.sourcefind_utils import fit_error_ellipse\nfrom fermipy.sourcefind_utils import find_peaks\nfrom fermipy.skymap import Map\nfrom fermipy.config import ConfigSchema\nfrom fermipy.gtutils import FreeParameterState, SourceMapState\nfrom fermipy.timing import Timer\nfrom fermipy.model_utils import get_function_norm_par_name\nfrom LikelihoodState import LikelihoodState\nimport pyLikelihood as pyLike\n\n\nclass SourceFind(object):\n    \"\"\"Mixin class which provides source-finding functionality to\n    `~fermipy.gtanalysis.GTAnalysis`.\"\"\"\n\n    def find_sources(self, prefix='', **kwargs):\n        \"\"\"An iterative source-finding algorithm that uses likelihood\n        ratio (TS) maps of the region of interest to find new sources.\n        After each iteration a new TS map is generated incorporating\n        sources found in the previous iteration.  The method stops\n        when the number of iterations exceeds ``max_iter`` or no\n        sources exceeding ``sqrt_ts_threshold`` are found.\n\n        Parameters\n        ----------\n        {options}\n\n        tsmap : dict\n           Keyword arguments dictionary for tsmap method.\n\n        tscube : dict\n           Keyword arguments dictionary for tscube method.\n\n        Returns\n        -------\n\n        peaks : list\n           List of peak objects.\n\n        sources : list\n           List of source objects.\n\n        \"\"\"\n        timer = Timer.create(start=True)\n        self.logger.info('Starting.')\n\n        schema = ConfigSchema(self.defaults['sourcefind'],\n                              tsmap=self.defaults['tsmap'],\n                              tscube=self.defaults['tscube'])\n\n        schema.add_option('search_skydir', None, '', SkyCoord)\n        schema.add_option('search_minmax_radius', [None, 1.0], '', list)\n\n        config = utils.create_dict(self.config['sourcefind'],\n                                   tsmap=self.config['tsmap'],\n                                   tscube=self.config['tscube'])\n        config = schema.create_config(config, **kwargs)\n\n        # Defining default properties of test source model\n        config['model'].setdefault('Index', 2.0)\n        config['model'].setdefault('SpectrumType', 'PowerLaw')\n        config['model'].setdefault('SpatialModel', 'PointSource')\n        config['model'].setdefault('Prefactor', 1E-13)\n\n        o = {'sources': [], 'peaks': []}\n\n        for i in range(config['max_iter']):\n            srcs, peaks = self._find_sources_iterate(prefix, i, **config)\n\n            self.logger.info('Found %i sources in iteration %i.' %\n                             (len(srcs), i))\n\n            o['sources'] += srcs\n            o['peaks'] += peaks\n            if len(srcs) == 0:\n                break\n\n        self.logger.info('Done.')\n        self.logger.info('Execution time: %.2f s', timer.elapsed_time)\n\n        return o\n\n    def _build_src_dicts_from_peaks(self, peaks, maps, src_dict_template):\n\n        tsmap = maps['ts']\n        amp = maps['amplitude']\n\n        src_dicts = []\n        names = []\n\n        for p in peaks:\n\n            o = fit_error_ellipse(tsmap, (p['ix'], p['iy']), dpix=2)\n            skydir = o['skydir']\n            p['fit_loc'] = o\n            p['fit_skydir'] = o['skydir']\n\n            p.update(o)\n            name = utils.create_source_name(skydir)\n            src_dict = copy.deepcopy(src_dict_template)\n            norm_par = get_function_norm_par_name(\n                src_dict_template['SpectrumType'])\n            src_dict.update({norm_par: amp.data[p['iy'], p['ix']],\n                             'ra': skydir.icrs.ra.deg,\n                             'dec': skydir.icrs.dec.deg})\n\n            src_dict['glon_err'] = o['glon_err']\n            src_dict['glat_err'] = o['glat_err']\n            src_dict['ra_err'] = o['ra_err']\n            src_dict['dec_err'] = o['dec_err']\n            src_dict['pos_err'] = o['pos_err']\n            src_dict['pos_err_semimajor'] = o['pos_err_semimajor']\n            src_dict['pos_err_semiminor'] = o['pos_err_semiminor']\n            src_dict['pos_r68'] = o['pos_r68']\n            src_dict['pos_r95'] = o['pos_r95']\n            src_dict['pos_r99'] = o['pos_r99']\n            src_dict['pos_angle'] = o['pos_angle']\n            src_dict['pos_gal_cov'] = o['pos_gal_cov']\n            src_dict['pos_gal_corr'] = o['pos_gal_corr']\n            src_dict['pos_cel_cov'] = o['pos_cel_cov']\n            src_dict['pos_cel_corr'] = o['pos_cel_corr']\n\n            self.logger.info('Found source\\n' +\n                             'name: %s\\n' % name +\n                             'ts: %f' % p['amp'] ** 2)\n\n            names.append(name)\n            src_dicts.append(src_dict)\n\n        return names, src_dicts\n\n    def _find_sources_iterate(self, prefix, iiter, **kwargs):\n\n        src_dict_template = kwargs.pop('model')\n\n        threshold = kwargs.get('sqrt_ts_threshold')\n        multithread = kwargs.get('multithread', False)\n        min_separation = kwargs.get('min_separation')\n        sources_per_iter = kwargs.get('sources_per_iter')\n        search_skydir = kwargs.get('search_skydir', None)\n        search_minmax_radius = kwargs.get('search_minmax_radius', [None, 1.0])\n        tsmap_fitter = kwargs.get('tsmap_fitter', 'tsmap')\n        free_params = kwargs.get('free_params', None)\n        if not free_params:\n            free_params = None\n\n        if tsmap_fitter == 'tsmap':\n            kw = kwargs.get('tsmap', {})\n            kw['model'] = src_dict_template\n            kw['multithread'] = multithread\n            m = self.tsmap(utils.join_strings([prefix,\n                                               'sourcefind_%02i' % iiter]),\n                           **kw)\n\n        elif tsmap_fitter == 'tscube':\n            kw = kwargs.get('tscube', {})\n            kw['model'] = src_dict_template\n            kw['do_sed'] = False\n            m = self.tscube(utils.join_strings([prefix,\n                                                'sourcefind_%02i' % iiter]),\n                            **kw)\n        else:\n            raise Exception(\n                'Unrecognized option for fitter: %s.' % tsmap_fitter)\n\n        if tsmap_fitter == 'tsmap':\n            peaks = find_peaks(m['sqrt_ts'], threshold, min_separation)\n            (names, src_dicts) = \\\n                self._build_src_dicts_from_peaks(peaks, m, src_dict_template)\n        elif tsmap_fitter == 'tscube':\n            peaks = find_peaks(m['sqrt_ts'], threshold, min_separation)\n            (names, src_dicts) = \\\n                self._build_src_dicts_from_peaks(peaks, m, src_dict_template)\n            \"\"\"\n            sd = m['tscube'].find_sources(threshold ** 2, min_separation,\n                                          use_cumul=False,\n                                          output_src_dicts=True,\n                                          output_peaks=True)\n            peaks = sd['Peaks']\n            names = sd['Names']\n            src_dicts = sd['SrcDicts']\n            \"\"\"\n\n        # Loop over the seeds and add them to the model\n        new_src_names = []\n        for name, src_dict in zip(names, src_dicts):\n            # Protect against finding the same source twice\n            if self.roi.has_source(name):\n                self.logger.info('Source %s found again.  Ignoring it.' % name)\n                continue\n            # Skip the source if it's outside the search region\n            if search_skydir is not None:\n\n                skydir = SkyCoord(src_dict['ra'], src_dict['dec'], unit='deg')\n                separation = search_skydir.separation(skydir).deg\n\n                if not utils.apply_minmax_selection(separation,\n                                                    search_minmax_radius):\n                    self.logger.info('Source %s outside of '\n                                     'search region.  Ignoring it.',\n                                     name)\n                    continue\n\n            self.add_source(name, src_dict, free=True)\n            self.free_source(name, False)\n            new_src_names.append(name)\n\n            if len(new_src_names) >= sources_per_iter:\n                break\n\n        # Re-fit spectral parameters of each source individually\n        for name in new_src_names:\n            self.logger.info('Performing spectral fit for %s.', name)\n            self.logger.debug(pprint.pformat(self.roi[name].params))\n            self.free_source(name, True, pars=free_params)\n            self.fit()\n            self.logger.info(pprint.pformat(self.roi[name].params))\n            self.free_source(name, False)\n\n        srcs = []\n        for name in new_src_names:\n            srcs.append(self.roi[name])\n\n        return srcs, peaks\n\n    def localize(self, name, **kwargs):\n        \"\"\"Find the best-fit position of a source.  Localization is\n        performed in two steps.  First a TS map is computed centered\n        on the source with half-width set by ``dtheta_max``.  A fit is\n        then performed to the maximum TS peak in this map.  The source\n        position is then further refined by scanning the likelihood in\n        the vicinity of the peak found in the first step.  The size of\n        the scan region is set to encompass the 99% positional\n        uncertainty contour as determined from the peak fit.\n\n        Parameters\n        ----------\n        name : str\n            Source name.\n\n        {options}\n\n        optimizer : dict\n            Dictionary that overrides the default optimizer settings.\n\n        Returns\n        -------\n        localize : dict\n            Dictionary containing results of the localization\n            analysis.\n\n        \"\"\"\n        timer = Timer.create(start=True)\n        name = self.roi.get_source_by_name(name).name\n\n        schema = ConfigSchema(self.defaults['localize'],\n                              optimizer=self.defaults['optimizer'])\n        schema.add_option('use_cache', True)\n        schema.add_option('prefix', '')\n        config = utils.create_dict(self.config['localize'],\n                                   optimizer=self.config['optimizer'])\n        config = schema.create_config(config, **kwargs)\n\n        self.logger.info('Running localization for %s' % name)\n\n        free_state = FreeParameterState(self)\n        loc = self._localize(name, **config)\n        free_state.restore()\n\n        self.logger.info('Finished localization.')\n\n        if config['make_plots']:\n            self._plotter.make_localization_plots(loc, self.roi,\n                                                  prefix=config['prefix'])\n\n        outfile = \\\n            utils.format_filename(self.workdir, 'loc',\n                                  prefix=[config['prefix'],\n                                          name.lower().replace(' ', '_')])\n\n        if config['write_fits']:\n            loc['file'] = os.path.basename(outfile) + '.fits'\n            self._make_localize_fits(loc, outfile + '.fits',\n                                     **config)\n\n        if config['write_npy']:\n            np.save(outfile + '.npy', dict(loc))\n\n        self.logger.info('Execution time: %.2f s', timer.elapsed_time)\n        return loc\n\n    def _make_localize_fits(self, loc, filename, **kwargs):\n\n        tab = fits_utils.dict_to_table(loc)\n        hdu_data = fits.table_to_hdu(tab)\n        hdu_data.name = 'LOC_DATA'\n\n        hdus = [loc['tsmap_peak'].make_hdu(hdu='PRIMARY'),\n                loc['tsmap'].make_hdu(hdu='TSMAP'),\n                hdu_data]\n\n        hdus[0].header['CONFIG'] = json.dumps(loc['config'])\n        hdus[2].header['CONFIG'] = json.dumps(loc['config'])\n        fits_utils.write_hdus(hdus, filename)\n\n    def _localize(self, name, **kwargs):\n\n        nstep = kwargs.get('nstep')\n        dtheta_max = kwargs.get('dtheta_max')\n        update = kwargs.get('update', True)\n        prefix = kwargs.get('prefix', '')\n        use_cache = kwargs.get('use_cache', False)\n        free_background = kwargs.get('free_background', False)\n        free_radius = kwargs.get('free_radius', None)\n        fix_shape = kwargs.get('fix_shape', False)\n        tsmap_fitter = kwargs.get('tsmap_fitter', 'tsmap')\n\n        saved_state = LikelihoodState(self.like)\n        loglike_init = -self.like()\n        self.logger.debug('Initial Model Log-Likelihood: %f', loglike_init)\n\n        if not free_background:\n            self.free_sources(free=False, loglevel=logging.DEBUG)\n\n        if free_radius is not None:\n            diff_sources = [s.name for s in self.roi.sources if s.diffuse]\n            skydir = self.roi[name].skydir\n            free_srcs = [s.name for s in\n                         self.roi.get_sources(skydir=skydir,\n                                              distance=free_radius,\n                                              exclude=diff_sources)]\n            self.free_sources_by_name(free_srcs, pars='norm',\n                                      loglevel=logging.DEBUG)\n\n        src = self.roi.copy_source(name)\n        skydir = src.skydir\n        skywcs = self.geom.wcs\n        src_pix = skydir.to_pixel(skywcs)\n\n        fit0 = self._fit_position_tsmap(name, prefix=prefix,\n                                        dtheta_max=dtheta_max,\n                                        zmin=-3.0,\n                                        use_pylike=False,\n                                        tsmap_fitter=tsmap_fitter)\n\n        self.logger.debug('Completed localization with TS Map.\\n'\n                          '(ra,dec) = (%10.4f,%10.4f) '\n                          '(glon,glat) = (%10.4f,%10.4f)',\n                          fit0['ra'], fit0['dec'],\n                          fit0['glon'], fit0['glat'])\n\n        # Fit baseline (point-source) model\n        self.free_source(name, loglevel=logging.DEBUG)\n        if fix_shape:\n            self.free_source(name, free=False, pars='shape',\n                             loglevel=logging.DEBUG)\n        fit_output = self._fit(loglevel=logging.DEBUG, **\n                               kwargs.get('optimizer', {}))\n\n        # Save likelihood value for baseline fit\n        loglike_base = fit_output['loglike']\n        self.logger.debug('Baseline Model Log-Likelihood: %f', loglike_base)\n\n        o = defaults.make_default_tuple(defaults.localize_output)\n        o.name = name\n        o.config = kwargs\n        o.fit_success = True\n        o.loglike_init = loglike_init\n        o.loglike_base = loglike_base\n        o.loglike_loc = np.nan\n        o.dloglike_loc = np.nan\n\n        if fit0['fit_success']:\n            scan_cdelt = 2.0 * fit0['pos_r95'] / (nstep - 1.0)\n        else:\n            scan_cdelt = np.abs(skywcs.wcs.cdelt[0])\n\n        self.logger.debug('Refining localization search to '\n                          'region of width: %.4f deg',\n                          scan_cdelt * nstep)\n\n        fit1 = self._fit_position_scan(name,\n                                       skydir=fit0['skydir'],\n                                       scan_cdelt=scan_cdelt,\n                                       **kwargs)\n\n        o.loglike_loc = fit1['loglike']\n        o.dloglike_loc = o.loglike_loc - o.loglike_base\n        o.tsmap = fit0.pop('tsmap')\n        o.tsmap_peak = fit1.pop('tsmap')\n        # o.update(fit1)\n\n        # Best fit position and uncertainty from fit to TS map\n        o.fit_init = fit0\n\n        # Best fit position and uncertainty from pylike scan\n        o.fit_scan = fit1\n        o.update(fit1)\n\n        cdelt0 = np.abs(skywcs.wcs.cdelt[0])\n        cdelt1 = np.abs(skywcs.wcs.cdelt[1])\n        pix = fit1['skydir'].to_pixel(skywcs)\n        o.pos_offset = skydir.separation(fit1['skydir']).deg\n        o.xpix = float(pix[0])\n        o.ypix = float(pix[1])\n        o.deltax = (o.xpix - src_pix[0]) * cdelt0\n        o.deltay = (o.ypix - src_pix[1]) * cdelt1\n\n        o.ra_preloc = skydir.ra.deg\n        o.dec_preloc = skydir.dec.deg\n        o.glon_preloc = skydir.galactic.l.deg\n        o.glat_preloc = skydir.galactic.b.deg\n\n        if o.pos_offset > dtheta_max:\n            o.fit_success = False\n\n        if not o.fit_success:\n            self.logger.warning('Fit to localization contour failed.')\n        elif not o.fit_inbounds:\n            self.logger.warning('Best-fit position outside of search region.')\n        else:\n            self.logger.info('Localization succeeded.')\n\n        if update and ((not o.fit_success) or (not o.fit_inbounds)):\n            self.logger.warning(\n                'Localization failed.  Keeping existing position.')\n\n        if update and o.fit_success and o.fit_inbounds:\n            self.logger.info('Updating source %s '\n                             'to localized position.', name)\n            src = self.delete_source(name)\n            src.set_position(fit1['skydir'])\n            self.add_source(name, src, free=True)\n            self.free_source(name, loglevel=logging.DEBUG)\n            if fix_shape:\n                self.free_source(name, free=False, pars='shape',\n                                 loglevel=logging.DEBUG)\n\n            fit_output = self.fit(loglevel=logging.DEBUG)\n            o.loglike_loc = fit_output['loglike']\n            o.dloglike_loc = o.loglike_loc - o.loglike_base\n            src = self.roi.get_source_by_name(name)\n\n            src['glon_err'] = o.glon_err\n            src['glat_err'] = o.glat_err\n            src['ra_err'] = o.ra_err\n            src['dec_err'] = o.dec_err\n            src['pos_err'] = o.pos_err\n            src['pos_err_semimajor'] = o.pos_err_semimajor\n            src['pos_err_semiminor'] = o.pos_err_semiminor\n            src['pos_r68'] = o.pos_r68\n            src['pos_r95'] = o.pos_r95\n            src['pos_r99'] = o.pos_r99\n            src['pos_angle'] = o.pos_angle\n            src['pos_gal_cov'] = o.pos_gal_cov\n            src['pos_gal_corr'] = o.pos_gal_corr\n            src['pos_cel_cov'] = o.pos_cel_cov\n            src['pos_cel_corr'] = o.pos_cel_corr\n        else:\n            saved_state.restore()\n            self._sync_params(name)\n            self._update_roi()\n\n        self.logger.info('Localization completed with new position:\\n'\n                         '(  ra, dec) = (%10.4f +/- %8.4f,%10.4f +/- %8.4f)\\n'\n                         '(glon,glat) = (%10.4f +/- %8.4f,%10.4f +/- %8.4f)\\n'\n                         'offset = %8.4f r68 = %8.4f r95 = %8.4f r99 = %8.4f',\n                         o.ra, o.ra_err, o.dec, o.dec_err,\n                         o.glon, o.glon_err, o.glat, o.glat_err,\n                         o.pos_offset, o.pos_r68, o.pos_r95, o.pos_r99)\n        self.logger.info('LogLike: %12.3f DeltaLogLike: %12.3f',\n                         o.loglike_loc, o.loglike_loc - o.loglike_init)\n\n        return o\n\n    def _fit_position(self, name, **kwargs):\n\n        dtheta_max = kwargs.setdefault('dtheta_max', 0.5)\n        nstep = kwargs.setdefault('nstep', 5)\n        fit0 = self._fit_position_tsmap(name, **kwargs)\n\n        if np.isfinite(fit0['pos_r68']):\n            scan_cdelt = min(2.0 * fit0['pos_r68'] / (nstep - 1.0),\n                             self._binsz)\n        else:\n            scan_cdelt = self._binsz\n\n        fit1 = self._fit_position_scan(name,\n                                       skydir=fit0['skydir'],\n                                       scan_cdelt=scan_cdelt,\n                                       **kwargs)\n        return fit1, fit0\n\n    def _fit_position_tsmap(self, name, **kwargs):\n        \"\"\"Localize a source from its TS map.\"\"\"\n\n        prefix = kwargs.get('prefix', '')\n        dtheta_max = kwargs.get('dtheta_max', 0.5)\n        zmin = kwargs.get('zmin', -3.0)\n        tsmap_fitter = kwargs.get('tsmap_fitter', 'tsmap')\n\n        kw = {'map_size': 2.0 * dtheta_max,\n              'write_fits':  kwargs.get('write_fits', False),\n              'write_npy':  kwargs.get('write_npy', False),\n              'max_kernel_radius': self.config['tsmap']['max_kernel_radius'],\n              'loglevel': logging.DEBUG}\n\n        src = self.roi.copy_source(name)\n\n        if src['SpatialModel'] in ['RadialDisk', 'RadialGaussian']:\n            kw['max_kernel_radius'] = max(kw['max_kernel_radius'],\n                                          2.0 * src['SpatialWidth'])\n\n        skydir = kwargs.get('skydir', src.skydir)\n        \n        if tsmap_fitter == 'tsmap':\n            tsmap = self.tsmap(utils.join_strings([prefix, name.lower().\n                                                   replace(' ', '_')]),\n                               model=src.data,\n                               map_skydir=skydir,\n                               exclude=[name],\n                               use_pylike=kwargs.get('use_pylike', True),\n                               make_plots=False, **kw)\n        else:\n            tsmap = self.tscube(utils.join_strings([prefix, name.lower().replace(' ', '_')]),                                \n                                model=src.data,\n                                map_skydir=skydir,\n                                exclude=[name],\n                                make_plots=False,\n                                do_sed=False,\n                                **kw)\n             \n\n        # Find peaks with TS > 4\n        peaks = find_peaks(tsmap['ts'], 4.0, 0.2)\n        peak_best = None\n        o = {}\n        for p in sorted(peaks, key=lambda t: t['amp'], reverse=True):\n            xy = p['ix'], p['iy']\n            ts_value = tsmap['ts'].data[xy[1], xy[0]]\n            posfit = fit_error_ellipse(tsmap['ts'], xy=xy, dpix=2,\n                                       zmin=max(zmin, -ts_value * 0.5))\n            offset = posfit['skydir'].separation(self.roi[name].skydir).deg\n            if posfit['fit_success'] and posfit['fit_inbounds']:\n                peak_best = p\n                break\n\n        if peak_best is None:\n            ts_value = np.max(tsmap['ts'].data)\n            posfit = fit_error_ellipse(tsmap['ts'], dpix=2,\n                                       zmin=max(zmin, -ts_value * 0.5))\n\n        o.update(posfit)\n        pix = posfit['skydir'].to_pixel(self.geom.wcs)\n        o['xpix'] = float(pix[0])\n        o['ypix'] = float(pix[1])\n        o['skydir'] = posfit['skydir'].transform_to('icrs')\n        o['pos_offset'] = posfit['skydir'].separation(\n            self.roi[name].skydir).deg\n        o['loglike'] = 0.5 * posfit['zoffset']\n        o['tsmap'] = tsmap['ts']\n\n        return o\n\n    def _fit_position_scan(self, name, **kwargs):\n\n        zmin = kwargs.get('zmin', -9.0)\n        tsmap, loglike = self._scan_position(name, **kwargs)\n        ts_value = np.max(tsmap.data)\n        posfit = fit_error_ellipse(tsmap, dpix=2,\n                                   zmin=max(zmin, -ts_value * 0.5))\n        pix = posfit['skydir'].to_pixel(self.geom.wcs)\n\n        o = {}\n        o.update(posfit)\n        o['xpix'] = float(pix[0])\n        o['ypix'] = float(pix[1])\n        o['skydir'] = posfit['skydir'].transform_to('icrs')\n        o['pos_offset'] = posfit['skydir'].separation(\n            self.roi[name].skydir).deg\n        o['loglike'] = 0.5 * posfit['zoffset'] + loglike\n        o['tsmap'] = tsmap\n\n        return o\n\n    def _scan_position(self, name, **kwargs):\n\n        saved_state = LikelihoodState(self.like)\n\n        skydir = kwargs.pop('skydir', self.roi[name].skydir)\n        scan_cdelt = kwargs.pop('scan_cdelt', 0.02)\n        nstep = kwargs.pop('nstep', 5)\n        use_cache = kwargs.get('use_cache', True)\n        use_pylike = kwargs.get('use_pylike', False)\n        optimizer = kwargs.get('optimizer', {})\n\n        # Fit without source\n        self.zero_source(name, loglevel=logging.DEBUG)\n        fit_output_nosrc = self._fit(loglevel=logging.DEBUG,\n                                     **optimizer)\n        self.unzero_source(name, loglevel=logging.DEBUG)\n        saved_state.restore()\n        self.free_norm(name, loglevel=logging.DEBUG)\n\n        lnlmap = WcsNDMap.create(skydir=skydir, binsz=scan_cdelt, npix=(nstep, nstep),\n                                 coordsys=wcs_utils.get_coordsys(self.geom.wcs))\n\n        src = self.roi.copy_source(name)\n\n        if use_cache and not use_pylike:\n            self._create_srcmap_cache(src.name, src)\n\n        coord = MapCoord.create(lnlmap.geom.get_coord(flat=True),\n                                coordsys=lnlmap.geom.coordsys)\n        scan_skydir = coord.skycoord.icrs\n        for lon, lat, ra, dec in zip(coord.lon, coord.lat,\n                                     scan_skydir.ra.deg, scan_skydir.dec.deg):\n\n            spatial_pars = {'ra': ra, 'dec': dec}\n            self.set_source_morphology(name,\n                                       spatial_pars=spatial_pars,\n                                       use_pylike=use_pylike)\n            fit_output = self._fit(loglevel=logging.DEBUG,\n                                   **optimizer)\n            lnlmap.set_by_coord((lon, lat), fit_output['loglike'])\n\n        self.set_source_morphology(name, spatial_pars=src.spatial_pars,\n                                   use_pylike=use_pylike)\n        saved_state.restore()\n\n        lnlmap.data -= fit_output_nosrc['loglike']\n        tsmap = WcsNDMap(lnlmap.geom, 2.0 * lnlmap.data)\n\n        self._clear_srcmap_cache()\n        return tsmap, fit_output_nosrc['loglike']\n\n    def _fit_position_opt(self, name, use_cache=True):\n\n        state = SourceMapState(self.like, [name])\n\n        src = self.roi.copy_source(name)\n\n        if use_cache:\n            self._create_srcmap_cache(src.name, src)\n\n        loglike = []\n        skydir = src.skydir\n        skywcs = self.geom.wcs\n        src_pix = skydir.to_pixel(skywcs)\n\n        c = skydir.transform_to('icrs')\n        src.set_radec(c.ra.deg, c.dec.deg)\n        self._update_srcmap(src.name, src)\n\n        print(src_pix, self.like())\n\n        import time\n\n        def fit_fn(params):\n\n            t0 = time.time()\n\n            c = SkyCoord.from_pixel(params[0], params[1], self.geom.wcs)\n            c = c.transform_to('icrs')\n            src.set_radec(c.ra.deg, c.dec.deg)\n\n            t1 = time.time()\n\n            self._update_srcmap(src.name, src)\n\n            t2 = time.time()\n\n            val = self.like()\n\n            t3 = time.time()\n\n            print(params, val)\n            # print(t1-t0,t2-t1,t3-t2)\n\n            return val\n\n        #lnl0 = fit_fn(src_pix[0],src_pix[1])\n        #lnl1 = fit_fn(src_pix[0]+0.1,src_pix[1])\n        # print(lnl0,lnl1)\n\n        import scipy\n\n        #src_pix[1] += 3.0\n        p0 = [src_pix[0], src_pix[1]]\n\n        #p0 = np.array([14.665692574327048, 16.004594098101926])\n        #delta = np.array([0.3,-0.4])\n        #p0 = [14.665692574327048, 16.004594098101926]\n\n        o = scipy.optimize.minimize(fit_fn, p0,\n                                    bounds=[(0.0, 39.0),\n                                            (0.0, 39.0)],\n                                    # method='L-BFGS-B',\n                                    method='SLSQP',\n                                    tol=1e-6)\n\n        print('fit 2')\n\n        o = scipy.optimize.minimize(fit_fn, o.x,\n                                    bounds=[(0.0, 39.0),\n                                            (0.0, 39.0)],\n                                    # method='L-BFGS-B',\n                                    method='SLSQP',\n                                    tol=1e-6)\n        print(o)\n\n        print(fit_fn(p0))\n        print(fit_fn(o.x))\n        print(fit_fn(o.x + np.array([0.02, 0.02])))\n        print(fit_fn(o.x + np.array([0.02, -0.02])))\n        print(fit_fn(o.x + np.array([-0.02, 0.02])))\n        print(fit_fn(o.x + np.array([-0.02, -0.02])))\n\n        state.restore()\n\n        return o\n", "meta": {"hexsha": "6fd2f58ee6fd65fe0a6bbf51216ac4e073e20c56", "size": 27897, "ext": "py", "lang": "Python", "max_stars_repo_path": "fermipy/sourcefind.py", "max_stars_repo_name": "damgreen/fermipy", "max_stars_repo_head_hexsha": "92b693a9272453bc6eb5c21e9bbac912408122fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fermipy/sourcefind.py", "max_issues_repo_name": "damgreen/fermipy", "max_issues_repo_head_hexsha": "92b693a9272453bc6eb5c21e9bbac912408122fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fermipy/sourcefind.py", "max_forks_repo_name": "damgreen/fermipy", "max_forks_repo_head_hexsha": "92b693a9272453bc6eb5c21e9bbac912408122fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.749661705, "max_line_length": 125, "alphanum_fraction": 0.5303796107, "include": true, "reason": "import numpy,import scipy,from astropy", "num_tokens": 6574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.197809311647725}}
{"text": "\n\n\n# ZBFitter5.py\n# Reverting to radial scaling factors UVMAX=27mrad, XYmax=390mm: RT169.py\n# Reading RT169_Nrings_8_Rmax_27.txt\n#\n#    0.000023    0.000002   -0.013169   -0.000001    0.000012    0.018778    0.000187   -0.000000   -0.000005    0.000001    0.000000    \n#    0.000001    0.000001    0.000001    0.000002    0.000001    0.000002    0.000002    0.000004    0.000001    0.000002    0.000005\n#\n#  all 24 look good!\n#  Maybe a Diameter effect at the focal surface?\n#  DESI-9.OPT has 840mm: should be plenty!\n# Let's try eliminating that Diameter:  DESI-10.OPT go to  RT170.py and YES here we are:\n#\n# Here using radial scaling factors UVMAX=28mrad,  XYMAX=407mm\n# Reading RT170_Nrings_8_Rmax_28.txt  using DESI-10.OPT lacking FP Diameter\n#\n#  Results forward, 11 ZB coefs, RT170, ZBF5fwd, UVMAX=28\n# ADC0      Xtrans      Ytrans      Magnif    UpDownUp  RightLeftRight  InOut      OutInOut     Roll   LeftRightCurl  UpDownCurl  RollAntiRoll\n# coefs    0.000023    0.000001   -0.019117   -0.000001    0.000012    0.020128    0.000215   -0.000000   -0.000005    0.000001    0.000000    \n# sigma    0.000001    0.000001    0.000001    0.000002    0.000001    0.000002    0.000002    0.000000    0.000001    0.000002    0.000005\n# ADC6 (180 deg):\n# coefs   -0.012770    0.000001   -0.019101   -0.000001   -0.000699    0.020127    0.000214    0.000000   -0.000104    0.000001   -0.000000    \n# sigma    0.000001    0.000001    0.000001    0.000002    0.000002    0.000002    0.000003    0.000003    0.000002    0.000002    0.000005\n#     .. in fact all the 25 ADC settings look good. No \"nan\" or crazy results. \n#\n#  Results reverse, 11 ZB coefs, RT170, ZBF5fwd, UVMAX=28\n# ADC0      Xtrans      Ytrans      Magnif    UpDownUp  RightLeftRight  InOut      OutInOut     Roll   LeftRightCurl  UpDownCurl  RollAntiRoll\n# coefs   -0.000023   -0.000001    0.018720    0.000001   -0.000010   -0.020395    0.000566    0.000000    0.000005   -0.000001    0.000000    \n# sigma    0.000001    0.000001    0.000001    0.000002    0.000001    0.000002    0.000002    0.000000    0.000001    0.000002    0.000005\n#     .. in fact ALL the 25 ADC settings look good.  No \"nan\" or crazy results. \n#\n# Conclusion: use DESI-10.OPT prescription with its absence of FP Diameter spec. \n#\n#\n# Earlier:  using radial scaling factors UVMAX=28mrad,  XYMAX=407mm\n# Reading RT168_Nrings_8_Rmax_28.txt\n#\n#  Results forward, 11 ZB coefs, RT168, ZBF3fwd, UVMAX=28\n# ADC0      Xtrans      Ytrans      Magnif    UpDownUp  RightLeftRight  InOut      OutInOut     Roll   LeftRightCurl  UpDownCurl  RollAntiRoll\n# coefs    0.000023   -0.000000   -0.019118    0.000000    0.000012    0.020126    0.000236   -0.000000   -0.000005    0.000000    0.000000    \n# sigma    0.000001    0.000005    0.000001         nan    0.000001    0.000002    0.000002    0.000007    0.000001         nan    0.000008\n# ADC6 (180 deg)\n# coefs   -0.012771   -0.000000   -0.019103    0.000000   -0.000701    0.020126    0.000236   -0.000000   -0.000108    0.000000    0.000000    \n# sigma    0.000001    0.000006    0.000002  631.809570    0.000002    0.000002    0.000003    0.000010    0.000002  631.809566    0.000010\n#                                             ^^^^^^^^                                                                ^^^^^^^^\n#  Yikes, why do the sigmas go crazy at ADC settings of 0, 180 degrees?\n#  Could it be my UVMAX=28, or is it some other bug?\n#  To find out, see RT169: just like RT168 but with UVMAX=27.\n#\n# Results reverse, 11 ZB coefs, RT168, ZBF3rev,UVMAX=28\n# ADC0:\n# coefs    -0.000023   -0.000000    0.018720   -0.000000   -0.000010   -0.020398    0.000538    0.000000    0.000005   -0.000000   -0.000000    \n# sigma     0.000001    0.000005    0.000001   52.833776    0.000001    0.000002    0.000002    0.000008    0.000001   52.833778    0.000008\n# ADC6:\n# coefs     0.012763    0.000000    0.018716   -0.000000   -0.000237   -0.020398    0.000537    0.000000    0.000271   -0.000000   -0.000000    \n# sigma     0.000001    0.000005    0.000001  348.925720    0.000001    0.000002    0.000002    0.000009    0.000001  348.925720    0.000009\n#\n#  COMPARE PREVIOUS RESULTS USING ZBFitter2.py:\n#\n# Results forward, 11 ZB coefs, RT166, ZBF2fwd, UVMAX=27\n# ADC0      Xtrans      Ytrans      Magnif    UpDownUp  RightLeftRight  InOut      OutInOut     Roll   LeftRightCurl  UpDownCurl  RollAntiRoll\n# coefs     0.000023    0.000002   -0.013169   -0.000001    0.000012    0.018778    0.000187   -0.000000   -0.000005    0.000001    0.000000    \n# sigma     0.000001    0.000001    0.000001    0.000002    0.000001    0.000002    0.000002    0.000004    0.000001    0.000002    0.000005\n# ADC6:\n# coefs    -0.013285    0.000002   -0.013153   -0.000001   -0.000678    0.018777    0.000187    0.000000   -0.000101    0.000001   -0.000000    \n# sigma     0.000001    0.000001    0.000002    0.000002    0.000001    0.000002    0.000002    0.000004    0.000001    0.000002    0.000004\n#\n# Results reverse, 11 ZB coefs, RT166, ZBF2rev,UVMAX=27\n# ADC0:\n# coefs    -0.000023   -0.000002    0.012965    0.000001   -0.000010   -0.018778    0.000475    0.000000    0.000005   -0.000001    0.000000    \n# sigma     0.000001    0.000001    0.000001    0.000002    0.000001    0.000002    0.000002    0.000000    0.000001    0.000002    0.000005\n# ADC6:\n# coefs     0.013233   -0.000002    0.012961    0.000001   -0.000226   -0.018777    0.000473   -0.000000    0.000256   -0.000001   -0.000000    \n# sigma     0.000001    0.000001    0.000001    0.000002    0.000001    0.000002    0.000002    0.000001    0.000001    0.000002    0.000000\n    \n\n\n\n\n\n\n\n\n# coefs  -0.000023   -0.000002    0.012965    0.000001   -0.000010   -0.018778    0.000475    0.000000    0.000005   -0.000001    0.000000   \n#\n# Modelling ADC roll as Zhao-Burge distortions.\n# Assumes that RT168.py has already run a complete monochromatic trace,\n# with ~ 400 rays per pupil, and 217 sky locations with image centroids,\n# for ADC1 = 0,30,60,... and then ADC2 = 0, 30, 60...degrees\n# These 24 cases are built into RT166.\n# The results file with all 24 cases is RT166_Nrings_8_Rmax_27.txt\n#\n\nimport csv\nimport numpy as np\nfrom numpy import genfromtxt\nimport matplotlib.pyplot as plt\nimport math\nfrom scipy.optimize import curve_fit\n\nPROGNAME = 'ZBFitter5.py'\n\nLUT = [0,  1,  2,  5,  6,   9,   20,  27, 28, 29, 30]   # 11 polynomials\n# parm 0,  1,  2,  3,  4,   5,   6,   7,  8,  9,  10    # parm numbers\n# ZB:  S2, S3, S4, S7, S8,  S11, S22, T4, T7, T8, T11    # Zhao-Burge labels\n#      Xt, Yt, mag,\n\n\nNPARMS = len(LUT)\n\n\ninfilename = 'RT169_Nrings_8_Rmax_27.txt'  # 5425 records = 25 x 217\n\n\ndef getFileArray(filename):\n    nums2D = list()    \n    with open(filename) as f:\n        data = f.readlines()\n    for row in data:\n        numrow = list()\n        words = row.split()\n        for word in words:\n            try:\n                x = float(word)\n            except:\n                x = -0.0\n            numrow.append(x)\n        nums2D.append(numrow)\n    #---Make nums2D rectangular, lest asarray() will return a 2D list---\n    nrows = len(nums2D)\n    ncols = 0\n    for i in range(nrows):\n        ncols = max(ncols, len(nums2D[i]))\n    print(' ncols = ' + str(ncols))\n    for i in range(nrows):\n        while len(nums2D[i]) < ncols:\n            nums2D[i].append(-0.0)\n    myArray = np.asarray(nums2D)\n    return myArray\n\n\n#-------ZERNIKE NORMALIZED FUNCTIONS & DERIVATIVES--------\n#-------------Using {n,m} definitions---------------------\n\ndef factorial(n):\n    if n > 1:\n       return int(n*factorial(n-1))\n    else:\n       return 1\n       \ndef convertNolltoBW(noll):\n    # converts a Noll Zernike index to the B&W {n,m,t} triplet\n    n = int(-0.5+np.sqrt(2*noll-1.75))\n    m = 0\n    base = int(0.5*n**2 +0.5*n + 1)\n    diff = noll - base\n    if n%2==0:\n        m = 2*int(0.5*diff + 0.7)\n    else:\n        m = 2*int(0.5*diff + 1.2) - 1\n    if noll%2>0:  \n        m = -m\n    return np.array([n, m])\n\ndef convertWyanttoBW(wyant):\n    # converts a Wyant Zernike index to the B&W {n,m,t}   \n    halfsum = int(np.sqrt(wyant))\n    idif = int(wyant - halfsum**2)\n    halfdif = int (idif/2)\n    n = halfsum + halfdif\n    m = halfsum - halfdif\n    if idif%2 >0:\n        m = -m\n    return np.array([n, m]) \n    \ndef getZernFuncXY(nm, xnorm, ynorm):   # BIG NINE:  #1\n    # Here, xnorm and ynorm must lie within the unit circle\n    rnorm = np.sqrt(xnorm*xnorm + ynorm*ynorm)\n    angle = np.arctan2(ynorm,xnorm)\n    return getZernRadial(nm,rnorm) * getZernAngular(nm,angle)\n\n    \ndef getZernRadial(nm, rnorm):    # BIG NINE: #4\n    n = nm[0]             # B&W\n    m = np.abs(nm[1])     # B&W\n    halfsum = (n+m)/2\n    idif = n-m\n    halfdif = int(idif/2)\n    # n = halfsum + halfdif   # or, halfsum = (n+m)/2\n    # m = halfsum - halfdif   # or, halfdif = (n-m)/2\n    # loop through the polynomial\n    result = 0.\n    for i in range(0, halfdif+1):\n        expon = int(n-2*i)\n        sign = 1 if i%2 == 0 else -1\n        numer = sign * factorial(n-i)\n        denom = factorial(i) * factorial(halfsum-i) * factorial(halfdif-i)\n        coef = numer / denom\n        term = coef*math.pow(rnorm, expon)\n        result = result + term\n    return result  \n    \ndef getZernAngular(nm, theta): \n    m = nm[1]    # B&W\n    if m==0:\n        return 1.\n    if m>0:\n        return math.cos(m*theta)\n    m = np.abs(m)         # note this abs() function\n    return math.sin(m*theta)  \n\ndef zernFormulaText(nm):           # BIG NINE: #8\n    #---generates a text representation of the specified Zernike function--\n    n = nm[0]  # B&W\n    m = nm[1]  # B&W\n    # print 'New zernFormulaText() is using n, m: ', n, m\n    needsine = True if m<0 else False\n    m = np.abs(m)\n    halfsum = (n+m)/2\n    idif = n-m\n    halfdif = int(idif/2)\n    \n    #--first do the radial part----\n    nterms = 0\n    s = ''\n    #--evaluate the radial polynomial-----\n    for i in range(0, halfdif+1):\n        nterms = nterms + 1\n        # print \"Starting with n,  m, i, nterms = \", n, m, i, nterms\n        expon = int(n-2*i)                # start with highest exponent\n        # print \"  expon = \", expon\n        sign = 1 if i%2 == 0 else -1      # alternating signs in Zernike series\n        strsign = '+' if i%2==0 else '-'\n        numer = sign * factorial(n-i)\n        denom = factorial(i) * factorial(halfsum-i) * factorial(halfdif-i)\n        coef = numer / denom\n        scoef = str(coef)\n        if coef==1 and expon>0:          # suppress showing coef=1\n            scoef = ''\n        if coef > 0 and nterms > 1:\n            scoef = '+' + scoef\n        s = s + scoef\n        if expon > 0:\n            s = s + 'r'\n        if expon > 1:\n            s = s + '^' + str(expon)\n    if nterms>1 and m!=0:\n        s = '('+ s + ')'\n    #--then do the azimuthal part, if any--------\n    if m==0:\n        return s\n    strm = ''\n    if m>1:    \n        strm = str(m)\n    if needsine:\n        s = s + '*sin(' + strm + 't)'\n    else:\n        s = s + '*cos(' + strm + 't)'\n    return s\n\n#--END ZERNIKES with {n,m} B&W indexing------------\n\n\n\n\n#-----Zhao-Burge functions built from Zernikes---------------------\n\nrh = np.sqrt(0.5)\nrt = np.sqrt(2.0)\n\n\nNPARMS = len(LUT)\n  \ndef getZ(noll, x, y):\n    return getZernFuncXY(convertNolltoBW(noll), x, y)\n\ndef getZhaoBurgeTerm(whichparm, x, y):\n    # Given a Lampton index \"which\" 0....19 and an object point x, y,\n    # fetches the needed the Zernikes via their Noll numbers..\n    # Returns the modeled image point deviation x, y.\n    # Case numbers shown are from Zhao & Burge Tables 1 and 2. \n    which = LUT[whichparm]\n    if which==0:   # case \"S2\"  r^0, keep; X translate\n        return getZ(1,x,y), 0.0\n        \n    if which==1:   # case \"S3\"  r^0, keep; Y translate\n        return 0.0, getZ(1,x,y)\n        \n    if which==2:   # case \"S4\"   r^1, keep: magnification\n        return rh*getZ(2,x,y), rh*getZ(3,x,y)\n        \n    if which==3:   # case \"S5\"   r^1   -1ppm Mangled, 3ppm PartlyMangled, 4ppm ADC45\n        return rh*getZ(3,x,y), rh*getZ(2,x,y)\n        \n    if which==4:   # case \"S6\"    r^1  24ppm Mangled,  6ppm PartlyMangled,-5ppm ADC45\n        return rh*getZ(2,x,y), -rh*getZ(3,x,y)\n        \n    if which==5:   # case \"S7\"   r^2 125ppm Mangled  -908ppm PartlyMangled, ADC=423\n        return 0.5*getZ(5,x,y), rh*getZ(4,x,y)-0.5*getZ(6,x,y)\n        \n    if which==6:   # case \"S8\"    r^2, 1223 Mangled, 653 PartlyMangled 10ppm ADC\n        return rh*getZ(4,x,y)+0.5*getZ(6,x,y), 0.5*getZ(5,x,y)\n        \n    if which==7:   # case \"S9\"   r^3, 77ppm Mangled, 383 PartlyMangled, 116ppm ADC\n        return rh*getZ(5,x,y), rh*getZ(6,x,y)\n        \n    if which==8:   # case \"S10\"   r^2, -6ppm Mangled  -1ppm PartlyMangled, zero ADC\n        return rh*getZ(6,x,y), -rh*getZ(5,x,y)\n        \n    if which==9:   # case \"S11\"   r^3, huge\n        return rh*getZ(8,x,y), rh*getZ(7,x,y)\n        \n    if which==10:  # case \"S12\"   r^3, 2ppm Mangled,zero PartlyMangled, zero ADC\n        return 0.5*getZ(8,x,y)+0.5*getZ(10,x,y), -0.5*getZ(7,x,y)+0.5*getZ(9,x,y)\n        \n    if which==11:  # case \"S13\"    r^3, zero Mangled  zero PartlyMangled, 1ppm ADC\n        return 0.5*getZ(7,x,y)+0.5*getZ(9,x,y), 0.5*getZ(8,x,y)-0.5*getZ(10,x,y)\n        \n    if which==12:  # case \"S14\"    r^3, 1ppm Mangled  zero PartlyMangled zero ppm ADC\n        return rh*getZ(10,x,y), -rh*getZ(9,x,y)\n        \n    if which==13:  # case \"S15\"    r^3, zero Mangled   zeroPartlyMangled  zero ppm ADC\n        return rh*getZ(9,x,y), rh*getZ(10,x,y)\n        \n    if which==14:  # Case \"S16\"  r^4  38ppm Mangled; 9ppm PartlyMangled, zeroADCero ADC\n        return rh*getZ(11,x,y)+0.5*getZ(12,x,y), 0.5*getZ(3,x,y)\n        \n    if which==15:  # Case \"S17\":   r^4   15ppmMangled, -7ppm PartlyMangled,   8ppm ADC\n        return 0.5*getZ(3,x,y), rh*getZ(11,x,y)-0.5*getZ(12,x,y)\n        \n    if which==16:  # Case \"S18\"  r^4   -6ppm Mangled, zero PartlyMangled, zero ADC\n        return 0.5*getZ(12,x,y)+0.5*getZ(14,x,y), 0.5*getZ(15,x,y)-0.5*getZ(13,x,y)\n        \n    if which==17:  # Case \"S19\"   r^4   2ppm Mangled  -1ppm PartlyMangled  1ppm ADC;\n        return 0.5*getZ(13,x,y)+0.5*getZ(15,x,y), 0.5*getZ(12,x,y)-0.5*getZ(14,x,y)\n        \n    if which==18:  # Case \"S20\"  r^4   zero Mangled, zero PartlyMangled, zero ADC\n        return rh*getZ(14,x,y), -rh*getZ(15,x,y)\n        \n    if which==19:  # Case \"S21\"  r^4   zero Mangled  1ppm PartlyMangled, zero ADC\n        return rh*getZ(15,x,y), rh*getZ(14,x,y)\n        \n    if which==20:  # Case \"S22\"  r^5  171 ppm Mangled  172ppm PartlyMangled, 172ppm ADC\n        return rh*getZ(16,x,y), rh*getZ(17,x,y)\n        \n    if which==21:  # Case \"S23\"  r^5  zero Mangled  1ppm PartlyMangled,  zero ADC\n        return 0.5*getZ(17,x,y)+0.5*getZ(19,x,y), 0.5*getZ(16,x,y)-0.5*getZ(18,x,y)\n        \n    if which==22:  # Case \"S24\"   r^5  -1ppm Mangled  zeroPartlyMangled,zero ADC\n        return 0.5*getZ(16,x,y)+0.5*getZ(18,x,y), -0.5*getZ(17,x,y)+0.5*getZ(19,x,y)\n        \n    if which==23:  # Case \"S25\"  r^5   zero Mangled  zero PartlyMangled zero ADC\n        return 0.5*getZ(19,x,y)+0.5*getZ(21,x,y), 0.5*getZ(18,x,y)-0.5*getZ(20,x,y)\n        \n    if which==24:  # Case \"S26\"   r^5  zero ppm  zero PartlyMangled  zero ADC\n        return 0.5*getZ(18,x,y)+0.5*getZ(20,x,y), -0.5*getZ(19,x,y)+0.5*getZ(21,x,y)\n\n    if which==25:  # Case \"S27\"   r^5   zero ppm  zero, PartlyMangled; zero ADC\n        return rh*getZ(21,x,y), rh*getZ(20,x,y)\n\n    if which==26:  # Case \"S28\"  r^5  zero ppm  zero PartlyMangled, zero ADC\n        return rh*getZ(20,x,y), -rh*getZ(21,x,y)\n\n    if which==27:  #  case \"T4\"   r^1,  huge, -6ppm ADC.  Roll.\n        return rh*getZ(3,x,y), -rh*getZ(2,x,y)\n        \n    if which==28:  # case \"T7\"    r^2,  -265ppm Mangled, 131 PartlyMangled, -4ppm ADC\n        return rh*getZ(4,x,y)-0.5*getZ(6,x,y), -0.5*getZ(5,x,y)\n        \n    if which==29:  # case \"T8\"   r^2, -105ppm Mangled.  -544ppm PartlyMangled, -163 ADC\n        return 0.5*getZ(5,x,y), -rh*getZ(4,x,y)+0.5*getZ(6,x,y)\n        \n    if which==30:  # case \"T11\"   r^3, 358ppm Mangled, 358 PartlyMangled  zero ADC\n        return rh*getZ(7,x,y), -rh*getZ(8,x,y)\n        \n    if which==31:  # case \"T12\"   r^3,  -1ppm Mangled, zero PartlyMangled, zero ADC\n        return -0.5*getZ(7,x,y)+0.5*getZ(9,x,y), -0.5*getZ(8,x,y)-0.5*getZ(10,x,y)\n        \n    if which==32:  # case \"T13\"  r^3, +1ppm Mangled,  zero PartlyMangled, zero ADC\n        return 0.5*getZ(8,x,y)-0.5*getZ(10,x,y), -0.5*getZ(7,x,y)-0.5*getZ(9,x,y)\n        \n    print(\"ZhaoBurgeTerm() is exitting because which = \", which)\n    quit()\n\n\n\"\"\"\ndef doRemapping(myParms):\n    # feeds each sky point {u,v} into getZhaoSum()\n    # will be called by optimizer to try out a mix of parameters.\n    for i in range(0, len(SkyGrid)):\n        u = SkyGrid[i, 0]\n        v = SkyGrid[i, 1]\n        x, y = getZhaoSum(myParms, u, v)\n        # print 'result:  i, x, y ={:6d}{:12.6f}{:12.6f}'.format(i, x, y) \n        X[i] = x\n        Y[i] = y\n\"\"\"     \n\ndef zbFunc(uv, *parms): # uv = 1D array input concatenate(u[],v[])\n    # Model: any number of Zhao & Burge parameters\n    # note: curve_fit() calls its given func(args, *parms)\n    # print(\"anyFunc() hasreceived parms = \")\n    # print([\"{0:0.6f}\".format(xx) for xx in parms])\n    pq = np.zeros(len(uv))\n    half = len(uv)//2\n    for i in range(0, half):  # EACH OBJECT POINT NOT AN ARRAY\n        u = uv[i]\n        v = uv[i+half]\n        x, y = getZhaoSum(u, v, *parms)  # always args then parms\n        pq[i] = x\n        pq[i+half] = y\n    return pq   \n\ndef getZhaoSum(u, v, *coefs):\n    # This models the distortion of ONE SKY POINT onto ONE FOCAL POINT.\n    # Sums over all terms.\n    # coefs is the array of 20 coefficients\n    # u and v are Cartesian sky coordinates mapped into unit radius circle.\n    x = u   # initially undeviated\n    y = v   # initially undeviated\n    for index in range(0, len(coefs)):\n        dx, dy = getZhaoBurgeTerm(index, u, v)\n        x += dx * coefs[index]\n        y += dy * coefs[index]\n    return x, y\n\ndef radialFunc(uv, *parms):\n    # 6 parms model: dx, dy, a1, a3, a5, a7\n    # untested!\n    pq = np.zeros(len(uv))\n    half = len(uv)//2\n    for i in range(0, half):\n        u = uv[i]\n        v = uv[i+half]\n        r = np.sqrt(u*u+v*v)\n        if r==0.:\n            u = 1E-12\n        t = np.arctan2(u,v)\n        rpoly = (1.+p[2])*r + p[3]*r**3 + p[4]*r**5 + p[5]*r**7\n        x = p[0] + np.cos(t)*rpoly\n        y = p[1] + np.sin(t)*rpoly\n        pq[i] = x\n        pq[i+half] = y\n    return pq\n     \n#-------------------Main program-------------------------    \n\n\nalldata = getFileArray(infilename)\nprint(alldata.shape)  # 5208 x 9; 24 fields of 217 spots each\nprint('  ADC1  ADC2    RU        RV      Ngood    Xave      Yave       Xrms      Yrms')\nNadcs     = 25\nNeach     = 217\nNRINGS    = 8\nUVMAX     = 28     # milliradians\nXYMAX     = 407    # millimeters\n\n\n# first get the forward (sky to FP) fits to the 25 ADC tasks\n\noutfilename = 'ZBF5fwd_Nrings_' + str(NRINGS) + '_Rmax_' + str(UVMAX) + '.txt'\n\nwith open(outfilename, 'w') as outfile:\n    for adc in range(Nadcs):\n        adc12 = np.copy(alldata[adc*Neach:(adc+1)*Neach, 0:2])    # rows,cols\n        uv    = np.copy(alldata[adc*Neach:(adc+1)*Neach, 2:4])    # rows,cols\n        xy    = np.copy(alldata[adc*Neach:(adc+1)*Neach, 5:7])    # rows,cols\n        uv *= 1000./UVMAX   # for unit circle scaling\n        xy *= 1./XYMAX     # for unit circle scaling\n        print()\n\n        pinitial = np.zeros(NPARMS)\n        args     = np.concatenate([uv[:,0], uv[:,1]])\n        goals    = np.concatenate([xy[:,0], xy[:,1]])\n        popt, covar = curve_fit(zbFunc, args, goals, pinitial)\n        #  note: curve_fit() calls its given func(args, *parms)\n        print('\\npopt: \\n', popt)\n        perror = np.sqrt(covar.diagonal())\n        print('\\nerrors: \\n', perror)\n        combo = np.concatenate((popt, perror))  # double parentheses\n        result = ''\n        for item in combo:\n            result += '{:12.6f}'.format(item)\n        outfile.writelines(result + '\\n') # yes, plural even for one line\n\n# then get the reverse (FP to sky) fits to the 25 ADC tasks\n\noutfilename = 'ZBF5rev_Nrings_' + str(NRINGS) + '_Rmax_' + str(UVMAX) + '.txt'\n\nwith open(outfilename, 'w') as outfile:\n    for adc in range(Nadcs):\n        adc12 = np.copy(alldata[adc*Neach:(adc+1)*Neach, 0:2])    # rows,cols\n        uv    = np.copy(alldata[adc*Neach:(adc+1)*Neach, 2:4])    # rows,cols\n        xy    = np.copy(alldata[adc*Neach:(adc+1)*Neach, 5:7])    # rows,cols\n        uv *= 1000./UVMAX   # for unit circle scaling\n        xy *= 1./XYMAX     # for unit circle scaling\n        print()\n\n        pinitial = np.zeros(NPARMS)\n        goals    = np.concatenate([uv[:,0], uv[:,1]])\n        args     = np.concatenate([xy[:,0], xy[:,1]])\n        popt, covar = curve_fit(zbFunc, args, goals, pinitial)\n        #  note: curve_fit() calls its given func(args, *parms)\n        print('\\npopt: \\n', popt)\n        perror = np.sqrt(covar.diagonal())\n        print('\\nerrors: \\n', perror)\n        combo = np.concatenate((popt, perror))  # double parentheses\n        result = ''\n        for item in combo:\n            result += '{:12.6f}'.format(item)\n        outfile.writelines(result + '\\n') # yes, plural even for one line\n\n", "meta": {"hexsha": "028abfc833a6ccf21930de31a7a6ff50aea43736", "size": 21178, "ext": "py", "lang": "Python", "max_stars_repo_path": "py/desici/DESI-5095-v6/ZBFitter5.py", "max_stars_repo_name": "desihub/desici", "max_stars_repo_head_hexsha": "d9d165e2d9595e114d2330f92776089368df01c2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "py/desici/DESI-5095-v6/ZBFitter5.py", "max_issues_repo_name": "desihub/desici", "max_issues_repo_head_hexsha": "d9d165e2d9595e114d2330f92776089368df01c2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "py/desici/DESI-5095-v6/ZBFitter5.py", "max_forks_repo_name": "desihub/desici", "max_forks_repo_head_hexsha": "d9d165e2d9595e114d2330f92776089368df01c2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1223300971, "max_line_length": 144, "alphanum_fraction": 0.5638870526, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 8092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.1977810586773576}}
{"text": "#  Copyright (c) 2019, CNRS-LAAS\n#  All rights reserved.\n#\n#  Redistribution and use in source and binary forms, with or without\n#  modification, are permitted provided that the following conditions are met:\n#\n#  * Redistributions of source code must retain the above copyright notice, this\n#  list of conditions and the following disclaimer.\n#\n#  * Redistributions in binary form must reproduce the above copyright notice,\n#  this list of conditions and the following disclaimer in the documentation\n#  and/or other materials provided with the distribution.\n#\n#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n#  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n#  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n#  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n#  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n#  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n#  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n#  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n#  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport typing as ty\n\nimport cv2\nimport numpy as np\nimport skimage.draw\nimport skimage.measure\n\nimport fire_rs.geodata.geo_data\nimport fire_rs.rbf\n\n\nclass Perimeter:\n\n    def __init__(self, wildfire: fire_rs.geodata.geo_data.GeoData, threshold: float,\n                 layer: str = 'ignition', perimeter_background=np.inf):\n        self._wildfire = wildfire\n        self._threshold = threshold\n        self._layer = layer\n        self._empty_val = perimeter_background\n\n        self._perimeter_array, self._cells, self._contour = _compute_perimeter(\n            self._wildfire, self._threshold, layer=self._layer, empty_val=self._empty_val)\n\n        if self._contour:\n            for cont in self._contour:\n                skimage.measure.grid_points_in_poly(self._wildfire.data.shape, cont)\n\n        self._perimeter_geodata = None\n        self._area_array = None\n\n    @property\n    def array(self) -> np.ndarray:\n        return self._perimeter_array\n\n    @property\n    def cells(self) -> ty.MutableMapping[ty.Tuple[int, int], np.float64]:\n        return self._cells\n\n    @property\n    def count(self) -> int:\n        \"\"\"Number of indepedent perimeters\"\"\"\n        return len(self._contour)\n\n    @property\n    def geodata(self) -> fire_rs.geodata.geo_data.GeoData:\n        if self._perimeter_geodata is None:\n            self._perimeter_geodata = self._wildfire.clone(data_array=self._perimeter_array,\n                                                           dtype=self._wildfire.data.dtype)\n        return self._perimeter_geodata\n\n    @property\n    def area_array(self):\n        \"\"\"Mask of cells inside the perimeter\"\"\"\n        if self._area_array is None:\n            if self._contour:\n                self._area_array = skimage.measure.grid_points_in_poly(self._wildfire.data.shape,\n                                                                       self._contour[0])\n                if len(self._contour) > 1:\n                    for cont in self._contour[1:]:\n                        self._area_array += skimage.measure.grid_points_in_poly(\n                            self._wildfire.data.shape, cont)\n        return self._area_array\n\n\n_compute_perimeter_output_type = ty.Tuple[\n    np.ndarray, ty.MutableMapping[ty.Tuple[int, int], np.float64], ty.List[np.ndarray]]\n\n\ndef _compute_perimeter(wildfire: fire_rs.geodata.geo_data.GeoData, threshold: float,\n                       layer: str = 'ignition', empty_val=np.inf) -> _compute_perimeter_output_type:\n    \"\"\"Extract the perimeter given by threshold from a fire map.\"\"\"\n\n    array = np.ones(wildfire.data.shape, dtype=np.float64) * empty_val\n    cells = {}\n\n    contours = skimage.measure.find_contours(wildfire.data[layer], threshold)\n\n    for contour in contours:\n        try:\n            rr, cc = skimage.draw.polygon_perimeter(contour[..., 0], contour[..., 1],\n                                                    shape=wildfire.data.shape, clip=True)\n            # Set perimeter in array format\n            array[rr, cc] = wildfire.data[layer][rr, cc]\n            # Set perimeter in dict format\n            for r, c in zip(rr, cc):\n                cells[r, c] = wildfire.data[layer][r, c]\n        except IndexError as e:\n            pass # Ignore contour if it contains NaN (polygon_perimeter throws IndexError)\n\n\n    # for contour in contours:\n    #     prev_edge = contour[0]\n    #     for edge in contour[1:]:\n    #         if np.isnan(prev_edge).any() or np.isnan(edge).any():\n    #             continue\n    #         rr, cc = skimage.draw.line(*np.asarray(prev_edge, dtype=int),\n    #                                    *np.asarray(edge, dtype=int))\n    #         # Set perimeter in array format\n    #         array[rr, cc] = wildfire.data[layer][rr, cc]\n    #         # Set perimeter in dict format\n    #         for r, c in zip(rr, cc):\n    #             cells[r, c] = wildfire.data[layer][r, c]\n    #\n    #         prev_edge = edge\n\n    return array, cells, contours\n\n\ndef interpolate(x, y, z, shape, function='thin_plate') -> np.ndarray:\n    \"\"\"RBF interpolation\"\"\"\n    # Wildland fire modeling with an Eulerian level set method and automated calibration\n    # might give a clue of which kind of kernel function to use\n\n    # default smooth=0 for interpolation\n    interpolator = fire_rs.rbf.Rbf(x, y, z, function=function, smooth=0, cond=10 ** -5)\n\n    xi = np.linspace(0, shape[0] - 1, shape[0])\n    yi = np.linspace(0, shape[1] - 1, shape[1])\n    meshgrid = np.meshgrid(xi, yi, indexing=\"ij\")\n\n    dense_array = interpolator(*[x.flatten() for x in meshgrid])\n\n    return dense_array.reshape(shape[0], shape[1])\n\n\ndef rate_of_spread_map(firemap: fire_rs.geodata.geo_data.GeoData, layer=\"ignition\",\n                       output_layer=\"ros\") -> fire_rs.geodata.geo_data.GeoData:\n    \"\"\"Compute the Rate of Spread from a wildfire_map\"\"\"\n    gradient = firemap.clone(data_array=np.linalg.norm(np.gradient(firemap[layer]), axis=0),\n                             dtype=[(output_layer, 'float64')])\n    return gradient\n\n\nclass WildfireGraph:\n    \"\"\"Computation of the propagation graph and end of ignition from a wildfire map\"\"\"\n    IGNITION_END = 'ignition_end'\n    PROP_X = 'prop_x'\n    PROP_Y = 'prop_y'\n    PROP_DIR = 'prop_dir'\n\n    def __init__(self, firemap: fire_rs.geodata.geo_data.GeoData, ignition_layer: str = 'ignition',\n                 ignition_end_layer: str = IGNITION_END, prop_x_layer: str = PROP_X,\n                 prop_y_layer: str = PROP_Y, prop_dir_layer: str = PROP_DIR):\n        self._ignition_layer = ignition_layer\n        self._ignition_end_layer = ignition_end_layer\n        self._prop_x_layer = prop_x_layer\n        self._prop_y_layer = prop_y_layer\n        self._prop_dir_layer = prop_dir_layer\n        self.geodata = firemap.clone(fill_value=0,\n                                     dtype=[(ignition_layer, 'float64'),\n                                            ('ignition_end', 'float64'),\n                                            ('prop_x', 'int8'),\n                                            ('prop_y', 'int8'),\n                                            ('prop_dir', 'float64')])\n        self.geodata.data[ignition_layer] = firemap.data[ignition_layer]\n        grad = np.gradient(self.geodata.data[ignition_layer])\n        self.geodata.data[prop_dir_layer] = np.arctan2(grad[1], grad[0])\n        self.geodata.data[prop_x_layer] = np.array(\n            np.round(np.cos(self.geodata.data[prop_dir_layer])), np.int)\n        self.geodata.data[prop_y_layer] = np.array(\n            np.round(np.sin(self.geodata.data[prop_dir_layer])), np.int)\n        self.geodata.data[ignition_end_layer] = WildfireGraph._compute_traversal_end(\n            self.geodata.data[ignition_layer])\n\n    @staticmethod\n    def _compute_propagation_direction(fire_array: np.array):\n        def default_ignition(x, y, dx, dy):\n            if x == 0 and dx < 0:\n                return fire_array[x, y]\n            if x + dx >= fire_array.shape[0]:\n                return fire_array[x, y]\n            if y == 0 and dy < 0:\n                return fire_array[x, y]\n            if y + dy >= fire_array.shape[1]:\n                return fire_array[x, y]\n            if fire_array[x + dx, y + dy] < np.inf:\n                return fire_array[x + dx, y + dy]\n            else:\n                return fire_array[x, y]\n\n        prop_delta_x = np.zeros_like(fire_array, np.int)\n        prop_delta_y = np.zeros_like(fire_array, np.int)\n        prop_dir = np.zeros_like(fire_array)\n\n        for x in range(0, fire_array.shape[0]):\n            for y in range(0, fire_array.shape[1]):\n                if fire_array[x, y] < np.inf:\n                    ign = lambda dx, dy: default_ignition(x, y, dx, dy)\n                    prop_delta_x[x, y] = ign(1, -1) + 2 * ign(1, 0) + ign(1, 1) - ign(-1,\n                                                                                      -1) - 2 * ign(\n                        -1, 0) - ign(-1, 1)\n                    prop_delta_y[x, y] = ign(1, 1) + 2 * ign(0, 1) + ign(-1, 1) - ign(1,\n                                                                                      -1) - 2 * ign(\n                        0, -1) - ign(-1, -1)\n                    prop_dir = np.arctan2(prop_delta_y[x, y], prop_delta_x[x, y])\n\n        return prop_delta_x, prop_delta_y, prop_dir\n\n    @staticmethod\n    def _compute_traversal_end(fire_array: np.ndarray):\n        \"\"\"Compute the ignition end time for each cell.\n\n        The ignition end time is the latest ignition time among all neighbor cells.\"\"\"\n        end = np.zeros_like(fire_array) * np.inf\n\n        for x in range(0, fire_array.shape[0]):\n            for y in range(0, fire_array.shape[1]):\n                if fire_array[x, y] < np.inf:\n                    max_neighbor = 0.0\n                    for dx in [-1, 0, 1]:\n                        for dy in [-1, 0, 1]:\n                            if (dx == 0 and dy == 0) or (x == 0 and dx < 0) or (\n                                    x + dx >= fire_array.shape[0]) or (y == 0 and dy < 0) or (\n                                    y + dy >= fire_array.shape[1]):\n                                continue\n                            if fire_array[x + dx, y + dy] < np.inf:\n                                max_neighbor = max(max_neighbor, fire_array[x + dx, y + dy])\n                    if max_neighbor <= fire_array[x, y]:\n                        # propagation_border\n                        end[x, y] = fire_array[x, y] + 180  # assume 3 minutes\n                    else:\n                        end[x, y] = max_neighbor\n                else:\n                    end[x, y] = fire_array[x, y]\n        return end\n\n    def find_parent_or_child_of_time(self, start_cell: fire_rs.geodata.geo_data.Cell, time: float):\n        \"\"\"Find an ignited cell at 'time' in the propagation graph starting from 'start_cell'\n\n        This function similar to the c++ planning 'project on firefront' algorithm.\n        \"\"\"\n\n        coord = start_cell\n        found = False\n        while not found:\n            if self.geodata.data[self._ignition_layer][coord] <= time and time < \\\n                    self.geodata.data[self._ignition_end_layer][coord]:\n                found = True\n            else:\n                uphill_cell = (coord[0] + self.geodata.data[self._prop_x_layer][coord],\n                               coord[1] + self.geodata.data[self._prop_y_layer][coord])\n                downhill_cell = (coord[0] - self.geodata.data[self._prop_x_layer][coord],\n                                 coord[1] - self.geodata.data[self._prop_y_layer][coord])\n                if uphill_cell[0] == downhill_cell[0] and uphill_cell[1] == downhill_cell[1]:\n                    # Extrema reached\n                    coord = uphill_cell\n                    found = True\n                next_cell = downhill_cell if self.geodata.data[self._ignition_layer][\n                                                 coord] > time else uphill_cell\n\n                if (next_cell[0] < 0 or next_cell[0] >\n                    self.geodata.data[self._ignition_layer].shape[0] - 1) and (\n                        next_cell[1] < 0 or next_cell[1] >\n                        self.geodata.data[self._ignition_layer].shape[1] - 1):\n                    found = True\n                if (next_cell == downhill_cell) and (\n                        self.geodata.data[self._ignition_layer][next_cell] >\n                        self.geodata.data[self._ignition_layer][coord]) or (\n                        next_cell == uphill_cell) and (\n                        self.geodata.data[self._ignition_layer][next_cell] <\n                        self.geodata.data[self._ignition_layer][coord]):\n                    # Extrema reached\n                    found = True\n                if self.geodata.data[self._ignition_layer][next_cell] < np.inf:\n                    coord = next_cell\n        return coord\n\n\ndef warp_firemap(gd: fire_rs.geodata.geo_data.GeoData, orig: ty.Sequence[ty.Tuple[int, int]],\n                 dest: ty.Sequence[ty.Tuple[int, int]],\n                 layer: str = \"ignition\"):\n    array = _warp_image(gd[layer], orig, dest)\n    new_gd = fire_rs.firemodel.propagation.empty_firemap(gd, layer=layer)\n    new_gd.data[\"ignition\"] = array\n    return new_gd\n\n\ndef _warp_image(array: np.ndarray, orig: ty.Sequence[ty.Tuple[int, int]],\n                dest: ty.Sequence[ty.Tuple[int, int]]) -> np.ndarray:\n    newarray = array.copy()\n    newarray = newarray.T  # opencv convention on columns and rows is inverted\n    newarray_min = newarray.min()\n    newarray_max = newarray.max()\n    newarray = (newarray - newarray_min) / (newarray_max - newarray_min)\n    orig_p = np.array(orig, np.int32)\n    orig_p = orig_p.reshape(1, -1, 2)  # Don't ask why. https://stackoverflow.com/a/47114049\n    dest_p = np.array(dest, np.int32)\n    dest_p = dest_p.reshape(1, -1, 2)  # Don't ask why. https://stackoverflow.com/a/47114049\n    good_matches = [cv2.DMatch(p, p, 0) for p in range(len(orig))]\n    tps = cv2.createThinPlateSplineShapeTransformer()\n    tps.estimateTransformation(dest_p, orig_p, good_matches)\n    warped = None\n    warped = tps.warpImage(newarray, warped, cv2.INTER_LINEAR, cv2.BORDER_CONSTANT, np.inf)\n    warped = warped * (newarray_max - newarray_min) + newarray_min\n    warped = warped.T\n    return warped\n", "meta": {"hexsha": "9f788fd06f698dcba093d450c0bfe7b2d1c41bf5", "size": 14606, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/fire_rs/geodata/wildfire.py", "max_stars_repo_name": "arthur-bit-monnot/fire-rs-saop", "max_stars_repo_head_hexsha": "321e16fceebf44e8e97b482c24f37fbf6dd7d162", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2018-11-19T15:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T11:24:21.000Z", "max_issues_repo_path": "python/fire_rs/geodata/wildfire.py", "max_issues_repo_name": "fire-rs-laas/fire-rs-saop", "max_issues_repo_head_hexsha": "321e16fceebf44e8e97b482c24f37fbf6dd7d162", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2017-10-12T16:19:19.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-12T12:07:56.000Z", "max_forks_repo_path": "python/fire_rs/geodata/wildfire.py", "max_forks_repo_name": "fire-rs-laas/fire-rs-saop", "max_forks_repo_head_hexsha": "321e16fceebf44e8e97b482c24f37fbf6dd7d162", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-03-12T12:28:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T18:32:17.000Z", "avg_line_length": 45.5015576324, "max_line_length": 100, "alphanum_fraction": 0.5804463919, "include": true, "reason": "import numpy", "num_tokens": 3443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.19770094964702586}}
{"text": "import calendar\nimport glob\nimport numpy as np\nimport openapi_client as dbitApi\nimport os\nimport pandas as pd\n\nfrom datetime import datetime\n\napi = dbitApi.MarketDataApi()\n\ndef format_datetime_to_expiry(date):\n    if os.name == 'nt':\n        return datetime.strftime(date, '%#d%b%y').upper()\n    else:\n        return datetime.strftime(date, '%-d%b%y').upper()\n\ndef get_near_next_terms(now):\n    c = calendar.Calendar(firstweekday=calendar.MONDAY)\n    \n    this_month_cal = c.monthdatescalendar(now.year, now.month)\n    this_fridays = [datetime(day.year, day.month, day.day, 8, 0, 0) \n                    for week in this_month_cal for day in week \n                    if day.weekday() == calendar.FRIDAY and day.month == now.month \n                    and datetime(day.year, day.month, day.day, 8, 0, 0) >= now]\n    \n    next_year = now.year if now.month < 12 else now.year + 1\n    next_month = now.month + 1 if now.month < 12 else 1\n    \n    next_month_cal = c.monthdatescalendar(next_year, next_month)\n    next_fridays = [datetime(day.year, day.month, day.day, 8, 0, 0) \n                    for week in next_month_cal for day in week \n                    if day.weekday() == calendar.FRIDAY and day.month == next_month \n                    and datetime(day.year, day.month, day.day, 8, 0, 0) >= now]\n    \n    fridays = this_fridays + next_fridays\n    \n    near_term, next_term = fridays[0], fridays[1]\n        \n    return (format_datetime_to_expiry(near_term), format_datetime_to_expiry(next_term), near_term, next_term)\n\ndef get_index(currency='BTC'):\n    try:\n        index_result = api.public_get_index_get(currency)['result'][currency]\n        return index_result\n    except dbitApi.exceptions.ApiException as e:\n        print(e)\n        #logger.exception('Exception when calling MarketDataApi->public_get_instruments_get!')\n        exit()\n\ndef get_instruments_with_expiry(expiry, currency='BTC', kind='option', expired='false'):\n    try:\n        instrument_result = api.public_get_instruments_get(currency, kind=kind, expired=expired)['result']\n        return [instrument['instrument_name'] for instrument in instrument_result if expiry in instrument['instrument_name']]\n    except dbitApi.exceptions.ApiException as e:\n        print(e)\n        #logger.exception('Exception when calling MarketDataApi->public_get_instruments_get!')\n        exit()\n\ndef get_ticker(instrument):\n    try:\n        instrument_result = api.public_ticker_get(instrument)['result']\n        return instrument_result\n    except dbitApi.exceptions.ApiException as e:\n        print(e)\n        #logger.exception('Exception when calling MarketDataApi->public_get_instruments_get!')\n        exit()\n\ndef get_bids_asks(near_list, next_list):\n    near_calls = dict()\n    near_puts = dict()\n    next_calls = dict()\n    next_puts = dict()\n\n    for instrument in near_list:\n        data = get_ticker(instrument)\n        best_bid, best_ask = data['best_bid_price'], data['best_ask_price']\n        strike, cp = int(instrument.split('-')[2]), instrument.split('-')[3]\n\n        if cp == 'C':\n            near_calls[strike] = {'best_bid': best_bid, 'best_ask': best_ask}\n        elif cp == 'P':\n            near_puts[strike] = {'best_bid': best_bid, 'best_ask': best_ask}\n        else:\n            print(f'Error {instrument}')\n\n    for instrument in next_list:\n        data = get_ticker(instrument)\n        best_bid, best_ask = data['best_bid_price'], data['best_ask_price']\n        strike, cp = int(instrument.split('-')[2]), instrument.split('-')[3]\n\n        if cp == 'C':\n            next_calls[strike] = {'best_bid': best_bid, 'best_ask': best_ask}\n        elif cp == 'P':\n            next_puts[strike] = {'best_bid': best_bid, 'best_ask': best_ask}\n        else:\n            print(f'Error {instrument}')\n\n    near_calls_df = pd.DataFrame.from_dict(near_calls, orient='index').sort_index().replace(0, np.nan)\n    near_puts_df = pd.DataFrame.from_dict(near_puts, orient='index').sort_index().replace(0, np.nan)\n    next_calls_df = pd.DataFrame.from_dict(next_calls, orient='index').sort_index().replace(0, np.nan)\n    next_puts_df = pd.DataFrame.from_dict(next_puts, orient='index').sort_index().replace(0, np.nan)\n\n    return near_calls_df, near_puts_df, next_calls_df, next_puts_df\n\ndef calculate_indices(time, near_datetime, next_datetime, const_mature_days, R, near_calls_df, near_puts_df, next_calls_df, next_puts_df):\n    # Compute strikes with min call/put price difference\n    near_prices = pd.DataFrame(index=near_calls_df.index)\n    near_prices['call_price'] = (near_calls_df['best_bid'] + near_calls_df['best_ask']) / 2\n    near_prices['put_price'] = (near_puts_df['best_bid'] + near_puts_df['best_ask']) / 2\n    near_prices['abs_diff'] = abs(near_prices['call_price'] - near_prices['put_price'])\n\n    min_near_strike = near_prices['abs_diff'].idxmin()\n    min_near_diff = near_prices.loc[min_near_strike].abs_diff\n\n    next_prices = pd.DataFrame(index=next_calls_df.index)\n    next_prices['call_price'] = (next_calls_df['best_bid'] + next_calls_df['best_ask']) / 2\n    next_prices['put_price'] = (next_puts_df['best_bid'] + next_puts_df['best_ask']) / 2\n    next_prices['abs_diff'] = abs(next_prices['call_price'] - next_prices['put_price'])\n\n    min_next_strike = next_prices['abs_diff'].idxmin()\n    min_next_diff = next_prices.loc[min_next_strike].abs_diff\n\n    n1 = (near_datetime - time).total_seconds() / 60\n    n2 = (next_datetime - time).total_seconds() / 60\n    nY = 525600\n    n = const_mature_days * 24 * 60\n\n    t1 = n1/nY\n    t2 = n2/nY\n\n    # Compute forward prices and at-the-money strikes\n    f1 = min_near_strike + np.e**(R*t1) * min_near_diff\n    k0_1 = max([strike for strike in near_prices.index if strike <= min_near_strike])\n\n    f2 = min_next_strike + np.e**(R*t2) * min_next_diff\n    k0_2 = max([strike for strike in next_prices.index if strike <= min_next_strike])\n\n    near_otm_puts_df = near_puts_df.loc[:k0_1].iloc[:-1]\n    near_otm_calls_df = near_calls_df.loc[k0_1:].iloc[1:]\n    next_otm_puts_df = next_puts_df.loc[:k0_2].iloc[:-1]\n    next_otm_calls_df = next_calls_df.loc[k0_2:].iloc[1:]\n\n    near_otm_puts_df = near_otm_puts_df.sort_index(ascending=False)\n    near_otm_puts_df = near_otm_puts_df.assign(zero_bid=lambda df: (df['best_bid'] == 0).astype(int))\n    near_otm_puts_df['zero_bid_cumsum'] = near_otm_puts_df['zero_bid'].cumsum()\n    near_otm_puts_df = near_otm_puts_df[(near_otm_puts_df['zero_bid_cumsum'] <= 2) & (near_otm_puts_df['best_bid'] > 0)]\n    \n    near_otm_calls_df = near_otm_calls_df.assign(zero_bid=lambda df: (df['best_bid'] == 0).astype(int))\n    near_otm_calls_df['zero_bid_cumsum'] = near_otm_calls_df['zero_bid'].cumsum()\n    near_otm_calls_df = near_otm_calls_df[(near_otm_calls_df['zero_bid_cumsum'] <= 2) & (near_otm_calls_df['best_bid'] > 0)]\n\n    next_otm_puts_df = next_otm_puts_df.sort_index(ascending=False)\n    next_otm_puts_df = next_otm_puts_df.assign(zero_bid=lambda df: (df['best_bid'] == 0).astype(int))\n    next_otm_puts_df['zero_bid_cumsum'] = next_otm_puts_df['zero_bid'].cumsum()\n    next_otm_puts_df = next_otm_puts_df[(next_otm_puts_df['zero_bid_cumsum'] <= 2) & (next_otm_puts_df['best_bid'] > 0)]\n\n    next_otm_calls_df = next_otm_calls_df.assign(zero_bid=lambda df: (df['best_bid'] == 0).astype(int))\n    next_otm_calls_df['zero_bid_cumsum'] = next_otm_calls_df['zero_bid'].cumsum()\n    next_otm_calls_df = next_otm_calls_df[(next_otm_calls_df['zero_bid_cumsum'] <= 2) & (next_otm_calls_df['best_bid'] > 0)]\n\n    near_calc_strikes_df = pd.DataFrame(index=near_prices.index)\n    near_calc_strikes_df['price'] = (near_otm_puts_df['best_bid'] + near_otm_puts_df['best_ask']) / 2\n    near_calc_strikes_df['price'] = near_calc_strikes_df.price.combine_first((near_otm_calls_df['best_bid'] + near_otm_calls_df['best_ask']) / 2)\n    near_calc_strikes_df.at[k0_1] = (near_prices.loc[k0_1].call_price + near_prices.loc[k0_1].put_price) / 2\n    near_calc_strikes_df = near_calc_strikes_df.dropna()\n\n    next_calc_strikes_df = pd.DataFrame(index=next_prices.index)\n    next_calc_strikes_df['price'] = (next_otm_puts_df['best_bid'] + next_otm_puts_df['best_ask']) / 2\n    next_calc_strikes_df['price'] = next_calc_strikes_df.price.combine_first((next_otm_calls_df['best_bid'] + next_otm_calls_df['best_ask']) / 2)\n    next_calc_strikes_df.at[k0_2] = (next_prices.loc[k0_2].call_price + next_prices.loc[k0_2].put_price) / 2\n    next_calc_strikes_df = next_calc_strikes_df.dropna()\n\n    near_sum = 0\n    for i in range(len(near_calc_strikes_df)):\n        row = near_calc_strikes_df.iloc[i]\n        if i == 0:\n            deltaKi = near_calc_strikes_df.iloc[i+1].name - row.name\n        elif i == len(near_calc_strikes_df) - 1:\n            deltaKi = row.name - near_calc_strikes_df.iloc[i-1].name\n        else:\n            deltaKi = (near_calc_strikes_df.iloc[i+1].name - near_calc_strikes_df.iloc[i-1].name) / 2\n\n        near_sum += deltaKi/(row.name ** 2) * np.e**(R*t1) * row.price\n        \n    next_sum = 0\n    for i in range(len(next_calc_strikes_df)):\n        row = next_calc_strikes_df.iloc[i]\n        if i == 0:\n            deltaKi = next_calc_strikes_df.iloc[i+1].name - row.name\n        elif i == len(next_calc_strikes_df) - 1:\n            deltaKi = row.name - next_calc_strikes_df.iloc[i-1].name\n        else:\n            deltaKi = (next_calc_strikes_df.iloc[i+1].name - next_calc_strikes_df.iloc[i-1].name) / 2\n        \n        next_sum += deltaKi/(row.name ** 2) * np.e**(R*t2) * row.price\n        \n    sigma1 = ((2/t1) * near_sum) - (1/t1)*((f1/k0_1 - 1)**2)\n    sigma2 = ((2/t2) * next_sum) - (1/t2)*((f2/k0_2 - 1)**2)\n\n    VXBT = 100 * np.sqrt(((t1*sigma1)*((n2-n)/(n2-n1)) + (t2*sigma2)*((n-n1)/(n2-n1)))*(nY/n))\n\n    omega = ((n2-nY)/(n2-n1))*n\n    sigma1_a = sigma1 * (f1**-2)\n    sigma2_a = sigma2 * (f2**-2)\n\n    GVXBT = np.sqrt(omega*t1*sigma1 + (1-omega)*t2*sigma2)\n    AVXBT = np.sqrt(omega*t1*sigma1_a + (1-omega)*t2*sigma2_a)\n    \n    return VXBT, GVXBT, AVXBT\n\ndef get_indices(maturity=7, rate=0, live=True, time=None, dfs=None):\n    if live:\n        now = datetime.now()\n        near_expiry, next_expiry, near_datetime, next_datetime = get_near_next_terms(now)\n        near_instruments = get_instruments_with_expiry(near_expiry)\n        next_instruments = get_instruments_with_expiry(next_expiry)\n\n        near_calls_df, near_puts_df, next_calls_df, next_puts_df = get_bids_asks(near_instruments, next_instruments)\n        \n        VXBT, GVXBT, AVXBT = calculate_indices(now, near_datetime, next_datetime, maturity, rate, near_calls_df, near_puts_df, next_calls_df, next_puts_df)\n\n    else:\n        near_expiry, next_expiry, near_datetime, next_datetime = get_near_next_terms(time)\n        VXBT, GVXBT, AVXBT = calculate_indices(time, near_datetime, next_datetime, maturity, rate, dfs[0], dfs[1], dfs[2], dfs[3])\n    \n    return VXBT, GVXBT, AVXBT\n\n\nif __name__ == '__main__':\n    print(get_indices())", "meta": {"hexsha": "12cc2001208170d19e293e93e984e3fe3ee7d06b", "size": 10878, "ext": "py", "lang": "Python", "max_stars_repo_path": "vix-implementation/vxbt_calc/vxbt_calc.py", "max_stars_repo_name": "mewmix/bitfear", "max_stars_repo_head_hexsha": "8fb5263a0d0b53f2f5cd063ec6e5de30bb42e4e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-19T22:02:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-19T22:02:22.000Z", "max_issues_repo_path": "vix-implementation/vxbt_calc/vxbt_calc.py", "max_issues_repo_name": "mewmix/bitfear", "max_issues_repo_head_hexsha": "8fb5263a0d0b53f2f5cd063ec6e5de30bb42e4e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vix-implementation/vxbt_calc/vxbt_calc.py", "max_forks_repo_name": "mewmix/bitfear", "max_forks_repo_head_hexsha": "8fb5263a0d0b53f2f5cd063ec6e5de30bb42e4e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.0909090909, "max_line_length": 155, "alphanum_fraction": 0.6817429675, "include": true, "reason": "import numpy", "num_tokens": 3081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.1977009496470258}}
{"text": "#!/usr/bin/env python3\n\nimport os\nimport re\nimport time\n\nimport click\nfrom netCDF4 import Dataset\nimport numpy as np\nimport numpy.ma as ma\nimport osr\n\nimport projections.geotools as geotools\nimport projections.utils as utils\n\nBINS = 52\n\ndef sum_layers(ds, idx, layers, out):\n  out.fill(0)\n  for l in layers:\n    out += ds.variables[l][idx]\n  return\n\ndef find_frac(values, tot, frac):\n  frac.fill(1)\n  ## FIXME: need np.clip() because pos - neg < 0\n  frac -= np.clip(ma.where(values[-1] > 0, tot / values[-1], 0), 0, 1)\n  #frac -= np.clip(tot / values[-1], 0, 1)\n  return\n\ndef dorem(values, remove, frac):\n  find_frac(values, remove, frac)\n  values[1:-1] *= np.broadcast_to(frac, values[1:-1].shape)\n  return\n\ndef to_year(scenario, idx):\n  if scenario == 'historical':\n    return idx + 850\n  return idx + 2015\n\ndef asserts(state, idx, name, values, atol):\n  assert np.all(values[0] <= 1.0 + atol), 'current > 1'\n  assert np.all(values[0] >= 0.0 - atol), 'current < 0'\n  secd = state.variables[name][idx]\n  assert np.allclose(values[-1] - secd, 0, atol=atol)\n\ndef write_data(out, fnf, idx, values):\n  out.variables['secdy%s' % fnf][idx, :, :] = values[0:30].sum(axis=0)\n  out.variables['secdi%s' % fnf][idx, :, :] = values[30:50].sum(axis=0)\n  out.variables['secdm%s' % fnf][idx, :, :] = values[50]\n\ndef write_bins(out, vname, values):\n  # FIXME: verify masked values are written and read correctly.\n  out.variables[vname][:] = values\n  return values\n\ndef init_values(state, vname, start_index, mask):\n  shape = state.variables[vname].shape\n  values = ma.zeros((BINS, shape[1], shape[2]),\n                    dtype=state.variables[vname].dtype,\n                    fill_value=-9999)\n  values.mask = np.broadcast_to(mask == 1.0, values.shape)\n  values[-1] = state.variables[vname][start_index]\n  values[-2] = state.variables[vname][start_index]\n  return values\n\ndef roll_values(values):\n  values[-3] += values[-2]\n  values[-2] = values[0:-2].sum(axis=0)\n  return np.roll(values, 1, 0)\n\ndef neg_re(fnf):\n  return r'secd{fnf}_to_'.format(fnf=fnf)\n\ndef pos_re(fnf):\n  return r'^(?!secd{fnf}).*_to_secd{fnf}$|prim{fnf}_harv$'.format(fnf=fnf)\n\n@click.command()\n@click.option('--scenario', type=click.Choice(utils.luh2_scenarios() +\n                                              ('all', )),\n              default='all',\n              help='Which LUH2 scenario to run (default: all)')\n@click.option('--outdir', type=click.Path(file_okay=False),\n              default='/out/luh2',\n              help='Output directory (default: /out/luh2)')\n@click.option('--start-index', type=int, default=0,\n              help='Start from given index skipping earlier years (default: 0)')\ndef doit(scenario, outdir, start_index=0):\n  static = Dataset(os.path.join(utils.luh2_dir(), 'staticData_quarterdeg.nc'))\n  icwtr = static.variables['icwtr'][:, :]\n  atol = 5e-5\n\n  variables = tuple([(x % fnf, 'f4', '1', -9999, 'time')\n                     for fnf in ('f', 'n')\n                     for x in ('secd%s%%s' % n for n in ('y', 'i', 'm'))] +\n                    [('bins%s' % fnf, 'f4', '1', -9999, 'bins')\n                     for fnf in ('f', 'n')])\n  baselinef = None\n  baselinen = None\n\n  if scenario == 'all':\n    # historical must be the first scenario processed\n    scenarios = sorted(utils.luh2_scenarios())\n  else:\n    scenarios = [scenario]\n\n  for scenario in scenarios:\n    oname = os.path.join(outdir, 'secd-%s.nc' % scenario)\n    tname = utils.luh2_transitions(scenario)\n    sname = utils.luh2_states(scenario)\n    if not (os.path.isfile(tname) and os.path.isfile(sname)):\n      click.echo(\"skipping %s\" % scenario)\n      continue\n    click.echo('%s -> %s' % (scenario, oname))\n\n    with Dataset(oname, 'w') as out:\n      click.echo(sname)\n      click.echo(tname)\n      with Dataset(tname) as trans:\n        with Dataset(sname) as state:\n          _ = init_nc(out, state, variables)\n          if scenario == 'historical':\n            # Create a 3-D array to hold the last 50 years (plus 2)\n            valuesf = init_values(state, 'secdf', start_index, icwtr)\n            valuesn = init_values(state, 'secdn', start_index, icwtr)\n          elif baselinef is None or baselinen is None:\n            with Dataset(os.path.join(outdir, 'secd-historical.nc')) as hist:\n              valuesf = hist.variables['binsf'][:]\n              valuesn = hist.variables['binsn'][:]\n          else:\n            valuesf = baselinef.copy()\n            valuesn = baselinen.copy()\n\n          # Write initial data to output.\n          valuesf[0].fill(0)\n          valuesn[0].fill(0)\n          write_data(out, 'f', start_index, valuesf)\n          write_data(out, 'n', start_index, valuesn)\n\n          remove = ma.empty_like(valuesf[0])\n          frac = ma.empty_like(valuesf[0])\n          posf = tuple(filter(lambda x: re.match(pos_re('f'), x),\n                              trans.variables.keys()))\n          posn = tuple(filter(lambda x: re.match(pos_re('n'), x),\n                              trans.variables.keys()))\n          negf = tuple(filter(lambda x: re.match(neg_re('f'), x),\n                              trans.variables.keys()))\n          negn = tuple(filter(lambda x: re.match(neg_re('n'), x),\n                              trans.variables.keys()))\n          click.echo(\"  \" + ', '.join(posf))\n          click.echo(\"  \" + ', '.join(negf))\n          click.echo(\"  \" + ', '.join(posn))\n          click.echo(\"  \" + ', '.join(negn))\n          for idx in range(start_index, trans.variables['time'].shape[0]):\n            click.echo(\"  year %d\" % to_year(scenario, idx))\n            # Compute transitions from / to secondary.\n            sum_layers(trans, idx, negf, remove)\n            sum_layers(trans, idx, posf, valuesf[0])\n            # Adjust secondary history\n            dorem(valuesf, remove, frac)\n\n            # Repeat for non-forested\n            sum_layers(trans, idx, negn, remove)\n            sum_layers(trans, idx, posn, valuesn[0])\n            dorem(valuesn, remove, frac)\n\n            # Check consistency of data.\n            asserts(state, idx, 'secdf', valuesf, atol)\n            asserts(state, idx, 'secdn', valuesn, atol)\n\n            # Write data to output.\n            write_data(out, 'f', idx + 1, valuesf)\n            write_data(out, 'n', idx + 1, valuesn)\n\n            # Rotate the array.\n            valuesf = roll_values(valuesf)\n            valuesn = roll_values(valuesn)\n\n      if scenario == 'historical':\n        baselinef = write_bins(out, 'binsf', valuesf).copy()\n        baselinen = write_bins(out, 'binsn', valuesn).copy()\n        start_index = 0\n\ndef init_nc(dst_ds, src_ds, variables):\n  # Set attributes\n  dst_ds.setncattr('Conventions', u'CF-1.5')\n  dst_ds.setncattr('GDAL', u'GDAL 1.11.3, released 2015/09/16')\n\n  # Create dimensions\n  dst_ds.createDimension('time', None)\n  dst_ds.createDimension('lat', len(src_ds.variables['lat']))\n  dst_ds.createDimension('lon', len(src_ds.variables['lon']))\n  dst_ds.createDimension('bins', BINS)\n\n  # Create variables\n  times = dst_ds.createVariable(\"time\", \"f8\", (\"time\"), zlib=True,\n                                least_significant_digit=3)\n  latitudes = dst_ds.createVariable(\"lat\", \"f4\", (\"lat\"), zlib=True,\n                                    least_significant_digit=3)\n  longitudes = dst_ds.createVariable(\"lon\", \"f4\", (\"lon\"), zlib=True,\n                                     least_significant_digit=3)\n  crs = dst_ds.createVariable('crs', \"S1\", ())\n\n  # Add metadata\n  dst_ds.history = \"Created at \" + time.ctime(time.time())\n  dst_ds.source = \"secd-dist.py\"\n  latitudes.units = \"degrees_north\"\n  latitudes.long_name = 'latitude'\n  longitudes.units = \"degrees_east\"\n  longitudes.long_name = \"longitude\"\n  times.units = \"years since 850-01-01 00:00:00.0\"\n  times.calendar = \"gregorian\"\n  times.standard_name = \"time\"\n  times.axis = 'T'\n\n  # Assign data to variables\n  latitudes[:] = src_ds.variables['lat'][:]\n  longitudes[:] = src_ds.variables['lon'][:]\n  times[:] = src_ds.variables['time'][:]\n\n  srs = osr.SpatialReference()\n  srs.ImportFromWkt(geotools.WGS84_WKT)\n  src_trans = (-180.0, 0.25, 0.0, 90.0, 0.0, -0.25)\n  crs.grid_mapping_name = 'latitude_longitude'\n  crs.spatial_ref = srs.ExportToWkt()\n  crs.GetTransform = ' '.join(tuple(map(str, src_trans)))\n  # FIXME: Attribute getters don't work in python3 or GDAL2\n  crs.longitude_of_prime_meridian = geotools.srs_get_prime_meridian(srs)\n  crs.semi_major_axis = geotools.srs_get_semi_major(srs)\n  crs.inverse_flattening = geotools.srs_get_inv_flattening(srs)\n\n  out = {}\n  for name, dtype, units, fill, dimension in variables:\n    dst_data = dst_ds.createVariable(name, dtype,\n                                     (dimension, \"lat\", \"lon\"), zlib=True,\n                                     least_significant_digit=4,\n                                     fill_value=fill)\n    dst_data.units = units\n    dst_data.grid_mapping = 'crs'\n    out[name] = dst_data\n  return out\n\nif __name__ == '__main__':\n#pylint: disable-msg=no-value-for-parameter\n  doit()\n#pylint: enable-msg=no-value-for-parameter\n  click.echo('done')\n", "meta": {"hexsha": "afb52387d7853a320b7c4f22b7c5ca69c14f40d4", "size": 9033, "ext": "py", "lang": "Python", "max_stars_repo_path": "secd-dist.py", "max_stars_repo_name": "ricardog/raster-project", "max_stars_repo_head_hexsha": "37d508ca329d31d4b1d21614371596f4c1bca526", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-02-23T14:26:17.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-23T14:26:17.000Z", "max_issues_repo_path": "secd-dist.py", "max_issues_repo_name": "NaturalHistoryMuseum/raster-project", "max_issues_repo_head_hexsha": "319a0f633de8cf2317eba5d82396036f01ce5262", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "secd-dist.py", "max_forks_repo_name": "NaturalHistoryMuseum/raster-project", "max_forks_repo_head_hexsha": "319a0f633de8cf2317eba5d82396036f01ce5262", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-10-11T15:49:18.000Z", "max_forks_repo_forks_event_max_datetime": "2017-10-11T15:49:18.000Z", "avg_line_length": 36.4233870968, "max_line_length": 80, "alphanum_fraction": 0.5990257943, "include": true, "reason": "import numpy", "num_tokens": 2500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.19770094964702578}}
{"text": "# This module needs: numpy, matplotlib, scipy, ase, spglib\nimport numpy\nfrom futile.Utils import write as safe_print\n\nAU_eV = 27.21138386\n\n\ndef get_ev(ev, keys=None, ikpt=1):\n    \"\"\"Get the correct list of the energies for this eigenvalue.\"\"\"\n    res = False\n    if keys is None:\n        ener = ev.get('e')\n        spin = ev.get('s')\n        kpt = ev.get('k')\n        if not kpt and ikpt == 1:\n            kpt = True\n        elif kpt and kpt != ikpt:\n            kpt = False\n        if ener and (spin == 1 or not spin):\n            if kpt:\n                res = [ener]\n        elif ener and spin == -1:\n            if kpt:\n                res = [None, ener]\n    else:\n        for k in keys:\n            if k in ev:\n                res = ev[k]\n                if not isinstance(res, list):  # type(res) != type([]):\n                    res = [res]\n                break\n    return res\n\n\ndef astruct_to_cell(astruct):\n    \"\"\"\n    Convert the astruct information as parsed from the module Logfiles into\n    the cell structure as needed from spglib\n    \"\"\"\n    import numpy\n    celltmp = [a if a != float('inf') else 1.0 for a in astruct['cell']]\n    lattice = numpy.diag(celltmp)\n    pos = [[a/b if b != float('inf') else 0.0\n            for a, b in zip(list(at.values())[0], celltmp)]\n           for at in astruct['positions']]\n    atoms = [list(at.keys())[0] for at in astruct['positions']]\n    ianames, iatype = numpy.unique(atoms, return_inverse=True)\n    return (lattice, pos, iatype)\n\n\nclass BandArray(numpy.ndarray):\n    \"\"\"\n    Defines the array of data for one band. It is a dictionary which contains\n    a numpy array for both spin channels.\n    \"\"\"\n    def __new__(cls, *args, **kwargs):  # logdata,ikpt=0,kpt=(0.0,0.0,0.0):\n        \"Takes the data from the logfile and convert it\"\n        datain = kwargs.get(\"data\", None)\n        if datain is not None:\n            evs = datain\n            shape0 = len(evs)\n            norbs = list(map(len, evs))\n            if len(norbs) == 1:\n                norbs = [norbs[0], 0]\n        else:\n            evs = [[], []]\n            logdata = kwargs.get(\"logdata\", args[0])\n            ikpt = kwargs.get(\"ikpt\", 1 if len(args) < 2 else args[1])\n            # Ugly patch to detect proper k point in Davidson...\n            prev_vrt = True\n            cur_ikpt = 0\n            # End of ugly patch\n            for ev in logdata:\n                occ = get_ev(ev, ['e_occ', 'e_occupied'], ikpt=ikpt)\n                vrt = get_ev(ev, ['e_vrt', 'e_virt'], ikpt=ikpt)\n                eigen = occ or vrt\n                # Ugly patch to detect proper k point in Davidson...\n                if occ and prev_vrt:\n                    cur_ikpt += 1\n                prev_vrt = vrt\n                if eigen and cur_ikpt != ikpt:\n                    continue\n                # End of ugly patch\n                if not eigen:\n                    eigen = get_ev(ev, ikpt=ikpt)\n                if not eigen:\n                    continue\n                for i, e in enumerate(eigen):\n                    if e:\n                        evs[i].append(e)\n            shape0 = 2 if len(evs[1]) > 0 else 1\n            norbs = list(map(len, evs))\n        data = numpy.ndarray.__new__(cls, shape=(shape0, max(norbs)),\n                                     dtype=numpy.float)\n        data.fill(numpy.nan)\n        data[0, :len(evs[0])] = evs[0]\n        if norbs[1] > 0:\n            data[1, :len(evs[1])] = evs[1]\n        data.info = norbs  # (map(len,evs))\n        return data\n\n    def __init__(self, *args, **kwargs):\n        ikpt = kwargs.get(\"ikpt\", 1 if len(args) < 2 else args[1])\n        kpt = kwargs.get(\"kpt\", (0., 0., 0.) if len(args) < 3 else args[2])\n        kwgt = kwargs.get('kwgt', 1.0)\n        self.set_kpt(ikpt, kpt, kwgt)\n\n    def set_kpt(self, ikpt, kpt, kwgt=1.0):\n        if not isinstance(ikpt, int):\n            raise TypeError('ikpt should be a integer')\n        if len(kpt) != 3:\n            raise TypeError('kpt should be a object of len 3')\n        self.ikpt = ikpt\n        self.kpt = kpt\n        self.kwgt = kwgt\n\n    def __add__(self, b):\n        if hasattr(b, 'kpt') and (b.kpt != self.kpt):\n            raise ValueError('cannot sum BandArray with different kpoints')\n        if hasattr(b, 'kwgt') and (b.kwgt != self.kwgt):\n            raise ValueError('cannot sum BandArray with different kweights')\n        c = super(type(self), self).__add__(b)\n        return BandArray(data=c, ikpt=self.ikpt, kpt=self.kpt, kwgt=self.kwgt)\n\n\nclass BZPath():\n    \"\"\"\n    Defines a set of points which are associated to a path in the reduced\n    Brillouin Zone.\n    \"\"\"\n\n    def __init__(self, lattice, path, special_points, npts=50):\n        import ase.dft.kpoints as ase\n        self.special_points = special_points\n        path_tmp = []\n        self.symbols = []\n        # construct the path\n        for p in path:\n            if isinstance(p, str):\n                # then this is a special point\n                path_tmp.append(self.special_points[p])\n                self.symbols.append(p.replace('G', '$\\\\Gamma$'))\n            else:\n                path_tmp.append(list(p.values())[0])\n                self.symbols.append(list(p.keys())[0])\n        self.path, self.xaxis, self.xlabel = ase.get_bandpath(\n            path_tmp, lattice, npts)\n\n\nclass BrillouinZone():\n    def __init__(self, astruct, mesh, evals, fermi_energy):\n        import spglib\n        import numpy\n        cell = astruct_to_cell(astruct)\n        self.lattice = cell[0]\n        # celltmp=[ a if a!=float('inf') else 1.0 for a in astruct['cell']]\n        # self.lattice=numpy.diag(celltmp)\n        # print 'lattice',self.lattice\n        # pos=[[ a/b if b!=float('inf') else 0.0\n        #        for a,b in zip(at.values()[0], celltmp)]\n        #      for at in astruct['positions']]\n        # atoms=[ at.keys()[0] for at in astruct['positions']]\n        # ianames,iatype=numpy.unique(atoms,return_inverse=True) #[1,]*4+[2,]*4\n        # we should write a function for the iatype\n        # print 'iatype', iatype\n        # cell=(self.lattice,pos,iatype)\n        safe_print('spacegroup', spglib.get_spacegroup(cell, symprec=1e-5))\n        # then define the pathes and special points\n        import ase.dft.kpoints as ase\n        # we should adapt the 'cubic'\n        cell_tmp = astruct['cell']\n        # print 'cell',\n        #        cell_tmp,numpy.allclose(cell_tmp,[cell_tmp[0],]*len(cell_tmp))\n        if numpy.allclose(cell_tmp, [cell_tmp[0], ]*len(cell_tmp)):\n            lattice_string = 'cubic'\n        else:\n            lattice_string = 'orthorhombic'\n        safe_print('Lattice found:', lattice_string)\n        self.special_points = ase.get_special_points(\n            lattice_string, self.lattice, eps=0.0001)\n        self.special_paths = ase.parse_path_string(\n            ase.special_paths[lattice_string])\n        self.fermi_energy = fermi_energy\n        # dataset = spglib.get_symmetry_dataset(cell, symprec=1e-3)\n        # print dataset\n        # the shift has also to be put if present\n        mapping, grid = spglib.get_ir_reciprocal_mesh(\n            mesh, cell, is_shift=[0, 0, 0])\n        lookup = []\n        for ikpt in numpy.unique(mapping):\n            ltmp = []\n            for ind, (m, g) in enumerate(zip(mapping, grid)):\n                if m == ikpt:\n                    ltmp.append((g, ind))\n            lookup.append(ltmp)\n        safe_print('irreductible k-points', len(lookup))\n        # print 'mapping',mapping\n        # print 'grid',len(grid),numpy.max(grid)\n        coords = numpy.array(grid, dtype=numpy.float)/mesh\n        # print 'coords',coords\n        # print 'shape',coords.shape\n        # print grid #[ x+mesh[0]*y+mesh[0]*mesh[1]*z for x,y,z in grid]\n        # brillouin zone\n        kp = numpy.array([k.kpt for k in evals])\n        ourkpt = numpy.rint(kp*(numpy.array(mesh))).astype(int)\n        # print ourkpt\n        bz = numpy.ndarray((coords.shape[0], evals[0].size), dtype=float)\n        # print bz\n        # shift = (numpy.array(mesh)-1)/2\n        # print 'shift',shift\n        for ik in lookup:\n            irrk = None\n            for orbs, bzk in zip(evals, ourkpt):\n                for (kt, ind) in ik:\n                    if (bzk == kt).all():\n                        irrk = orbs\n                        # print 'hello',orbs.kpt,kt\n                        break\n                if irrk is not None:\n                    break\n            if irrk is None:\n                safe_print('error in ik', ik)\n                safe_print('our', ourkpt)\n                safe_print('spglib', grid)\n                safe_print('mapping', mapping)\n            for (kt, ind) in ik:\n                # r=kt+shift\n                # ind=numpy.argwhere([(g==kt).all() for g in grid])\n                # print 'ik',kt,r,ind\n                # print irrk.shape, bz.shape\n                # bz[r[0],r[1],r[2],:]=irrk.reshape(irrk.size)\n                bz[ind, :] = irrk.reshape(irrk.size)\n        # duplicate coordinates for the interpolation\n        bztmp = bz  # .reshape((mesh[0]*mesh[1]*mesh[2], -1))\n        # print bztmp\n        ndup = 7\n        duplicates = [[-1, 0, 0], [1, 0, 0], [0, -1, 0],\n                      [0, 1, 0], [0, 0, -1], [0, 0, 1]]\n        bztot = numpy.ndarray((ndup, bztmp.shape[0], bztmp.shape[1]))\n        bztot[0, :, :] = bztmp\n        ctot = numpy.ndarray((ndup, coords.shape[0], coords.shape[1]))\n        ctot[0, :, :] = coords\n        for i, sh in enumerate(duplicates):\n            bztot[i+1, :, :] = bztmp\n            ctot[i+1, :, :] = coords+sh\n            # print 'coors',coords,coords+[1.0,0,0]\n        bztot = bztot.reshape((ndup*bztmp.shape[0], -1))\n        ctot = ctot.reshape((ndup*coords.shape[0], -1))\n        import scipy.interpolate.interpnd as interpnd\n        self.interpolator = interpnd.LinearNDInterpolator(ctot, bztot)\n        # sanity check of the interpolation\n        sanity = 0.0\n        for kpt in evals:\n            diff = numpy.ravel(numpy.ravel(\n                kpt)-numpy.ravel(self.interpolator([kpt.kpt])))\n            sanity = max(sanity, numpy.dot(diff, diff))\n        print('Interpolation bias', sanity)\n\n    def conversion_factor(self, units):\n        if units == 'AU':\n            fac = 1.0\n        elif units == 'eV':\n            fac = AU_eV\n        else:\n            raise ValueError('Unrecognized units ('+units+')')\n        return fac\n\n    def plot(self, path=None, npts=50, units='eV'):\n        if path is None:\n            # ppath=BZPath(self.lattice,self.special_paths[0]+['G',],self.special_points,npts)\n            ppath = BZPath(\n                self.lattice, self.special_paths[0], self.special_points, npts)\n        else:\n            ppath = path\n        toto = self.interpolator(ppath.path)\n        import matplotlib.pyplot as plt\n        # print toto.min(),toto.max()\n        for b in toto.transpose():\n            plt.plot(ppath.xaxis, [ib * self.conversion_factor(units)\n                                   for ib in b])  # , 'b-')\n\n        plt.axhline(self.conversion_factor(units)*self.fermi_energy, color='k',\n                    linestyle='--')\n        for p in ppath.xlabel:\n            plt.axvline(p, color='k', linestyle='-')\n            plt.xticks(ppath.xlabel, ppath.symbols)\n\n        # if units == 'eV':\n        #    plt.ylabel('Energy [eV]', fontsize=18)\n        # else:\n        #    plt.ylabel('Energy [Ha]', fontsize=18)\n\n        plt.show()\n", "meta": {"hexsha": "6892b3675564e36b4a7b688ad04012296d8ce58c", "size": 11367, "ext": "py", "lang": "Python", "max_stars_repo_path": "aiida_bigdft/PyBigDFT/BigDFT/BZ.py", "max_stars_repo_name": "adegomme/aiida-bigdft-plugin", "max_stars_repo_head_hexsha": "dfd17f166a8cd547d3e581c7c3c9f4eb32bd2aab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-10T02:45:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-05T18:55:05.000Z", "max_issues_repo_path": "aiida_bigdft/PyBigDFT/BigDFT/BZ.py", "max_issues_repo_name": "BigDFT-group/aiida-bigdft-plugin", "max_issues_repo_head_hexsha": "5a0091fde3784d699b1791a05d8ad4fa4bb3c1fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-12-15T19:35:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-07T15:32:18.000Z", "max_forks_repo_path": "aiida_bigdft/PyBigDFT/BigDFT/BZ.py", "max_forks_repo_name": "adegomme/aiida-bigdft-plugin", "max_forks_repo_head_hexsha": "dfd17f166a8cd547d3e581c7c3c9f4eb32bd2aab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-05T18:55:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-05T18:55:21.000Z", "avg_line_length": 38.6632653061, "max_line_length": 94, "alphanum_fraction": 0.5252925134, "include": true, "reason": "import numpy,import scipy", "num_tokens": 3073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.19761246859997844}}
{"text": "\"\"\"Code for BBPSSW entanglement purification.\n\nThis module defines code to support the BBPSSW protocol for entanglement purification.\nSuccess results are pre-determined based on network parameters.\nAlso defined is the message type used by the BBPSSW code.\n\"\"\"\n\nfrom enum import Enum, auto\nfrom typing import List, TYPE_CHECKING\nfrom functools import lru_cache\n\nfrom numpy.random import random\n\nif TYPE_CHECKING:\n    from ..components.memory import Memory\n    from ..topology.node import Node\n\nfrom ..message import Message\nfrom .entanglement_protocol import EntanglementProtocol\nfrom ..utils import log\nfrom ..components.circuit import Circuit\n\n\nclass BBPSSWMsgType(Enum):\n    \"\"\"Defines possible message types for entanglement purification\"\"\"\n\n    PURIFICATION_RES = auto()\n\n\nclass BBPSSWMessage(Message):\n    \"\"\"Message used by entanglement purification protocols.\n\n    This message contains all information passed between purification protocol instances.\n\n    Attributes:\n        msg_type (BBPSSWMsgType): defines the message type.\n        receiver (str): name of destination protocol instance.\n    \"\"\"\n\n    def __init__(self, msg_type: BBPSSWMsgType, receiver: str, **kwargs):\n        Message.__init__(self, msg_type, receiver)\n        if self.msg_type is BBPSSWMsgType.PURIFICATION_RES:\n            self.meas_res = kwargs['meas_res']\n        else:\n            raise Exception(\"BBPSSW protocol create unknown type of message: %s\" % str(msg_type))\n\n\nclass BBPSSW(EntanglementProtocol):\n    \"\"\"Purification protocol instance.\n\n    This class provides an implementation of the BBPSSW purification protocol.\n    It should be instantiated on a quantum router node.\n\n    Variables:\n        BBPSSW.circuit (Circuit): circuit that purifies entangled memories.\n\n    Attributes:\n        own (QuantumRouter): node that protocol instance is attached to.\n        name (str): label for protocol instance.\n        kept_memo: memory to be purified by the protocol (should already be entangled).\n        meas_memo: memory to measure and discart (should already be entangled).\n        another (BBPSSW): pointer of BBPSSW on another side (may be removed in the future).\n        meas_res (int): measurement result from circuit.\n    \"\"\"\n\n    circuit = Circuit(2)\n    circuit.cx(0, 1)\n    circuit.measure(1)\n\n    def __init__(self, own: \"Node\", name: str, kept_memo: \"Memory\", meas_memo: \"Memory\"):\n        \"\"\"Constructor for purification protocol.\n\n        Args:\n            own (Node): node protocol is attached to.\n            name (str): name of protocol instance.\n            kept_memo (Memory): memory to have fidelity improved.\n            meas_memo (Memory): memory to measure and discard.\n        \"\"\"\n\n        assert kept_memo != meas_memo\n        EntanglementProtocol.__init__(self, own, name)\n        self.memories = [kept_memo, meas_memo]\n        self.kept_memo = kept_memo\n        self.meas_memo = meas_memo\n        self.another = None\n        self.meas_res = None\n        if self.meas_memo is None:\n            self.memories.pop()\n\n    def is_ready(self) -> bool:\n        return self.another is not None\n\n    def set_others(self, another: \"BBPSSW\") -> None:\n        \"\"\"Method to set other entanglement protocol instance.\n\n        Args:\n            another (BBPSSW): other purification protocol instance.\n        \"\"\"\n\n        self.another = another\n\n    def start(self) -> None:\n        \"\"\"Method to start entanglement purification.\n\n        Run the circuit below on two pairs of entangled memories on both sides of protocol.\n\n        o -------(x)----------| M |\n        .         |\n        .   o ----.----------------\n        .   .\n        .   .\n        .   o\n        .\n        o\n\n        The overall circuit is shown below:\n\n         o -------(x)----------| M |\n         .         |\n         .   o ----.----------------\n         .   .\n         .   .\n         .   o ----.----------------\n         .         |\n         o -------(x)----------| M |\n\n        Side Effects:\n            May update parameters of kept memory.\n            Will send message to other protocol instance.\n        \"\"\"\n\n        log.logger.info(self.own.name + \" protocol start with partner {}\".format(self.another.own.name))\n\n        assert self.another is not None, \"other protocol is not set; please use set_others function to set it.\"\n        kept_memo_ent = self.kept_memo.entangled_memory[\"node_id\"]\n        meas_memo_ent = self.meas_memo.entangled_memory[\"node_id\"]\n        assert kept_memo_ent == meas_memo_ent, \"mismatch of entangled memories {}, {} on node {}\".format(kept_memo_ent, meas_memo_ent, self.own.name)\n        assert self.kept_memo.fidelity == self.meas_memo.fidelity > 0.5\n\n        self.meas_res = self.own.timeline.quantum_manager.run_circuit(self.circuit, [self.kept_memo.qstate_key,\n                                                                                     self.meas_memo.qstate_key])\n        self.meas_res = self.meas_res[self.meas_memo.qstate_key]\n        dst = self.kept_memo.entangled_memory[\"node_id\"]\n\n        message = BBPSSWMessage(BBPSSWMsgType.PURIFICATION_RES, self.another.name, meas_res=self.meas_res)\n        self.own.send_message(dst, message)\n\n    def received_message(self, src: str, msg: BBPSSWMessage) -> None:\n        \"\"\"Method to receive messages.\n\n        Args:\n            src (str): name of node that sent the message.\n            msg (BBPSSW message): message received.\n\n        Side Effects:\n            Will call `update_resource_manager` method.\n        \"\"\"\n\n        log.logger.info(self.own.name + \" received result message, succeeded: {}\".format(self.meas_res == msg.meas_res))\n        assert src == self.another.own.name\n        self.update_resource_manager(self.meas_memo, \"RAW\")\n        if self.meas_res == msg.meas_res:\n            self.kept_memo.fidelity = self.improved_fidelity(self.kept_memo.fidelity)\n            self.update_resource_manager(self.kept_memo, state=\"ENTANGLED\")\n        else:\n            self.update_resource_manager(self.kept_memo, state=\"RAW\")\n\n    def memory_expire(self, memory: \"Memory\") -> None:\n        \"\"\"Method to receive memory expiration events.\n\n        Args:\n            memory (Memory): memory that has expired.\n\n        Side Effects:\n            Will call `update_resource_manager` method.\n        \"\"\"\n\n        assert memory in self.memories\n        if self.meas_memo is None:\n            self.update_resource_manager(memory, \"RAW\")\n        else:\n            for memory in self.memories:\n                self.update_resource_manager(memory, \"RAW\")\n\n    def release(self) -> None:\n        pass\n\n    @staticmethod\n    @lru_cache(maxsize=128)\n    def success_probability(F: float) -> float:\n        \"\"\"Method to calculate probability of purification success.\n        \n        Formula comes from Dur and Briegel (2007) page 14.\n\n        Args:\n            F (float): fidelity of entanglement.\n        \"\"\"\n\n        return F ** 2 + 2 * F * (1 - F) / 3 + 5 * ((1 - F) / 3) ** 2\n\n    @staticmethod\n    @lru_cache(maxsize=128)\n    def improved_fidelity(F: float) -> float:\n        \"\"\"Method to calculate fidelity after purification.\n        \n        Formula comes from Dur and Briegel (2007) formula (18) page 14.\n\n        Args:\n            F (float): fidelity of entanglement.\n        \"\"\"\n\n        return (F ** 2 + ((1 - F) / 3) ** 2) / (F ** 2 + 2 * F * (1 - F) / 3 + 5 * ((1 - F) / 3) ** 2)\n\n", "meta": {"hexsha": "d362fa943569f2640480c60cb9e75c485016ef29", "size": 7355, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/entanglement_management/purification.py", "max_stars_repo_name": "alexk101/SeQUeNCe", "max_stars_repo_head_hexsha": "3ae6a9c0f787e65b905fd28de29303af0c9420c1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2020-09-11T20:06:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:01:17.000Z", "max_issues_repo_path": "src/entanglement_management/purification.py", "max_issues_repo_name": "alexk101/SeQUeNCe", "max_issues_repo_head_hexsha": "3ae6a9c0f787e65b905fd28de29303af0c9420c1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 62, "max_issues_repo_issues_event_min_datetime": "2020-09-03T16:49:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T16:08:48.000Z", "max_forks_repo_path": "src/entanglement_management/purification.py", "max_forks_repo_name": "alexk101/SeQUeNCe", "max_forks_repo_head_hexsha": "3ae6a9c0f787e65b905fd28de29303af0c9420c1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2020-09-11T20:06:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T14:31:31.000Z", "avg_line_length": 34.3691588785, "max_line_length": 149, "alphanum_fraction": 0.6179469748, "include": true, "reason": "from numpy", "num_tokens": 1734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.1976124685999784}}
{"text": "\"\"\"plot_utils module for plotting SEDs.\"\"\"\n\nimport copy\nimport glob\nfrom random import choice\n\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nimport pandas as pd\nimport numpy as np\nfrom astropy import units as u\nfrom astropy.io import fits\nfrom astropy.table import Table\nfrom extinction import apply\nfrom isochrones.interp import DFInterpolator\nfrom matplotlib.collections import LineCollection\nfrom matplotlib.gridspec import GridSpec\nfrom PyAstronomy import pyasl\nfrom scipy.optimize import curve_fit\nfrom scipy.stats import gaussian_kde\n\nimport corner\nfrom dynesty import plotting as dyplot\n\nfrom .config import filesdir, gridsdir, modelsdir\nfrom .isochrone import get_isochrone\nfrom .phot_utils import *\nfrom .sed_library import *\nfrom .utils import *\n\n\nclass SEDPlotter:\n    \"\"\"Artist class for all things SED.\n\n    Parameters\n    ----------\n    input_files : str\n        Directory containing the code's output files.\n    out_folder : type\n        Directory where to put the output plots.\n    pdf : type\n        Set to True to output plots in pdf.\n    png : type\n        Set to True to output plots in png.\n    model : type\n        Set to override the SED model that's going to be plotted.\n        Possible values are:\n            - Phoenix\n            - BTSettl\n            - NextGen\n            - CK04 (Castelli & Kurucz 2004)\n            - Kurucz (Kurucz 1993)\n\n    Examples\n    -------\n    Examples should be written in doctest format, and\n    should illustrate how to use the function/class.\n    >>>\n\n    Attributes\n    ----------\n    chain_out : str\n        Output directory for chain plot.\n    like_out : str\n        Output directory for likelihood plot.\n    post_out : str\n        Output directory for posteriors plot.\n    moddir : type\n        Directory wheere the SED models are located.\n    out : dict\n        SED fitting routine output.\n    engine : str\n        Selected fitting engine.\n    star : Star\n        The fitted Star object.\n    coordinator : array_like\n        Array coordinating fixed parameters.\n    fixed : array_like\n        Array coordinating fixed parameters.\n    norm : bool\n        norm is set to True if a normalization constant is fitted instead of\n        radius + distance.\n    grid : str\n        Selected model grid.\n    av_law : function\n        Exticntion law chosen for the fit.\n    order : array_like\n        Array coordinating parameter order.\n    interpolator : function\n        Interpolator function.\n    theta : array_like\n        `Best fit` parameter vector\n\n    \"\"\"\n\n    __wav_file = 'PHOENIXv2/WAVE_PHOENIX-ACES-AGSS-COND-2011.fits'\n\n    def __init__(self, input_files, out_folder, pdf=False,\n                 model=None, settings=None, method='averaged',\n                 save_model=False):\n        \"\"\"See class docstring.\"\"\"\n        print('\\nInitializing plotter.\\n')\n        # General setup\n        self.pdf = pdf\n        png = True if not pdf else False\n        self.png = png\n        self.out_folder = out_folder\n        self.bma = False\n        self.method = method\n        self.save = save_model\n\n        traces = f'{out_folder}/traces'\n        histograms = f'{out_folder}/histograms'\n        self.traces_out = traces\n        self.hist_out = histograms\n        self.moddir = modelsdir\n        self.settings_dir = settings\n\n        # Read output files.\n        if input_files != 'raw':\n            out = pickle.load(open(input_files, 'rb'))\n            self.out = out\n            self.engine = out['engine']\n            self.star = out['star']\n            self.coordinator = out['coordinator']\n            self.fixed = out['fixed']\n            self.norm = out['norm']\n            if model is None:\n                if self.engine != 'Bayesian Model Averaging':\n                    self.grid = out['model_grid']\n                else:\n                    self.bma = True\n                    zs = np.array([out['lnZ'][key]\n                                   for key in out['lnZ'].keys()])\n                    keys = np.array([key for key in out['lnZ'].keys()])\n                    grid = keys[np.argmax(zs)]\n                    self.grid = grid\n            else:\n                self.grid = model\n            self.av_law = out['av_law']\n\n            # Create target folders\n            create_dir(out_folder)\n            if self.engine != 'Bayesian Model Averaging':\n                create_dir(traces)\n            create_dir(histograms)\n\n            self.star.load_grid(self.grid)\n\n            if not self.norm:\n                self.order = np.array(\n                    [\n                        'teff', 'logg', 'z',\n                        'dist', 'rad', 'Av',\n                    ]\n                )\n            else:\n                self.order = np.array(\n                    ['teff', 'logg', 'z', 'norm', 'Av'])\n\n            mask = self.star.filter_mask\n            flxs = self.star.flux[mask]\n            errs = self.star.flux_er[mask]\n            filters = self.star.filter_names[mask]\n            wave = self.star.wave[mask]\n            for filt, flx, flx_e in zip(filters, flxs, errs):\n                p_ = get_noise_name(filt) + '_noise'\n                self.order = np.append(self.order, p_)\n\n            if self.grid.lower() == 'phoenix':\n                with open(gridsdir + '/Phoenixv2_DF.pkl', 'rb') as intp:\n                    self.interpolator = DFInterpolator(pd.read_pickle(intp))\n            if self.grid.lower() == 'btsettl':\n                with open(gridsdir + '/BTSettl_DF.pkl', 'rb') as intp:\n                    self.interpolator = DFInterpolator(pd.read_pickle(intp))\n            if self.grid.lower() == 'btnextgen':\n                with open(gridsdir + '/BTNextGen_DF.pkl', 'rb') as intp:\n                    self.interpolator = DFInterpolator(pd.read_pickle(intp))\n            if self.grid.lower() == 'btcond':\n                with open(gridsdir + '/BTCond_DF.pkl', 'rb') as intp:\n                    self.interpolator = DFInterpolator(pd.read_pickle(intp))\n            if self.grid.lower() == 'ck04':\n                with open(gridsdir + '/CK04_DF.pkl', 'rb') as intp:\n                    self.interpolator = DFInterpolator(pd.read_pickle(intp))\n            if self.grid.lower() == 'kurucz':\n                with open(gridsdir + '/Kurucz_DF.pkl', 'rb') as intp:\n                    self.interpolator = DFInterpolator(pd.read_pickle(intp))\n            if self.grid.lower() == 'coelho':\n                with open(gridsdir + '/Coelho_DF.pkl', 'rb') as intp:\n                    self.interpolator = DFInterpolator(pd.read_pickle(intp))\n\n            # Get best fit parameters.\n            theta_samples = np.zeros(self.order.shape[0])\n            theta_average = np.zeros(self.order.shape[0])\n            for i, param in enumerate(self.order):\n                if param != 'inflation':\n                    theta_samples[i] = out['best_fit_samples'][param]\n                    theta_average[i] = out['best_fit_averaged'][param]\n\n            # Calculate best fit model.\n            model_samples = model_grid(theta_samples, filters, wave,\n                                       self.interpolator, self.norm,\n                                       self.av_law)\n            model_average = model_grid(theta_average, filters, wave,\n                                       self.interpolator, self.norm,\n                                       self.av_law)\n            if method == 'averaged':\n                self.theta = theta_average\n                self.model = model_average\n            elif method == 'samples':\n                self.theta = theta_samples\n                self.model = model_samples\n\n            # Get archival fluxes.\n            self.__extract_info()\n        else:\n            self.star = None\n\n        # Setup plots.\n        self.__read_config()\n        print('\\nPlotter initialized.\\n')\n\n    def __extract_info(self):\n        self.flux = []\n        self.flux_er = []\n        self.wave = []\n        self.bandpass = []\n\n        for i, f in zip(self.star.used_filters, self.star.flux):\n            if i:\n                self.flux.append(f)\n        for i, e in zip(self.star.used_filters, self.star.flux_er):\n            if i:\n                self.flux_er.append(e)\n        for i, w in zip(self.star.used_filters, self.star.wave):\n            if i:\n                self.wave.append(w)\n        for i, bp in zip(self.star.used_filters, self.star.bandpass):\n            if i:\n                self.bandpass.append(bp)\n\n        self.flux = np.array(self.flux)\n        self.flux_er = np.array(self.flux_er)\n        self.wave = np.array(self.wave)\n        self.bandpass = np.array(self.bandpass).T\n\n    def plot_SED_no_model(self, s=None):\n        \"\"\"Plot raw photometry.\"\"\"\n        if self.star is None:\n            self.star = s\n        self.__extract_info()\n        # Get plot ylims.\n        ymin = (self.flux * self.wave).min()\n        ymax = (self.flux * self.wave).max()\n\n        f, ax = plt.subplots(figsize=self.figsize)\n\n        # Model plot\n        used_f = self.star.filter_names[self.star.filter_mask]\n        colors = np.array([\n            'tomato', 'indianred', 'tab:red',\n            'salmon', 'coral',\n            'mediumorchid', 'mediumslateblue', 'tab:blue',\n            'darkslateblue', 'darkblue',\n            'olivedrab', 'yellowgreen', 'greenyellow', 'yellow',\n            'orangered', 'chocolate', 'khaki',\n            'limegreen', 'darkgreen', 'lime', 'seagreen', 'lawngreen', 'green',\n            'aquamarine', 'turquoise', 'lightseagreen', 'teal', 'cadetblue',\n            'firebrick', 'darkred',\n            'blueviolet', 'darkviolet',\n            'midnightblue', 'blue',\n            'deeppink', 'fuchsia', 'mediumslateblue'\n        ])\n\n        for c, w, fl, fe, bp, fi in zip(\n                colors[self.star.filter_mask],\n                self.wave, self.flux, self.flux_er,\n                self.bandpass, used_f):\n            ax.errorbar(w, fl * w,\n                        xerr=bp, yerr=fe,\n                        fmt='',\n                        ecolor=c,\n                        marker=None)\n\n            ax.scatter(w, fl * w,\n                       edgecolors='black',\n                       marker=self.marker,\n                       c=c,\n                       s=self.scatter_size,\n                       alpha=self.scatter_alpha, label=fi)\n\n        ax.set_ylim([ymin * .8, ymax * 1.25])\n        ax.set_xscale('log', nonposx='clip')\n        ax.set_yscale('log', nonposy='clip')\n        ax.set_ylabel(r'$\\lambda$F$_\\lambda$ (erg cm$^{-2}$s$^{-1}$)',\n                      fontsize=self.fontsize,\n                      fontname=self.fontname\n                      )\n        ax.legend(loc=0)\n\n        ax.tick_params(\n            axis='both', which='major',\n            labelsize=self.tick_labelsize\n        )\n        ax.set_xticks(np.linspace(1, 10, 10))\n        ax.get_xaxis().set_major_formatter(ticker.ScalarFormatter())\n        ax.set_xlim([0.1, 6])\n\n        for tick in ax.get_yticklabels():\n            tick.set_fontname(self.fontname)\n\n        if self.pdf:\n            plt.savefig(self.out_folder + '/SED_no_model.pdf',\n                        bbox_inches='tight')\n        if self.png:\n            plt.savefig(self.out_folder + '/SED_no_model.png',\n                        bbox_inches='tight')\n        pass\n\n    def plot_SED(self, method='average'):\n        \"\"\"Create the plot of the SED.\"\"\"\n        if self.moddir is None:\n            print('Models directory not provided, skipping SED plot.')\n            return\n        print('Plotting SED')\n        # Get plot ylims.\n        ymin = (self.flux * self.wave).min()\n        ymax = (self.flux * self.wave).max()\n\n        n_filt = self.star.used_filters.sum()\n        n_pars = int(len(self.theta) - n_filt)\n\n        # Get models residuals\n        mask = self.star.filter_mask\n        mags = self.star.mags[mask]\n        flxs = self.star.flux[mask]\n        errs = self.star.flux_er[mask]\n        filters = self.star.filter_names[mask]\n        wave = self.star.wave[mask]\n\n        for i, th in enumerate(self.theta[n_pars:]):\n            mag = mags[i]\n            filt = filters[i]\n            _, er = mag_to_flux(mag, th, filt)\n            self.theta[n_pars + i] = er\n\n        residuals, errors = get_residuals(\n            self.theta, flxs, errs, wave, filters, self.interpolator, self.norm,\n            self.av_law)\n\n        norm_res = residuals / errors\n\n        # Create plot layout\n\n        f = plt.figure(figsize=self.figsize)\n        gs = GridSpec(2, 1, height_ratios=[3, 0.5], hspace=0.05)\n\n        ax = f.add_subplot(gs[0])\n        ax_r = f.add_subplot(gs[1])\n\n        self.SED(ax)\n\n        # Model plot\n        ax.errorbar(self.wave, self.flux * self.wave,\n                    xerr=self.bandpass, yerr=errors,\n                    fmt=',',\n                    ecolor=self.error_color,\n                    zorder=0,\n                    marker=None)\n\n        ax.scatter(self.wave, self.flux * self.wave,\n                   edgecolors='black',\n                   marker=self.marker,\n                   c=self.marker_colors,\n                   s=self.scatter_size, zorder=1,\n                   alpha=self.scatter_alpha)\n\n        ax.scatter(self.wave, self.model * self.wave,\n                   marker=self.marker_model,\n                   edgecolors=self.marker_colors_model,\n                   s=self.scatter_size,\n                   facecolor='', zorder=3,\n                   lw=3)\n\n        # Residual plot\n        ax_r.axhline(y=0, lw=2, ls='--', c='k', alpha=.7)\n\n        ax_r.errorbar(self.wave, np.zeros(self.wave.shape[0]),\n                      xerr=self.bandpass, yerr=self.flux_er,\n                      fmt=',',\n                      ecolor=self.error_color,\n                      marker=None)\n        ax_r.scatter(self.wave, np.zeros(self.wave.shape[0]),\n                     edgecolors='black',\n                     marker=self.marker,\n                     c=self.marker_colors,\n                     s=self.scatter_size,\n                     alpha=self.scatter_alpha)\n        ax_r.scatter(self.wave, norm_res,\n                     marker=self.marker_model,\n                     edgecolors=self.marker_colors_model,\n                     s=self.scatter_size,\n                     facecolor='',\n                     lw=3,\n                     zorder=10)\n\n        # Formatting\n        res_std = norm_res.std()\n        ax.set_ylim([ymin * 0.8, ymax * 1.2])\n        # ax_r.set_ylim([-5, 5])\n        ax_r.set_ylim([-4 * res_std, 4 * res_std])\n        ax.set_xscale('log', nonposx='clip')\n        ax.set_yscale('log', nonposy='clip')\n        ax_r.set_xscale('log', nonposx='clip')\n        ax_r.set_xlabel(r'$\\lambda (\\mu m)$',\n                        fontsize=self.fontsize,\n                        fontname=self.fontname\n                        )\n        ax.set_ylabel(r'$\\lambda$F$_\\lambda$ (erg cm$^{-2}$s$^{-1}$)',\n                      fontsize=self.fontsize,\n                      fontname=self.fontname\n                      )\n        ax_r.set_ylabel('Residuals\\n$(\\\\sigma)$',\n                        fontsize=self.fontsize,\n                        fontname=self.fontname\n                        )\n\n        ax.tick_params(\n            axis='both', which='major',\n            labelsize=self.tick_labelsize\n        )\n        ax_r.tick_params(\n            axis='both', which='major',\n            labelsize=self.tick_labelsize\n        )\n        ax_r.set_xticks(np.linspace(1, 10, 10))\n        ax_r.get_xaxis().set_major_formatter(ticker.ScalarFormatter())\n        ax.set_xticks(np.linspace(1, 10, 10))\n        ax.get_xaxis().set_major_formatter(ticker.NullFormatter())\n        ylocmin = ticker.LinearLocator(numticks=4)\n\n        ax_r.yaxis.set_minor_locator(ylocmin)\n        ax_r.yaxis.set_minor_formatter(ticker.NullFormatter())\n\n        if 'GALEX_FUV' in self.star.filter_names[self.star.filter_mask] or \\\n                'GALEX_NUV' in self.star.filter_names[self.star.filter_mask]:\n            ax.set_xlim([0.125, 6])\n            ax_r.set_xlim([0.125, 6])\n        else:\n            ax.set_xlim([0.25, 6])\n            ax_r.set_xlim([0.25, 6])\n\n        labels = [item.get_text() for item in ax.get_xticklabels()]\n\n        empty_string_labels = [''] * len(labels)\n        ax.set_xticklabels(empty_string_labels)\n\n        for tick in ax.get_yticklabels():\n            tick.set_fontname(self.fontname)\n        for tick in ax_r.get_yticklabels():\n            tick.set_fontname(self.fontname)\n        for tick in ax_r.get_xticklabels():\n            tick.set_fontname(self.fontname)\n\n        if self.pdf:\n            plt.savefig(f'{self.out_folder}/SED.pdf', bbox_inches='tight')\n        if self.png:\n            plt.savefig(f'{self.out_folder}/SED.png', bbox_inches='tight')\n        if self.save:\n            data = np.vstack((self.wave, self.model * self.wave)).T\n            np.savetxt(f'{self.out_folder}/synthetic.dat', data, fmt='%s',\n                       header='wavelength(mu m) wave*flux(erg cm-2 s-2)')\n        pass\n\n    def SED(self, ax):\n        \"\"\"Plot the SED model.\"\"\"\n        Rv = 3.1  # For extinction.\n        if not self.norm:\n            rad = self.theta[4]\n            dist = self.theta[3] * u.pc.to(u.solRad)\n            norm = (rad / dist) ** 2\n            Av = self.theta[5]\n        else:\n            norm = self.theta[3]\n            Av = self.theta[4]\n\n        # SED plot.\n        if self.grid == 'phoenix':\n            wave = fits.open(self.moddir + self.__wav_file)[0].data\n            wave *= u.angstrom.to(u.um)\n\n            lower_lim = 0.125 < wave\n            upper_lim = wave < 4.629296073126975\n\n            flux = self.fetch_Phoenix()\n\n            new_w = wave[lower_lim * upper_lim]\n\n            new_ww = np.linspace(new_w[0], new_w[-1], len(new_w))\n\n            ext = self.av_law(new_w * 1e4, Av, Rv)\n\n            brf, _ = pyasl.instrBroadGaussFast(\n                new_ww, flux, 1500,\n                edgeHandling=\"firstlast\",\n                fullout=True, maxsig=8\n            )\n            brf = brf[lower_lim * upper_lim]\n            brf = apply(ext, brf)\n            flx = brf * norm * new_w\n            ax.plot(new_w[:-1000], flx[:-1000], lw=1.25, color=self.model_color,\n                    zorder=0)\n\n        elif self.grid == 'btsettl':\n            wave, flux = self.fetch_btsettl()\n\n            lower_lim = 0.125 < wave\n            upper_lim = wave < 4.629296073126975\n\n            wave = wave[lower_lim * upper_lim]\n            flux = flux[lower_lim * upper_lim]\n            ext = self.av_law(wave * 1e4, Av, Rv)\n\n            new_w = np.linspace(wave[0], wave[-1], len(wave))\n\n            brf, _ = pyasl.instrBroadGaussFast(\n                new_w, flux, 1500,\n                edgeHandling=\"firstlast\",\n                fullout=True, maxsig=8\n            )\n            flx = apply(ext, brf)\n            flx *= wave * norm\n            ax.plot(wave, flx, lw=1.25, color=self.model_color, zorder=0)\n\n        elif self.grid == 'btnextgen':\n            wave, flux = self.fetch_btnextgen()\n\n            lower_lim = 0.125 < wave\n            upper_lim = wave < 4.629296073126975\n\n            wave = wave[lower_lim * upper_lim]\n            flux = flux[lower_lim * upper_lim]\n            ext = self.av_law(wave * 1e4, Av, Rv)\n\n            new_w = np.linspace(wave[0], wave[-1], len(wave))\n\n            brf, _ = pyasl.instrBroadGaussFast(\n                new_w, flux, 1500,\n                edgeHandling=\"firstlast\",\n                fullout=True, maxsig=8\n            )\n            flx = apply(ext, brf)\n            flx *= wave * norm\n            ax.plot(wave, flx, lw=1.25, color=self.model_color, zorder=0)\n\n        elif self.grid == 'btcond':\n            wave, flux = self.fetch_btcond()\n\n            lower_lim = 0.125 < wave\n            upper_lim = wave < 4.629296073126975\n\n            wave = wave[lower_lim * upper_lim]\n            flux = flux[lower_lim * upper_lim]\n            ext = self.av_law(wave * 1e4, Av, Rv)\n\n            new_w = np.linspace(wave[0], wave[-1], len(wave))\n\n            brf, _ = pyasl.instrBroadGaussFast(\n                new_w, flux, 1500,\n                edgeHandling=\"firstlast\",\n                fullout=True, maxsig=8\n            )\n            flx = apply(ext, brf)\n            flx *= wave * norm\n            ax.plot(wave, flx, lw=1.25, color=self.model_color, zorder=0)\n\n        elif self.grid == 'ck04':\n            wave, flux = self.fetch_ck04()\n\n            lower_lim = 0.125 < wave\n            upper_lim = wave < 4.629296073126975\n\n            wave = wave[lower_lim * upper_lim]\n            flux = flux[lower_lim * upper_lim]\n            ext = self.av_law(wave * 1e4, Av, Rv)\n            flux = apply(ext, flux)\n            flux *= wave * norm\n            ax.plot(wave, flux, lw=1.25, color=self.model_color, zorder=0)\n\n        elif self.grid == 'kurucz':\n            wave, flux = self.fetch_kurucz()\n\n            lower_lim = 0.15 < wave\n            upper_lim = wave < 4.629296073126975\n\n            wave = wave[lower_lim * upper_lim]\n            flux = flux[lower_lim * upper_lim]\n            ext = self.av_law(wave * 1e4, Av, Rv)\n            flux = apply(ext, flux)\n            flux *= wave * norm\n            ax.plot(wave, flux, lw=1.25, color=self.model_color, zorder=0)\n\n        elif self.grid == 'coelho':\n            wave, flux = self.fetch_coelho()\n\n            lower_lim = 0.15 < wave\n            upper_lim = wave < 4.629296073126975\n\n            wave = wave[lower_lim * upper_lim]\n            flux = flux[lower_lim * upper_lim]\n            ext = self.av_law(wave * 1e4, Av, Rv)\n            flux = apply(ext, flux)\n            flux *= wave * norm\n            ax.plot(wave, flux, lw=1.25, color=self.model_color, zorder=0)\n        if self.save:\n            data = np.vstack((wave, flux)).T\n            np.savetxt(f'{self.out_folder}/SED.dat', data, fmt='%s',\n                       header='wavelength(mu m) wave*flux(erg cm-2 s-2)')\n        pass\n\n    def plot_trace(self):\n        \"\"\"Plot SED chains.\"\"\"\n        samples = self.out['posterior_samples']\n        for i, param in enumerate(self.order):\n            if not self.coordinator[i]:\n                f, ax = plt.subplots(figsize=(12, 4))\n                ax.step(range(len(samples[param])), samples[param],\n                        color='k', alpha=0.8)\n                ax.set_ylabel(param,\n                              fontsize=self.fontsize,\n                              fontname=self.fontname\n                              )\n                ax.set_xlabel('Steps',\n                              fontsize=self.fontsize,\n                              fontname=self.fontname\n                              )\n                best = self.out['best_fit'][param]\n                # ax.axhline(np.median(samples[param]), color='red', lw=2)\n                ax.axhline(best, color='red', lw=2)\n                ax.tick_params(\n                    axis='both', which='major',\n                    labelsize=self.tick_labelsize\n                )\n                plt.savefig(self.chain_out + '/' + param +\n                            '.png', bbox_inches='tight')\n        plt.close('all')\n        pass\n\n    def plot_like(self):\n        \"\"\"Plot Likelihoods.\"\"\"\n        samples = self.out['posterior_samples']\n        for i, param in enumerate(self.order):\n            if not self.coordinator[i]:\n                f, ax = plt.subplots(figsize=(12, 4))\n                ax.scatter(samples[param], samples['loglike'], alpha=0.5, s=40)\n                best = self.out['best_fit'][param]\n                # ax.axvline(np.median(samples[param]), color='red', lw=1.5)\n                ax.axvline(best, color='red', lw=1.5)\n                ax.set_ylabel('log likelihood',\n                              fontsize=self.fontsize,\n                              fontname=self.fontname\n                              )\n                ax.set_xlabel(param,\n                              fontsize=self.fontsize,\n                              fontname=self.fontname\n                              )\n                ax.tick_params(\n                    axis='both', which='major',\n                    labelsize=self.tick_labelsize\n                )\n                plt.savefig(self.like_out + '/' + param + '.png',\n                            bbox_inches='tight')\n        plt.close('all')\n        if self.engine == 'dynesty':\n            fig, axes = dyplot.traceplot(\n                self.out['dynesty'],\n                truths=self.theta,\n                show_titles=True, trace_cmap='plasma',\n            )\n            plt.savefig(self.like_out + '/dynesty_trace.png')\n        pass\n\n    def plot_post(self):\n        \"\"\"Plot posteriors.\"\"\"\n        samples = self.out['posterior_samples']\n        for i, param in enumerate(self.order):\n            if not self.coordinator[i]:\n                f, ax = plt.subplots(figsize=(12, 4))\n                ax.scatter(samples[param], samples['posteriors'], alpha=0.5,\n                           s=40)\n                best = self.out['best_fit'][param]\n                # ax.axvline(np.median(samples[param]), color='red', lw=1.5)\n                ax.axvline(best, color='red', lw=1.5)\n                ax.set_ylabel('log posterior',\n                              fontsize=self.fontsize,\n                              fontname=self.fontname\n                              )\n                ax.set_xlabel(param,\n                              fontsize=self.fontsize,\n                              fontname=self.fontname\n                              )\n                ax.tick_params(\n                    axis='both', which='major',\n                    labelsize=self.tick_labelsize\n                )\n                plt.savefig(self.post_out + '/' + param + '.png',\n                            bbox_inches='tight')\n        plt.close('all')\n        pass\n\n    def plot_hist(self):\n        pass\n\n    def plot_bma_hist(self):\n        \"\"\"Plot histograms.\"\"\"\n        print('Plotting BMA histograms.')\n        colors = [\n            'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple',\n            'tab:brown'\n        ]\n        models = [key for key in self.out['originals'].keys()]\n        for i, param in enumerate(self.order):\n            if 'noise' in param:\n                continue\n            if not self.coordinator[i]:\n                f1, ax1 = plt.subplots(figsize=(12, 6))\n                f2, ax2 = plt.subplots(figsize=(12, 6))\n                for j, m in enumerate(models):\n                    # Get samples\n                    samp = self.out['originals'][m][param]\n                    # Plot sample histogram\n                    label = m + ' prob: {:.3f}'.format(self.out['weights'][m])\n                    # Normal\n                    n, bins1, patches = ax1.hist(samp, alpha=.3, bins=20,\n                                                 label=label, density=True,\n                                                 color=colors[j])\n                    # Weighted\n                    n, bins2, patches = ax2.hist(\n                        samp, alpha=.3, bins=20, label=label,\n                        weights=[self.out['weights'][m]] * len(samp)\n                    )\n                    # Fit a KDE to data\n                    kde = gaussian_kde(samp)\n                    # Estimate amplitude of the weighted distributions\n                    mu, sig = norm.fit(samp)\n                    try:\n                        bc = bins2[:-1] + np.diff(bins2)\n                        popt, pcov = curve_fit(norm_fit, xdata=bc, ydata=n,\n                                               p0=[mu, sig, n.max()],\n                                               maxfev=50000)\n                    except RuntimeError:\n                        popt = (mu, sig, n.max())\n                    xx1 = np.linspace(bins1[0], bins1[-1], 1000)\n                    xx2 = np.linspace(bins2[0], bins2[-1], 1000)\n                    # Plot best fit\n                    ax1.plot(xx1, kde(xx2), lw=2, alpha=1, color=colors[j])\n                    ax2.plot(xx1, kde(xx2) * popt[2], lw=2, alpha=1,\n                             color=colors[j])\n                # The same but for the weighted samples\n                n, bins, patches = ax1.hist(\n                    self.out['weighted_samples'][param], alpha=.3,\n                    bins=20, label='Weighted sampling', density=True,\n                    color='tab:cyan'\n                )\n                kde = gaussian_kde(self.out['weighted_samples'][param])\n                xx = np.linspace(bins[0], bins[-1], 300)\n                ax1.plot(xx, kde(xx), color='tab:cyan', lw=2, alpha=1, ls='--')\n\n                # Now ditto for the weighted average\n                n, bins, patches = ax1.hist(\n                    self.out['weighted_average'][param], alpha=.3,\n                    bins=20, label='Weighted average', density=True,\n                    color='tab:pink'\n                )\n                kde = gaussian_kde(self.out['weighted_average'][param])\n                xx = np.linspace(bins[0], bins[-1], 300)\n                ax1.plot(xx, kde(xx), color='tab:pink', lw=2, alpha=1, ls='-.')\n                if param == 'z':\n                    param = '[Fe/H]'\n                # Normal\n                ax1.set_ylabel('PDF',\n                               fontsize=self.fontsize,\n                               fontname=self.fontname\n                               )\n                # Weighted\n                ax2.set_ylabel('N',\n                               fontsize=self.fontsize,\n                               fontname=self.fontname\n                               )\n                axes = [ax1, ax2]\n                for ax in axes:\n                    ax.set_xlabel(param,\n                                  fontsize=self.fontsize,\n                                  fontname=self.fontname\n                                  )\n                    for tick in ax.get_yticklabels():\n                        tick.set_fontname(self.fontname)\n                    for tick in ax.get_xticklabels():\n                        tick.set_fontname(self.fontname)\n\n                    ax.tick_params(\n                        axis='both', which='major',\n                        labelsize=self.tick_labelsize\n                    )\n                    ax.legend(loc=0, prop={'size': 16})\n\n                if param == '[Fe/H]':\n                    param = 'Fe_H'\n                if self.png:\n                    f1.savefig(self.hist_out + '/' + param + '.png',\n                               bbox_inches='tight')\n                    f2.savefig(self.hist_out + '/weighted_' + param + '.png',\n                               bbox_inches='tight')\n                if self.pdf:\n                    f1.savefig(self.hist_out + '/' + param + '.pdf',\n                               bbox_inches='tight')\n                    f2.savefig(self.hist_out + '/weighted_' + param + '.pdf',\n                               bbox_inches='tight')\n                plt.close(f1)\n                plt.close(f2)\n\n        if self.bma:\n            # Age hist\n            f, ax = plt.subplots(figsize=(12, 4))\n            samp = self.out['mist_samples']['age']\n            n, bins, patches = ax.hist(\n                samp, alpha=.3, bins=20, label='MIST', density=True\n            )\n            kde = gaussian_kde(samp)\n            xx = np.linspace(bins[0], bins[-1], 10000)\n            ax.plot(xx, kde(xx), color='k', lw=2, alpha=.7)\n            ax.set_ylabel('PDF',\n                          fontsize=self.fontsize,\n                          fontname=self.fontname)\n            ax.set_xlabel('Age',\n                          fontsize=self.fontsize,\n                          fontname=self.fontname)\n\n            for tick in ax.get_yticklabels():\n                tick.set_fontname(self.fontname)\n            for tick in ax.get_xticklabels():\n                tick.set_fontname(self.fontname)\n\n            ax.tick_params(\n                axis='both', which='major',\n                labelsize=self.tick_labelsize\n            )\n            plt.legend(loc=0)\n            if self.png:\n                plt.savefig(self.hist_out + '/age.png',\n                            bbox_inches='tight')\n            if self.pdf:\n                plt.savefig(self.hist_out + '/age.pdf',\n                            bbox_inches='tight')\n            plt.close(f)\n            # Mass hist\n            f, ax = plt.subplots(figsize=(12, 4))\n            samp = self.out['mist_samples']['iso_mass']\n            n, bins, patches = ax.hist(\n                samp, alpha=.3, bins=20, label='MIST', density=True\n            )\n            kde = gaussian_kde(samp)\n            xx = np.linspace(bins[0], bins[-1], 10000)\n            ax.plot(xx, kde(xx), color='k', lw=2, alpha=.7)\n            ax.set_ylabel('PDF',\n                          fontsize=self.fontsize,\n                          fontname=self.fontname)\n            ax.set_xlabel('Mass',\n                          fontsize=self.fontsize,\n                          fontname=self.fontname)\n\n            for tick in ax.get_yticklabels():\n                tick.set_fontname(self.fontname)\n            for tick in ax.get_xticklabels():\n                tick.set_fontname(self.fontname)\n\n            ax.tick_params(\n                axis='both', which='major',\n                labelsize=self.tick_labelsize\n            )\n            plt.legend(loc=0)\n            if self.png:\n                plt.savefig(self.hist_out + '/iso_mass.png',\n                            bbox_inches='tight')\n            if self.pdf:\n                plt.savefig(self.hist_out + '/iso_mass.pdf',\n                            bbox_inches='tight')\n            plt.close(f)\n            # EEP hist\n            f, ax = plt.subplots(figsize=(12, 4))\n            samp = self.out['mist_samples']['eep']\n            n, bins, patches = ax.hist(\n                samp, alpha=.3, bins=20, label='MIST', density=True\n            )\n            kde = gaussian_kde(samp)\n            xx = np.linspace(bins[0], bins[-1], 10000)\n            ax.plot(xx, kde(xx), color='k', lw=2, alpha=.7)\n            ax.set_ylabel('PDF',\n                          fontsize=self.fontsize,\n                          fontname=self.fontname)\n            ax.set_xlabel('EEP',\n                          fontsize=self.fontsize,\n                          fontname=self.fontname)\n\n            for tick in ax.get_yticklabels():\n                tick.set_fontname(self.fontname)\n            for tick in ax.get_xticklabels():\n                tick.set_fontname(self.fontname)\n\n            ax.tick_params(\n                axis='both', which='major',\n                labelsize=self.tick_labelsize\n            )\n            plt.legend(loc=0)\n            if self.png:\n                plt.savefig(self.hist_out + '/EEP.png',\n                            bbox_inches='tight')\n            if self.pdf:\n                plt.savefig(self.hist_out + '/EEP.pdf',\n                            bbox_inches='tight')\n            plt.close(f)\n\n    def plot_bma_HR(self, nsamp):\n        \"\"\"Plot HR diagram for the star.\"\"\"\n        print('Plotting HR diagram')\n        # Get necessary info from the star.\n        age = self.out[f'best_fit_{self.method}']['age']\n        feh = self.out[f'best_fit_{self.method}']['z']\n        teff = np.log10(self.out[f'best_fit_{self.method}']['teff'])\n        lum = np.log10(self.out[f'best_fit_{self.method}']['lum'])\n        teff_lo, teff_hi = self.out[f'uncertainties_{self.method}']['teff']\n        lum_lo, lum_hi = self.out[f'uncertainties_{self.method}']['lum']\n        teff_lo = teff_lo / (10 ** teff * np.log(10))\n        teff_hi = teff_hi / (10 ** teff * np.log(10))\n        lum_lo = lum_lo / (10 ** lum * np.log(10))\n        lum_hi = lum_hi / (10 ** lum * np.log(10))\n        ages = self.out['mist_samples']['age']\n        m = self.method if self.method == 'samples' else 'average'\n        fehs = self.out[f'weighted_{m}']['z']\n\n        if feh > 0.5:\n            feh = 0.5\n\n        iso_bf = get_isochrone(np.log10(age) + 9, feh)\n\n        logteff = iso_bf['logTeff'].values\n        loglum = iso_bf['logL'].values\n        mass = iso_bf['mass'].values\n\n        fig, ax = plt.subplots(figsize=self.hr_figsize)\n\n        points = np.array([logteff, loglum]).T.reshape(-1, 1, 2)\n        segments = np.concatenate([points[:-1], points[1:]], axis=1)\n\n        norm = plt.Normalize(mass.min(), mass.max())\n        lc = LineCollection(segments, cmap=self.hr_cmap, norm=norm,\n                            linewidths=5)\n\n        lc.set_array(mass)\n        line = ax.add_collection(lc)\n        line.zorder = 1000\n        cbar = fig.colorbar(line, ax=ax, pad=0.01)\n        cbar.set_label(r'$M_\\odot$',\n                       rotation=270,\n                       fontsize=self.fontsize,\n                       fontname=self.fontname,\n                       labelpad=20)\n\n        for i in range(nsamp):\n            a = np.log10(choice(ages)) + 9\n            z = choice(fehs)\n            if z > 0.5:\n                z = 0.5\n            iso = get_isochrone(a, z)\n\n            logt = iso['logTeff'].values\n            logl = iso['logL'].values\n            ax.plot(logt, logl, color='gray')\n\n        ax.errorbar(teff, lum, xerr=[[teff_lo], [teff_hi]],\n                    yerr=[[lum_lo], [lum_hi]], color=self.hr_color,\n                    zorder=1001)\n        ax.scatter(teff, lum, s=350, color=self.hr_color, zorder=1002,\n                   edgecolors='k', marker=self.hr_marker)\n\n        ax.invert_xaxis()\n        ax.set_xlabel('logTeff',\n                      fontsize=self.fontsize,\n                      fontname=self.fontname)\n        ax.set_ylabel('logL',\n                      fontsize=self.fontsize,\n                      fontname=self.fontname)\n        ax.tick_params(\n            axis='both', which='major',\n            labelsize=self.tick_labelsize\n        )\n        for ll in cbar.ax.yaxis.get_ticklabels():\n            ll.set_fontsize(self.tick_labelsize)\n        for tick in ax.get_yticklabels():\n            tick.set_fontname(self.fontname)\n        for tick in ax.get_yticklabels():\n            tick.set_fontname(self.fontname)\n\n        if self.png:\n            plt.savefig(self.out_folder + '/HR_diagram.png',\n                        bbox_inches='tight')\n        if self.pdf:\n            plt.savefig(self.out_folder + '/HR_diagram.pdf',\n                        bbox_inches='tight')\n\n    def plot_corner(self):\n        \"\"\"Make corner plot.\"\"\"\n        print('Plotting corner.')\n        m = self.method if self.method == 'samples' else 'average'\n        samples = self.out[f'weighted_{m}']\n        all_samps = []\n        theta_lo = []\n        theta_up = []\n\n        for i, o in enumerate(self.order):\n            if 'noise' in o:\n                self.coordinator[i] = 1\n\n        theta = self.theta[self.coordinator == 0]\n        used_params = self.order[self.coordinator == 0]\n\n        for i, param in enumerate(self.order):\n            if not self.coordinator[i]:\n                if 'noise' in param:\n                    continue\n                _, lo, up = credibility_interval(samples[param])\n                theta_lo.append(lo)\n                theta_up.append(up)\n                all_samps.append(samples[param])\n\n        corner_samp = np.vstack(all_samps)\n\n        titles = self.__create_titles(used_params, theta, theta_up, theta_lo)\n        labels = self.__create_labels(used_params)\n\n        fig = corner.corner(\n            corner_samp.T,\n            plot_contours=True,\n            fill_contours=False,\n            plot_datapoints=True,\n            no_fill_contours=True,\n            max_n_ticks=4\n        )\n\n        axes = np.array(fig.axes).reshape((theta.shape[0], theta.shape[0]))\n\n        for i in range(theta.shape[0]):\n            ax = axes[i, i]\n            ax.axvline(theta[i], color=self.corner_med_c,\n                       linestyle=self.corner_med_style)\n            ax.axvline(theta_lo[i], color=self.corner_v_c,\n                       linestyle=self.corner_v_style)\n            ax.axvline(theta_up[i], color=self.corner_v_c,\n                       linestyle=self.corner_v_style)\n            t = titles[i]\n\n            ax.set_title(t, fontsize=self.corner_fontsize,\n                         fontname=self.fontname)\n\n        for yi in range(theta.shape[0]):\n            for xi in range(yi):\n                ax = axes[yi, xi]\n                if xi == 0:\n                    for tick in ax.yaxis.get_major_ticks():\n                        tick.label.set_fontsize(self.corner_tick_fontsize)\n                        tick.label.set_fontname(self.fontname)\n                        ax.set_ylabel(\n                            labels[yi],\n                            labelpad=self.corner_labelpad,\n                            fontsize=self.corner_fontsize,\n                            fontname=self.fontname\n                        )\n                if yi == theta.shape[0] - 1:\n                    for tick in ax.xaxis.get_major_ticks():\n                        tick.label.set_fontsize(self.corner_tick_fontsize)\n                        tick.label.set_fontname(self.fontname)\n                        ax.set_xlabel(\n                            labels[xi],\n                            labelpad=self.corner_labelpad,\n                            fontsize=self.corner_fontsize,\n                            fontname=self.fontname\n                        )\n                ax.axvline(theta[xi], color=self.corner_med_c,\n                           linestyle=self.corner_med_style)\n                ax.axhline(theta[yi], color=self.corner_med_c,\n                           linestyle=self.corner_med_style)\n                ax.plot(theta[xi], theta[yi], self.corner_marker)\n            axes[-1, -1].set_xlabel(\n                labels[-1],\n                labelpad=self.corner_labelpad,\n                fontsize=self.corner_fontsize,\n                fontname=self.fontname\n            )\n            for tick in axes[-1, -1].xaxis.get_major_ticks():\n                tick.label.set_fontsize(self.corner_tick_fontsize)\n                tick.label.set_fontname(self.fontname)\n\n            if self.pdf:\n                plt.savefig(f'{self.out_folder}/CORNER.pdf',\n                            bbox_inches='tight')\n            if self.png:\n                plt.savefig(f'{self.out_folder}/CORNER.png',\n                            bbox_inches='tight')\n        pass\n\n    def clean(self):\n        \"\"\"Close opened figures.\"\"\"\n        plt.close('all')\n\n    def fetch_Phoenix(self):\n        \"\"\"Fetch correct Phoenixv2 SED file.\n\n        The directory containing the Phoenix spectra must be called PHOENIXv2\n        Within PHOENIXv2 there should be the wavelength file called\n        WAVE_PHOENIX-ACES-AGSS-COND-2011.fits and several folders called\n        Z[-/+]X.X where X.X are the metallicities (e.g. Z-0.0, Z+1.0, etc)\n        \"\"\"\n        # Change hdd to a class variable depending on an env param.\n        teff = self.theta[0]\n        logg = self.theta[1]\n        z = self.theta[2]\n        select_teff = np.argmin((abs(teff - np.unique(self.star.teff))))\n        select_logg = np.argmin((abs(logg - np.unique(self.star.logg))))\n        select_z = np.argmin((abs(z - np.unique(self.star.z))))\n        sel_teff = int(np.unique(self.star.teff)[select_teff])\n        sel_logg = np.unique(self.star.logg)[select_logg]\n        sel_z = np.unique(self.star.z)[select_z]\n        selected_SED = self.moddir + 'PHOENIXv2/Z'\n        metal_add = ''\n        if sel_z < 0:\n            metal_add = str(sel_z)\n        if sel_z == 0:\n            metal_add = '-0.0'\n        if sel_z > 0:\n            metal_add = '+' + str(sel_z)\n        selected_SED += metal_add\n        selected_SED += '/lte'\n        selected_SED += str(sel_teff) if len(str(sel_teff)) == 5 else \\\n            '0' + str(sel_teff)\n        selected_SED += '-' + str(sel_logg) + '0'\n        selected_SED += metal_add\n        selected_SED += '.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits'\n        flux = fits.open(selected_SED)[0].data\n        flux *= (u.erg / u.s / u.cm ** 2 / u.cm).to(\n            u.erg / u.s / u.cm ** 2 / u.um)\n        return flux\n\n    def fetch_btsettl(self):\n        \"\"\"Fetch correct BT-Settl SED file.\n\n        The directory containing the BT-Settl spectra must be called BTSettl\n        Within BTSettl there should be yet another directory\n        called AGSS2009, within BTSettl/AGSS2009 there should be the SED fits\n        files with the following naming convention:\n\n        lteTTT-G.G[-/+]Z.Za+0.0.BT-Settl.AGSS2009.fits\n\n        where TTT are the first 3 digits of the effective temperature if it's a\n        number over 10000, else it's the first 2 digit prepended by a 0.\n        G.G is the log g and Z.Z the metallicity.\n        \"\"\"\n        conversion = (u.erg / u.s / u.cm ** 2 / u.angstrom)\n        conversion = conversion.to(u.erg / u.s / u.cm ** 2 / u.um)\n        teff = self.theta[0]\n        logg = self.theta[1]\n        z = self.theta[2]\n        select_teff = np.argmin((abs(teff - np.unique(self.star.teff))))\n        select_logg = np.argmin((abs(logg - np.unique(self.star.logg))))\n        select_z = np.argmin((abs(z - np.unique(self.star.z))))\n        sel_teff = int(np.unique(self.star.teff)[select_teff]) // 100\n        sel_logg = np.unique(self.star.logg)[select_logg]\n        sel_z = np.unique(self.star.z)[select_z]\n        metal_add = ''\n        if sel_z < 0:\n            metal_add = str(sel_z)\n        if sel_z == 0:\n            metal_add = '-0.0'\n        if sel_z > 0:\n            metal_add = '+' + str(sel_z)\n        selected_SED = self.moddir + 'BTSettl/AGSS2009/lte'\n        selected_SED += str(sel_teff) if len(str(sel_teff)) == 3 else \\\n            '0' + str(sel_teff)\n        selected_SED += '-' + str(sel_logg) + metal_add + 'a+*'\n        gl = glob.glob(selected_SED)\n        selected_SED = gl[0]\n        tab = Table(fits.open(selected_SED)[1].data)\n        flux = np.array(tab['FLUX'].tolist()) * conversion\n        wave = np.array(tab['WAVELENGTH'].tolist()) * u.angstrom.to(u.um)\n        return wave, flux\n\n    def fetch_btnextgen(self):\n        \"\"\"Fetch correct BT-NextGen SED file.\n\n        The directory containing the BT-NextGen spectra must be called\n        BTNextGen. Within BTNextGen there should be yet another directory\n        called AGSS2009, within BTNextGen/AGSS2009 there should be the SED fits\n        files with the following naming convention:\n\n        lteTTT-G.G[-/+]Z.Za+0.0..BT-NextGen.AGSS2009.fits\n\n        where TTT are the first 3 digits of the effective temperature if it's a\n        number over 10000, else it's the first 2 digit prepended by a 0.\n        G.G is the log g and Z.Z the metallicity.\n        \"\"\"\n        conversion = (u.erg / u.s / u.cm ** 2 / u.angstrom)\n        conversion = conversion.to(u.erg / u.s / u.cm ** 2 / u.um)\n        teff = self.theta[0]\n        logg = self.theta[1]\n        z = self.theta[2]\n        select_teff = np.argmin((abs(teff - np.unique(self.star.teff))))\n        select_logg = np.argmin((abs(logg - np.unique(self.star.logg))))\n        select_z = np.argmin((abs(z - np.unique(self.star.z))))\n        sel_teff = int(np.unique(self.star.teff)[select_teff]) // 100\n        sel_logg = np.unique(self.star.logg)[select_logg]\n        sel_z = np.unique(self.star.z)[select_z]\n        metal_add = ''\n        if sel_z < 0:\n            metal_add = str(sel_z)\n        if sel_z == 0:\n            metal_add = '-0.0'\n        if sel_z > 0:\n            metal_add = '+' + str(sel_z)\n        selected_SED = self.moddir + 'BTNextGen/AGSS2009/lte'\n        selected_SED += str(sel_teff) if len(str(sel_teff)) == 3 else \\\n            '0' + str(sel_teff)\n        selected_SED += '-' + str(sel_logg) + metal_add + 'a+*'\n        gl = glob.glob(selected_SED)\n        selected_SED = gl[0]\n        tab = Table(fits.open(selected_SED)[1].data)\n        flux = np.array(tab['FLUX'].tolist()) * conversion\n        wave = np.array(tab['WAVELENGTH'].tolist()) * u.angstrom.to(u.um)\n        return wave, flux\n\n    def fetch_btcond(self):\n        \"\"\"Fetch correct BT-COND SED file.\n\n        The directory containing the BT-COND spectra must be called\n        BTCOND. Within BTCOND there should be yet another directory\n        called CIFIST2011, within BTCOND/CIFIST2011 there should be the SED\n        fits files with the following naming convention:\n\n        lteTTT-G.G[-/+]Z.Za+0.0..BT-Cond.CIFIST2011.fits\n\n        where TTT are the first 3 digits of the effective temperature if it's a\n        number over 10000, else it's the first 2 digit prepended by a 0.\n        G.G is the log g and Z.Z the metallicity.\n        \"\"\"\n        conversion = (u.erg / u.s / u.cm ** 2 / u.angstrom)\n        conversion = conversion.to(u.erg / u.s / u.cm ** 2 / u.um)\n        teff = self.theta[0]\n        logg = self.theta[1]\n        z = self.theta[2]\n        select_teff = np.argmin((abs(teff - np.unique(self.star.teff))))\n        select_logg = np.argmin((abs(logg - np.unique(self.star.logg))))\n        select_z = np.argmin((abs(z - np.unique(self.star.z))))\n        sel_teff = int(np.unique(self.star.teff)[select_teff]) // 100\n        sel_logg = np.unique(self.star.logg)[select_logg]\n        sel_z = np.unique(self.star.z)[select_z]\n        metal_add = ''\n        if sel_z < 0:\n            metal_add = str(sel_z)\n        if sel_z == 0:\n            metal_add = '-0.0'\n        if sel_z > 0:\n            metal_add = '+' + str(sel_z)\n        selected_SED = self.moddir + 'BTCond/CIFIST2011/lte'\n        selected_SED += str(sel_teff) if len(str(sel_teff)) == 3 else \\\n            '0' + str(sel_teff)\n        selected_SED += '-' + str(sel_logg) + metal_add + 'a+*'\n        gl = glob.glob(selected_SED)\n        selected_SED = gl[0]\n        tab = Table(fits.open(selected_SED)[1].data)\n        flux = np.array(tab['FLUX'].tolist()) * conversion\n        wave = np.array(tab['WAVELENGTH'].tolist()) * u.angstrom.to(u.um)\n        return wave, flux\n\n    def fetch_ck04(self):\n        \"\"\"Fetch correct Castelli-Kurucz 2004 SED file.\n\n        The directory containing the Castelli-Kurucz spectra must be called\n        Castelli_Kurucz. Within Castelli_Kurucz there should be a group of\n        directories called ck[pm]ZZ where ZZ is the metalicity without the dot.\n        Within each directory there are fits files named:\n\n        ck[pm]ZZ_TTTT.fits\n\n        where ZZ is metalicity as previous and TTTT is the effective\n        temperature.\n        \"\"\"\n        conversion = (u.erg / u.s / u.cm ** 2 / u.angstrom)\n        conversion = conversion.to(u.erg / u.s / u.cm ** 2 / u.um)\n        teff = self.theta[0]\n        logg = self.theta[1]\n        z = self.theta[2]\n        select_teff = np.argmin((abs(teff - np.unique(self.star.teff))))\n        select_logg = np.argmin((abs(logg - np.unique(self.star.logg))))\n        select_z = np.argmin((abs(z - np.unique(self.star.z))))\n        sel_teff = int(np.unique(self.star.teff)[select_teff])\n        sel_logg = np.unique(self.star.logg)[select_logg]\n        sel_z = np.unique(self.star.z)[select_z]\n        metal_add = ''\n        if sel_z < 0:\n            metal_add = 'm' + str(-sel_z).replace('.', '')\n        if sel_z == 0:\n            metal_add = 'p00'\n        if sel_z > 0:\n            metal_add = 'p' + str(sel_z).replace('.', '')\n        name = 'ck' + metal_add\n        lgg = 'g{:.0f}'.format(sel_logg * 10)\n        selected_SED = self.moddir + 'Castelli_Kurucz/' + name + '/' + name\n        selected_SED += '_' + str(sel_teff) + '.fits'\n        tab = Table(fits.open(selected_SED)[1].data)\n        wave = np.array(tab['WAVELENGTH'].tolist()) * u.angstrom.to(u.um)\n        flux = np.array(tab[lgg].tolist()) * conversion\n        return wave, flux\n\n    def fetch_kurucz(self):\n        \"\"\"Fetch correct Kurucz 1993 SED file.\n\n        The directory containing the Kurucz spectra must be called\n        Kurucz. Within Kurucz there should be a group of\n        directories called k[pm]ZZ where ZZ is the metalicity without the dot.\n        Within each directory there are fits files named:\n\n        k[pm]ZZ_TTTT.fits\n\n        where ZZ is metalicity as previous and TTTT is the effective\n        temperature.\n        \"\"\"\n        conversion = (u.erg / u.s / u.cm ** 2 / u.angstrom)\n        conversion = conversion.to(u.erg / u.s / u.cm ** 2 / u.um)\n        teff = self.theta[0]\n        logg = self.theta[1]\n        z = self.theta[2]\n        select_teff = np.argmin((abs(teff - np.unique(self.star.teff))))\n        select_logg = np.argmin((abs(logg - np.unique(self.star.logg))))\n        select_z = np.argmin((abs(z - np.unique(self.star.z))))\n        sel_teff = int(np.unique(self.star.teff)[select_teff])\n        sel_logg = np.unique(self.star.logg)[select_logg]\n        sel_z = np.unique(self.star.z)[select_z]\n        metal_add = ''\n        if sel_z < 0:\n            metal_add = 'm' + str(-sel_z).replace('.', '')\n        if sel_z == 0:\n            metal_add = 'p00'\n        if sel_z > 0:\n            metal_add = 'p' + str(sel_z).replace('.', '')\n        name = 'k' + metal_add\n        lgg = 'g{:.0f}'.format(sel_logg * 10)\n        selected_SED = self.moddir + 'Kurucz/' + name + '/' + name\n        selected_SED += '_' + str(sel_teff) + '.fits'\n        tab = Table(fits.open(selected_SED)[1].data)\n        wave = np.array(tab['WAVELENGTH'].tolist()) * u.angstrom.to(u.um)\n        flux = np.array(tab[lgg].tolist()) * conversion\n        return wave, flux\n\n    def fetch_coelho(self):\n        \"\"\"Fetch correct Coelho 2014 SED file.\n\n        The directory containing the Coelho spectra must be called\n        Coelho14. Within Coelho14 there should be a group of\n        files called t[0X]XXXX_g[+-]Y.Y_[mp]ZZp0[14]_sed.fits\n        where X is the temperature, Y is the logg and Z the metallicity.\n        \"\"\"\n        conversion = (u.erg / u.s / u.cm ** 2 / u.angstrom)\n        conversion = conversion.to(u.erg / u.s / u.cm ** 2 / u.um)\n        teff = self.theta[0]\n        logg = self.theta[1]\n        z = self.theta[2]\n        select_teff = np.argmin((abs(teff - np.unique(self.star.teff))))\n        select_logg = np.argmin((abs(logg - np.unique(self.star.logg))))\n        select_z = np.argmin((abs(z - np.unique(self.star.z))))\n        sel_teff = int(np.unique(self.star.teff)[select_teff])\n        sel_logg = np.unique(self.star.logg)[select_logg]\n        sel_z = np.unique(self.star.z)[select_z]\n        sel_teff = str(sel_teff) if sel_teff >= 1e5 else '0{}'.format(sel_teff)\n        selected_SED = self.moddir + 'Coelho14/t' + sel_teff + '_g'\n        sel_logg = '+{:.1f}'.format(sel_logg) if sel_logg > 0 else '-0.5'\n        selected_SED += sel_logg\n        if sel_z < 0:\n            selected_SED += '_m{:02.0f}'.format(-sel_z * 10)\n        else:\n            selected_SED += '_p{:02.0f}'.format(sel_z * 10)\n\n        selected_SED = glob.glob(selected_SED + 'p0[04]_sed.fits')\n        selected_SED = selected_SED[0]\n        hdul = fits.open(selected_SED)\n        head = hdul[0].header\n        data = hdul[0].data\n        flux = data * conversion\n        CRVAL1 = head['CRVAL1']\n        CDEL1 = head['CDELT1']\n        wave = 10 ** np.array(\n            [CRVAL1 + CDEL1 * i for i in range(data.shape[0])])\n        wave *= u.angstrom.to(u.um)\n        return wave, flux\n\n    def __create_titles(self, titles, theta, theta_up, theta_lo):\n        new_titles = np.empty(titles.shape[0], dtype=object)\n        for i, param in enumerate(titles):\n            if param == 'teff':\n                new_titles[i] = r'Teff ='\n            if param == 'logg':\n                new_titles[i] = r'    Log g ='\n            if param == 'z':\n                new_titles[i] = r'        [Fe/H] ='\n            if param == 'dist':\n                new_titles[i] = r'    D ='\n            if param == 'rad':\n                new_titles[i] = r'R ='\n            if param == 'norm':\n                new_titles[i] = r'    (R/D)$^2$ ='\n            if param == 'Av':\n                new_titles[i] = r'Av ='\n            if param == 'inflation':\n                new_titles[i] = r'$\\sigma$ ='\n            if param == 'rad' or param == 'dist':\n                new_titles[i] += '{:.3f}'.format(theta[i])\n                new_titles[i] += r'$^{+' + \\\n                                 '{:.3f}'.format(theta_up[i] - theta[i])\n                new_titles[i] += r'}_{-' + \\\n                                 '{:.3f}'.format(theta[i] - theta_lo[i])\n                new_titles[i] += r'}$'\n            else:\n                new_titles[i] += '{:.2f}'.format(theta[i])\n                new_titles[i] += r'$^{+' + \\\n                                 '{:.2f}'.format(theta_up[i] - theta[i])\n                new_titles[i] += r'}_{-' + \\\n                                 '{:.2f}'.format(theta[i] - theta_lo[i])\n                new_titles[i] += r'}$'\n        return new_titles\n\n    def __create_labels(self, labels):\n        new_labels = np.empty(labels.shape[0], dtype=object)\n        for i, param in enumerate(labels):\n            if param == 'teff':\n                new_labels[i] = r'Teff (K)'\n            if param == 'logg':\n                new_labels[i] = r'Log g'\n            if param == 'z':\n                new_labels[i] = r'[Fe/H]'\n            if param == 'dist':\n                new_labels[i] = r'D (pc)'\n            if param == 'rad':\n                new_labels[i] = r'R $($R$_\\odot)$'\n            if param == 'norm':\n                new_labels[i] = r'(R/D)'\n            if param == 'Av':\n                new_labels[i] = r'Av'\n            if param == 'inflation':\n                new_labels[i] = r'$\\sigma$'\n        return new_labels\n\n    def __read_config(self):\n        \"\"\"Read plotter configuration file.\"\"\"\n        if self.settings_dir is None:\n            settings = open(filesdir + '/plot_settings.dat', 'r')\n        else:\n            settings = open(self.settings_dir, 'r')\n        for line in settings.readlines():\n            if line[0] == '#' or line[0] == '\\n':\n                continue\n            splt = line.split(' ')\n            attr = splt[0]\n            if attr == 'figsize':\n                vals = splt[1].split('\\n')[0].split(',')\n                val = (int(vals[0]), int(vals[1]))\n            elif attr == 'hr_figsize':\n                vals = splt[1].split('\\n')[0].split(',')\n                val = (int(vals[0]), int(vals[1]))\n            elif 'alpha' in attr:\n                val = float(splt[1].split('\\n')[0])\n            else:\n                try:\n                    val = int(splt[1].split('\\n')[0])\n                except ValueError:\n                    val = splt[1].split('\\n')[0]\n            setattr(self, attr, val)\n", "meta": {"hexsha": "c74b2be753dda81aaade13d2e41e0e13bc0c0a72", "size": 58212, "ext": "py", "lang": "Python", "max_stars_repo_path": "astroARIADNE/plotter.py", "max_stars_repo_name": "danhey/astroARIADNE", "max_stars_repo_head_hexsha": "1bce4684e565b89e9234c4693094480adf960f0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "astroARIADNE/plotter.py", "max_issues_repo_name": "danhey/astroARIADNE", "max_issues_repo_head_hexsha": "1bce4684e565b89e9234c4693094480adf960f0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "astroARIADNE/plotter.py", "max_forks_repo_name": "danhey/astroARIADNE", "max_forks_repo_head_hexsha": "1bce4684e565b89e9234c4693094480adf960f0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2264150943, "max_line_length": 80, "alphanum_fraction": 0.5057720058, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 13876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.19758572218337342}}
{"text": "# Copyright 2021 D-Wave Systems Inc.\n#\n#    Licensed under the Apache License, Version 2.0 (the \"License\");\n#    you may not use this file except in compliance with the License.\n#    You may obtain a copy of the License at\n#\n#        http://www.apache.org/licenses/LICENSE-2.0\n#\n#    Unless required by applicable law or agreed to in writing, software\n#    distributed under the License is distributed on an \"AS IS\" BASIS,\n#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#    See the License for the specific language governing permissions and\n#    limitations under the License.\n\nr\"\"\"This module contains a class that represents an influence path/functional.\n\"\"\"\n\n\n\n#####################################\n## Load libraries/packages/modules ##\n#####################################\n\n# For explicitly releasing memory.\nimport gc\n\n\n\n# For general array handling.\nimport numpy as np\n\n# For creating tensor networks.\nimport tensornetwork as tn\n\n\n\n# Assign an alias to the ``spinbosonchain`` library.\nimport spinbosonchain as sbc\n\n# For calculating the total two-point influence function.\nimport spinbosonchain._influence.twopt\n\n# For creating influence nodes and MPOs used to calculate the influence path.\nimport spinbosonchain._influence.tensorfactory\n\n# For applying MPO's to MPS's.\nimport spinbosonchain._mpomps\n\n# For shifting orthogonal centers of MPS's.\nimport spinbosonchain._qr\n\n\n\n############################\n## Authorship information ##\n############################\n\n__author__     = \"D-Wave Systems Inc.\"\n__copyright__  = \"Copyright 2021\"\n__credits__    = [\"Matthew Fitzpatrick\"]\n__maintainer__ = \"D-Wave Systems Inc.\"\n__email__      = \"support@dwavesys.com\"\n__status__     = \"Development\"\n\n\n\n##################################\n## Define classes and functions ##\n##################################\n\nclass PathPklPart():\n    def __init__(self, compress_params, alg):\n        # DM: Detailed manuscript.\n\n        # 'Pickle parts' can be saved to file in case of a crash and then\n        # subsequently recovered in a future run. See docs of method\n        # spinbosonchain.state.recover_and_resume for background information on\n        # pickles and simulation recovery.\n        \n        self.compress_params = compress_params\n        self.alg = alg  # yz- or z-noise algorithm?\n\n        self.n = 0  # Time step index.\n        self.m2 = 0\n        \n        # For caching purposes.\n        self.Xi_I_dashv_1_nodes = None  # Introduced in Eq. (143) of DM.\n        self.Xi_I_dashv_2_nodes = None  # Introduced in Eq. (143) of DM.\n        self.Xi_I_dashv_nodes = None  # Introduced in Eq. (143) of DM.\n        self.Xi_I_1_1_nodes = None  # Introduced in Eq. (126) of DM.\n        self.Xi_I_1_2_nodes = None  # Introduced in Eq. (126) of DM.\n\n        return None\n\n\n\nclass Path():\n    r\"\"\"This class represents a local influence path/functional, given by\n    Eq. (103) of the detailed manuscript (DM). For context read Sec. 4.3 and 4.4\n    of DM.\"\"\"\n    def __init__(self,\n                 r,  # Site index.\n                 system_model,\n                 bath_model,\n                 dt,  # Time step size.\n                 compress_params,\n                 pkl_parts=None):  # Used in loading/creating backups.\n        # DM: Detailed manuscript.\n\n        # 'Pickle parts' can be saved to file in case of a crash and then\n        # subsequently recovered in a future run. See docs of method\n        # spinbosonchain.state.recover_and_resume for background information on\n        # pickles and simulation recovery.\n        \n        # total_two_point_influence represents the quantity in Eq. (109) of DM.\n        total_two_point_influence = sbc._influence.twopt.Total(r,\n                                                               system_model,\n                                                               bath_model,\n                                                               dt,\n                                                               pkl_parts)\n\n        # This class generates the M-nodes given by Eq. (118) of DM.\n        InfluenceNodeRank3 = sbc._influence.tensorfactory.InfluenceNodeRank3\n\n        # This class generates the W-nodes given by Eqs. (120)-(123) of DM.\n        InfluenceMPO = sbc._influence.tensorfactory.InfluenceMPO\n        \n        influence_node_rank_3_factory = \\\n            InfluenceNodeRank3(total_two_point_influence)\n        self.influence_mpo_factory = \\\n            InfluenceMPO(total_two_point_influence)\n\n        # K_tau is given by Eq. (87) of DM.\n        K_tau = total_two_point_influence.z_bath.pkl_part.K_tau\n\n        # dm is given by Eq. (89) of DM.\n        dm = 3 if bath_model.y_spectral_densities is not None else 1\n\n        # mu_m_tau is given by Eq. (108) of DM.\n        self.mu_m_tau = lambda m: max(0, m-K_tau*dm+1)\n\n        # The 'first iteration procedure' involves executing Eqs. (130)-(137) of\n        # DM, whereas the 'second iteration procedure' involves executing\n        # Eqs. (146)-(154) of DM.\n        self.max_m2_in_first_iteration_procedure = lambda n: n*dm-2\n        self.max_m2_in_second_iteration_procedure = lambda n: (n+1)*dm-1\n\n        if pkl_parts is None:  # Create pickle part from scratch.\n            alg = total_two_point_influence.alg  # yz- or z-noise algorithm.\n            self.pkl_part = PathPklPart(compress_params, alg)\n\n            # M_r_1_0_I is given by Eq. (118) of DM with m2=0 and n=1.\n            M_r_1_0_I = influence_node_rank_3_factory.build(m=0, n=1)\n\n            # The quantities below are introduced in Eq. (126) of DM.\n            self.pkl_part.Xi_I_1_1_nodes = []\n            self.pkl_part.Xi_I_1_2_nodes = [M_r_1_0_I]\n        else:  # Reload pickle part from backup.\n            self.pkl_part = pkl_parts[\"influence_path\"]\n\n        return None\n\n\n\n    def reset_evolve_procedure(self, num_n_steps, k, forced_gc):\n        # DM: Detailed manuscript.\n\n        # The 'evolve procedure' refers to the step-evolution procedure\n        # implemented for the spinbosonchain.state.SystemState class, which\n        # represents the system state. An 'evolution step' consists of a\n        # sequence of 'k-steps', where in each k-step, a MPO is constructed\n        # which is applied to the MPS representing the system state [given by\n        # one of Eqs. (215)-(217) of DM depending on scenario]. Each of these\n        # MPO's requires a set of influence nodes taken from the MPS's\n        # representing the local influence paths. Details on the MPO\n        # construction procedure are given in Sec. 4.8 of DM. Instances of\n        # k-steps are given by Eqs. (219), (220), (221), (223), and (224) of\n        # DM. The current method here essentially calculates the required set of\n        # influence nodes to perform the first k-step of the current evolution\n        # step.\n\n        # The 'first iteration procedure' involves executing Eqs. (130)-(137) of\n        # DM, whereas the 'second iteration procedure' involves executing\n        # Eqs. (146)-(154) of DM.\n        n = self.pkl_part.n\n        m2 = max(0, self.max_m2_in_first_iteration_procedure(n)+1)\n        n += num_n_steps\n\n        self.pkl_part.n = n\n        self.pkl_part.m2 = m2\n\n        while self.first_m2_step_seq_in_reset_evolve_procedure_not_finished(k):\n            self.m2_step()\n            if forced_gc:\n                gc.collect()  # Enforce garbage collection.\n\n        if self.pkl_part.m2 <= self.max_m2_in_first_iteration_procedure(n):\n            return None\n\n        # At this point the first iteration procedure as finished, so the\n        # second procedure is initiated. The following code block is essentially\n        # Eq. (146) of DM.\n        self.pkl_part.Xi_I_dashv_1_nodes = []\n        self.pkl_part.Xi_I_dashv_2_nodes = self.pkl_part.Xi_I_1_2_nodes[:]\n\n        while self.second_m2_step_seq_in_reset_evolve_procedure_not_finished(k):\n            self.m2_step()\n            if forced_gc:\n                gc.collect()  # Enforce garbage collection.\n\n        return None\n\n\n\n    def first_m2_step_seq_in_reset_evolve_procedure_not_finished(self, k):\n        # See comments in method reset_evolve_procedure for context.\n\n        m2_limit = self.max_m2_in_first_iteration_procedure(self.pkl_part.n)\n        \n        if (k != -1) and (self.pkl_part.alg == \"yz-noise\"):\n            target_num_Xi_I_1_1_nodes = 3\n        else:\n            target_num_Xi_I_1_1_nodes = 1\n\n        num_Xi_I_1_1_nodes = len(self.pkl_part.Xi_I_1_1_nodes)\n\n        # If target_num_Xi_I_1_1_nodes of the Xi_I_1_1 nodes have been obtained\n        # before iterating through all the m2 steps of the 'first procedure',\n        # then the 'reset evolve procedure' is finished and we can proceed to\n        # executing our first 'k-step'. Otherwise, we iterate through all the m2\n        # steps of the first procedure.\n        \n        condition_1 = self.pkl_part.m2 <= m2_limit\n        condition_2 = num_Xi_I_1_1_nodes < target_num_Xi_I_1_1_nodes\n\n        return condition_1 and condition_2\n\n\n\n    def second_m2_step_seq_in_reset_evolve_procedure_not_finished(self, k):\n        # See comments in method reset_evolve_procedure for context.\n        \n        m2_limit = self.max_m2_in_second_iteration_procedure(self.pkl_part.n)\n        \n        if (k != -1) and (self.pkl_part.alg == \"yz-noise\"):\n            target_num_Xi_I_dashv_1_nodes = 3\n        else:\n            target_num_Xi_I_dashv_1_nodes = 1\n\n        num_Xi_I_dashv_1_nodes = len(self.pkl_part.Xi_I_dashv_1_nodes)\n\n        # If target_num_Xi_I_dashv_1_nodes of the Xi_I_1_1 nodes have been\n        # obtained before iterating through all the m2 steps of the 'second\n        # procedure', then the 'reset evolve procedure' is finished and we can\n        # proceed to executing our first 'k-step'. Otherwise, we iterate through\n        # all the m2 steps of the secon procedure.\n\n        condition_1 = self.pkl_part.m2 <= m2_limit\n        condition_2 = num_Xi_I_dashv_1_nodes < target_num_Xi_I_dashv_1_nodes\n\n        return condition_1 and condition_2\n\n\n    def k_step(self, forced_gc):\n        # DM: Detailed manuscript.\n\n        # An 'evolution step', wherein the system state is evolved, consists of\n        # a sequence of 'k-steps', where in each k-step, a MPO is constructed\n        # which is applied to the MPS representing the system state [given by\n        # one of Eqs. (215)-(217) of DM depending on scenario]. The role that\n        # the influence paths play in a single k-step is that they construct the\n        # set of influence nodes taken from the MPS's representing the local\n        # influence paths that are required to construct the aforementioned MPO\n        # for that k-step. Details on the MPO construction procedure are given\n        # in Sec. 4.8 of DM. Instances of k-steps are given by Eqs. (219),\n        # (220), (221), (223), and (224) of DM. \n\n        # The 'first iteration procedure' involves executing Eqs. (130)-(137) of\n        # DM, whereas the 'second iteration procedure' involves executing\n        # Eqs. (146)-(154) of DM.\n        n = self.pkl_part.n\n        max_m2_in_first_iteration_procedure_plus_1 = \\\n            self.max_m2_in_first_iteration_procedure(n)+1\n        max_m2_in_second_iteration_procedure = \\\n            self.max_m2_in_second_iteration_procedure(n)\n\n        if ((self.pkl_part.alg == \"z-noise\")\n            or (self.pkl_part.m2 == max_m2_in_second_iteration_procedure)):\n            num_m2_steps = 1  # The number of m2-steps taken in current k-step.\n        else:\n            num_m2_steps = 3  # The number of m2-steps taken in current k-step.\n\n        for _ in range(num_m2_steps):\n            self.m2_step()\n            if self.pkl_part.m2 == max_m2_in_first_iteration_procedure_plus_1:\n                # The following code block is essentially Eq. (146) of DM.\n                self.pkl_part.Xi_I_dashv_1_nodes = []\n                self.pkl_part.Xi_I_dashv_2_nodes = \\\n                    self.pkl_part.Xi_I_1_2_nodes[:]\n            if forced_gc:\n                gc.collect()  # Enforce garbage collection.\n\n        return None\n\n\n    \n    def m2_step(self):\n        # DM: Detailed manuscript.\n\n        # This method either performs a single 'm2-step' in the 'first\n        # procedure' which involves executing Eqs. (130)-(137) of DM, or the\n        # 'second procedure' which involves executing Eqs. (146)-(154) of DM.\n        \n        m2 = self.pkl_part.m2\n        n = self.pkl_part.n\n\n        if m2 <= self.max_m2_in_first_iteration_procedure(n):\n            mps_nodes = self.pkl_part.Xi_I_1_2_nodes\n        else:\n            mps_nodes = self.pkl_part.Xi_I_dashv_2_nodes\n\n        # The following code block implements Eq. (131) if in first procedure,\n        # and Eq. (147) if in second procedure.\n        node = tn.Node(np.ones([1, 4, 1]))\n        mps_nodes.append(node)\n        kwargs = {\"nodes\": mps_nodes,\n                  \"current_orthogonal_center_idx\": len(mps_nodes) - 2}\n        sbc._qr.shift_orthogonal_center_to_the_right(**kwargs)\n        mps_nodes[-1] /= tn.norm(mps_nodes[-1])\n\n        # Perform MPS compression for computational efficiency.\n        kwargs = {\"mpo_nodes\": self.influence_mpo_factory.build(m2+1, n),\n                  \"mps_nodes\": mps_nodes,\n                  \"compress_params\": self.pkl_part.compress_params}\n        sbc._mpomps.apply_finite_mpo_to_finite_mps_and_compress(**kwargs)\n\n        if m2 <= self.max_m2_in_first_iteration_procedure(n):\n            if self.mu_m_tau(m=m2+2) >= 1:\n                # This is essentially Eq. (137) of DM.\n                self.pkl_part.Xi_I_1_1_nodes.append(mps_nodes.pop(0))\n            # This is essentially Eq. (136) of DM.\n            self.pkl_part.Xi_I_1_2_nodes = mps_nodes\n        else:\n            if self.mu_m_tau(m=m2+2) >= 1:\n                # This is essentially Eq. (154) of DM.\n                self.pkl_part.Xi_I_dashv_1_nodes.append(mps_nodes.pop(0))\n            # This is essentially Eq. (153) of DM.\n            self.pkl_part.Xi_I_dashv_2_nodes = mps_nodes\n            # This is essentially Eq. (156) of DM.\n            self.pkl_part.Xi_I_dashv_nodes = \\\n                (self.pkl_part.Xi_I_dashv_1_nodes\n                 + self.pkl_part.Xi_I_dashv_2_nodes)\n\n        self.pkl_part.m2 += 1\n\n        return None\n        \n", "meta": {"hexsha": "424c7d04549d76b1c2225dc642a6c228563072c2", "size": 14219, "ext": "py", "lang": "Python", "max_stars_repo_path": "spinbosonchain/_influence/path.py", "max_stars_repo_name": "bonedog3000/spin-boson-chain", "max_stars_repo_head_hexsha": "8b8d4b91ed98d231be404b4de19ffe83dc2ace31", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spinbosonchain/_influence/path.py", "max_issues_repo_name": "bonedog3000/spin-boson-chain", "max_issues_repo_head_hexsha": "8b8d4b91ed98d231be404b4de19ffe83dc2ace31", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spinbosonchain/_influence/path.py", "max_forks_repo_name": "bonedog3000/spin-boson-chain", "max_forks_repo_head_hexsha": "8b8d4b91ed98d231be404b4de19ffe83dc2ace31", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-06T17:44:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-06T17:44:23.000Z", "avg_line_length": 39.717877095, "max_line_length": 80, "alphanum_fraction": 0.6299317814, "include": true, "reason": "import numpy", "num_tokens": 3516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.36658974324230986, "lm_q1q2_score": 0.19758572048381134}}
{"text": "#! /usr/bin/env python\n#\n\n\"\"\" Loading, transforming and comparing the corners of Camera CCDs.\"\"\"\n\nimport numpy as np\nfrom shapely import geometry\nfrom shapely import affinity\nfrom shapely.ops import cascaded_union\nfrom descartes import PolygonPatch\n\n\n##############################\n#                            #\n#  Camera Class              #\n#                            #\n##############################\n\nclass Camera:\n    \"\"\"\n    Class for collection and manipulation of a camera's CCD corner\n    coordinates. A list of CCD corner coordinates is inputted as a\n    *coordsList*, resulting in a shapely.geometry.multipolygon object\n    stored in *poly*. This *poly* can be geometrically translated and\n    rotated to model astronomical dither patterns.\n\n    Attributes:\n        coordsList : *list*\n            List of coordinates of the corners of each CCD in the camera.\n            The *coordsList* must follow these rules:\n\n            1) Coordinates are (ra, dec) numeric pairs of the angular\n               position of each camera's corners.\n            2) The *coordsList* must contain at least one CCD. If there\n               is only one CCD in the *coordsList*, then it must be passed\n               to the Camera as a list of length 1.\n            2) Each CCD in the *coordsList* must contain at least three\n               corners.\n            4) The CCDs in the *coordsList* CANNOT overlap.\n        name : *str*, optional\n            Name by which to identify a Camera.\n\n    Examples:\n        1) For a *coordsList* of two CCDs:\n            coordsList = [ [(0,0),(0,1),(1,1),(1,0)],\n                        [(2,2),(2,3),(3,3),(3,2)] ]\n            camera = Camera(coordsList)\n\n        2) For a *coordsList* of one CCD.\n            coordsList = [ [(0,0),(0,1),(1,1),(1,0)] ]\n            camera = Camera(coordsList)\n    \"\"\"\n\n    def __init__(self, coordsList, name=None):\n\n        if not isinstance(coordsList[0], list):\n            raise TypeError('coordsList must be a list of coordinates '\n                            'for the corners of each CCD in the camera.')\n\n        if name is not None and not isinstance(name, str):\n            raise TypeError('Camera name must be a string.')\n\n        # Combine corners of the CCDs in the coordsList into one poly\n        polys = []\n        for coords in coordsList:\n            polys.append(geometry.Polygon(coords))\n        self.poly = cascaded_union(polys)\n        self.name = name\n\n    @property\n    def poly(self):\n        return self.Poly\n\n    @poly.setter\n    def poly(self, newPoly):\n        \"\"\"\n        Sets the new poly and updates the Camera's coordsList\n\n        Parameters:\n            newPoly : *shapely.geometry.multipolygon.MultiPolygon*\n                       or\n                       *shapely.geometry.multipolygon.Polygon*\n                Sets the polygon for this Camera as *newPoly*, as well\n                as updating the *coordsList*.\n        \"\"\"\n        self.Poly = newPoly\n        self.coordsList = self.get_coordsList()\n\n    def get_coordsList(self):\n        \"\"\"\n        Returns the *coordsList* for THIS Camera's *poly*. This list will\n        follow the conventions for a *coordsList* as outlined in the\n        Camera Attributes.\n        \"\"\"\n        return self._get_coordsList(self.poly)\n\n    def _get_coordsList(self, poly):\n        \"\"\"\n        Returns the *coordsList* for ANY Camera's *poly*. This list will\n        follow the conventions for a *coordsList* as outlined in the\n        Camera Attributes.\n\n        Parameters:\n            poly : *shapely.geometry.multipolygon.MultiPolygon*\n                   or\n                   *shapely.geometry.multipolygon.Polygon*\n                Polygon from which a *coordsList* will be calculated.\n        \"\"\"\n        if poly.area == 0:\n            # If Camera is an empty polygon\n            coordsList = [[(0, 0), (0, 0), (0, 0)]]\n\n        elif poly.type == 'MultiPolygon':\n            # If Cameara is a collection of multiple polygons\n            coordsList = []\n            for p in poly:\n                coords = []\n                for x, y in p.exterior.coords:\n                    coords.append((x, y))\n                coordsList.append(coords)\n\n        elif poly.type == 'Polygon':\n            # If Camera is a single polygon\n            coords = []\n            for x, y in poly.exterior.coords:\n                coords.append((x, y))\n            coordsList = [coords]\n\n        return coordsList\n\n    def copy(self):\n        \"\"\"\n        Returns a copy of the current Camera.\n        \"\"\"\n        return Camera(self.coordsList)\n\n    def buffer(self, buffer, resolution=16):\n        \"\"\"\n        Expands the coundaries of each polygon in the Camera's *poly*\n        by the size of the *buffer*.\n        Parameters:\n            buffer : *float*\n                The number of degrees by which each polygon in *poly*\n                will be expanded.\n            resolution : *int*\n                The number of points added to the camera *poly* to\n                approximate the additional buffer\n        \"\"\"\n        self.poly = self.poly.buffer(buffer, resolution)\n\n    def expand_ra(self):\n        \"\"\"\n        Applys a spherical distortion to the Camera's coordinates to\n        adjust for the declination of the Camera's current position.\n        This function must be called AFTER geometric transformations\n        (translate, rotate) have been applied.\n        \"\"\"\n        centroid = self.get_center()\n        polys = []\n        for coords in self.coordsList:\n            new_coords = []\n            for (coordX, coordY) in coords:\n                coordX -= centroid[0]\n                coordX /= np.cos(np.radians(coordY))\n                coordX += centroid[0]\n                new_coords.append((coordX, coordY))\n            polys.append(geometry.Polygon(new_coords))\n        self.poly = cascaded_union(polys)\n\n    def collapse_ra(self):\n        \"\"\"\n        Applys a spherical distortion to the Camera's coordinates to\n        adjust for the declination of the Camera's current position.\n        This function must be called BEFORE geometric transformations\n        (translate, rotate) have been applied.\n        \"\"\"\n        centroid = self.get_center()\n        polys = []\n        for coords in self.coordsList:\n            new_coords = []\n            for (coordX, coordY) in coords:\n                coordX -= centroid[0]\n                coordX *= np.cos(np.radians(coordY))\n                coordX += centroid[0]\n                new_coords.append((coordX, coordY))\n            polys.append(geometry.Polygon(new_coords))\n        self.poly = cascaded_union(polys)\n\n    def rotate(self, degrees=0, origin=False):\n        \"\"\"\n        Rotates the Camera's *poly* by *degrees*. This is a rotation\n        around each polygon's center, not the origin (0,0). Rotation\n        can be performed around the origin by setting the *origin* flag to\n        True. Prior to and after rotation, *poly* is adjusted to account\n        for spherical distrotion effects at different declinations.\n\n        Parameters:\n            degrees : *float*\n                The number of degrees by which to rotate *poly*. Positive\n                angles are counter-clockwise and negative are clockwise\n                rotations.\n            origin : *bool*\n                Rotates the Camera's *poly* around the center of the *poly*\n                bounding box. If set to False, rotation will be performed\n                around the origin.\n        \"\"\"\n        self.collapse_ra()\n        if not origin:\n            self.poly = affinity.rotate(self.poly, degrees)\n        else:\n            self.poly = affinity.rotate(self.poly, degrees, origin=(0, 0))\n        self.expand_ra()\n\n    def translate(self, raOffset=0, decOffset=0):\n        \"\"\"\n        Translates the Camera's *poly* by *raOffset* and *decOffset*.\n        Prior to and after rotation, the Camera's *poly* is adjusted\n        to account for spherical  distrotion effects at different\n        declinations.\n\n        Parameters:\n            raOffset : *float*\n                The number of degrees by which to translate *poly* in\n                right ascension.\n            decOffset : *float*\n                The number of degrees by which to translate *poly* in\n                declination.\n        \"\"\"\n        self.collapse_ra()\n        self.poly = affinity.translate(self.poly,\n                                       xoff=raOffset,\n                                       yoff=decOffset)\n        self.expand_ra()\n\n    def get_radius(self):\n        \"\"\"\n        Returns the radius of the smallest circle which could encompass\n        all of the polygons in the Camera's *poly*. If the Camera's *poly*\n        is centered around (0,0), the radius is equal to the distance to\n        the polygon corner furthest from the Camera's center. Radius is\n        returned in degrees.\n        \"\"\"\n        center = self.get_center()\n        radius_list = []\n        for coords in self.coordsList:\n            for coord in coords:\n                radius = np.sqrt((coord[0] - center[0]) ** 2. +\n                                 (coord[1] - center[1]) ** 2.)\n                radius_list.append(radius)\n        return np.max(radius_list)\n\n    def get_area(self):\n        \"\"\"\n        Returns the total area of all polygons in the Camera's *poly*.\n        Area is returned in square degrees.\n        \"\"\"\n        return self.poly.area\n\n    def get_limits(self):\n        \"\"\"\n        Returns the coordinates of the smallest box which could surround\n        all of the polygons in the Camera's *poly*. Limits are returned\n        in degrees.\n\n        Returns:\n            ra_lim, dec_lim : *tuple* of *floats*\n                Two tuples, each containing the range of the Camera's *poly*\n                in right ascension and declination respectively.\n        \"\"\"\n        if self.poly.type == 'Polygon':\n            # If Camera is a single polygon\n            xArr = []\n            yArr = []\n            for x, y in self.poly.exterior.coords:\n                xArr.append(x)\n                yArr.append(y)\n        else:\n            # If Camera is a collection of multiple polygons\n            xArr = []\n            yArr = []\n            for poly in self.poly:\n                for x, y in poly.exterior.coords:\n                    xArr.append(x)\n                    yArr.append(y)\n\n        ra_lim = (min(xArr), max(xArr))\n        dec_lim = (min(yArr), max(yArr))\n\n        return ra_lim, dec_lim\n\n    def get_center(self, raOffset=0, decOffset=0):\n        \"\"\"\n        Returns the geometric center of the smallest box which could\n        surround all of the polygons in the Camera's *poly*. The center\n        is returned in degrees. User can apply a forced offset to the\n        right ascension or declination of the center if there is a known\n        asymmetry in the Camera's design.\n\n        Parameters:\n            raOffset : *float*\n                The number of degrees by which to offset the *poly* center\n                in right ascension.\n            decOffset : *float*\n                The number of degrees by which to offset the *poly* center\n                in declination.\n\n        Returns:\n            centerRa, centerDec : *float*\n                Two floats at the center location of the Camera's *poly*.\n        \"\"\"\n        bounds = self.poly.bounds\n        centerRa = np.mean([bounds[0], bounds[2]]) + raOffset\n        centerDec = np.mean([bounds[1], bounds[3]]) + decOffset\n        return centerRa, centerDec\n\n    def get_centroid(self, raOffset=0, decOffset=0):\n        \"\"\"\n        Returns the geometric centroid of the Camera's *poly*, as\n        calculated by the Shapely package. The centroid is returned in\n        degrees. User can apply a forced offset to the right ascension or\n        declination to the centroid if there is a known asymmetry in the\n        Camera's design.\n\n        Parameters:\n            raOffset : *float*\n                The number of degrees by which to offset the *poly*\n                centroid in right ascension.\n            decOffset : *float*\n                The number of degrees by which to offset the *poly*\n                centroid in declination.\n\n        Returns:\n            centroidRa, centroidDec : *float*\n                Two floats at the centroid location of the Camera's *poly*.\n        \"\"\"\n        if self.poly.type == 'Polygon':\n            for x, y in self.poly.centroid.coords:\n                return (x, y)\n        else:\n            centroidXList = []\n            centroidYList = []\n            for poly in self.poly:\n                for x, y in self.poly.centroid.coords:\n                    centroidXList.append(x)\n                    centroidYList.append(y)\n\n        centroidRa = np.mean(centroidXList) + raOffset\n        centroidDec = np.mean(centroidYList) + decOffset\n        return centroidRa, centroidDec\n\n    def intersect(self, camera):\n        \"\"\"\n        Calculates the intersection between this Camera's *poly* and the\n        *poly* of the *camera* passed as a parameter. The intersection is\n        then returned as a Camera object.\n\n        Parameters:\n            camera : *camera.Camera* object\n                An object from the camera.Camera class containing a *poly*\n                and a *coordsList*.\n\n        Returns:\n            camera : *camera.Camera* object\n                An object from the camera.Camera class that is the\n                intersection between this Camera and the *camera*\n                parameter.\n        \"\"\"\n        intersectPoly = self.poly.intersection(camera.poly)\n        coordsList = self._get_coordsList(intersectPoly)\n        return Camera(coordsList)\n\n    def union(self, camera):\n        \"\"\"\n        Calculates the union between this Camera's *poly* and the\n        *poly* of the *camera* passed as a parameter. The union is\n        then returned as a Camera object.\n\n        Parameters:\n            camera : *camera.Camera* object\n                An object from the camera.Camera class containing a *poly*\n                and a *coordsList*.\n\n        Returns:\n            camera : *camera.Camera* object\n                An object from the camera.Camera class that is the\n                union between this Camera and the *camera*\n                parameter.\n        \"\"\"\n        unionPoly = cascaded_union([self.poly, camera.poly])\n        coordsList = self._get_coordsList(unionPoly)\n        return Camera(coordsList)\n\n    def difference(self, camera):\n        \"\"\"\n        Calculates the difference between this Camera's *poly* and the\n        *poly* of the *camera* passed as a parameter. The difference is\n        then returned as a Camera object.\n\n        Parameters:\n            camera : *camera.Camera* object\n                An object from the camera.Camera class containing a *poly*\n                and a *coordsList*.\n\n        Returns:\n            camera : *camera.Camera* object\n                An object from the camera.Camera class that is the\n                difference between this Camera and the *camera*\n                parameter.\n        \"\"\"\n        differencePoly = self.poly.difference(camera.poly)\n        coordsList = self._get_coordsList(differencePoly)\n        return Camera(coordsList)\n\n    def plot(self, ax,\n             color='k',\n             alpha=0.5,\n             xlim=None,\n             ylim=None):\n        \"\"\"\n        Plots the Camera's *poly* onto an axis object from Matplotlib.\n        The user can specify the color and transparency of *poly*. Unless\n        the xlim and ylim of the Matplotlib axis is specified by the user,\n        this command will set the limits of the axis to surround just the\n        Camera's *poly*.\n\n        Parameters:\n            ax : *matplotlib.axes._subplots.AxesSubplot*\n                A Matplotlib axes object from the plt.subplots() command.\n            color : *str*\n                A color string compatible with a Matplotlib axis specifying\n                the color of the *poly*.\n            alpha : *float*\n                A number between 0 and 1 specifying the transparency of\n                the *poly*\n            xlim : *tuple* of *floats*\n                The range of x values with which to plot the *poly*\n            ylim : *tuple* of *floats*\n                The range of y values with which to plot the *poly*\n\n        Example:\n            1) For a single Camera object\n                camera = Camera(coordsList)\n                fig,ax = plt.subplots()\n                camera.plot(ax, color='g', alpha=0.3)\n\n            2) For multiple Camera objects\n                camera = Camera(coordsList)\n                camera2 = Camera(coordsList)\n                camera2.translate(raOffset=1.0)\n                fig,ax = plt.subplots()\n                camera.plot(ax,\n                            color='g',\n                            alpha=0.3,\n                            xlim=(-2,2),\n                            ylim=(-2,2))\n                camera2.plot(ax,\n                             color='b',\n                             alpha=0.3,\n                             xlim=(-2,2),\n                             ylim=(-2,2))\n        \"\"\"\n        ax.add_patch(PolygonPatch(self.poly,\n                                  fc=color,\n                                  alpha=alpha))\n\n        if xlim is None or ylim is None:\n            xlimPoly, ylimPoly = self.get_limits()\n\n        if xlim is None:\n            ax.set_xlim(xlimPoly)\n        else:\n            ax.set_xlim(xlim)\n\n        if ylim is None:\n            ax.set_ylim(ylimPoly)\n        else:\n            ax.set_ylim(ylim)\n\n\nemptyCamera = Camera([[(0, 0), (0, 0), (0, 0)]])\n\n\n##############################\n#                            #\n#  Return Known Cameras      #\n#                            #\n##############################\n\ndef return_machoCamera():\n    \"\"\"\n    Returns the CCD coordinates of the MACHO camera as a camera.Camera\n    object.\n    \"\"\"\n    from skysight import corners\n    corners = corners.load_machoCorners()\n    machoCamera = Camera([corners], name='macho')\n    return machoCamera\n\n\ndef return_hscCamera():\n    \"\"\"\n    Returns the CCD coordinates of the Hyper-Supreme Camera as a\n    camera.Camera object.\n    \"\"\"\n    from skysight import corners\n    corners = corners.load_hscCorners()\n    hscCamera = Camera(corners, name='hsc')\n    return hscCamera\n\n\ndef return_decamCamera():\n    \"\"\"\n    Returns the CCD coordinates of the Dark Energy Camera as a\n    camera.Camera object.\n    \"\"\"\n    from skysight import corners\n    corners = corners.load_decamCorners()\n    decamCamera = Camera(corners, name='decam')\n    return decamCamera\n", "meta": {"hexsha": "26c0dc8fb2b5c662d18af7f597d1e9327d56391b", "size": 18569, "ext": "py", "lang": "Python", "max_stars_repo_path": "skysight/camera.py", "max_stars_repo_name": "MichaelMedford/skysight", "max_stars_repo_head_hexsha": "121ac7134a3d45d5359243d95379ee1fa085532d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "skysight/camera.py", "max_issues_repo_name": "MichaelMedford/skysight", "max_issues_repo_head_hexsha": "121ac7134a3d45d5359243d95379ee1fa085532d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "skysight/camera.py", "max_forks_repo_name": "MichaelMedford/skysight", "max_forks_repo_head_hexsha": "121ac7134a3d45d5359243d95379ee1fa085532d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7096153846, "max_line_length": 76, "alphanum_fraction": 0.5529646185, "include": true, "reason": "import numpy", "num_tokens": 3885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.1975857167539666}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nColour\n======\n\n`Colour <https://github.com/colour-science/colour>`_ is an open-source\n`Python <https://www.python.org/>`_ package providing a comprehensive number of\nalgorithms and datasets for colour science.\n\nIt is freely available under the\n`New BSD License <https://opensource.org/licenses/BSD-3-Clause>`_ terms.\n\nSub-packages\n------------\n-   adaptation: Chromatic adaptation models and transformations.\n-   algebra: Algebra utilities.\n-   appearance: Colour appearance models.\n-   biochemistry: Biochemistry computations.\n-   blindness: Colour vision deficiency models.\n-   characterisation: Colour fitting and camera characterisation.\n-   colorimetry: Core objects for colour computations.\n-   constants: *CIE* and *CODATA* constants.\n-   continuous: Base objects for continuous data representation.\n-   contrast: Objects for contrast sensitivity computation.\n-   corresponding: Corresponding colour chromaticities computations.\n-   difference: Colour difference computations.\n-   examples: Examples for the sub-packages.\n-   graph: Graph for automatic colour conversions.\n-   io: Input / output objects for reading and writing data.\n-   models: Colour models.\n-   notation: Colour notation systems.\n-   phenomena: Computation of various optical phenomena.\n-   plotting: Diagrams, figures, etc...\n-   quality: Colour quality computation.\n-   recovery: Reflectance recovery.\n-   temperature: Colour temperature and correlated colour temperature\n    computation.\n-   utilities: Various utilities and data structures.\n-   volume: Colourspace volumes computation and optimal colour stimuli.\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport numpy as np\nimport sys\n\nfrom .utilities.deprecation import ModuleAPI, build_API_changes\nfrom .utilities.documentation import is_documentation_building\nfrom .utilities.common import (domain_range_scale, get_domain_range_scale,\n                               set_domain_range_scale)\n\nfrom .adaptation import (CHROMATIC_ADAPTATION_METHODS,\n                         CHROMATIC_ADAPTATION_TRANSFORMS,\n                         CMCCAT2000_VIEWING_CONDITIONS, chromatic_adaptation)\nfrom .algebra import (CubicSplineInterpolator, Extrapolator,\n                      KernelInterpolator, NearestNeighbourInterpolator,\n                      LinearInterpolator, NullInterpolator, PchipInterpolator,\n                      SpragueInterpolator, TABLE_INTERPOLATION_METHODS,\n                      kernel_cardinal_spline, kernel_lanczos, kernel_linear,\n                      kernel_nearest_neighbour, kernel_sinc,\n                      table_interpolation, lagrange_coefficients)\nfrom .colorimetry import (\n    ASTME308_PRACTISE_SHAPE, BANDPASS_CORRECTION_METHODS, CMFS,\n    DEFAULT_SPECTRAL_SHAPE, HUNTERLAB_ILLUMINANTS, ILLUMINANTS,\n    ILLUMINANTS_SDS, LEFS, LIGHTNESS_METHODS, LIGHT_SOURCES, LIGHT_SOURCES_SDS,\n    LMS_CMFS, LUMINANCE_METHODS, MULTI_SD_TO_XYZ_METHODS,\n    MultiSpectralDistributions, PHOTOPIC_LEFS, RGB_CMFS, SCOTOPIC_LEFS,\n    SD_GAUSSIAN_METHODS, SD_MULTI_LEDS_METHODS, SD_SINGLE_LED_METHODS,\n    SD_TO_XYZ_METHODS, STANDARD_OBSERVERS_CMFS, SpectralDistribution,\n    SpectralShape, WHITENESS_METHODS, YELLOWNESS_METHODS, bandpass_correction,\n    colorimetric_purity, complementary_wavelength, dominant_wavelength,\n    excitation_purity, lightness, luminance, luminous_efficacy,\n    luminous_efficiency, luminous_flux, multi_sds_to_XYZ,\n    sd_CIE_standard_illuminant_A, sd_CIE_illuminant_D_series, sd_blackbody,\n    sd_constant, sd_gaussian, sd_mesopic_luminous_efficiency_function,\n    sd_multi_leds, sd_ones, sd_single_led, sd_zeros, sd_to_XYZ,\n    wavelength_to_XYZ, whiteness, yellowness)\nfrom .blindness import (\n    CVD_MATRICES_MACHADO2010, anomalous_trichromacy_cmfs_Machado2009,\n    anomalous_trichromacy_matrix_Machado2009, cvd_matrix_Machado2009)\nfrom .appearance import (\n    ATD95_Specification, CAM16_Specification, CAM16_VIEWING_CONDITIONS,\n    CAM16_to_XYZ, CIECAM02_Specification, CIECAM02_VIEWING_CONDITIONS,\n    CIECAM02_to_XYZ, HUNT_VIEWING_CONDITIONS, Hunt_Specification,\n    LLAB_Specification, LLAB_VIEWING_CONDITIONS, Nayatani95_Specification,\n    RLAB_D_FACTOR, RLAB_Specification, RLAB_VIEWING_CONDITIONS, XYZ_to_ATD95,\n    XYZ_to_CAM16, XYZ_to_CIECAM02, XYZ_to_Hunt, XYZ_to_LLAB, XYZ_to_Nayatani95,\n    XYZ_to_RLAB)\nfrom .difference import DELTA_E_METHODS, delta_E\nfrom .characterisation import (\n    CAMERAS_RGB_SPECTRAL_SENSITIVITIES, COLOURCHECKERS, COLOURCHECKERS_SDS,\n    DISPLAYS_RGB_PRIMARIES, POLYNOMIAL_EXPANSION_METHODS, polynomial_expansion,\n    COLOUR_CORRECTION_MATRIX_METHODS, colour_correction_matrix,\n    COLOUR_CORRECTION_METHODS, colour_correction)\nfrom .io import (LUT1D, LUT3x1D, LUT3D, LUTSequence, READ_IMAGE_METHODS,\n                 SpectralDistribution_IESTM2714, WRITE_IMAGE_METHODS,\n                 read_image, read_LUT, read_sds_from_csv_file,\n                 read_sds_from_xrite_file, read_spectral_data_from_csv_file,\n                 write_image, write_LUT, write_sds_to_csv_file)\nfrom .models import (\n    CAM02LCD_to_JMh_CIECAM02, CAM02SCD_to_JMh_CIECAM02,\n    CAM02UCS_to_JMh_CIECAM02, CAM16LCD_to_JMh_CAM16, CAM16SCD_to_JMh_CAM16,\n    CAM16UCS_to_JMh_CAM16, CCTF_DECODINGS, CCTF_ENCODINGS, CMYK_to_CMY,\n    CMY_to_CMYK, CMY_to_RGB, CV_range, DIN99_to_Lab, EOTFS, EOTF_INVERSES,\n    HDR_CIELAB_METHODS, HDR_IPT_METHODS, HSL_to_RGB, HSV_to_RGB,\n    Hunter_Lab_to_XYZ, Hunter_Rdab_to_XYZ, ICTCP_to_RGB, IPT_hue_angle,\n    IPT_to_XYZ, JMh_CAM16_to_CAM16LCD, JMh_CAM16_to_CAM16SCD,\n    JMh_CAM16_to_CAM16UCS, JMh_CIECAM02_to_CAM02LCD, JMh_CIECAM02_to_CAM02SCD,\n    JMh_CIECAM02_to_CAM02UCS, JzAzBz_to_XYZ, LCHab_to_Lab, LCHuv_to_Luv,\n    LOG_DECODINGS, LOG_ENCODINGS, Lab_to_DIN99, Lab_to_LCHab, Lab_to_XYZ,\n    Luv_to_LCHuv, Luv_to_XYZ, Luv_to_uv, Luv_uv_to_xy,\n    MACADAM_1942_ELLIPSES_DATA, OETFS, OETF_INVERSES, OOTFS, OOTF_INVERSES,\n    OSA_UCS_to_XYZ, POINTER_GAMUT_BOUNDARIES, POINTER_GAMUT_DATA,\n    POINTER_GAMUT_ILLUMINANT, Prismatic_to_RGB, RGB_COLOURSPACES,\n    RGB_Colourspace, RGB_luminance, RGB_luminance_equation, RGB_to_CMY,\n    RGB_to_HSL, RGB_to_HSV, RGB_to_ICTCP, RGB_to_Prismatic, RGB_to_RGB,\n    RGB_to_RGB_matrix, RGB_to_XYZ, RGB_to_YCbCr, RGB_to_YcCbcCrc, RGB_to_YCoCg,\n    UCS_to_XYZ, UCS_to_uv, UCS_uv_to_xy, UVW_to_XYZ, XYZ_to_Hunter_Lab,\n    XYZ_to_Hunter_Rdab, XYZ_to_IPT, XYZ_to_JzAzBz, XYZ_to_K_ab_HunterLab1966,\n    XYZ_to_Lab, XYZ_to_Luv, XYZ_to_OSA_UCS, XYZ_to_RGB, XYZ_to_UCS, XYZ_to_UVW,\n    XYZ_to_hdr_CIELab, XYZ_to_hdr_IPT, XYZ_to_sRGB, XYZ_to_xy, XYZ_to_xyY,\n    YCBCR_WEIGHTS, YCbCr_to_RGB, YcCbcCrc_to_RGB, YCoCg_to_RGB, cctf_decoding,\n    cctf_encoding, chromatically_adapted_primaries, eotf, eotf_inverse,\n    full_to_legal, gamma_function, hdr_CIELab_to_XYZ, hdr_IPT_to_XYZ,\n    legal_to_full, linear_function, log_decoding, log_encoding,\n    normalised_primary_matrix, oetf, oetf_inverse, ootf, ootf_inverse,\n    primaries_whitepoint, sd_to_aces_relative_exposure_values, sRGB_to_XYZ,\n    uv_to_Luv, uv_to_UCS, xyY_to_XYZ, xyY_to_xy, xy_to_Luv_uv, xy_to_UCS_uv,\n    xy_to_XYZ, xy_to_xyY)\nfrom .corresponding import (\n    BRENEMAN_EXPERIMENTS, BRENEMAN_EXPERIMENTS_PRIMARIES_CHROMATICITIES,\n    CORRESPONDING_CHROMATICITIES_PREDICTION_MODELS, CorrespondingColourDataset,\n    CorrespondingChromaticitiesPrediction,\n    corresponding_chromaticities_prediction)\nfrom .contrast import (CONTRAST_SENSITIVITY_METHODS,\n                       contrast_sensitivity_function)\nfrom .phenomena import (rayleigh_scattering, scattering_cross_section,\n                        sd_rayleigh_scattering)\nfrom .notation import (MUNSELL_COLOURS, MUNSELL_VALUE_METHODS,\n                       munsell_colour_to_xyY, munsell_value,\n                       xyY_to_munsell_colour)\nfrom .quality import (COLOUR_QUALITY_SCALE_METHODS, colour_quality_scale,\n                      colour_rendering_index)\nfrom .recovery import XYZ_TO_SD_METHODS, XYZ_to_sd\nfrom .temperature import (CCT_TO_UV_METHODS, CCT_TO_XY_METHODS, CCT_to_uv,\n                          CCT_to_xy, UV_TO_CCT_METHODS, XY_TO_CCT_METHODS,\n                          uv_to_CCT, xy_to_CCT)\nfrom .volume import (\n    ILLUMINANTS_OPTIMAL_COLOUR_STIMULI, RGB_colourspace_limits,\n    RGB_colourspace_pointer_gamut_coverage_MonteCarlo,\n    RGB_colourspace_visible_spectrum_coverage_MonteCarlo,\n    RGB_colourspace_volume_MonteCarlo,\n    RGB_colourspace_volume_coverage_MonteCarlo, is_within_macadam_limits,\n    is_within_mesh_volume, is_within_pointer_gamut, is_within_visible_spectrum)\nfrom .graph import describe_conversion_path, convert\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2019 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-developers@colour-science.org'\n__status__ = 'Production'\n\n__all__ = [\n    'domain_range_scale', 'get_domain_range_scale', 'set_domain_range_scale'\n]\n__all__ += [\n    'CHROMATIC_ADAPTATION_METHODS', 'CHROMATIC_ADAPTATION_TRANSFORMS',\n    'CMCCAT2000_VIEWING_CONDITIONS', 'chromatic_adaptation'\n]\n__all__ += [\n    'CubicSplineInterpolator', 'Extrapolator', 'KernelInterpolator',\n    'NearestNeighbourInterpolator', 'LinearInterpolator', 'NullInterpolator',\n    'PchipInterpolator', 'SpragueInterpolator', 'TABLE_INTERPOLATION_METHODS',\n    'kernel_cardinal_spline', 'kernel_lanczos', 'kernel_linear',\n    'kernel_nearest_neighbour', 'kernel_sinc', 'table_interpolation',\n    'lagrange_coefficients'\n]\n__all__ += [\n    'ASTME308_PRACTISE_SHAPE', 'BANDPASS_CORRECTION_METHODS', 'CMFS',\n    'DEFAULT_SPECTRAL_SHAPE', 'HUNTERLAB_ILLUMINANTS', 'ILLUMINANTS',\n    'ILLUMINANTS_SDS', 'LEFS', 'LIGHTNESS_METHODS', 'LIGHT_SOURCES',\n    'LIGHT_SOURCES_SDS', 'LMS_CMFS', 'LUMINANCE_METHODS',\n    'MULTI_SD_TO_XYZ_METHODS', 'MultiSpectralDistributions', 'PHOTOPIC_LEFS',\n    'RGB_CMFS', 'SCOTOPIC_LEFS', 'SD_GAUSSIAN_METHODS',\n    'SD_MULTI_LEDS_METHODS', 'SD_SINGLE_LED_METHODS', 'SD_TO_XYZ_METHODS',\n    'STANDARD_OBSERVERS_CMFS', 'SpectralDistribution', 'SpectralShape',\n    'WHITENESS_METHODS', 'YELLOWNESS_METHODS', 'bandpass_correction',\n    'colorimetric_purity', 'complementary_wavelength', 'dominant_wavelength',\n    'excitation_purity', 'lightness', 'luminance', 'luminous_efficacy',\n    'luminous_efficiency', 'luminous_flux', 'multi_sds_to_XYZ',\n    'sd_CIE_standard_illuminant_A', 'sd_CIE_illuminant_D_series',\n    'sd_blackbody', 'sd_constant', 'sd_gaussian',\n    'sd_mesopic_luminous_efficiency_function', 'sd_multi_leds', 'sd_ones',\n    'sd_zeros', 'sd_single_led', 'sd_to_XYZ', 'wavelength_to_XYZ', 'whiteness',\n    'yellowness'\n]\n__all__ += [\n    'CVD_MATRICES_MACHADO2010', 'anomalous_trichromacy_cmfs_Machado2009',\n    'anomalous_trichromacy_matrix_Machado2009', 'cvd_matrix_Machado2009'\n]\n__all__ += [\n    'ATD95_Specification', 'CAM16_Specification', 'CAM16_VIEWING_CONDITIONS',\n    'CAM16_to_XYZ', 'CIECAM02_Specification', 'CIECAM02_VIEWING_CONDITIONS',\n    'CIECAM02_to_XYZ', 'HUNT_VIEWING_CONDITIONS', 'Hunt_Specification',\n    'LLAB_Specification', 'LLAB_VIEWING_CONDITIONS',\n    'Nayatani95_Specification', 'RLAB_D_FACTOR', 'RLAB_Specification',\n    'RLAB_VIEWING_CONDITIONS', 'XYZ_to_ATD95', 'XYZ_to_CAM16',\n    'XYZ_to_CIECAM02', 'XYZ_to_Hunt', 'XYZ_to_LLAB', 'XYZ_to_Nayatani95',\n    'XYZ_to_RLAB'\n]\n__all__ += ['DELTA_E_METHODS', 'delta_E']\n__all__ += [\n    'CAMERAS_RGB_SPECTRAL_SENSITIVITIES', 'COLOURCHECKERS',\n    'COLOURCHECKERS_SDS', 'DISPLAYS_RGB_PRIMARIES',\n    'POLYNOMIAL_EXPANSION_METHODS', 'polynomial_expansion',\n    'COLOUR_CORRECTION_MATRIX_METHODS', 'colour_correction_matrix',\n    'COLOUR_CORRECTION_METHODS', 'colour_correction'\n]\n__all__ += [\n    'LUT1D', 'LUT3x1D', 'LUT3D', 'LUTSequence', 'READ_IMAGE_METHODS',\n    'SpectralDistribution_IESTM2714', 'WRITE_IMAGE_METHODS', 'read_image',\n    'read_LUT', 'read_sds_from_csv_file', 'read_sds_from_xrite_file',\n    'read_spectral_data_from_csv_file', 'write_image', 'write_LUT',\n    'write_sds_to_csv_file'\n]\n__all__ += [\n    'CAM02LCD_to_JMh_CIECAM02', 'CAM02SCD_to_JMh_CIECAM02',\n    'CAM02UCS_to_JMh_CIECAM02', 'CAM16LCD_to_JMh_CAM16',\n    'CAM16SCD_to_JMh_CAM16', 'CAM16UCS_to_JMh_CAM16', 'CCTF_DECODINGS',\n    'CCTF_ENCODINGS', 'CMYK_to_CMY', 'CMY_to_CMYK', 'CMY_to_RGB', 'CV_range',\n    'DIN99_to_Lab', 'EOTFS', 'EOTF_INVERSES', 'HDR_CIELAB_METHODS',\n    'HDR_IPT_METHODS', 'HSL_to_RGB', 'HSV_to_RGB', 'Hunter_Lab_to_XYZ',\n    'Hunter_Rdab_to_XYZ', 'ICTCP_to_RGB', 'IPT_hue_angle', 'IPT_to_XYZ',\n    'JMh_CAM16_to_CAM16LCD', 'JMh_CAM16_to_CAM16SCD', 'JMh_CAM16_to_CAM16UCS',\n    'JMh_CIECAM02_to_CAM02LCD', 'JMh_CIECAM02_to_CAM02SCD',\n    'JMh_CIECAM02_to_CAM02UCS', 'JzAzBz_to_XYZ', 'LCHab_to_Lab',\n    'LCHuv_to_Luv', 'LOG_DECODINGS', 'LOG_ENCODINGS', 'Lab_to_DIN99',\n    'Lab_to_LCHab', 'Lab_to_XYZ', 'Luv_to_LCHuv', 'Luv_to_XYZ', 'Luv_to_uv',\n    'Luv_uv_to_xy', 'OETFS', 'OETF_INVERSES', 'OOTFS',\n    'MACADAM_1942_ELLIPSES_DATA', 'OOTF_INVERSES', 'OSA_UCS_to_XYZ',\n    'POINTER_GAMUT_BOUNDARIES', 'POINTER_GAMUT_DATA',\n    'POINTER_GAMUT_ILLUMINANT', 'Prismatic_to_RGB', 'RGB_COLOURSPACES',\n    'RGB_Colourspace', 'RGB_luminance', 'RGB_luminance_equation', 'RGB_to_CMY',\n    'RGB_to_HSL', 'RGB_to_HSV', 'RGB_to_ICTCP', 'RGB_to_Prismatic',\n    'RGB_to_RGB', 'RGB_to_RGB_matrix', 'RGB_to_XYZ', 'RGB_to_YCbCr',\n    'RGB_to_YcCbcCrc', 'RGB_to_YCoCg', 'UCS_to_XYZ', 'UCS_to_uv',\n    'UCS_uv_to_xy', 'UVW_to_XYZ', 'XYZ_to_Hunter_Lab', 'XYZ_to_Hunter_Rdab',\n    'XYZ_to_IPT', 'XYZ_to_JzAzBz', 'XYZ_to_K_ab_HunterLab1966', 'XYZ_to_Lab',\n    'XYZ_to_Luv', 'XYZ_to_OSA_UCS', 'XYZ_to_RGB', 'XYZ_to_UCS', 'XYZ_to_UVW',\n    'XYZ_to_hdr_CIELab', 'XYZ_to_hdr_IPT', 'XYZ_to_sRGB', 'XYZ_to_xy',\n    'XYZ_to_xyY', 'YCBCR_WEIGHTS', 'YCbCr_to_RGB', 'YcCbcCrc_to_RGB',\n    'YCoCg_to_RGB', 'cctf_decoding', 'cctf_encoding',\n    'chromatically_adapted_primaries', 'eotf', 'eotf_inverse', 'full_to_legal',\n    'gamma_function', 'hdr_CIELab_to_XYZ', 'hdr_IPT_to_XYZ', 'legal_to_full',\n    'linear_function', 'log_decoding', 'log_encoding',\n    'normalised_primary_matrix', 'oetf', 'oetf_inverse', 'ootf',\n    'ootf_inverse', 'primaries_whitepoint',\n    'sd_to_aces_relative_exposure_values', 'sRGB_to_XYZ', 'uv_to_Luv',\n    'uv_to_UCS', 'xyY_to_XYZ', 'xyY_to_xy', 'xy_to_Luv_uv', 'xy_to_UCS_uv',\n    'xy_to_XYZ', 'xy_to_xyY'\n]\n__all__ += [\n    'BRENEMAN_EXPERIMENTS', 'BRENEMAN_EXPERIMENTS_PRIMARIES_CHROMATICITIES',\n    'CORRESPONDING_CHROMATICITIES_PREDICTION_MODELS',\n    'CorrespondingColourDataset', 'CorrespondingChromaticitiesPrediction',\n    'corresponding_chromaticities_prediction'\n]\n__all__ += ['CONTRAST_SENSITIVITY_METHODS', 'contrast_sensitivity_function']\n__all__ += [\n    'rayleigh_scattering', 'scattering_cross_section', 'sd_rayleigh_scattering'\n]\n__all__ += [\n    'MUNSELL_COLOURS', 'MUNSELL_VALUE_METHODS', 'munsell_colour_to_xyY',\n    'munsell_value', 'xyY_to_munsell_colour'\n]\n__all__ += [\n    'COLOUR_QUALITY_SCALE_METHODS', 'colour_quality_scale',\n    'colour_rendering_index'\n]\n__all__ += ['XYZ_TO_SD_METHODS', 'XYZ_to_sd']\n__all__ += [\n    'CCT_TO_UV_METHODS', 'CCT_TO_XY_METHODS', 'CCT_to_uv', 'CCT_to_xy',\n    'UV_TO_CCT_METHODS', 'XY_TO_CCT_METHODS', 'uv_to_CCT', 'xy_to_CCT'\n]\n__all__ += [\n    'ILLUMINANTS_OPTIMAL_COLOUR_STIMULI', 'RGB_colourspace_limits',\n    'RGB_colourspace_pointer_gamut_coverage_MonteCarlo',\n    'RGB_colourspace_visible_spectrum_coverage_MonteCarlo',\n    'RGB_colourspace_volume_MonteCarlo',\n    'RGB_colourspace_volume_coverage_MonteCarlo', 'is_within_macadam_limits',\n    'is_within_mesh_volume', 'is_within_pointer_gamut',\n    'is_within_visible_spectrum'\n]\n__all__ += ['describe_conversion_path', 'convert']\n\n__application_name__ = 'Colour'\n\n__major_version__ = '0'\n__minor_version__ = '3'\n__change_version__ = '14'\n__version__ = '.'.join(\n    (__major_version__,\n     __minor_version__,\n     __change_version__))  # yapf: disable\n\n# TODO: Remove legacy printing support when deemed appropriate.\ntry:\n    np.set_printoptions(legacy='1.13')\nexcept TypeError:  # pragma: no cover\n    pass\n\n\n# ----------------------------------------------------------------------------#\n# ---                API Changes and Deprecation Management                ---#\n# ----------------------------------------------------------------------------#\nclass colour(ModuleAPI):\n    def __getattr__(self, attribute):\n        return super(colour, self).__getattr__(attribute)\n\n\ncolour.__application_name__ = __application_name__\n\ncolour.__major_version__ = __major_version__\ncolour.__minor_version__ = __minor_version__\ncolour.__change_version__ = __change_version__\ncolour.__version__ = __version__\n\n# v0.3.11\nAPI_CHANGES = {\n    'ObjectFutureAccessChange': [\n        [\n            'colour.ACES_2065_1_COLOURSPACE',\n            'colour.models.ACES_2065_1_COLOURSPACE',\n        ],\n        [\n            'colour.ACES_CCT_COLOURSPACE',\n            'colour.models.ACES_CCT_COLOURSPACE',\n        ],\n        [\n            'colour.ACES_CC_COLOURSPACE',\n            'colour.models.ACES_CC_COLOURSPACE',\n        ],\n        [\n            'colour.ACES_CG_COLOURSPACE',\n            'colour.models.ACES_CG_COLOURSPACE',\n        ],\n        [\n            'colour.ACES_PROXY_COLOURSPACE',\n            'colour.models.ACES_PROXY_COLOURSPACE',\n        ],\n        [\n            'colour.ACES_RICD',\n            'colour.models.ACES_RICD',\n        ],\n        [\n            'colour.ADOBE_RGB_1998_COLOURSPACE',\n            'colour.models.ADOBE_RGB_1998_COLOURSPACE',\n        ],\n        [\n            'colour.ADOBE_WIDE_GAMUT_RGB_COLOURSPACE',\n            'colour.models.ADOBE_WIDE_GAMUT_RGB_COLOURSPACE',\n        ],\n        [\n            'colour.ALEXA_WIDE_GAMUT_COLOURSPACE',\n            'colour.models.ALEXA_WIDE_GAMUT_COLOURSPACE',\n        ],\n        [\n            'colour.APPLE_RGB_COLOURSPACE',\n            'colour.models.APPLE_RGB_COLOURSPACE',\n        ],\n        [\n            'colour.AVOGADRO_CONSTANT',\n            'colour.constants.AVOGADRO_CONSTANT',\n        ],\n        [\n            'colour.AbstractContinuousFunction',\n            'colour.continuous.AbstractContinuousFunction',\n        ],\n        [\n            'colour.BEST_RGB_COLOURSPACE',\n            'colour.models.BEST_RGB_COLOURSPACE',\n        ],\n        [\n            'colour.BETA_RGB_COLOURSPACE',\n            'colour.models.BETA_RGB_COLOURSPACE',\n        ],\n        [\n            'colour.BOLTZMANN_CONSTANT',\n            'colour.constants.BOLTZMANN_CONSTANT',\n        ],\n        [\n            'colour.BRADFORD_CAT',\n            'colour.adaptation.BRADFORD_CAT',\n        ],\n        [\n            'colour.BS_CAT',\n            'colour.adaptation.BS_CAT',\n        ],\n        [\n            'colour.BS_PC_CAT',\n            'colour.adaptation.BS_PC_CAT',\n        ],\n        [\n            'colour.BT2020_COLOURSPACE',\n            'colour.models.BT2020_COLOURSPACE',\n        ],\n        [\n            'colour.BT470_525_COLOURSPACE',\n            'colour.models.BT470_525_COLOURSPACE',\n        ],\n        [\n            'colour.BT470_625_COLOURSPACE',\n            'colour.models.BT470_625_COLOURSPACE',\n        ],\n        [\n            'colour.BT709_COLOURSPACE',\n            'colour.models.BT709_COLOURSPACE',\n        ],\n        [\n            'colour.CAM16_InductionFactors',\n            'colour.appearance.CAM16_InductionFactors',\n        ],\n        [\n            'colour.CAT02_BRILL_CAT',\n            'colour.adaptation.CAT02_BRILL_CAT',\n        ],\n        [\n            'colour.CAT02_CAT',\n            'colour.adaptation.CAT02_CAT',\n        ],\n        [\n            'colour.CCT_to_uv_Krystek1985',\n            'colour.temperature.CCT_to_uv_Krystek1985',\n        ],\n        [\n            'colour.CCT_to_uv_Ohno2013',\n            'colour.temperature.CCT_to_uv_Ohno2013',\n        ],\n        [\n            'colour.CCT_to_uv_Robertson1968',\n            'colour.temperature.CCT_to_uv_Robertson1968',\n        ],\n        [\n            'colour.CCT_to_xy_CIE_D',\n            'colour.temperature.CCT_to_xy_CIE_D',\n        ],\n        [\n            'colour.CCT_to_xy_Kang2002',\n            'colour.temperature.CCT_to_xy_Kang2002',\n        ],\n        [\n            'colour.CIECAM02_InductionFactors',\n            'colour.appearance.CIECAM02_InductionFactors',\n        ],\n        [\n            'colour.CIE_RGB_COLOURSPACE',\n            'colour.models.CIE_RGB_COLOURSPACE',\n        ],\n        [\n            'colour.CINEMA_GAMUT_COLOURSPACE',\n            'colour.models.CINEMA_GAMUT_COLOURSPACE',\n        ],\n        [\n            'colour.CMCCAT2000_CAT',\n            'colour.adaptation.CMCCAT2000_CAT',\n        ],\n        [\n            'colour.CMCCAT2000_InductionFactors',\n            'colour.adaptation.CMCCAT2000_InductionFactors',\n        ],\n        [\n            'colour.CMCCAT97_CAT',\n            'colour.adaptation.CMCCAT97_CAT',\n        ],\n        [\n            'colour.COLOR_MATCH_RGB_COLOURSPACE',\n            'colour.models.COLOR_MATCH_RGB_COLOURSPACE',\n        ],\n        [\n            'colour.COLOURCHECKER_INDEXES_TO_NAMES_MAPPING',\n            'colour.characterisation.COLOURCHECKER_INDEXES_TO_NAMES_MAPPING',\n        ],\n        [\n            'colour.COLOURSPACE_MODELS',\n            'colour.models.COLOURSPACE_MODELS',\n        ],\n        [\n            'colour.COLOURSPACE_MODELS_LABELS',\n            'colour.models.COLOURSPACE_MODELS_AXIS_LABELS',\n        ],\n        [\n            'colour.CQS_Specification',\n            'colour.quality.CQS_Specification',\n        ],\n        [\n            'colour.CRI_Specification',\n            'colour.quality.CRI_Specification',\n        ],\n        [\n            'colour.CaseInsensitiveMapping',\n            'colour.utilities.CaseInsensitiveMapping',\n        ],\n        [\n            'colour.ColourWarning',\n            'colour.utilities.ColourWarning',\n        ],\n        [\n            'colour.DCI_P3_COLOURSPACE',\n            'colour.models.DCI_P3_COLOURSPACE',\n        ],\n        [\n            'colour.DCI_P3_P_COLOURSPACE',\n            'colour.models.DCI_P3_P_COLOURSPACE',\n        ],\n        [\n            'colour.DEFAULT_FLOAT_DTYPE',\n            'colour.constants.DEFAULT_FLOAT_DTYPE',\n        ],\n        [\n            'colour.DON_RGB_4_COLOURSPACE',\n            'colour.models.DON_RGB_4_COLOURSPACE',\n        ],\n        [\n            'colour.DRAGON_COLOR_2_COLOURSPACE',\n            'colour.models.DRAGON_COLOR_2_COLOURSPACE',\n        ],\n        [\n            'colour.DRAGON_COLOR_COLOURSPACE',\n            'colour.models.DRAGON_COLOR_COLOURSPACE',\n        ],\n        [\n            'colour.D_ILLUMINANTS_S_SPDS',\n            'colour.colorimetry.D_ILLUMINANTS_S_SDS',\n        ],\n        [\n            'colour.ECI_RGB_V2_COLOURSPACE',\n            'colour.models.ECI_RGB_V2_COLOURSPACE',\n        ],\n        [\n            'colour.EKTA_SPACE_PS_5_COLOURSPACE',\n            'colour.models.EKTA_SPACE_PS_5_COLOURSPACE',\n        ],\n        [\n            'colour.EPSILON',\n            'colour.constants.EPSILON',\n        ],\n        [\n            'colour.ERIMM_RGB_COLOURSPACE',\n            'colour.models.ERIMM_RGB_COLOURSPACE',\n        ],\n        [\n            'colour.FAIRCHILD_CAT',\n            'colour.adaptation.FAIRCHILD_CAT',\n        ],\n        [\n            'colour.FLOATING_POINT_NUMBER_PATTERN',\n            'colour.constants.FLOATING_POINT_NUMBER_PATTERN',\n        ],\n        [\n            'colour.Hunt_InductionFactors',\n            'colour.appearance.Hunt_InductionFactors',\n        ],\n        [\n            'colour.INTEGER_THRESHOLD',\n            'colour.constants.INTEGER_THRESHOLD',\n        ],\n        [\n            'colour.KP_M',\n            'colour.constants.KP_M',\n        ],\n        [\n            'colour.K_M',\n            'colour.constants.K_M',\n        ],\n        [\n            'colour.LIGHT_SPEED',\n            'colour.constants.LIGHT_SPEED',\n        ],\n        [\n            'colour.LLAB_InductionFactors',\n            'colour.appearance.LLAB_InductionFactors',\n        ],\n        [\n            'colour.LMS_10_degree_cmfs_to_XYZ_10_degree_cmfs',\n            'colour.colorimetry.LMS_10_degree_cmfs_to_XYZ_10_degree_cmfs',\n        ],\n        [\n            'colour.LMS_2_degree_cmfs_to_XYZ_2_degree_cmfs',\n            'colour.colorimetry.LMS_2_degree_cmfs_to_XYZ_2_degree_cmfs',\n        ],\n        [\n            'colour.LMS_ConeFundamentals',\n            'colour.colorimetry.LMS_ConeFundamentals',\n        ],\n        [\n            'colour.LineSegmentsIntersections_Specification',\n            'colour.algebra.LineSegmentsIntersections_Specification',\n        ],\n        [\n            'colour.Lookup',\n            'colour.utilities.Lookup',\n        ],\n        [\n            'colour.MAX_RGB_COLOURSPACE',\n            'colour.models.MAX_RGB_COLOURSPACE',\n        ],\n        [\n            'colour.MUNSELL_COLOURS_1929',\n            'colour.notation.MUNSELL_COLOURS_1929',\n        ],\n        [\n            'colour.MUNSELL_COLOURS_ALL',\n            'colour.notation.MUNSELL_COLOURS_ALL',\n        ],\n        [\n            'colour.MUNSELL_COLOURS_REAL',\n            'colour.notation.MUNSELL_COLOURS_REAL',\n        ],\n        [\n            'colour.MultiSignal',\n            'colour.continuous.MultiSignals',\n        ],\n        [\n            'colour.NTSC_1953_COLOURSPACE',\n            'colour.models.NTSC_1953_COLOURSPACE',\n        ],\n        [\n            'colour.PAL_SECAM_COLOURSPACE',\n            'colour.models.PAL_SECAM_COLOURSPACE',\n        ],\n        [\n            'colour.PLANCK_CONSTANT',\n            'colour.constants.PLANCK_CONSTANT',\n        ],\n        [\n            'colour.PROPHOTO_RGB_COLOURSPACE',\n            'colour.models.PROPHOTO_RGB_COLOURSPACE',\n        ],\n        [\n            'colour.PROTUNE_NATIVE_COLOURSPACE',\n            'colour.models.PROTUNE_NATIVE_COLOURSPACE',\n        ],\n        [\n            'colour.RED_COLOR_2_COLOURSPACE',\n            'colour.models.RED_COLOR_2_COLOURSPACE',\n        ],\n        [\n            'colour.RED_COLOR_3_COLOURSPACE',\n            'colour.models.RED_COLOR_3_COLOURSPACE',\n        ],\n        [\n            'colour.RED_COLOR_4_COLOURSPACE',\n            'colour.models.RED_COLOR_4_COLOURSPACE',\n        ],\n        [\n            'colour.RED_COLOR_COLOURSPACE',\n            'colour.models.RED_COLOR_COLOURSPACE',\n        ],\n        [\n            'colour.RED_WIDE_GAMUT_RGB_COLOURSPACE',\n            'colour.models.RED_WIDE_GAMUT_RGB_COLOURSPACE',\n        ],\n        [\n            'colour.RGB_10_degree_cmfs_to_LMS_10_degree_cmfs',\n            'colour.colorimetry.RGB_10_degree_cmfs_to_LMS_10_degree_cmfs',\n        ],\n        [\n            'colour.RGB_10_degree_cmfs_to_XYZ_10_degree_cmfs',\n            'colour.colorimetry.RGB_10_degree_cmfs_to_XYZ_10_degree_cmfs',\n        ],\n        [\n            'colour.RGB_2_degree_cmfs_to_XYZ_2_degree_cmfs',\n            'colour.colorimetry.RGB_2_degree_cmfs_to_XYZ_2_degree_cmfs',\n        ],\n        [\n            'colour.RGB_ColourMatchingFunctions',\n            'colour.colorimetry.RGB_ColourMatchingFunctions',\n        ],\n        [\n            'colour.RGB_DisplayPrimaries',\n            'colour.characterisation.RGB_DisplayPrimaries',\n        ],\n        [\n            'colour.RGB_SpectralSensitivities',\n            'colour.characterisation.RGB_SpectralSensitivities',\n        ],\n        [\n            'colour.RGB_to_sd_Smits1999',\n            'colour.recovery.RGB_to_sd_Smits1999',\n        ],\n        [\n            'colour.RIMM_RGB_COLOURSPACE',\n            'colour.models.RIMM_RGB_COLOURSPACE',\n        ],\n        [\n            'colour.ROMM_RGB_COLOURSPACE',\n            'colour.models.ROMM_RGB_COLOURSPACE',\n        ],\n        [\n            'colour.RUSSELL_RGB_COLOURSPACE',\n            'colour.models.RUSSELL_RGB_COLOURSPACE',\n        ],\n        [\n            'colour.SHARP_CAT',\n            'colour.adaptation.SHARP_CAT',\n        ],\n        [\n            'colour.SMITS_1999_SPDS',\n            'colour.recovery.SMITS_1999_SDS',\n        ],\n        [\n            'colour.SMPTE_240M_COLOURSPACE',\n            'colour.models.SMPTE_240M_COLOURSPACE',\n        ],\n        [\n            'colour.S_GAMUT3_CINE_COLOURSPACE',\n            'colour.models.S_GAMUT3_CINE_COLOURSPACE',\n        ],\n        [\n            'colour.S_GAMUT3_COLOURSPACE',\n            'colour.models.S_GAMUT3_COLOURSPACE',\n        ],\n        [\n            'colour.S_GAMUT_COLOURSPACE',\n            'colour.models.S_GAMUT_COLOURSPACE',\n        ],\n        [\n            'colour.Signal',\n            'colour.continuous.Signal',\n        ],\n        [\n            'colour.Structure',\n            'colour.utilities.Structure',\n        ],\n        [\n            'colour.TCS_SPDS',\n            'colour.quality.TCS_SDS',\n        ],\n        [\n            'colour.VON_KRIES_CAT',\n            'colour.adaptation.VON_KRIES_CAT',\n        ],\n        [\n            'colour.VS_SPDS',\n            'colour.quality.VS_SDS',\n        ],\n        [\n            'colour.V_GAMUT_COLOURSPACE',\n            'colour.models.V_GAMUT_COLOURSPACE',\n        ],\n        [\n            'colour.XTREME_RGB_COLOURSPACE',\n            'colour.models.XTREME_RGB_COLOURSPACE',\n        ],\n        [\n            'colour.XYZ_ColourMatchingFunctions',\n            'colour.colorimetry.XYZ_ColourMatchingFunctions',\n        ],\n        [\n            'colour.XYZ_SCALING_CAT',\n            'colour.adaptation.XYZ_SCALING_CAT',\n        ],\n        [\n            'colour.XYZ_to_colourspace_model',\n            'colour.models.XYZ_to_colourspace_model',\n        ],\n        [\n            'colour.XYZ_to_sd_Meng2015',\n            'colour.recovery.XYZ_to_sd_Meng2015',\n        ],\n        [\n            'colour.adjust_tristimulus_weighting_factors_ASTME30815',\n            'colour.colorimetry.adjust_tristimulus_weighting_factors_ASTME308',\n        ],\n        [\n            'colour.as_namedtuple',\n            'colour.utilities.as_namedtuple',\n        ],\n        [\n            'colour.as_numeric',\n            'colour.utilities.as_numeric',\n        ],\n        [\n            'colour.bandpass_correction_Stearns1988',\n            'colour.colorimetry.bandpass_correction_Stearns1988',\n        ],\n        [\n            'colour.batch',\n            'colour.utilities.batch',\n        ],\n        [\n            'colour.blackbody_spectral_radiance',\n            'colour.colorimetry.blackbody_spectral_radiance',\n        ],\n        [\n            'colour.cartesian_to_cylindrical',\n            'colour.algebra.cartesian_to_cylindrical',\n        ],\n        [\n            'colour.cartesian_to_polar',\n            'colour.algebra.cartesian_to_polar',\n        ],\n        [\n            'colour.cartesian_to_spherical',\n            'colour.algebra.cartesian_to_spherical',\n        ],\n        [\n            'colour.centroid',\n            'colour.utilities.centroid',\n        ],\n        [\n            'colour.chromatic_adaptation_CIE1994',\n            'colour.adaptation.chromatic_adaptation_CIE1994',\n        ],\n        [\n            'colour.chromatic_adaptation_CMCCAT2000',\n            'colour.adaptation.chromatic_adaptation_CMCCAT2000',\n        ],\n        [\n            'colour.chromatic_adaptation_Fairchild1990',\n            'colour.adaptation.chromatic_adaptation_Fairchild1990',\n        ],\n        [\n            'colour.chromatic_adaptation_VonKries',\n            'colour.adaptation.chromatic_adaptation_VonKries',\n        ],\n        [\n            'colour.chromatic_adaptation_forward_CMCCAT2000',\n            'colour.adaptation.chromatic_adaptation_forward_CMCCAT2000',\n        ],\n        [\n            'colour.chromatic_adaptation_matrix_VonKries',\n            'colour.adaptation.chromatic_adaptation_matrix_VonKries',\n        ],\n        [\n            'colour.chromatic_adaptation_reverse_CMCCAT2000',\n            'colour.adaptation.chromatic_adaptation_inverse_CMCCAT2000',\n        ],\n        [\n            'colour.closest',\n            'colour.utilities.closest',\n        ],\n        [\n            'colour.closest_indexes',\n            'colour.utilities.closest_indexes',\n        ],\n        [\n            'colour.corresponding_chromaticities_prediction_CIE1994',\n            'colour.corresponding.corresponding_chromaticities_prediction_CIE1994',  # noqa\n        ],\n        [\n            'colour.corresponding_chromaticities_prediction_CMCCAT2000',\n            'colour.corresponding.corresponding_chromaticities_prediction_CMCCAT2000',  # noqa\n        ],\n        [\n            'colour.corresponding_chromaticities_prediction_Fairchild1990',\n            'colour.corresponding.corresponding_chromaticities_prediction_Fairchild1990',  # noqa\n        ],\n        [\n            'colour.corresponding_chromaticities_prediction_VonKries',\n            'colour.corresponding.corresponding_chromaticities_prediction_VonKries',  # noqa\n        ],\n        [\n            'colour.cylindrical_to_cartesian',\n            'colour.algebra.cylindrical_to_cartesian',\n        ],\n        [\n            'colour.delta_E_CAM02LCD',\n            'colour.difference.delta_E_CAM02LCD',\n        ],\n        [\n            'colour.delta_E_CAM02SCD',\n            'colour.difference.delta_E_CAM02SCD',\n        ],\n        [\n            'colour.delta_E_CAM02UCS',\n            'colour.difference.delta_E_CAM02UCS',\n        ],\n        [\n            'colour.delta_E_CAM16LCD',\n            'colour.difference.delta_E_CAM16LCD',\n        ],\n        [\n            'colour.delta_E_CAM16SCD',\n            'colour.difference.delta_E_CAM16SCD',\n        ],\n        [\n            'colour.delta_E_CAM16UCS',\n            'colour.difference.delta_E_CAM16UCS',\n        ],\n        [\n            'colour.delta_E_CIE1976',\n            'colour.difference.delta_E_CIE1976',\n        ],\n        [\n            'colour.delta_E_CIE1994',\n            'colour.difference.delta_E_CIE1994',\n        ],\n        [\n            'colour.delta_E_CIE2000',\n            'colour.difference.delta_E_CIE2000',\n        ],\n        [\n            'colour.delta_E_CMC',\n            'colour.difference.delta_E_CMC',\n        ],\n        [\n            'colour.dot_matrix',\n            'colour.utilities.dot_matrix',\n        ],\n        [\n            'colour.dot_vector',\n            'colour.utilities.dot_vector',\n        ],\n        [\n            'colour.eotf_BT1886',\n            'colour.models.eotf_BT1886',\n        ],\n        [\n            'colour.eotf_BT2020',\n            'colour.models.eotf_BT2020',\n        ],\n        [\n            'colour.eotf_BT2100_HLG',\n            'colour.models.eotf_HLG_BT2100',\n        ],\n        [\n            'colour.eotf_BT2100_PQ',\n            'colour.models.eotf_PQ_BT2100',\n        ],\n        [\n            'colour.eotf_DCIP3',\n            'colour.models.eotf_DCDM',\n        ],\n        [\n            'colour.eotf_DICOMGSDF',\n            'colour.models.eotf_DICOMGSDF',\n        ],\n        [\n            'colour.cctf_decoding_ProPhotoRGB',\n            'colour.models.cctf_decoding_ProPhotoRGB',\n        ],\n        [\n            'colour.cctf_decoding_RIMMRGB',\n            'colour.models.cctf_decoding_RIMMRGB',\n        ],\n        [\n            'colour.cctf_decoding_ROMMRGB',\n            'colour.models.cctf_decoding_ROMMRGB',\n        ],\n        [\n            'colour.eotf_SMPTE240M',\n            'colour.models.eotf_SMPTE240M',\n        ],\n        [\n            'colour.eotf_ST2084',\n            'colour.models.eotf_ST2084',\n        ],\n        [\n            'colour.eotf_reverse_BT1886',\n            'colour.models.eotf_inverse_BT1886',\n        ],\n        [\n            'colour.eotf_reverse_BT2100_HLG',\n            'colour.models.eotf_inverse_HLG_BT2100',\n        ],\n        [\n            'colour.eotf_reverse_BT2100_PQ',\n            'colour.models.eotf_inverse_PQ_BT2100',\n        ],\n        [\n            'colour.eotf_reverse_ST2084',\n            'colour.models.eotf_inverse_ST2084',\n        ],\n        [\n            'colour.eotf_reverse_sRGB',\n            'colour.models.eotf_inverse_sRGB',\n        ],\n        [\n            'colour.eotf_sRGB',\n            'colour.models.eotf_sRGB',\n        ],\n        [\n            'colour.euclidean_distance',\n            'colour.algebra.euclidean_distance',\n        ],\n        [\n            'colour.extend_line_segment',\n            'colour.algebra.extend_line_segment',\n        ],\n        [\n            'colour.fill_nan',\n            'colour.utilities.fill_nan',\n        ],\n        [\n            'colour.filter_kwargs',\n            'colour.utilities.filter_kwargs',\n        ],\n        [\n            'colour.filter_warnings',\n            'colour.utilities.filter_warnings',\n        ],\n        [\n            'colour.first_item',\n            'colour.utilities.first_item',\n        ],\n        [\n            'colour.handle_numpy_errors',\n            'colour.utilities.handle_numpy_errors',\n        ],\n        [\n            'colour.ignore_numpy_errors',\n            'colour.utilities.ignore_numpy_errors',\n        ],\n        [\n            'colour.ignore_python_warnings',\n            'colour.utilities.ignore_python_warnings',\n        ],\n        [\n            'colour.in_array',\n            'colour.utilities.in_array',\n        ],\n        [\n            'colour.intersect_line_segments',\n            'colour.algebra.intersect_line_segments',\n        ],\n        [\n            'colour.interval',\n            'colour.utilities.interval',\n        ],\n        [\n            'colour.is_identity',\n            'colour.algebra.is_identity',\n        ],\n        [\n            'colour.is_integer',\n            'colour.utilities.is_integer',\n        ],\n        [\n            'colour.is_iterable',\n            'colour.utilities.is_iterable',\n        ],\n        [\n            'colour.is_numeric',\n            'colour.utilities.is_numeric',\n        ],\n        [\n            'colour.is_openimageio_installed',\n            'colour.utilities.is_openimageio_installed',\n        ],\n        [\n            'colour.is_pandas_installed',\n            'colour.utilities.is_pandas_installed',\n        ],\n        [\n            'colour.is_string',\n            'colour.utilities.is_string',\n        ],\n        [\n            'colour.is_uniform',\n            'colour.utilities.is_uniform',\n        ],\n        [\n            'colour.lagrange_coefficients_ASTME2022',\n            'colour.colorimetry.lagrange_coefficients_ASTME2022',\n        ],\n        [\n            'colour.lightness_CIE1976',\n            'colour.colorimetry.lightness_CIE1976',\n        ],\n        [\n            'colour.lightness_Fairchild2010',\n            'colour.colorimetry.lightness_Fairchild2010',\n        ],\n        [\n            'colour.lightness_Fairchild2011',\n            'colour.colorimetry.lightness_Fairchild2011',\n        ],\n        [\n            'colour.lightness_Glasser1958',\n            'colour.colorimetry.lightness_Glasser1958',\n        ],\n        [\n            'colour.lightness_Wyszecki1963',\n            'colour.colorimetry.lightness_Wyszecki1963',\n        ],\n        [\n            'colour.linear_conversion',\n            'colour.utilities.linear_conversion',\n        ],\n        [\n            'colour.log_decoding_ACEScc',\n            'colour.models.log_decoding_ACEScc',\n        ],\n        [\n            'colour.log_decoding_ACEScct',\n            'colour.models.log_decoding_ACEScct',\n        ],\n        [\n            'colour.log_decoding_ACESproxy',\n            'colour.models.log_decoding_ACESproxy',\n        ],\n        [\n            'colour.log_decoding_ALEXALogC',\n            'colour.models.log_decoding_ALEXALogC',\n        ],\n        [\n            'colour.log_decoding_CanonLog',\n            'colour.models.log_decoding_CanonLog',\n        ],\n        [\n            'colour.log_decoding_CanonLog2',\n            'colour.models.log_decoding_CanonLog2',\n        ],\n        [\n            'colour.log_decoding_CanonLog3',\n            'colour.models.log_decoding_CanonLog3',\n        ],\n        [\n            'colour.log_decoding_Cineon',\n            'colour.models.log_decoding_Cineon',\n        ],\n        [\n            'colour.log_decoding_ERIMMRGB',\n            'colour.models.log_decoding_ERIMMRGB',\n        ],\n        [\n            'colour.log_decoding_Log3G10',\n            'colour.models.log_decoding_Log3G10',\n        ],\n        [\n            'colour.log_decoding_Log3G12',\n            'colour.models.log_decoding_Log3G12',\n        ],\n        [\n            'colour.log_decoding_Panalog',\n            'colour.models.log_decoding_Panalog',\n        ],\n        [\n            'colour.log_decoding_PivotedLog',\n            'colour.models.log_decoding_PivotedLog',\n        ],\n        [\n            'colour.log_decoding_Protune',\n            'colour.models.log_decoding_Protune',\n        ],\n        [\n            'colour.log_decoding_REDLog',\n            'colour.models.log_decoding_REDLog',\n        ],\n        [\n            'colour.log_decoding_REDLogFilm',\n            'colour.models.log_decoding_REDLogFilm',\n        ],\n        [\n            'colour.log_decoding_SLog',\n            'colour.models.log_decoding_SLog',\n        ],\n        [\n            'colour.log_decoding_SLog2',\n            'colour.models.log_decoding_SLog2',\n        ],\n        [\n            'colour.log_decoding_SLog3',\n            'colour.models.log_decoding_SLog3',\n        ],\n        [\n            'colour.log_decoding_VLog',\n            'colour.models.log_decoding_VLog',\n        ],\n        [\n            'colour.log_decoding_ViperLog',\n            'colour.models.log_decoding_ViperLog',\n        ],\n        [\n            'colour.log_encoding_ACEScc',\n            'colour.models.log_encoding_ACEScc',\n        ],\n        [\n            'colour.log_encoding_ACEScct',\n            'colour.models.log_encoding_ACEScct',\n        ],\n        [\n            'colour.log_encoding_ACESproxy',\n            'colour.models.log_encoding_ACESproxy',\n        ],\n        [\n            'colour.log_encoding_ALEXALogC',\n            'colour.models.log_encoding_ALEXALogC',\n        ],\n        [\n            'colour.log_encoding_CanonLog',\n            'colour.models.log_encoding_CanonLog',\n        ],\n        [\n            'colour.log_encoding_CanonLog2',\n            'colour.models.log_encoding_CanonLog2',\n        ],\n        [\n            'colour.log_encoding_CanonLog3',\n            'colour.models.log_encoding_CanonLog3',\n        ],\n        [\n            'colour.log_encoding_Cineon',\n            'colour.models.log_encoding_Cineon',\n        ],\n        [\n            'colour.log_encoding_ERIMMRGB',\n            'colour.models.log_encoding_ERIMMRGB',\n        ],\n        [\n            'colour.log_encoding_Log3G10',\n            'colour.models.log_encoding_Log3G10',\n        ],\n        [\n            'colour.log_encoding_Log3G12',\n            'colour.models.log_encoding_Log3G12',\n        ],\n        [\n            'colour.log_encoding_Panalog',\n            'colour.models.log_encoding_Panalog',\n        ],\n        [\n            'colour.log_encoding_PivotedLog',\n            'colour.models.log_encoding_PivotedLog',\n        ],\n        [\n            'colour.log_encoding_Protune',\n            'colour.models.log_encoding_Protune',\n        ],\n        [\n            'colour.log_encoding_REDLog',\n            'colour.models.log_encoding_REDLog',\n        ],\n        [\n            'colour.log_encoding_REDLogFilm',\n            'colour.models.log_encoding_REDLogFilm',\n        ],\n        [\n            'colour.log_encoding_SLog',\n            'colour.models.log_encoding_SLog',\n        ],\n        [\n            'colour.log_encoding_SLog2',\n            'colour.models.log_encoding_SLog2',\n        ],\n        [\n            'colour.log_encoding_SLog3',\n            'colour.models.log_encoding_SLog3',\n        ],\n        [\n            'colour.log_encoding_VLog',\n            'colour.models.log_encoding_VLog',\n        ],\n        [\n            'colour.luminance_ASTMD153508',\n            'colour.colorimetry.luminance_ASTMD1535',\n        ],\n        [\n            'colour.luminance_CIE1976',\n            'colour.colorimetry.luminance_CIE1976',\n        ],\n        [\n            'colour.luminance_Fairchild2010',\n            'colour.colorimetry.luminance_Fairchild2010',\n        ],\n        [\n            'colour.luminance_Fairchild2011',\n            'colour.colorimetry.luminance_Fairchild2011',\n        ],\n        [\n            'colour.luminance_Newhall1943',\n            'colour.colorimetry.luminance_Newhall1943',\n        ],\n        [\n            'colour.mesopic_weighting_function',\n            'colour.colorimetry.mesopic_weighting_function',\n        ],\n        [\n            'colour.message_box',\n            'colour.utilities.message_box',\n        ],\n        [\n            'colour.munsell_value_ASTMD153508',\n            'colour.notation.munsell_value_ASTMD1535',\n        ],\n        [\n            'colour.munsell_value_Ladd1955',\n            'colour.notation.munsell_value_Ladd1955',\n        ],\n        [\n            'colour.munsell_value_McCamy1987',\n            'colour.notation.munsell_value_McCamy1987',\n        ],\n        [\n            'colour.munsell_value_Moon1943',\n            'colour.notation.munsell_value_Moon1943',\n        ],\n        [\n            'colour.munsell_value_Munsell1933',\n            'colour.notation.munsell_value_Munsell1933',\n        ],\n        [\n            'colour.munsell_value_Priest1920',\n            'colour.notation.munsell_value_Priest1920',\n        ],\n        [\n            'colour.munsell_value_Saunderson1944',\n            'colour.notation.munsell_value_Saunderson1944',\n        ],\n        [\n            'colour.ndarray_write',\n            'colour.utilities.ndarray_write',\n        ],\n        [\n            'colour.normalise_maximum',\n            'colour.utilities.normalise_maximum',\n        ],\n        [\n            'colour.normalise_vector',\n            'colour.algebra.normalise_vector',\n        ],\n        [\n            'colour.numpy_print_options',\n            'colour.utilities.numpy_print_options',\n        ],\n        [\n            'colour.oetf_ARIBSTDB67',\n            'colour.models.oetf_ARIBSTDB67',\n        ],\n        [\n            'colour.oetf_BT2020',\n            'colour.models.oetf_BT2020',\n        ],\n        [\n            'colour.oetf_BT2100_HLG',\n            'colour.models.oetf_HLG_BT2100',\n        ],\n        [\n            'colour.oetf_BT2100_PQ',\n            'colour.models.oetf_PQ_BT2100',\n        ],\n        [\n            'colour.oetf_BT601',\n            'colour.models.oetf_BT601',\n        ],\n        [\n            'colour.oetf_BT709',\n            'colour.models.oetf_BT709',\n        ],\n        [\n            'colour.oetf_DCIP3',\n            'colour.models.eotf_inverse_DCIP3',\n        ],\n        [\n            'colour.oetf_DICOMGSDF',\n            'colour.models.eotf_inverse_DICOMGSDF',\n        ],\n        [\n            'colour.cctf_encoding_ProPhotoRGB',\n            'colour.models.cctf_encoding_ProPhotoRGB',\n        ],\n        [\n            'colour.cctf_encoding_RIMMRGB',\n            'colour.models.cctf_encoding_RIMMRGB',\n        ],\n        [\n            'colour.cctf_encoding_ROMMRGB',\n            'colour.models.cctf_encoding_ROMMRGB',\n        ],\n        [\n            'colour.oetf_SMPTE240M',\n            'colour.models.oetf_SMPTE240M',\n        ],\n        [\n            'colour.oetf_reverse_ARIBSTDB67',\n            'colour.models.oetf_inverse_ARIBSTDB67',\n        ],\n        [\n            'colour.oetf_reverse_BT2100_HLG',\n            'colour.models.oetf_inverse_HLG_BT2100',\n        ],\n        [\n            'colour.oetf_reverse_BT2100_PQ',\n            'colour.models.oetf_inverse_PQ_BT2100',\n        ],\n        [\n            'colour.oetf_reverse_BT601',\n            'colour.models.oetf_inverse_BT601',\n        ],\n        [\n            'colour.oetf_reverse_BT709',\n            'colour.models.oetf_inverse_BT709',\n        ],\n        [\n            'colour.ootf_BT2100_HLG',\n            'colour.models.ootf_HLG_BT2100',\n        ],\n        [\n            'colour.ootf_BT2100_PQ',\n            'colour.models.ootf_PQ_BT2100',\n        ],\n        [\n            'colour.ootf_reverse_BT2100_HLG',\n            'colour.models.ootf_inverse_HLG_BT2100',\n        ],\n        [\n            'colour.ootf_reverse_BT2100_PQ',\n            'colour.models.ootf_inverse_PQ_BT2100',\n        ],\n        [\n            'colour.orient',\n            'colour.utilities.orient',\n        ],\n        [\n            'colour.planck_law',\n            'colour.colorimetry.planck_law',\n        ],\n        [\n            'colour.polar_to_cartesian',\n            'colour.algebra.polar_to_cartesian',\n        ],\n        [\n            'colour.print_numpy_errors',\n            'colour.utilities.print_numpy_errors',\n        ],\n        [\n            'colour.raise_numpy_errors',\n            'colour.utilities.raise_numpy_errors',\n        ],\n        [\n            'colour.random_triplet_generator',\n            'colour.algebra.random_triplet_generator',\n        ],\n        [\n            'colour.rayleigh_optical_depth',\n            'colour.phenomena.rayleigh_optical_depth',\n        ],\n        [\n            'colour.reaction_rate_MichealisMenten',\n            'colour.biochemistry.reaction_rate_MichealisMenten',\n        ],\n        [\n            'colour.row_as_diagonal',\n            'colour.utilities.row_as_diagonal',\n        ],\n        [\n            'colour.sRGB_COLOURSPACE',\n            'colour.models.sRGB_COLOURSPACE',\n        ],\n        [\n            'colour.sd_to_XYZ_ASTME30815',\n            'colour.colorimetry.sd_to_XYZ_ASTME308',\n        ],\n        [\n            'colour.sd_to_XYZ_integration',\n            'colour.colorimetry.sd_to_XYZ_integration',\n        ],\n        [\n            'colour.sd_to_XYZ_tristimulus_weighting_factors_ASTME30815',\n            'colour.colorimetry.sd_to_XYZ_tristimulus_weighting_factors_ASTME308',  # noqa\n        ],\n        [\n            'colour.spherical_to_cartesian',\n            'colour.algebra.spherical_to_cartesian',\n        ],\n        [\n            'colour.substrate_concentration_MichealisMenten',\n            'colour.biochemistry.substrate_concentration_MichealisMenten',\n        ],\n        [\n            'colour.tristimulus_weighting_factors_ASTME2022',\n            'colour.colorimetry.tristimulus_weighting_factors_ASTME2022',\n        ],\n        [\n            'colour.tsplit',\n            'colour.utilities.tsplit',\n        ],\n        [\n            'colour.tstack',\n            'colour.utilities.tstack',\n        ],\n        [\n            'colour.uv_to_CCT_Ohno2013',\n            'colour.temperature.uv_to_CCT_Ohno2013',\n        ],\n        [\n            'colour.uv_to_CCT_Robertson1968',\n            'colour.temperature.uv_to_CCT_Robertson1968',\n        ],\n        [\n            'colour.warn_numpy_errors',\n            'colour.utilities.warn_numpy_errors',\n        ],\n        [\n            'colour.warning',\n            'colour.utilities.warning',\n        ],\n        [\n            'colour.whiteness_ASTME313',\n            'colour.colorimetry.whiteness_ASTME313',\n        ],\n        [\n            'colour.whiteness_Berger1959',\n            'colour.colorimetry.whiteness_Berger1959',\n        ],\n        [\n            'colour.whiteness_CIE2004',\n            'colour.colorimetry.whiteness_CIE2004',\n        ],\n        [\n            'colour.whiteness_Ganz1979',\n            'colour.colorimetry.whiteness_Ganz1979',\n        ],\n        [\n            'colour.whiteness_Stensby1968',\n            'colour.colorimetry.whiteness_Stensby1968',\n        ],\n        [\n            'colour.whiteness_Taube1960',\n            'colour.colorimetry.whiteness_Taube1960',\n        ],\n        [\n            'colour.xy_to_CCT_Hernandez1999',\n            'colour.temperature.xy_to_CCT_Hernandez1999',\n        ],\n        [\n            'colour.xy_to_CCT_McCamy1992',\n            'colour.temperature.xy_to_CCT_McCamy1992',\n        ],\n        [\n            'colour.yellowness_ASTMD1925',\n            'colour.colorimetry.yellowness_ASTMD1925',\n        ],\n        [\n            'colour.yellowness_ASTME313',\n            'colour.colorimetry.yellowness_ASTME313',\n        ],\n    ]\n}\n\"\"\"\nDefines *colour* package API changes.\n\nAPI_CHANGES : dict\n\"\"\"\n\nAPI_CHANGES.update({\n    'ObjectRemoved': [\n        'colour.DEFAULT_WAVELENGTH_DECIMALS',\n        'colour.ArbitraryPrecisionMapping',\n        'colour.SpectralMapping',\n    ],\n    'ObjectRenamed': [\n        [\n            'colour.eotf_ARIBSTDB67',\n            'colour.models.oetf_inverse_ARIBSTDB67',\n        ],\n        [\n            'colour.eotf_BT709',\n            'colour.models.oetf_inverse_BT709',\n        ],\n        [\n            'colour.oetf_BT1886',\n            'colour.models.eotf_inverse_BT1886',\n        ],\n        [\n            'colour.eotf_sRGB',\n            'colour.models.eotf_sRGB',\n        ],\n        [\n            'colour.ALEXA_WIDE_GAMUT_RGB_COLOURSPACE',\n            'colour.models.ALEXA_WIDE_GAMUT_COLOURSPACE',\n        ],\n        [\n            'colour.NTSC_1953_RGB_COLOURSPACE',\n            'colour.models.NTSC_1953_COLOURSPACE',\n        ],\n        [\n            'colour.PAL_SECAM_RGB_COLOURSPACE',\n            'colour.models.PAL_SECAM_COLOURSPACE',\n        ],\n        [\n            'colour.REC_709_COLOURSPACE',\n            'colour.models.BT709_COLOURSPACE',\n        ],\n        [\n            'colour.REC_2020_COLOURSPACE',\n            'colour.models.BT2020_COLOURSPACE',\n        ],\n        [\n            'colour.SMPTE_C_RGB_COLOURSPACE',\n            'colour.models.SMPTE_240M_COLOURSPACE',\n        ],\n        [\n            'colour.TriSpectralPowerDistribution',\n            'colour.MultiSpectralDistributions',\n        ],\n    ]\n})\n\n# v0.3.12\nAPI_CHANGES['ObjectRenamed'] = API_CHANGES['ObjectRenamed'] + [\n    [\n        'colour.CIE_standard_illuminant_A_function',\n        'colour.sd_CIE_standard_illuminant_A',\n    ],\n    [\n        'colour.COLOURCHECKERS_SPDS',\n        'colour.COLOURCHECKERS_SDS',\n    ],\n    [\n        'colour.D_illuminant_relative_spd',\n        'colour.sd_CIE_illuminant_D_series',\n    ],\n    [\n        'colour.ILLUMINANTS_RELATIVE_SPDS',\n        'colour.ILLUMINANTS_SDS',\n    ],\n    [\n        'colour.LIGHT_SOURCES_RELATIVE_SPDS',\n        'colour.LIGHT_SOURCES_SDS',\n    ],\n    [\n        'colour.MultiSpectralPowerDistribution',\n        'colour.MultiSpectralDistributions',\n    ],\n    [\n        'colour.REFLECTANCE_RECOVERY_METHODS',\n        'colour.XYZ_TO_SD_METHODS',\n    ],\n    [\n        'colour.SPECTRAL_TO_XYZ_METHODS',\n        'colour.SD_TO_XYZ_METHODS',\n    ],\n    [\n        'colour.SpectralPowerDistribution',\n        'colour.SpectralDistribution',\n    ],\n    [\n        'colour.blackbody_spd',\n        'colour.sd_blackbody',\n    ],\n    [\n        'colour.constant_spd',\n        'colour.sd_constant',\n    ],\n    [\n        'colour.first_order_colour_fit',\n        'colour.colour_correction_matrix',\n    ],\n    [\n        'colour.IES_TM2714_Spd',\n        'colour.SpectralDistribution_IESTM2714',\n    ],\n    [\n        'colour.function_gamma',\n        'colour.gamma_function',\n    ],\n    [\n        'colour.function_linear',\n        'colour.linear_function',\n    ],\n    [\n        'colour.mesopic_luminous_efficiency_function',\n        'colour.sd_mesopic_luminous_efficiency_function',\n    ],\n    [\n        'colour.ones_spd',\n        'colour.sd_ones',\n    ],\n    [\n        'colour.rayleigh_scattering_spd',\n        'colour.sd_rayleigh_scattering',\n    ],\n    [\n        'colour.read_spds_from_csv_file',\n        'colour.read_sds_from_csv_file',\n    ],\n    [\n        'colour.read_spds_from_xrite_file',\n        'colour.read_sds_from_xrite_file',\n    ],\n    [\n        'colour.spectral_to_aces_relative_exposure_values',\n        'colour.sd_to_aces_relative_exposure_values',\n    ],\n    [\n        'colour.spectral_to_XYZ',\n        'colour.sd_to_XYZ',\n    ],\n    [\n        'colour.write_spds_to_csv_file',\n        'colour.write_sds_to_csv_file',\n    ],\n    [\n        'colour.XYZ_to_spectral',\n        'colour.XYZ_to_sd',\n    ],\n    [\n        'colour.zeros_spd',\n        'colour.sd_zeros',\n    ],\n]\n\n# v0.3.14\nAPI_CHANGES['ObjectRenamed'] = API_CHANGES['ObjectRenamed'] + [\n    [\n        'colour.ASTME30815_PRACTISE_SHAPE',\n        'colour.ASTME308_PRACTISE_SHAPE',\n    ],\n    [\n        'colour.decoding_cctf',\n        'colour.cctf_decoding',\n    ],\n    [\n        'colour.DECODING_CCTFS',\n        'colour.CCTF_DECODINGS',\n    ],\n    [\n        'colour.encoding_cctf',\n        'colour.cctf_encoding',\n    ],\n    [\n        'colour.ENCODING_CCTFS',\n        'colour.CCTF_ENCODINGS',\n    ],\n    [\n        'colour.EOTFS_REVERSE',\n        'colour.EOTF_INVERSES',\n    ],\n    [\n        'colour.eotf_reverse',\n        'colour.eotf_inverse',\n    ],\n    [\n        'colour.log_decoding_curve',\n        'colour.log_decoding',\n    ],\n    [\n        'colour.LOG_DECODING_CURVES',\n        'colour.LOG_DECODINGS',\n    ],\n    [\n        'colour.log_encoding_curve',\n        'colour.log_encoding',\n    ],\n    [\n        'colour.LOG_ENCODING_CURVES',\n        'colour.LOG_ENCODINGS',\n    ],\n    [\n        'colour.OETFS_REVERSE',\n        'colour.OETF_INVERSES',\n    ],\n    [\n        'colour.oetf_reverse',\n        'colour.oetf_inverse',\n    ],\n    [\n        'colour.OOTFS_REVERSE',\n        'colour.OOTF_INVERSES',\n    ],\n    [\n        'colour.ootf_reverse',\n        'colour.ootf_inverse',\n    ],\n    [\n        'colour.MultiSpectralDistribution',\n        'colour.MultiSpectralDistributions',\n    ],\n]\n\nif not is_documentation_building():\n    sys.modules['colour'] = colour(sys.modules['colour'],\n                                   build_API_changes(API_CHANGES))\n\n    del ModuleAPI, is_documentation_building, build_API_changes, sys\n", "meta": {"hexsha": "867971ab31b8ec83171f2f605a662446c8e2e9c6", "size": 57181, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/__init__.py", "max_stars_repo_name": "MaxSchambach/colour", "max_stars_repo_head_hexsha": "3f3685d616fda4be58cec20bc1e16194805d7e2d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "colour/__init__.py", "max_issues_repo_name": "MaxSchambach/colour", "max_issues_repo_head_hexsha": "3f3685d616fda4be58cec20bc1e16194805d7e2d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/__init__.py", "max_forks_repo_name": "MaxSchambach/colour", "max_forks_repo_head_hexsha": "3f3685d616fda4be58cec20bc1e16194805d7e2d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1422147274, "max_line_length": 97, "alphanum_fraction": 0.5919448768, "include": true, "reason": "import numpy", "num_tokens": 14380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.1975857130241219}}
{"text": "# coding: utf-8\n\"\"\"\nName: cycloen_deepeningrate.py\n\nFind cyclone center location and\ncalucurate cyclone deepinrate.\n\nexample:\npython3 cyclone_deepinrate.py -x 137 -y 40 -d <directory> -t yy-mm-dd-hh\n\nAuthor: Ryosuke Tomita\nDate: 2021/08/13\n\"\"\"\nimport argparse\nfrom datetime import datetime, timedelta\nimport math\nimport os\nfrom os.path import abspath, dirname, join\nimport re\nimport sys\nfrom typing import Union\nfrom netCDF4 import Dataset\nimport numpy as np\n\n\ndef parse_args() -> dict:\n    \"\"\"parse_args.\n    User have to determine ambiguous cyclen center location by weather map and so on.\n\n    Args:\n\n    Returns:\n        dict:\n    \"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"-y\", \"--lat\", help=\"Center of low pressure latitude\", type=float)\n    parser.add_argument(\n        \"-x\", \"--lon\", help=\"Center of low pressure longitude\", type=float)\n    parser.add_argument(\n        \"-d\", \"--dir\", help=\"set directory name. This is the initial time.\", type=str)\n    parser.add_argument(\n        \"-t\", \"--time\", help=\"set starttime. Format is yy-mm-dd-hh.\", type=str)\n    p = parser.parse_args()\n    args = {\"lat\": p.lat, \"lon\": p.lon, \"dir\": p.dir, \"time\": p.time}\n    return args\n\n\ndef mk_prmsl_file_list(data_root_dir: str, start_date: datetime) -> list:\n    \"\"\"mk_prmsl_file_list.\n    split data_root_dir's into prmslfile or the others. These lists are sorted by datetime.\n\n    Args:\n        data_root_dir (str): data_root_dir\n        start_date (datetime): start_date\n\n    Returns:\n        list:\n    \"\"\"\n    def _get_abs_path(par_dir: str, child: str) -> str:\n        \"\"\"get_abs_path.\n\n        Args:\n            par_dir:\n            child:\n        \"\"\"\n        abs_dir = abspath(join(par_dir, child))\n        return abs_dir\n\n    prmsl_all_list = sorted([_get_abs_path(data_root_dir, i)\n                            for i in os.listdir(data_root_dir) if \"prmsl\" in i])\n    date_list = [\n        datetime.strptime(re.search('[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{2}', i).group(),\"%Y-%m-%d_%H\")\n        for i in prmsl_all_list\n    ]\n    prmsl_list = [prmsl_all_list[i]\n                  for i in range(len(prmsl_all_list)) if date_list[i] >= start_date]\n    #print(prmsl_list)\n    return prmsl_list\n\n\ndef read_loc_prmsl(ncfile: str) -> Union[\n            np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray\n            ]:\n    \"\"\"read_loc_prmsl.\n    read ncfile and extract near Japan data.\n\n    Args:\n        file_name (str): file_name\n\n    Returns:\n        Union[\n                np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray\n                ]:\n    \"\"\"\n    read_ncfile = Dataset(ncfile)\n    prmsl_raw = read_ncfile.variables['prmsl'][0]\n    lat = [\n        i\n        if 20 <= i <= 60\n        else -99\n        for i in np.array(read_ncfile.variables['latitude'])\n    ]\n    lon =[\n        i if 110 <= i <= 180\n        else -99\n        for i in np.array(read_ncfile.variables['longitude'])\n    ]\n    prmsl_1d = [\n        prmsl_raw[i][j]\n        for i in range(len(lat))\n        if lat[i] != -99\n        for j in range(len(lon))\n        if lon[j] != -99\n    ]\n\n    near_jp_lat = np.array([i for i in lat if i != -99])\n    near_jp_lon = np.array([i for i in lon if i != -99])\n    prmsl = np.array(prmsl_1d).reshape(len(near_jp_lat), len(near_jp_lon))\n    #read_ncfile.close()\n    return lat, lon, near_jp_lat, near_jp_lon, prmsl\n\n\nclass CenterInfo:\n    \"\"\"CenterInfo.\n    store cycloen center information.\n    \"\"\"\n\n\n    def __init__(self, lat_index: np.ndarray, lon_index: np.ndarray,\n                 prmsl: np.ndarray, lat: np.ndarray, lon: np.ndarray, date: str):\n        \"\"\"__init__.\n        set varues.\n\n        Args:\n            lat_index (np.ndarray): lat_index\n            lon_index (np.ndarray): lon_index\n            prmsl (np.ndarray): prmsl\n            lat (np.ndarray): lat\n            lon (np.ndarray): lon\n            date (str): date\n        \"\"\"\n        self.lat_index = lat_index\n        self.lon_index = lon_index\n        self.prmsl = prmsl\n        self.lat = lat\n        self.lon = lon\n        date_jts = datetime.strptime(date, \"%Y-%m-%d_%H\") + timedelta(hours=9)\n        self.date = date_jts.strftime('%Y-%m-%d-%H')\n        self.epsilon = -999  # epsilon is None.\n        self.u_wind = None\n        self.v_wind = None\n        self.abs_wind = None\n        self.wind_direction = None\n\n    def __str__(self):\n        \"\"\"__str__.\n        print format settings.\n        \"\"\"\n        lat_data = f'latitude={self.lat},Index={self.lat_index}'\n        lon_data = f'longitude={self.lon},Index={self.lon_index}'\n        prmsl_data = f'prmslMin={self.prmsl}'\n        date_data = f'date={self.date}'\n        u_wind = f'u_wind={self.u_wind}'\n        v_wind = f'v_wind={self.v_wind}'\n        return f'{date_data},{lat_data},{lon_data},{prmsl_data},{u_wind},{v_wind}'\n\n    def read_wind(self, ncfile: str, lat: np.ndarray, lon: np.ndarray,\n            near_jp_lat: np.ndarray, near_jp_lon: np.ndarray, param: str) -> np.ndarray:\n        read_ncfile = Dataset(ncfile.replace(\"-prmsl_hPa\", \"\"))\n        var_all = read_ncfile.variables[param][0]\n        var_1d = [\n                var_all[i][j]\n            for i in range(len(lat))\n            if lat[i] != -99\n            for j in range(len(lon))\n            if lon[j] != -99\n    ]\n        var = np.array(var_1d).reshape(len(near_jp_lat), len(near_jp_lon))\n        return var[self.lat_index][self.lon_index]\n\n\ndef find_initial_prmslmin(lat: np.ndarray, lon: np.ndarray,\n                          center_lat_index: float, center_lon_index: float,\n                          prmsl: np.ndarray, date: str):# -> CenterInfo:\n    \"\"\"find center of cyclone using user's input lat,lon.\"\"\"\n    # if y,x are not varid value, then convert to int and recursion function.\n    flag = True\n    prmsl_min = 99999\n    prmsl_min_lat, prmsl_min_lon = np.where(lat == center_lat_index), np.where(lon == center_lon_index)\n    if lat[prmsl_min_lat].size == 0:\n        center_lat_index = round(center_lat_index)\n        flag = False\n    if lon[prmsl_min_lon].size == 0:\n        center_lon_index = round(center_lon_index)\n        flag = False\n    if not flag:\n        return find_initial_prmslmin(lat, lon, center_lat_index, center_lon_index, prmsl, date)\n\n    lat_search_area = np.arange(-2, 2.1, 0.5)\n    lon_search_area = np.arange(-2, 2.1, 0.5)\n    for la in [np.where(lat == i) for i in (lat_search_area + center_lat_index) if 20 <= i <= 60]:\n        for lo in [np.where(lon == i) for i in (lon_search_area + center_lon_index) if 110 <= i <= 180]:\n            la_index = (list(map(int, la))[0])\n            lo_index = (list(map(int, lo))[0])\n\n            if prmsl[la_index][lo_index] < prmsl_min:\n                min_data = CenterInfo(\n                    la_index, lo_index, prmsl[la_index][lo_index],\n                    lat[la_index], lon[lo_index], date\n                )\n                prmsl_min = prmsl[la_index][lo_index]\n    print(min_data)\n    return min_data\n\n\ndef find_next_prmslmin(lat:np.ndarray, lon:np.ndarray, prmsl: np.ndarray,\n                       prev_center_info, date: str) -> CenterInfo:\n    \"\"\"Using previous cyclone center location. Find next cyclone center location.\"\"\"\n    prmsl_min = 99999\n    prev_min_lat = prev_center_info.lat\n    prev_min_lon = prev_center_info.lon\n    #lat_search_area = np.arange(-6, 6.1, 0.5)\n    #lon_search_area = np.arange(-9, 9.1, 0.5)\n    #lat_search_area = np.arange(-3, 3.1, 0.5)\n    #lon_search_area = np.arange(-5, 5.1, 0.5)\n    lat_search_area = np.arange(-3, 3.1, 0.5)\n    lon_search_area = np.arange(-1, 7.1, 0.5)\n\n    for la in [np.where(lat == i) for i in lat_search_area + prev_min_lat if 20 <= i <= 60]:\n        for lo in [np.where(lon == i) for i in lon_search_area + prev_min_lon if 110 <= i <= 180]:\n            la_index = (list(map(int, la))[0])\n            lo_index = (list(map(int, lo))[0])\n\n            if prmsl[la_index][lo_index] < prmsl_min:\n                min_data = CenterInfo(\n                    la_index, lo_index, prmsl[la_index][lo_index],\n                    lat[la_index], lon[lo_index], date\n                    )\n                prmsl_min = prmsl[la_index][lo_index]\n    print(min_data)\n    return min_data\n\n\ndef cal_deeping_rate(prmsl_tracks: list):\n    \"\"\"calcurate cycloen deeping rate.\"\"\"\n    for i in range(1, len(prmsl_tracks)-1, 1):\n        prmsl6h_ago = prmsl_tracks[i-1].prmsl\n        prmsl6h_later = prmsl_tracks[i+1].prmsl\n        nowlat_rad = math.radians(prmsl_tracks[i].lat)\n        rad_45 = math.radians(45)\n\n        prmsl_tracks[i].epsilon = (\n            (prmsl6h_ago - prmsl6h_later)/12) * (math.sin(rad_45)/math.sin(nowlat_rad))\n\n\ndef write_data(prmsl_tracks, outname: str):\n    \"\"\"write_data.\n\n    Args:\n        prmsl_tracks:\n        outname (str): outname\n    \"\"\"\n    columns = [\"year-month-day_Hour\", \"prmsl center (hPa)\",\"latitude\", \"longitude\",\n               \"deepingRate\", \"u_wind\", \"v_wind\", \"abs_wind\", \"direction of wind(rad)\"]\n    file_path = join(abspath(dirname(__file__)) + \"/\" + outname + \".csv\")\n    with open(file_path, mode='w') as f:\n        f.write(\"{}\\n\".format(\",\".join(columns)))\n        for p in prmsl_tracks:\n            datas = list(map(str, [p.date, p.prmsl, p.lat, p.lon, p.epsilon, p.u_wind, p.v_wind, p.abs_wind, p.wind_direction]))\n            f.write(\"{}\\n\".format(\",\".join(datas)))\n\n\ndef main():\n    \"\"\"main\n    1. Set initial cyclone center info, initialtime,\n        directory path from stdin.\n    2. Make file list using directory path.\n    3. Get lan lot data and extract near japan area.\n    4. Find cyclone center location data and store in CenterInfo.\n    5. Go to next files and find next cyclone center location data.\n    6. Save to CSV file.\n    \"\"\"\n    args = parse_args()\n\n    data_root_dir = join(abspath(args[\"dir\"]))\n    data_root_dir_has_datetime = re.search('[0-9]{10}', data_root_dir)\n    if data_root_dir_has_datetime:\n        outname = data_root_dir_has_datetime.group()\n    else:\n        outname = \"initialdata\"\n    start_date = datetime.strptime(args[\"time\"], \"%Y-%m-%d_%H\")\n    ncfiles = mk_prmsl_file_list(data_root_dir, start_date)\n\n    # initial cyclone center data.\n    prmsl_tracks = []\n    lat, lon, near_jp_lat, near_jp_lon, prmsl = read_loc_prmsl(ncfiles[0])\n    pressure_center = find_initial_prmslmin(\n        near_jp_lat, near_jp_lon, args[\"lat\"], args[\"lon\"], prmsl, args[\"time\"])\n    pressure_center.u_wind = pressure_center.read_wind(\n        ncfiles[0], lat, lon, near_jp_lat, near_jp_lon,\n        'u10',\n    )\n    pressure_center.v_wind = pressure_center.read_wind(\n        ncfiles[0], lat, lon, near_jp_lat, near_jp_lon,\n        'v10',\n    )\n    prmsl_tracks.append(pressure_center)\n\n    # next cyclone center data.\n    for i in range(1, len(ncfiles), 1):\n        lat, lon, near_jp_lat, near_jp_lon, prmsl = read_loc_prmsl(ncfiles[i])\n\n        ncfiles_has_datetime = re.search('[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{2}', ncfiles[i])\n        if ncfiles_has_datetime:\n            date = ncfiles_has_datetime.group()\n        else:\n            raise Exception(\"ncfiles doesn't have datetime.\")\n\n        pressure_center = find_next_prmslmin(\n                near_jp_lat, near_jp_lon, prmsl, pressure_center, date)\n        pressure_center.u_wind = pressure_center.read_wind(\n                ncfiles[i], lat, lon, near_jp_lat, near_jp_lon,\n                'u10'\n        )\n        pressure_center.v_wind = pressure_center.read_wind(\n                ncfiles[i], lat, lon, near_jp_lat, near_jp_lon,\n                'v10'\n        )\n        pressure_center.abs_wind = (pressure_center.u_wind ** 2\n                + pressure_center.v_wind ** 2) ** 0.5\n        pressure_center.wind_direction = np.arctan2(pressure_center.u_wind, pressure_center.v_wind)\n\n        prmsl_tracks.append(pressure_center)\n        if pressure_center.lon == 180.0:\n            break\n\n    cal_deeping_rate(prmsl_tracks)\n    write_data(prmsl_tracks, outname)\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "e62a1308cb7484cc99368cb0aa9d3ac37c27da15", "size": 11908, "ext": "py", "lang": "Python", "max_stars_repo_path": "main/oldVersion/cyclone_deepingrate.py", "max_stars_repo_name": "RyosukeDTomita/gcmPlot", "max_stars_repo_head_hexsha": "430f8af353daf464b5c5566f1c163d5bef63f584", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main/oldVersion/cyclone_deepingrate.py", "max_issues_repo_name": "RyosukeDTomita/gcmPlot", "max_issues_repo_head_hexsha": "430f8af353daf464b5c5566f1c163d5bef63f584", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main/oldVersion/cyclone_deepingrate.py", "max_forks_repo_name": "RyosukeDTomita/gcmPlot", "max_forks_repo_head_hexsha": "430f8af353daf464b5c5566f1c163d5bef63f584", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6162790698, "max_line_length": 128, "alphanum_fraction": 0.6046355391, "include": true, "reason": "import numpy", "num_tokens": 3350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.36658972248186006, "lm_q1q2_score": 0.19758570929427727}}
{"text": "# pylint: disable=too-many-locals,too-many-lines\nimport os\nimport io\nimport math\nimport json\nimport shlex\nimport queue\nimport base64\nimport typing\nimport hashlib\nimport warnings\nimport logging\nimport fractions\nimport threading\nimport functools\nimport itertools\nimport subprocess\nfrom urllib import request\nfrom http import client\n\nimport numpy as np\nimport validators\nimport cv2\n\ntry:\n    import PIL\n    import PIL.Image\nexcept ImportError:  # pragma: no cover\n    PIL = None\n\nLOGGER = logging.getLogger(__name__)\n\nImageInputType = typing.Union[str, np.ndarray, 'PIL.Image.Image', io.BytesIO]\n\nSIZES = {'float32': 32, 'uint8': 8, 'bool': 1}\n\n# Map codec names to the CUDA-accelerated version. Obtain\n# from ffmpeg -codecs after building using CUDA.\nCUDA_CODECS = {\n    \"h264\": \"h264_cuvid\",\n    \"hevc\": \"hevc_cuvid\",\n    \"mjpeg\": \"mjpeg_cuvid\",\n    \"mpeg1video\": \"mpeg1_cuvid\",\n    \"mpeg2video\": \"mpeg2_cuvid\",\n    \"mpeg4\": \"mpeg4_cuvid\",\n    \"vc1\": \"vc1_cuvid\",\n    \"vp8\": \"vp8_cuvid\",\n    \"vp9\": \"vp9_cuvid\",\n}\n\nFramesWithIndexesAndTimestamps = typing.Generator[\n    typing.Tuple[np.ndarray, typing.Optional[int], typing.\n                 Optional[float]], None, None]\n\n\ndef get_ffprobe():\n    return os.environ.get(\"PERCEPTION_FFPROBE_BINARY\", \"ffprobe\")\n\n\ndef get_ffmpeg():\n    return os.environ.get(\"PERCEPTION_FFMPEG_BINARY\", \"ffmpeg\")\n\n\n# pylint: disable=invalid-name\ndef compute_quality(image) -> int:\n    \"\"\"Compute a quality metric, using the calculation proposed by\n    `Facebook <https://github.com/facebook/ThreatExchange/blob/master/hashing/hashing.pdf/>`_\n    for their PDQ hash algorithm.\"\"\"\n    if len(image.shape) == 3:\n        image = cv2.cvtColor(image, code=cv2.COLOR_RGB2GRAY)\n    if image.shape[0] != 64 or image.shape[1] != 64:\n        image = cv2.resize(src=image, dsize=(64, 64)).astype('float32')\n    dx = 100 * np.abs(image[:, 1:] - image[:, :-1]) / 255\n    dy = 100 * np.abs(image[1:] - image[:-1]) / 255\n    dx = dx.astype('int').sum()\n    dy = dy.astype('int').sum()\n    return int(np.clip(a=int((dx + dy) / 90), a_min=0, a_max=100))\n\n\ndef compute_md5(filepath) -> str:\n    \"\"\"Compute the md5 hash for a file at `filepath`.\n\n    Args:\n        filepath: The path to the file\n    \"\"\"\n    with open(filepath, 'rb') as f:  # pylint: disable=invalid-name\n        hash_str = hashlib.md5(f.read()).hexdigest()\n    return hash_str\n\n\ndef get_string_length(hash_length: int, dtype: str, hash_format='hex') -> int:\n    \"\"\"Compute the expected length of a hash string.\n\n    Args:\n        hash_length: The length of the hash vector\n        dtype: The dtype of the vector\n        hash_format: One of 'base64' or 'hex'\n\n    Returns:\n        The expected string length\n    \"\"\"\n    hash_bytes = math.ceil(hash_length * SIZES[dtype] / 8)\n\n    if hash_format == 'base64':\n        return int((4 * hash_bytes / 3) + 3) & ~3\n    if hash_format == 'hex':\n        return 2 * hash_bytes\n    raise NotImplementedError('Unknown hash format: ' + hash_format)\n\n\ndef vector_to_string(vector: np.ndarray, dtype: str,\n                     hash_format: str) -> typing.Optional[str]:\n    \"\"\"Convert vector to hash.\n\n    Args:\n        vector: Input vector\n    \"\"\"\n    # At times, a vector returned by a hasher is None (e.g., for hashes\n    # that depend on the image not being featureless). In those cases,\n    # we need to just return None, which is the least surprising outcome\n    # because after all, the string representation of None is None.\n    if vector is None:\n        return None\n    if hash_format == 'vector':\n        # return vector.astype(dtype)  # old behavior\n        raise DeprecationWarning(\"`hash_format` `vector` has been removed.\")\n    if dtype == 'uint8':\n        vector_bytes = vector.astype('uint8')\n    elif dtype == 'float32':\n        vector_bytes = vector.astype('float32')\n    elif dtype == 'bool':\n        vector_bytes = np.packbits(vector.astype('bool'))\n    else:\n        raise NotImplementedError(f'Cannot convert hash of type {dtype}.')\n    if hash_format == 'base64':\n        return base64.b64encode(vector_bytes.tobytes()).decode('utf-8')\n    if hash_format == 'hex':\n        return vector_bytes.tobytes().hex()\n    raise NotImplementedError(\n        f'Cannot convert to string format: {hash_format}.')\n\n\ndef string_to_vector(hash_string: str,\n                     dtype: str,\n                     hash_length: int,\n                     hash_format: str,\n                     verify_length: bool = True) -> np.ndarray:\n    \"\"\"Convert hash back to vector.\n\n    Args:\n        hash_string: The input hash string\n        dtype: The data type of the hash\n        hash_length: The length of the hash vector\n        hash_format: The input format of the hash (base64 or hex)\n        verify_length: Whether to verify the string length\n    \"\"\"\n    assert not verify_length or len(hash_string) == get_string_length(\n        hash_length=hash_length, hash_format=hash_format,\n        dtype=dtype), 'Incorrect string length for this hash format.'\n    if hash_format == 'base64':\n        vector_bytes = np.frombuffer(\n            base64.b64decode(hash_string),\n            dtype='uint8' if dtype in ['bool', 'uint8'] else dtype)\n    elif hash_format == 'hex':\n        vector_bytes = np.frombuffer(\n            bytearray.fromhex(hash_string),\n            dtype='uint8' if dtype in ['bool', 'uint8'] else dtype)\n    else:\n        raise NotImplementedError(\n            f'Cannot convert to string format: {hash_format}')\n    if dtype == 'uint8':\n        return vector_bytes[:hash_length]\n    if dtype == 'float32':\n        return vector_bytes[:hash_length]\n    if dtype == 'bool':\n        return np.unpackbits(vector_bytes)[:hash_length].astype('bool')\n    raise NotImplementedError(f'Cannot convert hash of type {dtype}.')\n\n\ndef hex_to_b64(hash_string: str,\n               dtype: str,\n               hash_length: int,\n               verify_length: bool = True):\n    \"\"\"Convert a hex-encoded hash to base64.\n\n    Args:\n        hash_string: The input base64 hash string\n        dtype: The data type of the hash\n        hash_length: The length of the hash vector\n        verify_length: Whether to verify the string length\n    \"\"\"\n    return vector_to_string(\n        string_to_vector(\n            hash_string,\n            hash_length=hash_length,\n            hash_format='hex',\n            dtype=dtype,\n            verify_length=verify_length),\n        dtype=dtype,\n        hash_format='base64')\n\n\ndef b64_to_hex(hash_string: str,\n               dtype: str,\n               hash_length: int,\n               verify_length: bool = True):\n    \"\"\"Convert a base64-encoded hash to hex.\n\n    Args:\n        hash_string: The input hex hash string\n        dtype: The data type of the hash\n        hash_length: The length of the hash vector\n        verify_length: Whether to verify the string length\n    \"\"\"\n    return vector_to_string(\n        string_to_vector(\n            hash_string,\n            hash_length=hash_length,\n            hash_format='base64',\n            dtype=dtype,\n            verify_length=verify_length),\n        dtype=dtype,\n        hash_format='hex')\n\n\ndef to_image_array(image: ImageInputType, require_color=True):\n    if isinstance(image, np.ndarray):\n        assert image.flags['C_CONTIGUOUS'], (\n            'Provided arrays must be contiguous to avoid '\n            'erroneous results when arrays are passed to '\n            'underlying libraries. This can be achieved using'\n            'np.ascontiguousarray(image)')\n        assert not require_color or (len(image.shape) == 3\n                                     and image.shape[-1] == 3), (\n                                         'Provided images must be RGB images.')\n        return image\n    return read(image)\n\n\ndef get_common_framerates(id_rates: dict):\n    \"\"\"Compute an optimal set of framerates for a list\n    of framerates. Optimal here means that reading the video\n    at each of the framerates will allow one to collect all\n    of the frames required with the smallest possible number of\n    frames decoded.\n\n    For example, consider if we need to read a video at\n    3 fps, 5 fps, 1 fps and 0.5 fps. We could read the video\n    4 times (once per framerate). But a more optimal approach\n    is to read the video only twice, once at 3 frames per second\n    and another time at 5 frames per second. For the 1 fps hasher,\n    we simply pass every 3rd frame of the 3 fps pass. For the\n    0.5 fps hasher, we pass every 6th frame of the 3 fps pass. So\n    if you pass this function {A: 3, B: 5, C: 1, D: 0.5}, you will\n    get back {3: [A, C, D], 5: C}.\n\n    Args:\n        id_rates: A dictionary with IDs as keys and frame rates as values.\n\n    Returns:\n        rate_ids: A dictionary with framerates as keys and a list of\n            ids as values.\n    \"\"\"\n\n    def partition(collection):\n        \"\"\"This function taken from\n        https://stackoverflow.com/questions/19368375/set-partitions-in-python/30134039#30134039\n        \"\"\"\n        if len(collection) == 1:\n            yield [collection]\n            return\n\n        first = collection[0]\n        for smaller in partition(collection[1:]):\n            # insert `first` in each of the subpartition's subsets\n            for n, subset in enumerate(smaller):\n                yield smaller[:n] + [[first] + subset] + smaller[n + 1:]\n            # put `first` in its own subset\n            yield [[first]] + smaller\n\n    framerates = list(id_rates.values())\n    factor = 2 * 3 * 5 * 7 * 11 * 60 * 60\n    assert min(framerates\n               ) >= 1 / factor, 'Framerates must be at least 1 frame per hour.'\n    best_frame_count = np.inf\n    best_grouping: typing.Optional[typing.List] = None\n    best_frame_rates: typing.Optional[typing.List] = None\n\n    # We try every possible grouping of framerates to minimize the number\n    # of frames we decode. There is likely a better way to do this,\n    # but this seems to do the job for now.\n    for grouping in partition(list(set(framerates))):\n        current_frame_rates = [\n            # pylint: disable=no-member\n            functools.reduce(np.lcm,\n                             (np.array(group) * factor).round().astype(int)) /\n            factor for group in grouping\n        ]\n        current_frame_count = sum(current_frame_rates)\n        if current_frame_count < best_frame_count:\n            best_frame_count = current_frame_count\n            best_frame_rates = current_frame_rates\n            best_grouping = grouping\n\n    assert best_frame_rates is not None\n    assert best_grouping is not None\n    return {\n        framerate:\n        tuple(name for name, rate in id_rates.items() if rate in group)\n        for framerate, group in zip(best_frame_rates, best_grouping)\n    }\n\n\ndef get_isometric_transforms(image: ImageInputType, require_color=True):\n    image = to_image_array(image, require_color=require_color)\n    return dict(\n        r0=image,\n        fv=np.ascontiguousarray(image[::-1, :]),\n        fh=np.ascontiguousarray(image[:, ::-1]),\n        r180=np.ascontiguousarray(image[::-1, ::-1]),\n        r90=np.ascontiguousarray(image.transpose(1, 0, 2)[::-1, :, :]),\n        r90fv=np.ascontiguousarray(image.transpose(1, 0, 2)),\n        r90fh=np.ascontiguousarray(image.transpose(1, 0, 2)[::-1, ::-1]),\n        r270=np.ascontiguousarray(image.transpose(1, 0, 2)[:, ::-1]))\n\n\ndef get_isometric_dct_transforms(dct: np.ndarray):\n    # pylint: disable=invalid-name\n    T1 = np.empty_like(dct)\n    T1[::2] = 1\n    T1[1::2] = -1\n\n    # pylint: disable=invalid-name\n    T2 = np.empty_like(dct)\n    T2[::2, ::2] = 1\n    T2[1::2, 1::2] = 1\n    T2[::2, 1::2] = -1\n    T2[1::2, ::2] = -1\n    return dict(\n        r0=dct,\n        fv=dct * T1,\n        fh=dct * T1.T,\n        r180=dct * T2,\n        r90=dct.T * T1,\n        r90fv=dct.T,\n        r90fh=dct.T * T2,\n        r270=dct.T * T1.T)\n\n\ndef read(filepath_or_buffer: ImageInputType, timeout=None):\n    \"\"\"Read a file into an image object\n\n    Args:\n        filepath_or_buffer: The path to the file or any object\n            with a `read` method (such as `io.BytesIO`)\n        timeout: If filepath_or_buffer is a URL, the timeout to\n            use for making the HTTP request.\n    \"\"\"\n    if PIL is not None and isinstance(filepath_or_buffer, PIL.Image.Image):\n        return np.array(filepath_or_buffer.convert(\"RGB\"))\n    if isinstance(filepath_or_buffer, (io.BytesIO, client.HTTPResponse)):\n        image = np.asarray(\n            bytearray(filepath_or_buffer.read()), dtype=np.uint8)\n        image = cv2.imdecode(image, cv2.IMREAD_UNCHANGED)\n    elif isinstance(filepath_or_buffer, str):\n        if validators.url(filepath_or_buffer):\n            return read(request.urlopen(filepath_or_buffer, timeout=timeout))\n        if not os.path.isfile(filepath_or_buffer):\n            raise FileNotFoundError('Could not find image at path: ' +\n                                    filepath_or_buffer)\n        image = cv2.imread(filepath_or_buffer)\n    else:\n        raise RuntimeError(\"Unhandled filepath_or_buffer type: \" +\n                           str(type(filepath_or_buffer)))\n    if image is None:\n        raise ValueError(f'An error occurred reading {filepath_or_buffer}.')\n    # We use cvtColor here instead of just ret[..., ::-1]\n    # in order to ensure that we provide a contiguous\n    # array for later processing. Some hashers use ctypes\n    # to pass the array and non-contiguous arrays can lead\n    # to erroneous results.\n    return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n\ndef _get_keyframes(filepath):\n    \"\"\"Get the keyframes for a video.\n\n    Args:\n        filepath: Path to the target file\n\n    Returns:\n        A list of frame indexes.\n    \"\"\"\n    args = [\n        get_ffprobe(), '-select_streams', 'v', '-i', f\"'{filepath}'\",\n        '-print_format', 'json', '-show_entries',\n        'frame=pict_type,coded_picture_number'\n    ]\n    with subprocess.Popen(\n            args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p:\n        out, err = p.communicate()\n        if p.returncode != 0:\n            raise ValueError(\"{out}: {err}\".format(out=str(out), err=str(err)))\n        data = json.loads(out.decode('utf-8'))['frames']\n        frames = [\n            f['coded_picture_number'] for f in data if f['pict_type'] == 'I'\n        ]\n        frames = list(set(frames))\n        frames.sort()\n    return frames\n\n\ndef get_video_properties(filepath):\n    cmd = f\"\"\"\n    {get_ffprobe()} -select_streams v:0 -i '{filepath}'\n    -print_format json -show_entries stream=width,height,avg_frame_rate,codec_name,start_time\n    \"\"\"\n    with subprocess.Popen(\n            shlex.split(cmd), stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE) as p:\n        out, err = p.communicate()\n        if p.returncode != 0:\n            raise ValueError(\"{out}: {err}\".format(out=str(out), err=str(err)))\n        data = json.loads(out.decode(\"utf-8\"))[\"streams\"][0]\n        numerator, denominator = tuple(\n            map(int, data[\"avg_frame_rate\"].split(\"/\")[:2]))\n        avg_frame_rate: typing.Optional[fractions.Fraction]\n        if numerator > 0 and denominator > 0:\n            avg_frame_rate = fractions.Fraction(\n                numerator=numerator, denominator=denominator)\n        else:\n            avg_frame_rate = None\n        return data[\"width\"], data[\"height\"], avg_frame_rate, data[\n            \"codec_name\"], float(data.get(\"start_time\", \"0\"))\n\n\n# pylint: disable=too-many-branches,too-many-statements,too-many-arguments\ndef read_video_to_generator_ffmpeg(\n        filepath,\n        frames_per_second: typing.Optional[typing.Union[str, float]] = None,\n        errors=\"raise\",\n        max_duration: float = None,\n        max_size: int = None,\n        interp: str = None,\n        frame_rounding: str = \"up\",\n        draw_timestamps=False,\n        use_cuda=False) -> FramesWithIndexesAndTimestamps:\n    \"\"\"This is used by :code:`read_video` when :code:`use_ffmpeg` is True. It\n    differs from :code:`read_video_to_generator` in that it uses FFMPEG instead of\n    OpenCV and, optionally, allows for CUDA acceleration. CUDA acceleration\n    can be faster for larger videos (>1080p) where downsampling is desired.\n    For other videos, CUDA may be slower, but the decoding load will still be\n    taken off the CPU, which may still be advantageous. You can specify which\n    FFMPEG binary to use by setting PERCEPTION_FFMPEG_BINARY.\n\n    Args:\n        filepath: See read_video\n        frames_per_second: See read_video\n        errors: See read_video\n        max_duration: See read_video\n        max_size: See read_video\n        interp: The interpolation method to use. When not using CUDA, you must choose one\n            of the `interpolation options <https://ffmpeg.org/ffmpeg-scaler.html#sws_005fflags>`_\n            (default: area). When using CUDA, you must choose from the\n            `interp_algo options <http://underpop.online.fr/f/ffmpeg/help/scale_005fnpp.htm.gz>`_\n            (default: super).\n        frame_rounding: The frame rounding method.\n        draw_timestamps: Draw original timestamps onto the frames (for debugging only)\n        use_cuda: Whether to enable CUDA acceleration. Requires a\n            CUDA-accelerated version of ffmpeg.\n\n    To build FFMPEG with CUDA, do the following in a Docker\n    container based on nvidia/cuda:10.1-cudnn7-devel-ubuntu18.04. The\n    FFMPEG binary will be ffmpeg/ffmpeg.\n\n    .. code-block:: bash\n\n        git clone https://git.videolan.org/git/ffmpeg/nv-codec-headers.git\n        cd nv-codec-headers\n        make\n        sudo make install\n        cd ..\n        git clone --branch release/4.3 https://git.ffmpeg.org/ffmpeg.git\n        cd ffmpeg\n        sudo apt-get update && sudo apt-get -y install yasm\n        export PATH=$PATH:/usr/local/cuda/bin\n        ./configure --enable-cuda-nvcc --enable-cuvid --enable-nvenc --enable-nvdec \\\n                    --enable-libnpp --enable-nonfree --extra-cflags=-I/usr/local/cuda/include \\\n                    --extra-ldflags=-L/usr/local/cuda/lib64\n        make -j 10\n\n    Returns:\n        See :code:`read_video`\n    \"\"\"\n    if interp is None:\n        interp = \"super\" if use_cuda else \"area\"\n    try:\n        raw_width, raw_height, avg_frame_rate, codec_name, start_time = get_video_properties(\n            filepath)\n        start_time_offset = 0.0 if avg_frame_rate is None else float(\n            (1 / (2 * avg_frame_rate)))\n        LOGGER.debug(\n            \"raw_width: %s, raw_height: %s, avg_frame_rate: %s, codec_name: %s, start_time: %s\",\n            raw_width, raw_height, avg_frame_rate, codec_name, start_time)\n        channels = 3\n        scale = (min(max_size / raw_width, max_size / raw_height, 1)\n                 if max_size is not None else 1)\n        width, height = map(lambda d: int(round(scale * d)),\n                            [raw_width, raw_height])\n        # If there is no average frame rate, the offset tends to be unreliable.\n        offset = max(start_time,\n                     start_time_offset) if avg_frame_rate is not None else 0\n        cmd = (f\"{get_ffmpeg()} -hide_banner -an -vsync 0 -loglevel fatal \"\n               f\"-itsoffset -{offset}\")\n        filters = []\n        if draw_timestamps:\n            pattern = \"%{pts}-%{frame_num}\"\n            filters.append(f\"drawtext=fontsize={int(raw_height * 0.1)}:\"\n                           f\"fontcolor=yellow:text={pattern}\"\n                           \":x=(w-text_w):y=(h-text_h)\")\n        # Add frame rate filters.\n        if frames_per_second is None:\n            seconds_per_frame = float(\n                1 / avg_frame_rate) if avg_frame_rate is not None else None\n        elif frames_per_second == \"keyframes\":\n            seconds_per_frame = None\n            filters.append(r\"select=eq(pict_type\\,I)\")\n        else:\n            assert isinstance(\n                frames_per_second,\n                (float, int)), f\"Invalid framerate: {frames_per_second}\"\n            seconds_per_frame = 1 / frames_per_second\n            filters.append(f\"fps={frames_per_second}:\"\n                           f\"round={frame_rounding}:\"\n                           f\"start_time={offset}\")\n        # Add resizing filters.\n        if use_cuda and codec_name in CUDA_CODECS:\n            cuda_codec = CUDA_CODECS[codec_name]\n            cmd += f\" -hwaccel cuda -c:v {cuda_codec}\"\n            filters.append(\"hwupload_cuda\")\n            if scale != 1:\n                filters.append(\n                    f\"scale_npp={width}:{height}:interp_algo={interp}\")\n            filters.extend([\n                \"hwdownload\",\n                \"format=nv12\",\n            ])\n        elif scale != 1:\n            filters.append(f\"scale={width}:{height}:flags={interp}\")\n        cmd += f\" -i '{filepath}'\"\n        if filters:\n            cmd += \" -vf '{fstring}'\".format(fstring=\",\".join(filters))\n        cmd += \" -pix_fmt rgb24 -f image2pipe -vcodec rawvideo -\"\n        LOGGER.debug(\"running ffmpeg with: %s\", cmd)\n        framebytes = width * height * channels\n        bufsize = framebytes * int(\n            os.environ.get(\"PERCEPTION_FFMPEG_BUFSIZE\", \"5\"))\n        with subprocess.Popen(\n                shlex.split(cmd),\n                stdout=subprocess.PIPE,\n                stderr=subprocess.PIPE,\n                bufsize=bufsize) as p:\n            assert p.stdout is not None, \"Could not launch subprocess pipe.\"\n            timestamp: typing.Optional[float] = 0\n            frame_index: typing.Optional[int] = 0\n            while True:\n                batch = p.stdout.read(bufsize)\n                if not batch:\n                    break\n                for image in np.frombuffer(\n                        batch, dtype=\"uint8\").reshape((-1, height, width,\n                                                       channels)):\n                    if frames_per_second != \"keyframes\":\n                        yield (image, frame_index, timestamp)\n                        if seconds_per_frame is not None:\n                            assert timestamp is not None\n                            timestamp += seconds_per_frame\n                            frame_index = math.ceil(\n                                avg_frame_rate * timestamp\n                            ) if avg_frame_rate is not None else None\n                        else:\n                            timestamp = None\n                            frame_index = None\n                    else:\n                        # Obtaining the keyframe indexes with ffprobe is very slow (slower\n                        # than reading the video sometimes). We don't *have* to do it\n                        # when using ffmpeg, so we don't. The OpenCV approach *does*\n                        # get the keyframe indexes, but only because they're required\n                        # in order to select them.\n                        yield (image, None, None)\n                    if (max_duration is not None and timestamp is not None\n                            and timestamp > max_duration):\n                        break\n            stdout, stderr = p.communicate()\n            if p.returncode != 0:\n                raise ValueError(\n                    f\"Error parsing video: {stdout.decode('utf-8')} {stderr.decode('utf-8')}\"\n                )\n    # pylint: disable=broad-except\n    except Exception as e:\n        if errors not in [\"warn\", \"ignore\"]:\n            raise e\n        if errors == \"warn\":\n            warnings.warn(\n                message=\n                f\"An error occurred while reading {filepath}. Processing may be truncated.\"\n            )\n\n\n# pylint: disable=too-many-branches,too-many-locals,too-many-statements\ndef read_video_to_generator(\n        filepath,\n        frames_per_second: typing.Optional[typing.Union[str, float]] = None,\n        errors='raise',\n        max_duration: float = None,\n        max_size: int = None) -> FramesWithIndexesAndTimestamps:\n    \"\"\"This is used by :code:`read_video` when :code:`use_ffmpeg` is False (default).\n\n    Args:\n        filepath: See :code:`read_video`.\n        frames_per_second: See :code:`read_video`.\n        errors: See :code:`read_video`.\n        max_duration: See :code:`read_video`.\n        max_size: See :code:`read_video`.\n\n    Returns:\n        See :code:`read_video`.\n    \"\"\"\n    # pylint: disable=no-member\n    if cv2.__version__ < '4.1.1' and filepath.lower().endswith('gif'):\n        message = 'Versions of OpenCV < 4.1.1 may read GIF files improperly. Upgrade recommended.'\n        if errors == 'raise':\n            raise ValueError(message)\n        warnings.warn(message=message)\n\n    if not os.path.isfile(filepath):\n        raise FileNotFoundError(f'Could not find {filepath}.')\n    cap = cv2.VideoCapture(filename=filepath, apiPreference=cv2.CAP_FFMPEG)\n    try:\n        # The purpose of the following block is largely to create a\n        # frame_indexes (iterator or list) that indicates which\n        # frames we should be returning to the user and then\n        # yielding those frames as we come across them.\n        file_frames_per_second = cap.get(cv2.CAP_PROP_FPS)\n        if file_frames_per_second == 0:\n            if errors == \"raise\":\n                raise ValueError(\"Video file has framerate of 0fps.\")\n            # The known case where this occurs is for GIFs, where\n            # 0 fps is typically inferred as 10 fps.\n            file_frames_per_second = 10\n            if errors == \"warn\":\n                warnings.warn(\n                    message=\n                    \"Video file has framerate of 0 fps. Guessing framerate of 10fps.\"\n                )\n        if frames_per_second is None:\n            frames_per_second = file_frames_per_second\n        seconds_between_desired_frames = None if (\n            frames_per_second is not None\n            and isinstance(frames_per_second,\n                           str)) else 1 / frames_per_second  # type: ignore\n        seconds_between_grabbed_frames = 1 / file_frames_per_second\n        grabbed_frame_count = 0\n        if frames_per_second == 'keyframes':\n            frame_indexes: typing.Union[range, typing.List[int], typing.\n                                        Iterator[int]] = _get_keyframes(\n                                            filepath)\n            # The repeat flag is used to handle the case where the\n            # desired sampling rate is higher than the file's frame\n            # rate. In this case, we will need to repeat frames in\n            # order to provide the least-surprising behavior that\n            # we can.\n            repeat = False\n        else:\n            frame_indexes = itertools.count(\n                0, max(1, file_frames_per_second / frames_per_second))\n            repeat = file_frames_per_second < frames_per_second\n        input_width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)\n        input_height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)\n        if max_size is not None:\n            scale = min(max_size / max(input_width, input_height), 1)\n        else:\n            scale = 1\n        target_size: typing.Optional[typing.Tuple[int, int]]\n        if scale < 1:\n            target_size = (int(scale * input_width), int(scale * input_height))\n        else:\n            target_size = None\n        for frame_index in frame_indexes:\n            while grabbed_frame_count < frame_index:\n                # We need to skip this frame.\n                success = cap.grab()\n                if not success:\n                    break\n                grabbed_frame_count += 1\n            success, frame = cap.read()\n            grabbed_frame_count += 1\n            if not success:\n                # The video is over or an error has occurred.\n                break\n            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n            if target_size is not None:\n                frame = cv2.resize(\n                    frame, target_size, interpolation=cv2.INTER_NEAREST)\n            current_timestamp = frame_index / file_frames_per_second\n            yield frame, grabbed_frame_count - 1, current_timestamp\n            if max_duration is not None and current_timestamp > max_duration:\n                break\n            if repeat:\n                next_desired_timestamp = current_timestamp + seconds_between_desired_frames\n                next_timestamp = current_timestamp + seconds_between_grabbed_frames\n                while next_desired_timestamp < next_timestamp:\n                    yield (frame, grabbed_frame_count - 1,\n                           next_desired_timestamp)\n                    next_desired_timestamp += seconds_between_desired_frames\n    # pylint: disable=broad-except\n    except Exception as e:\n        if errors not in ['warn', 'ignore']:\n            raise e\n        if errors == 'warn':\n            warnings.warn(\n                message=\n                f'An error occurred while reading {filepath}. Processing may be truncated.'\n            )\n    finally:\n        cap.release()\n\n\ndef read_video_into_queue(*args, video_queue, terminate, func, **kwargs):\n    # We're inside a thread now and the queue is being read elsewhere.\n    try:\n        for frame, frame_index, timestamp in func(*args, **kwargs):\n            if not terminate.isSet():\n                video_queue.put((frame, frame_index, timestamp))\n            else:\n                break\n    finally:\n        video_queue.put((None, None, None))\n\n\n# pylint: disable=too-many-arguments\ndef read_video(\n        filepath,\n        frames_per_second: typing.Optional[typing.Union[str, float]] = None,\n        max_queue_size=128,\n        use_queue=True,\n        errors='raise',\n        use_ffmpeg=False,\n        **kwargs) -> FramesWithIndexesAndTimestamps:\n    \"\"\"Provides a generator of RGB frames, frame indexes, and timestamps from a\n    video. This function requires you to have installed ffmpeg. All other\n    arguments passed to read_video_to_generator.\n\n    Args:\n        filepath: Path to the video file\n        frames_per_second: How many frames to provide for\n            each second of video. If None, all frames\n            are provided. If frames_per_second is \"keyframes\",\n            we use ffmpeg to select I frames from the video.\n        max_queue_size: The maximum number of frames to load in the queue\n        use_queue: Whether to use a queue of frames during processing\n        max_duration: The maximum length of the video to hash.\n        max_size: The maximum size of frames to queue\n        errors: Whether to 'raise', 'warn', or 'ignore' errors\n        use_ffmpeg: Whether to use the FFMPEG CLI to read videos. If True, other\n            kwargs (e.g., :code:`use_cuda`) are passed to\n            :code:`read_video_to_generator_ffmpeg`.\n\n    Yields:\n        (frame, frame_index, timestamp) tuples\n    \"\"\"\n    for ffmpeg_kwarg in [\n            \"interp\", \"frame_rounding\", \"draw_timestamps\", \"use_cuda\"\n    ]:\n        if not use_ffmpeg and ffmpeg_kwarg in kwargs:\n            warnings.warn(\n                f\"{ffmpeg_kwarg} is ignored when use_ffmpeg is False.\",\n                UserWarning)\n            del kwargs[ffmpeg_kwarg]\n    generator: typing.Callable[..., FramesWithIndexesAndTimestamps]\n    if use_ffmpeg:\n        generator = read_video_to_generator_ffmpeg\n    else:\n        generator = read_video_to_generator\n    frame_index: typing.Optional[int]\n    timestamp: typing.Optional[float]\n    if use_queue:\n        video_queue = queue.Queue(\n            maxsize=max_queue_size\n        )  # type: queue.Queue[typing.Tuple[np.ndarray, int, float]]\n        terminate = threading.Event()\n        thread = threading.Thread(\n            target=read_video_into_queue,\n            kwargs={\n                'frames_per_second': frames_per_second,\n                'func': generator,\n                'video_queue': video_queue,\n                'filepath': filepath,\n                'errors': errors,\n                'terminate': terminate,\n                **kwargs\n            })\n        thread.start()\n        try:\n            while True:\n                frame, frame_index, timestamp = video_queue.get()\n                video_queue.task_done()\n                if frame is None:\n                    break\n                yield (frame, frame_index, timestamp)\n        finally:\n            # Set the termination flag for the\n            # background thread.\n            terminate.set()\n            try:\n                # Unblock the thread, in the event\n                # that it is waiting.\n                video_queue.get_nowait()\n\n                # Do it twice for the edge case\n                # where the queue is completely\n                # full and the end sentinel is\n                # blocking.\n                video_queue.get_nowait()\n            except queue.Empty:\n                # It doesn't matter if it's empty.\n                pass\n            # Wait for the background thread to terminate.\n            thread.join()\n    else:\n        for frame, frame_index, timestamp in generator(\n                filepath=filepath,\n                frames_per_second=frames_per_second,\n                errors=errors,\n                **kwargs):\n            yield (frame, frame_index, timestamp)\n\n\ndef compute_synchronized_video_hashes(filepath: str,\n                                      hashers: dict,\n                                      framerates=None,\n                                      hash_format='base64',\n                                      use_queue=True):\n    \"\"\"Compute the video hashes for a group of hashers with synchronized\n    frame processing wherever possible.\n\n    Args:\n        filepath: Path to video file.\n        hashers: A dictionary mapping hasher names to video hasher objects\n        hash_format: The format in which to return the hashes\n        use_queue: Whether to use queued video frames\n    \"\"\"\n    if framerates is None:\n        framerates = get_common_framerates({\n            k: h.frames_per_second\n            for k, h in hashers.items() if h.frames_per_second is not None\n        })\n    else:\n        assert all(\n            any(hasher_name in hasher_names\n                for hasher_names in framerates.values())\n            for hasher_name, hasher in hashers.items()\n            if hasher.frames_per_second is not None\n        ), 'Provided framerates do not have an entry for all required hashers.'\n\n    results = {\n        hasher_name: {\n            'state':\n            None,\n            'hash':\n            None,\n            'relative_framerate':\n            next(framerate / hasher.frames_per_second\n                 for framerate, hasher_names in framerates.items()\n                 if hasher_name in hasher_names)\n        }\n        for hasher_name, hasher in hashers.items()\n        if hasher.frames_per_second is not None\n    }\n    for current_framerate, current_hasher_names in framerates.items():\n        for frame_index, (frame, grabbed_frame_index,\n                          frame_timestamp) in enumerate(\n                              read_video(\n                                  filepath=filepath,\n                                  frames_per_second=current_framerate,\n                                  use_queue=use_queue)):\n            for hasher_name in current_hasher_names:\n                config = results[hasher_name]\n                hasher = hashers[hasher_name]\n                assert config['relative_framerate'] is not None\n                if frame_index % config['relative_framerate'] == 0:\n                    config['state'] = hasher.process_frame(\n                        frame=frame,\n                        frame_index=grabbed_frame_index,\n                        frame_timestamp=frame_timestamp,\n                        state=config['state'])\n        for hasher_name in current_hasher_names:\n            config = results[hasher_name]\n            hasher = hashers[hasher_name]\n            current_hash = hasher.hash_from_final_state(state=config['state'])\n            if hash_format == 'vector':\n                config['hash'] = current_hash\n            else:\n                if not hasher.returns_multiple:\n                    config['hash'] = hasher.vector_to_string(\n                        current_hash, hash_format=hash_format)\n                else:\n                    config['hash'] = [\n                        hasher.vector_to_string(h, hash_format=hash_format)\n                        for h in current_hash\n                    ]\n            config['state'] = None\n    hashes = {\n        hasher_name: config['hash']\n        for hasher_name, config in results.items()\n    }\n    for hasher_name, hasher in hashers.items():\n        if hasher.frames_per_second is None:\n            # This is a custom hasher that we just pass a video path to.\n            hashes[hasher_name] = hasher.compute(filepath)\n    return hashes\n\n\ndef unletterbox(image) -> typing.Optional[\n        typing.Tuple[typing.Tuple[int, int], typing.Tuple[int, int]]]:\n    \"\"\"Return bounds of non-trivial region of image or None.\n\n    Unletterboxing is cropping an image such that trivial edge regions\n    are removed. Trivial in this context means that the majority of\n    the values in that row or column are zero or very close to\n    zero. This is why we don't use the terms \"non-blank\" or\n    \"non-empty.\"\n\n    In order to do unletterboxing, this function returns bounds in the\n    form (x1, x2), (y1, y2) where:\n\n    - x1 is the index of the first column where over 10% of the pixels\n      have means (average of R, G, B) > 2.\n    - x2 is the index of the last column where over 10% of the pixels\n      have means > 2.\n    - y1 is the index of the first row where over 10% of the pixels\n      have means > 2.\n    - y2 is the index of the last row where over 10% of the pixels\n      have means > 2.\n\n    If there are zero columns or zero rows where over 10% of the\n    pixels have means > 2, this function returns `None`.\n\n    Note that in the case(s) of a single column and/or row of\n    non-trivial pixels that it is possible for x1 = x2 and/or y1 = y2.\n\n    Consider these examples to understand edge cases.  Given two\n    images, `L` (entire left and bottom edges are 1, all other pixels\n    0) and `U` (left, bottom and right edges 1, all other pixels 0),\n    `unletterbox(L)` would return the bounds of the single bottom-left\n    pixel and `unletterbox(U)` would return the bounds of the entire\n    bottom row.\n\n    Consider `U1` which is the same as `U` but with the bottom two\n    rows all 1s. `unletterbox(U1)` returns the bounds of the bottom\n    two rows.\n\n    Args:\n        image: The image from which to remove letterboxing.\n\n    Returns:\n        A pair of coordinates bounds of the form (x1, x2)\n        and (y1, y2) representing the left, right, top, and\n        bottom bounds.\n\n    \"\"\"\n    # adj should be thought of as a boolean at each pixel indicating\n    # whether or not that pixel is non-trivial (True) or not (False).\n    adj = image.mean(axis=2) > 2\n\n    if adj.all():\n        return (0, image.shape[1] + 1), (0, image.shape[0] + 1)\n\n    y = np.where(adj.sum(axis=1) > 0.1 * image.shape[1])[0]\n    x = np.where(adj.sum(axis=0) > 0.1 * image.shape[0])[0]\n\n    if len(y) == 0 or len(x) == 0:\n        return None\n\n    if len(y) == 1:\n        y1 = y2 = y[0]\n    else:\n        y1, y2 = y[[0, -1]]\n    if len(x) == 1:\n        x1 = x2 = x[0]\n    else:\n        x1, x2 = x[[0, -1]]\n    bounds = (x1, x2 + 1), (y1, y2 + 1)\n\n    return bounds\n", "meta": {"hexsha": "053b0b8092021377dd384041d0c86fba87c67729", "size": 39155, "ext": "py", "lang": "Python", "max_stars_repo_path": "perception/hashers/tools.py", "max_stars_repo_name": "thorn-oss/perception", "max_stars_repo_head_hexsha": "e78790982ea3a02d100955ea45583243e2bd8ccd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 123, "max_stars_repo_stars_event_min_datetime": "2019-11-04T19:29:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T13:49:12.000Z", "max_issues_repo_path": "perception/hashers/tools.py", "max_issues_repo_name": "thorn-oss/perception", "max_issues_repo_head_hexsha": "e78790982ea3a02d100955ea45583243e2bd8ccd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2019-11-05T06:51:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T04:09:58.000Z", "max_forks_repo_path": "perception/hashers/tools.py", "max_forks_repo_name": "thorn-oss/perception", "max_forks_repo_head_hexsha": "e78790982ea3a02d100955ea45583243e2bd8ccd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-11-05T17:47:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:27:31.000Z", "avg_line_length": 39.312248996, "max_line_length": 98, "alphanum_fraction": 0.5950453327, "include": true, "reason": "import numpy", "num_tokens": 8931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091673, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.19758494542989596}}
{"text": "'''\nhttps://github.com/christiancosgrove/pytorch-spectral-normalization-gan\n\nchainer: https://github.com/pfnet-research/sngan_projection\n'''\n\n# ResNet generator and discriminator\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\n# from spectral_normalization import SpectralNorm\nimport numpy as np\nfrom torch.nn.utils import spectral_norm\n\n\n\nchannels = 3\nbias = True\nGEN_SIZE=64\nDISC_SIZE=64\n\nDIM_EMBED=128\n\n\n\nclass ConditionalBatchNorm2d(nn.Module):\n    def __init__(self, num_features, dim_embed):\n        super().__init__()\n        self.num_features = num_features\n        self.bn = nn.BatchNorm2d(num_features, affine=False)\n\n        # self.embed = nn.Linear(dim_embed, num_features * 2, bias=False)\n        # self.embed.weight.data[:, :num_features].normal_(1, 0.02)  # Initialise scale at N(1, 0.02)\n        # self.embed.weight.data[:, num_features:].zero_()  # Initialise bias at 0\n        # # self.embed = spectral_norm(self.embed) #seems not work\n\n        self.embed_gamma = nn.Linear(dim_embed, num_features, bias=False)\n        self.embed_beta = nn.Linear(dim_embed, num_features, bias=False)\n\n    def forward(self, x, y):\n        out = self.bn(x)\n\n        # gamma, beta = self.embed(y).chunk(2, 1)\n        # out = gamma.view(-1, self.num_features, 1, 1) * out + beta.view(-1, self.num_features, 1, 1)\n\n        gamma = self.embed_gamma(y).view(-1, self.num_features, 1, 1)\n        beta = self.embed_beta(y).view(-1, self.num_features, 1, 1)\n        out = out + out*gamma + beta\n\n        return out\n\n\nclass ResBlockGenerator(nn.Module):\n\n    def __init__(self, in_channels, out_channels, dim_embed, bias=True):\n        super(ResBlockGenerator, self).__init__()\n\n        self.conv1 = nn.Conv2d(in_channels, out_channels, 3, 1, padding=1, bias=bias)\n        self.conv2 = nn.Conv2d(out_channels, out_channels, 3, 1, padding=1, bias=bias)\n        nn.init.xavier_uniform_(self.conv1.weight.data, np.sqrt(2))\n        nn.init.xavier_uniform_(self.conv2.weight.data, np.sqrt(2))\n\n        self.condbn1 = ConditionalBatchNorm2d(in_channels, dim_embed)\n        self.condbn2 = ConditionalBatchNorm2d(out_channels, dim_embed)\n        self.relu = nn.ReLU()\n        self.upsample = nn.Upsample(scale_factor=2)\n\n        # unconditional case\n        self.model = nn.Sequential(\n            nn.BatchNorm2d(in_channels),\n            nn.ReLU(),\n            nn.Upsample(scale_factor=2),\n            self.conv1,\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(),\n            self.conv2\n            )\n\n\n        self.bypass_conv = nn.Conv2d(in_channels,out_channels, 1, 1, padding=0, bias=bias) #h=h\n        nn.init.xavier_uniform_(self.bypass_conv.weight.data, 1.0)\n        self.bypass = nn.Sequential(\n            nn.Upsample(scale_factor=2),\n            self.bypass_conv,\n        )\n\n    def forward(self, x, y):\n        if y is not None:\n            out = self.condbn1(x, y)\n            out = self.relu(out)\n            out = self.upsample(out)\n            out = self.conv1(out)\n            out = self.condbn2(out, y)\n            out = self.relu(out)\n            out = self.conv2(out)\n            out = out + self.bypass(x)\n        else:\n            out = self.model(x) + self.bypass(x)\n\n        return out\n\nclass ResBlockDiscriminator(nn.Module):\n\n    def __init__(self, in_channels, out_channels, stride=1):\n        super(ResBlockDiscriminator, self).__init__()\n\n        self.conv1 = nn.Conv2d(in_channels, out_channels, 3, 1, padding=1, bias=bias)\n        self.conv2 = nn.Conv2d(out_channels, out_channels, 3, 1, padding=1, bias=bias)\n        nn.init.xavier_uniform_(self.conv1.weight.data, np.sqrt(2))\n        nn.init.xavier_uniform_(self.conv2.weight.data, np.sqrt(2))\n\n        if stride == 1:\n            self.model = nn.Sequential(\n                nn.ReLU(),\n                spectral_norm(self.conv1),\n                nn.ReLU(),\n                spectral_norm(self.conv2)\n                )\n        else:\n            self.model = nn.Sequential(\n                nn.ReLU(),\n                spectral_norm(self.conv1),\n                nn.ReLU(),\n                spectral_norm(self.conv2),\n                nn.AvgPool2d(2, stride=stride, padding=0)\n                )\n\n        self.bypass_conv = nn.Conv2d(in_channels,out_channels, 1, 1, padding=0, bias=bias)\n        nn.init.xavier_uniform_(self.bypass_conv.weight.data, 1.0)\n        if stride != 1:\n            self.bypass = nn.Sequential(\n                spectral_norm(self.bypass_conv),\n                nn.AvgPool2d(2, stride=stride, padding=0)\n            )\n        else:\n            self.bypass = nn.Sequential(\n                spectral_norm(self.bypass_conv),\n            )\n\n    def forward(self, x):\n        return self.model(x) + self.bypass(x)\n\n# special ResBlock just for the first layer of the discriminator\nclass FirstResBlockDiscriminator(nn.Module):\n\n    def __init__(self, in_channels, out_channels, stride=1):\n        super(FirstResBlockDiscriminator, self).__init__()\n\n        self.conv1 = nn.Conv2d(in_channels, out_channels, 3, 1, padding=1, bias=bias)\n        self.conv2 = nn.Conv2d(out_channels, out_channels, 3, 1, padding=1, bias=bias)\n        self.bypass_conv = nn.Conv2d(in_channels, out_channels, 1, 1, padding=0, bias=bias)\n        nn.init.xavier_uniform_(self.conv1.weight.data, np.sqrt(2))\n        nn.init.xavier_uniform_(self.conv2.weight.data, np.sqrt(2))\n        nn.init.xavier_uniform_(self.bypass_conv.weight.data, 1.0)\n\n        # we don't want to apply ReLU activation to raw image before convolution transformation.\n        self.model = nn.Sequential(\n            spectral_norm(self.conv1),\n            nn.ReLU(),\n            spectral_norm(self.conv2),\n            nn.AvgPool2d(2)\n            )\n        self.bypass = nn.Sequential(\n            nn.AvgPool2d(2),\n            spectral_norm(self.bypass_conv),\n        )\n\n    def forward(self, x):\n        return self.model(x) + self.bypass(x)\n\n\n\nclass cont_cond_cnn_generator(nn.Module):\n    def __init__(self, nz=128, img_size=64, dim_embed=DIM_EMBED):\n        super(cont_cond_cnn_generator, self).__init__()\n        self.z_dim = nz\n        self.dim_embed = dim_embed\n\n        self.dense = nn.Linear(self.z_dim, 4 * 4 * GEN_SIZE*16, bias=True)\n        self.final = nn.Conv2d(GEN_SIZE, channels, 3, stride=1, padding=1, bias=bias)\n        nn.init.xavier_uniform_(self.dense.weight.data, 1.)\n        nn.init.xavier_uniform_(self.final.weight.data, 1.)\n\n        self.genblock0 = ResBlockGenerator(GEN_SIZE*16, GEN_SIZE*8, dim_embed=dim_embed) #4--->8\n        self.genblock1 = ResBlockGenerator(GEN_SIZE*8, GEN_SIZE*4, dim_embed=dim_embed) #8--->16\n        self.genblock2 = ResBlockGenerator(GEN_SIZE*4, GEN_SIZE*2, dim_embed=dim_embed) #16--->32\n        self.genblock3 = ResBlockGenerator(GEN_SIZE*2, GEN_SIZE, dim_embed=dim_embed) #32--->64\n\n        self.final = nn.Sequential(\n            nn.BatchNorm2d(GEN_SIZE),\n            nn.ReLU(),\n            self.final,\n            nn.Tanh()\n        )\n\n    def forward(self, z, y): #y is embedded in the feature space\n        z = z.view(z.size(0), z.size(1))\n        out = self.dense(z)\n        out = out.view(-1, GEN_SIZE*16, 4, 4)\n\n        out = self.genblock0(out, y)\n        out = self.genblock1(out, y)\n        out = self.genblock2(out, y)\n        out = self.genblock3(out, y)\n        out = self.final(out)\n\n        return out\n\n\nclass cont_cond_cnn_discriminator(nn.Module):\n    def __init__(self, img_size=64, dim_embed=DIM_EMBED):\n        super(cont_cond_cnn_discriminator, self).__init__()\n        self.dim_embed = dim_embed\n\n        self.discblock1 = nn.Sequential(\n            FirstResBlockDiscriminator(channels, DISC_SIZE, stride=2), #64--->32\n            ResBlockDiscriminator(DISC_SIZE, DISC_SIZE*2, stride=2), #32--->16\n            ResBlockDiscriminator(DISC_SIZE*2, DISC_SIZE*4, stride=2), #16--->8\n        )\n        self.discblock2 = ResBlockDiscriminator(DISC_SIZE*4, DISC_SIZE*8, stride=2) #8--->4\n        self.discblock3 = nn.Sequential(\n            ResBlockDiscriminator(DISC_SIZE*8, DISC_SIZE*16, stride=1), #4--->4;\n            nn.ReLU(),\n        )\n\n\n        # self.linear1 = nn.Linear(DISC_SIZE*16, 1, bias=True)\n        # nn.init.xavier_uniform_(self.linear1.weight.data, 1.)\n        # self.linear1 = spectral_norm(self.linear1)\n        # self.linear2 = nn.Linear(self.dim_embed, DISC_SIZE*16, bias=False)\n        # nn.init.xavier_uniform_(self.linear2.weight.data, 1.)\n        # self.linear2 = spectral_norm(self.linear2)\n\n        self.linear1 = nn.Linear(DISC_SIZE*16*4*4, 1, bias=True)\n        nn.init.xavier_uniform_(self.linear1.weight.data, 1.)\n        self.linear1 = spectral_norm(self.linear1)\n        self.linear2 = nn.Linear(self.dim_embed, DISC_SIZE*16*4*4, bias=False)\n        nn.init.xavier_uniform_(self.linear2.weight.data, 1.)\n        self.linear2 = spectral_norm(self.linear2)\n\n    def forward(self, x, y):\n        output = self.discblock1(x)\n        output = self.discblock2(output)\n        output = self.discblock3(output)\n\n        # output = torch.sum(output, dim=(2,3))\n        # output_y = torch.sum(output*self.linear2(y), 1, keepdim=True)\n        # output = self.linear1(output) + output_y\n\n        output = output.view(-1, DISC_SIZE*16*4*4)\n        output_y = torch.sum(output*self.linear2(y), 1, keepdim=True)\n        output = self.linear1(output) + output_y\n\n        return output.view(-1, 1)\n", "meta": {"hexsha": "202a027c80d461adf1b8b78e6a842f85a74e1b13", "size": 9338, "ext": "py", "lang": "Python", "max_stars_repo_path": "RC-49/RC-49_64x64/CcGAN-improved/models/cont_cond_cnn_generator_discriminator.py", "max_stars_repo_name": "asatk/improved_CcGAN", "max_stars_repo_head_hexsha": "29a58e6e2a03e56c2ad80ae1a2ebbd0710e026f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-26T00:07:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T00:07:37.000Z", "max_issues_repo_path": "RC-49/RC-49_64x64/CcGAN-improved/models/cont_cond_cnn_generator_discriminator.py", "max_issues_repo_name": "asatk/improved_CcGAN", "max_issues_repo_head_hexsha": "29a58e6e2a03e56c2ad80ae1a2ebbd0710e026f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RC-49/RC-49_64x64/CcGAN-improved/models/cont_cond_cnn_generator_discriminator.py", "max_forks_repo_name": "asatk/improved_CcGAN", "max_forks_repo_head_hexsha": "29a58e6e2a03e56c2ad80ae1a2ebbd0710e026f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4765625, "max_line_length": 102, "alphanum_fraction": 0.6200471193, "include": true, "reason": "import numpy", "num_tokens": 2454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.1975849450029357}}
{"text": "from __future__ import print_function\nimport numpy as np\nimport copy\nimport logging\nimport traceback\nfrom simtk import openmm, unit\nfrom perses.dispersed.feptasks import Particle, compute_reduced_potential\nfrom perses.storage import NetCDFStorageView\nfrom perses.annihilation.relative import HybridTopologyFactory\nfrom perses.tests.utils import quantity_is_finite\nfrom openmmtools.constants import kB\nfrom openmmtools.cache import LRUCache, global_context_cache\nfrom openmmtools.states import ThermodynamicState, SamplerState, CompoundThermodynamicState\nfrom perses.annihilation.lambda_protocol import RelativeAlchemicalState, LambdaProtocol\n\ndefault_temperature = 300.0*unit.kelvin\ndefault_nsteps = 1\ndefault_timestep = 1.0 * unit.femtoseconds\ndefault_steps_per_propagation = 1\n_logger = logging.getLogger(\"NCMCEngine\")\n\nclass NaNException(Exception):\n    def __init__(self, *args, **kwargs):\n        super(NaNException,self).__init__(*args,**kwargs)\n\nclass NCMCEngine(object):\n    \"\"\"\n    NCMC switching engine\n\n    Examples\n    --------\n\n    Create a transformation for an alanine dipeptide test system where the N-methyl group is eliminated.\n\n    >>> from openmmtools import testsystems\n    >>> testsystem = testsystems.AlanineDipeptideVacuum()\n    >>> from perses.rjmc.topology_proposal import TopologyProposal\n    >>> new_to_old_atom_map = { index : index for index in range(testsystem.system.getNumParticles()) if (index > 3) } # all atoms but N-methyl\n    >>> topology_proposal = TopologyProposal(old_system=testsystem.system, old_topology=testsystem.topology, old_chemical_state_key='AA', new_chemical_state_key='AA', new_system=testsystem.system, new_topology=testsystem.topology, logp_proposal=0.0, new_to_old_atom_map=new_to_old_atom_map, metadata=dict())\n    >>> ncmc_engine = NCMCEngine(temperature=300.0*unit.kelvin, functions=default_functions, nsteps=50, timestep=1.0*unit.femtoseconds)\n    >>> positions = testsystem.positions\n    >>> [positions, logP_delete, potential_delete] = ncmc_engine.integrate(topology_proposal, positions, direction='delete')\n    >>> [positions, logP_insert, potential_insert] = ncmc_engine.integrate(topology_proposal, positions, direction='insert')\n\n    \"\"\"\n\n    def __init__(self, temperature=default_temperature, functions=None, nsteps=default_nsteps,\n                 steps_per_propagation=default_steps_per_propagation, timestep=default_timestep,\n                 constraint_tolerance=None, platform=None, write_ncmc_interval=1, measure_shadow_work=False,\n                 integrator_splitting='V R O H R V', storage=None, verbose=False, LRUCapacity=10, pressure=None, bond_softening_constant=1.0, angle_softening_constant=1.0):\n        \"\"\"\n        This is the base class for NCMC switching between two different systems.\n\n        Arguments\n        ---------\n        temperature : simtk.unit.Quantity with units compatible with kelvin\n            The temperature at which switching is to be run\n        functions : dict of str:str, optional, default=default_functions\n            functions[parameter] is the function (parameterized by 't' which switched from 0 to 1) that\n            controls how alchemical context parameter 'parameter' is switched\n        nsteps : int, optional, default=1\n            The number of steps to use for switching.\n        steps_per_propagation : int, optional, default=1\n            The number of intermediate propagation steps taken at each switching step\n        timestep : simtk.unit.Quantity with units compatible with femtoseconds, optional, default=1*femtosecond\n            The timestep to use for integration of switching velocity Verlet steps.\n        constraint_tolerance : float, optional, default=None\n            If not None, this relative constraint tolerance is used for position and velocity constraints.\n        platform : simtk.openmm.Platform, optional, default=None\n            If specified, the platform to use for OpenMM simulations.\n        write_ncmc_interval : int, optional, default=None\n            If a positive integer is specified, a snapshot frame will be written to storage with the specified interval on NCMC switching.\n            'storage' must also be specified.\n        measure_shadow_work : bool, optional, default False\n            Whether to measure shadow work\n        integrator_splitting : str, optional, default='V R O H R V'\n            NCMC internal integrator splitting based on OpenMMTools Langevin splittings\n        storage : NetCDFStorageView, optional, default=None\n            If specified, write data using this class.\n        verbose : bool, optional, default=False\n            If True, print debug information.\n        LRUCapacity : int, default 10\n            Capacity of LRU cache for hybrid systems\n        pressure : float, default None\n            The pressure to use for the simulation. If None, no barostat\n        \"\"\"\n        # Handle some defaults.\n        if functions == None:\n            functions = LambdaProtocol.default_functions\n        if nsteps == None:\n            nsteps = default_nsteps\n        if timestep == None:\n            timestep = default_timestep\n        if temperature == None:\n            temperature = default_temperature\n\n        self._temperature = temperature\n        self._functions = copy.deepcopy(functions)\n        self._nsteps = nsteps\n        self._timestep = timestep\n        self._constraint_tolerance = constraint_tolerance\n        self._platform = platform\n        self._integrator_splitting = integrator_splitting\n        self._steps_per_propagation = steps_per_propagation\n        self._verbose = verbose\n        self._pressure = pressure\n        self._bond_softening_constant = bond_softening_constant\n        self._angle_softening_constant = angle_softening_constant\n        self._disable_barostat = False\n        self._hybrid_cache = LRUCache(capacity=LRUCapacity)\n        self._measure_shadow_work = measure_shadow_work\n\n        self._nattempted = 0\n\n        self._storage = None\n        if storage is not None:\n            self._storage = NetCDFStorageView(storage, modname=self.__class__.__name__)\n            self._save_configuration = True\n        else:\n            self._save_configuration = False\n        if write_ncmc_interval is not None:\n            self._write_ncmc_interval = write_ncmc_interval\n        else:\n            self._write_ncmc_interval = 1\n        self._work_save_interval = write_ncmc_interval\n\n    @property\n    def beta(self):\n        kT = kB * self._temperature\n        beta = 1.0 / kT\n        return beta\n\n    def _compute_energy_contribution(self, hybrid_thermodynamic_state, initial_sampler_state, final_sampler_state):\n        \"\"\"\n        Compute NCMC energy contribution to log probability.\n\n        See Eqs. 62 and 63 (two-stage) and Eq. 45 (hybrid) of reference document.\n        In both cases, the contribution is u(final_positions, final_lambda) - u(initial_positions, initial_lambda).\n\n        Parameters\n        ----------\n        hybrid_thermodynamic_state : openmmtools.states.CompoundThermodynamicState\n            The thermodynamic state of the hybrid sampler.\n        initial_sampler_state : openmmtools.states.SamplerState\n            The sampler state of the nonalchemical system at the start of the NCMC protocol with box vectors\n        final_sampler_state : openmmtools.states.SamplerState\n            The sampler state of the nonalchemical system at the end of the NCMC protocol\n\n        Returns\n        -------\n        logP_energy : float\n            The NCMC energy contribution to log probability.\n        \"\"\"\n        hybrid_thermodynamic_state.set_alchemical_parameters(0.0)\n        initial_reduced_potential = compute_reduced_potential(hybrid_thermodynamic_state, initial_sampler_state)\n\n        hybrid_thermodynamic_state.set_alchemical_parameters(1.0)\n        final_reduced_potential = compute_reduced_potential(hybrid_thermodynamic_state, final_sampler_state)\n\n        return final_reduced_potential - initial_reduced_potential\n\n    def _topology_proposal_to_thermodynamic_states(self, topology_proposal):\n        \"\"\"\n        Convert a topology proposal to thermodynamic states for the end systems. This will be used to compute the\n        \"logP_energy\" quantity.\n\n        Arguments\n        ---------\n        topology_proposal : perses.rjmc.TopologyProposal\n            topology proposal for whose endpoint systems we want ThermodynamicStates\n\n        Returns\n        -------\n        old_thermodynamic_state : openmmtools.states.ThermodynamicState\n            The old system (nonalchemical) thermodynamic state\n        new_thermodynamic_state : openmmtools.states.ThermodynamicState\n            The new system (nonalchemical) thermodynamic state\n        \"\"\"\n        systems = [topology_proposal.old_system, topology_proposal.new_system]\n        thermostates = []\n        for system in systems:\n            thermodynamic_state = ThermodynamicState(system, temperature=self._temperature, pressure=self._pressure)\n            thermostates.append(thermodynamic_state)\n\n        return thermostates[0], thermostates[1]\n\n    def make_alchemical_system(self, topology_proposal, current_positions, new_positions):\n        \"\"\"\n        Generate an alchemically-modified system at the correct atoms\n        based on the topology proposal. This method generates a hybrid system using the new\n        HybridTopologyFactory. It memoizes so that calling multiple times (within a recent time period)\n        will immediately return a cached object.\n\n        Arguments\n        ---------\n        topology_proposal : perses.rjmc.TopologyProposal\n            Unmodified real system corresponding to appropriate leg of transformation.\n        current_positions : np.ndarray of float\n            Positions of \"old\" system\n        new_positions : np.ndarray of float\n            Positions of \"new\" system atoms\n\n        Returns\n        -------\n        hybrid_factory : perses.annihilation.relative.HybridTopologyFactory\n            a factory object containing the hybrid system\n        \"\"\"\n        try:\n            hybrid_factory = self._hybrid_cache[topology_proposal]\n\n            #If we've retrieved the factory from the cache, update it to include the relevant positions\n            hybrid_factory._old_positions = current_positions\n            hybrid_factory._new_positions = new_positions\n            hybrid_factory._compute_hybrid_positions()\n        except KeyError:\n            try:\n                hybrid_factory = HybridTopologyFactory(topology_proposal, current_positions, new_positions, bond_softening_constant=self._bond_softening_constant, angle_softening_constant=self._angle_softening_constant)\n                self._hybrid_cache[topology_proposal] = hybrid_factory\n            except:\n                hybrid_factory = None\n\n\n        return hybrid_factory\n\n    def integrate(self, topology_proposal, initial_sampler_state, proposed_sampler_state, iteration=None):\n        \"\"\"\n        Performs NCMC switching to either delete or insert atoms according to the provided `topology_proposal`.\n\n        For `delete`, the system is first modified from fully interacting to alchemically modified, and then NCMC switching is used to eliminate atoms.\n        For `insert`, the system begins with eliminated atoms in an alchemically noninteracting form and NCMC switching is used to turn atoms on, followed by making system real.\n\n        Parameters\n        ----------\n        topology_proposal : TopologyProposal\n            Contains old/new Topology and System objects and atom mappings.\n        initial_sampler_state : openmmtools.states.SamplerState representing the initial (old) system\n            Configurational properties of the atoms at the beginning of the NCMC switching.\n        proposed_sampler_state : openmmtools.states.SamplerState representing the proposed (post-geometry new) system\n            Configurational properties new system atoms at beginning of NCMC switching\n        iteration : int, optional, default=None\n            Iteration number, for storage purposes.\n\n        Returns\n        -------\n        final_old_sampler_state : openmmtools.State.SamplerState\n            The final configurational properties of the old system after hybrid alchemical switching\n        final_sampler_state : openmmtools.states.SamplerState\n            The final configurational properties after `nsteps` steps of alchemical switching, and reversion to the nonalchemical system\n        logP_work : float\n            The NCMC work contribution to the log acceptance probability (Eqs. 62 and 63)\n        logP_initial : float\n            The initial logP of the hybrid configuration\n        logP_final : float\n            The final logP of the hybrid configuration\n        \"\"\"\n\n        assert not initial_sampler_state.has_nan() and not proposed_sampler_state.has_nan()\n\n        #generate or retrieve the hybrid topology factory:\n        hybrid_factory = self.make_alchemical_system(topology_proposal, initial_sampler_state.positions, proposed_sampler_state.positions)\n\n        if hybrid_factory is None:\n            _logger.warning(\"Unable to construct hybrid system for {} -> {}\".format(topology_proposal.old_chemical_state_key, topology_proposal.new_chemical_state_key))\n            return initial_sampler_state, proposed_sampler_state, -np.inf, 0.0, 0.0\n\n\n        topology = hybrid_factory.hybrid_topology\n\n        #generate the corresponding thermodynamic and sampler states so that we can use the NonequilibriumSwitchingMove:\n\n        #First generate the thermodynamic state:\n        hybrid_system = hybrid_factory.hybrid_system\n        hybrid_thermodynamic_state = ThermodynamicState(hybrid_system, temperature=self._temperature, pressure=self._pressure)\n\n        #Now create an RelativeAlchemicalState from the hybrid system:\n        alchemical_state = RelativeAlchemicalState.from_system(hybrid_system)\n        alchemical_state.set_alchemical_parameters(0.0)\n\n        #Now create a compound thermodynamic state that combines the hybrid thermodynamic state with the alchemical state:\n        compound_thermodynamic_state = CompoundThermodynamicState(hybrid_thermodynamic_state, composable_states=[alchemical_state])\n\n        #construct a sampler state from the hybrid positions and the box vectors of the initial sampler state:\n        initial_hybrid_positions = hybrid_factory.hybrid_positions\n        initial_hybrid_box_vectors = initial_sampler_state.box_vectors\n\n        initial_hybrid_sampler_state = SamplerState(initial_hybrid_positions, box_vectors=initial_hybrid_box_vectors)\n        final_hybrid_sampler_state = copy.deepcopy(initial_hybrid_sampler_state)\n\n        #create the nonequilibrium move:\n        #ne_move = NonequilibriumSwitchingMove(self._functions, self._integrator_splitting, self._temperature, self._nsteps, self._timestep,\n        #                                      work_save_interval=self._write_ncmc_interval, top=topology,subset_atoms=None,\n        #                                      save_configuration=self._save_configuration, measure_shadow_work=self._measure_shadow_work)\n\n        ne_move = ExternalNonequilibriumSwitchingMove(self._functions, nsteps_neq=self._nsteps,\n                                                      timestep=self._timestep, temperature=self._temperature,\n                                                      work_configuration_save_interval=self._work_save_interval,\n                                                      splitting=\"V R O R V\")\n\n\n        #run the NCMC protocol\n        try:\n            ne_move.apply(compound_thermodynamic_state, final_hybrid_sampler_state)\n        except Exception as e:\n            _logger.warn(\"NCMC failed because {}; rejecting.\".format(str(e)))\n            logP_work = -np.inf\n            return [initial_sampler_state, proposed_sampler_state, -np.inf, 0.0, 0.0]\n\n        #get the total work:\n        logP_work = - ne_move.cumulative_work[-1]\n\n        # Compute contribution of transforming to and from the hybrid system:\n        context, integrator = global_context_cache.get_context(hybrid_thermodynamic_state)\n\n        #set all alchemical parameters to zero:\n        for parameter in self._functions.keys():\n            context.setParameter(parameter, 0.0)\n\n        initial_hybrid_sampler_state.apply_to_context(context, ignore_velocities=True)\n        initial_reduced_potential = hybrid_thermodynamic_state.reduced_potential(context)\n\n        #set all alchemical parameters to one:\n        for parameter in self._functions.keys():\n            context.setParameter(parameter, 1.0)\n\n        final_hybrid_sampler_state.apply_to_context(context, ignore_velocities=True)\n        final_reduced_potential = hybrid_thermodynamic_state.reduced_potential(context)\n\n        #reset the parameters back to zero just in case\n        for parameter in self._functions.keys():\n            context.setParameter(parameter, 0.0)\n\n        #compute the output SamplerState, which has the atoms only for the new system post-NCMC:\n        new_positions = hybrid_factory.new_positions(final_hybrid_sampler_state.positions)\n        new_box_vectors = final_hybrid_sampler_state.box_vectors\n        final_sampler_state = SamplerState(new_positions, box_vectors=new_box_vectors)\n\n        #compute the output SamplerState for the atoms only in the old system (required for geometry_logP_reverse)\n        old_positions = hybrid_factory.old_positions(final_hybrid_sampler_state.positions)\n        old_box_vectors = copy.deepcopy(new_box_vectors) #these are the same as the new system\n        final_old_sampler_state = SamplerState(old_positions, box_vectors=old_box_vectors)\n\n        #extract the trajectory and box vectors from the move:\n        trajectory = ne_move.trajectory[::-self._write_ncmc_interval, :, :][::-1]\n        topology = hybrid_factory.hybrid_topology\n        position_varname = \"ncmcpositions\"\n        nframes = np.shape(trajectory)[0]\n\n        #extract box vectors:\n        box_vec_varname = \"ncmcboxvectors\"\n        box_lengths = ne_move.box_lengths[::-self._write_ncmc_interval, :][::-1]\n        box_angles = ne_move.box_angles[::-self._write_ncmc_interval, :][::-1]\n        box_lengths_and_angles = np.stack([box_lengths, box_angles])\n\n        #write out the positions of the topology\n        if self._storage:\n            for frame in range(nframes):\n                self._storage.write_configuration(position_varname, trajectory[frame, :, :], topology, iteration=iteration, frame=frame, nframes=nframes)\n\n        #write out the periodict box vectors:\n        if self._storage:\n            self._storage.write_array(box_vec_varname, box_lengths_and_angles, iteration=iteration)\n\n        #retrieve the protocol work and write that out too:\n        protocol_work = ne_move.cumulative_work\n        if self._storage:\n            self._storage.write_array(\"protocolwork\", protocol_work, iteration=iteration)\n\n        # Return\n        return [final_old_sampler_state, final_sampler_state, logP_work, -initial_reduced_potential, -final_reduced_potential]\n", "meta": {"hexsha": "ec4aaa7e0b7c7c9118304cd32ffd2fcef9d69149", "size": 18992, "ext": "py", "lang": "Python", "max_stars_repo_path": "perses/annihilation/ncmc_switching.py", "max_stars_repo_name": "hannahbrucemacdonald/perses", "max_stars_repo_head_hexsha": "6b43d200501e587b352dce5aaefef38e4145048b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "perses/annihilation/ncmc_switching.py", "max_issues_repo_name": "hannahbrucemacdonald/perses", "max_issues_repo_head_hexsha": "6b43d200501e587b352dce5aaefef38e4145048b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "perses/annihilation/ncmc_switching.py", "max_forks_repo_name": "hannahbrucemacdonald/perses", "max_forks_repo_head_hexsha": "6b43d200501e587b352dce5aaefef38e4145048b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.3297297297, "max_line_length": 307, "alphanum_fraction": 0.712247262, "include": true, "reason": "import numpy", "num_tokens": 3926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.19749079203406092}}
{"text": "#!/usr/bin/env python\n\n# stdlib modules\nimport copy\n\n# third party imports\nimport numpy as np\nfrom openquake.hazardlib.geo.mesh import Mesh\nfrom openquake.hazardlib.geo.point import Point\nfrom openquake.hazardlib.geo.utils import get_orthographic_projection\n\nfrom impactutils.vectorutils.ecef import latlon2ecef\nfrom impactutils.vectorutils.ecef import ecef2latlon\nfrom impactutils.vectorutils.vector import Vector\nfrom impactutils.time.ancient_time import HistoricTime\nfrom shakelib.utils.exception import ShakeLibException\nfrom shakelib.rupture.base import Rupture\nfrom shakelib.rupture import utils\nfrom shakelib.rupture import gc2\n\n\nclass QuadRupture(Rupture):\n    \"\"\"\n    Rupture class that represents the rupture surface as a combination of\n    quadrilaterals. Each quadrilateral must have horizontal top and bottom\n    edges and must be coplanar. These restrictions make the computation of\n    rupture distances more efficient. The number of points in the top edges\n    must match the number of points in the bottom edge.\n    \"\"\"\n\n    def __init__(self, d, origin):\n        \"\"\"\n        Create a QuadRupture instance from a GeoJSON dictionary and an Origin.\n\n        Args:\n           d (dict): Rupture GeoJSON dictionary.\n           origin (Origin): Reference to a ShakeMap Origin object.\n\n        Returns:\n            QuadRupture instance.\n\n        \"\"\"\n\n        polys = d['features'][0]['geometry']['coordinates'][0]\n        n_polygons = len(polys)\n        lon = []\n        lat = []\n        dep = []\n        for i in range(n_polygons):\n            p = polys[i]\n            p_lons = [pt[0] for pt in p][0:-1]\n            p_lats = [pt[1] for pt in p][0:-1]\n            p_depths = [pt[2] for pt in p][0:-1]\n            lon = lon + p_lons + [np.nan]\n            lat = lat + p_lats + [np.nan]\n            dep = dep + p_depths + [np.nan]\n\n        # Add origin information to metadata\n        odict = origin.__dict__\n        for k, v in odict.items():\n            if isinstance(v, HistoricTime):\n                d['metadata'][k] = v.strftime('%Y-%m-%dT%H:%M:%SZ')\n            else:\n                d['metadata'][k] = v\n\n        self._geojson = d\n        self._lon = lon\n        self._lat = lat\n        self._depth = dep\n        self._origin = origin\n        self._reference = d['metadata']['reference']\n        self._setQuadrilaterals()\n\n    def getDepthAtPoint(self, lat, lon):\n        SMALL_DISTANCE = 2e-03  # 2 meters\n        depth = np.nan\n\n        tmp = self.computeRjb(np.array([lon]), np.array([lat]), np.array([0]))\n        if tmp > SMALL_DISTANCE:\n            return depth\n\n        i = 0\n        imin = -1\n        dmin = 9999999999999999\n        for quad in self.getQuadrilaterals():\n            pX = Vector.fromPoint(Point(lon, lat, 0))\n            points = np.reshape(np.array([pX.x, pX.y, pX.z]), (1, 3))\n            rjb = utils._quad_distance(quad, points, horizontal=True)\n            if rjb[0][0] < dmin:\n                dmin = rjb[0][0]\n                imin = i\n            i += 1\n\n        quad = self._quadrilaterals[imin]\n        P0, P1, P2, P3 = quad\n        # project the quad and the point in question to orthographic defined by\n        # quad\n        xmin = np.min([P0.x, P1.x, P2.x, P3.x])\n        xmax = np.max([P0.x, P1.x, P2.x, P3.x])\n        ymin = np.min([P0.y, P1.y, P2.y, P3.y])\n        ymax = np.max([P0.y, P1.y, P2.y, P3.y])\n        proj = get_orthographic_projection(xmin, xmax, ymax, ymin)\n\n        # project each vertex of quad (at 0 depth)\n        s0x, s0y = proj(P0.x, P0.y)\n        s1x, s1y = proj(P1.x, P1.y)\n        s2x, s2y = proj(P2.x, P2.y)\n        s3x, s3y = proj(P3.x, P3.y)\n        sxx, sxy = proj(lon, lat)\n\n        # turn these to vectors\n        s0 = Vector(s0x, s0y, 0)\n        s1 = Vector(s1x, s1y, 0)\n        s3 = Vector(s3x, s3y, 0)\n        sx = Vector(sxx, sxy, 0)\n\n        # Compute vector from s0 to s1\n        s0s1 = s1 - s0\n        # Compute the vector from s0 to s3\n        s0s3 = s3 - s0\n        # Compute the vector from s0 to sx\n        s0sx = sx - s0\n\n        # cross products\n        s0normal = s0s3.cross(s0s1)\n        dd = s0s1.cross(s0normal)\n        # normalize dd (down dip direction)\n        ddn = dd.norm()\n        # dot product\n        sxdd = ddn.dot(s0sx)\n\n        # get width of quad\n        w = utils.get_quad_width(quad)\n\n        # Get weights for top and bottom edge depths\n        N = utils.get_quad_normal(quad)\n        V = utils.get_vertical_vector(quad)\n        dip = np.degrees(np.arccos(Vector.dot(N, V)))\n        ws = (w * np.cos(np.radians(dip)))\n        wtt = (ws - sxdd) / ws\n        wtb = sxdd / ws\n\n        # Compute the depth of of the plane at Px:\n        depth = wtt * P0.z + wtb * P3.z * 1000\n\n        return depth\n\n    def getLength(self):\n        \"\"\"\n        Compute length of rupture based on top edge in km.\n\n        Returns:\n            float: Length of rupture (km).\n\n        \"\"\"\n        flength = 0\n        for quad in self._quadrilaterals:\n            flength = flength + utils.get_quad_length(quad)\n        return flength\n\n    def getWidth(self):\n        \"\"\"\n        Compute average rupture width (km) for all quadrilaterals defined for\n        the rupture.\n\n        Returns:\n            float: Average width in km of all rupture quadrilaterals.\n        \"\"\"\n        wsum = 0.0\n        for quad in self._quadrilaterals:\n            wsum = wsum + utils.get_quad_width(quad)\n        mwidth = (wsum / len(self._quadrilaterals)) / 1000.0\n        return mwidth\n\n    def getArea(self):\n        \"\"\"\n        Compute area of rupture.\n\n        Returns:\n            float: Rupture area in square km.\n\n        \"\"\"\n        asum = 0.0\n        for quad in self._quadrilaterals:\n            width = utils.get_quad_width(quad)\n            length = utils.get_quad_length(quad)\n            asum = asum + width * length\n        return asum\n\n    @classmethod\n    def fromTrace(cls, xp0, yp0, xp1, yp1, zp, widths, dips, origin,\n                  strike=None, group_index=None, reference=\"\"):\n        \"\"\"\n        Create a QuadRupture instance from a set of vertices that define the\n        top of the rupture, and an array of widths/dips.\n\n        Each rupture quadrilaterial is defined by specifying the latitude,\n        longitude, and depth of the two vertices on the top edges, which must\n        have the dame depths. The other verticies are then constructed from\n        the top edges and the width and dip of the quadrilateral.\n\n        Args:\n            xp0 (array): Array or list of longitudes (floats) of p0.\n            yp0 (array): Array or list of latitudes (floats) of p0.\n            xp1 (array): Array or list of longitudes (floats) of p1.\n            yp1 (array): Array or list of latitudes (floats) of p1.\n            zp (array): Array or list of depths for each of the top of rupture\n                rectangles (km).\n            widths (array): Array of widths for each of rectangle (km).\n            dips (array): Array of dips for each of rectangle (degrees).\n            origin (Origin): Reference to a ShakeMap origin object.\n            strike (array): If None then strike is computed from verticies of\n                top edge of each quadrilateral. If a scalar, then all\n                quadrilaterals are constructed assuming this strike direction.\n                If an array with the same length as the trace coordinates then\n                it specifies the strike for each quadrilateral.\n            group_index (list): List of integers to indicate group index. If\n                None then each quadrilateral is assumed to be in a different\n                group since there is no guarantee that any of them are\n                continuous.\n            reference (str): String explaining where the rupture definition\n                came from (publication style reference, etc.).\n\n        Returns:\n            QuadRupture instance.\n\n        \"\"\"\n        if len(xp0) == len(yp0) == len(xp1) == len(\n                yp1) == len(zp) == len(dips) == len(widths):\n            pass\n        else:\n            raise ShakeLibException(\n                'Number of xp0,yp0,xp1,yp1,zp,widths,dips points must be '\n                'equal.')\n        if strike is None:\n            pass\n        else:\n            if (len(xp0) == len(strike)) | (len(strike) == 1):\n                pass\n            else:\n                raise ShakeLibException(\n                    'Strike must be None, scalar, or same length as '\n                    'trace coordinates.')\n\n        if group_index is None:\n            group_index = np.array(range(len(xp0)))\n\n        # Convert dips to radians\n        dips = np.radians(dips)\n\n        # Ensure that all input sequences are numpy arrays\n        xp0 = np.array(xp0, dtype='d')\n        xp1 = np.array(xp1, dtype='d')\n        yp0 = np.array(yp0, dtype='d')\n        yp1 = np.array(yp1, dtype='d')\n        zp = np.array(zp, dtype='d')\n        widths = np.array(widths, dtype='d')\n        dips = np.array(dips, dtype='d')\n\n        # Get a projection object\n        west = np.min((xp0.min(), xp1.min()))\n        east = np.max((xp0.max(), xp1.max()))\n        south = np.min((yp0.min(), yp1.min()))\n        north = np.max((yp0.max(), yp1.max()))\n\n        # Projected coordinates are in km\n        proj = get_orthographic_projection(west, east, north, south)\n        xp2 = np.zeros_like(xp0)\n        xp3 = np.zeros_like(xp0)\n        yp2 = np.zeros_like(xp0)\n        yp3 = np.zeros_like(xp0)\n        zpdown = np.zeros_like(zp)\n        for i in range(0, len(xp0)):\n            # Project the top edge coordinates\n            p0x, p0y = proj(xp0[i], yp0[i])\n            p1x, p1y = proj(xp1[i], yp1[i])\n\n            # Get the rotation angle defined by these two points\n            if strike is None:\n                dx = p1x - p0x\n                dy = p1y - p0y\n                theta = np.arctan2(dx, dy)  # theta is angle from north\n            elif len(strike) == 1:\n                theta = np.radians(strike[0])\n            else:\n                theta = np.radians(strike[i])\n\n            R = np.array([[np.cos(theta), -np.sin(theta)],\n                          [np.sin(theta), np.cos(theta)]])\n\n            # Rotate the top edge points into a new coordinate system (vertical\n            # line)\n            p0 = np.array([p0x, p0y])\n            p1 = np.array([p1x, p1y])\n            p0p = np.dot(R, p0)\n            p1p = np.dot(R, p1)\n\n            # Get right side coordinates in project, rotated system\n            dz = np.sin(dips[i]) * widths[i]\n            dx = np.cos(dips[i]) * widths[i]\n            p3xp = p0p[0] + dx\n            p3yp = p0p[1]\n            p2xp = p1p[0] + dx\n            p2yp = p1p[1]\n\n            # Get right side coordinates in un-rotated projected system\n            p3p = np.array([p3xp, p3yp])\n            p2p = np.array([p2xp, p2yp])\n            Rback = np.array([[np.cos(-theta), -np.sin(-theta)],\n                              [np.sin(-theta), np.cos(-theta)]])\n            p3 = np.dot(Rback, p3p)\n            p2 = np.dot(Rback, p2p)\n            p3x = np.array([p3[0]])\n            p3y = np.array([p3[1]])\n            p2x = np.array([p2[0]])\n            p2y = np.array([p2[1]])\n\n            # project lower edge points back to lat/lon coordinates\n            lon3, lat3 = proj(p3x, p3y, reverse=True)\n            lon2, lat2 = proj(p2x, p2y, reverse=True)\n\n            xp2[i] = lon2\n            xp3[i] = lon3\n            yp2[i] = lat2\n            yp3[i] = lat3\n            zpdown[i] = zp[i] + dz\n\n        # ---------------------------------------------------------------------\n        # Create GeoJSON object\n        # ---------------------------------------------------------------------\n\n        coords = []\n        u_groups = np.unique(group_index)\n        n_groups = len(u_groups)\n        for i in range(n_groups):\n            ind = np.where(u_groups[i] == group_index)[0]\n            lons = np.concatenate(\n                    [xp0[ind[0]].reshape((1,)),\n                     xp1[ind], xp2[ind][::-1],\n                     xp3[ind][::-1][-1].reshape((1,)),\n                     xp0[ind[0]].reshape((1,))\n                     ])\n            lats = np.concatenate(\n                    [yp0[ind[0]].reshape((1,)),\n                     yp1[ind],\n                     yp2[ind][::-1],\n                     yp3[ind][::-1][-1].reshape((1,)),\n                     yp0[ind[0]].reshape((1,))\n                     ])\n            deps = np.concatenate(\n                    [zp[ind[0]].reshape((1,)),\n                     zp[ind],\n                     zpdown[ind][::-1],\n                     zpdown[ind][::-1][-1].reshape((1,)),\n                     zp[ind[0]].reshape((1,))])\n\n            poly = []\n            for lon, lat, dep in zip(lons, lats, deps):\n                poly.append([lon, lat, dep])\n            coords.append(poly)\n\n        d = {\"type\": \"FeatureCollection\",\n             \"metadata\": {\n                 \"reference\": reference\n             },\n             \"features\": [{\n                 \"type\": \"Feature\",\n                 \"properties\": {\n                     \"rupture type\": \"rupture extent\"\n                 },\n                 \"geometry\": {\n                     \"type\": \"MultiPolygon\",\n                     \"coordinates\": [coords]\n                 }\n             }]}\n\n        # Add origin information to metadata\n        odict = origin.__dict__\n        for k, v in odict.items():\n            if isinstance(v, HistoricTime):\n                d['metadata'][k] = v.strftime('%Y-%m-%dT%H:%M:%SZ')\n            else:\n                d['metadata'][k] = v\n\n        return cls(d, origin)\n\n    def writeTextFile(self, rupturefile):\n        \"\"\"\n        Write rupture data to rupture file format as defined in ShakeMap\n        Software Guide.\n\n        Note that this currently treats each quadrilateral as a separate\n        polygon. This needs to be udpated.\n\n        Args:\n            rupturefile (str): Filename of output data file OR file-like\n                object.\n\n        \"\"\"\n        if not hasattr(rupturefile, 'read'):\n            f = open(rupturefile, 'wt')\n        else:\n            f = rupturefile  # just a reference to the input file-like object\n        f.write('#%s\\n' % self._reference)\n        for quad in self.getQuadrilaterals():\n            P0, P1, P2, P3 = quad\n            f.write('%.4f %.4f %.4f\\n' % (P0.latitude, P0.longitude, P0.depth))\n            f.write('%.4f %.4f %.4f\\n' % (P1.latitude, P1.longitude, P1.depth))\n            f.write('%.4f %.4f %.4f\\n' % (P2.latitude, P2.longitude, P2.depth))\n            f.write('%.4f %.4f %.4f\\n' % (P3.latitude, P3.longitude, P3.depth))\n            f.write('%.4f %.4f %.4f\\n' % (P0.latitude, P0.longitude, P0.depth))\n            f.write(u'>\\n')\n        if not hasattr(rupturefile, 'read'):\n            f.close()\n\n    @classmethod\n    def fromVertices(cls,\n                     xp0, yp0, zp0, xp1, yp1, zp1,\n                     xp2, yp2, zp2, xp3, yp3, zp3,\n                     origin,\n                     group_index=None,\n                     reference=None):\n        \"\"\"\n        Create a QuadDrupture instance from the vector of vertices that fully\n        define the quadrilaterals. The points p0, ..., p3 are labeled below for\n        a trapezoid:\n\n        ::\n\n              p0--------p1\n             /          |\n            /           |\n           p3-----------p2\n\n        All of the following vector arguments must have the same length.\n\n        Args:\n            xp0 (array): Array or list of longitudes (floats) of p0.\n            yp0 (array): Array or list of latitudes (floats) of p0.\n            zp0 (array): Array or list of depths (floats) of p0.\n            xp1 (array): Array or list of longitudes (floats) of p1.\n            yp1 (array): Array or list of latitudes (floats) of p1.\n            zp1 (array): Array or list of depths (floats) of p1.\n            xp2 (array): Array or list of longitudes (floats) of p2.\n            yp2 (array): Array or list of latitudes (floats) of p2.\n            zp2 (array): Array or list of depths (floats) of p2.\n            xp3 (array): Array or list of longitudes (floats) of p3.\n            yp3 (array): Array or list of latitudes (floats) of p3.\n            zp3 (array): Array or list of depths (floats) of p3.\n            origin (Origin): Reference to a ShakeMap Origin object.\n            group_index (list): List of integers to indicate group index. If\n                None then each quadrilateral is assumed to be in a different\n                group since there is no guarantee that any of them are\n                continuous.\n            reference (str): String explaining where the rupture definition\n                came from (publication style reference, etc.)\n\n        Returns:\n            QuadRupture object, where the rupture is modeled as a series of\n                trapezoids.\n\n        \"\"\"\n        if len(xp0) == len(yp0) == len(zp0) == len(xp1) == len(yp1) == \\\n           len(zp1) == len(xp2) == len(yp2) == len(zp2) == len(xp3) == \\\n           len(yp3) == len(zp3):\n            pass\n        else:\n            raise ShakeLibException('All vectors specifying quadrilateral '\n                                    'vertices must have the same length.')\n\n        nq = len(xp0)\n        if group_index is not None:\n            if len(group_index) != nq:\n                raise Exception(\n                    \"group_index must have same length as vertices.\")\n        else:\n            group_index = np.array(range(nq))\n\n        xp0 = np.array(xp0, dtype='d')\n        yp0 = np.array(yp0, dtype='d')\n        zp0 = np.array(zp0, dtype='d')\n        xp1 = np.array(xp1, dtype='d')\n        yp1 = np.array(yp1, dtype='d')\n        zp1 = np.array(zp1, dtype='d')\n        xp2 = np.array(xp2, dtype='d')\n        yp2 = np.array(yp2, dtype='d')\n        zp2 = np.array(zp2, dtype='d')\n        xp3 = np.array(xp3, dtype='d')\n        yp3 = np.array(yp3, dtype='d')\n        zp3 = np.array(zp3, dtype='d')\n\n        # ---------------------------------------------------------------------\n        # Create GeoJSON object\n        # ---------------------------------------------------------------------\n\n        coords = []\n        u_groups = np.unique(group_index)\n        n_groups = len(u_groups)\n        for i in range(n_groups):\n            ind = np.where(u_groups[i] == group_index)[0]\n            lons = np.concatenate(\n                    [xp0[ind[0]].reshape((1,)),\n                     xp1[ind],\n                     xp2[ind][::-1],\n                     xp3[ind][::-1][-1].reshape((1,)),\n                     xp0[ind[0]].reshape((1,))\n                     ])\n            lats = np.concatenate(\n                    [yp0[ind[0]].reshape((1,)),\n                     yp1[ind],\n                     yp2[ind][::-1],\n                     yp3[ind][::-1][-1].reshape((1,)),\n                     yp0[ind[0]].reshape((1,))\n                     ])\n            deps = np.concatenate(\n                    [zp0[ind[0]].reshape((1,)),\n                     zp1[ind],\n                     zp2[ind][::-1],\n                     zp3[ind][::-1][-1].reshape((1,)),\n                     zp0[ind[0]].reshape((1,))\n                     ])\n\n            poly = []\n            for lon, lat, dep in zip(lons, lats, deps):\n                poly.append([lon, lat, dep])\n            coords.append(poly)\n\n        d = {\"type\": \"FeatureCollection\",\n             \"metadata\": {\n                 \"reference\": reference\n             },\n             \"features\": [{\n                 \"type\": \"Feature\",\n                 \"properties\": {\n                     \"rupture type\": \"rupture extent\"\n                 },\n                 \"geometry\": {\n                     \"type\": \"MultiPolygon\",\n                     \"coordinates\": [coords]\n                 }\n             }]}\n\n        # Add origin information to metadata\n        odict = origin.__dict__\n        for k, v in odict.items():\n            if isinstance(v, HistoricTime):\n                d['metadata'][k] = v.strftime('%Y-%m-%dT%H:%M:%SZ')\n            else:\n                d['metadata'][k] = v\n        if hasattr(origin, 'id'):\n            d['metadata']['eventid'] = origin.id\n\n        return cls(d, origin)\n\n    def getQuadrilaterals(self):\n        \"\"\"\n        Return a list of quadrilaterals.\n\n        Returns:\n            list: List of quadrilaterals where each quad is a tuple of four\n                `Point <https://github.com/gem/oq-hazardlib/blob/master/openquake/hazardlib/geo/point.py>`__\n                objects.\n        \"\"\"  # noqa\n        return copy.deepcopy(self._quadrilaterals)\n\n    def getStrike(self):\n        \"\"\"\n        Return strike angle. If rupture consists of multiple quadrilaterals,\n        the average strike angle, weighted by quad length, is returned.\n        Note: for ruptures with quads where the strike angle changes by 180 deg\n        due to reverses in dip direction are problematic and not handeled well\n        by this algorithm.\n\n        Returns:\n            float: Strike angle in degrees.\n\n        \"\"\"\n        nq = len(self._quadrilaterals)\n        strikes = np.zeros(nq)\n        lengths = np.zeros(nq)\n        for i in range(nq):\n            P0 = self._quadrilaterals[i][0]\n            P1 = self._quadrilaterals[i][1]\n            strikes[i] = P0.azimuth(P1)\n            lengths[i] = utils.get_quad_length(self._quadrilaterals[i])\n        x = np.sin(np.radians(strikes))\n        y = np.cos(np.radians(strikes))\n        xbar = np.sum(x * lengths) / np.sum(lengths)\n        ybar = np.sum(y * lengths) / np.sum(lengths)\n        return np.degrees(np.arctan2(xbar, ybar))\n\n    def getDepthToTop(self):\n        \"\"\"\n        Determine shallowest vertex of entire rupture.\n\n        :returns:\n            Shallowest depth of all vertices (float).\n        \"\"\"\n        mindep = 9999999\n        for quad in self._quadrilaterals:\n            P0, P1, P2, P3 = quad\n            depths = np.array([P0.depth, P1.depth, P2.depth, P3.depth])\n            if np.min(depths) < mindep:\n                mindep = np.min(depths)\n        return mindep\n\n    def getDip(self):\n        \"\"\"\n        Return average dip of all quadrilaterals in the rupture.\n\n        Returns:\n           float: Average dip in degrees.\n\n        \"\"\"\n        dipsum = 0.0\n        for quad in self._quadrilaterals:\n            N = utils.get_quad_normal(quad)\n            V = utils.get_vertical_vector(quad)\n            dipsum = dipsum + np.degrees(np.arccos(Vector.dot(N, V)))\n        dip = dipsum / len(self._quadrilaterals)\n        return dip\n\n    def getIndividualWidths(self):\n        \"\"\"\n        Return an array of rupture widths (km), one for each quadrilateral\n        defined for the rupture.\n\n        Returns:\n            Array of quad widths in km of all rupture quadrilaterals.\n        \"\"\"\n        nquad = self.getNumQuads()\n        widths = np.zeros(nquad)\n        for i in range(nquad):\n            q = self._quadrilaterals[i]\n            widths[i] = utils.get_quad_width(q) / 1000.0\n        return widths\n\n    def getIndividualTopLengths(self):\n        \"\"\"\n        Return an array of rupture lengths along top edge (km),\n        one for each quadrilateral defined for the rupture.\n\n        :returns:\n            Array of lengths in km of top edge of quadrilaterals.\n        \"\"\"\n        nquad = self.getNumQuads()\n        lengths = np.zeros(nquad)\n        for i in range(nquad):\n            P0, P1, P2, P3 = self._quadrilaterals[i]\n            p0 = Vector.fromPoint(P0)\n            p1 = Vector.fromPoint(P1)\n            lengths[i] = (p1 - p0).mag() / 1000.0\n        return lengths\n\n    @staticmethod\n    def _fixStrikeDirection(quad):\n        P0, P1, P2, P3 = quad\n        eps = 1e-6\n        p0 = Vector.fromPoint(P0)  # fromPoint converts to ECEF\n        p1 = Vector.fromPoint(P1)\n        p2 = Vector.fromPoint(P2)\n        p1p0 = p1 - p0\n        p2p0 = p2 - p0\n        qnv = Vector.cross(p2p0, p1p0).norm()\n        tmp = p0 + qnv\n        tmplat, tmplon, tmpz = ecef2latlon(tmp.x, tmp.y, tmp.z)\n        if (tmpz - P0.depth) < eps:  # If True then do nothing\n            fixed = quad\n        else:\n            newP0 = copy.deepcopy(P1)\n            newP1 = copy.deepcopy(P0)\n            newP2 = copy.deepcopy(P3)\n            newP3 = copy.deepcopy(P2)\n            fixed = [newP0, newP1, newP2, newP3]\n        return fixed\n\n    def _setQuadrilaterals(self):\n        \"\"\"\n        Create internal list of N quadrilaterals. Reverses quad if dip\n        direction is incorrect.\n        \"\"\"\n\n        # Make sure arrays are numpy arrays.\n        self._lon = np.array(self._lon)\n        self._lat = np.array(self._lat)\n        self._depth = np.array(self._depth)\n\n        # Find the nans, which tells is where the separate polygons/groups are\n        group_ends = np.where(np.isnan(self._lon))[0]\n        n_groups = len(group_ends)\n\n        # Check that arrays are the same length\n        if len(self._lon) != len(self._lat) != len(self._depth):\n            raise IndexError(\n                'Length of input lon, lat, depth arrays must be equal')\n\n        # Construct quads\n        group_start = 0\n\n        self._quadrilaterals = []\n        self._group_index = []\n        groupind = 0\n        for i in range(n_groups):\n            lonseg = self._lon[group_start:group_ends[i]]\n            latseg = self._lat[group_start:group_ends[i]]\n            depthseg = self._depth[group_start:group_ends[i]]\n\n            # Each group can have many contiguous quadrilaterals defined in it\n            # separations (nans) between segments mean that segments are not\n            # contiguous.\n\n            npoints = len(lonseg)\n            nquads = int((npoints - 4) / 2) + 1\n            quad_start = 0\n            quad_end = -1\n            for j in range(nquads):\n                P0 = Point(lonseg[quad_start],\n                           latseg[quad_start],\n                           depthseg[quad_start])\n                P1 = Point(lonseg[quad_start + 1],\n                           latseg[quad_start + 1],\n                           depthseg[quad_start + 1])\n                P2 = Point(lonseg[quad_end - 1],\n                           latseg[quad_end - 1],\n                           depthseg[quad_end - 1])\n                P3 = Point(lonseg[quad_end],\n                           latseg[quad_end],\n                           depthseg[quad_end])\n                quad = [P0, P1, P2, P3]\n\n                # Enforce plane by moving P2 -- already close because of check\n                # in read_rupture_file/is_quadrupture_class/is_quad\n\n                dummy, fixed_quad = utils.is_quad(quad)\n\n                # Reverse quad if necessary\n                fixed_quad = self._fixStrikeDirection(fixed_quad)\n\n                self._quadrilaterals.append(fixed_quad)\n\n                quad_start = quad_start + 1\n                quad_end = quad_end - 1\n\n            group_start = group_ends[i] + 1\n            self._group_index.extend([groupind] * nquads)\n            groupind = groupind + 1\n\n    def _getGroupIndex(self):\n        \"\"\"\n        Return a list of segment group indexes.\n\n        Returns:\n            list: Segment group indexes; length equals the number of\n                quadrilaterals.\n        \"\"\"\n        return copy.deepcopy(self._group_index)\n\n    @property\n    def lats(self):\n        \"\"\"\n        Return an array of latitudes for the rupture verticies arranged for\n        plotting purposes; will give an outline of each group connected\n        segments.\n\n        Returns:\n            array: Numpy array of closed-loop latitude values; disconnected\n                segments are separated by nans.\n        \"\"\"\n        lats = []\n        quads = self.getQuadrilaterals()\n        groups = self._getGroupIndex()\n        u_groups = np.unique(groups)\n        ng = len(u_groups)\n        for i in range(ng):\n            q_ind = np.where(groups == u_groups[i])[0]\n            nq = len(q_ind)\n            top_lats = []\n            bot_lats = []\n            for j in range(nq):\n                if j == 0:\n                    top0 = [quads[q_ind[j]][0].latitude]\n                    bot0 = [quads[q_ind[j]][3].latitude]\n                    top_lats = top_lats + top0\n                    bot_lats = bot_lats + bot0\n                top_lats = top_lats + [quads[q_ind[j]][1].latitude]\n                bot_lats = bot_lats + [quads[q_ind[j]][2].latitude]\n            lats = lats + top_lats + bot_lats[::-1] + top0 + [np.nan]\n\n        return np.array(lats)\n\n    @property\n    def lons(self):\n        \"\"\"\n        Return an array of longitudes for the rupture verticies arranged for\n        plotting purposes; will give an outline of each group connected\n        segments.\n\n        Returns:\n            array: Numpy array of closed-loop longitude values; disconnected\n                segments are separated by nans.\n        \"\"\"\n        lons = []\n        quads = self.getQuadrilaterals()\n        groups = self._getGroupIndex()\n        u_groups = np.unique(groups)\n        ng = len(u_groups)\n        for i in range(ng):\n            q_ind = np.where(groups == u_groups[i])[0]\n            nq = len(q_ind)\n            top_lons = []\n            bot_lons = []\n            for j in range(nq):\n                if j == 0:\n                    top0 = [quads[q_ind[j]][0].longitude]\n                    bot0 = [quads[q_ind[j]][3].longitude]\n                    top_lons = top_lons + top0\n                    bot_lons = bot_lons + bot0\n                top_lons = top_lons + [quads[q_ind[j]][1].longitude]\n                bot_lons = bot_lons + [quads[q_ind[j]][2].longitude]\n            lons = lons + top_lons + bot_lons[::-1] + top0 + [np.nan]\n        return np.array(lons)\n\n    @property\n    def depths(self):\n        \"\"\"\n        Return an array of depths for the rupture verticies arranged for\n        plotting purposes; will give an outline of each group connected\n        segments.\n\n        Returns:\n            array: Numpy array of closed-loop depths; disconnected\n                segments are separated by nans.\n        \"\"\"\n        deps = []\n        quads = self.getQuadrilaterals()\n        groups = self._getGroupIndex()\n        u_groups = np.unique(groups)\n        ng = len(u_groups)\n        for i in range(ng):\n            q_ind = np.where(groups == u_groups[i])[0]\n            nq = len(q_ind)\n            top_deps = []\n            bot_deps = []\n            for j in range(nq):\n                if j == 0:\n                    top0 = [quads[q_ind[j]][0].depth]\n                    bot0 = [quads[q_ind[j]][3].depth]\n                    top_deps = top_deps + top0\n                    bot_deps = bot_deps + bot0\n                top_deps = top_deps + [quads[q_ind[j]][1].depth]\n                bot_deps = bot_deps + [quads[q_ind[j]][2].depth]\n            deps = deps + top_deps + bot_deps[::-1] + top0 + [np.nan]\n\n        return np.array(deps)\n\n    def getDeps(self):\n        \"\"\"\n        Return a copy of the array of depths for the rupture verticies.\n\n        Returns:\n            array: Numpy array of latitude values.\n        \"\"\"\n        return self._depth.copy()\n\n    def getNumGroups(self):\n        \"\"\"\n        Return a count of the number of rupture groups.\n\n        Returns:\n            int:Rnumber of rupture groups.\n\n        \"\"\"\n        return len(np.unique(self._group_index))\n\n    def getNumQuads(self):\n        \"\"\"\n        Return a count of the number of rupture quadrilaterals.\n\n        Returns:\n            int: Number of rupture quadrilaterals.\n        \"\"\"\n        return len(self._quadrilaterals)\n\n    def getRuptureAsArrays(self):\n        \"\"\"\n        Return a 3-tuple of numpy arrays indicating X, Y, Z (lon,lat,depth)\n        coordinates. Rupture groups are separated by numpy.NaN values.\n\n        Returns:\n            tuple: 3-tuple of numpy arrays indicating X,Y,Z (lon,lat,depth)\n                coordinates.\n        \"\"\"\n        return (np.array(self._lon),\n                np.array(self._lat),\n                np.array(self._depth))\n\n    def getRuptureAsMesh(self):\n        \"\"\"\n        Return rupture segments as a OQ-Hazardlib Mesh object.\n\n        Returns:\n            Mesh (https://github.com/gem/oq-hazardlib/blob/master/openquake/hazardlib/geo/mesh.py)\n        \"\"\"  # noqa\n        rupture = Mesh(self._lon, self._lat, self._depth)\n        return rupture\n\n    def computeRjb(self, lon, lat, depth):\n        \"\"\"\n        Method for computing Joyner-Boore distance.\n\n        Args:\n            lon (array): Numpy array of longitudes.\n            lat (array): Numpy array of latitudes.\n            depth (array): Numpy array of depths (km; positive down).\n\n        Returns:\n           array: Joyner-Boore distance (km).\n\n        \"\"\"\n\n        # ---------------------------------------------------------------------\n        # Sort out sites\n        # ---------------------------------------------------------------------\n        oldshape = lon.shape\n\n        if len(oldshape) == 2:\n            newshape = (oldshape[0] * oldshape[1], 1)\n        else:\n            newshape = (oldshape[0], 1)\n\n        x, y, z = latlon2ecef(lat, lon, depth)\n        x.shape = newshape\n        y.shape = newshape\n        z.shape = newshape\n        sites_ecef = np.hstack((x, y, z))\n\n        minrjb = np.ones(newshape, dtype=lon.dtype) * 1e16\n        quads = self.getQuadrilaterals()\n\n        for i in range(len(quads)):\n            P0, P1, P2, P3 = quads[i]\n            S0 = copy.deepcopy(P0)\n            S1 = copy.deepcopy(P1)\n            S2 = copy.deepcopy(P2)\n            S3 = copy.deepcopy(P3)\n            S0.depth = 0.0\n            S1.depth = 0.0\n            S2.depth = 0.0\n            S3.depth = 0.0\n            squad = [S0, S1, S2, S3]\n            rjbdist = utils._quad_distance(squad, sites_ecef, horizontal=True)\n            minrjb = np.minimum(minrjb, rjbdist)\n\n        minrjb = minrjb.reshape(oldshape)\n        return minrjb\n\n    def computeRrup(self, lon, lat, depth):\n        \"\"\"\n        Method for computing rupture distance.\n\n        Args:\n            lon (array): Numpy array of longitudes.\n            lat (array): Numpy array of latitudes.\n            depth (array): Numpy array of depths (km; positive down).\n\n        Returns:\n           array: Rupture distance (km).\n\n        \"\"\"\n\n        # ---------------------------------------------------------------------\n        # Sort out sites\n        # ---------------------------------------------------------------------\n        oldshape = lon.shape\n\n        if len(oldshape) == 2:\n            newshape = (oldshape[0] * oldshape[1], 1)\n        else:\n            newshape = (oldshape[0], 1)\n\n        x, y, z = latlon2ecef(lat, lon, depth)\n        x.shape = newshape\n        y.shape = newshape\n        z.shape = newshape\n        sites_ecef = np.hstack((x, y, z))\n\n        minrrup = np.ones(newshape, dtype=lon.dtype) * 1e16\n        quads = self.getQuadrilaterals()\n\n        for i in range(len(quads)):\n            rrupdist = utils._quad_distance(quads[i], sites_ecef)\n            minrrup = np.minimum(minrrup, rrupdist)\n\n        minrrup = minrrup.reshape(oldshape)\n        return minrrup\n\n    def computeGC2(self, lon, lat, depth):\n        \"\"\"\n        Method for computing version 2 of the Generalized Coordinate system\n        (GC2) by Spudich and Chiou OFR 2015-1028.\n\n        Args:\n            lon (array): Numpy array of longitudes.\n            lat (array): Numpy array of latitudes.\n            depth (array): Numpy array of depths (km; positive down).\n\n        Returns:\n            dict: Dictionary with keys for each of the GC2-related distances,\n                which include 'rx', 'ry', 'ry0', 'U', 'T'.\n        \"\"\"\n        # This just hands off to the module-level method\n        dict = gc2._computeGC2(self, lon, lat, depth)\n        return dict\n", "meta": {"hexsha": "9c298626db1d797e5c37dc8b9f5ce94b16318019", "size": 35549, "ext": "py", "lang": "Python", "max_stars_repo_path": "shakelib/rupture/quad_rupture.py", "max_stars_repo_name": "ynthdhj/shakemap", "max_stars_repo_head_hexsha": "2771b8aee6b22f065cc80632c894a0ba77829619", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "shakelib/rupture/quad_rupture.py", "max_issues_repo_name": "ynthdhj/shakemap", "max_issues_repo_head_hexsha": "2771b8aee6b22f065cc80632c894a0ba77829619", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shakelib/rupture/quad_rupture.py", "max_forks_repo_name": "ynthdhj/shakemap", "max_forks_repo_head_hexsha": "2771b8aee6b22f065cc80632c894a0ba77829619", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0581854043, "max_line_length": 108, "alphanum_fraction": 0.5116037019, "include": true, "reason": "import numpy", "num_tokens": 8896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.19749078416042504}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\n# standard imports \nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# custom imports\nimport GaN_fun\nimport GaN_type_peak_assignments\n\nimport peak_param_determination as ppd\nfrom histogram_functions import bin_dat\n\nplt.close('all')\n\n# Read in data\nepos = GaN_fun.load_epos(run_number='R44_03146', \n                         epos_trim=[5000, 5000],\n                         fig_idx=999)\n\npk_data = GaN_type_peak_assignments.In_doped_GaN()\nbg_rois=[[0.4,0.9]]\n#bg_rois=[[10,11]]\n\npk_params, glob_bg_param, Ga1p_idxs, Ga2p_idxs = GaN_fun.fit_spectrum(\n        epos=epos, \n        pk_data=pk_data, \n        peak_height_fraction=0.1, \n        bg_rois=bg_rois)\n\ncts, compositions, is_peak = GaN_fun.count_and_get_compositions(\n        epos=epos, \n        pk_data=pk_data,\n        pk_params=pk_params, \n        glob_bg_param=glob_bg_param, \n        bg_frac=1, \n        noise_threshhold=2)\n\n# Print out the composition of the full dataset\nppd.pretty_print_compositions(compositions,pk_data)\n\n# Plot the full spectrum\nxs, ys_sm = GaN_fun.bin_and_smooth_spectrum(epos=epos,\n                                            user_roi=[0,150],\n                                            bin_wid_mDa=30,\n                                            smooth_wid_mDa=-1)\n\nfig = plt.figure(num=1)\nfig.set_size_inches(w=6.69, h=3)\nfig.clear()\nax = fig.gca()\n\nax.plot(xs, ys_sm, lw=1, label='full spec')\n\nglob_bg = ppd.physics_bg(xs,glob_bg_param)    \nax.plot(xs, glob_bg, lw=1, label='bg', alpha=1)\n\nax.set_xlim(0,120)\nax.set_ylim(1e0,1e5)\nax.grid(b=True)\nax.set(xlabel='m/z', ylabel='counts')\nax.set_yscale('log')    \nax.legend()\nfig.tight_layout()\n\nfig.savefig('InGaN_full_spectrum.pdf')\nfig.savefig('InGaN_full_spectrum.jpg', dpi=300)\n\n\n\n\n# Find the pole center and show it\nm2q_roi = [3, 100]\nsel_idxs = np.where((epos['m2q']>m2q_roi[0]) & (epos['m2q']<m2q_roi[1]))\nxc,yc = GaN_fun.mean_shift(epos['x_det'][sel_idxs],epos['y_det'][sel_idxs])\n\n# Find all the Indium events\nis_In = ~np.isfinite(epos['m2q'])\nfor pk,param in zip(pk_data,pk_params):\n    if pk['In']>0:\n        is_In = is_In | ((epos['m2q']>=param['pre_rng']) & (epos['m2q']<=param['post_rng']))\n        \n# Fit the QW to a plane and rotate the point cloud to 'flatten' wrt z-axis\np = GaN_fun.qw_plane_fit(epos['x'][is_In],epos['y'][is_In],epos['z'][is_In],np.array([0,0,1.8]))\nepos['x'],epos['y'],epos['z'] = GaN_fun.rotate_data_flat(p,epos['x'],epos['y'],epos['z'])\n\n# USER DEFINED!!!\n# Z-ROIs TO TAKE COMPOSITIONS IN\nz_roi_qw = [38, 38.6]\nz_roi_buf = [43, 48]\nz_roi_gan = [40, 42]\n\n# Find all the Ga events\nis_Ga = ~np.isfinite(epos['m2q'])\nfor pk,param in zip(pk_data,pk_params):\n    if pk['Ga']>0:\n        is_Ga = is_Ga | ((epos['m2q']>=param['pre_rng']) & (epos['m2q']<=param['post_rng']))\n\nimport colorcet as cc    \ncm=cc.cm.glasbey\n\n# Plot the 'flat' interface to verify vector algebra didn't go awry\nfig = plt.figure(num=11)\nfig.clear()\nax = fig.gca()\n#ax.plot(epos['x'][is_In],epos['z'][is_In],'.')\n#ax.plot(epos['y'][is_In],epos['z'][is_In],'.')\nax.plot(epos['x'][is_Ga],epos['z'][is_Ga],'.', alpha=0.05, color=cm(2), ms=2)\nax.plot(epos['x'][is_In],epos['z'][is_In],'.', alpha=0.5, color=cm(10), ms=2)\n\n\n# Plot the ROIs for visual inspection\nax.fill([-8,-8, 8,8], [z_roi_qw[0], z_roi_qw[1], z_roi_qw[1], z_roi_qw[0]], color=[1,0,0,0.5]) \nax.fill([-8,-8, 8,8], [z_roi_buf[0], z_roi_buf[1], z_roi_buf[1], z_roi_buf[0]], color=[1,0,0,0.5]) \nax.fill([-8,-8, 8,8], [z_roi_gan[0], z_roi_gan[1], z_roi_gan[1], z_roi_gan[0]], color=[1,0,0,0.5]) \n\n\n# Calculate the QW composition\nis_roi = (epos['z']>=z_roi_qw[0]) & (epos['z']<=z_roi_qw[1])\nsub_epos = epos[is_roi]\n\nbg_frac_roi = [120,150]\nbg_frac = np.sum((sub_epos['m2q']>bg_frac_roi[0]) & (sub_epos['m2q']<bg_frac_roi[1])) \\\n                    / np.sum((epos['m2q']>bg_frac_roi[0]) & (epos['m2q']<bg_frac_roi[1]))\n\n# Count the peaks, local bg, and global bg.  Ignore the local bg based info\ncts, compositions, is_peak = GaN_fun.count_and_get_compositions(\n        epos=sub_epos, \n        pk_data=pk_data, \n        pk_params=pk_params, \n        glob_bg_param=glob_bg_param, \n        bg_frac=bg_frac, \n        noise_threshhold=2)\n\nppd.pretty_print_compositions(compositions,pk_data)\n\n# Plot the QW spectrum\nxs, ys_sm = GaN_fun.bin_and_smooth_spectrum(epos=sub_epos,\n                                            user_roi=[0,150],\n                                            bin_wid_mDa=30,\n                                            smooth_wid_mDa=-1)\n\nfig = plt.figure(num=2)\nfig.set_size_inches(w=6.69, h=3)\nfig.clear()\nax = fig.gca()\n\nax.plot(xs, ys_sm, lw=1, label='QW spec',color='k')\n\nglob_bg = ppd.physics_bg(xs,bg_frac*glob_bg_param)    \nax.plot(xs, glob_bg, lw=1, label='bg', alpha=1,color='r')\n\nax.set_xlim(0,120)\nax.set_ylim(1e0,1e3)\nax.grid(b=True)\nax.set(xlabel='m/z', ylabel='counts')\nax.set_yscale('log')    \nax.legend()\nfig.tight_layout()\n\nfig.savefig('InGaN_QW_spectrum.pdf')\nfig.savefig('InGaN_QW_spectrum.jpg', dpi=300)\n\n\n\n# Calculate the buffer composition\nis_roi = (epos['z']>=z_roi_buf[0]) & (epos['z']<=z_roi_buf[1])\nsub_epos = epos[is_roi]\n\nbg_frac_roi = [120,150]\nbg_frac = np.sum((sub_epos['m2q']>bg_frac_roi[0]) & (sub_epos['m2q']<bg_frac_roi[1])) \\\n                    / np.sum((epos['m2q']>bg_frac_roi[0]) & (epos['m2q']<bg_frac_roi[1]))\n\n# Count the peaks, local bg, and global bg.  Ignore the local bg based info\ncts, compositions, is_peak = GaN_fun.count_and_get_compositions(\n        epos=sub_epos, \n        pk_data=pk_data, \n        pk_params=pk_params, \n        glob_bg_param=glob_bg_param, \n        bg_frac=bg_frac, \n        noise_threshhold=2)\n\nppd.pretty_print_compositions(compositions,pk_data)\n\n# Plot the buffer spectrum\nxs, ys_sm = GaN_fun.bin_and_smooth_spectrum(epos=sub_epos,\n                                            user_roi=[0,150],\n                                            bin_wid_mDa=30,\n                                            smooth_wid_mDa=-1)\n\nfig = plt.figure(num=3)\nfig.set_size_inches(w=6.69, h=3)\nfig.clear()\nax = fig.gca()\n\nax.plot(xs, ys_sm, lw=1, label='buffer spec',color='k')\n\nglob_bg = ppd.physics_bg(xs,bg_frac*glob_bg_param)    \nax.plot(xs, glob_bg, lw=1, label='bg', alpha=1,color='r')\n\nax.set_xlim(0,120)\nax.set_ylim(1e0,1e4)\nax.grid(b=True)\nax.set(xlabel='m/z', ylabel='counts')\nax.set_yscale('log')    \nax.legend()\nfig.tight_layout()\n\nfig.savefig('InGaN_buffer_spectrum.pdf')\nfig.savefig('InGaN_buffer_spectrum.jpg', dpi=300)\n\n# Calculate the barrier composition\nis_roi = (epos['z']>=z_roi_gan[0]) & (epos['z']<=z_roi_gan[1])\nsub_epos = epos[is_roi]\n\nbg_frac_roi = [120,150]\nbg_frac = np.sum((sub_epos['m2q']>bg_frac_roi[0]) & (sub_epos['m2q']<bg_frac_roi[1])) \\\n                    / np.sum((epos['m2q']>bg_frac_roi[0]) & (epos['m2q']<bg_frac_roi[1]))\n\n# Count the peaks, local bg, and global bg.  Ignore the local bg based info\ncts, compositions, is_peak = GaN_fun.count_and_get_compositions(\n        epos=sub_epos, \n        pk_data=pk_data, \n        pk_params=pk_params, \n        glob_bg_param=glob_bg_param, \n        bg_frac=bg_frac, \n        noise_threshhold=2)\n\nppd.pretty_print_compositions(compositions,pk_data)\n\n# Plot the barrier spectrum\nxs, ys_sm = GaN_fun.bin_and_smooth_spectrum(epos=sub_epos,\n                                            user_roi=[0,150],\n                                            bin_wid_mDa=30,\n                                            smooth_wid_mDa=-1)\n\nfig = plt.figure(num=4)\nfig.set_size_inches(w=6.69, h=3)\nfig.clear()\nax = fig.gca()\n\nax.plot(xs, ys_sm, lw=1, label='barrier spec',color='k')\n\nglob_bg = ppd.physics_bg(xs,bg_frac*glob_bg_param)    \nax.plot(xs, glob_bg, lw=1, label='bg$\\pm', alpha=1,color='r')\n\nax.set_xlim(0,120)\nax.set_ylim(1e0,1e4)\nax.grid(b=True)\nax.set(xlabel='m/z', ylabel='counts')\nax.set_yscale('log')    \nax.legend()\nfig.tight_layout()\n\nfig.savefig('InGaN_barrier_spectrum.pdf')\nfig.savefig('InGaN_barrier_spectrum.jpg', dpi=300)\n", "meta": {"hexsha": "9ecdc85a745b818b1bb268c5cb68d2bfcbc5608e", "size": 7954, "ext": "py", "lang": "Python", "max_stars_repo_path": "JPCC_stuff/Figs_InGaN_NUV.py", "max_stars_repo_name": "bcaplins/NIST_APT_TOOLS", "max_stars_repo_head_hexsha": "80c25498e8b069b8ee289a2d09c76c932c054cea", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "JPCC_stuff/Figs_InGaN_NUV.py", "max_issues_repo_name": "bcaplins/NIST_APT_TOOLS", "max_issues_repo_head_hexsha": "80c25498e8b069b8ee289a2d09c76c932c054cea", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JPCC_stuff/Figs_InGaN_NUV.py", "max_forks_repo_name": "bcaplins/NIST_APT_TOOLS", "max_forks_repo_head_hexsha": "80c25498e8b069b8ee289a2d09c76c932c054cea", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.358778626, "max_line_length": 99, "alphanum_fraction": 0.6301232084, "include": true, "reason": "import numpy", "num_tokens": 2548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19734484463400281}}
{"text": "# Copyright 2018 Google LLC\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n#     http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# ==============================================================================\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport numpy as np\r\n\r\nQUANTIZATION_BYTES_TO_DTYPES = {1: np.uint8, 2: np.uint16}\r\n\r\n\r\ndef quantize_weights(data, quantization_dtype):\r\n  \"\"\"Quantizes the weights by linearly re-scaling across available bits.\r\n\r\n  The weights are quantized by linearly re-scaling the values between the\r\n  minimum and maximum value, and representing them with the number of bits\r\n  provided by the `quantization_dtype`.\r\n\r\n  In order to guarantee that 0 is perfectly represented by one of the quantized\r\n  values, the range is \"nudged\" in the same manner as in TF-Lite.\r\n\r\n  Weights can be de-quantized by multiplying by the returned `scale` and adding\r\n  `min`.\r\n\r\n  Args:\r\n    data: A numpy array of dtype 'float32' or 'int32'.\r\n    quantization_dtype: A numpy dtype to quantize weights to. Only np.uint8 and\r\n      np.uint16 are supported.\r\n\r\n  Returns:\r\n    quantized_data: The quantized weights as a numpy array with dtype\r\n      `quantization_dtype`.\r\n    scale: The linearly scaling constant used for quantization.\r\n    min_val: The minimum value of the linear range.\r\n  Raises:\r\n    ValueError: if `quantization_dtype` is not a valid type.\r\n  \"\"\"\r\n  if quantization_dtype not in QUANTIZATION_BYTES_TO_DTYPES.values():\r\n    raise ValueError('Invalid `quantization_dtype`: %r' % quantization_dtype)\r\n\r\n  # Compute the min and max for the group.\r\n  min_val = data.min().astype(np.float64)\r\n  max_val = data.max().astype(np.float64)\r\n  if min_val == max_val:\r\n    # If there is only a single value, we can represent everything as zeros.\r\n    quantized_data = np.zeros_like(data, dtype=quantization_dtype)\r\n    scale = 1.0\r\n  else:\r\n    # Quantize data.\r\n    scale, min_val, max_val = _get_quantization_range(\r\n        min_val, max_val, quantization_dtype)\r\n    quantized_data = np.round(\r\n        (data.clip(min_val, max_val) - min_val) / scale).astype(\r\n            quantization_dtype)\r\n\r\n  return quantized_data, scale, min_val\r\n\r\n\r\ndef dequantize_weights(\r\n    quantized_data, scale, min_val, original_dtype=np.float32):\r\n  return np.round(quantized_data * scale + min_val).astype(original_dtype)\r\n\r\ndef _get_quantization_range(min_val, max_val, quantization_dtype):\r\n  \"\"\"Computes quantization range to ensure that zero is represented if covered.\r\n\r\n  Gymnastics with nudged zero point is to ensure that real zero maps to an\r\n  integer, which is required for e.g. zero-padding in convolutional layers.\r\n\r\n  Based on `NudgeQuantizationRange` in\r\n  tensorflow/contrib/lite/kernels/internal/quantization_util.h, except we do not\r\n  nudge if 0 is not in the range.\r\n\r\n  Args:\r\n    min_val: The actual minimum value of the data.\r\n    max_val: The actual maximum value of the data.\r\n    quantization_dtype: A numpy dtype to quantize weights to. Only np.uint8 and\r\n      np.uint16 are supported.\r\n\r\n  Returns:\r\n    scale: The linear scaling constant used for quantization.\r\n    nudged_min: The adjusted minimum value to ensure zero is represented, if\r\n      covered.\r\n    nudged_max: The adjusted maximum value to ensure zero is represented, if\r\n      covered.\r\n  Raises:\r\n    ValueError: if `quantization_dtype` is not a valid type.\r\n  \"\"\"\r\n  if quantization_dtype not in QUANTIZATION_BYTES_TO_DTYPES.values():\r\n    raise ValueError('Invalid `quantization_dtype`: %r' % quantization_dtype)\r\n\r\n  quant_max = np.iinfo(quantization_dtype).max\r\n  scale = (max_val - min_val) / quant_max\r\n\r\n  if min_val <= 0 <= max_val:\r\n    quantized_zero_point = (0 - min_val) / scale\r\n    nudged_zero_point = np.round(quantized_zero_point)\r\n\r\n    # Solve `0 = nudged_zero_point * scale + nudged_min` for `nudged_min`.\r\n    nudged_min = -nudged_zero_point * scale\r\n    nudged_max = quant_max * scale + nudged_min\r\n  else:\r\n    nudged_min, nudged_max = min_val, max_val\r\n\r\n  return scale, nudged_min, nudged_max\r\n", "meta": {"hexsha": "e3bd49c2bd729464e5234413f3bd1080e3ade08f", "size": 4560, "ext": "py", "lang": "Python", "max_stars_repo_path": "tfjs-converter/python/tensorflowjs/quantization.py", "max_stars_repo_name": "565353780/tfjs-converter", "max_stars_repo_head_hexsha": "3f6a8fe91bda0658c57e20302198ee1a4c9527ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tfjs-converter/python/tensorflowjs/quantization.py", "max_issues_repo_name": "565353780/tfjs-converter", "max_issues_repo_head_hexsha": "3f6a8fe91bda0658c57e20302198ee1a4c9527ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tfjs-converter/python/tensorflowjs/quantization.py", "max_forks_repo_name": "565353780/tfjs-converter", "max_forks_repo_head_hexsha": "3f6a8fe91bda0658c57e20302198ee1a4c9527ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9743589744, "max_line_length": 81, "alphanum_fraction": 0.713377193, "include": true, "reason": "import numpy", "num_tokens": 1095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19734484463400281}}
{"text": "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Base classes for probability distributions.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\nimport contextlib\nimport types\n\nimport numpy as np\nimport six\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops.distributions import kullback_leibler\nfrom tensorflow.python.ops.distributions import util\nfrom tensorflow.python.util import tf_inspect\nfrom tensorflow.python.util.tf_export import tf_export\n\n\n__all__ = [\n    \"ReparameterizationType\",\n    \"FULLY_REPARAMETERIZED\",\n    \"NOT_REPARAMETERIZED\",\n    \"Distribution\",\n]\n\n_DISTRIBUTION_PUBLIC_METHOD_WRAPPERS = [\n    \"batch_shape\",\n    \"batch_shape_tensor\",\n    \"cdf\",\n    \"covariance\",\n    \"cross_entropy\",\n    \"entropy\",\n    \"event_shape\",\n    \"event_shape_tensor\",\n    \"kl_divergence\",\n    \"log_cdf\",\n    \"log_prob\",\n    \"log_survival_function\",\n    \"mean\",\n    \"mode\",\n    \"prob\",\n    \"sample\",\n    \"stddev\",\n    \"survival_function\",\n    \"variance\",\n]\n\n\n@six.add_metaclass(abc.ABCMeta)\nclass _BaseDistribution(object):\n  \"\"\"Abstract base class needed for resolving subclass hierarchy.\"\"\"\n  pass\n\n\ndef _copy_fn(fn):\n  \"\"\"Create a deep copy of fn.\n\n  Args:\n    fn: a callable\n\n  Returns:\n    A `FunctionType`: a deep copy of fn.\n\n  Raises:\n    TypeError: if `fn` is not a callable.\n  \"\"\"\n  if not callable(fn):\n    raise TypeError(\"fn is not callable: %s\" % fn)\n  # The blessed way to copy a function. copy.deepcopy fails to create a\n  # non-reference copy. Since:\n  #   types.FunctionType == type(lambda: None),\n  # and the docstring for the function type states:\n  #\n  #   function(code, globals[, name[, argdefs[, closure]]])\n  #\n  #   Create a function object from a code object and a dictionary.\n  #   ...\n  #\n  # Here we can use this to create a new function with the old function's\n  # code, globals, closure, etc.\n  return types.FunctionType(\n      code=fn.__code__, globals=fn.__globals__,\n      name=fn.__name__, argdefs=fn.__defaults__,\n      closure=fn.__closure__)\n\n\ndef _update_docstring(old_str, append_str):\n  \"\"\"Update old_str by inserting append_str just before the \"Args:\" section.\"\"\"\n  old_str = old_str or \"\"\n  old_str_lines = old_str.split(\"\\n\")\n\n  # Step 0: Prepend spaces to all lines of append_str. This is\n  # necessary for correct markdown generation.\n  append_str = \"\\n\".join(\"    %s\" % line for line in append_str.split(\"\\n\"))\n\n  # Step 1: Find mention of \"Args\":\n  has_args_ix = [\n      ix for ix, line in enumerate(old_str_lines)\n      if line.strip().lower() == \"args:\"]\n  if has_args_ix:\n    final_args_ix = has_args_ix[-1]\n    return (\"\\n\".join(old_str_lines[:final_args_ix])\n            + \"\\n\\n\" + append_str + \"\\n\\n\"\n            + \"\\n\".join(old_str_lines[final_args_ix:]))\n  else:\n    return old_str + \"\\n\\n\" + append_str\n\n\nclass _DistributionMeta(abc.ABCMeta):\n\n  def __new__(mcs, classname, baseclasses, attrs):\n    \"\"\"Control the creation of subclasses of the Distribution class.\n\n    The main purpose of this method is to properly propagate docstrings\n    from private Distribution methods, like `_log_prob`, into their\n    public wrappers as inherited by the Distribution base class\n    (e.g. `log_prob`).\n\n    Args:\n      classname: The name of the subclass being created.\n      baseclasses: A tuple of parent classes.\n      attrs: A dict mapping new attributes to their values.\n\n    Returns:\n      The class object.\n\n    Raises:\n      TypeError: If `Distribution` is not a subclass of `BaseDistribution`, or\n        the new class is derived via multiple inheritance and the first\n        parent class is not a subclass of `BaseDistribution`.\n      AttributeError:  If `Distribution` does not implement e.g. `log_prob`.\n      ValueError:  If a `Distribution` public method lacks a docstring.\n    \"\"\"\n    if not baseclasses:  # Nothing to be done for Distribution\n      raise TypeError(\"Expected non-empty baseclass. Does Distribution \"\n                      \"not subclass _BaseDistribution?\")\n    which_base = [\n        base for base in baseclasses\n        if base == _BaseDistribution or issubclass(base, Distribution)]\n    base = which_base[0]\n    if base == _BaseDistribution:  # Nothing to be done for Distribution\n      return abc.ABCMeta.__new__(mcs, classname, baseclasses, attrs)\n    if not issubclass(base, Distribution):\n      raise TypeError(\"First parent class declared for %s must be \"\n                      \"Distribution, but saw '%s'\" % (classname, base.__name__))\n    for attr in _DISTRIBUTION_PUBLIC_METHOD_WRAPPERS:\n      special_attr = \"_%s\" % attr\n      class_attr_value = attrs.get(attr, None)\n      if attr in attrs:\n        # The method is being overridden, do not update its docstring\n        continue\n      base_attr_value = getattr(base, attr, None)\n      if not base_attr_value:\n        raise AttributeError(\n            \"Internal error: expected base class '%s' to implement method '%s'\"\n            % (base.__name__, attr))\n      class_special_attr_value = attrs.get(special_attr, None)\n      if class_special_attr_value is None:\n        # No _special method available, no need to update the docstring.\n        continue\n      class_special_attr_docstring = tf_inspect.getdoc(class_special_attr_value)\n      if not class_special_attr_docstring:\n        # No docstring to append.\n        continue\n      class_attr_value = _copy_fn(base_attr_value)\n      class_attr_docstring = tf_inspect.getdoc(base_attr_value)\n      if class_attr_docstring is None:\n        raise ValueError(\n            \"Expected base class fn to contain a docstring: %s.%s\"\n            % (base.__name__, attr))\n      class_attr_value.__doc__ = _update_docstring(\n          class_attr_value.__doc__,\n          (\"Additional documentation from `%s`:\\n\\n%s\"\n           % (classname, class_special_attr_docstring)))\n      attrs[attr] = class_attr_value\n\n    return abc.ABCMeta.__new__(mcs, classname, baseclasses, attrs)\n\n\n@tf_export(\"distributions.ReparameterizationType\")\nclass ReparameterizationType(object):\n  \"\"\"Instances of this class represent how sampling is reparameterized.\n\n  Two static instances exist in the distributions library, signifying\n  one of two possible properties for samples from a distribution:\n\n  `FULLY_REPARAMETERIZED`: Samples from the distribution are fully\n    reparameterized, and straight-through gradients are supported.\n\n  `NOT_REPARAMETERIZED`: Samples from the distribution are not fully\n    reparameterized, and straight-through gradients are either partially\n    unsupported or are not supported at all. In this case, for purposes of\n    e.g. RL or variational inference, it is generally safest to wrap the\n    sample results in a `stop_gradients` call and use policy\n    gradients / surrogate loss instead.\n  \"\"\"\n\n  def __init__(self, rep_type):\n    self._rep_type = rep_type\n\n  def __repr__(self):\n    return \"<Reparameteriation Type: %s>\" % self._rep_type\n\n  def __eq__(self, other):\n    \"\"\"Determine if this `ReparameterizationType` is equal to another.\n\n    Since RepaparameterizationType instances are constant static global\n    instances, equality checks if two instances' id() values are equal.\n\n    Args:\n      other: Object to compare against.\n\n    Returns:\n      `self is other`.\n    \"\"\"\n    return self is other\n\n\n# Fully reparameterized distribution: samples from a fully\n# reparameterized distribution support straight-through gradients with\n# respect to all parameters.\nFULLY_REPARAMETERIZED = ReparameterizationType(\"FULLY_REPARAMETERIZED\")\ntf_export(\"distributions.FULLY_REPARAMETERIZED\").export_constant(\n    __name__, \"FULLY_REPARAMETERIZED\")\n\n\n# Not reparameterized distribution: samples from a non-\n# reparameterized distribution do not support straight-through gradients for\n# at least some of the parameters.\nNOT_REPARAMETERIZED = ReparameterizationType(\"NOT_REPARAMETERIZED\")\ntf_export(\"distributions.NOT_REPARAMETERIZED\").export_constant(\n    __name__, \"NOT_REPARAMETERIZED\")\n\n\n@six.add_metaclass(_DistributionMeta)\n@tf_export(\"distributions.Distribution\")\nclass Distribution(_BaseDistribution):\n  \"\"\"A generic probability distribution base class.\n\n  `Distribution` is a base class for constructing and organizing properties\n  (e.g., mean, variance) of random variables (e.g, Bernoulli, Gaussian).\n\n  #### Subclassing\n\n  Subclasses are expected to implement a leading-underscore version of the\n  same-named function. The argument signature should be identical except for\n  the omission of `name=\"...\"`. For example, to enable `log_prob(value,\n  name=\"log_prob\")` a subclass should implement `_log_prob(value)`.\n\n  Subclasses can append to public-level docstrings by providing\n  docstrings for their method specializations. For example:\n\n  ```python\n  @util.AppendDocstring(\"Some other details.\")\n  def _log_prob(self, value):\n    ...\n  ```\n\n  would add the string \"Some other details.\" to the `log_prob` function\n  docstring. This is implemented as a simple decorator to avoid python\n  linter complaining about missing Args/Returns/Raises sections in the\n  partial docstrings.\n\n  #### Broadcasting, batching, and shapes\n\n  All distributions support batches of independent distributions of that type.\n  The batch shape is determined by broadcasting together the parameters.\n\n  The shape of arguments to `__init__`, `cdf`, `log_cdf`, `prob`, and\n  `log_prob` reflect this broadcasting, as does the return value of `sample` and\n  `sample_n`.\n\n  `sample_n_shape = [n] + batch_shape + event_shape`, where `sample_n_shape` is\n  the shape of the `Tensor` returned from `sample_n`, `n` is the number of\n  samples, `batch_shape` defines how many independent distributions there are,\n  and `event_shape` defines the shape of samples from each of those independent\n  distributions. Samples are independent along the `batch_shape` dimensions, but\n  not necessarily so along the `event_shape` dimensions (depending on the\n  particulars of the underlying distribution).\n\n  Using the `Uniform` distribution as an example:\n\n  ```python\n  minval = 3.0\n  maxval = [[4.0, 6.0],\n            [10.0, 12.0]]\n\n  # Broadcasting:\n  # This instance represents 4 Uniform distributions. Each has a lower bound at\n  # 3.0 as the `minval` parameter was broadcasted to match `maxval`'s shape.\n  u = Uniform(minval, maxval)\n\n  # `event_shape` is `TensorShape([])`.\n  event_shape = u.event_shape\n  # `event_shape_t` is a `Tensor` which will evaluate to [].\n  event_shape_t = u.event_shape_tensor()\n\n  # Sampling returns a sample per distribution. `samples` has shape\n  # [5, 2, 2], which is [n] + batch_shape + event_shape, where n=5,\n  # batch_shape=[2, 2], and event_shape=[].\n  samples = u.sample_n(5)\n\n  # The broadcasting holds across methods. Here we use `cdf` as an example. The\n  # same holds for `log_cdf` and the likelihood functions.\n\n  # `cum_prob` has shape [2, 2] as the `value` argument was broadcasted to the\n  # shape of the `Uniform` instance.\n  cum_prob_broadcast = u.cdf(4.0)\n\n  # `cum_prob`'s shape is [2, 2], one per distribution. No broadcasting\n  # occurred.\n  cum_prob_per_dist = u.cdf([[4.0, 5.0],\n                             [6.0, 7.0]])\n\n  # INVALID as the `value` argument is not broadcastable to the distribution's\n  # shape.\n  cum_prob_invalid = u.cdf([4.0, 5.0, 6.0])\n  ```\n\n  #### Shapes\n\n  There are three important concepts associated with TensorFlow Distributions\n  shapes:\n  - Event shape describes the shape of a single draw from the distribution;\n    it may be dependent across dimensions. For scalar distributions, the event\n    shape is `[]`. For a 5-dimensional MultivariateNormal, the event shape is\n    `[5]`.\n  - Batch shape describes independent, not identically distributed draws, aka a\n    \"collection\" or \"bunch\" of distributions.\n  - Sample shape describes independent, identically distributed draws of batches\n    from the distribution family.\n\n  The event shape and the batch shape are properties of a Distribution object,\n  whereas the sample shape is associated with a specific call to `sample` or\n  `log_prob`.\n\n  For detailed usage examples of TensorFlow Distributions shapes, see\n  [this tutorial](\n  https://github.com/tensorflow/probability/blob/master/tensorflow_probability/examples/jupyter_notebooks/Understanding_TensorFlow_Distributions_Shapes.ipynb)\n\n  #### Parameter values leading to undefined statistics or distributions.\n\n  Some distributions do not have well-defined statistics for all initialization\n  parameter values. For example, the beta distribution is parameterized by\n  positive real numbers `concentration1` and `concentration0`, and does not have\n  well-defined mode if `concentration1 < 1` or `concentration0 < 1`.\n\n  The user is given the option of raising an exception or returning `NaN`.\n\n  ```python\n  a = tf.exp(tf.matmul(logits, weights_a))\n  b = tf.exp(tf.matmul(logits, weights_b))\n\n  # Will raise exception if ANY batch member has a < 1 or b < 1.\n  dist = distributions.beta(a, b, allow_nan_stats=False)\n  mode = dist.mode().eval()\n\n  # Will return NaN for batch members with either a < 1 or b < 1.\n  dist = distributions.beta(a, b, allow_nan_stats=True)  # Default behavior\n  mode = dist.mode().eval()\n  ```\n\n  In all cases, an exception is raised if *invalid* parameters are passed, e.g.\n\n  ```python\n  # Will raise an exception if any Op is run.\n  negative_a = -1.0 * a  # beta distribution by definition has a > 0.\n  dist = distributions.beta(negative_a, b, allow_nan_stats=True)\n  dist.mean().eval()\n  ```\n\n  \"\"\"\n\n  def __init__(self,\n               dtype,\n               reparameterization_type,\n               validate_args,\n               allow_nan_stats,\n               parameters=None,\n               graph_parents=None,\n               name=None):\n    \"\"\"Constructs the `Distribution`.\n\n    **This is a private method for subclass use.**\n\n    Args:\n      dtype: The type of the event samples. `None` implies no type-enforcement.\n      reparameterization_type: Instance of `ReparameterizationType`.\n        If `distributions.FULLY_REPARAMETERIZED`, this\n        `Distribution` can be reparameterized in terms of some standard\n        distribution with a function whose Jacobian is constant for the support\n        of the standard distribution. If `distributions.NOT_REPARAMETERIZED`,\n        then no such reparameterization is available.\n      validate_args: Python `bool`, default `False`. When `True` distribution\n        parameters are checked for validity despite possibly degrading runtime\n        performance. When `False` invalid inputs may silently render incorrect\n        outputs.\n      allow_nan_stats: Python `bool`, default `True`. When `True`, statistics\n        (e.g., mean, mode, variance) use the value \"`NaN`\" to indicate the\n        result is undefined. When `False`, an exception is raised if one or\n        more of the statistic's batch members are undefined.\n      parameters: Python `dict` of parameters used to instantiate this\n        `Distribution`.\n      graph_parents: Python `list` of graph prerequisites of this\n        `Distribution`.\n      name: Python `str` name prefixed to Ops created by this class. Default:\n        subclass name.\n\n    Raises:\n      ValueError: if any member of graph_parents is `None` or not a `Tensor`.\n    \"\"\"\n    graph_parents = [] if graph_parents is None else graph_parents\n    for i, t in enumerate(graph_parents):\n      if t is None or not tensor_util.is_tensor(t):\n        raise ValueError(\"Graph parent item %d is not a Tensor; %s.\" % (i, t))\n    if not name or name[-1] != \"/\":  # `name` is not a name scope\n      non_unique_name = name or type(self).__name__\n      with ops.name_scope(non_unique_name) as name:\n        pass\n    self._dtype = dtype\n    self._reparameterization_type = reparameterization_type\n    self._allow_nan_stats = allow_nan_stats\n    self._validate_args = validate_args\n    self._parameters = parameters or {}\n    self._graph_parents = graph_parents\n    self._name = name\n\n  @property\n  def _parameters(self):\n    return self._parameter_dict\n\n  @_parameters.setter\n  def _parameters(self, value):\n    \"\"\"Intercept assignments to self._parameters to avoid reference cycles.\n\n    Parameters are often created using locals(), so we need to clean out any\n    references to `self` before assigning it to an attribute.\n\n    Args:\n      value: A dictionary of parameters to assign to the `_parameters` property.\n    \"\"\"\n    if \"self\" in value:\n      del value[\"self\"]\n    self._parameter_dict = value\n\n  @classmethod\n  def param_shapes(cls, sample_shape, name=\"DistributionParamShapes\"):\n    \"\"\"Shapes of parameters given the desired shape of a call to `sample()`.\n\n    This is a class method that describes what key/value arguments are required\n    to instantiate the given `Distribution` so that a particular shape is\n    returned for that instance's call to `sample()`.\n\n    Subclasses should override class method `_param_shapes`.\n\n    Args:\n      sample_shape: `Tensor` or python list/tuple. Desired shape of a call to\n        `sample()`.\n      name: name to prepend ops with.\n\n    Returns:\n      `dict` of parameter name to `Tensor` shapes.\n    \"\"\"\n    with ops.name_scope(name, values=[sample_shape]):\n      return cls._param_shapes(sample_shape)\n\n  @classmethod\n  def param_static_shapes(cls, sample_shape):\n    \"\"\"param_shapes with static (i.e. `TensorShape`) shapes.\n\n    This is a class method that describes what key/value arguments are required\n    to instantiate the given `Distribution` so that a particular shape is\n    returned for that instance's call to `sample()`. Assumes that the sample's\n    shape is known statically.\n\n    Subclasses should override class method `_param_shapes` to return\n    constant-valued tensors when constant values are fed.\n\n    Args:\n      sample_shape: `TensorShape` or python list/tuple. Desired shape of a call\n        to `sample()`.\n\n    Returns:\n      `dict` of parameter name to `TensorShape`.\n\n    Raises:\n      ValueError: if `sample_shape` is a `TensorShape` and is not fully defined.\n    \"\"\"\n    if isinstance(sample_shape, tensor_shape.TensorShape):\n      if not sample_shape.is_fully_defined():\n        raise ValueError(\"TensorShape sample_shape must be fully defined\")\n      sample_shape = sample_shape.as_list()\n\n    params = cls.param_shapes(sample_shape)\n\n    static_params = {}\n    for name, shape in params.items():\n      static_shape = tensor_util.constant_value(shape)\n      if static_shape is None:\n        raise ValueError(\n            \"sample_shape must be a fully-defined TensorShape or list/tuple\")\n      static_params[name] = tensor_shape.TensorShape(static_shape)\n\n    return static_params\n\n  @staticmethod\n  def _param_shapes(sample_shape):\n    raise NotImplementedError(\"_param_shapes not implemented\")\n\n  @property\n  def name(self):\n    \"\"\"Name prepended to all ops created by this `Distribution`.\"\"\"\n    return self._name\n\n  @property\n  def dtype(self):\n    \"\"\"The `DType` of `Tensor`s handled by this `Distribution`.\"\"\"\n    return self._dtype\n\n  @property\n  def parameters(self):\n    \"\"\"Dictionary of parameters used to instantiate this `Distribution`.\"\"\"\n    # Remove \"self\", \"__class__\", or other special variables. These can appear\n    # if the subclass used:\n    # `parameters = dict(locals())`.\n    return {k: v for k, v in self._parameters.items()\n            if not k.startswith(\"__\") and k != \"self\"}\n\n  @property\n  def reparameterization_type(self):\n    \"\"\"Describes how samples from the distribution are reparameterized.\n\n    Currently this is one of the static instances\n    `distributions.FULLY_REPARAMETERIZED`\n    or `distributions.NOT_REPARAMETERIZED`.\n\n    Returns:\n      An instance of `ReparameterizationType`.\n    \"\"\"\n    return self._reparameterization_type\n\n  @property\n  def allow_nan_stats(self):\n    \"\"\"Python `bool` describing behavior when a stat is undefined.\n\n    Stats return +/- infinity when it makes sense. E.g., the variance of a\n    Cauchy distribution is infinity. However, sometimes the statistic is\n    undefined, e.g., if a distribution's pdf does not achieve a maximum within\n    the support of the distribution, the mode is undefined. If the mean is\n    undefined, then by definition the variance is undefined. E.g. the mean for\n    Student's T for df = 1 is undefined (no clear way to say it is either + or -\n    infinity), so the variance = E[(X - mean)**2] is also undefined.\n\n    Returns:\n      allow_nan_stats: Python `bool`.\n    \"\"\"\n    return self._allow_nan_stats\n\n  @property\n  def validate_args(self):\n    \"\"\"Python `bool` indicating possibly expensive checks are enabled.\"\"\"\n    return self._validate_args\n\n  def copy(self, **override_parameters_kwargs):\n    \"\"\"Creates a deep copy of the distribution.\n\n    Note: the copy distribution may continue to depend on the original\n    initialization arguments.\n\n    Args:\n      **override_parameters_kwargs: String/value dictionary of initialization\n        arguments to override with new values.\n\n    Returns:\n      distribution: A new instance of `type(self)` initialized from the union\n        of self.parameters and override_parameters_kwargs, i.e.,\n        `dict(self.parameters, **override_parameters_kwargs)`.\n    \"\"\"\n    parameters = dict(self.parameters, **override_parameters_kwargs)\n    return type(self)(**parameters)\n\n  def _batch_shape_tensor(self):\n    raise NotImplementedError(\n        \"batch_shape_tensor is not implemented: {}\".format(type(self).__name__))\n\n  def batch_shape_tensor(self, name=\"batch_shape_tensor\"):\n    \"\"\"Shape of a single sample from a single event index as a 1-D `Tensor`.\n\n    The batch dimensions are indexes into independent, non-identical\n    parameterizations of this distribution.\n\n    Args:\n      name: name to give to the op\n\n    Returns:\n      batch_shape: `Tensor`.\n    \"\"\"\n    with self._name_scope(name):\n      if self.batch_shape.is_fully_defined():\n        return ops.convert_to_tensor(self.batch_shape.as_list(),\n                                     dtype=dtypes.int32,\n                                     name=\"batch_shape\")\n      return self._batch_shape_tensor()\n\n  def _batch_shape(self):\n    return tensor_shape.TensorShape(None)\n\n  @property\n  def batch_shape(self):\n    \"\"\"Shape of a single sample from a single event index as a `TensorShape`.\n\n    May be partially defined or unknown.\n\n    The batch dimensions are indexes into independent, non-identical\n    parameterizations of this distribution.\n\n    Returns:\n      batch_shape: `TensorShape`, possibly unknown.\n    \"\"\"\n    return tensor_shape.as_shape(self._batch_shape())\n\n  def _event_shape_tensor(self):\n    raise NotImplementedError(\n        \"event_shape_tensor is not implemented: {}\".format(type(self).__name__))\n\n  def event_shape_tensor(self, name=\"event_shape_tensor\"):\n    \"\"\"Shape of a single sample from a single batch as a 1-D int32 `Tensor`.\n\n    Args:\n      name: name to give to the op\n\n    Returns:\n      event_shape: `Tensor`.\n    \"\"\"\n    with self._name_scope(name):\n      if self.event_shape.is_fully_defined():\n        return ops.convert_to_tensor(self.event_shape.as_list(),\n                                     dtype=dtypes.int32,\n                                     name=\"event_shape\")\n      return self._event_shape_tensor()\n\n  def _event_shape(self):\n    return tensor_shape.TensorShape(None)\n\n  @property\n  def event_shape(self):\n    \"\"\"Shape of a single sample from a single batch as a `TensorShape`.\n\n    May be partially defined or unknown.\n\n    Returns:\n      event_shape: `TensorShape`, possibly unknown.\n    \"\"\"\n    return tensor_shape.as_shape(self._event_shape())\n\n  def is_scalar_event(self, name=\"is_scalar_event\"):\n    \"\"\"Indicates that `event_shape == []`.\n\n    Args:\n      name: Python `str` prepended to names of ops created by this function.\n\n    Returns:\n      is_scalar_event: `bool` scalar `Tensor`.\n    \"\"\"\n    with self._name_scope(name):\n      return ops.convert_to_tensor(\n          self._is_scalar_helper(self.event_shape, self.event_shape_tensor),\n          name=\"is_scalar_event\")\n\n  def is_scalar_batch(self, name=\"is_scalar_batch\"):\n    \"\"\"Indicates that `batch_shape == []`.\n\n    Args:\n      name: Python `str` prepended to names of ops created by this function.\n\n    Returns:\n      is_scalar_batch: `bool` scalar `Tensor`.\n    \"\"\"\n    with self._name_scope(name):\n      return ops.convert_to_tensor(\n          self._is_scalar_helper(self.batch_shape, self.batch_shape_tensor),\n          name=\"is_scalar_batch\")\n\n  def _sample_n(self, n, seed=None):\n    raise NotImplementedError(\"sample_n is not implemented: {}\".format(\n        type(self).__name__))\n\n  def _call_sample_n(self, sample_shape, seed, name, **kwargs):\n    with self._name_scope(name, values=[sample_shape]):\n      sample_shape = ops.convert_to_tensor(\n          sample_shape, dtype=dtypes.int32, name=\"sample_shape\")\n      sample_shape, n = self._expand_sample_shape_to_vector(\n          sample_shape, \"sample_shape\")\n      samples = self._sample_n(n, seed, **kwargs)\n      batch_event_shape = array_ops.shape(samples)[1:]\n      final_shape = array_ops.concat([sample_shape, batch_event_shape], 0)\n      samples = array_ops.reshape(samples, final_shape)\n      samples = self._set_sample_static_shape(samples, sample_shape)\n      return samples\n\n  def sample(self, sample_shape=(), seed=None, name=\"sample\"):\n    \"\"\"Generate samples of the specified shape.\n\n    Note that a call to `sample()` without arguments will generate a single\n    sample.\n\n    Args:\n      sample_shape: 0D or 1D `int32` `Tensor`. Shape of the generated samples.\n      seed: Python integer seed for RNG\n      name: name to give to the op.\n\n    Returns:\n      samples: a `Tensor` with prepended dimensions `sample_shape`.\n    \"\"\"\n    return self._call_sample_n(sample_shape, seed, name)\n\n  def _log_prob(self, value):\n    raise NotImplementedError(\"log_prob is not implemented: {}\".format(\n        type(self).__name__))\n\n  def _call_log_prob(self, value, name, **kwargs):\n    with self._name_scope(name, values=[value]):\n      value = ops.convert_to_tensor(value, name=\"value\")\n      try:\n        return self._log_prob(value, **kwargs)\n      except NotImplementedError as original_exception:\n        try:\n          return math_ops.log(self._prob(value, **kwargs))\n        except NotImplementedError:\n          raise original_exception\n\n  def log_prob(self, value, name=\"log_prob\"):\n    \"\"\"Log probability density/mass function.\n\n    Args:\n      value: `float` or `double` `Tensor`.\n      name: Python `str` prepended to names of ops created by this function.\n\n    Returns:\n      log_prob: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with\n        values of type `self.dtype`.\n    \"\"\"\n    return self._call_log_prob(value, name)\n\n  def _prob(self, value):\n    raise NotImplementedError(\"prob is not implemented: {}\".format(\n        type(self).__name__))\n\n  def _call_prob(self, value, name, **kwargs):\n    with self._name_scope(name, values=[value]):\n      value = ops.convert_to_tensor(value, name=\"value\")\n      try:\n        return self._prob(value, **kwargs)\n      except NotImplementedError as original_exception:\n        try:\n          return math_ops.exp(self._log_prob(value, **kwargs))\n        except NotImplementedError:\n          raise original_exception\n\n  def prob(self, value, name=\"prob\"):\n    \"\"\"Probability density/mass function.\n\n    Args:\n      value: `float` or `double` `Tensor`.\n      name: Python `str` prepended to names of ops created by this function.\n\n    Returns:\n      prob: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with\n        values of type `self.dtype`.\n    \"\"\"\n    return self._call_prob(value, name)\n\n  def _log_cdf(self, value):\n    raise NotImplementedError(\"log_cdf is not implemented: {}\".format(\n        type(self).__name__))\n\n  def _call_log_cdf(self, value, name, **kwargs):\n    with self._name_scope(name, values=[value]):\n      value = ops.convert_to_tensor(value, name=\"value\")\n      try:\n        return self._log_cdf(value, **kwargs)\n      except NotImplementedError as original_exception:\n        try:\n          return math_ops.log(self._cdf(value, **kwargs))\n        except NotImplementedError:\n          raise original_exception\n\n  def log_cdf(self, value, name=\"log_cdf\"):\n    \"\"\"Log cumulative distribution function.\n\n    Given random variable `X`, the cumulative distribution function `cdf` is:\n\n    ```none\n    log_cdf(x) := Log[ P[X <= x] ]\n    ```\n\n    Often, a numerical approximation can be used for `log_cdf(x)` that yields\n    a more accurate answer than simply taking the logarithm of the `cdf` when\n    `x << -1`.\n\n    Args:\n      value: `float` or `double` `Tensor`.\n      name: Python `str` prepended to names of ops created by this function.\n\n    Returns:\n      logcdf: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with\n        values of type `self.dtype`.\n    \"\"\"\n    return self._call_log_cdf(value, name)\n\n  def _cdf(self, value):\n    raise NotImplementedError(\"cdf is not implemented: {}\".format(\n        type(self).__name__))\n\n  def _call_cdf(self, value, name, **kwargs):\n    with self._name_scope(name, values=[value]):\n      value = ops.convert_to_tensor(value, name=\"value\")\n      try:\n        return self._cdf(value, **kwargs)\n      except NotImplementedError as original_exception:\n        try:\n          return math_ops.exp(self._log_cdf(value, **kwargs))\n        except NotImplementedError:\n          raise original_exception\n\n  def cdf(self, value, name=\"cdf\"):\n    \"\"\"Cumulative distribution function.\n\n    Given random variable `X`, the cumulative distribution function `cdf` is:\n\n    ```none\n    cdf(x) := P[X <= x]\n    ```\n\n    Args:\n      value: `float` or `double` `Tensor`.\n      name: Python `str` prepended to names of ops created by this function.\n\n    Returns:\n      cdf: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with\n        values of type `self.dtype`.\n    \"\"\"\n    return self._call_cdf(value, name)\n\n  def _log_survival_function(self, value):\n    raise NotImplementedError(\n        \"log_survival_function is not implemented: {}\".format(\n            type(self).__name__))\n\n  def _call_log_survival_function(self, value, name, **kwargs):\n    with self._name_scope(name, values=[value]):\n      value = ops.convert_to_tensor(value, name=\"value\")\n      try:\n        return self._log_survival_function(value, **kwargs)\n      except NotImplementedError as original_exception:\n        try:\n          return math_ops.log1p(-self.cdf(value, **kwargs))\n        except NotImplementedError:\n          raise original_exception\n\n  def log_survival_function(self, value, name=\"log_survival_function\"):\n    \"\"\"Log survival function.\n\n    Given random variable `X`, the survival function is defined:\n\n    ```none\n    log_survival_function(x) = Log[ P[X > x] ]\n                             = Log[ 1 - P[X <= x] ]\n                             = Log[ 1 - cdf(x) ]\n    ```\n\n    Typically, different numerical approximations can be used for the log\n    survival function, which are more accurate than `1 - cdf(x)` when `x >> 1`.\n\n    Args:\n      value: `float` or `double` `Tensor`.\n      name: Python `str` prepended to names of ops created by this function.\n\n    Returns:\n      `Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type\n        `self.dtype`.\n    \"\"\"\n    return self._call_log_survival_function(value, name)\n\n  def _survival_function(self, value):\n    raise NotImplementedError(\"survival_function is not implemented: {}\".format(\n        type(self).__name__))\n\n  def _call_survival_function(self, value, name, **kwargs):\n    with self._name_scope(name, values=[value]):\n      value = ops.convert_to_tensor(value, name=\"value\")\n      try:\n        return self._survival_function(value, **kwargs)\n      except NotImplementedError as original_exception:\n        try:\n          return 1. - self.cdf(value, **kwargs)\n        except NotImplementedError:\n          raise original_exception\n\n  def survival_function(self, value, name=\"survival_function\"):\n    \"\"\"Survival function.\n\n    Given random variable `X`, the survival function is defined:\n\n    ```none\n    survival_function(x) = P[X > x]\n                         = 1 - P[X <= x]\n                         = 1 - cdf(x).\n    ```\n\n    Args:\n      value: `float` or `double` `Tensor`.\n      name: Python `str` prepended to names of ops created by this function.\n\n    Returns:\n      `Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type\n        `self.dtype`.\n    \"\"\"\n    return self._call_survival_function(value, name)\n\n  def _entropy(self):\n    raise NotImplementedError(\"entropy is not implemented: {}\".format(\n        type(self).__name__))\n\n  def entropy(self, name=\"entropy\"):\n    \"\"\"Shannon entropy in nats.\"\"\"\n    with self._name_scope(name):\n      return self._entropy()\n\n  def _mean(self):\n    raise NotImplementedError(\"mean is not implemented: {}\".format(\n        type(self).__name__))\n\n  def mean(self, name=\"mean\"):\n    \"\"\"Mean.\"\"\"\n    with self._name_scope(name):\n      return self._mean()\n\n  def _quantile(self, value):\n    raise NotImplementedError(\"quantile is not implemented: {}\".format(\n        type(self).__name__))\n\n  def _call_quantile(self, value, name, **kwargs):\n    with self._name_scope(name, values=[value]):\n      value = ops.convert_to_tensor(value, name=\"value\")\n      return self._quantile(value, **kwargs)\n\n  def quantile(self, value, name=\"quantile\"):\n    \"\"\"Quantile function. Aka \"inverse cdf\" or \"percent point function\".\n\n    Given random variable `X` and `p in [0, 1]`, the `quantile` is:\n\n    ```none\n    quantile(p) := x such that P[X <= x] == p\n    ```\n\n    Args:\n      value: `float` or `double` `Tensor`.\n      name: Python `str` prepended to names of ops created by this function.\n\n    Returns:\n      quantile: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with\n        values of type `self.dtype`.\n    \"\"\"\n    return self._call_quantile(value, name)\n\n  def _variance(self):\n    raise NotImplementedError(\"variance is not implemented: {}\".format(\n        type(self).__name__))\n\n  def variance(self, name=\"variance\"):\n    \"\"\"Variance.\n\n    Variance is defined as,\n\n    ```none\n    Var = E[(X - E[X])**2]\n    ```\n\n    where `X` is the random variable associated with this distribution, `E`\n    denotes expectation, and `Var.shape = batch_shape + event_shape`.\n\n    Args:\n      name: Python `str` prepended to names of ops created by this function.\n\n    Returns:\n      variance: Floating-point `Tensor` with shape identical to\n        `batch_shape + event_shape`, i.e., the same shape as `self.mean()`.\n    \"\"\"\n    with self._name_scope(name):\n      try:\n        return self._variance()\n      except NotImplementedError as original_exception:\n        try:\n          return math_ops.square(self._stddev())\n        except NotImplementedError:\n          raise original_exception\n\n  def _stddev(self):\n    raise NotImplementedError(\"stddev is not implemented: {}\".format(\n        type(self).__name__))\n\n  def stddev(self, name=\"stddev\"):\n    \"\"\"Standard deviation.\n\n    Standard deviation is defined as,\n\n    ```none\n    stddev = E[(X - E[X])**2]**0.5\n    ```\n\n    where `X` is the random variable associated with this distribution, `E`\n    denotes expectation, and `stddev.shape = batch_shape + event_shape`.\n\n    Args:\n      name: Python `str` prepended to names of ops created by this function.\n\n    Returns:\n      stddev: Floating-point `Tensor` with shape identical to\n        `batch_shape + event_shape`, i.e., the same shape as `self.mean()`.\n    \"\"\"\n\n    with self._name_scope(name):\n      try:\n        return self._stddev()\n      except NotImplementedError as original_exception:\n        try:\n          return math_ops.sqrt(self._variance())\n        except NotImplementedError:\n          raise original_exception\n\n  def _covariance(self):\n    raise NotImplementedError(\"covariance is not implemented: {}\".format(\n        type(self).__name__))\n\n  def covariance(self, name=\"covariance\"):\n    \"\"\"Covariance.\n\n    Covariance is (possibly) defined only for non-scalar-event distributions.\n\n    For example, for a length-`k`, vector-valued distribution, it is calculated\n    as,\n\n    ```none\n    Cov[i, j] = Covariance(X_i, X_j) = E[(X_i - E[X_i]) (X_j - E[X_j])]\n    ```\n\n    where `Cov` is a (batch of) `k x k` matrix, `0 <= (i, j) < k`, and `E`\n    denotes expectation.\n\n    Alternatively, for non-vector, multivariate distributions (e.g.,\n    matrix-valued, Wishart), `Covariance` shall return a (batch of) matrices\n    under some vectorization of the events, i.e.,\n\n    ```none\n    Cov[i, j] = Covariance(Vec(X)_i, Vec(X)_j) = [as above]\n    ```\n\n    where `Cov` is a (batch of) `k' x k'` matrices,\n    `0 <= (i, j) < k' = reduce_prod(event_shape)`, and `Vec` is some function\n    mapping indices of this distribution's event dimensions to indices of a\n    length-`k'` vector.\n\n    Args:\n      name: Python `str` prepended to names of ops created by this function.\n\n    Returns:\n      covariance: Floating-point `Tensor` with shape `[B1, ..., Bn, k', k']`\n        where the first `n` dimensions are batch coordinates and\n        `k' = reduce_prod(self.event_shape)`.\n    \"\"\"\n    with self._name_scope(name):\n      return self._covariance()\n\n  def _mode(self):\n    raise NotImplementedError(\"mode is not implemented: {}\".format(\n        type(self).__name__))\n\n  def mode(self, name=\"mode\"):\n    \"\"\"Mode.\"\"\"\n    with self._name_scope(name):\n      return self._mode()\n\n  def _cross_entropy(self, other):\n    return kullback_leibler.cross_entropy(\n        self, other, allow_nan_stats=self.allow_nan_stats)\n\n  def cross_entropy(self, other, name=\"cross_entropy\"):\n    \"\"\"Computes the (Shannon) cross entropy.\n\n    Denote this distribution (`self`) by `P` and the `other` distribution by\n    `Q`. Assuming `P, Q` are absolutely continuous with respect to\n    one another and permit densities `p(x) dr(x)` and `q(x) dr(x)`, (Shanon)\n    cross entropy is defined as:\n\n    ```none\n    H[P, Q] = E_p[-log q(X)] = -int_F p(x) log q(x) dr(x)\n    ```\n\n    where `F` denotes the support of the random variable `X ~ P`.\n\n    Args:\n      other: `tfp.distributions.Distribution` instance.\n      name: Python `str` prepended to names of ops created by this function.\n\n    Returns:\n      cross_entropy: `self.dtype` `Tensor` with shape `[B1, ..., Bn]`\n        representing `n` different calculations of (Shanon) cross entropy.\n    \"\"\"\n    with self._name_scope(name):\n      return self._cross_entropy(other)\n\n  def _kl_divergence(self, other):\n    return kullback_leibler.kl_divergence(\n        self, other, allow_nan_stats=self.allow_nan_stats)\n\n  def kl_divergence(self, other, name=\"kl_divergence\"):\n    \"\"\"Computes the Kullback--Leibler divergence.\n\n    Denote this distribution (`self`) by `p` and the `other` distribution by\n    `q`. Assuming `p, q` are absolutely continuous with respect to reference\n    measure `r`, the KL divergence is defined as:\n\n    ```none\n    KL[p, q] = E_p[log(p(X)/q(X))]\n             = -int_F p(x) log q(x) dr(x) + int_F p(x) log p(x) dr(x)\n             = H[p, q] - H[p]\n    ```\n\n    where `F` denotes the support of the random variable `X ~ p`, `H[., .]`\n    denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy.\n\n    Args:\n      other: `tfp.distributions.Distribution` instance.\n      name: Python `str` prepended to names of ops created by this function.\n\n    Returns:\n      kl_divergence: `self.dtype` `Tensor` with shape `[B1, ..., Bn]`\n        representing `n` different calculations of the Kullback-Leibler\n        divergence.\n    \"\"\"\n    with self._name_scope(name):\n      return self._kl_divergence(other)\n\n  def __str__(self):\n    return (\"tfp.distributions.{type_name}(\"\n            \"\\\"{self_name}\\\"\"\n            \"{maybe_batch_shape}\"\n            \"{maybe_event_shape}\"\n            \", dtype={dtype})\".format(\n                type_name=type(self).__name__,\n                self_name=self.name,\n                maybe_batch_shape=(\", batch_shape={}\".format(self.batch_shape)\n                                   if self.batch_shape.ndims is not None\n                                   else \"\"),\n                maybe_event_shape=(\", event_shape={}\".format(self.event_shape)\n                                   if self.event_shape.ndims is not None\n                                   else \"\"),\n                dtype=self.dtype.name))\n\n  def __repr__(self):\n    return (\"<tfp.distributions.{type_name} \"\n            \"'{self_name}'\"\n            \" batch_shape={batch_shape}\"\n            \" event_shape={event_shape}\"\n            \" dtype={dtype}>\".format(\n                type_name=type(self).__name__,\n                self_name=self.name,\n                batch_shape=self.batch_shape,\n                event_shape=self.event_shape,\n                dtype=self.dtype.name))\n\n  @contextlib.contextmanager\n  def _name_scope(self, name=None, values=None):\n    \"\"\"Helper function to standardize op scope.\"\"\"\n    with ops.name_scope(self.name):\n      with ops.name_scope(name, values=(\n          ([] if values is None else values) + self._graph_parents)) as scope:\n        yield scope\n\n  def _expand_sample_shape_to_vector(self, x, name):\n    \"\"\"Helper to `sample` which ensures input is 1D.\"\"\"\n    x_static_val = tensor_util.constant_value(x)\n    if x_static_val is None:\n      prod = math_ops.reduce_prod(x)\n    else:\n      prod = np.prod(x_static_val, dtype=x.dtype.as_numpy_dtype())\n\n    ndims = x.get_shape().ndims  # != sample_ndims\n    if ndims is None:\n      # Maybe expand_dims.\n      ndims = array_ops.rank(x)\n      expanded_shape = util.pick_vector(\n          math_ops.equal(ndims, 0),\n          np.array([1], dtype=np.int32), array_ops.shape(x))\n      x = array_ops.reshape(x, expanded_shape)\n    elif ndims == 0:\n      # Definitely expand_dims.\n      if x_static_val is not None:\n        x = ops.convert_to_tensor(\n            np.array([x_static_val], dtype=x.dtype.as_numpy_dtype()),\n            name=name)\n      else:\n        x = array_ops.reshape(x, [1])\n    elif ndims != 1:\n      raise ValueError(\"Input is neither scalar nor vector.\")\n\n    return x, prod\n\n  def _set_sample_static_shape(self, x, sample_shape):\n    \"\"\"Helper to `sample`; sets static shape info.\"\"\"\n    # Set shape hints.\n    sample_shape = tensor_shape.TensorShape(\n        tensor_util.constant_value(sample_shape))\n\n    ndims = x.get_shape().ndims\n    sample_ndims = sample_shape.ndims\n    batch_ndims = self.batch_shape.ndims\n    event_ndims = self.event_shape.ndims\n\n    # Infer rank(x).\n    if (ndims is None and\n        sample_ndims is not None and\n        batch_ndims is not None and\n        event_ndims is not None):\n      ndims = sample_ndims + batch_ndims + event_ndims\n      x.set_shape([None] * ndims)\n\n    # Infer sample shape.\n    if ndims is not None and sample_ndims is not None:\n      shape = sample_shape.concatenate([None]*(ndims - sample_ndims))\n      x.set_shape(x.get_shape().merge_with(shape))\n\n    # Infer event shape.\n    if ndims is not None and event_ndims is not None:\n      shape = tensor_shape.TensorShape(\n          [None]*(ndims - event_ndims)).concatenate(self.event_shape)\n      x.set_shape(x.get_shape().merge_with(shape))\n\n    # Infer batch shape.\n    if batch_ndims is not None:\n      if ndims is not None:\n        if sample_ndims is None and event_ndims is not None:\n          sample_ndims = ndims - batch_ndims - event_ndims\n        elif event_ndims is None and sample_ndims is not None:\n          event_ndims = ndims - batch_ndims - sample_ndims\n      if sample_ndims is not None and event_ndims is not None:\n        shape = tensor_shape.TensorShape([None]*sample_ndims).concatenate(\n            self.batch_shape).concatenate([None]*event_ndims)\n        x.set_shape(x.get_shape().merge_with(shape))\n\n    return x\n\n  def _is_scalar_helper(self, static_shape, dynamic_shape_fn):\n    \"\"\"Implementation for `is_scalar_batch` and `is_scalar_event`.\"\"\"\n    if static_shape.ndims is not None:\n      return static_shape.ndims == 0\n    shape = dynamic_shape_fn()\n    if (shape.get_shape().ndims is not None and\n        shape.get_shape()[0].value is not None):\n      # If the static_shape is correctly written then we should never execute\n      # this branch. We keep it just in case there's some unimagined corner\n      # case.\n      return shape.get_shape().as_list() == [0]\n    return math_ops.equal(array_ops.shape(shape)[0], 0)\n", "meta": {"hexsha": "76d980679e6bff533eecb60e2ad683b5e0a59975", "size": 45160, "ext": "py", "lang": "Python", "max_stars_repo_path": "tensorflow/python/ops/distributions/distribution.py", "max_stars_repo_name": "hsm207/tensorflow", "max_stars_repo_head_hexsha": "8ab4678ba216c3ec8fa32f417cb667b056689939", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-18T01:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-18T01:52:29.000Z", "max_issues_repo_path": "tensorflow/python/ops/distributions/distribution.py", "max_issues_repo_name": "hsm207/tensorflow", "max_issues_repo_head_hexsha": "8ab4678ba216c3ec8fa32f417cb667b056689939", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tensorflow/python/ops/distributions/distribution.py", "max_forks_repo_name": "hsm207/tensorflow", "max_forks_repo_head_hexsha": "8ab4678ba216c3ec8fa32f417cb667b056689939", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-12-20T01:35:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-10T17:29:57.000Z", "avg_line_length": 35.0893550894, "max_line_length": 158, "alphanum_fraction": 0.6751107174, "include": true, "reason": "import numpy", "num_tokens": 10589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19734484463400281}}
{"text": "#!/usr/bin/env python\n\"\"\"\n# =================================================================================================================== #\n# - Written by Enrico Ciraci - 04/24/2019\n# =================================================================================================================== #\n# - Create Basins Binary Mask given:\n# -\n# - input basin shapefile;\n# - reference lat/lon grid;\n# -\n# =================================================================================================================== #\n# -  INPUT PARAMETERS:\n# - \"-S\", \"--basins\" - list of basins to consider passed as csv\n# -                    (def. 'indus_river', 'lower_indus_river', 'upper_indus_river')\n# - \"-B\", \"--buffer\" - boundary shapefile buffer used in the intersection operation. (def. 0)\n# - \"-N\", \"--nproc\" - number of maximum simultaneous processes (def. 32)\n# =================================================================================================================== #\n#  OUTPUTS - (see introduction)\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #\n#     To Run this procedure digit:\n#\n#     python create_basins_mask.py\n# =================================================================================================================== #\n# PYTHON DEPENDENCIES:\n#\tnumpy: Scientific Computing Tools For Python (http://www.numpy.org)\n#   netCDF4: python/numpy interface to netCDF library (https://pypi.python.org/pypi/netCDF4)\n#   getopt: C-style parser for command line options (https://docs.python.org/2/library/getopt.html)\n#   xarray: xarray: N-D labeled arrays and datasets in Python (http://xarray.pydata.org)\n#   pyshp: This library reads and writes ESRI Shapefiles in pure Python. (https://github.com/GeospatialPython/pyshp)\n#   shapely: Manipulation and analysis of geometric objects in the Cartesian plane. (https://shapely.readthedocs.\n#            io/en/stable/manual.html)\n#   concurrent.futures: https://docs.python.org/3/library/concurrent.futures.html\n# PROGRAM DEPENDENCIES:\n#   enrico_library: https://github.com/uci-gravity/Enrico\n# =================================================================================================================== #\n# - UPDATE - \n# =================================================================================================================== #\n# IMPORTANT:\n# =================================================================================================================== #\n\"\"\"\n# - python dependencies\nfrom __future__ import print_function\nimport os\nimport sys\nimport numpy as np\nimport netCDF4 as nC4\nimport getopt\nimport shapefile\nfrom shapely.geometry import shape, Point, polygon\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nfrom tqdm import tqdm\nfrom time import time\n\n\ndef write_point_shapefile(output_path_shp, lat_vect, lon_vect, attribute_vect, attribute_name=''):\n    \"\"\"\n    Save a Point Type esri shapefile with a single attribute per point\n    :param output_path_shp: absolute path to the output file\n    :param lat_vect: vector containing the latitude points coordinates\n    :param lon_vect: vector containing the longitude points coordinates\n    :param attribute_vect: vector containing the discharge magnitude\n    :param attribute_name: name of the attribute\n    :return: \n    \"\"\"\n    # - python\n    w = shapefile.Writer(output_path_shp[:-4], shapeType=1)\n    w.autoBalance = 1\n    w.field(attribute_name, 'F', 10, 8)\n    # -\n    for ind in range(0, len(attribute_vect)):\n        w.point(np.float(lon_vect[ind]), np.float(lat_vect[ind]))\n        w.record(float(attribute_vect[ind]))\n    w.close()\n    # - create the PRJ file\n    with open(output_path_shp[:-3] + 'prj', \"w\") as prj:\n        epsg = 'GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563]],                ' \\\n               'PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433]]'\n        prj.write(epsg)\n\n\ndef verify_and_create_dir(abs_path, dir_name):\n    \"\"\"\n    Create directory\n    :param abs_path:absolute path to the output directory\n    :param dir_name: new directory name\n    :return: path to the new directory\n    \"\"\"\n    directory = os.path.join(abs_path, dir_name)\n\n    if not os.path.exists(directory):\n        os.mkdir(directory)\n    # -\n    return directory\n\n\ndef calculate_area_mask_vect(lat_vect, lon_vect):\n    \"\"\"\n    Calculate Latitude/Longitude Area mask at a selected degree resolution grid\n    defined employing the input latitude and longitude vector.\n    :param lat_vect: latitude vector\n    :param lon_vect: latitude vector\n    :return: Area Mask - Expressed in cm2\n    \"\"\"\n    # - General Parameters\n    dtr = np.pi / 180.    # - Coefficient for the deg to radiant conversion\n    rad_e = 6.371e8       # -  Earth Radius in cm\n    out_lat = lat_vect\n    out_lon = lon_vect\n    resolution_lat = np.abs(lat_vect[1] - lat_vect[0])\n    resolution_lon = np.abs(lon_vect[1] - lon_vect[0])\n    area0 = resolution_lat * resolution_lon * dtr * dtr  # - Area of a single point mass\n    out_lat_grid, out_lon_grid = np.meshgrid(out_lat, out_lon)\n    # - output area mask\n    radius = np.sqrt(area0 * np.cos(out_lat_grid * dtr) / np.pi) * rad_e\n    out_mask = np.pi * (radius ** 2)  # - Circular Area in cm^2\n    # -\n    return out_mask\n\n\ndef from_shp_to_polygon(path_to_shape, buffer_p=0.5):\n    \"\"\"\n    Read the input shapefile and return a list of polygon objects\n    :param path_to_shape: absolute path to the input shapefile\n    :param buffer_p: boundary buffer in degree\n    :return:\n    \"\"\"\n    # - open the shapefile using the python fiona package\n    region_list = list()\n    # - read the input regional shapefile\n    pol = shapefile.Reader(path_to_shape)\n    # - extract polygon-shapes\n    sub = pol.shapes()\n    # - Build the regional ice-covered region domain\n    for ss in range(0, len(sub)):\n        if len(sub[ss].parts) > 1:\n            # - the shapefile is composed by multiple parts defining an external ring and one ore more\n            # - interior holes\n            limits = sub[ss].parts\n            holes = []  # - holes boundaries\n            for x in range(2, len(limits)):\n                holes.append(sub[ss].points[limits[x - 1]:limits[x]])\n            # - define polygon with holes\n            shp_tmp = polygon.Polygon(sub[ss].points[limits[0]:limits[1]], holes)\n        else:\n            # - polygon composed only by an external ring\n            shp_tmp = shape(sub[ss]).buffer(buffer_p)\n\n        region_list.append(shp_tmp)\n    # -\n    return region_list\n\n\ndef write_netcdf_mask(binary_mask, area_mask, lat, lon, file_to_save):\n    \"\"\"\n    Write spatial field in a netcdf archive\n    :param binary_mask: input binary mask\n    :param area_mask: regional area mask in cm2\n    :param lat: latitude axis\n    :param lon: longitude axis\n    :param file_to_save: absolute path to the output fi;e\n    :return:\n    \"\"\"\n    # - Writing the Output file\n    rootgrp = nC4.Dataset(file_to_save, mode='w', format='NETCDF4')\n    # - Create Variable dimensions\n    rootgrp.createDimension('lat', len(lat))\n    rootgrp.createDimension('lon', len(lon))\n    # - Create output variables:\n    var_lat = rootgrp.createVariable('lat', 'f4', 'lat')\n    var_lon = rootgrp.createVariable('lon', 'f4', 'lon')\n    var_mask = rootgrp.createVariable('area', 'f8', ('lat', 'lon'))\n    var_mask_binary = rootgrp.createVariable('binary', 'f8', ('lat', 'lon'))\n\n    # - Longitude attributes\n    var_lon.units = 'degree east'\n    var_lon.long_name = 'Longitude'\n    var_lon.actual_range = [np.min(lon), np.max(lon)]\n    var_lon.standard_name = 'longitude'\n    var_lon.axis = 'X'\n    var_lon.coordinate_defines = 'point'\n    # - Latitude Attributes\n    var_lat.units = 'degree north'\n    var_lat.long_name = 'Latitude'\n    var_lat.actual_range = [np.min(lat), np.max(lat)]\n    var_lat.standard_name = 'latitude'\n    var_lat.axis = 'Y'\n    var_lat.coordinate_defines = 'point'\n    # - Mask Attributes\n    var_mask.units = 'cm2'\n    var_mask.var_desc = 'Basin Area Mask'\n    var_mask.actual_range = [np.min(area_mask), np.max(area_mask)]\n    # - Binary Mask Attributes\n    var_mask_binary.units = ''\n    var_mask_binary.var_desc = 'basin binary mask'\n    var_mask_binary.actual_range = [np.min(binary_mask), np.max(binary_mask)]\n\n    var_lon[:] = lon\n    var_lat[:] = lat\n    var_mask[:, :] = area_mask\n    var_mask_binary[:, :] = binary_mask\n    # -  close the netcdf file created\n    rootgrp.close()\n\n\ndef parallel_code(data_dict):\n    \"\"\"\n    Contains the portion of the code that is executed in parallel\n    :param data_dict: python dictionary containing the input parameters\n    :return:\n    \"\"\"\n    lon_s = data_dict['lon_s']\n    lat_s = data_dict['lat_s']\n    xy_point = Point(lon_s, lat_s)\n    region_list = data_dict['rl']\n    out_index = -9999.\n    for rl in region_list:\n        if xy_point.within(rl):\n            out_index = data_dict['index']\n            break\n    return out_index\n\n\ndef main():\n    \"\"\"\n    Main Section of the script.\n    :return:\n    \"\"\"\n    # -- Read the system arguments listed after the program and run the program\n    long_options = ['basins=', 'buffer=', 'nproc=']\n    try:\n        optlist = getopt.getopt(sys.argv[1:], 'S:B:N:', long_options)\n    except ValueError:\n        optlist = list()\n\n    # - list of the river basin to consider\n    basin_list = ['indus_river']\n    # - uses by default a number of simultaneous processes equal to the number of CPUs\n    max_processes = None\n    # - basin boundaries buffer\n    buffer_p = 0.\n    try:\n        for opt, arg in optlist[0]:\n            if opt in (\"-S\", \"--basins\"):\n                # - list of the basins to process\n                # - passed as csv\n                basin_list = arg.split(',')\n            elif opt in (\"-B\", \"--buffer\"):\n                # - Basin boundary buffer\n                buffer_p = float(arg)\n            elif opt in (\"-N\", \"--nproc\"):\n                # - number of simultaneous processes\n                max_processes = int(arg)\n    except ValueError:\n        pass\n    start = time()\n    \n    # - input/output data directory\n    input_dir = os.path.join('.', 'input')\n    output_dir = verify_and_create_dir('.', 'output')\n\n    # - lat/lon arrays\n    lat_vect = np.arange(-90,  90+1, 1)\n    lon_vect = np.arange(-180,  180+1, 1)\n    # - create lat lon domain grid\n    l_lon, l_lat = np.meshgrid(lon_vect, lat_vect)\n    l_lon_vect = l_lon.flatten()\n    l_lat_vect = l_lat.flatten()\n\n    # - calculate a global area mask in cm2 ad the model resolution\n    area_mask = np.transpose(calculate_area_mask_vect(lat_vect, lon_vect))\n\n    # - crop the model mask using the selected river mask\n    if basin_list:\n        print('# - Create Basins Mask.')\n        for basin in basin_list:\n            print('# - ' + basin)\n            # - load basin mask\n            b_info = dict()\n            b_info['basin_boundary'] = os.path.join(input_dir, basin, basin+'.shp')\n            out_dir_reg = verify_and_create_dir(output_dir, basin)\n            # - read regional shapefile and convert it to a shapely polygon object\n            region_list = from_shp_to_polygon(b_info['basin_boundary'], buffer_p=buffer_p)\n            # - list that will contain the indexes of the points within the region of interest\n            tot_ind = list()\n            # - parallel portion of the code\n            processes = []\n            with ThreadPoolExecutor(max_workers=max_processes) as executor:\n                for ll in tqdm(range(0, len(l_lon_vect)), ncols=50):\n                    lon_s = l_lon_vect[ll]\n                    lat_s = l_lat_vect[ll]\n                    # -\n                    data_dict = dict()\n                    data_dict['lon_s'] = lon_s\n                    data_dict['lat_s'] = lat_s\n                    data_dict['index'] = ll\n                    data_dict['rl'] = region_list\n                    processes.append(executor.submit(parallel_code, data_dict))\n\n            for res in as_completed(processes):\n                res_out = res.result()\n                if res_out != -9999.:\n                    tot_ind.append(res_out)\n            # - Save the obtained mask\n            out_lat = np.array(l_lat_vect)[tot_ind]\n            out_lon = np.array(l_lon_vect)[tot_ind]\n            id_y = np.arange(len(out_lon)) + 1\n            output_path_shp = os.path.join(out_dir_reg, basin + '.shp')\n            write_point_shapefile(output_path_shp, out_lat, out_lon, id_y, attribute_name='id')\n\n            # - Save the mask also in netcdf format\n            binary_mask = np.zeros(np.shape(l_lon))\n            # - fill the binary mask\n            for k in range(0, len(out_lat)):\n                binary_mask[np.where(lat_vect == out_lat[k]), np.where(lon_vect == out_lon[k])] = 1.\n            output_path_shp = os.path.join(out_dir_reg, basin + '.nc')\n            write_netcdf_mask(binary_mask, area_mask*binary_mask, lat_vect, lon_vect, output_path_shp)\n\n    end = time()\n    hours, rem = divmod(end - start, 3600)\n    minutes, seconds = divmod(rem, 60)\n    print(f'Execution Time: ' + \"{:0>2}:{:0>2}:{:05.2f}\".format(int(hours), int(minutes), seconds))\n\n\n# -- run main program\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "44fa2f49b6d563808e8b4ce11d0ca4a48e2a3301", "size": 13205, "ext": "py", "lang": "Python", "max_stars_repo_path": "read_gridded_latlon_data/create_basins_mask.py", "max_stars_repo_name": "eciraci/Geophysics", "max_stars_repo_head_hexsha": "6e216e78e09157769d6192f0ed8c5981be128a02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "read_gridded_latlon_data/create_basins_mask.py", "max_issues_repo_name": "eciraci/Geophysics", "max_issues_repo_head_hexsha": "6e216e78e09157769d6192f0ed8c5981be128a02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "read_gridded_latlon_data/create_basins_mask.py", "max_forks_repo_name": "eciraci/Geophysics", "max_forks_repo_head_hexsha": "6e216e78e09157769d6192f0ed8c5981be128a02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3822629969, "max_line_length": 119, "alphanum_fraction": 0.5824308974, "include": true, "reason": "import numpy", "num_tokens": 3176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.1973448446340028}}
{"text": "# Copyright (C) 2013 Lindley Graham\n\n\"\"\"\nThis module contains a set of methods and a class for interacting with NCSU\nSubdomain Modeling Python code and associated files. The focus of this module\nis the :class:`subdomain`.\n\"\"\"\n\nimport glob, os, sys, subprocess, re, math \nimport numpy as np\nimport scipy.io as sio\nimport py.gensub as gensub \nimport polyadcirc.run_framework.domain as dom\nimport polyadcirc.pyADCIRC.fort15_management as f15\nimport polyadcirc.pyADCIRC.fort13_management as f13\nimport polyadcirc.pyADCIRC.output as output\nimport polyadcirc.run_framework.random_manningsn as rmn\nimport polyadcirc.pyADCIRC.post_management as post\nimport polyadcirc.pyGriddata.file_management as fm\nfrom polyadcirc.pyADCIRC.basic import comm\n\ndef loadmat(save_file, base_dir, grid_dir, save_dir, basis_dir):\n    \"\"\"\n    Loads data from ``save_file`` into a\n    :class:`~polyadcirc.run_framwork.random_manningsn.runSet` object.\n    Reconstructs :class:`~polyadcirc.run_framwork.random_manningsn.subdomain`. \n\n    :param string save_file: local file name\n    :param string grid_dir: directory containing ``fort.14``, ``fort.15``, and\n        ``fort.22`` \n    :param string save_dir: directory where ``RF_directory_*`` are\n        saved, and where fort.13 is located \n    :param string basis_dir: directory where ``landuse_*`` folders are located\n    :param string base_dir: directory that contains ADCIRC executables, and\n        machine specific ``in.prep#`` files \n    :rtype: tuple of :class:`~polyadcirc.run_framwork.random_manningsn.runSet`\n        and :class:`~polyadcirc.run_framwork.random_manningsn.domain` objects\n    :returns: (main_run, domain)\n\n    \"\"\"\n    \n    # the lines below are only necessary if you need to update what the\n    # directories are when swithcing from euclid to your desktop/laptop\n    # assumes that the landuse directory and ADCIRC_landuse directory are in\n    # the same directory\n    domain = subdomain(grid_dir)\n    domain.update()\n    domain.get_Triangulation()\n    #domain.set_station_bathymetry()\n\n    main_run = rmn.runSet(grid_dir, save_dir, basis_dir, base_dir=base_dir)\n    main_run.ts_error = {}\n    main_run.nts_error = {}\n    main_run.time_obs = {}\n\n    # load the data from at *.mat file\n    mdat = sio.loadmat(os.path.join(save_dir, save_file))\n\n    for k, v in mdat.iteritems():\n        skey = k.split('_')\n        if skey[-1] == 'time':\n            # check to see if the key is \"*_time\"\n            main_run.time_obs[skey[0]] = v\n        elif f15.filetype.has_key(skey[0]):\n            if not re.match('fort', skey[0]):\n                # check to see if key is nts_data\n                main_run.nts_error[skey[0]] = v\n            else:\n                # check to see if key is ts_data\n                main_run.ts_error[skey[0]] = v\n        #print k, v\n    \n    return (main_run, domain)\n\nclass subdomain(dom.domain):\n    \"\"\"\n    Objects of this class contain all the data needed by :mod:`py.genbcs`,\n    :mod:`py.genfull`, and :mod:`py.gensub` for a particular subdomain\n    mesh/grid. References to :class:`polyadcirc.run_framework.subdomain` objects\n    are also contained in an instantiation of this class.\n    \"\"\"\n    def __init__(self, path, node_num=0, element_num=0,\n                 node=None, element=None):\n        \"\"\"\n        Initialization\n        \"\"\"\n        super(subdomain, self).__init__(path, node_num, element_num, node,\n                                        element)\n\n        # figure out where the script dir for the ncsu subdomain code is\n        for sys_path in sys.path:\n            potential_file_list = glob.glob(os.path.join(sys_path, 'py'))\n            if potential_file_list:\n                self.script_dir = potential_file_list[0]\n                break\n\n        fm.mkdir(path)\n\n        #: flag for shape of subdomain (0 ellipse, 1 circle)\n        self.flag = None\n\n    def set_fulldomain(self, fulldomain):\n        \"\"\"\n        Sets the fulldomain of this subdomain to fulldomain and adds this\n        subdomain to that fulldomain.\n\n        :type fulldomain: :class:`~polyadcirc.run_framework.fulldomain`\n        :param fulldomain: the fulldomain for this subdomain\n\n        \"\"\"\n        self.fulldomain = fulldomain\n        self.fulldomain.subdomains.append(self)\n\n    def gensub(self, bound_ele=1, bound_vel=1, bound_wd=1, winddir=None):\n        \"\"\"\n        Generate the subdomain input files (``fort.13``, ``fort.14``,\n        ``fort.015``, ``py.141``, ``py.140``) and shape file. Creates\n        ``fort.15`` based on the ``fort.15`` in\n        :class:`polyadcirc.run_framework.fulldomain` to ``self.path``, and\n        creates symbolic links to meterological forcing files (``fort.22*``).\n        \n        :param int bound_ele: a flag determining whether surface elevations of\n            the boundary nodes of a subdomain are enforced using a boundary\n            condition file.\n        :param int bound_vel: a flag determining whether velocities of\n            the boundary nodes of a subdomain are enforced using a boundary\n            condition file.\n        :param int bound_wd: a flag determining whether wet/dry status of\n            the boundary nodes of a subdomain are enforced using a boundary\n            condition file.\n        :rtype: string\n        :returns: command line for invoking gensub.py\n\n        \"\"\"\n        with open(os.path.join(self.path, 'gensub.in'), 'w') as fid:\n            fid.write(str(bound_ele)+'\\n')\n            fid.write(str(bound_vel)+'\\n')\n            fid.write(str(bound_wd)+'\\n')\n        command = 'python '+os.path.join(self.script_dir, 'gensub.py')+' '\n        command += os.path.join(self.fulldomain.path, 'fort.14')\n        command += ' '+str(self.flag)+' fort.14 '\n        \n        if os.path.exists(os.path.join(self.fulldomain.path, 'fort.13')):\n            command += os.path.join(self.fulldomain.path, 'fort.13')+' '\n            command += 'fort.13 ' \n        \n        command += '< gensub.in'\n        subprocess.call(command, shell=True, cwd=self.path)\n\n        #self.update_sub2full_map()\n        self.create_fort15()\n        self.link_fort22(winddir)\n        return command\n\n    def link_fort22(self, fdir=None):\n        \"\"\"\n        Create symboolic links to ``fort.22*`` meterological files in this\n        subdomain folder from the fulldomain folder.\n        \"\"\"\n        if fdir is None:\n            fdir = self.fulldomain.path\n        fort22_files = glob.glob(os.path.join(fdir, 'fort.22*'))\n        for fid in fort22_files:\n            fm.symlink(fid, os.path.join(self.path, fid.rpartition('/')[-1]))\n\n    def genfull(self, noutgs=1, nspoolgs=1):\n        \"\"\" \n        Generate the full domain control file, ``fort.015``, and save it to\n        ``self.fulldomain.path``.\n\n        :param int noutgs: flag controlling whether or not ``fort.06*`` will be\n            written out \n        :param int nspoolgs: the number of timesteps at which information is\n            written to the new output files ``fort.06*``\n        :rtype: string\n        :returns: command line for invoking genfull.py\n        \n        \"\"\"\n        return self.fulldomain.genfull(noutgs, nspoolgs, [self])\n\n    def genbcs(self, forcing_freq=1, dt=None, nspoolgs=1, h0=None, L=False):\n        \"\"\"\n        Generate the ``fort.019`` which is the boundary conditions file needed\n        for a subdomain run of :program:`ADCIRC`. This requires the presence of\n        the output files from a fulldomain run, ``fort.06*``.\n\n        :param int forcing_freq: number of timesteps at which infomration\n            is written to a boudnary conditions file (``fort.019``) THIS MUST\n            BE A MULTIPLE OF NSPOOLGS\n        :param float dt: One timestep in seconds\n        :param int nspoolgs: the number of timesteps at which information is\n            written to the new output files ``fort.06*``\n        :param float h0: minimum water depth for a node to be wet\n        :param bool L: flag whether or not :program:`PADCIRC` was run with\n            ``-L`` flag and if local files need to be post-processed into\n            global files\n        :rtype: string\n        :returns: command line for invoking genbcs.py\n\n        \"\"\"\n        if L:\n            # create post-processing input file\n            post.write_sub(self.fulldomain.path)\n            # run ADCPOST\n            subprocess.call('./adcpost < in.postsub > post_o.txt', shell=True,\n                            cwd=self.fulldomain.path)\n        \n        self.create_fort15()\n        self.link_fort22()\n        self.read_recording_data()\n\n        if self.check_fulldomain():\n            if h0 is None:\n                h0 = self.h0\n            if dt is None:\n                dt = self.fulldomain.time.dt\n            command = \"python \"+self.script_dir+\"/genbcs.py -p \"\n            command += self.fulldomain.path+'/ '+self.path+'/ '\n            command += str(forcing_freq)+' '+str(dt)+' '+str(nspoolgs)\n            command += ' '+str(h0)\n            print command\n            subprocess.call(command, shell=True, cwd=self.path)\n            return command\n        else:\n            print \"Output files from the fulldomain run do not exist\"\n            return \"Output files from the fulldomain run do not exist\"\n\n    def circle(self, x, y, r):\n        \"\"\"\n        Generate a subdomain shape file for a circular subdomain\n\n        :param float x: x coordinate of circle center\n        :param float y: y coordinate of circle center\n        :param float r: radius of circle\n        :rtype: int\n        :returns: flag for :meth:`py.gensub`\n\n        \"\"\"\n        with open(os.path.join(self.path, 'shape.c14'), 'w') as fid:\n            fid.write('{:17.15f} {:17.15f}\\n'.format(x, y))\n            fid.write(str(r))\n        self.flag = 1\n        return self.flag\n\n    def ellipse(self, x, y, w):\n        \"\"\"\n        Generate a subdomain shape file for an elliptical subdomain\n        \n        :param list x: x coordinates of the first and second focal points\n        :param list y: y coordinates of the first and second focal points\n        :param float w: width of ellipse\n        :rtype: int\n        :returns: flag for :meth:`py.gensub`\n\n        \"\"\"\n        with open(os.path.join(self.path, 'shape.e14'), 'w') as fid:\n            fid.write('{:17.15f} {:17.15f}\\n'.format(x[0], y[0]))\n            fid.write('{:17.15f} {:17.15f}\\n'.format(x[1], y[1]))\n            fid.write(str(w))\n        self.flag = 0\n        return self.flag\n\n    def read_circle(self):\n        \"\"\"\n        Read in the parameters used to define the circular subdomain cut out and\n        store them as ``self.x``, ``self.y``, and ``self.r``\n\n        :rtype: tuple\n        :returns: (x, y, r)\n\n        \"\"\"\n        with open(os.path.join(self.path, \"shape.c14\"), \"r\") as fid:\n            t = fid.readline().split()\n            x = float(t[0])\n            y = float(t[1])\n            r = float(fid.readline())\n\n        self.x = x\n        self.y = y\n        self.r = r\n        return (x, y, r)\n\n    def read_ellipse(self):\n        \"\"\"\n        Read in the parameters used to define the circular subdomain cut out and\n        store them as ``self.x``, ``self.y``, and ``self.r``\n\n        :rtype: tuple\n        :returns: (x, y, w)\n\n        \"\"\"\n\n        with open(os.path.join(self.path, \"shape.e14\"), \"r\") as fid:\n            point1 = fid.readline().split()\n            point2 = fid.readline().split()\n            x = [float(point1[0]), float(point2[0])]\n            y = [float(point1[1]), float(point2[1])]\n            w = float(fid.readline())\n            self.x = x\n            self.y = y\n            self.w = w\n        return (x, y, w)\n\n    def ellipse_properties(self, x, y, w):\n        \"\"\"\n        Given a the (x,y) locations of the foci of the ellipse and the width\n        return the center of the ellipse, width, height, and angle relative to\n        the x-axis.\n\n        :param double x: x-coordinates of the foci\n        :param double y: y-coordinates of the foci\n        :param double w: width of the ellipse\n        :rtype: tuple of doubles\n        :returns: (center_coordinates, width, height, angle_in_rads)\n\n        \"\"\"\n        return ellipse_properties(x, y, w)\n\n    def setup(self, flag=None, bound_ele=1, bound_vel=1, bound_wd=1,\n              winddir=None):\n        \"\"\"\n        Generate the subdomain input files (``fort.13``, ``fort.14``,\n        ``fort.015``, ``py.141``, ``py.140``) and shape file. Creates\n        ``fort.15`` based on the ``fort.15`` in\n        :class:`polyadcirc.run_framework.fulldomain` to ``self.path``, and\n        creates symbolic links to meterological forcing files (``fort.22*``).\n        \n        :param int flag: flag determining whether or not the subdomain is an\n            ellipse (0) or a circle (1)\n        :param int bound_ele: a flag determining whether surface elevations of\n            the boundary nodes of a subdomain are enforced using a boundary\n            condition file.\n        :param int bound_vel: a flag determining whether velocities of\n            the boundary nodes of a subdomain are enforced using a boundary\n            condition file.\n        :param int bound_wd: a flag determining whether wet/dry status of\n            the boundary nodes of a subdomain are enforced using a boundary\n            condition file.\n        :rtype: string\n        :returns: command line for invoking gensub.py\n\n        \"\"\"\n        # Appropriately flag subdomain\n        if flag is None and self.flag is None:\n            circle = glob.glob(os.path.join(self.path, 'shape.c14'))\n            if len(circle) > 0:\n                self.flag = 1\n            ellipse = glob.glob(os.path.join(self.path, 'shape.e14'))\n            if len(ellipse) > 0:\n                self.flag = 0\n        elif flag != None:\n            self.flag = flag #: flag for :meth:`py.gensub`\n        # Get rid of old files\n        f_list = ['fort.015', 'fort.13', 'fort.14', 'bv.nodes', 'py.140',\n                  'py.141']\n        for fid in f_list:\n            if os.path.exists(os.path.join(self.path, fid)):\n                os.remove(os.path.join(self.path, fid))\n        return self.gensub(bound_ele, bound_vel, bound_wd, winddir)\n        \n    def check_fulldomain(self):\n        \"\"\"\n        Check to see if the ``fort.06*`` and ``PE*/fort.065`` files exist\n\n        :rtype: bool\n        :returns: False if the ``fort.06*`` files don't exist\n        \n        \"\"\"\n        return self.fulldomain.check_fulldomain()\n\n    def check(self):\n        \"\"\"\n        Check to make sure the ``fort.019`` file exists\n\n        :rtype: bool\n        :returns: False the ``fort.019`` doesn't exist\n\n        \"\"\"\n        fort019 = glob.glob(os.path.join(self.path, 'fort.019'))\n        return len(fort019) > 0\n\n    def compare_runSet(self, ts_data, nts_data, ts_names=None, \n                       nts_names=None, save_file=None): \n        \"\"\"\n        Reads in :class:`polyadcirc.random_manningsn.runSet` output from this\n        subdomain and from it's fulldomain and compares them.\n\n        NOTE THIS DOES NOT CURRENTLY WORK FOR STATION DATA! ONLY USE FOR GLOBAL\n        DATA i.e files that are fort.*3 or fort.*4\n\n        comparision_data = fulldomain_data - subdomain_data\n        \n        :param list ts_data: (ts_data_subdomain, ts_data_fulldomain)\n        :param list nts_data: (nts_data_subdomain, nts_data_fulldomain)\n        :param list ts_names: names of ADCIRC timeseries\n            output files to be recorded from each run\n        :param list nts_names: names of ADCIRC non timeseries\n            output files to be recorded from each run\n        :param string save_file: name of file to save comparision matricies to\n        :rtype: tuple\n        :returns: (ts_error, nts_error)\n\n        \"\"\"\n        \n        if save_file is None:\n            save_file = os.path.join(self.path, 'compare_s2f_runSet.mat')\n\n        nts_keys = []\n        if nts_names is None:\n            nts_keys = nts_data[0].keys()\n        else:\n            for fid in nts_names:\n                nts_keys.append(fid.replace('.', ''))\n\n        ts_keys = []\n        if ts_names is None:\n            ts_keys = ts_data[0].keys()\n        else:\n            for fid in ts_names:\n                ts_keys.append(fid.replace('.', ''))\n\n        # Save matricies to *.mat file for use by MATLAB or Python\n        mdict = dict()\n\n        # Pre-allocate arrays for non-timeseries data\n        nts_error = {}\n        ts_error = {}\n\n        fulldom_nodes = [v-1 for v in self.sub2full_node.values()]\n\n        # Get nts_error\n        for key in nts_keys:\n            full_data = nts_data[1][key][fulldom_nodes]\n            sub_data = nts_data[0][key]\n            nts_error[key] = (full_data - sub_data)#/full_data\n\n        # fix dry nodes\n        if 'fort63' in ts_keys:\n            ts_data[0] = rmn.fix_dry_nodes(ts_data[0], self)\n            ts_data[1] = rmn.fix_dry_nodes(ts_data[1], self)\n\n        # fix dry data\n        if 'fort61' in ts_keys:\n            self.set_station_bathymetry()\n            ts_data[0] = rmn.fix_dry_data(ts_data[0], self)\n            ts_data[1] = rmn.fix_dry_data(ts_data[1], self)\n\n        # Get ts_data\n        for key in ts_keys:\n            # Theres a bug wrt stations here either we need a mapping between\n            # fulldomain stations and subdomain stations or these stations MUST\n            # be the same.\n            if key == 'fort61' or key == 'fort62':\n                continue\n            sub_data = ts_data[0][key]\n            total_obs = sub_data.shape[1]\n            if self.recording[key][2] == 1:\n                full_data = ts_data[1][key][fulldom_nodes, 0:total_obs]\n            else:\n                full_data = ts_data[1][key][fulldom_nodes, 0:total_obs, :]\n            ts_error[key] = (full_data - sub_data)#/full_data\n\n        # Update and save\n        # export nontimeseries data\n        for k, v in nts_error.iteritems():\n            mdict[k] = v\n            print k\n            b = np.ma.fix_invalid(v, fill_value=0)\n            print np.max(abs(b)), np.argmax(abs(b))\n        # export timeseries data\n        for k, v in ts_error.iteritems():\n            mdict[k] = v\n            print k\n            b = np.ma.fix_invalid(v, fill_value=0)\n            print np.max(abs(b)), np.argmax(abs(b))\n\n        sio.savemat(save_file, mdict, do_compression=True)\n        return (ts_error, nts_error)\n    \n    def compare_to_fulldomain(self, ts_names, nts_names, save_file=None,\n                              timesteps=None, savefull=True, readmatfull=False,\n                              savesub=True, readmatsub=False, fulldict=None):\n        \"\"\"\n        Reads in output files from this subdomain and from it's fulldomain and\n        compares them.\n\n        NOTE THIS DOES NOT CURRENTLY WORK FOR STATION DATA! ONLY USE FOR GLOBAL\n        DATA i.e files that are fort.*3 or fort.*4\n\n        NOTE THIS DOES NOT CURRENTLY WORK FOR ANY NTS DATA EXCEPT FOR MAXELE\n\n        comparision_data = fulldomain_data - subdomain_data\n\n        :param list ts_names: names of ADCIRC timeseries\n            output files to be recorded from each run\n        :param list nts_names: names of ADCIRC non timeseries\n            output files to be recorded from each run\n        :param string save_file: name of file to save comparision matricies to\n        :param int timesteps: number of timesteps to read from file\n        :rtype: tuple\n        :returns: (ts_error, nts_error, time_obs, ts_data, nts_data)\n\n        \"\"\"\n        \n        if save_file is None:\n            save_file = os.path.join(self.path, 'compare_s2f.mat')\n\n        full_file = os.path.join(self.fulldomain.path, 'full.mat')\n        sub_file = os.path.join(self.path, 'sub.mat')\n\n        # Save matricies to *.mat file for use by MATLAB or Python\n        mdict = dict()\n        if readmatsub:\n            subdict = sio.loadmat(sub_file)\n            savesub = False\n        else:\n            subdict = dict()\n\n        if fulldict is None:\n            if readmatfull:\n                fulldict = sio.loadmat(full_file)\n                savefull = False\n            else:\n                fulldict = dict()\n        else:\n            readmatfull = True\n            savefull = False\n\n        # Pre-allocate arrays for non-timeseries data\n        nts_error = {}\n        ts_error = {}\n        time_obs = {}\n\n        fulldom_nodes = [v-1 for v in self.sub2full_node.values()]\n\n        # Get nts_data\n        for fid in nts_names:\n            key = fid.replace('.', '')\n            if not readmatfull:\n                fulldict[key] = output.get_nts_sr(self.fulldomain.path,\n                                                  self.fulldomain, fid)\n            if not readmatsub:\n                subdict[key] = output.get_nts_sr(self.path, self, fid)\n\n        # Get ts_data\n        for fid in ts_names:\n            key = fid.replace('.', '')\n            if not readmatsub:\n                subdict[key], time_obs[key] = output.get_ts_sr(self.path, fid,\n                                                               True,\n                                                               ihot=self.ihot) \n                subdict[key+'_time'] = time_obs[key]\n            if not readmatfull:\n                fulldict[key] = output.get_ts_sr(self.fulldomain.path,\n                                                 fid, timesteps=timesteps,\n                                                 ihot=self.fulldomain.ihot)[0]\n       \n        if not readmatsub:\n            # fix dry nodes\n            if subdict.has_key('fort63'):\n                subdict['fort63'] = np.expand_dims(subdict['fort63'], axis=2)\n                subdict = rmn.fix_dry_nodes(subdict, self)\n                subdict['fort63'] = np.squeeze(subdict['fort63'])\n            # fix dry data\n            if subdict.has_key('fort61'):\n                subdict['fort61'] = np.expand_dims(subdict['fort61'], axis=1)\n                subdict = rmn.fix_dry_data(subdict, self)\n                subdict['fort61'] = np.squeeze(subdict['fort61'])\n            # fix dry nodes nts\n            if subdict.has_key('maxele63'):\n                subdict['maxele63'] = np.expand_dims(subdict['maxele63'],\n                                                     axis=1) \n                subdict = rmn.fix_dry_nodes_nts(subdict, self)\n                subdict['maxele63'] = np.squeeze(subdict['maxele63'])\n\n\n        if not readmatfull:\n            # fix dry nodes\n            if fulldict.has_key('fort63'):\n                fulldict['fort63'] = np.expand_dims(fulldict['fort63'], axis=2)\n                fulldict = rmn.fix_dry_nodes(fulldict, self)\n                fulldict['fort63'] = np.squeeze(fulldict['fort63'])\n            # fix dry data\n            if fulldict.has_key('fort61'):\n                fulldict['fort61'] = np.expand_dims(fulldict['fort61'], axis=1)\n                fulldict = rmn.fix_dry_data(fulldict, self)\n                fulldict['fort61'] = np.squeeze(fulldict['fort61'])\n            # fix dry nodes nts\n            if fulldict.has_key('maxele63'):\n                fulldict['maxele63'] = np.expand_dims(fulldict['maxele63'], \n                                                      axis=1)\n                fulldict = rmn.fix_dry_nodes_nts(fulldict, self)\n                fulldict['maxele63'] = np.squeeze(fulldict['maxele63'])\n    \n        # Get ts_error\n        for fid in ts_names:\n            key = fid.replace('.', '')\n            sub_data, time_obs[key] = subdict[key], subdict[key+'_time']\n            total_obs = sub_data.shape[1]\n            if timesteps and timesteps < total_obs:\n                total_obs = timesteps\n            full_data = fulldict[key]\n            if self.recording[key][2] == 1:\n                full_data = full_data[fulldom_nodes, 0:total_obs] \n            else:\n                full_data = full_data[fulldom_nodes, 0:total_obs, :]\n            ts_error[key] = (full_data - sub_data)\n            if key == 'fort63' and (subdict.has_key('maxele63') or\\\n                    subdict.has_key('maxele.63')):\n                nts_error['maxele63'] = np.max(full_data,\n                                               axis=1) - subdict['maxele63']\n            if key == 'fort64' and (subdict.has_key('maxvel63') or\\\n                    subdict.has_key('maxvel.63')):\n                nts_error['maxvel63'] = np.max(np.sqrt(full_data[:, :, 0]**2 +\n                                                       full_data[:, :, 1]**2), \n                                               axis=1) - subdict['maxvel63']\n        \n        # Get nts_error\n        for fid in nts_names:\n            key = fid.replace('.', '')\n            if key != 'maxele63' and key != 'maxevel63':\n                nts_error[key] = fulldict[key][fulldom_nodes] - subdict[key]\n        \n        # Update and save\n        # export nontimeseries data\n        for k, v in nts_error.iteritems():\n            mdict[k] = v\n            print k\n            #b = np.ma.fix_invalid(v, fill_value=0)\n            b = v\n            print np.max(abs(b)), np.argmax(abs(b))\n            print \"Nodes above threshold\", sum(np.abs(b) > 1e-2)\n        # export timeseries data\n        for k, v in ts_error.iteritems():\n            mdict[k] = v\n            print k\n            #b = np.ma.fix_invalid(v, fill_value=0)\n            b = v\n            print np.max(abs(b)), np.argmax(abs(b))\n            print \"Nodes above threshold\", sum(np.abs(b) > 1e-2)\n\n        # export time_obs data\n        for k, v in time_obs.iteritems():\n            mdict[k+'_time'] = v\n\n        sio.savemat(save_file, mdict, do_compression=True)\n        if savesub:\n            sio.savemat(sub_file, subdict, do_compression=True)\n        if savefull:\n            sio.savemat(full_file, fulldict, do_compression=True)\n\n        return (ts_error, nts_error, time_obs, None, None)\n\n    def create_fort15(self):\n        \"\"\"\n        Copy the ``fort.15`` from ``fulldomain.path`` to ``self.path`` and\n        modify for a subdomain run.\n\n        .. seealso:: :meth:`polyadcirc.pyADCIRC.fort15_management.subdomain`\n        \"\"\"\n\n        f15.subdomain(self.fulldomain.path, self.path)\n\n    def read_py_node(self):\n        \"\"\"\n        Read in the subdomain to fulldomain node map\n        \n        Store as ::\n            \n            self.sub2full_node = dict()\n        \n        where key = subdomain node #, value = fulldomain node #\n        \"\"\"\n        self.sub2full_node = {}\n        with open(os.path.join(self.path, 'py.140'), 'r') as fid:\n            fid.readline() # skip header\n            for line in fid:\n                k, v = np.fromstring(line, dtype=int, sep=' ')\n                self.sub2full_node[k] = v\n\n    def read_py_ele(self):\n        \"\"\"\n        Read in the subdomain to fulldomain element map\n        \n        Store as ::\n            \n            self.sub2full_element = dict()\n        \n        where key = subdomain element #, value = fulldomain element #\n        \"\"\"\n        self.sub2full_element = {}\n        with open(os.path.join(self.path, 'py.141'), 'r') as fid:\n            fid.readline() # skip header\n            for line in fid:\n                k, v = np.fromstring(line, dtype=int, sep=' ')\n                self.sub2full_element[k] = v\n\n    def read_bv_nodes(self):\n        \"\"\"\n        Read in the nodes on the boundary and store in ``self.bv_nodes`` as a\n        list.\n\n        :rtype: list\n        :returns: list of boundary nodes\n        \"\"\"\n        self.bv_nodes = []\n        with open(os.path.join(self.path, 'bv.nodes'), 'r') as fid:\n            for line in fid:\n                self.bv_nodes.append(int(np.fromstring(line, sep=' ')[0]))\n        return self.bv_nodes\n\n    def update_sub2full_map(self):\n        \"\"\"\n        Read in the subdomain to fulldomain element and node maps\n        \"\"\"\n        #: dict where key = subdomain node #, value = fulldomain node #\n        self.read_py_node()\n        #: dict where key = subdomain element #, value = fulldomain element #\n        self.read_py_ele()\n        #: list of boundary nodes\n        self.read_bv_fort13()\n\n    def trim_fort13(self, old_fort13, new_fort13):\n        \"\"\"\n        Trim ``old_fort13`` to match the nodes in this subdomain and save as\n        ``new_fort13``. This only assumes that a ``py.140`` file exists.\n\n        :param string old_fort13: path to the old ``fort.13`` file to be\n            trimmed\n        :param string new_fort13: path to save the new ``fort.13`` file\n        \"\"\"\n        trim_fort13(old_fort13, new_fort13, os.path.join(self.path, 'py.140'))\n\n    def trim_multiple_fort13(self, old_fort13, new_fort13):\n        \"\"\"\n        Trim ``old_fort13`` to match the nodes in this subdomain and save as\n        ``new_fort13``. This only assumes that a ``py.140`` file exists.\n\n        :param string old_fort13: path to the old ``fort.13`` file to be\n            trimmed\n        :param string new_fort13: path to save the new ``fort.13`` file\n        \"\"\"\n        trim_multiple_fort13(old_fort13, new_fort13, os.path.join(self.path,\n                                                                  'py.140'))\n\n    def read_bv_fort13(self):\n        \"\"\"\n        Read the boundary value nodal values for Manning's n from\n        ``self.fulldomain`` and save as a ``dict`` as ``self.bv_fort13``.\n        \"\"\"\n        self.read_bv_nodes()\n        self.bv_fort13 = f13.read_nodal_attr(self, self.path,\n                                             nums=self.bv_nodes)\n\n    def set_bv_fort13(self, mann_data):\n        \"\"\"\n        Replace the boundary nodal values with the boundary nodal values in the\n        fulldomain.\n\n        :type mann_data: :class:`numpy.ndarray` or :class:`dict`\n        :param mann_data: containing the nodal attribute information\n        \n        :rtype: :class:`numpy.ndarray` or :class:`dict`\n        :returns: dictionary or array of nodal values\n\n        \"\"\"\n        if isinstance(mann_data, dict):\n            for k, v in self.bv_fort13.iteritems():\n                mann_data[k] = v\n        else:\n            for k, v in self.bv_fort13.iteritems():\n                mann_data[k-1] = v\n        return mann_data\n\n    def update_mann(self, data, path=None, default=None, file_name='fort.13'):\n        \"\"\"\n        Write out fort.13 to path with the attributes contained in Data.  \n\n        :type data: :class:`numpy.ndarray` or :class:`dict`\n        :param data: containing the nodal attribute information\n        :type path: string or None\n        :param path: the directory to which the fort.13 file will be written\n        :type default: None or float\n        :param default: default value\n        :type file_name: string\n        :param file_name: the name of the ``fort.13`` formatted file\n\n        \"\"\"\n        data = self.set_bv_fort13(data)\n        f13.update_mann(data, path, default, file_name)\n\n\ndef trim_fort13(old_fort13, new_fort13, pynode_map):\n    \"\"\"\n    Trim ``old_fort13`` to match the nodes in this subdomain and save as\n    ``new_fort13``. This only assumes that a ``py.140`` file exists.\n\n    :param string old_fort13: path to the old ``fort.13`` file to be\n        trimmed\n    :param string new_fort13: path to save the new ``fort.13`` file\n    \"\"\"\n    print pynode_map\n    gensub.main13(None, old_fort13, new_fort13, pynode_map)\n\ndef trim_multiple_fort13(old_fort13, new_fort13, pynode_map):\n    \"\"\"\n    Trim ``old_fort13`` to match the nodes in this subdomain and save as\n    ``new_fort13``. This only assumes that a ``py.140`` file exists.\n\n    :param string old_fort13: path to the old ``fort.13`` file to be\n        trimmed\n    :param string new_fort13: path to save the new ``fort.13`` file\n    \"\"\"\n    size = comm.Get_size()\n    rank = comm.Get_rank()\n\n    print \"len old, len new\", len(old_fort13), len(new_fort13)\n\n    for i in range(0+rank, len(old_fort13), size):\n        if not os.path.exists(os.path.dirname(new_fort13[i])):\n            os.makedirs(os.path.dirname(new_fort13[i]))\n        trim_fort13(old_fort13[i], new_fort13[i], pynode_map)\n\ndef ellipse_properties(x, y, w):\n    \"\"\"\n    Given a the (x,y) locations of the foci of the ellipse and the width return\n    the center of the ellipse, width, height, and angle relative to the x-axis.\n\n    :param double x: x-coordinates of the foci\n    :param double y: y-coordinates of the foci\n    :param double w: width of the ellipse\n    :rtype: tuple of doubles\n    :returns: (center_coordinates, width, height, angle_in_rads)\n\n    \"\"\"\n    p1 = [x[0], y[0]]\n    p2 = [x[1], y[1]]\n    \n    #center point\n    xy = [(p1[0] + p2[0])/2, (p1[1] + p2[1])/2]\t\t\n    #distance between points\n    d = ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)**(0.5)\t\n    #theta to positive Xaxis\n    angle = math.atan((p1[1] - p2[1])/(p1[0] - p2[0])) \n    #sin = math.sin(-angle)\n    #cos = math.cos(-angle)\n    #width will be the axis the points lie on\n    width = 2*((0.5*d)**2 + (0.5*w)**2)**(0.5) \t\t\n    height = w\n\n    return (xy, width, height, angle*180/math.pi)\n\n", "meta": {"hexsha": "c74c4344c8cb6c21fff53be55fe738f32b7a02b7", "size": 32711, "ext": "py", "lang": "Python", "max_stars_repo_path": "polyadcirc/run_framework/subdomain.py", "max_stars_repo_name": "tmiesse/PolyADCIRC", "max_stars_repo_head_hexsha": "a4a31dda2c2dac4cd696c0f3827dbbcea7feab33", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2016-03-04T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T15:39:25.000Z", "max_issues_repo_path": "polyadcirc/run_framework/subdomain.py", "max_issues_repo_name": "tmiesse/PolyADCIRC", "max_issues_repo_head_hexsha": "a4a31dda2c2dac4cd696c0f3827dbbcea7feab33", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2015-04-28T05:14:28.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-19T12:54:59.000Z", "max_forks_repo_path": "polyadcirc/run_framework/subdomain.py", "max_forks_repo_name": "UT-CHG/PolyADCIRC", "max_forks_repo_head_hexsha": "a4a31dda2c2dac4cd696c0f3827dbbcea7feab33", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2016-01-20T00:34:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T11:00:56.000Z", "avg_line_length": 38.3481828839, "max_line_length": 80, "alphanum_fraction": 0.5719177035, "include": true, "reason": "import numpy,import scipy", "num_tokens": 8255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.1973448446340028}}
{"text": "# The MIT License (MIT)\n# Copyright (c) 2016, 2017 by the ESA CCI Toolbox development team and contributors\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n# of the Software, and to permit persons to whom the Software is furnished to do\n# so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"\nDescription\n===========\n\nThis module provides aggregation operations\n\nComponents\n==========\n\"\"\"\nfrom datetime import timezone\n\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\nfrom xarray.core.resample import DatasetResample as resampler\n\nfrom cate.core.op import op, op_input, op_return\nfrom cate.core.types import VarNamesLike, DatasetLike, ValidationError, DimNamesLike\nfrom cate.ops.normalize import adjust_temporal_attrs\nfrom cate.ops.select import select_var\nfrom cate.util.monitor import Monitor\n\n\n@op(tags=['aggregate', 'temporal'], version='1.5')\n@op_input('ds', data_type=DatasetLike)\n@op_input('var', value_set_source='ds', data_type=VarNamesLike)\n@op_return(add_history=True)\ndef long_term_average(ds: DatasetLike.TYPE,\n                      var: VarNamesLike.TYPE = None,\n                      monitor: Monitor = Monitor.NONE) -> xr.Dataset:\n    \"\"\"\n    Create a 'mean over years' dataset by averaging the values of the given input\n    dataset over all years. The output is a climatological dataset with the same\n    resolution as the input dataset. E.g. a daily input dataset will create a daily\n    climatology consisting of 365 days, a monthly input dataset will create a monthly\n    climatology, etc.\n\n    Seasonal input datasets must have matching seasons over all years denoted by the\n    same date each year. E.g., first date of each quarter. The output dataset will\n    then be a seasonal climatology where each season is denoted with the same date\n    as in the input dataset.\n\n    For further information on climatological datasets, see\n    http://cfconventions.org/cf-conventions/v1.6.0/cf-conventions.html#climatological-statistics\n\n    :param ds: A dataset to average\n    :param var: If given, only these variables will be preserved in the resulting dataset\n    :param monitor: A progress monitor\n    :return: A climatological long term average dataset\n    \"\"\"\n    ds = DatasetLike.convert(ds)\n    # Check if time dtype is what we want\n    if 'datetime64[ns]' != ds.time.dtype:\n        raise ValidationError('Long term average operation expects a dataset with the'\n                              ' time coordinate of type datetime64[ns], but received'\n                              ' {}. Running the normalize operation on this'\n                              ' dataset may help'.format(ds.time.dtype))\n\n    try:\n        t_resolution = ds.attrs['time_coverage_resolution']\n    except KeyError:\n        raise ValidationError('Could not determine temporal resolution. Running'\n                              ' the adjust_temporal_attrs operation beforehand may'\n                              ' help.')\n\n    var = VarNamesLike.convert(var)\n    # Shallow\n\n    if var:\n        ds = select_var(ds, var)\n\n    if t_resolution == 'P1D':\n        return _lta_daily(ds)\n    elif t_resolution == 'P1M':\n        return _lta_monthly(ds, monitor)\n    else:\n        return _lta_general(ds, monitor)\n\n\ndef _lta_monthly(ds: xr.Dataset, monitor: Monitor):\n    \"\"\"\n    Carry out a long term average on a monthly dataset\n\n    :param ds: Dataset to aggregate\n    :param monitor: Progress monitor\n    :return: Aggregated dataset\n    \"\"\"\n    time_min = pd.Timestamp(ds.time.values[0], tzinfo=timezone.utc)\n    time_max = pd.Timestamp(ds.time.values[-1], tzinfo=timezone.utc)\n    total_work = 100\n    retset = ds\n\n    with monitor.starting('LTA', total_work=total_work):\n        monitor.progress(work=0)\n        step = total_work / 12\n        kwargs = {'monitor': monitor, 'step': step}\n        retset = retset.groupby('time.month', squeeze=False).apply(_mean, **kwargs)\n\n    # Make the return dataset CF compliant\n    retset = retset.rename({'month': 'time'})\n    retset['time'] = pd.date_range('{}-01-01'.format(time_min.year),\n                                   freq='MS',\n                                   periods=12)\n\n    climatology_bounds = xr.DataArray(data=np.tile([time_min, time_max],\n                                                   (12, 1)),\n                                      dims=['time', 'nv'],\n                                      name='climatology_bounds')\n    retset['climatology_bounds'] = climatology_bounds\n    retset.time.attrs = ds.time.attrs\n    retset.time.attrs['climatology'] = 'climatology_bounds'\n\n    for var in retset.data_vars:\n        try:\n            retset[var].attrs['cell_methods'] = \\\n                retset[var].attrs['cell_methods'] + ' time: mean over years'\n        except KeyError:\n            retset[var].attrs['cell_methods'] = 'time: mean over years'\n\n    return retset\n\n\ndef _groupby_day(ds: xr.Dataset, monitor: Monitor, step: float):\n    \"\"\"\n    Groupby the given dataset by day of month and apply mean to it\n\n    :param ds: Dataset to aggregate\n    :param monitor: Progress monitor\n    :param step: Progress step\n    \"\"\"\n    kwargs = {'monitor': monitor, 'step': step}\n    return ds.groupby('time.day', squeeze=False).apply(_mean, **kwargs)\n\n\ndef _lta_daily(ds: xr.Dataset):\n    \"\"\"\n    Carry out a long term average of a daily dataset\n\n    :param ds: Dataset to aggregate\n    :return: Aggregated dataset\n    \"\"\"\n\n    retset = ds.groupby('time.dayofyear', squeeze=False).mean('time')\n\n    for var in retset.data_vars:\n        try:\n            retset[var].attrs['cell_methods'] = \\\n                retset[var].attrs['cell_methods'] + ' time: mean over years'\n        except KeyError:\n            retset[var].attrs['cell_methods'] = 'time: mean over years'\n\n    return retset\n\n\ndef _lta_general(ds: xr.Dataset, monitor: Monitor):\n    \"\"\"\n    Try to carry out a long term average in a general case, notably\n    in the case of having seasonal datasets\n\n    :param ds: Dataset to aggregate\n    :param monitor: Progress monitor\n    :return: Aggregated dataset\n    \"\"\"\n    time_min = pd.Timestamp(ds.time.values[0], tzinfo=timezone.utc)\n    time_max = pd.Timestamp(ds.time.values[-1], tzinfo=timezone.utc)\n    total_work = 100\n    retset = ds\n\n    # The dataset should feature time periods consistent over years\n    # and denoted with the same dates each year\n    if not _is_seasonal(ds.time):\n        raise ValidationError(\"A long term average dataset can not be created for\"\n                              \" a dataset with inconsistent seasons.\")\n\n    # Get 'representative year'\n    c = 0\n    for group in ds.time.groupby('time.year'):\n        c = c + 1\n        if c == 1:\n            rep_year = group[1].time\n            continue\n        if c == 2 and len(group[1].time) > len(rep_year):\n            rep_year = group[1].time\n            break\n\n    with monitor.starting('LTA', total_work=total_work):\n        monitor.progress(work=0)\n        step = total_work / len(rep_year.time)\n        kwargs = {'monitor': monitor, 'step': step}\n        retset = retset.groupby('time.month', squeeze=False).apply(_groupby_day, **kwargs)\n\n    # Make the return dataset CF compliant\n    retset = retset.stack(time=('month', 'day'))\n\n    # Turn month, day coordinates to time\n    retset = retset.reset_index('time')\n    retset = retset.drop(['month', 'day'])\n    retset['time'] = rep_year.time\n\n    climatology_bounds = xr.DataArray(data=np.tile([time_min, time_max],\n                                                   (len(rep_year), 1)),\n                                      dims=['time', 'nv'],\n                                      name='climatology_bounds')\n    retset['climatology_bounds'] = climatology_bounds\n    retset.time.attrs = ds.time.attrs\n    retset.time.attrs['climatology'] = 'climatology_bounds'\n\n    for var in retset.data_vars:\n        try:\n            retset[var].attrs['cell_methods'] = \\\n                retset[var].attrs['cell_methods'] + ' time: mean over years'\n        except KeyError:\n            retset[var].attrs['cell_methods'] = 'time: mean over years'\n\n    return retset\n\n\ndef _is_seasonal(time: xr.DataArray):\n    \"\"\"\n    Check if the given timestamp dataarray features consistent\n    seasons. E.g. Each year has the same date-month values in it.\n    \"\"\"\n    c = 0\n    test = None\n    for group in time.groupby('time.year'):\n        # Test (month, day) dates of all years against\n        # (month, day) dates of the first year, or second\n        # year in case the first year is not full\n        c = c + 1\n        np_time = group[1].time.values\n        months = pd.DatetimeIndex(np_time).month\n        days = pd.DatetimeIndex(np_time).day\n        if c == 1:\n            first_months = months\n            first_days = days\n            continue\n        elif c == 2:\n            second_months = months\n            second_days = days\n            if len(second_months) > len(first_months):\n                test = list(zip(second_months, second_days))\n                for date in zip(first_months, first_days):\n                    if date not in test:\n                        return False\n            else:\n                test = list(zip(first_months, first_days))\n                for date in zip(second_months, second_days):\n                    if date not in test:\n                        return False\n            continue\n\n        for date in zip(months, days):\n            if date not in test:\n                return False\n\n    return True\n\n\ndef _mean(ds: xr.Dataset, monitor: Monitor, step: float):\n    \"\"\"\n    Calculate mean of the given dataset and update the given monitor.\n\n    :param ds: Dataset to take the mean of\n    :param monitor: Monitor to update\n    :param step: Work step\n    \"\"\"\n    retset = ds.mean(dim='time', keep_attrs=True)\n    monitor.progress(work=step)\n    return retset\n\n\n@op(tags=['aggregate', 'temporal'], version='1.5')\n@op_input('ds', data_type=DatasetLike)\n@op_input('method', value_set=['mean', 'max', 'median', 'prod', 'sum', 'std',\n                               'var', 'argmax', 'argmin', 'first', 'last'])\n@op_input('output_resolution', value_set=['month', 'season'])\n@op_return(add_history=True)\ndef temporal_aggregation(ds: DatasetLike.TYPE,\n                         method: str = 'mean',\n                         output_resolution: str = 'month',\n                         custom_resolution: str = None,\n                         monitor: Monitor = Monitor.NONE) -> xr.Dataset:\n    \"\"\"\n    Perform aggregation of dataset according to the given\n    method and output resolution.\n\n    Note that the operation does not perform weighting. Depending on the\n    combination of input and output resolutions, as well as aggregation\n    method, the resulting dataset might yield unexpected results.\n\n    Resolution 'month' will result in a monthly dataset with each month\n    denoted by its first date. Resolution 'season' will result in a dataset\n    aggregated to DJF, MAM, JJA, SON seasons, each denoted by the first\n    date of the season.\n\n    The operation also works with custom resolution strings, see:\n    http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases\n    If ``custom_resolution`` is provided, it will override ``output_resolution``.\n\n    Some examples:\n      'QS-JUN' produces an output dataset on a quarterly resolution where the\n      year ends in 1st of June and each quarter is denoted by its first date\n      '8MS' produces an output dataset on an eight-month resolution where each\n      period is denoted by the first date. Note that such periods will not be\n      consistent over years.\n      '8D' produces a dataset on an eight day resolution\n\n    :param ds: Dataset to aggregate\n    :param method: Aggregation method\n    :param output_resolution: Desired temporal resolution of the output dataset\n    :param custom_resolution: Custom temporal resolution, overrides output_resolution\n    :return: Aggregated dataset\n    \"\"\"\n    ds = DatasetLike.convert(ds)\n    # Check if time dtype is what we want\n    if 'datetime64[ns]' != ds.time.dtype:\n        raise ValidationError('Temporal aggregation operation expects a dataset with the'\n                              ' time coordinate of type datetime64[ns], but received'\n                              ' {}. Running the normalize operation on this'\n                              ' dataset may help'.format(ds.time.dtype))\n\n    # Try to figure out the input frequency\n    try:\n        in_freq = ds.attrs['time_coverage_resolution']\n    except KeyError:\n        raise ValidationError('Could not determine temporal resolution of input dataset.'\n                              ' Running the adjust_temporal_attrs operation beforehand may'\n                              ' help.')\n\n    if custom_resolution:\n        freq = custom_resolution\n    else:\n        frequencies = {'month': 'MS', 'season': 'QS-DEC'}\n        freq = frequencies[output_resolution]\n\n    _validate_freq(in_freq, freq)\n\n    with monitor.observing(\"resample dataset\"):\n        try:\n            retset = getattr(resampler, method)(ds.resample(time=freq, keep_attrs=True))\n        except AttributeError:\n            raise ValidationError(f'Provided aggregation method {method} is not valid.')\n\n    for var in retset.data_vars:\n        try:\n            retset[var].attrs['cell_methods'] = \\\n                retset[var].attrs['cell_methods'] + \\\n                ' time: {} within years'.format(method)\n        except KeyError:\n            retset[var].attrs['cell_methods'] = 'time: {} within years'.format(method)\n\n    return adjust_temporal_attrs(retset)\n\n\ndef _validate_freq(in_res: str, out_res: str) -> None:\n    \"\"\"\n    Validate the aggregation step\n\n    See also: `ISO 8601 Durations <https://en.wikipedia.org/wiki/ISO_8601#Durations>`_\n    \"\"\"\n    # Validate output frequency as a valid offset string\n    try:\n        dates = pd.date_range('2000-01-01', periods=5, freq=out_res)\n    except ValueError:\n        raise ValidationError('Invalid custom resolution: {}.'\n                              ' Please check operation documentation.'.format(out_res))\n\n    # Assuming simple ISO_8601 periods: PXXD/M\n    try:\n        count = int(in_res[1:-1])\n    except ValueError:\n        raise ValidationError('Could not interpret time coverage resolution of'\n                              ' the given dataset: {}'.format(in_res))\n\n    if in_res == 'P1M' and out_res == 'MS':\n        raise ValidationError('Input dataset is already at the requested output resolution.'\n                              ' Execution stopped.')\n\n    in_delta = pd.Timedelta(count, unit=in_res[-1])\n    out_delta = dates[1] - dates[0]\n\n    if out_delta < in_delta:\n        raise ValidationError('Requested output resolution is smaller than dataset resolution.'\n                              ' This operation only performs aggregation to larger resolutions.')\n    elif out_delta == in_delta:\n        raise ValidationError('Input dataset is already at the requested output resolution.'\n                              'Execution stopped.')\n\n    return\n\n\n@op(tags=['aggregate'], version='1.0')\n@op_input('ds', data_type=DatasetLike)\n@op_input('var', value_set_source='ds', data_type=VarNamesLike)\n@op_input('dim', value_set_source='ds', data_type=DimNamesLike)\n@op_input('method', value_set=['mean', 'min', 'max', 'sum', 'median'])\n@op_return(add_history=True)\ndef reduce(ds: DatasetLike.TYPE,\n           var: VarNamesLike.TYPE = None,\n           dim: DimNamesLike.TYPE = None,\n           method: str = 'mean',\n           monitor: Monitor = Monitor.NONE) -> xr.Dataset:\n    \"\"\"\n    Reduce the given variables of the given dataset along the given dimensions.\n    If no variables are given, all variables of the dataset will be reduced. If\n    no dimensions are given, all dimensions will be reduced. If no variables\n    have been given explicitly, it can be set that only variables featuring numeric\n    values should be reduced.\n\n    :param ds: Dataset to reduce\n    :param var: Variables in the dataset to reduce\n    :param dim: Dataset dimensions along which to reduce\n    :param method: reduction method\n    :param monitor: A progress monitor\n    \"\"\"\n    ufuncs = {'min': np.nanmin, 'max': np.nanmax, 'mean': np.nanmean,\n              'median': np.nanmedian, 'sum': np.nansum}\n\n    ds = DatasetLike.convert(ds)\n\n    if not var:\n        var = list(ds.data_vars.keys())\n    var_names = VarNamesLike.convert(var)\n\n    if not dim:\n        dim = list(ds.coords.keys())\n    else:\n        dim = DimNamesLike.convert(dim)\n\n    retset = ds.copy()\n\n    for var_name in var_names:\n        intersection = [value for value in dim if value in retset[var_name].dims]\n        with monitor.starting(\"Reduce dataset\", total_work=100):\n            monitor.progress(5)\n            with monitor.child(95).observing(\"Reduce\"):\n                retset[var_name] = retset[var_name].reduce(ufuncs[method],\n                                                           dim=intersection,\n                                                           keep_attrs=True)\n\n    return retset\n", "meta": {"hexsha": "e2cd1d663d65800d833f73420defa50eaf066fa9", "size": 17848, "ext": "py", "lang": "Python", "max_stars_repo_path": "cate/ops/aggregate.py", "max_stars_repo_name": "pwambach/cate", "max_stars_repo_head_hexsha": "956eff12530e4a339f56d6d3739bc41328df4f75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cate/ops/aggregate.py", "max_issues_repo_name": "pwambach/cate", "max_issues_repo_head_hexsha": "956eff12530e4a339f56d6d3739bc41328df4f75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cate/ops/aggregate.py", "max_forks_repo_name": "pwambach/cate", "max_forks_repo_head_hexsha": "956eff12530e4a339f56d6d3739bc41328df4f75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5485961123, "max_line_length": 97, "alphanum_fraction": 0.6344128194, "include": true, "reason": "import numpy", "num_tokens": 3960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.1973448446340028}}
{"text": "#!/usr/bin/env python3\n\n#\n# Copyright 2015 Dovetail Genomics LLC\n#\n#\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom builtins import map\nfrom builtins import str\nfrom builtins import range\nfrom past.utils import old_div\nimport sys\nimport networkx as nx\nimport chicago_edge_scores as ces\n\ndefault_gapsize=100.0\n\nll={}\nlinks={}\n\ndef is_shaved_tail(G,shave_round,shaved_degree,shave_limit):\n    leaves=[]\n    r={}\n    for n in G.nodes():\n        if shave_round.get(n,0)>shave_limit and shaved_degree.get(n,0)==1:\n            leaves.append(n)\n    for l in leaves:\n        q=[l]\n        while len(q)>0:\n            n=q.pop()\n            r[n]=True\n            for nn in G.neighbors(n):\n                if shave_round.get(nn,0)>shave_limit and shaved_degree.get(nn,0)<=2 and (not nn in q) and (not nn in r ):\n                    q.append(nn)\n    return r\n\n\ndef distance_to_nearest_branch(G,shave_round,shave_limit,trim_degree):\n    branchpoints=[]\n    r={}\n\n    for n in G.nodes():\n        #print \"#\",n, G.degree(n),G.degree(n)==1\n        if shave_round.get(n,0)>shave_limit and trim_degree.get(n,0)>2:\n            branchpoints.append(n)\n#    print leaves\n\n    round=1\n#    print \"#\",leaves\n    boundary=list(branchpoints)\n    next=[]\n    done=[]\n    #r={}\n    for b in boundary: r[b]=round\n    while len(boundary)>0:\n        round +=1\n        next=[]\n        for n in boundary:\n            for nn in G.neighbors(n):\n                if (not nn in boundary+done+next) :\n                    next.append(nn)\n#                    r[nn]=round\n        for b in next: \n            r[b] = round\n#            if len( [nn for nn in G.neighbors(b) if not r.has_key(nn)] )==1: r[b]=round\n        for b in boundary: done.append(b)\n        boundary = []\n        for n in next: \n            if n in r: boundary.append(n)\n#        next=[]\n\n#    for n in G.nodes():\n#        if not r.has_key(n): r[n]=round\n    return r\n\n\ndef distance_to_nearest_leaf(G,shave_round,shave_limit,trim_degree):\n    leaves=[]\n    r={}\n    for n in G.nodes():\n        #print \"#\",n, G.degree(n),G.degree(n)==1\n        if shave_round.get(n,0)<=shave_limit :\n            r[n]=0\n    for n in G.nodes():\n        #print \"#\",n, G.degree(n),G.degree(n)==1\n        if trim_degree.get(n,0)==1 and shave_round.get(n,0)>shave_limit:\n            leaves.append(n)\n#    print leaves\n\n    round=1\n#    print \"#\",leaves\n    boundary=list(leaves)\n    next=[]\n    done=[]\n#    r={}\n    for b in boundary: r[b]=round\n    while len(boundary)>0:\n        round +=1\n        next=[]\n        for n in boundary:\n            for nn in G.neighbors(n):\n                if (not nn in boundary+done+next):\n                    next.append(nn)\n#                    r[nn]=round\n        for b in next: \n            r[b] = round\n#            if len( [nn for nn in G.neighbors(b) if not r.has_key(nn)] )==1: r[b]=round\n        for b in boundary: done.append(b)\n        boundary = []\n        for n in next: \n            if n in r: boundary.append(n)\n#        next=[]\n#    for n in G.nodes():\n#        if not r.has_key(n): r[n]=round\n    return r\n    \n\ndef shave_round(G):\n    leaves=[]\n    for n in G.nodes():\n        #print \"#\",n, G.degree(n),G.degree(n)==1\n        if G.degree(n)==1:\n            leaves.append(n)\n#    print leaves\n\n    round=1\n#    print \"#\",leaves\n    boundary=list(leaves)\n    next=[]\n    done=[]\n    r={}\n    for b in boundary: r[b]=round\n    while len(boundary)>0:\n        round +=1\n        next=[]\n        for n in boundary:\n            for nn in G.neighbors(n):\n                if (not nn in boundary+done+next):\n                    next.append(nn)\n#                    r[nn]=round\n        nr={}\n        for b in next: \n            if len( [nn for nn in G.neighbors(b) if nn not in r] )==1: nr[b]=round\n        r.update(nr)\n        for b in boundary: done.append(b)\n        boundary = []\n        for n in next: \n            if n in r: boundary.append(n)\n#        next=[]\n    for n in G.nodes():\n        if n not in r: r[n]=round\n    return r\n\ndef log(x):\n    sys.stderr.write(x+\"\\n\")\n\n\nLOCAL_BRIDGE=1\nCUT_ME=2\n\nedge_tags={}\n\ndef add_tag(s1,s2,tag):\n    if s1<s2:\n        ot = edge_tags.get((s1,s2),set())\n        ot.add(tag)\n        edge_tags[s1,s2] = ot\n    else:\n        ot = edge_tags.get((s2,s1),set())\n        ot.add(tag)\n        edge_tags[s2,s1] = ot\n\n\ndef get_tags(s1,s2):\n    if s1<s2:\n        ot = edge_tags.get((s1,s2),set())\n        return tuple(ot)\n    else:\n        ot = edge_tags.get((s2,s1),set())\n        return tuple(ot)\n\n\nedge_color_setting=\"hair\"\ndef edge_tag_to_style(tags,setting=edge_color_setting):\n    if setting == \"hair\":\n        style=\"\"\n        if \"hair\" in tags:\n            style= \"color=red\"\n        elif \"longHair\" in tags:\n            style= \"color=orange\"\n        elif \"H\" in tags:\n            style= \"color=blue\"\n        elif \"Y\" in tags:\n            style= \"color=goldenrod\"\n        elif \"nearY\" in tags:\n            style= \"color=goldenrod4\"\n        elif \"bigH\" in tags:\n            style= \"color=green\"\n        if \"promisc\" in tags:\n            style += \" style=dashed\"\n        return style\n            \ndef printdot(g,gg0,c,n,ll,bh,annot,trim_level={},post_trim_degree={},tag=\"bad\",yDist={},leafDist={},edgeTags=edge_tags):\n#def printdot(g,c,n,ll,bh,annot,tag=\"bad\"):\n#    print ll\n\n    import colorsys\n\n    chromosomes={}\n    chr_mins={}\n    chr_maxs={}\n    if bh:\n        sb=[]\n        for cc in c:\n            bhi = bh.get(cc,[0,0,0,0,0,0])\n            sb.append( ( bhi[1],old_div((float(bhi[3])+float(bhi[4])),2.0),bhi[2],cc ) )\n            chromosomes[bhi[1]]=1\n            if chr_mins.get(bhi[1],5.0e9)>min( float(bhi[3]), float(bhi[4]) ):  chr_mins[bhi[1]]=min( float(bhi[3]), float(bhi[4]) )\n            if chr_maxs.get(bhi[1],-1.0) <max( float(bhi[3]), float(bhi[4]) ):  chr_maxs[bhi[1]]=max( float(bhi[3]), float(bhi[4]) )\n        sb.sort()\n\n# {'19': 46194830.0, '18': 59221558.0, '8': 96645227.0, '4': 18548230.0, 'X': 102465955.0}\n# {}\n\n    print(\"#\",chr_mins)\n    print(\"#\",chr_maxs)\n\n    nchrs=len(list(chromosomes.keys()))\n    i=0\n    chr_hue={}\n    for ch in list(chromosomes.keys()):\n        chr_hue[ch] = old_div(float(i),nchrs)\n        i+=1\n\n    gg = nx.subgraph(g,c)\n    f=open(\"%s-%d.txt\" % (tag,n), \"wt\")\n    nn=1\n    lab0={}\n    for x in c:\n        p=\"\"\n        d=x\n        if x[0]==\"-\": \n            p=\"-\"\n            d=x[1:]\n#        lab0[d]=lab0.get(d,nn)\n        lab0[d]=lab0.get( d, float(ll.get(d,0)))\n        #print x,d,p,lab0[d]\n        nn+=1\n    lab={}\n    node_fill={}\n    for x in c:\n        p=\"\"\n        d=x\n        if x[0]==\"-\": \n            p=\"-\"\n            d=x[1:]\n\n        bhi = bh.get(x,False)\n        if bhi:\n            lab[x]=\"{:.1f} {}{}\\\\n{:.2f}-{:.2f}\\\\n{}\".format( old_div(lab0.get(d,0.0),1000), bhi[1],bhi[2],old_div(float(bhi[3]),1.0e6),old_div(float(bhi[4]),1.0e6), x)\n#            lab[x]=\"{:.1f} {}{}\\\\n{:.2f}-{:.2f}\\\\n{} {} {} {}\".format( lab0.get(d,0.0)/1000, bhi[1],bhi[2],float(bhi[3])/1.0e6,float(bhi[4])/1.0e6,leafDist.get(x,\"\"),yDist.get(x,\"\"), trim_level[x], post_trim_degree.get(x,\"\") )\n            if ( chr_maxs.get(bhi[1], (1.0+float(bhi[3])+float(bhi[4])) ) ) ==0.0: #/2.0)-chr_mins.get(bhi[1],0.0))==0.0: \n                print(\"wtf?\",x,bhi,bhi[1],( chr_maxs.get(bhi[1], (1.0+float(bhi[3])+float(bhi[4])) ) ))\n            rgb=(0,0,0)\n            try:\n                rgb=colorsys.hls_to_rgb( chr_hue[bhi[1]], 0.5, old_div((old_div((float(bhi[3])+float(bhi[4])),2.0) - chr_mins.get(bhi[1],0)),(chr_maxs.get(bhi[1],old_div((1.0+float(bhi[3])+float(bhi[4])),2.0))-chr_mins.get(bhi[1],0.0)))  )\n            except Exception as e:\n                print(e)\n            node_fill[x]= '#%02x%02x%02x' % (255.0*rgb[0], 255.0*rgb[1], 255.0*rgb[2] ) #\"#{}{}{}\".format()\n        else:\n            lab[x]=\"{:.1f}\\\\n{}\".format(old_div(lab0.get(d,0.0),1000),str(x))\n            node_fill[x]=\"white\"\n#        lab[x]=\"{} {}\".format( trim_level.get(x,\"?\"), post_trim_degree.get(x,\"?\") )\n\n    f.write( \"graph G {\\n\")\n#    f.write( \"node [margin=0 fontcolor=blue fontsize=32 width=0.5 shape=circle style=filled]\")\n    f.write( \"node [margin=0 fontsize=6 shape=box];\\n\")\n    f.write( \"edge [ fontsize=6 ];\\n\")\n\n    for x in list(lab.keys()):\n        f.write( \"{0} [label=\\\"{1}\\\" fillcolor=\\\"{2}\\\" style=\\\"filled\\\" color=\\\"{2}\\\"] ; \\n\".format(x,lab[x],node_fill[x]) )\n\n    if bh:\n        last=False\n        lastx=0.0\n        lastc=0\n        for c in sb:\n            if last and c[0]==last and (c[1]-lastx)<1000000:\n                last_bhi = bh.get(lastc,False)\n                this_bhi = bh.get(c[-1],False)\n                blast_label=str(last_bhi) + str(this_bhi)\n                if this_bhi and last_bhi :\n                    aa = tuple(last_bhi[1:5])\n                    bb = tuple(this_bhi[1:5])\n                    qd = qdist(aa,bb)\n                    blast_label = \"{}\".format(qd)\n                    \n                if gg0.has_edge(lastc,c[-1]) and not t.has_edge(lastc,c[-1]):\n                    f.write(\"\\t \\\"{}\\\" -- \\\"{}\\\" [weight=2 style=dotted label=\\\"{} {}\\\" fontcolor=red] ;\\n\".format(lastc,c[-1],blast_label,int(abs(gg0[lastc][c[-1]]['weight']))))\n                else:\n                    f.write(\"\\t \\\"{}\\\" -- \\\"{}\\\" [weight=2 style=dotted label=\\\"{}\\\" fontcolor=blue] ;\\n\".format(lastc,c[-1],blast_label))\n            last=c[0]\n            lastx=c[1]\n            lastc=c[-1]\n\n    for e in gg.edges():\n#        f.write( \"\\t\\\"%s\\\" -- \\\"%s\\\";\\n\" % (lab[e[0]],lab[e[1]]) ) #,gg[e[0]][e[1]]['weight'])\n#        color=\"black\"\n#        if annot.get(e,0)&LOCAL_BRIDGE : color=\"red\"\n#        if annot.get(e,0)&CUT_ME       : color=\"yellow\"\n        f.write( \"\\t \\\"%s\\\" -- \\\"%s\\\" [label=\\\"%d\\\" weight=1 %s];\\n\" % ( e[0],e[1],int(abs(gg[e[0]][e[1]]['weight'])),edge_tag_to_style( get_tags(e[0],e[1]) ) ))\n\n    f.write( \"}\\n\")\n\n\ndef independent_path(G,a,b,k,t):\n    q=[a]\n    l={}\n    l[a]=0\n    r=[]\n    while len(q)>0:\n#        print a,b,G[a][b],q,r\n        n=q.pop(0)\n        r.append(n)\n        for nn in G.neighbors(n):\n            if (n==a and nn==b) or (n==b and nn==a): continue\n            if G[n][nn]['weight']>-t: continue\n            if nn==b: return True\n#            print q,[l[i] for i in q]\n            l[nn] = min(l.get(nn,10000), l[n]+1)\n            if (not nn in q+r) and (l[nn]<=k):\n                q.append(nn)\n    return False\n    \ndef annotate_edges(t,G,node_list):\n    an={}\n#    nn= len(list(t.edges()))\n#    i=0.0\n    for a,b in t.edges():\n\n        if not independent_path(G,a,b,4,2): \n            an[a,b]=\"local_bridge\"\n            an[b,a]=\"local_bridge\"\n            \n    return an\n\n\ndef pairs_overlap(x,y):\n    a=min(x[0],x[1])\n    b=max(x[0],x[1])\n    c=min(y[0],y[1])\n    d=max(y[0],y[1])\n        \n    if a<=c and c<=b: return True\n    if a<=d and d<=b: return True\n    if c<=a and a<=d: return True\n    if c<=b and b<=d: return True\n    return False\n\ndef qdist(x,y):\n    if (not x) or (not y): return (-1)\n    if x[0]==y[0]:\n        x,y,w,z = list(map(int,[x[2],x[3],y[2],y[3]]))\n        ol = pairs_overlap((x,y),(w,z))\n        if ol:\n            return(-1*min(\n                abs(x-w),\n                abs(x-z),\n                abs(y-w),\n                abs(y-z )))\n        else:\n            return(min(\n                abs(x-w),\n                abs(x-z),\n                abs(y-w),\n                abs(y-z )))\n    else:\n        return(1.0e12)\n\ndef test_inversion_option(c1,c2,join_options,ograph,linked):\n    a=c1\n    b=linked[c1]\n    c=c2\n    d=linked[c2]\n\n    #k=linked[internal_node]\n    ograph.remove_edge(a,b)\n    ograph.remove_edge(c,d)\n                                                    ##                                                                        ---b a-------c d----\n    if a in nx.node_connected_component(ograph,c):  ## exchance labels of a,b if necessary, so the nodes are in this config:  ---a b-------c d------ \n        x=b\n        b=a\n        a=x\n     \n                                                    ##                                                                        ---b a-------d c----\n    if a in nx.node_connected_component(ograph,d):  ## exchance labels of a,b if necessary, so the nodes are in this config:  ---a b-------c d------ \n        x=b\n        b=a\n        a=x\n\n        x=d\n        d=c\n        c=x\n\n                                                    ##                                                                        ---a b-------d c----\n    if b in nx.node_connected_component(ograph,d):  ## exchance labels of c,d if necessary, so the nodes are in this config:  ---a b-------c d------ \n        x=d\n        d=c\n        c=x\n\n    n_scaffold = old_div(len(nx.node_connected_component(ograph,b)),2)\n    print(\"inversion n nodes\",n_scaffold)\n\n\n    total_i_len = sum( ograph[i][j]['length'] for i,j in nx.bfs_edges(ograph,b) )\n    print(\"inv len\",total_i_len)\n    if total_i_len < 10000.0 or n_scaffold<2:\n        print(\"inversion length\",total_i_len,n_scaffold,\"too short\")\n        join_options.append( (0.0,(),() ) )                                                                                              \n        ograph.add_edge(a,b,length=default_gapsize,contig=False)\n        ograph.add_edge(c,d,length=default_gapsize,contig=False)\n\n        return\n\n    interc_score0 = intercalation_score_raw(a,b,d,ograph) \n    interc_score1 = intercalation_score_raw(a,c,d,ograph) \n    print(\"inversion0\", interc_score0)\n    print(\"inversion\", interc_score1)\n    join_options.append( (interc_score0,(),() ) )\n    join_options.append( (interc_score1,((a,c),(b,d)),((a,b),(c,d)) ) )\n    ograph.add_edge(a,b,length=default_gapsize,contig=False)\n    ograph.add_edge(c,d,length=default_gapsize,contig=False)\n\n    return\n\ndef test_endInversion_option(free_end,internal_node,join_options,ograph,linked):\n    if free_end in linked:\n        x=free_end\n        free_end = internal_node\n        internal_node = x\n    print(\"end inversion\",free_end,linked.get(free_end),internal_node,linked[internal_node])\n\n    k=linked[internal_node]\n    ograph.remove_edge(internal_node,k)\n\n    if free_end in nx.node_connected_component(ograph,internal_node): \n        x=k\n        k=internal_node\n        internal_node=x\n\n    sc = link_test(ograph,k,internal_node)\n    join_options.append( (sc,(),()))\n    print(\"end inversion existing:\",sc)\n\n    sc = link_test(ograph,free_end,internal_node)\n    join_options.append( (sc ,((free_end,internal_node),),((internal_node,k),) ) ) \n    print(\"end inversion:\",sc)\n\n    ograph.add_edge(internal_node,k,length=default_gapsize, contig=False) \n    return\n\ndef test_interc_option( gap_edge1, gap_edge2, free_end1, join_options, ograph ):\n    if not ograph.has_edge(gap_edge1,gap_edge2):\n        print(\"expected nodes to be connected: {} {}\".format(gap_edge1, gap_edge2))\n        raise Exception('not connected')\n    ograph.remove_edge( gap_edge1, gap_edge2 )\n    if gap_edge1 in nx.node_connected_component(ograph,gap_edge2): \n        print(\"problem: these should be disconnected now:\",gap_edge1,gap_edge2)\n        raise Exception('too connected i')\n    if gap_edge2 in nx.node_connected_component(ograph,free_end1): \n        print(\"problem: these should have been disconnected all along\",free_end1,gap_edge2)\n        raise Exception('too connected j')\n    if gap_edge1 in nx.node_connected_component(ograph,free_end1): \n        print(\"problem: these should have been disconnected all along\",free_end1,gap_edge1) \n        raise Exception('too connected k')\n    interc_score = intercalation_score(gap_edge1,free_end1,gap_edge2,ograph)\n    ograph.add_edge(gap_edge1, gap_edge2, length=default_gapsize,contig=False)\n    d = far_end(ograph,free_end1)\n    join_options.append( (interc_score,((gap_edge1,free_end1),(d,gap_edge2)),((gap_edge1, gap_edge2),) ) )\n\n\nN=76710553.0 #100000000.0\npn=0.3\nGenomeSize=3.0e9\nimport math\n\ndef get_score(c1_stranded,c2_stranded,gaplen=default_gapsize,cache={}):\n    if gaplen<0.0: print(math.log(-1))\n#    if cache.has_key((c1_stranded,c2_stranded,gaplen)):\n#        return cache[c1_stranded,c2_stranded,gaplen]\n#    if cache.has_key((c2_stranded,c1_stranded,gaplen)):\n#        return cache[c2_stranded,c1_stranded,gaplen]\n    o1,o2=0,0\n    if c1_stranded[-2:]==\".5\": o1=1\n    if c2_stranded[-2:]==\".3\": o2=1\n    c1=c1_stranded[:-2]\n    c2=c2_stranded[:-2]\n    l1=ll[c1]\n    l2=ll[c2]\n    p0 = ces.p_not_a_hit(l1,l2,GenomeSize,gaplen,pn)\n    if p0<0.0:\n        print(\"wtf?  p0<0\",p0,l1,l2,GenomeSize,gaplen,pn)\n    thisscore=ces.llr_v0(l1,l2,o1,o2,GenomeSize,pn,links.get((c1,c2),[]),N,gaplen,p0 )\n    #cache[c1_stranded,c2_stranded,gaplen]=thisscore\n    return thisscore\n\ndef traverse_and_layout(n,coords,facing,x,s,og,maxD=2000000):\n    color={}\n    q=[n]\n    ptr=x\n    if s>0: \n        facing[n]=\"L\"    \n    else: \n        facing[n]=\"R\"\n    while (abs(ptr-x)<maxD) and len(q)>0:\n        m=q.pop(0)\n        coords[m]=ptr\n        color[m]=1\n        for mm in og.neighbors(m):\n            if not mm in color:\n                q.append(mm)\n                ptr+=s*og[m][mm]['length']\n                if not og[m][mm]['contig']:\n                   if s==-1:\n                       facing[mm]='R'\n                   else:\n                       facing[mm]='L'\n                else:\n                   if s==-1:\n                       facing[mm]='L'\n                   else:\n                       facing[mm]='R'\n\ndef far_end(g,n):\n    if not g.degree(n)==1:\n        print(\"wtf: this should be a leaf\")\n        exit(0)\n    for m in nx.node_connected_component(g,n):\n        if (not m==n) and g.degree(m)==1:\n            return m\n\ndef both_ends(g,n):\n    p=[]\n    for m in nx.node_connected_component(g,n):\n        if  g.degree(m)==1:\n            p.append( m)\n    return p\n\ndef strand_check(a,b,x,f):\n    if x[a]<x[b]:\n        if f[a]==\"R\" and f[b]==\"L\": return True\n    else:\n        if f[b]==\"R\" and f[a]==\"R\": return True\n    return False\n\ndef take_best_join_option(join_options,og,linked,edge_options,label=\"\"):\n#    print join_options\n    join_options.sort(reverse=True)\n#    print join_options\n    if join_options[0][0]>0.0:\n#        if len(join_options[0][2]) >=1 : print \"#accept join\",label, join_options[0], join_options\n        for x,y in join_options[0][2]:\n            og.remove_edge(x,y)\n            del linked[x]\n            del linked[y]\n        for x,y in join_options[0][1]:\n            linked[x]=y\n            linked[y]=x\n            og.add_edge(x,y,length=default_gapsize,contig=False)\n            edge_options[x,y] = \"[color=brown label=\\\"{:.2f}\\\"]\".format(weights.get((x,y),0))\n            edge_options[y,x] = \"[color=brown label=\\\"{:.2f}\\\"]\".format(weights.get((x,y),0))\n                    \ndef link_test(og,a,b,gapsize=default_gapsize,max_stretch=200000):\n    coords = {}\n    facing={}\n    traverse_and_layout(a,coords,facing,0,-1,og,maxD=200000)\n    traverse_and_layout(b,coords,facing,gapsize,+1,og,maxD=200000)\n#    print \"#x:setup done\"\n    sys.stdout.flush()\n    \n    score=0.0\n    for n1 in nx.node_connected_component(og,a):\n        if abs(coords.get(n1,-1e10))>max_stretch: continue\n        for n2 in nx.node_connected_component(og,b):\n            if abs(coords.get(n2,1e10))>max_stretch: continue\n            if strand_check(n1,n2,coords,facing):\n                distance = coords[n2] - coords[n1]\n                if distance < max_stretch:\n                    x=get_score(n1,n2,distance)\n#                    print \"#x:partial\",n1,n2,x\n                    sys.stdout.flush()\n                    score += x\n    return score\n\ndef intercalation_score(a,b,c,og):\n#    print \"#intercalation test:\",a,b,c\n    if a in nx.node_connected_component(og,b): \n        print(\"a should not be connected to b\",a,b)\n        raise Exception('too connected a')\n    if b in nx.node_connected_component(og,c): \n        print(\"b should not be connected to c\",b,c)\n        raise Exception('too connected b')\n    if a in nx.node_connected_component(og,c): \n        print(\"a should not be connected to c\",a,c)\n        raise Exception('too connected c')\n    coordinates1={}\n    coordinates2={}\n    facing={}\n    traverse_and_layout(a,coordinates1,facing,0,-1,og)\n    coordinates2=dict(coordinates1)\n    traverse_and_layout(c,coordinates1,facing,default_gapsize,+1,og)\n    traverse_and_layout(b,coordinates2,facing,default_gapsize,+1,og)\n    traverse_and_layout(c,coordinates2,facing,default_gapsize+max(coordinates2.values()),+1,og)\n\n    score_0=0.0\n    for n1 in nx.node_connected_component(og,a):\n        for n2 in nx.node_connected_component(og,c):\n            if strand_check(n1,n2,coordinates1,facing):\n                distance = coordinates1[n2] - coordinates1[n1]\n                if distance < 200000:\n                    if distance<0: print(\"wtf1?\")\n                    score_0 += get_score(n1,n2,distance)\n\n    score_1=0.0\n    for n1 in nx.node_connected_component(og,a):\n        for n2 in nx.node_connected_component(og,c):\n            if strand_check(n1,n2,coordinates2,facing):\n                distance = coordinates2[n2] - coordinates2[n1]\n                if distance < 200000:\n                    if distance<0: print(\"wtf2?\")\n                    score_1 += get_score(n1,n2,distance)\n\n        for n2 in nx.node_connected_component(og,b):\n            if strand_check(n1,n2,coordinates2,facing):\n                distance = coordinates2[n2] - coordinates2[n1]\n                if distance < 200000:\n                    if distance<0: print(\"wtf3?\")\n                    score_1 += get_score(n1,n2,distance)\n\n    for n1 in nx.node_connected_component(og,b):\n        for n2 in nx.node_connected_component(og,c):\n            if strand_check(n1,n2,coordinates2,facing):\n                distance = coordinates2[n2] - coordinates2[n1]\n                if distance < 200000:\n                    if distance<0: print(\"wtf4?\")\n                    score_1 += get_score(n1,n2,distance)\n\n#    print \"#intercalation scores:\",score_1,score_0\n\n\n    if a in nx.node_connected_component(og,b): \n        print(\"a should not be connected to b\",a,b)\n        raise Exception('too connected d')\n    if b in nx.node_connected_component(og,c): \n        print(\"b should not be connected to c\",b,c)\n        raise Exception('too connected e')\n    if a in nx.node_connected_component(og,c): \n        print(\"a should not be connected to c\",a,c)\n        raise Exception('too connected f')\n\n    return (score_1-score_0)\n\ndef intercalation_score_raw(a,b,c,og):\n#    print \"#intercalation test:\",a,b,c\n    if a in nx.node_connected_component(og,b): print(\"a should not be connected to b\",a,b)\n    if b in nx.node_connected_component(og,c): print(\"b should not be connected to c\",b,c)\n    if a in nx.node_connected_component(og,c): print(\"a should not be connected to c\",a,c)\n#    coordinates1={}\n    coordinates2={}\n    facing={}\n    traverse_and_layout(a,coordinates2,facing,0,-1,og)\n#    coordinates2=dict(coordinates1)\n#    traverse_and_layout(c,coordinates1,facing,1000,+1,og)\n    traverse_and_layout(b,coordinates2,facing,default_gapsize,+1,og)\n    traverse_and_layout(c,coordinates2,facing,default_gapsize+max(coordinates2.values()),+1,og)\n\n#    score_0=0.0\n#    for n1 in nx.node_connected_component(og,a):\n#        for n2 in nx.node_connected_component(og,c):\n#            if strand_check(n1,n2,coordinates1,facing):\n#                distance = coordinates1[n2] - coordinates1[n1]\n#                if distance < 200000:\n#                    if distance<0: print \"wtf1?\"\n#                    score_0 += get_score(n1,n2,distance)\n\n    score_1=0.0\n    for n1 in nx.node_connected_component(og,a):\n        for n2 in nx.node_connected_component(og,c):\n            if strand_check(n1,n2,coordinates2,facing):\n                distance = coordinates2[n2] - coordinates2[n1]\n                if distance < 200000:\n                    if distance<0: print(\"wtf2?\")\n                    score_1 += get_score(n1,n2,distance)\n\n        for n2 in nx.node_connected_component(og,b):\n            if strand_check(n1,n2,coordinates2,facing):\n                distance = coordinates2[n2] - coordinates2[n1]\n                if distance < 200000:\n                    if distance<0: print(\"wtf3?\")\n                    score_1 += get_score(n1,n2,distance)\n\n    for n1 in nx.node_connected_component(og,b):\n        for n2 in nx.node_connected_component(og,c):\n            if strand_check(n1,n2,coordinates2,facing):\n                distance = coordinates2[n2] - coordinates2[n1]\n                if distance < 200000:\n                    if distance<0: print(\"wtf4?\")\n                    score_1 += get_score(n1,n2,distance)\n\n#    print \"#intercalation scores:\",score_1,score_0\n    return (score_1)\n\n\nif __name__==\"__main__\":\n\n    import sys\n    import argparse\n    parser = argparse.ArgumentParser()\n   \n    parser.add_argument('-t','--threshold',default=0.0 ,  type=float)\n\n    parser.add_argument('-H','--head',default=False,type=int)\n    parser.add_argument('-D','--savetreedots',default=False,action='store_true')\n    parser.add_argument('-d','--debug',default=False,action='store_true')\n#    parser.add_argument('-I','--nointerc',default=False,action='store_true')\n    parser.add_argument('-p','--progress',default=False,action='store_true')\n    parser.add_argument('-M','--maxdegree',default=False,type=int)\n    parser.add_argument('-m','--minlength',default=500,type=int)\n\n    parser.add_argument('-S','--silent',default=False,action='store_true')\n    parser.add_argument('-K','--cutPromisc',default=False,action='store_true')\n    parser.add_argument('-J','--logH',default=False,action='store_true')\n    parser.add_argument('-T','--logTags',default=False,action='store_true')\n    parser.add_argument('-C','--cheat',default=False,action='store_true')\n    parser.add_argument('-B','--blacklist')\n\n    parser.add_argument('-j','--joins') #pre-join these\n    parser.add_argument('-k','--links') \n    parser.add_argument('-b','--besthits')\n    parser.add_argument('-s','--skip',default=0,type=int) \n    parser.add_argument('-l','--lengths')\n    parser.add_argument('-E','--edgefile')\n    parser.add_argument('--set_insert_size_dist_fit_params')\n    parser.add_argument('-L','--maxLength',type=float,default=150000.0)\n    parser.add_argument('-P','--promisc',type=float,default=0.023)\n    parser.add_argument('-o','--dotLabel',default=\"bad\")\n\n    args = parser.parse_args()\n    if args.debug:\n        args.progress=True\n\n    if args.progress: log( str(args) )\n    print(\"#\"+str(args))\n\n    if args.set_insert_size_dist_fit_params:\n        s=args.set_insert_size_dist_fit_params\n        a,b,c,d,f,pn,N = list(map(float,list(s.split(','))))\n        print(\"#\",a,b,c,d,f)\n        ces.set_insert_size_dist_fit_params(a,b,c,d,f,pn,N)\n        sys.stdout.flush()\n\n    G=nx.Graph()\n    SG=nx.Graph()\n\n    ll={}\n    if args.lengths:\n        f = open(args.lengths)\n        while True:\n            l = f.readline()\n            if not l: break\n            if l[0]==\"#\": continue\n\n            c=l.strip().split()\n            l = int(c[1])\n            ll[c[0]]=int(c[1])\n            if l>= args.minlength:\n                G.add_node(c[0])\n                SG.add_node(c[0])\n        f.close()\n    if args.progress: print(\"#Done reading lengths\")\n\n    #broken.al.masked.links.txt\n    def read_links(contigs=False):\n        links={}\n        import glob\n        for f in glob.glob(args.links): #[\"same_component-t4.links.txt\"]:\n            print(\"#file:\",f)\n            ff=open(f)\n            while True:\n                l = ff.readline()\n                if not l: break\n                if l[0]==\"#\": continue\n                c=l.strip().split(\"\\t\")\n                if (not contigs) or (c[0] in contigs) and (c[1] in contigs):\n                    links[(c[0],c[1])]=eval(c[5])\n        return links\n\n\n    besthit={}\n    if args.besthits:\n#        besthit={}\n        if args.besthits:\n            f = open(args.besthits)\n            while True:\n                l = f.readline()\n                if not l: break\n\n                if not l[:5]==\"best:\": continue\n                c=l.strip().split()\n                besthit[c[1]]=c[2:]\n    #            print c[1],besthit[c[1]]\n            f.close()\n    if args.progress: print(\"#Done reading besthits\")\n\n    if args.edgefile:\n        f = open(args.edgefile)\n    else:\n        f=sys.stdin\n    while True:\n        l = f.readline()\n        if not l: break\n        if l[0]==\"#\": continue\n        c=l.strip().split()\n        u,v,w = c[0],c[1],float(c[2])\n        if ( not args.lengths ) or (ll[u]>=args.minlength and ll[v]>=args.minlength):\n            G.add_edge(u,v,weight=-w)\n            if w >= args.threshold:\n                SG.add_edge(u,v,weight=-w)\n    if args.edgefile:\n        f.close()\n\n    if args.progress: print(\"#Done reading edgelist\")\n\n    bad_nodes=[]\n    total_discarded_length=0\n    total_discarded_length1=0\n    n_discarded1=0\n    n_discarded2=0\n    if args.maxdegree:\n        for n in SG.nodes():\n            print(\"#dg:\", SG.degree(n))\n            if SG.degree(n)>args.maxdegree:\n                n_discarded1+=1\n                bad_nodes.append(n)\n                total_discarded_length += ll[n]\n                print(\"#discard:\",n,ll[n],SG.degree(n))\n                for nn in SG.neighbors(n):\n                    if SG.degree(nn)==1:\n                        n_discarded2+=1\n                        total_discarded_length1+=ll[nn]\n        for n in bad_nodes:\n            e_to_remove=[]\n            for e in SG.edges([n]):\n                e_to_remove.append(e)\n            SG.remove_edges_from(e_to_remove)\n\n    if args.cutPromisc:\n        bad_nodes=[]\n        for n in G.nodes():\n#            print \"#dg:\", SG.degree(n)\n            if (old_div(float(G.degree(n)), ll[n]))>args.promisc : # G.degree(n)/ll[n]>args.maxdegree:\n                n_discarded1+=1\n                bad_nodes.append(n)\n                total_discarded_length += ll[n]\n                print(\"#discard:\",n,ll[n],G.degree(n))\n#                for nn in G.neighbors(n):\n#                    if G.degree(nn)==1:\n#                        n_discarded2+=1\n#                        total_discarded_length1+=ll[nn]\n        for n in bad_nodes:\n            e_to_remove=[]\n            for e in G.edges([n]):\n                e_to_remove.append(e)\n            G.remove_edges_from(e_to_remove)\n            SG.remove_edges_from(e_to_remove)\n            \n    if args.blacklist:\n        f=open(args.blacklist)\n        e_to_remove=[]\n        while True:\n            l=f.readline()\n            if not l: break\n            c=l.strip().split()\n            e_to_remove.append((c[1],c[2]))\n        G.remove_edges_from(e_to_remove)\n        SG.remove_edges_from(e_to_remove)\n        \n            \n    if args.cheat:\n        e_to_remove=[]\n        for a,b in SG.edges():\n            if not ( a in besthit and b in besthit):\n                e_to_remove.append((a,b))\n            else:\n                aa = tuple(besthit[a][1:5])\n                bb = tuple(besthit[b][1:5])\n                qd = qdist(aa,bb)\n                if qd >= args.maxLength : \n                    e_to_remove.append((a,b))\n        SG.remove_edges_from(e_to_remove)\n        \n\n    if args.progress: print(\"#total_discarded_length\",n_discarded1,n_discarded2,old_div(float(total_discarded_length),1.0e6),old_div(float(total_discarded_length1),1.0e6),old_div(float(total_discarded_length+total_discarded_length1),1.0e6))\n\n\n    promisc = {}\n    for n in G.nodes():\n        if args.debug: print(\"#r:\",old_div(float(G.degree(n)),ll[n]))\n        if (old_div(float(G.degree(n)),ll[n]))>args.promisc: promisc[n]=True\n\n    tag_tallies={}\n    bad_tag_tallies={}\n    strx={\"+\":0, \"-\":1}\n    strings = []\n    ccn=1\n\n    if args.progress: \n        print(\"about to load the links\")\n        sys.stdout.flush()\n    links = read_links()\n    if args.progress: \n        print(\"loaded the links\")\n        sys.stdout.flush()\n\n\n    print(\"#n_connected_components:\",len(nx.connected_components(SG)))\n    for c in nx.connected_components(SG):\n        if ccn<=args.skip:\n            ccn+=1\n            continue\n\n        if len(c)==1: \n            print(\"#edge:\",c[0]+\".5\",c[0]+\".3\",{\"length\": ll[c[0]],\"contig\": True})\n            continue\n\n#        if args.progress: \n#            print \"about to load the links\"\n#            sys.stdout.flush()\n#        links = read_links(c)\n#        if args.progress: \n#            print \"loaded the links\"\n#            sys.stdout.flush()\n\n        print(\"cc:\",ccn,len(c),c)\n\n        edge_options={}\n        nodes={}\n\n        og=nx.Graph()\n        linked={}\n\n        for cc in c:\n            og.add_node(cc+\".5\")\n            og.add_node(cc+\".3\")\n            nodes[cc+\".5\"]=\"5'\"\n            nodes[cc+\".3\"]=\"3'\"\n            og.add_edge(cc+\".5\",cc+\".3\",length=ll[cc],contig=True)\n            edge_options[cc+\".5\",cc+\".3\"] = \"[label=\\\"{} {}\\\" penwidth=3]\".format(cc,old_div((ll[cc]+500),1000))\n            edge_options[cc+\".3\",cc+\".5\"] = \"[label=\\\"{} {}\\\" penwidth=3]\".format(cc,old_div((ll[cc]+500),1000))\n\n        if args.joins:\n            f = open(args.joins)\n            while True:\n                l = f.readline()\n                if not l: break\n                cz=l.strip().split()\n                if not len(cz)>=3: continue\n                #print \"z:\",cz[1][:-2],cz[2][:-2],cz\n                if cz[0]==\"#join:\" :\n                    if (cz[1][:-2] in c) and (cz[2][:-2] in c):\n                        print(\"join\",cz[1:])\n                        og.add_edge( cz[1],cz[2],length=default_gapsize,contig=False)\n                        linked[cz[1]]=cz[2]\n                        linked[cz[2]]=cz[1]\n#                        og.add_edge(c1,c2,length=1000.0,contig=False)\n                        edge_options[cz[1],cz[2]] = \"[label=\\\"pre\\\" penwidth=2]\"\n                        edge_options[cz[2],cz[1]] = \"[label=\\\"pre\\\" penwidth=2]\"\n                    else: \n                        pass\n#                        print \"skip\",cz[1:]\n            f.close()\n\n        weights = {}\n        for c1 in c:\n            if args.progress: print(\"#\",c1)\n            l1=ll[c1]\n            for c2 in c:\n                if not c1<c2: continue\n                if args.joins and c2+\".3\" in nx.node_connected_component(og, c1+\".3\"): continue\n                l2=ll[c2]\n                if (c1,c2) not in links: continue\n                for gaplen in [default_gapsize]: # [ 0, 500, 1000, 2000 , 10000, 20000, 30000, 40000, 100000, 200000, 500000 ]:\n                    p0 = ces.p_not_a_hit(l1,l2,GenomeSize,gaplen,pn) \n                    s={}\n                    for (o1,o2,suf1,suf2) in ((0,0,\".3\",\".5\"),(0,1,\".3\",\".3\"),(1,0,\".5\",\".5\"),(1,1,\".5\",\".3\")):\n                        weights[c1+suf1,c2+suf2] = ces.llr_v0( l1,l2,o1,o2,GenomeSize,pn,links.get((c1,c2),[]),N,gaplen,p0 )\n                        weights[c2+suf2,c1+suf1] = weights[c1+suf1,c2+suf2] \n                        if args.progress: print(\"#\",c1+suf1,c2+suf2,len(links[c1,c2]),weights[c1+suf1,c2+suf2])\n\n        link_pairs = list(weights.keys())\n        link_pairs.sort(key = lambda x: weights[x], reverse=True)\n\n        for c1,c2 in link_pairs:\n            if not c1<c2: continue\n            if weights[c1,c2]>12:\n                if c2 in nx.node_connected_component(og, c1):  # link within one of the scaffolds.  \n                    if c1 in linked and linked[c1]==c2: continue # this join pre made!\n                    if (not c1 in linked) and (not c2 in linked):  # this would circularize\n                        pass\n                    elif ( c1 in linked) and ( c2 in linked):      # test to invert (or excize circle?)\n                        if og.has_edge(c1,c2): \n                            print(\"skip test flip of\",c1,c2)\n                            continue #don't test inversions of individual contigs\n#                        print \"test invert\",c1,linked.get(c1),c2, linked.get(c2) \n                        join_options=[]\n                        test_inversion_option(c1,c2,join_options,og,linked)\n                        take_best_join_option(join_options,og,linked,edge_options,\"inversion\")\n                        \n                    elif (not c1 in linked) or (not c2 in linked): # test for end inversion (scorpion tail?) or pinch off circle from end?\n#                        print \"test end invert\",c1,c2,linked.get(c1), linked.get(c2)\n                        join_options=[]\n                        test_endInversion_option(c1,c2,join_options,og,linked)\n                        take_best_join_option(join_options,og,linked,edge_options,\"end inversion\")                        \n                        \n                else:\n                    if (not c1 in linked) and (not c2 in linked): # and not c2 in nx.node_connected_component(og, c1):\n                        linked[c1]=c2\n                        linked[c2]=c1\n                        print(\"#easy\",c1,c2,weights[c1,c2])\n                        og.add_edge(c1,c2,length=default_gapsize,contig=False)\n                        edge_options[c1,c2] = \"[color=blue label=\\\"{:.2f}\\\"]\".format(weights[c1,c2])\n                        edge_options[c2,c1] = \"[color=blue label=\\\"{:.2f}\\\"]\".format(weights[c1,c2])\n                    elif (c1 in linked) and (c2 in linked):\n                        # This edge looks like an H.  test whether the two linked scaffolds can be put end-to-end:\n                        # a-b k-d : we'll test b+k, a+k, b+d and a+d, and if the best one raises the total score, we'll add it.\n                        a,b = both_ends(og,c1)\n                        k,d = both_ends(og,c2)\n                        sc={}\n                        for x,y in ((b,k),(a,k),(b,d),(a,d)):\n                            sc[x,y] = link_test(og,x,y)\n                        sll=list(sc.items())\n                        sll.sort(key=lambda x: x[1],reverse=True)\n                        print(\"# Htest:\", c1,c2,sll)\n                        x,y = sll[0][0]\n                        if sc[x,y]>0:\n                            print(\"#H accept\", sc[x,y] ,x,y)\n                            linked[x]=y\n                            linked[y]=x\n                            og.add_edge(x,y,length=default_gapsize,contig=False)\n                            edge_options[x,y] = \"[color=green label=\\\"{:.2f}\\\"]\".format(weights.get((x,y),0))\n                            edge_options[y,x] = \"[color=green label=\\\"{:.2f}\\\"]\".format(weights.get((x,y),0))\n                            \n                    elif (not c1 in linked) or (not c2 in linked):  #test whether one can be intercalated in the other:\n                        accepted=False\n                        join_options=[]\n                        if (not c1 in linked):\n                            b=c1\n                            a=c2\n                            cP=linked[a]\n                            print(\"#1:\",c1,c2,a,b,cP,weights[c1,c2])\n                        elif (not c2 in linked):\n                            b=c2\n                            a=c1\n                            cP=linked[a]\n                            print(\"#2:\",c1,c2,a,b,cP,weights[c1,c2])\n                        if (not c1 in linked) or (not c2 in linked):\n                            # not linking end-to-end:  \n                            #but one of them IS an end link, try inserting that scaffold into the other one.\n                            # a and c are the contig ends flanking the gap we're inserting into, b is the end of\n                           #  the scaffold being tested for insertion.\n\n\n                            test_interc_option(a,cP,b,join_options,og)\n                            test_interc_option(a,cP,far_end(og,b),join_options,og)\n\n                            a,k = both_ends(og,a)\n                            b,d = both_ends(og,b)\n                            sc={}\n                            for x,y in ((a,b),(k,b),(a,d),(k,d)):\n                                sc[x,y] = link_test(og,x,y)\n                                join_options.append( (sc[x,y],((x,y),),() ) )\n\n                            take_best_join_option(join_options,og,linked,edge_options,\"interc or end\")\n                                    \n\n        if False:\n            for c1,c2 in link_pairs:\n                if weights[c1,c2]>12 and not c2 in nx.node_connected_component(og, c1):\n    #                linked[c1]=True\n    #                linked[c2]=True\n                    og.add_edge(c1,c2)        \n                    edge_options[c1,c2] = \"[style=dotted label=\\\"{:.2f}\\\"]\".format(weights[c1,c2]) #]\"\n                    edge_options[c2,c1] = \"[style=dotted label=\\\"{:.2f}\\\"]\".format(weights[c1,c2]) #]\"\n\n        red_edges=\"\"\n        node_fill={}\n        if args.besthits:\n            import colorsys\n\n            chromosomes={}\n            chr_mins={}\n            chr_maxs={}\n            ends=[]\n            \n            for cc in c:\n#best:   Scaffold91_1    46380.0 chr12   +       49064574        49095652    \n#                besthit[c[1]]=c[2:]\n\n                if cc not in besthit: continue\n                aa = tuple(besthit[cc][1:5])\n                chromosomes[aa[0]]=1\n                xxx = old_div((int(aa[2])+int(aa[3])),2)\n                if chr_mins.get(aa[0],1.0e9)>xxx: chr_mins[aa[0]]=xxx\n                if chr_maxs.get(aa[0],-1.0e9)<xxx: chr_maxs[aa[0]]=xxx\n                if aa[1]==\"+\":\n                    ends.append((aa[0],xxx,cc+\".5\",cc+\".3\",cc))\n#                    ends.append((c[0],int(aa[3]),cc+\".3\",cc))\n                elif aa[1]==\"-\":\n                    ends.append((aa[0],xxx,cc+\".3\",cc+\".5\",cc))\n#                    ends.append((c[0],int(aa[3]),cc+\".5\",cc))\n            ends.sort()\n\n            nchrs=len(list(chromosomes.keys()))\n            if nchrs==0: nchrs+=1\n            i=0\n            chr_hue={}\n            for ch in list(chromosomes.keys()):\n                chr_hue[ch] = old_div(float(i),nchrs)\n                i+=1\n\n            for cc in c:\n                if not cc in besthit: continue\n                aa = tuple(besthit[cc][1:5])\n                chrid=aa[0]\n                xxx = old_div(float(int(aa[2])+int(aa[3])),2)\n                rgb=colorsys.hls_to_rgb( chr_hue[chrid], 0.5, old_div((xxx - chr_mins.get(chrid,0)),(1.0 + chr_maxs.get(chrid,xxx+1.0)-chr_mins.get(chrid,0.0))))\n                node_fill[cc+\".5\"]= '#%02x%02x%02x' % (255.0*rgb[0], 255.0*rgb[1], 255.0*rgb[2] ) #\"#{}{}{}\".format()\n                node_fill[cc+\".3\"]= '#%02x%02x%02x' % (255.0*rgb[0], 255.0*rgb[1], 255.0*rgb[2] ) #\"#{}{}{}\".format()\n\n\n\n            for i in range(1,len(ends)):\n                if ends[i-1][0]==ends[i][0] and ends[i-1][3] in nx.node_connected_component(og,ends[i][3]):\n#                    red_edges += \"\\\"{}\\\" -- \\\"{}\\\" [color=red style=dotted label=\\\"{:.1f}\\\" fontcolor=red];\\n\".format(ends[i-1][3],ends[i][2],weights.get((ends[i-1][3],ends[i][2]),\"\"))\n                    red_edges += \"\\\"{}\\\" -- \\\"{}\\\" [color=red style=dotted ];\\n\".format(ends[i-1][3],ends[i][2])\n\n        if args.savetreedots:\n            f=open(\"greedy-linear7-{}.dot\".format(ccn),\"wt\")\n            f.write(\"graph G {\\n\")\n            for cc in list(nodes.keys()):\n    #[label=\\\"{1}\\\" fillcolor=\\\"{2}\\\" style=\\\"filled\\\" color=\\\"{2}\\\"]\n                f.write(\"\\\"{}\\\" [ label=\\\"{}\\\" fillcolor=\\\"{}\\\" color=\\\"{}\\\" style=\\\"filled\\\" ];\\n\".format(cc,nodes[cc],node_fill.get(cc,\"white\"),node_fill.get(cc,\"white\")))\n                #            f.write(\"\\n\".format(c))\n            f.write(red_edges)\n            for c1,c2 in og.edges():\n                f.write(\"\\\"{}\\\" -- \\\"{}\\\" {} \\n\".format(c1,c2,edge_options.get((c1,c2),\"\")))\n            f.write(\"}\\n\")\n            f.close()\n      \n        for nnog in nx.connected_component_subgraphs(og):\n            tlnnog=0\n            for c1,c2 in nnog.edges():\n                print(\"#edge:\",c1,c2,og.get_edge_data(c1,c2))\n                tlnnog+=og[c1][c2]['length']\n            print(\"#slen\",tlnnog)\n        ccn+=1\n\n        if args.head and ccn>args.head:\n            break\n\n    \n\n\n", "meta": {"hexsha": "003f09ea04f5084917e678207ca0be439ad47a03", "size": 43724, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/greedy_chicagoan.py", "max_stars_repo_name": "aakashsur/docker-hirise", "max_stars_repo_head_hexsha": "9b97cc4e7522e287aa2ee39c2993270e75b43a6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/greedy_chicagoan.py", "max_issues_repo_name": "aakashsur/docker-hirise", "max_issues_repo_head_hexsha": "9b97cc4e7522e287aa2ee39c2993270e75b43a6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/greedy_chicagoan.py", "max_forks_repo_name": "aakashsur/docker-hirise", "max_forks_repo_head_hexsha": "9b97cc4e7522e287aa2ee39c2993270e75b43a6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1802721088, "max_line_length": 240, "alphanum_fraction": 0.5161467386, "include": true, "reason": "import networkx", "num_tokens": 12029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.1973448446340028}}
{"text": "\"\"\"Plot figures from the paper.\"\"\"\nimport logging\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\nfrom astropy import units as u\nfrom astropy.table import Table\nfrom gammapy.spectrum import CrabSpectrum, CountsPredictor\nfrom gammapy.spectrum.models import LogParabola\nimport matplotlib.lines as mlines\nfrom matplotlib import gridspec\nfrom .models import Log10Parabola\nfrom .utils import load_yaml\nfrom .conf import config\nfrom .errors import stat_errorband\n\nlog = logging.getLogger(__name__)\n\nFONTSIZE = 15\nFONTSIZE_CONTOURS = 18\nE_UNIT_LABEL = r\"$E\\,/\\,\\mathrm{TeV}$\"\nSED_UNIT_LABEL = (\n    r\"$E^2 \\cdot {\\rm d}\\phi/{\\rm d}E\\,/\\,({\\rm erg}\\,{\\rm cm}^{-2} {\\rm s}^{-1})$\"\n)\nCOLORS = [\"#21ABCD\", \"#FF9933\", \"#893F45\", \"#3EB489\", \"#002E63\", \"crimson\"]\n\n\ndef plot_crab():\n    \"\"\"Plot Crab pulsar and nebula SED.\"\"\"\n    log.info(\"Executing plot_crab ...\")\n\n    fig, ax = plt.subplots()\n\n    # Plot flux points\n    for component in [\"pulsar\", \"nebula\"]:\n        table = Table.read(\"data/other/crab_mwl.fits.gz\")\n        table = table[table[\"component\"] == component]\n        x = table[\"energy\"].data\n        y = table[\"energy_flux\"].data\n        yerr_lo = table[\"energy_flux_err_lo\"].data\n        yerr_hi = table[\"energy_flux_err_hi\"].data\n        ax.errorbar(x, y, yerr=(yerr_lo, yerr_hi), fmt=\"o\", label=component)\n\n    # Plot SED model\n    energy = np.logspace(2, 8, 100) * u.MeV\n\n    crab = CrabSpectrum(reference=\"meyer\")\n\n    flux = crab.model(energy)\n    energy_flux = (energy ** 2 * flux).to(\"erg cm^-2 s^-1\")\n    ax.plot(energy.value, energy_flux.value, label=\"Meyer (2010) model\", lw=3)\n\n    ax.set_xlim((3e-1, 3e8))\n    ax.set_ylim((3e-12, 3e-8))\n    ax.set_xlabel(\"Energy (MeV)\")\n    ax.set_ylabel(\"E^2 dN/dE (erg cm^-2 s^-1)\")\n    fig.legend(loc=\"upper center\", ncol=3)\n    ax.grid()\n    ax.loglog()\n\n    path = Path(\"results/figures\")\n    path.mkdir(parents=True, exist_ok=True)\n    filename = \"results/figures/crab_mwl.png\"\n    log.info(f\"Writing {filename}\")\n    fig.savefig(filename)\n\n\ndef plot_fit_results(tool):\n    \"\"\"plot the SEDs result of the gammapy / sherpa fit\n    for comparison with the literature we choose only the Mayer spectrum\n\n    Here we plot the butterfly as a result of the multivariate sampling\n    with the 68% containment in flux\n    \"\"\"\n    fig, ax = plt.subplots()\n\n    model_meyer_ref = CrabSpectrum(\"meyer\").model\n    model_meyer_ref.plot(\n        [10 * u.GeV, 100 * u.TeV],\n        energy_power=2,\n        flux_unit=\"erg-1 cm-2 s-1\",\n        ls=\":\",\n        lw=2.2,\n        color=\"#555555\",\n        label=\"Meyer et al. (2010)\",\n    )\n\n    # where to take the results, configurations for the individual butterflies\n    instruments = [\"fermi\", \"magic\", \"veritas\", \"fact\", \"hess\", \"joint\"]\n    labels = [\"Fermi-LAT\", \"MAGIC\", \"VERITAS\", \"FACT\", \"H.E.S.S.\", \"joint fit\"]\n    lss = [\"--\", \"--\", \"--\", \"--\", \"--\", \"-\"]\n    colors = COLORS\n    # with one loop we realize all the butterfly plots\n    for instrument, label, color, ls in zip(instruments, labels, colors, lss):\n\n        path = (\n            config.repo_path\n            / f\"results/fit/{tool}/{instrument}/fit_results_logparabola.yaml\"\n        )\n\n        if not path.exists():\n            log.warning(f\"Missing: {path} . Skipping.\")\n            continue\n\n        results = load_yaml(path)\n        parameters = results[\"parameters\"]\n\n        model_lp = LogParabola.from_log10(\n            amplitude=parameters[0][\"value\"] * u.Unit(parameters[0][\"unit\"]),\n            reference=parameters[1][\"value\"] * u.Unit(parameters[1][\"unit\"]),\n            alpha=parameters[2][\"value\"] * u.Unit(parameters[2][\"unit\"]),\n            beta=parameters[3][\"value\"] * u.Unit(parameters[3][\"unit\"]),\n        )\n\n        # energy range for the plot\n        dataset = config.get_dataset(instrument)\n        energy_range = dataset.energy_range\n\n        # just in case of the joint fit put a thicker line and a less transparent butterfly\n        if instrument == \"joint\":\n            model_lp.plot(\n                energy_range,\n                energy_power=2,\n                flux_unit=\"erg-1 cm-2 s-1\",\n                ls=ls,\n                lw=3,\n                color=color,\n                label=label,\n            )\n        else:\n            model_lp.plot(\n                energy_range,\n                energy_power=2,\n                flux_unit=\"erg-1 cm-2 s-1\",\n                ls=ls,\n                lw=2.2,\n                color=color,\n                label=label,\n            )\n\n        # read the butterfly from the multivariate sampling results\n        table_path = Path(\n            f\"{config.repo_path}/results/figures/stat_err/{instrument}_flux_errorband.dat\"\n        )\n        log.info(f\"reading butterfly values from {table_path}\")\n        t = Table.read(table_path, format=\"ascii.ecsv\")\n        energies = t[\"energies\"].data * t[\"energies\"].unit\n        flux_lo = t[\"flux_lo\"].data * t[\"flux_lo\"].unit\n        flux_hi = t[\"flux_hi\"].data * t[\"flux_hi\"].unit\n\n        if instrument == \"joint\":\n            alpha = 0.38\n        else:\n            alpha = 0.28\n\n        plt.fill_between(\n            energies.to(\"TeV\"),\n            (energies ** 2 * flux_lo).to(\"erg cm-2 s-1\"),\n            (energies ** 2 * flux_hi).to(\"erg cm-2 s-1\"),\n            color=color,\n            alpha=alpha,\n            label=\"\",\n        )\n\n    ax.legend(fontsize=FONTSIZE)\n    ax.set_ylim([1e-12, 2e-10])\n\n    ax.set_xlabel(E_UNIT_LABEL, size=FONTSIZE)\n    ax.set_ylabel(SED_UNIT_LABEL, size=FONTSIZE)\n    # make axis thicker\n    for axis in [\"top\", \"bottom\", \"left\", \"right\"]:\n        ax.spines[axis].set_linewidth(1.6)\n    ax.tick_params(\"both\", length=7, width=1.6, which=\"major\", labelsize=FONTSIZE)\n    ax.tick_params(\"both\", length=4, width=1.6, which=\"minor\", labelsize=FONTSIZE)\n\n    plt.tight_layout()\n\n    filename = f\"results/figures/crab_sed_{tool}_fit.png\"\n    filename_pdf = f\"results/figures/crab_sed_{tool}_fit.pdf\"\n    log.info(f\"Writing {filename}\")\n    fig.savefig(filename)\n    fig.savefig(filename_pdf)\n\n\ndef plot_sherpa_contours():\n    \"\"\"plot the confidence contours obtained from the sherpa fit\n    \"\"\"\n    log.info(\"plotting parameters contours obtained from sherpa\")\n    # where to take the results, configurations for the individual butterflies\n    instruments = [\"fermi\", \"magic\", \"hess\", \"fact\", \"veritas\", \"joint\"]\n    labels = [\"Fermi-LAT\", \"MAGIC\", \"H.E.S.S.\", \"FACT\", \"VERITAS\", \"joint fit\"]\n    colors = [\"#21ABCD\", \"#FF9933\", \"#5A4FCF\", \"#5CC184\", \"#702963\", \"crimson\"]\n    lss = [\"--\", \"--\", \"--\", \"--\", \"--\", \"-\"]\n\n    fig, axarr = plt.subplots(1, 3, figsize=(18, 6))\n\n    # with one loop we realize all the contour plots\n    for instrument, label, color, ls in zip(instruments, labels, colors, lss):\n\n        path = config.repo_path / f\"results/fit/sherpa/{instrument}\"\n\n        contours_path = path / \"fit_contours_logparabola.npy\"\n        results_path = path / \"fit_results_logparabola.yaml\"\n\n        if not path.exists():\n            log.warning(f\"Missing: {path} . Skipping.\")\n            continue\n\n        # load the contours and the results of the fit\n        contours = np.load(contours_path).tolist()\n        results = load_yaml(results_path)\n\n        # define a 2 x 2 matrix to visualise the plot\n        # we will delete one of the subplots and make something like a corner plot\n        # useful variables for the plot\n        ampl_range = contours[\"contour_ampl_c1\"][\"x0_range\"]\n        c1_range = contours[\"contour_ampl_c1\"][\"x1_range\"]\n        c2_range = contours[\"contour_ampl_c2\"][\"x1_range\"]\n        # actual values output of the fit\n        # remember in sherpa notation: (amplitude->ampl, alpha->c1, beta->c2)\n        ampl = results[\"parameters\"][0][\"value\"]\n        c1 = results[\"parameters\"][2][\"value\"]\n        c2 = results[\"parameters\"][3][\"value\"]\n\n        # axarr[0,0]\n        extent = [ampl_range[0] * 1e9, ampl_range[1] * 1e9, c1_range[0], c1_range[1]]\n\n        axarr[0].contour(\n            contours[\"contour_ampl_c1\"][\"like_values\"],\n            contours[\"contour_ampl_c1\"][\"levels\"],\n            origin=\"lower\",\n            extent=extent,\n            colors=color,\n            linewidths=(2., 1.5, 1.3),\n            linestyles=(\"-\", \"--\", \":\"),\n        )\n\n        # print actual value\n        axarr[0].plot(ampl, c1, marker=\"X\", markersize=7, color=color)\n        axarr[0].set_xlabel(\n            r\"$f_0 / (\\mathrm{TeV} \\, \\mathrm{cm}^{-2} \\mathrm{s}^{-1})$\"\n        )\n        axarr[0].set_ylabel(r\"$\\Gamma$\")\n\n        extent = [ampl_range[0] * 1e9, ampl_range[1] * 1e9, c2_range[0], c2_range[1]]\n\n        axarr[1].contour(\n            contours[\"contour_ampl_c2\"][\"like_values\"],\n            contours[\"contour_ampl_c2\"][\"levels\"],\n            origin=\"lower\",\n            extent=extent,\n            colors=color,\n            linewidths=(2., 1.5, 1.3),\n            linestyles=(\"-\", \"--\", \":\"),\n        )\n\n        # print actual value\n        axarr[1].plot(ampl, c2, marker=\"X\", markersize=7, color=color)\n        axarr[1].set_ylabel(r\"$\\beta$\")\n        axarr[1].set_xlabel(\n            r\"$f_0 / (\\mathrm{TeV} \\, \\mathrm{cm}^{-2} \\, \\mathrm{s}^{-1})$\"\n        )\n\n        extent = [c1_range[0], c1_range[1], c2_range[0], c2_range[1]]\n\n        axarr[2].contour(\n            contours[\"contour_c1_c2\"][\"like_values\"],\n            contours[\"contour_c1_c2\"][\"levels\"],\n            origin=\"lower\",\n            extent=extent,\n            colors=color,\n            linewidths=(2., 1.5, 1.3),\n            linestyles=(\"-\", \"--\", \":\"),\n        )\n\n        # print actual value\n        axarr[2].plot(c1, c2, marker=\"X\", markersize=7, color=color)\n        axarr[2].set_ylabel(r\"$\\beta$\")\n        axarr[2].set_xlabel(r\"$\\Gamma$\")\n\n    # axarr[0,1] is for the legend\n    import matplotlib.lines as mlines\n\n    sigma_1 = mlines.Line2D(\n        [], [], color=\"k\", marker=\"\", ls=\"-\", lw=2., label=r\"1 $\\sigma$ contour\"\n    )\n    sigma_2 = mlines.Line2D(\n        [], [], color=\"k\", marker=\"\", ls=\"--\", lw=1.5, label=r\"2 $\\sigma$ contour\"\n    )\n    sigma_3 = mlines.Line2D(\n        [], [], color=\"k\", marker=\"\", ls=\":\", lw=1.3, label=r\"3 $\\sigma$ contour\"\n    )\n    fermi = mlines.Line2D(\n        [], [], color=\"#21ABCD\", marker=\"\", ls=\"-\", lw=2., label=\"Fermi-LAT\"\n    )\n    magic = mlines.Line2D(\n        [], [], color=\"#FF9933\", marker=\"\", ls=\"-\", lw=2., label=\"MAGIC\"\n    )\n    hess = mlines.Line2D(\n        [], [], color=\"#5A4FCF\", marker=\"\", ls=\"-\", lw=2., label=\"H.E.S.S.\"\n    )\n    fact = mlines.Line2D(\n        [], [], color=\"#5CC184\", marker=\"\", ls=\"-\", lw=2., label=\"FACT\"\n    )\n    veritas = mlines.Line2D(\n        [], [], color=\"#702963\", marker=\"\", ls=\"-\", lw=2., label=\"VERITAS\"\n    )\n    joint = mlines.Line2D(\n        [], [], color=\"crimson\", marker=\"\", ls=\"-\", lw=2., label=\"joint fit\"\n    )\n    axarr[2].legend(\n        handles=[sigma_1, sigma_2, sigma_3, fermi, magic, hess, fact, veritas, joint],\n        loc=3,\n        fontsize=12,\n    )\n    # axarr[2].set_axis_off()\n\n    plt.tight_layout()\n    filename = \"results/figures/sherpa_logparabola_contour.png\"\n    fig.savefig(filename)\n    log.info(f\"Writing {filename}\")\n    fig.savefig(filename)\n\n\ndef plot_iminuit_contours():\n    \"\"\"plot the confidence contours obtained from the sherpa fit\n    \"\"\"\n    log.info(\"plotting parameters contours obtained from iminuit\")\n    # where to take the results, configurations for the individual butterflies\n    instruments = [\"fermi\", \"magic\", \"veritas\", \"fact\", \"hess\", \"joint\"]\n    labels = [\"Fermi-LAT\", \"MAGIC\", \"VERITAS\", \"FACT\", \"H.E.S.S.\", \"joint fit\"]\n    colors = COLORS\n    lss = [\"--\", \"--\", \"--\", \"--\", \"--\", \"-\"]\n\n    fig, axarr = plt.subplots(1, 3, figsize=(16, 5))\n\n    # with one loop we realize all the contour plots\n    for instrument, label, color, ls in zip(instruments, labels, colors, lss):\n        path = config.repo_path / f\"results/fit/gammapy/{instrument}\"\n\n        contours_path = path / \"fit_1.0_sigma_contours_logparabola.npy\"\n        results_path = path / \"fit_results_logparabola.yaml\"\n\n        if not path.exists():\n            log.warning(f\"Missing: {path} . Skipping.\")\n            continue\n\n        # load the contours and the results of the fit\n        contours = np.load(contours_path).tolist()\n        results = load_yaml(results_path)\n        # true values to be plotted\n        amplitude = float(results[\"parameters\"][0][\"value\"])\n        alpha = float(results[\"parameters\"][2][\"value\"])\n        beta = float(results[\"parameters\"][3][\"value\"])\n\n        # amplitude vs alpha\n        amplitude_alpha = contours[\"contour_amplitude_alpha\"]\n        axarr[0].plot(\n            amplitude_alpha[\"amplitude\"] * 10,\n            amplitude_alpha[\"alpha\"],\n            marker=\"\",\n            ls=\"-\",\n            lw=2.5,\n            color=color,\n        )\n        # plot actual value\n        axarr[0].plot(\n            amplitude * 1e11, alpha, marker=\"X\", markersize=7, color=color, lw=2.5\n        )\n        axarr[0].set_xlabel(\n            r\"$\\phi_0 \\,/\\,(10^{-11}\\,{\\rm TeV} \\, {\\rm cm}^{-2} {\\rm s}^{-1})$\",\n            size=FONTSIZE_CONTOURS,\n        )\n        axarr[0].set_ylabel(r\"$\\Gamma$\", size=FONTSIZE_CONTOURS)\n        # make axis thicker\n        for axis in [\"top\", \"bottom\", \"left\", \"right\"]:\n            axarr[0].spines[axis].set_linewidth(2.5)\n        axarr[0].set_yticks([2.2, 2.4, 2.6, 2.8])\n        axarr[0].set_ylim([2.1, 2.9])\n        axarr[0].set_xticks([3, 4, 5])\n        axarr[0].set_xlim([2.8, 5.2])\n        axarr[0].tick_params(\n            \"both\", length=7, width=1.6, which=\"major\", labelsize=FONTSIZE_CONTOURS\n        )\n        axarr[0].tick_params(\n            \"both\", length=4, width=1.6, which=\"minor\", labelsize=FONTSIZE_CONTOURS\n        )\n\n        # amplitude vs beta\n        amplitude_beta = contours[\"contour_amplitude_beta\"]\n        axarr[1].plot(\n            amplitude_beta[\"amplitude\"] * 10,\n            # contour have a scale factor of 1e-10, parameters are in units of 1e-11\n            amplitude_beta[\"beta\"],\n            marker=\"\",\n            ls=\"-\",\n            lw=2.5,\n            color=color,\n        )\n        # plot actual value\n        axarr[1].plot(amplitude * 1e11, beta, marker=\"X\", markersize=7, color=color)\n        axarr[1].set_xlabel(\n            r\"$\\phi_0 \\,/\\,(10^{-11}\\,{\\rm TeV} \\, {\\rm cm}^{-2} {\\rm s}^{-1})$\",\n            size=FONTSIZE_CONTOURS,\n        )\n        axarr[1].set_ylabel(r\"$\\beta$\", size=FONTSIZE_CONTOURS)\n        axarr[1].set_xticks([3, 4, 5])\n        axarr[1].set_xlim([2.8, 5.2])\n        axarr[1].set_yticks([0.2, 0.4, 0.6])\n        axarr[1].set_ylim([0.0, 0.8])\n        # make axis thicker\n        for axis in [\"top\", \"bottom\", \"left\", \"right\"]:\n            axarr[1].spines[axis].set_linewidth(2.5)\n        axarr[1].tick_params(\n            \"both\", length=7, width=1.6, which=\"major\", labelsize=FONTSIZE_CONTOURS\n        )\n        axarr[1].tick_params(\n            \"both\", length=4, width=1.6, which=\"minor\", labelsize=FONTSIZE_CONTOURS\n        )\n\n        # alpha vs beta\n        alpha_beta = contours[\"contour_alpha_beta\"]\n        axarr[2].plot(\n            alpha_beta[\"alpha\"],\n            alpha_beta[\"beta\"],\n            marker=\"\",\n            ls=\"-\",\n            lw=2.5,\n            color=color,\n        )\n        # plot actual value\n        axarr[2].plot(alpha, beta, marker=\"X\", markersize=7, color=color)\n        axarr[2].set_xlabel(r\"$\\Gamma$\", size=FONTSIZE_CONTOURS)\n        axarr[2].set_ylabel(r\"$\\beta$\", size=FONTSIZE_CONTOURS)\n        axarr[2].set_xticks([2.2, 2.4, 2.6, 2.8])\n        axarr[2].set_xlim([2.1, 2.9])\n        axarr[2].set_yticks([0.2, 0.4, 0.6])\n        axarr[2].set_ylim([0.0, 0.8])\n        # make axis thicker\n        for axis in [\"top\", \"bottom\", \"left\", \"right\"]:\n            axarr[2].spines[axis].set_linewidth(2.5)\n        axarr[2].tick_params(\n            \"both\", length=7, width=1.6, which=\"major\", labelsize=FONTSIZE_CONTOURS\n        )\n        axarr[2].tick_params(\n            \"both\", length=4, width=1.6, which=\"minor\", labelsize=FONTSIZE_CONTOURS\n        )\n\n    # legend\n    import matplotlib.lines as mlines\n\n    fermi = mlines.Line2D(\n        [], [], color=COLORS[0], marker=\"\", ls=\"-\", lw=2.5, label=\"Fermi-LAT\"\n    )\n    magic = mlines.Line2D(\n        [], [], color=COLORS[1], marker=\"\", ls=\"-\", lw=2.5, label=\"MAGIC\"\n    )\n    veritas = mlines.Line2D(\n        [], [], color=COLORS[2], marker=\"\", ls=\"-\", lw=2.5, label=\"VERITAS\"\n    )\n    fact = mlines.Line2D(\n        [], [], color=COLORS[3], marker=\"\", ls=\"-\", lw=2.5, label=\"FACT\"\n    )\n    hess = mlines.Line2D(\n        [], [], color=COLORS[4], marker=\"\", ls=\"-\", lw=2.5, label=\"H.E.S.S.\"\n    )\n    joint = mlines.Line2D(\n        [], [], color=COLORS[5], marker=\"\", ls=\"-\", lw=2.5, label=\"joint fit\"\n    )\n\n    box = axarr[2].get_position()\n    axarr[2].set_position([box.x0, box.y0, box.width * 0.97, box.height])\n    # plot the legend on top of the central plot\n    axarr[2].legend(\n        handles=[fermi, magic, veritas, fact, hess, joint],\n        loc=\"center left\",\n        fontsize=FONTSIZE_CONTOURS,\n        bbox_to_anchor=(1., 0.5),\n    )\n\n    plt.tight_layout()\n    filename = \"results/figures/iminuit_logparabola_contour.png\"\n    filename_pdf = \"results/figures/iminuit_logparabola_contour.pdf\"\n    fig.savefig(filename)\n    log.info(f\"Writing {filename}\")\n    fig.savefig(filename)\n    fig.savefig(filename_pdf)\n\n\ndef run_butterfly_stat(which):\n    \"\"\"run the estimation of the butterfly\"\"\"\n    if which in [\"fermi\", \"all\"]:\n        butterfly_stat(\"fermi\")\n    if which in [\"magic\", \"all\"]:\n        butterfly_stat(\"magic\")\n    if which in [\"veritas\", \"all\"]:\n        butterfly_stat(\"veritas\")\n    if which in [\"fact\", \"all\"]:\n        butterfly_stat(\"fact\")\n    if which in [\"hess\", \"all\"]:\n        butterfly_stat(\"hess\")\n    if which in [\"joint\", \"all\"]:\n        butterfly_stat(\"joint\")\n\n\ndef butterfly_stat(which, tool=\"gammapy\"):\n    \"\"\"plot an example figure showing how to correctly estimate a butterfly per each dataset\n    We do it by default with the gammapy (iminuit) results\n    \"\"\"\n    # the sampling in energy shall be consistent with the nbins of the spectrum extraction\n    if which == \"fermi\":\n        num_energy_points = 20\n    else:\n        num_energy_points = 60\n    energies, flux_min, flux_max = stat_errorband(\n        which=which, tool=tool, dim_sample=500, energy_points=num_energy_points, sigma=1\n    )\n\n    # plot best fit model\n    fig, ax = plt.subplots()\n    # best fit parameters for this fit\n    result_file = f\"results/fit/{tool}/{which}/fit_results_logparabola.yaml\"\n    results = load_yaml(result_file)\n\n    parameters = results[\"parameters\"]\n    covariance = results[\"covariance\"]\n\n    # best fit parameters\n    amplitude = parameters[0][\"value\"] * u.Unit(parameters[0][\"unit\"])\n    reference = parameters[1][\"value\"] * u.Unit(parameters[1][\"unit\"])\n    alpha = parameters[2][\"value\"] * u.Unit(parameters[2][\"unit\"])\n    beta = parameters[3][\"value\"] * u.Unit(parameters[3][\"unit\"])\n\n    # gammapy model with best-fit parameters\n    model_lp = Log10Parabola(\n        amplitude=amplitude, reference=reference, alpha=alpha, beta=beta\n    )\n\n    # set the covariance matrix from the output of the fit, this is needed to propagate the error\n    model_lp.parameters.covariance = np.asarray(covariance)\n\n    # plot some model representing the sampling\n    # dictionary from the multivariate sampling\n    path = Path(\n        f\"{config.repo_path}/results/debug/stat-err/{tool}/{which}/multivariate_sampling_fluxes.yaml\"\n    )\n    sampled_dict = load_yaml(path)\n    sampled_amplitude = sampled_dict[\"sampled_amplitude\"]\n    sampled_alpha = sampled_dict[\"sampled_alpha\"]\n    sampled_beta = sampled_dict[\"sampled_beta\"]\n\n    for (_ampl, _alpha, _beta) in zip(\n        sampled_amplitude[:100], sampled_alpha[:100], sampled_beta[:100]\n    ):\n        _amplitude = _ampl * u.Unit(parameters[0][\"unit\"])\n        _alpha = _alpha * u.Unit(parameters[2][\"unit\"])\n        _beta = _beta * u.Unit(parameters[3][\"unit\"])\n\n        _model_lp = Log10Parabola(\n            amplitude=_amplitude, reference=reference, alpha=_alpha, beta=_beta\n        )\n        _model_lp.plot(\n            energy_range=[energies[0], energies[-1]],\n            energy_unit=\"TeV\",\n            flux_unit=\"cm-2 s-1 erg-1\",\n            energy_power=2,\n            color=\"gray\",\n            lw=0.8,\n            alpha=0.8,\n            ax=ax,\n        )\n\n    # plot the 68 % containment correction\n    ax.plot(energies, (energies ** 2 * flux_min).to(\"erg cm-2 s-1\"), color=\"k\", lw=2.5)\n    ax.plot(\n        energies,\n        (energies ** 2 * flux_max).to(\"erg cm-2 s-1\"),\n        color=\"k\",\n        lw=2.5,\n        label=\"68% containment\" + \"\\n\" + \"multivariate sampling\",\n    )\n\n    model_lp.plot(\n        energy_range=[energies[0], energies[-1]],\n        energy_unit=\"TeV\",\n        flux_unit=\"cm-2 s-1 erg-1\",\n        energy_power=2,\n        color=\"k\",\n        lw=2.2,\n        ls=\"--\",\n        label=\"best fit model\",\n        ax=ax,\n    )\n\n    # plt.title(f'{which} dataset')\n    for axis in [\"top\", \"bottom\", \"left\", \"right\"]:\n        ax.spines[axis].set_linewidth(2.)\n    ax.tick_params(\"both\", length=7, width=1.6, which=\"major\", labelsize=FONTSIZE)\n    ax.tick_params(\"both\", length=4, width=1.6, which=\"minor\", labelsize=FONTSIZE)\n    ax.set_ylabel(SED_UNIT_LABEL, size=FONTSIZE)\n    ax.set_xlabel(E_UNIT_LABEL, size=FONTSIZE)\n    ax.set_xscale(\"log\")\n    ax.set_yscale(\"log\")\n    # ax.set_ylim([1e-12, 2e-10])\n    ax.legend(fontsize=FONTSIZE)\n    plt.tight_layout()\n\n    figname = f\"{config.repo_path}/results/figures/stat_err/{tool}_{which}_butterfly_comparison.png\"\n    figname_pdf = f\"{config.repo_path}/results/figures/stat_err/{tool}_{which}_butterfly_comparison.pdf\"\n    logging.info(f\"saving {figname}\")\n    fig.savefig(figname)\n    fig.savefig(figname_pdf)\n\n    log.info(\"making debug plots with histograms of the sampled parameters and fluxes\")\n    fig2, ax2 = plt.subplots(1, 3, sharey=True)\n    nbins_params = int(len(sampled_amplitude) / 20)\n    ax2[0].hist(sampled_amplitude, bins=nbins_params, color=\"lightgray\")\n    ax2[0].axvline(amplitude.value, lw=1.5, color=\"k\")\n    ax2[0].axvline(\n        amplitude.value - np.sqrt(covariance[0][0]), lw=1.5, ls=\"--\", color=\"k\"\n    )\n    ax2[0].axvline(\n        amplitude.value + np.sqrt(covariance[0][0]), lw=1.5, ls=\"--\", color=\"k\"\n    )\n    ax2[0].set_xlabel(\n        r\"$f_0 (\\mathrm{TeV}^{-1} \\, \\mathrm{cm}^{-2} \\, \\mathrm{s}^{-1})$\", labelpad=9\n    )\n\n    ax2[1].hist(sampled_alpha, bins=int(len(sampled_alpha) / 10), color=\"lightgray\")\n    ax2[1].axvline(alpha.value, lw=1.5, color=\"k\")\n    ax2[1].axvline(alpha.value - np.sqrt(covariance[2][2]), lw=1.5, ls=\"--\", color=\"k\")\n    ax2[1].axvline(alpha.value + np.sqrt(covariance[2][2]), lw=1.5, ls=\"--\", color=\"k\")\n    ax2[1].set_xlabel(r\"$\\Gamma$\")\n\n    ax2[2].hist(\n        sampled_beta,\n        bins=int(len(sampled_beta) / 10),\n        color=\"lightgray\",\n        label=\"sampled\",\n    )\n    ax2[2].axvline(beta.value, lw=1.5, color=\"k\", label=\"best fit\")\n    ax2[2].axvline(\n        beta.value - np.sqrt(covariance[3][3]),\n        lw=1.5,\n        ls=\"--\",\n        color=\"k\",\n        label=r\"best fit $\\pm$ 1 $\\sigma$\",\n    )\n    ax2[2].axvline(beta.value + np.sqrt(covariance[3][3]), lw=1.5, ls=\"--\", color=\"k\")\n    ax2[2].legend()\n    ax2[2].set_xlabel(r\"$\\beta$\")\n\n    figname2 = f\"{config.repo_path}/results/figures/stat_err/{tool}_{which}_sampled_parameters.png\"\n    logging.info(f\"saving {figname2}\")\n    fig2.savefig(figname2)\n\n    # sampled fluxes\n    fig3, ax3 = plt.subplots(1, 3, sharey=True, figsize=(12, 8))\n    for i, ene in enumerate([\"emin\", \"emid\", \"emax\"]):\n        flux_dict = sampled_dict[\"sampled_fluxes\"][ene]\n        energy = sampled_dict[\"sampled_fluxes\"][ene][\"value\"] * u.Unit(\n            sampled_dict[\"sampled_fluxes\"][\"energy_unit\"]\n        )\n        log.info(f\"building histogram of sampled fluxes for {energy}\")\n        nbins_fluxes = int(len(flux_dict[\"fluxes\"]) / 20)\n        bins_fluxes = np.logspace(\n            np.log10(np.min(flux_dict[\"fluxes\"])),\n            np.log10(np.max(flux_dict[\"fluxes\"])),\n            nbins_fluxes,\n        )\n        ax3[i].hist(\n            flux_dict[\"fluxes\"],\n            bins=bins_fluxes,\n            color=\"lightgray\",\n            label=\"sampled fluxes\",\n        )\n        ax3[i].axvline(\n            np.mean(flux_dict[\"fluxes\"]),\n            lw=1.5,\n            ls=\"-\",\n            color=\"k\",\n            label=\"mean sampled\",\n        )\n        ax3[i].axvline(\n            flux_dict[\"flux_quantiles\"][0],\n            lw=1.5,\n            ls=\"--\",\n            color=\"k\",\n            label=\"68% containment sampled\",\n        )\n        ax3[i].axvline(flux_dict[\"flux_quantiles\"][1], lw=1.5, ls=\"--\", color=\"k\")\n        ax3[i].set_xlabel(\n            r\"$F (\\mathrm{TeV}^{-1} \\, \\mathrm{cm}^{-2} \\, \\mathrm{s}^{-1})$\",\n            labelpad=9,\n        )\n        # evaluate normal model and error\n        fit_value = model_lp(energy).to(\"TeV-1 cm-2 s-1\").value\n        fit_value_err = model_lp.evaluate_error(energy).to(\"TeV-1 cm-2 s-1\").value\n        ax3[i].axvline(\n            fit_value, lw=2, ls=\"-\", color=\"crimson\", label=\"best fit result\"\n        )\n        ax3[i].axvline(\n            fit_value + fit_value_err[1],\n            lw=1.5,\n            ls=\"--\",\n            color=\"crimson\",\n            label=\"error propagation\",\n        )\n        ax3[i].axvline(fit_value - fit_value_err[1], lw=1.5, ls=\"--\", color=\"crimson\")\n        ax3[i].set_title(\"E = {:.2f}\".format(energy))\n        ax3[i].legend()\n        ax3[i].set_xscale(\"log\")\n\n    plt.tight_layout()\n    figname3 = (\n        f\"{config.repo_path}/results/figures/stat_err/{tool}_{which}_sampled_fluxes.png\"\n    )\n    logging.info(f\"saving {figname3}\")\n    fig3.savefig(figname3)\n\n\ndef counts_histogram(predicted=False):\n    \"\"\"function to plot the excesses per dataset and compare them with the predicted counts\n    if predicted == True will shwo the predicted counts from the results of the fit (for debug purpose)\n    \"\"\"\n    log.info(\"loading the results from the joint fit to predict the counts\")\n    results = load_yaml(\n        f\"{config.repo_path}/results/fit/gammapy/joint/fit_results_logparabola.yaml\"\n    )\n    parameters = results[\"parameters\"]\n\n    model_lp = LogParabola.from_log10(\n        amplitude=parameters[0][\"value\"] * u.Unit(parameters[0][\"unit\"]),\n        reference=parameters[1][\"value\"] * u.Unit(parameters[1][\"unit\"]),\n        alpha=parameters[2][\"value\"] * u.Unit(parameters[2][\"unit\"]),\n        beta=parameters[3][\"value\"] * u.Unit(parameters[3][\"unit\"]),\n    )\n\n    # defining the figure\n    dict_color = {\n        \"fermi\": COLORS[0],\n        \"magic\": COLORS[1],\n        \"veritas\": COLORS[2],\n        \"fact\": COLORS[3],\n        \"hess\": COLORS[4],\n    }\n    fig, ax = plt.subplots()\n\n    for which in config.all_datasets:\n        log.info(f\"predicting counts for {which} dataset\")\n        dataset = config.get_dataset(which)\n        obs = dataset.get_SpectrumObservationList().stack()\n        cts_pred = CountsPredictor(\n            model=model_lp, aeff=obs.aeff, edisp=obs.edisp, livetime=obs.livetime\n        )\n        cts_pred.run()\n\n        e_max = dataset.energy_range[1].to(\"TeV\").value\n        e_min = dataset.energy_range[0].to(\"TeV\").value\n\n        kwargs_mdl = dict(ls=\":\", range=(e_min, e_max), lw=2.2, color=dict_color[which])\n        kwargs_data = dict(\n            ls=\"-\", range=(e_min, e_max), lw=2.2, color=dict_color[which]\n        )\n\n        # CountsSpectrum with observed and predicted excesses\n        ex_pred = cts_pred.npred\n        ex_obs = obs.excess_vector\n        # if it is an IACT rebin the counts before plotting\n        if which != \"fermi\":\n            ex_pred = ex_pred.rebin(2)\n            ex_obs = ex_obs.rebin(2)\n\n        if predicted:  # if you want to display the predicted counts\n            ex_pred.plot_hist(ax, **kwargs_mdl)\n        ex_obs.plot_hist(ax, **kwargs_data)\n\n    # custom legend\n    legend_observed = mlines.Line2D(\n        [], [], color=\"gray\", marker=\"\", ls=\"-\", lw=2, label=\"observed\"\n    )\n    legend_expected = mlines.Line2D(\n        [], [], color=\"gray\", marker=\"\", ls=\":\", lw=2, label=\"expected\"\n    )\n    legend_fermi = mlines.Line2D(\n        [], [], color=COLORS[0], marker=\"\", ls=\"-\", lw=2, label=\"Fermi-LAT\"\n    )\n    legend_magic = mlines.Line2D(\n        [], [], color=COLORS[1], marker=\"\", ls=\"-\", lw=2, label=\"MAGIC\"\n    )\n    legend_veritas = mlines.Line2D(\n        [], [], color=COLORS[2], marker=\"\", ls=\"-\", lw=2, label=\"VERITAS\"\n    )\n    legend_fact = mlines.Line2D(\n        [], [], color=COLORS[3], marker=\"\", ls=\"-\", lw=2, label=\"FACT\"\n    )\n    legend_hess = mlines.Line2D(\n        [], [], color=COLORS[4], marker=\"\", ls=\"-\", lw=2, label=\"H.E.S.S.\"\n    )\n    legend_handles = [\n        legend_fermi,\n        legend_magic,\n        legend_veritas,\n        legend_fact,\n        legend_hess,\n    ]\n    if predicted:  # if you want to display the predicted counts\n        legend_handles = [legend_observed, legend_expected] + legend_handles\n\n    ax.legend(handles=legend_handles, fontsize=FONTSIZE)\n\n    ax.set_xscale(\"log\")\n    ax.set_ylabel(\"Excess counts\", size=FONTSIZE)\n    ax.set_xlabel(E_UNIT_LABEL, size=FONTSIZE)\n\n    # make axis thicker\n    for axis in [\"top\", \"bottom\", \"left\", \"right\"]:\n        ax.spines[axis].set_linewidth(1.6)\n    ax.tick_params(\"both\", length=7, width=1.6, which=\"major\", labelsize=FONTSIZE)\n    ax.tick_params(\"both\", length=4, width=1.6, which=\"minor\", labelsize=FONTSIZE)\n\n    plt.tight_layout()\n\n    filename = f\"{config.repo_path}/results/figures/counts_spectra.png\"\n    filename_pdf = f\"{config.repo_path}/results/figures/counts_spectra.pdf\"\n    log.info(f\"saving figure in {filename}\")\n    fig.savefig(filename)\n    fig.savefig(filename_pdf)\n\n\ndef butterfly_syst():\n    \"\"\"representation of the joint fit result w/ systematics uncertainty\"\"\"\n    log.info(\"plotting syst. + stat. butterfly\")\n    # reading the joint stat butterfly values\n    stat_table_path = Path(\n        f\"{config.repo_path}/results/figures/stat_err/joint_flux_errorband.dat\"\n    )\n    log.info(f\"reading butterfly values from {stat_table_path}\")\n    stat_table = Table.read(stat_table_path, format=\"ascii.ecsv\")\n    stat_energies = stat_table[\"energies\"].data * stat_table[\"energies\"].unit\n    stat_flux_min = stat_table[\"flux_lo\"].data * stat_table[\"flux_lo\"].unit\n    stat_flux_max = stat_table[\"flux_hi\"].data * stat_table[\"flux_hi\"].unit\n    # load result of stat fit\n    stat_result_file = f\"results/fit/gammapy/joint/fit_results_logparabola.yaml\"\n    stat_results = load_yaml(stat_result_file)\n\n    stat_parameters = stat_results[\"parameters\"]\n\n    # best fit parameters\n    stat_amplitude = stat_parameters[0][\"value\"] * u.Unit(stat_parameters[0][\"unit\"])\n    stat_reference = stat_parameters[1][\"value\"] * u.Unit(stat_parameters[1][\"unit\"])\n    stat_alpha = stat_parameters[2][\"value\"] * u.Unit(stat_parameters[2][\"unit\"])\n    stat_beta = stat_parameters[3][\"value\"] * u.Unit(stat_parameters[3][\"unit\"])\n\n    # reading the joint stat butterfly values\n    syst_table_path = Path(\n        f\"{config.repo_path}/results/figures/syst_err/joint_flux_errorband.dat\"\n    )\n    log.info(f\"reading butterfly values from {syst_table_path}\")\n    syst_table = Table.read(syst_table_path, format=\"ascii.ecsv\")\n    syst_energies = syst_table[\"energies\"].data * syst_table[\"energies\"].unit\n    syst_flux_min = syst_table[\"flux_lo\"].data * syst_table[\"flux_lo\"].unit\n    syst_flux_max = syst_table[\"flux_hi\"].data * syst_table[\"flux_hi\"].unit\n\n    # load result of syst fit\n    syst_result_file = (\n        f\"results/fit/gammapy/joint/fit_results_logparabola_energy_scale.yaml\"\n    )\n    syst_results = load_yaml(syst_result_file)\n\n    syst_parameters = syst_results[\"parameters\"]\n\n    # best fit parameters\n    syst_amplitude = syst_parameters[0][\"value\"] * u.Unit(syst_parameters[0][\"unit\"])\n    syst_reference = syst_parameters[1][\"value\"] * u.Unit(syst_parameters[1][\"unit\"])\n    syst_alpha = syst_parameters[2][\"value\"] * u.Unit(syst_parameters[2][\"unit\"])\n    syst_beta = syst_parameters[3][\"value\"] * u.Unit(syst_parameters[3][\"unit\"])\n\n    fig = plt.figure()\n    gs = gridspec.GridSpec(2, 1, height_ratios=[2.5, 1], wspace=0.)\n    ax0 = plt.subplot(gs[0])\n    ax1 = plt.subplot(gs[1], sharex=ax0)\n\n    ax0.fill_between(\n        syst_energies.to(\"TeV\"),\n        (syst_energies ** 2 * syst_flux_min).to(\"erg cm-2 s-1\"),\n        (syst_energies ** 2 * syst_flux_max).to(\"erg cm-2 s-1\"),\n        color=\"#002E63\",\n        alpha=0.4,\n        label=\"stat. + syst.\",\n    )\n\n    ax0.fill_between(\n        stat_energies.to(\"TeV\"),\n        (stat_energies ** 2 * stat_flux_min).to(\"erg cm-2 s-1\"),\n        (stat_energies ** 2 * stat_flux_max).to(\"erg cm-2 s-1\"),\n        color=\"crimson\",\n        alpha=0.4,\n        label=\"stat. only\",\n    )\n\n    stat_flux = Log10Parabola.evaluate(\n        stat_energies, stat_amplitude, stat_reference, stat_alpha, stat_beta\n    )\n\n    ax0.plot(\n        stat_energies.to(\"TeV\"),\n        (stat_energies ** 2 * stat_flux).to(\"erg cm-2 s-1\"),\n        color=\"crimson\",\n        lw=2.2,\n        ls=\"-\",\n    )\n\n    syst_flux = Log10Parabola.evaluate(\n        syst_energies, syst_amplitude, syst_reference, syst_alpha, syst_beta\n    )\n\n    ax0.plot(\n        syst_energies.to(\"TeV\"),\n        (syst_energies ** 2 * syst_flux).to(\"erg cm-2 s-1\"),\n        color=\"#002E63\",\n        lw=2.2,\n        ls=\"-\",\n    )\n\n    ax0.set_xscale(\"log\")\n    ax0.set_yscale(\"log\")\n    ax0.set_ylabel(SED_UNIT_LABEL, size=FONTSIZE)\n    ax0.legend(fontsize=FONTSIZE, loc=3)\n    # make axis thicker\n    for axis in [\"top\", \"bottom\", \"left\", \"right\"]:\n        ax0.spines[axis].set_linewidth(1.6)\n    ax0.tick_params(\"both\", length=7, width=1.6, which=\"major\", labelsize=FONTSIZE)\n    ax0.tick_params(\"both\", length=4, width=1.6, which=\"minor\", labelsize=FONTSIZE)\n\n    # plot the flux ratios\n    ax1.fill_between(\n        syst_energies.to(\"TeV\"),\n        (syst_flux_min - stat_flux) / stat_flux,\n        (syst_flux_max - stat_flux) / stat_flux,\n        color=\"#002E63\",\n        alpha=0.4,\n        label=\"stat. + syst.\",\n    )\n\n    ax1.fill_between(\n        stat_energies.to(\"TeV\"),\n        (stat_flux_min - stat_flux) / stat_flux,\n        (stat_flux_max - stat_flux) / stat_flux,\n        color=\"crimson\",\n        alpha=0.4,\n        label=\"stat. only\",\n    )\n\n    ax1.plot(\n        stat_energies.to(\"TeV\"),\n        (stat_flux - stat_flux) / stat_flux,\n        color=\"crimson\",\n        lw=2.2,\n        ls=\"-\",\n    )\n\n    ax1.plot(\n        syst_energies.to(\"TeV\"),\n        (syst_flux - stat_flux) / stat_flux,\n        color=\"#002E63\",\n        lw=2.2,\n        ls=\"-\",\n    )\n\n    ax1.set_xscale(\"log\")\n    ax1.set_ylim([-0.35, 0.35])\n    ax1.set_xlabel(E_UNIT_LABEL, size=FONTSIZE)\n    ax1.set_ylabel(\"fractional diff. \\n to stat.\", size=FONTSIZE)\n    # make axis thicker\n    for axis in [\"top\", \"bottom\", \"left\", \"right\"]:\n        ax1.spines[axis].set_linewidth(1.6)\n    ax1.tick_params(\"both\", length=7, width=1.6, which=\"major\", labelsize=FONTSIZE)\n    ax1.tick_params(\"both\", length=4, width=1.6, which=\"minor\", labelsize=FONTSIZE)\n\n    plt.tight_layout()\n\n    filename = \"results/figures/crab_sed_joint_fit_syst.png\"\n    filename_pdf = \"results/figures/crab_sed_joint_fit_syst.pdf\"\n    log.info(f\"Writing {filename}\")\n    fig.savefig(filename)\n    fig.savefig(filename_pdf)\n\n\ndef syst_contour():\n    \"\"\"plot a comparison of the contours obtained with the wstat statistics\n    and with the stat + syst likelihood\"\"\"\n\n    fig, axarr = plt.subplots(1, 3, figsize=(16, 5))\n\n    # first plot in light gray the stat contours\n    instruments = [\"fermi\", \"magic\", \"veritas\", \"fact\", \"hess\", \"joint\"]\n\n    # with one loop we realize all the contour plots\n    color = \"lightgray\"\n    for instrument in instruments:\n        path = f\"{config.repo_path}/results/fit/gammapy/{instrument}\"\n\n        contours_path = f\"{path}/fit_1.0_sigma_contours_logparabola.npy\"\n        results_path = f\"{path}/fit_results_logparabola.yaml\"\n\n        # load the contours and the results of the fit\n        contours = np.load(contours_path).tolist()\n        results = load_yaml(results_path)\n        # true values to be plotted\n        amplitude = float(results[\"parameters\"][0][\"value\"])\n        alpha = float(results[\"parameters\"][2][\"value\"])\n        beta = float(results[\"parameters\"][3][\"value\"])\n\n        # amplitude vs alpha\n        amplitude_alpha = contours[\"contour_amplitude_alpha\"]\n        axarr[0].plot(\n            amplitude_alpha[\"amplitude\"] * 10,\n            amplitude_alpha[\"alpha\"],\n            marker=\"\",\n            ls=\"-\",\n            lw=2.5,\n            color=color,\n        )\n        # plot actual value\n        axarr[0].plot(\n            amplitude * 1e11, alpha, marker=\"X\", markersize=7, color=color, lw=2.5\n        )\n\n        # amplitude vs beta\n        amplitude_beta = contours[\"contour_amplitude_beta\"]\n        axarr[1].plot(\n            amplitude_beta[\"amplitude\"] * 10,\n            # contour have a scale factor of 1e-10, parameters are in units of 1e-11\n            amplitude_beta[\"beta\"],\n            marker=\"\",\n            ls=\"-\",\n            lw=2.5,\n            color=color,\n        )\n        # plot actual value\n        axarr[1].plot(amplitude * 1e11, beta, marker=\"X\", markersize=7, color=color)\n\n        # alpha vs beta\n        alpha_beta = contours[\"contour_alpha_beta\"]\n        axarr[2].plot(\n            alpha_beta[\"alpha\"],\n            alpha_beta[\"beta\"],\n            marker=\"\",\n            ls=\"-\",\n            lw=2.5,\n            color=color,\n        )\n        # plot actual value\n        axarr[2].plot(alpha, beta, marker=\"X\", markersize=7, color=color)\n\n    # plotting stat vs syst result on top of instrument-wise contours in gray\n    path = config.repo_path / f\"results/fit/gammapy/joint\"\n\n    stat_contours_path = f\"{path}/fit_1.0_sigma_contours_logparabola.npy\"\n    stat_results_path = f\"{path}/fit_results_logparabola.yaml\"\n\n    syst_contours_path = f\"{path}/fit_1.0_sigma_contours_logparabola_energy_scale.npy\"\n    syst_results_path = f\"{path}/fit_results_logparabola_energy_scale.yaml\"\n\n    for (contours_path, results_path, color, label) in zip(\n        [stat_contours_path, syst_contours_path],\n        [stat_results_path, syst_results_path],\n        [\"crimson\", \"#002E63\"],\n        [\"stat. only\", \"stat. + syst.\"],\n    ):\n        # load the contours and the results of the fit\n        contours = np.load(contours_path).tolist()\n        results = load_yaml(results_path)\n        # true values to be plotted\n        amplitude = float(results[\"parameters\"][0][\"value\"])\n        alpha = float(results[\"parameters\"][2][\"value\"])\n        beta = float(results[\"parameters\"][3][\"value\"])\n\n        # amplitude vs alpha\n        amplitude_alpha = contours[\"contour_amplitude_alpha\"]\n        if label == \"stat. only\":\n            axarr[0].plot(\n                amplitude_alpha[\"amplitude\"] * 10,\n                # gammapy contour have a scale factor of 1e-10, parameters are in units of 1e-11\n                amplitude_alpha[\"alpha\"],\n                marker=\"\",\n                ls=\"-\",\n                lw=2.5,\n                color=color,\n            )\n        else:\n            axarr[0].plot(\n                amplitude_alpha[\"amplitude\"] * 1e11,\n                amplitude_alpha[\"alpha\"],\n                marker=\"\",\n                ls=\"-\",\n                lw=2.5,\n                color=color,\n            )\n\n        # plot actual value\n        axarr[0].plot(\n            amplitude * 1e11, alpha, marker=\"X\", markersize=7, color=color, lw=2.5\n        )\n\n        # amplitude vs beta\n        amplitude_beta = contours[\"contour_amplitude_beta\"]\n        if label == \"stat. only\":\n            axarr[1].plot(\n                amplitude_beta[\"amplitude\"] * 10,\n                # gammapy contour have a scale factor of 1e-10, parameters are in units of 1e-11\n                amplitude_beta[\"beta\"],\n                marker=\"\",\n                ls=\"-\",\n                lw=2.5,\n                color=color,\n            )\n        else:\n            axarr[1].plot(\n                amplitude_beta[\"amplitude\"] * 1e11,\n                amplitude_beta[\"beta\"],\n                marker=\"\",\n                ls=\"-\",\n                lw=2.5,\n                color=color,\n            )\n\n        # plot actual value\n        axarr[1].plot(amplitude * 1e11, beta, marker=\"X\", markersize=7, color=color)\n\n        # alpha vs beta\n        alpha_beta = contours[\"contour_alpha_beta\"]\n        axarr[2].plot(\n            alpha_beta[\"alpha\"],\n            alpha_beta[\"beta\"],\n            marker=\"\",\n            ls=\"-\",\n            lw=2.5,\n            color=color,\n        )\n        # plot actual value\n        axarr[2].plot(alpha, beta, marker=\"X\", markersize=7, color=color)\n\n    # legend\n    import matplotlib.lines as mlines\n\n    stat_label = mlines.Line2D(\n        [],\n        [],\n        color=\"crimson\",\n        marker=\"\",\n        ls=\"-\",\n        lw=2.5,\n        label=\"joint fit \\n stat. only\",\n    )\n    syst_label = mlines.Line2D(\n        [],\n        [],\n        color=\"#002E63\",\n        marker=\"\",\n        ls=\"-\",\n        lw=2.5,\n        label=\"joint fit \\n stat. + syst.\",\n    )\n    single_label = mlines.Line2D(\n        [],\n        [],\n        color=\"lightgray\",\n        marker=\"\",\n        ls=\"-\",\n        lw=2.5,\n        label=\"instr. fit \\n stat. only\",\n    )\n\n    axarr[0].set_xlabel(\n        r\"$\\phi_0 \\,/\\,(10^{-11}\\,{\\rm TeV} \\, {\\rm cm}^{-2} {\\rm s}^{-1})$\",\n        size=FONTSIZE_CONTOURS,\n    )\n    axarr[0].set_ylabel(r\"$\\Gamma$\", size=FONTSIZE_CONTOURS)\n    # make axis thicker\n    axarr[0].set_yticks([2.2, 2.4, 2.6, 2.8])\n    axarr[0].set_ylim([2.1, 2.9])\n    axarr[0].set_xticks([3, 4, 5])\n    axarr[0].set_xlim([2.8, 5.2])\n    for axis in [\"top\", \"bottom\", \"left\", \"right\"]:\n        axarr[0].spines[axis].set_linewidth(2.5)\n    axarr[0].tick_params(\n        \"both\", length=7, width=1.6, which=\"major\", labelsize=FONTSIZE_CONTOURS\n    )\n    axarr[0].tick_params(\n        \"both\", length=4, width=1.6, which=\"minor\", labelsize=FONTSIZE_CONTOURS\n    )\n\n    axarr[1].set_xlabel(\n        r\"$\\phi_0 \\,/\\,(10^{-11}\\,{\\rm TeV} \\, {\\rm cm}^{-2} {\\rm s}^{-1})$\",\n        size=FONTSIZE_CONTOURS,\n    )\n    axarr[1].set_ylabel(r\"$\\beta$\", size=FONTSIZE_CONTOURS)\n    # make axis thicker\n    axarr[1].set_xticks([3, 4, 5])\n    axarr[1].set_xlim([2.8, 5.2])\n    axarr[1].set_yticks([0.2, 0.4, 0.6])\n    axarr[1].set_ylim([0.0, 0.8])\n    for axis in [\"top\", \"bottom\", \"left\", \"right\"]:\n        axarr[1].spines[axis].set_linewidth(2.5)\n    axarr[1].tick_params(\n        \"both\", length=7, width=1.6, which=\"major\", labelsize=FONTSIZE_CONTOURS\n    )\n    axarr[1].tick_params(\n        \"both\", length=4, width=1.6, which=\"minor\", labelsize=FONTSIZE_CONTOURS\n    )\n\n    axarr[2].set_xlabel(r\"$\\Gamma$\", size=FONTSIZE_CONTOURS)\n    axarr[2].set_ylabel(r\"$\\beta$\", size=FONTSIZE_CONTOURS)\n    axarr[2].set_xticks([2.2, 2.4, 2.6, 2.8])\n    axarr[2].set_xlim([2.1, 2.9])\n    axarr[2].set_yticks([0.2, 0.4, 0.6])\n    axarr[2].set_ylim([0.0, 0.8])\n    # make axis thicker\n    for axis in [\"top\", \"bottom\", \"left\", \"right\"]:\n        axarr[2].spines[axis].set_linewidth(2.5)\n    axarr[2].tick_params(\n        \"both\", length=7, width=1.6, which=\"major\", labelsize=FONTSIZE_CONTOURS\n    )\n    axarr[2].tick_params(\n        \"both\", length=4, width=1.6, which=\"minor\", labelsize=FONTSIZE_CONTOURS\n    )\n\n    box = axarr[2].get_position()\n    axarr[2].set_position([box.x0, box.y0, box.width * 0.97, box.height])\n    # plot the legend on top of the central plot\n    axarr[2].legend(\n        handles=[stat_label, syst_label, single_label],\n        loc=\"center left\",\n        fontsize=FONTSIZE_CONTOURS,\n        bbox_to_anchor=(1., 0.5),\n    )\n\n    plt.tight_layout()\n    filename = \"results/figures/iminuit_logparabola_energy_scale_contour.png\"\n    filename_pdf = \"results/figures/iminuit_logparabola_energy_scale_contour.pdf\"\n    fig.savefig(filename)\n    log.info(f\"Writing {filename}\")\n    fig.savefig(filename)\n    fig.savefig(filename_pdf)\n", "meta": {"hexsha": "31aa639c9883f2b0ccda5c07050896ffd338a5dd", "size": 43883, "ext": "py", "lang": "Python", "max_stars_repo_path": "joint_crab/figures.py", "max_stars_repo_name": "Bultako/public-joint-crab", "max_stars_repo_head_hexsha": "2efcfa423b4ab682c8a28398d2bd04e5582616a1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "joint_crab/figures.py", "max_issues_repo_name": "Bultako/public-joint-crab", "max_issues_repo_head_hexsha": "2efcfa423b4ab682c8a28398d2bd04e5582616a1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "joint_crab/figures.py", "max_forks_repo_name": "Bultako/public-joint-crab", "max_forks_repo_head_hexsha": "2efcfa423b4ab682c8a28398d2bd04e5582616a1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1908580593, "max_line_length": 104, "alphanum_fraction": 0.5807032336, "include": true, "reason": "import numpy,from astropy", "num_tokens": 12555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.1973448446340028}}
{"text": "import torch.nn as nn\nimport torch.nn.functional as F\nimport torch\n\nimport numpy as np\n\n\n    \ndef model_box_to_xy_ori(box,ori_im_shape,prior_w = 0.5, prior_cx=0.5, prior_cy=0.5,size_variance = 0.1,center_variance = 0.1):\n    \n    box[:,0] = (box[:,0] * center_variance +  prior_cx * 2.0)/2.0\n    box[:,1] = (box[:,1] * center_variance +  prior_cy * 2.0)/2.0\n    box[:,2] = torch.exp(box[:,2] * size_variance) * prior_w\n    box[:,3] = torch.exp(box[:,3] * size_variance) * prior_w\n    \n    box_numpy = box.cpu().numpy()\n    \n    box_xyxy = np.zeros((box_numpy.shape[0],4),dtype = 'float32')\n    \n    \n    \n    \n    box_xyxy[:,0] = box_numpy[:,0] - box_numpy[:,2]/2.0\n    box_xyxy[:,1] = box_numpy[:,1] - box_numpy[:,3]/2.0\n    box_xyxy[:,2] = box_numpy[:,0] + box_numpy[:,2]/2.0\n    box_xyxy[:,3] = box_numpy[:,1] + box_numpy[:,3]/2.0\n    \n    return box_xyxy\n\ndef model_box_to_xy_ori_l1(box):\n    \n    \n    \n    box_numpy = box.cpu().numpy()\n    \n    box_xyxy = np.zeros((box_numpy.shape[0],4),dtype = 'float32')\n    \n    \n    \n    \n    box_xyxy[:,0] = box_numpy[:,0] - box_numpy[:,2]/2.0\n    box_xyxy[:,1] = box_numpy[:,1] - box_numpy[:,3]/2.0\n    box_xyxy[:,2] = box_numpy[:,0] + box_numpy[:,2]/2.0\n    box_xyxy[:,3] = box_numpy[:,1] + box_numpy[:,3]/2.0\n    \n    return box_xyxy\n\n\ndef norm_box_to_abs(box_norm,ori_im_shape):\n    box = box_norm.copy()\n    box[0] *=ori_im_shape[1]\n    box[1] *=ori_im_shape[0]\n    box[2] *=ori_im_shape[1]\n    box[3] *=ori_im_shape[0]\n    return box\n\n\ndef area_of(left_top, right_bottom) -> torch.Tensor:\n    \"\"\"Compute the areas of rectangles given two corners.\n\n    Args:\n        left_top (N, 2): left top corner.\n        right_bottom (N, 2): right bottom corner.\n\n    Returns:\n        area (N): return the area.\n    \"\"\"\n    hw = torch.clamp(right_bottom - left_top, min=0.0)\n    return hw[..., 0] * hw[..., 1]\n\n\ndef iou_of(boxes0, boxes1, eps=1e-5):\n    \"\"\"Return intersection-over-union (Jaccard index) of boxes.\n\n    Args:\n        boxes0 (N, 4): ground truth boxes.\n        boxes1 (N or 1, 4): predicted boxes.\n        eps: a small number to avoid 0 as denominator.\n    Returns:\n        iou (N): IoU values.\n    \"\"\"\n    overlap_left_top = torch.max(boxes0[..., :2], boxes1[..., :2])\n    overlap_right_bottom = torch.min(boxes0[..., 2:], boxes1[..., 2:])\n\n    overlap_area = area_of(overlap_left_top, overlap_right_bottom)\n    area0 = area_of(boxes0[..., :2], boxes0[..., 2:])\n    area1 = area_of(boxes1[..., :2], boxes1[..., 2:])\n    return overlap_area / (area0 + area1 - overlap_area + eps)\n\n    \n    \ndef iou_ori(box_pred,box_gt,ori_im_shape):\n    # one box input\n    b_pred = torch.from_numpy(box_pred)\n    b_gt = torch.from_numpy(box_gt)\n    \n    \n    \n    b_gt[:,0] *=ori_im_shape[1]\n    b_gt[:,1] *=ori_im_shape[0]\n    b_gt[:,2] *=ori_im_shape[1]\n    b_gt[:,3] *=ori_im_shape[0]\n\n    b_pred[:,0] *=ori_im_shape[1]\n    b_pred[:,1] *=ori_im_shape[0]\n    b_pred[:,2] *=ori_im_shape[1]\n    b_pred[:,3] *=ori_im_shape[0]\n\n\n    return iou_of(b_pred,b_gt)\n    \n\n\n#class Location_Box_Loss(nn.Module):\n#    def __init__(self,prior_w = 0.5, prior_cx=0.5, prior_cy=0.5,size_variance = 0.1,center_variance = 0.1):\n#        \"\"\"Implement Loss of box locolization\n#\n#        smooth L1 regression loss.\n#        \"\"\"\n#        super(Location_Box_Loss, self).__init__()\n#        self.prior_w = prior_w\n#        \n#        self.prior_cx = prior_cx\n#        self.prior_cy = prior_cy\n#        \n#        self.size_variance = size_variance\n#        self.center_variance = center_variance\n#\n#    def forward(self, gt_box, predicted_vec):\n#        \"\"\"\n#        # predicted_vec  x_center(-1,1)  /center_variance\n#                         y_center(-1,1) /center_variance\n#                         w ( -inf, inf)  0-1x, 1-2.7x -1 -0.36x  /size_variance\n#        \"\"\"\n#        ww_gt = gt_box[:,2] - gt_box[:,0]\n#        ww_gt_tr   = torch.log(ww_gt/self.prior_w)/self.size_variance\n#        \n#        hh_gt = gt_box[:,3] - gt_box[:,1]\n#        hh_gt_tr   = torch.log(hh_gt/self.prior_w)/self.size_variance\n#        \n#        xx_gt_tr = ((gt_box[:,2] + gt_box[:,0]) - self.prior_cx * 2.0)/ self.center_variance   # (0.1) -> (-1,1)        \n#        yy_gt_tr = ((gt_box[:,3] + gt_box[:,1]) - self.prior_cy * 2.0)/ self.center_variance   # (0.1) -> (-1,1)        \n#        \n#        loss_xx = F.smooth_l1_loss(predicted_vec[:,0], xx_gt_tr, size_average=True) \n#        loss_yy = F.smooth_l1_loss(predicted_vec[:,1], yy_gt_tr, size_average=True) \n#        \n#        loss_ww = F.smooth_l1_loss(predicted_vec[:,2], ww_gt_tr, size_average=True) \n#        loss_hh = F.smooth_l1_loss(predicted_vec[:,3], hh_gt_tr, size_average=True) \n#        \n#        \n#        loss = loss_xx + loss_yy +  loss_ww + loss_hh\n#        return loss,loss_xx,loss_yy,loss_ww,loss_hh\n\n    \n\n\nclass Location_Box_Loss(nn.Module):\n    def __init__(self,prior_w = 0.5, prior_cx=0.5, prior_cy=0.5,size_variance = 0.1,center_variance = 0.1):\n        \"\"\"Implement Loss of box locolization\n\n        smooth L1 regression loss.\n        \"\"\"\n        super(Location_Box_Loss, self).__init__()\n        self.prior_w = prior_w\n        \n        self.prior_cx = prior_cx\n        self.prior_cy = prior_cy\n        \n        self.size_variance = size_variance\n        self.center_variance = center_variance\n\n    def forward(self, gt_box, predicted_vec):\n        \"\"\"\n        # predicted_vec  x_center(-1,1)  /center_variance\n                         y_center(-1,1) /center_variance\n                         w ( -inf, inf)  0-1x, 1-2.7x -1 -0.36x  /size_variance\n        \"\"\"\n        ww_gt = gt_box[:,2] - gt_box[:,0] # (0,1)\n        #ww_gt_tr   = torch.log(ww_gt/self.prior_w)/self.size_variance\n        \n        hh_gt = gt_box[:,3] - gt_box[:,1]\n        #hh_gt_tr   = torch.log(hh_gt/self.prior_w)/self.size_variance\n        \n        xx_gt_tr = (gt_box[:,2] + gt_box[:,0])/2.0  #(0.1) \n        yy_gt_tr = (gt_box[:,3] + gt_box[:,1])/2.0   # (0.1)         \n        \n        #loss_xx = F.smooth_l1_loss(predicted_vec[:,0], xx_gt_tr, size_average=True) \n        #loss_yy = F.smooth_l1_loss(predicted_vec[:,1], yy_gt_tr, size_average=True) \n        \n        #loss_ww = F.smooth_l1_loss(predicted_vec[:,2], ww_gt, size_average=True) \n        #loss_hh = F.smooth_l1_loss(predicted_vec[:,3], hh_gt, size_average=True) \n  \n        \n        loss_xx = F.l1_loss(predicted_vec[:,0], xx_gt_tr, size_average=True) \n        loss_yy = F.l1_loss(predicted_vec[:,1], yy_gt_tr, size_average=True) \n        \n        loss_ww = F.l1_loss(predicted_vec[:,2], ww_gt, size_average=True) \n        loss_hh = F.l1_loss(predicted_vec[:,3], hh_gt, size_average=True)       \n        \n        loss = loss_xx + loss_yy +  loss_ww + loss_hh\n        return loss,loss_xx,loss_yy,loss_ww,loss_hh\n\n\n\nclass Location_Box_CenterNet(nn.Module):\n    def __init__(self):\n        \"\"\"Implement Loss of box locolization\n\n        hm focal-loss xywh L1 regression loss.\n        \"\"\"\n        super(Location_Box_CenterNet, self).__init__()\n\n\n    def forward(self, gt_box, pred):\n        \n       #score\n       hm = gt_box['hm'] \n       pred_s = pred[:,0:1,...]\n       pos_inds = hm.eq(1).float()\n       neg_inds = hm.lt(1).float()\n\n       neg_weights = torch.pow(1.0 - hm, 4)\n       pos_loss = torch.log(pred_s) * torch.pow(1 - pred_s, 2) * pos_inds\n       neg_loss = torch.log(1 - pred_s) * torch.pow(pred_s, 2) * neg_weights * neg_inds\n\n       num_pos  = pos_inds.float().sum()\n       pos_loss = pos_loss.sum()\n       neg_loss = neg_loss.sum()\n       \n       loss_s = -(pos_loss + neg_loss) / num_pos\n\n  \n\n       dense_xy = gt_box['dense_xy']\n       dense_wh = gt_box['dense_wh']\n       dense_mask = gt_box['dense_mask']\n       pred_xy = pred[:,1:3,...]\n       pred_wh = pred[:,3:,...]\n\n     \n       loss_xy = F.l1_loss(pred_xy*dense_mask,dense_xy*dense_mask,size_average=False) / num_pos\n       loss_wh = F.l1_loss(pred_wh*dense_mask,dense_wh*dense_mask,size_average=False) / num_pos\n       \n       loss = loss_s + loss_xy + loss_wh\n       return loss,loss_s,loss_xy,loss_wh\n\n\n", "meta": {"hexsha": "22fe822ce78d18976d7207d02c2126acd41071d5", "size": 7988, "ext": "py", "lang": "Python", "max_stars_repo_path": "modeling/location_box_loss.py", "max_stars_repo_name": "zyxwvu321/Classifer_SSL_Longtail", "max_stars_repo_head_hexsha": "e6c09414c49e695b0f4221a3c6245ae3929a1788", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modeling/location_box_loss.py", "max_issues_repo_name": "zyxwvu321/Classifer_SSL_Longtail", "max_issues_repo_head_hexsha": "e6c09414c49e695b0f4221a3c6245ae3929a1788", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modeling/location_box_loss.py", "max_forks_repo_name": "zyxwvu321/Classifer_SSL_Longtail", "max_forks_repo_head_hexsha": "e6c09414c49e695b0f4221a3c6245ae3929a1788", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2096774194, "max_line_length": 126, "alphanum_fraction": 0.5846269404, "include": true, "reason": "import numpy", "num_tokens": 2470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.1973448446340028}}
{"text": "#!/usr/bin/env python\n\n\"\"\"\"\nSimple implementation of http://arxiv.org/pdf/1502.04623v2.pdf in TensorFlow\n\nExample Usage: \n  python train.py --data_file=<TFRecord_file_path> --log_dir=<log_data_path>\n\nAuthor: Anurag Vempati\n\"\"\"\n\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport sys\nimport math\nimport time\nfrom tqdm import tqdm\nfrom config import train_config\nfrom model import DrawModel\n\ntf.flags.DEFINE_string(\"data_file\", \"\", \"\")\ntf.flags.DEFINE_string(\"log_dir\", \"\", \"\")\nFLAGS = tf.flags.FLAGS\n\n\ndef export_config(config, output_file):\n  \"\"\"\n  Write the configuration parameters into a human readable file.\n  :param config: the configuration dictionary\n  :param output_file: the output text file\n  \"\"\"\n  if not output_file.endswith('.txt'):\n      output_file.append('.txt')\n  max_key_length = np.amax([len(k) for k in config.keys()])\n  with open(output_file, 'w') as f:\n      for k in sorted(config.keys()):\n          out_string = '{:<{width}}: {}\\n'.format(k, config[k], width=max_key_length)\n          f.write(out_string)\n\n          \ndef load_data(config, data_file):\n  print('Loading data from {} ...'.format(data_file))\n\n  # Reads an image from a file, decodes it into a dense tensor, and resizes it\n  # to a fixed shape.\n  def _parse_function(filename):\n    data_fmt = {\n      \"height\": tf.FixedLenFeature((), tf.int64, -1),\n      \"width\": tf.FixedLenFeature((), tf.int64, -1),\n      \"depth\": tf.FixedLenFeature((), tf.int64, -1),\n      \"image_raw\": tf.FixedLenFeature((), tf.string, \"\")\n    }\n    \n    parsed_data = tf.parse_single_example(filename, data_fmt)\n    image_gray = tf.image.decode_jpeg(parsed_data[\"image_raw\"], channels=1)\n    image_converted = tf.image.convert_image_dtype(image_gray, tf.float32)\n    image_resized = tf.image.resize_images(image_converted, [config['A'], config['B']])\n    image_flattened = tf.reshape(image_resized, [-1])\n    return_image = image_flattened\n    if not config['draw_with_white']:\n      return_image = 1.0 - image_flattened\n    return_image = tf.clip_by_value(return_image, 0.0, 0.99)  # for numeric stability during arctanh() operation\n    return return_image\n\n  if not os.path.exists(data_file):\n    print(\"Data TFRecord not found\")\n    sys.exit()\n  \n  data_files = tf.data.Dataset.list_files(data_file)\n  dataset = data_files.interleave(tf.data.TFRecordDataset, cycle_length=2)\n  dataset = dataset.map(map_func=_parse_function, num_parallel_calls=4)\n  epoch_counter = tf.data.TFRecordDataset.range(config['n_epochs'])\n  dataset = epoch_counter.flat_map(lambda i: tf.data.Dataset.zip(\n    (dataset, tf.data.Dataset.from_tensors(i).repeat())))\n  dataset = dataset.repeat()\n  dataset = dataset.batch(config['batch_size'])\n  dataset = dataset.prefetch(buffer_size=config['batch_size'])\n  dataset_iterator = dataset.make_one_shot_iterator()\n  next_data_batch = dataset_iterator.get_next()\n  \n  return next_data_batch\n\n\ndef get_model_and_placeholders(config):\n    # create placeholders that we need to feed the required data into the model\n    input_pl = tf.placeholder(tf.float32, shape=(config['batch_size'], config['img_size']))\n    canvas_pl = tf.placeholder(tf.float32, shape=(config['batch_size'], config['img_size']))\n    placeholders = {'input_pl': input_pl,\n                    'canvas_pl': canvas_pl}\n    return DrawModel, placeholders\n\n\ndef main(config):\n  # create unique output directory for this model\n  timestamp = str(int(time.time()))\n  config['model_dir'] = os.path.abspath(os.path.join(FLAGS.log_dir, 'DRAW' + '_' + timestamp))\n  os.makedirs(config['model_dir'])\n  print('Logging data to {}'.format(config['model_dir']))\n  \n  # Export configuration for the current run\n  export_config(config, os.path.join(config['model_dir'], 'config.txt'))\n  \n  # load the data\n  next_data_batch = load_data(config, FLAGS.data_file)\n\n  # get input placeholders and get the model that we want to train\n  draw_model_class, placeholders = get_model_and_placeholders(config)\n  \n  # create a training graph, this is the graph we will use to optimize the parameters\n  print('Building training graph')\n  with tf.name_scope('training'):\n    draw_model = draw_model_class(config, placeholders, mode='training', annealing_schedules=config['annealing_schedules'])\n    draw_model.build_graph()\n    print('created DRAW model with {} parameters'.format(draw_model.n_parameters))\n      \n  print('Building valid graph')\n  with tf.name_scope('validation'):\n    draw_model_valid = draw_model_class(config, placeholders, mode='validation', annealing_schedules=config['annealing_schedules'])\n    draw_model_valid.build_graph()\n    print('Finished Building valid graphs')\n    \n  with tf.Session() as sess:\n    # Add the ops to initialize variables.\n    init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())\n    # Actually intialize the variables\n    sess.run(init_op)\n    \n    # Summaries\n    training_summaries = tf.summary.merge(tf.get_collection('training_summaries'))\n    train_writer = tf.summary.FileWriter(config['model_dir'] + '/summary/train', sess.graph)\n    valid_summaries = tf.summary.merge(tf.get_collection('validation_summaries'))\n    valid_writer = tf.summary.FileWriter(config['model_dir'] + '/summary/validation', sess.graph)\n    \n    # create a saver for writing training checkpoints\n    saver = tf.train.Saver(var_list=tf.trainable_variables(), max_to_keep=50)\n\n    # start training\n    draw_T = config['T']\n#     lowest_test_loss = 1.0e6\n    last_saved_epoch = 0  # epoch corresponding to last saved chkpnt\n    iteration = 0\n    previous_epoch = 0\n    epoch = 0\n    with tqdm() as pbar:\n      while epoch < config['n_epochs']:\n        # Next data batch\n        previous_epoch = epoch\n        xnext, epoch = sess.run(next_data_batch)\n        epoch = epoch[0]\n        if (previous_epoch > 0 and epoch == 0): break\n        \n        step = tf.train.global_step(sess, draw_model.global_step)\n  \n        # Hot start\n        if config['use_hot_start']:\n          crop_fraction = (epoch + 1) * config['crop_fraction_increase_rate']\n          if crop_fraction >= 1.0:\n            cnext = np.zeros([config['batch_size'], config['img_size']])\n            draw_T = config['T']\n          else:\n            xnext_reshaped = np.copy(xnext)\n            xnext_reshaped = xnext_reshaped.reshape((config['batch_size'], config['B'], config['A']))\n            start_row = np.random.randint(config['B'] * (1 - crop_fraction))  # , size=config['batch_size'])\n            start_col = np.random.randint(config['A'] * (1 - crop_fraction))  # , size=config['batch_size'])\n            xnext_reshaped[:, start_row:start_row + int(crop_fraction * config['B']), \\\n                           start_col:start_col + int(crop_fraction * config['A'])] = 0.0\n            cnext = np.reshape(xnext_reshaped, (config['batch_size'], config['img_size']))\n            draw_T = max(1, int(config['T'] * crop_fraction))\n        else:\n          cnext = np.zeros([config['batch_size'], config['img_size']])\n          draw_T = config['T']\n          \n        # Validate every 100th iteration\n        if iteration % 100 == 0:\n          valid_feed_dict = draw_model_valid.get_feed_dict(xnext, cnext)\n          valid_feed_dict[draw_model_valid.T] = draw_T\n          valid_feed_dict[draw_model_valid.global_step] = step\n          valid_fetches = {'summaries': valid_summaries,\n                           'reconstruction_loss': draw_model_valid.Lx,\n                           'latent_loss': draw_model_valid.Lz,\n                           'write_loss': draw_model_valid.Lwrite,\n                           'intensity_change_loss': draw_model_valid.Lintensity,\n                           'movement_loss': draw_model_valid.Lmove,\n                           'loss': draw_model_valid.loss}\n          valid_out = sess.run(valid_fetches, valid_feed_dict)\n          # For saving plot data\n          xlog = xnext\n          cost = valid_out['loss']\n          print(\"epoch=%d, iter=%d : Lx: %f Lz: %f Lwrite: %f cost: %f\" % \\\n                (epoch, iteration, valid_out['reconstruction_loss'], valid_out['latent_loss'], valid_out['write_loss'], cost))\n          valid_writer.add_summary(valid_out['summaries'], global_step=step)\n          # save this checkpoint if necessary\n          if (epoch - last_saved_epoch + 1) >= config['save_checkpoints_every_epoch']:  # and cost < lowest_test_loss:\n            last_saved_epoch = epoch\n  #           lowest_test_loss = cost\n            saver.save(sess, os.path.join(config['model_dir'], 'drawmodel'), epoch)\n        else:\n          train_feed_dict = draw_model.get_feed_dict(xnext, cnext)\n          train_feed_dict[draw_model.T] = draw_T\n          train_fetches = {'summaries': training_summaries,\n                           'train_op': draw_model.train_op}\n          train_out = sess.run(train_fetches, train_feed_dict)\n          if iteration % 100 == 1:\n            train_writer.add_summary(train_out['summaries'], global_step=step)\n            \n        iteration += 1\n        pbar.update(1)\n    \n    print('Training finished.')\n\n    # # Logging + Visualization\n    log_fetches = {'canvases': draw_model_valid.cs.stack(), 'read_bbs': draw_model_valid.read_bb.stack(), \\\n                   'write_bbs': draw_model_valid.write_bb.stack(), 'write_times': draw_model_valid.stop_times}\n    log_out = sess.run(log_fetches, valid_feed_dict)  # generate some examples\n    canvases = np.array(log_out['canvases'])  # T x batch x img_size\n    read_bounding_boxes = np.array(log_out['read_bbs'])  # T x batch x 3\n    write_bounding_boxes = np.array(log_out['write_bbs'])  # T x batch x 3\n    write_times = np.array(log_out['write_times'])  # batch\n    \n    log_file = os.path.join(config['model_dir'], \"draw_data.npy\")\n    np.save(log_file, [xlog, canvases, read_bounding_boxes, write_bounding_boxes, write_times, config['draw_with_white']])\n    print(\"Visualization outputs saved in file: %s\" % log_file)\n    \n    ckpt_file = os.path.join(config['model_dir'], \"drawmodel.ckpt\")\n    print(\"Model saved in file: %s\" % saver.save(sess, ckpt_file))\n\n\nif __name__ == '__main__':\n    main(train_config)\n", "meta": {"hexsha": "e59d17a4d09dbb033487be29959144b7d5903715", "size": 10071, "ext": "py", "lang": "Python", "max_stars_repo_path": "train.py", "max_stars_repo_name": "vanurag/draw", "max_stars_repo_head_hexsha": "6d24e6485c7688c94affed11183ea6f3df8418d3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "train.py", "max_issues_repo_name": "vanurag/draw", "max_issues_repo_head_hexsha": "6d24e6485c7688c94affed11183ea6f3df8418d3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "train.py", "max_forks_repo_name": "vanurag/draw", "max_forks_repo_head_hexsha": "6d24e6485c7688c94affed11183ea6f3df8418d3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.5974025974, "max_line_length": 131, "alphanum_fraction": 0.6692483368, "include": true, "reason": "import numpy", "num_tokens": 2398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19734484463400276}}
{"text": "import os\n\nimport cv2\nimport numpy as np\n\nfrom . import Config\nfrom . import TrackersProvider\nfrom .CalibrationResults import get_current_time\nfrom .QueuesEntries import Point\nfrom .QueuesProvider import QueuesProvider\n\n\nclass Localization(object):\n    \"\"\"Provides localizattion process\"\"\"\n\n    objects_count = Config.objects_count\n    rotation_matrix1 = None\n    rotation_matrix2 = None\n    projection_matrix1 = None\n    projection_matrix2 = None\n    mono_calibration_results = None\n\n    localization_precision = 5  # in millimeters\n    last_located_point = [None for _ in range(objects_count)]\n    last_located_point_time = [-1 for _ in range(objects_count)]\n    time_threshold_skip = 1 / 20\n    time_threshold_correspondence = 1 / 10\n\n    @classmethod\n    def prepare_projection_matrices(cls, calibration_results1, calibration_results2, stereo_calibration_results):\n        '''Prepares projeciton matrices for localization'''\n        cls.mono_calibration_results = [calibration_results1, calibration_results2]\n        rt = np.append(stereo_calibration_results.rotation_matrix, stereo_calibration_results.translation_vector,\n                       axis=1)\n        cls.projection_matrix2 = calibration_results2.camera_matrix.dot(rt)\n        cls.projection_matrix1 = calibration_results1.camera_matrix.dot(np.eye(3, 4))\n\n    @classmethod\n    def get_3d_coordinates(cls, *points):\n        '''Undistort points and then compute the estimated 3D position'''\n        if any(point is None for point in points) or len(points) != 2:\n            return None\n\n        # OpenCv function works with a set of points. In our case we have only one point per camera,\n        # therefore we reshape into required format\n        points = [np.array(point).reshape(1, 1, 2).astype(float) for point in points]\n        points = [cls.get_undistorted_point(point, i) for i, point in enumerate(points)]\n\n        located_points_hom = cv2.triangulatePoints(projMatr1=cls.projection_matrix1, projMatr2=cls.projection_matrix2,\n                                                   projPoints1=points[0],\n                                                   projPoints2=points[1])\n        return cls.convert_from_homogenous(located_points_hom)\n\n    @classmethod\n    def get_undistorted_point(cls, point, cam_ind):\n        '''Undistort point by using saved calibration data'''\n        calib_results = cls.mono_calibration_results[cam_ind]\n        undistorted = cv2.undistortPoints(point, calib_results.camera_matrix, calib_results.distortion_coeffs,\n                                          P=calib_results.camera_matrix)  # without setting P normalized points would be returned\n        return undistorted\n\n    @classmethod\n    def save_localization_data(cls):\n        '''Saves all localization data of all objects'''\n        times = [x[0].timestamp for x in QueuesProvider.LocalizatedPoints3D if x]\n        if not times:\n            return\n\n        first_point_time = min(times)\n        for i, localizated in enumerate(QueuesProvider.LocalizatedPoints3D):\n            if not localizated:\n                return\n\n            curr_dir = os.path.dirname(os.path.abspath(__file__))\n            filename = os.path.join(curr_dir, \"localization_data\", \"{}-{}.txt\".format(get_current_time(), i + 1))\n            os.makedirs(os.path.dirname(filename), exist_ok=True)\n\n            with open(filename, 'w') as output:\n                for point in localizated:\n                    point.timestamp -= first_point_time\n                    output.write('{}\\n'.format(point))\n\n    @classmethod\n    def localize_point(cls, object_id):\n        '''Localize point in 3D and save it to corresponding queue'''\n        points1 = QueuesProvider.TrackedPoints2D[(TrackersProvider.get_tracker_uid(0, object_id))]\n        points2 = QueuesProvider.TrackedPoints2D[(TrackersProvider.get_tracker_uid(1, object_id))]\n\n        if len(points1) == 0 or len(points2) == 0:\n            return\n\n        point1 = points1[-1]\n        point2 = points2[-1]\n\n        if abs(point1.timestamp - point2.timestamp) > cls.time_threshold_correspondence:\n            return\n\n        time = (point1.timestamp + point2.timestamp) / 2\n\n        try:\n            if time - cls.last_located_point_time[object_id] < cls.time_threshold_skip:\n                return\n        except IndexError:\n            return\n\n        cls.last_located_point_time[object_id] = time\n\n        located_point = Localization.get_3d_coordinates(point1.coordinates,\n                                                        point2.coordinates)\n        if located_point is None:\n            return\n\n        if cls.moved_more_than(cls.last_located_point[object_id], located_point, cls.localization_precision):\n            point = Point(located_point, time)\n            QueuesProvider.LocalizatedPoints3D[object_id].append(point)\n            cls.last_located_point[object_id] = located_point\n\n    @classmethod\n    def moved_more_than(cls, old, new, distance):\n        return old is None or np.linalg.norm(new - old) > distance\n\n    @classmethod\n    def convert_from_homogenous(cls, coords):\n        return (coords[:-1] / coords[-1])[:, 0]\n", "meta": {"hexsha": "96206349bf2349a2d5a2c3453223374f17c5111d", "size": 5120, "ext": "py", "lang": "Python", "max_stars_repo_path": "program/program/Localization.py", "max_stars_repo_name": "JankaSvK/thesis", "max_stars_repo_head_hexsha": "c440ab8242b058f580fdf9d5a1d00708a1696561", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-29T14:13:47.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-29T14:13:47.000Z", "max_issues_repo_path": "program/program/Localization.py", "max_issues_repo_name": "JankaSvK/thesis", "max_issues_repo_head_hexsha": "c440ab8242b058f580fdf9d5a1d00708a1696561", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-04-24T18:30:00.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-11T23:25:07.000Z", "max_forks_repo_path": "program/program/Localization.py", "max_forks_repo_name": "JankaSvK/thesis", "max_forks_repo_head_hexsha": "c440ab8242b058f580fdf9d5a1d00708a1696561", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.96, "max_line_length": 129, "alphanum_fraction": 0.66328125, "include": true, "reason": "import numpy", "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19734484463400276}}
{"text": "\"\"\"Provides a class, HP_model, to model the impact of a heat pump on\nenergy use and cost.\n\"\"\"\nfrom pprint import pformat\nimport inspect\nfrom pathlib import Path\nimport pickle\nimport time\nimport gzip\n\nimport pandas as pd\nimport numpy as np\n\nfrom . import library as lib\nfrom . import elec_cost\nfrom .home_heat_model import HomeHeatModel\nfrom .elec_cost import ElecCostCalc\nfrom .utils import is_null\nfrom . import ui_helper\n\n# --------- Some Constants\n\n# The days in each month\nDAYS_IN_MONTH = np.array([\n    31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31\n])\n\n# The pattern or Lights and appliances other than DHW, Clothes Drying & Cooking.\n# This is average power in the month divided average annual power.\nLIGHTS_OTHER_PAT = np.array([\n    1.13, 1.075, 1.0, 0.925, 0.87, 0.85, 0.87, 0.925, 1.0, 1.075, 1.13, 1.15\n])\n\ndef make_pattern(esc, life):\n    \"\"\"Makes a numpy array of length (life + 1) containing an escalation pattern\n    that starts with a 1.0 in year 1 and escalates at the rate of 'esc' per year.\n    \"\"\"\n    pat = np.ones(life - 1) * (1 + esc)\n    return np.insert(pat.cumprod(), 0, [0.0, 1.0])\n\ndef convert_co2_to_miles_driven(co2_saved):\n    \"\"\"Converts CO2 emissions to a mileage driven\n    equivalent for vehicles in the U.S. using EPA\n    methodology:  https://www.epa.gov/energy/greenhouse-gases-equivalencies-calculator-calculations-and-references#miles\n    \"\"\"\n    pounds_in_metric_ton = 2204.62\n    tons_co2_per_gallon = 0.0089\n    avg_gas_mileage_us_fleet = 22\n    mileage_equivalent = co2_saved / pounds_in_metric_ton / tons_co2_per_gallon * avg_gas_mileage_us_fleet\n    \n    return mileage_equivalent\n\n\nclass HP_model:\n    \"\"\"This is the class that orchestrates the heat pump analysis, running the home\n    energy model with and without the heat pump.  The class performs the economic\n    analysis and stores all results as object attributes.  The main method that\n    is run to perform the analysis is \"run()\".\n    \"\"\"\n\n    # Some of inputs parameters are documented in the home_heat_model.HomeHeatModel class constructor;\n    # those inputs are marked as such below.\n    def __init__(self,\n                 bldg_name,              # name of the building\n                 notes,                  # notes about the building\n                 city_id,                # see home_heat_model.HomeHeatModel\n                 utility,                # The full Pandas Series describing the Electric Utility\n                 pce_limit,              # The maximum kWh in a month subsidized by PCE (0 will mean no PCE subsidy)\n                 co2_lbs_per_kwh,        # see home_heat_model.HomeHeatModel\n                 exist_heat_fuel_id,     # see home_heat_model.HomeHeatModel\n                 exist_unit_fuel_cost,   # Cost per physical unit (e.g. gallon, CCF) of the existing space heating fuel.\n                 exist_fuel_use,         # Annual existing fuel use for Space Heating and the other end uses identified using that fuel. None if not available.\n                 elec_uses,              # 'all' if Annual Electric Use given by user includes lights & appliances, or 'space' if it is just Space Heating use.\n                 exist_heat_effic,       # see home_heat_model.HomeHeatModel\n                 exist_kwh_per_mmbtu,    # see home_heat_model.HomeHeatModel\n                 includes_dhw,           # True if the existing Space Heating Fuel type also is used for DHW.\n                 includes_dryer,         # True if the existing Space Heating Fuel type also is used for Clothes Drying.\n                 includes_cooking,       # True if the existing Space Heating Fuel type also is used for Cooking.\n                 occupant_count,         # Number of occupants using DHW, Clothes Drying, Cooking\n                 elec_use_jan,           # The electric use in January, prior to heat pump installation, kWh.\n                 elec_use_may,           # The electric use in May, prior to heat pump installation, kWh.\n                 hp_model_id,            # see home_heat_model.HomeHeatModel\n                 low_temp_cutoff,        # see home_heat_model.HomeHeatModel\n                 off_months_chks,        # see home_heat_model.HomeHeatModel, parameter 'off_months' there\n                 garage_stall_count,     # see home_heat_model.HomeHeatModel\n                 garage_heated_by_hp,    # see home_heat_model.HomeHeatModel\n                 bldg_floor_area,        # see home_heat_model.HomeHeatModel\n                 indoor_heat_setpoint,   # see home_heat_model.HomeHeatModel\n                 insul_level,            # see home_heat_model.HomeHeatModel\n                 pct_exposed_to_hp,      # see home_heat_model.HomeHeatModel\n                 doors_open_to_adjacent, # see home_heat_model.HomeHeatModel\n                 bedroom_temp_tolerance, # see home_heat_model.HomeHeatModel\n                 capital_cost,           # Initial cost of the heat pump installation\n                 rebate_dol,             # Rebate $ received for heat pump installation\n                 pct_financed,           # fraction (0 - 1.0) of heat pump installation cost financed by a loan.\n                 loan_term,              # Length of loan in years.\n                 loan_interest,          # interest rate of loan, expressed as fraction, i.e. 0.1 for 10%.\n                 hp_life,                # life of heat pump in years\n                 op_cost_chg,            # operating cost increase associated with heat pump (negative if decrease)\n                 sales_tax,              # sales tax, expressed as a fraction (0.05 for 5%/yr) that applies to electricity and fuel costs\n                 discount_rate,          # economic discount rate, expressed as a fraction, per year. Nominal, not adjusted for inflation.\n                 inflation_rate,         # general inflation rate expressed as a fraction, per year.\n                 fuel_esc_rate,          # price escalation rate of fuel used for existing heating system, fraction/year, nominal\n                 elec_esc_rate,          # price escalation rate of electricity, fraction/year, nominal\n                ):\n\n        # Store all of these input parameters as object attributes.\n        args, _, _, values = inspect.getargvalues(inspect.currentframe())\n        for arg in args[1:]:\n            setattr(self, arg, values[arg])\n            \n        # Look up the objects associated with the IDs\n        self.city = lib.city_from_id(city_id)\n        self.exist_fuel = lib.fuel_from_id(exist_heat_fuel_id)\n        self.hp_model = lib.heat_pump_from_id(hp_model_id)\n                    \n    def __repr__(self):\n        \"\"\"Returns a string with all the object attributes shown.  Text is truncated\n        at 1,000 characters for attributes with long representations.\n        \"\"\"\n        s = ''\n        for attr in self.__dict__:\n            val = pformat(self.__dict__[attr])[:1500]\n            if len(val)>70:\n                s+=f'\\n{attr}:\\n{val}\\n\\n'\n            else:\n                s += f'{attr}: {val}\\n'\n        return s\n        \n    def run(self):\n        \"\"\"This method performs all of the modeling and analysis, storing\n        results as object attributes.\n        \"\"\"\n        \n        # shortcut for self\n        s = self\n        \n        # shortcut to existing heating fuel\n        fuel = s.exist_fuel\n\n        # holds summary measures for the heat pump project (e.g. seasonal COP,\n        # internal rate of return).  Fill out first item: secondary fuel info.\n        s.summary = {'fuel_unit': fuel.unit, 'fuel_desc': fuel.desc}\n        \n        # Create the home energy simulation object\n        sim = HomeHeatModel(\n            city_id=s.city_id,\n            hp_model_id=s.hp_model_id,\n            exist_heat_fuel_id=s.exist_heat_fuel_id,\n            exist_heat_effic=s.exist_heat_effic,\n            exist_kwh_per_mmbtu=s.exist_kwh_per_mmbtu,    \n            co2_lbs_per_kwh=s.co2_lbs_per_kwh,\n            low_temp_cutoff=s.low_temp_cutoff,\n            off_months=s.off_months_chks,\n            garage_stall_count=s.garage_stall_count,\n            garage_heated_by_hp=s.garage_heated_by_hp,\n            bldg_floor_area=s.bldg_floor_area,\n            indoor_heat_setpoint=s.indoor_heat_setpoint,\n            insul_level=s.insul_level,\n            pct_exposed_to_hp=s.pct_exposed_to_hp,\n            doors_open_to_adjacent=s.doors_open_to_adjacent,\n            bedroom_temp_tolerance=s.bedroom_temp_tolerance,    \n        )\n\n        # If other end uses use the heating fuel, make an estimate of their annual\n        # consumption of that fuel.  This figure is expressed in the physical unit\n        # for the fuel type, e.g. gallons of oil.  Save this as an object attribute\n        # so it is accessible in other routines.  See Evernote notes on values (AkWarm\n        # for DHW and Michael Bluejay for Drying and Cooking).\n        is_electric = (s.exist_heat_fuel_id == ui_helper.ELECTRIC_ID)  # True if Electric\n        s.fuel_other_uses = s.includes_dhw * 4.23e6 / fuel.dhw_effic\n        s.fuel_other_uses += s.includes_dryer * (0.86e6 if is_electric else 2.15e6)\n        s.fuel_other_uses += s.includes_cooking * (0.64e6 if is_electric else 0.8e6)\n        s.fuel_other_uses *= s.occupant_count / fuel.btus\n\n        # For elecric heat we also need to account for lights and other applicances not\n        # itemized above.\n        if is_electric:\n            # Use the AkWarm Medium Lights/Appliances formula but take 25% off\n            # due to efficiency improvements since then.\n            s.lights_other_elec = 2086. + 1.20 * s.bldg_floor_area   # kWh in the year\n        else:\n            s.lights_other_elec = 0.0\n        \n        # Match the existing space heating use if it is provided.  Do so by using\n        # the UA true up factor.\n        if not is_null(s.exist_fuel_use):\n            \n            # Remove the energy use from the other end uses that use the fuel, unless\n            # this is electric heat and the user indicated that the entered value is\n            # just space heating.\n            if is_electric and s.elec_uses=='space':\n                # user explicitly indicated that the entered annual usage value is\n                # just space heating.\n                space_fuel_use = s.exist_fuel_use\n            else:\n                space_fuel_use = s.exist_fuel_use - s.fuel_other_uses - s.lights_other_elec\n\n            sim.no_heat_pump_use = True\n            sim.calculate()\n            if is_electric:\n                # For electric heat, electric use for space heat is in secondary_kwh\n                fuel_use1 = sim.annual_results().secondary_kwh\n            else:\n                fuel_use1 = sim.annual_results().secondary_fuel_units\n            \n            # scale the UA linearly to attempt to match the target fuel use\n            ua_true_up = space_fuel_use / fuel_use1\n            sim.ua_true_up = ua_true_up\n            sim.calculate()\n\n            if is_electric:\n                # For electric heat, electric use for space heat is in secondary_kwh\n                fuel_use2 = sim.annual_results().secondary_kwh\n            else:\n                fuel_use2 = sim.annual_results().secondary_fuel_units\n            \n            # In case it wasn't linear, inter/extrapolate to the final ua_true_up\n            slope = (fuel_use2 - fuel_use1)/(ua_true_up - 1.0)\n            # print(space_fuel_use, fuel_use1, fuel_use2, ua_true_up)\n            ua_true_up = 1.0 + (space_fuel_use - fuel_use1) / slope\n            # print(ua_true_up)\n\n        else:\n            ua_true_up = 1.0\n            \n        # Set the UA true up value into the model and also save it as\n        # an attribute of this object so it can be observed.\n        sim.ua_true_up = ua_true_up\n        s.ua_true_up = ua_true_up\n        \n        # Run the base case with no heat pump and record energy results.\n        # This model only models the space heating end use.\n        sim.no_heat_pump_use = True\n        sim.calculate()\n        s.df_mo_en_base = sim.monthly_results()\n        s.ann_en_base = sim.annual_results()\n        # print(s.ann_en_base.secondary_kwh)\n        \n        # Run the model with the heat pump and record energy results\n        sim.no_heat_pump_use = False\n        sim.calculate()\n        s.df_mo_en_hp = sim.monthly_results()\n        s.ann_en_hp = sim.annual_results()\n        s.df_hourly = sim.df_hourly\n\n        # record design heat load\n        s.summary['design_heat_load'], s.summary['design_heat_temp'] = sim.design_heat_load()\n        \n        # Calculate some summary measures\n        s.summary['cop'] = s.ann_en_hp.cop\n        s.summary['hp_max_capacity_5F'] = sim.hp_max_capacity_5F()\n        s.summary['max_hp_reached'] = sim.max_hp_reached\n        \n        # CO2 savings\n        s.summary['co2_lbs_saved'] = s.ann_en_base.co2_lbs - s.ann_en_hp.co2_lbs\n        s.summary['co2_driving_miles_saved'] = convert_co2_to_miles_driven(s.summary['co2_lbs_saved'])\n        s.summary['hp_load_frac'] = s.ann_en_hp.hp_load_mmbtu / (s.ann_en_hp.hp_load_mmbtu + s.ann_en_hp.secondary_load_mmbtu)\n        \n        # Create DataFrames that hold monthly energy cost amounts\n        # Results are stored as object attributes.\n        self.calc_monthly_cash()\n        \n        # Create a multi-year Cash Flow DataFrame and summary economic measures.\n        # Results are stored as object attributes.\n        self.calc_cash_flow()\n\n        # Save a gzipped pickle of this object using Unix time as the file name.\n        # make a directory to hold the files\n        save_dir = 'hpcalc_runs'\n        Path(save_dir).mkdir(exist_ok=True)\n        fname = f'{time.time():.2f}.pkl.gz'\n        s.file_name = fname\n        pickle.dump(self, gzip.open(f'{save_dir}/{fname}', 'wb'))\n\n    def calc_monthly_cash(self):\n        \"\"\"Calculates two DataFrames, s.df_mo_dol_base and s.df_mo_dol_hp, that contain\n        the fuel and electricity costs in the base case (no heat pump) scenario and the\n        with heat pump scenario.  A number of inputs found as object attributes are used. \n        \"\"\"\n        # shortcut to self\n        s = self\n\n        # Start the DataFrames, base and w/ heat pump\n        # Each starts with just an index column with the month\n        # Make shortcut variables as well.\n        s.df_mo_dol_base = dfb = s.df_mo_en_base[[]].copy()\n        s.df_mo_dol_hp = dfh = s.df_mo_en_base[[]].copy()\n\n        # Determine the base electric use by month.  Approach is different \n        # if there is electric heat.\n        is_electric_heat = (s.exist_heat_fuel_id == ui_helper.ELECTRIC_ID)\n        if not is_electric_heat:\n            # Fuel-based space heat.\n            # The User supplied a January and a May kWh usage value that should\n            # be used for the base case (no heat pump) total electricity use.\n            # But, need to come up with a kWh value for every month.  Do that by\n            # adjusting the kWh pattern available for this city.\n            #\n            # Determine the multiplier to adjust to the pattern to the actual.\n            pat_use = np.array(s.city.avg_elec_usage)\n            mult = (s.elec_use_jan - s.elec_use_may) / (pat_use[0] - pat_use[4])\n            pat_use = mult * pat_use\n            pat_use += s.elec_use_jan - pat_use[0]\n\n            # The electricity use in the base case\n            dfb['elec_kwh'] =  pat_use\n\n            # rough estimate of a base demand: not super critical, as the demand rate \n            # structure does not have blocks.  Assume a load factor of 0.4\n            dfb['elec_kw'] = dfb.elec_kwh / (DAYS_IN_MONTH * 24.0) / 0.4\n\n        else:\n            # Electric Heat Case\n            # No Jan and May values are provided.  Instead we have possibly some\n            # DHW, clothes drying, and cooking.  Plus, we have base lights/other appliances.\n            # And finally we have the Elecric heat making up the base electric usage.\n\n            # First, DHW, Clothes Drying and Cooking.  Assume flat use through year.\n            # This is a numpy array because DAYS_IN_MONTH is an array.\n            elec_kwh = s.fuel_other_uses / 8760.0 * DAYS_IN_MONTH * 24.0\n\n            # Now lights and other misc. appliances. Some monthly variation, given\n            # by LIGHTS_OTHER_PAT.\n            elec_kwh += s.lights_other_elec / 8760.0 * LIGHTS_OTHER_PAT * DAYS_IN_MONTH * 24.0\n\n            # For the peak demand of those two categories of use, just assume 40% load factor.\n            elec_kw = elec_kwh / (DAYS_IN_MONTH * 24.0) / 0.4\n\n            # Now add in space heating kWh and kW\n            elec_kwh += s.df_mo_en_base.total_kwh.values\n            elec_kw += s.df_mo_en_base.total_kw.values\n\n            # store results\n            dfb['elec_kwh'] =  elec_kwh\n            dfb['elec_kw'] =  elec_kw\n\n        # Make an object to calculate electric utility costs\n        elec_cost_calc = ElecCostCalc(s.utility, sales_tax=s.sales_tax, pce_limit=s.pce_limit)\n        # cost function that will be applied to each row of the cost DataFrame\n        cost_func = lambda r: elec_cost_calc.monthly_cost(r.elec_kwh, r.elec_kw)\n\n        dfb['elec_dol'] = dfb.apply(cost_func, axis=1)\n\n        if not is_electric_heat:\n            # Now fuel use by month.  Remember that the home heat model only looked at\n            # space heating, so we need to add in the fuel use from the other end uses\n            # that use this fuel.\n            dfb['secondary_fuel_units'] = s.df_mo_en_base.secondary_fuel_units + \\\n                s.fuel_other_uses / 12.0\n            dfb['secondary_fuel_dol'] = dfb.secondary_fuel_units * s.exist_unit_fuel_cost * (1. + s.sales_tax)\n        else:\n            # Electric Heat, so no secondary fuel\n            dfb['secondary_fuel_units'] = 0.0\n            dfb['secondary_fuel_dol'] = 0.0\n\n        # Total Electric + space heat\n        dfb['total_dol'] =  dfb.elec_dol + dfb.secondary_fuel_dol\n\n        # Now with the heat pump\n        # determine extra kWh used in the heat pump scenario. Note, this will\n        # be negative numbers if the base case used electric heat.\n        extra_kwh = (s.df_mo_en_hp.total_kwh - s.df_mo_en_base.total_kwh).values\n        dfh['elec_kwh'] = dfb['elec_kwh'] + extra_kwh\n        extra_kw = (s.df_mo_en_hp.total_kw - s.df_mo_en_base.total_kw).values\n        dfh['elec_kw'] =  dfb['elec_kw'] + extra_kw\n        dfh['elec_dol'] = dfh.apply(cost_func, axis=1)\n\n        # Now fuel, including other end uses using the heating fuel\n        if not is_electric_heat:\n            dfh['secondary_fuel_units'] = s.df_mo_en_hp.secondary_fuel_units + \\\n                s.fuel_other_uses / 12.0\n            dfh['secondary_fuel_dol'] = dfh.secondary_fuel_units * s.exist_unit_fuel_cost * (1. + s.sales_tax)\n        else:\n            # Electric Heat, so no secondary fuel\n            dfh['secondary_fuel_units'] = 0.0\n            dfh['secondary_fuel_dol'] = 0.0\n\n        # Total Electric + space heat\n        dfh['total_dol'] =  dfh.elec_dol + dfh.secondary_fuel_dol\n        \n    def calc_cash_flow(self):\n        \"\"\"Calculates the cash flow impacts of the installation over the \n        life of the heat pump.  Creates a DataFrame, self.df_cash_flow, that shows\n        the impacts. In that DataFrame, postive values are benefits and negative \n        values are costs. \n        Also calculates some summary economic measures that are added to\n        the self.summary dictionary.\n        \"\"\"\n        s = self   # shortcut variable\n\n        # determine the changes caused by the heat pump on an annual basis.\n        # First calculate annual totals for base case and heat pump case and\n        # then calculate the change.\n        ann_base = s.df_mo_dol_base.sum()\n        ann_hp = s.df_mo_dol_hp.sum()\n        ann_chg = ann_hp - ann_base\n        initial_cost = np.zeros(s.hp_life+1)\n        \n        # Am not automatically adding sales tax to the initial cost as the user was\n        # supposed to includes sales tax in their input.\n        initial_cost[0] = -s.capital_cost * (1 - s.pct_financed) + s.rebate_dol\n        loan_pmt = np.pmt(s.loan_interest, s.loan_term, s.capital_cost * s.pct_financed)\n        if loan_pmt < -0.01:   # loan payment is negative\n            loan_cost = [0.0] + [loan_pmt] * s.loan_term + [0.0] * (s.hp_life -  s.loan_term)\n            loan_cost = np.array(loan_cost)\n        else:\n            loan_cost = 0.0\n        op_cost = -s.op_cost_chg * make_pattern(s.inflation_rate, s.hp_life)\n        fuel_cost = -ann_chg.secondary_fuel_dol * make_pattern(s.fuel_esc_rate, s.hp_life)\n        elec_cost = -ann_chg.elec_dol * make_pattern(s.elec_esc_rate, s.hp_life)\n        cash_flow = initial_cost + loan_cost + op_cost + fuel_cost + elec_cost\n\n        # calculate cumulative, discounted cash flow.\n        disc_factor = np.ones(s.hp_life) * (1 + s.discount_rate)\n        disc_factor = np.insert(disc_factor.cumprod(), 0, 1.0)\n        cum_disc_cash_flow = np.cumsum(cash_flow / disc_factor)\n                \n        s.df_cash_flow = pd.DataFrame(\n            {'initial_cost': initial_cost,\n             'loan_cost': loan_cost,\n             'op_cost': op_cost,\n             'fuel_cost': fuel_cost,\n             'elec_cost': elec_cost,\n             'cash_flow': cash_flow,\n             'cum_disc_cash_flow': cum_disc_cash_flow,\n            }\n        )\n        s.df_cash_flow.index.name = 'year'\n        \n        # Calculate IRR and NPV for w/ and w/o PCE.\n        s.summary['irr'] = np.irr(s.df_cash_flow.cash_flow)\n        s.summary['npv'] = np.npv(s.discount_rate, s.df_cash_flow.cash_flow)\n        \n        # Add some summary fuel and electric usage  and unit cost info\n        s.summary['fuel_use_base'] = ann_base.secondary_fuel_units\n        s.summary['fuel_use_hp'] =  ann_hp.secondary_fuel_units\n        s.summary['fuel_use_chg'] = ann_chg.secondary_fuel_units\n        if ann_chg.secondary_fuel_units != 0.0:\n            s.summary['fuel_price_incremental'] = ann_chg.secondary_fuel_dol / ann_chg.secondary_fuel_units\n        else:\n            s.summary['fuel_price_incremental'] = np.nan\n        s.summary['elec_use_base'] = ann_base.elec_kwh\n        s.summary['elec_use_hp'] =  ann_hp.elec_kwh\n        s.summary['elec_use_chg'] = ann_chg.elec_kwh\n        s.summary['elec_rate_avg_base'] = ann_base.elec_dol / ann_base.elec_kwh\n        s.summary['elec_rate_avg_hp'] = ann_hp.elec_dol / ann_hp.elec_kwh\n        s.summary['elec_rate_incremental'] = ann_chg.elec_dol / ann_chg.elec_kwh\n    ", "meta": {"hexsha": "46c047f9f058702fdc9792f6585f24fc003e9652", "size": 22381, "ext": "py", "lang": "Python", "max_stars_repo_path": "heatpump/hp_model.py", "max_stars_repo_name": "alanmitchell/heat-pump-calc", "max_stars_repo_head_hexsha": "fd3efab5a956ce8ef68b5a7f35f3d0a1bd58565b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-03-19T17:37:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T19:32:48.000Z", "max_issues_repo_path": "heatpump/hp_model.py", "max_issues_repo_name": "alanmitchell/heat-pump-calc", "max_issues_repo_head_hexsha": "fd3efab5a956ce8ef68b5a7f35f3d0a1bd58565b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "heatpump/hp_model.py", "max_forks_repo_name": "alanmitchell/heat-pump-calc", "max_forks_repo_head_hexsha": "fd3efab5a956ce8ef68b5a7f35f3d0a1bd58565b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-11T23:57:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-11T23:57:11.000Z", "avg_line_length": 49.846325167, "max_line_length": 159, "alphanum_fraction": 0.6278539833, "include": true, "reason": "import numpy", "num_tokens": 5525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118493816806, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19734483884455647}}
{"text": "# Copyright (c) 2021, Oracle and/or its affiliates.  All rights reserved.\n# This software is licensed to you under the Universal Permissive License (UPL) 1.0 as shown at\n# https://oss.oracle.com/licenses/upl\n\"\"\"Module contains the MACEst model to estimate prediction intervals.\"\"\"\n\nimport nmslib\nimport logging\nimport os\nimport numpy as np\nimport scipy\nfrom scipy.optimize import differential_evolution\nfrom scipy.stats import laplace, norm\nfrom scipy.stats._continuous_distns import laplace_gen\nfrom typing import Optional, Union, NamedTuple, Tuple, Dict, Any\nfrom typing_extensions import Protocol, Literal\n\nlog = logging.getLogger()\n\nnum_threads_available = os.cpu_count()\n\n\nclass _RegressionPointPredictionModel(Protocol):\n    \"\"\"\n    Defines a protocol for the type PointPredModel.\n\n    if a model has a predict method then it is the same type as PointPredModel.\n    \"\"\"\n\n    def predict(self, x_star: np.ndarray) -> Any:\n        \"\"\"Return nothing as is only needed to check method exists.\"\"\"\n        pass\n\n\nclass HnswGraphArgs(NamedTuple):\n    \"\"\"Object for passing arguments to the nmslib function.\"\"\"\n\n    init_kwargs: Dict[str, str] = {\"method\": \"hnsw\", \"space\": \"l2\"}\n    construction_kwargs: Dict[str, int] = {\"post\": 2, \"efConstruction\": 1000, \"M\": 100}\n    query_kwargs: Dict[str, int] = {\"ef\": 1000}\n\n\nclass SearchBounds(NamedTuple):\n    \"\"\"Object for passing the range of allowed MACEst parameters.\"\"\"\n\n    alpha_bounds: Tuple[float, float] = (0.1, 50.0)\n    beta_bounds: Tuple[float, float] = (0.1, 50.0)\n    k_bounds: Tuple[int, int] = (5, 20)\n\n\nclass MacestPredIntervalModelParams(NamedTuple):\n    \"\"\"Class container for MACEst model parameters.\"\"\"\n\n    alpha: float = 1.0\n    beta: float = 1.0\n    num_neighbours: int = 10\n\n\nclass PrecomputedNeighbourInfo(NamedTuple):\n    \"\"\"Class container for the information about pre-computed nearest neighbours per class.\"\"\"\n\n    prec_distance_to_nn: Union[Dict[int, np.ndarray], np.ndarray]\n    prec_ind_of_nn: Union[Dict[int, np.ndarray], np.ndarray]  # Rhys- only dict for training, where I cache\n    # arrays for all values of allowed num neighbours\n\n\nclass ModelWithPredictionInterval:\n    \"\"\"Creates a model which returns a prediction and a confidence interval.\"\"\"\n\n    def __init__(\n        self,\n        model: _RegressionPointPredictionModel,\n        x_train: np.ndarray,\n        train_err: np.ndarray,\n        macest_model_params: MacestPredIntervalModelParams = MacestPredIntervalModelParams(),\n        error_dist: Literal[\"normal\", \"laplace\"] = \"normal\",\n        dist_func: Literal[\"linear\", \"error_weighted_poly\"] = \"linear\",\n        precomputed_neighbour_info: Optional[PrecomputedNeighbourInfo] = None,\n        prec_point_preds: Optional[np.ndarray] = None,\n        prec_graph: Optional[nmslib.dist.FloatIndex] = None,\n        search_method_args: HnswGraphArgs = HnswGraphArgs(),\n    ):\n        \"\"\"\n        Init.\n\n        :param model: Any model which takes some variables x and returns a point prediction y\n        :param x_train: The variables used to train the model\n        :param train_err: The error for each training point\n        :param num_neighbours: The number of points which define the local neighbourhood\n        :param alpha: co-efficient for distance function (hyper-parameter)\n        :param beta: The hyper-parameter used in distance function\n        :param error_dist: The assumed distribution for the errors\n        :param dist_func: The function to convert distance to confidence \\\n                          (currently linear or error_weighted_poly implemented)\n        :param prec_point_preds: The pre-computed model predictions\n        :param prec_distance_to_nn: The pre-computed nearest neighbour distances for the calibration and test data\n        :param prec_ind_of_nn: The pre-computed nearest neighbour indices for the calibration and test data\n        :param prec_graph: The pre-computed graph to use for online hnsw search\n        \"\"\"\n        self.model = model\n        self.x_train = x_train\n        self.train_err = train_err\n        self.macest_model_params = macest_model_params\n        self._num_neighbours = macest_model_params.num_neighbours\n        self._alpha = macest_model_params.alpha\n        self._beta = macest_model_params.beta\n        self.dist_func = dist_func\n        self.error_dist = error_dist\n        self.prec_graph = prec_graph\n        self.point_preds = prec_point_preds\n        self.precomputed_neighbour_info = precomputed_neighbour_info\n        if not self.precomputed_neighbour_info:\n            self._distance_to_nn = None\n            self._ind_of_nn = None\n        else:\n            self._distance_to_nn = self.precomputed_neighbour_info.prec_distance_to_nn\n            self._ind_of_nn = self.precomputed_neighbour_info.prec_ind_of_nn\n        self.search_method_args = search_method_args\n        self._check_consistent_search_method_args()\n        self._check_data_consistent_with_search_args()\n\n    def predict(self, x_star: np.ndarray) -> np.ndarray:\n        \"\"\"\n        Return a point prediction for x_star.\n\n        :param x_star: The position for which we would like to predict\n\n        :return: pred_star : The point prediction for x_star\n        \"\"\"\n        pred_star = self.model.predict(x_star)\n        return pred_star\n\n    def build_graph(self) -> nmslib.dist.FloatIndex:\n        \"\"\"\n        Build the  Hierarchical Navigable Small World (hnsw) index graph.\n\n        :return: A queryable HNSW graph\n        \"\"\"\n        graph = nmslib.init(**self.search_method_args.init_kwargs)\n        graph.addDataPointBatch(self.x_train)\n        graph.createIndex(self.search_method_args.construction_kwargs)\n        graph.setQueryTimeParams(self.search_method_args.query_kwargs)\n\n        return graph\n\n    def calc_nn_dist(self, x_star: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n        \"\"\"\n        Calculate the distant to a set of k nearest neighbours.\n\n        :param x_star: The position for which we would like to predict\n\n        :return: The distance to k nearest neighbours and the indices of the k closest neighbours\n        \"\"\"\n        if self.prec_graph is None:\n            self.prec_graph = self.build_graph()\n\n        neighbours = np.array(\n            self.prec_graph.knnQueryBatch(\n                x_star, k=self._num_neighbours, num_threads=num_threads_available\n            )\n        )\n        dist = neighbours[:, 1, :]\n        ind = neighbours[:, 0, :].astype(int)\n        return dist, ind\n\n    def calc_linear_dist_func(self, x_star: np.ndarray) -> np.ndarray:\n        \"\"\"\n        Calculate the linear sum of average distance to neighbours and average per neighbour error.\n\n        :param x_star: The position for which we would like to predict\n\n        :return: the sum of average distance to neighbours and average per neighbour error for x_star\n        \"\"\"\n        if self._distance_to_nn is not None:\n            local_distance = self._distance_to_nn\n            if self._ind_of_nn is None:\n                raise ValueError(\"_ind_of_nn has not been cached during training\")\n            ind = self._ind_of_nn\n        else:\n            local_distance, ind = self.calc_nn_dist(x_star)\n        if isinstance(local_distance, np.ndarray):\n            dist = self._alpha * np.average(\n                local_distance, weights=np.arange(local_distance.shape[1], 0, -1), axis=1,\n            )\n        else:\n            raise ValueError('Need to remove pre-cached training neighbour data from training')\n        if isinstance(ind, np.ndarray):\n            error = self._beta * np.average(\n                abs(self.train_err[ind.astype(int)]),\n                weights=1.0 / (1 + local_distance),\n                axis=1,)\n        else:\n            raise ValueError('Need to remove pre-cached training neighbour data from training')\n\n        return dist + error\n\n    def calc_error_weighted_dist(self, x_star: np.ndarray) -> np.ndarray:\n        \"\"\"\n        Calculate average distance to neighbours weighted by the per neighbour prediction error.\n\n        :param x_star: The position for which we would like to predict\n\n        :return: the error weighted distance from x_star point to it's neighbours\n        \"\"\"\n        if self._distance_to_nn is not None:\n            local_distance = self._distance_to_nn\n            if self._ind_of_nn is None:\n                raise ValueError(\"_ind_of_nn has not been cached during training\")\n            ind = self._ind_of_nn\n        else:\n            local_distance, ind = self.calc_nn_dist(x_star)\n\n        if isinstance(ind, np.ndarray):\n            train_error = self.train_err[ind.astype(int)]\n        else:\n            raise ValueError('Need to remove pre-cached training neighbour data from training')\n        if isinstance(local_distance, np.ndarray):\n            error_weighted_dist = np.average(\n                local_distance * abs(train_error),\n                weights=1.0 / (1 + local_distance),\n                axis=1,\n            )\n        else:\n            raise ValueError('Need to remove pre-cached training neighbour data from training')\n\n        error_weighted_poly = self._alpha * error_weighted_dist ** self._beta\n        return error_weighted_poly\n\n    def std_on_y_star(self, x_star: np.ndarray) -> np.ndarray:\n        \"\"\"\n        Return the predicted variance for x_star.\n\n        :param x_star: The position for which we would like to predict\n\n        :return: sigma: The standard deviation for the prediction at x_star\n        \"\"\"\n        if self.dist_func == \"error_weighted_poly\":\n            dist = self.calc_error_weighted_dist(x_star)\n        elif self.dist_func == \"linear\":\n            dist = self.calc_linear_dist_func(x_star)\n        else:\n            raise ValueError(f\"Unknown distance function: {self.dist_func}\")\n        sigma = dist\n        return sigma\n\n    def laplace_scale_on_y_star(self, x_star: np.ndarray) -> np.ndarray:\n        \"\"\"\n        Return the predicted laplacian variance for x_star.\n\n        :param x_star: The position for which we would like to predict\n\n        :return: sigma: The laplacian scaler for the prediction at x_star\n        \"\"\"\n        if self.dist_func == \"error_weighted_poly\":\n            dist = self.calc_error_weighted_dist(x_star)\n        elif self.dist_func == \"linear\":\n            dist = self.calc_linear_dist_func(x_star)\n        else:\n            raise ValueError(f\"Unknown distance function: {self.dist_func}\")\n        sigma = dist\n        return sigma\n\n    def _distribution(self, x_star: np.ndarray) -> laplace_gen:\n        \"\"\"\n        Return the distribution that we will predict from.\n\n        :return:\n        \"\"\"\n        if self.point_preds is not None:\n            point_preds = self.point_preds\n        else:\n            point_preds = self.predict(x_star,)\n        if self.error_dist == \"normal\":\n            scale = self.std_on_y_star(x_star,)\n            dist = norm(loc=point_preds, scale=scale)\n        elif self.error_dist == \"laplace\":\n            scale = self.laplace_scale_on_y_star(x_star,)\n            dist = laplace(loc=point_preds, scale=scale)\n        else:\n            raise ValueError(f\"Unknown distance function: {self.dist_func}\")\n        return dist\n\n    def predict_interval(\n        self, x_star: np.ndarray, conf_level: Union[np.ndarray, int, float] = 90,\n    ) -> np.ndarray:\n        \"\"\"\n        Predict the upper and lower prediction interval bounds for a given confidence level.\n\n        :param x_star: The position for which we would like to predict\n        :param conf_level:\n\n        :return: The confidence bounds for each x_star for each confidence level\n        \"\"\"\n        dist = self._distribution(x_star)\n        lower_perc = (100 - conf_level) / 2\n        upper_perc = 100 - lower_perc\n\n        lower_vec = 0.01 * np.ones((x_star.shape[0], len([conf_level]))) * lower_perc\n        upper_vec = 0.01 * np.ones((x_star.shape[0], len([conf_level]))) * upper_perc\n        return np.array([dist.ppf(lower_vec.T), dist.ppf(upper_vec.T)]).T\n\n    def calculate_prediction_interval_width(\n        self, x_star: np.ndarray, conf_level: Union[np.ndarray, int, float] = 90,\n    ) -> np.ndarray:\n        \"\"\"\n        Calculate the absolute width of a prediction interval for a given confidence level.\n\n        :param x_star: The position for which we would like to predict\n        :param conf_level:\n\n        :return: the absolute width of a prediction interval for each x_star for each confidence level\n        \"\"\"\n        intervals = self.predict_interval(x_star, conf_level)\n        return np.diff(intervals)\n\n    def sample_prediction(\n        self, x_star: np.ndarray, nsamples: int = 10 ** 3\n    ) -> np.ndarray:\n        \"\"\"\n        Draw samples from any predicted distribution to get a distribution of predictions.\n\n        :param x_star: The position in feature space for which we would like to predict\n        :param nsamples: The number of samples to draw from the distribution\n\n        :return: Samples from the predicted distribution\n        \"\"\"\n        dist = self._distribution(x_star)\n        return dist.rvs(size=(nsamples, x_star.shape[0])).T\n\n    def fit(\n        self,\n        x_cal: np.ndarray,\n        y_cal: np.ndarray,\n        param_range: SearchBounds = SearchBounds(),\n        optimiser_args: Optional[Dict[Any, Any]] = None,\n    ) -> None:\n        \"\"\"\n        Fit MACEst model using the calibration data.\n\n        :param x_cal: Calibration data\n        :param y_cal: Target values\n        :param param_range: The bounds within which to search for MACEst parameters\n        :param optimiser_args: Any arguments for the optimiser (see scipy.optimize)\n\n        :return: None\n        \"\"\"\n        if optimiser_args is None:\n            optimiser_args = {}\n\n        train_helper = _TrainingHelper(self, x_cal, y_cal, param_range)\n        train_helper.fit(optimiser_args=optimiser_args)\n\n    def _check_consistent_search_method_args(self) -> None:\n        init_args = self.search_method_args.init_kwargs\n        index = nmslib.init(**init_args)\n\n        if 'space' not in list(init_args.keys()):\n            raise ValueError('You must pass a space in your search method init args')\n\n        space = init_args['space']\n        if space[-6:] == 'sparse':\n            sparse_metric = True\n        else:\n            sparse_metric = False\n\n        data_type = index.dataType\n        if data_type == nmslib.DataType.SPARSE_VECTOR:\n            sparse_data = True\n        else:\n            sparse_data = False\n\n        if sparse_metric != sparse_data:\n            raise ValueError(\n                f'Data type and space are not compatible, your space is {space} '\n                f'and search data type is data_type nmslib.{data_type}')\n\n    def _check_data_consistent_with_search_args(self) -> None:\n        init_args = self.search_method_args.init_kwargs\n\n        space = init_args['space']\n        if space[-6:] == 'sparse':\n            sparse_metric = True\n        else:\n            sparse_metric = False\n\n        training_data_type = type(self.x_train)\n\n        if training_data_type == scipy.sparse.csr.csr_matrix:\n            sparse_data = True\n        else:\n            sparse_data = False\n\n        if sparse_metric != sparse_data:\n            raise ValueError(\n                f'Training data type and space are not compatible, your space is {space} '\n                f'and training data type is {training_data_type}')\n\n\nclass _TrainingHelper(object):\n    def __init__(\n        self,\n        init_conf_model: ModelWithPredictionInterval,\n        x_cal: np.ndarray,\n        y_cal: np.ndarray,\n        param_range: SearchBounds = SearchBounds(),\n    ):\n        \"\"\"\n        Init.\n\n        :param init_conf_model: an initialised ModelWithConfidence object that we want to fit\n        :param x_cal: The X variables that we will use to calibrate the confidence predictions\n        :param y_cal: The target variables that we will use to calibrate the confidence predictions\n        :param param_range: The bounds on the hyper-parameter space we want to search\n        \"\"\"\n        self.model = init_conf_model\n        self.x_cal = x_cal\n        self.y_cal = y_cal\n        self.param_range = param_range\n        self.prec_graph = self.model.build_graph()\n        self.model.prec_graph = self.prec_graph\n        self.prec_dist, self.prec_ind = self._prec_neighbours()\n        self.model.point_preds = self.model.predict(self.x_cal)\n\n    def _prec_neighbours(self) -> Tuple[Dict[int, np.ndarray], Dict[int, np.ndarray]]:\n        \"\"\"\n        Pre-compute the nearest neighbours and their distances.\n\n        :return:\n        \"\"\"\n        min_nbrs = self.param_range[2][0]\n        max_nbrs = self.param_range[2][1]\n        num_nbrs = np.arange(min_nbrs, max_nbrs + 0.1, 1)\n        x_cal_len_array = np.arange(len(self.x_cal))\n\n        dist_dict = {}\n        ind_dict = {}\n\n        max_neighbours = np.array(\n            self.prec_graph.knnQueryBatch(\n                self.x_cal, k=int(max_nbrs), num_threads=num_threads_available\n            )\n        )\n\n        max_dist = max_neighbours[x_cal_len_array, 1]\n        max_ind = max_neighbours[x_cal_len_array, 0]\n\n        for k in num_nbrs:\n            dist = max_dist[x_cal_len_array, 0: int(k)]\n            ind = max_ind[x_cal_len_array, 0: int(k)]\n\n            dist_dict[k] = dist\n            ind_dict[k] = ind\n\n        return dist_dict, ind_dict\n\n    def set_macest_model_params(self) -> MacestPredIntervalModelParams:\n        \"\"\"\n        Return MACEst parameter values.\n\n        :return:\n        \"\"\"\n        params = MacestPredIntervalModelParams(\n            num_neighbours=self.model._num_neighbours,\n            alpha=self.model._alpha,\n            beta=self.model._beta,\n        )\n        self.model.macest_model_params = params\n        return params\n\n    def loss_func(self, params: MacestPredIntervalModelParams) -> float:\n        \"\"\"\n        Calculate the loss for a given set of parameters, this will then be optimised when fit is called.\n\n        :param params: A tuple containing the model hyper-paramters\n        :return:\n        \"\"\"\n        self.model._alpha, self.model._beta, self.model._num_neighbours = params\n\n        self.model._num_neighbours = int(np.round(self.model._num_neighbours))\n\n        self.model.prec_graph = self.prec_graph\n        self.model._distance_to_nn = self.prec_dist[self.model._num_neighbours]\n        self.model._ind_of_nn = self.prec_ind[self.model._num_neighbours]\n\n        return picp_loss(self.model, self.x_cal, self.y_cal)\n\n    def fit(\n        self,\n        optimiser: Literal[\"de\"] = \"de\",\n        optimiser_args: Optional[Dict[Any, Any]] = None,\n    ) -> ModelWithPredictionInterval:\n        \"\"\"\n        Fit MACEst parameters.\n\n        :param optimiser: The optimisation method\n        :param optimiser_args: Any arguments for the optimisation strategy\n        :return: A ModelWithConfidence object with the hyper-parameters that minimises the loss function\n        \"\"\"\n        if optimiser == \"de\":\n            result = differential_evolution(\n                self.loss_func, self.param_range, **optimiser_args\n            )\n        else:\n            raise ValueError(\n                \"The only optimisation method currently implemented is differential evolution\"\n            )\n\n        log.info(f\"min_loss = {result.fun}\")\n\n        alpha, beta, k = result.x\n        k = int(np.round(k, 0))\n        log.info(f\" best_alpha: {alpha}\")\n        log.info(f\" best_beta: {beta}\")\n        log.info(f\" best_k: {k}\")\n\n        self.model._alpha = alpha\n        self.model._beta = beta\n        self.model._num_neighbours = int(np.round(k))\n\n        self.model.macest_model_params = self.set_macest_model_params()\n\n        self.model._distance_to_nn = None\n        self.model._ind_of_nn = None\n        self.model.point_preds = None\n\n        return self.model\n\n\ndef picp_loss(\n    interval_model: ModelWithPredictionInterval, x_test: np.ndarray, y_true: np.ndarray\n) -> float:\n    \"\"\"\n    Calculate the difference between the desired confidence level and the \\\n    prediction_interval_coverage_probability for several intervals.\n\n    :param interval_model: Some model which makes predictions with a standard deviation\n    :param x_test: The variables for which we would like to use to predict a distribution\n    :param y_true: The True target value\n\n    :return: The loss score\n    \"\"\"\n    levels = np.array((90, 70, 50, 30, 10))\n\n    intervals = interval_model.predict_interval(x_test, conf_level=levels,).T\n\n    lower = intervals[0]\n    upper = intervals[1]\n    loss = 0\n\n    for i in range(len(levels)):\n        loss += abs(\n            levels[i]\n            - (\n                100\n                * len(\n                    np.where(np.logical_and(y_true >= lower[i], y_true <= upper[i]))[0]\n                )\n                / len(y_true)\n            )\n        )\n    return loss / len(levels)\n", "meta": {"hexsha": "be78b929c6ad4429eb33eff858779b56c3d2b1e6", "size": 20794, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/macest/regression/models.py", "max_stars_repo_name": "LaudateCorpus1/macest", "max_stars_repo_head_hexsha": "0a6b7bd26a31900a55164c75938c074c116c78f6", "max_stars_repo_licenses": ["UPL-1.0", "Apache-2.0"], "max_stars_count": 88, "max_stars_repo_stars_event_min_datetime": "2021-08-20T15:34:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T04:26:20.000Z", "max_issues_repo_path": "src/macest/regression/models.py", "max_issues_repo_name": "LaudateCorpus1/macest", "max_issues_repo_head_hexsha": "0a6b7bd26a31900a55164c75938c074c116c78f6", "max_issues_repo_licenses": ["UPL-1.0", "Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-01-09T17:11:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T00:43:03.000Z", "max_forks_repo_path": "src/macest/regression/models.py", "max_forks_repo_name": "LaudateCorpus1/macest", "max_forks_repo_head_hexsha": "0a6b7bd26a31900a55164c75938c074c116c78f6", "max_forks_repo_licenses": ["UPL-1.0", "Apache-2.0"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2021-08-23T15:28:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T01:29:24.000Z", "avg_line_length": 37.0659536542, "max_line_length": 114, "alphanum_fraction": 0.6430220256, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 4641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.348645142101806, "lm_q1q2_score": 0.19733961263570088}}
{"text": "\"\"\"\nThis is the code associated to the paper \"Low Dimensional State Representation Learning with Robotics Priors in Continuous Action Spaces\"\nBotteghi N., et al, published in the International Conference of Intelligent Systems and Robots (IROS), September 2021.\n\nThe StateRepresentation class includes the encoder neural network for learning a low-dimensional state representation\nfrom high-dimesional observations (lidar data points + RGB camera images). The encoder is trained with a new set of\nrobotics priors tailored for continuous state and action spaces.\n\"\"\"\n\nimport tensorflow as tf\n# Hide some depreacation warnings and disable eager execution\ntf.logging.set_verbosity(tf.logging.ERROR)\nimport os\nimport numpy as np\nimport sonnet as snt\nfrom utils import load_pickle, reshape_observation, save_pickle\nfrom tqdm import tqdm\n\nclass ReplayBuffer:\n    def __init__(self, obs_dim, act_dim, size):\n        self.obs_dim = obs_dim\n        self.act_dim = act_dim\n        self.size = size\n\n        self.obs_buf = np.zeros([int(size), int(obs_dim)], dtype=np.float32)\n        self.acts_buf = np.zeros([int(size), int(act_dim)], dtype=np.float32)\n        self.rews_buf = np.zeros(int(size), dtype=np.float32)\n        self.done_buf = np.zeros(int(size), dtype=np.float32)\n        self.sample_nr_buf = np.zeros(int(size), dtype=np.float32)\n        self.ptr, self.size, self.max_size = 0, 0, int(size)\n\n    def store(self, obs, act, rew, done, sample_nr):\n        self.obs_buf[self.ptr] = obs\n        self.acts_buf[self.ptr] = act\n        self.rews_buf[self.ptr] = rew\n        self.done_buf[self.ptr] = done\n        self.sample_nr_buf[self.ptr] = sample_nr\n        self.ptr = (self.ptr + 1) % self.max_size  # replace oldest entry from memory\n        self.size = min(self.size + 1, self.max_size)\n\n    # def _get_act_seq\n\n    def sample_batch(self, batch_size=32):\n        idxs = np.random.randint(0, self.size - 1, size=batch_size)\n        idxs = idxs[self.done_buf[idxs] != 1.]  # remove the last samples of the sequence\n\n        obs_dict = dict(obs=self.obs_buf[idxs],\n                        acts=self.acts_buf[idxs],\n                        rews=self.rews_buf[idxs - 1],\n                        done=self.done_buf[idxs],\n                        sample_nr=self.sample_nr_buf[idxs])\n        next_obs_dict = dict(obs=self.obs_buf[idxs + 1],\n                             acts=self.acts_buf[idxs + 1],\n                             rews=self.rews_buf[idxs],\n                             done=self.done_buf[idxs + 1],\n                             sample_nr=self.sample_nr_buf[idxs + 1])\n        return obs_dict, next_obs_dict\n\n    def get_all_samples(self):\n        return dict(obs=self.obs_buf[:self.size],\n                    acts=self.acts_buf[:self.size],\n                    rews=self.rews_buf[:self.size],\n                    done=self.done_buf[:self.size],\n                    sample_nr=self.sample_nr_buf[:self.size])\n\n    def remove_all(self):\n        self.__init__(self.obs_dim, self.act_dim, self.size)\n\n\nclass StateRepresentation(object):\n    \"\"\"This class takes care of learning the state representation\"\"\"\n\n    def __init__(self, obs_dim, state_dim=5, act_dim=2, batch_size=256, learning_rate=5e-4,\n                 alpha=2, beta=10, seed=1, continuelearning=False, usingros=False):\n\n        folder = \"training_results\"\n        filename = 'SRLnetwork'\n        if usingros:\n            import rospkg\n            self.model_path = os.path.join(rospkg.RosPack().get_path(\"rosbot_srl\"), folder, \"srl\", filename + \".ckpt\")\n        else:\n            self.model_path = os.path.join(\"..\", folder, \"srl\", filename + \".ckpt\")\n\n        self.obs_dim = obs_dim   # size [32, 24, 40] with 32x24x3 --> size RGB image and 40 --> size of lidar array\n        self.obs_count = obs_dim[0] * obs_dim[1] * 3 + obs_dim[2]  #  calculate the flattened dimension of the observation vector\n        self.state_dim = state_dim\n        self.act_dim = act_dim   # linear and angular velocity of the robot\n        self.batch_size = batch_size\n        self.learning_rate = learning_rate\n        self.alpha = alpha   # priors coefficient (see paper for more details)\n        self.beta = beta   # priors coefficient (see paper for more details)\n        self.continuelearning = continuelearning\n\n        self.memory = ReplayBuffer(self.obs_count, act_dim=act_dim, size=3e4)\n\n        tf.random.set_random_seed(seed=seed)\n        np.random.seed(seed=seed)\n\n        # DEFINE THE FUNCTIONS REQUIRED FOR TRAINING\n        self.graph = tf.Graph()\n        with self.graph.as_default():\n            # Define the placeholders\n            self.obs_1 = tf.placeholder(tf.float32, shape=[None, self.obs_count], name='observation_1')\n            self.obs_2 = tf.placeholder(tf.float32, shape=[None, self.obs_count], name='observation_2')\n            self.obs_3 = tf.placeholder(tf.float32, shape=[None, self.obs_count], name='observation_3')\n            self.obs_4 = tf.placeholder(tf.float32, shape=[None, self.obs_count], name='observation_4')\n\n            self.act_1 = tf.placeholder(tf.float32, shape=[None, 2], name='action_1')\n            self.act_2 = tf.placeholder(tf.float32, shape=[None, 2], name='action_2')\n\n            self.is_training = tf.placeholder(tf.bool, shape=[], name=\"train_cond\")\n\n            # Define the neural network architecture and its output\n            self.nn = snt.Module(self.SRLencoder, name='SRL_Network')\n            self.state_1 = self.nn(self.obs_1, self.is_training)\n            self.state_2 = self.nn(self.obs_2, self.is_training)\n\n            self.state_delta = self.state_2 - self.state_1\n\n            self.state_shuff = self.nn(self.obs_3, self.is_training)\n            self.state_4 = self.nn(self.obs_4, self.is_training)\n            self.state_delt_shuff = self.state_4 - self.state_shuff\n\n            # define losses (i.e. the robotics priors) and optimizer (ADAM)\n\n            self.temp_coh_loss = self.temporal_coherence_prior(self.state_delta, self.act_1,alpha=self.alpha)\n\n            self.caus_loss = self.causality_prior(self.state_1, self.state_shuff, self.act_1,self.act_2, self.beta)\n\n            self.prop_loss = self.proportionality_prior(self.state_delta, self.state_delt_shuff, self.act_1, self.act_2,\n                                                        self.beta)\n\n            self.repeat_loss = self.repeatability_prior(self.state_1, self.state_shuff, self.state_delta,\n                                                        self.state_delt_shuff, self.act_1, self.act_2, self.beta)\n\n            graph_regularizers = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)\n            total_regularization_loss = tf.reduce_sum(graph_regularizers)\n\n            self.losses = [0, 1*self.temp_coh_loss, 2*self.caus_loss, 1*self.prop_loss, 1*self.repeat_loss,\n                           total_regularization_loss]\n            self.loss = tf.reduce_sum(self.losses)\n            self.losses[0] = tf.reduce_sum(self.losses[:])\n\n            optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate)\n            update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n            with tf.control_dependencies(update_ops):\n                self.train_op = optimizer.minimize(self.loss)\n\n            self.saver = tf.train.Saver()\n            self.init = tf.global_variables_initializer()\n\n        # Initialize the session\n        self.sess = tf.Session(graph=self.graph)\n        # Restore session if desired\n        if continuelearning:\n            print('Loading SR model from memory')\n            self.load_model()\n        else:\n            print(\"Starting SR model from scratch!\")\n            self.sess.run(self.init)\n\n    def SRLencoder(self, observations, is_training, l2_reg=0.001, batch_norm=False):\n\n        \"\"\"\n        The camera image and the lidar data points are separated from the flattened observation vector via snt.SliceByDim()\n        in camera_inputs and laser_inputs. camera_inputs are reshaped into [32, 24, 3] and fed to conv2d layers,\n        while laser_inputs are reshaped into [40, 1] and fed to a conv1d layer. Noise is added to the output during training\n        for preventing equal state predictions (for more details we reference to \"Learning State Representations with Robotics Priors\"\n        Jonschkowski R. et al).\n\n         image               laser\n           |                   |\n         conv2d              conv1d\n           |                   |\n         conv2d                |\n           |                   |\n        flatten             flatten\n           |                   |\n         dense               dense\n           |                   |\n           --------merge--------\n                     |\n                   dense\n                     |\n                   dense\n                     |\n                   dense\n                     |\n                   state\n\n\n        :param observations:\n        :param is_training:\n        :param l2_reg:\n        :param batch_norm:\n        :return state:\n        \"\"\"\n\n        regularizers = {\"w\": tf.contrib.layers.l2_regularizer(scale=l2_reg)}\n        initializers = {\"w\": tf.keras.initializers.he_normal()}\n\n        # Camera branch\n        camera_inputs = snt.SliceByDim(dims=[1], begin=[0], size=[self.obs_dim[0] * self.obs_dim[1] * 3])(observations)\n        camera_inputs = tf.reshape(camera_inputs, [-1, self.obs_dim[0], self.obs_dim[1], 3])\n\n        camera_conv1 = tf.layers.conv2d(camera_inputs, filters=32, kernel_size=3, strides=1, padding='valid',\n                                        activation=tf.nn.relu, kernel_regularizer=regularizers[\"w\"],\n                                        kernel_initializer=initializers[\"w\"])\n\n        if batch_norm:\n            camera_conv1 = tf.layers.batch_normalization(camera_conv1, training=is_training)\n\n        camera_conv2 = tf.layers.conv2d(camera_conv1, filters=64, kernel_size=3, strides=1, padding='valid',\n                                        activation=tf.nn.relu, kernel_regularizer=regularizers[\"w\"],\n                                        kernel_initializer=initializers[\"w\"])\n        if batch_norm:\n            camera_conv2 = tf.layers.batch_normalization(camera_conv2, training=is_training)\n\n        camera_flatten = snt.BatchFlatten()(camera_conv2)\n\n        camera_dense1 = tf.layers.dense(camera_flatten, 64, activation=tf.nn.relu, kernel_regularizer=regularizers[\"w\"],\n                                        kernel_initializer=initializers[\"w\"])\n\n        # Laser branch\n        laser_inputs = snt.SliceByDim(dims=[1], begin=[self.obs_dim[0] * self.obs_dim[1] * 3], size=[self.obs_dim[2]])(\n            observations)\n        laser_inputs = tf.reshape(laser_inputs, [-1, self.obs_dim[2], 1])\n\n        laser_conv1 = tf.layers.conv1d(laser_inputs, filters=32, kernel_size=3, strides=1, padding='valid',\n                                       activation=tf.nn.relu, kernel_regularizer=regularizers[\"w\"],\n                                       kernel_initializer=initializers[\"w\"])\n\n        if batch_norm:\n            laser_conv1 = tf.layers.batch_normalization(laser_conv1, training=is_training)\n\n\n        laser_flatten = snt.BatchFlatten()(laser_conv1)\n\n        laser_dense1 = tf.layers.dense(laser_flatten, 64, activation=tf.nn.relu, kernel_regularizer=regularizers[\"w\"],\n                                       kernel_initializer=initializers[\"w\"])\n\n        # Merged layers\n        merge_input = tf.concat(values=[camera_dense1, laser_dense1], axis=1)\n        merge_dense1 = tf.layers.dense(merge_input, 64, activation=tf.nn.relu, kernel_regularizer=regularizers[\"w\"],\n                                       kernel_initializer=initializers[\"w\"])\n        merge_dense2 = tf.layers.dense(merge_dense1, 32, activation=tf.nn.relu, kernel_regularizer=regularizers[\"w\"],\n                                       kernel_initializer=initializers[\"w\"])\n\n        state = tf.layers.dense(merge_dense2, self.state_dim, activation=None,\n                                      kernel_regularizer=regularizers[\"w\"], kernel_initializer=tf.initializers.zeros)\n\n        merge_noise = lambda x: tf.cond(self.is_training, lambda: x + tf.random_normal(shape=tf.shape(x), stddev=1e-6),\n                                        lambda: x)\n        return merge_noise(state)\n\n    def remember(self, observation, action, reward, done, sample_number):\n        self.memory.store(observation, action, reward, done, sample_number)\n\n    def learn(self):\n        with tqdm(total=self.memory.size) as pbar:\n            t_loss = 0\n            losses = np.zeros(6)\n            nr_batches = self.memory.size // self.batch_size\n            for _ in range(nr_batches):\n                b1 = self.memory.sample_batch(self.batch_size)\n                b2 = self.memory.sample_batch(self.batch_size)\n\n                l = min(len(b1[0].get('obs')), len(b2[0].get('obs')))\n\n                feed_dict = {self.obs_1: b1[0].get('obs')[:l], self.obs_2: b1[1].get('obs')[:l],\n                             self.obs_3: b2[0].get('obs')[:l], self.obs_4: b2[1].get('obs')[:l],\n                             self.act_1: b1[0].get('acts')[:l],\n                             self.act_2: b2[0].get('acts')[:l],\n                             self.is_training: True}\n\n                _, loss, l = self.sess.run([self.train_op, self.loss, self.losses], feed_dict=feed_dict)\n                t_loss += loss\n                losses += l\n                pbar.update(self.batch_size)\n\n        return t_loss / nr_batches, losses / nr_batches\n\n    def predict(self, observation):\n        feed_dict = {self.obs_1: np.reshape(observation, (1, -1)),\n                     self.is_training: False}\n        state = self.sess.run(self.state_1, feed_dict=feed_dict)\n        return state\n\n    def predict_all(self, observations, batch_size=512):\n        observations = observations.reshape(len(observations), -1)\n        states = np.ndarray([len(observations), self.state_dim])\n        num_batches = int(np.trunc((observations.shape[0] / batch_size)))\n\n        for i in range(num_batches):\n            states[i * batch_size: (i + 1) * (batch_size)] = self.sess.run(self.state_1, feed_dict={\n                self.obs_1: observations[i * batch_size: (i + 1) * (batch_size)], self.is_training: False})\n        states[num_batches * batch_size:] = self.sess.run(self.state_1, feed_dict={\n            self.obs_1: observations[num_batches * batch_size:], self.is_training: False})\n        return states\n\n    def get_memory_states(self):\n        states = []\n        mem = self.memory.get_all_samples().get('obs')\n\n        states = self.predict_all(mem)\n        return states, self.memory.get_all_samples()\n\n    def save_model(self):\n        print(\"SRL Network storing model..........\")\n        return self.saver.save(self.sess, self.model_path)\n\n    def load_model(self):\n        print(\"SRL Network restoring data...........\")\n        self.saver.restore(self.sess, self.model_path)\n\n    # Each prior is defined in a function\n\n    def temporal_coherence_prior(self, s_d, a1, alpha=2):\n        \"\"\"\n        E[||s_t+1 - s_t||_2 * e^(-alpha * ||a||_2)]\n\n        :param s_d: s_t+1 - s_t\n        :param a1:  action connecting s_t and s_t+1\n        :param alpha:\n        :return: expectation of the temporal coherence loss\n        \"\"\"\n\n        return tf.reduce_mean(tf.math.exp(-alpha * tf.norm(a1, ord=2, axis=1)) * tf.norm(s_d, ord=2, axis=1) ** 2)\n\n\n    def causality_prior(self, s1, s2, a1, a2, beta):\n        \"\"\"\n        E[e^(-||s1-s2||^2) * e^(-beta*||a1-a2||^2)]\n\n        :param s1: state s_t1\n        :param s2: state s_t2\n        :param a1: action connecting s_t1 and s_t1+1\n        :param a2:  action connecting s_t2 and s_t2+1\n        :param beta: weighting factor\n        :return: expectation of the causality loss\n        \"\"\"\n        closs1 = tf.math.exp(-tf.norm(s1 - s2, ord=2, axis=1) ** 2)\n        closs2 = tf.math.exp(-beta*tf.norm(a2 - a1, ord=2, axis=1) ** 2)\n\n        return tf.reduce_mean(closs1 * closs2)\n\n    def proportionality_prior(self, sd1, sd2, a1, a2, beta):\n        \"\"\"\n        E[(||s_t2+1 - s_t2||_2 - ||s_t1+1 - s_t1||_2)^2 * e^(-beta * ||a1 - a2||_2)^2]\n\n        :param sd1: s_t1+1 - s_t1\n        :param sd2: s_t2+1 - s_t2\n        :param a1: action connecting s_t1 and s_t1+1\n        :param a2: action connecting s_t2 and s_t2+1\n        :param beta: weighting factor\n        :return: expectation of the proportinality loss\n        \"\"\"\n        ploss1 = (tf.norm(sd2, ord=2, axis=1) - tf.norm(sd1, ord=2, axis=1)) ** 2\n        ploss2 = tf.math.exp(-beta * tf.norm(a1 - a2, ord=2, axis=1) ** 2)\n\n        return tf.reduce_mean(ploss1 * ploss2)\n\n\n    def repeatability_prior(self, s1, s2, s_d1, s_d2, a1, a2, beta):\n        \"\"\"\n        E[||(s_t2+1 - s_t2) - (s_t1+1 - s_t1)||_2)^2 * e^(-||s1-s2||^2) * e^(-beta * ||a1 - a2||_2)^2]\n\n\n        :param s1: state s_t1\n        :param s2: state s_t2\n        :param s_d1: s_t1+1 - s_t1\n        :param s_d2: s_t2+1 - s_t2\n        :param a1: action connecting s_t1 and s_t1+1\n        :param a2: action connecting s_t2 and s_t2+1\n        :param beta: weighting factor\n        :return: expectation of the repeatability loss\n        \"\"\"\n        rloss1 = tf.math.exp(-tf.norm(s1 - s2, ord=2, axis=1) ** 2)\n        rloss2 = tf.norm(s_d2 - s_d1, ord=2, axis=1) ** 2\n        rloss3 = tf.math.exp( -beta*tf.norm(a1 - a2, ord=2, axis=1) ** 2)\n\n        return tf.reduce_mean(rloss1 * rloss2 * rloss3)\n\n\nif __name__ == '__main__':\n    from Logger import Logger\n    import Plotter as plotter\n\n    # Load saved observations from memory (samples collected by random exploring the large 4 walls environment --> see our paper)\n    folder = 'training_data/observations_4walls_large.pkl'\n\n    data = load_pickle(folder)\n    print('Loaded {} data points'.format(len(data)))\n\n\n    srl = StateRepresentation(obs_dim=[32, 24, 40], state_dim=5, act_dim=2, batch_size=256, learning_rate=5e-4, alpha=2,\n                              beta=10, seed=3, continuelearning=False, usingros=False)\n\n\n    # add all data to srl memory\n    for d in data:\n        srl.remember(reshape_observation(d[0]), d[1], d[2], d[3], d[4])\n\n    epochs = 20\n    loss_history = []\n\n    # training the encoder for 20 epochs\n    for epoch in range(epochs):\n        loss, losses = srl.learn()\n        print('Finished epoch {}/{}. The loss this epoch was: {}'.format(epoch + 1, epochs, loss))\n        print('temp_coh_loss: {} caus_loss: {} prop_loss: {} repeat_loss: {}'.format(losses[1], losses[2], losses[3],\n                                                                                     losses[4]))\n\n        loss_history.append(losses)\n\n    # save the trained model\n    srl.save_model()\n\n    # compute all the states from the observations\n    print('Finished training, now predicting all states')\n    lg = Logger('./')\n    gt = []\n    for d in data:\n        gt.append(d[0][40:45])\n        lg.log(\"position_obs\", d[0][40:45])\n        lg.log(\"rewards\", d[2])\n\n    states, _ = srl.get_memory_states()\n\n    # visualise the results\n    print('Plotting the results')\n\n    plotter.plot_all_srl(states=states, rews=srl.memory.get_all_samples().get('rews'), data_dict=lg.logDict,\n                         loss_history=loss_history, trainingcycle=2, save=True, size=15000, name=\"continuous\")\n\n\n", "meta": {"hexsha": "0824950831489ea668059fc94cafc692f1cbf0a6", "size": 19188, "ext": "py", "lang": "Python", "max_stars_repo_path": "SRL_RoboticsPriors_ContinuousActions.py", "max_stars_repo_name": "nicob15/StateRepresentationLearning_with_RoboticsPriors", "max_stars_repo_head_hexsha": "a5bf33b3bafe2cdd55f9f2de5ecd1736c3165656", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SRL_RoboticsPriors_ContinuousActions.py", "max_issues_repo_name": "nicob15/StateRepresentationLearning_with_RoboticsPriors", "max_issues_repo_head_hexsha": "a5bf33b3bafe2cdd55f9f2de5ecd1736c3165656", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SRL_RoboticsPriors_ContinuousActions.py", "max_forks_repo_name": "nicob15/StateRepresentationLearning_with_RoboticsPriors", "max_forks_repo_head_hexsha": "a5bf33b3bafe2cdd55f9f2de5ecd1736c3165656", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.9084668192, "max_line_length": 137, "alphanum_fraction": 0.5976652074, "include": true, "reason": "import numpy", "num_tokens": 4712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.19733960624814278}}
{"text": "\"\"\"\nadaptive split data into bins.\n\"\"\"\n\nimport functools\n\nimport numpy as np\n\nfrom .data import data_index, data_mask\n\ntry:\n    import matplotlib.patches as mpathes\nexcept ImportError:\n    pass\n\n\nclass AdaptiveBound(object):\n    \"\"\"adaptive bound cut for data value\"\"\"\n\n    def __init__(self, base_data, bins):\n        if isinstance(bins, int):\n            self._base_data = np.array([base_data])\n            self.bins = [bins]\n        elif isinstance(bins, list):\n            self._base_data = np.array(base_data)\n            self.bins = bins\n        else:\n            raise TypeError(\n                \"bins should be int or list of int, \"\n                + \"insteading of {}\".format(type(bins))\n            )\n\n    @functools.lru_cache()\n    def get_bounds_data(self):\n        \"\"\"get split data bounds, and the data after splitting\"\"\"\n        base_bound = AdaptiveBound.base_bound(self._base_data)\n        bounds, datas = AdaptiveBound.loop_split_bound(\n            self._base_data, self.bins\n        )\n        return bounds, datas\n\n    def get_bounds(self):\n        \"\"\"get split data bounds\"\"\"\n        bounds, _ = self.get_bounds_data()\n        return bounds\n\n    def get_bool_mask(self, data):\n        \"\"\"bool mask for splitting data\"\"\"\n        bounds = self.get_bounds()\n        idx_data = data[: bounds[0][0].shape[0]]\n        ret = []\n        for lb, rb in bounds:\n            mask = np.logical_and(\n                idx_data >= lb[..., np.newaxis], idx_data < rb[..., np.newaxis]\n            )\n            mask = np.all(mask, axis=0)\n            ret.append(mask)\n        return ret\n\n    def split_full_data(self, data, base_index=None):\n        \"\"\"split structure data, (TODO because large IO,  the method is slow.)\"\"\"\n        base_data = [[data_index(data, i) for i in base_index]]\n        mask = self.get_bool_mask(base_data)\n        ret = []\n        for i in mask:\n            ret.append(data_mask(data, i))\n        return ret\n\n    def split_data(self, data):\n        \"\"\"split data, the shape is same as base_data\"\"\"\n        mask = self.get_bool_mask(data)\n        ret = []\n        for i in mask:\n            ret.append(data[..., i])\n        return ret\n\n    @staticmethod\n    def single_split_bound(data, n=2, base_bound=None):\n        \"\"\"split data in the order of data value\n\n        >>> data = np.array([1.0, 2.0, 1.4, 3.1])\n        >>> AdaptiveBound.single_split_bound(data)\n        [(1.0, 1.7...), (1.7..., 3.1...)]\n\n        \"\"\"\n        if base_bound is None:\n            base_bound = np.min(data), np.max(data) + 1e-6\n        num_lb = base_bound[0]\n        bounds = []\n        for j in range(1, n):\n            num_rb = np.percentile(data, j / n * 100, axis=0) + 1e-6\n            bounds.append((num_lb, num_rb))\n            num_lb = num_rb\n        bounds.append((num_lb, base_bound[1]))\n        return bounds\n\n    @staticmethod\n    def multi_split_bound(datas, n, base_bound=None):\n        \"\"\"multi data for single_split_bound, so `n` is list of int\n\n        >>> data = np.array([[1.0, 2.0, 1.4, 3.1], [2.0, 1.0, 3.0, 1.0]])\n        >>> bound, _ = AdaptiveBound.multi_split_bound(data, [2, 1])\n        >>> [(i[0][0]+1e-6, i[1][0]+1e-6) for i in bound]\n        [(1.0..., 1.7...), (1.7..., 3.1...)]\n\n        \"\"\"\n        datas = np.array(datas)\n        if base_bound is None:\n            base_bound = AdaptiveBound.base_bound(datas)\n        bound_chain = [base_bound]\n        data_chain = [datas]\n        for idx, size in enumerate(n):\n            new_bound_chain = []\n            new_data_chain = []\n            for bnd, data in zip(bound_chain, data_chain):\n                idx_data = data[idx]\n                bounds = AdaptiveBound.single_split_bound(\n                    idx_data, size, base_bound=(bnd[0][idx], bnd[1][idx])\n                )\n                for i in bounds:\n                    lb, rb = i\n                    l_bnd, r_bnd = bnd\n                    l_bnd = np.copy(l_bnd)\n                    r_bnd = np.copy(r_bnd)\n                    l_bnd[idx] = lb\n                    r_bnd[idx] = rb\n                    new_bound_chain.append((l_bnd, r_bnd))\n                    mask = np.logical_and(idx_data >= lb, idx_data < rb)\n                    new_data_chain.append(data[:, mask])\n            bound_chain = new_bound_chain\n            data_chain = new_data_chain\n        return bound_chain, data_chain\n\n    @staticmethod\n    def loop_split_bound(datas, n, base_bound=None):\n        \"\"\"loop for multi_split_bound, so `n` is list of list of int\"\"\"\n        datas = np.array(datas)\n        if base_bound is None:\n            base_bound = AdaptiveBound.base_bound(datas)\n        bound_chain = [base_bound]\n        data_chain = [datas]\n        for idx, size in enumerate(n):\n            new_bound_chain = []\n            new_data_chain = []\n            for bnd, data in zip(bound_chain, data_chain):\n                bound, data_i = AdaptiveBound.multi_split_bound(\n                    data, size, base_bound=bnd\n                )\n                new_bound_chain += bound\n                new_data_chain += data_i\n            bound_chain = new_bound_chain\n            data_chain = new_data_chain\n        return bound_chain, data_chain\n\n    @staticmethod\n    def base_bound(data):\n        \"\"\"base bound for the data\"\"\"\n        lb = np.min(data, axis=-1) - 1e-6\n        rb = np.max(data, axis=-1) + 1e-6\n        return (lb, rb)\n\n    def get_bound_patch(self, **kwargs):\n        ret = []\n        for i, bnd in enumerate(self.get_bounds()):\n            min_x, min_y = bnd[0]\n            max_x, max_y = bnd[1]\n            rect = mpathes.Rectangle(\n                (min_x, min_y), max_x - min_x, max_y - min_y, **kwargs\n            )  # cmap(weights[i]/max_weight))\n            ret.append(rect)\n        return ret\n\n    def plot_bound(self, ax, **kwargs):\n        for i in self.get_bound_patch(**kwargs):\n            ax.add_patch(i)\n\n\ndef cal_chi2(numbers, n_fp):\n    weights = []\n    # print(numbers)\n    # chi21 = []\n    for ndata, nmc in numbers:\n        weight = (ndata - nmc) / np.sqrt(np.abs(ndata))\n        weights.append(weight ** 2)\n        # chi21.append(ndata * np.log(nmc))\n    max_weight = np.max(weights)\n    chi2 = np.sum(weights)\n    print(\"bins: \", len(weights))\n    print(\"number of free parameters: \", n_fp)\n    ndf = len(weights) - 1 - n_fp\n    print(\n        \"chi2/ndf: \", np.sum(weights), \"/\", ndf\n    )  # ,\"another\", np.sum(chi21))\n    return chi2, ndf\n", "meta": {"hexsha": "b5d4f988a7a84bcc1c34aa933855a3047e2b8b57", "size": 6390, "ext": "py", "lang": "Python", "max_stars_repo_path": "tf_pwa/adaptive_bins.py", "max_stars_repo_name": "ReynLieu/tf-pwa", "max_stars_repo_head_hexsha": "f354b5036bc8c37ffba95849de5ec3367934eef8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-05-10T15:17:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-16T07:40:06.000Z", "max_issues_repo_path": "tf_pwa/adaptive_bins.py", "max_issues_repo_name": "ReynLieu/tf-pwa", "max_issues_repo_head_hexsha": "f354b5036bc8c37ffba95849de5ec3367934eef8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 45, "max_issues_repo_issues_event_min_datetime": "2020-10-24T08:26:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T06:14:58.000Z", "max_forks_repo_path": "tf_pwa/adaptive_bins.py", "max_forks_repo_name": "ReynLieu/tf-pwa", "max_forks_repo_head_hexsha": "f354b5036bc8c37ffba95849de5ec3367934eef8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-10-24T06:41:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T01:29:49.000Z", "avg_line_length": 32.7692307692, "max_line_length": 81, "alphanum_fraction": 0.5374021909, "include": true, "reason": "import numpy", "num_tokens": 1613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961013, "lm_q2_score": 0.34864512856608565, "lm_q1q2_score": 0.19733960497423222}}
{"text": "import psi4 \nimport numpy as np\n\npsi4.set_options({'scf_type': 'df',\n                  'freeze_core': 'true'})\n                  \n#different combinations of the isomers \n\n#O/M = comparison1 \n#O/P = comparison2 \n#M/P = comparison3 \n\n#comparison1 O/M               \n\n\ncomparison1 = psi4.geometry(\"\"\"\n\n0 1 \n\nO          1.72900        1.44890        1.30290\nO          0.52150       -2.76860        0.50990\nO          1.94280        1.60280       -0.95480\nO          1.94610       -1.35340       -0.55510\nC         -0.07460        0.73300       -0.00740\nC         -0.28440       -0.64490       -0.05810\nC         -1.16380        1.60440        0.00750\nC         -1.58340       -1.15170       -0.09400\nC         -2.46290        1.09750       -0.02840\nC         -2.67270       -0.28050       -0.07920\nC          1.27000        1.29310        0.03190\nC          0.83250       -1.58060       -0.07500\nH         -1.01340        2.68020        0.04680\nH         -1.78090       -2.21920       -0.14740\nH         -3.31100        1.77580       -0.01770\nH         -3.68430       -0.67460       -0.11040\nH          2.63430        1.82640        1.32040\nH          1.27850       -3.39240        0.49470\n\n--\n\n0 1 \nO         -3.54720        0.18420        0.00030\nO          3.54710        0.18450       -0.00070\nO         -2.58510       -1.87520       -0.00050\nO          2.58550       -1.87510        0.00060\nC         -1.20810        0.08130        0.00030\nC          1.20790        0.08110       -0.00010\nC         -0.00020       -0.61630        0.00010\nC         -1.20790        1.47630        0.00020\nC          1.20790        1.47610       -0.00020\nC          0.00000        2.17360        0.00010\nC         -2.46790       -0.64530       -0.00040\nC          2.46800       -0.64530        0.00040\nH         -0.00020       -1.70390        0.00010\nH         -2.12470        2.05900        0.00020\nH          2.12470        2.05880       -0.00020\nH          0.00010        3.25980        0.00000\nH         -4.39140       -0.31530        0.00040\nH          4.39150       -0.31500       -0.00100\n\"\"\")\n\npsi4.energy('sapt0/jun-cc-pvdz', molecule=comparison1)\n\n\none_disp = psi4.variable('SSAPT0 DISP ENERGY')\none_elst = psi4.variable('SSAPT0 ELST ENERGY')\none_exch = psi4.variable('SSAPT0 EXCH ENERGY')\none_ind = psi4.variable('SSAPT0 IND ENERGY')\none_tot =psi4.variable('SSAPT0 TOTAL ENERGY')\n\n\n\n#comparison2 O/P\n \ncomparison2 = psi4.geometry(\"\"\"\n \n0 1\n \nO          1.72900        1.44890        1.30290\nO          0.52150       -2.76860        0.50990\nO          1.94280        1.60280       -0.95480\nO          1.94610       -1.35340       -0.55510\nC         -0.07460        0.73300       -0.00740\nC         -0.28440       -0.64490       -0.05810\nC         -1.16380        1.60440        0.00750\nC         -1.58340       -1.15170       -0.09400\nC         -2.46290        1.09750       -0.02840\nC         -2.67270       -0.28050       -0.07920\nC          1.27000        1.29310        0.03190\nC          0.83250       -1.58060       -0.07500\nH         -1.01340        2.68020        0.04680\nH         -1.78090       -2.21920       -0.14740\nH         -3.31100        1.77580       -0.01770\nH         -3.68430       -0.67460       -0.11040\nH          2.63430        1.82640        1.32040\nH          1.27850       -3.39240        0.49470\n \n--\n \n0 1 \nO          3.39660        1.18370       -0.00030\nO         -3.39650       -1.18360       -0.00070\nO          3.54230       -1.08460        0.00020\nO         -3.54230        1.08470        0.00000\nC          1.39460       -0.03050       -0.00050\nC         -1.39450        0.03050        0.00050\nC          0.72350        1.19240       -0.00030\nC         -0.67100        1.22300        0.00030\nC          0.67090       -1.22310       -0.00020\nC         -0.72370       -1.19250        0.00030\nC          2.84840       -0.06240        0.00030\nC         -2.84820        0.06250        0.00030\nH          1.24760        2.14410       -0.00030\nH         -1.17530        2.18580        0.00040\nH          1.17520       -2.18590       -0.00010\nH         -1.24770       -2.14420        0.00050\nH          4.37700        1.15110       -0.00040\nH         -4.37700       -1.15080       -0.00130\n\"\"\")\n\npsi4.energy('sapt0/jun-cc-pvdz', molecule=comparison2)\n\n\n\ntwo_disp = psi4.variable('SSAPT0 DISP ENERGY')\ntwo_elst = psi4.variable('SSAPT0 ELST ENERGY')\ntwo_exch = psi4.variable('SSAPT0 EXCH ENERGY')\ntwo_ind = psi4.variable('SSAPT0 IND ENERGY')\ntwo_tot =psi4.variable('SSAPT0 TOTAL ENERGY')\n\n\n#comparison3 M/P\n\ncomparison3 = psi4.geometry(\"\"\"\n\n0 1 \nO         -3.54720        0.18420        0.00030\nO          3.54710        0.18450       -0.00070\nO         -2.58510       -1.87520       -0.00050\nO          2.58550       -1.87510        0.00060\nC         -1.20810        0.08130        0.00030\nC          1.20790        0.08110       -0.00010\nC         -0.00020       -0.61630        0.00010\nC         -1.20790        1.47630        0.00020\nC          1.20790        1.47610       -0.00020\nC          0.00000        2.17360        0.00010\nC         -2.46790       -0.64530       -0.00040\nC          2.46800       -0.64530        0.00040\nH         -0.00020       -1.70390        0.00010\nH         -2.12470        2.05900        0.00020\nH          2.12470        2.05880       -0.00020\nH          0.00010        3.25980        0.00000\nH         -4.39140       -0.31530        0.00040\nH          4.39150       -0.31500       -0.00100\n\n--\n \n0 1 \nO          3.39660        1.18370       -0.00030\nO         -3.39650       -1.18360       -0.00070\nO          3.54230       -1.08460        0.00020\nO         -3.54230        1.08470        0.00000\nC          1.39460       -0.03050       -0.00050\nC         -1.39450        0.03050        0.00050\nC          0.72350        1.19240       -0.00030\nC         -0.67100        1.22300        0.00030\nC          0.67090       -1.22310       -0.00020\nC         -0.72370       -1.19250        0.00030\nC          2.84840       -0.06240        0.00030\nC         -2.84820        0.06250        0.00030\nH          1.24760        2.14410       -0.00030\nH         -1.17530        2.18580        0.00040\nH          1.17520       -2.18590       -0.00010\nH         -1.24770       -2.14420        0.00050\nH          4.37700        1.15110       -0.00040\nH         -4.37700       -1.15080       -0.00130\n\"\"\")\n\n\npsi4.energy('sapt0/jun-cc-pvdz', molecule=comparison3)\n\n\nthree_disp = psi4.variable('SSAPT0 DISP ENERGY')\nthree_elst = psi4.variable('SSAPT0 ELST ENERGY')\nthree_exch = psi4.variable('SSAPT0 EXCH ENERGY')\nthree_ind = psi4.variable('SSAPT0 IND ENERGY')\nthree_tot =psi4.variable('SSAPT0 TOTAL ENERGY')\n\n#comparing the interaction energies for each dimer \n\nlabels = np.array(['disp','elst','exch','ind','tot'])\n\ndispersion = np.array([one_disp,two_disp,three_disp])\n\nelst = np.array([one_elst,two_elst,three_elst])\n\nexch = np.array([one_exch,two_exch,three_exch])\n\nind = np.array([one_ind,two_ind,three_ind])\n\nind = np.array([one_ind,two_ind,three_ind])\n\ntot = np.array([one_tot,two_tot,three_tot])\n\n#plotting these comparisons \n\nplt.plot(comparison,tot,'-ob')\n\nplt.plot(comparison,ind,'-xr')\n\nplt.plot(comparison,exch,'-py')\n\nplt.plot(comparison,elst,'-dk')\n\nplt.plot(comparison,dispersion,'-m<')\n\nplt.show()\n\n\n", "meta": {"hexsha": "af226cfce5a6d0af4f02d92d573b4c352f09cc96", "size": 7256, "ext": "py", "lang": "Python", "max_stars_repo_path": "calculation.py", "max_stars_repo_name": "mw00847/OMP", "max_stars_repo_head_hexsha": "b2cd0e4d212e359e11afb5940e25d20018f07053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "calculation.py", "max_issues_repo_name": "mw00847/OMP", "max_issues_repo_head_hexsha": "b2cd0e4d212e359e11afb5940e25d20018f07053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calculation.py", "max_forks_repo_name": "mw00847/OMP", "max_forks_repo_head_hexsha": "b2cd0e4d212e359e11afb5940e25d20018f07053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9818181818, "max_line_length": 54, "alphanum_fraction": 0.4714718853, "include": true, "reason": "import numpy", "num_tokens": 2748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3208212878370535, "lm_q1q2_score": 0.19733327793959593}}
{"text": "\"\"\"\nDynamic Routing Between Capsules\nhttps://arxiv.org/abs/1710.09829\n\nPyTorch implementation by Kenta Iwasaki @ Gram.AI.\nCapsRT implemented by horsepurve.\n\"\"\"\n\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\nimport numpy as np\nfrom torch.autograd import Variable\nimport pickle\nfrom scipy import sparse\nfrom config import *\n\nCNN_EMB = True # False # \n\nBATCH_SIZE = 16 # 16\nNUM_CLASSES = 10\nNUM_EPOCHS = 20\nNUM_ROUTING_ITERATIONS = 1\nCUDA = False # True # False # \nLR = 0.01\n\n# train_path = 'data/dia_train_269.txt' # 'data/mod_train_2.txt' # 'data/unmod_train_2.txt' # 'data/SCX_train_42.txt' # \n# test_path = 'data/dia_test_269.txt' # 'data/mod_test_2.txt' # 'data/unmod_test_2.txt' # 'data/SCX_test_42.txt' # \n# result_path = 'dia_pred_269.txt' # 'mod_pred_2.txt' # 'unmod_pred_2.txt' # 'SCX_pred_42.txt' # \nRTdata_path = 'dia.pkl' # 'mod.pkl' # 'unmod.pkl' # 'SCX.pkl' # \nLOAD_DATA = True # False # \n# TODO: add max_length to config.py\n## max_length = 66 # 66 # 50 # 38 # 50 # \n\n# log_path = ''\nif '' == dict_path:\n    dict_path = train_path\n\nfrom RTdata_emb import Dictionary, RTdata, Pearson, Spearman, Delta_t95, DATA_AUGMENTATION, Corpus\ndictionary = Dictionary(dict_path)\n'''\nif True == LOAD_DATA:\n    dictionary = Dictionary(dict_path)\n    RTtrain = RTdata(dictionary, max_length, train_path)\n    RTtest = RTdata(dictionary, max_length, test_path)\n    with open(RTdata_path, 'wb') as output:\n        pickle.dump(dictionary, output)\n        pickle.dump(RTtrain, output)\n        pickle.dump(RTtest, output)\nif False == LOAD_DATA:\n    with open(RTdata_path, 'rb') as input:\n        dictionary = pickle.load(input)\n        RTtrain = pickle.load(input)\n        RTtest = pickle.load(input)\n        print('>> note: load pre-read RTdata from:', RTdata_path)\n\n# DATA_AUGMENTATION = True\nSPARSE = True\ndef desparse(RTtt):\n    X = np.zeros((RTtt.number_seq, RTtt.N_aa, RTtt.N_time_step)) # DATA_AUGMENTATION->*2\n    for i in range(RTtt.number_seq): # DATA_AUGMENTATION->*2\n        # sparse to dense\n        X[i,::] = RTtt.X[i].todense()\n    RTtt.X = X\nif True == SPARSE:\n    print('>> note: de-sparse for both train & test data.')\n    desparse(RTtrain)\n    desparse(RTtest)\n'''\n\ndef softmax(input, dim=1):\n    transposed_input = input.transpose(dim, len(input.size()) - 1)\n    # print(transposed_input.contiguous().view(-1, transposed_input.size(-1)).shape)\n    '''\n    PyTorch 0.3.0:\n    UserWarning: Implicit dimension choice for softmax has been deprecated. Change the call to include dim=X as an argument.\n    '''\n    softmaxed_output = F.softmax(transposed_input.contiguous().view(-1, transposed_input.size(-1)),dim=1)\n    return softmaxed_output.view(*transposed_input.size()).transpose(dim, len(input.size()) - 1)\n\n\ndef augmentation(x, max_shift=2):\n    _, _, height, width = x.size()\n\n    h_shift, w_shift = np.random.randint(-max_shift, max_shift + 1, size=2)\n    source_height_slice = slice(max(0, h_shift), h_shift + height)\n    source_width_slice = slice(max(0, w_shift), w_shift + width)\n    target_height_slice = slice(max(0, -h_shift), -h_shift + height)\n    target_width_slice = slice(max(0, -w_shift), -w_shift + width)\n\n    shifted_image = torch.zeros(*x.size())\n    shifted_image[:, :, source_height_slice, source_width_slice] = x[:, :, target_height_slice, target_width_slice]\n    return shifted_image.float() # Note float here!\n\n\nclass CapsuleLayer(nn.Module):\n    def __init__(self, \n                 num_capsules, \n                 num_route_nodes, \n                 in_channels, \n                 out_channels, \n                 kernel_size=None, \n                 stride=None,\n                 num_iterations=NUM_ROUTING_ITERATIONS):\n\n        super(CapsuleLayer, self).__init__()\n\n        self.num_route_nodes = num_route_nodes\n        self.num_iterations = num_iterations\n\n        self.num_capsules = num_capsules\n\n        if num_route_nodes != -1:\n            self.route_weights = nn.Parameter(torch.randn(num_capsules, \n                                                          num_route_nodes, \n                                                          in_channels, \n                                                          out_channels))\n        else:\n            self.capsules = nn.ModuleList(\n                [nn.Conv2d(in_channels, \n                           out_channels, \n                           kernel_size=kernel_size, \n                           stride=stride, \n                           padding=0) for _ in\n                 range(num_capsules)])\n\n    def squash(self, tensor, dim=-1):\n        squared_norm = (tensor ** 2).sum(dim=dim, keepdim=True)\n        scale = squared_norm / (1 + squared_norm)\n        return scale * tensor / torch.sqrt(squared_norm)\n\n    def forward(self, x):\n        if self.num_route_nodes != -1:\n            priors = x[None, :, :, None, :] @ self.route_weights[:, None, :, :, :]\n\n            if True == CUDA:\n                logits = Variable(torch.zeros(*priors.size())).cuda()\n            if False == CUDA:\n                logits = Variable(torch.zeros(*priors.size()))\n\n            for i in range(self.num_iterations):\n                probs = softmax(logits, dim=2)\n                outputs = self.squash((probs * priors).sum(dim=2, keepdim=True))\n\n                if i != self.num_iterations - 1:\n                    delta_logits = (priors * outputs).sum(dim=-1, keepdim=True)\n                    logits = logits + delta_logits\n        else:\n            outputs = [capsule(x).view(x.size(0), -1, 1) for capsule in self.capsules]\n            outputs = torch.cat(outputs, dim=-1)\n            outputs = self.squash(outputs)\n\n        return outputs\n\nparam_2D = {'data' : 'mnist',\n            'dim' : 2,\n            'conv1_kernel' : 9,\n            'pri_caps_kernel' : 9,\n            'stride' : 2,\n            'digit_caps_nodes' : 32 * 6 * 6,\n            'NUM_CLASSES' : NUM_CLASSES}\n\nparam_1D = {'data' : 'mnist',\n            'dim' : 1,\n            'conv1_kernel' : (28, 9),\n            'pri_caps_kernel' : (1, 9),\n            'stride' : 1,\n            'digit_caps_nodes' : 32 * 1 * 12,\n            'NUM_CLASSES' : 1}\n\n# conv1_kernel = 15\n# conv2_kernel = 15\nparam_1D_rt = {'data' : 'rt',\n               'dim' : 1,\n               'conv1_kernel' : (len(dictionary), conv1_kernel),\n               'pri_caps_kernel' : (1, conv2_kernel),\n               'stride' : 1,\n               'digit_caps_nodes' : 32 * 1 * (max_length - conv1_kernel*2 + 2 - conv2_kernel + 1), # 32 # Note: number of conv!\n               'NUM_CLASSES' : 1}\n\nparam = param_1D_rt\n\nif 2 == param['dim']:\n    print('>> note: using image mode.')\nif 1 == param['dim']:\n    print('>> note: using seq mode.')\n\nclass CapsuleNet(nn.Module):\n    def __init__(self,conv1_kernel,conv2_kernel):\n        super(CapsuleNet, self).__init__()\n        EMB_SIZE = 0\n        if True == CNN_EMB:\n            # self.emb = nn.Embedding(len(dictionary), len(dictionary))\n            # Note: if using embedding, EMB_SIZE can be any value, and we choose 20 here\n            EMB_SIZE = 20\n            self.emb = nn.Embedding(len(dictionary), EMB_SIZE) # we use 20 for all data\n        else:\n            # Note: if using one-hot encoding, EMB_SIZE must be the same as len(dictionary)\n            EMB_SIZE = len(dictionary)\n        self.conv1 = nn.Conv2d(in_channels=1, \n                               out_channels=256, # 256\n                               kernel_size=(EMB_SIZE, conv1_kernel), # param['conv1_kernel'], # (28, 9), # 9, \n                               stride=1)\n        ''''''\n        self.bn1 = nn.BatchNorm2d(256) # Note: do we need this or not?\n        self.conv2 = nn.Conv2d(in_channels=256, \n                               out_channels=256, # 256\n                               kernel_size=(1, conv1_kernel), # (28, 9), # 9, \n                               stride=1)\n        self.bn2 = nn.BatchNorm2d(256)\n        '''\n        self.conv3 = nn.Conv2d(in_channels=128, \n                               out_channels=256, # 256\n                               kernel_size=(1, conv1_kernel), # (28, 9), # 9, \n                               stride=1)\n        self.bn3 = nn.BatchNorm2d(256)\n        '''\n\n        self.primary_capsules = CapsuleLayer(num_capsules=8, # 8\n                                             num_route_nodes=-1, \n                                             in_channels=256, # 256\n                                             out_channels=32, # 32\n                                             kernel_size=(1, conv2_kernel), # param['pri_caps_kernel'], # (1, 9), # 9, \n                                             stride=param['stride']) # 1) # 2)\n\n        self.digit_capsules = CapsuleLayer(num_capsules=param['NUM_CLASSES'], # 1, #NUM_CLASSES, # DeepRT\n                                           num_route_nodes=32 * 1 * (max_length - conv1_kernel*2 + 2 - conv2_kernel + 1), # param['digit_caps_nodes'], # 32 * 1 * 12, # 32 * 6 * 6, \n                                           in_channels=8, # 8\n                                           out_channels=16) # max_length-conv1_kernel + 1) # 16\n\n        # add dropout:\n        # self.dropout = nn.Dropout(0.1) # not good!\n        # self.linear = nn.Linear((max_length-conv1_kernel+1)*256,16) # try residue: not good!\n        ''' residue is not very good!\n        pad = 0\n        kernel_h = pad*2+1 # len + pad*2 - (kernel_h - 1) = len\n        self.conv_res = nn.Conv2d(in_channels=256, \n                                  out_channels=1, # 256\n                                  kernel_size=(1, kernel_h), # (28, 9), # 9, \n                                  stride=1)\n                                  #padding =(0,pad))\n        '''\n        self.decoder = nn.Sequential(\n            nn.Linear(16 * NUM_CLASSES, 512),\n            nn.ReLU(inplace=True),\n            nn.Linear(512, 1024),\n            nn.ReLU(inplace=True),\n            nn.Linear(1024, 784),\n            nn.Sigmoid()\n        )\n\n    def forward(self, x, y=None):\n        # print('>>dim: input', x.shape) # [batch, 1, 28, 28]\n        # print('>>dim: y', y) # [batch, 10] ~ [batch, NUM_CLASSES]\n        if True == CNN_EMB:\n            x = self.emb(x) # [batch, len] -> [batch, len, dict]\n            x = x.transpose(dim0=1, dim1=2) # -> [batch, dict, len]\n            x = x[:,None,:,:] # -> [batch, 1, dict, len]\n\n        # ^^^^^ pre-process x ^^^^^\n        x = F.relu(self.bn1(self.conv1(x)), inplace=True)      \n\n        ''' try residue: not good! \n        residue = x.view(x.shape[0],-1)        \n        residue = self.linear(residue).view(residue.shape[0],1,16)\n        # another residue method\n        residue = F.relu(self.conv_res(x), inplace=True)\n        residue = residue.view(residue.shape[0],1,residue.shape[-1])\n        '''\n\n        # x = self.dropout(x)\n        x = F.relu(self.bn2(self.conv2(x)), inplace=True) # improvement\n        # x = F.relu(self.bn3(self.conv3(x)), inplace=True)\n        # print('>>dim: conv1', x.shape) # [batch, 256, 20, 20]\n        x = self.primary_capsules(x)\n        # print('>>dim: primary_capsules', x.shape) # [batch, 1152, 8] = [batch, 6*6*32, 8]\n        # print('>>dim: unsqueezeed', self.digit_capsules(x).shape) # [10, batch, 1, 1, 16] ~ [num_caps, batch, ...]\n        if 2 == param['dim']:\n            x = self.digit_capsules(x).squeeze().transpose(0, 1) # DeepRT\n            # [10, batch, 1, 1, 16] -> squeeze: [10, batch, 16] -> transpose: [batch, 10, 16]\n        if 1 == param['dim']:\n            x = self.digit_capsules(x).squeeze()[:, None, :]\n            # [1, batch, 1, 1, 16] -> squeeze: [batch, 16]\n        # print('>>dim: digit_capsules', x.shape) # [batch, 10, 16]\n\n        # add dropout:\n        # x = self.dropout(x)\n        # x = self.linear(x)\n        # x = F.sigmoid(x)\n        \n        # x = x + residue # try residue: not good!\n        classes = (x ** 2).sum(dim=-1) ** 0.5\n        # print('>>dim: classes', classes) # [batch, 10]\n        if 2 == param['dim']:\n            classes = F.softmax(classes) # DeepRT\n        # print('>>dim: softmax', classes)\n\n        if y is None: # Note: not do this during training. Here y is only used for reconstruction\n            if 2 == param['dim']:\n                # In all batches, get the most active capsule.\n                # print('>>dim: reconstruction', classes) # [batch, 10]\n                _, max_length_indices = classes.max(dim=1) \n                # give: [torch.FloatTensor of size batch] and [torch.FloatTensor of size batch]\n                if True == CUDA:\n                    y = Variable(torch.sparse.torch.eye(NUM_CLASSES)).cuda().index_select(dim=0, index=max_length_indices.data)\n                if False == CUDA:\n                    y = Variable(torch.sparse.torch.eye(NUM_CLASSES)).index_select(dim=0, index=max_length_indices.data)\n                # generate a new y: [batch, 10] with each column having 1 in batch 0\n\n        if 2 == param['dim']:\n            # print('>>dim: x*y', x.shape, y.shape)\n            reconstructions = self.decoder((x * y[:, :, None]).view(x.size(0), -1))\n           # x: [batch, 10, 16], y: [batch, 10] -> [batch, 10, 1]\n            return classes, reconstructions\n        if 1 == param['dim']:\n            return classes, x # Note here\n\nclass CapsuleLoss(nn.Module):\n    def __init__(self):\n        super(CapsuleLoss, self).__init__()\n        self.reconstruction_loss = nn.MSELoss(size_average=False)\n\n    def forward(self, images, labels, classes, reconstructions):\n        if 2 == param['dim']:\n            # print('>>dim: labels', labels) # [batch, 10]\n            # print('>>dim: classes', classes) # [batch, 10]\n            left = F.relu(0.9 - classes, inplace=True) ** 2\n            right = F.relu(classes - 0.1, inplace=True) ** 2\n\n            margin_loss = labels * left + 0.5 * (1. - labels) * right\n            margin_loss = margin_loss.sum()\n\n            reconstruction_loss = self.reconstruction_loss(reconstructions, images)\n\n            loss = (margin_loss + 0.0005 * reconstruction_loss) / images.size(0)\n            # print('>>dim: loss', loss) # it's a single value\n            return loss\n        if 1 == param['dim']:\n            # print('>>dim: labels', labels) # torch.cuda.FloatTensor of size batch x 1\n            # print('>>dim: classes', classes) # [batch, 1]\n\n            '''\n            square = (labels - classes) ** 2\n            square = square.sort(dim=0,descending=False)[0]\n            cut = int(labels.shape[0]-1)\n            loss = (square[:cut]).sum()/cut\n            loss = loss ** 0.5 + square[cut] ** 0.5\n            '''\n            loss = ((labels - classes) ** 2).sum()/labels.shape[0] # MSE # Note: here it must be sum()\n            loss = loss ** 0.5 # RMSE\n            \n            # print('>>dim: loss', loss)\n            return loss\n\ndef desparse(RTtt):\n    if False == DATA_AUGMENTATION:\n        X = np.zeros((RTtt.number_seq, RTtt.N_aa, RTtt.N_time_step)) # DATA_AUGMENTATION->*2\n        for i in range(RTtt.number_seq): # DATA_AUGMENTATION->*2\n            # sparse to dense\n            X[i,::] = RTtt.X[i].todense()\n        RTtt.X = X\n    else:\n        print('>> note: usnig data_augmentation')\n        X = np.zeros((RTtt.number_seq*2, RTtt.N_aa, RTtt.N_time_step)) # DATA_AUGMENTATION->*2\n        for i in range(RTtt.number_seq*2): # DATA_AUGMENTATION->*2\n            # sparse to dense\n            X[i,::] = RTtt.X[i].todense()\n        RTtt.X = X\n\nif __name__ == \"__main__\":\n    # from torch.autograd import Variable\n    from torch.optim import Adam # Adam\n    from torchnet.engine import Engine\n    # from torchnet.logger import VisdomPlotLogger, VisdomLogger\n    # from torchvision.utils import make_grid\n    # from torchvision.datasets.mnist import MNIST\n    from tqdm import tqdm\n    import torchnet as tnt\n    import gc \n    from time import sleep, time\n    import timeit\n    T1 = timeit.default_timer()\n\n    # read data ========== ========== ========== ========== ========== ==========\n    # CNN_EMB = True\n    if False == CNN_EMB:\n        print('>> note: using one-hot encoding.')\n        if True == LOAD_DATA:\n            # dictionary = Dictionary(dict_path)\n            RTtrain = RTdata(dictionary, max_length, train_path)\n            RTtest = RTdata(dictionary, max_length, test_path)\n            with open(RTdata_path, 'wb') as output:\n                # pickle.dump(dictionary, output)\n                pickle.dump(RTtrain, output)\n                pickle.dump(RTtest, output)\n        if False == LOAD_DATA:\n            with open(RTdata_path, 'rb') as input:\n                # dictionary = pickle.load(input)\n                RTtrain = pickle.load(input)\n                RTtest = pickle.load(input)\n                print('>> note: load pre-read RTdata from:', RTdata_path)\n        \n        # DATA_AUGMENTATION = True\n        SPARSE = True\n        # def desparse(RTtt):\n        #     X = np.zeros((RTtt.number_seq, RTtt.N_aa, RTtt.N_time_step)) # DATA_AUGMENTATION->*2\n        #     for i in range(RTtt.number_seq): # DATA_AUGMENTATION->*2\n        #         # sparse to dense\n        #         X[i,::] = RTtt.X[i].todense()\n        #     RTtt.X = X\n        if True == SPARSE:\n            print('>> note: de-sparse for both train & test data.')\n            desparse(RTtrain)\n            desparse(RTtest)\n    if True == CNN_EMB:\n        print('>> note: using >>>embedding<<< method.')\n        corpus = Corpus(dictionary, # format: Corpus(dictionary, train_path, val_path='', test_path='', pad_length=0)\n                        train_path,\n                        test_path=test_path,\n                        pad_length=max_length)         \n\n\n    # read data ========== ========== ========== ========== ========== ==========\n\n    LOG = False\n    flog = open(log_path, 'w')\n\n    model = CapsuleNet(conv1_kernel,conv2_kernel)\n    if '' == pretrain_path:\n        pass\n    else:\n        model.load_state_dict(torch.load(pretrain_path)) # epoch.pt\n        print('>> note: load pre-trained model from:',pretrain_path)\n\n    if True == CUDA:\n        model.cuda()\n\n    print(\"# parameters:\", sum(param.numel() for param in model.parameters()))\n    flog.write(\"# parameters:\"+str(sum(param.numel() for param in model.parameters()))+'\\n')\n\n    optimizer = Adam(model.parameters(), lr = LR)\n    # optimizer = SGD(model.parameters(), lr = LR/10., momentum = 0.5)\n\n    engine = Engine()\n    meter_loss = tnt.meter.AverageValueMeter()\n    if 2 == param['dim']:        \n        meter_accuracy = tnt.meter.ClassErrorMeter(accuracy=True)\n        confusion_meter = tnt.meter.ConfusionMeter(NUM_CLASSES, normalized=True)\n    if 1 == param['dim']:\n        pass\n        # meter_mse = tnt.meter.MSEMeter()\n\n    if True == LOG:\n        train_loss_logger = VisdomPlotLogger('line', opts={'title': 'Train Loss'})\n        train_error_logger = VisdomPlotLogger('line', opts={'title': 'Train Accuracy'})\n        test_loss_logger = VisdomPlotLogger('line', opts={'title': 'Test Loss'})\n        test_accuracy_logger = VisdomPlotLogger('line', opts={'title': 'Test Accuracy'})\n        confusion_logger = VisdomLogger('heatmap', opts={'title': 'Confusion matrix',\n                                                     'columnnames': list(range(NUM_CLASSES)),\n                                                     'rownames': list(range(NUM_CLASSES))})\n        if 2 == param['dim']:\n            ground_truth_logger = VisdomLogger('image', opts={'title': 'Ground Truth'})\n            reconstruction_logger = VisdomLogger('image', opts={'title': 'Reconstruction'})\n\n    capsule_loss = CapsuleLoss()\n\n    def get_iterator(mode):\n        dataset = MNIST(root='./data', download=True, train=mode)\n        data = getattr(dataset, 'train_data' if mode else 'test_data')[:47]\n        # [torch.ByteTensor of size number x 28 x 28]\n        labels = getattr(dataset, 'train_labels' if mode else 'test_labels')[:47]\n        # [torch.LongTensor of size number]\n        tensor_dataset = tnt.dataset.TensorDataset([data, labels])\n\n        return tensor_dataset.parallel(batch_size=BATCH_SIZE, num_workers=4, shuffle=mode)\n\n    if False == CNN_EMB:\n        data_train = torch.FloatTensor(RTtrain.X)\n        label_train = torch.FloatTensor(RTtrain.y)\n        print('>> note: delete RTtrain.')\n        del RTtrain\n        gc.collect()\n        print('>> sleeping...')\n        for i in range(5):\n            print('~.~')\n        print('>> wake up!')  \n    if True == CNN_EMB:\n        data_train = corpus.train\n        label_train = corpus.train_label\n     \n    def get_rt_iterator(mode):\n        if mode:\n            data = data_train # Note: here must be FloatTensor not ByteTensor!            \n            labels = label_train\n        else:\n            if False == CNN_EMB:\n                data = torch.FloatTensor(RTtest.X)\n                labels = torch.FloatTensor(RTtest.y)\n            if True == CNN_EMB:\n                data = corpus.test\n                labels = corpus.test_label\n            # print('>>dim: test data:', data.shape, labels.shape)\n        tensor_dataset = tnt.dataset.TensorDataset([data, labels])\n        return tensor_dataset.parallel(batch_size=BATCH_SIZE, num_workers=1, shuffle=mode) # 1 for heatmap\n\n    def processor(sample):\n        data, labels, training = sample\n        # print('>>dim: data, labels, training', data.shape, labels.shape, training)\n        # torch.Size([batch, 28, 28]) torch.Size([batch]) True\n\n        if 'mnist' == param['data']:\n            data = augmentation(data.unsqueeze(1).float() / 255.0)            \n        # print('>>dim: data augmentation', data.shape) # torch.Size([batch, 1, 28, 28])\n        # print('>>dim: labels', labels) # Note: labels is already LongTensor?\n        if 'rt' == param['data']:\n            if False == CNN_EMB:\n                data = data[:, None, :, :] # Note: add dimension\n            if True == CNN_EMB:\n                pass\n\n        if 2 == param['dim']:\n            # for classification, we use LongTensor\n            labels = torch.LongTensor(labels)\n            labels = torch.sparse.torch.eye(NUM_CLASSES).index_select(dim=0, index=labels) \n        if 1 == param['dim']:\n            # for regression, we use FloatTensor\n            labels = torch.FloatTensor(labels.numpy())\n            labels = labels.view(-1, 1) # from [batch] to [batch, 1]\n\n        if True == CUDA:\n            data = Variable(data).cuda()\n            labels = Variable(labels).cuda()\n        if False == CUDA:\n            data = Variable(data)\n            labels = Variable(labels)\n\n        if training:\n            classes, reconstructions = model(data, labels)\n        else:\n            classes, reconstructions = model(data)\n\n        loss = capsule_loss(data, labels, classes, reconstructions)\n\n        return loss, classes\n\n\n    def reset_meters():\n        meter_loss.reset()\n        if 2 == param['dim']:\n            meter_accuracy.reset()            \n            confusion_meter.reset()\n        if 1 == param['dim']:\n            pass\n            # meter_mse.reset()\n\n    def on_sample(state):\n        state['sample'].append(state['train'])\n\n\n    def on_forward(state):\n        '''\n        So it is just used for recording?\n        '''\n        if 1 == param['dim']:\n            # print('>>dim: state output', state['output'].data.view(-1)) \n            # torch.FloatTensor of size [batch x 10]\n            # print('>>dim: state sample', state['sample'][1]) \n            # torch.LongTensor of size [batch]\n            # (1): [batch, 1] (2): [batch], so we view (1) as [batch], but no view is fine     \n            pass       \n            # meter_mse.add(state['output'].data, torch.FloatTensor(state['sample'][1].numpy()))\n        if 2 == param['dim']:\n            meter_accuracy.add(state['output'].data, torch.LongTensor(state['sample'][1]))\n            confusion_meter.add(state['output'].data, torch.LongTensor(state['sample'][1]))\n        meter_loss.add(state['loss'].data[0])\n\n\n    def on_start_epoch(state):\n        reset_meters()\n        state['iterator'] = tqdm(state['iterator'])\n\n\n    def on_end_epoch(state):\n        if 2 == param['dim']:\n            print('[Epoch %d] Training Loss: %.4f (Accuracy: %.2f%%)' % (\n                state['epoch'], meter_loss.value()[0], meter_accuracy.value()[0]))\n            flog.write('[Epoch %d] Training Loss: %.4f (Accuracy: %.2f%%)\\n' % (\n                state['epoch'], meter_loss.value()[0], meter_accuracy.value()[0]))\n            if True == LOG:\n                train_loss_logger.log(state['epoch'], meter_loss.value()[0])\n                train_error_logger.log(state['epoch'], meter_accuracy.value()[0])\n        if 1 == param['dim']:\n            print('[Epoch %d] Training Loss: %.4f (MSE: %.4f)' % (\n                state['epoch'], meter_loss.value()[0], 7)) # meter_mse.value()\n            flog.write('[Epoch %d] Training Loss: %.4f (MSE: %.4f)\\n' % (\n                state['epoch'], meter_loss.value()[0], 7)) # meter_mse.value()\n\n        reset_meters()\n\n        # iterator\n        if 'mnist' == param['data']:\n            engine.test(processor, get_iterator(False))\n        if 'rt' == param['data']:\n            engine.test(processor, get_rt_iterator(False))\n\n        if True == LOG:\n            test_loss_logger.log(state['epoch'], meter_loss.value()[0])\n            if 2 == param['dim']:\n                test_accuracy_logger.log(state['epoch'], meter_accuracy.value()[0])\n                confusion_logger.log(confusion_meter.value())\n            if 1 == param['dim']:\n                test_accuracy_logger.log(state['epoch'], 7) # meter_mse.value()\n\n        if 2 == param['dim']:\n            print('[Epoch %d] Testing Loss: %.4f (Accuracy: %.2f%%)' % (\n                state['epoch'], meter_loss.value()[0], meter_accuracy.value()[0]))\n            flog.write('[Epoch %d] Testing Loss: %.4f (Accuracy: %.2f%%)\\n' % (\n                state['epoch'], meter_loss.value()[0], meter_accuracy.value()[0]))\n        if 1 == param['dim']:\n            print('[Epoch %d] Testing Loss: %.4f (MSE: %.4f)' % (\n                state['epoch'], meter_loss.value()[0], 7)) # meter_mse.value()\n            flog.write('[Epoch %d] Testing Loss: %.4f (MSE: %.4f)\\n' % (\n                state['epoch'], meter_loss.value()[0], 7)) # meter_mse.value()\n\n        if 10 <= state['epoch']: # for heatmap\n            torch.save(model.state_dict(), save_prefix+'/epoch_%d.pt' % state['epoch'])\n            print('>> model: saved.')        \n\n        # prediction:\n        # model.load_state_dict(torch.load(PATH))\n        # pred_data = Variable(torch.FloatTensor(RTtest.X)[:,None,:,:])        \n        PRED_BATCH = 16 # 1000 # 16 for heatmap\n\n        if PRED_BATCH > 0:\n            '''\n            solve memory problem using batch\n            '''\n            if False == CNN_EMB:\n                pred = np.array([])\n                # TODO: handle int\n                pred_batch_number = int(RTtest.X.shape[0] / PRED_BATCH)+1\n                for bi in range(pred_batch_number):\n                    test_batch = Variable(torch.FloatTensor(RTtest.X[bi*PRED_BATCH:(bi+1)*PRED_BATCH,:,:])[:,None,:,:])\n                    test_batch = test_batch.cuda() # Note: we don't use this block anymore\n                    pred_batch = model(test_batch)\n                    pred = np.append(pred, pred_batch[0].data.cpu().numpy().flatten())\n                # print('>>dim: pred', pred.shape)      \n\n                if True == DATA_AUGMENTATION:\n                    ''' data augmentation:'''\n                    pep_num = int(len(pred) / 2)\n                    pred = pred[:pep_num]*0.5 + pred[pep_num:]*0.5\n                    obse = RTtest.y[:pep_num]\n                    pearson = Pearson(pred,obse)\n                    spearman = Spearman(pred,obse)\n                else:\n                    pearson = Pearson(pred,RTtest.y)\n                    spearman = Spearman(pred,RTtest.y)        \n            if True == CNN_EMB:\n                pred = np.array([])\n                # TODO: handle int\n                pred_batch_number = int(corpus.test.shape[0] / PRED_BATCH)+1\n                for bi in range(pred_batch_number):\n                    test_batch = Variable(corpus.test[bi*PRED_BATCH:(bi+1)*PRED_BATCH,:])\n                    if True == CUDA:\n                        test_batch = test_batch.cuda()\n                        pred_batch = model(test_batch)\n                        pred = np.append(pred, pred_batch[0].data.cpu().numpy().flatten())\n                    if False == CUDA:\n                        # test_batch = test_batch.cuda()\n                        pred_batch = model(test_batch)\n                        pred = np.append(pred, pred_batch[0].data.numpy().flatten())\n                # print('>>dim: pred', pred.shape)     \n                obse = corpus.test_label.numpy().flatten() \n                pearson = Pearson(pred,obse)\n                spearman = Spearman(pred,obse) \n        \n        else:\n            pred_data = Variable(torch.FloatTensor(RTtest.X)[:,None,:,:]) \n            if True == CUDA:\n                pred_data = pred_data.cuda()\n            pred = model(pred_data)\n            if True == CUDA:\n                # print('>>dim: pred', pred[0].data.cpu().numpy().flatten().shape)\n                pearson = Pearson(pred[0].data.cpu().numpy().flatten(),RTtest.y)\n                spearman = Spearman(pred[0].data.cpu().numpy().flatten(),RTtest.y)\n            if False == CUDA:\n                pearson = Pearson(pred[0].data.numpy().flatten(),RTtest.y)\n                spearman = Spearman(pred[0].data.numpy().flatten(),RTtest.y)\n        ''''''\n        print('>> Corr on %d testing samples: %.5f | %.5f' % (len(pred), pearson, spearman))\n        flog.write('>> Corr on %d testing samples: %.5f | %.5f\\n' % (len(pred), pearson, spearman))\n        # writing:\n        if True == CNN_EMB:\n            obse = corpus.test_label.numpy().flatten()\n        if False == CNN_EMB:\n            obse = RTtest.y\n        with open(result_path, 'w') as fo:\n                fo.write('observed\\tpredicted\\n')\n                for i in range(len(pred)):\n                    fo.write('%.5f\\t%.5f\\n' % (obse[i],pred[i]))\n        # writing done\n\n        # Reconstruction visualization.\n        if 2 == param['dim']:\n\n            # iterator\n            if 'mnist' == param['data']:\n                test_sample = next(iter(get_iterator(False)))\n            if 'rt' == param['data']:\n                test_sample = next(iter(get_rt_iterator(False)))\n            # print('>>dim: test_sample', test_sample) # [batch, 28, 28]\n\n            ground_truth = (test_sample[0].unsqueeze(1).float() / 255.0)\n            # print('>>dim: ground_truth', ground_truth.shape) # torch.FloatTensor of size batch x 1 x 28 x 28\n\n            if True == CUDA:\n                pred, reconstructions = model(Variable(ground_truth).cuda())\n            if False == CUDA:\n                pred, reconstructions = model(Variable(ground_truth))\n            # print('>>dim: pred', pred)\n            reconstruction = reconstructions.cpu().view_as(ground_truth).data\n\n            if True == LOG:\n                ground_truth_logger.log(\n                    make_grid(ground_truth, nrow=int(BATCH_SIZE ** 0.5), normalize=True, range=(0, 1)).numpy())\n                reconstruction_logger.log(\n                    make_grid(reconstruction, nrow=int(BATCH_SIZE ** 0.5), normalize=True, range=(0, 1)).numpy())\n\n    # def on_start(state):\n    #     state['epoch'] = 327\n    #\n    # engine.hooks['on_start'] = on_start\n\n    engine.hooks['on_sample'] = on_sample\n    engine.hooks['on_forward'] = on_forward\n    engine.hooks['on_start_epoch'] = on_start_epoch\n    engine.hooks['on_end_epoch'] = on_end_epoch\n\n    if 'mnist' == param['data']:\n        engine.train(processor, get_iterator(True), maxepoch=NUM_EPOCHS, optimizer=optimizer)\n    if 'rt' == param['data']:\n        engine.train(processor, get_rt_iterator(True), maxepoch=NUM_EPOCHS, optimizer=optimizer)\n\n    T2 = timeit.default_timer()\n    print('>> time: %.5f min\\n' %((T2-T1)/60.))\n    flog.write('>> time: %.5f min\\n' %((T2-T1)/60.))\n    flog.close()\n", "meta": {"hexsha": "d8063fe1171024d9eee1b05d6b80a52ea8b891d2", "size": 31879, "ext": "py", "lang": "Python", "max_stars_repo_path": "capsule_network_emb_cpu.py", "max_stars_repo_name": "horsepurve/DeepRTplus", "max_stars_repo_head_hexsha": "b29041c71f84c1d1a56c5c5f20fd49a805ed4d46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2018-03-29T12:00:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T07:26:16.000Z", "max_issues_repo_path": "capsule_network_emb_cpu.py", "max_issues_repo_name": "Jun-NIBS/DeepRTplus", "max_issues_repo_head_hexsha": "213f5101000377e17ec470b9a2057b9edc92ceb2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2018-09-20T14:59:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T04:51:46.000Z", "max_forks_repo_path": "capsule_network_emb_cpu.py", "max_forks_repo_name": "Jun-NIBS/DeepRTplus", "max_forks_repo_head_hexsha": "213f5101000377e17ec470b9a2057b9edc92ceb2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2018-04-17T06:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T19:52:26.000Z", "avg_line_length": 42.562082777, "max_line_length": 180, "alphanum_fraction": 0.5385990778, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.19726667820255434}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n.. module: pyAPES\n    :synopsis: APES-model component\n.. moduleauthor:: Kersti Haahti\n\nModel framework for Atmosphere-Plant Exchange Simulations\n\nCreated on Tue Oct 02 09:04:05 2018\n\nNote:\n    migrated to python3\n    - print on same line\n    - dict.keys(), but these are iterated after in for-each-loop\n\nReferences:\nLauniainen, S., Katul, G.G., Lauren, A. and Kolari, P., 2015. Coupling boreal\nforest CO2, H2O and energy flows by a vertically structured forest canopy –\nSoil model with separate bryophyte layer. Ecological modelling, 312, pp.385-405.\n\nTo call model and run single simulation and read results: see example in sandbox.py\n    from tools.iotools import read_results\n    from pyAPES import driver\n    # for NetCDF-outputs\n    outputfile = driver(create_ncf=True, result_file='test.nc')\n    results = read_results(outputfile) # opens NetCDF-file using xarray\n\n    # for returning results directly\n    results = driver(create_ncf=False) # returns dict with integer keys\n    results = results[0] # first simulation\n\nLAST EDIT: 15.1.2020 Samuli Launiainen\n    * new forestfloor and altered outputs\nTodo:\n\n    - make minimal example of handling and plotting outputs using xarray -tools;\n      now see tools.iotools.read_forcing for documentation!\n\n\"\"\"\nimport time\nimport logging\n\nimport numpy as np\nfrom pandas import date_range\n\nfrom tools.iotools import initialize_netcdf,  write_ncf\nfrom canopy.canopy import CanopyModel\nfrom soil.soil import Soil\nfrom canopy.constants import WATER_DENSITY\n\ndef driver(parameters,\n           create_ncf=False,\n           result_file=None):\n    \"\"\"\n    Reads parameters as argument, prepares output files, runs model.\n    Args:\n        parameters (dict/list): either single parameter dictionary or list of parameters\n        create_ncf (bool): results saved to netCDF4 file\n        result_file (str): name of result file\n    \"\"\"\n\n    # --- CONFIGURATION PARAMETERS of LOGGING and NetCDF -outputs read\n    from parameters.outputs import output_variables, logging_configuration\n    from logging.config import dictConfig\n\n    # --- LOGGING ---\n    dictConfig(logging_configuration)\n    logger = logging.getLogger(__name__)\n\n    # --- CHECK PARAMETERS ---\n\n    if isinstance(parameters, dict):\n        Nsim = 1\n        parameters = [parameters]\n    elif isinstance(parameters, list):\n        Nsim = len(parameters)\n    else:\n        raise TypeError('Parameters should be either dict or list.')\n\n    logger.info('Simulation started. Number of simulations: {}'.format(Nsim))\n\n    # --- SIMULATIOS AND OUTPUTS ---\n\n    tasks = []\n\n    for k in range(Nsim):\n        tasks.append(\n            Model(\n                parameters[k]['general']['dt'],\n                parameters[k]['canopy'],\n                parameters[k]['soil'],\n                parameters[k]['forcing'],\n                output_variables['variables'],\n                nsim=k\n            )\n        )\n\n    if create_ncf: # outputs to NetCDF-file, returns filename\n        gpara = parameters[0]['general'] # same for all tasks\n        timestr = time.strftime('%Y%m%d%H%M')\n        if result_file:\n            filename = result_file\n        else:\n            filename = timestr + '_pyAPES_results.nc'\n\n        #freq = '{}S'.format(gpara['dt'])\n        #time_index = date_range(gpara['start_time'], gpara['end_time'], freq=freq, closed='left')\n\n        time_index = parameters[0]['forcing'].index\n\n        ncf, _ = initialize_netcdf(\n                output_variables['variables'],\n                Nsim,\n                tasks[k].Nsoil_nodes,\n                tasks[k].Ncanopy_nodes,\n                tasks[k].Nplant_types,\n                tasks[k].Nground_types,\n                time_index=time_index,\n                filepath=gpara['results_directory'],\n                filename=filename)\n\n        for task in tasks:\n            logger.info('Running simulation number (start time %s): %s' % (\n                        time.strftime('%Y-%m-%d %H:%M'), task.Nsim))\n            running_time = time.time()\n            results = task.run()\n            logger.info('Running time %.2f seconds' % (time.time() - running_time))\n            write_ncf(nsim=task.Nsim, results=results, ncf=ncf)\n\n            del results\n\n        output_file = gpara['results_directory'] + filename\n        logger.info('Ready! Results are in: ' + output_file)\n\n        ncf.close()\n\n        return output_file, tasks[0]\n\n    else: # returns dictionary of outputs\n        running_time = time.time()\n        results = {task.Nsim: task.run() for task in tasks}\n\n        logger.info('Running time %.2f seconds' % (time.time() - running_time))\n\n        return results, tasks[0] # this would return also 1st Model instance\n\n\nclass Model(object):\n    \"\"\"\n    pyAPES - main model class.\n    Combines submodels 'CanopyModel' and 'Soil' and handles data-transfer\n    between these model components and writing results.\n\n    Last edit: SL 13.01.2020\n    \"\"\"\n    def __init__(self,\n                 dt,\n                 canopy_para,\n                 soil_para,\n                 forcing,\n                 outputs,\n                 nsim=0):\n\n        logger = logging.getLogger(__name__)\n\n        self.dt = dt\n\n        self.Nsteps = len(forcing)\n        self.forcing = forcing\n        self.Nsim = nsim\n\n        self.Nsoil_nodes = len(soil_para['grid']['dz'])\n        self.Ncanopy_nodes = canopy_para['grid']['Nlayers']\n\n        # create soil model instance\n        self.soil = Soil(soil_para)\n\n        if 'Wa' in forcing and soil_para['water_model']['solve'] is False:\n            logger.info(\"Soil moisture from forcing file\")\n            soil_para['water_model']['initial_condition']['volumetric_water_content'] = (\n                forcing['Wa'].iloc[0])\n        if 'Tsa' in forcing and soil_para['heat_model']['solve'] is False:\n            logger.info(\"Soil temperature from forcing file\")\n            soil_para['heat_model']['initial_condition']['temperature'] = (\n                forcing['Tsa'].iloc[0])\n\n        # create canopy model instance\n        # initial delayed temperature and degreedaysum for pheno & LAI-models\n        if canopy_para['ctr']['pheno_cycle'] and 'X' in forcing:\n            for pt in list(canopy_para['planttypes'].keys()):\n                canopy_para['planttypes'][pt]['phenop'].update({'Xo': forcing['X'].iloc[0]})\n        if canopy_para['ctr']['seasonal_LAI'] and 'DDsum' in forcing:\n            for pt in list(canopy_para['planttypes'].keys()):\n                canopy_para['planttypes'][pt]['laip'].update({'DDsum0': forcing['DDsum'].iloc[0]})\n\n\n        self.canopy_model = CanopyModel(canopy_para, self.soil.grid['dz'])\n\n        self.Nplant_types = len(self.canopy_model.planttypes)\n        self.Nground_types = len(self.canopy_model.forestfloor.bottomlayer_types)\n\n        # initialize structure to save results\n        self.results = _initialize_results(outputs,\n                                       self.Nsteps,\n                                       self.Nsoil_nodes,\n                                       self.Ncanopy_nodes,\n                                       self.Nplant_types,\n                                       self.Nground_types)\n\n    def run(self):\n        \"\"\"\n        Loops through self.forcing and appends to self.results.\n\n        self.forcing variables and units; correspond to uppermost gridpoint:\n            precipitation [kg m-2 s-1]\n            air_pressure [Pa]\n            air_temperature [degC]\n            wind_speed [m/s]\n            friction_velocity [m/s]\n            h2o[mol/mol]\n            co2 [ppm]\n            zenith_angle [rad]\n            lw_in: Downwelling long wave radiation [W/m2]\n            diffPar: Diffuse PAR [W/m2]\n            dirPar: Direct PAR [W/m2]\n            diffNir: Diffuse NIR [W/m2]\n            dirNir: Direct NIR [W/m2]\n        \"\"\"\n\n        logger = logging.getLogger(__name__)\n        logger.info('Running simulation {}'.format(self.Nsim))\n        time0 = time.time()\n\n        #print('RUNNING')\n        k_steps=np.arange(0, self.Nsteps, int(self.Nsteps/10))\n\n        for k in range(0, self.Nsteps):\n            # --- print progress on screen\n            if k in k_steps[:-1]:\n                s = str(np.where(k_steps==k)[0][0]*10) + '%'\n                print('{0}..'.format(s), end=' ')\n\n            # --- CanopyModel ---\n            # run daily loop: updates LAI, phenology and moisture stress ---\n            if self.forcing['doy'].iloc[k] != self.forcing['doy'].iloc[k-1] or k == 0:\n                self.canopy_model.run_daily(\n                        self.forcing['doy'].iloc[k],\n                        self.forcing['Tdaily'].iloc[k])\n\n            # compile forcing dict for canopy model: soil_ refers to state of soil model\n            canopy_forcing = {\n                'wind_speed': self.forcing['U'].iloc[k],            # [m s-1]\n                'friction_velocity': self.forcing['Ustar'].iloc[k], # [m s-1]\n                'air_temperature': self.forcing['Tair'].iloc[k],    # [deg C]\n                'precipitation': self.forcing['Prec'].iloc[k],      # [kg m-2 s-1]\n                'h2o': self.forcing['H2O'].iloc[k],                 # [mol mol-1]\n                'co2': self.forcing['CO2'].iloc[k],                 # [ppm]\n                'PAR': {'direct': self.forcing['dirPar'].iloc[k],   # [W m-2]\n                        'diffuse': self.forcing['diffPar'].iloc[k]},\n                'NIR': {'direct': self.forcing['dirNir'].iloc[k],   # [W m-2]\n                        'diffuse': self.forcing['diffNir'].iloc[k]},\n                'lw_in': self.forcing['LWin'].iloc[k],              # [W m-2]\n                'air_pressure': self.forcing['P'].iloc[k],          # [Pa]\n                'zenith_angle': self.forcing['Zen'].iloc[k],        # [rad]\n\n                # from soil model\n                'soil_temperature': self.soil.heat.T[self.canopy_model.ix_roots],       # [deg C]\n                'soil_water_potential': self.soil.water.h[self.canopy_model.ix_roots],  # [m] ?\n                'soil_volumetric_water': self.soil.heat.Wliq[self.canopy_model.ix_roots], # [m3 m-3]\n                'soil_volumetric_air': self.soil.heat.Wair[self.canopy_model.ix_roots],   # [m3 m-3]\n                'soil_pond_storage': self.soil.water.h_pond * WATER_DENSITY,    # [kg m-2]\n            }\n\n            canopy_parameters = {\n                'soil_depth': self.soil.grid['z'][0],   # [m]\n                'soil_hydraulic_conductivity': self.soil.water.Kv[self.canopy_model.ix_roots], # [m s-1]\n                'soil_thermal_conductivity': self.soil.heat.thermal_conductivity[0],        # [W m-1 K-1]?\n                'date': self.forcing.index[k]   # pd.datetime\n            }\n\n            # call self.canopy_model.run to solve above-ground part\n            out_canopy, out_planttype, out_ffloor, out_groundtype = self.canopy_model.run(\n                dt=self.dt,\n                forcing=canopy_forcing,\n                parameters=canopy_parameters\n            )\n\n            # --- Soil model  ---\n            # compile forcing for Soil: potential infiltration and evaporation are at from ground surface\n            # water fluxes must be in [m s-1]\n            soil_forcing = {\n                'potential_infiltration': out_ffloor['throughfall'] / WATER_DENSITY,\n                'potential_evaporation': ((out_ffloor['soil_evaporation'] +\n                                          out_ffloor['capillary_rise']) / WATER_DENSITY),\n                'pond_recharge': out_ffloor['pond_recharge'] / WATER_DENSITY,\n                'atmospheric_pressure_head': -1.0E6,  # set to large value, because potential_evaporation already account for h_soil\n                'ground_heat_flux': -out_ffloor['ground_heat'],\n                'date': self.forcing.index[k]}\n\n\n            if 'Ws' in self.forcing and self.soil.solve_water is False:\n                soil_forcing.update({\n                    'state_water':{'volumetric_water_content': self.forcing['Ws'].iloc[k]}})\n            if 'Tsa' in self.forcing and self.soil.solve_heat is False:\n                soil_forcing.update({\n                    'state_heat':{'temperature': self.forcing['Tsa'].iloc[k]}})\n\n            # call self.soil to solve below-ground water and heat flow\n            soil_flux, soil_state = self.soil.run(\n                    dt=self.dt,\n                    forcing=soil_forcing,\n                    water_sink=out_canopy['root_sink'])\n\n            # --- append results and copy of forcing to self.results\n            forcing_output = {\n                    'wind_speed': self.forcing['U'].iloc[k],\n                    'friction_velocity': self.forcing['Ustar'].iloc[k],\n                    'air_temperature': self.forcing['Tair'].iloc[k],\n                    'precipitation': self.forcing['Prec'].iloc[k],\n                    'h2o': self.forcing['H2O'].iloc[k],\n                    'co2': self.forcing['CO2'].iloc[k],\n                    'pressure': self.forcing['P'].iloc[k],\n                    'par':  self.forcing['dirPar'].iloc[k] + self.forcing['diffPar'].iloc[k],\n                    'nir':  self.forcing['dirNir'].iloc[k] + self.forcing['diffNir'].iloc[k],\n                    'lw_in': self.forcing['LWin'].iloc[k]\n                    }\n\n\n            soil_state.update(soil_flux)\n\n            self.results = _append_results('forcing', k, forcing_output, self.results)\n            self.results = _append_results('canopy', k, out_canopy, self.results)\n            self.results = _append_results('ffloor', k, out_ffloor, self.results)\n            self.results = _append_results('soil', k, soil_state, self.results)\n            self.results = _append_results('pt', k, out_planttype, self.results)\n            self.results = _append_results('gt', k, out_groundtype, self.results)\n\n        print('100%')\n\n        ptnames = [pt.name for pt in self.canopy_model.planttypes]\n\n        self.results = _append_results('canopy', None, {'z': self.canopy_model.z,\n                                                        'planttypes': np.array(ptnames)}, self.results)\n\n        gtnames = [gt.name for gt in self.canopy_model.forestfloor.bottomlayer_types]\n\n        self.results = _append_results('ffloor', None, {'groundtypes': np.array(gtnames)}, self.results)\n\n        self.results = _append_results('soil', None, {'z': self.soil.grid['z']}, self.results)\n\n        logger.info('Finished simulation %.0f, running time %.2f seconds' % (self.Nsim, time.time() - time0))\n\n        return self.results\n\n\ndef _initialize_results(variables, Nstep, Nsoil_nodes, Ncanopy_nodes, Nplant_types, Nground_types):\n    \"\"\"\n    Creates temporary results dictionary to accumulate simulation results\n    SL 12.11.2019: removed if 'date' in dimensions and added option to save planttype profiles\n    \"\"\"\n\n    results = {}\n\n    for var in variables:\n\n        var_name = var[0]\n        dimensions = var[2]\n\n        if 'canopy' in dimensions:\n            if 'planttype' in dimensions:\n                var_shape = [Nstep, Nplant_types, Ncanopy_nodes]\n            else:\n                var_shape = [Nstep, Ncanopy_nodes]\n\n        elif 'soil' in dimensions:\n            var_shape = [Nstep, Nsoil_nodes]\n\n        elif 'planttype' in dimensions and 'canopy' not in dimensions:\n            var_shape = [Nstep, Nplant_types]\n\n        elif 'groundtype' in dimensions:\n            if 'date' not in dimensions:\n                var_shape = [Nground_types]\n            else:\n                var_shape = [Nstep, Nground_types]\n\n        else:\n            var_shape = [Nstep]\n\n        results[var_name] = np.full(var_shape, np.NAN)\n        # print(var_name, var_shape, dimensions)\n\n    return results\n\n\ndef _append_results(group, step, step_results, results):\n    \"\"\"\n    Adds results from each simulation steps to temporary results dictionary\n    \"\"\"\n\n    results_keys = results.keys()\n    step_results_keys = step_results.keys()\n\n    for key in step_results_keys:\n        variable = group + '_' + key\n        if variable in results_keys:\n            if key == 'z' or key == 'planttypes' or key == 'groundtypes':\n                results[variable] = step_results[key]\n            else:\n                #print(variable, key, np.shape(results[variable][step]), np.shape(step_results[key]))\n                results[variable][step] = step_results[key]\n\n    return results\n\n#if __name__ == '__main__':\n#\n#    from parameters.parametersets import lettosuo_parameters\n#    outputfile=driver(create_ncf=True, parametersets=lettosuo_parameters)\n#\n#    print(outputfile)\n", "meta": {"hexsha": "2f85e2431e795b8f9dfbbc1af603da4f24935e87", "size": 16459, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyAPES.py", "max_stars_repo_name": "LukeEcomod/pyAPES_VESBO", "max_stars_repo_head_hexsha": "fdb4f44907e3055eb42db4a1260e0d7b9c55b415", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-12-21T16:33:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T05:13:14.000Z", "max_issues_repo_path": "pyAPES.py", "max_issues_repo_name": "LukeEcomod/pyAPES_VESBO", "max_issues_repo_head_hexsha": "fdb4f44907e3055eb42db4a1260e0d7b9c55b415", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyAPES.py", "max_forks_repo_name": "LukeEcomod/pyAPES_VESBO", "max_forks_repo_head_hexsha": "fdb4f44907e3055eb42db4a1260e0d7b9c55b415", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0950118765, "max_line_length": 132, "alphanum_fraction": 0.5780424084, "include": true, "reason": "import numpy", "num_tokens": 3873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.19726667062774914}}
{"text": "#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n#The script builds an evolutionary history of clones by sharing mutations between samples.\r\n\r\nimport os\r\nimport re\r\nimport numpy \r\nimport random \r\nimport sys, getopt\r\nfrom Bio import Phylo\r\nfrom io import StringIO\r\nimport matplotlib\r\nmatplotlib.use('Agg')\r\nimport matplotlib.pyplot as plt\r\n\r\n#24 chromosome\r\nall_chr=[]\r\nfor i in range(1,24):\r\n\tall_chr.append(str(i))\r\nall_chr.append('X')\r\nall_chr.append('Y')\r\n\r\n\r\n#parameter\r\n\r\nopts,args = getopt.getopt(sys.argv[1:], \"i:o:\",[\"AF=\",\"input=\", \"output=\"])\r\ndef get_driver_gene_path():\r\n    '''\r\n    return the driver gene path\r\n    '''\r\n    current_path = os.path.dirname(os.path.realpath(__file__))\r\n    return current_path\r\n\r\n\r\nAF=''\r\nfile_path=''\r\nfile_path_out=''\r\nfor para,value in opts:\r\n\tif para in ('--AF'):\r\n\t\tAF=value\r\n\tif para in ('-i','--input'):\r\n\t\tfile_path=value\r\n\tif para in ('-o','--output'):\r\n\t\tfile_path_out=value\r\nprint('AF: '+str(AF))\r\nif file_path[-len(os.path.sep):]==os.path.sep:\r\n\tfile_path=file_path[:-len(os.path.sep)]\r\nprint('file_path: '+str(file_path))\r\nif file_path_out[-len(os.path.sep):]==os.path.sep:\r\n\tfile_path_out=file_path_out[:-len(os.path.sep)]\r\nprint('file_path_out: '+str(file_path_out))\r\n\r\ndef fact(n):\r\n    if n == 0:\r\n        return 1\r\n    else:\r\n        return n*fact(n-1)\r\ndef Cmn(n,m):\r\n    return fact(n)/(fact(n-m)*fact(m))\r\n\r\n#map driver gene:\r\n# @ a is a list including mutation which is used to map driver gene\r\n# @ b =='FALSE', then output driver gene without mutation\r\n# @ b =='TRUE', then output driver gene with mutation\r\ndef search_gene(a,b):\r\n\tglobal count_gene\r\n\tcount_gene=0\r\n\tglobal gene_list\r\n\tgene_list=[]\r\n\tfor item in a:#read a mutation\r\n\t\tif item in all_mutation.keys():\r\n\t\t\tfor gene in all_mutation[item]:\r\n\t\t\t\tif gene in driver_gene.keys():\r\n\t\t\t\t\tif b=='FALSE':#do not output driver gene with mutation\r\n\t\t\t\t\t\tgene=gene\r\n\t\t\t\t\tif b=='TRUE':\r\n\t\t\t\t\t\tgene=gene+':'+item\r\n\t\t\t\t\tif gene not in gene_list:\r\n\t\t\t\t\t\tgene_list.append(gene)\r\n\tcount_gene=len(gene_list)\r\n\tgene_list.append(count_gene)\r\n\treturn gene_list\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n#.................................................find best branch..........................\r\ndef xunhuan(a):\r\n\tnum=1\r\n\tglobal first_1\r\n\tfirst_1={}\r\n\tglobal first_3\r\n\tfirst_3={}\r\n\tglobal first_4\r\n\tfirst_4={}\r\n\tfirst_6={}\r\n\twhile num<=len(a)/2:\r\n\t\tstruct_pattern=str(num)+'-'+str(len(a)-num)\r\n\t\tDIC={}#including structure info: Cmn information for a specific branch split\r\n\t\tcishu=int(Cmn(len(a),num))\r\n\t\twhile len(DIC.keys())<cishu:\r\n\t\t\tsel=random.sample(a,num)\r\n\t\t\tsel.sort()\r\n\t\t\tif num>1:\r\n\t\t\t\tda=','\r\n\t\t\t\tfor Item in sel:\r\n\t\t\t\t\tda=da+','+Item\r\n\t\t\t\tif da[2:] not in DIC.keys():\r\n\t\t\t\t\tDIC.update({da[2:]:[]})\r\n\t\t\tif num==1:\r\n\t\t\t\tDIC.update({sel[0]:[]})\r\n\t\tfirst_2={}#struct info\r\n\t\tfor item in DIC.keys():\r\n\t\t\ta_1=[]#first =a, then remove item from [a]. \r\n\t\t\tjiaoji_2=[]\r\n\t\t\tjiaoji_1=[]\r\n\t\t\tfor sample in a:\r\n\t\t\t\ta_1.append(sample)\r\n\t\t\tsplit=item.split(',')\r\n\t\t\tsplit.sort()\r\n\t\t\tfor item5 in split:\r\n\t\t\t\ta_1.remove(item5)\r\n\t\t\tif len(split)==1:\r\n\t\t\t\tjiaoji_1=dic[item]#sample mutation which is removed\r\n\t\t\telse:\r\n\t\t\t\tNUM=0\r\n\t\t\t\tfor item6 in split:\r\n\t\t\t\t\tNUM=NUM+1\r\n\t\t\t\t\tif NUM==1:\r\n\t\t\t\t\t\tjiaoji_1=dic[item6]\r\n\t\t\t\t\tjiaoji_1=[val for val in jiaoji_1 if val in dic[item6]]#sample mutation which are removed\r\n\r\n\t\t\ti=0\r\n\t\t\tno_item=','\r\n\t\t\ta_1.sort()\r\n\t\t\tfor item1 in a_1:\r\n\t\t\t\tno_item=no_item+','+item1\r\n\t\t\t\ti=i+1\r\n\t\t\t\tif i==1:\r\n\t\t\t\t\tjiaoji_2=dic[item1]\r\n\t\t\t\tjiaoji_2 = [val for val in jiaoji_2 if val in dic[item1]]#sample mutation which are retained; also is big group\r\n\r\n\t\t\tstruct_name=no_item[2:]\r\n\t\t\tstruct_share_mut=len(jiaoji_2)\r\n\t\t\tnum_1=str(len(jiaoji_1))+str(search_gene(jiaoji_1,'FALSE'))\r\n\t\t\tfirst_3.update({item:num_1})\r\n\t\t\tfirst_4.update({item:jiaoji_1})\r\n\t\t\tnum_2=str(len(jiaoji_2))+str(search_gene(jiaoji_2,'FALSE'))\r\n\t\t\tfirst_3.update({struct_name:num_2})\r\n\t\t\tfirst_4.update({struct_name:jiaoji_2})\r\n\t\t\t#if struct: n/2,n/2: we should retained group info which mutation is small\r\n\t\t\tif num==len(a)/2:\r\n\t\t\t\tif len(jiaoji_1)>len(jiaoji_2):\r\n\t\t\t\t\tstruct_name=no_item[2:]\r\n\t\t\t\t\tstruct_share_mut=len(jiaoji_2)\r\n\t\t\t\tif len(jiaoji_1)<len(jiaoji_2):\r\n\t\t\t\t\tstruct_name=item\r\n\t\t\t\t\tstruct_share_mut=len(jiaoji_1)\r\n\t\t\t\tif len(jiaoji_1)==len(jiaoji_2):\r\n\t\t\t\t\tstruct_name=item\r\n\t\t\t\t\tstruct_share_mut=len(jiaoji_1)\r\n\t\t\tfirst_2.update({struct_name:struct_share_mut})\r\n\t\tsort_d=sorted(first_2.items(),key = lambda d:d[1],reverse=True) \r\n\t\tcount=0\r\n\t\t#print('max value and second value:')\r\n\t\tmax_data=[]\r\n\t\tif num!=len(a)/2:\r\n\t\t\tfor key,value in sort_d:\r\n\t\t\t\tcount+=1\r\n\t\t\t\tif count==1:\r\n\t\t\t\t\tmax_data_name=key\r\n\t\t\t\t\tmax_data_value=value\r\n\t\t\t\t\tstruct_pattern1=struct_pattern+':'+key\r\n\t\t\t\t\tfirst_6.update({struct_pattern1:value})\r\n\t\t\t\tif count<=2:\r\n\t\t\t\t\tmax_data.append(value)\r\n\t\t\t\t\t#print(key,value)\r\n\t\t\t\tif count>1 and key!=max_data_name and value==max_data_value:\r\n\t\t\t\t\tstruct_pattern1=struct_pattern+':'+key\r\n\t\t\t\t\tif struct_pattern1 not in first_6.keys():\r\n\t\t\t\t\t\tfirst_6.update({struct_pattern1:value})\r\n\t\telse:\r\n\t\t\tfor key,value in sort_d:\r\n\t\t\t\tcount+=1\r\n\t\t\t\tif count==1:\r\n\t\t\t\t\tmax_data_name=key\r\n\t\t\t\t\tmax_data_value=value\r\n\t\t\t\t\tmax_data.append(value)\r\n\t\t\t\t\tstruct_pattern1=struct_pattern+':'+max_data_name\r\n\t\t\t\t\tif struct_pattern1 not in first_6.keys():\r\n\t\t\t\t\t\tfirst_6.update({struct_pattern1:max_data_value})\r\n\t\t\t\t\t#print(key,value)\r\n\t\t\t\t\tchongfu={}#judge random chongfu \r\n\t\t\t\t\twhile len(chongfu.keys())<(fact(len(key.split(',')))-1):\r\n\t\t\t\t\t\tlist1=key.split(',')\r\n\t\t\t\t\t\trandom.shuffle(list1)\r\n\t\t\t\t\t\t#print(list1)\r\n\t\t\t\t\t\tfan_da=','\r\n\t\t\t\t\t\tfor Item1 in list1:\r\n\t\t\t\t\t\t\tfan_da=fan_da+','+Item1\r\n\t\t\t\t\t\tif fan_da[2:]!=key:\r\n\t\t\t\t\t\t\tchongfu.update({fan_da[2:]:[]})\r\n\t\t\t\tif key != max_data_name and key not in chongfu.keys() and len(max_data)==1:\r\n\t\t\t\t\tmax_data.append(value)\r\n\t\t\t\t\t#print(key,value)\r\n\t\t\t\tif count>1 and key not in chongfu.keys() and key!=max_data_name and value==max_data_value:\r\n\t\t\t\t\tchongfu2={}\r\n\t\t\t\t\twhile len(chongfu2.keys())<(fact(len(key.split(',')))-1):\r\n\t\t\t\t\t\tlist1=key.split(',')\r\n\t\t\t\t\t\trandom.shuffle(list1)\r\n\t\t\t\t\t\tfan_da=','\r\n\t\t\t\t\t\tfor Item1 in list1:\r\n\t\t\t\t\t\t\tfan_da=fan_da+','+Item1\r\n\t\t\t\t\t\tif fan_da[2:]!=key:\r\n\t\t\t\t\t\t\tchongfu2.update({fan_da[2:]:[]})\r\n\t\t\t\t\tchongfu_count=0\r\n\t\t\t\t\tfor item_name in chongfu2.keys():\r\n\t\t\t\t\t\tstruct_pattern1=struct_pattern+':'+item_name\r\n\t\t\t\t\t\tif struct_pattern not in first_6.keys():\r\n\t\t\t\t\t\t\tchongfu_count=chongfu_count+1\r\n\t\t\t\t\tif chongfu_count==len(chongfu.keys()):\r\n\t\t\t\t\t\tstruct_pattern1=struct_pattern+':'+key\r\n\t\t\t\t\t\tif struct_pattern1 not in first_6.keys():\r\n\t\t\t\t\t\t\tfirst_6.update({struct_pattern1:value})\r\n\t\tif int(max_data[1])!=0:\r\n\t\t\tratio=int(max_data[0])/int(max_data[1])\r\n\t\telse:\r\n\t\t\tratio=int(max_data[0])\r\n\t\tstruct_pattern2=struct_pattern+':'+max_data_name\r\n\t\tfirst_1.update({struct_pattern2:ratio})\r\n\t\tnum=num+1\r\n\tsort_data=sorted(first_1.items(),key = lambda d:d[1],reverse=True) \r\n\t#print(sort_data)\r\n\tglobal return_data\r\n\treturn_data=[]\r\n\tcount_data=0\r\n\tfor key,value in sort_data:\r\n\t\tcount_data=count_data+1\r\n\t\tif count_data==1:\r\n\t\t\tmax_data_name=key\r\n\t\t\tmax_data_value=value\r\n\t\tif value==max_data_value:\r\n\t\t\treturn_data.append(key)\r\n\tfor item in return_data:\r\n\t\tidentify=item.split(':')[0]\r\n\t\tfor item1 in first_6.keys():\r\n\t\t\tif identify in item1 :\r\n\t\t\t\tif item1 not in return_data:\r\n\t\t\t\t\treturn_data.append(item1)\r\n\tif max_data_value==0:#ratio==0\r\n\t\tvalue1=[]\r\n\t\treturn_data=[]\r\n\t\tnum=divmod(len(a),2)[0]\r\n\t\twhile num>0:\r\n\t\t\tfor key in first_4.keys():\r\n\t\t\t\tif len(key.split(','))==num and len(first_4[key])!=0:\r\n\t\t\t\t\tvalue1.append(len(first_4[key]))\r\n\t\t\tif len(value1)!=0:\r\n\t\t\t\tbreak\r\n\t\t\telse:\r\n\t\t\t\tnum=num-1\r\n\t\tmax_data=value1[0]\r\n\t\tstruct_pattern=str(num)+'-'+str(len(a)-num)\r\n\t\tfor data in value1[1:]:\r\n\t\t\tif int(data)>max_data:\r\n\t\t\t\tmax_data=int(data)\r\n\t\tfor key in first_4.keys():\r\n\t\t\tif len(key.split(','))==num and len(first_4[key])==max_data:\r\n\t\t\t\tstruct_pattern1=struct_pattern+':'+key\r\n\t\t\t\treturn_data.append(struct_pattern1)\r\n\treturn_data.sort()\r\n\treturn(return_data)\r\n#split tree\r\ndef split_tree(tree_label_split):\r\n\tnew_tree_label=[]\r\n\tnum=0\r\n\tcount1=0\r\n\tcount2=0\r\n\tindex1=[]\r\n\tnew_tree_label=[]\r\n\twhile num <len(tree_label_split):\r\n\t\tif tree_label_split[num]=='(':\r\n\t\t\tcount1=count1+1\r\n\t\tif tree_label_split[num]==')':\r\n\t\t\tcount2=count2+1\r\n\t\tif count1==count2:\r\n\t\t\tif tree_label_split[num]==']':\r\n\t\t\t\tindex1.append(num+1)\r\n\t\t\t\tcount1=0\r\n\t\t\t\tcount2=0\r\n\t\tnum=num+1\r\n\tindex_1=0\r\n\tfor item in index1:\r\n\t\tnew_tree_label.append(tree_label_split[index_1:item])\r\n\t\tindex_1=item+1\r\n\t#print(new_tree_label)\r\n\treturn(new_tree_label)\t\r\n\t\r\n#...........................................299 driver gene........................\r\ndriver_gene_path=get_driver_gene_path()\r\nprint('driver_gene_path: '+driver_gene_path)\r\nif driver_gene_path!='.':\r\n\tfile=open(driver_gene_path+os.path.sep+'299_driverMutationList_Cell_2018.txt','r')\r\n\tglobal driver_gene\r\n\tdriver_gene={}\r\n\tlines=file.readlines()\r\n\tfor line in lines[1:]:\r\n\t\tdriver_gene.update({line.rstrip():[]})  #uniq driver gene\r\nelse:\r\n\tprint('can not read driver gene file')\r\n\r\n#...................................................read file...and mutation................................\r\n\r\nfilelist=os.listdir(file_path)\r\nprint(filelist)\r\n#find all patient\r\nall_patient_ID=[]\r\nfor filename in filelist:\r\n\tpatient_ID=filename.split('.')[0].split('_')[0]\r\n\tif patient_ID not in all_patient_ID:\r\n\t\tall_patient_ID.append(patient_ID)\r\nglobal all_mutation\r\nfor patient in all_patient_ID:\r\n\tif AF !='':#one sample per file\r\n\t\tprint('one sample per file')\r\n\t\tall_mutation={}\r\n\t\tprint('patient: '+patient)\r\n\t\tdic={}#[sample_id: all mutation_ID]\r\n\t\tall_data=[]#all_sample_ID\r\n\t\tsample_shu=0#the number of all samples of this patient\r\n\t\tfor filename in filelist:\r\n\t\t\tif filename.split('.')[0].split('_')[0]==patient:\r\n\t\t\t\tsample_shu=sample_shu+1\r\n\t\t\t\tsample_id=filename.split('.')[0].split('_')[1]\r\n\t\t\t\tif sample_id not in all_data:\r\n\t\t\t\t\tall_data.append(sample_id)\r\n\t\t\t\telse:\r\n\t\t\t\t\tprint('sample_id is not uniq!')\r\n\t\t\t\tif sample_id not in dic.keys():\r\n\t\t\t\t\tdic.update({sample_id:[]})\r\n\t\t\t\telse:\r\n\t\t\t\t\tprint('sample_ID is not uniq!')\r\n\t\t\t\tfile=open(file_path+os.path.sep+filename,'r')\r\n\t\t\t\tlines=file.readlines()\r\n\t\t\t\tfor line in lines[1:]:\r\n\t\t\t\t\tdata=line.rstrip().split('\\t')\r\n\t\t\t\t\tif int(data[1])+int(data[2])!=0:\r\n\t\t\t\t\t\tAF_data=int(data[1])/(int(data[1])+int(data[2]))\r\n\t\t\t\t\t\tif AF_data>=float(AF) and data[0].split('_')[0] in all_chr:\r\n\t\t\t\t\t\t\tif data[0] not in dic[sample_id] :\r\n\t\t\t\t\t\t\t\tdic[sample_id].append(data[0])\r\n\t\t\t\t\t\t\t\tif data[0] not in all_mutation.keys():\r\n\t\t\t\t\t\t\t\t\tall_mutation.update({data[0]:[]})\r\n\t\t\t\t\t\t\t\tfor refer_gene in data[3].split(';'):\r\n\t\t\t\t\t\t\t\t\tif refer_gene not in all_mutation[data[0]]:\r\n\t\t\t\t\t\t\t\t\t\tall_mutation[data[0]].append(refer_gene)\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\tprint(filename+' contains two or more identical mutation!')\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tprint(data[0]+': this sample have mutations that are uncovered!')\r\n\telse:\r\n\t\t# 0-1 matrix\r\n\t\tprint('0-1 matrix')\r\n\t\tall_mutation={}\r\n\t\tprint('patient: '+patient)\r\n\t\tdic={}#[sample_id: all mutation_ID]\r\n\t\tall_data=[]#all_sample_ID\r\n\t\tsample_shu=0#the number of all samples of this patient\r\n\t\tsample_index={}#[index:smaple_name]\r\n\t\tfile=open(file_path+os.path.sep+patient+'.txt','r')\r\n\t\tlines=file.readlines()\r\n\t\tdata_0=lines[0].rstrip().split('\\t')\r\n\t\tfor item in data_0[1:-1]:#sample_id\r\n\t\t\tsample_shu=sample_shu+1\r\n\t\t\tif item not in dic.keys() :\r\n\t\t\t\tdic.update({item:[]})\r\n\t\t\t\tall_data.append(item)\r\n\t\t\t\tsample_index.update({sample_shu:item})\r\n\t\t\telse:\r\n\t\t\t\tprint('sample_id is not uniq!')\r\n\t\t#print(sample_index)\r\n\t\t#print(dic)\r\n\t\tfor line in lines[1:]:\r\n\t\t\tdata=line.rstrip().split('\\t')\r\n\t\t\tfor i in range(1,len(data)-1):\r\n\t\t\t\tif int(data[i])==1 and data[0] not in dic[sample_index[i]]:\r\n\t\t\t\t\tdic[sample_index[i]].append(data[0])\r\n\t\t\tif data[0] not in all_mutation.keys():\r\n\t\t\t\tall_mutation.update({data[0]:[]})\r\n\t\t\t\tfor refer_gene in data[-1].split(';'):\r\n\t\t\t\t\tif refer_gene not in all_mutation[data[0]]:\r\n\t\t\t\t\t\tall_mutation[data[0]].append(refer_gene)\r\n\r\n\t#calculate the length of root trunk\r\n\t#remove the sample which have 0 muatation\r\n\tprint(all_data)\r\n\tfor item in dic.keys():\r\n\t\tif len(dic[item])==0:\r\n\t\t\tsample_shu=sample_shu-1\r\n\t\t\tprint(item+' have '+str(len(dic[item]))+' mutation,so remove this sample')\r\n\t\telse:\r\n\t\t\tprint(item+' have mutations: '+str(len(dic[item])))\r\n\tfor key in list(dic.keys()):\r\n\t\tif not dic.get(key):\r\n\t\t\tdel dic[key]\r\n\t\t\tall_data.remove(key)\r\n\tif len(all_data)>=3:\r\n\t\tall_driver_mutation={}\r\n\t\tfor item in dic.keys():\r\n\t\t\tif len(search_gene(dic[item],'FALSE'))>1:\r\n\t\t\t\tfor info in search_gene(dic[item],'TRUE')[:-1]:#remove count_map_driver_gene\r\n\t\t\t\t\tsplit=info.split(':')\r\n\t\t\t\t\tif split[0] not in all_driver_mutation.keys():\r\n\t\t\t\t\t\tall_driver_mutation.update({split[0]:[split[1]]})\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tif split[1] not in all_driver_mutation[split[0]]:\r\n\t\t\t\t\t\t\tall_driver_mutation[split[0]].append(split[1])\r\n\t\tun_uniq_gene=0\r\n\t\tfor key in all_driver_mutation.keys():\r\n\t\t\tif len(all_driver_mutation[key])>1:\r\n\t\t\t\tprint(key+' have '+str(len(all_driver_mutation[key]))+' uniq mutations: '+str(all_driver_mutation[key]))\r\n\t\t\telse:\r\n\t\t\t\tun_uniq_gene=un_uniq_gene+1\r\n\t\tif un_uniq_gene==len(all_driver_mutation.keys()):\r\n\t\t\tprint('every gene refer to a uniq gene')\r\n\t\t#........................................................................\r\n\t\ti=0\r\n\t\tfor item in dic.keys():\r\n\t\t\ti=i+1\r\n\t\t\tif i==1:\r\n\t\t\t\tall_jiaoji=dic[item]\r\n\t\t\tall_jiaoji = [val for val in all_jiaoji if val in dic[item]]\r\n\t\troot_node=str(len(all_jiaoji))+'['+str(search_gene(all_jiaoji,'False')[-1])+'-'\r\n\t\tfor item in search_gene(all_jiaoji,'False')[:-1]:\r\n\t\t\troot_node=root_node+item+';'\r\n\t\troot_node=root_node[:-1]+']'\r\n\t\tfor item in dic.keys():\r\n\t\t\tfor item1 in all_jiaoji:\r\n\t\t\t\tdic[item].remove(item1)\r\n\r\n\t\t#...............................................body......................\r\n\t\tdic_baocun={}\r\n\t\tfor item in all_data:\r\n\t\t\tdic_baocun.update({item:[]})\r\n\t\tfor item in dic_baocun.keys():\r\n\t\t\tfor item_data in dic[item]:\r\n\t\t\t\tdic_baocun[item].append(item_data)\r\n\t\tglobal all_DATA\r\n\t\tall_result_1=[]\r\n\t\tglobal branch_path\r\n\t\tbranch_path=[]\r\n\t\tglobal path_string\r\n\t\tpath_string=[]\r\n\t\tglobal final_path_count\r\n\t\tfinal_path_count=-1\r\n\t\tglobal DIC_result\r\n\t\tDIC_result={}\r\n\t\tDIC_count=0\r\n\t\tduli_count=0\r\n\t\tduli_state='false'\r\n\t\tchongfu_bianli=0\r\n\t\twhile final_path_count!=len(branch_path) or len(path_string)!=len(branch_path):\r\n\t\t\tchongfu_bianli=chongfu_bianli+1\r\n\t\t\tdic={}\r\n\t\t\tfor item in all_data:\r\n\t\t\t\tdic.update({item:[]})\r\n\t\t\tfor item in dic.keys():\r\n\t\t\t\tfor item_data in dic_baocun[item]:\r\n\t\t\t\t\tdic[item].append(item_data)\r\n\t\t\tall_DATA=[]\r\n\t\t\tall_DATA.append(all_data)\r\n\t\t\tresult_1=[]\r\n\t\t\tpath=','\r\n\t\t\tdic_result={}\r\n\t\t\tfor all_item in all_DATA:\r\n\t\t\t\tdic1={}\r\n\t\t\t\tfor item in all_item:\r\n\t\t\t\t\tdic1.update({item:[]})\r\n\t\t\t\tfor item in dic1.keys():\r\n\t\t\t\t\tfor item_data in dic[item]:\r\n\t\t\t\t\t\tdic1[item].append(item_data)\r\n\t\t\t\t#check if there are any-two sample that do not share any mutation?\r\n\t\t\t\twhile len(all_item)>=2:\r\n\t\t\t\t\tsample_2={}\r\n\t\t\t\t\tcount2=0\r\n\t\t\t\t\tcishu2=int(Cmn(len(all_item),2))\r\n\t\t\t\t\twhile len(sample_2.keys())<cishu2:\r\n\t\t\t\t\t\tsel2=random.sample(all_item,2)\r\n\t\t\t\t\t\toriginal_data=sel2[0]+','+sel2[1]\r\n\t\t\t\t\t\tfan_original_data=sel2[1]+','+sel2[0]\r\n\t\t\t\t\t\tif fan_original_data not in sample_2.keys():\r\n\t\t\t\t\t\t\tsample_2.update({original_data:[]})\r\n\t\t\t\t\tfor item_2 in sample_2.keys():\r\n\t\t\t\t\t\titem_2_split=item_2.split(',')\r\n\t\t\t\t\t\tsample_2_jiaoji=[val for val in dic1[item_2_split[0]] if val in dic1[item_2_split[1]]]\r\n\t\t\t\t\t\tif len(sample_2_jiaoji)!=0:\r\n\t\t\t\t\t\t\tcount2=count2+1\r\n\t\t\t\t\tif count2>0:\r\n\t\t\t\t\t\tduli_count=duli_count+1\t\r\n\t\t\t\t\t\tresult_all=xunhuan(all_item)\r\n\t\t\t\t\t\tpath_state='false'\r\n\t\t\t\t\t\tfor result_path in result_all:\r\n\t\t\t\t\t\t\tsame_path_count=0\r\n\t\t\t\t\t\t\tidentify1=result_path.split(':')[0]\r\n\t\t\t\t\t\t\tfor result_path_1 in result_all:\r\n\t\t\t\t\t\t\t\tif identify1 == result_path_1.split(':')[0]:\r\n\t\t\t\t\t\t\t\t\tsame_path_count=same_path_count+1\r\n\t\t\t\t\t\t\tif same_path_count>=2:\r\n\t\t\t\t\t\t\t\tpath_state='true'\r\n\t\t\t\t\t\tbranch_path_iter=[]\r\n\t\t\t\t\t\tfor path_item in branch_path:\r\n\t\t\t\t\t\t\tif path_item not in branch_path_iter:\r\n\t\t\t\t\t\t\t\tbranch_path_iter.append(path_item)\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\tprint('branch_path error')\r\n\t\t\t\t\t\t#print('path_state: '+path_state)\r\n\t\t\t\t\t\tfor result_all_1 in result_all:\r\n\t\t\t\t\t\t\tif path_state=='false':\r\n\t\t\t\t\t\t\t\tpath_merge=path+';'+result_all_1.split(':')[0]\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\tpath_merge=path+';'+result_all_1\r\n\t\t\t\t\t\t\t#print('path_merge: '+path_merge)\r\n\t\t\t\t\t\t\tif path_merge[0]==',' and chongfu_bianli==1:\r\n\t\t\t\t\t\t\t\tif path_merge[2:] not in branch_path:\r\n\t\t\t\t\t\t\t\t\tbranch_path.append(path_merge[2:])\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\tif path_merge[0]==',':\r\n\t\t\t\t\t\t\t\t\tpath_merge=path_merge[2:]\r\n\t\t\t\t\t\t\t\tpath_all=len(branch_path_iter)\r\n\t\t\t\t\t\t\t\tpath_count=0\r\n\t\t\t\t\t\t\t\twhile path_count<path_all:\r\n\t\t\t\t\t\t\t\t\tif len(branch_path_iter[path_count].split(';'))==len(path_merge.split(';'))-1 and branch_path_iter[path_count] ==path_merge[:len(branch_path_iter[path_count])] :\r\n\t\t\t\t\t\t\t\t\t\tif  branch_path_iter[path_count] == path_merge[:len(branch_path_iter[path_count])]:\r\n\t\t\t\t\t\t\t\t\t\t\tif branch_path_iter[path_count] in branch_path:\r\n\t\t\t\t\t\t\t\t\t\t\t\tbranch_path.remove(branch_path_iter[path_count])\r\n\t\t\t\t\t\t\t\t\t\tif path_merge not in branch_path:\r\n\t\t\t\t\t\t\t\t\t\t\tbranch_path.append(path_merge)\r\n\t\t\t\t\t\t\t\t\tpath_count=path_count+1\t\t\t\r\n\t\t\r\n\t\t\t\t\t\tfor result_all_1 in result_all:\r\n\t\t\t\t\t\t\tif path_state=='false':\r\n\t\t\t\t\t\t\t\tif path[0]==',':\r\n\t\t\t\t\t\t\t\t\t#print('ok1, in branch_path')\r\n\t\t\t\t\t\t\t\t\tpath_merge=path+';'+result_all_1.split(':')[0]\r\n\t\t\t\t\t\t\t\t\tpath_merge=path_merge[2:]\r\n\t\t\t\t\t\t\t\t\tpath_copy_state='FALSE'\r\n\t\t\t\t\t\t\t\t\tfor path_copy1 in branch_path:\r\n\t\t\t\t\t\t\t\t\t\tif path_copy1[-3:]!='end' and path_merge==path_copy1[:len(path_merge)] :\r\n\t\t\t\t\t\t\t\t\t\t\tpath=path_merge\r\n\t\t\t\t\t\t\t\t\t\t\tpath_copy_state='TRUE'\r\n\t\t\t\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\t\t\tif path_copy_state=='TRUE':\r\n\t\t\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\tpath_merge=path+';'+result_all_1.split(':')[0]\r\n\t\t\t\t\t\t\t\t\tpath_copy_state='FALSE'\r\n\t\t\t\t\t\t\t\t\tfor path_copy1 in branch_path:\r\n\t\t\t\t\t\t\t\t\t\tif path_copy1[-3:]!='end' and path_merge==path_copy1[:len(path_merge)] :\r\n\t\t\t\t\t\t\t\t\t\t\tpath=path_merge\r\n\t\t\t\t\t\t\t\t\t\t\tpath_copy_state='TRUE'\r\n\t\t\t\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\t\t\tif path_copy_state=='TRUE':\r\n\t\t\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\tif path[0]==',':\r\n\t\t\t\t\t\t\t\t\t#print('ok3, in branch_path')\r\n\t\t\t\t\t\t\t\t\tpath_merge=path+';'+result_all_1\r\n\t\t\t\t\t\t\t\t\tpath_merge=path_merge[2:]\r\n\t\t\t\t\t\t\t\t\tpath_copy_state='FALSE'\r\n\t\t\t\t\t\t\t\t\tfor path_copy1 in branch_path:\r\n\t\t\t\t\t\t\t\t\t\tif path_copy1[-3:]!='end' and path_merge==path_copy1[:len(path_merge)] :\r\n\t\t\t\t\t\t\t\t\t\t\tpath=path_merge\r\n\t\t\t\t\t\t\t\t\t\t\tpath_copy_state='TRUE'\r\n\t\t\t\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\t\t\tif path_copy_state=='TRUE':\r\n\t\t\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\tpath_merge=path+';'+result_all_1\r\n\t\t\t\t\t\t\t\t\tpath_copy_state='FALSE'\r\n\t\t\t\t\t\t\t\t\tfor path_copy1 in branch_path:\r\n\t\t\t\t\t\t\t\t\t\tif path_copy1[-3:]!='end' and path_merge==path_copy1[:len(path_merge)] :\r\n\t\t\t\t\t\t\t\t\t\t\tpath=path_merge\r\n\t\t\t\t\t\t\t\t\t\t\tpath_copy_state='TRUE'\r\n\t\t\t\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\t\t\tif path_copy_state=='TRUE':\r\n\t\t\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\tresult=result_all_1\r\n\t\t\t\t\t\tresult_split=result.split(':')\r\n\t\t\t\t\t\tresult_split=result_split[1].split(',')\r\n\t\t\t\t\t\tfirst='.'\r\n\t\t\t\t\t\t#print('max_pair:')\r\n\t\t\t\t\t\tfor item_split in result_split:\r\n\t\t\t\t\t\t\tfirst=first+','+item_split\r\n\t\t\t\t\t\tfirst=first[2:]\r\n\t\t\t\t\t\treturn_2=[]\r\n\t\t\t\t\t\tfor item_split in all_item:\r\n\t\t\t\t\t\t\tif item_split not in result_split:\r\n\t\t\t\t\t\t\t\treturn_2.append(item_split)\r\n\t\t\t\t\t\treturn_2.sort()\r\n\t\t\t\t\t\t#print(return_2)\r\n\t\t\t\t\t\treturn_2_zuhe=[]\r\n\t\t\t\t\t\twhile len(return_2_zuhe) <fact(len(return_2)):\r\n\t\t\t\t\t\t\tsel=random.sample(return_2,len(return_2))\r\n\t\t\t\t\t\t\tda=','\r\n\t\t\t\t\t\t\tfor Item in sel:\r\n\t\t\t\t\t\t\t\tda=da+','+Item\r\n\t\t\t\t\t\t\tif da[2:] not in return_2_zuhe:\r\n\t\t\t\t\t\t\t\treturn_2_zuhe.append(da[2:])\r\n\t\t\t\t\t\t#print(return_2_zuhe)\r\n\t\t\t\t\t\tsecond='.'\r\n\t\t\t\t\t\tfor item3 in return_2_zuhe:\r\n\t\t\t\t\t\t\tif item3 in first_3.keys():\r\n\t\t\t\t\t\t\t\tsecond=item3\r\n\t\t\t\t\t\t\t\tbreak\r\n\r\n\t\t\t\t\t\tif int(first_3[first].split('[')[0])!=len(first_4[first]):\r\n\t\t\t\t\t\t\tprint('false')\r\n\t\t\t\t\t\tresult_item_1=first+':'+str(len(first_4[first]))+'['+str(search_gene(first_4[first],'False')[-1])+'-'\r\n\t\t\t\t\t\tfor item in search_gene(first_4[first],'False')[:-1]:\r\n\t\t\t\t\t\t\tresult_item_1=result_item_1+item+';'\r\n\t\t\t\t\t\tresult_item_1=result_item_1[:-1]+']'\r\n\t\t\t\t\t\tresult_1.append(result_item_1)\r\n\t\t\t\t\t\tdic_result.update({first:first_4[first]})\r\n\t\t\t\t\t\tresult_item_2=second+':'+str(len(first_4[second]))+'['+str(search_gene(first_4[second],'False')[-1])+'-'\r\n\t\t\t\t\t\tfor item in search_gene(first_4[second],'False')[:-1]:\r\n\t\t\t\t\t\t\tresult_item_2=result_item_2+item+';'\r\n\t\t\t\t\t\tresult_item_2=result_item_2[:-1]+']'\r\n\t\t\t\t\t\tresult_1.append(result_item_2)\r\n\t\t\t\t\t\tdic_result.update({second:first_4[second]})\r\n\t\t\t\t\t\tif int(result[0:1])<2:\r\n\t\t\t\t\t\t\tresult_split=result.split(':')\r\n\t\t\t\t\t\t\tresult_split_split=result_split[1].split(',')\r\n\t\t\t\t\t\t\tall_item=[]\r\n\t\t\t\t\t\t\tfor item in result_split_split:\r\n\t\t\t\t\t\t\t\tall_item.append(item)\r\n\t\t\t\t\t\t\tfor key in list(dic1.keys()):\r\n\t\t\t\t\t\t\t\tif key not in result_split_split:\r\n\t\t\t\t\t\t\t\t\tdel dic1[key]\r\n\t\t\t\t\t\t\t#filter key which value=null\r\n\t\t\t\t\t\t\tfor key in list(dic1.keys()):\r\n\t\t\t\t\t\t\t\tif not dic1.get(key):\r\n\t\t\t\t\t\t\t\t\tdel dic1[key]\r\n\t\t\t\t\t\t\t\t\tall_item.remove(key)\r\n\t\t\t\t\t\t\t#print(all_item)\r\n\t\t\t\t\t\t\ti=0\r\n\t\t\t\t\t\t\tfor item_1 in dic1.keys():\r\n\t\t\t\t\t\t\t\ti=i+1\r\n\t\t\t\t\t\t\t\tif i==1:\r\n\t\t\t\t\t\t\t\t\tjiaoji=dic1[item_1]\r\n\t\t\t\t\t\t\t\tjiaoji=[val for val in jiaoji if val in dic1[item_1]]\r\n\r\n\t\t\t\t\t\t\tfor item in dic1.keys():\r\n\t\t\t\t\t\t\t\tfor item1 in jiaoji:\r\n\t\t\t\t\t\t\t\t\tdic1[item].remove(item1)\r\n\r\n\t\t\t\t\t\t\tfor item in dic1.keys():\r\n\t\t\t\t\t\t\t\tfor item1 in jiaoji:\r\n\t\t\t\t\t\t\t\t\tdic[item].remove(item1)\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tgroup1=[]\r\n\t\t\t\t\t\t\tgroup2=[]\r\n\t\t\t\t\t\t\tresult_split=result.split(':')\r\n\t\t\t\t\t\t\tresult_split_split=result_split[1].split(',')\r\n\t\t\t\t\t\t\tfor item in result_split_split:\r\n\t\t\t\t\t\t\t\tgroup1.append(item)\r\n\t\t\t\t\t\t\tgroup1.sort()\r\n\t\t\t\t\t\t\ti=0\r\n\t\t\t\t\t\t\tfor item_1 in group1:\r\n\t\t\t\t\t\t\t\ti=i+1\r\n\t\t\t\t\t\t\t\tif i==1:\r\n\t\t\t\t\t\t\t\t\tjiaoji=dic[item_1]\r\n\t\t\t\t\t\t\t\tjiaoji=[val for val in jiaoji if val in dic[item_1]]\r\n\r\n\t\t\t\t\t\t\tfor item in group1:\r\n\t\t\t\t\t\t\t\tfor item1 in jiaoji:\r\n\t\t\t\t\t\t\t\t\tdic[item].remove(item1)\r\n\r\n\t\t\t\t\t\t\tfor item in all_item:\r\n\t\t\t\t\t\t\t\tif item not in result_split_split:\r\n\t\t\t\t\t\t\t\t\tgroup2.append(item)\r\n\t\t\t\t\t\t\tgroup2.sort()\r\n\t\t\t\t\t\t\ti=0\r\n\t\t\t\t\t\t\tfor item_1 in group2:\r\n\t\t\t\t\t\t\t\ti=i+1\r\n\t\t\t\t\t\t\t\tif i==1:\r\n\t\t\t\t\t\t\t\t\tjiaoji=dic[item_1]\r\n\t\t\t\t\t\t\t\tjiaoji=[val for val in jiaoji if val in dic[item_1]]\r\n\r\n\t\t\t\t\t\t\tfor item in group2:\r\n\t\t\t\t\t\t\t\tfor item1 in jiaoji:\r\n\t\t\t\t\t\t\t\t\tdic[item].remove(item1)\r\n\t\t\t\r\n\t\t\t\t\t\t\tall_DATA.append(group1)\r\n\t\t\t\t\t\t\tall_DATA.append(group2)\r\n\r\n\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tfor item in all_item:\r\n\t\t\t\t\t\t\tresult_item =item+':'+str(len(dic1[item]))+'['+str(search_gene(dic1[item],'False')[-1])+'-'\r\n\t\t\t\t\t\t\tfor item0 in search_gene(dic1[item],'False')[:-1]:\r\n\t\t\t\t\t\t\t\tresult_item=result_item+item0+';'\r\n\t\t\t\t\t\t\tresult_item=result_item[:-1]+']'\r\n\t\t\t\t\t\t\t#print(result_item)\r\n\t\t\t\t\t\t\tresult_1.append(result_item)\r\n\t\t\t\t\t\t\tdic_result.update({item:dic1[item]})\r\n\t\t\t\t\t\t\tif duli_count==0:\r\n\t\t\t\t\t\t\t\tresult_item=result_item+';end'\r\n\t\t\t\t\t\t\t\tbranch_path.append(result_item)\r\n\t\t\t\t\t\tif duli_count==0:\r\n\t\t\t\t\t\t\tall_result_1.append(result_1)\r\n\t\t\t\t\t\t\tduli_state='true'\r\n\t\t\t\t\t\t#print(sample_name)\r\n\t\t\t\t\t\tbreak\r\n\t\t\tif duli_count>0:\r\n\t\t\t\tpath=path+';end'\r\n\t\t\t\tif path==',;end':\r\n\t\t\t\t\tprint('error: '+path)\r\n\t\t\t\tfor path_2 in branch_path:\r\n\t\t\t\t\tif path[:-4]==path_2:\r\n\t\t\t\t\t\tbranch_path.remove(path_2)\r\n\t\t\t\tif path not in branch_path:\r\n\t\t\t\t\tbranch_path.append(path)\r\n\t\t\tfor i in branch_path:\r\n\t\t\t\tif branch_path.count(i)>1:\r\n\t\t\t\t\tprint('branch_path have chongfu item: '+i)\r\n\t\t\tfinal_path_count=0\r\n\t\t\tfor path_data in branch_path:\r\n\t\t\t\tif path_data.split(';')[-1]=='end' or path_data[0].isalpha():\r\n\t\t\t\t\tfinal_path_count=final_path_count+1\r\n\r\n\t\t\tif duli_state=='false':\r\n\t\t\t\tif path not in path_string and path[-3:]=='end':\r\n\t\t\t\t\tpath_string.append(path)\r\n\r\n\t\t\t\t\tDIC_result.update({DIC_count:dic_result})\r\n\t\t\t\t\tDIC_count=DIC_count+1\r\n\t\t\t\t\tall_result_1.append(result_1)\r\n\t\t\telse:\r\n\t\t\t\tfor path_1 in branch_path:\r\n\t\t\t\t\tif path_1 not in path_string and path_1[-3:]=='end':\r\n\t\t\t\t\t\tpath_string.append(path_1)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tprint('The tree structure that completely branches from the root node is wrong!')\r\n\t\t\t\tDIC_result.update({DIC_count:dic_result})\r\n\t\t\t\tDIC_count=DIC_count+1\r\n\t\tprint('branch_path count: '+str(len(branch_path)))\r\n\t\tprint('path_string: '+str(len(path_string)))\r\n\t\tprint('all_result: '+str(len(all_result_1)))\r\n\t\tprint('DIC_result: '+str(len(DIC_result.keys())))\r\n\t\tfor item in all_result_1:\r\n\t\t\titem_copy = item[:]\r\n\r\n\t\t\tfor data in item_copy:\r\n\t\t\t\tif int(data.split(':')[1].split('[')[0])==0 and len(data.split(':')[0].split(','))>1:\r\n\t\t\t\t\titem.remove(data)\r\n\t\tall_result_weight=[]\r\n\t\tfor item in all_result_1:\r\n\t\t\tweight=0\r\n\r\n\t\t\tfor data in item:\r\n\t\t\t\tlength=len(data.split(':')[0].split(','))\r\n\t\t\t\tdata=data.split(':')[1].split('[')[0]\r\n\t\t\t\tif length>=2:\r\n\t\t\t\t\tweight=weight+length*int(data)\r\n\t\t\tall_result_weight.append(weight)\r\n\r\n\t\ti=0\r\n\t\tmax_weight_data=0\r\n\t\twhile i <len(all_result_weight):\r\n\t\t\tif i==0:\r\n\t\t\t\tmax_weight_data=all_result_weight[i]\r\n\t\t\tif all_result_weight[i]>max_weight_data:\r\n\t\t\t\tmax_weight_data=all_result_weight[i]\r\n\t\t\ti=i+1\r\n\t\tresult_max_weight=[]\r\n\t\tif max_weight_data==0:\r\n\t\t\tDIC_result_max_weight={}\r\n\t\t\tfor item in all_result_1:\r\n\t\t\t\tresult_max_weight.append(item)\r\n\t\t\tDIC_result_max_weight.update({0:DIC_result[0]})\r\n\t\telse:\r\n\t\t\tDIC_result_max_weight={}\r\n\t\t\ti=0\r\n\t\t\ti1=0\r\n\t\t\twhile i <len(all_result_weight):\r\n\t\t\t\tif all_result_weight[i]==max_weight_data:\r\n\t\t\t\t\tall_result_1[i].sort()\r\n\t\t\t\t\tif all_result_1[i] not in result_max_weight:\r\n\t\t\t\t\t\tresult_max_weight.append(all_result_1[i])\r\n\t\t\t\t\t\tDIC_result_max_weight.update({i1:DIC_result[i]})\r\n\r\n\t\t\t\t\t\ti1=i1+1\r\n\t\t\t\ti=i+1\r\n\r\n\t\ttree_count=0\r\n\t\tfor result_1 in result_max_weight:\r\n\t\t\tdic_result=DIC_result_max_weight[tree_count]\r\n\t\t\tdic_final={}\r\n\t\t\tll=[]#header\r\n\t\t\tll.append('mutation_id')\r\n\t\t\tfor item in dic_result.keys():\r\n\t\t\t\tif len(dic_result[item])!=0 or len(item.split(','))==1:\r\n\t\t\t\t\tll.append(item)#all branch\r\n\t\t\tfor item in ll[1:] :\r\n\t\t\t\tfor mut in dic_result[item]:\r\n\t\t\t\t\tif mut not in dic_final.keys():\r\n\t\t\t\t\t\tLL=[]\r\n\t\t\t\t\t\tLL.append(mut)\r\n\t\t\t\t\t\tfor item1 in ll[1:]:\r\n\t\t\t\t\t\t\tif mut in dic_result[item1]:\r\n\t\t\t\t\t\t\t\tLL.append(1)\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\tLL.append(0)\r\n\t\t\t\t\t\tdriver_string='.'\r\n\t\t\t\t\t\tfor driver_item in search_gene([mut],'FALSE')[:-1]:\r\n\t\t\t\t\t\t\tdriver_string=driver_string+driver_item\r\n\t\t\t\t\t\tif len(driver_string)==1:\r\n\t\t\t\t\t\t\tLL.append('.')\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tLL.append(driver_string[1:])\r\n\t\t\t\t\t\tdic_final.update({mut:LL})\r\n\t\t\t#print(dic_final)\r\n\t\t\tll.append('driver_gene')\r\n\t\t\tresult_2=[]\r\n\t\t\tnumber=1\r\n\t\t\t#print(str(sample_shu))\r\n\t\t\twhile number<=sample_shu:\r\n\t\t\t\tfor item in result_1:\r\n\t\t\t\t\tif number==1:\r\n\t\t\t\t\t\tif len(item.split(':')[0].split(','))==number:\r\n\t\t\t\t\t\t\t#print(item.split(':')[0].split(','))\r\n\t\t\t\t\t\t\tresult_2.append(item)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tif len(item.split(':')[0].split(','))==number:\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tnew_item=','\r\n\t\t\t\t\t\t\tif int(item.split(':')[1].split('[')[0])!=0:\r\n\t\t\t\t\t\t\t\tfor item1 in item.split(':')[0].split(','):\r\n\t\t\t\t\t\t\t\t\tfor item2 in result_2:\r\n\t\t\t\t\t\t\t\t\t\tnum=0\r\n\t\t\t\t\t\t\t\t\t\twhile num<len(item2):\r\n\t\t\t\t\t\t\t\t\t\t\tif item2[num]=='(':\r\n\t\t\t\t\t\t\t\t\t\t\t\tnum=num+1\r\n\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\t\t\t\tif item2[len(str(item1))+num]==':':\r\n\t\t\t\t\t\t\t\t\t\t\tif item1 ==item2[num:len(str(item1))+num]: \r\n\t\t\t\t\t\t\t\t\t\t\t\tnew_item=new_item+','+item2\r\n\t\t\t\t\t\t\t\t\t\t\t\tresult_2.remove(item2)\r\n\t\t\t\t\t\t\t\tnew_item='('+new_item[2:]+'):'\r\n\t\t\t\t\t\t\t\tfor item3 in item.split(':')[1:]:\r\n\t\t\t\t\t\t\t\t\tnew_item=new_item+item3+':'\r\n\t\t\t\t\t\t\t\t#print(new_item[:-1]) \r\n\t\t\t\t\t\t\t\tresult_2.append(new_item[:-1])\r\n\t\t\t\t\t#print(result_2)\r\n\t\t\t\tnumber=number+1\r\n\t\t\t#print(result_2)\r\n\t\t\tfinal_result=','\r\n\t\t\tfor item in result_2:\r\n\t\t\t\tfinal_result=final_result+','+item\r\n\t\t\tfinal_result='('+final_result[2:]+'):'+root_node\r\n\t\t\tprint('tree_structure:')\r\n\t\t\tprint(final_result)\r\n\t\t\tif tree_count==0:\r\n\t\t\t\tfirst_final=final_result\r\n\t\t\ttree_structure=re.sub(u\"\\\\[.*?]\", \"\", final_result)\r\n\t\t\ttree_structure=tree_structure+';'\r\n\t\t\t#print(tree_structure)\r\n\t\t\t#.......................................plot.........................................\r\n\t\t\tif tree_count==0 or (tree_count>0 and final_result!=first_final):\r\n\t\t\t\tout=open(file_path_out+os.path.sep+patient+'_info_'+str(tree_count)+'.txt','w')\r\n\t\t\t\tfor item in ll:\r\n\t\t\t\t\tout.write(str(item))\r\n\t\t\t\t\tout.write('\\t')\r\n\t\t\t\tout.write('\\n')\r\n\t\t\t\tfor item in dic_final.keys():\r\n\t\t\t\t\tcount=0\r\n\t\t\t\t\tfor data in dic_final[item][1:-1]:\r\n\t\t\t\t\t\tcount=count+int(data)\r\n\t\t\t\t\tif count>=2:\r\n\t\t\t\t\t\tout.write(item)\r\n\t\t\t\t\t\tout.write('\\t')\r\n\t\t\t\t\t\tfor data in dic_final[item][1:]:\r\n\t\t\t\t\t\t\tout.write(str(data))\r\n\t\t\t\t\t\t\tout.write('\\t')\r\n\t\t\t\t\t\tout.write('\\n')\r\n\t\t\t\tout.close()\r\n\t\t\t\ttree = Phylo.read(StringIO(tree_structure), \"newick\")\r\n\t\t\t\t#tree.ladderize()# Flip branches so deeper clades are displayed at top\r\n\t\t\t\ttree.rooted = True\r\n\t\t\t\ttree.name=patient\r\n\t\t\t\ttree = tree.as_phyloxml()\r\n\t\t\t\ttree.root.branch_labels=root_node\r\n\t\t\t\t#global tree_label\r\n\t\t\t\tif ('[' in final_result[1:].split(':')[-1]) and (']' in final_result[1:].split(':')[-1]):\r\n\t\t\t\t\ttree_label=final_result[1:].split(':')[:-1]\r\n\t\t\t\telse:\r\n\t\t\t\t\ttree_label=final_result[1:].split(':')[:-2]\r\n\t\t\t\ttree_label_1=[str(i) for i in tree_label]\r\n\t\t\t\ttree_labels = ':'.join(tree_label_1)\r\n\t\t\t\ttree_label_split=tree_labels[:-1]\r\n\t\t\t\tglobal new_tree_labels\r\n\t\t\t\tnew_tree_labels=split_tree(tree_label_split)\r\n\t\t\t\toriginal_count=len(new_tree_labels)\r\n\t\t\t\toriginal_count1=original_count\r\n\t\t\t\tnum=0\r\n\t\t\t\tfor item in new_tree_labels:\r\n\t\t\t\t\tif num <=original_count-1:\r\n\t\t\t\t\t\ttree.clade[num].branch_labels=item.split(':')[-1]\r\n\t\t\t\t\t\tif ('(' in item) or (')' in item):\r\n\t\t\t\t\t\t\tnew_item_1=[str(i) for i in item.split(':')[:-1]]\r\n\t\t\t\t\t\t\tnew_item_split=':'.join(new_item_1)\r\n\t\t\t\t\t\t\tnew_item_split=new_item_split[1:-1]\r\n\t\t\t\t\t\t\tnew_items=split_tree(new_item_split)\r\n\t\t\t\t\t\t\tindex=0\r\n\t\t\t\t\t\t\tfor branch in new_items:\r\n\t\t\t\t\t\t\t\tbranch=str(num)+'*'+str(index)+'*'+branch\r\n\t\t\t\t\t\t\t\tnew_tree_labels.append(branch)\r\n\t\t\t\t\t\t\t\tindex=index+1\r\n\t\t\t\t\t\toriginal_count1=original_count1-1\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tbranch=item.split('*')[-1]\r\n\t\t\t\t\t\tbranch_count=item.split('*')[:-1]\r\n\t\t\t\t\t\t#print(branch_count)\r\n\t\t\t\t\t\tbranch_count_merge=','\r\n\t\t\t\t\t\tfor index in branch_count:\r\n\t\t\t\t\t\t\tbranch_count_merge=branch_count_merge+'*'+index\r\n\t\t\t\t\t\tbranch_count_merge=branch_count_merge[2:]\r\n\t\t\t\t\t\tstr_count='tree.clade['\r\n\t\t\t\t\t\tfor ITEM in branch_count:\r\n\t\t\t\t\t\t\tstr_count=str_count+ITEM+','\r\n\t\t\t\t\t\tstr_count=str_count[:-1]+'].branch_labels = '+'\"'+item.split(':')[-1]+'\"'\r\n\t\t\t\t\t\t#print(str_count)\r\n\t\t\t\t\t\texec(str_count)\r\n\t\t\t\t\t\t#print(tree)\r\n\t\t\t\t\t\tif ('(' in item) or (')' in item):\r\n\t\t\t\t\t\t\tnew_item_1=[str(i) for i in item.split(':')[:-1]]\r\n\t\t\t\t\t\t\tnew_item_split=':'.join(new_item_1)\r\n\t\t\t\t\t\t\tnew_item_split=new_item_split.split('*')[-1]\r\n\t\t\t\t\t\t\tnew_item_split=new_item_split[1:-1]\r\n\t\t\t\t\t\t\tnew_items=split_tree(new_item_split)\r\n\t\t\t\t\t\t\tindex=0\r\n\t\t\t\t\t\t\tfor branch1 in new_items:\r\n\t\t\t\t\t\t\t\tbranch1=str(branch_count_merge)+'*'+str(index)+'*'+branch1\r\n\t\t\t\t\t\t\t\tnew_tree_labels.append(branch1)\r\n\t\t\t\t\t\t\t\tindex=index+1\r\n\t\t\t\t\tnum=num+1\r\n\t\t\t\tmatplotlib.rc('font', size=6)\r\n\t\t\t\tplt.rcParams['lines.linewidth'] = 0.7\r\n\t\t\t\tPhylo.draw(tree,do_show=False,branch_labels=lambda c: c.branch_labels)\t\r\n\t\t\t\t#Phylo.draw(tree,do_show=False,branch_labels=lambda c: int(c.branch_length))\r\n\t\t\t\tplt.savefig(file_path_out+os.path.sep+patient+'_tree_'+str(tree_count)+'.pdf',dpi=500)\r\n\t\t\t\tplt.close()\r\n\t\t\t\ttree_count=tree_count+1\r\n\t\tprint(patient+' ok!')\r\n\telse:\r\n\t\tprint(patient+' have less patients!')\r\n", "meta": {"hexsha": "fe784a6c6eeb2d1b38205f43fb058af9cef38af2", "size": 31274, "ext": "py", "lang": "Python", "max_stars_repo_path": "PTI-v1.0/PTI.py", "max_stars_repo_name": "morinlab/PTI", "max_stars_repo_head_hexsha": "cd3a9009021027551465a123aa31edad8b3caeb6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PTI-v1.0/PTI.py", "max_issues_repo_name": "morinlab/PTI", "max_issues_repo_head_hexsha": "cd3a9009021027551465a123aa31edad8b3caeb6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PTI-v1.0/PTI.py", "max_forks_repo_name": "morinlab/PTI", "max_forks_repo_head_hexsha": "cd3a9009021027551465a123aa31edad8b3caeb6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-28T09:39:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-26T16:56:55.000Z", "avg_line_length": 32.7819706499, "max_line_length": 171, "alphanum_fraction": 0.609963548, "include": true, "reason": "import numpy", "num_tokens": 8581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.19726667062774914}}
{"text": "#!/usr/bin/env python\n\"\"\"\ngapfill : Fills gaps of flux data from Eddy covariance measurements according\n          to Reichstein et al. (Global Change Biology, 2005) or estimate flux\n          uncertainties after Lasslop et al. (Biogeosciences, 2008).\n\nThis module was written by Matthias Cuntz while at Department of\nComputational Hydrosystems, Helmholtz Centre for Environmental\nResearch - UFZ, Leipzig, Germany, and continued while at Institut\nNational de Recherche pour l'Agriculture, l'Alimentation et\nl'Environnement (INRAE), Nancy, France.\n\nCopyright (c) 2012-2020 Matthias Cuntz - mc (at) macu (dot) de\nReleased under the MIT License; see LICENSE file for details.\n\n* Written Mar 2012 by Matthias Cuntz - mc (at) macu (dot) de\n* Ported to Python 3, Feb 2013, Matthias Cuntz\n* Input data can be ND-array, Apr 2014, Matthias Cuntz\n* Bug in longestmarginalgap: was only working at time series edges, rename it\n  to longgap, Apr 2014, Matthias Cuntz\n* Keyword fullday, Apr 2014, Matthias Cuntz\n* Input can be pandas Dataframe or numpy array(s), Apr 2020, Matthias Cuntz\n* Using numpy docstring format, May 2020, Matthias Cuntz\n* error estimates are undef by default, Jun 2021, Matthias Cuntz\n* mean of values for error estimates, Jun 2021, Matthias Cuntz\n\n.. moduleauthor:: Matthias Cuntz\n\nThe following functions are provided\n\n.. autosummary::\n   gapfill\n\"\"\"\nfrom __future__ import division, absolute_import, print_function\nimport numpy as np\nimport pandas as pd\n\n\n__all__ = ['gapfill']\n\n\ndef gapfill(dfin, flag=None, date=None, timeformat='%Y-%m-%d %H:%M:%S',\n            colhead=None,\n            sw_dev=50., ta_dev=2.5, vpd_dev=5.,\n            longgap=60, fullday=False, undef=-9999, ddof=1,\n            err=False, errmean=False, verbose=0):\n    \"\"\"\n    Fills gaps in flux data from Eddy covariance measurements with\n    Marginal Distribution Sampling (MDS) according to Reichstein et al.\n    (Global Change Biology, 2005).\n\n    This means, if there is a gap in the data, look for similar meteorological\n    conditions (defined as maximum possible deviations) in a certain time\n    window and fill with the average of these 'similar' values.\n\n    The routine can also do the same search for similar meteorological\n    conditions for every data point and calculate its standard deviation as a\n    measure of uncertainty after Lasslop et al. (Biogeosciences, 2008).\n\n    Parameters\n    ----------\n    dfin : pandas.Dataframe or numpy.array\n        time series of fluxes to fill as well as\n        meteorological variables incoming short-wave radiation,\n        air temperature, air vapour pressure deficit.\n\n        `dfin` can be a pandas.Dataframe with the columns\n        'SW_IN' (or starting with 'SW_IN') for incoming short-wave radiation [W m-2]\n        'TA'    (or starting with 'TA\\_') for air temperature [deg C]\n        'VPD'   (or starting with 'VPD') for air vapour deficit [hPa]\n        and columns with ecosystem fluxes with possible missing values (gaps).\n        The index is taken as date variable.\n\n        `dfin` can also me a numpy array with the same columns. In this case\n        `colhead`, `date`, and possibly `dateformat` must be given.\n    flag : pandas.Dataframe or numpy.array, optional\n        flag Dataframe or array has the same shape as dfin. Non-zero values in\n        `flag` will be treated as missing values in `dfin`.\n\n        `flag` must follow the same rules as `dfin` if pandas.Dataframe.\n\n        If `flag` is numpy array, `df.columns.values` will be used as\n        column heads and the index of `dfin` will be copied to `flag`.\n    date : array_like of string, optional\n        1D-array_like of calendar dates in format given in `timeformat`.\n\n        `date` must be given if `dfin` is numpy array.\n    timeformat : str, optional\n        Format of dates in `date`, if given (default: '%Y-%m-%d %H:%M:%S').\n        See strftime documentation of Python's datetime module:\n        https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior\n    colhed : array_like of str, optional\n        column names if `dfin` is numpy array. See `dfin` for mandatory\n        column names.\n    sw_dev : float, optional\n        threshold for maximum deviation of global radiation (default: 50)\n    ta_dev : float, optional\n        threshold for maximum deviation of air Temperature (default: 2.5)\n    vpd_dev : float, optional\n        threshold for maximum deviation of vpd (default: 5.)\n    longgap : int, optional\n        avoid extraploation into a gap longer than `longgap` days (default: 60)\n    fullday : bool, optional\n        True: move beginning of large gap to start of next day and move end of\n              large gap to end of last day (default: False)\n    undef : float, optional\n        values having `undef` value are treated as missing values in `dfin`\n        (default: -9999)\n\n        np.nan is not allowed (not working).\n    ddof : int, optional\n        Delta Degrees of Freedom. The divisor used in calculation of standard\n        deviation for error estimates (`err=True`) is ``N-ddof``, where ``N``\n        represents the number of elements (default: 1).\n    err : bool, optional\n        True: fill every data point with standard deviation instead of mean,\n        i.e. used for error generation as in Lasslop et al. (Biogeosci 2008)\n        (default: False)\n    errmean : bool, optional\n        True: also return mean value of values for error estimate\n        `if err == True` (default: False)\n    shape : bool or tuple, optional\n        True: output have the same shape as input data if `dfin` is\n        numpy array; if a tuple is given, then this tuple is used to reshape.\n\n        False: outputs are 1D arrays if `dfin` is numpy array (default: False).\n    verbose : int, optional\n        Verbosity level 0-3 (default: 0). 0 is no output; 3 is very verbose.\n\n    Returns\n    -------\n    pandas.Dataframe(s) or numpy array(s)\n        `if not err:` filled_data, quality_class\n\n        `if err and not errmean:` err_estimate\n\n        `if err and errmean:` err_estimate, mean_estimate\n\n        pandas.Dataframe(s) will be returned if `dfin` was Dataframe.\n\n        numpy array(s) will be returned if `dfin` was numpy array.\n\n    Notes\n    -----\n    If `err`, there is no error estimate if there are no meteorological\n    conditions in the vicinity of the data point (first cycle of\n    Reichstein et al. GCB 2005).\n\n    Routine does not work with `undef=np.nan`.\n\n    Reichstein et al. (2005)\n        On the separation of net ecosystem exchange into assimilation and\n        ecosystem respiration: review and improved algorithm\n        Global Change Biology 11, 1424-1439\n\n    Lasslop et al. (2008)\n        Inﬂuences of observation errors in eddy ﬂux data on inverse model\n        parameter estimation\n        Biogeosciences, 5, 1311–1324\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> from fread import fread\n    >>> from date2dec import date2dec\n    >>> from dec2date import dec2date\n    >>> ifile = 'test_gapfill.csv' # Tharandt 1998 = Online tool example file\n    >>> undef = -9999.\n    >>> # data\n    >>> dat   = fread(ifile, skip=2, transpose=True)\n    >>> ndat  = dat.shape[1]\n    >>> head  = fread(ifile, skip=2, header=True)\n    >>> head1 = head[0]\n    >>> # colhead\n    >>> idx   = []\n    >>> for i in head1:\n    ...     if i in ['NEE', 'LE', 'H', 'Rg', 'Tair', 'VPD']:\n    ...         idx.append(head1.index(i))\n    >>> colhead = ['FC', 'LE', 'H', 'SW_IN', 'TA', 'VPD']\n    >>> # data\n    >>> dfin = dat[idx,:]\n    >>> # flag\n    >>> flag = np.where(dfin == undef, 2, 0)\n    >>> flag[0, :] = dat[head1.index('qcNEE'), :].astype(int)\n    >>> flag[1, :] = dat[head1.index('qcLE'), :].astype(int)\n    >>> flag[2, :] = dat[head1.index('qcH'), :].astype(int)\n    >>> flag[np.where(flag==1)] = 0\n    >>> # date\n    >>> day_id  = head1.index('Day')\n    >>> hour_id = head1.index('Hour')\n    >>> ntime   = dat.shape[1]\n    >>> year  = np.ones(ntime, dtype=int) * 1998\n    >>> hh    = dat[hour_id, :].astype(int)\n    >>> mn    = np.rint((dat[hour_id,:] - hh) * 60.).astype(int)\n    >>> y0    = date2dec(yr=year[0], mo=1, dy=1, hr=hh, mi=mn)\n    >>> jdate = y0 + dat[day_id, :]\n    >>> adate = dec2date(jdate, eng=True)\n    >>> # fill\n    >>> dat_f, flag_f = gapfill(dfin, flag=flag, date=adate, colhead=colhead,\n    ...                         undef=undef, verbose=0)\n    >>> print('{:d} {:d} {:d} {:d} {:d} {:d}'.format(*flag_f[0, 11006:11012]))\n    1 1 1 2 2 2\n    >>> print('{:.2f} {:.2f} {:.2f} {:.2f} {:.2f} {:.2f}'.format(\n    ...       *dat_f[0, 11006:11012]))\n    -18.68 -15.63 -19.61 -15.54 -12.40 -15.33\n\n    >>> # 1D err\n    >>> dat_std = gapfill(dfin, flag=flag, date=adate, colhead=colhead,\n    ...                   undef=undef, verbose=0, err=True)\n    >>> print('{:.3f} {:.3f} {:.3f} {:.3f} {:.3f} {:.3f}'.format(\n    ...       *dat_std[0, 11006:11012]))\n    5.372 13.118 6.477 -9999.000 -9999.000 -9999.000\n\n    >>> dat_err = np.ones(ndat, dtype=int)*(-1)\n    >>> kk      = np.where((dat_std[0, :] != undef) & (dat_f[0, :] != 0.))[0]\n    >>> dat_err[kk] = np.abs(dat_std[0,kk]/dat_f[0,kk]*100.).astype(int)\n    >>> print('{:d} {:d} {:d} {:d} {:d} {:d}'.format(*dat_err[11006:11012]))\n    28 83 33 -1 -1 -1\n\n    >>> # 1D err + mean\n    >>> dat_std, dat_mean = gapfill(dfin, flag=flag, date=adate,\n    ...                             colhead=colhead, undef=undef, verbose=0,\n    ...                             err=True, errmean=True)\n    >>> print('{:.3f} {:.3f} {:.3f} {:.3f} {:.3f} {:.3f}'.format(\n    ...       *dat_std[0, 11006:11012]))\n    5.372 13.118 6.477 -9999.000 -9999.000 -9999.000\n    >>> print('{:.3f} {:.3f} {:.3f} {:.3f} {:.3f} {:.3f}'.format(\n    ...       *dat_mean[0, 11006:11012]))\n    -18.677 -15.633 -19.610 -9999.000 -9999.000 -9999.000\n\n\n    History\n    -------\n    Written,  Matthias Cuntz, Mar 2012 - modified gap_filling.py\n    Modified, Matthias Cuntz, Feb 2013 - ported to Python 3\n              Matthias Cuntz, Apr 2014 - assert\n                                       - data ND-array\n                                       - longestmarginalgap was only working at\n                                         beginning and end of time series\n                                         renamed to longgap\n                                       - fullday\n              Matthias Cuntz, Apr 2020 - Input can be pandas Dataframe or\n                                         numpy array(s)\n              Matthias Cuntz, May 2020 - numpy docstring format\n              Matthias Cuntz, Jun 2021 - prefill error estimates with undef\n                                       - errmean\n    \"\"\"\n    # Check input\n    # numpy or panda\n    if isinstance(dfin, (np.ndarray, np.ma.MaskedArray)):\n        isnumpy = True\n        istrans = False\n        astr = 'colhead must be given if input is numpy.ndarray.'\n        assert colhead is not None, astr\n        if dfin.shape[0] == len(colhead):\n            istrans = True\n            df = pd.DataFrame(dfin.T, columns=colhead)\n        elif dfin.shape[1] == len(colhead):\n            df = pd.DataFrame(dfin, columns=colhead)\n        else:\n            estr = 'Length of colhead must be number of columns in input'\n            estr = estr + ' array. len(colhead)=' + str(len(colhead))\n            estr = estr + ' shape(input)=(' + str(dfin.shape[0])\n            estr = estr + ',' + str(dfin.shape[1]) + ').'\n            raise ValueError(estr)\n        assert date is not None, 'date must be given if input is numpy arrary.'\n        df['Datetime'] = pd.to_datetime(date, format=timeformat)\n        df.set_index('Datetime', drop=True, inplace=True)\n    else:\n        isnumpy = False\n        istrans = False\n        astr = 'Input must be either numpy.ndarray or pandas.DataFrame.'\n        assert isinstance(dfin, pd.core.frame.DataFrame), astr\n        df = dfin.copy(deep=True)\n\n    # Incoming flags\n    if flag is not None:\n        if isinstance(flag, (np.ndarray, np.ma.MaskedArray)):\n            fisnumpy = True\n            fistrans = False\n            if flag.shape[0] == len(df):\n                ff = pd.DataFrame(flag, columns=df.columns.values)\n            elif flag.shape[1] == len(df):\n                fistrans = True\n                ff = pd.DataFrame(flag.T, columns=df.columns.values)\n            else:\n                estr  = 'flag must have same shape as data array. data:'\n                estr += ' ({:d},{:d}); flag: ({:d},{:d})'.format(\n                    dfin.shape[0], dfin.shape[1], flag.shape[0], flag.shape[1])\n                raise ValueError(estr)\n            ff = ff.set_index(df.index)\n        else:\n            fisnumpy = False\n            fistrans = False\n            astr = 'Flag must be either numpy.ndarray or pandas.DataFrame.'\n            assert isinstance(flag, pd.core.frame.DataFrame), astr\n            ff = flag.copy(deep=True)\n    else:\n        fisnumpy = isnumpy\n        fistrans = istrans\n        # flags: 0: good; 1: input flagged; 2: output flagged\n        ff              = df.copy(deep=True).astype(int)\n        ff[:]           = 0\n        ff[df == undef] = 1\n        ff[df.isna()]   = 1\n\n    # Data and flags\n    sw_id = ''\n    for cc in df.columns:\n        if cc.startswith('SW_IN_') or (cc == 'SW_IN'):\n            sw_id = cc\n            break\n    ta_id = ''\n    for cc in df.columns:\n        if cc.startswith('TA_') or (cc == 'TA'):\n            ta_id = cc\n            break\n    vpd_id = ''\n    for cc in df.columns:\n        if cc.startswith('VPD_') or (cc == 'VPD'):\n            vpd_id = cc\n            break\n    astr = 'Global radiation with name SW or starting with SW_'\n    astr = astr + ' must be in input.'\n    assert sw_id,  astr\n    astr = 'Air temperature with name TA or starting with TA_'\n    astr = astr + ' must be in input.'\n    assert ta_id,  astr\n    astr = 'Vapour pressure deficit with name VPD or starting'\n    astr = astr + ' with VPD_ must be in input.'\n    assert vpd_id, astr\n\n    sw      = df[sw_id].to_numpy()\n    sw_flg  = ff[sw_id].to_numpy()\n    ta      = df[ta_id].to_numpy()\n    ta_flg  = ff[ta_id].to_numpy()\n    vpd     = df[vpd_id].to_numpy()\n    vpd_flg = ff[vpd_id].to_numpy()\n\n    # dfill is filled data\n    # ffill is fill flag if not err else error estimate\n    dfill = df.copy(deep=True)\n    if err:\n        ffill = df.copy(deep=True)\n    else:\n        ffill    = ff.copy(deep=True)\n        ffill[:] = 0\n\n    # Times\n    # number of data points per week; basic factor of the time window\n    week    = pd.Timedelta('1 W') / (df.index[1] - df.index[0])\n    nperday = week // 7\n    hour    = df.index.hour + df.index.minute/60.\n    day     = (df.index.to_julian_date()-0.5).astype(int)\n\n    # Filling variables\n    ndata = len(df)\n    for hcol in df.columns:\n\n        if hcol.startswith('SW_IN_') or (hcol == 'SW_IN'):\n            continue\n        if hcol.startswith('TA_')    or (hcol == 'TA'):\n            continue\n        if hcol.startswith('VPD_')   or (hcol == 'VPD'):\n            continue\n\n        if verbose > 0:\n            if err:\n                print('  Error estimate ', str(hcol))\n            else:\n                print('  Filling ', str(hcol))\n\n        data  = df[hcol].to_numpy()\n        dflag = ff[hcol].to_numpy()\n\n        data_f  = dfill[hcol].to_numpy()\n        dflag_f = ffill[hcol].to_numpy()\n\n        if err:\n            data_f[:]  = undef\n            dflag_f[:] = undef\n\n        # Large margins\n\n        # Check for large margins at beginning\n        largegap   = np.zeros(ndata, dtype=bool)\n        firstvalid = np.amin(np.where(dflag == 0)[0])\n        lastvalid  = np.amax(np.where(dflag == 0)[0])\n        nn         = int(nperday*longgap)\n        if firstvalid > nn:\n            if verbose > 1:\n                print('    Large margin at beginning: ', firstvalid)\n            largegap[0:(firstvalid-nn)] = True\n        if lastvalid < (ndata-nn):\n            if verbose > 1:\n                print('    Large margin at end: ', lastvalid-nn)\n            largegap[(lastvalid+nn):] = True\n\n        # Large gaps\n\n        # search largegap - code from maskgroup.py\n        index  = []\n        length = []\n        count  = 0\n        for i in range(ndata):\n            if i == 0:\n                if dflag[i] != 0:\n                    index += [i]\n                    count  = 1\n            if i > 0:\n                if (dflag[i] != 0) and (dflag[i-1] == 0):\n                    index += [i]\n                    count  = 1\n                elif dflag[i] != 0:\n                    count += 1\n                elif (dflag[i] == 0) and (dflag[i-1] != 0):\n                    length += [count]\n                    count = 0\n                else:\n                    pass\n        if count > 0:\n            length += [count]\n\n        # set largegap\n        for i in range(len(index)):\n            if length[i] > nn:\n                if verbose > 1:\n                    print('    Large gap: ', index[i], ':', index[i]+length[i])\n                largegap[index[i]:index[i]+length[i]] = True\n\n        # set or unset rest of days in large gaps\n        if fullday:\n            for i in range(ndata-1):\n                # end of large margin\n                if largegap[i] and not largegap[i+1]:\n                    largegap[np.where(day == day[i])[0]] = False\n                # beginning of large margin\n                elif not largegap[i] and largegap[i+1]:\n                    largegap[np.where(day == day[i])[0]] = False\n                else:\n                    continue\n\n        # Gap filling\n\n        # flag for all meteorological conditions\n        meteo_flg = (ta_flg == 0) & (vpd_flg == 0) & (sw_flg == 0)\n        # flag for all meteorological conditions and data\n        total_flg = meteo_flg & (dflag == 0)\n\n        # Fill loop over all data points\n        for j in range(ndata):\n            if not err:\n                # no reason to go further, no gap -> continue\n                if (dflag[j] == 0) | largegap[j]:\n                    continue\n            # 3 Methods\n            #   1. ta, vpd and global radiation sw;\n            #   2. just global radiation sw;\n            #   3. no meteorolgical conditions: take the mean of +- hour\n\n            # for better overview: dynamic calculation of radiation threshold\n            # minimum 20; maximum 50 [Wm-2] according to private correspondence\n            # with Markus Reichstein\n            sw_devmax = np.maximum(20., np.minimum(sw[j], sw_dev))\n\n            # Method 1: all met conditions\n            if meteo_flg[j]:\n                # search for values around the met-conditions\n                # in a window of time\n                # (one week in the first iteration and odd weeks in the next)\n                j1  = j - np.arange(1, week+1, dtype=int) + 1\n                j2  = j + np.arange(1, week, dtype=int)\n                jj  = np.append(j1, j2)\n                win = np.unique(np.sort(np.clip(jj, 0, ndata-1)))\n                # get boolean array where meteo-conditions are in a given width\n                conditions = ( (np.abs(sw[win]-sw[j])   < sw_devmax) &\n                               (np.abs(ta[win]-ta[j])   < ta_dev) &\n                               (np.abs(vpd[win]-vpd[j]) < vpd_dev) &\n                               total_flg[win] )\n                num4avg = np.sum(conditions)\n                # we need at least two samples with similar conditions\n                if num4avg >= 2:\n                    dat = np.ma.array(data[win], mask=~conditions)\n                    if verbose > 2:\n                        print('    m1.1: ', j, win.size, dat.mean(),\n                              dat.std(ddof=ddof))\n                    data_f[j] = dat.mean()\n                    if err:\n                        dflag_f[j] = dat.std(ddof=ddof)\n                    else:\n                        # assign also quality category of gap filling\n                        dflag_f[j] = 1\n                    continue\n                else:  # --> extend time window to two weeks\n                    j1  = j - np.arange(1, 2*week+1, dtype=int) + 1\n                    j2  = j + np.arange(1, 2*week, dtype=int)\n                    jj  = np.append(j1, j2)\n                    win = np.unique(np.sort(np.clip(jj, 0, ndata-1)))\n                    conditions = ( (np.abs(sw[win]  - sw[j])  < sw_devmax) &\n                                   (np.abs(ta[win]  - ta[j])  < ta_dev) &\n                                   (np.abs(vpd[win] - vpd[j]) < vpd_dev) &\n                                   total_flg[win] )\n                    num4avg = np.sum(conditions)\n                    if num4avg >= 2:\n                        dat = np.ma.array(data[win], mask=~conditions)\n                        if verbose > 2:\n                            print('    m1.2: ', j, win.size, dat.mean(),\n                                  dat.std(ddof=ddof))\n                        data_f[j] = dat.mean()\n                        if err:\n                            dflag_f[j] = dat.std(ddof=ddof)\n                        else:\n                            # assign also quality category of gap filling\n                            dflag_f[j] = 1\n                        continue\n\n            if err:\n                continue\n            # if you come here, gap-filling rather than error estimate\n\n            # If nothing is found under similar meteo within two weeks,\n            # look for global radiation within one week ->\n\n            # Method 2: just global radiation available\n            if sw_flg[j] == 0:\n                j1  = j - np.arange(1, week+1, dtype=int) + 1\n                j2  = j + np.arange(1, week, dtype=int)\n                jj  = np.append(j1, j2)\n                win = np.unique(np.sort(np.clip(jj, 0, ndata-1)))\n                # get boolean array where meteo-conditions are in a given width\n                conditions = ( (np.abs(sw[win]-sw[j]) < sw_devmax) &\n                               total_flg[win] )\n                num4avg = np.sum(conditions)\n                # we need at least two samples with similar conditions\n                if num4avg >= 2:\n                    dat = np.ma.array(data[win], mask=~conditions)\n                    if verbose > 2:\n                        print('    m2: ', j, win.size, dat.mean(),\n                              dat.std(ddof=ddof))\n                    data_f[j]  = dat.mean()\n                    dflag_f[j] = 1\n                    continue\n\n            # If still nothing is found under similar sw within one week,\n            # take the same hour within 1-7 days\n\n            # Method 3: same hour\n            enough = False\n            for i in range(2):\n                t_win = (nperday * (2*i+1))//2\n                j1  = j - np.arange(1, t_win+1, dtype=int) + 1\n                j2  = j + np.arange(1, t_win, dtype=int)\n                jj  = np.append(j1, j2)\n                win = np.unique(np.sort(np.clip(jj, 0, ndata-1)))\n                conditions = ( (np.abs(hour[win]-hour[j]) < 1.1)\n                               & (dflag[win] == 0) )\n                num4avg = np.sum(conditions)\n                if num4avg >= 2:\n                    dat = np.ma.array(data[win], mask=~conditions)\n                    if verbose > 2:\n                        print('    m3.{:d}: '.format(i), j, win.size,\n                              dat.mean(), dat.std(ddof=ddof))\n                    data_f[j] = dat.mean()\n                    if i == 0:\n                        dflag_f[j] = 1\n                    else:\n                        dflag_f[j] = 2\n                    break\n\n            # sanity check\n            if dflag_f[j] > 0:\n                continue\n\n            # If still nothing is found, start a new cycle\n            # with increased window size\n            # Method 4: same as 1 but for 3-12 weeks\n            if meteo_flg[j]:\n                for multi in range(3, 12):\n                    j1  = j - np.arange(1, multi*week+1, dtype=int) + 1\n                    j2  = j + np.arange(1, multi*week, dtype=int)\n                    jj  = np.append(j1, j2)\n                    win = np.unique(np.sort(np.clip(jj, 0, ndata-1)))\n                    conditions = ( (np.abs(sw[win]  - sw[j])  < sw_devmax) &\n                                   (np.abs(ta[win]  - ta[j])  < ta_dev) &\n                                   (np.abs(vpd[win] - vpd[j]) < vpd_dev) &\n                                   total_flg[win] )\n                    num4avg = np.sum(conditions)\n                    # we need at least two samples with similar conditions\n                    if num4avg >= 2:\n                        dat = np.ma.array(data[win], mask=~conditions)\n                        if verbose > 2:\n                            print('    m4.{:d}: '.format(multi), j, win.size,\n                                  dat.mean(), dat.std(ddof=ddof))\n                        data_f[j] = dat.mean()\n                        # assign also quality category of gap filling\n                        if multi <= 2:\n                            dflag_f[j] = 1\n                        elif multi > 4:\n                            dflag_f[j] = 3\n                        else:\n                            dflag_f[j] = 2\n                        break\n\n                # Check because continue does not support\n                # to jump out of two loops\n                if dflag_f[j] > 0:\n                    continue\n\n            # Method 5: same as 2 but for 2-12 weeks\n            if sw_flg[j] == 0:\n                for multi in range(2, 12):\n                    j1  = j - np.arange(1, multi*week+1, dtype=int) + 1\n                    j2  = j + np.arange(1, multi*week, dtype=int)\n                    jj  = np.append(j1, j2)\n                    win = np.unique(np.sort(np.clip(jj, 0, ndata-1)))\n                    # get boolean array where meteo-conditions are\n                    # in a given width\n                    conditions = ( (np.abs(sw[win] - sw[j]) < sw_devmax) &\n                                   total_flg[win] )\n                    num4avg = np.sum(conditions)\n                    # we need at least two samples with similar conditions\n                    if num4avg >= 2:\n                        dat = np.ma.array(data[win], mask=~conditions)\n                        if verbose > 2:\n                            print('    m5.{:d}: '.format(multi), j, win.size,\n                                  dat.mean(), dat.std(ddof=ddof))\n                        data_f[j] = dat.mean()\n                        if multi == 0:\n                            dflag_f[j] = 1\n                        elif multi <= 2:\n                            dflag_f[j] = 2\n                        else:\n                            dflag_f[j] = 3\n                        break\n\n                if dflag_f[j] > 0:\n                    continue\n\n            # Method 6: same as 3 but for 3-120 days\n            for i in range(3, 120):\n                t_win = nperday * (2*i+1)/2\n                j1  = j - np.arange(1, t_win+1, dtype=int) + 1\n                j2  = j + np.arange(1, t_win, dtype=int)\n                jj  = np.append(j1, j2)\n                win = np.unique(np.sort(np.clip(jj, 0, ndata-1)))\n                conditions = ( (np.abs(hour[win]-hour[j]) < 1.1)\n                               & (dflag[win] == 0) )\n                num4avg = np.sum(conditions)\n                if num4avg >= 2:\n                    dat = np.ma.array(data[win], mask=~conditions)\n                    if verbose > 2:\n                        print('    m6.{:d}: '.format(i), j, win.size,\n                              dat.mean(), dat.std(ddof=ddof))\n                    data_f[j]  = dat.mean()\n                    dflag_f[j] = 3\n                    break\n\n        dfill[hcol] = data_f\n        ffill[hcol] = dflag_f\n\n    # Finish\n\n    if isnumpy:\n        if istrans:\n            dfout = dfill.to_numpy().T\n        else:\n            dfout = dfill.to_numpy()\n    else:\n        dfout = dfill\n\n    if fisnumpy:\n        if fistrans:\n            ffout = ffill.to_numpy().T\n        else:\n            ffout = ffill.to_numpy()\n    else:\n        ffout = ffill\n\n    if err:\n        if errmean:\n            return ffout, dfout\n        else:\n            return ffout\n    else:\n        return dfout, ffout\n\n\nif __name__ == '__main__':\n    import doctest\n    doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)\n\n    # import numpy as np\n    # from fread import fread\n    # from date2dec import date2dec\n    # from dec2date import dec2date\n    # from autostring import astr\n    # ifile = 'test_gapfill.csv' # Tharandt 1998 = Online tool example file\n    # undef = -9999.\n    # # Day Hour NEE         qcNEE  LE    qcLE  H       qcH  Rg    Tair  Tsoil  rH     VPD  Ustar\n    # # --  --   umolm-2s-1  --     Wm-2  --    Wm-2    --   Wm-2  degC  degC   %      hPa  ms-1\n    # # 1   0.5  -1.21       1      1.49  1     -11.77  1    0     7.4   4.19   55.27  4.6  0.72\n    # dat   = fread(ifile, skip=2, transpose=True)\n    # # dat = dat[:,:1000]\n    # ndat  = dat.shape[1]\n    # head  = fread(ifile, skip=2, header=True)\n    # head1 = head[0]\n    # # colhead\n    # idx   = []\n    # for i in head1:\n    #     if i in ['NEE', 'LE', 'H', 'Rg', 'Tair', 'VPD']: idx.append(head1.index(i))\n    # colhead = ['FC', 'LE', 'H', 'SW_IN', 'TA', 'VPD']\n    # # data\n    # dfin = dat[idx,:]\n    # # flag\n    # flag = np.where(dfin == undef, 2, 0)\n    # flag[0,:] = dat[head1.index('qcNEE'),:].astype(int)\n    # flag[1,:] = dat[head1.index('qcLE'),:].astype(int)\n    # flag[2,:] = dat[head1.index('qcH'),:].astype(int)\n    # flag[np.where(flag==1)] = 0\n    # # date\n    # day_id  = head1.index('Day')\n    # hour_id = head1.index('Hour')\n    # ntime   = dat.shape[1]\n    # year  = np.ones(ntime, dtype=int) * 1998\n    # hh    = dat[hour_id,:].astype(int)\n    # mn    = np.rint((dat[hour_id,:]-hh)*60.).astype(int)\n    # y0    = date2dec(yr=year[0], mo=1, dy=1, hr=hh, mi=mn)\n    # jdate = y0 + dat[day_id,:]\n    # adate = dec2date(jdate, eng=True)\n    # # fill\n    # dat_f, flag_f = gapfill(dfin, flag=flag, date=adate, colhead=colhead, undef=undef, verbose=0)\n    # print(astr(flag_f[0,11006:11012],0,pp=True))\n    # # ['1' '1' '1' '2' '2' '2']\n    # print(astr(dat_f[0,11006:11012],3,pp=True))\n    # # ['-18.678' '-15.633' '-19.610' '-15.536' '-12.402' '-15.329']\n\n    # # 1D err\n    # dat_std = gapfill(dfin, flag=flag, date=adate, colhead=colhead, undef=undef, verbose=0, err=True)\n    # print(astr(dat_std[0,11006:11012],3,pp=True))\n    # # ['    5.372' '   13.118' '    6.477' '-9999.000' '-9999.000' '-9999.000']\n\n    # dat_err     = np.ones(ndat, dtype=int)*(-1)\n    # kk          = np.where((dat_std[0,:] != undef) & (dat_f[0,:] != 0.))[0]\n    # dat_err[kk] = np.abs(dat_std[0,kk]/dat_f[0,kk]*100.).astype(int)\n    # print(astr(dat_err[11006:11012],pp=True))\n    # # [' 28' ' 83' ' 33' ' -1' ' -1' ' -1']\n", "meta": {"hexsha": "ae1870b9d00ac8a701ccb0ea3ab9df07d5d121d3", "size": 30647, "ext": "py", "lang": "Python", "max_stars_repo_path": "hesseflux/gapfill.py", "max_stars_repo_name": "mcuntz/hesseflux", "max_stars_repo_head_hexsha": "18884e1b33c647da18dcfa5ee689a37d2f274b5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-05-26T08:56:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T14:45:03.000Z", "max_issues_repo_path": "hesseflux/gapfill.py", "max_issues_repo_name": "mcuntz/hesseflux", "max_issues_repo_head_hexsha": "18884e1b33c647da18dcfa5ee689a37d2f274b5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-22T15:15:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T23:30:00.000Z", "max_forks_repo_path": "hesseflux/gapfill.py", "max_forks_repo_name": "mcuntz/hesseflux", "max_forks_repo_head_hexsha": "18884e1b33c647da18dcfa5ee689a37d2f274b5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-11-24T21:38:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T11:12:28.000Z", "avg_line_length": 41.0267737617, "max_line_length": 103, "alphanum_fraction": 0.5076516462, "include": true, "reason": "import numpy", "num_tokens": 8350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.19726666829148448}}
{"text": "from PyQt5 import QtCore, QtGui, QtWidgets\nimport res_rc\nimport ui as gui\nimport global_ as g\nimport numpy as np \nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar\nfrom matplotlib.figure import Figure\n\nimport pickle\nimport sys\nimport random\nimport numpy as np\nimport argparse\nimport Reader\nimport Spectrum\nimport Algorithm\nclass Button:\n    def __init__(self,button,entry):\n        self.button = button\n        self.entry = entry\n        g.values[self.entry] = self.button.value()\n        self.button.valueChanged.connect(self.valuechange)\n    def valuechange(self):\n        g.values[self.entry] = self.button.value()\n        if(self.entry == \"lb\" or self.entry == \"hb\"):\n            for i in range(len(g.canvas_list)):\n                try:\n                    g.canvas_list[i].change_x()\n                except:\n                    pass\n        elif(self.entry == \"w\" or self.entry == \"T\"):\n            try:\n                g.Spectrum.Boltzmann_weight_IR()\n                g.canvas_list[2].plot_IR_theo()\n                g.Spectrum.Boltzmann_weight_VCD()\n                g.canvas_list[3].plot_VCD_theo()\n            except:\n                pass\nclass Click_Button:\n    def __init__(self,button,entry,args = None):\n        self.button = button\n        self.entry = entry\n        self.button.clicked.connect(self.click)\n        self.args = args\n    def click(self):\n        if(self.entry == \"normalize_1\"):\n            try:\n                tmp = (g.exp_ir[:,0] <= g.values[\"hb\"]) & (g.exp_ir[:,0] >= g.values[\"lb\"])\n                g.exp_ir[:,1] = g.exp_ir[:,1]/np.max(g.exp_ir[tmp,1])\n                g.canvas_list[0].plot_IR()\n            except:\n                pass\n            try:\n                tmp = (g.exp_vcd[:,0] <= g.values[\"hb\"]) & (g.exp_vcd[:,0] >= g.values[\"lb\"])\n                g.exp_vcd[:,1] = g.exp_vcd[:,1]/np.max(np.abs(g.exp_vcd[tmp,1]))\n                g.canvas_list[1].plot_VCD()            \n            except:\n                pass\n        elif(self.entry == \"normalize_2\"):\n            try:\n                tmp = (g.theo_ir[:,0] <= g.values[\"hb\"]) & (g.theo_ir[:,0] >= g.values[\"lb\"])\n                g.theo_ir[:,1] = g.theo_ir[:,1]/np.max(g.theo_ir[tmp,1])\n                g.canvas_list[2].plot_IR()\n            except:\n                pass\n            try:\n                tmp = (g.theo_vcd[:,0] <= g.values[\"hb\"]) & (g.theo_vcd[:,0] >= g.values[\"lb\"])\n                g.theo_vcd[:,1] = g.theo_vcd[:,1]/np.max(np.abs(g.theo_vcd[tmp,1]))\n                g.canvas_list[3].plot_VCD()            \n            except:\n                pass\n        elif(self.entry == \"automatic\"):\n            try:\n                tmp = (g.exp_ir[:,0] <= g.values[\"hb\"]) & (g.exp_ir[:,0] >= g.values[\"lb\"])\n                tmp_ir = np.asarray(g.exp_ir[tmp])\n                g.peak_list_x = []\n                g.peak_list_y = []\n                g.peak_list_VCD_y = []\n                for i in range(1,len(tmp_ir)-1):\n                    if(tmp_ir[i-1,1]<=tmp_ir[i,1]>=tmp_ir[i+1,1]):\n                        g.peak_list_x.append(tmp_ir[i,0])\n                        g.peak_list_y.append(tmp_ir[i,1])\n                print(g.peak_list_x)\n                g.canvas_list[0].plot_peaks()\n                g.exp_peaks = np.zeros((len(g.peak_list_x),2))\n                g.exp_peaks[:,0] = np.asarray(g.peak_list_x)\n                g.exp_peaks[:,1] = np.asarray(g.peak_list_y)\n                for peak in g.peak_list_x:\n                    g.peak_list_VCD_y.append(g.exp_vcd[abs(g.exp_vcd[:,0]-peak)<10e-1,1][0])\n                g.canvas_list[1].plot_peaks_VCD()\n            except:\n                pass\n        elif(self.entry == \"align\"):\n            try:\n                del Algo\n                print(\"del\")\n            except: \n                pass\n            Algo = Algorithm.Algorithm()\n            if(g.set_VCD==False):\n                g.returnvalue, g.old_freq, g.freq_new, g.inten_new = Algo.Needleman_IR()\n            else:\n                g.returnvalue, g.old_freq, g.freq_new, g.inten_new,g.inten_VCD_new = Algo.Needleman_IR()\n            g.canvas_list[4].plot_IR_assigned()\n            g.Spectrum.IR_shifted()\n            if(g.set_VCD==True):\n                g.Spectrum.VCD_shifted()\n                p_ir,p_vcd = g.Spectrum.integrate()\n\n                self.args.setText(\"Score: \" + str(g.returnvalue)[0:6]+\"\\np_ir: \" + str(p_ir)[0:4]+\"\\np_vcd: \" + str(p_vcd)[0:4]+\"\\n\")\n            else:\n                p_ir = g.Spectrum.integrate()\n                self.args.setText(\"Score: \" + str(g.returnvalue)[0:6]+\"\\np_ir: \" + str(p_ir)[0:4]+\"\\n\")\n            g.canvas_list[5].plot_IR_shifted()\nclass Load_Button:\n    def __init__(self,button,entry):\n        self.button = button\n        self.entry = entry\n        self.button.clicked.connect(self.click)\n    def click(self):\n        if(self.entry == \"experimental IR\"):\n            try:\n                fileName, _ = QtWidgets.QFileDialog.getOpenFileName(None,\"Select \"+self.entry +\" Spectrum\",\"\",\"\")\n                g.exp_ir = np.loadtxt(fileName,usecols=(0,1))\n                g.exp_ir = g.exp_ir[g.exp_ir[:,0].argsort()]\n                g.canvas_list[0].plot_IR()\n                g.set_IR = True\n            except:\n                pass\n        elif(self.entry == \"experimental VCD\"):\n            try:\n                fileName, _ = QtWidgets.QFileDialog.getOpenFileName(None,\"Select \"+self.entry +\" Spectrum\",\"\",\"\")\n                g.exp_vcd = np.loadtxt(fileName,usecols=(0,1,))\n                g.exp_vcd = g.exp_vcd[g.exp_vcd[:,0].argsort()]\n                g.canvas_list[1].plot_VCD()\n                g.set_VCD = True\n            except:\n                pass\n        elif(self.entry == \"energies\"):\n            fileName_energy, _ = QtWidgets.QFileDialog.getOpenFileName(None,\"Select \"+self.entry +\" Energies\",\"\",\"\")\n            g.E = pickle.load(open(fileName_energy,\"rb\"))\n        elif(self.entry == \"theoretical IR\"):\n            fileName_IR, _ = QtWidgets.QFileDialog.getOpenFileName(None,\"Select \"+self.entry +\" Spectrum\",\"\",\"\")\n            g.theo_ir = pickle.load(open(fileName_IR,\"rb\"))\n            g.Spectrum.Boltzmann_weight_IR()\n            g.canvas_list[2].plot_IR_theo()\n        elif(self.entry == \"theoretical VCD\"):\n            try:\n                fileName_VCD, _ = QtWidgets.QFileDialog.getOpenFileName(None,\"Select \"+self.entry +\" Spectrum\",\"\",\"\")\n                g.theo_vcd = pickle.load(open(fileName_VCD,\"rb\"))\n                g.Spectrum.Boltzmann_weight_VCD()\n                g.canvas_list[3].plot_VCD_theo()\n            except:\n                pass\nclass Canvas(FigureCanvas):\n    def __init__(self, single = None, parent = None, Button = None, dpi = 100):\n        height = parent.height()/100.\n        width = parent.width()/100.\n        fig = Figure(figsize=(width, height), dpi=dpi)\n        FigureCanvas.__init__(self, fig)\n        self.setParent(parent)\n        self.ax = self.figure.add_subplot(111)\n        #Button\n    def change_x(self):\n        self.ax.set_xlim(g.values[\"lb\"],g.values[\"hb\"])\n        self.draw()\n    def plot_IR(self):\n        self.delete()\n        self.ax.plot(g.exp_ir[:,0],g.exp_ir[:,1],color=\"black\")\n        self.ax.set_ylim(0,1.05)\n        self.ax.set_xlim(g.values[\"lb\"],g.values[\"hb\"])\n        self.draw()\n    def plot_IR_shifted(self):\n        self.delete()\n        self.ax.plot(g.exp_ir[:,0],g.exp_ir[:,1],color=\"black\")\n        self.ax.plot(g.IR_shifted[:,0],g.IR_shifted[:,1],color=\"red\")\n        if(g.set_VCD==True):\n            self.ax.plot(g.exp_vcd[:,0],g.exp_vcd[:,1],\"--\",color=\"black\")\n            self.ax.plot(g.VCD_shifted[:,0],g.VCD_shifted[:,1],\"--\",color=\"red\")\n        self.ax.set_ylim(-1.05,1.05)\n        self.ax.set_xlim(g.values[\"lb\"],g.values[\"hb\"])\n        self.draw()\n    def plot_peaks(self):\n        self.delete()\n        self.ax.plot(g.exp_ir[:,0],g.exp_ir[:,1],color=\"black\")\n        self.ax.set_ylim(0,1.05)\n        self.ax.set_xlim(g.values[\"lb\"],g.values[\"hb\"])\n        self.ax.plot(g.peak_list_x,g.peak_list_y,\"o\",color=\"blue\")\n        self.draw()\n    def plot_peaks_VCD(self):\n        self.delete()\n        self.ax.plot(g.exp_vcd[:,0],g.exp_vcd[:,1],\"--\",color=\"black\")\n        self.ax.plot(g.peak_list_x,g.peak_list_VCD_y,\"o\",color=\"blue\")\n        self.ax.set_ylim(-1.05,1.05)\n        self.ax.set_xlim(g.values[\"lb\"],g.values[\"hb\"])\n        self.draw()\n    def delete(self):\n        try:\n            while(len(self.ax.lines)>0):\n                self.ax.lines[-1].remove()\n        except:\n            pass\n    def plot_VCD(self):\n        self.delete()\n        self.ax.plot(g.exp_vcd[:,0],g.exp_vcd[:,1],\"--\",color=\"black\")\n        self.ax.set_ylim(-1,1)\n        self.ax.set_xlim(g.values[\"lb\"],g.values[\"hb\"])\n        self.draw()\n    def plot_IR_theo(self):\n        self.delete()\n        self.ax.plot(g.spectrum_boltzmann[:,0],g.spectrum_boltzmann[:,1],color=\"red\") ##x_axis 0..2000\n        self.ax.set_ylim(0,1)\n        self.ax.set_xlim(g.values[\"lb\"],g.values[\"hb\"])\n        tmp_ir = g.spectrum_boltzmann[g.values[\"lb\"]:g.values[\"hb\"]]\n        g.theo_peaks_x = []\n        g.theo_peaks_y = []\n        for i in range(1,len(tmp_ir)-1):\n            if(tmp_ir[i-1,1]<=tmp_ir[i,1]>=tmp_ir[i+1,1]):\n                g.theo_peaks_x.append(tmp_ir[i,0])\n                g.theo_peaks_y.append(tmp_ir[i,1])\n        self.ax.plot(g.theo_peaks_x,g.theo_peaks_y,\"o\",color=\"blue\")\n        g.theo_peaks = np.zeros((len(g.theo_peaks_x),2))\n        g.theo_peaks[:,0] = np.asarray(g.theo_peaks_x)\n        g.theo_peaks[:,1] = np.asarray(g.theo_peaks_y)\n        self.draw()\n    def plot_IR_assigned(self):\n        self.delete()\n        #g.returnvalue, g.old_freq, g.freq, g.inten\n        self.ax.plot(g.spectrum_boltzmann[:,0],g.spectrum_boltzmann[:,1],color=\"red\") ##x_axis 0..2000\n        self.ax.plot(g.exp_ir[:,0],g.exp_ir[:,1],color=\"black\")\n        if(g.set_VCD==True):\n            self.ax.plot(g.exp_vcd[:,0],g.exp_vcd[:,1],\"--\",color=\"black\")\n            self.ax.plot(g.spectrum_boltzmann_vcd[:,0],g.spectrum_boltzmann_vcd[:,1],\"--\",color=\"red\")\n        for i in range(len(g.old_freq)):\n            self.ax.plot([g.old_freq[i],g.freq_new[i]],[g.inten_new[i],g.inten_new[i]],color=\"blue\")\n        self.ax.set_ylim(-1,1)\n        self.ax.set_xlim(g.values[\"lb\"],g.values[\"hb\"])\n        tmp_ir = g.spectrum_boltzmann[g.values[\"lb\"]:g.values[\"hb\"]]\n\n        self.draw()\n    def plot_VCD_theo(self):\n        self.delete()\n        self.ax.plot(g.spectrum_boltzmann_vcd[:,0],g.spectrum_boltzmann_vcd[:,1],\"--\",color=\"red\") ##x_axis 0..2000\n        tmp_vcd = g.spectrum_boltzmann_vcd[g.values[\"lb\"]:g.values[\"hb\"]]\n        self.ax.set_ylim(-1,1)\n        g.peak_list_VCD_y_theo = []\n        for peak in g.theo_peaks_x:\n            g.peak_list_VCD_y_theo.append(tmp_vcd[np.abs(tmp_vcd[:,0]-peak)<10e-3,1][0])\n        self.ax.plot(g.theo_peaks_x,g.peak_list_VCD_y_theo,\"o\",color=\"blue\")\n        self.ax.set_xlim(g.values[\"lb\"],g.values[\"hb\"])\n        self.draw()\nif __name__ == \"__main__\":\n    import sys\n    app = QtWidgets.QApplication(sys.argv)\n    MainWindow = QtWidgets.QMainWindow()\n    ui = gui.Ui_MainWindow()\n    ui.setupUi(MainWindow)\n    g.Spectrum = Spectrum.Spectrum()\n    g.canvas_list = []\n    g.canvas_list.append(Canvas(parent = ui.exp_ir_graph))\n    g.canvas_list.append(Canvas(parent = ui.exp_vcd_graph))\n    g.canvas_list.append(Canvas(parent = ui.theo_ir_graph))\n    g.canvas_list.append(Canvas(parent = ui.theo_vcd_graph))\n    g.canvas_list.append(Canvas(parent = ui.assignment_graph))\n    g.canvas_list.append(Canvas(parent = ui.shifted_graph))\n    g.list_buttons = []\n    g.list_buttons.append(Button(ui.w,\"w\"))\n    g.list_buttons.append(Button(ui.lb,\"lb\"))\n    g.list_buttons.append(Button(ui.hb,\"hb\"))\n    g.list_buttons.append(Button(ui.sigma_1,\"s0\"))\n    g.list_buttons.append(Button(ui.sigma_2,\"s1\"))\n    g.list_buttons.append(Button(ui.mu,\"mu\"))\n    g.list_buttons.append(Button(ui.cutoff,\"c\"))\n    g.list_buttons.append(Button(ui.temperature,\"T\"))\n\n    g.list_buttons.append(Load_Button(ui.Load_EXP,\"experimental IR\"))\n    g.list_buttons.append(Load_Button(ui.Load_EXP_VCD,\"experimental VCD\"))\n    g.list_buttons.append(Load_Button(ui.load_theo_exp,\"theoretical IR\"))\n    g.list_buttons.append(Load_Button(ui.load_theo_vcd,\"theoretical VCD\"))\n    g.list_buttons.append(Load_Button(ui.load_theo_exp_2,\"energies\"))\n    #g.list_buttons.append(Load_Button(ui.load_theo_vcd,\"theoretical VCD\"))\n\n\n    g.list_buttons.append(Click_Button(ui.normalize_1,\"normalize_1\"))\n    g.list_buttons.append(Click_Button(ui.normalize_2,\"normalize_2\"))\n    g.list_buttons.append(Click_Button(ui.automatic,\"automatic\"))\n    g.list_buttons.append(Click_Button(ui.align,\"align\",args = ui.results))\n\n    MainWindow.show()\n    sys.exit(app.exec_())\n", "meta": {"hexsha": "468441901994e3205b9c3479d30d445579b1fa9c", "size": 12842, "ext": "py", "lang": "Python", "max_stars_repo_path": "GUI/Gui.py", "max_stars_repo_name": "Lennard94/IRSA", "max_stars_repo_head_hexsha": "67dc6162f993de99289606740ed6b5d7402df0c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GUI/Gui.py", "max_issues_repo_name": "Lennard94/IRSA", "max_issues_repo_head_hexsha": "67dc6162f993de99289606740ed6b5d7402df0c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GUI/Gui.py", "max_forks_repo_name": "Lennard94/IRSA", "max_forks_repo_head_hexsha": "67dc6162f993de99289606740ed6b5d7402df0c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.6802721088, "max_line_length": 133, "alphanum_fraction": 0.5692259773, "include": true, "reason": "import numpy", "num_tokens": 3359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.19726666684034663}}
{"text": "\"\"\"\nMolecule generation and representation for generating theoretical spectre\n\"\"\"\nimport json\nimport os\nfrom bisect import (\n    bisect_left,\n    bisect_right,\n)\nfrom typing import (\n    List,\n    Optional,\n)\n\nimport IsoSpecPy as iso\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport typer  # pylint: disable=C0411\nfrom molmass import Formula\nfrom scipy.interpolate import interp1d\nfrom scipy.spatial import (\n    ckdtree,\n    distance,\n)\n\nfrom msaris.utils.distributions_util import generate_gauss_distribution\nfrom msaris.utils.intensities_util import (\n    get_spectrum_by_close_values,\n    norm,\n)\nfrom msaris.utils.molecule_utils import convert_into_formula_for_plot\n\n\nclass Molecule:  # pylint: disable=R0902\n    \"\"\"\n    Molecule generation and saving for performing molecule search\n    \"\"\"\n\n    def __init__(self, *, formula: str = \"\", delta: float = 0.5):\n        self.formula = formula  # saving for using to refer\n        self.brutto = self._get_brutto() if formula else None\n        self.mass_out: List = []\n        self.intens_out: List = []\n        self.mz: np.array = np.array([])\n        self.it: np.array = np.array([])\n        self.bar_raw = np.array([])\n        self.averaged_mass: float = 0.0\n        self.delta: float = delta\n\n    def _get_brutto(self) -> str:\n        \"\"\"\n        Generating brutto formula from provided one\n\n        :returns: brutto formula\n        \"\"\"\n        f = Formula(self.formula)\n        return \"\".join(map(lambda x: f\"{x[0]}{x[1]}\", f.composition()))\n\n    def _get_bar_isotope(self):\n        \"\"\"\n        Generating raw bar isotope pattern\n        :return:\n        \"\"\"\n        non_zero = np.argwhere(np.array(self.intens_out) > 0)\n        self.bar_raw = self.intens_out.copy()\n        for ind in non_zero:\n            left = bisect_left(self.mass_out, self.mass_out[ind] - self.delta)\n            right = bisect_right(\n                self.mass_out, self.mass_out[ind] + self.delta\n            )\n            self.bar_raw[left:right] = self.intens_out[ind]\n\n    def calculate(\n        self, *, resolution: int = 20, ppm: int = 50, scale: bool = False\n    ) -> None:\n        \"\"\"\n\n        :param resolution: generating m/z and intensities for provided formula\n        :return: None\n        \"\"\"\n        scaling: np.array\n\n        try:\n            sp = iso.IsoTotalProb(formula=self.brutto, prob_to_cover=0.99999)\n        except ValueError:\n            raise ValueError(f\"Invalid {self.formula}\")\n\n        for mass, prob in sp:\n            prob *= 100.0\n            self.mass_out += [mass]\n            self.intens_out += [prob]\n\n        self.mz, self.it, self.averaged_mass = generate_gauss_distribution(\n            self.mass_out, self.intens_out, ppm=ppm, resolution=resolution\n        )\n\n        if scale:\n            scaling = 100 / max(self.it)\n        else:\n            scaling = max(self.intens_out) / max(self.it)\n        # scaling resulting curve\n        self.it = self.it * scaling\n\n    def plot(\n        self,\n        *,\n        save: bool = False,\n        path: str = \"./\",\n        name: Optional[str] = None,\n    ) -> None:\n        \"\"\"\n        Plot spectra\n\n        :param save: bool value to save image of spectra\n        :param path: path to save image\n        :param name: name format\n\n        :return: None\n        \"\"\"\n        # TODO: change to be more flexible for output params\n        plt.rcParams[\"figure.figsize\"] = (30, 30)\n        # plot settings\n        fig, (ax_spiketrain, ax_filtered) = plt.subplots(2, 1, sharex=True)\n        ax_spiketrain.tick_params(axis=\"x\", labelbottom=True, rotation=-90)\n        ax_spiketrain.tick_params(axis=\"both\")\n        # tick parameters\n        plt.xticks(\n            np.arange(\n                int(min(self.mass_out)) - 1, int(max(self.mass_out)) + 2, 1.0\n            ),\n            rotation=-90,\n        )\n        markerline, stemlines, baseline = ax_spiketrain.stem(\n            self.mass_out,\n            self.intens_out,\n            use_line_collection=\"True\",\n            linefmt=\"grey\",\n            markerfmt=\"D\",\n            basefmt=\"k-\",\n            bottom=0,\n        )\n        markerline.set_markerfacecolor(\"none\")\n        plt.setp(stemlines, \"linewidth\", 0.9)\n        plt.setp(markerline, \"linewidth\", 0.8)\n        plt.setp(baseline, \"linewidth\", 0.9)\n        ax_spiketrain.set_title(\"Original spike train from IsoSpec data\")\n        ax_spiketrain.set_ylabel(\"Relative intensity, %\")\n        ax_spiketrain.set_xlabel(\"Mass, Da\")\n\n        ax_filtered.plot(self.mz, self.it, color=\"blue\", lw=1.2)\n        # axes labels\n        ax_filtered.set_title(\"Gaussian-filtered predicted spectra\")\n        ax_filtered.set_ylabel(\"Relative intensity, %\")\n        ax_filtered.set_xlabel(\"Mass, Da\")\n        plt.rcParams.update({\"font.size\": 30})\n\n        if save:\n            name = f\"{path}{name}.png\" if name else f\"{path}{self.formula}.png\"\n            fig.savefig(name, dpi=300, format=\"png\", bbox_inches=\"tight\")\n\n        plt.show()\n        plt.close()\n\n    def to_dict(self) -> dict:\n        \"\"\"\n        Present result in dict format\n        :return: dictionary of the main parameters\n        \"\"\"\n        return {\n            \"formula\": self.formula,\n            \"brutto\": self.brutto,\n            \"mz\": self.mz.tolist(),\n            \"it\": self.it.tolist(),\n            \"mass_out\": self.mass_out,\n            \"intens_out\": self.intens_out,\n            \"averaged_mass\": self.averaged_mass,\n        }\n\n    def to_json(self, path: str = \"./\", name: Optional[str] = None) -> None:\n        \"\"\"\n        Saves the molecule's to json\n\n        :param path: string default save to place where executed\n        :param name: redifine name default is formula with .mol format\n        :return: None\n        \"\"\"\n\n        if not os.path.isdir(path):\n            os.makedirs(path)\n\n        name = f\"{self.formula}.json\" if name is None else f\"{name}.json\"\n        if not path.endswith(\"/\"):\n            path = f\"{path}/\"\n\n        with open(f\"{path}{name}\", \"w\") as outfile:\n            json.dump(self.to_dict(), outfile)\n\n        typer.echo(f\"✨ JSON with was created: {os.path.abspath(path)}{name} ✨\")\n\n    def read_dict_data(self, data: dict) -> None:\n        \"\"\"\n        Gets Molecule from dictionary representation of molecule\n\n        :param data: data in dictionary format\n        :return: None\n        \"\"\"\n        for field, value in data.items():\n            if field in (\"mz\", \"it\"):\n                value = np.array(value)\n            setattr(self, field, value)\n\n    def load(self, file_path: str) -> None:\n        \"\"\"\n        Load file in JSON format\n\n        :param: Path to load data\n        :return: None\n        \"\"\"\n        with open(file_path, \"r\") as file:\n            self.read_dict_data(json.load(file))\n\n    def __str__(self) -> str:\n        return self.formula\n\n    def __repr__(self) -> str:\n        return (\n            f\"<Molecule(formula={self.formula},\"\n            f\" weighted_mass={self.averaged_mass})>\"\n        )\n\n    def compare(self, experimental: tuple) -> dict:\n\n        \"\"\"\n        Function to perform calculations for the theoretical and experimental spectrum\n        Based on interpolation selected peaks are recalculated to the same mz_t value\n\n        :param experimental: m/z and it of experimantal data\n\n        :return: calculated metrics for the selected spectras\n        \"\"\"\n        metrics: dict = {}\n        mz_t, it_t = self.mz.copy(), self.it.copy()\n        mz_e, it_e = experimental\n        it_t = norm(it_t)\n        it_e = norm(it_e)\n\n        interpol_t = interp1d(\n            mz_t, norm(it_t), bounds_error=False, fill_value=(0, 0)\n        )\n        interpol_e = interp1d(\n            mz_e, norm(it_e), bounds_error=False, fill_value=(0, 0)\n        )\n        theory = interpol_t(mz_e) * 100\n        exp = interpol_e(mz_e) * 100\n\n        metrics[\"cosine\"] = distance.cosine(theory, exp)\n        # TODO: improve and add other statistics calculations\n        return metrics\n\n\ndef plot_graph_for_comparing_molecules(\n    mz: np.array,\n    it: np.array,\n    formula: str,\n    *,\n    save: bool = False,\n    path: str = \"./\",\n    step: float = 0.5,\n    font: int = 18,\n):\n    \"\"\"\n    Provides plot with comparing stats with original spectrum\n    :param mz:  original spectrum m/z values\n    :param it: original spectrum intensity\n    :param formula: formula to find in original spectrum\n    :param save: save plot into provided path\n    :param path: path to save plot\n    :param step: parameter to tweak width of the spectrum\n    \"\"\"\n    mol = Molecule(formula=formula)\n    mol.calculate()\n    mz, it = mz.copy(), it.copy()\n    bar_mz: List = list()\n    bar_it: List = list()\n    visited: List = list()\n\n    mz_f, it_f, _, _ = get_spectrum_by_close_values(\n        mz, it, mol.mz[0], mol.mz[-1]\n    )\n    mpl.rcParams[\"xtick.labelsize\"] = font\n    mpl.rcParams[\"ytick.labelsize\"] = font\n    max_it_x_ind, max_it_t_ind = np.argmax(it_f), np.argmax(mol.it)\n    m_x, it_max_x, m_t, _ = (\n        mz_f[max_it_x_ind],\n        it_f[max_it_x_ind],\n        mol.mz[max_it_t_ind],\n        mol.it[max_it_t_ind],\n    )\n    tree = ckdtree.cKDTree(np.array([mol.mz, mol.mz]).T)\n    for _, val in enumerate(mol.mass_out):\n        inds = tree.query_ball_point((val, val), step)\n        S1, S2 = set(inds), set(visited)\n        if S1.intersection(S2):\n            continue\n        visited.extend(inds)\n        bar_mz.append(np.mean(mol.mz[inds]))\n        bar_it.append(np.mean(mol.it[inds]))\n\n    delta_b = m_x - m_t\n    spectrum = (\n        mz_f,\n        it_f,\n    )\n    stats = {\n        \"delta\": abs(delta_b),\n        \"metrics\": mol.compare(spectrum),\n        \"relative\": max(it_f) / max(it),\n    }\n    _, ax = plt.subplots(1, 1, figsize=(15, 5))\n    ax.bar(\n        bar_mz,\n        (bar_it / max(bar_it)) * 100,\n        width=step,\n        align=\"center\",\n        alpha=1,\n        color=\"r\",\n    )\n    ax.plot(\n        spectrum[0],\n        (spectrum[1] / it_max_x) * 100,\n        color=\"black\",\n    )\n    plotted_formula = convert_into_formula_for_plot(formula)\n    ax.set_xlabel(\"M/Z\", fontsize=20)\n    ax.set_ylabel(\"Intensity\", fontsize=20)\n    labels = [\n        plotted_formula,\n        f\"Delta m/z: {stats['delta']:.3f}\",\n        f\"Cosine: {stats['metrics']['cosine']:.3f}\",\n        f\"Relative: {stats['relative']:.3f}\",\n    ]\n    ax.text(\n        0.8,\n        0.8,\n        \"\\n\".join(labels),\n        color=\"black\",\n        horizontalalignment=\"center\",\n        verticalalignment=\"center\",\n        fontsize=font,\n        transform=ax.transAxes,\n    )\n    ax.set_title(f\"{plotted_formula}\", fontsize=20)\n    if save and path:\n        if not os.path.exists(path):\n            os.makedirs(path)\n        plt.savefig(f\"{path}/{formula}.png\", dpi=600)\n    plt.show()\n    plt.close()\n", "meta": {"hexsha": "4982733c04db4385d9649f5b6eeee34521ab5b90", "size": 10736, "ext": "py", "lang": "Python", "max_stars_repo_path": "msaris/molecule/molecule.py", "max_stars_repo_name": "Borschevik/msaris", "max_stars_repo_head_hexsha": "a12722441679d8246faa6028d31c3f2e51e58665", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "msaris/molecule/molecule.py", "max_issues_repo_name": "Borschevik/msaris", "max_issues_repo_head_hexsha": "a12722441679d8246faa6028d31c3f2e51e58665", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "msaris/molecule/molecule.py", "max_forks_repo_name": "Borschevik/msaris", "max_forks_repo_head_hexsha": "a12722441679d8246faa6028d31c3f2e51e58665", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8222222222, "max_line_length": 86, "alphanum_fraction": 0.5751676602, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.19726666684034658}}
{"text": "\"\"\"\n.. module:: adaptive_sampling\n   :synopsis: Ways of finding the next point to evaluate in the adaptive phase\n\n.. moduleauthor:: David Eriksson <dme65@cornell.edu>,\n                David Bindel <bindel@cornell.edu>\n\n:Module: adaptive_sampling\n:Author: David Eriksson <dme65@cornell.edu>,\n        David Bindel <bindel@cornell.edu>\n\n\"\"\"\n\nimport math\nimport scipy.stats as stats\nfrom merit_functions import *\nimport types\n\n\ndef __fix_docs(cls):\n    \"\"\"Help function for stealing docs from the parent\"\"\"\n    for name, func in vars(cls).items():\n        if isinstance(func, types.FunctionType) and not func.__doc__:\n            for parent in cls.__bases__:\n                parfunc = getattr(parent, name, None)\n                if parfunc and getattr(parfunc, '__doc__', None):\n                    func.__doc__ = parfunc.__doc__\n                    break\n    return cls\n\n\n\nclass CandidateSRBF(object):\n    \"\"\"An implementation of Stochastic RBF\n\n    This is an implementation of the candidate points method that is\n    proposed in the first SRBF paper. Candidate points are generated\n    by making normally distributed perturbations with standard\n    deviation sigma around the best solution. The candidate point that\n    minimizes a specified merit function is selected as the next\n    point to evaluate.\n\n    :param data: Optimization problem object\n    :type data: Object\n    :param numcand: Number of candidate points to be used. Default is min([5000, 100*data.dim])\n    :type numcand: int\n    :param weights: Weights used for the merit function, to balance exploration vs exploitation\n    :type weights: list of numpy.array\n\n    :raise ValueError: If number of candidate points is\n        incorrect or if the weights aren't a list in [0, 1]\n\n    :ivar data: Optimization problem object\n    :ivar fhat: Response surface object\n    :ivar xrange: Variable ranges, xup - xlow\n    :ivar dtol: Smallest allowed distance between evaluated points 1e-3 * sqrt(dim)\n    :ivar weights: Weights used for the merit function\n    :ivar proposed_points: List of points proposed to the optimization algorithm\n    :ivar dmerit: Minimum distance between the points and the proposed points\n    :ivar xcand: Candidate points\n    :ivar fhvals: Predicted values by the surrogate model\n    :ivar next_weight: Index of the next weight to be used\n    :ivar numcand: Number of candidate points\n    :ivar budget: Remaining evaluation budget\n\n    .. note:: This object needs to be initialized with the init method. This is done when the\n        initial phase has finished.\n\n    .. todo:: Get rid of the proposed_points object and replace it by something that is\n        controlled by the strategy.\n    \"\"\"\n\n    def __init__(self, data, numcand=None, weights=None):\n        self.data = data\n        self.fhat = None\n        self.xrange = self.data.xup - self.data.xlow\n        self.dtol = 1e-3 * math.sqrt(data.dim)\n        self.weights = weights\n        if self.weights is None:\n            self.weights = [0.3, 0.5, 0.8, 0.95]\n        self.proposed_points = None\n        self.dmerit = None\n        self.xcand = None\n        self.fhvals = None\n        self.next_weight = 0\n        self.numcand = numcand\n        if self.numcand is None:\n            self.numcand = min([5000, 100*data.dim])\n        self.budget = None\n\n        # Check that the inputs make sense\n        if not(isinstance(self.numcand, int) and self.numcand > 0):\n            raise ValueError(\"The number of candidate points has to be a positive integer\")\n        if not((isinstance(self.weights, np.ndarray) or isinstance(self.weights, list))\n               and max(self.weights) <= 1 and min(self.weights) >= 0):\n            raise ValueError(\"Incorrect weights\")\n\n    def init(self, start_sample, fhat, budget):\n        \"\"\"Initialize the sampling method after the initial phase\n\n        This initializes the list of sampling methods after the initial phase\n        has finished and the experimental design has been evaluated. The user\n        provides the points in the experimental design, the surrogate model,\n        and the remaining evaluation budget.\n\n        :param start_sample: Points in the experimental design\n        :type start_sample: numpy.array\n        :param fhat: Surrogate model\n        :type fhat: Object\n        :param budget: Evaluation budget\n        :type budget: int\n        \"\"\"\n\n        self.proposed_points = start_sample\n        self.budget = budget\n        self.fhat = fhat\n\n    def remove_point(self, x):\n        \"\"\"Remove x from proposed_points\n\n        This removes x from the list of proposed points in the case where the optimization\n        strategy decides to not evaluate x.\n\n        :param x: Point to be removed\n        :type x: numpy.array\n        :return: True if points was removed, False otherwise\n        :type: bool\n        \"\"\"\n\n        idx = np.sum(np.abs(self.proposed_points - x), axis=1).argmin()\n        if np.sum(np.abs(self.proposed_points[idx, :] - x)) < 1e-10:\n            self.proposed_points = np.delete(self.proposed_points, idx, axis=0)\n            return True\n        return False\n\n    def __generate_cand__(self, scalefactors, xbest, subset):\n        self.xcand = np.ones((self.numcand,  self.data.dim)) * xbest\n        for i in subset:\n            lower, upper = self.data.xlow[i], self.data.xup[i]\n            ssigma = scalefactors[i]\n            self.xcand[:, i] = stats.truncnorm.rvs(\n                (lower - xbest[i]) / ssigma, (upper - xbest[i]) / ssigma,\n                loc=xbest[i], scale=ssigma, size=self.numcand)\n\n    def make_points(self, npts, xbest, sigma, subset=None, proj_fun=None,\n                    merit=candidate_merit_weighted_distance):\n        \"\"\"Proposes npts new points to evaluate\n\n        :param npts: Number of points to select\n        :type npts: int\n        :param xbest: Best solution found so far\n        :type xbest: numpy.array\n        :param sigma: Current sampling radius w.r.t the unit box\n        :type sigma: float\n        :param subset: Coordinates to perturb, the others are fixed\n        :type subset: numpy.array\n        :param proj_fun: Routine for projecting infeasible points onto the feasible region\n        :type proj_fun: Object\n        :param merit: Merit function for selecting candidate points\n        :type merit: Object\n\n        :return: Points selected for evaluation, of size npts x dim\n        :rtype: numpy.array\n\n        .. todo:: Change the merit function from being hard-coded\n        \"\"\"\n\n        if subset is None:\n            subset = np.arange(0, self.data.dim)\n        scalefactors = sigma * self.xrange\n\n        # Make sure that the scale factors are correct for\n        # the integer variables (at least 1)\n        ind = np.intersect1d(self.data.integer, subset)\n        if len(ind) > 0:\n            scalefactors[ind] = np.maximum(scalefactors[ind], 1.0)\n\n        # Generate candidate points\n        self.__generate_cand__(scalefactors, xbest, subset)\n        if proj_fun is not None:\n            self.xcand = proj_fun(self.xcand)\n\n        dists = scp.distance.cdist(self.xcand, self.proposed_points)\n        fhvals = self.fhat.evals(self.xcand)\n\n        self.dmerit = np.amin(np.asmatrix(dists), axis=1)\n        self.fhvals = unit_rescale(fhvals)\n\n        xnew = merit(self, npts)\n        self.proposed_points = np.vstack((self.proposed_points,\n                                          np.asmatrix(xnew)))\n        return xnew\n\n\n@__fix_docs\nclass CandidateDYCORS(CandidateSRBF):\n    \"\"\"An implementation of the DYCORS method\n\n    The DYCORS method only perturbs a subset of the dimensions when\n    perturbing the best solution. The probability for a dimension\n    to be perturbed decreases after each evaluation and is capped\n    in order to guarantee global convergence.\n\n    :param data: Optimization problem object\n    :type data: Object\n    :param numcand: Number of candidate points to be used. Default is min([5000, 100*data.dim])\n    :type numcand: int\n    :param weights: Weights used for the merit function, to balance exploration vs exploitation\n    :type weights: list of numpy.array\n\n    :raise ValueError: If number of candidate points is\n        incorrect or if the weights aren't a list in [0, 1]\n\n    :ivar data: Optimization problem object\n    :ivar fhat: Response surface object\n    :ivar xrange: Variable ranges, xup - xlow\n    :ivar dtol: Smallest allowed distance between evaluated points 1e-3 * sqrt(dim)\n    :ivar weights: Weights used for the merit function\n    :ivar proposed_points: List of points proposed to the optimization algorithm\n    :ivar dmerit: Minimum distance between the points and the proposed points\n    :ivar xcand: Candidate points\n    :ivar fhvals: Predicted values by the surrogate model\n    :ivar next_weight: Index of the next weight to be used\n    :ivar numcand: Number of candidate points\n    :ivar budget: Remaining evaluation budget\n    :ivar minprob: Smallest allowed perturbation probability\n    :ivar n0: Evaluations spent when the initial phase ended\n    :ivar probfun: Function that computes the perturbation probability of a given iteration\n\n    .. note:: This object needs to be initialized with the init method. This is done when the\n        initial phase has finished.\n\n    .. todo:: Get rid of the proposed_points object and replace it by something that is\n        controlled by the strategy.\n    \"\"\"\n\n    def __init__(self, data, numcand=None, weights=None):\n        CandidateSRBF.__init__(self, data, numcand=numcand, weights=weights)\n        self.minprob = np.min([1.0, 1.0/self.data.dim])\n        self.n0 = None\n\n        if data.dim <= 1:\n            raise ValueError(\"You can't use DYCORS on a 1d problem\")\n\n        def probfun(numevals, budget):\n            if budget < 2:\n                return 0\n            return min([20.0/data.dim, 1.0]) * (1.0 - (np.log(numevals + 1.0) / np.log(budget)))\n        self.probfun = probfun\n\n    def init(self, start_sample, fhat, budget):\n        CandidateSRBF.init(self, start_sample, fhat, budget)\n        self.n0 = start_sample.shape[0]\n\n    def remove_point(self, x):\n        return CandidateSRBF.remove_point(self, x)\n\n    def make_points(self, npts, xbest, sigma, subset=None, proj_fun=None,\n                    merit=candidate_merit_weighted_distance):\n        return CandidateSRBF.make_points(self, npts, xbest, sigma, subset, proj_fun, merit)\n\n    def __generate_cand__(self, scalefactors, xbest, subset):\n        ddsprob = self.probfun(self.proposed_points.shape[0] - self.n0, self.budget - self.n0)\n        ddsprob = np.max([self.minprob, ddsprob])\n\n        nlen = len(subset)\n\n        # Fix when nlen is 1\n        # Todo: Use SRBF instead\n        if nlen == 1:\n            ar = np.ones((self.numcand, 1))\n        else:\n            ar = (np.random.rand(self.numcand, nlen) < ddsprob)\n            ind = np.where(np.sum(ar, axis=1) == 0)[0]\n            ar[ind, np.random.randint(0, nlen - 1, size=len(ind))] = 1\n\n        self.xcand = np.ones((self.numcand, self.data.dim)) * xbest\n        for i in range(nlen):\n            lower, upper = self.data.xlow[i], self.data.xup[i]\n            ssigma = scalefactors[subset[i]]\n            ind = np.where(ar[:, i] == 1)[0]\n            self.xcand[ind, subset[i]] = stats.truncnorm.rvs(\n                (lower - xbest[subset[i]]) / ssigma, (upper - xbest[subset[i]]) / ssigma,\n                loc=xbest[subset[i]], scale=ssigma, size=len(ind))\n\n", "meta": {"hexsha": "a9a34c1b1a0ba106d501c0f6c3a0113ad0adce30", "size": 11369, "ext": "py", "lang": "Python", "max_stars_repo_path": "dyno_pods/adaptive_sampling.py", "max_stars_repo_name": "louisXW/PODS-DYNO", "max_stars_repo_head_hexsha": "5cd3cced8f0556a5c42d9021ff1d965880f360dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dyno_pods/adaptive_sampling.py", "max_issues_repo_name": "louisXW/PODS-DYNO", "max_issues_repo_head_hexsha": "5cd3cced8f0556a5c42d9021ff1d965880f360dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-24T18:17:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T18:17:50.000Z", "max_forks_repo_path": "dyno_pods/adaptive_sampling.py", "max_forks_repo_name": "louisXW/PODS-DYNO", "max_forks_repo_head_hexsha": "5cd3cced8f0556a5c42d9021ff1d965880f360dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-01T12:57:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T12:57:30.000Z", "avg_line_length": 39.7517482517, "max_line_length": 96, "alphanum_fraction": 0.6511566541, "include": true, "reason": "import scipy", "num_tokens": 2797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604272, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.19726666684034655}}
{"text": "#  MINLP written by GAMS Convert at 08/13/20 17:38:08\n#  \n#  Equation counts\n#      Total        E        G        L        N        X        C        B\n#         53       18        0       35        0        0        0        0\n#  \n#  Variable counts\n#                   x        b        i      s1s      s2s       sc       si\n#      Total     cont   binary  integer     sos1     sos2    scont     sint\n#         96       21       75        0        0        0        0        0\n#  FX      0        0        0        0        0        0        0        0\n#  \n#  Nonzero counts\n#      Total    const       NL      DLL\n#        306      261       45        0\n# \n#  Reformulation has removed 1 variable and 1 equation\n\n\nfrom pyomo.environ import *\n\nmodel = m = ConcreteModel()\n\n\nm.b1 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b2 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b3 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b4 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b5 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b6 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b7 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b8 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b9 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b10 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b11 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b12 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b13 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b14 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b15 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b16 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b17 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b18 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b19 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b20 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b21 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b22 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b23 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b24 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b25 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b26 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b27 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b28 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b29 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b30 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b31 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b32 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b33 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b34 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b35 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b36 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b37 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b38 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b39 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b40 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b41 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b42 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b43 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b44 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b45 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b46 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b47 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b48 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b49 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b50 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b51 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b52 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b53 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b54 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b55 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b56 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b57 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b58 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b59 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b60 = Var(within=Binary,bounds=(0,1),initialize=0.2)\nm.b61 = Var(within=Binary,bounds=(0,1),initialize=0.333333333333333)\nm.b62 = Var(within=Binary,bounds=(0,1),initialize=0.333333333333333)\nm.b63 = Var(within=Binary,bounds=(0,1),initialize=0.333333333333333)\nm.b64 = Var(within=Binary,bounds=(0,1),initialize=0.333333333333333)\nm.b65 = Var(within=Binary,bounds=(0,1),initialize=0.333333333333333)\nm.b66 = Var(within=Binary,bounds=(0,1),initialize=0.333333333333333)\nm.b67 = Var(within=Binary,bounds=(0,1),initialize=0.333333333333333)\nm.b68 = Var(within=Binary,bounds=(0,1),initialize=0.333333333333333)\nm.b69 = Var(within=Binary,bounds=(0,1),initialize=0.333333333333333)\nm.b70 = Var(within=Binary,bounds=(0,1),initialize=0.333333333333333)\nm.b71 = Var(within=Binary,bounds=(0,1),initialize=0.333333333333333)\nm.b72 = Var(within=Binary,bounds=(0,1),initialize=0.333333333333333)\nm.b73 = Var(within=Binary,bounds=(0,1),initialize=0.333333333333333)\nm.b74 = Var(within=Binary,bounds=(0,1),initialize=0.333333333333333)\nm.b75 = Var(within=Binary,bounds=(0,1),initialize=0.333333333333333)\nm.x76 = Var(within=Reals,bounds=(0,None),initialize=1.18464727499703)\nm.x77 = Var(within=Reals,bounds=(0,None),initialize=2.21055142184158)\nm.x78 = Var(within=Reals,bounds=(0,None),initialize=1.19998063005095)\nm.x79 = Var(within=Reals,bounds=(0,None),initialize=1.11549458684761)\nm.x80 = Var(within=Reals,bounds=(0,None),initialize=1.13890807654545)\nm.x81 = Var(within=Reals,bounds=(0,None),initialize=0.18075340102651)\nm.x82 = Var(within=Reals,bounds=(0,None),initialize=0.18075340102651)\nm.x83 = Var(within=Reals,bounds=(0,None),initialize=0.18075340102651)\nm.x84 = Var(within=Reals,bounds=(0,None),initialize=0.229509008619004)\nm.x85 = Var(within=Reals,bounds=(0,None),initialize=0.229509008619004)\nm.x86 = Var(within=Reals,bounds=(0,None),initialize=0.229509008619004)\nm.x87 = Var(within=Reals,bounds=(0,None),initialize=0.181816847787907)\nm.x88 = Var(within=Reals,bounds=(0,None),initialize=0.181816847787907)\nm.x89 = Var(within=Reals,bounds=(0,None),initialize=0.181816847787907)\nm.x90 = Var(within=Reals,bounds=(0,None),initialize=0.175765767145396)\nm.x91 = Var(within=Reals,bounds=(0,None),initialize=0.175765767145396)\nm.x92 = Var(within=Reals,bounds=(0,None),initialize=0.175765767145396)\nm.x93 = Var(within=Reals,bounds=(0,None),initialize=0.177490575531558)\nm.x94 = Var(within=Reals,bounds=(0,None),initialize=0.177490575531558)\nm.x95 = Var(within=Reals,bounds=(0,None),initialize=0.177490575531558)\n\nm.obj = Objective(expr=   301.899928098152*m.b1 + 282.051473607022*m.b2 + 151.594044960674*m.b3 + 114.784185877557*m.b4\n                        + 213.364530716922*m.b5 + 772.653148294131*m.b6 + 697.676211791334*m.b7 + 146.306371684975*m.b8\n                        + 390.583393857486*m.b9 + 208.147527440482*m.b10 + 662.892902187869*m.b11\n                        + 577.461337631217*m.b12 + 221.10047354739*m.b13 + 425.919826737657*m.b14\n                        + 123.074770812851*m.b15 + 333.28129673946*m.b16 + 248.380746723092*m.b17\n                        + 249.162942146638*m.b18 + 164.598799150643*m.b19 + 280.957171099846*m.b20\n                        + 308.552481034871*m.b21 + 270.059605282374*m.b22 + 104.633483616243*m.b23\n                        + 79.6631898566695*m.b24 + 170.696237801571*m.b25 + 237.754076296143*m.b26\n                        + 189.862911729786*m.b27 + 107.217531395173*m.b28 + 131.358715293396*m.b29\n                        + 103.406777059692*m.b30 + 626.417763832299*m.b31 + 487.184730842973*m.b32\n                        + 502.300580630229*m.b33 + 506.426352475088*m.b34 + 463.185748318154*m.b35\n                        + 358.178221555384*m.b36 + 281.629247221142*m.b37 + 230.4203839171*m.b38\n                        + 251.915433121165*m.b39 + 209.261088879339*m.b40 + 303.899003044044*m.b41\n                        + 243.197489456663*m.b42 + 237.390965850675*m.b43 + 57.1385835039462*m.b44\n                        + 301.733744039334*m.b45 + 30.6123768510861*m.b46 + 21.3396948414106*m.b47\n                        + 278.520865043453*m.b48 + 162.122145724483*m.b49 + 304.508803157003*m.b50\n                        + 252.516206195527*m.b51 + 178.796029580139*m.b52 + 319.145634893211*m.b53\n                        + 257.755103285795*m.b54 + 317.996864520235*m.b55 + 936.171150833806*m.b56\n                        + 887.611963724196*m.b57 + 419.760722838682*m.b58 + 519.981401235063*m.b59\n                        + 524.621957902125*m.b60 + 326.37044675*m.b61 + 119.610927362864*m.b62 + 76.800859418795*m.b63\n                        + 338.15311375*m.b64 + 113.101546866718*m.b65 + 69.3762358590679*m.b66 + 313.6973235*m.b67\n                        + 116.266585440261*m.b68 + 75.0744657614982*m.b69 + 401.4402965*m.b70 + 138.599587312691*m.b71\n                        + 86.376825937843*m.b72 + 456.70672375*m.b73 + 150.554161322115*m.b74 + 91.6821859840903*m.b75\n                        + 93617.1150833806*m.x76 + 93617.1150833806*m.x77 + 93617.1150833806*m.x78\n                        + 93617.1150833806*m.x79 + 93617.1150833806*m.x80, sense=minimize)\n\nm.c2 = Constraint(expr=   0.609376132*m.b1 + 1.180016336*m.b6 + 0.967493052*m.b11 + 1.004918785*m.b16\n                        + 0.698898063*m.b21 + 0.540292599*m.b26 + 1.460452986*m.b31 + 0.811980791*m.b36\n                        + 0.973180988*m.b41 + 0.544914116*m.b46 + 0.78515855*m.b51 + 1.312281472*m.b56\n                        - 2.0080698912*m.x81 - 4.0161397824*m.x82 - 6.0242096736*m.x83 == 0)\n\nm.c3 = Constraint(expr=   0.609376132*m.b2 + 1.180016336*m.b7 + 0.967493052*m.b12 + 1.004918785*m.b17\n                        + 0.698898063*m.b22 + 0.540292599*m.b27 + 1.460452986*m.b32 + 0.811980791*m.b37\n                        + 0.973180988*m.b42 + 0.544914116*m.b47 + 0.78515855*m.b52 + 1.312281472*m.b57\n                        - 1.581486777*m.x84 - 3.162973554*m.x85 - 4.744460331*m.x86 == 0)\n\nm.c4 = Constraint(expr=   0.609376132*m.b3 + 1.180016336*m.b8 + 0.967493052*m.b13 + 1.004918785*m.b18\n                        + 0.698898063*m.b23 + 0.540292599*m.b28 + 1.460452986*m.b33 + 0.811980791*m.b38\n                        + 0.973180988*m.b43 + 0.544914116*m.b48 + 0.78515855*m.b53 + 1.312281472*m.b58\n                        - 1.9963246902*m.x87 - 3.9926493804*m.x88 - 5.9889740706*m.x89 == 0)\n\nm.c5 = Constraint(expr=   0.609376132*m.b4 + 1.180016336*m.b9 + 0.967493052*m.b14 + 1.004918785*m.b19\n                        + 0.698898063*m.b24 + 0.540292599*m.b29 + 1.460452986*m.b34 + 0.811980791*m.b39\n                        + 0.973180988*m.b44 + 0.544914116*m.b49 + 0.78515855*m.b54 + 1.312281472*m.b59\n                        - 2.065052076*m.x90 - 4.130104152*m.x91 - 6.195156228*m.x92 == 0)\n\nm.c6 = Constraint(expr=   0.609376132*m.b5 + 1.180016336*m.b10 + 0.967493052*m.b15 + 1.004918785*m.b20\n                        + 0.698898063*m.b25 + 0.540292599*m.b30 + 1.460452986*m.b35 + 0.811980791*m.b40\n                        + 0.973180988*m.b45 + 0.544914116*m.b50 + 0.78515855*m.b55 + 1.312281472*m.b60\n                        - 2.0449844238*m.x93 - 4.0899688476*m.x94 - 6.1349532714*m.x95 == 0)\n\nm.c7 = Constraint(expr=   m.b1 + m.b2 + m.b3 + m.b4 + m.b5 == 1)\n\nm.c8 = Constraint(expr=   m.b6 + m.b7 + m.b8 + m.b9 + m.b10 == 1)\n\nm.c9 = Constraint(expr=   m.b11 + m.b12 + m.b13 + m.b14 + m.b15 == 1)\n\nm.c10 = Constraint(expr=   m.b16 + m.b17 + m.b18 + m.b19 + m.b20 == 1)\n\nm.c11 = Constraint(expr=   m.b21 + m.b22 + m.b23 + m.b24 + m.b25 == 1)\n\nm.c12 = Constraint(expr=   m.b26 + m.b27 + m.b28 + m.b29 + m.b30 == 1)\n\nm.c13 = Constraint(expr=   m.b31 + m.b32 + m.b33 + m.b34 + m.b35 == 1)\n\nm.c14 = Constraint(expr=   m.b36 + m.b37 + m.b38 + m.b39 + m.b40 == 1)\n\nm.c15 = Constraint(expr=   m.b41 + m.b42 + m.b43 + m.b44 + m.b45 == 1)\n\nm.c16 = Constraint(expr=   m.b46 + m.b47 + m.b48 + m.b49 + m.b50 == 1)\n\nm.c17 = Constraint(expr=   m.b51 + m.b52 + m.b53 + m.b54 + m.b55 == 1)\n\nm.c18 = Constraint(expr=   m.b56 + m.b57 + m.b58 + m.b59 + m.b60 == 1)\n\nm.c19 = Constraint(expr=   m.b61 + m.b62 + m.b63 <= 1)\n\nm.c20 = Constraint(expr=   m.b64 + m.b65 + m.b66 <= 1)\n\nm.c21 = Constraint(expr=   m.b67 + m.b68 + m.b69 <= 1)\n\nm.c22 = Constraint(expr=   m.b70 + m.b71 + m.b72 <= 1)\n\nm.c23 = Constraint(expr=   m.b73 + m.b74 + m.b75 <= 1)\n\nm.c24 = Constraint(expr= - m.b61 + m.x81 <= 0)\n\nm.c25 = Constraint(expr= - m.b62 + m.x82 <= 0)\n\nm.c26 = Constraint(expr= - m.b63 + m.x83 <= 0)\n\nm.c27 = Constraint(expr= - m.b64 + m.x84 <= 0)\n\nm.c28 = Constraint(expr= - m.b65 + m.x85 <= 0)\n\nm.c29 = Constraint(expr= - m.b66 + m.x86 <= 0)\n\nm.c30 = Constraint(expr= - m.b67 + m.x87 <= 0)\n\nm.c31 = Constraint(expr= - m.b68 + m.x88 <= 0)\n\nm.c32 = Constraint(expr= - m.b69 + m.x89 <= 0)\n\nm.c33 = Constraint(expr= - m.b70 + m.x90 <= 0)\n\nm.c34 = Constraint(expr= - m.b71 + m.x91 <= 0)\n\nm.c35 = Constraint(expr= - m.b72 + m.x92 <= 0)\n\nm.c36 = Constraint(expr= - m.b73 + m.x93 <= 0)\n\nm.c37 = Constraint(expr= - m.b74 + m.x94 <= 0)\n\nm.c38 = Constraint(expr= - m.b75 + m.x95 <= 0)\n\nm.c39 = Constraint(expr=m.x81*m.b61 + m.x81*m.x76 - m.x76*m.b61 <= 0)\n\nm.c40 = Constraint(expr=m.x82*m.b62 + m.x82*m.x76 - m.x76*m.b62 <= 0)\n\nm.c41 = Constraint(expr=m.x83*m.b63 + m.x83*m.x76 - m.x76*m.b63 <= 0)\n\nm.c42 = Constraint(expr=m.x84*m.b64 + m.x84*m.x77 - m.x77*m.b64 <= 0)\n\nm.c43 = Constraint(expr=m.x85*m.b65 + m.x85*m.x77 - m.x77*m.b65 <= 0)\n\nm.c44 = Constraint(expr=m.x86*m.b66 + m.x86*m.x77 - m.x77*m.b66 <= 0)\n\nm.c45 = Constraint(expr=m.x87*m.b67 + m.x87*m.x78 - m.x78*m.b67 <= 0)\n\nm.c46 = Constraint(expr=m.x88*m.b68 + m.x88*m.x78 - m.x78*m.b68 <= 0)\n\nm.c47 = Constraint(expr=m.x89*m.b69 + m.x89*m.x78 - m.x78*m.b69 <= 0)\n\nm.c48 = Constraint(expr=m.x90*m.b70 + m.x90*m.x79 - m.x79*m.b70 <= 0)\n\nm.c49 = Constraint(expr=m.x91*m.b71 + m.x91*m.x79 - m.x79*m.b71 <= 0)\n\nm.c50 = Constraint(expr=m.x92*m.b72 + m.x92*m.x79 - m.x79*m.b72 <= 0)\n\nm.c51 = Constraint(expr=m.x93*m.b73 + m.x93*m.x80 - m.x80*m.b73 <= 0)\n\nm.c52 = Constraint(expr=m.x94*m.b74 + m.x94*m.x80 - m.x80*m.b74 <= 0)\n\nm.c53 = Constraint(expr=m.x95*m.b75 + m.x95*m.x80 - m.x80*m.b75 <= 0)\n", "meta": {"hexsha": "7cfac397480461d61e2ca617c98156c48290f6f4", "size": 14023, "ext": "py", "lang": "Python", "max_stars_repo_path": "models_nonconvex_simple/sssd12-05persp.py", "max_stars_repo_name": "grossmann-group/pyomo-MINLP-benchmarking", "max_stars_repo_head_hexsha": "714f0a0dffd61675649a805683c0627af6b4929e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-05-08T19:14:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T00:00:40.000Z", "max_issues_repo_path": "models_nonconvex_simple/sssd12-05persp.py", "max_issues_repo_name": "grossmann-group/pyomo-MINLP-benchmarking", "max_issues_repo_head_hexsha": "714f0a0dffd61675649a805683c0627af6b4929e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models_nonconvex_simple/sssd12-05persp.py", "max_forks_repo_name": "grossmann-group/pyomo-MINLP-benchmarking", "max_forks_repo_head_hexsha": "714f0a0dffd61675649a805683c0627af6b4929e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-05-10T18:34:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-10T18:34:18.000Z", "avg_line_length": 52.9169811321, "max_line_length": 119, "alphanum_fraction": 0.6283962062, "include": true, "reason": "from pyomo", "num_tokens": 5479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.19726232296342563}}
{"text": "\"\"\" Layout helper functions.\n\nAuthors: Thomas Ferreira de Lima @thomaslima\n         Lukas Chrostowski @lukasc-ubc\n\nThe following functions are useful for scripted layout, or making\nPDK Pcells.\n\nFunctions:\n\nlayout_waveguide2\nlayout_waveguide\nlayout_waveguide_sbend_bezier\nmake_pin\ny_splitter_tree\n\nTODO: enhance documentation\nTODO: make some of the functions in util use these.\n\"\"\"\n\nfrom itertools import repeat\nimport pya\nimport numpy as np\nfrom numpy import cos, sin, pi, sqrt\nfrom functools import reduce\nfrom .sampling import sample_function\nfrom .geometry import rotate90, rotate, bezier_optimal, curve_length\n\n'''\nCreate a waveguide, in a specific technology\ninputs\n- cell: into which Cell we add the waveguide\n- dpath: DPath type\n- waveguide_type: a name from Waveguides.XML\n    can be a <compound_waveguide>\n    or a primitive waveguide type containing <component> info\noutput\n- compound waveguide, or regular waveguide\nby Lukas Chrostowski\nacknowledgements: Diedrik Vermeulen for the code to place the taper in the correct orientation\n'''\ndef layout_waveguide4(cell, dpath, waveguide_type, debug=True):\n\n    \n    if debug:\n        print ('SiEPIC.utils.layout.layout_waveguide4: ' )\n        print (' - waveguide_type: %s' % (waveguide_type) )\n\n    # get the path and clean it up\n    layout = cell.layout()\n    dbu = layout.dbu\n    dpath = dpath.to_itype(dbu)\n    dpath.unique_points()\n    pts = dpath.get_points()\n    dpts = dpath.get_dpoints()\n\n    # Load the technology and all waveguide types\n    from SiEPIC.utils import load_Waveguides_by_Tech\n    technology_name = layout.technology_name\n    waveguide_types = load_Waveguides_by_Tech(technology_name)   \n    if debug:\n        print (' - technology_name: %s' % (technology_name) )\n        print (' - waveguide_types: %s' % (waveguide_types) )\n\n    # Load parameters for the chosen waveguide type\n    params = [t for t in waveguide_types if t['name'] == waveguide_type]\n    if type(params) == type([]) and len(params)>0:\n        params = params[0]\n    else:\n        print('error: waveguide type not found in PDK waveguides')\n        raise Exception('error: waveguide type (%s) not found in PDK waveguides' % waveguide_type)\n\n    # compound waveguide types:\n    if 'compound_waveguide' in params:\n        # find the singlemode and multimode waveguides:\n        if 'singlemode' in params['compound_waveguide']:\n            singlemode = params['compound_waveguide']['singlemode']\n        else:\n            raise Exception('error: waveguide type (%s) does not have singlemode defined' % waveguide_type)\n        if 'multimode' in params['compound_waveguide']:\n            multimode = params['compound_waveguide']['multimode']\n        else:\n            raise Exception('error: waveguide type (%s) does not have multimode defined' % waveguide_type)\n        params_singlemode = [t for t in waveguide_types if t['name'] == singlemode]\n        params_multimode = [t for t in waveguide_types if t['name'] == multimode]\n        if type(params_singlemode) == type([]) and len(params_singlemode)>0:\n            params_singlemode = params_singlemode[0]\n        else:\n            raise Exception('error: waveguide type (%s) not found in PDK waveguides' % singlemode)\n        if type(params_multimode) == type([]) and len(params_multimode)>0:\n            params_multimode = params_multimode[0]\n        else:\n            raise Exception('error: waveguide type (%s) not found in PDK waveguides' % multimode)\n        # find the taper\n        if 'taper_library' in params['compound_waveguide'] and 'taper_cell' in params['compound_waveguide']:\n            taper = layout.create_cell(params['compound_waveguide']['taper_cell'], params['compound_waveguide']['taper_library'])\n            if not taper:\n                raise Exception ('Cannot import cell %s : %s' % (params['compound_waveguide']['taper_cell'], params['compound_waveguide']['taper_library']))\n        else:\n            raise Exception('error: waveguide type (%s) does not have taper cell and library defined' % waveguide_type)\n        from pya import Trans, CellInstArray\n\n        '''\n        find sections of waveguides that are larger than (2 x radius + 2 x taper_length)\n         - insert two tapers\n         - insert multimode straight section\n         - insert singlemode waveguides (including bends) before\n        '''\n        import math\n        from SiEPIC.extend import to_itype\n        from pya import Point\n        radius = to_itype(params_singlemode['radius'],dbu)\n        taper_length = taper.find_pins()[0].center.distance(taper.find_pins()[1].center)\n        min_length = 2*radius + 2*taper_length\n        offset = radius\n        wg_sm_segment_pts = []\n        wg_last=0\n        waveguide_length = 0\n        for ii in range(1,len(dpts)):\n            start_point = dpts[ii-1]\n            end_point = dpts[ii]\n            distance_points = end_point.distance(start_point)\n            if distance_points < min_length:\n                # single mode segment, keep track\n                if ii==1:\n                    wg_sm_segment_pts.append(pts[ii-1])\n                wg_sm_segment_pts.append(pts[ii])\n                if ii==len(pts)-1:\n                    subcell = layout.create_cell(\"Waveguide_sm_%s\" %ii)\n                    cell.insert(CellInstArray(subcell.cell_index(), Trans()))\n                    waveguide_length += layout_waveguide3(subcell, wg_sm_segment_pts, params_singlemode, debug=True)\n            else:\n                # insert two tapers and multimode waveguide\n                angle = math.atan2((end_point.y-start_point.y),(end_point.x-start_point.x))/math.pi*180\n                if ii==1:\n                    wg_first=offset\n                else:\n                    wg_first=0\n                if ii==len(pts)-1:\n                    wg_last=offset\n                if round(angle)%360 == 270.0:\n                    t = Trans(Trans.R270, start_point.x, start_point.y-offset+wg_first)\n                    t2 = Trans(Trans.R90, end_point.x, end_point.y+offset-wg_last)\n                    wg_start_pt = Point(start_point.x, start_point.y-offset-taper_length+wg_first)\n                    wg_end_pt = Point(end_point.x, end_point.y+offset+taper_length-wg_last)\n                if round(angle)%360 == 90.0:\n                    t = Trans(Trans.R90, start_point.x, start_point.y+offset-wg_first)\n                    t2 = Trans(Trans.R270, end_point.x, end_point.y-offset+wg_last)\n                    wg_start_pt = Point(start_point.x, start_point.y+offset+taper_length-wg_first)\n                    wg_end_pt = Point(end_point.x, end_point.y-offset-taper_length+wg_last)\n                if round(angle)%360 == 180.0:\n                    t = Trans(Trans.R180, start_point.x-offset+wg_first, start_point.y)\n                    t2 = Trans(Trans.R0, end_point.x+offset-wg_last, end_point.y)\n                    wg_start_pt = Point(start_point.x-offset-taper_length+wg_first, start_point.y)\n                    wg_end_pt = Point(end_point.x+offset+taper_length-wg_last, end_point.y)\n                if round(angle)%360 == 0.0:\n                    t = Trans(Trans.R0, start_point.x+offset-wg_first, start_point.y)\n                    t2 = Trans(Trans.R180, end_point.x-offset+wg_last, end_point.y)\n                    wg_start_pt = Point(start_point.x+offset+taper_length-wg_first, start_point.y)\n                    wg_end_pt = Point(end_point.x-offset-taper_length+wg_last, end_point.y)\n                inst_taper = cell.insert(CellInstArray(taper.cell_index(), t))\n                inst_taper = cell.insert(CellInstArray(taper.cell_index(), t2))\n                waveguide_length += taper_length*2\n                subcell = layout.create_cell(\"Waveguide_mm_%s\" %ii)\n                cell.insert(CellInstArray(subcell.cell_index(), Trans()))\n                waveguide_length += layout_waveguide3(subcell, [wg_start_pt, wg_end_pt], params_multimode, debug=True)\n                # compound segment\n                if ii>1:\n                    wg_sm_segment_pts.append(t.disp.to_p())\n                    subcell = layout.create_cell(\"Waveguide_sm_%s\" %ii)\n                    cell.insert(CellInstArray(subcell.cell_index(), Trans()))\n                    waveguide_length += layout_waveguide3(subcell, wg_sm_segment_pts, params_singlemode, debug=True)\n                    wg_sm_segment_pts = [t2.disp.to_p(), pts[ii]]\n                else:\n                    wg_sm_segment_pts = [t2.disp.to_p(), pts[ii]]\n                \n    else:\n        # primitive waveguide type\n        waveguide_length = layout_waveguide3(cell, pts, params, debug=True)\n\n    return waveguide_length\n\n'''\nCreate a waveguide, in a specific technology\ninputs\n- cell: into which Cell we add the waveguide\n    from SiEPIC.utils import get_layout_variables\n    TECHNOLOGY, lv, layout, cell = get_layout_variables()\n- pts\n- params, obtained from load_Waveguides_by_Tech and Waveguides.XML\n    must be a primitive waveguide type containing <component> info\noutput:\n- waveguide\n- DevRec, PinRec\nby Lukas Chrostowski\n'''\ndef layout_waveguide3(cell, pts, params, debug=True):\n\n    if debug:\n        print ('SiEPIC.utils.layout.layout_waveguide3: ' )\n\n    layout = cell.layout()\n    dbu = layout.dbu\n    technology_name = layout.technology_name\n    from SiEPIC.utils import get_technology_by_name\n    TECHNOLOGY = get_technology_by_name(technology_name)\n\n    from SiEPIC.extend import to_itype\n    wg_width = to_itype(params['width'],dbu)\n    radius = float(params['radius'])\n    model = params['model']\n    cellName = 'Waveguide2'\n    CML = params['CML']\n    \n    if debug:\n        print (' - waveguide params: %s' % (params) )\n\n    if 'compound_waveguide' in params:    \n        print('error: this function cannot handle compound waveguides')\n        raise Exception('error: this function cannot handle compound waveguides (%s)' % waveguide_type)\n    \n    # draw the waveguide\n    waveguide_length = layout_waveguide2(TECHNOLOGY, layout, cell, [wg['layer'] for wg in params['component']], [wg['width'] for wg in params['component']], [wg['offset'] for wg in params['component']], pts, radius, params['adiabatic'], params['bezier'])\n\n    # Draw the marking layers\n    from SiEPIC.utils import angle_vector\n    LayerPinRecN = layout.layer(TECHNOLOGY['PinRec'])\n\n    make_pin(cell, 'opt1', pts[0], wg_width, LayerPinRecN, angle_vector(pts[0]-pts[1])%360)\n    make_pin(cell, 'opt2', pts[-1], wg_width, LayerPinRecN, angle_vector(pts[-1]-pts[-2])%360)\n\n    from pya import Trans, Text, Path, Point   \n\n    '''\n    t1 = Trans(angle_vector(pts[0]-pts[1])/90, False, pts[0])\n    cell.shapes(LayerPinRecN).insert(Path([Point(-10, 0), Point(10, 0)], wg_width).transformed(t1))\n    cell.shapes(LayerPinRecN).insert(Text(\"opt1\", t1, 0.3/dbu, -1))\n    \n    t = Trans(angle_vector(pts[-1]-pts[-2])/90, False, pts[-1])\n    cell.shapes(LayerPinRecN).insert(Path([Point(-10, 0), Point(10, 0)], wg_width).transformed(t))\n    cell.shapes(LayerPinRecN).insert(Text(\"opt2\", t, 0.3/dbu, -1))\n    '''\n    \t\n    LayerDevRecN = layout.layer(TECHNOLOGY['DevRec'])\n    \n    # Compact model information\n    angle_vec = angle_vector(pts[0]-pts[1])/90\n    halign = 0 # left\n    angle=0\n    dpt = Point(0,0)\n    if angle_vec == 0: # horizontal\n      halign = 2 # right\n      angle=0\n      dpt = Point(0, 0.2*wg_width)\n    if angle_vec == 2: # horizontal\n      halign = 0 # left\n      angle = 0\n      dpt=Point(0, 0.2*wg_width)\n    if angle_vec == 1: # vertical\n      halign = 2 # right\n      angle = 1\n      dpt=Point(0.2*wg_width,0)\n    if angle_vec == -1: # vertical\n      halign = 0 # left\n      angle = 1\n      dpt=Point(0.2*wg_width,0)\n    pt2=pts[0] + dpt\n    pt3=pts[0] - dpt\n    pt4=pts[0] - 6*dpt\n    pt5=pts[0] + 2*dpt\n\n    t = Trans(angle, False, pt3) \n    text = Text ('Lumerical_INTERCONNECT_library=Design kits/%s' % CML, t, 0.1*wg_width, -1)\n    text.halign=halign\n    shape = cell.shapes(LayerDevRecN).insert(text)\n    t = Trans(angle, False, pt2)\n    text = Text ('Component=%s' % model, t, 0.1*wg_width, -1)\n    text.halign=halign\n    shape = cell.shapes(LayerDevRecN).insert(text)\n    t = Trans(angle, False, pt5)\n    text = Text ('cellName=%s' % cellName, t, 0.1*wg_width, -1)\n    text.halign=halign\n    shape = cell.shapes(LayerDevRecN).insert(text)\n    t = Trans(angle, False, pts[0])\n    pts_txt = str([ [round(p.to_dtype(dbu).x,3), round(p.to_dtype(dbu).y,3)] for p in pts ]).replace(', ',',')\n    text = Text ( \\\n      'Spice_param:wg_length=%.9f wg_width=%.3g points=\"%s\" radius=%.3g' %\\\n        (waveguide_length*1e-6, wg_width*1e-9, pts_txt,radius*1e-6 ), t, 0.1*wg_width, -1  )\n    text.halign=halign\n    shape = cell.shapes(LayerDevRecN).insert(text)\n    t = Trans(angle, False, pt4)\n    text = Text ( \\\n      'Length=%.3f (microns)' %(waveguide_length), t, 0.5*wg_width, -1  )\n    text.halign=halign\n    shape = cell.shapes(LayerDevRecN).insert(text)\n    \n    return waveguide_length\n\n'''\nCreate a waveguide, in a specific technology\ninputs\n- TECHNOLOGY, layout, cell:\n    from SiEPIC.utils import get_layout_variables\n    TECHNOLOGY, lv, layout, cell = get_layout_variables()\n- layers: list of text names, e.g., ['Waveguide']\n- widths: list of floats in units Microns, e.g., [0.50]\n- offsets: list of floats in units Microns, e.g., [0]\n- pts: a list of pya.Points, e.g. \n    L=15/dbu\n    pts = [Point(0,0), Point(L,0), Point(L,L)]\n- radius: in Microns, e.g., 5\n- adiab: 1 = Bezier curve, 0 = radial bend (arc)\n- bezier: the bezier parameter, between 0 and 0.45 (almost a radial bend)\n\nNote: bezier parameters need to be simulated and optimized, and will depend on \n    wavelength, polarization, width, etc.  TM and rib waveguides don't benefit from bezier curves\n    most useful for TE \nby Lukas Chrostowski\n'''\ndef layout_waveguide2(TECHNOLOGY, layout, cell, layers, widths, offsets, pts, radius, adiab, bezier):\n    from SiEPIC.utils import arc_xy, arc_bezier, angle_vector, angle_b_vectors, inner_angle_b_vectors, translate_from_normal\n    from SiEPIC.extend import to_itype\n    from pya import Path, Polygon, Trans\n    dbu = layout.dbu\n    \n    if 'Errors' in TECHNOLOGY:\n        error_layer = layout.layer(TECHNOLOGY['Errors'])\n    else: \n        error_layer = None\n    \n    width=widths[0]\n    turn=0\n    waveguide_length = 0\n    for lr in range(0, len(layers)):\n        wg_pts = [pts[0]]\n        layer = layout.layer(TECHNOLOGY[layers[lr]])\n        width = to_itype(widths[lr],dbu)\n        offset = to_itype(offsets[lr],dbu)\n        for i in range(1,len(pts)-1):\n            turn = ((angle_b_vectors(pts[i]-pts[i-1],pts[i+1]-pts[i])+90)%360-90)/90\n            dis1 = pts[i].distance(pts[i-1])\n            dis2 = pts[i].distance(pts[i+1])\n            angle = angle_vector(pts[i]-pts[i-1])/90\n            pt_radius = to_itype(radius,dbu)\n            error_seg1 = False\n            error_seg2 = False\n            # determine the radius, based on how much space is available\n            if len(pts)==3:\n                # simple corner, limit radius by the two edges\n                if dis1 < pt_radius:\n                    error_seg1 = True\n                if dis2 < pt_radius:\n                    error_seg2 = True\n                pt_radius = min (dis1, dis2, pt_radius)\n            else:\n                if i==1:\n                    # first corner, limit radius by first edge, or 1/2 of second one\n                    if dis1 < pt_radius:\n                        error_seg1 = True\n                    if dis2/2 < pt_radius:\n                        error_seg2 = True\n                    pt_radius = min (dis1, dis2/2, pt_radius)\n                elif i==len(pts)-2:\n                    # last corner, limit radius by second edge, or 1/2 of first one\n                    if dis1/2 < pt_radius:\n                        error_seg1 = True\n                    if dis2 < pt_radius:\n                        error_seg2 = True\n                    pt_radius = min (dis1/2, dis2, pt_radius)\n                else:\n                    if dis1/2 < pt_radius:\n                        error_seg1 = True\n                    if dis2/2 < pt_radius:\n                        error_seg2 = True\n                    pt_radius = min (dis1/2, dis2/2, pt_radius)\n\n            if error_seg1 or error_seg2:\n                if not error_layer:\n                    # we have an error, but no Error layer\n                    print('- SiEPIC:layout_waveguide2: missing Error layer')\n                elif layer == layout.layer(TECHNOLOGY['Waveguide']): # and pt_radius < to_itype(radius,dbu):\n                    # add an error polygon to flag the incorrect bend        \n                    if error_seg1:\n                        error_pts = pya.Path([pts[i-1], pts[i]], width)\n                        cell.shapes(error_layer).insert(error_pts)\n                    if error_seg2:\n                        error_pts = pya.Path([pts[i], pts[i+1]], width)\n                        cell.shapes(error_layer).insert(error_pts)\n    #                error_pts = pya.Path([pts[i-1], pts[i], pts[i+1]], width)\n    #                cell.shapes(error_layer).insert(error_pts)\n            # waveguide bends:\n            if abs(turn)==1:\n                if(adiab):\n                    wg_pts += Path(arc_bezier(pt_radius, 270, 270 + inner_angle_b_vectors(pts[i-1]-pts[i], pts[i+1]-pts[i]), float(bezier), DevRec='DevRec' in layers[lr]), 0).transformed(Trans(angle, turn < 0, pts[i])).get_points()\n                else:\n                    wg_pts += Path(arc_xy(-pt_radius, pt_radius, pt_radius, 270, 270 + inner_angle_b_vectors(pts[i-1]-pts[i], pts[i+1]-pts[i]),DevRec='DevRec' in layers[lr]), 0).transformed(Trans(angle, turn < 0, pts[i])).get_points()\n            \n        wg_pts += [pts[-1]]\n        wg_pts = pya.Path(wg_pts, 0).unique_points().get_points()\n        wg_polygon = Polygon(translate_from_normal(wg_pts, width/2 + (offset if turn > 0 else - offset))+translate_from_normal(wg_pts, -width/2 + (offset if turn > 0 else - offset))[::-1])\n        cell.shapes(layer).insert(wg_polygon)\n  \n        if layout.layer(TECHNOLOGY['Waveguide']) == layer:\n            waveguide_length = wg_polygon.area() / width * dbu\n\n    return waveguide_length\n\n\ndef layout_waveguide(cell, layer, points_list, width):\n    \"\"\" Lays out a waveguide (or trace) with a certain width with along given points.\n\n    This is very useful for laying out Bezier curves with or without adiabatic tapers.\n\n    Args:\n        cell: cell to place into\n        layer: layer to place into. It is done with cell.shapes(layer).insert(pya.Polygon)\n        points_list: list of pya.DPoint (at least 2 points)\n        width (microns): constant or list. If list, then it has to have the same length as points\n\n    \"\"\"\n    if len(points_list) < 2:\n        raise NotImplemented(\"ERROR: points_list too short\")\n        return\n\n    if type(width)==type(0.0):\n        width_iterator = repeat(width)\n        points_iterator = iter(points_list)\n    else:\n        try:\n            if len(width) == len(points_list):\n                width_iterator = iter(width)\n            else:\n                width_iterator = repeat(width[0])\n        except TypeError:\n            width_iterator = repeat(width)\n        finally:\n            points_iterator = iter(points_list)\n\n    dbu = cell.layout().dbu\n\n    points_low = list()\n    points_high = list()\n\n    def norm(self):\n        return sqrt(self.x**2 + self.y**2)\n\n    def cos_angle(point1, point2):\n        return point1 * point2 / norm(point1) / norm(point2)\n\n    point_width_list = list(zip(points_iterator, width_iterator))\n    N = len(point_width_list)\n\n    first_point, first_width = point_width_list[0]\n    next_point, next_width = point_width_list[1]\n\n    delta = next_point - first_point\n    theta = np.arctan2(delta.y, delta.x)\n    first_high_point = first_point + 0.5 * first_width * \\\n        pya.DPoint(cos(theta + pi / 2), sin(theta + pi / 2))\n    first_low_point = first_point + 0.5 * first_width * \\\n        pya.DPoint(cos(theta - pi / 2), sin(theta - pi / 2))\n    points_high.append(first_high_point)\n    points_low.append(first_low_point)\n\n    for i in range(1, N - 1):\n        prev_point, prev_width = point_width_list[i - 1]\n        point, width = point_width_list[i]\n        next_point, next_width = point_width_list[i + 1]\n\n        delta_prev = point - prev_point\n        delta_next = next_point - point\n        theta_prev = np.arctan2(delta_prev.y, delta_prev.x)\n        theta_next = np.arctan2(delta_next.y, delta_next.x)\n\n        next_point_high = (next_point + 0.5 * next_width *\n                           pya.DPoint(cos(theta_next + pi / 2), sin(theta_next + pi / 2)))\n        next_point_low = (next_point + 0.5 * next_width *\n                          pya.DPoint(cos(theta_next - pi / 2), sin(theta_next - pi / 2)))\n\n        forward_point_high = (point + 0.5 * width *\n                              pya.DPoint(cos(theta_next + pi / 2), sin(theta_next + pi / 2)))\n        forward_point_low = (point + 0.5 * width *\n                             pya.DPoint(cos(theta_next - pi / 2), sin(theta_next - pi / 2)))\n\n        prev_point_high = (prev_point + 0.5 * prev_width *\n                           pya.DPoint(cos(theta_prev + pi / 2), sin(theta_prev + pi / 2)))\n        prev_point_low = (prev_point + 0.5 * prev_width *\n                          pya.DPoint(cos(theta_prev - pi / 2), sin(theta_prev - pi / 2)))\n\n        backward_point_high = (point + 0.5 * width *\n                               pya.DPoint(cos(theta_prev + pi / 2), sin(theta_prev + pi / 2)))\n        backward_point_low = (point + 0.5 * width *\n                              pya.DPoint(cos(theta_prev - pi / 2), sin(theta_prev - pi / 2)))\n\n        # High point decision\n        next_high_edge = pya.DEdge(forward_point_high, next_point_high)\n        prev_high_edge = pya.DEdge(backward_point_high, prev_point_high)\n\n        if next_high_edge.crossed_by(prev_high_edge):\n            intersect_point = next_high_edge.crossing_point(prev_high_edge)\n            points_high.append(intersect_point)\n        else:\n            if width * (1 - cos_angle(delta_next, delta_prev)) > dbu:\n                points_high.append(backward_point_high)\n                points_high.append(forward_point_high)\n            else:\n                points_high.append((backward_point_high + forward_point_high) * 0.5)\n\n        # Low point decision\n        next_low_edge = pya.DEdge(forward_point_low, next_point_low)\n        prev_low_edge = pya.DEdge(backward_point_low, prev_point_low)\n\n        if next_low_edge.crossed_by(prev_low_edge):\n            intersect_point = next_low_edge.crossing_point(prev_low_edge)\n            points_low.append(intersect_point)\n        else:\n            if width * (1 - cos_angle(delta_next, delta_prev)) > dbu:\n                points_low.append(backward_point_low)\n                points_low.append(forward_point_low)\n            else:\n                points_low.append((backward_point_low + forward_point_low) * 0.5)\n\n    last_point, last_width = point_width_list[-1]\n    point, width = point_width_list[-2]\n    delta = last_point - point\n    theta = np.arctan2(delta.y, delta.x)\n    final_high_point = last_point + 0.5 * last_width * \\\n        pya.DPoint(cos(theta + pi / 2), sin(theta + pi / 2))\n    final_low_point = last_point + 0.5 * last_width * \\\n        pya.DPoint(cos(theta - pi / 2), sin(theta - pi / 2))\n    if (final_high_point - points_high[-1]) * delta > 0:\n        points_high.append(final_high_point)\n    if (final_low_point - points_low[-1]) * delta > 0:\n        points_low.append(final_low_point)\n\n    # Append point only if change in direction is less than 120 degrees.\n    def smooth_append(point_list, point):\n        if point_list is None:\n            print(point)\n        if len(point_list) < 1:\n            point_list.append(point)\n            return point_list\n        elif len(point_list) < 2:\n            curr_edge = point - point_list[-1]\n            if norm(curr_edge) > dbu:\n                point_list.append(point)\n                return point_list\n\n        curr_edge = point - point_list[-1]\n        if norm(curr_edge) > dbu:\n            prev_edge = point_list[-1] - point_list[-2]\n            if cos_angle(curr_edge, prev_edge) > cos(120 / 180 * pi):\n                point_list.append(point)\n        return point_list\n\n    polygon_points = points_low + list(reversed(points_high))\n    polygon_points = list(reduce(smooth_append, polygon_points, list()))\n\n    poly = pya.DPolygon(polygon_points)\n    cell.shapes(layer).insert(poly)\n\n\ndef layout_ring(cell, layer, center, r, w):\n        # function to produce the layout of a ring\n        # cell: layout cell to place the layout\n        # layer: which layer to use\n        # center: origin DPoint\n        # r: radius\n        # w: waveguide width\n        # units in microns\n\n        # example usage.  Places the ring layout in the presently selected cell.\n        # cell = pya.Application.instance().main_window().current_view().active_cellview().cell\n        # layout_ring(cell, cell.layout().layer(LayerInfo(1, 0)), pya.DPoint(0,0), 10, 0.5)\n\n    layout_arc(cell, layer, center, r, w, 0, 2 * np.pi)\n\n\ndef layout_arc(cell, layer, center, r, w, theta_start, theta_end, ex=None):\n    # function to produce the layout of an arc\n    # cell: layout cell to place the layout\n    # layer: which layer to use\n    # center: origin DPoint\n    # r: radius\n    # w: waveguide width\n    # theta_start, theta_end: angle in radians\n    # units in microns\n\n    # example usage.  Places the ring layout in the presently selected cell.\n    # cell = pya.Application.instance().main_window().current_view().active_cellview().cell\n    # layout_arc(cell, layer, pya.DPoint(0,0), 10, 0.5, 0, np.pi/2)\n\n    # fetch the database parameters\n\n    if ex is None:\n        ex = pya.DPoint(1, 0)\n\n    delta_theta = np.arctan2(ex.y, ex.x)\n    theta_start += delta_theta\n    theta_end += delta_theta\n\n    # optimal sampling\n    arc_function = lambda t: np.array([center.x + r * np.cos(t), center.y + r * np.sin(t)])\n    t, coords = sample_function(arc_function,\n                                [theta_start, theta_end], tol=0.002 / r)\n\n    # # This yields a better polygon\n    coords = np.insert(coords, 0, arc_function(theta_start - 0.001),\n                       axis=1)  # start the waveguide a little bit before\n    coords = np.append(coords, np.atleast_2d(arc_function(theta_end + 0.001)).T,\n                       axis=1)  # finish the waveguide a little bit after\n\n    layout_waveguide(cell, layer, [pya.DPoint(x, y) for x, y in zip(*coords)], w)\n\n\ndef layout_arc_drc_exclude(cell, drc_layer, center, r, w, theta_start, theta_end, ex=None):\n    corner_points = [center + (r + w / 2) * rotate(ex, theta_start),\n                     center + (r - w / 2) * rotate(ex, theta_start),\n                     center + (r + w / 2) * rotate(ex, theta_end),\n                     center + (r - w / 2) * rotate(ex, theta_end)]\n    for corner_point in corner_points:\n        layout_square(cell, drc_layer, corner_point, 0.1, ex)\n\n\ndef layout_arc_with_drc_exclude(cell, layer, drc_layer, center, r, w, theta_start, theta_end, ex=None):\n    layout_arc(cell, layer, center, r, w, theta_start, theta_end, ex)\n    layout_arc_drc_exclude(cell, drc_layer, center, r, w, theta_start, theta_end, ex)\n\n\ndef layout_circle(cell, layer, center, r):\n    # function to produce the layout of a filled circle\n    # cell: layout cell to place the layout\n    # layer: which layer to use\n    # center: origin DPoint\n    # r: radius\n    # w: waveguide width\n    # theta_start, theta_end: angle in radians\n    # units in microns\n    # optimal sampling\n\n    arc_function = lambda t: np.array([center.x + r * np.cos(t), center.y + r * np.sin(t)])\n    t, coords = sample_function(arc_function,\n                                [0, 2 * np.pi - 0.001], tol=0.002 / r)\n\n    dbu = cell.layout().dbu\n    dpoly = pya.DPolygon([pya.DPoint(x, y) for x, y in zip(*coords)])\n    cell.shapes(layer).insert(dpoly.to_itype(dbu))\n\n\ndef layout_path(cell, layer, point_iterator, w):\n    path = pya.DPath(list(point_iterator), w, 0, 0).to_itype(cell.layout().dbu)\n    cell.shapes(layer).insert(pya.Path.from_dpath(path))\n\n\ndef layout_path_with_ends(cell, layer, point_iterator, w):\n    dpath = pya.DPath(list(point_iterator), w, w / 2, w / 2)\n    cell.shapes(layer).insert(dpath)\n\n\ndef box_dpolygon(point1, point3, ex=None):\n    # position point2 to the right of point1\n    if ex is None:\n        ex = pya.DPoint(1, 0)\n    ey = rotate90(ex)\n    point2 = point1 * ex * ex + point3 * ey * ey\n    point4 = point3 * ex * ex + point1 * ey * ey\n\n    return pya.DPolygon([point1, point2, point3, point4])\n\n\ndef square_dpolygon(center, width, ex=None):\n    # returns the polygon of a square centered at center,\n    # aligned with ex, with width in microns\n    if ex is None:\n        ex = pya.DPoint(1, 0)\n    ey = rotate90(ex)\n    quadrant = (width / 2) * (ex + ey)\n    point1 = center + quadrant\n    quadrant = rotate90(quadrant)\n    point2 = center + quadrant\n    quadrant = rotate90(quadrant)\n    point3 = center + quadrant\n    quadrant = rotate90(quadrant)\n    point4 = center + quadrant\n\n    return pya.DPolygon([point1, point2, point3, point4])\n\n\ndef layout_square(cell, layer, center, width, ex=None):\n    \"\"\" Lays out a square in the DRC layer\n\n    Args:\n        center: pya.DPoint (um units)\n        width: float (um units)\n        ex: orientation\n\n    \"\"\"\n\n    if ex is None:\n        ex = pya.DPoint(1, 0)\n\n    square = square_dpolygon(center, width, ex)\n    cell.shapes(layer).insert(square)\n\ndef layout_taper(cell, layer, trans, w1, w2, length, insert = True):\n    \"\"\" Lays out a taper\n\n    Args:\n        trans: pya.Trans: location and rotation\n        w1: width of waveguide, float for DPoint type (microns); int for Point type (nm)\n        w2: width of waveguide, float for DPoint type (microns); int for Point type (nm)\n        length: length, float\n        insert: flag to insert drawn waveguide or return shape, boolean\n\n    \"\"\"\n    import pya\n    if type(w1)==type(float()):\n        pts = [pya.DPoint(0,-w1/2), pya.DPoint(0,w1/2), pya.DPoint(length,w2/2), pya.DPoint(length,-w2/2)]\n        shape_taper = pya.DPolygon(pts).transformed(trans)\n    else:\n        pts = [pya.Point(0,-w1/2), pya.Point(0,w1/2), pya.Point(length,w2/2), pya.Point(length,-w2/2)]\n        shape_taper = pya.Polygon(pts).transformed(trans)\n    \n    if insert == True:\n        cell.shapes(layer).insert(shape_taper)\n    else:\n        return shape_taper\n\ndef layout_waveguide_sbend_bezier(cell, layer, trans, w=0.5, wo=None, h=2.0, length=15.0, insert = True):\n    \"\"\" Creates a waveguide s-bend using a bezier curve\n    Author: Lukas Chrostowski\n    Args:\n        trans: pya.Trans: location and rotation\n        w: width of input waveguide, float for DPoint type (microns); int for Point type (nm)\n        wo (optional): width of output waveguide, float\n        h: height\n        length: length\n        insert: flag to insert drawn waveguide or return shape, boolean\n    Usage:\n        from SiEPIC.utils import get_layout_variables\n        TECHNOLOGY, lv, ly, cell = get_layout_variables()\n        layer = cell.layout().layer(TECHNOLOGY['Waveguide'])\n        layout_waveguide_sbend_bezier(cell, layer, pya.Trans(), w=0.5, h=2.0, length=15.0, insert = True)\n    \"\"\"\n    \n    if wo==None:\n        wo = w\n        \n    from SiEPIC.utils.geometry import bezier_parallel, translate_from_normal2\n    from pya import DPoint, DPolygon, Point, Polygon\n\n    if type(w)==type(int()):\n        dbu = cell.layout().dbu\n        w=w*dbu\n        wo=wo*dbu\n        h=h*dbu\n        length=length*dbu\n        trans=trans.to_dtype(dbu)\n        \n    p = bezier_parallel(DPoint(0,0), DPoint(length,h), 0)\n\n    pt1 = translate_from_normal2(p,w/2,wo/2)\n    pt2 = translate_from_normal2(p,-w/2, -wo/2)\n    pt = pt1+pt2[::-1]\n    \n    poly = pya.DPolygon(pt)\n    print(poly)\n    poly_t = poly.transformed(trans)\n    if insert == True:\n        cell.shapes(layer).insert(poly_t)\n        return poly_t.area()/((w+wo)/2)\n    else:\n        return poly_t\n    \n\ndef layout_waveguide_sbend(cell, layer, trans, w=500, r=25000, h=2000, length=15000, insert = True):\n    \"\"\" Lays out an s-bend\n\n    Args:\n        trans: pya.Trans: location and rotation\n        w: width of waveguide, int\n        r: radius, int\n        h: height, int\n        length: length, int\n        insert: flag to insert drawn waveguide or return shape, boolean\n\n    \"\"\"\n\n    from math import pi, cos, sin, log, sqrt, acos\n    from SiEPIC.utils import points_per_circle\n    import pya\n    \n    theta = acos(float(r-abs(h/2))/r)*180/pi\n    x = int(2*r*sin(theta/180.0*pi))\n    straight_l = int( (length - x)/2 )\n\n    if (straight_l < 0):\n        # Problem: target length is too short. increase\n        print('SBend, too short: straight_l = %s' % straight_l)\n        length = x\n        straight_l = 0\n\n    # waveguide_length = (2*pi*r*(2*theta/360.0)+straight_l*2)\n    \n\n    # define the cell origin as the left side of the waveguide sbend\n\n    if (straight_l >= 0):\n      circle_fraction = abs(theta) / 360.0\n      npoints = int(points_per_circle(r*cell.layout().dbu) * circle_fraction)\n      if npoints == 0:\n        npoints = 1\n      da = 2 * pi / npoints * circle_fraction # increment, in radians\n      x1=straight_l\n      x2=length-straight_l\n\n      if h>0:\n        y1=r\n        theta_start1 = 270\n        y2=h-r\n        theta_start2 = 90\n        pts = []\n        th1 = theta_start1 / 360.0 * 2 * pi\n        th2 = theta_start2 / 360.0 * 2 * pi\n        pts.append(pya.Point.from_dpoint(pya.DPoint(0,w/2)))\n        pts.append(pya.Point.from_dpoint(pya.DPoint(0,-w/2)))\n        for i in range(0, npoints+1): # lower left\n          pts.append(pya.Point.from_dpoint(pya.DPoint((x1+(r+w/2)*cos(i*da+th1))/1, (y1+(r+w/2)*sin(i*da+th1))/1)))\n        for i in range(npoints, -1, -1): # lower right\n          pts.append(pya.Point.from_dpoint(pya.DPoint((x2+(r-w/2)*cos(i*da+th2))/1, (y2+(r-w/2)*sin(i*da+th2))/1)))\n        pts.append(pya.Point.from_dpoint(pya.DPoint(length,h-w/2)))\n        pts.append(pya.Point.from_dpoint(pya.DPoint(length,h+w/2)))\n        for i in range(0, npoints+1): # upper right\n         pts.append(pya.Point.from_dpoint(pya.DPoint((x2+(r+w/2)*cos(i*da+th2))/1, (y2+(r+w/2)*sin(i*da+th2))/1)))\n        for i in range(npoints, -1, -1): # upper left\n          pts.append(pya.Point.from_dpoint(pya.DPoint((x1+(r-w/2)*cos(i*da+th1))/1, (y1+(r-w/2)*sin(i*da+th1))/1)))\n      else:\n        y1=-r\n        theta_start1 = 90-theta\n        y2=r+h\n        theta_start2 = 270-theta\n        pts = []\n        th1 = theta_start1 / 360.0 * 2 * pi\n        th2 = theta_start2 / 360.0 * 2 * pi\n        pts.append(pya.Point.from_dpoint(pya.DPoint(length,h-w/2)))\n        pts.append(pya.Point.from_dpoint(pya.DPoint(length,h+w/2)))\n        for i in range(npoints, -1, -1): # upper right\n          pts.append(pya.Point.from_dpoint(pya.DPoint((x2+(r-w/2)*cos(i*da+th2))/1, (y2+(r-w/2)*sin(i*da+th2))/1)))\n        for i in range(0, npoints+1): # upper left\n          pts.append(pya.Point.from_dpoint(pya.DPoint((x1+(r+w/2)*cos(i*da+th1))/1, (y1+(r+w/2)*sin(i*da+th1))/1)))\n        pts.append(pya.Point.from_dpoint(pya.DPoint(0,w/2)))\n        pts.append(pya.Point.from_dpoint(pya.DPoint(0,-w/2)))\n        for i in range(npoints, -1, -1): # lower left\n          pts.append(pya.Point.from_dpoint(pya.DPoint((x1+(r-w/2)*cos(i*da+th1))/1, (y1+(r-w/2)*sin(i*da+th1))/1)))\n        for i in range(0, npoints+1): # lower right\n         pts.append(pya.Point.from_dpoint(pya.DPoint((x2+(r+w/2)*cos(i*da+th2))/1, (y2+(r+w/2)*sin(i*da+th2))/1)))\n      \n      shape_bend = pya.Polygon(pts).transformed(trans)\n      if insert == True:\n        cell.shapes(layer).insert(shape_bend)\n      else:\n        return shape_bend\n\n    print('SBend: theta %s, x %s, straight_l %s, r %s, h %s, length %s' % (theta, x, straight_l, r, h, length) )\n    return length\n\ndef append_relative(points, *relative_vectors):\n    \"\"\" Appends to list of points in relative steps \"\"\"\n    try:\n        if len(points) > 0:\n            origin = points[-1]\n    except TypeError:\n        raise TypeError(\"First argument must be a list of points\")\n\n    for vector in relative_vectors:\n        points.append(origin + vector)\n        origin = points[-1]\n    return points\n\n\ndef place_cell(parent_cell, cell, placement_origin, params=None, relative_to=None):\n    \"\"\" Places a cell and return ports\n    Args:\n        parent_cell: cell to place into\n        cell: cell to be placed\n        placement_origin: pya.Point object to be used as origin\n        relative_to: port name\n\n    Returns:\n        ports(dict): key:port.name, value: geometry.Port with positions relative to parent_cell's origin\n    \"\"\"\n    layout = parent_cell.layout()\n    pcell, ports = cell.pcell(layout, params=params)\n    if relative_to is not None:\n        offset = next((port.position for port in ports if port.name == relative_to), None)\n        placement_origin = placement_origin - offset\n    parent_cell.insert(pya.CellInstArray(pcell.cell_index(),\n                                         pya.Trans(pya.Trans.R0, placement_origin.to_itype(layout.dbu))))\n    for port in ports:\n        port.position += placement_origin\n\n    return {port.name: port for port in ports}\n\n\ndef layout_connect_ports(cell, layer, port_from, port_to):\n\n    P0 = port_from.position\n    P3 = port_to.position\n    angle_from = np.arctan2(port_from.direction.y, port_from.direction.x) * 180 / pi\n    angle_to = np.arctan2(-port_to.direction.y, -port_to.direction.x) * 180 / pi\n\n    curve = bezier_optimal(P0, P3, angle_from, angle_to)\n    layout_waveguide(cell, layer, curve, [port_from.width, port_to.width])\n    return curve_length(curve)\n\n\n\n\n\ndef make_pin(cell, name, center, w, layer, direction, debug=False):\n\n    '''\n    Makes a pin that SiEPIC-Tools will recognize\n    cell: which cell to draw it in\n    name: text label for the pin\n    center: location, int [x,y]\n    w: pin width\n    layer: layout.layer() type\n    direction = \n        0: right\n        90: up\n        180: left\n        270: down\n\n    Units: intput can be float for microns, or int for nm\n    '''\n    \n    from SiEPIC.extend import to_itype\n    from pya import Point, DPoint\n    import numpy\n    dbu = cell.layout().dbu\n    if type(w)==type(float()):\n        w = to_itype(w,dbu)\n        if debug:\n            print('SiEPIC.utils.layout.make_pin: w converted to %s' %w )\n    else:\n        if debug:\n            print('SiEPIC.utils.layout.make_pin: w %s' %w )\n#    print(type(center[0]))\n    if type(center) == type(Point()) or type(center) == type(DPoint()):\n        center = [center.x, center.y]\n    if type(center[0])==type(float()) or type(center[0])==type(numpy.float64()):\n        center[0] = to_itype(center[0],dbu)\n        center[1] = to_itype(center[1],dbu)\n        if debug:\n            print('SiEPIC.utils.layout.make_pin: center converted to %s' % (center)  )\n    else:\n        if debug:\n            print('SiEPIC.utils.layout.make_pin: center %s' % (center)  )\n\n    from SiEPIC._globals import PIN_LENGTH as pin_length\n\n    direction = direction % 360 \n    if direction not in [0, 90, 180, 270]:\n        raise('error in make_pin: direction must be one of [0, 90, 180, 270]')\n\n    # text label\n    t = pya.Trans(pya.Trans.R0, center[0],center[1])\n    text = pya.Text (name, t)\n    shape = cell.shapes(layer).insert(text)\n    shape.text_dsize = float(w*dbu/2)\n    shape.text_valign=1\n\n    if direction == 0:\n        p1 = pya.Point(center[0]-pin_length/2, center[1])\n        p2 = pya.Point(center[0]+pin_length/2, center[1])\n        shape.text_halign=2\n    if direction == 90:\n        p1 = pya.Point(center[0], center[1]-pin_length/2)\n        p2 = pya.Point(center[0], center[1]+pin_length/2)\n        shape.text_halign=2\n        shape.text_rot=1\n    if direction == 180:\n        p1 = pya.Point(center[0]+pin_length/2, center[1])\n        p2 = pya.Point(center[0]-pin_length/2, center[1])\n        shape.text_halign=3\n    if direction == 270:\n        p1 = pya.Point(center[0], center[1]+pin_length/2)\n        p2 = pya.Point(center[0], center[1]-pin_length/2)\n        shape.text_halign=3\n        shape.text_rot=1\n      \n    pin = pya.Path([p1,p2],w)\n    cell.shapes(layer).insert(pin)\n\n\n\n\ndef y_splitter_tree(cell, tree_depth=4, y_splitter_cell=\"y_splitter_1310\", library=\"SiEPICfab_Shuksan_PDK\", wg_type='Strip TE 1310 nm, w=350 nm', draw_waveguides=True):\n    '''\n    Create a tree of splitters\n    - cell: layout cell to create the structures in\n    - tree_depth: Tree depth (2^N outputs)\n    - y_splitter_cell: name of the y-splitter cell\n    - library: the library containing the y_splitter_cell\n    - wg_type: waveguide type from WAVEGUIDES.XML\n    - draw_waveguides: True draws the waveguides, False is faster for debugging\n    \n    Returns\n    - inst_in: instance of the input cell\n    - inst_out[]: array of instances of the output cells\n    - cell_tree: new cell created\n    This is useful for subsequent routing\n    \n    Limitations:\n    - the design uses regular 90 degree bends, rather than S-bends.\n      hence it could be made more compact\n    '''\n    \n    from SiEPIC.scripts import connect_pins_with_waveguide\n    from SiEPIC.extend import to_itype\n    from math import floor\n\n    # create a new sub-cell where the tree will go\n    ly = cell.layout()\n    tech = ly.technology().name\n    cell_tree = ly.create_cell(\"y_splitter_tree\")\n\n    # load the y-splitter from the library\n    y_splitter = ly.create_cell(y_splitter_cell, library)\n    if not y_splitter:\n        raise Exception ('Cannot import cell %s:%s' % (library,y_splitter_cell))\n\n    # Load waveguide information\n    from SiEPIC.utils import load_Waveguides_by_Tech\n    waveguides = load_Waveguides_by_Tech(tech)\n    wg = [w for w in waveguides if wg_type in w['name'] ][0]\n    if not wg:\n        raise Exception(\"Waveguide type not defined in WAVEGUIDES.XML: %s\" %wg_type )\n        return\n    wg_width = to_itype(float(wg['width']), ly.dbu)\n    wg_radius = to_itype(float(wg['radius']), ly.dbu)\n\n    # build the tree, using measurements from the cell and waveguide parameters\n    x = 0\n    dx = y_splitter.bbox().width() + wg_radius*2\n    # calculate the spacing for the y-splitters based on waveguide radius and 90 degree bends\n    y_wg_offset = (y_splitter.pinPoint(\"opt2\").y-y_splitter.pinPoint(\"opt3\").y)\n    dy = max(y_splitter.bbox().height(), wg_radius*4 + y_wg_offset)\n    # intialize loop\n    inst_out = []\n    y0 = 0\n    for i in range(0,tree_depth):\n        inst = []\n        y = y0\n        for j in range(0, int(2**(tree_depth-i-1))):\n            t = pya.Trans(pya.Trans.R0, x, y)\n            inst.append(cell_tree.insert(pya.CellInstArray(y_splitter.cell_index(), t)))\n            # perform waveguide routing\n            if (i > 0) and draw_waveguides:        \n                connect_pins_with_waveguide(\n                    inst[j], 'opt2',\n                    inst_higher[j*2+1], 'opt1', waveguide_type=wg_type)\n                connect_pins_with_waveguide(\n                    inst[j], 'opt3',\n                    inst_higher[j*2], 'opt1', waveguide_type=wg_type)\n            y += dy\n        inst_higher = inst\n        if i == 0:\n            inst_out = inst\n        if i == tree_depth-1:\n            inst_in = inst[0]\n        x += -dx\n        y0 = y0 + dy/2\n        dy = dy * 2\n        \n           \n    return inst_in, inst_out, cell_tree\n", "meta": {"hexsha": "3638b56b82875318d545820c7d0f192c5ba31b82", "size": 43248, "ext": "py", "lang": "Python", "max_stars_repo_path": "klayout_dot_config/python/SiEPIC/utils/layout.py", "max_stars_repo_name": "lukasc-ubc/SiEPIC-Tools", "max_stars_repo_head_hexsha": "9c3046f51dfce96c34715c66d9a903b1f883eca2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2017-12-11T22:15:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-11T12:35:24.000Z", "max_issues_repo_path": "klayout_dot_config/python/SiEPIC/utils/layout.py", "max_issues_repo_name": "lukasc-ubc/SiEPIC-Tools", "max_issues_repo_head_hexsha": "9c3046f51dfce96c34715c66d9a903b1f883eca2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 110, "max_issues_repo_issues_event_min_datetime": "2017-12-13T08:36:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-07T05:42:19.000Z", "max_forks_repo_path": "klayout_dot_config/python/SiEPIC/utils/layout.py", "max_forks_repo_name": "lukasc-ubc/SiEPIC-Tools", "max_forks_repo_head_hexsha": "9c3046f51dfce96c34715c66d9a903b1f883eca2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2018-01-04T18:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-07T03:53:47.000Z", "avg_line_length": 40.0815569972, "max_line_length": 254, "alphanum_fraction": 0.6159591195, "include": true, "reason": "import numpy,from numpy", "num_tokens": 11803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3415825128436339, "lm_q1q2_score": 0.1972623179957216}}
{"text": "\"\"\"必要的工具\"\"\"\nimport numpy as np\nimport tensorflow as tf\nfrom PIL import Image\nimport keras\nimport numpy as np\nimport math\n\ndef get_new_img_size(width, height, img_min_side=600):\n    \"\"\"把图片最小边resize到600\"\"\"\n    if width <= height:\n        f = float(img_min_side) / width\n        resized_height = int(f * height)\n        resized_width = int(img_min_side)\n    else:\n        f = float(img_min_side) / height\n        resized_width = int(f * width)\n        resized_height = int(img_min_side)\n\n    return resized_width, resized_height\n\n\nclass BBoxUtility(object):\n    def __init__(self, priors=None, overlap_threshold=0.7, ignore_threshold=0.3,\n                 nms_thresh=0.7, top_k=300):\n        self.priors = priors\n        self.num_priors = 0 if priors is None else len(priors)\n        self.overlap_threshold = overlap_threshold\n        self.ignore_threshold = ignore_threshold\n        self._nms_thresh = nms_thresh\n        self._top_k = top_k\n        self.boxes = tf.placeholder(dtype='float32', shape=(None, 4))\n        self.scores = tf.placeholder(dtype='float32', shape=(None,))\n        self.nms = tf.image.non_max_suppression(self.boxes, self.scores,\n                                                self._top_k,\n                                                iou_threshold=self._nms_thresh)\n        self.sess = tf.Session(config=tf.ConfigProto(device_count={'GPU': 0}))\n\n    @property\n    def nms_thresh(self):\n        return self._nms_thresh\n\n    @nms_thresh.setter\n    def nms_thresh(self, value):\n        self._nms_thresh = value\n        self.nms = tf.image.non_max_suppression(self.boxes, self.scores,\n                                                self._top_k,\n                                                iou_threshold=self._nms_thresh)\n\n    @property\n    def top_k(self):\n        return self._top_k\n\n    @top_k.setter\n    def top_k(self, value):\n        self._top_k = value\n        self.nms = tf.image.non_max_suppression(self.boxes, self.scores,\n                                                self._top_k,\n                                                iou_threshold=self._nms_thresh)\n\n    def iou(self, box):\n        \"\"\"\n        box：真实框\n        计算真实框与所有先验框的IOU值\n        \"\"\"\n        # 计算出每个真实框与所有的先验框的iou\n        # 判断真实框与先验框的重合情况\n        inter_upleft = np.maximum(self.priors[:, :2], box[:2])\n        inter_botright = np.minimum(self.priors[:, 2:4], box[2:])\n\n        inter_wh = inter_botright - inter_upleft\n        inter_wh = np.maximum(inter_wh, 0)\n        inter = inter_wh[:, 0] * inter_wh[:, 1]\n        # 真实框的面积\n        area_true = (box[2] - box[0]) * (box[3] - box[1])\n        # 先验框的面积\n        area_gt = (self.priors[:, 2] - self.priors[:, 0]) * (self.priors[:, 3] - self.priors[:, 1])\n        # 计算iou\n        union = area_true + area_gt - inter\n\n        iou = inter / union\n        return iou\n\n    def encode_box(self, box, return_iou=True):\n        \"\"\"如果重合度超过0.7，认为可以进行调节成真实框\"\"\"\n        #box为传入的真实框，计算与先验框的重合度\n        iou = self.iou(box)\n        encoded_box = np.zeros((self.num_priors, 4 + return_iou))\n\n        # 找到每一个真实框，重合程度较高的先验框\n        # 如果iou>0.7，认为可以利用这个先验框回归到真实框\n        assign_mask = iou > self.overlap_threshold\n        if not assign_mask.any():\n            assign_mask[iou.argmax()] = True\n        if return_iou:\n            encoded_box[:, -1][assign_mask] = iou[assign_mask]\n\n        #对真实框与先验框进行编码，计算出应该有的预测结果，用于网络回归训练\n        # 找到对应的先验框\n        assigned_priors = self.priors[assign_mask]\n        # 逆向编码，将真实框转化为FasterRCNN预测结果的格式\n        # 先计算真实框的中心与长宽\n        box_center = 0.5 * (box[:2] + box[2:])\n        box_wh = box[2:] - box[:2]\n        # 再计算重合度较高的先验框的中心与长宽\n        assigned_priors_center = 0.5 * (assigned_priors[:, :2] +\n                                        assigned_priors[:, 2:4])\n        assigned_priors_wh = (assigned_priors[:, 2:4] -\n                              assigned_priors[:, :2])\n\n        # 逆向求取FasterRCNN应该有的预测结果\n        encoded_box[:, :2][assign_mask] = box_center - assigned_priors_center\n        encoded_box[:, :2][assign_mask] /= assigned_priors_wh\n        encoded_box[:, :2][assign_mask] *= 4\n\n        encoded_box[:, 2:4][assign_mask] = np.log(box_wh / assigned_priors_wh)\n        encoded_box[:, 2:4][assign_mask] *= 4\n        return encoded_box.ravel()\n\n    def ignore_box(self, box):\n        \"\"\"\n        box:标记中真实的框\n        \"\"\"\n        # 获取所有先验框和真实框的重合程度\n        iou = self.iou(box)\n\n        ignored_box = np.zeros((self.num_priors, 1))\n\n        # 找到每一个真实框，重合程度较高的先验框\n        # 如果重合程度大于0.3或者小于0.7，就应该忽略这个框\n        assign_mask = (iou > self.ignore_threshold) & (iou < self.overlap_threshold)\n\n        if not assign_mask.any():\n            assign_mask[iou.argmax()] = True\n\n        #找出需要忽略的先验框\n        ignored_box[:, 0][assign_mask] = iou[assign_mask]\n        return ignored_box.ravel()\n\n    def assign_boxes(self, boxes, anchors):\n        \"\"\"计算真实框对应的先验框，与这个先验框应当有的预测结果\"\"\"\n        #先求出先验框个数\n        self.num_priors = len(anchors)\n        self.priors = anchors\n        #创建一个全0矩阵，第一维是先验框个数，第二维的前4列是先验框的位置信息，第5列代表是否包含物体\n        assignment = np.zeros((self.num_priors, 4 + 1))\n\n        #初始时，认为所有先验框为背景，所以第5列=0\n        assignment[:, 4] = 0.0\n        if len(boxes) == 0:\n            return assignment\n\n        # 对每一个真实框都进行iou计算，找到需要忽略的先验框\n        ingored_boxes = np.apply_along_axis(self.ignore_box, 1, boxes[:, :4])\n        # 取重合程度最大的先验框，并且获取这个先验框的index\n        ingored_boxes = ingored_boxes.reshape(-1, self.num_priors, 1)\n        # (num_priors)\n        ignore_iou = ingored_boxes[:, :, 0].max(axis=0)\n        # (num_priors)\n        ignore_iou_mask = ignore_iou > 0\n\n        #代表忽略此先验框，将ignore_iou_mask的序号下的先验框设为忽略\n        assignment[:, 4][ignore_iou_mask] = -1\n\n        # (n, num_priors, 5)encode_box将真实框进行编码，计算出训练使用的预测结果：即偏移信息\n        encoded_boxes = np.apply_along_axis(self.encode_box, 1, boxes[:, :4])\n        # 每一个真实框的编码后的值，和iou\n        # (n, num_priors)\n        encoded_boxes = encoded_boxes.reshape(-1, self.num_priors, 5)\n\n        #由于某些先验框会与多个真实框重合，所以要找iou最大的真实框进行对应\n        # 取重合程度最大的先验框，并且获取这个先验框的index\n        # (num_priors)\n        best_iou = encoded_boxes[:, :, -1].max(axis=0)\n        # (num_priors)\n        best_iou_idx = encoded_boxes[:, :, -1].argmax(axis=0)\n        # (num_priors)\n        best_iou_mask = best_iou > 0\n        # 某个先验框它属于哪个真实框\n        best_iou_idx = best_iou_idx[best_iou_mask]\n\n        assign_num = len(best_iou_idx)\n        # 保留重合程度最大的先验框的应该有的预测结果\n        # 哪些先验框存在真实框\n        encoded_boxes = encoded_boxes[:, best_iou_mask, :]\n\n        assignment[:, :4][best_iou_mask] = encoded_boxes[best_iou_idx, np.arange(assign_num), :4]\n        # 4代表为背景的概率，为0\n        # 1为正样本，代表有物体，0为负样本，代表背景，-1代表不要的框\n        assignment[:, 4][best_iou_mask] = 1\n        # 通过assign_boxes我们就获得了，输入进来的这张图片，应该有的预测结果是什么样子的\n        # assignment即为找到的合理先验框\n        return assignment\n\n    def decode_boxes(self, mbox_loc, mbox_priorbox):\n        \"\"\"\n        使用边框回归公式得到调整后的框\n        mbox_loc: RPN输出的先验框的调整参数\n        mbox_priorbox: 传入根据特征图生成好的先验框\n        \"\"\"\n        # 获得先验框的宽与高\n        prior_width = mbox_priorbox[:, 2] - mbox_priorbox[:, 0]\n        prior_height = mbox_priorbox[:, 3] - mbox_priorbox[:, 1]\n\n        # 获得先验框的中心点\n        prior_center_x = 0.5 * (mbox_priorbox[:, 2] + mbox_priorbox[:, 0])\n        prior_center_y = 0.5 * (mbox_priorbox[:, 3] + mbox_priorbox[:, 1])\n\n        # 真实框距离先验框中心的xy轴偏移情况\n        decode_bbox_center_x = mbox_loc[:, 0] * prior_width / 4\n        decode_bbox_center_x += prior_center_x\n        decode_bbox_center_y = mbox_loc[:, 1] * prior_height / 4\n        decode_bbox_center_y += prior_center_y\n\n        # 真实框的宽与高的求取\n        decode_bbox_width = np.exp(mbox_loc[:, 2] / 4)\n        decode_bbox_width *= prior_width\n        decode_bbox_height = np.exp(mbox_loc[:, 3] / 4)\n        decode_bbox_height *= prior_height\n\n        # 获取真实框的左上角与右下角\n        decode_bbox_xmin = decode_bbox_center_x - 0.5 * decode_bbox_width\n        decode_bbox_ymin = decode_bbox_center_y - 0.5 * decode_bbox_height\n        decode_bbox_xmax = decode_bbox_center_x + 0.5 * decode_bbox_width\n        decode_bbox_ymax = decode_bbox_center_y + 0.5 * decode_bbox_height\n\n        # 真实框的左上角与右下角进行堆叠\n        decode_bbox = np.concatenate((decode_bbox_xmin[:, None],\n                                      decode_bbox_ymin[:, None],\n                                      decode_bbox_xmax[:, None],\n                                      decode_bbox_ymax[:, None]), axis=-1)\n        # 为方便计算，框的坐标值设置在0-1，即防止超出0与1\n        decode_bbox = np.minimum(np.maximum(decode_bbox, 0.0), 1.0)\n        return decode_bbox\n\n    def detection_out(self, predictions, mbox_priorbox, num_classes, keep_top_k=300,confidence_threshold=0.5):\n        \"\"\"\n        初步选出300个建议框\n        predictions：RPN输出的结果，对每个先验框都要计算\n        mbox_priorbox：传入根据特征图生成好的先验框\n        \"\"\"\n\n        # 网络预测的结果\n        # x_class即置信度\n        mbox_conf = predictions[0]\n        # 先验框的调整参数\n        mbox_loc = predictions[1]\n        # 先验框\n        mbox_priorbox = mbox_priorbox\n        results = []\n        # 对每一个框进行处理\n        for i in range(len(mbox_loc)):\n            results.append([])\n            #得到调整后的框，这里是所有的框\n            decode_bbox = self.decode_boxes(mbox_loc[i], mbox_priorbox)\n            #选出含物体的框，并用NMS删除重叠框\n            for c in range(num_classes):\n                c_confs = mbox_conf[i, :, c]\n                #先进行对比，如果x_class的概率大于设置的置信度，认为框里有物体\n                c_confs_m = c_confs > confidence_threshold\n                if len(c_confs[c_confs_m]) > 0:\n                    # 取出得分高于confidence_threshold的框\n                    boxes_to_process = decode_bbox[c_confs_m]\n                    # 获取我们所选出的框的置信度用于NMS\n                    confs_to_process = c_confs[c_confs_m]\n                    # 进行iou的非极大抑制，删除重叠框\n                    feed_dict = {self.boxes: boxes_to_process,\n                                 self.scores: confs_to_process}\n                    idx = self.sess.run(self.nms, feed_dict=feed_dict)\n                    # 取出在非极大抑制中效果较好的内容\n                    good_boxes = boxes_to_process[idx]\n                    confs = confs_to_process[idx][:, None]\n                    # 将label、置信度、框的位置进行堆叠，label代表是否有物体，作用其实不大，因为置信度也可以反映\n                    labels = c * np.ones((len(idx), 1))\n                    c_pred = np.concatenate((labels, confs, good_boxes),\n                                            axis=1)\n                    # 添加进result里\n                    results[-1].extend(c_pred)\n            #将以上得到的框排序，选出前k个作为RPN的输出框，默认k=300\n            if len(results[-1]) > 0:\n                # 按照置信度进行排序\n                results[-1] = np.array(results[-1])\n                argsort = np.argsort(results[-1][:, 1])[::-1]\n                results[-1] = results[-1][argsort]\n                # 选出置信度最大的keep_top_k个\n                results[-1] = results[-1][:keep_top_k]\n        # 获得，在所有预测结果里面，置信度比较高的框\n        # 另外，利用先验框和RPN的预测结果x_class,x_regr，调整到真实框（预测框）的位置\n        return results\n\n    def nms_for_out(self, all_labels, all_confs, all_bboxes, num_classes, nms):\n        results = []\n        nms_out = tf.image.non_max_suppression(self.boxes, self.scores,\n                                               self._top_k,\n                                               iou_threshold=nms)\n        for c in range(num_classes):\n            c_pred = []\n            mask = all_labels == c\n            if len(all_confs[mask]) > 0:\n                # 取出得分高于confidence_threshold的框\n                boxes_to_process = all_bboxes[mask]\n                confs_to_process = all_confs[mask]\n                # 进行iou的非极大抑制\n                feed_dict = {self.boxes: boxes_to_process,\n                             self.scores: confs_to_process}\n                idx = self.sess.run(nms_out, feed_dict=feed_dict)\n                # 取出在非极大抑制中效果较好的内容\n                good_boxes = boxes_to_process[idx]\n                confs = confs_to_process[idx][:, None]\n                # 将label、置信度、框的位置进行堆叠。\n                labels = c * np.ones((len(idx), 1))\n                c_pred = np.concatenate((labels, confs, good_boxes), axis=1)\n            results.extend(c_pred)\n        return results", "meta": {"hexsha": "90c5970a5e3c29de35e7fe2c74ca5e54b9d3dba6", "size": 11950, "ext": "py", "lang": "Python", "max_stars_repo_path": "net/tools.py", "max_stars_repo_name": "TangZhenchaoTZC/Keras-mask-detection", "max_stars_repo_head_hexsha": "325679d06a12a90b2552ed7d447298a23e3b9d57", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-05-26T15:13:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-27T02:57:27.000Z", "max_issues_repo_path": "net/tools.py", "max_issues_repo_name": "TangZhenchaoTZC/Keras-mask-detection", "max_issues_repo_head_hexsha": "325679d06a12a90b2552ed7d447298a23e3b9d57", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "net/tools.py", "max_forks_repo_name": "TangZhenchaoTZC/Keras-mask-detection", "max_forks_repo_head_hexsha": "325679d06a12a90b2552ed7d447298a23e3b9d57", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0573248408, "max_line_length": 110, "alphanum_fraction": 0.5671129707, "include": true, "reason": "import numpy", "num_tokens": 4026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.1972623102542132}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom .GetFieldLine import GetFieldLine\n\ndef PlotFieldLineDensity(pos,Params,fig=None,maps=[1,1,0,0],Overplot=False,**kwargs):\n\t'''\n\tSimple routine to plot the modelled plasma mass density along a field line.\n\t\n\tArgs\n\t=====\n\t\tpos: 3 element ndarray containing the cartesian position to trace from in Rp.\n\t\tParams: For power law: 2-element array/list [p_eq,power].\n\t\t\t\tFor Sandhu model: 5-element array/list [n0,alpha,a,beta,mav0] (see GetSandhuParams).\n\t\tfig: Pyplot instance, useful if plotting as a subplot on a pre-existing figure, by default will create new figure.\n\t\tmaps: 4 element list containing subplot information [xmaps,ymaps,xmap,ymap] where xmaps and ymaps represent the number of subplots in the x and y directions and xmap and ymap are the specific x and y indices to plot to.\n\t\tOverplot: When set to True, this will inhibit the creation of a new subplot, fig must be supplied with a pre-existing figure, where the routine will plot over.\n\n\tKeyword Args\n\t============\n\t\tThe following keyword argument form **kwargs - they are completely \n\t\toptional and depend on which model is being used.\n\t\t\n\t\tModel\t\tkwargs\n\t\tT89\t\t\tiopt,Kp,Vx,Vy,Vz,tilt,CoordIn,CoordOut,Alt,MaxLen,DSMax,FlattenSingleTraces,Verbose\n\t\tT96\t\t\tparmod,Pdyn,SymH,By,Bz,Vx,Vy,Vz,tilt,CoordIn,CoordOut,Alt,MaxLen,DSMax,FlattenSingleTraces,Verbose\n\t\tT01\t\t\tparmod,Pdyn,SymH,By,Bz,Vx,Vy,Vz,tilt,CoordIn,CoordOut,Alt,MaxLen,DSMax,FlattenSingleTraces,Verbose\n\t\tTS05\t\tparmod,Pdyn,SymH,By,Bz,Vx,Vy,Vz,tilt,CoordIn,CoordOut,Alt,MaxLen,DSMax,FlattenSingleTraces,Verbose\n\t\tKT17\n\t\t\n\t\t\n\t\tMaxStepSize: Trace step size maximum in Rp (default = None).\n\t\tModelArgs: \tTuple containing arguments for the magnetic field models, \n\t\t\t\t\twhen set to None, a set of default parameters are used.\n\t\t\t\t\t'T89'|'T96'|'T01'|'TS05'|'T89c'|'T96c'|'T01c'|'TS05c': \n\t\t\t\t\t\tModelArgs = (Date,ut,CoordIn,CoordOut,Alt,MaxLen,DSMax,iopt,parmod,tilt,Vx,Vy,Vz)\n\t\t\t\t\t\t****NOTE****\n\t\t\t\t\t\tWhen using models 'T89'|'T96'|'T01'|'TS05' - the iopt,parmod,tilt,Vx,Vy,Vz parameters need not\n\t\t\t\t\t\tbe specified as they will be calculated automatically within the Geopack model from Omni data\n\t\t\t\t\t\tusing the Date and ut parameters\n\t\t\t\t\t\t\n\t\t\t\t\t\tTo use those parameters, add 'c' tot he model name string: 'T89c'|'T96c'|'T01c'|'TS05c'\n\t\t\t\t\t\tThen all parameters will be needed\n\t\t\t\t\t\t\n\t\t\t\t\t\t************\n\t\t\t\t\t\tDate:  Date in format yyyymmdd.\n\t\t\t\t\t\tUT: Time in format hh.hh (hh + mm/60.0 + ss/3600.0).\n\t\t\t\t\t\tCoordIn: Coordinate system of input position, by default 'SM' (Solar-Magnetic), can be set to 'GSM' (Geocentric Solar Magnetospheric).\n\t\t\t\t\t\tCoordOut: Coordinate system of output positions and field vectors, by default 'SM', can be set to 'GSM'.\n\t\t\t\t\t\tAlt: Altitude to stop tracing at - default = 100km\n\t\t\t\t\t\tMaxLen: maximum number of trace steps\n\t\t\t\t\t\tDSMax: Maximum step size\n\t\t\t\t\t\tiopt: integer for controlling T89c model\n\t\t\t\t\t\tparmod: 10-element floating point array to control T96c,T01c and TS05c models,\n\t\t\t\t\t\t\t\tfor T96:\n\t\t\t\t\t\t\t\t\tparmod[0] = Pdyn (nPa)\n\t\t\t\t\t\t\t\t\tparmod[1] = Dst (nT)\n\t\t\t\t\t\t\t\t\tparmod[2] = IMF By (nT)\n\t\t\t\t\t\t\t\t\tparmod[3] = IMF Bz (nT)\n\t\t\t\t\t\t\t\tfor T01:\n\t\t\t\t\t\t\t\t\tparmod[0] = Pdyn (nPa)\n\t\t\t\t\t\t\t\t\tparmod[1] = Dst (nT)\n\t\t\t\t\t\t\t\t\tparmod[2] = IMF By (nT)\n\t\t\t\t\t\t\t\t\tparmod[3] = IMF Bz (nT)\n\t\t\t\t\t\t\t\t\tparmod[4] = G1 parameter (See Tsyganenko [2001])\n\t\t\t\t\t\t\t\t\tparmod[5] = G2 parameter (See Tsyganenko [2001])\n\t\t\t\t\t\t\t\tfor TS05:\n\t\t\t\t\t\t\t\t\tparmod[0] = Pdyn (nPa)\n\t\t\t\t\t\t\t\t\tparmod[1] = Dst (nT)\n\t\t\t\t\t\t\t\t\tparmod[2] = IMF By (nT)\n\t\t\t\t\t\t\t\t\tparmod[3] = IMF Bz (nT)\n\t\t\t\t\t\t\t\t\tparmod[4] = W1 parameter (See Tsyganenko and Sitnov [2005])\n\t\t\t\t\t\t\t\t\tparmod[5] = W2 parameter (See Tsyganenko and Sitnov [2005])\t\n\t\t\t\t\t\t\t\t\tparmod[6] = W3 parameter (See Tsyganenko and Sitnov [2005])\n\t\t\t\t\t\t\t\t\tparmod[7] = W4 parameter (See Tsyganenko and Sitnov [2005])\n\t\t\t\t\t\t\t\t\tparmod[8] = W5 parameter (See Tsyganenko and Sitnov [2005])\n\t\t\t\t\t\t\t\t\tparmod[9] = W6 parameter (See Tsyganenko and Sitnov [2005])\t\t\n\t\t\t\t\t\ttilt: Geodipole tilt angle - if set to NaN then will be calculated using Date and ut\n\t\t\t\t\t\tVx,Vy,Vz: IMF velocity components\n\t\t\t\t\tKT17:\n\t\t\t\t\t\tModelArgs = (Rsun,DistIndex,MaxLen,InitStep,MaxStepSize,LimType)\n\t\t\t\t\t\tRsun: radial distance from the Sun in AU\n\t\t\t\t\t\tDistIndex: Disturbance index (0.0 - 100.0)\n\t\t\t\t\t\tMaxLen: Maximum number of steps for trace\n\t\t\t\t\t\tInitStep: Starting step size.\n\t\t\t\t\t\tMaxStepSize: Maximum step size\n\t\t\t\t\t\tLimType: Integer value to define where to stop the field trace (default 0):\n\t\t\t\t\t\t\t0: Terminate trace at planet surface and magnetopause\n\t\t\t\t\t\t\t1: Confine to box -6 < x < 2, -4 < y < 4, -4 < z < 4\n\t\t\t\t\t\t\t2: Confine to box and terminate at planet\n\t\t\t\t\t\t\t3: Terminate trace at planet\n\t\t\t\t\t\t\t4: Trace to MP, Planet and stop at 10Rm\n\t\t\t\t\t\t\t\t\n\t\t\t\t\tKT14:\n\t\t\t\t\t\tModelArgs = (MaxLen,InitStep,MaxStep,LimType,Rsm,t1,t2)\n\t\t\t\t\t\tMaxLen: Maximum number of steps for trace\n\t\t\t\t\t\tInitStep: Starting step size.\n\t\t\t\t\t\tMaxStepSize: Maximum step size\n\t\t\t\t\t\tLimType: Integer value to define where to stop the field trace (default 0):\n\t\t\t\t\t\t\t0: Terminate trace at planet surface and magnetopause\n\t\t\t\t\t\t\t1: Confine to box -6 < x < 2, -4 < y < 4, -4 < z < 4\n\t\t\t\t\t\t\t2: Confine to box and terminate at planet\n\t\t\t\t\t\t\t3: Terminate trace at planet\n\t\t\t\t\t\t\t4: Trace to MP, Planet and stop at 10Rm\n\t\t\t\t\t\tRsm: Subsolar magnetopause radius (default=1.42).\n\t\t\t\t\t\tt1: Tail disk current strength (default=7.37).\n\t\t\t\t\t\tt2: Tail quasi-harris current sheet strength (default=2.16).\n\t\t\t\t\tDipole:\n\t\t\t\t\t\tModelArgs = [Beq]\n\t\t\t\t\t\tBeq: Megnatic field strength at equator in nT (Default=-31200.0).\n\t\tDelta: Separation between two traced field lines\n\t\tPolarization: 'none'|'toroidal'|'poloidal'\n\t\tCore: This only applies to the KT14/KT17 field, as it will include tracing to the core of the planet rather than the surface.\t\n\n\t\t\n\tReturns\n\t========\n\t\tpyplot instance\n\t\n\t'''\n\ttmp = GetFieldLine(pos,**kwargs)\n\tPolarization = kwargs.get('Polarization','none')\n\tif Polarization == 'none':\n\t\tT,s = tmp\n\telse:\n\t\tT,s,h = tmp\n\t\t\n\t\n\tBm = np.sqrt(T.Bx**2.0 + T.By**2.0 + T.Bz**2.0).astype('float32')\n\tR = np.sqrt(T.x**2.0 + T.y**2.0 + T.z**2.0)\n\tmaxR = np.float32(R.max())\n\t\n\tif np.size(Params) == 2:\n\t\tp = Params[0]*(maxR/R)**Params[1]\n\t\tlabel='$\\\\rho_{eq} = $'+'{:5.1f}'.format(Params[0])+', $m = $'+'{:3.1f}'.format(Params[1])\n\telse:\n\t\tRnorm = R/maxR\n\t\tne = Params[2]*np.exp(-0.5*((Rnorm-1.0)/0.1)**2) + Params[0]*Rnorm**(-Params[1])\n\t\tmav = Params[4]*Rnorm**(-Params[3])\n\t\tp = ne*mav\n\t\tlabel='$\\\\rho_{eq} = $'+'{:5.1f}'.format(Params[0]*Params[4])\n\t\n\tif fig is None:\n\t\tfig = plt\n\t\tfig.figure()\n\tif hasattr(fig,'Axes'):\t\n\t\tax = fig.subplot2grid((maps[1],maps[0]),(maps[3],maps[2]))\n\telse:\n\t\tprint('here')\n\t\tax = fig\n\n\t\t\t\n\tax.plot(s,p,label=label)\n\tax.legend()\n\tax.set_ylabel('$\\\\rho$ (amu cm$^{-3}$)')\n\tax.set_xlabel('$x$ (km)')\n\treturn ax\n\t\n", "meta": {"hexsha": "2a1a5862d6b96afaefcde2372ac02672a69b9de1", "size": 6778, "ext": "py", "lang": "Python", "max_stars_repo_path": "MHDWaveHarmonics/PlotFieldLineDensity.py", "max_stars_repo_name": "mattkjames7/MHDWaveHarmonics", "max_stars_repo_head_hexsha": "ac8fcc5bf9190d300774c4e114a6ec4be865f014", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-11T13:47:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T13:47:00.000Z", "max_issues_repo_path": "MHDWaveHarmonics/PlotFieldLineDensity.py", "max_issues_repo_name": "mattkjames7/MHDWaveHarmonics", "max_issues_repo_head_hexsha": "ac8fcc5bf9190d300774c4e114a6ec4be865f014", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MHDWaveHarmonics/PlotFieldLineDensity.py", "max_forks_repo_name": "mattkjames7/MHDWaveHarmonics", "max_forks_repo_head_hexsha": "ac8fcc5bf9190d300774c4e114a6ec4be865f014", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.8987341772, "max_line_length": 221, "alphanum_fraction": 0.6555030983, "include": true, "reason": "import numpy", "num_tokens": 2228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.1972623102542132}}
{"text": "#!/usr/bin/env python3\r\nimport logging\r\nfrom enum import Enum\r\n\r\nimport numpy as np\r\n\r\n\r\nlog = logging.getLogger('LabberDriver')\r\n\r\n\r\nclass PulseType(Enum):\r\n    \"\"\"Define possible qubit pulse types.\"\"\"\r\n\r\n    XY = 'XY'\r\n    Z = 'Z'\r\n    DELAY = 'Delay'\r\n    READOUT = 'Readout'\r\n    NONE = 'None'\r\n\r\nclass PulseShape(Enum):\r\n    \"\"\"Define possible qubit pulses shapes.\"\"\"\r\n\r\n    GAUSSIAN = 'Gaussian'\r\n    SQUARE = 'Square'\r\n    ZBIAS = 'Z-Bias'\r\n    READ_FAST = 'Read_fast'\r\n    CUSTOM = 'Custom'\r\n\r\nclass Pulse(object):\r\n    \"\"\"Represents physical pulses played by an AWG.\r\n\r\n    Parameters\r\n    ----------\r\n    pulse_type : :obj:`PulseType`\r\n        Pulse type (the default is PulseType.XY).\r\n    shape : :obj:`PulseShape`\r\n        Pulse shape (the default is PulseShape.GAUSSIAN).\r\n\r\n    Attributes\r\n    ----------\r\n    length : float\r\n        Pulse length\r\n    amplitude : float\r\n        Pulse amplitude.\r\n    frequency : float\r\n        Carrier frequency of pulse.\r\n    phase : float\r\n        Pulse phase.\r\n    use_drag : bool\r\n        If True, applies DRAG correction.\r\n    drag_coefficient : float\r\n        Drag coefficient.\r\n    drag_detuning : float\r\n        Applies a frequnecy detuning for DRAG pulses.\r\n    gaussian_num_STDs : float\r\n        The truncation range of Gaussian pulses,\r\n        in units of standard deviations.\r\n    square_rise_time : float\r\n        How fast does the pulse edge rise\r\n\r\n    \"\"\"\r\n\r\n    def __init__(self,  pulse_type=PulseType.Z, shape=PulseShape.SQUARE):\r\n\r\n        # set variables\r\n        self.pulse_type = pulse_type\r\n        self.shape = shape\r\n\r\n        self.length = 30e-9\r\n        self.amplitude = 1.0\r\n        self.frequency = 0.0\r\n        self.phase = 0.0\r\n        self.use_drag = False\r\n        self.drag_coefficient = 0.0\r\n        self.drag_detuning = 0.0\r\n        self.gaussian_num_stds = 3.0\r\n        self.square_rise_time = 2e-9\r\n\r\n\r\n    def calculate_envelope(self, t,): #args will be for flux modulation on the Z-bias\r\n        \"\"\"Calculate pulse envelope.\r\n\r\n        Parameters\r\n        ----------\r\n        t : numpy array\r\n            Array with time values for which to calculate the pulse envelope.\r\n\r\n        Returns\r\n        -------\r\n        envelope : numpy array\r\n            Array containing pulse envelope.\r\n\r\n        \"\"\"\r\n        dt = t[1] - t[0]\r\n        len_pulse = len(t)\r\n        envelope = np.zeros(len_pulse) #initialize envelope array\r\n\r\n        if self.shape == PulseShape.SQUARE:\r\n\r\n            len_edge = np.int(np.ceil(self.square_rise_time/dt)+1) #calculate length of rising edge in samples\r\n\r\n            if len_pulse > 2*len_edge: #adding linear rising and falling edges to pulse if length of pulse > 2* length edge\r\n                envelope[:len_edge] = np.linspace(0,1,len_edge)\r\n                envelope[-len_edge:] = np.linspace(1,0,len_edge)\r\n                envelope[len_edge:-len_edge] = 1\r\n\r\n            else: #if length of pulse is smaller than 2*length of edge, then make an envelope with only falling and rising edges\r\n                halfway_t = np.int(np.floor(len_pulse/2)) #halfway point of the pulse, in samples\r\n                envelope[:halfway_t] = np.linspace(0,1, halfway_t)\r\n                envelope[halfway_t:] = np.linspace(1,0, len_pulse - halfway_t) #I do len_pulse - halfway_t instead of just halfway_t if the number of samples is odd\r\n\r\n        elif self.shape == PulseShape.GAUSSIAN:\r\n            halfway_t = int(np.floor(len_pulse/2)) #calculate midpoint of pulse, in samples\r\n            t0 = t[halfway_t] #midpoint of pulse\r\n            σ = self.length/(2*self.gaussian_num_stds) #calculate σ of gaussian based on pulse length and num of std deviations we want to fit\r\n            envelope = np.exp( -(t-t0)**2/(2*σ**2) )\r\n            envelope = envelope - envelope.min() #make pulse start at 0\r\n            envelope = envelope/envelope.max()\r\n\r\n        elif self.shape == PulseShape.READ_FAST: #for readout pulses with a starting high amplitude transient region to ring-up RO resonator faster\r\n            # Below I am hardcoding length of transient here to be 1/4 of pulse length, for it's shape to be Gaussian to minimize spectal leakage, and for it's amplitude to be 2.5 times larger than the steady region\r\n            halfway_t = int(np.floor(len_pulse/8)) #halfway_t is midpoint of transient region, in samples\r\n            t0 = t[halfway_t] #midpoint of transient region\r\n            σ = (self.length/4)/(2*3) #I am harcoding 3 gaussian standard deviations here\r\n            envelope[:halfway_t] = 2.5*np.exp( -(t[:halfway_t]-t0)**2/(2*σ**2) ) #the first half of the transient region is a pure Gaussian\r\n            envelope[halfway_t:2*halfway_t] = 1.5*np.exp( -(t[halfway_t:2*halfway_t]-t0)**2/(2*σ**2) )\r\n            envelope[halfway_t:] = envelope[halfway_t:] + np.ones(len_pulse-halfway_t) #the second region of the transient region is a down-scaled gaussian + the steady part; such that the second half of the transient smoothly converges to the steady part\r\n            envelope = envelope - envelope.min()\r\n\r\n        envelope = envelope * self.amplitude\r\n\r\n        return envelope\r\n\r\n        #if self.shape == PulseShape.ZBIAS: #Z-bias pulse consists of starting from the last Z-bias value and ramping to a new Z-bias value\r\n            #len_edge = np.int(np.ceil(self.square_rise_time/dt)+1) #calculate length of rising edge in samples\r\n            #if len_pulse > len_edge:\r\n            #    envelope[:len_edge] = np.linspace(last_value_Zbias,self.amplitude,len_edge) #make rising edge start from last Z-bias value and end at the new Z-bias level\r\n            #    envelope[len_edge:] = self.amplitude\r\n            #else:\r\n            #    envelope = np.linspace(last_value_Zbias, self.amplitude, len_pulse) #if length of pulse is smaller than rising edge, make the whole Z-bias pulse a rising edge\r\n            #envelope = np.ones(len_pulse) * self.amplitude + args[0] * np.cos(2*pi*args[1] * 1e6* (t-t[0]))\r\n            #return envelope\r\n\r\n\r\n    def calculate_waveform(self, t, IQ_ratio = 1.0, IQ_skew = 0.0, I_offset = 0.0, Q_offset = 0.0, custom_waveform = None,\r\n                            Z_bias_mod_amp = 0.0, Z_bias_mod_freq = 0.0): #custom waveform input is for Custom pulses\r\n        \"\"\"Calculate pulse waveform including carrier frequency, phase offsets, IQ mixer compensations, and DRAG implementation\r\n\r\n        Parameters\r\n        ----------\r\n        t : numpy array\r\n            Array with time values for which to calculate the pulse waveform.\r\n\r\n        Returns\r\n        -------\r\n        waveform : numpy array\r\n            Array containing pulse waveform.\r\n\r\n        \"\"\"\r\n        π = np.pi\r\n        if self.shape == PulseShape.CUSTOM: #make the \"envelope\" the custom waveform for a \"Custom\" Pulse\r\n            envelope = custom_waveform\r\n        elif self.shape == PulseShape.ZBIAS:\r\n            envelope = np.ones(len(t)) * self.amplitude + Z_bias_mod_amp * np.cos(2*np.pi*Z_bias_mod_freq * 1e6* (t-t[0]))\r\n        else:\r\n            envelope = self.calculate_envelope(t)\r\n        ω = self.frequency * 2 * π\r\n        dt = t[1]-t[0]\r\n\r\n        if self.pulse_type == PulseType.XY: #below I generate I/Q waveforms with the IQ parameters and DRAG\r\n            DRAG_δ = self.drag_detuning * 2 * π\r\n            I_waveform = (envelope * np.cos( (ω + DRAG_δ) * t + self.phase ) +\r\n                          -self.drag_coefficient * np.gradient(envelope)/dt * np.sin( (ω + DRAG_δ) * t + self.phase ) ) + I_offset\r\n            Q_waveform = IQ_ratio*(envelope * np.sin( (ω + DRAG_δ) * t + self.phase + IQ_skew ) -\r\n                          -self.drag_coefficient * np.gradient(envelope)/dt * np.cos( (ω + DRAG_δ) * t + self.phase + IQ_skew ) ) + Q_offset\r\n            waveform = I_waveform + 1j*Q_waveform\r\n\r\n        elif self.pulse_type == PulseType.Z:\r\n            t_noPhase = t-t[0] #make sure pulse doesn't have any intrinsic phase regardless of when it starts\r\n            waveform = envelope * np.cos(ω * t_noPhase + self.phase)\r\n\r\n        elif self.pulse_type == PulseType.READOUT:\r\n            I_waveform = envelope * np.cos(ω * t + self.phase) + I_offset\r\n            Q_waveform = envelope * IQ_ratio * np.sin(ω * t + self.phase + IQ_skew) + Q_offset\r\n            waveform = I_waveform + 1j*Q_waveform\r\n\r\n        elif self.pulse_type == PulseType.NONE or self.pulse_type == PulseType.DELAY:\r\n            waveform = np.zeros(len(t))\r\n\r\n        return waveform\r\n\r\nif __name__ == '__main__':\r\n    pass\r\n", "meta": {"hexsha": "fce2543fd5ecf66b1ba9a31da781016bbd85a880", "size": 8453, "ext": "py", "lang": "Python", "max_stars_repo_path": "Painter_Arbitrary_Sequence_Generator/pulses.py", "max_stars_repo_name": "sherryue123/Labber-Drivers", "max_stars_repo_head_hexsha": "90fc217db4158857f650122cd780f18fcf6d9a78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-06-18T21:14:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-11T19:05:35.000Z", "max_issues_repo_path": "Painter_Arbitrary_Sequence_Generator/pulses.py", "max_issues_repo_name": "sherryue123/Labber-Drivers", "max_issues_repo_head_hexsha": "90fc217db4158857f650122cd780f18fcf6d9a78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Painter_Arbitrary_Sequence_Generator/pulses.py", "max_forks_repo_name": "sherryue123/Labber-Drivers", "max_forks_repo_head_hexsha": "90fc217db4158857f650122cd780f18fcf6d9a78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-03T16:54:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-03T16:54:28.000Z", "avg_line_length": 43.5721649485, "max_line_length": 256, "alphanum_fraction": 0.609606057, "include": true, "reason": "import numpy", "num_tokens": 2114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.1972623102542132}}
{"text": "\"\"\"\nFunctions for explaining classifiers that use Multimodal data.\nDeveloped initially for the hateful memes challenge in mmf\n\"\"\"\n\nimport copy\nfrom functools import partial\nimport numpy as np\nimport scipy as sp\nimport sklearn\nfrom sklearn.utils import check_random_state\nfrom tqdm.auto import tqdm\n\nfrom lime.wrappers.scikit_image import SegmentationAlgorithm\nfrom mmxai.interpretability.classification.lime.lime_base import LimeBase\n\nfrom lime.lime_text import IndexedString, TextDomainMapper\nfrom lime.exceptions import LimeError\n\nfrom sklearn.calibration import CalibratedClassifierCV\nfrom PIL import Image\nfrom skimage.segmentation import mark_boundaries\n\n# from object_detection import *\n\n\nclass MultiModalExplanation(object):\n    def __init__(\n        self,\n        image,\n        segments,\n        domain_mapper,\n        n_txt_features,\n        n_img_features,\n        n_detection_features,\n        ratio_txt_img,\n        detection_label,\n        mode=\"classification\",\n        class_names=None,\n        random_state=None,\n    ):\n        \"\"\"Init function.\n\n        Args:\n            image: 3d numpy array\n            segments: 2d numpy array, with the output from skimage.segmentation\n            domain_mapper: Maps text feature ids to words or word-positions\n            n_txt_features:number of words to include in explanation\n            n_img_features: number of superpixels to include in explanation\n            n_detection_features:number of detected objects to include in explanation\n            ratio_txt_img: weight ratio between text and image features\n            detection_label: numpy array of names of detected objects\n            mode: what kind of model for this object, classification default\n            class_names: list of class names, ordered according to whatever the\n                classifier is using. If not present, class names will be '0',\n                '1', ...\n            random_state: an integer or numpy.RandomState that will be used to\n                generate random numbers. If None, the random state will be\n                initialized using the internal numpy seed.\n        \"\"\"\n        self.image = image\n        self.segments = segments\n        self.random_state = random_state\n        self.mode = mode\n        self.domain_mapper = domain_mapper\n        self.n_txt_features = n_txt_features\n        self.n_img_features = n_img_features\n        self.n_detection_features = n_detection_features\n        self.ratio_txt_img = ratio_txt_img\n        self.detection_label = detection_label\n        self.local_exp = {}\n        self.intercept = {}\n        self.score = {}\n        self.local_pred = {}\n        self.unsorted_weights = {}\n\n        # divide explanations of the two modalities\n        self.local_exp_img = {}\n        self.local_exp_txt = {}\n        self.local_exp_det = {}\n\n        if mode == \"classification\":\n            self.class_names = class_names\n            self.top_labels = None\n            self.predict_proba = None\n\n    def get_image_and_mask(\n        self,\n        label,\n        positive_only=True,\n        negative_only=False,\n        hide_rest=False,\n        num_features=5,\n        min_weight=0.0,\n    ):\n        \"\"\"\n\n        Args:\n            label: label to explain\n            positive_only: if True, only take superpixels that positively contribute to\n                the prediction of the label.\n            negative_only: if True, only take superpixels that negatively contribute to\n                the prediction of the label. If false, and so is positive_only, then both\n                negativey and positively contributions will be taken.\n                Both can't be True at the same time\n            hide_rest: if True, make the non-explanation part of the return\n                image gray\n            num_features: number of superpixels to include in explanation\n            min_weight: minimum weight of the superpixels to include in explanation\n        Returns:\n            (image, mask), where image is a 3d numpy array and mask is a 2d\n            numpy array that can be used with\n            skimage.segmentation.mark_boundaries\n        \"\"\"\n\n        if label not in self.local_exp_img:\n            raise KeyError(\"Label not in explanation\")\n        if positive_only & negative_only:\n            raise ValueError(\n                \"Positive_only and negative_only cannot be true at the same time.\"\n            )\n        segments = self.segments\n        image = self.image\n        exp = self.local_exp_img[label]\n        mask = np.zeros(segments.shape, segments.dtype)\n        if hide_rest:\n            temp = np.zeros(self.image.shape)\n        else:\n            temp = self.image.copy()\n        if positive_only:\n            fs = [x[0] for x in exp if x[1] > 0 and x[1] > min_weight][:num_features]\n        if negative_only:\n            fs = [x[0] for x in exp if x[1] < 0 and abs(x[1]) > min_weight][\n                :num_features\n            ]\n        if positive_only or negative_only:\n            for f in fs:\n                temp[segments == f] = image[segments == f].copy()\n                mask[segments == f] = 1\n            return temp, mask\n        else:\n            for f, w in exp[:num_features]:\n                if np.abs(w) >= min_weight:\n                    c = 0 if w < 0 else 1\n                    mask[segments == f] = -1 if w < 0 else 1\n                    temp[segments == f] = image[segments == f].copy()\n                    temp[segments == f, c] = np.max(image)\n            return temp, mask\n\n    def as_list(self, label=1, **kwargs):\n        \"\"\"\n        Returns the explanation as a list.\n        Args:\n            label: desired label. If you ask for a label for which an\n                explanation wasn't computed, will throw an exception.\n                Will be ignored for regression explanations.\n            kwargs: keyword arguments, passed to domain_mapper\n        Returns:\n            list of tuples (representation, weight), where representation is\n            given by domain_mapper. Weight is a float.\n        \"\"\"\n        label_to_use = label\n        ans = self.domain_mapper.map_exp_ids(self.local_exp_txt[label_to_use], **kwargs)\n        ans = [(x[0], float(x[1])) for x in ans]\n        return ans\n\n    def get_explanation(self, label, num_features=10, which_exp=\"positive\"):\n\n        # the explanation to display:\n        \"\"\"\n        :param label: label to explain\n        :param num_features: how many top features to display\n        :param which_exp: want features that encourage or discourage the dicision (label)\n        :return:\n            text_message: informative message to interpret text features\n            img_message: informative message to interpret image features\n            txt_exp_list: text part of the explanation, ready to display\n            temp, mask: image part of the explanation, ready to display\n        \"\"\"\n        this_exp = np.array(self.local_exp[label])\n\n        if which_exp == \"positive\":\n            positives = this_exp[this_exp[:, 1] >= 0]\n        else:  # negative\n            positives = this_exp[this_exp[:, 1] < 0]\n\n        if positives.shape[0] < num_features:\n            num_features = positives.shape[0]\n        top_exp = positives[:num_features]\n        top_exp_unique, top_idx = np.unique(top_exp[:, 0], return_index=True)\n\n        txt_exp = top_exp[top_exp[:, 0] < self.n_txt_features]\n        n_txt_exp = txt_exp.shape[0]\n        txt_top_idx = []\n        for txt_feature in txt_exp:\n            txt_top_idx.append(top_idx[top_exp_unique == txt_feature[0]] + 1)\n\n        img_exp = top_exp[self.n_txt_features <= top_exp[:, 0]]\n        img_exp = img_exp[img_exp[:, 0] < (self.n_txt_features + self.n_img_features)]\n        n_img_exp = img_exp.shape[0]\n        img_top_idx = []\n        for img_feature in img_exp:\n            img_top_idx.append(top_idx[top_exp_unique == img_feature[0]] + 1)\n\n        # detection features\n        det_exp = top_exp[top_exp[:, 0] >= self.n_txt_features + self.n_img_features]\n        n_det_exp = det_exp.shape[0]\n        det_top_idx = []\n        for det_feature in det_exp:\n            det_top_idx.append(\n                det_feature[0] - n_txt_exp - n_img_exp\n            )  # index for retrieving the labels\n\n        if n_det_exp != 0:\n            readable_exp_det = (\n                f\" Also, we have detected {n_det_exp} types \"\n                f\"of objects from the input image that can be the reason for the decision, they are:\"\n            )\n            for i in det_top_idx:\n                readable_exp_det += str(self.detection_label[i])\n        else:\n            readable_exp_det = (\n                \" No objects in the image contributed to the model decision\"\n            )\n\n        # explanation of explanations\n        readable_exp_txt = \"\"\n        readable_exp_img = \"\"\n        if n_txt_exp > 0:\n            readable_exp_txt = f\"{n_txt_exp} are from the text (the top\"\n            for i in txt_top_idx:\n                readable_exp_txt += str(i)\n            readable_exp_txt += \"th), \"\n        else:\n            readable_exp_txt += \"none are from the words, \"\n\n        if n_img_exp > 0:\n            readable_exp_img = f\"{n_img_exp} are from the image (the top\"\n            for j in img_top_idx:\n                readable_exp_img += str(j)\n            readable_exp_img += (\n                \"th, some adjacent regions might merge into a larger area).\"\n            )\n        else:\n            readable_exp_img += \"none are from the image pixel areas.\"\n\n        txt_exp_list = np.array(self.as_list(label), dtype=\"object\")\n\n        # return explanations upon request\n        if which_exp == \"positive\":\n            # txt_list = txt_exp_list[txt_exp_list[:, 1] >= 0]\n            temp, mask = self.get_image_and_mask(\n                label, num_features=n_img_exp, positive_only=True\n            )\n        else:\n            # txt_list = txt_exp_list[txt_exp_list[:, 1] < 0]\n            temp, mask = self.get_image_and_mask(\n                label, num_features=n_img_exp, positive_only=False, negative_only=True\n            )\n        # txt_list = txt_list[:n_txt_exp]\n\n        # image and text hover display message\n        label_decision = \"\"\n        if label == 1:\n            label_decision = \"hateful\"\n        else:\n            label_decision = \"not hateful\"\n\n        txt_message = (\n            f\"For this result, the value associated with each word indicates how much it pushes \"\n            f\"the model towards making a {label_decision} decision.\"\n        )\n\n        img_message = (\n            f\"Your image has been segmented into {self.n_img_features} small pixel areas, \"\n            f\"the ones that most encourage (or discourage) your \"\n            f\"model decision has been marked by the yellow boundaries.\"\n        )\n\n        top_message = (\n            f\"Each small pixel area in your image input and each distinct word \"\n            f\"in your text input are called an interpretable feature. There are \"\n            f\"{self.n_img_features + self.n_txt_features} features in total ({self.n_img_features} \"\n            f\"pixel areas and {self.n_txt_features} words). Among the top 10 \"\n            f\"such features that encourage (or discourage) your model decision, \"\n        )\n        top_message = top_message + readable_exp_txt + readable_exp_img\n\n        ratio_message = self.get_txt_img_ratio()\n\n        # format new line as html\n        img_message = \"<p>\" + img_message + \"</p><p>\" + top_message + \"</p>\"\n        img_message = img_message + ratio_message\n        return txt_message, img_message, txt_exp_list, temp, mask\n\n    def get_txt_img_ratio(self):\n        \"\"\"\n        Get informative message about the weight ratio between text and image features\n        Return:\n            words: informative string message to interpret the relative weight of text and image features\n        \"\"\"\n        img_percentage = 1 / (1 + self.ratio_txt_img)\n        txt_percentage = 1 - img_percentage\n        words = (\n            f\"For this prediction, the relative importance of \"\n            f\"text and image inputs to your model decision are respectively {round(100*txt_percentage, 2)}% \"\n            f\"and {round(100*img_percentage, 2)}%\"\n        )\n        return words\n\n\nclass LimeMultimodalExplainer(object):\n    def __init__(\n        self,\n        image,\n        text,\n        model,\n        kernel_width=0.25,\n        kernel=None,\n        feature_selection=\"auto\",\n        class_names=None,\n    ):\n        \"\"\"\n        Object to explain predictions on texts and images\n        Args:\n            image: input 3D numpy array\n            text: input string in the meme\n            model: multi-modal model to give predictions for given image and text\n            kernel_width: kernel width for the exponential kernel.\n            If None, defaults to sqrt(number of columns) * 0.75.\n            kernel: similarity kernel that takes euclidean distances and kernel\n                width as input and outputs weights in (0,1). If None, defaults to\n                an exponential kernel.\n            feature_selection: feature selection method. can be\n                'forward_selection', 'lasso_path', 'none' or 'auto'.\n                See function 'explain_instance_with_data' in lime_base.py for\n                details on what each of the options does.\n                class_names: list of class names, ordered according to whatever the\n                classifier is using. If not present, class names will be '0',\n                '1', ...\n        \"\"\"\n        self.image = image\n        self.text = text\n        self.pred_model = model\n        self.random_state = check_random_state(None)\n        if kernel is None:\n\n            def kernel(d, kernel_width):\n                return np.sqrt(np.exp(-(d ** 2) / kernel_width ** 2))\n\n        kernel_fn = partial(kernel, kernel_width=kernel_width)\n        self.feature_selection = feature_selection\n        self.class_names = class_names\n        self.base = LimeBase(kernel_fn, verbose=False, random_state=self.random_state)\n\n    def explain_instance(self, classifier_fn, n_samples, top_labels=2):\n\n        \"\"\"\n        Generate explanations for a multi-modal input\n        Arguments:\n            classifier_fn: classification function to give predictions for given texts and images\n            num_samples: size of the neighborhood to learn the linear model\n            top_labels: if not None, ignore labels and produce explanations for\n                the K labels with highest prediction probabilities, where K is\n                this parameter.\n            Return:\n                ret_exp: A MultiModalExplanation object with the corresponding\n            explanations.\n        \"\"\"\n        (\n            data,\n            labels,\n            distances,\n            n_txt_features,\n            n_img_features,\n            segments,\n            domain_mapper,\n            n_detection_features,\n            detection_label,\n            ratio_txt_img,\n        ) = self.data_labels(n_samples, classifier_fn)\n        num_features = data.shape[1]\n\n        if self.class_names is None:\n            self.class_names = [str(x) for x in range(labels[0].shape[0])]\n\n        ret_exp = MultiModalExplanation(\n            self.image,\n            segments,\n            domain_mapper=domain_mapper,\n            n_txt_features=n_txt_features,\n            n_img_features=n_img_features,\n            n_detection_features=n_detection_features,\n            ratio_txt_img=ratio_txt_img,\n            detection_label=detection_label,\n            class_names=self.class_names,\n            random_state=self.random_state,\n        )\n        ret_exp.predict_proba = labels[0]\n\n        if top_labels:\n            top = np.argsort(labels[0])[-top_labels:]\n            ret_exp.top_labels = list(top)\n            ret_exp.top_labels.reverse()\n        for label in top:\n            (\n                ret_exp.intercept[label],\n                ret_exp.unsorted_weights[label],\n                ret_exp.local_exp[label],\n                ret_exp.local_exp_txt[label],\n                ret_exp.local_exp_img[label],\n                ret_exp.local_exp_det[label],\n                ret_exp.score[label],\n                ret_exp.local_pred[label],\n            ) = self.base.explain_instance_with_data(\n                data,\n                labels,\n                distances,\n                label,\n                num_features,\n                n_txt_features,\n                n_img_features,\n                n_detection_features,\n                feature_selection=None,\n            )\n\n            # split local explanation into text and image features\n\n        return ret_exp\n\n    def data_labels(self, num_samples, classifier_fn, detection=False):\n        \"\"\"\n        Steps of this function:\n            1. generate perturbed text features and image features\n            2. in a loop, 1) using these features to make instances of perturbed (text, image) pairs,\n                          2) make predictions on these pairs, store labels into 'labels'\n            3. concatenate text and image features, store into 'data',\n                also append the original input and prediction of it\n            4. calculate distances\n            Arguments:\n                classifier_fn: classification function to give predictions for given texts and images\n                num_samples: size of the neighborhood to learn the linear model\n                detection: Whether object detection method is invoked, default to be false\n            Return:\n            data: dense num_samples * num_superpixels\n            labels: prediction probabilities matrix\n            distances:distance including text/image distance ratio where\n            text and image distance are cosine distances between the original instance and\n                    each perturbed instance (computed in the binary 'data'\n                    matrix), times 100.\n            doc_size: number of words in indexed string, where indexed string is the string with various indexes\n            n_img_features: number of superpixels to include in explanation\n            segments:2d numpy array, with the output from skimage.segmentation\n            domain_mapper:Maps text feature ids to words or word-positions\n            num_object_detection:number of detected objects to include in explanation\n            ori_label: numpy including deteced objects in the original image\n            ratio_txt_img: weight ratio between text and image features\n        \"\"\"\n\n        \"\"\" 1. make text features \"\"\"\n        indexed_string = IndexedString(\n            self.text, bow=True, split_expression=r\"\\W+\", mask_string=None\n        )\n        domain_mapper = TextDomainMapper(indexed_string)\n\n        doc_size = indexed_string.num_words()\n        sample = self.random_state.randint(\n            1, doc_size + 1, num_samples\n        )  # num_samples - 1\n        data_txt = np.ones((num_samples, doc_size))\n        # data[0] = np.ones(doc_size)\n        features_range = range(doc_size)\n        inverse_data_txt = []\n\n        \"\"\" 1. make image features \"\"\"\n        random_seed = self.random_state.randint(0, high=1000)\n        segmentation_fn = SegmentationAlgorithm(\n            \"quickshift\",\n            kernel_size=4,\n            max_dist=200,\n            ratio=0.2,\n            random_seed=random_seed,\n        )\n\n        # segmentation_fn = SegmentationAlgorithm('felzenszwalb', scale=200, sigma=2, min_size=100)\n        \"\"\"segmentation_fn = SegmentationAlgorithm('slic', n_segments=60, compactness=10, sigma=1,\n                     start_label=1)\"\"\"\n\n        segments = segmentation_fn(self.image)  # get segmentation\n        n_img_features = np.unique(segments).shape[0]  # get num of superpixel features\n        data_img = self.random_state.randint(\n            0, 2, n_img_features * num_samples\n        ).reshape((num_samples, n_img_features))\n        data_img_rows = tqdm(data_img)\n        imgs = []\n\n        \"\"\" 1. make object detection features \n        if detection:\n            predictor, cfg = object_detection_predictor()\n            ori_label = object_detection_obtain_label(predictor, cfg, self.image)\n            num_object_detection = ori_label.shape[0]\n            data_object_detection = np.zeros((num_samples,num_object_detection))\"\"\"\n\n        # create fudged_image\n        fudged_image = self.image.copy()\n        for x in np.unique(segments):\n            fudged_image[segments == x] = (\n                np.mean(self.image[segments == x][:, 0]),\n                np.mean(self.image[segments == x][:, 1]),\n                np.mean(self.image[segments == x][:, 2]),\n            )\n\n        # img_features[0, :] = 1  # the first sample is the full image                                # num_samples\n\n        \"\"\"2. create data instances and make predictions\"\"\"\n        labels = []\n        for i, instance in enumerate(zip(sample, data_img_rows)):\n            size_txt, row_img = instance\n\n            # make text instance\n            inactive = self.random_state.choice(features_range, size_txt, replace=False)\n            data_txt[i, inactive] = 0\n            inverse_data_txt.append(indexed_string.inverse_removing(inactive))\n\n            # make image instance\n            temp = copy.deepcopy(self.image)\n            zeros = np.where(row_img == 0)[\n                0\n            ]  # get segment numbers that are turned off in this instance\n            mask = np.zeros(segments.shape).astype(bool)\n            for zero in zeros:\n                mask[segments == zero] = True\n            temp[mask] = fudged_image[mask]\n\n            \"\"\"if detection:\n                label = object_detection_obtain_label(predictor, cfg, temp)\n                label_diff = compare_labels(ori_label,label)\n                data_object_detection[i] = label_diff\"\"\"\n            imgs.append(temp)\n\n            # make prediction and append result\n            if len(imgs) == 10:\n                preds = classifier_fn(self.pred_model, imgs, inverse_data_txt)\n                labels.extend(preds)\n                imgs = []\n                inverse_data_txt = []\n\n        if len(imgs) > 0:\n            preds = classifier_fn(self.pred_model, imgs, inverse_data_txt)\n            labels.extend(preds)\n\n        \"\"\"3. concatenate and append features\"\"\"\n        data = np.concatenate((data_txt, data_img), axis=1)\n\n        # append the original input to the last\n        orig_img_f = np.ones((n_img_features,))\n        orig_txt_f = np.ones(doc_size)\n\n        \"\"\"if detection:\n            data = np.concatenate((data, data_object_detection),axis=1)\n            orig_ot = np.ones(num_object_detection)\n            data = np.vstack((data, np.concatenate((np.concatenate((orig_txt_f, orig_img_f)),orig_ot))))\n        else:\"\"\"\n        data = np.vstack((data, np.ones((data.shape[1]))))  ###\n\n        labels.extend(classifier_fn(self.pred_model, [self.image], [self.text]))\n\n        \"\"\"4. compute distance# distances[:, :(doc_size-1)] *= 100\n            use platt scaling t get relative importance of text and image modalities\n        \"\"\"\n\n        labels = np.array(labels, dtype=float)\n\n        # Modify MMF source code to zero out image / text attributes\n        # dummy_label_image = np.array(classifier_fn([self.image], [self.text], zero_text=True))  # zero out text\n        # dummy_label_text = np.array(classifier_fn([self.image], [self.text], zero_image=True))  # zero out image\n\n        # perform calibration\n        try:\n            labels_for_calib = np.array(labels[:, 0] < 0.5, dtype=float)\n            calibrated = CalibratedClassifierCV(cv=3)\n            calibrated.fit(data[:, : doc_size + n_img_features], labels_for_calib)\n\n            calib_data = np.ones((3, doc_size + n_img_features), dtype=float)\n            calib_data[0][:doc_size] = 0  # zero out text\n            calib_data[1][doc_size:] = 0  # zero out image\n            calibrated_labels = calibrated.predict_proba(calib_data)\n\n            delta_txt = abs(calibrated_labels[-1][0] - calibrated_labels[0][0])\n            delta_img = abs(calibrated_labels[-1][0] - calibrated_labels[1][0])\n\n            ratio_txt_img = max(min(100, delta_txt / delta_img), 0.01)\n        except:\n            dummy_text = \"\"\n            dummy_image = np.zeros_like(self.image)\n            label_text_out = np.array(\n                classifier_fn(\n                    self.pred_model, [self.image], [self.text], zero_text=True\n                )\n            )  # zero out text\n            label_image_out = np.array(\n                classifier_fn(\n                    self.pred_model, [self.image], [self.text], zero_image=True\n                )\n            )  # zero out image\n\n            delta_txt = abs(labels[-1][0] - label_text_out[0][0])\n            delta_img = abs(labels[-1][0] - label_image_out[0][0])\n            ratio_txt_img = max(min(10, delta_txt / delta_img), 0.1)\n\n        # calculate distances\n        distances_img = sklearn.metrics.pairwise_distances(\n            data[:, doc_size:], data[-1, doc_size:].reshape(1, -1), metric=\"cosine\"\n        ).ravel()\n\n        def distance_fn(x):\n            return sklearn.metrics.pairwise.pairwise_distances(\n                x, x[-1], metric=\"cosine\"\n            ).ravel()\n\n        distances_txt = distance_fn(sp.sparse.csr_matrix(data[:, :doc_size]))\n\n        distances = (\n            1 / (1 + ratio_txt_img) * distances_img\n            + (1 - 1 / (1 + ratio_txt_img)) * distances_txt\n        )\n\n        # As required by lime_base, make the first element of data, labels, distances the original data point\n        data[0] = data[-1]\n        labels[0] = labels[-1]\n        distances[0] = distances[-1]\n\n        \"\"\"if not detection:\"\"\"\n        num_object_detection = 0\n        ori_label = None\n\n        return (\n            data,\n            labels,\n            distances,\n            doc_size,\n            n_img_features,\n            segments,\n            domain_mapper,\n            num_object_detection,\n            ori_label,\n            ratio_txt_img,\n        )\n", "meta": {"hexsha": "bcb7017e1b27d55bc680bb2ddaf55ea34f582752", "size": 25926, "ext": "py", "lang": "Python", "max_stars_repo_path": "mmxai/interpretability/classification/lime/lime_multimodal.py", "max_stars_repo_name": "junqi-jiang/mmxai", "max_stars_repo_head_hexsha": "08ae70a6d443fbdfa92dba6cd285429e85ac851f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-19T16:44:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-19T16:46:43.000Z", "max_issues_repo_path": "mmxai/interpretability/classification/lime/lime_multimodal.py", "max_issues_repo_name": "junqi-jiang/mmxai", "max_issues_repo_head_hexsha": "08ae70a6d443fbdfa92dba6cd285429e85ac851f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-05-19T17:23:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-09T09:58:02.000Z", "max_forks_repo_path": "mmxai/interpretability/classification/lime/lime_multimodal.py", "max_forks_repo_name": "junqi-jiang/mmxai", "max_forks_repo_head_hexsha": "08ae70a6d443fbdfa92dba6cd285429e85ac851f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9476117103, "max_line_length": 115, "alphanum_fraction": 0.5941140168, "include": true, "reason": "import numpy,import scipy", "num_tokens": 5448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.3415824860330003, "lm_q1q2_score": 0.19726230748040857}}
{"text": "from CHECLabPy.plotting.setup import Plotter\nimport numpy as np\nimport pandas as pd\nfrom sstcam_simulation.utils.efficiency import CameraEfficiency\nfrom sstcam_simulation.utils.sipm import SiPMOvervoltage\nfrom sstcam_simulation.utils.window_durham_needle import SSTWindowRun3, Window\n\nMINIMGAMP_GAMMA = 250\nMINIMGAMP_PROTON = 480\nBTEL1170_PDE = 0.2\nBTEL0090_SNR = 0.35\nPROD4_OPCT = 0.08\nPROD4_MINIMGAMP_GAMMA = 153\nPROD4_MINIMGAMP_PROTON = 208\n\n\ndef main():\n    sipm_tool = SiPMOvervoltage.lvr3_6mm_50um_uncoated()\n    sipm_tool.overvoltage = 6\n    pde_at_450nm = sipm_tool.pde\n    window_tool = SSTWindowRun3()\n\n    eff = CameraEfficiency.from_sstcam(\n        fov_angle=0,\n        pde_at_450nm=pde_at_450nm,\n        window=window_tool,\n    )\n\n    p = Plotter()\n    p.ax.plot(eff.wavelength, eff._cherenkov_diff_flux_on_ground, \"-\", color='blue', alpha=0.3, label=\"On-ground\")\n    p.ax.plot(eff.wavelength, eff._cherenkov_diff_flux_at_camera, \"--\", color='blue', alpha=0.6, label=\"At-camera\")\n    p.ax.plot(eff.wavelength, eff._cherenkov_diff_flux_at_pixel, \"-.\", color='blue', alpha=0.9, label=\"At-pixel\")\n    p.ax.plot(eff.wavelength, eff._cherenkov_diff_flux_inside_pixel, \":\", color='blue', alpha=1, label=\"Inside-pixel\")\n    p.ax.set_ylim(0, 0.45)\n    p.ax.set_xlabel(\"Wavelength [nm]\")\n    p.ax.set_ylabel(\"Cherenkov photons [100 * 1 / nm]\")\n    p.save(\"foldings/spectra_cherenkov.pdf\")\n\n    p = Plotter()\n    p.ax.plot(eff.wavelength, eff._nsb_diff_flux_on_ground, \"-\", color='red', alpha=0.3, label=\"On-ground\")\n    p.ax.plot(eff.wavelength, eff._nsb_diff_flux_at_camera, \"--\", color='red', alpha=0.6, label=\"At-camera\")\n    p.ax.plot(eff.wavelength, eff._nsb_diff_flux_at_pixel, \"-.\", color='red', alpha=0.9, label=\"At-pixel\")\n    p.ax.plot(eff.wavelength, eff._nsb_diff_flux_inside_pixel, \":\", color='red', alpha=1, label=\"Inside-pixel\")\n    p.ax.set_ylim(0, 25)\n    p.ax.set_xlabel(\"Wavelength [nm]\")\n    p.ax.set_ylabel(\"NSB photons [ 1 / (nm m2 ns sr) ]\")\n    p.save(\"foldings/spectra_nsb.pdf\")\n\n    p = Plotter()\n    camera_sensitivity = eff.pde * eff.window_transmissivity\n    p.ax.plot(eff.wavelength, eff.pde, label=\"PDE\")\n    p.ax.plot(eff.wavelength, eff.window_transmissivity, label=\"Window Transmissivity\")\n    p.ax.plot(eff.wavelength, camera_sensitivity, label=\"PDE * Window Transmissivity\")\n    # p.ax.plot(eff.wavelength, eff.telescope_transmissivity, label=\"Telescope Transmissivity\")\n    p.ax.plot(eff.wavelength, eff.mirror_reflectivity, label=\"Mirror Reflectivity\")\n    p.ax.set_xlabel(\"Wavelength [nm]\")\n    p.ax.set_ylabel(\"Sensitivity\")\n    p.add_legend()\n    p.save(\"foldings/sensitivity.pdf\")\n\n    p = Plotter()\n    def add_window(window_tool):\n        angles = np.array([0, 20, 45, 50, 60])\n        arrays = np.vstack([\n            window_tool.df['M0'],\n            window_tool.df['M20'],\n            window_tool.df['M45'],\n            window_tool.df['M50'],\n            window_tool.df['M60'],\n        ])\n        window_tool = Window(incidence_angles=angles, transmission=arrays)\n        \n        eff = CameraEfficiency.from_sstcam(\n            fov_angle=0,\n            pde_at_450nm=pde_at_450nm,\n            window=window_tool,\n        )\n        label = f\"NSB={eff.nominal_nsb_rate.to_value('MHz'):.2f}, PDE={eff.camera_cherenkov_pde:.2f}, S/N={eff.camera_signal_to_noise:.2f}\"\n        x = eff.wavelength.value\n        y = eff.window_transmissivity\n        p.ax.plot(x, y, alpha=0.7, label=label)\n\n    add_window(window_tool)\n    # from IPython import embed\n    # embed()\n    # window_tool.df.loc[window_tool.df.index < 300] = 0\n    # add_window(window_tool)\n    # window_tool.df.loc[window_tool.df.index > 750] = 0.2\n    # add_window(window_tool)\n    p.ax.set_xlabel(\"Wavelength [nm]\")\n    p.ax.set_ylabel(\"Sensitivity\")\n    p.add_legend()\n    p.save(\"foldings/window.pdf\")\n\n\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "8803fc4b394f6e3f3a461d33c600cce3b8287ce1", "size": 3853, "ext": "py", "lang": "Python", "max_stars_repo_path": "scratch/plot_foldings.py", "max_stars_repo_name": "cta-chec/sstCASSIM", "max_stars_repo_head_hexsha": "75bb863675991f1a36b7d430f9253ae09416f33e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-23T23:26:36.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-23T23:26:36.000Z", "max_issues_repo_path": "scratch/plot_foldings.py", "max_issues_repo_name": "cta-chec/sstCASSIM", "max_issues_repo_head_hexsha": "75bb863675991f1a36b7d430f9253ae09416f33e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scratch/plot_foldings.py", "max_forks_repo_name": "cta-chec/sstCASSIM", "max_forks_repo_head_hexsha": "75bb863675991f1a36b7d430f9253ae09416f33e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.53, "max_line_length": 139, "alphanum_fraction": 0.6781728523, "include": true, "reason": "import numpy", "num_tokens": 1160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3415824927356586, "lm_q1q2_score": 0.19726230638345907}}
{"text": "from __future__ import division, absolute_import, print_function\n\n__copyright__ = \"Copyright (C) 2017 - 2018 Xiaoyu Wei\"\n\n__license__ = \"\"\"\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\n\nimport numpy as np\nimport logging\nimport pyopencl as cl\nimport pyopencl.array\nfrom pytools.obj_array import make_obj_array\n\n# from pytools import memoize_method\nfrom volumential.nearfield_potential_table import NearFieldInteractionTable\nfrom volumential.expansion_wrangler_interface import (\n        ExpansionWranglerInterface, ExpansionWranglerCodeContainerInterface)\nfrom sumpy.fmm import SumpyExpansionWrangler, \\\n        SumpyTimingFuture, SumpyExpansionWranglerCodeContainer\nfrom boxtree.pyfmmlib_integration import FMMLibExpansionWrangler\n\nfrom sumpy.kernel import (\n        LaplaceKernel, HelmholtzKernel, AxisTargetDerivative,\n        DirectionalSourceDerivative)\n\nlogger = logging.getLogger(__name__)\n\n\ndef level_to_rscale(tree, level):\n    return tree.root_extent * (2 ** -level)\n\n\ndef inverse_id_map(queue, mapped_ids):\n    \"\"\"Given a index mapping as its mapped ids, compute its inverse,\n    and return the inverse by the inversely-mapped ids.\n    \"\"\"\n    cl_array = False\n    if isinstance(mapped_ids, cl.array.Array):\n        cl_array = True\n        mapped_ids = mapped_ids.get(queue)\n\n    inv_ids = np.zeros_like(mapped_ids)\n    inv_ids[mapped_ids] = np.arange(len(mapped_ids))\n\n    if cl_array:\n        inv_ids = cl.array.to_device(queue, inv_ids)\n\n    return inv_ids\n\n\n# {{{ sumpy backend\n\n\nclass FPNDSumpyExpansionWranglerCodeContainer(\n        ExpansionWranglerCodeContainerInterface,\n        SumpyExpansionWranglerCodeContainer):\n    \"\"\"Objects of this type serve as a place to keep the code needed\n    for ExpansionWrangler if it is using sumpy to perform multipole\n    expansion and manipulations.\n\n    Since :class:`SumpyExpansionWrangler` necessarily must have a\n    :class:`pyopencl.CommandQueue`, but this queue is allowed to be\n    more ephemeral than the code, the code's lifetime\n    is decoupled by storing it in this object.\n    \"\"\"\n    get_wrangler = SumpyExpansionWranglerCodeContainer.get_wrangler\n\n\nclass FPNDSumpyExpansionWrangler(\n        ExpansionWranglerInterface, SumpyExpansionWrangler):\n    \"\"\"This expansion wrangler uses \"fpnd\" strategy. That is, Far field is\n    computed via Particle approximation and Near field is computed Directly.\n    The FMM is performed using sumpy backend.\n\n    .. attribute:: source_extra_kwargs\n\n        Keyword arguments to be passed to interactions that involve\n        the source field.\n\n    .. attribute:: kernel_extra_kwargs\n\n        Keyword arguments to be passed to interactions that involve\n        expansions, but not the source field.\n\n    .. attribute:: self_extra_kwargs\n\n        Keyword arguments to be passed for handling\n        self interactions (singular integrals)\n    \"\"\"\n\n    # {{{ constructor\n\n    def __init__(\n        self,\n        code_container,\n        queue,\n        tree,\n        near_field_table,\n        dtype,\n        fmm_level_to_order,\n        quad_order,\n        potential_kind=1,\n        source_extra_kwargs=None,\n        kernel_extra_kwargs=None,\n        self_extra_kwargs=None,\n        list1_extra_kwargs=None,\n    ):\n        \"\"\"\n        near_field_table can either one of three things:\n            1. a single table, when len(target_kernels) = 1 (single level)\n            2. a list of tables, when len(target_kernels) = 1 (multiple levels)\n            3. otherwise, a dictionary from kernel.__repr__() to a list of its tables\n        \"\"\"\n\n        self.code = code_container\n        self.queue = queue\n        self.tree = tree\n\n        self.near_field_table = {}\n        # list of tables for a single out kernel\n        if isinstance(near_field_table, list):\n            assert len(self.code.target_kernels) == 1\n            self.near_field_table[\n                self.code.target_kernels[0].__repr__()\n            ] = near_field_table\n            self.n_tables = len(near_field_table)\n\n        # single table\n        elif isinstance(near_field_table, NearFieldInteractionTable):\n            assert len(self.code.target_kernels) == 1\n            self.near_field_table[self.code.target_kernels[0].__repr__()] = [\n                near_field_table\n            ]\n            self.n_tables = 1\n\n        # dictionary of lists of tables\n        elif isinstance(near_field_table, dict):\n            self.n_tables = dict()\n            for out_knl in self.code.target_kernels:\n                if repr(out_knl) not in near_field_table:\n                    raise RuntimeError(\n                            \"Missing nearfield table for %s.\" % repr(out_knl))\n                if isinstance(near_field_table[repr(out_knl)],\n                        NearFieldInteractionTable):\n                    near_field_table[repr(out_knl)] = [\n                            near_field_table[repr(out_knl)]]\n                else:\n                    assert isinstance(near_field_table[repr(out_knl)], list)\n\n                self.n_tables[repr(out_knl)] = len(near_field_table[repr(out_knl)])\n\n            self.near_field_table = near_field_table\n        else:\n            raise RuntimeError(\"Table type unrecognized.\")\n\n        self.quad_order = quad_order\n        self.potential_kind = potential_kind\n\n        # TODO: make all parameters table-specific (allow using inhomogeneous tables)\n        kname = repr(self.code.target_kernels[0])\n        self.root_table_source_box_extent = (\n                self.near_field_table[kname][0].source_box_extent)\n        table_starting_level = np.round(\n            np.log(self.tree.root_extent / self.root_table_source_box_extent)\n            / np.log(2)\n            )\n        for kid in range(len(self.code.target_kernels)):\n            kname = self.code.target_kernels[kid].__repr__()\n            for lev, table in zip(\n                    range(len(self.near_field_table[kname])),\n                    self.near_field_table[kname]\n                    ):\n                assert table.quad_order == self.quad_order\n\n                if not table.is_built:\n                    raise RuntimeError(\n                        \"Near field interaction table needs to be built \"\n                        \"prior to being used\"\n                    )\n\n                table_root_extent = table.source_box_extent * 2 ** lev\n                assert (\n                    abs(self.root_table_source_box_extent - table_root_extent)\n                    < 1e-15\n                )\n\n                # If the kernel cannot be scaled,\n                # - tree_root_extent must be integral times of table_root_extent\n                # - n_tables must be sufficient\n                if not isinstance(self.n_tables, dict) and self.n_tables > 1:\n                    if (\n                        not abs(\n                            int(self.tree.root_extent / table_root_extent)\n                            * table_root_extent\n                            - self.tree.root_extent\n                        )\n                        < 1e-15\n                    ):\n                        raise RuntimeError(\n                            \"Incompatible list of tables: the \"\n                            \"source_box_extent of the root table must \"\n                            \"divide the bounding box's extent by an integer.\"\n                        )\n\n            if not isinstance(self.n_tables, dict) and self.n_tables > 1:\n                # this checks that the boxes at the highest level are covered\n                if (\n                    not tree.nlevels\n                    <= len(self.near_field_table[kname]) + table_starting_level\n                ):\n                    raise RuntimeError(\n                        \"Insufficient list of tables: the \"\n                        \"finest level mesh cells at level \"\n                        + str(tree.nlevels)\n                        + \" are not covered.\"\n                    )\n\n                # the check that the boxes at the coarsest level are covered is\n                # deferred until trav.target_boxes is passed when invoking\n                # eval_direct\n\n        self.dtype = dtype\n\n        if source_extra_kwargs is None:\n            source_extra_kwargs = {}\n\n        if kernel_extra_kwargs is None:\n            kernel_extra_kwargs = {}\n\n        if self_extra_kwargs is None:\n            self_extra_kwargs = {}\n\n        if list1_extra_kwargs is None:\n            list1_extra_kwargs = {}\n\n        if not callable(fmm_level_to_order):\n            raise TypeError(\"fmm_level_to_order not passed\")\n\n        base_kernel = code_container.get_base_kernel()\n        kernel_arg_set = frozenset(kernel_extra_kwargs.items())\n        self.level_orders = [\n            fmm_level_to_order(base_kernel, kernel_arg_set, tree, lev)\n            for lev in range(tree.nlevels)\n        ]\n\n        # print(\"Multipole order = \",self.level_orders)\n\n        self.source_extra_kwargs = source_extra_kwargs\n        self.kernel_extra_kwargs = kernel_extra_kwargs\n        self.self_extra_kwargs = self_extra_kwargs\n        self.list1_extra_kwargs = list1_extra_kwargs\n\n        self.extra_kwargs = source_extra_kwargs.copy()\n        self.extra_kwargs.update(self.kernel_extra_kwargs)\n\n    # }}} End constructor\n\n    # {{{ data vector utilities\n\n    def multipole_expansion_zeros(self):\n        return SumpyExpansionWrangler.multipole_expansion_zeros(self)\n\n    def local_expansion_zeros(self):\n        return SumpyExpansionWrangler.local_expansion_zeros(self)\n\n    def output_zeros(self):\n        return SumpyExpansionWrangler.output_zeros(self)\n\n    def reorder_sources(self, source_array):\n        return SumpyExpansionWrangler.reorder_sources(self, source_array)\n\n    def reorder_targets(self, target_array):\n        if not hasattr(self.tree, 'user_target_ids'):\n            self.tree.user_target_ids = inverse_id_map(\n                self.queue, self.tree.sorted_target_ids)\n        return target_array.with_queue(self.queue)[self.tree.user_target_ids]\n\n    def reorder_potentials(self, potentials):\n        return SumpyExpansionWrangler.reorder_potentials(self, potentials)\n\n    def finalize_potentials(self, potentials):\n        # return potentials\n        return SumpyExpansionWrangler.finalize_potentials(self, potentials)\n\n    # }}} End data vector utilities\n\n    # {{{ formation & coarsening of multipoles\n\n    def form_multipoles(self, level_start_source_box_nrs, source_boxes, src_weights):\n        return SumpyExpansionWrangler.form_multipoles(\n            self, level_start_source_box_nrs, source_boxes, src_weights\n        )\n\n    def coarsen_multipoles(\n        self, level_start_source_parent_box_nrs, source_parent_boxes, mpoles\n    ):\n        return SumpyExpansionWrangler.coarsen_multipoles(\n            self, level_start_source_parent_box_nrs, source_parent_boxes, mpoles\n        )\n\n    # }}} End formation & coarsening of multipoles\n\n    # {{{ direct evaluation of near field interactions\n\n    def eval_direct_single_out_kernel(\n        self,\n        out_pot,\n        out_kernel,\n        target_boxes,\n        neighbor_source_boxes_starts,\n        neighbor_source_boxes_lists,\n        mode_coefs,\n    ):\n\n        # NOTE: mode_coefs are similar to source_weights BUT\n        # do not include quadrature weights (purely function\n        # expansiona coefficients)\n\n        if 0:\n            print(\"Returns range for list1\")\n            out_pot[:] = cl.array.to_device(self.queue, np.arange(len(out_pot)))\n            return out_pot, None\n\n        kname = out_kernel.__repr__()\n\n        if isinstance(self.n_tables, int) and self.n_tables > 1:\n            use_multilevel_tables = True\n        elif isinstance(self.n_tables, dict) and self.n_tables[kname] > 1:\n            use_multilevel_tables = True\n        else:\n            use_multilevel_tables = False\n\n        if use_multilevel_tables:\n            # this checks that the boxes at the coarsest level\n            # and allows for some round-off error\n            min_lev = np.min(\n                self.tree.box_levels.get(self.queue)[target_boxes.get(self.queue)]\n            )\n            largest_cell_extent = self.tree.root_extent * 0.5 ** min_lev\n            if not self.near_field_table[kname][0].source_box_extent >= (\n                largest_cell_extent - 1e-15\n            ):\n                raise RuntimeError(\n                    \"Insufficient list of tables: the \"\n                    \"coarsest level mesh cells at level \"\n                    + str(min_lev)\n                    + \" are not covered.\"\n                )\n\n        # table.case_encode\n        distinct_numbers = set()\n        for vec in self.near_field_table[kname][0].interaction_case_vecs:\n            for cvc in vec:\n                distinct_numbers.add(cvc)\n        base = len(range(min(distinct_numbers), max(distinct_numbers) + 1))\n        shift = -min(distinct_numbers)\n\n        case_indices_dev = cl.array.to_device(\n            self.queue, self.near_field_table[kname][0].case_indices\n        )\n\n        # table.data\n        table_data_combined = np.zeros(\n            (\n                len(self.near_field_table[kname]),\n                len(self.near_field_table[kname][0].data),\n            ), dtype=self.near_field_table[kname][0].data.dtype\n        )\n        mode_nmlz_combined = np.zeros(\n            (\n                len(self.near_field_table[kname]),\n                len(self.near_field_table[kname][0].mode_normalizers),\n            ), dtype=self.near_field_table[kname][0].mode_normalizers.dtype\n        )\n        exterior_mode_nmlz_combined = np.zeros(\n            (\n                len(self.near_field_table[kname]),\n                len(self.near_field_table[kname][0].kernel_exterior_normalizers),\n            ),\n            dtype=self.near_field_table[kname][0].kernel_exterior_normalizers.dtype\n        )\n        for lev in range(len(self.near_field_table[kname])):\n            table_data_combined[lev, :] = self.near_field_table[kname][lev].data\n            mode_nmlz_combined[lev, :] = \\\n                self.near_field_table[kname][lev].mode_normalizers\n            exterior_mode_nmlz_combined[lev, :] = \\\n                self.near_field_table[kname][lev].kernel_exterior_normalizers\n\n        self.queue.finish()\n        logger.info(\n                \"table data for kernel \"\n                + out_kernel.__repr__() + \" congregated\")\n\n        # The loop domain needs to know some info about the tables being used\n        table_data_shapes = {\n            \"n_tables\": len(self.near_field_table[kname]),\n            \"n_q_points\": self.near_field_table[kname][0].n_q_points,\n            \"n_table_entries\": len(self.near_field_table[kname][0].data),\n        }\n        assert table_data_shapes[\"n_q_points\"] == len(\n            self.near_field_table[kname][0].mode_normalizers\n        )\n\n        from volumential.list1 import NearFieldFromCSR\n\n        near_field = NearFieldFromCSR(out_kernel, table_data_shapes,\n            potential_kind=self.potential_kind,\n            **self.list1_extra_kwargs)\n\n        table_data_combined = cl.array.to_device(self.queue,\n                table_data_combined)\n        mode_nmlz_combined = cl.array.to_device(self.queue,\n                mode_nmlz_combined)\n        exterior_mode_nmlz_combined = cl.array.to_device(self.queue,\n            exterior_mode_nmlz_combined)\n        self.queue.finish()\n        logger.info(\"sent table data to device\")\n\n        # NOTE: box_sources for this evaluation should be \"box_targets\".\n        # This is due to the special features of how box-FMM works.\n\n        res, evt = near_field(\n            self.queue,\n            result=out_pot,\n            box_centers=self.tree.box_centers,\n            box_levels=self.tree.box_levels,\n            box_source_counts_cumul=self.tree.box_target_counts_cumul,\n            box_source_starts=self.tree.box_target_starts,\n            box_target_counts_cumul=self.tree.box_target_counts_cumul,\n            box_target_starts=self.tree.box_target_starts,\n            case_indices=case_indices_dev,\n            encoding_base=base,\n            encoding_shift=shift,\n            mode_nmlz_combined=mode_nmlz_combined,\n            exterior_mode_nmlz_combined=exterior_mode_nmlz_combined,\n            neighbor_source_boxes_starts=neighbor_source_boxes_starts,\n            root_extent=self.tree.root_extent,\n            neighbor_source_boxes_lists=neighbor_source_boxes_lists,\n            mode_coefs=mode_coefs,\n            table_data_combined=table_data_combined,\n            target_boxes=target_boxes,\n            table_root_extent=self.root_table_source_box_extent,\n        )\n\n        # print(near_field.get_kernel())\n        # import pudb; pu.db\n\n        assert res is out_pot\n\n        # sorted_target_ids=self.tree.user_source_ids,\n        # user_source_ids=self.tree.user_source_ids)\n\n        # FIXME: lazy evaluation sometimes returns incorrect results\n        res.finish()\n\n        return out_pot, evt\n\n    def eval_direct(\n        self,\n        target_boxes,\n        neighbor_source_boxes_starts,\n        neighbor_source_boxes_lists,\n        mode_coefs,\n    ):\n        pot = self.output_zeros()\n        events = []\n        for i in range(len(self.code.target_kernels)):\n            # print(\"processing near-field of out_kernel\", i)\n            pot[i], evt = self.eval_direct_single_out_kernel(\n                pot[i],\n                self.code.target_kernels[i],\n                target_boxes,\n                neighbor_source_boxes_starts,\n                neighbor_source_boxes_lists,\n                mode_coefs,\n            )\n            events.append(evt)\n\n        for out_pot in pot:\n            out_pot.finish()\n\n        return (pot, SumpyTimingFuture(self.queue, events))\n\n    # }}} End direct evaluation of near field interactions\n\n    # {{{ downward pass of fmm\n\n    def multipole_to_local(\n        self,\n        level_start_target_box_nrs,\n        target_boxes,\n        src_box_starts,\n        src_box_lists,\n        mpole_exps,\n    ):\n        return SumpyExpansionWrangler.multipole_to_local(\n            self,\n            level_start_target_box_nrs,\n            target_boxes,\n            src_box_starts,\n            src_box_lists,\n            mpole_exps,\n        )\n\n    def eval_multipoles(\n        self, target_boxes_by_source_level, source_boxes_by_level, mpole_exps\n    ):\n        return SumpyExpansionWrangler.eval_multipoles(\n            self, target_boxes_by_source_level, source_boxes_by_level, mpole_exps\n        )\n\n    def form_locals(\n        self,\n        level_start_target_or_target_parent_box_nrs,\n        target_or_target_parent_boxes,\n        starts,\n        lists,\n        src_weights,\n    ):\n        return SumpyExpansionWrangler.form_locals(\n            self,\n            level_start_target_or_target_parent_box_nrs,\n            target_or_target_parent_boxes,\n            starts,\n            lists,\n            src_weights,\n        )\n\n    def refine_locals(\n        self,\n        level_start_target_or_target_parent_box_nrs,\n        target_or_target_parent_boxes,\n        local_exps,\n    ):\n        return SumpyExpansionWrangler.refine_locals(\n            self,\n            level_start_target_or_target_parent_box_nrs,\n            target_or_target_parent_boxes,\n            local_exps,\n        )\n\n    def eval_locals(self, level_start_target_box_nrs, target_boxes, local_exps):\n        return SumpyExpansionWrangler.eval_locals(\n            self, level_start_target_box_nrs, target_boxes, local_exps\n        )\n\n    # }}} End downward pass of fmm\n\n    # {{{ direct evaluation of p2p (discrete) interactions\n\n    def eval_direct_p2p(\n        self, target_boxes, source_box_starts, source_box_lists, src_weights\n    ):\n        return SumpyExpansionWrangler.eval_direct(\n            self, target_boxes, source_box_starts, source_box_lists, src_weights\n        )\n\n    # }}} End direct evaluation of p2p interactions\n\n# }}} End sumpy backend\n\n# {{{ fmmlib backend (for laplace, helmholtz)\n\n\nclass FPNDFMMLibExpansionWranglerCodeContainer(\n        ExpansionWranglerCodeContainerInterface,\n        ):\n    \"\"\"Objects of this type serve as a place to keep the code needed\n    for ExpansionWrangler if it is using fmmlib to perform multipole\n    expansion and manipulations.\n\n    The interface is augmented with unecessary arguments acting as\n    placeholders, such that it can be a drop-in replacement of sumpy\n    backend.\n    \"\"\"\n    def __init__(self, cl_context,\n            multipole_expansion_factory, local_expansion_factory,\n            target_kernels, exclude_self=True, *args, **kwargs):\n        self.cl_context = cl_context\n        self.multipole_expansion_factory = multipole_expansion_factory\n        self.local_expansion_factory = local_expansion_factory\n\n        self.target_kernels = target_kernels\n        self.exclude_self = True\n\n    def get_wrangler(self, queue, tree, dtype, fmm_level_to_order,\n            source_extra_kwargs={}, kernel_extra_kwargs=None,\n            *args, **kwargs):\n        return FPNDFMMLibExpansionWrangler(self, queue, tree,\n                dtype, fmm_level_to_order,\n                source_extra_kwargs, kernel_extra_kwargs,\n                *args, **kwargs)\n\n\nclass FPNDFMMLibExpansionWrangler(\n        ExpansionWranglerInterface, FMMLibExpansionWrangler):\n    \"\"\"This expansion wrangler uses \"fpnd\" strategy. That is, Far field is\n    computed via Particle approximation and Near field is computed Directly.\n    The FMM is performed using FMMLib backend.\n\n    .. attribute:: source_extra_kwargs\n\n        Keyword arguments to be passed to interactions that involve\n        the source field.\n\n    .. attribute:: kernel_extra_kwargs\n\n        Keyword arguments to be passed to interactions that involve\n        expansions, but not the source field.\n\n    Much of this class is borrowed from pytential.qbx.fmmlib.\n    \"\"\"\n    # {{{ constructor\n\n    def __init__(self, code_container, queue, tree,\n            near_field_table, dtype,\n            fmm_level_to_order,\n            quad_order,\n            potential_kind=1,\n            source_extra_kwargs=None,\n            kernel_extra_kwargs=None,\n            self_extra_kwargs=None,\n            list1_extra_kwargs=None,\n            *args, **kwargs):\n        self.code = code_container\n        self.queue = queue\n\n        tree = tree.get(queue)\n        self.tree = tree\n\n        self.dtype = dtype\n        self.quad_order = quad_order\n        self.potential_kind = potential_kind\n\n        # {{{ digest target_kernels\n\n        ifgrad = False\n        outputs = []\n        source_deriv_names = []\n        k_names = []\n\n        for out_knl in self.code.target_kernels:\n\n            if self.is_supported_helmknl(out_knl):\n                outputs.append(())\n                no_target_deriv_knl = out_knl\n\n            elif (isinstance(out_knl, AxisTargetDerivative)\n                    and self.is_supported_helmknl(out_knl.inner_kernel)):\n                outputs.append((out_knl.axis,))\n                ifgrad = True\n                no_target_deriv_knl = out_knl.inner_kernel\n\n            else:\n                raise ValueError(\n                        \"only the 2/3D Laplace and Helmholtz kernel \"\n                        \"and their derivatives are supported\")\n\n            source_deriv_names.append(no_target_deriv_knl.dir_vec_name\n                    if isinstance(no_target_deriv_knl, DirectionalSourceDerivative)\n                    else None)\n\n            base_knl = out_knl.get_base_kernel()\n            k_names.append(base_knl.helmholtz_k_name\n                    if isinstance(base_knl, HelmholtzKernel)\n                    else None)\n\n        self.outputs = outputs\n\n        from pytools import is_single_valued\n\n        if not is_single_valued(source_deriv_names):\n            raise ValueError(\"not all kernels passed are the same in \"\n                    \"whether they represent a source derivative\")\n\n        source_deriv_name = source_deriv_names[0]\n\n        if not is_single_valued(k_names):\n            raise ValueError(\"not all kernels passed have the same \"\n                    \"Helmholtz parameter\")\n\n        k_name = k_names[0]\n\n        if k_name is None:\n            helmholtz_k = 0\n        else:\n            helmholtz_k = kernel_extra_kwargs[k_name]\n\n        # }}}\n\n        # {{{ table setup\n        # TODO put this part into the inteferce class\n\n        self.near_field_table = {}\n        # list of tables for a single out kernel\n        if isinstance(near_field_table, list):\n            assert len(self.code.target_kernels) == 1\n            self.near_field_table[\n                self.code.target_kernels[0].__repr__()\n            ] = near_field_table\n            self.n_tables = len(near_field_table)\n\n        # single table\n        elif isinstance(near_field_table, NearFieldInteractionTable):\n            assert len(self.code.target_kernels) == 1\n            self.near_field_table[self.code.target_kernels[0].__repr__()] = [\n                near_field_table\n            ]\n            self.n_tables = 1\n\n        # dictionary of lists of tables\n        elif isinstance(near_field_table, dict):\n            self.n_tables = dict()\n            for out_knl in self.code.target_kernels:\n                if repr(out_knl) not in near_field_table:\n                    raise RuntimeError(\n                            \"Missing nearfield table for %s.\" % repr(out_knl))\n                if isinstance(near_field_table[repr(out_knl)],\n                        NearFieldInteractionTable):\n                    near_field_table[repr(out_knl)] = [\n                            near_field_table[repr(out_knl)]]\n                else:\n                    assert isinstance(near_field_table[repr(out_knl)], list)\n\n                self.n_tables[repr(out_knl)] = len(near_field_table[repr(out_knl)])\n\n            self.near_field_table = near_field_table\n        else:\n            raise RuntimeError(\"Table type unrecognized.\")\n\n        # TODO: make all parameters table-specific (allow using inhomogeneous tables)\n        kname = repr(self.code.target_kernels[0])\n        self.root_table_source_box_extent = (\n                self.near_field_table[kname][0].source_box_extent)\n        table_starting_level = np.round(\n            np.log(self.tree.root_extent / self.root_table_source_box_extent)\n            / np.log(2)\n            )\n        for kid in range(len(self.code.target_kernels)):\n            kname = self.code.target_kernels[kid].__repr__()\n            for lev, table in zip(\n                    range(len(self.near_field_table[kname])),\n                    self.near_field_table[kname]\n                    ):\n                assert table.quad_order == self.quad_order\n\n                if not table.is_built:\n                    raise RuntimeError(\n                        \"Near field interaction table needs to be built \"\n                        \"prior to being used\"\n                    )\n\n                table_root_extent = table.source_box_extent * 2 ** lev\n                assert (\n                    abs(self.root_table_source_box_extent - table_root_extent)\n                    < 1e-15\n                )\n\n                # If the kernel cannot be scaled,\n                # - tree_root_extent must be integral times of table_root_extent\n                # - n_tables must be sufficient\n                if not isinstance(self.n_tables, dict) and self.n_tables > 1:\n                    if (\n                        not abs(\n                            int(self.tree.root_extent / table_root_extent)\n                            * table_root_extent\n                            - self.tree.root_extent\n                        )\n                        < 1e-15\n                    ):\n                        raise RuntimeError(\n                            \"Incompatible list of tables: the \"\n                            \"source_box_extent of the root table must \"\n                            \"divide the bounding box's extent by an integer.\"\n                        )\n\n            if not isinstance(self.n_tables, dict) and self.n_tables > 1:\n                # this checks that the boxes at the highest level are covered\n                if (\n                    not tree.nlevels\n                    <= len(self.near_field_table[kname]) + table_starting_level\n                ):\n                    raise RuntimeError(\n                        \"Insufficient list of tables: the \"\n                        \"finest level mesh cells at level \"\n                        + str(tree.nlevels)\n                        + \" are not covered.\"\n                    )\n\n                # the check that the boxes at the coarsest level are covered is\n                # deferred until trav.target_boxes is passed when invoking\n                # eval_direct\n\n        if source_extra_kwargs is None:\n            source_extra_kwargs = {}\n\n        if kernel_extra_kwargs is None:\n            kernel_extra_kwargs = {}\n\n        if self_extra_kwargs is None:\n            self_extra_kwargs = {}\n\n        if list1_extra_kwargs is None:\n            list1_extra_kwargs = {}\n\n        self.list1_extra_kwargs = list1_extra_kwargs\n\n        # }}} End table setup\n\n        if not callable(fmm_level_to_order):\n            raise TypeError(\"fmm_level_to_order not passed\")\n\n        dipole_vec = None\n        if source_deriv_name is not None:\n            dipole_vec = np.array([\n                    d_i.get(queue=queue)\n                    for d_i in source_extra_kwargs[source_deriv_name]],\n                    order=\"F\")\n\n        def inner_fmm_level_to_nterms(tree, level):\n            if helmholtz_k == 0:\n                return fmm_level_to_order(\n                        LaplaceKernel(tree.dimensions),\n                        frozenset(), tree, level)\n            else:\n                return fmm_level_to_order(\n                        HelmholtzKernel(tree.dimensions),\n                        frozenset([(\"k\", helmholtz_k)]), tree, level)\n\n        rotation_data = None\n        if 'traversal' in kwargs:\n            # add rotation data if traversal is passed as a keyword argument\n            from boxtree.pyfmmlib_integration import FMMLibRotationData\n            rotation_data = FMMLibRotationData(self.queue, kwargs['traversal'])\n        else:\n            logger.warning(\"Rotation data is not utilized since traversal is \"\n                           \"not known to FPNDFMMLibExpansionWrangler.\")\n\n        FMMLibExpansionWrangler.__init__(\n                self, tree,\n\n                helmholtz_k=helmholtz_k,\n                dipole_vec=dipole_vec,\n                dipoles_already_reordered=True,\n\n                fmm_level_to_nterms=inner_fmm_level_to_nterms,\n                rotation_data=rotation_data,\n\n                ifgrad=ifgrad)\n\n    # }}} End constructor\n\n# {{{ scale factor for fmmlib\n\n    def get_scale_factor(self):\n        if self.eqn_letter == \"l\" and self.dim == 2:\n            scale_factor = -1/(2*np.pi)\n        elif self.eqn_letter == \"h\" and self.dim == 2:\n            scale_factor = 1\n        elif self.eqn_letter in [\"l\", \"h\"] and self.dim == 3:\n            scale_factor = 1/(4*np.pi)\n        else:\n            raise NotImplementedError(\n                    \"scale factor for pyfmmlib %s for %d dimensions\" % (\n                        self.eqn_letter,\n                        self.dim))\n\n        return scale_factor\n\n# }}} End scale factor for fmmlib\n\n    # {{{ data vector utilities\n\n    def multipole_expansion_zeros(self):\n        return FMMLibExpansionWrangler.multipole_expansion_zeros(self)\n\n    def local_expansion_zeros(self):\n        return FMMLibExpansionWrangler.local_expansion_zeros(self)\n\n    def output_zeros(self):\n        return FMMLibExpansionWrangler.output_zeros(self)\n\n    def reorder_sources(self, source_array):\n        return FMMLibExpansionWrangler.reorder_sources(self, source_array)\n\n    def reorder_targets(self, target_array):\n        if not hasattr(self.tree, 'user_target_ids'):\n            self.tree.user_target_ids = inverse_id_map(\n                self.queue, self.tree.sorted_target_ids)\n        return target_array[self.tree.user_target_ids]\n\n    def reorder_potentials(self, potentials):\n        return FMMLibExpansionWrangler.reorder_potentials(self, potentials)\n\n    def finalize_potentials(self, potentials):\n        # return potentials\n        return FMMLibExpansionWrangler.finalize_potentials(self, potentials)\n\n    # }}} End data vector utilities\n\n    # {{{ formation & coarsening of multipoles\n\n    def form_multipoles(self, level_start_source_box_nrs, source_boxes, src_weights):\n        return FMMLibExpansionWrangler.form_multipoles(\n            self, level_start_source_box_nrs, source_boxes, src_weights\n        )\n\n    def coarsen_multipoles(\n        self, level_start_source_parent_box_nrs, source_parent_boxes, mpoles\n    ):\n        return FMMLibExpansionWrangler.coarsen_multipoles(\n            self, level_start_source_parent_box_nrs, source_parent_boxes, mpoles\n        )\n\n    # }}} End formation & coarsening of multipoles\n\n    # {{{ direct evaluation of near field interactions\n\n    def eval_direct_single_out_kernel(\n        self,\n        out_pot,\n        out_kernel,\n        target_boxes,\n        neighbor_source_boxes_starts,\n        neighbor_source_boxes_lists,\n        mode_coefs,\n    ):\n\n        # NOTE: mode_coefs are similar to source_weights BUT\n        # do not include quadrature weights (purely function\n        # expansiona coefficients)\n\n        if 0:\n            print(\"Returns range for list1\")\n            out_pot[:] = np.arange(len(out_pot))\n            return out_pot, None\n\n        kname = out_kernel.__repr__()\n\n        if isinstance(self.n_tables, int) and self.n_tables > 1:\n            use_multilevel_tables = True\n        elif isinstance(self.n_tables, dict) and self.n_tables[kname] > 1:\n            use_multilevel_tables = True\n        else:\n            use_multilevel_tables = False\n\n        if use_multilevel_tables:\n            # this checks that the boxes at the coarsest level\n            # and allows for some round-off error\n            min_lev = np.min(\n                self.tree.box_levels.get(self.queue)[target_boxes.get(self.queue)]\n            )\n            largest_cell_extent = self.tree.root_extent * 0.5 ** min_lev\n            if not self.near_field_table[kname][0].source_box_extent >= (\n                largest_cell_extent - 1e-15\n            ):\n                raise RuntimeError(\n                    \"Insufficient list of tables: the \"\n                    \"coarsest level mesh cells at level \"\n                    + str(min_lev)\n                    + \" are not covered.\"\n                )\n\n        # table.case_encode\n        distinct_numbers = set()\n        for vec in self.near_field_table[kname][0].interaction_case_vecs:\n            for cvc in vec:\n                distinct_numbers.add(cvc)\n        base = len(range(min(distinct_numbers), max(distinct_numbers) + 1))\n        shift = -min(distinct_numbers)\n\n        case_indices_dev = cl.array.to_device(\n            self.queue, self.near_field_table[kname][0].case_indices\n        )\n\n        # table.data\n        table_data_combined = np.zeros(\n            (\n                len(self.near_field_table[kname]),\n                len(self.near_field_table[kname][0].data),\n            ), dtype=self.near_field_table[kname][0].data.dtype\n        )\n        mode_nmlz_combined = np.zeros(\n            (\n                len(self.near_field_table[kname]),\n                len(self.near_field_table[kname][0].mode_normalizers),\n            ), dtype=self.near_field_table[kname][0].mode_normalizers.dtype\n        )\n        for lev in range(len(self.near_field_table[kname])):\n            table_data_combined[lev, :] = self.near_field_table[kname][lev].data\n            mode_nmlz_combined[lev, :] = self.near_field_table[kname][\n                lev\n            ].mode_normalizers\n        exterior_mode_nmlz_combined = np.zeros(\n            (\n                len(self.near_field_table[kname]),\n                len(self.near_field_table[kname][0].kernel_exterior_normalizers),\n            ),\n            dtype=self.near_field_table[kname][0].kernel_exterior_normalizers.dtype\n        )\n        for lev in range(len(self.near_field_table[kname])):\n            table_data_combined[lev, :] = self.near_field_table[kname][lev].data\n            mode_nmlz_combined[lev, :] = \\\n                self.near_field_table[kname][lev].mode_normalizers\n            exterior_mode_nmlz_combined[lev, :] = \\\n                self.near_field_table[kname][lev].kernel_exterior_normalizers\n\n        logger.info(\n                \"Table data for kernel \"\n                + out_kernel.__repr__() + \" congregated\")\n\n        # The loop domain needs to know some info about the tables being used\n        table_data_shapes = {\n            \"n_tables\": len(self.near_field_table[kname]),\n            \"n_q_points\": self.near_field_table[kname][0].n_q_points,\n            \"n_table_entries\": len(self.near_field_table[kname][0].data),\n        }\n        assert table_data_shapes[\"n_q_points\"] == len(\n            self.near_field_table[kname][0].mode_normalizers\n        )\n\n        from volumential.list1 import NearFieldFromCSR\n\n        near_field = NearFieldFromCSR(out_kernel, table_data_shapes,\n            potential_kind=self.potential_kind,\n            **self.list1_extra_kwargs)\n\n        res, evt = near_field(\n            self.queue,\n            result=out_pot,\n            box_centers=self.tree.box_centers,\n            box_levels=self.tree.box_levels,\n            box_source_counts_cumul=self.tree.box_target_counts_cumul,\n            box_source_starts=self.tree.box_target_starts,\n            box_target_counts_cumul=self.tree.box_target_counts_cumul,\n            box_target_starts=self.tree.box_target_starts,\n            case_indices=case_indices_dev,\n            encoding_base=base,\n            encoding_shift=shift,\n            mode_nmlz_combined=mode_nmlz_combined,\n            exterior_mode_nmlz_combined=exterior_mode_nmlz_combined,\n            neighbor_source_boxes_starts=neighbor_source_boxes_starts,\n            root_extent=self.tree.root_extent,\n            neighbor_source_boxes_lists=neighbor_source_boxes_lists,\n            mode_coefs=mode_coefs,\n            table_data_combined=table_data_combined,\n            target_boxes=target_boxes,\n            table_root_extent=self.root_table_source_box_extent,\n        )\n\n        if isinstance(out_pot, cl.array.Array):\n            assert res is out_pot\n            # FIXME: lazy evaluation sometimes returns incorrect results\n            res.finish()\n        else:\n            assert isinstance(out_pot, np.ndarray)\n            out_pot = res\n\n        # sorted_target_ids=self.tree.user_source_ids,\n        # user_source_ids=self.tree.user_source_ids)\n\n        scale_factor = self.get_scale_factor()\n        return out_pot / scale_factor, evt\n\n    def eval_direct(\n        self,\n        target_boxes,\n        neighbor_source_boxes_starts,\n        neighbor_source_boxes_lists,\n        mode_coefs,\n    ):\n        pot = self.output_zeros()\n        if pot.dtype != np.object:\n            pot = make_obj_array([pot, ])\n        events = []\n        for i in range(len(self.code.target_kernels)):\n            # print(\"processing near-field of out_kernel\", i)\n            pot[i], evt = self.eval_direct_single_out_kernel(\n                pot[i],\n                self.code.target_kernels[i],\n                target_boxes,\n                neighbor_source_boxes_starts,\n                neighbor_source_boxes_lists,\n                mode_coefs,\n            )\n            events.append(evt)\n\n        for out_pot in pot:\n            if isinstance(out_pot, cl.array.Array):\n                out_pot.finish()\n\n        # boxtree.pyfmmlib_integration handles things diffferently\n        # when target_kernels has only one element\n        if len(pot) == 1:\n            pot = pot[0]\n\n        return (pot, SumpyTimingFuture(self.queue, events))\n\n    # }}} End direct evaluation of near field interactions\n\n    # {{{ downward pass of fmm\n\n    def multipole_to_local(\n        self,\n        level_start_target_box_nrs,\n        target_boxes,\n        src_box_starts,\n        src_box_lists,\n        mpole_exps,\n    ):\n        return FMMLibExpansionWrangler.multipole_to_local(\n            self,\n            level_start_target_box_nrs,\n            target_boxes,\n            src_box_starts,\n            src_box_lists,\n            mpole_exps,\n        )\n\n    def eval_multipoles(\n        self, target_boxes_by_source_level, source_boxes_by_level, mpole_exps\n    ):\n        return FMMLibExpansionWrangler.eval_multipoles(\n            self, target_boxes_by_source_level, source_boxes_by_level, mpole_exps\n        )\n\n    def form_locals(\n        self,\n        level_start_target_or_target_parent_box_nrs,\n        target_or_target_parent_boxes,\n        starts,\n        lists,\n        src_weights,\n    ):\n        return FMMLibExpansionWrangler.form_locals(\n            self,\n            level_start_target_or_target_parent_box_nrs,\n            target_or_target_parent_boxes,\n            starts,\n            lists,\n            src_weights,\n        )\n\n    def refine_locals(\n        self,\n        level_start_target_or_target_parent_box_nrs,\n        target_or_target_parent_boxes,\n        local_exps,\n    ):\n        return FMMLibExpansionWrangler.refine_locals(\n            self,\n            level_start_target_or_target_parent_box_nrs,\n            target_or_target_parent_boxes,\n            local_exps,\n        )\n\n    def eval_locals(self, level_start_target_box_nrs, target_boxes, local_exps):\n        return FMMLibExpansionWrangler.eval_locals(\n            self, level_start_target_box_nrs, target_boxes, local_exps\n        )\n\n    # }}} End downward pass of fmm\n\n    # {{{ direct evaluation of p2p (discrete) interactions\n\n    def eval_direct_p2p(\n        self, target_boxes, source_box_starts, source_box_lists, src_weights\n    ):\n        return FMMLibExpansionWrangler.eval_direct(\n            self, target_boxes, source_box_starts, source_box_lists, src_weights\n        )\n\n    # }}} End direct evaluation of p2p interactions\n\n    @staticmethod\n    def is_supported_helmknl(knl):\n        if isinstance(knl, DirectionalSourceDerivative):\n            knl = knl.inner_kernel\n\n        return (isinstance(knl, (LaplaceKernel, HelmholtzKernel))\n                and knl.dim in (2, 3))\n\n\n# }}} End fmmlib backend (for laplace, helmholtz)\n\n\nclass FPNDExpansionWranglerCodeContainer(FPNDSumpyExpansionWranglerCodeContainer):\n    \"\"\"The default code container.\n    \"\"\"\n\n\nclass FPNDExpansionWrangler(FPNDSumpyExpansionWrangler):\n    \"\"\"The default wrangler class.\n    \"\"\"\n\n# vim: filetype=pyopencl:foldmethod=marker\n", "meta": {"hexsha": "b691f63f4d7edd57cb36c2dd68f229d47f2d88a6", "size": 43511, "ext": "py", "lang": "Python", "max_stars_repo_path": "volumential/expansion_wrangler_fpnd.py", "max_stars_repo_name": "xywei/volumential", "max_stars_repo_head_hexsha": "07c6ca8c623acf24fb8deddf93baa1035234db58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-21T23:57:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T22:02:50.000Z", "max_issues_repo_path": "volumential/expansion_wrangler_fpnd.py", "max_issues_repo_name": "inducer/volumential", "max_issues_repo_head_hexsha": "290a5943d3f47958dcab6736bc2b758525471570", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:41:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-26T15:42:21.000Z", "max_forks_repo_path": "volumential/expansion_wrangler_fpnd.py", "max_forks_repo_name": "inducer/volumential", "max_forks_repo_head_hexsha": "290a5943d3f47958dcab6736bc2b758525471570", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-21T21:23:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-21T21:23:39.000Z", "avg_line_length": 35.8410214168, "max_line_length": 85, "alphanum_fraction": 0.6143503942, "include": true, "reason": "import numpy", "num_tokens": 9053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3415824860330003, "lm_q1q2_score": 0.19726230251270496}}
{"text": "r\"\"\"Functions for spectator scattering corrections to $B\\to V\\ell^+\\ell^-$ decays.\n\nThis includes weak annihilation, chromomagnetic contributions, and light\nquark-loop spectator scattering.\n\"\"\"\n\nimport flavio\nimport numpy as np\nfrom flavio.classes import AuxiliaryQuantity, Implementation\nfrom flavio.physics.bdecays.common import meson_quark\nfrom flavio.physics.bdecays.wilsoncoefficients import wctot_dict\nfrom flavio.physics.common import conjugate_par, conjugate_wc, add_dict\nfrom flavio.config import config\n\n\n\n# Auxiliary quantities and implementations\n\n# function needed for the QCD factorization implementation (see qcdf.py)\ndef ha_qcdf_function(B, V):\n    scale = config['renormalization scale']['bvll']\n    label = meson_quark[(B,V)] + 'ee' # the lepton flavour is irrelevant here\n                                      # as only dipole and 4-quark operators contribute!\n    def function(wc_obj, par_dict, q2, cp_conjugate):\n        par = par_dict.copy()\n        if cp_conjugate:\n            par = conjugate_par(par)\n        wc = wctot_dict(wc_obj, label, scale, par)\n        if cp_conjugate:\n            wc = conjugate_wc(wc)\n        return flavio.physics.bdecays.bvll.qcdf.helicity_amps_qcdf(q2, wc, par, B, V)\n    return function\n\n# ... and the same for the interpolated version (see qcdf_interpolate.py)\ndef ha_qcdf_interpolate_function(B, V, contribution='all'):\n    scale = config['renormalization scale']['bvll']\n    def function(wc_obj, par_dict, q2, cp_conjugate):\n        return flavio.physics.bdecays.bvll.qcdf_interpolate.helicity_amps_qcdf(q2, par_dict, B, V, cp_conjugate, contribution)\n    return function\n\n# loop over hadronic transitions and lepton flavours\n# BTW, it is not necessary to loop over tau: for tautau final states, the minimum\n# q2=4*mtau**2 is so high that QCDF is not valid anymore anyway!\nfor had in [('B0','K*0'), ('B+','K*+'), ('B0','rho0'), ('B+','rho+'), ('Bs','phi'), ]:\n    process = had[0] + '->' + had[1] + 'll' # e.g. B0->K*0mumu\n    quantity = process + ' spectator scattering'\n    a = AuxiliaryQuantity(name=quantity, arguments=['q2', 'cp_conjugate'])\n    a.description = ('Contribution to ' + process + ' helicity amplitudes from'\n                    ' non-factorizable spectator scattering.')\n\n    # Implementation: QCD factorization\n    iname = process + ' QCDF'\n    i = Implementation(name=iname, quantity=quantity,\n                   function=ha_qcdf_function(B=had[0], V=had[1]))\n    i.set_description(\"QCD factorization\")\n\n    # Implementation: interpolated QCD factorization\n    iname = process + ' QCDF interpolated'\n    i = Implementation(name=iname, quantity=quantity,\n                   function=ha_qcdf_interpolate_function(B=had[0], V=had[1]))\n    i.set_description(\"Interpolated version of QCD factorization\")\n", "meta": {"hexsha": "184b0daa3e58653d7f742a83ccefb562276dd59f", "size": 2778, "ext": "py", "lang": "Python", "max_stars_repo_path": "flavio/physics/bdecays/bvll/nonfactorizable.py", "max_stars_repo_name": "Felicia56/flavio", "max_stars_repo_head_hexsha": "ea735bd8febbb961d249eddf338a4960c1fbee69", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61, "max_stars_repo_stars_event_min_datetime": "2016-03-09T16:19:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:55:51.000Z", "max_issues_repo_path": "flavio/physics/bdecays/bvll/nonfactorizable.py", "max_issues_repo_name": "Felicia56/flavio", "max_issues_repo_head_hexsha": "ea735bd8febbb961d249eddf338a4960c1fbee69", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 167, "max_issues_repo_issues_event_min_datetime": "2016-03-15T15:25:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T22:19:22.000Z", "max_forks_repo_path": "flavio/physics/bdecays/bvll/nonfactorizable.py", "max_forks_repo_name": "Felicia56/flavio", "max_forks_repo_head_hexsha": "ea735bd8febbb961d249eddf338a4960c1fbee69", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 57, "max_forks_repo_forks_event_min_datetime": "2016-03-15T14:24:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T01:00:03.000Z", "avg_line_length": 44.8064516129, "max_line_length": 126, "alphanum_fraction": 0.6958243341, "include": true, "reason": "import numpy", "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.19715090639729996}}
{"text": "# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Visualization of the results 3D VTK form\"\"\"\n\nimport os\nfrom pyevtk.hl import gridToVTK\nimport numpy as np\n\n\ndef vtk_structure(grid_tensor, eh_tensor, path_res):\n    r\"\"\"\n    Generates 3D vtk file for visualizaiton.\n\n    Args:\n        grid_tensor (numpy.ndarray): grid data (shape: (dim_t, dim_x, dim_y, dim_z, 4)).\n        eh_tensor (numpy.ndarray): electric and magnetic data (np.array, shape: (dim_t, dim_x, dim_y, dim_z, 6)).\n        path_res (str): save path for the output vtk file.\n\n    Supported Platforms:\n        ``Ascend``\n\n    Examples:\n        >>> import numpy as np\n        >>> from mindelec.vision import vtk_structure\n        >>> grid_tensor = np.random.rand(20, 10, 10, 10, 4).astype(np.float32)\n        >>> eh_tensor = np.random.rand(20, 10, 10, 10, 6).astype(np.float32)\n        >>> path_res = './result_vtk'\n        >>> vtk_structure(grid_tensor, eh_tensor, path_res)\n    \"\"\"\n    if not isinstance(grid_tensor, np.ndarray):\n        raise TypeError(\"The type of grid_tensor should be numpy array, but get {}\".format(type(grid_tensor)))\n\n    if not isinstance(eh_tensor, np.ndarray):\n        raise TypeError(\"The type of eh_tensor should be numpy array, but get {}\".format(type(eh_tensor)))\n\n    if not isinstance(path_res, str):\n        raise TypeError(\"The type of path_res should be str, but get {}\".format(type(path_res)))\n    if not os.path.exists(path_res):\n        os.makedirs(path_res)\n\n    input_grid = grid_tensor\n    output_grid = eh_tensor\n\n    shape_grid = input_grid.shape\n    shape_eh = output_grid.shape\n\n    if len(shape_grid) != 5 or shape_grid[-1] != 4:\n        raise ValueError(\"grid_tensor shape should be (dim_t, dim_x, dim_y, dim_z, 4), but get {}\"\n                         .format(shape_grid))\n\n    if len(shape_eh) != 5 or shape_eh[-1] != 6:\n        raise ValueError(\"eh_tensor shape should be (dim_t, dim_x, dim_y, dim_z, 6), but get {}\"\n                         .format(shape_eh))\n\n    if shape_grid[:4] != shape_eh[:4]:\n        raise ValueError(\"grid_tensor and eh_tensor should have the same dimension except the last axis, \"\n                         \"but get grid_tensor shape {} and eh_tensor shape{}\".format(shape_grid, shape_eh))\n\n    (dim_t, dim_x, dim_y, dim_z, d) = input_grid.shape\n    input_grid = np.reshape(input_grid, (dim_t * dim_x * dim_y * dim_z, d))\n    x_min, x_max = np.min(input_grid[:, 0]), np.max(input_grid[:, 0])\n    y_min, y_max = np.min(input_grid[:, 1]), np.max(input_grid[:, 1])\n    z_min, z_max = np.min(input_grid[:, 2]), np.max(input_grid[:, 2])\n\n    x_all = np.linspace(x_min, x_max, dim_x, endpoint=True, dtype='float64')\n    y_all = np.linspace(y_min, y_max, dim_y, endpoint=True, dtype='float64')\n    z_all = np.linspace(z_min, z_max, dim_z, endpoint=True, dtype='float64')\n\n    x = np.zeros((dim_x, dim_y, dim_z))\n    y = np.zeros((dim_x, dim_y, dim_z))\n    z = np.zeros((dim_x, dim_y, dim_z))\n\n    for i in range(dim_x):\n        for j in range(dim_y):\n            for k in range(dim_z):\n                x[i, j, k] = x_all[i]\n                y[i, j, k] = y_all[j]\n                z[i, j, k] = z_all[k]\n\n    for t in range(dim_t):\n        output_grid_show = output_grid[t]\n        ex, ey, ez = output_grid_show[:, :, :, 0], output_grid_show[:, :, :, 1], output_grid_show[:, :, :, 2]\n        hx, hy, hz = output_grid_show[:, :, :, 3], output_grid_show[:, :, :, 4], output_grid_show[:, :, :, 5]\n        ex, ey, ez = ex.astype(np.float64), ey.astype(np.float64), ez.astype(np.float64)\n        hx, hy, hz = hx.astype(np.float64), hy.astype(np.float64), hz.astype(np.float64)\n        gridToVTK(os.path.join(path_res, 'eh_t' + str(t)),\n                  x, y, z,\n                  pointData={\"Ex\": ex, \"Ey\": ey, \"Ez\": ez, \"Hx\": hx, \"Hy\": hy, \"Hz\": hz})\n", "meta": {"hexsha": "5051d730136f433055017c062dd64c2887a625ba", "size": 4399, "ext": "py", "lang": "Python", "max_stars_repo_path": "MindElec/mindelec/vision/body.py", "max_stars_repo_name": "mindspore-ai/mindscience", "max_stars_repo_head_hexsha": "b5269245915695de2d99fb290fef662c241db189", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-11-10T06:17:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T14:25:30.000Z", "max_issues_repo_path": "MindElec/mindelec/vision/body.py", "max_issues_repo_name": "mindspore-ai/mindscience", "max_issues_repo_head_hexsha": "b5269245915695de2d99fb290fef662c241db189", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MindElec/mindelec/vision/body.py", "max_forks_repo_name": "mindspore-ai/mindscience", "max_forks_repo_head_hexsha": "b5269245915695de2d99fb290fef662c241db189", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-05T11:41:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-05T11:41:29.000Z", "avg_line_length": 43.5544554455, "max_line_length": 113, "alphanum_fraction": 0.6180950216, "include": true, "reason": "import numpy", "num_tokens": 1182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19715090459420145}}
{"text": "\"\"\"\nrun_crack_lotf.py\nScript to run LOTF molecular dynamics for a crack slab,\nincrementing the load in small steps until fracture starts.\nJames Kermode <james.kermode@kcl.ac.uk>\nFebruary 2013\n\"\"\"\nimport numpy as np\n\nfrom ase.constraints import FixAtoms\nfrom ase.md.verlet import VelocityVerlet\nfrom ase.md.velocitydistribution import MaxwellBoltzmannDistribution\nimport ase.units as units\n\nfrom quippy import set_fortran_indexing\nfrom quippy.atoms import Atoms\nfrom quippy.potential import Potential\nfrom quippy.io import AtomsWriter\n\nfrom quippy.crack import (get_strain,\n                          get_energy_release_rate,\n                          ConstantStrainRate,\n                          find_crack_tip_stress_field)\n\n# additional requirements for the QM/MM simulation:\nfrom quippy.potential import ForceMixingPotential\nfrom quippy.lotf import LOTFDynamics, update_hysteretic_qm_region\n\n\n# ******* Start of parameters ***********\n\ninput_file = 'crack.xyz'         # File from which to read crack slab structure\nsim_T = 300.0*units.kB           # Simulation temperature\nnsteps = 1000000                   # Total number of timesteps to run for\ntimestep = 1.0*units.fs          # Timestep (NB: time base units are not fs!)\ncutoff_skin = 2.0*units.Ang      # Amount by which potential cutoff is increased\n                                 # for neighbour calculations\ntip_move_tol = 10.0              # Distance tip has to move before crack\n                                 # is taken to be running\nstrain_rate = 1e-5*(1/units.fs)  # Strain rate\ntraj_file = 'traj.xyz'           # Trajectory output file (NetCDF or XYZ format)\ntraj_interval = 10               # Number of time steps between\n                                 # writing output frames\nparam_file = 'params.xml'        # Filename of XML file containing\n                                 # potential parameters\nmm_init_args = 'IP SW'           # Initialisation arguments for\n                                 # classical potential\n\n# additional parameters for the QM/MM simulation:\nqm_init_args = 'TB DFTB'         # Initialisation arguments for QM potential\nqm_inner_radius = 6.0*units.Ang  # Inner hysteretic radius for QM region\nqm_outer_radius = 8.0*units.Ang  # Inner hysteretic radius for QM region\nextrapolate_steps = 10           # Number of steps for predictor-corrector\n                                 # interpolation and extrapolation\n\n# ******* End of parameters *************\n\nset_fortran_indexing(False)\n\n# ********** Read input file ************\n\nprint 'Loading atoms from file %s' % input_file\natoms = Atoms(input_file)\n\norig_height = atoms.info['OrigHeight']\norig_crack_pos = atoms.info['CrackPos'].copy()\n\n# ***** Setup constraints *******\n\ntop = atoms.positions[:, 1].max()\nbottom = atoms.positions[:, 1].min()\nleft = atoms.positions[:, 0].min()\nright = atoms.positions[:, 0].max()\n\n# fix atoms in the top and bottom rows\nfixed_mask = ((abs(atoms.positions[:, 1] - top) < 1.0) |\n              (abs(atoms.positions[:, 1] - bottom) < 1.0))\nfix_atoms = FixAtoms(mask=fixed_mask)\nprint('Fixed %d atoms\\n' % fixed_mask.sum())\natoms.set_constraint([fix_atoms])\n\n# Increase epsilon_yy applied to all atoms at constant strain rate\nstrain_atoms = ConstantStrainRate(orig_height, strain_rate*timestep)\n\n# ******* Set up potentials and calculators ********\n\nmm_pot = Potential(mm_init_args,\n                   param_filename=param_file,\n                   cutoff_skin=cutoff_skin)\n\n# Density functional tight binding (DFTB) potential\nqm_pot = Potential(qm_init_args,\n                   param_filename=param_file)\n\n# Construct the QM/MM potential, which mixes QM and MM forces.\n# The qm_args_str parameters control how the QM calculation is carried out:\n# we use a single cluster, periodic in the z direction and terminated\n# with hydrogen atoms. The positions of the outer layer of buffer atoms\n# are not randomised.\nqmmm_pot = ForceMixingPotential(pot1=mm_pot,\n                                pot2=qm_pot,\n                                qm_args_str='single_cluster cluster_periodic_z carve_cluster '+\n                                            'terminate cluster_hopping=F randomise_buffer=F',\n                                fit_hops=4,\n                                lotf_spring_hops=3,\n                                hysteretic_buffer=True,\n                                hysteretic_buffer_inner_radius=7.0,\n                                hysteretic_buffer_outer_radius=9.0,\n                                cluster_hopping_nneighb_only=False,\n                                min_images_only=True)\n\n# Use the force mixing potential as the Atoms' calculator\natoms.set_calculator(qmmm_pot)\nqmmm_pot.atoms = atoms\n\n# *** Set up the initial QM region ****\n\nqm_list = update_hysteretic_qm_region(atoms, [], orig_crack_pos,\n                                      qm_inner_radius, qm_outer_radius)\n\n# ********* Setup and run MD ***********\n\n# Set the initial temperature to 2*simT: it will then equilibriate to\n# simT, by the virial theorem\nMaxwellBoltzmannDistribution(atoms, 2.0*sim_T)\n\n# Initialise the dynamical system\ndynamics = LOTFDynamics(atoms, timestep, extrapolate_steps)\n\n# array to store time averaged stress field\navg_sigma = np.zeros((len(atoms), 3, 3))\n\n# Print some information every time step\ndef printstatus():\n    if dynamics.nsteps == 1:\n        print \"\"\"\nState      Time/fs    Temp/K     Strain      G/(J/m^2)  CrackPos/A D(CrackPos)/A\n---------------------------------------------------------------------------------\"\"\"\n\n    log_format = ('%(label)-4s%(time)12.1f%(temperature)12.6f'+\n                  '%(strain)12.5f%(G)12.4f%(crack_pos_x)12.2f    (%(d_crack_pos_x)+5.2f)')\n\n    atoms.info['label'] = dynamics.state_label  # Label for the status line\n    atoms.info['time'] = dynamics.get_time()/units.fs\n    atoms.info['temperature'] = (atoms.get_kinetic_energy() /\n                                 (1.5*units.kB*len(atoms)))\n    atoms.info['strain'] = get_strain(atoms)\n    atoms.info['G'] = get_energy_release_rate(atoms)/(units.J/units.m**2)\n\n    crack_pos = find_crack_tip_stress_field(atoms, calc=mm_pot,\n                                            avg_sigma=avg_sigma)\n    atoms.info['crack_pos_x'] = crack_pos[0]\n    atoms.info['d_crack_pos_x'] = crack_pos[0] - orig_crack_pos[0]\n\n    print log_format % atoms.info\n\ndynamics.attach(printstatus)\n\ndef atom_straining(atoms):\n    crack_pos = find_crack_tip_stress_field(atoms, calc=mm_pot,\n                                            avg_sigma=avg_sigma)\n    # keep straining until the crack tip has advanced to tip_move_tol\n    if not atoms.info['is_cracked'] and (crack_pos[0] - orig_crack_pos[0]) < tip_move_tol:\n      strain_atoms.apply_strain(atoms)\n    elif not atoms.info['is_cracked']:\n      atoms.info['is_cracked'] = True\n\ndynamics.attach(atom_straining, 1, dynamics.atoms)\n\n# Function to update the QM region at the beginning of each extrapolation cycle\ndef update_qm_region(atoms):\n   crack_pos = find_crack_tip_stress_field(atoms, calc=mm_pot,\n                                           avg_sigma=avg_sigma)\n   qm_list = qmmm_pot.get_qm_atoms(atoms)\n   qm_list = update_hysteretic_qm_region(atoms, qm_list, crack_pos,\n                                         qm_inner_radius, qm_outer_radius)\n   qmmm_pot.set_qm_atoms(qm_list, atoms)\n   #assert (atoms.hybrid == 1).sum() == len(qm_list)\n\ndynamics.set_qm_update_func(update_qm_region)\n\n\n# Save frames to the trajectory every `traj_interval` time steps\n# but only when interpolating\ntrajectory = AtomsWriter(traj_file)\n\ndef traj_writer(dynamics):\n   if dynamics.state == LOTFDynamics.Interpolation:\n      # copy time-averaged stress into Atoms so it will be written to trajectory file\n      dynamics.atoms.set_array('avg_sigma', avg_sigma.reshape((len(atoms), 9)))\n      trajectory.write(dynamics.atoms)\n\ndynamics.attach(traj_writer, traj_interval, dynamics)\n\n# Start running!\ndynamics.run(nsteps)\n", "meta": {"hexsha": "b4565469e9c4a2ed6d97a71eef4173eb83fad750", "size": 7912, "ext": "py", "lang": "Python", "max_stars_repo_path": "doc/Tutorials/run_crack_lotf.py", "max_stars_repo_name": "albapa/QUIP", "max_stars_repo_head_hexsha": "ecde1e332c6bd62c238d3cd90e31dba4fb390313", "max_stars_repo_licenses": ["NRL"], "max_stars_count": 229, "max_stars_repo_stars_event_min_datetime": "2015-01-20T16:35:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T10:44:32.000Z", "max_issues_repo_path": "doc/Tutorials/run_crack_lotf.py", "max_issues_repo_name": "albapa/QUIP", "max_issues_repo_head_hexsha": "ecde1e332c6bd62c238d3cd90e31dba4fb390313", "max_issues_repo_licenses": ["NRL"], "max_issues_count": 356, "max_issues_repo_issues_event_min_datetime": "2015-05-29T08:28:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:55:34.000Z", "max_forks_repo_path": "doc/Tutorials/run_crack_lotf.py", "max_forks_repo_name": "albapa/QUIP", "max_forks_repo_head_hexsha": "ecde1e332c6bd62c238d3cd90e31dba4fb390313", "max_forks_repo_licenses": ["NRL"], "max_forks_count": 106, "max_forks_repo_forks_event_min_datetime": "2015-01-21T12:56:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T08:39:24.000Z", "avg_line_length": 40.1624365482, "max_line_length": 95, "alphanum_fraction": 0.6449696663, "include": true, "reason": "import numpy", "num_tokens": 1876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.19715090084274456}}
{"text": "# Copyright 2016-2020 Blue Marble Analytics LLC.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport csv\nimport os.path\nfrom pyomo.environ import Param, Set, NonNegativeReals, PercentFraction, Expression\n\n\ndef generic_add_model_components(\n    m,\n    d,\n    reserve_zone_set,\n    reserve_requirement_tmp_param,\n    reserve_requirement_percent_param,\n    reserve_zone_load_zone_set,\n    ba_prj_req_contribution_set,\n    prj_power_param,\n    prj_capacity_param,\n    reserve_requirement_expression,\n):\n    \"\"\"\n    :param m:\n    :param d:\n    :param reserve_zone_set:\n    :param reserve_requirement_tmp_param:\n    :param reserve_requirement_percent_param:\n    :param reserve_zone_load_zone_set:\n    :param ba_prj_req_contribution_set:\n    :param prj_power_param:\n    :param prj_capacity_param:\n    :param reserve_requirement_expression:\n    :return:\n\n    Generic treatment of reserves. This function creates model components\n    related to a particular reserve requirement, including\n    1) the reserve requirement by zone and timepoint, if any\n    2) the reserve requirement as a percent of load and map for which load\n    zones' load to consider\n    3) the contributions to the reserve requirement from projects: there are two\n    types of these contributions, those based on the power output in the timepoint\n    and those based on the project capacity.\n    \"\"\"\n\n    # Magnitude of the requirement by reserve zone and timepoint\n    # If not specified for a reserve zone - timepoint combination,\n    # will default to 0\n    setattr(\n        m,\n        reserve_requirement_tmp_param,\n        Param(getattr(m, reserve_zone_set), m.TMPS, within=NonNegativeReals, default=0),\n    )\n\n    # Requirement as percentage of load\n    setattr(\n        m,\n        reserve_requirement_percent_param,\n        Param(getattr(m, reserve_zone_set), within=PercentFraction, default=0),\n    )\n\n    # Load zones included in the reserve percentage requirement\n    setattr(\n        m,\n        reserve_zone_load_zone_set,\n        Set(dimen=2, within=getattr(m, reserve_zone_set) * m.LOAD_ZONES),\n    )\n\n    # Projects contributing to BA requirement based on power output in the timepoint\n    # and on capacity in the period\n    setattr(\n        m,\n        ba_prj_req_contribution_set,\n        Set(dimen=2, within=getattr(m, reserve_zone_set) * m.PROJECTS),\n    )\n\n    setattr(\n        m,\n        prj_power_param,\n        Param(\n            getattr(m, ba_prj_req_contribution_set), within=PercentFraction, default=0\n        ),\n    )\n\n    setattr(\n        m,\n        prj_capacity_param,\n        Param(\n            getattr(m, ba_prj_req_contribution_set), within=PercentFraction, default=0\n        ),\n    )\n\n    def reserve_requirement_rule(mod, reserve_zone, tmp):\n        # If we have a map of reserve zones to load zones, apply the percentage\n        # target; if no map provided, the percentage_target is 0\n        if getattr(mod, reserve_zone_load_zone_set):\n            percentage_target = sum(\n                getattr(mod, reserve_requirement_percent_param)[reserve_zone]\n                * mod.static_load_mw[lz, tmp]\n                for (_reserve_zone, lz) in getattr(mod, reserve_zone_load_zone_set)\n                if _reserve_zone == reserve_zone\n            )\n        else:\n            percentage_target = 0\n\n        # Project contributions, if any projects in the respective set\n        if getattr(mod, ba_prj_req_contribution_set):\n            # Project contributions to requirement based on power output\n            prj_pwr_contribution = sum(\n                getattr(mod, prj_power_param)[reserve_zone, prj]\n                * mod.Power_Provision_MW[prj, tmp]\n                for (_reserve_zone, prj) in getattr(mod, ba_prj_req_contribution_set)\n                if _reserve_zone == reserve_zone\n                if (prj, tmp) in mod.PRJ_OPR_TMPS\n            )\n\n            # Project contributions to requirement based on (available) capacity\n            # We are not holding the extra reserves when projects are unavailable\n            prj_cap_contribution = sum(\n                getattr(mod, prj_capacity_param)[reserve_zone, prj]\n                * mod.Capacity_MW[prj, mod.period[tmp]]\n                * mod.Availability_Derate[prj, tmp]\n                for (_reserve_zone, prj) in getattr(mod, ba_prj_req_contribution_set)\n                if _reserve_zone == reserve_zone\n                if (prj, tmp) in mod.PRJ_OPR_TMPS\n            )\n        else:\n            prj_pwr_contribution = 0\n            prj_cap_contribution = 0\n\n        return (\n            getattr(mod, reserve_requirement_tmp_param)[reserve_zone, tmp]\n            + percentage_target\n            + prj_pwr_contribution\n            + prj_cap_contribution\n        )\n\n    setattr(\n        m,\n        reserve_requirement_expression,\n        Expression(\n            getattr(m, reserve_zone_set) * m.TMPS, rule=reserve_requirement_rule\n        ),\n    )\n\n\ndef generic_load_model_data(\n    m,\n    d,\n    data_portal,\n    scenario_directory,\n    subproblem,\n    stage,\n    reserve_requirement_param,\n    reserve_zone_load_zone_set,\n    reserve_requirement_percent_param,\n    ba_prj_req_contribution_set,\n    prj_power_param,\n    prj_capacity_param,\n    reserve_type,\n):\n    \"\"\"\n\n    :param m:\n    :param d:\n    :param data_portal:\n    :param scenario_directory:\n    :param subproblem:\n    :param stage:\n    :param reserve_requirement_param:\n    :param reserve_zone_load_zone_set:\n    :param reserve_requirement_percent_param\n    :param ba_prj_req_contribution_set\n    :param prj_power_param\n    :param prj_capacity_param\n    :param reserve_type:\n    :return:\n    \"\"\"\n    input_dir = os.path.join(scenario_directory, str(subproblem), str(stage), \"inputs\")\n\n    # Load by-tmp requriement if input file was written\n    by_tmp_req_filename = os.path.join(\n        input_dir, \"{}_tmp_requirement.tab\".format(reserve_type)\n    )\n    if os.path.exists(by_tmp_req_filename):\n        tmp_params_to_load = (\n            (\n                getattr(m, reserve_requirement_param),\n                m.frequency_response_requirement_partial_mw,\n            )\n            if reserve_type == \"frequency_response\"\n            else getattr(m, reserve_requirement_param)\n        )\n        data_portal.load(filename=by_tmp_req_filename, param=tmp_params_to_load)\n\n    # If we have a RPS zone to load zone map input file, load it and the\n    # percent requirement; otherwise, initialize the set as an empty list (\n    # the param defaults to 0)\n    map_filename = os.path.join(input_dir, \"{}_percent_map.tab\".format(reserve_type))\n    if os.path.exists(map_filename):\n        data_portal.load(\n            filename=map_filename, set=getattr(m, reserve_zone_load_zone_set)\n        )\n        data_portal.load(\n            filename=os.path.join(\n                input_dir, \"{}_percent_requirement.tab\".format(reserve_type)\n            ),\n            param=getattr(m, reserve_requirement_percent_param),\n        )\n    else:\n        data_portal.data()[reserve_zone_load_zone_set] = {None: []}\n\n    # If we have a project contributions file, load it into the respective\n    prj_contr_filename = os.path.join(\n        input_dir, \"{}_requirement_project_contributions.tab\".format(reserve_type)\n    )\n    if os.path.exists(prj_contr_filename):\n        data_portal.load(\n            filename=prj_contr_filename,\n            index=getattr(m, ba_prj_req_contribution_set),\n            param=(getattr(m, prj_power_param), getattr(m, prj_capacity_param)),\n        )\n    else:\n        data_portal.data()[ba_prj_req_contribution_set] = {None: []}\n\n\ndef generic_get_inputs_from_database(\n    scenario_id,\n    subscenarios,\n    subproblem,\n    stage,\n    conn,\n    reserve_type,\n    reserve_type_ba_subscenario_id,\n    reserve_type_req_subscenario_id,\n):\n    \"\"\"\n    :param subscenarios:\n    :param subproblem:\n    :param stage:\n    :param conn:\n    :param reserve_type:\n    :param reserve_type_ba_subscenario_id:\n    :param reserve_type_req_subscenario_id:\n    :return:\n    \"\"\"\n    subproblem = 1 if subproblem == \"\" else subproblem\n    stage = 1 if stage == \"\" else stage\n    c = conn.cursor()\n\n    partial_freq_resp_extra_column = (\n        \", frequency_response_partial_mw\"\n        if reserve_type == \"frequency_response\"\n        else \"\"\n    )\n\n    tmp_req = c.execute(\n        \"\"\"SELECT {}_ba, timepoint, {}_mw{}\n        FROM inputs_system_{}\n        INNER JOIN\n        (SELECT timepoint\n        FROM inputs_temporal\n        WHERE temporal_scenario_id = {}\n        AND subproblem_id = {}\n        AND stage_id = {}) as relevant_timepoints\n        USING (timepoint)\n        INNER JOIN\n        (SELECT {}_ba\n        FROM inputs_geography_{}_bas\n        WHERE {}_ba_scenario_id = {}) as relevant_bas\n        USING ({}_ba)\n        WHERE {}_scenario_id = {}\n        AND stage_id = {}\n        \"\"\".format(\n            reserve_type,\n            reserve_type,\n            partial_freq_resp_extra_column,\n            reserve_type,\n            subscenarios.TEMPORAL_SCENARIO_ID,\n            subproblem,\n            stage,\n            reserve_type,\n            reserve_type,\n            reserve_type,\n            reserve_type_ba_subscenario_id,\n            reserve_type,\n            reserve_type,\n            reserve_type_req_subscenario_id,\n            stage,\n        )\n    )\n\n    c2 = conn.cursor()\n    # Get any percentage requirement\n    percentage_req = c2.execute(\n        \"\"\"\n        SELECT {}_ba, percent_load_req\n        FROM inputs_system_{}_percent\n        WHERE {}_scenario_id = {}\n        \"\"\".format(\n            reserve_type, reserve_type, reserve_type, reserve_type_req_subscenario_id\n        )\n    )\n\n    # Get any reserve zone to load zone mapping for the percent target\n    c3 = conn.cursor()\n    lz_mapping = c3.execute(\n        \"\"\"\n        SELECT {}_ba, load_zone\n        FROM inputs_system_{}_percent_lz_map\n        JOIN\n        (SELECT {}_ba\n        FROM inputs_geography_{}_bas\n        WHERE {}_ba_scenario_id = {}) as relevant_bas\n        USING ({}_ba)\n        WHERE {}_scenario_id = {}\n        \"\"\".format(\n            reserve_type,\n            reserve_type,\n            reserve_type,\n            reserve_type,\n            reserve_type,\n            reserve_type_ba_subscenario_id,\n            reserve_type,\n            reserve_type,\n            reserve_type_req_subscenario_id,\n        )\n    )\n\n    # Get any project contributions to the magnitude of the reserve requirement\n    c4 = conn.cursor()\n    project_contributions = c4.execute(\n        \"\"\"\n        SELECT {reserve_type}_ba, project, percent_power_req, percent_capacity_req\n        FROM inputs_system_{reserve_type}_project\n        JOIN (\n        SELECT {reserve_type}_ba\n        FROM inputs_geography_{reserve_type}_bas\n        WHERE {reserve_type}_ba_scenario_id = {reserve_type_ba_subscenario_id}\n        ) as relevant_bas\n        USING ({reserve_type}_ba)\n        JOIN (\n        SELECT project\n        FROM inputs_project_portfolios\n        WHERE project_portfolio_scenario_id = (\n                SELECT project_portfolio_scenario_id\n                FROM scenarios\n                WHERE scenario_id = {scenario_id}\n            )\n        ) as relevant_prj\n        USING (project)\n        WHERE {reserve_type}_scenario_id = {reserve_type_req_subscenario_id}\n        \"\"\".format(\n            reserve_type=reserve_type,\n            reserve_type_ba_subscenario_id=reserve_type_ba_subscenario_id,\n            scenario_id=scenario_id,\n            reserve_type_req_subscenario_id=reserve_type_req_subscenario_id,\n        )\n    )\n\n    return tmp_req, percentage_req, lz_mapping, project_contributions\n\n\ndef generic_write_model_inputs(\n    scenario_directory,\n    subproblem,\n    stage,\n    timepoint_req,\n    percent_req,\n    percent_map,\n    project_contributions,\n    reserve_type,\n):\n    \"\"\"\n    Get inputs from database and write out the model input\n    lf_reserves_down_requirement.tab file.\n    :param scenario_directory: string, the scenario directory\n    :param subproblem:\n    :param stage:\n    :param timepoint_req:\n    :param percent_req:\n    :param percent_map:\n    :param project_contributions:\n    :param reserve_type:\n    :return:\n    \"\"\"\n    inputs_dir = os.path.join(scenario_directory, str(subproblem), str(stage), \"inputs\")\n\n    # Write the by-timepoint requirement file if by-tmp requirement specified\n    timepoint_req = timepoint_req.fetchall()\n    if timepoint_req:\n        with open(\n            os.path.join(inputs_dir, \"{}_tmp_requirement.tab\".format(reserve_type)),\n            \"w\",\n            newline=\"\",\n        ) as tmp_req_file:\n            writer = csv.writer(tmp_req_file, delimiter=\"\\t\", lineterminator=\"\\n\")\n\n            # Write header\n            extra_column = (\n                [\"partial_requirement\"] if reserve_type == \"frequency_response\" else []\n            )\n            writer.writerow([\"ba\", \"timepoint\", \"requirement\"] + extra_column)\n\n            for row in timepoint_req:\n                writer.writerow(row)\n\n    # Write the percent requirement files only if there's a mapping\n    ba_lz_map_list = [row for row in percent_map]\n\n    if ba_lz_map_list:\n        with open(\n            os.path.join(inputs_dir, \"{}_percent_requirement.tab\".format(reserve_type)),\n            \"w\",\n            newline=\"\",\n        ) as percent_req_file:\n            writer = csv.writer(percent_req_file, delimiter=\"\\t\", lineterminator=\"\\n\")\n\n            # Write header\n            writer.writerow([\"ba\", \"percent_requirement\"])\n\n            for row in percent_req:\n                writer.writerow(row)\n\n        with open(\n            os.path.join(inputs_dir, \"{}_percent_map.tab\".format(reserve_type)),\n            \"w\",\n            newline=\"\",\n        ) as percent_map_file:\n            writer = csv.writer(percent_map_file, delimiter=\"\\t\", lineterminator=\"\\n\")\n\n            # Write header\n            writer.writerow([\"ba\", \"load_zone\"])\n\n            for row in ba_lz_map_list:\n                writer.writerow(row)\n    else:\n        pass\n\n    # Project contributions to the magnitude requirement\n    project_contributions = project_contributions.fetchall()\n\n    prj_contributions = False\n    for (ba, prj, pwr, cap) in project_contributions:\n        if pwr is not None or cap is not None:\n            prj_contributions = True\n\n    if prj_contributions:\n        with open(\n            os.path.join(\n                inputs_dir,\n                \"{}_requirement_project_contributions.tab\".format(reserve_type),\n            ),\n            \"w\",\n            newline=\"\",\n        ) as prj_file:\n            writer = csv.writer(prj_file, delimiter=\"\\t\", lineterminator=\"\\n\")\n\n            # Write header\n            writer.writerow(\n                [\"ba\", \"project\", \"percent_power_req\", \"percent_capacity_req\"]\n            )\n            for (ba, prj, pwr, cap) in project_contributions:\n                if pwr is None:\n                    pwr = \".\"\n                if cap is None:\n                    cap = \".\"\n                writer.writerow([ba, prj, pwr, cap])\n", "meta": {"hexsha": "a68a396ae61a1be229daba28fd8b851ab05ae4a1", "size": 15454, "ext": "py", "lang": "Python", "max_stars_repo_path": "gridpath/system/reserves/requirement/reserve_requirements.py", "max_stars_repo_name": "souissim/gridpath", "max_stars_repo_head_hexsha": "4eeca2be24b485edc56026e38cfda83f4a6b27ea", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gridpath/system/reserves/requirement/reserve_requirements.py", "max_issues_repo_name": "souissim/gridpath", "max_issues_repo_head_hexsha": "4eeca2be24b485edc56026e38cfda83f4a6b27ea", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gridpath/system/reserves/requirement/reserve_requirements.py", "max_forks_repo_name": "souissim/gridpath", "max_forks_repo_head_hexsha": "4eeca2be24b485edc56026e38cfda83f4a6b27ea", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3305439331, "max_line_length": 88, "alphanum_fraction": 0.6305163712, "include": true, "reason": "from pyomo", "num_tokens": 3416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19715089903964625}}
{"text": "\"\"\"\n  Copyright (c) 2015 Semafor Informatik & Energie AG\n\n\"\"\"\nimport sys\nimport numpy as np\nimport copy\nimport operator as op\n\n\nclass Individual:\n    def __init__(self, n_dim, f_dim):\n        self.cur_f = [0]*f_dim\n        self.cur_x = [0]*n_dim\n        self.cur_v = []\n        self.cur_c = []\n\n        self.rank = 0\n        self.crowd_d = 0\n        self.idx = 0\n\n    def __str__(self):\n        return \"f {} x {} rank {} crowd_d {}\".format(self.cur_f, self.cur_x,\n                                                     self.rank, self.crowd_d)\n\n\nclass Population:\n\n    def __init__(self, probl, size, seed=None):\n        self.individuals = []\n        self.problem = probl\n        self.champion = None\n        self.dom_count = []\n        self.dom_list = []\n        np.random.seed(seed)\n        for s in range(size):\n            self.append([np.random.uniform(lb, ub)\n                         for lb, ub in zip(self.problem.lower,\n                                           self.problem.upper)])\n#        kmax=int(np.sqrt(size))+1\n#        f=[]\n#        for i in range(kmax):\n#            for k in range(kmax):\n#                f.append((i*0.8/kmax +0.1, k*0.8/kmax +0.1))\n#        for k,i in enumerate(self.individuals):\n#            i.cur_f = f[k]\n\n    def size(self):\n        return len(self.individuals)\n\n    def copy(self):\n        return copy.copy(self)\n\n    def append(self, child):\n        self.individuals.append(Individual(self.problem.dimension,\n                                           self.problem.f_dim))\n        self.individuals[-1].cur_x = child\n        self.individuals[-1].idx = len(self.individuals)-1\n        self.init_velocity()\n\n    def eval(self):\n        for k, i in enumerate(self.individuals):\n            i.cur_f = self.problem.objfun(i.cur_x)\n        self.update()\n\n    def best_idx(self):\n        return [i.idx for i in sorted(self.individuals,\n                                      key=op.attrgetter('rank',\n                                                        'crowd_d'))]\n\n    def merge(self, pop):\n        \"sort by rank and crowding distance (proximity)\"\n        self.individuals += pop.individuals\n        self.update()\n        for i in self.individuals:\n            if abs(i.crowd_d) > sys.float_info.epsilon:\n                i.crowd_d = 1/i.crowd_d\n            else:\n                i.crowd_d = sys.float_info.max\n\n        best = sorted(self.individuals,\n                      key=op.attrgetter('rank',\n                                        'crowd_d'))\n        self.individuals = best[:pop.size()]\n        self.update()\n\n    def init_velocity(self):\n        for i, j in enumerate(self.individuals[-1].cur_x):\n            w = (self.problem.upper[i] - self.problem.lower[i])/2\n            self.individuals[-1].cur_v.append(np.random.uniform(-w, w))\n\n    def populate(self, x, f, s):\n        \"\"\"populate with decision and objective values multiplied by sign\n        x: vector of decision values\n        f: matrix of objective values\n        s: vector of signs (1, -1)\"\"\"\n        for k, i in enumerate(self.individuals):\n            i.cur_x = x[k]\n            i.cur_f = [v*sign\n                       for v, sign in zip(f[:, k], s)]\n        self.update()\n\n    def get_ranked_decisions(self):\n        px = dict()\n        for i in self.individuals:\n            k = i.rank\n            if k in px:\n                px[k].append(i.cur_x)\n            else:\n                px[k] = [i.cur_x]\n        return px\n\n    def get_ranked_objectives(self, s):\n        po = dict()\n        for i in self.individuals:\n            cur_f = [v*sign\n                     for v, sign in zip(i.cur_f, s)]\n            k = i.rank\n            if k in po:\n                po[k].append(cur_f)\n            else:\n                po[k] = [cur_f]\n        return po\n\n    def update(self):\n        size = len(self.individuals)\n        self.dom_count = []\n        self.dom_list = [[] for s in range(size)]\n        self.champion = None\n        for s in range(size):\n            self.dom_count.append(0)\n            self.update_dom(s)\n            self.update_champion(s)\n        self.update_pareto_information()\n\n    def update_dom(self, n):\n        \"\"\"Loop over the population (j) and construct\n        dom_list[n] and dom_count \"\"\"\n\n        for i, x in enumerate(self.individuals):\n            if i != n:\n                # check if individual in position i\n                # dominates the one in position n\n                if self.problem.compare_fc(x.cur_f, x.cur_c,\n                                           self.individuals[n].cur_f,\n                                           self.individuals[n].cur_c):\n                    self.dom_count[n] += 1\n                    self.dom_list[i].append(n)\n\n    def update_champion(self, idx):\n        if self.champion is None or \\\n            self.problem.compare_fc(self.individuals[idx].cur_f,\n                                    self.individuals[idx].cur_c,\n                                    self.champion['f'], self.champion['c']):\n            self.champion = dict(x=self.individuals[idx].cur_x,\n                                 f=self.individuals[idx].cur_f,\n                                 c=self.individuals[idx].cur_c)\n\n    def update_crowding(self, F):\n        # sort along the fitness dimension\n        for i in range(self.problem.f_dim):\n            I = sorted(F, key=lambda k: self.individuals[k].cur_f[i],\n                       reverse=True)\n            self.individuals[I[0]].crowd_d = sys.float_info.max\n            self.individuals[I[-1]].crowd_d = sys.float_info.max\n            df = (self.individuals[I[-1]].cur_f[i] -\n                  self.individuals[I[0]].cur_f[i])\n            for j in range(1, len(F)-1):\n                if abs(df) > sys.float_info.epsilon:\n                    self.individuals[I[j]].crowd_d += (\n                        self.individuals[I[j+1]].cur_f[i] -\n                        self.individuals[I[j-1]].cur_f[i])/df\n\n    def update_pareto_information(self):\n        size = len(self.individuals)\n        self.pareto_rank = [0]*size\n        F = [i for i, c in enumerate(self.dom_count) if c == 0]\n        irank = 1\n        dom_count_copy = list(self.dom_count)\n        while True:\n            self.update_crowding(F)\n            S = []\n            for i, f in enumerate(F):\n                for j, k in enumerate(self.dom_list[f]):\n                    dom_count_copy[k] -= 1\n                    if dom_count_copy[k] == 0:\n                        S.append(k)\n                        self.pareto_rank[k] = irank\n                        self.individuals[k].rank = irank\n            if S:\n                F = list(S)\n            else:\n                return\n\n            irank += 1\n\n    def compute_pareto_fronts(self):\n        self.update_pareto_information()\n        retval = [[] for s in range(max(self.pareto_rank)+1)]\n        for i, j in enumerate(self.individuals):\n            retval[self.pareto_rank[i]].append(i)\n        return retval\n\n    def compute_ideal(self):\n        return [min(x)\n                for x in zip(*[i.cur_f\n                               for i in self.individuals if i.rank == 0])]\n\n    def compute_nadir(self):\n        return [max(x)\n                for x in zip(*[i.cur_f\n                               for i in self.individuals if i.rank == 0])]\n\n    def compute_worst(self):\n        return [max(x)\n                for x in zip(*[i.cur_f\n                               for i in self.individuals])]\n\n    def compute_norm_dist(self):\n        zi = np.array(self.compute_ideal())\n        zw = np.array(self.compute_worst())\n        znad = np.array(self.compute_nadir())\n        return np.sqrt(((znad-zi)**2).sum() / ((zw-zi)**2).sum())\n\n    def plot_pareto_fronts(\n            self,\n            rgb=(\n                0,\n                0,\n                0),\n            comp=[\n                0,\n                1],\n            symbol='o',\n            size=6,\n            fronts=[]):\n        \"\"\"\n        Plots the population pareto front in a 2-D graph\n\n        USAGE: pop.plot_pareto_front(comp = [0,1], rgb=(0,1,0))\n\n        * comp: components of the fitness function to plot in the 2-D window\n        * rgb: specify the color of the 1st front (use strong colors here)\n        * symbol: marker for the individual\n        * size: size of the markersymbol\n        * fronts: list of fronts to be plotted (use [0] to only show the first)\n        \"\"\"\n        from numpy import linspace\n        import matplotlib.pyplot as plt\n\n        if len(comp) != 2:\n            raise ValueError(\n                'Invalid components of the objective function selected for plot')\n\n        p_dim = self.problem.f_dimension\n\n        if p_dim == 1:\n            raise ValueError(\n                'Pareto fronts of a 1-dimensional problem cannot be plotted')\n\n        if not all([c in range(0, p_dim) for c in comp]):\n            raise ValueError(\n                'You need to select valid components of the objective function')\n\n        p_list = self.compute_pareto_fronts()\n        if (len(fronts) > 0):\n            n = len(p_list)\n            consistent = [d < n for d in fronts]\n            if consistent.count(False) > 0:\n                raise ValueError(\n                    'Check your fronts list, there seem to be not enough fronts')\n            p_list = [p_list[idx] for idx in fronts]\n\n        cl = list(zip(linspace(0.9 if rgb[0] else 0.1, 0.9, len(p_list)),\n                      linspace(0.9 if rgb[1] else 0.1, 0.9, len(p_list)),\n                      linspace(0.9 if rgb[2] else 0.1, 0.9, len(p_list))))\n\n        for id_f, f in enumerate(p_list):\n            for ind in f:\n                plt.plot([ind.cur_f[comp[0]]],\n                         [ind.cur_f[comp[1]]],\n                         symbol,\n                         color=cl[id_f], markersize=size)\n            x = [ind.cur_f[comp[0]] for ind in f]\n            y = [ind.cur_f[comp[1]] for ind in f]\n            tmp = [(a, b) for a, b in zip(x, y)]\n            tmp = sorted(tmp, key=lambda k: k[0])\n            plt.step([c[0] for c in tmp], [c[1]\n                     for c in tmp], color=cl[id_f], where='post')\n        return plt.gca()\n", "meta": {"hexsha": "4ec0a77895892c19694b22e3a8a62c518d0cabab", "size": 10100, "ext": "py", "lang": "Python", "max_stars_repo_path": "femagtools/moo/population.py", "max_stars_repo_name": "dapu/femagtools", "max_stars_repo_head_hexsha": "95eaf750adc2013232cdf482e523b3900ac6eb08", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2016-09-07T12:17:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T11:43:24.000Z", "max_issues_repo_path": "femagtools/moo/population.py", "max_issues_repo_name": "dapu/femagtools", "max_issues_repo_head_hexsha": "95eaf750adc2013232cdf482e523b3900ac6eb08", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 63, "max_issues_repo_issues_event_min_datetime": "2016-09-11T12:04:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T13:22:16.000Z", "max_forks_repo_path": "femagtools/moo/population.py", "max_forks_repo_name": "dapu/femagtools", "max_forks_repo_head_hexsha": "95eaf750adc2013232cdf482e523b3900ac6eb08", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2017-07-12T13:05:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-08T11:43:26.000Z", "avg_line_length": 34.7079037801, "max_line_length": 81, "alphanum_fraction": 0.4947524752, "include": true, "reason": "import numpy,from numpy", "num_tokens": 2407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.19715089168199268}}
{"text": "from __future__ import annotations\n\nfrom typing import Any, Generic, Tuple, TypeVar\n\nimport jax.numpy as jnp\nfrom jax import vjp\nfrom jax.tree_util import tree_map\n\nfrom ..annotations import PyTree\nfrom ..dataclasses import dataclass\nfrom ..shims import custom_vjp\nfrom .augmented import State\nfrom .comparing import ComparingIteratedFunction, ComparingState\nfrom .iterated_function import (Comparand, IteratedFunction, Parameters, TheAugmentedState,\n                                Trajectory)\n\n__all__ = ['IteratedFunctionWithCombinator', 'ComparingIteratedFunctionWithCombinator']\n\n\nDifferentiand = TypeVar('Differentiand', bound=PyTree)\n\n\n@dataclass\nclass _ZResiduals(Generic[Parameters, State, Comparand, Differentiand, TheAugmentedState]):\n    outer_iterated_function: IteratedFunctionWithCombinator[Parameters, State, Comparand,\n                                                            Differentiand, Any, TheAugmentedState]\n    outer_theta: Parameters\n    x_star: State\n\n\n@dataclass\nclass _ZParameters(Generic[Parameters, State, Differentiand]):\n    outer_theta: Parameters\n    x_star: State\n    x_star_differentiand: Differentiand\n    x_star_bar_differentiand: Differentiand\n\n\ndef _ffp_fwd(outer_iterated_function: IteratedFunctionWithCombinator[Parameters, State, Comparand,\n                                                                     Differentiand, Any,\n                                                                     TheAugmentedState],\n             theta: Parameters,\n             initial_state: State) -> Tuple[TheAugmentedState, _ZResiduals[Parameters, State,\n                                                                           Comparand, Differentiand,\n                                                                           TheAugmentedState]]:\n    \"\"\"\n    Args:\n        theta: The parameters for which gradients can be calculated.\n        initial_state: An initial guess of the final state.\n    Returns:\n        x_star: the result of the minimization.\n        residuals: residuals used in _ffp_bwd.\n    \"\"\"\n    augmented: TheAugmentedState = outer_iterated_function.find_fixed_point(\n        theta, initial_state)\n    return augmented, _ZResiduals(outer_iterated_function, theta, augmented.current_state)\n\n\ndef _ffp_bwd(residuals: _ZResiduals[Parameters, State, Comparand, Differentiand, TheAugmentedState],\n             augmented_star_bar: TheAugmentedState) -> Tuple[None, Parameters, None]:\n    \"\"\"\n    Args:\n        residuals: residuals produced by _ffp_fwd.\n        augmented_star_bar: cotangents\n    Returns:\n        theta_bar: cotangents for theta\n        zeroed_xs: cotangents for initial_state\n    \"\"\"\n    outer_iterated_function = residuals.outer_iterated_function\n    outer_theta = residuals.outer_theta\n    x_star = residuals.x_star\n    x_star_differentiand = outer_iterated_function.extract_differentiand(outer_theta, x_star)\n    x_star_bar = augmented_star_bar.current_state\n    x_star_bar_differentiand = outer_iterated_function.extract_differentiand(outer_theta,\n                                                                             x_star_bar)\n\n    def f_of_theta(some_theta: Parameters) -> Differentiand:\n        state = outer_iterated_function.expected_state(some_theta, x_star)\n        return outer_iterated_function.extract_differentiand(outer_theta, state)\n\n    z_iterator = _ZIterate(minimum_iterations=outer_iterated_function.z_minimum_iterations,\n                           maximum_iterations=outer_iterated_function.z_maximum_iterations,\n                           iterated_function=outer_iterated_function)\n    z_parameters = _ZParameters(residuals.outer_theta, x_star, x_star_differentiand,\n                                x_star_bar_differentiand)\n    augmented = z_iterator.find_fixed_point(z_parameters, x_star_bar_differentiand)\n    z_star_differentiand: State = augmented.current_state\n\n    _, df_by_dtheta = vjp(f_of_theta, residuals.outer_theta)\n    theta_bar, = df_by_dtheta(z_star_differentiand)\n    return None, theta_bar, None\n\n\n@dataclass\nclass IteratedFunctionWithCombinator(\n        IteratedFunction[Parameters, State, Comparand, Trajectory, TheAugmentedState],\n        Generic[Parameters, State, Comparand, Differentiand, Trajectory, TheAugmentedState]):\n    \"\"\"\n    An IteratedFunctionWithCombinator is an IteratedFunction that invokes a combinator so that\n    differentiation works through the fixed point.  Besides inheriting from this class, no other\n    action is necessary to get this capability.\n\n    It is a generic class with all of the parameters of IteratedFunction, and Differentiand, which\n    is the type of the *portion of the state* with respect to which derivatives at the fixed point\n    are calculated.\n\n    Attributes:\n        z_maximum_iterations:\n            The maximum number of iterations to use to evaluate the adjoint's fixed point.\n    \"\"\"\n    z_minimum_iterations: int = 11\n    z_maximum_iterations: int = 1000\n\n    # Overridden methods ---------------------------------------------------------------------------\n    def find_fixed_point(self,\n                         theta: Parameters,\n                         initial_state: State) -> TheAugmentedState:\n        \"\"\"\n        Args:\n            theta: The parameters for which gradients can be calculated.\n            initial_state: An initial guess of the final state.\n        Returns: The augmented state at the fixed point.\n        \"\"\"\n        return super().find_fixed_point(theta, initial_state)\n\n    find_fixed_point = custom_vjp(find_fixed_point)  # type: ignore\n\n    # Abstract methods -----------------------------------------------------------------------------\n    def extract_differentiand(self, theta: Parameters, state: State) -> Differentiand:\n        \"\"\"\n        Returns: The differentiable values in the state.  It is used by the combinator to find\n            cotangents.\n        \"\"\"\n        raise NotImplementedError\n\n    def implant_differentiand(self,\n                              theta: Parameters,\n                              state: State,\n                              differentiand: Differentiand) -> State:\n        \"\"\"\n        Args:\n            state: A state that will provide nondifferentiable values.\n            differentiand: A differentiand that will provide differentiable values.\n        Returns: A state containing differentiable from the differentiand and nondifferentiable\n            values from the inputted state.\n        \"\"\"\n        raise NotImplementedError\n\n    # Apply vjp ------------------------------------------------------------------------------------\n    find_fixed_point.defvjp(_ffp_fwd, _ffp_bwd)  # type: ignore\n\n\nclass ComparingIteratedFunctionWithCombinator(\n        IteratedFunctionWithCombinator[Parameters, State, Comparand, Differentiand, Trajectory,\n                                       ComparingState[State, Comparand]],\n        ComparingIteratedFunction[Parameters, State, Comparand, Trajectory],\n        Generic[Parameters, State, Comparand, Differentiand, Trajectory]):\n    pass\n\n\n@dataclass\nclass _ZIterate(ComparingIteratedFunctionWithCombinator[\n        _ZParameters[Parameters, State, Differentiand],\n        Differentiand,\n        Differentiand,\n        Differentiand,\n        None],\n        Generic[Parameters, State, Comparand, TheAugmentedState, Differentiand]):\n    \"\"\"\n    The state of _ZIterate is the differentiand of the outer iterated function.\n    \"\"\"\n    iterated_function: IteratedFunctionWithCombinator[\n        Parameters, State, Comparand, Differentiand, Any, TheAugmentedState]\n\n    # Implemented methods --------------------------------------------------------------------------\n    def expected_state(self,\n                       theta: _ZParameters[Parameters, State, Differentiand],\n                       state: Differentiand) -> Differentiand:\n        return self.sampled_state(theta, state)\n\n    def sampled_state(self,\n                      theta: _ZParameters[Parameters, State, Differentiand],\n                      state: Differentiand) -> Differentiand:\n        # The state should be called z, but we can't change the interface because of Liskov's\n        # substitution principle.\n        z = state\n        del state\n\n        def f_of_x(x_differentiand: Differentiand) -> Differentiand:\n            x = self.iterated_function.implant_differentiand(theta.outer_theta, theta.x_star,\n                                                             x_differentiand)\n            state = self.iterated_function.expected_state(theta.outer_theta, x)\n            return self.iterated_function.extract_differentiand(theta.outer_theta, state)\n\n        _, df_by_dx = vjp(f_of_x, theta.x_star_differentiand)\n        df_by_dx_times_z, = df_by_dx(z)\n        return tree_map(jnp.add, theta.x_star_bar_differentiand, df_by_dx_times_z)\n\n    def extract_comparand(self, state: Differentiand) -> Differentiand:\n        return state\n\n    def extract_differentiand(self,\n                              theta: _ZParameters[Parameters, State, Differentiand],\n                              state: Differentiand) -> Differentiand:\n        return state\n\n    def implant_differentiand(self,\n                              theta: _ZParameters[Parameters, State, Differentiand],\n                              state: Differentiand,\n                              differentiand: Differentiand) -> Differentiand:\n        return differentiand\n", "meta": {"hexsha": "b3424acb3fd8272b66c7e197851babcbd54dcdfe", "size": 9381, "ext": "py", "lang": "Python", "max_stars_repo_path": "tjax/_src/fixed_point/combinator.py", "max_stars_repo_name": "NeilGirdhar/tjax", "max_stars_repo_head_hexsha": "11a3abe3d287ddd4df4e0b3b04b46969b8bdc881", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2020-07-14T02:22:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T15:27:28.000Z", "max_issues_repo_path": "tjax/_src/fixed_point/combinator.py", "max_issues_repo_name": "NeilGirdhar/tjax", "max_issues_repo_head_hexsha": "11a3abe3d287ddd4df4e0b3b04b46969b8bdc881", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-11-24T13:13:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-22T16:08:47.000Z", "max_forks_repo_path": "tjax/_src/fixed_point/combinator.py", "max_forks_repo_name": "NeilGirdhar/tjax", "max_forks_repo_head_hexsha": "11a3abe3d287ddd4df4e0b3b04b46969b8bdc881", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.25, "max_line_length": 100, "alphanum_fraction": 0.6416160324, "include": true, "reason": "import jax,from jax", "num_tokens": 1905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.3629692193015556, "lm_q1q2_score": 0.19704266744951787}}
{"text": "import os\nimport json\nimport random\nimport pickle\nimport numpy as np\nfrom copy import deepcopy\n\nimport cma\nfrom svreg.optimizers import GAWrapper#, SofomoreWrapper\nfrom svreg.nodes import SVNode\nfrom svreg.tree import SVTree\nfrom svreg.tree import MultiComponentTree as MCTree\n\nimport dask\n\nclass SVRegressor:\n    \"\"\"\n    A class for running a genetic algorithm to perform symbolic\n    regression using structure vectors.\n\n    Attributes:\n\n        settings (Settings):\n            The settings used during regression. Use\n            Settings.printValidSettings() to see valid settings options and\n            suggested values.\n\n        svNodePool (list):\n            A list of SVNode objects representing the different types of SVs\n            to be used during the regression.\n\n        optimizer (object):\n            The constructor for an optimizer object that will be used to\n            optimize tree parameters. It is assumed that `optimizer` is a\n            population-based optimizer and that it implements an ask() and\n            tell() interface. An optimizer instance will be generated by calling\n            optimizer(tree.populate(N=1)[0], **optimizerArgs) for tree in\n            self.trees.\n\n        optimizerArgs (dict):\n            A dictionary of named arguments to be passed to the tree optimizers.\n\n        trees (list):\n            A list of SVTree objects being optimized.\n    \"\"\"\n\n    def __init__(\n            self,\n            settings,\n            database,\n        ):\n\n        # Note: it is assumed that Settings has already performed all validation\n        # checks on the provided settings.\n\n        self.settings = settings\n        self.svNodePool = buildSVNodePool(database)\n\n        self.structNames    = database.attrs['structNames']\n        self.svNames        = database.attrs['svNames']\n        self.elements       = database.attrs['elements']\n\n        if settings['optimizer'] == 'CMA':\n            self.optimizer = cma.CMAEvolutionStrategy\n            self.optimizerArgs = [\n                1.0,  # defaulted sigma0 value\n                {\n                    'verb_disp': 0,\n                    'popsize': settings['optimizerPopSize'],\n                    'maxiter': settings['maxNumOptimizerSteps'],\n                    'tolx': 1e-8,  # changes in x-values\n                    'tolfunhist': 1e-8,\n                    'tolfun': 1e-8,\n                    'tolfunrel': 1e-8,\n                }\n            ]\n        elif settings['optimizer'] == 'GA':\n            self.optimizer = GAWrapper\n            self.optimizerArgs = [\n                {\n                    'verb_disp': 0,\n                    'popsize': settings['optimizerPopSize'],\n                    'maxiter': settings['maxNumOptimizerSteps'],\n                    'tolx': 1e-8,  # changes in x-values\n                    'tolfunhist': 1e-8,\n                    'tolfun': 1e-8,\n                    'tolfunrel': 1e-8,\n                }\n            ]\n        # elif settings['optimizer'] == 'Sofomore':\n        #     self.optimizer = SofomoreWrapper\n        #     self.optimizerArgs = {\n        #         'numStructs': numStructs,\n        #         'paretoDimensionality': 2,\n        #         'CMApopSize': settings['optimizerPopSize'],\n        #         'SofomorePopSize': settings['numberOfTrees'],  # Placeholder\n        #         'threads_per_node': settings['PROCS_PER_PHYS_NODE'],\n        #         'threads_per_node': None,\n        #     }\n        else:\n            raise NotImplementedError(\n                'Must be one of `GA`, `CMA`, or `Sofomore`.'\n            )\n\n        self.trees = []\n        self.populationDict = None\n\n\n    def initializeTrees(self, elements):\n        \"\"\"Populates the GA with randomly-generated equation trees.\"\"\"\n\n        numElements = len(elements)\n\n        if numElements < 1:\n            raise RuntimeError(\"numElements must be >= 1 in initializeTrees()\")\n\n        uniqueTreeNames = []\n\n        for ii, tree in enumerate(self.trees):\n            tn = str(tree)\n            if tn not in uniqueTreeNames:\n                uniqueTreeNames.append(tn)\n            else:\n                del self.trees[ii]\n                print(\"Removed duplicate tree: {}\".format(tn))\n\n        treesToAdd = []\n        while len(uniqueTreeNames) < self.settings['numberOfTrees']:\n            randTree = MCTree.random(\n                svNodePool=self.svNodePool,\n                maxDepth=random.randint(0, self.settings['maxTreeDepth']),\n                elements=elements,\n                allSums=self.settings['allSums']\n            )\n\n            if str(randTree) not in uniqueTreeNames:\n                uniqueTreeNames.append(str(randTree))\n                treesToAdd.append(randTree)\n\n        self.trees += treesToAdd\n\n\n    def evaluateTrees(self, svEng, svFcs, P, trueValues, useDask=True):\n        \"\"\"\n        Updates the SVNode objects in the trees with the given values, then\n        evaluate the trees\n\n        Args:\n            svEng (dict):\n                svEng[structName][svName][elem] = computed values for given node\n\n            svFcs (dict):\n                svFcs[structName][svName][elem] = computed values for given node\n\n            P (int):\n                The number of parameter sets for each node. Used for splitting\n                the population of results.\n\n        Return:\n            energies, forces (dict):\n                {structName: [tree.eval() for tree in self.trees]}\n        \"\"\"\n\n        structNames = list(svEng.keys())\n        svNames     = list(svEng[structNames[0]].keys())\n        \n        # NOTE: elements must be sorted here to match assumed ordering of\n        # tree.svNodes\n        elements = sorted(list(svEng[structNames[0]][svNames[0]].keys()))\n\n        # indexers[sv][el][i] = list of indices for svEng[*][sv][el] for tree i\n        indexers = {}\n\n        struct0 = structNames[0]\n        # Build dictionary of indexers for each SV\n        for svName in svEng[struct0]:\n            indexers[svName] = {}\n            for elem in elements:\n                indexers[svName][elem]  = []\n\n                counter = 0\n\n                for tree in self.trees:\n                    treeIndices = []\n                    for svNode in tree.chemistryTrees[elem].svNodes:\n                        # Only update the SVNode objects of the current type\n                        if svNode.description == svName:\n                            treeIndices.append(counter)\n                            counter += 1\n\n                    # Reverse list here since we'll be popping from it later\n                    indexers[svName][elem].append(treeIndices[::-1])\n\n        taskArgs = []\n        for struct in structNames:\n            indexCopy = deepcopy(indexers)\n\n            for ii, tree in enumerate(self.trees):\n                treeArgs = []\n                for elem in elements:\n                    for svNode in tree.chemistryTrees[elem].svNodes:\n                        svName = svNode.description\n\n                        engDot = svEng[struct][svName][elem]\n                        fcsDot = svFcs[struct][svName][elem]\n\n                        treeArgs.append(\n                            (engDot, fcsDot, indexCopy[svName][elem][ii].pop())\n                        )\n\n                taskArgs.append(treeArgs)\n\n        taskArgs = taskArgs[::-1]\n\n        perTreeResults = []\n        for structName in structNames:\n            for t in self.trees:\n                args = taskArgs.pop()\n\n                if useDask:\n                    perTreeResults.append(\n                        dask.delayed(parseAndEval, pure=True, nout=2)(\n                            pickle.dumps(t), args, P,\n                            trueValues[structName]['forces'],\n                            allSums=self.settings['allSums']\n                        )\n                    )\n                else:\n                    perTreeResults.append(\n                        parseAndEval(\n                            t, args, P,\n                            trueValues[structName]['forces'],\n                            allSums=self.settings['allSums']\n                        )\n                    )\n\n        return perTreeResults \n\n\n    def initializeOptimizers(self):\n        import hashlib\n\n        h5Hash = lambda t: hashlib.md5(str(t).encode()).hexdigest()\n\n        path = os.path.join(self.settings['outputPath'], 'outcmaes', '{}/')\n\n        # self.optimizers = [\n        #     self.optimizer(\n        #         tree.populate(N=1)[0],\n        #         *.update(\n        #             self.optimizerArgs[-1]\n        #         )\n        #     )\n        #     for tree in self.trees\n        # ]\n\n        argsCopy = deepcopy(self.optimizerArgs)\n\n        self.optimizers = []\n        for tree in self.trees:\n            d = {'verb_filenameprefix': path.format(h5Hash(tree))}\n            d.update(self.optimizerArgs[-1])\n\n            argsCopy[-1] = d\n\n            self.optimizers.append(\n                self.optimizer(\n                    tree.populate(N=1)[0],\n                    *argsCopy\n                )\n            )\n\n\n    def tournament(self, topN):\n        \"\"\"\n        Randomly return a random individual from the topN individuals in the\n        population.\n\n        Return:\n            A deep copy (to avoid multiple trees pointing to the same nodes) of\n            the best individual.\n        \"\"\"\n\n        indices = np.arange(len(self.trees))\n        costs = [t.cost for t in self.trees]\n\n        argsort = np.argsort(costs)\n        costs = costs[argsort]\n        indices = indices[argsort]\n\n        return deepcopy(self.trees[random.choice(indices[:topN])])\n\n\n    def newIndividual(self):\n        \"\"\"\n        Generates a new individual using the current population. Allow for\n        random point mutation.\n        \"\"\"\n\n        newTree = self.tournament(self.settings['tournamentSize'])\n        donor   = self.tournament(self.settings['tournamentSize'])\n\n        newTree.crossover(donor)\n\n        if random.random() < self.settings['pointMutateProb']:\n            newTree.pointMutate(\n                self.svNodePool, self.settings['pointMutateProb']\n            )\n\n        newTree.updateSVNodes()\n\n        return newTree\n\n\n    def printTop10Header(self, regStep):\n        print(regStep, flush=True)\n\n        for treeNum, t in enumerate(self.trees):\n            print(treeNum, t)\n\n        print('\\t\\t\\t', ''.join(['{:<10}'.format(i) for i in range(10)]))\n\n\n    def generatePopulationDict(self, N):\n        \"\"\"\n        Generates N parameter sets for each tree, then groups them by SV name\n        for easy batch evaluation.\n\n        Returns:\n            populationDict: {svName: {el: stacked population}}\n            rawPopulation: the parameter arrays generated by each optimizer\n        \"\"\"\n\n        rawPopulations = [np.array(opt.ask(N)) for opt in self.optimizers]\n\n        # Used for parsing later\n        self.numNodes = {}\n\n        # Now parse the populations and group them by SV type\n\n        # populationDict[svName][elem]\n        populationDict = {}\n        for pop, tree in zip(rawPopulations, self.trees):\n            # popDict= {el: {svName: population}}\n            popDict = tree.parseArr2Dict(pop)\n\n            for elem in popDict:\n                for svName in popDict[elem]:\n                    if svName not in populationDict:\n                        populationDict[svName] = {}\n\n                    if elem not in populationDict[svName]:\n                        populationDict[svName][elem] = []\n\n                    populationDict[svName][elem].append(popDict[elem][svName])\n\n\n        # Count the number of each node to help with parsing results later\n        for tree in self.trees:\n            for elem in tree.chemistryTrees:\n                for svNode in tree.chemistryTrees[elem].svNodes:\n                    svName = svNode.description\n\n                    if svName not in self.numNodes:\n                        self.numNodes[svName] = {}\n\n                    if elem not in self.numNodes[svName]:\n                        self.numNodes[svName][elem] = 0\n\n                    self.numNodes[svName][elem] += 1\n\n        self.chunks = {}\n        # Stack each group\n        for svName in populationDict:\n            if svName not in self.chunks:\n                self.chunks[svName] = {}\n\n            for elem, popList in populationDict[svName].items():\n                dat = np.concatenate(popList, axis=0).T\n\n                populationDict[svName][elem] = dat.astype('float32')\n\n        return populationDict, rawPopulations\n\n    \n    def updateOptimizers(self, rawPopulations, costs, penalties):\n        for treeIdx in range(len(self.optimizers)):\n            fullCost = costs[treeIdx] + penalties[treeIdx]\n\n            opt = self.optimizers[treeIdx]\n            opt.tell(rawPopulations[treeIdx], fullCost)\n            opt.logger.add()\n\n\n    def checkStale(self):\n        \"\"\"\n        Returns a list of the indices of any trees that have finished\n        optimizing.\n        \"\"\"\n\n        stale = []\n        messages = []\n\n        for i, opt in enumerate(self.optimizers):\n            if opt.stop():\n                stale.append(i)\n                messages.append(opt.stop())\n\n        return stale, messages\n\n\ndef buildSVNodePool(database):\n    \"\"\"Prepare svNodePool for use in tree construction\"\"\"\n\n    svNodePool = []\n\n    for svName in database:\n\n        restrictions = None\n        if 'restrictions' in database.attrs[svName]:\n            restrictions = []\n            resList = database.attrs[svName]['restrictions'].tolist()[::-1]\n            for num in database.attrs[svName]['numRestrictions']:\n                tmp = []\n                for _ in range(num):\n                    tmp.append(tuple(resList.pop()))\n                restrictions.append(tmp)\n\n        bondComps = sorted(set(database.attrs[svName]['components']))\n        numParams = []\n        restr = []\n\n        cList = database.attrs[svName]['components'].tolist()\n        for c in bondComps:\n            idx = cList.index(c)\n            numParams.append(database.attrs[svName]['numParams'][idx].astype(int))\n            restr.append(restrictions[idx])\n\n        if 'paramRanges' in database.attrs[svName]:\n            pRanges = []\n            for c in bondComps:\n                idx = cList.index(c)\n                pRanges.append(database.attrs[svName]['paramRanges'][idx])\n        else:\n            pRanges = None\n\n        bondComps = [c.decode('utf-8') for c in bondComps]\n\n\n        svNodePool.append(\n            SVNode(\n                description=svName,\n                components=bondComps,\n                constructor=[\n                    c.decode('utf-8')\n                    for c in database.attrs[svName]['components']\n                ],\n                numParams=numParams,\n                restrictions=restr,\n                paramRanges=pRanges,\n                inputTypes=json.loads(\n                    database.attrs[svName]['inputTypes'].decode('utf-8').replace(\"'\", '\"')\n                )\n            )\n        )\n\n    return svNodePool\n\n    \ndef parseAndEval(\n    *args,\n    **kwargs,\n    ):\n\n    tree            = kwargs['tree']\n    listOfIndices   = kwargs['listOfIndices']\n    P               = kwargs['P']\n    tvF             = kwargs['tvF']\n    numChunks       = kwargs['numChunks']\n    allSums         = kwargs['allSums']\n\n    import pickle\n    tree = pickle.loads(tree)\n\n    nodeCounter     = 0\n    chunkCounter    = 0\n    for elem in tree.elements:\n        for svNode in tree.chemistryTrees[elem].svNodes:\n            svName = svNode.description\n\n            chunkTup = []\n            for _ in range(numChunks[svName][elem]):\n                chunkTup.append(args[chunkCounter])\n                chunkCounter += 1\n\n            idx = listOfIndices[nodeCounter]\n            nodeCounter += 1\n\n            eng = np.concatenate([c[0] for c in chunkTup], axis=-1)\n            fcs = np.concatenate([c[1] for c in chunkTup], axis=-1)\n\n            Ne = eng.shape[0]\n            Nn = eng.shape[1] // P\n\n            eng = eng.reshape((Ne, Nn, P))\n            eng = np.moveaxis(eng, 1, 0)\n            eng = np.moveaxis(eng, -1, 1)\n\n            # fcs shape: (Ne, Na, 3, P*Nn)\n\n            if allSums:\n                Na = fcs.shape[0]\n                fcs = fcs.reshape(Na, 3, Nn, P)\n            else:\n                Na = fcs.shape[1]\n                fcs = fcs.reshape(Ne, Na, 3, Nn, P)\n\n            fcs = np.moveaxis(fcs, -2, 0)\n            fcs = np.moveaxis(fcs, -1, 1)\n\n            # fcs shape: (Nn, P, Ne, Na, 3)\n\n            svNode.values = (eng[idx], fcs[idx])\n\n    engResult, fcsResult = tree.eval(useDask=False, allSums=allSums)\n\n    fcsErrors = np.average(abs(sum(fcsResult) - tvF['forces']), axis=(1,2))\n\n    return sum(engResult), fcsErrors\n", "meta": {"hexsha": "602b4922d5785f48d31a021e22747ecb06d728ff", "size": 16689, "ext": "py", "lang": "Python", "max_stars_repo_path": "svreg/regressor.py", "max_stars_repo_name": "TrinkleGroup/svreg", "max_stars_repo_head_hexsha": "b0c5b3c53792f0cc7b31a9d85f2e9b33824aaca1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "svreg/regressor.py", "max_issues_repo_name": "TrinkleGroup/svreg", "max_issues_repo_head_hexsha": "b0c5b3c53792f0cc7b31a9d85f2e9b33824aaca1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-10-28T17:14:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-28T17:16:55.000Z", "max_forks_repo_path": "svreg/regressor.py", "max_forks_repo_name": "TrinkleGroup/svreg", "max_forks_repo_head_hexsha": "b0c5b3c53792f0cc7b31a9d85f2e9b33824aaca1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4886792453, "max_line_length": 90, "alphanum_fraction": 0.5237581641, "include": true, "reason": "import numpy", "num_tokens": 3633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.3629692193015555, "lm_q1q2_score": 0.19704266208060342}}
{"text": "###############################################################\n#\n# Cantera UPF : freely-propagating premixed flames\n# Description : perform calculations of UPF for a range of eq. ratio\n#               and compute global indices (integrated fuel, CO, NO consumption, ...)\n# Author : A. Felden\n# Last modified : 02/2018\n#\n###############################################################\n\n#import :\nfrom cantera import *\nimport numpy as np\nimport csv\nimport sys,os\n\n#################################################################\n# Prepare your run\n#################################################################\n#Mechanism used for the process\ncas         = 'DET.cti' \npref        = 'C2H4DET_T298_P1'\nrestore     = 'no'\ninit_flame  = 'RedHighP_HighP_save.xml' \n\n#General parameter values :\np          \t= 101325.0                # pressure\ntin        \t= 298.0        # unburned gas temperature\nphi_min \t= 0.8\nphi_max \t= 1.5\nnpoints \t= 1\n\n########\n#STORAGE\n########\n# KSI\nksi = np.zeros(npoints,'d')\n# YC eq\nYc_equil = np.zeros(npoints,'d')\n#phiv\nphi = np.zeros(npoints,'d')\n#sl0phiv\nsl_phi = np.zeros(npoints,'d')\n#tadphiv\nt_phi = np.zeros(npoints,'d')\n#omega0phiv\n#delta0phiv\ndl0_phi = np.zeros(npoints,'d')\n\n#########################################\n# SPECS : profiles, wdot, consump, val max\n# prof  : Fuel, oxy,  CO, CO2, OH, C2H2\n# max   :       oxy,  CO, CO2, OH, C2H2\n# wdot  : Fuel, oxy,  CO,          C2H2\n# cons  : Fuel,       CO,          C2H2 \n#########################################\n#FUEL consump\nFuel_c \t\t= np.zeros(npoints,'d')\n#OXY consump\nO2m_phi \t= np.zeros(npoints,'d')\n#CO consump\nCOm_phi \t= np.zeros(npoints,'d')\nCO_c \t\t= np.zeros(npoints,'d')\n#CO2 consump\nCO2m_phi \t= np.zeros(npoints,'d')\n#OH consump\nOHm_phi \t= np.zeros(npoints,'d')\n\n\n#################\n#Run parameters:\n\n#Initial grids, chosen to be 15cm long : \ninitial_grid = np.array([0.0, 0.001, 0.005, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1], 'd')/0.1 #, 0.11, 0.115, 0.119, 0.12],'d')/0.1 # m\n\n#Tolerance properties\ntol_ss    = [1.0e-8, 1.0e-12]        # [rtol atol] for steady-state problem\ntol_ts    = [1.0e-8, 1.0e-12]        # [rtol atol] for time stepping\n\nloglevel  = 1                       # amount of diagnostic output\n\t\t\t\t    \nrefine_grid = True                  # True to enable refinement\n\n#################\n#Stoechiometry :\n\nfuel_species = 'C2H4'\nstoich_O2 = 3.0\nair_N2_O2_ratio = 3.76\n\ngas  = Solution(cas)\nm=gas.n_species\n\nifuel = gas.species_index(fuel_species)\nioh = gas.species_index('OH')\nih2 = gas.species_index('H2')\nio2 = gas.species_index('O2')\nin2 = gas.species_index('N2')\nico = gas.species_index('CO')\nico2 = gas.species_index('CO2')\nih2o = gas.species_index('H2O')\n\n#################################################################\n#BILGER PRE PROC :\n#################################################################\n#Mixt frac calculation based on Bilger\n#molecular weight of CHON\nC_W = 0.012\nH_W = 0.001\nO_W = 0.016\nN_W = 0.014\n#Bilger coefs pour formule\nBilger_coefs \t\t= np.zeros(4,'d')\nBilger_coefs[0]\t\t= 2.0 / C_W\nBilger_coefs[1]\t\t= 1.0 / ( 2.0 * H_W )\nBilger_coefs[2]\t\t= -1.0 / O_W\nBilger_coefs[3]\t\t= 0.0\n#Storage nb d atomes par especes\nNb_C\t\t\t= np.zeros(m,'d')\nNb_H\t\t\t= np.zeros(m,'d')\nNb_O\t\t\t= np.zeros(m,'d')\n#Compo du fuel et oxi tank\nFtank\t\t\t= np.zeros(m,'d')\nFtank[ifuel]\t\t= 1.0\nOxtank\t\t\t= np.zeros(m,'d')\nOxtank[io2]\t\t= 0.233\nOxtank[in2]\t\t= 0.767\n#Normalisation\nBetaF \t\t\t= 0.0\nBetaOx \t\t\t= 0.0\nfor i, spec in enumerate(gas.species_names):\n        Nb_C[i] = gas.n_atoms(spec,'C')  \n        Nb_H[i] = gas.n_atoms(spec,'H')  \n        Nb_O[i] = gas.n_atoms(spec,'O')  \n        Weightedatom = Bilger_coefs[0] * C_W * Nb_C[i] + Bilger_coefs[1] * H_W * Nb_H[i] + Bilger_coefs[2] * O_W * Nb_O[i]\n        BetaF = BetaF + 1000.0 * Weightedatom * Ftank[i] / gas.molecular_weights[i]\n        BetaOx = BetaOx + 1000.0 * Weightedatom * Oxtank[i] / gas.molecular_weights[i]\n\nif (restore == 'yes'): \n#################################################################\n# RESTORE PREVIOUS FLAME\n#################################################################\n    phi[0]   = phi_min \n    x        = np.zeros(m,'d')\n    x[ifuel] = phi[0]\n    x[io2]   = stoich_O2\n    x[in2]   = stoich_O2*air_N2_O2_ratio\n    \n    gas.TPX = tin, p, x\n    \n    f = FreeFlame(gas, initial_grid)\n    f.restore(init_flame, 'phi_'+str(phi[0]))\nelse:\n#################################################################\n#FIRST SIMULATION :\n#################################################################\n#Stoechiometry :\n    phi[0]   = phi_min \n    x        = np.zeros(m,'d')\n    x[ifuel] = phi[0]\n    x[io2]   = stoich_O2\n    x[in2]   = stoich_O2*air_N2_O2_ratio\n\n    print('  ')\n    print(' ### First flame at Phi : '+str(phi[0]))\n    \n    gas.TPX = tin, p, x\n\n#Create the free laminar premixed flame\n    f = FreeFlame(gas, initial_grid)\n    \n    f.flame.set_steady_tolerances(default=tol_ss)\n    f.flame.set_transient_tolerances(default=tol_ts)\n    \n    f.inlet.X = x\n    f.inlet.T = tin\n    \n    f.transport_model = 'Mix'\n\n#First flame:\n\n      #No energy for starters\n    f.energy_enabled = False\n\n      #Refinement criteria\n    f.set_refine_criteria(ratio = 5.0, slope = 1, curve = 1)\n\n      #Max number of times the Jacobian will be used before it must be re-evaluated\n    f.set_max_jac_age(30, 30)\n\n      #Set time steps whenever Newton convergence fails\n    f.set_time_step(1.0e-6, [5, 10, 20]) #s\n\n      #Calculation\n    f.solve(loglevel, refine_grid)\n\n#################\n#Second flame:\n\n\t#Energy equation enabled\n    f.energy_enabled = True\n\n      #Refinement criteria when energy equation is enabled\n    f.set_refine_criteria(ratio = 5.0, slope = 0.5, curve = 0.5)\n\n      #Calculation and save of the results\n    f.solve(loglevel, refine_grid)\n\n      #Refinement criteria when energy equation is enabled\n    f.set_refine_criteria(ratio = 3.0, slope = 0.2, curve = 0.2)\n\n      #Calculation and save of the results\n    f.solve(loglevel, refine_grid)\n\n#################\n#Third flame and so on ...:\n\n\t#Refinement criteria should be changed ...\n    f.set_refine_criteria(ratio = 2.0, slope = 0.04, curve = 0.04)\n\n    f.solve(loglevel, refine_grid)\n\n\t#Refinement criteria should be changed ...\n    f.set_refine_criteria(ratio = 2.0, slope = 0.02, curve = 0.02)\n\n    f.solve(loglevel, refine_grid)\n\n    sl_phi[0] = f.u[0]\n    t_phi[0]  = f.T[f.flame.n_points-1]\n    print( \"Sl ? \",  sl_phi[0])\n    print( \"Tad ? \", t_phi[0])\n\n\t#...and saving of the results\n    #f.save(str(pref)+'_save.xml','phi_'+str(phi[0]))\n    f.write_csv(str(pref)+'_Phi'+str(phi[0])+'_Y.csv', species='Y', quiet=False)\n\n", "meta": {"hexsha": "1db1c0e1163d308406a589ea1de52caaf3d35115", "size": 6593, "ext": "py", "lang": "Python", "max_stars_repo_path": "Support/Fuego/Mechanism/Models/ethylene_af/CANTERA/Cantera_UPF_Global.py", "max_stars_repo_name": "balos1/PelePhysics", "max_stars_repo_head_hexsha": "d01190cc7b0eaad4ec96fac573034ccb485f0e9f", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2018-11-21T01:49:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:41:43.000Z", "max_issues_repo_path": "Support/Fuego/Mechanism/Models/ethylene_af/CANTERA/Cantera_UPF_Global.py", "max_issues_repo_name": "balos1/PelePhysics", "max_issues_repo_head_hexsha": "d01190cc7b0eaad4ec96fac573034ccb485f0e9f", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 123, "max_issues_repo_issues_event_min_datetime": "2019-03-12T22:27:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T17:00:04.000Z", "max_forks_repo_path": "Support/Fuego/Mechanism/Models/ethylene_af/CANTERA/Cantera_UPF_Global.py", "max_forks_repo_name": "sundials-codes/PelePhysics", "max_forks_repo_head_hexsha": "5624f83a04f43aa95288be9d8a7bb372a4adefe6", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 32, "max_forks_repo_forks_event_min_datetime": "2018-11-05T11:51:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T13:09:32.000Z", "avg_line_length": 27.8185654008, "max_line_length": 154, "alphanum_fraction": 0.5490671925, "include": true, "reason": "import numpy", "num_tokens": 2134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808532, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.1970426567116891}}
{"text": "from torch.optim.optimizer import Optimizer, required\nimport torch\nimport math\nimport numpy as np\n\n\nclass LRangerMod(Optimizer):\n\n    # AMSGrad/Adam + AdaMod + QH Momentum + Iterate Averaging + Lookahead + Rule of Thumb Linear Warmup (instead of RAdam Rectification) + P from PAdam\n\n    def __init__(self, params, lr=1e-3,\n                 betas=(0.999, 0.999, 0.999),\n                 nus=(0.7, 1.0),\n                 p=0.5,\n                 eps=1e-8,\n                 k=5,\n                 alpha=0.8,\n                 amsgrad=True,\n                 AdaMod=True,\n                 warmup=True,\n                 AdaMod_bias_correct=True,\n                 IA=True,\n                 use_gc=False,\n                 IA_cycle=1000,\n                 epochs=100,\n                 step_per_epoch=None,\n                 weight_decay=0):\n\n        # betas = (beta1 for first order moments, beta2 for second order moments, beta3 for ema over adaptive learning rates (AdaMod))\n        # nus = (nu1,nu2) (for quasi hyperbolic momentum)\n        # eps = small value for numerical stability (avoid divide by zero)\n        # k = lookahead cycle\n        # alpha = outer learning rate (lookahead)\n        # amsgrad = bool to decide whether to use amsgrad instead of adam as the core optimizer\n        # AdaMod_bias_correct = bool to decide whether to add bias correction to AdaMod\n        # IA = bool to decide if Iterate Averaging is ever going to be used\n        # IA_cycle = Iterate Averaging Cycle (Recommended to initialize with no. of iterations in Epoch) (doesn't matter if you are not using IA)\n        # epochs = No. of epochs you plan to use (Only relevant if using DEMON)\n        # step_per_epoch = No. of iterations in an epoch (only relevant if using DEMON)\n        # weight decay = decorrelated weight decay value\n\n        if not 0.0 <= lr:\n            raise ValueError(\"Invalid learning rate: {}\".format(lr))\n        if not 0.0 <= eps:\n            raise ValueError(\"Invalid epsilon value: {}\".format(eps))\n        if not 0.0 <= p <= 0.5:\n            raise ValueError(\"Invalid p value: {}\".format(p))\n        if not 0.0 <= betas[0] < 1.0:\n            raise ValueError(\"Invalid beta parameter at index 0: {}\".format(betas[0]))\n        if not 0.0 <= betas[1] < 1.0:\n            raise ValueError(\"Invalid beta parameter at index 1: {}\".format(betas[1]))\n        if not 0.0 <= betas[2] < 1.0:\n            raise ValueError(\"Invalid beta parameter at index 2: {}\".format(betas[2]))\n        if not 0.0 <= nus[0] <= 1.0:\n            raise ValueError(\"Invalid nu parameter at index 0: {}\".format(nus[0]))\n        if not 0.0 <= nus[1] <= 1.0:\n            raise ValueError(\"Invalid nu parameter at index 1: {}\".format(nus[1]))\n        if not 0.0 <= alpha <= 1.0:\n            raise ValueError(\"Invalid alpha parameter: {}\".format(alpha))\n\n        self.k = k\n        self.epochs = epochs\n        self.amsgrad = amsgrad\n        self.warmup_period = 2/(1-betas[1])\n        self.IA_cycle = IA_cycle\n        self.IA = IA\n        self.AdaMod = AdaMod\n        self.use_gc = use_gc\n        self.AdaMod_bias_correct = AdaMod_bias_correct\n        self.warmup = warmup\n        if step_per_epoch is None:\n            self.step_per_epoch = IA_cycle\n        else:\n            self.step_per_epoch = step_per_epoch\n\n        self.T = self.epochs*self.step_per_epoch\n\n        defaults = dict(lr=lr,\n                        betas=betas,\n                        nus=nus,\n                        eps=eps,\n                        p=p,\n                        alpha=alpha,\n                        weight_decay=weight_decay)\n        super(LRangerMod, self).__init__(params, defaults)\n\n    def __setstate__(self, state):\n        super(LRangerMod, self).__setstate__(state)\n\n    def apply_AdaMod(self, beta3, n_avg, n, step):\n        n_avg.mul_(beta3).add_(1 - beta3, n)\n        if self.AdaMod_bias_correct:\n            n_avg_ = n_avg.clone()\n            n_avg_.div_(1 - (beta3 ** step))\n            torch.min(n, n_avg_, out=n)\n        else:\n            torch.min(n, n_avg, out=n)\n        return n\n\n    def step(self, activate_IA=False, closure=None):\n\n        loss = None\n        if closure is not None:\n            loss = closure()\n\n        for group in self.param_groups:\n\n            for p in group['params']:\n                if p.grad is None:\n                    continue\n                grad = p.grad.data.float()\n                if grad.is_sparse:\n                    raise RuntimeError('LRangerMod does not support sparse gradients')\n\n                state = self.state[p]\n\n                if len(state) == 0:\n                    state['step'] = 0\n                    state['exp_avg'] = torch.zeros_like(p.data)\n                    state['exp_avg_sq'] = torch.zeros_like(p.data)\n                    state['num_models'] = 0\n                    state['cached_params'] = p.data.clone()\n                    if self.amsgrad:\n                        state['max_exp_avg_sq'] = torch.zeros_like(p.data)\n                    if self.AdaMod:\n                        state['n_avg'] = torch.zeros_like(p.data)\n\n                state['step'] += 1\n\n                w = min([1.0, state['step']/self.warmup_period])\n                exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n                beta1, beta2, beta3 = group['betas']\n                nu1, nu2 = group['nus']\n\n                if self.warmup:\n                    lr = w*group['lr']\n                else:\n                    lr = group['lr']\n\n                wd = group['weight_decay']\n                alpha = group['alpha']\n\n                do_IA = False\n                lookahead_step = False\n\n                if self.IA and activate_IA:\n                    lookahead_step = False\n                    if state['step'] % self.IA_cycle == 0:\n                        do_IA = True\n                elif self.k == 0:\n                    lookahead_step = False\n                else:\n                    if state['step'] % self.k == 0:\n                        lookahead_step = True\n                    else:\n                        lookahead_step = False\n\n                if self.use_gc:\n                    grad.add_(-grad.mean(dim=tuple(range(1, len(list(grad.size())))), keepdim=True))\n\n                exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n                exp_avg.mul_(beta1).add_(1 - beta1, grad)\n\n                momentum = exp_avg.clone()\n                momentum.div_(1 - (beta1 ** state['step'])).mul_(nu1).add_(1-nu1, grad)\n\n                if wd != 0:\n                    p.data.add_(-wd*lr, p.data)\n\n                beta2_t = beta2 ** state['step']\n\n                if self.amsgrad and state['step'] > 1:\n                    max_exp_avg_sq = state['max_exp_avg_sq']\n                    # Maintains the maximum of all 2nd moment running avg. till now\n                    torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)\n                    vt = max_exp_avg_sq.clone()\n                else:\n                    vt = exp_avg_sq.clone()\n\n                bias_correction2 = 1 - beta2_t\n                vt.div_(bias_correction2)\n                if nu2 != 1.0:\n                    vt.mul_(nu2).addcmul_(1-nu2, grad, grad)\n                denom = vt.pow_(group['p']).add_(group['eps'])\n                n = lr/denom\n                if self.AdaMod:\n                    n_avg = state['n_avg']\n                    n = self.apply_AdaMod(beta3, n_avg, n, step=state['step'])\n\n                p.data.add_(-n*momentum)\n\n                if lookahead_step:\n                    p.data.mul_(alpha).add_(1.0 - alpha, state['cached_params'])\n                    state['cached_params'].copy_(p.data)\n\n                if do_IA:\n                    p.data.add_(state[\"num_models\"], state['cached_params']\n                                ).div_(state[\"num_models\"]+1.0)\n                    state['cached_params'].copy_(p.data)\n                    state[\"num_models\"] += 1\n\n        return loss\n\n\nclass DemonRanger(Optimizer):\n\n    # Rectified-AMSGrad/RAdam + AdaMod + QH Momentum + Iterat Averaging + Lookahead + DEMON (decaying Momentum) + gradient centralization + grad noise\n\n    def __init__(self, params, lr=1e-3,\n                 betas=(0.999, 0.999, 0.999),\n                 nus=(0.7, 1.0),\n                 eps=1e-8,\n                 k=5,\n                 alpha=0.8,\n                 gamma=0.55,\n                 use_demon=True,\n                 rectify=True,\n                 amsgrad=True,\n                 AdaMod=True,\n                 AdaMod_bias_correct=True,\n                 IA=True,\n                 IA_cycle=1000,\n                 epochs=100,\n                 step_per_epoch=None,\n                 weight_decay=0,\n                 use_gc=True,\n                 use_grad_noise=False):\n\n        # betas = (beta1 for first order moments, beta2 for second order moments, beta3 for ema over adaptive learning rates (AdaMod))\n        # nus = (nu1,nu2) (for quasi hyperbolic momentum)\n        # eps = small value for numerical stability (avoid divide by zero)\n        # k = lookahead cycle\n        # alpha = outer learning rate (lookahead)\n        # gamma = gradient noise control parameter (for regularization)\n        # use_demon = bool to decide whether to use DEMON (Decaying Momentum) or not\n        # rectify = bool to decide whether to apply the recitification term (from RAdam) or not\n        # amsgrad = bool to decide whether to use amsgrad instead of adam as the core optimizer\n        # AdaMod_bias_correct = bool to decide whether to add bias correction to AdaMod\n        # IA = bool to decide if Iterate Averaging is ever going to be used\n        # IA_cycle = Iterate Averaging Cycle (Recommended to initialize with no. of iterations in Epoch) (doesn't matter if you are not using IA)\n        # epochs = No. of epochs you plan to use (Only relevant if using DEMON)\n        # step_per_epoch = No. of iterations in an epoch (only relevant if using DEMON)\n        # weight decay = decorrelated weight decay value\n        # use_gc = bool to determine whether to use gradient centralization or not.\n        # use_grad_noise = bool to determine whether to use gradient noise or not.\n\n        if not 0.0 <= lr:\n            raise ValueError(\"Invalid learning rate: {}\".format(lr))\n        if not 0.0 <= eps:\n            raise ValueError(\"Invalid epsilon value: {}\".format(eps))\n        if not 0.0 <= betas[0] < 1.0:\n            raise ValueError(\"Invalid beta parameter at index 0: {}\".format(betas[0]))\n        if not 0.0 <= betas[1] < 1.0:\n            raise ValueError(\"Invalid beta parameter at index 1: {}\".format(betas[1]))\n        if not 0.0 <= betas[2] < 1.0:\n            raise ValueError(\"Invalid beta parameter at index 2: {}\".format(betas[2]))\n        if not 0.0 <= nus[0] <= 1.0:\n            raise ValueError(\"Invalid nu parameter at index 0: {}\".format(nus[0]))\n        if not 0.0 <= nus[1] <= 1.0:\n            raise ValueError(\"Invalid nu parameter at index 1: {}\".format(nus[1]))\n        if not 0.0 <= alpha <= 1.0:\n            raise ValueError(\"Invalid alpha parameter: {}\".format(alpha))\n\n        self.use_gc = use_gc\n        self.use_grad_noise = use_grad_noise\n        self.k = k\n        self.epochs = epochs\n        self.amsgrad = amsgrad\n        self.use_demon = use_demon\n        self.IA_cycle = IA_cycle\n        self.IA = IA\n        self.rectify = rectify\n        self.AdaMod = AdaMod\n        self.AdaMod_bias_correct = AdaMod_bias_correct\n        if step_per_epoch is None:\n            self.step_per_epoch = IA_cycle\n        else:\n            self.step_per_epoch = step_per_epoch\n\n        self.T = self.epochs*self.step_per_epoch\n\n        defaults = dict(lr=lr,\n                        betas=betas,\n                        nus=nus,\n                        eps=eps,\n                        alpha=alpha,\n                        gamma=gamma,\n                        weight_decay=weight_decay)\n        super(DemonRanger, self).__init__(params, defaults)\n\n    def __setstate__(self, state):\n        super(DemonRanger, self).__setstate__(state)\n\n    def apply_AdaMod(self, beta3, n_avg, n, step):\n        n_avg.mul_(beta3).add_(1 - beta3, n)\n        if self.AdaMod_bias_correct:\n            n_avg_ = n_avg.clone()\n            n_avg_.div_(1 - (beta3 ** step))\n            torch.min(n, n_avg_, out=n)\n        else:\n            torch.min(n, n_avg, out=n)\n        return n\n\n    def step(self, activate_IA=False, closure=None):\n\n        loss = None\n        if closure is not None:\n            loss = closure()\n\n        for group in self.param_groups:\n\n            for p in group['params']:\n                if p.grad is None:\n                    continue\n                grad = p.grad.data.float()\n                if grad.is_sparse:\n                    raise RuntimeError('DemonRanger does not support sparse gradients')\n\n                state = self.state[p]\n\n                if len(state) == 0:\n                    state['step'] = 0\n                    state['exp_avg'] = torch.zeros_like(p.data)\n                    state['exp_avg_sq'] = torch.zeros_like(p.data)\n                    state['num_models'] = 0\n                    state['cached_params'] = p.data.clone()\n                    if self.amsgrad:\n                        state['max_exp_avg_sq'] = torch.zeros_like(p.data)\n                    if self.AdaMod:\n                        state['n_avg'] = torch.zeros_like(p.data)\n\n                state['step'] += 1\n                exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n                beta1_init, beta2, beta3 = group['betas']\n                rho_inf = (2/(1-beta2)) - 1\n                nu1, nu2 = group['nus']\n                lr = group['lr']\n                wd = group['weight_decay']\n                alpha = group['alpha']\n                gamma = group['gamma']\n\n                do_IA = False\n                lookahead_step = False\n\n                if self.IA and activate_IA:\n                    lookahead_step = False\n                    if state['step'] % self.IA_cycle == 0:\n                        do_IA = True\n                elif self.k == 0:\n                    lookahead_step = False\n                else:\n                    if state['step'] % self.k == 0:\n                        lookahead_step = True\n                    else:\n                        lookahead_step = False\n\n                if self.use_demon:\n                    temp = 1-(state['step']/self.T)\n                    beta1 = beta1_init * temp / ((1-beta1_init)+beta1_init*temp)\n                else:\n                    beta1 = beta1_init\n\n                if self.use_grad_noise:\n                    grad_var = lr/((1+state['step'])**gamma)\n                    grad_noise = torch.empty_like(grad).normal_(mean=0.0, std=math.sqrt(grad_var))\n                    grad.add_(grad_noise)\n\n                if self.use_gc:\n                    grad.add_(-grad.mean(dim=tuple(range(1, len(list(grad.size())))), keepdim=True))\n\n                exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n                exp_avg.mul_(beta1).add_(1 - beta1, grad)\n\n                momentum = exp_avg.clone()\n                momentum.div_(1 - (beta1 ** state['step'])).mul_(nu1).add_(1-nu1, grad)\n\n                if wd != 0:\n                    p.data.add_(-wd*lr, p.data)\n\n                beta2_t = beta2 ** state['step']\n\n                if self.amsgrad and state['step'] > 1:\n                    max_exp_avg_sq = state['max_exp_avg_sq']\n                    # Maintains the maximum of all 2nd moment running avg. till now\n                    torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)\n                    vt = max_exp_avg_sq.clone()\n                else:\n                    vt = exp_avg_sq.clone()\n\n                if self.rectify:\n                    rho_t = rho_inf - 2 * state['step'] * beta2_t / (1 - beta2_t)\n\n                    # more conservative since it's an approximated value\n                    if rho_t >= 5:\n                        R = math.sqrt(((rho_t-4)*(rho_t-2)*rho_inf) /\n                                      ((rho_inf-4)*(rho_inf-2)*rho_t))\n                        bias_correction2 = 1 - beta2_t\n                        vt.div_(bias_correction2)\n                        if nu2 != 1.0:\n                            vt.mul_(nu2).addcmul_(1-nu2, grad, grad)\n                        denom = vt.sqrt_().add_(group['eps'])\n\n                        n = (lr*R)/denom\n\n                        if self.AdaMod:\n                            n_avg = state['n_avg']\n                            n = self.apply_AdaMod(beta3, n_avg, n, step=state['step'])\n\n                        p.data.add_(-n*momentum)\n                    else:\n                        if self.AdaMod:\n                            n_avg = state['n_avg']\n                            n_avg.mul_(beta3).add_(1 - beta3, lr)\n                        p.data.add_(-lr, momentum)\n                else:\n                    bias_correction2 = 1 - beta2_t\n                    vt.div_(bias_correction2)\n                    if nu2 != 1.0:\n                        vt.mul_(nu2).addcmul_(1-nu2, grad, grad)\n                    denom = vt.sqrt_().add_(group['eps'])\n                    n = lr/denom\n                    if self.AdaMod:\n                        n_avg = state['n_avg']\n                        n = self.apply_AdaMod(beta3, n_avg, n, step=state['step'])\n\n                    p.data.add_(-n*momentum)\n\n                if lookahead_step:\n                    p.data.mul_(alpha).add_(1.0 - alpha, state['cached_params'])\n                    state['cached_params'].copy_(p.data)\n\n                if do_IA:\n                    p.data.add_(state[\"num_models\"], state['cached_params']\n                                ).div_(state[\"num_models\"]+1.0)\n                    state['cached_params'].copy_(p.data)\n                    state[\"num_models\"] += 1\n\n        return loss\n\n\nclass HyperRanger(Optimizer):\n\n    # Nostalgic PAdam + QH Momentum + Iterate Averaging + Lookahead + DEMON (decaying Momentum) + gradient centralization + hypergradient descent on lr and nu1\n\n    def __init__(self, params, lr=1e-3,\n                 betas=(0.999, 0.999),\n                 nus=(0.7, 1.0),\n                 eps=1e-8,\n                 gamma=0.0001,\n                 nostalgia=True,\n                 use_demon=True,\n                 hypergrad_lr=1e-7,\n                 HDM=False,\n                 hypertune_nu1=False,\n                 p=0.25,\n                 k=5,\n                 alpha=0.8,\n                 IA=True,\n                 IA_cycle=1000,\n                 epochs=100,\n                 step_per_epoch=None,\n                 weight_decay=0,\n                 use_gc=True):\n\n        # betas = (beta1 for first order moments, beta2 for second order moments)\n        # nus = (nu1,nu2) (for quasi hyperbolic momentum)\n        # eps = small value for numerical stability (avoid divide by zero)\n        # k = lookahead cycle\n        # alpha = outer learning rate (lookahead)\n        # gamma = used for nostalgia\n        # nostalgia = bool to decide whether to use nostalgia (from Nostalgic Adam or NosAdam)\n        # use_demon = bool to decide whether to use DEMON (Decaying Momentum) or not\n        # hypergrad_lr = learning rate for updating hyperparameters (like lr) through hypergradient descent (probably need to increase around 0.02 if HDM is True). Set to 0.0 to disable hypergradient descent.\n        # HDM = bool to decide whether to use Multiplicative rule for updating hyperparameters or not\n        # hypertune_nu1 = bool to decide whether apply hypergradient descent on nu1 as well or not.\n        # p = p from PAdam\n        # IA = bool to decide if Iterate Averaging is ever going to be used\n        # IA_cycle = Iterate Averaging Cycle (Recommended to initialize with no. of iterations in Epoch) (doesn't matter if you are not using IA)\n        # epochs = No. of epochs you plan to use (Only relevant if using DEMON)\n        # step_per_epoch = No. of iterations in an epoch (only relevant if using DEMON)\n        # weight decay = decorrelated weight decay value\n        # use_gc = bool to determine whether to use gradient centralization or not.\n        # use_grad_noise = bool to determine whether to use gradient noise or not.\n\n        if not 0.0 <= lr:\n            raise ValueError(\"Invalid learning rate: {}\".format(lr))\n        if not 0.0 <= hypergrad_lr:\n            raise ValueError(\"Invalid hypergradient learning rate: {}\".format(hypergrad_lr))\n        if not 0.0 <= eps:\n            raise ValueError(\"Invalid epsilon value: {}\".format(eps))\n        if not 0.0 <= betas[0] < 1.0:\n            raise ValueError(\"Invalid beta parameter at index 0: {}\".format(betas[0]))\n        if not 0.0 <= betas[1] < 1.0:\n            raise ValueError(\"Invalid beta parameter at index 1: {}\".format(betas[1]))\n        if not 0.0 <= nus[0] <= 1.0:\n            raise ValueError(\"Invalid nu parameter at index 0: {}\".format(nus[0]))\n        if not 0.0 <= nus[1] <= 1.0:\n            raise ValueError(\"Invalid nu parameter at index 1: {}\".format(nus[1]))\n        if not 0.0 <= p <= 0.5:\n            raise ValueError(\"Invalid p parameter: {}\".format(p))\n        if not 0.0 <= alpha < 1.0:\n            raise ValueError(\"Invalid alpha parameter: {}\".format(alpha))\n\n        self.nostalgia = nostalgia\n        self.use_demon = use_demon\n        self.k = k\n        self.IA = IA\n        self.IA_cycle = IA_cycle\n        self.epochs = epochs\n        if step_per_epoch is None:\n            self.step_per_epoch = IA_cycle\n        else:\n            self.step_per_epoch = step_per_epoch\n        self.use_gc = use_gc\n        self.T = self.epochs*self.step_per_epoch\n        self.hypertune_nu1 = hypertune_nu1\n        self.HDM = HDM\n\n        defaults = dict(lr=lr,\n                        betas=betas,\n                        nu1=nus[0],\n                        nu2=nus[1],\n                        eps=eps,\n                        alpha=alpha,\n                        gamma=gamma,\n                        p=p,\n                        hypergrad_lr=hypergrad_lr,\n                        weight_decay=weight_decay)\n        super(HyperRanger, self).__init__(params, defaults)\n\n    def __setstate__(self, state):\n        super(HyperRanger, self).__setstate__(state)\n\n    def step(self, activate_IA=False, display=False, closure=None):\n\n        loss = None\n        if closure is not None:\n            loss = closure()\n\n        for group in self.param_groups:\n\n            for p in group['params']:\n                if p.grad is None:\n                    continue\n                grad = p.grad.data.float()\n                if grad.is_sparse:\n                    raise RuntimeError('HyperRanger does not support sparse gradients')\n\n                state = self.state[p]\n\n                hypergrad_lr = group['hypergrad_lr']\n                beta1_init, beta2 = group['betas']\n                wd = group['weight_decay']\n                alpha = group['alpha']\n                gamma = group['gamma']\n\n                if len(state) == 0:\n                    state['step'] = 0\n                    state['exp_avg'] = torch.zeros_like(p.data)\n                    state['exp_avg_sq'] = torch.zeros_like(p.data)\n                    state['lr'] = group['lr']\n\n                    if self.IA:\n                        state['num_models'] = 0\n                    if self.IA or (self.k > 0):\n                        state['cached_params'] = p.data.clone()\n                    if self.nostalgia:\n                        state['B_old'] = 0\n                        state['B_new'] = 1\n                    if hypergrad_lr > 0.0:\n                        state['nu'] = group['nu']\n                        state['prev_lr_grad'] = torch.zeros_like(grad.view(-1))\n                        if self.hypertune_nu1:\n                            state['prev_nu_grad'] = torch.zeros_like(grad.view(-1))\n\n                state['step'] += 1\n                exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n\n                if self.use_demon:\n                    temp = 1-(state['step']/self.T)\n                    beta1 = beta1_init * temp / ((1-beta1_init)+beta1_init*temp)\n                else:\n                    beta1 = beta1_init\n\n                if self.nostalgia:\n                    beta2 = state['B_old']/state['B_new']\n                    state['B_old'] += math.pow(state['step'], -gamma)\n                    state['B_new'] += math.pow(state['step']+1, -gamma)\n\n                do_IA = False\n                lookahead_step = False\n\n                if self.IA and activate_IA:\n                    lookahead_step = False\n                    if state['step'] % self.IA_cycle == 0:\n                        do_IA = True\n                elif self.k == 0:\n                    lookahead_step = False\n                else:\n                    if state['step'] % self.k == 0:\n                        lookahead_step = True\n                    else:\n                        lookahead_step = False\n\n                if state['step'] > 1 and hypergrad_lr > 0.0:\n                    prev_lr_grad = state['prev_lr_grad']\n                    h = torch.dot(grad.view(-1), prev_lr_grad)\n\n                    if self.HDM:\n                        grad_norm = grad.view(-1).norm()\n                        norm_denom = grad_norm*(prev_lr_grad.norm())\n                        norm_denom.add_(group['eps'])\n                        state['lr'] = state['lr']*(1-hypergrad_lr*(h/norm_denom))\n                    else:\n                        state['lr'] -= hypergrad_lr * h\n\n                    torch.max(state['lr'], torch.zeros_like(state['lr']), out=state['lr'])\n\n                    if display:\n                        print(\"lr\", state['lr'])\n\n                    if self.hypertune_nu1:\n                        prev_nu_grad = state['prev_nu_grad']\n                        h = torch.dot(grad.view(-1), prev_nu_grad)\n                        if self.HDM:\n                            norm_denom = grad_norm*(prev_nu_grad.norm())\n                            norm_denom.add_(group['eps'])\n                            state['nu1'] = state['nu1']*(1-hypergrad_lr*(h/norm_denom))\n                        else:\n                            state['nu1'] -= hypergrad_lr * h\n\n                        torch.max(state['nu1'], torch.zeros_like(state['nu1']), out=state['nu1'])\n                        torch.min(state['nu1'], torch.ones_like(state['nu1']), out=state['nu1'])\n\n                    if display:\n                        print(\"nu\", state['nu1'])\n\n                if self.use_gc:\n                    grad.add_(-grad.mean(dim=tuple(range(1, len(list(grad.size())))), keepdim=True))\n\n                nu1 = state['nu1']\n                nu2 = state['nu2']\n                exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n                exp_avg.mul_(beta1).add_(1 - beta1, grad)\n\n                momentum = exp_avg.clone()\n                bias_correction1 = 1 - (beta1 ** state['step'])\n                momentum.div_(bias_correction1)\n\n                vt = exp_avg_sq.clone()\n\n                if not self.nostalgia:\n                    vt.div_(1 - (beta2 ** state['step']))\n                if nu2 != 1.0:\n                    vt.mul_(nu2).addcmul_(1-nu2, grad, grad)\n\n                denom = vt.pow_(group['p']).add_(group['eps'])\n\n                n = state['lr']/denom\n\n                if lookahead_step:\n                    dalpha = alpha\n                elif do_IA:\n                    dalpha = (1/(state[\"num_models\"]+1.0))\n                else:\n                    dalpha = 1.0\n\n                if hypergrad_lr > 0.0 and self.hypertune_nu1:\n                    state['prev_nu_grad'] = (-dalpha*n*(momentum - grad)).view(-1)\n\n                momentum.mul_(nu1).add_(1-nu1, grad)  # quasi hyperbolic momentum\n\n                if hypergrad_lr > 0.0:\n                    temp = dalpha*(-(momentum/denom) - wd*p.data)\n                    state['prev_lr_grad'] = temp.view(-1)\n\n                p.data.add_(-n*momentum)\n\n                if wd != 0:\n                    p.data.add_(-wd*state['lr'], p.data)\n\n                if lookahead_step:\n                    p.data.mul_(alpha).add_(1.0 - alpha, state['cached_params'])\n                    state['cached_params'].copy_(p.data)\n\n                if do_IA:\n                    p.data.add_(state[\"num_models\"], state['cached_params']\n                                ).div_(state[\"num_models\"]+1.0)\n                    state['cached_params'].copy_(p.data)\n                    state[\"num_models\"] += 1\n\n        return loss\n\n\nclass HyperRangerMod(Optimizer):\n\n    # Different from HyperRanger integrates AdaMod, and hypergradient descent through it. Slower, however.\n    # doesn't have hypertunability for nu1 though.\n\n    def __init__(self, params, lr=1e-3,\n                 betas=(0.999, 0.999, 0.999),\n                 nus=(0.7, 1.0),\n                 eps=1e-8,\n                 AdaMod_bias_correct=True,\n                 gamma=0.0001,\n                 nostalgia=True,\n                 use_demon=True,\n                 hypergrad_lr=1e-7,\n                 p=0.5,\n                 k=5,\n                 alpha=0.8,\n                 IA=True,\n                 IA_cycle=1000,\n                 epochs=100,\n                 step_per_epoch=None,\n                 weight_decay=0,\n                 use_gc=True):\n\n        # betas = (beta1 for first order moments, beta2 for second order moments, beta3 for AdaMod) # set beta3 = 0 to disable AdaMod\n        # nus = (nu1,nu2) (for quasi hyperbolic momentum)\n        # eps = small value for numerical stability (avoid divide by zero)\n        # AdaMod_bias_correct = bool to determine whether to apply bias correction on AdaMod or not\n        # k = lookahead cycle\n        # alpha = outer learning rate (lookahead)\n        # gamma = used for nostalgia\n        # nostalgia = bool to decide whether to use nostalgia (from Nostalgic Adam or NosAdam)\n        # use_demon = bool to decide whether to use DEMON (Decaying Momentum) or not\n        # hypergrad_lr = learning rate for updating hyperparameters (like lr) through hypergradient descent (probably need to increase around 0.02 if HDM is True). Set to 0.0 to disable hypergradient descent.\n        # HDM = bool to decide whether to use Multiplicative rule for updating hyperparameters or not\n        # hypertune_nu1 = bool to decide whether apply hypergradient descent on nu1 as well or not.\n        # p = p from PAdam\n        # IA = bool to decide if Iterate Averaging is ever going to be used\n        # IA_cycle = Iterate Averaging Cycle (Recommended to initialize with no. of iterations in Epoch) (doesn't matter if you are not using IA)\n        # epochs = No. of epochs you plan to use (Only relevant if using DEMON)\n        # step_per_epoch = No. of iterations in an epoch (only relevant if using DEMON)\n        # weight decay = decorrelated weight decay value\n        # use_gc = bool to determine whether to use gradient centralization or not.\n        # use_grad_noise = bool to determine whether to use gradient noise or not.\n\n        if not 0.0 <= lr:\n            raise ValueError(\"Invalid learning rate: {}\".format(lr))\n        if not 0.0 <= hypergrad_lr:\n            raise ValueError(\"Invalid hypergradient learning rate: {}\".format(hypergrad_lr))\n        if not 0.0 <= eps:\n            raise ValueError(\"Invalid epsilon value: {}\".format(eps))\n        if not 0.0 <= betas[0] < 1.0:\n            raise ValueError(\"Invalid beta parameter at index 0: {}\".format(betas[0]))\n        if not 0.0 <= betas[1] < 1.0:\n            raise ValueError(\"Invalid beta parameter at index 1: {}\".format(betas[1]))\n        if not 0.0 <= betas[2] < 1.0:\n            raise ValueError(\"Invalid beta parameter at index 2: {}\".format(betas[2]))\n        if not 0.0 <= nus[0] <= 1.0:\n            raise ValueError(\"Invalid nu parameter at index 0: {}\".format(nus[0]))\n        if not 0.0 <= nus[1] <= 1.0:\n            raise ValueError(\"Invalid nu parameter at index 1: {}\".format(nus[1]))\n        if not 0.0 <= p <= 0.5:\n            raise ValueError(\"Invalid p parameter: {}\".format(p))\n        if not 0.0 <= alpha < 1.0:\n            raise ValueError(\"Invalid alpha parameter: {}\".format(alpha))\n\n        self.AdaMod_bias_correct = AdaMod_bias_correct\n        self.nostalgia = nostalgia\n        self.use_demon = use_demon\n        self.k = k\n        self.IA = IA\n        self.IA_cycle = IA_cycle\n        self.epochs = epochs\n        if step_per_epoch is None:\n            self.step_per_epoch = IA_cycle\n        else:\n            self.step_per_epoch = step_per_epoch\n        self.use_gc = use_gc\n        self.T = self.epochs*self.step_per_epoch\n\n        defaults = dict(lr=lr,\n                        betas=betas,\n                        nus=nus,\n                        eps=eps,\n                        alpha=alpha,\n                        gamma=gamma,\n                        p=p,\n                        hypergrad_lr=hypergrad_lr,\n                        weight_decay=weight_decay)\n        super(HyperRangerMod, self).__init__(params, defaults)\n\n    def __setstate__(self, state):\n        super(HyperRangerMod, self).__setstate__(state)\n\n    def step(self, display=False, activate_IA=False, closure=None):\n\n        loss = None\n        if closure is not None:\n            loss = closure()\n\n        for group in self.param_groups:\n\n            for p in group['params']:\n                if p.grad is None:\n                    continue\n                grad = p.grad.data.float()\n                if grad.is_sparse:\n                    raise RuntimeError('HyperRangerMod does not support sparse gradients')\n\n                state = self.state[p]\n\n                hypergrad_lr = group['hypergrad_lr']\n                beta1_init, beta2, beta3 = group['betas']\n                nu1, nu2 = group['nus']\n                wd = group['weight_decay']\n                alpha = group['alpha']\n                gamma = group['gamma']\n\n                if len(state) == 0:\n                    state['step'] = 0\n                    state['exp_avg'] = torch.zeros_like(p.data)\n                    state['exp_avg_sq'] = torch.zeros_like(p.data)\n\n                    if self.IA:\n                        state['num_models'] = 0\n                    if self.IA or self.k > 0:\n                        state['cached_params'] = p.data.clone()\n                    if beta3 > 0.0:\n                        state['n_avg'] = torch.zeros_like(p.data)\n                    if self.nostalgia:\n                        state['B_old'] = 0\n                        state['B_new'] = 1\n                    if hypergrad_lr > 0.0:\n                        state['cached_hypergrad_comp'] = torch.zeros_like(grad.view(-1))\n\n                state['step'] += 1\n                exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n\n                if self.use_demon:\n                    temp = 1-(state['step']/self.T)\n                    beta1 = beta1_init * temp / ((1-beta1_init)+beta1_init*temp)\n                else:\n                    beta1 = beta1_init\n\n                if self.nostalgia:\n                    beta2 = state['B_old']/state['B_new']\n                    state['B_old'] += math.pow(state['step'], -gamma)\n                    state['B_new'] += math.pow(state['step']+1, -gamma)\n\n                do_IA = False\n                lookahead_step = False\n\n                if self.IA and activate_IA:\n                    lookahead_step = False\n                    if state['step'] % self.IA_cycle == 0:\n                        do_IA = True\n                elif self.k == 0:\n                    lookahead_step = False\n                else:\n                    if state['step'] % self.k == 0:\n                        lookahead_step = True\n                    else:\n                        lookahead_step = False\n\n                if state['step'] > 1 and hypergrad_lr > 0.0:\n                    du = state['cached_hypergrad_comp']\n                    h = torch.dot(grad.view(-1), du)\n                    state['lr'] -= hypergrad_lr * h\n                    torch.max(state['lr'], torch.zeros_like(state['lr']), out=state['lr'])\n                    if display:\n                        print(state['lr'])\n\n                if self.use_gc:\n                    grad.add_(-grad.mean(dim=tuple(range(1, len(list(grad.size())))), keepdim=True))\n\n                exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n                exp_avg.mul_(beta1).add_(1 - beta1, grad)\n\n                momentum = exp_avg.clone()\n                momentum.div_(1 - (beta1 ** state['step'])).mul_(nu1).add_(1-nu1, grad)\n                vt = exp_avg_sq.clone()\n\n                if not self.nostalgia:\n                    vt.div_(1 - (beta2 ** state['step']))\n                if nu2 != 1.0:\n                    vt.mul_(nu2).addcmul_(1-nu2, grad, grad)\n\n                denom = vt.pow_(group['p']).add_(group['eps'])\n\n                n = state['lr']/denom\n\n                if beta3 > 0.0:  # apply AdaMod\n                    n_avg = state['n_avg']\n                    n_avg.mul_(beta3).add_(1 - beta3, n)\n                    if self.AdaMod_bias_correct:\n                        n_avg_ = n_avg.clone()\n                        bias_correction3 = 1 - (beta3 ** state['step'])\n                        n_avg_.div_(bias_correction3)\n                        torch.min(n, n_avg_, out=n)\n                    else:\n                        torch.min(n, n_avg, out=n)\n\n                p.data.add_(-n*momentum)\n\n                if lookahead_step:\n                    dalpha = alpha\n                elif do_IA:\n                    dalpha = (1/(state[\"num_models\"]+1.0))\n                else:\n                    dalpha = 1.0\n\n                if hypergrad_lr > 0.0:\n\n                    if beta3 > 0.0:\n                        grad_from_n = dalpha*(-(momentum/denom) - wd*p.data)\n\n                        if self.AdaMod_bias_correct:\n                            grad_from_n_avg_ = dalpha * \\\n                                (-((1-beta3)/bias_correction3)*(momentum/denom) - wd*p.data)\n                            du = torch.where(n_avg_ < n,\n                                             grad_from_n_avg_,\n                                             grad_from_n)\n                        else:\n                            grad_from_n_avg = dalpha*(-(1-beta3)*(momentum/denom) - wd*p.data)\n                            du = torch.where(n_avg < n,\n                                             grad_from_n_avg,\n                                             grad_from_n)\n\n                    else:\n                        du = dalpha*(-(momentum/denom) - wd*p.data)\n\n                    state['cached_hypergrad_comp'] = du.view(-1)\n\n                if wd != 0:\n                    p.data.add_(-wd*state['lr'], p.data)\n\n                if lookahead_step:\n                    p.data.mul_(alpha).add_(1.0 - alpha, state['cached_params'])\n                    state['cached_params'].copy_(p.data)\n\n                if do_IA:\n                    p.data.add_(state[\"num_models\"], state['cached_params']\n                                ).div_(state[\"num_models\"]+1.0)\n                    state['cached_params'].copy_(p.data)\n                    state[\"num_models\"] += 1\n\n        return loss\n\n\nclass HDQHSGDW(Optimizer):\n    def __init__(self, params, lr=1e-3,\n                 beta=0.999,\n                 nu=0.7,\n                 hypergrad_lr=1e-3,\n                 HDM=False,\n                 k=5,\n                 alpha=0.5,\n                 eps=1e-8,\n                 weight_decay=0,\n                 use_gc=True):\n\n        # BASIC SGD + Momentum but with QHMomentum and Hypergradient descent over all beta, lr, and nu + Lookahead and decorrelated weight decay\n        # they say the best of them all is still SGD + Momentum?\n\n        if not 0.0 <= lr:\n            raise ValueError(\"Invalid learning rate: {}\".format(lr))\n        if not 0.0 <= hypergrad_lr:\n            raise ValueError(\"Invalid hypergradient learning rate: {}\".format(hypergrad_lr))\n        if not 0.0 <= beta < 1.0:\n            raise ValueError(\"Invalid beta parameter: {}\".format(beta))\n        if not 0.0 <= nu <= 1.0:\n            raise ValueError(\"Invalid nu parameter: {}\".format(nu))\n        if not 0.0 <= alpha < 1.0:\n            raise ValueError(\"Invalid alpha parameter: {}\".format(alpha))\n\n        self.k = k\n        self.use_gc = use_gc\n        self.HDM = HDM\n\n        defaults = dict(lr=lr,\n                        beta=beta,\n                        nu=nu,\n                        alpha=alpha,\n                        hypergrad_lr=hypergrad_lr,\n                        eps=eps,\n                        weight_decay=weight_decay)\n        super(HDQHSGDW, self).__init__(params, defaults)\n\n    def __setstate__(self, state):\n        super(HDQHSGDW, self).__setstate__(state)\n\n    def hyperupdate(self, update, grad, grad_comp, hypergrad_lr, eps):\n        h = torch.dot(grad.view(-1), grad_comp)\n\n        if self.HDM:\n            grad_norm = grad.view(-1).norm()\n            norm_denom = grad_norm*(grad_comp.norm())\n            norm_denom.add_(eps)\n            update = update*(1-hypergrad_lr*(h/norm_denom))\n        else:\n            update -= hypergrad_lr * h\n\n        return update\n\n    def step(self, display=False, closure=None):\n\n        loss = None\n        if closure is not None:\n            loss = closure()\n\n        for group in self.param_groups:\n\n            for p in group['params']:\n                if p.grad is None:\n                    continue\n                grad = p.grad.data.float()\n                if grad.is_sparse:\n                    raise RuntimeError('HDQHSGDW does not support sparse gradients')\n\n                state = self.state[p]\n\n                hypergrad_lr = group['hypergrad_lr']\n                wd = group['weight_decay']\n                alpha = group['alpha']\n\n                if len(state) == 0:\n                    state['step'] = 0\n                    state['lr'] = group['lr']\n                    state['nu'] = group['nu']\n                    state['beta'] = group['beta']\n                    state['exp_avg'] = torch.zeros_like(p.data)\n                    if self.k > 0:\n                        state['cached_params'] = p.data.clone()\n                    if hypergrad_lr > 0.0:\n                        state['prev_lr_grad'] = torch.zeros_like(grad.view(-1))\n                        state['prev_nu_grad'] = torch.zeros_like(grad.view(-1))\n                        state['prev_beta_grad'] = torch.zeros_like(grad.view(-1))\n\n                state['step'] += 1\n                exp_avg = state['exp_avg']\n\n                lookahead_step = False\n\n                if self.k == 0:\n                    lookahead_step = False\n                else:\n                    if state['step'] % self.k == 0:\n                        lookahead_step = True\n                    else:\n                        lookahead_step = False\n\n                if state['step'] > 1 and hypergrad_lr > 0.0:\n\n                    prev_lr_grad = state['prev_lr_grad']\n                    prev_beta_grad = state['prev_beta_grad']\n                    prev_nu_grad = state['prev_nu_grad']\n\n                    state['lr'] = self.hyperupdate(update=state['lr'],\n                                                   grad=grad,\n                                                   grad_comp=prev_lr_grad,\n                                                   hypergrad_lr=hypergrad_lr,\n                                                   eps=group['eps'])\n\n                    torch.max(state['lr'], torch.zeros_like(state['lr']), out=state['lr'])\n\n                    if display:\n                        print(\"lr\", state['lr'])\n\n                    state['beta'] = self.hyperupdate(update=state['beta'],\n                                                     grad=grad,\n                                                     grad_comp=prev_beta_grad,\n                                                     hypergrad_lr=hypergrad_lr,\n                                                     eps=group['eps'])\n\n                    torch.max(state['beta'], torch.zeros_like(state['beta']), out=state['beta'])\n                    torch.min(state['beta'], torch.ones_like(state['beta']), out=state['beta'])\n\n                    if display:\n                        print(\"beta\", group['beta'])\n\n                    state['nu'] = self.hyperupdate(update=state['nu'],\n                                                   grad=grad,\n                                                   grad_comp=prev_beta_grad,\n                                                   hypergrad_lr=hypergrad_lr,\n                                                   eps=group['eps'])\n\n                    torch.max(state['nu'], torch.zeros_like(state['nu']), out=state['nu'])\n                    torch.min(state['nu'], torch.ones_like(state['nu']), out=state['nu'])\n\n                    if display:\n                        print(\"nu\", state['nu'])\n\n                if self.use_gc:\n                    grad.add_(-grad.mean(dim=tuple(range(1, len(list(grad.size())))), keepdim=True))\n\n                nu = state['nu']\n                beta = state['beta']\n                lr = state['lr']\n\n                if lookahead_step:\n                    dalpha = alpha\n                else:\n                    dalpha = 1.0\n\n                gx = 1 - (beta ** state['step'])\n                fx = beta*exp_avg + (1-beta)*grad\n\n                if hypergrad_lr > 0.0:\n                    dfx = exp_avg - grad\n                    dgx = - state['step'] * beta**(state['step']-1)\n                    dbeta = (gx*dfx + fx*dgx)/(math.pow(gx, 2)+group['eps'])\n                    dbeta = - dalpha*lr*nu*dbeta\n                    state['prev_beta_grad'] = dbeta.view(-1)\n\n                momentum = fx/gx\n                group['exp_avg'] = fx\n\n                if hypergrad_lr > 0.0:\n                    state['prev_nu_grad'] = (-dalpha*lr*(momentum - grad)).view(-1)\n\n                momentum.mul_(nu).add_(1-nu, grad)  # quasi hyperbolic momentum\n\n                if hypergrad_lr > 0.0:\n                    temp = dalpha*(-momentum - wd*p.data)\n                    state['prev_lr_grad'] = temp.view(-1)\n\n                p.data.add_(-group['lr']*momentum)\n\n                if wd != 0:\n                    p.data.add_(-wd*group['lr'], p.data)\n\n                if lookahead_step:\n                    p.data.mul_(alpha).add_(1.0 - alpha, state['cached_params'])\n                    state['cached_params'].copy_(p.data)\n\n        return loss\n\n\nclass HyperProp(Optimizer):\n\n    # LaProp + hypergradient descent on lr and nu (for QH momentum) + QH Momentum + Decaying Momentum (DEMON) + Lookahead + Iterate Averaging + Nostalgia (from NosAdam) + P from PAdam\n    # + gradient centralization + weight decay\n    def __init__(self, params, lr=1e-3,\n                 betas=(0.999, 0.999),\n                 nu=0.7,\n                 eps=1e-8,\n                 gamma=0.0001,\n                 nostalgia=True,\n                 use_demon=True,\n                 hypergrad_lr=0.02,\n                 HDM=True,\n                 hypertune_nu=True,\n                 p=0.25,\n                 k=5,\n                 alpha=0.8,\n                 IA=True,\n                 IA_cycle=1000,\n                 epochs=100,\n                 step_per_epoch=None,\n                 weight_decay=0,\n                 use_gc=True):\n\n        # betas = (beta1 for first order moments, beta2 for second order moments)\n        # nu = for quasi hyperbolic momentum\n        # eps = small value for numerical stability (avoid divide by zero)\n        # k = lookahead cycle\n        # alpha = outer learning rate (lookahead)\n        # gamma = used for nostalgia\n        # nostalgia = bool to decide whether to use nostalgia (from Nostalgic Adam or NosAdam)\n        # use_demon = bool to decide whether to use DEMON (Decaying Momentum) or not\n        # hypergrad_lr = learning rate for updating hyperparameters (like lr) through hypergradient descent (probably need to increase around 0.02 if HDM is True). Set to 0.0 to disable hypergradient descent.\n        # HDM = bool to decide whether to use Multiplicative rule for updating hyperparameters or not\n        # hypertune_nu1 = bool to decide whether apply hypergradient descent on nu1 as well or not.\n        # p = p from PAdam\n        # IA = bool to decide if Iterate Averaging is ever going to be used\n        # IA_cycle = Iterate Averaging Cycle (Recommended to initialize with no. of iterations in Epoch) (doesn't matter if you are not using IA)\n        # epochs = No. of epochs you plan to use (Only relevant if using DEMON)\n        # step_per_epoch = No. of iterations in an epoch (only relevant if using DEMON)\n        # weight decay = decorrelated weight decay value\n        # use_gc = bool to determine whether to use gradient centralization or not.\n        # use_grad_noise = bool to determine whether to use gradient noise or not.\n\n        if not 0.0 <= lr:\n            raise ValueError(\"Invalid learning rate: {}\".format(lr))\n        if not 0.0 <= hypergrad_lr:\n            raise ValueError(\"Invalid hypergradient learning rate: {}\".format(hypergrad_lr))\n        if not 0.0 <= eps:\n            raise ValueError(\"Invalid epsilon value: {}\".format(eps))\n        if not 0.0 <= betas[0] < 1.0:\n            raise ValueError(\"Invalid beta parameter at index 0: {}\".format(betas[0]))\n        if not 0.0 <= betas[1] < 1.0:\n            raise ValueError(\"Invalid beta parameter at index 1: {}\".format(betas[1]))\n        if not 0.0 <= nu <= 1.0:\n            raise ValueError(\"Invalid nu parameter: {}\".format(nu))\n        if not 0.0 <= p <= 0.5:\n            raise ValueError(\"Invalid p parameter: {}\".format(p))\n        if not 0.0 <= alpha < 1.0:\n            raise ValueError(\"Invalid alpha parameter: {}\".format(alpha))\n\n        self.nostalgia = nostalgia\n        self.use_demon = use_demon\n        self.k = k\n        self.IA = IA\n        self.IA_cycle = IA_cycle\n        self.epochs = epochs\n        if step_per_epoch is None:\n            self.step_per_epoch = IA_cycle\n        else:\n            self.step_per_epoch = step_per_epoch\n        self.use_gc = use_gc\n        self.T = self.epochs*self.step_per_epoch\n        self.hypertune_nu = hypertune_nu\n        self.HDM = HDM\n\n        defaults = dict(lr=lr,\n                        betas=betas,\n                        nu=nu,\n                        eps=eps,\n                        alpha=alpha,\n                        gamma=gamma,\n                        p=p,\n                        hypergrad_lr=hypergrad_lr,\n                        weight_decay=weight_decay)\n        super(HyperProp, self).__init__(params, defaults)\n\n    def __setstate__(self, state):\n        super(HyperProp, self).__setstate__(state)\n\n    def step(self, activate_IA=False, display=False, closure=None):\n\n        loss = None\n        if closure is not None:\n            loss = closure()\n\n        for group in self.param_groups:\n\n            for p in group['params']:\n                if p.grad is None:\n                    continue\n                grad = p.grad.data.float()\n                if grad.is_sparse:\n                    raise RuntimeError('HyperProp does not support sparse gradients')\n\n                state = self.state[p]\n\n                hypergrad_lr = group['hypergrad_lr']\n                beta1_init, beta2 = group['betas']\n                wd = group['weight_decay']\n                alpha = group['alpha']\n                gamma = group['gamma']\n\n                if len(state) == 0:\n                    state['lr'] = group['lr']\n                    state['nu'] = group['nu']\n                    state['step'] = 0\n                    state['exp_avg'] = torch.zeros_like(p.data)\n                    state['exp_avg_sq'] = torch.zeros_like(p.data)\n\n                    if self.IA:\n                        state['num_models'] = 0\n                    if self.IA or (self.k > 0):\n                        state['cached_params'] = p.data.clone()\n                    if self.nostalgia:\n                        state['B_old'] = 0\n                        state['B_new'] = 1\n                    if hypergrad_lr > 0.0:\n                        state['prev_lr_grad'] = torch.zeros_like(grad.view(-1))\n                        if self.hypertune_nu:\n                            state['prev_nu_grad'] = torch.zeros_like(grad.view(-1))\n\n                state['step'] += 1\n                exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n\n                if self.use_demon:\n                    temp = 1-(state['step']/self.T)\n                    beta1 = beta1_init * temp / ((1-beta1_init)+beta1_init*temp)\n                else:\n                    beta1 = beta1_init\n\n                if self.nostalgia:\n                    beta2 = state['B_old']/state['B_new']\n                    state['B_old'] += math.pow(state['step'], -gamma)\n                    state['B_new'] += math.pow(state['step']+1, -gamma)\n\n                do_IA = False\n                lookahead_step = False\n\n                if self.IA and activate_IA:\n                    lookahead_step = False\n                    if state['step'] % self.IA_cycle == 0:\n                        do_IA = True\n                elif self.k == 0:\n                    lookahead_step = False\n                else:\n                    if state['step'] % self.k == 0:\n                        lookahead_step = True\n                    else:\n                        lookahead_step = False\n\n                if state['step'] > 1 and hypergrad_lr > 0.0:\n                    prev_lr_grad = state['prev_lr_grad']\n                    h = torch.dot(grad.view(-1), prev_lr_grad)\n\n                    if self.HDM:\n                        grad_norm = grad.view(-1).norm()\n                        norm_denom = grad_norm*(prev_lr_grad.norm())\n                        norm_denom.add_(group['eps'])\n                        state['lr'] = state['lr']*(1-hypergrad_lr*(h/norm_denom))\n                    else:\n                        state['lr'] -= hypergrad_lr * h\n\n                    torch.max(state['lr'], torch.zeros_like(state['lr']), out=state['lr'])\n\n                    if display:\n                        print(\"lr\", state['lr'])\n\n                    if self.hypertune_nu:\n                        prev_nu_grad = state['prev_nu_grad']\n                        h = torch.dot(grad.view(-1), prev_nu_grad)\n                        if self.HDM:\n                            norm_denom = grad_norm*(prev_nu_grad.norm())\n                            norm_denom.add_(group['eps'])\n                            state['nu'] = state['nu']*(1-hypergrad_lr*(h/norm_denom))\n                        else:\n                            state['nu'] -= hypergrad_lr * h\n\n                        torch.max(state['nu'], torch.zeros_like(state['nu']), out=state['nu'])\n                        torch.min(state['nu'], torch.ones_like(state['nu']), out=state['nu'])\n\n                    if display:\n                        print(\"nu\", state['nu'])\n\n                if self.use_gc:\n                    grad.add_(-grad.mean(dim=tuple(range(1, len(list(grad.size())))), keepdim=True))\n\n                nu = state['nu']\n                exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n\n                vt = exp_avg_sq.clone()\n\n                if not self.nostalgia:\n                    vt.div_(1 - (beta2 ** state['step']))\n\n                denom = vt.pow_(group['p']).add_(group['eps'])\n\n                exp_avg.mul_(beta1).addcdiv_(1 - beta1, grad, denom)\n\n                momentum = exp_avg.clone()\n                bias_correction1 = 1 - (beta1 ** state['step'])\n                momentum.div_(bias_correction1)\n\n                if lookahead_step:\n                    dalpha = alpha\n                elif do_IA:\n                    dalpha = (1/(state[\"num_models\"]+1.0))\n                else:\n                    dalpha = 1.0\n\n                if hypergrad_lr > 0.0 and self.hypertune_nu:\n                    state['prev_nu_grad'] = (-dalpha*state['lr']*(momentum - grad)).view(-1)\n\n                momentum.mul_(nu).add_(1-nu, grad)  # quasi hyperbolic momentum\n\n                if hypergrad_lr > 0.0:\n                    temp = dalpha*(-momentum - wd*p.data)\n                    state['prev_lr_grad'] = temp.view(-1)\n\n                p.data.add_(-state['lr'] * momentum)\n\n                if wd != 0:\n                    p.data.add_(-wd*state['lr'], p.data)\n\n                if lookahead_step:\n                    p.data.mul_(alpha).add_(1.0 - alpha, state['cached_params'])\n                    state['cached_params'].copy_(p.data)\n\n                if do_IA:\n                    p.data.add_(state[\"num_models\"], state['cached_params']\n                                ).div_(state[\"num_models\"]+1.0)\n                    state['cached_params'].copy_(p.data)\n                    state[\"num_models\"] += 1\n\n        return loss\n\n# new stuffs to try: https://arxiv.org/pdf/1607.04381.pdf\n", "meta": {"hexsha": "106a295d4157c965d3a731ed518fb3fbf65915b7", "size": 56673, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/optim/optimizers.py", "max_stars_repo_name": "JRC1995/SocialMediaNER", "max_stars_repo_head_hexsha": "236b22ded48f64516ebf0577c3b9d9d907db84e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/optim/optimizers.py", "max_issues_repo_name": "JRC1995/SocialMediaNER", "max_issues_repo_head_hexsha": "236b22ded48f64516ebf0577c3b9d9d907db84e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/optim/optimizers.py", "max_forks_repo_name": "JRC1995/SocialMediaNER", "max_forks_repo_head_hexsha": "236b22ded48f64516ebf0577c3b9d9d907db84e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0673913043, "max_line_length": 208, "alphanum_fraction": 0.4850810792, "include": true, "reason": "import numpy", "num_tokens": 12847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.19704265459889497}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom astropy import units as u\nimport scipy.integrate\nfrom sys import float_info\nimport warnings\n\n\n\nclass Baseliner:\n  \"\"\"\n  A class for interactive baseliner of spectroscopic data.\n\n  The class works by being fed a spectrum and a matplotlib axis on which\n  it should be plotted. The spectrum is then plotted to the given axis,\n  and a number of interactive options are made available to the user.\n\n  Left-clicking with the mouse for the first time starts defining a window\n  from the x-axis location of the click. A second click finishes the\n  window between the locations of the first and second click.\n  A third click will finish selecting windows, and perform the baselining.\n  Alternately, right-clicking will cancel the last left-clicking action,\n  allowing misplaced windows to be adjusted.\n\n  Two keys are also accepted:\n  Pressing \"q\" will cause the baselining process to be canceled,\n  effectively skipping the baselining of this spectrum.\n  Pressing \"a\" will allow an additional window to be defined, assuming\n  one has been defined so far (by left-clicking twice to define its \n  boundaries).\n\n  Attributes\n  ----------\n  windows : `list`\n    A list of all the set windows.\n  \"\"\"\n  def __init__(self,ax,spec):\n    \"\"\"\n    Baseliner(ax,spec,order=1)\n\n    Initialise the `Baseliner` class by giving it the target axis and\n    spectrum.\n\n    Parameters\n    ----------\n    ax : `matplotlib.axis`\n      The matplotlib axis on which the interation will happen.\n    spec : `omnifit.spectrum.BaseSpectrum`\n      The spectrum which will be plotted as the visual reference on\n      the given axis.\n    \"\"\"\n    self.__ax = ax\n    self.__spec = spec\n    self.__x = spec.x.value\n    self.__y = spec.y.value\n    self.__limlo=None\n    self.__limhi=None\n    self.__minx=np.min(self.__x)\n    self.__maxx=np.max(self.__x)\n    self.__miny=np.min(self.__y)\n    self.__maxy=np.max(self.__y)\n    self.__ax.set_xlim(self.__minx,self.__maxx)\n    self.__ax.set_ylim(self.__miny,self.__maxy)\n    self.__specplot,=self.__ax.plot(self.__x,self.__y,'k-',drawstyle='steps-mid')\n    self.__buttonListener = self.__ax.figure.canvas.mpl_connect('button_press_event', self.__mouse_press)\n    self.__keyListener = self.__ax.figure.canvas.mpl_connect('key_press_event', self.__key_press)\n    self.windows=[]\n  def __key_press(self, event):\n    if event.key=='q':\n      self.__skip()\n    if event.key=='a' and self.__limlo != None and self.__limhi != None:\n      self.__addwindow(self.__limlo,self.__limhi)\n      self.__ax.plot([self.__limlo,self.__limlo],[self.__miny,self.__maxy],'g-')\n      self.__ax.plot([self.__limhi,self.__limhi],[self.__miny,self.__maxy],'g-')\n      self.__remlim()\n      self.__remlim()\n      print 'Window added. Ready to receive another one.'\n    else:\n      return\n  def __mouse_press(self, event):\n    if event.button==1:\n      self.__setlim(event.xdata)\n    elif event.button==2:\n      return\n    elif event.button==3:\n      self.__remlim()\n  def __skip(self):\n    plt.close()\n  def __setlim(self,i_x):\n    if self.__limlo==None:\n      self.__limlo=i_x\n      self.__limloplot,=self.__ax.plot([i_x,i_x],[self.__miny,self.__maxy],'b-')\n      self.__ax.figure.canvas.draw()\n    elif self.__limhi==None:\n      self.__limhi=i_x\n      self.__limhiplot,=self.__ax.plot([i_x,i_x],[self.__miny,self.__maxy],'b-')\n      self.__ax.figure.canvas.draw()\n      print 'Ready for finalising. Press once more to do so, or press a to add another window.'\n    else:\n      self.__finalise()\n  def __remlim(self):\n    if self.__limhi!=None:\n      self.__limhi=None\n      self.__limhiplot.set_ydata([self.__miny,self.__miny])\n      self.__ax.figure.canvas.draw()\n    elif self.__limlo!=None:\n      self.__limlo=None\n      self.__limloplot.set_ydata([self.__miny,self.__miny])\n      self.__ax.figure.canvas.draw()\n    else:\n      print 'No limits to cancel.'\n  def __addwindow(self,limlo,limhi):\n    if limhi < limlo:\n      limlo,limhi = limhi,limlo\n    self.windows.append([limlo,limhi])\n  def __finalise(self):\n    self.__addwindow(self.__limlo,self.__limhi)\n    self.__ax.figure.canvas.mpl_disconnect(self.__buttonListener)\n    self.__ax.figure.canvas.mpl_disconnect(self.__keyListener)\n    plt.close(self.__ax.figure)\n\n#---------------------\n#New units definitions\n#---------------------\n#the units themselves\nunit_t = u.def_unit('transmittance units',doc='Transmittance of radiation')\nunit_transmittance = unit_t\nunit_abs = u.def_unit('absorbance units',doc='Absorbance of radiation')\nunit_absorbance = unit_abs\nunit_od = u.def_unit('optical depth units',doc='Optical depth of radiation')\nunit_opticaldepth = unit_od\n\n#the equivalencies between the units\nequivalencies_absorption = [\n    (unit_t,unit_abs,lambda x:-np.log10(x),lambda x:10**-x),\n    (unit_od,unit_abs,lambda x:x/np.log(10),lambda x:x*np.log(10)),\n    (unit_od,unit_t,lambda x:10**(-x/np.log(10)),lambda x:-np.log10(x)*np.log(10))\n    ]\n\n#------------------------------------------------------\n#Functions related to light scattering and transmission\n#------------------------------------------------------\ndef cde_correct(freq,m):\n  \"\"\"\n  cde_correct(freq,m)\n\n  Generate a CDE-corrected spectrum from a complex refractive index\n  spectrum.\n\n  Parameters\n  ----------\n  freq : `numpy.ndarray`\n    The frequency data of the input spectrum, in reciprocal\n    wavenumbers (cm^-1).\n  m : `numpy.ndarray`\n    The complex refractive index spectrum.\n\n  Returns\n  -------\n  A list containing the following numpy arrays, in given order:\n    * The spectrum of the absorption cross section of the simulated grain.\n    * The spectrum of the absorption cross section of the simulated grain,\n      normalized by the volume distribution of the grain. This parameter\n      is the equivalent of optical depth in most cases.\n    * The spectrum of the scattering cross section of the simulated grain,\n      normalized by the volume distribution of the grain.\n    * The spectrum of the total cross section of the simulated grain.    \n  \"\"\"\n  wl=1.e4/freq\n  m2=m**2.0\n  im_part=((m2/(m2-1.0))*np.log(m2)).imag\n  cabs_vol=(4.0*np.pi/wl)*im_part\n  cabs=freq*(2.0*m.imag/(m.imag-1))*np.log10(m.imag)\n  cscat_vol=(freq**3.0/(6.0*np.pi))*cabs\n  ctot=cabs+cscat_vol\n  return cabs,cabs_vol,cscat_vol,ctot\n\ndef complex_transmission_reflection(in_m0,in_m1,in_m2):\n  \"\"\"\n  complex_transmission_reflection(in_m0,in_m1,in_m2)\n\n  Calculate the complex transmission and reflection coefficients between\n  media 0, 1, and 2 given their complex refractive indices.\n  In the Kramers-Kronig implementation (in which this is most likely used\n  in the context of Omnifit) media 0, 1, and 2 correspond\n  respectively to the vacuum, ice, and substrate.\n\n  Parameters\n  ----------\n  in_m0 : `complex` or `numpy.ndarray`\n    The complex refractive index of medium 0.\n  in_m1 : `complex` or `numpy.ndarray`\n    The complex refractive index of medium 1.\n  in_m2 : `complex` or `numpy.ndarray`\n    The complex refractive index of medium 2.\n\n  Returns\n  -------\n  A tuple containing the following elements:\n    * The complex transmission coefficient between media 0 and 1\n    * The complex transmission coefficient between media 0 and 2\n    * The complex transmission coefficient between media 1 and 2\n    * The complex reflection coefficient between media 0 and 1\n    * The complex reflection coefficient between media 0 and 2\n    * The complex reflection coefficient between media 1 and 2\n  \"\"\"\n  complex_transmission = lambda m1,m2: (2.*m1.real)/(m1+m2)\n  complex_reflection = lambda m1,m2: (m1-m2)/(m1+m2)\n  return (\n          complex_transmission(in_m0,in_m1),\n          complex_transmission(in_m0,in_m2),\n          complex_transmission(in_m1,in_m2),\n          complex_reflection(in_m0,in_m1),\n          complex_reflection(in_m0,in_m2),\n          complex_reflection(in_m1,in_m2)\n        )\n\ndef kramers_kronig(freq,transmittance,m_substrate,d_ice,m0,freq_m0,m_guess=1.0+0.0j,tol=0.001,maxiter=100,ignore_fraction=0.1,force_kkint_unity=False,precalc=False):\n  \"\"\"\n  kramers_kronig(freq,transmittance,m_substrate,d_ice,m0,freq_m0,\n                 m_guess=1.0+0.0j,tol=0.001,maxiter=100,ignore_fraction=0.1,\n                 force_kkint_unity=False,precalc=False)\n\n  Kramers-Kronig relation.\n  This is an implementation of the Kramers-Kronig relation calculation\n  presented in Hudgins et al 1993 (1993ApJS...86..713H), with an improved\n  integration method adapted from Trotta et al 1996 \n  (The Cosmic Dust Connection, 1996 169-184)\n\n  Parameters\n  ----------\n  wn : `astropy.units.Quantity` or `numpy.ndarray`\n    The frequency data of the input spectrum. If no units are given, this\n    is assumed to be in reciprocal wavenumbers (cm^-1).\n  transmittance : `astropy.units.Quantity` or `numpy.ndarray`\n    The transmittance data of the input spectrum. This can be given in\n    units other than transmittance, as long as they can be converted to \n    transmittance by making use of the `utils.equivalencies_absorption`\n    equivalency information. If no units are given, transmittance is\n    assumed.\n  m_substrate : `complex`\n    The complex refractive index of the substrate on which the ice being\n    studied was grown.\n  d_ice : `astropy.units.Quantity` or `float`\n    The thickness of the ice which is being studied. If no units are given,\n    centimeters are assumed.\n  m0 : `complex`\n    The complex refractive index of the ice at the reference frequency\n    defined by `freq_m0` (see below).\n  freq_m0 : `astropy.units.Quantity` or `float`\n    The frequency at which the reference complex refractive index `m0`\n    (see above) is defined. Best results are usually achieved if this\n    frequency is high compared to the frequency range being probed by\n    the spectrum.\n    If this is not defined as `astropy.units.Quantity` in spectroscopic\n    units, it is assumed to be in reciprocal wavenumbers (cm^-1).\n  m_guess : `complex` or `numpy.ndarray`\n    The starting guess of the complex refractive index of the ice. This\n    can either be a single number (in which case it is assumed to be this\n    number throughout the entire spectrum) or an array\n  tol : `float`\n    The square-sum of the residual between the original transmittance and\n    the transmittance modeled with the iterated complex refractive index\n    of the ice must be below this value for the iteration to converge. In\n    other words, the smaller this number is, the better the final result\n    will be at the expense of extra iterations.\n  maxiter : `int`\n    The maximum number of iterations allowed. If this number is reached,\n    the iteration is considered to not have converged, and an exception is\n    raised.\n  ignore_fraction : `float` between 0 and 0.5\n    The edges of the spectrum are blanked out (and replaced with the\n    non-blanked value closest to the edge) during iteration to avoid edge\n    effects arising from the usage of a non-infinite integration range.\n    This parameter controls how large of a fraction of the edges is blanked\n    out.\n  force_kkint_unity : `bool`\n    The results of the Kramers-Kronig integration are responsible for\n    determining the real part of the complex refractive index i.e. the\n    one which represents refraction. Normally this number should not drop\n    below unity, and unexpected behaviour can arise if it does.\n    Usually this means that there is something wrong with the input\n    parameters, but sometimes forcing the result to always be greater or\n    equal to unity can help. It should be noted, however, that the\n    accuracy of the results of an integration forced in this way are\n    suspect at best.\n  precalc : `bool`\n    The Kramers-Kronig iteration can be a very computationally intensive\n    operation. In some situations it may result in a faster iteration to\n    pre-calculate the large denominator which is part of the\n    Kramers-Kronig integration instead of computing new values of it in a\n    for loop. This denominator can be, however, a very\n    large variable as it contains a number of elements equal to the size\n    of the spectrum squared. Pre-calculating this can outright fail on\n    lower-end computers as Python runs out of available memory.\n    High-end systems may benefit from such pre-calculation, though.\n\n  Returns\n  -------\n  A `numpy.ndarray` which contains the complex refractive index of the\n  ice, in order of increasing frequency.\n  \"\"\"\n  #set up constants\n  m_vacuum = 1.0+0.0j\n  #make sure the input array units are correct; convert if necessary\n  if type(freq) != u.quantity.Quantity:\n    warnings.warn('No units detected in input freq. Assuming kayser.',RuntimeWarning)\n    freq *= u.kayser\n  else:\n    with u.set_enabled_equivalencies(u.equivalencies.spectral()):\n      freq=freq.to(u.kayser)\n  if type(transmittance) != u.quantity.Quantity:\n    warnings.warn('No units detected in input transmittance. Assuming transmittance units.',RuntimeWarning)\n    transmittance *= unit_t\n  else:\n    with u.set_enabled_equivalencies(equivalencies_absorption):\n      transmittance = transmittance.to(unit_t)\n  if type(d_ice) != u.quantity.Quantity:\n    warnings.warn('No units detected in input d_ice. Assuming centimeters.',RuntimeWarning)\n    d_ice *= u.cm\n  else:\n    d_ice = d_ice.to(u.cm)\n  #sort the arrays and get rid of units; won't need them after this\n  initial_sorter = np.argsort(freq)\n  freq = freq[initial_sorter].value\n  transmittance = transmittance[initial_sorter].value\n  d_ice = d_ice.value\n  #initialise complex refractive index and alpha arrays\n  m = np.full_like(freq,np.nan+np.nan*1j,dtype=complex)\n  alpha = np.full_like(freq,np.nan+np.nan*1j,dtype=complex)\n  #initial guess at m at first index\n  if type(m_guess)==complex:\n    m_ice = np.full_like(freq,m_guess,dtype=complex)\n  else:\n    m_ice = m_guess\n  #find top and bottom fraction indices. These will be replaced with dummy values after each integration to get rid of edge effects\n  if ignore_fraction > 0.5 or ignore_fraction < 0:\n    raise RuntimeError('ignore_fraction must be between 0.0 and 0.5')\n  bot_fraction = round(ignore_fraction*len(freq))\n  top_fraction = len(freq)-bot_fraction\n  #pre-calculate the large denominator component of the KK integration, if desired\n  if precalc:\n    try:\n      sfreq=(freq).reshape(len(freq),1)\n      kkint_deno1 = freq**2-sfreq**2\n      kkint_deno1[kkint_deno1!=0] = 1./kkint_deno1[kkint_deno1!=0]\n      precalc = True\n    #or at least try to do so; if run out of memory, switch to the slower no-precalc mode\n    except MemoryError:\n      precalc = False\n  #some other parts can always be precalced\n  kkint_mul = 1./(2*np.pi*np.pi)\n  kkint_deno2 = freq**2-freq_m0**2\n  kkint_deno2[kkint_deno2!=0] = 1./kkint_deno2[kkint_deno2!=0]\n  #calculate alpha at freq0\n  alpha0 = m0.imag/(4*np.pi*freq)\n  #iteration begin!\n  niter = 0\n  squaresum_diff = tol+1\n  while squaresum_diff > tol and niter < maxiter:\n    #calculate transmission and relfection coefficients\n    #in these 0 means vacuum, 1 means ice, 2 means substrate\n    t01,t02,t12,r01,r02,r12 = complex_transmission_reflection(m_vacuum,m_ice,m_substrate)\n    #the reflection component\n    # reflection_component = np.abs((t01*t12/t02)/(1.+r01*r12*np.exp(4.j*np.pi*d_ice*m_ice*freq)))**2.)\n    #this is an evil equation. do NOT touch it\n    #it calculates the lambert absorption coefficient using the current best guess at m_ice\n    alpha = (1./d_ice)*(-np.log(transmittance)+np.log(np.abs((t01*t12/t02)/(1.+r01*r12*np.exp(4.j*np.pi*d_ice*m_ice*freq)))**2.))\n    #using the new alpha, calculate a new n (and thus m) for the ice\n    #this is done in a parallel for loop, to avoid killing the computer when dealing with large amounts of data\n    kkint_nomi = alpha-alpha0\n    kkint = np.full_like(alpha,m0.real)\n    numcols = kkint_nomi.shape[0]\n    for current_col in range(numcols):\n      if precalc:\n        kkint[current_col]+=kkint_mul*scipy.integrate.simps((alpha-alpha[current_col])*kkint_deno1[current_col,:]-kkint_nomi*kkint_deno2)\n      else:\n        kkint_deno1 = freq[current_col]**2-freq**2\n        kkint_deno1[kkint_deno1!=0] = 1./kkint_deno1[kkint_deno1!=0]\n        kkint[current_col]+=kkint_mul*scipy.integrate.simps((alpha-alpha[current_col])*kkint_deno1-kkint_nomi/(freq**2-freq_m0**2))\n    if np.any(kkint<1):\n      if np.any(kkint<0):\n        warnings.warn('KK integration is producing negative refractive indices! This will most likely produce nonsensical results.',RuntimeWarning)\n      else:\n        warnings.warn('KK integration is producing refractive indices below unity! This may result in unexpected behaviour.',RuntimeWarning)\n      if force_kkint_unity:\n        kkint[kkint<1]=1.\n    m_ice = kkint+1j*alpha/(4*np.pi*freq)\n    if np.any(np.isnan(m_ice.real)) or np.any(np.isnan(m_ice.imag)):\n      raise RuntimeError('Produced complex refractive index contains NaNs. Check your input parameters.')\n    #replace top and bottom fractions of m_ice with the value closest to that edge\n    #this is done to combat edge effects arising from integrating over a non-infinite range\n    m_ice[:bot_fraction] = m_ice[bot_fraction]\n    m_ice[top_fraction:] = m_ice[top_fraction]\n    #calculate transmission and relfection coefficients (again)\n    #in these 0 means vacuum, 1 means ice, 2 means substrate\n    t01,t02,t12,r01,r02,r12 = complex_transmission_reflection(m_vacuum,m_ice,m_substrate)\n    #model a transmittance using given m_ice and alpha\n    #yes, this is another evil equation\n    transmittance_model = np.exp(-alpha*d_ice)*np.abs((t01*t12/t02)/(1.+r01*r12*np.exp(4.j*np.pi*d_ice*m_ice*freq)))**2.\n    diff = transmittance - transmittance_model\n    diff[:bot_fraction] = 0. #ignore top...\n    diff[top_fraction:] = 0. #...and bottom fraction differences\n    squaresum_diff = np.sum(diff**2) #square sum of difference\n    niter += 1\n  #at this point we are done\n  if niter>=maxiter:\n    raise RuntimeError('Maximum number of iterations reached before convergence criterion was met.')\n  return m_ice", "meta": {"hexsha": "ea263079e5d79bb71d5b830f68e49a093bee54c1", "size": 17927, "ext": "py", "lang": "Python", "max_stars_repo_path": "omnifit/utils/utils.py", "max_stars_repo_name": "astrobot/omnifit", "max_stars_repo_head_hexsha": "7cc9e499fd149d6d3a3a15761c5380778a3f4f42", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-08-25T16:40:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T08:25:07.000Z", "max_issues_repo_path": "omnifit/utils/utils.py", "max_issues_repo_name": "astrobot/omnifit", "max_issues_repo_head_hexsha": "7cc9e499fd149d6d3a3a15761c5380778a3f4f42", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2015-08-27T15:19:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T18:50:31.000Z", "max_forks_repo_path": "omnifit/utils/utils.py", "max_forks_repo_name": "astrobot/omnifit", "max_forks_repo_head_hexsha": "7cc9e499fd149d6d3a3a15761c5380778a3f4f42", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2015-12-31T19:24:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-18T07:28:19.000Z", "avg_line_length": 43.8312958435, "max_line_length": 165, "alphanum_fraction": 0.715903386, "include": true, "reason": "import numpy,import scipy,from astropy", "num_tokens": 4796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.36296919862864757, "lm_q1q2_score": 0.1970426508580408}}
{"text": "# -*- coding: utf-8 -*-\n'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling.\nCopyright (C) 2016, 2017 Caleb Bell <Caleb.Andrew.Bell@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.'''\n\nfrom __future__ import division\ntry: # pragma: no cover\n    from cStringIO import StringIO\nexcept: # pragma: no cover\n    from io import BytesIO as StringIO\nimport os\nimport gzip\nimport datetime\nfrom calendar import isleap\nfrom collections import namedtuple\n\nimport numpy as np\nfrom fluids.core import F2K\nfrom scipy.constants import mile, knot, inch\nfrom scipy.spatial import KDTree, cKDTree\nfrom scipy.stats import scoreatpercentile\n\n\ntry: # pragma: no cover\n    from urllib.request import urlopen\n    from urllib.error import HTTPError\nexcept ImportError: # pragma: no cover\n    from urllib2 import urlopen\n    from urllib2 import HTTPError\n    \ntry:  # pragma: no cover\n    from appdirs import user_data_dir, user_config_dir\n    data_dir = user_config_dir('fluids')\nexcept ImportError:  # pragma: no cover\n    data_dir = ''\n    pass\n# TODO: Import ephem and get hours/minutes of sunlight per day.\n    \n__all__ = ['get_clean_isd_history', 'IntegratedSurfaceDatabaseStation',\n           'get_closest_station', 'get_station_year_text', 'gsod_day_parser',\n           'StationDataGSOD', 'heating_degree_days', 'cooling_degree_days', 'stations']\n\nfolder = os.path.join(os.path.dirname(__file__), 'data')\n\n\ndef heating_degree_days(T, T_base=F2K(65), truncate=True):\n    r'''Calculates the heating degree days for a period of time.\n\n    .. math::\n        \\text{heating degree days} = max(T - T_{base}, 0)\n\n    Parameters\n    ----------\n    T : float\n        Measured temperature; sometimes an average over a length of time is used,\n        other times the average of the lowest and highest temperature in a \n        period are used, [K]\n    T_base : float, optional\n        Reference temperature for the degree day calculation, defaults\n        to 65 °F (18.33 °C, 291.483 K), the value most used in the US, [K]\n    truncate : bool\n        If truncate is True, no negative values will be returned; if negative, \n        the value is truncated to 0, [-]\n\n    Returns\n    -------\n    heating_degree_days : float\n        Degree above the base temperature multiplied by the length of time of\n        the measurement, normally days [day*K]\n\n    Notes\n    -----\n    Some common base temperatures are 18 °C (Canada), 15.5 °C (EU), \n    17 °C (Denmark, Finland), 12 °C Switzerland. The base temperature\n    should always be presented with the results.\n    \n    The time unit does not have to be days; it can be any time unit, and the\n    calculation behaves the same.\n\n    Examples\n    --------\n    >>> heating_degree_days(303.8)\n    12.31666666666672\n    \n    >>> heating_degree_days(273)\n    0.0\n    \n    >>> heating_degree_days(322, T_base=300)\n    22\n\n    References\n    ----------\n    .. [1] \"Heating Degree Day.\" Wikipedia, January 24, 2018. \n       https://en.wikipedia.org/w/index.php?title=Heating_degree_day&oldid=822187764.\n    '''\n    dd = T - T_base\n    if truncate and dd < 0.0:\n        dd = 0.0\n    return dd\n\n\ndef cooling_degree_days(T, T_base=283.15, truncate=True):\n    r'''Calculates the cooling degree days for a period of time.\n\n    .. math::\n        \\text{cooling degree days} = max(T_{base} - T, 0)\n\n    Parameters\n    ----------\n    T : float\n        Measured temperature; sometimes an average over a length of time is used,\n        other times the average of the lowest and highest temperature in a \n        period are used, [K]\n    T_base : float, optional\n        Reference temperature for the degree day calculation, defaults\n        to 10 °C, 283.15 K, a common value, [K]\n    truncate : bool\n        If truncate is True, no negative values will be returned; if negative, \n        the value is truncated to 0, [-]\n\n    Returns\n    -------\n    cooling_degree_days : float\n        Degree below the base temperature multiplied by the length of time of\n        the measurement, normally days [day*K]\n\n    Notes\n    -----\n    The base temperature should always be presented with the results.\n    \n    The time unit does not have to be days; it can be time unit, and the\n    calculation behaves the same.\n\n    Examples\n    --------\n    >>> cooling_degree_days(250)\n    33.14999999999998\n    \n    >>> cooling_degree_days(300)\n    0.0\n    \n    >>> cooling_degree_days(250, T_base=300)\n    50\n\n    References\n    ----------\n    .. [1] \"Heating Degree Day.\" Wikipedia, January 24, 2018. \n       https://en.wikipedia.org/w/index.php?title=Heating_degree_day&oldid=822187764.\n    '''\n    dd = T_base - T\n    if truncate and dd < 0.0:\n        dd = 0.0\n    return dd\n\n\ndef get_clean_isd_history(dest=os.path.join(folder, 'isd-history-cleaned.tsv'),\n                          url=\"ftp://ftp.ncdc.noaa.gov/pub/data/noaa/isd-history.csv\"): # pragma: no cover\n    '''Basic method to update the isd-history file from the NOAA. This is \n    useful as new weather stations are updated all the time.\n    \n    This function requires pandas to run. If fluids is installed for the \n    superuser, this method must be called in an instance of Python running\n    as the superuser (administrator).\n    \n    Retrieving the file from ftp typically takes several seconds.\n    Pandas reads the file in ~30 ms and writes it in ~220 ms. Reading it with \n    the code below takes ~220 ms but is necessary to prevent a pandas \n    dependency.\n    \n    Parameters\n    ----------\n    dest : str, optional\n        The file to store the data retrieved; leave as the default argument\n        for it to be accessible by fluids.\n    url : str, optional\n        The location of the data file; this can be anywhere that can be read\n        by pandas, including a local file as would be useful in an offline\n        situation.\n    '''\n    import pandas as pd\n    df = pd.read_csv(url)\n    df.to_csv(dest, sep='\\t', index=False, header=False)\n\n\nclass IntegratedSurfaceDatabaseStation(object):\n    '''Class to hold data on a weather station in the Integrated Surface\n    Database.\n    \n    License information for the database can be found at the following link:\n    https://data.noaa.gov/dataset/global-surface-summary-of-the-day-gsod\n\n    Parameters\n    ----------\n    USAF : int or None if unassigned\n        Air Force station ID. May contain a letter in the first position.\n    WBAN : int or None if unassigned\n        NCDC WBAN number\n    NAME : str\n        Name of the station; ex. 'CENTRAL COLORADO REGIONAL AP'\n    CTRY : str or None if unspecified\n        FIPS country ID\n    ST : str or None if not in the US\n        State for US stations\n    ICAO : str or None if not an airport\n        ICAO airport code\n    LAT : float\n        Latitude with a precision of one thousandths of a decimal degree, \n        [degrees]\n    LON : float\n        Longitude with a precision of one thousandths of a decimal degree, \n        [degrees]\n    ELEV : float\n        Elevation of weather station, [m]\n    BEGIN : float\n        Beginning Period Of Record (YYYYMMDD). There may be reporting gaps \n        within the P.O.R.\n    END : Ending Period Of Record (YYYYMMDD). There may be reporting gaps\n        within the P.O.R.\n    '''\n    __slots__ = ['USAF', 'WBAN', 'NAME', 'CTRY', 'ST', 'ICAO', 'LAT', 'LON',\n                 'ELEV', 'BEGIN', 'END', 'raw_data', 'parsed_data']\n    \n    def __repr__(self):\n        s = ('<Weather station registered in the Integrated Surface Database, '\n            'name %s, country %s, USAF %s, WBAN %s, coords (%s, %s) '\n            'Weather data from %s to %s>' )\n        return s%(self.NAME, self.CTRY, self.USAF, self.WBAN, self.LAT, self.LON, str(self.BEGIN)[0:4], str(self.END)[0:4])\n    \n    def __init__(self, USAF, WBAN, NAME, CTRY, ST, ICAO, LAT, LON, ELEV, BEGIN,\n                 END):\n        try:\n            self.USAF = int(USAF)\n        except TypeError:\n            self.USAF = USAF # Nones\n        try:\n            self.WBAN = int(WBAN)  \n        except TypeError:\n            self.WBAN = WBAN\n        self.NAME = NAME\n        self.CTRY = CTRY\n        self.ST = ST\n        self.ICAO = ICAO\n        self.LAT = LAT\n        self.LON = LON\n        self.ELEV = ELEV\n        self.BEGIN = int(BEGIN)\n        self.END = int(END)\n        \n\nclass StationDataGSOD(object):\n    # Holds data, caches and retrieves data\n    def __init__(self, station):\n        self.station = station\n        self.begin = datetime.datetime.strptime(str(self.station.BEGIN), '%Y%m%d')\n        self.end = datetime.datetime.strptime(str(self.station.END), '%Y%m%d')\n        \n        self.year_range = range(self.begin.year, self.end.year + 1)\n        \n#         Would be nice to create these later, when using a download_data method\n        self.raw_text = {}\n        self.raw_data = {}\n        self.parsed_data = {}\n        self.load_empty_vectors()\n        self.download_data()\n        self.parse_data()\n        \n    def load_empty_vectors(self):\n        for year in self.year_range:\n            days_in_year = 366 if isleap(year) else 365\n            self.raw_data[year] = [None]*days_in_year\n            self.parsed_data[year] = [None]*days_in_year\n            self.raw_text[year] = None\n#        days = [None]*days_in_year(y)\n\n    def download_data(self):\n        for year in self.year_range:\n            if self.raw_text[year] is None:\n                try:\n                    year_data = get_station_year_text(self.station.USAF, self.station.WBAN, year)\n                    self.raw_text[year] = year_data\n                except:\n                    pass\n    \n    def parse_data(self):\n        for year, data in self.raw_text.items():\n            if data is not None:\n                days = self.parsed_data[year]\n                for line in data.split('\\n')[1:-1]:\n                    parsed = gsod_day_parser(line)\n                    doy = parsed.DATE.timetuple().tm_yday-1\n                    days[doy] = parsed\n                    \n    def coldest_month(self, older_year=None, newer_year=None, minimum_days=23):\n        # Tested\n        month_data = self.month_average_temperature(older_year=older_year,\n                                                    newer_year=newer_year, \n                                                    minimum_days=minimum_days)\n        return month_data.index(min(month_data))\n    \n    def warmest_month(self, older_year=None, newer_year=None, minimum_days=23):\n        # Tested\n        month_data = self.month_average_temperature(older_year=older_year,\n                                                    newer_year=newer_year, \n                                                    minimum_days=minimum_days)\n        return month_data.index(max(month_data))\n\n    def month_average_temperature(self, older_year=None, newer_year=None,\n                                  include_yearly=False, minimum_days=23):\n        '''\n        >> station = get_closest_station(38.8572, -77.0369)\n        >> station_data = StationDataGSOD(station)\n        >> station_data.month_average_temperature(1990, 2000, include_yearly=False)\n        [276.1599380905833, 277.5375516246206, 281.1881231671554, 286.7367003367004, 291.8689638318671, 296.79545454545456, 299.51868686868687, 298.2097914630174, 294.4116161616162, 288.25883023786247, 282.3188552188553, 277.8282339524275]\n        '''\n        # Take years, make them inclusive; add minimum valid days.\n        year_month_averages = {}\n        year_month_counts = {}\n        \n        for year, data in self.parsed_data.items():\n            if not (older_year <= year <= newer_year):\n                continue # Ignore out-of-range years easily\n            year_month_averages[year] = [0.0]*12\n            year_month_counts[year] = [0]*12\n\n            for i, day in enumerate(data):\n                if day is None:\n                    continue\n                # Don't do these comparisions to make it fast\n                if day.DATE.year < older_year or day.DATE.year > newer_year:\n                    continue # Ignore out-of-range days as possible\n                    \n                T = day.TEMP\n                if T is None:\n                    continue\n                # Cache these lookups\n                year_month_averages[year][day.DATE.month-1] += T\n                year_month_counts[year][day.DATE.month-1] += 1\n            \n            for month in range(12):\n                count = year_month_counts[year][month]\n                if count < minimum_days:\n                    ans = None\n                else:\n                    ans = year_month_averages[year][month]/count\n                year_month_averages[year][month] = ans\n                \n        # Compute the average of the month\n        actual_averages = [0.0]*12\n        actual_averages_counts = [0]*12\n        for year, average in year_month_averages.items():\n            for month in range(12):\n                if average is not None and average[month] is not None:\n                    count = actual_averages_counts[month] \n                    if count is None:\n                        count = 1\n                    else: \n                        count += 1\n                    actual_averages_counts[month] = count\n                    month_average_sum = actual_averages[month]\n                    if month_average_sum is None:\n                        month_average_sum = average[month]\n                    else:\n                        month_average_sum += average[month]\n                    actual_averages[month] = month_average_sum\n                    \n        for month in range(12):\n            actual_averages[month] = actual_averages[month]/actual_averages_counts[month]\n                    \n        # Don't set anything as properties - too many variables used in calculating thems\n        # Speed is not that important.\n        if include_yearly:\n            return actual_averages, year_month_averages\n        else:\n            return actual_averages\n\n    # Copy and paste\n    def month_average_windspeed(self, older_year=None, newer_year=None,\n                                  include_yearly=False, minimum_days=23):\n        # Take years, make them inclusive; add minimum valid days.\n        year_month_averages = {}\n        year_month_counts = {}\n        \n        for year, data in self.parsed_data.items():\n            if not (older_year <= year <= newer_year):\n                continue # Ignore out-of-range years easily\n            year_month_averages[year] = [0.0]*12\n            year_month_counts[year] = [0]*12\n\n            for i, day in enumerate(data):\n                if day is None:\n                    continue\n                # Don't do these comparisions to make it fast\n                if day.DATE.year < older_year or day.DATE.year > newer_year:\n                    continue # Ignore out-of-range days as possible\n                    \n                wind_speed = day.WDSP\n                if wind_speed is None:\n                    continue\n                # Cache these lookups\n                year_month_averages[year][day.DATE.month-1] += wind_speed\n                year_month_counts[year][day.DATE.month-1] += 1\n            \n            for month in range(12):\n                count = year_month_counts[year][month]\n                if count < minimum_days:\n                    ans = None\n                else:\n                    ans = year_month_averages[year][month]/count\n                year_month_averages[year][month] = ans\n                \n        # Compute the average of the month\n        actual_averages = [0.0]*12\n        actual_averages_counts = [0]*12\n        for year, average in year_month_averages.items():\n            for month in range(12):\n                if average is not None and average[month] is not None:\n                    count = actual_averages_counts[month] \n                    if count is None:\n                        count = 1\n                    else: \n                        count += 1\n                    actual_averages_counts[month] = count\n                    month_average_sum = actual_averages[month]\n                    if month_average_sum is None:\n                        month_average_sum = average[month]\n                    else:\n                        month_average_sum += average[month]\n                    actual_averages[month] = month_average_sum\n                    \n        for month in range(12):\n            actual_averages[month] = actual_averages[month]/actual_averages_counts[month]\n                    \n        # Don't set anything as properties - too many variables used in calculating thems\n        # Speed is not that important.\n        if include_yearly:\n            return actual_averages, year_month_averages\n        else:\n            return actual_averages\n\n    def percentile_extreme_condition(self, older_year=None, newer_year=None,\n                                  include_yearly=False, minimum_days=23, attr='WDSP'):\n        # Really need to normalize data with interpolation etc here.\n        # Need to get the data, and process it and score interpolation regimes.\n        # Or could just randomly drop data and try to fill it in.\n        accepted_values = []\n        for year, data in self.parsed_data.items():\n            if not (older_year <= year <= newer_year):\n                continue # Ignore out-of-range years easily\n\n\n\nstations = []\n_latlongs = []\n'''Read in the parsed data into \n1) a list of latitudes and longitudes, temporary, which will get converted to\na numpy array for use in KDTree\n2) a list of IntegratedSurfaceDatabaseStation objects; the query will return\nthe index of the nearest weather stations.\n'''\nwith open(os.path.join(folder, 'isd-history-cleaned.tsv')) as f:\n    for line in f:\n        values = line.split('\\t')\n        for i in range(0, 11):\n            v = values[i]\n            if not v:\n                values[i] = None # '' case\n            else:\n                try:\n                    values[i] = float(v)\n                    if int(v) == 99999:\n                        values[i] = None\n                except:\n                    continue\n        lat, lon = values[6], values[7]\n        if lat and lon:\n            # Some stations have no lat-long; this isn't useful\n            stations.append(IntegratedSurfaceDatabaseStation(*values))\n            _latlongs.append((lat, lon))\n_latlongs = np.array(_latlongs)\nstation_count = len(stations)\n\n\nkd_tree = cKDTree(_latlongs) # _latlongs must be unchanged as data is not copied\n\n\ndef get_closest_station(latitude, longitude, minumum_recent_data=20140000, \n                        match_max=100):\n    '''Query function to find the nearest weather station to a particular \n    set of coordinates. Optionally allows for a recent date by which the \n    station is required to be still active at.\n    \n    Parameters\n    ----------\n    latitude : float\n        Latitude to search for nearby weather stations at, [degrees]\n    longitude : float\n        Longitude to search for nearby weather stations at, [degrees]\n    minumum_recent_data : int, optional\n        Date that the weather station is required to have more recent\n        weather data than; format YYYYMMDD; set this to 0 to not restrict data\n        by date.\n    match_max : int, optional\n        The maximum number of results in the KDTree to search for before \n        applying the filtering criteria; an internal parameter which is\n        increased automatically if the default value is insufficient [-]\n        \n    Returns\n    -------\n    station : IntegratedSurfaceDatabaseStation\n        Instance of IntegratedSurfaceDatabaseStation which was nearest\n        to the requested coordinates and with sufficiently recent data\n        available [-]\n        \n    Notes\n    -----\n    Searching for 100 stations is a reasonable choice as it takes, ~70 \n    microseconds vs 50 microsecond to find only 1 station. The search does get \n    slower as more points are requested. Bad data is returned from a KDTree\n    search if more points are requested than are available.\n    \n    Examples\n    --------\n    >>> get_closest_station(51.02532675, -114.049868485806, 20150000)\n    <Weather station registered in the Integrated Surface Database, name CALGARY INTL CS, country CA, USAF 713930, WBAN None, coords (51.1, -114.0) Weather data from 2004 to 2017>\n    '''\n    # Both station strings may be important\n    # Searching for 100 stations is fine, 70 microseconds vs 50 microsecond for 1\n    # but there's little point for more points, it gets slower.\n    # bad data is returned if k > station_count\n    distances, indexes = kd_tree.query([latitude, longitude], k=min(match_max, station_count)) \n    #\n    for i in indexes:\n        latlon = _latlongs[i]\n        enddate = stations[i].END\n        # Iterate for all indexes until one is found whose date is current\n        if enddate > minumum_recent_data:\n            return stations[i]\n    if match_max < station_count:\n        return get_closest_station(latitude, longitude, minumum_recent_data=minumum_recent_data, match_max=match_max*10)\n    raise Exception('Could not find a station with more recent data than '\n                    'specified near the specified coordinates.')\n\n\n# This should be agressively cached\ndef get_station_year_text(WMO, WBAN, year):\n    '''Basic method to download data from the GSOD database, given a \n    station idenfifier and year. \n\n    Parameters\n    ----------\n    WMO : int or None\n         World Meteorological Organization (WMO) identifiers, [-]\n    WBAN : int or None\n        Weather Bureau Army Navy (WBAN) weather station identifier, [-]\n    year : int\n        Year data should be retrieved from, [year]\n        \n    Returns\n    -------\n    data : str\n        Downloaded data file\n    '''\n    if WMO is None:\n        WMO = 999999\n    if WBAN is None:\n        WBAN = 99999\n    station = str(int(WMO)) + '-' + str(int(WBAN)) \n    gsod_year_dir = os.path.join(data_dir, 'gsod', str(year))\n    path = os.path.join(gsod_year_dir, station + '.op')\n    if os.path.exists(path):\n        data = open(path).read()\n        if data and data != 'Exception':\n            return data\n        else:\n            raise Exception(data)\n        \n    toget = ('ftp://ftp.ncdc.noaa.gov/pub/data/gsod/' + str(year) + '/' \n             + station + '-' + str(year) +'.op.gz')\n    try:\n        data = urlopen(toget, timeout=5)\n    except Exception as e:\n        if not os.path.exists(gsod_year_dir):\n            os.makedirs(gsod_year_dir)\n        open(path, 'w').write('Exception')\n        raise Exception('Could not obtain desired data; check '\n                        'if the year has data published for the '\n                        'specified station and the station was specified '\n                        'in the correct form. The full error is %s' %(e))\n        \n    data = data.read()\n    data_thing = StringIO(data)\n\n    f = gzip.GzipFile(fileobj=data_thing, mode=\"r\")\n    year_station_data = f.read()\n    try: \n        year_station_data = year_station_data.decode('utf-8')\n    except:\n        pass\n    \n    # Cache the data for future use\n    if not os.path.exists(gsod_year_dir):\n        os.makedirs(gsod_year_dir)\n    open(path, 'w').write(year_station_data)\n    \n    \n    return year_station_data\n    \n\n\ngsod_fields = ['DATE', # 15-18 int year; 19-22 int month/day\n               'TEMP', # 25-30 Real Mean temperature for the day in degrees Fahrenheit to tenths. Missing = 9999.9\n               'TEMP_COUNT', # 32-33 Int. Number of observations used in calculating mean temperature\n               'DEWP', # 36-41 Real Mean dew point for the day in degrees Fahrenheit to tenths.  Missing = 9999.9\n               'DEWP_COUNT', # 43-44 Int. Number of observations used in calculating mean dew point\n               'SLP', # 47-52 Real Mean sea level pressure for the day in millibars to tenths.  Missing = 9999.9\n               'SLP_COUNT', # 54-55 Int. Number of observations used in calculating mean sea level pressure\n               'STP', # 58-63 Real Mean station pressure for the day in millibars to tenths. Missing = 9999.9\n               'STP_COUNT', # 65-66 Int. Number of observations used in calculating mean station pressure\n               'VISIB', # 69-73 Real Mean visibility for the day in miles to tenths. Missing = 999.9\n               'VISIB_COUNT', # 75-76 Int. Number of observations used in calculating mean visibility\n               'WDSP', # 79-83 Real Mean wind speed for the day in knots to tenths. Missing = 999.9\n               'WDSP_COUNT', # 85-86 Int. Number of observations used in calculating mean wind speed\n               'MXSPD', # 89-93 Real Maximum sustained wind speed reported for the day in knots to tenths. Missing = 999.9\n               'GUST', # 96-100 Real Maximum wind gust reported for the day in knots to tenths. Missing = 999.9\n               'MAX', # 103-108 Real Maximum temperature reported during the \n                      # day in Fahrenheit to tenths--time of max temp report varies by country and\n                      # region, so this will sometimes not be the max for the calendar day.\n                      # Missing = 9999.9; FLAG of '*' is present on 109-109!\n               'MIN', # 111-116 Real Minimum temperature reported during the day in Fahrenheit to tenths--time of min\n                      # temp report varies by country and region, so this will sometimes not be \n                      # the min for the calendar day. Missing = 9999.9 FLAG of '*' is present on 117-117!\n               'PRCP', # 119-123 Real Total precipitation (rain and/or melted snow) reported during the day in inches\n                       # and hundredths; will usually not end with the midnight observation--i.e.,\n                       # may include latter part of previous day. .00 indicates no measurable\n                       # precipitation (includes a trace).\n                       # Missing = 99.99\n\n               'SNDP', # 126-130 Real Snow depth in inches to tenths--last report for the day if reported more than\n                       # once.  Missing = 999.9 Note: Most stations do not report '0' on days with no snow on the\n                       # ground--therefore, '999.9' will often appear on these days.\n               'FRSHTT' # 133-138 Int. Indicators (1 = yes, 0 = no/not reported) for the occurrence during the day of:\n                        # Fog ('F' - 1st digit).\n                        # Rain or Drizzle ('R' - 2nd digit).\n                        # Snow or Ice Pellets ('S' - 3rd digit).\n                        # Hail ('H' - 4th digit).\n                        # Thunder ('T' - 5th digit).\n                        # Tornado or Funnel Cloud ('T' - 6th digit).              \n              ]\n# Use TEMP and DEWP and STP to calculate wet bulb temperatures\n# Values to be converted to floats always\ngsod_float_fields = ('TEMP', 'DEWP', 'SLP', 'STP', 'VISIB', 'WDSP', 'MXSPD', \n                     'GUST', 'MAX', 'MIN', 'PRCP', 'SNDP')\n# Values to be converted to ints always\ngsod_int_fields = ('TEMP_COUNT', 'DEWP_COUNT', 'SLP_COUNT', 'STP_COUNT', \n                   'VISIB_COUNT', 'WDSP_COUNT')\n\n# Values which signify flags\ngsod_flag_chars = '*ABCDEFGHI'\n# Values which should be converted to None, as normally there is no value\ngsod_bad_values = set(['99.99', '999.9', '9999.9'])\n\ngsod_indicator_names = ['fog', 'rain', 'snow_ice', 'hail', 'thunder', \n                        'tornado']\nfive_ninths = 5.0/9.0\n\ngsod_day = namedtuple('gsod_day', gsod_fields + gsod_indicator_names)\n\n\ndef gsod_day_parser(line, SI=True, to_datetime=True):\n    '''One line (one file) parser of data in the format of the GSOD database.\n    Returns all parsed results as a namedtuple for reduced memory consumption.\n    Will convert all data to base SI units unless the `SI` flag is set to \n    False. As the values are rounded to one or two decimal places in the\n    GSOD database in Imperial units, it may be useful to look at the values\n    directly. \n    \n    The names columns of the columns in the GSOD database are retained and used\n    as the attributes of the namedtuple results.\n    \n    The day, month, and year are normally converted to a datetime instance in\n    resulting namedtuple; this behavior can be disabled by setting the \n    `datetime` flag to False; it will be a string in the format YYYYMMDD if so.\n    This may be useful because datetime conversion roughly doubles the speed of\n    this function.\n    \n    Parameters\n    ----------\n    line : str\n        Line in format of GSOD documentation, [-]\n    SI : bool\n        Whether or not the results get converted to base SI units, [-] \n    to_datetime : bool\n        Whether or not the date gets converted to a datetime instance or stays\n        as a string, [-]\n\n    Returns\n    -------\n    gsod_day_instance : gsod_day\n        namedtuple with fields described in the source (all values in SI units,\n        if `SI` is True, i.e. meters, m/s, Kelvin, Pascal; otherwise the \n        original unit set is used), [-]\n    '''    \n    # Ignore STN--- and WBAN, 8-12 characters\n    fields = line.strip().split()[2:]\n    # For the case the field is blank, set it to None; strip it either way \n    for i in range(len(fields)):\n        field = fields[i].strip()\n        if not field:\n            field = None\n        fields[i] = field \n\n    obj = dict(zip(gsod_fields, fields))\n    # Convert the date to a datetime object if specified\n    if to_datetime and obj['DATE'] is not None:\n        obj['DATE'] = datetime.datetime.strptime(obj['DATE'], '%Y%m%d')\n                \n    # Parse float values as floats\n    for field in gsod_float_fields:\n        value = obj[field].rstrip(gsod_flag_chars)\n        if value in gsod_bad_values:\n            value = None\n        else:\n            value = float(value)\n        obj[field] = value\n        \n    if SI:\n        # All temperatures are in deg F\n        for field in ('TEMP', 'DEWP', 'MAX', 'MIN'):\n            value = obj[field]\n            if value is not None:\n                # F2K inline for efficiency unfortunately\n                obj[field] = (value + 459.67)*five_ninths\n\n        # Convert visibility, wind speed, pressures\n        # to si units of meters, Pascal, and meters/second.\n        if obj['VISIB'] is not None:\n            obj['VISIB'] = obj['VISIB']*mile\n        if obj['PRCP'] is not None:\n            obj['PRCP'] = obj['PRCP']*inch\n        if obj['SNDP'] is not None:\n            obj['SNDP'] = obj['SNDP']*inch\n        if obj['WDSP'] is not None:\n            obj['WDSP'] = obj['WDSP']*knot \n        if obj['MXSPD'] is not None:\n            obj['MXSPD'] = obj['MXSPD']*knot\n        if obj['GUST'] is not None:\n            obj['GUST'] = obj['GUST']*knot\n        if obj['SLP'] is not None:\n            obj['SLP'] = obj['SLP']*100.0\n        if obj['STP'] is not None:\n            obj['STP'] = obj['STP']*100.0\n\n    # Parse int values as ints\n    for field in gsod_int_fields:\n        value = obj[field] \n        if value is not None:\n            obj[field] = int(value)\n\n    indicator_values = [flag == '1' for flag in obj['FRSHTT']]\n    obj.update(zip(gsod_indicator_names, indicator_values))\n    return gsod_day(**obj)\n", "meta": {"hexsha": "346b730e4a3e8673457107c68b11371a8b6b271d", "size": 32051, "ext": "py", "lang": "Python", "max_stars_repo_path": "fluids/design_climate.py", "max_stars_repo_name": "rddaz2013/fluids", "max_stars_repo_head_hexsha": "acde6a6edc2110c152c59341574739b24a2f1bad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fluids/design_climate.py", "max_issues_repo_name": "rddaz2013/fluids", "max_issues_repo_head_hexsha": "acde6a6edc2110c152c59341574739b24a2f1bad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fluids/design_climate.py", "max_forks_repo_name": "rddaz2013/fluids", "max_forks_repo_head_hexsha": "acde6a6edc2110c152c59341574739b24a2f1bad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1437740693, "max_line_length": 239, "alphanum_fraction": 0.6054725282, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.19704265085804076}}
{"text": "from __future__ import print_function\n#\n# Computing the free energy difference of an organic crystal polymorph at different gamma values\n# \n# Copyright Eric Dybeck and Michael R. Shirts, University of Virginia, 2014\n#\n\nimport numpy as np\nimport pymbar  # multistate Bennett acceptance ratio\nfrom pymbar import timeseries  # timeseries analysis\nfrom optparse import OptionParser # for parsing command-line options\nimport sys\nimport panedr\nimport os\n\ndef dA_MBAR(minimum=0, maximum=100, spacing=10, exponent=2, polymorphs='p1 p2', Molecules=72, Independent=4, Temp=200,\n            bonds=False, primary_directory='.', added_directories=[]):\n    # =============================================================================================\n    # Setting up the values for gamma or lambda states\n    # =============================================================================================\n#    raw_value = minimum\n#    values = []\n    directory_names = np.arange(minimum, maximum + spacing, spacing)\n    directory_names = np.sort(np.append(directory_names, added_directories)) \n\n#    while raw_value <= maximum:\n#        if exponent >= 0:\n#            value = int(100 * (float(raw_value) / float(maximum)) ** abs(exponent))\n#        else:\n#            value = int(100 * (1 - (float(maximum - raw_value) / float(maximum)) ** abs(exponent)))\n#        values.append(value)\n#        raw_value = raw_value + spacing\n#    print(values)\n#    print(directory_names)\n#    exit()   \n \n    # POLYMORPH\n    polymorphs = polymorphs.split()\n\n    # =============================================================================================\n    # READ IN RAW DATA\n    # =============================================================================================\n    # Constants.\n    kB = 1.3806488e-23 * 6.0221413e23 / (1000.0 * 4.184)  # Boltzmann constant in kcal/mol\n    \n    # Parameters\n    T_k = Temp * np.ones(len(directory_names), float)  # Convert temperatures to floats\n    print(T_k)\n  #  print(values)\n\n    K = len(directory_names)  # How many states?\n     \n    # total number of states examined; 0 are unsampled if bonds are left on, 1 is unsampled if the bonds are removed\n    Kbig = K\n    \n    # maximum number of snapshots/simulation (could make this automated) - doesn't matter, as long as it's long enough.\n    N_max = 5000\n    \n    # beta factor for the different temperatures\n    beta_k = 1.0 / (kB * T_k)\n    dA = np.zeros([len(polymorphs), Kbig], float)\n    ddA = np.zeros([len(polymorphs), Kbig], float)\n    convert_units = 0.2390057 * np.ones(Kbig, float)  # Convert all energies to kcal/mol\n    \n    # Allocate storage for simulation data\n    for i, poly in enumerate(polymorphs):\n        # N_k[k] is the total number of snapshots from alchemical state k\n        N_k = np.zeros([Kbig], np.int32)\n    \n        # N_k_s[k,s] is the total number of snapshots from alchemical state k from seed s\n        N_k_s = np.zeros([Kbig], np.int32)\n    \n        # u_kln[k,l,n] is the adjusted energy of snapshot n from simulation k\n        u_kln = np.zeros([K, Kbig, N_max], np.float64)\n    \n        # dhdl_kn[k,n] is the derivative of energy with respect to lambda of snapshot n from simulation k\n        dhdl_kn = np.zeros([K, N_max], np.float64)\n    \n        #Load in the data for each run\n        for k in range(K):\n            n = 0\n\n            # cycle through all the input total energy data\n            if directory_names[k] == int(directory_names[k]):\n                dirpath = polymorphs[i] + '/' + primary_directory + '/' + str(int(directory_names[k]))\n            else:\n                dirpath = polymorphs[i] + '/' + primary_directory + '/' + str(directory_names[k])\n            if os.path.isdir(dirpath):\n                fname = dirpath + '/PROD.edr'\n                dhdlname = dirpath + '/dhdl_PROD.xvg'\n\n                potential_energy = panedr.edr_to_df(fname)['Potential'].values\n                print(\"loading \" + fname)\n\n                dhdl_energy = np.loadtxt(dhdlname, comments=['#', '$', '@', '!'])\n                print(\"loading \" + dhdlname)\n\n                # Removing any non-equilibrated points of the simulation\n                [start_production, _, _] = timeseries.detectEquilibration(potential_energy)\n                potential_energy = potential_energy[start_production:]\n                dhdl_energy = dhdl_energy[start_production:,:]\n\n                # Cutting points if they exceed N_max\n                if len(potential_energy) > N_max:\n                    potential_energy = potential_energy[len(potential_energy) - N_max:]\n                    dhdl_energy = dhdl_energy[len(dhdl_energy) - N_max:,:]\n\n                # the energy of every configuration from each state evaluated at its sampled state\n                n = len(potential_energy)\n                dhdl_placement = len(dhdl_energy[0, :]) - K\n                u_kln[k, :K, :n] = (potential_energy.reshape((n, 1)) + dhdl_energy[:, dhdl_placement:]).T * convert_units[k]\n                dhdl_kn[k, :n] = (float(Independent) / Molecules) * \\\n                                 np.sum(dhdl_energy[:, 2:dhdl_placement], axis=1) * convert_units[k]\n\n                N_k_s[k] = n\n                N_k[k] = n\n\n        # convert to nondimensional units from kcal/mol\n        u_kln *= beta_k[0]\n    \n        #u_kln_save = u_kln.copy()\n        u_kln_save = u_kln[:]\n        g_k = np.zeros([K])\n\n        print(\"Number of retained samples\")\n        print(N_k)\n        print(\"Number of retained samples from each seed\")\n        print(N_k_s)\n\n        # =============================================================================================\n        # COMPUTE FREE ENERGY DIFFERENCE USING MBAR\n        # =============================================================================================\n        \n        # Initialize MBAR.\n        print(\"Running MBAR...\")\n    \n        # generate the weights of each of the umbrella set\n        mbar = pymbar.MBAR(u_kln, N_k, verbose=True, subsampling_protocol=[{'method': 'L-BFGS-B'}])\n    \n        print(\"MBAR Converged...\")\n        # testing\n        \n        for k in range(Kbig):\n            w = np.exp(mbar.Log_W_nk[:, k])\n            print(\"max weight in state %d is %12.7f\" % (k, np.max(w)))\n            neff = 1 / np.sum(w ** 2)\n            print(\"Effective number of sample in state %d is %10.3f\" % (k, neff))\n            print(\"Efficiency for state %d is %d/%d = %10.4f\" % (k, neff, len(w), neff / len(w)))\n    \n        # extract self-consistent weights and uncertainties\n        (df_i, ddf_i, theta_i) = mbar.getFreeEnergyDifferences()\n \n        print(\"Free Energies Optained...\")\n    \n        # convert PMF to kcal/mol and normalize by the number of molecules\n        df_i /= (beta_k[0] * float(Independent))\n        ddf_i /= (beta_k[0] * float(Independent))\n    \n        dA[i, :] = df_i[-1]\n\n        # =============================================================================================\n        # COMPUTE UNCERTAINTY USING THE UNCORRELATED DATA\n        # =============================================================================================\n        \n        for k in range(K):\n            N_k[k] = 0\n            n_old = 0\n\n            g_k[k] = timeseries.statisticalInefficiency(dhdl_kn[k, n_old: (n_old + N_k_s[k])])\n            print(\"Correlation time for sampled state %d is %10.3f\" % (k, g_k[k]))\n            # subsample the data to get statistically uncorrelated data\n            indices = np.array(timeseries.subsampleCorrelatedData(u_kln[k, k, n_old:(n_old + N_k_s[k])],\n                                                                          g=g_k[k]))  # subsample\n    \n            # not sure why we have to transpose\n            if indices != []:\n                u_kln[k, :, N_k[k]: (N_k[k] + len(indices))] = u_kln_save[k, :, (indices + n_old)].transpose()\n                N_k[k] = N_k[k] + len(indices)\n                n_old += N_k_s[k]\n\n        print(\"Number of retained samples\")\n        print(N_k)\n        print(\"Number of retained samples from each seed\")\n        print(N_k_s)\n    \n        # generate the weights of each of the umbrella set\n        mbar = pymbar.MBAR(u_kln, N_k, verbose=True, subsampling_protocol=[{'method': 'L-BFGS-B'}])\n    \n        print(\"MBAR Converged...\")\n    \n        # extract self-consistent weights and uncertainties\n        try:\n            (df_u, ddf_u, theta_i) = mbar.getFreeEnergyDifferences()\n        except ValueError:\n            pass\n    \n        print(\"Free Energies Optained...\")\n    \n        # convert PMF to kcal/mol and normalize by the number of molecules\n        df_u /= (beta_k[0] * float(Independent))\n        ddf_u /= (beta_k[0] * float(Independent))\n    \n        ddA[i, :] = ddf_u[-1]\n#        ddA[i, :] = ddf_i[-1]\n        \n        # Write out free energy differences\n        print(\"Free Energy Difference (in units of kcal/mol)\")\n        print(\"  dA(Gamma) = A(Gamma) - A(Interactions Off)\")\n        for k in range(Kbig):\n            print(\"%8.3f %8.3f\" % (df_i[k, -1], ddf_u[k, -1]))\n\n        del N_k\n        del N_k_s\n        del u_kln\n        del dhdl_kn\n\n    out_dA = np.zeros(len(polymorphs))\n    out_ddA = np.zeros(len(polymorphs))\n    for i, poly in enumerate(polymorphs):\n        out_dA[i] = dA[i, 0]\n        out_ddA[i] = ddA[i, 0]\n\n    return out_dA, out_ddA\n\n", "meta": {"hexsha": "eae4c33673463f4203a7a6309a84f593cc1f9faf", "size": 9297, "ext": "py", "lang": "Python", "max_stars_repo_path": "PSCP/analysis-scripts/dA_MBAR.py", "max_stars_repo_name": "shirtsgroup/finite-temperature-crystal-scripts", "max_stars_repo_head_hexsha": "799bc882d958d9afa264a168dae0b3051bafaf0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PSCP/analysis-scripts/dA_MBAR.py", "max_issues_repo_name": "shirtsgroup/finite-temperature-crystal-scripts", "max_issues_repo_head_hexsha": "799bc882d958d9afa264a168dae0b3051bafaf0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2017-07-25T04:59:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-25T22:48:53.000Z", "max_forks_repo_path": "PSCP/analysis-scripts/dA_MBAR.py", "max_forks_repo_name": "shirtsgroup/finite-temperature-crystal-scripts", "max_forks_repo_head_hexsha": "799bc882d958d9afa264a168dae0b3051bafaf0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-04T07:01:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T07:01:25.000Z", "avg_line_length": 41.32, "max_line_length": 124, "alphanum_fraction": 0.531676885, "include": true, "reason": "import numpy", "num_tokens": 2263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.19703608614449927}}
{"text": "# This file is part of LayerModel_lib\n#\n#     A tool to compute the transmission behaviour of plane electromagnetic waves\n#     through human tissue.\n#\n# Copyright (C) 2018 Jan-Christoph Brumm\n#\n# Licensed under MIT license.\n#\nimport numpy as np\nimport os\nfrom scipy import ndimage\n\nfrom LayerModel_lib import VoxelModel, VoxelModelImporter, Coordinate, TissueProperties\n\ncurrent_directory = os.path.dirname(__file__)\nbase_path = os.path.join(current_directory, '..', '..', '..', '..', '..', 'Numerical Human Phantoms', 'Golem')\n\n# path to the AVW File of this model\nfilename = os.path.join(base_path, 'segm_golem')\n# path to the tissue_mapping file\ntissue_file = os.path.join('ImportGolem_tissues.txt')\n\nAVW_Data = VoxelModelImporter(filename, tissue_file, 'AVW')\nmodel_orig = AVW_Data.data['image']\ntissue_name_orig = AVW_Data.tissue_names\ntissue_mapping = AVW_Data.tissue_mapping\n\nGolem = VoxelModel()\nGolem.show_progress_bar = True\n\n# needs to be set manually from README.txt\nGolem.set_scale(2.08, 2.08, 8)\n\nGolem.name = 'Golem'\nGolem.description = 'Golem model from the Helmholtz Zentrum München. ' \\\n                    'Resolution %.2fmm x %.2fmm x %.2fmm' % (Golem.scaling.x,\n                                                             Golem.scaling.y, Golem.scaling.z)\n\n# Golem is upside down and left right in wrong direction\nmodel_orig = np.flip(model_orig, axis=0)\nmodel_orig = np.flip(model_orig, axis=2)\n# The space around the model is too much\nmodel_orig = model_orig[0:166, :, :]\n\n#  Calculate the outer_shape of the original and the complete model\nouter_shape = AVW_Data.calculate_outer_shape(model_orig, tissue_mapping)\n\nGolem.add_voxel_data(short_name='original',\n                     name='Original data from AVW file',\n                     model=model_orig,\n                     outer_shape=outer_shape,\n                     tissue_names=tissue_name_orig)\n\nGolem.add_voxel_data(short_name='complete',\n                     name='The \\'original\\' model converted to our TissueProperties.',\n                     model=Golem.models['original'].data,\n                     outer_shape=outer_shape,\n                     tissue_mapping=tissue_mapping)\n\n# Calculate the trunk model\nstart_slice = int(110)\nend_slice = int(175)\n\n(model_trunk, trunk_mask) = AVW_Data.calculate_trunk_model(Golem, 'complete', z_start=start_slice, z_end=end_slice)\nouter_shape_trunk = AVW_Data.calculate_outer_shape(model_trunk)\n\n# label the inner parts of the small intestine as GIcontents. For that erode the small intestine in\n# 3D and replace the resulting voxels with GIcontents.\ntp = TissueProperties()\n\ntrunk = model_trunk\n\n# Golem has no labeled SmallIntestineContents. Therefore, we need to label that by ourself:\n# select only the small intenstine\ntrunk_si = trunk == tp.get_tissue_id_for_name(['SmallIntestine'])\nstruct = ndimage.generate_binary_structure(3, 1)\n# Erode the small intestine wall:\ntrunk_si_eroded = ndimage.binary_erosion(trunk_si, structure=struct, iterations=1)\ntrunk_si_out = np.copy(trunk)\n# replace remaining inner small intestine with GIcontents\ntrunk_si_out[trunk_si_eroded] = tp.get_tissue_id_for_name(['GIcontents'])\n\nmodel_trunk = trunk_si_out\n\nGolem.add_voxel_data(short_name='trunk',\n                     name=\"The trunk of the 'complete' model. Arms have been removed using \"\n                          \"VoxelModel.remove_arms().\",\n                     outer_shape=outer_shape_trunk,\n                     model=model_trunk,\n                     mask=trunk_mask,\n                     tissue_mapping=None)\n\nsurface = Golem.create_3d_model(model_type='trunk', patch_size=(30, 30))\nGolem.models['trunk'].surface_3d = surface\n\nGolem.models['trunk'].endpoints = []\nfor (i, s) in enumerate(surface):\n    Golem.models['trunk'].endpoints.append(Coordinate(np.array(s['centroid'])))\n\nGolem.save_model()\n", "meta": {"hexsha": "8a885302c0d4d342f15954825c585a0284b4ecf8", "size": 3822, "ext": "py", "lang": "Python", "max_stars_repo_path": "phantom_import/ImportGolem.py", "max_stars_repo_name": "janbrumm/layermodel_lib", "max_stars_repo_head_hexsha": "0d5e0c9ac77d302910823ebc757a4ec99541f3ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "phantom_import/ImportGolem.py", "max_issues_repo_name": "janbrumm/layermodel_lib", "max_issues_repo_head_hexsha": "0d5e0c9ac77d302910823ebc757a4ec99541f3ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phantom_import/ImportGolem.py", "max_forks_repo_name": "janbrumm/layermodel_lib", "max_forks_repo_head_hexsha": "0d5e0c9ac77d302910823ebc757a4ec99541f3ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4705882353, "max_line_length": 115, "alphanum_fraction": 0.7006802721, "include": true, "reason": "import numpy,from scipy", "num_tokens": 927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.19703608131630407}}
{"text": "#!/usr/bin/env python\n\n\"\"\"\nshort script to transform remodnav\n(https://github.com/psychoinformatics-de/remodnav) outputs from naturalistic\nstimulation with hollywood movie forrest gump into fixation vectors\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom bisect import bisect_right\nimport os.path as op\n\n\ndef pursuits_to_fixations(npdata):\n    \"\"\"this function takes a numpy record array from Asims eye-event detection\n    algorithm. Start and end points of pursuits are transformed into a fixation,\n    the pursuit movement can then be simplified as a saccade. The function\n    returns a recordarray\"\"\"\n    # initialize empty rec array of the same shape\n    newdata = np.recarray((0,), dtype=[('onset', '<f8'),\n                                       ('duration', '<f8'),\n                                       ('label', '<U10'),\n                                       ('start_x', '<f8'),\n                                       ('start_y', '<f8'),\n                                       ('end_x', '<f8'),\n                                       ('end_y', '<f8'),\n                                       ('amp', '<f8'),\n                                       ('peak_vel', '<f8'),\n                                       ('med_vel', '<f8'),\n                                       ('avg_vel', '<f8')])\n    # reassemble rec array. split pursuits to use end and start as fixations later\n    for i in range(0, len(npdata)):\n        if npdata[i]['label'] == 'PURS':\n            row_1 = npdata[i]\n            row_1['duration'] = npdata[i]['duration'] / 2\n            row_2 = row_1.copy()\n            row_2['onset'] += row_2['duration']\n            row_2['start_x'] = row_2['end_x']\n            row_2['start_y'] = row_2['end_y']\n            newdata = np.append(newdata, row_1)\n            newdata = np.append(newdata, row_2)\n        else:\n            newdata = np.append(newdata, npdata[i])\n    return newdata\n\n\ndef preprocess(data, sz=[1280, 720]):\n    \"\"\"\n    data = n x 11 rec array\n    sz = screen measurements\n    preprocesses a recordarray with eye events (from pursuits_to_fixations()\n    function. Assumes the datafile is sorted by time. Will filter to include\n    only Fixations and Pursuits-start/end-points, will check for out-of-bound\n    gazes.\n    Returns clean Fixation data with onset, start_x, start_y and duration \"\"\"\n    # only fixations and pursuits\n    Filterevents = data[np.logical_or(data['label'] == 'FIXA',\n                                      data['label'] == 'PURS')]\n    # within x coordinates?\n    Filterxbounds = Filterevents[np.logical_and(Filterevents['start_x'] >= 0,\n                                                Filterevents['start_x'] <= sz[0])]\n    # within y coordinates?\n    Filterybounds = Filterxbounds[np.logical_and(Filterxbounds['start_y'] >= 0,\n                                                 Filterxbounds['end_y'] <= sz[1])]\n    # give me onset times, start_x, start_y and duration\n    fixations = Filterybounds[[\"onset\", \"start_x\", \"start_y\",\n                               \"duration\"]]\n    return fixations\n\n\ndef takeClosestright(myList, myNumber):\n    \"\"\"return the integer closest to 'myNumber' in an ordered list.(shamelessly\n    stolen from\n    https://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-\n    closest-to-a-given-value)\n    \"\"\"\n    pos = bisect_right(myList, myNumber)\n    if pos == 0:\n        return myList[0]\n    if pos == len(myList):\n        return myList[-1]\n    after = myList[pos]\n    return after\n\n\ndef createOnsets(data, dur):\n    \"\"\"create onset times of all shots of 'dur' seconds of length\n    data = dataframe, should be location annotation\n    dur = duration in seconds\"\"\"\n    onsets = []\n    for index, row in data.iterrows():\n        if row['duration'] >= dur:\n            onsets.append(row['onset'])\n    return onsets\n\n\ndef createChunks(onsets, fixations, dur):\n    \"\"\"Create and return start and end indices to chunk eye movement data into\n    segments to compare scanpaths across.\n    onsets = output from CreateOnsets()\n    fixations = output from preprocess(). n x 4 np record array\n    dur = durations of segments in seconds\"\"\"\n    # initialize empty lists\n    startidx, endidx = [], []\n    for shotonset in onsets:\n        start = takeClosestright(fixations['onset'], shotonset)\n        startidx.append(np.where(fixations['onset'] == start)[0].tolist())\n        end = takeClosestright(fixations['onset'], shotonset + dur)\n        endidx.append(np.where(fixations['onset'] == end)[0].tolist())\n    # flatten the nested lists\n    startidx = [element for sublist in startidx for element in sublist]\n    endidx = [element for sublist in endidx for element in sublist]\n    return startidx, endidx\n\n\ndef FixationsChunks(fixations, startid, endid):\n    \"\"\"Chunk eye movement data into segments of approximate length to compute\n    scanpath similarities. Output is returned as a n x 3 fixation vector.\n    startid, endid = output from createChunks\n    fixations = output from preprocess\"\"\"\n    fixation_vector = []\n    # slice fixation data according to indices, take columns start_x, start_y and\n    # duration\n    for idx in range(0, len(startid)):\n        ind = fixations[startid[idx]:endid[idx]][[\"start_x\", \"start_y\", \"duration\"]]\n        fixation_vector.append(ind)\n    return fixation_vector\n\n\ndef longshot(shots, dur):\n    \"\"\"group movie shots without a cut together to obtain longer movie\n    segments. This way, fewer but longer scanpaths are obtained. Example: use\n    median shotlength of 4.92s.\n    shots = dataframe, contains movie location annotation\n    dur = length in seconds for movie shot\n    \"\"\"\n    # turn pandas dataframe shots into record array\n    structshots = shots.to_records()\n    i = 0\n    while i < len(structshots):\n        # break before running into index error\n        if structshots[i] == structshots[-1]:\n            break\n        else:\n            if (structshots[i]['duration'] < dur) & \\\n                    (structshots[i + 1]['duration'] < dur) & \\\n                    (structshots[i]['locale'] == structshots[i + 1]['locale']):\n                # add durations together and delete second row\n                structshots[i]['duration'] += structshots[i + 1]['duration']\n                structshots = np.delete(structshots, i + 1, 0)\n            else:\n                i += 1\n    aggregated = pd.DataFrame({'onset': structshots['onset'].tolist(),\n                               'duration': structshots['duration'].tolist()}, columns=['onset',\n                                                                                       'duration'])\n    return aggregated\n\n\ndef savefile(fixation_vector, output, header):\n    newheader = ''.join([w + '\\t' for w in header]).strip()\n    np.savetxt(output, fixation_vector, delimiter='\\t', comments='', header=newheader)\n\n\ndef run(data1, shots, sz, dur, subname):\n    newdata1 = pursuits_to_fixations(data1)\n    fixations1 = preprocess(newdata1, sz)\n    shots = longshot(shots, dur)\n    onset = createOnsets(shots, dur)\n    startid1, endid1 = createChunks(onset, fixations1, dur)\n    fixation_vectors1 = FixationsChunks(fixations1, startid1, endid1)\n    header = fixation_vectors1[0].dtype.names\n    for i in range(0, len(onset)):\n        output = args.output + '/fixvectors/segment_' + str(i) + '_' + subname + '.tsv'\n        print('saving file', i, 'into', output)\n        savefile(fixation_vectors1[i], output, header)\n\n\nif __name__ == '__main__':\n    import argparse\n\n    parser = argparse.ArgumentParser()\n    # define arguments\n    parser.add_argument('-i', '--input1', nargs='+', help='Input: eyemovement data of one subject', metavar='PATH',\n                        required=True)\n    parser.add_argument('-o', '--output', help='Output: Specify path where output should be saved', metavar='PATH',\n                        required=True)\n    parser.add_argument('-sz', '--screensize',\n                        help='Screensize: what are the dimensions of the screen the stimulus was displayed on in px, e.g. [1280, 720]',\n                        default=[1280, 720])\n    parser.add_argument('-s', '--shots', help='Input3: location annotation of the movie segment', metavar='PATH',\n                        required=True)\n    parser.add_argument('-d', '--duration',\n                        help='approximate duration of video segments to derive fixation vectors from', default=5.0)\n    args = parser.parse_args()\n\n\n    data1 = np.recfromcsv(args.input1[0],\n                          delimiter='\\t',\n                          dtype={'names': ('onset', 'duration', 'label', 'start_x', 'start_y',\n                                           'end_x', 'end_y', 'amp', 'peak_vel', 'med_vel', 'avg_vel'),\n                                 'formats': ('f8', 'f8', 'U10', 'f8', 'f8', 'f8', 'f8', 'f8', 'f8',\n                                             'f8', 'f8')})\n    shots = pd.read_csv(args.shots, sep='\\t')\n\n    subname = op.basename(args.input1[0]).split('_')[0]\n\n    if args.screensize:\n        sz = args.screensize\n    else:\n        sz = [1280, 720]\n\n    if args.duration:\n        dur = float(args.duration)\n    else:\n        dur = 5.0\n\n    # run everything\n    run(data1, shots, sz, dur, subname)\n", "meta": {"hexsha": "ff8397edcc057f1ccf02cecc761f946aace0da64", "size": 9174, "ext": "py", "lang": "Python", "max_stars_repo_path": "data/code/create_videodata.py", "max_stars_repo_name": "kyleniemeyer/multimatch_gaze", "max_stars_repo_head_hexsha": "fd022cf90f0690c0d334d3a2ed1d77dd2cf6db7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2019-06-25T06:12:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T14:56:39.000Z", "max_issues_repo_path": "data/code/create_videodata.py", "max_issues_repo_name": "kyleniemeyer/multimatch_gaze", "max_issues_repo_head_hexsha": "fd022cf90f0690c0d334d3a2ed1d77dd2cf6db7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2019-05-01T12:24:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-26T11:21:20.000Z", "max_forks_repo_path": "data/code/create_videodata.py", "max_forks_repo_name": "AdinaWagner/MultiMatch", "max_forks_repo_head_hexsha": "36fd53076b8e95897ed2e8650ecaa9d9c4de9bc0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-07-18T13:12:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-21T07:35:44.000Z", "avg_line_length": 41.7, "max_line_length": 135, "alphanum_fraction": 0.5808807499, "include": true, "reason": "import numpy", "num_tokens": 2161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.32423541204073586, "lm_q1q2_score": 0.1970259228602175}}
{"text": "\"\"\"Automatic differentiation filter-error method estimation models.\"\"\"\n\n\nimport collections\nimport functools\nimport inspect\nimport itertools\n\nimport jax\nfrom jax import numpy as jnp\nfrom jax import scipy as jscipy\n\nimport numpy as onp\n\n\n### Enable 64-bit in jax ###\njax.config.update(\"jax_enable_x64\", True)\n\n\nclass BoundADFunction:\n    def __init__(self, adfun, model):\n        self.adfun = adfun\n        self.model = model\n    \n    @property\n    def __signature__(self):\n        return bound_signature(self.adfun)\n    \n    @property\n    def __name__(self):\n        return self.adfun.__name__\n    \n    def __repr__(self):\n        cls = type(self)\n        name = getattr(self, '__name__', '*no name*')\n        return f\"<{cls.__module__}.{cls.__name__} '{name}'>\"\n    \n    def __call__(self, *args, **kwargs):\n        return self.adfun(self.model, *args, **kwargs)\n    \n    def hess_filter(self, dec_shapes=None, out_shape=None):\n        filt_name = f'_{self.__name__}_hess_filter'\n        try:\n            return getattr(self.model, filt_name)\n        except AttributeError:\n            assert dec_shapes is not None\n            assert out_shape is not None\n            \n            hess_filter = {}\n            adfun = self.adfun\n            wrt_seq = adfun.hessian\n            ind_base = adfun._sparse_deriv_ind(wrt_seq, dec_shapes, out_shape)\n            for wrt, ind in ind_base.items():\n                if len(wrt) == 2 and wrt[0] == wrt[1]:\n                    hess_filter[wrt] = ind[0] > ind[1]\n            setattr(self.model, filt_name, hess_filter)\n            return hess_filter\n    \n    def hess_nnz(self, dec_shapes, out_shape):\n        adfun = self.adfun\n        wrt_seq = adfun.hessian\n        filter = self.hess_filter(dec_shapes, out_shape)\n        return adfun._sparse_deriv_nnz(wrt_seq, dec_shapes, out_shape, filter)\n    \n    def hess_ind(self, dec_shapes, out_shape):\n        adfun = self.adfun\n        wrt_seq = adfun.hessian\n        filter = self.hess_filter(dec_shapes, out_shape)\n        return adfun._sparse_deriv_ind(wrt_seq, dec_shapes, out_shape, filter)\n\n    def hess_val(self, *args, **kwargs):\n        adfun = self.adfun\n        model = self.model\n        wrt_seq = adfun.hessian\n        \n        # The filter must be built by a previous call to hess_ind or hess_nnz\n        filter = self.hess_filter()\n        \n        return adfun._sparse_deriv_val(wrt_seq, model, args, kwargs, filter)\n\n\nclass BoundADConstraint(BoundADFunction):\n    def jac_nnz(self, dec_shapes, out_shape):\n        adfun = self.adfun\n        d1 = adfun.first_derivatives\n        return adfun._sparse_deriv_nnz(d1, dec_shapes, out_shape)\n    \n    def jac_ind(self, dec_shapes, out_shape):\n        adfun = self.adfun\n        d1 = adfun.first_derivatives\n        return adfun._sparse_deriv_ind(d1, dec_shapes, out_shape)\n\n    def jac_val(self, *args, **kwargs):\n        adfun = self.adfun\n        d1 = adfun.first_derivatives\n        return adfun._sparse_deriv_val(d1, args, kwargs)\n\n\nclass BoundADObjective(BoundADFunction):\n    def grad(self, *args, **kwargs):\n        adfun = self.adfun\n        ret = collections.OrderedDict()\n        for wrt in adfun.first_derivatives:\n            # Calculate the gradient\n            grad_fun = adfun.derivatives[wrt,]\n            grad_val = grad_fun(self.model, *args, **kwargs)\n            \n            # skip empty gradients\n            if not grad_val.size:\n                continue\n            \n            # Get the shape of the wrt argument\n            try:\n                wrt_shape = onp.shape(kwargs[wrt])\n            except KeyError:\n                wrt_shape = onp.shape(args[adfun.argnum(wrt) - 1])\n            \n            # Accumulate so the gradient has the same shape as the variable\n            ret[wrt] = grad_val.reshape(-1, *wrt_shape).sum(0)\n        return ret\n\n\nclass ADFunction:\n    \"\"\"Helper for optimization function automatic differentiation.\"\"\"\n\n    BoundClass = BoundADFunction\n    \n    def __init__(self, fun, core_shape=''):\n        self.fun = fun\n        \"\"\"Underlying function.\"\"\"\n        \n        self.core_shape = core_shape\n        \"\"\"The shape of the output of the elementary function, if vectorized.\"\"\"\n        \n        self.hessian = None\n        \"\"\"Hessian elements.\"\"\"\n        \n        self.__signature__ = inspect.signature(self.fun)\n        \"\"\"The underlying function's signature.\"\"\"\n        \n        self.args = list(self.__signature__.parameters)\n        \"\"\"The underlying function argument names.\"\"\"\n        \n        self.derivatives = {}\n        \"\"\"Dictionary of function derivatives.\"\"\"\n\n        self.first_derivatives = []\n        \"\"\"Sequence of registered first derivatives.\"\"\"\n        \n        self.isvectorized = False\n        \"\"\"Whether the function is vectorized\"\"\"\n    \n    def __call__(self, *args, **kwargs):\n        return self.fun(*args, **kwargs)\n\n    def __get__(self, instance, owner=None):\n        if instance is None:\n            return self\n        else:\n            return self.BoundClass(self, instance)\n\n    def __set_name__(self, owner, name):\n        self.__name__ = name\n    \n    def __repr__(self):\n        cls = type(self)\n        name = getattr(self, '__name__', '*no name*')\n        return f\"<{cls.__module__}.{cls.__name__} '{name}'>\"\n    \n    def argnum(self, argname):\n        return self.args.index(argname)\n    \n    def derivative(self, wrt):\n        if isinstance(wrt, str):\n            wrt_tuple = wrt,\n            return self.derivative(wrt_tuple)\n        \n        # Trivial case, i.e., 0-th derivative\n        if wrt == ():\n            return self.fun\n        \n        # Return the registered derivative, if it exists\n        try:\n            return self.derivatives[wrt]\n        except KeyError:\n            pass\n        \n        # Compute the derivative\n        assert len(wrt) >= 1\n        fun = self.derivative(wrt[1:])\n        argnum = self.argnum(wrt[0])\n        deriv = jax.jacrev(fun, argnum)\n        \n        # Save it and return\n        self.derivatives[wrt] = deriv\n        return deriv\n    \n    def prepare_derivatives(self, decision):\n        # Compute and save the first derivatives\n        for d in self.args:\n            if d in decision:\n                self.derivative(d)\n                self.first_derivatives.append(d)\n        \n        # Define default Hessian, if unset\n        if self.hessian is None:\n            first_deriv = self.first_derivatives\n            hess_gen = itertools.combinations_with_replacement(first_deriv, 2)\n            self.hessian = list(hess_gen)\n        \n        # Compute second derivatives\n        for wrt_pair in self.hessian:\n            self.derivative(wrt_pair)\n    \n    def vectorize(self, vectorized):\n        vec_args = [a for a in self.args if a in vectorized]\n        excluded = [i for i,a in enumerate(self.args) if a not in vectorized]\n        \n        if not vec_args:\n            return\n        \n        arg_sig = \",\".join(f'({vectorized[a]})' for a in vec_args)\n        sig = f\"{arg_sig}->({self.core_shape})\"\n        \n        self.fun = jnp.vectorize(self.fun, excluded=excluded, signature=sig)\n        for wrt, d in self.derivatives.items():\n            wrtsig = (vectorized[var] for var in reversed(wrt))\n            if self.core_shape:\n                outsig = ','.join((self.core_shape, *wrtsig))\n            else:\n                outsig = ','.join(wrtsig)\n            dsig = f\"{arg_sig}->({outsig})\"\n            vecd = jnp.vectorize(d, excluded=excluded, signature=dsig)\n            self.derivatives[wrt] = vecd\n        \n        core_shape = self.core_shape\n        out_core_ndim = len(core_shape.split(',')) if core_shape else 0\n        self.core_ndim = {a: len(vectorized[a].split(',')) for a in vec_args}\n        self.core_ndim[None] = out_core_ndim\n        self.isvectorized = True\n    \n    def _split_shape(self, shape, varname=None):\n        \"\"\"Split a variable's shape into extension and core.\"\"\"\n        try:\n            core_ndim = self.core_ndim[varname]\n        except KeyError:\n            return (), shape #This variable is not vectorized\n        \n        # Test whether the core element is scalar (ndim==0)\n        if core_ndim:\n            return shape[:-core_ndim], shape[-core_ndim:]\n        else:\n            return shape, ()        \n    \n    def _ext_shape(self, shape, varname=None):\n        \"\"\"Return a variable's shape extension.\"\"\"\n        return self._split_shape(shape, varname)[0]\n    \n    def _core_shape(self, shape, varname=None):\n        \"\"\"Return a variable's core shape.\"\"\"\n        return self._split_shape(shape, varname)[1]\n        \n    def _deriv_core_shape(self, wrt, dec_shapes, out_shape):\n        out_ext, out_core = self._split_shape(out_shape)\n        if len(wrt) == 0:\n            return out_core\n        else:\n            wrt0, *wrt_rem = wrt\n            wrt0_shape = dec_shapes[wrt0]\n            wrt0_ext, wrt0_core = self._split_shape(wrt0_shape, wrt0)\n            rem_core = self._deriv_core_shape(wrt_rem, dec_shapes, out_shape)\n            return rem_core + wrt0_core\n    \n    def _deriv_core_ind(self, wrt, dec_shapes, out_shape):\n        if len(wrt) == 0:\n            out_ext, out_core = self._split_shape(out_shape)\n            return [onp.arange(shape_size(out_core))]\n        else:\n            wrt0, *wrt_rem = wrt\n            wrt0_shape = dec_shapes[wrt0]\n            wrt0_ext, wrt0_core = self._split_shape(wrt0_shape, wrt0)\n            rem_ind = self._deriv_core_ind(wrt_rem, dec_shapes, out_shape)\n            \n            wrt0_core_size = shape_size(wrt0_core)\n            wrt0_tile = rem_ind[0].size\n            wrt0_ind = onp.tile(onp.arange(wrt0_core_size), wrt0_tile)\n            core_ind = [onp.repeat(i, wrt0_core_size) for i in rem_ind]\n            core_ind.insert(0, wrt0_ind)\n            return core_ind\n    \n    def _sparse_deriv_nnz(self, wrt_seq, dec_shapes, out_shape, filter={}):\n        nnz = 0\n        out_ext, out_core = self._split_shape(out_shape)\n        ext_sz = shape_size(out_ext)\n        for wrt in wrt_seq:\n            if wrt in filter:\n                nnz += filter[wrt].sum()\n            else:\n                deriv_core = self._deriv_core_shape(wrt, dec_shapes, out_shape)\n                nnz += shape_size(deriv_core) * ext_sz\n        return nnz\n    \n    def _sparse_deriv_ind(self, wrt_seq, dec_shapes, out_shape, filter={}):\n        out_ext, out_core = self._split_shape(out_shape)\n        core_out_sz = shape_size(out_core)\n        \n        ret = collections.OrderedDict()\n        for wrt in wrt_seq:\n            ind = []\n            base_ind = self._deriv_core_ind(wrt, dec_shapes, out_shape)\n            for wrt_name, wrt_ind in zip(wrt, base_ind):\n                wrt_shape = dec_shapes[wrt_name]\n                wrt_ext, wrt_core = self._split_shape(wrt_shape, wrt_name)\n                wrt_core_sz = shape_size(wrt_core)\n                \n                wrt_offs = ndim_range(wrt_ext) * wrt_core_sz\n                wrt_offs = onp.broadcast_to(wrt_offs, out_ext)\n                ind.append((wrt_ind + wrt_offs[..., None]).ravel())\n            \n            # Extend the output indices\n            out_ind = base_ind[-1]\n            out_offs = ndim_range(out_ext) * core_out_sz\n            ind.append((out_ind + out_offs[..., None]).ravel())\n            \n            # Save in dictionary\n            selected = filter.get(wrt, slice(None))\n            ret[wrt] = onp.array(ind)[:, selected]\n        return ret\n    \n    def _sparse_deriv_val(self, wrt_seq, args, kwargs, filter={}):\n        ret = collections.OrderedDict()\n        for wrt in wrt_seq:\n            deriv = self.derivatives[wrt]\n            selected = filter.get(wrt, slice(None))\n            ret[wrt] = deriv(*args, **kwargs).ravel()[selected]\n        return ret\n\n\nclass ADConstraint(ADFunction):\n    \"\"\"Helper for constraint function automatic differentiation.\"\"\"\n\n    BoundClass = BoundADConstraint\n    \n\nclass ADObjective(ADFunction):\n    \"\"\"Helper for objective function automatic differentiation.\"\"\"\n\n    BoundClass = BoundADObjective\n\n\ndef constraint(core_shape_or_fun=None):\n    if callable(core_shape_or_fun):\n        fun = core_shape_or_fun\n        return constraint()(fun)\n    else:\n        core_shape = core_shape_or_fun\n        def decorator(fun):\n            return ADConstraint(fun, core_shape)\n        return decorator\n\n\ndef objective(fun):\n    return ADObjective(fun)\n\n\ndef hessian(*args):\n    def decorator(obj):\n        obj.hessian = args\n        return obj\n    return decorator\n\n\nclass ADModel:\n    def __init_subclass__(cls):\n        base_dec = getattr(super(), 'decision', set())\n        cls_dec = getattr(cls, 'decision', set())  \n        cls.decision = set.union(base_dec, cls_dec)\n        \"\"\"The decision variables of this model.\"\"\"\n        \n        base_vec = getattr(super(), 'vectorized', {})\n        cls_vec = getattr(cls, 'vectorized', {})  \n        cls.vectorized = {**base_vec, **cls_vec}\n        \"\"\"The core shape of vectorized variables.\"\"\"\n        \n        cls_items = cls.__dict__.items()\n        adfuns = {k:v for k,v in cls_items if isinstance(v, ADFunction)}\n        for name, adfun in adfuns.items():\n            adfun.prepare_derivatives(cls.decision)\n            adfun.vectorize(cls.vectorized)\n\n\nclass InnovationDTModel(ADModel):\n    \n    decision = {\n        'x', 'en', 'xnext', 'xprev', 'enprev', 'ybias', \n        'A', 'B', 'C', 'D', 'Ln', 'isRp_tril'\n    }\n    \"\"\"Decision variables of the optimization problem.\"\"\"\n    \n    vectorized = dict(\n        x='nx', en='ny', xnext='nx', xprev='nx', enprev='ny',\n        u='nu', y='ny', uprev='nu',\n        A='nx,nx', B='nx,nu', C='ny,nx', D='ny,nu', Ln='nx,ny', ybias='ny',\n        isRp_tril='nty',\n    )\n    \"\"\"Decision variables of the optimization problem.\"\"\"\n    \n    def __init__(self, nx, nu, ny):\n        self.nx = nx\n        \"\"\"Number of states.\"\"\"\n        \n        self.nu = nu\n        \"\"\"Number of inputs.\"\"\"\n        \n        self.ny = ny\n        \"\"\"Number of outputs.\"\"\"\n    \n    @hessian(('xprev', 'A'), ('enprev', 'Ln'))\n    @constraint('nx')\n    def dynamics(self, xnext, xprev, uprev, enprev, A, B, Ln):\n        \"\"\"Model dynamics defects.\"\"\"\n        xpred = A @ xprev + B @ uprev + Ln @ enprev\n        return xnext - xpred\n    \n    @hessian(('x', 'C'), ('x', 'isRp_tril'), ('C', 'isRp_tril'), \n             ('D', 'isRp_tril'), ('ybias', 'isRp_tril'))\n    @constraint('ny')\n    def innovation(self, y, en, x, u, C, D, ybias, isRp_tril):\n        \"\"\"Model normalized innovation constraint.\"\"\"\n        ymodel = C @ x + D @ u + ybias\n        isRp = tril_mat(isRp_tril)\n        return isRp @ (y - ymodel) - en\n    \n    @hessian(('en', 'en'), ('isRp_tril', 'isRp_tril'))\n    @objective\n    def Ln(self, en, isRp_tril):\n        \"\"\"Measurement log-likelihood.\"\"\"\n        isRp = tril_mat(isRp_tril)\n        log_det_isRp = jnp.log(isRp.diagonal()).sum()\n        return -0.5 * (en ** 2).sum() + log_det_isRp\n\n\ndef tril_mat(tril_elem):\n    \"\"\"Build a matrix from its lower-triangular elements.\"\"\"\n    ntril = len(tril_elem)\n    n = int(round(0.5*(onp.sqrt(8*ntril + 1) - 1)))\n    tril_ind = onp.tril_indices(n)\n    M = jnp.zeros((n, n))\n    return M.at[tril_ind].set(tril_elem)\n\n\ndef shape_size(shape):\n    return onp.prod(shape, dtype=int)\n\n\ndef ndim_range(shape):\n    assert isinstance(shape, tuple)\n    return onp.arange(shape_size(shape)).reshape(shape)\n\n\ndef bound_signature(method):\n    \"\"\"Return the signature of a method when bound.\"\"\"\n    sig = inspect.signature(method)\n    param = list(sig.parameters.values())[1:]\n    return inspect.Signature(param, return_annotation=sig.return_annotation)\n", "meta": {"hexsha": "26a5616a24a0e4ff402cae951456f3e518d89db0", "size": 15543, "ext": "py", "lang": "Python", "max_stars_repo_path": "adfem.py", "max_stars_repo_name": "dimasad/colloc-fem-code", "max_stars_repo_head_hexsha": "1004e9b4aada426e1aa243d4c60cf80d2e1d1431", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "adfem.py", "max_issues_repo_name": "dimasad/colloc-fem-code", "max_issues_repo_head_hexsha": "1004e9b4aada426e1aa243d4c60cf80d2e1d1431", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "adfem.py", "max_forks_repo_name": "dimasad/colloc-fem-code", "max_forks_repo_head_hexsha": "1004e9b4aada426e1aa243d4c60cf80d2e1d1431", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3540772532, "max_line_length": 80, "alphanum_fraction": 0.584571833, "include": true, "reason": "import numpy,import scipy,import jax,from jax", "num_tokens": 3874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3849121585956185, "lm_q1q2_score": 0.1969659429059011}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 21 14:09:18 2020\n\n@author: gao\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import colors\nfrom mpl_toolkits.axes_grid1 import AxesGrid\nimport matplotlib as mpl\nimport os\nfrom matplotlib.colors import LinearSegmentedColormap\n#-------------------------------------------------------------------------------\n# set display width\nnp.get_printoptions()['linewidth']\nnp.set_printoptions(linewidth=400)\n#-------------------------------------------------------------------------------\n\"read size data at n=3, only size effects\"\n\ngrid_chi=101                                           # grid size in figure, so check figure.py file first\ngrid_n=7                                               # 13[5], 23[6], 37[7]; 58[8]; 87[9]; 128[10]\n\nchi_ratio_num=grid_chi\nchi_ratio_log = np.linspace(-0.4,0.4, chi_ratio_num)    # log scale for chi/chi_neutral\nchi_ratio_list=[np.power(10,i) for i in chi_ratio_log]       # chi/chi_neutral\nratio_index=72\n\nwith open(\"../simulation/LC.txt\", \"r\") as file:\n    lcs = eval(file.readline())                          # read lc list\n\n#--------define a function to transform [1+2] to 1+2--------------------\ndef lc_add(x):                                           # x is the number for life cycles\n\tlcs[x].sort(reverse=True)\n\toff_num=len(lcs[x])\n\tini=str(lcs[x][0])                                   #initial lcs\n\tfor i in range(1,off_num):\n\t\tini=ini+'+'+str(lcs[x][i])\n\treturn ini\n\n#----------------------------------------\nN=3\nlc_list=[5,56]\n\n\"add a list [[maturity size=3],[],[],;;;]\"\ndata_list=[ ]\n\t\nfor chi_cluster in range(ratio_index,ratio_index+1):                        # how many figures or cell divisions\n\tfor N_cluster in range(N-1,N):                        # y axes points = a\n\t\tall_list=[]                                          # algin all lcs' growth rates\n\t\tfor i_th in lc_list:                         # read all lcs data = growth rate\n\t\t\t\t\n\t\t\twith open('../data/data_size_effect/%d_%d_%d.txt'%(N_cluster,chi_cluster,i_th), \"r\") as file:\n\t\t\t\tnan=float(np.nan)\n\t\t\t\tinf=np.inf\n\t\t\t\tgrate = eval(file.readline())          # read growth rate\n\t\t\tdata_list.append(np.array([chi_cluster,i_th,grate]))\n\t\t\t\ndata_size=np.array(data_list)\n\n#-------------------------------------------------------------------------------\n\"read data of the threshold effects across k, only threshold effects\"\n\ngrid_num=31                                   # grid size in figure, so check figure.py file first\ngrid_m_num=11                                        # 13[5], 23[6], 37[7]; 58[8]; 87[9]; 128[10]\n\nb_range=np.array([1,16])\nm_range=np.array([0,0.1])\nk_range=np.array([1,2,3,4,5,6,7,8])          # first take 1,2,3, \nk_cluster_list=np.array([0,1,2,3,4,5,6])\n\ngrid_b=np.linspace(b_range[0],b_range[1],num=grid_num,endpoint=True)\ngrid_m=np.linspace(m_range[0],m_range[1],num=grid_m_num,endpoint=True)\n\ncell_number=[3,4,5,6,7,8]\nend_lc_list=[3,7,13,23,37,58]                   # 13[5], 23[6], 37[7]; 58[8]; 87[9]; 128[10]     # how many lcs we care\n\n\"add a list [[maturity size=3],[],[],;;;]\"\ndata_game=[]\nmax_size=8\nfor i in range(5,max_size-2):\n\tn=cell_number[i]\n\tend_lc=end_lc_list[i]\n\t#-------------------------------------------------------------------------------\n\t\"read max and min dps from data into result []\"\n\tnum_k=len(k_cluster_list)\n\tfor b_cluster in range(18,19):                             # b=10\n\t\tfor m_cluster in range(1,2):                             # y axes points = a\n\t\t\tfor k_cluster in k_cluster_list:\n\t\t\t\tfor i_th in lc_list:                            # read all lcs data = growth rate\n\t\t\t\t\twith open('../data/data_threshold_effect/%d_%d_%d_%d.txt'%(b_cluster,m_cluster,k_cluster,i_th), \"r\") as file:\n\t\t\t\t\t\tnan=float(np.nan)\n\t\t\t\t\t\tinf=np.inf\n\t\t\t\t\t\tgrate = eval(file.readline())          # read growth rate\n\t\t\t\t\tdata_game.append([b_cluster,m_cluster,k_cluster,i_th,grate])\ndata_game=np.array(data_game)\n\n#-------------------------------------------------------------------------------\n\"read data of both effects across k,\"\ngrid_num=7                                   # grid size in figure, so check figure.py file first\nt_ratio=1.5\n\nresult_list=[[],[]]                          # to store data of each k value\noptimal_matrix_list=[np.zeros(shape=(grid_num,grid_num))*np.nan for i in range(2)]\n\n\"add a list [[maturity size=3],[],[],;;;]\"\ndata_both=[]\nfor t_pterb_cluster in range(2,3):                        # perturbation at n=3\n\tfor k_cluster in range(0,grid_num):                    # y axes points = a\n\t\tall_list=[]                                    # algin all lcs' growth rates\n\t\tfor i_th in lc_list:                   # read all lcs data = growth rate\n\t\t\t\t\t\t\t\t\t\t\n\t\t\twith open('../data/data_size_threshold_chi_%s/%d_%d_%d.txt'%(t_ratio,t_pterb_cluster,k_cluster,i_th), \"r\") as file:\n\t\t\t\tnan=float(np.nan)\n\t\t\t\tinf=np.inf\n\t\t\t\tgrate = eval(file.readline())          # read growth rate\n\t\t\tdata_both.append(np.array([t_ratio,t_pterb_cluster,k_cluster,i_th,grate]))\n\ndata_both=np.array(data_both)\n\n#================= draw figures====================================================\nc = np.arange(1, 58 + 1)\n\nnorm = mpl.colors.Normalize(vmin=c.min(), vmax=c.max())\ncmap = mpl.cm.ScalarMappable(norm=norm, cmap=mpl.cm.jet)\ncmap.set_array([])\n \nfig, ax = plt.subplots(1, 1, figsize=(4, 4.5))\nfig.subplots_adjust(top=0.82)\nax.set_axisbelow(True)\nk_list=[1,2,3,4,5,6,7]\n\n\"size figure\"\ns_size=1\nfor i in lc_list:\n\ty=data_size[np.where(data_size[:,1]==i)][0,2]\n\tax.scatter(k_list, [y for i in range(7)], s=s_size,marker=\"^\",c=cmap.to_rgba(i + 1),alpha=0.9)\n\tif s_size==1:\n\t\tax.plot(k_list, [y for i in range(7)], ':',label=\"Size effects\",linewidth=1.5,c=cmap.to_rgba(i + 1),alpha=0.95)\n\telse:\n\t\tax.plot(k_list, [y for i in range(7)], ':',linewidth=1.5,c=cmap.to_rgba(i + 1),alpha=0.95)\n\t\n\t\"game figure\"\t\n\ty_game=data_game[np.where(data_game[:,3]==i)][:,4]\n\tax.scatter(k_list, y_game, s=s_size,marker=\"^\",c=cmap.to_rgba(i + 1),alpha=0.9)\n\tif s_size==1:\n\t\tax.plot(k_list, y_game, '--',label=\"Threshold effets\",linewidth=2,c=cmap.to_rgba(i + 1),alpha=0.95)\n\telse:\n\t\tax.plot(k_list, y_game, '--',linewidth=2,c=cmap.to_rgba(i + 1),alpha=0.95)\n\t\t\n\t\"size and game figure\"\t\n\ty_both=data_both[np.where(data_both[:,3]==i)][:,4]\n\tax.scatter(k_list, y_both, s=s_size,marker=\"^\",c=cmap.to_rgba(i + 1),alpha=0.9)\n\t\n\tif  s_size==1:\n\t\tax.plot(k_list, y_both, '-',label=\"Combined effects\",linewidth=2,c=cmap.to_rgba(i + 1),alpha=0.75)\n\telse:\n\t\tax.plot(k_list, y_both, '-',linewidth=2,c=cmap.to_rgba(i + 1),alpha=0.75)\n\n\ts_size+=1\n\t\nleg=ax.legend(frameon=False,loc='upper center', bbox_to_anchor=(0.7, 0.98), shadow=True, ncol=1, fontsize=10)\nfor i in range(3):\n\tleg.legendHandles[i].set_color('k')\n\t\nax.annotate(lc_add(lc_list[0]), (2.3, 1.65),color=cmap.to_rgba(5 + 1))\t\nax.annotate(lc_add(lc_list[1]), (4.5, 1.85),color=cmap.to_rgba(56 + 1))\t\n\nax.set_xlabel(r\"Contribution threshold $k$\",fontsize=12)\nax.set_xticks([i for i in range(1,8)], minor=False)\nax.set_ylim([0.65, 3.5])\nax.set_ylabel(r\"Population growth rate $\\lambda$\",fontsize=12)\n\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\nax.spines['left'].set_visible(False)\nax.yaxis.set_ticks_position('left')\n\nplt.show();\n\n\n", "meta": {"hexsha": "d40aa0c70acd7fef4a729d46fd208a7c700f41ce", "size": 7227, "ext": "py", "lang": "Python", "max_stars_repo_path": "figure/Figure4D.py", "max_stars_repo_name": "YuanxiaoGao/Evolution_of_reproductive_strategies_in_incipient_multicellularity", "max_stars_repo_head_hexsha": "13eb51639fcee630a76e197b50ef321e3a94ce0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "figure/Figure4D.py", "max_issues_repo_name": "YuanxiaoGao/Evolution_of_reproductive_strategies_in_incipient_multicellularity", "max_issues_repo_head_hexsha": "13eb51639fcee630a76e197b50ef321e3a94ce0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "figure/Figure4D.py", "max_forks_repo_name": "YuanxiaoGao/Evolution_of_reproductive_strategies_in_incipient_multicellularity", "max_forks_repo_head_hexsha": "13eb51639fcee630a76e197b50ef321e3a94ce0f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.277173913, "max_line_length": 119, "alphanum_fraction": 0.5738203957, "include": true, "reason": "import numpy", "num_tokens": 2052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166195971441, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19696594141720597}}
{"text": "# Main entrance of GAIL\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport gym\nimport safety_gym\nimport time\nimport os.path as osp\n\nfrom torch.distributions.categorical import Categorical\n\nfrom neural_nets import Discriminator, ActorCritic, ValorDiscriminator, count_vars\n\nfrom utils import BufferS, BufferT, BufferActor, VALORBuffer\nfrom utils import mpi_fork, proc_id, num_procs, EpochLogger,\\\n    average_gradients, sync_all_params\n\n\n\ndef ppo_penalized(env_fn,\n            actor_critic=ActorCritic,\n            ac_kwargs=dict(),\n            seed=0,\n            episodes_per_epoch=40,\n            epochs=500,\n            gamma=0.99,\n            lam=0.97,\n            pi_lr=3e-4,\n            vf_lr=1e-3,\n            train_v_iters=80,\n            max_ep_len=1000,\n            logger_kwargs=dict(),\n            save_freq=10):\n\n    logger = EpochLogger(**logger_kwargs)\n    logger.save_config(locals())\n\n    seed += 10000 * proc_id()\n    torch.manual_seed(seed)\n    np.random.seed(seed)\n\n    env = env_fn()\n    obs_dim = env.observation_space.shape\n    act_dim = env.action_space.shape\n\n    ac_kwargs['action_space'] = env.action_space\n\n    # Models\n    ac = actor_critic(input_dim=obs_dim[0], **ac_kwargs)\n\n    # Set up model saving\n    logger.setup_pytorch_saver(ac)\n\n    # Buffers\n    local_episodes_per_epoch = int(episodes_per_epoch / num_procs())\n    buf = BufferActor(obs_dim[0], act_dim[0], local_episodes_per_epoch, max_ep_len)\n\n    # Count variables\n    var_counts = tuple(count_vars(module) for module in [ac.policy, ac.value_f])\n    print(\"POLICY GRADIENT\")\n    logger.log('\\nNumber of parameters: \\t pi: %d, \\t v: %d\\n' % var_counts)\n\n    # Optimizers\n    train_pi = torch.optim.Adam(ac.policy.parameters(), lr=pi_lr)\n    train_v = torch.optim.Adam(ac.value_f.parameters(), lr=vf_lr)\n\n    # Parameters Sync\n    sync_all_params(ac.parameters())\n\n    def update(e):\n        obs, act, adv, ret, lgp_old = [torch.Tensor(x) for x in buf.retrieve_all()]\n\n        # Policy\n        _, lgp, _ = ac.policy(obs, act)\n        entropy = (-lgp).mean()\n\n        # Policy loss # policy gradient term + entropy term\n        pi_loss = -(lgp * adv).mean()\n\n        # Train policy\n        train_pi.zero_grad()\n        pi_loss.backward()\n        average_gradients(train_pi.param_groups)\n        train_pi.step()\n\n        # Value function\n        v = ac.value_f(obs)\n        v_l_old = F.mse_loss(v, ret)\n        for _ in range(train_v_iters):\n            v = ac.value_f(obs)\n            v_loss = F.mse_loss(v, ret)\n\n            # Value function train\n            train_v.zero_grad()\n            v_loss.backward()\n            average_gradients(train_v.param_groups)\n            train_v.step()\n\n        # Log the changes\n        _, lgp, _, v = ac(obs, act)\n        entropy_new = (-lgp).mean()\n        pi_loss_new = -(lgp * adv).mean()\n        v_loss_new = F.mse_loss(v, ret)\n        kl = (lgp_old - lgp).mean()\n        logger.store(LossPi=pi_loss, LossV=v_l_old, DeltaLossPi=(pi_loss_new - pi_loss),\n                     DeltaLossV=(v_loss_new - v_l_old), Entropy=entropy, KL=kl)\n\n    start_time = time.time()\n    o, r, d, ep_ret, ep_len = env.reset(), 0, False, 0, 0\n    total_t = 0\n\n    for epoch in range(epochs):\n        ac.eval()\n        # Policy rollout\n        for _ in range(local_episodes_per_epoch):\n            for _ in range(max_ep_len):\n                obs = torch.Tensor(o.reshape(1, -1))\n                a, _, lopg_t, v_t = ac(obs)\n\n                buf.store(o, a.detach().numpy(), r, v_t.item(), lopg_t.detach().numpy())\n                logger.store(VVals=v_t)\n\n                o, r, d, _ = env.step(a.detach().numpy()[0])\n                ep_ret += r\n                ep_len += 1\n                total_t += 1\n\n                terminal = d or (ep_len == max_ep_len)\n                if terminal:\n                    buf.end_episode()\n                    logger.store(EpRet=ep_ret, EpLen=ep_len)\n                    o, r, d, ep_ret, ep_len = env.reset(), 0, False, 0, 0\n\n        if (epoch % save_freq == 0) or (epoch == epochs - 1):\n            # logger._torch_save(ac, fname=\"expert_torch_save.pt\")\n            # logger._torch_save(ac, fname=\"model.pt\")\n            logger.save_state({'env': env}, None, None)\n\n        # Update\n        ac.train()\n\n        update(epoch)\n\n        # Log\n        logger.log_tabular('Epoch', epoch)\n        logger.log_tabular('EpRet', with_min_and_max=True)\n        logger.log_tabular('EpLen', average_only=True)\n        logger.log_tabular('VVals', with_min_and_max=True)\n        logger.log_tabular('TotalEnvInteracts', total_t)\n        logger.log_tabular('LossPi', average_only=True)\n        logger.log_tabular('DeltaLossPi', average_only=True)\n        logger.log_tabular('LossV', average_only=True)\n        logger.log_tabular('DeltaLossV', average_only=True)\n        logger.log_tabular('Entropy', average_only=True)\n        logger.log_tabular('KL', average_only=True)\n        logger.log_tabular('Time', time.time() - start_time)\n        logger.dump_tabular()\n\n\n\n\n\n\n\ndef gail_penalized(env_fn, actor_critic=ActorCritic, ac_kwargs=dict(),\n         disc=Discriminator,\n         dc_kwargs=dict(), seed=0,\n         episodes_per_epoch=40,\n         epochs=500,\n         gamma=0.99, lam=0.97,\n         pi_lr=3e-3, vf_lr=3e-3, dc_lr=5e-4, train_v_iters=80, train_dc_iters=80,\n         max_ep_len=1000, logger_kwargs=dict(), save_freq=10):\n    l_lam = 0  # balance two loss term\n\n    print(\"starting now\")\n\n    logger = EpochLogger(**logger_kwargs)\n    logger.save_config(locals())\n\n    seed += 10000 * proc_id()\n    torch.manual_seed(seed)\n    np.random.seed(seed)\n\n    env = env_fn()\n    obs_dim = env.observation_space.shape\n    act_dim = env.action_space.shape\n\n    ac_kwargs['action_space'] = env.action_space\n\n    # Models\n    ac = actor_critic(input_dim=obs_dim[0], **ac_kwargs)\n    disc = disc(input_dim=obs_dim[0], **dc_kwargs)\n\n    # Set up model saving\n    logger.setup_pytorch_saver([ac, disc])\n\n    # TODO: Load expert policy here\n    expert = actor_critic(input_dim=obs_dim[0], **ac_kwargs)\n    # expert_name = \"expert_torch_save.pt\"\n    expert_name = \"model.pt\"\n    # expert = torch.load(osp.join(logger_kwargs['output_dir'],'pyt_save' , expert_name))\n    expert = torch.load('/home/tyna/Documents/openai/research-project/data/anonymous-expert/anonymous-expert_s0/pyt_save/model.pt')\n\n    print('RUNNING GAIL')\n\n    # Buffers\n    local_episodes_per_epoch = int(episodes_per_epoch / num_procs())\n    buff_s = BufferS(obs_dim[0], act_dim[0], local_episodes_per_epoch, max_ep_len)\n    buff_t = BufferT(obs_dim[0], act_dim[0], local_episodes_per_epoch, max_ep_len)\n\n    # Count variables\n    var_counts = tuple(count_vars(module) for module in [ac.policy, ac.value_f, disc.policy])\n    print(\"GAIL\")\n    logger.log('\\nNumber of parameters: \\t pi: %d, \\t v: %d, \\t d: %d\\n' % var_counts)\n\n\n    # Optimizers\n    train_pi = torch.optim.Adam(ac.policy.parameters(), lr=pi_lr)\n    train_v = torch.optim.Adam(ac.value_f.parameters(), lr=vf_lr)\n    train_dc = torch.optim.Adam(disc.policy.parameters(), lr=dc_lr)\n\n    # Parameters Sync\n    sync_all_params(ac.parameters())\n    sync_all_params(disc.parameters())\n\n    def update(e):\n        obs_s, act, adv, ret, lgp_old = [torch.Tensor(x) for x in buff_s.retrieve_all()]\n        obs_t, _ = [torch.Tensor(x) for x in buff_t.retrieve_all()]\n\n        # Policy\n        _, lgp, _ = ac.policy(obs_s, act)\n        entropy = (-lgp).mean()\n\n        # Policy loss\n        # policy gradient term + entropy term\n        pi_loss = -(lgp * adv).mean() - l_lam * entropy\n\n        # Train policy\n        if e > 10:\n            train_pi.zero_grad()\n            pi_loss.backward()\n            average_gradients(train_pi.param_groups)\n            train_pi.step()\n\n        # Value function\n        v = ac.value_f(obs_s)\n        v_l_old = F.mse_loss(v, ret)\n\n        for _ in range(train_v_iters):\n            v = ac.value_f(obs_s)\n            v_loss = F.mse_loss(v, ret)\n\n            # Value function train\n            train_v.zero_grad()\n            v_loss.backward()\n            average_gradients(train_v.param_groups)\n            train_v.step()\n\n        # Discriminator\n        gt1 = torch.ones(obs_s.size()[0], dtype=torch.int)\n        gt2 = torch.zeros(obs_t.size()[0], dtype=torch.int)\n        _, lgp_s, _ = disc(obs_s, gt=gt1)\n        _, lgp_t, _ = disc(obs_t, gt=gt2)\n        dc_loss_old = - lgp_s.mean() - lgp_t.mean()\n\n        for _ in range(train_dc_iters):\n            _, lgp_s, _ = disc(obs_s, gt=gt1)\n            _, lgp_t, _ = disc(obs_t, gt=gt2)\n            dc_loss = - lgp_s.mean() - lgp_t.mean()\n\n            # Discriminator train\n            train_dc.zero_grad()\n            dc_loss.backward()\n            average_gradients(train_dc.param_groups)\n            train_dc.step()\n\n        _, lgp_s, _ = disc(obs_s, gt=gt1)\n        _, lgp_t, _ = disc(obs_t, gt=gt2)\n        dc_loss_new = - lgp_s.mean() - lgp_t.mean()\n\n        # Log the changes\n        _, lgp, _, v = ac(obs, act)\n        entropy_new = (-lgp).mean()\n        pi_loss_new = -(lgp * adv).mean() - l_lam * entropy\n        v_loss_new = F.mse_loss(v, ret)\n        kl = (lgp_old - lgp).mean()\n        logger.store(LossPi=pi_loss, LossV=v_l_old, LossDC=dc_loss_old, DeltaLossPi=(pi_loss_new - pi_loss),\n                     DeltaLossV=(v_loss_new - v_l_old), DeltaLossDC=(dc_loss_new - dc_loss_old),\n                     DeltaEnt=(entropy_new - entropy),\n                     Entropy=entropy, KL=kl)\n\n    start_time = time.time()\n    o, r, sdr, d, ep_ret, ep_sdr, ep_len = env.reset(), 0, 0, False, 0, 0, 0\n    total_t = 0\n\n    ep_len_t = 0\n    for epoch in range(epochs):\n        ac.eval()\n        disc.eval()\n        # We recognize the probability term of index [0] correspond to the teacher's policy\n\n        # Student's policy rollout\n        for _ in range(local_episodes_per_epoch):\n            for _ in range(max_ep_len):\n                obs = torch.Tensor(o.reshape(1, -1))\n                a, _, lopg_t, v_t = ac(obs)\n\n                buff_s.store(o, a.detach().numpy(), r, sdr, v_t.item(), lopg_t.detach().numpy())\n                logger.store(VVals=v_t)\n\n                o, r, d, _ = env.step(a.detach().numpy()[0])\n                _, sdr, _ = disc(torch.Tensor(o.reshape(1, -1)), gt=torch.Tensor([0]))\n                if sdr < -4:  # Truncate rewards\n                    sdr = -4\n                ep_ret += r\n                ep_sdr += sdr\n                ep_len += 1\n                total_t += 1\n\n                terminal = d or (ep_len == max_ep_len)\n                if terminal:\n                    buff_s.end_episode()\n                    logger.store(EpRetS=ep_ret, EpLenS=ep_len, EpSdrS=ep_sdr)\n                    print(\"Student Episode Return: \\t\", ep_ret)\n                    o, r, sdr, d, ep_ret, ep_sdr, ep_len = env.reset(), 0, 0, False, 0, 0, 0\n\n        # Teacher's policy rollout\n        for _ in range(local_episodes_per_epoch):\n            for _ in range(max_ep_len):\n                obs = torch.Tensor(o.reshape(1, -1))\n                a, _, _, _ = expert(obs)\n\n                buff_t.store(o, a.detach().numpy(), r)\n\n                o, r, d, _ = env.step(a.detach().numpy()[0])\n                ep_ret += r\n                ep_len += 1\n                total_t += 1\n\n                terminal = d or (ep_len == max_ep_len)\n                if terminal:\n                    buff_t.end_episode()\n                    logger.store(EpRetT=ep_ret, EpLenT=ep_len)\n                    print(\"Teacher Episode Return: \\t\", ep_ret)\n                    o, r, d, ep_ret, ep_len = env.reset(), 0, False, 0, 0\n\n        if (epoch % save_freq == 0) or (epoch == epochs - 1):\n            logger.save_state({'env': env}, [ac, disc], None)\n\n        # Update\n        ac.train()\n        disc.train()\n\n        update(epoch)\n\n        # Log\n        logger.log_tabular('Epoch', epoch)\n        logger.log_tabular('EpRetS', with_min_and_max=True)\n        logger.log_tabular('EpSdrS', with_min_and_max=True)\n        logger.log_tabular('EpLenS', average_only=True)\n        logger.log_tabular('EpRetT', with_min_and_max=True)\n        logger.log_tabular('EpLenT', average_only=True)\n        logger.log_tabular('VVals', with_min_and_max=True)\n        logger.log_tabular('TotalEnvInteracts', total_t)\n        logger.log_tabular('LossPi', average_only=True)\n        logger.log_tabular('DeltaLossPi', average_only=True)\n        logger.log_tabular('LossV', average_only=True)\n        logger.log_tabular('DeltaLossV', average_only=True)\n        logger.log_tabular('LossDC', average_only=True)\n        logger.log_tabular('DeltaLossDC', average_only=True)\n        logger.log_tabular('Entropy', average_only=True)\n        logger.log_tabular('DeltaEnt', average_only=True)\n        logger.log_tabular('KL', average_only=True)\n        logger.log_tabular('Time', time.time() - start_time)\n        logger.dump_tabular()\n\n\ndef valor_penalized(env_fn, actor_critic=ActorCritic, ac_kwargs=dict(),\n          disc=Discriminator, dc_kwargs=dict(), seed=0,\n          episodes_per_epoch=40,\n          epochs=50, gamma=0.99, pi_lr=3e-4, vf_lr=1e-3, dc_lr=5e-4,\n          train_v_iters=80, train_dc_iters=10,\n          train_dc_interv=10,\n          lam=0.97, max_ep_len=1000, logger_kwargs=dict(), con_dim=5, save_freq=10, k=1):\n\n    logger = EpochLogger(**logger_kwargs)\n    logger.save_config(locals())\n\n    seed += 10000 * proc_id()\n    torch.manual_seed(seed)\n    np.random.seed(seed)\n\n    env = env_fn()\n    obs_dim = env.observation_space.shape\n    act_dim = env.action_space.shape\n\n    ac_kwargs['action_space'] = env.action_space\n\n    # Model\n    ac = actor_critic(input_dim=obs_dim[0] + con_dim, **ac_kwargs)\n    disc = disc(input_dim=obs_dim[0], context_dim=con_dim, **dc_kwargs)\n\n    # Set up model saving\n    logger.setup_pytorch_saver([ac, disc])\n\n    # Buffer\n    local_episodes_per_epoch = int(episodes_per_epoch / num_procs())\n    buffer = VALORBuffer(con_dim, obs_dim[0], act_dim[0], local_episodes_per_epoch, max_ep_len, train_dc_interv)\n\n    # Count variables\n    var_counts = tuple(count_vars(module) for module in\n                       [ac.policy, ac.value_f, disc.policy])\n    logger.log('\\nNumber of parameters: \\t pi: %d, \\t v: %d, \\t d: %d\\n' % var_counts)\n\n    # Optimizers\n    train_pi = torch.optim.Adam(ac.policy.parameters(), lr=pi_lr)\n    train_v = torch.optim.Adam(ac.value_f.parameters(), lr=vf_lr)\n    train_dc = torch.optim.Adam(disc.policy.parameters(), lr=dc_lr)\n\n    # Parameters Sync\n    sync_all_params(ac.parameters())\n    sync_all_params(disc.parameters())\n\n    def update(e):\n        obs, act, adv, pos, ret, logp_old = [torch.Tensor(x) for x in buffer.retrieve_all()]\n\n        # Policy\n        _, logp, _ = ac.policy(obs, act)\n        entropy = (-logp).mean()\n\n        # Policy loss\n        pi_loss = -(logp * (k * adv + pos)).mean()\n\n        # Train policy\n        train_pi.zero_grad()\n        pi_loss.backward()\n        average_gradients(train_pi.param_groups)\n        train_pi.step()\n\n        # Value function\n        v = ac.value_f(obs)\n        v_l_old = F.mse_loss(v, ret)\n        for _ in range(train_v_iters):\n            v = ac.value_f(obs)\n            v_loss = F.mse_loss(v, ret)\n\n            # Value function train\n            train_v.zero_grad()\n            v_loss.backward()\n            average_gradients(train_v.param_groups)\n            train_v.step()\n\n        # Discriminator\n        if (e + 1) % train_dc_interv == 0:\n            print('Discriminator Update!')\n            con, s_diff = [torch.Tensor(x) for x in buffer.retrieve_dc_buff()]\n            _, logp_dc, _ = disc(s_diff, con)\n            d_l_old = -logp_dc.mean()\n\n            # Discriminator train\n            for _ in range(train_dc_iters):\n                _, logp_dc, _ = disc(s_diff, con)\n                d_loss = -logp_dc.mean()\n                train_dc.zero_grad()\n                d_loss.backward()\n                average_gradients(train_dc.param_groups)\n                train_dc.step()\n\n            _, logp_dc, _ = disc(s_diff, con)\n            dc_l_new = -logp_dc.mean()\n        else:\n            d_l_old = 0\n            dc_l_new = 0\n\n        # Log the changes\n        _, logp, _, v = ac(obs, act)\n        pi_l_new = -(logp * (k * adv + pos)).mean()\n        v_l_new = F.mse_loss(v, ret)\n        kl = (logp_old - logp).mean()\n        logger.store(LossPi=pi_loss, LossV=v_l_old, KL=kl, Entropy=entropy, DeltaLossPi=(pi_l_new - pi_loss),\n                     DeltaLossV=(v_l_new - v_l_old), LossDC=d_l_old, DeltaLossDC=(dc_l_new - d_l_old))\n        # logger.store(Adv=adv.reshape(-1).numpy().tolist(), Pos=pos.reshape(-1).numpy().tolist())\n\n    start_time = time.time()\n    o, r, d, ep_ret, ep_len = env.reset(), 0, False, 0, 0\n    context_dist = Categorical(logits=torch.Tensor(np.ones(con_dim)))\n    total_t = 0\n\n    for epoch in range(epochs):\n        ac.eval()\n        disc.eval()\n        for _ in range(local_episodes_per_epoch):\n            c = context_dist.sample()\n            c_onehot = F.one_hot(c, con_dim).squeeze().float()\n            for _ in range(max_ep_len):\n                concat_obs = torch.cat([torch.Tensor(o.reshape(1, -1)), c_onehot.reshape(1, -1)], 1)\n                a, _, logp_t, v_t = ac(concat_obs)\n\n                buffer.store(c, concat_obs.squeeze().detach().numpy(), a.detach().numpy(), r, v_t.item(),\n                             logp_t.detach().numpy())\n                logger.store(VVals=v_t)\n\n                o, r, d, _ = env.step(a.detach().numpy()[0])\n                ep_ret += r\n                ep_len += 1\n                total_t += 1\n\n                terminal = d or (ep_len == max_ep_len)\n                if terminal:\n                    dc_diff = torch.Tensor(buffer.calc_diff()).unsqueeze(0)\n                    con = torch.Tensor([float(c)]).unsqueeze(0)\n                    _, _, log_p = disc(dc_diff, con)\n                    buffer.end_episode(log_p.detach().numpy())\n                    logger.store(EpRet=ep_ret, EpLen=ep_len)\n                    o, r, d, ep_ret, ep_len = env.reset(), 0, False, 0, 0\n\n        if (epoch % save_freq == 0) or (epoch == epochs - 1):\n            logger.save_state({'env': env}, [ac, disc], None)\n\n        # Update\n        ac.train()\n        disc.train()\n\n        update(epoch)\n\n        # Log\n        logger.log_tabular('Epoch', epoch)\n        logger.log_tabular('EpRet', with_min_and_max=True)\n        logger.log_tabular('EpLen', average_only=True)\n        logger.log_tabular('VVals', with_min_and_max=True)\n        logger.log_tabular('TotalEnvInteracts', total_t)\n        logger.log_tabular('LossPi', average_only=True)\n        logger.log_tabular('DeltaLossPi', average_only=True)\n        logger.log_tabular('LossV', average_only=True)\n        logger.log_tabular('DeltaLossV', average_only=True)\n        logger.log_tabular('LossDC', average_only=True)\n        logger.log_tabular('DeltaLossDC', average_only=True)\n        logger.log_tabular('Entropy', average_only=True)\n        logger.log_tabular('KL', average_only=True)\n        logger.log_tabular('Time', time.time() - start_time)\n        logger.dump_tabular()\n\nif __name__ == '__main__':\n    import argparse\n\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--env', type=str, default='Safexp-PointGoal1-v0')\n    parser.add_argument('--hid', type=int, default=64)\n    parser.add_argument('--l', type=int, default=2)\n    parser.add_argument('--gamma', type=float, default=0.99)\n    parser.add_argument('--lam', type=float, default=0.97)\n    parser.add_argument('--seed', '-s', type=int, default=0)\n    parser.add_argument('--cpu', type=int, default=1)\n    parser.add_argument('--episodes-per-epoch', type=int, default=5)\n    # parser.add_argument('--episodes-per-epoch', type=int, default=40)\n    parser.add_argument('--epochs', type=int, default=1000)\n    parser.add_argument('--exp_name', type=str, default='valor-anonymous-expert')\n    parser.add_argument('--con', type=int, default=5)\n    args = parser.parse_args()\n\n    mpi_fork(args.cpu)\n\n    from utils import setup_logger_kwargs\n\n    logger_kwargs = setup_logger_kwargs(args.exp_name, args.seed)\n\n    # ppo_penalized(lambda: gym.make(args.env), actor_critic=ActorCritic, ac_kwargs=dict(hidden_dims=[args.hid]*args.l),\n    #     gamma=args.gamma, lam=args.lam, seed=args.seed, episodes_per_epoch=args.episodes_per_epoch,\n    #     epochs=args.epochs, logger_kwargs=logger_kwargs)\n\n    # gail_penalized(lambda: gym.make(args.env), actor_critic=ActorCritic, ac_kwargs=dict(hidden_dims=[args.hid] * args.l),\n    #      disc=Discriminator, dc_kwargs=dict(hidden_dims=[args.hid] * args.l), gamma=args.gamma, lam=args.lam,\n    #      seed=args.seed, episodes_per_epoch=args.episodes_per_epoch, epochs=args.epochs, logger_kwargs=logger_kwargs)\n\n\n    valor_penalized(lambda: gym.make(args.env), actor_critic=ActorCritic, ac_kwargs=dict(hidden_dims=[args.hid] * args.l),\n          disc=ValorDiscriminator, dc_kwargs=dict(hidden_dims=args.hid),\n          gamma=args.gamma, seed=args.seed, episodes_per_epoch=args.episodes_per_epoch, epochs=args.epochs,\n          logger_kwargs=logger_kwargs, con_dim=args.con)\n\n", "meta": {"hexsha": "be2035f9c5b84e1e72fdcebe05bdfe73db117673", "size": 21044, "ext": "py", "lang": "Python", "max_stars_repo_path": "algos/training_regimes_penalized.py", "max_stars_repo_name": "feloundou/safe-experts", "max_stars_repo_head_hexsha": "9592bd48ce7eed721a36cb688dd10dc7f527a13b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "algos/training_regimes_penalized.py", "max_issues_repo_name": "feloundou/safe-experts", "max_issues_repo_head_hexsha": "9592bd48ce7eed721a36cb688dd10dc7f527a13b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algos/training_regimes_penalized.py", "max_forks_repo_name": "feloundou/safe-experts", "max_forks_repo_head_hexsha": "9592bd48ce7eed721a36cb688dd10dc7f527a13b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2203098107, "max_line_length": 131, "alphanum_fraction": 0.5968922258, "include": true, "reason": "import numpy", "num_tokens": 5444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.1969659356847176}}
{"text": "# ===========================================================================\n# This module is adpated from: https://github.com/fchollet/keras\n# Revision: @bec2701\n# Original work Copyright (c) 2014-2015 keras contributors\n# Some idea are also borrowed from Lasagne library\n# Original work Copyright (c) 2014-2015 Lasagne contributors\n# Some work are adapted from tensorfuse library\n# Original work Copyright (c) [dementrock](https://github.com/dementrock)\n# Modified work Copyright 2016-2017 TrungNT\n# ===========================================================================\n\nimport tensorflow as tf\nimport numpy as np\nimport os\nfrom collections import OrderedDict\n\nfrom .. import config\nfrom .numpy_backend import get_random_magic_seed\n\nfrom six.moves import range, zip\n\n_FLOATX = config.floatX()\n_EPSILON = config.epsilon()\n\n# ===========================================================================\n# INTERNAL UTILS\n# ===========================================================================\n_SESSION = None\n\n\ndef get_session():\n    global _SESSION\n    if _SESSION is None:\n        if not os.environ.get('OMP_NUM_THREADS'):\n            _SESSION = tf.Session('')\n        else:\n            nb_thread = int(os.environ.get('OMP_NUM_THREADS'))\n            _SESSION = tf.Session(config=tf.ConfigProto(intra_op_parallelism_threads=nb_thread))\n    return _SESSION\n\n\ndef _set_session(session):\n    global _SESSION\n    _SESSION = session\n\n# From Theano\n\n\ndef _format_as(use_list, use_tuple, outputs):\n    \"\"\"\n    Formats the outputs according to the flags `use_list` and `use_tuple`.\n    If `use_list` is True, `outputs` is returned as a list (if `outputs`\n    is not a list or a tuple then it is converted in a one element list).\n    If `use_tuple` is True, `outputs` is returned as a tuple (if `outputs`\n    is not a list or a tuple then it is converted into a one element tuple).\n    Otherwise (if both flags are false), `outputs` is returned.\n    \"\"\"\n    assert not (use_list and use_tuple), \\\n        \"Both flags cannot be simultaneously True\"\n    if (use_list or use_tuple) and not isinstance(outputs, (list, tuple)):\n        if use_list:\n            return [outputs]\n        else:\n            return (outputs,)\n    elif not (use_list or use_tuple) and isinstance(outputs, (list, tuple)):\n        assert len(outputs) == 1, \\\n            \"Wrong arguments. Expected a one element list\"\n        return outputs[0]\n    elif use_list or use_tuple:\n        if use_list:\n            return list(outputs)\n        else:\n            return tuple(outputs)\n    else:\n        return outputs\n\n\ndef _wrap_into_list(x):\n    \"\"\"\n    Wrap the input into a list if it is not already a list.\n    \"\"\"\n    if x is None:\n        return []\n    elif not isinstance(x, (list, tuple)):\n        return [x]\n    else:\n        return list(x)\n# ===========================================================================\n# VARIABLE MANIPULATION\n# ===========================================================================\n\n\ndef variable(value, dtype=_FLOATX, name=None, broadcastable=None):\n    v = tf.Variable(np.asarray(value, dtype=dtype), name=name)\n    get_session().run(v.initializer)\n    return v\n\n\ndef zeros_var(shape, dtype=_FLOATX, name=None):\n    return variable(np.zeros(shape), dtype, name)\n\n\ndef ones_var(shape, dtype=_FLOATX, name=None):\n    return variable(np.ones(shape), dtype, name)\n\n\ndef is_variable(v):\n    return isinstance(v, tf.python.Variable)\n\n_PLACEHOLDER_ID = 0\n_PLACEHOLDER_SHAPE = {}\n\n\ndef placeholder(shape=None, ndim=None, dtype=_FLOATX, name=None):\n    # name must match: [A-Za-z0-9.][A-Za-z0-9_.\\-/]*\n    if not shape:\n        if ndim:\n            shape = [None for _ in range(ndim)]\n\n    # ====== Modify add name prefix ====== #\n    global _PLACEHOLDER_ID\n    name_prefix = 'ID.%02d.' % _PLACEHOLDER_ID\n    _PLACEHOLDER_ID += 1\n    if name is None:\n        name = ''\n    name = name_prefix + name\n    placeholder = tf.placeholder(dtype, shape=shape, name=name)\n    _PLACEHOLDER_SHAPE[placeholder.name] = shape\n    return placeholder\n\n\ndef is_expression(v):\n    return isinstance(v, tf.python.Tensor)\n\n\ndef is_placeholder(v):\n    if is_expression(v) and v.name in _PLACEHOLDER_SHAPE:\n        return True\n    return False\n\n\ndef eval(x):\n    '''Run a graph.\n    '''\n    if isinstance(x, tf.TensorShape):\n        return x.as_list()\n    return x.eval(session=get_session())\n\n# ===========================================================================\n# Shape operators\n# ===========================================================================\n\n\ndef shape(x):\n    return x.get_shape()\n\n\ndef int_shape(x):\n    shape = x.get_shape()\n    return tuple([i.__int__() for i in shape])\n\n\ndef ndim(x):\n    return len(x.get_shape())\n\n\ndef broadcastable(x):\n    return None\n\n\ndef addbroadcast(x, *axes):\n    return x\n\n# ===========================================================================\n# Predefined data\n# ===========================================================================\n\n\ndef zeros(shape, dtype=_FLOATX, name=None):\n    return tf.zeros(shape, dtype=dtype, name=name)\n\n\ndef ones(shape, dtype=_FLOATX, name=None):\n    return tf.ones(shape, dtype=dtype, name=name)\n\n\ndef ones_like(x, name=None):\n    return tf.ones_like(x, name=name)\n\n\ndef zeros_like(x, name=None):\n    return tf.zeros_like(x, name=name)\n\n\ndef count_params(x):\n    '''Return number of scalars in a tensor.\n    '''\n    shape = x.get_shape()\n    return np.prod([shape[i]._value for i in range(len(shape))])\n\n\ndef cast(x, dtype):\n    if 'tensorflow.' in str(x.__class__):\n        return tf.cast(x, dtype)\n    return np.cast[dtype](x)\n\n\ndef castX(x):\n    return cast(x, _FLOATX)\n\n# ===========================================================================\n# LINEAR ALGEBRA\n# ===========================================================================\n\n\ndef dot(x, y):\n    return tf.matmul(x, y)\n\n\ndef transpose(x):\n    return tf.transpose(x)\n\n\ndef gather(reference, indices):\n    '''\n    # Arguments\n        reference: a tensor.\n        indices: an int tensor of indices.\n\n    # Returns\n        a tensor of same type as `reference`.\n    '''\n    return tf.gather(reference, indices)\n\n\n# ===========================================================================\n# ELEMENT-WISE OPERATIONS\n# ===========================================================================\ndef normalize_axis(axis, ndim):\n    if type(axis) is tuple:\n        axis = list(axis)\n    if type(axis) is list:\n        for i, a in enumerate(axis):\n            if a is not None and a < 0:\n                axis[i] = a % ndim\n    else:\n        if axis is not None and axis < 0:\n            axis = axis % ndim\n    return axis\n\n\ndef max(x, axis=None, keepdims=False):\n    axis = normalize_axis(axis, ndim(x))\n    return tf.reduce_max(x, reduction_indices=axis, keep_dims=keepdims)\n\n\ndef min(x, axis=None, keepdims=False):\n    axis = normalize_axis(axis, ndim(x))\n    return tf.reduce_min(x, reduction_indices=axis, keep_dims=keepdims)\n\n\ndef sum(x, axis=None, keepdims=False):\n    '''Sum of the values in a tensor, alongside the specified axis.\n    '''\n    axis = normalize_axis(axis, ndim(x))\n    return tf.reduce_sum(x, reduction_indices=axis, keep_dims=keepdims)\n\n\ndef prod(x, axis=None, keepdims=False):\n    '''Multiply the values in a tensor, alongside the specified axis.\n    '''\n    axis = normalize_axis(axis, ndim(x))\n    return tf.reduce_prod(x, reduction_indices=axis, keep_dims=keepdims)\n\n\ndef var(x, axis=None, keepdims=False):\n    axis = normalize_axis(axis, ndim(x))\n    if x.dtype.base_dtype == tf.bool:\n        x = tf.cast(x, _FLOATX)\n    m = tf.reduce_mean(x, reduction_indices=axis, keep_dims=True)\n    devs_squared = tf.square(x - m)\n    return tf.reduce_mean(devs_squared,\n                          reduction_indices=axis,\n                          keep_dims=keepdims)\n\n\ndef std(x, axis=None, keepdims=False):\n    axis = normalize_axis(axis, ndim(x))\n    if x.dtype.base_dtype == tf.bool:\n        x = tf.cast(x, _FLOATX)\n    m = tf.reduce_mean(x, reduction_indices=axis, keep_dims=True)\n    devs_squared = tf.square(x - m)\n    return tf.sqrt(tf.reduce_mean(devs_squared,\n                                  reduction_indices=axis,\n                                  keep_dims=keepdims))\n\n\ndef mean(x, axis=None, keepdims=False):\n    axis = normalize_axis(axis, ndim(x))\n    if x.dtype.base_dtype == tf.bool:\n        x = tf.cast(x, _FLOATX)\n    return tf.reduce_mean(x, reduction_indices=axis, keep_dims=keepdims)\n\n\ndef any(x, axis=None, keepdims=False):\n    '''Bitwise reduction (logical OR).\n\n    Return array of uint8 (0s and 1s).\n    '''\n    axis = normalize_axis(axis, ndim(x))\n    x = tf.cast(x, tf.bool)\n    x = tf.reduce_any(x, reduction_indices=axis, keep_dims=keepdims)\n    return tf.cast(x, tf.uint8)\n\n\ndef argmax(x, axis=-1):\n    if axis < 0:\n        axis = axis % len(x.get_shape())\n    return tf.argmax(x, axis)\n\n\ndef argsort(x, axis=-1):\n    raise NotImplementedError\n\n\ndef argtop_k(x, k=1):\n    ''' See also: tf.nn.in_top_k '''\n    return tf.nn.top_k(x, k)[1]\n\n\ndef argmin(x, axis=-1):\n    if axis < 0:\n        axis = axis % len(x.get_shape())\n    return tf.argmin(x, axis)\n\n\ndef square(x):\n    return tf.square(x)\n\n\ndef abs(x):\n    return tf.abs(x)\n\n\ndef sqrt(x):\n    x = tf.clip_by_value(x, tf.cast(0., dtype=_FLOATX),\n                         tf.cast(np.inf, dtype=_FLOATX))\n    return tf.sqrt(x)\n\n\ndef exp(x):\n    return tf.exp(x)\n\n\ndef log(x):\n    return tf.log(x)\n\n\ndef round(x):\n    return tf.round(x)\n\n\ndef pow(x, a):\n    return tf.pow(x, a)\n\n\ndef clip(x, min_value, max_value):\n    if max_value < min_value:\n        max_value = min_value\n    return tf.clip_by_value(x, tf.cast(min_value, dtype=_FLOATX),\n                            tf.cast(max_value, dtype=_FLOATX))\n\n\ndef maximum(x, y):\n    return tf.maximum(x, y)\n\n\ndef minimum(x, y):\n    return tf.minimum(x, y)\n\n\n# ===========================================================================\n# SHAPE OPERATIONS\n# ===========================================================================\ndef reverse(x, axis=-1):\n    '''Apply [::-1] to appropriate axis'''\n    ndim = len(x.get_shape())\n    dims = [False] * ndim\n    if axis < 0:\n        axis = axis % ndim\n    dims[axis] = True\n    return tf.reverse(x, dims)\n\n\ndef concatenate(tensors, axis=-1):\n    if axis < 0:\n        axis = axis % len(tensors[0].get_shape())\n    return tf.concat(axis, tensors)\n\n\ndef reshape(x, shape):\n    return tf.reshape(x, shape)\n\n\ndef dimshuffle(x, pattern):\n    '''\n    # Arguments\n        pattern: should be a tuple or list of\n            dimension indices, e.g. [0, 2, 1].\n    '''\n    if 'x' in pattern:\n        x = tf.transpose(x, perm=[i for i in pattern if i != 'x'])\n    for i, p in enumerate(pattern):\n        if p == 'x':\n            x = tf.expand_dims(x, i)\n    return x\n\n\ndef resize_images(X, height_factor, width_factor, dim_ordering):\n    '''Resize the images contained in a 4D tensor of shape\n    - [batch, channels, height, width] (for 'th' dim_ordering)\n    - [batch, height, width, channels] (for 'tf' dim_ordering)\n    by a factor of (height_factor, width_factor). Both factors should be\n    positive integers.\n    '''\n    if dim_ordering == 'th':\n        new_height = shape(X)[2].value * height_factor\n        new_width = shape(X)[3].value * width_factor\n        X = dimshuffle(X, [0, 2, 3, 1])\n        X = tf.image.resize_nearest_neighbor(X, (new_height, new_width))\n        return dimshuffle(X, [0, 3, 1, 2])\n    elif dim_ordering == 'tf':\n        new_height = shape(X)[1].value * height_factor\n        new_width = shape(X)[2].value * width_factor\n        return tf.image.resize_nearest_neighbor(X, (new_height, new_width))\n    else:\n        raise Exception('Invalid dim_ordering: ' + dim_ordering)\n\n\ndef repeat_elements(x, rep, axis):\n    '''Repeats the elements of a tensor along an axis, like np.repeat\n\n    If x has shape (s1, s2, s3) and axis=1, the output\n    will have shape (s1, s2 * rep, s3)\n    '''\n    x_shape = x.get_shape().as_list()\n    # slices along the repeat axis\n    splits = tf.split(axis, x_shape[axis], x)\n    # repeat each slice the given number of reps\n    x_rep = [s for s in splits for i in range(rep)]\n    return tf.concat(axis, x_rep)\n\n\ndef repeat(x, n):\n    '''Repeat a 2D tensor:\n\n    if x has shape (samples, dim) and n=2,\n    the output will have shape (samples, 2, dim)\n    '''\n    assert ndim(x) == 2\n    tensors = [x] * n\n    stacked = tf.pack(tensors)\n    return tf.transpose(stacked, (1, 0, 2))\n\n\ndef tile(x, n):\n    return tf.tile(x, n)\n\n\ndef flatten(x, outdim=2):\n    '''Turn a n-D tensor into a m-D tensor (m < n) where\n    the first dimension is conserved.\n    '''\n    if outdim == 1:\n        pattern = [-1]\n    else:\n        pattern = [-1, np.prod(x.get_shape()[(outdim - 1):].as_list())]\n    return tf.reshape(x, pattern)\n\n\ndef expand_dims(x, dim=-1):\n    '''Add a 1-sized dimension at index \"dim\".\n    '''\n    return tf.expand_dims(x, dim)\n\n\ndef squeeze(x, axis):\n    '''Remove a 1-dimension from the tensor at index \"axis\".\n    '''\n    return tf.squeeze(x, [axis])\n\n\ndef temporal_padding(x, padding=1):\n    '''Pad the middle dimension of a 3D tensor\n    with \"padding\" zeros left and right.\n    '''\n    pattern = [[0, 0], [padding, padding], [0, 0]]\n    return tf.pad(x, pattern)\n\n\ndef spatial_2d_padding(x, padding=(1, 1), dim_ordering='th'):\n    '''Pad the 2nd and 3rd dimensions of a 4D tensor\n    with \"padding[0]\" and \"padding[1]\" (resp.) zeros left and right.\n    '''\n    if dim_ordering == 'th':\n        pattern = [[0, 0], [0, 0],\n                   [padding[0], padding[0]], [padding[1], padding[1]]]\n    else:\n        pattern = [[0, 0],\n                   [padding[0], padding[0]], [padding[1], padding[1]],\n                   [0, 0]]\n    return tf.pad(x, pattern)\n\n\ndef stack(*x):\n    return tf.pack(x)\n\n# ===========================================================================\n# VALUE MANIPULATION\n# ===========================================================================\n\n\ndef get_value(x, borrow=False):\n    '''Technically the same as eval() for TF.\n    '''\n    return x.eval(session=get_session())\n\n\ndef set_value(x, value):\n    tf.assign(x, np.asarray(value)).op.run(session=get_session())\n\n\ndef set_subtensor(x, y):\n    raise NotImplementedError\n\n\n# ===========================================================================\n# GRAPH MANIPULATION\n# ===========================================================================\n_GLOBALS_UPDATES = OrderedDict()\n\n\ndef add_global_updates(variable, value):\n    '''trick to update tensorflow variables anywhere\n    This dictionary will be reseted after each time you create a function\n    '''\n    _GLOBALS_UPDATES[variable] = value\n\n\ndef reset_global_updates():\n    global _GLOBALS_UPDATES\n    _GLOBALS_UPDATES = OrderedDict()\n\n\nclass Function(object):\n\n    def __init__(self, inputs, outputs, updates=[]):\n        assert type(inputs) in {list, tuple}\n        if type(outputs) not in {list, tuple}:\n            outputs = [outputs]\n            self._return_list = False\n        else:\n            self._return_list = True\n        if isinstance(updates, OrderedDict):\n            updates = updates.items()\n        assert type(updates) in {list, tuple}\n        self.inputs = list(inputs)\n        self.outputs = list(outputs)\n        with tf.control_dependencies(self.outputs):\n            self.updates = [tf.assign(p, new_p) for (p, new_p) in updates]\n        # ====== add global_update ====== #\n        self.global_update = [tf.assign(p, new_p) for (p, new_p) in _GLOBALS_UPDATES.items()]\n        reset_global_updates()\n\n    def __call__(self, *inputs):\n        assert type(inputs) in {list, tuple}\n        names = [v.name for v in self.inputs]\n        feed_dict = dict(zip(names, inputs))\n        session = get_session()\n        # ====== add global updates ====== #\n        updated = session.run(self.outputs + self.updates + self.global_update,\n            feed_dict=feed_dict)\n        if self._return_list:\n            return updated[:len(self.outputs)]\n        return updated[0]\n\n\ndef function(inputs, outputs, updates=[]):\n    return Function(inputs, outputs, updates=updates)\n\n\ndef gradients(loss, variables, consider_constant=None, known_grads=None):\n    \"\"\"\n    Return symbolic gradients for one or more variables with respect to some\n    cost.\n\n    For more information about how automatic differentiation works in Theano,\n    see :mod:`gradient`. For information on how to implement the gradient of\n    a certain Op, see :func:`grad`.\n\n    Parameters\n    ----------\n    cost : scalar (0-dimensional) tensor variable or None\n        Value with respect to which we are differentiating.  May be\n        `None` if known_grads is provided.\n    wrt : variable or list of variables\n        term[s] for which we want gradients\n    consider_constant : list of expressions(variables)\n        expressions not to backpropagate through\n    known_grads : dict, optional\n        A dictionary mapping variables to their gradients. This is\n        useful in the case where you know the gradient on some\n        variables but do not know the original cost.\n    Returns\n    -------\n    variable or list/tuple of variables (matches `wrt`)\n        symbolic expression of gradient of `cost` with respect to each\n        of the `wrt` terms.  If an element of `wrt` is not\n        differentiable with respect to the output, then a zero\n        variable is returned.\n\n    \"\"\"\n    if consider_constant is not None:\n        for i in consider_constant:\n            tf.stop_gradient(i)\n        raise NotImplementedError\n    grad = tf.gradients(loss, variables)\n    if known_grads is not None:\n        grad = [known_grads[i] if i in known_grads else j\n                for i, j in zip(variables, grad)]\n    return grad\n\n\ndef grad_clip(x, clip):\n    '''\n    This clip the gradient of expression, used on forward pass but clip the\n    gradient on backward pass\n\n    This is an elemwise operation.\n\n    Parameters\n    ----------\n    x: expression\n        the variable we want its gradient inputs clipped\n    lower_bound: float\n        The lower bound of the gradient value\n    upper_bound: float\n        The upper bound of the gradient value.\n\n    Example\n    -------\n    >>> x = theano.tensor.scalar()\n    >>>\n    >>> z = theano.tensor.grad(grad_clip(x, -1, 1)**2, x)\n    >>> z2 = theano.tensor.grad(x**2, x)\n    >>>\n    >>> f = theano.function([x], outputs = [z, z2])\n    >>>\n    >>> print(f(2.0))  # output (1.0, 4.0)\n\n    Note\n    ----\n    We register an opt in tensor/opt.py that remove the GradClip.\n    So it have 0 cost in the forward and only do work in the grad.\n\n    '''\n    # TODO: no implementation for grad_clipping on tensorflow on forward pass\n    return x\n\n\ndef jacobian(expression, wrt):\n    # copying theano's implementation, which is based on scan\n    #from theano.tensor import arange\n    # Check inputs have the right format\n    assert is_variable(expression), \\\n        \"tensor.jacobian expects a Variable as `expression`\"\n    assert expression.ndim < 2, \\\n        (\"tensor.jacobian expects a 1 dimensional variable as \"\n         \"`expression`. If not use flatten to make it a vector\")\n    assert not is_variable(expression.shape[0]), \\\n        \"shape of the expression must be known\"\n\n    using_list = isinstance(wrt, list)\n    using_tuple = isinstance(wrt, tuple)\n\n    if isinstance(wrt, (list, tuple)):\n        wrt = list(wrt)\n    else:\n        wrt = [wrt]\n\n    if expression.ndim == 0:\n        # expression is just a scalar, use grad\n        return _format_as(using_list, using_tuple, gradients(expression, wrt))\n\n    def inner_function(*args):\n        idx = args[0]\n        expr = args[1]\n        rvals = []\n        for inp in args[2:]:\n            try:\n                rval = gradients(expr[idx], inp)\n            except Exception as e:\n                import ipdb; ipdb.set_trace()\n            if rval is None:\n                import ipdb; ipdb.set_trace()\n            rvals.append(rval)\n        return rvals\n    # Computing the gradients does not affect the random seeds on any random\n    # generator used n expression (because during computing gradients we are\n    # just backtracking over old values. (rp Jan 2012 - if anyone has a\n    # counter example please show me)\n    jacobs, updates = scan(inner_function,\n                           sequences=[range(expression.shape[0])],\n                           non_sequences=[expression] + wrt,\n                           n_steps=expression.shape[0])\n    assert not updates\n    return _format_as(using_list, using_tuple, jacobs)\n\n\ndef hessian(expression, wrt):\n    raise NotImplementedError\n\n# ===========================================================================\n# CONTROL FLOW\n# ===========================================================================\n\n\ndef scan(step_fn, sequences=None, outputs_info=None, non_sequences=None,\n    n_steps=None, truncate_gradient=-1, go_backwards=False):\n    from operator import itemgetter\n    # n_steps must be provided under cgt or tensorflow\n    if n_steps is None:\n        raise ValueError(\n            'n_steps must be provided for scan to work under TensorFlow')\n    sequences = _wrap_into_list(sequences)\n    non_sequences = _wrap_into_list(non_sequences)\n    if outputs_info is not None:\n        outputs_info = _wrap_into_list(outputs_info)\n    if go_backwards and n_steps < 0:\n        go_backwards = False\n        n_steps = -n_steps\n    if go_backwards or n_steps < 0:\n        go_backwards = True\n        n_steps = abs(n_steps)\n    step_outputs = []\n    cur_output = outputs_info\n    loop_range = range(n_steps - 1, -1, -1) if go_backwards else range(n_steps)\n    for i in loop_range:\n        # Only pass output if needed\n        if outputs_info is not None:\n            cur_output = step_fn(*(map(itemgetter(i), sequences) + cur_output + non_sequences))\n        else:\n            cur_output = step_fn(*(map(itemgetter(i), sequences) + non_sequences))\n        step_outputs.append(cur_output)\n    outputs = []\n    try:\n        if len(step_outputs) > 0:\n            if outputs_info is None:\n                for i in range(len(step_outputs[0])):\n                    outputs.append(tf.pack(map(itemgetter(i), step_outputs)))\n                #outputs = step_outputs\n            else:\n                for i in range(len(outputs_info)):\n                    outputs.append(tf.pack(map(itemgetter(i), step_outputs)))\n        else:\n            import ipdb; ipdb.set_trace()\n    except Exception as e:\n        raise e\n    # This is quite ugly, but unfortunately it's what theano does\n    if len(outputs) > 1:\n        # update is not supported yet\n        return outputs, None\n    elif len(outputs) == 1:\n        return outputs[0], None\n    else:\n        return None, None\n\n\ndef loop(step_fn, n_steps, sequences=None, outputs_info=None, non_sequences=None,\n         go_backwards=False):\n    \"\"\"\n    Helper function to unroll for loops. Can be used to unroll theano.scan.\n    The parameter names are identical to theano.scan, please refer to here\n    for more information.\n\n    Note that this function does not support the truncate_gradient\n    setting from theano.scan.\n\n    Parameters\n    ----------\n    step_fn : function\n        Function that defines calculations at each step.\n\n    sequences : TensorVariable or list of TensorVariables\n        List of TensorVariable with sequence data. The function iterates\n        over the first dimension of each TensorVariable.\n\n    outputs_info : list of TensorVariables\n        List of tensors specifying the initial values for each recurrent\n        value. Specify output_info to None for non-arguments to\n        the step_function\n\n    non_sequences: list of TensorVariables\n        List of theano.shared variables that are used in the step function.\n\n    n_steps: int\n        Number of steps to unroll.\n\n    go_backwards: bool\n        If true the recursion starts at sequences[-1] and iterates\n        backwards.\n\n    Returns\n    -------\n    List of TensorVariables. Each element in the list gives the recurrent\n    values at each time step.\n\n    \"\"\"\n    if not isinstance(sequences, (list, tuple)):\n        sequences = [] if sequences is None else [sequences]\n\n    # When backwards reverse the recursion direction\n    counter = range(n_steps)\n    if go_backwards:\n        counter = counter[::-1]\n\n    # ====== check if outputs_info is None ====== #\n    output = []\n    if outputs_info is not None:\n        prev_vals = outputs_info\n    else:\n        prev_vals = []\n    output_idx = [i for i in range(len(prev_vals)) if prev_vals[i] is not None]\n    # ====== check if non_sequences is None ====== #\n    if non_sequences is None:\n        non_sequences = []\n    # ====== Main loop ====== #\n    for i in counter:\n        step_input = [s[i] for s in sequences] + \\\n                     [prev_vals[idx] for idx in output_idx] + \\\n            non_sequences\n        out_ = step_fn(*step_input)\n        # The returned values from step can be either a TensorVariable,\n        # a list, or a tuple.  Below, we force it to always be a list.\n        if isinstance(out_, tf.python.Tensor):\n            out_ = [out_]\n        if isinstance(out_, tuple):\n            out_ = list(out_)\n        output.append(out_)\n        prev_vals = output[-1]\n\n    # iterate over each scan output and convert it to same format as scan:\n    # [[output11, output12,...output1n],\n    # [output21, output22,...output2n],...]\n    output_scan = []\n    for i in range(len(output[0])):\n        l = map(lambda x: x[i], output)\n        output_scan.append(tf.pack(l))\n    return output_scan\n\n\ndef rnn(step_function, inputs, initial_states,\n        go_backwards=False, mask=None, constants=None):\n    '''Iterates over the time dimension of a tensor.\n    # Arguments\n        inputs: tensor of temporal data of shape (samples, time, ...)\n            (at least 3D).\n        step_function:\n            Parameters:\n                input: tensor with shape (samples, ...) (no time dimension),\n                    representing input for the batch of samples at a certain\n                    time step.\n                states: list of tensors.\n            Returns:\n                output: tensor with shape (samples, ...) (no time dimension),\n                new_states: list of tensors, same length and shapes\n                    as 'states'.\n        initial_states: tensor with shape (samples, ...) (no time dimension),\n            containing the initial values for the states used in\n            the step function.\n        go_backwards: boolean. If True, do the iteration over\n            the time dimension in reverse order.\n        mask: binary tensor with shape (samples, time, 1),\n            with a zero for every element that is masked.\n        constants: a list of constant values passed at each step.\n    # Returns\n        A tuple (last_output, outputs, new_states).\n            last_output: the latest output of the rnn, of shape (samples, ...)\n            outputs: tensor with shape (samples, time, ...) where each\n                entry outputs[s, t] is the output of the step function\n                at time t for sample s.\n            new_states: list of tensors, latest states returned by\n                the step function, of shape (samples, ...).\n    '''\n    ndim = len(inputs.get_shape())\n    assert ndim >= 3, \"Input should be at least 3D.\"\n    axes = [1, 0] + list(range(2, ndim))\n    inputs = tf.transpose(inputs, (axes))\n    input_list = tf.unpack(inputs)\n    if constants is None:\n        constants = []\n\n    states = initial_states\n    successive_states = []\n    successive_outputs = []\n    if go_backwards:\n        input_list.reverse()\n\n    if mask is not None:\n        # Transpose not supported by bool tensor types, hence round-trip to uint8.\n        mask = tf.cast(mask, tf.uint8)\n        if len(mask.get_shape()) == ndim - 1:\n            mask = expand_dims(mask)\n        mask = tf.cast(tf.transpose(mask, axes), tf.bool)\n        mask_list = tf.unpack(mask)\n\n        for input, mask_t in zip(input_list, mask_list):\n            output, new_states = step_function(input, states + constants)\n\n            # tf.select needs its condition tensor to be the same shape as its two\n            # result tensors, but in our case the condition (mask) tensor is\n            # (nsamples, 1), and A and B are (nsamples, ndimensions). So we need to\n            # broadcast the mask to match the shape of A and B. That's what the\n            # tile call does, is just repeat the mask along its second dimension\n            # ndimensions times.\n            tiled_mask_t = tf.tile(mask_t, tf.pack([1, tf.shape(output)[1]]))\n\n            if len(successive_outputs) == 0:\n                prev_output = zeros_like(output)\n            else:\n                prev_output = successive_outputs[-1]\n\n            output = tf.select(tiled_mask_t, output, prev_output)\n\n            return_states = []\n            for state, new_state in zip(states, new_states):\n                # (see earlier comment for tile explanation)\n                tiled_mask_t = tf.tile(mask_t, tf.pack([1, tf.shape(new_state)[1]]))\n                return_states.append(tf.select(tiled_mask_t, new_state, state))\n\n            states = return_states\n            successive_outputs.append(output)\n            successive_states.append(states)\n    else:\n        for input in input_list:\n            output, states = step_function(input, states + constants)\n            successive_outputs.append(output)\n            successive_states.append(states)\n\n    last_output = successive_outputs[-1]\n    outputs = tf.pack(successive_outputs)\n    new_states = successive_states[-1]\n\n    axes = [1, 0] + list(range(2, len(outputs.get_shape())))\n    outputs = tf.transpose(outputs, axes)\n    return last_output, outputs, new_states\n\n\ndef switch(condition, then_expression, else_expression):\n    '''Switch between two operations depending on a scalar value.\n\n    # Arguments\n        condition: scalar tensor.\n        then_expression: TensorFlow operation.\n        else_expression: TensorFlow operation.\n    '''\n    return tf.python.control_flow_ops.cond(condition,\n                                           lambda: then_expression,\n                                           lambda: else_expression)\n\n\n# ===========================================================================\n# NN OPERATIONS\n# ===========================================================================\ndef relu(x, alpha=0., max_value=None):\n    '''ReLU.\n    # Arguments\n        alpha: slope of negative section.\n        max_value: saturation threshold.\n    '''\n    negative_part = tf.nn.relu(-x)\n    x = tf.nn.relu(x)\n    if max_value is not None:\n        x = tf.clip_by_value(x, tf.cast(0., dtype=_FLOATX),\n                             tf.cast(max_value, dtype=_FLOATX))\n    if isinstance(alpha, (tuple, list, np.ndarray)) or np.isscalar(alpha):\n        alpha = tf.constant(alpha, dtype=_FLOATX)\n    x -= alpha * negative_part\n    return x\n\n\ndef linear(x):\n    return x\n\n\ndef softmax(x):\n    return tf.nn.softmax(x)\n\n\ndef softplus(x):\n    return tf.nn.softplus(x)\n\n\ndef categorical_crossentropy(output, target, from_logits=False):\n    '''Note: tf.nn.softmax_cross_entropy_with_logits\n    expects logits, Keras expects probabilities.\n    '''\n    if not from_logits:\n        # scale preds so that the class probas of each sample sum to 1\n        output /= tf.reduce_sum(output,\n                                reduction_indices=len(output.get_shape()) - 1,\n                                keep_dims=True)\n        # manual computation of crossentropy\n        output = tf.clip_by_value(output, tf.cast(_EPSILON, dtype=_FLOATX),\n                                  tf.cast(1. - _EPSILON, dtype=_FLOATX))\n        return - tf.reduce_sum(target * tf.log(output),\n                               reduction_indices=len(output.get_shape()) - 1)\n    else:\n        return tf.nn.softmax_cross_entropy_with_logits(output, target)\n\n\ndef binary_crossentropy(output, target, from_logits=False):\n    '''Note: tf.nn.sigmoid_cross_entropy_with_logits\n    expects logits, Keras expects probabilities.\n    '''\n    if not from_logits:\n        # transform back to logits\n        output = tf.clip_by_value(output, tf.cast(_EPSILON, dtype=_FLOATX),\n                                  tf.cast(1. - _EPSILON, dtype=_FLOATX))\n        output = tf.log(output / (1 - output))\n    return tf.nn.sigmoid_cross_entropy_with_logits(output, target)\n\n\ndef sigmoid(x):\n    return tf.nn.sigmoid(x)\n\n\ndef hard_sigmoid(x):\n    x = (0.2 * x) + 0.5\n    x = tf.clip_by_value(x, tf.cast(0., dtype=_FLOATX),\n                         tf.cast(1., dtype=_FLOATX))\n    return x\n\n\ndef tanh(x):\n    return tf.nn.tanh(x)\n\n\ndef dropout(x, level, rescale=True, noise_shape=None,\n    seed=None, rng=None):\n    \"\"\"Computes dropout.\n\n    With probability `keep_prob`, outputs the input element scaled up by\n    `1 / keep_prob`, otherwise outputs `0`.  The scaling is so that the expected\n    sum is unchanged.\n\n    By default, each element is kept or dropped independently.  If `noise_shape`\n    is specified, it must be\n    [broadcastable](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)\n    to the shape of `x`, and only dimensions with `noise_shape[i] == shape(x)[i]`\n    will make independent decisions.  For example, if `shape(x) = [k, l, m, n]`\n    and `noise_shape = [k, 1, 1, n]`, each batch and channel component will be\n    kept independently and each row and column will be kept or not kept together.\n\n    Parameters\n    ----------\n    x: A tensor.\n    level: float(0.-1.)\n        probability dropout values in given tensor\n    rescale: bool\n        whether rescale the outputs by dividing the retain probablity\n    noise_shape: A 1-D `Tensor` of type `int32`, representing the\n      shape for randomly generated keep/drop flags.\n    seed: int\n        A Python integer. Used to create random seeds. See\n    rng: `tensor.rng`\n        random generator from tensor class\n    \"\"\"\n    retain_prob = 1. - level\n    if isinstance(rng, _RandomWrapper):\n        seed = rng._rng.randint(10e6)\n    elif seed is None:\n        seed = get_random_magic_seed()\n\n    if noise_shape is not None:\n        # from tensorflow.python.ops import array_ops\n        # shape_x = array_ops.shape(x)\n        noise_shape = tuple([shape(x)[i].value if j is None or j < 0 else j\n                            for i, j in enumerate(noise_shape)])\n    # the dummy 1. works around a TF bug\n    # (float32_ref vs. float32 incomptability)\n    x = tf.nn.dropout(x * 1., retain_prob, noise_shape=noise_shape, seed=seed)\n    if not rescale:\n        x = x * retain_prob\n    return x\n\n# ==================== Regularizations ==================== #\n\n\ndef l2_normalize(x, axis):\n    if axis < 0:\n        axis = axis % len(x.get_shape())\n    return tf.nn.l2_normalize(x, dim=axis)\n\n\ndef l2_regularize(x):\n    return sum(tf.square(x))\n\n\ndef l1_regularize(x):\n    return sum(tf.abs(x))\n\n\ndef jacobian_regularize(hidden, params):\n    ''' Computes the jacobian of the hidden layer with respect to\n    the input, reshapes are necessary for broadcasting the\n    element-wise product on the right axis\n    '''\n    hidden = hidden * (1 - hidden)\n    L = expand_dims(hidden, 1) * expand_dims(params, 0)\n    # Compute the jacobian and average over the number of samples/minibatch\n    L = sum(mean(tf.pow(L, 2), axis=0)) # avr over all samples in batch\n    return mean(L)\n\n\ndef kl_gaussian(mean_, logsigma,\n                prior_mean=0., prior_logsigma=0.,\n                regularizer_scale=1.):\n    ''' KL-divergence between two gaussians.\n    Useful for Variational AutoEncoders. Use this as an activation regularizer\n    Parameters:\n    -----------\n    mean, logsigma: parameters of the input distributions\n    prior_mean, prior_logsigma: paramaters of the desired distribution (note the\n        log on logsigma)\n    regularizer_scale: Rescales the regularization cost. Keep this 1 for most cases.\n\n    Note\n    ----\n    origin implementation from seya:\n    https://github.com/Philip-Bachman/ICML-2015/blob/master/LogPDFs.py\n    Copyright (c) Philip Bachman\n    '''\n    gauss_klds = 0.5 * (prior_logsigma - logsigma +\n            ((tf.exp(logsigma) + pow((mean_ - prior_mean), 2.0)) / tf.exp(prior_logsigma)) - 1.0)\n    return mean(gauss_klds)\n\n\ndef correntropy_regularize(x, sigma=1.):\n    '''\n    Note\n    ----\n    origin implementation from seya:\n    https://github.com/EderSantana/seya/blob/master/seya/regularizers.py\n    Copyright (c) EderSantana\n    '''\n    return -sum(mean(tf.exp(tf.pow(x, 2) / sigma), axis=0)) / tf.sqrt(2 * np.pi * sigma)\n\n# ===========================================================================\n# CONVOLUTIONS\n# ===========================================================================\n\n\ndef conv2d(x, kernel, strides=(1, 1), border_mode='valid', dim_ordering='th',\n           image_shape=None, filter_shape=None):\n    '''Runs on cuDNN if available.\n\n    # Arguments\n        border_mode: string, \"same\" or \"valid\".\n        dim_ordering: whether to use Theano or TensorFlow dimension ordering\n        in inputs/kernels/ouputs.\n    '''\n    if border_mode == 'same':\n        padding = 'SAME'\n    elif border_mode == 'valid':\n        padding = 'VALID'\n    else:\n        raise Exception('Invalid border mode: ' + str(border_mode))\n\n    strides = (1,) + strides + (1,)\n\n    if _FLOATX == 'float64':\n        # tf conv2d only supports float32\n        x = tf.cast(x, 'float32')\n        kernel = tf.cast(kernel, 'float32')\n\n    if dim_ordering == 'th':\n        # TF uses the last dimension as channel dimension,\n        # instead of the 2nd one.\n        # TH input shape: (samples, input_depth, rows, cols)\n        # TF input shape: (samples, rows, cols, input_depth)\n        # TH kernel shape: (depth, input_depth, rows, cols)\n        # TF kernel shape: (rows, cols, input_depth, depth)\n        x = tf.transpose(x, (0, 2, 3, 1))\n        kernel = tf.transpose(kernel, (2, 3, 1, 0))\n        x = tf.nn.conv2d(x, kernel, strides, padding=padding)\n        x = tf.transpose(x, (0, 3, 1, 2))\n    elif dim_ordering == 'tf':\n        x = tf.nn.conv2d(x, kernel, strides, padding=padding)\n    else:\n        raise Exception('Unknown dim_ordering: ' + str(dim_ordering))\n\n    if _FLOATX == 'float64':\n        x = tf.cast(x, 'float64')\n    return x\n\n\ndef conv3d(x, kernel, strides=(1, 1, 1), border_mode='valid', dim_ordering='th',\n           image_shape=None, filter_shape=None):\n    raise NotImplementedError\n\n\ndef pool2d(x, pool_size, strides=(1, 1),\n           border_mode='valid', dim_ordering='th', pool_mode='max'):\n    '''\n    # Arguments\n        pool_size: tuple of 2 integers.\n        strides: tuple of 2 integers.\n        border_mode: one of \"valid\", \"same\".\n        dim_ordering: one of \"th\", \"tf\".\n    '''\n    if border_mode == 'same':\n        padding = 'SAME'\n    elif border_mode == 'valid':\n        padding = 'VALID'\n    else:\n        raise Exception('Invalid border mode: ' + str(border_mode))\n\n    strides = (1,) + strides + (1,)\n    pool_size = (1,) + pool_size + (1,)\n\n    if _FLOATX == 'float64':\n        # tf max_pool only supports float32\n        x = tf.cast(x, 'float32')\n\n    if dim_ordering in {'tf', 'th'}:\n        if dim_ordering == 'th':\n            # TF uses the last dimension as channel dimension,\n            # instead of the 2nd one.\n            # TH input shape: (samples, input_depth, rows, cols)\n            # TF input shape: (samples, rows, cols, input_depth)\n            # TH kernel shape: (depth, input_depth, rows, cols)\n            # TF kernel shape: (rows, cols, input_depth, depth)\n            x = tf.transpose(x, (0, 2, 3, 1))\n        if pool_mode == 'max':\n            x = tf.nn.max_pool(x, pool_size, strides, padding=padding)\n        elif pool_mode == 'avg':\n            x = tf.nn.avg_pool(x, pool_size, strides, padding=padding)\n        else:\n            raise Exception('Invalid pooling mode: ' + str(pool_mode))\n        if dim_ordering == 'th':\n            x = tf.transpose(x, (0, 3, 1, 2))\n    else:\n        raise Exception('Unknown dim_ordering: ' + str(dim_ordering))\n\n    if _FLOATX == 'float64':\n        x = tf.cast(x, 'float64')\n    return x\n\n\ndef pool3d(x, pool_size, strides=(1, 1, 1),\n           border_mode='valid', dim_ordering='th', pool_mode='max'):\n    raise NotImplementedError\n\n# ===========================================================================\n# RANDOMNESS\n# ===========================================================================\n\n\nclass _RandomWrapper(object):\n\n    def __init__(self, rng):\n        super(_RandomWrapper, self).__init__()\n        self._rng = np.random.RandomState(rng)\n        self._state = np.random.RandomState(rng)\n\n    def randint(self):\n        return self._state.randint(10e6)\n\n    def normal(self, shape, mean, std, dtype=_FLOATX):\n        return tf.random_normal(shape=shape, mean=mean, stddev=std,\n            dtype=dtype, seed=self._rng.randint(10e6))\n\n    def uniform(self, shape, low, high, dtype=_FLOATX):\n        return tf.random_uniform(shape=shape, minval=low, maxval=high,\n                             dtype=dtype, seed=self._rng.randint(10e6))\n\n    def binomial(self, shape, p, dtype=_FLOATX):\n        return tf.cast(\n            tf.less(\n                tf.random_uniform(shape=shape, minval=0., maxval=1.,\n                             dtype=_FLOATX, seed=self._rng.randint(10e6)),\n                p),\n            dtype)\n\n\ndef rng(seed=None):\n    if seed is None:\n        seed = get_random_magic_seed()\n    return _RandomWrapper(seed)\n\n\ndef random_normal(shape, mean=0.0, std=1.0, dtype=_FLOATX, seed=None):\n    if seed is None:\n        seed = get_random_magic_seed()\n    return tf.random_normal(shape, mean=mean, stddev=std,\n                            dtype=dtype, seed=seed)\n\n\ndef random_uniform(shape, low=0.0, high=1.0, dtype=_FLOATX, seed=None):\n    if seed is None:\n        seed = get_random_magic_seed()\n    return tf.random_uniform(shape, minval=low, maxval=high,\n                             dtype=dtype, seed=seed)\n\n\ndef random_binomial(shape, p, dtype=_FLOATX, seed=None):\n    if seed is None:\n        seed = get_random_magic_seed()\n    return tf.cast(\n        tf.less(\n            tf.random_uniform(shape=shape, minval=0., maxval=1.,\n                         dtype=dtype, seed=seed),\n            p),\n        dtype)\n\n# ===========================================================================\n# Comparator\n# ===========================================================================\n\n\ndef eq(x, y):\n    \"\"\"a == b\"\"\"\n    return tf.equal(x, y)\n\n\ndef neq(x, y):\n    \"\"\"a != b\"\"\"\n    return tf.not_equal(x, y)\n\n\ndef gt(a, b):\n    \"\"\"a > b\"\"\"\n    return tf.greater(a, b)\n\n\ndef ge(a, b):\n    \"\"\"a >= b\"\"\"\n    return tf.greater_equal(a, b)\n\n\ndef lt(a, b):\n    \"\"\"a < b\"\"\"\n    return tf.less(a, b)\n\n\ndef le(a, b):\n    \"\"\"a <= b\"\"\"\n    return tf.less_equal(a, b)\n\n\ndef one_hot(x, nb_class):\n    ''' x: 1D-integer vector '''\n    shape = x.get_shape()\n    ret = tf.zeros((shape[0].value, nb_class), dtype=_FLOATX)\n    ret[np.arange(shape[0].value), x] = 1\n    return ret\n\n\ndef one_hot_max(x, axis=-1):\n    '''\n    Example\n    -------\n    >>> Input: [[0.0, 0.0, 0.5],\n    >>>         [0.0, 0.3, 0.1],\n    >>>         [0.6, 0.0, 0.2]]\n    >>> Output: [[0.0, 0.0, 1.0],\n    >>>         [0.0, 1.0, 0.0],\n    >>>         [1.0, 0.0, 0.0]]\n    '''\n    if axis < 0:\n        axis = axis % len(x.get_shape())\n    shape = x.get_shape()[axis].value\n    return tf.cast(\n        tf.equal(tf.cast(tf.range(shape), 'int64'),\n                expand_dims(tf.argmax(x, axis))),\n        _FLOATX\n    )\n\n\ndef apply_mask(x, mask):\n    '''\n    x : 3D tensor\n    mask : 2D tensor\n\n    Example\n    -------\n    >>> Input: [128, 500, 120]\n    >>> Mask:  [1, 1, 0]\n    >>> Output: [128, 500, 0]\n    '''\n    return tf.mul(x, tf.expand_dims(mask, -1))\n", "meta": {"hexsha": "c72722e8f83a96fb9a15bbbf179446766073582c", "size": 43735, "ext": "py", "lang": "Python", "max_stars_repo_path": "odin/tensor/tf_backend.py", "max_stars_repo_name": "trungnt13/odin_old", "max_stars_repo_head_hexsha": "e5f44f9b6c483d6498767899315ae56e06fe36c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-02-24T20:41:08.000Z", "max_stars_repo_stars_event_max_datetime": "2016-02-29T02:25:16.000Z", "max_issues_repo_path": "odin/tensor/tf_backend.py", "max_issues_repo_name": "trungnt13/odin", "max_issues_repo_head_hexsha": "e5f44f9b6c483d6498767899315ae56e06fe36c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "odin/tensor/tf_backend.py", "max_forks_repo_name": "trungnt13/odin", "max_forks_repo_head_hexsha": "e5f44f9b6c483d6498767899315ae56e06fe36c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1724875267, "max_line_length": 97, "alphanum_fraction": 0.5825311535, "include": true, "reason": "import numpy,from theano", "num_tokens": 10383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.1969659356847176}}
{"text": "import math\nfrom collections import OrderedDict\n\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n'''\nAdaCos and Ad margin loss taken from https://github.com/4uiiurz1/pytorch-adacos\n'''\n\nclass DropClassBase(nn.Module):\n\n    def __init__(self, num_classes):\n        '''\n        DropClass class which other classifier heads should inherit from\n\n        This is to package the useful wrapper scripts for which classes to include/ignore\n\n        The class has two main modes, called via .drop() and .nodrop(), which sets which method will be\n        called by .forward()\n\n        forward_drop defines the ordinary behaviour\n        forward_nodrop defines the behaviour in which only the remaining class columns are used\n        '''\n        super(DropClassBase, self).__init__()\n        self.n_classes = num_classes\n        self.dropmode = False # Default is the normal behaviour\n        self.set_ignored_classes([])\n        self.combined_class_label = None\n\n    def forward(self, input, label=None):\n        '''\n        input: (batch_size, num_features): FloatTensor\n        label (optional): (batch_size): LongTensor\n        '''\n        if self.dropmode:\n            if label is not None:\n                assert (torch.max(label) < len(self.rem_classes)), 'Contains label out of range of allowed classes: Have they been converted?'\n            return self.forward_drop(input, label=label)\n        else:\n            return self.forward_nodrop(input, label=label)\n\n    def drop(self):\n        self.dropmode = True\n    \n    def nodrop(self):\n        self.dropmode = False\n\n    def forward_drop(self, input, label=None):\n        raise NotImplementedError\n\n    def forward_nodrop(self, input, label=None):\n        raise NotImplementedError\n\n    def set_ignored_classes(self, ignored:list):\n        if len(ignored) != 0:\n            assert min(ignored) >= 0\n            assert max(ignored) < self.n_classes\n        self.ignored = sorted(list(set(ignored)))\n        self.rem_classes = sorted(set(np.arange(self.n_classes)) - set(ignored))\n        self.ldict = OrderedDict({k:v for v, k in enumerate(self.rem_classes)}) #mapping of original label to new index\n        self.idict = OrderedDict({k:v for k, v in enumerate(self.rem_classes)}) #mapping of remaining indexes to original label\n\n    def set_remaining_classes(self, remaining:list):\n        assert min(remaining) >= 0\n        assert max(remaining) < self.n_classes\n        self.rem_classes = sorted(set(remaining))\n        self.ignored = sorted(set(np.arange(self.n_classes)) - set(remaining))\n        self.ldict = OrderedDict({k:v for v, k in enumerate(self.rem_classes)}) #mapping of original label to new index\n        self.idict = OrderedDict({k:v for k, v in enumerate(self.rem_classes)}) #mapping of remaining indexes to original label\n\n    def get_mini_labels(self, label:list):\n        # convert list of labels into new indexes for ignored classes\n        mini_labels = torch.LongTensor(list(map(lambda x: self.ldict[x], label)))\n        return mini_labels\n\n    def get_orig_labels(self, label:list):\n        # convert list of mini_labels into original class labels\n        # assert not self.combined_class_label, 'Combined classes means original labels not recoverable'\n        orig_labels = list(map(lambda x: self.idict[x], label))\n        return orig_labels\n\n    def set_remaining_classes_comb(self, remaining:list):\n        # remaining must not include the combined class\n        assert self.combined_class_label is not None, 'combined_class_label has not been set'\n        assert min(remaining) >= 0\n        assert max(remaining) < self.n_classes\n        remaining.append(self.combined_class_label)\n        self.rem_classes = sorted(set(remaining))\n        self.ignored = sorted(set(np.arange(self.n_classes)) - set(remaining)) # not really ignored, just combined\n        self.ldict = OrderedDict({k:v for v, k in enumerate(self.rem_classes)})\n        for k in self.ignored:\n            self.ldict[k] = self.combined_class_label # set all ignored classes to the combined class label\n        self.idict = OrderedDict({k:v for k, v in enumerate(self.rem_classes)}) # not the original mapping for comb classes\n\nclass DropAffine(DropClassBase):\n\n    def __init__(self, num_features, num_classes):\n        super(DropAffine, self).__init__(num_classes)\n        self.fc = nn.Linear(num_features, num_classes)\n        self.reset_parameters()\n\n    def reset_parameters(self):\n        self.fc.reset_parameters()\n        \n    def forward_nodrop(self, input, label=None):\n        W = self.fc.weight\n        b = self.fc.bias\n        logits = F.linear(input, W, b)\n        return logits\n\n    def forward_drop(self, input, label=None):\n        W = self.fc.weight[self.rem_classes]\n        b = self.fc.bias[self.rem_classes]\n        logits = F.linear(input, W, b)\n        return logits\n\nclass L2SoftMax(DropClassBase):\n\n    def __init__(self, num_features, num_classes):\n        super(L2SoftMax, self).__init__(num_classes)\n        self.W = nn.Parameter(torch.FloatTensor(num_classes, num_features))\n        self.reset_parameters()\n\n    def reset_parameters(self):\n        nn.init.xavier_uniform_(self.W)\n    \n    def forward_nodrop(self, input, label=None):\n        x = F.normalize(input)\n        W = F.normalize(self.W)\n        logits = F.linear(x, W)\n        return logits\n\n    def forward_drop(self, input, label=None):\n        x = F.normalize(input)\n        W = F.normalize(self.W[self.rem_classes])\n        logits = F.linear(x, W)\n        return logits\n\nclass SoftMax(DropClassBase):\n\n    def __init__(self, num_features, num_classes):\n        super(SoftMax, self).__init__(num_classes)\n        self.W = nn.Parameter(torch.FloatTensor(num_classes, num_features))\n        self.reset_parameters()\n\n    def reset_parameters(self):\n        nn.init.xavier_uniform_(self.W)\n    \n    def forward_nodrop(self, input, label=None):\n        x = input\n        W = self.W\n        logits = F.linear(x, W)\n        return logits\n\n    def forward_drop(self, input, label=None):\n        x = input\n        W = self.W[self.rem_classes]\n        logits = F.linear(x, W)\n        return logits\n\nclass XVecHead(DropClassBase):\n\n    def __init__(self, num_features, num_classes, hidden_features=None):\n        super(XVecHead, self).__init__(num_classes)\n        hidden_features = num_features if not hidden_features else hidden_features\n        self.fc_hidden = nn.Linear(num_features, hidden_features)\n        self.nl = nn.LeakyReLU()\n        self.bn = nn.BatchNorm1d(hidden_features)\n        self.fc = nn.Linear(hidden_features, num_classes)\n        self.reset_parameters()\n\n    def reset_parameters(self):\n        self.fc.reset_parameters()\n\n    def forward_nodrop(self, input, label=None):\n        input = self.fc_hidden(input)\n        input = self.nl(input)\n        input = self.bn(input)\n        W = self.fc.weight\n        b = self.fc.bias\n        logits = F.linear(input, W, b)\n        return logits\n\n    def forward_drop(self, input, label=None):\n        input = self.fc_hidden(input)\n        input = self.nl(input)\n        input = self.bn(input)\n        W = self.fc.weight[self.rem_classes]\n        b = self.fc.bias[self.rem_classes]\n        logits = F.linear(input, W, b)\n        return logits\n\n\nclass AMSMLoss(DropClassBase):\n\n    def __init__(self, num_features, num_classes, s=30.0, m=0.4):\n        super(AMSMLoss, self).__init__(num_classes)\n        self.num_features = num_features\n        self.n_classes = num_classes\n        self.s = s\n        self.m = m\n        self.W = nn.Parameter(torch.FloatTensor(num_classes, num_features))\n        self.reset_parameters()\n\n    def reset_parameters(self):\n        nn.init.xavier_uniform_(self.W)\n\n    def forward_nodrop(self, input, label=None):\n        # normalize features\n        x = F.normalize(input)\n        # normalize weights\n        W = F.normalize(self.W)\n        # dot product\n        logits = F.linear(x, W)\n        if label is None:\n            return logits\n        # add margin\n        target_logits = logits - self.m\n        one_hot = torch.zeros_like(logits)\n        one_hot.scatter_(1, label.view(-1, 1).long(), 1)\n        output = logits * (1 - one_hot) + target_logits * one_hot\n        # feature re-scale\n        output *= self.s\n\n        return output\n\n    def forward_drop(self, input, label=None):\n        # normalize features\n        x = F.normalize(input)\n        # normalize weights\n        W = F.normalize(self.W[self.rem_classes])\n        # dot product\n        logits = F.linear(x, W)\n        if label is None:\n            return logits\n        # add margin\n        target_logits = logits - self.m\n        one_hot = torch.zeros_like(logits)\n        one_hot.scatter_(1, label.view(-1, 1).long(), 1)\n        output = logits * (1 - one_hot) + target_logits * one_hot\n        # feature re-scale\n        output *= self.s\n\n        return output\n\n\nclass SphereFace(DropClassBase):\n\n    def __init__(self, num_features, num_classes, s=30.0, m=1.35):\n        super(SphereFace, self).__init__(num_classes)\n        self.num_features = num_features\n        self.n_classes = num_classes\n        self.s = s\n        self.m = m\n        self.W = nn.Parameter(torch.FloatTensor(num_classes, num_features))\n        self.reset_parameters()\n\n    def reset_parameters(self):\n        nn.init.xavier_uniform_(self.W)\n\n    def forward_nodrop(self, input, label=None):\n        # normalize features\n        x = F.normalize(input)\n        # normalize weights\n        W = F.normalize(self.W)\n        # dot product\n        logits = F.linear(x, W)\n        if label is None:\n            return logits\n        # add margin\n        theta = torch.acos(torch.clamp(logits, -1.0 + 1e-7, 1.0 - 1e-7))\n        target_logits = torch.cos(self.m * theta)\n        one_hot = torch.zeros_like(logits)\n        one_hot.scatter_(1, label.view(-1, 1).long(), 1)\n        output = logits * (1 - one_hot) + target_logits * one_hot\n        # feature re-scale\n        output *= self.s\n\n        return output\n    \n    def forward_drop(self, input, label=None):\n        # normalize features\n        x = F.normalize(input)\n        # normalize weights\n        W = F.normalize(self.W[self.rem_classes])\n        # dot product\n        logits = F.linear(x, W)\n        if label is None:\n            return logits\n        # add margin\n        theta = torch.acos(torch.clamp(logits, -1.0 + 1e-7, 1.0 - 1e-7))\n        target_logits = torch.cos(self.m * theta)\n        one_hot = torch.zeros_like(logits)\n        one_hot.scatter_(1, label.view(-1, 1).long(), 1)\n        output = logits * (1 - one_hot) + target_logits * one_hot\n        # feature re-scale\n        output *= self.s\n\n        return output\n\nclass ArcFace(DropClassBase):\n\n    def __init__(self, num_features, num_classes, s=30.0, m=0.50):\n        super(ArcFace, self).__init__(num_classes)\n        self.num_features = num_features\n        self.n_classes = num_classes\n        self.s = s\n        self.m = m\n        self.W = nn.Parameter(torch.FloatTensor(num_classes, num_features))\n        self.reset_parameters()\n\n    def reset_parameters(self):\n        nn.init.xavier_uniform_(self.W)\n\n    def forward_nodrop(self, input, label=None):\n        # normalize features\n        x = F.normalize(input)\n        # normalize weights\n        W = F.normalize(self.W)\n        # dot product\n        logits = F.linear(x, W)\n        if label is None:\n            return logits\n        # add margin\n        theta = torch.acos(torch.clamp(logits, -1.0 + 1e-7, 1.0 - 1e-7))\n        target_logits = torch.cos(theta + self.m)\n        one_hot = torch.zeros_like(logits)\n        one_hot.scatter_(1, label.view(-1, 1).long(), 1)\n        output = logits * (1 - one_hot) + target_logits * one_hot\n        # feature re-scale\n        output *= self.s\n\n        return output\n    \n    def forward_drop(self, input, label=None):\n        # normalize features\n        x = F.normalize(input)\n        # normalize weights\n        W = F.normalize(self.W[self.rem_classes])\n        # dot product\n        logits = F.linear(x, W)\n        if label is None:\n            return logits\n        # add margin\n        theta = torch.acos(torch.clamp(logits, -1.0 + 1e-7, 1.0 - 1e-7))\n        target_logits = torch.cos(theta + self.m)\n        one_hot = torch.zeros_like(logits)\n        one_hot.scatter_(1, label.view(-1, 1).long(), 1)\n        output = logits * (1 - one_hot) + target_logits * one_hot\n        # feature re-scale\n        output *= self.s\n\n        return output\n\nclass AdaCos(DropClassBase):\n\n    def __init__(self, num_features, num_classes, m=0.50):\n        super(AdaCos, self).__init__(num_classes)\n        self.num_features = num_features\n        self.n_classes = num_classes\n        self.s = math.sqrt(2) * math.log(num_classes - 1)\n        self.m = m\n        self.W = nn.Parameter(torch.FloatTensor(num_classes, num_features))\n        self.reset_parameters()\n\n    def reset_parameters(self):\n        nn.init.xavier_uniform_(self.W)\n\n    def forward_nodrop(self, input, label=None):\n        # normalize features\n        x = F.normalize(input)\n        # normalize weights\n        W = F.normalize(self.W)\n        # dot product\n        logits = F.linear(x, W)\n        if label is None:\n            return logits\n        # feature re-scale\n        theta = torch.acos(torch.clamp(logits, -1.0 + 1e-7, 1.0 - 1e-7))\n        one_hot = torch.zeros_like(logits)\n        one_hot.scatter_(1, label.view(-1, 1).long(), 1)\n        with torch.no_grad():\n            B_avg = torch.where(one_hot < 1, torch.exp(self.s * logits), torch.zeros_like(logits))\n            B_avg = torch.sum(B_avg) / input.size(0)\n            theta_med = torch.median(theta[one_hot == 1])\n            self.s = torch.log(B_avg) / torch.cos(torch.min(math.pi/4 * torch.ones_like(theta_med), theta_med))\n        output = self.s * logits\n\n        return output\n\n    def forward_drop(self, input, label=None):\n        # normalize features\n        x = F.normalize(input)\n        # normalize weights\n        W = F.normalize(self.W[self.rem_classes])\n        # dot product\n        logits = F.linear(x, W)\n        if label is None:\n            return logits\n        # feature re-scale\n        theta = torch.acos(torch.clamp(logits, -1.0 + 1e-7, 1.0 - 1e-7))\n        one_hot = torch.zeros_like(logits)\n        one_hot.scatter_(1, label.view(-1, 1).long(), 1)\n        with torch.no_grad():\n            B_avg = torch.where(one_hot < 1, torch.exp(self.s * logits), torch.zeros_like(logits))\n            B_avg = torch.sum(B_avg) / input.size(0)\n            theta_med = torch.median(theta[one_hot == 1])\n            self.s = torch.log(B_avg) / torch.cos(torch.min(math.pi/4 * torch.ones_like(theta_med), theta_med))\n        output = self.s * logits\n\n        return output\n\n\n\n\nclass DisturbLabelLoss(nn.Module):\n\n    def __init__(self, device, disturb_prob=0.1):\n        super(DisturbLabelLoss, self).__init__()\n        self.disturb_prob = disturb_prob\n        self.ce = nn.CrossEntropyLoss()\n        self.device = device\n\n    def forward(self, pred, target):\n        with torch.no_grad():\n            disturb_indexes = torch.rand(len(pred)) < self.disturb_prob\n            target[disturb_indexes] = torch.randint(pred.shape[-1], (int(disturb_indexes.sum()),)).to(self.device)\n        return self.ce(pred, target)\n\n    \nclass LabelSmoothingLoss(nn.Module):\n\n    def __init__(self, smoothing=0.1, dim=-1):\n        super(LabelSmoothingLoss, self).__init__()\n        self.confidence = 1.0 - smoothing\n        self.smoothing = smoothing\n        self.dim = dim\n\n    def forward(self, pred, target):\n        pred = pred.log_softmax(dim=self.dim)\n        with torch.no_grad():\n            true_dist = torch.zeros_like(pred)\n            true_dist.fill_(self.smoothing / (pred.shape[-1] - 1))\n            true_dist.scatter_(1, target.data.unsqueeze(1), self.confidence)\n        return torch.mean(torch.sum(-true_dist * pred, dim=self.dim))", "meta": {"hexsha": "8c204830a6d3589113c20fe7c4b6294a14aecceb", "size": 15892, "ext": "py", "lang": "Python", "max_stars_repo_path": "loss_functions.py", "max_stars_repo_name": "entn-at/dropclass_speaker", "max_stars_repo_head_hexsha": "4f3f7627226986b9b5d8c969f7707237b71c2ddf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2020-02-12T19:27:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T00:14:32.000Z", "max_issues_repo_path": "loss_functions.py", "max_issues_repo_name": "entn-at/dropclass_speaker", "max_issues_repo_head_hexsha": "4f3f7627226986b9b5d8c969f7707237b71c2ddf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-29T03:32:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-29T07:16:20.000Z", "max_forks_repo_path": "loss_functions.py", "max_forks_repo_name": "entn-at/dropclass_speaker", "max_forks_repo_head_hexsha": "4f3f7627226986b9b5d8c969f7707237b71c2ddf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2020-01-31T10:14:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-23T07:39:03.000Z", "avg_line_length": 35.3942093541, "max_line_length": 142, "alphanum_fraction": 0.6233324943, "include": true, "reason": "import numpy", "num_tokens": 3770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.1969659356847176}}
{"text": "#!/usr/bin/python\r\n# -*- coding: UTF-8 -*-\r\n\r\nimport matplotlib\r\nmatplotlib.use('Agg')\r\n\r\n# Pytorch requirements\r\nimport unicodedata\r\nimport string\r\nimport re\r\nimport random\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nfrom torch.nn import init\r\nfrom torch.autograd import Variable\r\nfrom torch import optim\r\nimport torch.nn.functional as F\r\nfrom MatchingLayer import MatchingLayer\r\nimport numpy as np\r\n\r\n\r\nif torch.cuda.is_available():\r\n    dtype = torch.cuda.FloatTensor\r\n    dtype_l = torch.cuda.LongTensor\r\nelse:\r\n    dtype = torch.FloatTensor\r\n    dtype_l = torch.cuda.LongTensor\r\n\r\ndef sinkhorn_knopp(A, iterations=1):\r\n    A_size = A.size()\r\n    for it in range(iterations):\r\n        A = A.view(A_size[0]*A_size[1], A_size[2])\r\n        A = F.softmax(A)\r\n        A = A.view(*A_size).permute(0, 2, 1)\r\n        A = A.view(A_size[0]*A_size[1], A_size[2])\r\n        A = F.softmax(A)\r\n        A = A.view(*A_size).permute(0, 2, 1)\r\n    return A\r\n\r\ndef gmul(input):\r\n    W, x = input\r\n    # x is a tensor of size (bs, N, num_features)\r\n    # W is a tensor of size (bs, N, N, J)\r\n    x_size = x.size()\r\n    W_size = W.size()\r\n    N = W_size[-2]\r\n    J = W_size[-1]\r\n    W = W.split(1, 3)\r\n    W = torch.cat(W, 1).squeeze(3) # W is now a tensor of size (bs, J*N, N)\r\n    output = torch.bmm(W, x) # output has size (bs, J*N, num_features)\r\n    output = output.split(N, 1)\r\n    output = torch.cat(output, 2) # output has size (bs, N, J*num_features)\r\n    return output\r\n\r\nclass Gconv_last(nn.Module):\r\n    def __init__(self, feature_maps, J):\r\n        super(Gconv_last, self).__init__()\r\n        self.num_inputs = J*feature_maps[0]\r\n        self.num_outputs = feature_maps[2]\r\n        self.fc = nn.Linear(self.num_inputs, self.num_outputs)\r\n\r\n    def forward(self, input):\r\n        W = input[0]\r\n        x = gmul(input) # out has size (bs, N, num_inputs)\r\n        x_size = x.size()\r\n        x = x.contiguous()\r\n        x = x.view(x_size[0]*x_size[1], -1)\r\n        x = self.fc(x) # has size (bs*N, num_outputs)\r\n        x = x.view(*x_size[:-1], self.num_outputs)\r\n        return W, x\r\n\r\nclass Gconv(nn.Module):\r\n    def __init__(self, feature_maps, J):\r\n        super(Gconv, self).__init__()\r\n        self.num_inputs = J*feature_maps[0]\r\n        self.num_outputs = feature_maps[2]\r\n        self.fc1 = nn.Linear(self.num_inputs, self.num_outputs // 2)\r\n        self.fc2 = nn.Linear(self.num_inputs, self.num_outputs // 2)\r\n        self.bn = nn.BatchNorm1d(self.num_outputs)\r\n\r\n    def forward(self, input):\r\n        W = input[0]\r\n        x = gmul(input) # out has size (bs, N, num_inputs)\r\n        x_size = x.size()\r\n        x = x.contiguous()\r\n        x = x.view(-1, self.num_inputs)\r\n        x1 = F.relu(self.fc1(x)) # has size (bs*N, num_outputs)\r\n        x2 = self.fc2(x)\r\n        x = torch.cat((x1, x2), 1)\r\n        x = self.bn(x)\r\n        x = x.view(*x_size[:-1], self.num_outputs)\r\n        return W, x\r\n\r\nclass GNN(nn.Module):\r\n    def __init__(self, num_features, num_layers, J):\r\n        super(GNN, self).__init__()\r\n        self.num_features = num_features\r\n        self.num_layers = num_layers\r\n        self.featuremap_in = [1, 1, num_features]\r\n        self.featuremap_mi = [num_features, num_features, num_features]\r\n        self.featuremap_end = [num_features, num_features, num_features]\r\n        self.layer0 = Gconv(self.featuremap_in, J)\r\n        for i in range(num_layers):\r\n            module = Gconv(self.featuremap_mi, J)\r\n            self.add_module('layer{}'.format(i + 1), module)\r\n        self.layerlast = Gconv_last(self.featuremap_end, J)\r\n\r\n    def forward(self, input):\r\n        cur = self.layer0(input)\r\n        for i in range(self.num_layers):\r\n            cur = self._modules['layer{}'.format(i+1)](cur)\r\n        out = self.layerlast(cur)\r\n        return out[1]\r\n\r\n\r\n\r\n\r\n\r\nclass GNN_Matcher(nn.Module):\r\n    def __init__(self, num_features, num_layers, J, matching_layer):\r\n        super(GNN_Matcher, self).__init__()\r\n        self.num_features = num_features\r\n        self.num_layers = num_layers\r\n        self.featuremap_in = [1, 1, num_features]\r\n        self.featuremap_mi = [num_features, num_features, num_features]\r\n        self.featuremap_end = [num_features, num_features, num_features]\r\n        self.layer0 = Gconv(self.featuremap_in, J)\r\n        self.matching_layer = matching_layer\r\n        for i in range(num_layers):\r\n            module = Gconv(self.featuremap_mi, J)\r\n            self.add_module('layer{}'.format(i + 1), module)\r\n        self.layerlast = Gconv_last(self.featuremap_end, J)\r\n\r\n    def forward(self, input):\r\n        cur = self.layer0(input)\r\n        for i in range(self.num_layers):\r\n            cur = self._modules['layer{}'.format(i+1)](cur)\r\n\r\n        out = self.layerlast(cur)\r\n\r\n\r\n        x = out[1]\r\n        outsize = x.size()\r\n\r\n        x = x.sum(2)   # sum along the axis of 'features' from the GNN\r\n        outsize = x.size()\r\n\r\n        \"\"\"\r\n        print(\"after sum\")\r\n        print(\"outsize\")\r\n        print( outsize )\r\n        \"\"\"\r\n\r\n        ns = np.ceil(np.sqrt(x.size()[1])).astype(int)\r\n\r\n        x = self.matching_layer(x.view(1,-1)).view(outsize)\r\n        #x = self.matching_layer(x.view(1,ns,ns))#.view(outsize)\r\n\r\n        return x.view(1,ns,ns)\r\n        #return out[1]\r\n\r\n\r\n\r\n\r\nclass Siamese_GNN(nn.Module):\r\n    def __init__(self, num_features, num_layers, J):\r\n        super(Siamese_GNN, self).__init__()\r\n        self.gnn = GNN(num_features, num_layers, J)\r\n\r\n    def forward(self, g1, g2):\r\n        \"\"\"\r\n        print(\"Inside Siamese GNN forward\")\r\n        print(\"g1 = \")\r\n        print( g1 )\r\n        print(\"g2 = \")\r\n        print( g2 )\r\n        \"\"\"\r\n        emb1 = self.gnn(g1)\r\n        emb2 = self.gnn(g2)\r\n        \"\"\"\r\n        print(\"emb1 = \")\r\n        print( emb1 )\r\n        print(\"emb2 = \")\r\n        print( emb2 )\r\n        print(\"emb2.size() = \")\r\n        print( emb2.size() )\r\n        \"\"\"\r\n\r\n\r\n        # embx are tensors of size (bs, N, num_features)\r\n        out = torch.bmm(emb1, emb2.permute(0, 2, 1))\r\n        return out # out has size (bs, N, N)\r\n\r\n\r\nclass Siamese_Matcher(nn.Module):\r\n    def __init__(self, num_features, num_layers, J, matching_layer):\r\n        super(Siamese_Matcher, self).__init__()\r\n        self.gnn = GNN(num_features, num_layers, J)\r\n        self.matching_layer = matching_layer  #MatchingLayer(nNodes=n, eps=1e-4)\r\n\r\n    def forward(self, g1, g2):\r\n\r\n        emb1 = self.gnn(g1)\r\n        emb2 = self.gnn(g2)\r\n\r\n        # embx are tensors of size (bs, N, num_features)\r\n        out = torch.bmm(emb1, emb2.permute(0, 2, 1))\r\n        outsize = out.size()\r\n        out = self.matching_layer(out.view(1,-1)).view(outsize)\r\n        # adjust training loop to accomodate this output\r\n        return out # out has size (bs, N, N)\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n    # test modules\r\n    bs =  4\r\n    num_features = 10\r\n    num_layers = 5\r\n    N = 8\r\n    x = torch.ones((bs, N, num_features))\r\n    W1 = torch.eye(N).unsqueeze(0).unsqueeze(-1).expand(bs, N, N, 1)\r\n    W2 = torch.ones(N).unsqueeze(0).unsqueeze(-1).expand(bs, N, N, 1)\r\n    J = 2\r\n    W = torch.cat((W1, W2), 3)\r\n    input = [Variable(W), Variable(x)]\r\n    ######################### test gmul ##############################\r\n    # feature_maps = [num_features, num_features, num_features]\r\n    # out = gmul(input)\r\n    # print(out[0, :, num_features:])\r\n    ######################### test gconv ##############################\r\n    # feature_maps = [num_features, num_features, num_features]\r\n    # gconv = Gconv(feature_maps, J)\r\n    # _, out = gconv(input)\r\n    # print(out.size())\r\n    ######################### test gnn ##############################\r\n    # x = torch.ones((bs, N, 1))\r\n    # input = [Variable(W), Variable(x)]\r\n    # gnn = GNN(num_features, num_layers, J)\r\n    # out = gnn(input)\r\n    # print(out.size())\r\n    ######################### test siamese gnn ##############################\r\n    x = torch.ones((bs, N, 1))\r\n    input1 = [Variable(W), Variable(x)]\r\n    input2 = [Variable(W.clone()), Variable(x.clone())]\r\n    siamese_gnn = Siamese_GNN(num_features, num_layers, J)\r\n    out = siamese_gnn(input1, input2)\r\n    print(out.size())\r\n", "meta": {"hexsha": "13509ba37e16ba0cb2855b54f5a1d59074929bb6", "size": 8123, "ext": "py", "lang": "Python", "max_stars_repo_path": "qap-lp/model.py", "max_stars_repo_name": "j-kota/LP-QAP", "max_stars_repo_head_hexsha": "8b972d754f916b1905f4d89d995b6e9cce093595", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "qap-lp/model.py", "max_issues_repo_name": "j-kota/LP-QAP", "max_issues_repo_head_hexsha": "8b972d754f916b1905f4d89d995b6e9cce093595", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qap-lp/model.py", "max_forks_repo_name": "j-kota/LP-QAP", "max_forks_repo_head_hexsha": "8b972d754f916b1905f4d89d995b6e9cce093595", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.492, "max_line_length": 81, "alphanum_fraction": 0.5596454512, "include": true, "reason": "import numpy", "num_tokens": 2218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.1969659356847176}}
{"text": "\"\"\"\n.. class:: SpectraStackingEBOSS\n\n.. moduleauthor:: Johan Comparat <johan.comparat__at__gmail.com>\n\nThe class SpectraStacking is dedicated to stacking spectra from SDSS-IV eBOSS\n\nCurrent version\n\n\"\"\"\nimport os \nimport astropy.io.fits as fits\nimport numpy as n\nfrom scipy.interpolate import interp1d\nimport spectres as sp\n\nmaskLambda = n.loadtxt(os.path.join(os.environ['GIT_ARCHETYPES'],'data',\"dr12-sky-mask.txt\"), unpack=True)\n\nget_path_to_spectrum_v5_13_0 = lambda plate, mjd, fiberid : os.path.join(\n\tos.environ['HOME'], \n\t'SDSS', \n\t'v5_13_0', \n\t'spectra', \n\tstr(int(plate)).zfill(4), \n\t\"spec-\"+str(int(plate)).zfill(4)+\"-\"+str(int(mjd)).zfill(5)+\"-\"+str(int(fiberid)).zfill(4)+\".fits\" \n\t)\n\nget_path_to_spectrum_26 = lambda plate, mjd, fiberid : os.path.join(\n\tos.environ['HOME'], \n\t'SDSS', \n\t'26', \n\t'spectra', \n\tstr(int(plate)).zfill(4), \n\t\"spec-\"+str(int(plate)).zfill(4)+\"-\"+str(int(mjd)).zfill(5)+\"-\"+str(int(fiberid)).zfill(4)+\".fits\" )\n\n\nline_list_abs = n.array([2249.88, 2260.78, 2344.21, 2374.46, 2382.76, 2576.88, 2586.65, 2594.50, 2600.17, 2606.46, 2796.35, 2803.53, 2852.96])\nline_list_abs_names = n.array(['FeII', 'FeII', 'FeII', 'FeII', 'FeII', 'MnII', 'FeII', 'MnII','FeII', 'MnII', 'MgII','MgII','MgI'])\nline_list_em = n.array([2327, 2365.55, 2396.36, 2612.65,2626.45])\nline_list_em_names = n.array(['CII]', 'FeII*', 'FeII*', 'FeII*', 'FeII*'])\n\n\nclass SpectraStackingEBOSS:\n\t\"\"\"\n\tThe model luminosity function class\n\t:param in_file: file containing spectra ids to be stacked\n\t:param Resolution: Resolution\n\t:param out_file: where to output stacks\n\t\"\"\"\n\tdef __init__(self, in_file, out_file, dLambda = 0.0001, dV=-9999, l_start=2.9, l_end=4.04, KZ_input=False, PBKT_input=False, csv_input=False):\n\t\tprint( \"input list:\", in_file )\n\t\tself.in_file = in_file\n\t\tif KZ_input :\n\t\t\tprint('KZ input')\n\t\t\tself.mjds, self.plates, self.fiberids, self.redshifts = n.loadtxt(self.in_file, unpack=True)\n\t\telif PBKT_input :\n\t\t\tprint('PBKT input')\n\t\t\tself.plates, self.mjds, self.fiberids, self.redshifts, self.weights = n.loadtxt(self.in_file, unpack=True)\n\t\telif csv_input :\n\t\t\tprint('csv input list')\n\t\t\tself.plates, self.mjds, self.fiberids, self.redshifts = n.loadtxt(self.in_file, unpack=True, delimiter=',', skiprows=1)\n\t\telse:\n\t\t\tprint('regular input list')\n\t\t\tself.plates, self.mjds, self.fiberids, self.redshifts = n.loadtxt(self.in_file, unpack=True)\n\t\t\n\t\tprint('N spectra = ', len(self.plates))\n\t\tself.out_file = out_file\n\t\tself.dLambda = dLambda\n\t\t#self.wave= 10**n.arange(2.6, 4.0211892990699383, dLambda) # 1500,10500\n\t\tself.wave= 10**n.arange(l_start, l_end, dLambda) # 1500,10500\n\t\tprint('wavelength array', self.wave)\n\t\tself.R = int(1/n.mean((self.wave[1:] -self.wave[:-1])/ self.wave[1:]))\n\t\tprint( \"R=\", n.median(self.R) )\n\t\tself.dV = dV\n\t\tself.survey=\"eBOSS\"\n\t\tself.N_angstrom_masked = 20.\n\t\t#self.run2d = run2d\n\t\t#self.run1d = self.run2d\n\t\t#self.topdirBOSS = os.path.join(os.environ['BOSS_SPECTRO_REDUX'], run2d)\n\n\tdef stack_function(self,specMatrix,specMatrixWeight):\n\t\t\"\"\"Creates the stack.\n\t\t:param specMatrix: matrix of observed spectra\n\t\t:param specMatrixWeight: matrix of the statistical weights used in the LF.\n\t\t\"\"\"\n\t\tstackMed = n.ones_like(n.empty(len(self.wave)))*self.dV\n\t\tstackMean = n.ones_like(n.empty(len(self.wave)))*self.dV\n\t\t#stackMeanWeighted = n.ones_like(n.empty(len(self.wave)))*self.dV\n\t\tstackVar = n.ones_like(n.empty(len(self.wave)))*self.dV\n\t\tstackN = n.ones_like(n.empty(len(self.wave)))*self.dV\n\t\tjackknifes = n.ones_like(n.empty((len(self.wave),10)))*self.dV\n\t\tfor i in range(len(specMatrix.T)):\n\t\t\t\tpt=specMatrix.T[i]\n\t\t\t\twt=specMatrixWeight.T[i]\n\t\t\t\tsel=(pt!=self.dV)\n\t\t\t\t# jackknife sub-sampling\n\t\t\t\trd=n.random.random(len(pt))\n\t\t\t\taim=n.arange(0,1.01,0.1)\n\t\t\t\tjks=n.array([ (rd>aim[jj])&(rd<aim[jj+1]) for jj in range(len(aim)-1) ])\n\t\t\t\tif len(pt[sel])>1:\n\t\t\t\t\t\tstackMed[i] = n.median(pt[sel])\n\t\t\t\t\t\tstackMean[i] = n.mean(pt[sel])\n\t\t\t\t\t\t#stackMeanWeighted[i] = n.average(pt[sel],weights=wt[sel])\n\t\t\t\t\t\tstackN[i] = len(pt[sel])\n\t\t\t\t\t\tinter = n.array([ n.median( pt[sel & (seK==False)] ) for seK in jks ])\n\t\t\t\t\t\tjackknifes[i] = inter\n\t\t\t\t\t\tstackVar[i] = n.std(inter)\n\n\t\twavelength = fits.Column(name=\"wavelength\",format=\"D\", unit=\"Angstrom\", array= self.wave)\n\t\tmedianStack=fits.Column(name=\"medianStack\",format=\"D\", unit=\"erg/s/cm2/Angstrom\", array= n.array(stackMed))\n\t\tmeanStack=fits.Column(name=\"meanStack\",format=\"D\", unit=\"erg/s/cm2/Angstrom\", array= n.array(stackMean))\n\t\t#meanWeightedStack=fits.Column(name=\"meanWeightedStack\",format=\"D\", unit= \"erg/s/cm2/Angstrom\", array= n.array(stackMeanWeighted))\n\t\tjackknifeSpectra=fits.Column(name=\"jackknifeSpectra\",format=\"10D\", unit=\"erg/s/cm2/Angstrom\", array= n.array(jackknifes))\n\t\tjackknifStackErrors=fits.Column(name=\"jackknifStackErrors\",format=\"D\", unit=\"erg/s/cm2/Angstrom\", array= n.array(stackVar))\n\t\tNspectraPerPixel=fits.Column(name=\"NspectraPerPixel\",format=\"D\", unit=\"\", array= n.array(stackN))\n\t\treturn  wavelength, medianStack, meanStack, jackknifStackErrors, jackknifeSpectra, NspectraPerPixel\n\t\t#return  wavelength, medianStack, meanStack, meanWeightedStack, jackknifStackErrors, jackknifeSpectra, NspectraPerPixel\n\n\tdef convertSpectrum(self,redshift):\n\t\t\"\"\"\n\t\tShifts the spectrum in the rest-frame and creates a spectrum with the sampling desired.\n\t\tUses the spectres package from A.C. Carnall\n\t\t:param redshift: redshift of the spectrum\n\t\treturn the new flux and erro flux array\n\t\t\"\"\"\t\n\t\tnwave=self.wavelength/(1+redshift)\n\t\t\n\t\t#inL=(self.wave>nwave.min())&(self.wave<nwave.max())\n\t\t#outL=(inL==False)\n\n\t\t#points=interp1d(nwave,nwave * self.fluxl)\n\t\t#pts=points(self.wave[inL]) / self.wave[inL]\n\t\t#res=n.ones_like(self.wave)*self.dV\n\t\t#res[inL]=pts\n\n\t\t#pointsErr=interp1d(nwave,nwave * self.fluxlErr)\n\t\t#ptsErr=pointsErr(self.wave[inL]) / self.wave[inL]\n\t\t#resErr=n.ones_like(self.wave)*self.dV\n\t\t#resErr[inL]=ptsErr\n\n\t\t#return res, resErr\n\t\twavelength_spectrum = n.hstack(( \n\t\t\tself.wave[0]-10, \n\t\t\tself.wave[0]-5,\n\t\t\tn.min(nwave)-10,\n\t\t\tn.min(nwave)-5,\n\t\t\tnwave,\n\t\t\tn.max(nwave)+5,\n\t\t\tn.max(nwave)+10,\n\t\t\tself.wave[-1]+5, \n\t\t\tself.wave[-1]+10\n\t\t\t))\n\t\t#\n\t\tflux_spectrum = n.hstack(( \n\t\t\tself.dV,self.dV,self.dV,self.fluxl[0],\n\t\t\tself.fluxl,\n\t\t\tself.fluxl[-1],self.dV,self.dV,self.dV\n\t\t\t))\n\t\t#\n\t\tflux_error_spectrum = n.hstack(( \n\t\t\tself.dV,self.dV,self.dV,self.dV,\n\t\t\tself.fluxlErr,\n\t\t\tself.dV,self.dV,self.dV,self.dV\n\t\t\t))\t\n\t\t#\n\t\tfinal_spectrum, final_spectrum_err = sp.spectres(\n\t\t\tself.wave, \n\t\t\twavelength_spectrum, \n\t\t\tflux_spectrum, \n\t\t\tflux_error_spectrum )\n\t\treturn final_spectrum, final_spectrum_err\n\n\n\tdef getSpectra(self, path_to_spectrum):\n\t\thdulist = fits.open(path_to_spectrum)\n\t\twave = 10**hdulist[1].data['loglam']\n\t\tflux = hdulist[1].data['flux']\n\t\tivar = hdulist[1].data['ivar']\n\t\tratio = n.min(abs(10000.*n.log10(n.outer(wave, 1./maskLambda))), axis=1)\n\t\tmargin = 1.5\n\t\tveto_sky = ratio <= margin\n\t\tselection = (veto_sky) & (ivar<=0) & (flux<0.)& (n.isinf(ivar)) & (n.isinf(flux))\n\t\tflux[selection] = n.zeros_like(ivar[selection])\n\t\tivar[selection] = n.zeros_like(ivar[selection])\n\t\tout_sel = (flux>0)&(ivar>0)\n\t\tself.fluxl =flux[out_sel]\n\t\tself.fluxlErr=ivar[out_sel]**(-0.5)\n\t\tself.wavelength = wave[out_sel] #/(1+z)\n\n\tdef fit_UV_continuum(self,x,y,yerr,degree=3):\n\t\t\"\"\"\n\t\tWe then mask out\n\t\tabsorption and emission features and fit a cubic polyno-\n\t\tmial function through the rest of the spectrum. \n\t\tUsing\n\t\tthe best-fit polynomial function as an estimate of the un-\n\t\tderlying continuum, F lambda\n\t\twe normalize the observed spectrum to obtain the continuum-normalized spectrum\n\t\t\"\"\"\t\t\t\t\t\n\t\tself.bad_flags = n.ones(len(x))\n\n\t\t# masking sky contaminated pixels\n\t\tmaskLambda = n.loadtxt(os.path.join(os.environ['GIT_SPM'],'data',\"dr12-sky-mask.txt\"), unpack=True)\n\t\tratio = n.min(abs(10000.*n.log10(n.outer(x, 1./maskLambda))), axis=1)\n\t\tmargin = 1.5\n\t\tveto_sky = ( ratio <= margin )\n\t\t\n\t\t# UV mask\n\t\tUV_mask = (x>2000)&(x<3600)\n\t\t\n\t\t# UV line mask\n\t\tratio = n.min(abs(10000.*n.log10(n.outer(x, 1./line_list_abs))), axis=1)\n\t\tmargin = 8\n\t\tveto_line_abs = ( ratio <= margin )\n\n\t\tratio = n.min(abs(10000.*n.log10(n.outer(x, 1./line_list_em))), axis=1)\n\t\tmargin = 8\n\t\tveto_line_em = ( ratio <= margin )\n\t\t\n\t\t# MASKING BAD DATA\n\t\tbad_data = n.isnan(y) | n.isinf(y) | (y <= 0.0) | n.isnan(yerr) | n.isinf(yerr)\n\t\t# creating new arrays\n\t\tx = x[(UV_mask)&(veto_sky==False)&(bad_data==False)&(veto_line_abs==False)&(veto_line_em==False)] \n\t\ty = y[(UV_mask)&(veto_sky==False)&(bad_data==False)&(veto_line_abs==False)&(veto_line_em==False)] \n\t\tyerr = yerr[(UV_mask)&(veto_sky==False)&(bad_data==False)&(veto_line_abs==False)&(veto_line_em==False)] \n\t\t\n\t\tout=n.polyfit(x, y, degree, w=1/yerr)\n\t\treturn out\n\n\tdef createStackMatrix_Weighted(self):\n\t\t\"\"\"\n\t\tFunction that constructs the stack matrix UV normed\n\t\t\"\"\"\n\t\t# loop over the file with N sorted with luminosity\n\t\tspecMatrix, specMatrixErr, specMatrixWeight=[],[],[]\n\t\tprint('plate, mjd, fiber, z, weights',self.plates[:10], self.mjds[:10], self.fiberids[:10], self.redshifts[:10], self.weights[:10])\n\t\tfor plate, mjd, fiber, redshift, weight in zip(self.plates, self.mjds, self.fiberids, self.redshifts, self.weights):\n\t\t\ttry:\n\t\t\t\t#print(plate, mjd, fiber, redshift)\n\t\t\t\tif plate > 3006 :\n\t\t\t\t\tpath_to_spectrum = get_path_to_spectrum_v5_13_0(plate, mjd, fiber)\n\t\t\t\telse:\n\t\t\t\t\tpath_to_spectrum = get_path_to_spectrum_26(plate, mjd, fiber)\n\t\t\t\t\t\n\t\t\t\tif os.path.isfile(path_to_spectrum):\n\t\t\t\t\tself.getSpectra(path_to_spectrum)\n\t\t\t\t\tpts,ptsErr = self.convertSpectrum(redshift)\n\t\t\t\t\tspecMatrix.append(pts)\n\t\t\t\t\tspecMatrixErr.append(ptsErr)\n\t\t\t\t\tspecMatrixWeight.append(n.ones_like(pts)*weight)\n\t\t\t\telse: # for ELG spectra in v5_10_7\n\t\t\t\t\tpath_to_spectrum = get_path_to_spectrum_v5_13_0(plate, mjd, fiber)\n\t\t\t\t\tif os.path.isfile(path_to_spectrum):\n\t\t\t\t\t\tself.getSpectra(path_to_spectrum)\n\t\t\t\t\t\tpts,ptsErr = self.convertSpectrum(redshift)\n\t\t\t\t\t\tspecMatrix.append(pts)\n\t\t\t\t\t\tspecMatrixErr.append(ptsErr)\n\t\t\t\t\t\tspecMatrixWeight.append(n.ones_like(pts)*weight)\n\t\t\texcept(ValueError,FileNotFoundError):\n\t\t\t\tprint('value / file not found error !',plate, mjd, fiber)\n\n\t\tspecMatrixWeight=n.array(specMatrixWeight)\n\t\tspecMatrix=n.array(specMatrix)\n\t\tspecMatrixErr=n.array(specMatrixErr)\n\t\tn.savetxt(self.out_file+'.specMatrix.dat', specMatrix)\n\t\tn.savetxt(self.out_file+'.specMatrixErr.dat', specMatrixErr)\n\t\tn.savetxt(self.out_file+'.specMatrixWeight.dat', specMatrixWeight)\n\t\n\tdef createStackMatrix(self):\n\t\t\"\"\"\n\t\tFunction that constructs the stack matrix UV normed\n\t\t\"\"\"\n\t\t# loop over the file with N sorted with luminosity\n\t\tspecMatrix, specMatrixErr, specMatrixWeight=[],[],[]\n\t\tprint(self.plates, self.mjds, self.fiberids, self.redshifts)\n\t\tfor plate, mjd, fiber, redshift in zip(self.plates, self.mjds, self.fiberids, self.redshifts):\n\t\t\ttry:\n\t\t\t\tprint(plate, mjd, fiber, redshift)\n\t\t\t\tif plate > 3006 :\n\t\t\t\t\tpath_to_spectrum = get_path_to_spectrum_v5_13_0(plate, mjd, fiber)\n\t\t\t\telse:\n\t\t\t\t\tpath_to_spectrum = get_path_to_spectrum_26(plate, mjd, fiber)\n\t\t\t\t\t\n\t\t\t\tif os.path.isfile(path_to_spectrum):\n\t\t\t\t\tself.getSpectra(path_to_spectrum)\n\t\t\t\t\tpts,ptsErr = self.convertSpectrum(redshift)\n\t\t\t\t\tspecMatrix.append(pts)\n\t\t\t\t\tspecMatrixErr.append(ptsErr)\n\t\t\t\t\tweight=1.\n\t\t\t\t\tspecMatrixWeight.append(n.ones_like(pts)*weight)\n\t\t\t\telse: # for ELG spectra in v5_10_7\n\t\t\t\t\tpath_to_spectrum = get_path_to_spectrum_v5_13_0(plate, mjd, fiber)\n\t\t\t\t\tif os.path.isfile(path_to_spectrum):\n\t\t\t\t\t\tself.getSpectra(path_to_spectrum)\n\t\t\t\t\t\tpts,ptsErr = self.convertSpectrum(redshift)\n\t\t\t\t\t\tspecMatrix.append(pts)\n\t\t\t\t\t\tspecMatrixErr.append(ptsErr)\n\t\t\t\t\t\tweight=1.\n\t\t\t\t\t\tspecMatrixWeight.append(n.ones_like(pts)*weight)\n\t\t\texcept(ValueError,FileNotFoundError):\n\t\t\t\tprint('value / file not found error !',plate, mjd, fiber)\n\n\t\tspecMatrixWeight=n.array(specMatrixWeight)\n\t\tspecMatrix=n.array(specMatrix)\n\t\tspecMatrixErr=n.array(specMatrixErr)\n\t\tn.savetxt(self.out_file+'.specMatrix.dat', specMatrix)\n\t\tn.savetxt(self.out_file+'.specMatrixErr.dat', specMatrixErr)\n\t\tn.savetxt(self.out_file+'.specMatrixWeight.dat', specMatrixWeight)\n\t\n\tdef createStackMatrix_UVnormed(self):\n\t\t\"\"\"\n\t\tFunction that constructs the stack matrix UV normed\n\t\t\"\"\"\n\t\t# loop over the file with N sorted with luminosity\n\t\tspecMatrix, specMatrixErr, specMatrixWeight=[],[],[]\n\t\t\n\t\tfor plate, mjd, fiber, redshift in zip(self.plates, self.mjds, self.fiberids, self.redshifts):\n\t\t\ttry:\n\t\t\t\t#print(plate, mjd, fiber, redshift)\n\t\t\t\tif plate > 3006 :\n\t\t\t\t\tpath_to_spectrum = get_path_to_spectrum_v5_13_0(plate, mjd, fiber)\n\t\t\t\telse:\n\t\t\t\t\tpath_to_spectrum = get_path_to_spectrum_26(plate, mjd, fiber)\n\t\t\t\tif os.path.isfile(path_to_spectrum):\n\t\t\t\t\tself.getSpectra(path_to_spectrum)\n\t\t\t\t\tpts,ptsErr = self.convertSpectrum(redshift)\n\t\t\t\t\tpfit = self.fit_UV_continuum(self.wave, pts ,ptsErr)\n\t\t\t\t\tFcont = n.polyval(pfit, self.wave)\n\t\t\t\t\tspecMatrix.append(pts/Fcont)\n\t\t\t\t\tspecMatrixErr.append(ptsErr/Fcont)\n\t\t\t\t\tspecMatrix.append(pts)\n\t\t\t\t\tspecMatrixErr.append(ptsErr)\n\t\t\t\t\tweight=1.\n\t\t\t\t\tspecMatrixWeight.append(n.ones_like(pts)*weight)\n\t\t\t\telse: # get ELG spectra in v5_10_7\n\t\t\t\t\tpath_to_spectrum = get_path_to_spectrum_v5_13_0(plate, mjd, fiber)\n\t\t\t\t\tif os.path.isfile(path_to_spectrum):\n\t\t\t\t\t\tself.getSpectra(path_to_spectrum)\n\t\t\t\t\t\tpts,ptsErr = self.convertSpectrum(redshift)\n\t\t\t\t\t\tpfit = self.fit_UV_continuum(self.wave, pts ,ptsErr)\n\t\t\t\t\t\tFcont = n.polyval(pfit, self.wave)\n\t\t\t\t\t\tspecMatrix.append(pts/Fcont)\n\t\t\t\t\t\tspecMatrixErr.append(ptsErr/Fcont)\n\t\t\t\t\t\tspecMatrix.append(pts)\n\t\t\t\t\t\tspecMatrixErr.append(ptsErr)\n\t\t\t\t\t\tweight=1.\n\t\t\t\t\t\tspecMatrixWeight.append(n.ones_like(pts)*weight)\n\n\t\t\texcept(ValueError,TypeError,FileNotFoundError):\n\t\t\t\tprint('value or type error !',plate, mjd, fiber)\n\n\t\tspecMatrixWeight=n.array(specMatrixWeight)\n\t\tspecMatrix=n.array(specMatrix)\n\t\tspecMatrixErr=n.array(specMatrixErr)\n\t\tn.savetxt(self.out_file+'.specMatrix.dat', specMatrix)\n\t\tn.savetxt(self.out_file+'.specMatrixErr.dat', specMatrixErr)\n\t\tn.savetxt(self.out_file+'.specMatrixWeight.dat', specMatrixWeight)\n\n\tdef stackSpectra(self):\n\t\t\"\"\"\n\t\tStacks\n\t\t\"\"\"\n\t\t# loop over the file with N sorted with luminosity\n\t\tself.specMatrix = n.loadtxt(self.out_file+'.specMatrix.dat')\n\t\t#specMatrixErr = n.loadtxt(self.out_file+'.specMatrixErr.dat')\n\t\tself.specMatrixWeight = n.loadtxt(self.out_file+'.specMatrixWeight.dat')\n\t\tprint( \"now stacks\" )\n\t\t#wavelength, medianStack, meanStack, meanWeightedStack, jackknifStackErrors, jackknifeSpectra, NspectraPerPixel = self.stack_function( specMatrix ,specMatrixWeight)\n\t\t#cols = fits.ColDefs([wavelength, medianStack, meanStack, meanWeightedStack, jackknifStackErrors, jackknifeSpectra, NspectraPerPixel])\n\t\twavelength, medianStack, meanStack, jackknifStackErrors, jackknifeSpectra, NspectraPerPixel = self.stack_function( self.specMatrix ,self.specMatrixWeight)\n\t\tcols = fits.ColDefs([wavelength, medianStack, meanStack, jackknifStackErrors, jackknifeSpectra, NspectraPerPixel])\n\t\ttbhdu = fits.BinTableHDU.from_columns(cols)\n\t\tprihdr = fits.Header()\n\t\tprihdr['author'] = \"JC\"\n\t\tprihdr['survey'] = self.survey\n\t\tprihdr['in_file'] = os.path.basename(self.in_file)[:-4]\n\t\tprihdr['Nspec'] = len(self.plates)\n\t\tprihdu = fits.PrimaryHDU(header=prihdr)\n\t\tthdulist = fits.HDUList([prihdu, tbhdu])\n\t\tif os.path.isfile(self.out_file):\n\t\t\tos.remove(self.out_file)\n\t\tprint( \"stack written to\", self.out_file )\n\t\tthdulist.writeto(self.out_file)\n\t", "meta": {"hexsha": "e7a85e228e29a6e770e34a94edfe4219e7ff9694", "size": 15287, "ext": "py", "lang": "Python", "max_stars_repo_path": "galaxy/python/SpectraStackingEBOSS.py", "max_stars_repo_name": "AndresSixtos/pyeBOSS", "max_stars_repo_head_hexsha": "4750908c8bc409633bef8f790133e3a1f3f0c9e4", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "galaxy/python/SpectraStackingEBOSS.py", "max_issues_repo_name": "AndresSixtos/pyeBOSS", "max_issues_repo_head_hexsha": "4750908c8bc409633bef8f790133e3a1f3f0c9e4", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "galaxy/python/SpectraStackingEBOSS.py", "max_forks_repo_name": "AndresSixtos/pyeBOSS", "max_forks_repo_head_hexsha": "4750908c8bc409633bef8f790133e3a1f3f0c9e4", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8098958333, "max_line_length": 166, "alphanum_fraction": 0.7070713678, "include": true, "reason": "import numpy,from scipy,import astropy", "num_tokens": 4797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.1969659356847176}}
{"text": "'''\nAndrew Till\nSummer 2014\n\nUtility functions for materials.\n\nReferences:\nmcnp5: MCNP 5 Manual, Volume I, LA-UR-03-1987, Appendix G (MCNP Data Libraries, including S(alpha,beta))\nmcnpdata: Listing of Available ACE Data Tables [for MCNP6], LA-UR-13-21822 (An updated version of the above)\nnjoy2012: The NJOY Nuclear Data Processing System, Version 2012, LA-UR-12-27079 (NJOY 2012 manual)\nendf6: ENDF-6 Formats Manual, BNL-90365-2009 Rev.2 (Description of the ENDF-6 format)\n\nNaming conventions:\n'Thermal name' is specified in materials_materials.py and applies to a material (e.g., ZrH is 'zrh').\n'Element thermal name' includes the (bound) thermal treatment of the material and the applicable \n    element (e.g., H in Zr is 'hzrh'). Uses Hollerith strings specified in Table 21 of MATXSR chapter\n    in NJOY manual (ref: njoy2012).\n    Elsewhere, this is called Sab.\n'Thermal XS name' includes the (bound) thermal treatment of the material, the applicable element,\n    and the applicable type of thermal XS (e.g., the inelastic bound thermal XS for H in ZrH is 'hzrhinel')\n'MCNP thermal name' is the string used by MCNP to refer to a bound thermal treatment of a material along\n    with a consituent element (e.g., the bound thermal XS for H in ZrH is 'h/zr')\nNB: 'free' is used for thermal name, element thermal name, and thermal xs name for free-gas thermal    \n    treatment\nNB: ''/None/'none' is used for thermal name; 'none' is used for element thermal name; [] is used\n    for the thermal xs list (for no thermal treatment)\n'''\n\n#TPL\nimport numpy as np\n\n###############################################################################\ndef get_nearest_points(value, sortedArray):\n    '''If value in sortedArray, return [value], else return two nearest points in sortedArray'''\n    nearestIndex = np.argmin(np.abs(sortedArray - value))\n    nearestPoints = [sortedArray[nearestIndex]]\n    lastIndex = len(sortedArray) - 1\n    if value < sortedArray[nearestIndex] and nearestIndex != 0:\n        nearestPoints.append(sortedArray[nearestIndex-1])\n    elif value > sortedArray[nearestIndex] and nearestIndex != lastIndex:\n        nearestPoints.append(sortedArray[nearestIndex+1])\n    return nearestPoints\n\ndef thin_list(inList, useLinSpacing=True):\n    '''Thin a list by returning the value of the point which is nearest to its two neighbors.'''\n    sortedList = np.array(sorted(inList))\n    # Use [2:] and [:-2] to get sum of distances to neighbors. Add 1 for the indexing to be correct.\n    if useLinSpacing:\n        distance = sortedList[2:] - sortedList[:-2]\n    else:\n        distance = sortedList[2:] / sortedList[:-2]\n    index = np.argmin(distance) + 1\n    return sortedList[index]\n\n###############################################################################\ndef calc_chord_length(fuelRadius):\n    if fuelRadius == 'unshielded':\n        return 1.e10\n    elif fuelRadius:\n        surfaceArea = 2 * np.pi * fuelRadius\n        volume = np.pi * fuelRadius * fuelRadius\n        chordLength = surfaceArea / (4 * volume)\n        return chordLength\n    else:\n        return 0.0\n\ndef has_bondarenko_iteration(Z):\n    if Z <= 5:\n        return False\n    else:\n        return True\n\ndef is_fissionable((Z,A)):\n    if Z >= 89:\n        return True\n    elif (Z,A) in [(88, 223), (88, 226)]:\n        return True\n    else:\n        return False\n\ndef avogadros_number():\n    '''In units of atoms / mole, but multiplied by 1E-24'''\n    return 0.60221413\n    \ndef get_inelastic_thermal_mt_list():\n    '''Ref: Culled from Table 4 in the NJOY manual (ref: njoy2012)'''\n    return set([221, 222, 223, 225, 227, 228, 229, 231, 233, 235, 237, 239, 241, 243, 245])\n\n###############################################################################\ndef format_zaid():\n    '''Use format_ZAID()(**dict) to apply to a dictionary'''\n    return '{Z:d}{A:03d}'.format\n\ndef format_zaid_leading_zeros():\n    return '{Z:02d}{A:03d}'.format\n\ndef format_thermal_filename():\n    return 'endf_th_{Z:02d}_{thermalName}_vii1'.format\n\ndef get_nuclide_dirr(sym, A, elementThermalName, metastableStr=''):\n    '''Returns the directory name for a nuclide'''\n    nuclideName = '{0}-{1}{2}'.format(sym.lower(), A, metastableStr)\n    et2t = get_element_thermal_name_to_thermal_name_dict()\n    if elementThermalName in et2t:\n        thermalName = et2t[elementThermalName]\n        nuclideName = '{0}-{1}'.format(nuclideName, thermalName)\n    return nuclideName\n\ndef get_ace_extension(elementThermalName):\n    '''Returns the ACE extension given an element thermal name. The extension is 9 (as in .90c)\n    if the *nuclide* does not have a bound thermal treatment.'''\n    if elementThermalName in get_non_bound_names():\n        return 9\n    else:\n        et2t = get_element_thermal_name_to_thermal_name_dict()\n        t2ext = get_thermal_name_to_ace_ext_dict()\n        return t2ext[et2t[elementThermalName]]\n\n###############################################################################\ndef get_thermal_name_to_element_thermal_name_dict():\n    '''Returns a dict that maps tuple (Z, thermal_name) to element thermal name (a Hollerith string).\n    Free thermal treatment is not in dict'''\n    return {(1,'poly'): 'hpoly', (1,'h2o'): 'hh2o', (8,'uo2'): 'ouo2', (92,'uo2'): 'uuo2', (1,'zrh'): 'hzrh', (40,'zrh'): 'zrzrh', (6,'graphite'): 'graph', (13,'al'): 'al', (26,'fe'): 'fe'}\n\ndef get_element_thermal_name_to_nuclide_list_dict():\n    '''Returns a dict that maps element thermal name to the (Z,A)'s of the nuclides to which it applies.\n    Free thermal treatment is not in dict. Ref: mcnp5, mcnpdata'''\n    return {'hpoly': [(1,1)], 'hh2o': [(1,1)], 'ouo2': [(8,16), (8,17), (8,18)], 'uuo2': [(92,238)], 'hzrh': [(1,1)], 'zrzrh': [(40,0), (40,90), (40,91), (40,92), (40,94), (40,96)], 'graph': [(6,0), (6,12)], 'al': [(13,27)], 'fe': [(26,56)]}\n\ndef get_element_thermal_name_to_inelastic_mt_number_dict():\n    '''Returns a dict that maps element thermal name to the MT number corresponding to the\n    inelastic thermal XS for that element thermal name. See Tables 4 and 25 in NJOY manual (ref: njoy2012).\n    Should correspond to 'inel' endf numbers in Readgroupr.py's get_endf_mt_list() function.'''\n    return {'free': 221, 'hh2o': 222, 'hpoly': 223, 'ouo2': 239, 'uuo2': 241, 'hzrh': 225, 'zrzrh': 235, 'graph': 229, 'al': 243, 'fe': 245}\n\ndef get_thermal_name_to_nuclide_list_dict():\n    '''Returns a dict that maps thermal name to the (Z,A)'s of the nuclides to which it applies.\n    Free thermal treatment is not in dict'''\n    # Derive this dictionary from previous information\n    Zthermal2elem = get_thermal_name_to_element_thermal_name_dict()\n    elem2ZAs = get_element_thermal_name_to_nuclide_list_dict() \n    # First, initialize each thermal name as an empty set of nuclides\n    thermal2ZAs = {}\n    for (Z,thermalName) in Zthermal2elem:\n        thermal2ZAs[thermalName] = set()\n    # Then, populate nuclides that correspond to that thermal name\n    for (Z,thermalName) in Zthermal2elem:\n        elem = Zthermal2elem[(Z,thermalName)]\n        ZAList = elem2ZAs[elem]\n        thermal2ZAs[thermalName].update(ZAList)\n    return thermal2ZAs\n\ndef get_element_thermal_name_to_thermal_name_dict():\n    '''Returns a dict that maps element thermal name (e.g., hh2o) to thermal name (h2o).\n    Free thermal treatment is not in dict.'''\n    # Derive this dictionary from previous information\n    return {et: t for (Z,t), et in get_thermal_name_to_element_thermal_name_dict().items()}\n\n###############################################################################\ndef get_non_bound_names():\n    '''Returns a set of thermal names that do not use bound cross sections'''\n    return set(['free', '', None, 'none'])\n\ndef get_element_thermal_name_to_thermal_xs_list_dict():\n    '''Returns a dict that maps element thermal name to a list of thermal XS names.\n    See Tables 4 and 25 in NJOY manual (ref: njoy2012)'''\n    return {'free': ['free'], 'none': [], 'hpoly': ['hpolyinel', 'hpolyelas'], 'hh2o': ['hh2o'], 'ouo2': ['ouo2inel', 'ouo2elas'], 'uuo2': ['uuo2inel', 'uuo2elas'], 'hzrh': ['hzrhinel', 'hzrhelas'], 'zrzrh': ['zrzrhinel', 'zrzrhelas'], 'graph': ['graphinel', 'graphelas'], 'al': ['alinel', 'alelas'], 'fe': ['feinel', 'feelas'],}\n\ndef get_element_thermal_name_to_mat_number_dict():\n    '''Returns a dict that maps element thermal name to thermal MAT number.\n    See Table 4 in THERMR chapter of NJOY manual (ref: njoy2012).\n    Change: Manuals say Al is material 45, but the data file has material 53'''\n    return {'free': 0, 'none': 0, 'hpoly': 37, 'hh2o': 1, 'ouo2': 75, 'uuo2': 48, 'hzrh': 7, 'zrzrh': 58, 'graph': 31, 'al': 53, 'fe': 56}\n\ndef get_element_thermal_name_to_bnl_id_dict():\n    '''Returns a dict that maps element thermal name to BNL's ID. Used in URL for automatic downloads.\n    Free thermal treatment not in dict. \n    Can be check at http://www.nndc.bnl.gov/sigma/tree/index.html. Last verified: 05/31/2016.'''\n    return {'hpoly': 15390, 'hh2o': 15391, 'ouo2': 15395, 'uuo2': 15402, 'hzrh': 15392, 'zrzrh': 15403, 'graph': 15389, 'al': 15383, 'fe': 15384}\n    \ndef get_element_thermal_name_to_endf_filename_dict():\n    '''Returns a dict that maps element thermal name to bound thermal ENDF file name'''\n    # Derive this dictionary from previous information\n    ZName2elem = get_thermal_name_to_element_thermal_name_dict()\n    ZName2filename = format_thermal_filename()\n    elem2filename = {}\n    for (Z,thermalName) in ZName2elem:\n        elem = ZName2elem[(Z,thermalName)]\n        elem2filename[elem] = ZName2filename(Z=Z, thermalName=thermalName) \n    for key in ['free', None]:\n        elem2filename[key] = None\n    return elem2filename\n\n###############################################################################\ndef get_thermal_name_to_ace_ext_dict():\n    '''Returns a dict that maps thermal name to ACE extension (e.g., the 9 in 1001.92c).\n    Reasonable extension options include poly (CH2) being 6, benzene (C6H6) being 7, and d2o (D2O) being 8, though these are currently unsupported'''\n    return {'h2o': 0, 'uo2': 1, 'zrh': 2, 'graphite': 3, 'al': 4, 'fe': 5, 'free': 9}\n\ndef get_element_thermal_name_to_mcnp_thermal_name_dict():\n    '''Returns a dict that maps element thermal name to MCNP thermal material name. Ref: mcnp5, mcnpdata'''\n    return {'hpoly': 'poly', 'hh2o': 'lwtr', 'zrzrh': 'zr/h', 'hzrh': 'h/zr', 'uuo2': 'u/o2', 'ouo2': 'o2/u', 'graph': 'grph', 'fe': 'fe56', 'al': 'al27'}\n\ndef get_mcnp_thermal_name_to_main_za_dict():\n    '''Returns a dict that maps MCNP bound thermal material name to the (Z,A) of the nuclide from which to read PENDF tape (for ACE only). Uses nuclide with highest atom fraction.'''\n    return {'poly': (1,1), 'lwtr': (1,1), 'o2/u': (8,16), 'u/o2': (92,238), 'grph': (6,0), 'h/zr': (1,1), 'zr/h': (40,90), 'al27': (13,27), 'fe56': (26,56), }\n\ndef get_mcnp_thermal_name_to_zaid_list_dict():\n    '''Returns a dict that maps MCNP bound thermal material name to a ZZAAA string of the nuclides that use this thermal option. Ref: mcnp5, mcnpdata'''\n    # Derive this dictionary from previous information\n    elem2mcnp = get_element_thermal_name_to_mcnp_thermal_name_dict()\n    elem2ZAs = get_element_thermal_name_to_nuclide_list_dict() \n    ZA2zaid = format_zaid()\n    mcnp2zaid = {}\n    for elem in elem2mcnp:\n        mcnpName = elem2mcnp[elem]\n        ZAList = elem2ZAs[elem]\n        zaidList = [ZA2zaid(Z=Z, A=A) for (Z,A) in ZAList]\n        mcnp2zaid[mcnpName] = zaidList\n    return mcnp2zaid\n    \n###############################################################################\ndef print_newline(verbosity=False):\n    if verbosity:\n        print ''\n", "meta": {"hexsha": "3bf5d14972799f466225f97e763fa93c28e956cc", "size": 11593, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/materials_util.py", "max_stars_repo_name": "attom/barnfire", "max_stars_repo_head_hexsha": "6c9fd7c3ef481ada2a31c8618cfb2a33e135b6ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-09-27T07:25:32.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-27T07:25:32.000Z", "max_issues_repo_path": "src/materials_util.py", "max_issues_repo_name": "attom/barnfire", "max_issues_repo_head_hexsha": "6c9fd7c3ef481ada2a31c8618cfb2a33e135b6ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-02-21T18:26:32.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-21T22:14:41.000Z", "max_forks_repo_path": "src/materials_util.py", "max_forks_repo_name": "attom/barnfire", "max_forks_repo_head_hexsha": "6c9fd7c3ef481ada2a31c8618cfb2a33e135b6ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-01-23T23:13:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-29T17:03:42.000Z", "avg_line_length": 51.296460177, "max_line_length": 329, "alphanum_fraction": 0.6519451393, "include": true, "reason": "import numpy", "num_tokens": 3355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.1969659356847176}}
{"text": "\"\"\" Methods related to galaxy photometry \"\"\"\n\nimport os\nimport warnings\nimport numpy as np\n\nfrom pkg_resources import resource_filename\n\nfrom IPython import embed\n\nfrom astropy.io import fits\nfrom astropy.table import Table, hstack, vstack, join\nfrom astropy.coordinates import SkyCoord\nfrom astropy.coordinates import match_coordinates_sky\nfrom astropy import units\nfrom astropy.cosmology import Planck15 as cosmo\nfrom astropy.wcs import utils as wcs_utils\nfrom astropy.nddata import Cutout2D\nfrom astropy.wcs import WCS\nfrom astropy import stats\n\nfrom photutils import SkyCircularAperture\nfrom photutils import aperture_photometry\n\nfrom frb.galaxies import defs\n\ntry:\n    import extinction\nexcept ImportError:\n    print(\"extinction package not loaded.  Extinction corrections will fail\")\n\n# Photometry globals\ntable_format = 'ascii.fixed_width'\nfill_values_list = [('-999', '0'), ('-999.0', '0')]\nfill_value = -999.\n\ndef merge_photom_tables(new_tbl, old_file, tol=1*units.arcsec, debug=False):\n    \"\"\"\n    Merge photometry tables\n\n    Args:\n        new_tbl (astropy.table.Table):\n            New table of photometry\n        old_file (str or Table):\n            Path to the old table\n\n    Returns:\n        astropy.table.Table:\n            Merged tables\n\n    \"\"\"\n    # File or tbl?\n    if isinstance(old_file, str):\n        # New file?\n        if not os.path.isfile(old_file):\n            return new_tbl\n        # Load me\n        old_tbl = Table.read(old_file, format=table_format)\n    elif isinstance(old_file, Table):\n        old_tbl = old_file\n    else:\n        embed(header='42 of photom')\n    # Coords\n    new_coords = SkyCoord(ra=new_tbl['ra'], dec=new_tbl['dec'], unit='deg')\n    old_coords = SkyCoord(ra=old_tbl['ra'], dec=old_tbl['dec'], unit='deg')\n    idx, d2d, _ = match_coordinates_sky(new_coords, old_coords, nthneighbor=1)\n    match = d2d < tol\n\n\n    # Match?\n    if np.sum(match) == len(new_coords):\n        # Insist on the same RA, DEC\n        new_tbl['ra'] = old_tbl['ra'][idx[0]]\n        new_tbl['dec'] = old_tbl['dec'][idx[0]]\n        # Join\n        merge_tbl = hstack([old_tbl.filled(-999.), new_tbl.filled(-999.)])\n        merge_tbl.remove_columns(['ra_2', 'dec_2'])\n        merge_tbl.rename_columns(['ra_1', 'dec_1'], ['ra', 'dec'])\n        #merge_tbl = join(old_tbl.filled(-999.), new_tbl, join_type='left').filled(-999.)\n    elif np.sum(match) == 0:\n        merge_tbl = vstack([old_tbl, new_tbl]).filled(-999.)\n    else:\n        embed(header='50 of photom')  # Best to avoid!!  Use photom_by_name\n    # Return\n    return merge_tbl\n\ndef photom_by_name(name, filelist):\n    \"\"\"\n    Generate a Table for a given galaxy from a list of photom files\n\n    Warning:  Order matters!  Use best data last\n\n    Args:\n        name (str):\n        filelist (list):\n\n    Returns:\n        astropy.table.Table:\n\n    \"\"\"\n    # Loop on tables\n    final_tbl = None\n    for ifile in filelist:\n        # Load an insure it is a masked Table\n        tbl = Table(Table.read(ifile, format=table_format, fill_values=fill_values_list), masked=True)\n        idx = tbl['Name'] == name\n        if np.sum(idx) == 1:\n            sub_tbl = tbl[idx]\n            if final_tbl is None:\n                final_tbl = sub_tbl\n            else:\n                for key in sub_tbl.keys():\n                    if sub_tbl[key].mask != True:  # Cannot use \"is\"\n                        final_tbl[key] = sub_tbl[key]\n    # Return\n    return final_tbl.filled(fill_value)\n\n\ndef extinction_correction(filt, EBV, RV=3.1, max_wave=None, required=True):\n    \"\"\"\n    calculate MW extinction correction for given filter\n\n    Uses the Fitzpatrick & Massa (2007) extinction law\n\n    Args:\n        filt (str):\n            filter name (name of file without .dat extension)\n        EBV (float):\n            E(B-V) (can get from frb.galaxies.nebular.get_ebv which uses IRSA Dust extinction query\n        RV:\n            from gbrammer/threedhst eazyPy.py -- characterizes MW dust\n        max_wave (float, optional):\n            If set, cut off the calculation at this maximum wavelength.\n            A bit of a hack for the near-IR, in large part because the\n            MW extinction curve ends at 1.4 microns.\n        required (bool, optional):\n            Crash out if the transmission curve is not present\n\n    Returns:\n             float: linear extinction correction\n\n    \"\"\"\n    # Read in filter in Table\n    path_to_filters = os.path.join(resource_filename('frb', 'data'), \n                                   'analysis', 'CIGALE')\n    # Hack for LRIS which does not differentiate between cameras\n    if 'LRIS' in filt:\n        _filter = 'LRIS_{}'.format(filt[-1])\n    else:\n        _filter = filt\n    filter_file = os.path.join(path_to_filters, _filter+'.dat')\n    if not os.path.isfile(filter_file):\n        msg = \"Filter {} is not in the Repo.  Add it!!\".format(filter_file)\n        if required:\n            raise IOError(msg)\n        else:\n            warnings.warn(msg)\n            return 1.\n    filter_tbl = Table.read(filter_file, format='ascii')\n\n    #get wave and transmission (file should have these headers in first row)\n    wave = filter_tbl['col1'].data\n    throughput = filter_tbl['col2'].data\n\n    if max_wave:\n        warnings.warn(\"Cutting off the extinction correction calculation at {} Ang\".format(max_wave))\n        gdwv = wave < max_wave\n        wave = wave[gdwv]\n        throughput = throughput[gdwv]\n\n    #get MW extinction correction\n    AV = EBV * RV\n    #AlAV = nebular.load_extinction('MW')\n    Alambda = extinction.fm07(wave, AV)\n    source_flux = 1.\n\n    #calculate linear correction\n    delta = np.trapz(throughput * source_flux * 10 ** (-0.4 * Alambda), wave) / np.trapz(\n        throughput * source_flux, wave)\n\n    correction = 1./delta\n\n    return correction\n\n\ndef correct_photom_table(photom, EBV, name, max_wave=None, required=True):\n    \"\"\"\n    Correct the input photometry table for Galactic extinction\n    Table is modified in place\n\n    If there is SDSS photometry, we look for the extinction values\n    provided by the Survey itself.\n\n    Uses extinction_correction()\n\n    Args:\n        photom (astropy.table.Table):\n        EBV (float):\n            E(B-V) (can get from frb.galaxies.nebular.get_ebv which uses IRSA Dust extinction query\n        name (str):\\\n            Name of the object to correct\n        required (bool, optional):\n            Crash out if the transmission curve is not present\n\n    \"\"\"\n    # Cut the table\n    mt_name = photom['Name'] == name\n    if not np.any(mt_name):\n        print(\"No matches to input name={}.  Returning\".format(name))\n        return\n    elif np.sum(mt_name) > 1:\n        raise ValueError(\"More than 1 match to input name={}.  Bad idea!!\".format(name))\n    idx = np.where(mt_name)[0][0]\n    cut_photom = photom[idx]  # This is a Row\n\n    # Dust correct\n    for key in photom.keys():\n        if key in ['Name', 'ra', 'dec', 'extinction', 'SDSS_ID',\n                   'run', 'rerun'] or 'err' in key:\n            continue\n        filt = key\n        if filt not in defs.valid_filters:\n            print(\"Assumed filter {} is not in our valid list.  Skipping extinction\".format(\n                filt))\n            continue\n        # -999? -- Not even measured\n        try:\n            if cut_photom[filt] <= -999.:\n                continue\n        except:\n            embed(header='187 in photom')\n        # SDSS\n        if 'SDSS' in filt:\n            if 'extinction_{}'.format(filt[-1]) in photom.keys():\n                print(\"Appying SDSS-provided extinction correction\")\n                cut_photom[key] -= cut_photom['extinction_{}'.format(filt[-1])]\n                continue\n        # Hack for LRIS\n        if 'LRIS' in filt:\n            _filter = 'LRIS_{}'.format(filt[-1])\n        else:\n            _filter = filt\n        # Do it\n        dust_correct = extinction_correction(_filter, EBV, max_wave=max_wave, \n                                             required=required)\n        mag_dust = 2.5 * np.log10(1. / dust_correct)\n        cut_photom[key] += mag_dust\n    # Add it back in\n    photom[idx] = cut_photom\n\ndef sb_at_frb(host, cut_dat:np.ndarray, cut_err:np.ndarray, wcs:WCS, \n          fwhm=3., physical=False, min_uncert=2):\n    \"\"\" Measure the surface brightness at an FRB location\n    in a host galaxy\n\n    Args:\n        host (Host object): host galaxy object from frb repo\n        cut_dat (np.ndarray): data (data from astorpy 2D Cutout object)\n        cut_err (np.ndarray): inverse variance of data (from astropy 2D Cutout object)\n        wcs (WCS): WCS for the cutout\n        fwhm (float, optional): FWHM of the PSF of the image in either\n            pixels or kpc. Defaults to 3 [pix].\n        physical (bool, optional): If True, FWHM is in kpc. Defaults to False.\n        min_uncert (int, optional): Minimum localization unceratainty\n            for the FRB, in pixels.  Defaults to 2.\n\n    Returns:\n        tuple: sb_average, sb_average_err  [counts/sqarcsec]\n    \"\"\"\n    # Generate the x,y grid of coordiantes\n    x = np.arange(np.shape(cut_dat)[0])\n    y = np.arange(np.shape(cut_dat)[1])\n    xx, yy = np.meshgrid(x, y)\n    coords = wcs_utils.pixel_to_skycoord(xx, yy, wcs)\n    xfrb, yfrb = wcs_utils.skycoord_to_pixel(host.frb.coord, wcs)\n    plate_scale = coords[0, 0].separation(coords[0, 1]).to('arcsec').value\n\n    # Calculate total a, b uncertainty (FRB frame)\n    uncerta, uncertb = host.calc_tot_uncert()\n\n    # Put in pixel space\n    uncerta /= plate_scale \n    uncertb /= plate_scale \n\n    # Set a minimum threshold\n    uncerta = max(uncerta, min_uncert)\n    uncertb = max(uncertb, min_uncert)\n        \n    # check if in ellipse -- pixel space!\n    theta = host.frb.eellipse['theta']\n    in_ellipse = ((xx - xfrb.item()) * np.cos(theta) + \n                  (yy - yfrb.item()) * np.sin(theta)) ** 2 / (uncerta ** 2) + (\n                      (xx - xfrb.item()) * np.sin(theta) - (\n                          yy - yfrb.item()) * np.cos(theta)) ** 2 / (uncertb ** 2) <= 1\n    idx = np.where(in_ellipse)\n    xval = xx[idx]\n    yval = yy[idx]\n\n    # x, y gal on the tilted grid (same for frb coords)\n    xp = yval * np.cos(theta) - xval * np.sin(theta)\n    yp = xval * np.cos(theta) + yval * np.sin(theta)\n\n    xpfrb = yfrb.item() * np.cos(theta) - xfrb.item() * np.sin(theta)\n    ypfrb = xfrb.item() * np.cos(theta) + yfrb.item() * np.sin(theta)\n\n    # convert fwhm from pixels to arcsec or kpc to arcsec\n    if physical:\n        fwhm_as = fwhm * units.kpc * cosmo.arcsec_per_kpc_proper(host.z)\n    else:\n        fwhm_as = fwhm * plate_scale * units.arcsec\n\n    # Aperture photometry at every pixel in the ellipse\n    photom = []\n    photom_var = []\n    for i in np.arange(np.shape(idx)[1]):\n        aper = SkyCircularAperture(coords[idx[0][i], idx[1][i]], fwhm_as)\n        apermap = aper.to_pixel(wcs)\n\n        # aperture photometry for psf-size within the galaxy\n        photo_frb = aperture_photometry(cut_dat, apermap)\n        photo_err = aperture_photometry(1 / cut_err, apermap)\n\n        photom.append(photo_frb['aperture_sum'][0])\n        photom_var.append(photo_err['aperture_sum'][0])\n\n    # ff prob distribution\n    p_ff = np.exp(-(xp - xpfrb) ** 2 / (2 * uncerta ** 2)) * np.exp(\n        -(yp - ypfrb) ** 2 / (2 * uncertb ** 2))\n    f_weight = (photom / (np.pi * fwhm_as.value ** 2)) * p_ff  # weighted photometry\n    fvar_weight = (photom_var / (np.pi * fwhm_as.value ** 2)) * p_ff  # weighted sigma\n\n    weight_avg = np.sum(f_weight) / np.sum(p_ff) # per unit area (arcsec^2)\n\n    # Errors\n    weight_var_avg = np.sum(fvar_weight) / np.sum(p_ff)\n    weight_err_avg = np.sqrt(weight_var_avg)\n\n\n    return weight_avg, weight_err_avg\n\n\ndef fractional_flux(cutout, frbdat, hg, nsig=3.):\n    \"\"\"Calculate the fractional flux at the FRB location\n\n    Args:\n        cutout (WCS Cutout2D): astropy 2D Cutout of data around host galaxy\n        frbdat (frb.FRB): frb object loaded from frb repo\n        hg (frb.galaxies.frbgalaxy.FRBHost): host galaxy object loaded from frb repo\n        nsig (float, optional): sigma for FRB localization within which the measurement should be made. Defaults to 3.\n\n    Returns:\n        tuple: median_ff, sig_ff, ff_weight [no units]\n            Median fractional flux, uncertainty\n    \"\"\"\n\n    # get image data from cutout\n    cut_data = cutout.data\n    frbcoord = frbdat.coord\n\n    # shift the data to above zero (all positive values)\n    shift_data = cut_data - np.min(cut_data)\n\n    # make mesh grid\n    if np.shape(cut_data)[0] != np.shape(cut_data)[1]:\n        cut_data = np.resize(cut_data, (np.shape(cut_data)[1], np.shape(cut_data)[1]))\n    x = np.arange(np.shape(cut_data)[0])\n    y = np.arange(np.shape(cut_data)[1])\n    xx, yy = np.meshgrid(x, y)\n    coords = wcs_utils.pixel_to_skycoord(xx, yy, cutout.wcs)\n    xfrb, yfrb = wcs_utils.skycoord_to_pixel(frbcoord, cutout.wcs)\n\n    # Calc plate scale\n    plate_scale = coords[0, 0].separation(coords[0, 1]).to('arcsec').value\n\n    # get a, b, and theta from frb object -- convert to pixel space\n    sig_a, sig_b = hg.calc_tot_uncert()\n    # Put in pixel space\n    sig_a /= plate_scale \n    sig_b /= plate_scale \n\n    # sigma\n    a = nsig * sig_a\n    if a < 1:\n        print('a is less than 1!')\n        a = 3\n\n    b = nsig * sig_b\n    if b < 1:\n        print('b is less than 1!')\n        b = 3\n\n\n    # check if in ellipse -- pixel space!\n    theta = hg.frb.eellipse['theta'] * units.deg\n    in_ellipse = ((xx - xfrb.item()) * np.cos(theta).value + (yy - yfrb.item()) * np.sin(theta).value) ** 2 / (\n            a ** 2) + (\n                         (xx - xfrb.item()) * np.sin(theta).value - (yy - yfrb.item()) * np.cos(\n                     theta).value) ** 2 / (\n                         b ** 2) <= 1\n\n    #print(frbdat.FRB, a, b, np.size(cut_data), np.size(cut_data[in_ellipse]))\n\n    idx = np.where(in_ellipse)\n    xval = xx[idx]\n    yval = yy[idx]\n\n    # x, y gal\n    xp = yval * np.cos(theta).value - xval * np.sin(theta).value\n    yp = xval * np.cos(theta).value + yval * np.sin(theta).value\n\n    xpfrb = yfrb.item() * np.cos(theta).value - xfrb.item() * np.sin(theta).value\n    ypfrb = xfrb.item() * np.cos(theta).value + yfrb.item() * np.sin(theta).value\n\n    # sigma clip data to exclude background\n    clipp = stats.sigma_clip(shift_data, sigma=1, maxiters=5)\n    mask = np.ma.getmask(clipp)\n    masked_dat = shift_data[mask]\n\n    # fractional flux for all values in ellipse\n    fprime_inlocal = []\n    for dat in shift_data[idx]:\n        fprime = np.sum(shift_data[shift_data < dat]) / np.sum(shift_data)\n        fprime_inlocal.append(fprime)\n\n    # ff prob distribution\n    p_ff = np.exp(-(xp - xpfrb) ** 2 / (2 * a ** 2)) * np.exp(-(yp - ypfrb) ** 2 / (2 * b ** 2))\n    f_weight = fprime_inlocal * p_ff  # weighted fractional fluxes\n\n    avg_ff = np.sum(fprime_inlocal * p_ff) / np.sum(p_ff)\n    var_ff = np.sum((fprime_inlocal - avg_ff) ** 2 * p_ff) / np.sum(p_ff)\n    sig_ff = np.sqrt(var_ff)\n\n    med_ff = np.percentile(f_weight, 50)\n    l68, u68 = np.abs(np.percentile(f_weight, (16, 84)))\n\n    # make array into list for writing out\n    f_weight = np.array(f_weight).tolist()\n\n    # return med_ff, med_flux, fprime_inlocal\n    return med_ff, sig_ff, f_weight", "meta": {"hexsha": "48746601f0ee391c239f23b80de2e432f5307f7a", "size": 15154, "ext": "py", "lang": "Python", "max_stars_repo_path": "frb/galaxies/photom.py", "max_stars_repo_name": "Lachimax/FRB", "max_stars_repo_head_hexsha": "aa3bb6828db0cf81931dac35cf7bd7184fc3b598", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "frb/galaxies/photom.py", "max_issues_repo_name": "Lachimax/FRB", "max_issues_repo_head_hexsha": "aa3bb6828db0cf81931dac35cf7bd7184fc3b598", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "frb/galaxies/photom.py", "max_forks_repo_name": "Lachimax/FRB", "max_forks_repo_head_hexsha": "aa3bb6828db0cf81931dac35cf7bd7184fc3b598", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4409090909, "max_line_length": 118, "alphanum_fraction": 0.6125115481, "include": true, "reason": "import numpy,from astropy", "num_tokens": 4190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.19696593568471757}}
{"text": "import numpy as np\nimport util\nimport ctypes\nimport units.springel_units\nimport physicalmodels.attenuation.attenuate as atten\n\ndef checklen(x):\n    return len(np.array(x,ndmin=1));\n\ndef vfloat(x):\n    return x.ctypes.data_as(ctypes.POINTER(ctypes.c_float));\n\ndef fcor(x):\n    return np.array(x,dtype='f',ndmin=1)\n\ndef ok_scan(input,xmax=1.0e10,pos=0):\n    if (pos==1):\n        return (np.isnan(input)==False) & (np.fabs(input)<=xmax) & (input > 0.);\n    else:\n        return (np.isnan(input)==False) & (np.fabs(input)<=xmax);\n\n\ndef get_attenuated_stellar_luminosities( BAND_IDS, star_pos, gas_pos, bh_pos, \\\n                                        stellar_age, stellar_metallicity, stellar_mass, \\\n                                        gas_u, gas_rho, gas_hsml, gas_numh, gas_nume, gas_metallicity, gas_mass, \\\n                                        bh_luminosity, \\\n                                        xrange=0, yrange=0, zrange=0, \\\n                                        INCLUDE_BH=0, SKIP_ATTENUATION=0,\n                                        IMF_SALPETER=0, IMF_CHABRIER=1, \\\n                                        MIN_CELL_SIZE=0.01, OUTER_RANGE_OF_INT=1200., \\\n                                        SCATTERED_FRACTION=0.0, \\\n                                        REDDENING_SMC=0, REDDENING_LMC=0, REDDENING_MW=0, \\\n                                        AGN_MARCONI=0, AGN_HRH=1, AGN_RICHARDS=0, AGN_SDSS=0 ):\n    \n    ## first some basic pre-processing to make sure the numbers are in order\n    if ((checklen(gas_pos[0,:])==3) & (checklen(gas_pos[:,0]) !=3)): gas_pos=np.transpose(gas_pos);\n    if ((checklen(star_pos[0,:])==3) & (checklen(star_pos[:,0]) !=3)): star_pos=np.transpose(star_pos);\n    if (INCLUDE_BH==1):\n        if ((checklen(bh_pos[0,:])==3) & (checklen(bh_pos[:,0]) !=3)): bh_pos=np.transpose(bh_pos);\n    if checklen(stellar_metallicity.shape)>1: stellar_metallicity=stellar_metallicity[:,0];\n    if checklen(gas_metallicity.shape)>1: gas_metallicity=gas_metallicity[:,0];\n    \n    gas_temp = units.springel_units.gas_code_to_temperature(gas_u,gas_nume);\n    gas_metallicity[gas_temp > 1.0e6] = 0.0; ## don't allow hot gas to have dust\n    \n    \n    ## now call the extinction calculation\n    Nstar=checklen(star_pos[0,:]);\n    if (SKIP_ATTENUATION==0):\n        if (INCLUDE_BH==1):\n            Nbh=checklen(bh_pos[0,:]);\n            source_pos=np.zeros(3,Nstar+Nbh);\n            for j in [0,1,2]:\n                source_pos[j,0:Nstar]=star_pos[j,:];\n                source_pos[j,Nstar:Nstar+Nbh]=bh_pos[j,:];\n        else:\n            source_pos=star_pos;\n    \n        LOS_NH, LOS_NH_HOT, LOS_Z = \\\n            return_columns_to_sources( source_pos, gas_pos, \\\n                                              gas_u, gas_rho, gas_hsml, gas_numh, gas_nume, gas_metallicity, gas_mass, \\\n                                              xrange=xrange, yrange=yrange, zrange=zrange, \\\n                                              MIN_CELL_SIZE=MIN_CELL_SIZE, OUTER_RANGE_OF_INT=OUTER_RANGE_OF_INT, \\\n                                              TRIM_PARTICLES=1 );\n\n    else: ## SKIP_ATTENUATION==1\n        N_sources=checklen(star_pos[0,:]);\n        if(INCLUDE_BH==1): N_sources+=checklen(bh_pos[0,:]);\n        NHmin=1.0e10; LOS_NH=np.zeros(N_sources)+NHmin; LOS_NH_HOT=np.copy(LOS_NH); LOS_Z=0.*LOS_NH+1.0;\n    \n    print '<LOS_NH> == ',np.median(LOS_NH),' <LOS_Z> == ',np.median(LOS_Z)\n\n\n    ## alright now we're ready to get the (intrinsic) stellar luminosities\n    nband=checklen(BAND_IDS); lums=np.zeros([nband,Nstar]); nu_eff_l=np.zeros([nband]);\n    for i_band in range(nband):\n        nu_eff_l[i_band] = colors_table(np.array([1.0]),np.array([1.0]), \\\n                                            BAND_ID=BAND_IDS[i_band],RETURN_NU_EFF=1);\n        lums[i_band,:] = stellar_mass * colors_table( stellar_age, stellar_metallicity/0.02, \\\n                                            BAND_ID=BAND_IDS[i_band], CHABRIER_IMF=IMF_CHABRIER, SALPETER_IMF=IMF_SALPETER, CRUDE=1, \\\n                                            UNITS_SOLAR_IN_BAND=1); ## this is such that solar-type colors appear white\n\n    ## if we're using the BH, also get its luminosities at the bands of interest\n    if (INCLUDE_BH==1):\n        Nbh=checklen(bh_pos[0,:]); Nbands=checklen(BAND_IDS); lums_bh=np.zeros([Nbands,Nbh]);\n        for i_bh in range(Nbh):\n            lums_bh[:,i_bh] = util.agn_spectrum( nu_eff_l, np.log10(bh_luminosity[i_bh]), \\\n                                                HRH=AGN_HRH,MARCONI=AGN_MARCONI,RICHARDS=AGN_RICHARDS,SDSS=AGN_SDSS );\n        lums_new=np.zeros([Nbands,Nstar+Nbh]);\n        for i_band in range(Nbands):\n            lums_new[i_band,0:Nstar]=lums[i_band,:];\n            lums_new[i_band,Nstar:Nstar+Nbh]=lums_bh[i_band,:];\n        lums=lums_new\n\n\n    ## call the attenuation routine to get the post-extinction luminosities\n    lums_atten=1.0*lums;\n    LOS_NH_TO_USE = LOS_NH;\n    for i_band in range(checklen(BAND_IDS)):\n        f_atten = attenuate( nu_eff_l[i_band], np.log10(LOS_NH), LOS_Z/0.02, \\\n                                 SMC=REDDENING_SMC, LMC=REDDENING_LMC, MW=REDDENING_MW );\n        lums_atten[i_band,:] = lums[i_band,:] * \\\n                                     ((1.-SCATTERED_FRACTION)*f_atten + SCATTERED_FRACTION);\n    \n    return lums, lums_atten;\n\n\n\n\n##\n## return: los_NH_allgas, los_NH_hotphase, los_gas_metallicity\n##\ndef return_columns_to_sources( source_pos, gas_pos, \\\n                              gas_u, gas_rho, gas_hsml, gas_numh, gas_nume, gas_metallicity, gas_mass, \\\n                              xrange=0, yrange=0, zrange=0, \\\n                              MIN_CELL_SIZE=0.01, OUTER_RANGE_OF_INT=1200., \\\n                              TRIM_PARTICLES=1 ):\n    \n    ## check the ordering of the position matrices:\n    if ((checklen(gas_pos[0,:])==3) & (checklen(gas_pos[:,0]) !=3)): gas_pos=np.transpose(gas_pos);\n    if ((checklen(source_pos[0,:])==3) & (checklen(source_pos[:,0]) !=3)): source_pos=np.transpose(source_pos);\n    ## and that metallicities are a vector, not a matrix\n    if (len(gas_metallicity.shape)>1): gas_metallicity=gas_metallicity[:,0]\n    \n    if ((checklen(gas_pos[:,0]) != 3) | (checklen(gas_pos[0,:]) <= 1)):\n        print 'ERROR WILL OCCUR :: need pos to be (3,N)'\n    \n    x=source_pos[0,:] ; y=source_pos[1,:] ; z=source_pos[2,:]\n    if(checklen(xrange)<=1): xrange=[np.min(x),np.max(x)];\n    if(checklen(yrange)<=1): yrange=[np.min(y),np.max(y)];\n    xr=xrange; yr=yrange;\n    if(checklen(zrange)<=1):\n        zrr=np.sqrt((xr[1]-xr[0])**2.+(yr[1]-yr[0])**2.)/np.sqrt(2.);\n        zmin=np.median(z)-zrr; zmax=np.median(z)+zrr;\n        if (np.min(z) > zmin): zmin=np.min(z);\n        zrange=[zmin,zmax]; print 'z_range (calc) == ',zrange\n    zr=zrange;\n    x00=0.5*(xr[1]+xr[0]); y00=0.5*(yr[1]+yr[0]); z00=0.5*(zr[1]+zr[0]);\n    tolfac = 1.0e10;\n    if (TRIM_PARTICLES==1):\n        tolfac = 0.05;\n    #tolfac = -0.01;\n    ## trim down the incoming list to only whats in the range plotted\n    ##   (saves a ton of time and memory overflow crashes)\n    \n    dx=(0.5+tolfac)*(xr[1]-xr[0]); dy=(0.5+tolfac)*(yr[1]-yr[0]); dz=(0.5+tolfac)*(zr[1]-zr[0]);\n    ok_sources=ok_scan(x-x00,xmax=dx) & ok_scan(y-y00,xmax=dy) & ok_scan(z-z00,xmax=dz);\n    x=gas_pos[0,:] ; y=gas_pos[1,:] ; z=gas_pos[2,:]\n    gw=gas_rho ; gh=gas_hsml ; gz=gas_metallicity ; gm=gas_mass\n    ok_gas=ok_scan(x-x00,xmax=dx) & ok_scan(y-y00,xmax=dy) & ok_scan(z-z00,xmax=dz) & \\\n        ok_scan(gw,pos=1) & ok_scan(gh,pos=1) & ok_scan(gz,pos=1) & ok_scan(gm,pos=1,xmax=1.0e40);\n    \n    Ngas = checklen(gas_mass[ok_gas]);\n    Nstars = checklen(source_pos[0,ok_sources]);\n    if (Nstars<=1) or (Ngas<=1):\n        print ' UH-OH: EXPECT ERROR NOW, there are no valid source/gas particles to send!'\n        print 'Ngas=',Ngas,'Nstars=',Nstars,'dx=',dx,'dy=',dy,'dz=',dz,'x00=',x00,'y00=',y00,'z00=',z00\n        return -1,-1,-1;\n    \n    dzmax=np.max(gas_pos[2,ok_gas])-z00;\n    if(dzmax<OUTER_RANGE_OF_INT): OUTER_RANGE_OF_INT=dzmax;\n    print 'PASSING: N_gas=',Ngas,'N_sources=',Nstars,'MaxDist=',OUTER_RANGE_OF_INT,'MinCell=',MIN_CELL_SIZE;\n    Nbh=0; theta=1.0e-4; phi=1.0e-4;\n\n    ## load the routine we need\n    exec_call=util.dir.c_routines_dir()+'/LOS_column_singlePOV/getnh.so'\n    NH_routine=ctypes.cdll[exec_call];\n\n\n\n    ## cast the variables to store the results\n    nh_out_cast=ctypes.c_float*Nstars;\n    los_NH_out=nh_out_cast(); los_NH_hot_out=nh_out_cast(); los_Z_out=nh_out_cast();\n\n    ## ok this is a bit arcane but the routine will read appropriately this block order\n    Coord = np.zeros((Ngas+Nstars,10),dtype='f');\n    Coord[0:Ngas,0] = gas_pos[0,ok_gas]-x00;\n    Coord[0:Ngas,1] = gas_pos[1,ok_gas]-y00;\n    Coord[0:Ngas,2] = gas_pos[2,ok_gas]-z00;\n    Coord[0:Ngas,3] = gas_u[ok_gas]\n    Coord[0:Ngas,4] = gas_rho[ok_gas]\n    Coord[0:Ngas,5] = gas_hsml[ok_gas]\n    Coord[0:Ngas,6] = gas_numh[ok_gas]\n    Coord[0:Ngas,7] = gas_nume[ok_gas]\n    Coord[0:Ngas,8] = gas_metallicity[ok_gas]\n    Coord[0:Ngas,9] = gas_mass[ok_gas]\n    Coord[Ngas:Nstars+Ngas,0] = source_pos[0,ok_sources]-x00;\n    Coord[Ngas:Nstars+Ngas,1] = source_pos[1,ok_sources]-y00;\n    Coord[Ngas:Nstars+Ngas,2] = source_pos[2,ok_sources]-z00;\n    Coord=np.copy(np.transpose(Coord));\n\n    ## main call to the NH-calculation routine\n    NH_routine.getnh(   ctypes.c_int(Ngas),\n                        ctypes.c_int(Nstars),\n                        ctypes.c_int(Nbh),\n                        ctypes.c_float(theta),\n                        ctypes.c_float(phi),\n                        vfloat(Coord),\n                        ctypes.byref(los_NH_out),\n                        ctypes.byref(los_NH_hot_out),\n                        ctypes.byref(los_Z_out),\n                        ctypes.c_float(OUTER_RANGE_OF_INT),\n                        ctypes.c_float(MIN_CELL_SIZE) );\n    ## now put the output arrays into a useful format\n    print type(los_NH_out), los_NH_out\n    los_NH = np.ctypeslib.as_array(los_NH_out);     # removed a np.copy() as below\n    los_NH_hot = np.ctypeslib.as_array(np.copy(los_NH_hot_out));\n    los_Z = np.ctypeslib.as_array(np.copy(los_Z_out));\n     \n    # trap for really low NH value and zero metallicity (make it small instead)\n    low_NH = 1.0e10;\n    los_NH[los_NH<low_NH]=low_NH; los_NH_hot[los_NH_hot<low_NH]=low_NH;\n    los_Z[los_Z<=1.0e-5]=1.0e-5;\n     \n    ## assign strong attenuation to all 'off-grid' sources, then fill in calc. vals\n    Nstarstot=checklen(source_pos[0,:]);\n    los_NH_allgas=np.zeros(Nstarstot,dtype='f')+1.0e23;\n    los_NH_hotgas=np.zeros(Nstarstot,dtype='f')+1.0e23;\n    los_gas_metallicity=np.zeros(Nstarstot,dtype='f')+0.02;\n    nok=checklen(los_NH_allgas[ok_sources])\n    los_NH_allgas[ok_sources]=fcor(los_NH[0:Nstars]);\n    los_NH_hotgas[ok_sources]=fcor(los_NH_hot[0:Nstars]);\n    los_gas_metallicity[ok_sources]=fcor(los_Z[0:Nstars]);\n\n    return los_NH_allgas, los_NH_hotgas, los_gas_metallicity;\n\n\n\n## routines from colors_sps module\ndef colors_table( age_in_Gyr, metallicity_in_solar_units,\n                 BAND_ID=0, SALPETER_IMF=0, CHABRIER_IMF=1, QUIET=0, CRUDE=0,\n                 RETURN_NU_EFF=0, RETURN_LAMBDA_EFF=0, UNITS_SOLAR_IN_BAND=0 ):\n    return colors_table( age_in_Gyr, metallicity_in_solar_units,\n                             BAND_ID=BAND_ID, SALPETER_IMF=SALPETER_IMF, CHABRIER_IMF=CHABRIER_IMF, QUIET=QUIET, CRUDE=CRUDE,\n                             RETURN_NU_EFF=RETURN_NU_EFF, RETURN_LAMBDA_EFF=RETURN_LAMBDA_EFF, UNITS_SOLAR_IN_BAND=UNITS_SOLAR_IN_BAND )\n\n\ndef colors_table( age_in_Gyr, metallicity_in_solar_units,\n                 BAND_ID=0, SALPETER_IMF=0, CHABRIER_IMF=1, QUIET=0, CRUDE=0,\n                 RETURN_NU_EFF=0, RETURN_LAMBDA_EFF=0, UNITS_SOLAR_IN_BAND=0 ):\n    \n    #import utilities as util\n    import numpy as np\n    import scipy.ndimage.interpolation as interpolate\n    import struct\n    \n    age_in_Gyr=np.array(age_in_Gyr,ndmin=1);\n    metallicity_in_solar_units=np.array(metallicity_in_solar_units,ndmin=1);\n    \n    band=BAND_ID; # default=bolometric\n    j = [  0,  6,  7,  8,  9, 10, 11, 12, 13,  1,   2,   3,   4,   5] # ordering I'm used to\n    i = [  0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10,  11,  12,  13] # ordering of this\n    band_standardordering = band\n    band = j[band]\n    if (band > 13):\n        print 'BAND_ID must be < 13';\n        return 0;\n    \n    b=['Bolometric', \\\n       'Sloan u','Sloan g','Sloan r','Sloan i','Sloan z', \\\n       'Johnsons U','Johnsons B', 'Johnsons V','Johnsons R','Johnsons I', \\\n       'Cousins J','Cousins H','Cousins K']\n    if (QUIET==0): print 'Calculating M/L in '+str(b[band])+' ('+str(band)+','+str(band_standardordering)+')'\n    \n    if (RETURN_NU_EFF==1) or (RETURN_LAMBDA_EFF==1):\n        lam_eff=np.array([1.e-5, 3541., 4653., 6147., 7461., 8904., 3600., 4400., \\\n                          5556., 6940., 8700., 12150., 16540., 21790.]);\n        nu_eff = 2.998e18 / lam_eff;\n        if (RETURN_NU_EFF==1): return nu_eff[band];\n        if (RETURN_LAMBDA_EFF==1): return lam_eff[band];\n\n#froot = util.return_python_routines_homedir()+'/colors_sps/'; # directory in which the data binaries are stored\n    if (CHABRIER_IMF==1): fname=util.dir.sps_dir()+'colors.chabrier.dat'\n    if (SALPETER_IMF==1): fname=util.dir.sps_dir()+'colors.salpeter.dat'\n\n    lut = open(fname,'r');\n    lut_dat = lut.read();\n    Nl,Na,Nz = struct.unpack('3i',lut_dat[0:12])\n    z_grid = np.array(struct.unpack(str(Nz)+'d',lut_dat[12:12+8*Nz]))\n    age_grid = np.array(struct.unpack(str(Na)+'d',lut_dat[12+8*Nz:12+8*Nz+8*Na]))\n    l_all_l = np.array(struct.unpack(str(Nl*Na*Nz)+'d',lut_dat[12+8*Nz+8*Na:12+8*Nz+8*Na+8*Nl*Na*Nz]))\n    l_all = np.transpose(l_all_l.reshape(Nz,Na,Nl))\n    lut.close()\n    \n    l_band = np.zeros((Na,Nz),dtype=np.float64);\n    for iz in range(Nz): l_band[:,iz]=l_all[band,:,iz]\n    \n    # allow for extreme metallicities (extrapolate linearly past table)\n    push_metals = 1;\n    if (push_metals==1):\n        Nz = Nz + 1;\n        z_ext = [1000.0];\n        z_grid = np.concatenate([z_grid,z_ext])\n        lb1 = l_band[:,Nz-3]\n        lb2 = l_band[:,Nz-2]\n        lbx = np.zeros((Na,Nz),dtype=np.float64)\n        lbx[:,0:Nz-1] = l_band\n        lbx[:,Nz-1] = (lb2 - lb1) / (np.log10(z_grid[Nz-2]/z_grid[Nz-3])) * \\\n            np.log10(z_grid[Nz-1]/z_grid[Nz-2])\n        l_band = lbx;\n\n    # get the x-axis (age) locations of input points\n    ia_pts=np.interp(np.log10(age_in_Gyr)+9.0,age_grid,np.arange(0,Na,1));\n    # this returns the boundary values for points outside of them (no extrapolation)\n    #f=interp.interp1d(age_grid,np.arange(0,Na,1),kind='linear');\n    #ia_pts=f(np.log10(age_in_Gyr)+9.0);\n    \n    # get the y-axis (metallicity) locations of input points\n    zsun = 0.02;\n    iz_pts=np.interp(np.log10(metallicity_in_solar_units*zsun),np.log10(z_grid),np.arange(0,Nz,1));\n    #f=interp.interp1d(np.log10(z_grid),np.arange(0,Nz,1),kind='linear');\n    #iz_pts=f(np.log10(metallicity_in_solar_units*zsun));\n    \n    if (CRUDE==1):\n        ia_pts=np.around(ia_pts).astype(int);\n        iz_pts=np.around(iz_pts).astype(int);\n        print ia_pts, iz_pts, ia_pts, iz_pts\n        print np.min( ia_pts), np.min( iz_pts), np.min( ia_pts), np.min( iz_pts)\n        print np.max( ia_pts), np.max( iz_pts), np.max( ia_pts), np.max( iz_pts)\n        ia_pts[ia_pts < 0] = np.max(ia_pts) \n        iz_pts[iz_pts < 0] = np.max(iz_pts)\n        l_b=l_band[ia_pts,iz_pts];\n    else:\n        l_b = interpolate.map_coordinates(l_band, (ia_pts,iz_pts), order=1);\n    l_b = 10.**l_b\n    \n    # output is currently L/M in L_sun_IN_THE_BAND_OF_INTEREST/M_sun,\n    # but we want our default to be L/M in units of L_bolometric/M_sun = 3.9e33/2.0e33, so\n    #   need to get rid fo the L_sun_IN_THE_BAND_OF_INTEREST/L_bolometric\n    \n    # AB system solar luminosities used for determining L_sun in absolute units for each of these\n    N_BANDS=14\n    mag_sun_ab = np.zeros(N_BANDS,dtype=float)\n    mag_sun_ab[0] = 4.74;\n    l_bol_sun = 3.9e33; # bolometric solar in erg/s\n    mag_sun_ab[1] = 6.34;  #U (BESSEL)\n    mag_sun_ab[2] = 5.33;  #B (BESSEL)\n    mag_sun_ab[3] = 4.81;  #V (BESSEL)\n    mag_sun_ab[4] = 4.65;  #R (KPNO)\n    mag_sun_ab[5] = 4.55;  #I (KPNO)\n    mag_sun_ab[6] = 4.57;  #J (BESSEL)\n    mag_sun_ab[7] = 4.71;  #H (BESSEL)\n    mag_sun_ab[8] = 5.19;  #K (BESSEL)\n    mag_sun_ab[9] = 6.75;  #SDSS u (unprimed AB)\n    mag_sun_ab[10] = 5.33; #SDSS g (unprimed AB)\n    mag_sun_ab[11] = 4.67; #SDSS r (unprimed AB)\n    mag_sun_ab[12] = 4.48; #SDSS i (unprimed AB)\n    mag_sun_ab[13] = 4.42; #SDSS z (unprimed AB)\n    \n    # Effective wavelengths of the bands (in Angstroms), to compute nuLnu<->Lnu\n    # UBVRIJHK from http://cassfos02.ucsd.edu/physics/ph162/mags.html\n    # SDSS ugriz from http://www.sdss.org/dr4/instruments/imager/index.html#filters\n    lambda_eff = np.zeros(N_BANDS,dtype=float);\n    lambda_eff[0] = 4243.93;  #bolometric, no nu\n    lambda_eff[1] = 3600.0;  #U\n    lambda_eff[2] = 4400.0;  #B\n    lambda_eff[3] = 5556.0;  #V\n    lambda_eff[4] = 6940.0;  #R\n    lambda_eff[5] = 8700.0;  #I\n    lambda_eff[6] = 12150.;  #J\n    lambda_eff[7] = 16540.;  #H\n    lambda_eff[8] = 21790.;  #K\n    lambda_eff[9]  = 3551.;  #SDSS u\n    lambda_eff[10] = 4686.;  #SDSS g\n    lambda_eff[11] = 6165.;  #SDSS r\n    lambda_eff[12] = 7481.;  #SDSS i\n    lambda_eff[13] = 8931.;  #SDSS z\n    c_light = 2.998e10; # speed of light in cm/s\n    nu_eff  = c_light / (lambda_eff * 1.0e-8); # converts to nu_eff in Hz\n    \n    ten_pc   = 10.e0 * 3.086e18; # 10 pc in cm\n    log_S_nu = -(mag_sun_ab + 48.6)/2.5; # zero point definition for ab magnitudes\n    S_nu     = 10.**log_S_nu; # get the S_nu at 10 pc which defines M_AB\n    lnu_sun_band = S_nu * (4.*3.14159*ten_pc*ten_pc); # multiply by distance modulus\n    nulnu_sun_band = lnu_sun_band * nu_eff; # multiply by nu_eff to get nu*L_nu\n    l_bol_sun = nulnu_sun_band[0];\n    \n    if (UNITS_SOLAR_IN_BAND==0):\n        l_b *= nulnu_sun_band[band_standardordering] / l_bol_sun; \n    \n    return l_b;\n\n\n\n\n## routines from attenuation module\ndef attenuate( nu_in_Hz, log_NH, metallicity_in_solar, \\\n              SMC=0, LMC=0, MW=0, BB=0, IR=0, SX=0, HX=0):\n    return atten.attenuate( nu_in_Hz, log_NH, metallicity_in_solar, \\\n                           SMC=SMC, LMC=LMC, MW=MW, BB=BB, IR=IR, SX=SX, HX=HX)\n", "meta": {"hexsha": "033334cecc74bc09b6dff3a8504bb5ad9dde01c6", "size": 18272, "ext": "py", "lang": "Python", "max_stars_repo_path": "paul_analysis/Python/physicalmodels/stellarproperties/stellar_luminosities.py", "max_stars_repo_name": "lzkelley/arepo-mbh-sims_analysis", "max_stars_repo_head_hexsha": "f14519552cedd39a040b53e6d7cc538b5b8f38a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paul_analysis/Python/physicalmodels/stellarproperties/stellar_luminosities.py", "max_issues_repo_name": "lzkelley/arepo-mbh-sims_analysis", "max_issues_repo_head_hexsha": "f14519552cedd39a040b53e6d7cc538b5b8f38a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paul_analysis/Python/physicalmodels/stellarproperties/stellar_luminosities.py", "max_forks_repo_name": "lzkelley/arepo-mbh-sims_analysis", "max_forks_repo_head_hexsha": "f14519552cedd39a040b53e6d7cc538b5b8f38a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.7314578005, "max_line_length": 136, "alphanum_fraction": 0.6081983363, "include": true, "reason": "import numpy,import scipy", "num_tokens": 6130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499941, "lm_q2_score": 0.2974699363766585, "lm_q1q2_score": 0.19690215576535255}}
{"text": "#!/usr/bin/env python3\n\nimport io\nimport numpy as np\n#import psycopg2\nimport sys\n#import sqlite3\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.utils.data\nfrom torchvision import transforms\n\nimport modelInput\nimport deep.dataStorage\n\n#this could go in a config file or something\n#dbConnect = \"dbname='shallow-red' user='shallow-red' host='localhost' password='shallow-red'\"\n\n\n#model of the network\n#the topology of this really should be configurable\nclass Net(nn.Module):\n    def __init__(self, softmax=False, width=1000):\n        super(Net, self).__init__()\n\n        self.softmax = softmax\n\n        #simple feed forward\n        #this is kind of big, but I waste CPU cycles\n        #with smaller networks (given mini-batching)\n        #and this should be even more true with a GPU\n        self.fc1 = nn.Linear(modelInput.stateSize, width)\n        self.fc2 = nn.Linear(width, width)\n        self.fc3 = nn.Linear(width, width)\n        #self.fc4 = nn.Linear(width, width)\n        #self.fc5 = nn.Linear(width, width)\n        self.fc6 = nn.Linear(width, modelInput.numActions)\n\n        #I don't know how this function works but whatever\n        #that's how we roll\n        #self.normalizer = nn.LayerNorm((width,))\n\n    def forward(self, x):\n        x = F.relu(self.fc1(x))\n        x = F.relu(self.fc2(x))\n        x = F.relu(self.fc3(x))\n        #x = F.relu(self.fc4(x))\n        #x = F.relu(self.fc5(x))\n        #normalize to 0 mean and unit variance\n        #like in the paper\n        #x = self.normalizer(x)\n        if self.softmax:\n            x = F.softmax(self.fc6(x), dim=1)\n        else:\n            x = self.fc6(x)\n        return x\n\nclass DeepCfrModel:\n\n    #for advantages, the input is the state vector\n    #and the output is a vector of each move's advantage\n    #for strategies, the input is the state vector\n    #and the output is a vector of each move's probability\n\n    #so the inputs are exactly the same (modelInput.stateSize), and the outputs\n    #are almost the same (modelInput.numActions)\n    #strategy is softmaxed, advantage is not\n\n    def __init__(self, name, softmax, writeLock, sharedDict, lr=0.0001, sampleCacheSize=10000, clearDb=True):\n        self.softmax = softmax\n        self.lr = lr\n        self.writeLock = writeLock\n        self.sharedDict = sharedDict\n\n        #if we're not clearing the db, then we should also load in the id map\n        #so that the inputs to the model will match those in the db\n        if not clearDb:\n            modelInput.readIdMap('idmap.pickle')\n\n        self.net = Net(softmax=softmax)\n        self.optimizer = optim.Adam(self.net.parameters(), lr=lr)\n        #self.optimizer = optim.SGD(self.net.parameters(), lr=lr, momentum=0.9)\n\n        #cache of (state tensor, label tensor, iteration) tuples\n        #will eventually be put in training db\n        self.sampleCacheSize = sampleCacheSize\n        self.sampleCache = []\n\n        self.name = name\n\n    def addSample(self, data, label, iter):\n        stateTensor = modelInput.stateToTensor(data)\n\n        labelTensor = np.zeros(modelInput.numActions)\n        for action, value in label:\n            n = modelInput.enumAction(action)\n            labelTensor[n] = value\n\n        #put the np array in a tuple because that's what sqlite expects\n        self.sampleCache.append(np.concatenate((stateTensor, labelTensor, [iter])))\n        if len(self.sampleCache) > self.sampleCacheSize:\n            self.clearSampleCache()\n\n    #moves all samples from cache to the db\n    def clearSampleCache(self):\n        if len(self.sampleCache) == 0:\n            return\n        deep.dataStorage.addSamples(self.writeLock, self.name, self.sampleCache, self.sharedDict)\n        self.sampleCache = []\n\n    #we need to clean our db, clear out caches\n    def close(self):\n        #make sure we save everything first\n        #so we can use the same training data in the future\n        self.clearSampleCache()\n\n    def predict(self, state):\n        data = modelInput.stateToTensor(state)\n        device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n        data = torch.from_numpy(data).float().to(device)\n        self.net.to(device)\n        return self.net(data).cpu().detach().numpy()\n\n    def train(self, epochs=100):\n        #I'm doing this so we can manually resume a stopped run\n        modelInput.saveIdMap('idmap.pickle')\n\n        #move from write cache to db\n        self.clearSampleCache()\n\n\n        device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n        #device = torch.device('cpu')\n\n        self.net = Net(softmax=self.softmax)\n        self.net = self.net.to(device)\n        #self.optimizer = optim.SGD(self.net.parameters(), lr=self.lr, momentum=0.9)\n        self.optimizer = optim.Adam(self.net.parameters(), lr=self.lr)\n        miniBatchSize = 4\n\n        dataset = deep.dataStorage.Dataset(self.name, self.sharedDict)\n        loader = torch.utils.data.DataLoader(dataset, batch_size=miniBatchSize, shuffle=True, num_workers=4, pin_memory=True)\n\n        print('dataset size:', dataset.size, file=sys.stderr)\n\n        batchIter = iter(loader)\n        for i in range(epochs):\n            #print('getting data from loader', file=sys.stderr)\n            try:\n                data, labels, iters = next(batchIter)\n            except StopIteration:\n                batchIter = iter(loader)\n                data, labels, iters = next(batchIter)\n\n            #print('moving data to device', file=sys.stderr)\n            data = data.to(device)\n            labels = labels.to(device)\n            iters = iters.to(device)\n            \n            #print('getting ys', file=sys.stderr)\n            #evaluate on network\n            self.optimizer.zero_grad()\n            ys = self.net(data)\n\n            #print('getting loss', file=sys.stderr)\n            #loss function from the paper\n            loss = torch.sum(iters.view(labels.shape[0],-1) * ((labels - ys) ** 2))\n            #print the last 10 losses\n            if i > epochs-11:\n                print(i, loss, file=sys.stderr)\n            #get gradient of loss\n            #print('backward', file=sys.stderr)\n            loss.backward()\n            #clip gradient norm, which was done in the paper\n            #print('clip', file=sys.stderr)\n            nn.utils.clip_grad_norm_(self.net.parameters(), 1000)\n            #train the network\n            #print('step', file=sys.stderr)\n            self.optimizer.step()\n            #print('done with step', file=sys.stderr)\n\n        self.net = self.net.to(torch.device('cpu'))\n", "meta": {"hexsha": "c04f3b05aabb5051ae47a78de5e850ada4cb874f", "size": 6576, "ext": "py", "lang": "Python", "max_stars_repo_path": "old/deep/deepModel.py", "max_stars_repo_name": "samhippie/shallow-red", "max_stars_repo_head_hexsha": "5690cdf380c6e138e25d88e85093738951438298", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "old/deep/deepModel.py", "max_issues_repo_name": "samhippie/shallow-red", "max_issues_repo_head_hexsha": "5690cdf380c6e138e25d88e85093738951438298", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "old/deep/deepModel.py", "max_forks_repo_name": "samhippie/shallow-red", "max_forks_repo_head_hexsha": "5690cdf380c6e138e25d88e85093738951438298", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-13T12:53:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-13T12:53:35.000Z", "avg_line_length": 35.5459459459, "max_line_length": 125, "alphanum_fraction": 0.6215024331, "include": true, "reason": "import numpy", "num_tokens": 1531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778403, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.19679701119515455}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nRED Colourspaces\n================\n\nDefines the *RED* colourspaces:\n\n-   :attr:`colour.models.RGB_COLOURSPACE_RED_COLOR`\n-   :attr:`colour.models.RGB_COLOURSPACE_RED_COLOR_2`\n-   :attr:`colour.models.RGB_COLOURSPACE_RED_COLOR_3`\n-   :attr:`colour.models.RGB_COLOURSPACE_RED_COLOR_4`\n-   :attr:`colour.models.RGB_COLOURSPACE_DRAGON_COLOR`\n-   :attr:`colour.models.RGB_COLOURSPACE_DRAGON_COLOR_2`\n-   :attr:`colour.models.RGB_COLOURSPACE_RED_WIDE_GAMUT_RGB`\n\nReferences\n----------\n-   :cite:`Mansencal2015d` : Mansencal, T. (2015). RED Colourspaces Derivation.\n    Retrieved May 20, 2015, from\n    https://www.colour-science.org/posts/red-colourspaces-derivation\n-   :cite:`Nattress2016a` : Nattress, G. (2016). Private Discussion with Shaw,\n    N.\n-   :cite:`SonyImageworks2012a` : Sony Imageworks. (2012). make.py. Retrieved\n    November 27, 2014, from\n    https://github.com/imageworks/OpenColorIO-Configs/blob/master/\\\nnuke-default/make.py\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\n\nfrom colour.colorimetry import CCS_ILLUMINANTS\nfrom colour.models.rgb import (\n    RGB_Colourspace, normalised_primary_matrix, log_encoding_REDLogFilm,\n    log_decoding_REDLogFilm, log_encoding_Log3G10, log_decoding_Log3G10)\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2020 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-developers@colour-science.org'\n__status__ = 'Production'\n\n__all__ = [\n    'PRIMARIES_RED_COLOR', 'WHITEPOINT_NAME_RED_COLOR',\n    'CCS_WHITEPOINT_RED_COLOR', 'MATRIX_RED_COLOR_TO_XYZ',\n    'MATRIX_XYZ_TO_RED_COLOR', 'RGB_COLOURSPACE_RED_COLOR',\n    'PRIMARIES_RED_COLOR_2', 'WHITEPOINT_NAME_RED_COLOR_2',\n    'CCS_WHITEPOINT_RED_COLOR_2', 'MATRIX_RED_COLOR_2_TO_XYZ',\n    'MATRIX_XYZ_TO_RED_COLOR_2', 'RGB_COLOURSPACE_RED_COLOR_2',\n    'PRIMARIES_RED_COLOR_3', 'WHITEPOINT_NAME_RED_COLOR_3',\n    'CCS_WHITEPOINT_RED_COLOR_3', 'MATRIX_RED_COLOR_3_TO_XYZ',\n    'MATRIX_XYZ_TO_RED_COLOR_3', 'RGB_COLOURSPACE_RED_COLOR_3',\n    'PRIMARIES_RED_COLOR_4', 'WHITEPOINT_NAME_RED_COLOR_4',\n    'CCS_WHITEPOINT_RED_COLOR_4', 'MATRIX_RED_COLOR_4_TO_XYZ',\n    'MATRIX_XYZ_TO_RED_COLOR_4', 'RGB_COLOURSPACE_RED_COLOR_4',\n    'PRIMARIES_DRAGON_COLOR', 'WHITEPOINT_NAME_DRAGON_COLOR',\n    'CCS_WHITEPOINT_DRAGON_COLOR', 'MATRIX_DRAGON_COLOR_TO_XYZ',\n    'MATRIX_XYZ_TO_DRAGON_COLOR', 'RGB_COLOURSPACE_DRAGON_COLOR',\n    'PRIMARIES_DRAGON_COLOR_2', 'WHITEPOINT_NAME_DRAGON_COLOR_2',\n    'CCS_WHITEPOINT_DRAGON_COLOR_2', 'MATRIX_DRAGON_COLOR_2_TO_XYZ',\n    'MATRIX_XYZ_TO_DRAGON_COLOR_2', 'RGB_COLOURSPACE_DRAGON_COLOR_2',\n    'PRIMARIES_RED_WIDE_GAMUT_RGB', 'WHITEPOINT_NAME_RED_WIDE_GAMUT_RGB',\n    'CCS_WHITEPOINT_RED_WIDE_GAMUT_RGB', 'MATRIX_RED_WIDE_GAMUT_RGB_TO_XYZ',\n    'MATRIX_XYZ_TO_RED_WIDE_GAMUT_RGB', 'RGB_COLOURSPACE_RED_WIDE_GAMUT_RGB'\n]\n\nPRIMARIES_RED_COLOR = np.array([\n    [0.701058563171395, 0.330180975940326],\n    [0.298811317306316, 0.625169245953133],\n    [0.135038675201355, 0.035261776551191],\n])\n\"\"\"\n*REDcolor* colourspace primaries.\n\nPRIMARIES_RED_COLOR : ndarray, (3, 2)\n\"\"\"\n\nWHITEPOINT_NAME_RED_COLOR = 'D65'\n\"\"\"\n*REDcolor* colourspace whitepoint name.\n\nWHITEPOINT_NAME_RED_COLOR : unicode\n\"\"\"\n\nCCS_WHITEPOINT_RED_COLOR = (CCS_ILLUMINANTS[\n    'CIE 1931 2 Degree Standard Observer'][WHITEPOINT_NAME_RED_COLOR])\n\"\"\"\n*REDcolor* colourspace whitepoint chromaticity coordinates.\n\nCCS_WHITEPOINT_RED_COLOR : ndarray\n\"\"\"\n\nMATRIX_RED_COLOR_TO_XYZ = normalised_primary_matrix(PRIMARIES_RED_COLOR,\n                                                    CCS_WHITEPOINT_RED_COLOR)\n\"\"\"\n*REDcolor* colourspace to *CIE XYZ* tristimulus values matrix.\n\nMATRIX_RED_COLOR_XYZ : array_like, (3, 3)\n\"\"\"\n\nMATRIX_XYZ_TO_RED_COLOR = np.linalg.inv(MATRIX_RED_COLOR_TO_XYZ)\n\"\"\"\n*CIE XYZ* tristimulus values to *REDcolor* colourspace matrix.\n\nMATRIX_XYZ_TO_RED_COLOR : array_like, (3, 3)\n\"\"\"\n\nRGB_COLOURSPACE_RED_COLOR = RGB_Colourspace(\n    'REDcolor',\n    PRIMARIES_RED_COLOR,\n    CCS_WHITEPOINT_RED_COLOR,\n    WHITEPOINT_NAME_RED_COLOR,\n    MATRIX_RED_COLOR_TO_XYZ,\n    MATRIX_XYZ_TO_RED_COLOR,\n    log_encoding_REDLogFilm,\n    log_decoding_REDLogFilm,\n)\nRGB_COLOURSPACE_RED_COLOR.__doc__ = \"\"\"\n*REDcolor* colourspace.\n\nReferences\n----------\n:cite:`Mansencal2015d`, :cite:`SonyImageworks2012a`\n\nRGB_COLOURSPACE_RED_COLOR : RGB_Colourspace\n\"\"\"\n\nPRIMARIES_RED_COLOR_2 = np.array([\n    [0.897407221929776, 0.330776225980398],\n    [0.296022094516625, 0.684635550900945],\n    [0.099799512883393, -0.023000513177992],\n])\n\"\"\"\n*REDcolor2* colourspace primaries.\n\nPRIMARIES_RED_COLOR_2 : ndarray, (3, 2)\n\"\"\"\n\nWHITEPOINT_NAME_RED_COLOR_2 = WHITEPOINT_NAME_RED_COLOR\n\"\"\"\n*REDcolor2* colourspace whitepoint name.\n\nWHITEPOINT_NAME_RED_COLOR_2 : unicode\n\"\"\"\n\nCCS_WHITEPOINT_RED_COLOR_2 = CCS_WHITEPOINT_RED_COLOR\n\"\"\"\n*REDcolor2* colourspace whitepoint chromaticity coordinates.\n\nCCS_WHITEPOINT_RED_COLOR_2 : ndarray\n\"\"\"\n\nMATRIX_RED_COLOR_2_TO_XYZ = normalised_primary_matrix(\n    PRIMARIES_RED_COLOR_2, CCS_WHITEPOINT_RED_COLOR_2)\n\"\"\"\n*REDcolor2* colourspace to *CIE XYZ* tristimulus values matrix.\n\nMATRIX_RED_COLOR_2_XYZ : array_like, (3, 3)\n\"\"\"\n\nMATRIX_XYZ_TO_RED_COLOR_2 = np.linalg.inv(MATRIX_RED_COLOR_2_TO_XYZ)\n\"\"\"\n*CIE XYZ* tristimulus values to *REDcolor2* colourspace matrix.\n\nMATRIX_XYZ_TO_RED_COLOR_2 : array_like, (3, 3)\n\"\"\"\n\nRGB_COLOURSPACE_RED_COLOR_2 = RGB_Colourspace(\n    'REDcolor2',\n    PRIMARIES_RED_COLOR_2,\n    CCS_WHITEPOINT_RED_COLOR_2,\n    WHITEPOINT_NAME_RED_COLOR_2,\n    MATRIX_RED_COLOR_2_TO_XYZ,\n    MATRIX_XYZ_TO_RED_COLOR_2,\n    log_encoding_REDLogFilm,\n    log_decoding_REDLogFilm,\n)\nRGB_COLOURSPACE_RED_COLOR_2.__doc__ = \"\"\"\n*REDcolor2* colourspace.\n\nReferences\n----------\n:cite:`Mansencal2015d`, :cite:`SonyImageworks2012a`\n\nRGB_COLOURSPACE_RED_COLOR_2 : RGB_Colourspace\n\"\"\"\n\nPRIMARIES_RED_COLOR_3 = np.array([\n    [0.702598658589917, 0.330185588938484],\n    [0.295782235737268, 0.689748258397534],\n    [0.111090529079787, -0.004332320984771],\n])\n\"\"\"\n*REDcolor3* colourspace primaries.\n\nPRIMARIES_RED_COLOR_3 : ndarray, (3, 2)\n\"\"\"\n\nWHITEPOINT_NAME_RED_COLOR_3 = WHITEPOINT_NAME_RED_COLOR\n\"\"\"\n*REDcolor3* colourspace whitepoint name.\n\nWHITEPOINT_NAME_RED_COLOR_3 : unicode\n\"\"\"\n\nCCS_WHITEPOINT_RED_COLOR_3 = CCS_WHITEPOINT_RED_COLOR\n\"\"\"\n*REDcolor3* colourspace whitepoint chromaticity coordinates.\n\nCCS_WHITEPOINT_RED_COLOR_3 : ndarray\n\"\"\"\n\nMATRIX_RED_COLOR_3_TO_XYZ = normalised_primary_matrix(\n    PRIMARIES_RED_COLOR_3, CCS_WHITEPOINT_RED_COLOR_3)\n\"\"\"\n*REDcolor3* colourspace to *CIE XYZ* tristimulus values matrix.\n\nMATRIX_RED_COLOR_3_TO_XYZ : array_like, (3, 3)\n\"\"\"\n\nMATRIX_XYZ_TO_RED_COLOR_3 = np.linalg.inv(MATRIX_RED_COLOR_3_TO_XYZ)\n\"\"\"\n*CIE XYZ* tristimulus values to *REDcolor3* colourspace matrix.\n\nMATRIX_XYZ_TO_RED_COLOR_3 : array_like, (3, 3)\n\"\"\"\n\nRGB_COLOURSPACE_RED_COLOR_3 = RGB_Colourspace(\n    'REDcolor3',\n    PRIMARIES_RED_COLOR_3,\n    CCS_WHITEPOINT_RED_COLOR_3,\n    WHITEPOINT_NAME_RED_COLOR_3,\n    MATRIX_RED_COLOR_3_TO_XYZ,\n    MATRIX_XYZ_TO_RED_COLOR_3,\n    log_encoding_REDLogFilm,\n    log_decoding_REDLogFilm,\n)\nRGB_COLOURSPACE_RED_COLOR_3.__doc__ = \"\"\"\n*REDcolor3* colourspace.\n\nReferences\n----------\n:cite:`Mansencal2015d`, :cite:`SonyImageworks2012a`\n\nRGB_COLOURSPACE_RED_COLOR_3 : RGB_Colourspace\n\"\"\"\n\nPRIMARIES_RED_COLOR_4 = np.array([\n    [0.702598154635438, 0.330185096210515],\n    [0.295782328047083, 0.689748253964859],\n    [0.144459236489795, 0.050837720977386],\n])\n\"\"\"\n*REDcolor4* colourspace primaries.\n\nPRIMARIES_RED_COLOR_4 : ndarray, (3, 2)\n\"\"\"\n\nWHITEPOINT_NAME_RED_COLOR_4 = WHITEPOINT_NAME_RED_COLOR\n\"\"\"\n*REDcolor4* colourspace whitepoint name.\n\nWHITEPOINT_NAME_RED_COLOR_4 : unicode\n\"\"\"\n\nCCS_WHITEPOINT_RED_COLOR_4 = CCS_WHITEPOINT_RED_COLOR\n\"\"\"\n*REDcolor4* colourspace whitepoint chromaticity coordinates.\n\nCCS_WHITEPOINT_RED_COLOR_4 : ndarray\n\"\"\"\n\nMATRIX_RED_COLOR_4_TO_XYZ = normalised_primary_matrix(\n    PRIMARIES_RED_COLOR_4, CCS_WHITEPOINT_RED_COLOR_4)\n\"\"\"\n*REDcolor4* colourspace to *CIE XYZ* tristimulus values matrix.\n\nMATRIX_RED_COLOR_4_TO_XYZ : array_like, (3, 3)\n\"\"\"\n\nMATRIX_XYZ_TO_RED_COLOR_4 = np.linalg.inv(MATRIX_RED_COLOR_4_TO_XYZ)\n\"\"\"\n*CIE XYZ* tristimulus values to *REDcolor4* colourspace matrix.\n\nMATRIX_XYZ_TO_RED_COLOR_4 : array_like, (3, 3)\n\"\"\"\n\nRGB_COLOURSPACE_RED_COLOR_4 = RGB_Colourspace(\n    'REDcolor4',\n    PRIMARIES_RED_COLOR_4,\n    CCS_WHITEPOINT_RED_COLOR_4,\n    WHITEPOINT_NAME_RED_COLOR_4,\n    MATRIX_RED_COLOR_4_TO_XYZ,\n    MATRIX_XYZ_TO_RED_COLOR_4,\n    log_encoding_REDLogFilm,\n    log_decoding_REDLogFilm,\n)\nRGB_COLOURSPACE_RED_COLOR_4.__doc__ = \"\"\"\n*REDcolor4* colourspace.\n\nReferences\n----------\n:cite:`Mansencal2015d`, :cite:`SonyImageworks2012a`\n\nRGB_COLOURSPACE_RED_COLOR_4 : RGB_Colourspace\n\"\"\"\n\nPRIMARIES_DRAGON_COLOR = np.array([\n    [0.758655892599321, 0.330355348611293],\n    [0.294923619810175, 0.708053242065117],\n    [0.085961601167585, -0.045879436983969],\n])\n\"\"\"\n*DRAGONcolor* colourspace primaries.\n\nPRIMARIES_DRAGON_COLOR : ndarray, (3, 2)\n\"\"\"\n\nWHITEPOINT_NAME_DRAGON_COLOR = WHITEPOINT_NAME_RED_COLOR\n\"\"\"\n*DRAGONcolor* colourspace whitepoint name.\n\nWHITEPOINT_NAME_DRAGON_COLOR : unicode\n\"\"\"\n\nCCS_WHITEPOINT_DRAGON_COLOR = CCS_WHITEPOINT_RED_COLOR\n\"\"\"\n*DRAGONcolor* colourspace whitepoint chromaticity coordinates.\n\nCCS_WHITEPOINT_DRAGON_COLOR : ndarray\n\"\"\"\n\nMATRIX_DRAGON_COLOR_TO_XYZ = normalised_primary_matrix(\n    PRIMARIES_DRAGON_COLOR, CCS_WHITEPOINT_DRAGON_COLOR)\n\"\"\"\n*DRAGONcolor* colourspace to *CIE XYZ* tristimulus values matrix.\n\nMATRIX_DRAGON_COLOR_TO_XYZ : array_like, (3, 3)\n\"\"\"\n\nMATRIX_XYZ_TO_DRAGON_COLOR = np.linalg.inv(MATRIX_DRAGON_COLOR_TO_XYZ)\n\"\"\"\n*CIE XYZ* tristimulus values to *DRAGONcolor* colourspace matrix.\n\nMATRIX_XYZ_TO_DRAGON_COLOR : array_like, (3, 3)\n\"\"\"\n\nRGB_COLOURSPACE_DRAGON_COLOR = RGB_Colourspace(\n    'DRAGONcolor',\n    PRIMARIES_DRAGON_COLOR,\n    CCS_WHITEPOINT_DRAGON_COLOR,\n    WHITEPOINT_NAME_DRAGON_COLOR,\n    MATRIX_DRAGON_COLOR_TO_XYZ,\n    MATRIX_XYZ_TO_DRAGON_COLOR,\n    log_encoding_REDLogFilm,\n    log_decoding_REDLogFilm,\n)\nRGB_COLOURSPACE_DRAGON_COLOR.__doc__ = \"\"\"\n*DRAGONcolor* colourspace.\n\nReferences\n----------\n:cite:`Mansencal2015d`, :cite:`SonyImageworks2012a`\n\nRGB_COLOURSPACE_DRAGON_COLOR : RGB_Colourspace\n\"\"\"\n\nPRIMARIES_DRAGON_COLOR_2 = np.array([\n    [0.758656214177604, 0.330355835762678],\n    [0.294923887732982, 0.708053363192126],\n    [0.144168726866337, 0.050357384587121],\n])\n\"\"\"\n*DRAGONcolor2* colourspace primaries.\n\nPRIMARIES_DRAGON_COLOR_2 : ndarray, (3, 2)\n\"\"\"\n\nWHITEPOINT_NAME_DRAGON_COLOR_2 = WHITEPOINT_NAME_RED_COLOR\n\"\"\"\n*DRAGONcolor2* colourspace whitepoint name.\n\nWHITEPOINT_NAME_DRAGON_COLOR_2 : unicode\n\"\"\"\n\nCCS_WHITEPOINT_DRAGON_COLOR_2 = CCS_WHITEPOINT_RED_COLOR\n\"\"\"\n*DRAGONcolor2* colourspace whitepoint chromaticity coordinates.\n\nCCS_WHITEPOINT_DRAGON_COLOR_2 : ndarray\n\"\"\"\n\nMATRIX_DRAGON_COLOR_2_TO_XYZ = normalised_primary_matrix(\n    PRIMARIES_DRAGON_COLOR_2, CCS_WHITEPOINT_DRAGON_COLOR_2)\n\"\"\"\n*DRAGONcolor2* colourspace to *CIE XYZ* tristimulus values matrix.\n\nMATRIX_DRAGON_COLOR_2_TO_XYZ : array_like, (3, 3)\n\"\"\"\n\nMATRIX_XYZ_TO_DRAGON_COLOR_2 = np.linalg.inv(MATRIX_DRAGON_COLOR_2_TO_XYZ)\n\"\"\"\n*CIE XYZ* tristimulus values to *DRAGONcolor2* colourspace matrix.\n\nMATRIX_XYZ_TO_DRAGON_COLOR_2 : array_like, (3, 3)\n\"\"\"\n\nRGB_COLOURSPACE_DRAGON_COLOR_2 = RGB_Colourspace(\n    'DRAGONcolor2',\n    PRIMARIES_DRAGON_COLOR_2,\n    CCS_WHITEPOINT_DRAGON_COLOR_2,\n    WHITEPOINT_NAME_DRAGON_COLOR_2,\n    MATRIX_DRAGON_COLOR_2_TO_XYZ,\n    MATRIX_XYZ_TO_DRAGON_COLOR_2,\n    log_encoding_REDLogFilm,\n    log_decoding_REDLogFilm,\n)\nRGB_COLOURSPACE_DRAGON_COLOR_2.__doc__ = \"\"\"\n*DRAGONcolor2* colourspace.\n\nReferences\n----------\n:cite:`Mansencal2015d`, :cite:`SonyImageworks2012a`\n\nRGB_COLOURSPACE_DRAGON_COLOR_2 : RGB_Colourspace\n\"\"\"\n\nPRIMARIES_RED_WIDE_GAMUT_RGB = np.array([\n    [0.780308, 0.304253],\n    [0.121595, 1.493994],\n    [0.095612, -0.084589],\n])\n\"\"\"\n*REDWideGamutRGB* colourspace primaries.\n\nPRIMARIES_RED_WIDE_GAMUT_RGB : ndarray, (3, 2)\n\"\"\"\n\nWHITEPOINT_NAME_RED_WIDE_GAMUT_RGB = WHITEPOINT_NAME_RED_COLOR\n\"\"\"\n*REDWideGamutRGB* colourspace whitepoint name.\n\nWHITEPOINT_NAME_RED_WIDE_GAMUT_RGB : unicode\n\"\"\"\n\nCCS_WHITEPOINT_RED_WIDE_GAMUT_RGB = CCS_WHITEPOINT_RED_COLOR\n\"\"\"\n*REDWideGamutRGB* colourspace whitepoint chromaticity coordinates.\n\nCCS_WHITEPOINT_RED_WIDE_GAMUT_RGB : ndarray\n\"\"\"\n\nMATRIX_RED_WIDE_GAMUT_RGB_TO_XYZ = np.array([\n    [0.735275, 0.068609, 0.146571],\n    [0.286694, 0.842979, -0.129673],\n    [-0.079681, -0.347343, 1.516082],\n])\n\"\"\"\n*REDWideGamutRGB* colourspace to *CIE XYZ* tristimulus values matrix.\n\nMATRIX_RED_WIDE_GAMUT_RGB_TO_XYZ : array_like, (3, 3)\n\"\"\"\n\nMATRIX_XYZ_TO_RED_WIDE_GAMUT_RGB = np.linalg.inv(\n    MATRIX_RED_WIDE_GAMUT_RGB_TO_XYZ)\n\"\"\"\n*CIE XYZ* tristimulus values to *REDWideGamutRGB* colourspace matrix.\n\nMATRIX_XYZ_TO_RED_WIDE_GAMUT_RGB : array_like, (3, 3)\n\"\"\"\n\nRGB_COLOURSPACE_RED_WIDE_GAMUT_RGB = RGB_Colourspace(\n    'REDWideGamutRGB',\n    PRIMARIES_RED_WIDE_GAMUT_RGB,\n    CCS_WHITEPOINT_RED_WIDE_GAMUT_RGB,\n    WHITEPOINT_NAME_RED_WIDE_GAMUT_RGB,\n    MATRIX_RED_WIDE_GAMUT_RGB_TO_XYZ,\n    MATRIX_XYZ_TO_RED_WIDE_GAMUT_RGB,\n    log_encoding_Log3G10,\n    log_decoding_Log3G10,\n)\nRGB_COLOURSPACE_RED_WIDE_GAMUT_RGB.__doc__ = \"\"\"\n*REDWideGamutRGB* colourspace.\n\nReferences\n----------\n:cite:`Mansencal2015d`, :cite:`Nattress2016a`, :cite:`SonyImageworks2012a`\n\nRGB_COLOURSPACE_RED_WIDE_GAMUT_RGB : RGB_Colourspace\n\"\"\"\n", "meta": {"hexsha": "52102a78e0d3ab992492680e980adfc8c64325c6", "size": 13466, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/models/rgb/datasets/red.py", "max_stars_repo_name": "wenh06/colour", "max_stars_repo_head_hexsha": "445fdad2711ae39c95b4375166905568d24a95f4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-09T01:53:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T01:53:40.000Z", "max_issues_repo_path": "colour/models/rgb/datasets/red.py", "max_issues_repo_name": "wenh06/colour", "max_issues_repo_head_hexsha": "445fdad2711ae39c95b4375166905568d24a95f4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/models/rgb/datasets/red.py", "max_forks_repo_name": "wenh06/colour", "max_forks_repo_head_hexsha": "445fdad2711ae39c95b4375166905568d24a95f4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3144016227, "max_line_length": 79, "alphanum_fraction": 0.7798158325, "include": true, "reason": "import numpy", "num_tokens": 4179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802471698041, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.19679458744082073}}
{"text": "# Copyright 2019-2021 Cambridge Quantum Computing\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom pytket import Circuit\nfrom pytket.backends import Backend\nfrom pytket.transform import Transform  # type: ignore\nfrom pytket.utils import QubitPauliOperator\nfrom pytket.pauli import Pauli, QubitPauliString  # type: ignore\nfrom pytket.tailoring import apply_clifford_basis_change  # type: ignore\nfrom numpy import mean\n\nfrom typing import List, Tuple, cast, Union, Dict\nimport copy\n\nfrom qermit import (\n    MitEx,\n    SymbolsDict,\n    MeasurementCircuit,\n    ObservableTracker,\n    MitTask,\n    AnsatzCircuit,\n    ObservableExperiment,\n    TaskGraph,\n)\nfrom qermit.taskgraph.mitex import get_basic_measurement_circuit, gen_compiled_MitRes\n\n\ndef get_clifford_mcs(input_circuit: Circuit) -> List[MeasurementCircuit]:\n    \"\"\"\n    For given Circuit, rebases and substitutes all non-Clifford angles with symbols.\n    Then, makes MeasurementCircuit objects wherein each Circuit is the same, but each SymbolsDict\n    object varies with some different set of Clifford angles.\n\n    :param input_circuit: Circuit to make all-non Clifford gates paramterised.\n    :type input_circuit: Circuit\n\n    :return: New MeasurementCircuits with Clifford parameters\n    :rtype: List[MeasurementCircuit]\n    \"\"\"\n    copy_circ = input_circuit.copy()\n    symbols = copy_circ.free_symbols()\n    symbols_dict = dict()\n    for s in symbols:\n        symbols_dict[s] = cast(Union[None, float], float(0))\n    sd = SymbolsDict.symbols_from_dict(symbols_dict)\n    return [MeasurementCircuit(copy_circ, sd)]\n\n\n# TODO: make prepare -1 eigenstate also\ndef preparation_circuit_for_partition(\n    clifford_circuit: Circuit, partition: List[QubitPauliString]\n) -> Circuit:\n    \"\"\"\n    For each Pauli string in partition, finds Pauli string produced by applying a Clifford basis change from given Clifford circuit.\n    Returns a state preparation circuit for preparing a +1 eigenstate of all basis changed Pauli strings.\n    \"\"\"\n\n    eigenstate_circuit = Circuit(0)\n    for q in clifford_circuit.qubits:\n        eigenstate_circuit.add_qubit(q)\n    # to make +1 eigenstate of all transformed strings\n    # transform string, then append gates for preparing\n    # +1 eigenstate to circuit\n    # use RemoveRedundancies after to minimise gates required in cosntruction\n    Transform.RebaseToCliffordSingles().apply(clifford_circuit)\n    for string in partition:\n        transformed_string = apply_clifford_basis_change(string, clifford_circuit)\n        transformed_dict = transformed_string.map\n        for qubit in transformed_dict:\n            if transformed_dict[qubit] == Pauli.X:\n                eigenstate_circuit.H(qubit)\n            if transformed_dict[qubit] == Pauli.Y:\n                eigenstate_circuit.V(qubit)\n        Transform.RemoveRedundancies().apply(eigenstate_circuit)\n    return eigenstate_circuit\n\n\ndef DFSC_circuit_task_gen() -> MitTask:\n    \"\"\"\n    For each experiment, the ansatz circuit has all symbolic gates substituted for Clifford angles (in this case, all 0's).\n    If any non symbolic gates are non Clifford, an error is thrown.\n    For each Clifford ansatz circuit, a new ObservableTracke is forme with new measurement circuits\n    added for each Qubit Pauli String in the operator.\n\n    :return: MitTask object that produces characterisation circuits for DFSC on a new wire as new experiments\n    :rtype: MitTask\n    \"\"\"\n\n    def task(\n        obj,\n        measurement_wires: List[ObservableExperiment],\n    ) -> Tuple[List[ObservableExperiment], List[List[List[ObservableExperiment]]],]:\n        \"\"\"\n        :param measurement_wires: A list of tuples, each tuple representing a different experiment\n        :type measurement_wires: List[ObservableExperiment]\n\n        :return: Original experiment wires and another list of characterisation experiments for each original experiment.\n        These are organised in later task.\n        :rtype: Tuple[List[ObservableExperiment], List[List[List[ObservableExperiment]]]]\n        \"\"\"\n        characterisation_wires = []\n        for measurement_wire in measurement_wires:\n            ansatz_circ = measurement_wire.AnsatzCircuit\n            base_circ = ansatz_circ[0]\n            tracker = measurement_wire.ObservableTracker\n            # Given a circuit, sets all Symbols to Clifford angles\n            # If circuit has non-Clifford elements not as symbolics, error thrown\n            clifford_circuits = get_clifford_mcs(base_circ)\n\n            # make a new ObservableTracker for holding characterisation circuits\n            single_experiment_wires = []\n            for c in clifford_circuits:\n                clifford_trackers = []\n                for string in tracker._qps_to_indices.keys():\n                    # each characterisation circuit must have its own observable tracker\n                    # this is as the 'ansatz' circuit changes for each string + Clifford combo\n                    # as state preparation changes\n                    new_tracker = ObservableTracker(QubitPauliOperator({string: 1}))\n                    # get measurement circuit\n                    measurement_circuit_info = get_basic_measurement_circuit(string)\n\n                    para_circuit = c.get_parametric_circuit()\n                    # get preparation circuit for partition, though only pass 1 string\n                    prep_circuit = preparation_circuit_for_partition(\n                        para_circuit, [string]\n                    )\n                    # add components to get characterisation circuit\n                    prep_circuit.append(para_circuit)\n                    new_ansatz_c = AnsatzCircuit(\n                        Circuit=prep_circuit.copy(),\n                        Shots=ansatz_circ[1],\n                        SymbolsDict=c._symbols,\n                    )\n                    prep_circuit.append(measurement_circuit_info[0])\n                    # add to new tracker for given Clifford circuit\n\n                    new_tracker.add_measurement_circuit(\n                        MeasurementCircuit(prep_circuit, c._symbols),\n                        [measurement_circuit_info[1]],\n                    )\n                    clifford_trackers.append(\n                        ObservableExperiment(\n                            AnsatzCircuit=new_ansatz_c, ObservableTracker=new_tracker\n                        )\n                    )\n                # a single experiment being all pauli string measurement circuits for a single Clifford Circuit\n                single_experiment_wires.append(clifford_trackers)\n            # single experiment wires being all observable trackers for all sampled Clifford circuits with\n            # added measurement circuits for all pauli strings in given experiment\n            characterisation_wires.append(single_experiment_wires)\n        return (measurement_wires, characterisation_wires)\n\n    return MitTask(_label=\"DFSCCircuits\", _n_in_wires=1, _n_out_wires=2, _method=task)\n\n\ndef DFSC_collater_task_gen() -> MitTask:\n    \"\"\"\n    For each experiment passed to MitEx, DFSC characterisation produces an ObservableTracker\n    of a single Measurement Circuit for each combination of Clifford circuit produced, eigenstates preparation\n    and QubitPauliString in operator, via several nested Lists.\n    This task unpackages these Lists into a single List as suitable for input to MitEx objects.\n    It also stores information required to produce characterisation from resulting QubitPauliOperators out of\n    MitEx object.\n\n    :return: MitTask object that collates many BackendResult objects for a single\n        frame randomisation instance and converts them into a single\n        BackendResult object.\n    :rtype: MitTask\n    \"\"\"\n\n    def task(\n        obj,\n        all_characterisation_trackers: List[List[List[ObservableExperiment]]],\n    ) -> Tuple[List[ObservableExperiment], List[int]]:\n        \"\"\"\n        :param all_characterisation_trackers: Experiment wires; outer list is experiments, second outer list\n        is Cliffords, inner list is qubit pauli strings.\n        :type all_characterisation_trackers: List[List[List[ObservableExperiment]]]\n\n        :return: Wire 1; All individual experiments collated into a single wire.\n        Wire 2; Indexing to produce characterisation later.\n        :rtype: Tuple[List[ObservableExperiment], List[Tuple[int, List[int]]]]\n        \"\"\"\n        organisation_indices = []\n        collated_experiments = []\n        for experiment_char in all_characterisation_trackers:\n            # individual list is for some cliffords\n            # qps is stored in output\n            base_len = 0\n            for cliff_ots in experiment_char:\n                base_len += len(cliff_ots)\n                for qps_ot in cliff_ots:\n                    collated_experiments.append(qps_ot)\n            organisation_indices.append(base_len)\n        return (collated_experiments, organisation_indices)\n\n    return MitTask(_label=\"DFSCCollation\", _n_in_wires=1, _n_out_wires=2, _method=task)\n\n\ndef DFSC_characterisation_task_gen() -> MitTask:\n    \"\"\"\n    Given characterisation results for all experiments, Clifford circuits and QubitPauliStrings, produces\n    a characterisation result for each Experiment.\n\n    :return: MitTask object for organising and calculating characterisation.\n    :rtype: MitTask\n    \"\"\"\n\n    def task(\n        obj,\n        characterisation_results: List[QubitPauliOperator],\n        experiment_indexing: List[int],\n    ) -> Tuple[List[QubitPauliOperator]]:\n        \"\"\"\n        :param characterisation_results: All QubitPauliOperators returned from running experiment through some MitEx object\n        :type characteriastion_results: List[QubitPauliOperator]\n        :param experiment_indexing: Number of characteriastion results for each experiment, used to split results up.\n        :type experiment_indexing: List[int]\n\n        :return: Collated characterisation results, one QubitPauliOperator characterisation for each experiment\n        :rtype: Tuple[List[QubitPauliOperator]]\n        \"\"\"\n        split_results = []\n        lower_bound = 0\n        for size in experiment_indexing:\n            upper_bound = lower_bound + size\n            split_results.append(characterisation_results[lower_bound:upper_bound])\n            lower_bound = upper_bound\n\n        characterisation_qpos = []\n        for experiment_results in split_results:\n            characterisation_dict: Dict[QubitPauliString, List[float]] = dict()\n            # add all expectations for each Clifford + String combo to dict\n            for qpo in experiment_results:\n                for string in qpo._dict:\n                    if string not in characterisation_dict:\n                        characterisation_dict[string] = list()\n                    characterisation_dict[string].append(qpo._dict[string])\n            # set entry to average of values in list\n            # add characterisation for DFSC to output list\n            characterisation_qpos.append(\n                QubitPauliOperator(\n                    {k: mean(characterisation_dict[k]) for k in characterisation_dict}\n                )\n            )\n        # number of characterisation qpos should match original number of experiments\n        return (characterisation_qpos,)\n\n    return MitTask(\n        _label=\"DFSCCharacterisation\", _n_in_wires=2, _n_out_wires=1, _method=task\n    )\n\n\ndef DFSC_correction_task_gen(zero_threshold: float) -> MitTask:\n    \"\"\"\n    For each experiment expectation, if characterisation value greater than threshold, divide experiment expectation\n    by characteriastion value to correct for depolaring noise.\n\n    :param zero_threshold: Method does not correct for zero characteriastion expectation values, threshold for this zero limit.\n    :type zero_threshold: float\n\n    :return: Function for DFSC correctoin.\n    :rtype: MitTask\n    \"\"\"\n\n    def task(\n        obj,\n        experiment_results: List[QubitPauliOperator],\n        characterisation_results: List[QubitPauliOperator],\n    ) -> Tuple[List[QubitPauliOperator]]:\n        \"\"\"\n        :param experiment_results: QubitPauliOperators corresponding to expectations for all observable experiments.\n        :type experiment_results: List[QubitPauliOperator]\n        :param characteriastion_results: QubitPauliOperators corresponding to expectations for all characterisation experiments.\n        :type characterisation_results: List[QubitPauliOperator]\n\n        :return: Corrected expectations as QubitPauliOperator objects.\n        :rtype: Tuple[List[QubitPauliOperator]]\n        \"\"\"\n        if len(experiment_results) != len(characterisation_results):\n            raise ValueError(\n                \"{} Experiment results and {} Characterisation results: mismatch for DFSC correction.\".format(\n                    len(experiment_results), len(characterisation_results)\n                ),\n            )\n        corrected_results = []\n        for experiment_qpo, characterisation_qpo in zip(\n            experiment_results, characterisation_results\n        ):\n            new_qpo = dict()\n            for key in experiment_qpo._dict:\n                val = characterisation_qpo._dict[key]\n                if val > zero_threshold:\n                    new_qpo[key] = experiment_qpo._dict[key] / val\n                else:\n                    new_qpo[key] = experiment_qpo._dict[key]\n            corrected_results.append(QubitPauliOperator(new_qpo))\n        return (corrected_results,)\n\n    return MitTask(_label=\"DFSCCorrection\", _n_in_wires=2, _n_out_wires=1, _method=task)\n\n\ndef gen_DFSC_MitEx(backend: Backend, **kwargs) -> MitEx:\n    \"\"\"\n    Produces a MitEx object that applies DFSC characteriastion to all experiment results.\n\n    :param backend: Backend experiments are run through.\n    :type backend: Backend\n    :key experiment_mitex: MitEx object observable experiments are run through\n    :key characterisation_mitex: MitEX object characteriastion experiments are run through.\n\n    :return: MitEx object for automatic DFSC correction of circuits.\n    :rtype: MitEx\n\n    \"\"\"\n\n    _experiment_mitex = copy.copy(\n        kwargs.get(\n            \"experiment_mitex\",\n            MitEx(\n                backend,\n                _label=\"ExperimentMitex\",\n                mitres=gen_compiled_MitRes(backend, 0),\n            ),\n        )\n    )\n    _characterisation_mitex = copy.copy(\n        kwargs.get(\n            \"characterisation_mitex\",\n            MitEx(\n                backend,\n                _label=\"CharacterisationMitex\",\n                mitres=gen_compiled_MitRes(backend, 0),\n            ),\n        )\n    )\n\n    _characterisation_taskgraph = TaskGraph().from_TaskGraph(_characterisation_mitex)\n    _experiment_taskgraph = TaskGraph().from_TaskGraph(_experiment_mitex)\n\n    _characterisation_taskgraph.add_wire()\n    _characterisation_taskgraph.prepend(DFSC_collater_task_gen())\n    _characterisation_taskgraph.append(DFSC_characterisation_task_gen())\n\n    _experiment_taskgraph.parallel(\n        MitEx(backend).from_TaskGraph(_characterisation_taskgraph)\n    )\n    _experiment_taskgraph.prepend(DFSC_circuit_task_gen())\n    _experiment_taskgraph.append(\n        DFSC_correction_task_gen(kwargs.get(\"DFSC_threshold\", 0.01))\n    )\n    return MitEx(backend).from_TaskGraph(_experiment_taskgraph)\n", "meta": {"hexsha": "2e66c83a15a24f16b5861eb2a7a0cff3478514a0", "size": 15767, "ext": "py", "lang": "Python", "max_stars_repo_path": "qermit/clifford_noise_characterisation/dfsc.py", "max_stars_repo_name": "CQCL/qermit", "max_stars_repo_head_hexsha": "931e8ee3bfcf4497f4be9e9278a9544d3136e67c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2021-05-28T00:20:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T14:14:27.000Z", "max_issues_repo_path": "qermit/clifford_noise_characterisation/dfsc.py", "max_issues_repo_name": "CQCL/qermit", "max_issues_repo_head_hexsha": "931e8ee3bfcf4497f4be9e9278a9544d3136e67c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-10-08T10:13:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T20:23:07.000Z", "max_forks_repo_path": "qermit/clifford_noise_characterisation/dfsc.py", "max_forks_repo_name": "CQCL/qermit", "max_forks_repo_head_hexsha": "931e8ee3bfcf4497f4be9e9278a9544d3136e67c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-06-11T10:04:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T19:19:22.000Z", "avg_line_length": 43.197260274, "max_line_length": 132, "alphanum_fraction": 0.6809792605, "include": true, "reason": "from numpy", "num_tokens": 3321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.19666720619014788}}
{"text": "from typing import Dict, Tuple, Text, Sequence\nfrom pydantic import BaseModel\nfrom clu.phontools import features\nimport numpy as np\n\n\nclass PhonemeErrors(BaseModel):\n    \"\"\"\n    stores phoneme errors.\n    \"\"\"\n\n    insertions: Sequence[Tuple[Text, Text]]\n    deletions: Sequence[Tuple[Text, Text]]\n    substitutions: Sequence[Tuple[Text, Text]]\n\n    @property\n    def edit_distance(self) -> int:\n        return len(self.insertions) + len(self.deletions) + len(self.substitutions)\n\n    def to_dict(self) -> Dict[str, float]:\n        return {\n            \"insertions\": self.insertions,\n            \"deletions\": self.deletions,\n            \"substitutions\": self.substitutions,\n        }\n\n\nclass ReAline:\n    \"\"\"\n    Feature-based algorithm for aligning two sequences of phones.\n\n    Based on Kondrak 2002\n    \"\"\"\n\n    inf = float(\"inf\")\n\n    def __init__(\n        self,\n        similarity_matrix=features.similarity_matrix,\n        feature_matrix=features.feature_matrix,\n        salience=features.salience,\n        consonants=features.consonants,\n        C_skip=features.C_skip,\n        C_vwl=features.C_vwl,\n        C_sub=features.C_sub,\n        C_exp=features.C_exp,\n        R_c=features.R_c,\n        R_v=features.R_v,\n    ):\n        self.similarity_matrix = similarity_matrix\n        self.feature_matrix = feature_matrix\n        self.consonants = consonants\n        self.salience = salience\n        self.C_skip = C_skip\n        # weight assigned to vowel, consonant pairs\n        self.C_vwl = C_vwl\n        self.C_sub = C_sub\n        self.C_exp = C_exp\n        # List of relevant features for consonants\n        self.R_c = R_c\n        # List of relevant features for vowels\n        self.R_v = R_v\n        # sanity check\n        self.sanity_check()\n\n    @staticmethod\n    def phoneme_errors(alignments: Sequence[Tuple[Text, Text]]) -> PhonemeErrors:\n        \"\"\"\n        Counts insertions, deletions, and substitutions according to the output of Re-Aline\n        \"\"\"\n        insertions = []\n        deletions = []\n        substitutions = []\n        for pair in alignments:\n            (phone_1, phone_2) = pair\n            if phone_1 == \"-\":\n                insertions.append(pair)\n            elif phone_2 == \"-\":\n                deletions.append(pair)\n            elif phone_1 != phone_2 and phone_1 != \"-\" and phone_2 != \"-\":\n                substitutions.append(pair)\n        return PhonemeErrors(\n            insertions=insertions, deletions=deletions, substitutions=substitutions\n        )\n\n    def sanity_check(self):\n        \"\"\"\n        Sanity check that ensures necessary features are present\n        \"\"\"\n\n        similarity_matrix = self.similarity_matrix\n        feature_matrix = self.feature_matrix\n        salience = self.salience\n        consonants = self.consonants\n\n        # ensure all salience values are found in feature matrix\n        feats = set()\n        feat_values = set()\n        for phone_fm in feature_matrix.values():\n            for (k, v) in phone_fm.items():\n                feats.add(k)\n                feat_values.add(v)\n\n        assert (\n            len(salience.keys() - feats) == 0\n        ), f\"salience and features for each sound in feature_matrix do not match: {salience.keys() - feats}\"\n\n        assert (\n            len(similarity_matrix.keys() - feat_values) == 0\n        ), f\"similarity_matrix and feature values for each sound in feature_matrix do not match: {similarity_matrix.keys() - feat_values}\"\n\n        missing = [c for c in consonants if c not in feature_matrix.keys()]\n        assert (\n            len(missing) == 0\n        ), f\"Some consonants missing from feature_matrix: {missing}\"\n\n    def sigma_skip(self, p: Text) -> int:\n        \"\"\"\n        Returns score of an indel of P.\n        (Kondrak 2002: 54)\n        \"\"\"\n        return self.C_skip\n\n    def V(self, p: Text) -> int:\n        \"\"\"\n        Return vowel weight if P is vowel.\n        (Kondrak 2002: 54)\n        \"\"\"\n        return 0 if p in self.consonants else self.C_vwl\n\n    def R(self, p: Text, q: Text) -> Sequence[Text]:\n        \"\"\"\n        Return relevant features for segment comparsion.\n        (Kondrak 2002: 54)\n        \"\"\"\n        consonants = self.consonants\n\n        return self.R_c if p in consonants or q else self.R_v\n\n    def diff(self, p: Text, q: Text, f: Text) -> int:\n        \"\"\"\n        Returns difference between phonetic segments P and Q for feature F.\n        (Kondrak 2002: 52, 54)\n        \"\"\"\n        p_features, q_features = self.feature_matrix[p], self.feature_matrix[q]\n        return abs(\n            self.similarity_matrix[p_features[f]]\n            - self.similarity_matrix[q_features[f]]\n        )\n\n    def delta(self, p: Text, q: Text) -> int:\n        \"\"\"\n        Return weighted sum of difference between P and Q.\n        (Kondrak 2002: 54)\n        \"\"\"\n        features = self.R(p, q)\n        total = 0\n        for f in features:\n            total += self.diff(p, q, f) * self.salience[f]\n        return total\n\n    def sigma_sub(self, p: Text, q: Text) -> int:\n        \"\"\"\n        Returns score of a substitution of P with Q.\n        (Kondrak 2002: 54)\n        \"\"\"\n        return self.C_sub - self.delta(p, q) - self.V(p) - self.V(q)\n\n    def sigma_exp(self, p: Text, q: Sequence[Text]) -> int:\n        \"\"\"\n        Returns score of an expansion/compression.\n        (Kondrak 2002: 54)\n        \"\"\"\n        q1 = q[0]\n        q2 = q[1]\n        return (\n            self.C_exp\n            - self.delta(p, q1)\n            - self.delta(p, q2)\n            - self.V(p)\n            - max(self.V(q1), self.V(q2))\n        )\n\n    def _retrieve(self, i, j, s, S, T, seq1, seq2, out) -> Sequence[Tuple[Text, Text]]:\n        \"\"\"\n        Retrieve the path through the similarity matrix S starting at (i, j).\n\n        :return: Alignment of seq1 and seq2\n        \"\"\"\n        if S[i, j] == 0:\n            return out\n        else:\n            if (\n                j > 1\n                and S[i - 1, j - 2] + self.sigma_exp(seq1[i - 1], seq2[j - 2 : j]) + s\n                >= T\n            ):\n                out.insert(0, (seq1[i - 1], seq2[j - 2 : j]))\n                self._retrieve(\n                    i - 1,\n                    j - 2,\n                    s + self.sigma_exp(seq1[i - 1], seq2[j - 2 : j]),\n                    S,\n                    T,\n                    seq1,\n                    seq2,\n                    out,\n                )\n            elif (\n                i > 1\n                and S[i - 2, j - 1] + self.sigma_exp(seq2[j - 1], seq1[i - 2 : i]) + s\n                >= T\n            ):\n                out.insert(0, (seq1[i - 2 : i], seq2[j - 1]))\n                self._retrieve(\n                    i - 2,\n                    j - 1,\n                    s + self.sigma_exp(seq2[j - 1], seq1[i - 2 : i]),\n                    S,\n                    T,\n                    seq1,\n                    seq2,\n                    out,\n                )\n            elif S[i, j - 1] + self.sigma_skip(seq2[j - 1]) + s >= T:\n                out.insert(0, (\"-\", seq2[j - 1]))\n                self._retrieve(\n                    i, j - 1, s + self.sigma_skip(seq2[j - 1]), S, T, seq1, seq2, out\n                )\n            elif S[i - 1, j] + self.sigma_skip(seq1[i - 1]) + s >= T:\n                out.insert(0, (seq1[i - 1], \"-\"))\n                self._retrieve(\n                    i - 1, j, s + self.sigma_skip(seq1[i - 1]), S, T, seq1, seq2, out\n                )\n            elif S[i - 1, j - 1] + self.sigma_sub(seq1[i - 1], seq2[j - 1]) + s >= T:\n                out.insert(0, (seq1[i - 1], seq2[j - 1]))\n                self._retrieve(\n                    i - 1,\n                    j - 1,\n                    s + self.sigma_sub(seq1[i - 1], seq2[j - 1]),\n                    S,\n                    T,\n                    seq1,\n                    seq2,\n                    out,\n                )\n        return out\n\n    def align(\n        self, seq1: Sequence[Text], seq2: Sequence[Text], epsilon: float = 0\n    ) -> Sequence[Tuple[Text, Text]]:\n        \"\"\"\n        Computes the alignment of two symbol sequences.\n\n        :param seq1: a sequence of symbols\n        :param seq2: a sequence of symbols\n\n        :type epsilon: float (0.0 to 1.0)\n        :param epsilon: Adjusts threshold similarity score for near-optimal alignments\n        :return: Alignment(s) of seq1 and seq2\n        (Kondrak 2002: 51)\n        \"\"\"\n\n        assert 0.0 <= epsilon <= 1.0, \"Epsilon must be between 0.0 and 1.0.\"\n\n        m = len(seq1)\n        n = len(seq2)\n        # This includes Kondrak's initialization of row 0 and column 0 to all 0s.\n        S = np.zeros((m + 1, n + 1), dtype=float)\n        # If i <= 1 or j <= 1, don't allow expansions as it doesn't make sense,\n        # and breaks array and string indices. Make sure they never get chosen\n        # by setting them to -inf.\n        for i in range(1, m + 1):\n            for j in range(1, n + 1):\n                edit1 = S[i - 1, j] + self.sigma_skip(seq1[i - 1])\n                edit2 = S[i, j - 1] + self.sigma_skip(seq2[j - 1])\n                edit3 = S[i - 1, j - 1] + self.sigma_sub(seq1[i - 1], seq2[j - 1])\n                if i > 1:\n                    edit4 = S[i - 2, j - 1] + self.sigma_exp(\n                        seq2[j - 1], seq1[i - 2 : i]\n                    )\n                else:\n                    edit4 = -ReAline.inf\n                if j > 1:\n                    edit5 = S[i - 1, j - 2] + self.sigma_exp(\n                        seq1[i - 1], seq2[j - 2 : j]\n                    )\n                else:\n                    edit5 = -ReAline.inf\n                S[i, j] = max(edit1, edit2, edit3, edit4, edit5, 0)\n        T = (1 - epsilon) * np.amax(S)  # Threshold score for near-optimal alignments\n\n        alignments = []\n        for i in range(1, m + 1):\n            for j in range(1, n + 1):\n                if S[i, j] >= T:\n                    alignments.append(self._retrieve(i, j, 0, S, T, seq1, seq2, []))\n        return [pair for alignment in alignments for pair in alignment]\n", "meta": {"hexsha": "65c20ab5c9c3d5a7bd7c3ac397b636e5dd6c7138", "size": 10002, "ext": "py", "lang": "Python", "max_stars_repo_path": "clu/phontools/alignment/realine.py", "max_stars_repo_name": "clu-ling/clu-phontools", "max_stars_repo_head_hexsha": "304510150c6f9a4b0e1372bc9275630b7f976aeb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "clu/phontools/alignment/realine.py", "max_issues_repo_name": "clu-ling/clu-phontools", "max_issues_repo_head_hexsha": "304510150c6f9a4b0e1372bc9275630b7f976aeb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-06-15T23:32:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-01T18:49:20.000Z", "max_forks_repo_path": "clu/phontools/alignment/realine.py", "max_forks_repo_name": "clu-ling/clu-phontools", "max_forks_repo_head_hexsha": "304510150c6f9a4b0e1372bc9275630b7f976aeb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-18T05:48:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-18T05:48:29.000Z", "avg_line_length": 33.4515050167, "max_line_length": 138, "alphanum_fraction": 0.4927014597, "include": true, "reason": "import numpy", "num_tokens": 2603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.37022539954425293, "lm_q1q2_score": 0.19666719700365673}}
{"text": "#!/usr/bin python\n# -*- coding: utf-8 -*-\n# FIXME: -par_plot option fails:\n# ValueError: range parameter must be finite\n# ('vis_range', [nan, nan])\n# ('ticks', [nan, nan])\n\n\nfrom __future__ import (print_function)\nimport os\nimport sys\nimport argparse\nimport matplotlib\nmatplotlib.use('Agg')\nlabel_size = 6\nmatplotlib.rcParams['xtick.labelsize'] = label_size\nmatplotlib.rcParams['ytick.labelsize'] = label_size\npath = os.path.normpath(os.path.join(os.path.dirname(sys.argv[0]), '..'))\nsys.path.insert(0, path)\nimport glob\nimport numpy as np\nfrom vlbi_errors.uv_data import UVData\nfrom vlbi_errors.spydiff import (import_difmap_model, modelfit_difmap)\nfrom vlbi_errors.bootstrap import CleanBootstrap\nfrom vlbi_errors.model import Model\nfrom vlbi_errors.utils import hdi_of_mcmc\n\ntry:\n    import corner as triangle\nexcept ImportError:\n    triangle = None\n\noutname = 'boot_uv'\nerrors_fname = 'bootstrap_errors.txt'\n\n\nif 'DIFMAP_LOGIN' in os.environ:\n    del os.environ['DIFMAP_LOGIN']\n\n\ndef xy_2_rtheta(params):\n    flux, x, y = params[:3]\n    r = np.sqrt(x ** 2 + y ** 2)\n    theta = np.rad2deg(np.arctan(x / y))\n    result = [flux, r, theta]\n    try:\n        result.extend(params[3:])\n    except IndexError:\n        pass\n    return result\n\n\ndef analyze_bootstrap_samples(dfm_model_fname, booted_mdl_paths,\n                              dfm_model_dir=None, plot_comps=None,\n                              plot_file=None, txt_file=None, cred_mass=0.68,\n                              coordinates='xy'):\n    \"\"\"\n    Plot bootstrap distribution of model component parameters.\n\n    :param dfm_model_fname:\n        File name of original difmap model.\n    :param booted_mdl_paths:\n        Iterable of paths to bootstrapped difmap models.\n    :param dfm_model_dir: (optional)\n        Directory with original difmap model. If ``None`` then CWD. (default:\n        ``None``)\n    :param plot_comps: (optional)\n        Iterable of components number to plot on same plot. If ``None`` then\n        plot parameter distributions of all components.\n    :param plot_file: (optional)\n        File to save picture. If ``None`` then don't save picture. (default:\n        ``None``)\n    :param txt_file: (optional)\n        File to save credible intervals for parameters. If ``None`` then don't\n        save credible intervals. (default: ``None``)\n    :param cred_mass: (optional)\n        Value of credible interval mass. Float in range (0., 1.). (default:\n        ``0.68``)\n    :param coordinates: (optional)\n        Type of coordinates to use. ``xy`` or ``rtheta``. (default: ``xy``)\n    \"\"\"\n    n_boot = len(booted_mdl_paths)\n    # Get params of initial model used for bootstrap\n    comps_orig = import_difmap_model(dfm_model_fname, dfm_model_dir)\n    comps_params0 = {i: [] for i in range(len(comps_orig))}\n    for i, comp in enumerate(comps_orig):\n        # FIXME: Move (x, y) <-> (r, theta) mapping to ``Component``\n        if coordinates == 'xy':\n            params = comp.p\n        elif coordinates == 'rtheta':\n            params = xy_2_rtheta(comp.p)\n        else:\n            raise Exception\n        comps_params0[i].extend(list(params))\n\n    # Load bootstrap models\n    comps_params = {i: [] for i in range(len(comps_orig))}\n    for booted_mdl_path in booted_mdl_paths:\n        path, booted_mdl_file = os.path.split(booted_mdl_path)\n        comps = import_difmap_model(booted_mdl_file, path)\n        for i, comp in enumerate(comps):\n            # FIXME: Move (x, y) <-> (r, theta) mapping to ``Component``\n            if coordinates == 'xy':\n                params = comp.p\n            elif coordinates == 'rtheta':\n                params = xy_2_rtheta(comp.p)\n            else:\n                raise Exception\n            comps_params[i].extend(list(params))\n\n    comps_to_plot = [comps_orig[k] for k in plot_comps]\n    # (#boot, #parameters)\n    boot_data = np.hstack(np.array(comps_params[i]).reshape((n_boot,\n                                                             comps_orig[i].size)) for\n                          i in plot_comps)\n\n    # Optionally plot\n    if plot_file:\n        if triangle:\n            lens = list(np.cumsum([comp.size for comp in comps_orig]))\n            lens.insert(0, 0)\n\n            labels = list()\n            for comp in comps_to_plot:\n                for lab in np.array(comp._parnames)[~comp._fixed]:\n                    # FIXME: Move (x, y) <-> (r, theta) mapping to ``Component``\n                    if coordinates == 'rtheta':\n                        if lab == 'x':\n                            lab = 'r'\n                        if lab == 'y':\n                            lab = 'theta'\n                    elif coordinates == 'xy':\n                        pass\n                    else:\n                        raise Exception\n                    labels.append(lab)\n\n            try:\n                n = sum([c.size for c in comps_to_plot])\n                figure, axes = matplotlib.pyplot.subplots(nrows=n, ncols=n)\n                figure.set_size_inches(19.5, 19.5)\n                triangle.corner(boot_data, labels=labels, plot_contours=False,\n                                truths=np.hstack([comps_params0[i] for i in\n                                                  plot_comps]),\n                                title_kwargs={\"fontsize\": 6},\n                                label_kwargs={\"fontsize\": 6},\n                                quantiles=[0.16, 0.5, 0.84], fig=figure,\n                                use_math_text=True, show_titles=True,\n                                title_fmt=\".3f\")\n                figure.gca().annotate(\"Components {}\".format(plot_comps),\n                                      xy=(0.5, 1.0),\n                                      xycoords=\"figure fraction\",\n                                      xytext=(0, -5),\n                                      textcoords=\"offset points\", ha=\"center\",\n                                      va=\"top\")\n                figure.savefig(plot_file, bbox_inches='tight', dpi=300)\n            except ValueError:\n                print(\"Failed to plot... ValueError\")\n        else:\n            print(\"Install ``corner`` for corner-plots\")\n\n    if txt_file:\n        # Print credible intervals\n        fn = open(txt_file, 'w')\n        fn.write(\"# parameter original.value low.boot high.boot mean.boot\"\n                 \" median.boot (mean-low).boot (high-mean).boot\\n\")\n        recorded = 0\n        for i in plot_comps:\n            comp = comps_orig[i]\n            for j in range(comp.size):\n                low, high, mean, median = hdi_of_mcmc(boot_data[:, recorded+j],\n                                                      cred_mass=cred_mass,\n                                                      return_mean_median=True)\n                # FIXME: Move (x, y) <-> (r, theta) mapping to ``Component``\n                parnames = comp._parnames\n                if coordinates == 'xy':\n                    params = comp.p\n                elif coordinates == 'rtheta':\n                    params = xy_2_rtheta(comp.p)\n                    parnames[1] = 'r'\n                    parnames[2] = 'theta'\n                else:\n                    raise Exception\n                fn.write(\"{:<4} {:.4f} {:.4f} {:.4f} {:.4f} {:.4f} {:.4f}\"\n                         \" {:.4f}\".format(parnames[j], params[j], low,\n                                          high, mean, median, abs(median - low),\n                                          abs(high - median)))\n                fn.write(\"\\n\")\n            recorded += (j + 1)\n        fn.close()\n\n\nif __name__ == \"__main__\":\n    parser = \\\n        argparse.ArgumentParser(description='Bootstrap Difmap models.\\n'\n                                            ' Required '\n                                            'arguments are ``dfm_model_path`` &'\n                                            ' one of the ``-uv_fits_path`` or'\n                                            ' ``-booted_mdl_path``. If'\n                                            ' ``-booted_mdl_path`` is used then'\n                                            ' options ``-parametric``,'\n                                            ' ``-n_boot``, ``-n_iter``,'\n                                            ' ``-res_plot`` are not used.')\n\n    parser.add_argument('dfm_model_path', type=str, metavar='dfm_model_path',\n                        help='Path to Difmap-format file with model.')\n    parser.add_argument('-uv_fits_path', action='store', nargs='?', type=str,\n                        metavar='PATH TO UV-DATA FITS FILE', default=None,\n                        help='Path to FITS-file with self-calibrated UV-data.')\n    parser.add_argument('-booted_mdl_card', action='store', nargs='?', type=str,\n                        default=None,\n                        help='Wildcard to find bootstrapped model'\n                             ' files', metavar='WILCARD WITH FULL PATH')\n    parser.add_argument('-n_boot', action='store', nargs='?', default=100,\n                        type=int, help='Number of bootstrap realizations.'\n                                       ' Default value = 100',\n                        metavar='INT')\n    parser.add_argument('-n_iter', action='store', nargs='?', default=50,\n                        type=int, help='Number of iterations in difmap internal'\n                                       ' fitting. Default is 50.',\n                        metavar='INT')\n    parser.add_argument('-cred_value', action='store', nargs='?', default=0.68,\n                        type=float, help='Credible interval specification.'\n                                         ' Float from (0, 1) interval. Default'\n                                         ' is 0.68.',\n                        metavar='FLOAT FROM (0, 1)')\n    parser.add_argument('-out_dir', action='store', nargs='?',\n                        default=os.getcwd(), type=str, help='Directory to store'\n                                                     ' bootstrap files, models'\n                                                     ' & results.',\n                        metavar='DIRECTORY')\n    parser.add_argument('-errors_file', action='store', nargs='?',\n                        default='bootstrap_errors.txt', type=str,\n                        help='File name to store bootstrap errors. Default is'\n                             '`bootstrap_errors.txt`.',\n                        metavar='FILE NAME')\n    parser.add_argument('-res_plot', action='store', nargs='?', default=None,\n                        type=str, help='File name to store IF-averages'\n                                       ' residuals of Stokes I real & imag part'\n                                       ' plot in output directory.',\n                        metavar='FILE NAME')\n    parser.add_argument('-amplitude_scale_sigma', action='store', nargs='?',\n                        default=None, type=float, help='Sigma of amplitude'\n                                                       ' scale. In fractions of'\n                                                       ' amplitude.',\n                        metavar='FLOAT nearly 0.05-0.1')\n    parser.add_argument('-res_plot_full', action='store', nargs='?', default=None,\n                        type=str, help='File name to store residuals of Stokes '\n                                       'RR & LL real & imag part'\n                                       ' plot in output directory.',\n                        metavar='FILE NAME')\n    parser.add_argument('-par_plot', action='store', nargs='?', default=None,\n                        type=str, help='File name to store parameters plot in'\n                                       ' output directory.',\n                        metavar='FILE NAME')\n    parser.add_argument('-plot_comps', action='store', nargs='+', default=None,\n                        type=str, help='Components numbers to plot.',\n                        metavar='COMPONENT #')\n    parser.add_argument('-txt_comps', action='store', nargs='*', default=None,\n                        type=str, help='Components numbers to output'\n                                       ' parameters in a text file.',\n                        metavar='COMPONENT #')\n    parser.add_argument('-parametric', action='store_true', dest='parametric',\n                        default=False,\n                        help='Use parametric bootstrap instead of'\n                             ' nonparametric (nonparametric is the default).')\n    parser.add_argument('-recenter', action='store_true', dest='recenter',\n                        default=False,\n                        help='Recenter residuals on each baseline.')\n    parser.add_argument('-clean_after', action='store_true', dest='clean_after',\n                        default=False,\n                        help='Remove bootstrapped data & model files in the'\n                             ' end.')\n    parser.add_argument('-bic', action='store_true', dest='bic',\n                        default=False,\n                        help='Calculate BIC criterion value for original model'\n                             ' and bootstrapped samples.')\n    parser.add_argument('-rtheta', action='store_true', dest='use_rtheta',\n                        default=False,\n                        help='Use `r-theta` coordinates instead of `xy`.')\n    parser.add_argument('-split_scans', action='store_true', dest='split_scans',\n                        default=False, help='Resample each scan individually?')\n\n    args = parser.parse_args()\n\n    data_dir = args.out_dir\n    if not os.path.exists(data_dir):\n        os.makedirs(data_dir)\n    print(\"Data directory: {}\".format(data_dir))\n\n    cred_value = args.cred_value\n    uv_fits_path = args.uv_fits_path\n    booted_mdl_card = args.booted_mdl_card\n    dfm_model_path = args.dfm_model_path\n    n_boot = args.n_boot\n    niter = args.n_iter\n    nonparametric = not args.parametric\n    errors_fname = args.errors_file\n    par_plot = args.par_plot\n    recenter = args.recenter\n    plot_comps = args.plot_comps\n    txt_comps = args.txt_comps\n    split_scans = args.split_scans\n    amplitude_scale_sigma = args.amplitude_scale_sigma\n\n    bic = args.bic\n    if args.use_rtheta:\n        coordinates = 'rtheta'\n    else:\n        coordinates = 'xy'\n\n    if par_plot and not plot_comps:\n        raise Exception(\"Use -plot_comps argument to specify # of components\"\n                        \" to plot\")\n\n    dfm_model_dir, dfm_model_fname = os.path.split(dfm_model_path)\n    try:\n        comps = import_difmap_model(dfm_model_fname, dfm_model_dir)\n    except ValueError:\n        print(\"Problem importing difmap model...\")\n        sys.exit(1)\n\n    # Check that component numbers in input are among model components\n    if plot_comps:\n        for c in plot_comps:\n            if int(c) not in range(len(comps)):\n                raise Exception(\"No such component {} in current\"\n                                \" model!\".format(c))\n    if not txt_comps:\n        txt_comps = range(len(comps))\n    else:\n        txt_comps = [int(k) for k in txt_comps]\n    for c in txt_comps:\n        if int(c) not in range(len(comps)):\n            raise Exception(\"No such component {} in current model!\".format(c))\n\n    if uv_fits_path:\n        print(\"Bootstrapping uv-data\")\n        uv_fits_dir, uv_fits_fname = os.path.split(uv_fits_path)\n        boot_type_dict = {True: \"non-parametric\", False: \"parametric\"}\n        print(\"==================================\")\n        print(\"Bootstrap uv-data: {}\".format(uv_fits_fname))\n        print(\"With model: {}\".format(dfm_model_fname))\n        print(\"Using {} bootstrap\".format(boot_type_dict[nonparametric]))\n        if not nonparametric:\n            if recenter:\n                print(\"Recentering KDE-fitted residuals\")\n            else:\n                print(\"Using fitted KDE Model to generate resamples\")\n        print(\"Using {} bootstrap replications\".format(n_boot))\n        if amplitude_scale_sigma:\n            print(\"Using amplitude sigma for scale\"\n                  \" = {}\".format(amplitude_scale_sigma))\n        print(\"Using {} fitting iterations\".format(niter))\n        print(\"Finding {}-confidence regions\".format(cred_value))\n        print(\"Using directory {} for storing output\".format(data_dir))\n        txt_save_dict = {'None': \"all\"}\n        try:\n            print(\"Saving errors of {} components to file\"\n                  \" {}\".format(txt_save_dict[str(txt_comps)], errors_fname))\n        except KeyError:\n            print(\"Saving errors of {} components to file\"\n                  \" {}\".format(txt_comps, errors_fname))\n\n        if split_scans:\n            print(\"Resampling each scan individually\")\n        if par_plot:\n            print(\"Saving components {} parameters distributions plot to file\"\n                  \" {}\".format(plot_comps, par_plot))\n        if args.res_plot:\n            print(\"Saving residuals I plot to file {}\".format(args.res_plot))\n        if args.res_plot_full:\n            print(\"Saving residulas RR & LL plots to files\"\n                  \" {}*\".format(args.res_plot_full))\n        print(\"==================================\")\n\n        uvdata = UVData(uv_fits_path)\n        model = Model(stokes='I')\n        model.add_components(*comps)\n\n        if bic:\n            bic_orig = model.bic(uvdata)\n            bic_booted = list()\n\n        try:\n            boot = CleanBootstrap([model], uvdata,\n                                  sigma_ampl_scale=amplitude_scale_sigma)\n        # If uv-data contains only one Stokes parameter (e.g. `0838+133`)\n        except IndexError:\n            print(\"Problem in bootstrapping data...\")\n            sys.exit(1)\n        # FIXME: Broken - ValueError\n        if args.res_plot:\n            print(\"Plotting histograms of I residuals...\")\n            boot.plot_residuals(args.res_plot)\n\n        curdir = os.getcwd()\n        os.chdir(data_dir)\n        boot.run(n=n_boot, nonparametric=nonparametric, outname=[outname,\n                                                                 '.fits'],\n                 recenter=recenter, use_kde=True, use_v=False)\n        if args.res_plot_full:\n            print(\"Plotting histograms of RR & LL residuals...\")\n            boot.plot_residuals_trio(args.res_plot_full, split_scans,\n                                     stokes=['RR', 'LL'])\n\n        os.chdir(curdir)\n\n        booted_uv_paths = sorted(glob.glob(os.path.join(data_dir,\n                                                        outname + \"*\")))\n        booted_mdl_paths = list()\n        # Modelfit bootstrapped uvdata\n        for booted_uv_path in booted_uv_paths:\n            path, booted_uv_file = os.path.split(booted_uv_path)\n            i = booted_uv_file.split('_')[-1].split('.')[0]\n            out_fname = dfm_model_fname + '_' + i\n            modelfit_difmap(booted_uv_file, dfm_model_fname, out_fname,\n                            path=path, mdl_path=dfm_model_dir,\n                            out_path=data_dir, niter=niter)\n            booted_mdl_paths.append(os.path.join(data_dir, out_fname))\n            if bic:\n                uvdata_ = UVData(booted_uv_path)\n                model_ = Model(stokes='I')\n                comps_ = import_difmap_model(out_fname, data_dir)\n                model_.add_components(comps_)\n                bic_booted.append(model_.bic(uvdata_))\n\n        if bic:\n            low_, high_, mean_, median_ = hdi_of_mcmc(bic_booted,\n                                                      cred_mass=0.68,\n                                                      return_mean_median=True)\n            print(\"Model BIC with bootstrapped 68% interval = {:.2f}\"\n                  \" -{:.2f} +{:.2f}\".format(bic_orig, abs(mean_ - low_),\n                                            abs(high_ - mean_)))\n\n    elif booted_mdl_card:\n        print(\"Using already bootstrapped uv-data\")\n        booted_mdl_paths = glob.glob(booted_mdl_card)\n        n_boot = len(booted_mdl_paths)\n        print(\"==================================\")\n        print(\"With {} bootstrap replications\".format(n_boot))\n        print(\"Finding {}-confidence regions\".format(cred_value))\n        print(\"Using directory {} for storing output\".format(data_dir))\n        txt_save_dict = {'None': \"all\"}\n        try:\n            print(\"Saving errors of {} components to file\"\n                  \" {}\".format(txt_save_dict[str(txt_comps)], errors_fname))\n        except KeyError:\n            print(\"Saving errors of {} components to file\"\n                  \" {}\".format(txt_comps, errors_fname))\n        if par_plot:\n            print(\"Saving components {} parameters distributions plot to file\"\n                  \" {}\".format(plot_comps, par_plot))\n        print(\"==================================\")\n\n    else:\n        raise Exception(\"Use -uv_fits_path or -booted_mdl_card to create/get\"\n                        \" bootstrapped models.\")\n\n    # Optionally plot component parameters\n    if par_plot:\n        plot_comps = [int(k) for k in plot_comps]\n        analyze_bootstrap_samples(dfm_model_fname, booted_mdl_paths,\n                                  dfm_model_dir=dfm_model_dir,\n                                  plot_comps=plot_comps,\n                                  plot_file=os.path.join(data_dir, par_plot),\n                                  cred_mass=cred_value,\n                                  coordinates=coordinates)\n    analyze_bootstrap_samples(dfm_model_fname, booted_mdl_paths,\n                              dfm_model_dir=dfm_model_dir,\n                              plot_comps=txt_comps,\n                              txt_file=os.path.join(data_dir, errors_fname),\n                              cred_mass=cred_value, coordinates=coordinates)\n\n    if args.clean_after:\n        for rmfile in booted_uv_paths:\n            os.unlink(rmfile)\n        for rmfile in booted_mdl_paths:\n            os.unlink(rmfile)\n", "meta": {"hexsha": "9645f8cf706925f5ca3413046ac3fa6762c8c99d", "size": 21768, "ext": "py", "lang": "Python", "max_stars_repo_path": "silke/boot_silke.py", "max_stars_repo_name": "akutkin/SACA", "max_stars_repo_head_hexsha": "2d9b759e2de91734f7f7b61b8810ffbd73443d9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "silke/boot_silke.py", "max_issues_repo_name": "akutkin/SACA", "max_issues_repo_head_hexsha": "2d9b759e2de91734f7f7b61b8810ffbd73443d9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-10-16T20:36:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-24T19:28:01.000Z", "max_forks_repo_path": "silke/boot_silke.py", "max_forks_repo_name": "ipashchenko/ve", "max_forks_repo_head_hexsha": "b866b6d9465310d4cd5bb4d2e92595d918b681d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.35, "max_line_length": 85, "alphanum_fraction": 0.5210859978, "include": true, "reason": "import numpy", "num_tokens": 4487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306515, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.1966671933124602}}
{"text": "\"\"\"\n@author: reubendo\n\"\"\"\n\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, print_function, division\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom niftynet.layer.base_layer import TrainableLayer\nfrom niftynet.layer.convolution import ConvolutionalLayer\nfrom niftynet.layer.deconvolution import DeconvolutionalLayer\nfrom niftynet.layer.fully_connected import FullyConnectedLayer\nfrom niftynet.layer.activation import ActiLayer\nfrom niftynet.layer.bn import InstanceNormLayer\nfrom niftynet.layer.convolution import ConvLayer\nfrom niftynet.layer.elementwise import ElementwiseLayer\nfrom niftynet.layer.downsample import DownSampleLayer as Pooling\nfrom niftynet.layer.linear_resize import LinearResizeLayer\n\n\nMODALITIES = ['T1', 'T1c', 'T2', 'Flair', 'seg']\n\nHIDDEN_SPACE = 512\n\nNB_CONV = 8\ntf.set_random_seed(1)\nclass U_HeMIS(TrainableLayer):\n    \"\"\"\n    Implementation of U-HeMIS introduced [1] mixing HeMIS [2] and a U-Net architecture [3]\n    [1] Dorent, et al. \"Hetero-Modal Variational Encoder-Decoder for\n        Joint Modality Completion and Segmentation\". \n        MICCAI 2019.\n    [2] Havaei, et al. \"HeMIS: Hetero-Modal Image Segmentation\". \n        MICCAI 2016. https://arxiv.org/abs/1607.05194\n    [3] Ronneberger, et al. \"U-Net: Convolutional Networks for Biomedical Image Segmentation\". \n        MICCAI 2015. https://arxiv.org/abs/1505.04597\n    \"\"\"\n\n    def __init__(self,\n                num_classes,\n                w_initializer=None,\n                w_regularizer=None,\n                b_initializer=None,\n                b_regularizer=None,\n                acti_func='leakyrelu',\n                name='VAE'):\n\n        super(U_HeMIS, self).__init__(name=name)\n\n        self.initializers = {'w': w_initializer, 'b': b_initializer}\n        self.regularizers = {'w': w_regularizer, 'b': b_regularizer}\n        self.num_classes = num_classes\n\n    def layer_op(self, images, choices, is_training=True, is_inference=False, **unused_kwargs):\n\n        encoder = ConvEncoder(w_initializer=self.initializers['w'], w_regularizer=self.regularizers['w'], b_initializer=self.initializers['b'],b_regularizer=self.regularizers['b'])\n\n        abstraction_op = HeMISAbstractionBlock()\n\n        img_decoder = ConvDecoderImg(w_initializer=self.initializers['w'], w_regularizer=self.regularizers['w'], b_initializer=self.initializers['b'],b_regularizer=self.regularizers['b'])\n\n\n        mod_img = MODALITIES[:4]\n\n        # Encode the input\n        list_skips = encoder(images)\n\n        # Sample from the posterior distribution P(latent variables|input)\n        skip_flow = []\n        for k in range(len(list_skips)):\n            sample = abstraction_op(list_skips[k],  choices,  is_inference)\n            skip_flow.append(sample)\n\n        img_output = img_decoder(skip_flow)\n\n        \n\n\n        return img_output\n\n\nclass ConvEncoder(TrainableLayer):\n    \"\"\"\n        Each modality are encoded indepedently.\n    \"\"\"\n\n    def __init__(self,\n                 w_initializer=None,\n                 w_regularizer=None,\n                 b_initializer=None,\n                 b_regularizer=None,\n                 name='ConvEncoder'):\n\n        super(ConvEncoder, self).__init__(name=name)\n\n\n        self.initializers = {'w': w_initializer, 'b': b_initializer}\n        self.regularizers = {'w': w_regularizer, 'b': b_regularizer}\n\n        self.ini_f = NB_CONV\n        self.layers = [\n            {'name': 'conv_0', 'n_features': self.ini_f, 'kernel_size': (1,1,1)},\n            {'name': 'block_1', 'n_features': self.ini_f, 'kernels': ((3,3,3), (3,3,3)), 'downsampling':True},\n            {'name': 'block_2', 'n_features': 2*self.ini_f, 'kernels': ((3,3,3), (3,3,3)), 'downsampling':True},\n            {'name': 'block_3', 'n_features': 4*self.ini_f, 'kernels': ((3,3,3), (3,3,3)), 'downsampling':True},\n            {'name': 'block_4', 'n_features': 8*self.ini_f, 'kernels': ((3,3,3), (3,3,3)), 'downsampling':False}]\n\n        self.skip_ind = [1, 3, 5, 7]\n        self.hidden = [self.layers[k]['n_features'] for k in range(1,len(self.layers))] \n        self.hidden = [int(k/2) for k in self.hidden]\n        \n\n    def layer_op(self, images):\n        # Define the encoding convolutional layers\n        def clip(input):\n            # This is for clipping logvars,\n            # so that variances = exp(logvars) behaves well\n            output = tf.maximum(input, -50)\n            output = tf.minimum(output, 50)\n            return output\n        \n        layer_instances = [] #list layers\n        means = dict()\n        logvars = dict()\n\n        pooling_params = {'kernel_size': 2, 'stride': 2}\n\n\n        list_skip_flow = [[] for k in range(len(self.skip_ind))]\n\n        layer_fc_mod = dict()\n        layer_cnn_mod = dict()\n        \n\n        for mod in MODALITIES[:4]:\n            layer_cnn_mod[mod] = []\n            layer_fc_mod[mod] = []\n\n\n            params = self.layers[0]\n            first_conv_layer = ConvolutionalLayer(\n                n_output_chns=params['n_features'],\n                kernel_size=params['kernel_size'],\n                acti_func='leakyrelu',\n                with_bn=False,\n                w_initializer=self.initializers['w'],\n                w_regularizer=self.regularizers['w'],\n                name='%s_%s' % (params['name'],mod))\n            \n            layer_instances.append(first_conv_layer)\n            layer_cnn_mod[mod].append(first_conv_layer)\n\n\n            for i in range(1,len(self.layers)):\n\n                params = self.layers[i]\n                res_block = ResBlock(\n                    n_output_chns=params['n_features'],\n                    kernels=params['kernels'],\n                    acti_func='leakyrelu',\n                    encoding=True,\n                    w_initializer=self.initializers['w'],\n                    w_regularizer=self.regularizers['w'],\n                    name='%s_%s' % (params['name'],mod))\n                layer_instances.append(res_block)\n                layer_cnn_mod[mod].append(res_block)\n                \n                if params['downsampling']:    \n                    downsampler = Pooling(func='MAX', kernel_size=2, stride=2,)\n\n                    layer_instances.append(downsampler)\n                    layer_cnn_mod[mod].append(downsampler)\n\n\n\n\n        \n        for mod in MODALITIES[:4]:\n            flow_mod = images[mod]\n            print(flow_mod)\n            \n            for ind, cnn_mod in enumerate(layer_cnn_mod[mod]):\n                \n                flow_mod = cnn_mod(flow_mod)\n                layer_cnn_mod[mod][ind] = cnn_mod\n                if ind in self.skip_ind:\n                    pos = self.skip_ind.index(ind)\n                    list_skip_flow[pos].append(flow_mod)\n                print(flow_mod)\n            print('list_flow')\n        \n        print(list_skip_flow)\n            \n\n        output = list_skip_flow\n\n\n\n        if True:\n            self._print(layer_instances)\n            return output\n        return output\n\n    def _print(self, list_of_layers):\n        for op in list_of_layers:\n            print(op)\n\nclass HeMISAbstractionBlock(TrainableLayer):\n    def __init__(self,\n                 pooling_type='average',\n                 name='HeMISAbstractionBlock'):\n\n        super(HeMISAbstractionBlock, self).__init__(name=name)\n\n        self.pooling_type = pooling_type\n        self.name = name\n\n    def layer_op(self, input_tensor, choices, is_training):\n        \"\"\"\n        Written by Thomas Varsavsky.\n\n        Function will drop all zero columns and compute E[C] and Var[C]\n        :param backend_output: backend_output\n        :return: 1xC tensor where C is the number of features.\n        \"\"\"\n        # Omit zero columns from average\n        # intermediate_tensor = tf.reduce_sum(tf.abs(input_tensor), 0)\n        # zero_vector = tf.zeros(shape=(1, 1), dtype=tf.float32)\n        # bool_mask = tf.not_equal(intermediate_tensor, zero_vector)\n        # omit_zero_columns = tf.boolean_mask(input_tensor, bool_mask)\n        # Compute E[C]\n        input_tensor = tf.boolean_mask(input_tensor, choices)\n        average_over_modalities, variance_between_modalities = tf.nn.moments(input_tensor, axes=[0])\n        abstraction_output = tf.concat([average_over_modalities, variance_between_modalities], axis=-1)\n        return abstraction_output\n\n\nclass ConvDecoderImg(TrainableLayer):\n    \"\"\"\n    Each modality are then decoded using the average of the skip-connections across\n    the available modalities. \n    \"\"\"\n\n    def __init__(self,\n                 w_initializer=None,\n                 w_regularizer=None,\n                 b_initializer=None,\n                 b_regularizer=None,\n                 name='ConvDecoderImg'):\n\n        super(ConvDecoderImg, self).__init__(name=name)\n\n\n        self.initializers = {'w': w_initializer, 'b': b_initializer}\n        self.regularizers = {'w': w_regularizer, 'b': b_regularizer}\n\n        self.ini_f = NB_CONV\n        self.layers = [\n            {'name': 'block_1', 'n_features': 4*self.ini_f, 'kernels': ((3,3,3), (3,3,3))},\n            {'name': 'block_2', 'n_features': 2*self.ini_f, 'kernels': ((3,3,3), (3,3,3))},\n            {'name': 'block_3', 'n_features': self.ini_f, 'kernels': ((3,3,3), (3,3,3))}]\n\n    def layer_op(self, list_skips):\n\n        # Define the decoding convolutional layers\n        layer_instances = [] #list layers\n        layer_mod = dict()\n        decoders_fc = dict()\n        flow = dict()\n\n        list_skips = list_skips[::-1]\n\n        for mod in ['seg']:\n            layer_mod[mod] = []\n\n            flow_mod = list_skips[0]\n\n            if mod =='seg':\n                double = True\n                n_output = 4\n            else:\n                double = True\n                n_output = 1\n\n            for i in range(len(self.layers)):\n                \n                params = self.layers[i]\n\n                flow_mod = LinearResizeLayer(list_skips[i+1].shape.as_list()[1:-1])(flow_mod)\n\n                print(mod)\n                print(flow_mod)\n                print('added with ')\n                print(list_skips[i+1])\n                flow_mod = ElementwiseLayer('CONCAT')(flow_mod, list_skips[i+1])\n                print(flow_mod)\n\n\n                res_block = ResBlock(\n                    n_output_chns=params['n_features'],\n                    kernels=params['kernels'],\n                    acti_func='leakyrelu',\n                    encoding=False,\n                    double_n = double,\n                    w_initializer=self.initializers['w'],\n                    w_regularizer=self.regularizers['w'],\n                    name='%s_%s' % (params['name'],mod))\n                layer_instances.append(res_block)\n                layer_mod[mod].append(res_block)\n                flow_mod = res_block(flow_mod)\n\n\n            last_conv = ConvolutionalLayer(\n                n_output_chns=n_output,\n                kernel_size=(1,1,1),\n                with_bn=False,\n                acti_func=None,\n                w_initializer=self.initializers['w'],\n                w_regularizer=self.regularizers['w'],\n                name='final_conv_seg')\n            layer_instances.append(last_conv)\n            flow_mod = last_conv(flow_mod)\n            flow[mod] = flow_mod\n\n        if True:\n            self._print(layer_instances)\n            return flow['seg']\n        return flow['seg']\n    \n    def _print(self, list_of_layers):\n        for op in list_of_layers:\n            print(op)\n\nclass ResBlock(TrainableLayer):\n    \"\"\"\n    This class define a high-resolution block with residual connections\n    kernels\n\n        - specify kernel sizes of each convolutional layer\n        - e.g.: kernels=(5, 5, 5) indicate three conv layers of kernel_size 5\n\n    with_res\n\n        - whether to add residual connections to bypass the conv layers\n    \"\"\"\n\n    def __init__(self,\n                 n_output_chns,\n                 kernels=((3,3,3), (3,3,3)),\n                 acti_func='leakyrelu',\n                 encoding=False,\n                 double_n = True,\n                 w_initializer=None,\n                 w_regularizer=None,\n                 with_res=True,\n                 name='ResBlock',\n                 stride=1):\n\n        super(ResBlock, self).__init__(name=name)\n\n        self.n_output_chns = n_output_chns\n        if hasattr(kernels, \"__iter__\"):  # a list of layer kernel_sizes\n            self.kernels = kernels\n        else:  # is a single number (indicating single layer)\n            self.kernels = [kernels]\n        self.acti_func = acti_func\n        self.with_res = with_res\n\n        self.initializers = {'w': w_initializer}\n        self.regularizers = {'w': w_regularizer}\n        self.stride = stride\n        self.encoding = encoding\n        self.double_n = double_n\n        self.kernels = self.kernels if double_n else [self.kernels[0]]\n\n    def layer_op(self, input_tensor):\n        output_tensor = input_tensor\n        for (i, k) in enumerate(self.kernels):\n            # create parameterised layers\n            if self.encoding:\n                if i==0:\n                    nb_channels = self.n_output_chns\n                elif i==1:\n                    nb_channels = int(self.n_output_chns/2)\n            else:\n                if self.double_n:\n                    if i==0:\n                        nb_channels = self.n_output_chns\n                    elif i==1:\n                        nb_channels = int(self.n_output_chns/2)\n                else:\n                    nb_channels = int(self.n_output_chns/2)\n\n            in_op = InstanceNormLayer(name='in_{}'.format(i))\n            acti_op = ActiLayer(func=self.acti_func,\n                                regularizer=self.regularizers['w'],\n                                name='acti_{}'.format(i))\n            conv_op = ConvLayer(n_output_chns=nb_channels,\n                                kernel_size=k,\n                                stride=self.stride,\n                                w_initializer=self.initializers['w'],\n                                w_regularizer=self.regularizers['w'],\n                                name='conv_{}'.format(i))\n            # connect layers\n            output_tensor = in_op(output_tensor)\n            output_tensor = acti_op(output_tensor)\n            output_tensor = conv_op(output_tensor)\n        # make residual connections\n        # if self.with_res:\n        #     output_tensor = ElementwiseLayer('SUM')(output_tensor, input_tensor)\n        return output_tensor\n\n\n", "meta": {"hexsha": "98e74a01892c655b9a5765b427e07068d8c2f34f", "size": 14383, "ext": "py", "lang": "Python", "max_stars_repo_path": "extensions/u_hemis/u_hemis_net.py", "max_stars_repo_name": "ReubenDo/U-HVED", "max_stars_repo_head_hexsha": "1d293a87d496c52adafd69dbcea37767ac6a7ee8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2019-10-29T08:04:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T12:17:28.000Z", "max_issues_repo_path": "extensions/u_hemis/u_hemis_net.py", "max_issues_repo_name": "ReubenDo/U-HVED", "max_issues_repo_head_hexsha": "1d293a87d496c52adafd69dbcea37767ac6a7ee8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-01-28T22:14:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T23:31:15.000Z", "max_forks_repo_path": "extensions/u_hemis/u_hemis_net.py", "max_forks_repo_name": "ReubenDo/U-HVED", "max_forks_repo_head_hexsha": "1d293a87d496c52adafd69dbcea37767ac6a7ee8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-02-10T23:59:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T05:22:41.000Z", "avg_line_length": 34.5745192308, "max_line_length": 187, "alphanum_fraction": 0.5652506431, "include": true, "reason": "import numpy", "num_tokens": 3260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.19666719142536115}}
{"text": "from collections import defaultdict\nfrom collections.abc import MutableSequence, Iterable\nimport io\n\nimport numpy as np\nfrom numpy.polynomial import Polynomial\nimport pandas as pd\n\nfrom .data import NEUTRON_MASS\nfrom .endf import get_head_record, get_cont_record, get_tab1_record, get_list_record\ntry:\n    from .reconstruct import wave_number, penetration_shift, reconstruct_mlbw, \\\n        reconstruct_slbw, reconstruct_rm\n    _reconstruct = True\nexcept ImportError:\n    _reconstruct = False\nimport openmc.checkvalue as cv\n\n\nclass Resonances(object):\n    \"\"\"Resolved and unresolved resonance data\n\n    Parameters\n    ----------\n    ranges : list of openmc.data.ResonanceRange\n        Distinct energy ranges for resonance data\n\n    Attributes\n    ----------\n    ranges : list of openmc.data.ResonanceRange\n        Distinct energy ranges for resonance data\n    resolved : openmc.data.ResonanceRange or None\n        Resolved resonance range\n    unresolved : openmc.data.Unresolved or None\n        Unresolved resonance range\n\n    \"\"\"\n\n    def __init__(self, ranges):\n        self.ranges = ranges\n\n    def __iter__(self):\n        for r in self.ranges:\n            yield r\n\n    @property\n    def ranges(self):\n        return self._ranges\n\n    @property\n    def resolved(self):\n        resolved_ranges = [r for r in self.ranges\n                           if not isinstance(r, Unresolved)]\n        if len(resolved_ranges) > 1:\n            raise ValueError('More than one resolved range present')\n        elif len(resolved_ranges) == 0:\n            return None\n        else:\n            return resolved_ranges[0]\n\n    @property\n    def unresolved(self):\n        for r in self.ranges:\n            if isinstance(r, Unresolved):\n                return r\n        else:\n            return None\n\n    @ranges.setter\n    def ranges(self, ranges):\n        cv.check_type('resonance ranges', ranges, MutableSequence)\n        self._ranges = cv.CheckedList(ResonanceRange, 'resonance ranges',\n                                      ranges)\n\n    @classmethod\n    def from_endf(cls, ev):\n        \"\"\"Generate resonance data from an ENDF evaluation.\n\n        Parameters\n        ----------\n        ev : openmc.data.endf.Evaluation\n            ENDF evaluation\n\n        Returns\n        -------\n        openmc.data.Resonances\n            Resonance data\n\n        \"\"\"\n        file_obj = io.StringIO(ev.section[2, 151])\n\n        # Determine whether discrete or continuous representation\n        items = get_head_record(file_obj)\n        n_isotope = items[4]  # Number of isotopes\n\n        ranges = []\n        for iso in range(n_isotope):\n            items = get_cont_record(file_obj)\n            abundance = items[1]\n            fission_widths = (items[3] == 1)  # fission widths are given?\n            n_ranges = items[4]  # number of resonance energy ranges\n\n            for j in range(n_ranges):\n                items = get_cont_record(file_obj)\n                resonance_flag = items[2]  # flag for resolved (1)/unresolved (2)\n                formalism = items[3]  # resonance formalism\n\n                if resonance_flag in (0, 1):\n                    # resolved resonance region\n                    erange = _FORMALISMS[formalism].from_endf(ev, file_obj, items)\n\n                elif resonance_flag == 2:\n                    # unresolved resonance region\n                    erange = Unresolved.from_endf(file_obj, items, fission_widths)\n\n                # erange.material = self\n                ranges.append(erange)\n\n        return cls(ranges)\n\n\nclass ResonanceRange(object):\n    \"\"\"Resolved resonance range\n\n    Parameters\n    ----------\n    target_spin : float\n        Intrinsic spin, :math:`I`, of the target nuclide\n    energy_min : float\n        Minimum energy of the resolved resonance range in eV\n    energy_max : float\n        Maximum energy of the resolved resonance range in eV\n    channel : dict\n        Dictionary whose keys are l-values and values are channel radii as a\n        function of energy\n    scattering : dict\n        Dictionary whose keys are l-values and values are scattering radii as a\n        function of energy\n\n    Attributes\n    ----------\n    channel_radius : dict\n        Dictionary whose keys are l-values and values are channel radii as a\n        function of energy\n    energy_max : float\n        Maximum energy of the resolved resonance range in eV\n    energy_min : float\n        Minimum energy of the resolved resonance range in eV\n    scattering_radius : dict\n        Dictionary whose keys are l-values and values are scattering radii as a\n        function of energ\n    target_spin : float\n        Intrinsic spin, :math:`I`, of the target nuclide\n\n    \"\"\"\n    def __init__(self, target_spin, energy_min, energy_max, channel, scattering):\n        self.target_spin = target_spin\n        self.energy_min = energy_min\n        self.energy_max = energy_max\n        self.channel_radius = channel\n        self.scattering_radius = scattering\n\n        self._prepared = False\n        self._parameter_matrix = {}\n\n    def __copy__(self):\n        cls = type(self)\n        new_copy = cls.__new__(cls)\n        new_copy.__dict__.update(self.__dict__)\n        new_copy._prepared = False\n        return new_copy\n\n    @classmethod\n    def from_endf(cls, ev, file_obj, items):\n        \"\"\"Create resonance range from an ENDF evaluation.\n\n        This factory method is only used when LRU=0, indicating that only a\n        scattering radius appears in MF=2, MT=151. All subclasses of\n        ResonanceRange override this method with their own.\n\n        Parameters\n        ----------\n        ev : openmc.data.endf.Evaluation\n            ENDF evaluation\n        file_obj : file-like object\n            ENDF file positioned at the second record of a resonance range\n            subsection in MF=2, MT=151\n        items : list\n            Items from the CONT record at the start of the resonance range\n            subsection\n\n        Returns\n        -------\n        openmc.data.ResonanceRange\n            Resonance range data\n\n        \"\"\"\n        energy_min, energy_max = items[0:2]\n\n        # For scattering radius-only, NRO must be zero\n        assert items[4] == 0\n\n        # Get energy-independent scattering radius\n        items = get_cont_record(file_obj)\n        target_spin = items[0]\n        ap = Polynomial((items[1],))\n\n        # Calculate channel radius from ENDF-102 equation D.14\n        a = Polynomial((0.123 * (NEUTRON_MASS*ev.target['mass'])**(1./3.) + 0.08,))\n\n        return cls(target_spin, energy_min, energy_max, {0: a}, {0: ap})\n\n    def reconstruct(self, energies):\n        \"\"\"Evaluate cross section at specified energies.\n\n        Parameters\n        ----------\n        energies : float or Iterable of float\n            Energies at which the cross section should be evaluated\n\n        Returns\n        -------\n        3-tuple of float or numpy.ndarray\n            Elastic, capture, and fission cross sections at the specified\n            energies\n\n        \"\"\"\n        if not _reconstruct:\n            raise RuntimeError(\"Resonance reconstruction not available.\")\n\n        # Pre-calculate penetrations and shifts for resonances\n        if not self._prepared:\n            self._prepare_resonances()\n\n        if isinstance(energies, Iterable):\n            elastic = np.zeros_like(energies)\n            capture = np.zeros_like(energies)\n            fission = np.zeros_like(energies)\n\n            for i, E in enumerate(energies):\n                xse, xsg, xsf = self._reconstruct(self, E)\n                elastic[i] = xse\n                capture[i] = xsg\n                fission[i] = xsf\n        else:\n            elastic, capture, fission = self._reconstruct(self, energies)\n\n        return {2: elastic, 102: capture, 18: fission}\n\n\nclass MultiLevelBreitWigner(ResonanceRange):\n    \"\"\"Multi-level Breit-Wigner resolved resonance formalism data.\n\n    Multi-level Breit-Wigner resolved resonance data is identified by LRF=2 in\n    the ENDF-6 format.\n\n    Parameters\n    ----------\n    target_spin : float\n        Intrinsic spin, :math:`I`, of the target nuclide\n    energy_min : float\n        Minimum energy of the resolved resonance range in eV\n    energy_max : float\n        Maximum energy of the resolved resonance range in eV\n    channel : dict\n        Dictionary whose keys are l-values and values are channel radii as a\n        function of energy\n    scattering : dict\n        Dictionary whose keys are l-values and values are scattering radii as a\n        function of energy\n\n    Attributes\n    ----------\n    atomic_weight_ratio : float\n        Atomic weight ratio of the target nuclide given as a function of\n        l-value. Note that this may be different than the value for the\n        evaluation as a whole.\n    channel_radius : dict\n        Dictionary whose keys are l-values and values are channel radii as a\n        function of energy\n    energy_max : float\n        Maximum energy of the resolved resonance range in eV\n    energy_min : float\n        Minimum energy of the resolved resonance range in eV\n    parameters : pandas.DataFrame\n        Energies, spins, and resonances widths for each resonance\n    q_value : dict\n        Q-value to be added to incident particle's center-of-mass energy to\n        determine the channel energy for use in the penetrability factor. The\n        keys of the dictionary are l-values.\n    scattering_radius : dict\n        Dictionary whose keys are l-values and values are scattering radii as a\n        function of energy\n    target_spin : float\n        Intrinsic spin, :math:`I`, of the target nuclide\n\n    \"\"\"\n\n    def __init__(self, target_spin, energy_min, energy_max, channel, scattering):\n        super().__init__(target_spin, energy_min, energy_max, channel,\n                         scattering)\n        self.parameters = None\n        self.q_value = {}\n        self.atomic_weight_ratio = None\n\n        # Set resonance reconstruction function\n        if _reconstruct:\n            self._reconstruct = reconstruct_mlbw\n        else:\n            self._reconstruct = None\n\n    @classmethod\n    def from_endf(cls, ev, file_obj, items):\n        \"\"\"Create MLBW data from an ENDF evaluation.\n\n        Parameters\n        ----------\n        ev : openmc.data.endf.Evaluation\n            ENDF evaluation\n        file_obj : file-like object\n            ENDF file positioned at the second record of a resonance range\n            subsection in MF=2, MT=151\n        items : list\n            Items from the CONT record at the start of the resonance range\n            subsection\n\n        Returns\n        -------\n        openmc.data.MultiLevelBreitWigner\n            Multi-level Breit-Wigner resonance parameters\n\n        \"\"\"\n\n        # Read energy-dependent scattering radius if present\n        energy_min, energy_max = items[0:2]\n        nro, naps = items[4:6]\n        if nro != 0:\n            params, ape = get_tab1_record(file_obj)\n\n        # Other scatter radius parameters\n        items = get_cont_record(file_obj)\n        target_spin = items[0]\n        ap = Polynomial((items[1],))  # energy-independent scattering-radius\n        NLS = items[4]  # number of l-values\n\n        # Read resonance widths, J values, etc\n        channel_radius = {}\n        scattering_radius = {}\n        q_value = {}\n        records = []\n        for l in range(NLS):\n            items, values = get_list_record(file_obj)\n            l_value = items[2]\n            awri = items[0]\n            q_value[l_value] = items[1]\n            competitive = items[3]\n\n            # Calculate channel radius from ENDF-102 equation D.14\n            a = Polynomial((0.123 * (NEUTRON_MASS*awri)**(1./3.) + 0.08,))\n\n            # Construct scattering and channel radius\n            if nro == 0:\n                scattering_radius[l_value] = ap\n                if naps == 0:\n                    channel_radius[l_value] = a\n                elif naps == 1:\n                    channel_radius[l_value] = ap\n            elif nro == 1:\n                scattering_radius[l_value] = ape\n                if naps == 0:\n                    channel_radius[l_value] = a\n                elif naps == 1:\n                    channel_radius[l_value] = ape\n                elif naps == 2:\n                    channel_radius[l_value] = ap\n\n            energy = values[0::6]\n            spin = values[1::6]\n            gt = np.asarray(values[2::6])\n            gn = np.asarray(values[3::6])\n            gg = np.asarray(values[4::6])\n            gf = np.asarray(values[5::6])\n            if competitive > 0:\n                gx = gt - (gn + gg + gf)\n            else:\n                gx = np.zeros_like(gt)\n\n            for i, E in enumerate(energy):\n                records.append([energy[i], l_value, spin[i], gt[i], gn[i],\n                                gg[i], gf[i], gx[i]])\n\n        columns = ['energy', 'L', 'J', 'totalWidth', 'neutronWidth',\n                   'captureWidth', 'fissionWidth', 'competitiveWidth']\n        parameters = pd.DataFrame.from_records(records, columns=columns)\n\n        # Create instance of class\n        mlbw = cls(target_spin, energy_min, energy_max,\n                   channel_radius, scattering_radius)\n        mlbw.q_value = q_value\n        mlbw.atomic_weight_ratio = awri\n        mlbw.parameters = parameters\n\n        return mlbw\n\n    def _prepare_resonances(self):\n        df = self.parameters.copy()\n\n        # Penetration and shift factors\n        p = np.zeros(len(df))\n        s = np.zeros(len(df))\n\n        # Penetration and shift factors for competitive reaction\n        px = np.zeros(len(df))\n        sx = np.zeros(len(df))\n\n        l_values = []\n        competitive = []\n\n        A = self.atomic_weight_ratio\n        for i, E, l, J, gt, gn, gg, gf, gx in df.itertuples():\n            if l not in l_values:\n                l_values.append(l)\n                competitive.append(gx > 0)\n\n            # Determine penetration and shift corresponding to resonance energy\n            k = wave_number(A, E)\n            rho = k*self.channel_radius[l](E)\n            rhohat = k*self.scattering_radius[l](E)\n            p[i], s[i] = penetration_shift(l, rho)\n\n            # Determine penetration at modified energy for competitive reaction\n            if gx > 0:\n                Ex = E + self.q_value[l]*(A + 1)/A\n                rho = k*self.channel_radius[l](Ex)\n                rhohat = k*self.scattering_radius[l](Ex)\n                px[i], sx[i] = penetration_shift(l, rho)\n            else:\n                px[i] = sx[i] = 0.0\n\n        df['p'] = p\n        df['s'] = s\n        df['px'] = px\n        df['sx'] = sx\n\n        self._l_values = np.array(l_values)\n        self._competitive = np.array(competitive)\n        for l in l_values:\n            self._parameter_matrix[l] = df[df.L == l].values\n\n        self._prepared = True\n\n\nclass SingleLevelBreitWigner(MultiLevelBreitWigner):\n    \"\"\"Single-level Breit-Wigner resolved resonance formalism data.\n\n    Single-level Breit-Wigner resolved resonance data is is identified by LRF=1\n    in the ENDF-6 format.\n\n    Parameters\n    ----------\n    target_spin : float\n        Intrinsic spin, :math:`I`, of the target nuclide\n    energy_min : float\n        Minimum energy of the resolved resonance range in eV\n    energy_max : float\n        Maximum energy of the resolved resonance range in eV\n    channel : dict\n        Dictionary whose keys are l-values and values are channel radii as a\n        function of energy\n    scattering : dict\n        Dictionary whose keys are l-values and values are scattering radii as a\n        function of energy\n\n    Attributes\n    ----------\n    atomic_weight_ratio : float\n        Atomic weight ratio of the target nuclide given as a function of\n        l-value. Note that this may be different than the value for the\n        evaluation as a whole.\n    channel_radius : dict\n        Dictionary whose keys are l-values and values are channel radii as a\n        function of energy\n    energy_max : float\n        Maximum energy of the resolved resonance range in eV\n    energy_min : float\n        Minimum energy of the resolved resonance range in eV\n    parameters : pandas.DataFrame\n        Energies, spins, and resonances widths for each resonance\n    q_value : dict\n        Q-value to be added to incident particle's center-of-mass energy to\n        determine the channel energy for use in the penetrability factor. The\n        keys of the dictionary are l-values.\n    scattering_radius : dict\n        Dictionary whose keys are l-values and values are scattering radii as a\n        function of energy\n    target_spin : float\n        Intrinsic spin, :math:`I`, of the target nuclide\n\n    \"\"\"\n\n    def __init__(self, target_spin, energy_min, energy_max, channel, scattering):\n        super().__init__(target_spin, energy_min, energy_max, channel,\n                         scattering)\n\n        # Set resonance reconstruction function\n        if _reconstruct:\n            self._reconstruct = reconstruct_slbw\n        else:\n            self._reconstruct = None\n\n\nclass ReichMoore(ResonanceRange):\n    \"\"\"Reich-Moore resolved resonance formalism data.\n\n    Reich-Moore resolved resonance data is identified by LRF=3 in the ENDF-6\n    format.\n\n    Parameters\n    ----------\n    target_spin : float\n        Intrinsic spin, :math:`I`, of the target nuclide\n    energy_min : float\n        Minimum energy of the resolved resonance range in eV\n    energy_max : float\n        Maximum energy of the resolved resonance range in eV\n    channel : dict\n        Dictionary whose keys are l-values and values are channel radii as a\n        function of energy\n    scattering : dict\n        Dictionary whose keys are l-values and values are scattering radii as a\n        function of energy\n\n    Attributes\n    ----------\n    angle_distribution : bool\n        Indicate whether parameters can be used to compute angular distributions\n    atomic_weight_ratio : float\n        Atomic weight ratio of the target nuclide given as a function of\n        l-value. Note that this may be different than the value for the\n        evaluation as a whole.\n    channel_radius : dict\n        Dictionary whose keys are l-values and values are channel radii as a\n        function of energy\n    energy_max : float\n        Maximum energy of the resolved resonance range in eV\n    energy_min : float\n        Minimum energy of the resolved resonance range in eV\n    num_l_convergence : int\n        Number of l-values which must be used to converge the calculation\n    scattering_radius : dict\n        Dictionary whose keys are l-values and values are scattering radii as a\n        function of energy\n    parameters : pandas.DataFrame\n        Energies, spins, and resonances widths for each resonance\n    target_spin : float\n        Intrinsic spin, :math:`I`, of the target nuclide\n\n    \"\"\"\n\n    def __init__(self, target_spin, energy_min, energy_max, channel, scattering):\n        super().__init__(target_spin, energy_min, energy_max, channel,\n                         scattering)\n        self.parameters = None\n        self.angle_distribution = False\n        self.num_l_convergence = 0\n\n        # Set resonance reconstruction function\n        if _reconstruct:\n            self._reconstruct = reconstruct_rm\n        else:\n            self._reconstruct = None\n\n    @classmethod\n    def from_endf(cls, ev, file_obj, items):\n        \"\"\"Create Reich-Moore resonance data from an ENDF evaluation.\n\n        Parameters\n        ----------\n        ev : openmc.data.endf.Evaluation\n            ENDF evaluation\n        file_obj : file-like object\n            ENDF file positioned at the second record of a resonance range\n            subsection in MF=2, MT=151\n        items : list\n            Items from the CONT record at the start of the resonance range\n            subsection\n\n        Returns\n        -------\n        openmc.data.ReichMoore\n            Reich-Moore resonance parameters\n\n        \"\"\"\n        # Read energy-dependent scattering radius if present\n        energy_min, energy_max = items[0:2]\n        nro, naps = items[4:6]\n        if nro != 0:\n            params, ape = get_tab1_record(file_obj)\n\n        # Other scatter radius parameters\n        items = get_cont_record(file_obj)\n        target_spin = items[0]\n        ap = Polynomial((items[1],))\n        angle_distribution = (items[3] == 1)  # Flag for angular distribution\n        NLS = items[4]  # Number of l-values\n        num_l_convergence = items[5]  # Number of l-values for convergence\n\n        # Read resonance widths, J values, etc\n        channel_radius = {}\n        scattering_radius = {}\n        records = []\n        for i in range(NLS):\n            items, values = get_list_record(file_obj)\n            apl = Polynomial((items[1],)) if items[1] != 0.0 else ap\n            l_value = items[2]\n            awri = items[0]\n\n            # Calculate channel radius from ENDF-102 equation D.14\n            a = Polynomial((0.123 * (NEUTRON_MASS*awri)**(1./3.) + 0.08,))\n\n            # Construct scattering and channel radius\n            if nro == 0:\n                scattering_radius[l_value] = apl\n                if naps == 0:\n                    channel_radius[l_value] = a\n                elif naps == 1:\n                    channel_radius[l_value] = apl\n            elif nro == 1:\n                if naps == 0:\n                    channel_radius[l_value] = a\n                    scattering_radius[l_value] = ape\n                elif naps == 1:\n                    channel_radius[l_value] = scattering_radius[l_value] = ape\n                elif naps == 2:\n                    channel_radius[l_value] = apl\n                    scattering_radius[l_value] = ape\n\n            energy = values[0::6]\n            spin = values[1::6]\n            gn = values[2::6]\n            gg = values[3::6]\n            gfa = values[4::6]\n            gfb = values[5::6]\n\n            for i, E in enumerate(energy):\n                records.append([energy[i], l_value, spin[i], gn[i], gg[i],\n                                gfa[i], gfb[i]])\n\n        # Create pandas DataFrame with resonance data\n        columns = ['energy', 'L', 'J', 'neutronWidth', 'captureWidth',\n                   'fissionWidthA', 'fissionWidthB']\n        parameters = pd.DataFrame.from_records(records, columns=columns)\n\n        # Create instance of ReichMoore\n        rm = cls(target_spin, energy_min, energy_max,\n                 channel_radius, scattering_radius)\n        rm.parameters = parameters\n        rm.angle_distribution = angle_distribution\n        rm.num_l_convergence = num_l_convergence\n        rm.atomic_weight_ratio = awri\n\n        return rm\n\n    def _prepare_resonances(self):\n        df = self.parameters.copy()\n\n        # Penetration and shift factors\n        p = np.zeros(len(df))\n        s = np.zeros(len(df))\n\n        l_values = []\n        lj_values = []\n\n        A = self.atomic_weight_ratio\n        for i, E, l, J, gn, gg, gfa, gfb in df.itertuples():\n            if l not in l_values:\n                l_values.append(l)\n            if (l, abs(J)) not in lj_values:\n                lj_values.append((l, abs(J)))\n\n            # Determine penetration and shift corresponding to resonance energy\n            k = wave_number(A, E)\n            rho = k*self.channel_radius[l](E)\n            rhohat = k*self.scattering_radius[l](E)\n            p[i], s[i] = penetration_shift(l, rho)\n\n        df['p'] = p\n        df['s'] = s\n\n        self._l_values = np.array(l_values)\n        for (l, J) in lj_values:\n            self._parameter_matrix[l, J] = df[(df.L == l) &\n                                              (abs(df.J) == J)].values\n\n        self._prepared = True\n\n\nclass RMatrixLimited(ResonanceRange):\n    \"\"\"R-matrix limited resolved resonance formalism data.\n\n    R-matrix limited resolved resonance data is identified by LRF=7 in the\n    ENDF-6 format.\n\n    Parameters\n    ----------\n    energy_min : float\n        Minimum energy of the resolved resonance range in eV\n    energy_max : float\n        Maximum energy of the resolved resonance range in eV\n    particle_pairs : list of dict\n        List of particle pairs. Each particle pair is represented by a\n        dictionary that contains the mass, atomic number, spin, and parity of\n        each particle as well as other characteristics.\n    spin_groups : list of dict\n        List of spin groups. Each spin group is characterized by channels,\n        resonance energies, and resonance widths.\n\n    Attributes\n    ----------\n    reduced_width : bool\n        Flag indicating whether channel widths in eV or reduced-width amplitudes\n        in eV^1/2 are given\n    formalism : int\n        Flag to specify which formulae for the R-matrix are to be used\n    particle_pairs : list of dict\n        List of particle pairs. Each particle pair is represented by a\n        dictionary that contains the mass, atomic number, spin, and parity of\n        each particle as well as other characteristics.\n    spin_groups : list of dict\n        List of spin groups. Each spin group is characterized by channels,\n        resonance energies, and resonance widths.\n\n    \"\"\"\n\n    def __init__(self, energy_min, energy_max, particle_pairs, spin_groups):\n        super().__init__(0.0, energy_min, energy_max, None, None)\n        self.reduced_width = False\n        self.formalism = 3\n        self.particle_pairs = particle_pairs\n        self.spin_groups = spin_groups\n\n    @classmethod\n    def from_endf(cls, ev, file_obj, items):\n        \"\"\"Read R-Matrix limited resonance data from an ENDF evaluation.\n\n        Parameters\n        ----------\n        ev : openmc.data.endf.Evaluation\n            ENDF evaluation\n        file_obj : file-like object\n            ENDF file positioned at the second record of a resonance range\n            subsection in MF=2, MT=151\n        items : list\n            Items from the CONT record at the start of the resonance range\n            subsection\n\n        Returns\n        -------\n        openmc.data.RMatrixLimited\n            R-matrix limited resonance parameters\n\n        \"\"\"\n        energy_min, energy_max = items[0:2]\n\n        items = get_cont_record(file_obj)\n        reduced_width = (items[2] == 1)  # reduced width amplitude?\n        formalism = items[3]  # Specify which formulae are used\n        n_spin_groups = items[4]  # Number of Jpi values (NJS)\n\n        particle_pairs = []\n        spin_groups = []\n\n        items, values = get_list_record(file_obj)\n        n_pairs = items[5]//2  # Number of particle pairs (NPP)\n        for i in range(n_pairs):\n            first = {'mass': values[12*i],\n                     'z': int(values[12*i + 2]),\n                     'spin': values[12*i + 4],\n                     'parity': values[12*i + 10]}\n            second = {'mass': values[12*i + 1],\n                      'z': int(values[12*i + 3]),\n                      'spin': values[12*i + 5],\n                      'parity': values[12*i + 11]}\n\n            q_value = values[12*i + 6]\n            penetrability = values[12*i + 7]\n            shift = values[12*i + 8]\n            mt = int(values[12*i + 9])\n\n            particle_pairs.append(ParticlePair(\n                first, second, q_value, penetrability, shift, mt))\n\n        # loop over spin groups\n        for i in range(n_spin_groups):\n            items, values = get_list_record(file_obj)\n            J = items[0]\n            if J == 0.0:\n                parity = '+' if items[1] == 1.0 else '-'\n            else:\n                parity = '+' if J > 0. else '-'\n                J = abs(J)\n            kbk = items[2]\n            kps = items[3]\n            n_channels = items[5]\n            channels = []\n            for j in range(n_channels):\n                channel = {}\n                channel['particle_pair'] = particle_pairs[\n                    int(values[6*j]) - 1]\n                channel['l'] = values[6*j + 1]\n                channel['spin'] = values[6*j + 2]\n                channel['boundary'] = values[6*j + 3]\n                channel['effective_radius'] = values[6*j + 4]\n                channel['true_radius'] = values[6*j + 5]\n                channels.append(channel)\n\n            # Read resonance energies and widths\n            items, values = get_list_record(file_obj)\n            n_resonances = items[3]\n            records = []\n            m = n_channels//6 + 1\n            for j in range(n_resonances):\n                energy = values[6*m*j]\n                records.append([energy] + [values[6*m*j + k + 1]\n                                           for k in range(n_channels)])\n\n            # Determine column names\n            columns = ['energy']\n            for channel in channels:\n                mt = channel['particle_pair'].mt\n                if mt == 2:\n                    columns.append('neutronWidth')\n                elif mt == 18:\n                    columns.append('fissionWidth')\n                elif mt == 102:\n                    columns.append('captureWidth')\n                else:\n                    columns.append('width (MT={})'.format(mt))\n\n            # Create Pandas dataframe with resonance parameters\n            parameters = pd.DataFrame.from_records(records, columns=columns)\n\n            # Construct SpinGroup instance and add to list\n            sg = SpinGroup(J, parity, channels, parameters)\n            spin_groups.append(sg)\n\n            # Optional extension (Background R-Matrix)\n            if kbk > 0:\n                items, values = get_list_record(file_obj)\n                lbk = items[4]\n                if lbk == 1:\n                    params, rbr = get_tab1_record(file_obj)\n                    params, rbi = get_tab1_record(file_obj)\n\n            # Optional extension (Tabulated phase shifts)\n            if kps > 0:\n                items, values = get_list_record(file_obj)\n                lps = items[4]\n                if lps == 1:\n                    params, psr = get_tab1_record(file_obj)\n                    params, psi = get_tab1_record(file_obj)\n\n        rml = cls(energy_min, energy_max, particle_pairs, spin_groups)\n        rml.reduced_width = reduced_width\n        rml.formalism = formalism\n\n        return rml\n\n\nclass ParticlePair(object):\n    def __init__(self, first, second, q_value, penetrability,\n                 shift, mt):\n        self.first = first\n        self.second = second\n        self.q_value = q_value\n        self.penetrability = penetrability\n        self.shift = shift\n        self.mt = mt\n\n\nclass SpinGroup(object):\n    \"\"\"Resonance spin group\n\n    Attributes\n    ----------\n    spin : float\n        Total angular momentum (nuclear spin)\n    parity : {'+', '-'}\n        Even (+) or odd(-) parity\n    channels : list of openmc.data.Channel\n        Available channels\n    parameters : pandas.DataFrame\n        Energies/widths for each resonance/channel\n\n    \"\"\"\n\n    def __init__(self, spin, parity, channels, parameters):\n        self.spin = spin\n        self.parity = parity\n        self.channels = channels\n        self.parameters = parameters\n\n    def __repr__(self):\n        return '<SpinGroup: Jpi={}{}>'.format(self.spin, self.parity)\n\n\nclass Unresolved(ResonanceRange):\n    \"\"\"Unresolved resonance parameters as identified by LRU=2 in MF=2.\n\n    Parameters\n    ----------\n    target_spin : float\n        Intrinsic spin, :math:`I`, of the target nuclide\n    energy_min : float\n        Minimum energy of the unresolved resonance range in eV\n    energy_max : float\n        Maximum energy of the unresolved resonance range in eV\n    channel : openmc.data.Function1D\n        Channel radii as a function of energy\n    scattering : openmc.data.Function1D\n        Scattering radii as a function of energy\n\n    Attributes\n    ----------\n    add_to_background : bool\n        If True, file 3 contains partial cross sections to be added to the\n        average unresolved cross sections calculated from parameters.\n    atomic_weight_ratio : float\n        Atomic weight ratio of the target nuclide\n    channel_radius : openmc.data.Function1D\n        Channel radii as a function of energy\n    energies : Iterable of float\n        Energies at which parameters are tabulated\n    energy_max : float\n        Maximum energy of the unresolved resonance range in eV\n    energy_min : float\n        Minimum energy of the unresolved resonance range in eV\n    parameters : list of pandas.DataFrame\n        Average resonance parameters at each energy\n    scattering_radius : openmc.data.Function1D\n        Scattering radii as a function of energy\n    target_spin : float\n        Intrinsic spin, :math:`I`, of the target nuclide\n\n    \"\"\"\n\n    def __init__(self, target_spin, energy_min, energy_max, channel, scattering):\n        super().__init__(target_spin, energy_min, energy_max, channel,\n                         scattering)\n        self.energies = None\n        self.parameters = None\n        self.add_to_background = False\n        self.atomic_weight_ratio = None\n\n    @classmethod\n    def from_endf(cls, file_obj, items, fission_widths):\n        \"\"\"Read unresolved resonance data from an ENDF evaluation.\n\n        Parameters\n        ----------\n        file_obj : file-like object\n            ENDF file positioned at the second record of a resonance range\n            subsection in MF=2, MT=151\n        items : list\n            Items from the CONT record at the start of the resonance range\n            subsection\n        fission_widths : bool\n            Whether fission widths are given\n\n        Returns\n        -------\n        openmc.data.Unresolved\n            Unresolved resonance region parameters\n\n        \"\"\"\n        # Read energy-dependent scattering radius if present\n        energy_min, energy_max = items[0:2]\n        nro, naps = items[4:6]\n        if nro != 0:\n            params, ape = get_tab1_record(file_obj)\n\n        # Get SPI, AP, and LSSF\n        formalism = items[3]\n        if not (fission_widths and formalism == 1):\n            items = get_cont_record(file_obj)\n            target_spin = items[0]\n            if nro == 0:\n                ap = Polynomial((items[1],))\n            add_to_background = (items[2] == 0)\n\n        if not fission_widths and formalism == 1:\n            # Case A -- fission widths not given, all parameters are\n            # energy-independent\n            NLS = items[4]\n            columns = ['L', 'J', 'd', 'amun', 'gn0', 'gg']\n            records = []\n            for ls in range(NLS):\n                items, values = get_list_record(file_obj)\n                awri = items[0]\n                l = items[2]\n                NJS = items[5]\n                for j in range(NJS):\n                    d, j, amun, gn0, gg = values[6*j:6*j + 5]\n                    records.append([l, j, d, amun, gn0, gg])\n            parameters = pd.DataFrame.from_records(records, columns=columns)\n            energies = None\n\n        elif fission_widths and formalism == 1:\n            # Case B -- fission widths given, only fission widths are\n            # energy-dependent\n            items, energies = get_list_record(file_obj)\n            target_spin = items[0]\n            if nro == 0:\n                ap = Polynomial((items[1],))\n            add_to_background = (items[2] == 0)\n            NE, NLS = items[4:6]\n            records = []\n            columns = ['L', 'J', 'E', 'd', 'amun', 'amuf', 'gn0', 'gg', 'gf']\n            for ls in range(NLS):\n                items = get_cont_record(file_obj)\n                awri = items[0]\n                l = items[2]\n                NJS = items[4]\n                for j in range(NJS):\n                    items, values = get_list_record(file_obj)\n                    muf = items[3]\n                    d = values[0]\n                    j = values[1]\n                    amun = values[2]\n                    gn0 = values[3]\n                    gg = values[4]\n                    gfs = values[6:]\n                    for E, gf in zip(energies, gfs):\n                        records.append([l, j, E, d, amun, muf, gn0, gg, gf])\n            parameters = pd.DataFrame.from_records(records, columns=columns)\n\n        elif formalism == 2:\n            # Case C -- all parameters are energy-dependent\n            NLS = items[4]\n            columns = ['L', 'J', 'E', 'd', 'amux', 'amun', 'amuf', 'gx', 'gn0',\n                       'gg', 'gf']\n            records = []\n            for ls in range(NLS):\n                items = get_cont_record(file_obj)\n                awri = items[0]\n                l = items[2]\n                NJS = items[4]\n                for j in range(NJS):\n                    items, values = get_list_record(file_obj)\n                    ne = items[5]\n                    j = items[0]\n                    amux = values[2]\n                    amun = values[3]\n                    amuf = values[5]\n                    energies = []\n                    for k in range(1, ne + 1):\n                        E = values[6*k]\n                        d = values[6*k + 1]\n                        gx = values[6*k + 2]\n                        gn0 = values[6*k + 3]\n                        gg = values[6*k + 4]\n                        gf = values[6*k + 5]\n                        energies.append(E)\n                        records.append([l, j, E, d, amux, amun, amuf, gx, gn0,\n                                        gg, gf])\n            parameters = pd.DataFrame.from_records(records, columns=columns)\n\n        # Calculate channel radius from ENDF-102 equation D.14\n        a = Polynomial((0.123 * (NEUTRON_MASS*awri)**(1./3.) + 0.08,))\n\n        # Determine scattering and channel radius\n        if nro == 0:\n            scattering_radius = ap\n            if naps == 0:\n                channel_radius = a\n            elif naps == 1:\n                channel_radius = ap\n        elif nro == 1:\n            scattering_radius = ape\n            if naps == 0:\n                channel_radius = a\n            elif naps == 1:\n                channel_radius = ape\n            elif naps == 2:\n                channel_radius = ap\n\n        urr = cls(target_spin, energy_min, energy_max, channel_radius,\n                  scattering_radius)\n        urr.parameters = parameters\n        urr.add_to_background = add_to_background\n        urr.atomic_weight_ratio = awri\n        urr.energies = energies\n\n        return urr\n\n\n_FORMALISMS = {0: ResonanceRange,\n               1: SingleLevelBreitWigner,\n               2: MultiLevelBreitWigner,\n               3: ReichMoore,\n               7: RMatrixLimited}\n\n_RESOLVED = (SingleLevelBreitWigner, MultiLevelBreitWigner,\n             ReichMoore, RMatrixLimited)\n", "meta": {"hexsha": "628ad184b588a666f57a187107f5eedc54f5938b", "size": 38375, "ext": "py", "lang": "Python", "max_stars_repo_path": "openmc/data/resonance.py", "max_stars_repo_name": "janmalec/openmc", "max_stars_repo_head_hexsha": "4a4ac4c351d41fe153ca3341820cc507e484ce50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-19T14:46:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-19T14:46:10.000Z", "max_issues_repo_path": "openmc/data/resonance.py", "max_issues_repo_name": "janmalec/openmc", "max_issues_repo_head_hexsha": "4a4ac4c351d41fe153ca3341820cc507e484ce50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-02-24T15:13:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-17T18:59:22.000Z", "max_forks_repo_path": "openmc/data/resonance.py", "max_forks_repo_name": "janmalec/openmc", "max_forks_repo_head_hexsha": "4a4ac4c351d41fe153ca3341820cc507e484ce50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7285067873, "max_line_length": 84, "alphanum_fraction": 0.5718566775, "include": true, "reason": "import numpy,from numpy", "num_tokens": 8669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.196662695910624}}
{"text": "# coding: utf-8\n# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department\n# Distributed under the terms of \"New BSD License\", see the LICENSE file.\n\nimport numpy as np\nfrom pyiron.atomistics.job.interactivewrapper import InteractiveWrapper, ReferenceJobOutput\nfrom pyiron_base import InputList, Settings\n\n__author__ = \"Osamu Waseda\"\n__copyright__ = \"Copyright 2020, Max-Planck-Institut für Eisenforschung GmbH \" \\\n                \"- Computational Materials Design (CM) Department\"\n__version__ = \"1.0\"\n__maintainer__ = \"Osamu Waseda\"\n__email__ = \"waseda@mpie.de\"\n__status__ = \"development\"\n__date__ = \"Sep 1, 2018\"\n\ns = Settings()\n\n\nclass ARTInteractive(object):\n    def __init__(self, art_id, direction, gamma=0.1, fix_layer=False, non_art_id=None):\n        if int(art_id) != art_id or art_id < 0:\n            raise ValueError('art_id must be a posive integer')\n        if len(direction) != 3 or np.isclose(np.linalg.norm(direction), 0):\n            raise ValueError('direction must be a finite 3d vector')\n        if gamma < 0:\n            raise ValueError('gamma must be a positive float')\n        if fix_layer and non_art_id is not None:\n            raise ValueError('fix_layer and non_art_id cannot be set at the same time')\n        self.art_id = art_id\n        self.direction = direction\n        self.gamma = gamma\n        self.non_art_id = non_art_id\n        if non_art_id is not None:\n            self.non_art_id = np.array([non_art_id]).flatten()\n        self.fix_layer = fix_layer\n\n    @property\n    def _R(self):\n        value = np.array(self.direction)\n        value = value / np.linalg.norm(value)\n        return np.outer(value, value)\n\n    def get_forces(self, f_in):\n        f = np.array(f_in)\n        if len(f.shape) == 2:\n            f = np.array([f])\n        if self.non_art_id is None:\n            self.non_art_id = np.arange(len(f[0])) != self.art_id\n        f_art = (1.0+self.gamma)*np.einsum('ij,nj->ni', self._R, f[:, self.art_id])\n        if self.fix_layer:\n            f[:, self.non_art_id] = np.einsum('nmj,ij->nmi', f[:, self.non_art_id], np.identity(3)-self._R)\n        else:\n            f[:, self.non_art_id] += f_art[:, np.newaxis, :] / np.sum(self.non_art_id != False)\n        f[:, self.art_id] -= f_art\n        return f.reshape(np.array(f_in).shape)\n\nclass ART(InteractiveWrapper):\n    \"\"\"\n    Apply an artificial force according to the Activation Relaxation Technique (ART)\n    DOI:https://doi.org/10.1103/PhysRevE.57.2419\n\n    The applied force f_art is calculated from the original force f by:\n\n    f_art = f-(1+gamma)*np.dot(n,f)*n\n\n    where gamma is a parameter to be determined in the input (default: 0.1) and n is\n    the direction along which the force is reversed (3d-vector). In order to homogenize\n    the total force in the system, f_art is distributed among atoms specified by\n    non_art_id (default: all atoms), or if fix_layer is defined, the forces acting on\n    all the other atoms along the direction n are cancelled. Note: Since the energy\n    is not compatible with the forces anymore, structure optimization methods which\n    rely on the energy variation (such as conjugate gradient) cannot/should not be used.\n\n    Input:\n        - art_id (int): atom id on which ART force is applied\n        - direction (list/numpy.ndarray): direction along which force is reversed\n        - gamma (float): prefactor for force inversion. v.s.\n        - non_art_id (list/numpy.ndarray): list of atoms to be used for the force cancellation\n        - fix_layer (bool): whether or not to fix all other atoms on the layer perpendicular\n            to the direction along which force is reversed.\n\n    Example:\n\n        # Structure creation\n        >>> vacancy_position = structure.positions[0]\n        >>> del structure[0]\n        >>> neighbors = structure.get_neighborhood(vacancy_position)\n        >>> direction = neighbors.vecs[0]\n        >>> art_id = neighbors.indices[0]\n        >>> structure.positions[art_id] -= 0.5*direction\n\n        # Job creation\n        >>> some_atomistic_job.structure = structure\n        >>> art = ART(job_name='art')\n        >>> art.ref_job = some_atomistic_job\n        >>> art.input.art_id = art_id\n        >>> art.input.direction = direction\n        >>> some_minimizer.ref_job = art\n        >>> some_minimizer.run()\n\n\n    \"\"\"\n    def __init__(self, project, job_name):\n        super(ART, self).__init__(project, job_name)\n        self.__name__ = \"ART\"\n        self.input = InputList(table_name='custom_dict')\n        self.input.gamma = 0.1\n        self.input.fix_layer = False\n        self.input.non_art_id = None\n        self.input.art_id = None\n        self.input.direction = None\n        self.output = ARTIntOutput(job=self)\n        self.server.run_mode.interactive = True\n        self._interactive_interface = None\n        self._art = None\n\n    def set_input_to_read_only(self):\n        \"\"\"\n        This function enforces read-only mode for the input classes, but it has to be implement in the individual\n        classes.\n        \"\"\"\n        self.input.read_only = True\n\n    @property\n    def art(self):\n        if self._art is None:\n            self._art = ARTInteractive(\n                art_id=self.input.art_id,\n                direction=self.input.direction,\n                gamma=self.input.gamma,\n                fix_layer=self.input.fix_layer,\n                non_art_id=self.input.non_art_id\n            )\n        return self._art\n\n    def run_if_interactive(self):\n        self._logger.debug('art status: ' + str(self.status))\n        if not self.status.running:\n            self.ref_job_initialize()\n        self.status.running = True\n        if self.ref_job.server.run_mode.interactive:\n            self.ref_job.run()\n        else:\n            self.ref_job.run(run_again=True)\n        self._logger.debug('art status: ' + str(self.status))\n\n    def interactive_forces_getter(self):\n        return self.art.get_forces(self.ref_job.output.forces[-1])\n\n    def validate_ready_to_run(self):\n        \"\"\"\n            check whether art_id and direction are set\n        \"\"\"\n        if self.input.art_id is None or self.input.direction is None:\n            raise AssertionError('art_id and/or direction not set')\n\n    def interactive_close(self):\n        self.status.collect = True\n        if self.ref_job.server.run_mode.interactive:\n            self.ref_job.interactive_close()\n        self.status.finished = True\n\n\nclass ARTIntOutput(ReferenceJobOutput):\n    def __init__(self, job):\n        super(ARTIntOutput, self).__init__(job=job)\n\n    @property\n    def forces(self):\n        return self._job.art.get_forces(self._job.ref_job.output.forces)\n", "meta": {"hexsha": "075667a8ade84d7e799386ccbbedf5d295f811dd", "size": 6673, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyiron/interactive/activation_relaxation_technique.py", "max_stars_repo_name": "t-brink/pyiron", "max_stars_repo_head_hexsha": "c07552b54a39e3f036ba395325cd4b372af0f794", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyiron/interactive/activation_relaxation_technique.py", "max_issues_repo_name": "t-brink/pyiron", "max_issues_repo_head_hexsha": "c07552b54a39e3f036ba395325cd4b372af0f794", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-02T09:22:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-02T09:22:56.000Z", "max_forks_repo_path": "pyiron/interactive/activation_relaxation_technique.py", "max_forks_repo_name": "t-brink/pyiron", "max_forks_repo_head_hexsha": "c07552b54a39e3f036ba395325cd4b372af0f794", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-02T08:35:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T08:35:47.000Z", "avg_line_length": 38.5722543353, "max_line_length": 113, "alphanum_fraction": 0.6445376892, "include": true, "reason": "import numpy", "num_tokens": 1583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.19665915751061697}}
{"text": "from __future__ import print_function, absolute_import, division, unicode_literals\n\nimport logging\nfrom collections import namedtuple, deque, OrderedDict\n\nimport casadi as ca\nimport numpy as np\nimport itertools\nfrom typing import Union, Dict, Iterable\n\nfrom pymoca import ast\nfrom pymoca.tree import TreeWalker, TreeListener, flatten\n\nfrom .alias_relation import AliasRelation\nfrom .model import Model, Variable, DelayArgument\nfrom .mtensor import _MTensor, _new_mx\n\nfrom ._options import _merge_default_options\n\nlogger = logging.getLogger(\"pymoca\")\n\n# TODO\n#  - Nested for loops\n#  - Delay operator on arbitrary expressions\n#  - Pre operator\n\nOP_MAP = {'*': \"__mul__\",\n          '+': \"__add__\",\n          \"-\": \"__sub__\",\n          \"/\": \"__div__\",\n          '^': \"__pow__\",\n          '>': '__gt__',\n          '<': '__lt__',\n          '<=': '__le__',\n          '>=': '__ge__',\n          '!=': '__ne__',\n          '==': '__eq__',\n          \"min\": \"fmin\",\n          \"max\": \"fmax\",\n          \"abs\": \"fabs\",\n          \"and\": \"__mul__\",\n          \"or\": \"__add__\"}\n\nForLoopIndexedSymbol = namedtuple('ForLoopIndexedSymbol', ['tree', 'transpose', 'indices'])\n\n\n# noinspection PyPep8Naming,PyUnresolvedReferences\nclass ForLoop:\n    def __init__(self, generator, tree):\n        self.tree = tree\n        self.generator = generator\n        i = tree.indices[0]\n        e = i.expression\n        start = e.start.value\n        step = e.step.value\n        stop = self.generator.get_integer(e.stop)\n        self.values = np.arange(start, stop + step, step, dtype=np.int)\n        self.index_variable = _new_mx(i.name)\n        self.name = i.name\n        self.indexed_symbols = OrderedDict()\n\n    def register_indexed_symbol(self, e, index_function, transpose, tree, index_expr=None):\n        if isinstance(index_expr, ca.MX) and index_expr is not self.index_variable:\n            F = ca.Function('index_expr', [self.index_variable], [index_expr])\n            # expr = lambda ar: np.array([F(a)[0] for a in ar], dtype=np.int)\n            Fmap = F.map(\"map\", self.generator.map_mode, len(self.values), [], [])\n            res = Fmap.call([self.values])\n            indices = np.array(res[0].T, dtype=np.int)\n        else:\n            indices = self.values\n        self.indexed_symbols[e] = ForLoopIndexedSymbol(tree, transpose, index_function(indices - 1))\n\n\nAssignment = namedtuple('Assignment', ['left', 'right'])\n\n\nclass GeneratorWalker(TreeWalker):\n    \"\"\"TreeWalker that skips processing of annotations\"\"\"\n\n    def skip_child(self, tree: ast.Node, child_name: str) -> bool:\n        skip = super().skip_child(tree, child_name)\n        if isinstance(tree, ast.Class) and child_name == \"annotation\":\n            return True\n        return skip\n\n    def order_keys(self, keys: Iterable[str]):\n        # Symbols must come before classes, as we need to access symbol values when creating\n        # CasADi interpolant functions.\n        return sorted(keys, key=lambda attr: 0 if attr == 'symbols' else 1)\n\n\n# noinspection PyPep8Naming,PyUnresolvedReferences\nclass Generator(TreeListener):\n    def __init__(self, root: ast.Tree, class_name: str, options: Dict[str, bool]):\n        super(Generator, self).__init__()\n        self.src = {}\n        self.model = Model()\n        self.root = root\n        c = self.root.classes[class_name]\n        self.nodes = {c: {'time': self.model.time, 'finalTime': self.model.finalTime}}\n        self.derivative = {}\n        self.for_loops = deque()\n        self.functions = {}\n        self.entered_classes = deque()\n        self.map_mode = 'inline' if options['unroll_loops'] else 'serial'\n        self.function_mode = (True, False) if options['inline_functions'] else (False, True)\n        self.delay_counter = 0\n\n        # NOTE: Part of MTensor workaround.\n        self._expand_vectors_enabled = options['expand_vectors']\n\n    @property\n    def current_class(self):\n        return self.entered_classes[-1]\n\n    def _ast_symbols_to_variables(self, ast_symbols, differentiate=False):\n        variables = []\n        for ast_symbol in ast_symbols:\n            mx_symbol = self.get_mx(ast_symbol)\n            modelica_shape = mx_symbol._modelica_shape\n            if mx_symbol.is_empty():\n                continue\n            if differentiate:\n                mx_symbol = self.get_derivative(mx_symbol)\n                mx_symbol._modelica_shape = modelica_shape\n            python_type = self.get_python_type(ast_symbol)\n            variable = Variable(mx_symbol, python_type)\n            if not differentiate:\n                for a in ast.Symbol.ATTRIBUTES:\n                    v = self.get_mx(getattr(ast_symbol, a))\n                    if v is not None:\n                        if isinstance(v, ca.DM) and all(x == (None,) for x in modelica_shape):\n                            # Scalar numeric type that behaves like an array.\n                            # Coerce to Pyhton type to avoid interpretation\n                            # issues.\n                            v = python_type(v)\n                        elif isinstance(v, (float, int)) and not isinstance(v, python_type):\n                            # We skip booleans for now, as users likely depend\n                            # on them being integer/float-like.\n                            try:\n                                v = python_type(v)\n                            except (OverflowError, ValueError):\n                                # Cannot convert NaN/infs to integer\n                                pass\n\n                        setattr(variable, a, v)\n                variable.prefixes = ast_symbol.prefixes\n            variables.append(variable)\n        return variables\n\n    def enterClass(self, tree):\n        logger.debug('enterClass {}'.format(tree.name))\n\n        self.entered_classes.append(tree)\n        self.nodes.setdefault(tree, {})\n\n    def exitClass(self, tree):\n        logger.debug('exitClass {}'.format(tree.name))\n\n        if tree.type == 'function':\n            # Already handled previously\n            self.entered_classes.pop()\n            return\n\n        ode_states = []\n        alg_states = []\n        inputs = []\n        constants = []\n        parameters = []\n        symbols = sorted(tree.symbols.values(), key=lambda x: x.order)\n        for s in symbols:\n            if 'constant' in s.prefixes:\n                constants.append(s)\n            elif 'parameter' in s.prefixes:\n                parameters.append(s)\n            elif 'input' in s.prefixes:\n                inputs.append(s)\n            elif 'state' in s.prefixes:\n                ode_states.append(s)\n            else:\n                alg_states.append(s)\n\n        self.model.states = self._ast_symbols_to_variables(ode_states)\n        self.model.der_states = self._ast_symbols_to_variables(ode_states, differentiate=True)\n        self.model.alg_states = self._ast_symbols_to_variables(alg_states)\n        self.model.constants = self._ast_symbols_to_variables(constants)\n        self.model.parameters = self._ast_symbols_to_variables(parameters)\n\n        # We extend the input list, as it is already populated with delayed states.\n        self.model.inputs.extend(self._ast_symbols_to_variables(inputs))\n\n        # The outputs are a list of strings of state names. Specifying\n        # multiple aliases of the same state is allowed.\n        self.model.outputs = [v.symbol.name() for v in itertools.chain(self.model.states, self.model.alg_states) if 'output' in v.prefixes]\n\n        def discard_empty(l):\n            return list(filter(lambda x: not ca.MX(x).is_empty(), l))\n\n        self.model.equations = discard_empty([self.get_mx(e) for e in tree.equations])\n        self.model.initial_equations = discard_empty([self.get_mx(e) for e in tree.initial_equations])\n\n        # TODO: check if it is valid (like not empty equation)\n        self.model.constraints = [self.get_mx(e) for e in tree.constraints]\n\n        if tree.type == 'optimization':\n            self.model.optimization_attributes = {argument.value.component.name: self.src[argument.value.modifications[0]] for argument in tree.optimization_attributes.arguments}\n\n        if len(tree.statements) + len(tree.initial_statements) > 0:\n            raise NotImplementedError('Statements are currently supported inside functions only')\n\n        self.entered_classes.pop()\n\n    def exitArray(self, tree):\n        self.src[tree] = [self.src[e] for e in tree.values]\n\n    def exitPrimary(self, tree):\n        self.src[tree] = tree.value\n\n    def exitExpression(self, tree):\n        if isinstance(tree.operator, ast.ComponentRef):\n            op = tree.operator.name\n        else:\n            op = tree.operator\n\n        if op == '*':\n            op = 'mtimes'  # .* differs from *\n        if op.startswith('.'):\n            op = op[1:]\n\n        logger.debug('exitExpression')\n\n        n_operands = len(tree.operands)\n        if op == 'der':\n            v = self.get_mx(tree.operands[0])\n            src = self.get_derivative(v)\n        elif op == '-' and n_operands == 1:\n            src = -self.get_mx(tree.operands[0])\n        elif op == 'not' and n_operands == 1:\n            src = ca.if_else(self.get_mx(tree.operands[0]), 0, 1, True)\n        elif op == 'mtimes':\n            assert n_operands >= 2\n            src = self.get_mx(tree.operands[0])\n            for i in tree.operands[1:]:\n                src = ca.mtimes(src, self.get_mx(i))\n        elif op == 'transpose' and n_operands == 1:\n            src = self.get_mx(tree.operands[0]).T\n        elif op == 'sum' and n_operands == 1:\n            v = self.get_mx(tree.operands[0])\n            src = ca.sum1(v)\n        elif op == 'linspace' and n_operands == 3:\n            a = self.get_mx(tree.operands[0])\n            b = self.get_mx(tree.operands[1])\n            n_steps = self.get_integer(tree.operands[2])\n            src = ca.linspace(a, b, n_steps)\n        elif op == 'fill' and n_operands == 2:\n            val = self.get_mx(tree.operands[0])\n            n_row = self.get_integer(tree.operands[1])\n            src = val * ca.DM.ones(n_row)\n        elif op == 'fill' and n_operands == 3:\n            val = self.get_mx(tree.operands[0])\n            n_row = self.get_integer(tree.operands[1])\n            n_col = self.get_integer(tree.operands[2])\n            src = val * ca.DM.ones(n_row, n_col)\n        elif op == 'zeros' and n_operands == 1:\n            n_row = self.get_integer(tree.operands[0])\n            src = ca.DM.zeros(n_row)\n        elif op == 'zeros' and n_operands == 2:\n            n_row = self.get_integer(tree.operands[0])\n            n_col = self.get_integer(tree.operands[1])\n            src = ca.DM.zeros(n_row, n_col)\n        elif op == 'ones' and n_operands == 1:\n            n_row = self.get_integer(tree.operands[0])\n            src = ca.DM.ones(n_row)\n        elif op == 'ones' and n_operands == 2:\n            n_row = self.get_integer(tree.operands[0])\n            n_col = self.get_integer(tree.operands[1])\n            src = ca.DM.ones(n_row, n_col)\n        elif op == 'identity' and n_operands == 1:\n            n = self.get_integer(tree.operands[0])\n            src = ca.DM.eye(n)\n        elif op == 'diagonal' and n_operands == 1:\n            diag = self.get_mx(tree.operands[0])\n            n = len(diag)\n            indices = list(range(n))\n            src = ca.DM.triplet(indices, indices, diag, n, n)\n        elif op == 'cat':\n            axis = self.get_integer(tree.operands[0])\n            assert axis == 1, \"Currently only concatenation on first axis is supported\"\n\n            entries = []\n            for sym in [self.get_mx(op) for op in tree.operands[1:]]:\n                if isinstance(sym, list):\n                    for e in sym:\n                        entries.append(e)\n                else:\n                    entries.append(sym)\n            src = ca.vertcat(*entries)\n        elif op == 'delay' and n_operands == 2:\n            expr = self.get_mx(tree.operands[0])\n            duration = self.get_mx(tree.operands[1])\n\n            src = _new_mx('_pymoca_delay_{}'.format(self.delay_counter), *expr.size())\n            self.delay_counter += 1\n\n            for f in self.for_loops:\n                syms = set(ca.symvar(expr))\n                if syms.intersection(f.indexed_symbols):\n                    f.register_indexed_symbol(src, lambda i: i, True, tree.operands[0], f.index_variable)\n\n            self.model.delay_states.append(src.name())\n            self.model.inputs.append(Variable(src))\n\n            delay_argument = DelayArgument(expr, duration)\n            self.model.delay_arguments.append(delay_argument)\n        elif op == '_pymoca_interp1d' and n_operands >= 3 and n_operands <= 4:\n            entered_class = self.entered_classes[-1]\n            if isinstance(tree.operands[0], ast.ComponentRef):\n                xp = self.get_mx(entered_class.symbols[tree.operands[0].name].value)\n            else:\n                xp = self.get_mx(tree.operands[0])\n            if isinstance(tree.operands[1], ast.ComponentRef):\n                yp = self.get_mx(entered_class.symbols[tree.operands[1].name].value)\n            else:\n                yp = self.get_mx(tree.operands[1])\n            arg = self.get_mx(tree.operands[2])\n            if n_operands == 4:\n                assert isinstance(tree.operands[3], ast.Primary)\n                mode = tree.operands[3].value\n            else:\n                mode = 'linear'\n            func = ca.interpolant('interpolant', mode, [xp], yp)\n            src = func(arg)\n        elif op == '_pymoca_interp2d' and n_operands >= 5 and n_operands <= 6:\n            entered_class = self.entered_classes[-1]\n            if isinstance(tree.operands[0], ast.ComponentRef):\n                xp = self.get_mx(entered_class.symbols[tree.operands[0].name].value)\n            else:\n                xp = self.get_mx(tree.operands[0])\n            if isinstance(tree.operands[1], ast.ComponentRef):\n                yp = self.get_mx(entered_class.symbols[tree.operands[1].name].value)\n            else:\n                yp = self.get_mx(tree.operands[1])\n            if isinstance(tree.operands[2], ast.ComponentRef):\n                zp = self.get_mx(entered_class.symbols[tree.operands[2].name].value)\n            else:\n                zp = self.get_mx(tree.operands[2])\n            arg_1 = self.get_mx(tree.operands[3])\n            arg_2 = self.get_mx(tree.operands[4])\n            if n_operands == 6:\n                assert isinstance(tree.operands[5], ast.Primary)\n                mode = tree.operands[5].value\n            else:\n                mode = 'linear'\n            func = ca.interpolant('interpolant', mode, [xp, yp], np.array(zp).ravel(order='F'))\n            src = func(ca.vertcat(arg_1, arg_2))\n        elif op in OP_MAP and n_operands == 2:\n            lhs = ca.MX(self.get_mx(tree.operands[0]))\n            rhs = ca.MX(self.get_mx(tree.operands[1]))\n            lhs_op = getattr(lhs, OP_MAP[op])\n            src = lhs_op(rhs)\n        elif op in OP_MAP and n_operands == 1:\n            lhs = ca.MX(self.get_mx(tree.operands[0]))\n            lhs_op = getattr(lhs, OP_MAP[op])\n            src = lhs_op()\n        else:\n            src = ca.MX(self.get_mx(tree.operands[0]))\n            # Check for built-in operations, such as the\n            # elementary functions, first.\n            if hasattr(src, op) and n_operands <= 2:\n                if n_operands == 1:\n                    src = ca.MX(self.get_mx(tree.operands[0]))\n                    src = getattr(src, op)()\n                else:\n                    lhs = ca.MX(self.get_mx(tree.operands[0]))\n                    rhs = ca.MX(self.get_mx(tree.operands[1]))\n                    lhs_op = getattr(lhs, op)\n                    src = lhs_op(rhs)\n            else:\n                try: # Check if there is a component named as the operation. In that case we are dealing with a time access\n                    # Should we check for symbol as well?\n                    v = self.get_mx(ast.ComponentRef(name=op))\n                    t = self.get_mx(tree.operands[0])\n                    src = self.get_symbol_time_access(v, t)\n\n                except KeyError:\n                    func = self.get_function(op)\n                    src = ca.vertcat(*func.call([self.get_mx(operand) for operand in tree.operands], *self.function_mode))\n\n        self.src[tree] = src\n\n    def exitIfExpression(self, tree):\n        logger.debug('exitIfExpression')\n\n        assert (len(tree.conditions) + 1 == len(tree.expressions))\n\n        src = self.get_mx(tree.expressions[-1])\n        for cond_index in range(len(tree.conditions)):\n            cond = self.get_mx(tree.conditions[-(cond_index + 1)])\n            expr1 = self.get_mx(tree.expressions[-(cond_index + 2)])\n\n            src = ca.if_else(cond, expr1, src, True)\n\n        self.src[tree] = src\n        \n    def exitConstraint(self, tree):\n        logger.debug('exitConstraint')\n\n        src_left = self.get_mx(tree.left)\n        src_right = self.get_mx(tree.right)\n\n        # Always return bigger equal constraints\n        if tree.operand == '>=':\n            self.src[tree] = src_left - src_right\n        elif tree.operand == '<=':\n            self.src[tree] = src_right - src_left\n        else:\n            raise Exception('Operand {} is not supported in constraints'.format(tree.operand))\n\n\n    def exitEquation(self, tree):\n        logger.debug('exitEquation')\n\n        if isinstance(tree.left, list):\n            src_left = ca.vertcat(*[self.get_mx(c) for c in tree.left])\n        else:\n            src_left = self.get_mx(tree.left)\n\n        if isinstance(tree.right, list):\n            src_right = ca.vertcat(*[self.get_mx(c) for c in tree.right])\n        else:\n            src_right = self.get_mx(tree.right)\n\n        src_left = ca.MX(src_left)\n        src_right = ca.MX(src_right)\n\n        # According to the Modelica spec,\n        # \"It is possible to omit left hand side component references and/or truncate the left hand side list in order to discard outputs from a function call.\"\n        if isinstance(tree.right, ast.Expression) and tree.right.operator in self.root.classes:\n            if src_left.size1() < src_right.size1():\n                src_right = src_right[0:src_left.size1()]\n        if isinstance(tree.left, ast.Expression) and tree.left.operator in self.root.classes:\n            if src_left.size1() > src_right.size1():\n                src_left = src_left[0:src_right.size1()]\n\n        # If dimensions between the lhs and rhs do not match, but the dimensions of lhs\n        # and transposed rhs do match, transpose the rhs.\n        if src_left.shape != src_right.shape and src_left.shape == src_right.shape[::-1]:\n            src_right = ca.transpose(src_right)\n\n        self.src[tree] = src_left - src_right\n\n    def enterForEquation(self, tree):\n        logger.debug('enterForEquation')\n\n        self.for_loops.append(ForLoop(self, tree))\n\n    def exitForEquation(self, tree):\n        logger.debug('exitForEquation')\n\n        f = self.for_loops.pop()\n        if len(f.values) > 0:\n            indexed_symbols = list(f.indexed_symbols.keys())\n            args = [f.index_variable] + indexed_symbols\n            expr = ca.vcat([ca.vec(self.get_mx(e)) for e in tree.equations])\n            free_vars = ca.symvar(expr)\n\n            arg_names = [arg.name() for arg in args]\n            free_vars = [e for e in free_vars if e.name() not in arg_names]\n            all_args = args + free_vars\n            F = ca.Function('loop_body', all_args, [expr])\n\n            indexed_symbols_full = []\n            for k in indexed_symbols:\n                s = f.indexed_symbols[k]\n                indices = s.indices\n                try:\n                    i = self.model.delay_states.index(k.name())\n                except ValueError:\n                    orig_symbol = self.nodes[self.current_class][s.tree.name]\n                else:\n                    # We are missing a similarly shaped delayed symbol. Make a new one with the appropriate shape.\n                    delay_symbol = self.model.delay_arguments[i]\n\n                    # We need to figure out the shape of the expression that\n                    # we are delaying. The symbols that can occur in the delay\n                    # expression should have been encountered before this\n                    # iteration of the loop. The assert statement below covers\n                    # this.\n                    delay_expr_args = free_vars + all_args[:len(indexed_symbols_full)+1]\n                    assert set(ca.symvar(delay_symbol.expr)).issubset(delay_expr_args)\n\n                    f_delay_expr = ca.Function('delay_expr', delay_expr_args, [delay_symbol.expr])\n                    f_delay_map = f_delay_expr.map(\"map\", self.map_mode, len(f.values), list(\n                        range(len(free_vars))), [])\n                    [res] = f_delay_map.call(free_vars + [f.values] + indexed_symbols_full)\n                    res = res.T\n\n                    # Make the symbol with the appropriate size, and replace the old symbol with the new one.\n                    orig_symbol = _new_mx(k.name(), *res.size())\n                    assert res.size1() == 1 or res.size2() == 1, \"Slicing does not yet work with 2-D indices\"\n                    indices = slice(None, None)\n\n                    model_input = next(x for x in self.model.inputs if x.symbol.name() == k.name())\n                    model_input.symbol = orig_symbol\n                    self.model.delay_arguments[i] = DelayArgument(res, delay_symbol.duration)\n\n                indexed_symbol = orig_symbol[indices]\n                if s.transpose:\n                    indexed_symbol = ca.transpose(indexed_symbol)\n                indexed_symbols_full.append(indexed_symbol)\n\n            Fmap = F.map(\"map\", self.map_mode, len(f.values), list(\n                range(len(args), len(all_args))), [])\n            res = Fmap.call([f.values] + indexed_symbols_full + free_vars)\n\n            self.src[tree] = res[0].T\n        else:\n            self.src[tree] = ca.MX()\n\n    def exitIfEquation(self, tree):\n        logger.debug('exitIfEquation')\n\n        # Check if every equation block contains the same number of equations\n        if len(set((len(x) for x in tree.blocks))) != 1:\n            raise Exception(\"Every branch in an if-equation needs the same number of equations.\")\n\n        # NOTE: We currently assume that we always have an else-clause. This\n        # is not strictly necessary, see the Modelica Spec on if equations.\n        assert tree.conditions[-1] == True\n\n        src = ca.vertcat(*[self.get_mx(e) for e in tree.blocks[-1]])\n\n        for cond_index in range(1, len(tree.conditions)):\n            cond = self.get_mx(tree.conditions[-(cond_index + 1)])\n            expr1 = ca.vertcat(*[self.get_mx(e) for e in tree.blocks[-(cond_index + 1)]])\n            src = ca.if_else(cond, expr1, src, True)\n\n        self.src[tree] = src\n\n    def exitAssignmentStatement(self, tree):\n        logger.debug('exitAssignmentStatement')\n\n        all_assignments = []\n\n        expr = self.get_mx(tree.right)\n        for component_ref in tree.left:\n            all_assignments.append(Assignment(self.get_mx(component_ref), expr))\n\n        self.src[tree] = all_assignments\n\n    def exitIfStatement(self, tree):\n        logger.debug('exitIfStatement')\n\n        # We assume an equal number of statements per branch.\n        # Furthermore, we assume that every branch assigns to the same variables.\n        assert len(set((len(x) for x in tree.blocks))) == 1\n\n        # NOTE: We currently assume that we always have an else-clause. This\n        # is not strictly necessary, see the Modelica Spec on if statements.\n        assert tree.conditions[-1] == True\n\n        expanded_blocks = OrderedDict()\n\n        for b in tree.blocks:\n            block_assignments = []\n            for s in b:\n                assignments = self.get_mx(s)\n                for assignment in assignments:\n                    expanded_blocks.setdefault(assignment.left, []).append(assignment.right)\n\n        assert len(set((len(x) for x in expanded_blocks.values()))) == 1\n\n        all_assignments = []\n\n        for lhs, values in expanded_blocks.items():\n            # Set default value to else block, and then loop in reverse over all branches\n            src = values[-1]\n            for cond, rhs in zip(tree.conditions[-2::-1], values[-2::-1]):\n                cond = self.get_mx(cond)\n                src = ca.if_else(cond, rhs, src, True)\n\n            all_assignments.append(Assignment(lhs, src))\n\n        self.src[tree] = all_assignments\n\n    def enterForStatement(self, tree):\n        logger.debug('enterForStatement')\n\n        self.for_loops.append(ForLoop(self, tree))\n\n    def exitForStatement(self, tree):\n        logger.debug('exitForStatement')\n\n        f = self.for_loops.pop()\n        if len(f.values) > 0:\n            indexed_symbols = list(f.indexed_symbols.keys())\n            args = [f.index_variable] + indexed_symbols\n            expr = ca.vcat([ca.vec(self.get_mx(e.right)) for e in tree.statements])\n            free_vars = ca.symvar(expr)\n\n            arg_names = [arg.name() for arg in args]\n            free_vars = [e for e in free_vars if e.name() not in arg_names]\n            all_args = args + free_vars\n            F = ca.Function('loop_body', all_args, [expr])\n\n            indexed_symbols_full = []\n            for k in indexed_symbols:\n                s = f.indexed_symbols[k]\n                orig_symbol = self.nodes[self.current_class][s.tree.name]\n                indexed_symbol = orig_symbol[s.indices]\n                if s.transpose:\n                    indexed_symbol = ca.transpose(indexed_symbol)\n                indexed_symbols_full.append(indexed_symbol)\n\n            Fmap = F.map(\"map\", self.map_mode, len(f.values), list(\n                range(len(args), len(all_args))), [])\n            res = Fmap.call([f.values] + indexed_symbols_full + free_vars)\n\n            # Split into a list of statements\n            variables = [assignment.left for statement in tree.statements for assignment in self.get_mx(statement)]\n            all_assignments = []\n            for i in range(len(f.values)):\n                for j, variable in enumerate(variables):\n                    all_assignments.append(Assignment(variable, res[0][j, i].T))\n\n            self.src[tree] = all_assignments\n        else:\n            self.src[tree] = []\n\n    def get_integer(self, tree: Union[ast.Primary, ast.ComponentRef, ast.Expression, ast.Slice]) -> Union[int, ca.MX, np.ndarray]:\n        # CasADi needs to know the dimensions of symbols at instantiation.\n        # We therefore need a mechanism to evaluate expressions that define dimensions of symbols.\n        if isinstance(tree, ast.Primary):\n            return None if tree.value is None else int(tree.value)\n        if isinstance(tree, ast.ComponentRef):\n            s = self.current_class.symbols[tree.name]\n            assert (s.type.name == 'Integer')\n            return self.get_integer(s.value)\n        if isinstance(tree, ast.Expression):\n            # Make sure that the expression has been converted to MX by (re)visiting the\n            # relevant part of the AST.\n            ast_walker = TreeWalker()\n            ast_walker.walk(self, tree)\n\n            # Obtain expression\n            expr = self.get_mx(tree)\n\n            # Obtain the symbols it depends on\n            free_vars = ca.symvar(expr)\n\n            # Find the values of the symbols\n            vals = []\n            for free_var in free_vars:\n                if free_var.is_symbolic():\n                    if (len(self.for_loops) > 0) and (free_var.name() == self.for_loops[-1].name):\n                        vals.append(self.for_loops[-1].index_variable)\n                    else:\n                        vals.append(self.get_integer(self.current_class.symbols[free_var.name()].value))\n\n            # Evaluate the expression\n            F = ca.Function('get_integer', free_vars, [expr])\n            ret = F.call(vals, *self.function_mode)\n            if ret[0].is_constant():\n                # We managed to evaluate the expression.  Assume the result to be integer.\n                return int(ret[0])\n            else:\n                # Expression depends on other symbols.  Could not extract integer value.\n                return ret[0]\n        if isinstance(tree, ast.Slice):\n            start = self.get_integer(tree.start)\n            step = self.get_integer(tree.step)\n            stop = self.get_integer(tree.stop)\n            return slice(start, stop, step)\n        else:\n            raise Exception('Unexpected node type {}'.format(tree.__class__.__name__))\n\n    @staticmethod\n    def get_python_type(tree):\n        if tree.type.name == 'Boolean':\n            return bool\n        elif tree.type.name == 'Integer':\n            return int\n        else:\n            return float\n\n    def get_shape(self, tree):\n        return [[self.get_integer(d) for d in d_list] for d_list in tree.dimensions]\n\n    def get_symbol(self, tree):\n        # Create symbol\n        shape = self.get_shape(tree)\n\n        if any(isinstance(x, slice) for var_shape in shape for x in var_shape):\n            # Symbol has unspecified dimensions. Value is specified, and\n            # carries the correct dimensions.\n\n            # We should only get slices as dimensions for a symbol if one of\n            # the dimensions is unspecified, i.e. None.\n            assert None in (itertools.chain.from_iterable((x.start, x.stop)\n                            for var_shape in shape for x in var_shape if isinstance(x, slice)))\n\n            val_shape = np.array(self.src[tree.value]).shape\n\n            # Check if specified dimensions agree between definition and value\n            val_dim_i = -1\n            for var_i, var_shape in enumerate(shape):\n                for dim_i, dim_size in enumerate(var_shape):\n                    if dim_size is None:\n                        continue\n\n                    val_dim_i += 1\n                    if isinstance(dim_size, slice):\n                        shape[var_i][dim_i] = val_shape[val_dim_i]\n                        continue\n\n                    if val_shape[val_dim_i] != dim_size:\n                        raise Exception(\"Dimension {} of definition and value for symbol {} \"\n                                        \"differs: {} != {}\"\n                                        .format(val_dim_i + 1, tree.name, dim_size,\n                                                val_shape[val_dim_i]))\n\n        tensor_shape = [d for var_shape in shape for d in var_shape if d is not None]\n        if len(tensor_shape) > 2:\n            # MX does not support this, so we have to use our own wrapper.\n            if not self._expand_vectors_enabled:\n                raise NotImplementedError(\"Cannot handle 3D+ arrays without setting 'expand_vectors'\")\n            s = _MTensor(tree.name, *tensor_shape)\n        else:\n            s = _new_mx(tree.name, *tensor_shape)\n\n        # Make a notion of the original shape, as MX is always 2D (even for 1D symbols),\n        # and for nested classes we want to remember at which symbols to place indices.\n        s._modelica_shape = tuple([tuple(var_shape) for var_shape in shape])\n\n        self.nodes[self.current_class][tree.name] = s\n        return s\n\n    def get_derivative(self, s):\n\n        # Case 1: s is a constant, e.g. MX(5)\n        if ca.MX(s).is_constant():\n            return 0\n\n        # Case 2: s is a symbol, e.g. MX(x)\n        elif s.is_symbolic():\n            if s.name() not in self.derivative:\n                if len(self.for_loops) > 0 and s in self.for_loops[-1].indexed_symbols:\n                    # Create a new indexed symbol, referencing to the for loop index inside the vector derivative symbol.\n                    for_loop_symbol = self.for_loops[-1].indexed_symbols[s]\n                    s_without_index = self.get_mx(ast.ComponentRef(name=for_loop_symbol.tree.name))\n                    der_s_without_index = self.get_derivative(s_without_index)\n                    if ca.MX(der_s_without_index).is_symbolic():\n                        return self.get_indexed_symbol(ast.ComponentRef(name=der_s_without_index.name(), indices=for_loop_symbol.tree.indices), der_s_without_index)\n                    else:\n                        return 0\n                else:\n                    der_s = _new_mx(\"der({})\".format(s.name()), s.size())\n                    # If the derivative contains an expression (e.g. der(x + y)) this method is\n                    # called with MX variables that are the result of a ca.symvar call. This\n                    # ca.symvar call strips the _modelica_shape field from the MX variable,\n                    # therefore we need to find the original MX to get the modelica shape.\n                    der_s._modelica_shape = \\\n                        self.nodes[self.current_class][s.name()]._modelica_shape\n                    self.derivative[s.name()] = der_s\n                    self.nodes[self.current_class][der_s.name()] = der_s\n                    return der_s\n            else:\n                return self.derivative[s.name()]\n\n        # Case 3: s is an already indexed symbol, e.g. MX(x[1])\n        elif s.is_op(ca.OP_GETNONZEROS) and s.dep().is_symbolic():\n            slice_info = s.info()['slice']\n            dep = s.dep()\n            if dep.name() not in self.derivative:\n                der_dep = _new_mx(\"der({})\".format(dep.name()), dep.size())\n                der_dep._modelica_shape = \\\n                    self.nodes[self.current_class][dep.name()]._modelica_shape\n                self.derivative[dep.name()] = der_dep\n                self.nodes[self.current_class][der_dep.name()] = der_dep\n                return der_dep[slice_info['start']:slice_info['stop']:slice_info['step']]\n            else:\n                return self.derivative[dep.name()][slice_info['start']:slice_info['stop']:slice_info['step']]\n\n        # Case 4: s is an expression that requires differentiation, e.g. MX(x2 * x2)\n        # Need to do this sort of expansion: der(x1 * x2) = der(x1) * x2 + x1 * der(x2)\n        else:\n            # Differentiate expression using CasADi\n            orig_deps = ca.symvar(s)\n            deps = ca.vertcat(*orig_deps)\n            J = ca.Function('J', [deps], [ca.jacobian(s, deps)])\n            J_sparsity = J.sparsity_out(0)\n            der_deps = [self.get_derivative(dep) if J_sparsity.has_nz(0, j) else ca.DM.zeros(dep.size()) for j, dep in enumerate(orig_deps)]\n            return ca.mtimes(J(deps), ca.vertcat(*der_deps))\n\n    def get_indexed_symbol(self, tree, s):\n        assert len([dim for shape in s._modelica_shape for dim in shape if dim is not None]) <= 2,\\\n            \"Dimensions higher than two are not yet supported\"\n\n        assert len(s._modelica_shape) >= len(tree.indices)\n\n        # For nested variables where an equation is defined at one of the nested models,\n        # the modelica shape will contain the shape for the whole nested variable, but the indices\n        # will only contain the indices for the symbol in the nested model. We only use the last\n        # part of _modelica_shape in this case.\n        assert tree.indices\n        shapes = s._modelica_shape[-len(tree.indices):]\n\n        # Check whether we loop over an index of this symbol\n        indices = []\n        for_loop = None\n        for i, (index_array, shape) in enumerate(zip(tree.indices, shapes)):\n            if len(index_array) > len(shape):\n                symbol_name = s.name() if len(tree.indices) == 1 \\\n                    else s.name().split('.')[i] + ' in nested symbol ' + s.name()\n                raise ValueError('Too many indices found for symbol {}, check if the symbol has '\n                                 'the correct dimensions.'.format(symbol_name))\n\n            for index, dim in zip(index_array, shape):\n                if index is None and dim is None:\n                    continue\n\n                sl = None\n\n                if isinstance(index, ast.ComponentRef):\n                    for f in self.for_loops:\n                        if index.name == f.name:\n                            # TODO support nested loops\n                            for_loop = f\n                            sl = for_loop.index_variable\n\n                if sl is None:\n                    sl = self.get_integer(index) if index is not None else None\n\n                    if sl is None and dim is not None:\n                        sl = slice(None, None, 1)\n                    if sl is not None and dim is None:\n                        symbol_name = s.name() if len(tree.indices) == 1 \\\n                            else s.name().split('.')[i] + ' in nested symbol ' + s.name()\n                        raise ValueError('Symbol {} was given an index of {} but this symbol '\n                                         'is not an array.'.format(symbol_name, sl))\n                    elif isinstance(sl, int):\n                        # Modelica indexing starts from one;  Python from zero.\n                        if sl <= 0 or sl > dim:\n                            symbol_name = s.name() if len(tree.indices) == 1 \\\n                                else s.name().split('.')[i] + ' in nested symbol ' + s.name()\n                            raise ValueError(\"Index {} of symbol {} is out of bounds. \"\n                                             \"Index should be in range [1,{}] \"\n                                             \"(Modelica uses 1-based indexing).\"\n                                             .format(sl, symbol_name, dim))\n                        sl = sl - 1\n                    elif isinstance(sl, slice):\n                        # Modelica indexing starts from one;  Python from zero.\n                        sl = slice(None if sl.start is None else sl.start - 1, sl.stop, sl.step)\n                    else:\n                        for_loop = self.for_loops[-1]\n\n                indices.append(sl)\n\n        if for_loop is not None:\n            if isinstance(indices[0], ca.MX):\n                if len(indices) > 1:\n                    s = s[:, indices[1]]\n                    indexed_symbol = _new_mx('{}[{},{}]'.format(tree.name, for_loop.name, indices[1]), s.size2())\n                    index_function = lambda i : (i, indices[1])\n                else:\n                    indexed_symbol = _new_mx('{}[{}]'.format(tree.name, for_loop.name))\n                    index_function = lambda i : i\n\n                # If the indexed symbol is empty, we know we do not have to\n                # map the for loop over it\n                if np.prod(s.shape) != 0:\n                    for_loop.register_indexed_symbol(indexed_symbol, index_function, True, tree, indices[0])\n            else:\n                s = ca.transpose(s[indices[0], :])\n                indexed_symbol = _new_mx('{}[{},{}]'.format(tree.name, indices[0], for_loop.name), s.size2())\n                index_function = lambda i: (indices[0], i)\n                if np.prod(s.shape) != 0:\n                    for_loop.register_indexed_symbol(indexed_symbol, index_function, False, tree, indices[1])\n            return indexed_symbol\n        else:\n            if len(indices) == 1:\n                return s[indices[0]]\n            else:\n                return s[indices[0], indices[1]]\n\n    def get_symbol_time_access(self, v, t):\n        return _new_mx('{}({})'.format(v.name(), str(t)), v.size())\n\n\n    def get_component(self, tree):\n        # Check special symbols\n        if tree.name == 'time':\n            return self.model.time\n        elif tree.name == 'finalTime':\n            return self.model.finalTime\n        else:\n            for f in reversed(self.for_loops):\n                if f.name == tree.name:\n                    return f.index_variable\n\n        # Check ordinary symbols\n        symbol = self.current_class.symbols[tree.name]\n        s = self.get_mx(symbol)\n        if len([index for index_array in tree.indices\n                for index in index_array if index is not None]) > 0:\n            s = self.get_indexed_symbol(tree, s)\n        return s\n\n    def get_mx(self, tree: Union[ast.Symbol, ast.ComponentRef, ast.Expression]) -> ca.MX:\n        \"\"\"\n        We pull components and symbols from the AST on demand.\n        This is to ensure that parametrized vector dimensions can be resolved.  Vector\n        dimensions need to be known at CasADi MX creation time.\n        :param tree:\n        :return:\n        \"\"\"\n        if tree not in self.src:\n            if isinstance(tree, ast.Symbol):\n                s = self.get_symbol(tree)\n            elif isinstance(tree, ast.ComponentRef):\n                s = self.get_component(tree)\n            else:\n                raise Exception('Tried to look up expression before it was reached by the tree walker')\n            self.src[tree] = s\n        return self.src[tree]\n\n    def get_function(self, function_name):\n        if function_name in self.functions:\n            return self.functions[function_name]\n\n        try:\n            tree = self.root.classes[function_name]\n        except KeyError:\n            raise Exception('Unknown function {}'.format(function_name))\n\n        inputs = []\n        outputs = []\n        tmp = []\n        for s in tree.symbols.values():\n            src = self.get_mx(s)\n            if 'input' in s.prefixes:\n                inputs.append(src)\n            elif 'output' in s.prefixes:\n                outputs.append(src)\n            else:\n                tmp.append(src)\n\n        # Store current variable values\n        values = {}\n        for variable in inputs:\n            values[variable] = variable\n\n        # Process statements in order\n        for statement in tree.statements:\n            src = self.get_mx(statement)\n            for assignment in src:\n                [values[assignment.left]] = ca.substitute([assignment.right], list(values.keys()), list(values.values()))\n\n        output_expr = ca.substitute([values[output] for output in outputs], tmp, [values[t] for t in tmp])\n        func = ca.Function(tree.name, inputs, output_expr)\n        self.functions[function_name] = func\n\n        return func\n\n\ndef generate(ast_tree: ast.Tree, model_name: str, options: Dict[str, bool]=None) -> Model:\n    \"\"\"\n    :param ast_tree: AST to generate from\n    :param model_name: class to generate\n    :param options: dictionary of generator options\n    :return: casadi model\n    \"\"\"\n    options = _merge_default_options(options)\n\n\n    component_ref = ast.ComponentRef.from_string(model_name)\n    ast_walker = GeneratorWalker()\n    flat_tree = flatten(ast_tree, component_ref)\n    component_ref_tuple = component_ref.to_tuple()\n    casadi_gen = Generator(flat_tree, component_ref_tuple[-1], options)\n    ast_walker.walk(casadi_gen, flat_tree)\n    return casadi_gen.model\n", "meta": {"hexsha": "670d0e007809a4701dcedec008bc22b07f739890", "size": 42683, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/pymoca/backends/casadi/generator.py", "max_stars_repo_name": "PeterRabbit95/pymoca", "max_stars_repo_head_hexsha": "e10d7b14538062a144026be2c6fa3e0d1a8cfad3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pymoca/backends/casadi/generator.py", "max_issues_repo_name": "PeterRabbit95/pymoca", "max_issues_repo_head_hexsha": "e10d7b14538062a144026be2c6fa3e0d1a8cfad3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pymoca/backends/casadi/generator.py", "max_forks_repo_name": "PeterRabbit95/pymoca", "max_forks_repo_head_hexsha": "e10d7b14538062a144026be2c6fa3e0d1a8cfad3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4211597152, "max_line_length": 178, "alphanum_fraction": 0.5674624558, "include": true, "reason": "import numpy", "num_tokens": 9301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.19665915246851606}}
{"text": "\"\"\"\nA Python interface to CPTEC's Plume Rise Model.\n\nTO DO: Create a base class name PLUMES and share code with the LockPlume.\n\n\"\"\"\n\nfrom numpy      import zeros, ones, meshgrid, linspace, any, \\\n                       pi, sin, cos, arccos, arange, array, \\\n                       savez, NaN, isnan\n\nfrom scipy import optimize as opt\n\nfrom datetime   import datetime, date, timedelta\nfrom glob       import glob\n\nfrom dozier     import DOZIER, granules\nfrom PlumeRise_ import *       # f2py extension\nfrom gfio       import GFIO\n\nfrom pyobs           import NPZ, kde\nfrom pyobs.binObs_   import binareas\nfrom pyobs.minx      import MINXs\nfrom MAPL.constants  import *\n\nimport eta\n\n__VERSION__ = 2.1\n__CVSTAG__  = '@CVSTAG'\n__AMISS__   = 1.E+20\n\nBioma = [ 'Tropical Forest',\n          'Extra-Tropical Forest',\n          'Savanna',\n          'Grassland' ]\n\nDAY = timedelta(seconds=60*60*24)\n\n#----------------------------------------------------------------------------------------------\n\n#----\nclass MINXs_PR(MINXs):\n\n    \"\"\"\n    Extension of the MINXs class adding the Freitas Plume Rise\n    functionality. This class handles non-gridded, observation\n    location fires.\n\n    Parabolic Vertical Mass Distribution (VMD)\n    ------------------------------------------\n    If using the parabolic VMD as in getVMD() below, the (z_c,delta) parameters can\n    be computed from the (z_i,z_f,z_d) parameters returned by plumevmd().\n\n     a) Like Saulo:\n                     z_c   = (z_f+z_i)/2\n                     delta = (z_f-z_i)/2\n\n     b) Preserve bottom half:\n                     z_c   = z_d\n                     delta = z_d - z_i\n\n     c) Preserve upper half:\n                     z_c   = z_d\n                     delta = z_f - z_d\n\n                       ---\n\n    \"\"\"\n    \n    def getPlume1(self,i,\n                  hflux_kW=None,\n                  frp_MW=None,\n                  area_m2=None,afac=None,\n                  Area=None,\n                  rad2conv=5.,\n                  Nominal=False,\n                  which='z_a',\n                  Verbose=False):\n \n        \"\"\"\n        Runs the Plume Rise extension to compute the extent of the plume.\n        On input,\n        \n           i         ---  index to operate on\n           frp_MW    ---  fire radiative power in MW\n           area_m2   ---  firea are im m2\n           afac      ---  scale area by this amount\n           Area      ---  if specified, PR model will see this value, but heat flux\n                          will be computed the regular way, based on *area*\n           rad2conv  ---  factor for converting radiative to convective heat fluxes.\n           which     ---  Return one of z_i, z_f, z_d, z_a or all (Tupple), where\n                          z_i -- height of maximum W (bottom of plume)\n                          z_d -- height of maximum detrainment\n                          z_a -- average height in (z_i,z_f), weighted by -dw/dz\n                          z_f -- height where w<1 (top of plume)\n           Nominal   ---  by default, areas and heat fluxes are from a\n                          Dozier type algorithm, If Nominal=True,\n                             area = 20e4 (20 ha)\n                             hflux = rad2conv * FRP / area\n           \n\t\"\"\"\n\n        area = area_m2\n        ptop = 1. # Pascal\n\n        # Default areas, heat flux\n        # ------------------------\n        if Nominal:\n            d_area = 20e4  #  typical fire size in m2 (20 ha)\n        else: \n            d_area = 1e6 * self.mod14.farea[i]      # km2 --> m2\n\n        # Area\n        # ----\n        if area == None:\n            area = d_area # m2\n\n        # FRP\n        # ---\n        if frp_MW == None:\n            frp_MW = self.mod14.frp[i] # MW\n\n        # Convective Heat Flux\n        # --------------------\n        if hflux_kW == None:\n            hflux_kW = 1e3 * rad2conv * frp_MW / area # kW/m2\n\n        # Scaled Area\n        # -----------\n        if afac!=None:\n            if afac==0:\n                afac = 1e-8\n            area = afac * area\n            hflux_kW = hflux_kW / afac\n        \n        u = self.sample.u[i]\n        v = self.sample.v[i]\n        T = self.sample.t[i]\n        q = self.sample.qv[i]\n        delp = self.sample.delp[i]\n\n        if delp.min()<=0 or T.min()<=0:\n            print \"out of range: \", delp.min(), T.min() \n            return NaN\n\n        # Ensure arrays are top-down as in GEOS-5\n        # ---------------------------------------\n        if delp[0] > delp[-1]:\n            u = u[::-1]\n            v = v[::-1]\n            T = T[::-1]\n            q = q[::-1]\n            delp = delp[::-1]\n\n        # Override firea area\n        # -------------------\n        if Area is not None:\n            area = Area\n                \n        # Run plume rise model\n        # --------------------\n        # p,z,k,rc = plume(u,v,T,q,delp,ptop,hflux_kW,area)\n        z_i,z_d,z_a,z_f,z,w,rc = plumevmd(u,v,T,q,delp,ptop,hflux_kW,area)\n        if rc:\n            raise ValueError, \"error on return from <plume>, rc = %d\"%rc\n\n        if z_i==-1.: \n             z_i,z_d,z_a,z_f = (NaN,self.sample.pblh[i],NaN,NaN)\n             \n        if   which=='z_i': z = z_i\n        elif which=='z_f': z = z_f\n        elif which=='z_d': z = z_d\n        elif which=='z_a': z = z_a\n        else:              z = (z_i,z_d,z_a,z_f,z,w)\n        \n        if Verbose:\n            print \" \", self.tyme[i], \"| %8.2f | %8.2f %8.2f | %8.2f %8.2f %8.2f %8.2f | %03d\"%\\\n                (self.mod14.fdist[i], area/1e4, hflux_kW, z_i,z_d,z_a,z_f,i)\n\n        return z\n\n#---\n    def getPlume(self,I=None,Verbose=True,**kwopts):\n \n        \"\"\"\n        Runs the Plume Rise extension to compute the extent of each plume.\n\t    \"\"\"\n\n        z_plume = __AMISS__ * ones(self.N)\n\n        R = arange(self.N)\n        if I is not None:\n            R = R[I]\n\n        if Verbose:\n            print \"\"\n            print \"                    Plume Height Estimates\"\n            print \"\"\n            print \"  --------------------|----------|-------------------|-------------------------------------------\"\n            print \"                      | Distance |   Fire Properties |             Plume Height\"\n            print \"    MINX Date/Time    |  to Fire |   Area   Heat Flx |    z_i      z_d      z_a      z_f\"\n            print \"                      |    km    |    ha      kW     |    km       km       km       km\"\n            print \"  --------------------|----------|-------------------|-------------------------------------------\"\n            \n#       Loop over time\n#       --------------\n        for i in R:\n            z_plume[i] = self.getPlume1(i,Verbose=Verbose,**kwopts)\n        if Verbose:\n            print \"  --------------------|----------|-------------------|-------------------------------------------\"\n\n        return array(z_plume)\n\n        if Verbose:\n            print \"  --------------------|----------|-------------------|----------\"\n\n#---\n    def getFires(self,mod14_path='/home/adasilva/iesa/aerosol/data/MODIS/Level2/MOD14',\n                      method='classic',\n                      npzFile=None,Verbose=True):\n        \"\"\"\n        Retrieves Level2 MOD14 fire data for each MINX fire.\n        \"\"\"\n        from dozier import DOZIER\n\n        self.mod14 = []\n        d2r = pi / 180.\n        a = MAPL_RADIUS/1000. # Earth radius in km\n        dt = timedelta(seconds=5*60)\n\n        self.mod14 = MOD14(self.N)\n        \n        if Verbose:\n            print \"\"\n            print \"                   Fire Heat Flux Estimates\"\n            print \"\"\n            print \"  --------------------|----------|-------------------|----------\"\n            print \"                      | Distance |    FRP Estimates  |   Fire\"\n            print \"    MINX Date/Time    |  to Fire |   MINX      MODIS | Heat Flux\"\n            print \"                      |    km    |    MW         MW  |  kW/m2\"\n            print \"  --------------------|----------|-------------------|----------\"\n\n        for i in range(self.N):\n\n            # Get fire granule for this particular day\n            # ----------------------------------------\n            t = self.tyme[i]\n            p = mod14_path\n            m = DOZIER(_getGran(t-dt,p) + _getGran(t,p) + _getGran(t+dt,p))\n\n            # Select closest fires\n            # --------------------\n            x0 = cos(d2r*self.lat_f[i]) * cos(d2r*self.lon_f[i])\n            y0 = cos(d2r*self.lat_f[i]) * sin(d2r*self.lon_f[i])\n            z0 = sin(d2r*self.lat_f[i])\n            dx = x0*cos(d2r*m.lat) * cos(d2r*m.lon)\n            dy = y0*cos(d2r*m.lat) * sin(d2r*m.lon)\n            dz = z0*sin(d2r*m.lat) \n            s  = a * arccos(dx+dy+dz) # great circle distance\n            j = s.argmin()\n\n            # Estimate fire heat flux\n            # -----------------------\n            if method=='bimodal':\n                m.bimodal_u()   # bimodal Dozier, need to provide trasnmittance\n                self.mod14.hflux[i] = m.h_F[j] # flaming Radiative Heat Flux\n                self.mod14.fdist[i] = s[j]\n                self.mod14.frp[i]  = m.pow_F[j]\n                self.mod14.pixar[i] = m.pixar[j]\n                self.mod14.farea[i] = m.r_F[j]\n                self.mod14.qa[i] = m.m[j] # bolean\n            else:\n                m.classic_var() # classic Dozier, need to provide trasnmittance\n                self.mod14.hflux[i] = m.hflux[j] # Radiative Heat Flux\n                self.mod14.fdist[i] = s[j]\n                self.mod14.frp[i]  = m.pow[j]\n                self.mod14.pixar[i] = m.pixar[j]\n                self.mod14.farea[i] = m.farea[j]\n                self.mod14.qa[i] = m.m[j] # bolean\n            if Verbose:\n                print \" \", t, \"| %8.2f | %8.2f %8.2f | %8.2f\"%\\\n                    (self.mod14.fdist[i], self.mod14.frp[i], self.mod14.frp[i], \\\n                     self.mod14.hflux[i] )\n\n        # Save fire properties in NPZ file for later\n        # ------------------------------------------\n        if npzFile!=None:\n            savez(npzFile,**self.mod14.__dict__)\n                  \n        if Verbose:\n            print \"  --------------------|----------|-------------------|----------\"\n\n#---\n    def getOptBrute(self,I=None,Verbose=True,**kwopts):\n \n        \"\"\"\n        Runs the Plume Rise extension to compute brute force optimal value of (hflux,area)\n        to match MISR plume height.\n\t    \"\"\"\n\n        z_opt = __AMISS__ * ones(self.N)\n        h_opt = __AMISS__ * ones(self.N)\n        a_opt = __AMISS__ * ones(self.N)\n        \n        R = arange(self.N)\n        if I is not None:\n            R = R[I]\n\n        Hflux_kW = linspace(1,100,10)\n        Area = linspace(0.1e4,2e4,10)\n\n        print Hflux_kW\n        print Area\n\n        if Verbose:\n            print \"\"\n            print \"                    Plume Height Estimates\"\n            print \"\"\n            print \"  --------------------|----------|-------------------|----------\"\n            print \"                      | Observed |    Opt Properties |  Optimal \"\n            print \"    MINX Date/Time    |  Height  |   Area   Heat Flx |  Height\"\n            print \"                      |    km    |    ha      kW     |    km\"\n            print \"  --------------------|----------|-------------------|----------\"\n            \n\n#       Loop over time\n#       --------------\n        for i in R:\n            z = m.z[i]\n            e = 1e20 # overestimate\n            for hflux_kW in Hflux_kW:\n                for area in Area:\n                    z_ = self.getPlume1(i,Verbose=False,hflux_kW=hflux_kW,area=area)\n                    if isnan(z)==False:\n                        e_ = (z-z_)**2\n                        if e_<e:\n                            e = e_\n                            z_opt[i] = z_\n                            h_opt[i] = hflux_kW\n                            a_opt[i] = area\n            if e<1e20:\n                if Verbose:\n                    print \" \", self.tyme[i], \"| %8.2f | %8.2f %8.2f | %8.2f\"%\\\n                          (z, a_opt[i]/1e4, h_opt[i], z_opt[i])\n                                        \n        if Verbose:\n            print \"  --------------------|----------|-------------------|----------\"\n\n        return (z_opt,h_opt,a_opt)\n\n#---\n    def getOptF(self,Verbose=True,area_m2=None):\n        \"\"\"\n        Find optimal fire modified bstar to match observed plume height.\n        \"\"\"\n\n        if Verbose:\n            print \"\"\n            print \"    Fire Modified bstar Optimization\"\n            print \"\"\n            print \"Plume | f_opt  |    J     |  Ni | Nf\"\n            print \"------|--------|----------|-----|-----\"\n\n        self.f_opt = ones(self.N)\n        self.z_opt = ones(self.N)\n        for i in range(self.N):\n#            xmin, fval, iter, fcalls = opt.brent(CostFuncF,args=(self,i),brack=(1.,4),full_output=True)\n            xmin, fval, iter, fcalls = opt.brent(CostFuncF,args=(self,i,area_m2),full_output=True)\n            if isnan(fval):\n                self.f_opt[i] = NaN\n                self.z_opt[i] = NaN\n            else:\n                rad2conv = xmin**2\n                self.f_opt[i] = rad2conv\n                self.z_opt[i] = self.getPlume1(i,rad2conv=self.f_opt[i],area_m2=area_m2)\n\n            if Verbose:\n                print \"%5d | %6.2f | %8.2f | %3d | %3d \"%(i, rad2conv, fval, iter, fcalls)\n\n        if Verbose:\n            print \"------|--------|----------|-----|-----\"\n\n#---\n    def getOptA(self,Verbose=True,rad2conv=5):\n        \"\"\"\n        Find optimal fire modified afac to match observed plume height.\n        \"\"\"\n\n        if Verbose:\n            print \"\"\n            print \"    Fire Modified afac Optimization\"\n            print \"\"\n            print \"Plume | f_opt  |    J     |  Ni | Nf\"\n            print \"------|--------|----------|-----|-----\"\n\n        self.a_opt = ones(self.N)\n        self.z_opt = ones(self.N)\n        for i in range(self.N):\n            xmin, fval, iter, fcalls = opt.brent(CostFuncA,args=(self,i,rad2conv),full_output=True) \n            afac = xmin**2\n            self.a_opt[i] = afac\n            self.z_opt[i] = self.getPlume1(i,afac=self.a_opt[i],rad2conv=rad2conv)\n            if Verbose:\n                print \"%5d | %6.2f | %8.2f | %3d | %3d \"%(i, afac, fval, iter, fcalls)\n\n        if Verbose:\n            print \"------|--------|----------|-----|-----\"\n\n#---\n    def getOptFanneal(self,Verbose=True):\n        \"\"\"\n        Find optimal fire hflux scaling to match observed plume height.\n        \"\"\"\n\n        if Verbose:\n            print \"\"\n            print \"    Fire Modified bstar Optimization\"\n            print \"\"\n            print \"Plume | f_opt  |    J     |  Ni | Nf\"\n            print \"------|--------|----------|-----|-----\"\n\n        self.f_opt = ones(self.N)\n        self.z_opt = ones(self.N)\n        for i in range(self.N):\n            xmin, fval, T, fcalls, iter, accept, retval = opt.anneal(CostFuncF,1.0,args=(self,i),full_output=True)\n            ffac = xmin**2\n            self.f_opt[i] = ffac\n            self.z_opt[i] = self.getPlume1(i,ffac=self.f_opt[i])\n            if Verbose:\n                print \"%5d | %6.2f | %8.2f | %3d | %3d \"%(i, ffac, fval, iter, fcalls)\n\n        if Verbose:\n            print \"------|--------|----------|-----|-----\"\n\n#---\n    def getOptFbnd(self,Verbose=True):\n        \"\"\"\n        Find optimal fire hflux scaling to match observed plume height.\n        \"\"\"\n\n        if Verbose:\n            print \"\"\n            print \"    Fire Modified bstar Optimization\"\n            print \"\"\n            print \"Plume | f_opt  |    J     |  Ni | Nf\"\n            print \"------|--------|----------|-----|-----\"\n\n        self.f_opt = ones(self.N)\n        self.z_opt = ones(self.N)\n        for i in range(self.N):\n            xmin,fval,ier,fcalls  = opt.fminbound(CostFuncF,0.,2.,args=(self,i),full_output=True)\n            ffac = xmin**2\n            self.f_opt[i] = ffac\n            self.z_opt[i] = self.getPlume1(i,rad2conv=self.f_opt[i])\n            if Verbose:\n                print \"%5d | %6.2f | %8.2f | %3d | %3d \"%(i, ffac, fval, fcalls, fcalls)\n\n        if Verbose:\n            print \"------|--------|----------|-----|-----\"\n\n#----\ndef CostFuncF(f,m,i,area_m2):\n    z = m.getPlume1(i,rad2conv=f**2,area_m2=area_m2)\n    return 1e-6 * (m.z[i]-z)**2\n\ndef CostFuncA(f,m,i,rad2conv):\n    z = m.getPlume1(i,afac=f**2,rad2conv=rad2conv)\n    return 1e-6 * (m.z[i]-z)**2\n\n#----------------------------------------------------------------------------------------------\n\nclass MOD14(object):\n    def __init__(self,N):\n        \"\"\"\n        Simple container class for fire properties.\n        \"\"\"\n        self.hflux = __AMISS__ * ones(N)  # fire heat flux estimate\n        self.fdist = __AMISS__ * ones(N)  # distance to detected fire\n        self.frp   = __AMISS__ * ones(N)  # nearest MODIS FRP\n        self.pixar = __AMISS__ * ones(N)  # pixel area\n        self.farea = __AMISS__ * ones(N)  # fire area\n        self.qa    = __AMISS__ * ones(N)  # quality flag\n        return\n    \n#----------------------------------------------------------------------------------------------\nclass PLUME_L2(DOZIER):\n\n    \"\"\"\n    Extension of the MxD14,IGBP and DOZIER classes, adding the\n    Plume Rise functionality. This class handles non-gridded,\n    observation location fires.\n    \"\"\"\n\n    def getPlume1(self,i,Verbose=False,rad2conv=5,area_m2=None):\n        \"\"\"\n        Compute plume height for the ith fire.\n        \"\"\"\n\n        # Fire properties\n        # ---------------\n        if area_m2 is None:\n            area = 1e6 * self.sample.farea[i] # km2 --> m2\n        else:\n            area = area_m2\n        hflux_kW = 1e3 * rad2conv * self.sample.pow[i] / area\n            \n        # Meteorology\n        # -----------        \n        ptop = 1. # Pascal\n        u = self.sample.u[i]\n        v = self.sample.v[i]\n        T = self.sample.t[i]\n        q = self.sample.qv[i]\n        delp = self.sample.delp[i]\n\n        if delp.min()<=0 or T.min()<=0:\n            print \"out of range: \", delp.min(), T.min() \n            return None\n\n        # Ensure arrays are top-down as in GEOS-5\n        # ---------------------------------------\n        if delp[0] > delp[-1]:\n            u = u[::-1]\n            v = v[::-1]\n            T = T[::-1]\n            q = q[::-1]\n            delp = delp[::-1]\n\n        # Run plume rise model\n        # --------------------        \n        z_i,z_d,z_a,z_f,z,w,rc = plumevmd(u,v,T,q,delp,ptop,hflux_kW,area)\n        if rc:\n            raise ValueError, \"error on return from <plume>, rc = %d\"%rc\n\n        if Verbose:\n            print \"| %8.2f %8.2f %s | %8.2f %8.2f | %8.2f %8.2f %8.2f %8.2f | %03d\"%\\\n                (self.lon[i],self.lat[i], str(self.tyme[i]), area/1e4, hflux_kW, z_i,z_d,z_a,z_f,i)\n        \n        return (z_i,z_d,z_a,z_f,z,w)\n\n#---\n    def getPlume(self,algo='dozier',Verbose=False,**kwargs):\n \n        \"\"\"\n        Runs the Plume Rise extension to compute the extent of the plume for each fire.\n        It is assumed that the necessary met fields have already been loaded in attribute\n        *sample* by method sampleFP or alternative.\n\n        \"\"\"\n\n        I = self.sample.I             # spatial subsetting\n        if len(I) != self.lon.size:\n                raise ValueError, 'sampling data appear inconsistent'\n            \n        N = len(self.lon)     # all obs\n        n = len(self.lon[I])  # reduced set in case of regional subsetting\n        self.sample.z_i = __AMISS__ * ones(n,dtype='float32')\n        self.sample.z_d = __AMISS__ * ones(n,dtype='float32')\n        self.sample.z_a = __AMISS__ * ones(n,dtype='float32')\n        self.sample.z_f = __AMISS__ * ones(n,dtype='float32')\n\n          \n        # Gather fire properties\n        # ----------------------\n        self.sample.pow   = self.pow[I]\n        self.sample.m     = self.m[I]\n            \n        # Assume that fire area has alread been estimated by classic_var()\n        # ----------------------------------------------------------------\n        if algo is not None:\n            self.sample.farea = self.farea[I]\n            if self.algo != algo:\n                raise ValueError, 'only dozier algorithm supportted'\n\n        if Verbose:\n            print \"\"\n            print \"                         Plume Height Estimates\"\n            print \"\"\n            print \"  --------------------|-----------------------|-------------------------------------------\"\n            print \"                      |    Fire Properties    |             Plume Height\"\n            print \"    Lon  Lat  Time    |   Area     Conv Pwr   |    z_i      z_d      z_a      z_f\"\n            print \"                      |    ha         kW      |    km       km       km       km\"\n            print \"  --------------------|-----------------------|-------------------------------------------\"\n            \n\n#       Loop over time\n#       --------------\n        s = self.sample # shorthand\n        for i in range(n):\n\n#           Interpolate met fields to fire location\n#           ---------------------------------------\n            if not self.sample.m[i]: continue   # skip over bad points\n\n#           Compute plume rise for this fire\n#           --------------------------------\n            s.z_i[i],s.z_d[i],s.z_a[i],s.z_f[i],z,q = self.getPlume1(i,Verbose=Verbose,**kwargs)\n\n#---\n    def getPlumeDeprecated(self,met):\n \n        \"\"\"\n        Runs the Plume Rise extension to compute the extent of the plume.\n        On input,\n\n        met --- MET object for computing Met fields\n\n        Notice that the Dozier must have been run and produced the farea\n        attribute. In addition, the veg attribute with the biome type must\n        have been defined as well.\n\t\"\"\"\n\n        if self.algo != 'dozier':\n            raise ValueError, 'only Dozier algorithm supported for now'\n\n        if self.veg is None:\n            raise ValueError, 'veg attribute with biome type has not been defined'\n\n\n#       Initialize Plume Rise ranges\n#       ----------------------------\n        ntd = met.ntd\n        N = self.lon.size\n        self.p_plume = zeros((ntd,N,2))\n        self.k_plume = zeros((ntd,N,2))\n        self.z_plume = zeros((ntd,N,2))\n        yyyy = self.yyyy[N/2]\n        jjj = self.jjj[N/2]\n\n#       Loop over time\n#       --------------\n        for t in range(1,ntd+1):\n    \n#           Interpolate met fields to fire location\n#           ---------------------------------------\n            met.interp(yyyy,jjj,t,lon=self.lon,lat=self.lat)\n\n#           Compute plume rise for this time\n#           --------------------------------\n            farea = self.r_F * self.farea # reduce area by flaming fraction\n            p, z, k = getPlume(farea,self.veg,met,t,ntd,self.verb)  \n\n#           Save in the approapriate containers\n#           -----------------------------------\n            self.p_plume[t-1,:,:] = p[:,:]\n            self.z_plume[t-1,:,:] = z[:,:]\n            self.k_plume[t-1,:,:] = k[:,:]\n\n#...............................................................................\n\nclass PLUME_L3(object):\n\n    \"\"\"\n    Extension of the MxD14,IGBP and DOZIER classes, adding the\n    Plume Rise functionality. This class handles non-gridded,\n    observation location fires.\n    \"\"\"\n\n    def __init__(self,plume,refine=4,res=None):\n        \"\"\"\n        Create a gridded Plume Rise object from a Level 2\n        PLUME_L2 object *plume*. The grid resolution is\n        specified by\n\n        refine  -- refinement level for a base 4x5 GEOS-5 grid\n                       refine=1  produces a   4  x  5    grid\n                       refine=2  produces a   2  x2.50   grid\n                       refine=4  produces a   1  x1,25   grid\n                       refine=8  produces a  0.50x0.625  grid\n                       refine=16 produces a  0.25x0.3125 grid\n\n        Alternatively, one can specify the grid resolution with a\n        single letter:\n\n        res     -- single letter denoting GEOS-5 resolution,\n                       res='a'  produces a   4  x  5    grid\n                       res='b'  produces a   2  x2.50   grid\n                       res='c'  produces a   1  x1,25   grid\n                       res='d'  produces a  0.50x0.625  grid\n                       res='e'  produces a  0.25x0.3125 grid\n\n                   NOTE: *res*, if specified, supersedes *refine*.\n\n        After initialization only the FRP weighted average area is\n        set, for each gridbox/biome, along with the coordinates of the\n        global grid.\n        \n        \"\"\"\n\n        N = plume.lon.size\n        self.verb = plume.verb\n\n#       Output grid resolution\n#       ----------------------\n        if res is not None:\n            if res=='a': refine = 1 \n            if res=='b': refine = 2\n            if res=='c': refine = 4\n            if res=='d': refine = 8\n            if res=='e': refine = 16\n\n#       Lat lon grid\n#       ------------\n        dx = 5. / refine\n        dy = 4. / refine\n        im = int(360. / dx)\n        jm = int(180. / dy + 1)\n        self.im = im\n        self.jm = jm\n        self.glon = linspace(-180.,180.,im,endpoint=False)\n        self.glat = linspace(-90.,90.,jm)\n        Lat, Lon  = meshgrid(self.glat,self.glon)  # shape should be (im,jm)\n\n        self.yyyy = plume.yyyy[N/2]\n        self.jjj  = plume.jjj[N/2]\n        self.date = date((int(self.yyyy),1,1)) + (int(self.jjj) - 1)*DAY\n        self.col  = plume.col\n        \n#       Supperobed fire attributes for each biome\n#       These will have 1D arrays for each biome, using\n#       a standard sparse matrix storage\n#       -----------------------------------------------\n        self.bioma = [1,2,3,4]\n        NONE       = [None,None,None,None] \n        self.idx   = NONE[:]  # non-zero indices for each biome\n        self.area  = NONE[:]  # non-zero areas   for \n        self.r_F   = NONE[:]  # corresponding flaming fraction\n        self.lon   = NONE[:]  # corresponding lon\n        self.lat   = NONE[:]  # corresponding lat\n\n#       Plume extent to be filled later\n#       -------------------------------\n        self.p_plume = NONE[:]\n        self.k_plume = NONE[:]\n        self.z_plume = NONE[:]\n\n#       Grid box average of fire flaming area, weighted by FRP\n#       -----------------------------------------------------\n        for b in self.bioma:\n\n#           Compute average area in gridbox for this biome\n#           ----------------------------------------------\n            Frac = zeros((im,jm))\n            Area = zeros((im,jm))\n            FRP  = zeros((im,jm))\n            i = (plume.veg==b)\n            if any(i):\n                blon = plume.lon[i]\n                blat = plume.lat[i]\n                bfrac = plume.r_F[i] * plume.pow[i] \n                barea = plume.r_F[i] * plume.farea[i] * plume.pow[i] # notice flaming fraction \n                bfrp  = plume.pow[i]\n                Area +=  binareas(blon,blat,barea,im,jm) # to be normalized\n                Frac +=  binareas(blon,blat,bfrac,im,jm) # to be normalized\n                FRP  +=  binareas(blon,blat,bfrp, im,jm)\n                I = (FRP>0.0)\n                if any(I):\n                    Area[I] = Area[I] / FRP[I]\n                    Frac[I] = Frac[I] / FRP[I]\n\n#           Use sparse matrix storage scheme\n#           --------------------------------\n            I = Area.nonzero()\n            if any(I):\n                self.area[b-1] = Area[I]\n                self.r_F[b-1]  = Frac[I] # average flaming/total energy fraction\n                self.lon[b-1]  = Lon[I]\n                self.lat[b-1]  = Lat[I]\n                self.idx[b-1]  = I       # save indices for going to global grid\n\n    def getPlume(self):\n \n        \"\"\"\n        Runs the Plume Rise extension to compute the extent of the plume.\n        On input,\n\n        met --- MET object for computing Met Fields at obs location.\n\n\t\"\"\"\n\n        ntd = met.ntd # number of time steps per day\n        self.ntd = ntd\n        \n#       Loop over bioma\n#       ---------------\n        for i in range(len(self.bioma)):\n\n#           No data for this bioma, nothing to do\n#           -------------------------------------\n            if self.idx[i] is None:\n                if self.verb>0:\n                    print \"[x] no data for %s\"%Bioma[i] \n                continue\n\n            lon = self.lon[i]\n            lat = self.lat[i]\n            area = self.area[i]\n            N = lon.size\n            veg = self.bioma[i] * ones(N)\n\n            p_plume = zeros((ntd,2,N))\n            z_plume = zeros((ntd,2,N))\n            k_plume = zeros((ntd,2,N))\n                            \n            if self.verb>0:\n                print \"[ ] got %d burning gridboxes in %s\"%(N,Bioma[i]) \n\n#           Loop over time \n#           --------------\n            for t in range(1,ntd+1):\n\n#               Interpolate met fields to fire locations\n#               ----------------------------------------\n                met.interp(self.yyyy,self.jjj,t,lon=lon,lat=lat)\n\n#               Compute plume rise for this time, biome\n#               ---------------------------------------\n                p, z, k = getPlume(area,veg,met,t,ntd,self.verb)  \n\n#               Save in the approapriate containers\n#               -----------------------------------\n                p_plume[t-1,:,:] = p.T[:,:]\n                z_plume[t-1,:,:] = z.T[:,:]\n                k_plume[t-1,:,:] = k.T[:,:]\n\n#           Plume extent for this biome (sparse storage)\n#           --------------------------------------------\n            self.p_plume[i] = p_plume\n            self.z_plume[i] = z_plume\n            self.k_plume[i] = k_plume\n\n#---\n    def write(self,filename=None,dir='.',expid='qfed2',tag=None):\n       \"\"\"\n       Writes gridded Area and FRP to file.\n       \"\"\"\n\n       vtitle = {}\n       vtitle['fa'] = 'Flaming Area'\n       vtitle['ff'] = 'Fraction of Flaming Energy'\n       vtitle['p2'] = 'Plume Bottom Pressure'\n       vtitle['p1'] = 'Plume Top Pressure' \n       vtitle['z2'] = 'Plume Bottom Height' \n       vtitle['z1'] = 'Plume Top Height' \n       vtitle['k2'] = 'Plume Bottom Vertical Index' \n       vtitle['k1'] = 'Plume Top Vertical Index' \n                 \n       vunits = {}\n       vunits['fa'] = 'km2'\n       vunits['ff'] = '1'\n       vunits['p2'] = 'Pa'\n       vunits['p1'] = 'Pa'\n       vunits['z2'] = 'meter'\n       vunits['z1'] = 'meter'\n       vunits['k2'] = '1'\n       vunits['k1'] = '1'\n                 \n       btitle = {}\n       btitle['tf'] = 'Tropical Forest' \n       btitle['xf'] = 'Extra-Tropical Forest'\n       btitle['sv'] = 'Savanna'\n       btitle['gl'] = 'Grassland'\n\n#      Create master variable list\n#      ---------------------------\n       Vname  = []\n       Vtitle = []\n       Vunits = []\n       for v in vtitle.keys():\n           vt = vtitle[v]\n           vu = vunits[v]\n           for b in btitle.keys(): \n               bt = btitle[b]\n               Vname.append(v+'_'+b)\n               Vtitle.append(vt+' ('+bt+')')\n               Vunits.append(v)\n\n#      Global metadata\n#      ---------------\n       title = 'QFED Level3c v%3.1f (%s) Gridded Plume Rise Estimates' % (__VERSION__, _getTagName(tag))\n       source = 'NASA/GSFC/GMAO GEOS-5 Aerosol Group'\n       contact = 'arlindo.dasilva@nasa.gov'\n\n#      Time/date handling\n#      ------------------\n       if self.date is None:\n           print \"[x] did not find matching files, skipped writing an output file\"\n           return\n\n       if 24%self.ntd != 0:\n           raise ValueError,\"invalid number of times per day (%d),\"%self.ntd\\\n                 +\"it must be a divisor of 24.\"\n       else:\n           dT = 240000/self.ntd # timestep in hhmmss format\n           NHMS = range(0,240000,dT)\n\n       nymd = 10000*self.date.year + 100*self.date.month + self.date.day\n       nhms = NHMS[0]\n       col = self.col\n\n#      Create output file name\n#      -----------------------\n       if filename is None:\n           filename = '%s/%s.plumerise.%s.%d.nc'%(dir,expid,col,nymd)\n       self.filename = filename\n       f = GFIO()\n       f.create(filename,Vname, nymd, nhms,\n                lon=self.glon, lat=self.glat,\n                vtitle=Vtitle, vunits=Vunits,\n                timinc=dT, amiss=__AMISS__,\n                title=title, source=source, contact=contact)\n\n#      Write out Plume Rise variables\n#      ------------------------------\n       d = (self.im,self.jm)\n       for t in range(self.ntd):\n           nhms = NHMS[t]\n           b = 0\n           for bn in btitle.keys():\n               I = self.idx[b]\n               f_area  = self.area[b]\n               f_frac  = self.r_F[b]\n               p_plume = self.p_plume[b]\n               z_plume = self.z_plume[b]\n               k_plume = self.k_plume[b]\n               _writeOne(f,'fa_'+bn,nymd,nhms,I,f_area, t,0,d)\n               _writeOne(f,'ff_'+bn,nymd,nhms,I,f_frac, t,0,d)\n               _writeOne(f,'p1_'+bn,nymd,nhms,I,p_plume,t,0,d)\n               _writeOne(f,'p1_'+bn,nymd,nhms,I,p_plume,t,0,d)\n               _writeOne(f,'p2_'+bn,nymd,nhms,I,p_plume,t,1,d)\n               _writeOne(f,'z1_'+bn,nymd,nhms,I,z_plume,t,0,d)\n               _writeOne(f,'z2_'+bn,nymd,nhms,I,z_plume,t,1,d)\n               _writeOne(f,'k1_'+bn,nymd,nhms,I,k_plume,t,0,d)\n               _writeOne(f,'k2_'+bn,nymd,nhms,I,k_plume,t,1,d)\n               b += 1\n\n       try:\n           f.close()\n       except:\n           pass\n\n       if self.verb >=1:\n           print \"[w] Wrote file \"+filename\n\n#..............................................................................\n\n#\n#                                    Static Methods\n#                                    --------------\n#\n\ndef _writeOne(f,vname,nymd,nhms,I,S,t,k,d):\n    \"\"\"\n    Write one sparse variable to a GFIO file.\n    \"\"\"\n    A = zeros(d) + __AMISS__\n    if I is not None:\n        if len(S.shape)==3:\n            A[I] = S[t,k,:]\n        elif len(S.shape)==1:\n            A[I] = S[:]\n        else:\n            raise ValueError, 'invalid S rank = %d'%len(S.shape)\n            \n    f.write(vname,nymd,nhms,A)\n\n\ndef getPlumeDeprecated(farea,veg,met,t,ntd,Verb=0):\n    \n    \"\"\"\n    Runs the Plume Rise extension to compute the extent of the plume.\n\n          p, z, k = getPlume(farea,veg,met,t,ntd)\n\n    where p, z and k are nd-arrays of shape(N,2), N being the\n    number of observations (as in met.lon.size). On input,\n\n    farea --- (flaming) fire area\n    veg   --- biome type\n    \n    \"\"\"\n\n    N = met.lon.size\n    nominal_area = 1.e6 # 1 km^2: pixar and farea are in units of km2\n    km = met.lev.size\n    ptop = met.ptop\n    ktop = met.ktop # 1-offset\n\n    if Verb:\n        if N>100:\n            Np = range(0,N,N/10)\n        elif N>10:\n            Np = range(0,N,N/10)\n        else:\n            Np = range(N)\n        print \"\"\n        print \"                   Plume Rise Estimation for t=%d\"%t\n        print \"                   ------------------------------\"\n        print \"\"\n        print \"  %  |    Lon    Lat  b |   p_bot    p_top  |  z_bot z_top  |  k   k\"     \n        print \"     |    deg    deg    |    mb       mb    |   km     km   | bot top\"\n        print \"---- |  ------ ------ - | -------- -------- | ------ ------ | --- ---\"\n\n#   Allocate space\n#   --------------\n    p_plume = zeros((N,2))\n    k_plume = zeros((N,2))\n    z_plume = zeros((N,2))\n        \n#   Compute plume extent, one fire at a time\n#   ----------------------------------------\n    for i in range(N):\n\n        u = met.fields['u'][i]\n        v = met.fields['v'][i]\n        T = met.fields['t'][i]\n        q = met.fields['qv'][i]\n        delp = met.fields['delp'][i]\n\n#       Ensure arrays are top-down as in GEOS-5\n#       ---------------------------------------\n        if delp[0] > delp[-1]:\n            u = u[::-1]\n            v = v[::-1]\n            T = T[::-1]\n            q = q[::-1]\n            delp = delp[::-1]\n\n#       Units:\n#           farea - km2 (must multiply by nominal area for m2)\n#            area  - m2 as required by plume rise model\n#       ------------------------------------------------------   \n        area = farea[i] * nominal_area\n        veg_ = veg[i]\n\n#       Run plume rise model\n#       --------------------\n        p1, p2, z1, z2, k1, k2, rc = \\\n            biome(u, v, T, q, delp, ptop, area, veg_)\n\n        k1, k2 = (k1+ktop-1, k2+ktop-1)\n\n        p_plume[i,:] = (p1, p2)\n        k_plume[i,:] = (k1, k2)\n        z_plume[i,:] = (z1, z2)\n\n        if Verb:\n            if i in Np:\n                ip = int(0.5+100.*i/N)\n                print \"%3d%% | %7.2f %6.2f %d | %8.2f %8.2f | %6.2f %6.2f | %3d %3d \"%\\\n                      (ip,met.lon[i],met.lat[i],veg[i], \\\n                       p2/100,p1/100,z2/1000,z1/1000,k2,k1)\n\n    return (p_plume, z_plume, k_plume)\n\n\ndef _getTagName(tag):\n    if tag != None:\n        tag_name = tag\n    else:    \n        if __CVSTAG__ not in (None, ''):\n            tag_name = __CVSTAG__\n        else:\n            tag_name = 'unknown'\n\n    return tag_name\n\n#----\ndef _getGran(t,mod14_path):\n    doy = t.date().toordinal() - date(t.year-1,12,31).toordinal()\n    hhmm = \"%02d%02d\"%(t.hour,5*(t.minute/5))\n    patt = mod14_path+'/%4d/%03d/MOD14.A%4d%03d.%s.005.*.hdf'%(t.year,doy,t.year,doy,hhmm)\n#    print '--> ', patt\n    return glob(patt)\n\n#---\n\n#..............................................................................\n\ndef plotMINX(m,imfile=None,Title=None):\n\n    from matplotlib.pyplot import plot, legend, xlabel, ylabel, title, grid, figure, savefig\n\n    I_ = m.z>0\n    I = m.z>(m.sample.pblh+250)\n    J = m.zm>(m.sample.pblh+250)\n    K = m.zt>(m.sample.pblh+250)\n\n    figure(dpi=120)\n    plot([0,5],[0,5],'k') # 1:1 line\n    plot(m.sample.pblh[I_]/1000,m.z[I_]/1000, 'bo',label='Mode Height < PBL')\n    plot(m.sample.pblh[I]/1000,m.z[I]/1000, 'co',label='Mode Height > PBL')\n    plot(m.sample.pblh[K]/1000,m.zt[K]/1000, 'ro',label='95%-ile Height > PBL')\n\n    print \"Percent above PBL: \",100.*len(m.z[I])/len(m.z[I_])\n    \n    \n    x, ya, yb = m.sample.pblh[K]/1000, m.zt[K]/1000, m.z[K]/1000\n    for i in range(len(x)):\n        plot([x[i],x[i]],[ya[i],yb[i]],'k')\n    \n    xlabel('GEOS-5 PBL Height AGL [km]')\n    ylabel('MINX Plume Height AGL [km]')\n    legend(loc='upper right',fontsize='medium')\n    grid()\n\n    if Title is not None:\n        title(Title)\n        \n    if imfile is not None:\n        savefig(imfile,bbox_inches='tight')\n\ndef plotAreaFRP(m,z_plume,imfile=None,Title=None):\n    from matplotlib.pyplot import plot, legend, xlabel, ylabel, title, grid, figure, savefig\n\n    figure(dpi=120)\n    J = z_plume>(m.sample.pblh+250)\n    area = m.mod14.farea * m.mod14.pixar * 1e6 / 1e4\n    plot(area,m.mod14.frp,'bo')\n    plot(area[J],m.mod14.frp[J],'ro')\n    grid()\n    xlabel(r'Fire Area [Ha]')\n    ylabel('FRP/Area [MW]')\n    \ndef plotPR(m,z_plume,imfile=None,Title=None):\n    from matplotlib.pyplot import plot, legend, xlabel, ylabel, title, grid, figure, savefig\n    \n    I = m.z>(m.sample.pblh+250)\n    J = z_plume>(m.sample.pblh+250)\n    \n    figure(dpi=120)\n    plot([0.5,4],[0.5,4],'k')\n    plot(m.sample.pblh/1000,z_plume/1000, 'bo',label='Modeled Below PBL')\n    plot(m.sample.pblh[J]/1000,z_plume[J]/1000,'co',label='Modeled above PBL')\n    #plot(m.sample.pblh[I]/1000,z_plume[I]/1000,'ro',label='Observed above PBL')\n    plot(m.sample.pblh[I]/1000,m.z[I]/1000,'ro',label='Observed above PBL')\n\n    x, ya, yb = m.sample.pblh[I]/1000, z_plume[I]/1000, m.z[I]/1000\n    for i in range(len(x)):\n        plot([x[i],x[i]],[ya[i],yb[i]],'k')\n    \n    xlabel('GEOS-5 PBL Height AGL [km]')\n    ylabel('Plume Height AGL [km]')\n    legend(loc='lower right')\n    grid()\n\n    if Title is not None:\n        title(Title)\n        \n    if imfile is not None:\n        savefig(imfile,bbox_inches='tight')\n    \ndef scatOpt(m,imfile=None,Title=None,norm=True,xymax=1.9999):\n\n    from matplotlib.pyplot import plot, legend, xlabel, ylabel, title, grid, figure, savefig\n\n    z     = m.z/m.sample.pblh\n    z_opt = m.z_opt/m.sample.pblh\n    \n    I = z>0\n    J = z_opt>1\n    K = (z>1)&(z_opt>1)\n\n    if not norm:    \n        z     = m.z/1000\n        z_opt = m.z_opt/1000\n        \n    figure(dpi=120)\n    if norm:\n        plot([0,xymax],[0,xymax],'k')\n        plot([0,xymax],[1,1],'k')\n        plot([1,1],[0,xymax],'k')\n    plot(z[I],z_opt[I],'yo',label=r'$z_{OBS}<z_{PBL}$, $z_{OPT}<z_{PBL}$')\n    plot(z[J],z_opt[J],'ro',label=r'$z_{OBS}<z_{PBL}$, $z_{OPT}>z_{PBL}$')\n    plot(z[K],z_opt[K],'go',label=r'$z_{OBS}>z_{PBL}$, $z_{OPT}>z_{PBL}$')\n\n    if norm:\n        xlabel(r'$z_{OBS}/z_{PBL}$')\n        ylabel(r'$z_{OPT}/z_{PBL}$')\n    else:\n        xlabel(r'$z_{OBS}$')\n        ylabel(r'$z_{OPT}$')\n        \n    legend(loc='lower right')\n    grid()\n\n    if Title is not None:\n        title(Title)\n        \n    if imfile is not None:\n        savefig(imfile,bbox_inches='tight')\n\ndef scatOptF(m,imfile=None,Title=None,norm=True,xymax=1.9999):\n\n    from matplotlib.pyplot import plot, legend, xlabel, ylabel, title, grid, figure, savefig, loglog\n\n    z     = m.z/m.sample.pblh\n    z_opt = m.z_opt/m.sample.pblh\n    \n    I = (z>0)&(isnan(m.f_opt)==False)#&(m.f_opt<100)&(m.mod14.frp<100)\n    J = I&(z_opt>1)\n    K = I&(z>1)&(z_opt>1)\n\n    if not norm:    \n        z     = m.z/1000\n        z_opt = m.z_opt/1000\n        \n    figure(dpi=120)\n    loglog(m.mod14.frp[I],m.f_opt[I],'yo',label=r'$z_{OBS}<z_{PBL}$, $z_{OPT}<z_{PBL}$')\n    loglog(m.mod14.frp[J],m.f_opt[J],'ro',label=r'$z_{OBS}<z_{PBL}$, $z_{OPT}>z_{PBL}$')\n    loglog(m.mod14.frp[K],m.f_opt[K],'go',label=r'$z_{OBS}>z_{PBL}$, $z_{OPT}>z_{PBL}$')\n\n    xlabel('FRP [MW]')\n    ylabel(r'$\\gamma$')     \n    #legend(loc='upper right')\n    grid()\n\n    if Title is not None:\n        title(Title)\n        \n    if imfile is not None:\n        savefig(imfile,bbox_inches='tight')\n\ndef scatPR(m,z_plume,imfile=None,Title=None):\n\n    from matplotlib.pyplot import plot, legend, xlabel, ylabel, title, grid, figure, savefig\n\n    z     = m.z/m.sample.pblh\n    z_pr = z_plume/m.sample.pblh\n    \n    I = z>0\n    J = (z_pr>1)|((z_pr<1)&(z>1))\n    K = (z>1)&(z_pr>1)\n\n    figure(dpi=120)\n    plot([0,1.5999],[0,1.5999],'k')\n    plot([0,2.999],[1,1],'k')\n    plot([1,1],[0,1.5999],'k')\n    plot(z[I],z_pr[I],'yo',label=r'$z_{OBS}<z_{PBL}$, $z_{PR}<z_{PBL}$')\n    plot(z[J],z_pr[J],'ro',label=r'$z_{OBS}<z_{PBL}$, $z_{PR}>z_{PBL}$')\n    plot(z[K],z_pr[K],'go',label=r'$z_{OBS}>z_{PBL}$, $z_{PR}>z_{PBL}$')\n\n    xlabel(r'$z_{OBS}/z_{PBL}$')\n    ylabel(r'$z_{PR}/z_{PBL}$')\n        \n    legend(loc='lower right')\n    grid()\n\n    if Title is not None:\n        title(Title)\n        \n    if imfile is not None:\n        savefig(imfile,bbox_inches='tight')\n\n#--\n\ndef plotKDE(s,s2=None,Title='',imfile=None):\n\n    from matplotlib.pyplot import plot, legend, xlabel, ylabel, title, grid, figure, savefig\n\n    J = (s.pblh>100)&(s.z_a>0)\n    r = s.z_a/s.pblh\n    if s2 is not None:\n        J2 = (s2.pblh>100)&(s2.z_a>0)\n        r2 = s2.z_a/s2.pblh\n    \n    # KDE 1d\n    # ------\n    figure(dpi=120)\n    bins, P = kde.calc_kde1d(r[J],range=(0,5))\n    plot(bins,P,'b',linewidth=2,label='Terra')\n    if s2 is not None:\n        bins, P2 = kde.calc_kde1d(r2[J2],range=(0,5))\n        plot(bins,P2,'r',linewidth=2,label='Aqua')\n        legend(loc='upper right')\n    grid()\n    xlabel(r'$z_{PR}/z_{PBL}$')\n    ylabel('p.d.f.')\n    if Title is not None:\n        title(Title)\n    if imfile is not None:\n        savefig('kde1d.'+imfile,bbox_inches='tight')\n\n    if s2 is not None: return\n    \n    # KDE 2d\n    # ------\n    x, y, P = kde.calc_kde2d(s.pblh[J]/1000,s.z_a[J]/1000,x_range=(0,3),y_range=(0,3))\n    kde.plot_kde2d(x,y,P,dpi=120,Title=Title,\n                   xLabel=r'$z_{PBL}$', yLabel=r'$z_{PR}$')\n    grid()\n    if imfile is not None:\n        savefig('kde2d.'+imfile,bbox_inches='tight')\n    \ndef aveVMD(s):\n    \"\"\"\n    Compute average vertical mass distribution, weighted by FRP.\n    \"\"\"\n    J = (s.pblh>100)&(s.z_a>0)\n\n    z_c   = s.z_d[J]/1000\n    delta = (s.z_f[J] - s.z_d[J])/1000\n    pow = s.pow[J]\n    pblh = s.pblh[J]/1000\n    \n    nz = 100\n    nf = len(pblh)\n    z = linspace(0,5,nz)\n\n\n    # PBL mass distribution\n    # ---------------------\n    V = zeros(nz)\n    for i in range(nf):\n        v = zeros(nz)\n        v[z<pblh[i]] = 1\n        v = pow[i] * v / sum(v)\n        V += v\n    v_pbl = V / pow.sum()\n\n    return v_pbl\n\n    v = getvmd(z,z_c,delta)\n\n    \n\n    \n#-------------------------------\n        \nif __name__ == \"__main__\":\n\n    import crtmmodis_\n\n    m = MINXs_PR('/Users/adasilva/workspace/misrPlumes/western_fires_2013/*.txt')\n    m.sampleLoadz('/Users/adasilva/workspace/Data_Analysis/AGU-2014/seac4rs_01.npz')\n    m.mod14 = NPZ(('/Users/adasilva/workspace/Data_Analysis/AGU-2014/mod14_seac4rs.npz',))\n\ndef _allfires():\n    \n    print \"ok\"\n    topdir = '/Volumes/ArlindoSD' # SDXC card\n\n    t1 = datetime(2013,8,2)\n    t2 = datetime(2013,8,31)\n\n    #for p in ( 'MOD14', 'MYD14'):\n    for p in ( 'MYD14',):\n\n        print \"Loading fires\"\n        f = PLUME_L2(None)\n        f.restart('%s.fires_nam.%4d-%02d.npz'%(p,t1.year,t1.month))\n\n        f.m = f.qc>0\n        \n        print \"Loading Meteorology\"\n        f.sampleLoadz('%s/AGU-2014/%s.sample_nam.%4d-%02d.npz'%(topdir,p,t1.year,t1.month))\n\n        I_na = (f.lon>-170)&(f.lon<-50)&(f.lat>15)&(f.lat<80)\n        f.sample.I = I_na\n\n        f.getPlume(algo=None,Verbose=True,area_m2=10e4,rad2conv=5)\n\n        f.sample.pblh = f.sample.pblh[I_na]\n        savez('%s.sample_a1_r10_r5.2013-08.npz'%p,**f.sample.__dict__)\n        \ndef xxxxx():\n    \n#--\n                \n        Files = granules(t1,t2,product=p,rootdir=topdir+'/MODIS')\n\n        print 'Number of files: ', len(Files)\n        f = PLUME_L2(Files,Verb=1)\n\n        print \"Computing fire properties\"\n        ###f.classic_var()\n\n        print \"Checkpointing\"\n        f.checkpoint('%s.fires_nam.%4d-%02d.npz'%(p,t1.year,t1.month))\n\ndef minx_test():\n    \n    m = MINXs_PR('/Users/adasilva/workspace/misrPlumes/western_fires_2013/*.txt')\n    m.sampleLoadz('/Users/adasilva/workspace/Data_Analysis/AGU-2014/seac4rs_01.npz')\n    m.mod14 = NPZ(('/Users/adasilva/workspace/Data_Analysis/AGU-2014/mod14_seac4rs.npz',))\n    #plotMINX(m)\n\n    #z_plume = m.getPlume()\n\n    \ndef arctas():\n    # m.getFires(npzFile='mod14_seac4rs.npz')\n#    m = MINXs_PR('/Users/adasilva/workspace/misrPlumes/canada2008/Plumes*.txt')\n\n    m = MINXs_PR('/Users/adasilva/workspace/misrPlumes/canada2008/Plumes*.txt')\n    m.sampleLoadz('merraero.npz')\n    m.mod14 = NPZ('mod14.npz')\n    \n#    z_plume = m.getPlume()\n\ndef Mac():\n    m = MINXs_PR('/Users/adasilva/workspace.local/misrPlumes/canada2008/Plumes*.txt')\n#    m.sampleLoadz('/Users/adasilva/workspace.local/misrPlumes/canada2008/merra.npz')\n#    m.sampleLoadz('merra.npz')\n#    m.mod14 = NPZ('mod14.npz')\n#    z_plume = m.getPlume()\n", "meta": {"hexsha": "1251a32277ffcbb2dfcf4ad987c9deb150be9a4b", "size": 46464, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Components/qfed/qfed/PlumeRise.py", "max_stars_repo_name": "GEOS-ESM/AeroApps", "max_stars_repo_head_hexsha": "874dad6f34420c014d98eccbe81a061bdc0110cf", "max_stars_repo_licenses": ["NASA-1.3", "ECL-2.0", "Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-02T14:23:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T15:39:30.000Z", "max_issues_repo_path": "src/Components/qfed/qfed/PlumeRise.py", "max_issues_repo_name": "GEOS-ESM/AeroApps", "max_issues_repo_head_hexsha": "874dad6f34420c014d98eccbe81a061bdc0110cf", "max_issues_repo_licenses": ["NASA-1.3", "ECL-2.0", "Apache-2.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-04-15T16:22:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T13:59:25.000Z", "max_forks_repo_path": "src/Components/qfed/qfed/PlumeRise.py", "max_forks_repo_name": "GEOS-ESM/AeroApps", "max_forks_repo_head_hexsha": "874dad6f34420c014d98eccbe81a061bdc0110cf", "max_forks_repo_licenses": ["NASA-1.3", "ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0234541578, "max_line_length": 117, "alphanum_fraction": 0.462035124, "include": true, "reason": "from numpy,from scipy", "num_tokens": 13144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.34510526422232046, "lm_q1q2_score": 0.19665914983407257}}
{"text": "# Copyright (c) Anand Patil, 2007\n\n__docformat__ = 'reStructuredText'\n\nimport pymc as pm\nimport linalg_utils\nimport copy\nimport types\nimport numpy as np\nfrom gp_submodel import *\nimport warnings\n\nfrom Realization import Realization\nfrom Mean import Mean\nfrom Covariance import Covariance\nfrom GPutils import observe, regularize_array\n\n__all__ = ['wrap_metropolis_for_gp_parents', 'GPEvaluationGibbs', 'GPParentAdaptiveMetropolis']\n\ndef wrap_metropolis_for_gp_parents(metro_class):\n    \"\"\"\n    Wraps Metropolis step methods so they can handle extended parents of\n    Gaussian processes.\n    \"\"\"\n    class wrapper(metro_class):\n        def __init__(self, stochastic, *args, **kwds):\n            \n            self.metro_class.__init__(self, stochastic, *args, **kwds)\n            \n            # Remove f from the set that will be used to compute logp_plus_loglike.\n            self.markov_blanket_no_f = filter(lambda x: not isinstance(x, GaussianProcess), self.markov_blanket)\n            self.fs = filter(lambda x: isinstance(x, GaussianProcess), self.markov_blanket)\n            self.fr_checks = [f.submodel.fr_check for f in self.fs]\n\n        def get_logp_plus_loglike(self):\n            return pm.logp_of_set(self.markov_blanket_no_f)\n        logp_plus_loglike = property(get_logp_plus_loglike)\n    \n        def propose(self):\n            self.metro_class.propose(self)\n            try:\n                # First make sure none of the stochastics handled by metro_method forbid their current values.\n                for s in self.stochastics:\n                    s.logp\n                # Then make sure the covariances are all still full-rank on the observation locations.\n                for frc in self.fr_checks:\n                    frc.logp\n                for f in self.fs:\n                    f.rand()\n                self.f_proposed = True\n            except pm.ZeroProbability:\n                self.f_proposed = False\n            \n        def reject(self):\n            self.metro_class.reject(self)\n            if self.f_proposed:\n                for f in self.fs:\n                    f.revert()\n        \n        @staticmethod\n        def competence(stochastic, metro_class=metro_class):\n            if any([isinstance(child, GaussianProcess) for child in stochastic.extended_children]):\n                return metro_class.competence(stochastic)+.01\n            else:\n                return 0\n        \n    wrapper.__name__ = 'GPParent%s'%metro_class.__name__\n    wrapper.metro_class = metro_class\n    wrapper.__doc__ = \"\"\"A modified version of class %s that handles parents of Gaussian processes.\nDocstring of class %s: \\n\\n%s\"\"\"%(metro_class.__name__,metro_class.__name__,metro_class.__doc__)\n            \n    return wrapper\n\n\n# Wrap all registered Metropolis step methods to use GP parents.\nnew_sm_dict = {}\nfiltered_registry = filter(lambda x: issubclass(x, pm.Metropolis), pm.StepMethodRegistry)\nfor sm in filtered_registry:\n    wrapped_method = wrap_metropolis_for_gp_parents(sm)\n    new_sm_dict[wrapped_method.__name__] = wrapped_method\nGPParentAdaptiveMetropolis = wrap_metropolis_for_gp_parents(pm.AdaptiveMetropolis)\n__all__ += new_sm_dict.keys()\nlocals().update(new_sm_dict)\n\n\nclass GPEvaluationGibbs(pm.Metropolis):\n    \"\"\"\n    Updates a GP evaluation f_eval. Assumes the only children of f_eval\n    are as distributed follows:\n    \n    eps_p_f ~ Normal(f_eval[ti], 1./V)\n    \n    or\n    \n    eps_p_f ~ Normal(f_eval, 1./V)\n    \n    if ti is None.\n    \"\"\"\n    def __init__(self, submod, V, eps_p_f, ti=None, tally=True, verbose=0):        \n\n        self.f_eval = submod.f_eval\n        self.f = submod.f\n        pm.StepMethod.__init__(self, [self.f, self.f_eval], tally=tally)\n        \n        self.children_no_data = copy.copy(self.children)\n        if isinstance(eps_p_f, pm.Variable):\n            self.children_no_data.discard(eps_p_f)\n        else:\n            for epf in eps_p_f:\n                self.children_no_data.discard(epf)\n        \n        self.V = V\n        self.C_eval = submod.C_eval\n        self.M_eval = submod.M_eval\n        self.S_eval = submod.S_eval\n        self.eps_p_f = eps_p_f\n\n        M_eval_shape = pm.utils.value(self.M_eval).shape\n        C_eval_shape = pm.utils.value(self.C_eval).shape\n        self.ti = ti or np.arange(M_eval_shape[0])\n\n        # Work arrays\n        self.scratch1 = np.asmatrix(np.empty(C_eval_shape, order='F'))\n        self.scratch2 = np.asmatrix(np.empty(C_eval_shape, order='F'))\n        self.scratch3 = np.empty(M_eval_shape)    \n\n        # Initialize hidden attributes\n        self.accepted = 0.\n        self.rejected = 0.\n        self._state = ['rejected', 'accepted', 'proposal_distribution']\n        self._tuning_info = []\n        self.proposal_distribution=None\n    \n    \n    def get_logp(self):\n        return 0.\n    logp = property(get_logp)\n    \n    def get_loglike(self):\n        return pm.utils.logp_of_set(self.children_no_data)\n    loglike = property(get_loglike)\n        \n    def get_logp_plus_loglike(self):\n        return self.get_loglike()\n    logp_plus_loglike = property(get_logp_plus_loglike)\n        \n    def reject(self):\n        self.rejected += 1\n        if self.verbose:\n            print self._id + ' rejecting'\n        # Revert the field evaluation and the rest of the field.\n        self.f_eval.revert()\n        self.f.revert()\n    \n    def tune(self, verbose=0):\n        return False\n            \n    def propose(self):\n        if self.verbose:\n            print self._id + ' proposing'\n\n        fc = pm.gp.fast_matrix_copy\n\n        eps_p_f = pm.utils.value(self.eps_p_f)\n        f = pm.utils.value(self.f_eval)\n        for i in xrange(len(self.scratch3)):\n            self.scratch3[i] = np.sum(eps_p_f[self.ti[i]] - f[i])\n\n        # Compute Cholesky factor of covariance of eps_p_f, C(x,x) + V\n        C_eval_value = pm.utils.value(self.C_eval)\n        C_eval_shape = C_eval_value.shape\n        \n        # Get the Cholesky factor of C_eval, plus the nugget.\n        # I don't think you can use S_eval for speed, unfortunately.\n        in_chol = fc(C_eval_value, self.scratch1)\n        for i in xrange(pm.utils.value(C_eval_shape)[0]):\n            in_chol[i,i] += pm.utils.value(self.V) / np.alen(self.ti[i])\n        info = pm.gp.linalg_utils.dpotrf_wrap(in_chol)\n        if info > 0:\n            raise np.linalg.LinAlgError\n\n        # Compute covariance of f conditional on eps_p_f.\n        offdiag = fc(C_eval_value, self.scratch2)\n        offdiag = pm.gp.trisolve(in_chol, offdiag, uplo='U', transa='T', inplace=True)\n\n        C_step = offdiag.T * offdiag\n        C_step *= -1\n        C_step += C_eval_value\n\n        # Compute mean of f conditional on eps_p_f.\n        for i in xrange(len(self.scratch3)):\n            self.scratch3[i] = np.mean(eps_p_f[self.ti[i]])\n        m_step = pm.utils.value(self.M_eval) + np.dot(offdiag.T, pm.gp.trisolve(in_chol,(self.scratch3 - self.M_eval.value),uplo='U',transa='T')).view(np.ndarray).ravel()\n\n        sig_step = C_step\n        info = pm.gp.linalg_utils.dpotrf_wrap(C_step.T)\n        if info > 0:\n            warnings.warn('Full conditional covariance was not positive definite.')\n            return\n\n        # Update value of f.\n        self.f_eval.value = m_step+np.dot(sig_step,np.random.normal(size=sig_step.shape[1])).view(np.ndarray).ravel()\n        # Propose the rest of the field from its conditional prior.\n        self.f.rand()            ", "meta": {"hexsha": "f3dc3dd8495dcd07802b80359ac42a625cb05614", "size": 7397, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymc/gp/step_methods.py", "max_stars_repo_name": "matthew-brett/pymc", "max_stars_repo_head_hexsha": "3a31613f056e7993a449d89bafef5fdaa40d47e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-12-03T09:42:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T19:23:29.000Z", "max_issues_repo_path": "pymc/gp/step_methods.py", "max_issues_repo_name": "matthew-brett/pymc", "max_issues_repo_head_hexsha": "3a31613f056e7993a449d89bafef5fdaa40d47e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-09-27T02:00:41.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-27T02:15:32.000Z", "max_forks_repo_path": "pymc/gp/step_methods.py", "max_forks_repo_name": "matthew-brett/pymc", "max_forks_repo_head_hexsha": "3a31613f056e7993a449d89bafef5fdaa40d47e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-10-27T13:27:32.000Z", "max_forks_repo_forks_event_max_datetime": "2017-10-27T13:27:32.000Z", "avg_line_length": 36.2598039216, "max_line_length": 170, "alphanum_fraction": 0.6303906989, "include": true, "reason": "import numpy", "num_tokens": 1788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.3522017820478897, "lm_q1q2_score": 0.1966437675471579}}
{"text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n   This file belong to https://github.com/snolfi/evorobotpy\n   and has been written by Stefano Nolfi and Paolo Pagliuca, stefano.nolfi@istc.cnr.it, paolo.pagliuca@istc.cnr.it\n   salimans.py include an implementation of the OpenAI-ES algorithm described in\n   Salimans T., Ho J., Chen X., Sidor S & Sutskever I. (2017). Evolution strategies as a scalable alternative to reinforcement learning. arXiv:1703.03864v2\n   requires es.py, policy.py, and evoalgo.py \n\"\"\"\n\nimport numpy as np\nfrom numpy import zeros, ones, dot, sqrt\nimport math\nimport time\nfrom evoalgo import EvoAlgo\nfrom utils import ascendent_sort\nimport sys\nimport os\nimport configparser\n\n# Parallel implementation of Open-AI-ES algorithm developed by Salimans et al. (2017)\n# the workers evaluate a fraction of the population in parallel\n# the master post-evaluate the best sample of the last generation and eventually update the input normalization vector\n\nclass Algo(EvoAlgo):\n    def __init__(self, env, policy, seed, fileini, filedir):\n        EvoAlgo.__init__(self, env, policy, seed, fileini, filedir)\n\n    def loadhyperparameters(self):\n\n        if os.path.isfile(self.fileini):\n\n            config = configparser.ConfigParser()\n            config.read(self.fileini)\n            self.maxsteps = 1000000\n            self.stepsize = 0.01\n            self.batchSize = 20\n            self.noiseStdDev = 0.02\n            self.wdecay = 0\n            self.symseed = 1\n            self.saveeach = 60\n            options = config.options(\"ALGO\")\n            for o in options:\n                found = 0\n                if o == \"maxmsteps\":\n                    self.maxsteps = config.getint(\"ALGO\",\"maxmsteps\") * 1000000\n                    found = 1\n                if o == \"stepsize\":\n                    self.stepsize = config.getfloat(\"ALGO\",\"stepsize\")\n                    found = 1\n                if o == \"noisestddev\":\n                    self.noiseStdDev = config.getfloat(\"ALGO\",\"noiseStdDev\")\n                    found = 1\n                if o == \"samplesize\":\n                    self.batchSize = config.getint(\"ALGO\",\"sampleSize\")\n                    found = 1\n                if o == \"wdecay\":\n                    self.wdecay = config.getint(\"ALGO\",\"wdecay\")\n                    found = 1\n                if o == \"symseed\":\n                    self.symseed = config.getint(\"ALGO\",\"symseed\")\n                    found = 1\n                if o == \"saveeach\":\n                    self.saveeach = config.getint(\"ALGO\",\"saveeach\")\n                    found = 1\n\n                if found == 0:\n                    print(\"\\033[1mOption %s in section [ALGO] of %s file is unknown\\033[0m\" % (o, filename))\n                    print(\"available hyperparameters are: \")\n                    print(\"maxmsteps [integer]       : max number of (million) steps (default 1)\")\n                    print(\"stepsize [float]          : learning stepsize (default 0.01)\")\n                    print(\"samplesize [int]          : popsize/2 (default 20)\")\n                    print(\"noiseStdDev [float]       : samples noise (default 0.02)\")\n                    print(\"wdecay [0/2]              : weight decay (default 0), 1 = L1, 2 = L2\")\n                    print(\"symseed [0/1]             : same environmental seed to evaluate symmetrical samples [default 1]\")\n                    print(\"saveeach [integer]        : save file every N minutes (default 60)\")\n\n                    sys.exit()\n        else:\n            print(\"\\033[1mERROR: configuration file %s does not exist\\033[0m\" % (self.fileini))\n    \n\n\n    def setProcess(self):\n        self.loadhyperparameters()               # load hyperparameters\n        self.center = np.copy(self.policy.get_trainable_flat())  # the initial centroid\n        self.nparams = len(self.center)          # number of adaptive parameters\n        self.cgen = 0                            # currrent generation\n        self.samplefitness = zeros(self.batchSize * 2) # the fitness of the samples\n        self.samples = None                      # the random samples\n        self.m = zeros(self.nparams)             # Adam: momentum vector \n        self.v = zeros(self.nparams)             # Adam: second momentum vector (adam)\n        self.epsilon = 1e-08                     # Adam: To avoid numerical issues with division by zero...\n        self.beta1 = 0.9                         # Adam: beta1\n        self.beta2 = 0.999                       # Adam: beta2\n        self.bestgfit = -99999999                # the best generalization fitness\n        self.bfit = 0                            # the fitness of the best sample\n        self.gfit = 0                            # the postevaluation fitness of the best sample of last generation\n        self.rs = None                           # random number generator\n        self.inormepisodes = self.batchSize * 2 * self.policy.ntrials / 100.0 # number of normalization episode for generation (1% of generation episodes)\n        self.tnormepisodes = 0.0                 # total epsidoes in which normalization data should be collected so far\n        self.normepisodes = 0                    # numer of episodes in which normalization data has been actually collected so far\n        self.normalizationdatacollected = False  # whether we collected data for updating the normalization vector\n\n    def savedata(self):\n        self.save()             # save the best agent so far, the best postevaluated agent so far, and progress data across generations\n        fname = self.filedir + \"/S\" + str(self.seed) + \".fit\"\n        fp = open(fname, \"w\")   # save summary\n        fp.write('Seed %d (%.1f%%) gen %d msteps %d bestfit %.2f bestgfit %.2f bestsam %.2f avgfit %.2f paramsize %.2f \\n' %\n             (self.seed, self.steps / float(self.maxsteps) * 100, self.cgen, self.steps / 1000000, self.bestfit, self.bestgfit, self.bfit, self.avgfit, self.avecenter))\n        fp.close()\n \n    def evaluate(self):\n        cseed = self.seed + self.cgen * self.batchSize  # Set the seed for current generation (master and workers have the same seed)\n        self.rs = np.random.RandomState(cseed)\n        self.samples = self.rs.randn(self.batchSize, self.nparams)\n        self.cgen += 1\n\n        # evaluate samples\n        candidate = np.arange(self.nparams, dtype=np.float64)\n        for b in range(self.batchSize):               \n            for bb in range(2):\n                if (bb == 0):\n                    candidate = self.center + self.samples[b,:] * self.noiseStdDev\n                else:\n                    candidate = self.center - self.samples[b,:] * self.noiseStdDev\n                self.policy.set_trainable_flat(candidate)\n                self.policy.nn.normphase(0) # normalization data is collected during the post-evaluation of the best sample of he previous generation\n                eval_rews, eval_length = self.policy.rollout(self.policy.ntrials, seed=(self.seed + (self.cgen * self.batchSize) + b))\n                self.samplefitness[b*2+bb] = eval_rews\n                self.steps += eval_length\n\n        fitness, self.index = ascendent_sort(self.samplefitness)       # sort the fitness\n        self.avgfit = np.average(fitness)                         # compute the average fitness                   \n\n        self.bfit = fitness[(self.batchSize * 2) - 1]\n        bidx = self.index[(self.batchSize * 2) - 1]  \n        if ((bidx % 2) == 0):                                     # regenerate the genotype of the best samples\n            bestid = int(bidx / 2)\n            self.bestsol = self.center + self.samples[bestid] * self.noiseStdDev  \n        else:\n            bestid = int(bidx / 2)\n            self.bestsol = self.center - self.samples[bestid] * self.noiseStdDev\n\n        self.updateBest(self.bfit, self.bestsol)                  # Stored if it is the best obtained so far \n                \n        # postevaluate best sample of the last generation\n        # in openaiesp.py this is done the next generation, move this section before the section \"evaluate samples\" to produce identical results\n        gfit = 0\n        if self.bestsol is not None:\n            self.policy.set_trainable_flat(self.bestsol)\n            self.tnormepisodes += self.inormepisodes\n            for t in range(self.policy.nttrials):\n                if self.policy.normalize == 1 and self.normepisodes < self.tnormepisodes:\n                    self.policy.nn.normphase(1)\n                    self.normepisodes += 1  # we collect normalization data\n                    self.normalizationdatacollected = True\n                else:\n                    self.policy.nn.normphase(0)\n                eval_rews, eval_length = self.policy.rollout(1, seed=(self.seed + 100000 + t))\n                gfit += eval_rews               \n                self.steps += eval_length\n            gfit /= self.policy.nttrials    \n            self.updateBestg(gfit, self.bestsol)\n\n\n    def optimize(self):\n            \n        popsize = self.batchSize * 2                              # compute a vector of utilities [-0.5,0.5]\n        utilities = zeros(popsize)\n        for i in range(popsize):\n            utilities[self.index[i]] = i\n        utilities /= (popsize - 1)\n        utilities -= 0.5\n        \n        weights = zeros(self.batchSize)                           # Assign the weights (utility) to samples on the basis of their fitness rank\n        for i in range(self.batchSize):\n            idx = 2 * i\n            weights[i] = (utilities[idx] - utilities[idx + 1])    # merge the utility of symmetric samples\n\n        g = 0.0\n        i = 0\n        while i < self.batchSize:                                 # Compute the gradient (the dot product of the samples for their utilities)\n            gsize = -1\n            if self.batchSize - i < 500:                          # if the popsize is larger than 500, compute the gradient for multiple sub-populations\n                gsize = self.batchSize - i\n            else:\n                gsize = 500\n            g += dot(weights[i:i + gsize], self.samples[i:i + gsize,:]) \n            i += gsize\n        g /= popsize                                              # normalize the gradient for the popsize\n        \n        if self.wdecay == 1:\n            globalg = -g + 0.005 * self.center                    # apply weight decay\n        else:\n            globalg = -g\n\n        # adam stochastic optimizer\n        a = self.stepsize * sqrt(1.0 - self.beta2 ** self.cgen) / (1.0 - self.beta1 ** self.cgen)\n        self.m = self.beta1 * self.m + (1.0 - self.beta1) * globalg\n        self.v = self.beta2 * self.v + (1.0 - self.beta2) * (globalg * globalg)\n        dCenter = -a * self.m / (sqrt(self.v) + self.epsilon)\n        \n        self.center += dCenter                                    # move the center in the direction of the momentum vectors\n        self.avecenter = np.average(np.absolute(self.center))      \n\n\n    def run(self):\n\n        self.setProcess()                           # initialize class variables\n        start_time = time.time()\n        last_save_time = start_time\n        elapsed = 0\n        self.steps = 0\n        print(\"Salimans: seed %d maxmsteps %d batchSize %d stepsize %lf noiseStdDev %lf wdecay %d symseed %d nparams %d\" % (self.seed, self.maxsteps / 1000000, self.batchSize, self.stepsize, self.noiseStdDev, self.wdecay, self.symseed, self.nparams))\n\n        while (self.steps < self.maxsteps):\n\n            \n            self.evaluate()                           # evaluate samples  \n            \n            self.optimize()                           # estimate the gradient and move the centroid in the gradient direction\n\n            self.stat = np.append(self.stat, [self.steps, self.bestfit, self.bestgfit, self.bfit, self.avgfit, self.avecenter])  # store performance across generations\n\n            if ((time.time() - last_save_time) > (self.saveeach * 60)):\n                self.savedata()                       # save data on files\n                last_save_time = time.time()\n\n            if self.normalizationdatacollected:\n                self.policy.nn.updateNormalizationVectors()  # update the normalization vectors with the new data collected\n                self.normalizationdatacollected = False\n\n            print('Seed %d (%.1f%%) gen %d msteps %d bestfit %.2f bestgfit %.2f bestsam %.2f avg %.2f weightsize %.2f' %\n                      (self.seed, self.steps / float(self.maxsteps) * 100, self.cgen, self.steps / 1000000, self.bestfit, self.bestgfit, self.bfit, self.avgfit, self.avecenter))\n\n        self.savedata()                           # save data at the end of evolution\n\n        # print simulation time\n        end_time = time.time()\n        print('Simulation time: %dm%ds ' % (divmod(end_time - start_time, 60)))\n\n", "meta": {"hexsha": "651fcb74b3801ffa34d37787b37ae0c4640fd65a", "size": 12778, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week-04/evorobotpy2/bin/openaies.py", "max_stars_repo_name": "mhd-medfa/BCR22", "max_stars_repo_head_hexsha": "9f892928f293bb9c2c7152e82713f976d8cd0485", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Week-04/evorobotpy2/bin/openaies.py", "max_issues_repo_name": "mhd-medfa/BCR22", "max_issues_repo_head_hexsha": "9f892928f293bb9c2c7152e82713f976d8cd0485", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week-04/evorobotpy2/bin/openaies.py", "max_forks_repo_name": "mhd-medfa/BCR22", "max_forks_repo_head_hexsha": "9f892928f293bb9c2c7152e82713f976d8cd0485", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-03T17:27:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T17:27:47.000Z", "avg_line_length": 52.368852459, "max_line_length": 250, "alphanum_fraction": 0.5585381124, "include": true, "reason": "import numpy,from numpy", "num_tokens": 2981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.19664376237036085}}
{"text": "import copy\nimport numpy as np\nimport scipy as sp\nfrom scipy import sparse\nfrom mesohops.dynamics.eom_functions import operator_expectation\nfrom mesohops.util.physical_constants import hbar\nfrom mesohops.util.exceptions import UnsupportedRequest\n\n\n__title__ = \"Basis Class\"\n__author__ = \"D. I. G. Bennett\"\n__version__ = \"1.0\"\n\n\nclass HopsBasis(object):\n    \"\"\"\n    Every HOPS calculation is defines by the HopsSystem, HopsHierarchy, and HopsEOM\n    classes (and their associated parameters). These form the basis set for the\n    calculation. HopsBasis is the class that contains all of these sub-classes and\n    mediates the way the HopsTrajectory will interact with them.\n    \"\"\"\n\n    def __init__(self, system, hierarchy, eom):\n        \"\"\"\n        INPUTS:\n        -------\n        1. system: dictionary of user inputs\n            [see hops_system.py]\n            a. HAMILTONIAN\n            b. GW_SYSBATH\n            c. CORRELATION_FUNCTION_TYPE\n            d. LOPERATORS\n            e. CORRELATION_FUNCTION\n        2. hierarchy_parameters: dictionary of user inputs\n            [see hops_hierarchy.py]\n            f. MAXHIER\n            g. TERMINATOR\n            h. STATIC_FILTERS\n        3. eom_parameters: dictionary of user inputs\n            [see hops_eom.py]\n            i. TIME_DEPENDENCE\n            j. EQUATION_OF_MOTION\n            k. ADAPTIVE_H\n            l. ADAPTIVE_S\n            m. DELTA_H\n            n. DELTA_S\n\n        RETURNS\n        -------\n        None\n        \"\"\"\n        self.system = system\n        self.hierarchy = hierarchy\n        self.eom = eom\n\n    def initialize(self, psi_0):\n        \"\"\"\n        This function initializes the hierarchy and equations of motion classes\n        so that everything is prepared for integration. It returns the\n        dsystem_dt function to be used in the integrator.\n\n        PARAMETERS\n        ----------\n        1. psi_0 : np.array\n                  the initial wave function\n\n        RETURNS\n        -------\n        1. dsystem_dt : function\n                       this is the core function for calculating the time-evolution of\n                       the wave function\n        \"\"\"\n        self.hierarchy.initialize(self.adaptive_h)\n        self.system.initialize(self.adaptive_s, psi_0)\n        dsystem_dt = self.eom._prepare_derivative(self.system, self.hierarchy)\n\n        return dsystem_dt\n\n    def define_basis(self, Φ, delta_t, z_step):\n        \"\"\"\n        This is the function that determines what basis is needed for a given\n        full hierarchy (Φ) in order to construct an approximate derivative with\n        error below the specified threshold.\n\n        PARAMETERS\n        ----------\n        1. Φ : np.array\n               the current full hierarchy\n        2. delta_t : float\n                     the timestep for the calculation\n        3. z_step : list\n                    the list of noise terms (compressed) for the next timestep\n\n        RETURNS\n        -------\n        1. state_update :\n            a. list_state_new : list\n                               list of states in the new basis (S_1)\n            b. list_state_stable : list\n                                   list of stable states in the new basis (S_S)\n            c. list_state_bound : list\n                                  list of boundary states in the new basis (S_B)\n        2. hierarchy_update :\n            d. list_aux_new : list\n                              list of auxiliaries in new basis (H_1)\n            e. list_stable_aux : list\n                                 list of stable auxiliaries in the new basis (H_S)\n            f. list_aux_bound : list\n                                list of boundary auxiliaries in the new basis (H_B)\n\n        \"\"\"\n        # ==========================================\n        # =======      Calculate Updates      ======\n        # ==========================================\n\n        # Calculate New Hierarchy List\n        # ----------------------------\n        if self.adaptive_h:\n            list_aux_stable, list_aux_bound = self._check_hierarchy_list(\n                Φ, delta_t, z_step\n            )\n            list_aux_new = list(set(list_aux_stable) | set(list_aux_bound))\n            list_index_stable_aux = [\n                self.hierarchy._aux_index(aux) for aux in list_aux_stable\n            ]\n            list_index_stable_aux.sort()\n        else:\n            list_aux_new = self.hierarchy.auxiliary_list\n            list_aux_stable = self.hierarchy.auxiliary_list\n            list_aux_bound = []\n            list_index_stable_aux = np.arange(len(self.hierarchy.auxiliary_list))\n            E2_flux = None\n\n        # Calculate New State List\n        # ------------------------\n        if self.adaptive_s:\n            list_state_stable, list_state_bound = self._check_state_list(\n                Φ, delta_t, z_step, list_index_stable_aux\n            )\n            list_state_new = list(set(list_state_stable) | set(list_state_bound))\n            list_state_stable.sort()\n        else:\n            list_state_new = list(set(self.system.state_list))\n            list_state_bound = []\n            list_state_stable = list_state_new\n\n        return [\n            (list_state_new, list_state_stable, list_state_bound),\n            (list_aux_new, list_aux_stable, list_aux_bound),\n        ]\n\n    def update_basis(self, Φ, state_update, aux_update):\n        \"\"\"\n        This function updates the derivative function and full hierarchy vector (Φ) for the\n        new basis (hierarchy and/or system).\n\n        PARAMETERS\n        ----------\n        1. Φ : np.array\n               the current full hierarchy\n        2. state_update : list\n                          list of list containing list_state_new, list_stable_state, and list_add_state\n        3. aux_update : list\n                        list of list containing list_aux_new, list_stable_aux, and list_add_aux\n\n        RETURNS\n        -------\n        1. Φ_new : np.array\n                   the updated full hierarchy\n        2. dsystem_dt : function\n                        the updated derivative function\n        \"\"\"\n        # Unpack input values\n        # ===================\n        (list_state_new, list_stable_state, list_add_state) = state_update\n        (list_aux_new, list_stable_aux, list_add_aux) = aux_update\n\n        # Update State List\n        # =================\n        flag_update = False\n        if set(list_state_new) != set(self.system.state_list):\n            flag_update = True\n            list_state_previous = copy.deepcopy(self.system.state_list)\n            list_absindex_l2_old = copy.deepcopy(self.system.list_absindex_L2)\n            self.system.state_list = np.array(list_state_new)\n        else:\n            list_state_previous = self.system.state_list\n            list_absindex_l2_old = self.system.list_absindex_L2\n\n        # Update Hierarchy List\n        # =====================\n        if set(list_aux_new) != set(self.hierarchy.auxiliary_list):\n            flag_update = True\n            # Update Auxiliary List\n            list_old_aux = self.hierarchy.auxiliary_list\n            self.hierarchy.auxiliary_list = list_aux_new\n        else:\n            list_old_aux = self.hierarchy.auxiliary_list\n\n        # Update state of calculation for new basis\n        # =========================================\n        if flag_update:\n\n            # Define permutation matrix from old basis --> new basis\n            # ------------------------------------------------------\n            permute_aux_row = []\n            permute_aux_col = []\n            nstate_old = len(list_state_previous)\n            list_index_old_stable_state = np.array(\n                [\n                    i_rel\n                    for (i_rel, i_abs) in enumerate(list_state_previous)\n                    if i_abs in list_stable_state\n                ]\n            )\n            list_index_new_stable_state = np.array(\n                [\n                    i_rel\n                    for (i_rel, i_abs) in enumerate(self.system.state_list)\n                    if i_abs in list_stable_state\n                ]\n            )\n\n            for aux in list_stable_aux:\n                permute_aux_row.extend(\n                    self.hierarchy._aux_index(aux) * self.n_state\n                    + list_index_new_stable_state\n                )\n                permute_aux_col.extend(\n                    list_old_aux.index(aux) * nstate_old + list_index_old_stable_state\n                )\n\n            # Update phi\n            # ----------\n            Φ_new = np.zeros(self.n_hier * self.n_state, dtype=np.complex128)\n            Φ_new[permute_aux_row] = Φ[permute_aux_col]\n\n            # Update dsystem_dt\n            # -----------------\n            dsystem_dt = self.eom._prepare_derivative(\n                self.system,\n                self.hierarchy,\n                list_stable_aux,\n                list_add_aux,\n                list_stable_state,\n                list_absindex_l2_old,\n                len(list_old_aux) * nstate_old,\n                [permute_aux_row, permute_aux_col],\n                update=True,\n            )\n\n            return (Φ_new, dsystem_dt)\n        else:\n            return (Φ, self.eom.dsystem_dt)\n\n    def _check_state_list(self, Φ, delta_t, z_step, list_index_aux_stable):\n        \"\"\"\n        This is a function that determines the states which should be\n        included in the adaptive integration for the next time point.\n\n        PARAMETERS\n        ----------\n        1. Φ : np.array\n               the current full hierarchy\n        2. delta_t : float\n                     the timestep for the calculation\n        3. z_step : list\n                    the list of noise terms (compressed) for the next timestep\n        4. list_index_aux_stable : list\n                                   a list of relative indices for the stable auxiliaries\n\n        RETURNS\n        -------\n        1. list_state_stable : list\n                               list of stable states (absolute state index, S_S)\n        2. list_state_boundary : list\n                                 a list of the boundary states (absolute state index, S_B)\n        \"\"\"\n        # Define Constants\n        # ----------------\n        delta_state = self.delta_s  # * np.linalg.norm(Φ)\n\n        # CONSTRUCT STABLE STATE (S_S)\n        # ============================\n\n        # Construct Error For Excluding Member of S0\n        # ------------------------------------------\n        error_by_state = self.error_stable_state(\n            Φ, delta_t, z_step, list_index_aux_stable\n        )\n\n        # Determine the Stable States (S_S = S_0 & S_1)\n        # ---------------------------------------------\n        list_index_stable, list_state_stable = self._determine_basis_from_list(\n            error_by_state, delta_state / 2, self.system.state_list\n        )\n\n        # CONSTRUCT BOUNDARY STATE (S_B)\n        # ==============================\n\n        # Establish the error available for the boundary states\n        # -----------------------------------------------------\n        stable_error = np.sqrt(\n            np.max([\n                np.sum(error_by_state ** 2) - np.sum(error_by_state[list_index_stable] ** 2),\n                0])\n        )\n        bound_error = delta_state - stable_error\n\n        # Construct Error for Excluding Member of S0^C\n        # --------------------------------------------\n        list_index_nonzero, list_error_nonzero = self.error_boundary_state(\n            Φ, list_index_stable, list_index_aux_stable\n        )\n\n        # Determine Boundary States\n        # -------------------------\n        if len(list_error_nonzero) > 0:\n            _, list_state_boundary = self._determine_basis_from_list(\n                list_error_nonzero, bound_error, list_index_nonzero\n            )\n        else:\n            list_state_boundary = []\n\n        # Check for overlap with populated states\n        # ---------------------------------------\n        list_state_boundary = list(\n            set(list_state_boundary) - set(self.system.state_list)\n        )\n        list_state_boundary.sort()\n\n        return (\n            np.array(list_state_stable, dtype=np.int),\n            np.array(list_state_boundary, dtype=np.int),\n        )\n\n    def _check_hierarchy_list(self, Φ, delta_t, z_step):\n        \"\"\"\n        This is a function that determines the auxiliaries which should be\n        included in the adaptive integration for the next time point.\n\n        PARAMETERS\n        ----------\n        1. Φ : np.array\n               the current full hierarchy\n        2. delta_t : float\n                     the timestep for the calculation\n        3. z_step : list\n                    the list of noise terms (compressed) for the next timestep\n\n        RETURNS\n        -------\n        1. list_aux_stable : list\n                             a list of the stable auxiliaries (H_S)\n        2. list_aux_boundary : list\n                               a list of auxiliaries that share a boundary with stable\n                               auxiliaries (H_B)\n        \"\"\"\n        # Define Constants\n        # ----------------\n        delta_hier = self.delta_h  # * np.linalg.norm(Φ)\n\n        # CONSTRUCT STABLE HIERARCHY\n        # ==========================\n\n        # Construct Error For Excluding Member of H0\n        # ------------------------------------------\n        error_by_aux, list_e2_kflux = self.hier_stable_error(Φ, delta_t, z_step)\n\n        # Determine the Stable Auxiliaries (H_S = H_0 & H_1)\n        # --------------------------------------------------\n        list_index_stable, list_aux_stable = self._determine_basis_from_list(\n            error_by_aux, delta_hier / 2, self.hierarchy.auxiliary_list\n        )\n\n        # CONSTRUCT BOUNDARY HIERARCHY\n        # ============================\n\n        # Establish the error available for the boundary auxiliaries\n        # ----------------------------------------------------------\n        stable_error = np.sqrt(\n            np.max([\n                np.sum(error_by_aux ** 2) - np.sum(error_by_aux[list_index_stable] ** 2),\n                0])\n        )\n        bound_error = delta_hier - stable_error\n\n        # Construct Error For Excluding Members of H0^C\n        # ---------------------------------------------\n        E2_flux_up = list_e2_kflux[0][:, list_index_stable]\n        E2_flux_down = list_e2_kflux[1][:, list_index_stable]\n\n        # Determine the Boundary Auxiliaries (H_B = H0^C & H_1)\n        # -----------------------------------------------------\n        list_aux_up, list_aux_down = self._determine_boundary_hier(\n            [E2_flux_up, E2_flux_down], list_index_stable, bound_error\n        )\n\n        # Check Boundary Set For Duplication\n        # ----------------------------------\n        # NOTE: Theoretically, the boundary should not contain any members of H0, but\n        #       when we implemented that in practice it resulted in a huge explosion\n        #       of the number of inch wormsteps that were required.\n        list_aux_boundary = list(\n            (set(list_aux_up) | set(list_aux_down)) - set(self.hierarchy.auxiliary_list)\n        )\n\n        # Filter Boundary Set for Auxiliaries That Are Not Part of H_T\n        # ------------------------------------------------------------\n        if len(list_aux_boundary) > 0:\n            list_aux_boundary = self.hierarchy.filter_aux_list(list_aux_boundary)\n        return list_aux_stable, list_aux_boundary\n\n    def _determine_boundary_hier(\n        self, list_e2_kflux, list_index_aux_stable, bound_error\n    ):\n        \"\"\"\n        This function determines the set of boundary auxiliaries for the next time step\n\n        PARAMETERS\n        ----------\n        1. list_e2_kflux : list\n                           a list of list containing the error values for the flux up\n                           and flux down terms\n        2. list_index_aux_stable : list\n                                   a list of the indices for stable auxiliaries\n        3. bound_error : float\n                         the boundary error value\n\n        RETURNS\n        -------\n        1. list_aux_up : list\n                         a list of the flux up auxiliaries\n        2. list_aux_down : list\n                           a list of the flux down auxiliaries\n        \"\"\"\n        # Construct constants\n        # -------------------\n        E2_flux_up = list_e2_kflux[0]\n        E2_flux_down = list_e2_kflux[1]\n\n        # Find the error threshold for edge auxiliaries\n        # ---------------------------------------------\n        E1_nonzero_flux = E2_flux_up[E2_flux_up != 0]\n        sorted_error = np.sort(\n            np.append(E1_nonzero_flux, E2_flux_down[E2_flux_down != 0])\n        )\n        error_thresh = self._determine_error_thresh(sorted_error, bound_error)\n\n        # Loop over residual fluxes to identify boundary auxiliaries\n        # ----------------------------------------------------------\n        list_aux_up = [\n            self.hierarchy.auxiliary_list[list_index_aux_stable[i_aux]].e_step(\n                self.system.list_absindex_mode[i_mode_rel], 1\n            )\n            for (i_mode_rel, i_aux) in zip(*np.where(E2_flux_up > error_thresh))\n        ]\n\n        list_aux_down = [\n            self.hierarchy.auxiliary_list[list_index_aux_stable[i_aux]].e_step(\n                self.system.list_absindex_mode[i_mode_rel], -1\n            )\n            for (i_mode_rel, i_aux) in zip(*np.where(E2_flux_down > error_thresh))\n        ]\n        return (list_aux_up, list_aux_down)\n\n    def _determine_basis_from_list(self, error_by_member, max_error, list_member):\n        \"\"\"\n        This function determines the members of a list that must be kept in order\n        for the total error (terms that are dropped) to be below the max_error value.\n\n        PARAMETERS\n        ----------\n        1. error_by_member : np.array\n                             a list of error values\n        2. max_error : float\n                       the maximum error value\n        3. list_member : np.array\n                         a list of members\n\n        RETURNS\n        -------\n        1. list_index : np.array\n                        a list of indices for the members\n        2. list_new_member : list\n                             a list of the members\n        \"\"\"\n        error_thresh = self._determine_error_thresh(np.sort(error_by_member), max_error)\n        list_index = np.where(error_by_member > error_thresh)[0]\n        list_new_member = [list_member[i_aux] for i_aux in list_index]\n        return (list_index, list_new_member)\n\n    @staticmethod\n    def _determine_error_thresh(sorted_error, max_error):\n        \"\"\"\n        This function determines which error value becomes the error threshold such\n        that the sum of all errors below the threshold remains less then max_error.\n\n        PARAMETERS\n        ----------\n        1. sorted_error : np.array\n                          a list of error values\n        2. max_error : float\n                       the maximum error value\n\n        RETURNS\n        -------\n        3. error_thresh : float\n                          the error value at which the threshold is established\n\n        \"\"\"\n        index_thresh = np.argmax(np.sqrt(np.cumsum(sorted_error ** 2)) > max_error)\n\n        if index_thresh > 0:\n            error_thresh = sorted_error[index_thresh - 1]\n        else:\n            error_thresh = 0.0\n\n        return error_thresh\n\n    def error_boundary_state(self, Φ, list_index_stable, list_index_aux_stable):\n        \"\"\"\n        This function determines the error associated with neglecting flux into n not\n        a member of S_t. This corresponds to equations 43-45 in arXiv:2008.06496\n\n        PARAMETERS\n        ----------\n        1. Φ : np.array\n               the current full hierarchy vector\n        2. list_index_stable : list\n                               a list of the stable states\n        3. list_index_aux_stable : list\n                                   a list relative indices for the stable auxiliaries\n\n        RETURNS\n        -------\n        1. list_index_nonzero : list\n                                a list of the nonzero state boundary indices\n        2. list_error_nonzero : list\n                                a list of the nonzero state boundary error values\n        \"\"\"\n        if len(list_index_stable) < self.system.param[\"NSTATES\"]:\n            # Remove aux components from H0\\H1\n            # -------------------------------------\n            C2_phi = np.zeros([self.n_state, self.n_hier], dtype=np.complex128)\n            C2_phi[np.ix_(list_index_stable, list_index_aux_stable)] = np.array(\n                Φ\n            ).reshape([self.n_state, self.n_hier], order=\"F\")[\n                np.ix_(list_index_stable, list_index_aux_stable)\n            ]\n\n            # Construct Hamiltonian\n            # ---------------------------------------------------------\n            list_s0 = np.array(self.system.state_list)\n\n            # First construct ST<--S0 Hamiltonian\n            H2_sparse_hamiltonian = self.system.param[\"SPARSE_HAMILTONIAN\"][:, list_s0]\n\n            # Remove components that map S0<--S0\n            H2_sparse_subset = sparse.coo_matrix(\n                H2_sparse_hamiltonian[np.ix_(list_s0, range(len(list_s0)))]\n            )\n            H2_removal = sparse.csc_matrix(\n                (\n                    H2_sparse_subset.data,\n                    (\n                        list_s0[H2_sparse_subset.row],\n                        np.arange(len(list_s0))[H2_sparse_subset.col],\n                    ),\n                ),\n                shape=H2_sparse_hamiltonian.shape,\n            )\n            H2_sparse_hamiltonian = H2_sparse_hamiltonian - H2_removal\n\n            # Determine Boundary States\n            # -------------------------\n            C2_phi_deriv = abs(\n                H2_sparse_hamiltonian @ sparse.csc_matrix(C2_phi / hbar)\n            ).power(2)\n            C1_sum_deriv = np.sum(C2_phi_deriv, axis=1)\n            return (\n                C1_sum_deriv.nonzero()[0],\n                np.sqrt(np.array(C1_sum_deriv[C1_sum_deriv.nonzero()])[0]),\n            )\n\n        else:\n            return [], []\n\n    def error_stable_state(self, Φ, delta_t, z_step, list_index_aux_stable):\n        \"\"\"\n        This function finds the total error associated with neglecting n in the state\n        basis S_t. This includes the error associated with deleting a state from the basis,\n        the error associated with losing all flux into a state, and the error associated\n        with losing all flux out of a state. This corresponds to equations 37-42 in\n        arXiv:2008.06496\n\n\n        PARAMETERS\n        ----------\n        1. Φ : np.array\n               the current full hierarchy vector\n        2. delta_t : float\n                     the timestep for the calculation\n        3. z_step : list\n                    the list of noise terms (compressed) for the next timestep\n        4. list_index_aux_stable : list\n                                   a list relative indices for the stable auxiliaries (A_p)\n\n        RETURNS\n        -------\n        1. error : np.array\n                   list of error associated with removing each state\n        \"\"\"\n        M2_state_from_mode = np.zeros([self.n_state, self.system.n_hmodes])\n        M2_state_from_mode[\n            self.system.list_state_indices_by_hmode[:, 0],\n            np.arange(np.shape(self.system.list_state_indices_by_hmode)[0]),\n        ] = 1\n\n        # Construct the error terms\n        # -------------------------\n        E2_deriv_state = self.error_deriv(Φ, z_step, list_index_aux_stable)[\n            :, list_index_aux_stable\n        ]\n        E2_deletion = self.error_deletion(Φ, delta_t)[:, list_index_aux_stable]\n        E1_state_flux = self.error_sflux_state(\n            Φ, list_index_aux_stable, self.system.state_list\n        )\n        E2_flux_down = self.error_flux_down(Φ, \"S\")[:, list_index_aux_stable]\n        E2_flux_up = self.error_flux_up(Φ)[:, list_index_aux_stable]\n        # Map flux_up error from mode to state space\n        E2_flux_up = np.sqrt(M2_state_from_mode @ E2_flux_up ** 2)\n\n        # Compress the error onto the state/mode axis\n        # -------------------------------------------\n        return np.sqrt(\n            np.sum(E2_deriv_state ** 2, axis=1)\n            + np.sum(E2_deletion ** 2, axis=1)\n            + np.sum(E2_flux_up ** 2, axis=1)\n            + np.sum(E2_flux_down ** 2, axis=1)\n            + E1_state_flux ** 2\n        )\n\n    def hier_stable_error(self, Φ, delta_t, z_step):\n        \"\"\"\n        This function finds the total error associated with removing k in A_t.\n        This corresponds to the sum of equations 29,30,31,33, and 34 in arXiv:2008.06496\n\n        PARAMETERS\n        ----------\n        1. Φ : np.array\n               the current full hierarchy vector\n        2. delta_t : float\n                     the timestep for the calculation\n        3. z_step : list\n                    the list of noise terms (compressed) for the next timestep\n\n        RETURNS\n        -------\n        1. error : np.array\n                   list of error associated with removing each auxiliary in A_t\n        2. E2_flux_up : np.array\n                        the error induced by neglecting flux from A_t (or A_p)\n                                to auxiliaries with lower summed index in A_t^C.\n        3. E2_flux_down : np.array\n                          the error induced by neglecting flux from A_t (or A_p)\n                                to auxiliaries with higher summed index in A_t^C.\n        \"\"\"\n        # Construct the error terms\n        # -------------------------\n        E2_deletion = self.error_deletion(Φ, delta_t)\n        E2_deriv_self = self.error_deriv(Φ, z_step)\n        E1_flux_state = self.error_sflux_hier(Φ, self.system.state_list)\n        E2_flux_up = self.error_flux_up(Φ)\n        E2_flux_down = self.error_flux_down(Φ, \"H\")\n\n        # Compress the error onto the aux axis\n        # ------------------------------------\n        return (\n            np.sqrt(\n                np.sum(E2_deriv_self ** 2, axis=0)\n                + np.sum(E2_deletion ** 2, axis=0)\n                + np.sum(E2_flux_down ** 2, axis=0)\n                + np.sum(E2_flux_up ** 2, axis=0)\n                + E1_flux_state\n            ),\n            [E2_flux_up, E2_flux_down],\n        )\n\n    def error_sflux_state(self, Φ, list_index_aux_stable, list_states):\n        \"\"\"\n        The error associated with losing all flux out of n in S_t. This flux always involves\n        changing the state index and, as a result, can be rewritten in terms of the -iH\n        component of the self-interaction. This corresponds to equation 38 and 39 in\n        arXiv:2008.06496\n\n        PARAMETERS\n        ----------\n        1. Φ : np.array\n               the current full hierarchy vector\n        2. list_index_aux_stable : list\n                                   a list relative indices for the stable auxiliaries (A_p)\n        3. list_states : list\n                         the list of current states (absolute index)\n\n        RETURNS\n        -------\n        1. E1_state_flux : array\n                           the error associated with flux out of each state in S_t\n        \"\"\"\n        C2_phi = np.asarray(Φ).reshape([self.n_state, self.n_hier], order=\"F\")[\n            :, list_index_aux_stable\n        ]\n        H2_sparse_hamiltonian = self.system.param[\"SPARSE_HAMILTONIAN\"][:, list_states]\n        H2_sparse_hamiltonian = H2_sparse_hamiltonian - sp.sparse.diags(\n            H2_sparse_hamiltonian.diagonal(0),\n            format=\"csc\",\n            shape=H2_sparse_hamiltonian.shape,\n        )\n        V1_norm_squared = np.array(\n            np.sum(np.abs(H2_sparse_hamiltonian).power(2), axis=0))[:, 0]\n        C1_norm_squared_by_state = np.sum(np.abs(C2_phi) ** 2, axis=1)\n        return np.sqrt(V1_norm_squared * C1_norm_squared_by_state) / hbar\n\n    def error_sflux_hier(self, Φ, list_s0):\n        \"\"\"\n        The error associated with losing all flux terms inside the kth auxiliary to\n        states not contained in S_t. This corresponds to equation 30 in arXiv:2008.06496\n\n\n        PARAMETERS\n        ----------\n        1. Φ : np.array\n               the current full hierarchy vector\n        2. list_s0 : list\n                     a list of the current states (absolute index)\n\n        RETURNS\n        -------\n        1. E2_flux_state : array\n                           the error introduced by losing flux within k from S_t to S_t^C\n                           for each k in A_t\n\n        \"\"\"\n        # Construct the 2D phi and sparse Hamiltonian\n        # -------------------------------------------\n        list_s0 = np.array(list_s0)\n        C2_phi = np.asarray(Φ).reshape([self.n_state, self.n_hier], order=\"F\")\n\n        H2_sparse_hamiltonian = self.system.param[\"SPARSE_HAMILTONIAN\"][:, list_s0]\n\n        # Remove the components of the Hamiltonian that map S0-->S0\n        # ---------------------------------------------------------\n        H2_sparse_subset = sparse.coo_matrix(\n            H2_sparse_hamiltonian[np.ix_(list_s0, range(len(list_s0)))]\n        )\n        H2_removal = sparse.csc_matrix(\n            (\n                H2_sparse_subset.data,\n                (\n                    list_s0[H2_sparse_subset.row],\n                    np.arange(len(list_s0))[H2_sparse_subset.col],\n                ),\n            ),\n            shape=H2_sparse_hamiltonian.shape,\n        )\n        H2_sparse_hamiltonian = H2_sparse_hamiltonian - H2_removal\n        D2_derivative_abs_sq = np.abs(\n            H2_sparse_hamiltonian @ sparse.csc_matrix(C2_phi) / hbar).power(2)\n        return np.sqrt(np.array(np.sum(D2_derivative_abs_sq, axis=0))[0])\n\n    def error_deriv(self, Φ, z_step, list_index_aux_stable=None):\n        \"\"\"\n        The error associated with losing all flux terms into the k auxiliary and n state,\n        where k is in A_t and n is in S_t. This corresponds to equation 29 in arXiv:2008.06496\n\n        PARAMETERS\n        ----------\n        1. Φ : np.array\n               The current full hierarchy vector\n        2. z_step : list\n                    the list of noise terms (compressed) for the next timestep\n        3. list_index_aux_stable : list\n                                   a list relative indices for the stable auxiliaries\n\n        RETURNS\n        -------\n        1. E2_del_phi : np.array\n                        the error associated with losing flux to a component (either\n                        hierarchy or state basis element) in H_t direct sum S_t\n        \"\"\"\n        if list_index_aux_stable is not None:\n            # Error arises for flux only out of the stable auxiliaries\n            # --------------------------------------------------------\n            Φ_stab = np.zeros(self.n_state * self.n_hier, dtype=np.complex128)\n            Φ_stab_v = Φ_stab.view().reshape([self.n_state, self.n_hier], order=\"F\")\n            Φ_stab_v[:, list_index_aux_stable] = Φ.view().reshape(\n                [self.n_state, self.n_hier], order=\"F\"\n            )[:, list_index_aux_stable]\n        else:\n            Φ_stab = Φ\n\n        list_avg_L2 = [\n            operator_expectation(L, Φ[: self.n_state]) for L in self.system.list_L2_coo\n        ]\n\n        P1_del_phi = (\n            self.eom.K2_k @ Φ_stab + self.eom.K2_kp1 @ Φ_stab + self.eom.K2_km1 @ Φ_stab\n        )\n\n        for j in range(len(self.system.list_absindex_L2)):\n            P1_del_phi += z_step[j] * self.eom.Z2_k[j] @ Φ_stab\n            P1_del_phi += np.conj(list_avg_L2[j]) * self.eom.Z2_kp1[j] @ Φ_stab\n\n        E2_del_phi = np.abs(\n            P1_del_phi.reshape([self.n_state, self.n_hier], order=\"F\") / hbar\n        )\n\n        return E2_del_phi\n\n    def error_deletion(self, Φ, delta_t):\n        \"\"\"\n        The error associated with setting the corresponding component of Phi to 0,\n        corresponding to equation 34 and 42 in arXiv:2008.06496\n\n        PARAMETERS\n        ----------\n        1. Φ : np.array\n               The current position of the full hierarchy vector\n        2. delta_t : float\n                     the timestep for the calculation\n\n        RETURNS\n        -------\n        1. E2_site_aux : np.array\n                         the error induced by removing components of Φ in A_t+S_t\n        \"\"\"\n\n        # Error arising from removing the auxiliary directly\n        # --------------------------------------------------\n        E2_site_aux = np.abs(\n            np.asarray(Φ).reshape([self.n_state, self.n_hier], order=\"F\") / delta_t\n        )\n\n        return E2_site_aux\n\n    def error_flux_down(self, Φ, type):\n        \"\"\"\n        A function that returns the error associated with neglecting flux from members of\n        A_t to auxiliaries in A_t^C that arise due to flux from higher auxiliaries to\n        lower auxiliaries. This corresponds to equation 33 and 41 in arXiv:2008.06496\n\n        PARAMETERS\n        ----------\n        1. Φ : np.array\n               The current state of the hierarchy\n        2. type: string\n                 'H' - Hierarchy type calculation\n                 'S' - State type calculation\n\n        RETURNS\n        -------\n        1. E2_flux_down_error : np.array\n                                the error induced by neglecting flux from A_t (or A_S)\n                                to auxiliaries with higher summed index in A_t^C.\n        \"\"\"\n        # Constants\n        # ---------\n        list_new_states = [\n            self.system.list_state_indices_by_hmode[:, 0] + i * self.n_state\n            for i in range(self.n_hier)\n        ]\n        list_modes_from_site_index = [\n            item for sublist in list_new_states for item in sublist\n        ]\n\n        # Reshape hierarchy (to matrix)\n        # ------------------------------\n        P2_pop_site = (\n            np.abs(np.asarray(Φ).reshape([self.n_state, self.n_hier], order=\"F\")) ** 2\n        )\n        P1_aux_norm = np.sqrt(np.sum(P2_pop_site, axis=0))\n        P2_modes_from0 = np.asarray(Φ)[\n            np.tile(self.system.list_state_indices_by_hmode[:, 0], self.n_hier)\n        ]\n        P2_pop_modes_down_1 = (np.abs(P2_modes_from0) ** 2).reshape(\n            [self.n_hmodes, self.n_hier], order=\"F\"\n        )\n        P1_modes = np.asarray(Φ)[list_modes_from_site_index]\n        P2_pop_modes = np.abs(P1_modes).reshape([self.n_hmodes, self.n_hier], order=\"F\")\n\n        # Get flux factors\n        # ----------------\n        G2_bymode = np.array(self.system.g)[\n            np.tile(list(range(self.n_hmodes)), self.n_hier)\n        ].reshape([self.n_hmodes, self.n_hier], order=\"F\")\n        W2_bymode = np.array(self.system.w)[\n            np.tile(list(range(self.n_hmodes)), self.n_hier)\n        ].reshape([self.n_hmodes, self.n_hier], order=\"F\")\n\n        F2_filter_aux = np.array(\n            [\n                [\n                    1 if aux[self.system.list_absindex_mode[i_mode_rel]] - 1 >= 0 else 0\n                    for aux in self.hierarchy.auxiliary_list\n                ]\n                for i_mode_rel in range(self.n_hmodes)\n            ]\n        )\n\n        if type == \"H\":\n            # Hierarchy Type Downward Flux\n            # ============================\n            E2_flux_down_error = (\n                np.real(\n                    F2_filter_aux\n                    * np.abs(G2_bymode / W2_bymode)\n                    * (P2_pop_modes_down_1 * P1_aux_norm[None, :] + P2_pop_modes)\n                )\n                / hbar\n            )\n        elif type == \"S\":\n            # State Type Downward Flux\n            # ========================\n            # Construct <L_m> term\n            # --------------------\n            E2_lm = np.tile(\n                np.sum(\n                    F2_filter_aux * np.abs(G2_bymode / W2_bymode) * P2_pop_modes_down_1,\n                    axis=0,\n                ),\n                [self.n_state, 1],\n            )\n\n            # Map Error to States\n            # -------------------\n            M2_state_from_mode = np.zeros([self.n_state, self.system.n_hmodes])\n            M2_state_from_mode[\n                self.system.list_state_indices_by_hmode[:, 0],\n                np.arange(np.shape(self.system.list_state_indices_by_hmode)[0]),\n            ] = 1\n            E2_flux_down_error = (\n                M2_state_from_mode\n                @ np.real(F2_filter_aux * np.abs(G2_bymode / W2_bymode) * P2_pop_modes)\n                / hbar\n            )\n            E2_flux_down_error += E2_lm * P2_pop_site / hbar\n        else:\n            E2_flux_down_error = 0\n            raise UnsupportedRequest(type, \"error_flux_down\")\n\n        return E2_flux_down_error\n\n    def error_flux_up(self, Φ):\n        \"\"\"\n        A function that returns the error associated with neglecting flux from members of\n        A_t to auxiliaries in A_t^C that arise due to flux from lower auxiliaries to\n        higher auxiliaries. This corresponds to equation 31 and 40 in arXiv:2008.06496\n\n        PARAMETERS\n        ----------\n        1. Φ : np.array\n               The current state of the hierarchy\n\n        RETURNS\n        -------\n        1. E2_flux_up_error : np. array\n                              the error induced by neglecting flux from A_t (or A_S)\n                              to auxiliaries with lower summed index in A_t^C.\n        \"\"\"\n        # Constants\n        # ---------\n        list_new_states = [\n            self.system.list_state_indices_by_hmode[:, 0] + i * self.n_state\n            for i in range(self.n_hier)\n        ]\n        list_modes_from_site_index = [\n            item for sublist in list_new_states for item in sublist\n        ]\n\n        # Reshape hierarchy (to matrix)\n        # ------------------------------\n        P1_modes = np.asarray(Φ)[list_modes_from_site_index]\n        P2_pop_modes = np.sqrt(np.abs(P1_modes) ** 2).reshape(\n            [self.n_hmodes, self.n_hier], order=\"F\"\n        )\n\n        # Get flux factors\n        # ----------------\n        W2_bymode = np.array(self.system.w)[\n            np.tile(list(range(self.n_hmodes)), self.n_hier)\n        ].reshape([self.n_hmodes, self.n_hier], order=\"F\")\n        K2aux_bymode = np.transpose(\n            np.array(\n                [\n                    aux.get_values(self.system.list_absindex_mode)\n                    for aux in self.hierarchy.auxiliary_list\n                ]\n            )\n        )\n\n        # Filter out fluxes beyond the hierarchy depth\n        # --------------------------------------------\n        filter_aux = np.array(\n            [\n                i_aux\n                for (i_aux, aux) in enumerate(self.hierarchy.auxiliary_list)\n                if np.sum(aux) + 1 > self.hierarchy.param[\"MAXHIER\"]\n            ]\n        )\n        F2_filter = np.ones([self.n_hmodes, self.n_hier])\n        if filter_aux.size > 0:\n            F2_filter[:, filter_aux] = 0\n\n        # Filter out Markovian Modes\n        # --------------------------\n        array2D_mark_param = np.array(\n            [\n                np.array(param)[self.system.list_absindex_mode]\n                for (name, param) in self.hierarchy.param[\"STATIC_FILTERS\"]\n                if name == \"Markovian\"\n            ]\n        )\n        if len(array2D_mark_param) > 0:\n            array_mark_param = np.any(array2D_mark_param, axis=0)\n            F2_filter_markov = np.ones([self.n_hmodes, self.n_hier])\n            F2_filter_markov[array_mark_param, 1:] = 0\n            F2_filter = F2_filter * F2_filter_markov\n\n        # Test upward fluxes\n        # ------------------\n        return F2_filter * np.abs(W2_bymode) * (1 + K2aux_bymode) * P2_pop_modes / hbar\n\n    @property\n    def n_hmodes(self):\n        return self.system.n_hmodes\n\n    @property\n    def n_state(self):\n        return self.system.size\n\n    @property\n    def n_hier(self):\n        return self.hierarchy.size\n\n    @property\n    def adaptive(self):\n        return self.eom.param[\"ADAPTIVE\"]\n\n    @property\n    def adaptive_h(self):\n        return self.eom.param[\"ADAPTIVE_H\"]\n\n    @property\n    def adaptive_s(self):\n        return self.eom.param[\"ADAPTIVE_S\"]\n\n    @property\n    def delta_h(self):\n        return self.eom.param[\"DELTA_H\"]\n\n    @property\n    def delta_s(self):\n        return self.eom.param[\"DELTA_S\"]\n", "meta": {"hexsha": "eece8ad60efc833327882e67bc68c5952f178e6e", "size": 40101, "ext": "py", "lang": "Python", "max_stars_repo_path": "mesohops/dynamics/hops_basis.py", "max_stars_repo_name": "MesoscienceLab/mesohops", "max_stars_repo_head_hexsha": "b845dc61e65af158382a47c4894c3875e05f09e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-08-17T03:39:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T22:55:55.000Z", "max_issues_repo_path": "mesohops/dynamics/hops_basis.py", "max_issues_repo_name": "MesoscienceLab/mesohops", "max_issues_repo_head_hexsha": "b845dc61e65af158382a47c4894c3875e05f09e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mesohops/dynamics/hops_basis.py", "max_forks_repo_name": "MesoscienceLab/mesohops", "max_forks_repo_head_hexsha": "b845dc61e65af158382a47c4894c3875e05f09e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-26T02:11:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T02:11:16.000Z", "avg_line_length": 37.6535211268, "max_line_length": 103, "alphanum_fraction": 0.5325552979, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 8974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3522017820478896, "lm_q1q2_score": 0.19664376237036085}}
{"text": "# -*- coding: utf-8 -*-\nimport re\nimport os\nimport gc\nimport math\nimport glob\nimport nltk\nimport shutil\nimport numpy as np\nfrom os import listdir\nfrom zipfile import ZipFile\nfrom collections import Counter\nfrom os.path import isfile, join\nfrom collections import defaultdict\nfrom nltk.stem import PorterStemmer\nfrom nltk.corpus import stopwords as stopWords\nfrom nltk.tokenize import word_tokenize as wordTokenize\n\nnltk.download('punkt')\nnltk.download('stopwords')\n\nstopWordsSet = set(stopWords.words('english'))\nps = PorterStemmer()\n\nclass Node:\n    def __init__(self, docId, freq):\n        self.freq = freq\n        self.doc = docId\n        self.next = None\n    \n    def __str__(self):        \n        return 'doc:' + str(self.doc) + ', freq:' + str(self.freq)\n\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n        self.tail = None\n        self.n_docs = 0\n    \n    def print_list(self):\n        aux = self.head\n        while aux:\n            print(aux)\n            aux = aux.next\n    \n    def get_doclist(self):\n        l = []\n        aux = self.head\n        while aux:\n            l.append([aux.doc, aux.freq])\n            aux = aux.next\n        return l\n    \n    def add_doc(self, doc, freq):\n        node = Node(doc, freq)        \n        if self.head == None:\n            self.head = node        \n        else:\n            self.tail.next = node\n        self.tail = node\n        self.n_docs += 1\n\ndef removeSpecialCharacters(text):\n    regex = re.compile('[^a-zA-Z0-9\\s]')\n    return re.sub(regex, '', text)\n\ndef tokenizeAndRemoveSpecialCharacters(text):\n    return wordTokenize(removeSpecialCharacters(text))\n\ndef listsIntersection(lst1, lst2):\n    return list(set(lst1) & set(lst2))\n\ndef computeNorm(word, maxFreq, linkedListData, wordsInDocument, itf, docsIds):\n    sum = 0\n    docs = linkedListData[word].get_doclist()\n\n    for doc in wordsInDocument.keys():\n        if doc in docs:\n            freq = docs[1]\n        else:\n            freq = 0\n        a = pow((0.5 + 0.5 * (freq / maxFreq)), 2)\n        b = pow(itf[docsIds[doc]], 2)\n        sum = sum + a * b\n\n    return math.sqrt(sum)\n\ndef getMaxFreq(word, linkedListData):\n    maxFreq = 0\n    docs = linkedListData[word].get_doclist()\n\n    for doc in docs:\n        freq = doc[1]\n        if freq > maxFreq:\n            maxFreq = freq\n    return maxFreq\n\ndef getFileText(text):\n    try:\n        text = re.search('<TEXT>(.+?)</TEXT>', text, flags=re.DOTALL).group(1)\n    except AttributeError: # <TEXT></TEXT> not found in the original string\n        text = ''\n    return text\n\ndef getFileName(text):\n    try:\n        name = re.search('<DOCNO>(.+?)</DOCNO>', text, flags=re.DOTALL).group(1)\n    except AttributeError: # <DOCNO></DOCNO> not found in the original string\n        name = ''\n    return name\n\ndef filterText(removeStopWords, removeStemmingWords, value):\n    words = []\n    for w in value:\n        if removeStopWords == True and w not in stopWordsSet: # stop words\n            if removeStemmingWords == True:\n                w = ps.stem(w)  # stemming\n        elif removeStopWords == False:\n            if removeStemmingWords == True:\n                w = ps.stem(w)  # stemming\n        words.append(w)\n    return words\n\ndef readDocs(path):\n    numDocs = 0\n    docsIds = {}\n    docsNames = []\n    wordsInDocument = {}\n\n    for folder in glob.glob(path):\n        for subfolder in glob.glob(folder + '/*'):\n            for directory in glob.glob(subfolder + '/*'):\n                for subdir in glob.glob(directory):\n                    with open(subdir, \"r\") as doc:\n                        text = doc.read()\n                        \n                        fileName = getFileName(text)\n                        \n                        wordsInDocument[fileName] = getFileText(text)\n                        \n                        wordsInDocument[fileName] = tokenizeAndRemoveSpecialCharacters(wordsInDocument[fileName].lower())\n                        \n                        # atribuindo um id pra cada documento\n                        docsIds[fileName] = numDocs\n\n                        # salvando nomes dos arquivos\n                        docsNames.append(fileName)\n                        \n                        numDocs = numDocs + 1\n                doc.close()\n\n    return numDocs, docsIds, docsNames, wordsInDocument\n\ndef readQueriesDoc(path):\n    \"\"\"Lê o documento en.topics e armazena as queries, e seus respectivos ids, que serão usados\"\"\"\n\n    queries = defaultdict()\n    with open(path) as file:\n        text = file.read()\n        splitted = text.split(\"\\n\\n\")\n\n    for line in splitted:\n        if 'topics' in line: continue\n        id = re.search(r'<num>(.*?)</num>', line).group(1)\n        query = re.search(r'<title>(.*?)</title>.', line, flags=re.DOTALL).group(1)\n        query += re.search(r'<narr>(.*?)</narr>', line, flags=re.DOTALL).group(1)\n        query = removeSpecialCharacters(query)\n        queries[id] = wordTokenize(query)\n        queries[id] = filterText(True, True, queries[id])\n\n    return queries\n\ndef prob_model(wordsInDocument, query, linkedListData, numDocs, uniqueWords):\n    \"\"\"\n    Modelo probabilistico\n    \"\"\"\n\n    print(\"\\nRealizando seleção inicial no Modelo probabilístico...\\n\")\n    # Seleção inicial\n    initial_sel_answer = {}\n    \n    for doc in wordsInDocument.keys():\n        words = wordsInDocument[doc]\n        commonWordsBetweenQueryAndDoc = listsIntersection(query, words)\n        relevance = 0\n        for ki in commonWordsBetweenQueryAndDoc:\n            numDocsWithKi = linkedListData[ki].n_docs\n            relevance += math.log10((numDocs + 0.5)/(numDocsWithKi + 0.5))\n            if relevance > 0:\n                initial_sel_answer[doc] = relevance\n    \n    # verifica qual a maior relevancia encontrada\n    # na seleção inicial dentre os documentos\n    max = 0\n    doc = ''\n    for item in initial_sel_answer.keys():\n        if initial_sel_answer[item] > max:\n            max = initial_sel_answer[item]\n            doc = item\n            \n    print(\"Documento mais relevante na seleção inicial:\", doc)\n\n    # Ranqueamento final\n    print(\"\\nRealizando Rnaqueamento final no Modelo probabilístico...\\n\")\n\n    relevantDocs = []\n    numRelevantDocs = {}\n    \n    sorted_answer = sorted(initial_sel_answer.items(), key = lambda x: x[1], reverse = True)\n\n    relevantDocs.append(sorted_answer[0][0])\n    \n    print(\"Documentos mais relevantes:\", relevantDocs)\n\n    final_rank_answer = {}\n    \n    for word in query:\n        if word not in uniqueWords:\n            continue\n        postings = linkedListData[word].head\n        numRelevantDocs[word] = 0\n        while postings:\n            if postings.doc in relevantDocs:\n                numRelevantDocs[word] += 1\n            postings = postings.next\n    \n    numRelevantDocsToQuery = len(relevantDocs)\n    \n    for doc in wordsInDocument.keys():\n        words = wordsInDocument[doc]\n        commonWordsBetweenQueryAndDoc = listsIntersection(query, words)\n        relevance = 0\n    \n        for ki in commonWordsBetweenQueryAndDoc:\n            numDocsWithKi = linkedListData[ki].n_docs\n            numRelevantDocsWithKi = numRelevantDocs[ki]\n            numerator = ((numRelevantDocsWithKi + 0.5) * (numDocs - numDocsWithKi - numRelevantDocsToQuery + numRelevantDocsWithKi + 0.5))\n            denominator = ((numRelevantDocsToQuery - numRelevantDocsWithKi + 0.5) * (numDocsWithKi - numRelevantDocsWithKi + 0.5))\n            relevance += math.log10(numerator / denominator)\n        final_rank_answer[doc] = relevance\n\n    # final_rank_answer\n\n    # Se os dois prints tiverem o mesmo valor, significa que\n    # o documento com mais relevância na seleção inicial\n    # é o mesmo na seleção final\n\n    max = 0\n    for item in final_rank_answer.keys():\n        if final_rank_answer[item] > max:\n            max = final_rank_answer[item]\n\n    if final_rank_answer[relevantDocs[0]] == max:\n        print(\"\\nResultados iguais = \", final_rank_answer[relevantDocs[0]])\n\n    print(\"\\nFim do Modelo probabilístico...\\n\\n\")\n\n    return initial_sel_answer, final_rank_answer\n\ndef vect_model(wordsIds, uniqueWords, numDocs, linkedListData, query, docsNames, docsIds):\n    \"\"\"\n    Modelo Vetorial\n\n    Iremos utilizar a ponderação de termos TF-IDF, que considera a frequência de cada termo e a frequência inversa de documento.\n\n    Alguns termos possuem maior importância semântica para representar determinado elemento. Por exemplo, um termo que aparece em todos os documentos indexados não nos auxilia em nada no rankeamento dos mesmos, da mesma forma que um termo raro pode ser de extrema importância para identificar um determinado assunto.\n\n    \"\"\"\n    # Ponderação TF-IDF\n    print(\"Realizando ponderação TF-IDF no Modelo Vetorial...\\n\")\n\n    m = np.zeros((len(uniqueWords), numDocs))\n    \n    for word in uniqueWords:\n        postings = linkedListData[word].get_doclist()\n        \n        idf = math.log2(numDocs/ linkedListData[word].n_docs)\n    \n        for node in postings:\n    \n            docName = node[0]\n            freq = node[1]\n    \n            # tf-idf = (1+log2(freq))*idf, se freq > 0\n            if freq > 0:\n              m[wordsIds[word], docsIds[docName]] = (1 + math.log2(freq)) * idf\n            # tf-idf = 0, caso contrario\n            #   m[wordsIds[word], docsIds[docName]] = 0\n\n    \"\"\"Normalização pelo tamanho dos documentos\"\"\"\n    print(\"Realizando Normalização pelo tamanho dos documentos no Modelo Vetorial...\\n\")\n\n    m = m**2\n    norm = np.sum(m, axis=0)\n    norm = [math.sqrt(norm[i]) for i in range(len(norm))]\n\n    \"\"\"Realizando a ponderação TF-IDF na query\"\"\"\n    print(\"Realizando ponderação TF-IDF na query no Modelo Vetorial...\\n\")\n\n    i = 0\n    queryVector = np.zeros(len(uniqueWords))\n    \n    for word in uniqueWords:\n        if word in query:\n            idf = math.log2(numDocs/ linkedListData[word].n_docs)\n            queryVector[i] = (1 + math.log2(query.count(word))) * idf\n            i += 1\n\n    \"\"\"Ranqueamento\"\"\"\n    print(\"Realizando Ranqueamento no Modelo Vetorial...\\n\")\n    \n    ranking = {}\n    \n    for docName in docsNames:\n        ranking[docName] = np.dot(m[:,docsIds[docName]], queryVector) / norm[docsIds[docName]]\n    \n    sorted_ranking = {k: v for k, v in sorted(ranking.items(), key = lambda item: item[1], reverse=True)}\n\n    del m\n    gc.collect()\n\n    print(\"\\nFim do Modelo Vetorial...\\n\\n\")\n\n    return sorted_ranking\n\ndef query_expansion(numDocs, wordsInDocument, docsIds, uniqueWords, linkedListData, query, wordsIds):\n    \"\"\"\n    Expansão de consultas\n\n    \"\"\"\n    \n    \"\"\"Frequência inversa de termo (itf)\"\"\"\n    print(\"Realizando Frequência inversa de termo (itf) na Expansao\\n\")\n\n    # Frequencia inversa de termo (itf) pra cada documento j\n    # Calculo dele é dado por:\n    # numerador = nro de termos distintos em tds os docs\n    # denominador = nro de termos distintos no doc j\n    # itf(doc j) = numerador / denominador\n    itf = [0] * numDocs\n\n    for doc in wordsInDocument.keys():\n        uniqueWordsInDoc = set(wordsInDocument[doc])\n        if(len(uniqueWordsInDoc) == 0): \n            continue\n        docId = docsIds[doc]\n        itf[docId] = math.log2(len(uniqueWords) / len(uniqueWordsInDoc))\n\n    \"\"\"Pesagem dos documentos\"\"\"\n    print(\"Realizando Pesagem dos documentos na Expansao\\n\")\n\n    w = np.zeros((len(uniqueWords), numDocs))\n    \n    for word in uniqueWords:\n        maxFreq = getMaxFreq(word, linkedListData)\n        norm = computeNorm(word, maxFreq, linkedListData, wordsInDocument, itf, docsIds)\n    \n        for docs in linkedListData[word].get_doclist():\n            fileName = docs[0]\n            freq = docs[1]\n            a = (0.5 + 0.5 * (freq / maxFreq))\n            b = itf[docsIds[fileName]]\n            w[wordsIds[word]][docsIds[fileName]] = (a * b) / norm\n\n    \"\"\"Similaridade\"\"\"\n    print(\"Calculando similaridade na Expansao\\n\")\n\n    # Similaridade\n    c = np.dot(w, w.transpose())\n\n    del w\n    gc.collect()\n\n    \"\"\"Pesagem da consulta\"\"\"\n    print(\"Realizando Pesagem da consulta na Expansao\\n\")\n\n    # Pesagem da consulta\n    q = [0] * len(query)\n    \n    uniqueWordsInQuery = set(query)\n    \n    i = 0\n    wordsInQueryIds = {}\n    for word in query:\n        wordsInQueryIds[word] = i\n        i = i + 1\n    \n    sum = 0\n    for i in range(len(itf)):\n        sum = sum + math.pow(itf[i], 2)\n    norm = math.sqrt(sum)\n    \n    for word in query:\n        q[wordsInQueryIds[word]] = math.log2(len(uniqueWords)/ len(uniqueWordsInQuery)) / norm\n\n    \"\"\"Combinação da similaridade com pesagem da consulta\"\"\"\n    print(\"Combinando similaridade com pesagem da consulta na Expansao\\n\")\n\n    result = {}\n    \n    # Combinação da similaridade com a pesagem da consulta\n    for word in uniqueWords:\n        similaridade = 0\n        result[word] = similaridade\n        for item in query:\n            a = q[wordsInQueryIds[item]]\n            if item not in uniqueWords:\n                b = 0\n            else:\n                b = c[wordsIds[item]][wordsIds[word]]\n            similaridade = similaridade + a * b\n            result[word] = similaridade\n\n    \"\"\"Resultado da expansão\"\"\"\n\n    sorted_result = {k: v for k, v in sorted(result.items(), key = lambda item: item[1], reverse=True)}\n\n    keys = list(sorted_result.keys())\n\n    print(\"Query expandida: \", keys[:4])\n\n    print(\"\\nFim da Expansao...\\n\\n\")\n\n    return sorted_result\n\ndef getRelDocs(path):\n    rel_docs = defaultdict()\n\n    with open(path) as file:\n        for line in file:\n            token = wordTokenize(line)\n            if token[3] == '1':\n                if int(token[0]) in rel_docs.keys():\n                    rel_docs[int(token[0])].append(token[2])\n                else:\n                    rel_docs[int(token[0])] = [token[2]]\n\n    return rel_docs\n\ndef evaluation(queryId, rel_docs, answer):\n    \"\"\"\n    Avaliação\n    \n    A avaliação serve para julgar o quão bem o sistema atende à necessidade de \n    informação do usuário. Estamos considerando precisão e revocação. \n    \"\"\"\n\n    intersec = 0\n\n    for rel_doc in answer.keys():\n        if rel_doc in rel_docs[int(queryId)]:\n            intersec += 1\n\n    precisao = intersec/len(rel_docs[int(queryId)])\n    revocacao = intersec/len(answer)\n\n    return precisao, revocacao\n\ndef main():\n\n    docsPath = 'a/*'\n    topicsPath = 'en.topics.76-125.2010.txt'\n    queriesPath = 'en.qrels.76-125.2010.txt'\n\n\n    numDocs, docsIds, docsNames, wordsInDocument = readDocs(docsPath)\n\n    # Remoção de stopwords, radicalização e indexação\n\n    dict = defaultdict(int)\n\n    for key, value in wordsInDocument.items():\n        wordsInDocument[key] = filterText(True, True, value)\n\n    for key, value in wordsInDocument.items():\n        for w in set(value): \n            dict[w] += 1\n\n    i = 0\n    wordsIds = {}\n    linkedListData = {}\n    uniqueWords = sorted(set(dict.keys()))\n    \n    # atribuindo um id pra cada palavra\n    for word in uniqueWords:\n        wordsIds[word] = i\n        linkedListData[word] = LinkedList()\n        i = i + 1\n    \n    print(\"\\nFound %d unique words\" % len(uniqueWords))\n\n    for doc in wordsInDocument.keys():\n        words = wordsInDocument[doc]\n        for word in set(words):\n            linkedListData[word].add_doc(doc, words.count(word))\n\n    queries = readQueriesDoc(topicsPath)\n\n    # Define qual query iremos trabalhar em cima\n    queryId = '76'\n    query = queries[queryId]\n\n    initial_sel_answer, final_rank_answer = prob_model(wordsInDocument, query, linkedListData, numDocs, uniqueWords)\n\n    ranked_vect_answer = vect_model(wordsIds, uniqueWords, numDocs, linkedListData, query, docsNames, docsIds)\n\n    expansion_answer = query_expansion(numDocs, wordsInDocument, docsIds, uniqueWords, linkedListData, query, wordsIds)\n\n    rel_docs = getRelDocs(queriesPath)\n    \n    precisao = defaultdict()\n    revocacao = defaultdict()\n\n    precisao[queryId], revocacao[queryId] = evaluation(queryId, rel_docs, initial_sel_answer)\n\n    print(\"precisao \", precisao[queryId], \"\\nrevocacao \", revocacao[queryId])\n\nmain()", "meta": {"hexsha": "d22b271e99353432ed7fb9570f630f69950b618f", "size": 15966, "ext": "py", "lang": "Python", "max_stars_repo_path": "Information Retrieval/project.py", "max_stars_repo_name": "henriquesqs/Codes", "max_stars_repo_head_hexsha": "59e5bb683f3de2ee1b13621569954be1e4f37396", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Information Retrieval/project.py", "max_issues_repo_name": "henriquesqs/Codes", "max_issues_repo_head_hexsha": "59e5bb683f3de2ee1b13621569954be1e4f37396", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-21T03:26:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-21T03:26:14.000Z", "max_forks_repo_path": "Information Retrieval/project.py", "max_forks_repo_name": "henriquesqs/Codes", "max_forks_repo_head_hexsha": "59e5bb683f3de2ee1b13621569954be1e4f37396", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-31T01:49:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-31T01:49:23.000Z", "avg_line_length": 30.8223938224, "max_line_length": 316, "alphanum_fraction": 0.6118627083, "include": true, "reason": "import numpy", "num_tokens": 4041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.19664375477759474}}
{"text": "\"\"\" Implementation of the Constrained Policy Optimization (CPO) algorithm.\n\n    see:\n    Joshua Achiam, David Held, Aviv Tamar, Peter Abbeel\n    Constrained Policy Optimization\n    ICML 2017\n\nAuthor:     Sven Gronauer (sven.gronauer@tum.de)\nCreated:    12.10.2020\nUpdated:    27.10.2020\n\"\"\"\n\nimport numpy as np\nimport torch\nfrom rl_safety_algorithms.common import utils\nfrom rl_safety_algorithms.algs.trpo.trpo import TRPOAlgorithm\nfrom rl_safety_algorithms.algs.npg.npg import NaturalPolicyGradientAlgorithm\nimport rl_safety_algorithms.algs.utils as U\nimport rl_safety_algorithms.common.mpi_tools as mpi_tools\n\n\nclass CPOAlgorithm(TRPOAlgorithm):\n    \"\"\"Constrained Policy Optimization Algorithm.\n\n    This implementation does not use cost shaping, but relies on exploration\n    noise annealing.\n    Large parts are inspired and taken from:\n    https://github.com/openai/safety-starter-agents/blob/master/safe_rl/pg/agents.py#L209\n    (MIT License)\n    \"\"\"\n    def __init__(\n            self,\n            alg: str = 'cpo',\n            cost_limit: float = 25.,\n            **kwargs\n    ):\n        super().__init__(\n            alg=alg,\n            cost_limit=cost_limit,\n            use_cost_value_function=True,\n            **kwargs\n        )\n        self.cost_limit = cost_limit\n        self.loss_pi_cost_before = 0.\n\n    def adjust_cpo_step_direction(\n            self,\n            step_dir,\n            g_flat,\n            c,\n            optim_case,\n            p_dist,\n            data,\n            total_steps: int = 25,\n            decay: float = 0.8\n    ):\n        \"\"\"CPO algorithm performs line-search to ensure constraint satisfaction\n        for rewards and costs.\"\"\"\n        step_frac = 1.0\n        _theta_old = U.get_flat_params_from(self.ac.pi.net)\n        _, old_log_p = self.ac.pi(data['obs'], data['act'])\n        expected_rew_improve = g_flat.dot(step_dir)\n\n        # while not within_trust_region:\n        for j in range(total_steps):\n            new_theta = _theta_old + step_frac * step_dir\n            U.set_param_values_to_model(self.ac.pi.net, new_theta)\n            acceptance_step = j + 1\n\n            with torch.no_grad():\n                loss_pi_rew, _ = self.compute_loss_pi(data=data)\n                loss_pi_cost, _ = self.compute_loss_cost_performance(data=data)\n                # determine KL div between new and old policy\n                q_dist = self.ac.pi.dist(data['obs'])\n                torch_kl = torch.distributions.kl.kl_divergence(\n                    p_dist, q_dist).mean().item()\n            loss_rew_improve = self.loss_pi_before - loss_pi_rew.item()\n            cost_diff = loss_pi_cost.item() - self.loss_pi_cost_before\n\n            # Average across MPI processes...\n            torch_kl = mpi_tools.mpi_avg(torch_kl)\n            loss_rew_improve = mpi_tools.mpi_avg(loss_rew_improve)\n            cost_diff = mpi_tools.mpi_avg(cost_diff)\n\n            self.logger.log(\"Expected Improvement: %.3f Actual: %.3f\" % (\n                expected_rew_improve, loss_rew_improve))\n\n            if not torch.isfinite(loss_pi_rew) and not torch.isfinite(\n                    loss_pi_cost):\n                self.logger.log('WARNING: loss_pi not finite')\n            elif loss_rew_improve < 0 if optim_case > 1 else False:\n                self.logger.log('INFO: did not improve improve <0')\n\n            elif cost_diff > max(-c, 0):\n                self.logger.log(f'INFO: no improve {cost_diff} > {max(-c, 0)}')\n            elif torch_kl > self.target_kl * 1.5:\n                self.logger.log(\n                    f'INFO: violated KL constraint {torch_kl} at step {j + 1}.')\n            else:\n                # step only if surrogate is improved and we are\n                # within the trust region\n                self.logger.log(f'Accept step at i={j + 1}')\n                break\n            step_frac *= decay\n        else:\n            self.logger.log('INFO: no suitable step found...')\n            step_dir = torch.zeros_like(step_dir)\n            acceptance_step = 0\n\n        U.set_param_values_to_model(self.ac.pi.net, _theta_old)\n        return step_frac * step_dir, acceptance_step\n\n    def algorithm_specific_logs(self):\n        NaturalPolicyGradientAlgorithm.algorithm_specific_logs(self)\n        self.logger.log_tabular('Misc/cost_gradient_norm')\n        self.logger.log_tabular('Misc/A')\n        self.logger.log_tabular('Misc/B')\n        self.logger.log_tabular('Misc/q')\n        self.logger.log_tabular('Misc/r')\n        self.logger.log_tabular('Misc/s')\n        self.logger.log_tabular('Misc/Lambda_star')\n        self.logger.log_tabular('Misc/Nu_star')\n        self.logger.log_tabular('Misc/OptimCase')\n\n    def compute_loss_cost_performance(self, data):\n        dist, _log_p = self.ac.pi(data['obs'], data['act'])\n        ratio = torch.exp(_log_p - data['log_p'])\n        cost_loss = (ratio * data['cost_adv']).mean()\n        # ent = dist.entropy().mean().item()\n        info = {}\n        return cost_loss, info\n\n    def update_policy_net(self, data):\n        # Get loss and info values before update\n        theta_old = U.get_flat_params_from(self.ac.pi.net)\n        self.pi_optimizer.zero_grad()\n        loss_pi, pi_info = self.compute_loss_pi(data=data)\n        self.loss_pi_before = loss_pi.item()\n        self.loss_v_before = self.compute_loss_v(data['obs'],\n                                                 data['target_v']).item()\n        self.loss_c_before = self.compute_loss_c(data['obs'],\n                                                 data['target_c']).item()\n        # get prob. distribution before updates\n        p_dist = self.ac.pi.dist(data['obs'])\n        # Train policy with multiple steps of gradient descent\n        loss_pi.backward()\n        # average grads across MPI processes\n        mpi_tools.mpi_avg_grads(self.ac.pi.net)\n        g_flat = U.get_flat_gradients_from(self.ac.pi.net)\n\n        # flip sign since policy_loss = -(ration * adv)\n        g_flat *= -1\n\n        x = U.conjugate_gradients(self.Fvp, g_flat, self.cg_iters)\n        assert torch.isfinite(x).all()\n        eps = 1.0e-8\n        # Note that xHx = g^T x, but calculating xHx is faster than g^T x\n        xHx = torch.dot(x, self.Fvp(x))  # equivalent to : g^T x\n        alpha = torch.sqrt(2 * self.target_kl / (xHx + eps))\n        assert xHx.item() >= 0, 'No negative values'\n\n        # get the policy cost performance gradient b (flat as vector)\n        self.pi_optimizer.zero_grad()\n        loss_cost, _ = self.compute_loss_cost_performance(data=data)\n        loss_cost.backward()\n        # average grads across MPI processes\n        mpi_tools.mpi_avg_grads(self.ac.pi.net)\n        self.loss_pi_cost_before = loss_cost.item()\n        b_flat = U.get_flat_gradients_from(self.ac.pi.net)\n\n        ep_costs = self.logger.get_stats('EpCosts')[0]\n        c = ep_costs - self.cost_limit\n        c /= (self.logger.get_stats('EpLen')[0] + eps)  # rescale\n        self.logger.log(f'c = {c}')\n        self.logger.log(f'b^T b = {b_flat.dot(b_flat).item()}')\n\n        # set variable names as used in the paper\n        p = U.conjugate_gradients(self.Fvp, b_flat, self.cg_iters)\n        q = xHx\n        r = g_flat.dot(p)  # g^T H^{-1} b\n        s = b_flat.dot(p)  # b^T H^{-1} b\n\n        # print('b^T g', g_flat.dot(b_flat))\n\n        if b_flat.dot(b_flat) <= 1e-6 and c < 0:\n            # feasible step and cost grad is zero: use plain TRPO update...\n            A = torch.zeros(1)\n            B = torch.zeros(1)\n            optim_case = 4\n        else:\n\n            self.logger.log(f'q={q.item()}')\n            self.logger.log(f'r={r.item()}')\n            self.logger.log(f's={s.item()}')\n            self.logger.log(f'r/c={(r / c).item()}')\n            assert torch.isfinite(r).all()\n            assert torch.isfinite(s).all()\n\n            A = q - r ** 2 / s  # must be always >= 0 (Cauchy-Schwarz inequality)\n            B = 2 * self.target_kl - c ** 2 / s  # safety line intersects trust-region if B > 0\n\n            if c < 0 and B < 0:\n                # point in trust region is feasible and safety boundary doesn't intersect\n                # ==> entire trust region is feasible\n                optim_case = 3\n            elif c < 0 and B >= 0:\n                # x = 0 is feasible and safety boundary intersects\n                # ==> most of trust region is feasible\n                optim_case = 2\n            elif c >= 0 and B >= 0:\n                # x = 0 is infeasible and safety boundary intersects\n                # ==> part of trust region is feasible, recovery possible\n                optim_case = 1\n                self.logger.log('Alert! Attempting feasible recovery!',\n                                'yellow')\n            else:\n                # x = 0 infeasible, and safety halfspace is outside trust region\n                # ==> whole trust region is infeasible, try to fail gracefully\n                optim_case = 0\n                self.logger.log('Alert! Attempting infeasible recovery!', 'red')\n\n        if optim_case in [3, 4]:\n            alpha = torch.sqrt(2 * self.target_kl / (xHx + 1e-8))\n            nu_star = torch.zeros(1)\n            lambda_star = 1 / alpha\n            step_dir = alpha * x\n\n        elif optim_case in [1, 2]:\n            def project_on_set(t: torch.Tensor,\n                               low: float,\n                               high: float\n                               ) -> torch.Tensor:\n                return torch.Tensor([max(low, min(t, high))])\n\n            lambda_a = torch.sqrt(A / B)\n            lambda_b = torch.sqrt(q / (2 * self.target_kl))\n            if c < 0:\n                lambda_a_star = project_on_set(lambda_a, 0., r / c)\n                lambda_b_star = project_on_set(lambda_b, r / c, np.inf)\n            else:\n                lambda_a_star = project_on_set(lambda_a, r / c, np.inf)\n                lambda_b_star = project_on_set(lambda_b, 0., r / c)\n\n            def f_a(lam):\n                return -0.5 * (A / (lam + eps) + B * lam) - r * c / (s + eps)\n\n            def f_b(lam):\n                return -0.5 * (q / (lam + eps) + 2 * self.target_kl * lam)\n\n            lambda_star = lambda_a_star \\\n                if f_a(lambda_a_star) >= f_b(lambda_b_star) else lambda_b_star\n\n            # Discard all negative values with torch.clamp(x, min=0)\n            nu_star = torch.clamp(lambda_star * c - r, min=0) / (s + eps)\n            step_dir = 1. / (lambda_star + eps) * (x - nu_star * p)\n\n        else:  # case == 0\n            # purely decrease costs\n            lambda_star = torch.zeros(1)\n            nu_star = np.sqrt(2 * self.target_kl / (s + eps))\n            step_dir = -nu_star * p\n\n        final_step_dir, accept_step = self.adjust_cpo_step_direction(\n            step_dir,\n            g_flat,\n            c=c,\n            optim_case=optim_case,\n            p_dist=p_dist,\n            data=data,\n            total_steps=20\n        )\n        # update actor network parameters\n        new_theta = theta_old + final_step_dir\n        U.set_param_values_to_model(self.ac.pi.net, new_theta)\n\n        q_dist = self.ac.pi.dist(data['obs'])\n        torch_kl = torch.distributions.kl.kl_divergence(\n            p_dist, q_dist).mean().item()\n\n        self.logger.store(**{\n            'Values/Adv': data['act'].numpy(),\n            'Entropy': pi_info['ent'],\n            'KL': torch_kl,\n            'PolicyRatio': pi_info['ratio'],\n            'Loss/Pi': self.loss_pi_before,\n            'Loss/DeltaPi': loss_pi.item() - self.loss_pi_before,\n            'Misc/StopIter': 1,\n            'Misc/AcceptanceStep': accept_step,\n            'Misc/Alpha': alpha.item(),\n            'Misc/FinalStepNorm': final_step_dir.norm().numpy(),\n            'Misc/xHx': xHx.numpy(),\n            'Misc/H_inv_g': x.norm().item(),  # H^-1 g\n            'Misc/gradient_norm': torch.norm(g_flat).numpy(),\n            'Misc/cost_gradient_norm': torch.norm(b_flat).numpy(),\n            'Misc/Lambda_star': lambda_star.item(),\n            'Misc/Nu_star': nu_star.item(),\n            'Misc/OptimCase': int(optim_case),\n            'Misc/A': A.item(),\n            'Misc/B': B.item(),\n            'Misc/q': q.item(),\n            'Misc/r': r.item(),\n            'Misc/s': s.item(),\n        })\n\n\ndef get_alg(env_id, **kwargs) -> CPOAlgorithm:\n    defaults = utils.get_defaults_kwargs(alg='cpo', env_id=env_id)\n    defaults.update(**kwargs)\n    return CPOAlgorithm(\n        env_id=env_id,\n        **defaults\n    )\n\n\ndef learn(\n        env_id,\n        **kwargs\n) -> tuple:\n    defaults = utils.get_defaults_kwargs(alg='cpo', env_id=env_id)\n    defaults.update(**kwargs)\n    alg = CPOAlgorithm(\n        env_id=env_id,\n        **defaults\n    )\n    ac, env = alg.learn()\n    return ac, env\n", "meta": {"hexsha": "fa830007fa1784e0a4383923c61cef7a8491acc7", "size": 12665, "ext": "py", "lang": "Python", "max_stars_repo_path": "rl_safety_algorithms/algs/cpo/cpo.py", "max_stars_repo_name": "liuzuxin/RL-Safety-Algorithms", "max_stars_repo_head_hexsha": "2575225b1ea8ce12e1e13f7a81f8dda7b4189708", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-09-05T17:49:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T03:13:39.000Z", "max_issues_repo_path": "rl_safety_algorithms/algs/cpo/cpo.py", "max_issues_repo_name": "liuzuxin/RL-Safety-Algorithms", "max_issues_repo_head_hexsha": "2575225b1ea8ce12e1e13f7a81f8dda7b4189708", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rl_safety_algorithms/algs/cpo/cpo.py", "max_forks_repo_name": "liuzuxin/RL-Safety-Algorithms", "max_forks_repo_head_hexsha": "2575225b1ea8ce12e1e13f7a81f8dda7b4189708", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-09-05T17:49:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-30T17:36:30.000Z", "avg_line_length": 38.7308868502, "max_line_length": 95, "alphanum_fraction": 0.5627319384, "include": true, "reason": "import numpy", "num_tokens": 3081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.19663464749282641}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nRun future simulations based on IUCN data and status transition rates\n\nCreated on Wed Oct 30 20:59:28 2019\n@author: Tobias Andermann (tobias.andermann@bioenv.gu.se)\n\"\"\"\n\nimport numpy as np\nnp.set_printoptions(suppress=True)\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_pdf import PdfPages\nimport os\nimport sys\nimport iucn_sim.functions as cust_func\n\n\ndef add_arguments(parser):\n    parser.add_argument(\n        '--input_data',\n        required=True,\n        help=\"Path to 'simulation_input_data.pkl' file created by esimate_rates function.\"\n    )\n    parser.add_argument(\n        '--outdir',\n        required=True,\n        help=\"Provide path to outdir where results will be saved.\"\n    )\n    parser.add_argument(\n        '--n_years',\n        default=100,\n        help=\"How many years to simulate into the future.\"\n    )\n    parser.add_argument(\n        '--n_sim',\n        default=10000,\n        help=\"How many simulation replicates to run. At least 10,000 simulations are recommended for accurate rate estimation (default). If the number of simulation replicates exceeds the number of available transition rate estimates (produced by the 'transition_rates' function), these rates will be randomely resampled for the remaining simulations.\"\n    )\n    parser.add_argument(\n        '--status_change',\n        default=1,\n        help=\"Model IUCN status changes in future simulations. 0=off, 1=on (default=1).\"\n    )\n    parser.add_argument(\n        '--conservation_increase_factor',\n        default=1,\n        help=\"The transition rates leading to improvements in IUCN conservation status are multiplied by this factor.\"\n    )\n    parser.add_argument(\n        '--threat_increase_factor',\n        default=1,\n        help=\"Opposite of conservation_increase_factor, multiplies the transition rates leading to worsening in IUCN conservation status.\"\n    )\n    parser.add_argument(\n        '--model_unknown_as_lc',\n        default=0,\n        help=\"Model new status for all DD and NE species as LC (best case scenario). 0=off, 1=on (default=0).\"\n    )\n    parser.add_argument(\n        '--n_extinct_taxa',\n        default=0,\n        help=\"Setting this value will stop the simulations when n taxa have gone extinct. This can be used to simulate the expected time until n extinctions. The value of the --n_years flag in this case will be interpreted as the maximum possible time frame, so set it large enough to cover a realistic time-frame for these extinctions to occur. Set to 0 to disable this function (default=0).\"\n    )\n    parser.add_argument(\n        '--extinction_rates',\n        default=1,\n        help=\"Estimation of extinction rates from simulation results: 0=off, 1=on (default=1).\"\n    )\n    parser.add_argument(\n        '--n_gen',\n        default=100000,\n        help=\"Number of generations for MCMC for extinction rate estimation (default=100000).\"\n    )\n    parser.add_argument(\n        '--burnin',\n        default=1000,\n        help=\"Burn-in for MCMC for extinction rate estimation (default=1000).\"\n    )\n    parser.add_argument(\n        '--plot_diversity_trajectory',\n        default=1,\n        help=\"Plots the simulated diversity trajectory: 0=off, 1=on (default=1).\"\n    )\n    parser.add_argument(\n        '--plot_status_trajectories',\n        default=1,\n        help=\"Plots the simulated IUCN status trajectory: 0=off, 1=on (default=0).\"\n    )\n    parser.add_argument(\n        '--plot_histograms',\n        default=0,\n        help=\"Plots histograms of simulated extinction times for each species: 0=off, 1=on (default=0).\"\n    )\n    parser.add_argument(\n        '--plot_posterior',\n        default=0,\n        help=\"Plots histograms of posterior rate estimates for each species: 0=off, 1=on (default=0).\"\n    )\n    parser.add_argument(\n        '--plot_status_piechart',\n        default=1,\n        help=\"Plots pie charts of status distribution: 0=off, 1=on (default=1).\"\n    )\n    parser.add_argument(\n        '--seed',\n        default=None,\n        help=\"Set random seed for future simulations.\"\n    )\n\n\ndef p_e_year(years,p_e):\n    pe_year = 1-(1-p_e)**(1/years)\n    return pe_year\n\ndef update_multiplier(q,d=1.1):\n    u = np.random.uniform(0,1)\n    l = 2*np.log(d)\n    m = np.exp(l*(u-.5))\n    new_q = q * m\n    return new_q, np.log(m)\n\ndef get_rate_estimate(ext_time_array,max_t,index,species_list,plot_posterior=0,pdf=0,n_gen = 100000,burnin = 1000):\n    sys.stdout.write('\\rProcessing species: %i/%i '%(index+1,len(species_list)))\n    ext_time_array_new = ext_time_array.copy()\n    ext_time_array_new[ext_time_array_new!=ext_time_array_new] = max_t\n    ext_time_array_new = ext_time_array_new.astype(float)\n    w_times = np.sum(ext_time_array_new)\n    ext_events = len(ext_time_array_new[ext_time_array_new<max_t])\n    post_samples = []\n    q = 0.01\n    likA = np.log(q)*ext_events -q*w_times    \n    for i in range(n_gen):\n        new_q, hast = update_multiplier(q)\n        lik = np.log(new_q)*ext_events -new_q*w_times\n        if lik-likA + hast >= np.log(np.random.random()):\n            q = new_q\n            likA = lik\n        if i > burnin and i % 10==0:\n            post_samples.append(q)\n    mean_value = np.mean(post_samples)\n    lower,upper = cust_func.calcHPD(post_samples,0.95)\n    if plot_posterior:\n        plt.figure()\n        plt.hist(post_samples,100)\n        plt.xlabel('Extinction rate estimates')\n        plt.ylabel('Counts')\n        plt.title(species_list[index])\n        plt.tight_layout()\n        pdf.savefig()\n        plt.close()\n        #fig.savefig(os.path.join(posterior_plot_dir,'%s.pdf'%species_list[index]),bbox_inches='tight', dpi = 500)\n    return [mean_value,lower,upper]\n\ndef select_target_species(species,species_list_status,species_list,en_ext_data,cr_ext_data):\n    target_species = species\n    target_index = species_list_status[species_list_status.species==target_species].index.values[0]\n    species_list_status = species_list_status.iloc[target_index,:]\n    species_list = np.array([species_list[target_index]])\n    en_ext_data = np.array([en_ext_data[target_index]])\n    cr_ext_data = np.array([cr_ext_data[target_index]])\n    return pd.DataFrame(species_list_status).T,species_list,en_ext_data,cr_ext_data\n\ndef get_rate_estimate_posterior(ext_time_array,max_t,index,species_list,n_gen = 100000,burnin = 1000):\n    sys.stdout.write('\\rProcessing species: %i/%i '%(index+1,len(species_list)))\n    ext_time_array_new = ext_time_array.copy()\n    ext_time_array_new[ext_time_array_new!=ext_time_array_new] = max_t\n    ext_time_array_new = ext_time_array_new.astype(float)\n    w_times = np.sum(ext_time_array_new)\n    ext_events = len(ext_time_array_new[ext_time_array_new<max_t])\n    post_samples = []\n    q = 0.01\n    likA = np.log(q)*ext_events -q*w_times    \n    for i in range(n_gen):\n        new_q, hast = update_multiplier(q)\n        lik = np.log(new_q)*ext_events -new_q*w_times\n        if lik-likA + hast >= np.log(np.random.random()):\n            q = new_q\n            likA = lik\n        if i > burnin and i % 10==0:\n            post_samples.append(q)\n    return post_samples\n\n## test rate estimator\n#true_rate = 0.01\n#n_sim = 100\n#ext_time_array = (np.random.exponential(1./true_rate, n_sim)).astype(int)\n#max_t=100\n#ext_time_array[ext_time_array>max_t] = max_t\n#get_rate_estimate(ext_time_array,max_t)\n\ndef main(args):\n    \n    # get user input___________________________________________________________\n    seed = args.seed\n    try:\n        random_seed = int(seed)\n        print('Simulating with user-set starting seed %i.'%random_seed)\n\n    except:\n        random_seed = np.random.randint(999999999)\n        print('Simulating with randomely generated starting seed %i.'%random_seed)\n    np.random.seed(random_seed)\n    \n    infile = args.input_data\n    outdir = args.outdir\n    n_years = int(args.n_years)\n    n_sim = int(args.n_sim)\n    n_extinct_taxa = int(args.n_extinct_taxa)\n    allow_status_change = int(args.status_change)\n    conservation_increase_factor = int(args.conservation_increase_factor)\n    threat_increase_factor = int(args.threat_increase_factor)\n    extinction_rates = int(args.extinction_rates)\n    n_gen = int(args.n_gen)\n    burnin = int(args.burnin)\n    plot_diversity_trajectory = int(args.plot_diversity_trajectory)\n    plot_histograms = int(args.plot_histograms)\n    plot_posterior = int(args.plot_posterior)\n    model_unknown_as_lc = int(args.model_unknown_as_lc)\n    plot_status_trajectories = int(args.plot_status_trajectories)\n    plot_status_piechart = int(args.plot_status_piechart)\n    if not os.path.exists(outdir):\n        os.makedirs(outdir)\n    np.savetxt(os.path.join(outdir,'starting_seed.txt'),np.array([random_seed]),fmt='%i')\n        \n    input_data = cust_func.load_obj(infile)\n    species_input_data, dd_probs = input_data\n    species_list = np.array([i[0] for i in species_input_data])\n    current_status_list = np.array([i[1] for i in species_input_data])\n    q_matrix_list = [i[2] for i in species_input_data]\n    n_rates = dd_probs.shape[1]\n    #__________________________________________________________________________    \n\n\n\n\n    # modify q-matrices, if set by user________________________________________\n    final_qmatrix_list = []\n    q_matrix_list_copy = np.array(q_matrix_list).copy()\n    for q_matrix_list_i in q_matrix_list_copy:\n        q_matrix_list_temp = []\n        for q_matrix in q_matrix_list_i:\n            if conservation_increase_factor != 1:\n                indeces_lower_triangle = np.tril_indices(q_matrix.shape[0],-1)\n                q_matrix[indeces_lower_triangle] = q_matrix[indeces_lower_triangle] * conservation_increase_factor\n                np.fill_diagonal(q_matrix,0)\n                np.fill_diagonal(q_matrix, -np.sum(q_matrix,axis=1))\n            if threat_increase_factor != 1:\n                indeces_upper_triangle = np.triu_indices(q_matrix.shape[0],1)\n                q_matrix[indeces_upper_triangle] = q_matrix[indeces_upper_triangle] * threat_increase_factor\n                np.fill_diagonal(q_matrix,0)\n                np.fill_diagonal(q_matrix, -np.sum(q_matrix,axis=1))                \n            q_matrix_list_temp.append(q_matrix)\n        final_qmatrix_list.append(q_matrix_list_temp)\n    # turn into a dict with the n qmatrices for each species\n    final_qmatrix_dict = dict(zip(species_list,final_qmatrix_list))    \n    #__________________________________________________________________________    \n    \n\n\n\n    # if more n_rep are set than there are q-matrices, resample________________\n    if n_sim <= n_rates:\n        sample_columns = np.random.choice(np.arange(n_rates),size=n_sim,replace=False)\n    # since there are only as many cr and en p(ex) estimates as there are provided GL values, we may have to resample some (but make sure all are present at least once)\n    else:\n        sample_columns1 = np.random.choice(np.arange(n_rates),size=n_rates,replace=False)\n        sample_columns2 = np.random.choice(np.arange(n_rates),size=(n_sim-n_rates),replace=True)\n        sample_columns = np.concatenate([sample_columns1,sample_columns2])    \n    #__________________________________________________________________________    \n\n\n\n\n    # run simulations__________________________________________________________\n    delta_t = n_years\n    model_ne_as_dd = False\n    dynamic_qmatrix = True\n\n    if model_ne_as_dd:\n        current_status_list[current_status_list=='NE'] = 'DD'    \n    if model_unknown_as_lc:\n        print('\\nSetting all DD and NE species to LC.')\n        all_lc=True\n    else:\n        all_lc=False\n    if allow_status_change:\n        status_change=True\n    else:\n        print('\\nNot simulating future status changes!')\n        status_change=False\n\n    print('\\nStarting simulations ...')\n    diversity_through_time,te_array,status_through_time,time_until_n_extinctions_list = cust_func.run_multi_sim(n_sim,delta_t,species_list,current_status_list,dd_probs,final_qmatrix_dict,sample_columns,outdir,all_lc=all_lc,status_change=status_change,dynamic_qmatrix=dynamic_qmatrix,n_extinct_taxa=n_extinct_taxa)\n    # summarize simulation results\n    sim_species_list = te_array[:,0].copy()\n    ext_date_data = te_array[:,1:].copy()\n    extinction_occs = np.array([len(row[~np.isnan(list(row))]) for row in ext_date_data])\n    extinction_prob = extinction_occs/ext_date_data.shape[1]\n    # produce output file for status distribution through time\n    mean_status_through_time = np.mean(status_through_time,axis=2)\n    year = np.arange(delta_t+1).astype(int)\n    status_df_data = np.round(np.vstack([year,mean_status_through_time])).astype(int)\n    status_df = pd.DataFrame(data = status_df_data.T,columns=['year','LC','NT','VU','EN','CR','EX'])\n    status_df.to_csv(os.path.join(outdir,'status_distribution_through_time.txt'),sep='\\t',index=False)\n    np.savetxt(os.path.join(outdir,'simulated_extinctions_array.txt'),status_through_time[-1],fmt='%i')\n    pd.DataFrame(data=te_array).to_csv(os.path.join(outdir,'te_all_species.txt'),sep='\\t',header=False,index=False)\n    #__________________________________________________________________________   \n\n\n\n\n    #__________________________________________________________________________       \n#    if target_species:\n#        posterior = get_rate_estimate_posterior(ext_date_data[0],n_years,0,sim_species_list,n_gen=n_gen,burnin=burnin)\n#        np.savetxt('/Users/tobias/GitHub/iucn_predictions/doc/figures/Figure_2/figure_data/posterior_samples/%s_gl_no_status_change.txt'%target_species.replace(' ','_'),posterior,fmt='%.8f')\n#        print('\\nPrinted posterior')\n    #__________________________________________________________________________   \n    \n    if n_extinct_taxa:        \n        np.savetxt(os.path.join(outdir,'time_until_%i_extinctions.txt'%n_extinct_taxa),time_until_n_extinctions_list,fmt='%.2f')\n        fig = plt.figure()\n        plt.hist(time_until_n_extinctions_list)\n        plt.xlabel('Time in years')\n        plt.ylabel('N')\n        plt.title('Simulated years until %i extinctions (%i simulations)'%(n_extinct_taxa,n_sim))\n        fig.savefig(os.path.join(outdir,'time_until_%i_extinctions.pdf'%n_extinct_taxa),bbox_inches='tight', dpi = 500)\n\n    #__________________________________________________________________________           \n    if plot_diversity_trajectory:\n        # plot diversity trajectory of species list________________________________\n        #colors = [\"#9a002e\",\"#df4a3d\",\"#fecd5f\",\"#5cd368\",\"#916200\"]\n        # define time axis\n        time_axis = np.array(range(len(diversity_through_time[0])))\n        fig = plt.figure()\n        y_values = np.mean(diversity_through_time, axis =0)\n        plt.plot(time_axis,y_values,color=\"#b80033\", label='accounting for GL')\n        # get upper and lower confidence interval boundaries\n        min_hpd, max_hpd = np.array([cust_func.calcHPD(i,0.95) for i in diversity_through_time.T]).T\n        mean_min_max = np.vstack([y_values,min_hpd,max_hpd])\n        np.savetxt(os.path.join(outdir,'future_diversity_trajectory.txt'),mean_min_max,fmt='%.2f')\n        plt.fill_between(time_axis, min_hpd, max_hpd,\n                 color=\"#b80033\", alpha=0.2)\n        #plt.legend()\n        plt.ylabel('Total diversity')\n        plt.xlabel('Years from present')\n        ax = plt.gca()\n        ax1 = ax.twinx()\n        # Set the limits of the new axis from the original axis limits\n        ax1.set_ylim(ax.get_ylim())\n        current_diversity = diversity_through_time[0,0]\n        plt.yticks([np.mean(diversity_through_time[:,-1])],[int(current_diversity-np.mean(diversity_through_time[:,-1]))])\n        #plt.xticks(modified_q_matrix.year[::10],modified_q_matrix.year[::10])\n        plt.ylabel('Lost species')\n        plt.tight_layout()\n        fig.savefig(os.path.join(outdir,'future_diversity_trajectory.pdf'),bbox_inches='tight', dpi = 500)\n    #__________________________________________________________________________   \n\n\n\n\n    #__________________________________________________________________________   \n    if plot_status_trajectories:\n        # color palette\n        colors = [\"#227a00\",\"#a5c279\",\"#f3d248\",\"#6956cb\",\"#79262a\",\"#e34349\"]\n        # define time axis\n        time_axis = np.array(range(len(diversity_through_time[0])))\n        # plot results\n        def plot_mean_and_interval(div,color,label,fig):\n            plt.plot(time_axis,np.mean(div,axis=0),color=color,label=label);\n            min_hpd, max_hpd = np.array([cust_func.calcHPD(i,0.95) for i in div.T]).T\n            plt.fill_between(time_axis, min_hpd, max_hpd, color=color, alpha=0.2);\n            return fig\n        fig = plt.figure(figsize=(10,10))\n        plot_mean_and_interval(status_through_time[0,:,:].T,colors[0],'LC',fig)\n        plot_mean_and_interval(status_through_time[1,:,:].T,colors[1],'NT',fig)\n        plot_mean_and_interval(status_through_time[2,:,:].T,colors[2],'VU',fig)\n        plot_mean_and_interval(status_through_time[3,:,:].T,colors[3],'EN',fig)\n        plot_mean_and_interval(status_through_time[4,:,:].T,colors[4],'CR',fig)\n        plot_mean_and_interval(status_through_time[5,:,:].T,colors[5],'EX',fig)\n        # add title, legend and axis-labels\n        plt.legend(loc='best',fancybox=True)\n        plt.title('Diversity trajectory IUCN categories - status change') #10x higher conservation\n        plt.ylabel('Number species in category')\n        plt.xlabel('Years from present')\n        ax = plt.gca()\n        ax1 = ax.twinx()\n        # Set the limits of the new axis from the original axis limits\n        ax1.set_ylim(ax.get_ylim())\n        # annotate final counts with labels\n        right_ticks = [int(np.round(np.mean(status_through_time[i,-1,:]))) for i in range(status_through_time.shape[0])]\n        plt.yticks(right_ticks,right_ticks)\n        #plt.xticks(modified_q_matrix.year[::10],modified_q_matrix.year[::10])\n        plt.tight_layout()\n        fig.savefig(os.path.join(outdir,'future_status_trajectory.pdf'),bbox_inches='tight', dpi = 500)\n    #__________________________________________________________________________   \n\n\n\n\n    #__________________________________________________________________________       \n    if plot_status_piechart:\n        statuses, counts = np.unique(current_status_list,return_counts=True)\n        init_status_dict = dict(zip(statuses, counts))\n        init_status_dict['EX'] = 0\n        iucn_status_code = {0:'LC', 1:'NT', 2:'VU', 3:'EN', 4:'CR', 5:'EX', 6:'DD'}\n        status_count_list = []\n        for status_id in np.arange(status_through_time.shape[0]+1):\n            status = iucn_status_code[status_id]\n            if status in init_status_dict.keys():\n                pre_dd_modeling_count = init_status_dict[status]\n            else:\n                pre_dd_modeling_count = 0\n            if not status == 'DD':\n                present_status_count = int(np.round(np.mean(status_through_time[status_id][0])))\n                final_status_count = int(np.round(np.mean(status_through_time[status_id][-1])))\n            else:\n                present_status_count = 0\n                final_status_count = 0\n            status_count_list.append([pre_dd_modeling_count,present_status_count,final_status_count])\n        status_count_list = np.array(status_count_list).T\n        colors = np.array([\"#227a00\",\"#a5c279\",\"#f3d248\",\"#6956cb\",\"#79262a\",\"#b80033\",'black'])\n        labels = np.array(['LC', 'NT', 'VU', 'EN', 'CR', 'EX', 'DD'])\n        def func(pct, allvals):\n            absolute = int(np.round((pct/100.*np.sum(allvals))))\n            return \"{:d}\".format(absolute)\n        fig, axs = plt.subplots(1, 3,figsize=(12,10))\n        # status distribution beginning\n        wedges, texts, autotexts =axs[1].pie(status_count_list[1][status_count_list[1] >0], colors= colors[status_count_list[1] >0], autopct=lambda pct: func(pct, status_count_list[1][status_count_list[1] >0]), shadow=False,textprops=dict(color=\"w\"))\n        # status distribution end\n        wedges, texts, autotexts =axs[2].pie(status_count_list[2][status_count_list[2] >0], colors= colors[status_count_list[2] >0], autopct=lambda pct: func(pct, status_count_list[2][status_count_list[2] >0]), shadow=False,textprops=dict(color=\"w\"))\n        ext = wedges[-1]\n        # status distribution pre-dd\n        wedges, texts, autotexts =axs[0].pie(status_count_list[0][status_count_list[0] >0], colors= colors[status_count_list[0] >0], autopct=lambda pct: func(pct, status_count_list[0][status_count_list[0] >0]), shadow=False,textprops=dict(color=\"w\"))\n        axs[0].set_title('Current (including DD)')\n        axs[1].set_title('Current (DD corrected)')\n        axs[2].set_title('Final (%i years)'%delta_t)\n        final_labels = list(labels[status_count_list[0] >0]) + ['EX']\n        plt.legend(wedges+[ext], final_labels,title=\"IUCN status\\n(N=%i sp.)\"%status_count_list[2].sum(),loc=\"center left\",bbox_to_anchor=(1, 0, 0.5, 1))\n        fig.savefig(os.path.join(outdir,'status_pie_chart.pdf'),bbox_inches='tight', dpi = 500)\n    #__________________________________________________________________________   \n\n\n\n\n    #__________________________________________________________________________   \n    if extinction_rates:\n        # calculate some extinction stats\n        # estimate extinction rates scaled by year\n        print('\\nRunning %i MCMCs to estimate species-specific extinction rates from simulation output...'%len(species_list))\n        #ext_date_data = ext_date_data[:10,:]\n        if plot_posterior:\n            with PdfPages(os.path.join(outdir,'posterior_ext_rate_histograms.pdf')) as pdf:\n                sampled_rates = np.array([get_rate_estimate(species_values,n_years,i,sim_species_list,plot_posterior=plot_posterior,pdf=pdf,n_gen=n_gen,burnin=burnin) for i,species_values in enumerate(ext_date_data)])\n        else:\n            sampled_rates = np.array([get_rate_estimate(species_values,n_years,i,sim_species_list,plot_posterior=plot_posterior,pdf=0,n_gen=n_gen,burnin=burnin) for i,species_values in enumerate(ext_date_data)])\n        # export extinction stats to file\n        column_names = ['species','rate_e_mean','rate_e_lower','rate_e_upper','simulated_p_e_in_%i_years'%delta_t]\n        extinction_prob_df = pd.DataFrame(np.array([sim_species_list,sampled_rates[:,0],sampled_rates[:,1],sampled_rates[:,2],extinction_prob]).T,columns=column_names)\n    else:\n        column_names = ['species','simulated_p_e_in_%i_years'%delta_t]\n        extinction_prob_df = pd.DataFrame(np.array([sim_species_list,extinction_prob]).T,columns=column_names)        \n    extinction_prob_df[column_names[1:]] = extinction_prob_df[column_names[1:]].astype(float)\n    extinction_prob_df.to_csv(os.path.join(outdir,'extinction_prob_all_species.txt'),sep='\\t',index=False,float_format='%.8f')\n    print('\\n')\n    #__________________________________________________________________________   \n\n\n\n\n    #__________________________________________________________________________   \n    if plot_histograms:\n        # plot histograms of extinction times\n        with PdfPages(os.path.join(outdir,'extinction_time_histograms.pdf')) as pdf:\n            for i,species in enumerate(te_array[:,0]):\n                sys.stdout.write('\\rPlotting extinction histogram for species %i/%i'%(i+1,len(te_array[:,0])))\n                plt.figure()\n                species_te_array = te_array[:,1:][i]\n                not_na_values = species_te_array[~np.isnan(list(species_te_array))]\n                heights, bins = np.histogram(not_na_values,np.arange(0,delta_t+10,10))\n                percent = heights/n_sim\n                plt.bar(bins[:-1],percent,width=10, align=\"edge\")\n                plt.ylim(0,0.5)\n                #survival_prob = 1-sum(percent)\n                #if survival_prob >= 0.5:\n                #    text_color = 'green'\n                #else:\n                #    text_color = 'red'\n                ax = plt.gca()\n                #plt.text(0.05, 0.7, 'survival probability: %.2f'%survival_prob,color=text_color, horizontalalignment='left',verticalalignment='baseline', transform=ax.transAxes)\n                # annotate last bar            \n                if ax.patches[-1].get_height() > 0:\n                    ax.text(ax.patches[-1].get_x()+3, np.round(ax.patches[-1].get_height()+0.001,4), '**', fontsize=12, color='black')\n                plt.title('%s - Extinct in %i years: %i/%i'%(species,delta_t,sum(heights),n_sim))\n                plt.xlabel('Years from present')\n                plt.ylabel('Fraction of simulations')\n                plt.tight_layout()\n                pdf.savefig()  # saves the current figure into a pdf page\n                plt.close()\n    print('\\n')\n    #__________________________________________________________________________   \n\n\n\n\n        \n", "meta": {"hexsha": "a1714bca427aa15eb97e9f307f7ea8b613514509", "size": 24694, "ext": "py", "lang": "Python", "max_stars_repo_path": "iucn_sim/misc/run_sim.py", "max_stars_repo_name": "tobiashofmann88/iucn_extinction_simulator", "max_stars_repo_head_hexsha": "9953be13637fbc9c5ec629700dc1d4ee9ad8225c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-06-18T11:34:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-25T17:38:52.000Z", "max_issues_repo_path": "iucn_sim/misc/run_sim.py", "max_issues_repo_name": "tobiashofmann88/iucn_extinction_simulator", "max_issues_repo_head_hexsha": "9953be13637fbc9c5ec629700dc1d4ee9ad8225c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "iucn_sim/misc/run_sim.py", "max_forks_repo_name": "tobiashofmann88/iucn_extinction_simulator", "max_forks_repo_head_hexsha": "9953be13637fbc9c5ec629700dc1d4ee9ad8225c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-05T19:00:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-09T21:07:45.000Z", "avg_line_length": 48.6102362205, "max_line_length": 393, "alphanum_fraction": 0.685065198, "include": true, "reason": "import numpy", "num_tokens": 5899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.19663464749282641}}
{"text": "# Copyright 2002 Gary Strangman.  All rights reserved\n# Copyright 2002-2016 The SciPy Developers\n#\n# The original code from Gary Strangman was heavily adapted for\n# use in SciPy by Travis Oliphant.  The original code came with the\n# following disclaimer:\n#\n# This software is provided \"as-is\".  There are no expressed or implied\n# warranties of any kind, including, but not limited to, the warranties\n# of merchantability and fitness for a given application.  In no event\n# shall Gary Strangman be liable for any direct, indirect, incidental,\n# special, exemplary or consequential damages (including, but not limited\n# to, loss of use, data or profits, or business interruption) however\n# caused and on any theory of liability, whether in contract, strict\n# liability or tort (including negligence or otherwise) arising in any way\n# out of the use of this software, even if advised of the possibility of\n# such damage.\n\n\"\"\"\nA collection of basic statistical functions for Python.\n\nReferences\n----------\n.. [CRCProbStat2000] Zwillinger, D. and Kokoska, S. (2000). CRC Standard\n   Probability and Statistics Tables and Formulae. Chapman & Hall: New\n   York. 2000.\n\n\"\"\"\nimport warnings\nimport math\nfrom math import gcd\nfrom collections import namedtuple\n\nimport numpy as np\nfrom numpy import array, asarray, ma\n\nfrom scipy.spatial.distance import cdist\nfrom scipy.ndimage import measurements\nfrom scipy._lib._util import (check_random_state, MapWrapper,\n                              rng_integers, float_factorial)\nimport scipy.special as special\nfrom scipy import linalg\nfrom scipy.stats import distributions\n\n\n\n# Functions/classes in other files should be added in `__init__.py`, not here\n__all__ = ['find_repeats', 'gmean', 'hmean', 'mode', 'tmean', 'tvar',\n           'tmin', 'tmax', 'tstd', 'tsem', 'moment', 'variation',\n           'skew', 'kurtosis', 'describe', 'skewtest', 'kurtosistest',\n           'normaltest', 'jarque_bera', 'itemfreq',\n           'scoreatpercentile', 'percentileofscore',\n           'cumfreq', 'relfreq', 'obrientransform',\n           'sem', 'zmap', 'zscore', 'iqr', 'gstd', 'median_absolute_deviation',\n           'median_abs_deviation',\n           'sigmaclip', 'trimboth', 'trim1', 'trim_mean',\n           'f_oneway', 'F_onewayConstantInputWarning',\n           'F_onewayBadInputSizesWarning',\n           'PearsonRConstantInputWarning', 'PearsonRNearConstantInputWarning',\n           'pearsonr', 'fisher_exact',\n           'SpearmanRConstantInputWarning', 'spearmanr', 'pointbiserialr',\n           'kendalltau', 'weightedtau', 'multiscale_graphcorr',\n           'linregress', 'siegelslopes', 'theilslopes', 'ttest_1samp',\n           'ttest_ind', 'ttest_ind_from_stats', 'ttest_rel',\n           'kstest', 'ks_1samp', 'ks_2samp',\n           'chisquare', 'power_divergence',\n           'tiecorrect', 'ranksums', 'kruskal', 'friedmanchisquare',\n           'rankdata',\n           'combine_pvalues', 'wasserstein_distance', 'energy_distance',\n           'brunnermunzel', 'alexandergovern']\n\n\ndef _contains_nan(a, nan_policy='propagate'):\n    policies = ['propagate', 'raise', 'omit']\n    if nan_policy not in policies:\n        raise ValueError(\"nan_policy must be one of {%s}\" %\n                         ', '.join(\"'%s'\" % s for s in policies))\n    try:\n        # Calling np.sum to avoid creating a huge array into memory\n        # e.g. np.isnan(a).any()\n        with np.errstate(invalid='ignore'):\n            contains_nan = np.isnan(np.sum(a))\n    except TypeError:\n        # This can happen when attempting to sum things which are not\n        # numbers (e.g. as in the function `mode`). Try an alternative method:\n        try:\n            contains_nan = np.nan in set(a.ravel())\n        except TypeError:\n            # Don't know what to do. Fall back to omitting nan values and\n            # issue a warning.\n            contains_nan = False\n            nan_policy = 'omit'\n            warnings.warn(\"The input array could not be properly \"\n                          \"checked for nan values. nan values \"\n                          \"will be ignored.\", RuntimeWarning)\n\n    if contains_nan and nan_policy == 'raise':\n        raise ValueError(\"The input contains nan values\")\n\n    return contains_nan, nan_policy\n\n\ndef _chk_asarray(a, axis):\n    if axis is None:\n        a = np.ravel(a)\n        outaxis = 0\n    else:\n        a = np.asarray(a)\n        outaxis = axis\n\n    if a.ndim == 0:\n        a = np.atleast_1d(a)\n\n    return a, outaxis\n\n\ndef _chk2_asarray(a, b, axis):\n    if axis is None:\n        a = np.ravel(a)\n        b = np.ravel(b)\n        outaxis = 0\n    else:\n        a = np.asarray(a)\n        b = np.asarray(b)\n        outaxis = axis\n\n    if a.ndim == 0:\n        a = np.atleast_1d(a)\n    if b.ndim == 0:\n        b = np.atleast_1d(b)\n\n    return a, b, outaxis\n\n\ndef _shape_with_dropped_axis(a, axis):\n    \"\"\"\n    Given an array `a` and an integer `axis`, return the shape\n    of `a` with the `axis` dimension removed.\n\n    Examples\n    --------\n    >>> a = np.zeros((3, 5, 2))\n    >>> _shape_with_dropped_axis(a, 1)\n    (3, 2)\n\n    \"\"\"\n    shp = list(a.shape)\n    try:\n        del shp[axis]\n    except IndexError:\n        raise np.AxisError(axis, a.ndim) from None\n    return tuple(shp)\n\n\ndef _broadcast_shapes(shape1, shape2):\n    \"\"\"\n    Given two shapes (i.e. tuples of integers), return the shape\n    that would result from broadcasting two arrays with the given\n    shapes.\n\n    Examples\n    --------\n    >>> _broadcast_shapes((2, 1), (4, 1, 3))\n    (4, 2, 3)\n    \"\"\"\n    d = len(shape1) - len(shape2)\n    if d <= 0:\n        shp1 = (1,)*(-d) + shape1\n        shp2 = shape2\n    else:\n        shp1 = shape1\n        shp2 = (1,)*d + shape2\n    shape = []\n    for n1, n2 in zip(shp1, shp2):\n        if n1 == 1:\n            n = n2\n        elif n2 == 1 or n1 == n2:\n            n = n1\n        else:\n            raise ValueError(f'shapes {shape1} and {shape2} could not be '\n                             'broadcast together')\n        shape.append(n)\n    return tuple(shape)\n\n\ndef _broadcast_shapes_with_dropped_axis(a, b, axis):\n    \"\"\"\n    Given two arrays `a` and `b` and an integer `axis`, find the\n    shape of the broadcast result after dropping `axis` from the\n    shapes of `a` and `b`.\n\n    Examples\n    --------\n    >>> a = np.zeros((5, 2, 1))\n    >>> b = np.zeros((1, 9, 3))\n    >>> _broadcast_shapes_with_dropped_axis(a, b, 1)\n    (5, 3)\n    \"\"\"\n    shp1 = _shape_with_dropped_axis(a, axis)\n    shp2 = _shape_with_dropped_axis(b, axis)\n    try:\n        shp = _broadcast_shapes(shp1, shp2)\n    except ValueError:\n        raise ValueError(f'non-axis shapes {shp1} and {shp2} could not be '\n                         'broadcast together') from None\n    return shp\n\n# Map from names to lambda_ values used in power_divergence().\n_power_div_lambda_names = {\n    \"pearson\": 1,\n    \"log-likelihood\": 0,\n    \"freeman-tukey\": -0.5,\n    \"mod-log-likelihood\": -1,\n    \"neyman\": -2,\n    \"cressie-read\": 2/3,\n}\n\n\ndef _count(a, axis=None):\n    \"\"\"Count the number of non-masked elements of an array.\n\n    This function behaves like `np.ma.count`, but is much faster\n    for ndarrays.\n    \"\"\"\n    if hasattr(a, 'count'):\n        num = a.count(axis=axis)\n        if isinstance(num, np.ndarray) and num.ndim == 0:\n            # In some cases, the `count` method returns a scalar array (e.g.\n            # np.array(3)), but we want a plain integer.\n            num = int(num)\n    else:\n        if axis is None:\n            num = a.size\n        else:\n            num = a.shape[axis]\n    return num\n\n\ndef _m_broadcast_to(a, shape):\n    if np.ma.isMaskedArray(a):\n        return np.ma.masked_array(np.broadcast_to(a, shape),\n                                  mask=np.broadcast_to(a.mask, shape))\n    return np.broadcast_to(a, shape, subok=True)\n\nPower_divergenceResult = namedtuple('Power_divergenceResult',\n                                    ('statistic', 'pvalue'))\n\ndef power_divergence(f_obs, f_exp=None, ddof=0, axis=0, lambda_=None):\n    \"\"\"Cressie-Read power divergence statistic and goodness of fit test.\n\n    This function tests the null hypothesis that the categorical data\n    has the given frequencies, using the Cressie-Read power divergence\n    statistic.\n\n    Parameters\n    ----------\n    f_obs : array_like\n        Observed frequencies in each category.\n    f_exp : array_like, optional\n        Expected frequencies in each category.  By default the categories are\n        assumed to be equally likely.\n    ddof : int, optional\n        \"Delta degrees of freedom\": adjustment to the degrees of freedom\n        for the p-value.  The p-value is computed using a chi-squared\n        distribution with ``k - 1 - ddof`` degrees of freedom, where `k`\n        is the number of observed frequencies.  The default value of `ddof`\n        is 0.\n    axis : int or None, optional\n        The axis of the broadcast result of `f_obs` and `f_exp` along which to\n        apply the test.  If axis is None, all values in `f_obs` are treated\n        as a single data set.  Default is 0.\n    lambda_ : float or str, optional\n        The power in the Cressie-Read power divergence statistic.  The default\n        is 1.  For convenience, `lambda_` may be assigned one of the following\n        strings, in which case the corresponding numerical value is used::\n\n            String              Value   Description\n            \"pearson\"             1     Pearson's chi-squared statistic.\n                                        In this case, the function is\n                                        equivalent to `stats.chisquare`.\n            \"log-likelihood\"      0     Log-likelihood ratio. Also known as\n                                        the G-test [3]_.\n            \"freeman-tukey\"      -1/2   Freeman-Tukey statistic.\n            \"mod-log-likelihood\" -1     Modified log-likelihood ratio.\n            \"neyman\"             -2     Neyman's statistic.\n            \"cressie-read\"        2/3   The power recommended in [5]_.\n\n    Returns\n    -------\n    statistic : float or ndarray\n        The Cressie-Read power divergence test statistic.  The value is\n        a float if `axis` is None or if` `f_obs` and `f_exp` are 1-D.\n    pvalue : float or ndarray\n        The p-value of the test.  The value is a float if `ddof` and the\n        return value `stat` are scalars.\n\n    See Also\n    --------\n    chisquare\n\n    Notes\n    -----\n    This test is invalid when the observed or expected frequencies in each\n    category are too small.  A typical rule is that all of the observed\n    and expected frequencies should be at least 5.\n\n    Also, the sum of the observed and expected frequencies must be the same\n    for the test to be valid; `power_divergence` raises an error if the sums\n    do not agree within a relative tolerance of ``1e-8``.\n\n    When `lambda_` is less than zero, the formula for the statistic involves\n    dividing by `f_obs`, so a warning or error may be generated if any value\n    in `f_obs` is 0.\n\n    Similarly, a warning or error may be generated if any value in `f_exp` is\n    zero when `lambda_` >= 0.\n\n    The default degrees of freedom, k-1, are for the case when no parameters\n    of the distribution are estimated. If p parameters are estimated by\n    efficient maximum likelihood then the correct degrees of freedom are\n    k-1-p. If the parameters are estimated in a different way, then the\n    dof can be between k-1-p and k-1. However, it is also possible that\n    the asymptotic distribution is not a chisquare, in which case this\n    test is not appropriate.\n\n    This function handles masked arrays.  If an element of `f_obs` or `f_exp`\n    is masked, then data at that position is ignored, and does not count\n    towards the size of the data set.\n\n    .. versionadded:: 0.13.0\n\n    References\n    ----------\n    .. [1] Lowry, Richard.  \"Concepts and Applications of Inferential\n           Statistics\". Chapter 8.\n           https://web.archive.org/web/20171015035606/http://faculty.vassar.edu/lowry/ch8pt1.html\n    .. [2] \"Chi-squared test\", https://en.wikipedia.org/wiki/Chi-squared_test\n    .. [3] \"G-test\", https://en.wikipedia.org/wiki/G-test\n    .. [4] Sokal, R. R. and Rohlf, F. J. \"Biometry: the principles and\n           practice of statistics in biological research\", New York: Freeman\n           (1981)\n    .. [5] Cressie, N. and Read, T. R. C., \"Multinomial Goodness-of-Fit\n           Tests\", J. Royal Stat. Soc. Series B, Vol. 46, No. 3 (1984),\n           pp. 440-464.\n\n    Examples\n    --------\n    (See `chisquare` for more examples.)\n\n    When just `f_obs` is given, it is assumed that the expected frequencies\n    are uniform and given by the mean of the observed frequencies.  Here we\n    perform a G-test (i.e. use the log-likelihood ratio statistic):\n\n    >>> from scipy.stats import power_divergence\n    >>> power_divergence([16, 18, 16, 14, 12, 12], lambda_='log-likelihood')\n    (2.006573162632538, 0.84823476779463769)\n\n    The expected frequencies can be given with the `f_exp` argument:\n\n    >>> power_divergence([16, 18, 16, 14, 12, 12],\n    ...                  f_exp=[16, 16, 16, 16, 16, 8],\n    ...                  lambda_='log-likelihood')\n    (3.3281031458963746, 0.6495419288047497)\n\n    When `f_obs` is 2-D, by default the test is applied to each column.\n\n    >>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T\n    >>> obs.shape\n    (6, 2)\n    >>> power_divergence(obs, lambda_=\"log-likelihood\")\n    (array([ 2.00657316,  6.77634498]), array([ 0.84823477,  0.23781225]))\n\n    By setting ``axis=None``, the test is applied to all data in the array,\n    which is equivalent to applying the test to the flattened array.\n\n    >>> power_divergence(obs, axis=None)\n    (23.31034482758621, 0.015975692534127565)\n    >>> power_divergence(obs.ravel())\n    (23.31034482758621, 0.015975692534127565)\n\n    `ddof` is the change to make to the default degrees of freedom.\n\n    >>> power_divergence([16, 18, 16, 14, 12, 12], ddof=1)\n    (2.0, 0.73575888234288467)\n\n    The calculation of the p-values is done by broadcasting the\n    test statistic with `ddof`.\n\n    >>> power_divergence([16, 18, 16, 14, 12, 12], ddof=[0,1,2])\n    (2.0, array([ 0.84914504,  0.73575888,  0.5724067 ]))\n\n    `f_obs` and `f_exp` are also broadcast.  In the following, `f_obs` has\n    shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting\n    `f_obs` and `f_exp` has shape (2, 6).  To compute the desired chi-squared\n    statistics, we must use ``axis=1``:\n\n    >>> power_divergence([16, 18, 16, 14, 12, 12],\n    ...                  f_exp=[[16, 16, 16, 16, 16, 8],\n    ...                         [8, 20, 20, 16, 12, 12]],\n    ...                  axis=1)\n    (array([ 3.5 ,  9.25]), array([ 0.62338763,  0.09949846]))\n\n    \"\"\"\n    # Convert the input argument `lambda_` to a numerical value.\n    if isinstance(lambda_, str):\n        if lambda_ not in _power_div_lambda_names:\n            names = repr(list(_power_div_lambda_names.keys()))[1:-1]\n            raise ValueError(\"invalid string for lambda_: {0!r}. \"\n                             \"Valid strings are {1}\".format(lambda_, names))\n        lambda_ = _power_div_lambda_names[lambda_]\n    elif lambda_ is None:\n        lambda_ = 1\n\n    f_obs = np.asanyarray(f_obs)\n    f_obs_float = f_obs.astype(np.float64)\n\n    if f_exp is not None:\n        f_exp = np.asanyarray(f_exp)\n        bshape = _broadcast_shapes(f_obs_float.shape, f_exp.shape)\n        f_obs_float = _m_broadcast_to(f_obs_float, bshape)\n        f_exp = _m_broadcast_to(f_exp, bshape)\n        rtol = 1e-2  # to pass existing tests #EDIT from 1e-8 to 1e-2\n        with np.errstate(invalid='ignore'):\n            f_obs_sum = f_obs_float.sum(axis=axis)\n            f_exp_sum = f_exp.sum(axis=axis)\n            relative_diff = (np.abs(f_obs_sum - f_exp_sum) /\n                             np.minimum(f_obs_sum, f_exp_sum))\n            diff_gt_tol = (relative_diff > rtol).any()\n        if diff_gt_tol:\n            msg = (f\"For each axis slice, the sum of the observed \"\n                   f\"frequencies must agree with the sum of the \"\n                   f\"expected frequencies to a relative tolerance \"\n                   f\"of {rtol}, but the percent differences are:\\n\"\n                   f\"{relative_diff}\")\n            raise ValueError(msg)\n\n    else:\n        # Ignore 'invalid' errors so the edge case of a data set with length 0\n        # is handled without spurious warnings.\n        with np.errstate(invalid='ignore'):\n            f_exp = f_obs.mean(axis=axis, keepdims=True)\n\n    # `terms` is the array of terms that are summed along `axis` to create\n    # the test statistic.  We use some specialized code for a few special\n    # cases of lambda_.\n    if lambda_ == 1:\n        # Pearson's chi-squared statistic\n        terms = (f_obs_float - f_exp)**2 / f_exp\n    elif lambda_ == 0:\n        # Log-likelihood ratio (i.e. G-test)\n        terms = 2.0 * special.xlogy(f_obs, f_obs / f_exp)\n    elif lambda_ == -1:\n        # Modified log-likelihood ratio\n        terms = 2.0 * special.xlogy(f_exp, f_exp / f_obs)\n    else:\n        # General Cressie-Read power divergence.\n        terms = f_obs * ((f_obs / f_exp)**lambda_ - 1)\n        terms /= 0.5 * lambda_ * (lambda_ + 1)\n\n    stat = terms.sum(axis=axis)\n\n    num_obs = _count(terms, axis=axis)\n    ddof = asarray(ddof)\n    p = distributions.chi2.sf(stat, num_obs - 1 - ddof)\n\n    return Power_divergenceResult(stat, p)\n\n\ndef chisquare(f_obs, f_exp=None, ddof=0, axis=0):\n    \"\"\"Calculate a one-way chi-square test.\n\n    The chi-square test tests the null hypothesis that the categorical data\n    has the given frequencies.\n\n    Parameters\n    ----------\n    f_obs : array_like\n        Observed frequencies in each category.\n    f_exp : array_like, optional\n        Expected frequencies in each category.  By default the categories are\n        assumed to be equally likely.\n    ddof : int, optional\n        \"Delta degrees of freedom\": adjustment to the degrees of freedom\n        for the p-value.  The p-value is computed using a chi-squared\n        distribution with ``k - 1 - ddof`` degrees of freedom, where `k`\n        is the number of observed frequencies.  The default value of `ddof`\n        is 0.\n    axis : int or None, optional\n        The axis of the broadcast result of `f_obs` and `f_exp` along which to\n        apply the test.  If axis is None, all values in `f_obs` are treated\n        as a single data set.  Default is 0.\n\n    Returns\n    -------\n    chisq : float or ndarray\n        The chi-squared test statistic.  The value is a float if `axis` is\n        None or `f_obs` and `f_exp` are 1-D.\n    p : float or ndarray\n        The p-value of the test.  The value is a float if `ddof` and the\n        return value `chisq` are scalars.\n\n    See Also\n    --------\n    scipy.stats.power_divergence\n    scipy.stats.fisher_exact : Fisher exact test on a 2x2 contingency table.\n    scipy.stats.barnard_exact : An unconditional exact test. An alternative\n        to chi-squared test for small sample sizes.\n\n    Notes\n    -----\n    This test is invalid when the observed or expected frequencies in each\n    category are too small.  A typical rule is that all of the observed\n    and expected frequencies should be at least 5. According to [3]_, the\n    total number of samples is recommended to be greater than 13,\n    otherwise exact tests (such as Barnard's Exact test) should be used\n    because they do not overreject.\n\n    Also, the sum of the observed and expected frequencies must be the same\n    for the test to be valid; `chisquare` raises an error if the sums do not\n    agree within a relative tolerance of ``1e-8``.\n\n    The default degrees of freedom, k-1, are for the case when no parameters\n    of the distribution are estimated. If p parameters are estimated by\n    efficient maximum likelihood then the correct degrees of freedom are\n    k-1-p. If the parameters are estimated in a different way, then the\n    dof can be between k-1-p and k-1. However, it is also possible that\n    the asymptotic distribution is not chi-square, in which case this test\n    is not appropriate.\n\n    References\n    ----------\n    .. [1] Lowry, Richard.  \"Concepts and Applications of Inferential\n           Statistics\". Chapter 8.\n           https://web.archive.org/web/20171022032306/http://vassarstats.net:80/textbook/ch8pt1.html\n    .. [2] \"Chi-squared test\", https://en.wikipedia.org/wiki/Chi-squared_test\n    .. [3] Pearson, Karl. \"On the criterion that a given system of deviations from the probable\n           in the case of a correlated system of variables is such that it can be reasonably\n           supposed to have arisen from random sampling\", Philosophical Magazine. Series 5. 50\n           (1900), pp. 157-175.\n\n    Examples\n    --------\n    When just `f_obs` is given, it is assumed that the expected frequencies\n    are uniform and given by the mean of the observed frequencies.\n\n    >>> from scipy.stats import chisquare\n    >>> chisquare([16, 18, 16, 14, 12, 12])\n    (2.0, 0.84914503608460956)\n\n    With `f_exp` the expected frequencies can be given.\n\n    >>> chisquare([16, 18, 16, 14, 12, 12], f_exp=[16, 16, 16, 16, 16, 8])\n    (3.5, 0.62338762774958223)\n\n    When `f_obs` is 2-D, by default the test is applied to each column.\n\n    >>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T\n    >>> obs.shape\n    (6, 2)\n    >>> chisquare(obs)\n    (array([ 2.        ,  6.66666667]), array([ 0.84914504,  0.24663415]))\n\n    By setting ``axis=None``, the test is applied to all data in the array,\n    which is equivalent to applying the test to the flattened array.\n\n    >>> chisquare(obs, axis=None)\n    (23.31034482758621, 0.015975692534127565)\n    >>> chisquare(obs.ravel())\n    (23.31034482758621, 0.015975692534127565)\n\n    `ddof` is the change to make to the default degrees of freedom.\n\n    >>> chisquare([16, 18, 16, 14, 12, 12], ddof=1)\n    (2.0, 0.73575888234288467)\n\n    The calculation of the p-values is done by broadcasting the\n    chi-squared statistic with `ddof`.\n\n    >>> chisquare([16, 18, 16, 14, 12, 12], ddof=[0,1,2])\n    (2.0, array([ 0.84914504,  0.73575888,  0.5724067 ]))\n\n    `f_obs` and `f_exp` are also broadcast.  In the following, `f_obs` has\n    shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting\n    `f_obs` and `f_exp` has shape (2, 6).  To compute the desired chi-squared\n    statistics, we use ``axis=1``:\n\n    >>> chisquare([16, 18, 16, 14, 12, 12],\n    ...           f_exp=[[16, 16, 16, 16, 16, 8], [8, 20, 20, 16, 12, 12]],\n    ...           axis=1)\n    (array([ 3.5 ,  9.25]), array([ 0.62338763,  0.09949846]))\n\n    \"\"\"\n    return power_divergence(f_obs, f_exp=f_exp, ddof=ddof, axis=axis,\n                            lambda_=\"pearson\")\n\n\n\ndef _sum_of_squares(a, axis=0):\n    \"\"\"Square each element of the input array, and return the sum(s) of that.\n\n    Parameters\n    ----------\n    a : array_like\n        Input array.\n    axis : int or None, optional\n        Axis along which to calculate. Default is 0. If None, compute over\n        the whole array `a`.\n\n    Returns\n    -------\n    sum_of_squares : ndarray\n        The sum along the given axis for (a**2).\n\n    See Also\n    --------\n    _square_of_sums : The square(s) of the sum(s) (the opposite of\n        `_sum_of_squares`).\n\n    \"\"\"\n    a, axis = _chk_asarray(a, axis)\n    return np.sum(a*a, axis)\n\n\ndef _square_of_sums(a, axis=0):\n    \"\"\"Sum elements of the input array, and return the square(s) of that sum.\n\n    Parameters\n    ----------\n    a : array_like\n        Input array.\n    axis : int or None, optional\n        Axis along which to calculate. Default is 0. If None, compute over\n        the whole array `a`.\n\n    Returns\n    -------\n    square_of_sums : float or ndarray\n        The square of the sum over `axis`.\n\n    See Also\n    --------\n    _sum_of_squares : The sum of squares (the opposite of `square_of_sums`).\n\n    \"\"\"\n    a, axis = _chk_asarray(a, axis)\n    s = np.sum(a, axis)\n    if not np.isscalar(s):\n        return s.astype(float) * s\n    else:\n        return float(s) * s\n", "meta": {"hexsha": "ce2caa4d38fbef56eedbd853f987be27a53ae586", "size": 24030, "ext": "py", "lang": "Python", "max_stars_repo_path": "stats_modified.py", "max_stars_repo_name": "seamanticscience/Benfords-law", "max_stars_repo_head_hexsha": "3e59ca7dc16ac6657048ee9703e6bb1896cc7277", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stats_modified.py", "max_issues_repo_name": "seamanticscience/Benfords-law", "max_issues_repo_head_hexsha": "3e59ca7dc16ac6657048ee9703e6bb1896cc7277", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stats_modified.py", "max_forks_repo_name": "seamanticscience/Benfords-law", "max_forks_repo_head_hexsha": "3e59ca7dc16ac6657048ee9703e6bb1896cc7277", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9124423963, "max_line_length": 100, "alphanum_fraction": 0.6200998752, "include": true, "reason": "import numpy,from numpy,import scipy,from scipy", "num_tokens": 6611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3812195803163617, "lm_q1q2_score": 0.1965644078746858}}
{"text": "#!/usr/bin/env python\n#This script plots drag around an inline oscillating cylinder for re 200 kc 10 against dutsch et als work at cycle 14\nimport argparse\nimport os\nimport os.path\nimport sys\nimport csv\nimport matplotlib\nfrom matplotlib import pyplot as plt\nimport numpy\n\ncuibmFolder = os.path.expandvars(\"/scratch/src/cuIBM\")\n\nvalidationData = '/osc_Re200_KC10_Dutsch.txt'\n\nexecPath       = cuibmFolder + '/bin/cuIBM'\ncaseFolder     = cuibmFolder + '/validation/osc/static'\nvalidationData = cuibmFolder + '/validation-data' + validationData\n\nprint \"\\n\"+\"-\"*100\nprint \"Plotting validation for flow around inline oscillating cylinder with Re200 and KC10\\n\"\nprint \"-\"*100+\"\\n\"\n\nexperiment = numpy.genfromtxt(validationData,delimiter='\\t')\nexternal = numpy.genfromtxt(caseFolder+'/externalkc10/forces',delimiter='\\t')\nembedded = numpy.genfromtxt(caseFolder+'/embeddedkc10/forces',delimiter='\\t')\n\n#external\nplt.plot([i-13 for i in zip(*external)[0]],[i*5 for i in zip(*external)[1]],'-',color='blue',linewidth=2,label='External')\nplt.plot(zip(*experiment)[0],zip(*experiment)[1],'o', color = 'red', markersize = 8, label = 'Dutsch et al')\nplt.title('Drag for flow around inline oscillating cylinder Re 200, KC 10')\nplt.legend(loc='lower right',numpoints=1, fancybox=True)\nplt.xlabel('t/T')\nplt.ylabel('Fd')\nplt.ylim([-6,6])\nplt.xlim([0,1])\nplt.savefig('%s/External_static_kc10.pdf' % (caseFolder))\nplt.clf()\n\n#emb\nplt.plot([i-13 for i in zip(*embedded)[0]],[i*5 for i in zip(*embedded)[1]],'-',color='blue',linewidth=2,label='Embedded')\nplt.plot(zip(*experiment)[0],zip(*experiment)[1],'o', color = 'red', markersize = 8, label = 'Dutsch et al')\nplt.title('Drag for flow around inline oscillating cylinder Re 200, KC 10')\nplt.legend(loc='lower right',numpoints=1, fancybox=True)\nplt.xlabel('t/T')\nplt.ylabel('Fd')\nplt.ylim([-6,6])\nplt.xlim([0,1])\nplt.savefig('%s/Embedded_static_kc10.pdf' % (caseFolder))\nplt.clf()\n\n\nprint '\\nDone plotting!\\n Files saved to %s' % caseFolder\n", "meta": {"hexsha": "ccbc293e44f9e193c1aa8b2cc6e9c264d0cadafc", "size": 1972, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/validation/osc_Re200_KC10.py", "max_stars_repo_name": "Niemeyer-Research-Group/cuIBM", "max_stars_repo_head_hexsha": "0fa913a465e4f0f3432e0dbd4d3df9bc47905406", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-05T17:48:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-05T17:48:41.000Z", "max_issues_repo_path": "scripts/validation/osc_Re200_KC10.py", "max_issues_repo_name": "Niemeyer-Research-Group/cuIBM-FSI", "max_issues_repo_head_hexsha": "0fa913a465e4f0f3432e0dbd4d3df9bc47905406", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-05-11T16:04:33.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-12T01:40:27.000Z", "max_forks_repo_path": "scripts/validation/osc_Re200_KC10.py", "max_forks_repo_name": "Niemeyer-Research-Group/cuIBM-FSI", "max_forks_repo_head_hexsha": "0fa913a465e4f0f3432e0dbd4d3df9bc47905406", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-06T14:32:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-03T13:36:48.000Z", "avg_line_length": 36.5185185185, "max_line_length": 122, "alphanum_fraction": 0.7231237323, "include": true, "reason": "import numpy", "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19656440062496064}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"RGB color space.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import cast\nfrom typing import Union\n\nimport cv2\nimport numpy as np\nimport torch\nfrom multipledispatch import dispatch\nfrom torch import nn\nfrom torch import Tensor\n\nfrom onevision.cv.utils import batch_image_processing\nfrom onevision.cv.utils import channel_last_processing\nfrom onevision.factory import TRANSFORMS\nfrom onevision.type import TensorOrArray\n\n__all__ = [\n    \"bgr_to_rgb\",\n    \"bgr_to_rgba\",\n    \"linear_rgb_to_rgb\",\n    \"rgb_to_bgr\",\n    \"rgb_to_linear_rgb\",\n    \"rgb_to_rgba\",\n    \"rgba_to_bgr\",\n    \"rgba_to_rgb\",\n    \"BgrToRgb\",\n    \"BgrToRgba\",\n    \"LinearRgbToRgb\",\n    \"RgbaToBgr\",\n    \"RgbaToRgb\",\n    \"RgbToBgr\",\n    \"RgbToLinearRgb\",\n    \"RgbToRgba\"\n]\n\n\n# MARK: - Functional\n\n@dispatch(Tensor)\ndef bgr_to_rgb(image: Tensor) -> Tensor:\n    \"\"\"Convert a BGR image to RGB.\n\n    Args:\n        image (Tensor[B, 3, H, W]):\n            BGR Image to be converted to BGR.\n\n    Returns:\n        rgb (Tensor[B, 3, H, W]):\n            RGB version of the image.\n    \"\"\"\n    # Flip image channels\n    rgb = image.flip(-3)\n    return rgb\n\n\n@batch_image_processing\n@channel_last_processing\n@dispatch(np.ndarray)\ndef bgr_to_rgb(image: np.ndarray) -> np.ndarray:\n    \"\"\"Convert a BGR image to RGB.\n\n    Args:\n        image (np.ndarray[B, 3, H, W]):\n            BGR Image to be converted to BGR.\n\n    Returns:\n        rgb (np.ndarray[B, 3, H, W]):\n            RGB version of the image.\n    \"\"\"\n    return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n\n@dispatch(Tensor, (float, Tensor))\ndef bgr_to_rgba(image: Tensor, alpha_val: Union[float, Tensor]) -> Tensor:\n    \"\"\"Convert an image from BGR to RGBA.\n\n    Args:\n        image (Tensor[B, 3, H, W]):\n            BGR Image to be converted to RGBA.\n        alpha_val (float, Tensor[B, 1, H, W]):\n            A float number or tensor for the alpha value.\n\n    Returns:\n        rgba (Tensor[B, 4, H, W]):\n            RGBA version of the image.\n\n    Notes:\n        Current functionality is NOT supported by Torchscript.\n    \"\"\"\n    if not isinstance(alpha_val, (float, Tensor)):\n        raise TypeError(f\"`alpha_val` must be a `float` or `Tensor`. \"\n                        f\"But got: {type(alpha_val)}.\")\n  \n    # Convert first to RGB, then add alpha channel\n    rgb  = bgr_to_rgb(image)\n    rgba = rgb_to_rgba(rgb, alpha_val)\n\n    return rgba\n\n\n@batch_image_processing\n@channel_last_processing\n@dispatch(np.ndarray, (float, np.ndarray))\ndef bgr_to_rgba(image: np.ndarray, alpha_val: Union[float, np.ndarray]) -> np.ndarray:\n    \"\"\"Convert an image from BGR to RGBA.\n\n    Args:\n        image (np.ndarray[B, 3, H, W]):\n            BGR Image to be converted to RGBA.\n        alpha_val (float, np.ndarray[B, 1, H, W]):\n            A float number or tensor for the alpha value.\n\n    Returns:\n        rgba (np.ndarray[B, 4, H, W]):\n            RGBA version of the image.\n\n    Notes:\n        Current functionality is NOT supported by Torchscript.\n    \"\"\"\n    return cv2.cvtColor(image, cv2.COLOR_BGR2RGBA)\n\n\n@dispatch(Tensor)\ndef linear_rgb_to_rgb(image: Tensor) -> Tensor:\n    \"\"\"Convert a linear RGB image to sRGB. Used in colorspace conversions.\n\n    Args:\n        image (Tensor[B, 3, H, W]):\n            Linear RGB Image to be converted to sRGB.\n\n    Returns:\n        rgb (Tensor[B, 3, H, W]):\n            sRGB version of the image.\n    \"\"\"\n    threshold = 0.0031308\n    rgb       = torch.where(\n        image > threshold,\n        1.055 * torch.pow(image.clamp(min=threshold), 1 / 2.4) - 0.055,\n        12.92 * image\n    )\n    return rgb\n\n\ndef rgb_to_bgr(image: TensorOrArray) -> TensorOrArray:\n    \"\"\"Convert an RGB image to BGR.\n\n    Args:\n        image (TensorOrArray[B, 3, H, W]):\n            RGB Image to be converted to BGR.\n\n    Returns:\n        bgr (TensorOrArray[B, 3, H, W]):\n            BGR version of the image.\n    \"\"\"\n    return bgr_to_rgb(image)\n\n\n@dispatch(Tensor)\ndef rgb_to_linear_rgb(image: Tensor) -> Tensor:\n    \"\"\"Convert an sRGB image to linear RGB. Used in colorspace conversions.\n\n    Args:\n        image (Tensor[B, 3, H, W]):\n            sRGB Image to be converted to linear RGB.\n\n    Returns:\n        linear_rgb (Tensor[B, 3, H, W]):\n            linear RGB version of the image.\n    \"\"\"\n    lin_rgb = torch.where(\n        image > 0.04045,\n        torch.pow(((image + 0.055) / 1.055), 2.4),\n        image / 12.92\n    )\n    return lin_rgb\n\n\n@dispatch(Tensor, (float, Tensor))\ndef rgb_to_rgba(image: Tensor, alpha_val: Union[float, Tensor]) -> Tensor:\n    \"\"\"Convert an image from RGB to RGBA.\n\n    Args:\n        image (Tensor[B, 3, H, W]):\n            RGB Image to be converted to RGBA.\n        alpha_val (float, Tensor[B, 1, H, W]):\n            A float number or tensor for the alpha value.\n\n    Returns:\n        rgba (Tensor[B, 4, H, W]):\n            RGBA version of the image\n\n    Notes:\n        Current functionality is NOT supported by Torchscript.\n    \"\"\"\n    if not isinstance(alpha_val, (float, Tensor)):\n        raise TypeError(f\"`alpha_val` must be `float` or `Tensor`. \"\n                        f\"But got: {type(alpha_val)}.\")\n  \n    # Add one channel\n    r, g, b = torch.chunk(image, image.shape[-3], dim=-3)\n    a       = cast(Tensor, alpha_val)\n\n    if isinstance(alpha_val, float):\n        a = torch.full_like(r, fill_value=float(alpha_val))\n    rgba = torch.cat([r, g, b, a], dim=-3)\n\n    return rgba\n\n\n@batch_image_processing\n@channel_last_processing\n@dispatch(np.ndarray, (float, np.ndarray))\ndef rgb_to_rgba(image: np.ndarray, alpha_val: Union[float, np.ndarray]) -> np.ndarray:\n    \"\"\"Convert an image from RGB to RGBA.\n\n    Args:\n        image (np.ndarray[B, 3, H, W]):\n            RGB Image to be converted to RGBA.\n        alpha_val (float, np.ndarray[B, 1, H, W]):\n            A float number or tensor for the alpha value.\n\n    Returns:\n        rgba (np.ndarray[B, 4, H, W]):\n            RGBA version of the image\n\n    Notes:\n        Current functionality is NOT supported by Torchscript.\n    \"\"\"\n    return cv2.cvtColor(image, cv2.COLOR_RGB2RGBA)\n\n\n@dispatch(Tensor)\ndef rgba_to_bgr(image: Tensor) -> Tensor:\n    \"\"\"Convert an image from RGBA to BGR.\n\n    Args:\n        image (Tensor[B, 4, H, W]):\n            RGBA Image to be converted to BGR.\n\n    Returns:\n        rgb (Tensor[B, 3, H, W]):\n            RGB version of the image.\n    \"\"\"\n    if not isinstance(image, Tensor):\n        raise TypeError(f\"`image` must be a `Tensor`. But got: {type(image)}\")\n    if image.ndim < 3 or image.shape[-3] != 4:\n        raise ValueError(f\"`image` must have a shape of [*, 4, H, W]. \"\n                         f\"But got: {image.shape}\")\n\n    # Convert to RGB first, then to BGR\n    rgb = rgba_to_rgb(image)\n    bgr = rgb_to_bgr(rgb)\n    \n    return bgr\n\n\n@batch_image_processing\n@channel_last_processing\n@dispatch(np.ndarray)\ndef rgba_to_bgr(image: np.ndarray) -> np.ndarray:\n    \"\"\"Convert an image from RGBA to BGR.\n\n    Args:\n        image (np.ndarray[B, 4, H, W]):\n            RGBA Image to be converted to BGR.\n\n    Returns:\n        bgr (np.ndarray[B, 3, H, W]):\n            BGR version of the image.\n    \"\"\"\n    return cv2.cvtColor(image, cv2.COLOR_RGBA2BGR)\n\n\n@dispatch(Tensor)\ndef rgba_to_rgb(image: Tensor) -> Tensor:\n    \"\"\"Convert an image from RGBA to RGB.\n\n    Args:\n        image (Tensor[B, 4, H, W]):\n            RGBA Image to be converted to RGB.\n\n    Returns:\n        rgb (Tensor[B, 3, H, W]):\n            RGB version of the image.\n    \"\"\"\n    # Unpack channels\n    r, g, b, a = torch.chunk(image, image.shape[-3], dim=-3)\n\n    # Compute new channels\n    a_one = torch.tensor(1.0) - a\n    r_new = a_one * r + a * r\n    g_new = a_one * g + a * g\n    b_new = a_one * b + a * b\n    rgb   = torch.cat([r_new, g_new, b_new], dim=-3)\n\n    return rgb\n\n\n@batch_image_processing\n@channel_last_processing\n@dispatch(np.ndarray)\ndef rgba_to_rgb(image: np.ndarray) -> np.ndarray:\n    \"\"\"Convert an image from RGBA to RGB.\n\n    Args:\n        image (np.ndarray[B, 4, H, W]):\n            RGBA Image to be converted to RGB.\n\n    Returns:\n        rgb (np.ndarray[B, 3, H, W]):\n            RGB version of the image.\n    \"\"\"\n    return cv2.cvtColor(image, cv2.COLOR_RGBA2RGB)\n\n\n# MARK: - Modules\n\n@TRANSFORMS.register(name=\"bgr_to_rgb\")\nclass BgrToRgb(nn.Module):\n    \"\"\"Convert image from BGR to RGB. Image data is assumed to be in the\n    range of [0.0, 1.0].\n    \"\"\"\n\n    # MARK: Forward Pass\n    \n    def forward(self, image: TensorOrArray) -> TensorOrArray:\n        return bgr_to_rgb(image)\n\n\n@TRANSFORMS.register(name=\"bgr_to_rgba\")\nclass BgrToRgba(nn.Module):\n    \"\"\"Convert an image from BGR to RGBA. Add an alpha channel to existing RGB\n    image.\n\n    Args:\n        alpha_val (float, TensorOrArray[B, 1, H, W]):\n            A float number or tensor for the alpha value.\n \n    Notes:\n        Current functionality is NOT supported by Torchscript.\n    \"\"\"\n\n    # MARK: Magic Functions\n    \n    def __init__(self, alpha_val: Union[float, TensorOrArray]):\n        super().__init__()\n        self.alpha_val = alpha_val\n\n    # MARK: Forward Pass\n    \n    def forward(self, image: TensorOrArray) -> TensorOrArray:\n        return rgb_to_rgba(image, self.alpha_val)\n\n\n@TRANSFORMS.register(name=\"linear_rgb_to_rgb\")\nclass LinearRgbToRgb(nn.Module):\n    \"\"\"Convert a linear RGB image to sRGB. Applies gamma correction to linear\n    RGB values, at the end of colorspace conversions, to get sRGB.\n   \n    References:\n        [1] https://stackoverflow.com/questions/35952564/convert-rgb-to-srgb\n        [2] https://www.cambridgeincolour.com/tutorials/gamma-correction.htm\n        [3] https://en.wikipedia.org/wiki/SRGB\n    \"\"\"\n\n    # MARK: Forward Pass\n    \n    def forward(self, image: TensorOrArray) -> TensorOrArray:\n        return linear_rgb_to_rgb(image)\n\n\n@TRANSFORMS.register(name=\"rgb_to_bgr\")\nclass RgbToBgr(nn.Module):\n    \"\"\"Convert an image from RGB to BGR. Image data is assumed to be in the\n    range of [0.0, 1.0].\n    \"\"\"\n\n    # MARK: Forward Pass\n    \n    def forward(self, image: TensorOrArray) -> TensorOrArray:\n        return rgb_to_bgr(image)\n\n\n@TRANSFORMS.register(name=\"rgb_to_linear_rgb\")\nclass RgbToLinearRgb(nn.Module):\n    \"\"\"Convert an image from sRGB to linear RGB. Reverses the gamma correction\n    of sRGB to get linear RGB values for colorspace conversions. Image data\n    is assumed to be in the range of [0.0, 1.0].\n \n    References:\n        [1] https://stackoverflow.com/questions/35952564/convert-rgb-to-srgb\n        [2] https://www.cambridgeincolour.com/tutorials/gamma-correction.htm\n        [3] https://en.wikipedia.org/wiki/SRGB\n    \"\"\"\n\n    # MARK: Forward Pass\n    \n    def forward(self, image: TensorOrArray) -> TensorOrArray:\n        return rgb_to_linear_rgb(image)\n\n\n@TRANSFORMS.register(name=\"rgb_to_rgba\")\nclass RgbToRgba(nn.Module):\n    \"\"\"Convert an image from RGB to RGBA. Add an alpha channel to existing RGB\n    image.\n\n    Args:\n        alpha_val (float, TensorOrArray[B, 1, H, W]):\n            A float number or tensor for the alpha value.\n \n    Notes:\n        Current functionality is NOT supported by Torchscript.\n    \"\"\"\n\n    # MARK: Magic Functions\n    \n    def __init__(self, alpha_val: Union[float, TensorOrArray]) -> None:\n        super().__init__()\n        self.alpha_val = alpha_val\n\n    # MARK: Forward Pass\n    \n    def forward(self, image: TensorOrArray) -> TensorOrArray:\n        return rgb_to_rgba(image, self.alpha_val)\n\n\n@TRANSFORMS.register(name=\"rgba_to_bgr\")\nclass RgbaToBgr(nn.Module):\n    \"\"\"Convert an image from RGBA to BGR. Remove an alpha channel from BGR\n    image.\n    \"\"\"\n\n    # MARK: Forward Pass\n    \n    def forward(self, image: TensorOrArray) -> TensorOrArray:\n        return rgba_to_bgr(image)\n\n\n@TRANSFORMS.register(name=\"rgba_to_rgb\")\nclass RgbaToRgb(nn.Module):\n    \"\"\"Convert an image from RGBA to RGB. Remove an alpha channel from RGB\n    image.\n    \"\"\"\n\n    # MARK: Forward Pass\n    \n    def forward(self, image: TensorOrArray) -> TensorOrArray:\n        return rgba_to_rgb(image)\n", "meta": {"hexsha": "d01958d5bdff8057ec2a9bafa4da149c845a20eb", "size": 11971, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/onevision/cv/imgproc/color/rgb.py", "max_stars_repo_name": "phlong3105/onevision", "max_stars_repo_head_hexsha": "90552b64df7213e7fbe23c80ffd8a89583289433", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-28T09:46:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T14:12:32.000Z", "max_issues_repo_path": "src/onevision/cv/imgproc/color/rgb.py", "max_issues_repo_name": "phlong3105/onevision", "max_issues_repo_head_hexsha": "90552b64df7213e7fbe23c80ffd8a89583289433", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/onevision/cv/imgproc/color/rgb.py", "max_forks_repo_name": "phlong3105/onevision", "max_forks_repo_head_hexsha": "90552b64df7213e7fbe23c80ffd8a89583289433", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2521929825, "max_line_length": 86, "alphanum_fraction": 0.6218361039, "include": true, "reason": "import numpy", "num_tokens": 3159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19656440062496064}}
{"text": "import math\nfrom typing import Optional, Union, Tuple, List\n\nimport numpy as np\n\nimport torch\nimport torch.nn.functional as F\nfrom torch import Tensor\nfrom torch_geometric.utils.num_nodes import maybe_num_nodes\nfrom torch_scatter import scatter, segment_csr, gather_csr\nfrom torch_scatter.utils import broadcast\n\nimport tsl\n\n__all__ = [\n    'expand_then_cat',\n    'gated_tanh',\n    'reverse_tensor',\n    'sparse_softmax',\n    'sparse_multi_head_attention'\n]\n\n\ndef expand_then_cat(tensors: Union[Tuple[Tensor, ...], List[Tensor]],\n                    dim=-1) -> Tensor:\n    r\"\"\"\n    Match the dimensions of tensors in the input list and then concatenate.\n\n    Args:\n        tensors: Tensors to concatenate.\n        dim (int): Dimension along which to concatenate.\n    \"\"\"\n    shapes = [t.shape for t in tensors]\n    expand_dims = list(np.max(shapes, 0))\n    expand_dims[dim] = -1\n    tensors = [t.expand(*expand_dims) for t in tensors]\n    return torch.cat(tensors, dim=dim)\n\n\n@torch.jit.script\ndef gated_tanh(input: Tensor, dim: int = -1) -> Tensor:\n    r\"\"\"The gated tanh unite. Computes:\n\n    .. math ::\n        \\text{GatedTanH}(a, b) = \\text{TanH}(a) \\otimes \\sigma(b)\n\n    where `input` is split in half along `dim` to form `a` and `b`, :math:`\\text{TanH}` is the hyperbolic tangent\n    function, :math:`\\sigma` is the sigmoid function and :math:`\\otimes` is the element-wise product between matrices.\n\n    Args:\n        input (Tensor): Input tensor.\n        dim (int, optional): Dimension on which to split the input.\n                             (default: -1)\n    \"\"\"\n\n    out, gate = torch.tensor_split(input, 2, dim=dim)\n    return torch.tanh(out) * torch.sigmoid(gate)\n\n\n@torch.jit.script\ndef reverse_tensor(tensor: Tensor, dim: int) -> Tensor:\n    \"\"\"Reverse tensor along specific dimension.\n\n    Args:\n        tensor (Tensor): Input tensor.\n        dim (int): Dimension along which to reverse sequence.\n    \"\"\"\n    indices = torch.arange(tensor.size(dim) - 1, -1, -1, device=tensor.device)\n    return tensor.index_select(dim, indices)\n\n\n@torch.jit.script\ndef sparse_softmax(src: Tensor, index: Optional[Tensor] = None,\n                   ptr: Optional[Tensor] = None,\n                   num_nodes: Optional[int] = None,\n                   dim: int = -2) -> Tensor:\n    r\"\"\"Extension of ~torch_geometric.softmax with index broadcasting to compute\n    a sparsely evaluated softmax over multiple broadcast dimensions.\n\n    Given a value tensor :attr:`src`, this function first groups the values\n    along the first dimension based on the indices specified in :attr:`index`,\n    and then proceeds to compute the softmax individually for each group.\n\n    Args:\n        src (Tensor): The source tensor.\n        index (Tensor, optional): The indices of elements for applying the softmax.\n        ptr (LongTensor, optional): If given, computes the softmax based on\n            sorted inputs in CSR representation. (default: :obj:`None`)\n        num_nodes (int, optional): The number of nodes, *i.e.*\n            :obj:`max_val + 1` of :attr:`index`. (default: :obj:`None`)\n        dim (int, optional): The dimension in which to normalize, i.e., the edge\n            dimension. (default: :obj:`-2`)\n    \"\"\"\n    if ptr is not None:\n        dim = dim + src.dim() if dim < 0 else dim\n        size = ([1] * dim) + [-1]\n        ptr = ptr.view(size)\n        src_max = gather_csr(segment_csr(src, ptr, reduce='max'), ptr)\n        out = (src - src_max).exp()\n        out_sum = gather_csr(segment_csr(out, ptr, reduce='sum'), ptr)\n    elif index is not None:\n        N = maybe_num_nodes(index, num_nodes)\n        expanded_index = broadcast(index, src, dim)\n        src_max = scatter(src, expanded_index, dim, dim_size=N, reduce='max')\n        src_max = src_max.index_select(dim, index)\n        out = (src - src_max).exp()\n        out_sum = scatter(out, expanded_index, dim, dim_size=N, reduce='sum')\n        out_sum = out_sum.index_select(dim, index)\n    else:\n        raise NotImplementedError\n\n    return out / (out_sum + tsl.epsilon)\n\n\n@torch.jit.script\ndef sparse_multi_head_attention(q: Tensor, k: Tensor, v: Tensor, index: Tensor,\n                                dim_size: Optional[int] = None,\n                                dropout_p: float = 0.0):\n    r\"\"\"Computes multi-head, scaled, dot product attention on query, key and\n    value tensors, applying dropout if a probability greater than 0.0 is\n    specified. Index specifies for each query in q the belonging sequence in the\n    original batched, dense tensor.\n    Returns a tensor pair containing attended values and attention weights.\n\n    Args:\n        q (Tensor): Query tensor. See Shape section for shape details.\n        k (Tensor): Key tensor. See Shape section for shape details.\n        v (Tensor): Value tensor. See Shape section for shape details.\n        index (Tensor): Tensor containing mask values to be added to calculated\n            attention. May be 2D or 3D; see Shape section for details.\n        dim_size (int, optional): The batched target length sequence, i.e.\n            :obj:`max_val + 1` of :attr:`index`. (default: :obj:`None`)\n        dropout_p: dropout probability. If greater than 0.0, dropout is applied.\n\n    Shape:\n        - q: :math:`(S, H, E)` where S is sparsed dimension, H is the number of\n            heads, and E is embedding dimension.\n        - k: :math:`(S, H, E)` where S is sparsed dimension, H is the number of\n            heads, and E is embedding dimension.\n        - v: :math:`(S, H, O)` where S is sparsed dimension, H is the number of\n            heads, and O is output dimension.\n        - index: :math:`(S)` where S is sparsed dimension.\n        - dim_size: must be :math:`(B \\times Nt)`\n\n        - Output: attention values have shape :math:`(B, Nt, E)`; attention\n            weights have shape :math:`(S, H)`\n    \"\"\"\n    dim = 0\n    B, H, E = q.shape\n    N = maybe_num_nodes(index, dim_size)\n    # scores\n    alpha = (q * k).sum(dim=-1) / math.sqrt(E)\n    alpha = sparse_softmax(alpha, index, num_nodes=N, dim=dim)\n    if dropout_p > 0.0:\n        alpha = F.dropout(alpha, p=dropout_p)\n    v *= alpha.view(-1, H, 1)\n    # out\n    out = torch.zeros((N, H, v.size(2)), dtype=v.dtype, device=v.device)\n    add_index = broadcast(index, v, dim)\n    out.scatter_add_(dim, add_index, v)\n    return out, alpha\n", "meta": {"hexsha": "b6dc9cc154880b1deb3d98f14f03edffbf6158a5", "size": 6314, "ext": "py", "lang": "Python", "max_stars_repo_path": "tsl/nn/functional.py", "max_stars_repo_name": "TorchSpatiotemporal/tsl", "max_stars_repo_head_hexsha": "da13493b0cf83826bf41fe78a67e8d4ce1d7a8a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-03-21T09:16:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:24:30.000Z", "max_issues_repo_path": "tsl/nn/functional.py", "max_issues_repo_name": "TorchSpatiotemporal/tsl", "max_issues_repo_head_hexsha": "da13493b0cf83826bf41fe78a67e8d4ce1d7a8a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tsl/nn/functional.py", "max_forks_repo_name": "TorchSpatiotemporal/tsl", "max_forks_repo_head_hexsha": "da13493b0cf83826bf41fe78a67e8d4ce1d7a8a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.975308642, "max_line_length": 118, "alphanum_fraction": 0.6352549889, "include": true, "reason": "import numpy", "num_tokens": 1601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.1965644006249606}}
{"text": "from __future__ import print_function, division, absolute_import\n\nimport os\nimport copy\nimport json\nfrom collections import OrderedDict\nfrom warnings import warn\nfrom six import iteritems, string_types\n\nfrom sympy import Basic, sympify, Symbol\nfrom numpy import bool_, float_\nfrom jsonschema import validate, ValidationError\nimport cobra\n\nimport cobrame\nfrom cobrame.util import me_model_interface, mu\n\ntry:\n    # If cannot import SymbolicParameter, assume using cobrapy\n    # versions <= 0.5.11\n    from optlang.interface import SymbolicParameter\nexcept ImportError:\n    from cobra.io.json import metabolite_from_dict, save_json_model\nelse:\n    from cobra.io.json import save_json_model\n    from cobra.io.dict import metabolite_from_dict\n\nmu_temp = Symbol('mu')\n\ncur_dir = os.path.dirname(os.path.abspath(__file__))\n\n\ndef save_json_me(me0, file_name):\n    \"\"\"\n    Save a stripped-down JSON version of the ME-model. This will exclude all of\n    ME-Model information except the reaction stoichiometry information and the\n    reaction bounds. Saving/loading a model in this format will thus occur much\n    quicker, but limit the ability to edit the model and use most of its\n    features.\n\n    :param :class:`~cobrame.core.model.MEModel` me0:\n        A full ME-model\n\n    :param str or file-like object file_name:\n        Filename of the JSON output\n\n    :returns JSON-object:\n        Stripped-down JSON representation of full ME-model\n    \"\"\"\n    me = copy.deepcopy(me0)\n\n    for rxn in me.reactions:\n        for met in rxn.metabolites:\n            s = rxn._metabolites[met]\n            if isinstance(s, Basic):\n                rxn._metabolites[met] = str(s)\n        if isinstance(rxn.lower_bound, Basic):\n            rxn.lower_bound = str(rxn.lower_bound)\n        if isinstance(rxn.upper_bound, Basic):\n            rxn.upper_bound = str(rxn.upper_bound)\n\n    for met in me.metabolites:\n        if isinstance(met._bound, Basic):\n            met._bound = str(met._bound)\n\n    save_json_model(me, file_name)\n\n\ndef get_sympy_expression(value):\n    \"\"\"\n    Return sympy expression from json string using sympify\n\n\n    mu is assumed to be positive but using sympify does not apply this\n    assumption\"\"\"\n\n    expression_value = sympify(value)\n    return expression_value.subs(mu_temp, mu)\n\n\ndef get_numeric_from_string(string):\n    try:\n        return float(string)\n    except ValueError:\n        return get_sympy_expression(string)\n\n\ndef load_json_me(file_name):\n    \"\"\"\n    Load a stripped-down JSON version of the ME-model. This will exclude all of\n    ME-Model information except the reaction stoichiometry information and the\n    reaction bounds. Saving/loading a model in this format will thus occur much\n    quicker, but limit the ability to edit the model and use most of its\n    features.\n\n    :param str or file-like object file_name:\n        Filename of the JSON ME-model\n\n    Returns\n    -------\n    :class:`cobra.core.model.Model`\n        COBRA Model representation of the ME-model. This will not include\n        all of the functionality of a :class:`~cobrame.core.model.MEModel` but\n        will solve identically compared to the full model.\n    \"\"\"\n    if isinstance(file_name, string_types):\n        with open(file_name, 'r') as f:\n            obj = json.load(f)\n    else:\n        obj = file_name\n\n    model = cobra.Model()\n\n    # If cannot import SymbolicParameter, assume using cobrapy\n    # versions <= 0.5.11. If versions >= 0.8.0 are used, a ME-model interface\n    # must be assigned as the solver interface\n    try:\n        from optlang.interface import SymbolicParameter\n    except ImportError:\n        pass\n    else:\n        model.solver = me_model_interface\n\n    default_reactions = [i.id for i in model.reactions]\n\n    for k, v in iteritems(obj):\n        if k in {'id', 'name'}:\n            setattr(model, k, v)\n\n    def _reaction_from_dict(reaction, model):\n        new_reaction = cobra.Reaction()\n        for k, v in iteritems(reaction):\n            if k in {'objective_coefficient', 'reversibility', 'reaction'}:\n                continue\n            elif k == 'metabolites':\n                new_reaction.add_metabolites(OrderedDict(\n                    (model.metabolites.get_by_id(str(met)),\n                     get_numeric_from_string(coeff))\n                    for met, coeff in iteritems(v)))\n            elif k in {'upper_bound', 'lower_bound'}:\n                v = get_numeric_from_string(v)\n                setattr(new_reaction, k, v)\n            else:\n                setattr(new_reaction, k, v)\n        return new_reaction\n\n    model.add_metabolites(\n        [metabolite_from_dict(metabolite) for metabolite in obj['metabolites']]\n    )\n\n    new_reactions = [\n        _reaction_from_dict(reaction, model) for reaction in obj['reactions']]\n\n    model.remove_reactions(default_reactions)\n    model.add_reactions(new_reactions)\n\n    return model\n\n# -----------------------------------------------------------------------------\n# Functions below here facilitate json dumping/loading of full ME-models with\n# all process_data/reaction info intact.\n_REQUIRED_REACTION_ATTRIBUTES = {\"id\", \"name\", \"metabolites\", \"lower_bound\",\n                                 \"upper_bound\", \"objective_coefficient\",\n                                 \"variable_kind\"}\n\n# Reaction types can have different attributes\n_REACTION_TYPE_DEPENDENCIES = \\\n    {'MetabolicReaction': ['complex_data',\n                           'stoichiometric_data',\n                           'keff', 'reverse'],\n     'ComplexFormation': ['_complex_id',\n                          'complex_data_id'],\n     'PostTranslationReaction':\n         ['posttranslation_data'],\n     'TranscriptionReaction': ['transcription_data'],\n     'GenericFormationReaction': [],\n     'MEReaction': [],\n     'SummaryVariable': [],\n     'TranslationReaction': ['translation_data'],\n     'tRNAChargingReaction': ['tRNA_data']}\n\n_REQUIRED_PROCESS_DATA_ATTRIBUTES = {\"id\"}\n\n# Process data types have different attributes\n_PROCESS_DATA_TYPE_DEPENDENCIES = \\\n    {'StoichiometricData': ['_stoichiometry', 'lower_bound', 'upper_bound',\n                            'subreactions'],\n\n     'ComplexData': ['stoichiometry', 'complex_id', 'subreactions'],\n\n     'TranscriptionData': ['subreactions', 'nucleotide_sequence',\n                           'RNA_products', 'RNA_polymerase'],\n\n     'TranslationData': ['subreactions', 'nucleotide_sequence', 'mRNA',\n                         'protein'],\n\n     'tRNAData': ['subreactions', 'codon', 'RNA', 'amino_acid',\n                  'synthetase', 'synthetase_keff'],\n\n     'TranslocationData': ['enzyme_dict', 'stoichiometry', 'keff',\n                           'length_dependent_energy'],\n\n     'PostTranslationData': ['processed_protein_id', 'unprocessed_protein_id',\n                             'propensity_scaling', 'aggregation_propensity',\n                             'translocation', 'subreactions', 'surface_area',\n                             'keq_folding', 'k_folding', 'biomass_type',\n                             'translocation_multipliers'],\n\n     'SubreactionData': ['stoichiometry', 'enzyme', 'keff',\n                         'element_contribution'],\n\n     'GenericData': ['component_list']\n     }\n\n_REQUIRED_METABOLITE_ATTRIBUTES = {\"id\", \"name\", \"formula\"}\n\n_OPTIONAL_METABOLITE_ATTRIBUTES = {\"charge\", \"formula\", \"compartment\",\n                                   \"_bound\", \"_constraint_sense\"}\n\n# Some metabolite types require additional attributes\n_METABOLITE_TYPE_DEPENDENCIES = \\\n    {'TranscribedGene': ['left_pos', 'right_pos', 'strand', 'RNA_type',\n                         'nucleotide_sequence'],\n     'ProcessedProtein': ['unprocessed_protein_id']\n     }\n\n\ndef get_schema():\n    with open(os.path.join(cur_dir, 'JSONSCHEMA'), 'r') as f:\n        return json.load(f)\n\n\ndef _fix_type(value):\n    \"\"\"convert possible types to str, float, and bool\"\"\"\n    # Because numpy floats can not be pickled to json\n    if isinstance(value, string_types):\n        return str(value)\n    if isinstance(value, float_):\n        return float(value)\n    if isinstance(value, bool_):\n        return bool(value)\n    if isinstance(value, set):\n        return list(value)\n    if isinstance(value, Basic):\n        return str(value)\n    if hasattr(value, 'id'):\n        return str(value.id)\n    # if value is None:\n    #     return ''\n    return value\n\n\ndef _reaction_to_dict(reaction):\n    new_reaction = {key: _fix_type(getattr(reaction, key))\n                    for key in _REQUIRED_REACTION_ATTRIBUTES\n                    if key != 'metabolites'}\n\n    reaction_type = reaction.__class__.__name__\n    new_reaction['reaction_type'] = {}\n    new_reaction['reaction_type'][reaction_type] = {}\n\n    for attribute in _REACTION_TYPE_DEPENDENCIES.get(reaction_type, []):\n        reaction_attribute = getattr(reaction, attribute)\n\n        new_reaction['reaction_type'][reaction_type][attribute] = \\\n            _fix_type(reaction_attribute)\n\n    # Add metabolites\n    new_reaction['metabolites'] = {}\n    for met, value in reaction.metabolites.items():\n        new_reaction['metabolites'][met.id] = _fix_type(value)\n\n    return new_reaction\n\n\ndef _process_data_to_dict(data):\n    process_data_type = data.__class__.__name__\n\n    new_data = {key: _fix_type(getattr(data, key))\n                for key in _REQUIRED_PROCESS_DATA_ATTRIBUTES}\n\n    new_data['process_data_type'] = {}\n    new_data['process_data_type'][process_data_type] = {}\n    new_process_data_type_dict = \\\n        new_data['process_data_type'][process_data_type]\n\n    special_list = ['subreactions', 'stoichiometry', 'enzyme_dict',\n                    'surface_area', 'keq_folding' 'k_folding']\n\n    for attribute in _PROCESS_DATA_TYPE_DEPENDENCIES[process_data_type]:\n        if attribute not in special_list:\n            data_attribute = getattr(data, attribute)\n\n            new_process_data_type_dict[attribute] = _fix_type(data_attribute)\n\n        elif attribute == 'enzyme_dict':\n            new_process_data_type_dict[attribute] = {}\n            for cplx, values in getattr(data, attribute).items():\n                new_process_data_type_dict[attribute][cplx] = {}\n                for property, value in values.items():\n                    new_process_data_type_dict[attribute][cplx][property] = \\\n                        _fix_type(value)\n        else:\n            new_process_data_type_dict[attribute] = {}\n            for metabolite, coefficient in getattr(data, attribute).items():\n                new_process_data_type_dict[attribute][metabolite] = \\\n                    _fix_type(coefficient)\n\n    return new_data\n\n\ndef _metabolite_to_dict(metabolite):\n\n    metabolite_type = metabolite.__class__.__name__\n\n    new_metabolite = {key: _fix_type(getattr(metabolite, key))\n                      for key in _REQUIRED_METABOLITE_ATTRIBUTES}\n\n    # Som metabolites require additional information to construct working\n    # ME-model\n    new_metabolite['metabolite_type'] = {}\n    new_metabolite['metabolite_type'][metabolite_type] = {}\n    for attribute in _METABOLITE_TYPE_DEPENDENCIES.get(metabolite_type, []):\n        metabolite_attribute = getattr(metabolite, attribute)\n        new_metabolite['metabolite_type'][metabolite_type][attribute] = \\\n            metabolite_attribute\n\n    return new_metabolite\n\n\ndef get_attribute_array(dictlist, type):\n    if type == 'reaction':\n        return [_reaction_to_dict(reaction) for reaction in dictlist]\n    elif type == 'process_data':\n        return [_process_data_to_dict(data) for data in dictlist]\n    elif type == 'metabolite':\n        return [_metabolite_to_dict(metabolite) for metabolite in dictlist]\n    else:\n        raise TypeError('Type must be reaction, process_data or metabolite')\n\n\ndef get_global_info_dict(global_info):\n    new_global_info = {}\n    for key, value in global_info.items():\n        if type(value) != dict:\n            new_global_info[key] = _fix_type(value)\n        else:\n            new_global_info[key] = value\n    return new_global_info\n\n\ndef _to_dict(model):\n\n    obj = dict(\n        reactions=get_attribute_array(model.reactions, 'reaction'),\n        process_data=get_attribute_array(model.process_data,\n                                         'process_data'),\n        metabolites=get_attribute_array(model.metabolites, 'metabolite'),\n        global_info=get_global_info_dict(model.global_info)\n    )\n\n    return obj\n\n\ndef save_full_me_model_json(model, file_name):\n    \"\"\"\n    Save a full JSON version of the ME-model. Saving/loading a model in this\n    format can then be loaded to return a ME-model identical to the one saved.\n\n    :param :class:`~cobrame.core.MEModel.MEModel` model:\n        A full ME-model\n\n    :param str or file-like object file_name:\n        Filename of the JSON output\n\n    :returns JSON-object:\n        Full JSON representation of full ME-model\n    \"\"\"\n\n    should_close = False\n    if isinstance(file_name, string_types):\n        file_name = open(file_name, 'w')\n        should_close = True\n\n    json.dump(_to_dict(model), file_name)\n\n    if should_close:\n        file_name.close()\n\n\ndef add_metabolite_from_dict(model, metabolite_info):\n    \"\"\"\n    Builds metabolite instances defined in dictionary, then add it to the\n    ME-model being constructed.\n\n    ProcessedProteins require additional information\n    \"\"\"\n\n    metabolite_type_dict = metabolite_info['metabolite_type']\n    if len(metabolite_type_dict) != 1:\n        raise Exception('Only 1 metabolite_type in valid json')\n\n    metabolite_type = list(metabolite_type_dict.keys())[0]\n\n    # ProcessedProtein types require their unprocessed protein id as well\n    if metabolite_type == 'ProcessedProtein':\n        unprocessed_id = \\\n            metabolite_type_dict['ProcessedProtein']['unprocessed_protein_id']\n\n        metabolite_obj = \\\n            getattr(cobrame, metabolite_type)(metabolite_info['id'],\n                                              unprocessed_id)\n\n    elif metabolite_type == 'TranscribedGene':\n        rna_type = metabolite_type_dict['TranscribedGene']['RNA_type']\n        nucleotide_sequence = \\\n            metabolite_type_dict['TranscribedGene']['nucleotide_sequence']\n        metabolite_obj = \\\n            getattr(cobrame, metabolite_type)(metabolite_info['id'],\n                                              rna_type, nucleotide_sequence)\n    else:\n        metabolite_obj = \\\n            getattr(cobrame, metabolite_type)(metabolite_info['id'])\n\n    for attribute in _REQUIRED_METABOLITE_ATTRIBUTES:\n        setattr(metabolite_obj, attribute, metabolite_info[attribute])\n\n    for attribute in _METABOLITE_TYPE_DEPENDENCIES.get(metabolite_type, []):\n        value = metabolite_type_dict[metabolite_type][attribute]\n        setattr(metabolite_obj, attribute, value)\n\n    model.add_metabolites([metabolite_obj])\n\n\ndef add_process_data_from_dict(model, process_data_dict):\n    \"\"\"\n    Builds process_data instances defined in dictionary, then add it to the\n    ME-model being constructed.\n\n    Most classes of process_data only require an id and model to initiate them,\n    but TranslationData, tRNAData, PostTranslationData and GenericData require\n    additional inputs.\n\n    \"\"\"\n\n    # Create process data instances. Handel certain types individually\n    id = process_data_dict['id']\n    process_data_type_dict = process_data_dict['process_data_type']\n    if len(process_data_type_dict) == 1:\n        process_data_type, process_data_info = process_data_type_dict.popitem()\n    else:\n        print(process_data_type_dict, len(process_data_type_dict))\n        raise Exception('Only 1 reaction_type in valid json')\n\n    if process_data_type == 'TranslationData':\n        mrna = process_data_info['mRNA']\n        protein = process_data_info['protein']\n        process_data = \\\n            getattr(cobrame, process_data_type)(id, model, mrna, protein)\n    elif process_data_type == 'tRNAData':\n        amino_acid = process_data_info['amino_acid']\n        rna = process_data_info['RNA']\n        codon = process_data_info['codon']\n        process_data = \\\n            getattr(cobrame, process_data_type)(id, model, amino_acid, rna,\n                                                codon)\n    elif process_data_type == 'PostTranslationData':\n        processed_protein_id = process_data_info['processed_protein_id']\n        unprocessed_protein_id = process_data_info['unprocessed_protein_id']\n        process_data = \\\n            getattr(cobrame, process_data_type)(id, model,\n                                                processed_protein_id,\n                                                unprocessed_protein_id)\n    elif process_data_type == 'GenericData':\n        component_list = process_data_info['component_list']\n        process_data = \\\n            getattr(cobrame, process_data_type)(id, model, component_list)\n        # Create reaction from generic process data\n        process_data.create_reactions()\n    else:\n        process_data = getattr(cobrame, process_data_type)(id, model)\n\n    # Set all of the required attributes using information in info dictionary\n    for attribute in _REQUIRED_PROCESS_DATA_ATTRIBUTES:\n        setattr(process_data, attribute, process_data_dict[attribute])\n\n    # Some attributes depend on process data type. Set those here.\n    for attribute in _PROCESS_DATA_TYPE_DEPENDENCIES.get(process_data_type,\n                                                         []):\n        value = process_data_info[attribute]\n        try:\n            setattr(process_data, attribute, value)\n        except AttributeError:\n            # set to the hidden attribute instead\n            setattr(process_data, '_' + attribute, value)\n\n\ndef add_reaction_from_dict(model, reaction_info):\n    \"\"\"\n    Builds reaction instances defined in dictionary, then add it to the\n    ME-model being constructed.\n\n    \"\"\"\n    reaction_type_dict = reaction_info['reaction_type']\n\n    if len(reaction_type_dict) == 1:\n        reaction_type = list(reaction_type_dict.keys())[0]\n        reaction_obj = getattr(cobrame, reaction_type)(reaction_info['id'])\n    else:\n        raise Exception('Only 1 reaction_type in valid json')\n\n    for attribute in _REQUIRED_REACTION_ATTRIBUTES:\n        # Metabolites are added to reactions using their update function,\n        # skip setting metabolite stoichiometries here\n        if attribute == 'metabolites':\n            continue\n\n        # upper and lower bounds may contain mu values. Handle that here\n        value = reaction_info[attribute]\n        if attribute in ['upper_bound', 'lower_bound']:\n            value = get_sympy_expression(value)\n        setattr(reaction_obj, attribute, value)\n\n    # Some reactions are added to model when ME-models are initialized\n    try:\n        model.add_reactions([reaction_obj])\n    except Exception:\n        reaction_obj = model.reactions.get_by_id(reaction_obj.id)\n        if reaction_type not in ['SummaryVariable',\n                                 'GenericFormationReaction']:\n            warn('Reaction (%s) already in model' % reaction_obj.id)\n\n    # These reactions types do not have update functions and need their\n    # stoichiometries set explicitly .\n    if reaction_type in ['SummaryVariable', 'MEReaction']:\n        for key, value in reaction_info['metabolites'].items():\n            reaction_obj.add_metabolites({key: get_sympy_expression(value)},\n                                         combine=False)\n\n    for attribute in _REACTION_TYPE_DEPENDENCIES.get(reaction_type, []):\n        # Spontaneous reactions do no require complex_data\n        if attribute == 'complex_data' and 'SPONT' in reaction_obj.id:\n            continue\n\n        value = reaction_type_dict[reaction_type][attribute]\n        setattr(reaction_obj, attribute, value)\n\n    if hasattr(reaction_obj, 'update'):\n        reaction_obj.update()\n\n\ndef full_me_model_from_dict(obj):\n    \"\"\"\n    Validate and load JSON representation of the ME-model. This will return\n    a full :class:`~cobrame.core.model.MEModel` object identical to the\n    one saved.\n\n    :param str or file-like object obj:\n        JSON-serialized ME-model\n\n    :returns :class:`~cobrame.core.model.MEModel`:\n        Full COBRAme ME-model\n    \"\"\"\n\n    try:\n        validate(obj, get_schema())\n    except ValidationError:\n        raise Exception('Must pass valid ME-model json file')\n\n    model = cobrame.MEModel()\n\n    for k, v in iteritems(obj):\n        if k in {'id', 'name', 'global_info'}:\n            setattr(model, k, v)\n\n    for metabolite in obj['metabolites']:\n        add_metabolite_from_dict(model, metabolite)\n\n    for process_data in obj['process_data']:\n        add_process_data_from_dict(model, process_data)\n\n    for reaction in obj['reactions']:\n        add_reaction_from_dict(model, reaction)\n\n    model.update()\n\n    return model\n\n\ndef load_full_me_model_json(file_name):\n\n    with open(file_name, 'r') as f:\n        model_dict = json.load(f)\n\n    return full_me_model_from_dict(model_dict)\n", "meta": {"hexsha": "d821fac968f6bf5cf0cee8ac2fb27b8fe664ce09", "size": 20891, "ext": "py", "lang": "Python", "max_stars_repo_path": "cobrame/io/jsonme.py", "max_stars_repo_name": "zakandrewking/cobrame", "max_stars_repo_head_hexsha": "66fc05de462f1aa9ce79c9812f7a24457560510b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cobrame/io/jsonme.py", "max_issues_repo_name": "zakandrewking/cobrame", "max_issues_repo_head_hexsha": "66fc05de462f1aa9ce79c9812f7a24457560510b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cobrame/io/jsonme.py", "max_forks_repo_name": "zakandrewking/cobrame", "max_forks_repo_head_hexsha": "66fc05de462f1aa9ce79c9812f7a24457560510b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-07T08:39:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-07T08:39:29.000Z", "avg_line_length": 35.0520134228, "max_line_length": 79, "alphanum_fraction": 0.6549710402, "include": true, "reason": "from numpy,from sympy", "num_tokens": 4552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19656440062496058}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\n\nimport argparse\n\nimport multiprocessing\nimport numpy as np\n\nimport torch\nfrom torch import nn, optim, Tensor\n\nfrom ctp.training.data import Data\nfrom ctp.training.batcher import Batcher\n\nfrom ctp.kernels import BaseKernel, GaussianKernel\n\nfrom ctp.smart.kb import NeuralKB\nfrom ctp.smart.simple import SimpleHoppy\n\nfrom ctp.reformulators import BaseReformulator\nfrom ctp.reformulators import StaticReformulator\nfrom ctp.reformulators import LinearReformulator\nfrom ctp.reformulators import AttentiveReformulator\nfrom ctp.reformulators import MemoryReformulator\nfrom ctp.reformulators import NTPReformulator\n\nfrom ctp.regularizers import N2, N3\nfrom ctp.evaluation import evaluate_slow as evaluate\nfrom ctp.evaluation import evaluate_naive\nfrom ctp.evaluation import evaluate_on_countries\n\nfrom typing import Tuple, Dict, Optional\n\nimport logging\n\nlogger = logging.getLogger(os.path.basename(sys.argv[0]))\nnp.set_printoptions(linewidth=48, precision=5, suppress=True)\n\ntorch.set_num_threads(multiprocessing.cpu_count())\n# torch.autograd.set_detect_anomaly(True)\n\n\ndef metrics_to_str(metrics):\n    return f'MRR {metrics[\"MRR\"]:.6f}\\tH@1 {metrics[\"hits@1\"]:.6f}\\tH@3 {metrics[\"hits@3\"]:.6f}\\t' \\\n        f'H@5 {metrics[\"hits@5\"]:.6f}\\tH@10 {metrics[\"hits@10\"]:.6f}'\n\n\ndef decode(vector: Tensor,\n           kernel: BaseKernel,\n           predicate_embeddings: nn.Module) -> Tuple[int, float]:\n    weight = predicate_embeddings.weight\n    k = kernel.pairwise(vector, weight)[0, :]\n    top_idx = k.argmax(dim=0).item()\n    top_score = k[top_idx].item()\n    return top_idx, top_score\n\n\ndef show_rules(model: SimpleHoppy,\n               kernel: BaseKernel,\n               predicate_embeddings: nn.Embedding,\n               predicate_to_idx: Dict[str, int],\n               device: Optional[torch.device] = None):\n    idx_to_predicate = {i: p for p, i in predicate_to_idx.items()}\n\n    pred_idx_pair_lst = sorted(predicate_to_idx.items(), key=lambda kv: kv[1])\n\n    for p, i in pred_idx_pair_lst:\n        indices = torch.tensor([i], dtype=torch.long, device=device)\n\n        p_emb = predicate_embeddings(indices)\n\n        hops_lst = [p for p in model.hops_lst]\n\n        for reformulator, is_reversed in hops_lst:\n            def _to_pair(hop: Tensor) -> Tuple[str, float]:\n                idx, score = decode(hop, kernel, predicate_embeddings)\n                rel = idx_to_predicate[idx]\n                return rel, score\n\n            hop_tensor_lst = [hop for hop in reformulator(p_emb)]\n\n            r_hops = [_to_pair(hop) for hop in hop_tensor_lst]\n            print(p, ' ← ', ', '.join(f'({a} {b:.4f})' for a, b in r_hops), is_reversed)\n    return\n\n\ndef main(argv):\n    parser = argparse.ArgumentParser('KBC Research', formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n    parser.add_argument('--train', action='store', required=True, type=str)\n\n    parser.add_argument('--dev', action='store', type=str, default=None)\n    parser.add_argument('--test', action='store', type=str, default=None)\n\n    parser.add_argument('--test-i', action='store', type=str, default=None)\n    parser.add_argument('--test-ii', action='store', type=str, default=None)\n\n    parser.add_argument('--embedding-size', '-k', action='store', type=int, default=20)\n    parser.add_argument('--k-max', '-K', action='store', type=int, default=3)\n\n    parser.add_argument('--hops', nargs='+', type=str, default=['1', '2'])\n\n    # training params\n    parser.add_argument('--epochs', '-e', action='store', type=int, default=100)\n    parser.add_argument('--learning-rate', '-l', action='store', type=float, default=0.001)\n\n    parser.add_argument('--batch-size', '-b', action='store', type=int, default=8)\n    parser.add_argument('--eval-batch-size', '-E', action='store', type=int, default=None)\n\n    parser.add_argument('--optimizer', '-o', action='store', type=str, default='adam',\n                        choices=['adagrad', 'adam', 'sgd'])\n\n    parser.add_argument('--N2', action='store', type=float, default=None)\n    parser.add_argument('--N3', action='store', type=float, default=None)\n\n    parser.add_argument('--reformulator', '-r', action='store', type=str, default='linear',\n                        choices=['static', 'linear', 'attentive', 'memory', 'ntp'])\n    parser.add_argument('--nb-rules', '-R', action='store', type=int, default=4)\n\n    # parser.add_argument('--GNTP-R', action='store', type=int, default=None)\n\n    parser.add_argument('--seed', action='store', type=int, default=0)\n\n    parser.add_argument('--validate-every', '-V', action='store', type=int, default=None)\n    parser.add_argument('--input-type', '-I', action='store', type=str, default='standard',\n                        choices=['standard', 'reciprocal'])\n\n    parser.add_argument('--init-size', '-i', action='store', type=float, default=1.0)\n\n    parser.add_argument('--init', action='store', type=str, default='uniform')\n    parser.add_argument('--ref-init', action='store', type=str, default='uniform')\n\n    parser.add_argument('--load', action='store', type=str, default=None)\n    parser.add_argument('--save', action='store', type=str, default=None)\n\n    parser.add_argument('--nb-negatives', action='store', type=int, default=1)\n\n    parser.add_argument('--quiet', '-q', action='store_true', default=False)\n\n    parser.add_argument('--freeze-entities', '-f', action='store', type=int, default=None)\n    parser.add_argument('--refresh-interval', '--refresh', action='store', type=int, default=None)\n    parser.add_argument('--index-type', '--index', action='store', type=str, default='faiss',\n                        choices=['np', 'faiss', 'nms'])\n\n    parser.add_argument('--lower-bound', '--lb', action='store', type=float, default=-1.0)\n    parser.add_argument('--upper-bound', '--ub', action='store', type=float, default=1.0)\n\n    parser.add_argument('--slow-eval', action='store_true', default=False)\n\n    parser.add_argument('--show', action='store_true', default=False)\n\n    parser.add_argument('--fix-entities', action='store_true', default=False)\n    parser.add_argument('--fix-predicates', action='store_true', default=False)\n\n    args = parser.parse_args(argv)\n\n    import pprint\n    pprint.pprint(vars(args))\n\n    train_path = args.train\n    dev_path = args.dev\n    test_path = args.test\n\n    test_i_path = args.test_i\n    test_ii_path = args.test_ii\n\n    embedding_size = args.embedding_size\n    k_max = args.k_max\n\n    hops_str = args.hops\n\n    nb_epochs = args.epochs\n    learning_rate = args.learning_rate\n    batch_size = args.batch_size\n    optimizer_name = args.optimizer\n\n    N2_weight = args.N2\n    N3_weight = args.N3\n\n    reformulator_type = args.reformulator\n    nb_rules = args.nb_rules\n\n    # gntp_R = args.GNTP_R\n\n    eval_batch_size = batch_size if args.eval_batch_size is None else args.eval_batch_size\n\n    seed = args.seed\n\n    validate_every = args.validate_every\n    input_type = args.input_type\n    init_size = args.init_size\n\n    init_type = args.init\n    ref_init_type = args.ref_init\n\n    load_path = args.load\n    save_path = args.save\n\n    nb_neg = args.nb_negatives\n    is_quiet = args.quiet\n\n    freeze_entities = args.freeze_entities\n    refresh_interval = args.refresh_interval\n    index_type = args.index_type\n\n    lower_bound = args.lower_bound\n    upper_bound = args.upper_bound\n\n    slow_eval = args.slow_eval\n\n    evaluate_ = evaluate_naive if slow_eval else evaluate\n\n    is_show = args.show\n\n    is_fix_entities = args.fix_entities\n    is_fix_predicates = args.fix_predicates\n\n    # set the seeds\n    np.random.seed(seed)\n    random_state = np.random.RandomState(seed)\n    torch.manual_seed(seed)\n\n    if torch.cuda.is_available():\n        torch.cuda.manual_seed(seed)\n\n    rs = np.random.RandomState(seed)\n\n    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n    logger.info(f'Device: {device}')\n\n    if torch.cuda.is_available():\n        torch.set_default_tensor_type(torch.cuda.FloatTensor)\n\n    data = Data(train_path=train_path, dev_path=dev_path, test_path=test_path,\n                test_i_path=test_i_path, test_ii_path=test_ii_path, input_type=input_type)\n\n    triples_name_pairs = [\n        (data.dev_triples, 'dev'),\n        (data.test_triples, 'test'),\n        (data.test_i_triples, 'test-I'),\n        (data.test_ii_triples, 'test-II'),\n    ]\n\n    entity_embeddings = nn.Embedding(data.nb_entities, embedding_size, sparse=True)\n    predicate_embeddings = nn.Embedding(data.nb_predicates, embedding_size, sparse=True)\n\n    print('Entity Embeddings', entity_embeddings)\n    print('Predicate Embeddings', predicate_embeddings)\n\n    if init_type in {'uniform'}:\n        nn.init.uniform_(entity_embeddings.weight, lower_bound, upper_bound)\n        nn.init.uniform_(predicate_embeddings.weight, lower_bound, upper_bound)\n\n    nn.init.uniform_(entity_embeddings.weight, lower_bound, upper_bound)\n    nn.init.uniform_(predicate_embeddings.weight, lower_bound, upper_bound)\n\n    entity_embeddings.weight.data *= init_size\n    predicate_embeddings.weight.data *= init_size\n\n    if freeze_entities is not None:\n        entity_embeddings.weight.requires_grad = False\n\n    if is_fix_entities is True:\n        entity_embeddings.weight.requires_grad = False\n\n    if is_fix_predicates is True:\n        predicate_embeddings.weight.requires_grad = False\n\n    kernel = GaussianKernel(slope=1.0)\n\n    fact_rel = torch.tensor([data.predicate_to_idx[p] for (_, p, _) in data.train_triples],\n                            dtype=torch.long, device=device)\n    fact_arg1 = torch.tensor([data.entity_to_idx[s] for (s, _, _) in data.train_triples],\n                             dtype=torch.long, device=device)\n    fact_arg2 = torch.tensor([data.entity_to_idx[o] for (_, _, o) in data.train_triples],\n                             dtype=torch.long, device=device)\n    facts = [fact_rel, fact_arg1, fact_arg2]\n\n    base_model = NeuralKB(entity_embeddings=entity_embeddings, predicate_embeddings=predicate_embeddings,\n                          k=k_max, facts=facts, kernel=kernel, device=device,\n                          index_type=index_type, refresh_interval=refresh_interval).to(device)\n\n    memory: Dict[int, MemoryReformulator.Memory] = {}\n\n    def make_hop(s: str) -> Tuple[BaseReformulator, bool]:\n        nonlocal memory\n        if s.isdigit():\n            nb_hops, is_reversed = int(s), False\n        else:\n            nb_hops, is_reversed = int(s[:-1]), True\n        res = None\n        if reformulator_type in {'static'}:\n            res = StaticReformulator(nb_hops, embedding_size, init_name=ref_init_type,\n                                     lower_bound=lower_bound, upper_bound=upper_bound)\n        elif reformulator_type in {'linear'}:\n            res = LinearReformulator(nb_hops, embedding_size, init_name=ref_init_type,\n                                     lower_bound=lower_bound, upper_bound=upper_bound)\n        elif reformulator_type in {'attentive'}:\n            res = AttentiveReformulator(nb_hops, predicate_embeddings, init_name=ref_init_type,\n                                        lower_bound=lower_bound, upper_bound=upper_bound)\n        elif reformulator_type in {'memory'}:\n            if nb_hops not in memory:\n                memory[nb_hops] = MemoryReformulator.Memory(nb_hops, nb_rules, embedding_size, init_name=ref_init_type)\n\n            res = MemoryReformulator(memory[nb_hops])\n        elif reformulator_type in {'ntp'}:\n            res = NTPReformulator(nb_hops=nb_hops, embedding_size=embedding_size,\n                                  kernel=kernel, init_name=ref_init_type,\n                                  lower_bound=lower_bound, upper_bound=upper_bound)\n        assert res is not None\n        return res, is_reversed\n\n    hops_lst = [make_hop(s) for s in hops_str]\n\n    # model = MultiHoppy(model=base_model, entity_embeddings=entity_embeddings, hops_lst=hops_lst).to(device)\n    # model = SimpleHoppy(model=base_model, entity_embeddings=entity_embeddings, hops_lst=hops_lst).to(device)\n    model = SimpleHoppy(model=base_model, entity_embeddings=entity_embeddings, hops_lst=hops_lst).to(device)\n\n    def scoring_function(batch_xs: np.ndarray,\n                         batch_xp: np.ndarray,\n                         batch_xo: np.ndarray) -> np.ndarray:\n        with torch.no_grad():\n            tensor_xs = torch.tensor(batch_xs, dtype=torch.long, device=device)\n            tensor_xp = torch.tensor(batch_xp, dtype=torch.long, device=device)\n            tensor_xo = torch.tensor(batch_xo, dtype=torch.long, device=device)\n\n            tensor_xs_emb = entity_embeddings(tensor_xs)\n            tensor_xp_emb = predicate_embeddings(tensor_xp)\n            tensor_xo_emb = entity_embeddings(tensor_xo)\n\n            scores_ = model.score(tensor_xp_emb, tensor_xs_emb, tensor_xo_emb)\n        return scores_.cpu().numpy()\n\n    print('Model Params:', [p.shape for p in model.parameters()])\n\n    params_lst = {p for p in model.parameters()} | \\\n                 ({entity_embeddings.weight} if is_fix_entities is False else set()) | \\\n                 ({predicate_embeddings.weight} if is_fix_predicates is False else set())\n\n    params = nn.ParameterList(params_lst).to(device)\n\n    if load_path is not None:\n        model.load_state_dict(torch.load(load_path))\n\n    for tensor in params_lst:\n        logger.info(f'\\t{tensor.size()}\\t{tensor.device}')\n\n    optimizer_factory = {\n        'adagrad': lambda arg: optim.Adagrad(arg, lr=learning_rate),\n        'adam': lambda arg: optim.Adam(arg, lr=learning_rate),\n        'sgd': lambda arg: optim.SGD(arg, lr=learning_rate)\n    }\n\n    assert optimizer_name in optimizer_factory\n    optimizer = optimizer_factory[optimizer_name](params)\n\n    # loss_function = nn.BCELoss(reduction=\"sum\")\n    loss_function = nn.BCELoss()\n\n    N2_reg = N2() if N2_weight is not None else None\n    N3_reg = N3() if N3_weight is not None else None\n\n    for epoch_no in range(1, nb_epochs + 1):\n        batcher = Batcher(data, batch_size, 1, random_state)\n        nb_batches = len(batcher.batches)\n\n        if freeze_entities is not None and is_fix_entities is False and epoch_no > freeze_entities:\n            entity_embeddings.weight.requires_grad = True\n\n        epoch_loss_values = []\n        for batch_no, (batch_start, batch_end) in enumerate(batcher.batches, 1):\n            xp_batch_np, xs_batch_np, xo_batch_np, xi_batch_np = batcher.get_batch(batch_start, batch_end)\n            t = xp_batch_np.shape[0]\n\n            assert nb_neg > 0\n\n            xp_exp_np = np.repeat(xp_batch_np, nb_neg * 3 + 1)\n            xs_exp_np = np.repeat(xs_batch_np, nb_neg * 3 + 1)\n            xo_exp_np = np.repeat(xo_batch_np, nb_neg * 3 + 1)\n            xi_exp_np = np.repeat(xi_batch_np, nb_neg * 3 + 1)\n\n            xt_exp_np = np.zeros_like(xp_exp_np)\n            xt_exp_np[0::nb_neg * 3 + 1] = 1\n\n            for i in range(t):\n                a_ = rs.permutation(data.nb_entities)\n                b_ = rs.permutation(data.nb_entities)\n\n                c_ = rs.permutation(data.nb_entities)\n                d_ = rs.permutation(data.nb_entities)\n\n                while a_.shape[0] < nb_neg:\n                    a_ = np.concatenate([a_, rs.permutation(data.nb_entities)])\n                    b_ = np.concatenate([b_, rs.permutation(data.nb_entities)])\n\n                    c_ = np.concatenate([c_, rs.permutation(data.nb_entities)])\n                    d_ = np.concatenate([d_, rs.permutation(data.nb_entities)])\n\n                a = a_[:nb_neg]\n                b = b_[:nb_neg]\n                c = c_[:nb_neg]\n                d = d_[:nb_neg]\n\n                xs_exp_np[(i * nb_neg * 3) + i + 1:(i * nb_neg * 3) + nb_neg + i + 1] = a\n                xo_exp_np[(i * nb_neg * 3) + nb_neg + i + 1:(i * nb_neg * 3) + nb_neg * 2 + i + 1] = b\n\n                xs_exp_np[(i * nb_neg * 3) + nb_neg * 2 + i + 1:(i * nb_neg * 3) + nb_neg * 3 + i + 1] = c\n                xo_exp_np[(i * nb_neg * 3) + nb_neg * 2 + i + 1:(i * nb_neg * 3) + nb_neg * 3 + i + 1] = d\n\n            xp_batch = torch.tensor(xp_exp_np, dtype=torch.long, device=device)\n            xs_batch = torch.tensor(xs_exp_np, dtype=torch.long, device=device)\n            xo_batch = torch.tensor(xo_exp_np, dtype=torch.long, device=device)\n            xi_batch = torch.tensor(xi_exp_np, dtype=torch.long, device=device)\n            xt_batch = torch.tensor(xt_exp_np, dtype=torch.float32, device=device)\n\n            # Disable masking\n            # xi_batch = None\n\n            xp_batch_emb = predicate_embeddings(xp_batch)\n            xs_batch_emb = entity_embeddings(xs_batch)\n            xo_batch_emb = entity_embeddings(xo_batch)\n\n            factors = [model.factor(e) for e in [xp_batch_emb, xs_batch_emb, xo_batch_emb]]\n\n            scores = model.score(xp_batch_emb, xs_batch_emb, xo_batch_emb, mask_indices=xi_batch)\n            # scores = base_model.score(xp_batch_emb, xs_batch_emb, xo_batch_emb, mask_indices=xi_batch)\n\n            # print(scores)\n            loss = loss_function(scores, xt_batch)\n\n            loss += N2_weight * N2_reg(factors) if N2_weight is not None else 0.0\n            loss += N3_weight * N3_reg(factors) if N3_weight is not None else 0.0\n\n            loss.backward()\n            optimizer.step()\n            optimizer.zero_grad()\n\n            loss_value = loss.item()\n            epoch_loss_values += [loss_value]\n\n            if not is_quiet:\n                logger.info(f'Epoch {epoch_no}/{nb_epochs}\\tBatch {batch_no}/{nb_batches}\\tLoss {loss_value:.6f}')\n\n        loss_mean, loss_std = np.mean(epoch_loss_values), np.std(epoch_loss_values)\n        logger.info(f'Epoch {epoch_no}/{nb_epochs}\\tLoss {loss_mean:.4f} ± {loss_std:.4f}')\n\n        if validate_every is not None and epoch_no % validate_every == 0:\n            if 'countries' in train_path:\n                dev_auc = evaluate_on_countries('dev', data.entity_to_idx, data.predicate_to_idx, scoring_function)\n                print('Last AUC-PR (dev) {:.4f}'.format(dev_auc))\n\n                test_auc = evaluate_on_countries('test', data.entity_to_idx, data.predicate_to_idx, scoring_function)\n                print('Last AUC-PR (test) {:.4f}'.format(test_auc))\n            else:\n                for triples, name in [(t, n) for t, n in triples_name_pairs if len(t) > 0]:\n                    metrics = evaluate_(entity_embeddings=entity_embeddings, predicate_embeddings=predicate_embeddings,\n                                        test_triples=triples, all_triples=data.all_triples,\n                                        entity_to_index=data.entity_to_idx, predicate_to_index=data.predicate_to_idx,\n                                        model=model, batch_size=eval_batch_size, device=device)\n                    logger.info(f'Epoch {epoch_no}/{nb_epochs}\\t{name} results\\t{metrics_to_str(metrics)}')\n\n            if is_show is True:\n                with torch.no_grad():\n                    # print(entity_embeddings.weight)\n                    show_rules(model=model, kernel=kernel, predicate_embeddings=predicate_embeddings,\n                               predicate_to_idx=data.predicate_to_idx, device=device)\n\n    if 'countries' in train_path:\n        dev_auc = evaluate_on_countries('dev', data.entity_to_idx, data.predicate_to_idx, scoring_function)\n        print('Last AUC-PR (dev) {:.4f}'.format(dev_auc))\n\n        test_auc = evaluate_on_countries('test', data.entity_to_idx, data.predicate_to_idx, scoring_function)\n        print('Last AUC-PR (test) {:.4f}'.format(test_auc))\n    else:\n        for triples, name in [(t, n) for t, n in triples_name_pairs if len(t) > 0]:\n            metrics = evaluate_(entity_embeddings=entity_embeddings, predicate_embeddings=predicate_embeddings,\n                                test_triples=triples, all_triples=data.all_triples,\n                                entity_to_index=data.entity_to_idx, predicate_to_index=data.predicate_to_idx,\n                                model=model, batch_size=eval_batch_size, device=device)\n            logger.info(f'Final \\t{name} results\\t{metrics_to_str(metrics)}')\n\n    if is_show is True:\n        with torch.no_grad():\n            show_rules(model=model, kernel=kernel, predicate_embeddings=predicate_embeddings,\n                       predicate_to_idx=data.predicate_to_idx, device=device)\n\n    if save_path is not None:\n        torch.save(model.state_dict(), save_path)\n\n    logger.info(\"Training finished\")\n\n\nif __name__ == '__main__':\n    logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n    logging.getLogger('nmslib').setLevel(logging.WARNING)\n    print(' '.join(sys.argv))\n    main(sys.argv[1:])\n", "meta": {"hexsha": "5cca8fcf0ddf50985e812f091191bade10fdd889", "size": 20601, "ext": "py", "lang": "Python", "max_stars_repo_path": "bin/hoppy-cli.py", "max_stars_repo_name": "Vikicsizmadia/ctp", "max_stars_repo_head_hexsha": "d88fdfecf4b90ee42e6137a9767226c0d35b19a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2020-07-14T15:44:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T10:33:07.000Z", "max_issues_repo_path": "bin/hoppy-cli.py", "max_issues_repo_name": "Vikicsizmadia/ctp", "max_issues_repo_head_hexsha": "d88fdfecf4b90ee42e6137a9767226c0d35b19a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-12-28T05:57:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T01:05:06.000Z", "max_forks_repo_path": "bin/hoppy-cli.py", "max_forks_repo_name": "Vikicsizmadia/ctp", "max_forks_repo_head_hexsha": "d88fdfecf4b90ee42e6137a9767226c0d35b19a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-07-14T22:56:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T02:40:10.000Z", "avg_line_length": 41.119760479, "max_line_length": 119, "alphanum_fraction": 0.6502596961, "include": true, "reason": "import numpy", "num_tokens": 4871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19656440062496058}}
{"text": "\"\"\"\nClass for holding the NN and processing the output\n\nArthur McCray\namccray@anl.gov\n\"\"\"\n\nimport numpy as np\nimport scipy.ndimage as ndi\nimport torch\nimport torch.nn.functional as F\n\nfrom smallUnet import smallUnet\n\n\nclass trained_NN(object):\n    def __init__(self, path, cuda=True, gpu=0):\n        model = smallUnet()\n        if gpu == \"cpu\":\n            self.cuda = False\n        else:\n            self.cuda = cuda\n        self.gpu = gpu\n        self.scale = None\n        self.prediction = None\n        if self.cuda:\n            model.load_state_dict(torch.load(path))\n            model.cuda(gpu)\n        else:\n            print(\"Loading the NN on the CPU\")\n            model.load_state_dict(torch.load(path, map_location=torch.device(\"cpu\")))\n\n        model.eval()\n        self.model = model\n\n    def find_skyrms(self, image, tilt_dir, thresh=0.5, scale=None):\n        \"\"\"Makes a prediction using the NN on image, then also finds the centers of the\n        found skyrmions on that image. To just find the skyrmions on a previously made\n        prediction with a new threshold value, update model.threshold and run\n        model.get_centers() which will return centers.\n\n        The model.prediction will of course be scaled by self.scale, and in get_centers\n        the rescaling will be applied\n\n        Args:\n            image (ndarray): Image from which to find skyrms\n            tilt_dir (float): direction along which sample is tilted\n            thresh (float, optional): Prediction threshold. Defaults to 0.5.\n            scale (float, optional): Scaling factor of image before prediction. Scale is\n                the factor by which the image will be rescaled before inputting into the\n                NN. Output skyrmion locations will be appropriately rescaled back to the\n                original input image.\n\n        Returns:\n            ndarray: [[y1,x1], [y2,x2], ...] array of skyrmion center positions.\n        \"\"\"\n        self.threshold = thresh\n        ## apply rotation\n        dimy, dimx = image.shape\n        if scale is not None:\n            self.scale = scale\n        if self.scale is not None:\n            dimy, dimx = round(dimy * scale), round(dimx * scale)\n            image = norm_image(rescale(image, scale))\n\n        imagerot = ndi.rotate(image, 90 + tilt_dir)\n        image2 = center_pad_pwr2(imagerot)\n\n        # Convert to 4D tensor (required, even if it is a single image)\n        image4d = image2[None, None, ...]\n        # Convert to pytorch format and move to GPU\n        if self.cuda:\n            image4d_ = torch.from_numpy(image4d).float().cuda(self.gpu)\n        else:\n            image4d_ = torch.from_numpy(image4d).float()\n\n        # make a prediction\n        prediction = self.model.forward(image4d_)\n        prediction = F.softmax(prediction, dim=1).cpu().detach().numpy()\n        prediction = np.transpose(prediction, [0, 2, 3, 1])\n        # get coordinates\n        prediction2 = ndi.rotate(\n            prediction[0, :, :, :], -1 * (90 + tilt_dir), axes=(0, 1)\n        )\n\n        prediction2 = center_crop_im(\n            prediction2, (dimy, dimx), dim_order_in=\"channels_last\"\n        )[:, :, ::-1]\n        self.prediction = prediction2\n        centers = self.get_centers()\n        return centers\n\n    def rng_seed(self, seed):\n        torch.manual_seed(seed)\n        np.random.seed(seed)\n        torch.cuda.empty_cache()\n        torch.cuda.manual_seed(seed)\n        torch.backends.cudnn.deterministic = True\n        torch.backends.cudnn.benchmark = False\n\n    def get_centers(self):\n        FA = FindObjects(self.prediction[None, ...], threshold=self.threshold)\n        coords = FA.get_all_coordinates()\n        centers = coords[0][:, :2]\n        if self.scale is not None:\n            centers /= self.scale\n\n        return centers\n\n\ndef center_pad_pwr2(image):\n    dimy, dimx = np.shape(image)\n    final_dim = int(2 ** np.ceil(np.log2(max(dimy, dimx))))\n    padl = int(np.floor((final_dim - dimx) / 2))\n    padr = int(np.ceil((final_dim - dimx) / 2))\n    padt = int(np.floor((final_dim - dimy) / 2))\n    padb = int(np.ceil((final_dim - dimy) / 2))\n    return np.pad(image, ((padt, padb), (padl, padr)))\n\n\ndef center_crop_im(image, shape, dim_order_in=\"channels_last\"):\n    if image.ndim == 2:\n        dimy, dimx = image.shape\n    elif image.ndim == 3:\n        if dim_order_in == \"channels_last\":\n            dimy, dimx, dimz = image.shape\n        elif dim_order_in == \"channels_first\":\n            dimz, dimy, dimx = image.shape\n\n    dyf, dxf = shape\n    cropl = int(np.floor((dimx - dxf) / 2))\n    cropr = int(np.ceil((dimx - dxf) / 2))\n    cropt = int(np.floor((dimy - dyf) / 2))\n    cropb = int(np.ceil((dimy - dyf) / 2))\n    if dim_order_in == \"channels_last\":\n        return image[cropt:-cropb, cropl:-cropr]\n    elif dim_order_in == \"channels_first\":\n        return image[:, cropt:-cropb, cropl:-cropr]\n\n\ndef norm_image(image):\n    \"\"\"Normalize image intensities to between 0 and 1\"\"\"\n    image = image - np.min(image)\n    image = image / np.max(image)\n    return image\n\n\nclass FindObjects:\n    \"\"\"\n    Transforms pixel data from NN output into coordinate data\n    \"\"\"\n\n    def __init__(self, nn_output, threshold=0.5, dist_edge=5, dim_order=\"channel_last\"):\n\n        if nn_output.shape[-1] == 1:  # Add background class for 1-channel data\n            nn_output_b = 1 - nn_output\n            nn_output = np.concatenate(\n                (nn_output[:, :, :, None], nn_output_b[:, :, :, None]), axis=3\n            )\n        if dim_order == \"channel_first\":  # make channel dim the last dim\n            nn_output = np.transpose(nn_output, (0, 2, 3, 1))\n        elif dim_order == \"channel_last\":\n            pass\n        else:\n            raise NotImplementedError(\n                'For dim_order, use \"channel_first\" (e.g. pytorch)',\n                'or \"channel_last\" (e.g. tensorflow)',\n            )\n        self.nn_output = nn_output\n        self.threshold = threshold\n        self.dist_edge = dist_edge\n\n    def get_all_coordinates(self):\n        \"\"\"Extract all center coordinates in image via CoM method & store data as a\n        dictionary (key: frame number)\"\"\"\n\n        def find_com(image_data):\n            \"\"\"Find objects via center of mass methods\"\"\"\n            labels, nlabels = ndi.label(image_data)\n            coordinates = np.array(\n                ndi.center_of_mass(image_data, labels, np.arange(nlabels) + 1)\n            )\n            coordinates = coordinates.reshape(coordinates.shape[0], 2)\n            return coordinates\n\n        d_coord = {}\n        for i, decoded_img in enumerate(self.nn_output):\n            coordinates = np.empty((0, 2))\n            category = np.empty((0, 1))\n            # we assume that class backgrpund is always the last one\n            for ch in range(decoded_img.shape[2] - 1):\n                decoded_img_c = np.array(\n                    (decoded_img[:, :, ch] > self.threshold), dtype=\"int\"\n                )\n\n                dilated_img_c = ndi.binary_dilation(decoded_img_c, iterations=2)\n                coord = find_com(dilated_img_c)\n                coord_ch = self.rem_edge_coord(coord)\n                category_ch = np.zeros((coord_ch.shape[0], 1)) + ch\n                coordinates = np.append(coordinates, coord_ch, axis=0)\n                category = np.append(category, category_ch, axis=0)\n            d_coord[i] = np.concatenate((coordinates, category), axis=1)\n        return d_coord\n\n    def rem_edge_coord(self, coordinates):\n        \"\"\"Remove coordinates at the image edges\"\"\"\n\n        def coord_edges(coordinates, w, h):\n            return [\n                coordinates[0] > w - self.dist_edge,\n                coordinates[0] < self.dist_edge,\n                coordinates[1] > h - self.dist_edge,\n                coordinates[1] < self.dist_edge,\n            ]\n\n        w, h = self.nn_output.shape[1:3]\n        coord_to_rem = [\n            idx for idx, c in enumerate(coordinates) if any(coord_edges(c, w, h))\n        ]\n        coord_to_rem = np.array(coord_to_rem, dtype=int)\n        coordinates = np.delete(coordinates, coord_to_rem, axis=0)\n        return coordinates\n", "meta": {"hexsha": "6626618b749090da97e4c6bd403010077d389911", "size": 8102, "ext": "py", "lang": "Python", "max_stars_repo_path": "trained_NN.py", "max_stars_repo_name": "Art-MC/SKX_NN", "max_stars_repo_head_hexsha": "02d5089ea9c4b3ca7c1878e1d9a5811f5da9f6bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trained_NN.py", "max_issues_repo_name": "Art-MC/SKX_NN", "max_issues_repo_head_hexsha": "02d5089ea9c4b3ca7c1878e1d9a5811f5da9f6bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trained_NN.py", "max_forks_repo_name": "Art-MC/SKX_NN", "max_forks_repo_head_hexsha": "02d5089ea9c4b3ca7c1878e1d9a5811f5da9f6bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.331838565, "max_line_length": 88, "alphanum_fraction": 0.5908417675, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19656440062496058}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# ====================================================\n# \n# Module : 3D Depth Segmentation\n#\n# Written by hepheir@gmail.com\n# Last updated : Oct 27 2019\n#\n# ====================================================\n#\n#  Process order\n#\n#  1. Breakage mesh : (3D, 3D, 3D)\n#    1-1. Sort facets into front, slice, or rear areas.\n#\n#  2. Cutting mesh : (3D, 2D, 3D)\n#    2-1. Separate each facet in slice area (after breakage)\n#         into 1 line, and 2 small facets\n#\n# ====================================================\n\nfrom stl import mesh\nimport stl\nimport numpy as np\n\n# ====================================================\n\ndef macro(obj):\n    assert isinstance(obj,mesh.Mesh)\n    breakage = _breakage(obj)\n    cutting  = _cutting(breakage)\n    return np.array(cutting)\n\n# ====================================================\n\ndef _breakage(obj):\n    z = obj.z\n    n = obj.normals\n    front,section_breakage,rear = [],[],[]\n\n    for i in range(obj.__len__()):\n        # Front or behind the xy-surface\n        isFront = isRear = False\n        for _z in z[i]:\n            isFront |= (_z >= 0)\n            isRear  |= (_z <= 0)\n        #  - Find slices\n        if isFront and isRear:\n            section_breakage.append(obj.data[i])\n        #  - Find fronts and behinds\n        elif n[i,2] > 0:\n            if isFront:\n                front.append(obj.data[i])\n            if isRear:\n                rear.append(obj.data[i])\n    return front,section_breakage,rear\n\ndef _cutting(breakage):\n    \"\"\"breakage 과정에서 section으로 분류된 facet의 후처리.\n    - 단면에 걸치는 Facet을 모두 단면을 따라 정밀하게 3분할 및 front/rear로의 재분배.\n    - 처리 이후 section에는 facet data가 아닌 2D 선분정보만 남게 됨.\n    (front와 rear의 데이터형식은 변화없음.)\"\"\"\n\n    def where_z_is_0(v0,v1):\n        \"\"\"두 벡터가 이루는 선분 상에서 z=0인 점을 계산.\"\"\"\n        x0,y0,z0 = v0\n        x1,y1,z1 = v1\n        x = (x0*z1 - x1*z0) / (z1 - z0)\n        y = (y0*z1 - y1*z0) / (z1 - z0)\n        return [x,y,0]\n\n    front, section_breakage, rear = breakage\n    section_cutting = []\n\n    new_data = new_vectors = None\n    i = j = k = A = B = C = z = None\n\n    for normal,vectors,attr in section_breakage:\n        z = vectors[:, 2]\n\n        if np.prod(z) == 0:\n            # Pattern (a), (b) or (c)\n            # TODO\n            print('found 0')\n            continue\n\n        else:\n            # Pattern (e)\n            for i in [0,1,2]:\n                if (z[i] * z[(i+1)%3] > 0): break\n            j = (i+1)%3\n            k = (i+2)%3\n\n            B = where_z_is_0(vectors[j],vectors[k])\n            C = where_z_is_0(vectors[k],vectors[i])\n\n            if B[:2] == C[:2]:\n                # Meaningless to append a dot.\n                continue\n\n            section_cutting.append((B[0],B[1],C[0],C[1]))\n\n            new_vectors = np.array([ # Create new reference : no need to .copy()\n                [ vectors[i], vectors[j], B         ],\n                [ vectors[i], B         , C         ],\n                [ C         , B         , vectors[k]]]) # opp.\n\n        if normal[2] > 0: # if Visible\n            n_of_vectors = len(new_vectors)\n            new_data = np.zeros(n_of_vectors, dtype=mesh.Mesh.dtype)\n            new_data['vectors'] = new_vectors\n            new_data['normals'] = [ normal ] * n_of_vectors\n            new_data['attr']    = [ attr ]   * n_of_vectors\n\n            for i in range(n_of_vectors):\n                if np.sum(new_vectors[:,2]) > 0:\n                    front.append(new_data[i])\n                else:\n                    rear.append(new_data[i])\n    return front, section_cutting, rear", "meta": {"hexsha": "88a982712c87d0929727ceebf0db4a3e006e9cd6", "size": 3558, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/module/depthSegmentation.py", "max_stars_repo_name": "Hepheir/Artifact-Mapping-from-3D-Scanning", "max_stars_repo_head_hexsha": "153c0e65c499e8b0078a4e1efbf70d91ad7feb58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/module/depthSegmentation.py", "max_issues_repo_name": "Hepheir/Artifact-Mapping-from-3D-Scanning", "max_issues_repo_head_hexsha": "153c0e65c499e8b0078a4e1efbf70d91ad7feb58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/module/depthSegmentation.py", "max_forks_repo_name": "Hepheir/Artifact-Mapping-from-3D-Scanning", "max_forks_repo_head_hexsha": "153c0e65c499e8b0078a4e1efbf70d91ad7feb58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4049586777, "max_line_length": 80, "alphanum_fraction": 0.4688026981, "include": true, "reason": "import numpy", "num_tokens": 1052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19656440062496058}}
{"text": "import pymongo\nimport math\nimport datetime\n# import aiohttp\nimport requests\nimport json\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\n\ndef jd_to_date(jd):\n    \"\"\"\n    Convert Julian Day to date.\n\n    Algorithm from 'Practical Astronomy with your Calculator or Spreadsheet',\n        4th ed., Duffet-Smith and Zwart, 2011.\n\n    Parameters\n    ----------\n    jd : float\n        Julian Day\n\n    Returns\n    -------\n    year : int\n        Year as integer. Years preceding 1 A.D. should be 0 or negative.\n        The year before 1 A.D. is 0, 10 B.C. is year -9.\n\n    month : int\n        Month as integer, Jan = 1, Feb. = 2, etc.\n\n    day : float\n        Day, may contain fractional part.\n\n    Examples\n    --------\n    Convert Julian Day 2446113.75 to year, month, and day.\n\n    >>> jd_to_date(2446113.75)\n    (1985, 2, 17.25)\n\n    \"\"\"\n    jd += 0.5\n\n    F, I = math.modf(jd)\n    I = int(I)\n\n    A = math.trunc((I - 1867216.25) / 36524.25)\n\n    if I > 2299160:\n        B = I + 1 + A - math.trunc(A / 4.)\n    else:\n        B = I\n\n    C = B + 1524\n\n    D = math.trunc((C - 122.1) / 365.25)\n\n    E = math.trunc(365.25 * D)\n\n    G = math.trunc((C - E) / 30.6001)\n\n    day = C - E + F - math.trunc(30.6001 * G)\n\n    if G < 13.5:\n        month = G - 1\n    else:\n        month = G - 13\n\n    if month > 2.5:\n        year = D - 4716\n    else:\n        year = D - 4715\n\n    return year, month, day\n\n\ndef jd2date(jd):\n\n    year, month, day = jd_to_date(jd)\n\n    return datetime.datetime(year, month, int(np.floor(day)))\n\n\ndef fetch_cutout(_id, jd, _path='./'):\n\n    date_utc = jd2date(jd).strftime('%Y%m%d')\n    url = f'http://private.caltech.edu:8001/data/stamps/stamps_{date_utc}/{_id}_scimref.jpg'\n\n    filename = os.path.join(_path, f'{_id}_scimref.jpg')\n    r = requests.get(url, stream=True)\n\n    if r.status_code == 200:\n        # if (not os.path.exists(os.path.join('/Users/dmitryduev/_caltech/python/deep-asteroids/data-raw/'+\n        #                                     '20181105_161419__rb_gt_0.97__sl_gt_0.85', f'{_id}_scimref.jpg'))) and \\\n        #         (not os.path.exists(os.path.join('/Users/dmitryduev/_caltech/python/deep-asteroids/data-raw/' +\n        #                                          '20181105_164845__rb_gt_0.97__sl_gt_0.85', f'{_id}_scimref.jpg'))):\n        # if (not os.path.exists(os.path.join('/Users/dmitryduev/_caltech/python/deep-asteroids/data-raw/'+\n        #                                     '20181102_124622__rb_gt_0.8', f'{_id}_scimref.jpg'))):\n        with open(filename, 'wb') as f:\n            f.write(r.content)\n\n\nif __name__ == '__main__':\n    ''' load secrets '''\n    with open('./secrets.json') as sjson:\n        secrets = json.load(sjson)\n\n    client = pymongo.MongoClient(host=secrets['deep_asteroids_mongodb']['host'],\n                                 port=secrets['deep_asteroids_mongodb']['port'])\n\n    db = client['deep-asteroids']\n    db.authenticate(name=secrets['deep_asteroids_mongodb']['user'],\n                    password=secrets['deep_asteroids_mongodb']['pwd'])\n\n    # cursor = db['deep-asteroids'].find({}, {'_id': 1, 'rb': 1, 'sl': 1})\n\n    ''' training sets for the sl classifier (short/long) '''\n    cursor = db['deep-asteroids'].aggregate([\n        {'$match': {'rb': {'$gt': 0.93}}},\n        {'$project': {'_id': 1, 'jd': 1}},\n        {'$sample': {'size': 8000}}\n    ], allowDiskUse=True)\n\n    streaks = list(cursor)\n\n    path = os.path.join('data-raw', datetime.datetime.now().strftime('%Y%m%d_%H%M%S') + '__rb_gt_0.93')\n    os.makedirs(path)\n\n    num_streaks = len(streaks)\n    for si, streak in enumerate(streaks):\n        print(f'fetching {streak[\"_id\"]}: {si+1}/{num_streaks}')\n        fetch_cutout(streak['_id'], streak['jd'], path)\n\n    raise Exception('HAENDE HOCH!!')\n\n    ''' training sets for the kd classifier (keep/ditch) '''\n    cursor = db['deep-asteroids'].aggregate([\n        {'$match': {'rb': {'$gt': 0.97}, 'sl': {'$gt': 0.85}}},\n        {'$project': {'_id': 1, 'jd': 1}},\n        {'$sample': {'size': 3333}}\n    ], allowDiskUse=True)\n\n    streaks = list(cursor)\n\n    path = os.path.join('data-raw', datetime.datetime.now().strftime('%Y%m%d_%H%M%S') + '__rb_gt_0.97__sl_gt_0.85')\n    os.makedirs(path)\n\n    num_streaks = len(streaks)\n    for si, streak in enumerate(streaks):\n        print(f'fetching {streak[\"_id\"]}: {si+1}/{num_streaks}')\n        fetch_cutout(streak['_id'], streak['jd'], path)\n\n    raise Exception('HAENDE HOCH!!')\n\n    ''' Fetch rb > 0.8 '''\n\n    cursor = db['deep-asteroids'].aggregate([\n        {'$match': {'rb': {'$gt': 0.8}}},\n        {'$project': {'_id': 1, 'jd': 1}},\n        {'$sample': {'size': 3000}}\n    ], allowDiskUse=True)\n\n    streaks = list(cursor)\n\n    path = os.path.join('data-raw', datetime.datetime.now().strftime('%Y%m%d_%H%M%S') + '__rb_gt_0.8')\n    os.makedirs(path)\n\n    num_streaks = len(streaks)\n    for si, streak in enumerate(streaks):\n        print(f'fetching {streak[\"_id\"]}: {si+1}/{num_streaks}')\n        fetch_cutout(streak['_id'], streak['jd'], path)\n\n    ''' Fetch rb < 0.2 '''\n\n    cursor = db['deep-asteroids'].aggregate([\n        {'$match': {'rb': {'$lt': 0.2}}},\n        {'$project': {'_id': 1, 'jd': 1}},\n        {'$sample': {'size': 3000}}\n    ], allowDiskUse=True)\n\n    streaks = list(cursor)\n\n    path = os.path.join('data-raw', datetime.datetime.now().strftime('%Y%m%d_%H%M%S') + '__rb_lt_0.2')\n    os.makedirs(path)\n\n    num_streaks = len(streaks)\n    for si, streak in enumerate(streaks):\n        print(f'fetching {streak[\"_id\"]}: {si+1}/{num_streaks}')\n        fetch_cutout(streak['_id'], streak['jd'], path)\n\n    ''' Fetch 0.2 < rb < 0.8 '''\n\n    cursor = db['deep-asteroids'].aggregate([\n        {'$match': {'rb': {'$gt': 0.2, '$lt': 0.8}}},\n        {'$project': {'_id': 1, 'jd': 1}},\n        {'$sample': {'size': 1000}}\n    ], allowDiskUse=True)\n\n    streaks = list(cursor)\n\n    path = os.path.join('data-raw', datetime.datetime.now().strftime('%Y%m%d_%H%M%S') + '__0.2_gt_rb_lt_0.8')\n    os.makedirs(path)\n\n    num_streaks = len(streaks)\n    for si, streak in enumerate(streaks):\n        print(f'fetching {streak[\"_id\"]}: {si+1}/{num_streaks}')\n        fetch_cutout(streak['_id'], streak['jd'], path)\n", "meta": {"hexsha": "371852ca1c4d1f7624ea2fef7c0fe1a1302f6201", "size": 6169, "ext": "py", "lang": "Python", "max_stars_repo_path": "dev/sample.py", "max_stars_repo_name": "dmitryduev/deep-asteroids", "max_stars_repo_head_hexsha": "2eb648c3de552ec0ec90947d2af8a100f2b67ce1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-04-15T14:53:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-23T03:13:18.000Z", "max_issues_repo_path": "dev/sample.py", "max_issues_repo_name": "dmitryduev/deep-asteroids", "max_issues_repo_head_hexsha": "2eb648c3de552ec0ec90947d2af8a100f2b67ce1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2019-12-16T21:24:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T23:37:51.000Z", "max_forks_repo_path": "dev/sample.py", "max_forks_repo_name": "dmitryduev/deep-asteroids", "max_forks_repo_head_hexsha": "2eb648c3de552ec0ec90947d2af8a100f2b67ce1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-24T18:29:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-24T18:29:45.000Z", "avg_line_length": 29.3761904762, "max_line_length": 118, "alphanum_fraction": 0.5595720538, "include": true, "reason": "import numpy", "num_tokens": 1926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19656440062496058}}
{"text": "\"\"\"\nBSD 3-Clause License\n\nCopyright (c) 2019, HJ Reachability Group\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\n* Neither the name of the copyright holder nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nAuthor(s): David Fridovich-Keil ( dfk@eecs.berkeley.edu )\n\"\"\"\n################################################################################\n#\n# Script to run a 3 player collision avoidance example intended to model\n# a T-intersection.\n#\n################################################################################\n\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom unicycle_4d import Unicycle4D\nfrom point_mass_2d import PointMass2D\nfrom product_multiplayer_dynamical_system import \\\n    ProductMultiPlayerDynamicalSystem\n\nfrom point import Point\nfrom polyline import Polyline\n\nfrom ilq_solver import ILQSolver\nfrom proximity_cost import ProximityCost\nfrom product_state_proximity_cost import ProductStateProximityCost\nfrom semiquadratic_cost import SemiquadraticCost\nfrom quadratic_cost import QuadraticCost\nfrom semiquadratic_polyline_cost import SemiquadraticPolylineCost\nfrom quadratic_polyline_cost import QuadraticPolylineCost\nfrom player_cost import PlayerCost\nfrom box_constraint import BoxConstraint\n\nfrom visualizer import Visualizer\nfrom logger import Logger\n\n# General parameters.\nTIME_HORIZON = 10.0   # s\nTIME_RESOLUTION = 0.1 # s\nHORIZON_STEPS = int(TIME_HORIZON / TIME_RESOLUTION)\nLOG_DIRECTORY = \"./logs/three_player/\"\n\n# Create dynamics.\ncar1 = Unicycle4D()\ncar2 = Unicycle4D()\nped = PointMass2D()\ndynamics = ProductMultiPlayerDynamicalSystem(\n    [car1, car2, ped], T=TIME_RESOLUTION)\n\n# Choose initial states and set initial control laws to zero, such that\n# we start with a situation that looks like this:\n#\n#              (car 2)\n#             |   X   .       |\n#             |   :   .       |\n#             |  \\./  .       |\n#             |       .      <--X (ped)\n#             |       .        ------------------\n#             |       .\n#             |       .        ..................\n#             |       .\n#             |       .        ------------------\n#             |       .   ^   |\n#             |       .   :   |         (+y)\n#             |       .   :   |          |\n#             |       .   X   |          |\n#                      (car 1)           |______ (+x)\n#\n# We shall set up the costs so that car 2 wants to turn and car 1 / ped 1\n# continue straight in their initial direction of motion.\n# We shall assume that lanes are 4 m wide and set the origin to be in the\n# bottom left along the road boundary.\ncar1_theta0 = np.pi / 2.0 # 90 degree heading\ncar1_v0 = 0.1             # 5 m/s initial speed\ncar1_x0 = np.array([\n    [6.5],\n    [-5.0],\n    [car1_theta0],\n    [car1_v0]\n])\n\ncar2_theta0 = -np.pi / 2.0 # -90 degree heading\ncar2_v0 = 5.0              # 2 m/s initial speed\ncar2_x0 = np.array([\n    [1.5],\n    [65.0],\n    [car2_theta0],\n    [car2_v0]\n])\n\nped_vx0 = 0.25 # moving right at 0.25 m/s\nped_vy0 = 0.0   # moving normal to traffic flow\nped_x0 = np.array([\n    [-4.0],\n    [19.0],\n    [ped_vx0],\n    [ped_vy0]\n])\n\nstacked_x0 = np.concatenate([car1_x0, car2_x0, ped_x0], axis=0)\n\ncar1_Ps = [np.zeros((car1._u_dim, dynamics._x_dim))] * HORIZON_STEPS\ncar2_Ps = [np.zeros((car2._u_dim, dynamics._x_dim))] * HORIZON_STEPS\nped_Ps = [np.zeros((ped._u_dim, dynamics._x_dim))] * HORIZON_STEPS\n\ncar1_alphas = [np.zeros((car1._u_dim, 1))] * HORIZON_STEPS\ncar2_alphas = [np.zeros((car2._u_dim, 1))] * HORIZON_STEPS\nped_alphas = [np.zeros((ped._u_dim, 1))] * HORIZON_STEPS\n\n# Create environment.\ncar1_position_indices_in_product_state = (0, 1)\ncar1_polyline = Polyline([Point(6.0, -100.0), Point(6.0, 100.0)])\ncar1_polyline_boundary_cost = SemiquadraticPolylineCost(\n    car1_polyline, 1.0, car1_position_indices_in_product_state,\n    \"car1_polyline_boundary\")\ncar1_polyline_cost = QuadraticPolylineCost(\n    car1_polyline, car1_position_indices_in_product_state, \"car1_polyline\")\n\ncar1_goal = Point(6.0, 30.0)\ncar1_goal_cost = ProximityCost(\n    car1_position_indices_in_product_state, car1_goal, np.inf, \"car1_goal\")\n\ncar2_position_indices_in_product_state = (4, 5)\ncar2_polyline = Polyline([Point(2.0, 100.0),\n                          Point(2.0, 18.0),\n                          Point(2.5, 15.0),\n                          Point(3.0, 14.0),\n                          Point(5.0, 12.5),\n                          Point(8.0, 12.0),\n                          Point(100.0, 12.0)])\ncar2_polyline_boundary_cost = SemiquadraticPolylineCost(\n    car2_polyline, 1.0, car2_position_indices_in_product_state,\n    \"car2_polyline_boundary\")\ncar2_polyline_cost = QuadraticPolylineCost(\n    car2_polyline, car2_position_indices_in_product_state, \"car2_polyline\")\n\ncar2_goal = Point(16.0, 12.0)\ncar2_goal_cost = ProximityCost(\n    car2_position_indices_in_product_state, car2_goal, np.inf, \"car2_goal\")\n\nped_position_indices_in_product_state = (8, 9)\nped_goal = Point(10.0, 19.0)\nped_goal_cost = ProximityCost(\n    ped_position_indices_in_product_state, ped_goal, np.inf, \"ped_goal\")\n\n# Penalize speed above a threshold for all players.\ncar1_v_index_in_product_state = 3\ncar1_maxv = 10.0 # m/s\ncar1_maxv_cost = SemiquadraticCost(\n    car1_v_index_in_product_state, car1_maxv, True, \"car1_maxv\")\n\ncar2_v_index_in_product_state = 7\ncar2_maxv = 10.0 # m/s\ncar2_maxv_cost = SemiquadraticCost(\n    car2_v_index_in_product_state, car2_maxv, True, \"car2_maxv\")\n\nped_vx_index_in_product_state = 10\nped_vy_index_in_product_state = 11\nped_maxvx = 0.5 # m/s\nped_maxvy = 0.5 # m/s\nped_maxvx_cost = SemiquadraticCost(\n    ped_vx_index_in_product_state, ped_maxvx, True, \"ped_maxvx\")\nped_maxvy_cost = SemiquadraticCost(\n    ped_vy_index_in_product_state, ped_maxvy, True, \"ped_maxvy\")\n\n# Control costs for all players.\ncar1_w_cost = QuadraticCost(0, 0.0, \"car1_w_cost\")\ncar1_a_cost = QuadraticCost(1, 0.0, \"car1_a_cost\")\n\ncar2_w_cost = QuadraticCost(0, 0.0, \"car2_w_cost\")\ncar2_a_cost = QuadraticCost(1, 0.0, \"car2_a_cost\")\n\nped_ax_cost = QuadraticCost(0, 0.0, \"ped_ax_cost\")\nped_ay_cost = QuadraticCost(1, 0.0, \"ped_ay_cost\")\n\n# Proximity cost.\nPROXIMITY_THRESHOLD = 1.0\nproximity_cost = ProductStateProximityCost(\n    [car1_position_indices_in_product_state,\n     car2_position_indices_in_product_state,\n     ped_position_indices_in_product_state],\n    PROXIMITY_THRESHOLD,\n    \"proximity\")\n\n# Build up total costs for both players. This is basically a zero-sum game.\ncar1_cost = PlayerCost()\ncar1_cost.add_cost(car1_goal_cost, \"x\", -1.0)\ncar1_cost.add_cost(car1_polyline_cost, \"x\", 10.0)\ncar1_cost.add_cost(car1_polyline_boundary_cost, \"x\", 100.0)\ncar1_cost.add_cost(car1_maxv_cost, \"x\", 100.0)\ncar1_cost.add_cost(proximity_cost, \"x\", 10.0)\n\ncar1_player_id = 0\ncar1_cost.add_cost(car1_w_cost, car1_player_id, 10.0)\ncar1_cost.add_cost(car1_a_cost, car1_player_id, 1.0)\n\ncar2_cost = PlayerCost()\ncar2_cost.add_cost(car2_goal_cost, \"x\", -1.0)\ncar2_cost.add_cost(car2_polyline_cost, \"x\", 10.0)\ncar2_cost.add_cost(car2_polyline_boundary_cost, \"x\", 100.0)\ncar2_cost.add_cost(car2_maxv_cost, \"x\", 100.0)\ncar2_cost.add_cost(proximity_cost, \"x\", 10.0)\n\ncar2_player_id = 1\ncar2_cost.add_cost(car2_w_cost, car2_player_id, 10.0)\ncar2_cost.add_cost(car2_a_cost, car2_player_id, 1.0)\n\nped_cost = PlayerCost()\nped_cost.add_cost(ped_goal_cost, \"x\", -1.0)\nped_cost.add_cost(ped_maxvx_cost, \"x\", 100.0)\nped_cost.add_cost(ped_maxvy_cost, \"x\", 100.0)\nped_cost.add_cost(proximity_cost, \"x\", 2.0)\n\nped_player_id = 2\nped_cost.add_cost(ped_ax_cost, ped_player_id, 0.001)\nped_cost.add_cost(ped_ay_cost, ped_player_id, 0.001)\n\n# Visualizer.\nvisualizer = Visualizer(\n    [car1_position_indices_in_product_state,\n     car2_position_indices_in_product_state,\n     ped_position_indices_in_product_state],\n    [car1_polyline_boundary_cost,\n     car1_goal_cost,\n     car2_polyline_boundary_cost,\n     car2_goal_cost,\n     ped_goal_cost],\n    [\".-r\", \".-g\", \".-b\"],\n    1,\n    False,\n    plot_lims=[-10, 30, -10, 70])\n\n# Logger.\nif not os.path.exists(LOG_DIRECTORY):\n    os.makedirs(LOG_DIRECTORY)\n\nlogger = Logger(os.path.join(LOG_DIRECTORY, 'intersection_example.pkl'))\n\n# Set up ILQSolver.\nsolver = ILQSolver(dynamics,\n                   [car1_cost, car2_cost, ped_cost],\n                   stacked_x0,\n                   [car1_Ps, car2_Ps, ped_Ps],\n                   [car1_alphas, car2_alphas, ped_alphas],\n                   0.02,\n                   0.1,\n                   logger,\n                   visualizer,\n                   None)\n\nsolver.run()\n", "meta": {"hexsha": "61941924196867c1b2b308524c79dba090053564", "size": 9794, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/three_player_intersection_pedestrian_example.py", "max_stars_repo_name": "anjianli21/ilqgames", "max_stars_repo_head_hexsha": "2be8e2bc6d34a9a6296d341b75d59e37c9057ad5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 53, "max_stars_repo_stars_event_min_datetime": "2019-11-25T02:51:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T18:30:02.000Z", "max_issues_repo_path": "python/three_player_intersection_pedestrian_example.py", "max_issues_repo_name": "anjianli21/ilqgames", "max_issues_repo_head_hexsha": "2be8e2bc6d34a9a6296d341b75d59e37c9057ad5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2019-10-05T20:22:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T20:10:35.000Z", "max_forks_repo_path": "python/three_player_intersection_pedestrian_example.py", "max_forks_repo_name": "anjianli21/ilqgames", "max_forks_repo_head_hexsha": "2be8e2bc6d34a9a6296d341b75d59e37c9057ad5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2020-01-02T13:33:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T01:55:28.000Z", "avg_line_length": 34.8540925267, "max_line_length": 80, "alphanum_fraction": 0.6876659179, "include": true, "reason": "import numpy", "num_tokens": 2779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19656440062496058}}
{"text": "# pylint: disable=E1101\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader, TensorDataset\n\nimport numpy as np\nfrom physionet import PhysioNet, get_data_min_max, variable_time_collate_fn2\nfrom sklearn import model_selection\nfrom sklearn import metrics\nfrom person_activity import PersonActivity\n\n\ndef count_parameters(model):\n    return sum(p.numel() for p in model.parameters() if p.requires_grad)\n\n\ndef log_normal_pdf(x, mean, logvar, mask):\n    const = torch.from_numpy(np.array([2. * np.pi])).float().to(x.device)\n    const = torch.log(const)\n    return -.5 * (const + logvar + (x - mean) ** 2. / torch.exp(logvar)) * mask\n\n\ndef normal_kl(mu1, lv1, mu2, lv2):\n    v1 = torch.exp(lv1)\n    v2 = torch.exp(lv2)\n    lstd1 = lv1 / 2.\n    lstd2 = lv2 / 2.\n\n    kl = lstd2 - lstd1 + ((v1 + (mu1 - mu2) ** 2.) / (2. * v2)) - .5\n    return kl\n\n\ndef mean_squared_error(orig, pred, mask):\n    error = (orig - pred) ** 2\n    error = error * mask\n    return error.sum() / mask.sum()\n\n\ndef normalize_masked_data(data, mask, att_min, att_max):\n    # we don't want to divide by zero\n    att_max[att_max == 0.] = 1.\n\n    if (att_max != 0.).all():\n        data_norm = (data - att_min) / att_max\n    else:\n        raise Exception(\"Zero!\")\n\n    if torch.isnan(data_norm).any():\n        raise Exception(\"nans!\")\n\n    # set masked out elements back to zero\n    data_norm[mask == 0] = 0\n\n    return data_norm, att_min, att_max\n\n\ndef evaluate(dim, rec, dec, test_loader, args, num_sample=10, device=\"cuda\"):\n    mse, test_n = 0.0, 0.0\n    with torch.no_grad():\n        for test_batch in test_loader:\n            test_batch = test_batch.to(device)\n            observed_data, observed_mask, observed_tp = (\n                test_batch[:, :, :dim],\n                test_batch[:, :, dim: 2 * dim],\n                test_batch[:, :, -1],\n            )\n            if args.sample_tp and args.sample_tp < 1:\n                subsampled_data, subsampled_tp, subsampled_mask = subsample_timepoints(\n                    observed_data.clone(), observed_tp.clone(), observed_mask.clone(), args.sample_tp)\n            else:\n                subsampled_data, subsampled_tp, subsampled_mask = \\\n                    observed_data, observed_tp, observed_mask\n            out = rec(torch.cat((subsampled_data, subsampled_mask), 2), subsampled_tp)\n            qz0_mean, qz0_logvar = (\n                out[:, :, : args.latent_dim],\n                out[:, :, args.latent_dim:],\n            )\n            epsilon = torch.randn(\n                num_sample, qz0_mean.shape[0], qz0_mean.shape[1], qz0_mean.shape[2]\n            ).to(device)\n            z0 = epsilon * torch.exp(0.5 * qz0_logvar) + qz0_mean\n            z0 = z0.view(-1, qz0_mean.shape[1], qz0_mean.shape[2])\n            batch, seqlen = observed_tp.size()\n            time_steps = (\n                observed_tp[None, :, :].repeat(num_sample, 1, 1).view(-1, seqlen)\n            )\n            pred_x = dec(z0, time_steps)\n            pred_x = pred_x.view(num_sample, -1, pred_x.shape[1], pred_x.shape[2])\n            pred_x = pred_x.mean(0)\n            mse += mean_squared_error(observed_data, pred_x, observed_mask) * batch\n            test_n += batch\n    return mse / test_n\n\n\ndef compute_losses(dim, dec_train_batch, qz0_mean, qz0_logvar, pred_x, args, device):\n    observed_data, observed_mask \\\n        = dec_train_batch[:, :, :dim], dec_train_batch[:, :, dim:2*dim]\n\n    noise_std = args.std  # default 0.1\n    noise_std_ = torch.zeros(pred_x.size()).to(device) + noise_std\n    noise_logvar = 2. * torch.log(noise_std_).to(device)\n    logpx = log_normal_pdf(observed_data, pred_x, noise_logvar,\n                           observed_mask).sum(-1).sum(-1)\n    pz0_mean = pz0_logvar = torch.zeros(qz0_mean.size()).to(device)\n    analytic_kl = normal_kl(qz0_mean, qz0_logvar,\n                            pz0_mean, pz0_logvar).sum(-1).sum(-1)\n    if args.norm:\n        logpx /= observed_mask.sum(-1).sum(-1)\n        analytic_kl /= observed_mask.sum(-1).sum(-1)\n    return logpx, analytic_kl\n\n\ndef evaluate_classifier(model, test_loader, dec=None, args=None, classifier=None,\n                        dim=41, device='cuda', reconst=False, num_sample=1):\n    pred = []\n    true = []\n    test_loss = 0\n    for test_batch, label in test_loader:\n        test_batch, label = test_batch.to(device), label.to(device)\n        batch_len = test_batch.shape[0]\n        observed_data, observed_mask, observed_tp \\\n            = test_batch[:, :, :dim], test_batch[:, :, dim:2*dim], test_batch[:, :, -1]\n        with torch.no_grad():\n            out = model(\n                torch.cat((observed_data, observed_mask), 2), observed_tp)\n            if reconst:\n                qz0_mean, qz0_logvar = out[:, :,\n                                           :args.latent_dim], out[:, :, args.latent_dim:]\n                epsilon = torch.randn(\n                    num_sample, qz0_mean.shape[0], qz0_mean.shape[1], qz0_mean.shape[2]).to(device)\n                z0 = epsilon * torch.exp(.5 * qz0_logvar) + qz0_mean\n                z0 = z0.view(-1, qz0_mean.shape[1], qz0_mean.shape[2])\n                if args.classify_pertp:\n                    pred_x = dec(z0, observed_tp[None, :, :].repeat(\n                        num_sample, 1, 1).view(-1, observed_tp.shape[1]))\n                    #pred_x = pred_x.view(num_sample, batch_len, pred_x.shape[1], pred_x.shape[2])\n                    out = classifier(pred_x)\n                else:\n                    out = classifier(z0)\n            if args.classify_pertp:\n                N = label.size(-1)\n                out = out.view(-1, N)\n                label = label.view(-1, N)\n                _, label = label.max(-1)\n                test_loss += nn.CrossEntropyLoss()(out, label.long()).item() * batch_len * 50.\n            else:\n                label = label.unsqueeze(0).repeat_interleave(\n                    num_sample, 0).view(-1)\n                test_loss += nn.CrossEntropyLoss()(out, label).item() * batch_len * num_sample\n        pred.append(out.cpu().numpy())\n        true.append(label.cpu().numpy())\n    pred = np.concatenate(pred, 0)\n    true = np.concatenate(true, 0)\n    acc = np.mean(pred.argmax(1) == true)\n    auc = metrics.roc_auc_score(\n        true, pred[:, 1]) if not args.classify_pertp else 0.\n    return test_loss/pred.shape[0], acc, auc\n\n\ndef get_mimiciii_data(args):\n    input_dim = 12\n    x = np.load('../../../neuraltimeseries/Dataset/final_input3.npy')\n    y = np.load('../../../neuraltimeseries/Dataset/final_output3.npy')\n    x = x[:, :25]\n    x = np.transpose(x, (0, 2, 1))\n\n    # normalize values and time\n    observed_vals, observed_mask, observed_tp = x[:, :,\n                                                  :input_dim], x[:, :, input_dim:2*input_dim], x[:, :, -1]\n    if np.max(observed_tp) != 0.:\n        observed_tp = observed_tp / np.max(observed_tp)\n\n    if not args.nonormalize:\n        for k in range(input_dim):\n            data_min, data_max = float('inf'), 0.\n            for i in range(observed_vals.shape[0]):\n                for j in range(observed_vals.shape[1]):\n                    if observed_mask[i, j, k]:\n                        data_min = min(data_min, observed_vals[i, j, k])\n                        data_max = max(data_max, observed_vals[i, j, k])\n            #print(data_min, data_max)\n            if data_max == 0:\n                data_max = 1\n            observed_vals[:, :, k] = (\n                observed_vals[:, :, k] - data_min)/data_max\n    # set masked out elements back to zero\n    observed_vals[observed_mask == 0] = 0\n    print(observed_vals[0], observed_tp[0])\n    print(x.shape, y.shape)\n    kfold = model_selection.StratifiedKFold(\n        n_splits=5, shuffle=True, random_state=0)\n    splits = [(train_inds, test_inds)\n              for train_inds, test_inds in kfold.split(np.zeros(len(y)), y)]\n    x_train, y_train = x[splits[args.split][0]], y[splits[args.split][0]]\n    test_data_x, test_data_y = x[splits[args.split]\n                                 [1]], y[splits[args.split][1]]\n    if not args.old_split:\n        train_data_x, val_data_x, train_data_y, val_data_y = \\\n            model_selection.train_test_split(\n                x_train, y_train, stratify=y_train, test_size=0.2, random_state=0)\n    else:\n        frac = int(0.8*x_train.shape[0])\n        train_data_x, val_data_x = x_train[:frac], x_train[frac:]\n        train_data_y, val_data_y = y_train[:frac], y_train[frac:]\n\n    print(train_data_x.shape, train_data_y.shape, val_data_x.shape, val_data_y.shape,\n          test_data_x.shape, test_data_y.shape)\n    print(np.sum(test_data_y))\n    train_data_combined = TensorDataset(torch.from_numpy(train_data_x).float(),\n                                        torch.from_numpy(train_data_y).long().squeeze())\n    val_data_combined = TensorDataset(torch.from_numpy(val_data_x).float(),\n                                      torch.from_numpy(val_data_y).long().squeeze())\n    test_data_combined = TensorDataset(torch.from_numpy(test_data_x).float(),\n                                       torch.from_numpy(test_data_y).long().squeeze())\n    train_dataloader = DataLoader(\n        train_data_combined, batch_size=args.batch_size, shuffle=False)\n    test_dataloader = DataLoader(\n        test_data_combined, batch_size=args.batch_size, shuffle=False)\n    val_dataloader = DataLoader(\n        val_data_combined, batch_size=args.batch_size, shuffle=False)\n\n    data_objects = {\"train_dataloader\": train_dataloader,\n                    \"test_dataloader\": test_dataloader,\n                    \"val_dataloader\": val_dataloader,\n                    \"input_dim\": input_dim}\n    return data_objects\n\n\ndef get_physionet_data(args, device, q, flag=1):\n    train_dataset_obj = PhysioNet('data/physionet', train=True,\n                                  quantization=q,\n                                  download=True, n_samples=min(10000, args.n),\n                                  device=device)\n    # Use custom collate_fn to combine samples with arbitrary time observations.\n    # Returns the dataset along with mask and time steps\n    test_dataset_obj = PhysioNet('data/physionet', train=False,\n                                 quantization=q,\n                                 download=True, n_samples=min(10000, args.n),\n                                 device=device)\n\n    # Combine and shuffle samples from physionet Train and physionet Test\n    total_dataset = train_dataset_obj[:len(train_dataset_obj)]\n\n    if not args.classif:\n        # Concatenate samples from original Train and Test sets\n        # Only 'training' physionet samples are have labels.\n        # Therefore, if we do classifiction task, we don't need physionet 'test' samples.\n        total_dataset = total_dataset + \\\n            test_dataset_obj[:len(test_dataset_obj)]\n    print(len(total_dataset))\n    # Shuffle and split\n    train_data, test_data = model_selection.train_test_split(total_dataset, train_size=0.8,\n                                                             random_state=42, shuffle=True)\n\n    record_id, tt, vals, mask, labels = train_data[0]\n\n    # n_samples = len(total_dataset)\n    input_dim = vals.size(-1)\n    data_min, data_max = get_data_min_max(total_dataset, device)\n    batch_size = min(min(len(train_dataset_obj), args.batch_size), args.n)\n    if flag:\n        test_data_combined = variable_time_collate_fn(test_data, device, classify=args.classif,\n                                                      data_min=data_min, data_max=data_max)\n\n        if args.classif:\n            train_data, val_data = model_selection.train_test_split(train_data, train_size=0.8,\n                                                                    random_state=11, shuffle=True)\n            train_data_combined = variable_time_collate_fn(\n                train_data, device, classify=args.classif, data_min=data_min, data_max=data_max)\n            val_data_combined = variable_time_collate_fn(\n                val_data, device, classify=args.classif, data_min=data_min, data_max=data_max)\n            print(train_data_combined[1].sum(\n            ), val_data_combined[1].sum(), test_data_combined[1].sum())\n            print(train_data_combined[0].size(), train_data_combined[1].size(),\n                  val_data_combined[0].size(), val_data_combined[1].size(),\n                  test_data_combined[0].size(), test_data_combined[1].size())\n\n            train_data_combined = TensorDataset(\n                train_data_combined[0], train_data_combined[1].long().squeeze())\n            val_data_combined = TensorDataset(\n                val_data_combined[0], val_data_combined[1].long().squeeze())\n            test_data_combined = TensorDataset(\n                test_data_combined[0], test_data_combined[1].long().squeeze())\n        else:\n            train_data_combined = variable_time_collate_fn(\n                train_data, device, classify=args.classif, data_min=data_min, data_max=data_max)\n            print(train_data_combined.size(), test_data_combined.size())\n\n        train_dataloader = DataLoader(\n            train_data_combined, batch_size=batch_size, shuffle=False)\n        test_dataloader = DataLoader(\n            test_data_combined, batch_size=batch_size, shuffle=False)\n\n    else:\n        train_dataloader = DataLoader(train_data, batch_size=batch_size, shuffle=False,\n                                      collate_fn=lambda batch: variable_time_collate_fn2(batch, args, device, data_type=\"train\",\n                                                                                         data_min=data_min, data_max=data_max))\n        test_dataloader = DataLoader(test_data, batch_size=batch_size, shuffle=False,\n                                     collate_fn=lambda batch: variable_time_collate_fn2(batch, args, device, data_type=\"test\",\n                                                                                        data_min=data_min, data_max=data_max))\n\n    attr_names = train_dataset_obj.params\n    data_objects = {\"dataset_obj\": train_dataset_obj,\n                    \"train_dataloader\": train_dataloader,\n                    \"test_dataloader\": test_dataloader,\n                    \"input_dim\": input_dim,\n                    \"n_train_batches\": len(train_dataloader),\n                    \"n_test_batches\": len(test_dataloader),\n                    \"attr\": attr_names,  # optional\n                    \"classif_per_tp\": False,  # optional\n                    \"n_labels\": 1}  # optional\n    if args.classif:\n        val_dataloader = DataLoader(\n            val_data_combined, batch_size=batch_size, shuffle=False)\n        data_objects[\"val_dataloader\"] = val_dataloader\n    return data_objects\n\n\ndef variable_time_collate_fn(batch, device=torch.device(\"cpu\"), classify=False, activity=False,\n                             data_min=None, data_max=None):\n    \"\"\"\n    Expects a batch of time series data in the form of (record_id, tt, vals, mask, labels) where\n      - record_id is a patient id\n      - tt is a 1-dimensional tensor containing T time values of observations.\n      - vals is a (T, D) tensor containing observed values for D variables.\n      - mask is a (T, D) tensor containing 1 where values were observed and 0 otherwise.\n      - labels is a list of labels for the current patient, if labels are available. Otherwise None.\n    Returns:\n      combined_tt: The union of all time observations.\n      combined_vals: (M, T, D) tensor containing the observed values.\n      combined_mask: (M, T, D) tensor containing 1 where values were observed and 0 otherwise.\n    \"\"\"\n    D = batch[0][2].shape[1]\n    # number of labels\n    N = batch[0][-1].shape[1] if activity else 1\n    len_tt = [ex[1].size(0) for ex in batch]\n    maxlen = np.max(len_tt)\n    enc_combined_tt = torch.zeros([len(batch), maxlen]).to(device)\n    enc_combined_vals = torch.zeros([len(batch), maxlen, D]).to(device)\n    enc_combined_mask = torch.zeros([len(batch), maxlen, D]).to(device)\n    if classify:\n        if activity:\n            combined_labels = torch.zeros([len(batch), maxlen, N]).to(device)\n        else:\n            combined_labels = torch.zeros([len(batch), N]).to(device)\n\n    for b, (record_id, tt, vals, mask, labels) in enumerate(batch):\n        currlen = tt.size(0)\n        enc_combined_tt[b, :currlen] = tt.to(device)\n        enc_combined_vals[b, :currlen] = vals.to(device)\n        enc_combined_mask[b, :currlen] = mask.to(device)\n        if classify:\n            if activity:\n                combined_labels[b, :currlen] = labels.to(device)\n            else:\n                combined_labels[b] = labels.to(device)\n\n    if not activity:\n        enc_combined_vals, _, _ = normalize_masked_data(enc_combined_vals, enc_combined_mask,\n                                                        att_min=data_min, att_max=data_max)\n\n    if torch.max(enc_combined_tt) != 0.:\n        enc_combined_tt = enc_combined_tt / torch.max(enc_combined_tt)\n\n    combined_data = torch.cat(\n        (enc_combined_vals, enc_combined_mask, enc_combined_tt.unsqueeze(-1)), 2)\n    if classify:\n        return combined_data, combined_labels\n    else:\n        return combined_data\n\n\ndef get_activity_data(args, device):\n    n_samples = min(10000, args.n)\n    dataset_obj = PersonActivity('data/PersonActivity',\n                                 download=True, n_samples=n_samples, device=device)\n\n    print(dataset_obj)\n\n    train_data, test_data = model_selection.train_test_split(dataset_obj, train_size=0.8,\n                                                             random_state=42, shuffle=True)\n\n    # train_data = [train_data[i] for i in np.random.choice(len(train_data), len(train_data))]\n    # test_data = [test_data[i] for i in np.random.choice(len(test_data), len(test_data))]\n\n    record_id, tt, vals, mask, labels = train_data[0]\n    input_dim = vals.size(-1)\n\n    batch_size = min(min(len(dataset_obj), args.batch_size), args.n)\n    test_data_combined = variable_time_collate_fn(test_data, device, classify=args.classif,\n                                                  activity=True)\n    train_data, val_data = model_selection.train_test_split(train_data, train_size=0.8,\n                                                            random_state=11, shuffle=True)\n    train_data_combined = variable_time_collate_fn(\n        train_data, device, classify=args.classif, activity=True)\n    val_data_combined = variable_time_collate_fn(\n        val_data, device, classify=args.classif, activity=True)\n    print(train_data_combined[1].sum(\n    ), val_data_combined[1].sum(), test_data_combined[1].sum())\n    print(train_data_combined[0].size(), train_data_combined[1].size(),\n          val_data_combined[0].size(), val_data_combined[1].size(),\n          test_data_combined[0].size(), test_data_combined[1].size())\n\n    train_data_combined = TensorDataset(\n        train_data_combined[0], train_data_combined[1].long())\n    val_data_combined = TensorDataset(\n        val_data_combined[0], val_data_combined[1].long())\n    test_data_combined = TensorDataset(\n        test_data_combined[0], test_data_combined[1].long())\n\n    train_dataloader = DataLoader(\n        train_data_combined, batch_size=batch_size, shuffle=False)\n    test_dataloader = DataLoader(\n        test_data_combined, batch_size=batch_size, shuffle=False)\n    val_dataloader = DataLoader(\n        val_data_combined, batch_size=batch_size, shuffle=False)\n\n    #attr_names = train_dataset_obj.params\n    data_objects = {\"train_dataloader\": train_dataloader,\n                    \"test_dataloader\": test_dataloader,\n                    \"val_dataloader\": val_dataloader,\n                    \"input_dim\": input_dim,\n                    \"n_train_batches\": len(train_dataloader),\n                    \"n_test_batches\": len(test_dataloader),\n                    # \"attr\": attr_names, #optional\n                    \"classif_per_tp\": False,  # optional\n                    \"n_labels\": 1}  # optional\n\n    return data_objects\n\n\ndef irregularly_sampled_data_gen(n=10, length=20, seed=0):\n    np.random.seed(seed)\n    # obs_times = obs_times_gen(n)\n    obs_values, ground_truth, obs_times = [], [], []\n    for i in range(n):\n        t1 = np.sort(np.random.uniform(low=0.0, high=1.0, size=length))\n        t2 = np.sort(np.random.uniform(low=0.0, high=1.0, size=length))\n        t3 = np.sort(np.random.uniform(low=0.0, high=1.0, size=length))\n        a = 10 * np.random.randn()\n        b = 10 * np.random.rand()\n        f1 = .8 * np.sin(20*(t1+a) + np.sin(20*(t1+a))) + \\\n            0.01 * np.random.randn()\n        f2 = -.5 * np.sin(20*(t2+a + 20) + np.sin(20*(t2+a + 20))\n                          ) + 0.01 * np.random.randn()\n        f3 = np.sin(12*(t3+b)) + 0.01 * np.random.randn()\n        obs_times.append(np.stack((t1, t2, t3), axis=0))\n        obs_values.append(np.stack((f1, f2, f3), axis=0))\n        #obs_values.append([f1.tolist(), f2.tolist(), f3.tolist()])\n        t = np.linspace(0, 1, 100)\n        fg1 = .8 * np.sin(20*(t+a) + np.sin(20*(t+a)))\n        fg2 = -.5 * np.sin(20*(t+a + 20) + np.sin(20*(t+a + 20)))\n        fg3 = np.sin(12*(t+b))\n        #ground_truth.append([f1.tolist(), f2.tolist(), f3.tolist()])\n        ground_truth.append(np.stack((fg1, fg2, fg3), axis=0))\n    return obs_values, ground_truth, obs_times\n\n\ndef sine_wave_data_gen(args, seed=0):\n    np.random.seed(seed)\n    obs_values, ground_truth, obs_times = [], [], []\n    for _ in range(args.n):\n        t = np.sort(np.random.choice(np.linspace(\n            0, 1., 101), size=args.length, replace=True))\n        b = 10 * np.random.rand()\n        f = np.sin(12*(t+b)) + 0.1 * np.random.randn()\n        obs_times.append(t)\n        obs_values.append(f)\n        tc = np.linspace(0, 1, 100)\n        fg = np.sin(12*(tc + b))\n        ground_truth.append(fg)\n\n    obs_values = np.array(obs_values)\n    obs_times = np.array(obs_times)\n    ground_truth = np.array(ground_truth)\n    print(obs_values.shape, obs_times.shape, ground_truth.shape)\n    mask = np.ones_like(obs_values)\n    combined_data = np.concatenate((np.expand_dims(obs_values, axis=2), np.expand_dims(\n        mask, axis=2), np.expand_dims(obs_times, axis=2)), axis=2)\n    print(combined_data.shape)\n    print(combined_data[0])\n    train_data, test_data = model_selection.train_test_split(combined_data, train_size=0.8,\n                                                             random_state=42, shuffle=True)\n    print(train_data.shape, test_data.shape)\n    train_dataloader = DataLoader(torch.from_numpy(\n        train_data).float(), batch_size=args.batch_size, shuffle=False)\n    test_dataloader = DataLoader(torch.from_numpy(\n        test_data).float(), batch_size=args.batch_size, shuffle=False)\n    data_objects = {\"dataset_obj\": combined_data,\n                    \"train_dataloader\": train_dataloader,\n                    \"test_dataloader\": test_dataloader,\n                    \"input_dim\": 1,\n                    \"ground_truth\": np.array(ground_truth)}\n    return data_objects\n\n\ndef kernel_smoother_data_gen(args, alpha=100., seed=0, ref_points=10):\n    np.random.seed(seed)\n    obs_values, ground_truth, obs_times = [], [], []\n    for _ in range(args.n):\n        key_values = np.random.randn(ref_points)\n        key_points = np.linspace(0, 1, ref_points)\n\n        query_points = np.sort(np.random.choice(\n            np.linspace(0, 1., 101), size=args.length, replace=True))\n        # query_points = np.sort(np.random.uniform(low=0.0, high=1.0, size=args.length))\n        weights = np.exp(-alpha*(np.expand_dims(query_points,\n                                                1) - np.expand_dims(key_points, 0))**2)\n        weights /= weights.sum(1, keepdims=True)\n        query_values = np.dot(weights, key_values)\n        obs_values.append(query_values)\n        obs_times.append(query_points)\n\n        query_points = np.linspace(0, 1, 100)\n        weights = np.exp(-alpha*(np.expand_dims(query_points,\n                                                1) - np.expand_dims(key_points, 0))**2)\n        weights /= weights.sum(1, keepdims=True)\n        query_values = np.dot(weights, key_values)\n        ground_truth.append(query_values)\n\n    obs_values = np.array(obs_values)\n    obs_times = np.array(obs_times)\n    ground_truth = np.array(ground_truth)\n    print(obs_values.shape, obs_times.shape, ground_truth.shape)\n    mask = np.ones_like(obs_values)\n    combined_data = np.concatenate((np.expand_dims(obs_values, axis=2), np.expand_dims(\n        mask, axis=2), np.expand_dims(obs_times, axis=2)), axis=2)\n    print(combined_data.shape)\n    print(combined_data[0])\n    train_data, test_data = model_selection.train_test_split(combined_data, train_size=0.8,\n                                                             random_state=42, shuffle=True)\n    print(train_data.shape, test_data.shape)\n    train_dataloader = DataLoader(torch.from_numpy(\n        train_data).float(), batch_size=args.batch_size, shuffle=False)\n    test_dataloader = DataLoader(torch.from_numpy(\n        test_data).float(), batch_size=args.batch_size, shuffle=False)\n    data_objects = {\"dataset_obj\": combined_data,\n                    \"train_dataloader\": train_dataloader,\n                    \"test_dataloader\": test_dataloader,\n                    \"input_dim\": 1,\n                    \"ground_truth\": np.array(ground_truth)}\n    return data_objects\n\n\ndef get_toy_data(args):\n    dim = 3\n    obs_values, ground_truth, obs_times = irregularly_sampled_data_gen(\n        args.n, args.length)\n    obs_times = np.array(obs_times).reshape(args.n, -1)\n    obs_values = np.array(obs_values)\n    combined_obs_values = np.zeros((args.n, dim, obs_times.shape[-1]))\n    mask = np.zeros((args.n, dim, obs_times.shape[-1]))\n    for i in range(dim):\n        combined_obs_values[:, i, i *\n                            args.length: (i+1)*args.length] = obs_values[:, i]\n        mask[:, i, i*args.length: (i+1)*args.length] = 1.\n    #print(combined_obs_values.shape, mask.shape, obs_times.shape, np.expand_dims(obs_times, axis=1).shape)\n    combined_data = np.concatenate(\n        (combined_obs_values, mask, np.expand_dims(obs_times, axis=1)), axis=1)\n    combined_data = np.transpose(combined_data, (0, 2, 1))\n    print(combined_data.shape)\n    train_data, test_data = model_selection.train_test_split(combined_data, train_size=0.8,\n                                                             random_state=42, shuffle=True)\n    print(train_data.shape, test_data.shape)\n    train_dataloader = DataLoader(torch.from_numpy(\n        train_data).float(), batch_size=args.batch_size, shuffle=False)\n    test_dataloader = DataLoader(torch.from_numpy(\n        test_data).float(), batch_size=args.batch_size, shuffle=False)\n    data_objects = {\"dataset_obj\": combined_data,\n                    \"train_dataloader\": train_dataloader,\n                    \"test_dataloader\": test_dataloader,\n                    \"input_dim\": dim,\n                    \"ground_truth\": np.array(ground_truth)}\n    return data_objects\n\n\ndef compute_pertp_loss(label_predictions, true_label, mask):\n    criterion = nn.CrossEntropyLoss(reduction='none')\n    n_traj, n_tp, n_dims = label_predictions.size()\n    label_predictions = label_predictions.reshape(n_traj * n_tp, n_dims)\n    true_label = true_label.reshape(n_traj * n_tp, n_dims)\n    mask = torch.sum(mask, -1) > 0\n    mask = mask.reshape(n_traj * n_tp,  1)\n    _, true_label = true_label.max(-1)\n    ce_loss = criterion(label_predictions, true_label.long())\n    ce_loss = ce_loss * mask\n    return torch.sum(ce_loss)/mask.sum()\n\n\ndef get_physionet_data_extrap(args, device, q, flag=1):\n    train_dataset_obj = PhysioNet('data/physionet', train=True,\n                                  quantization=q,\n                                  download=True, n_samples=min(10000, args.n),\n                                  device=device)\n    # Use custom collate_fn to combine samples with arbitrary time observations.\n    # Returns the dataset along with mask and time steps\n    test_dataset_obj = PhysioNet('data/physionet', train=False,\n                                 quantization=q,\n                                 download=True, n_samples=min(10000, args.n),\n                                 device=device)\n\n    # Combine and shuffle samples from physionet Train and physionet Test\n    total_dataset = train_dataset_obj[:len(train_dataset_obj)]\n\n    if not args.classif:\n        # Concatenate samples from original Train and Test sets\n        # Only 'training' physionet samples are have labels.\n        # Therefore, if we do classifiction task, we don't need physionet 'test' samples.\n        total_dataset = total_dataset + \\\n            test_dataset_obj[:len(test_dataset_obj)]\n    print(len(total_dataset))\n    # Shuffle and split\n    train_data, test_data = model_selection.train_test_split(total_dataset, train_size=0.8,\n                                                             random_state=42, shuffle=True)\n\n    record_id, tt, vals, mask, labels = train_data[0]\n\n    # n_samples = len(total_dataset)\n    input_dim = vals.size(-1)\n    data_min, data_max = get_data_min_max(total_dataset, device)\n    batch_size = min(min(len(train_dataset_obj), args.batch_size), args.n)\n\n    def extrap(test_data):\n        enc_test_data = []\n        dec_test_data = []\n        for (record_id, tt, vals, mask, labels) in test_data:\n            midpt = 0\n            for tp in tt:\n                if tp < 24:\n                    midpt += 1\n                else:\n                    break\n            if mask[:midpt].sum() and mask[midpt:].sum():\n                enc_test_data.append(\n                    (record_id, tt[:midpt], vals[:midpt], mask[:midpt], labels))\n                dec_test_data.append(\n                    (record_id, tt[midpt:], vals[midpt:], mask[midpt:], labels))\n        return enc_test_data, dec_test_data\n\n    enc_train_data, dec_train_data = extrap(train_data)\n    enc_test_data, dec_test_data = extrap(test_data)\n    enc_train_data_combined = variable_time_collate_fn(\n        enc_train_data, device, classify=args.classif, data_min=data_min, data_max=data_max)\n    dec_train_data_combined = variable_time_collate_fn(\n        dec_train_data, device, classify=args.classif, data_min=data_min, data_max=data_max)\n    enc_test_data_combined = variable_time_collate_fn(\n        enc_test_data, device, classify=args.classif, data_min=data_min, data_max=data_max)\n    dec_test_data_combined = variable_time_collate_fn(\n        dec_test_data, device, classify=args.classif, data_min=data_min, data_max=data_max)\n    print(enc_train_data_combined.shape, dec_train_data_combined.shape)\n    print(enc_test_data_combined.shape, dec_test_data_combined.shape)\n\n    # keep the timepoints in enc between 0.0 and 0.5\n    enc_train_data_combined[:, :, -1] *= 0.5\n    enc_test_data_combined[:, :, -1] *= 0.5\n    print(enc_train_data_combined[0, :, -1], dec_train_data_combined[0, :, -1])\n    enc_train_dataloader = DataLoader(\n        enc_train_data_combined, batch_size=batch_size, shuffle=False)\n    dec_train_dataloader = DataLoader(\n        dec_train_data_combined, batch_size=batch_size, shuffle=False)\n    enc_test_dataloader = DataLoader(\n        enc_test_data_combined, batch_size=batch_size, shuffle=False)\n    dec_test_dataloader = DataLoader(\n        dec_test_data_combined, batch_size=batch_size, shuffle=False)\n\n    attr_names = train_dataset_obj.params\n    data_objects = {\"dataset_obj\": train_dataset_obj,\n                    \"enc_train_dataloader\": enc_train_dataloader,\n                    \"enc_test_dataloader\": enc_test_dataloader,\n                    \"dec_train_dataloader\": dec_train_dataloader,\n                    \"dec_test_dataloader\": dec_test_dataloader,\n                    \"input_dim\": input_dim,\n                    \"attr\": attr_names,  # optional\n                    \"classif_per_tp\": False,  # optional\n                    \"n_labels\": 1}  # optional\n\n    return data_objects\n\n\ndef subsample_timepoints(data, time_steps, mask, percentage_tp_to_sample=None):\n    # Subsample percentage of points from each time series\n    for i in range(data.size(0)):\n        # take mask for current training sample and sum over all features --\n        # figure out which time points don't have any measurements at all in this batch\n        current_mask = mask[i].sum(-1).cpu()\n        non_missing_tp = np.where(current_mask > 0)[0]\n        n_tp_current = len(non_missing_tp)\n        n_to_sample = int(n_tp_current * percentage_tp_to_sample)\n        subsampled_idx = sorted(np.random.choice(\n            non_missing_tp, n_to_sample, replace=False))\n        tp_to_set_to_zero = np.setdiff1d(non_missing_tp, subsampled_idx)\n\n        data[i, tp_to_set_to_zero] = 0.\n        if mask is not None:\n            mask[i, tp_to_set_to_zero] = 0.\n\n    return data, time_steps, mask\n", "meta": {"hexsha": "81030c55250a4daa5d1b9ced8055592987bbda43", "size": 32695, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/utils.py", "max_stars_repo_name": "mobiledoctorDev/mTANs", "max_stars_repo_head_hexsha": "a59cc52e19920fc8eadb75ed57c308c009dde791", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45, "max_stars_repo_stars_event_min_datetime": "2021-03-23T02:38:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:02:34.000Z", "max_issues_repo_path": "src/utils.py", "max_issues_repo_name": "mobiledoctorDev/mTANs", "max_issues_repo_head_hexsha": "a59cc52e19920fc8eadb75ed57c308c009dde791", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-11-12T22:03:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-13T06:51:25.000Z", "max_forks_repo_path": "src/utils.py", "max_forks_repo_name": "mobiledoctorDev/mTANs", "max_forks_repo_head_hexsha": "a59cc52e19920fc8eadb75ed57c308c009dde791", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-05-04T18:53:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-27T05:22:46.000Z", "avg_line_length": 46.840974212, "max_line_length": 128, "alphanum_fraction": 0.6139776724, "include": true, "reason": "import numpy", "num_tokens": 7693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.19656440062496056}}
{"text": "from __future__ import print_function\nimport numpy as np\nimport powderday.config as cfg\nimport pdb\n\nimport astropy.units as u\nimport astropy.constants as constants\nfrom astropy import cosmology as cosmo\n\nimport fsps \nfrom datetime import datetime\nfrom powderday.grid_construction import stars_coordinate_boost\n\nfrom multiprocessing import Pool\nfrom functools import partial\nfrom itertools import repeat\nfrom scipy.integrate import simps\n\nfrom powderday.nebular_emission.cloudy_tools import calc_LogQ, cmdf, get_nearest,convert_metals\nfrom powderday.analytics import logu_diagnostic,dump_emlines\nfrom powderday.nebular_emission.cloudy_model import get_nebular\n\n#this is required to keep the reg as a strong reference.  for some\n#reason in the star_list.append in star_list_gen, reg otherwise gets\n#garbage collected.\nimport gc\ngc.set_threshold(0)\n\n# Lazily initialize FSPS\nsp = None\n\nclass Stars:\n    def __init__(self,mass,metals,positions,age,sed_bin=[-1,-1,-1],lum=-1,fsps_zmet=20,all_metals=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1]):\n        self.mass = mass\n        self.metals = metals\n        self.positions = positions\n        self.age = age\n        self.sed_bin = sed_bin\n        self.lum = lum\n        self.fsps_zmet = fsps_zmet\n        self.all_metals = all_metals\n\n    def info(self):\n        return(self.mass,self.metals,self.positions,self.age,self.sed_bin,self.lum,self.fsps_zmet)\n\ndef star_list_gen(boost,dx,dy,dz,reg,ds):\n    print ('[SED_gen/star_list_gen]: reading in stars particles for SPS calculation')\n    mass = reg[\"starmasses\"].value\n    positions = reg[\"starcoordinates\"].value\n    age = reg[\"stellarages\"].value\n    nstars = len(reg[\"stellarages\"].value) \n    el = ['He', 'C', 'N', 'O', 'Ne', 'Mg', 'Si', 'S', 'Ca', 'Fe' ]\n\n    try:                                                                                                                                                                \n        metals = np.zeros((nstars,11))-10.0\n        for i in range(11):\n            if i == 0:\n                el_str = \"\"\n            else:\n                el_str = \"_\"+el[i-1]\n            metals[:, i] = reg[\"starmetals\"+el_str].value\n    except:\n        metals = reg[\"starmetals\"].value\n    print ('number of new stars =',nstars)\n    \n    #calculate the fsps interpolated metallicity\n\n    #if the metallicity has many fields, and not just global\n    #metallicity then just extract the global metallicity\n    if metals.ndim > 1:\n        metals_tot = metals[:,0]\n    else:\n        metals_tot = metals\n\n    print ('[SED_gen/star_list_gen:] Manually increasing the newstar metallicities by: ',cfg.par.Z_init)\n    metals_tot += cfg.par.Z_init\n    \n    #ADVANCED FEATURE - if force_stellar_metallcities or force_stellar_ages are set, then we set to those values\n    if cfg.par.FORCE_STELLAR_AGES:\n        print (\"[SED_GEN/stars_list_gen:]  FORCE_STELLAR_AGES is set to True: setting all stars to age: %e Gyr\"%cfg.par.FORCE_STELLAR_AGES_VALUE)\n        age = np.repeat(cfg.par.FORCE_STELLAR_AGES_VALUE,nstars)\n\n    if cfg.par.FORCE_STELLAR_METALLICITIES:\n        print (\"[SED_GEN/stars_list_gen:]  FORCE_STELLAR_METALLICITIES is set to True: setting all stars to metallicity: %e \"%cfg.par.FORCE_STELLAR_METALLICITIES_VALUE)\n        metals_tot = np.repeat(cfg.par.FORCE_STELLAR_METALLICITIES_VALUE,nstars)\n\n\n\n    zmet = fsps_metallicity_interpolate(metals_tot)\n    #mwd(zmet,mass,'zmet_distribution.png')\n\n    #print '[SED_gen/star_list_gen: ] fsps zmet codes:',zmet\n\n    #create the stars_list full of Stars objects\n    stars_list = []\n    \n    if metals.ndim > 1:\n        for i in range(nstars):\n            stars_list.append(Stars(mass[i],metals_tot[i],positions[i],age[i],fsps_zmet=zmet[i],all_metals = metals[i]))\n    else:\n        for i in range(nstars):\n            stars_list.append(Stars(mass[i],metals_tot[i],positions[i],age[i],fsps_zmet=zmet[i]))\n    \n    #boost stellar positions to grid center\n    print ('boosting new stars to coordinate center')\n    stars_list = stars_coordinate_boost(stars_list,boost)\n\n    #orig_stars_list_len = len(stars_list)\n    \n    #ASSIGN DISK AND BULGE STARS - note, if these don't exist, it will\n    #just make empty lists\n\n   \n\n    \n    bulgestars_list = []\n    diskstars_list = []\n\n    \n    #in principle, we should just be able to do the following blocks\n    #if the particle types exist. the issue is that different groups\n    #use PartType2 and 3 as 'filler' particle types, so they may exist\n    #even if they don't correspond to disk/bulge stars.\n\n\n    if ds.cosmological_simulation == False:\n\n        #Disk Stars\n\n        if (\"diskstarcoordinates\") in ds.derived_field_list:\n            \n            disk_positions = reg[(\"diskstarcoordinates\")].value\n            disk_masses =  reg[(\"diskstarmasses\")].value\n            nstars_disk = len(disk_masses)\n     \n            #create the disk_list full of DiskStars objects\n            for i in range(nstars_disk):\n                diskstars_list.append(Stars(disk_masses[i],cfg.par.solar,disk_positions[i],cfg.par.disk_stars_age))\n\n            print ('boosting disk stars to coordinate center')    \n            diskstars_list = stars_coordinate_boost(diskstars_list,boost)\n\n        #orig_disk_stars_list_len = nstars_disk\n            \n       \n        #Bulge Stars\n\n\n        if (\"bulgestarcoordinates\") in ds.derived_field_list:\n            bulge_positions = reg[(\"bulgestarcoordinates\")].value\n            bulge_masses =  reg[(\"bulgestarmasses\")].value\n            nstars_bulge = len(bulge_masses)\n            \n            #create the bulge_list full of BulgeStars objects\n            \n            for i in range(nstars_bulge):\n                bulgestars_list.append(Stars(bulge_masses[i],cfg.par.solar,bulge_positions[i],cfg.par.bulge_stars_age))\n                \n\n            print ('boosting bulge stars to coordinate center')\n            bulgestars_list = stars_coordinate_boost(bulgestars_list,boost)\n\n\n    #EXPERIMENTAL FEATURES\n    if cfg.par.SOURCES_IN_CENTER == True:\n        for i in range(nstars):\n            stars_list[i].positions[:] =  np.array([0,0,0])\n        if (\"bulgestarcoordinates\") in ds.derived_field_list:\n            for i in range(nstars_bulge):\n                bulgestars_list[i].positions[:] =  np.array([0,0,0])\n            for i in range(nstars_disk):\n                diskstars_list[i].positions[:] = np.array([0,0,0])\n\n    if cfg.par.SOURCES_RANDOM_POSITIONS == True:\n        print (\"================================\")\n        print (\"SETTING SOURCES TO RANDOM POSITIONS\")\n        print (\"================================\")\n        for i in range(nstars):\n            xpos,ypos,zpos = np.random.uniform(-0.9*dx/2.,0.9*dx/2.),np.random.uniform(-0.9*dy/2.,0.9*dy/2.),np.random.uniform(-0.9*dz/2.,0.9*dz/2.)\n            stars_list[i].positions[:] = np.array([xpos,ypos,zpos])\n\n        if (\"bulgestarcoordinates\") in ds.derived_field_list:\n            for i in range(nstars_bulge):\n                xpos,ypos,zpos = np.random.uniform(-0.9*dx/2.,0.9*dx/2.),np.random.uniform(-0.9*dy/2.,0.9*dy/2.),np.random.uniform(-0.9*dz/2.,0.9*dz/2.)\n                bulgestars_list[i].positions[:] = np.array([xpos,ypos,zpos])\n            for i in range(nstars_disk):\n                xpos,ypos,zpos = np.random.uniform(-0.9*dx/2.,0.9*dx/2.),np.random.uniform(-0.9*dy/2.,0.9*dy/2.),np.random.uniform(-0.9*dz/2.,0.9*dz/2.)\n                diskstars_list[i].positions[:] = np.array([xpos,ypos,zpos])\n\n    return stars_list,diskstars_list,bulgestars_list,reg\n\n\n\ndef allstars_sed_gen(stars_list,cosmoflag,sp):\n\n\n    #NOTE this part is just for the gadget simulations - this will\n    #eventually become obviated as it gets passed into a function to\n    #populate the stars_list with objects as we start to feed in new\n    #types of simulation results.\n\n    nstars = len(stars_list)\n    \n    #get just the wavelength array\n    sp.params[\"tage\"] = stars_list[0].age\n    sp.params[\"imf_type\"] = cfg.par.imf_type\n    sp.params[\"pagb\"] = cfg.par.pagb\n    sp.params[\"sfh\"] = 0\n    sp.params[\"zmet\"] = stars_list[0].fsps_zmet\n    sp.params[\"add_neb_emission\"] = cfg.par.add_neb_emission\n    sp.params[\"add_agb_dust_model\"] = cfg.par.add_agb_dust_model\n    sp.params['gas_logu'] = cfg.par.gas_logu\n    if cfg.par.FORCE_gas_logz == False:\n        sp.params['gas_logz'] = np.log10(stars_list[0].metals/cfg.par.solar)\n    else:\n        sp.params['gas_logz'] = cfg.par.gas_logz\n\n        '''\n    sp = fsps.StellarPopulation(tage=stars_list[0].age,imf_type=cfg.par.imf_type,pagb = cfg.par.pagb,sfh=0,zmet=stars_list[0].fsps_zmet,\n                                add_neb_emission = cfg.par.add_neb_emission, add_agb_dust_model=cfg.par.add_agb_dust_model)\n                                '''\n    spec = sp.get_spectrum(tage=stars_list[0].age,zmet=stars_list[0].fsps_zmet)\n    nu = 1.e8*constants.c.cgs.value/spec[0]\n    nlam = len(nu)\n\n    nprocesses = np.min([cfg.par.n_processes,len(stars_list)]) #the pool.map will barf if there are less star bins than process threads\n\n    #initialize the process pool and build the chunks\n    p = Pool(processes = nprocesses)\n    nchunks = nprocesses\n\n\n    chunk_start_indices = []\n    chunk_start_indices.append(0) #the start index is obviously 0\n\n\n    #this should just be int(nstars/nchunks) but in case nstars < nchunks, we need to ensure that this is at least  1\n    delta_chunk_indices = np.max([int(nstars / nchunks),1]) \n    print ('delta_chunk_indices = ',delta_chunk_indices)\n    \n    for n in range(1,nchunks):\n        chunk_start_indices.append(chunk_start_indices[n-1]+delta_chunk_indices)\n\n    '''\n    chunk_start_indices = list(np.fix(np.arange(0,nstars,np.fix(nstars/nchunks))))\n    #because this can result in too many chunks sometimes given the number of processors:\n    chunk_start_indices = chunk_start_indices[0:nchunks]\n    '''\n    print ('Entering Pool.map multiprocessing for Stellar SED generation')\n    list_of_chunks = []\n    for n in range(nchunks):\n        stars_list_chunk = stars_list[chunk_start_indices[n]:chunk_start_indices[n]+delta_chunk_indices]\n        #if we're on the last chunk, we might not have the full list included, so need to make sure that we have that here\n        if n == nchunks-1: \n            stars_list_chunk = stars_list[chunk_start_indices[n]::]\n\n        list_of_chunks.append(stars_list_chunk)\n    \n\n    t1=datetime.now()\n    chunk_sol = p.map(newstars_gen, [arg for arg in list_of_chunks])\n    \n    t2=datetime.now()\n    print ('Execution time for SED generation in Pool.map multiprocessing = '+str(t2-t1))\n\n    \n    stellar_fnu = np.zeros([nstars,nlam])\n    star_counter=0\n    for i in range(nchunks):\n        fnu_list = chunk_sol[i] #this is a list of the stellar_fnu's returned by that chunk\n        for j in range(len(fnu_list)):\n            stellar_fnu[star_counter,:] = fnu_list[j,:]\n            star_counter+=1\n\n\n\n\n    p.close()\n    p.terminate()\n    p.join()\n\n\n    stellar_nu = nu\n\n\n\n    if cosmoflag == False:\n\n        #calculate the SED for disk stars; note, this gets calculated\n        #whether or not disk stars actually exist.  if they don't exist,\n        #bogus values for the disk age and metallicity are assigned based\n        #on whatever par.disk_stars_age and metallicity are.  it's no big\n        #deal since these SEDs don't end up getting added to the model in\n        #source_creation.  \n        \n        #note, even if there are no disk/bulge stars, these are still\n        #created since they're completely based on input parameters in\n        #parameters_master.  they just won't get used at a later point\n        #as there will be no disk/bulge star positions to add them to.\n\n        #dust_tesc is an absolute value (not relative to min star age) as the ages of these stars are input by the user\n\n        # Load in the metallicity legend\n        fsps_metals = np.loadtxt(cfg.par.metallicity_legend)\n\n        sp.params[\"tage\"] = cfg.par.disk_stars_age\n        sp.params[\"imf_type\"] = cfg.par.imf_type\n        sp.params[\"imf1\"] = cfg.par.imf1\n        sp.params[\"imf2\"] = cfg.par.imf2\n        sp.params[\"imf3\"] = cfg.par.imf3\n        sp.params[\"pagb\"] = cfg.par.pagb\n        sp.params[\"sfh\"] = 0\n        sp.params[\"zmet\"] = cfg.par.disk_stars_metals\n        sp.params[\"add_neb_emission\"] = cfg.par.add_neb_emission\n        sp.params[\"add_agb_dust_model\"] = cfg.par.add_agb_dust_model\n        sp.params['gas_logu'] = cfg.par.gas_logu\n        if cfg.par.FORCE_gas_logz == False:\n            sp.params['gas_logz'] = np.log10(fsps_metals[cfg.par.disk_stars_metals]/cfg.par.solar)\n        else:\n            sp.params['gas_logz'] = cfg.par.gas_logz\n\n        spec = sp.get_spectrum(tage=cfg.par.disk_stars_age,zmet=cfg.par.disk_stars_metals)\n        disk_fnu = spec[1]\n        \n        #calculate the SED for bulge stars\n        sp.params[\"tage\"] = cfg.par.bulge_stars_age\n        sp.params[\"imf_type\"] = cfg.par.imf_type\n        sp.params[\"imf1\"] = cfg.par.imf1\n        sp.params[\"imf2\"] = cfg.par.imf2\n        sp.params[\"imf3\"] = cfg.par.imf3\n        sp.params[\"pagb\"] = cfg.par.pagb\n        sp.params[\"sfh\"] = 0\n        sp.params[\"zmet\"] = cfg.par.bulge_stars_metals\n        sp.params[\"add_neb_emission\"] = cfg.par.add_neb_emission\n        sp.params[\"add_agb_dust_model\"] = cfg.par.add_agb_dust_model\n        sp.params['gas_logu'] = cfg.par.gas_logu\n        if cfg.par.FORCE_gas_logz == False:\n            sp.params['gas_logz'] = np.log10(fsps_metals[cfg.par.bulge_stars_metals]/cfg.par.solar)\n        else:\n            sp.params['gas_logz'] = cfg.par.gas_logz\n\n\n        spec = sp.get_spectrum(tage=cfg.par.bulge_stars_age,zmet=cfg.par.bulge_stars_metals)\n        bulge_fnu = spec[1]\n    \n\n    else: #we have a cosmological simulation\n\n        disk_fnu = []\n        bulge_fnu = []\n        \n\n    total_lum_in_sed_gen = 0.\n    for i in range(stellar_fnu.shape[0]):\n        total_lum_in_sed_gen += np.absolute(np.trapz(stellar_fnu[i,:],x=nu))\n\n    print ('[SED_gen: ] total_lum_in_sed_gen = ',total_lum_in_sed_gen)\n\n    #return positions,disk_positions,bulge_positions,mass,stellar_nu,stellar_fnu,disk_masses,disk_fnu,bulge_masses,bulge_fnu\n    return stellar_nu,stellar_fnu,disk_fnu,bulge_fnu\n\n\ndef newstars_gen(stars_list):\n    global sp\n    if sp is None:\n        sp = fsps.StellarPopulation()\n\n    #the newstars (particle type 4; so, for cosmological runs, this is all\n    #stars) are calculated in a separate function with just one argument so that it is can be fed \n    #into pool.map for multithreading.\n    #sp = fsps.StellarPopulation()\n    sp.params[\"tage\"] = stars_list[0].age\n    sp.params[\"imf_type\"] = cfg.par.imf_type\n    sp.params[\"pagb\"] = cfg.par.pagb\n    sp.params[\"sfh\"] = 0\n    sp.params[\"zmet\"] = stars_list[0].fsps_zmet\n    sp.params[\"add_neb_emission\"] = False\n    sp.params[\"add_agb_dust_model\"] = cfg.par.add_agb_dust_model\n\n    #first figure out how many wavelengths there are\n    \n    spec = sp.get_spectrum(tage=stars_list[0].age,zmet=stars_list[0].fsps_zmet)\n    nu = 1.e8*constants.c.cgs.value/spec[0]\n\n    nlam = len(nu)\n\n    stellar_nu = np.zeros([nlam])\n    stellar_fnu = np.zeros([len(stars_list),nlam])\n    \n  \n    minage = 13 #Gyr\n    for i in range(len(stars_list)): \n        if stars_list[i].age < minage:\n            minage = stars_list[i].age\n\n    tesc_age = np.log10((minage+cfg.par.birth_cloud_clearing_age)*1.e9)\n\n\n    # Get the number of ionizing photons from SED\n\n    #calculate the SEDs for new stars\n    for i in range(len(stars_list)):\n        \n        sp.params[\"tage\"] = stars_list[i].age\n        sp.params[\"imf_type\"] = cfg.par.imf_type\n        sp.params[\"imf1\"] = cfg.par.imf1\n        sp.params[\"imf2\"] = cfg.par.imf2\n        sp.params[\"imf3\"] = cfg.par.imf3\n        sp.params[\"pagb\"] = cfg.par.pagb\n        sp.params[\"sfh\"] = 0\n        sp.params[\"zmet\"] = stars_list[i].fsps_zmet\n        sp.params[\"add_neb_emission\"] = False\n        sp.params[\"add_agb_dust_model\"] = cfg.par.add_agb_dust_model\n\n        if cfg.par.CF_on == True:\n            sp.params[\"dust_type\"] = 0\n            sp.params[\"dust1\"] = 1\n            sp.params[\"dust2\"] = 0\n            sp.params[\"dust_tesc\"] = tesc_age\n\n        spec_noneb = sp.get_spectrum(tage=stars_list[i].age,zmet=stars_list[i].fsps_zmet)\n        f = spec_noneb[1]\n\n        pagb = cfg.par.add_pagb_stars and cfg.par.PAGB_min_age <= stars_list[i].age <= cfg.par.PAGB_max_age\n        young_star = cfg.par.add_young_stars and cfg.par.HII_min_age <= stars_list[i].age <= cfg.par.HII_max_age\n\n        if (cfg.par.add_neb_emission or cfg.par.use_cmdf) and (young_star or pagb):\n\n            # Cluster Mass Distribution Funtion is used only when the star particle's mass is gretaer than the maximum cluster mass and use_cmdf is True. \n\n            if stars_list[i].mass/constants.M_sun.cgs.value > 10**cfg.par.cmdf_max_mass and cfg.par.use_cmdf:\n                cluster_mass, num_clusters = cmdf(stars_list[i].mass/constants.M_sun.cgs.value,int(cfg.par.cmdf_bins),cfg.par.cmdf_min_mass,\n                        cfg.par.cmdf_max_mass, cfg.par.cmdf_beta)\n            \n            else:\n                cluster_mass = [np.log10(stars_list[i].mass/constants.M_sun.cgs.value)]\n                num_clusters = [1]\n\n            f = np.zeros(nlam)\n            cloudy_nlam = len(np.genfromtxt(cfg.par.pd_source_dir + \"/powderday/nebular_emission/data/refLines.dat\", delimiter=','))\n            line_em = np.zeros([cloudy_nlam])\n            \n            for j in range(len(cluster_mass)):\n                num_HII_clusters = num_clusters[j]\n                neb_file_output = cfg.par.NEB_DEBUG\n\n                sp.params[\"add_neb_emission\"] = False\n                if cfg.par.add_neb_emission:\n                    # id_val = 0, 1, 2 for young stars, Post-AGB star and AGNs respectively.\n                    if young_star:\n                        id_val = 0\n                        Rinner_per_Rs = cfg.par.HII_Rinner_per_Rs\n                        nh = cfg.par.HII_nh       \n                        escape_fraction  = cfg.par.HII_escape_fraction\n                    \n                    elif pagb:\n                        id_val = 1\n                        Rinner_per_Rs = cfg.par.PAGB_Rinner_per_Rs\n                        nh = cfg.par.PAGB_nh    \n                        escape_fraction  = cfg.par.PAGB_escape_fraction\n\n                    if cfg.par.HII_alpha_enhance: #Setting Zstar based on Fe/H \n                        Fe = stars_list[i].all_metals[-1]\n\n                        # Gizmo metallicity structure, photospheric abundances from Asplund et al. 2009:\n                        # Photospheric mass fraction of H = 0.7381\n                        # Photospheric mass fraction of Fe = 1.31e-3\n\n                        # Converting from mass fraction to atomic fraction of Fe\n                        # Taking atmoic mass of H = 1.008u\n                        # Taking atmoic mass of Fe = 55.845u\n                        FeH = (Fe/0.7381)*(1.008/55.845)\n\n                        # Solar atomic fraction of Fe. Calculated by substituting Fe = 1.31e-3 in the previous equation\n                        FeH_sol = 3.22580645e-5\n\n                        Logzsol = np.log10(FeH/FeH_sol)\n                        \n                        sp1 = fsps.StellarPopulation(zcontinuous=1)\n                        sp1.params[\"tage\"] = stars_list[i].age\n                        sp1.params[\"imf_type\"] = cfg.par.imf_type\n                        sp1.params[\"imf1\"] = cfg.par.imf1\n                        sp1.params[\"imf2\"] = cfg.par.imf2\n                        sp1.params[\"imf3\"] = cfg.par.imf3\n                        sp1.params[\"pagb\"] = cfg.par.pagb\n                        sp1.params[\"sfh\"] = 0\n                        sp1.params[\"zmet\"] = stars_list[i].fsps_zmet\n                        sp1.params[\"add_neb_emission\"] = False\n                        sp1.params[\"add_agb_dust_model\"] = cfg.par.add_agb_dust_model\n                        sp1.params[\"logzsol\"] = Logzsol\n\n                        if cfg.par.CF_on == True:\n                            sp1.params[\"dust_type\"] = 0\n                            sp1.params[\"dust1\"] = 1\n                            sp1.params[\"dust2\"] = 0\n                            sp1.params[\"dust_tesc\"] = tesc_age\n\n                        spec = sp1.get_spectrum(tage=stars_list[i].age)\n\n                    else:\n                        spec = sp.get_spectrum(tage=stars_list[i].age,zmet=stars_list[i].fsps_zmet)\n\n                    alpha = 2.5e-13 # Recombination Rate (assuming T = 10^4 K)\n\n                    if cfg.par.FORCE_gas_logu[id_val]:\n                        LogU = cfg.par.gas_logu[id_val]\n                        LogQ = np.log10((10 ** (3*LogU))*(36*np.pi*(constants.c.cgs.value**3))/((alpha**2)*nh))\n                        Rs = ((3*(10 ** LogQ))/(4*np.pi*(nh**2)*alpha))**(1./3.)\n                    \n                    elif cfg.par.FORCE_logq[id_val]:\n                        LogQ = cfg.par.source_logq[id_val]\n                        Rs = ((3*(10 ** LogQ))/(4*np.pi*(nh**2)*alpha))**(1./3.)\n                        LogU = np.log10((10**LogQ)/(4*np.pi*Rs*Rs*nh*constants.c.cgs.value))\n\n                    else:\n                        LogQ = calc_LogQ(1.e8*constants.c.cgs.value/spec[0], spec[1]*constants.L_sun.cgs.value\n                                , efrac=escape_fraction, mstar=10**cluster_mass[j])   \n                        Rs = ((3*(10 ** LogQ))/(4*np.pi*(nh**2)*alpha))**(1./3.)\n                        LogU = np.log10((10**LogQ)/(4*np.pi*Rs*Rs*nh*constants.c.cgs.value))+cfg.par.gas_logu_init[id_val]\n                        LogQ = np.log10((10 ** (3*LogU))*(36*np.pi*(constants.c.cgs.value**3))/((alpha**2)*nh))\n                        Rs = ((3*(10 ** LogQ))/(4*np.pi*(nh**2)*alpha))**(1./3.)\n\n                    if cfg.par.FORCE_inner_radius[id_val]:\n                        Rin = cfg.par.inner_radius[id_val]\n\n                    else:\n                        Rin = Rinner_per_Rs*Rs\n\n                    if cfg.par.FORCE_gas_logz[id_val]:\n                        LogZ = cfg.par.gas_logz[id_val]\n                    \n                    else:\n                        LogZ = np.log10(stars_list[i].metals/cfg.par.solar)\n\n\n                    if neb_file_output:\n                        if cfg.par.use_cloudy_tables:\n                            Rin = 1.e19   # Rinner is fixed at 1.e19 cm for lookup tables\n                        \n                        if cfg.par.FORCE_inner_radius[id_val]:\n                            Rin = cfg.par.inner_radius[id_val]\n                        \n                        LogU = np.log10((10**LogQ)/(4*np.pi*Rin*Rin*nh*constants.c.cgs.value))\n\n                        logu_diagnostic(LogQ, LogU, LogZ, Rs, 10**cluster_mass[j], num_HII_clusters, stars_list[i].age, append=True)\n                        neb_file_output = False\n\n                    sp.params['gas_logu'] = LogU\n                    sp.params['gas_logz'] = LogZ\n                    sp.params[\"add_neb_emission\"] = True  \n                    if cfg.par.use_cloudy_tables:\n                        lam_neb, spec_neb = sp.get_spectrum(tage=stars_list[i].age, zmet=stars_list[i].fsps_zmet)\n                        line_lum = sp.emline_luminosity\n                        wave_line = sp.emline_wavelengths\n                    else:\n                        try:\n                            # Calculating ionizing photons again but for 1 Msun in order to scale the output for FSPS\n                            LogQ_1 = calc_LogQ(1.e8 * constants.c.cgs.value / spec[0], spec[1] * constants.L_sun.cgs.value,\n                                    efrac=escape_fraction) \n                            #LogQ_1 = LogQ_1 + cfg.par.gas_logu_init[id_val]\n                               \n                            spec_neb, wave_line, line_lum = get_nebular(spec[0], spec[1], nh, LogQ, Rin, LogU, LogZ, LogQ_1, stars_list[i].all_metals, \n                                                    Dust=False, abund=cfg.par.neb_abund[id_val], clean_up = cfg.par.cloudy_cleanup, index=id_val)\n                        except ValueError as err:\n                            # If the CLOUDY run crashes we switch to using lookup tables for young stars but throw an error for post-AGB stars.\n                            if  young_star:\n                                print (\"WARNING: Switching to using lookup tables pre-packed with FSPS to calculate nebular emission for this particle.\") \n                                print (\"WARNING: The emission line fluxes repoted may not be accurate if the particle lies outside the range of the lookup table paramters.\")\n                                lam_neb, spec_neb = sp.get_spectrum(tage=stars_list[i].age, zmet=stars_list[i].fsps_zmet)\n                                line_lum = sp.emline_luminosity\n                                wave_line = sp.emline_wavelengths\n                            else:\n                                print (\"ERROR: Can't switch to using lookup tables.\")\n                                print (\"ERROR: Please check the CLOUDY output file to figure out why the run was unsuccessful\" )\n                                raise ValueError('CLOUDY run was unsucessful')\n                \n                else:\n                    lam_neb, spec_neb = sp.get_spectrum(tage=stars_list[i].age, zmet=stars_list[i].fsps_zmet)\n\n                weight = num_HII_clusters*(10**cluster_mass[j])/(stars_list[i].mass/constants.M_sun.cgs.value)    \n                f = f + spec_neb*weight\n                if cfg.par.add_neb_emission and cfg.par.dump_emlines:\n                    line_em = line_em + line_lum*weight\n        \n            if cfg.par.add_neb_emission and cfg.par.dump_emlines:\n                #the stellar population returns the calculation in units of Lsun/1 Msun: https://github.com/dfm/python-fsps/issues/117#issuecomment-546513619\n                line_em = line_em * ((stars_list[i].mass*u.g).to(u.Msun).value) * (3.839e33)  # Units: ergs/s\n                line_em = np.append(line_em, stars_list[i].age)\n                dump_emlines(wave_line, line_em)\n\n        stellar_nu[:] = 1.e8*constants.c.cgs.value/spec[0]\n        stellar_fnu[i,:] = f\n\n    return stellar_fnu\n\n\ndef get_gas_metals(ngas):\n    # This function outputs the metallicity (total as well as all the 10 elements tracked by the simulation)\n    # for all the gas particles\n    reg = reg_gl\n    el = ['He', 'C', 'N', 'O', 'Ne', 'Mg', 'Si', 'S', 'Ca', 'Fe']\n    metals = np.zeros((ngas,11))-10.0\n    try:\n        for i in range(11):\n            if i == 0:\n                el_str = \"\"\n            else:\n                el_str = \"_\"+el[i-1]\n            metals[:, i] = reg[\"gasmetals\"+el_str].value\n    except:\n        metals[:,0] = reg[\"gasmetals\"].value\n    \n    return metals\n\n\ndef get_nearest_gas_metals(all_gas_coordinates, particle_coordinates):\n\n    all_gas_metals = get_gas_metals(len(all_gas_coordinates))\n    \n    # Getting N nearest gas particles to the AGN where N is defined by cfg.par.AGN_num_gas\n    nearest_gas_dist, nearest_gas_id = get_nearest(all_gas_coordinates, particle_coordinates, num=cfg.par.AGN_num_gas)\n    \n    metals_avg = []\n    \n    # We take the distance weighted avearge of the metallicity of nearest N gas particles.\n    # This is used as input to the CLOUDY model.\n    for q in range(11):\n        nearest_gas_metals = np.array(all_gas_metals[:,q][nearest_gas_id])\n        metals_avg.append(np.sum(nearest_gas_metals*nearest_gas_dist)/np.sum(nearest_gas_dist))\n\n    return metals_avg\n                                                                                                                \n\ndef get_agn_seds(agn_ids, reg):\n  \n    print ('Starting AGN SED generation')\n    \n    t1 = datetime.now()\n    nprocesses = np.min([cfg.par.n_processes,len(agn_ids)])\n    p = Pool(processes = nprocesses)\n\n    # Pre-calculating average metallicity and fluxes for all the BH particles\n    nu = []\n    fnu_in = []\n    metals_avg = []\n    for agn_id in agn_ids:\n        fnu_in.append(reg[\"bhsed\"][agn_id,:].in_units(\"Lsun\").value/reg[\"bhnu\"].in_units(\"Hz\").value)\n        nu.append(reg[\"bhnu\"].in_units(\"Hz\").value)\n        all_gas_coordinates = reg[\"gascoordinates\"].in_units('kpc').value\n        agn_coordinates = reg[\"bhcoordinates\"][agn_id].in_units('kpc').value\n        metals_avg.append(get_nearest_gas_metals(all_gas_coordinates, agn_coordinates))\n\n    z = zip(agn_ids, nu, fnu_in, metals_avg)\n    fnu_out = p.starmap(agn_sed, z)\n    fnu_out = np.atleast_2d(fnu_out)\n    p.close()\n    p.terminate()\n    p.join()\n    t2 = datetime.now()\n\n    print ('Execution time for AGN SED generation = '+str(t2-t1))\n    \n    return fnu_out\n\n\ndef agn_sed(agn_id, nu, fnu, metals_avg):\n    agn_id = int(agn_id)\n\n    # Hopkins model returns the nu and fnu in reversed order. \n    # Thus, we have to reverse it back to make it compatible.\n    if cfg.par.BH_model != 'Nenkova': \n        nu = nu[::-1]\n        fnu = fnu[::-1]\n\n    if cfg.par.add_neb_emission and cfg.par.add_AGN_neb:\n        \n        id_val = 2\n            \n        tot_metals = metals_avg[0]\n        metals = metals_avg\n        \n        if cfg.par.FORCE_gas_logz[id_val]:\n            LogZ = gas_logz[id_val]\n        \n        else:\n            LogZ = tot_metals/cfg.par.solar\n\n        Rin = cfg.par.inner_radius[id_val]\n\n        if cfg.par.FORCE_gas_logu[id_val]:\n            LogU = cfg.par.gas_logu[id_val]\n            LogQ = np.log10((10**LogU)*(4*np.pi*Rin*Rin*cfg.par.AGN_nh*constants.c.cgs.value))\n        \n        elif cfg.par.FORCE_logq[id_val]:\n            LogQ = cfg.par.source_logq[id_val]\n            LogU = np.log10((10**LogQ)/(4*np.pi*Rin*Rin*cfg.par.AGN_nh*constants.c.cgs.value))\n\n        else:\n            LogQ = calc_LogQ(nu, fnu*constants.L_sun.cgs.value)\n            LogU = np.log10((10**LogQ)/(4*np.pi*Rin*Rin*cfg.par.AGN_nh*constants.c.cgs.value))+cfg.par.gas_logu_init[id_val]\n            LogQ = np.log10((10**LogU)*(4*np.pi*Rin*Rin*cfg.par.AGN_nh*constants.c.cgs.value))\n\n        spec, wave_line, line_lum = get_nebular(1.e8 * constants.c.cgs.value / nu, fnu, cfg.par.AGN_nh, LogQ, Rin, LogU, LogZ, LogQ, metals,\n                                        Dust=False, abund=cfg.par.neb_abund[id_val],clean_up = cfg.par.cloudy_cleanup, index=id_val)\n\n        if cfg.par.dump_emlines:\n        # The stellar population returns the calculation in units of Lsun\n            line_em = line_lum * 3.839e33  # Units: ergs/s\n            # The last column in dump_emlines is reserved for age of the star particle. For AGN we just set it to -1 as a place holder.\n            line_em = np.append(line_em, -1.0)\n            dump_emlines(wave_line, line_em)\n\n    else:\n        spec = fnu\n\n    return spec\n\n\ndef fsps_metallicity_interpolate(metals):\n\n    # takes a list of metallicities for star particles, and returns a\n    # list of interpolated metallicities\n    \n    fsps_metals = np.loadtxt(cfg.par.metallicity_legend)\n    nstars = len(metals)\n    \n    zmet = []\n\n    for i in range(nstars):\n        zmet.append(find_nearest_zmet(fsps_metals,metals[i]))\n    \n    return zmet\n    \ndef find_nearest_zmet(array,value):\n    # this is modified from the normal find_nearest in that it forces\n    # the output to be 1 index higher than the true value since the\n    # minimum zmet value fsps will take is 1 (not 0)\n\n    idx = (np.abs(array-value)).argmin()\n    \n    return idx+1      \n", "meta": {"hexsha": "57daa7b3f400a999d6c607a6c02a23510a6a3d6f", "size": 31203, "ext": "py", "lang": "Python", "max_stars_repo_path": "powderday/SED_gen.py", "max_stars_repo_name": "jwise77/powderday", "max_stars_repo_head_hexsha": "66a5ce6b13f0e96ab9e5beeef0da339d36f18984", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "powderday/SED_gen.py", "max_issues_repo_name": "jwise77/powderday", "max_issues_repo_head_hexsha": "66a5ce6b13f0e96ab9e5beeef0da339d36f18984", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "powderday/SED_gen.py", "max_forks_repo_name": "jwise77/powderday", "max_forks_repo_head_hexsha": "66a5ce6b13f0e96ab9e5beeef0da339d36f18984", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.0525606469, "max_line_length": 173, "alphanum_fraction": 0.5958401436, "include": true, "reason": "import numpy,from scipy,import astropy,from astropy", "num_tokens": 8219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371502, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.196525276116822}}
{"text": "# Contents in this file are specified for RASCIL\n\nimport ctypes\nimport os\nimport warnings\n\nimport numpy as np\nfrom ctypes import c_double\nfrom ctypes import c_int\nfrom ctypes import c_float\nfrom ctypes import c_void_p\n\nc_int_p = ctypes.POINTER(c_int)\nc_float_p = ctypes.POINTER(c_float)\nc_double_p = ctypes.POINTER(c_double)\n\n# TODO: See if there is a way to improve this so it is less hacky.\nlib = None\n# Try to load a local library directly.\nlib_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),\"libcurafft.so\")\ntry:\n    lib = ctypes.cdll.LoadLibrary(lib_path)\nexcept Exception:\n    raise RuntimeError('Failed to find curagridder library')\n\n\n\n\nms2dirty_1 = lib.ms2dirty_1\n# the last two parameters have default value\nms2dirty_1.argtypes = [c_int, c_int, c_int, c_double, c_double, np.ctypeslib.ndpointer(np.double, flags='C'),\n                     np.ctypeslib.ndpointer(np.complex128, flags='C'), np.ctypeslib.ndpointer(np.complex128, flags='C'), c_double, c_double, c_int] \nms2dirty_1.restype = c_int\n\nms2dirty_2 = lib.ms2dirty_2\nms2dirty_2.argtypes = [c_int, c_int, c_int, c_double, c_double, np.ctypeslib.ndpointer(np.double, flags='C'),\n                     np.ctypeslib.ndpointer(np.complex128, flags='C'), np.ctypeslib.ndpointer(np.double, flags='C'), np.ctypeslib.ndpointer(np.complex128, flags='C'), c_double, c_double, c_int] \nms2dirty_2.restype = c_int\n\ndirty2ms_1 = lib.dirty2ms_1\n# the last two parameters have default value\ndirty2ms_1.argtypes = [c_int, c_int, c_int, c_double, c_double, np.ctypeslib.ndpointer(np.double, flags='C'),\n                     np.ctypeslib.ndpointer(np.complex128, flags='C'), np.ctypeslib.ndpointer(np.complex128, flags='C'), c_double, c_double, c_int] \ndirty2ms_1.restype = c_int\n\ndirty2ms_2 = lib.dirty2ms_2\ndirty2ms_2.argtypes = [c_int, c_int, c_int, c_double, c_double, np.ctypeslib.ndpointer(np.double, flags='C'),\n                     np.ctypeslib.ndpointer(np.complex128, flags='C'), np.ctypeslib.ndpointer(np.double, flags='C'), np.ctypeslib.ndpointer(np.complex128, flags='C'), c_double, c_double, c_int] \ndirty2ms_2.restype = c_int\n\n#----------------------------------------\n# the interfaces below are idential to NIFTY\n#-----------------------------------------\n\ndef ms2dirty(uvw, freq, ms, wgt, nxdirty, nydirty, rad_pix_x, rad_pix_y, nx, ny, epsilon, do_wstacking, *args):\n    \"\"\"\n    Generate an image from visibility by non-uniform fourier transform\n    Arguments:\n        uvw - 3D coordinates, numpy array, shape - (nrow,3)\n        freq - frequencies\n        ms - visibility, shape - (nrow,)\n        wgt - weight\n        nxdirty, nydirty - image size\n        deg_pix_ - degree per pixel\n        epsilon - tolerance of relative error (expect, default 1e-6)\n        do_wstacking - True, improved w stacking.\n    \n    Return:\n        dirty image - shape-[nxdirty,nydirty]\n    \"\"\"\n    nrow = uvw.shape[0]\n    sigma = 2\n    fov = rad_pix_x * nxdirty * 180 / np.pi\n    dirty = np.zeros((nxdirty,nydirty),dtype=np.complex128)\n    sign = -1\n    # u = np.ctypeslib.as_ctypes(uvw[:,0])\n    # v = np.ctypeslib.as_ctypes(uvw[:,1])\n    # w = np.ctypeslib.as_ctypes(uvw[:,2])\n    if(wgt is None):\n        ms2dirty_1(nrow,nxdirty,nydirty,fov,freq[0],uvw\n            ,ms,dirty,epsilon,sigma,sign)\n    else:\n        ms2dirty_2(nrow,nxdirty,nydirty,fov,freq[0],uvw\n                ,ms,wgt,dirty,epsilon,sigma,sign)\n    dirty = np.reshape(dirty,[nxdirty,nydirty])\n    return dirty.real\n\ndef dirty2ms(uvw, freq, dirty, wgt, rad_pix_x, rad_pix_y, nx, ny, epsilon, do_wstacking, *args):\n    \"\"\"\n    Generate Visibility from dirty image by non-uniform fourier transform\n    Arguments:\n        uvw - 3D coordinates, numpy array, shape - (nrow,3)\n        freq - frequencies\n        ms - visibility, shape - (nrow,)\n        wgt - weight\n        nxdirty, nydirty - image size\n        fov - field of view\n        epsilon - tolerance of relative error (expect, default 1e-6)\n        sigma - upsampling factor for grid (default 1.25)\n    Return:\n        vis - shape-[M,]\n    \"\"\"\n    nrow = uvw.shape[0]\n    nxdirty = dirty.shape[0]\n    nydirty = dirty.shape[1]\n    sigma = 2\n    fov = rad_pix_x * nxdirty * 180 / np.pi\n    sign = -1\n    ms = np.zeros((nrow,1),dtype=np.complex128)\n    dirty1 = np.zeros(dirty.shape,dtype=np.complex128)\n    dirty1.real = dirty\n\n    if(wgt is None):\n        dirty2ms_1(nrow,nxdirty,nydirty,fov,freq[0],uvw\n            ,ms,dirty1,epsilon,sigma,sign)\n    else:\n        dirty2ms_2(nrow,nxdirty,nydirty,fov,freq[0],uvw\n            ,ms,wgt,dirty1,epsilon,sigma,sign)\n    return ms", "meta": {"hexsha": "039c3b2871a5e4aab71e2b2174969f3041cec7b7", "size": 4552, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/curagridder/cursl.py", "max_stars_repo_name": "astronomical-data-processing/curig", "max_stars_repo_head_hexsha": "4d0e944b8c67e99106e56decda00c9c424002625", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/curagridder/cursl.py", "max_issues_repo_name": "astronomical-data-processing/curig", "max_issues_repo_head_hexsha": "4d0e944b8c67e99106e56decda00c9c424002625", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-14T02:06:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T08:50:30.000Z", "max_forks_repo_path": "python/curagridder/cursl.py", "max_forks_repo_name": "astronomical-data-processing/curig", "max_forks_repo_head_hexsha": "4d0e944b8c67e99106e56decda00c9c424002625", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-13T10:42:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T10:42:03.000Z", "avg_line_length": 38.2521008403, "max_line_length": 194, "alphanum_fraction": 0.6625659051, "include": true, "reason": "import numpy", "num_tokens": 1350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.33807711081162, "lm_q1q2_score": 0.19652526939089474}}
{"text": "# coding: utf-8\n# Copyright (c) Tingzheng Hou.\n# Distributed under the terms of the MIT License.\n\nimport numpy as np\nfrom tqdm.notebook import tqdm\nfrom MDAnalysis.analysis.distances import distance_array\nfrom scipy.signal import savgol_filter\nfrom mdgo.util import atom_vec\n\n__author__ = \"Tingzheng Hou\"\n__version__ = \"1.0\"\n__maintainer__ = \"Tingzheng Hou\"\n__email__ = \"tingzheng_hou@berkeley.edu\"\n__date__ = \"Feb 9, 2021\"\n\n\ndef trajectory(nvt_run, li_atom, run_start, run_end, species, selection_dict, distance):\n    dist_values = {}\n    time_count = 0\n    trj_analysis = nvt_run.trajectory[run_start:run_end:]\n    if species not in list(selection_dict):\n        print(\"Invalid species selection\")\n        return None\n    for ts in trj_analysis:\n        selection = (\n            \"(\" + selection_dict.get(species) + \") and (around \" + str(distance) + \" index \" + str(li_atom.id - 1) + \")\"\n        )\n        shell = nvt_run.select_atoms(selection, periodic=True)\n        for atom in shell.atoms:\n            if str(atom.id) not in dist_values:\n                dist_values[str(atom.id)] = np.full(run_end - run_start, 100.0)\n        time_count += 1\n    time_count = 0\n    for ts in trj_analysis:\n        for atomid in dist_values.keys():\n            dist = distance_array(ts[li_atom.id - 1], ts[(int(atomid) - 1)], ts.dimensions)\n            dist_values[atomid][time_count] = dist\n        time_count += 1\n    return dist_values\n\n\ndef find_nearest(trj, time_step, distance, hopping_cutoff, smooth=51):\n    \"\"\"Returns an array of binding sites (unique on each timestep),\n    the frequency of hopping between sites, and steps when each binding site\n    exhibits the closest distance to the central atom.\n\n    Args:\n        trj (dict): A python dict of distances between central atom and selected atoms.\n        time_step (int): The time step of the simulation.\n        distance (int or float): Binding cutoff distance.\n        hopping_cutoff: (int or float): Detaching cutoff distance.\n        smooth (int): The length of the smooth filter window. Default to 51.\n    \"\"\"\n    time_span = len(list(trj.values())[0])\n    for kw in list(trj):\n        trj[kw] = savgol_filter(trj.get(kw), smooth, 2)\n    site_distance = [100 for _ in range(time_span)]\n    sites = [0 for _ in range(time_span)]\n    sites[0] = min(trj, key=lambda k: trj[k][0])\n    site_distance[0] = trj.get(sites[0])[0]\n    for time in range(1, time_span):\n        if sites[time - 1] == 0:\n            old_site_distance = 100\n        else:\n            old_site_distance = trj.get(sites[time - 1])[time]\n        if old_site_distance > hopping_cutoff:\n            new_site = min(trj, key=lambda k: trj[k][time])\n            new_site_distance = trj.get(new_site)[time]\n            if new_site_distance > distance:\n                site_distance[time] = 100\n            else:\n                sites[time] = new_site\n                site_distance[time] = new_site_distance\n        else:\n            sites[time] = sites[time - 1]\n            site_distance[time] = old_site_distance\n    sites = [int(i) for i in sites]\n    sites_and_distance_array = np.array([[sites[i], site_distance[i]] for i in range(len(sites))])\n    steps = []\n    closest_step = 0\n    previous_site = sites_and_distance_array[0][0]\n    for i, step in enumerate(sites_and_distance_array):\n        site = step[0]\n        distance = step[1]\n        if site == 0:\n            pass\n        else:\n            if site == previous_site:\n                if distance < sites_and_distance_array[closest_step][1]:\n                    closest_step = i\n                else:\n                    pass\n            else:\n                steps.append(closest_step)\n                closest_step = i\n                previous_site = site\n    if previous_site is not None:\n        steps.append(closest_step)\n    change = (np.diff([i for i in sites if i != 0]) != 0).sum()\n    frequency = change / (time_span * time_step)\n    return sites, frequency, steps\n\n\ndef find_in_n_out(trj, distance, hopping_cutoff, smooth=51, cool=20):\n    \"\"\"Returns two arrays of time step of hopping in and hopping out, respectively.\n\n    Args:\n        trj (dict): A python dict of distances between central atom and selected atoms.\n        distance (int or float): Binding cutoff distance.\n        hopping_cutoff: (int or float): Detaching cutoff distance.\n        smooth (int): The length of the smooth filter window. Default to 51.\n        cool (int): The cool down timesteps between hopping in and hopping out.\n    \"\"\"\n    time_span = len(list(trj.values())[0])\n    for kw in list(trj):\n        trj[kw] = savgol_filter(trj.get(kw), smooth, 2)\n    site_distance = [100 for _ in range(time_span)]\n    sites = [0 for _ in range(time_span)]\n    sites[0] = min(trj, key=lambda k: trj[k][0])\n    site_distance[0] = trj.get(sites[0])[0]\n    for time in range(1, time_span):\n        if sites[time - 1] == 0:\n            old_site_distance = 100\n        else:\n            old_site_distance = trj.get(sites[time - 1])[time]\n        if old_site_distance > hopping_cutoff:\n            new_site = min(trj, key=lambda k: trj[k][time])\n            new_site_distance = trj.get(new_site)[time]\n            if new_site_distance > distance:\n                site_distance[time] = 100\n            else:\n                sites[time] = new_site\n                site_distance[time] = new_site_distance\n        else:\n            sites[time] = sites[time - 1]\n            site_distance[time] = old_site_distance\n    sites = [int(i) for i in sites]\n\n    last = sites[0]\n    steps_in = list()\n    steps_out = list()\n    in_cool = cool\n    out_cool = cool\n    for i, s in enumerate(sites):\n        if last == s:\n            pass\n        elif last == 0:\n            in_cool = 0\n            steps_in.append(i)\n            if out_cool < cool:\n                steps_out.pop()\n        elif s == 0:\n            out_cool = 0\n            steps_out.append(i)\n            if in_cool < cool:\n                steps_in.pop()\n        else:\n            pass\n        last = s\n        in_cool += 1\n        out_cool += 1\n    return steps_in, steps_out\n\n\ndef check_contiguous_steps(nvt_run, li_atom, species_dict, select_dict, run_start, run_end, checkpoints, lag=20):\n    \"\"\"Returns two arrays of time step of hopping in and hopping out, respectively.\n\n    Args:\n        nvt_run (MDAnalysis.Universe): An Universe object of wrapped trajectory.\n        li_atom (MDAnalysis.core.groups.Atom): the interested central atom object.\n        species_dict (dict): Dict of Cutoff distance of neighbor for each species.\n        select_dict (dict): A dictionary of selection language of atom species.\n        run_start (int): Start time step.\n        run_end (int): End time step.\n        checkpoints (numpy.array): The time step of interest to check for contiguous steps\n        lag (int): The range (+/- lag) of the contiguous steps\n    \"\"\"\n    coord_num = {x: [[] for _ in range(lag * 2 + 1)] for x in species_dict.keys()}\n    trj_analysis = nvt_run.trajectory[run_start:run_end:]\n    has = False\n    for i, ts in enumerate(trj_analysis):\n        log = False\n        checkpoint = None\n        for j in checkpoints:\n            if abs(i - j) <= lag:\n                log = True\n                has = True\n                checkpoint = j\n        if log:\n            for kw in species_dict.keys():\n                selection = (\n                    \"(\"\n                    + select_dict[kw]\n                    + \") and (around \"\n                    + str(species_dict[kw])\n                    + \" index \"\n                    + str(li_atom.id - 1)\n                    + \")\"\n                )\n                shell = nvt_run.select_atoms(selection, periodic=True)\n                coord_num[kw][i - checkpoint + lag].append(len(shell))\n    if has:\n        for kw in coord_num:\n            np_arrays = np.array([np.array(time).mean() for time in coord_num[kw]])\n            coord_num[kw] = np_arrays\n    return coord_num\n\n\ndef heat_map(\n    nvt_run,\n    li_atom,\n    sites,\n    dist_to_center,\n    bind_atom_type,\n    cartesian_by_ref,\n    run_start,\n    run_end,\n):\n    trj_analysis = nvt_run.trajectory[run_start:run_end:]\n    coordinates = []\n    for i, ts in enumerate(trj_analysis):\n        if sites[i] == 0:\n            pass\n        else:\n            center_atom = nvt_run.select_atoms(\"index \" + str(sites[i] - 1))[0]\n            selection = (\n                \"(\"\n                + bind_atom_type\n                + \") and \"\n                + \"(around \"\n                + str(dist_to_center)\n                + \" index \"\n                + str(center_atom.id - 1)\n                + \")\"\n            )\n            bind_atoms = nvt_run.select_atoms(selection, periodic=True)\n            distances = distance_array(ts[li_atom.id - 1], bind_atoms.positions, ts.dimensions)\n            idx = np.argpartition(distances[0], 3)\n            vertex_atoms = bind_atoms[idx[:3]]\n            vector_li = atom_vec(li_atom, center_atom, ts.dimensions)\n            vector_a = atom_vec(vertex_atoms[0], center_atom, ts.dimensions)\n            vector_b = atom_vec(vertex_atoms[1], center_atom, ts.dimensions)\n            vector_c = atom_vec(vertex_atoms[2], center_atom, ts.dimensions)\n            basis_abc = np.transpose([vector_a, vector_b, vector_c])\n            abc_li = np.linalg.solve(basis_abc, vector_li)\n            unit_x = np.linalg.norm(\n                cartesian_by_ref[0, 0] * vector_a\n                + cartesian_by_ref[0, 1] * vector_b\n                + cartesian_by_ref[0, 2] * vector_c\n            )\n            unit_y = np.linalg.norm(\n                cartesian_by_ref[1, 0] * vector_a\n                + cartesian_by_ref[1, 1] * vector_b\n                + cartesian_by_ref[1, 2] * vector_c\n            )\n            unit_z = np.linalg.norm(\n                cartesian_by_ref[2, 0] * vector_a\n                + cartesian_by_ref[2, 1] * vector_b\n                + cartesian_by_ref[2, 2] * vector_c\n            )\n            vector_x = cartesian_by_ref[0] / unit_x\n            vector_y = cartesian_by_ref[1] / unit_y\n            vector_z = cartesian_by_ref[2] / unit_z\n            basis_xyz = np.transpose([vector_x, vector_y, vector_z])\n            xyz_li = np.linalg.solve(basis_xyz, abc_li)\n            coordinates.append(xyz_li)\n    return np.array(coordinates)\n\n\ndef get_full_coords(coords, reflection=None, rotation=None, inversion=None, sample=None):\n    coords_full = coords\n    if reflection:\n        for vec in reflection:\n            coords_full = np.concatenate((coords, coords * vec), axis=0)\n    if rotation:\n        coords_copy = coords_full\n        for mat in rotation:\n            coords_rot = np.dot(coords_copy, mat)\n            coords_full = np.concatenate((coords_full, coords_rot), axis=0)\n    if inversion:\n        coords_copy = coords_full\n        for mat in inversion:\n            coords_inv = np.dot(coords_copy, mat)\n            coords_full = np.concatenate((coords_full, coords_inv), axis=0)\n    if sample:\n        index = np.random.choice(coords_full.shape[0], sample, replace=False)\n        coords_full = coords_full[index]\n    return coords_full\n\n\ndef cluster_coordinates(\n    nvt_run,\n    select_dict,\n    run_start,\n    run_end,\n    species,\n    distance,\n    basis_vectors=None,\n    cluster_center=\"center\",\n):\n    trj_analysis = nvt_run.trajectory[run_start:run_end:]\n    cluster_center = nvt_run.select_atoms(select_dict.get(cluster_center), periodic=True)[0]\n    selection = (\n        \"(\"\n        + \" or \".join([s for s in species])\n        + \") and (around \"\n        + str(distance)\n        + \" index \"\n        + str(cluster_center.id - 1)\n        + \")\"\n    )\n    print(selection)\n    shell = nvt_run.select_atoms(selection, periodic=True)\n    cluster = []\n    for atom in shell:\n        coord_list = []\n        for ts in trj_analysis:\n            coord_list.append(atom.position)\n        cluster.append(np.mean(np.array(coord_list), axis=0))\n    cluster = np.array(cluster)\n    if basis_vectors:\n        if len(basis_vectors) == 2:\n            vec1 = basis_vectors[0]\n            vec2 = basis_vectors[1]\n            vec3 = np.cross(vec1, vec2)\n            vec2 = np.cross(vec1, vec3)\n        elif len(basis_vectors) == 3:\n            vec1 = basis_vectors[0]\n            vec2 = basis_vectors[1]\n            vec3 = basis_vectors[2]\n        else:\n            raise ValueError(\"incorrect vector format\")\n        vec1 = vec1 / np.linalg.norm(vec1)\n        vec2 = vec2 / np.linalg.norm(vec2)\n        vec3 = vec3 / np.linalg.norm(vec3)\n        basis_xyz = np.transpose([vec1, vec2, vec3])\n        cluster_norm = np.linalg.solve(basis_xyz, cluster.T).T\n        cluster_norm = cluster_norm - np.mean(cluster_norm, axis=0)\n        return cluster_norm\n    else:\n        return cluster\n\n\ndef num_of_neighbor_one_li(\n    nvt_run,\n    li_atom,\n    species_dict,\n    select_dict,\n    run_start,\n    run_end,\n    write=False,\n    structure_code=None,\n    write_freq=0,\n    write_path=None,\n    element_id_dict=None,\n):\n\n    time_count = 0\n    trj_analysis = nvt_run.trajectory[run_start:run_end:]\n    cn_values = dict()\n    species = list(species_dict.keys())\n    for kw in species:\n        if kw in select_dict.keys():\n            cn_values[kw] = np.zeros(int(len(trj_analysis)))\n        else:\n            print(\"Invalid species selection\")\n            return None\n    cn_values[\"total\"] = np.zeros(int(len(trj_analysis)))\n    for ts in trj_analysis:\n        digit_of_species = len(species) - 1\n        for kw in species:\n            selection = (\n                \"(\"\n                + select_dict.get(kw)\n                + \") and (around \"\n                + str(species_dict.get(kw))\n                + \" index \"\n                + str(li_atom.id - 1)\n                + \")\"\n            )\n            shell = nvt_run.select_atoms(selection, periodic=True)\n            # for each atom in shell, create/add to dictionary\n            # (key = atom id, value = list of values for step function)\n            for _ in shell.atoms:\n                cn_values[kw][time_count] += 1\n                cn_values[\"total\"][time_count] += 10 ** digit_of_species\n            digit_of_species = digit_of_species - 1\n        if write and cn_values[\"total\"][time_count] == structure_code:\n            a = np.random.random()\n            if a > 1 - write_freq:\n                print(\"writing\")\n                selection_write = \" or \".join(\n                    \"(same resid as (\"\n                    + select_dict.get(kw)\n                    + \" and around \"\n                    + str(species_dict.get(kw))\n                    + \" index \"\n                    + str(li_atom.id - 1)\n                    + \"))\"\n                    for kw in species\n                )\n                selection_write = \"((\" + selection_write + \")and not \" + select_dict.get(\"cation\") + \")\"\n                structure = nvt_run.select_atoms(selection_write, periodic=True)\n                li_pos = ts[(int(li_atom.id) - 1)]\n                path = write_path + str(li_atom.id) + \"_\" + str(int(ts.time)) + \"_\" + str(structure_code) + \".xyz\"\n                write_out(li_pos, structure, element_id_dict, path)\n        time_count += 1\n    return cn_values\n\n\ndef num_of_neighbor_one_li_simple(nvt_run, li_atom, species_dict, select_dict, run_start, run_end):\n\n    time_count = 0\n    trj_analysis = nvt_run.trajectory[run_start:run_end:]\n    species = list(species_dict.keys())[0]\n    if species in select_dict.keys():\n        cn_values = np.zeros(int(len(trj_analysis)))\n    else:\n        print(\"Invalid species selection\")\n        return None\n    for ts in trj_analysis:\n        selection = (\n            \"(\"\n            + select_dict.get(species)\n            + \") and (around \"\n            + str(species_dict.get(species))\n            + \" index \"\n            + str(li_atom.id - 1)\n            + \")\"\n        )\n        shell = nvt_run.select_atoms(selection, periodic=True)\n        shell_len = len(shell)\n        if shell_len == 0:\n            cn_values[time_count] = 1\n        elif shell_len == 1:\n            selection_species = (\n                \"(\"\n                + select_dict.get(\"cation\")\n                + \" and around \"\n                + str(species_dict.get(species))\n                + \" index \"\n                + str(shell.atoms[0].id - 1)\n                + \")\"\n            )\n            shell_species = nvt_run.select_atoms(selection_species, periodic=True)\n            shell_species_len = len(shell_species) - 1\n            if shell_species_len == 0:\n                cn_values[time_count] = 2\n            else:\n                cn_values[time_count] = 3\n        else:\n            cn_values[time_count] = 3\n        time_count += 1\n    cn_values = {\"total\": cn_values}\n    return cn_values\n\n\ndef num_of_neighbor_one_li_simple_extra(nvt_run, li_atom, species, select_dict, distance, run_start, run_end):\n\n    time_count = 0\n    emc_angle = list()\n    ec_angle = list()\n    trj_analysis = nvt_run.trajectory[run_start:run_end:]\n    if species in select_dict.keys():\n        cn_values = np.zeros(int(len(trj_analysis)))\n    else:\n        print(\"Invalid species selection\")\n        return None\n    for ts in trj_analysis:\n        selection = (\n            \"(\" + select_dict.get(species) + \") and (around \" + str(distance) + \" index \" + str(li_atom.id - 1) + \")\"\n        )\n        shell = nvt_run.select_atoms(selection, periodic=True)\n        shell_len = len(shell)\n        if shell_len == 0:\n            cn_values[time_count] = 1\n        elif shell_len == 1:\n            selection_species = (\n                \"(\"\n                + select_dict.get(\"cation\")\n                + \" and around \"\n                + str(distance)\n                + \" index \"\n                + str(shell.atoms[0].id - 1)\n                + \")\"\n            )\n            shell_species = nvt_run.select_atoms(selection_species, periodic=True)\n            shell_species_len = len(shell_species) - 1\n            if shell_species_len == 0:\n                cn_values[time_count] = 2\n                li_pos = li_atom.position\n                p_pos = shell.atoms[0].position\n                ec_select = (\n                    \"(\" + select_dict.get(\"EC\") + \") and (around \" + str(3) + \" index \" + str(li_atom.id - 1) + \")\"\n                )\n                emc_select = (\n                    \"(\" + select_dict.get(\"EMC\") + \") and (around \" + str(3) + \" index \" + str(li_atom.id - 1) + \")\"\n                )\n                ec_group = nvt_run.select_atoms(ec_select, periodic=True)\n                emc_group = nvt_run.select_atoms(emc_select, periodic=True)\n                for atom in ec_group.atoms:\n                    theta = angle(p_pos, li_pos, atom.position)\n                    ec_angle.append(theta)\n                for atom in emc_group.atoms:\n                    theta = angle(p_pos, li_pos, atom.position)\n                    emc_angle.append(theta)\n            else:\n                cn_values[time_count] = 3\n        else:\n            cn_values[time_count] = 3\n        time_count += 1\n    return cn_values, np.array(ec_angle), np.array(emc_angle)\n\n\ndef num_of_neighbor_one_li_simple_extra_two(nvt_run, li_atom, species_list, select_dict, distances, run_start, run_end):\n    time_count = 0\n    trj_analysis = nvt_run.trajectory[run_start:run_end:]\n    cip_step = list()\n    ssip_step = list()\n    agg_step = list()\n    cn_values = dict()\n    for kw in species_list:\n        if kw in select_dict.keys():\n            cn_values[kw] = np.zeros(int(len(trj_analysis)))\n        else:\n            print(\"Invalid species selection\")\n            return None\n    cn_values[\"total\"] = np.zeros(int(len(trj_analysis)))\n    for ts in trj_analysis:\n        digit_of_species = len(species_list) - 1\n        for kw in species_list:\n            selection = (\n                \"(\"\n                + select_dict.get(kw)\n                + \") and (around \"\n                + str(distances.get(kw))\n                + \" index \"\n                + str(li_atom.id - 1)\n                + \")\"\n            )\n            shell = nvt_run.select_atoms(selection, periodic=True)\n            # for each atom in shell, create/add to dictionary\n            # (key = atom id, value = list of values for step function)\n            for _ in shell.atoms:\n                cn_values[kw][time_count] += 1\n                cn_values[\"total\"][time_count] += 10 ** digit_of_species\n            digit_of_species = digit_of_species - 1\n\n        selection = (\n            \"(\"\n            + select_dict.get(\"anion\")\n            + \") and (around \"\n            + str(distances.get(\"anion\"))\n            + \" index \"\n            + str(li_atom.id - 1)\n            + \")\"\n        )\n        shell = nvt_run.select_atoms(selection, periodic=True)\n        shell_len = len(shell)\n        if shell_len == 0:\n            ssip_step.append(time_count)\n        elif shell_len == 1:\n            selection_species = (\n                \"(\"\n                + select_dict.get(\"cation\")\n                + \" and around \"\n                + str(distances.get(\"anion\"))\n                + \" index \"\n                + str(shell.atoms[0].id - 1)\n                + \")\"\n            )\n            shell_species = nvt_run.select_atoms(selection_species, periodic=True)\n            shell_species_len = len(shell_species) - 1\n            if shell_species_len == 0:\n                cip_step.append(time_count)\n            else:\n                agg_step.append(time_count)\n        else:\n            agg_step.append(time_count)\n        time_count += 1\n    cn_ssip = dict()\n    cn_cip = dict()\n    cn_agg = dict()\n    for kw in species_list:\n        cn_ssip[kw] = np.mean(cn_values[kw][ssip_step])\n        cn_cip[kw] = np.mean(cn_values[kw][cip_step])\n        cn_agg[kw] = np.mean(cn_values[kw][agg_step])\n    return cn_ssip, cn_cip, cn_agg\n\n\ndef angle(a, b, c):\n    ba = a - b\n    bc = c - b\n    cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc))\n    cosine_angle = np.clip(cosine_angle, -1.0, 1.0)\n    angle_in_radian = np.arccos(cosine_angle)\n    return np.degrees(angle_in_radian)\n\n\n# Depth-first traversal\ndef num_of_neighbor_one_li_complex(nvt_run, li_atom, species, selection_dict, distance, run_start, run_end):\n    time_count = 0\n    trj_analysis = nvt_run.trajectory[run_start:run_end:]\n    cn_values = np.zeros((int(len(trj_analysis)), 4))\n    for ts in trj_analysis:\n        cation_list = [li_atom.id]\n        anion_list = []\n        shell = nvt_run.select_atoms(\n            \"(\" + selection_dict.get(species) + \" and around \" + str(distance) + \" index \" + str(li_atom.id - 1) + \")\",\n            periodic=True,\n        )\n        for anion_1 in shell.atoms:\n            if anion_1.resid not in anion_list:\n                anion_list.append(anion_1.resid)\n                cn_values[time_count][0] += 1\n                shell_anion_1 = nvt_run.select_atoms(\n                    \"(type 17 and around 3 resid \" + str(anion_1.resid) + \")\",\n                    periodic=True,\n                )\n                for cation_2 in shell_anion_1:\n                    if cation_2.id not in cation_list:\n                        cation_list.append(cation_2.id)\n                        cn_values[time_count][1] += 1\n                        shell_cation_2 = nvt_run.select_atoms(\n                            \"(type 15 and around 3 index \" + str(cation_2.id - 1) + \")\",\n                            periodic=True,\n                        )\n                        for anion_3 in shell_cation_2.atoms:\n                            if anion_3.resid not in anion_list:\n                                anion_list.append(anion_3.resid)\n                                cn_values[time_count][2] += 1\n                                shell_anion_3 = nvt_run.select_atoms(\n                                    \"(type 17 and around 3 resid \" + str(anion_3.resid) + \")\",\n                                    periodic=True,\n                                )\n                                for cation_4 in shell_anion_3:\n                                    if cation_4.id not in cation_list:\n                                        cation_list.append(cation_4.id)\n                                        cn_values[time_count][3] += 1\n\n\ndef coord_shell_array(nvt_run, func, li_atoms, species_dict, select_dict, run_start, run_end):\n    \"\"\"\n    Args:\n        nvt_run: MDAnalysis Universe\n        func: One of the neighbor statistical method (num_of_neighbor_one_li,\n            num_of_neighbor_one_li_simple)\n        li_atoms: Atom group of the Li atoms.\n        species_dict (dict): A dict of coordination cutoff distance\n            of the interested species.\n        select_dict: A dictionary of species selection.\n        run_start (int): Start time step.\n        run_end (int): End time step.\n    \"\"\"\n    num_array = func(nvt_run, li_atoms[0], species_dict, select_dict, run_start, run_end)\n    for li in tqdm(li_atoms[1::]):\n        this_li = func(nvt_run, li, species_dict, select_dict, run_start, run_end)\n        for kw in num_array.keys():\n            num_array[kw] = np.concatenate((num_array.get(kw), this_li.get(kw)), axis=0)\n    return num_array\n\n\ndef write_out(li_pos, selection, element_id_dict, path):\n    lines = list()\n    lines.append(str(len(selection) + 1))\n    lines.append(\"\")\n    lines.append(\"Li 0.0000000 0.0000000 0.0000000\")\n    box = selection.dimensions\n    half_box = np.array([box[0], box[1], box[2]]) / 2\n    for atom in selection:\n        locs = list()\n        for i in range(3):\n            loc = atom.position[i] - li_pos[i]\n            if loc > half_box[i]:\n                loc = loc - box[i]\n            elif loc < -half_box[i]:\n                loc = loc + box[i]\n            else:\n                pass\n            locs.append(loc)\n        line = element_id_dict.get(int(atom.type)) + \" \" + \" \".join(str(loc) for loc in locs)\n        lines.append(line)\n    with open(path, \"w\") as xyz_file:\n        xyz_file.write(\"\\n\".join(lines))\n", "meta": {"hexsha": "a6bb30e86483be7b3f47368726dd472439ce0eaf", "size": 25846, "ext": "py", "lang": "Python", "max_stars_repo_path": "mdgo/coordination.py", "max_stars_repo_name": "kdfong/mdgo", "max_stars_repo_head_hexsha": "3505e07a1a4ebb73db20ade6e72810f0efac1fef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mdgo/coordination.py", "max_issues_repo_name": "kdfong/mdgo", "max_issues_repo_head_hexsha": "3505e07a1a4ebb73db20ade6e72810f0efac1fef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mdgo/coordination.py", "max_forks_repo_name": "kdfong/mdgo", "max_forks_repo_head_hexsha": "3505e07a1a4ebb73db20ade6e72810f0efac1fef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6763848397, "max_line_length": 120, "alphanum_fraction": 0.5526967422, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.19647809611685554}}
{"text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n'''\n2/24/2021\n\nThis script takes outputs from a regional climate model (RCM) - e.g. MERRA, \nMAR - for a particular site and puts that data into a pandas dataframe. \n\nThe output can be fed to RCMpkl_to_spin.py to generate a time series to force the CFM\n\nYOU MAY HAVE TO EDIT THIS SCRIPT A LOT TO MAKE IT WORK WITH YOUR FILE STRUCTURE \nAND WHAT CLIMATE FILES YOU HAVE.\n\nAnd, for now there are little things you need to search out and change manually,\nlike the reference climate interval. Sorry!\n\n@author: maxstev\n'''\n\nimport netCDF4 as nc\nimport numpy as np\nimport scipy.io\nimport csv\nimport math\nimport sys\nimport decimal\nimport os\nimport sys\nimport matplotlib.pyplot as plt\nfrom dateutil import rrule\nfrom datetime import datetime, timedelta, date\nimport pandas as pd\nimport fnmatch\nfrom scipy.spatial import cKDTree\nfrom sklearn import datasets, linear_model\nfrom sklearn.metrics import mean_squared_error, r2_score\nfrom sklearn.svm import SVR\nimport time\nimport xarray as xr\nimport glob\nimport hl_analytic as hla\n\n\ndef find_indices(points,lon,lat,tree=None):\n    '''\n    find the grid point nearest a given coordinate.\n    '''\n    if tree is None:\n        # lon,lat = lon.T,lat.T\n        lonlat = np.column_stack((lon.ravel(),lat.ravel()))\n        tree = cKDTree(lonlat)\n    dist,idx = tree.query(points,k=[1])\n    ind = np.column_stack(np.unravel_index(idx,lon.shape))\n    print(ind)\n    for i,j in ind:\n        ii=i\n        jj=j\n\n    return ii,jj #, [(i,j) for i,j in ind]\n\n\ndef read_netcdfs_merra(files, dim, ii, jj, vv, transform_func=None):\n    '''\n    Read merra files and concatenate into a pandas dataframe\n    '''\n    def process_one_path(path):\n        with xr.open_dataset(path) as ds:\n            # transform_func should do some sort of selection or\n            # aggregation\n            # if transform_func is not None:\n            #     ds = transform_func(ds)\n            # load all data from the transformed dataset, to ensure we can\n            # use it after closing each original file\n            ds = ds[vv].isel(lat=ii,lon=jj)\n            ds.load()\n            return ds\n    datasets = [process_one_path(p) for p in files]\n    combined = xr.concat(datasets, dim)\n    df1 = combined.to_dataframe()\n    return (df1.drop(labels=['lon','lat'],axis=1)).sort_index()\n\ndef read_netcdfs_mar(files, dim, ii, jj, vv):\n    '''\n    Read mar files and concatenate into a pandas dataframe\n    '''\n    def process_one_path(path):\n        with xr.open_dataset(path) as ds:\n            dsd = {}\n            for v in vv:\n                # print(v)\n                if len(ds[v].dims)==4:\n                    dsd[v] = ds[v][:,0,ii,jj].to_dataframe()\n                else:\n                    dsd[v] = ds[v][:,ii,jj].to_dataframe()\n            df_list = [v for k,v in dsd.items()]\n            df1 = pd.concat(df_list, axis=1)\n            return df1[df1.columns.intersection(vv)]\n    datasets = [process_one_path(p) for p in files]\n    return (pd.concat(datasets)).sort_index()\n\ndef effectiveT(T):\n    '''\n    The Arrhenius mean temperature.\n    '''\n    Q   = -1 * 60.0e3\n    R   = 8.314\n    k   = np.exp(Q/(R*T))\n    km  = np.mean(k)\n    return Q/(R*np.log(km))\n\ndef getClimate(lat_int,lon_int,writer=True,datatype='MERRA',timeres='1D',melt=False,runtype='local',dsource = None):\n    '''\n    Load data from MERRA or MAR or whatever.\n    Put it into a pandas dataframe, called df_CLIM. index must be datetimeindex for \n    resampling.\n    df_CLIM can have any number of columns: BDOT, TSKIN, SMELT, RAIN, \n    SUBLIMATION (use capital letters. We use SMELT because melt is a pandas function)\n    Hopefully this makes it easy to adapt for the different climate products.\n    write df_CLIM into a pickle for future use.\n\n    Reference for Summit, Greenland (my favorite test site):\n    lat = 72.57972\n    lon = -38.50454\n\n    DYE-2 (my favorite wet test site):\n    lat = 66.5\n    lon = -46.2\n\n    UNITS FOR MASS FLUXES IN THE DATAFRAMES ARE kg/m^2 PER TIME STEP SIZE IN\n    THE DATA FRAME. e.g. if you have hourly data in the dataframe, the units\n    for accumulation are kg/m^2/hour - the mass of precip that fell during that \n    time interval.\n\n    Parameters\n    ----------\n    lat_int: float\n        the latitude of the site you want to build a climate history for\n    lon_int: float\n        the longitude of the site you want to build a climate history for\n    writer: boolean\n        Whether or not you want to write the pandas dataframe to a pickle\n    datatype: string\n        The type of RCM data you are using 'MERRA' or 'MAR' for now.\n    melt: boolean\n        Whether or not to put melt into the pandas dataframe\n    Tinterp: 'mean', 'effective', or 'weighted'\n        how to resample the temperature; mean is regular mean, 'effective' is \n        Arrhenius mean; 'weighted' is accumulation-weighted mean\n    runtype: 'local' or 'remote'\n        Allows you easily switch between directory structures if you are testing\n        code locally and running on a remote server\n    dsource: 'ERA10k', 'ERA6k', or 'NCEP20k'\n        MAR has several flavors; choose which one.\n\n    Returns\n    -------\n    df_CLIM: pandas dataframe\n        Dataframe containing the time series of each pertinent variable for \n        the site, pulled from the RCM data. Index is a datetimeindex.\n\n\n    '''\n\n    if not writer:\n        print('Files will not be written!')\n    SPY = 365.25*24*3600\n\n    todaystring = date.today().strftime(\"%Y%m%d\")\n    # write_out_dir = 'inputdata{}/'.format(todaystring) + datatype + 'input'\n    write_out_dir = 'pickle'\n    if writer:\n        try: \n            os.makedirs(write_out_dir)\n        except:\n            pass\n\n    if datatype == 'MERRA':\n        '''\n        smb has dimensions of (time,lat,lon)\n        smb has units of kg m^-2 s^-1 per day (because I sum the hourly values to get a value for each day, but do not divde by 24 after that) (pretty sure, at least!)\n        temperature has dimensions of (time,lat,lon)\n        temperature has units K\n\n        '''\n\n        ### Set directory to find climate files.\n        if lat_int < 0: # Antarctica\n            if runtype=='local':\n                # ddir = 'PATH/TO/LOCAL/DATA/MERRA/Antarctica/Hourly'\n                ddir = '/Volumes/Samsung_T1/MERRA/Antarctica/daily_melt'\n            elif runtype=='remote':\n                ddir = 'PATH/TO/REMOTE/DATA/MERRA/Antarctica/Hourly'\n            elif runtype=='differentremote':\n                ddir = 'PATH/TO/OTHER/REMOTE/DATA/CFM/MERRA/Antarctica/Hourly'\n            \n            # Adjust these as you see fit to set the Reference Climate Interval (RCI)\n            spin_date_st = 1980 \n            spin_date_end = 2019\n\n        else: # Greenland\n            if runtype=='local':\n                # ddir = 'PATH/TO/LOCAL/DATA/MERRA/Greenland/Hourly'\n                # ddir = '/Volumes/Samsung_T1/MERRA/Greenland/daily_melt'\n                ddir = '/Users/cdsteve2/RCMdata/MERRA2/Greenland/daily_melt'\n            elif runtype=='remote':\n                ddir = 'PATH/TO/REMOTE/DATA/MERRA/Greenland/Hourly'\n            elif runtype == 'loki':\n                ddir = '/home/maxstev/CFM_main/MERRA/Greenland/daily_melt'\n\n            \n            # Adjust these as you see fit to set the Reference Climate Interval (RCI)\n            spin_date_st = 1980\n            spin_date_end = 1995\n\n        # input_datetimes = [dparser.parse((re.search(r'\\d{8}',xx)).group()) for xx in ff] # this will extract the dates for each file\n        # yy = np.array([float((re.search(r'\\d{8}',xx)).group()[0:4]) for xx in glob.glob(ddir+'/TS/*.nc*')])\n        # yrs = np.arange(min(yy),max(yy)+1)\n\n        fn_ll = glob.glob(ddir + '/*.nc*')\n        nc_ll = nc.Dataset(fn_ll[0],'r')\n        lat_ll = nc_ll.variables['lat'][:]\n        lon_ll = nc_ll.variables['lon'][:]\n        ii, lat_val = min(enumerate(lat_ll), key=lambda x: abs(x[1]-lat_int))\n        jj, lon_val = min(enumerate(lon_ll), key=lambda x: abs(x[1]-lon_int))\n        nc_ll.close()       \n        print('lat_val: ', lat_val)\n        print('lon_val: ', lon_val)\n\n        if runtype=='local':\n            # pickle_folder = '/PUT/PICKLES/HERE/MERRA/IDSpickle/pickle/'\n            pickle_folder = 'example_pickle/'\n        else:\n            pickle_folder = 'IDS/pickle/'\n        pickle_name = pickle_folder + 'MERRA2_CLIM_df_{}_{}.pkl'.format(lat_val,lon_val)\n        if not os.path.exists(pickle_folder):\n            os.makedirs(pickle_folder)\n\n        if os.path.isfile(pickle_name):\n            print('pickle found')\n            writer = False\n            loadnetcdf = False\n            df_CLIM = pd.read_pickle(pickle_name)\n            # try:\n            #     df_BDOT = pd.DataFrame(df_CLIM['PRECTOT'])\n            #     df_TS = pd.DataFrame(df_CLIM['TS'])\n            #     df_CLIM.rename(columns={'PRECTOT':'BDOT','TS':'TSKIN'},inplace=True)\n            # except Exception:\n            #     df_BDOT = pd.DataFrame(xx['BDOT'])\n            #     df_TS = pd.DataFrame(xx['TSKIN'])\n\n            # if df_CLIM.BDOT.resample('1A').sum().mean()<1:\n            #     df_CLIM.BDOT = df_CLIM.BDOT *3600 #get rid of seconds dimension - MERRA is hourly, so this gives precip per hour.\n\n        else:\n            vv=['TS','EVAP','SMELT','PRECTOT','PRECSNO']\n            # flist_TS = glob.glob(ddir+'/TS/*.nc*')\n\n            # df_TS = read_netcdfs_merra(flist_TS, dim='time',ii=ii,jj=jj,vv='TS')\n            # df_TS.rename(columns={'TS':'TSKIN'},inplace=True)\n\n            # flist_SMB = glob.glob(ddir+'/SMB/*.nc*')\n            # df_BDOT = read_netcdfs_merra(flist_SMB, dim='time',ii=ii,jj=jj,vv='PRECTOT') # [kg m^-2 s^-1]\n            # df_BDOT = (df_BDOT.rename(columns={'PRECTOT':'BDOT'}))*3600 # [kg m^-2 hour^-1] (this is amount of precip per MERRA time interval)\n\n            df_merra = read_netcdfs_merra(fn_ll, dim='time',ii=ii,jj=jj,vv=vv)\n\n            df_CLIM = df_merra\n        # ACCVAR = 'PRECTOT'\n        # TVAR = 'TS'\n             \n        # df_MELT = None\n        # df_RAIN = None\n        ####################\n        #### end MERRA #####\n\n    elif datatype == 'MAR':\n        spin_date_st = 1980\n        spin_date_end = 1995\n        print('Using MAR')\n        if lat_int < 0:\n            print('no Antarctic MAR data')\n            sys.exit()            \n        else:\n            if runtype=='local':\n                ddir = '/Volumes/Samsung_T1/MAR311/Greenland/Daily'\n\n        if not dsource:\n            dsource = 'ERA10k'\n            print('using MAR ', dsource)\n\n        if dsource == 'ERA10k':\n            d2 = '/ERA_1958-2019-10km/'\n            vv = ['ME','SF','ST2','RF','SU','TT']\n        elif dsource == 'ERA6k':\n            d2 = '/ERA_1979-2020-6km/'\n            vv = ['ME','SF','ST2','RF','TT']\n        elif dsource == 'NCEP20k':\n            d2 = '/NCEP1_1948-2020_20km/'\n            vv = ['ME','SF','ST2','RF','SU','TT']\n\n        pickle_folder = ddir + '/pickles' + d2\n        print(pickle_folder)\n        if not os.path.exists(pickle_folder):\n            os.makedirs(pickle_folder)\n        # searchdir = ddir + d2 + '/*.nc'\n        flist = glob.glob(ddir + d2 + '*.nc')\n        rgr = nc.Dataset(flist[0],'r')\n        lat = rgr['LAT'][:,:]\n        lon = rgr['LON'][:,:]\n        ii,jj = find_indices((lon_int,lat_int),lon,lat)\n        lat_val = lat[ii,jj]\n        lon_val = lon[ii,jj]\n        print('lat_val: ', lat_val)\n        print('lon_val: ', lon_val)\n        rgr.close()\n\n        PN = pickle_folder + 'MAR_{}_CLIM_df_{}_{}.pkl'.format(dsource,lat_val,lon_val)\n        if os.path.isfile(PN):\n            df_CLIM = pd.read_pickle(PN)\n            print('Pickle found!')\n            df_BDOT = pd.DataFrame(df_CLIM.BDOT)\n            df_TS = pd.DataFrame(df_CLIM.TSKIN)\n        \n        # vv = ['ST2','SMB']\n        else:\n            df_CLIM = (read_netcdfs_mar(flist,'TIME',ii=ii,jj=jj,vv=vv))[str(spin_date_st):]\n\n            if 'SMB' in df_CLIM.columns:\n                df_BDOT = pd.DataFrame(df_CLIM['SMB']/1000*917).rename(columns = ['BDOT']) #put into units kg/m^2/day (i.e. per time resolution in the files))\n                df_MELT = None\n                df_RAIN = None\n            else:\n                if 'SU' in df_CLIM.columns:\n                    df_BDOT = pd.DataFrame(((df_CLIM['SF']-df_CLIM['SU'])/1000*917),columns=['BDOT']) #put into units kg/m^2/day (i.e. per time resolution in the files))\n                    df_CLIM['BDOT'] = df_BDOT.BDOT.values\n                    df_CLIM.drop(['SF','SU'],axis=1,inplace=True)\n                else:\n                    df_BDOT = pd.DataFrame((df_CLIM['SF'])/1000*917).rename(columns={'SF':'BDOT'}) #put into units kg/m^2/day (i.e. per time resolution in the files))\n                    df_CLIM['BDOT'] = df_BDOT.BDOT.values\n                    df_CLIM.drop(['SF'],axis=1,inplace=True)\n                df_CLIM['ME'] = df_CLIM['ME']/1000*917 #put into units kg/m^2/day (i.e. per time resolution in the files))\n                df_CLIM['RF'] = df_CLIM['RF']/1000*917 #put into units kg/m^2/day (i.e. per time resolution in the files))\n                # df_MELT = pd.DataFrame(df_CLIM['ME']/1000*917/3600).rename(columns={'ME':'MELT'}) #put into equivalent units to the merra data (kg/m^2/s)\n                # df_RAIN = pd.DataFrame(df_CLIM['RF']/1000*917/3600).rename(columns={'RF':'RAIN'}) #put into equivalent units to the merra data (kg/m^2/s)\n            df_TS = pd.DataFrame(df_CLIM[['ST2','TT']]).rename(columns = {'ST2':'TSKIN','TT':'T2M'}) + 273.15\n\n            drn = {'ME':'SMELT','SU':'SUBLIMATION','SF':'BDOT','RF':'RAIN','ST2':'TSKIN','SMB':'BDOT','TT':'T2M'}\n            df_CLIM.rename(mapper=drn,axis=1,inplace=True)\n            df_CLIM.TSKIN = df_CLIM.TSKIN + 273.15\n            df_CLIM.T2M = df_CLIM.T2M + 273.15\n        ###############\n        ### end MAR ###\n        ###############\n\n    elif datatype == 'RACMO':\n\n        ### Set directory to find climate files.\n        if lat_int < 0: # Antarctica\n            if runtype=='local':\n                ddir = '/Volumes/Samsung_T1/RACMO/Antarctica'\n            elif runtype=='remote':\n                ddir = 'PATH/TO/REMOTE/DATA/RACMO/Antarctica/Hourly'\n            elif runtype=='differentremote':\n                ddir = 'PATH/TO/OTHER/REMOTE/DATA/RACMO/Antarctica/Hourly'\n            \n            # Adjust these as you see fit to set the Reference Climate Interval (RCI)\n            spin_date_st = 1980 \n            spin_date_end = 2019\n\n        else: # Greenland\n            if runtype=='local':\n                # ddir = 'PATH/TO/LOCAL/DATA/MERRA/Greenland/Hourly'\n                ddir = '/Volumes/Samsung_T1/RACMO/Greenland'\n            elif runtype=='remote':\n                ddir = 'PATH/TO/REMOTE/DATA/RACMO/Greenland/Hourly'\n            elif runtype == 'differentremote':\n                ddir = 'PATH/TO/OTHER/REMOTE/DATA/RACMO/Greenland/Hourly'\n\n        spin_date_st = 1980\n        spin_date_end = 1995\n\n        flist = glob.glob(ddir + '/*1958-2016*.nc*')[0]\n        rgr = nc.Dataset(flist[0],'r')\n        lat = rgr['LAT'][:,:]\n        lon = rgr['LON'][:,:]\n        ii,jj = find_indices((lon_int,lat_int),lon,lat)\n        lat_val = lat[ii,jj]\n        lon_val = lon[ii,jj]\n        print('lat_val: ', lat_val)\n        print('lon_val: ', lon_val)\n        rgr.close()\n\n\n\n\n    if writer:\n        if datatype =='MERRA':\n            df_CLIM.to_pickle(pickle_folder + 'MERRA2_CLIM_df_{}_{}.pkl'.format(lat_val,lon_val))\n        elif datatype == 'MAR':\n            df_CLIM.to_pickle(pickle_folder + 'MAR_{}_CLIM_df_{}_{}.pkl'.format(dsource,lat_val,lon_val))\n\n    return df_CLIM\n    # return CD, stepsperyear, depth_S1, depth_S2, desired_depth\n\n\nif __name__ == '__main__':\n    tic = time.time()\n\n    LLpair = sys.argv[1]\n    nn = np.fromstring(LLpair,dtype =float, sep=' ')\n    lat_int = nn[0]\n    lon_int = nn[1]\n    writer=True\n    datatype='MERRA'\n    runtype = 'local'\n\n    df_CLIM = getClimate(lat_int,lon_int,writer = True, runtype = runtype)\n    print(time.time()-tic)\n\n\n\n\n\n", "meta": {"hexsha": "e0783995f34d1a18371acc0a213f57497d162465", "size": 15923, "ext": "py", "lang": "Python", "max_stars_repo_path": "CFM_main/siteClimate_from_RCM.py", "max_stars_repo_name": "UWGlaciology/CommunityFirnModel", "max_stars_repo_head_hexsha": "820f8b3cfd8355b0c3085058a51f7488cac17fbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2019-03-28T13:56:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T12:39:10.000Z", "max_issues_repo_path": "CFM_main/siteClimate_from_RCM.py", "max_issues_repo_name": "UWGlaciology/CommunityFirnModel", "max_issues_repo_head_hexsha": "820f8b3cfd8355b0c3085058a51f7488cac17fbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-06-10T06:53:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T22:07:02.000Z", "max_forks_repo_path": "CFM_main/siteClimate_from_RCM.py", "max_forks_repo_name": "UWGlaciology/CommunityFirnModel", "max_forks_repo_head_hexsha": "820f8b3cfd8355b0c3085058a51f7488cac17fbe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2017-10-09T08:16:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T03:51:40.000Z", "avg_line_length": 37.554245283, "max_line_length": 169, "alphanum_fraction": 0.5794762294, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 4406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3593641588823761, "lm_q1q2_score": 0.19647809611685546}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nThis script runs MCSED on objects and is organized in the same BLOCK method\nthat variable_house.py is.  A user should have read through variable_house.py\nbefore interacting with main.py.  Heres an overview:\n\nBlock 1 - imports, ignore\nBlock 2 - for running multiple scripts. *INTERACTABLE*\nBlock 3 - set up how walkers obtain SEDs during random walk\nBlock 4 - defination of the stellar population/PRErams, user interactible \nBlock 5 - begin the for loop to run MCSED on each object\nBlock 6 - handle fluxes and errors, including error floors\nBlock 7 - begin actual random walk. pass lnprob() additional inputs here.\nBlock 8 - save results of walk in .npz\n\"\"\"\n\nVERSION = '1.4c' #see docs/change_log.txt\n\n# = BLOCK 1 ========================================================= BLOCK 1 =\n# Be polite and print a title.\nprint \"\\n ** MCSED ** \\n\"\nprint \"written by Hunter Brooks, hzb5080@psu.edu\"\nprint \"Penn State, Dep't of Astronomy\"\nprint \"version:\", VERSION, \"\\n\"\n\n# remove all old .pyc files to make sure no funny business is going on\nprint '... Cleaning old .pyc files'\nimport os\ndirectory = os.listdir('.')\nfor filename in directory:\n    if filename[-3:] == 'pyc':\n        os.remove(filename)\n\n# import everything that is needed\nprint '... Doing initial imports'\nimport time\nstart_time = time.time() # store start time \nimport numpy as np\nimport emcee_functions as mcF\nimport factory\nimport math_functions as mathF\n# get home\nimport wheres_home\nhome = wheres_home.getHomeLocation()\nimport variable_house as vHouse\nimport sys\n\n\n# = BLOCK 2 ========================================================= BLOCK 2 =\nnScriptsRunning = 1 #up to 100, numbered with two digits each time\nsuperIndexes = np.loadtxt(home+'data/active/superIndexes.dat')\n\n# get name of this script, and which number it is\nthisScriptName = sys.argv[0][-9:] # filename should be NNmain.py, eg 04main.py\nthisScriptNumb = int(thisScriptName[0:2])\nprint thisScriptNumb\nprint \n\n# split superIndexes into nScriptsRunning chunks\nif (nScriptsRunning == 1):\n    chunks = np.array_split(superIndexes, nScriptsRunning)[0]\nelse:\n    chunks = np.array_split(superIndexes, nScriptsRunning)\nprint chunks    \n\n# = BLOCK 3 ========================================================= BLOCK 3 =\nprint '... Opening necesary MCSED data'\nif vHouse.walker_SED_type == 'Interp':\n    pSpaceGridSize = vHouse.pSpaceGridSize\n    # being loading interpolation data... make a time stamp\n    load_data_time = time.time()\n    npzopendata = np.load(home+'data/pSpaces/size'+str(pSpaceGridSize)+'_sed.npz')\n    sedGrid = npzopendata[\"sedGrid\"]\n    npzopendata.close()\n    npzopendata = np.load(home+'data/pSpaces/size'+str(pSpaceGridSize)+'_other.npz')\n    #valsGrid=npzopendata['valsGrid']  #BROKEN, see create_pSpace.py\n    lambda_e=npzopendata['waves']\n    stellarMassGrid=npzopendata['stellarMassGrid']\n    npzopendata.close()\n    import scipy.interpolate as spterp                                           \n    stellarmass_interp_f = spterp.RegularGridInterpolator(vHouse.paramRanges, \n                                                  stellarMassGrid, \n                                                  method='linear')   \n\n    walker_SED_notes = 'pSpace grid size: '+str(pSpaceGridSize)\n    print '...      Took ', str(time.time() - load_data_time)\nif vHouse.walker_SED_type == 'Direct':\n    sp = vHouse.defSP()\n    lambda_e = sp.wavelengths\n    walker_SED_notes = 'Currently, direct does not work well.. be careful'\n\n\n# = BLOCK 4 ========================================================= BLOCK 4 =\nprint '... Opening necesary observational data'\n# find nFilters and load input data from mcsed/data/active\ncol_names = np.loadtxt(home+'data/active/filter_names.dat', dtype='str')\nfilter_lambdas = np.loadtxt(home+'data/active/filter_lambdas.dat')\nnFilters = len(col_names)\n# load input data, this is the data for the objects YOU want to match\nsuperFluxes = np.loadtxt(home+'data/active/superFluxes.dat')\nsuperErrors = np.loadtxt(home+'data/active/superErrors.dat')\nsuperInfo = np.loadtxt(home+'data/active/superInfo.dat')\nsuperRedshift = np.loadtxt(home+'data/active/superRedshift.dat')\n# handle an irregularity that arises when there is only 1 input\nif len(np.shape(superFluxes)) == 1: #there is only 1 row\n    nSuperCols = np.shape(superFluxes)[0]\n    # we need to reshape superdata because it looses this property when super\n    # data contains only a single row.\n    superFluxes = np.reshape(superFluxes, [1,nSuperCols])\n    superErrors = np.reshape(superErrors, [1,nSuperCols])\n    superInfo = np.reshape(superInfo, [1,np.shape(superInfo)[1]])\n    \nnObjects, nSuperCols = np.shape(superFluxes)\n# make sure nSuperCols == nFilters\nassert nFilters == nSuperCols, \"All observations must have nFilters datum, even if some =0\"\n# make sure no negative errors of average fluxes\nassert len(np.where(superErrors < 0 )[0]) == 0, \"There was a negative average flux.\"\n\n\n# = BLOCK 5 ========================================================= BLOCK 5 =\n# being for loop to run MCSED on each object \nprint '... Starting runs, superIndexes: ', chunks[thisScriptNumb]\n\nfor run_i in chunks:\n# for run_i in chunks[thisScriptNumb]: original    \n    # this keeps things simple, since run_i is just an index\n    run_i = int(run_i)\n    \n    # check to see if this object is in /OUTPUTS\n    if os.path.isfile(home+'OUTPUTS/output'+str(run_i)+'.npz') == True:\n        print\n        print '... '+str(run_i)+' has already been run.'\n        continue\n    \n    # log starting time for this obj\n    run_start_time = time.time()\n    dataAvgFlux = np.zeros([nFilters])\n    dataAvgFluxErr = np.zeros([nFilters])\n    \n    # = BLOCK 6 ===================================================== BLOCK 6 =\n    z = superRedshift[run_i] #redshift for this object\n    assert z >= 0.0, \"Just a check to make sure Redshift is positive...\"\n    dataAvgFlux = np.zeros([nFilters])\n    dataAvgFluxErr = np.zeros([nFilters])\n    \n    # feed all the data into the active variable (dataAvgFlux/Err)...\n    for filt_i in range(0, nFilters):\n        # pull data from superFluxes/Errors into working data\n        dataAvgFlux[filt_i] = superFluxes[run_i, filt_i  ]\n        dataAvgFluxErr[filt_i] = superErrors[run_i, filt_i  ]\n        \n    # ...then run the data/errors through filter machine\n    dataAvgFlux, dataAvgFluxErr = mathF.filterMachine(    dataAvgFlux, \n                                                          dataAvgFluxErr,\n                                                          z, \n                                                          filter_lambdas,\n                                                          run_i)\n                                                          \n    # make sure that dataAvgFlux is not entirely zeros!\n    nNullObs = len(np.where(dataAvgFlux==0)[0])\n    if nNullObs == len(dataAvgFlux):\n        print\n        print '... '+str(run_i)+\" has only null observations (entire dataAvgFlux = 0)\"\n        continue\n    \n    # = BLOCK 7 ===================================================== BLOCK 7 =\n    print\n    print '... Customizing pSpace for super row index: ', run_i\n    \n    # this is used to move data to observed frame\n    nu_obs = mathF.get_nu_obs(lambda_e, z)\n    # create an R_nu array, dont need to do this each time but its fast and\n    # for confusion's sake we just do it each time...\n    R_nu, nFilters = factory.R_nu(home,\n                                  nu_obs)\n    # create D_nu array. D_nu is the space between nu's that corrispond to \n    # sp.wavelengths\n    D_nu = factory.D_nu(nFilters,\n                        nu_obs)\n    # create NU_obs array\n    NU_obs = factory.NU_obs(nFilters,\n                            nu_obs)\n    if vHouse.walker_SED_type == 'Interp':                        \n        # create flux_interp_f from luminosity SED grid\n        fluxes, nu_obs = mathF.getFlux(sedGrid, lambda_e, z)\n        # find the A value for each flux sed\n        A_grid, A_compatible = factory.A_grid(fluxes, \n                                              nFilters, NU_obs, D_nu, R_nu,\n                                              dataAvgFlux, dataAvgFluxErr)\n        # scale fluxes by each SEDs A value\n        fluxes = fluxes*A_compatible\n        # create flux interp function\n        flux_interp_f = spterp.RegularGridInterpolator(vHouse.paramRanges, \n                                                       fluxes, \n                                                       method='linear')                                    \n        # create A interp function\n        A_interp_f = spterp.RegularGridInterpolator(vHouse.paramRanges,\n                                                    A_grid,\n                                                    method='linear')\n    if vHouse.walker_SED_type == 'Direct':\n        flux_interp_f = sp\n        A_interp_f = None\n        stellarmass_interp_f = None\n    \n    print '... Conducting random walk'\n    # BEGIN emcee RUN\n    MCMCout = mcF.conductMCMC(      flux_interp_f,\n                                    A_interp_f,\n                                    stellarmass_interp_f,\n                                    lambda_e, \n                                   \n                                    nFilters,\n                                    z,\n                                    NU_obs,\n                                    D_nu, \n                                    R_nu,\n                                   \n                                    dataAvgFlux,\n                                    dataAvgFluxErr)  \n                                \n    print '...      Took ', str(time.time() - run_start_time)\n    \n    # = BLOCK 8 ===================================================== BLOCK 8 =\n    # save data\n    print '... Saving results of row index: ', run_i\n    save_time = time.time()\n    \n    np.savez_compressed(home+'OUTPUTS/output'+str(run_i)+'.npz', \n                        \n                        run_date=(time.strftime(\"%D :: %H:%M:%S\")),\n                        time_taken = time.time() - run_start_time,\n    \n                        dataAvgFlux = dataAvgFlux,\n                        dataAvgFluxErr = dataAvgFluxErr,\n                        z=z,\n\n                        data_nu_obs = nu_obs,\n                        D_nu = D_nu[0,:-1],\n                        R_nu = R_nu,\n                        \n                        nDim = vHouse.nDim,\n                        nDram = vHouse.nDram,\n                        nWalkers = vHouse.nWalkers,\n                        nSteps = vHouse.nSteps,\n                        nBurnInSteps = vHouse.nBurnInSteps,\n                        \n                        paramNames = vHouse.nameL,\n                        dramNames = vHouse.dRamNames,\n                        paramRanges = vHouse.paramRanges,\n                        \n                        walker_SED_type = vHouse.walker_SED_type,\n                        walker_SED_notes = walker_SED_notes,\n                        \n                        sampler_type = vHouse.sampler_type,\n                        chain = MCMCout[0],\n                        lnprobability = MCMCout[1],\n                        auto_corr = MCMCout[2],\n                        acc_frac = MCMCout[3],\n                        flatchain = MCMCout[4],\n                        flatlnprobability = MCMCout[5],\n                        VERSION = VERSION)\n                        \n    print '...      Took ', str(time.time() - save_time)\n", "meta": {"hexsha": "7b66a2722c10a5bf03104cf41e7bbf61eb1ccf66", "size": 11425, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/01main.py", "max_stars_repo_name": "astronomeralex/mcsed", "max_stars_repo_head_hexsha": "b54184bd0e954420fd2680d789eab1493c2bda16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/01main.py", "max_issues_repo_name": "astronomeralex/mcsed", "max_issues_repo_head_hexsha": "b54184bd0e954420fd2680d789eab1493c2bda16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/01main.py", "max_forks_repo_name": "astronomeralex/mcsed", "max_forks_repo_head_hexsha": "b54184bd0e954420fd2680d789eab1493c2bda16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.2765151515, "max_line_length": 107, "alphanum_fraction": 0.5473085339, "include": true, "reason": "import numpy,import scipy", "num_tokens": 2599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.1964780939225172}}
{"text": "#!/usr/bin/python\n'''\nProgram:\n    This is a program for finding the minimum magnitude of source found in the image. \nUsage: \n    plot_d_mag.py [image_list]\nEditor:\n    Jacob975\n20181219\n#################################\nupdate log\n\n20181219 version alpha 1:\n    1. The code works.\n'''\nfrom astropy.io import fits as pyfits\nfrom astropy import wcs\nfrom astropy.coordinates import SkyCoord\nfrom astropy import units as u\nimport numpy as np\nimport time\nfrom sys import argv\nimport TAT_env\nfrom cataio_lib import get_catalog, get_distance, get_app_mag\nfrom reduction_lib import get_rid_of_exotic\nfrom matplotlib import pyplot as plt\nimport os\nfrom photometry import take_data_within_duration\nimport collections\n\ndef show_cata_mag(mag, ra, dec, VERBOSE = 1):\n    # Load the index of columes\n    reduce_data = np.transpose(np.array([mag, ra, dec], dtype = float))\n    reduce_data = reduce_data[mag.argsort()]\n    reduce_data = reduce_data[~np.isnan(reduce_data[:,0])]\n    # Pick 50 brightest stars from the data\n    reduce_data = reduce_data[:20]\n    world = reduce_data[:,1:]\n    #--------------------------------------------------\n    # Find the catalog magnitude.\n    # Query data from vizier\n    mag_delta_list = []\n    filter_ = 'V'\n    for i in xrange(len(reduce_data)):\n        inst_mag = reduce_data[i,0] \n        RA = float(world[i, 0])\n        DEC = float(world[i, 1])\n        failure, match_star = get_catalog(RA, DEC, TAT_env.URAT_1, TAT_env.index_URAT_1)\n        if failure:\n            continue\n        failure, app_mag = get_app_mag(match_star, filter_)\n        if failure:\n            continue\n        if np.isnan(inst_mag):\n            continue\n        mag_delta = app_mag - inst_mag\n        if VERBOSE == 1: print \"INST_MAG = {0}, CATA_MAG = {1}, delta = {2}\".format(inst_mag, app_mag, mag_delta)\n        mag_delta_list.append(mag_delta)\n    # Find the average of delta_mag\n    # Check if the number of source is enough or not.\n    if len(mag_delta_list) == 0:\n        print \"No enough source found in catalogue for comparison\"\n        return 1\n    mag_delta_list = get_rid_of_exotic(mag_delta_list)\n    if len(mag_delta_list) < 3:\n        print \"No enough source found in catalogue for comparison\"\n        return 1\n    # remove np.nan\n    mag_delta_array = np.array(mag_delta_list)\n    mag_delta_array = mag_delta_array[~np.isnan(mag_delta_array)]\n    # Find the median of the delta of the magnitude, and apply the result on all sources.\n    median_mag_delta = np.median(mag_delta_array)\n    app_mag = mag + median_mag_delta\n    return 0, app_mag\n\ndef pick_median(app_mag, err_app_mag):\n    cata_mag = np.linspace(9, 20, 45)\n    cata_mag = (cata_mag[1:] + cata_mag[:-1]) / 2.0\n    lim_err_mag = np.zeros(len(cata_mag))\n    for i, mag in enumerate(cata_mag):\n        index = np.where(   (app_mag >= mag - 0.125 ) & \n                            (app_mag <  mag + 0.125))\n        selected_err_app_mag = err_app_mag[index]\n        lim_err_mag[i] = np.median(selected_err_app_mag)\n    index_min_err_mag = np.nanargmin(lim_err_mag)\n    lim_err_mag[:index_min_err_mag] = lim_err_mag[index_min_err_mag]\n    nans, x= nan_helper(lim_err_mag)\n    lim_err_mag[nans]= np.interp(x(nans), x(~nans), lim_err_mag[~nans])\n    return cata_mag, lim_err_mag\n\ndef nan_helper(y):\n    \"\"\"Helper to handle indices and logical indices of NaNs.\n\n    Input:\n        - y, 1d numpy array with possible NaNs\n    Output:\n        - nans, logical indices of NaNs\n        - index, a function, with signature indices= index(logical_indices),\n            to convert logical indices of NaNs to 'equivalent' indices\n    Example:\n        >>> # linear interpolation of NaNs\n        >>> nans, x= nan_helper(y)\n        >>> y[nans]= np.interp(x(nans), x(~nans), y[~nans])\n    \"\"\"\n    return np.isnan(y), lambda z: z.nonzero()[0]\n\ndef observable_kepler(cata_mag, lim_err_mag, kepler_mag, kepler_depth):\n    num_observable_sources = np.zeros(len(cata_mag))\n    for i, mag in enumerate(cata_mag):\n        index = np.where(   (kepler_mag >= mag - 0.125 ) & \n                            (kepler_mag < mag + 0.125) & \n                            (kepler_depth > lim_err_mag[i]))\n        num_observable_sources[i] = len(index[0])\n    return cata_mag, num_observable_sources\n#--------------------------------------------\n# main code\nif __name__ == \"__main__\":\n    # Measure time\n    start_time = time.time()\n    #----------------------------------------\n    # Initialize\n    if len(argv) != 4:\n        print \"Error!\\n The number of arguments is wrong.\"\n        print \"Usage: plot_d_mag.py [start time] [end time]\"\n        exit(1)\n    start_date = argv[1]\n    end_date = argv[2]\n    transit_table_name = argv[3]\n    #----------------------------------------\n    # Processing\n    print ('---plot d mag ---')\n    # Take the data in this duration\n    data = take_data_within_duration(start_date, end_date)\n    # Load the index\n    index_BJD = TAT_env.obs_data_titles.index(\"BJD\") \n    index_INST_MAG = TAT_env.obs_data_titles.index('INST_MAG')\n    index_E_INST_MAG = TAT_env.obs_data_titles.index('E_INST_MAG')\n    index_EP_MAG = TAT_env.obs_data_titles.index('EP_MAG')\n    index_E_EP_MAG = TAT_env.obs_data_titles.index('E_EP_MAG')\n    index_RA = TAT_env.obs_data_titles.index('RA')\n    index_DEC = TAT_env.obs_data_titles.index('`DEC`')\n    # Find the first image\n    all_bjd = data[:,index_BJD]\n    bjd_s = [item for item, count in collections.Counter(all_bjd).items() if count > 1]\n    first_bjd = np.amin(bjd_s)\n    # Take and analyize the data of the first image.\n    first_frame_data = data[data[:,index_BJD] == first_bjd]\n    ep_mag = np.array(first_frame_data[:, index_EP_MAG], dtype = float)\n    e_ep_mag = np.array(first_frame_data[:, index_E_EP_MAG], dtype = float)\n    index_no_nan_in_ep_mag = np.where(~np.isnan(ep_mag) & ~np.isnan(e_ep_mag))\n    ra = first_frame_data[:, index_RA]\n    dec = first_frame_data[:, index_DEC]\n    ep_mag = ep_mag[index_no_nan_in_ep_mag]\n    e_ep_mag = e_ep_mag[index_no_nan_in_ep_mag]\n    ra = ra[index_no_nan_in_ep_mag]\n    dec = dec[index_no_nan_in_ep_mag]\n    failure, app_mag = show_cata_mag(ep_mag, ra, dec)\n    # Load transit table\n    index_Vmag = 11\n    index_depth = 10\n    index_depth_measure = 9\n    index_DEC = 5\n    transit_table = np.loadtxt(transit_table_name, dtype = str, delimiter = '\\t')\n    transit_table = transit_table[1:]\n    # Ignore all no-observed data\n    transit_table = transit_table[transit_table[:,index_Vmag] != '']\n    # Take data\n    Vmag = np.array(transit_table[:,index_Vmag], dtype = float)\n    depth = np.array(transit_table[:,index_depth], dtype = float)\n    depth_measure = np.array(transit_table[:,index_depth_measure], dtype = str)\n    DEC = np.array(transit_table[:, index_DEC], dtype = float)\n    above_south30 = DEC > -30.\n    \n    # Take source above -30 dec\n    Vmag  = Vmag[above_south30]\n    depth = depth[above_south30]\n    depth_measure = depth_measure[above_south30]\n    \n    depth_measure[depth_measure == ''] = '0.0'\n    depth_measure = np.array(depth_measure, dtype = float)\n    where_no_depth = depth == 0.0\n    depth[where_no_depth] = depth_measure[where_no_depth]\n    depth = depth / 100.\n    # Calculate the histogram\n    numbers, bin_edges = np.histogram(Vmag, bins = np.linspace(9, 20, 45))\n    bins = (bin_edges[1:] + bin_edges[:-1]) / 2.0\n    cata_mag, lim_err_mag = pick_median(app_mag, e_ep_mag)\n    _, num_obs_source = observable_kepler(cata_mag, lim_err_mag, Vmag, depth)\n    print np.sum(numbers)\n    print np.sum(num_obs_source)\n    # plot the histogram of magnitude\n    fig, axs = plt.subplots(1, 1, figsize = (8,6))\n    axs.set_title('The observable transits')\n    axs.bar(bins, numbers, width = 0.25, color = 'b', label = 'Comfirm transits')\n    axs.bar(cata_mag, num_obs_source, width = 0.20, color = 'r', label = 'Observable comfirm transits')\n    axs.set_xlabel('V magnitude')\n    axs.set_ylabel(\"# of sources\")\n    axs.set_xlim(9, 20)\n    axs.grid()\n    axs.legend()\n    plt.savefig('{0}_{1}_hist_kepler.png'.format(start_date, end_date))\n    #---------------------------------------\n    # Measure time\n    elapsed_time = time.time() - start_time\n    print \"Exiting Main Program, spending \", elapsed_time, \"seconds.\"\n", "meta": {"hexsha": "f31df1c106ef3f1add5768858936a2613d0a9fdb", "size": 8195, "ext": "py", "lang": "Python", "max_stars_repo_path": "plot_observable_TTV_3.py", "max_stars_repo_name": "jacob975/TATIRP", "max_stars_repo_head_hexsha": "2d81fa280e039aa931c6f8456632a23ef123282a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "plot_observable_TTV_3.py", "max_issues_repo_name": "jacob975/TATIRP", "max_issues_repo_head_hexsha": "2d81fa280e039aa931c6f8456632a23ef123282a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-08-22T03:15:22.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-19T17:55:31.000Z", "max_forks_repo_path": "plot_observable_TTV_3.py", "max_forks_repo_name": "jacob975/TATIRP", "max_forks_repo_head_hexsha": "2d81fa280e039aa931c6f8456632a23ef123282a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7815533981, "max_line_length": 113, "alphanum_fraction": 0.6505186089, "include": true, "reason": "import numpy,from astropy", "num_tokens": 2192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.35936415202123906, "lm_q1q2_score": 0.19647809236561006}}
{"text": "\"\"\"\ndefines:\n  - split_line_elements(bdf_model, eids, neids=2,\n                        eid_start=1, nid_start=1)\n\n\"\"\"\nimport numpy as np\nfrom pyNastran.bdf.bdf import read_bdf\n\n\ndef split_line_elements(bdf_model, eids, neids=2,\n                        eid_start=1, nid_start=1):\n    \"\"\"\n    Splits a set of element ids\n\n    Parameters\n    ----------\n    eids : List[int]\n        element ids to split\n    neids : int; default=5\n        how many elements should a single bar be split into\n        min=2\n    eid_start : int; default=1\n        the starting element id\n    nid_start : int; default=1\n        the starting node id\n\n    Returns\n    -------\n    eids_out : List[int]\n        the list of elements that have been added\n    eid_end : int; default=1\n        the final element id\n    nid_end : int; default=1\n        the final node id\n\n    A-----*-----B; neids=2\n    A--*--*--*--B; neids=4\n\n    \"\"\"\n    eids_out = []\n    assert neids >= 2, neids\n    dx = np.linspace(0., 1., num=neids+1)\n    for eid in eids:\n        elem = bdf_model.elements[eid]\n        n1, n2 = elem.nodes\n        node1 = bdf_model.nodes[n1]\n        node2 = bdf_model.nodes[n2]\n        cp = node1.cp\n        assert node1.cp == node2.cp\n        assert node1.cd == node2.cd\n        xyz1 = node1.xyz\n        xyz2 = node2.xyz\n        dxyz = xyz2 - xyz1\n        etype = elem.type\n\n        if etype in ['CBAR', 'CBEAM']:\n            pa = elem.pa\n            pb = 0\n\n        elem.comment = ''\n        comment = str(elem) + '\\n'\n        for ieid in range(neids):\n            dxi = dx[ieid + 1]\n            new_xyz = xyz1 + dxyz * dxi\n            if dxi < 1.:\n                new_node = nid_start\n                nid_start += 1\n                bdf_model.add_grid(new_node, new_xyz, cp=cp)\n            else:\n                new_node = n2\n                if etype in ['CBAR', 'CBEAM']:\n                    pb = elem.pb\n\n            if etype == 'CONROD':\n                nids = [n1, new_node]\n                bdf_model.add_conrod(eid_start, elem.mid, nids, elem.A, j=elem.j,\n                                     c=elem.c, nsm=elem.nsm, comment=comment)\n            elif etype == 'CROD':\n                nids = [n1, new_node]\n                bdf_model.add_crod(eid_start, elem.pid, nids, comment=comment)\n            elif etype == 'CBAR':\n                ga = n1\n                gb = new_node\n                bdf_model.add_cbar(eid_start, elem.pid, [ga, gb], elem.x, elem.g0, offt=elem.offt,\n                                   pa=pa, pb=pb, wa=elem.wa, wb=elem.wb, comment=comment)\n                pa = 0\n            elif etype == 'CBEAM':\n                ga = n1\n                gb = new_node\n                bdf_model.add_cbeam(eid_start, elem.pid, [ga, gb], elem.x, elem.g0,\n                                    offt=elem.offt, bit=elem.bit,\n                                    pa=pa, pb=pb,\n                                    wa=elem.wa, wb=elem.wb, sa=elem.sa, sb=elem.sb,\n                                    comment=comment)\n                pa = 0\n            else:\n                raise NotImplementedError(elem)\n            n1 = new_node\n            eids_out.append(eid_start)\n            eid_start += 1\n            comment = str(eid)\n        del bdf_model.elements[eid]\n    return eids_out, eid_start, nid_start\n\n\ndef split_elements(bdf_filename):\n    \"\"\"unimplemented method for splitting elements\"\"\"\n    model = read_bdf(bdf_filename, xref=True)\n    for eid, elem in model.elements.items():\n        if elem.type == 'CTRIA3':\n            #\n            #        3\n            #       /|\\\n            #      / | \\\n            #     /  |  \\\n            #    /   4   \\\n            #   /  /   \\  \\\n            #  / /       \\ \\\n            # 1-------------2\n            #\n            p1, p2, p3 = elem.get_node_positions()\n            #centroid = (p1 + p2 + p3) / 3.\n\n            #\n            #      3\n            #     /|\\\n            #    / | \\\n            #   /  |  \\\n            #  /   |   \\\n            # 1----4----2\n            #\n        elif elem.type == 'CQUAD4':\n            #\n            #\n            # 4---------3\n            # | \\     / |\n            # |   \\  /  |\n            # |    5    |\n            # |  /   \\  |\n            # |/       \\|\n            # 1---------2\n            #\n            # the same thing shown in a rotated view\n            #           4\n            #          /| \\\n            #       /   |   \\\n            #     /     |     \\\n            #   /       |       \\\n            # 1---------5---------3\n            #   \\       |       /\n            #     \\     |     /\n            #       \\   |   /\n            #         \\ | /\n            #           2\n            #\n            # max_area, taper_ratio, area_ratio\n            # 4----7----3\n            # |    |    |\n            # |    |    |\n            # 8----9----6\n            # |    |    |\n            # |    |    |\n            # 1----4----2\n            #\n            # max_interior_angle\n            #      4---------3\n            #     / \\       /\n            #    /   \\     /\n            #   /     \\   /\n            #  /       \\ /\n            # 1---------2\n            #\n            # taper_ratio\n            #     4--6--3\n            #    /   |   \\\n            #   /    |    \\\n            #  /     |     \\\n            # 1------5------2\n            #\n            # taper_ratio\n            #     4------3\n            #    / \\    / \\\n            #   /   \\  /   \\\n            #  /     \\/     \\\n            # 1-------5------2\n            #\n            # taper_ratio\n            #     4------3\n            #    / \\      \\\n            #   /   \\      \\\n            #  /     \\      \\\n            # 1-------5------2\n            pass\n", "meta": {"hexsha": "e26d3e14824347b41d16eccb7af132efd41fa253", "size": 5678, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyNastran/bdf/mesh_utils/split_elements.py", "max_stars_repo_name": "ACea15/pyNastran", "max_stars_repo_head_hexsha": "5ffc37d784b52c882ea207f832bceb6b5eb0e6d4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 293, "max_stars_repo_stars_event_min_datetime": "2015-03-22T20:22:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T20:28:24.000Z", "max_issues_repo_path": "pyNastran/bdf/mesh_utils/split_elements.py", "max_issues_repo_name": "ACea15/pyNastran", "max_issues_repo_head_hexsha": "5ffc37d784b52c882ea207f832bceb6b5eb0e6d4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 512, "max_issues_repo_issues_event_min_datetime": "2015-03-14T18:39:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:15:43.000Z", "max_forks_repo_path": "pyNastran/bdf/mesh_utils/split_elements.py", "max_forks_repo_name": "ACea15/pyNastran", "max_forks_repo_head_hexsha": "5ffc37d784b52c882ea207f832bceb6b5eb0e6d4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 136, "max_forks_repo_forks_event_min_datetime": "2015-03-19T03:26:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T22:14:54.000Z", "avg_line_length": 29.1179487179, "max_line_length": 98, "alphanum_fraction": 0.3420218387, "include": true, "reason": "import numpy", "num_tokens": 1520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.19647808861436467}}
{"text": "import numbers\nfrom contextlib import contextmanager\nfrom functools import wraps, partial\nfrom typing import List, Callable\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.client import device_lib\n\nfrom ..math.backend._backend import combined_dim\nfrom ..math.backend._dtype import DType, to_numpy_dtype, from_numpy_dtype\nfrom phi.math.backend import Backend, ComputeDevice, NUMPY\nfrom ._tf_cuda_resample import resample_cuda, use_cuda\n\n\nclass TFBackend(Backend):\n\n    def __init__(self):\n        Backend.__init__(self, \"TensorFlow\", default_device=None)\n\n    def prefers_channels_last(self) -> bool:\n        return True\n\n    def list_devices(self, device_type: str or None = None) -> List[ComputeDevice]:\n        tf_devices = device_lib.list_local_devices()\n        devices = []\n        for device in tf_devices:\n            if device_type in (None, device.device_type):\n                devices.append(ComputeDevice(self, device.name, device.device_type, device.memory_limit,\n                                             processor_count=-1,\n                                             description=str(device),\n                                             ref=device))\n        return devices\n\n    def seed(self, seed: int):\n        tf.random.set_seed(seed)\n\n    def is_tensor(self, x, only_native=False):\n        is_tf_tensor = tf.is_tensor(x) is True  # tf.is_tensor() can return non-bool values which indicates not a Tensor\n        if only_native:\n            return is_tf_tensor\n        else:\n            return is_tf_tensor or NUMPY.is_tensor(x, only_native=False)\n\n    def as_tensor(self, x, convert_external=True):\n        if self.is_tensor(x, only_native=convert_external):\n            return x\n        tensor = tf.convert_to_tensor(x)\n        # --- Enforce Precision ---\n        if not isinstance(tensor, numbers.Number):\n            if isinstance(tensor, np.ndarray):\n                tensor = NUMPY.as_tensor(tensor)\n            elif tensor.dtype.is_floating:\n                tensor = self.to_float(tensor)\n        return tensor\n\n    def is_available(self, tensor) -> bool:\n        if self.is_tensor(tensor, only_native=True):\n            return tf.executing_eagerly()\n        else:\n            return True\n\n    def numpy(self, tensor):\n        if tf.is_tensor(tensor):\n            return tensor.numpy()\n        return NUMPY.numpy(tensor)\n\n    def to_dlpack(self, tensor):\n        from tensorflow import experimental\n        return experimental.dlpack.to_dlpack(tensor)\n\n    def from_dlpack(self, capsule):\n        from tensorflow import experimental\n        return experimental.dlpack.from_dlpack(capsule)\n\n    def copy(self, tensor, only_mutable=False):\n        if not only_mutable or tf.executing_eagerly():\n            return tf.identity(tensor)\n        else:\n            return tensor\n\n    def jit_compile(self, f: Callable) -> Callable:\n        compiled = tf.function(f)\n        return lambda *args: self.as_registered.call(compiled, *args, name=f\"run jit-compiled '{f.__name__}'\")\n\n    def custom_gradient(self, f: Callable, gradient: Callable = None) -> Callable:\n        @tf.custom_gradient\n        def tf_function(*args, **kwargs):\n            def grad(*grad_args):\n                return gradient(args, y, grad_args)\n            y = f(*args, **kwargs)\n            return y, grad\n        return tf_function\n\n    def transpose(self, tensor, axes):\n        return tf.transpose(tensor, perm=axes)\n\n    def equal(self, x, y):\n        return tf.equal(x, y)\n\n    def divide_no_nan(self, x, y):\n        x, y = self.auto_cast(x, y)\n        return tf.math.divide_no_nan(x, y)\n\n    def random_uniform(self, shape):\n        return tf.random.uniform(shape, dtype=to_numpy_dtype(self.float_type))\n\n    def random_normal(self, shape):\n        return tf.random.normal(shape, dtype=to_numpy_dtype(self.float_type))\n\n    def rank(self, value):\n        return len(value.shape)\n\n    def range(self, start, limit=None, delta=1, dtype: DType = DType(int, 32)):\n        return tf.range(start, limit, delta, to_numpy_dtype(dtype))\n\n    def tile(self, value, multiples):\n        if isinstance(multiples, (tuple, list)) and self.ndims(value) < len(multiples):\n            value = self.expand_dims(value, axis=0, number=len(multiples) - self.ndims(value))\n        return tf.tile(value, multiples)\n\n    def stack(self, values, axis=0):\n        return tf.stack(values, axis=axis)\n\n    def concat(self, values, axis):\n        return tf.concat(values, axis)\n\n    def pad(self, value, pad_width, mode='constant', constant_values=0):\n        if mode == 'boundary' and np.all(np.array(pad_width) <= 1):\n            mode = 'symmetric'\n        if mode in ('constant', 'symmetric', 'reflect'):\n            return tf.pad(value, pad_width, mode.upper(), constant_values=constant_values)\n        else:\n            return NotImplemented\n\n    def reshape(self, value, shape):\n        return tf.reshape(value, shape)\n\n    def sum(self, value, axis=None, keepdims=False):\n        if axis is not None:\n            if not isinstance(axis, int):\n                axis = list(axis)\n        if isinstance(value, tf.SparseTensor):\n            return tf.sparse.reduce_sum(value, axis=axis, keepdims=keepdims, output_is_sparse=False)\n        if isinstance(value, (tuple, list)) and any([isinstance(x, tf.SparseTensor) for x in value]):\n            result = value[0]\n            for v in value[1:]:\n                result = tf.sparse.add(result, v, threshold=0)\n            return result\n        return tf.reduce_sum(value, axis=axis, keepdims=keepdims)\n\n    def prod(self, value, axis=None):\n        if axis is not None:\n            if not isinstance(axis, int):\n                axis = list(axis)\n        if value.dtype == bool:\n            return tf.reduce_all(value, axis=axis)\n        return tf.reduce_prod(value, axis=axis)\n\n    def where(self, condition, x=None, y=None):\n        c = self.cast(condition, self.dtype(x))\n        return c * x + (1 - c) * y\n        # return tf.where(condition, x, y)  # TF1 has an inconsistent broadcasting rule for where\n\n    def nonzero(self, values):\n        return tf.where(tf.not_equal(values, 0))\n\n    def mean(self, value, axis=None, keepdims=False):\n        if axis is not None:\n            if not isinstance(axis, int):\n                axis = list(axis)\n        return tf.reduce_mean(value, axis, keepdims=keepdims)\n\n    def grid_sample(self, grid, spatial_dims: tuple, coordinates, extrapolation='constant'):\n        if use_cuda(grid):\n            # TODO reshape for spatial_dims\n            return resample_cuda(grid, coordinates, extrapolation)\n        else:\n            return NotImplemented\n\n    def zeros(self, shape, dtype: DType = None):\n        return tf.zeros(shape, dtype=to_numpy_dtype(dtype or self.float_type))\n\n    def zeros_like(self, tensor):\n        return tf.zeros_like(tensor)\n\n    def ones(self, shape, dtype: DType = None):\n        return tf.ones(shape, dtype=to_numpy_dtype(dtype or self.float_type))\n\n    def ones_like(self, tensor):\n        return tf.ones_like(tensor)\n\n    def meshgrid(self, *coordinates):\n        result = tf.meshgrid(*coordinates, indexing='ij')\n        return result\n\n    def linspace(self, start, stop, number):\n        return self.to_float(tf.linspace(start, stop, number))\n\n    def tensordot(self, a, a_axes: tuple or list, b, b_axes: tuple or list):\n        return tf.tensordot(a, b, (a_axes, b_axes))\n\n    def matmul(self, A, b):\n        if isinstance(A, tf.SparseTensor):\n            result_T = tf.sparse.sparse_dense_matmul(A, tf.transpose(b))  # result shape contains unknown size\n            result = tf.transpose(result_T)\n            result.set_shape(tf.TensorShape([b.shape[0], A.shape[0]]))\n            return result\n        else:\n            return tf.matmul(A, b)\n\n    def einsum(self, equation, *tensors):\n        return tf.einsum(equation, *tensors)\n\n    def while_loop(self, loop: Callable, values: tuple):\n        cond = lambda c, *vals: tf.reduce_any(c)\n        return tf.nest.map_structure(tf.stop_gradient, tf.while_loop(cond, loop, values))\n\n    def abs(self, x):\n        return tf.abs(x)\n\n    def sign(self, x):\n        return tf.sign(x)\n\n    def round(self, x):\n        return tf.round(x)\n\n    def ceil(self, x):\n        return tf.math.ceil(x)\n\n    def floor(self, x):\n        return tf.floor(x)\n\n    def max(self, x, axis=None, keepdims=False):\n        if isinstance(x, (tuple, list)):\n            x = tf.stack(x)\n        if x.dtype == tf.bool:\n            return tf.cast(tf.reduce_max(tf.cast(x, tf.uint8), axis=axis, keepdims=keepdims), tf.bool)  # reduce_max allows no bool\n        return tf.reduce_max(x, axis=axis, keepdims=keepdims)\n\n    def min(self, x, axis=None, keepdims=False):\n        if isinstance(x, (tuple, list)):\n            x = tf.stack(x)\n        if x.dtype == tf.bool:\n            return tf.cast(tf.reduce_min(tf.cast(x, tf.uint8), axis=axis, keepdims=keepdims), tf.bool)  # reduce_min allows no bool\n        return tf.reduce_min(x, axis=axis, keepdims=keepdims)\n\n    def maximum(self, a, b):\n        a, b = self.auto_cast(a, b)\n        return tf.maximum(a, b)\n\n    def minimum(self, a, b):\n        a, b = self.auto_cast(a, b)\n        return tf.minimum(a, b)\n\n    def clip(self, x, minimum, maximum):\n        x, minimum, maximum = self.auto_cast(x, minimum, maximum)\n        return tf.clip_by_value(x, minimum, maximum)\n\n    def sqrt(self, x):\n        return tf.sqrt(x)\n\n    def exp(self, x):\n        return tf.exp(x)\n\n    def conv(self, value, kernel, zero_padding=True):\n        value = self.to_float(value)\n        kernel = self.to_float(kernel)  # should use auto_cast but TensorFlow only supports DT_HALF, DT_BFLOAT16, DT_FLOAT, DT_DOUBLE, DT_INT32\n        if zero_padding:\n            value_padding = [[0, 0]] * 2 + [[s // 2, (s - 1) // 2] for s in kernel.shape[3:]]\n            value = tf.pad(value, value_padding)\n        convf = {3: partial(tf.nn.conv1d, stride=1),\n                 4: partial(tf.nn.conv2d, strides=[1, 1, 1, 1]),\n                 5: partial(tf.nn.conv3d, strides=[1, 1, 1, 1, 1])}[len(value.shape)]\n        value = tf.transpose(value, [0, *range(2, self.ndims(value)), 1])  # could use data_format='NC...' but it's supported neither on CPU and for int tensors\n        kernel = tf.transpose(kernel, [0, *range(3, self.ndims(kernel)), 2, 1])\n        if kernel.shape[0] == 1:\n            result = convf(value, kernel[0, ...], padding='VALID')\n        else:\n            result = []\n            for b in range(kernel.shape[0]):\n                result.append(convf(value[b:b+1, ...], kernel[b], padding='VALID'))\n            result = tf.concat(result, 0)\n        result = tf.transpose(result, [0, self.ndims(result) - 1, *range(1, self.ndims(result) - 1)])\n        return result\n\n    def expand_dims(self, a, axis=0, number=1):\n        if number == 0:\n            return a\n        for _i in range(number):\n            a = tf.expand_dims(a, axis)\n        return a\n\n    def shape(self, tensor):\n        return tf.shape(tensor)\n\n    def staticshape(self, tensor):\n        if self.is_tensor(tensor, only_native=True):\n            return tuple(tensor.shape.as_list())\n        else:\n            return np.shape(tensor)\n\n    def batched_gather_nd(self, values, indices):\n        values_shape = self.staticshape(values)\n        if values_shape[0] == 1 and self.staticshape(indices)[0] > 1:\n            result = tf.gather_nd(values[0, ...], indices, batch_dims=0)\n            return result\n        if values_shape[0] > 1 and self.staticshape(indices)[0] == 1:\n            indices = tf.tile(indices, [values_shape[0]] + [1] * (len(values_shape) - 1))\n        return tf.gather_nd(values, indices, batch_dims=1)\n\n    def unstack(self, tensor, axis=0, keepdims=False):\n        unstacked = tf.unstack(tensor, axis=axis)\n        if keepdims:\n            unstacked = [self.expand_dims(c, axis=axis) for c in unstacked]\n        return unstacked\n\n    def std(self, x, axis=None, keepdims=False):\n        _mean, var = tf.nn.moments(x, axis, keepdims=keepdims)\n        return tf.sqrt(var)\n\n    def boolean_mask(self, x, mask, axis=0):\n        return tf.boolean_mask(x, mask, axis=axis)\n\n    def isfinite(self, x):\n        return tf.math.is_finite(x)\n\n    def any(self, boolean_tensor, axis=None, keepdims=False):\n        return tf.reduce_any(boolean_tensor, axis=axis, keepdims=keepdims)\n\n    def all(self, boolean_tensor, axis=None, keepdims=False):\n        return tf.reduce_all(boolean_tensor, axis=axis, keepdims=keepdims)\n\n    def scatter(self, base_grid, indices, values, mode: str):\n        base_grid, values = self.auto_cast(base_grid, values)\n        indices = self.as_tensor(indices)\n        batch_size = combined_dim(combined_dim(indices.shape[0], values.shape[0]), base_grid.shape[0])\n        scatter = tf.tensor_scatter_nd_add if mode == 'add' else tf.tensor_scatter_nd_update\n        result = []\n        for b in range(batch_size):\n            b_grid = base_grid[b, ...]\n            b_indices = indices[min(b, indices.shape[0] - 1), ...]\n            b_values = values[min(b, values.shape[0] - 1), ...]\n            result.append(scatter(b_grid, b_indices, b_values))\n        return self.stack(result, axis=0)\n\n    def fft(self, x):\n        rank = len(x.shape) - 2\n        assert rank >= 1\n        x = self.to_complex(x)\n        if rank == 1:\n            return tf.stack([tf.signal.fft(c) for c in tf.unstack(x, axis=-1)], axis=-1)\n        elif rank == 2:\n            return tf.stack([tf.signal.fft2d(c) for c in tf.unstack(x, axis=-1)], axis=-1)\n        elif rank == 3:\n            return tf.stack([tf.signal.fft3d(c) for c in tf.unstack(x, axis=-1)], axis=-1)\n        else:\n            raise NotImplementedError('n-dimensional FFT not implemented.')  # TODO perform multiple lower-dimensional FFTs\n\n    def ifft(self, k):\n        rank = len(k.shape) - 2\n        assert rank >= 1\n        if rank == 1:\n            return tf.stack([tf.signal.ifft(c) for c in tf.unstack(k, axis=-1)], axis=-1)\n        elif rank == 2:\n            return tf.stack([tf.signal.ifft2d(c) for c in tf.unstack(k, axis=-1)], axis=-1)\n        elif rank == 3:\n            return tf.stack([tf.signal.ifft3d(c) for c in tf.unstack(k, axis=-1)], axis=-1)\n        else:\n            raise NotImplementedError('n-dimensional inverse FFT not implemented.')\n\n    def imag(self, complex):\n        return tf.math.imag(complex)\n\n    def real(self, complex):\n        return tf.math.real(complex)\n\n    def cast(self, x, dtype: DType):\n        if not self.is_tensor(x, only_native=True):\n            x = self.as_tensor(x, convert_external=True)\n        if self.dtype(x) == dtype:\n            return x\n        else:\n            return tf.cast(x, to_numpy_dtype(dtype))\n\n    def sin(self, x):\n        return tf.math.sin(x)\n\n    def cos(self, x):\n        return tf.math.cos(x)\n\n    def tan(self, x):\n        return tf.math.tan(x)\n\n    def log(self, x):\n        return tf.math.log(x)\n\n    def log2(self, x):\n        return tf.math.log(x) / 0.6931471805599453094  # log(x) / log(2)\n\n    def log10(self, x):\n        return tf.math.log(x) / 2.3025850929940456840  # log(x) / log(10)\n\n    def dtype(self, array) -> DType:\n        if tf.is_tensor(array):\n            dt = array.dtype.as_numpy_dtype\n            return from_numpy_dtype(dt)\n        else:\n            return NUMPY.dtype(array)\n\n    def sparse_tensor(self, indices, values, shape):\n        indices = [tf.convert_to_tensor(i, tf.int64) for i in indices]\n        indices = tf.cast(tf.stack(indices, axis=-1), tf.int64)\n        return tf.SparseTensor(indices=indices, values=values, dense_shape=shape)\n\n    def coordinates(self, tensor):\n        assert isinstance(tensor, tf.SparseTensor)\n        idx = tensor.indices\n        idx = tuple(tf.unstack(idx, axis=-1))\n        return idx, tensor.values\n\n    def add(self, a, b):\n        if isinstance(a, tf.SparseTensor) or isinstance(b, tf.SparseTensor):\n            return tf.sparse.add(a, b, threshold=1e-5)\n        else:\n            return Backend.add(self, a, b)\n\n    def functional_gradient(self, f, wrt: tuple or list, get_output: bool):\n        @wraps(f)\n        def eval_grad(*args):\n            args = [self.as_tensor(arg, True) if i in wrt else arg for i, arg in enumerate(args)]\n            wrt_args = [arg for i, arg in enumerate(args) if i in wrt]\n            with tf.GradientTape(watch_accessed_variables=False) as tape:\n                for arg in wrt_args:\n                    assert arg.dtype in (tf.float16, tf.float32, tf.float64, tf.complex64, tf.complex128), f\"Gradients can only be computed for float or complex tensors but got {arg.dtype} for argument with shape {arg.shape}\"\n                    tape.watch(arg)\n                output = f(*args)\n            loss, aux = (output[0], output[1:]) if isinstance(output, (tuple, list)) else (output, None)\n            # if self.ndims(loss) > 0:\n            #     loss = tf.reduce_sum(loss)  # this is not needed and will cause gradients to be None\n            grads = list(self.as_registered.call(tape.gradient, loss, wrt_args, name=f\"Backpropagation\"))\n            assert None not in grads, f\"Gradient could not be computed for wrt argument {grads.index(None)} (argument {wrt[grads.index(None)]}) with shape {wrt_args[grads.index(None)].shape}. TensorFlow returned gradient=None.\"\n            if get_output:\n                if aux is not None:\n                    return (loss, *aux, *grads)\n                else:\n                    return (loss, *grads)\n            else:\n                return grads\n        return eval_grad\n\n    # def variable(self, value):  # not supported, variables must record gradients outside a context\n    #     return tf.Variable(value, trainable=True)\n\n    def gradients(self, y, xs: tuple or list, grad_y):\n        if _TAPES:\n            tape = _TAPES[-1]\n            return tape.gradient(y, xs, grad_y)\n        return tf.gradients(y, xs, grad_y)\n\n    @contextmanager\n    def record_gradients(self, xs: tuple or list, persistent=False):\n        tape = tf.GradientTape(persistent=persistent)\n        tape.__enter__()\n        for x in xs:\n            tape.watch(x)\n        _TAPES.append(tape)\n\n        try:\n            yield None\n        finally:\n            tape.__exit__(None, None, None)\n            _TAPES.pop(-1)\n\n    def stop_gradient(self, value):\n        return tf.stop_gradient(value)\n\n\n_TAPES = []\n", "meta": {"hexsha": "6eea13df5c47bb7838cd97aa350eabbfc14f117f", "size": 18296, "ext": "py", "lang": "Python", "max_stars_repo_path": "phi/tf/_tf_backend.py", "max_stars_repo_name": "marc-gav/PhiFlow", "max_stars_repo_head_hexsha": "b6186fd1503d040997b52d49aa18cd875267c27e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "phi/tf/_tf_backend.py", "max_issues_repo_name": "marc-gav/PhiFlow", "max_issues_repo_head_hexsha": "b6186fd1503d040997b52d49aa18cd875267c27e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phi/tf/_tf_backend.py", "max_forks_repo_name": "marc-gav/PhiFlow", "max_forks_repo_head_hexsha": "b6186fd1503d040997b52d49aa18cd875267c27e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1166666667, "max_line_length": 227, "alphanum_fraction": 0.6062527328, "include": true, "reason": "import numpy", "num_tokens": 4451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3593641382989649, "lm_q1q2_score": 0.19647808486311927}}
{"text": "# Copyright (c) 2015, Michael Boyle\n# See LICENSE file for details: <https://github.com/moble/scri/blob/master/LICENSE>\n\nimport os\nimport inspect\nimport functools\nimport warnings\nimport socket\nimport datetime\nimport pprint\nimport copy\nimport numpy as np\nimport quaternion\nimport scipy.constants as spc\nfrom scipy.interpolate import CubicSpline\nfrom . import *\n\n@jit(\"void(c16[:,:], f8[:])\")\ndef complex_array_norm(c, s):\n    for i in range(len(s)):\n        s[i] = 0.0\n        for j in range(c.shape[1]):\n            s[i] += c[i, j].real ** 2 + c[i, j].imag ** 2\n    return\n\n@jit(\"void(c16[:,:], f8[:])\")\ndef complex_array_abs(c, s):\n    for i in range(len(s)):\n        s[i] = 0.0\n        for j in range(c.shape[1]):\n            s[i] += c[i, j].real ** 2 + c[i, j].imag ** 2\n        s[i] = np.sqrt(s[i])\n    return\n\n\ndef waveform_alterations(func):\n    \"\"\"Temporarily increment history depth safely\n\n    This decorator stores the value of `self.__history_depth__`, then increments it by 1, calls the function,\n    returns the history depth to its original value, and then returns the result of the function.  This should be\n    used on any member function that could alter the waveform on which it is called, or which could return a new\n    altered version of the original.\n\n    Typically, within the function itself, you will want to decrement the depth manually just before appending to the\n    history -- which will presumably take place at the end of the function.  You do not need to undo this,\n    as the decorator will take care of that part.\n\n    \"\"\"\n\n    @functools.wraps(func)\n    def func_wrapper(self, *args, **kwargs):\n        if self.__history_depth__ == 0:\n            self._append_history(\"\")\n        stored_history_depth = self.__history_depth__\n        self.__history_depth__ += 1\n        result = func(self, *args, **kwargs)\n        self.__history_depth__ = stored_history_depth\n        return result\n\n    return func_wrapper\n\n\ndef test_without_assertions(errs, val, msg=\"\"):\n    \"\"\"Replacement for np.testing.assert_\n\n    This function should be able to replace `assert_`, but rather than raising an exception, this just adds a\n    description of the problem to the `errors` variable.\n\n    \"\"\"\n    if not val:\n        try:\n            smsg = msg()\n        except TypeError:\n            smsg = msg\n        errs += [smsg]\n\n\ndef test_with_assertions(errs, val, msg=\"\"):\n    np.testing.assert_(val, \"Failed assertion:\\n\\t\" + msg)\n\n\nclass _object:\n    \"\"\"Useless class to allow multiple inheritance\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        super().__init__()\n\n\nclass WaveformBase(_object):\n    \"\"\"Object containing time, frame, and data, along with related information\n\n    This object is just the base object from which these other classes are derived:\n      * WaveformModes\n      * WaveformGrid\n      * WaveformInDetector\n      * WaveformInDetectorFT\n    For more specific information, see the documentation of those classes.\n\n    Attributes\n    ----------\n    t : float array\n        Time steps corresponding to other data\n    frame : quaternion array\n        Rotors taking static basis onto decomposition basis\n    data : 2-d array of complex or real numbers\n        The nature of this data depends on the derived type.  First index is time, second index depends on type.\n    history : list of strings\n        As far as possible, all functions applied to the object are recorded in the `history` variable.  In fact,\n        the object should almost be able to be recreated using the commands in the history list. Commands taking\n        large arrays, however, are shortened -- so the data will not be entirely reconstructable.\n    version_hist : list of pairs of strings\n        Records the git hash and description for any change in the way SpEC outputs waveform data.\n    frameType : int\n        Index corresponding to `scri.FrameType` appropriate for `data`.\n    dataType : int\n        Index corresponding to `scri.DataType` appropriate for `data`.\n    r_is_scaled_out : bool\n        True if the `data` have been multiplied by the appropriate power of radius so that the asymptotic value can\n        be finite and nonzero.\n    m_is_scaled_out : bool\n        True if the `data` have been scaled by the appropriate value of the total mass so that they are dimensionless.\n    num : int (read only)\n        Automatically assigned number of this object.  The constructor of this type keeps count of the number of\n        objects it has created, to assign each object a more-or-less unique ID for use in the history strings.  This\n        counter is reset at the beginning of each python session.  Subclasses should automatically have a different\n        counter.\n\n    Indexing\n    --------\n    WaveformBase objects can be indexed much like a numpy array, where the first dimension gives the time indices,\n    and the second gives the data-set indices. This will return another WaveformBase object containing slices of the\n    original data.\n\n    It is important to note, however, that as with numpy array slices, slicing a WaveformBase will not typically copy\n    the original data; the result will simply be a view into the data.  This means that changing the data in the\n    slice can change the data in the original.  If you want to make a copy, you should probably use the copy\n    constructor: `W2 = WaveformBase(W1)`. It is also possible to use the standard copy.deepcopy method.\n\n    Also note that the first slice dimension corresponds to the indices of the time, but the second dimension may NOT\n    correspond to indices for derived types.  In particular, for `WaveformModes`, the second index corresponds to\n    modes, because this type enforces completeness of each ell mode.  For the `WaveformBase` type, however,\n    the second index does correspond to the second dimension of the data.\n\n    For example,\n\n    >>> W  = WaveformBase()\n    >>> W[10:-20]\n\n    will give all columns in the data, but only at times starting with the\n    10th time step, and ending one before the -20th time step.  Meanwhile,\n\n    >>> W[10:-20,2]\n\n    will give the same range of times, but only the second column (unless the subclass overrides this behavior,\n    as in `WaveformModes`).  Similarly,\n\n    >>> W[10:-20,2:5]\n\n    will return the same range of times, along with the 2,3,4 columns. Note the lack of 5 column, for consistency\n    with python's usual slice syntax.\n\n    >>> W[:,:0]\n\n    will return all time steps, along with all `frame` data, but `data` will be empty (because the `:0` term selects\n    everything before the 0th element).  Similarly,\n\n    >>> W[:0,:0]\n\n    is empty of all numerical data.\n\n    \"\"\"\n\n    __num = 0  # Used to count number of Waveforms created\n\n    def __init__(self, *args, **kwargs):\n        \"\"\"Initializer for WaveformBase object\n\n        WaveformBase objects may be created in two ways.  First, by copying an existing WaveformBase object -- in\n        which case the only parameter should be that object.  Second, by passing any of the (writable) attributes as\n        keywords.\n\n        In both cases, the last step in initialization is to check the validity of the result.  By default,\n        this will raise an exception if the result is not valid.  An additional keyword parameter\n        `override_exception_from_invalidity` may be set if this is not desired.  This may be necessary if only some\n        of the data can be passed in to the initializer, for example.\n\n        Keyword parameters\n        ------------------\n        t: float array, empty default\n        frame : quaternion array, empty default\n        data : 2-d complex array, empty default\n        history : list of strings, empty default\n            This is the list of strings prepended to the history, an additional line is appended, showing the call to\n            this initializer.\n        version_hist : list of pairs of strings, empty default\n            Remains empty if waveform data is on version 0.\n        frameType : int, defaults to 0 (UnknownFrameType)\n            See scri.FrameNames for possible values\n        dataType : int, defaults to 0 (UnknownDataType)\n            See scri.DataNames for possible values\n        r_is_scaled_out : bool, defaults to False\n            Set to True if the data represented could approach a nonzero value at Scri\n        m_is_scaled_out : bool, defaults to False\n            Set to True if the data represented are dimensionless and in units where the total mass is 1\n        override_exception_from_invalidity: bool, defaults to False\n            If True, report any errors, but do not raise them.\n        constructor_statement : str, optional\n            If this is present, it will replace the default constructor statement added to the history.  It is\n            prepended with a string of the form `'{0} = '.format(self)`, which prints the ID of the resulting object\n            (unique to this session only).\n\n        \"\"\"\n        original_kwargs = kwargs.copy()\n        super().__init__(*args, **kwargs)  # to ensure proper calling in multiple inheritance\n        override_exception_from_invalidity = kwargs.pop(\"override_exception_from_invalidity\", False)\n        self.__num = type(self).__num\n        self.__history_depth__ = 0\n        type(self).__num += 1  # Increment class's instance tracker\n        if len(args) == 0:\n            self.t = kwargs.pop(\"t\", np.empty((0,), dtype=float))\n            self.frame = kwargs.pop(\"frame\", np.empty((0,), dtype=np.quaternion))\n            self.data = kwargs.pop(\"data\", np.empty((0, 0), dtype=complex))\n            # Information about this object\n            self.history = kwargs.pop(\"history\", [])\n            self.version_hist = kwargs.pop(\"version_hist\", [])\n            self.frameType = kwargs.pop(\"frameType\", UnknownFrameType)\n            self.dataType = kwargs.pop(\"dataType\", UnknownDataType)\n            self.r_is_scaled_out = kwargs.pop(\"r_is_scaled_out\", False)\n            self.m_is_scaled_out = kwargs.pop(\"m_is_scaled_out\", False)\n            if \"constructor_statement\" in kwargs:\n                self._append_history(\"{} = {}\".format(self, kwargs.pop(\"constructor_statement\")))\n            else:\n                opts = np.get_printoptions()\n                np.set_printoptions(threshold=6)\n                self._append_history(\n                    \"{} = {}(**{})\".format(self, type(self).__name__, pprint.pformat(original_kwargs, indent=4))\n                )\n                np.set_printoptions(**opts)\n        elif len(args) == 1 and isinstance(args[0], type(self)):\n            other = args[0]\n            self.t = np.copy(other.t)\n            self.frame = np.copy(other.frame)\n            self.data = np.copy(other.data)\n            # Information about this object\n            self.history = other.history[:]\n            self.version_hist = other.version_hist[:]\n            self.frameType = other.frameType\n            self.dataType = other.dataType\n            self.r_is_scaled_out = other.r_is_scaled_out\n            self.m_is_scaled_out = other.m_is_scaled_out\n            self._append_history([\"\", \"{} = {}({})\".format(self, type(self).__name__, other)])\n        else:\n            raise ValueError(\n                \"Did not understand input arguments to `{}` constructor.\\n\".format(type(self).__name__)\n                + \"Note that explicit data values must be passed as keywords,\\n\"\n                + \"whereas objects to be copied must be passed as the sole argument.\"\n            )\n        hostname = socket.gethostname()\n        cwd = os.getcwd()\n        time = datetime.datetime.now().isoformat()\n        self.__history_depth__ = 1\n        self.ensure_validity(alter=True, assertions=(not override_exception_from_invalidity))\n        self.__history_depth__ = 0\n        self._append_history([f\"hostname = {hostname}\", f\"cwd = {cwd}\", f\"datetime = {time}\", version_info()], 1)\n        if kwargs:\n            warning = \"\\nIn `{}` initializer, unused keyword arguments:\\n\".format(type(self).__name__)\n            warning += pprint.pformat(kwargs, indent=4)\n            warnings.warn(warning)\n\n    @waveform_alterations\n    def ensure_validity(self, alter=True, assertions=False):\n        \"\"\"Try to ensure that the `WaveformBase` object is valid\n\n        This tests various qualities of the WaveformBase's members that are frequently assumed throughout the code.\n        If the optional argument `alter` is `True` (which is the default), this function tries to alter the\n        WaveformBase in place to ensure validity.  Note that this is not always possible.  If that is the case,\n        an exception may be raised.  For example, if the `t` member is not a one-dimensional array of floats,\n        it is not clear what that data should be. Similarly, if the `t` and `data` members have mismatched\n        dimensions, there is no way to resolve that automatically.\n\n        Also note that this is almost certainly not be an exhaustive test of all assumptions made in the code.\n\n        If the optional `assertions` argument is `True` (default is `False`), the first test that fails will raise an\n        assertion error.\n\n        \"\"\"\n        import numbers\n\n        errors = []\n        alterations = []\n\n        if assertions:\n            test = test_with_assertions\n        else:\n            test = test_without_assertions\n\n        # Ensure that the various data are correct and compatible\n        test(\n            errors,\n            isinstance(self.t, np.ndarray),\n            \"isinstance(self.t, np.ndarray) # type(self.t)={}\".format(type(self.t)),\n        )\n        test(\n            errors,\n            self.t.dtype == np.dtype(np.float),\n            f\"self.t.dtype == np.dtype(np.float) # self.t.dtype={self.t.dtype}\",\n        )\n        if alter and self.t.ndim == 2 and self.t.shape[1] == 1:\n            self.t = self.t[:, 0]\n            alterations += [\"{0}.t = {0}.t[:,0]\".format(self)]\n        test(\n            errors,\n            not self.t.size or self.t.ndim == 1,\n            f\"not self.t.size or self.t.ndim==1 # self.t.size={self.t.size}; self.t.ndim={self.t.ndim}\",\n        )\n        test(\n            errors,\n            self.t.size <= 1 or np.all(np.diff(self.t) > 0.0),\n            \"self.t.size<=1 or np.all(np.diff(self.t)>0.0) \"\n            \"# self.t.size={}; max(np.diff(self.t))={}\".format(\n                self.t.size, (max(np.diff(self.t)) if self.t.size > 1 else np.nan)\n            ),\n        )\n        test(errors, np.all(np.isfinite(self.t)), \"np.all(np.isfinite(self.t))\")\n\n        if alter and self.frame is None:\n            self.frame = np.empty((0,), dtype=np.quaternion)\n            alterations += [f\"{self}.frame = np.empty((0,), dtype=np.quaternion)\"]\n        test(\n            errors,\n            isinstance(self.frame, np.ndarray),\n            \"isinstance(self.frame, np.ndarray) # type(self.frame)={}\".format(type(self.frame)),\n        )\n        if alter and self.frame.dtype == np.dtype(np.float):\n            try:  # Might fail because of shape\n                self.frame = quaternion.as_quat_array(self.frame)\n                alterations += [\"{0}.frame = quaternion.as_quat_array({0}.frame)\".format(self)]\n            except (AssertionError, ValueError):\n                pass\n        test(\n            errors,\n            self.frame.dtype == np.dtype(np.quaternion),\n            f\"self.frame.dtype == np.dtype(np.quaternion) # self.frame.dtype={self.frame.dtype}\",\n        )\n        test(\n            errors,\n            self.frame.size <= 1 or self.frame.size == self.t.size,\n            \"self.frame.size<=1 or self.frame.size==self.t.size \"\n            \"# self.frame.size={}; self.t.size={}\".format(self.frame.size, self.t.size),\n        )\n        test(errors, np.all(np.isfinite(self.frame)), \"np.all(np.isfinite(self.frame))\")\n\n        test(\n            errors,\n            isinstance(self.data, np.ndarray),\n            \"isinstance(self.data, np.ndarray) # type(self.data)={}\".format(type(self.data)),\n        )\n        test(errors, self.data.ndim >= 1, f\"self.data.ndim >= 1 # self.data.ndim={self.data.ndim}\")\n        test(\n            errors,\n            self.data.shape[0] == self.t.shape[0],\n            \"self.data.shape[0]==self.t.shape[0] \"\n            \"# self.data.shape[0]={}; self.t.shape[0]={}\".format(self.data.shape[0], self.t.shape[0]),\n        )\n        test(errors, np.all(np.isfinite(self.data)), \"np.all(np.isfinite(self.data))\")\n\n        # Information about this object\n        if alter and not self.history:\n            self.history = [\"\"]\n            alterations += [f\"{self}.history = ['']\"]\n        if alter and isinstance(self.history, str):\n            self.history = self.history.split(\"\\n\")\n            alterations += [\"{0}.history = {0}.history.split('\\n')\".format(self)]\n        test(\n            errors,\n            isinstance(self.history, list),\n            \"isinstance(self.history, list) # type(self.history)={}\".format(type(self.history)),\n        )\n        test(\n            errors,\n            isinstance(self.history[0], str),\n            \"isinstance(self.history[0], str) # type(self.history[0])={}\".format(type(self.history[0])),\n        )\n        test(\n            errors,\n            isinstance(self.frameType, numbers.Integral),\n            \"isinstance(self.frameType, numbers.Integral) # type(self.frameType)={}\".format(type(self.frameType)),\n        )\n        test(errors, self.frameType in FrameType, f\"self.frameType in FrameType # self.frameType={self.frameType}\")\n        test(\n            errors,\n            isinstance(self.dataType, numbers.Integral),\n            \"isinstance(self.dataType, numbers.Integral) # type(self.dataType)={}\".format(type(self.dataType)),\n        )\n        test(errors, self.dataType in DataType, f\"self.dataType in DataType # self.dataType={self.dataType}\")\n        test(\n            errors,\n            isinstance(self.r_is_scaled_out, bool),\n            \"isinstance(self.r_is_scaled_out, bool) # type(self.r_is_scaled_out)={}\".format(type(self.r_is_scaled_out)),\n        )\n        test(\n            errors,\n            isinstance(self.m_is_scaled_out, bool),\n            \"isinstance(self.m_is_scaled_out, bool) # type(self.m_is_scaled_out)={}\".format(type(self.m_is_scaled_out)),\n        )\n        test(\n            errors,\n            isinstance(self.num, numbers.Integral),\n            \"isinstance(self.num, numbers.Integral) # type(self.num)={}\".format(type(self.num)),\n        )\n\n        if alterations:\n            self._append_history(alterations)\n            warnings.warn(\"The following alterations were made:\\n\\t\" + \"\\n\\t\".join(alterations))\n        if errors:\n            warnings.warn(\"The following conditions were found to be incorrectly False:\\n\\t\" + \"\\n\\t\".join(errors))\n            return False\n\n        self.__history_depth__ -= 1\n        self._append_history(\"WaveformBase.ensure_validity\" + f\"({self}, alter={alter}, assertions={assertions})\")\n\n        return True\n\n    @property\n    def is_valid(self):\n        return self.ensure_validity(alter=False, assertions=False)\n\n    # Data sizes\n    @property\n    def n_data_sets(self):\n        return int(np.prod(self.data.shape[1:]))\n\n    @property\n    def n_times(self):\n        return self.t.shape[0]\n\n    # Calculate weights\n    @property\n    def spin_weight(self):\n        return SpinWeights[self.dataType]\n\n    @property\n    def conformal_weight(self):\n        return ConformalWeights[self.dataType] + (-RScaling[self.dataType] if self.r_is_scaled_out else 0)\n\n    @property\n    def gamma_weight(self):\n        \"\"\"Non-conformal effect of a boost.\n\n        This factor allows for mass-scaling, for example.  If the waveform describes `r*h/M`, for example,\n        then `r` and `h` vary by the conformal weight, which depends on the direction; whereas `M` is a monopole,\n        and thus cannot depend on the direction.  Instead, `M` simply obeys the standard formula, scaling with gamma.\n\n        \"\"\"\n        return (MScaling[self.dataType] if self.m_is_scaled_out else 0) + (\n            -RScaling[self.dataType] if (self.r_is_scaled_out and self.m_is_scaled_out) else 0\n        )\n\n    @property\n    def r_scaling(self):\n        return RScaling[self.dataType]\n\n    @property\n    def m_scaling(self):\n        return MScaling[self.dataType]\n\n    # Text descriptions\n    @property\n    def num(self):\n        return self.__num\n\n    @property\n    def frame_type_string(self):\n        return FrameNames[self.frameType]\n\n    @property\n    def data_type_string(self):\n        return DataNames[self.dataType]\n\n    @property\n    def data_type_latex(self):\n        return DataNamesLaTeX[self.dataType]\n\n    @property\n    def descriptor_string(self):\n        \"\"\"Create a simple string describing the content of the waveform\n\n        This string will be suitable for file names.  For example, 'rMpsi4' or 'rhOverM'.  It uses the waveform's\n        knowledge of itself, so if this is incorrect, the result will be incorrect.\n\n        \"\"\"\n        if self.dataType == UnknownDataType:\n            return self.data_type_string\n        descriptor = \"\"\n        if self.r_is_scaled_out:\n            if RScaling[self.dataType] == 1:\n                descriptor = \"r\"\n            elif RScaling[self.dataType] > 1:\n                descriptor = \"r\" + str(RScaling[self.dataType])\n        if self.m_is_scaled_out:\n            Mexponent = MScaling[self.dataType] - (RScaling[self.dataType] if self.r_is_scaled_out else 0)\n            if Mexponent < -1:\n                descriptor = descriptor + self.data_type_string + \"OverM\" + str(-Mexponent)\n            elif Mexponent == -1:\n                descriptor = descriptor + self.data_type_string + \"OverM\"\n            elif Mexponent == 0:\n                descriptor = descriptor + self.data_type_string\n            elif Mexponent == 1:\n                descriptor = descriptor + \"M\" + self.data_type_string\n            elif Mexponent > 1:\n                descriptor = descriptor + \"M\" + str(Mexponent) + self.data_type_string\n        else:\n            descriptor = descriptor + self.data_type_string\n        return descriptor\n\n    # Data simplifications\n    @property\n    def data_2d(self):\n        return self.data.reshape((self.n_times, self.n_data_sets))\n\n    @property\n    def abs(self):\n        return np.abs(self.data)\n\n    @property\n    def arg(self):\n        return np.angle(self.data)\n\n    @property\n    def arg_unwrapped(self):\n        return np.unwrap(np.angle(self.data), axis=0)\n\n    def norm(self, take_sqrt=False, indices=slice(None, None, None)):\n        \"\"\"L2 norm of the waveform\n\n        The optional arguments say whether to take the square-root of\n        the norm at each time, and allow restriction to a slice of the\n        data, respectively.\n\n        \"\"\"\n        if indices == slice(None, None, None):\n            n = np.empty((self.n_times,), dtype=float)\n        else:\n            n = np.empty((self.t[indices].shape[0],), dtype=float)\n        if take_sqrt:\n            complex_array_abs(self.data_2d[indices], n)\n        else:\n            complex_array_norm(self.data_2d[indices], n)\n        return n\n\n    def max_norm_index(self, skip_fraction_of_data=4):\n        \"\"\"Index of time step with largest norm\n\n        The optional argument skips a fraction of the data.  The default is\n        4, which means that it only searches the last three-fourths of the\n        data for the max.  If 0 or 1 is input, this is ignored, and all the\n        data is searched.\n\n        \"\"\"\n        if skip_fraction_of_data == 0 or skip_fraction_of_data == 1:\n            indices = slice(None, None, None)\n            return np.argmax(self.norm(indices=indices))\n        else:\n            indices = slice(self.n_times // skip_fraction_of_data, None, None)\n            return np.argmax(self.norm(indices=indices)) + (self.n_times // skip_fraction_of_data)\n\n    def max_norm_time(self, skip_fraction_of_data=4):\n        \"\"\"Return time at which largest norm occurs in data\n\n        See `help(max_norm_index)` for explanation of the optional argument.\n\n        \"\"\"\n        return self.t[self.max_norm_index(skip_fraction_of_data=skip_fraction_of_data)]\n\n    def compare(self, w_a, min_time_step=0.005, min_time=-3.0e300):\n        \"\"\"Return a waveform with differences between the two inputs\n\n        This function simply subtracts the data in this waveform from the data\n        in Waveform A, and finds the rotation needed to take this frame into frame A.\n        Note that the waveform data are stored as complex numbers, rather than as \n        modulus and phase.\n        \"\"\"\n        from quaternion.means import mean_rotor_in_chordal_metric\n        from scri.extrapolation import intersection\n        import scri.waveform_modes\n\n        if self.frameType != w_a.frameType:\n            warning = (\n                \"\\nWarning:\"\n                + \"\\n    This Waveform is in the \"\n                + self.frame_type_string\n                + \" frame,\"\n                + \"\\n    The Waveform in the argument is in the \"\n                + w_a.frame_type_string\n                + \" frame.\"\n                + \"\\n    Comparing them probably does not make sense.\\n\"\n            )\n            warnings.warn(warning)\n\n        if self.n_modes != w_a.n_modes:\n            raise Exception(\n                \"Trying to compare waveforms with mismatched LM data.\"\n                + \"\\nA.n_modes=\"\n                + str(w_a.n_modes)\n                + \"\\tB.n_modes()=\"\n                + str(self.n_modes)\n            )\n\n        new_times = intersection(self.t, w_a.t)\n\n        w_c = scri.waveform_modes.WaveformModes(\n            t=new_times,\n            data=np.zeros((new_times.shape[0], self.n_modes), dtype=self.data.dtype),\n            history=[],\n            version_hist=self.version_hist,\n            frameType=self.frameType,\n            dataType=self.dataType,\n            r_is_scaled_out=self.r_is_scaled_out,\n            m_is_scaled_out=self.m_is_scaled_out,\n            ell_min=self.ell_min,\n            ell_max=self.ell_max,\n        )\n\n        w_c.history += [\"B.compare(A)\\n\"]\n        w_c.history += [\"### A.history.str():\\n\" + \"\".join(w_a.history)]\n        w_c.history += [\"### B.history.str():\\n\" + \"\".join(self.history)]\n        w_c.history += [\"### End of old histories from `compare`\"]\n\n        # Process the frame, depending on the sizes of the input frames\n        if w_a.frame.shape[0] > 1 and self.frame.shape[0] > 1:\n            # Find the frames interpolated to the appropriate times\n            Aframe = quaternion.squad(w_a.frame, w_a.t, w_c.t)\n            Bframe = quaternion.squad(self.frame, self.t, w_c.t)\n            # Assign the data\n            w_c.frame = Aframe * np.array([np.quaternion.inverse(v) for v in Bframe])\n        elif w_a.frame.shape[0] == 1 and self.frame.shape[0] > 1:\n            # Find the frames interpolated to the appropriate times\n            Bframe = np.quaternion.squad(self.frame, self.t, w_c.t)\n            # Assign the data\n            w_c.frame.resize(w_c.n_times)\n            w_c.frame = w_a.frame[0] * np.array([np.quaternion.inverse(v) for v in Bframe])\n        elif w_a.frame.shape[0] > 1 and self.frame.shape[0] == 1:\n            # Find the frames interpolated to the appropriate times\n            Aframe = np.quaternion.squad(w_a.frame, w_a.t, w_c.t)\n            # Assign the data\n            w_c.frame.resize(w_c.n_times)\n            w_c.frame = Aframe * np.quaternion.inverse(self.frame[0])\n        elif w_a.frame.shape[0] == 1 and self.frame.shape[0] == 1:\n            # Assign the data\n            w_c.frame = np.array(w_a.frame[0] * np.quaternions.inverse(self.frame[0]))\n        elif w_a.frame.shape[0] == 0 and self.frame.shape[0] == 1:\n            # Assign the data\n            w_c.frame = np.array(np.quaternions.inverse(self.frame[0]))\n        elif w_a.frame.shape[0] == 1 and self.frame.shape[0] == 1:\n            # Assign the data\n            w_c.frame = np.array(w_a.frame[0])\n        # else, leave the frame data empty\n\n        # If the average frame rotor is closer to -1 than to 1, flip the sign\n        if w_c.frame.shape[0] == w_c.n_times:\n            R_m = mean_rotor_in_chordal_metric(w_c.frame, w_c.t)\n            if quaternion.rotor_chordal_distance(R_m, -quaternion.one) < quaternion.rotor_chordal_distance(\n                R_m, quaternion.one\n            ):\n                w_c.frame = -w_c.frame\n        elif w_c.frame.shape[0] == 1:\n            if quaternion.rotor_chordal_distance(w_c.frame[0], -quaternion.one) < quaternion.rotor_chordal_distance(\n                w_c.frame[0], quaternion.one\n            ):\n                w_c.frame[0] = -w_c.frame[0]\n\n        # Now loop over each mode filling in the waveform data\n        for AMode in range(w_a.n_modes):\n            # Assume that all the ell,m data are the same, but not necessarily in the same order\n            BMode = self.index(w_a.LM[AMode][0], w_a.LM[AMode][1])\n            # Initialize the interpolators for this data set\n            # (Can't just re-view here because data are not contiguous)\n            splineReA = CubicSpline(w_a.t, w_a.data[:, AMode].real)\n            splineImA = CubicSpline(w_a.t, w_a.data[:, AMode].imag)\n            splineReB = CubicSpline(self.t, self.data[:, BMode].real)\n            splineImB = CubicSpline(self.t, self.data[:, BMode].imag)\n            # Assign the data from the transition\n            w_c.data[:, AMode] = (splineReA(w_c.t) - splineReB(w_c.t)) + 1j * (splineImA(w_c.t) - splineImB(w_c.t))\n\n        return w_c\n\n    @property\n    def data_dot(self):\n        return CubicSpline(self.t, self.data).derivative()(self.t)\n\n    @property\n    def data_ddot(self):\n        return CubicSpline(self.t, self.data).derivative(2)(self.t)\n\n    @property\n    def data_int(self):\n        return CubicSpline(self.t, self.data).antiderivative()(self.t)\n\n    @property\n    def data_iint(self):\n        return CubicSpline(self.t, self.data).antiderivative(2)(self.t)\n\n    # Data representations\n    def _append_history(self, hist, additional_depth=0):\n        \"\"\"Add to the object's history log\n\n        Input may be a single string or list of strings.  Any newlines will be split into separate strings.  Each\n        such string is then prepended with a number of `#`s, indicating that the content of that line was called from\n        within a member function, or is simply a piece of information relevant to the waveform.  The idea behind this\n        is that the history should be -- as nearly as possible --  a script that could be run to reproduce the\n        waveform, so the lines beginning with `#` would not be run.\n\n        The number of `#`s is controlled by the object's `__history_depth__` field and the optional input to this\n        function; their sum is the number prepended.  The user should never have to deal with this issue,\n        but all member functions should increment the `__history_depth__` before calling another member function,\n        and decrement it again as necessary before recording itself in the history.  Also, for any lines added just\n        for informational purposes (e.g., the hostname, pwd, date, and versions added in `__init__`), this function\n        should be called with `1` as the optional argument.\n\n        \"\"\"\n        if not isinstance(hist, list):\n            hist = [hist]\n        self.history += [\n            \"# \" * (self.__history_depth__ + additional_depth) + hist_line\n            for hist_element in hist\n            for hist_line in hist_element.split(\"\\n\")\n        ]\n\n    def __str__(self):\n        # \"The goal of __str__ is to be readable; the goal of __repr__ is to be unambiguous.\" --- stackoverflow\n        return \"{}_{}\".format(type(self).__name__, self.num)\n\n    def __repr__(self):\n        # \"The goal of __str__ is to be readable; the goal of __repr__ is to be unambiguous.\" --- stackoverflow\n        from textwrap import dedent\n\n        opts = np.get_printoptions()\n        np.set_printoptions(threshold=6, linewidth=150, precision=6)\n        rep = \"\"\"\n         {0}(\n             t={1},\n             frame={2},\n             data={5},\n             frameType={6}, dataType={7},\n             r_is_scaled_out={8}, m_is_scaled_out={9})  # num = {10}\"\"\"\n        rep = rep.format(\n            type(self).__name__,\n            str(self.t).replace(\"\\n\", \"\\n\" + \" \" * 15),\n            str(self.frame).replace(\"\\n\", \"\\n\" + \" \" * 19),\n            self.history,\n            self.version_hist,\n            str(self.data).replace(\"\\n\", \"\\n\" + \" \" * 18),\n            self.frameType,\n            self.dataType,\n            self.r_is_scaled_out,\n            self.m_is_scaled_out,\n            self.num,\n        )\n        np.set_printoptions(**opts)\n        return dedent(rep)\n\n    def __getstate__(self):\n        \"\"\"Get state of object for copying and pickling\n\n        The only nontrivial operation is with quaternions, since they can't\n        currently be pickled automatically.  We just view the frame array as\n        a float array, and pickle as usual.\n\n        Also, we remove the `num` value, because this will get reset\n        properly on creation.\n\n        \"\"\"\n        state = copy.deepcopy(self.__dict__)\n        state[\"frame\"] = quaternion.as_float_array(self.frame)\n        return state\n\n    def __setstate__(self, state):\n        \"\"\"Set state of object for copying and pickling\n\n        The only nontrivial operation is with quaternions, since they can't\n        currently be pickled automatically.  We just view the frame array as\n        a float array, and unpickle as usual, then convert the float array\n        back to a quaternion array.\n\n        \"\"\"\n        new_num = self.__num\n        old_num = state.get(\"_WaveformBase__num\")\n        self.__dict__.update(state)\n        # Make sure to preserve auto-incremented num\n        self.__num = new_num\n        self.frame = quaternion.as_quat_array(self.frame)\n        self._append_history(f\"copied, deepcopied, or unpickled as {self}\", 1)\n        self._append_history(\"{} = {}\".format(self, f\"{self}\".replace(str(self.num), str(old_num))))\n\n    @waveform_alterations\n    def deepcopy(self):\n        \"\"\"Return a deep copy of the object\n\n        This is just an alias for `copy`, which is deep anyway.\n\n        \"\"\"\n        W = self.copy()\n        W.__history_depth__ -= 1\n        W._append_history(f\"{W} = {self}.deepcopy()\")\n        return W\n\n    @waveform_alterations\n    def copy(self):\n        \"\"\"Return a (deep) copy of the object\n\n        Note that this also copies all members if the object is a subclass.  If you want a forgetful WaveformBase\n        object, you can simply use the copy constructor.\n\n        \"\"\"\n        W = type(self)()\n        state = copy.deepcopy(self.__dict__)\n        state.pop(\"_WaveformBase__num\")\n        W.__dict__.update(state)\n        W.__history_depth__ -= 1\n        W._append_history(f\"{W} = {self}.copy()\")\n        return W\n\n    @waveform_alterations\n    def copy_without_data(self):\n        \"\"\"Return a copy of the object, with empty `t`, `frame`, and `data` fields\n\n        Note that subclasses may override this to set some related data members.  For example,\n        `WaveformModes.copy_without_data` sets the `ell_min` and `ell_max` fields appropriately.  If you wish to only\n        skip `t`, `frame`, and `data`, you can simply use `WaveformBase.copy_without_data(W)`.  The latter is useful\n        if, for example, you will only be making changes to those three fields, and want everything else preserved.\n\n        Also note that some slicing operations can achieve similar -- but different -- goals.  For example,\n        `w = w[:, :0]` will simply empty `data` and `ells`, without affecting the `time` and `frame`.\n\n        \"\"\"\n        W = type(self)()\n        state = copy.deepcopy(self.__dict__)\n        state.pop(\"_WaveformBase__num\")\n        state.pop(\"t\")\n        state.pop(\"frame\")\n        state.pop(\"data\")\n        W.__dict__.update(state)\n        W.__history_depth__ -= 1\n        W._append_history(f\"{W} = {self}.copy_without_data()\")\n        return W\n\n    def _allclose(\n        self, other, report_all=True, rtol=1e-10, atol=1e-10, compare_history_beginnings=False, exceptions=[]\n    ):\n        \"\"\"Check that member data in two waveforms are the same\n\n        For data sets (time, modes, etc.), the numpy function `np.allclose` is used, with the input tolerances.  See\n        that function's documentation for more details.  The `*__num` datum is always ignored.  By default,\n        the `history` is ignored, though this can be partially overridden -- in which case, the shortest subset of\n        the histories is compared for exact equality.  This is probably only appropriate for the case where one\n        waveform was created from the other.\n\n        Parameters\n        ----------\n        other : object\n            Another object subclassing WaveformBase to compare\n        report_all: bool, optional\n            Wait until all attributes have been checked (and reported on) before returning the verdict\n        rtol : float, optional\n            Relative tolerance to which to compare arrays (see np.allclose), defaults to 1e-10\n        atol : float, optional\n            Absolute tolerance to which to compare arrays (see np.allclose), defaults to 1e-10\n        compare_history_beginnings: bool, optional\n            Compare the shortest common part of the `history` fields for equality, defaults to False\n        exceptions : list, optional\n            Don't compare elements in this list, corresponding to keys in the object's `__dict__`, defaults to []\n\n        \"\"\"\n        equality = True\n        if not type(self) == type(other):  # not isinstance(other, self.__class__):\n            warnings.warn(\"\\n  (type(self)={}) != (type(other)={})\".format(type(self), type(other)))\n            equality = False\n            if not report_all and not equality:\n                return False\n        for key, val in self.__dict__.items():\n            if key.endswith(\"__num\") or key in exceptions:\n                continue\n            elif key == \"history\":\n                if compare_history_beginnings:\n                    min_length = min(len(self.history), len(other.history))\n                    if self.history[:min_length] != other.history[:min_length]:\n                        warnings.warn(\"\\n  `history` fields differ\")\n                        equality = False\n            elif key == \"version_hist\":\n                if self.version_hist != other.version_hist:\n                    warnings.warn(\"\\n  `version_hist` fields differ\")\n                    equality = False\n            elif isinstance(val, np.ndarray):\n                if val.dtype == np.quaternion:\n                    if not np.allclose(\n                        quaternion.as_float_array(val), quaternion.as_float_array(other.__dict__[key]), rtol, atol\n                    ):\n                        warnings.warn(f\"\\n  `{key}` fields differ\")\n                        equality = False\n                elif not np.allclose(val, other.__dict__[key], rtol, atol):\n                    warnings.warn(f\"\\n  `{key}` fields differ\")\n                    equality = False\n            else:\n                if not val == other.__dict__[key]:\n                    warnings.warn(\n                        \"\\n  (self.{0}={1}) != (other.{0}={2}) fields differ\".format(key, val, other.__dict__[key])\n                    )\n                    equality = False\n            if not report_all and not equality:\n                return False\n        return equality\n\n    # Slicing\n    @waveform_alterations\n    def __getitem__(self, key):\n        \"\"\"Extract subsets of the data efficiently\n\n        See the docstring of the WaveformBase class for examples.\n\n        \"\"\"\n        W = WaveformBase.copy_without_data(self)\n\n        # Remove trivial tuple structure first\n        if isinstance(key, tuple) and len(key) == 1:\n            key = key[0]\n\n        # Now figure out which type of return is desired\n        if isinstance(key, tuple) and 2 <= len(key) <= self.n_data_sets:\n            # Return a subset of the data from a subset of times\n            W.t = self.t[key[0]]\n            W.frame = self.frame[key[0]]\n            W.data = self.data[key]\n        elif isinstance(key, slice) or isinstance(key, int):\n            # Return complete data from a subset of times (key is slice), or\n            # return complete data from a single instant in time (key is int)\n            W.t = self.t[key]\n            W.frame = self.frame[key]\n            W.data = self.data[key]\n        else:\n            raise ValueError(\"Could not understand input `{}` (of type `{}`) \".format(key, type(key)))\n\n        W.__history_depth__ -= 1\n        W._append_history(f\"{W} = {self}[{key}]\")\n\n        return W\n\n    @waveform_alterations\n    def interpolate(self, tprime):\n        \"\"\"Interpolate the frame and data onto the new set of time steps\n\n        Note that only `t`, `frame`, and `data` are changed in this function.  If there is a corresponding data set\n        in a subclass, for example, the subclass must override this function to set that data set -- though this\n        function should probably be called to handle the ugly stuff.\n\n        \"\"\"\n        # Copy the information fields, but not the data\n        W = WaveformBase.copy_without_data(self)\n\n        W.t = np.copy(tprime)\n        W.frame = quaternion.squad(self.frame, self.t, W.t)\n        W.data = np.empty((W.n_times,) + self.data.shape[1:], dtype=self.data.dtype)\n        W.data_2d[:] = CubicSpline(self.t, self.data_2d.view(float))(W.t).view(complex)\n        W.__history_depth__ -= 1\n        W._append_history(f\"{W} = {self}.interpolate({tprime})\")\n        return W\n\n    @waveform_alterations\n    def SI_units(self, current_unit_mass_in_solar_masses, distance_from_source_in_megaparsecs=100):\n        \"\"\"Assuming current quantities are in geometric units, convert to SI units\n\n        This function assumes that the `dataType`, `r_is_scaled_out`, and `m_is_scaled_out` attributes are correct,\n        then scales the amplitude and time data appropriately so that the data correspond to data that could be\n        observed from a source with the given total mass at the given distance.\n\n        Note that the curvature scalars will have units of s^-2, rather than the arguably more correct m^-2.  This\n        seems to be more standard in numerical relativity.  The result can be divided by `scipy.constants.c**2`\n        to give units of m^-2 if desired.\n\n        Parameters\n        ----------\n        current_unit_mass_in_solar_masses : float\n            Mass of the system in the data converted to solar masses\n        distance_from_source_in_megaparsecs : float, optional\n            Output will be waveform as observed from this distance, default=100 (Mpc)\n\n        \"\"\"\n        if not self.r_is_scaled_out:\n            warning = (\n                \"\\nTrying to convert to SI units, the radius is supposedly not scaled out.\\n\"\n                + \"This seems to suggest that the data may already be in some units...\"\n            )\n            warnings.warn(warning)\n        if not self.m_is_scaled_out:\n            warning = (\n                \"\\nTrying to convert to SI units, the mass is supposedly not scaled out.\\n\"\n                + \"This seems to suggest that the data may already be in some units...\"\n            )\n            warnings.warn(warning)\n\n        M_in_meters = current_unit_mass_in_solar_masses * m_sun_in_meters  # m\n        M_in_seconds = M_in_meters / speed_of_light  # s\n        R_in_meters = distance_from_source_in_megaparsecs * (1e6 * parsec_in_meters)  # m\n        R_over_M = R_in_meters / M_in_meters  # [dimensionless]\n\n        # The radius scaling `r_scaling` is the number of factors of the dimensionless quantity `R_over_M` required\n        # to keep the waveform asymptotically constant.  So, for example, h and Psi4 both have `r_scaling=1`.  The\n        # mass scaling `m_scaling` is the number of factors of `M_in_meters` required to make the waveform\n        # dimensionless, and does not account for the factors of mass in the radius scale.  The Newman-Penrose\n        # quantities are curvature quantities, so they have dimensions 1/m^2, and thus have `m_scaling=2`.\n        if self.r_is_scaled_out:\n            if self.m_is_scaled_out:\n                amplitude_scaling = (R_over_M ** -self.r_scaling) * (M_in_meters ** -self.m_scaling)\n            else:\n                amplitude_scaling = R_over_M ** -self.r_scaling\n        else:\n            if self.m_is_scaled_out:\n                amplitude_scaling = M_in_meters ** -self.m_scaling\n            else:\n                amplitude_scaling = 1.0\n\n        # Copy the information fields, but not the data\n        W = WaveformBase.copy_without_data(self)\n\n        if self.m_is_scaled_out:\n            W.t = M_in_seconds * self.t  # s\n        else:\n            W.t = np.copy(self.t)  # supposedly already in the appropriate units...\n        W.frame = np.copy(self.frame)\n        W.data = amplitude_scaling * self.data\n\n        W.m_is_scaled_out = False\n        W.r_is_scaled_out = False\n\n        W.__history_depth__ -= 1\n        W._append_history(\n            \"{} = {}.SI_units(current_unit_mass_in_solar_masses={}, \"\n            \"distance_from_source_in_megaparsecs={})\".format(\n                W, self, current_unit_mass_in_solar_masses, distance_from_source_in_megaparsecs\n            )\n        )\n\n        return W\n", "meta": {"hexsha": "58f3e44e42996bfc3dd046731d739697f0cd4722", "size": 45242, "ext": "py", "lang": "Python", "max_stars_repo_path": "scri/waveform_base.py", "max_stars_repo_name": "akhairna/scri", "max_stars_repo_head_hexsha": "3b7f307d19ef303914cef2fa088ee750ef8533c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scri/waveform_base.py", "max_issues_repo_name": "akhairna/scri", "max_issues_repo_head_hexsha": "3b7f307d19ef303914cef2fa088ee750ef8533c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scri/waveform_base.py", "max_forks_repo_name": "akhairna/scri", "max_forks_repo_head_hexsha": "3b7f307d19ef303914cef2fa088ee750ef8533c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.3767976989, "max_line_length": 120, "alphanum_fraction": 0.6174351267, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 10399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.31742625913050115, "lm_q1q2_score": 0.1964171627695396}}
{"text": "def selection_3():\n\n    # Library import\n    import numpy\n    import matplotlib\n    import matplotlib.pyplot   as plt\n    import matplotlib.gridspec as gridspec\n\n    # Library version\n    matplotlib_version = matplotlib.__version__\n    numpy_version      = numpy.__version__\n\n    # Histo binning\n    xBinning = numpy.linspace(0.0,1000.0,101,endpoint=True)\n\n    # Creating data sequence: middle of each bin\n    xData = numpy.array([5.0,15.0,25.0,35.0,45.0,55.0,65.0,75.0,85.0,95.0,105.0,115.0,125.0,135.0,145.0,155.0,165.0,175.0,185.0,195.0,205.0,215.0,225.0,235.0,245.0,255.0,265.0,275.0,285.0,295.0,305.0,315.0,325.0,335.0,345.0,355.0,365.0,375.0,385.0,395.0,405.0,415.0,425.0,435.0,445.0,455.0,465.0,475.0,485.0,495.0,505.0,515.0,525.0,535.0,545.0,555.0,565.0,575.0,585.0,595.0,605.0,615.0,625.0,635.0,645.0,655.0,665.0,675.0,685.0,695.0,705.0,715.0,725.0,735.0,745.0,755.0,765.0,775.0,785.0,795.0,805.0,815.0,825.0,835.0,845.0,855.0,865.0,875.0,885.0,895.0,905.0,915.0,925.0,935.0,945.0,955.0,965.0,975.0,985.0,995.0])\n\n    # Creating weights for histo: y4_PT_0\n    y4_PT_0_weights = numpy.array([0.0,0.0,5786.78210348,5281.0605314,4910.13784526,4512.19118199,4188.24845609,3792.452791,3452.23507887,3119.38536052,2778.24544917,2424.20944874,2150.00818076,1824.83545591,1649.19940452,1437.02338405,1233.75225605,1147.16242932,997.011956373,855.151676409,756.58675981,611.349082704,565.904821157,500.808776238,433.256333398,377.679280425,332.541918618,297.844607977,263.454317077,241.653305524,201.12186982,173.793872943,150.150532949,139.096502303,123.743685294,107.776768804,92.423951795,77.9923140064,74.9217266046,58.0336308945,58.3407106347,46.979600248,40.8384854443,39.6102564836,31.3197334986,27.6350676164,19.9586591119,17.5022101904,19.6516033717,13.510476568,9.51874594566,14.4316467886,11.3610833868,7.98346424475,4.60584510274,3.07056340183,4.29878936256,4.91290084292,4.29878936256,4.91290084292,4.29878936256,2.14939408128,3.07056340183,2.76350676164,1.53528140091,1.22822506073,1.22822506073,0.0,0.0,0.921169020548,0.614112680365,0.614112680365,0.921169020548,0.0,0.307056340183,0.0,0.307056340183,0.307056340183,0.307056340183,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_1\n    y4_PT_1_weights = numpy.array([0.0,0.0,0.912787033803,1.81916001616,0.913150150035,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_2\n    y4_PT_2_weights = numpy.array([0.0,0.0,9.03876615718,14.3000564189,12.8016704253,17.3227331768,16.5649496758,11.2956205368,5.27149226024,0.753445792208,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_3\n    y4_PT_3_weights = numpy.array([0.0,0.0,14.8559620956,23.5128565693,33.4114494002,35.0706872792,41.6621785534,41.2548950084,49.9204336313,37.5395562166,36.3045123613,32.5797585463,32.5970041875,21.8638411509,21.0363520176,13.2018247826,9.90207547543,4.94335946635,2.06216552844,1.64844503259,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_4\n    y4_PT_4_weights = numpy.array([0.0,0.0,8.06773951744,11.4694905207,15.7648365263,18.0599629707,19.6151602019,20.4277586991,19.985478039,19.5384174939,17.6129655561,16.5048709572,18.0592444849,16.2814248587,15.4683002735,16.2833668748,14.9508972563,15.6930059769,12.5830985217,12.7298289681,11.4718383762,8.06757718172,7.25323808485,5.77328345942,3.84893179711,3.035434441,1.92420736389,1.48061599318,0.518508403149,0.296202322267,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_5\n    y4_PT_5_weights = numpy.array([0.0,0.0,1.98520664078,2.76083543994,3.47885497709,4.36822048457,4.57526056873,4.72688710688,4.70792778793,5.27467278568,4.7451202221,5.19959472287,4.85838399774,4.93370812958,4.63180543214,5.12282718608,4.650557693,4.55613920432,4.34802181793,4.23457499093,4.10239390812,4.12158129106,3.38377030151,3.64899670958,3.42176996214,3.30863222186,3.04361887356,3.02438047631,2.8168308492,2.79897253913,2.60929172504,2.06127168048,1.38007397353,1.30416587786,0.907631031796,0.718306417629,0.585807245583,0.264645535112,0.22687985012,0.0944662320757,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_6\n    y4_PT_6_weights = numpy.array([0.0,0.0,0.880926044487,1.20383059022,1.20151975902,1.09497409521,1.31032601857,1.24538506363,1.69603313814,1.84686773395,1.48109284564,1.58894013274,1.43859064653,1.33080709099,1.1594854245,1.50232819976,1.28826365381,1.24532733034,1.33089706495,1.095309998,1.11736711428,1.09536248281,1.00963604355,0.773454398675,1.07269504316,1.05274631667,0.665614834344,0.881270194884,1.18044410868,0.793935471091,1.11647562229,1.00927614771,0.793924974129,0.880071291868,0.988191499975,0.966535517598,0.773048766072,0.600648461756,0.902253621911,0.580388350389,0.558027497014,0.708427668556,0.49457681076,0.407801125172,0.408065798571,0.343790800887,0.257956317898,0.214864039563,0.279192496774,0.17203800917,0.236497678407,0.0857799737648,0.0427792889203,0.0427693093086,0.0641474146084,0.107100053358,0.0,0.0641858334893,0.0212968213248,0.0215439423037,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_7\n    y4_PT_7_weights = numpy.array([0.0,0.0,0.0939633949117,0.126374698649,0.139312395938,0.137681978341,0.110036261618,0.130970489133,0.106837410644,0.0971007960125,0.0988517245135,0.0939811540823,0.0938545139077,0.102055573202,0.0712685263583,0.0824750345434,0.0808946569453,0.0890838348826,0.0745356165535,0.0550748658589,0.0745386969052,0.0680569453587,0.0648158809925,0.0518185254627,0.0404785877563,0.0567118213458,0.0388850715151,0.0583254227375,0.043744232072,0.0421359112833,0.029187709366,0.0403724413503,0.0517026036547,0.0615929529829,0.0436066535055,0.0502176855281,0.0404902176557,0.0583105238935,0.0599251311143,0.0647839144853,0.0356373120987,0.0356562656915,0.0534745288389,0.0550742686478,0.0372410752242,0.0421144745498,0.0615596034606,0.0437515243332,0.0583280944712,0.0631650639227,0.0550754316378,0.0615762625057,0.043736594057,0.04858245881,0.0631755308322,0.0583313005516,0.0453435003985,0.043755201896,0.0453509812527,0.0485824273778,0.0372615689929,0.0453472408256,0.0291467186855,0.0340059829685,0.0291682214265,0.0388617174199,0.0113483458093,0.0162010376275,0.0113408869576,0.0129638299874,0.0097293192267,0.00324230279333,0.00161444628819,0.00324402841894,0.0016198774512,0.006482166451,0.0,0.0,0.00162193248585,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_8\n    y4_PT_8_weights = numpy.array([0.0,0.0,0.019051396408,0.0255568357526,0.0170323594326,0.0127713462745,0.0169406513367,0.0127830172016,0.0105960224445,0.0191430599584,0.0149063018377,0.0106548047169,0.00638585020569,0.0106519348716,0.0149184961746,0.00424989905007,0.00635183190326,0.00426200095508,0.0042612147266,0.0105419653385,0.00637643216845,0.00426733639512,0.00635995589306,0.00632726281994,0.00638804852726,0.00213219485438,0.00212624023157,0.0042598315881,0.00213219485438,0.00841264032944,0.00850301317327,0.00213060680648,0.00425744172078,0.00213219485438,0.0,0.00213366819756,0.00426427500404,0.0,0.0,0.00426586305194,0.0,0.00213219485438,0.00212980498706,0.00213219485438,0.0,0.00212624023157,0.00425149489344,0.00639408110474,0.0,0.0042458554302,0.00213219485438,0.00426041290718,0.00426200095508,0.0,0.00426130493128,0.00212763673372,0.00851974001723,0.0,0.00426200095508,0.00425744172078,0.0,0.00213366819756,0.0,0.0084835634842,0.00213366819756,0.00637891001318,0.00639180594214,0.00212763673372,0.0,0.0,0.00425387585165,0.00212624023157,0.0106495450043,0.0,0.0,0.0042598315881,0.00212624023157,0.0,0.00423014979236,0.0,0.00851209043726,0.0,0.00212624023157,0.0,0.00425744172078,0.00212980498706,0.0,0.00212763673372,0.0,0.00213219485438,0.00213219485438,0.00213366819756,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_9\n    y4_PT_9_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_10\n    y4_PT_10_weights = numpy.array([0.0,0.0,79.0971291539,0.0,78.9085371523,0.0,78.97186254,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_11\n    y4_PT_11_weights = numpy.array([0.0,0.0,86.4011892197,310.922590593,155.352700617,172.742662894,190.060574561,103.726017745,51.7445000294,51.7772398266,69.099589811,34.5700267167,103.78097795,17.2983917156,51.8014200112,17.3004869473,17.2596400156,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_12\n    y4_PT_12_weights = numpy.array([0.0,0.0,176.541933258,95.5647890812,118.376517189,91.3858283688,64.4067086643,39.4564829255,33.2292406025,43.6029289416,29.0534246123,29.0616470511,35.2906492644,20.7724767543,18.7008953489,18.6877019411,16.6110745549,12.4623349111,18.6940433166,14.5383189276,10.3939732397,6.2198536684,4.15369618751,16.6027338285,2.0744012691,4.1530989788,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_13\n    y4_PT_13_weights = numpy.array([0.0,0.0,55.9532928362,43.1132315618,26.4785176646,15.1222611138,11.3375538375,8.30775980306,9.83549701357,9.83379014633,5.29433803914,6.80093740577,9.07770713151,3.77614745088,5.29255379392,3.78273459292,5.28628617742,6.04602416396,4.53634287784,2.2632385926,3.02597565867,3.02454553151,3.02161836798,4.53661005946,6.80269889276,2.26997184248,2.27025495486,0.753999271304,2.27222854855,0.755502679967,2.26702510688,2.26997184248,0.0,0.0,0.757751193074,2.26503558243,0.757151741301,0.0,0.0,0.756398443893,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_14\n    y4_PT_14_weights = numpy.array([0.0,0.0,23.7674343961,14.6405087644,8.91044047609,6.15365179535,3.81934144307,4.45546262709,3.18444951776,2.33413519734,2.54683244708,2.54656408778,1.69643848455,1.27313920749,1.69562878973,1.27251332436,1.90997688198,1.48488940862,1.48360041832,1.27332388486,2.12264325597,1.27222159184,1.06087854659,0.849298883466,0.848617885682,1.06072993902,1.48590080575,0.423367953954,0.84894482233,1.69853428409,1.2726247079,1.27345777595,0.849662755587,0.211760964354,0.42432337076,1.06204951651,1.06050803762,1.27395034511,1.27262413078,1.06099195003,0.848647318637,0.637179039051,0.637099108379,0.635627172068,0.0,0.0,0.0,0.0,0.212437806897,0.212281033127,0.849012056433,0.0,0.0,0.0,0.212060776514,0.0,0.0,0.0,0.211908013706,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_15\n    y4_PT_15_weights = numpy.array([0.0,0.0,1.48145933214,1.02773175815,0.913812555037,0.230039122125,0.571482938632,0.341581832162,0.113137203039,0.0,0.343819689084,0.114071224206,0.114864836383,0.0,0.0,0.0,0.113137203039,0.0,0.0,0.0,0.0,0.0,0.0,0.343041057412,0.0,0.0,0.0,0.0,0.0,0.115905759849,0.0,0.114914830493,0.0,0.0,0.114337238966,0.0,0.34382775551,0.0,0.0,0.11422918432,0.0,0.114144619814,0.0,0.0,0.0,0.0,0.0,0.0,0.229372179422,0.114122193378,0.0,0.0,0.0,0.0,0.113795547464,0.228137395816,0.0,0.0,0.115905759849,0.113137203039,0.113449045733,0.0,0.115222152443,0.114071224206,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_16\n    y4_PT_16_weights = numpy.array([0.0,0.0,0.162605602178,0.121873470418,0.0947348178819,0.06764164162,0.0270516297151,0.0135876322733,0.027095275389,0.0541827144219,0.0,0.0135400366601,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0135152253822,0.0135469606033,0.0,0.0,0.0,0.0,0.0135727680281,0.0,0.0,0.0,0.0,0.0,0.0135492849462,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0135550741481,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0135469606033,0.0,0.0,0.0,0.0,0.0,0.0,0.0135469606033,0.0,0.0,0.0,0.0,0.0135469606033,0.0,0.0,0.0135414774639,0.0135377527405,0.0135002716282,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating a new Canvas\n    fig   = plt.figure(figsize=(12,6),dpi=80)\n    frame = gridspec.GridSpec(1,1,right=0.7)\n    pad   = fig.add_subplot(frame[0])\n\n    # Creating a new Stack\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights+y4_PT_14_weights+y4_PT_15_weights+y4_PT_16_weights,\\\n             label=\"$bg\\_dip\\_1600\\_inf$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#e5e5e5\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights+y4_PT_14_weights+y4_PT_15_weights,\\\n             label=\"$bg\\_dip\\_1200\\_1600$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#f2f2f2\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights+y4_PT_14_weights,\\\n             label=\"$bg\\_dip\\_800\\_1200$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#ccc6aa\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights,\\\n             label=\"$bg\\_dip\\_600\\_800$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#ccc6aa\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights,\\\n             label=\"$bg\\_dip\\_400\\_600$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#c1bfa8\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights,\\\n             label=\"$bg\\_dip\\_200\\_400$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#bab5a3\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights,\\\n             label=\"$bg\\_dip\\_100\\_200$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#b2a596\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights,\\\n             label=\"$bg\\_dip\\_0\\_100$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#b7a39b\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights,\\\n             label=\"$bg\\_vbf\\_1600\\_inf$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#ad998c\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights,\\\n             label=\"$bg\\_vbf\\_1200\\_1600$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#9b8e82\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights,\\\n             label=\"$bg\\_vbf\\_800\\_1200$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#876656\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights,\\\n             label=\"$bg\\_vbf\\_600\\_800$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#afcec6\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights,\\\n             label=\"$bg\\_vbf\\_400\\_600$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#84c1a3\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights,\\\n             label=\"$bg\\_vbf\\_200\\_400$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#89a8a0\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights,\\\n             label=\"$bg\\_vbf\\_100\\_200$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#829e8c\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights,\\\n             label=\"$bg\\_vbf\\_0\\_100$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#adbcc6\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights,\\\n             label=\"$signal$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#7a8e99\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n\n    # Axis\n    plt.rc('text',usetex=False)\n    plt.xlabel(r\"p_{T} [ j_{2} ]   ( GeV ) \",\\\n               fontsize=16,color=\"black\")\n    plt.ylabel(r\"$\\mathrm{Events}$ $(\\mathcal{L}_{\\mathrm{int}} = 3000.0\\ \\mathrm{fb}^{-1})$ \",\\\n               fontsize=16,color=\"black\")\n\n    # Boundary of y-axis\n    ymax=(y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights+y4_PT_14_weights+y4_PT_15_weights+y4_PT_16_weights).max()*1.1\n    #ymin=0 # linear scale\n    ymin=min([x for x in (y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights+y4_PT_14_weights+y4_PT_15_weights+y4_PT_16_weights) if x])/100. # log scale\n    plt.gca().set_ylim(ymin,ymax)\n\n    # Log/Linear scale for X-axis\n    plt.gca().set_xscale(\"linear\")\n    #plt.gca().set_xscale(\"log\",nonposx=\"clip\")\n\n    # Log/Linear scale for Y-axis\n    #plt.gca().set_yscale(\"linear\")\n    plt.gca().set_yscale(\"log\",nonposy=\"clip\")\n\n    # Legend\n    plt.legend(bbox_to_anchor=(1.05,1), loc=2, borderaxespad=0.)\n\n    # Saving the image\n    plt.savefig('../../HTML/MadAnalysis5job_0/selection_3.png')\n    plt.savefig('../../PDF/MadAnalysis5job_0/selection_3.png')\n    plt.savefig('../../DVI/MadAnalysis5job_0/selection_3.eps')\n\n# Running!\nif __name__ == '__main__':\n    selection_3()\n", "meta": {"hexsha": "5d96b95cc1dd5d54e484e68c397cbc8f8669ff9f", "size": 24260, "ext": "py", "lang": "Python", "max_stars_repo_path": "optimization/second_sdEta_mjj_optimization/lumi_and_kin_plots/four_cuts_lum3000/Output/Histos/MadAnalysis5job_0/selection_3.py", "max_stars_repo_name": "sheride/axion_pheno", "max_stars_repo_head_hexsha": "7d3fc08f5ae5b17a3500eba19a2e43f87f076ce5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "optimization/second_sdEta_mjj_optimization/lumi_and_kin_plots/four_cuts_lum3000/Output/Histos/MadAnalysis5job_0/selection_3.py", "max_issues_repo_name": "sheride/axion_pheno", "max_issues_repo_head_hexsha": "7d3fc08f5ae5b17a3500eba19a2e43f87f076ce5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optimization/second_sdEta_mjj_optimization/lumi_and_kin_plots/four_cuts_lum3000/Output/Histos/MadAnalysis5job_0/selection_3.py", "max_forks_repo_name": "sheride/axion_pheno", "max_forks_repo_head_hexsha": "7d3fc08f5ae5b17a3500eba19a2e43f87f076ce5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 125.0515463918, "max_line_length": 1326, "alphanum_fraction": 0.7228771641, "include": true, "reason": "import numpy", "num_tokens": 12289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432182679957, "lm_q2_score": 0.27202455699569283, "lm_q1q2_score": 0.19633187921399717}}
{"text": "import numpy as np\nimport scipy.constants as const\nfrom astropy.io import fits\nimport scipy.interpolate as si\nimport glob\nfrom ppxf import ppxf_util as P\nimport glob\nimport os\n\n\nclass Spectrum(object):\n    \"\"\"\n\n    UPDATE THE DOCSTRING! A stripped down version of specTools in order to package this all together nicely\n    Original Author: Ryan Houghton (20/4/11)\n    Updated: Sam Vaughan (Early 2018)\n\n    Purpose: A spectrum object to aid manipulation of wavelength/frequency and the associated\n             flux values\n\n    Inputs:\n    This class MUST be initalised with EITHER\n       lamspec - a NLAMxNSPEC numpy array with [:,0] being the wavelength array (AA) and [:,1:] being\n                 the associated flux values (erg/s/cm**2/AA)\n       muspec  - a NLAMxNSPEC numpy array with [:,0] being the frequency array (GHz) and [:,1:] being\n                 the associated flux values (GJy = 1e-14 erg/s/cm**2/Hz)\n\n    NOTE: 2xN seems a funny way to order the indicies but in numpy, this IS the efficient\n    way to order the memory elements\n\n    Definitions:\n    Once you have initalised the class with either lamspec or muspec, you will find available\n    the following variables (no matter if you initalised with lamspec or muspec):\n       lam  - the wavelength array (AA)\n       flam - the associated flux (erg/s/cm**2/AA)\n       mu   - the frequency array (GHz)\n       fmu  - the associated flux (GJy = 1e-14 erg/s/cm**2/Hz)\n\n    Functions:\n       calcABmag  - given a filter (spectrum class), return a magnitude on the AB system\n       calcSTmag  - as above but for the ST system\n       calcVEGAmag- as above but for the VEGA system; you must also supply a vega *spectrum*\n\n    Notes:\n       - You can define more than one flam/fmu for each lam/mu\n       - Filters used in the functions should also be *spectrum* classes\n       - Filters don't need to be sorted in mu or lam\n    \"\"\"\n\n    global c, pc, d_sun\n\n    def __init__(self, lam=None, lamspec=None, errlamspec=None, age=None, Z=None, wavesyst=None, userdict=None):\n\n        \"\"\"\n        Inputs:\n        -------\n           lam     - the 1D array of wavelengths (becomes self.lam)\n           lamspec - the (1D, 2D or 3D) array of fluxes on the specified lambda grid (becomes self.flam)\n           errlamspec - standard deviation for pixels in lamspec (becomes self.eflam)\n           age     - the 1D array of ages (Gyr) for the spectra\n           Z       - the 1D array of metallicities for the spectra\n           wavesyst - you MUST specify if the wavelengths are in the AIR or VAC system.\n           userdict- add extra user-defined tags to the spectrum, such as airmass, water vapour etc.\n\n        Notes:\n        ------\n        There are 3 ways to inialise a spectrum class:\n            1. With a 1D lam/mu and a 1D spectrum (single spec mode).\n                 - Magnitudes are returned as single values\n            2. With a 1D lam/mu and a 2D spectrum array (NSPECxN{LAM/MU}) (multispec mode)\n                 - In this case, you may specify AGE where len(age)=NSPEC.\n                 - Magnitudes are returned as 1D arrays with NSPEC=len(age) elements\n            #3. With a 1D lam/mu and a 3D spectrum array (NZxNAGExN{LAM/MU}) (multispec mode)\n            #     - In this case, you can specify AGE and Z.\n            #     - Magnitudes will be returned as 2D arrays with NZxNAGE elements\n        \"\"\"\n\n        # start defining spectrum parts\n        if lamspec is not None:\n            # check that lam has been given\n            if lam is None:\n                raise Exception(\"If you give lamspec, you must also give lam\")\n\n            # make sure 2d\n            flam = np.atleast_2d(lamspec)\n            # get array size\n            loc = flam.shape\n\n            # check for bigger arrays\n            # if len(loc)> 2: raise \"lamspec not understood\"\n\n            # get sizes\n            nlam = loc[1]\n            nspec = loc[0]\n\n            self.lam = lam\n            self.flam = np.atleast_2d(singleOrList2Array(flam))\n\n            if errlamspec is not None:\n                eflam = np.atleast_2d(errlamspec)\n                eloc = eflam.shape\n                self.eflam = eflam\n                # sanity check\n                assert np.all(loc == eloc), \"Flux and error arrays appear different sizes...\"\n            else:\n                self.eflam = None\n\n        # add age info\n        if age is not None:\n            self.age = singleOrList2Array(age)\n\n            checkDims(self.age, \"Age\", self.flam.shape[:-1])\n            self.logage = np.log10(self.age)\n        else:\n            self.age = None\n\n        # add metallicitiy\n        if Z is not None:\n\n            self.Z = singleOrList2Array(Z)\n            checkDims(self.Z, \"Z\", self.flam.shape[:-1])\n        else:\n            self.Z = None\n\n        # add VAC or AIR\n        if wavesyst is not None:\n            if (wavesyst == \"vac\" or wavesyst == \"VAC\" or wavesyst == \"Vac\"):\n                self.wavesyst = \"vac\"\n            elif (wavesyst == \"air\" or wavesyst == \"AIR\" or wavesyst == \"Air\"):\n                self.wavesyst = \"air\"\n            else:\n                raise ValueError(\"wavesyst not understood. Should be air or vac.\")\n        else:\n            warn.warn(\"You failed to specify if the wavelength is defined in AIR or VAC units.\")\n            self.wavesyst = None\n\n        # add user dictionary for extra info\n        if userdict is not None:\n            self.__userdict__ = userdict\n            keys = list(userdict.keys())\n            for key in keys:\n                setattr(self, key, singleOrList2Array(userdict[key]))\n        else:\n            self.__userdict__ = None\n\n\ndef checkDims(var, varname, parentShape):\n    assert (np.isscalar(var)) or (np.all(np.equal(np.array(var).shape, parentShape))), varname + \" dimensions not understood.\"\n\n\ndef singleOrList2Array(invar):\n    \"\"\"\n    If a single value, leave. If a list, convert to array. If array, leave as array.\n    But for size-1 arrays/lits, convert back to scalar.\n    \"\"\"\n\n    if isinstance(invar, list):\n        # convert to array unless size-1\n        rval = np.squeeze(np.array(invar))\n        if rval.size == 1:\n            rval = np.asscalar(rval)\n    elif isinstance(invar, np.ndarray):\n        # leave except if size-1\n        rval = np.squeeze(invar)\n        if rval.size == 1:\n            rval = np.asscalar(rval)\n    else:\n        # leave\n        rval = invar\n    # return\n    return rval\n\ndef load_varelem_CvD16ssps(varelem_template_location, imf='kroupa', verbose=True):\n\n    '''\n    Load the CvD16 spectra (response functions) with variable elemental abundances.\n\n    Arguments:\n        dirname (string): Base location of the stellar models directory\n        folder (string): The folder inside the base directory which contains the response functions\n        imf (string): The IMF of the response functions. Choices are 'kroupa' or 'salpeter'\n        verbose (bool): Print information to the console\n    Returns:\n        (dict): A dictionary of spectra. See below for example\n\n    Example:\n        The spectra are returned in a dictionary. The dictionary is indexed by a string referring to the name of the respone function,\n        e.g. 'Na+'. At each index, we have a Spectrum class which contains the response functions at various ages and metallicities\n\n        >>> spectra=load_varelem_CvD16ssps(dirname='/path/to/dir', folder='folder', imf='kroupa')\n        >>> spectra['Na+'] #Gives all RFs with [Na/H]=+0.3\n\n    '''\n\n    varelem_template_location = os.path.expanduser(varelem_template_location)\n\n    if imf in ['kroupa', 'krpa', 'Kroupa', 'Krpa']:\n        model_spectra = sorted(glob.glob('{}/atlas_ssp_*.krpa.s100'.format(varelem_template_location)))\n        imf_name = 'krpa'\n    elif imf in ['Salpeter', 'salpeter', 'salp', 'Salp']:\n        model_spectra = sorted(glob.glob('{}/atlas_ssp_*.salp.s100'.format(varelem_template_location)))\n        imf_name = 'salp'\n    else:\n        raise NameError('IMF type not understood')\n\n    data = np.genfromtxt(model_spectra[0])\n    lams = data[:, 0]\n\n    model_Zs_names = ['m1.5', 'm1.0', 'm0.5', 'p0.0', 'p0.2']\n    model_age_names = ['01', '03', '05', '09', '13']\n\n    model_elem_order = ['Solar', 'Na+', 'Na-', 'Ca+', 'Ca-', 'Fe+', 'Fe-', 'C+', 'C-', 'a/Fe+', 'N+', 'N-', 'as/Fe+', 'Ti+', 'Ti-', 'Mg+', 'Mg-', 'Si+', 'Si-', 'T+', 'T-', 'Cr+', 'Mn+', 'Ba+', 'Ba-', 'Ni+', 'Co+', 'Eu+', 'Sr+', 'K+', 'V+', 'Cu+', 'Na+0.6', 'Na+0.9']\n\n    Zs = [-1.5, -1.0, -0.5, 0.0, 0.2]\n    ages = [float(a) for a in model_age_names]\n\n    n_ages = len(model_age_names)\n    n_zs = len(model_Zs_names)\n    n_elems = len(model_elem_order)\n\n    templates = np.empty((n_elems, n_ages, n_zs, len(lams)))\n\n    for a, Z in enumerate(model_Zs_names):\n        for b, age in enumerate(model_age_names):\n\n            model = glob.glob('{}/atlas_ssp*t{}*{}*{}.s100'.format(varelem_template_location, age, Z, imf_name))[0]\n            if verbose:\n                print('Loading {}'.format(model))\n            data = np.genfromtxt(model)\n\n            for i, elem in enumerate(model_elem_order):\n                templates[i, b, a, :] = data[:, i + 1]\n\n    spectra = {}\n    for i, elem in enumerate(model_elem_order):\n\n        age_values = np.repeat(ages, n_zs).reshape(n_ages, n_zs)\n        Z_values = np.repeat(Zs, n_ages).reshape(n_zs, n_ages).T\n\n        spectra[elem] = Spectrum(lam=lams, lamspec=templates[i, :, :, :], age=age_values, Z=Z_values, wavesyst='vac', userdict={'elem': elem})\n\n    return spectra\n\n\n################################################################################################################################################################\ndef prepare_CvD_interpolator_twopartIMF(base_template_location, templates_lam_range, velscale, verbose=True, instrumental_resolution=None):\n    \"\"\"\n    Set up the interpolator for the base SSP spectra using the log-rebinned templates we get from `prepare_CvD2_templates_twopartIMF`.\n\n    Arguments:\n        templates_lam_range (array-like): A 2 component vector with the start and stop wavelengths we want for the templates\n        velscale (float): The velocity difference between two adjacent pixels in the log-rebinned spectrum. Use the same value\n        for the templates as you *measure* from the spectrum!\n        verbose (bool): Print information to the consolse\n\n    Returns:\n        (tuple): A two component tuple containing:\n            * interp: the interpolate object. Axes are wavelength, age, Z, imf_x1 and imf_x2\n            * logLam_template: the log-rebinned wavelength array of the templates\n    \"\"\"\n    templates, logLam_template = prepare_CvD2_templates_twopartIMF(base_template_location, templates_lam_range, velscale, verbose=verbose, instrumental_resolution=instrumental_resolution)\n\n    nimfs = 16\n    ages = [1., 3., 5., 7., 9., 11.0, 13.5]\n    Zs = [-1.5, -1.0, -0.5, 0.0, 0.2]\n    n_imfs = 16\n    imfs_X1 = 0.5 + np.arange(n_imfs) / 5.0\n    imfs_X2 = 0.5 + np.arange(n_imfs) / 5.0\n\n    linear_interp = si.RegularGridInterpolator(((logLam_template, ages, Zs, imfs_X1, imfs_X2)), templates, bounds_error=False, fill_value=None)\n\n    return linear_interp, logLam_template\n\n################################################################################################################################################################\n\ndef prepare_CvD2_templates_twopartIMF(template_location, templates_lam_range, velscale, verbose=True, instrumental_resolution=None):\n\n    '''\n    Load the CvD16 base spectra, those that vary age, [Z/H] and the IMF. The templates are log-rebinned to have a uniform wavelength\n    spacing in **log** wavelength, to ensure the difference in velocity between two adjacent pixels is the same, regardless of wavelength. \n\n    They are returned in an array of shape (n_ages, n_Zs, n_pixels).\n\n    Arguments: \n        templates_lam_range (array-like): A 2 component vector with the start and stop wavelengths we want for the templates\n        velscale (float): The velocity difference between two adjacent pixels in the log-rebinned spectrum. Use the same value\n        for the templates as you *measure* from the spectrum!\n        verbose (bool): Print information to the consolse\n    Returns:\n        (tuple): A two component tuple:\n            * templates (array): An array of templates with shape (N_wavelength, N_ages, N_metallicities, N_imf_x1, N_imf_x2)\n            * logLam_template (array): The log-rebinned wavelength array of the templates\n    '''\n    \n    template_glob=os.path.expanduser(f'{template_location}/VCJ_v8_mcut0.08_t*')\n\n    vcj_models=sorted(glob.glob(template_glob))\n    models=np.genfromtxt(vcj_models[-1])\n\n    temp_lamdas=models[:, 0]\n\n    n_ages=7\n    n_zs=5\n    n_imfs=16\n\n    \n\n\n    Zs=['m1.5', 'm1.0', 'm0.5', 'p0.0', 'p0.2']\n    ages=['01.0', '03.0', '05.0', '07.0', '09.0', '11.0', '13.5']\n    imfs_X1=0.5+np.arange(n_imfs)/5.0\n    imfs_X2=0.5+np.arange(n_imfs)/5.0\n\n    t_mask = ((temp_lamdas > templates_lam_range[0]) & (temp_lamdas <templates_lam_range[1]))\n\n\n\n    y=models[t_mask, 1]\n    x=temp_lamdas[t_mask]\n    #Make a new lamda array, carrying on the delta lamdas of high resolution bit\n    new_x=temp_lamdas[t_mask][0]+0.9*(np.arange(np.ceil((temp_lamdas[t_mask][-1]-temp_lamdas[t_mask][0])/0.9))+1)\n    interp=si.interp1d(x, y, fill_value='extrapolate')\n    out=interp(new_x)\n\n    sspNew, logLam_template, template_velscale = P.log_rebin(templates_lam_range, out, velscale=velscale)\n    templates=np.empty((len(sspNew), n_ages, n_zs, len(imfs_X1), len(imfs_X2)))\n\n    #Resolution of the templates in km/s\n\n    for a, Z in enumerate(Zs):    \n        for b, age in enumerate(ages):\n            model=glob.glob(os.path.expanduser(f'{template_location}/VCJ_v8_mcut0.08_t{age}*{Z}.ssp.imf_varydoublex.s100'))[0]\n            print('Loading {}'.format(model))\n            data=np.genfromtxt(model)\n\n            for c, counter1 in enumerate(imfs_X1):\n                for d, counter2 in enumerate(imfs_X2):\n                \n                    #Interpolate templates onto a uniform wavelength grid and then log-rebin\n                    y=data[:, c*n_imfs+d+1][t_mask]   \n                    x=temp_lamdas[t_mask]\n                    \n                    #Make a new lamda array, carrying on the delta lamdas of high resolution bit\n                    new_x=temp_lamdas[t_mask][0]+0.9*(np.arange(np.ceil((temp_lamdas[t_mask][-1]-temp_lamdas[t_mask][0])/0.9))+1)\n\n                    interp=si.interp1d(x, y, fill_value='extrapolate')\n                    out=interp(new_x)\n\n                    #log rebin them\n                    sspNew, logLam_template, template_velscale = P.log_rebin(templates_lam_range, out, velscale=velscale)\n                    if instrumental_resolution is not None:\n                        sspNew = P.gaussian_filter1d(sspNew, instrumental_resolution/velscale)\n\n                    templates[:, b, a, c, d]=sspNew#/np.median(sspNew)\n\n    return templates, logLam_template\n\n################################################################################################################################################################\n\n\n################################################################################################################################################################\ndef prepare_CvD_correction_interpolators(varelem_template_location, templates_lam_range, velscale, elements, verbose=True, element_imf='kroupa', instrumental_resolution=None):\n\n    \"\"\"\n    Set up the interpolator for the response functions using the log-rebinned templates we get from `prepare_CvD2_element_templates`.\n    The response functions allow for variation in a general set of elements (Fe, Ca, Mg, etc), a set of elements which can only be \n    positive (Mn, K, V, etc), and Sodium, which can be extended from -0.3 dex to +1.0 dex. We have to treat each of these cases \n    separately, so we end up with three different interpolation objects. You can also vary the effective temperature of the isochrone, \n    but this is now deprecated in V2. \n\n    Arguments:\n        templates_lam_range (array-like): A 2 component vector with the start and stop wavelengths we want for the templates\n        velscale (float): The velocity difference between two adjacent pixels in the log-rebinned spectrum. Use the same value\n        for the templates as you *measure* from the spectrum!\n        elements (array): This is an array of integers corresponding to the elements we want to vary in the interpolators. The\n        numbers come from the headings in the SSP RF file. Na is element 1, Ca is element 2, etc. TODO: Improve this! Make it clearer\n\n        verbose (bool): Print information to the consolse\n\n    Returns:\n        (tuple): A two component tuple containing:\n            * correction_interps: A tuple of the interpolators. The order is [general_interp, na_interp, positive_only_interp, T_interp). TODO explain this more\n            * logLam_template: The log-rebinned wavelength array of the templates\n    \"\"\"\n\n    all_corrections, logLam_template=prepare_CvD2_element_templates(varelem_template_location, templates_lam_range, velscale, elements, verbose=verbose, element_imf=element_imf, instrumental_resolution=instrumental_resolution)\n\n    general_templates, na_templates, carbon_templates, positive_only_templates, T_templates=all_corrections\n\n    positive_only_elems, Na_elem, Carbon_elem, normal_elems=elements\n\n\n    #It's not clear if the last value here should be 13.5 or 13\n    ages=np.array([  1.,   3.,   5.,   9.,  13.0])\n    Zs=[-1.5, -1.0, -0.5, 0.0, 0.2]\n\n\n    elem_steps=[-0.45, -0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.3, 0.45]\n    Na_elem_steps=[-0.45, -0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n    C_elem_steps = [-0.2, -0.15, -0.1, -0.05, 0.0, 0.05, 0.1, 0.15, 0.2]\n    positive_only_elem_steps=[0.0, 0.1, 0.2, 0.3, 0.45]\n    T_steps=[-50.0, -40.0, -30.0, -20.0, -10.0, 0.0, 10.0, 20.0, 30.0, 40.0, 50.0]\n    \n    na_interp=si.RegularGridInterpolator(((Na_elem_steps, ages, Zs, logLam_template)), na_templates, bounds_error=False, fill_value=None, method='linear')\n\n    carbon_interp = si.RegularGridInterpolator(((C_elem_steps, ages, Zs, logLam_template)), carbon_templates, bounds_error=False, fill_value=None, method='linear')\n\n    T_interp=si.RegularGridInterpolator(((T_steps, ages, Zs, logLam_template)), T_templates, bounds_error=False, fill_value=None, method='linear')\n\n    #If we only have one positive element to check, we need to do something different- can't have a dimension with only one element in RegularGridInterpolator apparently.\n    if len(positive_only_elems)>1:\n        positive_only_interp=si.RegularGridInterpolator(((np.arange(len(positive_only_elems)), positive_only_elem_steps, ages, Zs, logLam_template)), positive_only_templates, bounds_error=False, fill_value=None, method='linear')\n    else:\n        positive_only_interp=si.RegularGridInterpolator((positive_only_elem_steps, ages, Zs, logLam_template), positive_only_templates[0, :], bounds_error=False, fill_value=None, method='linear')\n\n    if len(normal_elems)>1:\n        general_interp=si.RegularGridInterpolator(((np.arange(len(normal_elems)), elem_steps, ages, Zs, logLam_template)), general_templates, bounds_error=False, fill_value=None, method='linear')\n    else:\n        general_interp=si.RegularGridInterpolator((elem_steps, ages, Zs, logLam_template), general_templates[0, :], bounds_error=False, fill_value=None, method='linear')\n    \n\n    correction_interps=[general_interp, na_interp, carbon_interp, positive_only_interp, T_interp]\n\n    return correction_interps, logLam_template\n\n##########\n\ndef new_wavelength_array_high_resolution(wavelengths):\n    \"\"\"\n    The templates have different spacings in wavelength between the blue and red ends. This function makes a new set of wavelength values which ensures the same wavelength spacing throughout \n    \"\"\"\n\n    new_wavelength_array = wavelengths[0]+0.9*(np.arange(np.ceil((wavelengths[-1]-wavelengths[0])/0.9))+1)\n\n    return new_wavelength_array\n\ndef prepare_CvD2_element_templates(varelem_template_location, templates_lam_range, velscale, elements, verbose=True, element_imf='kroupa', instrumental_resolution=None):\n\n    var_elem_spectra=load_varelem_CvD16ssps(varelem_template_location, imf=element_imf)\n\n    ages=var_elem_spectra['Solar'].age[:, 0]\n    Zs=var_elem_spectra['Solar'].Z[0, :]\n    n_ages=len(ages)\n    n_Zs=len(Zs)\n\n    temp_lamdas=var_elem_spectra['Solar'].lam\n\n    t_mask = ((temp_lamdas > templates_lam_range[0]) & (temp_lamdas <templates_lam_range[1]))\n\n\n    positive_only_elems, Na_elem, Carbon_elem, normal_elems=elements\n\n    elem_steps=[-0.45, -0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.3, 0.45]\n    Na_elem_steps=[-0.45, -0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n    C_elem_steps = [-0.2, -0.15, -0.1, -0.05, 0.0, 0.05, 0.1, 0.15, 0.2]\n    positive_only_elem_steps=[0.0, 0.1, 0.2, 0.3, 0.45]\n    T_steps=[-50.0, -40.0, -30.0, -20.0, -10.0, 0.0, 10.0, 20.0, 30.0, 40.0, 50.0]\n\n    x=var_elem_spectra['Solar'].lam[t_mask]\n    y=var_elem_spectra['Solar'].flam[-1, -1, t_mask]\n    #Make a new lamda array, carrying on the delta lamdas of high resolution bit\n    new_x = new_wavelength_array_high_resolution(var_elem_spectra['Solar'].lam[t_mask])\n    interp=si.interp1d(x, y, fill_value='extrapolate')\n    data=interp(new_x)\n\n\n    sspNew, logLam_template, template_velscale = P.log_rebin(templates_lam_range, data, velscale=velscale)\n\n\n    positive_only_templates = np.empty((len(positive_only_elems), len(positive_only_elem_steps), n_ages, n_Zs, len(sspNew)))\n    general_templates = np.empty((len(normal_elems), len(elem_steps), n_ages, n_Zs, len(sspNew)))\n    \n    na_templates = np.empty((len(Na_elem_steps), n_ages, n_Zs, len(sspNew)))\n    carbon_templates = np.empty((len(C_elem_steps), n_ages, n_Zs, len(sspNew)))\n    T_templates = np.empty((len(T_steps), n_ages, n_Zs, len(sspNew)))\n\n    print('Making the Positive-Only Correction templates')\n    #Do the positve only correction templates:\n    for a, elem in enumerate(positive_only_elems):\n        print('\\t{}'.format(elem))\n        for b, step in enumerate(positive_only_elem_steps):\n            for c, _ in enumerate(ages):\n                for d, _ in enumerate(Zs):\n\n                    if step !=0.0:\n                        y=(var_elem_spectra[elem].flam[c, d, t_mask]/var_elem_spectra['Solar'].flam[c, d, t_mask] - 1.0)*((10**(step)-1.0)/(10**(0.3)-1.0))\n\n\n                    else:\n                        y=np.zeros_like(var_elem_spectra['Solar'].flam[c, d, t_mask])\n\n\n                    x=var_elem_spectra[elem].lam[t_mask]\n                    #Make a new lamda array, carrying on the delta lamdas of high resolution bit\n                    new_x=new_wavelength_array_high_resolution(x)\n                    interp=si.interp1d(x, y, fill_value='extrapolate')\n                    data=interp(new_x)\n                            \n                    sspNew, logLam_template, template_velscale = P.log_rebin(templates_lam_range, data, velscale=velscale)\n                    if instrumental_resolution is not None:\n                        sspNew = P.gaussian_filter1d(sspNew, instrumental_resolution/velscale)\n\n                    positive_only_templates[a, b, c, d, :]=sspNew\n\n\n    print('Making the General Correction templates')\n    #Do the general templates\n    for a, elem in enumerate(normal_elems):\n        \n        print('\\t{}'.format(elem))\n        for b, step in enumerate(elem_steps):\n            for c, _ in enumerate(ages):\n                for d, _ in enumerate(Zs):\n\n                    if step>0.0:\n                        e='{}+'.format(elem)\n                        gen_step=step\n                    elif step<0.0:\n                        e='{}-'.format(elem)\n                        gen_step=np.abs(step)\n\n                    if step !=0.0:\n                        y=(var_elem_spectra[e].flam[c, d, t_mask]/var_elem_spectra['Solar'].flam[c, d, t_mask]-1)*((10**(gen_step)-1.0)/(10**(0.3)-1.0))\n                    else:\n                        y=np.zeros_like(var_elem_spectra['Solar'].flam[c, d, t_mask])\n\n                    x=var_elem_spectra[e].lam[t_mask]\n                    #Make a new lamda array, carrying on the delta lamdas of high resolution bit\n                    new_x=new_wavelength_array_high_resolution(x)\n                    interp=si.interp1d(x, y, fill_value='extrapolate')\n                    data=interp(new_x)\n\n                    #data=util.gaussian_filter1d(data, sigs/velscale)\n\n                    sspNew, logLam_template, template_velscale = P.log_rebin(templates_lam_range, data, velscale=velscale)\n                    if instrumental_resolution is not None:\n                        sspNew = P.gaussian_filter1d(sspNew, instrumental_resolution/velscale)\n\n                    general_templates[a, b, c, d, :]=sspNew\n\n    # Make the Carbon templates        \n    # Treat Carbon differently because it's templates are at +0.15 and -0.15 dex rather than +0.3 and -0.3 dex\n    print('Making the Carbon Correction template')\n    for b, step in enumerate(C_elem_steps):\n        for c, _ in enumerate(ages):\n            for d, _ in enumerate(Zs):\n\n                if step>0.0:\n                    e='{}+'.format(elem)\n                    gen_step=step\n                elif step<0.0:\n                    e='{}-'.format(elem)\n                    gen_step=np.abs(step)\n\n                if step !=0.0:\n                    y=(var_elem_spectra[e].flam[c, d, t_mask]/var_elem_spectra['Solar'].flam[c, d, t_mask]-1)*((10**(gen_step)-1.0)/(10**(0.15)-1.0))\n                else:\n                    y=np.zeros_like(var_elem_spectra['Solar'].flam[c, d, t_mask])\n\n                x=var_elem_spectra[e].lam[t_mask]\n                #Make a new lamda array, carrying on the delta lamdas of high resolution bit\n                new_x=new_wavelength_array_high_resolution(x)\n                interp=si.interp1d(x, y, fill_value='extrapolate')\n                data=interp(new_x)\n\n                #data=util.gaussian_filter1d(data, sigs/velscale)\n\n                sspNew, logLam_template, template_velscale = P.log_rebin(templates_lam_range, data, velscale=velscale)\n                if instrumental_resolution is not None:\n                        sspNew = P.gaussian_filter1d(sspNew, instrumental_resolution/velscale)\n\n                carbon_templates[b, c, d, :]=sspNew\n\n    #Do the Na templates:\n    print('Making the Na Correction template')\n    for a, step in enumerate(Na_elem_steps):\n        for b, _ in enumerate(ages):\n            for c, _ in enumerate(Zs):\n\n                if step <0.0:\n                    e='Na-'\n                    base_enhancement=0.3\n                    Na_step=np.abs(step)                    \n                elif 0.0<=step<0.45:\n                    e='Na+'\n                    base_enhancement=0.3\n                    Na_step=step\n                elif 0.45<=step<0.75:\n                    e='Na+0.6'\n                    base_enhancement=0.6\n                    Na_step=step\n                elif 0.75<=step<1.0:\n                    e='Na+0.9'\n                    base_enhancement=0.9\n                    Na_step=step\n                \n                if step !=0.0:\n                    y=(var_elem_spectra[e].flam[b, c, t_mask]/var_elem_spectra['Solar'].flam[b, c, t_mask]-1)*((10**(Na_step)-1.0)/(10**(base_enhancement)-1.0))\n\n                else:\n\n                    y=np.zeros_like(var_elem_spectra['Solar'].flam[b, c, t_mask])\n\n\n                x=var_elem_spectra[e].lam[t_mask]\n                #Make a new lamda array, carrying on the delta lamdas of high resolution bit\n                new_x=new_wavelength_array_high_resolution(x)\n                interp=si.interp1d(x, y, fill_value='extrapolate')\n                data=interp(new_x)\n\n                    \n                sspNew, logLam_template, template_velscale = P.log_rebin(templates_lam_range, data, velscale=velscale)\n                if instrumental_resolution is not None:\n                        sspNew = P.gaussian_filter1d(sspNew, instrumental_resolution/velscale)\n\n                na_templates[a, b, c, :]=sspNew\n\n\n    print('Making the Temperature Correction template')\n    for a, step in enumerate(T_steps):\n        for b, _ in enumerate(ages):\n            for c, _ in enumerate(Zs):\n\n                if step>0.0:\n                    e='T+'\n                    T_step=step\n                elif step<0.0:\n                    e='T-'\n                    T_step=np.abs(step)\n            \n                if step !=0.0:\n                    y=(var_elem_spectra[e].flam[b, c, t_mask]/var_elem_spectra['Solar'].flam[b, c, t_mask]-1)*(T_step/50.0)\n\n                else:\n\n                    y=np.zeros_like(var_elem_spectra['Solar'].flam[b, c, t_mask])\n\n\n                x=var_elem_spectra[e].lam[t_mask]\n                #Make a new lamda array, carrying on the delta lamdas of high resolution bit\n                new_x=new_wavelength_array_high_resolution(x)\n                interp=si.interp1d(x, y, fill_value='extrapolate')\n                data=interp(new_x)\n\n                    \n                sspNew, logLam_template, template_velscale = P.log_rebin(templates_lam_range, data, velscale=velscale)\n                if instrumental_resolution is not None:\n                        sspNew = P.gaussian_filter1d(sspNew, instrumental_resolution/velscale)\n\n                T_templates[a, b, c, :]=sspNew\n\n    return [general_templates, na_templates, carbon_templates, positive_only_templates, T_templates], logLam_template\n", "meta": {"hexsha": "40bf5e72cc69b007a85853b3816bb6d381f252af", "size": 29480, "ext": "py", "lang": "Python", "max_stars_repo_path": "pystaff/CvD_SSP_tools.py", "max_stars_repo_name": "WillCollier/PyStaff", "max_stars_repo_head_hexsha": "aa4d87738872f8168d6ed4c168c6b0be1cfa4846", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-06-01T01:44:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-08T09:03:24.000Z", "max_issues_repo_path": "pystaff/CvD_SSP_tools.py", "max_issues_repo_name": "WillCollier/PyStaff", "max_issues_repo_head_hexsha": "aa4d87738872f8168d6ed4c168c6b0be1cfa4846", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2018-05-25T15:44:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-24T01:40:49.000Z", "max_forks_repo_path": "pystaff/CvD_SSP_tools.py", "max_forks_repo_name": "WillCollier/PyStaff", "max_forks_repo_head_hexsha": "aa4d87738872f8168d6ed4c168c6b0be1cfa4846", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-08-10T10:15:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T08:38:35.000Z", "avg_line_length": 45.145482389, "max_line_length": 266, "alphanum_fraction": 0.6088873813, "include": true, "reason": "import numpy,import scipy,from astropy", "num_tokens": 7867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.33111975283019596, "lm_q1q2_score": 0.1962436180875042}}
{"text": "\"\"\"BLPose Train: Generator\n\nAuthor: Bo Lin (@linbo0518)\nDate: 2020-09-11\n\"\"\"\n\nimport json\nimport math\nimport numpy as np\n\n__all__ = [\"dict2json\", \"json2dict\", \"TargetGenerator\"]\n\n\ndef dict2json(dict_obj: dict, filename: str) -> None:\n    with open(filename, \"w\") as f:\n        json.dump(dict_obj, f, indent=2)\n\n\ndef json2dict(filename: str) -> dict:\n    dict_obj: dict\n    with open(filename, \"r\") as f:\n        dict_obj = json.load(f)\n    return dict_obj\n\n\ndef _gaussian_kernel(height, width, x, y, sigma=1.75):\n    grid_y, grid_x = np.mgrid[0:height, 0:width]\n    return np.exp(-((grid_x - x) ** 2 + (grid_y - y) ** 2) / (2.0 * sigma ** 2))\n\n\ndef _part_affinity_field(height, width, x1, y1, x2, y2, thickness=1):\n    pafmap = np.zeros((2, height, width), dtype=np.float32)\n    countmap = np.zeros_like(pafmap, dtype=np.uint)\n\n    limb_vec_x = x2 - x1\n    limb_vec_y = y2 - y1\n    limb_len = math.sqrt(limb_vec_x ** 2 + limb_vec_y ** 2)\n\n    if limb_len < 1e-7:\n        return pafmap, countmap\n\n    limb_unit_x = limb_vec_x / limb_len\n    limb_unit_y = limb_vec_y / limb_len\n\n    min_x = max(min(x1, x2) - thickness, 0)\n    max_x = min(max(x1, x2) + thickness, width)\n    min_y = max(min(y1, y2) - thickness, 0)\n    max_y = min(max(y1, y2) + thickness, height)\n\n    grid_y, grid_x = np.mgrid[min_y:max_y, min_x:max_x]\n    x_12 = grid_x - x1\n    y_12 = grid_y - y1\n\n    limb_width = np.abs(x_12 * limb_unit_y - y_12 * limb_unit_x)\n    limb_mask = limb_width < thickness\n\n    pafmap[:, grid_y, grid_x] = np.repeat(\n        limb_mask[np.newaxis, :, :], repeats=2, axis=0\n    )\n    pafmap[0, grid_y, grid_x] *= limb_unit_x\n    pafmap[1, grid_y, grid_x] *= limb_unit_y\n\n    limb_mask = (pafmap[0] != 0) | (pafmap[1] != 0)\n    countmap[:, limb_mask] += 1\n    return pafmap, countmap\n\n\nclass TargetGenerator:\n    def __init__(\n        self, n_keypoints, limbs, image_shape, stride, sigma=1.75, thickness=1\n    ):\n        self.n_keypoints = n_keypoints\n        self.n_limbs = len(limbs)\n        self.limbs = limbs\n        height, width, _ = image_shape\n        self.height = height // stride  # or round\n        self.width = width // stride  # or round\n        self.stride = stride\n        self.sigma = sigma\n        self.thickness = thickness\n\n    def __call__(self, annotation):\n        heatmap = np.zeros(\n            (self.n_keypoints + 1, self.height, self.width), dtype=np.float32\n        )\n        pafmap = np.zeros((self.n_limbs * 2, self.height, self.width), dtype=np.float32)\n        countmap = np.zeros_like(pafmap, dtype=np.uint)\n        for keypoints in annotation:\n            heat = self.gen_heatmap(keypoints)\n            heatmap = np.maximum(heatmap, heat)\n\n            paf, count = self.gen_pafmap(keypoints)\n            pafmap += paf\n            countmap += count\n\n        countmap[countmap == 0] = 1\n        pafmap /= countmap\n        heatmap[-1] = 1.0 - np.max(heatmap[:-1], axis=0)\n        return heatmap, pafmap\n\n    def gen_heatmap(self, keypoints):\n        heatmap = np.zeros(\n            (self.n_keypoints + 1, self.height, self.width), dtype=np.float32\n        )\n        for idx, keypoint in enumerate(keypoints):\n            x, y, v = keypoint\n            if v == 0:\n                continue\n            x, y = round(x / self.stride), round(y / self.stride)\n\n            heatmap[idx] = _gaussian_kernel(self.height, self.width, x, y, self.sigma)\n            heatmap[idx][heatmap[idx] > 1.0] = 1\n            heatmap[idx][heatmap[idx] < 0.01] = 0\n        return heatmap\n\n    def gen_pafmap(self, keypoints):\n        pafmap = np.zeros((self.n_limbs * 2, self.height, self.width), dtype=np.float32)\n        countmap = np.zeros_like(pafmap, dtype=np.uint)\n        for idx, limb in zip(range(0, self.n_limbs * 2, 2), self.limbs):\n            x1, y1, v1 = keypoints[limb[0]]\n            x2, y2, v2 = keypoints[limb[1]]\n            if v1 == 0 or v2 == 0:\n                continue\n            x1, y1 = round(x1 / self.stride), round(y1 / self.stride)\n            x2, y2 = round(x2 / self.stride), round(y2 / self.stride)\n\n            paf, count = _part_affinity_field(\n                self.height, self.width, x1, y1, x2, y2, self.thickness\n            )\n            pafmap[idx : idx + 2] = paf\n            countmap[idx : idx + 2] = count\n        return pafmap, countmap\n", "meta": {"hexsha": "43a0ccbc68139bb3de6f4c19d9505a67054dd8bc", "size": 4283, "ext": "py", "lang": "Python", "max_stars_repo_path": "blpose/train/generator.py", "max_stars_repo_name": "linbo0518/BLPose", "max_stars_repo_head_hexsha": "c431a3d458cc6358cd59261776a292e59b5db8b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "blpose/train/generator.py", "max_issues_repo_name": "linbo0518/BLPose", "max_issues_repo_head_hexsha": "c431a3d458cc6358cd59261776a292e59b5db8b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "blpose/train/generator.py", "max_forks_repo_name": "linbo0518/BLPose", "max_forks_repo_head_hexsha": "c431a3d458cc6358cd59261776a292e59b5db8b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2030075188, "max_line_length": 88, "alphanum_fraction": 0.5851038991, "include": true, "reason": "import numpy", "num_tokens": 1313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.1962436094109563}}
{"text": "\"\"\"A stochastic policy\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom context import flags\nimport env_info\nfrom utils import build_mlp, trainable_vars\n\n\nclass StochasticPolicy:\n    \"\"\"\n    Provides tensorflow interface to sampling-with-density and acting\n    according to it.\n    \"\"\"\n\n    def tf_sample_action_with_log_prob(self, obs_ns):\n        \"\"\"Return a sample from the policy, along with its log probability.\"\"\"\n        raise NotImplementedError  # return sample, log prob\n\n    def tf_greedy_action(self, obs_ns):\n        \"\"\"Return a sample from the greedy version of the policy.\"\"\"\n        raise NotImplementedError\n\n    def act(self, obs_ns):\n        \"\"\"Eager version of sampling an action\"\"\"\n        raise NotImplementedError\n\n    def greedy_act(self, obs_ns):\n        \"\"\"Eager version of sampling a greedy action\"\"\"\n        raise NotImplementedError\n\n    def expectation(self, obs_ns, fn):\n        \"\"\"\n        Given a function fn : (acs_na, log pi(acs_na)) -> reals\n        which maps a TF batch of actions and their likelihoods (taken according\n        to this stochastic policy), this returns a tensor which, when\n        differentiated wrt the policy parameters,\n        gives an estimator for the gradient of E[fn(A)], where A follows\n        this stochastic policy. The expectation is wrt the state distribution\n        an empirical sample of which should be given as the obs_ns argument\n        here.\n        \"\"\"\n        pass\n\n    def tf_report(self, reporter, obs_ns):\n        \"\"\"\n        Update a TF reporter with various statistics according to the given\n        sample of states.\n        \"\"\"\n        pass\n\n\nclass SquashedGaussianPolicy(StochasticPolicy):\n    \"\"\"\n    This stochastic policy implements a unimodal multivariate\n    Gaussian distribution with a diagonal covariance, with the both the mean\n    and covariance conditional on the state. This generates\n    a latent distribution, which then is then clipped for stability\n    and squashed into a compact [-1, 1] interval.\n    \"\"\"\n\n    def __init__(self, scope='sac/policy'):\n        \"\"\"\n        Generates a diagonal gaussian policy which keeps its log standard\n        deviations between the lower and upper bounds provided as arguments.\n        \"\"\"\n        self._scope = scope\n        self._obs_ph_ns = tf.placeholder(tf.float32, [None, env_info.ob_dim()])\n        self._acs_na, _ = self.tf_sample_action_with_log_prob(self._obs_ph_ns)\n        self._greedy_acs_na = self.tf_greedy_action(self._obs_ph_ns)\n        self.variables = trainable_vars(self._scope)\n\n    def _tf_mu_logstd(self, obs_ns):\n        unclipped_mu_logstd_n2a = build_mlp(\n            obs_ns, scope=self._scope,\n            output_size=(env_info.ac_dim() * 2),\n            n_layers=flags().sac.learner_depth,\n            size=flags().sac.learner_width,\n            activation=tf.nn.relu,\n            reuse=tf.AUTO_REUSE)\n        unclipped_mu_na = unclipped_mu_logstd_n2a[:, :env_info.ac_dim()]\n        unclipped_logstd_na = unclipped_mu_logstd_n2a[:, env_info.ac_dim():]\n\n        # What follows is black magic clipping for stability. These constants\n        # are luckily not specific to any enviornment, since we are going to\n        # squash outputs with tanh anyway. In turn, they're mostly determined\n        # by the range of tanh and the machine accuracy of floats. However,\n        # the logstd upper bound can be higher in this sense, but this was a\n        # magic constant taken from Tuomas' code that I do not have the\n        # confidence to mess with.\n        #\n        # TODO:\n        # Consider adding a policy regularization term to encourage staying in\n        # the active interval, e.g., add loss max(x - ub, 0) ** 2 or something.\n        logstd_na = tf.clip_by_value(unclipped_logstd_na, -20, 2)\n        mu_na = tf.clip_by_value(unclipped_mu_na, -5, 5)\n        return mu_na, logstd_na\n\n    @staticmethod\n    def _tf_sample(mu_na, logstd_na):\n        return tf.random_normal(tf.shape(mu_na)) * tf.exp(logstd_na) + mu_na\n\n    @staticmethod\n    def _tf_log_prob(x_na, mu_na, logstd_na):\n        diffs_na = x_na - mu_na\n        quadratic_n = tf.reduce_sum(\n            (diffs_na * tf.exp(-logstd_na)) ** 2, axis=1)\n\n        norm_factor_n = 2 * tf.reduce_sum(logstd_na, axis=1)\n        norm_factor_n += tf.to_float(env_info.ac_dim()) * np.log(2 * np.pi)\n        logprob_n = -0.5 * (quadratic_n + norm_factor_n)\n        return logprob_n\n\n    def tf_sample_action_with_log_prob(self, obs_ns):\n        return self._tf_sample_action_with_log_prob(\n            obs_ns, stop_gradient=True)\n\n    def _tf_sample_action_with_log_prob(self, obs_ns, stop_gradient=True):\n        # stop_gradient stops the contribution of the parameters to the\n        # sampling directly.\n        # when using the reparameterization trick, we *do* want the\n        # Jacobian effect of the policy parameters on the sampling, so\n        # we would have stop_gradient set to false. However for vanilla\n        # policy gradient we don't want this on because it would not\n        # correspond to performing a valid reinforce gradient estimation.\n\n        # latent mean, logstd, and log prob\n        mu_na, logstd_na = self._tf_mu_logstd(obs_ns)\n\n        # stop the gradient for computing the sample log prob, the\n        # parameters of the policy should only affect the log prob\n        # gradient by their influence on the policy distribution.\n        unbounded_sample_na = self._tf_sample(mu_na, logstd_na)\n        if stop_gradient:\n            unbounded_sample_na = tf.stop_gradient(unbounded_sample_na)\n\n        unbounded_logprob_n = self._tf_log_prob(\n            unbounded_sample_na, mu_na, logstd_na)\n        # squash with tanh and scale\n        logprob_n = self._scale_correction(\n            unbounded_sample_na, unbounded_logprob_n)\n        sample_na = self._scale(unbounded_sample_na)\n        return sample_na, logprob_n\n\n    def _scale(self, unbounded_acs_na):\n        return tf.tanh(unbounded_acs_na)\n\n    @staticmethod\n    def _scale_correction(unbounded_acs_na, unbounded_log_prob_n):\n        # chain rule to correct for density after modifications\n        log_prob_n = unbounded_log_prob_n\n        # original paper has 1-tanh**2, we use sech**2 for stability\n        # log(sech**2) == 2 * (log 2 - log (e^x + e^-x))\n        #              == 2 * (log 2 - |x| - log (1 + e^(-2|x|)))\n        abs_na = tf.abs(unbounded_acs_na)\n        log_prob_n -= 2 * tf.reduce_sum(\n            -1 * abs_na - tf.log1p(tf.exp(-2 * abs_na)) + np.log(2), axis=1)\n        # scale to unit action\n        log_prob_n -= np.log(0.5) * env_info.ac_dim()\n        space = env_info.ac_space()\n        # scale to box of action space\n        log_prob_n -= np.sum(np.log(space.high - space.low))\n        return log_prob_n\n\n    def tf_greedy_action(self, obs_ns):\n        mu_na, _ = self._tf_mu_logstd(obs_ns)\n        return self._scale(mu_na)\n\n    def act(self, obs_ns):\n        return tf.get_default_session().run(self._acs_na, feed_dict={\n            self._obs_ph_ns: obs_ns})\n\n    def greedy_act(self, obs_ns):\n        return tf.get_default_session().run(self._greedy_acs_na, feed_dict={\n            self._obs_ph_ns: obs_ns})\n\n    def tf_report(self, reporter, obs_ns):\n        mu_na, logstd_na = self._tf_mu_logstd(obs_ns)\n        reporter.stats('logstd', logstd_na)\n        reporter.stats('abs(mu)', tf.abs(mu_na))\n        acs_na, log_pi_n = self.tf_sample_action_with_log_prob(obs_ns)\n        reporter.stats('log pi', log_pi_n)\n        reporter.stats('abs(scaled sample acs)', tf.abs(acs_na))\n\n    def expectation(self, obs_ns, fn):\n        if flags().sac.reparameterization_trick:\n            # for the reparameterization trick, we do not stop the gradient\n            # when sampling from the latent distribution, intentionally.\n            # This way we can use gradient information of fn to improve the\n            # parameters\n            onpol_act_na, log_prob_acs_n = (\n                self._tf_sample_action_with_log_prob(\n                    obs_ns, stop_gradient=False))\n            return tf.reduce_mean(fn(onpol_act_na, log_prob_acs_n))\n        # else use the reinforce trick\n        onpol_act_na, log_prob_acs_n = self._tf_sample_action_with_log_prob(\n            obs_ns, stop_gradient=True)\n        return tf.reduce_mean(\n            log_prob_acs_n * tf.stop_gradient(\n                fn(onpol_act_na, log_prob_acs_n)))\n", "meta": {"hexsha": "c1b106bf30192ecff12ad2889cfa601de59eaec5", "size": 8361, "ext": "py", "lang": "Python", "max_stars_repo_path": "mve/sac/stochastic_policy.py", "max_stars_repo_name": "vlad17/mve", "max_stars_repo_head_hexsha": "19835bba87a2e5abc9bca653d011bf2eed68dd62", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-11-27T07:15:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T08:23:40.000Z", "max_issues_repo_path": "mve/sac/stochastic_policy.py", "max_issues_repo_name": "vlad17/mve", "max_issues_repo_head_hexsha": "19835bba87a2e5abc9bca653d011bf2eed68dd62", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mve/sac/stochastic_policy.py", "max_forks_repo_name": "vlad17/mve", "max_forks_repo_head_hexsha": "19835bba87a2e5abc9bca653d011bf2eed68dd62", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3910891089, "max_line_length": 79, "alphanum_fraction": 0.6592512857, "include": true, "reason": "import numpy", "num_tokens": 1998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.3311197462295937, "lm_q1q2_score": 0.1962436094109563}}
{"text": "#!/usr/bin/env python\n\n\"\"\"Convert astronomical positions between various coordinate systems.\n\nThe CnvObj code is getting ugly enough (I had to add ICRS<->ICRS2000 cases\nto handle the proper motion) that I'm wondering if it wouldn't be better\nto just hand code the converter as I did in the TCC. I hate all those\nif/then/else statements but it's probably more obvious what's going on\nthen this mess of magic stuff.\n\nI could also hand code all apparent->ICRS2000 and back routines\nand then ditch the entire catalog of methods. That might be cleanest.\n\nHistory:\n2002-08-07 ROwen    Beta release. Not yet well tested and I hope to clean up the code somewhat.\n2002-08-23 ROwen    Renamed from Convert; added coordConv method and stopped exporting CnvObj\n    (I'm giving up on CnvObj being useful for now, but may revive it later).\n    Added velocity handling and default date handling. Still beta; still not well tested.\n2002-12-23 ROwen    Bug fix: was not importing ICRSFromFK4 (thanks to pychecker);\n    Reorganized the code that computates method dictionaries to make it clearer;\n    Reduced the number of globals and made them self-hiding (initial underscore).\n2003-05-28 ROwen    Modified to handle opscore.RO.CoordSys 2003-05-09 (defaultDate->currDefaultDate).\n2005-01-21 ROwen    Bug fix: was miscomputing proper motion, due to using ICRS\n                    instead of ICRS2000 as the intermediate coordinate system.\n2005-04-26 ROwen    Bug fix: conversions requiring a App Topo<->Observed step were broken\n                    (thanks to Emmanouil Angelakis for the report).\n2007-04-24 ROwen    Converted from Numeric to numpy.\n2015-09-24 ROwen    Replace \"== None\" with \"is None\" to modernize the code.\n\"\"\"\n__all__ = [\"coordConv\"]\n\nimport numpy\nimport opscore.RO.CoordSys\nfrom opscore.RO.Astro import Tm\nfrom .AppGeoData import AppGeoData\nfrom .FK4FromICRS import fk4FromICRS\nfrom .FK5Prec import fk5Prec\nfrom .GalFromICRS import galFromICRS\nfrom .GeoFromICRS import geoFromICRS\nfrom .GeoFromTopo import geoFromTopo\nfrom .ICRSFromFK4 import icrsFromFK4\nfrom .ICRSFromFixedFK4 import icrsFromFixedFK4\nfrom .ICRSFromGal import icrsFromGal\nfrom .ICRSFromGeo import icrsFromGeo\nfrom .ObsFromTopo import obsFromTopo\nfrom .TopoFromGeo import topoFromGeo\nfrom .TopoFromObs import topoFromObs\n\n_CSysList = (opscore.RO.CoordSys.ICRS, opscore.RO.CoordSys.FK5, opscore.RO.CoordSys.FK4, opscore.RO.CoordSys.Galactic,\n    opscore.RO.CoordSys.Geocentric, opscore.RO.CoordSys.Topocentric, opscore.RO.CoordSys.Observed,\n    \"ICRS2000\")\n\nclass _CnvObj (object):\n    \"\"\"\n    An object that can convert between coordinate systems. To use,\n    create one of these objects and then call its \"coordConv\" method.\n\n    This code is a slightly awkward mix of functional and object-oriented programming.\n    Some data is stored as instance variables purely for ease of passing to functions,\n    but at present the caching serves no other purpose. In the future I hope to figure out an\n    interface whereby the user can save some data and repeatedly ask for conversions.\n    For instance one could create an object and then repeatedly ask for its current\n    observed position. Then CnvObj would start to feel more like a normal object.\n\n    Also, the method dictionary really should be saved as a class variable, but these\n    are relatively new to Python and clumsy, and I'm not yet sure I want to bother\n    (especially as it makes the code incompatible with older versions of Python).\n    \"\"\"\n    ZeroV = (0.0, 0.0, 0.0)\n\n    def __init__(self):\n        # Compute self.methDictDict, a dictionary of _CnvObj method dictionaries\n        # to convert between any two coordinate systems:\n        # - key: the \"from\" coordinate system\n        # - value: the method dictionary to use if starting from that coordinate system:\n        #   - key: a \"to\" coordinate system\n        #   - value: a tuple consisting of:\n        #     - the _CnvObj method to convert to \"to\" from \"from\" coordinate system\n        #     - the \"from\" coordinate system\n        # Each method dictionary gives a chain of methods that stretches from a given\n        # starting \"from\" coordinate system to all other coordinate systems\n\n        def addMethods(methDict, fromSys):\n            \"\"\"Recursively add all methods to a method dictionary\n            starting from a given \"from\" coordinate system.\n\n            For the first call, set methDict = {}\n\n            Inputs:\n            - methDict: the method dictionary\n            - a \"from\" coordinate system\n            \"\"\"\n            # if first execution, set entry for \"from\" = \"to\":\n            if methDict == {}:\n                methDict[fromSys] = (None, None)\n\n            # add an entry for each \"to\" coordinate system\n            for toSys in _CSysList:\n                if toSys == fromSys:\n                    continue\n                if toSys in methDict:\n                    continue\n                funcName = \"%sFrom%s\" % (toSys, fromSys)\n                if hasattr(_CnvObj, funcName):\n                    methDict[toSys] = (getattr(_CnvObj, funcName), fromSys)\n                    #print \"methDict[%s] = %r\" % (toSys, methDict[toSys])\n                    addMethods(methDict, toSys)\n\n        # pre-compute conversion dictionaries for every possible starting coordinate system\n        # (which so far includes all in opscore.RO.CoordSys except Physical and Mount)\n        methDictDict = {}\n        for _whatGiven in _CSysList:\n            # define method dictionary for coordsys _whatGiven given\n            methDict = {}\n            addMethods(methDict, _whatGiven)\n            assert len(methDict) == len(_CSysList), \"incomplete function list; check your conversion functions\"\n            methDictDict[_whatGiven] = methDict\n            #print \"methDictDict[%s] = %r\" % (_whatGiven, methDictDict[_whatGiven])\n\n        self.methDictDict = methDictDict\n\n    def coordConv(self, fromP, fromV, fromSys, fromDate, toSys, toDate, obsData=None, refCo=None):\n        \"\"\"Converts a position from one coordinate system to another.\n        See notes for the coordConv function below.\n        \"\"\"\n        # handle default dates\n        if fromDate is None:\n            fromDate = opscore.RO.CoordSys.getSysConst(fromSys).currDefaultDate()\n        if toDate is None:\n            toDate = opscore.RO.CoordSys.getSysConst(toSys).currDefaultDate()\n\n        self.fromDate = fromDate\n        self.toDate = toDate\n        self.obsData = obsData\n        if refCo:\n            self.refCo = refCo[:]\n        else:\n            refCo = None\n\n        # convert to ICRS from fromSys\n        icrsP, icrsV = self._getItem(\"ICRS2000\", self.methDictDict[fromSys], fromP, fromV)\n        #print \"Cnv.coordConv: icrsP=%s, icrsV=%s\" % (icrsP, icrsV)\n\n        # convert to toSys from ICRS\n        toP, toV = self._getItem(toSys, self.methDictDict[\"ICRS2000\"], icrsP, icrsV)\n        #print \"Cnv.coordConv: toP=%s, toV=%s\" % (toP, toV)\n        return (toP, toV)\n\n    def _getItem(self, csys, methDict, initP, initV):\n        \"\"\"Internal routine that returns the position initP and velocity initV\n        converted to the requested coordinate system.\n\n        To perform a full conversion, first convert fromP, fromV, fromSys, fromDate to ICRS\n        and then convert ICRS to toP, toV, toSys, toDate.\n\n        Before calling, set self.fromDate, self.toDate, self.obsData and self.refCo.\n\n        Inputs:\n        - csys      desired coordinate system\n        - methDict  _MethodDict[initSys], where initSys is the initial coordinate system\n                    (a dictionary of unbound coordinate conversion methods)\n        - initP     position in initSys\n        - initV     velocity in initSys\n        \"\"\"\n        #print \"Cnv._CnvObj._getItem: csys=%s; fromP=%s; fromV=%s\" % (csys, initP, initV)\n        func, nextSys = methDict[csys]\n        #print \"Cnv._CnvObj._getItem: nextSys=%s; func=%s\" % (nextSys, func)\n        if func:\n            toP, toV = func(self, *self._getItem(nextSys, methDict, initP, initV))\n            #print \"Cnv._CnvObj._getItem: toP=%s, toV=%s\" % (toP, toV)\n            return (toP, toV)\n        else:\n            #print \"Cnv._CnvObj._getItem: null conversion; toP, V = fromP, V\"\n            return (initP, initV)\n\n    # conversion functions\n    def ICRSFromICRS2000(self, fromP, fromV):\n        return (fromP + (numpy.asarray(fromV, dtype=float) * (self.toDate - 2000.0)), fromV)\n\n    def ICRS2000FromICRS(self, fromP, fromV):\n        return (fromP + (numpy.asarray(fromV, dtype=float) * (2000.0 - self.fromDate)), fromV)\n\n    def FK5FromICRS2000(self, fromP, fromV):\n        return fk5Prec(fromP, fromV, 2000.0, self.toDate)\n\n    def ICRS2000FromFK5(self, fromP, fromV):\n        return fk5Prec(fromP, fromV, self.fromDate, 2000.0)\n\n    def FK4FromICRS2000(self, fromP, fromV):\n        return fk4FromICRS (fromP, fromV, self.toDate)\n\n    def ICRS2000FromFK4(self, fromP, fromV):\n        if tuple(fromV) == (0.0, 0.0, 0.0):\n            return (icrsFromFixedFK4 (fromP, self.fromDate), _CnvObj.ZeroV)\n        else:\n            return icrsFromFK4(fromP, fromV, self.fromDate)\n\n    def GalacticFromICRS2000(self, fromP, fromV):\n        return galFromICRS (fromP, fromV, self.toDate)\n\n    def ICRS2000FromGalactic(self, fromP, fromV):\n        return icrsFromGal(fromP, fromV, self.fromDate)\n\n    def GeocentricFromICRS2000(self, fromP, fromV):\n        agData = AppGeoData(Tm.epJFromMJD(self.toDate))\n        return (geoFromICRS(fromP, fromV, agData), _CnvObj.ZeroV)\n\n    def ICRS2000FromGeocentric(self, fromP, dumV):\n        agData = AppGeoData(Tm.epJFromMJD(self.fromDate))\n        return (icrsFromGeo(fromP, agData), _CnvObj.ZeroV)\n\n    def TopocentricFromGeocentric(self, fromP, dumV):\n        if self.obsData is None:\n            raise ValueError(\"must specify obsData to cnvert to Topocentric from Geocentric\")\n        return (\n            topoFromGeo(fromP, Tm.lastFromUT1(self.toDate, self.obsData.longitude), self.obsData),\n            _CnvObj.ZeroV,\n        )\n\n    def GeocentricFromTopocentric(self, fromP, dumV):\n        if self.obsData is None:\n            raise ValueError(\"must specify obsData to convert to Geocentric from Topocentric\")\n        return (\n            geoFromTopo(fromP, Tm.lastFromUT1(self.fromDate, self.obsData.longitude), self.obsData),\n            _CnvObj.ZeroV,\n        )\n\n    def ObservedFromTopocentric(self, fromP, dumV):\n        if self.refCo is None:\n            raise ValueError(\"must specify refCo to convert to Observed from Topocentric\")\n        pos, tooLow = obsFromTopo(fromP, self.refCo)\n        return (pos, _CnvObj.ZeroV)\n\n    def TopocentricFromObserved(self, fromP, dumV):\n        if self.refCo is None:\n            raise ValueError(\"must specify refCo to convert to Topocentric from Observed\")\n        pos, tooLow = topoFromObs(fromP, self.refCo)\n        return (pos, _CnvObj.ZeroV)\n\n# create a singleton _CnvObj for the coordConv method to use\n_TheCnvObj = _CnvObj()\n\n# this is the only public function defined in this file\ndef coordConv(fromP, fromV, fromSys, fromDate, toSys, toDate, obsData=None, refCo=None):\n        \"\"\"Converts a position from one coordinate system to another.\n\n        Inputs:\n        - fromP(3)  cartesian position (au)\n        - fromV(3)  cartesian velocity (au/year); ignored if fromSys\n                    is Geocentric, Topocentric or Observed\n        - fromSys   coordinate system from which to convert;\n                    any of the entries in the table below; use opscore.RO.CoordSys constants.\n        - fromDate  date*\n        - toSys     coordinate system to which to convert (see fromSys)\n        - toDate    date*\n        - obsData   an opscore.RO.Astro.Cnv.ObserverData object; required if fromSys or toSys\n                    is Topocentric or Observed; ignored otherwise.\n        - refCo(2)  refraction coefficients; required if fromSys or toSys is Observed;\n                    ignored otherwise.\n\n        Returns:\n        - toP(3)    converted cartesian position (au)\n        - toV(3)    converted cartesian velocity (au/year)\n\n        *the units of date depend on the associated coordinate system:\n        coord sys   def date    date\n        ICRS        2000.0      Julian epoch of observation\n        FK5         2000.0      Julian epoch of equinox and observation\n        FK4         1950.0      Besselian epoch of equinox and observation\n        Galactic     now        Julian epoch of observation\n        Geocentric   now        UT1 (MJD)\n        Topocentric  now        UT1 (MJD)\n        Observed     now        UT1 (MJD)\n\n        **Setting fromV all zero means the object is fixed. This slighly affects\n        conversion to or from FK4, which has fictitious proper motion.\n\n        Error Conditions:\n        - If obsData or refCo are absent and are required, raises ValueError.\n\n        Details:\n        The conversion is performed in two stages:\n        - fromP/fromSys/fromDate -> ICRS\n        - ICRS -> toP/toSys/toDate\n\n        Each of these two stages is performed using the following graph:\n\n        FK5 ------\\\n        FK4 ------ ICRS --- Geocentric -*- Topocentric -**- Observed\n        Galactic--/\n\n        * obsData required\n        ** refCo required\n        \"\"\"\n        return _TheCnvObj.coordConv(fromP, fromV, fromSys, fromDate, toSys, toDate, obsData, refCo)\n", "meta": {"hexsha": "d1ac8fa0eaedc6eba44fbcf1817037a8d8184525", "size": 13281, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/opscore/RO/Astro/Cnv/CoordConv.py", "max_stars_repo_name": "sdss/opscore", "max_stars_repo_head_hexsha": "dd4f2b2ad525fe3dfe3565463de2c079a7e1232e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/opscore/RO/Astro/Cnv/CoordConv.py", "max_issues_repo_name": "sdss/opscore", "max_issues_repo_head_hexsha": "dd4f2b2ad525fe3dfe3565463de2c079a7e1232e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-17T21:08:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-17T21:08:14.000Z", "max_forks_repo_path": "python/opscore/RO/Astro/Cnv/CoordConv.py", "max_forks_repo_name": "sdss/opscore", "max_forks_repo_head_hexsha": "dd4f2b2ad525fe3dfe3565463de2c079a7e1232e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8682432432, "max_line_length": 118, "alphanum_fraction": 0.6598900685, "include": true, "reason": "import numpy", "num_tokens": 3509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.33111972642778714, "lm_q1q2_score": 0.1962436072042694}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nFile bounding_box.py\n@author:ZhengYuwei\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\nclass BoundingBox(object):\n    \"\"\" 定义BoundingBox类，描述bounding box的坐标及预定义一些操作 \"\"\"\n    \n    def __init__(self, w, h):\n        \"\"\" box参数初始化\n        :param w: box的宽\n        :param h: box的高\n        \"\"\"\n        self.w = w\n        self.h = h\n        self.area = w * h\n    \n    @staticmethod\n    def distance(box, boxes):\n        \"\"\"\n        计算一个box与一列表boxes的 1 - IoUs 的静态方法 （作为距离）\n        :param box: box对象\n        :param boxes：box对象列表\n        :return box对象与box对象列表中每一个元素的 1-IOU\n        \"\"\"\n        boxes_w, boxes_h, boxes_area = map(np.array, zip(*[(box.w, box.h, box.area) for box in boxes]))\n        intersections = np.minimum(box.w, boxes_w) * np.minimum(box.h, boxes_h)\n        dist_iou = 1 - intersections / (box.area + boxes_area - intersections)\n        return dist_iou\n    \n    @staticmethod\n    def mean(boxes):\n        \"\"\"\n        计算一个box对象列表的均值中心点\n        :param boxes: box对象列表\n        :return box对象列表的均值中心点box对象\n        \"\"\"\n        boxes_w, boxes_h = map(np.array, zip(*[(box.w, box.h) for box in boxes]))\n        return BoundingBox(boxes_w.mean(), boxes_h.mean())\n    \n    @staticmethod\n    def plot(centroids, boxes, group, name='GT bounding prediction cluster'):\n        \"\"\"\n        绘制boxes散点图：聚类中心点为黑色，其他每一类一种颜色\n        :param centroids: 各个group中心点\n        :param boxes: boxes列表\n        :param group: boxes对应的归属的中心点\n        :param name: 散点图名称\n        :return:\n        \"\"\"\n        col = ['silver', 'red', 'peru', 'yellow', 'green', 'cyan', 'blue', 'fuchsia', 'pink', 'black']\n        # 中心点和boxes的 width 和 height 解析\n        center_w, center_h = map(np.array, zip(*[(box.w, box.h) for box in centroids]))\n        center_colors = col[:len(centroids)]  # 'k'\n        boxes_w, boxes_h = map(np.array, zip(*[(box.w, box.h) for box in boxes]))\n        boxes_colors = [col[i] for i in group]\n        # 绘制散点图\n        plt.grid(ls='--')\n        plt.scatter(boxes_w, boxes_h, c=boxes_colors, s=36, alpha=0.3)\n        plt.scatter(center_w, center_h, c=center_colors, marker='p', s=48, alpha=1)\n        shift = np.max(center_h) * 0.1\n        for box in centroids:\n            plt.text(box.w, box.h - shift, '({:.3f}, {:.3f})'.format(box.w, box.h))\n        plt.title(name)\n        plt.xlabel('Width')\n        plt.ylabel('Height')\n        plt.show()\n    \n    @staticmethod\n    def plot3D(centroids, boxes, group, cls_names, name='GT bounding prediction cluster'):\n        \"\"\"\n        绘制boxes的3维散点图\n        :param centroids: 各个group中心点\n        :param boxes: boxes列表\n        :param group: boxes对应的归属的中心点\n        :param cls_names: 物体类别名称\n        :param name: 散点图名称\n        :return:\n        \"\"\"\n        fig = plt.figure()\n        ax = Axes3D(fig)\n        col = ['black', 'silver', 'red', 'peru', 'yellow', 'green', 'cyan', 'blue', 'fuchsia', 'pink']\n        # 中心点和boxes的 width 和 height 解析\n        center_w, center_h = map(np.array, zip(*[(box.w, box.h) for box in centroids]))\n        center_colors = 'k'  # col[:len(centroids)]\n        boxes_w, boxes_h = map(np.array, zip(*[(box.w, box.h) for box in boxes]))\n        boxes_colors = [col[i] for i in group]\n        # 绘制散点图\n        plt.grid(ls='--')\n        ax.scatter(boxes_w, boxes_h, [0] * len(boxes_h), c=boxes_colors, alpha=0.3)\n        ax.scatter(center_w, center_h, [0] * len(center_w), c=center_colors, marker='p', s=48, alpha=1)\n        for index, cls_name in enumerate(cls_names):\n            cls_indices = np.where([name == cls_name for name in cls_names])[0]\n            ax.scatter(boxes_w[cls_indices], boxes_h[cls_indices], [(index + 1) * 10] * len(cls_indices),\n                       c=[boxes_colors[i] for i in cls_indices], alpha=0.3)\n            ax.scatter(center_w, center_h, [(index + 1) * 10] * len(center_w),\n                       c=center_colors, marker='p', s=48, alpha=1)\n        plt.title(name)\n        ax.set_xlabel('Width')\n        ax.set_ylabel('Height')\n        ax.set_zlabel('Classes')\n        ax.set_zlim(0, 10 * len(cls_names) + 10)\n        plt.savefig(\"scatter3D.png\")\n        plt.show()\n    \n    @staticmethod\n    def plot_pareto(centroids, boxes, group, title='IOU-Ratio Curve'):\n        \"\"\"\n        绘制 IOU-probability曲线\n        :param centroids: 聚类中心\n        :param boxes: box列表\n        :param group: boxes对应的归属的中心点\n        :param title: 标题\n        :return:\n        \"\"\"\n        plt.grid(ls='--')\n        plt.title('{} Pareto'.format(title))\n        col = ['black', 'silver', 'red', 'peru', 'yellow', 'green', 'cyan', 'blue', 'fuchsia', 'pink']\n        for i, box in enumerate(centroids):\n            pos = np.where(group == i)[0]\n            x = 1 - np.sort(BoundingBox.distance(box, [boxes[j] for j in pos]))  # 因为距离是 1 - IOU\n            y = np.arange(len(x)) / len(x)\n            plt.plot(x, y, color=col[i], label='cluster {}'.format(i))\n        \n        plt.legend()\n        plt.xlabel('IoU')\n        plt.ylabel('Sample ratio')\n        plt.show()\n", "meta": {"hexsha": "462e46fdc32cc429cb821e92a1cbd1bbd5b73644", "size": 4993, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/anchors/bounding_box.py", "max_stars_repo_name": "zheng-yuwei/YOLOv2-tensorflow", "max_stars_repo_head_hexsha": "28da5dac1754da3f164c64352b233327b20248ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-11-08T06:43:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-23T02:05:54.000Z", "max_issues_repo_path": "utils/anchors/bounding_box.py", "max_issues_repo_name": "zheng-yuwei/YOLOv2-tensorflow", "max_issues_repo_head_hexsha": "28da5dac1754da3f164c64352b233327b20248ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-12-18T13:18:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-19T02:07:39.000Z", "max_forks_repo_path": "utils/anchors/bounding_box.py", "max_forks_repo_name": "zheng-yuwei/YOLOv2-tensorflow", "max_forks_repo_head_hexsha": "28da5dac1754da3f164c64352b233327b20248ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2611940299, "max_line_length": 105, "alphanum_fraction": 0.5597836972, "include": true, "reason": "import numpy", "num_tokens": 1535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.36658972248186006, "lm_q1q2_score": 0.19616158445070891}}
{"text": "# -*- coding: utf-8 -*-\n\n\"\"\"\nThis module does calculations compliant to ISO 3382-1 in order to obtain room\nacoustic paramters.\n\nIt has an implementation of Lundeby et al. [1] algorithm to estimate the\ncorrection factor for the cumulative integral, as suggested by the ISO 3382-1.\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom numba import njit\nfrom pytta import SignalObj, OctFilter, Analysis, ImpulsiveResponse\nfrom pytta.utils import fractional_octave_frequencies as FOF\nimport traceback\nimport copy as cp\n\n\ndef _filter(signal,\n            order: int = 4,\n            nthOct: int = 3,\n            minFreq: float = 20,\n            maxFreq: float = 20000,\n            refFreq: float = 1000,\n            base: int = 10):\n    of = OctFilter(order=order,\n                   nthOct=nthOct,\n                   samplingRate=signal.samplingRate,\n                   minFreq=minFreq,\n                   maxFreq=maxFreq,\n                   refFreq=refFreq,\n                   base=base)\n    result = of.filter(signal)\n    return result[0]\n\n\n@njit\ndef _level_profile(timeSignal, samplingRate,\n                    numSamples, numChannels, blockSamples=None):\n    \"\"\"\n    Gets h(t) in octave bands and do the local time averaging in nblocks.\n    Returns h^2_averaged(block).\n    \"\"\"\n    def mean_squared(x):\n        return np.mean(x**2)\n\n    if blockSamples is None:\n        blockSamples = 100\n    nblocks = int(numSamples // blockSamples)\n    profile = np.zeros((nblocks, numChannels), dtype=np.float32)\n    timeStamp = np.zeros((nblocks, 1))\n\n    for ch in range(numChannels):\n        # if numChannels == 1:\n        #     tmp = timeSignal\n        # else:\n        tmp = timeSignal[:, ch]\n        for idx in range(nblocks):\n            profile[idx, ch] = mean_squared(tmp[:blockSamples])\n            timeStamp[idx, 0] = idx*blockSamples/samplingRate\n            tmp = tmp[blockSamples:]\n    return profile, timeStamp\n\n\n@njit\ndef _start_sample_ISO3382(timeSignal, threshold) -> np.ndarray:\n    squaredIR = timeSignal**2\n    # assume the last 10% of the IR is noise, and calculate its noise level\n    last10Idx = -int(len(squaredIR)//10)\n    noiseLevel = np.mean(squaredIR[last10Idx:])\n    # get the maximum of the signal, that is the assumed IR peak\n    max_val = np.max(squaredIR)\n    max_idx = np.argmax(squaredIR)\n    # check if the SNR is enough to assume that the signal is an IR. If not,\n    # the signal is probably not an IR, so it starts at sample 1\n    idxNoShift = np.asarray([max_val < 100*noiseLevel or\n                             max_idx > int(0.9*squaredIR.shape[0])])\n    # less than 20dB SNR or in the \"noisy\" part\n    if idxNoShift.any():\n        print(\"noiseLevelCheck: The SNR too bad or this is not an \" +\n              \"impulse response.\")\n        return 0\n    # find the first sample that lies under the given threshold\n    threshold = abs(threshold)\n    startSample = 1\n#    # TODO - envelope mar/pdi - check!\n#    if idxNoShift:\n#        print(\"Something wrong!\")\n#        return\n    # if maximum lies on the first point, then there is no point in searching\n    # for the beginning of the IR. Just return this position.\n    if max_idx > 0:\n        abs_dat = 10*np.log10(squaredIR[:max_idx]) \\\n                  - 10.*np.log10(max_val)\n        thresholdNotOk = True\n        thresholdShift = 0\n        while thresholdNotOk:\n            if len(np.where(abs_dat < (-threshold+thresholdShift))[0]) > 0:\n                lastBelowThreshold = \\\n                    np.where(abs_dat < (-threshold+thresholdShift))[0][-1]\n                thresholdNotOk = False\n            else:\n                thresholdShift += 1\n        if thresholdShift > 0:\n            print(\"_start_sample_ISO3382: 20 dB threshold too high. \" +\n                  \"Decreasing it.\")\n        if lastBelowThreshold > 0:\n            startSample = lastBelowThreshold\n        else:\n            startSample = 1\n    return startSample\n\n\n@njit\ndef _circular_time_shift(timeSignal, threshold=20):\n    # find the first sample where inputSignal level > 20 dB or > bgNoise level\n    startSample = _start_sample_ISO3382(timeSignal, threshold)\n    newTimeSignal = timeSignal[startSample:]\n    return (newTimeSignal, startSample)\n\n\n@njit\ndef _Lundeby_correction(band, timeSignal, samplingRate, numSamples,\n                         numChannels, timeLength):\n    returnTuple = (np.float32(0), np.float32(0), np.int32(0), np.float32(0))\n    timeSignal, sampleShift = _circular_time_shift(timeSignal)\n    if sampleShift is None:\n        return returnTuple\n    winTimeLength = 0.03  # 30 ms window\n    numSamples -= sampleShift  # discount shifted samples\n    numParts = 5  # number of parts per 10 dB decay. N = any([3, 10])\n    dBtoNoise = 7  # stop point 10 dB above first estimated background noise\n    useDynRange = 15  # dynamic range\n\n    # 1) local time average:\n    blockSamples = int(winTimeLength * samplingRate)\n    timeWinData, timeVecWin = _level_profile(timeSignal, samplingRate,\n                                              numSamples, numChannels,\n                                              blockSamples)\n\n    # 2) estimate noise from h^2_averaged(block):\n    bgNoiseLevel = 10 * \\\n                   np.log10(\n                            np.mean(timeWinData[-int(timeWinData.size/10):]))\n\n    # 3) Calculate premilinar slope\n    startIdx = np.argmax(np.abs(timeWinData/np.max(np.abs(timeWinData))))\n    stopIdx = startIdx + np.where(10*np.log10(timeWinData[startIdx+1:])\n                                  >= bgNoiseLevel + dBtoNoise)[0][-1]\n    dynRange = 10*np.log10(timeWinData[stopIdx]) \\\n        - 10*np.log10(timeWinData[startIdx])\n    if (stopIdx == startIdx) or (dynRange > -5)[0]:\n        print(band, \"[Hz] band: SNR too low for the preliminar slope\",\n              \"calculation.\")\n        return returnTuple\n\n    # X*c = EDC (energy decaying curve)\n    X = np.ones((stopIdx-startIdx, 2), dtype=np.float32)\n    X[:, 1] = timeVecWin[startIdx:stopIdx, 0]\n    c = np.linalg.lstsq(X, 10*np.log10(timeWinData[startIdx:stopIdx]),\n                        rcond=-1)[0]\n\n    if (c[1] == 0)[0] or np.isnan(c).any():\n        print(band, \"[Hz] band: regression failed. T would be inf.\")\n        return returnTuple\n\n    # 4) preliminary intersection\n    crossingPoint = (bgNoiseLevel - c[0]) / c[1]  # [s]\n    if (crossingPoint > 2*(timeLength + sampleShift/samplingRate))[0]:\n        print(band, \"[Hz] band: preliminary intersection point between\",\n              \"bgNoiseLevel and the decay slope greater than signal length.\")\n        return returnTuple\n\n    # 5) new local time interval length\n    nBlocksInDecay = numParts * dynRange[0] / -10\n\n    dynRangeTime = timeVecWin[stopIdx] - timeVecWin[startIdx]\n    blockSamples = int(samplingRate * dynRangeTime[0] / nBlocksInDecay)\n\n    # 6) average\n    timeWinData, timeVecWin = _level_profile(timeSignal, samplingRate,\n                                              numSamples, numChannels,\n                                              blockSamples)\n\n    oldCrossingPoint = 11+crossingPoint  # arbitrary higher value to enter loop\n    loopCounter = 0\n\n    while (np.abs(oldCrossingPoint - crossingPoint) > 0.001)[0]:\n        # 7) estimate background noise level (BGL)\n        bgNoiseMargin = 7\n        idxLast10Percent = int(len(timeWinData)-(len(timeWinData)//10))\n        bgStartTime = crossingPoint - bgNoiseMargin/c[1]\n        if (bgStartTime > timeVecWin[-1:][0])[0]:\n            idx10dBDecayBelowCrossPoint = len(timeVecWin)-1\n        else:\n            idx10dBDecayBelowCrossPoint = \\\n                np.where(timeVecWin >= bgStartTime)[0][0]\n        BGL = np.mean(timeWinData[np.min(\n                np.array([idxLast10Percent,\n                          idx10dBDecayBelowCrossPoint])):])\n        bgNoiseLevel = 10*np.log10(BGL)\n\n        # 8) estimate late decay slope\n        stopTime = (bgNoiseLevel + dBtoNoise - c[0])/c[1]\n        if (stopTime > timeVecWin[-1])[0]:\n            stopIdx = 0\n        else:\n            stopIdx = int(np.where(timeVecWin >= stopTime)[0][0])\n\n        startTime = (bgNoiseLevel + dBtoNoise + useDynRange - c[0])/c[1]\n        if (startTime < timeVecWin[0])[0]:\n            startIdx = 0\n        else:\n            startIdx = int(np.where(timeVecWin <= startTime)[0][0])\n\n        lateDynRange = np.abs(10*np.log10(timeWinData[stopIdx]) \\\n            - 10*np.log10(timeWinData[startIdx]))\n\n        # where returns empty\n        if stopIdx == startIdx or (lateDynRange < useDynRange)[0]:\n            print(band, \"[Hz] band: SNR for the Lundeby late decay slope too\",\n                \"low. Skipping!\")\n            # c[1] = np.inf\n            c[1] = 0\n            break\n\n        X = np.ones((stopIdx-startIdx, 2), dtype=np.float32)\n        X[:, 1] = timeVecWin[startIdx:stopIdx, 0]\n        c = np.linalg.lstsq(X, 10*np.log10(timeWinData[startIdx:stopIdx]),\n                            rcond=-1)[0]\n\n        if (c[1] >= 0)[0]:\n            print(band, \"[Hz] band: regression did not work, T -> inf.\",\n                \"Setting slope to 0!\")\n            # c[1] = np.inf\n            c[1] = 0\n            break\n\n        # 9) find crosspoint\n        oldCrossingPoint = crossingPoint\n        crossingPoint = (bgNoiseLevel - c[0]) / c[1]\n\n        loopCounter += 1\n        if loopCounter > 30:\n            print(band, \"[Hz] band: more than 30 iterations on regression.\",\n                \"Canceling!\")\n            break\n\n    interIdx = crossingPoint * samplingRate # [sample]\n\n    return c[0][0], c[1][0], np.int32(interIdx[0]), BGL\n\n@njit\ndef energy_decay_calculation(band, timeSignal, timeVector, samplingRate,\n                             numSamples, numChannels, timeLength, bypassLundeby):\n    \"\"\"Calculate the Energy Decay Curve.\"\"\"\n    if not bypassLundeby:\n        lundebyParams = \\\n            _Lundeby_correction(band,\n                                timeSignal,\n                                samplingRate,\n                                numSamples,\n                                numChannels,\n                                timeLength)\n        _, c1, interIdx, BGL = lundebyParams\n        lateRT = -60/c1 if c1 != 0 else 0\n    else:\n        interIdx = 0\n        lateRT = 1\n\n    if interIdx == 0:\n        interIdx = -1\n\n    truncatedTimeSignal = timeSignal[:interIdx, 0]\n    truncatedTimeVector = timeVector[:interIdx]\n\n    if lateRT != 0.0:\n        if not bypassLundeby:\n            C = samplingRate*BGL*lateRT/(6*np.log(10))\n        else:\n            C = 0\n        sqrInv = truncatedTimeSignal[::-1]**2\n        energyDecayFull = np.cumsum(sqrInv)[::-1] + C\n        energyDecay = energyDecayFull/energyDecayFull[0]\n    else:\n        print(band, \"[Hz] band: could not estimate C factor\")\n        C = 0\n        energyDecay = np.zeros(truncatedTimeVector.size)\n    return (energyDecay, truncatedTimeVector, lundebyParams)\n\ndef cumulative_integration(inputSignal,\n                           bypassLundeby,\n                           plotLundebyResults,\n                           **kwargs):\n    \"\"\"Cumulative integration with proper corrections.\"\"\"\n\n    def plot_lundeby():\n        c0, c1, interIdx, BGL = lundebyParams\n        fig = plt.figure(figsize=(10, 5))\n        ax = fig.add_axes([0.08, 0.15, 0.75, 0.8], polar=False,\n                            projection='rectilinear', xscale='linear')\n        line = c1*timeVector + c0\n        ax.plot(timeVector, 10*np.log10(timeSignal**2),label='IR')\n        ax.axhline(y=10*np.log10(BGL), color='#1f77b4', label='BG Noise')\n        ax.plot(timeVector, line,label='Late slope')\n        ax.axvline(x=interIdx/samplingRate, label='Truncation point')\n        plt.title('{0:.0f} [Hz]'.format(band))\n        ax.legend(loc='upper center', shadow=True, fontsize='x-large')\n\n    timeSignal = inputSignal.timeSignal[:]\n    # Substituted by SignalObj.crop in analyse function\n    # timeSignal, sampleShift = _circular_time_shift(timeSignal)\n    # del sampleShift\n    hSignal = SignalObj(timeSignal,\n                        inputSignal.lengthDomain,\n                        inputSignal.samplingRate)\n    hSignal = _filter(hSignal, **kwargs)\n    bands = FOF(nthOct=kwargs['nthOct'],\n                freqRange=[kwargs['minFreq'],kwargs['maxFreq']])[:,1]\n    listEDC = []\n    for ch in range(hSignal.numChannels):\n        signal = hSignal[ch]\n        band = bands[ch]\n        timeSignal = cp.copy(signal.timeSignal[:])\n        timeVector = signal.timeVector[:]\n        samplingRate = signal.samplingRate\n        numSamples = signal.numSamples\n        numChannels = signal.numChannels\n        timeLength = signal.timeLength\n        energyDecay, energyVector, lundebyParams = \\\n            energy_decay_calculation(band,\n                                     timeSignal,\n                                     timeVector,\n                                     samplingRate,\n                                     numSamples,\n                                     numChannels,\n                                     timeLength,\n                                     bypassLundeby)\n        listEDC.append((energyDecay, energyVector))\n        if plotLundebyResults:  # Placed here because Numba can't handle plots.\n            # plot_lundeby(band, timeVector, timeSignal,  samplingRate,\n            #             lundebyParams)\n            plot_lundeby()\n    return listEDC\n\n@njit\ndef reverb_time_regression(energyDecay, energyVector, upperLim, lowerLim):\n    \"\"\"Interpolate the EDT to get the reverberation time.\"\"\"\n    if not np.any(energyDecay):\n        return 0\n    first = np.where(10*np.log10(energyDecay) >= upperLim)[0][-1]\n    last = np.where(10*np.log10(energyDecay) >= lowerLim)[0][-1]\n    if last <= first:\n        # return np.nan\n        return 0\n    X = np.ones((last-first, 2))\n    X[:, 1] = energyVector[first:last]\n    c = np.linalg.lstsq(X, 10*np.log10(energyDecay[first:last]), rcond=-1)[0]\n    return -60/c[1]\n\n\ndef reverberation_time(decay, nthOct, samplingRate, listEDC):\n    \"\"\"Call the reverberation time regression.\"\"\"\n    try:\n        decay = int(decay)\n        y1 = -5\n        y2 = y1 - decay\n    except ValueError:\n        if decay in ['EDT', 'edt']:\n            y1 = 0\n            y2 = -10\n        else:\n            raise ValueError(\"Decay must be either 'EDT' or an integer \\\n                             corresponding to the amount of energy decayed to \\\n                             evaluate, e.g. (decay='20' | 20).\")\n    RT = []\n    for ED in listEDC:\n        edc, edv = ED\n        RT.append(reverb_time_regression(edc, edv, y1, y2))\n    return RT\n\n\ndef G_Lpe(IR, nthOct, minFreq, maxFreq, IREndManualCut=None):\n    \"\"\"\n    Calculate the energy level from the room impulsive response.\n\n    Reference:\n        Christensen, C. L.; Rindel, J. H. APPLYING IN-SITU RECALIBRATION FOR\n        SOUND STRENGTH MEASUREMENTS IN AUDITORIA.\n\n    :param IR: one channel impulsive response\n    :type IR: ImpulsiveResponse\n\n    :param nthOct: number of fractions per octave\n    :type nthOct: int\n\n    :param minFreq: analysis inferior frequency limit\n    :type minFreq: float\n\n    :param maxFreq: analysis superior frequency limit\n    :type maxFreq: float\n\n    :return: Analysis object with the calculated parameter\n    :rtype: Analysis\n    \"\"\"\n    # Code snippet to guarantee that generated object name is\n    # the declared at global scope\n    # for frame, line in traceback.walk_stack(None):\n    for framenline in traceback.walk_stack(None):\n        # varnames = frame.f_code.co_varnames\n        varnames = framenline[0].f_code.co_varnames\n        if varnames is ():\n            break\n    # creation_file, creation_line, creation_function, \\\n    #     creation_text = \\\n    extracted_text = \\\n        traceback.extract_stack(framenline[0], 1)[0]\n        # traceback.extract_stack(frame, 1)[0]\n    # creation_name = creation_text.split(\"=\")[0].strip()\n    creation_name = extracted_text[3].split(\"=\")[0].strip()\n\n    # firstChNum = IR.systemSignal.channels.mapping[0]\n    # if not IR.systemSignal.channels[firstChNum].calibCheck:\n    #     raise ValueError(\"'IR' must be a calibrated ImpulsiveResponse\")\n    if isinstance(IR, SignalObj):\n        SigObj = cp.copy(IR)\n    elif isinstance(IR, ImpulsiveResponse):\n        SigObj = cp.copy(IR.systemSignal)\n    else:\n        raise TypeError(\"'IR' must be an ImpulsiveResponse or SignalObj.\")\n    # Cutting the IR\n    if IREndManualCut is not None:\n        SigObj.crop(0, IREndManualCut)\n    timeSignal, _ = _circular_time_shift(SigObj.timeSignal[:,0])\n    # Bands filtering\n    # hSignal = SignalObj(SigObj.timeSignal[:,0],\n    hSignal = SignalObj(timeSignal,\n                        SigObj.lengthDomain,\n                        SigObj.samplingRate)\n    hSignal = _filter(signal=hSignal, nthOct=nthOct, minFreq=minFreq,\n                      maxFreq=maxFreq)\n    bands = FOF(nthOct=nthOct,\n                freqRange=[minFreq,maxFreq])[:,1]\n    Lpe = []\n    for chIndex in range(hSignal.numChannels):\n        Lpe.append(\n            10*np.log10(np.trapz(y=hSignal.timeSignal[:,chIndex]**2/(2e-5**2),\n                                 x=hSignal.timeVector)))\n    LpeAnal = Analysis(anType='mixed', nthOct=nthOct, minBand=float(bands[0]),\n                       maxBand=float(bands[-1]), data=Lpe,\n                       comment='h**2 energy level')\n    LpeAnal.creation_name = creation_name\n    return LpeAnal\n\n\ndef G_Lps(IR, nthOct, minFreq, maxFreq):\n    \"\"\"G_Lps \n    \n    Calculates the recalibration level, for both in-situ and\n    reverberation chamber. Lps is applied for G calculation.\n\n    During the recalibration: source height and mic heigth must be >= 1 [m],\n    while the distance between source and mic must be <= 1 [m]. The distances\n    must be the same for in-situ and reverberation chamber measurements.\n\n    Reference:\n        Christensen, C. L.; Rindel, J. H. APPLYING IN-SITU RECALIBRATION FOR\n        SOUND STRENGTH MEASUREMENTS IN AUDITORIA.\n\n    :param IR: one channel impulsive response\n    :type IR: ImpulsiveResponse\n\n    :param nthOct: number of fractions per octave\n    :type nthOct: int\n\n    :param minFreq: analysis inferior frequency limit\n    :type minFreq: float\n\n    :param maxFreq: analysis superior frequency limit\n    :type maxFreq: float\n\n    :return: Analysis object with the calculated parameter\n    :rtype: Analysis\n    \"\"\"\n    # Code snippet to guarantee that generated object name is\n    # the declared at global scope\n    # for frame, line in traceback.walk_stack(None):\n    for framenline in traceback.walk_stack(None):\n        # varnames = frame.f_code.co_varnames\n        varnames = framenline[0].f_code.co_varnames\n        if varnames is ():\n            break\n    # creation_file, creation_line, creation_function, \\\n    #     creation_text = \\\n    extracted_text = \\\n        traceback.extract_stack(framenline[0], 1)[0]\n        # traceback.extract_stack(frame, 1)[0]\n    # creation_name = creation_text.split(\"=\")[0].strip()\n    creation_name = extracted_text[3].split(\"=\")[0].strip()\n\n    # firstChNum = IR.systemSignal.channels.mapping[0]\n    # if not IR.systemSignal.channels[firstChNum].calibCheck:\n    #     raise ValueError(\"'IR' must be a calibrated ImpulsiveResponse\")\n    if isinstance(IR, SignalObj):\n        SigObj = IR\n    elif isinstance(IR, ImpulsiveResponse):\n        SigObj = IR.systemSignal\n    else:\n        raise TypeError(\"'IR' must be an ImpulsiveResponse or SignalObj.\")\n    # Windowing the IR\n    # dBtoOnSet = 20\n    # dBIR = 10*np.log10((SigObj.timeSignal[:,0]**2)/((2e-5)**2))\n    # windowStart = np.where(dBIR > (max(dBIR) - dBtoOnSet))[0][0]\n\n    broadBandTimeSignal = cp.copy(SigObj.timeSignal[:,0])\n    broadBandTimeSignalNoStart, sampleShift = \\\n        _circular_time_shift(broadBandTimeSignal)\n    windowLength = 0.0032 # [s]\n    windowEnd = int(windowLength*SigObj.samplingRate)\n\n\n    hSignal = SignalObj(broadBandTimeSignalNoStart[:windowEnd],\n    # hSignal = SignalObj(timeSignal,\n                        SigObj.lengthDomain,\n                        SigObj.samplingRate)\n    hSignal = _filter(signal=hSignal, nthOct=nthOct, minFreq=minFreq,\n                      maxFreq=maxFreq)\n    bands = FOF(nthOct=nthOct,\n                freqRange=[minFreq,maxFreq])[:,1]\n    Lps = []\n    for chIndex in range(hSignal.numChannels):\n        timeSignal = cp.copy(hSignal.timeSignal[:,chIndex])\n        # timeSignalNoStart, sampleShift = _circular_time_shift(timeSignal)\n        # windowLength = 0.0032 # [s]\n        # windowEnd = int(windowLength*SigObj.samplingRate)\n\n        Lps.append(\n            # 10*np.log10(np.trapz(y=timeSignalNoStart[:windowEnd]**2/(2e-5**2),\n            10*np.log10(np.trapz(y=timeSignal**2/(2e-5**2),\n                                #  x=hSignal.timeVector[sampleShift:sampleShift+windowEnd])))\n                                 x=hSignal.timeVector)))\n    LpsAnal = Analysis(anType='mixed', nthOct=nthOct, minBand=float(bands[0]),\n                       maxBand=float(bands[-1]), data=Lps,\n                       comment='Source recalibration method IR')\n    LpsAnal.creation_name = creation_name\n    LpsAnal.windowLimits = ((sampleShift)/SigObj.samplingRate,\n                            (sampleShift+windowEnd)/SigObj.samplingRate)\n    # Plot IR cutting\n    # fig = plt.figure(figsize=(10, 5))\n    # ax = fig.add_axes([0.08, 0.15, 0.75, 0.8], polar=False,\n    #                         projection='rectilinear', xscale='linear')\n    # ax.plot(SigObj.timeVector, 10*np.log10(SigObj.timeSignal**2/2e-5**2))\n    # ax.axvline(x=(sampleShift)/SigObj.samplingRate, linewidth=4, color='k')\n    # ax.axvline(x=(sampleShift+windowEnd)/SigObj.samplingRate, linewidth=4, color='k')\n    # ax.set_xlim([(sampleShift-100)/SigObj.samplingRate, (sampleShift+windowEnd+100)/SigObj.samplingRate])\n    return LpsAnal\n\n\ndef strength_factor(Lpe, Lpe_revCh, V_revCh, T_revCh, Lps_revCh, Lps_inSitu):\n    S0 = 1 # [m2]\n\n    bands = T_revCh.bands\n    nthOct = T_revCh.nthOct\n    terms = []\n    for bandData in T_revCh.data:\n        if bandData == 0:\n            terms.append(0)\n        else:\n            term = (V_revCh * 0.16) / (bandData * S0)\n            terms.append(term)\n    terms = [10*np.log10(term) if term != 0 else 0 for term in terms]\n\n    revChTerm = Analysis(anType='mixed', nthOct=nthOct, minBand=float(bands[0]),\n                         maxBand=float(bands[-1]), data=terms)\n    Lpe.anType = 'mixed'\n    Lpe_revCh.anType = 'mixed'\n    Lps_revCh.anType = 'mixed'\n    Lps_inSitu.anType = 'mixed'\n    G = Lpe - Lpe_revCh - revChTerm + 37 \\\n        + Lps_revCh - Lps_inSitu\n    G.anType = 'G'\n    return G\n\n\ndef _clarity(temp, signalObj, nthOct, **kwargs):  # TODO\n    \"\"\"\n\n    \"\"\"\n#    try:\n#        temp = int(temp)*signalObj.samplingRate//1000\n#    except ValueError:\n#        raise ValueError(\"The temp parameter must be an integer or a string \\\n#                         of integers, e.g. (temp='80' | 80).\")\n#    output = []\n#    for ch in range(signalObj.num_channels()):\n#        filtResp = filtered_response(signalObj[ch], nthOct, **kwargs)\n#        C = []\n#        for bd in range(len(filtResp)):\n#            C.append(round(np.sum(filtResp[bd][:temp], axis=0)\n#                           / np.sum(filtResp[bd][temp:], axis=0)[0], 2))\n#        output.append(C)\n#    return output\n    pass\n\n\ndef _definition(temp, signalObj, nthOct, **kwargs):  # TODO\n    \"\"\"\n\n    \"\"\"\n#    try:\n#        temp = int(temp)*signalObj.samplingRate//1000\n#    except ValueError:\n#        raise ValueError(\"The temp parameter must be an integer or a string \\\n#                         of integers, e.g. (temp='50' | 50).\")\n#    output = []\n#    for ch in range(signalObj.num_channels()):\n#        filtResp = filtered_response(signalObj[ch], nthOct, **kwargs)\n#        D = []\n#        for bd in range(len(filtResp)):\n#            D.append(round(10*np.log10(\n#                        np.sum(filtResp[bd][:temp], axis=0)\n#                        / np.sum(filtResp[bd][:], axis=0))[0], 2))\n#        output.append(D)\n#    return output\n    pass\n\ndef crop_IR(SigObj, IREndManualCut):\n    \"\"\"Cut the impulse response at background noise level.\"\"\"\n    timeSignal = cp.copy(SigObj.timeSignal)\n    timeVector = SigObj.timeVector\n    samplingRate = SigObj.samplingRate\n    numSamples = SigObj.numSamples\n    # numChannels = SigObj.numChannels\n    if SigObj.numChannels > 1:\n        print('crop_IR: The provided impulsive response has more than one ' +\n              'channel. Cropping based on channel 1.')\n    numChannels = 1\n    # Cut the end automatically or manual\n    if IREndManualCut is None:\n        winTimeLength = 0.1  # [s]\n        meanSize = 5  # [blocks]\n        dBtoReplica = 6  # [dB]\n        blockSamples = int(winTimeLength * samplingRate)\n        timeWinData, timeVecWin = _level_profile(timeSignal, samplingRate,\n                                                numSamples, numChannels,\n                                                blockSamples)\n        endTimeCut = timeVector[-1]\n        for blockIdx, blockAmplitude in enumerate(timeWinData):\n            if blockIdx >= meanSize:\n                anteriorMean = 10*np.log10( \\\n                    np.sum(timeWinData[blockIdx-meanSize:blockIdx])/meanSize)\n                if 10*np.log10(blockAmplitude) > anteriorMean+dBtoReplica:\n                    endTimeCut = timeVecWin[blockIdx-meanSize//2]\n                    break\n    else:\n        endTimeCut = IREndManualCut\n    endTimeCutIdx = np.where(timeVector >= endTimeCut)[0][0]\n    timeSignal = timeSignal[:endTimeCutIdx]\n    # Cut the start automatically\n    timeSignal, _ = _circular_time_shift(timeSignal)\n    result = SignalObj(timeSignal,\n                       'time',\n                       samplingRate,\n                       signalType='energy')\n    return result\n\ndef analyse(obj, *params,\n            bypassLundeby=False,\n            plotLundebyResults=False,\n            IREndManualCut=None, **kwargs):\n    \"\"\"\n    Receives an one channel SignalObj or ImpulsiveResponse and calculate the\n    room acoustic parameters especified in the positional input arguments.\n\n    :param obj: one channel impulsive response\n    :type obj: SignalObj or ImpulsiveResponse\n\n    Input parameters for reverberation time, 'RT':\n        :param RTdecay: decay interval for RT calculation. e.g. 20\n        :type RTdecay: int\n\n    Input parameters for clarity, 'C':\n        TODO\n\n    Input parameters for definition, 'D':\n        TODO\n\n    Input parameters for strength factor, 'G':\n        TODO\n\n    :param nthOct: number of fractions per octave\n    :type nthOct: int\n\n    :param minFreq: analysis inferior frequency limit\n    :type minFreq: float\n\n    :param maxFreq: analysis superior frequency limit\n    :type maxFreq: float\n    \n    :param bypassLundeby: bypass lundeby correction\n    to False\n    :type bypassLundeby: bool, optional\n\n    :param plotLundebyResults: plot the Lundeby correction parameters, defaults to False\n    :type plotLundebyResults: bool, optional\n\n    :return: Analysis object with the calculated parameter\n    :rtype: Analysis\n\n    \"\"\"\n    # Code snippet to guarantee that generated object name is\n    # the declared at global scope\n    # for frame, line in traceback.walk_stack(None):\n    for framenline in traceback.walk_stack(None):\n        # varnames = frame.f_code.co_varnames\n        varnames = framenline[0].f_code.co_varnames\n        if varnames is ():\n            break\n    # creation_file, creation_line, creation_function, \\\n    #     creation_text = \\\n    extracted_text = \\\n        traceback.extract_stack(framenline[0], 1)[0]\n    # traceback.extract_stack(frame, 1)[0]\n    # creation_name = creation_text.split(\"=\")[0].strip()\n    creation_name = extracted_text[3].split(\"=\")[0].strip()\n\n    if not isinstance(obj, SignalObj) and not isinstance(obj, ImpulsiveResponse):\n        raise TypeError(\"'obj' must be an one channel SignalObj or\" +\n                        \" ImpulsiveResponse.\")\n    if isinstance(obj, ImpulsiveResponse):\n        SigObj = obj.systemSignal\n    else:\n        SigObj = obj\n\n    if SigObj.numChannels > 1:\n        raise TypeError(\"'obj' can't contain more than one channel.\")\n    samplingRate = SigObj.samplingRate\n\n    SigObj = crop_IR(SigObj, IREndManualCut)\n\n    listEDC = cumulative_integration(SigObj,\n                                     bypassLundeby,\n                                     plotLundebyResults,\n                                     **kwargs)\n    for _ in params:\n        if 'RT' in params:\n            RTdecay = params[params.index('RT')+1]\n            nthOct = kwargs['nthOct']\n            RT = reverberation_time(RTdecay, nthOct, samplingRate, listEDC)\n            result = Analysis(anType='RT', nthOct=nthOct,\n                              minBand=kwargs['minFreq'],\n                              maxBand=kwargs['maxFreq'],\n                              data=RT)\n        # if 'C' in prm:\n        #     Ctemp = prm[1]\n        # if 'D' in prm:\n        #     Dtemp = prm[1]\n    result.creation_name = creation_name\n    return result\n", "meta": {"hexsha": "e40002796bccfa19e1b854696c8cdd7e833454d0", "size": 28848, "ext": "py", "lang": "Python", "max_stars_repo_path": "pytta/rooms.py", "max_stars_repo_name": "carolgaudeoso/PyTTa", "max_stars_repo_head_hexsha": "13a5d2a8f30a096897baaffe98ebb84b324d6891", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-17T00:22:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T00:22:45.000Z", "max_issues_repo_path": "pytta/rooms.py", "max_issues_repo_name": "carolgaudeoso/PyTTa", "max_issues_repo_head_hexsha": "13a5d2a8f30a096897baaffe98ebb84b324d6891", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pytta/rooms.py", "max_forks_repo_name": "carolgaudeoso/PyTTa", "max_forks_repo_head_hexsha": "13a5d2a8f30a096897baaffe98ebb84b324d6891", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8582677165, "max_line_length": 107, "alphanum_fraction": 0.5988976705, "include": true, "reason": "import numpy,from numba", "num_tokens": 7358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.3208212878370535, "lm_q1q2_score": 0.19614435203258856}}
{"text": "\"\"\"\nMain module of the neda inference package\n\nThis introduces the `Environment` class, which we use to facilitate repeating\ntasks like running MCMC, calculating or estimating evidence. Finally, the\n`main` function runs the whole scheme. Note that both of these are imported\ninto the ``tracklib.analysis.neda`` namespace, i.e. can be imported from there\n(instead of ``tracklib.analysis.neda.neda``).\n\"\"\"\n\nimport numpy as np\nimport scipy.optimize\n\nfrom . import mcmc\n\nclass Environment:\n    \"\"\"\n    Environment for inference runs\n\n    This is essentially a semi-disguised way of using global variables for the\n    `Trajectory` we are looking at, the inference `models.Model` we want to use, and\n    the `MCMCscheme` together with the `MCMCconfig`. We use this approach\n    mainly for code readability / useability.\n\n    Attributes\n    ----------\n    traj : Trajectory\n    model : models.Model\n    MCMCconfig : dict\n        see `tracklib.util.mcmc.Sampler`\n    MCMCscheme : mcmc.MCMCScheme, optional\n        defaults to an instance of `mcmc.TPWMCMC`\n    \"\"\"\n    # Here we use ``env`` instead of ``self``.\n    def __init__(self, traj, model, MCMCconfig, MCMCscheme=None):\n        self.traj = traj\n        self.model = model\n        self.MCMCconfig = MCMCconfig\n        if MCMCscheme is None:\n            self.MCMCscheme = mcmc.TPWMCMC()\n        else: # pragma: no cover\n            self.MCMCscheme = MCMCscheme\n\n    def runMCMC(env, prior):\n        \"\"\"\n        Run the `MCMCscheme` with a given `prior`\n\n        Parameters\n        ----------\n        prior : Prior\n        \n        Returns\n        -------\n        mcmc.MCMCRun\n        \"\"\"\n        env.MCMCscheme.setup(env.traj, env.model, prior)\n        env.MCMCscheme.configure(**env.MCMCconfig)\n        return env.MCMCscheme.run()\n\n    def posterior_density(env, mcmcrun, prior, trace_eval,\n                          nSample_proposal=float('inf')):\n        r\"\"\"\n        Estimate the posterior density at a specific point from an `MCMCRun`\n\n        Parameters\n        ----------\n        mcmcrun : MCMCRun\n        prior : Prior\n        trace_eval : Loopingtrace\n            the point in parameter space for which to estimate the posterior\n            density\n        nSample_proposal : float, optional\n            how many samples from the proposal distribution to use for\n            evaluation of the exit rate. Defaults to exhaustive sampling, so\n            may be reduced if that seems excessive.\n\n        Returns\n        -------\n        float\n            the estimated posterior density for `!trace_eval`. Might be\n            ``np.inf`` if the MCMC ensemble collapsed to a single sample.\n\n        Notes\n        -----\n        This estimation follows eq. (9) of [1]_. Essentially, we estimate the\n        density at the sample point as the number of times it is entered from\n        another point in the steady state ensemble, times the average number of\n        steps it takes to leave this point again, divided by the total sample\n        number :math:`M`. This yields\n\n        .. math:: \\hat{p}(\\theta^*) = \\frac{N_\\text{enter}N_\\text{stay}}{M} = \\frac{P_\\text{enter}}{k_\\text{exit}} = \\frac{M^{-1}\\sum_{m=1}^M\\, \\alpha(\\theta^{(m)}, \\theta^*) q(\\theta^{(m)}, \\theta^*)}{J^{-1}\\sum_{j=1}^J\\, \\alpha(\\theta^*, \\theta^{(j)})}\\,,\n\n        where the :math:`\\theta^{(m)}` in the numerator are the samples from\n        the given MCMC run (i.e. are assumed to be sampled from the posterior\n        distribution), while :math:`\\theta^{(j)}` in the denominator are\n        independent samples from the proposal distribution\n        :math:`q(\\theta_\\text{from} = \\theta^*, \\theta_\\text{to})`\n        around the evaluation point :math:`\\theta^*`. Finally,\n        :math:`\\alpha(\\theta_\\text{from}, \\theta_\\text{to})` is the\n        acceptance probability for a given step.\n\n        References\n        ----------\n        .. [1] Chib, S. & Jeliazkov, I. Marginal Likelihood From the Metropolis-Hastings Output. Journal of the American Statistical Association 96, 270-281 (2001)\n        \"\"\"\n        # Check whether the MCMC sample collapsed, in which case the posterior\n        # estimation would diverge\n        logLs = mcmcrun.logLs_trunc()\n        if np.all(logLs == logLs[0]):\n            print('MCMC ensemble collapsed to single sample')\n            return np.inf\n\n        L_eval = env.MCMCscheme.likelihood(env.traj, trace_eval, env.model, prior)\n\n        # Chance to enter the target state from steady state\n        def get_p_step_to_eval(trace): return env.MCMCscheme.stepping_probability(trace, trace_eval)\n        p_step_to_eval = np.array(mcmcrun.evaluate(get_p_step_to_eval))\n\n        # Note: p_accept = 1 *if* we evaluate at the maximum likelihood trace\n        p_accept_move = env.MCMCscheme.acceptance_probability(mcmcrun.logLs_trunc(), L_eval)\n        p_enter = np.mean(p_step_to_eval * p_accept_move)\n\n        # Survival in target state\n        neighbor_logLs = [env.MCMCscheme.likelihood(env.traj, trace, env.model, prior) \\\n                          for trace in env.MCMCscheme.gen_proposal_sample_from(trace_eval, nSample=nSample_proposal)]\n        k_leave = np.mean(env.MCMCscheme.acceptance_probability(L_eval, neighbor_logLs))\n\n        # Occupancy of the target state = p_enter * survival\n        return p_enter / k_leave\n\n    def evidence(env, prior, mcmcrun):\n        \"\"\"\n        Calculate the (log-)evidence from an `MCMCRun`\n\n        Parameters\n        ----------\n        prior : Prior\n            the prior over `Loopingtraces <Loopingtrace>` used for the MCMC run\n        mcmcrun : MCMCRun\n            the MCMC sample\n\n        Returns\n        -------\n        float\n            the estimated log-evidence\n\n        Notes\n        -----\n        The log-evidence is given by ``log(likelihood) + log(prior) -\n        log(posterior)``.\n\n        See also\n        --------\n        posterior_density\n        \"\"\"\n        trace_eval, L_eval = mcmcrun.best_sample_L()\n        log_post = np.log(env.posterior_density(mcmcrun, prior, trace_eval, nSample_proposal=len(mcmcrun.samples)))\n        log_prior = prior.logpi(trace_eval)\n\n        if np.isinf(log_post):\n            return L_eval\n        else:\n            return L_eval + log_prior - log_post\n\n    def evidence_differential(env, prior, ref_prior, ref_mcmcrun):\n        r\"\"\"\n        Estimate the relative evidence given a reference point\n\n        Parameters\n        ----------\n        prior : Prior\n            the prior whose evidence we want to estimate\n        ref_prior : Prior\n            the reference point in prior space\n        ref_mcmcrun : MCMCRun\n            an `MCMCRun` using the reference prior\n\n        Returns\n        -------\n        float\n            the estimated log-evidence, relative to the reference\n\n        Notes\n        -----\n        The relative evidence is given by the expectation value of the prior\n        ratio over the MCMC sample: ``E = < prior/ref_prior >`` where ``<.>``\n        indicates an average over the MCMC sample.\n        \"\"\"\n        return np.log(np.mean(np.exp(prior.logpi_vectorized(ref_mcmcrun.samples) - \\\n                                     ref_prior.logpi_vectorized(ref_mcmcrun.samples))))\n\ndef main(traj, model, priorfam,\n         MCMCconfig, MCMCscheme=None,\n         max_iterations=20, min_iterations=5,\n         return_ = 'nothing', # 'traj', 'dict', or anything else\n         show_progress=False, assume_notebook_for_progressbar=True,\n        ):\n    \"\"\"\n    Run the neda looping inference scheme\n\n    The output of the inference run will be assembled into a dict whose fields\n    are detailed below. Where exactly this dict will end up depends on the\n    setting of `!return_`.\n    \n    Parameters\n    ----------\n    traj : Trajectory\n        the `Trajectory` whose looping profile to infer\n    model : models.Model\n        the inference model to use\n    priorfam : ParametricFamily\n        a family of priors\n    MCMCconfig : dict\n        configuration for the MCMC runs. See `tracklib.util.mcmc.Sampler`\n    MCMCscheme : mcmc.MCMCScheme, optional\n        the sampling scheme to use, i.e. an object implementing the\n        `mcmc.MCMCScheme` interface. Defaults to `mcmc.TPWMCMC'\n    max_iterations : int, optional\n        maximum number of iterations to run\n    min_iterations : int, optional\n        run at least this many iterations\n    return_ : {'nothing', 'None', 'traj', 'dict'}\n        what the return value of this function should be. Generally, the\n        results of the inference run will be stored in a dict. If\n        ``return_='dict'``, that dict is directly returned. Otherwise it is\n        written to ``traj.meta['neda']``, and if ``return_='traj'`` the\n        trajectory is returned (useful for parallelization). Otherwise this\n        function returns nothing, i.e. the inference results can be accessed\n        simply from ``traj.meta['neda']`` after calling this function.\n    show_progress : bool, optional\n        whether to show a progress bar. Note: for ``show_progress=True`` it\n        might happen that the termination condition is fulfilled during the\n        last \"required\" run, in which case the progress bar will stop before\n        reaching its maximum.\n    assume_notebook_for_progressbar : bool, optional\n        set to ``False`` if running outside Jupyter notebook to show\n        progressbar ASCII style\n\n    Returns\n    -------\n    prior_prams : np.array\n        the prior parameters for each iteration\n    mcmcrun : list of MCMCRun\n        the MCMC runs for each iteration\n    evidence : np.array\n        the evidence estimated from each `MCMCRun`\n    evidence_diff : np.array\n        the estimated evidence differential (relative evidence) at each\n        iteration\n    final : dict\n        the corresponding values for the iteration that should be considered\n        the final result. Has entries ``'prior_params'``, ``'mcmcrun'``,\n        ``'evidence'``, and ``'iteration'`` where the last one is the index of\n        the iteration the other three refer to.\n\n    Example\n    -------\n    Assuming we have a `Trajectory` ``traj`` that we want to run the looping\n    inference on:\n\n    >>> # Set up inference scheme\n    ... looppositions = [(0, 0), (0, -1)] # 2 states: unlooped (=0), fully looped (=1)\n    ... model = neda.models.RouseModel(N=20, D=1, k=5, k_extra=1, looppositions=looppositions)\n    ... priorfam = neda.ParametricFamily(start_params=(0), bounds=[(None, 0)])\n    ... priorfam.get = lambda logq : neda.priors.GeometricPrior(logq, nStates=len(looppositions))\n    ... MCMCconfig = {\n    ...         'iterations' : 1000,\n    ...         'burn_in'    :  100,\n    ...         }\n    ... \n    ... # Run the inference\n    ... neda.main(traj, model, priorfam, MCMCconfig, show_progress=True)\n    ... \n    ... # Visualize output\n    ... from matplotlib import pyplot as plt\n    ... neda.plot.butterfly(traj)\n    ... plt.show()\n\n    See also\n    --------\n    tracklib.analysis.kli.fit_RouseParams\n    \"\"\"\n    assert min_iterations >= 2\n    assert return_ in {'nothing', 'None', 'traj', 'dict'}\n\n    # Set up environment\n    env = Environment(traj, model, MCMCconfig, MCMCscheme)\n\n    # Set up iterative scheme\n    iterations = range(max_iterations)\n    if show_progress: # pragma: no cover\n        if assume_notebook_for_progressbar:\n            from tqdm.notebook import tqdm\n        else:\n            from tqdm import tqdm\n        iterations = tqdm(iterations, total=min(min_iterations, max_iterations))\n\n    prior_params = [priorfam.start_params]\n    mcmcruns = []\n    evidences = []\n    evidence_diffs = []\n\n    # Run iterations\n    for it in iterations:\n        prior = priorfam.get(*prior_params[-1])\n        mcmcruns.append(env.runMCMC(prior))\n        evidences.append(env.evidence(prior, mcmcruns[-1]))\n\n        if it+1 >= min_iterations:\n            if np.argmax(evidences) < it:\n                break\n        \n        # Maximize estimated evidence differential to find new prior parameters\n        def minimization_target(*params):\n            return -env.evidence_differential(priorfam.get(*params), prior, mcmcruns[-1])\n        minimization_result = scipy.optimize.minimize(minimization_target,\n                                                      x0=prior_params[-1],\n                                                      bounds=priorfam.bounds)\n\n        if not minimization_result.success: # pragma: no cover\n            print(minimization_result)\n            raise RuntimeError('Relative evidence maximization did not converge')\n\n        evidence_diffs.append(-minimization_result.fun)\n        prior_params.append(tuple(minimization_result.x))\n\n    # Output\n    best_it = np.argmax(evidences)\n    output = {\n        'prior_params'  : np.array(prior_params),\n        'mcmcrun'       : mcmcruns,\n        'evidence'      : np.array(evidences),\n        'evidence_diff' : np.array(evidence_diffs),\n        'final'         : {\n            'prior_params' : prior_params[best_it],\n            'mcmcrun'      : mcmcruns[best_it],\n            'evidence'     : evidences[best_it],\n            'iteration'    : best_it,\n            'best_trace'   : mcmcruns[best_it].best_sample_L()[0],\n            },\n        }\n\n    if return_ == 'dict':\n        return output\n    else:\n        traj.meta['neda'] = output\n        if return_ == 'traj':\n            return traj\n        else:\n            return None\n", "meta": {"hexsha": "5cbd83dcf10153abaabce8f522e8e3c1ae8ea481", "size": 13321, "ext": "py", "lang": "Python", "max_stars_repo_path": "tracklib/analysis/neda/neda.py", "max_stars_repo_name": "SGrosse-Holz/tracklib", "max_stars_repo_head_hexsha": "e0b88e3959db2ce65869d8292ce5792f4c77c7a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-30T15:10:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T15:10:51.000Z", "max_issues_repo_path": "tracklib/analysis/neda/neda.py", "max_issues_repo_name": "SGrosse-Holz/tracklib", "max_issues_repo_head_hexsha": "e0b88e3959db2ce65869d8292ce5792f4c77c7a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tracklib/analysis/neda/neda.py", "max_forks_repo_name": "SGrosse-Holz/tracklib", "max_forks_repo_head_hexsha": "e0b88e3959db2ce65869d8292ce5792f4c77c7a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9515669516, "max_line_length": 257, "alphanum_fraction": 0.6185721793, "include": true, "reason": "import numpy,import scipy", "num_tokens": 3252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.19614042734468984}}
{"text": "from __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom past.utils import old_div\nimport anuga\nimport numpy as num\nimport math\nfrom . import inlet_enquiry\n\nfrom anuga.utilities.system_tools import log_to_file\nfrom anuga.utilities.numerical_tools import ensure_numeric\n\n\n\nclass Structure_operator(anuga.Operator):\n    \"\"\"Structure Operator - transfer water from one rectangular box to another.\n    Sets up the geometry of problem\n    \n    This is the base class for structures (culverts, pipes, bridges etc). Inherit from this class (and overwrite\n    discharge_routine method for specific subclasses)\n    \n    Input: Two points, pipe_size (either diameter or width, depth),\n    mannings_rougness,\n    \"\"\" \n\n    counter = 0\n\n    def __init__(self,\n                 domain,\n                 end_points=None,\n                 exchange_lines=None,\n                 enquiry_points=None,\n                 invert_elevations=None,\n                 width=None,\n                 height=None,\n                 diameter=None,\n                 z1=None,\n                 z2=None,\n                 blockage=None,\n                 barrels=None,\n                 #culvert_slope=None,\n                 apron=None,\n                 manning=None,\n                 enquiry_gap=None,\n                 use_momentum_jet=False,\n                 zero_outflow_momentum=True,\n                 use_old_momentum_method=True,\n                 always_use_Q_wetdry_adjustment=True,\n                 force_constant_inlet_elevations=False,\n                 description=None,\n                 label=None,\n                 structure_type=None,\n                 logging=None,\n                 verbose=None):\n                     \n        \"\"\"\n        exchange_lines define the input lines for each inlet.\n\n        If end_points = None, then the culvert_vector is calculated in the\n        directions from the centre of echange_line[0] to centre of exchange_line[1}\n\n        If end_points != None, then culvert_vector is unit vector in direction\n        end_point[1] - end_point[0]\n        \"\"\"\n\n        anuga.Operator.__init__(self,domain)\n\n        self.master_proc = 0\n        self.end_points = ensure_numeric(end_points)\n        self.exchange_lines = ensure_numeric(exchange_lines)\n        self.enquiry_points = ensure_numeric(enquiry_points)\n        self.invert_elevations = ensure_numeric(invert_elevations)\n\n        assert self.end_points is None or self.exchange_lines is None\n\n        \n        if height is None:\n            height = width\n\n        if width is None:\n            width = diameter\n\n        if apron is None:\n            apron = width\n\n\n        assert width is not None\n\n\n        self.width  = width\n        self.height = height\n        self.diameter = diameter\n        self.z1 = z1 \n        self.z2 = z2 \n        self.blockage = blockage \n        self.barrels = barrels\n        self.apron  = apron\n        self.manning = manning\n        self.enquiry_gap = enquiry_gap\n        self.use_momentum_jet = use_momentum_jet\n        self.zero_outflow_momentum = zero_outflow_momentum\n        if use_momentum_jet and zero_outflow_momentum:\n            msg = \"Can't have use_momentum_jet and zero_outflow_momentum both True\"\n            raise Exception(msg)\n        self.use_old_momentum_method = use_old_momentum_method\n        self.always_use_Q_wetdry_adjustment = always_use_Q_wetdry_adjustment\n\n\n        if description is None:\n            self.description = ' '\n        else:\n            self.description = description\n        \n        if label is None:\n            self.label = \"structure_%g\" % Structure_operator.counter\n        else:\n            self.label = label + '_%g' % Structure_operator.counter\n\n        if structure_type is None:\n            self.structure_type = 'generic structure'\n        else:\n            self.structure_type = structure_type\n            \n        self.verbose = verbose        \n        \n        # Keep count of structures\n        Structure_operator.counter += 1\n\n        # Slots for recording current statistics\n        self.accumulated_flow = 0.0\n        self.discharge = 0.0\n        self.discharge_abs_timemean = 0.0\n        self.velocity = 0.0\n        self.outlet_depth = 0.0\n        self.delta_total_energy = 0.0\n        self.driving_energy = 0.0\n        \n        if exchange_lines is not None:\n            self.__process_skew_culvert()\n        elif end_points is not None:\n            self.__process_non_skew_culvert()\n        else:\n            raise Exception('Define either exchange_lines or end_points')\n        \n\n        self.inlets = []\n        line0 = self.exchange_lines[0] #self.inlet_lines[0]\n        if self.apron is None:\n            poly0 = line0\n        else:\n            offset = -self.apron*self.outward_vector_0 \n            #print line0\n            #print offset\n            poly0 = num.array([ line0[0], line0[1], line0[1]+offset, line0[0]+offset])\n            #print poly0\n        if self.invert_elevations is None:\n            invert_elevation0 = None\n        else:\n            invert_elevation0 = self.invert_elevations[0]\n\n        enquiry_point0 = self.enquiry_points[0]\n\n        #outward_vector0 = - self.culvert_vector\n        self.inlets.append(inlet_enquiry.Inlet_enquiry(\n                           self.domain,\n                           poly0,\n                           enquiry_point0,\n                           invert_elevation = invert_elevation0,\n                           outward_culvert_vector = self.outward_vector_0,\n                           verbose = self.verbose))\n\n        if force_constant_inlet_elevations:\n            # Try to enforce a constant inlet elevation \n            inlet_global_elevation = self.inlets[-1].get_average_elevation() \n            self.inlets[-1].set_elevations(inlet_global_elevation)\n\n        tris_0 = self.inlets[0].triangle_indices\n        #print tris_0\n        #print self.domain.centroid_coordinates[tris_0]\n\n        line1 = self.exchange_lines[1]\n        if self.apron is None:\n            poly1 = line1\n        else:\n            offset = -self.apron*self.outward_vector_1\n            #print line1\n            #print offset\n            poly1 = num.array([ line1[0], line1[1], line1[1]+offset, line1[0]+offset])\n            #print poly1\n            \n        if self.invert_elevations is None:\n            invert_elevation1 = None\n        else:\n            invert_elevation1 = self.invert_elevations[1]\n        enquiry_point1 = self.enquiry_points[1]\n\n        self.inlets.append(inlet_enquiry.Inlet_enquiry(\n                           self.domain,\n                           poly1,\n                           enquiry_point1,\n                           invert_elevation = invert_elevation1,\n                           outward_culvert_vector = self.outward_vector_1,\n                           verbose = self.verbose))\n\n        if force_constant_inlet_elevations:\n            # Try to enforce a constant inlet elevation \n            inlet_global_elevation = self.inlets[-1].get_average_elevation() \n            self.inlets[-1].set_elevations(inlet_global_elevation)\n\n        tris_1 = self.inlets[1].triangle_indices\n        \n        self.set_logging(logging)\n\n        \n\n\n\n    def __call__(self):\n\n        timestep = self.domain.get_timestep()\n        \n        Q, barrel_speed, outlet_depth = self.discharge_routine()\n\n        old_inflow_depth = self.inflow.get_average_depth()\n        old_inflow_stage = self.inflow.get_average_stage()\n        old_inflow_xmom = self.inflow.get_average_xmom()\n        old_inflow_ymom = self.inflow.get_average_ymom()\n\n        # Implement the update of flow over a timestep by\n        # using a semi-implict update. This ensures that\n        # the update does not create a negative depth\n        if old_inflow_depth > 0.0 :\n            dt_Q_on_d = old_div(timestep*Q,old_inflow_depth)\n        else:\n            dt_Q_on_d = 0.0\n\n        always_use_Q_wetdry_adjustment = self.always_use_Q_wetdry_adjustment\n        use_Q_wetdry_adjustment = ((always_use_Q_wetdry_adjustment) |\\\n            (old_inflow_depth*self.inflow.get_area() <= Q*timestep))\n        # If we use the 'Q_adjustment', then the discharge is rescaled so that\n        # the depth update is: \n        #    new_inflow_depth*inflow_area = \n        #    old_inflow_depth*inflow_area - \n        #    timestep*Q*(new_inflow_depth/old_inflow_depth)\n        # The last term in () is a wet-dry improvement trick (which rescales Q)\n        #\n        # Before Feb 2015 this rescaling was always done (even if the flow was\n        # not near wet-dry). Now if use_old_Q_adjustment=False, the rescaling\n        # is only done if required to avoid drying\n        #\n        #\n        factor = 1.0/(1.0 + old_div(dt_Q_on_d,self.inflow.get_area()))\n\n\n        if use_Q_wetdry_adjustment:\n            # FIXME:\n            new_inflow_depth = old_inflow_depth*factor\n\n            if(old_inflow_depth>0.):\n                timestep_star = old_div(timestep*new_inflow_depth,old_inflow_depth)\n            else:\n                timestep_star = 0.\n\n        else:\n            new_inflow_depth = old_inflow_depth - old_div(timestep*Q,self.inflow.get_area())\n            timestep_star = timestep\n\n        if(self.use_old_momentum_method):\n            # This method is here for consistency with the old version of the\n            # routine\n            new_inflow_xmom = old_inflow_xmom*factor\n            new_inflow_ymom = old_inflow_ymom*factor\n\n        else:\n            # For the momentum balance, note that Q also advects the momentum,\n            # The volumetric momentum flux should be Q*momentum/depth, where\n            # momentum has an average value of new_inflow_mom (or\n            # old_inflow_mom).  We use old_inflow_depth for depth\n            #\n            #     new_inflow_xmom*inflow_area = \n            #     old_inflow_xmom*inflow_area - \n            #     [timestep*Q]*new_inflow_xmom/old_inflow_depth\n            # and:\n            #     new_inflow_ymom*inflow_area = \n            #     old_inflow_ymom*inflow_area - \n            #     [timestep*Q]*new_inflow_ymom/old_inflow_depth\n            #\n            # The units balance: m^2/s*m^2 = m^2/s*m^2 - s*m^3/s*m^2/s *m^(-1)\n            #\n            if old_inflow_depth > 0.:\n                if use_Q_wetdry_adjustment:\n                    # Replace dt*Q with dt*Q*new_inflow_depth/old_inflow_depth = dt_Q_on_d*new_inflow_depth\n                    factor2 = 1.0/(1.0 + old_div(dt_Q_on_d*new_inflow_depth,(old_inflow_depth*self.inflow.get_area())))\n                else:\n                    factor2 = 1.0/(1.0 + old_div(timestep*Q,(old_inflow_depth*self.inflow.get_area())))\n            else:\n                factor2 = 0.\n\n            new_inflow_xmom = old_inflow_xmom*factor2\n            new_inflow_ymom = old_inflow_ymom*factor2\n        \n        self.inflow.set_depths(new_inflow_depth)\n\n        #inflow.set_xmoms(Q/inflow.get_area())\n        #inflow.set_ymoms(0.0)\n\n        self.inflow.set_xmoms(new_inflow_xmom)\n        self.inflow.set_ymoms(new_inflow_ymom)\n\n        loss = (old_inflow_depth - new_inflow_depth)*self.inflow.get_area()\n        xmom_loss = (old_inflow_xmom - new_inflow_xmom)*self.inflow.get_area()\n        ymom_loss = (old_inflow_ymom - new_inflow_ymom)*self.inflow.get_area()\n\n        # set outflow\n        outflow_extra_depth = old_div(Q*timestep_star,self.outflow.get_area())\n        outflow_direction = - self.outflow.outward_culvert_vector\n        #outflow_extra_momentum = outflow_extra_depth*barrel_speed*outflow_direction\n            \n        gain = outflow_extra_depth*self.outflow.get_area()\n        \n        #print gain, loss\n        assert num.allclose(gain-loss, 0.0)\n            \n        # Stats\n        self.accumulated_flow += gain\n        self.discharge  = old_div(Q*timestep_star,timestep) \n        self.discharge_abs_timemean += old_div(gain,self.domain.yieldstep)\n        self.velocity =   barrel_speed\n        self.outlet_depth = outlet_depth\n\n        new_outflow_depth = self.outflow.get_average_depth() + outflow_extra_depth\n\n        self.outflow.set_depths(new_outflow_depth)\n\n        if self.use_momentum_jet:\n            # FIXME (SR) Review momentum to account for possible hydraulic jumps at outlet\n            # FIXME (GD) Depending on barrel speed I think this will be either\n            # a source or sink of momentum (considering the momentum losses\n            # above). Might not always be reasonable.\n            #new_outflow_xmom = self.outflow.get_average_xmom() + outflow_extra_momentum[0]\n            #new_outflow_ymom = self.outflow.get_average_ymom() + outflow_extra_momentum[1]\n            new_outflow_xmom = barrel_speed*new_outflow_depth*outflow_direction[0]\n            new_outflow_ymom = barrel_speed*new_outflow_depth*outflow_direction[1]\n            \n        elif self.zero_outflow_momentum:\n            new_outflow_xmom = 0.0\n            new_outflow_ymom = 0.0\n            #new_outflow_xmom = outflow.get_average_xmom()\n            #new_outflow_ymom = outflow.get_average_ymom()\n\n        else:\n            # Add the momentum lost from the inflow to the outflow. For\n            # structures where barrel_speed is unknown + direction doesn't\n            # change from inflow to outflow\n            new_outflow_xmom = self.outflow.get_average_xmom() + old_div(xmom_loss,self.outflow.get_area())\n            new_outflow_ymom = self.outflow.get_average_ymom() + old_div(ymom_loss,self.outflow.get_area())\n\n        self.outflow.set_xmoms(new_outflow_xmom)\n        self.outflow.set_ymoms(new_outflow_ymom)\n\n\n\n    def set_culvert_height(self, height):\n\n        self.culvert_height = height\n\n    def set_culvert_width(self, width):\n\n        self.culvert_width = width\n        \n    def set_culvert_z1(self, z1): \n\n        self.culvert_z1 = z1 \n\n    def set_culvert_z2(self, z2):\n\n        self.culvert_z2 = z2\n        \n    def set_culvert_blockage(self, blockage): \n\n        self.culvert_blockage = blockage \n\n    def set_culvert_barrels(self, barrels): \n\n        self.culvert_barrels = barrels \n        \n        \n    def __process_non_skew_culvert(self):\n\n        \"\"\"Create lines at the end of a culvert inlet and outlet.\n        At either end two lines will be created; one for the actual flow to pass through and one a little further away\n        for enquiring the total energy at both ends of the culvert and transferring flow.\n        \"\"\"\n        \n        self.culvert_vector = self.end_points[1] - self.end_points[0]\n        self.culvert_length = math.sqrt(num.sum(self.culvert_vector**2))   \n        assert self.culvert_length > 0.0, 'The length of culvert is less than 0'\n        \n        self.culvert_vector /= self.culvert_length\n        self.outward_vector_0 =   self.culvert_vector\n        self.outward_vector_1 = - self.culvert_vector\n\n        \n        culvert_normal = num.array([-self.culvert_vector[1], self.culvert_vector[0]])  # Normal vector\n        w = 0.5*self.width*culvert_normal # Perpendicular vector of 1/2 width\n\n        self.exchange_lines = []\n\n        # Build exchange polyline and enquiry point\n        if self.enquiry_points is None:\n            \n            gap = (self.apron + self.enquiry_gap)*self.culvert_vector\n            self.enquiry_points = []\n            \n            for i in [0, 1]:\n                p0 = self.end_points[i] + w\n                p1 = self.end_points[i] - w\n                self.exchange_lines.append(num.array([p0, p1]))\n                ep = self.end_points[i] + (2*i - 1)*gap #(2*i - 1) determines the sign of the points\n                self.enquiry_points.append(ep)\n            \n        else:            \n            for i in [0, 1]:\n                p0 = self.end_points[i] + w\n                p1 = self.end_points[i] - w\n                self.exchange_lines.append(num.array([p0, p1]))\n            \n  \n    def __process_skew_culvert(self):    \n        \n        \"\"\"Compute skew culvert.\n        If exchange lines are given, the enquiry points are determined. This is for enquiring \n        the total energy at both ends of the culvert and transferring flow.\n        \"\"\"\n            \n        centre_point0 = 0.5*(self.exchange_lines[0][0] + self.exchange_lines[0][1])\n        centre_point1 = 0.5*(self.exchange_lines[1][0] + self.exchange_lines[1][1])\n\n        n_exchange_0 = len(self.exchange_lines[0])\n        n_exchange_1 = len(self.exchange_lines[1])\n\n        assert n_exchange_0 == n_exchange_1, 'There should be the same number of points in both exchange_lines'\n\n        if n_exchange_0 == 2:\n        \n            if self.end_points is None:\n                self.culvert_vector = centre_point1 - centre_point0\n            else:\n                self.culvert_vector = self.end_points[1] - self.end_points[0]\n\n            self.outward_vector_0 =   self.culvert_vector\n            self.outward_vector_1 = - self.culvert_vector\n\n\n        elif n_exchange_0 == 4:\n\n            self.outward_vector_0 = self.exchange_lines[0][3] - self.exchange_lines[0][2]\n            self.outward_vector_1 = self.exchange_lines[1][3] - self.exchange_lines[1][2]\n\n            self.culvert_vector = centre_point1 - centre_point0\n\n        else:\n            raise Exception('n_exchange_0 != 2 or 4')\n\n\n        self.culvert_length = math.sqrt(num.sum(self.culvert_vector**2))\n        assert self.culvert_length > 0.0, 'The length of culvert is less than 0'\n        self.culvert_vector /= self.culvert_length\n\n        outward_vector_0_length = math.sqrt(num.sum(self.outward_vector_0**2))\n        assert outward_vector_0_length > 0.0, 'The length of outlet_vector_0 is less than 0'\n        self.outward_vector_0 /= outward_vector_0_length\n\n        outward_vector_1_length = math.sqrt(num.sum(self.outward_vector_1**2))\n        assert outward_vector_1_length > 0.0, 'The length of outlet_vector_1 is less than 0'\n        self.outward_vector_1 /= outward_vector_1_length\n\n\n        if self.enquiry_points is None:\n        \n            gap = (self.apron + self.enquiry_gap)*self.culvert_vector\n        \n            self.enquiry_points = []\n\n            self.enquiry_points.append(centre_point0 - gap)\n            self.enquiry_points.append(centre_point1 + gap)\n            \n\n    def discharge_routine(self):\n\n        msg = 'Need to implement '\n        raise\n            \n\n    def statistics(self):\n\n\n        message  = '=====================================\\n'\n        message += 'Structure Operator: %s\\n' % self.label\n        message += '=====================================\\n'\n\n        message += 'Structure Type: %s\\n' % self.structure_type\n\n        message += 'Description\\n'\n        message += '%s' % self.description\n        \n        #add the culvert dimensions, blockage factor here\n        if self.structure_type == 'boyd_pipe':\n            message += 'Culvert Diameter: %s\\n'% self.diameter\n            message += 'Culvert Blockage: %s\\n'% self.blockage\n            message += 'No.  of  barrels: %s\\n'% self.barrels\n        elif self.structure_type == 'boyd_box':\n            message += 'Culvert  Height: %s\\n'% self.height\n            message += 'Culvert    Width: %s\\n'% self.width\n            message += 'Culvert Blockage: %s\\n'% self.blockage\n            message += 'No.  of  barrels: %s\\n'% self.barrels\n        else:\n            message += 'Culvert Height: %s\\n'% self.height\n            message += 'Culvert  Width: %s\\n'% self.width\n            message += 'Batter Slope 1: %s\\n'% self.z1\n            message += 'Batter Slope 2: %s\\n'% self.z2\n            message += 'Culvert Blockage: %s\\n'% self.blockage\n            message += 'No.  of  barrels: %s\\n'% self.barrels\n            \n        message += '\\n'\n        \n        for i, inlet in enumerate(self.inlets):\n            message += '-------------------------------------\\n'\n            message +=  'Inlet %i\\n' % i\n            message += '-------------------------------------\\n'\n\n            message += 'inlet triangle indices and centres and elevations\\n'\n            message += '%s' % inlet.triangle_indices\n            message += '\\n'\n            \n            message += '%s' % self.domain.get_centroid_coordinates()[inlet.triangle_indices]\n            message += '\\n'\n\n            elev = self.domain.quantities['elevation'].centroid_values[inlet.triangle_indices]\n            message += '%s' % elev\n            message += '\\n'\n           \n            elevation_range = elev.max() - elev.min() \n            if not num.allclose(elevation_range, 0.):\n                message += 'Warning: non-constant inlet elevation can cause well-balancing problems'\n\n            message += 'region\\n'\n            message += '%s' % inlet.region\n            message += '\\n'\n\n        message += '=====================================\\n'\n\n        return message\n\n\n    def print_statistics(self):\n\n        print(self.statistics())\n\n\n    def print_timestepping_statistics(self):\n\n        message = '---------------------------\\n'\n        message += 'Structure report for %s:\\n' % self.label\n        message += '--------------------------\\n'\n        message += 'Type: %s\\n' % self.structure_type\n        \n        message += 'inlets[0]_enquiry_depth [m]:  %.2f\\n' %self.inlets[0].get_enquiry_depth()\n        message += 'inlets[0]_enquiry_speed [m/s]:  %.2f\\n' %self.inlets[0].get_enquiry_speed()\n        message += 'inlets[0]_enquiry_stage [m]:  %.2f\\n' %self.inlets[0].get_enquiry_stage()\n        message += 'inlets[0]_enquiry_elevation [m]:  %.2f\\n' %self.inlets[0].get_enquiry_elevation()\n        message += 'inlets[0]_average_depth [m]:  %.2f\\n' %self.inlets[0].get_average_depth()\n        message += 'inlets[0]_average_speed [m/s]:  %.2f\\n' %self.inlets[0].get_average_speed()\n        message += 'inlets[0]_average_stage [m]:  %.2f\\n' %self.inlets[0].get_average_stage()\n        message += 'inlets[0]_average_elevation [m]:  %.2f\\n' %self.inlets[0].get_average_elevation()\n\n        message += '\\n'\n       \n        message += 'inlets[1]_enquiry_depth [m]:  %.2f\\n' %self.inlets[1].get_enquiry_depth()\n        message += 'inlets[1]_enquiry_speed [m/s]:  %.2f\\n' %self.inlets[1].get_enquiry_speed()\n        message += 'inlets[1]_enquiry_stage [m]:  %.2f\\n' %self.inlets[1].get_enquiry_stage()\n        message += 'inlets[1]_enquiry_elevation [m]:  %.2f\\n' %self.inlets[1].get_enquiry_elevation()\n\n        message += 'inlets[1]_average_depth [m]:  %.2f\\n' %self.inlets[1].get_average_depth()\n        message += 'inlets[1]_average_speed [m/s]:  %.2f\\n' %self.inlets[1].get_average_speed()\n        message += 'inlets[1]_average_stage [m]:  %.2f\\n' %self.inlets[1].get_average_stage()\n        message += 'inlets[1]_average_elevation [m]:  %.2f\\n' %self.inlets[1].get_average_elevation()\n\n        \n        message += 'Discharge [m^3/s]: %.2f\\n' % self.discharge\n        message += 'Discharge_function_value [m^3/s]: %.2f\\n' % self.discharge_abs_timemean\n        message += 'Velocity  [m/s]: %.2f\\n' % self.velocity\n        message += 'Outlet Depth  [m]: %.2f\\n' % self.outlet_depth\n        message += 'Accumulated Flow [m^3]: %.2f\\n' % self.accumulated_flow\n        message += 'Inlet Driving Energy %.2f\\n' % self.driving_energy\n        message += 'Delta Total Energy %.2f\\n' % self.delta_total_energy\n        message += 'Control at this instant: %s\\n' % self.case\n        \n\n\n\n        print(message)\n\n\n    def set_logging(self, flag=True):\n\n        self.logging = flag\n\n        # If flag is true open file with mode = \"w\" to form a clean file for logging\n        if self.logging:\n            self.log_filename = self.domain.get_datadir() + '/' + self.label + '.log'\n            log_to_file(self.log_filename, self.statistics(), mode='w')\n            log_to_file(self.log_filename, 'time, discharge_instantaneous, discharge_abs_timemean, velocity, accumulated_flow, driving_energy_instantaneous, delta_total_energy_instantaneous')\n\n            #log_to_file(self.log_filename, self.culvert_type)\n\n\n    def timestepping_statistics(self):\n\n        message  = '%.5f, ' % self.domain.get_time()\n        message += '%.5f, ' % self.discharge\n        message += '%.5f, ' % self.discharge_abs_timemean\n        message += '%.5f, ' % self.velocity\n        message += '%.5f, ' % self.accumulated_flow\n        message += '%.5f, ' % self.driving_energy\n        message += '%.5f' % self.delta_total_energy\n       \n        # Reset discharge_abs_timemean since last time this function was called\n        # (FIXME: This assumes that the function is called only just after a\n        # yield step)\n        self.discharge_abs_timemean = 0.\n\n        return message\n\n\n    def get_inlets(self):\n        \n        return self.inlets\n        \n        \n    def get_culvert_length(self):\n        \n        return self.culvert_length\n    \n    \n    \n    def get_culvert_slope(self):\n        \n        inlet0 = self.inlets[0]\n        inlet1 = self.inlets[1]\n        \n        elev0 = inlet0.get_enquiry_invert_elevation()\n        elev1 = inlet1.get_enquiry_invert_elevation()\n        \n        return old_div((elev1-elev0),self.get_culvert_length())\n                          \n                          \n        \n    def get_culvert_width(self):\n        \n        return self.width\n        \n        \n    def get_culvert_diameter(self):\n    \n            return self.diameter\n        \n        \n    def get_culvert_height(self):\n    \n        return self.height\n\n    def get_culvert_z1(self):\n    \n        return self.z1 \n\n    def get_culvert_z2(self):\n    \n        return self.z2\n\n    def get_culvert_blockage(self):\n\t\t\n        return self.blockage \n\n    def get_culvert_barrels(self):\n\t\t\n        return self.barrels\n                       \n    def get_culvert_apron(self):\n\n        return self.apron\n\n\n    def get_master_proc(self):\n\n        return 0\n\n\n\n    #--------------------------------------------------------\n    # Set of enquiry functions so that in the sequential and paralle case\n    # we can get equiry info fron the master Proc\n    #---------------------------------------------------------\n\n    def get_enquiry_stages(self):\n\n        enq0 = self.inlets[0].get_enquiry_stage()\n        enq1 = self.inlets[1].get_enquiry_stage()\n\n        return [enq0, enq1]\n\n\n    def get_enquiry_depths(self):\n\n        enq0 = self.inlets[0].get_enquiry_depth()\n        enq1 = self.inlets[1].get_enquiry_depth()\n\n        return [enq0, enq1]\n\n\n    def get_enquiry_positions(self):\n\n        enq0 = self.inlets[0].get_enquiry_position()\n        enq1 = self.inlets[1].get_enquiry_position()\n\n        return [enq0, enq1]\n\n\n    def get_enquiry_xmoms(self):\n\n        enq0 = self.inlets[0].get_enquiry_xmom()\n        enq1 = self.inlets[1].get_enquiry_xmom()\n\n        return [enq0, enq1]\n\n    def get_enquiry_ymoms(self):\n\n        enq0 = self.inlets[0].get_enquiry_ymom()\n        enq1 = self.inlets[1].get_enquiry_ymom()\n\n        return [enq0, enq1]\n\n\n    def get_enquiry_elevations(self):\n\n        enq0 = self.inlets[0].get_enquiry_elevation()\n        enq1 = self.inlets[1].get_enquiry_elevation()\n\n        return [enq0, enq1]\n\n\n\n    def get_enquiry_water_depths(self):\n\n        enq0 = self.inlets[0].get_enquiry_water_depth()\n        enq1 = self.inlets[1].get_enquiry_water_depth()\n\n        return [enq0, enq1]\n\n\n    def get_enquiry_invert_elevations(self):\n\n        enq0 = self.inlets[0].get_enquiry_invert_elevation()\n        enq1 = self.inlets[1].get_enquiry_invert_elevation()\n\n        return [enq0, enq1]\n\n\n    def get_enquiry_velocitys(self):\n\n        enq0 = self.inlets[0].get_enquiry_velocity()\n        enq1 = self.inlets[1].get_enquiry_velocity()\n\n        return [enq0, enq1]\n\n\n    def get_enquiry_xvelocitys(self):\n\n        enq0 = self.inlets[0].get_enquiry_xvelocity()\n        enq1 = self.inlets[1].get_enquiry_xvelocity()\n\n        return [enq0, enq1]\n\n    def get_enquiry_yvelocitys(self):\n\n        enq0 = self.inlets[0].get_enquiry_yvelocity()\n        enq1 = self.inlets[1].get_enquiry_yvelocity()\n\n        return [enq0, enq1]\n\n\n    def get_enquiry_speeds(self):\n\n        enq0 = self.inlets[0].get_enquiry_speed()\n        enq1 = self.inlets[1].get_enquiry_speed()\n\n        return [enq0, enq1]\n\n\n    def get_enquiry_velocity_heads(self):\n\n        enq0 = self.inlets[0].get_enquiry_velocity_head()\n        enq1 = self.inlets[1].get_enquiry_velocity_head()\n\n        return [enq0, enq1]\n\n\n    def get_enquiry_total_energys(self):\n\n        enq0 = self.inlets[0].get_enquiry_total_energy()\n        enq1 = self.inlets[1].get_enquiry_total_energy()\n\n        return [enq0, enq1]\n\n\n    def get_enquiry_specific_energys(self):\n\n        enq0 = self.inlets[0].get_enquiry_specific_energy()\n        enq1 = self.inlets[1].get_enquiry_specific_energy()\n\n        return [enq0, enq1]\n\n", "meta": {"hexsha": "41f954152cd8035300d2642125ae1d6c0ed80aff", "size": 28546, "ext": "py", "lang": "Python", "max_stars_repo_path": "anuga/structures/structure_operator.py", "max_stars_repo_name": "samcom12/anuga_core", "max_stars_repo_head_hexsha": "f4378114dbf02d666fe6423de45798add5c42806", "max_stars_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_stars_count": 136, "max_stars_repo_stars_event_min_datetime": "2015-05-07T05:47:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T03:07:40.000Z", "max_issues_repo_path": "anuga/structures/structure_operator.py", "max_issues_repo_name": "samcom12/anuga_core", "max_issues_repo_head_hexsha": "f4378114dbf02d666fe6423de45798add5c42806", "max_issues_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_issues_count": 184, "max_issues_repo_issues_event_min_datetime": "2015-05-03T09:27:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-20T04:22:48.000Z", "max_forks_repo_path": "anuga/structures/structure_operator.py", "max_forks_repo_name": "samcom12/anuga_core", "max_forks_repo_head_hexsha": "f4378114dbf02d666fe6423de45798add5c42806", "max_forks_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_forks_count": 70, "max_forks_repo_forks_event_min_datetime": "2015-03-18T07:35:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T07:07:29.000Z", "avg_line_length": 34.6852976914, "max_line_length": 191, "alphanum_fraction": 0.5971414559, "include": true, "reason": "import numpy", "num_tokens": 7113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.19614042734468984}}
{"text": "\"\"\"\nContains RDKit-related functions.\n\"\"\"\n\n# for handling ligand data and calculating ligand-related properties\nfrom rdkit import Chem  \nfrom rdkit.Chem import Draw, AllChem, Descriptors\nimport numpy as np  # for some more functionalities when using Pandas (e.g. for handling NaN values)\n\n\ndef create_molecule_object(input_type, input_value):\n    \"\"\"\n    This class is used to create an RDKit molecule object from various sources.\n    It can be used to calculate or retrieve properties and descriptors (MW, h-bonds, etc.),\n    generate images or SDF files or to perform similarity searches.\n\n    Parameters\n    ----------\n    input_type : str\n        Type of the input.\n        Allowed input-types are: 'smiles', 'inchi', 'smarts', 'pdb_file'\n    input_value : str\n        Value of the corresponding input type.\n\n    Returns\n    -------\n    rdkit.Chem.rdchem.Mol\n        Structure as RDKit molecule object.\n    \"\"\"\n\n    functions = {\n        \"smiles\": Chem.MolFromSmiles,\n        \"inchi\": Chem.MolFromInchi,\n        \"smarts\": Chem.MolFromSmarts,\n        \"pdb_file\": Chem.MolFromPDBFile,\n    }\n    Molobj = functions[input_type](input_value)\n    Molobj.smiles = Chem.MolToSmiles(Molobj)\n    return Molobj\n\n\ndef draw_molecules(\n    list_mol_objs,\n    list_legends=None,\n    mols_per_row=3,\n    sub_img_size=(350, 350),\n    filepath=None,\n):\n    \"\"\"\n    Take a list of RDKit molecule objects and draws them as a grid image.\n\n    Parameters\n    ----------\n    list_mol_objs: list\n        List of RDKit molecule objects to be drawn.\n    list_legends: list\n        Optional; default: None\n        List of legends for the molecules.\n        If not provided, the list indices (+1) will be used as legends.\n    mols_per_row : int\n        Optional; default: 3\n        Number of structures to show per row.\n    sub_img_size : tuple (int, int)\n        Optional; default: (350, 350)\n        Size of each structure.\n    filepath : str or pathlib.Path\n        Full filepath to save the image in.\n\n    Returns\n    -------\n    rdkit.Chem.Draw.MolsToGridImage\n        Molecules shown as grid.\n    \"\"\"\n    if list_legends is None:\n        list_legends = list(map(str, range(1, len(list_mol_objs) + 1)))\n    figure = Draw.MolsToGridImage(\n        list_mol_objs,\n        molsPerRow=mols_per_row,\n        subImgSize=sub_img_size,\n        legends=list(map(str, list_legends)),\n    )\n    if filepath is not None:\n        with open(f\"{filepath}.png\", \"wb\") as f:\n            f.write(figure.data)\n    return figure\n\n\ndef save_molecule_image_to_file(mol_obj, filepath):\n    \"\"\"\n    Save the image of a single molecule as a PNG file.\n\n    Parameters\n    ----------\n    mol_obj : rdkit.Chem.rdchem.Mol\n        The molecule to be saved as image.\n    filepath : str or pathlib.Path\n        Full filpath to save the image in.\n    \"\"\"\n    Draw.MolToFile(mol_obj, f\"{filepath}.png\")\n\n\ndef save_3D_molecule_to_SDfile(mol_obj, filepath):\n    \"\"\"\n    Generate a 3D conformer and save as SDF file.\n\n    Parameters\n    ----------\n    mol_obj : rdkit.Chem.rdchem.Mol\n        The molecule to be saved as SDF file.\n    filepath : str or pathlib.Path\n        Full filpath to save the image in.\n    \"\"\"\n    mol = Chem.AddHs(mol_obj)\n    embedding = AllChem.EmbedMolecule(mol, maxAttempts=1000, clearConfs=True)\n    uffoptim = AllChem.UFFOptimizeMolecule(mol, maxIters=1000)\n    # check if calculations converged (both should return 0 when converged)\n    if embedding + uffoptim != 0:\n        raise ValueError(\"Embedding/Optimization failed to converge.\")\n    session = Chem.SDWriter(f\"{filepath}.sdf\")\n    session.write(mol)\n    session.close()\n\n\ndef calculate_similarity_dice(mol_obj1, mol_obj2, morgan_radius=2, morgan_nbits=4096):\n    \"\"\"\n    Calculate the Dice similarity between two molecules,\n    based on 4096-bit Morgan fingerprints with a radius of 2.\n\n    Parameters\n    ----------\n    mol_obj1 : rdkit.Chem.rdchem.Mol\n        The first molecule.\n    mol_obj2 : rdkit.Chem.rdchem.Mol\n        The second molecule.\n    morgan_radius : int\n        Optional; default: 2\n        The radius used to generate Morgan fingerprints.\n    morgan_nbits : int\n        Optional; default: 4096\n        The number of bits in the Morgan fingerprints.\n    Returns\n    -------\n    float\n        Dice similarity between the two molecules rounded to two decimal places.\n    \"\"\"\n    morgan_fp_mol1 = AllChem.GetMorganFingerprintAsBitVect(\n        mol_obj1, radius=morgan_radius, nBits=morgan_nbits\n    )\n    morgan_fp_mol2 = AllChem.GetMorganFingerprintAsBitVect(\n        mol_obj2, radius=morgan_radius, nBits=morgan_nbits\n    )\n    dice_similarity = round(\n        AllChem.DataStructs.DiceSimilarity(morgan_fp_mol1, morgan_fp_mol2), 2\n    )\n    return dice_similarity\n\n\ndef calculate_druglikeness(mol_obj):\n    \"\"\"\n    Calculate several molecular properties and drug-likeness scores,\n    from an RDKit molecule object.\n\n    Parameters\n    ----------\n    mol_obj: rdkit.Chem.rdchem.Mol\n        Molecule object of interest.\n\n    Returns\n    -------\n    dict\n        The calculated values are returned in a dictionary with following keys:\n        MolWt, NumHAcceptors, NumHDonors, MolLogP, TPSA, NumRotBonds, Saturation,\n        lipinski_score, custom_drug_score, qed_score, total_drug_score\n    \"\"\"\n    properties = {\n        \"mol_weight\": round(Descriptors.MolWt(mol_obj), 3),\n        \"num_H_acceptors\": Descriptors.NumHAcceptors(mol_obj),\n        \"num_H_donors\": Descriptors.NumHDonors(mol_obj),\n        \"logp\": round(Descriptors.MolLogP(mol_obj), 2),\n        \"tpsa\": round(Descriptors.TPSA(mol_obj), 2),\n        \"num_rot_bonds\": Descriptors.NumRotatableBonds(mol_obj),\n        \"saturation\": round(Descriptors.FractionCSP3(mol_obj), 2),\n        \"drug_score_qed\": round(Descriptors.qed(mol_obj), 2),\n    }\n\n    # Calculating Lipinski score\n    l1 = int(properties[\"mol_weight\"] < 500)\n    l2 = int(properties[\"num_H_acceptors\"] <= 10)\n    l3 = int(properties[\"num_H_donors\"] <= 5)\n    l4 = int(properties[\"logp\"] < 5)\n    properties[\"drug_score_lipinski\"] = round((l1 + l2 + l3 + l4) / 4, 2)\n\n    # Calculating druglikeness score with custom scoring functions\n    # derived from Hopkins paper: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3524573/\n    def molWt_score(molWt):\n        if molWt <= 440:\n            return np.exp(-((molWt - 300) ** 2) / 15000)\n        else:\n            return np.exp(-(molWt - 180) / 190) + 0.01\n\n    def molLogP_score(molLogP):\n        return np.exp(-((molLogP - 2.5) ** 2) / 9)\n\n    def numHDonors_score(numHDonors):\n        if numHDonors == 0:\n            return 0.6\n        elif numHDonors < 5:\n            return np.exp(-((numHDonors - 1) ** 2) / 5)\n        else:\n            return np.exp(-((numHDonors - 1) ** 2) / 5) + (0.4 / numHDonors)\n\n    def numHAcceptors_score(numHAcceptors):\n        if numHAcceptors < 4:\n            return np.exp(-((numHAcceptors - 3) ** 2) / 3)\n        else:\n            return np.exp(-0.3 * numHAcceptors / 0.8 + 1.4)\n\n    def TPSA_score(TPSA):\n        if TPSA < 50:\n            return 0.015 * TPSA + 0.25\n        else:\n            return np.exp(-((TPSA - 50) ** 2) / 8000)\n\n    def numRotBonds_score(numRotBonds):\n        if numRotBonds < 10:\n            return np.exp(-((numRotBonds - 4) ** 2) / 19)\n        else:\n            return np.exp(-((numRotBonds - 4) ** 2) / 19) + (1.5 / numRotBonds ** 1.5)\n\n    def saturation_score(saturation):\n        return np.exp(-((saturation - 0.625) ** 2) / 0.05)\n\n    d1 = molWt_score(properties[\"mol_weight\"])\n    d2 = numHAcceptors_score(properties[\"num_H_acceptors\"])\n    d3 = numHDonors_score(properties[\"num_H_donors\"])\n    d4 = molLogP_score(properties[\"logp\"])\n    d5 = TPSA_score(properties[\"tpsa\"])\n    d6 = numRotBonds_score(properties[\"num_rot_bonds\"])\n    d7 = saturation_score(properties[\"saturation\"])\n    properties[\"drug_score_custom\"] = round((d1 + d2 + d3 + d4 + d5 + d6 + d7) / 7, 2)\n\n    properties[\"drug_score_total\"] = round(\n        (\n            3 * properties[\"drug_score_qed\"]\n            + 2 * properties[\"drug_score_custom\"]\n            + properties[\"drug_score_lipinski\"]\n        )\n        / 6,\n        2,\n    )\n    return properties\n", "meta": {"hexsha": "c0e186e94c7c79d96614c3e1d00b2308cf391c21", "size": 8111, "ext": "py", "lang": "Python", "max_stars_repo_path": "teachopencadd/talktorials/T018_automated_cadd_pipeline/utils/helpers/rdkit.py", "max_stars_repo_name": "volkamerlab/TeachOpenCADD", "max_stars_repo_head_hexsha": "bccfe61e03b14278e19baa30fc60c9e4a26b3047", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 155, "max_stars_repo_stars_event_min_datetime": "2018-11-09T16:54:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-26T16:19:54.000Z", "max_issues_repo_path": "teachopencadd/talktorials/T018_automated_cadd_pipeline/utils/helpers/rdkit.py", "max_issues_repo_name": "volkamerlab/TeachOpenCADD", "max_issues_repo_head_hexsha": "bccfe61e03b14278e19baa30fc60c9e4a26b3047", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2019-04-10T01:12:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-26T12:51:15.000Z", "max_forks_repo_path": "teachopencadd/talktorials/T018_automated_cadd_pipeline/utils/helpers/rdkit.py", "max_forks_repo_name": "volkamerlab/TeachOpenCADD", "max_forks_repo_head_hexsha": "bccfe61e03b14278e19baa30fc60c9e4a26b3047", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2018-12-01T14:13:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-26T08:41:23.000Z", "avg_line_length": 32.1865079365, "max_line_length": 100, "alphanum_fraction": 0.6360498089, "include": true, "reason": "import numpy", "num_tokens": 2269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.19614042734468984}}
{"text": "import random\n\nimport numpy as np\n\nfrom .meta_gf import GFMeta\nfrom .linalg import dot, inner, outer, matrix_rank, solve, inv, det, row_reduce, lu_decompose, lup_decompose\nfrom .overrides import set_module\nfrom .poly_conversion import integer_to_poly, poly_to_str, str_to_integer\n\n__all__ = [\"GFArray\"]\n\n\nUNSUPPORTED_ONE_ARG_FUNCTIONS = [\n    np.packbits, np.unpackbits,\n    np.unwrap,\n    np.around, np.round_, np.fix,\n    np.gradient, np.trapz,\n    np.i0, np.sinc,\n    np.angle, np.real, np.imag, np.conj, np.conjugate,\n]\n\nUNSUPPORTED_TWO_ARG_FUNCTIONS = [\n    np.lib.scimath.logn,\n    np.cross,\n]\n\nUNSUPPORTED_FUNCTIONS = UNSUPPORTED_ONE_ARG_FUNCTIONS + UNSUPPORTED_TWO_ARG_FUNCTIONS\n\nOVERRIDDEN_FUNCTIONS = {\n    np.dot: dot,\n    np.inner: inner,\n    np.outer: outer,\n    # np.tensordot: \"tensordot\",\n    np.linalg.matrix_rank: matrix_rank,\n    np.linalg.inv: inv,\n    np.linalg.det: det,\n    np.linalg.solve: solve\n}\n\nFUNCTIONS_REQUIRING_VIEW = [\n    np.copy, np.concatenate,\n    np.broadcast_to,\n    np.trace,\n]\n\nUNSUPPORTED_ONE_ARG_UFUNCS = [\n    np.invert, np.sqrt,\n    np.log2, np.log10,\n    np.exp, np.expm1, np.exp2,\n    np.sin, np.cos, np.tan,\n    np.sinh, np.cosh, np.tanh,\n    np.arcsin, np.arccos, np.arctan,\n    np.arcsinh, np.arccosh, np.arctanh,\n    np.degrees, np.radians,\n    np.deg2rad, np.rad2deg,\n    np.floor, np.ceil, np.trunc, np.rint,\n]\n\nUNSUPPORTED_TWO_ARG_UFUNCS = [\n    np.hypot, np.arctan2,\n    np.logaddexp, np.logaddexp2,\n    np.remainder,\n    np.fmod, np.modf,\n    np.fmin, np.fmax,\n]\n\nUNSUPPORTED_UFUNCS = UNSUPPORTED_ONE_ARG_UFUNCS + UNSUPPORTED_TWO_ARG_UFUNCS\n\nOVERRIDDEN_UFUNCS = {\n    np.add: \"_ufunc_add\",\n    np.subtract: \"_ufunc_subtract\",\n    np.multiply: \"_ufunc_multiply\",\n    np.floor_divide: \"_ufunc_divide\",\n    np.true_divide: \"_ufunc_divide\",\n    np.negative: \"_ufunc_negative\",\n    np.reciprocal: \"_ufunc_reciprocal\",\n    np.power: \"_ufunc_power\",\n    np.square: \"_ufunc_square\",\n    np.log: \"_ufunc_log\",\n    np.matmul: \"_ufunc_matmul\",\n}\n\nUFUNCS_REQUIRING_VIEW = [\n    np.bitwise_and, np.bitwise_or, np.bitwise_xor,\n    np.left_shift, np.right_shift,\n]\n\n\n@set_module(\"galois\")\nclass GFArray(np.ndarray, metaclass=GFMeta):\n    \"\"\"\n    Create an array over :math:`\\\\mathrm{GF}(p^m)`.\n\n    The :obj:`galois.GFArray` class is a parent class for all Galois field array classes. Any Galois field :math:`\\\\mathrm{GF}(p^m)`\n    with prime characteristic :math:`p` and positive integer :math:`m`, can be constructed by calling the class factory\n    `galois.GF(p**m)`.\n\n    Warning\n    -------\n        This is an abstract base class for all Galois field array classes. :obj:`galois.GFArray` cannot be instantiated\n        directly. Instead, Galois field array classes are created using :obj:`galois.GF`.\n\n        For example, one can create the :math:`\\\\mathrm{GF}(7)` field array class as follows:\n\n        .. ipython:: python\n\n            GF7 = galois.GF(7)\n            print(GF7)\n\n        This subclass can then be used to instantiate arrays over :math:`\\\\mathrm{GF}(7)`.\n\n        .. ipython:: python\n\n            GF7([3,5,0,2,1])\n            GF7.Random((2,5))\n\n    :obj:`galois.GFArray` is a subclass of :obj:`numpy.ndarray`. The :obj:`galois.GFArray` constructor has the same syntax as\n    :obj:`numpy.array`. The returned :obj:`galois.GFArray` object is an array that can be acted upon like any other\n    numpy array.\n\n    Parameters\n    ----------\n    array : array_like\n        The input array to be converted to a Galois field array. The input array is copied, so the original array\n        is unmodified by changes to the Galois field array. Valid input array types are :obj:`numpy.ndarray`,\n        :obj:`list` or :obj:`tuple` of ints or strs, :obj:`int`, or :obj:`str`.\n    dtype : numpy.dtype, optional\n        The :obj:`numpy.dtype` of the array elements. The default is `None` which represents the smallest valid\n        dtype for this class, i.e. the first element in :obj:`galois.GFMeta.dtypes`.\n    copy : bool, optional\n        The `copy` keyword argument from :obj:`numpy.array`. The default is `True` which makes a copy of the input\n        object is it's an array.\n    order : str, optional\n        The `order` keyword argument from :obj:`numpy.array`. Valid values are `\"K\"` (default), `\"A\"`, `\"C\"`, or `\"F\"`.\n    ndmin : int, optional\n        The `ndmin` keyword argument from :obj:`numpy.array`. The minimum number of dimensions of the output.\n        The default is 0.\n\n    Returns\n    -------\n    galois.GFArray\n        The copied input array as a :math:`\\\\mathrm{GF}(p^m)` field array.\n\n    Examples\n    --------\n    Construct various kinds of Galois fields using :obj:`galois.GF`.\n\n    .. ipython:: python\n\n        # Construct a GF(2^m) class\n        GF256 = galois.GF(2**8); print(GF256)\n\n        # Construct a GF(p) class\n        GF571 = galois.GF(571); print(GF571)\n\n        # Construct a very large GF(2^m) class\n        GF2m = galois.GF(2**100); print(GF2m)\n\n        # Construct a very large GF(p) class\n        GFp = galois.GF(36893488147419103183); print(GFp)\n\n    Depending on the field's order (size), only certain `dtype` values will be supported.\n\n    .. ipython:: python\n\n        GF256.dtypes\n        GF571.dtypes\n\n    Very large fields, which can't be represented using `np.int64`, can only be represented as `dtype=np.object_`.\n\n    .. ipython:: python\n\n        GF2m.dtypes\n        GFp.dtypes\n\n    Newly-created arrays will use the smallest, valid dtype.\n\n    .. ipython:: python\n\n        a = GF256.Random(10); a\n        a.dtype\n\n    This can be explicitly set by specifying the `dtype` keyword argument.\n\n    .. ipython:: python\n\n        a = GF256.Random(10, dtype=np.uint32); a\n        a.dtype\n\n    Arrays can also be created explicitly by converting an \"array-like\" object.\n\n    .. ipython:: python\n\n        # Construct a Galois field array from a list\n        l = [142, 27, 92, 253, 103]; l\n        GF256(l)\n\n        # Construct a Galois field array from an existing numpy array\n        x_np = np.array(l, dtype=np.int64); x_np\n        GF256(l)\n\n    Arrays can also be created by \"view casting\" from an existing numpy array. This avoids\n    a copy operation, which is especially useful for large data already brought into memory.\n\n    .. ipython:: python\n\n        a = x_np.view(GF256); a\n\n        # Changing `x_np` will change `a`\n        x_np[0] = 0; x_np\n        a\n    \"\"\"\n\n    def __new__(cls, array, dtype=None, copy=True, order=\"K\", ndmin=0):\n        if cls is GFArray:\n            raise NotImplementedError(\"GFArray is an abstract base class that cannot be directly instantiated. Instead, create a GFArray subclass using `galois.GF`.\")\n        return cls._array(array, dtype=dtype, copy=copy, order=order, ndmin=ndmin)\n\n    @classmethod\n    def _get_dtype(cls, dtype):\n        if dtype is None:\n            return cls.dtypes[0]\n\n        # Convert \"dtype\" to a numpy dtype. This does platform specific conversion, if necessary.\n        # For example, np.dtype(int) == np.int64 (on some systems).\n        dtype = np.dtype(dtype)\n        if dtype not in cls.dtypes:\n            raise TypeError(f\"{cls.name} arrays only support dtypes {[np.dtype(d).name for d in cls.dtypes]}, not '{dtype.name}'.\")\n\n        return dtype\n\n    @classmethod\n    def _array(cls, array_like, dtype=None, copy=True, order=\"K\", ndmin=0):\n        dtype = cls._get_dtype(dtype)\n        array_like = cls._check_array_like_object(array_like)\n        array = np.array(array_like, dtype=dtype, copy=copy, order=order, ndmin=ndmin)\n        return array.view(cls)\n\n    @classmethod\n    def _check_array_like_object(cls, array_like):\n        if isinstance(array_like, str):\n            # Convert the string to an integer\n            array_like = str_to_integer(array_like, cls.prime_subfield)\n\n        if isinstance(array_like, (int, np.integer)):\n            # Just check that the single int is in range\n            cls._check_array_values(array_like)\n\n        elif isinstance(array_like, (list, tuple)):\n            # Recursively check the items in the iterable to ensure they're of the correct type\n            # and that their values are in range\n            array_like = cls._check_iterable_types_and_values(array_like)\n\n        elif isinstance(array_like, np.ndarray):\n            if array_like.dtype == np.object_:\n                array_like = cls._check_array_types_dtype_object(array_like)\n            elif not np.issubdtype(array_like.dtype, np.integer):\n                raise TypeError(f\"{cls.name} arrays must have integer dtypes, not {array_like.dtype}.\")\n            cls._check_array_values(array_like)\n\n        else:\n            raise TypeError(f\"{cls.name} arrays can be created with scalars of type int, not {type(array_like)}.\")\n\n        return array_like\n\n    @classmethod\n    def _check_iterable_types_and_values(cls, iterable):\n        new_iterable = []\n        for item in iterable:\n            if isinstance(item, (list, tuple)):\n                item = cls._check_iterable_types_and_values(item)\n                new_iterable.append(item)\n                continue\n\n            if isinstance(item, str):\n                item = str_to_integer(item, cls.prime_subfield)\n            elif not isinstance(item, (int, np.integer, cls)):\n                raise TypeError(f\"When {cls.name} arrays are created/assigned with an iterable, each element must be an integer. Found type {type(item)}.\")\n\n            if not 0 <= item < cls.order:\n                raise ValueError(f\"{cls.name} arrays must have elements in 0 <= x < {cls.order}, not {item}.\")\n\n            # Ensure the type is int so dtype=object classes don't get all mixed up\n            new_iterable.append(int(item))\n\n        return new_iterable\n\n    @classmethod\n    def _check_array_types_dtype_object(cls, array):\n        if array.size == 0:\n            return array\n        if array.ndim == 0:\n            if not isinstance(array[()], (int, np.integer, cls)):\n                raise TypeError(f\"When {cls.name} arrays are created/assigned with a numpy array with dtype=object, each element must be an integer. Found type {type(array[()])}.\")\n            return int(array)\n\n        iterator = np.nditer(array, flags=[\"multi_index\", \"refs_ok\"])\n        for _ in iterator:\n            a = array[iterator.multi_index]\n            if not isinstance(a, (int, np.integer, cls)):\n                raise TypeError(f\"When {cls.name} arrays are created/assigned with a numpy array with dtype=object, each element must be an integer. Found type {type(a)}.\")\n\n            # Ensure the type is int so dtype=object classes don't get all mixed up\n            array[iterator.multi_index] = int(a)\n\n        return array\n\n    @classmethod\n    def _check_array_values(cls, array):\n        if not isinstance(array, np.ndarray):\n            # Convert single integer to array so next step doesn't fail\n            array = np.array(array)\n\n        # Check the value of the \"field elements\" and make sure they are valid\n        if np.any(array < 0) or np.any(array >= cls.order):\n            idxs = np.logical_or(array < 0, array >= cls.order)\n            raise ValueError(f\"{cls.name} arrays must have elements in 0 <= x < {cls.order}, not {array[idxs]}.\")\n\n    ###############################################################################\n    # Alternate constructors\n    ###############################################################################\n\n    @classmethod\n    def Zeros(cls, shape, dtype=None):\n        \"\"\"\n        Creates a Galois field array with all zeros.\n\n        Parameters\n        ----------\n        shape : tuple\n            A numpy-compliant `shape` tuple, see :obj:`numpy.ndarray.shape`. An empty tuple `()` represents a scalar.\n            A single integer or 1-tuple, e.g. `N` or `(N,)`, represents the size of a 1-dim array. An n-tuple, e.g.\n            `(M,N)`, represents an n-dim array with each element indicating the size in each dimension.\n        dtype : numpy.dtype, optional\n            The :obj:`numpy.dtype` of the array elements. The default is `None` which represents the smallest valid\n            dtype for this class, i.e. the first element in :obj:`galois.GFMeta.dtypes`.\n\n        Returns\n        -------\n        galois.GFArray\n            A Galois field array of zeros.\n\n        Examples\n        --------\n        .. ipython:: python\n\n            GF = galois.GF(31)\n            GF.Zeros((2,5))\n        \"\"\"\n        dtype = cls._get_dtype(dtype)\n        array = np.zeros(shape, dtype=dtype)\n        return array.view(cls)\n\n    @classmethod\n    def Ones(cls, shape, dtype=None):\n        \"\"\"\n        Creates a Galois field array with all ones.\n\n        Parameters\n        ----------\n        shape : tuple\n            A numpy-compliant `shape` tuple, see :obj:`numpy.ndarray.shape`. An empty tuple `()` represents a scalar.\n            A single integer or 1-tuple, e.g. `N` or `(N,)`, represents the size of a 1-dim array. An n-tuple, e.g.\n            `(M,N)`, represents an n-dim array with each element indicating the size in each dimension.\n        dtype : numpy.dtype, optional\n            The :obj:`numpy.dtype` of the array elements. The default is `None` which represents the smallest valid\n            dtype for this class, i.e. the first element in :obj:`galois.GFMeta.dtypes`.\n\n        Returns\n        -------\n        galois.GFArray\n            A Galois field array of ones.\n\n        Examples\n        --------\n        .. ipython:: python\n\n            GF = galois.GF(31)\n            GF.Ones((2,5))\n        \"\"\"\n        dtype = cls._get_dtype(dtype)\n        array = np.ones(shape, dtype=dtype)\n        return array.view(cls)\n\n    @classmethod\n    def Identity(cls, size, dtype=None):\n        \"\"\"\n        Creates an :math:`n \\\\times n` identity matrix over :math:`\\\\mathrm{GF}(q)`.\n\n        Parameters\n        ----------\n        size : int\n            The size :math:`n` along one axis of the matrix. The resulting array has shape `(size,size)`.\n        dtype : numpy.dtype, optional\n            The :obj:`numpy.dtype` of the array elements. The default is `None` which represents the smallest valid\n            dtype for this class, i.e. the first element in :obj:`galois.GFMeta.dtypes`.\n\n        Returns\n        -------\n        galois.GFArray\n            A Galois field identity matrix of shape `(size, size)`.\n\n        Examples\n        --------\n        .. ipython:: python\n\n            GF = galois.GF(31)\n            GF.Identity(4)\n        \"\"\"\n        dtype = cls._get_dtype(dtype)\n        array = np.identity(size, dtype=dtype)\n        return array.view(cls)\n\n    @classmethod\n    def Vandermonde(cls, a, m, n, dtype=None):\n        \"\"\"\n        Creates a :math:`m \\\\times n` Vandermonde matrix of :math:`a \\\\in \\\\mathrm{GF}(q)`.\n\n        Parameters\n        ----------\n        a : int, galois.GFArray\n            An element of :math:`\\\\mathrm{GF}(q)`.\n        m : int\n            The number of rows in the Vandermonde matrix.\n        n : int\n            The number of columns in the Vandermonde matrix.\n        dtype : numpy.dtype, optional\n            The :obj:`numpy.dtype` of the array elements. The default is `None` which represents the smallest valid\n            dtype for this class, i.e. the first element in :obj:`galois.GFMeta.dtypes`.\n\n        Returns\n        -------\n        galois.GFArray\n            The :math:`m \\\\times n` Vandermonde matrix.\n\n        Examples\n        --------\n        .. ipython:: python\n\n            GF = galois.GF(2**3)\n            a = GF.primitive_element\n            V = GF.Vandermonde(a, 7, 7)\n            with GF.display(\"power\"):\n                print(V)\n        \"\"\"\n        if not isinstance(a, (int, np.integer,cls)):\n            raise TypeError(f\"Argument `a` must be an integer or element of {cls.name}, not {type(a)}.\")\n        if not isinstance(m, (int, np.integer)):\n            raise TypeError(f\"Argument `m` must be an integer, not {type(m)}.\")\n        if not isinstance(n, (int, np.integer)):\n            raise TypeError(f\"Argument `n` must be an integer, not {type(n)}.\")\n        if not m > 0:\n            raise ValueError(f\"Argument `m` must be non-negative, not {m}.\")\n        if not n > 0:\n            raise ValueError(f\"Argument `n` must be non-negative, not {n}.\")\n\n        dtype = cls._get_dtype(dtype)\n        a = cls(a, dtype=dtype)\n        if not a.ndim == 0:\n            raise ValueError(f\"Argument `a` must be a scalar, not {a.ndim}-D.\")\n\n        v = a ** np.arange(0, m)\n        V = np.power.outer(v, np.arange(0, n))\n\n        return V\n\n    @classmethod\n    def Range(cls, start, stop, step=1, dtype=None):\n        \"\"\"\n        Creates a Galois field array with a range of field elements.\n\n        Parameters\n        ----------\n        start : int\n            The starting value (inclusive).\n        stop : int\n            The stopping value (exclusive).\n        step : int, optional\n            The space between values. The default is 1.\n        dtype : numpy.dtype, optional\n            The :obj:`numpy.dtype` of the array elements. The default is `None` which represents the smallest valid\n            dtype for this class, i.e. the first element in :obj:`galois.GFMeta.dtypes`.\n\n        Returns\n        -------\n        galois.GFArray\n            A Galois field array of a range of field elements.\n\n        Examples\n        --------\n        .. ipython:: python\n\n            GF = galois.GF(31)\n            GF.Range(10,20)\n        \"\"\"\n        dtype = cls._get_dtype(dtype)\n        if not stop <= cls.order:\n            raise ValueError(f\"The stopping value must be less than the field order of {cls.order}, not {stop}.\")\n\n        if dtype != np.object_:\n            array = np.arange(start, stop, step=step, dtype=dtype)\n        else:\n            array = np.array(range(start, stop, step), dtype=dtype)\n\n        return array.view(cls)\n\n    @classmethod\n    def Random(cls, shape=(), low=0, high=None, dtype=None):\n        \"\"\"\n        Creates a Galois field array with random field elements.\n\n        Parameters\n        ----------\n        shape : tuple\n            A numpy-compliant `shape` tuple, see :obj:`numpy.ndarray.shape`. An empty tuple `()` represents a scalar.\n            A single integer or 1-tuple, e.g. `N` or `(N,)`, represents the size of a 1-dim array. An n-tuple, e.g.\n            `(M,N)`, represents an n-dim array with each element indicating the size in each dimension.\n        low : int, optional\n            The lowest value (inclusive) of a random field element. The default is 0.\n        high : int, optional\n            The highest value (exclusive) of a random field element. The default is `None` which represents the\n            field's order :math:`p^m`.\n        dtype : numpy.dtype, optional\n            The :obj:`numpy.dtype` of the array elements. The default is `None` which represents the smallest valid\n            dtype for this class, i.e. the first element in :obj:`galois.GFMeta.dtypes`.\n\n        Returns\n        -------\n        galois.GFArray\n            A Galois field array of random field elements.\n\n        Examples\n        --------\n        .. ipython:: python\n\n            GF = galois.GF(31)\n            GF.Random((2,5))\n        \"\"\"\n        dtype = cls._get_dtype(dtype)\n        high = cls.order if high is None else high\n        if not 0 <= low < high <= cls.order:\n            raise ValueError(f\"Arguments must satisfy `0 <= low < high <= order`, not `0 <= {low} < {high} <= {cls.order}`.\")\n\n        if dtype != np.object_:\n            array = np.random.randint(low, high, shape, dtype=dtype)\n        else:\n            array = np.empty(shape, dtype=dtype)\n            iterator = np.nditer(array, flags=[\"multi_index\", \"refs_ok\"])\n            for _ in iterator:\n                array[iterator.multi_index] = random.randint(low, high - 1)\n\n        return array.view(cls)\n\n    @classmethod\n    def Elements(cls, dtype=None):\n        \"\"\"\n        Creates a Galois field array of the field's elements :math:`\\\\{0, \\\\dots, p^m-1\\\\}`.\n\n        Parameters\n        ----------\n        dtype : numpy.dtype, optional\n            The :obj:`numpy.dtype` of the array elements. The default is `None` which represents the smallest valid\n            dtype for this class, i.e. the first element in :obj:`galois.GFMeta.dtypes`.\n\n        Returns\n        -------\n        galois.GFArray\n            A Galois field array of all the field's elements.\n\n        Examples\n        --------\n        .. ipython:: python\n\n            GF = galois.GF(31)\n            GF.Elements()\n        \"\"\"\n        return cls.Range(0, cls.order, step=1, dtype=dtype)\n\n    @classmethod\n    def Vector(cls, array, dtype=None):\n        \"\"\"\n        Creates a Galois field array over :math:`\\\\mathrm{GF}(p^m)` from length-:math:`m` vectors over the prime subfield :math:`\\\\mathrm{GF}(p)`.\n\n        Parameters\n        ----------\n        array : array_like\n            The input array with field elements in :math:`\\\\mathrm{GF}(p)` to be converted to a Galois field array in :math:`\\\\mathrm{GF}(p^m)`.\n            The last dimension of the input array must be :math:`m`. An input array with shape `(n1, n2, m)` has output shape `(n1, n2)`.\n        dtype : numpy.dtype, optional\n            The :obj:`numpy.dtype` of the array elements. The default is `None` which represents the smallest valid\n            dtype for this class, i.e. the first element in :obj:`galois.GFMeta.dtypes`.\n\n        Returns\n        -------\n        galois.GFArray\n            A Galois field array over :math:`\\\\mathrm{GF}(p^m)`.\n\n        Examples\n        --------\n        .. ipython:: python\n\n            GF = galois.GF(2**6)\n            vec = galois.GF2.Random((3,6)); vec\n            a = GF.Vector(vec); a\n            with GF.display(\"poly\"):\n                print(a)\n            a.vector()\n        \"\"\"\n        order = cls.prime_subfield.order\n        degree = cls.degree\n        array = cls.prime_subfield(array).view(np.ndarray).astype(cls.dtypes[-1])  # Use the largest dtype so computation doesn't overflow\n        if not array.shape[-1] == degree:\n            raise ValueError(f\"The last dimension of `array` must be the field extension dimension {cls.degree}, not {array.shape[-1]}.\")\n        degrees = np.arange(degree - 1, -1, -1, dtype=cls.dtypes[-1])\n        array = np.sum(array * order**degrees, axis=-1)\n        return cls(array, dtype=dtype)\n\n    ###############################################################################\n    # Array methods\n    ###############################################################################\n\n    def vector(self, dtype=None):\n        \"\"\"\n        Converts the Galois field array over :math:`\\\\mathrm{GF}(p^m)` to length-:math:`m` vectors over the prime subfield :math:`\\\\mathrm{GF}(p)`.\n\n        For an input array with shape `(n1, n2)`, the output shape is `(n1, n2, m)`.\n\n        Parameters\n        ----------\n        dtype : numpy.dtype, optional\n            The :obj:`numpy.dtype` of the array elements. The default is `None` which represents the smallest valid\n            dtype for this class, i.e. the first element in :obj:`galois.GFMeta.dtypes`.\n\n        Returns\n        -------\n        galois.GFArray\n            A Galois field array of length-:math:`m` vectors over :math:`\\\\mathrm{GF}(p)`.\n\n        Examples\n        --------\n        .. ipython:: python\n\n            GF = galois.GF(2**6)\n            a = GF.Random(3); a\n            vec = a.vector(); vec\n            GF.Vector(vec)\n        \"\"\"\n        order = type(self).prime_subfield.order\n        degree = type(self).degree\n        array = self.view(np.ndarray)\n        array = np.repeat(array, degree).reshape(*array.shape, degree)\n        x = 0\n        for i in range(degree):\n            q = (array[...,i] - x) // order**(degree - 1 - i)\n            array[...,i] = q\n            x += q*order**(degree - 1 - i)\n        return type(self).prime_subfield(array, dtype=dtype)\n\n    def row_reduce(self, ncols=None):\n        \"\"\"\n        Performs Gaussian elimination on the matrix to achieve reduced row echelon form.\n\n        **Row reduction operations**\n\n        1. Swap the position of any two rows.\n        2. Multiply a row by a non-zero scalar.\n        3. Add one row to a scalar multiple of another row.\n\n        Parameters\n        ----------\n        ncols : int, optional\n            The number of columns to perform Gaussian elimination over. The default is `None` which represents\n            the number of columns of the input array.\n\n        Returns\n        -------\n        galois.GFArray\n            The reduced row echelon form of the input array.\n\n        Examples\n        --------\n        .. ipython:: python\n\n            GF = galois.GF(31)\n            A = GF.Random((4,4)); A\n            A.row_reduce()\n            np.linalg.matrix_rank(A)\n\n        One column is a linear combination of another.\n\n        .. ipython:: python\n\n            GF = galois.GF(31)\n            A = GF.Random((4,4)); A\n            A[:,2] = A[:,1] * GF(17); A\n            A.row_reduce()\n            np.linalg.matrix_rank(A)\n\n        One row is a linear combination of another.\n\n        .. ipython:: python\n\n            GF = galois.GF(31)\n            A = GF.Random((4,4)); A\n            A[3,:] = A[2,:] * GF(8); A\n            A.row_reduce()\n            np.linalg.matrix_rank(A)\n        \"\"\"\n        return row_reduce(self, ncols=ncols)\n\n    def lu_decompose(self):\n        \"\"\"\n        Decomposes the input array into the product of lower and upper triangular matrices.\n\n        Returns\n        -------\n        galois.GFArray\n            The lower triangular matrix.\n        galois.GFArray\n            The upper triangular matrix.\n\n        Examples\n        --------\n        .. ipython:: python\n\n            GF = galois.GF(5)\n\n            # Not every square matrix has an LU decomposition\n            A = GF([[2, 4, 4, 1], [3, 3, 1, 4], [4, 3, 4, 2], [4, 4, 3, 1]])\n            L, U = A.lu_decompose()\n            L\n            U\n\n            # A = L U\n            np.array_equal(A, L @ U)\n        \"\"\"\n        return lu_decompose(self)\n\n    def lup_decompose(self):\n        \"\"\"\n        Decomposes the input array into the product of lower and upper triangular matrices using partial pivoting.\n\n        Returns\n        -------\n        galois.GFArray\n            The lower triangular matrix.\n        galois.GFArray\n            The upper triangular matrix.\n        galois.GFArray\n            The permutation matrix.\n\n        Examples\n        --------\n        .. ipython:: python\n\n            GF = galois.GF(5)\n            A = GF([[1, 3, 2, 0], [3, 4, 2, 3], [0, 2, 1, 4], [4, 3, 3, 1]])\n            L, U, P = A.lup_decompose()\n            L\n            U\n            P\n\n            # P A = L U\n            np.array_equal(P @ A, L @ U)\n        \"\"\"\n        return lup_decompose(self)\n\n    ###############################################################################\n    # Overridden numpy methods\n    ###############################################################################\n\n    def astype(self, dtype, **kwargs):  # pylint: disable=arguments-differ\n        if dtype not in type(self).dtypes:\n            raise TypeError(f\"{type(self).name} arrays can only be cast as integer dtypes in {type(self).dtypes}, not {dtype}.\")\n        return super().astype(dtype, **kwargs)\n\n    def __array_finalize__(self, obj):\n        \"\"\"\n        A numpy dunder method that is called after \"new\", \"view\", or \"new from template\". It is used here to ensure\n        that view casting to a Galois field array has the appropriate dtype and that the values are in the field.\n        \"\"\"\n        if obj is not None and not isinstance(obj, GFArray):\n            # Only invoked on view casting\n            if obj.dtype not in type(self).dtypes:\n                raise TypeError(f\"{type(self).name} can only have integer dtypes {type(self).dtypes}, not {obj.dtype}.\")\n            if np.any(obj < 0) or np.any(obj >= type(self).order):\n                idxs = np.logical_or(obj < 0, obj >= type(self).order)\n                raise ValueError(f\"{type(self).name} arrays must have values in 0 <= x < {type(self).order}, not {obj[idxs]}.\")\n\n    def __getitem__(self, key):\n        item = super().__getitem__(key)\n        if np.isscalar(item):\n            # Return scalar array elements as 0-dimension Galois field arrays. This enables Galois field arithmetic\n            # on scalars, which would otherwise be implemented using standard integer arithmetic.\n            item = self.__class__(item, dtype=self.dtype)\n        return item\n\n    def __setitem__(self, key, value):\n        # Verify the values to be written to the Galois field array are in the field\n        value = self._check_array_like_object(value)\n        super().__setitem__(key, value)\n\n    def __array_function__(self, func, types, args, kwargs):\n        if func in OVERRIDDEN_FUNCTIONS:\n            output = OVERRIDDEN_FUNCTIONS[func](*args, **kwargs)\n\n        elif func in UNSUPPORTED_FUNCTIONS:\n            raise NotImplementedError(f\"The numpy function '{func.__name__}' is not supported on Galois field arrays. If you believe this function should be supported, please submit a GitHub issue at https://github.com/mhostetter/galois/issues.\\n\\nIf you'd like to perform this operation on the data (but not necessarily a Galois field array), you should first call `array = array.view(np.ndarray)` and then call the function.\")\n\n        else:\n            if func is np.insert:\n                args = list(args)\n                args[2] = self._check_array_like_object(args[2])\n                args = tuple(args)\n\n            output = super().__array_function__(func, types, args, kwargs)  # pylint: disable=no-member\n\n            if func in FUNCTIONS_REQUIRING_VIEW:\n                if np.isscalar(output):\n                    output = type(self)(output, dtype=self.dtype)\n                else:\n                    output = output.view(type(self))\n\n        return output\n\n    def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):  # pylint: disable=too-many-branches\n        # print(ufunc, method, inputs, kwargs)\n        meta = {}\n        meta[\"types\"] = [type(inputs[i]) for i in range(len(inputs))]\n        meta[\"operands\"] = list(range(len(inputs)))\n        if method in [\"at\", \"reduceat\"]:\n            # Remove the second argument for \"at\" ufuncs which is the indices list\n            meta[\"operands\"].pop(1)\n        meta[\"field_operands\"] = [i for i in meta[\"operands\"] if isinstance(inputs[i], self.__class__)]\n        meta[\"non_field_operands\"] = [i for i in meta[\"operands\"] if not isinstance(inputs[i], self.__class__)]\n        meta[\"field\"] = self.__class__\n        meta[\"dtype\"] = self.dtype\n        # meta[\"ufuncs\"] = self._ufuncs\n\n        if ufunc in OVERRIDDEN_UFUNCS:\n            # Set all ufuncs with \"casting\" keyword argument to \"unsafe\" so we can cast unsigned integers\n            # to integers. We know this is safe because we already verified the inputs.\n            if method not in [\"reduce\", \"accumulate\", \"at\", \"reduceat\"]:\n                kwargs[\"casting\"] = \"unsafe\"\n\n            # Need to set the intermediate dtype for reduction operations or an error will be thrown. We\n            # use the largest valid dtype for this field.\n            if method in [\"reduce\"]:\n                kwargs[\"dtype\"] = type(self).dtypes[-1]\n\n            return getattr(type(self), OVERRIDDEN_UFUNCS[ufunc])(ufunc, method, inputs, kwargs, meta)\n\n        elif ufunc in UNSUPPORTED_UFUNCS:\n            raise NotImplementedError(f\"The numpy ufunc '{ufunc.__name__}' is not supported on Galois field arrays. If you believe this ufunc should be supported, please submit a GitHub issue at https://github.com/mhostetter/galois/issues.\")\n\n        else:\n            inputs, kwargs = type(self)._view_inputs_as_ndarray(inputs, kwargs)\n            output = super().__array_ufunc__(ufunc, method, *inputs, **kwargs)  # pylint: disable=no-member\n\n            if ufunc in UFUNCS_REQUIRING_VIEW:\n                output = output.view(type(self))\n\n            return output\n\n    ###############################################################################\n    # Display methods\n    ###############################################################################\n\n    def __str__(self):\n        return self.__repr__()\n\n    def __repr__(self):\n        # pylint: disable=attribute-defined-outside-init\n        formatter = {}\n        if type(self).display_mode == \"poly\":\n            formatter[\"int\"] = self._print_poly\n            formatter[\"object\"] = self._print_poly\n        elif type(self).display_mode == \"power\":\n            nonzero_idxs = np.nonzero(self)\n            if self.ndim > 1:\n                self._display_power_pre_width = 0 if nonzero_idxs[0].size == self.size else 1\n                max_power = np.max(np.log(self[nonzero_idxs]))\n                if max_power > 1:\n                    self._display_power_width = self._display_power_pre_width + 2 + len(str(max_power))\n                else:\n                    self._display_power_width = self._display_power_pre_width + 1\n            else:\n                self._display_power_pre_width = None\n                self._display_power_width = None\n            formatter[\"int\"] = self._print_power\n            formatter[\"object\"] = self._print_power\n        elif self.dtype == np.object_:\n            formatter[\"object\"] = self._print_int\n\n        cls = type(self)\n        class_name = cls.__name__\n        with np.printoptions(formatter=formatter):\n            cls.__name__ = \"GF\"  # Rename the class so very large fields don't create large indenting\n            string = super().__repr__()\n        cls.__name__ = class_name\n\n        if cls.degree == 1:\n            order = \"{}\".format(cls.order)\n        else:\n            order = \"{}^{}\".format(cls.characteristic, cls.degree)\n\n        # Remove the dtype from the repr and add the Galois field order\n        dtype_idx = string.find(\"dtype\")\n        if dtype_idx == -1:\n            string = string[:-1] + f\", order={order})\"\n        else:\n            string = string[:dtype_idx] + f\"order={order})\"\n\n        return string\n\n    @staticmethod\n    def _print_int(element):\n        return \"{:d}\".format(int(element))\n\n    def _print_poly(self, element):\n        poly = integer_to_poly(element, type(self).characteristic)\n        poly_var = \"α\" if type(self).primitive_element == type(self).characteristic else \"x\"\n        return poly_to_str(poly, poly_var=poly_var)\n\n    def _print_power(self, element):\n        if element == 0:\n            s = \"-∞\"\n        else:\n            power = type(self)._ufuncs[\"log\"](element)\n            if power > 1:\n                s = f\"α^{power}\"\n            elif power == 1:\n                s = \"α\"\n            else:\n                s = \"1\"\n\n            if self._display_power_pre_width:\n                s = \" \" + s\n\n        if self._display_power_width:\n            return s + \" \"*(self._display_power_width - len(s))\n        else:\n            return s\n\n    @classmethod\n    def _poly_eval(cls, coeffs, x):\n        coeffs = cls(coeffs)  # Convert coefficient into the field\n        coeffs = coeffs.view(np.ndarray)  # View cast to normal integers so ufunc_poly_eval call uses normal arithmetic\n        coeffs = np.atleast_1d(coeffs)\n        if coeffs.size == 1:\n            # TODO: Why must coeffs have atleast 2 elements otherwise it will be converted to a scalar, not 1d array?\n            coeffs = np.insert(coeffs, 0, 0)\n\n        x = cls(x)  # Convert evaluation values into the field (checks that values are in the field)\n        x = x.view(np.ndarray)  # View cast to normal integers so ufunc_poly_eval call uses normal arithmetic\n        x = np.atleast_1d(x)\n\n        if cls.dtypes[-1] == np.object_:\n            # For object dtypes, call the vectorized classmethod\n            y = cls._ufuncs[\"poly_eval\"](coeffs=coeffs, values=x)  # pylint: disable=not-callable\n        else:\n            # For integer dtypes, call the JIT-compiled gufunc\n            y = np.copy(x)\n            cls._ufuncs[\"poly_eval\"](coeffs, x, y, casting=\"unsafe\")  # pylint: disable=not-callable\n\n        y = cls(y)\n        if y.size == 1:\n            y = y[0]\n\n        return y\n", "meta": {"hexsha": "0ce3a790858ffecf114f8a3144d9992c80e23421", "size": 36032, "ext": "py", "lang": "Python", "max_stars_repo_path": "galois/array.py", "max_stars_repo_name": "BK-Modding/galois", "max_stars_repo_head_hexsha": "5da4db84d90083e337ebe2c1838df5c6db88fd3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "galois/array.py", "max_issues_repo_name": "BK-Modding/galois", "max_issues_repo_head_hexsha": "5da4db84d90083e337ebe2c1838df5c6db88fd3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "galois/array.py", "max_forks_repo_name": "BK-Modding/galois", "max_forks_repo_head_hexsha": "5da4db84d90083e337ebe2c1838df5c6db88fd3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1081359423, "max_line_length": 428, "alphanum_fraction": 0.5767095915, "include": true, "reason": "import numpy", "num_tokens": 8737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.19614042734468984}}
{"text": "#!/usr/bin/env python\r\n# -*- coding: UTF-8 -*-\r\n\r\n# Copyright 2017 Timothy Dozat\r\n# \r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n# \r\n#     http://www.apache.org/licenses/LICENSE-2.0\r\n# \r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\nimport six\r\n\r\nimport numpy as np\r\nimport tensorflow as tf\r\n\r\nfrom .base_vocabs import BaseVocab \r\nfrom . import conllu_vocabs as cv\r\n\r\nfrom parser.neural import nn, nonlin, classifiers\r\nimport pdb\r\n#***************************************************************\r\nclass SecondOrderLBPVocab(BaseVocab):\r\n\t\"\"\"\"\"\"\r\n\t\r\n\t#=============================================================\r\n\tdef __init__(self, *args, **kwargs):\r\n\t\t\"\"\"\"\"\"\r\n\t\t\r\n\t\tsuper(SecondOrderLBPVocab, self).__init__(*args, **kwargs)\r\n\t\t\r\n\t\tself.PAD_STR = '_'\r\n\t\tself.PAD_IDX = -1\r\n\t\tself.ROOT_STR = '0'\r\n\t\tself.ROOT_IDX = 0\r\n\t\treturn\r\n\t\r\n\t#=============================================================\r\n\tdef add(self, token):\r\n\t\t\"\"\"\"\"\"\r\n\t\t\r\n\t\treturn self.index(token)\r\n\t\r\n\t#=============================================================\r\n\tdef token(self, index):\r\n\t\t\"\"\"\"\"\"\r\n\t\t\r\n\t\tif index > -1:\r\n\t\t\treturn str(index)\r\n\t\telse:\r\n\t\t\treturn '_'\r\n\t\r\n\t#=============================================================\r\n\tdef index(self, token):\r\n\t\t\"\"\"\"\"\"\r\n\t\t\r\n\t\tif token != '_':\r\n\t\t\treturn int(token)\r\n\t\telse:\r\n\t\t\treturn -1\r\n\t\r\n\t#=============================================================\r\n\tdef get_root(self):\r\n\t\t\"\"\"\"\"\"\r\n\t\t\r\n\t\treturn self.ROOT_STR\r\n\t\r\n\t#=============================================================\r\n\tdef get_bilinear_classifier(self, layer, token_weights, variable_scope=None, reuse=False):\r\n\t\t\"\"\"\"\"\"\r\n\t\t\r\n\t\trecur_layer = layer\r\n\t\thidden_keep_prob = 1 if reuse else self.hidden_keep_prob\r\n\t\thidden_func = self.hidden_func\r\n\t\thidden_size = self.hidden_size\r\n\t\tadd_linear = self.add_linear\r\n\t\tlinearize = self.linearize\r\n\t\tdistance = self.distance\r\n\t\tn_splits = 2*(1+linearize+distance)\r\n\t\twith tf.variable_scope(variable_scope or self.field):\r\n\t\t\tfor i in six.moves.range(0, self.n_layers-1):\r\n\t\t\t\twith tf.variable_scope('FC-%d' % i):\r\n\t\t\t\t\tlayer = classifiers.hidden(layer, n_splits*hidden_size,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\thidden_func=hidden_func,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob)\r\n\t\t\twith tf.variable_scope('FC-top'):\r\n\t\t\t\tlayers = classifiers.hiddens(layer, n_splits*[hidden_size],\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\thidden_func=hidden_func,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob)\r\n\t\t\tlayer1, layer2 = layers.pop(0), layers.pop(0)\r\n\t\t\tif linearize:\r\n\t\t\t\tlin_layer1, lin_layer2 = layers.pop(0), layers.pop(0)\r\n\t\t\tif distance:\r\n\t\t\t\tdist_layer1, dist_layer2 = layers.pop(0), layers.pop(0)\r\n\t\t\t\r\n\t\t\twith tf.variable_scope('Attention'):\r\n\t\t\t\tif self.diagonal:\r\n\t\t\t\t\tlogits, _ = classifiers.diagonal_bilinear_attention(\r\n\t\t\t\t\t\tlayer1, layer2, \r\n\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob,\r\n\t\t\t\t\t\tadd_linear=add_linear)\r\n\t\t\t\t\tif linearize:\r\n\t\t\t\t\t\twith tf.variable_scope('Linearization'):\r\n\t\t\t\t\t\t\tlin_logits = classifiers.diagonal_bilinear_discriminator(\r\n\t\t\t\t\t\t\t\tlin_layer1, lin_layer2,\r\n\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob,\r\n\t\t\t\t\t\t\t\tadd_linear=add_linear)\r\n\t\t\t\t\tif distance:\r\n\t\t\t\t\t\twith tf.variable_scope('Distance'):\r\n\t\t\t\t\t\t\tdist_lamda = 1+tf.nn.softplus(classifiers.diagonal_bilinear_discriminator(\r\n\t\t\t\t\t\t\t\tdist_layer1, dist_layer2,\r\n\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob,\r\n\t\t\t\t\t\t\t\tadd_linear=add_linear))\r\n\t\t\t\telse:\r\n\t\t\t\t\tlogits, _ = classifiers.bilinear_attention(\r\n\t\t\t\t\t\tlayer1, layer2,\r\n\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob,\r\n\t\t\t\t\t\tadd_linear=add_linear)\r\n\t\t\t\t\tif linearize:\r\n\t\t\t\t\t\twith tf.variable_scope('Linearization'):\r\n\t\t\t\t\t\t\tlin_logits = classifiers.bilinear_discriminator(\r\n\t\t\t\t\t\t\t\tlin_layer1, lin_layer2,\r\n\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob,\r\n\t\t\t\t\t\t\t\tadd_linear=add_linear)\r\n\t\t\t\t\tif distance:\r\n\t\t\t\t\t\twith tf.variable_scope('Distance'):\r\n\t\t\t\t\t\t\tdist_lamda = 1+tf.nn.softplus(classifiers.bilinear_discriminator(\r\n\t\t\t\t\t\t\t\tdist_layer1, dist_layer2,\r\n\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob,\r\n\t\t\t\t\t\t\t\tadd_linear=add_linear))\r\n\t\t\t\t\r\n\t\t\t\t#-----------------------------------------------------------\r\n\t\t\t\t# Process the targets\r\n\t\t\t\ttargets = self.placeholder\r\n\t\t\t\tshape = tf.shape(layer1)\r\n\t\t\t\tbatch_size, bucket_size = shape[0], shape[1]\r\n\t\t\t\t# (1 x m)\r\n\t\t\t\tids = tf.expand_dims(tf.range(bucket_size), 0)\r\n\t\t\t\t# (1 x m) -> (1 x 1 x m)\r\n\t\t\t\thead_ids = tf.expand_dims(ids, -2)\r\n\t\t\t\t# (1 x m) -> (1 x m x 1)\r\n\t\t\t\tdep_ids = tf.expand_dims(ids, -1)\r\n\t\t\t\tif linearize:\r\n\t\t\t\t\t# Wherever the head is to the left\r\n\t\t\t\t\t# (n x m), (1 x m) -> (n x m)\r\n\t\t\t\t\tlin_targets = tf.to_float(tf.less(targets, ids))\r\n\t\t\t\t\t# cross-entropy of the linearization of each i,j pair\r\n\t\t\t\t\t# (1 x 1 x m), (1 x m x 1) -> (n x m x m)\r\n\t\t\t\t\tlin_ids = tf.tile(tf.less(head_ids, dep_ids), [batch_size, 1, 1])\r\n\t\t\t\t\t# (n x 1 x m), (n x m x 1) -> (n x m x m)\r\n\t\t\t\t\tlin_xent = -tf.nn.softplus(tf.where(lin_ids, -lin_logits, lin_logits))\r\n\t\t\t\t\t# add the cross-entropy to the logits\r\n\t\t\t\t\t# (n x m x m), (n x m x m) -> (n x m x m)\r\n\t\t\t\t\tlogits += tf.stop_gradient(lin_xent)\r\n\t\t\t\tif distance:\r\n\t\t\t\t\t# (n x m) - (1 x m) -> (n x m)\r\n\t\t\t\t\tdist_targets = tf.abs(targets - ids)\r\n\t\t\t\t\t# KL-divergence of the distance of each i,j pair\r\n\t\t\t\t\t# (1 x 1 x m) - (1 x m x 1) -> (n x m x m)\r\n\t\t\t\t\tdist_ids = tf.to_float(tf.tile(tf.abs(head_ids - dep_ids), [batch_size, 1, 1]))+1e-12\r\n\t\t\t\t\t# (n x m x m), (n x m x m) -> (n x m x m)\r\n\t\t\t\t\t#dist_kld = (dist_ids * tf.log(dist_lamda / dist_ids) + dist_ids - dist_lamda)\r\n\t\t\t\t\tdist_kld = -tf.log((dist_ids - dist_lamda)**2/2 + 1)\r\n\t\t\t\t\t# add the KL-divergence to the logits\r\n\t\t\t\t\t# (n x m x m), (n x m x m) -> (n x m x m)\r\n\t\t\t\t\tlogits += tf.stop_gradient(dist_kld)\r\n\t\t\t\t\r\n\t\t\t\t#-----------------------------------------------------------\r\n\t\t\t\t# Compute probabilities/cross entropy\r\n\t\t\t\t# (n x m) + (m) -> (n x m)\r\n\t\t\t\tnon_pads = tf.to_float(token_weights) + tf.to_float(tf.logical_not(tf.cast(tf.range(bucket_size), dtype=tf.bool)))\r\n\t\t\t\t# (n x m x m) o (n x 1 x m) -> (n x m x m)\r\n\t\t\t\tprobabilities = tf.nn.softmax(logits) * tf.expand_dims(non_pads, -2)\r\n\t\t\t\t# (n x m), (n x m x m), (n x m) -> ()\r\n\t\t\t\tloss = tf.losses.sparse_softmax_cross_entropy(\r\n\t\t\t\t\ttargets,\r\n\t\t\t\t\tlogits,\r\n\t\t\t\t\tweights=token_weights)\r\n\t\t\t\t# (n x m) -> (n x m x m x 1)\r\n\t\t\t\tone_hot_targets = tf.expand_dims(tf.one_hot(targets, bucket_size), -1)\r\n\t\t\t\t# (n x m) -> ()\r\n\t\t\t\tn_tokens = tf.to_float(tf.reduce_sum(token_weights))\r\n\t\t\t\tif linearize:\r\n\t\t\t\t\t# (n x m x m) -> (n x m x 1 x m)\r\n\t\t\t\t\tlin_xent_reshaped = tf.expand_dims(lin_xent, -2)\r\n\t\t\t\t\t# (n x m x 1 x m) * (n x m x m x 1) -> (n x m x 1 x 1)\r\n\t\t\t\t\tlin_target_xent = tf.matmul(lin_xent_reshaped, one_hot_targets)\r\n\t\t\t\t\t# (n x m x 1 x 1) -> (n x m)\r\n\t\t\t\t\tlin_target_xent = tf.squeeze(lin_target_xent, [-1, -2])\r\n\t\t\t\t\t# (n x m), (n x m), (n x m) -> ()\r\n\t\t\t\t\tloss -= tf.reduce_sum(lin_target_xent*tf.to_float(token_weights)) / (n_tokens + 1e-12)\r\n\t\t\t\tif distance:\r\n\t\t\t\t\t# (n x m x m) -> (n x m x 1 x m)\r\n\t\t\t\t\tdist_kld_reshaped = tf.expand_dims(dist_kld, -2)\r\n\t\t\t\t\t# (n x m x 1 x m) * (n x m x m x 1) -> (n x m x 1 x 1)\r\n\t\t\t\t\tdist_target_kld = tf.matmul(dist_kld_reshaped, one_hot_targets)\r\n\t\t\t\t\t# (n x m x 1 x 1) -> (n x m)\r\n\t\t\t\t\tdist_target_kld = tf.squeeze(dist_target_kld, [-1, -2])\r\n\t\t\t\t\t# (n x m), (n x m), (n x m) -> ()\r\n\t\t\t\t\tloss -= tf.reduce_sum(dist_target_kld*tf.to_float(token_weights)) / (n_tokens + 1e-12)\r\n\t\t\t\t\r\n\t\t\t\t#-----------------------------------------------------------\r\n\t\t\t\t# Compute predictions/accuracy\r\n\t\t\t\t# (n x m x m) -> (n x m)\r\n\t\t\t\tpredictions = tf.argmax(logits, axis=-1, output_type=tf.int32)\r\n\t\t\t\t# (n x m) (*) (n x m) -> (n x m)\r\n\t\t\t\tcorrect_tokens = nn.equal(targets, predictions) * token_weights\r\n\t\t\t\t# (n x m) -> (n)\r\n\t\t\t\ttokens_per_sequence = tf.reduce_sum(token_weights, axis=-1)\r\n\t\t\t\t# (n x m) -> (n)\r\n\t\t\t\tcorrect_tokens_per_sequence = tf.reduce_sum(correct_tokens, axis=-1)\r\n\t\t\t\t# (n), (n) -> (n)\r\n\t\t\t\tcorrect_sequences = nn.equal(tokens_per_sequence, correct_tokens_per_sequence)\r\n\t\t\r\n\t\t#-----------------------------------------------------------\r\n\t\t# Populate the output dictionary\r\n\t\toutputs = {}\r\n\t\toutputs['recur_layer'] = recur_layer\r\n\t\toutputs['unlabeled_targets'] = self.placeholder\r\n\t\toutputs['probabilities'] = probabilities\r\n\t\toutputs['unlabeled_loss'] = loss\r\n\t\toutputs['loss'] = loss\r\n\t\t\r\n\t\toutputs['unlabeled_predictions'] = predictions\r\n\t\toutputs['predictions'] = predictions\r\n\t\toutputs['correct_unlabeled_tokens'] = correct_tokens\r\n\t\toutputs['n_correct_unlabeled_tokens'] = tf.reduce_sum(correct_tokens)\r\n\t\toutputs['n_correct_unlabeled_sequences'] = tf.reduce_sum(correct_sequences)\r\n\t\toutputs['n_correct_tokens'] = tf.reduce_sum(correct_tokens)\r\n\t\toutputs['n_correct_sequences'] = tf.reduce_sum(correct_sequences)\r\n\t\treturn outputs\r\n\t\r\n\t#=============================================================\r\n\tdef __getitem__(self, key):\r\n\t\tif isinstance(key, six.string_types):\r\n\t\t\tif key == '_':\r\n\t\t\t\treturn -1\r\n\t\t\telse:\r\n\t\t\t\treturn int(key)\r\n\t\telif isinstance(key, six.integer_types + (np.int32, np.int64)):\r\n\t\t\tif key > -1:\r\n\t\t\t\treturn str(key)\r\n\t\t\telse:\r\n\t\t\t\treturn '_'\r\n\t\telif hasattr(key, '__iter__'):\r\n\t\t\treturn [self[k] for k in key]\r\n\t\telse:\r\n\t\t\traise ValueError('key to IndexVocab.__getitem__ must be (iterable of) string or integer')\r\n\t\treturn\r\n\t#=============================================================\r\n\t@property\r\n\tdef distance(self):\r\n\t\treturn self._config.getboolean(self, 'distance')\r\n\t@property\r\n\tdef linearize(self):\r\n\t\treturn self._config.getboolean(self, 'linearize')\r\n\t@property\r\n\tdef decomposition_level(self):\r\n\t\treturn self._config.getint(self, 'decomposition_level')\r\n\t@property\r\n\tdef diagonal(self):\r\n\t\treturn self._config.getboolean(self, 'diagonal')\r\n\t@property\r\n\tdef add_linear(self):\r\n\t\treturn self._config.getboolean(self, 'add_linear')\r\n\t@property\r\n\tdef n_layers(self):\r\n\t\treturn self._config.getint(self, 'n_layers')\r\n\t@property\r\n\tdef hidden_size(self):\r\n\t\treturn self._config.getint(self, 'hidden_size')\r\n\t@property\r\n\tdef hidden_keep_prob(self):\r\n\t\treturn self._config.getfloat(self, 'hidden_keep_prob')\r\n\t@property\r\n\tdef hidden_keep_prob_tri(self):\r\n\t\ttry:\r\n\t\t\treturn self._config.getfloat(self, 'hidden_keep_prob_tri')\r\n\t\texcept:\r\n\t\t\treturn self._config.getfloat(self, 'hidden_keep_prob')\r\n\t\t\r\n\t@property\r\n\tdef hidden_func(self):\r\n\t\thidden_func = self._config.getstr(self, 'hidden_func')\r\n\t\tif hasattr(nonlin, hidden_func):\r\n\t\t\treturn getattr(nonlin, hidden_func)\r\n\t\telse:\r\n\t\t\traise AttributeError(\"module '{}' has no attribute '{}'\".format(nonlin.__name__, hidden_func))\r\n\t@property\r\n\tdef num_iteration(self):\r\n\t\treturn self._config.getfloat(self, 'num_iteration')\r\n\t@property\r\n\tdef discriminator2(self):\r\n\t\treturn self._config.getboolean(self,'discriminator2')\r\n\t@property\r\n\tdef sibling_only(self):\r\n\t\treturn self._config.getboolean(self,'sibling_only')\r\n\t@property\r\n\tdef self_minus(self):\r\n\t\treturn self._config.getboolean(self,'self_minus')\r\n\t@property\r\n\tdef use_sib(self):\r\n\t\treturn self._config.getboolean(self,'use_sib')\r\n\t@property\r\n\tdef use_gp(self):\r\n\t\treturn self._config.getboolean(self,'use_gp')\r\n\t@property\r\n\tdef use_cop(self):\r\n\t\treturn self._config.getboolean(self,'use_cop')\r\n\t@property\r\n\tdef transposed(self):\r\n\t\treturn self._config.getboolean(self,'transposed')\r\n\t@property\r\n\tdef unary_weight(self):\r\n\t\tif self._config.getboolean(self,'unary_weight'):\r\n\t\t\treturn int(self.use_cop)+int(self.use_sib)+2*int(self.use_gp)\r\n\t\telse:\r\n\t\t\treturn 1\r\n\t@property\r\n\tdef new_potential(self):\r\n\t\treturn self._config.getboolean(self,'new_potential')\r\n\t@property\r\n\tdef separate_embed(self):\r\n\t\ttry:\r\n\t\t\treturn self._config.getboolean(self,'separate_embed')\r\n\t\texcept:\r\n\t\t\treturn False\r\n\t@property\r\n\tdef old_trilin(self):\r\n\t\ttry:\r\n\t\t\treturn self._config.getboolean(self,'old_trilin')\r\n\t\texcept:\r\n\t\t\treturn False\r\n\t@property\r\n\tdef remove_loop(self):\r\n\t\ttry:\r\n\t\t\treturn self._config.getboolean(self,'remove_loop')\r\n\t\texcept:\r\n\t\t\treturn False\r\n\t@property\r\n\tdef combine_loss(self):\r\n\t\ttry:\r\n\t\t\treturn self._config.getboolean(self,'combine_loss')\r\n\t\texcept:\r\n\t\t\treturn False\r\n\t@property\r\n\tdef loss_weight(self):\r\n\t\ttry:\r\n\t\t\treturn self._config.getfloat(self,'loss_weight')\r\n\t\texcept:\r\n\t\t\treturn 0.5\r\n\t@property\r\n\tdef loss_weight_unary(self):\r\n\t\ttry:\r\n\t\t\treturn self._config.getfloat(self,'loss_weight_unary')\r\n\t\texcept:\r\n\t\t\treturn 0.5\r\n\t@property\r\n\tdef test_new_potential(self):\r\n\t\ttry:\r\n\t\t\treturn self._config.getboolean(self,'test_new_potential')\r\n\t\texcept:\r\n\t\t\treturn False\r\n\t@property\r\n\tdef layer_mask(self):\r\n\t\ttry:\r\n\t\t\treturn self._config.getboolean(self,'layer_mask')\r\n\t\texcept:\r\n\t\t\treturn False\r\n\t@property\r\n\tdef normalize(self):\r\n\t\ttry:\r\n\t\t\treturn self._config.getboolean(self,'normalize')\r\n\t\texcept:\r\n\t\t\treturn False\r\n\t@property\r\n\tdef use_unary_hidden(self):\r\n\t\ttry:\r\n\t\t\treturn self._config.getboolean(self,'use_unary_hidden')\r\n\t\texcept:\r\n\t\t\treturn False\r\n\t@property\r\n\tdef unary_hidden(self):\r\n\t\ttry:\r\n\t\t\treturn self._config.getint(self,'unary_hidden')\r\n\t\texcept:\r\n\t\t\treturn self._config.getint(self,'hidden_size')\r\n\t@property\r\n\tdef tri_std(self):\r\n\t\ttry:\r\n\t\t\treturn self._config.getfloat(self,'tri_std')\r\n\t\texcept:\r\n\t\t\treturn 0.01\r\n\t@property\r\n\tdef tri_std_unary(self):\r\n\t\ttry:\r\n\t\t\treturn self._config.getfloat(self,'tri_std_unary')\r\n\t\texcept:\r\n\t\t\treturn 0.5\r\n\t@property\r\n\tdef hidden_k(self):\r\n\t\ttry:\r\n\t\t\treturn self._config.getint(self,'hidden_k')\r\n\t\texcept:\r\n\t\t\treturn 200\r\n\t@property\r\n\tdef two_gpu(self):\r\n\t\ttry:\r\n\t\t\tif self._config.get('GraphParserNetwork','two_gpu')=='True':\r\n\t\t\t\treturn True\r\n\t\t\telse:\r\n\t\t\t\treturn False\r\n\t\texcept:\r\n\t\t\treturn False\r\n\t@property\r\n\tdef remove_root_child(self):\r\n\t\ttry:\r\n\t\t\treturn self._config.getboolean(self,'remove_root_child')\r\n\t\texcept:\r\n\t\t\treturn False\r\n\t@property\r\n\tdef compare_precision(self):\r\n\t\ttry:\r\n\t\t\tif self._config.get('DEFAULT', 'tb')=='ptb' or self._config.get('DEFAULT', 'tb')=='ctb':\r\n\t\t\t\treturn True\r\n\t\t\telse:\r\n\t\t\t\treturn False\r\n\t\texcept:\r\n\t\t\treturn False\r\n#***************************************************************\r\nclass GraphSecondLBPVocab(SecondOrderLBPVocab): #second order trilinear classifier\r\n\t\"\"\"\"\"\"\r\n\t\r\n\t_depth = -1\r\n\t\r\n\t#=============================================================\r\n\tdef __init__(self, *args, **kwargs):\r\n\t\t\"\"\"\"\"\"\r\n\t\t\r\n\t\tkwargs['placeholder_shape'] = [None, None, None]\r\n\t\tsuper(GraphSecondLBPVocab, self).__init__(*args, **kwargs)\r\n\t\treturn\r\n\t\r\n\t#=============================================================\r\n\tdef get_bilinear_discriminator(self, layer, token_weights, variable_scope=None, reuse=False, debug=False, token_weights4D=None):\r\n\t\t\"\"\"\"\"\"\r\n\t\t#in fact here is get_trilinear_discriminator\r\n\t\toutputs = {}\r\n\t\trecur_layer = layer\r\n\t\thidden_keep_prob = 1 if reuse else self.hidden_keep_prob\r\n\t\thidden_keep_prob_tri = 1 if reuse else self.hidden_keep_prob_tri\r\n\t\tadd_linear = self.add_linear\r\n\t\t#here set n_splits to be three\r\n\t\tif self.separate_embed:\r\n\t\t\tn_splits = 9*(1+self.linearize+self.distance)\r\n\t\telse:\r\n\t\t\tn_splits = 3*(1+self.linearize+self.distance)\r\n\t\twith tf.variable_scope(variable_scope or self.field):\r\n\t\t\tfor i in six.moves.range(0, self.n_layers-1):#number of layers of FNN? what is this?\r\n\t\t\t\twith tf.variable_scope('FC-%d' % i):#here is FNN? did not run\r\n\t\t\t\t\tlayer = classifiers.hidden(layer, n_splits*self.hidden_size,\r\n\t\t\t\t\t\t\t\t\t\t\t\t hidden_func=self.hidden_func,\r\n\t\t\t\t\t\t\t\t\t\t\t\t hidden_keep_prob=hidden_keep_prob)\r\n\t\t\twith tf.variable_scope('FC-top'):#FNN output and split two layer? FNN+split. Linear transform for a sentence, n_splits is number of features you want \r\n\t\t\t\t#this linear transformation contains word information\r\n\t\t\t\tif self.use_unary_hidden:\r\n\t\t\t\t\tprint('separate unary and binary hidden size')\r\n\t\t\t\t\tif self.separate_embed:\r\n\t\t\t\t\t\thidden_list=2*[self.unary_hidden]+(n_splits-2)*[self.hidden_size]\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\thidden_list=2*[self.unary_hidden]+n_splits*[self.hidden_size]\r\n\t\t\t\telse:\r\n\t\t\t\t\thidden_list=n_splits*[self.hidden_size]\r\n\t\t\t\t#pdb.set_trace()\r\n\t\t\t\tlayers = classifiers.hiddens(layer, hidden_list,\r\n\t\t\t\t\t\t\t\t\t\t\t hidden_func=self.hidden_func,\r\n\t\t\t\t\t\t\t\t\t\t\t hidden_keep_prob=hidden_keep_prob)\r\n\t\t\tif self.separate_embed:\r\n\t\t\t\t# unary_head + unary_dep + sib_head + sib_dep + gp_head + gp_dep + gp_(head+dep) + cop_head + cop_dep\r\n\t\t\t\tunary_layer1, unary_layer2, sib_head, sib_dep, gp_head, gp_dep, gp_headdep, cop_head, cop_dep = layers.pop(0), layers.pop(0), layers.pop(0), layers.pop(0), layers.pop(0)\\\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, layers.pop(0), layers.pop(0), layers.pop(0), layers.pop(0)\r\n\t\t\telse:\r\n\t\t\t\t# head + dep + (head+dep)\r\n\t\t\t\tif self.use_unary_hidden:\r\n\t\t\t\t\tunary_layer1, unary_layer2, layer1, layer2, layer3 = layers.pop(0), layers.pop(0), layers.pop(0), layers.pop(0), layers.pop(0)\r\n\t\t\t\telse:\r\n\t\t\t\t\tlayer1, layer2, layer3 = layers.pop(0), layers.pop(0), layers.pop(0)\r\n\t\t\t\t\t#pdb.set_trace()\r\n\t\t\t\t\tunary_layer1=layer1\r\n\t\t\t\t\tunary_layer2=layer2\r\n\t\t\tif self.linearize:#false\r\n\t\t\t\tlin_layer1, lin_layer2 = layers.pop(0), layers.pop(0), layers.pop(0)\r\n\t\t\tif self.distance:#false in graph\r\n\t\t\t\tdist_layer1, dist_layer2 = layers.pop(0), layers.pop(0), layers.pop(0)\r\n\t\t\t#pdb.set_trace()\r\n\t\t\tif self.layer_mask:\r\n\t\t\t\t#pdb.set_trace()\r\n\t\t\t\tsentence_mask=tf.expand_dims(tf.cast(tf.transpose(token_weights,[0,2,1])[:,0],dtype=tf.float32),-1)\r\n\t\t\t\t\r\n\t\t\t\tunary_layer1=unary_layer1*sentence_mask\r\n\t\t\t\tunary_layer2=unary_layer2*sentence_mask\r\n\t\t\t\tif self.separate_embed:\r\n\t\t\t\t\tsib_head, sib_dep, gp_head, gp_dep, gp_headdep, cop_head, cop_dep = sib_head*sentence_mask, sib_dep*sentence_mask,\\\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tgp_head*sentence_mask, gp_dep*sentence_mask,\\\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tgp_headdep*sentence_mask, cop_head*sentence_mask,\\\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcop_dep*sentence_mask\r\n\t\t\t\telse:\r\n\t\t\t\t\tif not self.separate_embed:\r\n\t\t\t\t\t\tlayer1=layer1*sentence_mask\r\n\t\t\t\t\t\tlayer2=layer2*sentence_mask\r\n\t\t\t\t\tlayer3=layer3*sentence_mask\r\n\t\t\t\tpass\r\n\t\t\twith tf.variable_scope('Discriminator'):\r\n\t\t\t\tif self.diagonal:\r\n\t\t\t\t\tlogits = classifiers.diagonal_bilinear_discriminator(\r\n\t\t\t\t\t\tlayer1, layer2,\r\n\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob,\r\n\t\t\t\t\t\tadd_linear=add_linear)\r\n\t\t\t\t\tif self.linearize:\r\n\t\t\t\t\t\twith tf.variable_scope('Linearization'):\r\n\t\t\t\t\t\t\tlin_logits = classifiers.diagonal_bilinear_discriminator(\r\n\t\t\t\t\t\t\t\tlin_layer1, lin_layer2,\r\n\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob,\r\n\t\t\t\t\t\t\t\tadd_linear=add_linear)\r\n\t\t\t\t\tif self.distance:\r\n\t\t\t\t\t\twith tf.variable_scope('Distance'):\r\n\t\t\t\t\t\t\tdist_lamda = 1+tf.nn.softplus(classifiers.diagonal_bilinear_discriminator(\r\n\t\t\t\t\t\t\t\tdist_layer1, dist_layer2,\r\n\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob,\r\n\t\t\t\t\t\t\t\tadd_linear=add_linear))\r\n\t\t\t\telse:\r\n\t\t\t\t\t#only run here\r\n\t\t\t\t\t#First order potential and second order potential\r\n\t\t\t\t\t#change it to two label discriminator, because we need a score for the condition of 0 and 1\r\n\t\t\t\t\t#(n x m x 2 x m)\r\n\r\n\t\t\t\t\t#with tf.device('/device:GPU:1'):\r\n\t\t\t\t\t'''\r\n\t\t\t\t\tunary, unary_weights = classifiers.bilinear_classifier(\r\n\t\t\t\t\t\tlayer1, layer2, 2,\r\n\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob,\r\n\t\t\t\t\t\tadd_linear=add_linear)\r\n\t\t\t\t\t'''\r\n\t\t\t\t\tunary = classifiers.bilinear_classifier(\r\n\t\t\t\t\t\tunary_layer1, unary_layer2, 2,\r\n\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob,\r\n\t\t\t\t\t\tadd_linear=add_linear,target_model='LBP', tri_std=self.tri_std_unary)\r\n\t\t\t\t\t#'''\r\n\t\t\t\t\t'''\r\n\t\t\t\t\tunary = classifiers.bilinear_discriminator(\r\n\t\t\t\t\t\tlayer1, layer2,\r\n\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob,\r\n\t\t\t\t\t\tadd_linear=add_linear)\r\n\t\t\t\t\t#'''\r\n\r\n\t\t\t\t\t\t\r\n\t\t\t\t\tif self.separate_embed:\r\n\t\t\t\t\t\tprint('separate')\r\n\t\t\t\t\t\t# head dep dep\r\n\t\t\t\t\t\tif self.test_new_potential:\r\n\t\t\t\t\t\t\tprint('testing new potential')\r\n\t\t\t\t\t\t\tif self.use_sib:\r\n\t\t\t\t\t\t\t\twith tf.variable_scope('Sibling'):\r\n\t\t\t\t\t\t\t\t\tlayer_sib = classifiers.trilinear_discriminator_outer(\r\n\t\t\t\t\t\t\t\t\t\tsib_head, sib_dep, sib_dep,\r\n\t\t\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob_tri,\r\n\t\t\t\t\t\t\t\t\t\tadd_linear=add_linear, tri_std=self.tri_std, hidden_k=self.hidden_k)\r\n\t\t\t\t\t\t\t# head head+dep dep\r\n\t\t\t\t\t\t\tif self.use_gp:\r\n\t\t\t\t\t\t\t\twith tf.variable_scope('GrandParents'):\r\n\t\t\t\t\t\t\t\t\tlayer_gp = classifiers.trilinear_discriminator_outer(\r\n\t\t\t\t\t\t\t\t\t\tgp_head, gp_headdep, gp_dep,\r\n\t\t\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob_tri,\r\n\t\t\t\t\t\t\t\t\t\tadd_linear=add_linear, tri_std=self.tri_std, hidden_k=self.hidden_k)\r\n\t\t\t\t\t\t\t# head dep head\r\n\t\t\t\t\t\t\tif self.use_cop:\r\n\t\t\t\t\t\t\t\twith tf.variable_scope('CoParents'):\r\n\t\t\t\t\t\t\t\t\tlayer_cop = classifiers.trilinear_discriminator_outer(\r\n\t\t\t\t\t\t\t\t\t\tcop_head, cop_dep, cop_head,\r\n\t\t\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob_tri,\r\n\t\t\t\t\t\t\t\t\t\tadd_linear=add_linear, tri_std=self.tri_std, hidden_k=self.hidden_k)\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tif self.use_sib:\r\n\t\t\t\t\t\t\t\twith tf.variable_scope('Sibling'):\r\n\t\t\t\t\t\t\t\t\tlayer_sib = classifiers.trilinear_discriminator_new(\r\n\t\t\t\t\t\t\t\t\t\tsib_head, sib_dep, sib_dep,\r\n\t\t\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob_tri,\r\n\t\t\t\t\t\t\t\t\t\tadd_linear=add_linear,target_model='LBP',tri_std=self.tri_std)\r\n\t\t\t\t\t\t\tif self.use_gp:\r\n\t\t\t\t\t\t\t\twith tf.variable_scope('GrandParents'):\r\n\t\t\t\t\t\t\t\t\tlayer_gp= classifiers.trilinear_discriminator_new(\r\n\t\t\t\t\t\t\t\t\t\tgp_head, gp_headdep, gp_dep,\r\n\t\t\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob_tri,\r\n\t\t\t\t\t\t\t\t\t\tadd_linear=add_linear,target_model='LBP',tri_std=self.tri_std)\r\n\t\t\t\t\t\t\t\t\t#'''\r\n\t\t\t\t\t\t\t# head dep head\r\n\t\t\t\t\t\t\tif self.use_cop:\r\n\t\t\t\t\t\t\t\twith tf.variable_scope('CoParents'):\r\n\t\t\t\t\t\t\t\t\tlayer_cop = classifiers.trilinear_discriminator_new(\r\n\t\t\t\t\t\t\t\t\t\tcop_head, cop_dep, cop_head,\r\n\t\t\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob_tri,\r\n\t\t\t\t\t\t\t\t\t\tadd_linear=add_linear,target_model='LBP',tri_std=self.tri_std)\r\n\t\t\t\t\t\t\t\t\t#'''\r\n\t\t\t\t\telif not self.old_trilin:\r\n\t\t\t\t\t\tprint('head dep')\r\n\t\t\t\t\t\tif self.test_new_potential:\r\n\t\t\t\t\t\t\tprint('testing new potential')\r\n\t\t\t\t\t\t\t# head dep dep\r\n\t\t\t\t\t\t\tif self.use_sib:\r\n\t\t\t\t\t\t\t\twith tf.variable_scope('Sibling'):\r\n\t\t\t\t\t\t\t\t\tlayer_sib = classifiers.trilinear_discriminator_test(\r\n\t\t\t\t\t\t\t\t\t\tlayer1, layer2, layer2,\r\n\t\t\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob_tri,\r\n\t\t\t\t\t\t\t\t\t\tadd_linear=add_linear,target_model='LBP',tri_std=self.tri_std)\r\n\t\t\t\t\t\t\t# head head+dep dep\r\n\t\t\t\t\t\t\tif self.use_gp:\r\n\t\t\t\t\t\t\t\twith tf.variable_scope('GrandParents'):\r\n\t\t\t\t\t\t\t\t\tlayer_gp = classifiers.trilinear_discriminator_test(\r\n\t\t\t\t\t\t\t\t\t\tlayer1, layer3, layer2,\r\n\t\t\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob_tri,\r\n\t\t\t\t\t\t\t\t\t\tadd_linear=add_linear,target_model='LBP',tri_std=self.tri_std)\r\n\t\t\t\t\t\t\t# head dep head\r\n\t\t\t\t\t\t\tif self.use_cop:\r\n\t\t\t\t\t\t\t\twith tf.variable_scope('CoParents'):\r\n\t\t\t\t\t\t\t\t\tlayer_cop = classifiers.trilinear_discriminator_test(\r\n\t\t\t\t\t\t\t\t\t\tlayer1, layer2, layer1,\r\n\t\t\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob_tri,\r\n\t\t\t\t\t\t\t\t\t\tadd_linear=add_linear,target_model='LBP',tri_std=self.tri_std)\r\n\t\t\t\t\t\t#=================================================\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t# head dep dep\r\n\t\t\t\t\t\t\tif self.use_sib:\r\n\t\t\t\t\t\t\t\twith tf.variable_scope('Sibling'):\r\n\t\t\t\t\t\t\t\t\tlayer_sib = classifiers.trilinear_discriminator_new(\r\n\t\t\t\t\t\t\t\t\t\tlayer1, layer2, layer2,\r\n\t\t\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob_tri,\r\n\t\t\t\t\t\t\t\t\t\tadd_linear=add_linear,target_model='LBP',tri_std=self.tri_std)\r\n\t\t\t\t\t\t\t# head head+dep dep\r\n\t\t\t\t\t\t\tif self.use_gp:\r\n\t\t\t\t\t\t\t\twith tf.variable_scope('GrandParents'):\r\n\t\t\t\t\t\t\t\t\tlayer_gp = classifiers.trilinear_discriminator_new(\r\n\t\t\t\t\t\t\t\t\t\tlayer1, layer3, layer2,\r\n\t\t\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob_tri,\r\n\t\t\t\t\t\t\t\t\t\tadd_linear=add_linear,target_model='LBP',tri_std=self.tri_std)\r\n\t\t\t\t\t\t\t# head dep head\r\n\t\t\t\t\t\t\tif self.use_cop:\r\n\t\t\t\t\t\t\t\twith tf.variable_scope('CoParents'):\r\n\t\t\t\t\t\t\t\t\tlayer_cop = classifiers.trilinear_discriminator_new(\r\n\t\t\t\t\t\t\t\t\t\tlayer1, layer2, layer1,\r\n\t\t\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob_tri,\r\n\t\t\t\t\t\t\t\t\t\tadd_linear=add_linear,target_model='LBP',tri_std=self.tri_std)\r\n\t\t\t\t\t#-----------------------------------------------------------\r\n\t\t\t\t\tif self.linearize:\r\n\t\t\t\t\t\twith tf.variable_scope('Linearization'):\r\n\t\t\t\t\t\t\tlin_logits = classifiers.bilinear_discriminator(\r\n\t\t\t\t\t\t\t\tlin_layer1, lin_layer2,\r\n\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob,\r\n\t\t\t\t\t\t\t\tadd_linear=add_linear)\r\n\t\t\t\t\tif self.distance:\r\n\t\t\t\t\t\twith tf.variable_scope('Distance'):\r\n\t\t\t\t\t\t\tdist_lamda = 1+tf.nn.softplus(classifiers.bilinear_discriminator(\r\n\t\t\t\t\t\t\t\tdist_layer1, dist_layer2,\r\n\t\t\t\t\t\t\t\thidden_keep_prob=hidden_keep_prob,\r\n\t\t\t\t\t\t\t\tadd_linear=add_linear))\r\n\t\t\t\t\r\n\t\t\t\tbinary_shape = layer_sib.shape.as_list()\r\n\t\t\t\tif debug:\r\n\t\t\t\t\toutputs['printdata']={}\r\n\t\t\t\t\tif self.new_potential:\r\n\t\t\t\t\t\toutputs['printdata']['unary_old']=unary\r\n\t\t\t\t\tif self.use_sib:\r\n\t\t\t\t\t\toutputs['printdata']['layer_sib_old']=layer_sib\r\n\t\t\t\t\tif self.use_cop:\r\n\t\t\t\t\t\toutputs['printdata']['layer_cop_old']=layer_cop\r\n\t\t\t\t\tif self.use_gp:\r\n\t\t\t\t\t\toutputs['printdata']['layer_gp_old']=layer_gp\r\n\r\n\t\t\t\t#======================LBP==========================\r\n\t\t\t\t\r\n\t\t\t\t#pdb.set_trace()\r\n\t\t\t\t#update: use log space for LBP\r\n\t\t\t\tif self.two_gpu:\r\n\t\t\t\t\tprint('two gpu training for LBP')\r\n\t\t\t\t\t#pdb.set_trace()\r\n\t\t\t\t\tGPUID=1\r\n\t\t\t\telse:\r\n\t\t\t\t\tGPUID=0\r\n\t\t\t\twith tf.device('/device:GPU:'+str(GPUID)):  \r\n\t\t\t\t\tif self.use_sib:\r\n\t\t\t\t\t\tlayer_type=layer_sib\r\n\t\t\t\t\telif self.use_cop:\r\n\t\t\t\t\t\tlayer_type=layer_cop\r\n\t\t\t\t\telif self.use_gp:\r\n\t\t\t\t\t\tlayer_type=layer_gp\r\n\t\t\t\t\t# (n x 2 x ma x mb x mc) ab <- ac\r\n\t\t\t\t\tlog_message_sib=tf.stack([tf.zeros_like(layer_type),tf.zeros_like(layer_type)],1)\r\n\t\t\t\t\t# (n x 2 x ma x mb x mc) ab <- cb\r\n\t\t\t\t\tlog_message_cop=tf.stack([tf.zeros_like(layer_type),tf.zeros_like(layer_type)],1)\r\n\t\t\t\t\t# (n x 2 x ma x mb x mc) ab <- bc \r\n\t\t\t\t\tlog_message_gp1=tf.stack([tf.zeros_like(layer_type),tf.zeros_like(layer_type)],1)\r\n\t\t\t\t\t# (n x 2 x ma x mb x mc) ab <- ca \r\n\t\t\t\t\tlog_message_gp2=tf.stack([tf.zeros_like(layer_type),tf.zeros_like(layer_type)],1)\r\n\t\t\t\t\t#pdb.set_trace()\r\n\t\t\t\t\t#'''\r\n\t\t\t\t\tif self.layer_mask:\r\n\t\t\t\t\t\tprint('use layer mask')\r\n\t\t\t\t\t\tunary=unary*tf.cast(tf.expand_dims(tf.transpose(token_weights,[0,2,1]),-2),dtype=tf.float32)\r\n\t\t\t\t\t\tif self.remove_root_child:\r\n\t\t\t\t\t\t\t# abc -> ab,ac\r\n\t\t\t\t\t\t\tif self.use_sib:\r\n\t\t\t\t\t\t\t\tlayer_sib=layer_sib*self.token_weights_sib\r\n\t\t\t\t\t\t\t\tlog_message_sib=log_message_sib*self.token_weights_sib[:,None,:,:,:]\r\n\t\t\t\t\t\t\tif self.use_cop:\r\n\t\t\t\t\t\t\t\tlayer_cop=layer_cop*self.token_weights_cop\r\n\t\t\t\t\t\t\t\tlog_message_cop=log_message_cop*self.token_weights_cop[:,None,:,:,:]\r\n\t\t\t\t\t\t\tif self.use_gp:\r\n\t\t\t\t\t\t\t\tlayer_gp=layer_gp*self.token_weights_gp\r\n\t\t\t\t\t\t\t\tlog_message_gp1=log_message_gp1*self.token_weights_gp[:,None,:,:,:]\r\n\t\t\t\t\t\t\t\tlog_message_gp2=log_message_gp2*self.token_weights_gp2[:,None,:,:,:]\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tif self.use_sib:\r\n\t\t\t\t\t\t\t\tlayer_sib=layer_sib*token_weights4D\r\n\t\t\t\t\t\t\tif self.use_cop:\r\n\t\t\t\t\t\t\t\tlayer_cop=layer_cop*token_weights4D\r\n\t\t\t\t\t\t\tif self.use_gp:\r\n\t\t\t\t\t\t\t\tlayer_gp=layer_gp*token_weights4D\r\n\t\t\t\t\t\t\ttoken_weights4D=tf.expand_dims(token_weights4D,1)\r\n\t\t\t\t\t\t\tif self.use_sib:\r\n\t\t\t\t\t\t\t\tlog_message_sib=log_message_sib*token_weights4D\r\n\t\t\t\t\t\t\tif self.use_cop:\r\n\t\t\t\t\t\t\t\tlog_message_cop=log_message_cop*token_weights4D\r\n\t\t\t\t\t\t\tif self.use_gp:\r\n\t\t\t\t\t\t\t\tlog_message_gp1=log_message_gp1*token_weights4D\r\n\t\t\t\t\t\t\t\tlog_message_gp2=log_message_gp2*token_weights4D\r\n\t\t\t\t\t#'''\r\n\t\t\t\t\t#(n x m x 2 x m) -> (n x 2 x m x m)\r\n\t\t\t\t\tbatch_size=nn.get_sizes(layer_sib)[0]\r\n\t\t\t\t\tunary=tf.transpose(unary,[0,2,1,3])\r\n\t\t\t\t\tif self.use_sib:\r\n\t\t\t\t\t\tlayer_sib = layer_sib-tf.linalg.band_part(layer_sib,-1,0) + tf.transpose(tf.linalg.band_part(layer_sib,0,-1),perm=[0,1,3,2])\r\n\t\t\t\t\tif self.use_gp:\r\n\t\t\t\t\t\tlayer_gp2 = tf.transpose(layer_gp,perm=[0,2,3,1])\r\n\t\t\t\t\tif self.use_cop:\r\n\t\t\t\t\t\t#(n x ma x mb x mc) -> (n x mb x ma x mc) \r\n\t\t\t\t\t\t#in order to create a symmtric tensor on ma and mc\r\n\t\t\t\t\t\tlayer_cop = tf.transpose(layer_cop,perm=[0,2,1,3])\r\n\t\t\t\t\t\t# first set lower triangle part to be zero, then assign the upper triangle part transposed to lower triangle part\r\n\t\t\t\t\t\tlayer_cop = layer_cop - tf.linalg.band_part(layer_cop,-1,0) + tf.transpose(tf.linalg.band_part(layer_cop,0,-1),perm=[0,1,3,2])\r\n\t\t\t\t\t\t# Finally (n x mb x ma x mc) -> (n x ma x mb x mc)\r\n\t\t\t\t\t\tlayer_cop = tf.transpose(layer_cop,perm=[0,2,1,3])\r\n\t\t\t\t\tfor i in range(1,int(self.num_iteration)+1):\r\n\t\t\t\t\t\t#(n x ma x mb x mc x 2)\r\n\t\t\t\t\t\tprev_sib=log_message_sib\r\n\t\t\t\t\t\tprev_cop=log_message_cop\r\n\t\t\t\t\t\tprev_gp1=log_message_gp1\r\n\t\t\t\t\t\tprev_gp2=log_message_gp2\r\n\t\t\t\t\t\t#first gp is a->b->c second is c->a->b\r\n\t\t\t\t\t\t#(n x 2 x ma x mb x mc) -> (n x 2 x ma x mb)\r\n\t\t\t\t\t\t#TODO: add mask when message passing\r\n\t\t\t\t\t\tFP=tf.reduce_sum(prev_gp1,-1)+tf.reduce_sum(prev_gp2,-1)+tf.reduce_sum(prev_cop,-1)+tf.reduce_sum(prev_sib,-1)\r\n\t\t\t\t\t\t#FP=tf.reduce_sum(prev_gp1,-1)+tf.reduce_sum(prev_gp2,-1)\r\n\t\t\t\t\t\tif debug:\r\n\t\t\t\t\t\t\toutputs['printdata']['FP0'+str(i)]=FP\r\n\t\t\t\t\t\t\toutputs['printdata']['prev_sib'+str(i)]=prev_sib\r\n\t\t\t\t\t\t\toutputs['printdata']['prev_cop'+str(i)]=prev_cop\r\n\t\t\t\t\t\t\toutputs['printdata']['prev_gp1'+str(i)]=prev_gp1\r\n\t\t\t\t\t\t\toutputs['printdata']['prev_gp2'+str(i)]=prev_gp2\r\n\t\t\t\t\t\t# remove self loop and self repeat (a b a) (a b b)\r\n\t\t\t\t\t\t#'''\r\n\t\t\t\t\t\tFP=FP-tf.transpose(tf.linalg.diag_part(tf.transpose(prev_sib,perm=[0,1,3,2,4])),perm=[0,1,3,2])-tf.linalg.diag_part(prev_sib)\r\n\t\t\t\t\t\tFP=FP-tf.transpose(tf.linalg.diag_part(tf.transpose(prev_cop,perm=[0,1,3,2,4])),perm=[0,1,3,2])-tf.linalg.diag_part(prev_cop)\r\n\t\t\t\t\t\tFP=FP-tf.transpose(tf.linalg.diag_part(tf.transpose(prev_gp1,perm=[0,1,3,2,4])),perm=[0,1,3,2])-tf.linalg.diag_part(prev_gp1)\r\n\t\t\t\t\t\tFP=FP-tf.transpose(tf.linalg.diag_part(tf.transpose(prev_gp2,perm=[0,1,3,2,4])),perm=[0,1,3,2])-tf.linalg.diag_part(prev_gp2)\r\n\t\t\t\t\t\t#'''\r\n\t\t\t\t\t\t#TODO: softmax form\r\n\t\t\t\t\t\tFP_potential=tf.expand_dims(unary+FP,-1)\r\n\t\t\t\t\t\tif self.use_sib:\r\n\t\t\t\t\t\t\t#update sibling\r\n\t\t\t\t\t\t\t#pdb.set_trace()\r\n\t\t\t\t\t\t\t#(n x 2 x ma x mc) -> (n x 2 x ma x mc x 1) - (n x 2 x ma x mc x mb)-> (n x 2 x ma x mc x mb)-> (n x 2 x ma x mb x mc)\r\n\t\t\t\t\t\t\tsib_FP=tf.transpose(FP_potential-prev_sib,perm=[0,1,2,4,3])\r\n\t\t\t\t\t\t\tlog_message_sib_0=tf.reduce_logsumexp(sib_FP,axis=1)\r\n\t\t\t\t\t\t\t#(n x ma x mb x mc) + (n x ma x mb x mc) -> (n x ma x mb x mc)\r\n\t\t\t\t\t\t\tlog_message_sib_1=tf.reduce_logsumexp(tf.stack([sib_FP[:,0],sib_FP[:,1]+layer_sib],1),axis=1)\r\n\t\t\t\t\t\t\t#(n x ma x mb x mc) -> (n x 2 x ma x mb x mc)\r\n\t\t\t\t\t\t\tlog_message_sib=tf.stack([log_message_sib_0,log_message_sib_1],axis=1)\r\n\t\t\t\t\t\tif self.use_cop:\r\n\t\t\t\t\t\t\t#update coparents\r\n\t\t\t\t\t\t\t#(n x 2 x mc x mb) -> (n x 2 x mc x mb x 1) - (n x 2 x mc x mb x ma)-> (n x 2 x mc x mb x ma)-> (n x 2 x ma x mb x mc)\r\n\t\t\t\t\t\t\tcop_FP=tf.transpose(FP_potential-prev_cop,perm=[0,1,4,3,2])\r\n\t\t\t\t\t\t\tlog_message_cop_0=tf.reduce_logsumexp(cop_FP,axis=1)\r\n\t\t\t\t\t\t\t#(n x ma x mb x mc) + (n x ma x mb x mc) -> (n x ma x mb x mc)\r\n\t\t\t\t\t\t\tlog_message_cop_1=tf.reduce_logsumexp(tf.stack([cop_FP[:,0],cop_FP[:,1]+layer_cop],1),axis=1)\r\n\t\t\t\t\t\t\t#(n x ma x mb x mc) -> (n x 2 x ma x mb x mc)\r\n\t\t\t\t\t\t\tlog_message_cop=tf.stack([log_message_cop_0,log_message_cop_1],axis=1)\r\n\t\t\t\t\t\tif self.use_gp:\r\n\t\t\t\t\t\t\t#update gp1 (a->b->c)\r\n\t\t\t\t\t\t\t#(n x 2 x ma x mc) -> (n x 2 x mb x mc x 1) - (n x 2 x mb x mc x ma)-> (n x 2 x mb x mc x ma)-> (n x 2 x ma x mb x mc)\r\n\t\t\t\t\t\t\t# Note that here gp1 should minus prev_gp2 as we need to keep ab->bc is still representing a->b->c\r\n\t\t\t\t\t\t\tgp_FP=tf.transpose(FP_potential-prev_gp2,perm=[0,1,4,2,3])\r\n\t\t\t\t\t\t\tlog_message_gp_0=tf.reduce_logsumexp(gp_FP,axis=1)\r\n\t\t\t\t\t\t\t#(n x ma x mb x mc) + (n x ma x mb x mc) -> (n x ma x mb x mc)\r\n\t\t\t\t\t\t\tlog_message_gp_1=tf.reduce_logsumexp(tf.stack([gp_FP[:,0],gp_FP[:,1]+layer_gp],1),axis=1)\r\n\t\t\t\t\t\t\t#(n x ma x mb x mc) -> (n x 2 x ma x mb x mc)\r\n\t\t\t\t\t\t\tlog_message_gp1=tf.stack([log_message_gp_0,log_message_gp_1],axis=1)\r\n\r\n\t\t\t\t\t\t\t#update gp2 (c->a->b)\r\n\t\t\t\t\t\t\t#(n x 2 x ma x mc) -> (n x 2 x mc x ma x 1) - (n x 2 x mc x ma x mb)-> (n x 2 x mc x ma x mb)-> (n x 2 x ma x mb x mc)\r\n\t\t\t\t\t\t\tgp2_FP=tf.transpose(FP_potential-prev_gp1,perm=[0,1,3,4,2])\r\n\t\t\t\t\t\t\tlog_message_gp2_0=tf.reduce_logsumexp(gp2_FP,axis=1)\r\n\t\t\t\t\t\t\t#(n x ma x mb x mc) + (n x ma x mb x mc) -> (n x ma x mb x mc)\r\n\t\t\t\t\t\t\tlog_message_gp2_1=tf.reduce_logsumexp(tf.stack([gp2_FP[:,0],gp2_FP[:,1]+layer_gp2],1),axis=1)\r\n\t\t\t\t\t\t\t#(n x ma x mb x mc) -> (n x 2 x ma x mb x mc)\r\n\t\t\t\t\t\t\tlog_message_gp2=tf.stack([log_message_gp2_0,log_message_gp2_1],axis=1)\r\n\t\t\t\t\t\tif self.normalize:\r\n\t\t\t\t\t\t\tif i==1:\r\n\t\t\t\t\t\t\t\tprint('normalize each LBP iteration')\r\n\t\t\t\t\t\t\tif self.use_sib:\r\n\t\t\t\t\t\t\t\tlog_message_sib=tf.nn.log_softmax(log_message_sib,1)\r\n\t\t\t\t\t\t\tif self.use_cop:\r\n\t\t\t\t\t\t\t\tlog_message_cop=tf.nn.log_softmax(log_message_cop,1)\r\n\t\t\t\t\t\t\tif self.use_gp:\r\n\t\t\t\t\t\t\t\tlog_message_gp1=tf.nn.log_softmax(log_message_gp1,1)\r\n\t\t\t\t\t\t\t\tlog_message_gp2=tf.nn.log_softmax(log_message_gp2,1)\r\n\t\t\t\t\t\tif self.layer_mask:\r\n\t\t\t\t\t\t\tif self.remove_root_child:\r\n\t\t\t\t\t\t\t\t# abc -> ab,ac\r\n\t\t\t\t\t\t\t\tif self.use_sib:\r\n\t\t\t\t\t\t\t\t\tlayer_sib=layer_sib*self.token_weights_sib\r\n\t\t\t\t\t\t\t\tif self.use_cop:\r\n\t\t\t\t\t\t\t\t\tlayer_cop=layer_cop*self.token_weights_cop\r\n\t\t\t\t\t\t\t\tif self.use_gp:\r\n\t\t\t\t\t\t\t\t\tlayer_gp=layer_gp*self.token_weights_gp\r\n\t\t\t\t\t\t\t\tlog_message_sib=log_message_sib*self.token_weights_sib[:,None,:,:,:]\r\n\t\t\t\t\t\t\t\tlog_message_cop=log_message_cop*self.token_weights_cop[:,None,:,:,:]\r\n\t\t\t\t\t\t\t\tlog_message_gp1=log_message_gp1*self.token_weights_gp[:,None,:,:,:]\r\n\t\t\t\t\t\t\t\tlog_message_gp2=log_message_gp2*self.token_weights_gp2[:,None,:,:,:]\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\tlog_message_sib=log_message_sib*token_weights4D\r\n\t\t\t\t\t\t\t\tlog_message_cop=log_message_cop*token_weights4D\r\n\t\t\t\t\t\t\t\tlog_message_gp1=log_message_gp1*token_weights4D\r\n\t\t\t\t\t\t\t\tlog_message_gp2=log_message_gp2*token_weights4D\r\n\t\t\t\t\t\tif debug:\r\n\t\t\t\t\t\t\t'''\r\n\t\t\t\t\t\t\toutputs['printdata']['gp2_FP'+str(i)]=gp2_FP\r\n\t\t\t\t\t\t\toutputs['printdata']['FP_potential'+str(i)]=FP_potential\r\n\t\t\t\t\t\t\toutputs['printdata']['FP4'+str(i)]=FP\r\n\t\t\t\t\t\t\toutputs['printdata']['sib_FP'+str(i)]=sib_FP\r\n\t\t\t\t\t\t\toutputs['printdata']['cop_FP'+str(i)]=cop_FP\r\n\t\t\t\t\t\t\toutputs['printdata']['gp1_FP'+str(i)]=gp_FP\r\n\t\t\t\t\t\t\toutputs['printdata']['gp2_FP'+str(i)]=gp2_FP\r\n\t\t\t\t\t\t\toutputs['printdata']['message_sib_0'+str(i)]=log_message_sib_0\r\n\t\t\t\t\t\t\toutputs['printdata']['message_sib_1'+str(i)]=log_message_sib_1\r\n\t\t\t\t\t\t\toutputs['printdata']['message_sib'+str(i)]=log_message_sib\r\n\t\t\t\t\t\t\toutputs['printdata']['message_cop_0'+str(i)]=log_message_cop_0\r\n\t\t\t\t\t\t\toutputs['printdata']['message_cop_1'+str(i)]=log_message_cop_1\r\n\t\t\t\t\t\t\toutputs['printdata']['message_cop'+str(i)]=log_message_cop\r\n\t\t\t\t\t\t\toutputs['printdata']['message_gp1'+str(i)]=log_message_gp1\r\n\t\t\t\t\t\t\toutputs['printdata']['message_gp2'+str(i)]=log_message_gp2\r\n\t\t\t\t\t\t\toutputs['printdata']['message_gp1_0'+str(i)]=log_message_gp_0\r\n\t\t\t\t\t\t\toutputs['printdata']['message_gp1_1'+str(i)]=log_message_gp_1\r\n\t\t\t\t\t\t\toutputs['printdata']['message_gp2_0'+str(i)]=log_message_gp2_0\r\n\t\t\t\t\t\t\toutputs['printdata']['message_gp2_1'+str(i)]=log_message_gp2_1\r\n\t\t\t\t\t\t\t#'''\r\n\t\t\t\t\t\t\tpass\r\n\r\n\t\t\t\t\tlog_belief=tf.reduce_sum(log_message_gp1,-1)+tf.reduce_sum(log_message_gp2,-1)+tf.reduce_sum(log_message_cop,-1)+tf.reduce_sum(log_message_sib,-1)\r\n\t\t\t\t\t#log_belief=tf.reduce_sum(log_message_gp1,-1)+tf.reduce_sum(log_message_gp2,-1)\r\n\t\t\t\t\t# remove self loop and self repeat (a b a) (a b b)\r\n\t\t\t\t\t#'''\r\n\t\t\t\t\tlog_belief=log_belief-tf.transpose(tf.linalg.diag_part(tf.transpose(log_message_sib,perm=[0,1,3,2,4])),perm=[0,1,3,2])-tf.linalg.diag_part(log_message_sib)\r\n\t\t\t\t\tlog_belief=log_belief-tf.transpose(tf.linalg.diag_part(tf.transpose(log_message_cop,perm=[0,1,3,2,4])),perm=[0,1,3,2])-tf.linalg.diag_part(log_message_cop)\r\n\t\t\t\t\tlog_belief=log_belief-tf.transpose(tf.linalg.diag_part(tf.transpose(log_message_gp1,perm=[0,1,3,2,4])),perm=[0,1,3,2])-tf.linalg.diag_part(log_message_gp1)\r\n\t\t\t\t\tlog_belief=log_belief-tf.transpose(tf.linalg.diag_part(tf.transpose(log_message_gp2,perm=[0,1,3,2,4])),perm=[0,1,3,2])-tf.linalg.diag_part(log_message_gp2)\r\n\t\t\t\t\t#'''\r\n\t\t\t\t\tlog_belief=log_belief+unary\r\n\t\t\t\t\t#q_value=belief/tf.reduce_sum(belief,axis=1,keepdims=True)\r\n\t\t\t\t\t#calculate softmax loss later\r\n\t\t\t\t\tq_value=log_belief\r\n\t\t\t\t\tif debug:\r\n\t\t\t\t\t\toutputs['printdata']['message_sib_fin']=tf.reduce_sum(log_message_sib,-1)-tf.transpose(tf.linalg.diag_part(tf.transpose(log_message_sib,perm=[0,1,3,2,4])),perm=[0,1,3,2])-tf.linalg.diag_part(log_message_sib)\r\n\t\t\t\t\t\toutputs['printdata']['message_cop_fin']=tf.reduce_sum(log_message_cop,-1)-tf.transpose(tf.linalg.diag_part(tf.transpose(log_message_cop,perm=[0,1,3,2,4])),perm=[0,1,3,2])-tf.linalg.diag_part(log_message_cop)\r\n\t\t\t\t\t\toutputs['printdata']['message_gp1_fin']=tf.reduce_sum(log_message_gp1,-1)-tf.transpose(tf.linalg.diag_part(tf.transpose(log_message_gp1,perm=[0,1,3,2,4])),perm=[0,1,3,2])-tf.linalg.diag_part(log_message_gp1)\r\n\t\t\t\t\t\toutputs['printdata']['message_gp2_fin']=tf.reduce_sum(log_message_gp2,-1)-tf.transpose(tf.linalg.diag_part(tf.transpose(log_message_gp2,perm=[0,1,3,2,4])),perm=[0,1,3,2])-tf.linalg.diag_part(log_message_gp2)\r\n\t\t\t\t\t#======================LBP==========================\r\n\r\n\t\t\t\t\r\n\t\t\t\t\t#-----------------------------------------------------------\r\n\t\t\t\t\t# Process the targetsb\r\n\t\t\t\t\t# (n x m x m) -> (n x m x m)\r\n\t\t\t\t\t#here in fact is a graph, which is m*m representing the connection between each edge\r\n\t\t\t\t\tunlabeled_targets = self.placeholder#ground truth graph, what is self.placeholder?\r\n\t\t\t\t\t#USELESS\r\n\t\t\t\t\tshape = tf.shape(unary_layer1)\r\n\t\t\t\t\tbatch_size, bucket_size = shape[0], shape[1]\r\n\t\t\t\t\t# (1 x m)\r\n\t\t\t\t\tids = tf.expand_dims(tf.range(bucket_size), 0)\r\n\t\t\t\t\t# (1 x m) -> (1 x 1 x m)\r\n\t\t\t\t\thead_ids = tf.expand_dims(ids, -2)\r\n\t\t\t\t\t# (1 x m) -> (1 x m x 1)\r\n\t\t\t\t\tdep_ids = tf.expand_dims(ids, -1)\r\n\t\t\t\t\t#pdb.set_trace()\r\n\t\t\t\t\tif debug:\r\n\t\t\t\t\t\t#outputs['printdata']['logits']=logits\r\n\t\t\t\t\t\toutputs['printdata']['q_value']=q_value\r\n\t\t\t\t\t\toutputs['printdata']['unary']=unary\r\n\t\t\t\t\t\t#outputs['printdata']['binary']=binary\r\n\t\t\t\t\t\toutputs['printdata']['belief']=log_belief\r\n\t\t\t\t\t\tif self.use_sib:\r\n\t\t\t\t\t\t\toutputs['printdata']['message_sib']=log_message_sib\r\n\t\t\t\t\t\t\toutputs['printdata']['message_sib_0']=log_message_sib_0\r\n\t\t\t\t\t\t\toutputs['printdata']['layer_sib']=layer_sib\r\n\t\t\t\t\t\tif self.use_gp:\r\n\t\t\t\t\t\t\t#outputs['printdata']['second_temp_gp']=second_temp_gp\r\n\t\t\t\t\t\t\toutputs['printdata']['message_gp1']=log_message_gp1\r\n\t\t\t\t\t\t\toutputs['printdata']['message_gp2']=log_message_gp2\r\n\t\t\t\t\t\t\toutputs['printdata']['layer_gp']=layer_gp\r\n\t\t\t\t\t\tif self.use_cop:\r\n\t\t\t\t\t\t\toutputs['printdata']['layer_cop']=layer_cop\r\n\t\t\t\t\t\t\toutputs['printdata']['message_cop']=log_message_cop\r\n\t\t\t\t\t\t#outputs['printdata']['layer1']=layer1\r\n\t\t\t\t\t\t#outputs['printdata']['layer2']=layer2\r\n\t\t\t\t\t\tif not self.separate_embed:\r\n\t\t\t\t\t\t\toutputs['printdata']['layer3']=layer3\r\n\t\t\t\t\t\toutputs['printdata']['targets']=unlabeled_targets\r\n\t\t\t\t\t\toutputs['printdata']['token_weights']=token_weights\r\n\t\t\t\t\t\tif self.sibling_only:\r\n\t\t\t\t\t\t\toutputs['printdata']['binary_weights']=binary_weights \r\n\t\t\t\t\t\t\toutputs['printdata']['binary']=layer_sib\r\n\t\t\t\t\t\tif self.new_potential:\r\n\t\t\t\t\t\t\t\t#outputs['printdata']['layer_sib2']=layer_sib2\r\n\t\t\t\t\t\t\t\toutputs['printdata']['layer_gp2']=layer_gp2\r\n\t\t\t\t\t\t\t\t#outputs['printdata']['layer_cop2']=layer_cop2\r\n\t\t\t\t\t\t\t\tpass\r\n\t\t\t\t\t\t#outputs['printdata']['binary_weights']=binary_weights\r\n\t\t\t\t\t\t'''\r\n\t\t\t\t\t\toutputs['printdata']['unary_weights']=unary_weights\r\n\t\t\t\t\t\toutputs['printdata']['binary_weights']=binary_weights\r\n\t\t\t\t\t\toutputs['printdata']['binary_weights_cop']=binary_weights_cop\r\n\t\t\t\t\t\toutputs['printdata']['binary_weights_gp']=binary_weights_gp\r\n\t\t\t\t\t\t#'''\r\n\r\n\t\t\t\t\t#no running here\r\n\t\t\t\t\tif self.linearize:\r\n\t\t\t\t\t\t# Wherever the head is to the left\r\n\t\t\t\t\t\t# (n x m x m), (1 x m x 1) -> (n x m x m)\r\n\t\t\t\t\t\tlin_targets = tf.to_float(tf.less(unlabeled_targets, dep_ids))\r\n\t\t\t\t\t\t# cross-entropy of the linearization of each i,j pair\r\n\t\t\t\t\t\t# (1 x 1 x m), (1 x m x 1) -> (n x m x m)\r\n\t\t\t\t\t\tlin_ids = tf.tile(tf.less(head_ids, dep_ids), [batch_size, 1, 1])\r\n\t\t\t\t\t\t# (n x 1 x m), (n x m x 1) -> (n x m x m)\r\n\t\t\t\t\t\tlin_xent = -tf.nn.softplus(tf.where(lin_ids, -lin_logits, lin_logits))\r\n\t\t\t\t\t\t# add the cross-entropy to the logits\r\n\t\t\t\t\t\t# (n x m x m), (n x m x m) -> (n x m x m)\r\n\t\t\t\t\t\tlogits += tf.stop_gradient(lin_xent)\r\n\t\t\t\t\tif self.distance:\r\n\t\t\t\t\t\t# (n x m x m) - (1 x m x 1) -> (n x m x m)\r\n\t\t\t\t\t\tdist_targets = tf.abs(unlabeled_targets - dep_ids)\r\n\t\t\t\t\t\t# KL-divergence of the distance of each i,j pair\r\n\t\t\t\t\t\t# (1 x 1 x m) - (1 x m x 1) -> (n x m x m)\r\n\t\t\t\t\t\tdist_ids = tf.to_float(tf.tile(tf.abs(head_ids - dep_ids), [batch_size, 1, 1]))+1e-12\r\n\t\t\t\t\t\t# (n x m x m), (n x m x m) -> (n x m x m)\r\n\t\t\t\t\t\t#dist_kld = (dist_ids * tf.log(dist_lamda / dist_ids) + dist_ids - dist_lamda)\r\n\t\t\t\t\t\tdist_kld = -tf.log((dist_ids - dist_lamda)**2/2 + 1)\r\n\t\t\t\t\t\t# add the KL-divergence to the logits\r\n\t\t\t\t\t\t# (n x m x m), (n x m x m) -> (n x m x m)\r\n\t\t\t\t\t\tlogits += tf.stop_gradient(dist_kld)\r\n\t\t\t\t\t#pdb.set_trace()\r\n\t\t\t\t\t#-----------------------------------------------------------\r\n\t\t\t\t\t# Note: here need a transpose as the target is the transpose graph(or opposite direction of adjacency graph)\r\n\t\t\t\t\t# (n x 2 x ma x mb) -> (n x 2 x mb x ma)\r\n\t\t\t\t\tif self.transposed:\r\n\t\t\t\t\t\tq_value=tf.transpose(q_value, [0,1,3,2])\r\n\t\t\t\t\t# Compute probabilities/cross entropy\r\n\t\t\t\t\t# (n x 2 x m x m) -> (n x m x m x 2)\r\n\t\t\t\t\ttransposed_logits = tf.transpose(q_value, [0,2,3,1])\r\n\t\t\t\t\tprobabilities=tf.nn.softmax(transposed_logits) * tf.to_float(tf.expand_dims(token_weights, axis=-1))\r\n\t\t\t\t\t#TODO: what I want is still a probability of label 1, compared to the origin sigmoid(logits)? check later\r\n\t\t\t\t\tprobabilities=probabilities[:,:,:,1]\r\n\t\t\t\t\t#label_probabilities = tf.nn.softmax(transposed_logits) * tf.to_float(tf.expand_dims(token_weights, axis=-1))\r\n\t\t\t\t\t# (n x m x m), (n x m x m x c), (n x m x m) -> ()\r\n\t\t\t\t\t# change sparse_softmax_cross_entropy to softmax_cross_entropy? It is the same in this situation\r\n\t\t\t\t\tloss = tf.losses.sparse_softmax_cross_entropy(unlabeled_targets, transposed_logits, weights=token_weights)\r\n\t\t\t\t\t#loss = tf.losses.sparse_sigmoid_cross_entropy(unlabeled_targets, transposed_logits, weights=token_weights)\r\n\t\t\t\t\t#pdb.set_trace()\r\n\t\t\t\t\t'''\r\n\t\t\t\t\ttransposed_logits=tf.nn.softmax(transposed_logits,-1)\r\n\t\t\t\t\tL2_target=tf.cast(unlabeled_targets,dtype=tf.float32)\r\n\t\t\t\t\tloss = tf.reduce_sum((tf.pow(L2_target-transposed_logits[:,:,:,1],2)+tf.pow(1-L2_target-transposed_logits[:,:,:,0],2))\\\r\n\t\t\t\t\t\t\t*tf.cast(token_weights,dtype=tf.float32))/tf.cast(batch_size,dtype=tf.float32)\r\n\t\t\t\t\tif debug:\r\n\t\t\t\t\t\toutputs['printdata']['L2_target']=L2_target\r\n\t\t\t\t\t\toutputs['printdata']['transposed_logits']=transposed_logits\r\n\t\t\t\t\t#'''\r\n\t\t\t\t\tif self.combine_loss:\r\n\t\t\t\t\t\tprint('use combined loss')\r\n\t\t\t\t\t\tunary_probs=-unary\r\n\t\t\t\t\t\t# similar to q_value\r\n\t\t\t\t\t\tif self.transposed:\r\n\t\t\t\t\t\t\tunary_probs=tf.transpose(unary_probs,[0,3,2,1])\r\n\t\t\t\t\t\tunary_probs=tf.transpose(unary_probs, [0,1,3,2])\r\n\t\t\t\t\t\t#loss /= 2\r\n\t\t\t\t\t\tloss = loss*self.loss_weight + tf.losses.sparse_softmax_cross_entropy(unlabeled_targets, unary_probs, weights=token_weights)*self.loss_weight_unary\r\n\t\t\t\t\t'''\r\n\t\t\t\t\t# (n x m x m) -> (n x m x m)\r\n\t\t\t\t\tprobabilities = tf.nn.sigmoid(logits) * tf.to_float(token_weights)#token weights is sentence length?\r\n\t\t\t\t\t# (n x m x m), (n x m x m), (n x m x m) -> ()\r\n\t\t\t\t\tloss = tf.losses.sigmoid_cross_entropy(unlabeled_targets, logits, weights=token_weights)#here label_smoothing is 0, the sigmoid XE have any effect?\r\n\t\t\t\t\t'''\r\n\t\t\t\t\tn_tokens = tf.to_float(tf.reduce_sum(token_weights))\r\n\t\t\t\t\tif self.linearize:\r\n\t\t\t\t\t\tlin_target_xent = lin_xent * unlabeled_targets\r\n\t\t\t\t\t\tloss -= tf.reduce_sum(lin_target_xent * tf.to_float(token_weights)) / (n_tokens + 1e-12)\r\n\t\t\t\t\tif self.distance:\r\n\t\t\t\t\t\tdist_target_kld = dist_kld * unlabeled_targets\r\n\t\t\t\t\t\tloss -= tf.reduce_sum(dist_target_kld * tf.to_float(token_weights)) / (n_tokens + 1e-12)\r\n\t\t\t\t\t\r\n\t\t\t\t\t#-----------------------------------------------------------\r\n\t\t\t\t\t# Compute predictions/accuracy \r\n\t\t\t\t\t# precision/recall\r\n\t\t\t\t\t# (n x m x m) -> (n x m x m)\r\n\t\t\t\t\t#predictions = nn.greater(logits, 0, dtype=tf.int32) * token_weights#edge that predicted\r\n\t\t\t\t\tpredictions = tf.argmax(transposed_logits, axis=-1, output_type=tf.int32) * token_weights\r\n\t\t\t\t\t# if self.compare_precision:\r\n\t\t\t\t\t# \tcond = tf.equal(transposed_logits[:,:,:,1], tf.expand_dims(tf.reduce_max(transposed_logits[:,:,:,1],-1),-1))\r\n\t\t\t\t\t# \tpredictions = tf.where(cond, tf.cast(cond,tf.float32), tf.zeros_like(transposed_logits[:,:,:,1])) \r\n\t\t\t\t\t# \tpredictions = tf.cast(predictions,tf.int32) * token_weights\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t# (n x m x m) (*) (n x m x m) -> (n x m x m)\r\n\t\t\t\t\ttrue_positives = predictions * unlabeled_targets\r\n\t\t\t\t\t# (n x m x m) -> ()\r\n\t\t\t\t\tn_predictions = tf.reduce_sum(predictions)\r\n\t\t\t\t\tn_targets = tf.reduce_sum(unlabeled_targets)\r\n\t\t\t\t\tn_true_positives = tf.reduce_sum(true_positives)\r\n\t\t\t\t\t# () - () -> ()\r\n\t\t\t\t\tn_false_positives = n_predictions - n_true_positives\r\n\t\t\t\t\tn_false_negatives = n_targets - n_true_positives\r\n\t\t\t\t\t# (n x m x m) -> (n)\r\n\t\t\t\t\tn_targets_per_sequence = tf.reduce_sum(unlabeled_targets, axis=[1,2])\r\n\t\t\t\t\tn_true_positives_per_sequence = tf.reduce_sum(true_positives, axis=[1,2])\r\n\t\t\t\t\t# (n) x 2 -> ()\r\n\t\t\t\t\tn_correct_sequences = tf.reduce_sum(nn.equal(n_true_positives_per_sequence, n_targets_per_sequence))\r\n\t\t\t#-----------------------------------------------------------\r\n\t\t\t# Populate the output dictionary\r\n\t\t\tif debug:\r\n\t\t\t\toutputs['printdata']['logits']=transposed_logits\r\n\t\t\t\toutputs['printdata']['loss']=loss\r\n\t\t\t#print(123)\r\n\t\t\toutputs['unlabeled_targets'] = unlabeled_targets\r\n\t\t\toutputs['probabilities'] = probabilities\r\n\t\t\toutputs['unlabeled_loss'] = loss\r\n\t\t\toutputs['loss'] = loss\r\n\t\t\t\r\n\t\t\toutputs['unlabeled_predictions'] = predictions\r\n\t\t\toutputs['n_unlabeled_true_positives'] = n_true_positives\r\n\t\t\toutputs['n_unlabeled_false_positives'] = n_false_positives\r\n\t\t\toutputs['n_unlabeled_false_negatives'] = n_false_negatives\r\n\t\t\toutputs['n_correct_unlabeled_sequences'] = n_correct_sequences\r\n\t\t\toutputs['predictions'] = predictions\r\n\t\t\toutputs['n_true_positives'] = n_true_positives\r\n\t\t\toutputs['n_false_positives'] = n_false_positives\r\n\t\t\toutputs['n_false_negatives'] = n_false_negatives\r\n\t\t\toutputs['n_correct_sequences'] = n_correct_sequences\r\n\t\t\treturn outputs\r\n\t\r\n\t\r\n\t#=============================================================\r\n\t# token should be: 1:rel|2:acl|5:dep or 1|2|5\r\n\tdef index(self, token):\r\n\t\t\"\"\"\"\"\"\r\n\t\t\r\n\t\tnodes = []\r\n\t\tif token != '_':\r\n\t\t\ttoken = token.split('|')\r\n\t\t\tfor edge in token:\r\n\t\t\t\thead = edge.split(':')[0]\r\n\t\t\t\tnodes.append(int(head))\r\n\t\treturn nodes\r\n\t\r\n\t#=============================================================\r\n\t# index should be [1, 2, 5]\r\n\tdef token(self, index):\r\n\t\t\"\"\"\"\"\"\r\n\t\t\r\n\t\treturn [str(head) for head in index]\r\n\t\r\n\t#=============================================================\r\n\tdef get_root(self):\r\n\t\t\"\"\"\"\"\"\r\n\t\t\r\n\t\treturn '_'\r\n\t\r\n\t#=============================================================\r\n\tdef __getitem__(self, key):\r\n\t\tif isinstance(key, six.string_types):\r\n\t\t\tnodes = []\r\n\t\t\tif key != '_':\r\n\t\t\t\ttoken = key.split('|')\r\n\t\t\t\tfor edge in token:\r\n\t\t\t\t\thead = edge.split(':')[0]\r\n\t\t\t\t\tnodes.append(int(head))\r\n\t\t\treturn nodes\r\n\t\telif hasattr(key, '__iter__'):\r\n\t\t\tif len(key) > 0:\r\n\t\t\t\tif isinstance(key[0], six.integer_types + (np.int32, np.int64)):\r\n\t\t\t\t\treturn '|'.join([str(head) for head in key])\r\n\t\t\t\telse:\r\n\t\t\t\t\treturn [self[k] for k in key]\r\n\t\t\telse:\r\n\t\t\t\treturn '_'\r\n\t\telse:\r\n\t\t\traise ValueError('Key to GraphIndexVocab.__getitem__ must be (iterable of) strings or iterable of integers')\r\n\t\r\n#***************************************************************\r\n\r\nclass SecondOrderGraphLBPVocab(GraphSecondLBPVocab, cv.SemheadVocab):\r\n\tpass\r\n", "meta": {"hexsha": "b17c856188818bcc31d6789b0cab089df75fa824", "size": 47435, "ext": "py", "lang": "Python", "max_stars_repo_path": "parser/structs/vocabs/second_order_LBP_vocab.py", "max_stars_repo_name": "shtechair/Second_Order_SDP", "max_stars_repo_head_hexsha": "d8e90aef1ff9bade86d602790adf08e37ed4c746", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2019-07-12T13:57:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T15:54:25.000Z", "max_issues_repo_path": "parser/structs/vocabs/second_order_LBP_vocab.py", "max_issues_repo_name": "shtechair/Second_Order_SDP", "max_issues_repo_head_hexsha": "d8e90aef1ff9bade86d602790adf08e37ed4c746", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-08-04T06:19:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-15T06:34:51.000Z", "max_forks_repo_path": "parser/structs/vocabs/second_order_LBP_vocab.py", "max_forks_repo_name": "shtechair/Second_Order_SDP", "max_forks_repo_head_hexsha": "d8e90aef1ff9bade86d602790adf08e37ed4c746", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-09-30T06:24:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T13:53:13.000Z", "avg_line_length": 42.0896184561, "max_line_length": 214, "alphanum_fraction": 0.6280172868, "include": true, "reason": "import numpy", "num_tokens": 13253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.1961404273446898}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon May  3 15:59:09 2021\r\n\r\nThis file is is and adaptation of the WorkMATe source code, from the article:\r\n    \"Flexible Working Memory through Selective Gating and Attentional Tagging\"\r\nWouter Kruijne, Sander M Bohte, Pieter R Roelfsema, Christian N L Olivers\r\n\r\n-------------------\r\nThe class defined in this file implements the WorkMATe model;\r\nEntry point for the model is the 'step()' function which defined what WorkMATe\r\ndoes during a single time step; this entails: \r\n1-  the feedforward sweep to determine its  next action, \r\n2-  Learning: update the weights in response to any potentially obtained reward\r\n3-  recurrent attentional feedback to place synaptic tags on connections \r\n    responsible for the selected action. \r\n4-  Executing the desired action, including possibly storing \r\n    an observation in memory.\r\n\r\nSeveral extensions are added to the original code --> making it a Deep WorkMATe\r\nwith CIFAAR-10 inputs and a locally learned matching function. \r\n1- An extra layer was added (latent) \r\n2- Timestamp is added at latent level, learning rate is set to 0.05\r\n3- Only weight updates are performed between trials\r\n4- Both CIFAR-10 latent features and the alphabet can be used as a stimulus dictionary\r\n\r\n@author: Lieke Ceton\r\n\"\"\"\r\n#%% Dependencies\r\n\r\nimport numpy as np \r\n\r\nfrom stimuli import obs_time, obs_cifar, match_cifar, obs_alpha, match_alpha\r\nfrom matchnet import MatchNet, cosine_similarity\r\n\r\n#%% Define WorkMATe architecture\r\n\r\n#np.random.seed(20)\r\nclass WorkMATe(object):\r\n    \"\"\"\r\n    Architecture schematic:\r\n    x -- l -- S\r\n          \\/\r\n          h\r\n          |\r\n    [q_int|q_ext]\r\n    \"\"\"\r\n    def __init__(self, env=None, nhidden=25, nblocks=2, block_size=20, lr=0.05, wh=0.5):\r\n        super(WorkMATe, self).__init__()\r\n        \r\n        #np.random.seed(20)\r\n        assert env is not None\r\n        self.env=env\r\n        \r\n        ## learning params (adopted from Rombouts et al., 2015)\r\n        self.beta = lr\r\n        self.gamma = 0.90\r\n        self.L = 0.8\r\n        # exploration:\r\n        self.epsilon = 0.025\r\n        self.bias = 1\r\n        print('Agent WorkMATe_match initialising')\r\n        \r\n        ## member lambda functions:\r\n        # sigmoid transfer function, offset at 2.5\r\n        sigmoid_offset = 2.5\r\n        self.transfer = lambda x: 1 / ( 1. + np.exp(sigmoid_offset - x) )\r\n        self.dtransfer= lambda x: x * (1. - x) # derivative\r\n        \r\n        # softmax normalization; for action selection - boltzmann controller\r\n        self.softmaxnorm = lambda x: (\r\n            np.exp( x - x.max() ) / np.exp( x - x.max() ) .sum() )\r\n\r\n        ## init network architecture -- inputs and output shape from env\r\n        # input and hidden\r\n        #nx = inputs.get_obs('a').size\r\n        nl = block_size\r\n        nh = nhidden\r\n        # memory cell properties:\r\n        self.nblocks = nblocks\r\n        self.block_size = block_size\r\n        nS = nblocks * block_size\r\n        \r\n        # output -- q layer consisting of 2 modules\r\n        # module for n external actions, internal actions for nblocks + 1 (null) \r\n        mod_sz = env.n_actions, nblocks + 1\r\n        nq = np.sum(mod_sz)\r\n        # indices of module for each node:\r\n        self.zmods = np.hstack( [ [i] * sz for i, sz in enumerate( mod_sz ) ] )\r\n\r\n        ## init network layers (activations 0)\r\n        # (x will be constructed when processing 'new_obs')\r\n        time_input = obs_time().size\r\n        if self.env.stim_type == 'alpha':\r\n            letter_input = obs_alpha().size\r\n        if self.env.stim_type == 'cifar':\r\n            letter_input = obs_cifar().size\r\n        \r\n        self.S = np.zeros( nS )\r\n        self.l = np.zeros( nl )\r\n        self.h = np.zeros( nh ) \r\n        self.q = np.zeros( nq ) \r\n\r\n        ## init weights, tags traces, (+1 indicates projection from bias node)\r\n        wl, wh = -wh, wh\r\n        \r\n        #Characteristics used as attributes for step_match()\r\n        self.ch = [letter_input, nl, nh, nS, wh, wl]  \r\n        \r\n        # Memory projection (x > S)\r\n        #self.W_Sx  = np.random.sample( (nS, nx) )  * (wh-wl) + wl \r\n        self.W_Sl  = np.random.sample( (nS, nl) )  * (wh-wl) + wl \r\n        # Note that time and sensory input cells are not separated in memory\r\n\r\n        # PLASTIC CONNECTIONS (all except memory projection)\r\n        \r\n        # Input projection with bias node\r\n        self.W_lx = np.random.sample((nl, letter_input + 1))*(wh-wl) + wl\r\n        #self.W_lx = np.array(W_lx)\r\n        self.W_lx_start = np.copy(self.W_lx)\r\n        \r\n        # connections l -> h; nl + match nodes + bias\r\n        self.W_hl  = np.random.sample( (nh, time_input + nl + nblocks + 1) ) * (wh-wl) + wl\r\n        self.W_hl_start = np.copy(self.W_hl)\r\n\r\n        # connections S-> h:\r\n        self.W_hS  = np.random.sample( (nh, nS    ) ) * (wh-wl) + wl\r\n        # connections h-> q:\r\n        self.W_qh  = np.random.sample( (nq, nh + 1) ) * (wh-wl) + wl\r\n        \r\n        # tags are shaped like weights but initialized at 0:\r\n        zeros_ = np.zeros_like\r\n        # W_lx is only updated between trials to keep memory trace stable \r\n        # W_lx_trial accumulates all changes made within a trial \r\n        self.W_lx_trial = zeros_(self.W_lx)\r\n\r\n        #initialise tags\r\n        self.Tag_W_lx, self.Trace_W_lx = zeros_(self.W_lx), zeros_(self.W_lx)\r\n        self.Tag_W_hl, self.Trace_W_hl = zeros_(self.W_hl), zeros_(self.W_hl)\r\n        self.Tag_W_hS, self.Trace_W_hS = zeros_(self.W_hS), zeros_(self.W_hS)\r\n        self.Tag_W_qh, self.Trace_W_qh = zeros_(self.W_qh), zeros_(self.W_qh)\r\n        \r\n        ## Init matchnet:\r\n        dummy_inp = np.zeros(block_size) #dummy input of length S == Sproj and Memory\r\n        self.matchnet = [MatchNet(dummy_inp, dummy_inp) for item in range(self.nblocks)]\r\n       \r\n        # Init action state\r\n        self.action = -1\r\n        # (prev) predicted reward:\r\n        self.qat_1 = self.qat = None\r\n        self.t   = 0 \r\n        return\r\n\r\n    def _intertrial_reset(self):\r\n        \"\"\"\r\n        Reset time, memory, tags and traces\r\n        \"\"\"\r\n        # update weights W_lx with the accumulated weight updates from the whole trial \r\n        self.W_lx += self.W_lx_trial\r\n\r\n        # reset time and memory\r\n        self.t = 0 \r\n        self.S *= 0\r\n\r\n        # previous action = zeros \r\n        self.z *= 1 #I set this from 0 to 1, it does not seem to change anything\r\n        # reset tags/traces for each Wmat\r\n        zeros_ = np.zeros_like\r\n        self.Tag_W_lx, self.Trace_W_lx = zeros_(self.W_lx), zeros_(self.W_lx)\r\n        self.Tag_W_hl, self.Trace_W_hl = zeros_(self.W_hl), zeros_(self.W_hl)\r\n        self.Tag_W_hS, self.Trace_W_hS = zeros_(self.W_hS), zeros_(self.W_hS)\r\n        self.Tag_W_qh, self.Trace_W_qh = zeros_(self.W_qh), zeros_(self.W_qh)\r\n        #reset accumulated weight updates W_lx\r\n        self.W_lx_trial = zeros_(self.W_lx)\r\n        \r\n        # reset 'current action', and the like\r\n        self.action = -1\r\n        self.qat = None\r\n        return\r\n    \r\n    def step_match(self):\r\n        if self.env.stim_type == 'cifar':\r\n            self.x_sens = match_cifar() #get random input\r\n        elif self.env.stim_type == 'alpha':\r\n            self.x_sens = match_alpha() #get random input\r\n            \r\n        self.x = np.r_[self.x_sens, self.bias]\r\n        Sproj = self.compute_latent()   #Compute the memory projection\r\n        Sproj = Sproj.reshape((self.nblocks, self.block_size)) \r\n        \r\n        #Decide on trial type and thus on memory content\r\n        #For each memory block there is a match network\r\n        #tt is the trial type: 0 is match, 1 is mismatch\r\n        #If tt = 0, the memory is updated to the current input\r\n        #The chance is around equal to save or not\r\n        tt = np.random.choice([0,1], self.nblocks, p=[0.5, 0.5])\r\n        S_ = self.S.reshape( (self.nblocks, self.block_size) )\r\n        for i in range(self.nblocks):\r\n            if tt[i] == 0:\r\n                S_[i,:] = Sproj[i,:]#the S projection should be here!\r\n                            \r\n        #Compute the match values\r\n        m, tt, corr = self.compute_match(Sproj)\r\n        \r\n        #Noise/random changes in weights W_lx and W_Sl\r\n        self.W_lx = np.random.sample((self.ch[1], self.ch[0] + 1))*(0.5--0.5) - 0.5\r\n        self.W_Sl  = np.random.sample((self.ch[3], self.ch[1]))*(self.ch[4]-self.ch[5]) + self.ch[5]\r\n\r\n        return m, tt, corr #return match values and trial_types\r\n        \r\n    def step(self):\r\n        # get observation and reward from env\r\n        self.obs, self.r = self.env.step(self.action) \r\n        # do feedforward:\r\n        #matches, tt_match = self._feedforward()\r\n        matches, tt = self._feedforward() \r\n        # learn from the obtained reward\r\n        self._learn()\r\n        # end of trial?\r\n        if 'RESET' == self.obs: #change in to == because the observation is now an integer not a string\r\n            self._intertrial_reset()\r\n            return self.r, None, None #fake matches\r\n        # do feedback (tag placement)\r\n        self._feedback()\r\n        # act (internal, external)\r\n        self._act()\r\n        self.t += 1\r\n        #return self.r, matches #, tt_match\r\n        return self.r, matches, tt\r\n\r\n    def _feedforward(self):\r\n        # shift previous action\r\n        self.qat_1 = self.qat\r\n        if 'RESET' == self.obs: #change in to == because the observation is now an integer not a string\r\n            # however, we do not expect RESET to ever only be part of the observation so the equal to boolean should be good enough\r\n            # no meaningful feedforward sweep:  qat is not computed\r\n            self.qat = None\r\n            return None, None #return fake match\r\n        # else:\r\n        # compute input, hidden, output:\r\n        self.construct_input()\r\n        Sproj = self.compute_latent()\r\n        matches, tt, _ = self.compute_match(Sproj)\r\n        self.compute_hidden(matches)\r\n        self.compute_output()\r\n        # determine z from q (action selection)\r\n        self.action_selection()\r\n        # determine new qat\r\n        self.qat = (self.z * self.q).sum()\r\n        return matches, tt\r\n\r\n    def _learn(self):\r\n        \"\"\"\r\n        Learn from the reward; compute RPE and update weights\r\n        general form form delta = r + gamma * qat - qat_1\r\n        ...but there are edge cases\r\n        \"\"\"\r\n        r = self.r\r\n        if self.qat and self.qat_1: # regular\r\n            delta = r + (self.gamma * self.qat) - self.qat_1\r\n        elif self.qat_1 is None: # first step\r\n            delta = r + (self.gamma * self.qat) - self.qat\r\n        else: # self.qa(t) is None (final step):\r\n            delta = r - self.qat_1\r\n        self.delta = delta\r\n        self.update_weights()\r\n        return\r\n\r\n    def _feedback(self):\r\n        # updates traces and tags, based on action selection:\r\n        # traces and tags\r\n        self.update_traces()\r\n        self.update_tags()\r\n        return\r\n\r\n    def _act(self):\r\n        # external and internal actions:\r\n        zext =  self.z[self.zmods == 0]\r\n        zint =  self.z[self.zmods == 1]\r\n        self.action = np.argmax(zext)\r\n        self.update_memory( zint )\r\n        return\r\n\r\n    def construct_input(self):\r\n        \"\"\"\r\n        Turn obs into a vector; uses coding defined in 'inputs.py'\r\n        \"\"\"\r\n        # input consists of: observation and time t\r\n        self.x_time = obs_time(self.t) #time-part\r\n        #letter-part\r\n        if self.env.stim_type == 'alpha':\r\n           self.x_sens = obs_alpha(self.obs)\r\n           #self.x_sens = inputs.obs_alpha_with_noise(self.obs)\r\n        if self.env.stim_type == 'cifar':\r\n           self.x_sens = obs_cifar(self.obs)\r\n           #self.x_sens = inputs.obs_orthogonal(self.obs)\r\n        #self.x_sens = inputs.get_obs(self.obs, self.t) #only letter-part\r\n        self.x = np.r_[self.x_sens, self.bias] #only bias included \r\n        return\r\n    \r\n    def compute_latent(self):\r\n        # x -> l \r\n        self.l_in = self.W_lx.dot(self.x)\r\n        # Compute l activities\r\n        self.l_sens = self.transfer(np.r_[self.l_in]) \r\n        # Compute match value:\r\n        Sproj = self.W_Sl.dot(self.l_in).reshape( (self.nblocks, self.block_size) )\r\n        return Sproj\r\n    \r\n    def compute_match(self, Sproj):\r\n        #output = self.matchnet.step(x,y)\r\n        matches = []\r\n        corr = []\r\n        tt = []\r\n        S_ = self.S.reshape( (self.nblocks, self.block_size) )\r\n        for i in range(self.nblocks):\r\n            m, _ = self.matchnet[i].step(Sproj[i,:], S_[i,:])\r\n            cos_corr = cosine_similarity(Sproj[i,:], S_[i,:])\r\n            corr.append(cos_corr)\r\n            matches.append(m)\r\n            if np.all(Sproj[i,:] == S_[i,:]):\r\n                 tt_match = 0\r\n            else: \r\n                 tt_match = 1\r\n            tt.append(tt_match)\r\n        return matches, tt, corr\r\n    \r\n    def compute_hidden(self, matches):\r\n        # add match nodes + bias to input vector\r\n        #add time-part here\r\n        self.l_out = np.r_[self.x_time, self.l_sens, matches, self.bias] #the matches are added here now\r\n        \r\n        # x->h  +  S->h\r\n        self.S_out  = self.S\r\n\r\n        # Compute Ha and h\r\n        h_in = self.W_hl.dot(self.l_out) + self.W_hS.dot(self.S_out)\r\n        self.h_out  = np.r_[self.transfer(h_in), self.bias] # bias added\r\n        return\r\n\r\n    def compute_output(self):\r\n        # hidden output (has bias added)\r\n        self.q = self.W_qh.dot(self.h_out)\r\n        # (no transfer, q nodes are linear)\r\n        return\r\n\r\n    def action_selection(self):\r\n        #np.random.seed(self.seed)\r\n        # using q, per module, determine z (based on argmax or exploration)\r\n        self.z = np.zeros_like(self.q)\r\n        # action selection for both modules separately\r\n        for mod_idx in np.unique(self.zmods):\r\n            qvec = self.q[self.zmods == mod_idx] # get the module's qvalues \r\n            # check exploration; if not just take argmax:\r\n            if ( np.random.sample() >= self.epsilon ):\r\n                action = np.argmax(qvec)\r\n            else: # compute softmax over Q and explore:\r\n                pvec = self.softmaxnorm(qvec)\r\n                action = np.random.choice( list(range(qvec.size)), p = pvec) \r\n            # set zvec: 1-hot code of actions:            \r\n            zvec = np.zeros_like(qvec)\r\n            zvec[ action ] = 1.0\r\n            # place zvec into z at the right indices:\r\n            self.z[self.zmods == mod_idx] = zvec\r\n        return\r\n\r\n    def update_weights(self):\r\n        \"\"\"\r\n        all Weight-Trace pairs are updated with the same rule:\r\n        w += beta * delta * tag\r\n        \"\"\"\r\n        #Only update W_lx during intertrial resets\r\n        #Accumulate changes during trial and update later\r\n        self.W_lx_trial += self.beta * self.delta * self.Tag_W_lx\r\n        \r\n        #Change the weights between h and S slower to have memory..\r\n        self.W_hS += self.beta * self.delta * self.Tag_W_hS\r\n        \r\n        wt_pairs = ( \r\n                     ( self.W_hl, self.Tag_W_hl ),    \r\n                     ( self.W_qh, self.Tag_W_qh )) #added by LJC\r\n        for W, Tag in wt_pairs:\r\n            W += self.beta * self.delta * Tag\r\n        \r\n        return\r\n\r\n    def update_traces(self):\r\n        \"\"\"\r\n        Traces are the intermediate layers' markers\r\n        The Traces are a relic from old AuGMEnT code, have no 'meaning' here\r\n        \"\"\"\r\n        # Regulars, are replaced by new input:\r\n        self.Trace_W_lx *= 0.0\r\n        self.Trace_W_hl *= 0.0\r\n        self.Trace_W_hS *= 0.0\r\n        # add 1 x X vec to H x X matrix yields H copies of 1 x X vec\r\n        self.Trace_W_lx += self.x.reshape(1, self.x.size) # this includes trace for bias\r\n        self.Trace_W_hl += self.l_out.reshape(1, self.l_out.size) # this includes trace for bias\r\n        self.Trace_W_hS += self.S_out.reshape(1, self.S.size)\r\n        return\r\n\r\n    def update_tags(self):\r\n        \r\n        # 1. old tag decay:\r\n        alltags = (self.Tag_W_lx, self.Tag_W_hl, self.Tag_W_hS, self.Tag_W_qh)\r\n        for Tag in alltags:\r\n            Tag *= (self.L * self.gamma)\r\n\r\n        # 2. form new tags:\r\n        # tags onto output units: selected action.\r\n        self.Tag_W_qh[self.z.astype('bool'), :] += self.h_out\r\n\r\n        # feedback to hidden\r\n        dh = self.dtransfer(self.h_out[:-1])\r\n        self.fbh = self.W_qh[self.z.astype('bool'), :-1] # excluding the bias node\r\n        self.fbh = self.fbh.sum(axis = 0 ) # summed contribution of all actions\r\n        self.feedbackh = self.fbh * dh\r\n        self.Tag_W_hS +=  np.expand_dims(self.feedbackh, 1) *  self.Trace_W_hS\r\n        #update tag hl\r\n        self.Tag_W_hl +=  np.expand_dims(self.feedbackh, 1) *  self.Trace_W_hl \r\n        \r\n        #feedback to latent\r\n        dl = self.dtransfer(self.l_sens)\r\n        self.fbh_transfer = self.dtransfer(self.fbh) #the feedback onto h is transferred through the hidden layer\r\n        #W_hl_no_m = self.W_hl[:,:-3] #no match no bias, no time-part\r\n        #W_hl_no_m = self.W_hl[:,10:30]\r\n        \r\n        W_hl_no_m = self.W_hl[:,obs_time().size:-(self.nblocks + 1)] #only learn back onto the stimulus input, not the time inputs (exclude the bias node)\r\n        #inputs.obs_time().size\r\n        \r\n        self.W_hl_transpose = W_hl_no_m.T\r\n        self.fhl = self.W_hl_transpose.dot(self.fbh_transfer) #for each node in l, all active h units are summed\r\n        self.feedbackl = self.fhl * dl\r\n        self.Tag_W_lx += np.expand_dims(self.feedbackl,1) * self.Trace_W_lx\r\n        return\r\n\r\n    def update_memory(self, zvec):\r\n        # final z is 'do not gate'; nothing happens then\r\n        if not zvec[-1] == 1:\r\n            # else:\r\n            gate_idx = np.argmax(zvec)\r\n            l = self.l_in   #this excludes bias- and  match\r\n            S_ = self.S.reshape( (self.nblocks, self.block_size) )\r\n            W_ = self.W_Sl.reshape( S_.shape +  (l.size, ) ) \r\n            # project x->S (encode)\r\n            Sproj = W_.dot(l)\r\n            # store @ gated 'stripe'\r\n            S_[gate_idx,:] = Sproj[gate_idx,:]\r\n            # transform S back to its flat representation\r\n            self.S = S_.reshape(self.S.shape)\r\n        return\r\n    \r\n\r\n\r\n", "meta": {"hexsha": "7706072e41df151cad1f27974c2d56d23afb536e", "size": 18202, "ext": "py", "lang": "Python", "max_stars_repo_path": "workmate_match.py", "max_stars_repo_name": "lieke2020/workmate_match", "max_stars_repo_head_hexsha": "803f4e3b1fa62280cc0d6a7cd61eb80929dae918", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "workmate_match.py", "max_issues_repo_name": "lieke2020/workmate_match", "max_issues_repo_head_hexsha": "803f4e3b1fa62280cc0d6a7cd61eb80929dae918", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "workmate_match.py", "max_forks_repo_name": "lieke2020/workmate_match", "max_forks_repo_head_hexsha": "803f4e3b1fa62280cc0d6a7cd61eb80929dae918", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0043956044, "max_line_length": 155, "alphanum_fraction": 0.5720799912, "include": true, "reason": "import numpy", "num_tokens": 4650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.37754065479083276, "lm_q1q2_score": 0.19614042006759222}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------------\n# glumpy is an OpenGL framework for the fast visualization of numpy arrays.\n# Copyright (C) 2009-2011  Nicolas P. Rougier. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n#    this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n#    notice, this list of conditions and the following disclaimer in the\n#    documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY NICOLAS P. ROUGIER ''AS IS'' AND ANY EXPRESS OR\n# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n# EVENT SHALL NICOLAS P. ROUGIER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n# The views and conclusions contained in the software and documentation are\n# those of the authors and should not be interpreted as representing official\n# policies, either expressed or implied, of Nicolas P. Rougier.\n# -----------------------------------------------------------------------------\n'''\nA filter is a shader that transform the current displayed texture. Since\nshaders cannot be easily serialized within the GPU, they have to be well\nstructured on the python side such that we can possibly merge them into a\nsingle source code for both vertex and fragment. Consequently, there is a\ndefault code for both vertex and fragment with specific entry points such that\nfilter knows where to insert their specific code (declarations, functions and\ncall (or code) to be inserted in the main function).\n\nSpatial interpolation filter classes for OpenGL textures.\n\nEach filter generates a one-dimensional lookup table (weights value from 0 to\nceil(radius)) that is uploaded to video memory (as a 1d texture) and is then\nread by the shader when necessary. It avoids computing weight values for each\npixel. Furthemore, each 2D-convolution filter is separable and can be computed\nusing 2 1D-convolution with same 1d-kernel (= the lookup table values).\n\nAvailable filters:\n\n  - Nearest  (radius 0.5)\n  - Bilinear (radius 1.0)\n  - Hanning (radius 1.0)\n  - Hamming (radius 1.0)\n  - Hermite (radius 1.0)\n  - Kaiser (radius 1.0)\n  - Quadric (radius 1.5)\n  - Bicubic (radius 2.0)\n  - CatRom (radius 2.0)\n  - Mitchell (radius 2.0)\n  - Spline16 (radius 2.0)\n  - Spline36 (radius 4.0)\n  - Gaussian (radius 2.0)\n  - Bessel (radius 3.2383)\n  - Sinc (radius 4.0)\n  - Lanczos (radius 4.0)\n  - Blackman (radius 4.0)\n\n\nNote::\n\n  Weights code has been translated from the antigrain geometry library\n  available at http://www.antigrain.com/\n'''\n\n\nimport math\nimport numpy as np\n\n\nclass SpatialFilter(object):\n    ''' '''\n\n    def __init__(self, radius=1.0):\n        self.radius = radius\n\n    def weight(self, x):\n        '''\n        Return filter weight for a distance x.\n\n        :Parameters:\n            ``x`` : 0 < float < ceil(self.radius)\n                Distance to be used to compute weight.\n        '''\n        raise NotImplemented\n\n    def kernel(self, size=4*512):\n        radius = self.radius\n        r = int(max(1.0, math.ceil(radius)))\n        samples = int(size / r)\n        n = size  # r*samples\n        kernel = np.zeros(n)\n        X = np.linspace(0, r, n)\n        for i in range(n):\n            kernel[i] = self.weight(X[i])\n        N = np.zeros(samples)\n        for i in range(r):\n            N += kernel[::+1][i*samples:(i+1)*samples]\n            N += kernel[::-1][i*samples:(i+1)*samples]\n        for i in range(r):\n            kernel[i*samples:(i+1)*samples:+1] /= N\n        return kernel\n\n    def filter_code(self):\n\n        n = int(math.ceil(self.radius))\n        filter_1 = 'filter1D_radius%d' % n\n        filter_2 = 'filter2D_radius%d' % n\n\n        code = ''\n        code += 'vec4\\n'\n        code += '%s( sampler2D kernel, float index, float x, ' % filter_1\n        for i in range(2*n):\n            if i == 2*n-1:\n                code += 'vec4 c%d )\\n' % i\n            else:\n                code += 'vec4 c%d, ' % i\n        code += '{\\n'\n        code += '    float w, w_sum = 0.0;\\n'\n        code += '    vec4 r = vec4(0.0,0.0,0.0,0.0);\\n'\n        for i in range(n):\n            code += '    w = unpack_interpolate(kernel, vec2(%f+(x/%.1f), index));\\n' % (1.0 - (i + 1) / float(n), n)  # noqa\n            code += '    w = w*kernel_scale + kernel_bias;\\n'  # noqa\n            # code += '   w_sum += w;'\n            code += '    r += c%d * w;\\n' % i\n            code += '    w = unpack_interpolate(kernel, vec2(%f-(x/%.1f), index));\\n' % ((i+1)/float(n), n)  # noqa\n            code += '    w = w*kernel_scale + kernel_bias;\\n'\n            # code += '   w_sum += w;'\n            code += '    r += c%d * w;\\n' % (i + n)\n        # code += '    return r/w_sum;\\n'\n        code += '    return r;\\n'\n        code += '}\\n'\n        code += \"\\n\"\n        code += 'vec4\\n'\n        code += '%s' % filter_2\n        code += '(sampler2D texture, sampler2D kernel, float index, vec2 uv, vec2 pixel)\\n'  # noqa\n        code += '{\\n'\n        code += '    vec2 texel = uv/pixel - vec2(0.5, 0.5) ;\\n'\n        code += '    vec2 f = fract(texel);\\n'\n        code += '    texel = (texel-fract(texel) + vec2(0.001, 0.001)) * pixel;\\n'  # noqa\n        for i in range(2*n):\n            code += '    vec4 t%d = %s(kernel, index, f.x,\\n' % (i, filter_1)\n            for j in range(2*n):\n                x, y = (-n+1+j, -n+1+i)\n                code += '        texture2D( texture, texel + vec2(%d, %d) * pixel),\\n' % (x, y)  # noqa\n\n            # Remove last trailing',' and close function call\n            code = code[:-2] + ');\\n'\n\n        code += '    return %s(kernel, index, f.y, ' % filter_1\n        for i in range(2*n):\n            code += 't%d, ' % i\n\n        # Remove last trailing',' and close function call\n        code = code[:-2] + ');\\n'\n        code += '}\\n'\n\n        return code\n\n    def call_code(self, index):\n        code = \"\"\n        n = int(math.ceil(self.radius))\n        filter_1 = 'filter1D_radius%d' % n  # noqa\n        filter_2 = 'filter2D_radius%d' % n\n\n        code += 'vec4 %s(sampler2D texture, vec2 shape, vec2 uv)\\n' % self.__class__.__name__  # noqa\n        code += '{'\n        code += ' return %s(texture, u_kernel, %f, uv, 1.0/shape); ' % (filter_2, index)  # noqa\n        code += '}\\n'\n        return code\n\n\nclass Nearest(SpatialFilter):\n    '''\n    Nearest (=None) filter (radius = 0.5).\n\n    Weight function::\n\n      w(x) = 1\n\n    '''\n\n    def __init__(self):\n        SpatialFilter.__init__(self, radius=.5)\n\n    def weight(self, x):\n        return 1.0\n\n    def _get_code(self):\n        self.build_LUT()\n        code = 'vec4\\n'\n        code += 'interpolate(sampler2D texture, sampler1D kernel, vec2 uv, vec2 pixel)\\n'  # noqa\n        code += '{\\n   return texture2D(texture, uv);\\n}\\n'\n        return code\n    code = property(_get_code, doc='''filter functions code''')\n\n\nclass Bilinear(SpatialFilter):\n    '''\n    Bilinear filter (radius = 1.0).\n\n    Weight function::\n\n      w(x) = 1 - x\n\n    '''\n\n    def __init__(self):\n        SpatialFilter.__init__(self, radius=1.0)\n\n    def weight(self, x):\n        return 1.0 - x\n\n\nclass Hanning(SpatialFilter):\n    '''\n    Hanning filter (radius = 1.0).\n\n    Weight function::\n\n      w(x) = 0.5 + 0.5 * cos(pi * x)\n\n    '''\n\n    def __init__(self):\n        SpatialFilter.__init__(self, radius=1.0)\n\n    def weight(self, x):\n        return 0.5 + 0.5 * math.cos(math.pi * x)\n\n\nclass Hamming(SpatialFilter):\n    '''\n    Hamming filter (radius = 1.0).\n\n    Weight function::\n\n      w(x) = 0.54 + 0.46 * cos(pi * x)\n\n    '''\n\n    def __init__(self):\n        SpatialFilter.__init__(self, radius=1.0)\n\n    def weight(self, x):\n        return 0.54 + 0.46 * math.cos(math.pi * x)\n\n\nclass Hermite(SpatialFilter):\n    ''' Hermite filter (radius = 1.0).\n\n    Weight function::\n\n      w(x) = (2*x-3)*x^2 + 1\n\n    '''\n\n    def __init__(self):\n        SpatialFilter.__init__(self, radius=1.0)\n\n    def weight(self, x):\n        return (2.0 * x - 3.0) * x * x + 1.0\n\n\nclass Quadric(SpatialFilter):\n    '''\n    Quadric filter (radius = 1.5).\n\n    Weight function::\n\n             |  0.0 ≤ x < 0.5: 0.75 - x*x\n      w(x) = |  0.5 ≤ x < 1.5: 0.5 - (x-1.5)^2\n             |  1.5 ≤ x      : 0\n\n    '''\n\n    def __init__(self):\n        SpatialFilter.__init__(self, radius=1.5)\n\n    def weight(self, x):\n        if x < 0.75:\n            return 0.75 - x * x\n        elif x < 1.5:\n            t = x - 1.5\n            return 0.5 * t * t\n        else:\n            return 0.0\n\n\nclass Bicubic(SpatialFilter):\n    '''\n    Bicubic filter (radius = 2.0).\n\n    Weight function::\n\n      w(x) = 1/6((x+2)^3 - 4*(x+1)^3 + 6*x^3 -4*(x-1)^3)\n    '''\n\n    def __init__(self):\n        SpatialFilter.__init__(self, radius=2.0)\n\n    def pow3(self, x):\n        if x <= 0:\n            return 0\n        else:\n            return x * x * x\n\n    def weight(self, x):\n        return (1.0/6.0) * (self.pow3(x + 2) -\n                            4 * self.pow3(x + 1) +\n                            6 * self.pow3(x) -\n                            4 * self.pow3(x - 1))\n\n\nclass Kaiser(SpatialFilter):\n    '''\n    Kaiser filter (radius = 1.0).\n\n\n    Weight function::\n\n      w(x) = bessel_i0(a sqrt(1-x^2)* 1/bessel_i0(b)\n\n    '''\n\n    def __init__(self, b=6.33):\n        self.a = b\n        self.epsilon = 1e-12\n        self.i0a = 1.0 / self.bessel_i0(b)\n        SpatialFilter.__init__(self, radius=1.0)\n\n    def bessel_i0(self, x):\n        s = 1.0\n        y = x * x / 4.0\n        t = y\n        i = 2\n        while t > self.epsilon:\n            s += t\n            t *= float(y) / (i * i)\n            i += 1\n        return s\n\n    def weight(self, x):\n        if x > 1:\n            return 0\n        return self.bessel_i0(self.a * math.sqrt(1.0 - x * x)) * self.i0a\n\n\nclass CatRom(SpatialFilter):\n    '''\n    Catmull-Rom filter (radius = 2.0).\n\n    Weight function::\n\n             |  0 ≤ x < 1: 0.5*(2 + x^2*(-5+x*3))\n      w(x) = |  1 ≤ x < 2: 0.5*(4 + x*(-8+x*(5-x)))\n             |  2 ≤ x    : 0\n\n    '''\n\n    def __init__(self, size=256*8):\n        SpatialFilter.__init__(self, radius=2.0)\n\n    def weight(self, x):\n        if x < 1.0:\n            return 0.5 * (2.0 + x * x * (-5.0 + x * 3.0))\n        elif x < 2.0:\n            return 0.5 * (4.0 + x * (-8.0 + x * (5.0 - x)))\n        else:\n            return 0.0\n\n\nclass Mitchell(SpatialFilter):\n    '''\n    Mitchell-Netravali filter (radius = 2.0).\n\n    Weight function::\n\n             |  0 ≤ x < 1: p0 + x^2*(p2 + x*p3)\n      w(x) = |  1 ≤ x < 2: q0 + x*(q1 + x*(q2 + x*q3))\n             |  2 ≤ x    : 0\n\n    '''\n\n    def __init__(self, b=1.0/3.0, c=1.0/3.0):\n        self.p0 = (6.0 - 2.0 * b) / 6.0\n        self.p2 = (-18.0 + 12.0 * b + 6.0 * c) / 6.0\n        self.p3 = (12.0 - 9.0 * b - 6.0 * c) / 6.0\n        self.q0 = (8.0 * b + 24.0 * c) / 6.0\n        self.q1 = (-12.0 * b - 48.0 * c) / 6.0\n        self.q2 = (6.0 * b + 30.0 * c) / 6.0\n        self.q3 = (-b - 6.0 * c) / 6.0\n        SpatialFilter.__init__(self, radius=2.0)\n\n    def weight(self, x):\n        if x < 1.0:\n            return self.p0 + x * x * (self.p2 + x * self.p3)\n        elif x < 2.0:\n            return self.q0 + x * (self.q1 + x * (self.q2 + x * self.q3))\n        else:\n            return 0.0\n\n\nclass Spline16(SpatialFilter):\n    '''\n    Spline16 filter (radius = 2.0).\n\n    Weight function::\n\n             |  0 ≤ x < 1: ((x-9/5)*x - 1/5)*x + 1\n      w(x) = |\n             |  1 ≤ x < 2: ((-1/3*(x-1) + 4/5)*(x-1) - 7/15 )*(x-1)\n\n    '''\n\n    def __init__(self):\n        SpatialFilter.__init__(self, radius=2.0)\n\n    def weight(self, x):\n        if x < 1.0:\n            return ((x - 9.0/5.0) * x - 1.0/5.0) * x + 1.0\n        else:\n            return ((-1.0/3.0 * (x-1) + 4.0/5.0) * (x-1) - 7.0/15.0) * (x-1)\n\n\nclass Spline36(SpatialFilter):\n    '''\n    Spline36 filter (radius = 3.0).\n\n    Weight function::\n\n             |  0 ≤ x < 1: ((13/11*x - 453/209)*x -3/209)*x +1\n      w(x) = |  1 ≤ x < 2: ((-6/11*(x-1) - 270/209)*(x-1) -156/209)*(x-1)\n             |  2 ≤ x < 3: (( 1/11*(x-2) - 45/209)*(x-2) + 26/209)*(x-2)\n    '''\n\n    def __init__(self):\n        SpatialFilter.__init__(self, radius=3.0)\n\n    def weight(self, x):\n        if x < 1.0:\n            return ((13.0/11.0 * x - 453.0/209.0) * x - 3.0/209.0) * x + 1.0\n        elif x < 2.0:\n            return ((-6.0/11.0 * (x-1) + 270.0/209.0) * (x-1) - 156.0 / 209.0) * (x-1)  # noqa\n        else:\n            return ((1.0 / 11.0 * (x-2) - 45.0/209.0) * (x - 2) + 26.0/209.0) * (x-2)  # noqa\n\n\nclass Gaussian(SpatialFilter):\n    '''\n    Gaussian filter (radius = 2.0).\n\n    Weight function::\n\n      w(x) = exp(-2x^2) * sqrt(2/pi)\n\n    Note::\n\n      This filter does not seem to be correct since:\n\n        x = np.linspace(0, 1.0, 100 )\n        f = weight\n        z = f(x+1)+f(x)+f(1-x)+f(2-x)\n\n        z should be 1 everywhere but it is not the case and it produces \"grid\n        effects\".\n    '''\n    def __init__(self):\n        SpatialFilter.__init__(self, radius=2.0)\n\n    def weight(self, x):\n        return math.exp(-2.0 * x * x) * math.sqrt(2.0 / math.pi)\n\n\nclass Bessel(SpatialFilter):\n    '''\n    Bessel filter (radius = 3.2383).\n    '''\n\n    def __init__(self):\n        SpatialFilter.__init__(self, radius=3.2383)\n\n    def besj(self, x, n):\n        '''\n        Function BESJ calculates Bessel function of first kind of order n\n        Arguments:\n            x - value at which the Bessel function is required\n            n - an integer (>=0), the order\n        --------------------\n        C++ Mathematical Library\n        Converted from equivalent FORTRAN library\n        Converted by Gareth Walker for use by course 392 computational project\n        All functions tested and yield the same results as the corresponding\n        FORTRAN versions.\n\n        If you have any problems using these functions please report them to\n        M.Muldoon@UMIST.ac.uk\n\n        Documentation available on the web\n        http://www.ma.umist.ac.uk/mrm/Teaching/392/libs/392.html\n        Version 1.0   8/98\n        29 October, 1999\n        --------------------\n        Adapted for use in AGG library by\n                    Andy Wilk (castor.vulgaris@gmail.com)\n        Adapted for use in vispy library by\n                    Nicolas P. Rougier (Nicolas.Rougier@inria.fr)\n        -----------------------------------------------------------------------\n        '''\n        if n < 0:\n            return 0.0\n        x = float(x)  # force float type\n\n        d = 1e-6\n        b = 0\n        if math.fabs(x) <= d:\n            if n != 0:\n                return 0\n            return 1\n\n        b1 = 0  # b1 is the value from the previous iteration\n        # Set up a starting order for recurrence\n        m1 = int(math.fabs(x)) + 6\n        if math.fabs(x) > 5:\n            m1 = int(math.fabs(1.4 * x + 60 / x))\n\n        m2 = int(n + 2 + math.fabs(x) / 4)\n        if m1 > m2:\n            m2 = m1\n\n        # Apply recurrence down from current max order\n        while True:\n            c3 = 0\n            c2 = 1e-30\n            c4 = 0\n            m8 = 1\n            if m2 // 2 * 2 == m2:\n                m8 = -1\n\n            imax = m2 - 2\n            for i in range(1, imax+1):\n                c6 = 2 * (m2 - i) * c2 / x - c3\n                c3 = c2\n                c2 = c6\n                if m2 - i - 1 == n:\n                    b = c6\n                m8 = -1 * m8\n                if m8 > 0:\n                    c4 = c4 + 2 * c6\n\n            c6 = 2 * c2 / x - c3\n            if n == 0:\n                b = c6\n            c4 += c6\n            b /= c4\n            if math.fabs(b - b1) < d:\n                return b\n            b1 = b\n            m2 += 3\n\n    def weight(self, x):\n        if x == 0.0:\n            return math.pi/4.0\n        else:\n            return self.besj(math.pi * x, 1) / (2.0 * x)\n\n\nclass Sinc(SpatialFilter):\n    '''\n    Sinc filter (radius = 4.0).\n\n    Weight function::\n\n\n    '''\n\n    def __init__(self, size=256, radius=4.0):\n        SpatialFilter.__init__(self, radius=max(radius, 2.0))\n\n    def weight(self, x):\n        if x == 0.0:\n            return 1.0\n        x *= math.pi\n        return (math.sin(x) / x)\n\n\nclass Lanczos(SpatialFilter):\n    '''\n    Lanczos filter (radius = 4.0).\n\n    Weight function::\n\n\n    '''\n\n    def __init__(self, size=256, radius=4.0):\n        SpatialFilter.__init__(self, radius=max(radius, 2.0))\n\n    def weight(self, x):\n        if x == 0.0:\n            return 1.0\n        elif x > self.radius:\n            return 0.0\n        x *= math.pi\n        xr = x / self.radius\n        return (math.sin(x) / x) * (math.sin(xr)/xr)\n\n\nclass Blackman(SpatialFilter):\n    '''\n    Blackman filter (radius = 4.0).\n    '''\n\n    def __init__(self, size=256, radius=4.0):\n        SpatialFilter.__init__(self, radius=max(radius, 2.0))\n\n    def weight(self, x):\n        if x == 0.0:\n            return 1.0\n        elif x > self.radius:\n            return 0.0\n        x *= math.pi\n        xr = x / self.radius\n        return (math.sin(x) / x) * (0.42 + 0.5*math.cos(xr) + 0.08*math.cos(2*xr))  # noqa\n\n\n# Generate kernels texture (16 x 1024)\nfilters = [Bilinear(), Hanning(),  Hamming(),  Hermite(),\n           Kaiser(),   Quadric(),  Bicubic(),  CatRom(),\n           Mitchell(), Spline16(), Spline36(), Gaussian(),\n           Bessel(),   Sinc(),     Lanczos(),  Blackman()]\n\nn = 1024\nK = np.zeros((16, n))\nfor i, f in enumerate(filters):\n    K[i] = f.kernel(n)\n\nbias = K.min()\nscale = K.max()-K.min()\nK = (K-bias)/scale\nnp.save(\"spatial-filters.npy\", K.astype(np.float32))\n\nprint(\"// ------------------------------------\")\nprint(\"// Automatically generated, do not edit\")\nprint(\"// ------------------------------------\")\nprint(\"\")\nprint(\"const float kernel_bias  = %f;\" % bias)\nprint(\"const float kernel_scale = %f;\" % scale)\nprint(\"const float kernel_size = %f;\" % n)\nprint(\"const vec4 bits = vec4(1.0, 1.0/256.0, 1.0/(256.0*256.0), 1.0/(256.0*256.0*256.0));\")  # noqa\nprint(\"uniform sampler2D u_kernel;\")\nprint(\"\")\n\ncode = 'float\\n'\ncode += 'unpack_unit(vec4 rgba)\\n'\ncode += '{\\n'\ncode += '\\t// return rgba.r;  // uncomment this for r32f debugging\\n'\ncode += '\\treturn dot(rgba, bits);\\n'\ncode += '}\\n'\nprint(code.expandtabs(4))\n\ncode = 'float\\n'\ncode += 'unpack_ieee(vec4 rgba)\\n'\ncode += '{\\n'\ncode += '\\t// return rgba.r;  // uncomment this for r32f debugging\\n'\ncode += '\\trgba.rgba = rgba.abgr * 255.;\\n'\ncode += '\\tfloat sign = 1.0 - step(128.0,rgba[0])*2.0;\\n'\ncode += '\\tfloat exponent = 2.0 * mod(rgba[0],128.0) + ' \\\n        'step(128.0,rgba[1]) - 127.0;\\n'\ncode += '\\tfloat mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 + ' \\\n        'rgba[3] + float(0x800000);\\n'\ncode += '\\treturn sign * exp2(exponent) * (mantissa * exp2(-23.));\\n'\ncode += '}\\n'\nprint(code.expandtabs(4))\n\ncode = 'float\\n'\ncode += 'unpack_interpolate(sampler2D kernel, vec2 uv)\\n'\ncode += '{\\n'\ncode += '\\t// return texture2D(kernel, uv).r; ' \\\n        '//uncomment this for r32f debug without interpolation\\n'\ncode += '\\tfloat kpixel = 1. / kernel_size;\\n'\ncode += '\\tfloat u = uv.x / kpixel;\\n'\ncode += '\\tfloat v = uv.y;\\n'\ncode += '\\tfloat uf = fract(u);\\n'\ncode += '\\tu = (u - uf) * kpixel;\\n'\ncode += '\\n'\ncode += '\\tfloat d0 = unpack_unit(texture2D(kernel, vec2(u, v)));\\n'\ncode += '\\tfloat d1 = unpack_unit(texture2D(kernel, vec2(u + 1. * kpixel, v)));\\n'  # noqa\ncode += '\\treturn mix(d0, d1, uf);\\n'\ncode += '}\\n'\nprint(code.expandtabs(4))\n\nF = SpatialFilter(1.0)\nprint(F.filter_code())\nF = SpatialFilter(2.0)\nprint(F.filter_code())\nF = SpatialFilter(3.0)\nprint(F.filter_code())\nF = SpatialFilter(4.0)\nprint(F.filter_code())\n\n# Generate filter functions\n# Special case for nearest\nprint(\"\"\"vec4 Nearest(sampler2D texture, vec2 shape, vec2 uv)\"\"\")\nprint(\"\"\"{ return texture2D(texture,uv); }\\n\"\"\")\n\nfor i, f in enumerate(filters):\n    print(f.call_code((i+0.5)/16.0))\n", "meta": {"hexsha": "ab0637ef172f519823e87461d7b9e5f784d4bd5c", "size": 20504, "ext": "py", "lang": "Python", "max_stars_repo_path": "vispy/glsl/build-spatial-filters.py", "max_stars_repo_name": "mkkb/vispy", "max_stars_repo_head_hexsha": "8540f8d96fe3af84ba80bde6d6bf55484eaa8e3a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-23T18:32:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-23T18:32:06.000Z", "max_issues_repo_path": "vispy/glsl/build-spatial-filters.py", "max_issues_repo_name": "mkkb/vispy", "max_issues_repo_head_hexsha": "8540f8d96fe3af84ba80bde6d6bf55484eaa8e3a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vispy/glsl/build-spatial-filters.py", "max_forks_repo_name": "mkkb/vispy", "max_forks_repo_head_hexsha": "8540f8d96fe3af84ba80bde6d6bf55484eaa8e3a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-03-18T19:35:17.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-18T19:35:17.000Z", "avg_line_length": 28.5173852573, "max_line_length": 125, "alphanum_fraction": 0.520630121, "include": true, "reason": "import numpy", "num_tokens": 6489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.19600010984235716}}
{"text": "import torch\nimport numpy as np\n# 19-4-12  pytorch\n\n# input: coeff with shape [1,257]\ndef Split_coeff(coeff):\n    id_coeff = coeff[:,:80] # identity(shape) coeff of dim 80\n    ex_coeff = coeff[:,80:144] # expression coeff of dim 64\n    tex_coeff = coeff[:,144:224] # texture(albedo) coeff of dim 80\n    angles = coeff[:,224:227] # ruler angles(x,y,z) for rotation of dim 3\n    gamma = coeff[:,227:254] # lighting coeff for 3 channel SH function of dim 27\n    translation = coeff[:,254:] # translation coeff of dim 3\n\n    return id_coeff,ex_coeff,tex_coeff,angles,gamma,translation\n\n# CHJ_ADD\nclass _need_const:\n    import numpy as np\n    a0 = np.pi\n    a1 = 2 * np.pi / np.sqrt(3.0)\n    a2 = 2 * np.pi / np.sqrt(8.0)\n    c0 = 1 / np.sqrt(4 * np.pi)\n    c1 = np.sqrt(3.0) / np.sqrt(4 * np.pi)\n    c2 = 3 * np.sqrt(5.0) / np.sqrt(12 * np.pi)\n    d0 = 0.5/ np.sqrt(3.0)\n\n    illu_consts=[a0, a1, a2, c0, c1, c2, d0]\n\n    focal = 1015.0\n    center = 112.0\n    cam_pos = 10\n    p_matrix = np.concatenate([[focal], [0.0], [center], [0.0], [focal], [center], [0.0], [0.0], [1.0]],\n                              axis=0).astype(np.float32)  # projection matrix\n    p_matrix = np.reshape(p_matrix, [1, 3, 3])\n    p_matrix = torch.from_numpy(p_matrix)\n    gpu_p_matrix = None\n\n\n# compute face shape with identity and expression coeff, based on BFM model\n# input: id_coeff with shape [1,80]\n#         ex_coeff with shape [1,64]\n# output: face_shape with shape [1,N,3], N is number of vertices\ndef Shape_formation(id_coeff,ex_coeff,facemodel):\n    n_b = id_coeff.size(0)\n    face_shape = torch.einsum('ij,aj->ai',facemodel.idBase,id_coeff) + \\\n                torch.einsum('ij,aj->ai',facemodel.exBase,ex_coeff) + \\\n                facemodel.meanshape\n\n    face_shape = face_shape.view(n_b,-1,3)\n    # re-center face shape\n    face_shape = face_shape - facemodel.meanshape.view(1, -1, 3).mean(dim=1, keepdim=True)\n\n    return face_shape\n\n# compute vertex texture(albedo) with tex_coeff\n# input: tex_coeff with shape [1,N,3]\n# output: face_texture with shape [1,N,3], RGB order, range from 0-255\ndef Texture_formation(tex_coeff,facemodel):\n    n_b = tex_coeff.size(0)\n    face_texture = torch.einsum('ij,aj->ai',facemodel.texBase,tex_coeff) + facemodel.meantex\n\n    face_texture = face_texture.view(n_b,-1,3)\n    return face_texture\n\n# compute vertex normal using one-ring neighborhood\n# input: face_shape with shape [1,N,3]\n# output: v_norm with shape [1,N,3]\ndef Compute_norm(face_shape,facemodel):\n\n    face_id = facemodel.tri # vertex index for each triangle face, with shape [F,3], F is number of faces\n    point_id = facemodel.point_buf # adjacent face index for each vertex, with shape [N,8], N is number of vertex\n    shape = face_shape\n    \n    v1 = shape[:,face_id[:,0],:]\n    v2 = shape[:,face_id[:,1],:]\n    v3 = shape[:,face_id[:,2],:]\n    e1 = v1 - v2\n    e2 = v2 - v3\n    face_norm = e1.cross(e2) # compute normal for each face\n    empty = torch.zeros((face_norm.size(0), 1, 3), dtype=face_norm.dtype, device=face_norm.device)\n\n    face_norm = torch.cat((face_norm, empty), 1) # concat face_normal with a zero vector at the end\n\n    v_norm = face_norm[:,point_id,:].sum(2) # compute vertex normal using one-ring neighborhood \n    # CHJ: not average, directly normalize\n    v_norm = v_norm/v_norm.norm(dim=2).unsqueeze(2) # normalize normal vectors\n\n    return v_norm\n\n\n# compute rotation matrix based on 3 ruler angles\n# input: angles with shape [1,3]\n# output: rotation matrix with shape [1,3,3]\ndef Compute_rotation_matrix(angles):\n\n    n_b = angles.size(0)\n    sinx = torch.sin(angles[:, 0])\n    siny = torch.sin(angles[:, 1])\n    sinz = torch.sin(angles[:, 2])\n    cosx = torch.cos(angles[:, 0])\n    cosy = torch.cos(angles[:, 1])\n    cosz = torch.cos(angles[:, 2])\n\n    rotXYZ = torch.eye(3).view(1, 3, 3).repeat(n_b * 3, 1, 1).view(3, n_b, 3, 3)\n\n    if angles.is_cuda: rotXYZ = rotXYZ.cuda(angles.get_device())\n\n    rotXYZ[0, :, 1, 1] = cosx\n    rotXYZ[0, :, 1, 2] = -sinx\n    rotXYZ[0, :, 2, 1] = sinx\n    rotXYZ[0, :, 2, 2] = cosx\n    rotXYZ[1, :, 0, 0] = cosy\n    rotXYZ[1, :, 0, 2] = siny\n    rotXYZ[1, :, 2, 0] = -siny\n    rotXYZ[1, :, 2, 2] = cosy\n    rotXYZ[2, :, 0, 0] = cosz\n    rotXYZ[2, :, 0, 1] = -sinz\n    rotXYZ[2, :, 1, 0] = sinz\n    rotXYZ[2, :, 1, 1] = cosz\n\n    rotation = rotXYZ[2].bmm(rotXYZ[1]).bmm(rotXYZ[0])\n\n    return rotation.permute(0, 2, 1)\n\n# project 3D face onto image plane\n# input: face_shape with shape [1,N,3]\n#          rotation with shape [1,3,3]\n#         translation with shape [1,3]\n# output: face_projection with shape [1,N,2]\n#           z_buffer with shape [1,N,1]\ndef Projection_layer(face_shape,rotation,translation,focal=1015.0,center=112.0): # we choose the focal length and camera position empirically\n\n    n_b, nV, _ = face_shape.size()\n    if face_shape.is_cuda:\n        if _need_const.gpu_p_matrix is None:\n            _need_const.gpu_p_matrix = _need_const.p_matrix.cuda(face_shape.get_device())\n\n        p_matrix = _need_const.gpu_p_matrix.expand(n_b, 3, 3)\n    else:\n        p_matrix = _need_const.p_matrix.expand(n_b, 3, 3)\n\n    face_shape_r = face_shape.bmm(rotation)  # CHJ: R has been transposed\n    face_shape_t = face_shape_r + translation.view(n_b, 1, 3)\n\n    face_shape_t[:, :, 2] = _need_const.cam_pos - face_shape_t[:, :, 2]\n\n    aug_projection = face_shape_t.bmm(p_matrix.permute(0, 2, 1))\n\n    #print(aug_projection)\n    #exit()\n\n    face_projection = aug_projection[:, :, 0:2] / aug_projection[:, :, 2:]\n    \n    # CHJ_WARN: I do this for visualization\n    z_buffer = _need_const.cam_pos - aug_projection[:, :, 2:] # CHJ: same as the z of  face_shape_t\n\n    return face_projection, z_buffer\n\n# CHJ: It's different from what I knew.\n# compute vertex color using face_texture and SH function lighting approximation\n# input: face_texture with shape [1,N,3]\n#          norm with shape [1,N,3]\n#         gamma with shape [1,27]\n# output: face_color with shape [1,N,3], RGB order, range from 0-255\n#          lighting with shape [1,N,3], color under uniform texture\n\ndef Illumination_layer(face_texture, norm, gamma):\n\n    n_b, num_vertex, _ = face_texture.size()\n    n_v_full = n_b * num_vertex\n    gamma = gamma.view(-1, 3, 9).clone() \n    gamma[:, :, 0] += 0.8\n\n    gamma = gamma.permute(0, 2, 1)\n\n    a0, a1, a2, c0, c1, c2, d0 = _need_const.illu_consts\n\n    Y0 = torch.ones(n_v_full).float() * a0*c0\n    if gamma.is_cuda: Y0=Y0.cuda(gamma.get_device())\n    norm = norm.view(-1, 3)\n    nx, ny, nz = norm[:,0], norm[:,1], norm[:,2]\n    arrH = []\n\n    arrH.append( Y0 )\n    arrH.append(-a1*c1*ny)\n    arrH.append(a1*c1*nz)\n    arrH.append(-a1*c1*nx)\n    arrH.append(a2*c2*nx*ny)\n    arrH.append(-a2*c2*ny*nz)\n    arrH.append(a2*c2*d0*(3*nz.pow(2)-1))\n    arrH.append(-a2*c2*nx*nz)\n    arrH.append(a2*c2*0.5*(nx.pow(2)-ny.pow(2)))\n\n    H = torch.stack(arrH, 1)\n    Y = H.view(n_b, num_vertex, 9)\n\n    # Y shape:[batch,N,9].\n\n    # shape:[batch,N,3]\n    lighting = Y.bmm(gamma)\n\n    face_color = face_texture * lighting\n    #lighting *= 128\n\n    #print( face_color[0, 5] )\n    return face_color,lighting\n\n# face reconstruction with coeff and BFM model\ndef Reconstruction(coeff,facemodel):\n    id_coeff,ex_coeff,tex_coeff,angles,gamma,translation = Split_coeff(coeff)\n\n    # compute face shape\n    face_shape = Shape_formation(id_coeff, ex_coeff, facemodel)\n    # compute vertex texture(albedo)\n    face_texture = Texture_formation(tex_coeff, facemodel)\n    #print(face_texture[0, 2])\n    # vertex normal\n    face_norm = Compute_norm(face_shape,facemodel)\n    # rotation matrix\n    rotation = Compute_rotation_matrix(angles)\n    face_norm_r = face_norm.bmm(rotation)\n\n    # compute vertex projection on image plane (with image sized 224*224)\n    face_projection,z_buffer = Projection_layer(face_shape,rotation,translation)\n    \n    # compute vertex color using SH function lighting approximation\n    face_color,lighting = Illumination_layer(face_texture, face_norm_r, gamma)\n\n    # vertex index for each face of BFM model\n    tri = facemodel.tri\n\n\n    face_shape = torch.matmul(face_shape,rotation)\n    face_shape = face_shape + torch.reshape(translation,[-1,1,3])\n\n    return face_shape, angles,face_color,tri,face_projection,z_buffer,gamma\n\n\n\ndef Reconstruction_for_render(coeff,facemodel):\n    id_coeff,ex_coeff,tex_coeff,angles,gamma,translation = Split_coeff(coeff)\n    face_shape = Shape_formation(id_coeff, ex_coeff, facemodel)\n    face_texture = Texture_formation(tex_coeff, facemodel)\n    face_norm = Compute_norm(face_shape,facemodel)\n    rotation = Compute_rotation_matrix(angles)\n    face_shape_r = torch.matmul(face_shape,rotation)\n    face_shape_r = face_shape_r + torch.reshape(translation,[-1,1,3])\n    face_norm_r = torch.matmul(face_norm,rotation)\n    face_color,lighting = Illumination_layer(face_texture, face_norm_r, gamma)\n    tri = facemodel.tri\n\n    return face_shape_r,face_norm_r,face_color,tri", "meta": {"hexsha": "8cf8da4aa4d12bce6f87d0dd4bef799d76fffb57", "size": 8887, "ext": "py", "lang": "Python", "max_stars_repo_path": "mmRegressor/reconstruct_mesh.py", "max_stars_repo_name": "yeongjoonJu/Occlusion-Robust-3D-Face-CFR-GAN", "max_stars_repo_head_hexsha": "1966faf9bfe8d8afd6bc2cea88e5400ce3be54d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2021-11-01T08:09:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T06:45:14.000Z", "max_issues_repo_path": "mmRegressor/reconstruct_mesh.py", "max_issues_repo_name": "yeongjoonJu/Occlusion-Robust-3D-Face-CFR-GAN", "max_issues_repo_head_hexsha": "1966faf9bfe8d8afd6bc2cea88e5400ce3be54d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-10T11:08:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T11:23:13.000Z", "max_forks_repo_path": "mmRegressor/reconstruct_mesh.py", "max_forks_repo_name": "yeongjoonJu/Occlusion-Robust-3D-Face-CFR-GAN", "max_forks_repo_head_hexsha": "1966faf9bfe8d8afd6bc2cea88e5400ce3be54d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-11-03T07:11:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T06:45:16.000Z", "avg_line_length": 35.2658730159, "max_line_length": 141, "alphanum_fraction": 0.6642286486, "include": true, "reason": "import numpy", "num_tokens": 2773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.348645142101806, "lm_q1q2_score": 0.1960001060376252}}
{"text": "# -*implants -*-\n\"\"\"\n\nFunctions for creating retinal implants\n\n\"\"\"\nimport numpy as np\nimport logging\n\nfrom pulse2percept import utils\n\n\nSUPPORTED_IMPLANT_TYPES = ['epiretinal', 'subretinal']\n\n\nclass Electrode(object):\n\n    def __init__(self, etype, radius, x_center, y_center, height=0, name=None):\n        \"\"\"Create an electrode on the retina\n\n        This function creates a disk electrode of type `etype` and places it\n        on the retina at location (`xs`, `ys`) in microns. The electrode has\n        radius `radius` (microns) and sits a distance `height` away from the\n        retinal surface.\n        The coordinate system is anchored around the fovea at (0, 0).\n\n        Parameters\n        ----------\n        etype : str\n            Electrode type, {'epiretinal', 'subretinal'}\n        radius : float\n            The radius of the electrode (in microns).\n        x_center : float\n            The x coordinate of the electrode center (in microns) from the\n            fovea.\n        y_center : float\n            The y location of the electrode (in microns) from the fovea\n        height : float\n            The height of the electrode from the retinal surface:\n\n            - epiretinal array: distance to the ganglion layer\n            - subretinal array: distance to the bipolar layer\n        name : string\n            Electrode name\n\n        \"\"\"\n        assert radius >= 0\n        assert height >= 0\n\n        if etype.lower() not in SUPPORTED_IMPLANT_TYPES:\n            e_s = \"Acceptable values for `etype` are: \"\n            e_s += \", \".join(SUPPORTED_IMPLANT_TYPES) + \".\"\n            raise ValueError(e_s)\n\n        self.etype = etype.lower()\n        self.radius = radius\n        self.x_center = x_center\n        self.y_center = y_center\n        self.name = name\n        self.height = height\n\n    def __str__(self):\n        info_s = \"Electrode(%s, r=%.2f um, \" % (self.etype, self.radius)\n        info_s += \"(x,y) = (%.2f, %.2f) um, \" % (self.x_center, self.y_center)\n        info_s += \"h=%.2f um, n=%s\" % (self.height, self.name)\n        return info_s\n\n    def get_height(self):\n        \"\"\"Returns the electrode-retina distance\n\n        For epiretinal electrodes, this returns the distance to the ganglion\n        cell layer.\n        For subretinal electrodes, this returns the distance to the bipolar\n        layer.\n        \"\"\"\n        if self.etype == 'epiretinal':\n            return self.h_ofl\n        elif self.etype == 'subretinal':\n            return self.h_inl\n        else:\n            raise ValueError(\"Unknown `etype`: \" + self.etype)\n\n    def set_height(self, height):\n        \"\"\"Sets the electrode-to-retina distance\n\n        This function sets the electrode-to-retina distance according to\n        `height`. For an epiretinal device, we calculate the distance to\n        the ganglion cell layer (layer thickness depends on retinal location).\n        For a subretinal device, we calculate the distance to the bipolar\n        layer (layer thickness again depends on retinal location).\n\n        Estimates of layer thickness based on:\n        LoDuca et al. Am J. Ophthalmology 2011\n        Thickness Mapping of Retinal Layers by Spectral Domain Optical\n        Coherence Tomography\n        Note that this is for normal retinal, so may overestimate thickness.\n        Thickness from their paper (averaged across quadrants):\n            0-600 um radius (from fovea):\n\n            - Layer 1. (Nerve fiber layer) = 4\n            - Layer 2. (Ganglion cell bodies + inner plexiform) = 56\n            - Layer 3. (Bipolar bodies, inner nuclear layer) = 23\n\n          600-1550 um radius:\n\n            - Layer 1. 34\n            - Layer 2. 87\n            - Layer 3. 37.5\n\n          1550-3000 um radius:\n            - Layer 1. 45.5\n            - Layer 2. 58.2\n            - Layer 3. 30.75\n\n        We place our ganglion axon surface on the inner side of the nerve fiber\n        layer.\n        We place our bipolar surface 1/2 way through the inner nuclear layer.\n        So for an epiretinal array the bipolar layer is L1 + L2 + 0.5 * L3.\n\n        \"\"\"\n        fovdist = np.sqrt(self.x_center ** 2 + self.y_center ** 2)\n        if fovdist <= 600:\n            # Layer thicknesses given for 0-600 um distance (from fovea)\n            th_ofl = 4.0  # nerve fiber layer\n            th_gc = 56.0  # ganglion cell bodies + inner nuclear layer\n            th_bp = 23.0  # bipolar bodies + inner nuclear layer\n        elif fovdist <= 1550:\n            # Layer thicknesses given for 600-1550 um distance (from fovea)\n            th_ofl = 34.0\n            th_gc = 87.0\n            th_bp = 37.5\n        else:\n            # Layer thicknesses given for 1550-3000 um distance (from fovea)\n            th_ofl = 45.5\n            th_gc = 58.2\n            th_bp = 30.75\n            if fovdist > 3000:\n                e_s = \"Distance to fovea=%.0f > 3000 um, \" % fovdist\n                e_s += \"assuming same layer thicknesses as for 1550-3000 um \"\n                e_s += \"distance.\"\n                logging.getLogger(__name__).warning(e_s)\n\n        if self.etype == 'epiretinal':\n            # This is simply the electrode-retina distance\n            self.h_ofl = height\n\n            # All the way through the ganglion cell layer, inner plexiform\n            # layer, and halfway through the inner nuclear layer\n            self.h_inl = height + th_ofl + th_gc + 0.5 * th_bp\n        elif self.etype == 'subretinal':\n            # Starting from the outer plexiform layer, go halfway through the\n            # inner nuclear layer\n            self.h_inl = height + 0.5 * th_bp\n\n            # Starting from the outer plexiform layer, all the way through the\n            # inner nuclear layer, inner plexiform layer, and ganglion cell\n            # layer\n            self.h_ofl = height + th_bp + th_gc + th_ofl\n        else:\n            raise ValueError(\"Unknown `etype`: \" + self.etype)\n    height = property(get_height, set_height)\n\n    def current_spread(self, xg, yg, layer, alpha=14000, n=1.69):\n        \"\"\"\n\n        The current spread due to a current pulse through an electrode,\n        reflecting the fall-off of the current as a function of distance from\n        the electrode center. This can be calculated for any layer in the\n        retina.\n        Based on equation 2 in Nanduri et al [1].\n\n        Parameters\n        ----------\n        xg : array\n            x-coordinates of the retinal grid\n        yg : array\n            y-coordinates of the retinal grid\n        layer: str\n            Layer for which to calculate the current spread:\n\n            - 'OFL': optic fiber layer, ganglion axons\n            - 'INL': inner nuclear layer, containing the bipolars\n        alpha : float\n            A constant to do with the spatial fall-off.\n\n        n : float\n            A constant to do with the spatial fall-off (Default: 1.69, based\n            on Ahuja et al. [2]  An In Vitro Model of a Retinal Prosthesis.\n            Ashish K. Ahuja, Matthew R. Behrend, Masako Kuroda, Mark S.\n            Humayun, and James D. Weiland (2008). IEEE Trans Biomed Eng 55.\n\n        \"\"\"\n        r = np.sqrt((xg - self.x_center) ** 2 + (yg - self.y_center) ** 2)\n        # current values on the retina due to array being above the retinal\n        # surface\n        if 'OFL' in layer:  # optic fiber layer, ganglion axons\n            h = np.ones(r.shape) * self.h_ofl\n            # actual distance from the electrode edge\n            d = ((r - self.radius)**2 + self.h_ofl**2)**.5\n        elif 'INL' in layer:  # inner nuclear layer, containing the bipolars\n            h = np.ones(r.shape) * self.h_inl\n            d = ((r - self.radius)**2 + self.h_inl**2)**.5\n        else:\n            s = \"Layer %s not found. Acceptable values for `layer` are \" \\\n                \"'OFL' or 'INL'.\" % layer\n            raise ValueError(s)\n        cspread = (alpha / (alpha + h ** n))\n        cspread[r > self.radius] = (alpha\n                                   / (alpha + d[r > self.radius] ** n))\n\n        return cspread\n\n    def receptive_field(self, xg, yg, rftype='square', size=None):\n        \"\"\"An electrode's receptive field\n\n        Parameters\n        ----------\n        xg : array_like\n            Array of all x coordinates\n        yg : array_like\n            Array of all y coordinates\n        rftype : {'square', 'gaussian'}\n            The type of receptive field.\n            - 'square': A simple square box receptive field with side length\n                        `size`.\n            - 'gaussian': A Gaussian receptive field where the weight drops off\n                          as a function of distance from the electrode center.\n                          The standard deviation of the Gaussian is `size`.\n        size : float, optional\n            Parameter describing the size of the receptive field. For square\n            receptive fields, this corresponds to the side length of the\n            square.\n            For Gaussian receptive fields, this corresponds to the standard\n            deviation of the Gaussian.\n            Default: Twice the electrode radius.\n        \"\"\"\n        if size is None:\n            size = 2 * self.radius\n\n        if rftype == 'square':\n            # Create a map of the retina for each electrode\n            # where it's 1 under the electrode, 0 elsewhere\n            rf = np.zeros(xg.shape).astype(np.float32)\n            ind = np.where((xg > self.x_center - (size / 2.0))\n                           & (xg < self.x_center + (size / 2.0))\n                           & (yg > self.y_center - (size / 2.0))\n                           & (yg < self.y_center + (size / 2.0)))\n            rf[ind] = 1.0\n        elif rftype == 'gaussian':\n            # Create a map of the retina where the weight drops of as a\n            # function of distance from the electrode center\n            dist = (xg - self.x_center) ** 2 + (yg - self.y_center) ** 2\n            rf = np.exp(-dist / (2 * size ** 2))\n            rf /= np.sum(rf)\n        else:\n            e_s = \"Acceptable values for `rftype` are 'square' or 'gaussian'\"\n            raise ValueError(e_s)\n\n        return rf\n\n\nclass ElectrodeArray(object):\n\n    def __init__(self, etype, radii, xs, ys, hs=0, names=None, eye='RE'):\n        \"\"\"Create an ElectrodeArray on the retina\n        This function creates an electrode array of type `etype` and places it\n        on the retina. Lists should specify, for each electrode, its size\n        (`radii`), location on the retina (`xs` and `ys`), distance to the\n        retina (height, `hs`), and a string identifier (`names`, optional).\n        Array location should be given in microns, where the fovea is located\n        at (0, 0).\n        Single electrodes in the array can be addressed by index (integer)\n        or name.\n        Parameters\n        ----------\n        radii : array_like\n            List of electrode radii.\n        xs : array_like\n            List of x-coordinates for the center of the electrodes (microns).\n        ys : array_like\n            List of y-coordinates for the center of the electrodes (microns).\n        hs : float | array_like, optional, default: 0\n            List of electrode heights (distance from the retinal surface).\n        names : array_like, optional, default: None\n            List of names (string identifiers) for each eletrode.\n        eye : {'LE', 'RE'}, optional, default: 'RE'\n            Eye in which array is implanted.\n\n        Examples\n        --------\n        A single epiretinal electrode called 'A1', with radius 100um, sitting\n        at retinal location (0, 0), 10um away from the retina:\n        >>> from pulse2percept import implants\n        >>> implant0 = implants.ElectrodeArray('epiretinal', 100, 0, 0, hs=10,\n        ...                                    names='A1')\n\n        Get access to the electrode with name 'A1' in the first array:\n        >>> my_electrode = implant0['A1']\n\n        An array with two electrodes of size 100um, one sitting at\n        (-100, -100), the other sitting at (0, 0), with 0 distance from the\n        retina, of type 'subretinal':\n        >>> implant1 = implants.ElectrodeArray('subretinal', [100, 100],\n        ...                                    [-100, 0], [-100, 0], hs=[0, 0])\n        \"\"\"\n        self.etype = etype\n        self.eye = eye\n        self.electrodes = []\n        self.num_electrodes = 0\n        self.add_electrodes(radii, xs, ys, hs, names)\n\n    def __str__(self):\n        return \"ElectrodeArray(%s, num_electrodes=%d)\" % (self.etype,\n                                                          self.num_electrodes)\n\n    def add_electrode(self, electrode):\n        \"\"\"Adds an electrode to an ElectrodeArray object\n        This function adds a single electrode to an existing ElectrodeArray\n        object. The electrode must have the same type as the array\n        (see implants.SUPPORTED_IMPLANT_TYPES).\n        Parameters\n        ----------\n        electrode : implants.Electrode\n            An electrode object specifying type, size, and location of the\n            electrode on the retina.\n        \"\"\"\n        if not isinstance(electrode, Electrode):\n            raise TypeError(\"`electrode` must be of type retina.Electrode.\")\n\n        if electrode.etype != self.etype:\n            e_s = \"Added electrode must be of same type as the existing\"\n            e_s = \"array (%s).\" % self.etype\n            raise ValueError(e_s)\n\n        self.num_electrodes += 1\n        self.electrodes.append(electrode)\n\n    def add_electrodes(self, radii, xs, ys, hs=0, names=None):\n        \"\"\"Adds electrodes to an ElectrodeArray object\n        This function adds one or more electrodes to an existing ElectrodeArray\n        object. Lists should specify, for each electrode to be added, the size\n        (`radii`), location on the retina (`xs` and `ys`), distance to the\n        retina (height, `hs`), and a string identifier (`names`, optional).\n        Array location should be given in microns, where the fovea is located\n        at (0, 0).\n        Single electrodes in the array can be addressed by index (integer)\n        or name.\n\n        Parameters\n        ----------\n        radii : array_like\n            List of electrode radii.\n        xs : array_like\n            List of x-coordinates for the center of the electrodes (microns).\n        ys : array_like\n            List of y-coordinates for the center of the electrodes (microns).\n        hs : float | array_like, optional, default: 0\n            List of electrode heights (distance from the retinal surface).\n        names : array_like, optional, default: None\n            List of names (string identifiers) for each eletrode.\n\n        Examples\n        --------\n        Adding a single electrode of radius 50um sitting at (0, 0) to an\n        existing ElectrodeArray object:\n        >>> implant = ElectrodeArray('epiretinal', 100, 100, 100)\n        >>> implant.add_electrodes(50, 0, 0)\n        \"\"\"\n        # Make it so the method can accept either floats, lists, or\n        # numpy arrays, and `zip` works regardless.\n        radii = np.array([radii], dtype=np.float32).flatten()\n        xs = np.array([xs], dtype=np.float32).flatten()\n        ys = np.array([ys], dtype=np.float32).flatten()\n        names = np.array([names], dtype=np.str).flatten()\n\n        if isinstance(hs, list):\n            hs = np.array(hs).flatten()\n        else:\n            # All electrodes have the same height\n            hs = np.ones_like(radii) * hs\n\n        assert radii.size == xs.size == ys.size == hs.size\n\n        if names.size != radii.size:\n            # If not every electrode has a name, replace with None's\n            names = np.array([None] * radii.size)\n\n        for r, x, y, h, n in zip(radii, xs, ys, hs, names):\n            self.add_electrode(Electrode(self.etype, r, x, y, h, n))\n\n    def __iter__(self):\n        return iter(self.electrodes)\n\n    def __getitem__(self, item):\n        \"\"\"Return the electrode specified by `item`\n        Parameters\n        ----------\n        item : int|string\n            If `item` is an integer, returns the `item`-th electrode in the\n            array. If `item` is a string, returns the electrode with string\n            identifier `item`.\n        \"\"\"\n        try:\n            # Is `item` an integer?\n            return self.electrodes[item]\n        except (IndexError, TypeError):\n            # If `item` is a valid string identifier, return valid index.\n            # Else return None\n            try:\n                return self.electrodes[self.get_index(item)]\n            except (IndexError, TypeError):\n                return None\n\n    def get_index(self, name):\n        \"\"\"Returns the index of an electrode called `name`\n        This function searches the electrode array for an electrode with\n        string identifier `name`. If found, the index of that electrode is\n        returned, else None.\n        Parameters\n        ----------\n        name : str\n            An electrode name (string identifier).\n        Returns\n        -------\n        A valid electrode index or None.\n        \"\"\"\n        # Is `name` a valid electrode name?\n        # Iterate through electrodes to find a matching name. Shuffle list\n        # to reduce time complexity of average lookup.\n        for idx, el in utils.traverse_randomly(enumerate(self.electrodes)):\n            if el.name == name:\n                return idx\n\n        # Worst case O(n): name could not be found.\n        return None\n\n    def get_eye(self):\n        return self._eye\n\n    def set_eye(self, eye):\n        if eye.lower() in ['r', 're', 'right']:\n            self._eye = 'RE'\n        elif eye.lower() in ['l', 'le', 'left']:\n            self._eye = 'LE'\n        else:\n            raise ValueError(\"Unknown eye '%s'. Choose from 'LE', 'RE'.\")\n\n    eye = property(get_eye, set_eye)\n\n\nclass ArgusI(ElectrodeArray):\n\n    def __init__(self, x_center=0, y_center=0, h=0, rot=0, eye='RE',\n                 use_legacy_names=False):\n        \"\"\"Create an ArgusI array on the retina\n        This function creates an ArgusI array and places it on the retina\n        such that the center of the array is located at\n        [`x_center`, `y_center`] (microns) and the array is rotated by\n        rotation angle `rot` (radians).\n        The array is oriented in the visual field as shown in Fig. 1 of\n        Horsager et al. (2009); that is, if placed in (0,0), the top two\n        rows will lie in the lower retina (upper visual field):\n        .. raw:: html\n          <pre>\n            y       A1 B1 C1 D1                     260 520 260 520\n            ^       A2 B2 C2 D2   where electrode   520 260 520 260\n            |       A3 B3 C3 D3   diameters are:    260 520 260 520\n            -->x    A4 B4 C4 D4                     520 260 520 260\n          </pre>\n        Electrode order is: A1, B1, C1, D1, A2, B2, ..., D4.\n        If `use_legacy_names` is True, electrode order is: L6, L2, M8, M4, ...\n        An electrode can be addressed by index (integer) or name.\n\n        Parameters\n        ----------\n        x_center : float, optional, default: 0\n            x coordinate of the array center (um)\n        y_center : float, optional, default: 0\n            y coordinate of the array center (um)\n        h : float || array_like, optional, default: 0\n            Distance of the array to the retinal surface (um). Either a list\n            with 16 entries or a scalar.\n        rot : float, optional, default: 0\n            Rotation angle of the array (rad). Positive values denote\n            counter-clock-wise (CCW) rotations in the retinal coordinate\n            system.\n        eye : {'LE', 'RE'}, optional, default: 'RE'\n            Eye in which array is implanted.\n\n        Examples\n        --------\n        Create an ArgusI array centered on the fovea, at 100um distance from\n        the retina:\n        >>> from pulse2percept import implants\n        >>> argus = implants.ArgusI(x_center=0, y_center=0, h=100, rot=0)\n\n        Get access to electrode 'B1':\n        >>> my_electrode = argus['B1']\n        \"\"\"\n        # Alternating electrode sizes, arranged in checkerboard pattern\n        r_arr = np.array([260, 520, 260, 520]) / 2.0\n        r_arr = np.concatenate((r_arr, r_arr[::-1], r_arr, r_arr[::-1]),\n                               axis=0)\n\n        # Set left/right eye\n        self.eye = eye\n\n        # In older papers, Argus I electrodes go by L and M\n        self.old_names = names = ['L6', 'L2', 'M8', 'M4',\n                                  'L5', 'L1', 'M7', 'M3',\n                                  'L8', 'L4', 'M6', 'M2',\n                                  'L7', 'L3', 'M5', 'M1']\n        # In newer papers, they go by A-D: A1, B1, C1, D1, A1, B2, ..., D4\n        # Shortcut: Use `chr` to go from int to char\n        self.new_names = [chr(i) + str(j) for j in range(1, 5)\n                          for i in range(65, 69)]\n\n        if use_legacy_names:\n            names = self.old_names\n        else:\n            names = self.new_names\n\n        if isinstance(h, list):\n            h_arr = np.array(h).flatten()\n            if h_arr.size != len(r_arr):\n                e_s = \"If `h` is a list, it must have 16 entries.\"\n                raise ValueError(e_s)\n        else:\n            # All electrodes have the same height\n            h_arr = np.ones_like(r_arr) * h\n\n        # Equally spaced electrodes: n_rows x n_cols = 16\n        e_spacing = 800  # um\n        n_cols = 4  # number of electrodes horizontally (same vertically)\n        x_arr = np.arange(n_cols) * e_spacing - (n_cols / 2 - 0.5) * e_spacing\n        if self.eye == 'LE':\n            # Left eye: Need to invert x coordinates and rotation angle\n            x_arr = x_arr[::-1]\n        x_arr, y_arr = np.meshgrid(x_arr, x_arr, sparse=False)\n\n        # Rotation matrix\n        R = np.array([np.cos(rot), -np.sin(rot),\n                      np.sin(rot), np.cos(rot)]).reshape((2, 2))\n\n        # Set the x, y location of the tack\n        if self.eye == 'RE':\n            self.tack = np.matmul(R, [-(n_cols / 2 + 0.5) * e_spacing, 0])\n        else:\n            self.tack = np.matmul(R, [(n_cols / 2 + 0.5) * e_spacing, 0])\n        self.tack = tuple(self.tack + [x_center, y_center])\n\n        # Rotate the array\n        xy = np.vstack((x_arr.flatten(), y_arr.flatten()))\n        xy = np.matmul(R, xy)\n        x_arr = xy[0, :]\n        y_arr = xy[1, :]\n\n        # Apply offset\n        x_arr += x_center\n        y_arr += y_center\n\n        self.etype = 'epiretinal'\n        self.num_electrodes = 0\n        self.electrodes = []\n        for r, x, y, h, n in zip(r_arr, x_arr, y_arr, h_arr, names):\n            self.add_electrode(Electrode(self.etype, r, x, y, h, n))\n\n    def __str__(self):\n        return \"ArgusI(%s, num_electrodes=%d)\" % (self.etype,\n                                                  self.num_electrodes)\n\n    def get_old_name(self, new_name):\n        \"\"\"Look up the legacy name of a standard-named Argus I electrode\"\"\"\n        return self.old_names[self.new_names.index(new_name)]\n\n    def get_new_name(self, old_name):\n        \"\"\"Look up the standard name of a legacy-named Argus I electrode\"\"\"\n        return self.new_names[self.old_names.index(old_name)]\n\n\nclass ArgusII(ElectrodeArray):\n\n    def __init__(self, x_center=0, y_center=0, h=0, rot=0, eye='RE'):\n        \"\"\"Create an ArgusII array on the retina\n        This function creates an ArgusII array and places it on the retina\n        such that the center of the array is located at\n        [`x_center`, `y_center`] (microns) and the array is rotated by\n        rotation angle `rot` (radians).\n        The array is oriented upright in the visual field, such that an\n        array with center (0,0) has the top three rows lie in the lower\n        retina (upper visual field), as shown below:\n        .. raw:: html\n          <pre>\n                    A1 A2 A3 A4 A5 A6 A7 A8 A9 A10\n            y       B1 B2 B3 B4 B5 B6 B7 B8 B9 B10\n            ^       C1 C2 C3 C4 C5 C6 C7 C8 C9 C10\n            |       D1 D2 D3 D4 D5 D6 D7 D8 D9 D10\n            -->x    E1 E2 E3 E4 E5 E6 E7 E8 E9 E10\n                    F1 F2 F3 F4 F5 F6 F7 F8 F9 F10\n          </pre>\n        Electrode order is: A1, A2, ..., A10, B1, B2, ..., F10.\n        An electrode can be addressed by index (integer) or name.\n\n        Parameters\n        ----------\n        x_center : float\n            x coordinate of the array center (um)\n        y_center : float\n            y coordinate of the array center (um)\n        h : float || array_like\n            Distance of the array to the retinal surface (um). Either a list\n            with 60 entries or a scalar.\n        rot : float\n            Rotation angle of the array (rad). Positive values denote\n            counter-clock-wise (CCW) rotations in the retinal coordinate\n            system.\n        eye : {'LE', 'RE'}, optional, default: 'RE'\n            Eye in which array is implanted.\n\n        Examples\n        --------\n        Create an ArgusII array centered on the fovea, at 100um distance from\n        the retina:\n        >>> from pulse2percept import implants\n        >>> argus = implants.ArgusII(x_center=0, y_center=0, h=100, rot=0)\n\n        Get access to electrode 'E7':\n        >>> my_electrode = argus['E7']\n        \"\"\"\n        # Electrodes are 200um in diameter\n        r_arr = np.ones(60) * 100.0\n\n        # Set left/right eye\n        self.eye = eye\n\n        # Standard ArgusII names: A1, A2, ..., A10, B1, ..., F10\n        names = [chr(i) + str(j) for i in range(65, 71) for j in range(1, 11)]\n\n        if isinstance(h, list):\n            h_arr = np.array(h).flatten()\n            if h_arr.size != len(r_arr):\n                e_s = \"If `h` is a list, it must have 60 entries.\"\n                raise ValueError(e_s)\n        else:\n            # All electrodes have the same height\n            h_arr = np.ones_like(r_arr) * h\n\n        # Equally spaced electrodes: n_rows x n_cols = 60\n        e_spacing = 525  # um\n        n_cols = 10  # number of electrodes horizontally\n        n_rows = 6  # number of electrodes vertically\n        x_arr = np.arange(n_cols) * e_spacing - (n_cols / 2 - 0.5) * e_spacing\n        if self.eye == 'LE':\n            # Left eye: Need to invert x coordinates and rotation angle\n            x_arr = x_arr[::-1]\n        y_arr = np.arange(n_rows) * e_spacing - (n_rows / 2 - 0.5) * e_spacing\n        x_arr, y_arr = np.meshgrid(x_arr, y_arr, sparse=False)\n\n        # Rotation matrix\n        rotmat = np.array([np.cos(rot), -np.sin(rot),\n                           np.sin(rot), np.cos(rot)]).reshape((2, 2))\n\n        # Set the x, y location of the tack\n        if self.eye == 'RE':\n            self.tack = np.matmul(rotmat, [-(n_cols / 2 + 0.5) * e_spacing, 0])\n        else:\n            self.tack = np.matmul(rotmat, [(n_cols / 2 + 0.5) * e_spacing, 0])\n        self.tack = tuple(self.tack + [x_center, y_center])\n\n        # Rotate the array\n        xy = np.vstack((x_arr.flatten(), y_arr.flatten()))\n        xy = np.matmul(rotmat, xy)\n        x_arr = xy[0, :]\n        y_arr = xy[1, :]\n\n        # Apply offset\n        x_arr += x_center\n        y_arr += y_center\n\n        self.etype = 'epiretinal'\n        self.num_electrodes = 0\n        self.electrodes = []\n        for r, x, y, h, n in zip(r_arr, x_arr, y_arr, h_arr, names):\n            self.add_electrode(Electrode(self.etype, r, x, y, h, n))\n\n    def __str__(self):\n        return \"ArgusII(%s, num_electrodes=%d)\" % (self.etype,\n                                                   self.num_electrodes)\n\n\nclass AlphaIMS(ElectrodeArray):\n\n    def __init__(self, x_center=0, y_center=0, h=0, rot=0, eye='RE'):\n        \"\"\"Create an Alpha IMS array on the retina and place it on the retina\n        such that the center of the array is located at [`x_center`, `y_center`]\n        (microns) and the array is rotated by rotation angle `rot` (radians).\n        The array is oriented upright in the visual field, such that an array\n        with center (0,0) has the top three rows lie in the lower retina\n        (upper visual field), as shown below:\n\n        Parameters\n        ----------\n        x_center : float\n            x coordinate of the array center (um)\n        y_center : float\n            y coordinate of the array center (um)\n        h : float || array_like\n            Distance of the array to the retinal surface (um). Either a list\n            with 60 entries or a scalar.\n        rot : float\n            Rotation angle of the array (rad). Positive values denote\n            counter-clock-wise (CCW) rotations in the retinal coordinate\n            system.\n        eye : {'LE', 'RE'}, optional, default: 'RE'\n            Eye in which array is implanted.\n        \"\"\"\n\n        self.eye = eye\n        self.etype = 'subretinal'\n\n        # Electrode spacing, radius\n        e_spacing = 72  # um\n        elec_radius = 50\n        # number of electrodes horizontally, vertically, and total\n        n_cols = 37\n        n_rows = 37\n        n_elecs = n_cols * n_rows\n\n        # TODO: look up naming convention\n        names = np.ones(n_elecs)\n\n        # array containing electrode radii (uniform)\n        r_arr = np.full(shape=n_elecs, fill_value=elec_radius)\n\n        # array of electrode heights (uniform)\n        h_arr = np.ones_like(r_arr) * h\n\n        # arrays of x and y coordinates\n        x_arr = np.arange(n_cols) * e_spacing - (n_cols / 2 - 0.5) * e_spacing\n        if self.eye == 'LE':\n            # Left eye: Need to invert x coordinates and rotation angle\n            x_arr = x_arr[::-1]\n        y_arr = np.arange(n_rows) * e_spacing - (n_rows / 2 - 0.5) * e_spacing\n        x_arr, y_arr = np.meshgrid(x_arr, y_arr, sparse=False)\n\n        # Rotation matrix\n        rotmat = np.array([np.cos(rot), -np.sin(rot),\n                           np.sin(rot), np.cos(rot)]).reshape((2, 2))\n\n        # Set the x, y location of the tack\n        if self.eye == 'RE':\n            self.tack = np.matmul(rotmat, [-(n_cols / 2 + 0.5) * e_spacing, 0])\n        else:\n            self.tack = np.matmul(rotmat, [(n_cols / 2 + 0.5) * e_spacing, 0])\n        self.tack = tuple(self.tack + [x_center, y_center])\n\n        # Rotate the array\n        xy = np.vstack((x_arr.flatten(), y_arr.flatten()))\n        xy = np.matmul(rotmat, xy)\n        x_arr = xy[0, :]\n        y_arr = xy[1, :]\n\n        # Apply offset\n        x_arr += x_center\n        y_arr += y_center\n\n        # add all electrodes\n        self.num_electrodes = 0\n        self.electrodes = []\n        for r, x, y, h, n in zip(r_arr, x_arr, y_arr, h_arr, names):\n            self.add_electrode(Electrode(self.etype, r, x, y, h, n))\n\n    def __str__(self):\n        return \"AlphaIMS(%s, num_electrodes=%d)\" % (self.etype,\n                                                    self.num_electrodes)\n", "meta": {"hexsha": "5e4ced2438b93e9c3e5ade90e629db8996f6cf66", "size": 30644, "ext": "py", "lang": "Python", "max_stars_repo_path": "pulse2percept/implants.py", "max_stars_repo_name": "jonluntzel/pulse2percept", "max_stars_repo_head_hexsha": "dbe17230be0354c4cfc57a72b649c611fe496464", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pulse2percept/implants.py", "max_issues_repo_name": "jonluntzel/pulse2percept", "max_issues_repo_head_hexsha": "dbe17230be0354c4cfc57a72b649c611fe496464", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pulse2percept/implants.py", "max_forks_repo_name": "jonluntzel/pulse2percept", "max_forks_repo_head_hexsha": "dbe17230be0354c4cfc57a72b649c611fe496464", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4896907216, "max_line_length": 80, "alphanum_fraction": 0.5601422791, "include": true, "reason": "import numpy", "num_tokens": 7881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.34864514210180597, "lm_q1q2_score": 0.19600010603762516}}
{"text": "#!/usr/bin/env python\n\n#everything is needed to perform the script and maybe something else\nfrom numpy import *\nfrom scipy import *\nfrom scipy import integrate\nfrom scipy.interpolate import interp1d\nimport pyfits\nimport os\nimport sys\nimport string \nimport shutil\nimport math\nimport glob\nimport s3 #import metadata \nfrom s3.utilities import *  #import definitions\nfrom time import strftime, sleep\nimport time\nfrom pylab import *\nfrom scipy.optimize import curve_fit\n# pre-set plot parameters, resolution untouched since it is not needed (default=80 dpi) \nfrom pylab import rcParams\nrcParams['figure.figsize'] = 11, 8\nrcParams['figure.subplot.top'] = 0.95\nrcParams['figure.subplot.right'] = 0.90\nrcParams['figure.subplot.left'] = 0.11\n###########################################\npypath = os.path.expandvars('$HOME')           # it copies login.cl if it is not in the same dir\nif not os.path.isfile('login.cl'):\n    shutil.copyfile(pypath+'/iraf/login.cl','login.cl')\n###########################################\n\n################### for the help ##################\nfrom optparse import OptionParser\n\ndescription = \" K-correction loop for flux calibrated spectra. List of files are accepted \"\nusage = \"%prog \"\nif __name__ == \"__main__\":\n    parser = OptionParser(usage=usage, description=description, version=\"%prog \" + str(s3.__version__))\n    parser.add_option(\"-v\", \"--verbose\",dest=\"verbose\",\\\n                  action=\"store_true\",default=False,\n                  help='Print tasks description')\n    parser.add_option(\"-s\", \"--sleep\",dest=\"sleepc\", action=\"store\", type=\"float\", default=None, \n                  help='Change the sleep time between cycles. Default is 1s (good for 4GB of RAM or greater), the lower your RAM, the higher it should be.')\n    parser.add_option(\"-r\", \"--redshifterr\",dest=\"redshifterr\", action=\"store\", type=\"float\" ,default=None,\n                  help='Change the default error on your redshift (+/- 0.005) to estimate the K-correction errors')\n    option,args = parser.parse_args()\n\n###### moved here because OptionParser --version conflicts with pyraf version########\n#what we need from iraf\nfrom pyraf import iraf\n\n########### option to change the python sleep function between cycles #########\nif option.sleepc == None:\n    _sleepc = 1\nelse:\n    _sleepc = option.sleepc\n\nif option.redshifterr == None:\n    _redshifterr = 0.005\nelse:\n    _redshifterr = option.redshifterr\n################ internal description #############\n\nh=\"######################################################################\\n\"+\\\n  \"#########  SuperNova Algorithm for K-correction Evaluation  ##########\\n\"+\\\n  \"##################     S.N.A.K.E. (loop version)      ################\\n\"+\\\n  \"##########          C. Inserra  v1.1.0 29/10/2015          ###########\\n\"+\\\n  \"######################################################################\\n\"+\\\n  \" K-correction based on the formula m(x) = M(y) + DM + K(y,x)\\n\"+\\\n  \" BE SURE that the spectra are flux calibrated  \\n\"+ \\\n  \" If you use this code and find it useful, please give a thought \\n\"+ \\\n  \" to cite it. \\n\"+ \\\n  \" The reference is Inserra et al. 2015, ApJ submitted \\n\"+\\\n  \"######################################################################\\n\"\n\nprint h \n\n#the path where the metatabs dat are\nfilterdir=s3.__path__[0]+'/metadata/' # To set the directory\n\n# cleaning process\nos.system('rm -rf sn.txt')\nos.system('rm -rf sn.fits')\nos.system('rm -rf sn_xbbody.txt')\nos.system('rm -rf sn_dez_xbbody.txt')\nos.system('rm -rf sn_dez_xbbody_err1.txt')\nos.system('rm -rf sn_dez_xbbody_err2.txt')\nos.system('rm -rf bbody_sn_dez_fit.dat')\nos.system('rm -rf bbody_sn_dez_fit_err1.dat')\nos.system('rm -rf bbody_sn_dez_fit_err2.dat')\nos.system('rm -rf bbody_sn_dez_fit.fits')\nos.system('rm -rf bbody_sn_dez_fit_err1.fits')\nos.system('rm -rf bbody_sn_dez_fit_err2.fits')\nos.system('rm -rf bbody_sn_fit.fits')\nos.system('rm -rf bbody_sn_fit.dat')\nos.system('rm -rf sn_dez.txt')\nos.system('rm -rf sn_dez_err1.txt')\nos.system('rm -rf sn_dez_err2.txt')\nos.system('rm -rf sn_dez.fits')\nos.system('rm -rf sn_dez_err1.fits')\nos.system('rm -rf sn_dez_err2.fits')\nos.system('rm -rf sn_dez_dered.fits')\nos.system('rm -rf sn_dez_dered_err1.fits')\nos.system('rm -rf sn_dez_dered_err2.fits')\nos.system('rm -rf sn_dez_dered.txt')\nos.system('rm -rf sn_dez_dered_err1.txt')\nos.system('rm -rf sn_dez_dered_err2.txt')\nos.system('rm -rf sn_galdered_dez.fits')\nos.system('rm -rf sn_galdered_dez_err1.fits')\nos.system('rm -rf sn_galdered_dez_err2.fits')\nos.system('rm -rf sn_galdered.fits')\nos.system('rm -rf bsn_combo_dez.fits')\nos.system('rm -rf bsn_combo_dez_err1.fits')\nos.system('rm -rf bsn_combo_dez_err2.fits')\nos.system('rm -rf bsn_combo_dez.txt')\nos.system('rm -rf bsn_combo_dez_err1.txt')\nos.system('rm -rf bsn_combo_dez_err2.txt')\nos.system('rm -rf bsn_combo.fits')\nos.system('rm -rf bsn_combo.txt')\n\n#######################################################\n# Variable definitions\n#######################################################\n\nquestion = raw_input('Do you have a list of spectra ? ([yes]/no) ')\nif not question:\n    question = 'yes'\n\nif question == 'yes' or question == 'y' or question == 'Y' or question == 'Yes' or question == 'YES':\n\tfiles = raw_input('List ? [e.g. list, list.txt, list.dat] ')\n\tlcf = open(files,'r')  \n\triga = lcf.readlines()             # lista di righe intere\n\tlcf.close()\n\tsnlist = []\n\tfor line in riga:\n\t\tp = line.split()\n\t\tsnlist.append(p[0])\nelse:\n\tfiles = raw_input('List the spectra to use (space separated list): ')\n\tsnlist = string.split(files)\n\nprint ''\nquestionred = raw_input('Do you have a list of redshifts ? ([yes]/no) ')\nif not questionred:\n    questionred = 'yes'\n\nif questionred == 'yes' or questionred == 'y' or questionred == 'Y' or questionred == 'Yes' or questionred == 'YES':\n\tfiles = raw_input('List ? [e.g. list, list.txt, list.dat] ')\n\tlcf = open(files,'r')  \n\triga = lcf.readlines()             # lista di righe intere\n\tlcf.close()\n\tz = []\n\tfor line in riga:\n\t\tp = line.split()\n\t\tz.append(p[0])\nelse:\n\tred = raw_input('List the redshifts you want to use (space separated list) or the single redshift that will be used for all the spectra: ')\n\tredshift = string.split(red)\n\tif len(redshift) != len(snlist):\n\t\tif len(redshift) == 1:\n\t\t\tz = redshift * len(snlist)\n\telse:\n\t\tz = redshift\n\t\t\nprint ''\nprint '#################################'\nprint '#   Available filters and ID    #'\nprint '#-------------------------------#'\nprint '# BESSEL:  U  B  V  R  I        #'\nprint '# SLOAN:   us gs rs is zs       #'\nprint '# UV:  NUV  FUV  uw2  um2  uw1  #'\nprint '# NIR:     J  H  K              #' \nprint '#################################'\nprint ''  \nquestionfilobs = raw_input('Do you have a list of observed filters ? ([yes]/no) ')\nif not questionfilobs:\n    questionfilobs = 'yes'\n\nif questionfilobs == 'yes' or questionfilobs == 'y' or questionfilobs == 'Y' or questionfilobs == 'Yes' or questionfilobs == 'YES':\n\tfiles = raw_input('List ? [e.g. list, list.txt, list.dat] ')\n\tlcf = open(files,'r')  \n\triga = lcf.readlines()             # lista di righe intere\n\tlcf.close()\n\tfobs = []\n\tfor line in riga:\n\t\tp = line.split()\n\t\tfobs.append(p[0])\nelse:\n\tfolist = raw_input('List the observed filters you want to use (space separated list) or the observed filter that will be used for all the spectra: ')\n\tfolist_1 = string.split(folist)\n\tif len(folist_1) != len(snlist):\n\t\tif len(folist_1) == 1:\n\t\t\tfobs = folist_1 * len(snlist)\n\telse:\n\t\tfobs = folist_1\nprint ''\nquestionfilrest = raw_input('Do you have a list of rest-frame filters ? ([yes]/no) ')\nif not questionfilrest:\n    questionfilrest = 'yes'\n\nif questionfilrest == 'yes' or questionfilrest == 'y' or questionfilrest == 'Y' or questionfilrest == 'Yes' or questionfilrest == 'YES':\n\tfiles = raw_input('List ? [e.g. list, list.txt, list.dat] ')\n\tlcf = open(files,'r')  \n\triga = lcf.readlines()             # lista di righe intere\n\tlcf.close()\n\tfrest = []\n\tfor line in riga:\n\t\tp = line.split()\n\t\tfrest.append(p[0])\nelse:\n\tfrlist = raw_input('List the rest-frame filters you want to use (space separated list) or the rest-frame filter that will be used for all the spectra: ')\n\tfrlist_1 = string.split(frlist)\n\tif len(frlist_1) != len(snlist):\n\t\tif len(frlist_1) == 1:\n\t\t\tfrest = frlist_1 * len(snlist)\n\telse:\n\t\tfrest = frlist_1\n\nprint ''\nprint '######################################################################'\nprint 'Please, bear in mind that the true K-correction should be evaluated   '\nprint 'without reddening. As a consequence in the cases of K-coorection on   '\nprint 'hybrid spectra reddening will not be evaluated.'\nprint '######################################################################'\n\nprint ''\n_ebvg = raw_input('Galactic E(B-V) [0.0] ? ')\nif not _ebvg:\n    ebvg = 0.0\nelse: \n    ebvg = float(_ebvg)\nprint ''\n\n_ebvh = raw_input('Host E(B-V) [0.0] ? ')\nif not _ebvh:\n    ebvh = 0.0\nelse: \n    ebvh = float(_ebvh)\nprint ''\n\nquestionplot = raw_input('Do you want to see your results plotted against redshift ? ([yes]/no) ')\nif not questionplot:\n    questionplot = 'yes'\n\n###### Arrays definition ##########\nlength = shape(snlist)[0]\nkcorr = array(zeros(length))\nkcorr_e = array(zeros(length))\nmethod = [None] * len(snlist)\nbtemp = [None] * len(snlist)\nanguncov = [None] * len(snlist)\nuncovside = [None] * len(snlist)\nredlist = [None] * len(snlist)\n\n\n##########################\n### Creating a txt file\n#########################\nTnow = int(strftime(\"%H%M%S\"))\nTnowd = int(strftime(\"%d%m%Y\"))\nkcf = \"Kcorrection_%.0i_%.0i.txt\" % (Tnowd,Tnow)\nfilekc = open(kcf,\"w\")\nfilekc.write(\"# K-corrections from observed filter to rest-frame filter \\n\")\nfilekc.write(\"# Galactic E(B-V)=%g, host E(B-V)=%g \\n\" % (ebvg,ebvh))\nfilekc.write(\"# File\\tRedshift\\tObs-filter\\tRest-filter\\tK-corr\\terror\\tSNAKE mode\\t Blackbody Temperature\\t Angstroms uncovered in the wavelength region\\n\\n\")\n\nnow = time.time() \nii = 0\nwhile ii != len(snlist):\n\t_snname = snlist[ii]\n\t#### it recognizes automatically the extension of your file and convert to fits\n\tfileName, fileExtension = os.path.splitext(_snname)\n\tif fileExtension == '.txt' or fileExtension == '.dat' or fileExtension == '.asci' or fileExtension == '.ascii':\n\t\tiraf.rspec(_snname,fileName+'.fits',flux='no',dtype='interp')\n\t\tsnname = fileName+'.fits'\n\telse:\n\t\tsnname = _snname\n\n\tredshift = float(z[ii])\n\tredserrspace1 = float(redshift)+_redshifterr\n\tredserrspace2 = float(redshift)-_redshifterr\n\tfilter1 = fobs[ii]\n\tfilter2 = frest[ii]\n\tprint '\\033[1mSpectrum number\\033[0m ', 1+ii\n\tprint 'Spectrum = ', snname, ' & redshift = ', redshift,'+/-',_redshifterr\n \tlogterm = 2.5*log10(1+float(redshift))\n\tsn = snname\n\n\t############################# Safety loop to check again if you have everything removed and avoid errors in the programme ###################\n\tfiletoremove = ['sn.txt','sn.fits','sn_xbbody.txt','sn_dez_xbbody.txt','sn_dez_xbbody_err1.txt','sn_dez_xbbody_err2.txt','bbody_sn_dez_fit.dat','bbody_sn_dez_fit_err1.dat','bbody_sn_dez_fit_err2.dat','bbody_sn_dez_fit.fits', \\\n\t\t\t\t\t'bbody_sn_dez_fit_err1.fits','bbody_sn_dez_fit_err2.fits','bbody_sn_fit.fits','bbody_sn_fit.dat','sn_dez.txt','sn_dez_err1.txt','sn_dez_err2.txt','sn_dez.fits','sn_dez_err1.fits','sn_dez_err2.fits','sn_dez_dered.fits', \\\n\t\t\t\t\t'sn_dez_dered_err1.fits','sn_dez_dered_err2.fits','sn_dez_dered.txt','sn_dez_dered_err1.txt','sn_dez_dered_err2.txt','sn_galdered_dez.fits','sn_galdered_dez_err1.fits','sn_galdered_dez_err2.fits','sn_galdered.fits', \\\n\t\t\t\t\t'bsn_combo_dez.fits','bsn_combo_dez_err1.fits','bsn_combo_dez_err2.fits','bsn_combo_dez.txt','bsn_combo_dez_err1.txt','bsn_combo_dez_err2.txt','bsn_combo.fits','bsn_combo.txt']\n\tjj = 0\n\twhile jj != len(filetoremove):\n\t\tif os.path.exists(filetoremove[jj]):\n\t\t\tprint ''\n\t\t\tprint \"######################################################################\"\n\t\t\tprint \"Sorry, I am going too fast for your computer RAM, I need to rest for a bit...\"\n\t\t\tprint \"######################################################################\"\n\t\t\tprint ''\n\t\t\tfor i in xrange(5,0,-1):\n\t\t\t\ttime.sleep(1)\n    \t\t\tsys.stdout.write(str(i)+' ')\n    \t\t\tsys.stdout.flush()\n\t\t\tif os.path.exists(filetoremove[jj]):\n\t\t\t\tprint ''\n\t\t\t\tprint \"######################################################################\"\n\t\t\t\tprint \"Ooops, that is kind of embarassing, apparently there is this file \"+filetoremove[jj]+\" that is delaying my job. May I ask you to assist me and remove it?\"\n\t\t\t\tfor i in xrange(10,0,-1):\n\t\t\t\t\ttime.sleep(1)\n    \t\t\t\tsys.stdout.write(str(i)+' ')\n    \t\t\t\tsys.stdout.flush()\n\n\t\t\t\tprint \"######################################################################\"\n\t\t\t\tprint ''\n\t\tjj = jj + 1\n\t#########################################################################################################\n\t\n\t#######################################################\n\t# Filter1 and its definitions\n\t#######################################################\n\tlcf = open(filterdir+filter1+'.txt','r')      # defintion of the file\n\triga = lcf.readlines()             # list of lines\n\triga1 = riga[4:len(riga)]  #list of lines where the wave and transmission are stored\n\tlcf.close()\n\tzp_ef = float(riga[0]) #zero point in energy flux (erg/cm^2/s)\n\tzp_ef_err = zp_ef * 1.0075\n\tfilter_ew = riga[1] #equivalent width of the filter\n\tpeak_wave = float(riga[2]) #peak wavelength of the filter\n\tsystem = riga[3] # system used: vega or ab\n\twavefilter, transmission= [], []\n\tfor line in riga1:\n\t    p = line.split()\n\t    wavefilter.append(float(p[0]))\n\t    transmission.append(float(p[1]))\n\t\n\twavefilterv = array(wavefilter)\n\ttransmissionv = array(transmission)\n\tfil_obs_min= min(wavefilterv)\n\tfil_obs_max= int(max(wavefilterv)) #integer is needed for a sharper cut-off\n\t#############################################################\n\t\n\t#######################################################\n\t# Filter2 and its definitions\n\t#######################################################\n\tlcfr = open(filterdir+filter2+'.txt','r')      # defintion of the file\n\trigar = lcfr.readlines()             # list of lines\n\trigar1 = rigar[4:len(rigar)]  #list of lines where the wave and transmission are stored\n\tlcfr.close()\n\tzp_ef_rest = float(rigar[0]) #zero point in energy flux (erg/cm^2/s)\n\tzp_ef_rest_err = zp_ef_rest * 1.0075\n\tfilter_ew_rest = rigar[1] #equivalent width of the filter\n\tpeak_wave_rest = float(rigar[2]) #peak wavelength of the filter\n\tsystem_rest = rigar[3] # system used: vega or ab\n\twavefilter_rest, transmission_rest= [], []\n\tfor line in rigar1:\n\t    p = line.split()\n\t    wavefilter_rest.append(float(p[0]))\n\t    transmission_rest.append(float(p[1]))\n\t\n\twavefilter_restv = array(wavefilter_rest)\n\ttransmission_restv = array(transmission_rest)\n\tfil_rest_min= min(wavefilter_restv)\n\tfil_rest_max= int(max(wavefilter_restv)) #integer is needed for a sharper cut-off\n\t#############################################################\n\n\tspec = sn + \"[*,1,1]\"            # generally multidimension\n\tiraf.imcopy(sn+'[*,1,1]','sn.fits',verbose='no')             # to create a onedimension fit to use during the script\n\t# redshift correction without absorption                \n\tprint '\\033[34m*** correcting the spectrum for redshift without Milky Way absorption *** \\033[0m'\n\ttry:\n\t\tiraf.dopcor('sn.fits','sn_dez.fits', redshift=redshift, isveloc='no', flux='no',factor=3)\n\t\tiraf.dopcor('sn.fits','sn_dez_err1.fits', redshift=redserrspace1, isveloc='no', flux='no',factor=3)\n\t\tiraf.dopcor('sn.fits','sn_dez_err2.fits', redshift=redserrspace2, isveloc='no', flux='no',factor=3)\n\texcept:\n\t\tprint ' WARNING: Problem to redshift the spectrum'\n\n\tif ebvh == 0.0:\n\t\t# galaxy and host reddening correction\n\t\tprint '\\033[31m'+'*** correcting spectrum for galactic reddening ***\\033[0m'\n\t\tebv = ebvg+ebvh\n\t\tprint '\\033[31m Total E(B-V) = galactic E(B-V) = \\033[0m',ebv\n\t\ttry:\n\t\t\tiraf.unlearn(\"deredden\")\n\t\t\tiraf.dered('sn_dez.fits',\"sn_dez_dered.fits\", value=ebv, R=3.1, type='E(B-V)',overrid='yes',uncorre='no')\n\t\t\tiraf.dered('sn_dez_err1.fits',\"sn_dez_dered_err1.fits\", value=ebv, R=3.1, type='E(B-V)',overrid='yes',uncorre='no')\n\t\t\tiraf.dered('sn_dez_err2.fits',\"sn_dez_dered_err2.fits\", value=ebv, R=3.1, type='E(B-V)',overrid='yes',uncorre='no')\n\t\texcept:\n\t\t\t\tprint 'WARNING: it is not possible to correct the spectrum for salactic reddenning '\n\t\t\t\ttry:\n\t\t\t\t\tiraf.unlearn(\"scopy\")\n\t\t\t\t\tiraf.scopy('sn_dez.fits',\"sn_dez_dered.fits\", w1='INDEF', w2='INDEF',format='multispec')\n\t\t\t\t\tiraf.scopy('sn_dez_err1.fits',\"sn_dez_dered_err1.fits\", w1='INDEF', w2='INDEF',format='multispec')\n\t\t\t\t\tiraf.scopy('sn_dez_err2.fits',\"sn_dez_dered_err2.fits\", w1='INDEF', w2='INDEF',format='multispec')\n\t\t\t\texcept:\n\t\t\t\t\tprint 'WARNING: problem to copy the spectrum or with the spectrum fits format'\n\telse:\n\t\t#Galaxy reddening correction\n\t\tprint '\\033[31m'+'*** correcting spectrum for galactic reddening ***\\033[0m'\n\t\ttry:\n\t\t\tiraf.dered(sn + '[*,1,1]',\"sn_galdered.fits\", value=ebvg, R=3.1, type='E(B-V)')\n\t\texcept:\n\t\t\tprint ' WARNING: it is not possible to correct the spectrum for salactic reddenning '\n\t\t\ttry:\n\t\t\t\tiraf.scopy(sn + '[*,1,1]',\"sn_galdered.fits\", w1='INDEF', w2='INDEF',format='multispec')\n\t\t\texcept:\n\t\t\t\tprint ' WARNING: a problem is appeared to copy the spectrum, problems with the spectrum fits format'\n\t\tprint '\\033[34m*** correcting the spectrum for redshift ***\\033[0m'\n\t\ttry:\n\t\t\tiraf.dopcor('sn_galdered.fits','sn_galdered_dez.fits', redshift=redshift, isveloc='no', flux='no')\n\t\t\tiraf.dopcor('sn_galdered.fits','sn_galdered_dez_err1.fits', redshift=redserrspace1, isveloc='no', flux='no',factor=3)\n\t\t\tiraf.dopcor('sn_galdered.fits','sn_galdered_dez_err2.fits', redshift=redserrspace2, isveloc='no', flux='no',factor=3)\n\t\texcept:\n\t\t\tprint ' WARNING: Problem to redshift the spectrum'\n\t\t# host reddening correction\n\t\tprint '\\033[31m*** correcting spectrum for host reddening ***\\033[0m'\n\t\tebv = ebvg+ebvh\n\t\tprint '\\033[31m NOW total E(B-V) = ',ebv\n\t\tiraf.hedit(\"sn_galdered_dez.fits\", 'DEREDDEN', add='no', addonly='no', delete='yes', verify ='no')\n\t\tiraf.hedit(\"sn_galdered_dez_err1.fits\", 'DEREDDEN', add='no', addonly='no', delete='yes', verify ='no', show='no')\n\t\tiraf.hedit(\"sn_galdered_dez_err2.fits\", 'DEREDDEN', add='no', addonly='no', delete='yes', verify ='no', show='no')\n\t\tiraf.dered('sn_galdered_dez.fits',\"sn_dez_dered.fits\", value=ebvh, R=3.1, type='E(B-V)',overrid='yes')\n\t\tiraf.dered('sn_galdered_dez_err1.fits',\"sn_dez_dered_err1.fits\", value=ebvh, R=3.1, type='E(B-V)',overrid='yes')\n\t\tiraf.dered('sn_galdered_dez_err2.fits',\"sn_dez_dered_err2.fits\", value=ebvh, R=3.1, type='E(B-V)',overrid='yes')\n\t\tprint '\\033[0m' \n\t\n\n\t#################################################################\n\t#### Preparation for wavelength check\n\t#################################################################\n\t\n\tspectrum=iraf.wspec(\"sn.fits\",\"sn_xbbody.txt\", header='no')\n\tlcf = open('sn_xbbody.txt','r')     \n\triga = lcf.readlines()            \n\tlcf.close()\n\twave,flux= [],[]\n\tfor line in riga:\n\t    p = line.split()\n\t    wave.append(float(p[0]))\n\t    flux.append(float(p[1]))\n\t\n\twavev = array(wave)\n\tfluxv = array(flux)\n\twaveobs_min= min(wavev)\n\twaveobs_max= max(wavev)\n\t\n\tspectrum=iraf.wspec(\"sn_dez_dered.fits\",\"sn_dez_xbbody.txt\", header='no')\n\tlcf = open('sn_dez_xbbody.txt','r')     \n\triga = lcf.readlines()          \n\tlcf.close()\n\twavedez,fluxdez= [],[]\n\tfor line in riga:\n\t\tp = line.split()\n\t\twavedez.append(float(p[0]))\n\t\tfluxdez.append(float(p[1]))\n\t\n\twavedezv = array(wavedez)\n\tfluxdezv = array(fluxdez)\n\twaverest_min= min(wavedezv)\n\twaverest_max= max(wavedezv)\n\t\n\tspectrum=iraf.wspec(\"sn_dez_err1.fits\",\"sn_dez_xbbody_err1.txt\", header='no')\n\tlcf = open('sn_dez_xbbody_err1.txt','r')      \n\triga = lcf.readlines()             \n\tlcf.close()\n\twave,flux= [],[]\n\tfor line in riga:\n\t    p = line.split()\n\t    wave.append(float(p[0]))\n\t    flux.append(float(p[1]))\n\t\n\twavedezv_err1 = array(wave)\n\tfluxdezv_err1 = array(flux)\n\t\n\tspectrum=iraf.wspec(\"sn_dez_err2.fits\",\"sn_dez_xbbody_err2.txt\", header='no')\n\tlcf = open('sn_dez_xbbody_err1.txt','r')      \n\triga = lcf.readlines()             \n\tlcf.close()\n\twave,flux= [],[]\n\tfor line in riga:\n\t    p = line.split()\n\t    wave.append(float(p[0]))\n\t    flux.append(float(p[1]))\n\t\n\twavedezv_err2 = array(wave)\n\tfluxdezv_err2 = array(flux)\n\n\t################################\n\t### Define the different cases for K-correction\n\t################################\n\tsplit = 0 # splitting value\n\n\tif ((waveobs_min-fil_obs_min) > 50) or ((fil_obs_max-waveobs_max) > 50):\n\t    print ''\n\t    if (waveobs_min-fil_obs_min) > 50:\n\t        print waveobs_min-fil_obs_min,' Angstrom not covered by the observed spectrum in the blue' \n\t        anguncov[ii] = waveobs_min-fil_obs_min\n\t        uncovside[ii] = 'Blue'\n\t    if (fil_obs_max-waveobs_max) > 50:\n\t        print fil_obs_max-waveobs_max,' Angstrom not covered by the observed spectrum in the red'\n\t        anguncov[ii] = fil_obs_max-waveobs_max\n\t        uncovside[ii] = 'Red'\n\t        ############################################\n\t        # Prevent small exceptions for blue bands or the extreme of the NIR\n\t        ############################################\n\t    if filter1 != 'U' or filter1 != 'u' or filter1 != 'K' or filter1 != 'uvw1' or filter1 != 'uvw2' or filter1 != 'uvm2' or filter1 != 'NUV' or filter1 != 'FUV':\n\n\t\t    ###############################\n\t\t    ### BBody evaluation of the observed spectrum\n\t\t    ###############################\n\t\t    BBparams, covar = curve_fit(bbody,wavev,fluxv,p0=(10000,1E-16)) #intial guess\n\t\t    T= BBparams[0]\n\t\t    Area = BBparams[1]\n\t\t    print '\\nBlackbody temperature observed spectrum = %.0f +\\- %.0f K\\n' % (T,np.sqrt(covar[0,0]))\n\t\t    bbt = 'BBobs = %.0f +\\- %.0f K' % (T,np.sqrt(covar[0,0]))\n\t\t    outputname = \"bbody_sn_fit.dat\" #% T\n\t\t    file = open(outputname,\"w\")\n\t\t    file.write(\"# Blackbody temperature = %.0f +\\- %.0f K\\n\" % (T,np.sqrt(covar[0,0])))\n\t\t    w,f = [],[]\n\t\t    for wav in range(900,26000):\n\t\t        file.write(\"%g\\t%g\\n\" % (wav,bbody(wav,T,Area)))\n\t\t        w.append(wav)\n\t\t        f.append(bbody(wav,T,Area))\n\n\t\t    iraf.rspec('bbody_sn_fit.dat','bbody_sn_fit.fits', title='bbodyfit',flux='no',dtype='interp',crval1=900,cdelt1=1)\n\t\t    iraf.scombine('bbody_sn_fit.fits,sn.fits,sn.fits,sn.fits', 'bsn_combo.fits',combine='median')\n\n\t\t    iraf.wspec('bsn_combo.fits','bsn_combo.txt',header='no')\n\n\t\t    print '#######################################'\n\t\t    print '\\033[4mSince now you are working with an hybrid spectrum+blackbody, if you want additional information, please use the normal version.\\033[0m '\n\t\t    print '#######################################'\n\n\t\t    lcf = open('bsn_combo.txt','r')\n\t\t    riga = lcf.readlines()\n\t\t    lcf.close()\n\t\t    wave,flux= [],[]\n\t\t    for line in riga:\n\t\t        p = line.split()\n\t\t        if float(line.split()[0]) >= fil_obs_min and float(line.split()[0]) <= fil_obs_max: #to match the spectrum wavelegnths to those of the filter\n\t\t            wave.append(float(p[0]))\n\t\t            flux.append(float(p[1]))\n\t\t        \n\t\t    wavev = array(wave)\n\t\t    fluxv = array(flux)\n\t\t    wavesp_min= min(wavev)\n\t\t    wavesp_max= int(max(wavev)) #needed to avoid problems with interp1d\n\n\t\t    # interpolating the two responses to match the length and sampling coverage\n\t\t    conf = conv(wavev,fluxv,wavefilterv,transmissionv,wavesp_min,wavesp_max,fil_obs_min,fil_obs_max)\n\n\t\t    ##################################\n\t\t    ### Evaluating the magnitudes\n\t\t    ##################################\n\n\t\t    flux_obs = max(integrate.cumtrapz(conf[0],conf[1])) # using trapezoidal rule to integrate\n\t\t    flux_obs_err = flux_obs * (1+(anguncov[ii]-50)*0.0001)\n\n\t\t    iraf.dopcor('bsn_combo.fits','bsn_combo_dez.fits', redshift=redshift, isveloc='no', flux='no',factor=3)\n\t\t    iraf.dopcor('bsn_combo.fits','bsn_combo_dez_err1.fits', redshift=redserrspace1, isveloc='no', flux='no',factor=3)\n\t\t    iraf.dopcor('bsn_combo.fits','bsn_combo_dez_err2.fits', redshift=redserrspace2, isveloc='no', flux='no',factor=3)\n\t\t    iraf.wspec('bsn_combo_dez.fits','bsn_combo_dez.txt',header='no')\n\t\t    iraf.wspec('bsn_combo_dez_err1.fits','bsn_combo_dez_err1.txt',header='no')\n\t\t    iraf.wspec('bsn_combo_dez_err2.fits','bsn_combo_dez_err2.txt',header='no')\n\t\t    \n\t\t    lcf = open('bsn_combo_dez.txt','r')\n\t\t    riga = lcf.readlines()\n\t\t    lcf.close()\n\t\t    rwave,rflux= [],[]\n\t\t    for line in riga:\n\t\t        p = line.split()\n\t\t        if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n\t\t            rwave.append(float(p[0]))\n\t\t            rflux.append(float(p[1]))\n\t\t        \n\t\t    wave_dezv = array(rwave)\n\t\t    flux_dezv = array(rflux)\n\t\t    wavesp_dez_min= min(wave_dezv)\n\t\t    wavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n\n\t\t    # interpolating the two responses in the rest wavelength to match the length and sampling coverage\n\t\t    conf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n\t\t    flux_rest = max(integrate.cumtrapz(conf[0],conf[1]))\n\n\t\t    ###### doing that again for the errors  ############################################################\n\t\t    lcf = open('bsn_combo_dez_err1.txt','r')\n\t\t    riga = lcf.readlines()\n\t\t    lcf.close()\n\t\t    rwave,rflux= [],[]\n\t\t    for line in riga:\n\t\t        p = line.split()\n\t\t        if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n\t\t            rwave.append(float(p[0]))\n\t\t            rflux.append(float(p[1]))\n\t\t        \n\t\t    wave_dezv = array(rwave)\n\t\t    flux_dezv = array(rflux)\n\t\t    wavesp_dez_min= min(wave_dezv)\n\t\t    wavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n\n\t\t    conf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n\n\t\t    flux_rest_err1 = max(integrate.cumtrapz(conf[0],conf[1]))\n\t\t    \n\t\t    lcf = open('bsn_combo_dez_err2.txt','r')\n\t\t    riga = lcf.readlines()\n\t\t    lcf.close()\n\t\t    rwave,rflux= [],[]\n\t\t    for line in riga:\n\t\t        p = line.split()\n\t\t        if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n\t\t            rwave.append(float(p[0]))\n\t\t            rflux.append(float(p[1]))\n\t\t        \n\t\t    wave_dezv = array(rwave)\n\t\t    flux_dezv = array(rflux)\n\t\t    wavesp_dez_min= min(wave_dezv)\n\t\t    wavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n\n\t\t    conf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n\n\t\t    flux_rest_err2 = max(integrate.cumtrapz(conf[0],conf[1]))\n        \t##################################################################################################\n\t\t    kcorrrest_bb_wor=-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest)) +logterm\n\t\t    kcorrrest_bb_wor_err1=-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest_err1/zp_ef_rest)) +(2.5*log10(1+redserrspace1))\n\t\t    kcorrrest_bb_wor_err2=-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest_err2/zp_ef_rest)) +(2.5*log10(1+redserrspace2))\n\t\t    kcorrerror_bb_wor=(abs(kcorrrest_bb_wor_err1 - kcorrrest_bb_wor) + abs(kcorrrest_bb_wor_err2 - kcorrrest_bb_wor))/2\n\t\t    kcorrerrfilt_obs = abs((-2.5*log10(flux_obs/zp_ef_err) - (-2.5*log10(flux_rest/zp_ef_rest)))-(-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest))))\n\t\t    kcorrerrfilt_rest = abs((-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest_err)))-(-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest))))\n\t\t    Kcorrerr_bb = abs((-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest)))-(-2.5*log10(flux_obs_err/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest))))\n\t\t    kcorrerr = sqrt((kcorrerror_bb_wor**2 + kcorrerrfilt_obs**2 + kcorrerrfilt_rest**2 + Kcorrerr_bb**2)/4)\n\t\t    \n\t\t    kcorr[ii] = kcorrrest_bb_wor\n\t\t    kcorr_e[ii] = kcorrerr\n\t\t    method[ii] = 'Hybrid obs_spec_BB'\n\t\t    btemp[ii] = bbt\t\t    \n\t\t    split = 1\n\n\t    elif filter1 == 'U' or filter1 == 'u' or filter1 == 'uvw1' or filter1 == 'uvw2' or filter1 == 'uvm2' or filter1 == 'NUV' or filter1 == 'FUV':\n\t\t    print waveobs_min-fil_obs_min,' Angstrom not covered by the observed spectrum in the blue'\n\t\t    kcorr[ii] = 0.0\n\t\t    kcorr_e[ii] = 0.0\n\t\t    method[ii] = 'None'\n\t\t    btemp[ii] = 'None' \n\t\t    anguncov[ii] = waveobs_min-fil_obs_min\n\t\t    uncovside[ii] = 'Blue'\n\t    elif filter1 == 'K':\n\t\t    print fil_obs_max-waveobs_max,' Angstrom not covered by the observed spectrum in the red'\n\t\t    kcorr[ii] = 0.0\n\t\t    kcorr_e[ii] = 0.0\n\t\t    method[ii] = 'None'\n\t\t    btemp[ii] = 'None'\n\t\t    anguncov[ii] = fil_obs_max-waveobs_max\n\t\t    uncovside[ii] = 'Red'\n\n\tif split == 0:\n\t\tif ((waverest_min-fil_rest_min) > 50) or ((fil_rest_max-waverest_max) > 50):\n\t\t\tprint ''\n\t\t\tif (waverest_min-fil_rest_min) > 50:\n\t\t\t\tprint waverest_min-fil_rest_min,' Angstrom not covered by the restframe spectrum in the blue'\n\t\t\t\tanguncov[ii] = waverest_min-fil_rest_min\n\t\t\t\tuncovside[ii] = 'Blue'\n\t\t\telif (fil_rest_max-waverest_max) > 50:\n\t\t\t\tprint fil_rest_max-waverest_max,' Angstrom not covered by the restframe spectrum in the red'\n\t\t\t\tanguncov[ii] = fil_rest_max-waverest_max\n\t\t\t\tuncovside[ii] = 'Red'\n\n\t\t\tprint ''\n\t\t\tBBparams, covar = curve_fit(bbody,wavedezv,fluxdezv,p0=(10000,1E-16))\n\t\t\tT= BBparams[0]\n\t\t\tArea = BBparams[1]\n\t\t\tprint '\\nBlackbody temperature rest spectrum = %.0f +\\- %.0f K\\n' % (T,np.sqrt(covar[0,0]))\n\t\t\tbbt = 'BBrest = %.0f +\\- %.0f K' % (T,np.sqrt(covar[0,0]))\n\t\t\toutputname = \"bbody_sn_dez_fit.dat\" #% T\n\t\t\tfile = open(outputname,\"w\")\n\t\t\tfile.write(\"# Blackbody temperature = %.0f +\\- %.0f K\\n\" % (T,np.sqrt(covar[0,0])))\n\t\t\tw,f = [],[]\n\t\t\tfor wav in range(900,26000):\n\t\t\t\tfile.write(\"%g\\t%g\\n\" % (wav,bbody(wav,T,Area)))\n\t\t\t\tw.append(wav)\n\t\t\t\tf.append(bbody(wav,T,Area))\n\n\t\t\t######### BBody for the error spectra ################################################\n\t\t\tBBparams, covar = curve_fit(bbody,wavedezv_err1,fluxdezv_err1,p0=(10000,1E-16)) #initial guess\n\t\t\tT= BBparams[0]\n\t\t\tArea = BBparams[1]\n\t\t\toutputname = \"bbody_sn_dez_fit_err1.dat\" #% T\n\t\t\tfile = open(outputname,\"w\")\n\t\t\tfile.write(\"# Blackbody temperature = %.0f +\\- %.0f K\\n\" % (T,np.sqrt(covar[0,0])))\n\t\t\tw,f = [],[]\n\t\t\tfor wav in range(900,24005):\n\t\t\t   file.write(\"%g\\t%g\\n\" % (wav,bbody(wav,T,Area)))\n\t\t\t   w.append(wav)\n\t\t\t   f.append(bbody(wav,T,Area))\n\t\t\t\n\t\t\tBBparams, covar = curve_fit(bbody,wavedezv_err2,fluxdezv_err2,p0=(10000,1E-16)) #initial guess\n\t\t\tT= BBparams[0]\n\t\t\tArea = BBparams[1]\n\t\t\toutputname = \"bbody_sn_dez_fit_err2.dat\" #% T\n\t\t\tfile = open(outputname,\"w\")\n\t\t\tfile.write(\"# Blackbody temperature = %.0f +\\- %.0f K\\n\" % (T,np.sqrt(covar[0,0])))\n\t\t\tw,f = [],[]\n\t\t\tfor wav in range(900,24005):\n\t\t\t   file.write(\"%g\\t%g\\n\" % (wav,bbody(wav,T,Area)))\n\t\t\t   w.append(wav)\n\t\t\t   f.append(bbody(wav,T,Area))\n\t\t\t########################################################################################   \n\t\t\tiraf.rspec('bbody_sn_dez_fit.dat','bbody_sn_dez_fit.fits', title='bbodyfit',flux='no',dtype='interp',crval1=900,cdelt1=1)\n\t\t\tiraf.rspec('bbody_sn_dez_fit_err1.dat','bbody_sn_dez_fit_err1.fits', title='bbodyfit',flux='no',dtype='interp',crval1=900,cdelt1=1)\n\t\t\tiraf.rspec('bbody_sn_dez_fit_err2.dat','bbody_sn_dez_fit_err2.fits', title='bbodyfit',flux='no',dtype='interp',crval1=900,cdelt1=1)\n\t\t\tiraf.scombine('bbody_sn_dez_fit.fits,sn_dez.fits,sn_dez.fits,sn_dez.fits', 'bsn_combo_dez.fits',combine='median')\n\t\t\tiraf.scombine('bbody_sn_dez_fit_err1.fits,sn_dez_err1.fits,sn_dez_err1.fits,sn_dez_err1.fits', 'bsn_combo_dez_err1.fits',combine='median')\n\t\t\tiraf.scombine('bbody_sn_dez_fit_err2.fits,sn_dez_err2.fits,sn_dez_err2.fits,sn_dez_err2.fits', 'bsn_combo_dez_err2.fits',combine='median')\n\t\t\tiraf.wspec('bsn_combo_dez.fits','bsn_combo_dez.txt',header='no')\n\t\t\tiraf.wspec('bsn_combo_dez_err1.fits','bsn_combo_dez_err1.txt',header='no')\n\t\t\tiraf.wspec('bsn_combo_dez_err2.fits','bsn_combo_dez_err2.txt',header='no')\n\n\t\t\tprint '#######################################'\n\t\t\tprint ' Since now you are using a rest-frame spectrum based on a combination of SN+Blackbody '\n\t\t\tprint '#######################################'\n\n\t\t\tiraf.wspec(\"sn.fits\",\"sn.txt\", header='no')\n\t\t\tlcf = open('sn.txt','r')\n\t\t\triga = lcf.readlines()\n\t\t\tlcf.close()\n\t\t\twave,flux= [],[]\n\t\t\tfor line in riga:\n\t\t\t    p = line.split()\n\t\t\t    if float(line.split()[0]) >= fil_obs_min and float(line.split()[0]) <= fil_obs_max: #to match the spectrum wavelegnths to those of the filter\n\t\t\t        wave.append(float(p[0]))\n\t\t\t        flux.append(float(p[1]))\n\t\t\t    \n\t\t\twavev = array(wave)\n\t\t\tfluxv = array(flux)\n\t\t\twavesp_min= min(wavev)\n\t\t\twavesp_max= int(max(wavev)) #needed to avoid problems with interp1d\n\t\t\t\n\t\t\t# interpolating the two responses to match the length and sampling coverage\n\t\t\tconf = conv(wavev,fluxv,wavefilterv,transmissionv,wavesp_min,wavesp_max,fil_obs_min,fil_obs_max)\n\t\t\tflux_obs = max(integrate.cumtrapz(conf[0],conf[1])) # using trapezoidal rule to integrate\n\n\t\t\tlcf = open('bsn_combo_dez.txt','r')\n\t\t\triga = lcf.readlines()\n\t\t\tlcf.close()\n\t\t\trwave,rflux= [],[]\n\t\t\tfor line in riga:\n\t\t\t\tp = line.split()\n\t\t\t\tif float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n\t\t\t\t\trwave.append(float(p[0]))\n\t\t\t\t\trflux.append(float(p[1]))\n\t\t\t\t\n\t\t\twave_dezv = array(rwave)\n\t\t\tflux_dezv = array(rflux)\n\t\t\twavesp_dez_min= min(wave_dezv)\n\t\t\twavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n\t\t\t\n\t\t\t# interpolating the two responses in the rest wavelength to match the length and sampling coverage\n\t\t\tconf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n\n\t\t\tflux_rest = max(integrate.cumtrapz(conf[0],conf[1]))\n\t\t\tflux_rest_err = flux_rest * (1+(anguncov[ii]-50)*0.0001)\n\n\t\t\t############ Errors #########################################################################\n\t\t\tlcf = open('bsn_combo_dez_err1.txt','r')\n\t\t\triga = lcf.readlines()\n\t\t\tlcf.close()\n\t\t\trwave,rflux= [],[]\n\t\t\tfor line in riga:\n\t\t\t    p = line.split()\n\t\t\t    if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n\t\t\t        rwave.append(float(p[0]))\n\t\t\t        rflux.append(float(p[1]))\n\t\t\t    \n\t\t\twave_dezv = array(rwave)\n\t\t\tflux_dezv = array(rflux)\n\t\t\twavesp_dez_min= min(wave_dezv)\n\t\t\twavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n\n\t\t\tconf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n\n\t\t\tflux_rest_err1 = max(integrate.cumtrapz(conf[0],conf[1]))\n\n\t\t\tlcf = open('bsn_combo_dez_err2.txt','r')\n\t\t\triga = lcf.readlines()\n\t\t\tlcf.close()\n\t\t\trwave,rflux= [],[]\n\t\t\tfor line in riga:\n\t\t\t    p = line.split()\n\t\t\t    if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n\t\t\t        rwave.append(float(p[0]))\n\t\t\t        rflux.append(float(p[1]))\n\t\t\t    \n\t\t\twave_dezv = array(rwave)\n\t\t\tflux_dezv = array(rflux)\n\t\t\twavesp_dez_min= min(wave_dezv)\n\t\t\twavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n\n\t\t\tconf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n\t\t\tflux_rest_err2 = max(integrate.cumtrapz(conf[0],conf[1]))\n \t\t\t#############################################################################################\n\n\t\t\tkcorrrest_bb_wor=-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest))+logterm\n\t\t\tkcorrrest_bb_wor_err1=-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest_err1/zp_ef_rest))+(2.5*log10(1+redserrspace1))\n\t\t\tkcorrrest_bb_wor_err2=-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest_err2/zp_ef_rest))+(2.5*log10(1+redserrspace2))\n\t\t\tkcorrerror_bb_wor=(abs(kcorrrest_bb_wor_err1 - kcorrrest_bb_wor) + abs(kcorrrest_bb_wor_err2 - kcorrrest_bb_wor))/2\n\t\t\tkcorrerrfilt_obs = abs((-2.5*log10(flux_obs/zp_ef_err) - (-2.5*log10(flux_rest/zp_ef_rest)))-(-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest))))\n\t\t\tkcorrerrfilt_rest = abs((-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest_err)))-(-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest))))\n\t\t\tKcorrerr_bb = abs((-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest)) +(2.5*log10(1+redshift)))-(-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest_err/zp_ef_rest)) +(2.5*log10(1+redshift))))\n\t\t\tkcorrerr = sqrt((kcorrerror_bb_wor**2 + kcorrerrfilt_obs**2 + kcorrerrfilt_rest**2 + Kcorrerr_bb**2)/4)\n\n\t\t\tkcorr[ii] = kcorrrest_bb_wor\n\t\t\tkcorr_e[ii] = kcorrerr\n\t\t\tmethod[ii] = 'Hybrid rest_spec_BB'\n\t\t\tbtemp[ii] = bbt\n\t\telse:\n\t\t\tiraf.wspec(\"sn.fits\",\"sn.txt\", header='no')\n\t\t\tlcf = open('sn.txt','r')\n\t\t\triga = lcf.readlines()\n\t\t\tlcf.close()\n\t\t\twave,flux= [],[]\n\t\t\tfor line in riga:\n\t\t\t    p = line.split()\n\t\t\t    if float(line.split()[0]) >= fil_obs_min and float(line.split()[0]) <= fil_obs_max: #to match the spectrum wavelegnths to those of the filter\n\t\t\t        wave.append(float(p[0]))\n\t\t\t        flux.append(float(p[1]))\n\t\t\t    \n\t\t\twavev = array(wave)\n\t\t\tfluxv = array(flux)\n\t\t\twavesp_min= min(wavev)\n\t\t\twavesp_max= int(max(wavev)) #needed to avoid problems with interp1d\n\t\t\t# interpolating the two responses to match the length and sampling coverage\n\n\t\t\tconf = conv(wavev,fluxv,wavefilterv,transmissionv,wavesp_min,wavesp_max,fil_obs_min,fil_obs_max)\n\n\t\t\t##################################\n\t\t\t### Evaluating the magnitudes\n\t\t\t##################################\n\t\t\tflux_obs = max(integrate.cumtrapz(conf[0],conf[1])) # using trapezoidal rule to integrate\n\t\t\tphot_filtobs_sn = -2.5*log10(flux_obs/zp_ef)\n\n\t\t\tiraf.wspec(\"sn_dez_dered.fits\",\"sn_dez_dered.txt\", header='no')\n\t\t\tlcf = open('sn_dez_dered.txt','r')\n\t\t\triga = lcf.readlines()\n\t\t\tlcf.close()\n\t\t\trwave,rflux= [],[]\n\t\t\tfor line in riga:\n\t\t\t    p = line.split()\n\t\t\t    if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n\t\t\t        rwave.append(float(p[0]))\n\t\t\t        rflux.append(float(p[1]))\n\t\t\t    \n\t\t\twave_dezv = array(rwave)\n\t\t\tflux_dezv = array(rflux)\n\t\t\twavesp_dez_min= min(wave_dezv)\n\t\t\twavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n\t\t\t\n\t\t\t# interpolating the two responses in the rest wavelength to match the length and sampling coverage\n\t\t\tconf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n\t\t\tflux_rest = max(integrate.cumtrapz(conf[0],conf[1]))\n\n\t\t\tphot_filtrest_sn_dez_dered=-2.5*log10(flux_rest/zp_ef_rest)\n \t\t\t#######    Errors  ######################################################################################\n \t\t\tiraf.wspec(\"sn_dez_dered_err1.fits\",\"sn_dez_dered_err1.txt\", header='no')\n \t\t\tlcf = open('sn_dez_dered_err1.txt','r')\n \t\t\triga = lcf.readlines()\n \t\t\tlcf.close()\n \t\t\trwave,rflux= [],[]\n \t\t\tfor line in riga:\n \t\t\t    p = line.split()\n \t\t\t    if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n \t\t\t        rwave.append(float(p[0]))\n \t\t\t        rflux.append(float(p[1]))\n \t\t\t    \n \t\t\twave_dezv = array(rwave)\n \t\t\tflux_dezv = array(rflux)\n \t\t\twavesp_dez_min= min(wave_dezv)\n \t\t\twavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n \t\t\t\n \t\t\t# interpolating the two responses in the rest wavelength to match the length and sampling coverage\n \t\t\tconf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n \t\t\tflux_rest_err1 = max(integrate.cumtrapz(conf[0],conf[1]))\n\t\t\t\n \t\t\tiraf.wspec(\"sn_dez_dered_err2.fits\",\"sn_dez_dered_err2.txt\", header='no')\n \t\t\tlcf = open('sn_dez_dered_err2.txt','r')\n \t\t\triga = lcf.readlines()\n \t\t\tlcf.close()\n \t\t\trwave,rflux= [],[]\n \t\t\tfor line in riga:\n \t\t\t    p = line.split()\n \t\t\t    if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n \t\t\t        rwave.append(float(p[0]))\n \t\t\t        rflux.append(float(p[1]))\n \t\t\t    \n \t\t\twave_dezv = array(rwave)\n \t\t\tflux_dezv = array(rflux)\n \t\t\twavesp_dez_min= min(wave_dezv)\n \t\t\twavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n \t\t\t\n \t\t\t# interpolating the two responses in the rest wavelength to match the length and sampling coverage\n \t\t\tconf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n \t\t\tflux_rest_err2 = max(integrate.cumtrapz(conf[0],conf[1]))\n \t\t\t######################################################################################################\n \t\t\tphot_filtrest_sn_dez_dered_err1=-2.5*log10(flux_rest_err1/zp_ef_rest)\n \t\t\tphot_filtrest_sn_dez_dered_err2=-2.5*log10(flux_rest_err2/zp_ef_rest)\n\n\t\t\tiraf.wspec(\"sn_dez.fits\",\"sn_dez.txt\", header='no')\n\t\t\tlcf = open('sn_dez.txt','r')\n\t\t\triga = lcf.readlines()\n\t\t\tlcf.close()\n\t\t\trwave,rflux= [],[]\n\t\t\tfor line in riga:\n\t\t\t    p = line.split()\n\t\t\t    if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n\t\t\t        rwave.append(float(p[0]))\n\t\t\t        rflux.append(float(p[1]))\n\t\t\t    \n\t\t\twave_dezv = array(rwave)\n\t\t\tflux_dezv = array(rflux)\n\t\t\twavesp_dez_min= min(wave_dezv)\n\t\t\twavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n\t\t\t\n\t\t\t# interpolating the two responses in the rest wavelength to match the length and sampling coverage\n\t\t\tconf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n\t\t\tflux_rest = max(integrate.cumtrapz(conf[0],conf[1]))\n  \n\t\t\tphot_filtrest_sn_dez=-2.5*log10(flux_rest/zp_ef_rest)\n\t\t\t\n\t\t\t##################### Errors ######################################################################\n\t\t\tiraf.wspec(\"sn_dez_err1.fits\",\"sn_dez_err1.txt\", header='no')\n\t\t\tlcf = open('sn_dez_err1.txt','r')\n\t\t\triga = lcf.readlines()\n\t\t\tlcf.close()\n\t\t\trwave,rflux= [],[]\n\t\t\tfor line in riga:\n\t\t\t    p = line.split()\n\t\t\t    if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n\t\t\t        rwave.append(float(p[0]))\n\t\t\t        rflux.append(float(p[1]))\n\t\t\t    \n\t\t\twave_dezv = array(rwave)\n\t\t\tflux_dezv = array(rflux)\n\t\t\twavesp_dez_min= min(wave_dezv)\n\t\t\twavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n\t\t\t\n\t\t\t# interpolating the two responses in the rest wavelength to match the length and sampling coverage\n\t\t\tconf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n\t\t\tflux_rest_err1 = max(integrate.cumtrapz(conf[0],conf[1]))\n\t\t\t\n\t\t\tiraf.wspec(\"sn_dez_err2.fits\",\"sn_dez_err2.txt\", header='no')\n\t\t\tlcf = open('sn_dez_err2.txt','r')\n\t\t\triga = lcf.readlines()\n\t\t\tlcf.close()\n\t\t\trwave,rflux= [],[]\n\t\t\tfor line in riga:\n\t\t\t    p = line.split()\n\t\t\t    if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n\t\t\t        rwave.append(float(p[0]))\n\t\t\t        rflux.append(float(p[1]))\n\t\t\t    \n\t\t\twave_dezv = array(rwave)\n\t\t\tflux_dezv = array(rflux)\n\t\t\twavesp_dez_min= min(wave_dezv)\n\t\t\twavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n\t\t\t\n\t\t\t# interpolating the two responses in the rest wavelength to match the length and sampling coverage\n\t\t\tconf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n\t\t\tflux_rest_err2 = max(integrate.cumtrapz(conf[0],conf[1]))\n\t\t\t####################################################################################################\n\t\t\tphot_filtrest_sn_dez_err1=-2.5*log10(flux_rest_err1/zp_ef_rest)\n\t\t\tphot_filtrest_sn_dez_err2=-2.5*log10(flux_rest_err2/zp_ef_rest)\n\n\t\t\t##################################\n\t\t\t### K-correction evaluation\n\t\t\t##################################\n\t\t\t\n\t\t\tkcorrrest_wr=(float(phot_filtobs_sn)-float(phot_filtrest_sn_dez_dered))+logterm\n\t\t\tkcorrrest_wr_err1=(float(phot_filtobs_sn)-float(phot_filtrest_sn_dez_dered_err1))+(2.5*log10(1+redserrspace1))\n\t\t\tkcorrrest_wr_err2=(float(phot_filtobs_sn)-float(phot_filtrest_sn_dez_dered_err2))+(2.5*log10(1+redserrspace2))\n\t\t\tkcorrerror_wr=(abs(kcorrrest_wr_err1 - kcorrrest_wr) + abs(kcorrrest_wr_err2 - kcorrrest_wr))/2\n\n\t\t\tkcorrrest_wor=(float(phot_filtobs_sn)-float(phot_filtrest_sn_dez))+logterm\n\t\t\tkcorrrest_wor_err1=(float(phot_filtobs_sn)-float(phot_filtrest_sn_dez_err1))+(2.5*log10(1+redserrspace1))\n\t\t\tkcorrrest_wor_err2=(float(phot_filtobs_sn)-float(phot_filtrest_sn_dez_err2))+(2.5*log10(1+redserrspace2))\n\t\t\tkcorrerror_wor=(abs(kcorrrest_wor_err1 - kcorrrest_wor) + abs(kcorrrest_wor_err2 - kcorrrest_wor))/2\n\t\t\t\n\t\t\tkcorrerrfilt_obs = abs((-2.5*log10(flux_obs/zp_ef_err) - (-2.5*log10(flux_rest/zp_ef_rest)))-(-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest))))\n\t\t\tkcorrerrfilt_rest = abs((-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest_err)))-(-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest))))\n\t\t\t\n\t\t\tkcorrerr_wor = sqrt((kcorrerror_wor**2 + kcorrerrfilt_obs**2 + kcorrerrfilt_rest**2)/3)\n\t\t\tkcorrerr_wr = sqrt((kcorrerror_wr**2 + kcorrerrfilt_obs**2 + kcorrerrfilt_rest**2)/3)\n\n\t\t\tkcorr[ii] = kcorrrest_wr\n\t\t\tkcorr_e[ii] = kcorrerr_wr\n\t\t\tmethod[ii] = 'specTOspec'\n\t\t\tbtemp[ii] = 'None'\n\t\t\tanguncov[ii] = 0.0\n\t\t\tuncovside[ii] = 'None'\n\n\n\t# cleaning process (unnecessary)\n\tos.system('rm -rf sn.txt')\n\tos.system('rm -rf sn.fits')\n\tos.system('rm -rf sn_xbbody.txt')\n\tos.system('rm -rf sn_dez_xbbody.txt')\n\tos.system('rm -rf sn_dez_xbbody_err1.txt')\n\tos.system('rm -rf sn_dez_xbbody_err2.txt')\n\tos.system('rm -rf bbody_sn_dez_fit.dat')\n\tos.system('rm -rf bbody_sn_dez_fit_err1.dat')\n\tos.system('rm -rf bbody_sn_dez_fit_err2.dat')\n\tos.system('rm -rf bbody_sn_dez_fit.fits')\n\tos.system('rm -rf bbody_sn_dez_fit_err1.fits')\n\tos.system('rm -rf bbody_sn_dez_fit_err2.fits')\n\tos.system('rm -rf bbody_sn_fit.fits')\n\tos.system('rm -rf bbody_sn_fit.dat')\n\tos.system('rm -rf sn_dez.txt')\n\tos.system('rm -rf sn_dez_err1.txt')\n\tos.system('rm -rf sn_dez_err2.txt')\n\tos.system('rm -rf sn_dez.fits')\n\tos.system('rm -rf sn_dez_err1.fits')\n\tos.system('rm -rf sn_dez_err2.fits')\n\tos.system('rm -rf sn_dez_dered.fits')\n\tos.system('rm -rf sn_dez_dered_err1.fits')\n\tos.system('rm -rf sn_dez_dered_err2.fits')\n\tos.system('rm -rf sn_dez_dered.txt')\n\tos.system('rm -rf sn_dez_dered_err1.txt')\n\tos.system('rm -rf sn_dez_dered_err2.txt')\n\tos.system('rm -rf sn_galdered_dez.fits')\n\tos.system('rm -rf sn_galdered_dez_err1.fits')\n\tos.system('rm -rf sn_galdered_dez_err2.fits')\n\tos.system('rm -rf sn_galdered.fits')\n\tos.system('rm -rf bsn_combo_dez.fits')\n\tos.system('rm -rf bsn_combo_dez_err1.fits')\n\tos.system('rm -rf bsn_combo_dez_err2.fits')\n\tos.system('rm -rf bsn_combo_dez.txt')\n\tos.system('rm -rf bsn_combo_dez_err1.txt')\n\tos.system('rm -rf bsn_combo_dez_err2.txt')\n\tos.system('rm -rf bsn_combo.fits')\n\tos.system('rm -rf bsn_combo.txt')\n\tsleep(_sleepc) #to avoid missing files and correction due to a combo of two different spectra (a.k.a. the code arrives at the right step before the system remove the file)\n\t##########################\n\t### Adding values to the txt file\n\t#########################\n\tredlist[ii] = redshift\n\tfilekc.write(snname)\n\tfilekc.write(\"\\t\")\n\tfilekc.write(\"%s+/-%s\" % (redshift,_redshifterr))\n\tfilekc.write(\"\\t\\t\")\n\tfilekc.write(filter1)\n\tfilekc.write(\"\\t\\t\")\n\tfilekc.write(filter2)\n\tfilekc.write(\"\\t\\t\")\n\tfilekc.write(\"%0.3f\" % (kcorr[ii]))\n\tfilekc.write(\"\\t\\t\")\n\tfilekc.write(\"+/-%0.3f\" % (kcorr_e[ii]))\n\tfilekc.write(\"\\t\\t\")\n\tfilekc.write(method[ii])\n\tfilekc.write(\"\\t\\t\")\n\tfilekc.write(btemp[ii])\n\tfilekc.write(\"\\t\\t\")\n\tfilekc.write(\"%s\" % (anguncov[ii]))\n\tfilekc.write(\"\\t\")\n\tfilekc.write(uncovside[ii])\n\tfilekc.write(\"\\n\")\n\t#ax = subplot(111)\n\tif questionplot == 'yes':\n\t\tax = axes([0.1, 0.1, 0.65, 0.82])\n\t\tplot(9999,9999,color='b',marker='o',markeredgecolor='k',ls='None')\n\t\tplot(9999,9999,color='g',marker='d',markeredgecolor='k',ls='None')\n\t\tplot(9999,9999,color='r',marker='s',markeredgecolor='k',ls='None')\n\t\treds,redo,redr,kcors,kcoro,kcor1 = [],[],[],[],[],[]\n\t\tif method[ii] == 'specTOspec':\n\t\t\treds.append(redshift)\n\t\t\tkcors.append(kcorr[ii])\n\t\t\tplot(reds,kcors,'bo',ms=12)\n\t\tif method[ii] == 'Hybrid rest_spec_BB':\t\t\n\t\t\tredr.append(redshift)\n\t\t\tkcor1.append(kcorr[ii])\n\t\t\tplot(redr,kcor1,'gd',ms=12)\n\t\tif method[ii] == 'Hybrid obs_spec_BB':\n\t\t\tredo.append(redshift)\n\t\t\tkcoro.append(kcorr[ii])\n\t\t\tplot(redo,kcoro,'rs',ms=12)\n\tii = ii + 1\n\nthen = time.time()\ntime = then -now\n################\n### plotting commands\n##################\nif questionplot == 'yes':\n\txl = [float(min(redlist))-0.07,float(max(redlist))+0.07]\n\tyl = [min(kcorr)-0.3,max(kcorr)+0.3]\n\tlegend(('specTOspec', 'Hybrid rest specBB', 'Hybrid obs specBB'), numpoints=1,bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.)\n\tltext = gca().get_legend().get_texts()\n\tsetp(ltext[0], fontsize = 14, color = 'b')\n\tsetp(ltext[1], fontsize = 14, color = 'g')\n\tsetp(ltext[2], fontsize = 14, color = 'r')\n\txlim(xl[0],xl[1])\n\tylim(yl[0],yl[1])\n\ttitle('From various observed filters to various rest filters')\n\txlabel('Redshift',size=18)\n\tylabel('K-correction',size=18)\n\tax.minorticks_on()\n\tshow()\n####################\n##### writing legend on the file\n####################\nfilekc.write(\"\\n# ----------------------------------------------------------------------------------\\n\")\nfilekc.write(\"# Legend for SNAKE mode:\\n\")\nfilekc.write(\"# specTOspec        \\t--> K-correction computed with original spectrum in observed  \\n#\\t\\t\\t\\t\\t\\tand rest frame\\n\")\nfilekc.write(\"# Hybrid rest_spec_BB\\t--> K-correction computed with original spectrum in observed  \\n#\\t\\t\\t\\t\\t\\tframe and SN+Bbody hybrid in rest frame\\n\")\nfilekc.write(\"# Hybrid obs_spec_BB \\t--> K-correction computed with SN+bbody spectrum in observed  \\n#\\t\\t\\t\\t\\t\\tand rest frame\\n\")\nfilekc.write(\"# ----------------------------------------------------------------------------------\\n\")\n\nsltime = _sleepc*len(snlist)\nprint '######################################################################'\nprint ''\nprint ' Evaluation done in %.0is, of which %.0is to take a nap to let rest your Random Access Memory (RAM) ' % (time,sltime)\t\nprint ''\nprint ' \\033[46mList of K-corrections\\033[0m ' , kcorr\nprint ' \\033[44mVersion used\\033[0m ' , method\nprint ''\nprint ' A text file has been created ===> Kcorrection_%.0i_%.0i.txt ' % (Tnowd,Tnow)\t\n\n\n", "meta": {"hexsha": "87a058295eb404bb6659803f74b1bfc81f0e0ee8", "size": 50093, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/s3/SNAKELOOP.py", "max_stars_repo_name": "cinserra/S3", "max_stars_repo_head_hexsha": "eefc12265bd7824204dc5cbbd648e3ff8b291273", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-07-24T17:35:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-05T15:40:45.000Z", "max_issues_repo_path": "src/s3/SNAKELOOP.py", "max_issues_repo_name": "cinserra/S3", "max_issues_repo_head_hexsha": "eefc12265bd7824204dc5cbbd648e3ff8b291273", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-24T10:46:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-24T10:46:26.000Z", "max_forks_repo_path": "src/s3/SNAKELOOP.py", "max_forks_repo_name": "cinserra/S3", "max_forks_repo_head_hexsha": "eefc12265bd7824204dc5cbbd648e3ff8b291273", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-12T13:03:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-12T13:03:05.000Z", "avg_line_length": 44.4086879433, "max_line_length": 227, "alphanum_fraction": 0.6302078135, "include": true, "reason": "from numpy,from scipy", "num_tokens": 15304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1960001022328932}}
{"text": "\"\"\"\nTools for aperture photometry with non native bg/error methods\n\nThis function serves to ease the computation of photometric magnitudes\nand errors using PhotUtils by replicating DAOPHOT's photometry and\nerror methods.  The formula for DAOPHOT's error is:\n\nerr = sqrt (Poisson_noise / epadu + area * stdev**2 + area**2 * stdev**2 / nsky)\n\nWhich gives a magnitude error:\n\nmag_err = 1.0857 * err / flux\n\nWhere epadu is electrons per ADU (gain), area is the photometric\naperture area, stdev is the uncertainty in the sky measurement\nand nsky is the sky annulus area.  To get the uncertainty in the sky\nwe must use a custom background tool, which also enables computation of\nthe mean and median of the sky as well (more robust statistics).\nAll the stats are sigma clipped.  These are calculated by the\nfunctions in aperture_stats_tbl.\n\n.. note::\n    Currently, the background computations will fully include a pixel that has ANY overlap with the background aperture\n    (the annulus). This is to simplify the computation of the median, as a weighted median is nontrivial, and slower.\n    Copied from https://grit.stsci.edu/HLA/software/blob/master/HLApipeline/HLApipe/scripts/photometry_tools.py\nAuthors\n-------\n    - Varun Bajaj, January 2018\n\nUse\n---\n\n::\n\n    from photometry_tools import iraf_style_photometry\n    phot_aps = CircularAperture((sources['xcentroid'], sources['ycentroid']),r=10.)\n    bg_aps = CircularAnnulus((sources['xcentroid'], sources['ycentroid']), r_in=13., r_out=15.)\n\nSimplest call:\n\n::\n\n    photometry_tbl = iraf_style_photometry(phot_aps, bg_aps, data)\n\nPass in pixelwise error and set background to mean\n\n::\n\n    photometry_tbl = iraf_style_photometry(phot_aps, bg_aps, data, error_array=data_err, bg_method='mean')\n\nCan also set the gain (if image units are DN)\n\n::\n\n    photometry_tbl = iraf_style_photometry(phot_aps, bg_aps, data, epadu=2.5)\n\nClasses and Functions\n---------------------\n\"\"\"\nimport numpy as np\nfrom astropy.table import Table\nfrom drizzlepac.hlautils.background_median import aperture_stats_tbl\nfrom photutils import aperture_photometry\n\n\ndef iraf_style_photometry(phot_apertures, bg_apertures, data, photflam, photplam, error_array=None,\n                          bg_method='mode', epadu=1.0):\n    \"\"\"\n    Computes photometry with PhotUtils apertures, with IRAF formulae\n\n    Parameters\n    ----------\n    phot_apertures : photutils PixelAperture object (or subclass)\n        The PhotUtils apertures object to compute the photometry. i.e. the object returned via CirularAperture.\n\n    bg_apertures : photutils PixelAperture object (or subclass)\n        The phoutils aperture object to measure the background in. i.e. the object returned via CircularAnnulus.\n\n    data : array\n        The data for the image to be measured.\n\n    photflam : float\n        inverse sensitivity, in ergs/cm2/angstrom/electron\n\n    photplam : float\n        Pivot wavelength, in angstroms\n\n    error_array : array\n        (Optional) The array of pixelwise error of the data.  If none, the Poisson noise term in the error computation\n        will just be the square root of the flux/epadu. If not none, the aperture_sum_err column output by\n        aperture_photometry (divided by epadu) will be used as the Poisson noise term.\n\n    bg_method: string\n        {'mean', 'median', 'mode'}, optional. The statistic used to calculate the background. All measurements are\n        sigma clipped. Default value is 'mode'. NOTE: From DAOPHOT, mode = 3 * median - 2 * mean.\n\n    epadu : float\n        (optional) Gain in electrons per adu (only use if image units aren't e-). Default value is 1.0\n\n    Returns\n    -------\n        An astropy Table with columns as follows:\n        X-Center Y-Center RA DEC ID MagAp1 MagErrAp1 MagAp2 MagErrAp2 MSkyAp2 StdevAp2 FluxAp2 CI Flags\n    \"\"\"\n    if bg_method not in ['mean', 'median', 'mode']:\n        raise ValueError('Invalid background method, choose either \\\n                          mean, median, or mode')\n    phot = aperture_photometry(data, phot_apertures, error=error_array)\n    bg_phot = aperture_stats_tbl(data, bg_apertures, sigma_clip=True)\n    names = ['X-Center', 'Y-Center', 'ID']\n    x, y = phot_apertures[0].positions.T\n    final_stacked = np.stack([x, y, phot[\"id\"].data], axis=1)\n    # n_aper = 0\n    name_list = 'Flux', 'FluxErr', 'Mag', 'MagErr'\n    for aper_string  in ['Ap1', 'Ap2']:\n        for col_name in name_list:\n            names.append(\"{}{}\".format(col_name,aper_string))\n\n    # for item in list(phot.keys()):\n    #     if item.startswith(\"aperture_sum_\") and not item.startswith(\"aperture_sum_err_\"):\n    #         aper_size_arcsec = phot_apertures[n_aper].r * platescale\n    #         for name in name_list:\n    #             names.append(\"{}_{:.2f}\".format(name, aper_size_arcsec))\n    #         n_aper += 1\n    for aperCtr in range(0, 2):\n        ap_area = phot_apertures[aperCtr].area\n        bg_method_name = 'aperture_{}'.format(bg_method)\n\n        # NOTE background subtraction below commented out 8/14/19\n        flux = phot['aperture_sum_{}'.format(aperCtr)]  # - bg_phot[bg_method_name] * ap_area\n\n        # Need to use variance of the sources\n        # for Poisson noise term in error computation.\n        #\n        # This means error needs to be squared.\n        # If no error_array error = flux ** .5\n\n        if error_array is not None:\n            flux_error = compute_phot_error(phot['aperture_sum_err_{}'.format(aperCtr)] ** 2.0, bg_phot, bg_method,\n                                            ap_area, epadu)\n        else:\n            flux_error = compute_phot_error(flux, bg_phot, bg_method, ap_area, epadu)\n\n        mag = convert_flux_to_abmag(flux, photflam, photplam)\n\n        # NOTE: Magnitude error calculation comes from computing d(ABMAG)/d(flux).\n        # See https://iraf.net/forum/viewtopic.php?showtopic=83932 for details.\n        mag_err = 1.0857 * flux_error / flux\n\n        # Build the final data table\n        stacked = np.stack([flux, flux_error, mag, mag_err], axis=1)\n        final_stacked = np.concatenate([final_stacked, stacked], axis=1)\n\n    # Build final output table\n    final_tbl = Table(data=final_stacked, names=names,\n                      dtype=[np.float64, np.float64, np.int64, np.float64, np.float64, np.float64, np.float64,\n                             np.float64, np.float64, np.float64, np.float64])\n\n    # add sky and std dev columns from background calculation subroutine\n    final_tbl.add_column(bg_phot[bg_method_name])\n    final_tbl.rename_column(bg_method_name, 'MSkyAp2')\n    final_tbl.add_column(bg_phot['aperture_std'])\n    final_tbl.rename_column('aperture_std', 'StdevAp2')\n\n    return final_tbl\n\n\ndef compute_phot_error(flux_variance, bg_phot, bg_method, ap_area, epadu=1.0):\n    \"\"\"Computes the flux errors using the DAOPHOT style computation\n\n    Parameters\n    ----------\n    flux_variance : array\n        flux values\n\n    bg_phot : array\n        background brightness values.\n\n    bg_method : string\n        background method\n\n    ap_area : array\n        the area of the aperture in square pixels\n\n    epadu : float\n        (optional) Gain in electrons per adu (only use if image units aren't e-). Default value is 1.0\n\n    Returns\n    -------\n    flux_error : array\n        an array of flux errors\n    \"\"\"\n\n    bg_variance_terms = (ap_area * bg_phot['aperture_std'] ** 2.) * (1. + ap_area/bg_phot['aperture_area'])\n    variance = flux_variance / epadu + bg_variance_terms\n    flux_error = variance ** .5\n    return flux_error\n\n\ndef convert_flux_to_abmag(in_flux, photflam, photplam):\n    \"\"\"converts flux (in units of electrons/sec) to ABMAG\n\n    Parameters\n    ----------\n    in_flux : astropy.table.column.Column object\n        flux values to convert to ABMAG, in electrons/second\n\n    photflam : float\n        inverse sensitivity, in ergs/cm2/angstrom/electron\n\n    photplam : float\n        pivot wavelength, in angstroms\n\n    Returns\n    -------\n    abmag : astropy.table.column.Column object\n        input flux values converted to ABMAG\n    \"\"\"\n\n    # convert flux from units of electrons/second to ergs/cm2/angstrom/second\n    f_lambda = in_flux * photflam\n\n    # Convert f_lambda to STMAG\n    stmag = -2.5 * np.log10(f_lambda) - 21.10\n\n    # Convert STMAG to ABMAG\n    abmag =  stmag - 5.0 * np.log10(photplam) + 18.6921\n\n    return abmag", "meta": {"hexsha": "40c945ee0442611df342eb9c85d747bc5936291e", "size": 8306, "ext": "py", "lang": "Python", "max_stars_repo_path": "drizzlepac/hlautils/photometry_tools.py", "max_stars_repo_name": "srodney/drizzlepac", "max_stars_repo_head_hexsha": "c554523331a6204ce113d4317b7286ad39094f74", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-02-10T16:15:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T20:08:03.000Z", "max_issues_repo_path": "drizzlepac/hlautils/photometry_tools.py", "max_issues_repo_name": "srodney/drizzlepac", "max_issues_repo_head_hexsha": "c554523331a6204ce113d4317b7286ad39094f74", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "drizzlepac/hlautils/photometry_tools.py", "max_forks_repo_name": "srodney/drizzlepac", "max_forks_repo_head_hexsha": "c554523331a6204ce113d4317b7286ad39094f74", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-02T18:08:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-02T18:08:39.000Z", "avg_line_length": 36.2707423581, "max_line_length": 119, "alphanum_fraction": 0.6797495786, "include": true, "reason": "import numpy,from astropy", "num_tokens": 2180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.34864512179822543, "lm_q1q2_score": 0.19600009973830929}}
{"text": "# Copyright (c) Facebook, Inc. and its affiliates.\n\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n\n\n\"\"\"Calculates the Frechet Inception Distance (FID) to evalulate GANs\n\nThe FID metric calculates the distance between two distributions of images.\nTypically, we have summary statistics (mean & covariance matrix) of one\nof these distributions, while the 2nd distribution is given by a GAN.\n\nWhen run as a stand-alone program, it compares the distribution of\nimages that are stored as PNG/JPEG at a specified location with a\ndistribution given by summary statistics (in pickle format).\n\nThe FID is calculated by assuming that X_1 and X_2 are the activations of\nthe pool_3 layer of the inception net for generated samples and real world\nsamples respectively.\n\nSee --help to see further details.\n\nCode apapted from https://github.com/bioinf-jku/TTUR to use PyTorch instead\nof Tensorflow\n\nCopyright 2018 Institute of Bioinformatics, JKU Linz\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n   http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport os\nimport cv2\nimport json\nimport pathlib\nfrom argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\nimport torchvision\n\nimport numpy as np\nimport torch\nfrom scipy import linalg\nfrom torch.nn.functional import adaptive_avg_pool2d\nimport torch.nn.functional as F\n\nfrom PIL import Image\n\ntry:\n    from tqdm import tqdm\nexcept ImportError:\n    # If not tqdm is not available, provide a mock version of it\n    def tqdm(x): return x\n\nfrom inception import InceptionV3\n\nparser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)\nparser.add_argument('path', type=str, nargs=2,\n                    help=('Path to the generated images or '\n                          'to .npz statistic files'))\nparser.add_argument('--batch-size', type=int, default=50,\n                    help='Batch size to use')\nparser.add_argument('--dims', type=int, default=2048,\n                    choices=list(InceptionV3.BLOCK_INDEX_BY_DIM),\n                    help=('Dimensionality of Inception features to use. '\n                          'By default, uses pool3 features'))\nparser.add_argument('-c', '--gpu', default='', type=str,\n                    help='GPU to use (leave blank for CPU only)')\nparser.add_argument('--name', default='birds', type=str,\n                    help='which dataset to be evluated', choices=['birds', 'creatures'])\n\n\nwith open('../data/id_to_class.json', 'r') as fp:\n    ID2CLASS = json.load(fp)\n    ID2CLASS ={int(k): v for k, v in ID2CLASS.items()}\n\nB_SET = ['bird', 'duck', 'flamingo', 'parrot']\nC_SET = ['ant', 'bear', 'bee', 'bird', 'butterfly', 'camel', 'cat', 'cow', 'crab', 'crocodile', 'dog', 'dolphin', 'duck', \n        'elephant', 'fish', 'flamingo', 'frog', 'giraffe', 'hedgehog', 'horse', 'kangaroo', 'lion', 'lobster', 'monkey', 'mosquito', \n        'mouse', 'octopus', 'owl', 'panda', 'parrot', 'penguin', 'pig', 'rabbit', 'raccoon', 'rhinoceros', 'scorpion', 'sea_turtle', \n        'shark', 'sheep', 'snail', 'snake', 'spider', 'squirrel', 'swan', 'tiger', 'whale', 'zebra']\n\ndef imread(filename):\n    \"\"\"\n    Loads an image file into a (height, width, 3) uint8 ndarray.\n    \"\"\"\n    return np.asarray(Image.open(filename), dtype=np.uint8)\n\n\ndef resize(sketch):\n    x_nonzero, y_nonzero = np.where(sketch>0)\n    try:\n        coord_min = min(x_nonzero.min(), y_nonzero.min())\n        coord_max = max(x_nonzero.max(), y_nonzero.max())\n        sketch_new = np.zeros([64, 64])\n        sketch_cropped = cv2.resize(sketch[coord_min:coord_max, coord_min:coord_max], (60, 60))\n        sketch_new[2:-2, 2:-2] = sketch_cropped\n    except:\n        sketch_new = sketch\n    return sketch_new\n\ndef resize_batch(sketches):\n    return np.array([resize(sketch) for sketch in sketches])\n\ndef get_acts_and_preds(files, model, batch_size=50, dims=2048,\n                    cuda=False, verbose=False, name='birds'):\n    \"\"\"Calculates the activations of the pool_3 layer for all images.\n\n    Params:\n    -- files       : List of image files paths\n    -- model       : Instance of inception model\n    -- batch_size  : Batch size of images for the model to process at once.\n                     Make sure that the number of samples is a multiple of\n                     the batch size, otherwise some samples are ignored. This\n                     behavior is retained to match the original FID score\n                     implementation.\n    -- dims        : Dimensionality of features returned by Inception\n    -- cuda        : If set to True, use GPU\n    -- verbose     : If set to True and parameter out_step is given, the number\n                     of calculated batches is reported.\n    -- name        : The name of the dataset: for birds we calculate CS only and for creatures we also calculate SDS.\n    \"\"\"\n    if name == 'birds':\n        target_set = B_SET\n    elif name == 'creatures':\n        target_set = C_SET\n\n    model.eval()\n\n    if batch_size > len(files):\n        print(('Warning: batch size is bigger than the data size. '\n               'Setting batch size to data size'))\n        batch_size = len(files)\n\n    pred_arr = np.empty((len(files), dims))\n    preds_final_arr = {}\n    logits_arr = torch.zeros(345).cuda()\n\n    for i in tqdm(range(0, len(files), batch_size)):\n        if verbose:\n            print('\\rPropagating batch %d/%d' % (i + 1, n_batches),\n                  end='', flush=True)\n        start = i\n        end = i + batch_size\n\n        images = np.array([imread(str(f)).astype(np.float32) for f in files[start:end]])\n        images = images/255.\n        images = 1-images\n        images[images<0.1] = 0\n\n        # Reshape to (n_images, 3, height, width)\n        if len(images.shape) == 4:\n            images = images.transpose((0, 3, 1, 2))\n        elif len(images.shape) == 3:\n            images = np.expand_dims(images, 1)\n\n        batch = torch.from_numpy(images).type(torch.FloatTensor)\n        if cuda:\n            batch = batch.cuda()\n\n        batch = F.interpolate(batch, size=(299, 299), mode='bilinear', align_corners=False)\n\n        # store the model predictions\n        logits = model.inception(batch)\n        _, final_preds = torch.max(logits, 1)\n        logits = F.softmax(logits, 1)\n        for logit, final_pred in zip(logits, final_preds):\n            logits_arr += logit\n            pred_class = ID2CLASS[final_pred.item()]\n            if pred_class in preds_final_arr:\n                preds_final_arr[pred_class] += 1\n            else:\n                preds_final_arr[pred_class] = 1\n\n        \n        pred = model(batch)[0]        \n\n        # If model output is not scalar, apply global spatial average pooling.\n        # This happens if you choose a dimensionality not equal 2048.\n        if pred.size(2) != 1 or pred.size(3) != 1:\n            pred = adaptive_avg_pool2d(pred, output_size=(1, 1))\n\n        pred_arr[start:end] = pred.cpu().data.numpy().reshape(pred.size(0), -1)\n\n    # calculate CS and SDS\n    characteristic_count = 0.\n    total_count = 0.\n    for class_name in preds_final_arr:\n        total_count += preds_final_arr[class_name]\n        if class_name not in target_set:\n            continue\n        characteristic_count += preds_final_arr[class_name]\n    CS = characteristic_count/total_count\n    probs_all = logits_arr / total_count\n    # import ipdb;ipdb.set_trace()\n    if name == 'creatures':\n        C_prob = sum([probs_all[cl_id].item() for cl_id in range(345) if ID2CLASS[cl_id] in C_SET])\n        CCS = sum([-probs_all[cl_id].item()*np.log(probs_all[cl_id].item()/C_prob) for cl_id in range(345) if ID2CLASS[cl_id] in C_SET])\n    else:\n        CCS = 0.\n\n    if verbose:\n        print(' done')\n    return pred_arr, CS, CCS\n\n\ndef calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):\n    \"\"\"Numpy implementation of the Frechet Distance.\n    The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)\n    and X_2 ~ N(mu_2, C_2) is\n            d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).\n\n    Stable version by Dougal J. Sutherland.\n\n    Params:\n    -- mu1   : Numpy array containing the activations of a layer of the\n               inception net (like returned by the function 'get_predictions')\n               for generated samples.\n    -- mu2   : The sample mean over activations, precalculated on an\n               representative data set.\n    -- sigma1: The covariance matrix over activations for generated samples.\n    -- sigma2: The covariance matrix over activations, precalculated on an\n               representative data set.\n\n    Returns:\n    --   : The Frechet Distance.\n    \"\"\"\n\n    mu1 = np.atleast_1d(mu1)\n    mu2 = np.atleast_1d(mu2)\n\n    sigma1 = np.atleast_2d(sigma1)\n    sigma2 = np.atleast_2d(sigma2)\n\n    assert mu1.shape == mu2.shape, \\\n        'Training and test mean vectors have different lengths'\n    assert sigma1.shape == sigma2.shape, \\\n        'Training and test covariances have different dimensions'\n\n    diff = mu1 - mu2\n\n    # Product might be almost singular\n    covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)\n    if not np.isfinite(covmean).all():\n        msg = ('fid calculation produces singular product; '\n               'adding %s to diagonal of cov estimates') % eps\n        print(msg)\n        offset = np.eye(sigma1.shape[0]) * eps\n        covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))\n\n    # Numerical error might give slight imaginary component\n    if np.iscomplexobj(covmean):\n        if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):\n            m = np.max(np.abs(covmean.imag))\n            raise ValueError('Imaginary component {}'.format(m))\n        covmean = covmean.real\n\n    tr_covmean = np.trace(covmean)\n\n    return (diff.dot(diff) + np.trace(sigma1) +\n            np.trace(sigma2) - 2 * tr_covmean)\n\n\ndef calculate_acts_and_preds(files, model, batch_size=50,\n                                    dims=2048, cuda=False, verbose=False, name='birds'):\n    \"\"\"Calculation of the statistics used by the FID and diversity, CS, SDS.\n    Params:\n    -- files       : List of image files paths\n    -- model       : Instance of inception model\n    -- batch_size  : The images numpy array is split into batches with\n                     batch size batch_size. A reasonable batch size\n                     depends on the hardware.\n    -- dims        : Dimensionality of features returned by Inception\n    -- cuda        : If set to True, use GPU\n    -- verbose     : If set to True and parameter out_step is given, the\n                     number of calculated batches is reported.\n    Returns:\n    -- mu    : The mean over samples of the activations of the pool_3 layer of\n               the inception model.\n    -- sigma : The covariance matrix of the activations of the pool_3 layer of\n               the inception model.\n    -- diversity : average pairwise distances between samples.\n    -- CS : characteristic score.\n    -- SDS : semantic diversity score.\n    \"\"\"\n    assert name in ['birds', 'creatures']\n    act, CS, SDS = get_acts_and_preds(files, model, batch_size, dims, cuda, verbose, name)\n    mu = np.mean(act, axis=0)\n    sigma = np.cov(act, rowvar=False)\n    diversity = cal_diversity(act)\n    # import ipdb;ipdb.set_trace()\n    return mu, sigma, diversity, CS, SDS\n\n\ndef cal_diversity(act):\n    n_sample = min(act.shape[0], 1000)\n    act = act[:n_sample]\n    n_part = n_sample*(n_sample-1)/2\n    score = 0.\n    for i in range(n_sample):\n        for j in range(i+1, n_sample):\n            score += np.sqrt(np.sum((act[i]-act[j])**2))\n    return score/n_part\n\n\ndef _compute_statistics_of_path(path, model, batch_size, dims, cuda, name):\n    if path.endswith('.npz'):\n        f = np.load(path)\n        m, s = f['mu'][:], f['sigma'][:]\n        f.close()\n    else:\n        path = pathlib.Path(path)\n        files = list(path.glob('*.jpg')) + list(path.glob('*.png'))\n        m, s, diversity, CS, SDS = calculate_acts_and_preds(files, model, batch_size,\n                                               dims, cuda, False, name)\n    return m, s, diversity, CS, SDS\n\n\ndef calculate_scores_given_paths(paths, batch_size, cuda, dims, name):\n    \"\"\"Calculates the FID of two paths\"\"\"\n    for p in paths:\n        if not os.path.exists(p):\n            raise RuntimeError('Invalid path: %s' % p)\n\n    block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims]\n\n    model = InceptionV3([block_idx], normalize_input=False, use_fid_inception=False)\n    if cuda:\n        model.cuda()\n\n    m1, s1, d1, CS1, SDS1 = _compute_statistics_of_path(paths[0], model, batch_size,\n                                         dims, cuda, name)\n    m2, s2, d2, CS2, SDS2 = _compute_statistics_of_path(paths[1], model, batch_size,\n                                         dims, cuda, name)\n    # import ipdb;ipdb.set_trace()\n    fid_value = calculate_frechet_distance(m1, s1, m2, s2)\n\n    return fid_value, d1, d2, CS1, CS2, SDS1, SDS2\n\n\nif __name__ == '__main__':\n    args = parser.parse_args()\n    os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu\n\n    fid_value, d1, d2, CS1, CS2, SDS1, SDS2 = calculate_scores_given_paths(args.path,\n                                          args.batch_size,\n                                          args.gpu != '',\n                                          args.dims,\n                                          args.name)\n    print('FID: ', fid_value)\n    if args.name == 'birds':\n        print('Diversity 1: %.2f, characteristic score 1: %.2f'%(d1, CS1))\n        print('Diversity 2: %.2f, characteristic score 2: %.2f'%(d2, CS2))\n    elif args.name == 'creatures':\n        print('Diversity 1: %.2f, characteristic score 1: %.2f, semantic diversity score 1: %.2f'%(d1, CS1, SDS1))\n        print('Diversity 2: %.2f, characteristic score 2: %.2f, semantic diversity score 2: %.2f'%(d2, CS2, SDS2))\n\n", "meta": {"hexsha": "49e13a538e2d13a7533b8d19ae36fdb536da7a34", "size": 14258, "ext": "py", "lang": "Python", "max_stars_repo_path": "evaluate.py", "max_stars_repo_name": "SongweiGe/DoodlerGAN", "max_stars_repo_head_hexsha": "d435d9b3c0579937cd3c22aa2051960ceb921785", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 92, "max_stars_repo_stars_event_min_datetime": "2020-10-02T23:44:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T22:49:35.000Z", "max_issues_repo_path": "evaluate.py", "max_issues_repo_name": "SongweiGe/DoodlerGAN", "max_issues_repo_head_hexsha": "d435d9b3c0579937cd3c22aa2051960ceb921785", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-10-03T05:11:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-23T23:27:05.000Z", "max_forks_repo_path": "evaluate.py", "max_forks_repo_name": "SongweiGe/DoodlerGAN", "max_forks_repo_head_hexsha": "d435d9b3c0579937cd3c22aa2051960ceb921785", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-10-03T05:06:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-06T14:03:24.000Z", "avg_line_length": 39.0630136986, "max_line_length": 136, "alphanum_fraction": 0.6279983167, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3486451285660856, "lm_q1q2_score": 0.1960000984281612}}
{"text": "\"\"\"\nBasic Amplitude Calculations.\nA partial wave analysis process has following structure:\n\nDecayGroup: addition (+)\n    DecayChain: multiplication (x)\n        Decay, Particle(Propagator)\n\n\"\"\"\n\nimport contextlib\nimport functools\nimport inspect\nimport warnings\nfrom itertools import combinations\nfrom pprint import pprint\n\nimport numpy as np\nimport sympy as sym\n\nfrom tf_pwa.breit_wigner import BW, BWR, Bprime, Bprime_q2\nfrom tf_pwa.cg import cg_coef\nfrom tf_pwa.config import get_config, regist_config, temp_config\nfrom tf_pwa.data import data_map, data_shape, split_generator\nfrom tf_pwa.dec_parser import load_dec_file\nfrom tf_pwa.dfun import get_D_matrix_lambda\nfrom tf_pwa.einsum import einsum\nfrom tf_pwa.particle import DEFAULT_DECAY, BaseParticle, Decay\nfrom tf_pwa.particle import DecayChain as BaseDecayChain\nfrom tf_pwa.particle import DecayGroup as BaseDecayGroup\nfrom tf_pwa.particle import _spin_int, _spin_range, split_particle_type\nfrom tf_pwa.tensorflow_wrapper import tf\nfrom tf_pwa.variable import Variable, VarsManager\n\n# from pysnooper import snoop\n\n\nPARTICLE_MODEL = \"particle_model\"\nregist_config(PARTICLE_MODEL, {})\nDECAY_MODEL = \"decay_model\"\nregist_config(DECAY_MODEL, {})\n\n\ndef register_particle(name=None, f=None):\n    \"\"\"register a particle model\n\n    :params name: model name used in configuration\n    :params f: Model class\n    \"\"\"\n\n    def regist(g):\n        if name is None:\n            my_name = g.__name__\n        else:\n            my_name = name\n        config = get_config(PARTICLE_MODEL)\n        if my_name in config:\n            warnings.warn(\"Override model {}\".format(my_name))\n        config[my_name] = g\n        g.model_name = my_name\n        return g\n\n    if f is None:\n        return regist\n    return regist(f)\n\n\ndef register_decay(name=None, num_outs=2, f=None):\n    \"\"\"register a decay model\n\n    :params name: model name used in configuration\n    :params f: Model class\n    \"\"\"\n\n    def regist(g):\n        if name is None:\n            my_name = g.__name__\n        else:\n            my_name = name\n        config = get_config(DECAY_MODEL)\n        id_ = (num_outs, my_name)\n        if id_ in config:\n            warnings.warn(\"Override deccay model {}\".format(my_name))\n        config[id_] = g\n        g.model_name = my_name\n        return g\n\n    if f is None:\n        return regist\n    return regist(f)\n\n\nregist_particle = register_particle\nregist_decay = register_decay\n\n\ndef get_particle_model(name):\n    all_model = get_config(PARTICLE_MODEL)\n    return all_model.get(name, None)\n\n\ndef get_particle_model_name(p):\n    all_model = get_config(PARTICLE_MODEL)\n    for k, v in all_model.items():\n        if type(p) is v:\n            return k\n    return str(type(p))\n\n\ndef get_particle(*args, model=\"default\", **kwargs):\n    \"\"\"method for getting particle of model\"\"\"\n    if isinstance(model, dict):\n        model_class = trans_model(model)\n    else:\n        model_class = get_particle_model(model)\n    if model_class is None:\n        warnings.warn(\n            \"No model named {} found, use default instead.\".format(model)\n        )\n        model_class = get_particle_model(\"default\")\n    return model_class(*args, **kwargs)\n\n\ndef trans_model(model):\n    expr = model.get(\"expr\")\n    expr = sym.simplify(expr)\n    var = {str(k): str(k) for k in expr.free_symbols}\n    var.update(model.get(\"where\", {}))\n    model_name = []\n    for k, v in var.items():\n        if isinstance(v, str):\n            model_name.append((k, v))\n    assert len(model_name) == 1\n    expr = sym.simplify(expr)\n    var_name, name = model_name.pop()\n    expr2 = expr.subs({k: v for k, v in var.items() if k != var_name})\n    assert len(expr2.free_symbols) == 1, str(expr2)\n    fun = sym.lambdify((var_name,), expr2, \"tensorflow\")\n    base_model = get_particle_model(name)\n\n    class _TempModel(base_model):\n        _from_trans = True\n\n        def get_amp(self, *args, **kwargs):\n            amp = super().get_amp(*args, **kwargs)\n            return fun(amp)\n\n    return _TempModel\n\n\ndef get_decay(core, outs, **kwargs):\n    \"\"\"method for getting decay of model\"\"\"\n    num_outs = len(outs)\n\n    prod_params = {}\n    for i in outs:\n        prod_params.update(getattr(i, \"production_params\", {}))\n\n    decay_params = getattr(core, \"decay_params\", {})\n\n    new_kwargs = {**prod_params, **decay_params, **kwargs}\n\n    model = new_kwargs.get(\"model\", \"default\")\n    id_ = (num_outs, model)\n\n    return get_config(DECAY_MODEL)[id_](core, outs, **new_kwargs)\n\n\ndef data_device(data):\n    def get_device(dat):\n        if hasattr(dat, \"device\"):\n            return dat.device\n        return None\n\n    pprint(data_map(data, get_device))\n    return data\n\n\ndef get_name(self, names):\n    name = (\n        (str(self) + \"_\" + names)\n        .replace(\":\", \"/\")\n        .replace(\"+\", \".\")\n        .replace(\",\", \"\")\n        .replace(\"[\", \"\")\n        .replace(\"]\", \"\")\n        .replace(\" \", \"\")\n    )\n    return name\n\n\ndef _add_var(self, names, is_complex=False, shape=(), **kwargs):\n    name = get_name(self, names)\n    return Variable(name, shape, is_complex, **kwargs)\n\n\nclass AmpBase(object):\n    \"\"\"Base class for amplitude \"\"\"\n\n    def add_var(self, names, is_complex=False, shape=(), **kwargs):\n        \"\"\"\n        default add_var method\n        \"\"\"\n        if not hasattr(self, \"_variables_map\"):\n            self._variables_map = {}\n        name = self.get_variable_name(names)\n        var = Variable(name, shape, is_complex, **kwargs)\n        self._variables_map[names] = var\n        return var\n\n    def get_var(self, name):\n        return getattr(self, \"_variables_map\", {}).get(name)\n\n    def get_variable_name(self, name=\"\"):\n        return get_name(self, name)\n\n    def amp_shape(self):\n        raise NotImplementedError\n\n    def get_factor_variable(self):\n        return []\n\n\n@contextlib.contextmanager\ndef variable_scope(vm=None):\n    \"\"\"variabel name scope\"\"\"\n    if vm is None:\n        vm = VarsManager(dtype=get_config(\"dtype\"))\n    with temp_config(\"vm\", vm):\n        yield vm\n\n\ndef simple_deepcopy(dic):\n    if isinstance(dic, dict):\n        return {k: simple_deepcopy(v) for k, v in dic.items()}\n    if isinstance(dic, list):\n        return [simple_deepcopy(v) for v in dic]\n    if isinstance(dic, tuple):\n        return tuple([simple_deepcopy(v) for v in dic])\n    return dic\n\n\ndef simple_cache_fun(f):\n    name = \"simple_cached_\" + f.__name__\n\n    @functools.wraps(f)\n    def g(self, *args, **kwargs):\n        if not hasattr(self, name):\n            setattr(self, name, f(self, *args, **kwargs))\n        return getattr(self, name)\n\n    return g\n\n\ndef get_relative_p(m_0, m_1, m_2):\n    \"\"\"relative momentum for 0 -> 1 + 2\"\"\"\n    M12S = m_1 + m_2\n    M12D = m_1 - m_2\n    if hasattr(M12S, \"dtype\"):\n        m_0 = tf.convert_to_tensor(m_0, dtype=M12S.dtype)\n    m_eff = tf.where(m_0 > M12S, m_0, M12S)\n    p = (m_eff - M12S) * (m_eff + M12S) * (m_eff - M12D) * (m_eff + M12D)\n    # if p is negative, which results from bad data, the return value is 0.0\n    # print(\"p\", tf.where(p==0), m_0, m_1, m_2)\n    return tf.sqrt(p) / (2 * m_eff)\n\n\ndef get_relative_p2(m_0, m_1, m_2):\n    \"\"\"relative momentum for 0 -> 1 + 2\"\"\"\n    M12S = m_1 + m_2\n    M12D = m_1 - m_2\n    if hasattr(M12S, \"dtype\"):\n        m_0 = tf.convert_to_tensor(m_0, dtype=M12S.dtype)\n    # m_eff = tf.where(m_0 > M12S, m_0, M12S)\n    p = (m_0 - M12S) * (m_0 + M12S) * (m_0 - M12D) * (m_0 + M12D)\n    # if p is negative, which results from bad data, the return value is 0.0\n    # print(\"p\", tf.where(p==0), m_0, m_1, m_2)\n    return p / (2 * m_0) ** 2\n\n\ndef _ad_hoc(m0, m_max, m_min):\n    r\"\"\"ad-hoc formula\n\n    .. math::\n        m_0^{eff} = m^{min} + \\frac{m^{max} - m^{min}}{2}(1+tanh \\frac{m_0 - \\frac{m^{max} + m^{min}}{2}}{m^{max} - m^{min}})\n\n    \"\"\"\n    k = (m_max - m_min) / 2\n    m_eff = k * (1 + tf.tanh((2 * m0 - (m_max + m_min)) / k))\n    return m_eff + m_min\n\n\n@regist_particle(\"BWR\")\n@regist_particle(\"default\")\nclass Particle(BaseParticle, AmpBase):\n    \"\"\"\n    .. math::\n        R(m) = \\\\frac{1}{m_0^2 - m^2 - i m_0 \\\\Gamma(m)}\n\n    \"\"\"\n\n    def __init__(self, *args, running_width=True, bw_l=None, **kwargs):\n        super(Particle, self).__init__(*args, **kwargs)\n        self.running_width = running_width\n        self.bw_l = bw_l\n\n    def init_params(self):\n        self.d = 3.0\n        if self.mass is None:\n            self.mass = self.add_var(\"mass\", fix=True)\n            # print(\"$$$$$\",self.mass)\n        else:\n            if not isinstance(self.mass, Variable):\n                self.mass = self.add_var(\"mass\", value=self.mass, fix=True)\n        if self.width is not None:\n            if not isinstance(self.width, Variable):\n                self.width = self.add_var(\"width\", value=self.width, fix=True)\n\n    def get_amp(self, data, data_c, **kwargs):\n        mass = self.get_mass()\n        width = self.get_width()\n        if width is None:\n            return tf.ones_like(data[\"m\"])\n        if not self.running_width:\n            ret = BW(data[\"m\"], mass, width)\n        else:\n            q = data_c[\"|q|\"]\n            q0 = data_c[\"|q0|\"]\n            if self.bw_l is None:\n                decay = self.decay[0]\n                self.bw_l = min(decay.get_l_list())\n            ret = BWR(data[\"m\"], mass, width, q, q0, self.bw_l, self.d)\n            # ret = tf.where(q0 > 0, ret, tf.zeros_like(ret))\n            # ret = tf.where(q > 0, ret, tf.zeros_like(ret))\n        return ret\n\n    def amp_shape(self):\n        return ()\n\n    def get_mass(self):\n        if self.mass is None:\n            warnings.warn(\n                f\"The mass of {self} is None, may be you should calculate amplitude first to infer mass\"\n            )\n        if callable(self.mass):\n            return self.mass()\n        return self.mass\n\n    def get_width(self):\n        if callable(self.width):\n            return self.width()\n        return self.width\n\n\n@regist_particle(\"x\")\nclass ParticleX(BaseParticle, AmpBase):\n    \"\"\"simple particle model for mass, (used in expr)\n\n    .. math::\n        R(m) = m\n\n    \"\"\"\n\n    def __call__(self, m):\n        return self.get_amp({\"m\": m})\n\n    def get_amp(self, data, *args, **kwargs):\n        m = data[\"m\"]\n        zeros = tf.zeros_like(m)\n        return tf.complex(m, zeros)\n\n\nclass SimpleResonances(Particle):\n    def __init__(self, *args, **kwargs):\n        self.params = {}\n        super(SimpleResonances, self).__init__(*args, **kwargs)\n\n    def __call__(self, m, m0=None, g0=None, q=None, q0=None, **kwargs):\n        raise NotImplementedError\n\n    def get_amp(self, *args, **kwargs):\n        m = args[0][\"m\"]\n        q, q0 = None, None\n        if len(args) >= 2:\n            q = args[1].get(\"|q|\", 1.0)\n            q0 = args[1].get(\"|q0|\", 1.0)\n        m0 = self.get_mass()\n        g0 = self.get_width()\n        return self(m, m0=m0, g0=g0, q=q, q0=q0, **kwargs)\n\n\nclass FloatParams(float):\n    pass\n\n\ndef simple_resonance(name, fun=None, params=None):\n    \"\"\"convert simple fun f(m) into a resonances model\n\n    :params name: model name used in configuration\n    :params fun: Model function\n    :params params: arguments name list for parameters\n\n    \"\"\"\n\n    if params is None:\n        params = {}\n\n    def _wrapper(f):\n        argspec = inspect.getfullargspec(f)\n        args = argspec.args\n        if argspec.defaults is None:\n            defaults = {}\n        else:\n            defaults = dict(zip(argspec.args[::-1], argspec.defaults[::-1]))\n\n        @register_particle(name)\n        class _R(SimpleResonances):\n            def init_params(self):\n                if \"m0\" in argspec.args and \"g0\" in argspec.args:\n                    super(_R, self).init_params()\n                self.params = {}\n                for i in argspec.args:\n                    tp = argspec.annotations.get(i, None)\n                    if i in params or tp is FloatParams:\n                        val = getattr(self, i, defaults.get(i, None))\n                        if val is None:\n                            self.params[i] = self.add_var(i)\n                        else:\n                            self.params[i] = self.add_var(\n                                i, value=val, fix=True\n                            )\n\n            def __call__(self, m, **kwargs):\n                my_kwargs = {}\n                for i in argspec.args:\n                    if i in kwargs:\n                        my_kwargs[i] = kwargs[i]\n                    elif i in self.params:\n                        my_kwargs[i] = self.params[i]()\n                    elif hasattr(self, i):\n                        my_kwargs[i] = getattr(self, i)\n                ret = f(m, **my_kwargs)\n                return tf.cast(ret, tf.complex128)\n\n            __call__.__doc__ = f.__doc__\n\n        _R.get_amp.__doc__ = f.__doc__\n        return _R\n\n    if fun is None:\n        return _wrapper\n    return _wrapper(fun)\n\n\nclass AmpDecay(Decay, AmpBase):\n    \"\"\"base class for decay with amplitude\"\"\"\n\n    def amp_shape(self):\n        ret = [len(self.core.spins)]\n        for i in self.outs:\n            ret.append(len(i.spins))\n        return tuple(ret)\n\n    # @simple_cache_fun\n    def amp_index(self, base_map):\n        ret = [base_map[self.core]]\n        for i in self.outs:\n            ret.append(base_map[i])\n        return ret\n\n\n@regist_decay(\"default\")\n@regist_decay(\"gls-bf\")\nclass HelicityDecay(AmpDecay):\n    \"\"\"default decay model\"\"\"\n\n    def __init__(\n        self,\n        *args,\n        has_barrier_factor=True,\n        l_list=None,\n        barrier_factor_mass=False,\n        has_bprime=True,\n        aligned=False,\n        allow_cc=True,\n        ls_list=None,\n        barrier_factor_norm=False,\n        params_polar=None,\n        **kwargs\n    ):\n        super(HelicityDecay, self).__init__(*args, **kwargs)\n        self.has_barrier_factor = has_barrier_factor\n        self.l_list = l_list\n        self.barrier_factor_mass = barrier_factor_mass\n        self.has_bprime = has_bprime\n        self.aligned = aligned\n        self.allow_cc = allow_cc\n        self.single_gls = False\n        self.ls_index = None\n        self.total_ls = None\n        self.barrier_factor_norm = barrier_factor_norm\n        self.ls_list = None\n        if ls_list is not None:\n            self.ls_list = tuple([tuple(i) for i in ls_list])\n        self.params_polar = params_polar\n\n    def check_valid_jp(self):\n        if len(self.get_ls_list()) == 0:\n            if not self.p_break:\n                raise ValueError(\n                    \"\"\"invalid spin parity for {}, maybe you should set `p_break: True` for weak decay\"\"\".format(\n                        self\n                    )\n                )\n            raise ValueError(\"invalid spin parity for {}\".format(self))\n\n    def set_ls(self, ls):\n        if self.total_ls is None:\n            self.total_ls = self.get_ls_list()\n        self.ls_list = tuple([tuple(i) for i in ls])\n        self.single_gls = len(ls) == 1\n        # print(self, \"total_ls: \", self.total_ls)\n        total_ls = self.total_ls\n        if len(total_ls) == len(ls):\n            self.ls_index = None\n            return\n        self.ls_index = []\n        for i in self.ls_list:\n            self.ls_index.append(total_ls.index(i))\n\n    def init_params(self):\n        self.d = 3.0\n        ls = self.get_ls_list()\n        self.g_ls = self.add_var(\n            \"g_ls\", is_complex=True, polar=self.params_polar, shape=(len(ls),)\n        )\n        try:\n            self.g_ls.set_fix_idx(fix_idx=0, fix_vals=(1.0, 0.0))\n        except Exception as e:\n            print(e, self, self.get_ls_list())\n\n    def get_factor_variable(self):\n        return [(self.g_ls,)]\n\n    def _get_particle_mass(self, p, data, from_data=False):\n        if from_data:\n            return data[p][\"m\"]\n        if p.mass is None:\n            p.mass = tf.reduce_mean(data[p][\"m\"])\n        return p.get_mass()\n\n    def get_relative_momentum(self, data, from_data=False):\n        \"\"\"\"\"\"\n\n        _get_mass = lambda p: self._get_particle_mass(p, data, from_data)\n\n        m0 = _get_mass(self.core)\n        m1 = _get_mass(self.outs[0])\n        m2 = _get_mass(self.outs[1])\n        return get_relative_p(m0, m1, m2)\n\n    def get_relative_momentum2(self, data, from_data=False):\n        \"\"\"\"\"\"\n\n        _get_mass = lambda p: self._get_particle_mass(p, data, from_data)\n\n        m0 = _get_mass(self.core)\n        m1 = _get_mass(self.outs[0])\n        m2 = _get_mass(self.outs[1])\n        return get_relative_p2(m0, m1, m2)\n\n    def get_cg_matrix(self):\n        ls = self.get_ls_list()\n        return self._get_cg_matrix(ls)\n\n    @functools.lru_cache()\n    def _get_cg_matrix(self, ls):  # CG factor inside H\n        \"\"\"\n        [(l,s),(lambda_b,lambda_c)]\n\n        .. math::\n          \\\\sqrt{\\\\frac{ 2 l + 1 }{ 2 j_a + 1 }}\n          \\\\langle j_b, j_c, \\\\lambda_b, - \\\\lambda_c | s, \\\\lambda_b - \\\\lambda_c \\\\rangle\n          \\\\langle l, s, 0, \\\\lambda_b - \\\\lambda_c | j_a, \\\\lambda_b - \\\\lambda_c \\\\rangle\n        \"\"\"\n        m = len(ls)\n        ja = self.core.J\n        jb = self.outs[0].J\n        jc = self.outs[1].J\n        n = _spin_int(2 * jb + 1), _spin_int(2 * jc + 1)\n        ret = np.zeros(shape=(m, *n))\n        for i, ls_i in enumerate(ls):\n            l, s = ls_i\n            for i1, lambda_b in enumerate(_spin_range(-jb, jb)):\n                for i2, lambda_c in enumerate(_spin_range(-jc, jc)):\n                    ret[i][i1][i2] = (\n                        np.sqrt((2 * l + 1) / (2 * ja + 1))\n                        * cg_coef(\n                            jb, jc, lambda_b, -lambda_c, s, lambda_b - lambda_c\n                        )\n                        * cg_coef(\n                            l,\n                            s,\n                            0,\n                            lambda_b - lambda_c,\n                            ja,\n                            lambda_b - lambda_c,\n                        )\n                    )\n        return tf.convert_to_tensor(ret)\n\n    def get_helicity_amp(self, data, data_p, **kwargs):\n        m_dep = self.get_ls_amp(data, data_p, **kwargs)\n        cg_trans = tf.cast(self.get_cg_matrix(), m_dep.dtype)\n        n_ls = len(self.get_ls_list())\n        m_dep = tf.reshape(m_dep, (-1, n_ls, 1, 1))\n        cg_trans = tf.reshape(\n            cg_trans, (n_ls, len(self.outs[0].spins), len(self.outs[1].spins))\n        )\n        H = tf.reduce_sum(m_dep * cg_trans, axis=1)\n        # print(n_ls, cg_trans, self, m_dep.shape) # )data_p)\n        if self.allow_cc:\n            all_data = kwargs.get(\"all_data\", {})\n            charge = all_data.get(\"charge_conjugation\", None)\n            if charge is not None:\n                H = tf.where(\n                    charge[..., None, None] > 0, H, H[..., ::-1, ::-1]\n                )\n        ret = tf.reshape(\n            H, (-1, 1, len(self.outs[0].spins), len(self.outs[1].spins))\n        )\n        return ret\n\n    def get_angle_helicity_amp(self, data, data_p, **kwargs):\n        m_dep = self.get_angle_ls_amp(data, data_p, **kwargs)\n        cg_trans = tf.cast(self.get_cg_matrix(), m_dep.dtype)\n        n_ls = len(self.get_ls_list())\n        m_dep = tf.reshape(m_dep, (-1, n_ls, 1, 1))\n        cg_trans = tf.reshape(\n            cg_trans, (n_ls, len(self.outs[0].spins), len(self.outs[1].spins))\n        )\n        H = tf.reduce_sum(m_dep * cg_trans, axis=1)\n        # print(n_ls, cg_trans, self, m_dep.shape) # )data_p)\n        if self.allow_cc:\n            all_data = kwargs.get(\"all_data\", {})\n            charge = all_data.get(\"charge_conjugation\", None)\n            if charge is not None:\n                H = tf.where(\n                    charge[..., None, None] > 0, H, H[..., ::-1, ::-1]\n                )\n        ret = tf.reshape(\n            H, (-1, 1, len(self.outs[0].spins), len(self.outs[1].spins))\n        )\n        return ret\n\n    def get_g_ls(self):\n        gls = self.g_ls()\n        if self.ls_index is None:\n            return tf.stack(gls)\n        # print(self, gls, self.ls_index)\n        return tf.stack([gls[k] for k in self.ls_index])\n\n    def get_ls_amp_org(self, data, data_p, **kwargs):\n        g_ls = self.get_g_ls()\n        # print(g_ls)\n        q0 = self.get_relative_momentum(data_p, False)\n        data[\"|q0|\"] = q0\n        if \"|q|\" in data:\n            q = data[\"|q|\"]\n        else:\n            q = self.get_relative_momentum(data_p, True)\n            data[\"|q|\"] = q\n        if self.has_barrier_factor:\n            bf = self.get_barrier_factor(data_p[self.core][\"m\"], q, q0, self.d)\n            mag = g_ls\n            m_dep = mag * tf.cast(bf, mag.dtype)\n        else:\n            m_dep = g_ls\n        return m_dep\n\n    def get_ls_amp(self, data, data_p, **kwargs):\n        g_ls = self.get_g_ls()\n        # print(g_ls)\n        q0 = self.get_relative_momentum2(data_p, False)\n        data[\"|q0|2\"] = q0\n        if \"|q|2\" in data:\n            q = data[\"|q|2\"]\n        else:\n            q = self.get_relative_momentum2(data_p, True)\n            data[\"|q|2\"] = q\n        if self.has_barrier_factor:\n            bf = self.get_barrier_factor2(\n                data_p[self.core][\"m\"], q, q0, self.d\n            )\n            mag = g_ls\n            m_dep = mag * tf.cast(bf, mag.dtype)\n        else:\n            m_dep = g_ls\n        return m_dep\n\n    def get_angle_g_ls(self):\n        gls = [complex(1.0, 0.0) for i in self.g_ls()]\n        if self.ls_index is None:\n            return tf.stack(gls)\n        return tf.stack([gls[k] for k in self.ls_index])\n\n    def get_angle_ls_amp(self, data, data_p, **kwargs):\n        g_ls = self.get_angle_g_ls()\n        return g_ls\n\n    def get_barrier_factor(self, mass, q, q0, d):\n        ls = self.get_l_list()\n        ret = []\n        for l in ls:\n            if self.has_bprime:\n                tmp = q ** l * tf.cast(Bprime(l, q, q0, d), dtype=q.dtype)\n            else:\n                tmp = q ** l\n            # tmp = tf.where(q > 0, tmp, tf.zeros_like(tmp))\n            ret.append(tf.reshape(tmp, (-1, 1)))\n        ret = tf.concat(ret, axis=-1)\n        mass_dep = self.get_barrier_factor_mass(mass)\n        return ret * mass_dep\n\n    def get_barrier_factor2(self, mass, q2, q02, d):\n        ls = self.get_l_list()\n        ret = []\n        for l in ls:\n            if self.has_bprime:\n                bp = Bprime_q2(l, q2, q02, d)\n                tmp = q2 ** (l / 2) * tf.cast(bp, dtype=q2.dtype)\n                if self.barrier_factor_norm:\n                    tmp = tmp / q02 ** (l / 2)\n            else:\n                tmp = q2 ** (l / 2)\n            # tmp = tf.where(q > 0, tmp, tf.zeros_like(tmp))\n            ret.append(tf.reshape(tmp, (-1, 1)))\n        ret = tf.concat(ret, axis=-1)\n        mass_dep = self.get_barrier_factor_mass(mass)\n        return ret * mass_dep\n\n    def get_barrier_factor_mass(self, mass):\n        if not self.barrier_factor_mass:\n            return 1.0\n        ls = tf.convert_to_tensor(self.get_l_list(), dtype=mass.dtype)\n        m_dep = 1.0 / tf.pow(tf.expand_dims(mass, -1), ls)\n        return m_dep\n\n    def get_amp(self, data, data_p, **kwargs):\n        a = self.core\n        b = self.outs[0]\n        c = self.outs[1]\n        ang = data[b][\"ang\"]\n        D_conj = get_D_matrix_lambda(ang, a.J, a.spins, b.spins, c.spins)\n        H = self.get_helicity_amp(data, data_p, **kwargs)\n        H = tf.reshape(\n            H, (-1, 1, len(self.outs[0].spins), len(self.outs[1].spins))\n        )\n        H = tf.cast(H, dtype=D_conj.dtype)\n        ret = H * tf.stop_gradient(D_conj)\n        # print(self, H, D_conj)\n        # exit()\n        if self.aligned:\n            for j, particle in enumerate(self.outs):\n                if particle.J != 0 and \"aligned_angle\" in data[particle]:\n                    ang = data[particle].get(\"aligned_angle\", None)\n                    if ang is None:\n                        continue\n                    dt = get_D_matrix_lambda(\n                        ang, particle.J, particle.spins, particle.spins\n                    )\n                    dt_shape = [-1, 1, 1, 1, 1]\n                    dt_shape[j + 2] = len(particle.spins)\n                    dt_shape[j + 3] = len(particle.spins)\n                    dt = tf.reshape(dt, dt_shape)\n                    D_shape = [-1, len(a.spins), len(b.spins), len(c.spins)]\n                    D_shape.insert(j + 3, 2)\n                    D_shape[j + 3] = 1\n                    ret = tf.reshape(ret, D_shape)\n                    ret = dt * ret\n                    ret = tf.reduce_sum(ret, axis=j + 2)\n        return ret\n\n    def get_angle_amp(self, data, data_p, **kwargs):\n        a = self.core\n        b = self.outs[0]\n        c = self.outs[1]\n        ang = data[b][\"ang\"]\n        D_conj = get_D_matrix_lambda(ang, a.J, a.spins, b.spins, c.spins)\n        H = self.get_angle_helicity_amp(data, data_p, **kwargs)\n        H = tf.reshape(\n            H, (-1, 1, len(self.outs[0].spins), len(self.outs[1].spins))\n        )\n        H = tf.cast(H, dtype=D_conj.dtype)\n        ret = H * tf.stop_gradient(D_conj)\n        # print(self, H, D_conj)\n        # exit()\n        if self.aligned:\n            for j, particle in enumerate(self.outs):\n                if particle.J != 0 and \"aligned_angle\" in data[particle]:\n                    ang = data[particle].get(\"aligned_angle\", None)\n                    if ang is None:\n                        continue\n                    dt = get_D_matrix_lambda(\n                        ang, particle.J, particle.spins, particle.spins\n                    )\n                    dt_shape = [-1, 1, 1, 1, 1]\n                    dt_shape[j + 2] = len(particle.spins)\n                    dt_shape[j + 3] = len(particle.spins)\n                    dt = tf.reshape(dt, dt_shape)\n                    D_shape = [-1, len(a.spins), len(b.spins), len(c.spins)]\n                    D_shape.insert(j + 3, 2)\n                    D_shape[j + 3] = 1\n                    ret = tf.reshape(ret, D_shape)\n                    ret = dt * ret\n                    ret = tf.reduce_sum(ret, axis=j + 2)\n        return ret\n\n    def get_m_dep(self, data, data_p, **kwargs):\n        return self.get_ls_amp(data, data_p, **kwargs)\n\n    def get_ls_list(self):\n        \"\"\"get possible ls for decay, with l_list filter possible l\"\"\"\n        ls_list = super(HelicityDecay, self).get_ls_list()\n        if self.ls_list is not None:\n            return self.ls_list\n        if self.l_list is None:\n            return ls_list\n        ret = []\n        for l, s in ls_list:\n            if l in self.l_list:\n                ret.append((l, s))\n        return tuple(ret)\n\n\n@regist_decay(\"default\", 3)\n@regist_decay(\"AngSam3\", 3)\nclass AngSam3Decay(AmpDecay, AmpBase):\n    def init_params(self):\n        a = self.core.J\n        self.gi = self.add_var(\n            \"G_mu\", is_complex=True, shape=(_spin_int(2 * a + 1),)\n        )\n        try:\n            self.gi.set_fix_idx(fix_idx=0, fix_vals=(1.0, 0.0))\n        except Exception as e:\n            print(e)\n\n    def get_amp(self, data, data_extra=None, **kwargs):\n        a = self.core\n        b = self.outs[0]\n        c = self.outs[1]\n        d = self.outs[2]\n        gi = tf.stack(self.gi())\n        ang = data[\"ang\"]\n        D_conj = get_D_matrix_lambda(\n            ang, a.J, a.spins, tuple(_spin_range(-a.J, a.J))\n        )\n        ret = tf.cast(gi, D_conj.dtype) * D_conj\n        ret = tf.reduce_sum(ret, axis=-1)\n        ret = tf.reshape(ret, (-1, len(a.spins), 1, 1, 1))\n        ret = tf.tile(ret, [1, 1, len(b.spins), len(c.spins), len(d.spins)])\n        return ret\n\n\nclass DecayChain(BaseDecayChain, AmpBase):\n    \"\"\"A list of Decay as a chain decay\"\"\"\n\n    def __init__(self, *args, is_cp=False, **kwargs):\n        self.is_cp = is_cp\n        super(DecayChain, self).__init__(*args, **kwargs)\n        self.aligned = True\n        self.need_amp_particle = True\n\n    def init_params(self, name=\"\"):\n        self.total = self.add_var(\n            name + \"total\", is_complex=True, is_cp=self.is_cp, shape=[1]\n        )\n        # self.total = self.add_var(name + \"total\", is_complex=True, shape=[1])\n\n    def get_factor_variable(self):\n        a = []\n        for i in self:\n            tmp = i.get_factor_variable()\n            if tmp:\n                a.append(tmp)\n        for j in self.inner:\n            tmp = j.get_factor_variable()\n            if tmp:\n                a.append(tmp)\n        return [tuple([self.total] + a)]\n\n    def get_amp_total(self, charge=1):\n        return tf.stack(self.total(charge))\n\n    def product_gls(self):\n        ret = self.get_all_factor()\n        return tf.reduce_prod(ret)\n\n    def get_all_factor(self):\n        ret = [self.get_amp_total()]\n        for i in self:\n            ret.append(i.get_g_ls())\n        return ret\n\n    def get_cp_amp_total(self, charge=1):\n        if not self.is_cp:\n            return self.get_amp_total()\n        total_pos = self.get_amp_total(1)\n        total_neg = self.get_amp_total(-1)\n        # print(\"total_pos\", total_pos)\n        # print(\"total_neg\", total_neg)\n        charge_cond = charge > 0\n        # print(\"charge\", charge)\n        total = tf.where(charge_cond, total_pos, total_neg)\n        return total\n\n    def get_amp(self, data_c, data_p, all_data=None, base_map=None):\n        base_map = self.get_base_map(base_map)\n        iter_idx = [\"...\"]\n        amp_d = []\n        indices = []\n        final_indices = \"\".join(iter_idx + self.amp_index(base_map))\n        for i in self:\n            indices.append(i.amp_index(base_map))\n            amp_d.append(i.get_amp(data_c[i], data_p, all_data=all_data))\n\n        if self.need_amp_particle:\n            rs = self.get_amp_particle(data_p, data_c, all_data=all_data)\n\n            total = self.get_cp_amp_total(\n                charge=all_data.get(\"charge_conjugation\", 1)\n            )\n            if rs is not None:\n                total = total * tf.cast(rs, total.dtype)\n            # print(total)*self.get_amp_total()\n            amp_d.append(total)\n            indices.append([])\n\n        if self.aligned:\n            for i in self:\n                for j in i.outs:\n                    if j.J != 0 and \"aligned_angle\" in data_c[i][j]:\n                        ang = data_c[i][j][\"aligned_angle\"]\n                        dt = get_D_matrix_lambda(ang, j.J, j.spins, j.spins)\n                        amp_d.append(tf.stop_gradient(dt))\n                        idx = [base_map[j], base_map[j].upper()]\n                        indices.append(idx)\n                        final_indices = final_indices.replace(*idx)\n        idxs = []\n        for i in indices:\n            tmp = \"\".join(iter_idx + i)\n            idxs.append(tmp)\n        idx = \",\".join(idxs)\n        idx_s = \"{}->{}\".format(idx, final_indices)\n        # ret = amp * tf.reshape(rs, [-1] + [1] * len(self.amp_shape()))\n        # print(idx_s)#, amp_d)\n        try:\n            ret = einsum(idx_s, *amp_d)\n        except:\n            ret = tf.einsum(idx_s, *amp_d)\n        # print(self, ret[0])\n        # exit()\n        # ret = einsum(idx_s, *amp_d)\n        return ret\n\n    def get_angle_amp(self, data_c, data_p, all_data=None, base_map=None):\n        base_map = self.get_base_map(base_map)\n        iter_idx = [\"...\"]\n        amp_d = []\n        indices = []\n        final_indices = \"\".join(iter_idx + self.amp_index(base_map))\n        for i in self:\n            indices.append(i.amp_index(base_map))\n            amp_d.append(i.get_angle_amp(data_c[i], data_p, all_data=all_data))\n\n        if self.aligned:\n            for i in self:\n                for j in i.outs:\n                    if j.J != 0 and \"aligned_angle\" in data_c[i][j]:\n                        ang = data_c[i][j][\"aligned_angle\"]\n                        dt = get_D_matrix_lambda(ang, j.J, j.spins, j.spins)\n                        amp_d.append(tf.stop_gradient(dt))\n                        idx = [base_map[j], base_map[j].upper()]\n                        indices.append(idx)\n                        final_indices = final_indices.replace(*idx)\n        idxs = []\n        for i in indices:\n            tmp = \"\".join(iter_idx + i)\n            idxs.append(tmp)\n        idx = \",\".join(idxs)\n        idx_s = \"{}->{}\".format(idx, final_indices)\n        # ret = amp * tf.reshape(rs, [-1] + [1] * len(self.amp_shape()))\n        # print(idx_s)#, amp_d)\n        try:\n            ret = einsum(idx_s, *amp_d)\n        except:\n            ret = tf.einsum(idx_s, *amp_d)\n        # print(self, ret[0])\n        # exit()\n        # ret = einsum(idx_s, *amp_d)\n        return ret\n\n    def get_m_dep(self, data_c, data_p, all_data=None, base_map=None):\n        base_map = self.get_base_map(base_map)\n        iter_idx = [\"...\"]\n        amp_d = []\n        indices = []\n        final_indices = \"\".join(iter_idx + self.amp_index(base_map))\n        for i in self:\n            indices.append(i.amp_index(base_map))\n            amp_d.append(i.get_m_dep(data_c[i], data_p, all_data=all_data))\n\n        if self.need_amp_particle:\n            rs = self.get_amp_particle(data_p, data_c, all_data=all_data)\n            total = self.get_cp_amp_total(\n                all_data.get(\"charge_conjugation\", 1)\n            )\n            # print(\"total_pos\", total_pos)\n            # print(\"total_neg\", total_neg)\n            if rs is not None:\n                total = total * tf.cast(rs, total.dtype)\n                # print(\"charge\", charge)\n            # print(total)\n            # print(total)*self.get_amp_total()\n            amp_d.append(total)\n        return amp_d\n\n    def get_amp_particle(self, data_p, data_c, all_data=None):\n        amp_p = []\n        if not self.inner:\n            return 1.0\n        for i in self.inner:\n            if len(i.decay) >= 1:\n                decay_i = i.decay[0]\n                found = False\n                for j in i.decay:\n                    if j in self:\n                        decay_i = j\n                        found = True\n                        break\n                if not found:\n                    raise IndexError(\n                        \"not found {} decay in {}\".format(i, self)\n                    )\n                data_c_i = data_c[decay_i]\n                if \"|q|\" not in data_c_i:\n                    data_c_i[\"|q|\"] = decay_i.get_relative_momentum(\n                        data_p, True\n                    )\n                if \"|q0|\" not in data_c_i:\n                    data_c_i[\"|q0|\"] = decay_i.get_relative_momentum(\n                        data_p, False\n                    )\n                if \"|q|2\" not in data_c_i:\n                    data_c_i[\"|q|2\"] = decay_i.get_relative_momentum2(\n                        data_p, True\n                    )\n                if \"|q0|2\" not in data_c_i:\n                    data_c_i[\"|q0|2\"] = decay_i.get_relative_momentum2(\n                        data_p, False\n                    )\n                amp_p.append(i.get_amp(data_p[i], data_c_i, all_data=all_data))\n            else:\n                amp_p.append(i.get_amp(data_p[i], all_data=all_data))\n        rs = 1.0\n        for i in amp_p:\n            rs = rs * i\n        # tf.reduce_prod(amp_p, axis=0)\n        return rs\n\n    def amp_shape(self):\n        ret = [len(self.top.spins)]\n        for i in self.outs:\n            ret.append(len(i.spins))\n        return tuple(ret)\n\n    # @simple_cache_fun\n    def amp_index(self, base_map=None):\n        if base_map is None:\n            base_map = self.get_base_map()\n        ret = [base_map[self.top]]\n        for i in self.outs:\n            ret.append(base_map[i])\n        return ret\n\n    def get_base_map(self, base_map=None):\n        gen = index_generator(base_map)\n        if base_map is None:\n            base_map = {}\n        ret = base_map.copy()\n        if self.top not in base_map:\n            ret[self.top] = next(gen)\n        for i in self.outs:\n            if i not in base_map:\n                ret[i] = next(gen)\n        for i in self.inner:\n            if i not in ret:\n                ret[i] = next(gen)\n        return ret\n\n\nclass DecayGroup(BaseDecayGroup, AmpBase):\n    \"\"\" A Group of Decay Chains with the same final particles.\"\"\"\n\n    def __init__(self, chains):\n        self.chains_idx = list(range(len(chains)))\n        first_chain = chains[0]\n        if not isinstance(first_chain, DecayChain):\n            chains = [DecayChain(i) for i in chains]\n        super(DecayGroup, self).__init__(chains)\n        self.not_full = False\n        self.polarization = getattr(self.top, \"polarization\", \"none\")\n        # self.init_params()\n\n    def init_params(self, name=\"\"):\n        for i in self.resonances:\n            i.init_params()\n        inited_set = set()\n        for i in self:\n            i.init_params(name)\n            for j in i:\n                if j not in inited_set:\n                    j.init_params()\n                    inited_set.add(j)\n        if self.polarization == \"vector\":\n            print(\"add polarization vector\")\n            if self.top.J == 0.5:\n                self.polarization_vector = [\n                    self.top.add_var(\"polarization_px\"),\n                    self.top.add_var(\"polarization_py\"),\n                    self.top.add_var(\"polarization_pz\"),\n                ]\n\n    def get_factor_variable(self):\n        ret = []\n        for i in self:\n            ret += i.get_factor_variable()\n        return ret\n\n    def get_amp(self, data):\n        \"\"\"\n        calculate the amplitude as complex number\n        \"\"\"\n        data_particle = data[\"particle\"]\n        data_decay = data[\"decay\"]\n\n        used_chains = tuple([self.chains[i] for i in self.chains_idx])\n        chain_maps = self.get_chains_map(used_chains)\n        base_map = self.get_base_map()\n        ret = []\n        for chains in chain_maps:\n            for decay_chain in chains:\n                chain_topo = decay_chain.standard_topology()\n                found = False\n                for i in data_decay.keys():\n                    if i == chain_topo:\n                        data_decay_i = data_decay[i]\n                        found = True\n                        break\n                if not found:\n                    raise KeyError(\"not found {}\".format(chain_topo))\n                data_c = rename_data_dict(data_decay_i, chains[decay_chain])\n                data_p = rename_data_dict(data_particle, chains[decay_chain])\n                # print(\"$$$$$\",data_c)\n                # print(\"$$$$$\",data_p)\n                amp = decay_chain.get_amp(\n                    data_c, data_p, base_map=base_map, all_data=data\n                )\n                ret.append(amp)\n                # print(decay_chain, amp[:10])\n        ret = tf.reduce_sum(ret, axis=0)\n        return ret\n\n    def get_m_dep(self, data):\n        \"\"\"get mass dependent items\"\"\"\n        data_particle = data[\"particle\"]\n        data_decay = data[\"decay\"]\n\n        used_chains = tuple([self.chains[i] for i in self.chains_idx])\n        chain_maps = self.get_chains_map(used_chains)\n        base_map = self.get_base_map()\n        ret = []\n        for decay_chain in used_chains:\n            for chains in chain_maps:\n                if str(decay_chain) in [str(i) for i in chains]:\n                    maps = chains[decay_chain]\n                    break\n            chain_topo = decay_chain.standard_topology()\n            found = False\n            for i in data_decay.keys():\n                if i == chain_topo:\n                    data_decay_i = data_decay[i]\n                    found = True\n                    break\n            if not found:\n                raise KeyError(\"not found {}\".format(chain_topo))\n            data_c = rename_data_dict(data_decay_i, maps)\n            data_p = rename_data_dict(data_particle, maps)\n            # print(\"$$$$$\",data_c)\n            # print(\"$$$$$\",data_p)\n            amp = decay_chain.get_m_dep(\n                data_c, data_p, base_map=base_map, all_data=data\n            )\n            ret.append(amp)\n        # ret = tf.reduce_sum(ret, axis=0)\n        return ret\n\n    def get_angle_amp(self, data):\n        data_particle = data[\"particle\"]\n        data_decay = data[\"decay\"]\n\n        used_chains = tuple([self.chains[i] for i in self.chains_idx])\n        chain_maps = self.get_chains_map(used_chains)\n        base_map = self.get_base_map()\n        ret = []\n        for decay_chain in used_chains:\n            for chains in chain_maps:\n                if str(decay_chain) in [str(i) for i in chains]:\n                    maps = chains[decay_chain]\n                    break\n            chain_topo = decay_chain.standard_topology()\n            found = False\n            for i in data_decay.keys():\n                if i == chain_topo:\n                    data_decay_i = data_decay[i]\n                    found = True\n                    break\n            if not found:\n                raise KeyError(\"not found {}\".format(chain_topo))\n            data_c = rename_data_dict(data_decay_i, maps)\n            data_p = rename_data_dict(data_particle, maps)\n            amp = decay_chain.get_angle_amp(\n                data_c, data_p, base_map=base_map, all_data=data\n            )\n            ret.append(amp)\n        # ret = tf.reduce_sum(ret, axis=0)\n        return amp\n\n    @functools.lru_cache()\n    def get_swap_factor(self, key):\n        factor = 1.0\n        for i, j in zip(self.identical_particles, key[1]):\n            p = self.get_particle(i[0])\n            if int(p.J * 2) % 2 == 0:\n                continue\n            for m, n in zip(i, j):\n                if m != n:\n                    factor *= -1.0\n        return factor\n\n    def get_amp2(self, data):\n        amp = self.get_amp(data)\n        id_swap = data.get(\"id_swap\", {})\n        for k, v in id_swap.items():\n            new_data = {**data, **v}\n            factor = self.get_swap_factor(k)\n            amp_swap = factor * self.get_amp(new_data)\n            # print(k, amp, amp_swap)\n            amp = amp + amp_swap\n        return amp\n\n    def sum_amp(self, data, cached=True):\n        \"\"\"\n        calculat the amplitude modular square\n        \"\"\"\n        if not cached:\n            data = simple_deepcopy(data)\n        if self.polarization != \"none\":\n            return self.sum_amp_polarization(data)\n        amp = self.get_amp2(data)\n        amp2s = tf.math.real(amp * tf.math.conj(amp))\n        idx = list(range(1, len(amp2s.shape)))\n        sum_A = tf.reduce_sum(amp2s, idx)\n        return sum_A\n\n    def sum_amp_polarization(self, data):\n        \"\"\"\n        sum amplitude suqare with density _get_cg_matrix\n\n        .. math::\n            P = \\\\sum_{m, m', \\\\cdots } A_{m, \\\\cdots}  \\\\rho_{m, m'} A^{*}_{m', \\\\cdots}\n\n        \"\"\"\n\n        amp = self.get_amp(data)\n        amp = tf.reshape(\n            amp, (amp.shape[0], amp.shape[1], -1)\n        )  # (i, la, lb lc ld ...)\n        na, nl = amp.shape[1], amp.shape[2]\n        rho = self.get_density_matrix()\n        amp = tf.reshape(amp, (-1, na, 1, nl))\n        amp_c = tf.reshape(\n            tf.math.conj(amp), (-1, na, nl)\n        )  # (i, la, lb lc ld ...)\n        sum_A = (\n            tf.reduce_sum(amp * tf.reshape(rho, (na, na, 1)), axis=1) * amp_c\n        )\n        return tf.reduce_sum(tf.math.real(sum_A), axis=[1, 2])\n\n    def get_density_matrix(self):\n        if self.polarization == \"vector\":\n            px, py, pz = [i() for i in self.polarization_vector]\n            zeros = tf.zeros_like(px)\n            ones = tf.ones_like(px)\n            rho00 = tf.complex(ones + pz, zeros)\n            rho11 = tf.complex(ones - pz, zeros)\n            rho01 = tf.complex(px, -py)\n            rho10 = tf.complex(px, py)\n            ret = 0.5 * tf.stack([[rho00, rho01], [rho10, rho11]])\n            # print(ret)\n            return ret\n        raise NotImplementedError\n\n    # @simple_cache_fun\n    def amp_index(self, gen=None, base_map=None):\n        if base_map is None:\n            base_map = self.get_base_map()\n        ret = [base_map[self.top]]\n        for i in self.outs:\n            ret.append(base_map[i])\n        return ret\n\n    def get_base_map(self, gen=None, base_map=None):\n        if gen is None:\n            gen = index_generator(base_map)\n        if base_map is None:\n            base_map = {self.top: next(gen)}\n        for i in self.outs:\n            base_map[i] = next(gen)\n        return base_map\n\n    def get_res_map(self):\n        res_map = {}\n        for i, decay in enumerate(self.chains):\n            for j in decay.inner:\n                if j not in res_map:\n                    res_map[j] = []\n                res_map[j].append(i)\n        return res_map\n\n    def set_used_res(self, res, only=False):\n        res_set = set()\n        for i in res:\n            if isinstance(i, str):\n                res_set.add(BaseParticle(i))\n            elif isinstance(i, BaseParticle):\n                res_set.add(i)\n            else:\n                raise TypeError(\n                    \"type({}) = {} not a Particle\".format(i, type(i))\n                )\n        if not only:\n            used_res = set()\n            for i in res_set:\n                for j, c in enumerate(self.chains):\n                    if i in c.inner:\n                        used_res.add(j)\n            self.set_used_chains(list(used_res))\n        else:\n            unused_res = set(self.resonances) - res_set\n            unused_decay = set()\n            res_map = self.get_res_map()\n            for i in unused_res:\n                for j in res_map[i]:\n                    unused_decay.add(j)\n            used_decay = []\n            for i, _ in enumerate(self.chains):\n                if i not in unused_decay:\n                    used_decay.append(i)\n            self.set_used_chains(used_decay)\n\n    def set_used_chains(self, used_chains):\n        self.chains_idx = list(used_chains)\n        if len(self.chains_idx) != len(self.chains):\n            self.not_full = True\n\n    def partial_weight(self, data, combine=None):\n        chains = list(self.chains)\n        if combine is None:\n            combine = [[i] for i in range(len(chains))]\n        o_used_chains = self.chains_idx\n        weights = []\n        for i in combine:\n            self.set_used_chains(i)\n            weight = self.sum_amp(data)\n            weights.append(weight)\n        self.set_used_chains(o_used_chains)\n        return weights\n\n    def chains_particle(self):\n        ret = []\n        for i in self:\n            ret.append(tuple(i.inner))\n        return ret\n\n    def partial_weight_interference(self, data):\n        chains = list(self.chains)\n        combine = combinations(range(len(chains)), 2)\n        o_used_chains = self.chains_idx\n        weights = {}\n        for i in combine:\n            self.set_used_chains(i)\n            weight = self.sum_amp(data)\n            weights[i] = weight\n        self.set_used_chains(o_used_chains)\n        return weights\n\n    def generate_phasespace(self, num=100000):\n        def get_mass(i):\n            mass = i.get_mass()\n            if mass is None:\n                raise Exception(\"mass is required for particle {}\".format(i))\n            return mass\n\n        top_mass = get_mass(self.top)\n        final_mass = [get_mass(i) for i in self.outs]\n        from tf_pwa.phasespace import PhaseSpaceGenerator\n\n        a = PhaseSpaceGenerator(top_mass, final_mass)\n        data = a.generate(num)\n        return dict(zip(self.outs, data))\n\n\ndef index_generator(base_map=None):\n    indices = \"abcdefghjklmnopqrstuvwxyz\"\n    if base_map is not None:\n        for i in base_map:\n            indices = indices.replace(base_map[i], \"\")\n    for i in indices:\n        yield i\n\n\ndef rename_data_dict(data, idx_map):\n    if isinstance(data, dict):\n        return {\n            idx_map.get(k, k): rename_data_dict(v, idx_map)\n            for k, v in data.items()\n        }\n    if isinstance(data, tuple):\n        return tuple([rename_data_dict(i, idx_map) for i in data])\n    if isinstance(data, list):\n        return [rename_data_dict(i, idx_map) for i in data]\n    return data\n\n\ndef value_and_grad(f, var):\n    with tf.GradientTape() as tape:\n        s = f(var)\n    g = tape.gradient(s, var)\n    return s, g\n\n\nclass AmplitudeModel(object):\n    def __init__(\n        self, decay_group, name=\"\", polar=None, vm=None, use_tf_function=False\n    ):\n        self.decay_group = decay_group\n        self._name = name\n        with variable_scope(vm) as vm:\n            if polar is not None:\n                vm.polar = polar\n            decay_group.init_params(name)\n        self.vm = vm\n        res = decay_group.resonances\n        self.used_res = res\n        self.res = res\n        self.f_data = []\n        if use_tf_function:\n            self.cached_fun = tf.function(\n                self.decay_group.sum_amp, experimental_relax_shapes=True\n            )\n        else:\n            self.cached_fun = self.decay_group.sum_amp\n\n    def __del__(self):\n        if hasattr(self, \"cached_fun\"):\n            del self.cached_fun\n        # super(AmplitudeModel, self).__del__()\n\n    def cache_data(self, data, split=None, batch=None):\n        for i in self.decay_group:\n            for j in i.inner:\n                print(j)\n        if split is None and batch is None:\n            return data\n        else:\n            n = data_shape(data)\n            if batch is None:  # split个一组，共batch组\n                batch = (n + split - 1) // split\n            ret = list(split_generator(data, batch))\n            return ret\n\n    def set_used_res(self, res):\n        self.decay_group.set_used_res(res)\n\n    def set_used_chains(self, used_chains):\n        self.decay_group.set_used_chains(used_chains)\n\n    def partial_weight(self, data, combine=None):\n        return self.decay_group.partial_weight(data, combine)\n\n    def partial_weight_interference(self, data):\n        return self.decay_group.partial_weight_interference(data)\n\n    def get_params(self, trainable_only=False):\n        return self.vm.get_all_dic(trainable_only)\n\n    def set_params(self, var):\n        self.vm.set_all(var)\n\n    @contextlib.contextmanager\n    def temp_params(self, var):\n        params = self.get_params()\n        self.set_params(var)\n        yield var\n        self.set_params(params)\n\n    def chains_particle(self):\n        return self.decay_group.chains_particle()\n\n    @property\n    def variables(self):\n        return self.vm.variables\n\n    @property\n    def trainable_variables(self):\n        return self.vm.trainable_variables\n\n    def __call__(self, data, cached=False):\n        if id(data) in self.f_data:\n            if not self.decay_group.not_full:\n                return self.cached_fun(data)\n        else:\n            self.f_data.append(id(data))\n        ret = self.decay_group.sum_amp(data)\n        return ret\n\n\ndef load_decfile_particle(fname):\n    with open(fname) as f:\n        dec = load_dec_file(f)\n    dec = list(dec)\n    particles = {}\n\n    def get_particles(name):\n        if name not in particles:\n            a = get_particle(name)\n            particles[name] = a\n        return particles[name]\n\n    decay = []\n    for i in dec:\n        cmd, var = i\n        if cmd == \"Particle\":\n            a = get_particles(var[\"name\"])\n            setattr(a, \"params\", var[\"params\"])\n        if cmd == \"Decay\":\n            for j in var[\"final\"]:\n                outs = [get_particles(k) for k in j[\"outs\"]]\n                de = Decay(get_particles(var[\"name\"]), outs)\n                for k in j:\n                    if k != \"outs\":\n                        setattr(de, k, j[k])\n                decay.append(de)\n        if cmd == \"RUNNINGWIDTH\":\n            pa = get_particles(var[0])\n            setattr(pa, \"running_width\", True)\n    top, inner, outs = split_particle_type(decay)\n    return top, inner, outs\n\n\nregist_config(DEFAULT_DECAY, (HelicityDecay, {}))\n", "meta": {"hexsha": "b2f416f29c256aabaa01f8f95a0dc9a5d01a5426", "size": 51374, "ext": "py", "lang": "Python", "max_stars_repo_path": "tf_pwa/amp/core.py", "max_stars_repo_name": "jiangyi15/tf-pwa", "max_stars_repo_head_hexsha": "17980750407a89bfd694e0b4f470332a886a3de9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-05-10T15:17:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-16T07:40:06.000Z", "max_issues_repo_path": "tf_pwa/amp/core.py", "max_issues_repo_name": "jiangyi15/tf-pwa", "max_issues_repo_head_hexsha": "17980750407a89bfd694e0b4f470332a886a3de9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 45, "max_issues_repo_issues_event_min_datetime": "2020-10-24T08:26:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T06:14:58.000Z", "max_forks_repo_path": "tf_pwa/amp/core.py", "max_forks_repo_name": "jiangyi15/tf-pwa", "max_forks_repo_head_hexsha": "17980750407a89bfd694e0b4f470332a886a3de9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-10-24T06:41:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T01:29:49.000Z", "avg_line_length": 32.6391359593, "max_line_length": 125, "alphanum_fraction": 0.5341028536, "include": true, "reason": "import numpy,import sympy", "num_tokens": 12799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.34864512179822554, "lm_q1q2_score": 0.19600009462342935}}
{"text": "import numpy as np\nimport scipy.stats as sps\nimport warnings\nfrom GOFevaluation.utils import equiprobable_histogram\nfrom GOFevaluation.utils import apply_irregular_binning\nfrom GOFevaluation.utils import plot_equiprobable_histogram\nfrom GOFevaluation.utils import check_sample_sanity\n\n\nclass EvaluatorBase(object):\n    \"\"\"Parent class for all evaluator base classes\"\"\"\n\n    def __init__(self):\n        self._name = self.__class__.__name__\n        self.gof = None\n        self.pvalue = None\n\n    def __repr__(self):\n        # return f'{self.__class__.__module__}, {self.__dict__}'\n        return f'{self.__class__.__module__}.{self.__class__.__qualname__}'\\\n            f'({self.__dict__.keys()})'\n\n    def __str__(self):\n        args = [self._name]\n        if self.gof is not None:\n            args.append(f'gof = {self.gof}')\n        if self.pvalue is not None:\n            args.append(f'p-value = {self.pvalue}')\n        args_str = \"\\n\".join(args)\n        return f'{self.__class__.__module__}\\n{args_str}'\n\n    @staticmethod\n    def calculate_gof():\n        raise NotImplementedError(\"calculate_gof is not implemented yet!\")\n\n    def get_gof(self):\n        raise NotImplementedError(\"get_gof is not implemented yet!\")\n\n    def get_pvalue(self):\n        raise NotImplementedError(\"get_pvalue is not implemented yet!\")\n\n\nclass EvaluatorBaseBinned(EvaluatorBase):\n    \"\"\"Evaluator base class for binned expectations reference input.\"\"\"\n\n    def __init__(self, data_sample, pdf, bin_edges, nevents_expected):\n        check_sample_sanity(data_sample)\n        super().__init__()\n        self.pdf = pdf\n        assert (isinstance(nevents_expected, int)\n                | isinstance(nevents_expected, np.int64)\n                | isinstance(nevents_expected, float)), \\\n            ('nevents_expected must be numeric but is of type '\n             + f'{type(nevents_expected)}.')\n        self.binned_reference = self.pdf * nevents_expected\n\n        if bin_edges is None:\n            # In this case data_sample is binned data!\n            assert (data_sample.shape == pdf.shape), \\\n                \"Shape of binned data does not match shape of the pdf!\"\n\n            # Convert to int. Make sure the deviation is purely from\n            # dtype conversion, i.e. the values provided are actually\n            # bin counts and not float values.\n            binned_data_int = np.abs(data_sample.round(0).astype(int))\n            assert (np.sum(np.abs(data_sample - binned_data_int)) < 1e-10), \\\n                'Deviation encounterd when converting dtype of binned_data to'\\\n                'int. Make sure binned_data contains natural numbers!'\n            self.binned_data = binned_data_int\n        else:\n            self.bin_data(data_sample=data_sample, bin_edges=bin_edges)\n        return\n\n    @classmethod\n    def from_binned(cls, binned_data, binned_reference):\n        \"\"\"Initialize with already binned data + expectations\n        \"\"\"\n        # bin_edges=None will set self.binned_data=binned_data\n        # in the init\n        return cls(data_sample=binned_data,\n                   pdf=binned_reference / np.sum(binned_reference),\n                   bin_edges=None,\n                   nevents_expected=np.sum(binned_reference))\n\n    @classmethod\n    def bin_equiprobable(cls, data_sample, reference_sample, nevents_expected,\n                         n_partitions, order=None, plot=False,\n                         plot_mode='sigma_deviation', **kwargs):\n        \"\"\"Initialize with data and reference sample that are binned\n        such that the expectation value is the same in each bin.\n        kwargs are passed to `plot_equiprobable_histogram` if plot is True.\n        \"\"\"\n        check_sample_sanity(data_sample)\n        check_sample_sanity(reference_sample)\n        if len(reference_sample) < 50 * len(data_sample):\n            warnings.warn(\n                f'Number of reference samples ({len(reference_sample)}) '\n                + 'should be much larger than number of data samples '\n                + f'({len(data_sample)}) to ensure negligible statistical '\n                + 'fluctuations for the equiprobable binning.', stacklevel=2)\n\n        pdf, bin_edges = equiprobable_histogram(\n            data_sample=reference_sample,\n            reference_sample=reference_sample,\n            n_partitions=n_partitions,\n            order=order)\n        pdf = pdf / np.sum(pdf)\n\n        binned_data = apply_irregular_binning(\n            data_sample=data_sample,\n            bin_edges=bin_edges,\n            order=order)\n\n        if plot:\n            plot_equiprobable_histogram(data_sample=data_sample,\n                                        bin_edges=bin_edges,\n                                        order=order,\n                                        nevents_expected=nevents_expected,\n                                        plot_mode=plot_mode,\n                                        **kwargs)\n\n        # bin_edges=None will set self.binned_data=binned_data\n        # in the init\n        return cls(data_sample=binned_data,\n                   pdf=pdf,\n                   bin_edges=None,\n                   nevents_expected=nevents_expected)\n\n    def bin_data(self, data_sample, bin_edges):\n        \"\"\"function to bin nD data sample\"\"\"\n        if len(data_sample.shape) == 1:\n            self.binned_data, _ = np.histogram(data_sample,\n                                               bins=bin_edges)\n        else:\n            self.binned_data, _ = np.histogramdd(data_sample,\n                                                 bins=bin_edges)\n\n        assert (self.binned_data.shape == self.pdf.shape), \\\n            \"Shape of binned data doesn not match shape of pdf!\"\n\n    def sample_gofs(self, n_mc=1000):\n        \"\"\"Generate fake GoFs for toy data sampled from binned reference\n\n        :param n_mc: Number of fake-gofs calculated, defaults to 1000\n        :type n_mc: int, optional\n        :return: Array of fake GoFs\n        :rtype: array_like\n        \"\"\"\n        fake_gofs = np.zeros(n_mc)\n        for i in range(n_mc):\n            samples = sps.poisson(self.binned_reference).rvs()\n            fake_gofs[i] = self.calculate_gof(\n                samples, self.binned_reference)\n        return fake_gofs\n\n    def _get_pvalue(self, n_mc=1000):\n        if self.gof is None:\n            _ = self.get_gof()\n        fake_gofs = self.sample_gofs(n_mc=n_mc)\n        percentile = sps.percentileofscore(fake_gofs, self.gof, kind='strict')\n        pvalue = 1 - percentile / 100\n\n        if pvalue == 0:\n            warnings.warn(f'p-value is 0.0. (Observed GoF: '\n                          f'{self.gof:.2e}, maximum of simulated GoFs: '\n                          f'{max(fake_gofs):.2e}). For a more '\n                          f'precise result, increase n_mc!', stacklevel=2)\n        elif pvalue == 1:\n            warnings.warn(f'p-value is 1.0. (Observed GoF '\n                          f'{self.gof:.2e}, minimum of simulated GoFs: '\n                          f'{min(fake_gofs):.2e}). For a more '\n                          f'precise result, increase n_mc!', stacklevel=2)\n\n        self.pvalue = pvalue\n        return pvalue, fake_gofs\n\n    def get_pvalue(self, n_mc=1000):\n        \"\"\"p-value is calculated\n\n        Computes the p-value by means of generating toyMCs and calculating\n        their GoF. The p-value can then be obtained from the distribution of\n        these fake-gofs.\n\n        :param n_mc: Number of fake-gofs calculated, defaults to 1000\n        :type n_mc: int, optional\n        :return: p-value\n        :rtype: float\n        \"\"\"\n        pvalue, _ = self._get_pvalue(n_mc=n_mc)\n        return pvalue\n\n    def get_pvalue_return_fake_gofs(self, n_mc=1000):\n        \"\"\"p-value is calculated\n\n        Computes the p-value by means of generating toyMCs and calculating\n        their GoF. The p-value can then be obtained from the distribution of\n        these fake-gofs. The array of fake-gofs is returned together with\n        the p-value.\n\n        :param n_mc: Number of fake-gofs calculated, defaults to 1000\n        :type n_mc: int, optional\n        :return: p-value\n        :rtype: float\n        \"\"\"\n        pvalue, fake_gofs = self._get_pvalue(n_mc=n_mc)\n        return pvalue, fake_gofs\n\n\nclass EvaluatorBasePdf(EvaluatorBase):\n    \"\"\"Evaluator base class for sample data, binned pdf reference input.\"\"\"\n\n    def __init__(self, data_sample, pdf):\n        check_sample_sanity(data_sample)\n        super().__init__()\n        self.data_sample = data_sample\n        self.pdf = pdf\n\n    def get_pvalue(self):\n        # This method is not implemented yet. We are working on adding it in\n        # the near future.\n        raise NotImplementedError(\"p-value computation not yet implemented!\")\n\n\nclass EvaluatorBaseSample(EvaluatorBase):\n    \"\"\"Evaluator base class for sample data and reference input.\"\"\"\n\n    def __init__(self, data_sample, reference_sample):\n        check_sample_sanity(data_sample)\n        check_sample_sanity(reference_sample)\n        super().__init__()\n        self.data_sample = data_sample\n        self.reference_sample = reference_sample\n\n    def permutation_gofs(self, n_perm=1000, d_min=None):\n        \"\"\"Generate fake GoFs by re-sampling data and reference sample\n\n        :param n_perm: Number of fake-gofs calculated, defaults to 1000\n        :type n_perm: int, optional\n        :param d_min: Only for PointToPointGOF, defaults to None\n        :type d_min: float, optional\n        :return: Array of fake GoFs\n        :rtype: array_like\n        \"\"\"\n        n_data = len(self.data_sample)\n        mixed_sample = np.concatenate([self.data_sample,\n                                       self.reference_sample],\n                                      axis=0)\n        fake_gofs = np.zeros(n_perm)\n        for i in range(n_perm):\n            rng = np.random.default_rng()\n            rng.shuffle(mixed_sample, axis=0)\n\n            data_perm = mixed_sample[:n_data]\n            reference_perm = mixed_sample[n_data:]\n            if d_min is not None:\n                fake_gofs[i] = self.calculate_gof(\n                    data_sample=data_perm, reference_sample=reference_perm,\n                    d_min=d_min)\n            else:\n                fake_gofs[i] = self.calculate_gof(\n                    data_sample=data_perm, reference_sample=reference_perm)\n        return fake_gofs\n\n    def _get_pvalue(self, n_perm=1000, d_min=None):\n        if self.gof is None:\n            if d_min is not None:\n                _ = self.get_gof(d_min=d_min)\n            else:\n                _ = self.get_gof()\n        fake_gofs = self.permutation_gofs(n_perm=n_perm, d_min=d_min)\n\n        percentile = sps.percentileofscore(fake_gofs, self.gof, kind='strict')\n        pvalue = 1 - percentile / 100\n\n        if pvalue == 0:\n            warnings.warn(f'p-value is 0.0. (Observed GoF: '\n                          f'{self.gof:.2e}, maximum of simulated GoFs: '\n                          f'{max(fake_gofs):.2e}). For a more '\n                          f'precise result, increase n_mc!', stacklevel=2)\n        elif pvalue == 1:\n            warnings.warn(f'p-value is 1.0. (Observed GoF '\n                          f'{self.gof:.2e}, minimum of simulated GoFs: '\n                          f'{min(fake_gofs):.2e}). For a more '\n                          f'precise result, increase n_mc!', stacklevel=2)\n        self.pvalue = pvalue\n\n        return pvalue, fake_gofs\n\n    def get_pvalue(self, n_perm=1000, d_min=None):\n        \"\"\"p-value is calculated\n\n        Computes the p-value by means of re-sampling data sample\n        and reference sample. For each re-sampling, the gof is calculated.\n        The p-value can then be obtained from the distribution of these\n        fake-gofs.\n\n        :param n_perm: Number of fake-gofs calculated, defaults to 1000\n        :type n_perm: int, optional\n        :return: p-value\n        :rtype: float\n        \"\"\"\n        pvalue, _ = self._get_pvalue(n_perm=n_perm, d_min=d_min)\n        return pvalue\n\n    def get_pvalue_return_fake_gofs(self, n_perm=1000, d_min=None):\n        \"\"\"p-value is calculated\n\n        Computes the p-value by means of re-sampling data sample\n        and reference sample. For each re-sampling, the gof is calculated.\n        The p-value can then be obtained from the distribution of these\n        fake-gofs. The array of fake-gofs is returned together with\n        the p-value.\n\n        :param n_perm: Number of fake-gofs calculated, defaults to 1000\n        :type n_perm: int, optional\n\n        :return: p-value, fake_gofs\n        :rtype: float\n        \"\"\"\n        pvalue, fake_gofs = self._get_pvalue(n_perm=n_perm, d_min=d_min)\n        return pvalue, fake_gofs\n", "meta": {"hexsha": "f96d1360b4e77518f8c7858c7a5342c2124495c7", "size": 12641, "ext": "py", "lang": "Python", "max_stars_repo_path": "GOFevaluation/evaluator_base.py", "max_stars_repo_name": "XENONnT/GOFevaluation", "max_stars_repo_head_hexsha": "ef34b2b0ee911d74cee0ba7c1fdcfc25dedb7350", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GOFevaluation/evaluator_base.py", "max_issues_repo_name": "XENONnT/GOFevaluation", "max_issues_repo_head_hexsha": "ef34b2b0ee911d74cee0ba7c1fdcfc25dedb7350", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-10-19T13:46:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-28T15:06:59.000Z", "max_forks_repo_path": "GOFevaluation/evaluator_base.py", "max_forks_repo_name": "XENONnT/GOFevaluation", "max_forks_repo_head_hexsha": "ef34b2b0ee911d74cee0ba7c1fdcfc25dedb7350", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2577639752, "max_line_length": 79, "alphanum_fraction": 0.5998734277, "include": true, "reason": "import numpy,import scipy", "num_tokens": 2864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.19600008950854927}}
{"text": "# Python modules\nimport ctypes\n\n# 3rd party modules\nimport numpy as np\nimport multiprocessing as mp\nimport xml.etree.cElementTree as ElementTree\n\n# Our modules\nimport vespa.analysis.constants as constants\nimport vespa.analysis.mrs_user_prior as mrs_user_prior\nimport vespa.analysis.block_fit_voigt as block_fit_voigt\n\nimport vespa.analysis.algos.wavelet_filter as wavelet_filter\n\nimport vespa.common.mrs_prior             as mrs_prior\nimport vespa.common.util.ppm              as util_ppm\nimport vespa.common.util.xml_             as util_xml\nimport vespa.common.util.math_            as util_math\nimport vespa.common.util.generic_spectral as util_spectral\n\nfrom vespa.common.constants import Deflate\nfrom vespa.analysis.constants import FitLineshapeModel\n\nfrom vespa.common.constants import DEGREES_TO_RADIANS as DTOR\nfrom vespa.analysis.algos.constrained_levenberg_marquardt import constrained_levenberg_marquardt as clm \n\n# Sad but true, we need these globals to be able to minimize the amount\n# of data and fitting parameters that are transferred to the processes\n\ndata = None\nchain = None\n\n\nclass ProcessChain(block_fit_voigt._Settings):\n    \"\"\"\n    A subclass of block_fit_voigt._Settings that will let us serialize\n    fitting information that can be sent to each process.  We add a dash\n    of values from mrs_dataset.Dataset to be able to use the util_ppm\n    methods. \n    \n    \"\"\"\n    # This is the version of this object's XML output format. \n    XML_VERSION = \"1.0.0\"\n\n    def __init__(self, attributes=None):\n        \n        block_fit_voigt._Settings.__init__(self)\n\n        # Spectral data information\n        self.frequency              = 124.0\n        self.sw                     = 1000.0\n        self.raw_dims               = []\n        self.raw_hpp                = 1.0\n        self.resppm                 = 4.7\n        self.echopeak               = 0.0\n        self.spectral_dims          = []\n        self.spectral_hpp           = 1.0\n        self.phase_1_pivot          = 2.01\n        self.zero_fill_multiplier   = 1\n\n        self.user_prior = mrs_user_prior.UserPrior()\n        self.metinfo    = self.user_prior.metinfo\n\n        # These are run-time attributes\n        \n        self.peakpts = []\n        self.basis_mets = None\n        self.init_results = None\n        self.fit_results = None\n\n        # Now if we are loading in data we can re-set a few attributes\n        \n        if attributes is not None:\n            self.inflate(attributes)\n\n            # Here are attributes that can be calculated if we are loading\n            # a ProcessChain object back into this instance. \n            \n            if self.prior.names != []:\n                self.prior_list = self.prior.names\n                #FIXME-bjs need new code to account for GISO fit method here! if needed.\n                self.prior.calculate_full_basis_set(self.prior_ppm_start, \n                                                    self.prior_ppm_end, \n                                                    self)\n                basis_mets = []\n                ppms       = []\n                peaks      = []\n                alist      = self.prior.basis_set_names\n                for name in sorted(alist):\n                    item = self.prior.basis_set[name]\n                    basis_mets.append(item.fid.copy())\n                    ppms += item.all_ppms\n                    peaks.append(item.peak_ppm)\n                    \n                self.peakpts        = self.ppm2pts(np.array(ppms))  \n                self.prior_peak_ppm = np.array(peaks)  # ppm is OK here\n                self.basis_mets     = np.array(basis_mets)\n                \n                self.fit_results    = np.zeros((self.nmet,), 'float')\n                self.init_results   = np.zeros((self.nmet,), 'float')\n\n        self.current_lw     = 5.0\n        self.data           = None\n        self.limits         = None\n        self.weight_array   = None\n        self.weight_array   = None\n        self.fit_baseline   = None\n        self.fit_stats      = None\n        \n\n    @property\n    def nmet(self):\n        if self.prior is not None:\n            return len(self.prior.names)\n        else:\n            return 0\n\n\n    def deflate(self, flavor=Deflate.ETREE):\n        if flavor == Deflate.ETREE:\n            # Make my base class do its deflate work\n            e = block_fit_voigt._Settings.deflate(self, flavor)\n\n            # Alter the tag name & XML version info   \n            e.tag = \"process_chain\"\n            e.set(\"version\", self.XML_VERSION)\n\n            # Add custom attributes here.\n            \n            # These attributes are all lists.\n            for attribute in (\"raw_dims\", \n                              \"spectral_dims\", ):\n                for value in getattr(self, attribute):\n                    util_xml.TextSubElement(e, attribute, value)\n                    \n            # These atttributes are all scalars and map directly to \n            # XML elements of the same name.\n            for attribute in (  \"frequency\",\n                                \"sw\",\n                                \"raw_hpp\",\n                                \"resppm\",\n                                \"echopeak\",\n                                \"spectral_hpp\",\n                                \"phase_1_pivot\",\n                                \"zero_fill_multiplier\",):\n                util_xml.TextSubElement(e, attribute, getattr(self, attribute))            \n\n            return e\n\n        \n    def inflate(self, source):   \n        if hasattr(source, \"makeelement\"):\n            # Quacks like an ElementTree.Element\n         \n            block_fit_voigt._Settings.inflate(self, source)\n                     \n            # We inflate in attributes grouped by type since there's so\n            # doggone many attrs on this class.\n            \n#             # Booleans\n#             for attribute in (\"xxx\", \"xxx\", ):\n#                 item = source.findtext(attribute)\n#                 if item is not None:\n#                     setattr(self, attribute, util_xml.BOOLEANS[item])\n            # floats\n            for attribute in (\"frequency\", \n                              \"sw\", \n                              \"raw_hpp\", \n                              \"resppm\",\n                              \"echopeak\",\n                              \"spectral_hpp\",\n                              \"phase_1_pivot\", ):\n                item = source.findtext(attribute)\n                if item is not None:\n                    setattr(self, attribute, float(item))\n\n            # ints\n            for attribute in (\"zero_fill_multiplier\", ):\n                item = source.findtext(attribute)\n                if item is not None:\n                    setattr(self, attribute, int(float(item)))\n\n#             # No translation required for these text attrs\n#             for attribute in (\"xxx\", \"xxx\", ):\n#                 item = source.findtext(attribute)\n#                 if item is not None:\n#                     setattr(self, attribute, item)\n\n            # lists\n            self.raw_dims       = [int(val.text) for val in source.getiterator(\"raw_dims\")]\n            self.spectral_dims  = [int(val.text) for val in source.getiterator(\"spectral_dims\")]\n\n\n    def fit_function(self, a,   pderflg=True, \n                                nobase=False, \n                                indiv=False,   \n                                finalwflg=False):\n    \n        # Setup constants and flags\n\n#         import os\n#         print \"fit_function: process id = {0}  got here 100 data={1})\".format(os.getpid(), self.data.shape )\n\n        nmet    = self.nmet\n        npts    = self.data.shape[0]\n        zfmult  = self.zero_fill_multiplier\n        nptszf  = round(npts * zfmult)\n        sw      = 1.0 * self.sw\n        td      = 1.0/sw\n        piv     = self.ppm2pts(self.phase_1_pivot, acq=True)\n        t2fix   = self.prior_fix_t2\n    \n        arr1    = np.zeros(npts,float) + 1.0\n        f       = np.zeros((nmet,nptszf),complex)  \n        mf      = np.zeros((nptszf,),complex)\n\n        t = (np.arange(nmet * npts) % npts) * td\n        t.shape = nmet, npts\n        mt = np.arange(npts) * td\n    \n        # get prior max peak ppm vals for metabs which are flagged ON\n        peaks   = self.prior_peak_ppm\n    \n        # setup Lineshape \n        if self.lineshape_model != FitLineshapeModel.GAUSS:\n            # voigt and lorentzian models\n            expo     = t/a[nmet*2] + (t/a[nmet*2+1])**2\n            lshape   = util_math.safe_exp(-expo)\n        else:\n            # Note. in the case of the Gaussian lineshape, we now allow the user to \n            # set a fixed T2 value for each metabolite. In the model call (fitt_funct.pro)\n            # we now create a lineshape array that takes each fixed value into account.\n            # BUT! we are still passing in a Tb parameter here, and though that parameter\n            # will be tightly constrained, it should still be in the range of the fixed\n            # physiologic params choosen by the user. At the moment, we have choosen to\n            # just set this parameter to 0.250 sec, which should be a reasonable average\n            # of 1H metabolite T2 values in the brain. It is then allowed to bop plus or\n            # minus 0.001 as set further below.  In the fitting function, we adjust each \n            # fixed value by the delta from 0.250 so that the pder will fluctuate as the\n            # parameter changes and not confuse the poor optimization routine. In reality,\n            # the 0.250 is never used, just the delta amount of the actual a[nmet*2]\n            # parameter from that value.\n    \n            ma     = (self.fix_t2_center - a[nmet*2]) + t2fix    # delta for Ta param that is set at 0.25 sec\n            ma     =  t/np.outer(ma, arr1)\n            mb     = (t / a[nmet*2+1])**2\n            expo   = ma+mb\n            lshape = util_math.safe_exp(-expo)            \n\n        if finalwflg:  \n            finalw = lshape[:,0]\n            finalw = util_spectral.full_width_half_max(np.fft.fft(util_spectral.chop(finalw))/len(finalw)) * self.spectral_hpp\n            return finalw\n    \n        # if FID, then for correct area, first point must be divided by 2\n\n        tmp  = self.basis_mets.copy()  \n        fre  = a[nmet:nmet*2] - self.ppm2hz(peaks)*2.0*np.pi    # in Radians here\n        fre  = np.exp( 1j * (np.outer(fre, arr1)) * t ) # outer is matrix multiplication\n        amp  = np.outer(a[0:nmet], arr1)\n        ph0  = np.outer(np.exp(1j * (np.zeros(nmet) + a[nmet*2+2])), arr1)    \n        tmp *= amp * fre * ph0 * lshape\n        f[:,0:npts] = tmp  \n\n        f[:,0] = f[:,0] / 2.0  \n    \n        # Calc Phase1 \n        phase1 = np.exp(1j * (a[nmet*2+3]*DTOR*(np.arange(nptszf,dtype=float)-piv)/nptszf))\n    \n        # Calculate Partial Derivatives  \n        pder = None\n        if pderflg:\n            pder = np.zeros((len(a),nptszf), complex)\n    \n            pall = np.sum(f,axis=0)   # all lines added\n    \n            pind = f\n            tt         = np.zeros(nptszf,float)\n            tt[0:npts] = np.arange(npts,dtype=float) * td\n    \n            for i in range(nmet):   # Calc the Ampl and Freq pders\n                pder[i,:]      = (np.fft.fft(pind[i,:] / a[i]   )/nptszf) * phase1\n                pder[i+nmet,:] = (np.fft.fft(tt * 1j * pind[i,:])/nptszf) * phase1\n            pder[nmet*2+0,:]  = (np.fft.fft(     tt     * pall/(a[nmet*2+0]**2))/nptszf) * phase1\n            pder[nmet*2+1,:]  = (np.fft.fft(2.0*(tt**2) * pall/(a[nmet*2+1]**3))/nptszf) * phase1\n    \n            pder[nmet*2+2,:]  = (np.fft.fft(1j*pall)/nptszf) * phase1 * nptszf\n            pder[nmet*2+3,:]  = (np.fft.fft(   pall)/nptszf) * (1j*DTOR*(np.arange(nptszf,dtype=float)-piv)/nptszf) * phase1\n    \n        # Do the FFT \n        if indiv:   # return individual lines\n            if nmet != 1: \n                for i in range(nmet): \n                    f[i,:] = (np.fft.fft(f[i,:])/nptszf) * phase1\n            else:\n                f = (np.fft.fft(f[0,:])/nptszf) * phase1\n        else:  # return summed spectrum    \n            if (nmet) != 1: \n                f = np.sum(f,axis=0)\n                f = (np.fft.fft(f)/nptszf) * phase1\n            else:\n                f = (np.fft.fft(f[0,:])/nptszf) * phase1\n    \n        # Add in baseline unless nobase is True ---\n        if not nobase:\n            if f.ndim > 1: \n                for i in range(len(f)): f[i,:] = f[i,:] + self.fit_baseline\n            else: \n                f = f + self.fit_baseline\n    \n        return f, pder          \n\n\n    def set_weight_array(self, lwidth=None, wtmult=None, wtmax=None):\n        \"\"\"\n        Creates a weight array to be used in the optimization based on setting in\n        the chain structure.  *(self.wtarr)) is set as the output.\n        \n        chain: ptr to optimization control structure\n    \n        \"\"\"\n        prior     = self.prior\n        metinfo   = self.metinfo\n    \n        abbr = [metinfo.get_abbreviation(item) for item in self.prior_list]\n        dim0 = self.spectral_dims[0]\n    \n        if not lwidth:\n            lwidth = self.initial_linewidth_value\n        else: \n            lwidth = float(lwidth) if lwidth > 0.1 else 0.1\n        \n        if not wtmult:\n            wtmult = self.optimize_weights_width_factor  \n        else: \n            wtmult = float(wtmult) if wtmult>0.0001 else 0.001\n            \n        if not wtmax:\n            wtmax  = dim0-1  \n        else: \n            wtmax  = float(wtmax)\n    \n        wtarr = np.zeros(dim0, float)\n    \n        if self.optimize_weights_method == constants.FitOptimizeWeightsMethod.EVEN_WEIGHTING:\n            wtarr = wtarr + 1.0  \n    \n        elif self.optimize_weights_method == constants.FitOptimizeWeightsMethod.LOCAL_WEIGHTING:\n            \n            lw = lwidth / self.spectral_hpp   # in points\n            centers = self.peakpts\n    \n            wid = lw * wtmult\n            wid = wid if lw<wtmax else wtmax\n    \n            for ctr in self.peakpts:\n                cs  = int(np.where(round(ctr-wid)>0, round(ctr-wid), 0))\n                cs  = int(np.where(cs<dim0, cs, dim0))\n                ce  = int(np.where(round(ctr+wid)>0, round(ctr+wid), 0))\n                ce  = int(np.where(ce<dim0, ce, dim0))\n                wtarr[cs:ce] = 1.0  \n    \n            # set small pk weight scale higher if needed len(chain.peakpts)\n            if self.optimize_weights_small_peak_factor != 1.0:\n                \n                ws = np.clip(int(np.round(self.ppm2pts(14.0))),0,dim0)\n                we = np.clip(int(np.round(self.ppm2pts(1.25))),0,dim0)\n                wtarr[ws:we] = wtarr[ws:we] * self.optimize_weights_small_peak_factor\n    \n                if 'lac' in abbr:\n                    ws = np.clip(int(np.round(self.ppm2pts(1.45))),0,dim0)\n                    we = np.clip(int(np.round(self.ppm2pts(1.25))),0,dim0)\n                    wtarr[ws:we] = 1.0  \n    \n                if 'naa' in abbr:\n                    ws = np.clip(int(np.round(self.ppm2pts(2.12))),0,dim0)\n                    we = np.clip(int(np.round(self.ppm2pts(1.85))),0,dim0)\n                    wtarr[ws:we] = 1.0  \n    \n                if 'cr' in abbr or 'cho' in abbr:\n                    ws = np.clip(int(np.round(self.ppm2pts(3.30))),0,dim0)\n                    we = np.clip(int(np.round(self.ppm2pts(2.85))),0,dim0)\n                    wtarr[ws:we] = 1.0  \n    \n            # Set and filter the weights\n            indx0 = np.where(wtarr == 0.0)[0]\n            if np.size(indx0) != 0: \n                wtarr[indx0] = 1.0 / self.optimize_weights_scale_factor        \n    \n            # set pks in water suppression low\n            if self.optimize_weights_water_flag:\n                ws = np.clip(int(np.round(self.ppm2pts(self.optimize_weights_water_end))),0,dim0)\n                we = np.clip(int(np.round(self.ppm2pts(self.optimize_weights_water_start))),0,dim0)\n                wtarr[ws:we] = 1.0 / self.optimize_weights_scale_factor\n    \n            # set pks in lipid area low\n            if self.optimize_weights_lipid_flag == 1:\n                ws = np.clip(int(np.round(self.ppm2pts(self.optimize_weights_lipid_end))),0,dim0)\n                we = np.clip(int(np.round(self.ppm2pts(self.optimize_weights_lipid_start))),0,dim0)\n                wtarr[ws:we] = 1.0 / self.optimize_weights_scale_factor\n    \n            wtarr = wtarr / max(wtarr)\n    \n        return wtarr\n    \n    \n    def set_initial_values(self, indx):\n        \n        # indx will be used in future\n        \n        inival = [  1.7,6.0,10.0, 3.21,3.01,2.02, 0.06, 0.06,   0.1,  0.1]\n        limits = [[ 1.4,4.8, 8.0, 3.31,2.85,1.80, 0.03, 0.06, -20.0,-50.1],\n                  [ 1.9,7.2,12.0, 3.14,3.10,2.22, 100.0,100.0, 20.0,50.1]]\n        \n        self.current_lw    = 5.0\n        self.init_results  = np.array(inival)\n        self.fit_results   = np.array(inival)\n        \n        self.fit_results[0:3] *= 0.8\n        self.fit_results[4:6] += 0.015\n        self.fit_results[9]    = 12.0\n        \n        self.limits = np.array(limits)\n                            \n\n\ndef _create_default_prior():\n    # This creates & returns a Prior object populated with some default\n    # metabs. It's exists just so that something shows up when users first\n    # open this tab.\n    metabolites = { \"n-acetylaspartate\" : { \"spins\" : 3, \n                                            \"ppm\"   : 2.01,   \n                                            \"area\"  : 3.0,\n                                            \"phase\" : 0.0,\n                                          },\n                    \"creatine\"          : { \"spins\" : 3, \n                                            \"ppm\"   : 3.01,   \n                                            \"area\"  : 3.0,\n                                            \"phase\" : 0.0,\n                                          },\n                    \"choline\"          : { \"spins\"  : 9, \n                                            \"ppm\"   : 3.21,   \n                                            \"area\"  : 9.0,\n                                            \"phase\" : 0.0,\n                                          },\n                  }\n\n    deflated_metabolites = [ ]\n    for name, metabolite in metabolites.items():\n        d = { \"name\" : name,\n              \"spins\" : metabolite[\"spins\"],\n              \"dims\" : [0, 0, 0],\n              \"group\" : [0],\n              \"ppms\" : [metabolite[\"ppm\"]],\n              \"areas\" : [metabolite[\"area\"]],\n              \"phases\" : [metabolite[\"phase\"]],\n            }\n        deflated_metabolites.append(d)\n\n             \n    d = { \"source\" : \"default\",\n          \"source_id\" : \"default\",\n          \"comment\" : \"This is a typical 1H singlet prior basis set.\",\n          \"nucleus\" : \"1H\",\n          \"seqte\"  : 0.07, \n          \"prior_metabolites\" : deflated_metabolites,\n        }\n\n    return mrs_prior.Prior(d)      \n\n\n        \n\ndef init_chain(npts=1024, sw=1024.0):\n    \"\"\"\n    This is only called in main process on startup to enable us to create\n    fake data and a string version of the deflated XML object that can be\n    sent to each process and resuscitated into a local copy for fitting data\n    \n    \"\"\"\n\n    # this is local\n    chain = ProcessChain()\n\n    chain.prior                     = _create_default_prior()\n    chain.prior_list                = chain.prior.names\n    \n    chain.frequency                 = 124.0\n    chain.sw                        = sw\n    chain.raw_dims                  = np.array([npts,])\n    chain.raw_hpp                   = chain.sw / float(npts) \n    chain.resppm                    = 4.7\n    chain.echopeak                  = 0.0\n    chain.spectral_dims             = np.array([npts,])\n    chain.spectral_hpp              = chain.sw / float(npts)\n    chain.phase_1_pivot             = 2.01\n    chain.zero_fill_multiplier      = 1    \n    \n    chain.prior_fix_t2                      = [200.0 for i in range(chain.nmet)]\n    chain.initial_linewidth_value           = 6.0\n    chain.baseline_wavelet_scale            = 16.0\n    chain.baseline_wavelet_min_dyad         = 4\n    chain.lineshape_model                   = FitLineshapeModel.VOIGT\n    chain.optimize_max_iterations           = 100\n    chain.optimize_stop_tolerance           = 0.005\n    chain.optimize_global_iterations        = 6\n    chain.optimize_weights_width_factor     = 4.0\n    chain.optimize_weights_scale_factor     = 3.0\n    chain.optimize_weights_method           = constants.FitOptimizeWeightsMethod.LOCAL_WEIGHTING\n    chain.optimize_weights_water_flag       = True\n    chain.optimize_weights_water_end        = 4.2\n    chain.optimize_weights_water_start      = 5.2\n    chain.optimize_weights_lipid_flag       = False\n    chain.optimize_weights_lipid_end        = 1.7\n    chain.optimize_weights_lipid_start      = 0.9\n    chain.optimize_weights_small_peak_factor= 1.0\n\n    #FIXME-bjs need new code to account for GISO fit method here! if needed.\n    chain.prior.calculate_full_basis_set(chain.prior_ppm_start, chain.prior_ppm_end, chain)\n\n    basis_mets = []\n    ppms       = []\n    peaks      = []\n    alist      = chain.prior.basis_set_names\n    for name in sorted(alist):\n        item = chain.prior.basis_set[name]\n        basis_mets.append(item.fid.copy())\n        ppms += item.all_ppms\n        peaks.append(item.peak_ppm)\n        \n    chain.peakpts        = chain.ppm2pts(np.array(ppms))  \n    chain.prior_peak_ppm = np.array(peaks)  # ppm is OK here\n    chain.basis_mets     = np.array(basis_mets)\n\n    strout = chain.deflate()\n    util_xml.indent(strout)\n    strout = ElementTree.tostring(strout, \"utf-8\")\n    \n    return strout\n\n\ndef init_model():\n    \"\"\" Create a single ideal spectrum as basis for creating fake data \"\"\"\n    \n    global chain\n    chain.set_initial_values(0)   # need this input parameters here\n    \n    # Create fake data model\n    a = chain.init_results.copy()\n    nmet = chain.nmet\n    a[nmet:nmet*2] = chain.ppm2hz(a[nmet:nmet*2], acq=True)*2.0*np.pi\n    a[nmet*2+2]    = a[nmet*2+2] * np.pi / 180.0 \n    if a[nmet*2]   == 0.0: a[nmet*2]   = 0.000001\n    if a[nmet*2+1] == 0.0: a[nmet*2+1] = 0.000001\n\n    chain.data = np.zeros((chain.spectral_dims[0],),'complex')\n    model, _ = chain.fit_function(a, pderflg=False, nobase=True)\n    \n    return model\n \n  \n    \ndef do_baseline():\n\n    global chain\n\n#     import os\n#     print \"do_baseline: process id = {0}  got here 10 )\".format(os.getpid(), )\n    \n    data = chain.data.copy()\n\n    a = chain.fit_results.copy()\n    model, _ = chain.fit_function(a, pderflg=False, nobase=True)\n\n    # Subtract metabolite model from data \n    basr = data.real - model.real\n    basi = data.imag - model.imag\n\n    # Estimate the baseline from the residual spectral calculated above.\n    thresh  = chain.current_lw / chain.spectral_hpp\n    scale   = int(chain.baseline_wavelet_scale)\n    dyadmin = int(chain.baseline_wavelet_min_dyad)\n\n    baser = wavelet_filter.wavelet_filter(basr, thresh, scale, dyadmin=dyadmin)\n    basei = wavelet_filter.wavelet_filter(basi, thresh, scale, dyadmin=dyadmin)\n\n    base = baser + 1j * basei  # Make complex array from real and imaginary parts\n\n    chain.fit_baseline = base\n    \n    \ndef do_model():\n    \n    global chain\n\n    data  = chain.data.copy()\n    nmet  = chain.nmet\n    a     = chain.fit_results.copy()\n    ww    = chain.weight_array\n    lim   = chain.limits.copy()\n    itmax = chain.optimize_max_iterations\n    toler = chain.optimize_stop_tolerance\n    funct = chain.fit_function\n\n    # optimize the model\n    yfit, a, sig, chis, wchis, badfit = clm(data, ww, a, lim, funct, itmax, toler)\n\n    # copy results into chain object so the do_baseline method can get them\n    chain.fit_results = a.copy()\n    chain.fit_stats   = np.array([chis, wchis, badfit])\n    chain.fit_plot    = yfit\n\n    chain.fitted_lw, _ = util_spectral.voigt_width(a[nmet*2], a[nmet*2+1], chain)    \n    \n\ndef check_out(dest, chain):\n    \"\"\" helper function - converts PPMs to Hz and Phase degrees to radians \"\"\"\n    nmet = chain.nmet\n    dest[nmet:nmet*2] = chain.ppm2hz(dest[nmet:nmet*2], acq=True)*2.0*np.pi\n    dest[nmet*2+2]    = dest[nmet*2+2] * np.pi / 180.0 \n    if dest[nmet*2]   == 0.0: dest[nmet*2]   = 0.000001\n    if dest[nmet*2+1] == 0.0: dest[nmet*2+1] = 0.000001\n    return dest\n\ndef check_in(dest, chain):\n    \"\"\" helper function - converts Hz to PPMs and Phase radians to degrees \"\"\"\n    nmet = chain.nmet\n    dest[nmet:nmet*2] = chain.hz2ppm(dest[nmet:nmet*2]/(2.0*np.pi), acq=True)\n    dest[nmet*2+2]    = dest[nmet*2+2] * 180.0 / np.pi\n    return dest\n\n\ndef tonumpyarray(mp_arr):\n    \"\"\" helper function to re-cast the shared array to a numpy array \"\"\"\n    return np.frombuffer(mp_arr.get_obj())\n\n\ndef do_loop_kernel(indx):\n    \"\"\"\n    This is where each spectrum is fitted over N iterations of baseline\n    and spectral model estimation and optimization respectively.\n    \n    We return the optimized spectral model parameters and index of the voxel\n    so we can sort the results list in the main process after they have all\n    been fitted.\n    \n    \"\"\"\n    global data\n    global chain\n\n#     import os\n#     print \"do_loop_kernel: proc_id={0} indx={1})\".format(os.getpid(), indx)\n    \n    # load FID from shared array into chain object\n    _data  = tonumpyarray(data)\n    _datac = _data.view('complex64')\n    str = chain.spectral_dims[0] * indx # compute offset since we flattened it\n    end = str + chain.spectral_dims[0]\n    chain.data = _datac[str:end]\n\n    # set initial values and limits here - hard set for this example\n    chain.set_initial_values(indx)\n    chain.init_results = check_out(chain.init_results, chain)\n    chain.limits[0,:]  = check_out(chain.limits[0,:].copy(), chain)\n    chain.limits[1,:]  = check_out(chain.limits[1,:].copy(), chain)\n    \n    # calculate weight array ... likely should be in baseline/model loop\n    chain.weight_array = chain.set_weight_array()\n    chain.fit_results = chain.init_results.copy() \n    chain.fit_results[0:chain.nmet] *= 0.8 \n\n    for k in range(chain.optimize_global_iterations):\n        do_baseline()\n        do_model()\n\n    result = check_in(chain.fit_results, chain)\n    \n    return (indx, result)\n\n\ndef do_process_init(xmlstring, shared_arr):\n\n    import os\n#     narr = 0 if shared_arr is None else len(shared_arr)\n#     print \"do_process_init: process id = {0}  xml_len({1}) data_len({2}))\".format(os.getpid(),len(xmlstring),narr)\n\n    global chain\n    tree = ElementTree.ElementTree(ElementTree.fromstring(xmlstring))\n    attributes = tree.getroot()\n    chain = ProcessChain(attributes)\n    \n    if shared_arr is not None:\n        global data\n        data = shared_arr\n    \n\n\ndef do_loop(nvox, xmlstring, shared_arr):\n\n    global data\n    global chain\n\n    inputs = list(range(nvox))\n\n    pool_size = 10 if mp.cpu_count() < 10 else mp.cpu_count()\n    \n    if pool_size > nvox:\n        pool_size = nvox\n     \n    pool = mp.Pool(processes=pool_size, \n                   initializer=do_process_init,\n                   initargs=(xmlstring,shared_arr) )\n    \n    pool_outputs = pool.map(do_loop_kernel, inputs)\n    pool.close() # no more tasks\n    pool.join()  # wrap up current tasks\n    \n    # Get process results from the output list\n    pool_outputs.sort()\n    results = np.array([r[1] for r in pool_outputs])\n    \n    return results\n\n\ndef run_tests():\n    \"\"\"\n    Ran some tests on my T3500 with 6 cores and HT = 12 cores\n    \n    There's a major hit at the startup of the processes, on the order of 24\n    seconds or so ...\n    \n    Here's the breakdown:\n     1         3.51 sec\n     2         5.40 sec\n     10       23.44 sec\n     50       29.81 sec\n     100      31.84 sec\n     800      64.41 sec\n    \n    \"\"\"\n#     from pylab import *\n\n    nvox = 100\n    \n    # I test this convoluted way of initializing global chain variable here so \n    # I know that it will perform well in the processes without having to printf\n    # my way through a distributed debug session\n    \n    xmlstring  = init_chain()           # deflated object with values for fake data set properly\n    do_process_init(xmlstring, None)    # inflate and set equal to the global chain variable\n\n    global chain\n    \n    # Create fake data and a shared array that will be accessed by all the \n    # distributed processes. Init model uses the inital values set in the \n    # chain object. We then add different data to this model to create nvox\n    # distinct sets of data.\n    \n    model = init_model()\n    fake_data = np.zeros((nvox,chain.raw_dims[0]), 'complex64')\n\n    ndbl = nvox * chain.spectral_dims[0] * 2    # for complex data\n    shared_arr = mp.Array(ctypes.c_float, ndbl)\n    arr = tonumpyarray(shared_arr).view('complex64')    \n    \n    for i in range(nvox):\n        noiser = np.random.randn(chain.raw_dims[0])\n        noisei = np.random.randn(chain.raw_dims[0])\n        noise  = noiser + 1j*noisei\n        fake_data[i,:] = model + noise * 0.02\n    \n    tmp = _data.flatten()\n    arr[:] = tmp\n    \n    # We are ready to start the processes, initialize them and then use them\n    # to fit the fake data. The results list stores fitted parameters for \n    # each data entry in the order they are in the shared_array\n    \n    results = do_loop(nvox, xmlstring, shared_arr)\n      \n    # Check the results to see if the first set of fitted parameters\n    # and the visulization of the overlaid fit on the data is good.\n    # Note. We do not actually have the fitted baseline results where\n    # we can plot them in this example ... something for the future.\n      \n    print('fit - init =' + str(results[0,:] - chain.init_results))    \n\n    a = results[0,:].copy()\n    a = check_out(a, chain)\n    fit, _ = chain.fit_function(a, pderflg=False, nobase=True)\n\n#     plot(_data[0,:])\n#     plot(fit)\n#     plot(chain.fit_baseline)\n#     plot(chain.weight_array)\n#     show()\n\n    bob = 10\n    bob = bob + 1\n    \n\n\n\n\n\nif __name__ == '__main__':\n\n    import cProfile\n    cProfile.run('run_tests()')\n\n#    run_tests()", "meta": {"hexsha": "d233b38b33b1089ca6ee75ad24756391c4c291e8", "size": 29864, "ext": "py", "lang": "Python", "max_stars_repo_path": "vespa/analysis/test_multi_optimize_pool.py", "max_stars_repo_name": "vespa-mrs/vespa", "max_stars_repo_head_hexsha": "6d3e84a206ec427ac1304e70c7fadf817432956b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vespa/analysis/test_multi_optimize_pool.py", "max_issues_repo_name": "vespa-mrs/vespa", "max_issues_repo_head_hexsha": "6d3e84a206ec427ac1304e70c7fadf817432956b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-04-17T13:58:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T14:19:57.000Z", "max_forks_repo_path": "vespa/analysis/test_multi_optimize_pool.py", "max_forks_repo_name": "vespa-mrs/vespa", "max_forks_repo_head_hexsha": "6d3e84a206ec427ac1304e70c7fadf817432956b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-06-05T16:34:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T16:13:22.000Z", "avg_line_length": 36.7783251232, "max_line_length": 126, "alphanum_fraction": 0.5531074203, "include": true, "reason": "import numpy", "num_tokens": 7691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301064, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.19595851311604393}}
{"text": "# This file is part of LayerModel_lib\n#\n#     A tool to compute the transmission behaviour of plane electromagnetic waves\n#     through human tissue.\n#\n# Copyright (C) 2018 Jan-Christoph Brumm\n#\n# Licensed under MIT license.\n#\n\"\"\"\nA small example showing how to generate a layer model for specific coordinates inside the chosen VoxelModel.\nAdditionally, the transfer function for S_21 and E-, and H-field are compared for surface to in-body communication\nand vice versa\n\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom LayerModel_lib import VoxelModel, LayerModel, Coordinate\nfrom config import phantom_path\n\nVoxelModel.working_directory = phantom_path\nall_models = VoxelModel.list_all_voxel_models()\nfor model in all_models:\n    print(model)\n\n# Load a virtual human model\nvm = VoxelModel('AustinMan_v2.5_2x2x2')\n\nstart = Coordinate([231, 270, 1110])  # some point in the colon\nend = Coordinate([330, 277, 1110])  # some point outside the body\n\n# calculate the layer model from two of these points\nlm = LayerModel(vm, start, end)\n\n# show info about the model\nlm.print_info()\n\n# Calculate the transfer function for S21 (square root of transmitted power) from 0 to 10 GHz with 1024 samples,\n# the default direction is 'start->end'\n(transfer_function, frequency) = lm.S21(f_start=3.1e9, f_end=4.8e9, n_samples=1024)\n\n# plot the magnitude\nhf, ha = plt.subplots(nrows=2)\nha[0].plot(frequency / 1e9, 20 * np.log10(np.abs(transfer_function)))\nha[0].set_xlabel(\"Frequency in GHz\")\nha[0].set_ylabel(\"Magnitude in dB\")\nha[0].set_title(\"Transfer Function between the two coordinates\")\n\nha[1].plot(frequency / 1e9, np.unwrap(np.angle(transfer_function), axis=0))\nha[1].set_xlabel(\"Frequency in GHz\")\nha[1].set_ylabel(\"Phase in rad\")\nplt.tight_layout()\nplt.show()\n", "meta": {"hexsha": "144f88462ea5cb3e5cb63002d085ed5e3a83a643", "size": 1764, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/transfer_function_from_voxelmodel.py", "max_stars_repo_name": "janbrumm/layermodel_lib", "max_stars_repo_head_hexsha": "0d5e0c9ac77d302910823ebc757a4ec99541f3ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/transfer_function_from_voxelmodel.py", "max_issues_repo_name": "janbrumm/layermodel_lib", "max_issues_repo_head_hexsha": "0d5e0c9ac77d302910823ebc757a4ec99541f3ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/transfer_function_from_voxelmodel.py", "max_forks_repo_name": "janbrumm/layermodel_lib", "max_forks_repo_head_hexsha": "0d5e0c9ac77d302910823ebc757a4ec99541f3ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0727272727, "max_line_length": 114, "alphanum_fraction": 0.7590702948, "include": true, "reason": "import numpy", "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.19595850429142145}}
{"text": "import numpy as np\nimport subprocess\n\nfrom numpy import (\n    zeros,\n    pi,\n    floor_divide,\n    loadtxt,\n    max as np_max,\n    min as np_min,\n    sign,\n    angle as np_angle,\n)\nfrom os.path import basename, splitext\nfrom SciDataTool import DataTime, VectorField, Data1D\nfrom os.path import join\n\nfrom ....Functions.Winding.gen_phase_list import gen_name\n\n\nfrom ....Classes.Magnetics import Magnetics\nfrom ....Functions.labels import (\n    AIRGAP_LAB,\n    ROTOR_LAB_S,\n    short_label,\n    decode_label,\n    get_obj_from_label,\n    LAM_LAB_S,\n    STATOR_LAB_S,\n    HOLEV_LAB_S,\n    HOLEM_LAB_S,\n    WIND_LAB_S,\n    MAG_LAB,\n    SHAFT_LAB,\n    NO_LAM_LAB,\n    SLID_LAB,\n    BOT_LAB,\n)\nfrom ....Functions.Winding.find_wind_phase_color import get_phase_id\nfrom .... import __version__\nfrom ....Functions.get_path_binary import get_path_binary\n\nfrom ....Classes.HoleM50 import HoleM50\nfrom ....Classes.HoleM51 import HoleM51\nfrom ....Classes.HoleM52 import HoleM52\nfrom ....Classes.HoleM53 import HoleM53\nfrom ....Classes.MachineSIPMSM import MachineSIPMSM\nfrom ....Classes.MachineIPMSM import MachineIPMSM\nfrom ....Methods import NotImplementedYetError\n\n\ndef solve_FEA(self, output, sym, angle, time, angle_rotor, Is, Ir):\n    \"\"\"\n    Solve Elmer model to calculate airgap flux density, torque instantaneous/average/ripple values,\n    flux induced in stator windings and flux density, field and permeability maps\n\n    Parameters\n    ----------\n    self: MagElmer\n        A MagElmer object\n    output: Output\n        An Output object\n    sym: int\n        Spatial symmetry factor\n    time: ndarray\n        Time vector for calculation\n    angle: ndarray\n        Angle vector for calculation\n    Is : ndarray\n        Stator current matrix (qs,Nt) [A]\n    Ir : ndarray\n        Stator current matrix (qs,Nt) [A]\n    angle_rotor: ndarray\n        Rotor angular position vector (Nt,)\n    \"\"\"\n\n    project_name = self.get_path_save_fea(output)\n    elmermesh_folder = project_name\n    mesh_names_file = join(project_name, \"mesh.names\")\n    boundaries = {}\n    bodies = {}\n    machine = output.simu.machine\n    BHs = output.geo.stator.BH_curve  # Stator B(H) curve\n    BHr = output.geo.rotor.BH_curve  # Rotor B(H) curve\n    # Is = output.elec.Is  # Stator currents waveforms\n    # Ir = output.elec.Ir  # Rotor currents waveforms\n    Speed = output.elec.OP.get_N0()\n    rotor_mat_file = join(project_name, \"rotor_material.pmf\")\n    stator_mat_file = join(project_name, \"stator_material.pmf\")\n\n    # TO-DO: Time vector must be greater than one\n    timesize_str = np.array2string(\n        np.diff(time), separator=\" \", formatter={\"float_kind\": lambda x: \"%.2e\" % x}\n    )\n    time = np.append(time, time[1] + time[-1])\n    timesize_str = np.array2string(\n        np.diff(time), separator=\" \", formatter={\"float_kind\": lambda x: \"%.2e\" % x}\n    )\n    timelen = len(time) - 1\n    ones_str = np.array2string(\n        np.ones(timelen), separator=\" \", formatter={\"int\": lambda x: \"%d\" % x}\n    )\n    timeinterval_str = ones_str.replace(\".\", \"\")\n\n    with open(mesh_names_file, \"rt\") as f:\n        for line in f:\n            fields = line.strip().split()\n            if fields[0] == \"$\":\n                field_name = fields[1]\n                field_value = fields[3]\n                # update dictionary\n                # _settings['Geometry'][field_name] = field_value\n                if field_name.count(\"BOUNDARY\"):\n                    boundaries[field_name] = field_value\n                else:\n                    bodies[field_name] = {\n                        \"id\": field_value,\n                        \"mat\": 1,  # Air by Default\n                        \"eq\": 1,  # RigidMeshMapper by Default\n                        \"bf\": None,\n                        \"tg\": None,\n                    }\n\n    with open(rotor_mat_file, \"wt\") as ro:\n        ro.write(\"! File Generated by pyleecan v{0}\\n\".format(__version__))\n        ro.write(\n            \"! Material Name: {0}\\n\"\n            \"! B-H Curve Rotor Material\\n\"\n            \"Electric Conductivity = 0\\n\"\n            \"H-B Curve = Variable coupled iter\\n\"\n            \" Real\\t\\tCubic Monotone\\n\".format(machine.rotor.mat_type.name)\n        )\n        for ii in range(BHr.shape[0]):\n            ro.write(\"   {0}\\t\\t{1}\\n\".format(BHr[ii][1], BHr[ii][0]))\n        ro.write(\"End\\n\")\n\n    with open(stator_mat_file, \"wt\") as ro:\n        ro.write(\"! File Generated by pyleecan v{0}\\n\".format(__version__))\n        ro.write(\n            \"! Material Name: {0}\\n\"\n            \"! B-H Curve Stator Material\\n\"\n            \"Electric Conductivity = 0\\n\"\n            \"H-B Curve = Variable coupled iter\\n\"\n            \" Real\\t\\tCubic Monotone\\n\".format(machine.stator.mat_type.name)\n        )\n        for ii in range(BHs.shape[0]):\n            ro.write(\"   {0}\\t\\t{1}\\n\".format(BHs[ii][1], BHs[ii][0]))\n        ro.write(\"End\\n\")\n\n    elmer_sim_file = join(project_name, \"pyleecan_elmer.sif\")\n    pp = machine.stator.winding.p\n    wind_mat = machine.stator.winding.get_connection_mat(machine.stator.slot.Zs)\n    surf_wind = machine.stator.slot.comp_surface_active()\n    ror = machine.rotor.comp_radius_mec()\n    sir = machine.stator.comp_radius_mec()\n    with open(elmer_sim_file, \"wt\") as fo:\n        fo.write(\"! File Generated by pyleecan v{0}\\n\".format(__version__))\n        fo.write(\n            \"$ WM = 2*pi*{0}/60        ! Mechanical Frequency [rad/s]\\n\".format(Speed)\n        )\n        fo.write(\"$ PP = {0}                ! Pole pairs\\n\".format(pp))\n        fo.write(\"$ WE = PP*WM              ! Electrical Frequency [Hz]\\n\")\n\n        if isinstance(machine, MachineSIPMSM):\n            # magnet_0 = machine.rotor.slot.magnet[0]\n            magnet_0 = machine.rotor.magnet\n        elif isinstance(machine, MachineIPMSM):\n            magnet_dict = machine.rotor.hole[0].get_magnet_dict()\n            magnet_0 = magnet_dict[\"magnet_0\"]\n        else:\n            self.get_logger().info(\"ElmerSolver [Error]: Unsupported Machine Geometry\")\n            return False\n\n        surf_list = machine.build_geometry(sym=sym)\n        pm_index = 6\n        Mangle = list()\n        Ncond_Aplus = 1\n        Ncond_Aminus = 1\n        Ncond_Bplus = 1\n        Ncond_Bminus = 1\n        Ncond_Cplus = 1\n        Ncond_Cminus = 1\n        Ncond_Dplus = 1\n        Ncond_Dminus = 1\n        Ncond_Eplus = 1\n        Ncond_Eminus = 1\n        Ncond_Fplus = 1\n        Ncond_Fminus = 1\n        Npcp = machine.stator.winding.Npcp\n        for surf in surf_list:\n            label = short_label(surf.label)\n            label_dict = decode_label(label)\n            point_ref = surf.point_ref\n            if HOLEM_LAB_S in label_dict[\"surf_type\"]:  # LamHole\n                mag_obj = get_obj_from_label(machine, label_dict=label_dict)\n                if mag_obj.type_magnetization == 1:  # Parallel\n                    magnetization_type = \"parallel\"\n                    # calculate pole angle and angle of pole middle\n                    T_id = label_dict[\"T_id\"]\n                    hole = mag_obj.parent\n                    Zh = hole.Zh\n                    alpha_p = 360 / Zh\n                    mag_0 = (\n                        floor_divide(np_angle(point_ref, deg=True), alpha_p) + 0.5\n                    ) * alpha_p\n\n                    mag_dict = hole.comp_magnetization_dict()\n                    mag = mag_0 + mag_dict[\"magnet_\" + str(T_id)] * 180 / pi\n                    # modifiy magnetisation of south poles\n                    if (label_dict[\"S_id\"] % 2) == 1:\n                        mag = mag + 180\n                else:\n                    raise NotImplementedYetError(\n                        \"Only parallele magnetization are available for HoleMagnet\"\n                    )\n                if bodies.get(label, None) is not None:\n                    Mangle.append(mag)\n                    bodies[label][\"mat\"] = pm_index\n                    bodies[label][\"eq\"] = 1\n                    bodies[label][\"bf\"] = 1\n                    bodies[label][\"tg\"] = 1\n                    pm_index = pm_index + 1\n            elif MAG_LAB in label_dict[\"surf_type\"]:\n                mag_obj = get_obj_from_label(machine, label_dict=label_dict)\n                if mag_obj.type_magnetization == 0 and (label_dict[\"S_id\"] % 2) == 0:\n                    mag = 0  # North pole magnet\n                    magnetization_type = \"radial\"\n                elif mag_obj.type_magnetization == 0:\n                    mag = 180  # South pole magnet\n                    magnetization_type = \"radial\"\n                elif mag_obj.type_magnetization == 1 and (label_dict[\"S_id\"] % 2) == 0:\n                    mag = np_angle(point_ref) * 180 / pi  # North pole magnet\n                    magnetization_type = \"parallel\"\n                elif mag_obj.type_magnetization == 1:\n                    mag = np_angle(point_ref) * 180 / pi + 180  # South pole magnet\n                    magnetization_type = \"parallel\"\n                elif mag_obj.type_magnetization == 2:\n                    Zs = mag_obj.parent.slot.Zs\n                    mag = str(-(Zs / 2 - 1)) + \" * theta + 90 \"\n                    magnetization_type = \"hallback\"\n                else:\n                    continue\n                if bodies.get(label, None) is not None:\n                    Mangle.append(mag)\n                    bodies[label][\"mat\"] = pm_index\n                    bodies[label][\"eq\"] = 1\n                    bodies[label][\"bf\"] = 1\n                    bodies[label][\"tg\"] = 1\n                    pm_index = pm_index + 1\n            elif WIND_LAB_S in label_dict[\"surf_type\"]:\n                lam_obj = get_obj_from_label(machine, label_dict=label_dict)\n                wind_mat = lam_obj.winding.get_connection_mat(lam_obj.get_Zs())\n                Nrad_id = label_dict[\"R_id\"]  # zone radial coordinate\n                Ntan_id = label_dict[\"T_id\"]  # zone tangential coordinate\n                Zs_id = label_dict[\"S_id\"]  # Zone slot number coordinate\n                # Get the phase value in the correct slot zone\n                q_id = get_phase_id(wind_mat, Nrad_id, Ntan_id, Zs_id)\n                Ncond = wind_mat[Nrad_id, Ntan_id, Zs_id, q_id]\n                s = sign(Ncond)\n                if bodies.get(label, None) is not None:\n                    bodies[label][\"mat\"] = 5\n                    bodies[label][\"eq\"] = 1\n                    if q_id == 0 and s == 1:\n                        bodies[label][\"bf\"] = 2\n                        Ncond_Aplus = abs(Ncond)\n                    elif q_id == 0 and s == -1:\n                        bodies[label][\"bf\"] = 3\n                        Ncond_Aminus = abs(Ncond)\n                    elif q_id == 1 and s == 1:\n                        bodies[label][\"bf\"] = 4\n                        Ncond_Bplus = abs(Ncond)\n                    elif q_id == 1 and s == -1:\n                        bodies[label][\"bf\"] = 5\n                        Ncond_Bminus = abs(Ncond)\n                    elif q_id == 2 and s == 1:\n                        bodies[label][\"bf\"] = 6\n                        Ncond_Cplus = abs(Ncond)\n                    elif q_id == 2 and s == -1:\n                        bodies[label][\"bf\"] = 7\n                        Ncond_Cminus = abs(Ncond)\n                    elif q_id == 3 and s == 1:\n                        bodies[label][\"bf\"] = 8\n                        Ncond_Dplus = abs(Ncond)\n                    elif q_id == 3 and s == -1:\n                        bodies[label][\"bf\"] = 9\n                        Ncond_Dminus = abs(Ncond)\n                    elif q_id == 4 and s == 1:\n                        bodies[label][\"bf\"] = 10\n                        Ncond_Eplus = abs(Ncond)\n                    elif q_id == 4 and s == -1:\n                        bodies[label][\"bf\"] = 11\n                        Ncond_Eminus = abs(Ncond)\n                    elif q_id == 5 and s == 1:\n                        bodies[label][\"bf\"] = 12\n                        Ncond_Fplus = abs(Ncond)\n                    elif q_id == 5 and s == -1:\n                        bodies[label][\"bf\"] = 13\n                        Ncond_Fminus = abs(Ncond)\n                    else:\n                        pass\n            elif (\n                LAM_LAB_S in label_dict[\"surf_type\"]\n                and ROTOR_LAB_S in label_dict[\"lam_label\"]\n                and bodies.get(label, None) is not None\n            ):\n                bodies[label][\"mat\"] = 4\n                bodies[label][\"eq\"] = 1\n                bodies[label][\"bf\"] = 1\n                bodies[label][\"tg\"] = 1\n            elif (\n                LAM_LAB_S in label_dict[\"surf_type\"]\n                and STATOR_LAB_S in label_dict[\"lam_label\"]\n                and bodies.get(label, None) is not None\n            ):\n                bodies[label][\"mat\"] = 3\n                bodies[label][\"eq\"] = 1\n            elif (\n                SHAFT_LAB in label_dict[\"surf_type\"]\n                and bodies.get(label, None) is not None\n            ):\n                bodies[label][\"mat\"] = 1\n                bodies[label][\"eq\"] = 1\n                bodies[label][\"bf\"] = 1\n                bodies[label][\"tg\"] = 1\n            elif (\n                HOLEV_LAB_S in label_dict[\"surf_type\"]\n                and bodies.get(label, None) is not None\n            ):\n                bodies[label][\"mat\"] = 1\n                bodies[label][\"eq\"] = 1\n                bodies[label][\"bf\"] = 1\n                bodies[label][\"tg\"] = 1\n            else:\n                pass\n\n        # The following bodies are not in the dictionary\n        bodies[ROTOR_LAB_S + \"-0_\" + AIRGAP_LAB + BOT_LAB][\"bf\"] = 1\n        bodies[NO_LAM_LAB + \"_\" + SLID_LAB + BOT_LAB][\"bf\"] = 1  # Sliding band bottom\n\n        No_Magnets = pm_index - 6\n        magnet_temp = 20.0  # Magnet Temperature Fixed for now\n        Hcm20 = magnet_0.mat_type.mag.Hc\n        Brm20 = magnet_0.mat_type.mag.Brm20\n        kt = 0.01  # Br Temperature Coefficient fixed for now\n        Br = Brm20 * (1 + kt * 0.01 * (magnet_temp - 20.0))\n        magnet_permeability = magnet_0.mat_type.mag.mur_lin\n        rho20_m = magnet_0.mat_type.elec.rho\n        kt_m = 0.01  # Rho Temperature Coefficient fixed for now\n        rho_m = rho20_m * (1 + kt_m * (magnet_temp - 20.0))\n        conductivity_m = 0.0 * 1.0 / rho_m\n\n        skip_steps = 1  # Fixed for now\n        degrees_step = 1  # Fixed for now\n        current_angle = 0 - pp * degrees_step * skip_steps\n        angle_shift = self.angle_rotor_shift - self.angle_stator_shift\n        rotor_init_pos = machine.comp_angle_rotor_initial() + angle_shift\n        rotor_d_axis = machine.rotor.comp_angle_d_axis() * 180.0 / pi\n        Ncond = 1  # Fixed for Now\n        Cp = 1  # Fixed for Now\n        qs = len(machine.stator.get_name_phase())\n\n        fo.write(\n            \"$ H_PM = {0}              ! Magnetization [A/m]\\n\".format(round(Hcm20, 2))\n        )\n        fo.write(\"$ Shift = 2*pi/{0}        ! N-phase machine [rad]\\n\".format(qs))\n        fo.write(\n            \"$ Gamma = {0}*pi/180      ! Current Angle [rad]\\n\".format(\n                round(current_angle, 2)\n            )\n        )\n        fo.write(\"$ Ncond = {0}             ! Conductors per coil\\n\".format(Ncond))\n        fo.write(\"$ Cp = {0}                ! Parallel paths\\n\".format(Cp))\n        fo.write(\"$ Is = {0}                ! Stator current [A]\\n\".format(0.0))\n        fo.write(\"$ Aaxis = {0}             ! Axis Coil A [deg]\\n\".format(0.0))\n        fo.write(\n            \"$ Carea = {0}             ! Coil Side Conductor Area [m2]\\n\".format(\n                surf_wind\n            )\n        )\n\n        for mm in range(1, No_Magnets + 1):\n            fo.write(\n                \"$ Mangle{0} = {1}     ! Magnetization Angle [deg]\\n\".format(\n                    mm, round(Mangle[mm - 1], 2)\n                )\n            )\n\n        fo.write(\"$ Nsteps = {0}            !\\n\".format(2))\n        fo.write(\"$ StepDegrees = {0}       !\\n\".format(degrees_step))\n        fo.write(\"$ DegreesPerSec = WM*180.0/pi  !\\n\")\n        fo.write(\"$ RotorInitPos = {}!\\n\".format(round(rotor_init_pos * 180.0 / pi, 2)))\n\n        fo.write(\n            \"\\nHeader\\n\"\n            \"\\tCHECK KEYWORDS Warn\\n\"\n            '\\tMesh DB \"{0}\"\\n'\n            '\\tInclude Path \".\"\\n'\n            '\\tResults Directory \"{1}\"\\n'\n            \"End\\n\".format(elmermesh_folder, elmermesh_folder)\n        )\n\n        fo.write(\"\\nConstants\\n\" \"\\tPermittivity of Vacuum = 8.8542e-12\\n\" \"End\\n\")\n\n        fo.write(\n            \"\\nSimulation\\n\"\n            \"\\tMax Output Level = 4\\n\"\n            \"\\tCoordinate System = Cartesian 2D\\n\"\n            \"\\tCoordinate Scaling = {0}\\n\"\n            \"\\tSimulation Type = Transient\\n\"\n            \"\\tTimestepping Method = BDF\\n\"\n            \"\\tBDF Order = 2\\n\"\n            #                 \"\\tTimestep Sizes = $ (StepDegrees / DegreesPerSec)  ! sampling time\\n\"\n            #                 \"\\tTimestep Intervals = $ Nsteps              ! steps\\n\"\n            #                 \"\\tOutput Intervals = 1\\n\"\n            \"\\tTimestep Sizes({1}) = {2}\\n\"\n            \"\\tTimestep Intervals({1}) = {3}\\n\"\n            \"\\tUse Mesh Names = Logical True\\n\"\n            \"End\\n\".format(1.0, timelen, timesize_str[1:-1], timeinterval_str[1:-1])\n        )\n\n        fo.write(\"\\n!--- MATERIALS ---\\n\")\n        fo.write(\n            \"Material 1\\n\"\n            '\\tName = \"Air\"\\n'\n            \"\\tRelative Permeability = 1\\n\"\n            \"\\tElectric Conductivity = 0\\n\"\n            \"End\\n\"\n        )\n\n        fo.write(\n            \"\\nMaterial 2\\n\"\n            '\\tName = \"Insulation\"\\n'\n            \"\\tRelative Permeability = 1\\n\"\n            \"\\tElectric Conductivity = 0\\n\"\n            \"End\\n\"\n        )\n\n        fo.write(\n            \"\\nMaterial 3\\n\"\n            '\\tName = \"StatorMaterial\"\\n'\n            '\\tInclude \"{0}\"\\n'\n            \"End\\n\".format(stator_mat_file)\n        )\n\n        fo.write(\n            \"\\nMaterial 4\\n\"\n            '\\tName = \"RotorMaterial\"\\n'\n            '\\tInclude \"{0}\"\\n'\n            \"End\\n\".format(rotor_mat_file)\n        )\n\n        winding_temp = 20.0  # Fixed for Now\n        rho20 = machine.stator.winding.conductor.cond_mat.elec.rho\n        kt = 0.01  # Br Temperature Coefficient fixed for now\n        rho = rho20 * (1 + kt * (winding_temp - 20.0))\n        conductivity = 0.0 * 1.0 / rho\n\n        fo.write(\n            \"\\nMaterial 5\\n\"\n            '\\tName = \"Copper\"\\n'\n            \"\\tRelative Permeability = 1\\n\"\n            \"\\tElectric Conductivity = {0}\\n\"\n            \"End\\n\".format(round(conductivity, 2))\n        )\n\n        magnets_per_pole = No_Magnets  # TO-DO: Assumes only one pole drawn\n        for m in range(1, magnets_per_pole + 1):\n            mat_number = 5 + m\n            if magnetization_type == \"parallel\":\n                fo.write(\n                    \"\\nMaterial {0}\\n\"\n                    '\\tName = \"PM_{1}\"\\n'\n                    \"\\tRelative Permeability = {2}\\n\"\n                    \"\\tMagnetization 1 = Variable time, timestep size\\n\"\n                    '\\t\\tReal MATC  \"H_PM*cos(WM*(tx(0)-tx(1)) + {3}*pi/PP + {3}*pi + (RotorInitPos + Mangle{1})*pi/180)\"\\n'\n                    \"\\tMagnetization 2 = Variable time, timestep size\\n\"\n                    '\\t\\tReal MATC \"H_PM*sin(WM*(tx(0)-tx(1)) + {3}*pi/PP + {3}*pi + (RotorInitPos + Mangle{1})*pi/180)\"\\n'\n                    \"\\tElectric Conductivity = {4}\\n\"\n                    \"End\\n\".format(\n                        mat_number,\n                        m,\n                        magnet_permeability,\n                        int((m - 1) / magnets_per_pole),\n                        round(conductivity_m, 2),\n                    )\n                )\n            elif magnetization_type == \"radial\":\n                fo.write(\n                    \"\\nMaterial {0}\\n\"\n                    '\\tName = \"PM_{1}\"\\n'\n                    \"\\tRelative Permeability = {2}\\n\"\n                    \"\\tMagnetization 1 = Variable Coordinate\\n\"\n                    '\\t\\tReal MATC  \"H_PM*cos(atan2(tx(1),tx(0)) + {3}*pi + Mangle{1}*pi/180)\"\\n'\n                    \"\\tMagnetization 2 = Variable Coordinate\\n\"\n                    '\\t\\tReal MATC \"H_PM*sin(atan2(tx(1),tx(0)) + {3}*pi + Mangle{1}*pi/180)\"\\n'\n                    \"\\tElectric Conductivity = {4}\\n\"\n                    \"End\\n\".format(\n                        mat_number,\n                        m,\n                        magnet_permeability,\n                        m - 1,\n                        round(conductivity_m, 2),\n                    )\n                )\n            elif magnetization_type == \"perpendicular\":\n                fo.write(\n                    \"\\nMaterial {0}\\n\"\n                    '\\tName = \"PM_{1}\"\\n'\n                    \"\\tRelative Permeability = {2}\\n\"\n                    \"\\tMagnetization 1 = Variable time, timestep size\\n\"\n                    '\\t\\tReal MATC  \"H_PM*cos(WM*(tx(0)-tx(1)) + {3}*pi/PP + {3}*pi + Aaxis*pi/180 + (Mangle{1}*pi/180))\"\\n'\n                    \"\\tMagnetization 2 = Variable time, timestep size\\n\"\n                    '\\t\\tReal MATC \"H_PM*sin(WM*(tx(0)-tx(1)) + {3}*pi/PP + {3}*pi + Aaxis*pi/180 + (Mangle{1}*pi/180))\"\\n'\n                    \"\\tElectric Conductivity = {4}\\n\"\n                    \"End\\n\".format(\n                        mat_number,\n                        m,\n                        magnet_permeability,\n                        int((m - 1) / magnets_per_pole),\n                        round(conductivity_m, 2),\n                    )\n                )\n            else:\n                fo.write(\n                    \"\\nMaterial {0}\\n\"\n                    '\\tName = \"PM_{1}\"\\n'\n                    \"\\tRelative Permeability = {2}\\n\"\n                    \"\\tElectric Conductivity = {4}\\n\"\n                    \"End\\n\".format(\n                        mat_number, m, magnet_permeability, round(conductivity_m, 2)\n                    )\n                )\n\n        fo.write(\"\\n!--- BODY FORCES ---\\n\")\n\n        # fo.write(\"Body Force 1\\n\"\n        #          \"\\tName = \\\"BodyForce_Rotation\\\"\\n\"\n        #          \"\\t$omega = (180/pi)*WM\\n\"\n        #          \"\\tMesh Rotate 3 = Variable time, timestep size\\n\"\n        #          \"\\t\\tReal MATC \\\"omega*(tx(0)-tx(1)) + RotorInitPos\\\"\\n\"\n        #          \"End\\n\")\n        fo.write(\n            \"Body Force 1\\n\"\n            '\\tName = \"BodyForce_Rotation\"\\n'\n            \"\\tMesh Rotate 3 = Variable time\\n\"\n            \"\\t\\tReal\\n\"\n            \"\\t\\t0.0\\t\\t0.0\\n\"\n        )\n        for tt in range(1, timelen + 1):\n            fo.write(\n                \"\\t\\t{:.2e}\\t\\t{:.3f}\\n\".format(\n                    time[tt], angle_rotor[tt - 1] * 180.0 / pi\n                )\n            )\n        fo.write(\"\\tEnd\\n\" \"End\\n\")\n\n        # fo.write(\"Body Force 2\\n\"\n        #          \"\\tName = \\\"J_A_PLUS\\\"\\n\"\n        #          \"\\tCurrent Density = Variable time, timestep size\\n\"\n        #          \"\\t\\tReal MATC \\\"(Is/Carea) * ({0}/Cp) * sin(WE * (tx(0)-tx(1)) + Gamma)\\\"\\n\"\n        #          \"End\\n\".format(Ncond_Aplus))\n\n        # fo.write(\"Body Force 3\\n\"\n        #          \"\\tName = \\\"J_A_MINUS\\\"\\n\"\n        #          \"\\tCurrent Density = Variable time, timestep size\\n\"\n        #          \"\\t\\tReal MATC \\\"-(Is/Carea) * ({0}/Cp) * sin(WE * (tx(0)-tx(1)) + Gamma)\\\"\\n\"\n        #          \"End\\n\".format(Ncond_Aminus))\n\n        # fo.write(\"Body Force 4\\n\"\n        #          \"\\tName = \\\"J_B_PLUS\\\"\\n\"\n        #          \"\\tCurrent Density = Variable time, timestep size\\n\"\n        #          \"\\t\\tReal MATC \\\"(Is/Carea) * ({0}/Cp) * sin(WE * (tx(0)-tx(1)) - Shift + Gamma)\\\"\\n\"\n        #          \"End\\n\".format(Ncond_Bplus))\n        #\n        # fo.write(\"Body Force 5\\n\"\n        #          \"\\tName = \\\"J_B_MINUS\\\"\\n\"\n        #          \"\\tCurrent Density = Variable time, timestep size\\n\"\n        #          \"\\t\\tReal MATC \\\"-(Is/Carea) * ({0}/Cp) * sin(WE * (tx(0)-tx(1)) - Shift + Gamma)\\\"\\n\"\n        #          \"End\\n\".format(Ncond_Bminus))\n        #\n        # fo.write(\"Body Force 6\\n\"\n        #          \"\\tName = \\\"J_C_PLUS\\\"\\n\"\n        #          \"\\tCurrent Density = Variable time, timestep size\\n\"\n        #          \"\\t\\tReal MATC \\\"(Is/Carea) * ({0}/Cp) * sin(WE * (tx(0)-tx(1)) - 2*Shift + Gamma)\\\"\\n\"\n        #          \"End\\n\".format(Ncond_Cplus))\n        #\n        # fo.write(\"Body Force 7\\n\"\n        #          \"\\tName = \\\"J_C_MINUS\\\"\\n\"\n        #          \"\\tCurrent Density = Variable time, timestep size\\n\"\n        #          \"\\t\\tReal MATC \\\"-(Is/Carea) * ({0}/Cp) * sin(WE * (tx(0)-tx(1)) - 2*Shift + Gamma)\\\"\\n\"\n        #          \"End\\n\".format(Ncond_Cminus))\n        #\n        # fo.write(\"Body Force 8\\n\"\n        #          \"\\tName = \\\"J_D_PLUS\\\"\\n\"\n        #          \"\\tCurrent Density = Variable time, timestep size\\n\"\n        #          \"\\t\\tReal MATC \\\"(Is/Carea) * ({0}/Cp) * sin(WE * (tx(0)-tx(1)) - 3*Shift + Gamma)\\\"\\n\"\n        #          \"End\\n\".format(Ncond_Dplus))\n        #\n        # fo.write(\"Body Force 9\\n\"\n        #          \"\\tName = \\\"J_D_MINUS\\\"\\n\"\n        #          \"\\tCurrent Density = Variable time, timestep size\\n\"\n        #          \"\\t\\tReal MATC \\\"-(Is/Carea) * ({0}/Cp) * sin(WE * (tx(0)-tx(1)) - 3*Shift + Gamma)\\\"\\n\"\n        #          \"End\\n\".format(Ncond_Dminus))\n        #\n        # fo.write(\"Body Force 10\\n\"\n        #          \"\\tName = \\\"J_E_PLUS\\\"\\n\"\n        #          \"\\tCurrent Density = Variable time, timestep size\\n\"\n        #          \"\\t\\tReal MATC \\\"(Is/Carea) * ({0}/Cp) * sin(WE * (tx(0)-tx(1)) - 4*Shift + Gamma)\\\"\\n\"\n        #          \"End\\n\".format(Ncond_Eplus))\n        #\n        # fo.write(\"Body Force 11\\n\"\n        #          \"\\tName = \\\"J_E_MINUS\\\"\\n\"\n        #          \"\\tCurrent Density = Variable time, timestep size\\n\"\n        #          \"\\t\\tReal MATC \\\"-(Is/Carea) * ({0}/Cp) * sin(WE * (tx(0)-tx(1)) - 4*Shift + Gamma)\\\"\\n\"\n        #          \"End\\n\".format(Ncond_Eminus))\n        #\n        # fo.write(\"Body Force 12\\n\"\n        #          \"\\tName = \\\"J_F_PLUS\\\"\\n\"\n        #          \"\\tCurrent Density = Variable time, timestep size\\n\"\n        #          \"\\t\\tReal MATC \\\"(Is/Carea) * ({0}/Cp) * sin(WE * (tx(0)-tx(1)) - 5*Shift + Gamma)\\\"\\n\"\n        #          \"End\\n\".format(Ncond_Fplus))\n        #\n        # fo.write(\"Body Force 13\\n\"\n        #          \"\\tName = \\\"J_F_MINUS\\\"\\n\"\n        #          \"\\tCurrent Density = Variable time, timestep size\\n\"\n        #          \"\\t\\tReal MATC \\\"-(Is/Carea) * ({0}/Cp) * sin(WE * (tx(0)-tx(1)) - 5*Shift + Gamma)\\\"\\n\"\n        #          \"End\\n\".format(Ncond_Fminus))\n\n        fo.write(\n            \"Body Force 2\\n\"\n            '\\tName = \"J_A_PLUS\"\\n'\n            \"\\tCurrent Density = Variable time\\n\"\n            \"\\t\\tReal\\n\"\n            \"\\t\\t0.0\\t\\t0.0\\n\"\n        )\n        for tt in range(1, timelen + 1):\n            fo.write(\n                \"\\t\\t{:.2e}\\t\\t{:.3f}\\n\".format(\n                    time[tt], Ncond_Aplus * Is[0, tt - 1] / surf_wind\n                )\n            )\n        fo.write(\"\\tEnd\\n\" \"End\\n\")\n\n        fo.write(\n            \"Body Force 3\\n\"\n            '\\tName = \"J_A_MINUS\"\\n'\n            \"\\tCurrent Density = Variable time\\n\"\n            \"\\t\\tReal\\n\"\n            \"\\t\\t0.0\\t\\t0.0\\n\"\n        )\n        for tt in range(1, timelen + 1):\n            fo.write(\n                \"\\t\\t{:.2e}\\t\\t{:.3f}\\n\".format(\n                    time[tt], -Ncond_Aminus * Is[0, tt - 1] / surf_wind\n                )\n            )\n        fo.write(\"\\tEnd\\n\" \"End\\n\")\n\n        fo.write(\n            \"Body Force 4\\n\"\n            '\\tName = \"J_B_PLUS\"\\n'\n            \"\\tCurrent Density = Variable time\\n\"\n            \"\\t\\tReal\\n\"\n            \"\\t\\t0.0\\t\\t0.0\\n\"\n        )\n        for tt in range(1, timelen + 1):\n            fo.write(\n                \"\\t\\t{:.2e}\\t\\t{:.3f}\\n\".format(\n                    time[tt], Ncond_Bplus * Is[1, tt - 1] / surf_wind\n                )\n            )\n        fo.write(\"\\tEnd\\n\" \"End\\n\")\n\n        fo.write(\n            \"Body Force 5\\n\"\n            '\\tName = \"J_B_MINUS\"\\n'\n            \"\\tCurrent Density = Variable time\\n\"\n            \"\\t\\tReal\\n\"\n            \"\\t\\t0.0\\t\\t0.0\\n\"\n        )\n        for tt in range(1, timelen + 1):\n            fo.write(\n                \"\\t\\t{:.2e}\\t\\t{:.3f}\\n\".format(\n                    time[tt], -Ncond_Bminus * Is[1, tt - 1] / surf_wind\n                )\n            )\n        fo.write(\"\\tEnd\\n\" \"End\\n\")\n\n        fo.write(\n            \"Body Force 6\\n\"\n            '\\tName = \"J_C_PLUS\"\\n'\n            \"\\tCurrent Density = Variable time\\n\"\n            \"\\t\\tReal\\n\"\n            \"\\t\\t0.0\\t\\t0.0\\n\"\n        )\n        for tt in range(1, timelen + 1):\n            fo.write(\n                \"\\t\\t{:.2e}\\t\\t{:.3f}\\n\".format(\n                    time[tt], Ncond_Cplus * Is[2, tt - 1] / surf_wind\n                )\n            )\n        fo.write(\"\\tEnd\\n\" \"End\\n\")\n\n        fo.write(\n            \"Body Force 7\\n\"\n            '\\tName = \"J_C_MINUS\"\\n'\n            \"\\tCurrent Density = Variable time\\n\"\n            \"\\t\\tReal\\n\"\n            \"\\t\\t0.0\\t\\t0.0\\n\"\n        )\n        for tt in range(1, timelen + 1):\n            fo.write(\n                \"\\t\\t{:.2e}\\t\\t{:.3f}\\n\".format(\n                    time[tt], -Ncond_Cminus * Is[2, tt - 1] / surf_wind\n                )\n            )\n        fo.write(\"\\tEnd\\n\" \"End\\n\")\n\n        fo.write(\"\\n!--- BODIES ---\\n\")\n        for k, v in bodies.items():\n            bid = bodies[k][\"id\"]\n            beq = bodies[k][\"eq\"]\n            bmat = bodies[k][\"mat\"]\n            bf = bodies[k][\"bf\"]\n            btg = bodies[k][\"tg\"]\n            fo.write(\n                \"Body {0}\\n\"\n                \"\\tName = {1}\\n\"\n                \"\\tEquation = {2}\\n\"\n                \"\\tMaterial = {3}\\n\".format(bid, k, beq, bmat)\n            )\n            if bf is not None:\n                fo.write(\"\\tBody Force = {0}\\n\".format(bf))\n            if btg is not None:\n                fo.write(\"\\tTorque Groups = Integer {0}\\n\".format(btg))\n            if k == \"SB_INT\":\n                fo.write(\n                    \"\\tR Inner = Real {0}\\n\" \"\\tR Outer = Real {1}\\n\".format(ror, sir)\n                )\n            fo.write(\"End\\n\\n\")\n\n        fo.write(\n            \"Equation 1\\n\"\n            '\\tName = \"Model_Domain\"\\n'\n            \"\\tActive Solvers(6) = 1 2 3 4 5 6\\n\"\n            \"End\\n\"\n        )\n\n        fo.write(\"\\n!--- SOLVERS ---\\n\")\n        fo.write(\n            \"Solver 1\\n\"\n            \"\\tExec Solver = Before Timestep\\n\"\n            \"\\tEquation = MeshDeform\\n\"\n            '\\tProcedure = \"RigidMeshMapper\" \"RigidMeshMapper\"\\n'\n            \"End\\n\"\n        )\n\n        fo.write(\n            \"\\nSolver 2\\n\"\n            \"\\tEquation = MgDyn2D\\n\"\n            '\\tProcedure = \"MagnetoDynamics2D\" \"MagnetoDynamics2D\"\\n'\n            \"\\tExec Solver = Always\\n\"\n            \"\\tVariable = A\\n\"\n        )\n        fo.write(\"\\tNonlinear System Convergence Tolerance = {0}\\n\".format(1e-6))\n        fo.write(\"\\tNonlinear System Max Iterations = {0}\\n\".format(100))\n        fo.write(\"\\tNonlinear System Min Iterations = {0}\\n\".format(1))\n        fo.write(\"\\tNonlinear System Newton After Iterations = {0}\\n\".format(5))\n        fo.write(\"\\tNonlinear System Relaxation Factor = {0}\\n\".format(0.9))\n        fo.write(\n            \"\\tNonlinear System Convergence Without Constraints = {0}\\n\".format(\n                \"Logical True\"\n            )\n        )\n        fo.write(\"\\tExport Lagrange Multiplier = {0}\\n\".format(\"Logical True\"))\n        fo.write(\"\\tLinear System Abort Not Converged = {0}\\n\".format(\"Logical False\"))\n        fo.write(\"\\tLinear System Solver = {0}\\n\".format(\"Direct\"))\n        fo.write(\"\\tLinear System Direct Method = {0}\\n\".format(\"umfpack\"))\n        fo.write(\"\\tOptimize Bandwidth = {0}\\n\".format(\"Logical True\"))\n        fo.write(\"\\tLinear System Preconditioning =  {0}\\n\".format(\"ILU2\"))\n        fo.write(\"\\tLinear System Max Iterations =  {0}\\n\".format(5000))\n        fo.write(\"\\tLinear System Residual Output =  {0}\\n\".format(20))\n        fo.write(\"\\tLinear System Convergence Tolerance =  {0}\\n\".format(1e-7))\n        fo.write(\"\\tMortar BCs Additive =  {0}\\n\".format(\"Logical True\"))\n        fo.write(\"End\\n\")\n\n        fo.write(\n            \"\\nSolver 3\\n\"\n            \"\\tExec Solver = Always\\n\"\n            \"\\tEquation = CalcFields\\n\"\n            '\\tPotential Variable = \"A\"\\n'\n            '\\tProcedure = \"MagnetoDynamics\" \"MagnetoDynamicsCalcFields\"\\n'\n            \"\\tCalculate Nodal Forces = Logical True\\n\"\n            \"\\tCalculate Magnetic Vector Potential = Logical True\\n\"\n            \"\\tCalculate Winding Voltage = Logical True\\n\"\n            \"\\tCalculate Current Density = Logical True\\n\"\n            \"\\tCalculate Maxwell Stress = Logical True\\n\"\n            \"\\tCalculate JxB = Logical True\\n\"\n            \"\\tCalculate Magnetic Field Strength = Logical True\\n\"\n            \"End\\n\"\n        )\n\n        fo.write(\n            \"\\nSolver 4\\n\"\n            \"\\tExec Solver = After Timestep\\n\"\n            '\\tProcedure = \"ResultOutputSolve\" \"ResultOutputSolver\"\\n'\n            '\\tOutput File Name = \"{0}\"\\n'\n            \"\\tVtu Format = True\\n\"\n            \"\\tBinary Output = True\\n\"\n            \"\\tSingle Precision = True\\n\"\n            \"\\tSave Geometry Ids = True\\n\"\n            \"\\tShow Variables = True\\n\"\n            \"End\\n\".format(\"step\")\n        )\n\n        fo.write(\n            \"\\nSolver 5\\n\"\n            \"\\tExec Solver = After Timestep\\n\"\n            \"\\tEquation = SaveLine\\n\"\n            '\\tFilename = \"{0}\"\\n'\n            '\\tProcedure = \"SaveData\" \"SaveLine\"\\n'\n            \"\\tVariable 1 = Magnetic Flux Density 1\\n\"\n            \"\\tVariable 2 = Magnetic Flux Density 2\\n\"\n            \"\\tVariable 3 = Magnetic Flux Density 3\\n\"\n            \"\\tVariable 4 = Magnetic Flux Density e 1\\n\"\n            \"\\tVariable 5 = Magnetic Flux Density e 2\\n\"\n            \"\\tVariable 6 = Magnetic Flux Density e 3\\n\"\n            \"End\\n\".format(\"lines.dat\")\n        )\n\n        fo.write(\n            \"\\nSolver 6\\n\"\n            \"\\tExec Solver = After Timestep\\n\"\n            '\\tFilename = \"{0}\"\\n'\n            '\\tProcedure = \"SaveData\" \"SaveScalars\"\\n'\n            \"\\tShow Norm Index = 1\\n\"\n            \"End\\n\".format(\"scalars.dat\")\n        )\n\n        fo.write(\"\\n!--- BOUNDARIES ---\\n\")\n        for k, v in boundaries.items():\n            if k == \"VP0_BOUNDARY\":\n                fo.write(\n                    \"Boundary Condition {0}\\n\"\n                    \"\\tName = {1}\\n\"\n                    \"\\tA = Real 0\\n\"\n                    \"End\\n\\n\".format(v, k)\n                )\n            elif k == \"MASTER_STATOR_BOUNDARY\":\n                for k1, v1 in boundaries.items():\n                    if k1 == \"SLAVE_STATOR_BOUNDARY\":\n                        slave = v1\n                        break\n                if not self.is_periodicity_a:\n                    fo.write(\n                        \"Boundary Condition {0}\\n\"\n                        \"\\tName = {1}\\n\"\n                        \"\\tMortar BC = Integer {2}\\n\"\n                        \"\\tMortar BC Static = Logical True\\n\"\n                        \"\\tRadial Projector = Logical True\\n\"\n                        \"\\tGalerkin Projector = Logical True\\n\"\n                        \"End\\n\\n\".format(v, k, slave)\n                    )\n                else:\n                    fo.write(\n                        \"Boundary Condition {0}\\n\"\n                        \"\\tName = {1}\\n\"\n                        \"\\tMortar BC = Integer {2}\\n\"\n                        \"\\tMortar BC Static = Logical True\\n\"\n                        \"\\tAnti Radial Projector = Logical True\\n\"\n                        \"\\tGalerkin Projector = Logical True\\n\"\n                        \"End\\n\\n\".format(v, k, slave)\n                    )\n            elif k == \"MASTER_ROTOR_BOUNDARY\":\n                for k1, v1 in boundaries.items():\n                    if k1 == \"SLAVE_ROTOR_BOUNDARY\":\n                        slave = v1\n                        break\n                if not self.is_periodicity_a:\n                    fo.write(\n                        \"Boundary Condition {0}\\n\"\n                        \"\\tName = {1}\\n\"\n                        \"\\tMortar BC = Integer {2}\\n\"\n                        \"\\tMortar BC Static = Logical True\\n\"\n                        \"\\tRadial Projector = Logical True\\n\"\n                        \"\\tGalerkin Projector = Logical True\\n\"\n                        \"End\\n\\n\".format(v, k, slave)\n                    )\n                else:\n                    fo.write(\n                        \"Boundary Condition {0}\\n\"\n                        \"\\tName = {1}\\n\"\n                        \"\\tMortar BC = Integer {2}\\n\"\n                        \"\\tMortar BC Static = Logical True\\n\"\n                        \"\\tAnti Radial Projector = Logical True\\n\"\n                        \"\\tGalerkin Projector = Logical True\\n\"\n                        \"End\\n\\n\".format(v, k, slave)\n                    )\n            elif k == \"SB_STATOR_BOUNDARY\":\n                for k1, v1 in boundaries.items():\n                    if k1 == \"SB_ROTOR_BOUNDARY\":\n                        slave = v1\n                        break\n                if not self.is_periodicity_a:\n                    fo.write(\n                        \"Boundary Condition {0}\\n\"\n                        \"\\tName = {1}\\n\"\n                        \"\\tMortar BC = Integer {2}\\n\"\n                        \"\\tRotational Projector = Logical True\\n\"\n                        \"\\tGalerkin Projector = Logical True\\n\"\n                        \"End\\n\\n\".format(v, k, slave)\n                    )\n                else:\n                    fo.write(\n                        \"Boundary Condition {0}\\n\"\n                        \"\\tName = {1}\\n\"\n                        \"\\tMortar BC = Integer {2}\\n\"\n                        \"\\tAnti Rotational Projector = Logical True\\n\"\n                        \"\\tGalerkin Projector = Logical True\\n\"\n                        \"End\\n\\n\".format(v, k, slave)\n                    )\n            elif k == \"AIRGAP_ARC_BOUNDARY\":\n                fo.write(\n                    \"Boundary Condition {0}\\n\"\n                    \"\\tName = {1}\\n\"\n                    \"\\tSave Line = True\\n\"\n                    \"End\\n\\n\".format(v, k)\n                )\n            else:\n                fo.write(\n                    \"Boundary Condition {0}\\n\" \"\\tName = {1}\\n\" \"End\\n\\n\".format(v, k)\n                )\n\n    # setup Elmer solver\n    # ElmerSolver v8.4 must be installed and in the PATH\n\n    elmer_settings = join(project_name, \"pyleecan_elmer.sif\")\n    ElmerSolver_binary = get_path_binary(\"ElmerSolver\")\n    cmd_elmersolver = [\n        ElmerSolver_binary,\n        elmer_settings,\n    ]\n    self.get_logger().info(\n        \"Calling ElmerSolver: \" + \" \".join(map(str, cmd_elmersolver))\n    )\n    elmersolver = subprocess.Popen(\n        cmd_elmersolver, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n    )\n    (stdout, stderr) = elmersolver.communicate()\n    elmersolver.wait()\n    self.get_logger().info(stdout.decode(\"UTF-8\"))\n    if elmersolver.returncode != 0:\n        self.get_logger().info(\"ElmerSolver [Error]: \" + stderr.decode(\"UTF-8\"))\n        return False\n    elmersolver.terminate()\n    self.get_logger().info(\"ElmerSolver call complete!\")\n\n    self.get_meshsolution(output)\n\n    Na = angle.size\n    Nt = time.size - 1\n\n    # Loading parameters for readibility\n    L1 = output.simu.machine.stator.comp_length()\n    save_path = self.get_path_save(output)\n\n    scalars_file = join(elmermesh_folder, \"scalars.dat\")\n    ecp, mfe, agt, iv, im, tq = loadtxt(\n        scalars_file, unpack=True, usecols=(0, 1, 2, 3, 4, 5)\n    )\n    # ecp: eddy current power\n    # mfe: magnetic field energy\n    # agt: air gap torque\n    # iv: inertial volume\n    # im: inertial moment\n    # tq: group 1 torque\n\n    # TODO Load Air gap flux density\n\n    # FEM_dict = output.mag.FEM_dict\n    #\n    if (\n        hasattr(output.simu.machine.stator, \"winding\")\n        and output.simu.machine.stator.winding is not None\n    ):\n        qs = output.simu.machine.stator.winding.qs  # Winding phase number\n        Phi_wind_stator = zeros((Nt, qs))\n    else:\n        Phi_wind_stator = None\n\n    # Initialize results matrix\n    Br = zeros((Nt, Na))\n    Bt = zeros((Nt, Na))\n    Bz = zeros((Nt, Na))\n    Tem = tq * sym * L1\n\n    # Phi_wind_stator = zeros((Nt, qs))\n\n    # compute the data for each time step\n    # TODO Other than FEMM, in Elmer I think it's possible to compute\n    #      all time steps at once\n    self.get_logger().debug(\"Solving Simulation\")\n\n    # run the computation\n    if self.nb_worker > 1:\n        # TODO run solver in parallel\n        pass\n    else:\n        # TODO run solver 'normal'\n        pass\n\n    # get the air gap flux result\n    # TODO add function (or method)\n    # ii -> Time, jj -> Angle\n    # Br[ii, jj], Bt[ii, jj] = get_airgap_flux()\n\n    # get the torque\n    # TODO add function (or method)\n    # Tem[ii] = comp_Elmer_torque(FEM_dict, sym=sym)\n\n    # flux linkage computation\n    # if Phi_wind_stator is not None:\n    #     # TODO\n    #     # Phi_wind[ii, :] = comp_Elmer_Phi_wind()\n    #     pass\n\n    return Br, Bt, Bz, Tem, Phi_wind_stator\n", "meta": {"hexsha": "cb07f4c86712da036c67972ccb3e8df754e09a35", "size": 40725, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyleecan/Methods/Simulation/MagElmer/solve_FEA.py", "max_stars_repo_name": "nnassar98/pyleecan", "max_stars_repo_head_hexsha": "3a6ffe14ab46e90dc0b2855386623833c622b95e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-03-05T15:22:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T15:26:08.000Z", "max_issues_repo_path": "pyleecan/Methods/Simulation/MagElmer/solve_FEA.py", "max_issues_repo_name": "thalesmaoa/pyleecan", "max_issues_repo_head_hexsha": "c4fdc6362fdeba3d0766d5d1df3ff9c97c3f9fa3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-07-09T07:43:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T12:52:06.000Z", "max_forks_repo_path": "pyleecan/Methods/Simulation/MagElmer/solve_FEA.py", "max_forks_repo_name": "thalesmaoa/pyleecan", "max_forks_repo_head_hexsha": "c4fdc6362fdeba3d0766d5d1df3ff9c97c3f9fa3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-12-23T12:38:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-07T10:47:48.000Z", "avg_line_length": 39.6157587549, "max_line_length": 124, "alphanum_fraction": 0.4714794352, "include": true, "reason": "import numpy,from numpy", "num_tokens": 10699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.19595849660108075}}
{"text": "\"\"\"\nThis is a module containing functions and classes for imaging propagation with HCIPy, for now LUVOIR A.\n\"\"\"\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\nfrom astropy.io import fits\nimport hcipy as hc\nfrom hcipy.optics.segmented_mirror import SegmentedMirror\n\nfrom config import CONFIG_INI\n\n\nclass SegmentedTelescopeAPLC:\n    \"\"\" A segmented telescope with an APLC and actuated segments.\n\n    Parameters:\n    ----------\n    aper : Field\n        Telescope aperture.\n    indexed_aperture : Field\n        The *indexed* segmented aperture of the mirror, all pixels each segment being filled with its number for\n        segment identification. Segment gaps must be strictly zero.\n    seg_pos : CartesianGrid(UnstructuredCoords)\n        Segment positions of the aperture.\n    apod : Field\n        Apodizer\n    lyots : Field\n        Lyot stop\n    fpm : fpm\n        Focal plane mask\n    focal_grid :\n        Focal plane grid to put final image on\n    params : dict\n        wavelength, diameter, image size in lambda/D, FPM radius\n    \"\"\"\n\n    def __init__(self, aper, indexed_aperture, seg_pos, apod, lyotst, fpm, focal_grid, params):\n        self.sm = SegmentedMirror(indexed_aperture=indexed_aperture, seg_pos=seg_pos)\n        self.aper = aper\n        self.apodizer = apod\n        self.lyotstop = lyotst\n        self.fpm = fpm   #TODO: this is not actually used inside this class\n        self.wvln = params['wavelength']\n        self.diam = params['diameter']\n        self.imlamD = params['imlamD']\n        self.fpm_rad = params['fpm_rad']\n        self.lamDrad = self.wvln / self.diam\n        self.coro = hc.LyotCoronagraph(indexed_aperture.grid, fpm, lyotst)\n        self.prop = hc.FraunhoferPropagator(indexed_aperture.grid, focal_grid)\n        self.coro_no_ls = hc.LyotCoronagraph(indexed_aperture.grid, fpm)\n        self.wf_aper = hc.Wavefront(aper, wavelength=self.wvln)\n        self.focal_det = focal_grid\n\n    def calc_psf(self, ref=False, display_intermediate=False,  return_intermediate=None):\n        \"\"\"Calculate the PSF of the segmented telescope, normalized to contrast units.\n\n        Parameters:\n        ----------\n        ref : bool\n            Keyword for additionally returning the refrence PSF without the FPM.\n        display_intermediate : bool\n            Keyword for display of all planes.\n        return_intermediate : string\n            Either 'intensity', return the intensity in all planes; except phase on the SM (first plane)\n            or 'efield', return the E-fields in all planes. Default none.\n        Returns:\n        --------\n        wf_im_coro.intensity : Field\n            Coronagraphic image, normalized to contrast units by max of reference image (even when ref\n            not returned).\n        wf_im_ref.intensity : Field, optional\n            Reference image without FPM.\n        intermediates : dict of Fields, optional\n            Intermediate plane intensity images; except for full wavefront on segmented mirror.\n        wf_im_coro : Wavefront\n            Wavefront in last focal plane.\n        wf_im_ref : Wavefront, optional\n            Wavefront of reference image without FPM.\n        intermediates : dict of Wavefronts, optional\n            Intermediate plane E-fields; except intensity in focal plane after FPM.\n        \"\"\"\n\n        # Create fake FPM for plotting\n        fpm_plot = 1 - hc.circular_aperture(2 * self.fpm_rad * self.lamDrad)(self.focal_det)\n\n        # Create apodozer as hc.Apodizer() object to be able to propagate through it\n        apod_prop = hc.Apodizer(self.apodizer)\n\n        # Calculate all wavefronts of the full propagation\n        wf_sm = self.sm(self.wf_aper)\n        wf_apod = apod_prop(wf_sm)\n        wf_lyot = self.coro(wf_apod)\n        wf_im_coro = self.prop(wf_lyot)\n\n        # Wavefronts in extra planes\n        wf_before_fpm = self.prop(wf_apod)\n        int_after_fpm = np.log10(wf_before_fpm.intensity / wf_before_fpm.intensity.max()) * fpm_plot  # this is the intensity straight\n        wf_before_lyot = self.coro_no_ls(wf_apod)\n\n        # Wavefronts of the reference propagation\n        wf_ref_pup = hc.Wavefront(self.aper * self.apodizer * self.lyotstop, wavelength=self.wvln)\n        wf_im_ref = self.prop(wf_ref_pup)\n\n        # Display intermediate planes\n        if display_intermediate:\n\n            plt.figure(figsize=(15, 15))\n\n            plt.subplot(331)\n            hc.imshow_field(wf_sm.phase, mask=self.aper, cmap='RdBu')\n            plt.title('Seg aperture phase')\n\n            plt.subplot(332)\n            hc.imshow_field(wf_apod.intensity, cmap='inferno')\n            plt.title('Apodizer')\n\n            plt.subplot(333)\n            hc.imshow_field(wf_before_fpm.intensity / wf_before_fpm.intensity.max(), norm=LogNorm(), cmap='inferno')\n            plt.title('Before FPM')\n\n            plt.subplot(334)\n            hc.imshow_field(int_after_fpm / wf_before_fpm.intensity.max(), cmap='inferno')\n            plt.title('After FPM')\n\n            plt.subplot(335)\n            hc.imshow_field(wf_before_lyot.intensity / wf_before_lyot.intensity.max(), norm=LogNorm(vmin=1e-3, vmax=1),\n                            cmap='inferno')\n            plt.title('Before Lyot stop')\n\n            plt.subplot(336)\n            hc.imshow_field(wf_lyot.intensity / wf_lyot.intensity.max(), norm=LogNorm(vmin=1e-3, vmax=1),\n                            cmap='inferno', mask=self.lyotstop)\n            plt.title('After Lyot stop')\n\n            plt.subplot(337)\n            hc.imshow_field(wf_im_coro.intensity / wf_im_ref.intensity.max(), norm=LogNorm(vmin=1e-10, vmax=1e-3),\n                            cmap='inferno')\n            plt.title('Final image')\n            plt.colorbar()\n\n        if return_intermediate == 'intensity':\n\n            # Return the intensity in all planes; except phase on the SM (first plane)\n            intermediates = {'seg_mirror': wf_sm.phase,\n                             'apod': wf_apod.intensity,\n                             'before_fpm': wf_before_fpm.intensity / wf_before_fpm.intensity.max(),\n                             'after_fpm': int_after_fpm / wf_before_fpm.intensity.max(),\n                             'before_lyot': wf_before_lyot.intensity / wf_before_lyot.intensity.max(),\n                             'after_lyot': wf_lyot.intensity / wf_lyot.intensity.max()}\n\n            if ref:\n                return wf_im_coro.intensity, wf_im_ref.intensity, intermediates\n            else:\n                return wf_im_coro.intensity, intermediates\n\n        if return_intermediate == 'efield':\n\n            # Return the E-fields in all planes; except intensity in focal plane after FPM\n            intermediates = {'seg_mirror': wf_sm,\n                             'apod': wf_apod,\n                             'before_fpm': wf_before_fpm,\n                             'after_fpm': int_after_fpm,\n                             'before_lyot': wf_before_lyot,\n                             'after_lyot': wf_lyot}\n\n            if ref:\n                return wf_im_coro, wf_im_ref, intermediates\n            else:\n                return wf_im_coro, intermediates\n\n        if ref:\n            return wf_im_coro.intensity, wf_im_ref.intensity\n\n        return wf_im_coro.intensity\n\n    def flatten(self):\n        self.sm.flatten()\n\n    def set_segment(self, segid, piston, tip, tilt):\n        self.sm.set_segment(segid, piston, tip, tilt)\n\n    def apply_aberrations(self, aber_array):\n        for vals in aber_array:\n            self.sm.set_segment(vals[0], vals[1], vals[2], vals[3])\n\n    def forward(self, wavefront):\n        raise NotImplementedError()\n\n    def backward(self, wavefront):\n        raise NotImplementedError()\n\n\nclass LuvoirAPLC(SegmentedTelescopeAPLC):\n    \"\"\" Simple E2E simulator for LUVOIR A (with APLC).\n\n    Parameters:\n    ----------\n    input dir : string\n        Path to input files: apodizer, aperture, indexed aperture, Lyot stop.\n    apod_design : string\n        Choice of apodizer design from May 2019 delivery. \"small\", \"medium\" or \"large\".\n    \"\"\"\n    def __init__(self, input_dir, apod_design, samp):\n        self.nseg = 120   # FIXME: this should not be hard-coded\n        self.wvln = CONFIG_INI.getfloat('LUVOIR', 'lambda') * 1e-9    # m\n        self.diam = 15.  # m   # FIXME: this should not be hard-coded\n        self.sampling = samp\n        self.lam_over_d = self.wvln / self.diam\n        self.apod_dict = {'small': {'pxsize': 1000, 'fpm_rad': 3.5, 'fpm_px': 150, 'iwa': 3.4, 'owa': 12.,\n                                    'fname': '0_LUVOIR_N1000_FPM350M0150_IWA0340_OWA01200_C10_BW10_Nlam5_LS_IDD0120_OD0982_no_ls_struts.fits'},\n                          'medium': {'pxsize': 1000, 'fpm_rad': 6.82, 'fpm_px': 250, 'iwa': 6.72, 'owa': 23.72,\n                                     'fname': '0_LUVOIR_N1000_FPM682M0250_IWA0672_OWA02372_C10_BW10_Nlam5_LS_IDD0120_OD0982_no_ls_struts.fits'},\n                          'large': {'pxsize': 1000, 'fpm_rad': 13.38, 'fpm_px': 400, 'iwa': 13.28, 'owa': 46.88,\n                                    'fname': '0_LUVOIR_N1000_FPM1338M0400_IWA1328_OWA04688_C10_BW10_Nlam5_LS_IDD0120_OD0982_no_ls_struts.fits'}}\n        self.imlamD = 1.2*self.apod_dict[apod_design]['owa']\n\n        # Pupil plane optics\n        aper_path = 'inputs/TelAp_LUVOIR_gap_pad01_bw_ovsamp04_N1000.fits'\n        aper_ind_path = 'inputs/TelAp_LUVOIR_gap_pad01_bw_ovsamp04_N1000_indexed.fits'\n        apod_path = os.path.join(input_dir, 'luvoir_stdt_baseline_bw10', apod_design + '_fpm', 'solutions',\n                                 self.apod_dict[apod_design]['fname'])\n        ls_fname = 'inputs/LS_LUVOIR_ID0120_OD0982_no_struts_gy_ovsamp4_N1000.fits'\n\n        pup_read = hc.read_fits(os.path.join(input_dir, aper_path))\n        aper_ind_read = hc.read_fits(os.path.join(input_dir, aper_ind_path))\n        apod_read = hc.read_fits(os.path.join(input_dir, apod_path))\n        ls_read = hc.read_fits(os.path.join(input_dir, ls_fname))\n\n        pupil_grid = hc.make_pupil_grid(dims=self.apod_dict[apod_design]['pxsize'], diameter=self.diam)\n\n        self.aperture = hc.Field(pup_read.ravel(), pupil_grid)\n        self.aper_ind = hc.Field(aper_ind_read.ravel(), pupil_grid)\n        self.apod = hc.Field(apod_read.ravel(), pupil_grid)\n        self.ls = hc.Field(ls_read.ravel(), pupil_grid)\n\n        # Load segment positions from fits header\n        hdr = fits.getheader(os.path.join(input_dir, aper_ind_path))\n\n        poslist = []\n        for i in range(self.nseg):\n            segname = 'SEG' + str(i + 1)\n            xin = hdr[segname + '_X']\n            yin = hdr[segname + '_Y']\n            poslist.append((xin, yin))\n\n        poslist = np.transpose(np.array(poslist))\n        self.seg_pos = hc.CartesianGrid(poslist)\n\n        # Focal plane mask\n        samp_foc = self.apod_dict[apod_design]['fpm_px'] / (self.apod_dict[apod_design]['fpm_rad'] * 2)\n        focal_grid_fpm = hc.make_focal_grid(pupil_grid=pupil_grid, q=samp_foc,\n                                            num_airy=self.apod_dict[apod_design]['fpm_rad'], wavelength=self.wvln)\n        self.fpm = 1 - hc.circular_aperture(2*self.apod_dict[apod_design]['fpm_rad']*self.lam_over_d)(focal_grid_fpm)\n\n        # Final focal plane grid (detector)\n        self.focal_det = hc.make_focal_grid(pupil_grid=pupil_grid, q=self.sampling, num_airy=self.imlamD, wavelength=self.wvln)\n\n        luvoir_params = {'wavelength': self.wvln, 'diameter': self.diam, 'imlamD': self.imlamD,\n                         'fpm_rad': self.apod_dict[apod_design]['fpm_rad']}\n\n        # Initialize the general segmented telescope with APLC class, includes the SM\n        super().__init__(aper=self.aperture, indexed_aperture=self.aper_ind, seg_pos=self.seg_pos, apod=self.apod,\n                         lyotst=self.ls, fpm=self.fpm, focal_grid=self.focal_det, params=luvoir_params)\n\n        # Make dark hole mask\n        dh_outer = hc.circular_aperture(2 * self.apod_dict[apod_design]['owa'] * self.lam_over_d)(\n            self.focal_det)\n        dh_inner = hc.circular_aperture(2 * self.apod_dict[apod_design]['iwa'] * self.lam_over_d)(\n            self.focal_det)\n        self.dh_mask = (dh_outer - dh_inner).astype('bool')\n\n        # Propagators\n        self.coro = hc.LyotCoronagraph(pupil_grid, self.fpm, self.ls)\n        self.prop = hc.FraunhoferPropagator(pupil_grid, self.focal_det)\n        self.coro_no_ls = hc.LyotCoronagraph(pupil_grid, self.fpm)\n        #TODO: these three propagators should actually happen in the super init\n        # -> how are self.aper_ind and pupil_grid connected?\n", "meta": {"hexsha": "2070fa25ccb872c39ecdf7a4979b6d46e427e3a4", "size": 12550, "ext": "py", "lang": "Python", "max_stars_repo_path": "pastis/e2e_simulators/luvoir_imaging.py", "max_stars_repo_name": "ivalaginja/PASTIS", "max_stars_repo_head_hexsha": "ed52a4c838c93cd933f7a8c0bf52113cddd5a415", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pastis/e2e_simulators/luvoir_imaging.py", "max_issues_repo_name": "ivalaginja/PASTIS", "max_issues_repo_head_hexsha": "ed52a4c838c93cd933f7a8c0bf52113cddd5a415", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pastis/e2e_simulators/luvoir_imaging.py", "max_forks_repo_name": "ivalaginja/PASTIS", "max_forks_repo_head_hexsha": "ed52a4c838c93cd933f7a8c0bf52113cddd5a415", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8214285714, "max_line_length": 144, "alphanum_fraction": 0.6302788845, "include": true, "reason": "import numpy,from astropy", "num_tokens": 3237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.35577490717496246, "lm_q1q2_score": 0.19589228436315076}}
{"text": "\"\"\" Class for correlating galaxies and IGM within a given field on the sky\n\"\"\"\nfrom __future__ import print_function, absolute_import, division, unicode_literals\n\nimport numpy as np\nimport warnings\nimport pdb\n\nimport astropy\nfrom astropy import units as u\nfrom astropy.units import Quantity\nfrom astropy.coordinates import SkyCoord\nfrom astropy import constants as const\nfrom astropy.cosmology import Planck15\n\nimport pyigm.field.utils as pfu\nfrom pyigm.utils import calc_rho\n\n#from xastropy.xutils import xdebug as xdb\n\n\nclass IgmGalaxyField(object): \n    \"\"\" Class for a field associating galaxies to the IGM/CGM\n\n    Parameters\n    ----------\n    radec : tuple or SkyCoord\n        (RA,DEC) in deg or astropy.coordinate\n    name : str; optional\n        Default is set from sexagesimal coordinates\n    zem : float; optional\n        Redshift of background source (e.g., QSO)\n    cosmo : Cosmology; optional\n        Default is astropy.cosmology.Planck15\n\n    \"\"\"\n\n    # Initialize\n    def __init__(self, radec, name=None, zem=None, cosmo=None, verbose=False):\n        # coord\n        if isinstance(radec, (tuple)):\n            self.coord = SkyCoord(ra=radec[0], dec=radec[1])\n        elif isinstance(radec, SkyCoord):\n            self.coord = radec\n\n        # Field\n        if name is None:\n            self.name = 'IGMFIELD_J{:s}{:s}'.format(\n                    self.coord.ra.to_string(unit=u.hour, pad=True),\n                    self.coord.dec.to_string(pad=True, alwayssign=True))\n        self.name = name\n\n        # Cosmology\n        if cosmo is None:\n            cosmo = Planck15\n            if verbose is True:\n                print('IgmGalxyField: Using Planck15 cosmology')\n        self.cosmo = cosmo\n\n        # Init\n        self.zem = zem\n        self.igm = None\n        self.targets = None\n        self.galaxies = None\n        self.observing = None\n        self.selection = None\n\n    def calc_rhoimpact(self, obj, comoving=True, los_coord=None):\n        \"\"\"Calculate impact parameter from LOS RA/DEC for a set of objects\n\n        Parameters\n        ----------\n        obj : Table or dict\n          Anything that takes 'Z', and 'RA','DEC' in degrees\n          Sources for calculation\n        comoving : bool, optional\n           If True then comoving, else physical\n        los_radec : SkyCoord, optional\n          Defaults to field RA/DEC\n\n\n        Returns\n        -------\n        rho : Quantity (array usually)\n          Impact parameter(s) in kpc\n        \"\"\"\n        if los_coord is None:\n            los_coord = self.coord\n        # Coord\n        ora = obj['RA']\n        odec = obj['DEC']\n        #if ((isinstance(obj['RA'], Quantity)) |\n        #        (isinstance(obj['RA'],astropy.table.column.MaskedColumn)) |\n        #        (isinstance(obj['RA'], astropy.table.column.Column))):\n        #    ora = obj['RA']\n        #    odec = obj['DEC']\n        #else:\n        #    ora = obj['RA']*u.deg\n        #    odec = obj['DEC']*u.deg\n        o_coord = SkyCoord(ra=ora, dec=odec, unit='deg')\n        # Calculate\n        rho, ang_sep = calc_rho(los_coord, o_coord, obj['Z'], self.cosmo, comoving=comoving)\n        # Return\n        return rho\n\n    def get_associated_galaxies(self, z, los_coord=None, R=300*u.kpc, dv_tol=500*u.km/u.s):\n        \"\"\"Return a Table of associated galaxies for a given redshift and separation\n\n        Parameters\n        ----------\n        z : float\n          Redshift for association (usually IGM/CGM absorber redshift)\n        R : Quantity\n          Radius of impact parameter for association [300kpc]\n        dv_tol : Quantity\n          Velocity window for association [500km/s]\n        los_coord : SkyCoord, optional\n          Line-of-sight coordinates\n\n        Returns\n        -------\n        assoc_gal : Table\n          Table of associated galaxies (if any)\n        rho : Quantity\n          Impact parameters [kpc]\n        \"\"\"\n        # los_radec\n        if los_coord is None:\n            los_coord = self.coord\n        # Cut on z first\n        dv_gal = const.c.to('km/s') * (self.galaxies['Z']-z)/(1+z)  # Approximate\n        gdz = np.where(np.abs(dv_gal)<dv_tol)[0]\n        if len(gdz) == 0:\n            return None\n        #\n        gdz_gal = self.galaxies[gdz]\n        rho = self.calc_rhoimpact(gdz_gal, los_coord)  # Could add this to Table\n        #\n        gd_rho = np.where(rho < R)[0]\n        if len(gd_rho) == 0:\n            return None\n        # Return\n        return gdz_gal[gd_rho], rho[gd_rho]\n\n    def get_observed(self, theta=None, subtab=None):\n        \"\"\"Generate a Table of observed targets\n\n        Optionally to an angular distance from field center\n\n        Parameters\n        ----------\n        theta : Quantity or Angle, optional\n          Angular radius\n        subtab : Table, optional\n          User may input a table for processing\n          theta is ignored\n\n        Returns\n        -------\n        obs_targ : Table\n          Sub-table of targets that have been observed within theta (if given)\n          and/or within subtab (if given)\n        obs_dates : List\n          List of observing dates [eventually might add to Table]\n        indices : array\n          Indices from the target table\n        \"\"\"\n        if (self.targets is None) or (self.observing is None):\n            raise ValueError('IgmGalaxyField: Need to fill the target and/or observing table first!')\n        if subtab is None:\n            if theta is None:\n                subtab = self.targets\n            else:\n                # Trim on angular cut first\n                targ_coord = SkyCoord(ra=self.targets['TARG_RA']*u.deg,\n                    dec=self.targets['TARG_DEC']*u.deg)\n                sep = self.coord.separation(targ_coord)\n                gdsep = np.where(sep < theta)[0]\n                if len(gdsep) == 0:\n                    return None\n                subtab = self.targets[gdsep]\n        else:\n            gdsep = np.arange(len(subtab)) # For indexing below\n        # Generate mask (set all to False; True is masked in numpy)\n        tmsk = np.array([False]*len(subtab))\n        # Grab those with a MASK_NAME\n        have_mask = np.where(~subtab['MASK_NAME'].mask)[0]\n        if len(have_mask) == 0:\n            warnings.warn(\"No sources with a MASK_NAME\")\n            pdb.set_trace()\n            return None\n        # Get unique mask values\n        all_masks = subtab['MASK_NAME'][have_mask]\n        uni_masks = np.unique(all_masks)\n        obs_dict = {}\n        # Loop on these\n        for mask in uni_masks:\n            obs_dates = self.get_mask_obsdate(mask)\n            if len(obs_dates) > 0:\n                mt2 = np.where(subtab['MASK_NAME'][have_mask]==mask)\n                tmsk[have_mask[mt2]] = True\n                obs_dict[mask] = obs_dates\n        # Finish\n        return subtab[tmsk], obs_dict, gdsep[tmsk]\n\n    def get_unobserved(self, theta=None):\n        \"\"\"Generate a Table of unobserved targets within an angular distance\n\n        Parameters\n        ----------\n        theta : Quantity, optional\n          Angular distance\n\n        Returns\n        -------\n        unobs_targ : Table\n          Sub-table of targets that have been not been observed within theta (if given)\n        \"\"\"\n        if (self.targets is None) or (self.observing is None):\n            raise ValueError('IgmGalaxyField: Need to fill the target and/or observing table first!')\n        # Trim on angular cut first\n        if theta is None:\n            targ_coord = SkyCoord(ra=self.targets['TARG_RA']*u.deg,\n                dec=self.targets['TARG_DEC']*u.deg)\n            sep = self.coord.separation(targ_coord)\n            gdsep = np.where(sep < theta)[0]\n            if len(gdsep) == 0:\n                return None\n            # Set all to False to start\n            subtab = self.targets[gdsep]\n        else:\n            subtab = self.targets\n        tmsk = np.array([True]*len(subtab))\n        # Grab observed (short cut!)\n        obs_tab, odict, _ = self.get_observed(theta, subtab=subtab)\n        # Remove those\n        for kk, row in enumerate(subtab):\n            if row['TARG_RA'] in obs_tab['TARG_RA']: # Could use DEC too\n                tmsk[kk] = False\n        # Return\n        return subtab[tmsk]\n\n\n    def get_mask_obsdate(self, mask_name):\n        \"\"\"Given a mask name, find the observing dates\n\n        Parameters\n        ----------\n        mask_name : str\n          Name of the mask\n\n        Returns\n        -------\n        obs_dates : List\n          List of the observing dates (can be empty)\n        \"\"\"\n        if self.observing is None:\n            raise ValueError('Need to fill observing info!')\n        #\n        mt = np.where(self.observing['MASK_NAME'] == mask_name)[0]\n        if self.observing['DATE_OBS'].mask[mt[0]]:\n            return []\n        obs_dates = [self.observing['DATE_OBS'][imt] for imt in mt]\n        # Return\n        return obs_dates\n\n\n    def clean_duplicates(self, table, tol=1*u.arcsec, method='first'):\n        \"\"\" Clean duplicates in table based on (ra,dec) coordinates\n\n        Parameters\n        ----------\n        table : Table\n            Table to clean duplicates based on (ra, dec)\n        tol : Angle, optional\n            Angular tolerance for considering duplicates\n        method : str, optional\n            Method to use. Current options are:\n            ``'first'``: if duplicates exist keep only the first one\n\n        Returns\n        -------\n        cleaned_table : Table\n            A version of `table` without duplicates\n        \"\"\"\n\n        # TODO: add more methods for merging/cleaning duplicates\n\n        if method not in ['first']:\n            raise RuntimeError('Not ready for this method=`{}`'.format(method))\n\n        isdup, idx, dcoord = pfu.check_dup_table(table, tol=tol)\n        dup_inds = np.where(isdup == True)[0]\n        keep = []\n\n        if method == 'first':\n            for ii in dup_inds:\n                mtch = np.where(dcoord[ii].separation(dcoord) < tol)[0]\n                keep.append(min(mtch))\n\n            first_dup = np.unique(np.array(keep))\n\n            no_dup = np.arange(len(idx))[~isdup]\n            clean_inds = np.append(no_dup, first_dup)\n            clean_inds = np.sort(clean_inds)\n\n        #return\n        return table[clean_inds]\n\n    #    \n    def __repr__(self):\n        return ('<{:s}: {:s} {:s} {:s}>'.format(\n                self.__class__.__name__,\n                 self.name,\n                 self.coord.ra.to_string(unit=u.hour, sep=':', pad=True),\n                 self.coord.dec.to_string(sep=':', pad=True, alwayssign=True)))\n\n\n\n\n", "meta": {"hexsha": "e3316c60661388557937df9f9cf5f68cf89ffb88", "size": 10504, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyigm/field/igmfield.py", "max_stars_repo_name": "pyigm/pyigm", "max_stars_repo_head_hexsha": "8b4bc7f7f1c9f1c280720a4cc0693cd7cb79e9cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2016-02-12T19:03:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-11T15:16:25.000Z", "max_issues_repo_path": "pyigm/field/igmfield.py", "max_issues_repo_name": "pyigm/pyigm", "max_issues_repo_head_hexsha": "8b4bc7f7f1c9f1c280720a4cc0693cd7cb79e9cb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 204, "max_issues_repo_issues_event_min_datetime": "2015-12-06T13:40:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-11T21:48:39.000Z", "max_forks_repo_path": "pyigm/field/igmfield.py", "max_forks_repo_name": "pyigm/pyigm", "max_forks_repo_head_hexsha": "8b4bc7f7f1c9f1c280720a4cc0693cd7cb79e9cb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2015-12-06T23:27:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T10:08:24.000Z", "avg_line_length": 32.722741433, "max_line_length": 101, "alphanum_fraction": 0.5621667936, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 2493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3557748935136304, "lm_q1q2_score": 0.1958922768411207}}
{"text": "#!/usr/bin/env python3\nimport sys\nimport os\nimport json\nimport networkx as nx\nimport math\nfrom networkx.algorithms import approximation as approx\nimport time\nfrom itertools import groupby as g\nfrom operator import itemgetter\nfrom graphFunctions import * \nimport csv\nimport configparser\nimport logging\n#from networkx.readwrite import d3_js\nfrom networkx.readwrite import json_graph\n#import mpld3\n#mpld3.enable_notebook()\n#from mpld3 import plugins\n#import matplotlib.pyplot as plt\n\n\nConfig = configparser.ConfigParser()\nConfig.read(\"../etc/config.cfg\")\n\nlogging.basicConfig(filename=Config.get(\"Debug\", \"Logfile\"),level=logging.INFO, format='%(asctime)s %(message)s')\n\ndebug = Config.getboolean(\"Debug\", \"DebugInfo\")\nstandardDirectory = Config.get(\"Path\", \"StandardDirectory\")\nfilename = \"\"\nlastcomm = \"\"\noutputfile = \"\"\nmaxEdgeValue = Config.getint(\"Graph\", \"maxEdgeValue\");\n# Values for Edge creation\ncreateEdgePercent = Config.getint(\"Graph\", \"createEdgePercent\") \t\t\t# Bis zu einem Wert von 30% NICHT ähnlich\ncreateBlueEdgePercent = Config.getint(\"Graph\", \"createBlueEdgePercent\") \t# Bis zu einem Wert von 50% ETWAS ähnlich\ncreateBluedEdges = True\n\nfor argument in sys.argv:\n\tif lastcomm.strip() == \"-f\":\n\t\tfilename = argument.strip();\n\tif lastcomm.strip() == \"-d\":\n\t\tdebug = True\n\tif lastcomm.strip() == \"-m\":\n\t\tmaxEdgeValue = int(argument.strip());\n\tif lastcomm.strip() == \"-o\":\n\t\toutputfile = argument.strip();\n\tlastcomm = argument\nif lastcomm.strip() == \"-f\":\n\tfilename = argument.strip();\nif lastcomm.strip() == \"-d\":\n\tdebug = True\nif lastcomm.strip() == \"-m\":\n\tmaxEdgeValue = int(argument.strip());\nif lastcomm.strip() == \"-o\":\n\toutputfile = argument.strip();\n\nlogging.debug (\" ========\")\nlogging.info (\"  Starting PS-Clustering Algorithm with Complement on \"+filename)\nlogging.info (\" ========\")\nstart_time = time.time()\n\nif filename == \"\":\n\tlogging.error (\"No file name given.\")\n\texit()\n\nG=nx.Graph()\nlogging.info (\" ... now reading graph at \"+filename)\nG = nx.read_gml(filename)\n\nif len(G) == 0:\n\tlogging.error (\" ... Graph is empty! Exiting!\")\n\texit()\nbuild_time = time.time() - start_time\nlogging.info (\" => Build time: \"+str(build_time))\n\nstart_time = time.time()\n\nG2 = G.copy()\nG2 = nx.complement(G2)\nnh = getNeighbors(G2)\ncliques = []\nfor key, value in nh.items():\n\tu1 = key\n\t#print (u1)\n\tif u1 not in G2.nodes():\n\t\t#print (\" -> not in G2\")\n\t\tcontinue\n\tu2 = getSmalestNeighbor(G2,u1)\n\tif u2 == None:\t\t\n\t\t#print (\" -> None \")\n\t\tcontinue\n\tG2.add_node (str(u1)+\"|\"+str(u2))\n\tfor node in G2[u1]:\n\t\tif nodes_connected(G2, u2, node):\n\t\t\tG2.add_edge(str(u1)+\"|\"+str(u2), node)\n\tif 'clique' in G2.node[u2]:\n\t\tG2.node[str(u1)+\"|\"+str(u2)]['clique']=G2.node[u2]['clique']\n\telse:\n\t\tG2.node[str(u1)+\"|\"+str(u2)]['clique']=getMaxClique(G2)+1\n\tG2.remove_node(u1)\n\tG2.remove_node(u2)\nfor node in G2.nodes():\n\tif 'clique' not in G2.node[node]:\n\t\tG2.node[node]['clique']=getMaxClique(G2)+1\ncl = nx.get_node_attributes(G2,'clique')\nfor key, value in cl.items():\n\tif \"|\" in str(key):\n\t\tnodes = key.split(\"|\")\n\telse:\n\t\tnodes = [key]\n\tfor node in nodes:\n\t\tif node in G.nodes():\n\t\t\tG.node[node]['color']=value\n\t\telif int(node) in G.nodes():\n\t\t\t\tG.node[int(node)]['color']=value\n\t\telse:\n\t\t\tprint (\" Error, node does not exist! \")\n\n#d = nx.coloring.greedy_color(G, strategy=nx.coloring.strategy_largest_first)\nd = nx.get_node_attributes(G, 'color')\ncolorCount = d[max(d, key=lambda key: d[key])]\n\nbuild_time = time.time() - start_time\nlogging.info (\" => Clique time: \"+str(build_time))\nstart_time = time.time()\n\n\nstart_time = time.time()\n# valueGraph und Farbenliste bauen\nvalueGraph = buildValueGraph (G, d )\noutputpathfilename = standardDirectory+outputfile\nif os.path.isabs (outputfile):\n\toutputpathfilename = outputfile\nlogging.debug (\"  ... saving weightes Value Graph at \"+outputpathfilename+'coloredWithValue.gml')\nnx.write_gml(valueGraph, outputpathfilename+'coloredWithValue.gml')\n# Build a colorlist and sort min first\ncolorList = []\nfor i in range(0,colorCount):\n\t\tcountC = countColor (G,i);\n\t\tcolorList.append ( [i, countC] )\ncolorList = sorted(colorList,key=itemgetter(1))\n\nbuild_time = time.time() - start_time\nlogging.info (\" => Build weighted graph time: \"+str(build_time))\nstart_time = time.time()\n\n#G = addBlueEdges (G, createEdgePercent, createBlueEdgePercent, createBluedEdges, data)\n\n# For all nodes\ncountNodesEliminated = 0;\nlistConnections = []\n\ncolorCount = d[max(d, key=lambda key: d[key])]\nminYear = 3000\nmaxYear = 0\nfor i in range(0,colorCount):#\n\tyearc = getClusterYearsList (G,i)\n\tfor year in yearc:#\n\t\tif year[0]==0:\n\t\t\tcontinue\n\t\tif year[0]>maxYear:\n\t\t\tmaxYear = year[0]\n\t\tif year[0]<minYear:\n\t\t\tminYear = year[0]\n\nfor node in G.nodes():\n\tG.node[node]['year']=int(G.node[node]['year'])\n\nfor colorSet in colorList:\n\t# Get a list of nodes with that color\n\ttmpNodeList = list(n for n,d in G.nodes_iter(data=True) if d['color']==colorSet[0])\t\n\t#print (\" Color count before: \"+str(countColor(G, colorSet[0])))\n\t# Now iterate over these nodes\n\tfor i in range(0,len(tmpNodeList)):\n\t\t# catch that node\n\t\tnode = tmpNodeList[i]\n\t\t# check if this node is not already an end-point!\n\t\tif G.node[node][\"end\"]==0:\n\t\t\tcolors = [];\n\t\t\t# for all neighbours\n\t\t\tfor nb in G.neighbors(node):\n\t\t\t\t# is edge blue?\n\t\t\t\tif G[node][nb][\"color\"] == \"blue\":\n\t\t\t\t\t# is node not yet excluded from stable sets? \n\t\t\t\t\tif (G.node[nb][\"color\"] >= 0):\n\t\t\t\t\t\t# Nodes are not in the same stable sets\n\t\t\t\t\t\tif (G.node[nb][\"color\"] != G.node[node][\"color\"]):\n\t\t\t\t\t\t\tcolors.append (G.node[nb][\"color\"])\n\t\t\t# Now remove all double entries\n\t\t\tuniqueList = unique(colors)\n\t\t\t# check if \"node\" has at last two blue neighbours in different stable sets\n\t\t\tif len(uniqueList) >= 2:\n\t\t\t\t# Node is excluded from stable sets (color -1)\n\t\t\t\tG.node[node][\"color\"] = -1;\n\t\t\t\tcountNodesEliminated += 1\n\t\t\t\t# now we see, that this node connects all stable sets connected with blue edges:\n\t\t\t\tfor i in range(0,len(uniqueList)) :\n\t\t\t\t\tfor j in range (i+1, len(uniqueList)):\n\t\t\t\t\t\tnewYear = \"y\"+str(G.node[node][\"year\"])\n\t\t\t\t\t\t#print (\" Year: \"+newYear + \" from \"+ str(G.node[node][\"year\"]))\n\t\t\t\t\t\tif str(uniqueList[i]-1) in valueGraph.nodes() and str(str(uniqueList[j]-1)) in valueGraph.nodes():\n\t\t\t\t\t\t\tif valueGraph.has_edge(str(uniqueList[i]-1),str(uniqueList[j]-1)):\n\t\t\t\t\t\t\t\tvalueGraph[str(uniqueList[i]-1)][str(uniqueList[j]-1)][\"value\"]+=1\n\t\t\t\t\t\t\t\tif  \"y\"+str(G.node[node][\"year\"]) in valueGraph[str(uniqueList[i]-1)][str(uniqueList[j]-1)]:\n\t\t\t\t\t\t\t\t\t# Jahr existiert\n\t\t\t\t\t\t\t\t\tvalueGraph[str(uniqueList[i]-1)][str(uniqueList[j]-1)][\"y\"+str(G.node[node][\"year\"])] += 1\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tvalueGraph.add_edge (str(uniqueList[i]-1) , str(uniqueList[j]-1), {newYear : 1})\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tvalueGraph.add_edge(str(uniqueList[i]-1),str(uniqueList[j]-1), value=1)\n\t\t\t\t\t\t\t\tvalueGraph.add_edge (str(uniqueList[i]-1) , str(uniqueList[j]-1), {newYear : 1})\n\t\t\t\t\t\t\tfor yearsum in range(minYear, G.node[node][\"year\"]-1):\n\t\t\t\t\t\t\t\tif  \"s\"+str(yearsum) not in valueGraph[str(uniqueList[i]-1)][str(uniqueList[j]-1)]:\n\t\t\t\t\t\t\t\t\tnewYear2 = \"s\"+str(yearsum)\n\t\t\t\t\t\t\t\t\tvalueGraph.add_edge (str(uniqueList[i]-1) , str(uniqueList[j]-1), {newYear2 : 0})\n\t\t\t\t\t\t\tfor yearsum in range(G.node[node][\"year\"], maxYear):\n\t\t\t\t\t\t\t\tif  \"s\"+str(yearsum) in valueGraph[str(uniqueList[i]-1)][str(uniqueList[j]-1)]:\n\t\t\t\t\t\t\t\t\tvalueGraph[str(uniqueList[i]-1)][str(uniqueList[j]-1)][\"s\"+str(yearsum)] += 1\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tnewYear2 = \"s\"+str(yearsum)\n\t\t\t\t\t\t\t\t\tvalueGraph.add_edge (str(uniqueList[i]-1) , str(uniqueList[j]-1), {newYear2 : 1})\n\t\t\t\t\t\t#else:\n\t\t\t\t\t\t#\tlogging.warn (\" Error, nodes do not exist. \")\n\t\t\t\t\t\t#valueGraph[str(uniqueList[i]-1)][str(uniqueList[j]-1)][\"y\"+str(G.node[node][\"year\"])] += 1\n\t\t\t\t# mark all nodes as end-nodes\n\t\t\t\tfor nb in G.neighbors(node):\n\t\t\t\t\t# is edge blue?\n\t\t\t\t\tif G[node][nb][\"color\"] == \"blue\":\n\t\t\t\t\t\t# is node not yet excluded from stable sets? \n\t\t\t\t\t\tif (G.node[nb][\"color\"] >= 0):\n\t\t\t\t\t\t\tG.node[nb][\"end\"] = 1\n\t#print (\" Color count after: \"+str(countColor(G, colorSet[0])))\n#print (str(valueGraph.number_of_nodes()))\n\nif \"-1\" in valueGraph.nodes():\n\tvalueGraph.remove_node(\"-1\")\nif -1 in valueGraph.nodes():\n\tvalueGraph.remove_node(-1)\n\ncount = 15\n\nfor node in valueGraph.nodes():\t\n\tnewValue = countColor (G, int(node))\n\tif newValue == 0:\n\t\t#print (\"Removing node \"+str(node)+\" with \"+str(valueGraph.node[node][\"text\"]))\n\t\tvalueGraph.remove_node(node)\n\telse:\n\t\tvalueGraph.node[node][\"value\"]=newValue\n\t\tterms = getClusterName(G,node,count);\n\t\tjournals = getClusterJournals (G,node,count)\n\t\tyearc = getClusterYearsList (G,node,count)\n\t\tvalueGraph.node[node][\"text\"]=terms\n\t\tvalueGraph.node[node][\"journal\"]=journals\n\t\tyearc.sort(key=lambda tup: tup[0]) \n\t\t#print (str(yearc))\n\t\tsumme = 0\n\t\t#print (\"New Sum\")\n\t\t#print (str(minYear) +\" -- \"+str(maxYear))\n\t\t#print (yearc)\n\t\tfor year in range(minYear, maxYear):\n\t\t\taddValue = 0\n\t\t\t#print (\"Looking for year \"+str(year))\n\t\t\tfor years in yearc:\n\t\t\t\tif years[0]==0:\n\t\t\t\t\tcontinue\n\t\t\t\tif years[0] == year:\n\t\t\t\t\t#print (str(years[0]) +\" == \"+str(year))\n\t\t\t\t\taddValue = years[1]\n\t\t\t#print (\" \"+str(year))\n\t\t\tvalueGraph.node[node][\"y\"+str(year)] = addValue\n\t\t\tvalueGraph.node[node][\"s\"+str(year)] = addValue + summe\n\t\t\tsumme += addValue\t\n\t\t#csvwriter.writerow ([''])\n\t\t#csvwriter.writerow ([\"Node\", int(node), \"Nodes:\", newValue])\n\t\t#csvwriter.writerow (getClusterName (G, int(node), maxCount=-1, separator=\";\").split(\";\")) \n\t\t#csvwriter.writerow ([''])\n\t\t#nodeList = (n for n in G if G.node[n]['color']==int(node))\n\t\t#for nodeG in nodeList:\n\t\t#\tcsvwriter.writerow ([ G.node[nodeG]['title'], G.node[nodeG]['ref'], G.node[nodeG]['uri']])\nlogging.debug (\"  ... saving PS Value Graph at \"+outputpathfilename+'coloredWithValuePS.gml')\nnx.write_gml(valueGraph, outputpathfilename+'coloredWithValuePS.gml')\n\nbuild_time = time.time() - start_time\nlogging.debug (\" => PS time: \"+str(build_time))\nstart_time = time.time()\n\nps_time = build_time\n\n#csvwriter.writerows (sorted(oldList.items(), key=operator.itemgetter(1), reverse=True)) \n\nlogging.debug (\"  ... saving Network RB at  \"+outputpathfilename+'network_rb.gml')\n# Output nach neu färben\nnx.write_gml(G, outputpathfilename+'network_rb.gml')\n\nnumbers = getMeshTermNumber (G);\n#print ( sorted(numbers.items(), key=operator.itemgetter(1)))\n\n\n\n# Export \ndata = json_graph.node_link_data(valueGraph)\nwith open(outputpathfilename+'coloredWithValuePS.json', 'w') as outfile:\n    json.dump(data, outfile)\n\n#fig, axs = plt.subplots(1, 1, figsize=(10, 10))\n#ax = axs\n#pos = None\n#mpld3.plugins.connect(fig,  NetworkXD3ForceLayout(valueGraph,\n#                                                  pos,\n#                                                  ax,\n#                                                  gravity=.5,\n#                                                  link_distance=20,\n#                                                  charge=-600,\n#                                                  friction=1\n#                                                 )\n#                     )\n\n\nif debug:\n\t#logging.debug (\"Graph created. Number of nodes: \" + str(G.number_of_nodes())+ \", number edges: \"+ str(G.number_of_edges()))\n\t#logging.debug (\" Blue edges: \"+str(bluedEdges))\n\t#print (\" Black edges: \"+ str(countBlack) + \", Blued edges: \"+ str(countBlue) +\", lost edged: \"+str(countLost))\n\t#logging.debug (\" Build time: \\t \" + str((build_time)))\n\t#logging.debug (\" Color time: \\t \" + str((color_time )))\n\tlogging.info (\" PS time:  \\t \" + str((ps_time )))\n\t\n\t\n\tlogging.info (\" ========\")\n\tlogging.info (\" Farben: \\t\\t \"+str(colorCount))\n\tlogging.info (\" minMPS: \\t\\t \"+str(valueGraph.number_of_nodes()-1))\n\t#lower = colorCount - math.floor (bluedEdges / 2)\n\t#if lower < 2:\n\t#\tlower = 2\n\t#logging.debug (\" l_b: \\t \\t\\t \"+str(lower))\n\t#print (\" Cliquenzahl:  \"+ str(clique) )\n\tlogging.info (\" Eliminated nodes: \\t \"+str(countNodesEliminated))\n\t#print (\" Clique time: \" + str((clique_time - color_time)))\n\t#print (G.edges())\n#nx.set_node_attributes(G, 'label', {0: \"0\", 1: \"1\"})\n\noutput = []\noutput.append (ps_time)\noutput.append (colorCount)\noutput.append (valueGraph.number_of_nodes())\noutput.append (countNodesEliminated)\n\nprint (output)\n", "meta": {"hexsha": "819946f7e749b67ba293f2f4cb94982899f33e93", "size": 12098, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/DocClustering/heuristics/colorGraphComplement.py", "max_stars_repo_name": "jd-s/DocClustering", "max_stars_repo_head_hexsha": "a7d4acff8464f960558cf9cc6d03de78d07d56bf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/DocClustering/heuristics/colorGraphComplement.py", "max_issues_repo_name": "jd-s/DocClustering", "max_issues_repo_head_hexsha": "a7d4acff8464f960558cf9cc6d03de78d07d56bf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DocClustering/heuristics/colorGraphComplement.py", "max_forks_repo_name": "jd-s/DocClustering", "max_forks_repo_head_hexsha": "a7d4acff8464f960558cf9cc6d03de78d07d56bf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.664756447, "max_line_length": 125, "alphanum_fraction": 0.6444040337, "include": true, "reason": "import networkx,from networkx", "num_tokens": 3386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.19589227684112068}}
{"text": "# cython: language_level=3\n# distutils: language = c++\n# -*- coding: utf-8 -*-\n# *****************************************************************************\n# Copyright (c) 2016-2020, Intel Corporation\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# - Redistributions of source code must retain the above copyright notice,\n#   this list of conditions and the following disclaimer.\n# - Redistributions in binary form must reproduce the above copyright notice,\n#   this list of conditions and the following disclaimer in the documentation\n#   and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n# THE POSSIBILITY OF SUCH DAMAGE.\n# *****************************************************************************\n\n\"\"\"\nInterface of the Linear Algebra part of the DPNP\n\nNotes\n-----\nThis module is a face or public interface file for the library\nit contains:\n - Interface functions\n - documentation for the functions\n - The functions parameters check\n\n\"\"\"\n\n\nimport dpnp\nimport numpy\n\nfrom dpnp.dparray import dparray\nfrom dpnp.dpnp_utils import *\nfrom dpnp.linalg.dpnp_algo_linalg import *\n\n\n__all__ = [\n    \"cholesky\",\n    \"cond\",\n    \"det\",\n    \"eig\",\n    \"eigvals\",\n    \"inv\",\n    \"matrix_power\",\n    \"matrix_rank\",\n    \"multi_dot\",\n    \"norm\",\n    \"qr\",\n    \"svd\",\n]\n\n\ndef cholesky(input):\n    \"\"\"\n    Cholesky decomposition.\n    Return the Cholesky decomposition, `L * L.H`, of the square matrix `input`,\n    where `L` is lower-triangular and .H is the conjugate transpose operator\n    (which is the ordinary transpose if `input` is real-valued).  `input` must be\n    Hermitian (symmetric if real-valued) and positive-definite. No\n    checking is performed to verify whether `a` is Hermitian or not.\n    In addition, only the lower-triangular and diagonal elements of `input`\n    are used. Only `L` is actually returned.\n\n    Parameters\n    ----------\n    input : (..., M, M) array_like\n        Hermitian (symmetric if all elements are real), positive-definite\n        input matrix.\n\n    Returns\n    -------\n    L : (..., M, M) array_like\n        Upper or lower-triangular Cholesky factor of `input`.  Returns a\n        matrix object if `input` is a matrix object.\n    \"\"\"\n\n    if not use_origin_backend(input):\n        if not isinstance(input, dparray):\n            pass\n        elif input.shape[-1] != input.shape[-2]:\n            pass\n        elif input.ndim < 3:\n            pass\n        else:\n            return dpnp_cholesky(input)\n\n    return call_origin(numpy.linalg.cholesky, input)\n\n\ndef cond(input, p=None):\n    \"\"\"\n    Compute the condition number of a matrix.\n    For full documentation refer to :obj:`numpy.linalg.cond`.\n\n    Limitations\n    -----------\n    Input array is supported as :obj:`dpnp.ndarray`.\n    Parameter p=[None, 1, -1, 2, -2, numpy.inf, -numpy.inf, 'fro'] is supported.\n\n    See Also\n    --------\n    :obj:`dpnp.norm` : Matrix or vector norm.\n    \"\"\"\n\n    is_input_dparray = isinstance(input, dparray)\n\n    if (not use_origin_backend(input) and is_input_dparray):\n        if p in [None, 1, -1, 2, -2, numpy.inf, -numpy.inf, 'fro']:\n            result = dpnp_cond(input, p=p)\n            return result.dtype.type(result[0])\n        else:\n            pass\n\n    return call_origin(numpy.linalg.cond, input, p)\n\n\ndef det(input):\n    \"\"\"\n    Compute the determinant of an array.\n\n    Parameters\n    ----------\n    input : (..., M, M) array_like\n        Input array to compute determinants for.\n\n    Returns\n    -------\n    det : (...) array_like\n        Determinant of `input`.\n    \"\"\"\n    is_input_dparray = isinstance(input, dparray)\n\n    if not use_origin_backend(input) and is_input_dparray:\n        if input.shape[-1] == input.shape[-2]:\n            result = dpnp_det(input)\n\n            # scalar returned\n            if result.shape == (1,):\n                return result.dtype.type(result[0])\n\n            return result\n\n    return call_origin(numpy.linalg.det, input)\n\n\ndef eig(x1):\n    \"\"\"\n    Compute the eigenvalues and right eigenvectors of a square array.\n\n    .. seealso:: :obj:`numpy.linalg.eig`\n\n    \"\"\"\n\n    is_x1_dparray = isinstance(x1, dparray)\n\n    if (not use_origin_backend(x1) and is_x1_dparray):\n        if (x1.size > 0):\n            return dpnp_eig(x1)\n\n    return call_origin(numpy.linalg.eig, x1)\n\n\ndef eigvals(input):\n    \"\"\"\n    Compute the eigenvalues of a general matrix.\n    Main difference between `eigvals` and `eig`: the eigenvectors aren't\n    returned.\n\n    Parameters\n    ----------\n    input : (..., M, M) array_like\n        A complex- or real-valued matrix whose eigenvalues will be computed.\n\n    Returns\n    -------\n    w : (..., M,) ndarray\n        The eigenvalues, each repeated according to its multiplicity.\n        They are not necessarily ordered, nor are they necessarily\n        real for real matrices.\n    \"\"\"\n\n    is_input_dparray = isinstance(input, dparray)\n\n    if (not use_origin_backend(input) and is_input_dparray):\n        if (input.size > 0):\n            return dpnp_eigvals(input)\n\n    return call_origin(numpy.linalg.eigvals, input)\n\n\ndef inv(input):\n    \"\"\"\n    Divide arguments element-wise.\n\n    For full documentation refer to :obj:`numpy.linalg.inv`.\n\n    Limitations\n    -----------\n        Input array is supported as :obj:`dpnp.ndarray`.\n        Dimension of input array is supported to be equal to ``2``.\n        Shape of input array is limited by ``input.shape[0] == input.shape[1]``, ``input.shape[0] >= 2``.\n        Otherwise the function will be executed sequentially on CPU.\n    \"\"\"\n\n    is_input_dparray = isinstance(input, dparray)\n\n    if (not use_origin_backend(input) and is_input_dparray):\n        if input.ndim == 2 and input.shape[0] == input.shape[1] and input.shape[0] >= 2:\n            return dpnp_inv(input)\n\n    return call_origin(numpy.linalg.inv, input)\n\n\ndef matrix_power(input, count):\n    \"\"\"\n    Raise a square matrix to the (integer) power `count`.\n\n    Parameters\n    ----------\n    input : sequence of array_like\n\n    Returns\n    -------\n    output : dparray\n        Returns the dot product of the supplied arrays.\n\n    See Also\n    --------\n    :obj:`numpy.linalg.matrix_power`\n\n    \"\"\"\n\n    is_input_dparray = isinstance(input, dparray)\n\n    if not use_origin_backend(input) and is_input_dparray and count > 0:\n        result = input\n        for id in range(count - 1):\n            result = dpnp.matmul(result, input)\n\n        return result\n\n    input1 = dpnp.asnumpy(input) if is_input_dparray else input\n\n    # TODO need to put dparray memory into NumPy call\n    result_numpy = numpy.linalg.matrix_power(input1, count)\n    result = result_numpy\n    if isinstance(result, numpy.ndarray):\n        result = dparray(result_numpy.shape, dtype=result_numpy.dtype)\n        for i in range(result.size):\n            result._setitem_scalar(i, result_numpy.item(i))\n\n    return result\n\n\ndef matrix_rank(input, tol=None, hermitian=False):\n    \"\"\"\n    Return matrix rank of array\n    Rank of the array is the number of singular values of the array that are\n    greater than `tol`.\n\n    Parameters\n    ----------\n    M : {(M,), (..., M, N)} array_like\n        Input vector or stack of matrices.\n    tol : (...) array_like, float, optional\n        Threshold below which SVD values are considered zero. If `tol` is\n        None, and ``S`` is an array with singular values for `M`, and\n        ``eps`` is the epsilon value for datatype of ``S``, then `tol` is\n        set to ``S.max() * max(M.shape) * eps``.\n    hermitian : bool, optional\n        If True, `M` is assumed to be Hermitian (symmetric if real-valued),\n        enabling a more efficient method for finding singular values.\n        Defaults to False.\n\n    Returns\n    -------\n    rank : (...) array_like\n        Rank of M.\n\n    \"\"\"\n\n    is_input_dparray = isinstance(input, dparray)\n\n    if not use_origin_backend(input) and is_input_dparray:\n        if tol is not None:\n            checker_throw_value_error(\"matrix_rank\", \"tol\", type(tol), None)\n        if hermitian is not False:\n            checker_throw_value_error(\"matrix_rank\", \"hermitian\", hermitian, False)\n\n        result = dpnp_matrix_rank(input)\n\n        # scalar returned\n        if result.shape == (1,):\n            return result.dtype.type(result[0])\n\n        return result\n\n    return call_origin(numpy.linalg.matrix_rank, input, tol, hermitian)\n\n\ndef multi_dot(arrays, out=None):\n    \"\"\"\n    Compute the dot product of two or more arrays in a single function call\n\n    Parameters\n    ----------\n    arrays : sequence of array_like\n        If the first argument is 1-D it is treated as row vector.\n        If the last argument is 1-D it is treated as column vector.\n        The other arguments must be 2-D.\n    out : ndarray, optional\n        unsupported\n\n    Returns\n    -------\n    output : ndarray\n        Returns the dot product of the supplied arrays.\n\n    See Also\n    --------\n    :obj:`numpy.multi_dot`\n\n    \"\"\"\n\n    n = len(arrays)\n\n    if n < 2:\n        checker_throw_value_error(\"multi_dot\", \"arrays\", n, \">1\")\n\n    result = arrays[0]\n    for id in range(1, n):\n        result = dpnp.dot(result, arrays[id])\n\n    return result\n\n\ndef norm(input, ord=None, axis=None, keepdims=False):\n    \"\"\"\n    Matrix or vector norm.\n    This function is able to return one of eight different matrix norms,\n    or one of an infinite number of vector norms (described below), depending\n    on the value of the ``ord`` parameter.\n\n    Parameters\n    ----------\n    input : array_like\n        Input array.  If `axis` is None, `x` must be 1-D or 2-D, unless `ord`\n        is None. If both `axis` and `ord` are None, the 2-norm of\n        ``x.ravel`` will be returned.\n    ord : optional\n        Order of the norm (see table under ``Notes``). inf means numpy's\n        `inf` object. The default is None.\n    axis : optional.\n        If `axis` is an integer, it specifies the axis of `x` along which to\n        compute the vector norms.  If `axis` is a 2-tuple, it specifies the\n        axes that hold 2-D matrices, and the matrix norms of these matrices\n        are computed.  If `axis` is None then either a vector norm (when `x`\n        is 1-D) or a matrix norm (when `x` is 2-D) is returned. The default\n        is None.\n    keepdims : bool, optional\n        If this is set to True, the axes which are normed over are left in the\n        result as dimensions with size one.  With this option the result will\n        broadcast correctly against the original `x`.\n\n    Returns\n    -------\n    n : float or ndarray\n        Norm of the matrix or vector(s).\n    \"\"\"\n\n    if not use_origin_backend(input):\n        if not isinstance(input, dparray):\n            pass\n        elif not isinstance(axis, int) and not isinstance(axis, tuple) and axis is not None:\n            pass\n        elif keepdims is not False:\n            pass\n        elif ord not in [None, 0, 3, 'fro', 'f']:\n            pass\n        else:\n            result = dpnp_norm(input, ord=ord, axis=axis)\n\n            # scalar returned\n            if result.shape == (1,) and axis is None:\n                return result.dtype.type(result[0])\n\n            return result\n\n    return call_origin(numpy.linalg.norm, input, ord, axis, keepdims)\n\n\n#linalg.qr(a, mode='reduced')\ndef qr(a, mode='complete'):\n    \"\"\"\n    Compute the qr factorization of a matrix.\n\n    Factor the matrix `a` as *qr*, where `q` is orthonormal and `r` is\n    upper-triangular.\n\n    For full documentation refer to :obj:`numpy.linalg.qr`.\n\n    Limitations\n    -----------\n    Input array is supported as :obj:`dpnp.ndarray`.\n    Parameter mode='complete' is supported.\n\n    \"\"\"\n\n    if not use_origin_backend(a):\n        if not isinstance(a, dparray):\n            pass\n        elif not mode == 'complete':\n            pass\n        else:\n            return dpnp_qr(a, mode)\n\n    return call_origin(numpy.linalg.qr, a, mode)\n\n\ndef svd(a, full_matrices=True, compute_uv=True, hermitian=False):\n    \"\"\"\n    Singular Value Decomposition.\n\n    For full documentation refer to :obj:`numpy.linalg.svd`.\n\n    Examples\n    --------\n    >>> import dpnp as np\n    >>> a = np.random.randn(9, 6) + 1j*np.random.randn(9, 6)\n    >>> b = np.random.randn(2, 7, 8, 3) + 1j*np.random.randn(2, 7, 8, 3)\n\n    Reconstruction based on full SVD, 2D case:\n\n    >>> u, s, vh = np.linalg.svd(a, full_matrices=True)\n    >>> u.shape, s.shape, vh.shape\n    ((9, 9), (6,), (6, 6))\n    >>> np.allclose(a, np.dot(u[:, :6] * s, vh))\n    True\n    >>> smat = np.zeros((9, 6), dtype=complex)\n    >>> smat[:6, :6] = np.diag(s)\n    >>> np.allclose(a, np.dot(u, np.dot(smat, vh)))\n    True\n\n    Reconstruction based on reduced SVD, 2D case:\n\n    >>> u, s, vh = np.linalg.svd(a, full_matrices=False)\n    >>> u.shape, s.shape, vh.shape\n    ((9, 6), (6,), (6, 6))\n    >>> np.allclose(a, np.dot(u * s, vh))\n    True\n    >>> smat = np.diag(s)\n    >>> np.allclose(a, np.dot(u, np.dot(smat, vh)))\n    True\n\n    Reconstruction based on full SVD, 4D case:\n\n    >>> u, s, vh = np.linalg.svd(b, full_matrices=True)\n    >>> u.shape, s.shape, vh.shape\n    ((2, 7, 8, 8), (2, 7, 3), (2, 7, 3, 3))\n    >>> np.allclose(b, np.matmul(u[..., :3] * s[..., None, :], vh))\n    True\n    >>> np.allclose(b, np.matmul(u[..., :3], s[..., None] * vh))\n    True\n\n    Reconstruction based on reduced SVD, 4D case:\n\n    >>> u, s, vh = np.linalg.svd(b, full_matrices=False)\n    >>> u.shape, s.shape, vh.shape\n    ((2, 7, 8, 3), (2, 7, 3), (2, 7, 3, 3))\n    >>> np.allclose(b, np.matmul(u * s[..., None, :], vh))\n    True\n    >>> np.allclose(b, np.matmul(u, s[..., None] * vh))\n    True\n\n    \"\"\"\n\n    if not use_origin_backend(a):\n        if not isinstance(a, dparray):\n            pass\n        elif not a.ndim == 2:\n            pass\n        elif not full_matrices == True:\n            pass\n        elif not compute_uv == True:\n            pass\n        elif not hermitian == False:\n            pass\n        else:\n            return dpnp_svd(a, full_matrices, compute_uv, hermitian)\n\n    return call_origin(numpy.linalg.svd, a, full_matrices, compute_uv, hermitian)\n", "meta": {"hexsha": "da8c1d765a8dcf90f3257eaee7f3225a97ad27b1", "size": 14827, "ext": "py", "lang": "Python", "max_stars_repo_path": "dpnp/linalg/dpnp_iface_linalg.py", "max_stars_repo_name": "Rubtsowa/dpnp", "max_stars_repo_head_hexsha": "ef404c0f284b0c508ed1e556e140f02f76ae5551", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dpnp/linalg/dpnp_iface_linalg.py", "max_issues_repo_name": "Rubtsowa/dpnp", "max_issues_repo_head_hexsha": "ef404c0f284b0c508ed1e556e140f02f76ae5551", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dpnp/linalg/dpnp_iface_linalg.py", "max_forks_repo_name": "Rubtsowa/dpnp", "max_forks_repo_head_hexsha": "ef404c0f284b0c508ed1e556e140f02f76ae5551", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3023715415, "max_line_length": 105, "alphanum_fraction": 0.6113846361, "include": true, "reason": "import numpy", "num_tokens": 3713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.19589227684112068}}
{"text": "import numpy as np\nimport array\nimport os, sys\nimport re\nimport time\nimport multiprocessing\nimport h5py\nimport logging\nfrom astropy.table import Table, Column\nfrom astropy import units as u\n\n\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-p\",\"--params\", type=str,\n                    help = \"Parameter file\")\nparser.add_argument(\"-q\", \"--quiet\", help = \"Suppress extra outputs\",\n                    action = \"store_true\")\nargs = parser.parse_args()\nquiet = args.quiet\n\nparams_root = re.split(\".py\", args.params)[0]\nif os.path.isfile(params_root+\".pyc\"):\n    os.remove(params_root+\".pyc\")\n\nimport importlib\ntry:\n    params = importlib.import_module(params_root)\n    print('Successfully loaded \"{0}\" as params'.format(args.params))\n    importlib.reload(params)\nexcept:\n    print('Failed to load \"{0}\" as params'.format(args.params))\n    raise\n\nif quiet:\n    quietprint = lambda *a: None\nelse:\n    def quietprint(*args):\n        for arg in args:\n            print(arg, end=' ')\n        print()\n\n# Fitting function definition for later use by Processess\n\ndef galaxyFit(inputQueue, printQueue, printlock):\n    for gal in iter(inputQueue.get, 'STOP'):\n        j = np.argmin(np.abs(z-zobs[gal])) # Find closest model redshift\n\n\n        flux_obs = obs[gal,:]\n        flux_err = obs_err[gal,:]\n        \n        #flux_obs[fo <= 0.] = 0.       # Set negative fluxes to zero\n        I = np.where(flux_err > 0.)[0] # Find bands with no observation\n        \n        if len(I) == 0:\n            if include_rest:\n                M_scaled = np.ones(len(fo)) * -99.\n                restframe_output = ' '.join(M_scaled.astype('str'))\n                output_string = '{0} {1} {2} {3} {4} {5} {6} {7}' \\\n                                ' {8} {9} {10} {11} {12} {13} {14} {15} {16}'.format(gal+1,ID[gal],zobs[gal],-99,-99,-99,-99,-99,-99, -99, -99,-99,len(I),-99,z[j],restframe_output,'\\n')\n            else:\n                output_string = '{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11} {12} {13} {14}'.format(gal+1,ID[gal],zobs[gal],-99,-99,-99,-99,-99,-99,-99, -99,-99,len(I),-99,'\\n')\n            printQueue.put(output_string)\n            continue\n            \n        flux_obs = flux_obs[I]                    # and exclude from fit\n        flux_err = flux_err[I]\n        flux_models = f[j,I,:]\n\n        tot_err = np.sqrt(flux_err**2 + (0.1*flux_obs)**2)\n        \n        top = 0.\n        bottom = 0.\n    \n        for i in range(len(flux_obs)):\n            top += (flux_models[i,:]*flux_obs[i])/(tot_err[i]**2)\n            bottom += (flux_models[i,:]**2)/(tot_err[i]**2)\n    \n        scale = top/bottom\n        scale = np.reshape(scale, (n_metal, n_tg, n_tau, n_tauv, n_fesc))  \n\n        chisq = 0.\n        for i in range(len(flux_obs)):\n            chisq += ((np.abs(scale*flux_models[i,:]-flux_obs[i])**2)/(flux_err[i])**2)\n\n        chimin, minind = np.nanmin(chisq), np.nanargmin(chisq)\n        \n        if np.isinf(chimin) or np.isnan(minind):\n            if include_rest:\n                M_scaled = np.ones(len(flux_obs)) * -99.\n                restframe_output = ' '.join(M_scaled.astype('str'))\n                output_string = '{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11} {12} {13} {14} {15} {16}'.format(gal+1,ID[gal],zobs[gal],-99,-99,-99,-99,-99,-99, -99, -99,-99,len(I),-99,z[j],restframe_output,'\\n')\n            else:\n                output_string = '{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11} {12} {13} {14}'.format(gal+1,ID[gal],zobs[gal],-99,-99,-99,-99,-99,-99,-99, -99,-99,len(I),-99,'\\n')\n            printQueue.put(output_string)\n            continue\n\n\n        #Find the coordinate of the model with the bestfit mass\n        mi, tgi, ti, tvi, fi = np.unravel_index(minind, \n                                                   (n_metal, n_tg, \n                                                   n_tau, n_tauv, n_fesc)) \n\n        Bestfit_Mass = np.log10(scale[mi, tgi, ti, tvi, fi]*flux_corr)\n        Bestfit_SFR = (scale[mi, tgi, ti, tvi, fi] * \n                       SFR[mi, tgi, ti, tvi, fi]*flux_corr)\n        #Bestfit_Beta = beta[tgi,tvi,ti,mi]\n        Bestfit_Beta = -99.\n\n        #Scale the observed tot_mag band of the template to be the same as the observed tot_mag band of the galaxy\n        #Convert the templates so they are no longer units of per stellar mass\n\n        F_rest = f[0,:]*scale[mi, tgi, ti, tvi, fi]*flux_corr\n        restframeMags = 23.9 - 2.5*np.log10(F_rest)\n    \n        #UV_rest = UV_flux[0]*scale[tgi,tvi,ti,mi]*flux_corr\n        #restframeMUV = 23.9 - 2.5*np.log10(UV_rest)\n\n        M_scaled = restframeMags[:, mi, tgi, ti, tvi, fi]\n        #MUV_scaled = restframeMUV[tgi,tvi,ti,mi]\n        MUV_scaled = -99.\n        \n        if np.isnan(Bestfit_Mass) or np.isinf(chimin):\n            Bestfit_Mass = -99\n            #M_scaled[:] = -99\n            tgs = -99\n            tvs = -99\n            taus = -99\n            mis = -99\n            escape_fraction = -99\n\n        else:\n            tgs = tg[tgi]/1e9\n            tvs = tv[tvi]\n            taus = tau[ti]\n            mis = metallicities[mi]\n            escape_fraction = fesc[fi] \n\n\n        printlock.acquire()\n\n        print('{0:6d} {1:8d} {2:>5.2f} {3:>7.2f} {4:>8.1f} {5:>8.3f} {6:>5.1f} {7:>8.2f} {8:>4.2f} {9:>5.2f}'.format(gal+1,ID[gal], zobs[gal],Bestfit_Mass,chimin,tgs,tvs,taus,mis,np.log10(Bestfit_SFR)))\n\n        if include_rest:\n            restframe_output = ' '.join(M_scaled.astype('str'))\n            output_string = '{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11} {12} {13} {14} {15} {16}'.format(gal+1,ID[gal],zobs[gal],Bestfit_Mass,chimin,tgs,tvs,taus,mis, MUV_scaled, minind,Bestfit_SFR,len(I),Bestfit_Beta,z[j],restframe_output,'\\n')\n        else:\n            output_string = '{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11} {12} {13} {14}'.format(gal+1,ID[gal],zobs[gal],Bestfit_Mass,chimin,tgs,tvs,taus,mis, MUV_scaled, minind,Bestfit_SFR,len(I),Bestfit_Beta,'\\n')\n\n        printlock.release()\n        printQueue.put(output_string)\n\ndef galaxyFit2(inputQueue, printQueue, printlock):\n    for gal in iter(inputQueue.get, 'STOP'):\n        \n        \n        output_string = '{0[0]} {0[1]} {0[2]} {0[3]} {0[4]} {0[5]} ' + \\\n                        '{0[6]} {0[7]} {0[8]} {0[9]} {0[10]} {0[11]} ' + \\\n                        '{0[12]} {0[13]} {0[14]}'\n        \n        j = np.argmin(np.abs(z-zobs[gal])) # Find closest model redshift\n\n        log_mass_min, log_mass_max = 7, 13\n        log_sfr_min, log_sfr_max = -3, 4\n\n        flux_obs = obs[gal,:]\n        flux_err = obs_err[gal,:]\n        \n        #flux_obs[fo <= 0.] = 0.       # Set negative fluxes to zero\n        I = np.where(flux_err > 0.)[0] # Find bands with no observation\n        \n        if len(I) == 0:\n            output_array = [gal+1, ID[gal], zobs[gal], z[j],\n                            -99, -99, -99, -99, -99, -99, -99,\n                            -99,-99,len(I),-99,'\\n']\n            output = output_string.format(output_array)\n            \n            if include_rest:\n                M_scaled = np.ones(len(flux_obs)) * -99.\n                restframe_output = ' '.join(M_scaled.astype('str'))\n                output = output + restframe_output + ' \\n'\n                \n            else:\n                output = output + ' \\n'\n            printQueue.put(output_string)\n            continue\n            \n        flux_obs = flux_obs[I]                    # and exclude from fit\n        flux_err = flux_err[I]\n        flux_models = f[j,I,:]\n\n        tot_err = np.sqrt(flux_err**2 + (params.flux_err*flux_obs)**2)\n\n        top = 0.\n        bottom = 0.\n    \n        for i in range(len(flux_obs)):\n            top += (flux_models[i,:]*flux_obs[i])/(tot_err[i]**2)\n            bottom += (flux_models[i,:]**2)/(tot_err[i]**2)\n    \n        scale = top/bottom\n        scale = np.reshape(scale, (n_metal, n_tg, n_tau, n_tauv, n_fesc))  \n\n        chisq = 0.\n        for i in range(len(flux_obs)):\n            chisq += ((np.abs(scale*flux_models[i,:]-flux_obs[i])**2)/(tot_err[i])**2)\n\n        chimin, minind = np.nanmin(chisq), np.nanargmin(chisq)\n        likelihood = np.reshape(np.exp(-0.5*chisq), \n                                (n_metal, n_tg, n_tau, n_tauv, n_fesc))\n        likelihood[np.isnan(likelihood)] = 0.\n        likelihood = np.abs(likelihood/likelihood.sum())\n        \n        \n        if np.isinf(chimin) or np.isnan(minind):\n            output_array = [gal+1, ID[gal], zobs[gal], z[j],\n                            -99, -99, -99, -99, -99, -99, -99,\n                            -99,-99,len(I),-99,'\\n']\n            output = output_string.format(output_array)\n\n        else:\n            #Find the coordinate of the model with the bestfit mass\n            mi, tgi, ti, tvi, fi = np.unravel_index(minind, \n                                                       (n_metal, n_tg, \n                                                       n_tau, n_tauv, n_fesc)) \n\n            Masses = np.abs(np.log10(scale*flux_corr))\n            SFRs = np.abs(np.log10(scale * SFR * flux_corr))\n        \n            mass_hist = np.histogram(Masses.flatten(),\n                                     range = (log_mass_min, log_mass_max),\n                                     bins = 120,\n                                     weights = likelihood.flatten(),\n                                     density = True)\n                                 \n            sfr_hist = np.histogram(SFRs.flatten(),\n                                     range = (log_sfr_min, log_sfr_max),\n                                     bins = 140,\n                                     weights = likelihood.flatten(),\n                                     density = True)\n        \n            Bestfit_Mass = np.abs(np.log10(scale[mi, tgi, ti, tvi, fi]*flux_corr))\n            Bestfit_SFR = np.abs(np.log10(scale[mi, tgi, ti, tvi, fi] * \n                                   SFR[mi, tgi, ti, tvi, fi]*flux_corr))\n        \n            if np.isnan(Bestfit_Mass) or np.isinf(chimin):\n                Bestfit_Mass = -99\n                #M_scaled[:] = -99\n                tgs = -99\n                tvs = -99\n                taus = -99\n                mis = -99\n                escape_fraction = -99\n\n            else:\n                tgs = tg[tgi]/1e9\n                tvs = tv[tvi]\n                taus = tau[ti]\n                mis = metallicities[mi]\n                escape_fraction = fesc[fi] \n\n            m16, m50, m84 = weighted_quantile(Masses.flatten(), \n                                              [0.16, 0.5, 0.84],\n                                              sample_weight=likelihood.flatten(),\n                                              values_sorted=False)\n            s16, s50, s84 = weighted_quantile(SFRs.flatten(), \n                                              [0.16, 0.5, 0.84],\n                                              sample_weight=likelihood.flatten(),\n                                              values_sorted=False)\n\n            printlock.acquire()\n\n            MUV_scaled = -99. \n            Bestfit_Beta = -99.\n        \n            print_string = \"{0[0]:6d} {0[1]:8d} {0[2]:>5.2f} \" + \\\n                           \"{0[3]:>7.2f} {0[4]:>8.1f} {0[5]:>8.3f} \" + \\\n                           \"{0[6]:>5.1f} {0[7]:>8.2f} {0[8]:>4.2f} \" + \\\n                           \"{0[9]:>5.2f}\"\n                       \n            print_array = [gal+1, ID[gal], zobs[gal],\n                           Bestfit_Mass, chimin, \n                           tgs, tvs, taus, mis, \n                           Bestfit_SFR]                  \n            print(print_string.format(print_array))\n\n            output_string = '{n} {id} {zobs} {ztemp} {mass_best} {sfr_best} '+ \\\n                            '{chi_best} {tg} {tvs} {taus} {mis} {fesc} '+ \\\n                            '{mass_med} {mass_l68} {mass_u68} ' + \\\n                            '{sfr_med} {sfr_l68} {sfr_u68} ' + \\\n                            '{nfilts} '\n                        \n            output_values = {'n': gal+1,\n                             'id': ID[gal],\n                             'zobs': zobs[gal], 'ztemp':z[j],\n                             'mass_best': Bestfit_Mass,\n                             'sfr_best': Bestfit_SFR,\n                             'chi_best': chimin,\n                             'tg': tgs, 'tvs': tvs, 'taus': taus, \n                             'mis': mis, 'fesc': escape_fraction,\n                             'mass_med': m50, 'mass_l68': m16, 'mass_u68': m84,\n                             'sfr_med': s50, 'sfr_l68': s16, 'sfr_u68': s84,\n                             'nfilts': len(I)}\n\n            output_array = [gal+1, ID[gal], zobs[gal], \n                            Bestfit_Mass, chimin, tgs, tvs, taus, mis, \n                            MUV_scaled, minind, Bestfit_SFR, len(I), -99., '\\n']\n            output = output_string.format(**output_values)\n        \n        if include_rest:\n            if np.isinf(chimin) or np.isnan(minind):\n                M_scaled = np.ones(len(flux_obs)) * -99.\n                restframe_output = ' '.join(M_scaled.astype('str'))\n                output = output + restframe_output + ' \\n'\n            \n            else:\n                F_rest = np.array(f[0, :, mi, tgi, ti, tvi, fi] * \n                                  scale[mi, tgi, ti, tvi, fi] * flux_corr)\n                restframeMags = 23.9 - 2.5*np.log10(F_rest)\n                restframe_output = ' '.join(restframeMags.astype('str'))\n                output = output + restframe_output + ' \\n'\n        else:\n            output = output + ' \\n'\n            \n        printlock.release()\n        printQueue.put([output, mass_hist, sfr_hist])\n\ndef galaxyFitPlus(inputQueue, printQueue, printlock):\n    for gal in iter(inputQueue.get, 'STOP'):\n        mass_range = 7, 13\n        log_sfr_min, log_sfr_max = -3, 4\n        \n        j = np.argmin(np.abs(z-zobs[gal])) # Find closest model redshift\n\n        fo = obs[gal,:]\n        ferr = obs_err[gal,:]\n\n\n        flux_obs[fo <= 0.] = 0.       # Set negative fluxes to zero\n        #print fo\n        I = (ferr > 0.)*(ferr < 1e6) # Find bands with no observation\n        fo = flux_obs[I]                    # and exclude from fit\n        ferr = flux_err[I]\n        fm = f[I,j,:]\n        #print flux_models[:,0,0,0,0]        \n\n        top = 0.\n        bottom = 0.\n    \n        for i in range(len(fo)):\n            top += (flux_models[i,:]*flux_obs[i])/(flux_err[i]**2)\n            bottom += (flux_models[i,:]**2)/(flux_err[i]**2)\n    \n        scale = top/bottom\n        scale = np.reshape(scale, (n_metal, n_tg, n_tau, n_tauv, n_fesc))  \n\n        chisq = 0.\n        for i in range(len(fo)):\n            chisq += ((np.abs(scale*flux_models[i,:]-flux_obs[i])**2)/(flux_err[i])**2)\n\n        chimin, minind = np.nanmin(chisq), np.nanargmin(chisq)\n\n        chisq -= (chisq.min() - 1)\n        likelihood = np.exp(-0.5*chisq)\n        likelihood /= likelihood.sum()\n        \n        if np.isinf(chimin) or np.isnan(minind) or len(fo) == 0:\n            output_string = '{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} \\\n            {10} {11} {12} {13} {14} {15} {16} {17} {18}'.format(gal+1,ID[gal],zobs[gal],\n                                                                 -99,-99,-99,-99,-99,-99,\n                                                                 -99, -99, -99, -99,-99,-99,-99,\n                                                                 len(I),-99,'\\n')\n            \n            massLikelihood = np.zeros(mass_bins+1)\n            massLikelihood[0] = gal\n            muvLikelihood = np.zeros(muv_bins+1)\n            muvLikelihood[0] = gal\n            betaLikelihood = np.zeros(beta_bins+1)\n            betaLikelihood[0] = gal\n            #tauLikelihood = np.zeros(n_tau)        \n            #tauLikelihood = np.insert(tauLikelihood,0,gal)        \n            printQueue.put([output_string,massLikelihood,muvLikelihood,betaLikelihood])\n            continue\n\n        #Find the coordinate of the model with the bestfit mass\n        si,tgi,tvi,ti,mi = np.unravel_index(minind,(mass_bins,n_tg,n_tauv,n_tau,n_ssp))\n        Bestfit_Mass = np.log10(mass_range[si]*flux_corr)\n        Bestfit_SFR = (mass_range[si]*SFR[tgi,ti,mi]*flux_corr)\n        Bestfit_Beta = beta[tgi,tvi,ti,mi]\n\n        F_rest = f[:,0]*mass_range[likelihood.argmax(0)]*flux_corr\n        restframeMags = 23.9 - 2.5*np.log10(F_rest)\n    \n        UV_rest = UV_flux[0]*mass_range[likelihood.argmax(0)]*flux_corr\n        restframeMUV = 23.9 - 2.5*np.log10(UV_rest)\n\n        Bestfit_restframeMags = restframeMags[:,tgi,tvi,ti,mi]\n        Bestfit_restframeMUV = restframeMUV[tgi,tvi,ti,mi]\n\n        if np.isnan(Bestfit_Mass) or np.isinf(chimin):\n            Bestfit_Mass = -99\n            #M_scaled[:] = -99\n            tgs = -99\n            tvs = -99\n            taus = -99\n            mis = -99\n\n        else:\n            tgs = tg[tgi]/1.e9\n            tvs = tv[tvi]\n            taus = tau[ti]/1.e9\n            mis = mi\n            \n        \"\"\"\n        Likelihood array section:\n        \"\"\"\n        mass_hist = np.histogram(np.log10(mass_))\n        \n        printlock.acquire()\n\n        if calc_mode:\n            print('{0:4d} {1:6d} {2:>6.2f} {3:>8.1f} {4:>6.2f}'.format(gal+1,ID[gal],Bestfit_Mass,chimin, np.log10(Mode_Mass), '/n'))\n        else:\n            print('{0:6d} {1:8f} {2:>5.2f} {3:>7.2f} {4:>8.1f} {5:>8.3f} {6:>5.1f} {7:>8.2f} {8:>3d} {9:>5.2f}'.format(gal+1,int(ID[gal]),zobs[gal],Bestfit_Mass,chimin,tgs,tvs,taus,mis,np.log10(Bestfit_SFR)))\n\n        output_string = '{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11} {12} {13} {14} {15}'.format(gal+1,int(ID[gal]),zobs[gal],Bestfit_Mass,chimin,tgs,tvs,taus,mis,Bestfit_restframeMags[tot],Bestfit_restframeMUV,minind,Bestfit_SFR,len(I),Bestfit_Beta,'\\n')\n\n        printlock.release()\n        printQueue.put([output_string, massLikelihoods, muvLikelihoods, betaLikelihoods])\n\n\ndef getObservations(inputpath):\n    input_data = Table.read(inputpath,format=input_format)\n\n    column_names = list(input_data.columns.keys())\n\n    ID = input_data[ID_col]\n    zobs = input_data[z_col]\n\n    filter_names = []\n\n    k,l = 0,0\n    for ii in range(len(column_names)):\n        if column_names[ii].lower().endswith(flux_col_end.lower()):\n            if k == 0:\n                fluxes = input_data[column_names[ii]]\n            else:\n                fluxes = np.column_stack((fluxes,input_data[column_names[ii]]))\n            k+=1\n            filter_names.append(column_names[ii])\n\n        if column_names[ii].lower().endswith(fluxerr_col_end.lower()):\n            if l == 0:\n                fluxerrs = input_data[column_names[ii]]\n            else:\n                fluxerrs = np.column_stack((fluxerrs,input_data[column_names[ii]]))\n            l+=1\n    \"\"\"        \n    if filts_used != None:\n        try:\n            fluxes = fluxes[:,filts_used]\n            fluxerrs = fluxerrs[:,filts_used]\n        except:r\n            print('Filter mismatch 1')\n            # Array slicing fail\n    \"\"\"\n    return ID, zobs, fluxes, fluxerrs, k, filter_names\n\nclass _function_wrapper(object):\n    \"\"\"\n    This is a hack to make the likelihood function pickleable when ``args``\n    or ``kwargs`` are also included.\n    \n    Stolen from emcee\n    \"\"\"\n    def __init__(self, f, args, kwargs):\n        self.f = f\n        self.args = args\n        self.kwargs = kwargs\n\n    def __call__(self, x):\n        try:\n            return self.f(x, *self.args, **self.kwargs)\n        except:\n            import traceback\n            print(\"emcee: Exception while calling your likelihood function:\")\n            print(\"  params:\", x)\n            print(\"  args:\", self.args)\n            print(\"  kwargs:\", self.kwargs)\n            print(\"  exception:\")\n            traceback.print_exc()\n            raise\n\ndef weighted_quantile(values, quantiles, sample_weight=None, values_sorted=False, old_style=False):\n    \"\"\" Very close to np.percentile, but supports weights.\n    NOTE: quantiles should be in [0, 1]!\n    :param values: np.array with data\n    :param quantiles: array-like with many quantiles needed\n    :param sample_weight: array-like of the same length as `array`\n    :param values_sorted: bool, if True, then will avoid sorting of initial array\n    :param old_style: if True, will correct output to be consistent with np.percentile.\n    :return: np.array with computed quantiles.\n    \"\"\"\n    values = np.array(values)\n    quantiles = np.array(quantiles)\n    if sample_weight is None:\n        sample_weight = np.ones(len(values))\n    sample_weight = np.array(sample_weight)\n    assert np.all(quantiles >= 0) and np.all(quantiles <= 1), 'quantiles should be in [0, 1]'\n\n    if not values_sorted:\n        sorter = np.argsort(values)\n        values = values[sorter]\n        sample_weight = sample_weight[sorter]\n\n    weighted_quantiles = np.cumsum(sample_weight) - 0.5 * sample_weight\n    if old_style:\n        # To be convenient with np.percentile\n        weighted_quantiles -= weighted_quantiles[0]\n        weighted_quantiles /= weighted_quantiles[-1]\n    else:\n        weighted_quantiles /= np.sum(sample_weight)\n    return np.interp(quantiles, weighted_quantiles, values)\n\nif __name__ == '__main__':\n    \n    logfile = open(\"error.log\", \"w\")\n    original_stderr = sys.stderr\n    sys.stderr = logfile\n    \n    start = time.time()\n    \n    \"\"\"\n    SECTION 1\n\n    \"\"\"\n    model_path = params.model_path\n\n    input_catalog = params.input_catalog\n    input_format = params.input_format\n    z_col = params.z_col\n    ID_col = params.ID_col\n    flux_col_end = params.flux_col_end\n    fluxerr_col_end = params.fluxerr_col_end\n\n    ncpus = params.ncpus\n    filts_used = params.filts_used\n    include_rest = params.include_rest\n    \n    output_path = params.output_catalog_path\n    output_format = params.output_format\n    output_hdf_path = params.output_hdf_path\n    \n    calc_mode = params.fitting_mode\n    flux_corr = params.flux_corr \n\n    \n    ID, zobs, obs, obs_err, filters_found, filter_names = getObservations(input_catalog)\n    \n    \"\"\"\n    Section 2\n    \n    \"\"\"\n\n\n    print(\"Loading synthetic mags and mass array:\")\n    models = h5py.File(model_path, 'r')\n    tg = models['ages'].value\n    tv = models['dust'].value\n    tau = models['sfh'].value\n    metallicities = models['metallicities'].value\n    fesc = models['fesc'].value\n\n    Mshape = models['fluxes'].shape\n    z = models['z']\n    nfilts = Mshape[1]\n    n_metal = Mshape[2]        \n    n_tg = Mshape[3]\n    n_tau = Mshape[4]\n    n_tauv = Mshape[5]\n    n_fesc = Mshape[6]\n    \n    #UV_flux = synmags['UV_flux']\n    SFR = models['SFR']\n    Ms = models['Ms']\n\n    if (nfilts == filters_found) and (filts_used == None):\n        f = models['fluxes']\n    \n    elif filts_used != None:\n        try:        \n            f = models['fluxes'][:,filts_used]\n            obs = obs[:,filts_used]\n            obs_err = obs_err[:,filts_used]\n            filter_names = np.array(filter_names)[filts_used]\n        except:\n            print('Mis-match between model and observed filter numbers')\n            raise\n            # Slice fail\n\n    print (\"Done.\")\n\n    \"\"\"\n    SECTION 3\n    \"\"\"\n    if os.path.isfile(output_path+\".temp_output.txt\"):\n        os.remove(output_path+\".temp_output.txt\")\n    temp_file = open(output_path+\".temp_output.txt\",\"w\")\n    \n    \"\"\"\n    SECTION 4\n    Chi-sq calculation\n\n    \"\"\"\n    out_string = '{0:6s} {1:8s} {2:>5s} {3:>7s} {4:>8s} {5:>8s}' + \\\n                 '{6:>5s} {7:>8s} {8:>4s} {9:>5s}'\n\n    print(out_string.format('N','ID','zobs','Best', 'chimin', \n                            'tg', 'tauv','tau','met', 'sfr'))\n\n    loop_start = time.time()\n    ncpus = np.clip(ncpus, 1, multiprocessing.cpu_count())\n\n    inputQueue = multiprocessing.Queue()\n    printQueue = multiprocessing.Queue()\n    printlock = multiprocessing.Lock()\n    \n    if calc_mode == 'hist':\n        output_hdf = h5py.File(output_hdf_path, 'w')\n        output_hdf.create_dataset(\"mass_pdf\", (len(ID), 120), dtype=\"f\")\n        output_hdf.create_dataset(\"sfr_pdf\", (len(ID), 140), dtype=\"f\")\n        fitFunction = galaxyFit2\n        \n    else:\n        fitFunction = galaxyFit\n    \n    for i in range( ncpus ):\n        multiprocessing.Process(target = fitFunction,\n                                args = (inputQueue, printQueue,\n                                        printlock)).start()\n\n    # Put elements in the send queue for processing\n    for gal in range( len(ID) ):\n        inputQueue.put( gal )\n\n    if calc_mode == 'hist':\n        for i, gal in enumerate(ID):\n            printout, mass_hist, sfr_hist = printQueue.get()\n            if i == 0:\n                mass_centers = 0.5*(mass_hist[1][1:] + mass_hist[1][:-1])\n                sfr_centers = 0.5*(sfr_hist[1][1:] + sfr_hist[1][:-1])\n                \n                output_hdf.create_dataset(\"mass_bins\", data = mass_centers)\n                output_hdf.create_dataset(\"sfr_bins\", data = sfr_centers)            \n            output_hdf[\"mass_pdf\"][i] = mass_hist[0]\n            output_hdf[\"sfr_pdf\"][i] = sfr_hist[0]\n            temp_file.write( printout )\n        #tau_array.tofile(tau_file)\n    else:\n        for i, gal in enumerate(ID):\n            printout = printQueue.get()\n            temp_file.write( printout )\n            #print len(mass_array), len(muv_array), len(beta_array)\n       \n\n    # Stop all the running processes\n    for i in range( ncpus ):\n        inputQueue.put( 'STOP' )\n\n    # Close both send and receive queues\n    inputQueue.close()\n    printQueue.close()\n\n    temp_file.close()    \n    models.close()\n    output_hdf.close()\n    print(\"Fitting time taken: {0:.2f} {1}\".format(time.time()-loop_start,\n                                                   '\\n'))\n    \n    \"\"\"\n    Section 3\n    Reload, format and save output table\n    \"\"\"\n    while temp_file.closed == False:\n        pause(0.1)\n\n    data = np.loadtxt(output_path+\".temp_output.txt\")\n    try:\n        rows, cols = data.shape\n    except:\n        cols = len(data)\n\n    output = Table()\n\n    names = ['N', 'ID', 'z', 'zmodel', \n             'Mass_best', 'SFR_best', 'chi_best', \n             'Age_best','Dust_best', 'SFH_best',\n             'Metallicity_best', 'fesc_best',\n             'Mass_median', 'Mass_l68', 'Mass_u68',\n             'SFR_median', 'SFR_l68', 'SFR_u68',\n             'Nfilts']\n             \n    units = [None, None, None, None,\n             u.Msun, u.Msun/u.yr, None,\n             u.Gyr, None, None, \n             None, None,\n             u.Msun, u.Msun, u.Msun,\n             u.Msun/u.yr, u.Msun/u.yr, u.Msun/u.yr,\n             None]\n             \n    types = ['i4', 'i4', 'f4', 'f4',\n             'f4', 'f4', 'f4',\n             'f4', 'f4', 'f4', \n             'f4', 'f4', \n             'f4', 'f4', 'f4',\n             'f4', 'f4', 'f4',\n             'i4']\n             \n    if include_rest:\n        for name in filter_names:\n            names.append(name[:-len(flux_col_end)]+'_rest')\n            units.append(u.mag)\n            types.append('f4')\n        \n    for col in range(cols):\n        column = Column( data[:,col], name = names[col], unit=units[col], dtype=types[col])\n        output.add_column(column)\n\n    table_format = 'ascii.commented_header'\n    output.sort('ID')\n    if os.path.isfile(output_path):\n        os.remove(output_path)\n    output.write(output_path,format=table_format)\n    print('Catalog saved')\n    \n    os.remove(temp_file.name)\n\n    print()\n    print(\"Total time taken: \"+str(time.time()-start))\n    \n    sys.stderr = original_stderr\n    logfile.close()\n    \n", "meta": {"hexsha": "c3e85afdfdee9ef07a1e191bf9bd299a9f45eb54", "size": 27412, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/data/fitting.py", "max_stars_repo_name": "dunkenj/smpy", "max_stars_repo_head_hexsha": "2c7ad73726e8fcfbbdf3667a918f60890c84673f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2015-04-09T13:51:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T00:25:05.000Z", "max_issues_repo_path": "scripts/data/fitting.py", "max_issues_repo_name": "bamford/smpy", "max_issues_repo_head_hexsha": "2c7ad73726e8fcfbbdf3667a918f60890c84673f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-04-29T13:00:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-17T13:50:16.000Z", "max_forks_repo_path": "scripts/data/fitting.py", "max_forks_repo_name": "dunkenj/smpy", "max_forks_repo_head_hexsha": "2c7ad73726e8fcfbbdf3667a918f60890c84673f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-08-12T13:15:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-07T14:05:43.000Z", "avg_line_length": 36.7946308725, "max_line_length": 261, "alphanum_fraction": 0.5086093682, "include": true, "reason": "import numpy,from astropy", "num_tokens": 7632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3557748935136303, "lm_q1q2_score": 0.19589227684112065}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n# Copyright 2018 The TensorFlow Authors All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Simple example of contextual bandits simulation.\n\nCode corresponding to:\nDeep Bayesian Bandits Showdown: An Empirical Comparison of Bayesian Deep Networks\nfor Thompson Sampling, by Carlos Riquelme, George Tucker, and Jasper Snoek.\nhttps://arxiv.org/abs/1802.09127\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport time,sys\nimport tensorflow as tf\nfrom absl import app\nfrom absl import flags\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nimport matplotlib\n# print(matplotlib.get_backend())\nfrom bandits.helpers.benchmarker import Benchmarker\nfrom bandits.algorithms.lin_ucb import LinUCB\nfrom bandits.algorithms.lin_epsilon import LinEpsilon\nfrom bandits.algorithms.neural_lin_ucb import NeuralLinUCB\n\nfrom bandits.algorithms.bootstrapped_bnn_sampling import BootstrappedBNNSampling\nfrom bandits.core.contextual_bandit import run_contextual_bandit\n# from bandits.data.data_sampler import sample_mushroom_data\nfrom bandits.algorithms.fixed_policy_sampling import FixedPolicySampling\nfrom bandits.algorithms.linear_full_posterior_sampling import LinearFullPosteriorSampling\nfrom bandits.algorithms.neural_linear_sampling import NeuralLinearPosteriorSampling\nfrom bandits.algorithms.parameter_noise_sampling import ParameterNoiseSampling\nfrom bandits.algorithms.posterior_bnn_sampling import PosteriorBNNSampling\nfrom bandits.data.synthetic_data_sampler import sample_linear_data\nfrom bandits.data.synthetic_data_sampler import sample_wheel_bandit_data\nfrom bandits.data.environments import  *\nfrom bandits.data.wasserstein_gans import WGANCovertype\n\nfrom bandits.data.bootstrap_thompson_sampling import generate_uniform_artificial, gan_artificial_covertype,\\\n    gan_artificial_mushroom, gan_artificial_linear, gan_artificial_wheel\n\nfrom bandits.algorithms.neural_linear_sampling import NeuralLinearPosteriorSampling\nfrom bandits.data.synthetic_data_sampler import sample_sparse_linear_data\nfrom bandits.data.synthetic_data_sampler import sample_wheel_bandit_data\nfrom bandits.algorithms.uniform_sampling import UniformSampling\n\nbase_route = os.getcwd()\ndata_route = 'contextual_bandits/datasets'\n\nFLAGS = flags.FLAGS\nFLAGS.set_default('alsologtostderr', True)\n\nflags.DEFINE_string('logdir', base_route, 'Base directory to save output')\nFLAGS(sys.argv)\n\n############# STARTS HERE ##############\"\"\"\nname = \"linear\"\ntest_name = \"full_analysis_\" + name\n\nif name==\"linear\":\n    num_actions = 8\n    context_dim = 10\n    num_contexts = 1500\n    # noise_stds = [0.01 * (i + 1) for i in range(num_actions)]\n    noise_stds = [1 for i in range(num_actions)]\n\n    wgan = WGANCovertype(context_dim, file=\"linear\")\n    wgan.train(epochs=400, batch_size=32, sample_interval=50)\n    artificial_data_generator = lambda: gan_artificial_linear(wgan, n_samples=50, n_actions=num_actions)\n\nelif name==\"mushroom\":\n    num_actions = 2\n    context_dim = 117\n    num_contexts = 1500\n    from bandits.data.wasserstein_gans import WGANMushroom\n    wgan = WGANMushroom(context_dim)\n    wgan.train(epochs=2000, batch_size=32, sample_interval=50)\n    artificial_data_generator = lambda: gan_artificial_mushroom(wgan, n_samples=50, n_actions=num_actions)\n\nelif name==\"wheel\":\n    num_actions = 5\n    context_dim = 2\n    num_contexts = 1500\n    delta = 0.95\n    mean_v = [1.0, 1.0, 1.0, 1.0, 1.2]\n    std_v = [0.05, 0.05, 0.05, 0.05, 0.05]\n    mu_large = 50\n    std_large = 0.01\n    from bandits.data.wasserstein_gans import WGANCovertype\n    wgan = WGANCovertype(context_dim, file=\"wheel\")\n    wgan.train(epochs=1000, batch_size=32, sample_interval=50)\n    artificial_data_generator = lambda: gan_artificial_wheel(wgan, n_samples=50, n_actions=num_actions)\n\n\nelif name==\"covertype\":\n    num_actions = 7\n    context_dim = 54\n    num_contexts = 1500\n    from bandits.data.wasserstein_gans import WGANCovertype\n    wgan = WGANCovertype(context_dim)\n    wgan.train(epochs=4000, batch_size=32, sample_interval=50)\n    artificial_data_generator = lambda: gan_artificial_covertype(wgan, n_samples=50, n_actions=num_actions)\nelse:\n    raise Exception('name not recognized')\n\ndef dataset_proto(name=name):\n    if name==\"linear\":\n        dataset, _, opt_linear = sample_linear_data(num_contexts, context_dim,\n                                                    num_actions, sigma=noise_stds)\n    elif name==\"wheel\":\n        dataset, opt_linear = sample_wheel_bandit_data(num_contexts, delta,\n                                                      mean_v, std_v,\n                                                      mu_large, std_large)\n\n\n    elif name==\"mushroom\":\n        mush = Mushrooms(num_contexts=num_contexts)\n        dataset = mush.table\n        opt_rewards, opt_actions = mush.opts[:,0], mush.opts[:,1]\n        opt_linear = (opt_rewards, opt_actions)\n\n    elif name==\"covertype\":\n        cov = Covertype(num_contexts=num_contexts)\n        dataset = cov.table\n        opt_rewards, opt_actions = cov.opts[:,0], cov.opts[:,1]\n        opt_linear = (opt_rewards, opt_actions)\n\n    return dataset, opt_linear\n\nprint(dataset_proto()[0].shape)\n\n\n# Params for algo templates\nhparams = tf.contrib.training.HParams(num_actions=num_actions)\n\nhparams_linear = tf.contrib.training.HParams(num_actions=num_actions,\n                                             context_dim=context_dim,\n                                             a0=6,\n                                             b0=6,\n                                             lambda_prior=0.25,\n                                             initial_pulls=2)\n\nhparams_rms = tf.contrib.training.HParams(num_actions=num_actions,\n                                        context_dim=context_dim,\n                                        init_scale=0.3,\n                                        activation=tf.nn.relu,\n                                        layer_sizes=[50],\n                                        batch_size=512,\n                                        activate_decay=True,\n                                        initial_lr=0.1,\n                                        max_grad_norm=5.0,\n                                        show_training=False,\n                                        freq_summary=1000,\n                                        buffer_s=-1,\n                                        initial_pulls=2,\n                                        optimizer='RMS',\n                                        reset_lr=True,\n                                        lr_decay_rate=0.5,\n                                        training_freq=50,\n                                        training_epochs=50,\n                                        bootstrap=None)\n\nhparams_rms_bootstrapped = tf.contrib.training.HParams(num_actions=num_actions,\n                                        context_dim=context_dim,\n                                        init_scale=0.3,\n                                        activation=tf.nn.relu,\n                                        layer_sizes=[50],\n                                        batch_size=512,\n                                        activate_decay=True,\n                                        initial_lr=0.1,\n                                        max_grad_norm=5.0,\n                                        show_training=False,\n                                        freq_summary=1000,\n                                        buffer_s=-1,\n                                        initial_pulls=2,\n                                        optimizer='RMS',\n                                        reset_lr=True,\n                                        lr_decay_rate=0.5,\n                                        training_freq=50,\n                                        training_epochs=50,\n                                        bootstrap=artificial_data_generator)\n\nhparams_rmsb = tf.contrib.training.HParams(num_actions=num_actions,\n                                        context_dim=context_dim,\n                                        init_scale=0.3,\n                                        activation=tf.nn.relu,\n                                        layer_sizes=[50],\n                                        batch_size=512,\n                                        activate_decay=True,\n                                        initial_lr=0.1,\n                                        max_grad_norm=5.0,\n                                        show_training=False,\n                                        freq_summary=1000,\n                                        buffer_s=-1,\n                                        initial_pulls=2,\n                                        optimizer='RMS',\n                                        reset_lr=True,\n                                        lr_decay_rate=0.5,\n                                        training_freq=50,\n                                        training_epochs=50,\n                                        bootstrap=None,\n                                        q=3,p=0.95)\n\nhparams_rmsb_bootstrapped = tf.contrib.training.HParams(num_actions=num_actions,\n                                        context_dim=context_dim,\n                                        init_scale=0.3,\n                                        activation=tf.nn.relu,\n                                        layer_sizes=[50],\n                                        batch_size=512,\n                                        activate_decay=True,\n                                        initial_lr=0.1,\n                                        max_grad_norm=5.0,\n                                        show_training=False,\n                                        freq_summary=1000,\n                                        buffer_s=-1,\n                                        initial_pulls=2,\n                                        optimizer='RMS',\n                                        reset_lr=True,\n                                        lr_decay_rate=0.5,\n                                        training_freq=50,\n                                        training_epochs=50,\n                                        q=3,p=0.95,\n                                        bootstrap=artificial_data_generator)\n\nhparams_dropout = tf.contrib.training.HParams(num_actions=num_actions,\n                                        context_dim=context_dim,\n                                        init_scale=0.3,\n                                        use_dropout=True,\n                                        keep_prob=0.95,\n                                        activation=tf.nn.relu,\n                                        layer_sizes=[50],\n                                        batch_size=512,\n                                        activate_decay=True,\n                                        initial_lr=0.1,\n                                        max_grad_norm=5.0,\n                                        show_training=False,\n                                        freq_summary=1000,\n                                        buffer_s=-1,\n                                        initial_pulls=2,\n                                        optimizer='RMS',\n                                        reset_lr=True,\n                                        lr_decay_rate=0.5,\n                                        training_freq=50,\n                                        training_epochs=50,\n                                        bootstrap=None)\n\nhparams_dropout_bootstrapped = tf.contrib.training.HParams(num_actions=num_actions,\n                                        context_dim=context_dim,\n                                        init_scale=0.3,\n                                        use_dropout=True,\n                                        keep_prob=0.95,\n                                        activation=tf.nn.relu,\n                                        layer_sizes=[50],\n                                        batch_size=512,\n                                        activate_decay=True,\n                                        initial_lr=0.1,\n                                        max_grad_norm=5.0,\n                                        show_training=False,\n                                        freq_summary=1000,\n                                        buffer_s=-1,\n                                        initial_pulls=2,\n                                        optimizer='RMS',\n                                        reset_lr=True,\n                                        lr_decay_rate=0.5,\n                                        training_freq=50,\n                                        training_epochs=50,\n                                        bootstrap=artificial_data_generator)\n\nhparams_linucb = tf.contrib.training.HParams(num_actions=num_actions,\n                                        context_dim=context_dim,\n                                        alpha=1,\n                                        lam=0.1)\n\nhparams_neural_linucb = tf.contrib.training.HParams(num_actions=num_actions,\n                                        context_dim=context_dim,\n                                        init_scale=0.3,\n                                        activation=tf.nn.relu,\n                                        layer_sizes=[50],\n                                        batch_size=512,\n                                        activate_decay=True,\n                                        initial_lr=0.1,\n                                        max_grad_norm=5.0,\n                                        show_training=False,\n                                        freq_summary=1000,\n                                        buffer_s=-1,\n                                        initial_pulls=2,\n                                        optimizer='RMS',\n                                        reset_lr=True,\n                                        lr_decay_rate=0.5,\n                                        training_freq=50,\n                                        training_epochs=50,\n                                        training_freq_network=50,\n                                        bootstrap=None,\n                                        alpha=1,\n                                        lam=0.1)\nhparams_neural_linucb_bootstrapped = tf.contrib.training.HParams(num_actions=num_actions,\n                                        context_dim=context_dim,\n                                        init_scale=0.3,\n                                        activation=tf.nn.relu,\n                                        layer_sizes=[50],\n                                        batch_size=512,\n                                        activate_decay=True,\n                                        initial_lr=0.1,\n                                        max_grad_norm=5.0,\n                                        show_training=False,\n                                        freq_summary=1000,\n                                        buffer_s=-1,\n                                        initial_pulls=2,\n                                        optimizer='RMS',\n                                        reset_lr=True,\n                                        lr_decay_rate=0.5,\n                                        training_freq=50,\n                                        training_epochs=50,\n                                        training_freq_network=50,\n                                        bootstrap=artificial_data_generator,\n                                        alpha=1,\n                                        lam=0.1)\nhparams_neural_linthomson = tf.contrib.training.HParams(num_actions=num_actions,\n                                        context_dim=context_dim,\n                                        init_scale=0.3,\n                                        activation=tf.nn.relu,\n                                        layer_sizes=[50],\n                                        batch_size=512,\n                                        activate_decay=True,\n                                        initial_lr=0.1,\n                                        max_grad_norm=5.0,\n                                        show_training=False,\n                                        freq_summary=1000,\n                                        buffer_s=-1,\n                                        optimizer='RMS',\n                                        reset_lr=True,\n                                        lr_decay_rate=0.5,\n                                        training_freq=50,\n                                        training_epochs=50,\n                                        training_freq_network=50,\n                                        bootstrap=None,\n                                        a0=6,\n                                        b0=6,\n                                        lambda_prior=0.25,\n                                        initial_pulls=2)\n\nhparams_neural_linthomson_bootstrapped = tf.contrib.training.HParams(num_actions=num_actions,\n                                        context_dim=context_dim,\n                                        init_scale=0.3,\n                                        activation=tf.nn.relu,\n                                        layer_sizes=[50],\n                                        batch_size=512,\n                                        activate_decay=True,\n                                        initial_lr=0.1,\n                                        max_grad_norm=5.0,\n                                        show_training=False,\n                                        freq_summary=1000,\n                                        buffer_s=-1,\n                                        optimizer='RMS',\n                                        reset_lr=True,\n                                        lr_decay_rate=0.5,\n                                        training_freq=50,\n                                        training_epochs=50,\n                                        training_freq_network=50,\n                                        bootstrap=artificial_data_generator,\n                                        a0=6,\n                                        b0=6,\n                                        lambda_prior=0.25,\n                                        initial_pulls=2)\n\nhparams_pnoise = tf.contrib.training.HParams(num_actions=num_actions,\n                                       context_dim=context_dim,\n                                       init_scale=0.3,\n                                       activation=tf.nn.relu,\n                                       layer_sizes=[50],\n                                       batch_size=512,\n                                       activate_decay=True,\n                                       initial_lr=0.1,\n                                       max_grad_norm=5.0,\n                                       show_training=False,\n                                       freq_summary=1000,\n                                       buffer_s=-1,\n                                       initial_pulls=2,\n                                       optimizer='RMS',\n                                       reset_lr=True,\n                                       lr_decay_rate=0.5,\n                                       training_freq=50,\n                                       training_epochs=100,\n                                       noise_std=0.05,\n                                       eps=0.1,\n                                       d_samples=300\n                                      )\n\nhparams_pnoise_bootstrapped = tf.contrib.training.HParams(num_actions=num_actions,\n                                       context_dim=context_dim,\n                                       init_scale=0.3,\n                                       activation=tf.nn.relu,\n                                       layer_sizes=[50],\n                                       batch_size=512,\n                                       activate_decay=True,\n                                       initial_lr=0.1,\n                                       max_grad_norm=5.0,\n                                       show_training=False,\n                                       freq_summary=1000,\n                                       buffer_s=-1,\n                                       initial_pulls=2,\n                                       optimizer='RMS',\n                                       reset_lr=True,\n                                       lr_decay_rate=0.5,\n                                       training_freq=50,\n                                       training_epochs=100,\n                                       noise_std=0.05,\n                                       eps=0.1,\n                                       d_samples=300,\n                                       bootstrap=artificial_data_generator\n                                      )\n\nhparams_lineps = tf.contrib.training.HParams(num_actions=num_actions,\n                                        context_dim=context_dim,\n                                        lam=0.1,\n                                        eps=0.05)\n\nrandom_proto = lambda : UniformSampling('Uniform Sampling', hparams)\nneural_greedy_proto = lambda : PosteriorBNNSampling('NeuralGreedy', hparams_rms, 'RMSProp')\nneural_greedy_proto_bootstrapped = lambda : PosteriorBNNSampling('NeuralGreedy_artificial_data', hparams_rms_bootstrapped, 'RMSProp')\n\nbootstrap_proto = lambda : BootstrappedBNNSampling('BootRMS', hparams_rmsb)\nbootstrap_proto_bootstrapped = lambda : BootstrappedBNNSampling('BootRMS_artificial_data', hparams_rmsb_bootstrapped)\n\nnoise_proto = lambda : ParameterNoiseSampling('ParamNoise', hparams_pnoise)\nnoise_proto_bootstrapped = lambda : ParameterNoiseSampling('ParamNoise_artificial_data', hparams_pnoise_bootstrapped)\n\ndropout_proto = lambda : PosteriorBNNSampling('Dropout', hparams_dropout, 'RMSProp')\ndropout_proto_bootstrapped = lambda : PosteriorBNNSampling('Dropout_artificial_data', hparams_dropout_bootstrapped, 'RMSProp')\n\nlinThompson_proto = lambda : LinearFullPosteriorSampling('linThompson', hparams_linear)\nlinUCB_proto = lambda : LinUCB('linUCB', hparams_linucb)\nlinEps_proto = lambda : LinEpsilon('LinEpsilon', hparams_lineps)\n\nneuralLinUCB_proto = lambda : NeuralLinUCB('NeuralLinUCB', hparams_neural_linucb, 'RMSProp')\nneuralLinThomson_proto = lambda : NeuralLinearPosteriorSampling('NeuralLinThomson', hparams_neural_linthomson, 'RMSProp')\nneuralLinUCB_proto_bootstrapped = lambda : NeuralLinUCB('NeuralLinUCB_artificial_data', hparams_neural_linucb_bootstrapped, 'RMSProp')\nneuralLinThomson_proto_bootstrapped = lambda : NeuralLinearPosteriorSampling('NeuralLinThomson_artificial_data', hparams_neural_linthomson_bootstrapped, 'RMSProp')\n\nalgo_protos = [linUCB_proto,\n    neuralLinUCB_proto, neuralLinUCB_proto_bootstrapped,\n    dropout_proto, dropout_proto_bootstrapped,\n    bootstrap_proto, bootstrap_proto_bootstrapped,\n    noise_proto, noise_proto_bootstrapped,\n    neuralLinThomson_proto, neuralLinThomson_proto_bootstrapped,\n    linEps_proto,\n    linThompson_proto,\n    neural_greedy_proto, neural_greedy_proto_bootstrapped,\n    random_proto]\n\n# Run experiments several times save and plot results\nbenchmarker = Benchmarker(algo_protos, dataset_proto, num_actions, context_dim, nb_contexts=num_contexts, test_name=test_name)\n\nbenchmarker.run_experiments(50)\nbenchmarker.save_results('./results/')\nbenchmarker.save_final_res_to_tex('./results/')\nbenchmarker.display_results(save_path='./results/')\n", "meta": {"hexsha": "af52e2671bddba33c4214f466ab0968c4ebe0e66", "size": 24219, "ext": "py", "lang": "Python", "max_stars_repo_path": "research/deep_contextual_bandits/run_full_analysis.py", "max_stars_repo_name": "pedevineau/models", "max_stars_repo_head_hexsha": "ca93c26d3520240ceb8601497cffb676dc06f8ca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-22T09:41:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-22T09:41:03.000Z", "max_issues_repo_path": "research/deep_contextual_bandits/run_full_analysis.py", "max_issues_repo_name": "pedevineau/models", "max_issues_repo_head_hexsha": "ca93c26d3520240ceb8601497cffb676dc06f8ca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "research/deep_contextual_bandits/run_full_analysis.py", "max_forks_repo_name": "pedevineau/models", "max_forks_repo_head_hexsha": "ca93c26d3520240ceb8601497cffb676dc06f8ca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-13T09:41:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-13T09:41:00.000Z", "avg_line_length": 50.45625, "max_line_length": 163, "alphanum_fraction": 0.4590197779, "include": true, "reason": "import numpy", "num_tokens": 3971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.195892271593972}}
{"text": "# -*- coding: utf-8 -*-\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n#\n# Copyright (C) 2017-2018 GEM Foundation\n#\n# OpenQuake is free software: you can redistribute it and/or modify it\n# under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# OpenQuake is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"\nModule exports :class:`MunsonThurber1997`\n               :class:`MunsonThurber1997Vector`.\n\"\"\"\nimport numpy as np\n\nfrom openquake.hazardlib.gsim.base import GMPE\nfrom openquake.hazardlib import const\nfrom openquake.hazardlib.imt import PGA\n\n\nclass MunsonThurber1997(GMPE):\n    \"\"\"\n    Implements GMPE developed by Clifford G. Munson and Clifford H. Thurber\n    and published as \"Analysis of the Attenuation of Strong Ground Motion\n    on the Island of Hawaii\" (1997, Bulletin of the Seismological Society\n    of America, Vol. 87, No. 4, pp. 954-960).\n    \"\"\"\n\n    #: Supported tectonic region type is volcanic,\n    #: see paragraph 'Introduction', page 99.\n    DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.VOLCANIC\n\n    #: Supported intensity measure types is spectral acceleration,\n    #: see table 3, pag. 110\n    DEFINED_FOR_INTENSITY_MEASURE_TYPES = set([PGA])\n\n    #: Supported intensity measure component is maximum horizontal\n    #: :attr:`~openquake.hazardlib.const.IMC.VECTORIAL`,\n    DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = const.IMC.HORIZONTAL\n\n    #: Supported standard deviation type is total\n    DEFINED_FOR_STANDARD_DEVIATION_TYPES = set([\n        const.StdDev.TOTAL\n    ])\n\n    #: Required site parameters is Vs30.\n    #: See paragraph 'Predictor Variables', pag 103\n    REQUIRES_SITES_PARAMETERS = set(('vs30', ))\n\n    #: Required rupture parameter is magnitude\n    REQUIRES_RUPTURE_PARAMETERS = set(('mag', ))\n\n    #: Required distance measure is hypocentral distance\n    #: see page 18 in Atkinson and Boore's manuscript\n    REQUIRES_DISTANCES = set(('rjb', ))\n\n    def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):\n        \"\"\"\n        See :meth:`superclass method\n        <.base.GroundShakingIntensityModel.get_mean_and_stddevs>`\n        for spec of input and result values.\n        \"\"\"\n\n        # Distance term\n        R = np.sqrt(dists.rjb ** 2 + 11.29 ** 2)\n\n        # Magnitude term\n        M = rup.mag - 6\n\n        # Site term only distinguishes between lava and ash;\n        # since ash sites have Vs30 in the range 60-200m/s,\n        # we use this upper value as class separator\n        S = np.zeros(R.shape)\n        S[sites.vs30 <= 200] = 1\n\n        # Mean ground motion (log10)\n        mean = (0.518 + 0.387*M - np.log10(R) - 0.00256*R + 0.335*S)\n\n        # Converting to natural log\n        mean /= np.log10(np.e)\n\n        # Check for standard deviation type\n        assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES\n                   for stddev_type in stddev_types)\n\n        # Constant (total) standard deviation\n        stddevs = [0.237/np.log10(np.e) + np.zeros(R.shape)]\n\n        return mean, stddevs\n\n\nclass MunsonThurber1997Vector(MunsonThurber1997):\n    \"\"\"\n    Modification of the original base class to correct mean ground motion\n    to geometric mean of horizontal components (Beyer and Bommer, 2006)\n    \"\"\"\n\n    #: Supported intensity measure component is geometric mean of horizontal\n    #: :attr:`~openquake.hazardlib.const.IMC.VECTORIAL`,\n    DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = const.IMC.VECTORIAL\n\n    def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):\n        mean, stddevs = super().get_mean_and_stddevs(sites, rup, dists,\n                                                     imt, stddev_types)\n\n        # Conversion to geometric mean of horizontal components\n        # using the coefficient in Beyer and Bommer, 2006\n        mean += np.log(1.1)\n\n        return mean, stddevs\n", "meta": {"hexsha": "a82a24861f96476bdf02ea293986bf10e85ab361", "size": 4255, "ext": "py", "lang": "Python", "max_stars_repo_path": "openquake/hazardlib/gsim/munson_thurber_1997.py", "max_stars_repo_name": "gfzriesgos/shakyground-lfs", "max_stars_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-01T00:28:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-01T00:28:24.000Z", "max_issues_repo_path": "openquake/hazardlib/gsim/munson_thurber_1997.py", "max_issues_repo_name": "gfzriesgos/shakyground-lfs", "max_issues_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-08-31T14:14:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-11T12:53:13.000Z", "max_forks_repo_path": "openquake/hazardlib/gsim/munson_thurber_1997.py", "max_forks_repo_name": "gfzriesgos/shakyground-lfs", "max_forks_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-08-31T14:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-17T10:06:02.000Z", "avg_line_length": 35.4583333333, "max_line_length": 76, "alphanum_fraction": 0.683666275, "include": true, "reason": "import numpy", "num_tokens": 1082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.19589226931909068}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nfrom copy import deepcopy\nimport numpy as np\nimport astropy.io.fits as fits\nimport astropy.units as u\nfrom gammapy.irf import EDispKernel\nfrom gammapy.maps import Map, MapCoord, WcsGeom\nfrom gammapy.utils.random import InverseCDFSampler, get_random_state\n\n__all__ = [\"make_edisp_map\", \"EDispMap\"]\n\n\ndef make_edisp_map(edisp, pointing, geom, exposure_map=None):\n    \"\"\"Make a edisp map for a single observation\n\n    Expected axes : migra and true energy in this specific order\n    The name of the migra MapAxis is expected to be 'migra'\n\n    Parameters\n    ----------\n    edisp : `~gammapy.irf.EnergyDispersion2D`\n        the 2D Energy Dispersion IRF\n    pointing : `~astropy.coordinates.SkyCoord`\n        the pointing direction\n    geom : `~gammapy.maps.Geom`\n        the map geom to be used. It provides the target geometry.\n        rad and true energy axes should be given in this specific order.\n    exposure_map : `~gammapy.maps.Map`, optional\n        the associated exposure map.\n        default is None\n\n    Returns\n    -------\n    edispmap : `~gammapy.cube.EDispMap`\n        the resulting EDisp map\n    \"\"\"\n    energy_axis = geom.get_axis_by_name(\"energy\")\n    energy = energy_axis.center\n\n    migra_axis = geom.get_axis_by_name(\"migra\")\n    migra = migra_axis.center\n\n    # Compute separations with pointing position\n    offset = geom.separation(pointing)\n\n    # Compute EDisp values\n    edisp_values = edisp.data.evaluate(\n        offset=offset,\n        e_true=energy[:, np.newaxis, np.newaxis, np.newaxis],\n        migra=migra[:, np.newaxis, np.newaxis],\n    )\n\n    # Create Map and fill relevant entries\n    data = edisp_values.to_value(\"\")\n    edispmap = Map.from_geom(geom, data=data, unit=\"\")\n    return EDispMap(edispmap, exposure_map)\n\n\nclass EDispMap:\n    \"\"\"Energy dispersion map.\n\n    Parameters\n    ----------\n    edisp_map : `~gammapy.maps.Map`\n        the input Energy Dispersion Map. Should be a Map with 2 non spatial axes.\n        migra and true energy axes should be given in this specific order.\n    exposure_map : `~gammapy.maps.Map`, optional\n        Associated exposure map. Needs to have a consistent map geometry.\n\n    Examples\n    --------\n    ::\n\n        import numpy as np\n        from astropy import units as u\n        from astropy.coordinates import SkyCoord\n        from gammapy.maps import WcsGeom, MapAxis\n        from gammapy.irf import EnergyDispersion2D, EffectiveAreaTable2D\n        from gammapy.cube import make_edisp_map, make_map_exposure_true_energy\n\n        # Define energy dispersion map geometry\n        energy_axis = MapAxis.from_edges(np.logspace(-1, 1, 4), unit=\"TeV\", name=\"energy\")\n        migra_axis = MapAxis.from_edges(np.linspace(0, 3, 100), name=\"migra\")\n        pointing = SkyCoord(0, 0, unit=\"deg\")\n        max_offset = 4 * u.deg\n        geom = WcsGeom.create(\n            binsz=0.25 * u.deg,\n            width=10 * u.deg,\n            skydir=pointing,\n            axes=[migra_axis, energy_axis],\n        )\n\n        # Extract EnergyDispersion2D from CTA 1DC IRF\n        filename = \"$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits\"\n        edisp2D = EnergyDispersion2D.read(filename, hdu=\"ENERGY DISPERSION\")\n        aeff2d = EffectiveAreaTable2D.read(filename, hdu=\"EFFECTIVE AREA\")\n\n        # Create the exposure map\n        exposure_geom = geom.to_image().to_cube([energy_axis])\n        exposure_map = make_map_exposure_true_energy(pointing, \"1 h\", aeff2d, exposure_geom)\n\n        # create the EDispMap for the specified pointing\n        edisp_map = make_edisp_map(edisp2D, pointing, geom, max_offset, exposure_map)\n\n        # Get an Energy Dispersion (1D) at any position in the image\n        pos = SkyCoord(2.0, 2.5, unit=\"deg\")\n        e_reco = np.logspace(-1.0, 1.0, 10) * u.TeV\n        edisp = edisp_map.get_edisp_kernel(pos=pos, e_reco=e_reco)\n\n        # Write map to disk\n        edisp_map.write(\"edisp_map.fits\")\n    \"\"\"\n\n    def __init__(self, edisp_map, exposure_map):\n        if edisp_map.geom.axes[1].name.upper() != \"ENERGY\":\n            raise ValueError(\"Incorrect energy axis position in input Map\")\n\n        if edisp_map.geom.axes[0].name.upper() != \"MIGRA\":\n            raise ValueError(\"Incorrect migra axis position in input Map\")\n\n        self.edisp_map = edisp_map\n        self.exposure_map = exposure_map\n\n    @classmethod\n    def from_hdulist(\n        cls,\n        hdulist,\n        edisp_hdu=\"EDISPMAP\",\n        edisp_hdubands=\"BANDSEDISP\",\n        exposure_hdu=\"EXPMAP\",\n        exposure_hdubands=\"BANDSEXP\",\n    ):\n        \"\"\"Convert to `~astropy.io.fits.HDUList`.\n\n        Parameters\n        ----------\n        edisp_hdu : str\n            Name or index of the HDU with the edisp_map data.\n        edisp_hdubands : str\n            Name or index of the HDU with the edisp_map BANDS table.\n        exposure_hdu : str\n            Name or index of the HDU with the exposure_map data.\n        exposure_hdubands : str\n            Name or index of the HDU with the exposure_map BANDS table.\n        \"\"\"\n        edisp_map = Map.from_hdulist(hdulist, edisp_hdu, edisp_hdubands, \"auto\")\n        if exposure_hdu in hdulist:\n            exposure_map = Map.from_hdulist(\n                hdulist, exposure_hdu, exposure_hdubands, \"auto\"\n            )\n        else:\n            exposure_map = None\n\n        return cls(edisp_map, exposure_map)\n\n    @classmethod\n    def read(cls, filename, **kwargs):\n        \"\"\"Read an edisp_map from file and create an EDispMap object\"\"\"\n        with fits.open(filename, memmap=False) as hdulist:\n            return cls.from_hdulist(hdulist, **kwargs)\n\n    def to_hdulist(\n        self,\n        edisp_hdu=\"EDISPMAP\",\n        edisp_hdubands=\"BANDSEDISP\",\n        exposure_hdu=\"EXPMAP\",\n        exposure_hdubands=\"BANDSEXP\",\n    ):\n        \"\"\"Convert to `~astropy.io.fits.HDUList`.\n\n        Parameters\n        ----------\n        edisp_hdu : str\n            Name or index of the HDU with the edisp_map data.\n        edisp_hdubands : str\n            Name or index of the HDU with the edisp_map BANDS table.\n        exposure_hdu : str\n            Name or index of the HDU with the exposure_map data.\n        exposure_hdubands : str\n            Name or index of the HDU with the exposure_map BANDS table.\n\n        Returns\n        -------\n        hdu_list : `~astropy.io.fits.HDUList`\n        \"\"\"\n        hdulist = self.edisp_map.to_hdulist(hdu=edisp_hdu, hdu_bands=edisp_hdubands)\n        if self.exposure_map is not None:\n            new_hdulist = self.exposure_map.to_hdulist(\n                hdu=exposure_hdu, hdu_bands=exposure_hdubands\n            )\n            hdulist.extend(new_hdulist[1:])\n        return hdulist\n\n    def write(self, filename, overwrite=False, **kwargs):\n        \"\"\"Write to fits\"\"\"\n        hdulist = self.to_hdulist(**kwargs)\n        hdulist.writeto(filename, overwrite=overwrite)\n\n    def get_edisp_kernel(self, position, e_reco, migra_step=5e-3):\n        \"\"\"Get energy dispersion at a given position.\n\n        Parameters\n        ----------\n        position : `~astropy.coordinates.SkyCoord`\n            the target position. Should be a single coordinates\n        e_reco : `~astropy.units.Quantity`\n            Reconstructed energy axis binning\n        migra_step : float\n            Integration step in migration\n\n        Returns\n        -------\n        edisp : `~gammapy.irf.EnergyDispersion`\n            the energy dispersion (i.e. rmf object)\n        \"\"\"\n        # TODO: reduce code duplication with EnergyDispersion2D.get_response\n        if position.size != 1:\n            raise ValueError(\n                \"EnergyDispersion can be extracted at one single position only.\"\n            )\n\n        # axes ordering fixed. Could be changed.\n        pix_ener = np.arange(self.edisp_map.geom.axes[1].nbin)\n\n        # Define a vector of migration with mig_step step\n        mrec_min = self.edisp_map.geom.axes[0].edges[0]\n        mrec_max = self.edisp_map.geom.axes[0].edges[-1]\n        mig_array = np.arange(mrec_min, mrec_max, migra_step)\n        pix_migra = (mig_array - mrec_min) / mrec_max * self.edisp_map.geom.axes[0].nbin\n\n        # Convert position to pixels\n        pix_lon, pix_lat = self.edisp_map.geom.to_image().coord_to_pix(position)\n\n        # Build the pixels tuple\n        pix = np.meshgrid(pix_lon, pix_lat, pix_migra, pix_ener)\n        # Interpolate in the EDisp map. Squeeze to remove dimensions of length 1\n        edisp_values = self.edisp_map.interp_by_pix(pix) * u.Unit(self.edisp_map.unit)\n        edisp_values = np.squeeze(edisp_values, axis=(0, 1))\n\n        e_trues = self.edisp_map.geom.axes[1].center\n        data = []\n\n        for i, e_true in enumerate(e_trues):\n            # We now perform integration over migra\n            # The code is adapted from `~gammapy.EnergyDispersion2D.get_response`\n\n            # migration value of e_reco bounds\n            migra_e_reco = e_reco / e_true\n\n            # Compute normalized cumulative sum to prepare integration\n            tmp = np.nan_to_num(\n                np.cumsum(edisp_values[:, i]) / np.sum(edisp_values[:, i])\n            )\n\n            # Determine positions (bin indices) of e_reco bounds in migration array\n            pos_mig = np.digitize(migra_e_reco, mig_array) - 1\n            # We ensure that no negative values are found\n            pos_mig = np.maximum(pos_mig, 0)\n\n            # We compute the difference between 2 successive bounds in e_reco\n            # to get integral over reco energy bin\n            integral = np.diff(tmp[pos_mig])\n\n            data.append(integral)\n\n        data = np.asarray(data)\n        # EnergyDispersion uses edges of true energy bins\n        e_true_edges = self.edisp_map.geom.axes[1].edges\n\n        e_lo, e_hi = e_true_edges[:-1], e_true_edges[1:]\n        ereco_lo, ereco_hi = (e_reco[:-1], e_reco[1:])\n\n        return EDispKernel(\n            e_true_lo=e_lo,\n            e_true_hi=e_hi,\n            e_reco_lo=ereco_lo,\n            e_reco_hi=ereco_hi,\n            data=data,\n        )\n\n    def stack(self, other, weights=None):\n        \"\"\"Stack EDispMap with another one in place.\n\n        Parameters\n        ----------\n        other : `~gammapy.cube.EDispMap`\n            Energy dispersion map to be stacked with this one.\n\n        \"\"\"\n        if self.exposure_map is None or other.exposure_map is None:\n            raise ValueError(\"Missing exposure map for PSFMap.stack\")\n\n        cutout_info = other.edisp_map.geom.cutout_info\n\n        if cutout_info is not None:\n            slices = cutout_info[\"parent-slices\"]\n            parent_slices = Ellipsis, slices[0], slices[1]\n        else:\n            parent_slices = None\n\n        self.edisp_map.data[parent_slices] *= self.exposure_map.data[parent_slices]\n        self.edisp_map.stack(other.edisp_map * other.exposure_map.data, weights=weights)\n\n        # stack exposure map\n        self.exposure_map.stack(other.exposure_map, weights=weights)\n\n        with np.errstate(invalid=\"ignore\"):\n            self.edisp_map.data[parent_slices] /= self.exposure_map.data[parent_slices]\n            self.edisp_map.data = np.nan_to_num(self.edisp_map.data)\n\n    def copy(self):\n        \"\"\"Copy EDispMap\"\"\"\n        return deepcopy(self)\n\n    @classmethod\n    def from_geom(cls, geom):\n        \"\"\"Create edisp map from geom.\n\n        By default a diagonal edisp matrix is created.\n\n        Parameters\n        ----------\n        geom : `Geom`\n            Edisp map geometry.\n\n        Returns\n        -------\n        edisp_map : `EDispMap`\n            Energy dispersion map.\n        \"\"\"\n        geom_exposure_edisp = geom.squash(axis=\"migra\")\n        exposure_edisp = Map.from_geom(geom_exposure_edisp, unit=\"m2 s\")\n\n        migra_axis = geom.get_axis_by_name(\"migra\")\n        edisp_map = Map.from_geom(geom, unit=\"\")\n        loc = migra_axis.edges.searchsorted(1.0)\n        edisp_map.data[:, loc, :, :] = 1.0\n        return cls(edisp_map, exposure_edisp)\n\n    def sample_coord(self, map_coord, random_state=0):\n        \"\"\"Apply the energy dispersion corrections on the coordinates of a set of simulated events.\n\n        Parameters\n        ----------\n        map_coord : `~gammapy.maps.MapCoord` object.\n            Sequence of coordinates and energies of sampled events.\n        random_state : {int, 'random-seed', 'global-rng', `~numpy.random.RandomState`}\n            Defines random number generator initialisation.\n            Passed to `~gammapy.utils.random.get_random_state`.\n\n        Returns\n        -------\n        `~gammapy.maps.MapCoord`.\n            Sequence of Edisp-corrected coordinates of the input map_coord map.\n        \"\"\"\n        random_state = get_random_state(random_state)\n        migra_axis = self.edisp_map.geom.get_axis_by_name(\"migra\")\n\n        coord = {\n            \"skycoord\": map_coord.skycoord.reshape(-1, 1),\n            \"energy\": map_coord[\"energy\"].reshape(-1, 1),\n            \"migra\": migra_axis.center,\n        }\n\n        pdf_edisp = self.edisp_map.interp_by_coord(coord)\n\n        sample_edisp = InverseCDFSampler(pdf_edisp, axis=1, random_state=random_state)\n        pix_edisp = sample_edisp.sample_axis()\n        migra = migra_axis.pix_to_coord(pix_edisp)\n\n        energy_reco = map_coord[\"energy\"] * migra\n\n        return MapCoord.create({\"skycoord\": map_coord.skycoord, \"energy\": energy_reco})\n\n    @classmethod\n    def from_diagonal_response(cls, energy_axis_true, migra_axis=None):\n        \"\"\"Create an allsky EDisp map with diagonal response.\n\n        Parameters\n        ----------\n        energy_axis_true : `MapAxis`\n            True energy axis\n        migra_axis : `MapAxis`\n            Migra axis\n\n        Returns\n        -------\n        edisp_map : `EDispMap`\n            Energy dispersion map.\n        \"\"\"\n        from .fit import MIGRA_AXIS_DEFAULT\n\n        migra_axis = migra_axis or MIGRA_AXIS_DEFAULT\n\n        geom = WcsGeom.create(\n            npix=(2, 1), proj=\"CAR\", binsz=180, axes=[migra_axis, energy_axis_true]\n        )\n\n        return cls.from_geom(geom)\n\n    def cutout(self, position, width, mode=\"trim\"):\n        \"\"\"Cutout edisp map.\n\n        Parameters\n        ----------\n        position : `~astropy.coordinates.SkyCoord`\n            Center position of the cutout region.\n        width : tuple of `~astropy.coordinates.Angle`\n            Angular sizes of the region in (lon, lat) in that specific order.\n            If only one value is passed, a square region is extracted.\n        mode : {'trim', 'partial', 'strict'}\n            Mode option for Cutout2D, for details see `~astropy.nddata.utils.Cutout2D`.\n\n        Returns\n        -------\n        cutout : `EdispMap`\n            Cutout edisp map.\n        \"\"\"\n        edisp_map = self.edisp_map.cutout(position, width, mode)\n        exposure_map = self.exposure_map.cutout(position, width, mode)\n        return self.__class__(edisp_map=edisp_map, exposure_map=exposure_map)\n", "meta": {"hexsha": "efcc82518f4ebcafafb398943cdea78c01ab3c9b", "size": 14880, "ext": "py", "lang": "Python", "max_stars_repo_path": "gammapy/cube/edisp_map.py", "max_stars_repo_name": "QRemy/gammapy", "max_stars_repo_head_hexsha": "fe799e8a8e792d216fdb11fb7abcb64d58f273dd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gammapy/cube/edisp_map.py", "max_issues_repo_name": "QRemy/gammapy", "max_issues_repo_head_hexsha": "fe799e8a8e792d216fdb11fb7abcb64d58f273dd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gammapy/cube/edisp_map.py", "max_forks_repo_name": "QRemy/gammapy", "max_forks_repo_head_hexsha": "fe799e8a8e792d216fdb11fb7abcb64d58f273dd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2606635071, "max_line_length": 99, "alphanum_fraction": 0.6235887097, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 3694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.19589226931909068}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2019 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#\n\n'''Non-relativistic UKS analytical nuclear gradients'''\n\nimport time\nimport numpy\nimport scipy.linalg\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf.grad import rhf as rhf_grad\nfrom pyscf.grad import rks as rks_grad\nfrom pyscf.grad import uhf as uhf_grad\nfrom pyscf.dft import numint, gen_grid\nfrom pyscf import __config__\n\n\ndef get_veff(ks_grad, mol=None, dm=None):\n    '''Coulomb + XC functional\n    '''\n    if mol is None: mol = ks_grad.mol\n    if dm is None: dm = ks_grad.base.make_rdm1()\n    t0 = (time.clock(), time.time())\n\n    mf = ks_grad.base\n    ni = mf._numint\n    if ks_grad.grids is not None:\n        grids = ks_grad.grids\n    else:\n        grids = mf.grids\n    if grids.coords is None:\n        grids.build(with_non0tab=True)\n\n    if mf.nlc != '':\n        raise NotImplementedError\n    #enabling range-separated hybrids\n    omega, alpha, hyb = ni.rsh_and_hybrid_coeff(mf.xc, spin=mol.spin)\n\n    mem_now = lib.current_memory()[0]\n    max_memory = max(2000, ks_grad.max_memory*.9-mem_now)\n    if ks_grad.grid_response:\n        exc, vxc = get_vxc_full_response(ni, mol, grids, mf.xc, dm,\n                                         max_memory=max_memory,\n                                         verbose=ks_grad.verbose)\n        logger.debug1(ks_grad, 'sum(grids response) %s', exc.sum(axis=0))\n    else:\n        exc, vxc = get_vxc(ni, mol, grids, mf.xc, dm,\n                           max_memory=max_memory, verbose=ks_grad.verbose)\n    t0 = logger.timer(ks_grad, 'vxc', *t0)\n\n    if abs(hyb) < 1e-10:\n        vj = ks_grad.get_j(mol, dm)\n        vxc += vj[0] + vj[1]\n    else:\n        vj, vk = ks_grad.get_jk(mol, dm)\n        vk *= hyb\n        if abs(omega) > 1e-10:  # For range separated Coulomb operator\n            with mol.with_range_coulomb(omega):\n                vk += ks_grad.get_k(mol, dm) * (alpha - hyb)\n        vxc += vj[0] + vj[1] - vk\n\n    return lib.tag_array(vxc, exc1_grid=exc)\n\n\ndef get_vxc(ni, mol, grids, xc_code, dms, relativity=0, hermi=1,\n            max_memory=2000, verbose=None):\n    xctype = ni._xc_type(xc_code)\n    make_rho, nset, nao = ni._gen_rho_evaluator(mol, dms, hermi)\n    ao_loc = mol.ao_loc_nr()\n\n    vmat = numpy.zeros((2,3,nao,nao))\n    if xctype == 'LDA':\n        ao_deriv = 1\n        for ao, mask, weight, coords \\\n                in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):\n            rho_a = make_rho(0, ao[0], mask, 'LDA')\n            rho_b = make_rho(1, ao[0], mask, 'LDA')\n            vxc = ni.eval_xc(xc_code, (rho_a,rho_b), 1, relativity, 1, verbose)[1]\n            vrho = vxc[0]\n            aow = numpy.einsum('pi,p->pi', ao[0], weight*vrho[:,0])\n            rks_grad._d1_dot_(vmat[0], mol, ao[1:4], aow, mask, ao_loc, True)\n            aow = numpy.einsum('pi,p->pi', ao[0], weight*vrho[:,1])\n            rks_grad._d1_dot_(vmat[1], mol, ao[1:4], aow, mask, ao_loc, True)\n            rho = vxc = vrho = aow = None\n\n    elif xctype == 'GGA':\n        ao_deriv = 2\n        for ao, mask, weight, coords \\\n                in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):\n            rho_a = make_rho(0, ao[:4], mask, 'GGA')\n            rho_b = make_rho(1, ao[:4], mask, 'GGA')\n            vxc = ni.eval_xc(xc_code, (rho_a,rho_b), 1, relativity, 1, verbose)[1]\n            wva, wvb = numint._uks_gga_wv0((rho_a,rho_b), vxc, weight)\n\n            rks_grad._gga_grad_sum_(vmat[0], mol, ao, wva, mask, ao_loc)\n            rks_grad._gga_grad_sum_(vmat[1], mol, ao, wvb, mask, ao_loc)\n            rho_a = rho_b = vxc = wva = wvb = None\n\n    elif xctype == 'NLC':\n        raise NotImplementedError('NLC')\n    else:\n        raise NotImplementedError('meta-GGA')\n\n    exc = numpy.zeros((mol.natm,3))\n    # - sign because nabla_X = -nabla_x\n    return exc, -vmat\n\n\ndef get_vxc_full_response(ni, mol, grids, xc_code, dms, relativity=0, hermi=1,\n                          max_memory=2000, verbose=None):\n    '''Full response including the response of the grids'''\n    xctype = ni._xc_type(xc_code)\n    make_rho, nset, nao = ni._gen_rho_evaluator(mol, dms, hermi)\n    ao_loc = mol.ao_loc_nr()\n    aoslices = mol.aoslice_by_atom()\n\n    excsum = 0\n    vmat = numpy.zeros((2,3,nao,nao))\n    if xctype == 'LDA':\n        ao_deriv = 1\n        for atm_id, (coords, weight, weight1) \\\n                in enumerate(rks_grad.grids_response_cc(grids)):\n            ngrids = weight.size\n            sh0, sh1 = aoslices[atm_id][:2]\n            mask = gen_grid.make_mask(mol, coords)\n            ao = ni.eval_ao(mol, coords, deriv=ao_deriv, non0tab=mask)\n            rho_a = make_rho(0, ao[0], mask, 'LDA')\n            rho_b = make_rho(1, ao[0], mask, 'LDA')\n            exc, vxc = ni.eval_xc(xc_code, (rho_a,rho_b), 1, relativity, 1, verbose)[:2]\n            vrho = vxc[0]\n\n            vtmp = numpy.zeros((3,nao,nao))\n            aow = numpy.einsum('pi,p->pi', ao[0], weight*vrho[:,0])\n            rks_grad._d1_dot_(vtmp, mol, ao[1:4], aow, mask, ao_loc, True)\n            vmat[0] += vtmp\n            excsum += numpy.einsum('r,r,nxr->nx', exc, rho_a+rho_b, weight1)\n            excsum[atm_id] += numpy.einsum('xij,ji->x', vtmp, dms[0]) * 2\n\n            vtmp = numpy.zeros((3,nao,nao))\n            aow = numpy.einsum('pi,p->pi', ao[0], weight*vrho[:,1])\n            rks_grad._d1_dot_(vtmp, mol, ao[1:4], aow, mask, ao_loc, True)\n            vmat[1] += vtmp\n            excsum[atm_id] += numpy.einsum('xij,ji->x', vtmp, dms[1]) * 2\n            rho = vxc = vrho = aow = None\n\n    elif xctype == 'GGA':\n        ao_deriv = 2\n        for atm_id, (coords, weight, weight1) \\\n                in enumerate(rks_grad.grids_response_cc(grids)):\n            ngrids = weight.size\n            sh0, sh1 = aoslices[atm_id][:2]\n            mask = gen_grid.make_mask(mol, coords)\n            ao = ni.eval_ao(mol, coords, deriv=ao_deriv, non0tab=mask)\n            rho_a = make_rho(0, ao[:4], mask, 'GGA')\n            rho_b = make_rho(1, ao[:4], mask, 'GGA')\n            exc, vxc = ni.eval_xc(xc_code, (rho_a,rho_b), 1, relativity, 1, verbose)[:2]\n            wva, wvb = numint._uks_gga_wv0((rho_a,rho_b), vxc, weight)\n\n            vtmp = numpy.zeros((3,nao,nao))\n            rks_grad._gga_grad_sum_(vtmp, mol, ao, wva, mask, ao_loc)\n            vmat[0] += vtmp\n            excsum += numpy.einsum('r,r,nxr->nx', exc, rho_a[0]+rho_b[0], weight1)\n            excsum[atm_id] += numpy.einsum('xij,ji->x', vtmp, dms[0]) * 2\n\n            vtmp = numpy.zeros((3,nao,nao))\n            rks_grad._gga_grad_sum_(vtmp, mol, ao, wvb, mask, ao_loc)\n            vmat[1] += vtmp\n            excsum[atm_id] += numpy.einsum('xij,ji->x', vtmp, dms[1]) * 2\n            rho_a = rho_b = vxc = wva = wvb = None\n\n    elif xctype == 'NLC':\n        raise NotImplementedError('NLC')\n    else:\n        raise NotImplementedError('meta-GGA')\n\n    # - sign because nabla_X = -nabla_x\n    return excsum, -vmat\n\n\nclass Gradients(uhf_grad.Gradients):\n\n    grid_response = getattr(__config__, 'grad_uks_Gradients_grid_response', False)\n\n    def __init__(self, mf):\n        uhf_grad.Gradients.__init__(self, mf)\n        self.grids = None\n        self.grid_response = False\n        self._keys = self._keys.union(['grid_response', 'grids'])\n\n    def dump_flags(self, verbose=None):\n        uhf_grad.Gradients.dump_flags(self, verbose)\n        logger.info(self, 'grid_response = %s', self.grid_response)\n        return self\n\n    get_veff = get_veff\n\n    def extra_force(self, atom_id, envs):\n        '''Hook for extra contributions in analytical gradients.\n\n        Contributions like the response of auxiliary basis in density fitting\n        method, the grid response in DFT numerical integration can be put in\n        this function.\n        '''\n        if self.grid_response:\n            vhf = envs['vhf']\n            log = envs['log']\n            log.debug('grids response for atom %d %s',\n                      atom_id, vhf.exc1_grid[atom_id])\n            return vhf.exc1_grid[atom_id]\n        else:\n            return 0\n\nGrad = Gradients\n\nfrom pyscf import dft\ndft.uks.UKS.Gradients = dft.uks_symm.UKS.Gradients = lib.class_as_method(Gradients)\n\n\nif __name__ == '__main__':\n    from pyscf import gto\n    from pyscf import dft\n\n    mol = gto.Mole()\n    mol.atom = [\n        ['O' , (0. , 0.     , 0.)],\n        [1   , (0. , -0.757 , 0.587)],\n        [1   , (0. ,  0.757 , 0.587)] ]\n    mol.basis = '631g'\n    mol.charge = 1\n    mol.spin = 1\n    mol.build()\n    mf = dft.UKS(mol)\n    mf.conv_tol = 1e-12\n    #mf.grids.atom_grid = (20,86)\n    e0 = mf.scf()\n    g = mf.Gradients()\n    print(lib.finger(g.kernel()) - -0.12090786243525126)\n#[[-5.23195019e-16 -5.70291415e-16  5.32918387e-02]\n# [ 1.33417513e-16  6.75277008e-02 -2.66519852e-02]\n# [ 1.72274651e-16 -6.75277008e-02 -2.66519852e-02]]\n    g.grid_response = True\n    print(lib.finger(g.kernel()) - -0.12091122429043633)\n#[[-2.95956939e-16 -4.22275612e-16  5.32998759e-02]\n# [ 1.34532051e-16  6.75279140e-02 -2.66499379e-02]\n# [ 1.68146089e-16 -6.75279140e-02 -2.66499379e-02]]\n\n    mf.xc = 'b88,p86'\n    e0 = mf.scf()\n    g = Gradients(mf)\n    print(lib.finger(g.kernel()) - -0.11509739136150157)\n#[[ 2.58483362e-16  5.82369026e-16  5.17616036e-02]\n# [-5.46977470e-17  6.39273304e-02 -2.58849008e-02]\n# [ 5.58302713e-17 -6.39273304e-02 -2.58849008e-02]]\n    g.grid_response = True\n    print(lib.finger(g.kernel()) - -0.11507986316077731)\n\n    mf.xc = 'b3lypg'\n    e0 = mf.scf()\n    g = Gradients(mf)\n    print(lib.finger(g.kernel()) - -0.10202554999695367)\n#[[ 6.47874920e-16 -2.75292214e-16  3.97215970e-02]\n# [-6.60278148e-17  5.87909340e-02 -1.98650384e-02]\n# [ 6.75500259e-18 -5.87909340e-02 -1.98650384e-02]]\n\n\n    mol = gto.Mole()\n    mol.atom = [\n        ['H' , (0. , 0. , 1.804)],\n        ['F' , (0. , 0. , 0.   )], ]\n    mol.unit = 'B'\n    mol.basis = '631g'\n    mol.charge = -1\n    mol.spin = 1\n    mol.build()\n\n    mf = dft.UKS(mol)\n    mf.conv_tol = 1e-14\n    mf.kernel()\n    print(lib.finger(Gradients(mf).kernel()) - 0.10365160440876001)\n# sum over z direction non-zero, due to meshgrid response\n# H    -0.0000000000     0.0000000000    -0.1481125370\n# F    -0.0000000000     0.0000000000     0.1481164667\n    mf = dft.UKS(mol)\n    mf.grids.prune = None\n    mf.grids.level = 6\n    mf.conv_tol = 1e-14\n    mf.kernel()\n    print(lib.finger(Gradients(mf).kernel()) - 0.10365040148752827)\n# H     0.0000000000     0.0000000000    -0.1481124925\n# F    -0.0000000000     0.0000000000     0.1481122913\n\n", "meta": {"hexsha": "bea5561995c94b617be6b821b5ccecceb5793122", "size": 11055, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/grad/uks.py", "max_stars_repo_name": "crisely09/pyscf", "max_stars_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-07T21:12:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-07T21:12:08.000Z", "max_issues_repo_path": "pyscf/grad/uks.py", "max_issues_repo_name": "crisely09/pyscf", "max_issues_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-09-16T17:58:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-22T17:26:01.000Z", "max_forks_repo_path": "pyscf/grad/uks.py", "max_forks_repo_name": "crisely09/pyscf", "max_forks_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.009771987, "max_line_length": 88, "alphanum_fraction": 0.5921302578, "include": true, "reason": "import numpy,import scipy", "num_tokens": 3715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.28140560140262283, "lm_q1q2_score": 0.19584657100720076}}
{"text": "# This source reads a text file and produces a data set\n# The file is of the form (where [denotes optional and repeatable]:\n# X,Y,Z[,ARRAYNAME]\n# x0,y0,z0[,value]\n# x1,y1,z1[,value\n# ...\n# from paraview import vtk\n# from random import randint as randi\n# pdo=self.GetOutputDataObject(0)\n# pdi=self.GetInputDataObject(0,0)\n# pdo.CopyAttributes(pdi)\n# pdo.Allocate(500,1)\n# maxPt=pdi.GetNumberOfPoints()\n# for i in range(500):\n# \taLine = vtk.vtkLine()\n# \taLine.GetPointIds().SetId(0, randi(0, maxPt))\n# \taLine.GetPointIds().SetId(1, randi(0, maxPt))\n# \tpdo.InsertNextCell(aLine.GetCellType(), aLine.GetPointIds())\nfrom paraview import vtk\nfrom paraview.vtk import dataset_adapter as DA\nimport os, sys\nfrom numpy import array, single, zeros\nimport numpy\nimport os, sys\n\n\ndef loadFoam(cObj, cNum):\n    cFile = \"/Users/maderk/Documents/MATLAB/TextureTensor/Foam/ujax/dk31m00/\"\n    cFile += \"bubble_dk31_%02d.csv\" % cNum\n    filterList = []\n    # filterList+=[('MASK_DISTANCE_MEAN',lambda x: x>180)]\n    # filterList+=[('VOLUME',lambda x: x<4000)]\n    synList = []\n    synList += [\n        (\n            \"Alignment\",\n            lambda x: 180\n            / numpy.pi\n            * calcAlignment(x, \"PCA1_X\", \"PCA1_Y\", \"PCA1_Z\", \"VOLUME\"),\n        )\n    ]\n    synList += [\n        (\"ShapeAnisotropy\", lambda x: calcAnisotropy(x, \"PCA1_S\", \"PCA2_S\", \"PCA3_S\"))\n    ]\n    synList += [\n        (\"ShapeOblateness\", lambda x: calcOblateness(x, \"PCA1_S\", \"PCA2_S\", \"PCA3_S\"))\n    ]\n    synList += [(\"PosTheta\", lambda x: calcTheta(x, \"POS_X\", \"POS_Y\", recenter=True))]\n    synList += [(\"Theta\", lambda x: calcTheta(x, \"PCA1_X\", \"PCA2_Y\", recenter=False))]\n    synList += [\n        (\"Theta-XZ\", lambda x: chkgvlcalcTheta(x, \"PCA1_X\", \"PCA2_Z\", recenter=False))\n    ]\n    return ImportCSV(cObj, cFile, filterList, synList)\n\n\ndef initCol(cName, data, keepPoints):\n    name = vtk.vtkTypeFloat32Array()\n    name.SetNumberOfComponents(1)\n    name.SetNumberOfTuples(0)\n    name.SetName(cName)\n    if keepPoints is None:\n        keepPoints = range(0, len(data))\n    for cI in keepPoints:\n        name.InsertNextTuple((data[cI],))\n    return name\n\n\ndef initCol3(cName, dat1, dat2, dat3, keepPoints=None):\n    name = vtk.vtkTypeFloat32Array()\n    name.SetNumberOfComponents(3)\n    name.SetNumberOfTuples(0)\n    name.SetName(cName)\n    if keepPoints is None:\n        keepPoints = range(0, len(dat1))\n    for cI in keepPoints:\n        name.InsertNextTuple((dat1[cI], dat2[cI], dat3[cI]))\n    print (cName, len(keepPoints))\n    return name\n\n\ndef initColTens(\n    cName, dat1, dat2, dat3, dat4, dat5, dat6, dat7, dat8, dat9, keepPoints=None\n):\n    name = vtk.vtkTypeFloat32Array()\n    name.SetNumberOfComponents(9)\n    name.SetNumberOfTuples(0)\n    name.SetName(cName + \"_T\")\n    if keepPoints is None:\n        keepPoints = range(0, len(dat1))\n\n    for cI in keepPoints:\n        name.InsertNextTuple(\n            (\n                dat1[cI],\n                dat2[cI],\n                dat3[cI],\n                dat4[cI],\n                dat5[cI],\n                dat6[cI],\n                dat7[cI],\n                dat8[cI],\n                dat9[cI],\n            )\n        )\n    print (cName, len(keepPoints))\n    return name\n\n\ndef getTriplets(allCols, cn1=\"_X\", cn2=\"_Y\", cn3=\"_Z\"):\n    xcols = filter(lambda x: (x.find(cn1) >= 0), allCols)\n    xcols = filter(lambda x: not (x.find(\"T\" + cn1) >= 0), xcols)\n    repPrefix = lambda x, y, z: z.join(x.split(y))\n    goodList = [\n        (\n            repPrefix(curCol, cn1, \"\"),\n            (\n                repPrefix(curCol, cn1, cn1),\n                repPrefix(curCol, cn1, cn2),\n                repPrefix(curCol, cn1, cn3),\n            ),\n        )\n        for curCol in xcols\n        if (\n            (repPrefix(curCol, cn1, cn2) in allCols)\n            and (repPrefix(curCol, cn1, cn3) in allCols)\n        )\n    ]\n    return goodList\n\n\ndef getTensors(\n    allCols, cn1=[\"_XX\", \"_XY\", \"_XZ\", \"_YX\", \"_YY\", \"_YZ\", \"_ZX\", \"_ZY\", \"_ZZ\"]\n):\n    xcols = filter(lambda x: x.find(\"T\" + cn1[0]) >= 0, allCols)\n    repPrefix = lambda x, y, z: z.join(x.split(y))\n    goodList = []\n    for curCol in xcols:\n        cRow = []\n        for curEle in cn1:\n            cName = repPrefix(curCol, cn1[0], curEle)\n            if cName in allCols:\n                cRow += [cName]\n            else:\n                cRow += [\"NULL\"]\n        if len(cRow) > 2:\n            goodList += [(repPrefix(curCol, cn1[0], \"\"), tuple(cRow))]\n    return goodList\n\n\ndef wtexture(xv, yv, zv, wv):\n    \"\"\" Since the function will be used alot and is tedious to implement \"\"\"\n    xv = numpy.array(xv)\n    yv = numpy.array(yv)\n    zv = numpy.array(zv)\n    wv = numpy.array(wv)\n\n    swv = sum(wv)\n    xm = numpy.multiply(xv, wv) / swv\n    ym = numpy.multiply(yv, wv) / swv\n    zm = numpy.multiply(zv, wv) / swv\n\n    xv -= xm\n    yv -= ym\n    zv -= zm\n\n    xv *= wv\n    yv *= wv\n    zv *= wv\n\n    textMat = [[sum(xv * xv) / swv, sum(xv * yv) / swv, sum(xv * zv) / swv]]\n    textMat += [[sum(yv * xv) / swv, sum(yv * yv) / swv, sum(yv * zv) / swv]]\n    textMat += [[sum(zv * xv) / swv, sum(zv * yv) / swv, sum(zv * zv) / swv]]\n    return textMat\n    DA.numpyTovtkDataArray(numpy.random.rand(50, 1))\n\n\nimport numpy as np\n\n\nclass ctexture:\n    def __init__(self, textMat):\n        self.textMat = textMat\n        (self._w, self._v) = np.linalg.eigh(textMat)\n        # self._w=np.sqrt(self._w) # No sqrt in texture tensor\n\n    def todict(self, name=\"TEXTURE\", length=1, oDict=None):\n        if oDict is None:\n            oDict = {}\n        for (i, cAxI) in enumerate(\"XYZ\"):\n            for (j, cAxJ) in enumerate(\"XYZ\"):\n                oDict[name + \"T_\" + cAxI + cAxJ] = [self.textMat[i, j]] * length\n        return oDict\n\n    def mean(self):\n        return sqrt(self.textMat.trace())\n\n    def v1(self):\n        return self._v[:, 2]\n\n    def alignment(self):\n        return 3.0 / 2.0 * (self._w[2] / sum(self._w) - 1.0 / 3.0) * 100\n\n\nclass lacDB_TEXT:\n    def __init__(self):\n        self.count = 0.0\n        self.countn = 0\n        self.sumx2 = 0.0\n        self.sumx = 0.0\n        self.sumxy = 0.0\n        self.sumxz = 0.0\n        self.sumy2 = 0.0\n        self.sumyz = 0.0\n        self.sumz2 = 0.0\n        self.text = 0\n\n    def step(self, valueX, valueY, valueZ, valueW=1.0):\n        if valueX is None:\n            return 0\n        if valueY is None:\n            return 0\n        if valueZ is None:\n            return 0\n        if valueW is None:\n            return 0\n        self.count += valueW\n        self.countn += 1\n        self.sumx += valueW * valueX\n        self.sumy += valueW * valueY\n        self.sumz += valueW * valueZ\n\n        self.sumx2 += valueW * valueX ** 2\n        self.sumxy += valueW * valueX * valueY\n        self.sumxz += valueW * valueX * valueZ\n        self.sumy2 += valueW * valueY ** 2\n        self.sumyz += valueW * valueY * valueZ\n        self.sumz2 += valueW * valueZ ** 2\n\n    def textMat(self):\n        meanx = self.sumx / self.count\n        meany = self.sumy / self.count\n        meanz = self.sumz / self.count\n\n        return np.array(\n            [\n                [\n                    self.sumx2 / self.count - meanx ** 2,\n                    self.sumxy / self.count - meanx * meany,\n                    self.sumxz / self.count - meanx * meanz,\n                ],\n                [\n                    self.sumxy / self.count - meanx * meany,\n                    self.sumy2 / self.count - meany ** 2,\n                    self.sumyz / self.count - meany * meanz,\n                ],\n                [\n                    self.sumxz / self.count - meany * meanz,\n                    self.sumyz / self.count - meany * meanz,\n                    self.sumz2 / self.count - meanz ** 2,\n                ],\n            ]\n        )\n\n    def finalize(self):\n        if self.countn < 2:\n            return 100\n        self.text = ctexture(self.textMat())\n        return self.text.alignment()\n\n\ndef calcAlignment(\n    allcols, cn1, cn2, cn3, cnWeight=None, returnAxis=True, signedAxis=True\n):\n    \"\"\" Since the function will be used alot and is tedious to implement \"\"\"\n    ptlist = []\n    ptlist += [allcols[cn1]]\n    ptlist += [allcols[cn2]]\n    ptlist += [allcols[cn3]]\n    ptlist = numpy.array(ptlist)\n    ptmag = numpy.sqrt(ptlist[0, :] ** 2 + ptlist[1, :] ** 2 + ptlist[2, :] ** 2)\n    ptlist[0, :] /= ptmag\n    ptlist[1, :] /= ptmag\n    ptlist[2, :] /= ptmag\n    if cnWeight is None:\n        textMat = numpy.cov(ptlist)\n    else:\n        xv = ptlist[0, :]\n        yv = ptlist[1, :]\n        zv = ptlist[2, :]\n        wv = numpy.array(allcols[cnWeight])\n        textMat = wtexture(xv, yv, zv, wv)\n        print (len(xv), len(wv))\n        print textMat\n    (_w, _v) = numpy.linalg.eigh(textMat)\n    print \"Main Direction:\" + str(_v[:, 2]) + \", Overall alignment:\" + str(\n        3.0 / 2.0 * (_w[2] / sum(_w) - 1.0 / 3.0) * 100\n    )\n\n    if returnAxis:\n        oMat = []\n        sMat = []\n        for cRow in range(3):\n            mv = numpy.array([list(_v[:, cRow])] * ptlist.shape[1]).transpose()\n            oMat += [numpy.abs(numpy.sum(numpy.multiply(ptlist, mv), 0))]\n            sMat += [numpy.sign(numpy.sum(numpy.multiply(ptlist, mv), 0))]\n        oAx = numpy.argmax(numpy.array(oMat), 0)\n        if signedAxis:\n            sMat = numpy.array(sMat).transpose()\n            return numpy.array(\n                map(lambda x: 2 * (x[1] + 1) + 1 * (x[0][x[1]] == 1), zip(sMat, oAx))\n            )\n        else:\n            return oAx + 1\n    else:\n        mv = numpy.array([list(_v[:, 2])] * ptlist.shape[1]).transpose()\n        return numpy.arccos(numpy.abs(numpy.sum(numpy.multiply(ptlist, mv), 0)))\n\n\ndef calcAnisotropy(allcols, cn1, cn2, cn3):\n    \"\"\" Since the function will be used alot and is tedious to implement \"\"\"\n    p1list = numpy.array(allcols[cn1])\n    p2list = numpy.array(allcols[cn2])\n    p3list = numpy.array(allcols[cn3])\n    return 3.0 / 2.0 * (p1list / (p1list + p2list + p3list) - 1.0 / 3.0) * 100\n\n\ndef calcOblateness(allcols, cn1, cn2, cn3):\n    \"\"\" Since the function will be used alot and is tedious to implement \"\"\"\n    p1list = numpy.array(allcols[cn1])\n    p2list = numpy.array(allcols[cn2])\n    p3list = numpy.array(allcols[cn3])\n    return 2 * (p1list - p2list) / (p1list - p3list) - 1\n\n\ndef calcTheta(allcols, cnx, cny, cnw=None, recenter=True):\n    \"\"\" Since the function will be used alot and is tedious to implement \"\"\"\n    p1list = numpy.array(allcols[cnx])\n    p2list = numpy.array(allcols[cny])\n    if cnw is not None:\n        p3list = numpy.array(allcols[cnw])\n    else:\n        p3list = p1list * 0 + 1\n    mx = numpy.multiply(p1list, p3list) / sum(p3list)\n    my = numpy.multiply(p2list, p3list) / sum(p3list)\n    if not recenter:\n        mx = 0\n        my = 0\n    return 180 / numpy.pi * numpy.arctan2(p2list - my, p1list - mx)\n\n\ndef ImportCSV(cObj, filename=\"\", filterList=[], synList=[], outObj=0, fromR=False):\n    cTable = cObj.GetOutputDataObject(outObj)\n    (header, cols) = LoadCSVFile(filename, fromR=fromR)\n    return ImportData(cTable, cols, filterList, synList)\n\n\ndef ImportDB(cObj, sqlRest=\"\", filterList=[], synList=[], outObj=0):\n    cTable = cObj.GetOutputDataObject(outObj)\n    if len(sqlRest) > 0:\n        sqlRest = \"WHERE \" + sqlRest\n    import dbImport as dbi\n\n    cur = dbi.cur\n    headerCols = [\n        cCol[0] for cCol in cur.execute(\"SHOW COLUMNS FROM LACUNA\").fetchall()\n    ]\n    cols = {}\n    for cCol in headerCols:\n        cols[cCol] = []\n    for cResult in cur.execute(\n        \"SELECT \" + \",\".join(headerCols) + \" FROM LACUNA \" + sqlRest\n    ):\n        for (ccCol, cVal) in zip(headerCols, cResult):\n            cols[ccCol] += [cVal]\n    return ImportData(cTable, cols, filterList, synList)\n\n\ndef ImportData(output, cols, filterList=[], synList=[]):\n    \"\"\" Filter list is for adding lambda based filters, synList is for synthetic columns \"\"\"\n\n    print \"Importing Next Step...\"\n    # ncols=lacpa_adddb(None,cols,header,'',False) # formatted and scaled\n    # cols=ncols\n    print \"Filtering List\"\n    keepPoints = numpy.array([True] * len(cols.values()[0]))  # only\n    for (cFiltCol, cFiltFunc) in filterList:\n        keepPoints &= map(cFiltFunc, cols[cFiltCol])\n    print \"Keeping - \" + str((sum(keepPoints), len(keepPoints)))\n    keepPoints = [cValue for (cValue, isKept) in enumerate(keepPoints) if isKept]\n    for cKey in cols.keys():\n        cols[cKey] = numpy.array(cols[cKey])[keepPoints]\n    print \" Adding columns\"\n    for (cName, cData) in cols.items():\n        output.AddColumn(initCol(cName, cData, None))\n    print \" Adding Triplets\"\n    allTrips = getTriplets(cols.keys())\n    print allTrips\n    for (cName, cCols) in allTrips:\n        output.AddColumn(\n            initCol3(cName, cols[cCols[0]], cols[cCols[1]], cols[cCols[2]], None)\n        )\n    print \" Adding Tensors\"\n    cols[\"NULL\"] = 0 * single(cols.values()[0])\n    allTens = getTensors(cols.keys())\n    print allTens\n    for (cName, cCols) in allTens:\n        output.AddColumn(\n            initColTens(\n                cName,\n                cols[cCols[0]],\n                cols[cCols[1]],\n                cols[cCols[2]],\n                cols[cCols[3]],\n                cols[cCols[4]],\n                cols[cCols[5]],\n                cols[cCols[6]],\n                cols[cCols[7]],\n                cols[cCols[8]],\n                None,\n            )\n        )\n\n    print \" Adding synthetic columns\"\n    for (cName, cFunc) in synList:\n        output.AddColumn(initCol(cName, cFunc(cols), None))\n    return output\n\n\ndef addRowsToTable(output, junkName, outMat, entry_order):\n    # globals()['a']=entry_order\n    # globals()['b']=outMat\n    outArray = numpy.array(outMat)\n    outDict = {}\n    for (cI, cLabel) in enumerate(entry_order):\n        outDict[cLabel] = outArray[:, cI]\n    return outDict\n\n\nfrom numpy import single\n\n\ndef parseCSV(text, filename=\"\", fromR=False):\n    def temp_clean(text):\n        return (\"\".join(text.split(\"/\"))).upper().strip()\n\n    def temp_parse(temp):\n        ntemp = []\n        errCount = 0\n        for val in temp:\n            if val.strip().upper() == \"NAN\":\n                cval = \"0\"\n                errCount += 1\n            else:\n                cval = val\n            try:\n                cval = single(cval)\n            except:\n                cval = -1\n                errCount += 1\n            ntemp += [cval]\n        return (ntemp, errCount)\n\n    rows = text.split(\"\\n\")\n    # First row is header\n    if fromR:\n        fileDict = {}\n        hRow = 0\n    else:\n        hRow = 1\n        head1 = rows[0]\n        head1 = \"\".join(head1.split(\"//\"))\n        newStr = [cEle.strip().split(\":\") for cEle in head1.strip().split(\",\")]\n        fileDict = {}\n        for cEle in newStr:\n            if len(cEle) == 2:\n                fileDict[temp_clean(cEle[0])] = cEle[1].split(\"/\")[-1].strip()\n    fTime = True\n    head2 = rows[hRow]\n    head2 = \"\".join(head2.split(\"//\"))\n    head2 = [temp_clean(cEle) for cEle in head2.strip().split(\",\")]\n    # Check for duplicates in header string (and just use the last entry)\n    # Generate a dictionary of all header entries\n    cleanHeader = {}\n    for k in range(len(head2)):\n        cleanHeader[head2[k]] = k\n    # create a new null filled header\n    head2 = [\"NULL\"] * len(head2)\n    # use the dictionary to repopulate the head2 entry\n    for cKey in cleanHeader.keys():\n        head2[cleanHeader[cKey]] = cKey\n    outTable = {}\n    for col in head2:\n        outTable[col] = []\n    for row in rows[2:]:\n        temp = row.split(\",\")\n        try:\n            (ntemp, errs) = temp_parse(temp)\n            if errs < 2:\n                if len(ntemp) == len(head2):\n                    for k in range(0, len(head2)):\n                        outTable[head2[k]] += [ntemp[k]]\n        except:\n            # if fTime: print (len(ntemp),len(head2))\n            fTime = False\n            temp = []\n    for col in head2:\n        outTable[col] = numpy.array(outTable[col])\n    outrows = len(outTable[head2[0]])\n    print \"Parsed .. \" + str(outrows) + \" of \" + str(len(rows))\n    return (outrows, fileDict, outTable)\n\n\ndef LoadCSVFile(filename, fromR=False):\n    if True:\n        rawtext = \"\".join(open(filename).readlines())\n    else:\n        print filename + \" is garbage\"\n    if True:\n        (outrows, a, b) = parseCSV(rawtext, fromR=fromR)\n        if outrows > 2:\n            return (a, b)\n        else:\n            print filename + \" is too short!\" + str((outrows, a, b))\n    else:\n        print filename + \" is junk:\" + rawtext[0:100]\n\n\ndef getProjNum(*args):\n    return 1\n\n\ndef getSampleNum(*args):\n    return 1\n\n\ndef lacpa_adddb(\n    cur,\n    ptList,\n    oTable,\n    rawFilename,\n    processName=True,\n    tableName=\"Lacuna\",\n    CanalMode=0,\n    projectTitle=\"None\",\n):\n    lacNumOffset = 0\n    if processName:\n        (filename, lacNumOffset) = processInputName(rawFilename, lacFilename)\n    else:\n        filename = rawFilename\n    nptList = dict([(cCol.upper(), cDat) for (cCol, cDat) in ptList.items()])\n    # ptList=CaseFreeDict(ptList)\n\n    dbLen = len(ptList[\"SCALE_X\"])\n    if not oTable.has_key(\"SAMPLE\"):\n        oTable[\"SAMPLE\"] = \"\"\n        print filename + \" is missing sample name\"\n    dx = numpy.median(ptList[\"SCALE_X\"])\n    dy = numpy.median(ptList[\"SCALE_Y\"])\n    dz = numpy.median(ptList[\"SCALE_Z\"])\n    dr = numpy.sqrt(dx ** 2 + dy ** 2 + dz ** 2)\n    lacTemp = {}\n    if type(projectTitle) is type(\"\"):\n        cProjNum = getProjNum(cur, projectTitle)\n    else:\n        cProjNum = projectTitle\n    cSampleNum = getSampleNum(cur, filename, cProjNum)\n    lacTemp[\"SAMPLE_AIM_Number\"] = (cSampleNum,) * dbLen\n    lacTemp[\"PROJECT\"] = (cProjNum,) * dbLen\n    lacunIds = [lacId + lacNumOffset for lacId in ptList[\"LACUNA_NUMBER\"]]\n    lacTemp[tableName + \"_NUMBER\"] = tuple(lacunIds)\n    # Variables that scale directly with x,y,z voxel size\n    lacTemp[\"VOX_SIZE\"] = tuple(numpy.abs(ptList[\"SCALE_X\"] * 1000))\n    scaleVars = [\"POS\", \"STD\", \"PROJ\"]\n    for cVar in scaleVars:\n        for cAx in [\"X\", \"Y\", \"Z\"]:\n            lacTemp[cVar + \"_\" + cAx] = tuple(\n                ptList[cVar + \"_\" + cAx] * ptList[\"SCALE_\" + cAx]\n            )\n    # This doesnt work since I dont save PCA1,2,3 dumb\n    # Variables that scale with PCA 1,2,3 voxel size * denotes PCA1, PCA2, PCA3\n    pcaScaleVars = [\"*_S\", \"PROJ_*\"]\n    for cAx in [\"PCA1\", \"PCA2\", \"PCA3\"]:\n        cDr = numpy.sqrt(\n            (ptList[cAx + \"_X\"] * dx) ** 2\n            + (ptList[cAx + \"_Y\"] * dy) ** 2\n            + (ptList[cAx + \"_Z\"] * dz) ** 2\n        )\n        for cVar in pcaScaleVars:\n            rcVar = cAx.join(cVar.split(\"*\"))\n            lacTemp[rcVar] = tuple(ptList[rcVar] * cDr)\n    # Normal Variables\n    normalVars = [\"PCA1_X\", \"PCA1_Y\", \"PCA1_Z\", \"PCA2_X\", \"PCA2_Y\", \"PCA2_Z\"]\n    normalVars += [\"MASK_GRAD_X\", \"MASK_GRAD_Y\", \"MASK_GRAD_Z\", \"MASK_ANGLE\"]\n    if CanalMode == 0:\n        normalVars += [\"Canal_ANGLE\", \"Canal_GRAD_X\", \"Canal_GRAD_Y\", \"Canal_GRAD_Z\"]\n    for cVar in normalVars:\n        if ptList.has_key(cVar):\n            lacTemp[cVar] = tuple(ptList[cVar])\n        elif (cVar.find(\"GRAD\") >= 0) | (cVar.find(\"ANGLE\")):\n            lacTemp[cVar] = (-1,) * dbLen\n        else:\n            print \"Missing important column:\" + cVar + \", what the frick!\"\n    # Variables that require a radial scaling factor\n    radialVars = [\"MASK_DISTANCE_MEAN\", \"MASK_DISTANCE_STD\"]  # 'MASK_DISTANCE_COV'\n    radialVars += [\"OBJ_RADIUS\", \"OBJ_RADIUS_STD\"]\n    if CanalMode == 0:\n        if ptList.has_key(cVar):\n            radialVars += [\"Canal_DISTANCE_MEAN\", \"Canal_DISTANCE_STD\"]\n    for cVar in radialVars:\n        if ptList.has_key(cVar):\n            lacTemp[cVar] = tuple(numpy.abs(ptList[cVar] * dr))\n    # Variables that require a radial cubed scaling factor\n    volVars = [\"VOLUME\", \"VOLUME_BOX\"]\n    for cVar in volVars:\n        lacTemp[cVar] = tuple(numpy.abs(ptList[cVar] * dx * dy * dz))\n    if ptList.has_key(\"SHELL_CNT\"):\n        lacTemp[\"VOLUME_LAYER\"] = tuple(\n            numpy.abs((ptList[\"VOLUME\"] - ptList[\"SHELL_CNT\"]) * dx * dy * dz)\n        )\n    # GrayAnalysis Columns\n    if ptList.has_key(\"MASK\"):  # new Lacuna method\n        lacTemp[\"MASK_DISTANCE_MEAN\"] = tuple(numpy.abs(ptList[\"MASK\"] * dr))\n        lacTemp[\"MASK_DISTANCE_STD\"] = tuple(numpy.abs(ptList[\"MASK_STD\"] * dr))\n    if ptList.has_key(\"MASK_WX\"):\n        lacTemp[\"MASK_GRAD\"] = tuple(ptList[\"MASK\"])\n        lacTemp[\"MASK_DISTANCE_STD\"] = tuple(ptList[\"MASK_STD\"])\n    if ptList.has_key(\"SHELL_ABSORPTION\"):\n        lacTemp[\"SHELL_ABSORPTION\"] = tuple(ptList[\"SHELL_ABSORPTION\"])\n    if ptList.has_key(\"SHELL_ABSORPTION_STD\"):\n        lacTemp[\"SHELL_ABSORPTION_STD\"] = tuple(ptList[\"SHELL_ABSORPTION_STD\"])\n    else:\n        lacTemp[\"SHELL_ABSORPTION\"] = (-1,) * dbLen\n        lacTemp[\"SHELL_ABSORPTION_STD\"] = (-1,) * dbLen\n    # Lining Absorption\n    if ptList.has_key(\"LINING_ABSORPTION\"):\n        lacTemp[\"LINING_ABSORPTION\"] = tuple(ptList[\"LINING_ABSORPTION\"])\n    if ptList.has_key(\"LINING_ABSORPTION_STD\"):\n        lacTemp[\"LINING_ABSORPTION_STD\"] = tuple(ptList[\"LINING_ABSORPTION_STD\"])\n    else:\n        lacTemp[\"LINING_ABSORPTION\"] = (-1,) * dbLen\n        lacTemp[\"LINING_ABSORPTION_STD\"] = (-1,) * dbLen\n    if CanalMode == 0:\n        # This doesnt work since I dont save PCA1,2,3 dumb\n        # Variables that scale with PCA 1,2,3 voxel size * denotes PCA1, PCA2, PCA3\n        for cAx in [\"PCA1\", \"PCA2\", \"PCA3\"]:\n            cDr = numpy.sqrt(\n                (ptList[cAx + \"_X\"] * dx) ** 2\n                + (ptList[cAx + \"_Y\"] * dy) ** 2\n                + (ptList[cAx + \"_Z\"] * dz) ** 2\n            )\n            rcVar = \"DENSITY_PROJ_\" + cAx\n            if ptList.has_key(\"DENSITY_VOLUME_PROJ_\" + cAx):\n                lacTemp[rcVar] = tuple(ptList[rcVar] * cDr)\n            else:\n                lacTemp[rcVar] = (-1,) * dbLen\n        if ptList.has_key(\"Canal_NUMBER\"):\n            lacTemp[\"Canal_NUMBER\"] = tuple(ptList[\"Canal_NUMBER\"])\n            # lacTemp['Canal_NAME']=tuple([projectTitle+'_'+filename+'_CAN_'+str(int(curCan)) for curCan in ptList['Canal_NUMBER']])\n        if ptList.has_key(\"Canal_NUMBER_STD\"):\n            lacTemp[\"Canal_NUMBER_STD\"] = tuple(ptList[\"Canal_NUMBER_STD\"])\n        else:\n            lacTemp[\"Canal_NUMBER_STD\"] = (-1,) * dbLen\n        # Nearest Neighbors\n        lacTemp[\"NEAREST_NEIGHBOR_DISTANCE\"] = (-1,) * dbLen\n        lacTemp[\"NEAREST_NEIGHBOR_ANGLE\"] = (-1,) * dbLen\n\n        if ptList.has_key(\"NEIGHBORS\"):\n            lacTemp[\"NEAREST_NEIGHBOR_NEIGHBORS\"] = tuple(ptList[\"NEIGHBORS\"])\n        else:\n            lacTemp[\"NEAREST_NEIGHBOR_NEIGHBORS\"] = (-1,) * dbLen\n        # Mask Params\n        lacTemp[\"POS_RADIUS\"] = (-1,) * dbLen\n        lacTemp[\"MASK_RADIUS\"] = (-1,) * dbLen\n        lacTemp[\"MASK_RADIUS_MIN\"] = (-1,) * dbLen\n        lacTemp[\"MASK_RADIUS_MAX\"] = (-1,) * dbLen\n        lacTemp[\"MASK_RADIUS_MEAN\"] = (-1,) * dbLen\n        lacTemp[\"MASK_THETA\"] = (-1,) * dbLen\n    if ptList.has_key(\"THICKNESS\"):\n        lacTemp[\"THICKNESS\"] = tuple(ptList[\"THICKNESS\"])\n    else:\n        lacTemp[\"THICKNESS\"] = (-1,) * dbLen\n    if ptList.has_key(\"THICKNESS_STD\"):\n        lacTemp[\"THICKNESS_STD\"] = tuple(ptList[\"THICKNESS_STD\"])\n    else:\n        lacTemp[\"THICKNESS_STD\"] = (-1,) * dbLen\n    # Lacuna Density / Volume\n    if ptList.has_key(\"DENSITY_VOLUME\"):\n        lacTemp[\"DENSITY_VOLUME\"] = tuple(\n            numpy.abs(ptList[\"DENSITY_VOLUME\"] * dx * dy * dz)\n        )\n        lacTemp[\"DENSITY\"] = tuple(\n            numpy.abs(1 / (ptList[\"DENSITY_VOLUME\"] * dx * dy * dz))\n        )\n    elif ptList.has_key(\"DENSITY_VOLUME_CNT\"):\n        lacTemp[\"DENSITY_VOLUME\"] = tuple(\n            numpy.abs(ptList[\"DENSITY_VOLUME_CNT\"] * dx * dy * dz)\n        )\n        lacTemp[\"DENSITY\"] = tuple(\n            numpy.abs(1 / (ptList[\"DENSITY_VOLUME_CNT\"] * dx * dy * dz))\n        )\n    else:\n        lacTemp[\"DENSITY_VOLUME\"] = (-1,) * dbLen\n        lacTemp[\"DENSITY\"] = (-1,) * dbLen\n    if CanalMode == 0:\n        # Lacuna Territory Shape\n        lacTemp[\"DISPLACEMENT_MEAN\"] = (-1,) * dbLen\n        if ptList.has_key(\"NEIGHBOR_AREA\"):\n            lacTemp[\"DENSITY_VOLUME_SHELL\"] = tuple(\n                numpy.abs(ptList[\"NEIGHBOR_AREA\"] * dx * dy)\n            )\n        elif ptList.has_key(\"MASK_VOLUME_SHELL_CNT\"):\n            ## Old Definition of Shell\n            lacTemp[\"DENSITY_VOLUME_SHELL\"] = tuple(\n                numpy.abs(ptList[\"MASK_VOLUME_SHELL_CNT\"] * dx * dy * dz)\n            )\n        else:\n            lacTemp[\"DENSITY_VOLUME_SHELL\"] = (-1,) * dbLen\n        # Lacuna Territory that is mineralized\n        if ptList.has_key(\"BONE_VOLUME_CNT\"):\n            lacTemp[\"DENSITY_VOLUME_BONE\"] = tuple(\n                numpy.abs(ptList[\"BONE_VOLUME_CNT\"] * dx * dy * dz)\n            )\n        else:\n            lacTemp[\"DENSITY_VOLUME_BONE\"] = (-1,) * dbLen\n        # Lacuna Territory that is part of the mask (for porosity calculations)\n        if ptList.has_key(\"MASK_VOLUME_CNT\"):\n            lacTemp[\"DENSITY_VOLUME_MASK\"] = tuple(\n                numpy.abs(ptList[\"MASK_VOLUME_CNT\"] * dx * dy * dz)\n            )\n        else:\n            lacTemp[\"DENSITY_VOLUME_MASK\"] = (-1,) * dbLen\n        # PCA1 is a makeshift holding place for STD until the table is once again updated\n        terrShapeMap = {\n            \"DENSITY_VOLUME_C\": \"DENSITY_\",\n            \"DENSITY_VOLUME_S\": \"DENSITY_STD_\",\n        }\n        for cKey in terrShapeMap.keys():\n            missingKeys = False\n            for cAx in [\"X\", \"Y\", \"Z\"]:\n                # print cKey+cAx\n                if ptList.has_key(cKey + cAx):\n                    # print 'isch da'\n                    lacTemp[terrShapeMap[cKey] + cAx] = tuple(\n                        ptList[cKey + cAx] * ptList[\"SCALE_\" + cAx]\n                    )\n                else:\n                    if cKey == \"DENSITY_VOLUME_C\":\n                        missingKeys = True\n                    else:\n                        lacTemp[terrShapeMap[cKey] + cAx] = (-1,) * dbLen\n            if not missingKeys:\n                if cKey == \"DENSITY_VOLUME_C\":\n                    dispMean = numpy.sqrt(\n                        ((ptList[cKey + \"X\"] - ptList[\"POS_X\"]) * dx) ** 2\n                        + ((ptList[cKey + \"Y\"] - ptList[\"POS_Y\"]) * dy) ** 2\n                        + ((ptList[cKey + \"Z\"] - ptList[\"POS_Z\"]) * dz) ** 2\n                    )\n                    lacTemp[\"DISPLACEMENT_MEAN\"] = tuple(dispMean)\n                    lacTemp[\"DISPLACEMENT_X\"] = tuple(\n                        (ptList[cKey + \"X\"] - ptList[\"POS_X\"]) * dx\n                    )\n                    lacTemp[\"DISPLACEMENT_Y\"] = tuple(\n                        (ptList[cKey + \"Y\"] - ptList[\"POS_Y\"]) * dy\n                    )\n                    lacTemp[\"DISPLACEMENT_Z\"] = tuple(\n                        (ptList[cKey + \"Z\"] - ptList[\"POS_Z\"]) * dz\n                    )\n    # Polar Coordinates Hints\n    # Only really valid for Full Femur, but Lacuna angle can be useful\n    mR = numpy.sqrt(\n        ((ptList[\"POS_X\"] - numpy.mean(ptList[\"POS_X\"])) * dx) ** 2\n        + ((ptList[\"POS_Y\"] - numpy.mean(ptList[\"POS_Y\"])) * dy) ** 2\n    )\n    for cPCA in [1, 2]:\n        pR = numpy.sqrt(\n            ptList[\"PCA\" + str(cPCA) + \"_X\"] ** 2\n            + ptList[\"PCA\" + str(cPCA) + \"_Y\"] ** 2\n        )\n        pPhi = 180 / numpy.pi * numpy.arctan2(ptList[\"PCA\" + str(cPCA) + \"_Z\"], pR)\n        lacTemp[\"PCA\" + str(cPCA) + \"_Phi\"] = tuple(pPhi)\n        lacTemp[\"PCA\" + str(cPCA) + \"_Theta\"] = tuple(\n            180 / numpy.pi * numpy.arccos(ptList[\"PCA\" + str(cPCA) + \"_X\"] / pR)\n        )  # update\n    # Junk Angles\n    lacTemp[\"POS_THETA\"] = (-1,) * dbLen\n    lacTemp[\"MASK_THETA\"] = (-1,) * dbLen\n    lacTemp[\"POS_DISTANCE\"] = (-1,) * dbLen\n    lacTemp[\"NEAREST_NEIGHBOR_AVG\"] = (-1,) * dbLen\n    lacTemp[\"NEAREST_NEIGHBOR_DISTANCE\"] = (-1,) * dbLen\n    lacTemp[\"NEAREST_NEIGHBOR_DISTANCE\"] = (-1,) * dbLen\n    # Normalize PCA\n    pcastot = dr * numpy.sqrt(\n        ptList[\"PCA1_S\"] ** 2 + ptList[\"PCA2_S\"] ** 2 + ptList[\"PCA3_S\"] ** 2\n    )\n    # lacTemp['PCAS_TOTAL']=tuple(pcastot)\n    # for tz in lacTemp.keys(): print tz+' '+str(len(lacTemp[tz]))\n    outKeys = lacTemp.keys()\n    outArr = [lacTemp[cKey] for cKey in outKeys]\n    # for cKey in outKeys: print (cKey,len(lacTemp[cKey]))\n    outMat = numpy.array(outArr).swapaxes(1, 0)\n    invalidRows = numpy.sum(numpy.isnan(outMat), 1)\n    outMat = outMat[numpy.nonzero(invalidRows == 0)[0], :]\n    globals()[\"Om\"] = outMat\n    outMat = [tuple(obj) for obj in outMat]\n    return None\n    return addRowsToTable(cur, tableName, outMat, entry_order=outKeys)\n    print filename + \" was successfully entered %05d, invalid  %03d\" % (\n        lacNumOffset,\n        sum(invalidRows),\n    )\n\n\nclass CaseFreeDict:\n    \"\"\"Dictionary, that has case-insensitive keys.\n    \n    Keys are retained in their original form\n    when queried with .keys() or .items().\n\n    Implementation: An internal dictionary maps lowercase\n    keys to (key,value) pairs. All key lookups are done\n    against the lowercase keys, but all methods that expose\n    keys to the user retrieve the original keys.\"\"\"\n\n    def __init__(self, dict=None):\n        \"\"\"Create an empty dictionary, or update from 'dict'.\"\"\"\n        self._dict = {}\n        if dict:\n            self.update(dict)\n\n    def __getitem__(self, key):\n        \"\"\"Retrieve the value associated with 'key' (in any case).\"\"\"\n        k = key.lower()\n        return self._dict[k][1]\n\n    def __setitem__(self, key, value):\n        \"\"\"Associate 'value' with 'key'. If 'key' already exists, but\n        in different case, it will be replaced.\"\"\"\n        k = key.lower()\n        self._dict[k] = (key, value)\n\n    def has_key(self, key):\n        \"\"\"Case insensitive test wether 'key' exists.\"\"\"\n        k = key.lower()\n        return self._dict.has_key(k)\n\n    def keys(self):\n        \"\"\"List of keys in their original case.\"\"\"\n        return [v[0] for v in self._dict.values()]\n\n    def values(self):\n        \"\"\"List of values.\"\"\"\n        return [v[1] for v in self._dict.values()]\n\n    def items(self):\n        \"\"\"List of (key,value) pairs.\"\"\"\n        return self._dict.values()\n\n    def get(self, key, default=None):\n        \"\"\"Retrieve value associated with 'key' or return default value\n        if 'key' doesn't exist.\"\"\"\n        try:\n            return self[key]\n        except KeyError:\n            return default\n\n    def setdefault(self, key, default):\n        \"\"\"If 'key' doesn't exists, associate it with the 'default' value.\n        Return value associated with 'key'.\"\"\"\n        if not self.has_key(key):\n            self[key] = default\n        return self[key]\n\n    def update(self, dict):\n        \"\"\"Copy (key,value) pairs from 'dict'.\"\"\"\n        for k, v in dict.items():\n            self[k] = v\n\n    def __repr__(self):\n        \"\"\"String representation of the dictionary.\"\"\"\n        items = \", \".join([(\"%r: %r\" % (k, v)) for k, v in self.items()])\n        return \"{%s}\" % items\n\n    def __str__(self):\n        \"\"\"String representation of the dictionary.\"\"\"\n        return repr(self)\n", "meta": {"hexsha": "ee5ddfdaf69e1446e2b6818e102bbae02a1fe166", "size": 30985, "ext": "py", "lang": "Python", "max_stars_repo_path": "snippets/Python/pvtools.py", "max_stars_repo_name": "JLLeitschuh/TIPL", "max_stars_repo_head_hexsha": "89c5d82932f89a2b4064d5d86ac83045ce9bc7d5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-22T11:02:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-22T11:02:52.000Z", "max_issues_repo_path": "snippets/Python/pvtools.py", "max_issues_repo_name": "JLLeitschuh/TIPL", "max_issues_repo_head_hexsha": "89c5d82932f89a2b4064d5d86ac83045ce9bc7d5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-11-21T14:13:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-11T15:15:23.000Z", "max_forks_repo_path": "snippets/Python/pvtools.py", "max_forks_repo_name": "JLLeitschuh/TIPL", "max_forks_repo_head_hexsha": "89c5d82932f89a2b4064d5d86ac83045ce9bc7d5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-11T06:19:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-11T06:19:45.000Z", "avg_line_length": 34.932356257, "max_line_length": 132, "alphanum_fraction": 0.5526222366, "include": true, "reason": "import numpy,from numpy", "num_tokens": 9013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.1958270216359123}}
{"text": "\"\"\"\nThe ``bifacial`` module contains functions for modeling back surface\nplane-of-array irradiance under various conditions.\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\n\n\ndef pvfactors_timeseries(\n        solar_azimuth, solar_zenith, surface_azimuth, surface_tilt,\n        axis_azimuth,\n        timestamps, dni, dhi, gcr, pvrow_height, pvrow_width, albedo,\n        n_pvrows=3, index_observed_pvrow=1,\n        rho_front_pvrow=0.03, rho_back_pvrow=0.05,\n        horizon_band_angle=15.,\n        run_parallel_calculations=True, n_workers_for_parallel_calcs=2):\n    \"\"\"\n    Calculate front and back surface plane-of-array irradiance on\n    a fixed tilt or single-axis tracker PV array configuration, and using\n    the open-source \"pvfactors\" package.  pvfactors implements the model\n    described in [1]_.\n    Please refer to pvfactors online documentation for more details:\n    https://sunpower.github.io/pvfactors/\n\n    Parameters\n    ----------\n    solar_azimuth: numeric\n        Sun's azimuth angles using pvlib's azimuth convention (deg)\n    solar_zenith: numeric\n        Sun's zenith angles (deg)\n    surface_azimuth: numeric\n        Azimuth angle of the front surface of the PV modules, using pvlib's\n        convention (deg)\n    surface_tilt: numeric\n        Tilt angle of the PV modules, going from 0 to 180 (deg)\n    axis_azimuth: float\n        Azimuth angle of the rotation axis of the PV modules, using pvlib's\n        convention (deg). This is supposed to be fixed for all timestamps.\n    timestamps: datetime or DatetimeIndex\n        List of simulation timestamps\n    dni: numeric\n        Direct normal irradiance (W/m2)\n    dhi: numeric\n        Diffuse horizontal irradiance (W/m2)\n    gcr: float\n        Ground coverage ratio of the pv array\n    pvrow_height: float\n        Height of the pv rows, measured at their center (m)\n    pvrow_width: float\n        Width of the pv rows in the considered 2D plane (m)\n    albedo: float\n        Ground albedo\n    n_pvrows: int, default 3\n        Number of PV rows to consider in the PV array\n    index_observed_pvrow: int, default 1\n        Index of the PV row whose incident irradiance will be returned. Indices\n        of PV rows go from 0 to n_pvrows-1.\n    rho_front_pvrow: float, default 0.03\n        Front surface reflectivity of PV rows\n    rho_back_pvrow: float, default 0.05\n        Back surface reflectivity of PV rows\n    horizon_band_angle: float, default 15\n        Elevation angle of the sky dome's diffuse horizon band (deg)\n    run_parallel_calculations: bool, default True\n        pvfactors is capable of using multiprocessing. Use this flag to decide\n        to run calculations in parallel (recommended) or not.\n    n_workers_for_parallel_calcs: int, default 2\n        Number of workers to use in the case of parallel calculations. The\n        '-1' value will lead to using a value equal to the number\n        of CPU's on the machine running the model.\n\n    Returns\n    -------\n    front_poa_irradiance: numeric\n        Calculated incident irradiance on the front surface of the PV modules\n        (W/m2)\n    back_poa_irradiance: numeric\n        Calculated incident irradiance on the back surface of the PV modules\n        (W/m2)\n    df_registries: pandas DataFrame\n        DataFrame containing detailed outputs of the simulation; for\n        instance the shapely geometries, the irradiance components incident on\n        all surfaces of the PV array (for all timestamps), etc.\n        In the pvfactors documentation, this is refered to as the \"surface\n        registry\".\n\n    References\n    ----------\n    .. [1] Anoma, Marc Abou, et al. \"View Factor Model and Validation for\n        Bifacial PV and Diffuse Shade on Single-Axis Trackers.\" 44th IEEE\n        Photovoltaic Specialist Conference. 2017.\n    \"\"\"\n\n    # Convert pandas Series inputs (and some lists) to numpy arrays\n    if isinstance(solar_azimuth, pd.Series):\n        solar_azimuth = solar_azimuth.values\n    elif isinstance(solar_azimuth, list):\n        solar_azimuth = np.array(solar_azimuth)\n    if isinstance(solar_zenith, pd.Series):\n        solar_zenith = solar_zenith.values\n    if isinstance(surface_azimuth, pd.Series):\n        surface_azimuth = surface_azimuth.values\n    elif isinstance(surface_azimuth, list):\n        surface_azimuth = np.array(surface_azimuth)\n    if isinstance(surface_tilt, pd.Series):\n        surface_tilt = surface_tilt.values\n    if isinstance(dni, pd.Series):\n        dni = dni.values\n    if isinstance(dhi, pd.Series):\n        dhi = dhi.values\n    if isinstance(solar_azimuth, list):\n        solar_azimuth = np.array(solar_azimuth)\n\n    # Import pvfactors functions for timeseries calculations.\n    from pvfactors.run import (run_timeseries_engine,\n                               run_parallel_engine)\n\n    # Build up pv array configuration parameters\n    pvarray_parameters = {\n        'n_pvrows': n_pvrows,\n        'axis_azimuth': axis_azimuth,\n        'pvrow_height': pvrow_height,\n        'pvrow_width': pvrow_width,\n        'gcr': gcr,\n        'rho_front_pvrow': rho_front_pvrow,\n        'rho_back_pvrow': rho_back_pvrow,\n        'horizon_band_angle': horizon_band_angle\n    }\n\n    # Run pvfactors calculations: either in parallel or serially\n    if run_parallel_calculations:\n        report = run_parallel_engine(\n            PVFactorsReportBuilder, pvarray_parameters,\n            timestamps, dni, dhi,\n            solar_zenith, solar_azimuth,\n            surface_tilt, surface_azimuth,\n            albedo, n_processes=n_workers_for_parallel_calcs)\n    else:\n        report = run_timeseries_engine(\n            PVFactorsReportBuilder.build, pvarray_parameters,\n            timestamps, dni, dhi,\n            solar_zenith, solar_azimuth,\n            surface_tilt, surface_azimuth,\n            albedo)\n\n    # Turn report into dataframe\n    df_report = pd.DataFrame(report, index=timestamps)\n\n    return df_report.total_inc_front, df_report.total_inc_back\n\n\nclass PVFactorsReportBuilder(object):\n    \"\"\"In pvfactors, a class is required to build reports when running\n    calculations with multiprocessing because of python constraints\"\"\"\n\n    @staticmethod\n    def build(report, pvarray):\n        \"\"\"Reports will have total incident irradiance on front and\n        back surface of center pvrow (index=1)\"\"\"\n        # Initialize the report as a dictionary\n        if report is None:\n            report = {'total_inc_back': [], 'total_inc_front': []}\n        # Add elements to the report\n        if pvarray is not None:\n            pvrow = pvarray.pvrows[1]  # use center pvrow\n            report['total_inc_back'].append(\n                pvrow.back.get_param_weighted('qinc'))\n            report['total_inc_front'].append(\n                pvrow.front.get_param_weighted('qinc'))\n        else:\n            # No calculation is performed when the sun is down\n            report['total_inc_back'].append(np.nan)\n            report['total_inc_front'].append(np.nan)\n\n        return report\n\n    @staticmethod\n    def merge(reports):\n        \"\"\"Works for dictionary reports. Merges the reports list of\n        dictionaries in a single dictionary. The list of the first\n        dictionary are extended by those of all subsequent lists.\"\"\"\n        report = reports[0]\n        keys_report = list(report.keys())\n        for other_report in reports[1:]:  # loop won't run if len(reports) < 2\n            for key in keys_report:\n                report[key] += other_report[key]\n        return report\n", "meta": {"hexsha": "bc59e9ef111388a9092ba8540b76e48628ae9dc2", "size": 7458, "ext": "py", "lang": "Python", "max_stars_repo_path": "pvlib/bifacial.py", "max_stars_repo_name": "Ahanmr/pvlib-python", "max_stars_repo_head_hexsha": "fea9ff81a114506a95e21dbbebf79d79787d54c7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-17T14:28:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-17T14:28:35.000Z", "max_issues_repo_path": "pvlib/bifacial.py", "max_issues_repo_name": "Ahanmr/pvlib-python", "max_issues_repo_head_hexsha": "fea9ff81a114506a95e21dbbebf79d79787d54c7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-01-10T17:43:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T03:52:45.000Z", "max_forks_repo_path": "pvlib/bifacial.py", "max_forks_repo_name": "Ahanmr/pvlib-python", "max_forks_repo_head_hexsha": "fea9ff81a114506a95e21dbbebf79d79787d54c7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-17T15:47:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-17T15:47:03.000Z", "avg_line_length": 39.4603174603, "max_line_length": 79, "alphanum_fraction": 0.674711719, "include": true, "reason": "import numpy", "num_tokens": 1743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19582702163591229}}
{"text": "\"\"\"\r\n    Code for collecting failure trajectories using Bayesian Optimization\r\n    Project : Policy correction using Bayesian Optimization\r\n    Description : The file contains functions for computing failure trajectories given RL policy and\r\n    safety specifications\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport gym\r\nimport GPyOpt\r\nfrom numpy.random import seed\r\nfrom eval_policy import choose_best_action\r\nimport gym\r\nfrom network import FeedForwardActorNN\r\nimport torch\r\nimport pickle\r\nfrom numpy import arange\r\nfrom numpy.random import rand\r\n\r\n'''\r\n    Bayesian Optimization module for uncovering failure trajectories\r\n\r\n    Safety Requirement\r\n    # Requirement 1: We would like the cartpole to not travel more than a certain\r\n    # distance from its original location(2.4) \r\n    # Always stay within the region (-2.4, 2.4)\r\n'''\r\n\r\n#=============================================Global Variables =================================#\r\npolicy = None\r\nenv = None\r\ntraj_spec_dic = {}\r\ntraj_count = 0\r\n\r\n\r\n'''\r\n    The function called from within the bayesian optimization module\r\n    parameters : bounds containing the sampled variables of the state vector\r\n    return : calls specification function and computes and returns the minimum value\r\n'''\r\ndef sample_trajectory(sample_1,sample_2,sample_3,sample_4):\r\n    global policy, env, traj_spec_dic,traj_count\r\n    x1 = sample_1\r\n    x2 = sample_2\r\n    x3 = sample_3\r\n    x4 = sample_4\r\n    obs = np.array([x1,x2,x3,x4])\r\n    #print(f'obs =========== {obs}')\r\n    max_steps = 400\r\n    env.reset()\r\n    env.env.state = obs\r\n    traj = [obs]\r\n    actions = []\r\n    reward = 0\r\n    iters= 0\r\n    ep_ret = 0\r\n    done = False\r\n    for _ in range(max_steps):\r\n        iters+=1\r\n        action = choose_best_action(obs,policy)\r\n        actions.append(action)\r\n        obs, rew, done, _ = env.step(action)\r\n        #add the observation state to the current trajectory\r\n        traj.append(obs)\r\n        ep_ret += rew\r\n        if done:\r\n            break\r\n    additional_data = {'reward':ep_ret, 'mass':env.env.total_mass}\r\n    #Create trajectory to be sent to safety specification\r\n    traj = (traj, additional_data)\r\n    #print(f'trajectory ========== {traj}')\r\n    specification_evaluation = safety_spec(traj)\r\n    #Store the set of trajectories with negative evaluation\r\n    if specification_evaluation<0:\r\n        traj_spec_dic[traj_count] = (traj[0],specification_evaluation)\r\n        traj_count = traj_count + 1\r\n    print(f'specification_evaluation ========== {specification_evaluation}')\r\n    return specification_evaluation\r\n\r\n\r\ndef run_Random():\r\n    x1_max = 0.05\r\n    x1_min = -0.05\r\n    x2_max = 0.05\r\n    x2_min = -0.05\r\n    x3_max = 0.05\r\n    x3_min = -0.05\r\n    x4_max = 0.05\r\n    x4_min = -0.05\r\n    # generate a random sample from the domain\r\n    sample_1 = x1_min + rand(1000) * (x1_max - x1_min)\r\n    sample_2 = x2_min + rand(1000) * (x2_max - x2_min)\r\n    sample_3 = x3_min + rand(1000) * (x3_max - x3_min)\r\n    sample_4 = x4_min + rand(1000) * (x4_max - x4_min)\r\n    sample = list()\r\n    step = 0.1\r\n    print(f'sample length ========== {len(sample_1)}')\r\n    for i in range(len(sample_1)):\r\n        val = sample_trajectory(sample_1[i],sample_2[i],sample_3[i],sample_4[i])\r\n        print(f'sample1 =========== {sample_1[i]} ======== sample2 ==== {sample_2[i]} ==== sample3 ===== {sample_3[i]}')\r\n    '''sample = list()\r\n    step = 0.04\r\n    for sample_1 in arange(x1_min, x1_max+step, step):\r\n        for sample_2 in arange(x2_min, x2_max+step, step):\r\n            for sample_3 in arange(x3_min, x3_max+step, step):\r\n                for sample_4 in arange(x4_min, x4_max+step, step):\r\n                    sample.append([sample_1,sample_2,sample_3,sample_4])\r\n    print(f'sample length ========== {len(sample)}')\r\n    for i in range(len(sample)):\r\n        val = sample_trajectory(sample[i][0],sample[i][1],sample[i][2],sample[i][3])\r\n        print(f'sample1 =========== {sample[i][0]} ======== sample2 ==== {sample[i][1]} ==== sample3 ===== {sample[i][2]}')'''\r\n\r\n\r\n# 1. Always stay within the region (-2.4, 2.4)\r\ndef safety_spec(traj):\r\n    traj = traj[0]\r\n    #print(f'traj ========== {traj}')\r\n    x_s = np.array(traj).T[0]\r\n    #print(f'min value ========== {x_s}')\r\n    return min(2.4 - np.abs(x_s))\r\n\r\n# 2. Maintain a momentum >=-2.0 and <= 2.0\r\ndef safet_spec_2(traj):\r\n    traj_ = traj[0]\r\n    #print(f'traj ========== {traj}')\r\n    mass = traj[1]['mass']\r\n    v_s = np.array(traj_).T[1]\r\n    return min(2. - np.abs(mass*v_s))\r\n\r\n\r\n# 3. The angle made by the cartpole should <=0.2 within the rest position\r\ndef safet_spec_3(traj):\r\n    traj = traj[0]\r\n    theta=np.array(traj).T[2]\r\n    #print(f'theta ========== {theta}')\r\n    return min(0.2 - np.abs(theta))\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n    env = gym.make('CartPole-v0')\r\n    seed = 0\r\n    env.seed(seed)\r\n    actor_model = 'Policies/ppo_actor_updatedCartPole-v0.pth'\r\n    # Extract out dimensions of observation and action spaces\r\n    obs_dim = env.observation_space.shape[0]\r\n    act_dim = env.action_space.n #env.action_space.shape[0]\r\n\r\n    # Build our policy the same way we build our actor model in PPO\r\n    policy = FeedForwardActorNN(obs_dim, act_dim,True)\r\n\r\n    # Load in the actor model saved by the PPO algorithm\r\n    policy.load_state_dict(torch.load(actor_model))\r\n    run_Random()\r\n    print(f'Length trajectory ========== {len(traj_spec_dic)}')\r\n    with open('failure_trajectory_cartpole.data', 'wb') as filehandle1:\r\n        # store the observation data as binary data stream\r\n        pickle.dump(traj_spec_dic, filehandle1)\r\n\r\n", "meta": {"hexsha": "7f94a0c6ad796e1cde11827ac79fd1870954cd45", "size": 5563, "ext": "py", "lang": "Python", "max_stars_repo_path": "Policy Refinement Using Bayesian Optimization/CartpoleRandom.py", "max_stars_repo_name": "britig/policy-refinement-bo", "max_stars_repo_head_hexsha": "c8a1e347d6e27c991e945afae9b5d9b482806f4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-28T05:07:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T05:07:41.000Z", "max_issues_repo_path": "Policy Refinement Using Bayesian Optimization/CartpoleRandom.py", "max_issues_repo_name": "britig/policy-refinement-bo", "max_issues_repo_head_hexsha": "c8a1e347d6e27c991e945afae9b5d9b482806f4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Policy Refinement Using Bayesian Optimization/CartpoleRandom.py", "max_forks_repo_name": "britig/policy-refinement-bo", "max_forks_repo_head_hexsha": "c8a1e347d6e27c991e945afae9b5d9b482806f4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.76875, "max_line_length": 127, "alphanum_fraction": 0.6187309006, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19582702163591229}}
{"text": "# VIRANET TOOLS #\n###############################################################################\n# objSto\n# Strips stoichiometric coefficients from the objectives reactions\n# usage\n# Inputs:\n# HVM               Integrated host-virus model\n# HostRxn           Host objective reaction, either:\n#                   - Index value of reaction in Model.reactions        [int]\n#                   - Reaction ID of the host-objective reaction        [str]\n#\n# Outputs:\n# hostSto           Stoichiometric coefficients with metabolites for host objective\n# virusSto          Stoichiometric coefficients with metabolites for virus objective\n#\n\ndef objSto(HVM,HostRxn):\n    \"Differential usage of amino acids and nucleotides\"\n    # [1] Initial Setup\n    # Function Dependencies\n    import pandas   as pd\n    import numpy    as np\n    # Identify the host objective reaction\n    try:\n        intTest = int(HostRxn)\n        hostIdx = HostRxn\n    except:\n        for ii in range(len(HVM.reactions)):\n            if HostRxn in str(HVM.reactions[ii]):\n                hostIdx = ii\n    virusIdx    = len(HVM.reactions) - 1    # ViraNet(c) appends virus reaction to end in genHVM.py\n    objIdx      = [hostIdx,virusIdx]\n    hostID      = HVM.reactions[hostIdx].id\n    virusID     = HVM.reactions[virusIdx].id\n    # Condition: ensure virus reaction is virus objective\n    if '_prodrxn_VN' not in virusID:\n        raise ValueError('Unsupported objective, unable to analyse: refer to README')\n    # Convert model into an array\n    m       = HVM.to_array_based_model()\n    # Create data frame\n    mFrame  = pd.DataFrame(\n        data    = m.S.todense(),\n        columns = m.reactions.list_attr(\"id\"),\n        index   = m.metabolites.list_attr(\"id\")\n    )\n    # [2] Stoichiometric Data\n    # Strip the host and virus objective function stoichiometric coefficients\n    hostS   = mFrame[hostID]\n    virusS  = mFrame[virusID]\n    # Record only non zero values\n    hostSto     = hostS.loc[~(hostS==0)]\n    virusSto    = virusS.loc[~(virusS==0)]\n    # [3] Create output\n    hostSto     = pd.DataFrame(hostSto)\n    virusSto    = pd.DataFrame(virusSto)\n    return (hostSto,virusSto)\n###############################################################################\n\n###############################################################################\n# boundCheck\n# Checks a model for any arbitrarily large bounds, removes these \n# and replaces with infinite bounds\n# Work based upon Kelk et al 2012\n# Kelk, S. M., Olivier, B. G., Stougie, L., & Bruggeman, F. J. (2012). Optimal flux spaces of genome-scale stoichiometric models are determined by a few subnetworks. Scientific Reports, 2, 580. http://doi.org/10.1038/srep00580\n# Inputs:\n# Model         User-supplied model file   [.mat,.xml]\n#\n# Outputs:\n# infModel      Model with bound corrections applied\ndef boundCheck(Model):\n    \"Reaction bound checker\"\n    # [1] Initial Setup\n    # Function Dependencies\n    import numpy    as np\n    # Create pointer\n    altModel = Model\n    # [2] Identify and correct arbitrarily large reaction bounds\n    for ii in range(len(altModel.reactions)):\n        # Temporarily record the lower and upper bounds\n        tmpLb   = altModel.reactions[ii].lower_bound\n        tmpUb   = altModel.reactions[ii].upper_bound\n        # Conditional statement\n        if tmpLb <= -1000:\n            altLb   = -np.inf\n            altModel.reactions[ii].lower_bound = altLb\n        if tmpUb >= 1000:\n            altUb   = np.inf\n            altModel.reactions[ii].upper_bound = altUb\n    # [3] Output model\n    return altModel\n###############################################################################\n# rangeCalculator\n# Calculates , using FVA results for host and virus, the flux range to use in the \n# host-derived enforcement analysis\n# Inputs:\n# hostIdx           Index (model.reactions) for the host-objective reaction\n# virusIdx          Index (model.reactions) for the virus-objective reaction\n# Optional Inputs\n# solver            Declare solver to use for cobrapy: default is cglpk\n# Outputs\n# enfVirus          Vector of virus optima values with additional host-constraint\n# maxEnfBound       Maximum enf bound\n# minEnfBound       Minimum enf bound\ndef rangeCalculator(HVM,hostIdx,virusIdx,solver):\n    \"Enforcement bound creator\"\n    # [1] Initial Setup\n    # Function Dependencies\n    import cobra\n    import numpy    as np\n    import pandas   as pd\n    # Create the virus optima vector\n    enfVirus    = np.zeros((len(HVM.reactions),1))\n    maxEnfBound = np.zeros((len(HVM.reactions),1))\n    minEnfBound = np.zeros((len(HVM.reactions),1))\n    # [2] Perform FVA for each objective\n    # Objective reactions\n    hostObj     = HVM.reactions[hostIdx]\n    virusObj    = HVM.reactions[virusIdx]\n    # Host Optimisation\n    HVM.change_objective(hostObj)\n    # Ensure no flux can go through the virus reaction\n    # Store the bounds\n    virusLb     = HVM.reactions[virusIdx].lower_bound\n    virusUb     = HVM.reactions[virusIdx].upper_bound\n    HVM.reactions[virusIdx].lower_bound = 0\n    HVM.reactions[virusIdx].upper_bound = 0\n    # FVA\n    varHost     = cobra.flux_analysis.flux_variability_analysis(HVM,solver=solver)\n    # Return virus objective bounds\n    HVM.reactions[virusIdx].lower_bound = virusLb\n    HVM.reactions[virusIdx].upper_bound = virusUb\n    # Virus Optimisation\n    HVM.change_objective(virusObj)\n    # Ensure no flux can go through the host reaction\n    # Store the bounds\n    hostLb      = HVM.reactions[hostIdx].lower_bound\n    hostUb      = HVM.reactions[hostIdx].upper_bound\n    HVM.reactions[hostIdx].lower_bound = 0\n    HVM.reactions[hostIdx].upper_bound = 0\n    # FVA\n    varVirus    = cobra.flux_analysis.flux_variability_analysis(HVM,solver=solver)\n    # Return host objective bounds\n    HVM.reactions[hostIdx].lower_bound = hostLb\n    HVM.reactions[hostIdx].upper_bound = hostUb\n    # Create data frames\n    hostFVA     = pd.DataFrame.from_dict(varHost)\n    hostFVA     = hostFVA.transpose()\n    virusFVA    = pd.DataFrame.from_dict(varVirus)\n    virusFVA    = virusFVA.transpose()\n    # [3] Condition statements to determine the calculation and FVA steps    \n    # Initiate loop\n    for ii in range(len(HVM.reactions)):\n        # Create temporary host and virus max|min variables\n        hostMax     = varHost[HVM.reactions[ii].id]['maximum']\n        hostMin     = varHost[HVM.reactions[ii].id]['minimum']\n        virusMax    = varVirus[HVM.reactions[ii].id]['maximum']\n        virusMin    = varVirus[HVM.reactions[ii].id]['minimum']\n        # Record the upper and lower bounds\n        tmpLb       = HVM.reactions[ii].lower_bound\n        tmpUb       = HVM.reactions[ii].upper_bound\n        # Conditional: H+ > V+ && H- < V-\n        if (hostMax > virusMax) and (hostMin < virusMin):\n            #####################################################################\n            # Calculation of bounds for condition [1]\n            enfMax1 = hostMax\n            enfMin1 = (hostMax - ((hostMax - virusMax) / 2))\n            # Apply bounds to reaction\n            HVM.reactions[ii].lower_bound   = enfMin1\n            HVM.reactions[ii].upper_bound   = enfMax1\n            # Zero-bound host\n            HVM.reactions[hostIdx].lower_bound = 0\n            HVM.reactions[hostIdx].upper_bound = 0\n            # Optimize for virus\n            HVM.change_objective(virusObj)\n            sol = HVM.optimize(objective_sense='maximize',solver=solver)\n            # Record the optima\n            zMax    = sol.f\n            # Return host bounds to original\n            HVM.reactions[hostIdx].lower_bound = hostLb\n            HVM.reactions[hostIdx].upper_bound = hostUb\n            # Return reaction bounds to original\n            HVM.reactions[ii].lower_bound   = tmpLb\n            HVM.reactions[ii].upper_bound   = tmpUb\n            # Calculation of bounds for condition [2]\n            enfMin2 = hostMin\n            enfMax2 = (hostMin - ((hostMin - virusMin) / 2))\n            # Apply bounds to reaction\n            HVM.reactions[ii].lower_bound   = enfMin2\n            HVM.reactions[ii].upper_bound   = enfMax2\n            # Zero-bound host\n            HVM.reactions[hostIdx].lower_bound = 0\n            HVM.reactions[hostIdx].upper_bound = 0\n            # Optimize for virus\n            HVM.change_objective(virusObj)\n            sol = HVM.optimize(objective_sense='maximize',solver=solver)\n            # Record the optima\n            zMin    = sol.f\n            # Return host bounds to original\n            HVM.reactions[hostIdx].lower_bound = hostLb\n            HVM.reactions[hostIdx].upper_bound = hostUb\n            # Return reaction bounds to original\n            HVM.reactions[ii].lower_bound   = tmpLb\n            HVM.reactions[ii].upper_bound   = tmpUb\n            # COMPARISON #\n            # Compare zMax and zMin to find which is smallest\n            if zMax < zMin:\n                enfVirus[ii] = zMax\n                # Record the bound\n                maxEnfBound[ii] = enfMax1\n                minEnfBound[ii] = enfMin1\n            elif zMin < zMax:\n                enfVirus[ii] = zMin\n                # Record the bound\n                maxEnfBound[ii] = enfMax2\n                minEnfBound[ii] = enfMin2\n            else:\n                enfVirus[ii] = zMax\n                # Record the bound\n                maxEnfBound[ii] = enfMax1\n                minEnfBound[ii] = enfMin1\n        # Conditional: H+ > V+\n        else:\n            if hostMax > virusMax:\n                #####################################################################\n                # Calculation of bounds\n                enfMax  = hostMax\n                enfMin  = (hostMax - ((hostMax - virusMax) / 2))\n                # Apply bounds to reaction\n                HVM.reactions[ii].lower_bound   = enfMin\n                HVM.reactions[ii].upper_bound   = enfMax\n                # Zero-bound host\n                HVM.reactions[hostIdx].lower_bound = 0\n                HVM.reactions[hostIdx].upper_bound = 0\n                # Optimize for virus\n                HVM.change_objective(virusObj)\n                sol = HVM.optimize(objective_sense='maximize',solver=solver)\n                # Record the optima\n                enfVirus[ii]    = sol.f\n                # Return host bounds to original\n                HVM.reactions[hostIdx].lower_bound = hostLb\n                HVM.reactions[hostIdx].upper_bound = hostUb\n                # Return reaction bounds to original\n                HVM.reactions[ii].lower_bound   = tmpLb\n                HVM.reactions[ii].upper_bound   = tmpUb\n                # Record the bound\n                maxEnfBound[ii] = enfMax\n                minEnfBound[ii] = enfMin\n                #####################################################################\n            else:\n                # Conditional: H- < V-\n                if hostMin < virusMin:\n                    #####################################################################\n                    enfMin  = hostMin\n                    enfMax  = (hostMin - ((hostMin - virusMin) / 2))\n                    # Apply bounds to reaction\n                    HVM.reactions[ii].lower_bound   = enfMin\n                    HVM.reactions[ii].upper_bound   = enfMax\n                    # Zero-bound host\n                    HVM.reactions[hostIdx].lower_bound = 0\n                    HVM.reactions[hostIdx].upper_bound = 0\n                    # Optimize for virus\n                    HVM.change_objective(virusObj)\n                    sol = HVM.optimize(objective_sense='maximize',solver=solver)\n                    # Record the optima\n                    enfVirus[ii]    = sol.f\n                    # Return host bounds to original\n                    HVM.reactions[hostIdx].lower_bound = hostLb\n                    HVM.reactions[hostIdx].upper_bound = hostUb\n                    # Return reaction bounds to original\n                    HVM.reactions[ii].lower_bound   = tmpLb\n                    HVM.reactions[ii].upper_bound   = tmpUb\n                    # Record the bound\n                    maxEnfBound[ii] = enfMax\n                    minEnfBound[ii] = enfMin\n                    #####################################################################\n                else:\n                    #####################################################################\n                    enfMax  = hostMax\n                    enfMin  = hostMin\n                    # Apply bounds to reaction\n                    HVM.reactions[ii].lower_bound   = enfMin\n                    HVM.reactions[ii].upper_bound   = enfMax\n                    # Zero-bound host\n                    HVM.reactions[hostIdx].lower_bound = 0\n                    HVM.reactions[hostIdx].upper_bound = 0\n                    # Optimize for virus\n                    HVM.change_objective(virusObj)\n                    sol = HVM.optimize(objective_sense='maximize',solver=solver)\n                    # Record the optima\n                    enfVirus[ii]    = sol.f\n                    # Return host bounds to original\n                    HVM.reactions[hostIdx].lower_bound = hostLb\n                    HVM.reactions[hostIdx].upper_bound = hostUb\n                    # Return reaction bounds to original\n                    HVM.reactions[ii].lower_bound   = tmpLb\n                    HVM.reactions[ii].upper_bound   = tmpUb\n                    # Record the bound\n                    maxEnfBound[ii] = enfMax\n                    minEnfBound[ii] = enfMin\n                    #####################################################################\n    # [4] Output\n    return (enfVirus,maxEnfBound,minEnfBound)\n###############################################################################", "meta": {"hexsha": "7f17f4a7d5b33f2247fe854bbc97ebf2c68fb9a2", "size": 13680, "ext": "py", "lang": "Python", "max_stars_repo_path": "viranet/tools.py", "max_stars_repo_name": "seanaller/viranet", "max_stars_repo_head_hexsha": "8a8e3f7531110ce5f8dca9df6e9a0b9225ec5604", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "viranet/tools.py", "max_issues_repo_name": "seanaller/viranet", "max_issues_repo_head_hexsha": "8a8e3f7531110ce5f8dca9df6e9a0b9225ec5604", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "viranet/tools.py", "max_forks_repo_name": "seanaller/viranet", "max_forks_repo_head_hexsha": "8a8e3f7531110ce5f8dca9df6e9a0b9225ec5604", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.1485148515, "max_line_length": 226, "alphanum_fraction": 0.543494152, "include": true, "reason": "import numpy", "num_tokens": 3216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19582702163591229}}
{"text": "#!/usr/bin/env python3\n\"\"\"\nGenerate Doppler Centroid product from L0B data\n\"\"\"\nimport os\nimport time\nimport argparse as argp\nimport numpy as np\nfrom datetime import datetime\n\nfrom nisar.workflows import doppler_lut_from_raw\nfrom nisar.workflows.doppler_lut_from_raw import set_logger\nfrom nisar.products.readers.Raw import open_rrsd\nfrom isce3.core import TimeDelta, Linspace\nfrom nisar.products.readers.antenna import AntennaParser\n\n\ndef cmd_line_parser():\n    \"\"\"Parse command line input arguments.\n\n    Notes\n    -----\n    It also allows parsing arguments via an ASCII file\n    by using prefix char \"@\".\n\n    Returns\n    -------\n    argparse.Namespace\n\n    \"\"\"\n    prs = argp.ArgumentParser(\n        description='Estimate Doppler centroid from L0B raw echo and creates '\n        'a 2-D Doppler LUT dumped into a CSV file',\n        fromfile_prefix_chars=\"@\",\n        formatter_class=argp.ArgumentDefaultsHelpFormatter\n    )\n    prs.add_argument('filename_l0b', type=str,\n                     help='Filename of HDF5 L0B product')\n    prs.add_argument('-antenna_file', type=str, dest='antenna_file',\n                     help='Filename of HDF5 Antenna product used to extract '\n                     'averaged azimuth angle for EL cuts of TX + RX pol of '\n                     'first beam. If not provided, the azimuth angle is '\n                     'assumed to be zero!')\n    prs.add_argument('-f', '--freq', type=str, choices=['A', 'B'], default='A',\n                     dest='freq_band', help='Frequency band such as \"A\".')\n    prs.add_argument('-p', '--pol', type=str, dest='txrx_pol',\n                     choices=[\"HH\", \"VV\", \"HV\", \"VH\"],\n                     help='TxRx Polarization such as \"HH\". Default is the '\n                     'first pol in the specified frequency band')\n    prs.add_argument('-r', '--rgb', type=int, dest='num_rgb_avg', default=16,\n                     help='Number of range bins to be averaged in Doppler '\n                     'Estimator block. Shall be equal or larger than 1.')\n    prs.add_argument('-a', '--az_block_dur', type=float, dest='az_block_dur',\n                     default=4.0,\n                     help='Azimuth block duration in seconds defining time-'\n                     'domain correlator length used in Doppler estimator.')\n    prs.add_argument('-t', '--time_interval', type=float, dest='time_interval',\n                     default=2.0,\n                     help='Time stamp interval between azimuth blocks in '\n                     'seconds. Must not be larger than \"az_block_dur\".')\n    prs.add_argument('-m', '--method', type=str, dest='dop_method',\n                     default='CDE', choices=['SDE', 'CDE'],\n                     help='Time-domain Doppler estimator methods \"CDE\"/\"SDE\"'\n                     ' which are Correlator/Sign Doppler Estimator.')\n    prs.add_argument('--subband', action='store_true', dest='subband',\n                     help='Perform fast-time frequency subbanding on top of '\n                     'time-domain correlator in Doppler estimator')\n    prs.add_argument('-d', '--deg', type=int, dest='polyfit_deg',\n                     default=3, help='Degree of the polyfit.')\n    prs.add_argument('--polyfit', action='store_true', dest='polyfit',\n                     help='If set, it will replace actual estimated doppler '\n                     'by its polyfitted ones in slant range.')\n    prs.add_argument('--plot', action='store_true', dest='plot',\n                     help='Plot Doppler centroids and save them in '\n                     '*.png files at the specified output path')\n    prs.add_argument('-o', '--out', type=str, dest='out_path', default='.',\n                     help='Output directory to dump Doppler product as well as'\n                     'PNG plots.')\n\n    return prs.parse_args()\n\n\ndef gen_doppler_range_product(args):\n    \"\"\"Generate Doppler-Range LUT Product.\n\n    It generates Doppler centroid LUT as a function of slant range\n    at various azimuth/pulse times and dump them into a CSV file.\n\n    The format of the file and output filename convention is defined\n    in reference [1]_.\n\n    Parameters\n    ----------\n    args : argparse.Namespace\n        All input arguments parsed from a command line or an ASCII file.\n\n    References\n    ----------\n    .. [1] D. Kannapan, \"D&C Radar Data Product SIS,\" JPL D-104976,\n        December 3, 2020.\n\n    \"\"\"\n    # Const\n    PREFIX_NAME_CSV = 'NISAR_ANC'\n\n    tic = time.time()\n    # set logger\n    logger = set_logger(\"DopplerRangeProduct\")\n\n    # get keyword args for function \"doppler_lut_from_raw\"\n    kwargs = {key: val for key, val in args.__dict__.items() if\n              'file' not in key}\n\n    # get Raw object\n    raw_obj = open_rrsd(args.filename_l0b)\n    # get the SAR band char\n    sar_band_char = raw_obj.sarBand\n    logger.info(f'SAR band char -> {sar_band_char}')\n\n    # operation mode, whether DBF (single or a composite channel) or\n    # 'DM2' (multi-channel)\n    # currently, the nunderlying module simply support DBF or single channel\n    op_mode = 'DBF'\n\n    # generate Doppler LUT2d from Raw L0B\n    dop_lut, ref_utc, mask_rgb, corr_coef, txrx_pol, centerfreq, _ = \\\n        doppler_lut_from_raw(raw_obj, logger=logger, **kwargs)\n\n    # check out antenna file to extract azimuth angle for EL cuts used for\n    # Doppler CSV product\n    if args.antenna_file is None:\n        az_ang_deg = 0.0\n        logger.warning(\n            'No antenna file! Azimuth angle for Doppler product is '\n            'assumed to be zero!'\n        )\n    else:\n        logger.info(\n            'Extracting the azimuth angle of EL cuts from antenna file.')\n        ant_obj = AntennaParser(args.antenna_file)\n\n        ant_tx = ant_obj.el_cut(pol=txrx_pol[0])\n        az_ang = ant_tx.cut_angle\n        # if RX pol is different from TX pol then take average of both\n        if txrx_pol[0] != txrx_pol[1]:\n            ant_rx = ant_obj.el_cut(pol=txrx_pol[1])\n            az_ang += ant_rx.cut_angle\n            az_ang *= 0.5\n        az_ang_deg = np.rad2deg(az_ang)\n        logger.info(\n            'Azimuth angle extracted from antenna file -> '\n            f'{az_ang_deg:.3f} (deg)'\n        )\n\n    # form Linspace object for uniformly-spaced azimuth time and slant range\n    azt_lsp = Linspace(dop_lut.y_start, dop_lut.y_spacing, dop_lut.length)\n    sr_lsp = Linspace(dop_lut.x_start, dop_lut.x_spacing, dop_lut.width)\n\n    # get the first and last utc azimuth time w/o fractional seconds\n    # in \"%Y%m%dT%H%M%S\" format to be used as part of CSV product filename.\n    dt_utc_start = sec2str(ref_utc, azt_lsp.first)\n    dt_utc_stop = sec2str(ref_utc, azt_lsp.last)\n    # get current time w/o fractional seconds in \"%Y%m%dT%H%M%S\" format\n    # used as part of CSV product filename\n    dt_utc_cur = datetime.now().strftime('%Y%m%dT%H%M%S')\n\n    # naming convention of CSV file and product spec is defined in Doc:\n    # See reference [1]\n    name_csv = (f'{PREFIX_NAME_CSV}_{sar_band_char}_{op_mode}_DOPP_'\n                f'{dt_utc_cur}_{dt_utc_start}_{dt_utc_stop}.csv')\n    file_csv = os.path.join(args.out_path, name_csv)\n    logger.info(f'Dump Doppler product in \"CSV\" format to file -> {file_csv}')\n\n    with open(file_csv, 'wt') as fid_csv:\n        fid_csv.write(\n            'UTC Time,Frequency (Hz),Doppler (Hz),Range (m),Azimuth (deg),'\n            'Correlation\\n'\n        )\n        # loop over azimuth time and slant ranges\n        for i_row, azt in enumerate(azt_lsp):\n            tm_utc_str = sec2isofmt(ref_utc, azt)\n\n            for i_col, sr in enumerate(sr_lsp):\n                fid_csv.write(\n                    '{:s},{:.1f},{:.3f},{:.3f},{:.3f},{:.3f}\\n'.format(\n                        tm_utc_str, centerfreq, dop_lut.data[i_row, i_col],\n                        sr, az_ang_deg,\n                        mask_rgb[i_row, i_col] * corr_coef[i_row, i_col])\n                    )\n\n    # total elapsed time\n    logger.info(f'Elapsed time -> {time.time() - tic:.1f} (sec)')\n\n\ndef sec2isofmt(ref_utc: 'isce3.core.DateTime', seconds: float) -> str:\n    \"\"\"seconds to isoformat string\"\"\"\n    return (ref_utc + TimeDelta(seconds)).isoformat()\n\n\ndef sec2str(ref_utc: 'isce3.core.DateTime', seconds: float) -> str:\n    \"\"\"seconds to string format '%Y%m%dT%H%M%S'\"\"\"\n    fmt = '%Y%m%dT%H%M%S'\n    dt_iso = sec2isofmt(ref_utc, seconds)\n    return datetime.fromisoformat(dt_iso.split('.')[0]).strftime(fmt)\n\n\nif __name__ == \"__main__\":\n    \"\"\"Main driver\"\"\"\n    gen_doppler_range_product(cmd_line_parser())\n", "meta": {"hexsha": "f50a217ff700dc3838e7718b04e135879f7e6d23", "size": 8467, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/packages/nisar/workflows/gen_doppler_range_product.py", "max_stars_repo_name": "isce3-testing/isce3-circleci-poc", "max_stars_repo_head_hexsha": "ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/packages/nisar/workflows/gen_doppler_range_product.py", "max_issues_repo_name": "isce3-testing/isce3-circleci-poc", "max_issues_repo_head_hexsha": "ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-23T00:00:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-23T00:00:31.000Z", "max_forks_repo_path": "python/packages/nisar/workflows/gen_doppler_range_product.py", "max_forks_repo_name": "isce3-testing/isce3-circleci-poc", "max_forks_repo_head_hexsha": "ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-02T21:10:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T21:10:11.000Z", "avg_line_length": 40.319047619, "max_line_length": 79, "alphanum_fraction": 0.6147395772, "include": true, "reason": "import numpy", "num_tokens": 2112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.32423541204073586, "lm_q1q2_score": 0.19581608695265326}}
{"text": "#! /usr/bin/env python\n\"\"\"\nMIMAS - The Multi-resolution Image Mask for Depexo Software\n\nTODO: Write an in/out reader for MOC formats described by\nhttp://arxiv.org/abs/1505.02937\n\"\"\"\n\nfrom __future__ import print_function\n\nimport logging\nimport numpy as np\n\nimport os\nimport re\nfrom astropy.coordinates import Angle, SkyCoord\nimport astropy.units as u\nfrom astropy.io import fits as pyfits\nfrom astropy.wcs import wcs as pywcs\nimport healpy as hp\nfrom .regions import Region\nfrom .catalogs import load_table, write_table\n\n__author__ = \"Paul Hancock\"\n__version__ = 'v1.3.1'\n__date__ = '2018-08-29'\n\n\n# globals\nfilewcs = None\n\n\nclass Dummy():\n    \"\"\"\n    A state storage class for MIMAS to work with.\n\n    Attributes\n    ----------\n    add_region : list\n        List of :class:`depexoTools.MIMAS.Region` to be added.\n\n    rem_region : list\n        List of :class:`depexoTools.MIMAS.Region` to be subtracted.\n\n    include_circles : [[ra, dec, radius],...]\n        List of circles to be added to the region, units are degrees.\n\n    exclude_circles : [[ra, dec, radius], ...]\n        List of circles to be subtracted from the region, units are degrees.\n\n    include_polygons : [[ra,dec, ...], ...]\n        List of polygons to be added to the region, units are degrees.\n\n    exclude_polygons : [[ra,dec, ...], ...]\n        List of polygons to be subtracted from the region, units are degrees.\n\n    maxdepth : int\n        Depth or resolution of the region for HEALPix.\n        There are 4*2**maxdepth pixels at the deepest layer.\n        Default = 8.\n\n    galactic: bool\n        If true then all ra/dec coordinates will be interpreted as if they were in galactic\n        lat/lon (degrees)\n    \"\"\"\n    def __init__(self, maxdepth=8):\n        self.add_region = []\n        self.rem_region = []\n        self.include_circles = []\n        self.exclude_circles = []\n        self.include_polygons = []\n        self.exclude_polygons = []\n        self.maxdepth = maxdepth\n        self.galactic = False\n        return\n\n\ndef galactic2fk5(l, b):\n    \"\"\"\n    Convert galactic l/b to fk5 ra/dec\n\n    Parameters\n    ----------\n    l, b : float\n        Galactic coordinates in radians.\n\n    Returns\n    -------\n    ra, dec : float\n        FK5 ecliptic coordinates in radians.\n    \"\"\"\n    a = SkyCoord(l, b, unit=(u.radian, u.radian), frame='galactic')\n    return a.fk5.ra.radian, a.fk5.dec.radian\n\n\ndef mask_plane(data, wcs, region, negate=False):\n    \"\"\"\n    Mask a 2d image (data) such that pixels within 'region' are set to nan.\n\n    Parameters\n    ----------\n    data : 2d-array\n        Image array.\n\n    wcs : astropy.wcs.WCS\n        WCS for the image in question.\n\n    region : :class:`depexoTools.regions.Region`\n        A region within which the image pixels will be masked.\n\n    negate : bool\n        If True then pixels *outside* the region are masked.\n        Default = False.\n\n    Returns\n    -------\n    masked : 2d-array\n        The original array, but masked as required.\n    \"\"\"\n    # create an array but don't set the values (they are random)\n    indexes = np.empty((data.shape[0]*data.shape[1], 2), dtype=int)\n    # since I know exactly what the index array needs to look like i can construct\n    # it faster than list comprehension would allow\n    # we do this only once and then recycle it\n    idx = np.array([(j, 0) for j in range(data.shape[1])])\n    j = data.shape[1]\n    for i in range(data.shape[0]):\n        idx[:, 1] = i\n        indexes[i*j:(i+1)*j] = idx\n\n    # put ALL the pixles into our vectorized functions and minimise our overheads\n    ra, dec = wcs.wcs_pix2world(indexes, 1).transpose()\n    bigmask = region.sky_within(ra, dec, degin=True)\n    if not negate:\n        bigmask = np.bitwise_not(bigmask)\n    # rework our 1d list into a 2d array\n    bigmask = bigmask.reshape(data.shape)\n    # and apply the mask\n    data[bigmask] = np.nan\n    return data\n\n\ndef mask_file(regionfile, infile, outfile, negate=False):\n    \"\"\"\n    Created a masked version of file, using a region.\n\n\n    Parameters\n    ----------\n    regionfile : str\n        A file which can be loaded as a :class:`depexoTools.regions.Region`.\n        The image will be masked according to this region.\n\n    infile : str\n        Input FITS image.\n\n    outfile : str\n        Output FITS image.\n\n    negate :  bool\n        If True then pixels *outside* the region are masked.\n        Default = False.\n\n    See Also\n    --------\n    :func:`depexoTools.MIMAS.mask_plane`\n    \"\"\"\n    # Check that the input file is accessible and then open it\n    if not os.path.exists(infile): raise AssertionError(\"Cannot locate fits file {0}\".format(infile))\n    im = pyfits.open(infile)\n    if not os.path.exists(regionfile): raise AssertionError(\"Cannot locate region file {0}\".format(regionfile))\n    region = Region.load(regionfile)\n    try:\n        wcs = pywcs.WCS(im[0].header, naxis=2)\n    except:  # TODO: figure out what error is being thrown\n        wcs = pywcs.WCS(str(im[0].header), naxis=2)\n\n    if len(im[0].data.shape) > 2:\n        data = np.squeeze(im[0].data)\n    else:\n        data = im[0].data\n\n    print(data.shape)\n    if len(data.shape) == 3:\n        for plane in range(data.shape[0]):\n            mask_plane(data[plane], wcs, region, negate)\n    else:\n        mask_plane(data, wcs, region, negate)\n    im[0].data = data\n    im.writeto(outfile, overwrite=True)\n    logging.info(\"Wrote {0}\".format(outfile))\n    return\n\n\ndef mask_table(region, table, negate=False, racol='ra', deccol='dec'):\n    \"\"\"\n    Apply a given mask (region) to the table, removing all the rows with ra/dec inside the region\n    If negate=False then remove the rows with ra/dec outside the region.\n\n\n    Parameters\n    ----------\n    region : :class:`depexoTools.regions.Region`\n        Region to mask.\n\n    table : Astropy.table.Table\n        Table to be masked.\n\n    negate :  bool\n        If True then pixels *outside* the region are masked.\n        Default = False.\n\n    racol, deccol : str\n        The name of the columns in `table` that should be interpreted as ra and dec.\n        Default = 'ra', 'dec'\n\n    Returns\n    -------\n    masked : Astropy.table.Table\n        A view of the given table which has been masked.\n    \"\"\"\n    inside = region.sky_within(table[racol], table[deccol], degin=True)\n    if not negate:\n        mask = np.bitwise_not(inside)\n    else:\n        mask = inside\n    return table[mask]\n\n\ndef mask_catalog(regionfile, infile, outfile, negate=False, racol='ra', deccol='dec'):\n    \"\"\"\n    Apply a region file as a mask to a catalog, removing all the rows with ra/dec inside the region\n    If negate=False then remove the rows with ra/dec outside the region.\n\n\n    Parameters\n    ----------\n    regionfile : str\n        A file which can be loaded as a :class:`depexoTools.regions.Region`.\n        The catalogue will be masked according to this region.\n\n    infile : str\n        Input catalogue.\n\n    outfile : str\n        Output catalogue.\n\n    negate :  bool\n        If True then pixels *outside* the region are masked.\n        Default = False.\n\n    racol, deccol : str\n        The name of the columns in `table` that should be interpreted as ra and dec.\n        Default = 'ra', 'dec'\n\n    See Also\n    --------\n    :func:`depexoTools.MIMAS.mask_table`\n\n    :func:`depexoTools.catalogs.load_table`\n    \"\"\"\n    logging.info(\"Loading region from {0}\".format(regionfile))\n    region = Region.load(regionfile)\n    logging.info(\"Loading catalog from {0}\".format(infile))\n    table = load_table(infile)\n    masked_table = mask_table(region, table, negate=negate, racol=racol, deccol=deccol)\n    write_table(masked_table, outfile)\n    return\n\n\ndef mim2reg(mimfile, regfile):\n    \"\"\"\n    Convert a MIMAS region (.mim) file into a DS9 region (.reg) file.\n\n    Parameters\n    ----------\n    mimfile : str\n        Input file in MIMAS format.\n\n    regfile : str\n        Output file.\n\n    \"\"\"\n    region = Region.load(mimfile)\n    region.write_reg(regfile)\n    logging.info(\"Converted {0} -> {1}\".format(mimfile, regfile))\n    return\n\n\ndef mim2fits(mimfile, fitsfile):\n    \"\"\"\n    Convert a MIMAS region (.mim) file into a MOC region (.fits) file.\n\n    Parameters\n    ----------\n    mimfile : str\n        Input file in MIMAS format.\n\n    fitsfile : str\n        Output file.\n    \"\"\"\n    region = Region.load(mimfile)\n    region.write_fits(fitsfile, moctool='MIMAS {0}-{1}'.format(__version__, __date__))\n    logging.info(\"Converted {0} -> {1}\".format(mimfile, fitsfile))\n    return\n\n\ndef mask2mim(maskfile, mimfile, threshold=1.0, maxdepth=8):\n    \"\"\"\n    Use a fits file as a mask to create a region file.\n\n    Pixels in mask file that are equal or above the threshold will be included in the reigon,\n    while those that are below the threshold will not.\n\n    Parameters\n    ----------\n    maskfile : str\n        Input file in fits format.\n\n    mimfile : str\n        Output filename\n\n    threshold : float\n        threshold value for separating include/exclude values\n\n    maxdepth : int\n        Maximum depth (resolution) of the healpix pixels\n\n    \"\"\"\n    hdu = pyfits.open(maskfile)\n    wcs = pywcs.WCS(hdu[0].header)\n\n    x, y = np.where(hdu[0].data >= threshold)\n    ra, dec = wcs.all_pix2world(y, x, 0)\n    sky = np.radians(Region.radec2sky(ra, dec))\n    vec = Region.sky2vec(sky)\n    x, y, z = np.transpose(vec)\n    pix = hp.vec2pix(2**maxdepth, x, y, z, nest=True)\n\n    region = Region(maxdepth=maxdepth)\n    region.add_pixels(pix, depth=maxdepth)\n    region._renorm()\n    save_region(region, mimfile)\n    logging.info(\"Converted {0} -> {1}\".format(maskfile, mimfile))\n    return\n\n\ndef box2poly(line):\n    \"\"\"\n    Convert a string that describes a box in ds9 format, into a polygon that is given by the corners of the box\n\n    Parameters\n    ----------\n    line : str\n        A string containing a DS9 region command for a box.\n\n    Returns\n    -------\n    poly : [ra, dec, ...]\n        The corners of the box in clockwise order from top left.\n    \"\"\"\n    words = re.split('[(\\s,)]', line)\n    ra = words[1]\n    dec = words[2]\n    width = words[3]\n    height = words[4]\n    if \":\" in ra:\n        ra = Angle(ra, unit=u.hour)\n    else:\n        ra = Angle(ra, unit=u.degree)\n    dec = Angle(dec, unit=u.degree)\n    width = Angle(float(width[:-1])/2, unit=u.arcsecond)  # strip the \"\n    height = Angle(float(height[:-1])/2, unit=u.arcsecond)  # strip the \"\n    center = SkyCoord(ra, dec)\n    tl = center.ra.degree+width.degree, center.dec.degree+height.degree\n    tr = center.ra.degree-width.degree, center.dec.degree+height.degree\n    bl = center.ra.degree+width.degree, center.dec.degree-height.degree\n    br = center.ra.degree-width.degree, center.dec.degree-height.degree\n    return np.ravel([tl, tr, br, bl]).tolist()\n\n\ndef circle2circle(line):\n    \"\"\"\n    Parse a string that describes a circle in ds9 format.\n\n    Parameters\n    ----------\n    line : str\n        A string containing a DS9 region command for a circle.\n\n    Returns\n    -------\n    circle : [ra, dec, radius]\n        The center and radius of the circle.\n    \"\"\"\n    words = re.split('[(,\\s)]', line)\n    ra = words[1]\n    dec = words[2]\n    radius = words[3][:-1]  # strip the \"\n    if \":\" in ra:\n        ra = Angle(ra, unit=u.hour)\n    else:\n        ra = Angle(ra, unit=u.degree)\n    dec = Angle(dec, unit=u.degree)\n    radius = Angle(radius, unit=u.arcsecond)\n    return [ra.degree, dec.degree, radius.degree]\n\n\ndef poly2poly(line):\n    \"\"\"\n    Parse a string of text containing a DS9 description of a polygon.\n\n    This function works but is not very robust due to the constraints of healpy.\n\n    Parameters\n    ----------\n    line : str\n        A string containing a DS9 region command for a polygon.\n\n    Returns\n    -------\n    poly : [ra, dec, ...]\n        The coordinates of the polygon.\n    \"\"\"\n    words = re.split('[(\\s,)]', line)\n    ras = np.array(words[1::2])\n    decs = np.array(words[2::2])\n    coords = []\n    for ra, dec in zip(ras, decs):\n        if ra.strip() == '' or dec.strip() == '':\n            continue\n        if \":\" in ra:\n            pos = SkyCoord(Angle(ra, unit=u.hour), Angle(dec, unit=u.degree))\n        else:\n            pos = SkyCoord(Angle(ra, unit=u.degree), Angle(dec, unit=u.degree))\n        # only add this point if it is some distance from the previous one\n        coords.extend([pos.ra.degree, pos.dec.degree])\n    return coords\n\n\ndef reg2mim(regfile, mimfile, maxdepth):\n    \"\"\"\n    Parse a DS9 region file and write a MIMAS region (.mim) file.\n\n    Parameters\n    ----------\n    regfile : str\n        DS9 region (.reg) file.\n\n    mimfile : str\n        MIMAS region (.mim) file.\n\n    maxdepth : str\n        Depth/resolution of the region file.\n\n    \"\"\"\n    logging.info(\"Reading regions from {0}\".format(regfile))\n    lines = (l for l in open(regfile, 'r') if not l.startswith('#'))\n    poly = []\n    circles = []\n    for line in lines:\n        if line.startswith('box'):\n            poly.append(box2poly(line))\n        elif line.startswith('circle'):\n            circles.append(circle2circle(line))\n        elif line.startswith('polygon'):\n            logging.warning(\"Polygons break a lot, but I'll try this one anyway.\")\n            poly.append(poly2poly(line))\n        else:\n            logging.warning(\"Not sure what to do with {0}\".format(line[:-1]))\n    container = Dummy(maxdepth=maxdepth)\n    container.include_circles = circles\n    container.include_polygons = poly\n\n    region = combine_regions(container)\n    save_region(region, mimfile)\n    return\n\n\ndef combine_regions(container):\n    \"\"\"\n    Return a region that is the combination of those specified in the container.\n    The container is typically a results instance that comes from argparse.\n\n    Order of construction is: add regions, subtract regions, add circles, subtract circles,\n    add polygons, subtract polygons.\n\n    Parameters\n    ----------\n    container : :class:`depexoTools.MIMAS.Dummy`\n        The regions to be combined.\n\n    Returns\n    -------\n    region : :class:`depexoTools.regions.Region`\n        The constructed region.\n    \"\"\"\n    # create empty region\n    region = Region(container.maxdepth)\n\n    # add/rem all the regions from files\n    for r in container.add_region:\n        logging.info(\"adding region from {0}\".format(r))\n        r2 = Region.load(r[0])\n        region.union(r2)\n\n    for r in container.rem_region:\n        logging.info(\"removing region from {0}\".format(r))\n        r2 = Region.load(r[0])\n        region.without(r2)\n\n\n    # add circles\n    if len(container.include_circles) > 0:\n        for c in container.include_circles:\n            circles = np.radians(np.array(c))\n            if container.galactic:\n                l, b, radii = circles.reshape(3, circles.shape[0]//3)\n                ras, decs = galactic2fk5(l, b)\n            else:\n                ras, decs, radii = circles.reshape(3, circles.shape[0]//3)\n            region.add_circles(ras, decs, radii)\n\n    # remove circles\n    if len(container.exclude_circles) > 0:\n        for c in container.exclude_circles:\n            r2 = Region(container.maxdepth)\n            circles = np.radians(np.array(c))\n            if container.galactic:\n                l, b, radii = circles.reshape(3, circles.shape[0]//3)\n                ras, decs = galactic2fk5(l, b)\n            else:\n                ras, decs, radii = circles.reshape(3, circles.shape[0]//3)\n            r2.add_circles(ras, decs, radii)\n            region.without(r2)\n\n    # add polygons\n    if len(container.include_polygons) > 0:\n        for p in container.include_polygons:\n            poly = np.radians(np.array(p))\n            poly = poly.reshape((poly.shape[0]//2, 2))\n            region.add_poly(poly)\n\n    # remove polygons\n    if len(container.exclude_polygons) > 0:\n        for p in container.include_polygons:\n            poly = np.array(np.radians(p))\n            r2 = Region(container.maxdepth)\n            r2.add_poly(poly)\n            region.without(r2)\n\n    return region\n\n\ndef intersect_regions(flist):\n    \"\"\"\n    Construct a region which is the intersection of all regions described in the given\n    list of file names.\n\n    Parameters\n    ----------\n    flist : list\n        A list of region filenames.\n\n    Returns\n    -------\n    region : :class:`depexoTools.regions.Region`\n        The intersection of all regions, possibly empty.\n    \"\"\"\n    if len(flist) < 2:\n        raise Exception(\"Require at least two regions to perform intersection\")\n    a = Region.load(flist[0])\n    for b in [Region.load(f) for f in flist[1:]]:\n        a.intersect(b)\n    return a\n\n\ndef save_region(region, filename):\n    \"\"\"\n    Save the given region to a file\n\n    Parameters\n    ----------\n    region : :class:`depexoTools.regions.Region`\n        A region.\n\n    filename : str\n        Output file name.\n    \"\"\"\n    region.save(filename)\n    logging.info(\"Wrote {0}\".format(filename))\n    return\n\n\ndef save_as_image(region, filename):\n    \"\"\"\n    Convert a MIMAS region (.mim) file into a image (eg .png)\n\n    Parameters\n    ----------\n    region : :class:`depexoTools.regions.Region`\n        Region of interest.\n\n    filename : str\n        Output filename.\n    \"\"\"\n    import healpy as hp\n    pixels = list(region.get_demoted())\n    order = region.maxdepth\n    m = np.arange(hp.nside2npix(2**order))\n    m[:] = 0\n    m[pixels] = 1\n    hp.write_map(filename, m, nest=True, coord='C')\n    return\n", "meta": {"hexsha": "5773e6b9aa5e7edc037779bd1bd8b56f0e8335ca", "size": 17307, "ext": "py", "lang": "Python", "max_stars_repo_path": "DepexoTools/MIMAS.py", "max_stars_repo_name": "erpmaroc/Depexo-Prestashop-Like", "max_stars_repo_head_hexsha": "53d01dea6fd56c8ef21394f301df51cf699cd4d7", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DepexoTools/MIMAS.py", "max_issues_repo_name": "erpmaroc/Depexo-Prestashop-Like", "max_issues_repo_head_hexsha": "53d01dea6fd56c8ef21394f301df51cf699cd4d7", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DepexoTools/MIMAS.py", "max_forks_repo_name": "erpmaroc/Depexo-Prestashop-Like", "max_forks_repo_head_hexsha": "53d01dea6fd56c8ef21394f301df51cf699cd4d7", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1414634146, "max_line_length": 111, "alphanum_fraction": 0.615589068, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 4389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.32423540551084407, "lm_q1q2_score": 0.1958160783863151}}
{"text": "# Fit to multiple relative binding free energy edges\nimport sys\nfrom argparse import ArgumentParser\nimport jax\nfrom jax import numpy as jnp\nimport numpy as np\nimport datetime\nimport timemachine\n\n# forcefield handlers\nfrom ff import Forcefield\nfrom ff.handlers.serialize import serialize_handlers\nfrom ff.handlers.deserialize import deserialize_handlers\nfrom ff.handlers.nonbonded import AM1CCCHandler, LennardJonesHandler\n\n# free energy classes\nfrom fe.free_energy import RelativeFreeEnergy, construct_lambda_schedule\nfrom fe.estimator import SimulationResult\nfrom fe.model import RBFEModel\nfrom fe.loss import pseudo_huber_loss  # , l1_loss, flat_bottom_loss\n\n# MD initialization\nfrom md import builders\n\n# parallelization across multiple GPUs\nfrom parallel.client import CUDAPoolClient, GRPCClient\nfrom parallel.utils import get_gpu_count\n\nfrom collections import namedtuple\n\nfrom pickle import load\n\nfrom optimize.step import truncated_step\n\nfrom typing import Tuple, Dict, List, Union\n\nfrom pathlib import Path\nfrom time import time\n\narray = Union[np.array, jnp.array]\n\nHandler = Union[AM1CCCHandler, LennardJonesHandler]  # TODO: relax this assumption\n\nNUM_GPUS = get_gpu_count()\n\n# how much MD to run, on how many GPUs\nConfiguration = namedtuple(\n    'Configuration',\n    ['num_complex_windows', 'num_solvent_windows', 'num_equil_steps', 'num_prod_steps'])\n\n# define a couple configurations: one for quick tests, and one for production\nproduction_configuration = Configuration(\n    num_complex_windows=60,\n    num_solvent_windows=60,\n    num_equil_steps=10000,\n    num_prod_steps=100000,\n)\n\nintermediate_configuration = Configuration(\n    num_complex_windows=60,\n    num_solvent_windows=60,\n    num_equil_steps=10000,\n    num_prod_steps=10000,\n)\n\ntesting_configuration = Configuration(\n    num_complex_windows=10,\n    num_solvent_windows=10,\n    num_equil_steps=1000,\n    num_prod_steps=1000,\n)\n\n# TODO: rename this to something more descriptive than \"Configuration\"...\n#   want to distinguish later between an \"RBFE configuration\"\n#       (which describes the computation of a single edge)\n#   and a \"training configuration\"\n#       (which describes the overall training loop)\n\n\n# locations relative to project root\nroot = Path(timemachine.__file__).parent\npath_to_protein = str(root.joinpath('tests/data/hif2a_nowater_min.pdb'))\n\n\nclass ParameterUpdate:\n    def __init__(self, before, after, gradient, update):\n        self.before = before\n        self.after = after\n        self.gradient = gradient\n        self.update = update\n\n    # TODO: def __str__\n\n    def save(self, fname='parameter_update.npz'):\n        \"\"\"save numpy arrays to fname\"\"\"\n        print(f'saving parameter updates to {fname}')\n        np.savez(\n            file=fname,\n            before=self.before,\n            after=self.after,\n            gradient=self.gradient,\n            update=self.update,\n        )\n\n\ndef _save_forcefield(fname, ff_params):\n    with open(fname, 'w') as fh:\n        fh.write(ff_params)\n\n\nif __name__ == \"__main__\":\n    default_output_path = f\"results_{str(datetime.datetime.now())}\"\n    parser = ArgumentParser(description=\"Fit Forcefield parameters to hif2a\")\n    parser.add_argument(\"--num-gpus\", default=None, type=int,\n                        help=f\"Number of GPUs to run against, defaults to {NUM_GPUS} if no hosts provided\")\n    parser.add_argument(\"--hosts\", nargs=\"*\", default=None, help=\"Hosts running GRPC worker to use for compute\")\n    parser.add_argument(\"--param-updates\", default=1000, type=int, help=\"Number of updates for parameters\")\n    parser.add_argument(\"--seed\", default=2021, type=int, help=\"Seed for shuffling ordering of transformations\")\n    parser.add_argument(\"--config\", default=\"intermediate\", choices=[\"intermediate\", \"production\", \"test\"])\n\n    parser.add_argument(\"--path_to_ff\", default=str(root.joinpath('ff/params/smirnoff_1_1_0_ccc.py')))\n    parser.add_argument(\"--path_to_edges\", default=\"relative_transformations.pkl\",\n                        help=\"Path to pickle file containing list of RelativeFreeEnergy objects\")\n    parser.add_argument(\"--output_path\", default=default_output_path, help=\"Path to output directory\")\n    # TODO: also make configurable: forces_to_refit, optimizer params, path_to_protein, path_to_protein_ff, ...\n    args = parser.parse_args()\n\n    # create path if it doesn't exist\n    output_path = Path(args.output_path)\n    output_path.mkdir(parents=True, exist_ok=True)\n    print(f'output path: {output_path}')\n\n    # xor num_gpus and hosts args\n    args = parser.parse_args()\n    if args.num_gpus is not None and args.hosts is not None:\n        print(\"Unable to provide --num-gpus and --hosts together\")\n        sys.exit(1)\n\n    # which force field components we'll refit\n    forces_to_refit = [AM1CCCHandler, LennardJonesHandler]\n\n    # how much computation to spend per refitting step\n    configuration = None\n    if args.config == \"intermediate\":  # goldilocks\n        configuration = intermediate_configuration\n    elif args.config == \"test\":\n        configuration = testing_configuration  # a little\n    elif args.config == \"production\":\n        configuration = production_configuration  # a lot\n    assert configuration is not None, \"No configuration provided\"\n\n    if not args.hosts:\n        num_gpus = args.num_gpus\n        if num_gpus is None:\n            num_gpus = NUM_GPUS\n        # set up multi-GPU client\n        client = CUDAPoolClient(max_workers=num_gpus)\n    else:\n        # Setup GRPC client\n        client = GRPCClient(hosts=args.hosts)\n    client.verify()\n\n    # load and construct forcefield\n    with open(args.path_to_ff) as f:\n        ff_handlers = deserialize_handlers(f.read())\n\n    forcefield = Forcefield(ff_handlers)\n\n    # load pre-defined collection of relative transformations\n    with open(args.path_to_edges, 'rb') as f:\n        relative_transformations: List[RelativeFreeEnergy] = load(f)\n\n    # update the forcefield parameters for a few steps, each step informed by a single free energy calculation\n\n    # compute and save the sequence of relative_transformation indices\n    num_epochs = int(np.ceil(args.param_updates / len(relative_transformations)))\n    np.random.seed(args.seed)\n    step_inds = []\n    for epoch in range(num_epochs):\n        inds = np.arange(len(relative_transformations))\n        np.random.shuffle(inds)\n        step_inds.append(inds)\n    step_inds = np.hstack(step_inds)[:args.param_updates]\n\n    np.save(output_path.joinpath('step_indices.npy'), step_inds)\n\n    # build the complex system\n    complex_system, complex_coords, _, _, complex_box, _ = builders.build_protein_system(\n        path_to_protein)\n    # TODO: optimize box\n    complex_box += np.eye(3) * 0.1  # BFGS this later\n\n    # build the water system\n    solvent_system, solvent_coords, solvent_box, _ = builders.build_water_system(4.0)\n    # TODO: optimize box\n    solvent_box += np.eye(3) * 0.1  # BFGS this later\n\n    # note: \"complex\" means \"protein + solvent\"\n    binding_model = RBFEModel(\n        client=client,\n        ff=forcefield,\n        complex_system=complex_system,\n        complex_coords=complex_coords,\n        complex_box=complex_box,\n        complex_schedule=construct_lambda_schedule(configuration.num_complex_windows),\n        solvent_system=solvent_system,\n        solvent_coords=solvent_coords,\n        solvent_box=solvent_box,\n        solvent_schedule=construct_lambda_schedule(configuration.num_solvent_windows),\n        equil_steps=configuration.num_equil_steps,\n        prod_steps=configuration.num_prod_steps,\n    )\n\n\n    def loss_fxn(ff_params, mol_a, mol_b, core, label_ddG, callback=None):\n        pred_ddG = binding_model.predict(ff_params, mol_a, mol_b, core, callback)\n        return pseudo_huber_loss(pred_ddG - label_ddG)\n\n\n    # TODO: how to get intermediate results from the computational pipeline encapsulated in binding_model.loss ?\n    #   e.g. stage_results, and further diagnostic information\n    #   * x trajectories,\n    #   * d U / d parameters trajectories,\n    #   * matrix of U(x; lambda) for all x, lambda\n    #   * the deltaG pred\n    #   (proper way is probably something like has_aux=True https://jax.readthedocs.io/en/latest/jax.html#jax.value_and_grad)\n\n    ordered_params = forcefield.get_ordered_params()\n    ordered_handles = forcefield.get_ordered_handles()\n\n    handle_types_being_optimized = [AM1CCCHandler, LennardJonesHandler]\n\n\n    # TODO: move flatten into optimize.utils\n    def flatten(params) -> Tuple[np.array, callable]:\n        \"\"\"Turn params dict into flat array, with an accompanying unflatten function\n\n        TODO: note that the result is going to be in the order given by ordered_handles (filtered by presence in handle_types)\n            rather than in the order they appear in handle_types_being_optimized\n\n        TODO: maybe leave out the reference to handle_types_being optimized altogether\n\n        TODO: does Jax have a pytree-based flatten / unflatten utility?\n        \"\"\"\n\n        theta_list = []\n        _shapes = dict()\n        _handle_types = []\n\n        for param, handle in zip(params, ordered_handles):\n            assert handle.params.shape == param.shape\n            key = type(handle)\n\n            if key in handle_types_being_optimized:\n                theta_list.append(param.flatten())\n                _shapes[key] = param.shape\n                _handle_types.append(key)\n\n        theta = np.hstack(theta_list)\n\n        def unflatten(theta: array) -> Dict[Handler, array]:\n            params = dict()\n            i = 0\n            for key in _handle_types:\n                shape = _shapes[key]\n                num_params = int(np.prod(shape))\n                params[key] = np.array(theta[i: i + num_params]).reshape(shape)\n                i += num_params\n            return params\n\n        return theta, unflatten\n\n\n    relative_improvement_bound = 0.8\n\n\n    def _compute_step_lower_bound(loss, blown_up):\n        \"\"\"problem this addresses: on a small fraction of steps, the free energy estimate may be grossly unreliable\n        away from target, typically indicating an instability was encountered.\n        detect if this occurs, and don't allow a step.\n\n        \"\"\"\n        if not blown_up:\n            return loss * relative_improvement_bound\n        else:\n            return loss  # don't move!\n\n\n    def _results_to_arrays(results: List[SimulationResult]):\n        \"\"\"each result object was constructed by SimulationResult(xs=xs, du_dls=full_du_dls, du_dps=grads)\n\n        for each field, concatenate into an array\n        \"\"\"\n\n        xs = np.array([r.xs for r in results])\n        du_dls = np.array([r.du_dls for r in results])\n        du_dps = np.array([r.du_dps for r in results])\n\n        return xs, du_dls, du_dps\n\n\n    def _blew_up(results: List[SimulationResult]):\n        \"\"\"if stddev(du_dls) for any window exceeded 1000 kJ/mol, don't trust result enough to take a step\n        if du_dls contains any nans, don't trust result enough to take a step\"\"\"\n        du_dls = _results_to_arrays(results)[1]\n\n        # TODO: adjust this threshold a bit, move reliability calculations into fe/estimator.py or fe/model.py\n        return np.isnan(du_dls).any() or (du_dls.std(1).max() > 1000)\n\n\n    results_this_step = dict()  # {stage : result} pairs # TODO: proper type hint\n\n\n    def save_in_memory_callback(results, stage):\n        global results_this_step\n        results_this_step[stage] = results\n        print(f'collected {stage} results!')\n\n\n    # in each optimizer step, look at one transformation from relative_transformations\n    for step, rfe_ind in enumerate(step_inds):\n        rfe = relative_transformations[rfe_ind]\n\n        # compute a step, measuring total wall-time\n        t0 = time()\n\n        # TODO: perhaps update this to accept an rfe argument, instead of all of rfe's attributes as arguments\n        loss, loss_grads = jax.value_and_grad(loss_fxn, argnums=0)(ordered_params, rfe.mol_a, rfe.mol_b, rfe.core,\n                                                                   rfe.label, callback=save_in_memory_callback)\n        print(f\"at optimizer step {step}, loss={loss:.3f}\")\n\n        # check if it's probably okay to take an optimizer step on the basis of this result\n        # TODO: move responsibility for returning error flags / simulation uncertainty estimates further upstream\n        blown_up = _blew_up(results_this_step['complex']) or _blew_up(results_this_step['solvent'])\n\n        # note: unflatten_grad and unflatten_theta have identical definitions for now\n        flat_loss_grad, unflatten_grad = flatten(loss_grads)\n        flat_theta, unflatten_theta = flatten(ordered_params)\n\n        # based on current estimate of (loss, grad, and simulation stability), return a conservative step to take in parameter space\n        theta_increment = truncated_step(flat_theta, loss, flat_loss_grad,\n                                         step_lower_bound=_compute_step_lower_bound(loss, blown_up))\n        param_increments = unflatten_theta(theta_increment)\n\n        # for any parameter handler types being updated, update in place\n        for handle in ordered_handles:\n            handle_type = type(handle)\n            if handle_type in param_increments:\n                print(f'updating {handle_type.__name__}')\n\n                # TODO: careful -- this must be a \"+=\" or \"-=\" not an \"=\"!\n                handle.params += param_increments[handle_type]\n\n                increment = param_increments[handle_type]\n                update_mask = increment != 0\n\n                # TODO: replace with a function that knows what to report about each handle type\n                print(\n                    f'updated {int(np.sum(update_mask))} params by between {np.min(increment[update_mask]):.4f} and {np.max(increment[update_mask])}')\n\n        t1 = time()\n        elapsed = t1 - t0\n\n        print(f'completed forcefield-updating step {step} in {elapsed:.3f} s !')\n\n        # save du_dls snapshot\n        path_to_du_dls = output_path.joinpath(f'du_dls_snapshot_{step}.npz')\n        print(f'saving du_dl trajs to {path_to_du_dls}')\n        du_dls_dict = dict()  # keywords here must be strings\n        for stage, results in results_this_step.items():\n            du_dls_dict[stage] = _results_to_arrays(results)[1]\n        np.savez(path_to_du_dls, **du_dls_dict)\n\n        # also save information about this step's parameter gradient and parameter update\n        # results to npz\n        path_to_npz = output_path.joinpath(f'theta_grad_loss_snapshot_{step}.npz')\n        print(f'saving theta, grad, loss snapshot to {path_to_npz}')\n        np.savez(\n            path_to_npz,\n            theta=np.array(flat_theta),\n            grad=np.array(flat_loss_grad),\n            loss=loss\n        )\n\n        # TODO: same for xs and du_dps snapshots\n\n        # save updated forcefield .py files after every gradient step\n        step_params = serialize_handlers(ff_handlers)\n        # TODO: consider if there's a more modular way to keep track of ff updates\n        _save_forcefield(output_path.joinpath(\"forcefield_checkpoint_{step}.py\"), ff_params=step_params)\n", "meta": {"hexsha": "fa7f2846e848bb0d7bf5c60792c572cea3dad4d8", "size": 15077, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/hif2a/fit_to_multiple_rbfes.py", "max_stars_repo_name": "fehomi/timemachine", "max_stars_repo_head_hexsha": "594b10c03a6688c008eb4d35e612dbd98f5eede4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/hif2a/fit_to_multiple_rbfes.py", "max_issues_repo_name": "fehomi/timemachine", "max_issues_repo_head_hexsha": "594b10c03a6688c008eb4d35e612dbd98f5eede4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/hif2a/fit_to_multiple_rbfes.py", "max_forks_repo_name": "fehomi/timemachine", "max_forks_repo_head_hexsha": "594b10c03a6688c008eb4d35e612dbd98f5eede4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5601023018, "max_line_length": 150, "alphanum_fraction": 0.6872056775, "include": true, "reason": "import numpy,import jax,from jax", "num_tokens": 3419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.1958160751218249}}
{"text": "#!/usr/bin/env python\nfrom __future__ import division\nimport numpy as np\nimport pandas as pd\nimport warnings\nfrom .helpers import *\n\ndef analyze_chunk(data, subjgroup=None, subjname='Subject', listgroup=None, listname='List', analysis=None, analysis_type=None, pass_features=False, **kwargs):\n    \"\"\"\n    Private function that groups data by subject/list number and performs analysis for a chunk of data.\n\n    Parameters\n    ----------\n    data : Egg data object\n        The data to be analyzed\n\n    subjgroup : list of strings or ints\n        String/int variables indicating how to group over subjects.  Must be\n        the length of the number of subjects\n\n    subjname : string\n        Name of the subject grouping variable\n\n    listgroup : list of strings or ints\n        String/int variables indicating how to group over list.  Must be\n        the length of the number of lists\n\n    listname : string\n        Name of the list grouping variable\n\n    analysis : function\n        This function analyzes data and returns it.\n\n    pass_features : bool\n        Logical indicating whether the analyses uses the features field of the Egg\n\n    Returns\n    ----------\n    analyzed_data : Pandas DataFrame\n        DataFrame containing the analysis results\n\n    \"\"\"\n    # if no grouping, set default to iterate over each list independently\n    subjgroup = subjgroup if subjgroup else data.pres.index.levels[0].values\n    listgroup = listgroup if listgroup else data.pres.index.levels[1].values\n\n    # create a dictionary for grouping\n    subjdict = {subj : data.pres.index.levels[0].values[subj==np.array(subjgroup)] for subj in set(subjgroup)}\n    # listdict = {lst : data.pres.index.levels[1].values[lst==np.array(listgroup)] for lst in set(listgroup)}\n\n    # allow for lists of listgroup arguments\n    if all(isinstance(el, list) for el in listgroup):\n        listdict = [{lst : data.pres.index.levels[1].values[lst==np.array(listgrpsub)] for lst in set(listgrpsub)} for listgrpsub in listgroup]\n    else:\n        listdict = [{lst : data.pres.index.levels[1].values[lst==np.array(listgroup)] for lst in set(listgroup)} for subj in subjdict]\n\n    # perform the analysis\n    def perform_analysis(subj, lst):\n\n        # get data slice for presentation and recall\n        pres_slice = data.pres.loc[[(s,l) for s in subjdict[subj] for l in listdict[subj][lst] if all(~pd.isnull(data.pres.loc[(s,l)]))]]\n        pres_slice.list_length = data.list_length\n\n        rec_slice = data.rec.loc[[(s,l) for s in subjdict[subj] for l in listdict[subj][lst] if all(~pd.isnull(data.pres.loc[(s,l)]))]]\n\n        # if features are need for analysis, get the features for this slice of data\n        if pass_features:\n            feature_slice = data.features.loc[[(s,l) for s in subjdict[subj] for l in listdict[subj][lst] if all(~pd.isnull(data.pres.loc[(s,l)]))]]\n\n        # generate indices\n        index = pd.MultiIndex.from_arrays([[subj],[lst]], names=[subjname, listname])\n\n        # perform analysis for each data chunk\n        if pass_features:\n            return pd.DataFrame([analysis(pres_slice, rec_slice, feature_slice, data.dist_funcs, **kwargs)], index=index, columns=[feature for feature in feature_slice[0].as_matrix()[0].keys()])\n        else:\n            return pd.DataFrame([analysis(pres_slice, rec_slice, **kwargs)], index=index)\n\n    # create list of chunks to process\n    a=[]\n    b=[]\n    for subj in subjdict:\n        for lst in listdict[0]:\n            a.append(subj)\n            b.append(lst)\n\n    # handle parellel kwarg\n    parallel=kwargs['parallel']\n    del kwargs['parallel']\n\n    # if we're running permutation tests, use multiprocessing\n    if parallel==True:\n        import multiprocessing\n        from pathos.multiprocessing import ProcessingPool as Pool\n        p = Pool(multiprocessing.cpu_count())\n        analyzed_data = p.map(perform_analysis, a, b)\n    else:\n        analyzed_data = [perform_analysis(ai, bi) for ai,bi in zip(a,b)]\n\n    # concatenate slices\n    analyzed_data = pd.concat(analyzed_data)\n\n    analyzed_data.attrs = {\n        'analysis_type' : analysis_type,\n        'list_length' : data.list_length\n    }\n\n    for key in kwargs:\n        analyzed_data.attrs[key] = kwargs[key]\n\n    return analyzed_data\n\n# recall matrix\ndef recall_matrix(presented, recalled):\n    \"\"\"\n    Computes recall matrix given list of presented and list of recalled words\n\n    Parameters\n    ----------\n    presented : list of list of strings\n      presentedWords are the words presented in the experiment, in order, grouped by list\n\n    recalled : list of list of strings\n      recalledWords are the words recalled by the subject, in order, grouped by list\n\n    Returns\n    ----------\n    recall_matrix : list of lists of ints\n      each integer represents the presentation position of the recalled word in a given list in order of recall\n      0s represent recalled words not presented\n      negative ints represent words recalled from previous lists\n\n    \"\"\"\n\n    def recall_pos(pres_list,rec_list):\n        pres_list = list(pres_list)\n        rec_list = list(rec_list)\n        result = np.zeros(len(pres_list)) if len(pres_list)>=len(rec_list) else np.zeros(len(rec_list))\n        result.fill(np.nan)\n        for idx,rec_word in enumerate(rec_list):\n            if rec_word in pres_list:\n                if type(rec_word) is str:\n                    result[idx]=int(pres_list.index(rec_word)+1)\n        return result\n\n    result = []\n    for pres_list, rec_list in zip(presented.values, recalled.values):\n        result.append(recall_pos(pres_list, rec_list))\n    return result\n\ndef compute_distances(pres_list, feature_list, dist_funcs):\n    \"\"\"\n    Compute distances between list words along n feature dimensions\n\n    Parameters\n    ----------\n    pres_list : list\n        list of presented words\n    feature_list : list\n        list of feature dicts for presented words\n    dist_funcs : dict\n        dict of distance functions for each feature\n\n    Returns\n    ----------\n    distances : dict\n        dict of distance matrices for each feature\n    \"\"\"\n\n    # initialize dist dict\n    distances = {}\n\n    # for each feature in dist_funcs\n    for feature in dist_funcs:\n\n        # initialize dist matrix\n        dists = np.zeros((len(pres_list), len(pres_list)))\n\n        # for each word in the list\n        for idx1, item1 in enumerate(pres_list):\n\n            # for each word in the list\n            for idx2, item2 in enumerate(pres_list):\n\n                # compute the distance between word 1 and word 2 along some feature dimension\n                dists[idx1,idx2] = dist_funcs[feature](feature_list[idx1][feature],feature_list[idx2][feature])\n\n        # set that distance matrix to the value of a dict where the feature name is the key\n        distances[feature] = dists\n\n    return distances\n\ndef compute_feature_weights(pres_list, rec_list, feature_list, distances):\n    \"\"\"\n    Compute clustering scores along a set of feature dimensions\n\n    Parameters\n    ----------\n    pres_list : list\n        list of presented words\n    rec_list : list\n        list of recalled words\n    feature_list : list\n        list of feature dicts for presented words\n    distances : dict\n        dict of distance matrices for each feature\n\n    Returns\n    ----------\n    weights : list\n        list of clustering scores for each feature dimension\n    \"\"\"\n\n    # initialize the weights object for just this list\n    weights = {}\n    for feature in feature_list[0]:\n        weights[feature] = []\n\n    # return default list if there is not enough data to compute the fingerprint\n    if len(rec_list) <= 2:\n        print('Not enough recalls to compute fingerprint, returning default fingerprint.. (everything is .5)')\n        for feature in feature_list[0]:\n            weights[feature] = .5\n        return [weights[key] for key in weights]\n\n    # initialize past word list\n    past_words = []\n    past_idxs = []\n\n    # loop over words\n    for i in range(len(rec_list)-1):\n\n        # grab current word\n        c = rec_list[i]\n\n        # grab the next word\n        n = rec_list[i + 1]\n\n        # if both recalled words are in the encoding list and haven't been recalled before\n        if (c in pres_list and n in pres_list) and (c not in past_words and n not in past_words):\n\n            # for each feature\n            for feature in feature_list[0]:\n\n                # get the distance vector for the current word\n                dists = distances[feature][pres_list.index(c),:]\n\n                # distance between current and next word\n                cdist = dists[pres_list.index(n)]\n\n                # filter dists removing the words that have already been recalled\n                dists_filt = np.array([dist for idx, dist in enumerate(dists) if idx not in past_idxs])\n\n                # get indices\n                avg_rank = np.mean(np.where(np.sort(dists_filt)[::-1] == cdist)[0]+1)\n\n                # compute the weight\n                weights[feature].append(avg_rank / len(dists_filt))\n\n            # keep track of what has been recalled already\n            past_idxs.append(pres_list.index(c))\n            past_words.append(c)\n\n    # average over the cluster scores for a particular dimension\n    for feature in weights:\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n            weights[feature] = np.nanmean(weights[feature])\n\n    return [weights[key] for key in weights]\n\n# def single_perm(p, r, f, distances):\n#     r_real = compute_feature_weights(p, r, f, distances)\n#     perm = list(np.random.permutation(r))\n#     r_perm = compute_feature_weights(p, perm, f, distances)\n#     return [feature_perm < r_real[idx] for idx, feature_perm in enumerate(r_perm)]\n#\n# def permute_fingerprint_parallel(p, r, f, distances, n_perms=100):\n#\n#     executor = concurrent.futures.ThreadPoolExecutor(10)\n#     futures = [executor.submit(single_perm, p, r, f, distances) for perm in range(n_perms)]\n#     concurrent.futures.wait(futures)\n#\n#     results = [perm.result() for perm in futures]\n#\n#     print(np.sum(np.array(results), axis=0) / n_perms)\n#\n#     return np.sum(np.array(results), axis=0) / n_perms\n\ndef permute_fingerprint_serial(p, r, f, distances, n_perms=100):\n\n    r_perms = []\n    r_real = compute_feature_weights(p, r, f, distances)\n\n    for iperm in range(n_perms):\n        r_perm = list(np.random.permutation(r))\n        r_perms.append(compute_feature_weights(p, r_perm, f, distances))\n\n    r_perms_bool = []\n    for perm in r_perms:\n        r_perm_bool = []\n        for idx, feature_perm in enumerate(perm):\n            r_perm_bool.append(feature_perm < r_real[idx])\n        r_perms_bool.append(r_perm_bool)\n\n    return np.sum(np.array(r_perms_bool), axis=0) / n_perms\n\n# accuracy analysis\ndef accuracy_helper(pres_slice, rec_slice):\n    \"\"\"\n    Computes proportion of words recalled\n\n    Parameters\n    ----------\n    pres_slice : Pandas Dataframe\n        chunk of presentation data to be analyzed\n    rec_slice : Pandas Dataframe\n        chunk of recall data to be analyzed\n\n    Returns\n    ----------\n    prop_recalled : numpy array\n      proportion of words recalled\n\n    \"\"\"\n\n    # compute recall_matrix for data slice\n    recall = recall_matrix(pres_slice, rec_slice)\n\n    # simple function that returns 1 if item encoded in position n is in recall list\n    def compute_acc(lst):\n        return len([i for i in np.unique(lst) if i>0])/(pres_slice.list_length)\n\n    # get spc for each row in recall matrix\n    acc_matrix = [compute_acc(lst) for lst in recall]\n\n    # average over rows\n    prop_recalled = np.mean(acc_matrix,axis=0)\n\n    return prop_recalled\n\n# serial position curve\ndef spc_helper(pres_slice, rec_slice):\n    \"\"\"\n    Computes probability of a word being recalled (in the appropriate recall list), given its presentation position\n\n    Parameters\n    ----------\n    pres_slice : Pandas Dataframe\n        chunk of presentation data to be analyzed\n    rec_slice : Pandas Dataframe\n        chunk of recall data to be analyzed\n\n    Returns\n    ----------\n    prop_recalled : numpy array\n      each number represents the probability of recall for a word presented in given position/index\n\n    \"\"\"\n\n    # compute recall_matrix for data slice\n    recall = recall_matrix(pres_slice, rec_slice)\n\n    # get spc for each row in recall matrix\n    spc_matrix = [[1 if pos in lst else 0 for pos in range(1,len(lst)+1)] for lst in recall]\n\n    # average over rows\n    prop_recalled = np.mean(spc_matrix, axis=0)\n\n    return prop_recalled\n\n# probability of nth recall\ndef pnr_helper(pres_slice, rec_slice, n):\n\n    \"\"\"\n    Computes probability of a word being recalled nth (in the appropriate recall\n    list), given its presentation position.  Note: zero indexed\n\n    Parameters\n    ----------\n    pres_slice : Pandas Dataframe\n        chunk of presentation data to be analyzed\n    rec_slice : Pandas Dataframe\n        chunk of recall data to be analyzed\n\n    Returns\n    ----------\n    prob_recalled : numpy array\n      each number represents the probability of nth recall for a word presented in given position/index\n\n    \"\"\"\n\n    # compute recall_matrix for data slice\n    recall = recall_matrix(pres_slice, rec_slice)\n\n    # simple function that returns 1 if item encoded in position n is recalled first\n    def pos_recalled_first(pos,lst,n):\n        return 1 if pos==lst[n] else 0\n\n    # get pfr for each row in recall matrix\n    pnr_matrix = [[pos_recalled_first(pos,lst,n) for pos in range(1,len(lst)+1)] for lst in recall]\n\n    # average over rows\n    prob_recalled = np.mean(pnr_matrix,axis=0)\n\n    return prob_recalled\n\n# lag-crp\ndef lagcrp_helper(pres_slice, rec_slice):\n    \"\"\"\n    Computes probabilities for each transition distance (probability that a word recalled will be a given distance--in presentation order--from the previous recalled word)\n\n    Parameters\n    ----------\n    pres_slice : Pandas Dataframe\n        chunk of presentation data to be analyzed\n    rec_slice : Pandas Dataframe\n        chunk of recall data to be analyzed\n\n    Returns\n    ----------\n    prob_recalled : numpy array\n      each float is the probability of transition distance (distnaces indexed by position, from -(n-1) to (n-1), excluding zero\n\n    \"\"\"\n\n    # compute recall_matrix for data slice\n    recall = recall_matrix(pres_slice, rec_slice)\n\n    def check_pair(a, b):\n        if (a>0 and b>0) and (a!=b):\n            return True\n        else:\n            return False\n\n    def compute_actual(recall_list, list_length):\n        arr=pd.Series(data=np.zeros((list_length)*2), index=list(range(-list_length,0))+list(range(1,list_length+1)))\n        recalled=[]\n        for trial in range(0,list_length-1):\n            a=recall_list[trial]\n            b=recall_list[trial+1]\n            if check_pair(a, b) and (a not in recalled) and (b not in recalled):\n                arr[b-a]+=1\n            recalled.append(a)\n        return arr\n\n    def compute_possible(recall_list, list_length):\n        arr=pd.Series(data=np.zeros((list_length)*2), index=list(range(-list_length,0))+list(range(1,list_length+1)))\n        recalled=[]\n        for trial in recall_list:\n\n            if np.isnan(trial):\n                pass\n            else:\n\n                low_bound=int(1-trial)\n                up_bound=int(list_length-trial)\n\n                chances=list(range(low_bound,0))+list(range(1,up_bound+1))\n                #ALL transitions\n\n                #remove transitions not possible\n                for each in recalled:\n                    if each-trial in chances:\n                        chances.remove(each-trial)\n\n                #update array with possible transitions\n                arr[chances]+=1\n\n                recalled.append(trial)\n\n        return arr\n\n    ########\n\n    list_crp = []\n    for n_list in recall:\n        actual = compute_actual(n_list, pres_slice.list_length)\n        possible = compute_possible(n_list, pres_slice.list_length)\n        crp = [0.0 if j==0 else i/j for i,j in zip(actual,possible)]\n        crp.insert(int(len(crp)/2),np.nan)\n        list_crp.append(crp)\n\n    prob_recalled = np.mean(list_crp, axis=0)\n\n    return prob_recalled\n\n# temporal clustering analysis\ndef temporal_helper(pres_slice, rec_slice, permute=False, n_perms=1000):\n    \"\"\"\n    Computes temporal clustering score\n\n    Parameters\n    ----------\n    pres_slice : Pandas Dataframe\n        chunk of presentation data to be analyzed\n    rec_slice : Pandas Dataframe\n        chunk of recall data to be analyzed\n\n    Returns\n    ----------\n    score : float\n        a number representing temporal clustering\n\n    \"\"\"\n\n    # initialize temporal clustering list\n    temporal_clustering = []\n\n    # define distance function for temporal clustering\n    dist_funcs = {\n        'temporal' : lambda a, b : np.abs(a-b)\n    }\n\n    # define features (just positions for temporal clustering)\n    f = [{'temporal' : i} for i in range(pres_slice.list_length+1)]\n\n    # loop over lists\n    for p, r in zip(pres_slice.as_matrix(), rec_slice.as_matrix()):\n\n        # turn arrays into lists\n        p = list(p)\n        r = list(filter(lambda ri: isinstance(ri, str), list(r)))\n\n        if len(r)>1:\n\n            # compute distances\n            distances = compute_distances(p, f, dist_funcs)\n\n            # add optional bootstrapping\n            if permute:\n                temporal_clustering.append(permute_fingerprint_serial(p, r, f, distances, n_perms=n_perms))\n            else:\n                temporal_clustering.append(compute_feature_weights(p, r, f, distances))\n        else:\n            temporal_clustering.append([np.nan]*len(f[0].keys()))\n\n    # return average over rows\n    return np.nanmean(temporal_clustering, axis=0)\n\n# fingerprint analysis\ndef fingerprint_helper(pres_slice, rec_slice, feature_slice, dist_funcs, permute=False, n_perms=1000):\n    \"\"\"\n    Computes clustering along a set of feature dimensions\n\n    Parameters\n    ----------\n    pres_slice : Pandas Dataframe\n        chunk of presentation data to be analyzed\n    rec_slice : Pandas Dataframe\n        chunk of recall data to be analyzed\n    feature_slice : Pandas Dataframe\n        chunk of features data to be analyzed\n    dist_funcs : dict\n        Dictionary of distance functions for feature clustering analyses\n\n    Returns\n    ----------\n    probabilities : numpy array\n      each number represents clustering along a different feature dimension\n\n    \"\"\"\n    import time\n\n    # compute fingerprint for each list within a chunk\n    fingerprint_matrix = []\n\n    for p, r, f in zip(pres_slice.as_matrix(), rec_slice.as_matrix(), feature_slice.as_matrix()):\n\n        # turn arrays into lists\n        p = list(p)\n        f = list(f)\n        r = list(filter(lambda ri: isinstance(ri, str), list(r)))\n\n        if len(r)>1:\n\n            # compute distances\n            distances = compute_distances(p, f, dist_funcs)\n\n            # add optional bootstrapping\n            if permute:\n                fingerprint_matrix.append(permute_fingerprint_serial(p, r, f, distances, n_perms=n_perms))\n            else:\n                fingerprint_matrix.append(compute_feature_weights(p, r, f, distances))\n        else:\n            fingerprint_matrix.append([np.nan]*len(f[0].keys()))\n\n    # return average over rows\n    return np.mean(fingerprint_matrix, axis=0)\n\n# fingerprint + temporal clustering analysis\ndef fingerprint_temporal_helper(pres_slice, rec_slice, feature_slice, dist_funcs, permute=True, n_perms=1000):\n    \"\"\"\n    Computes clustering along a set of feature dimensions\n\n    Parameters\n    ----------\n    pres_slice : Pandas Dataframe\n        chunk of presentation data to be analyzed\n    rec_slice : Pandas Dataframe\n        chunk of recall data to be analyzed\n    feature_slice : Pandas Dataframe\n        chunk of features data to be analyzed\n    dist_funcs : dict\n        Dictionary of distance functions for feature clustering analyses\n\n    Returns\n    ----------\n    probabilities : numpy array\n      each number represents clustering along a different feature dimension\n\n    \"\"\"\n    # compute fingerprint for each list within a chunk\n    fingerprint_matrix = []\n\n    for p, r, f in zip(pres_slice.as_matrix(), rec_slice.as_matrix(), feature_slice.as_matrix()):\n\n        # turn arrays into lists\n        p = list(p)\n        f = list(f)\n        r = list(filter(lambda ri: isinstance(ri, str), list(r)))\n\n        # add in temporal clustering\n        nf = []\n        for idx, fi in enumerate(f):\n            fi['temporal'] = idx\n            nf.append(fi)\n\n        dist_funcs_copy = dist_funcs.copy()\n        dist_funcs_copy['temporal'] = lambda a, b : np.abs(a-b)\n\n        # if there is at least 1 transition\n        if len(r)>1:\n\n            # compute distances\n            distances = compute_distances(p, nf, dist_funcs_copy)\n\n            # add optional bootstrapping\n            if permute:\n                fingerprint_matrix.append(permute_fingerprint_serial(p, r, nf, distances, n_perms=n_perms))\n            else:\n                fingerprint_matrix.append(compute_feature_weights(p, r, nf, distances))\n        else:\n            fingerprint_matrix.append([np.nan]*len(nf[0].keys()))\n\n    return np.nanmean(fingerprint_matrix, axis=0)\n\n# main analysis function\ndef analyze(data, subjgroup=None, listgroup=None, subjname='Subject',\n            listname='List', analysis=None, n=0, permute=False, n_perms=1000,\n            parallel=False):\n    \"\"\"\n    General analysis function that groups data by subject/list number and performs analysis.\n\n    Parameters\n    ----------\n    data : Egg data object\n        The data to be analyzed\n\n    subjgroup : list of strings or ints\n        String/int variables indicating how to group over subjects.  Must be\n        the length of the number of subjects\n\n    subjname : string\n        Name of the subject grouping variable\n\n    listgroup : list of strings or ints\n        String/int variables indicating how to group over list.  Must be\n        the length of the number of lists\n\n    listname : string\n        Name of the list grouping variable\n\n    analysis : string\n        This is the analysis you want to run.  Can be accuracy, spc, pfr,\n        temporal or fingerprint\n\n    n : int\n        Optional argument for pnr analysis.  Defines encoding position of item\n        to run pnr.  Default is 0, and it is zero indexed\n\n    permute : bool\n        Optional argument for fingerprint/temporal cluster analyses. Determines\n        whether to correct clustering scores by shuffling recall order for each list\n        to create a distribution of clustering scores (for each feature). The\n        \"corrected\" clustering score is the proportion of clustering scores in\n        that random distribution that were lower than the clustering score for\n        the observed recall sequence. Default is False.\n\n    n_perms : int\n        Optional argument for fingerprint/temporal cluster analyses. Number of\n        permutations to run for \"corrected\" clustering scores. Default is 1000 (\n        per recall list).\n\n    parallel : bool\n        Option to use multiprocessing (this can help speed up the permutations\n        tests in the clustering calculations)\n\n    Returns\n    ----------\n    analyzed_data : Pandas DataFrame\n        DataFrame containing the analysis results\n\n    \"\"\"\n\n    # make sure an analysis is specified\n    if analysis is None:\n        raise ValueError('You must pass an analysis type.')\n\n    # check if subject/list grouping variables exist on the egg\n    if hasattr(data, 'subjgroup'):\n        if data.subjgroup is not None:\n            subjgroup = data.subjgroup\n\n    if hasattr(data, 'subjname'):\n        if data.subjname is not None:\n            subjname = data.subjname\n\n    if hasattr(data, 'listgroup'):\n        if data.listgroup is not None:\n            listgroup = data.listgroup\n\n    if hasattr(data, 'listname'):\n        if data.listname is not None:\n            listname = data.listname\n\n    if type(data) != list:\n        data = [data]\n\n    if type(analysis) != list:\n        analysis = [analysis]\n\n    result = [[] for d in range(len(data))]\n\n    for idx,d in enumerate(data):\n        for a in analysis:\n\n            if a is 'accuracy':\n                r = analyze_chunk(d, subjgroup=subjgroup,\n                                  listgroup=listgroup,\n                                  subjname=subjname,\n                                  listname=listname,\n                                  analysis=accuracy_helper,\n                                  analysis_type='accuracy',\n                                  pass_features=False,\n                                  parallel=parallel)\n            elif a is 'spc':\n                r = analyze_chunk(d, subjgroup=subjgroup,\n                                  listgroup=listgroup,\n                                  subjname=subjname,\n                                  listname=listname,\n                                  analysis=spc_helper,\n                                  analysis_type='spc',\n                                  pass_features=False,\n                                  parallel=parallel)\n            elif a is 'pfr':\n                r = analyze_chunk(d, subjgroup=subjgroup,\n                                  listgroup=listgroup,\n                                  subjname=subjname,\n                                  listname=listname,\n                                  analysis=pnr_helper,\n                                  analysis_type='pfr',\n                                  pass_features=False,\n                                  n=0,\n                                  parallel=parallel)\n            elif a is 'pnr':\n                r = analyze_chunk(d, subjgroup=subjgroup,\n                                  listgroup=listgroup,\n                                  subjname=subjname,\n                                  listname=listname,\n                                  analysis=pnr_helper,\n                                  analysis_type='pnr',\n                                  pass_features=False,\n                                  n=n,\n                                  parallel=parallel)\n            elif a is 'lagcrp':\n                r = analyze_chunk(d, subjgroup=subjgroup,\n                                  listgroup=listgroup,\n                                  subjname=subjname,\n                                  listname=listname,\n                                  analysis=lagcrp_helper,\n                                  analysis_type='lagcrp',\n                                  pass_features=False,\n                                  parallel=parallel)\n                # set indices for lagcrp\n                r.columns=range(-int((len(r.columns)-1)/2),int((len(r.columns)-1)/2)+1)\n            elif a is 'fingerprint':\n                r = analyze_chunk(d, subjgroup=subjgroup,\n                                  listgroup=listgroup,\n                                  subjname=subjname,\n                                  listname=listname,\n                                  analysis=fingerprint_helper,\n                                  analysis_type='fingerprint',\n                                  pass_features=True,\n                                  permute=permute,\n                                  n_perms=n_perms,\n                                  parallel=parallel)\n            elif a is 'temporal':\n                r = analyze_chunk(d, subjgroup=subjgroup,\n                                  listgroup=listgroup,\n                                  subjname=subjname,\n                                  listname=listname,\n                                  analysis=temporal_helper,\n                                  analysis_type='temporal',\n                                  permute=permute,\n                                  n_perms=n_perms,\n                                  parallel=parallel)\n            elif a is 'fingerprint_temporal':\n                r = analyze_chunk(d, subjgroup=subjgroup,\n                                  listgroup=listgroup,\n                                  subjname=subjname,\n                                  listname=listname,\n                                  analysis=fingerprint_temporal_helper,\n                                  analysis_type='fingerprint_temporal',\n                                  pass_features=True,\n                                  permute=permute,\n                                  n_perms=n_perms,\n                                  parallel=parallel)\n\n            result[idx].append(r)\n\n    # return analysis result\n    if len(data)>1 and len(analysis)>1:\n        return result\n    elif len(data)>1 and len(analysis)==1:\n        return [item[0] for item in result]\n    elif len(data)==1 and len(analysis)>1:\n        return [item for item in result[0]]\n    else:\n        return result[0][0]\n", "meta": {"hexsha": "b45933c9840ca69f59b90f1ea5ad44248b1ed99f", "size": 28772, "ext": "py", "lang": "Python", "max_stars_repo_path": "build/lib/quail/analysis.py", "max_stars_repo_name": "mkclairhong/quail", "max_stars_repo_head_hexsha": "a6d6502746c853518a670d542222eb5fc2b05542", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-05-30T15:33:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-30T15:33:26.000Z", "max_issues_repo_path": "build/lib/quail/analysis.py", "max_issues_repo_name": "mkclairhong/quail", "max_issues_repo_head_hexsha": "a6d6502746c853518a670d542222eb5fc2b05542", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2018-06-21T13:21:22.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-24T21:20:05.000Z", "max_forks_repo_path": "build/lib/quail/analysis.py", "max_forks_repo_name": "mkclairhong/quail", "max_forks_repo_head_hexsha": "a6d6502746c853518a670d542222eb5fc2b05542", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-06-01T17:39:48.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-01T17:39:48.000Z", "avg_line_length": 34.623345367, "max_line_length": 194, "alphanum_fraction": 0.6048588906, "include": true, "reason": "import numpy", "num_tokens": 6099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.19576866826145334}}
{"text": "from copy import deepcopy\nimport os\nROOT = os.path.dirname(os.path.abspath(__file__)) + '/'\n\nfrom astropy import log as logger\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\nfrom .filter import Filter\n\nfrom .utils.one_filter import OneFilter\nfrom .utils.plot import MakePlots\nfrom .utils.plot_filters import PlotFilters\nfrom .utils.tools import properties, grid_units, get_slices, average_collapse, central_wav\nfrom .utils.units import ConvertUnits\n\n\nclass SyntheticSED(object):\n\n    '''\n    SyntheticSED is part of the FluxCompensator. It converts \n    input_arrays (e. g. HYPERION ModelOutput) to \"realistic\" synthetic observations. \n    It contains attributes like ModelOutput (see Notes).\n    If input_array is already a SyntheticSED object, the attributes are\n    passed. If input_array is not a SyntheticSED object, SyntheticSED\n    specific attributes are defined and then passed. \n    \n    \n    Parameters\n    ----------\n    \n    input_array : SyntheticSED, ModelOutput (get_sed), optional\n        input_array also reads arrays with ModelOutput like properties.        \n    \n    unit_out : str, optional\n        The output units for SyntheticSED val. Valid options are:\n\n            * ``'ergs/cm^2/s'``\n            * ``'ergs/cm^2/s/Hz'``\n            * ``'Jy'``\n            * ``'mJy'``\n            * ``'MJy/sr'``\n        \n        The default is ``'ergs/cm^2/s'``.\n        \n    name : str\n        The name of the FluxCompensator object until another\n        input_array is called. The default is ``None``.\n        \n    \n    Attributes\n    ----------\n    \n    wav : numpy.ndarray\n        The wavelengths of the val vector entries in microns.\n    \n    val : numpy.ndarray\n        The 1D vector with shape like wav.\n        \n    units : str\n        Current units of the val vector.\n        \n    distance : str\n        Distance to the observed object in cm.\n        \n    x_min : float \n        Physical offset from axis origin in FOV in cm.\n        \n    x_max : float \n        Physical offset from axis origin in FOV in cm.\n    \n    y_min : float\n        Physical offset from axis origin in FOV in cm.\n    \n    y_max : float \n        Physical offset from axis origin in FOV in cm.\n    \n    lon_min : float\n        Minimal longitudinal angle.\n        \n    lon_max : float\n        Maximal longitudinal angle.\n        \n    lat_min : float\n        Minimal latitudinal angle.\n        \n    lat_max : float\n        Maximal latitudinal angle.\n    \n    pix_area_sr : float\n        Pixel area per sr.\n        \n    ap_min : float\n        Minimal aperture.\n    \n    ap_max : float\n        Maximal aperture.\n    \n    \n    Notes\n    -----\n    unit_in : str\n        Unit of val in input_array. Valid options are:\n        \n            * ``'ergs/cm^2/s'``\n            * ``'ergs/cm^2/s/Hz'``\n            * ``'Jy'``\n            * ``'mJy'``\n            * ``'MJy/sr'``\n        \n    grid_unit : float\n        Physical unit of FOV axis in cm. Valid options are:\n        \n            * ``au`` in cm\n            * ``pc`` in cm\n            * ``kpc`` in cm\n    \n    grid_unit_name\n        Astronomical unit of FOV axis. Valid options are:\n    \n            * ``'au'``\n            * ``'pc'``\n            * ``'kpc'``\n            \n    FOV : tuple\n        Tuple ``FOV(x,y)`` of Field of View pixel entries.\n        \n            * pixel in x direction: ``FOV[0]``\n            * pixel in y direction: ``FOV[1]``\n        \n    name : str\n        The name of the FluxCompensator object until another  \n        input_array is called. The default is ``None``.\n    \n    stage : str\n        Gives current operation stage of SyntheticSED.\n        E. g. ``'SyntheticSED: convolve_filter'``\n        \n    log : list\n         List of strings of the previous and current stages.\n        \n    filter : dict\n        Dictionary ``filter = {name, waf_0, waf_min, waf_max}`` \n        of the applied filter. \n        \n            * name of filter:     ``filter['name']``\n            * central wavelength: ``filter['waf_0']``\n            * minimal wavelength:  ``filter['waf_min']``\n            * maximal wavelength: ``filter['waf_max']``\n     \n    Returns\n    -------\n    \n    sed : SyntheticSED\n        1D val array (collapsed rough SED) with SyntheticSED properties.\n        \n    flux : SyntheticFlux\n        0D val array (scalar) with SyntheticFlux properties.\n    '''\n\n    def __init__(self, input_array, unit_out='ergs/cm^2/s', name=None):\n\n        # Hyperion ModelOutput attributes (image and sed)\n        if input_array.val.ndim == 2 and input_array.val[:, 0].ndim == 1:\n            self.val = np.array(input_array.val[0, :])\n        else:\n            self.val = np.array(deepcopy(input_array.val))\n\n        self.wav = np.array(deepcopy(input_array.wav))\n        self.units = input_array.units\n        self.distance = input_array.distance\n\n        # Hyperion Image\n        try:\n            self.x_max = input_array.x_max\n            self.x_max = input_array.x_max\n            self.x_min = input_array.x_min\n            self.y_max = input_array.y_max\n            self.y_min = input_array.y_min\n            self.lon_min = input_array.lon_min\n            self.lon_max = input_array.lon_max\n            self.lat_min = input_array.lat_min\n            self.lat_max = input_array.lat_max\n            self.pix_area_sr = input_array.pix_area_sr\n            # switch\n            self.hyperion_cube = True\n\n        except AttributeError:\n            self.x_max = None\n            self.x_max = None\n            self.x_min = None\n            self.y_max = None\n            self.y_min = None\n            self.lon_min = None\n            self.lon_max = None\n            self.lat_min = None\n            self.lat_max = None\n            self.pix_area_sr = None\n            # switch\n            self.hyperion_cube = None\n\n        # Hyperion SED\n        try:\n            self.ap_min = input_array.ap_min\n            self.ap_max = input_array.ap_max\n            # switch\n            self.hyperion_sed = True\n\n        except AttributeError:\n            self.ap_min = None\n            self.ap_max = None\n            # switch\n            self.hyperion_sed = None\n\n        ##################\n        # new attributes #\n        ##################\n\n        from .cube import SyntheticCube\n\n        if isinstance(input_array, SyntheticSED) or isinstance(input_array, SyntheticCube):\n            # attributes with are passed, since input_array is SyntheticSED or SyntheticCube\n\n            # physical values\n            self.unit_in = input_array.unit_in\n            self.unit_out = input_array.unit_out\n\n            if self.x_max is not None:\n                self.grid_unit = grid_units(self.x_max - self.x_min)['grid_unit']\n                self.grid_unit_name = grid_units(self.x_max - self.x_min)['grid_unit_name']\n            else:\n                self.grid_unit = None\n                self.grid_unit_name = None\n\n            # properties of cube\n            self.FOV = deepcopy(input_array.FOV)\n\n            # name\n            self.name = input_array.name\n            self.stage = input_array.stage\n            self.log = deepcopy(input_array.log)\n\n            # filter\n            self.filter = deepcopy(input_array.filter)\n\n        elif not isinstance(input_array, SyntheticSED) and not isinstance(input_array, SyntheticCube) and self.hyperion_sed is True:\n            # attributes with are defined, since input_array is NOT SyntheticSED or SyntheticCube but HyperionSED\n            self.unit_in = input_array.units\n            self.unit_out = unit_out\n\n            self.grid_unit = None\n            self.grid_unit_name = None\n\n            self.FOV = None\n\n            # name\n            self.name = name\n            self.stage = 'SyntheticSED:  initial'\n            self.log = [self.stage]\n\n            # filter\n            self.filter = {'name': None, 'waf_0': None, 'waf_min': None, 'waf_max': None}\n\n            # convert into val units into unit_out\n            if self.unit_in == 'MJy/sr' or self.unit_out == 'MJy/sr' or self.unit_in == 'Jy/arcsec^2' or self.unit_out == 'Jy/arcsec^2':\n                raise Exception('WARNING: Input or Output units needs to differ from MJy/sr if Input_array is not SyntheticCube or SyntheticSED or HyperionCube')\n\n            s = ConvertUnits(wav=self.wav, val=self.val)\n            self.val = s.get_unit(in_units=self.unit_in, out_units=self.unit_out)\n\n            self.units = self.unit_out\n\n        else:   # attributes with are defined, since input_array is NOT SyntheticSED or SyntheticCube or HyperionOutput\n            # physical values\n            self.unit_in = input_array.units\n            self.unit_out = unit_out\n\n            self.grid_unit = grid_units(self.x_max)['grid_unit']\n            self.grid_unit_name = grid_units(self.x_max)['grid_unit_name']\n\n            self.FOV = (self.x_max - self.x_min, self.y_max - self.y_min)\n\n            # name\n            self.name = name\n            self.stage = 'SyntheticSED:  initial'\n            self.log = [self.stage]\n\n            # filter\n            self.filter = {'name': None, 'waf_0': None, 'waf_min': None, 'waf_max': None}\n\n            # convert into val units into unit_out\n            s = ConvertUnits(wav=self.wav, val=self.val)\n            self.val = s.get_unit(in_units=self.unit_in, out_units=self.unit_out, input_resolution=self.resolution['arcsec'])\n\n            self.units = self.unit_out\n\n    def extinction(self, A_v, input_opacities=None):\n        '''\n        Accounts for reddening.\n        \n        Parameters\n        ----------\n        \n        A_v : Value of the visible extinction.\n                         \n        input_opacities : ``None``, str\n            If ``None`` standard extinction law is used. \n            Otherwise a e. g. input_opacities.txt file can be passed \n            as a str to read an opacity file with column #1 wav in microns \n            and column #2 in cm^2/g. \n            Default is ``None``.\n                \n        Returns\n        -------\n        \n        sed : SyntheticSED    \n        '''\n\n        stage = 'SyntheticSED: extinction'\n\n        # read own extinction law\n        if input_opacities is None:\n            t = np.loadtxt(ROOT + 'database/extinction/extinction_law.txt')\n\n        else:\n            t = np.loadtxt(input_opacities)\n\n        wav_ext = t[:, 0]\n        k_lam = t[:, 1]\n\n        # wav_ext monotonically increasing\n        if wav_ext[0] > wav_ext[1]:\n            wav_ext = wav_ext[::-1]\n            k_lam = k_lam[::-1]\n\n        k_v = np.interp(0.550, wav_ext, k_lam)\n\n        # interpolate to get A_int for a certain wavelength\n        k = np.interp(self.wav, wav_ext, k_lam)\n        A_int_lam = A_v * (k / k_v)\n\n        # apply extinction law\n        val_ext = np.zeros(shape=np.shape(self.val))\n        val_ext[:len(self.wav)] = self.val[:len(self.wav)] * 10 ** (-0.4 * A_int_lam[:len(self.wav)])\n\n        # return SyntheticSED\n        s = SyntheticSED(self)\n        s.val = val_ext\n        s.stage = stage\n        s.log.append(s.stage)\n\n        return s\n\n    def convolve_filter(self, filter_input, plot_rebin=None, plot_rebin_dpi=None):\n        '''\n        Convolves vector val entries within filter limits in a 0D val array.\n        \n        Parameters\n        ----------\n        \n        filter_input : object\n        \n            * database : if filter ``name`` from FluxCompensator database is used.            \n            * Filter : if own filter is used.\n            \n        plot_rebin : ``True``, ``None``\n            Switch to plot the rebined filter and the original filter in one plot.\n            \n        plot_rebin_dpi  :  ``None``, scalar > 0 \n            The resolution in dots per inch. \n            ``None`` is default and will use the val savefig.dpi \n            in the matplotlibrc file.\n        \n\n        Returns\n        -------\n        \n        flux : SyntheticFlux\n        '''\n\n        stage = 'SyntheticSED: convolve_filter'\n\n        # debugging comment\n        logger.debug('-' * 70)\n        logger.debug(stage)\n        logger.debug('-' * 70)\n        \n        weight = filter_input.rebin(self.wav, self.val)\n\n        # returns weight{'wav_short' 'val_short' 'Response_new' 'filter_index' 'wavf_0' 'waf_min' 'waf_max' 'filter_name'}\n        wav_short = weight['wav_short']\n        val_short = weight['val_short']\n        filter_index = weight['filter_index']\n        Response_new = weight['Response_new']\n        waf_0 = weight['waf_0']\n        waf_min = weight['waf_min']\n        waf_max = weight['waf_max']\n        filter_name = weight['filter_name']\n\n        if plot_rebin is not None:\n            plot = filter_input.plot(val_name=self.name, dpi=plot_rebin_dpi)\n\n        # weight val_short with rebined response\n        val = val_short.copy()\n        val[:len(wav_short)] = val_short[:len(wav_short)] * Response_new[:len(wav_short)]\n\n        # collapse remaining vector to val scalar\n        val_tot = np.sum(val)\n\n        # return SyntheticFlux\n        from .flux import SyntheticFlux\n        f = SyntheticFlux(self)\n        f.log.append(stage)\n        f.stage = 'SyntheticFlux: initial'\n        f.log.append(f.stage)\n        f.val = val_tot\n        f.wav = np.array(waf_0)\n        f.filter = {'name': filter_name, 'waf_0': waf_0, 'waf_min': waf_min, 'waf_max': waf_max}\n\n        return f\n\n    def get_total_val(self, wav_1, wav_2):\n        '''\n        Collapses the val entries in the vector within the boundaries wav_1\n        and wav_2 into a 0D val array. \n        \n        WARNING: This tool cannot replace convolve_filter! \n                 But it can be used to produce rough estimates \n                 in-between the processes.\n\n\n        Parameters\n        ----------\n        \n        wav_1, wav_2 : float\n            Boundaries in microns.\n            \n        \n        Returns\n        -------\n        \n        flux : SyntheticFlux\n        '''\n\n        stage = 'SyntheticSED: get_total_val'\n\n        # for MJy/sr convert first, add and then convert back\n        if self.unit_out == 'MJy/sr' or self.unit_out == 'Jy/arcsec^2':\n            s = ConvertUnits(wav=self.wav, val=self.val)\n            self.val = s.get_unit(in_units=self.units, out_units='Jy', input_resolution=self.resolution['arcsec'])\n\n        # slices within boundaries are extracted, averaged collapsed to a single scalar val\n        vec = get_slices(wav=self.wav, val=self.val, wav_1=wav_1, wav_2=wav_2)\n        f_total = average_collapse(val=vec['val_short'])\n\n        # real limits within collapse\n        wav_max = 10 ** (np.log10(self.wav[vec['filter_index'][0]]) + self.spacing_wav / 2.)\n        wav_min = 10 ** (np.log10(self.wav[vec['filter_index'][-1]]) - self.spacing_wav / 2.)\n        wav_total = central_wav(wav=[wav_min, wav_max])\n\n        # for MJy/sr convert first, add and then convert back\n        if self.unit_out == 'MJy/sr' or self.unit_out == 'Jy/arcsec^2':\n            s = ConvertUnits(wav=wav_total, val=f_total)\n            f_total = s.get_unit(in_units='Jy', out_units=self.unit_out, input_resolution=self.resolution['arcsec'] * self.pixel[0])\n\n        # return SyntheticFlux\n        from .flux import SyntheticFlux\n        f = SyntheticFlux(self)\n        f.log.append(stage)\n        f.stage = 'SyntheticFlux: initial'\n        f.log.append(f.stage)\n        f.val = np.array(f_total)\n        f.wav = np.array(wav_total)\n        f.filter = {'name': 'val_tot', 'waf_0': wav_total, 'waf_min': wav_min, 'waf_max': wav_max}\n\n        return f\n\n    def plot_sed_multi_filter(self, multi_filter_val, multi_filter_wav, names, filter_label_size=None, ymin=10. ** (-5), dpi=None):\n        '''\n        Reads in array of filtered val and plots it with the current passed val of  \n        SyntheticSED in a log-log diagram. \n        That way the quality of multiple filtered val can be checked, if filters are\n        in database.\n        If the used filters are not part of the filter database, define a OneFilter object.\n        \n        \n        Parameters\n        ----------\n        \n        multi_filter_val : np.ndarray\n            1D vector with val entries from several filters.\n                    \n        multi_filter_wav : np.ndarray\n            1D vector of central wavelengths from several filters.\n\n        names : np.ndarray\n            Original name of several filters, if found in database.\n            \n        filter_label_size : ``None``, ``True``\n            Switch wether to set print labels above the filters.\n            \n                * ``None``: No labels plotted.\n                * ``True``: Plots names[index] as label.\n            \n        ymin : float\n            Minimal vertical limit for SED plot. \n            Default is 10.**(-10) of the maximum val.\n            \n        dpi  :  ``None``, scalar > 0 \n            The resolution in dots per inch. \n            ``None`` is default and will use the val savefig.dpi \n            in the matplotlibrc file.\n            \n            \n        Returns\n        -------\n        \n        flux : SyntheticFlux\n        '''\n\n        stage = 'SyntheticSED: plot_sed_multi_filter'\n\n        # plot sed and val within boundaries of sed\n        fig = plt.figure()\n        font = {'size': 8}\n\n        mpl.rc('font', **font)\n        suptitle = fig.suptitle('output SED with filtered val', fontsize=12.)\n\n        x_max = self.wav[0]\n        x_min = self.wav[-1]\n        y_max = 10 * max(self.val)\n        y_min = max(self.val) * ymin\n\n        # subplot with SED and collapsed fluval\n        gs = gridspec.GridSpec(2, 1, height_ratios=[2, 1])\n        ax = plt.subplot(gs[0])\n        plt.subplots_adjust(wspace=0, hspace=0)\n        ax.set_xlim([x_min, x_max])\n        ax.set_ylim([y_min, y_max])\n\n        #ax.set_xlabel(r'$\\lambda$ [$\\mu$m]')\n        ax.set_ylabel('val ' + '[' + str(self.unit_out) + ']')\n        plt.loglog(self.wav, self.val, 'o-k', label='rough SED', linewidth=2)\n\n        # sort c.fluval.wav, filt after c.wav\n        # get index of c.wav in right order\n        # [::-1] largest cwav comes first\n        sort_order = np.argsort(multi_filter_wav)\n        multi_filter_val = np.take(multi_filter_val, sort_order)[::-1]\n        multi_filter_wav = np.take(multi_filter_wav, sort_order)[::-1]\n        names = np.take(names, sort_order)[::-1]\n\n        # color\n        f = np.linspace(0, 200, len(names))\n\n        for i in range(len(names)):\n            current_waf_0 = multi_filter_wav[i]\n            current_val = multi_filter_val[i]\n            current_name = names[i]\n\n            color = plt.cm.RdYlBu(int(f[i]))\n            #color = plt.cm.autumn(int(f[i]))\n\n            # filter\n            text = 'filtered val by ' + str(current_name)\n            x = PlotFilters(style='loglog', normalized=True, unit='unit energy')\n            plot_filter = x.collect_filters(current_name)\n            plt.loglog(current_waf_0, current_val, 'o', color=color)\n\n        # subplot with filter responses\n        ax2 = plt.subplot(gs[1])\n        ax2.set_xlim([x_min, x_max])\n        ax2.set_ylim([10. ** (-4), 10.])\n        ax2.set_ylabel('filter response [unit energy]', color='k')\n\n        for i in range(len(names)):\n            current_waf_0 = multi_filter_wav[i]\n            current_val = multi_filter_val[i]\n            current_name = names[i]\n\n            color = plt.cm.RdYlBu(int(f[i]))\n            #color = plt.cm.autumn(int(f[i]))\n            fancy_line = {'color': color, 'linestyle': '-', 'linewidth': 2}\n\n            x = PlotFilters(style='loglog', normalized=True, unit='unit energy')\n            plot_filter = x.collect_filters(current_name)\n            x.plot(plot_filter, line=fancy_line)\n\n            # text above filters\n            if filter_label_size is not None:\n                plt.text(current_waf_0, 3, current_name, horizontalalignment='center', verticalalignment='center', fontsize=filter_label_size)\n\n        ax2.set_xlabel(r'$\\lambda$ [$\\mu$m]')\n\n        # legend merged\n        h1, l1 = ax.get_legend_handles_labels()\n        h2, l2 = ax2.get_legend_handles_labels()\n\n        leg = ax.legend(h1 + h2, l1 + l2, loc=(1.03, -0.5))\n        for t in leg.get_texts():\n            t.set_fontsize('small')    # the legend text fontsize\n\n        fig.savefig(str(self.name) + '_' + 'process-output_SS-multi-filter.png', dpi=dpi, bbox_inches='tight')\n\n        # return SyntheticSED\n        s = SyntheticSED(self)\n        s.log.append(stage)\n        s.stage = 'SyntheticSED: initial'\n        s.log.append(s.stage)\n\n        return s\n\n    @property\n    def spacing_wav(self):\n        '''\n        The property spacing_wav estimates the width of the logarithmic\n        spaced wav entries.\n        '''\n\n        if self.wav.ndim != 0:\n            spacing_wav = np.log10(self.wav[0] / self.wav[-1]) / (len(self.wav) - 1)\n        else:\n            spacing_wav = None\n        return spacing_wav\n\n    @property\n    def pixel(self):\n        '''\n        The property pixel is a tuple which resembles the current pixel in a\n        val slice. ``pixel(x,y)`` are calls as follows:\n         \n        ``x = pixel[0]``\n        ``y = pixel[1]``\n        '''\n        if self.val.ndim in (0, 1):\n            pixel = (None, None)\n        if self.val.ndim in (2, 3):\n            pixel = (self.val.shape[0], self.val.shape[1])\n        return pixel\n\n    @property\n    def shape(self):\n        '''\n        The property shape is a string, which resembles the current shape of\n        the val array. \n        \n        scalar: ``'()'`` \n        1D:     ``'(wav)'`` \n        2D:     ``'(x, y)'`` \n        3D:     ``'(x, y , wav)'`` \n        '''\n        if self.val.ndim == 0:\n            shape = '()'\n        if self.val.ndim == 1:\n            shape = '(wav)'\n        if self.val.ndim == 2:\n            shape = '(x, y)'\n        if self.val.ndim == 3:\n            shape = '(x, y, wav)'\n        return shape\n\n    @property\n    def resolution(self):\n        '''\n        The property resolution tells you the current resolution. If we are already \n        in the SED or val dimension everything is considered as one large pixel.\n\n            resolution in arcsec per pixel : ``resolution['arcsec']``\n            resolution in rad per pixel    : ``resolution['rad']``\n        \n        '''\n        resolution = {}\n        if self.pixel[0] is None:\n            resolution['rad'] = self.FOV[0] / 1. / self.distance\n        else:\n            resolution['rad'] = self.FOV[0] / self.pixel[0] / self.distance\n        resolution['arcsec'] = np.degrees(resolution['rad']) * 3600\n        return resolution\n", "meta": {"hexsha": "ce0bd378e8f89a71bede97fbe343aca97e49f24f", "size": 22447, "ext": "py", "lang": "Python", "max_stars_repo_path": "fluxcompensator/sed.py", "max_stars_repo_name": "koepferl/FluxCompensator", "max_stars_repo_head_hexsha": "751cac08971845069da8c962bc83459f091ba0f8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2017-06-22T15:29:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T11:55:41.000Z", "max_issues_repo_path": "fluxcompensator/sed.py", "max_issues_repo_name": "koepferl/FluxCompensator", "max_issues_repo_head_hexsha": "751cac08971845069da8c962bc83459f091ba0f8", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-06-16T21:01:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-16T21:01:51.000Z", "max_forks_repo_path": "fluxcompensator/sed.py", "max_forks_repo_name": "koepferl/FluxCompensator", "max_forks_repo_head_hexsha": "751cac08971845069da8c962bc83459f091ba0f8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-06-22T14:57:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-14T16:46:44.000Z", "avg_line_length": 32.9134897361, "max_line_length": 161, "alphanum_fraction": 0.56101038, "include": true, "reason": "import numpy,from astropy", "num_tokens": 5391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.1957686682614533}}
{"text": "import logging\r\n\r\nimport numba\r\nimport numpy as np\r\nimport numpy.random as npr\r\n\r\nimport second.core.box_np_ops as box_np_ops\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\ndef unmap(data, count, inds, fill=0):\r\n    \"\"\"Unmap a subset of item (data) back to the original set of items (of\r\n    size count)\"\"\"\r\n    if count == len(inds):\r\n        return data\r\n\r\n    if len(data.shape) == 1:\r\n        ret = np.empty((count, ), dtype=data.dtype)\r\n        ret.fill(fill)\r\n        ret[inds] = data\r\n    else:\r\n        ret = np.empty((count, ) + data.shape[1:], dtype=data.dtype)\r\n        ret.fill(fill)\r\n        ret[inds, :] = data\r\n    return ret\r\n\r\n\r\ndef create_target_np(all_anchors,\r\n                     gt_boxes,\r\n                     similarity_fn,\r\n                     box_encoding_fn,\r\n                     prune_anchor_fn=None,\r\n                     gt_classes=None,\r\n                     matched_threshold=0.6,\r\n                     unmatched_threshold=0.45,\r\n                     bbox_inside_weight=None,\r\n                     positive_fraction=None,\r\n                     rpn_batch_size=300,\r\n                     norm_by_num_examples=False,\r\n                     gt_importance=None,\r\n                     box_code_size=7):\r\n    \"\"\"Modified from FAIR detectron.\r\n    Args:\r\n        all_anchors: [num_of_anchors, box_ndim] float tensor.\r\n        gt_boxes: [num_gt_boxes, box_ndim] float tensor.\r\n        similarity_fn: a function, accept anchors and gt_boxes, return\r\n            similarity matrix(such as IoU).\r\n        box_encoding_fn: a function, accept gt_boxes and anchors, return\r\n            box encodings(offsets).\r\n        prune_anchor_fn: a function, accept anchors, return indices that\r\n            indicate valid anchors.\r\n        gt_classes: [num_gt_boxes] int tensor. indicate gt classes, must\r\n            start with 1.\r\n        matched_threshold: float, iou greater than matched_threshold will\r\n            be treated as positives.\r\n        unmatched_threshold: float, iou smaller than unmatched_threshold will\r\n            be treated as negatives.\r\n        bbox_inside_weight: unused\r\n        positive_fraction: [0-1] float or None. if not None, we will try to\r\n            keep ratio of pos/neg equal to positive_fraction when sample.\r\n            if there is not enough positives, it fills the rest with negatives\r\n        rpn_batch_size: int. sample size\r\n        norm_by_num_examples: bool. norm box_weight by number of examples, but\r\n            I recommend to do this outside.\r\n        gt_importance: 1d array. loss weight per gt.\r\n    Returns:\r\n        labels, bbox_targets, bbox_outside_weights\r\n    \"\"\"\r\n    total_anchors = all_anchors.shape[0]\r\n    if prune_anchor_fn is not None:\r\n        inds_inside = prune_anchor_fn(all_anchors)\r\n        anchors = all_anchors[inds_inside, :]\r\n        if not isinstance(matched_threshold, float):\r\n            matched_threshold = matched_threshold[inds_inside]\r\n        if not isinstance(unmatched_threshold, float):\r\n            unmatched_threshold = unmatched_threshold[inds_inside]\r\n    else:\r\n        anchors = all_anchors\r\n        inds_inside = None\r\n    num_inside = len(inds_inside) if inds_inside is not None else total_anchors\r\n    box_ndim = all_anchors.shape[1]\r\n    logger.debug('total_anchors: {}'.format(total_anchors))\r\n    logger.debug('inds_inside: {}'.format(num_inside))\r\n    logger.debug('anchors.shape: {}'.format(anchors.shape))\r\n    if gt_classes is None:\r\n        gt_classes = np.ones([gt_boxes.shape[0]], dtype=np.int32)\r\n    if gt_importance is None:\r\n        gt_importance = np.ones([gt_boxes.shape[0]], dtype=np.float32)\r\n\r\n    # Compute anchor labels:\r\n    # label=1 is positive, 0 is negative, -1 is don't care (ignore)\r\n    labels = np.empty((num_inside, ), dtype=np.int32)\r\n    gt_ids = np.empty((num_inside, ), dtype=np.int32)\r\n    labels.fill(-1)\r\n    gt_ids.fill(-1)\r\n    importance = np.empty((num_inside, ), dtype=np.float32)\r\n    importance.fill(1)\r\n    if len(gt_boxes) > 0:\r\n        # Compute overlaps between the anchors and the gt boxes overlaps\r\n        anchor_by_gt_overlap = similarity_fn(anchors, gt_boxes)\r\n        # Map from anchor to gt box that has highest overlap\r\n        anchor_to_gt_argmax = anchor_by_gt_overlap.argmax(axis=1)\r\n        # For each anchor, amount of overlap with most overlapping gt box\r\n        anchor_to_gt_max = anchor_by_gt_overlap[np.arange(num_inside),\r\n                                                anchor_to_gt_argmax]  #\r\n        # Map from gt box to an anchor that has highest overlap\r\n        gt_to_anchor_argmax = anchor_by_gt_overlap.argmax(axis=0)\r\n        # For each gt box, amount of overlap with most overlapping anchor\r\n        gt_to_anchor_max = anchor_by_gt_overlap[gt_to_anchor_argmax,\r\n                                                np.arange(anchor_by_gt_overlap.\r\n                                                          shape[1])]\r\n        # must remove gt which doesn't match any anchor.\r\n        empty_gt_mask = gt_to_anchor_max == 0\r\n        gt_to_anchor_max[empty_gt_mask] = -1\r\n        \"\"\"\r\n        if not np.all(empty_gt_mask):\r\n            gt_to_anchor_max = gt_to_anchor_max[empty_gt_mask]\r\n            anchor_by_gt_overlap = anchor_by_gt_overlap[:, empty_gt_mask]\r\n            gt_classes = gt_classes[empty_gt_mask]\r\n            gt_boxes = gt_boxes[empty_gt_mask]\r\n        \"\"\"\r\n        # Find all anchors that share the max overlap amount\r\n        # (this includes many ties)\r\n        anchors_with_max_overlap = np.where(\r\n            anchor_by_gt_overlap == gt_to_anchor_max)[0]\r\n        # Fg label: for each gt use anchors with highest overlap\r\n        # (including ties)\r\n        gt_inds_force = anchor_to_gt_argmax[anchors_with_max_overlap]\r\n        labels[anchors_with_max_overlap] = gt_classes[gt_inds_force]\r\n        gt_ids[anchors_with_max_overlap] = gt_inds_force\r\n        # Fg label: above threshold IOU\r\n        pos_inds = anchor_to_gt_max >= matched_threshold\r\n        gt_inds = anchor_to_gt_argmax[pos_inds]\r\n        labels[pos_inds] = gt_classes[gt_inds]\r\n        gt_ids[pos_inds] = gt_inds\r\n        bg_inds = np.where(anchor_to_gt_max < unmatched_threshold)[0]\r\n        importance[pos_inds] = gt_importance[gt_inds]\r\n    else:\r\n        # labels[:] = 0\r\n        bg_inds = np.arange(num_inside)\r\n    fg_inds = np.where(labels > 0)[0]\r\n    fg_max_overlap = None\r\n    if len(gt_boxes) > 0:\r\n        fg_max_overlap = anchor_to_gt_max[fg_inds]\r\n    gt_pos_ids = gt_ids[fg_inds]\r\n    # bg_inds = np.where(anchor_to_gt_max < unmatched_threshold)[0]\r\n    # bg_inds = np.where(labels == 0)[0]\r\n    # subsample positive labels if we have too many\r\n    if positive_fraction is not None:\r\n        num_fg = int(positive_fraction * rpn_batch_size)\r\n        if len(fg_inds) > num_fg:\r\n            disable_inds = npr.choice(\r\n                fg_inds, size=(len(fg_inds) - num_fg), replace=False)\r\n            labels[disable_inds] = -1\r\n            fg_inds = np.where(labels > 0)[0]\r\n\r\n        # subsample negative labels if we have too many\r\n        # (samples with replacement, but since the set of bg inds is large most\r\n        # samples will not have repeats)\r\n        num_bg = rpn_batch_size - np.sum(labels > 0)\r\n        # print(num_fg, num_bg, len(bg_inds) )\r\n        if len(bg_inds) > num_bg:\r\n            enable_inds = bg_inds[npr.randint(len(bg_inds), size=num_bg)]\r\n            labels[enable_inds] = 0\r\n        bg_inds = np.where(labels == 0)[0]\r\n    else:\r\n        if len(gt_boxes) == 0:\r\n            labels[:] = 0\r\n        else:\r\n            labels[bg_inds] = 0\r\n            # re-enable anchors_with_max_overlap\r\n            labels[anchors_with_max_overlap] = gt_classes[gt_inds_force]\r\n    bbox_targets = np.zeros((num_inside, box_code_size),\r\n                            dtype=all_anchors.dtype)\r\n    if len(gt_boxes) > 0:\r\n        # print(anchors[fg_inds, :].shape, gt_boxes[anchor_to_gt_argmax[fg_inds], :].shape)\r\n        # bbox_targets[fg_inds, :] = box_encoding_fn(\r\n        #     anchors[fg_inds, :], gt_boxes[anchor_to_gt_argmax[fg_inds], :])\r\n        bbox_targets[fg_inds, :] = box_encoding_fn(\r\n            gt_boxes[anchor_to_gt_argmax[fg_inds], :], anchors[fg_inds, :])\r\n    # Bbox regression loss has the form:\r\n    #   loss(x) = weight_outside * L(weight_inside * x)\r\n    # Inside weights allow us to set zero loss on an element-wise basis\r\n    # Bbox regression is only trained on positive examples so we set their\r\n    # weights to 1.0 (or otherwise if config is different) and 0 otherwise\r\n    # NOTE: we don't need bbox_inside_weights, remove it.\r\n    # bbox_inside_weights = np.zeros((num_inside, box_ndim), dtype=np.float32)\r\n    # bbox_inside_weights[labels == 1, :] = [1.0] * box_ndim\r\n\r\n    # The bbox regression loss only averages by the number of images in the\r\n    # mini-batch, whereas we need to average by the total number of example\r\n    # anchors selected\r\n    # Outside weights are used to scale each element-wise loss so the final\r\n    # average over the mini-batch is correct\r\n    # bbox_outside_weights = np.zeros((num_inside, box_ndim), dtype=np.float32)\r\n    bbox_outside_weights = np.zeros((num_inside, ), dtype=all_anchors.dtype)\r\n    # uniform weighting of examples (given non-uniform sampling)\r\n    if norm_by_num_examples:\r\n        num_examples = np.sum(labels >= 0)  # neg + pos\r\n        num_examples = np.maximum(1.0, num_examples)\r\n        bbox_outside_weights[labels > 0] = 1.0 / num_examples\r\n    else:\r\n        bbox_outside_weights[labels > 0] = 1.0\r\n    # bbox_outside_weights[labels == 0, :] = 1.0 / num_examples\r\n\r\n    # Map up to original set of anchors\r\n    if inds_inside is not None:\r\n        labels = unmap(labels, total_anchors, inds_inside, fill=-1)\r\n        bbox_targets = unmap(bbox_targets, total_anchors, inds_inside, fill=0)\r\n        # bbox_inside_weights = unmap(\r\n        #     bbox_inside_weights, total_anchors, inds_inside, fill=0)\r\n        bbox_outside_weights = unmap(\r\n            bbox_outside_weights, total_anchors, inds_inside, fill=0)\r\n        importance = unmap(importance, total_anchors, inds_inside, fill=0)\r\n    # return labels, bbox_targets, bbox_outside_weights\r\n    ret = {\r\n        \"labels\": labels,\r\n        \"bbox_targets\": bbox_targets,\r\n        \"bbox_outside_weights\": bbox_outside_weights,\r\n        \"assigned_anchors_overlap\": fg_max_overlap,\r\n        \"positive_gt_id\": gt_pos_ids,\r\n        \"importance\": importance,\r\n    }\r\n    if inds_inside is not None:\r\n        ret[\"assigned_anchors_inds\"] = inds_inside[fg_inds]\r\n    else:\r\n        ret[\"assigned_anchors_inds\"] = fg_inds\r\n    return ret\r\n", "meta": {"hexsha": "860dfaf5d597d0f5fbce1fc195f82693b34018c3", "size": 10568, "ext": "py", "lang": "Python", "max_stars_repo_path": "second/core/target_ops.py", "max_stars_repo_name": "jerry99s/second.pytorch", "max_stars_repo_head_hexsha": "80143908a349b9f3ff1642d21dacaf23455b3cf8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1541, "max_stars_repo_stars_event_min_datetime": "2018-10-04T00:32:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:54:59.000Z", "max_issues_repo_path": "second/core/target_ops.py", "max_issues_repo_name": "Karthik-Ragunath/second.pytorch", "max_issues_repo_head_hexsha": "414de8936a165d7cdba4a6eb15ce9603201d2e61", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 466, "max_issues_repo_issues_event_min_datetime": "2018-10-06T01:05:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T08:49:44.000Z", "max_forks_repo_path": "second/core/target_ops.py", "max_forks_repo_name": "Karthik-Ragunath/second.pytorch", "max_forks_repo_head_hexsha": "414de8936a165d7cdba4a6eb15ce9603201d2e61", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 537, "max_forks_repo_forks_event_min_datetime": "2018-10-04T07:36:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T10:12:02.000Z", "avg_line_length": 45.947826087, "max_line_length": 92, "alphanum_fraction": 0.6279333838, "include": true, "reason": "import numpy,import numba", "num_tokens": 2459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.1956942136140167}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2019 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#\n\n'''\nGeneralized Kohn-Sham\n'''\n\nimport time\nimport numpy\nimport scipy.linalg\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf.scf import ghf\nfrom pyscf.dft import rks\n\n\ndef get_veff(ks, mol=None, dm=None, dm_last=0, vhf_last=0, hermi=1):\n    '''Coulomb + XC functional for GKS.\n    '''\n    if mol is None: mol = self.mol\n    if dm is None: dm = ks.make_rdm1()\n    t0 = (time.clock(), time.time())\n\n    ground_state = (isinstance(dm, numpy.ndarray) and dm.ndim == 2)\n\n    assert(hermi == 1)\n    dm = numpy.asarray(dm)\n    nso = dm.shape[-1]\n    nao = nso // 2\n    dm_a = dm[...,:nao,:nao].real\n    dm_b = dm[...,nao:,nao:].real\n\n    if ks.grids.coords is None:\n        ks.grids.build(with_non0tab=True)\n        if ks.small_rho_cutoff > 1e-20 and ground_state:\n            ks.grids = rks.prune_small_rho_grids_(ks, mol, dm_a+dm_b, ks.grids)\n        t0 = logger.timer(ks, 'setting up grids', *t0)\n    if ks.nlc != '':\n        if ks.nlcgrids.coords is None:\n            ks.nlcgrids.build(with_non0tab=True)\n            if ks.small_rho_cutoff > 1e-20 and ground_state:\n                ks.nlcgrids = rks.prune_small_rho_grids_(ks, mol, dm_a+dm_b, ks.nlcgrids)\n            t0 = logger.timer(ks, 'setting up nlc grids', *t0)\n\n    max_memory = ks.max_memory - lib.current_memory()[0]\n    ni = ks._numint\n    n, exc, vxc = ni.nr_uks(mol, ks.grids, ks.xc, (dm_a,dm_b), max_memory=max_memory)\n    if ks.nlc != '':\n        assert('VV10' in ks.nlc.upper())\n        _, enlc, vnlc = ni.nr_rks(mol, ks.nlcgrids, ks.xc+'__'+ks.nlc, dm_a+dm_b,\n                                  max_memory=max_memory)\n        exc += enlc\n        vxc += vnlc\n    logger.debug(ks, 'nelec by numeric integration = %s', n)\n    t0 = logger.timer(ks, 'vxc', *t0)\n    if vxc.ndim == 4:\n        raise NotImplementedError\n    vxc = numpy.asarray(scipy.linalg.block_diag(*vxc), dtype=dm.dtype)\n\n    #enabling range-separated hybrids\n    omega, alpha, hyb = ni.rsh_and_hybrid_coeff(ks.xc, spin=mol.spin)\n\n    if abs(hyb) < 1e-10 and abs(alpha) < 1e-10:\n        vk = None\n        if (ks._eri is None and ks.direct_scf and\n            getattr(vhf_last, 'vj', None) is not None):\n            ddm = numpy.asarray(dm) - numpy.asarray(dm_last)\n            vj = ks.get_j(mol, ddm, hermi)\n            vj += vhf_last.vj\n        else:\n            vj = ks.get_j(mol, dm, hermi)\n        vxc += vj\n    else:\n        if (ks._eri is None and ks.direct_scf and\n            getattr(vhf_last, 'vk', None) is not None):\n            ddm = numpy.asarray(dm) - numpy.asarray(dm_last)\n            vj, vk = ks.get_jk(mol, ddm, hermi)\n            vk *= hyb\n            if abs(omega) > 1e-10:\n                vklr = _get_k_lr(mol, ddm, omega, hermi)\n                vklr *= (alpha - hyb)\n                vk += vklr\n            vj += vhf_last.vj\n            vk += vhf_last.vk\n        else:\n            vj, vk = ks.get_jk(mol, dm, hermi)\n            vk *= hyb\n            if abs(omega) > 1e-10:\n                vklr = _get_k_lr(mol, dm, omega, hermi)\n                vklr *= (alpha - hyb)\n                vk += vklr\n        vxc += vj - vk\n\n        if ground_state:\n            exc -= numpy.einsum('ij,ji', dm, vk).real * .5\n    if ground_state:\n        ecoul = numpy.einsum('ij,ji', dm, vj).real * .5\n    else:\n        ecoul = None\n\n    vxc = lib.tag_array(vxc, ecoul=ecoul, exc=exc, vj=vj, vk=vk)\n    return vxc\n\ndef _get_k_lr(mol, dm, omega=0, hermi=0):\n    nso = dm.shape[-1]\n    nao = nso // 2\n    dms = dm.reshape(-1,nso,nso)\n    n_dm = dms.shape[0]\n\n    dmaa = dms[:,:nao,:nao]\n    dmab = dms[:,nao:,:nao]\n    dmbb = dms[:,nao:,nao:]\n    dms = numpy.vstack((dmaa, dmbb, dmab))\n    if dm.dtype == numpy.complex128:\n        dms = numpy.vstack((dms.real, dms.imag))\n        hermi = 0\n\n    k1 = rks._get_k_lr(mol, dms, omega, hermi)\n    k1 = k1.reshape(-1,n_dm,nao,nao)\n\n    if dm.dtype == numpy.complex128:\n        k1 = k1[:3] + k1[3:] * 1j\n\n    vk = numpy.zeros((n_dm,nso,nso), dm.dtype)\n    vk[:,:nao,:nao] = k1[0]\n    vk[:,nao:,nao:] = k1[1]\n    vk[:,:nao,nao:] = k1[2]\n    vk[:,nao:,:nao] = k1[2].transpose(0,2,1).conj()\n    vk = vk.reshape(dm.shape)\n    return vk\n\n\nclass GKS(ghf.GHF):\n    '''Generalized Kohn-Sham'''\n    def __init__(self, mol):\n        ghf.GHF.__init__(self, mol)\n        rks._dft_common_init_(self)\n\n    def dump_flags(self, verbose=None):\n        ghf.GHF.dump_flags(self, verbose)\n        logger.info(self, 'XC functionals = %s', self.xc)\n        if self.nlc!='':\n            logger.info(self, 'NLC functional = %s', self.nlc)\n        logger.info(self, 'small_rho_cutoff = %g', self.small_rho_cutoff)\n        self.grids.dump_flags(verbose)\n\n    get_veff = get_veff\n    energy_elec = rks.energy_elec\n    define_xc_ = rks.define_xc_\n\n    def nuc_grad_method(self):\n        raise NotImplementedError\n\n\nif __name__ == '__main__':\n    from pyscf import gto\n    mol = gto.Mole()\n    mol.verbose = 3\n    mol.atom = 'H 0 0 0; H 0 0 1; O .5 .6 .2'\n    mol.basis = 'ccpvdz'\n    mol.build()\n\n    mf = GKS(mol)\n    mf.xc = 'b3lyp'\n    mf.kernel()\n\n    dm = mf.init_guess_by_1e(mol)\n    dm = dm + 0j\n    nao = mol.nao_nr()\n    numpy.random.seed(12)\n    dm[:nao,nao:] = numpy.random.random((nao,nao)) * .1j\n    dm[nao:,:nao] = dm[:nao,nao:].T.conj()\n    mf.kernel(dm)\n    mf.canonicalize(mf.mo_coeff, mf.mo_occ)\n    mf.analyze()\n    print(mf.spin_square())\n    print(mf.e_tot - -76.2760115704274)\n", "meta": {"hexsha": "37ee094862f5c7f631532e38cf1f43f07cdbf64b", "size": 6031, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/dft/gks.py", "max_stars_repo_name": "crisely09/pyscf", "max_stars_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-07T21:12:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-07T21:12:08.000Z", "max_issues_repo_path": "pyscf/dft/gks.py", "max_issues_repo_name": "crisely09/pyscf", "max_issues_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-09-16T17:58:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-22T17:26:01.000Z", "max_forks_repo_path": "pyscf/dft/gks.py", "max_forks_repo_name": "crisely09/pyscf", "max_forks_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2487046632, "max_line_length": 89, "alphanum_fraction": 0.5848118057, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.31069437683198775, "lm_q1q2_score": 0.19566742919212396}}
{"text": "#!/usr/bin/env python\n# ------------------------------------------------------------------------------------------------------%\n# Created by \"Thieu Nguyen\" at 14:14, 20/09/2020                                                        %\n#\n#       Email:      nguyenthieu2102@gmail.com                                                           %\n#       Homepage:   https://www.researchgate.net/profile/Thieu_Nguyen6                                  %\n#       Github:     https://github.com/thieu1995                                                  %\n#-------------------------------------------------------------------------------------------------------%\n\nfrom numpy import ones, zeros, concatenate\n\nD = [9, 11, 7, 6, 9, 38, 48, 2, 3, 3, 7, 7, 5, 10, 7, 14, 3, 4, 4, 2, 5, 9, 5, 7, 4, 22, 10, 10, 4, 3, 4, 5,\n     30, 118, 153, 158, 126, 126, 126, 76, 74, 86, 86, 30, 25, 25, 25, 30, 30, 30, 59, 59, 59, 59, 64, 64, 64]\ngn = [0, 0, 14, 1, 2, 0, 0, 2, 1, 3, 4, 9, 3, 10, 11, 15, 4, 4, 5, 3, 8, 10, 8, 7, 7, 86, 3, 9, 1, 8, 1, 6, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 105, 24, 24, 24,\n      29, 29, 29, 14, 14, 14, 14, 0, 0, 0]\nhn = [8, 9, 0, 4, 4, 32, 38, 0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 108, 148, 148, 116, 116, 116, 76, 74, 76, 76, 0, 1,\n      1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 6, 6]\n\n# bound constraint definitions for all 53 test functions\nxmin1 = [0, 0, 0, 0, 1000, 0, 100, 100, 100]\nxmax1 = [10, 200, 100, 200, 2000000, 600, 600, 600, 900]\nxmin2 = [10 ** 4, 10 ** 4, 10 ** 4, 0, 0, 0, 100, 100, 100, 100, 100]\nxmax2 = [0.819 * 10 ** 6, 1.131 * 10 ** 6, 2.05 * 10 ** 6, 0.05074, 0.05074, 0.05074, 200, 300, 300, 300, 400]\nxmin3 = [1000, 0, 2000, 0, 0, 0, 0]\nxmax3 = [2000, 100, 4000, 100, 100, 20, 200]\nxmin4 = [0, 0, 0, 0, 1e-5, 1e-5]\nxmax4 = [1, 1, 1, 1, 16, 16]\nxmin5 = zeros(D[4])\nxmax5 = [100, 200, 100, 100, 100, 100, 200, 100, 200]\nxmin6 = zeros(D[5])\nxmax6 = [90, 150, 90, 150, 90, 90, 150, 90, 90, 90, 150, 150, 90, 90, 150, 90, 150, 90, 150, 90, 1, 1.2,\n         1, 1, 1, 0.5, 1, 1, 0.5, 0.5, 0.5, 1.2, 0.5, 1.2, 1.2, 0.5, 1.2, 1.2]\nxmin7 = zeros(D[6])\nxmin7[23] = xmin7[25] = xmin7[27] = xmin7[30] = 0.849999\nxmax7 = ones(D[6])\nxmax7[3] = 140\nxmax7[24] = xmax7[26] = xmax7[31] = xmax7[34] = xmax7[36] = xmax7[28] = 30\nxmax7[1] = xmax7[2] = xmax7[4] = xmax7[12:15] = 90\nxmax7[0] = xmax7[5:12] = xmax7[15:20] = 35\nxmin8 = [0, -0.51]\nxmax8 = [1.6, 1.49]\nxmin9 = [0.5, 0.5, -0.51]\nxmax9 = [1.4, 1.4, 1.49]\nxmin10 = [0.2, -2.22554, -0.51]\nxmax10 = [1, -1, 1.49]\nxmin11 = [0, 0, 0, 0, -0.51, -0.51, 0]\nxmax11 = [20, 20, 10, 10, 1.49, 1.49, 40]\nxmin12 = [0, 0, 0, -0.51, -0.51, -0.51, -0.51]\nxmax12 = [100, 100, 100, 1.49, 1.49, 1.49, 1.49]\nxmin13 = [27, 27, 27, 77.51, 32.51]\nxmax13 = [45, 45, 45, 102.49, 45.49]\nxmin14 = [0.51, 0.51, 0.51, 250, 250, 250, 6, 4, 40, 10]\nxmax14 = [3.49, 3.49, 3.49, 2500, 2500, 2500, 20, 16, 700, 450]\nxmin15 = [2.6, 0.7, 17, 7.3, 7.3, 2.9, 5]\nxmax15 = [3.6, 0.8, 28, 8.3, 8.3, 3.9, 5.5]\nxmin16 = 0.001 * ones(D[15])\nxmax16 = +5 * ones(D[15])\nxmin17 = [0.05, 0.25, 2.00]\nxmax17 = [2, 1.3, 15.0]\nxmin18 = [0.51, 0.51, 10, 10]\nxmax18 = [99.49, 99.49, 200, 200]\nxmin19 = [0.125, 0.1, 0.1, 0.1]\nxmax19 = [2, 10, 10, 2]\nxmin20 = zeros(D[19])\nxmax20 = 1 * ones(D[19])\nxmin21 = [60, 90, 1, 0, 2]\nxmax21 = [80, 110, 3, 1000, 9]\nxmin22 = [16.51, 13.51, 13.51, 16.51, 13.51, 47.51, 0.51, 0.51, 0.51]\nxmax22 = [96.49, 54.49, 51.49, 46.49, 51.49, 124.49, 3.49, 6.49, 6.49]\nxmin23 = [0, 0, 0, 0, 0]\nxmax23 = [60, 60, 90, 90, 90]\nxmin24 = [10, 10, 100, 0, 10, 100, 1]\nxmax24 = [150, 150, 200, 50, 150, 300, 3.14]\nxmin25 = [1, 1, 1e-6, 1]\nxmax25 = [16, 16, 16 * 1e-6, 16]\nxmin26 = concatenate((6.51 * ones(8), 0.51 * ones(14)), axis=0)\nxmax26 = concatenate((76.49 * ones(8), 4.49 * ones(4), 9.49 * ones(10)), axis=0)\nxmin27 = 0.645e-4 * ones(D[26])\nxmax27 = 50e-4 * ones(D[26])\nxmin28 = [125, 10.5, 4.51, 0.515, 0.515, 0.4, 0.6, 0.3, 0.02, 0.6]\nxmax28 = [150, 31.5, 50.49, 0.6, 0.6, 0.5, 0.7, 0.4, 0.1, 0.85]\nxmin29 = [20, 1, 20, 0.1]\nxmax29 = [50, 10, 50, 60]\nxmin30 = [0.51, 0.6, 0.51]\nxmax30 = [70.49, 3, 42.49]\nxmin31 = 12. * ones(4)\nxmax31 = 60. * ones(4)\nxmin32 = [78, 33, 27, 27, 27]\nxmax32 = [102, 45, 45, 45, 45]\nxmin33 = 0.001 * ones(D[32])\nxmax33 = ones(D[32])\nxmin34 = -1 * ones(D[33])\nxmax34 = +1 * ones(D[33])\nxmin35 = -1 * ones(D[34])\nxmax35 = +1 * ones(D[34])\nxmin36 = -1 * ones(D[35])\nxmax36 = +1 * ones(D[35])\nxmin37 = -1 * ones(D[36])\nxmin37[117: 126] = 0\nxmax37 = +1 * ones(D[36])\nxmin38 = -1 * ones(D[37])\nxmin38[117: 126] = 0\nxmax38 = +1 * ones(D[37])\nxmin39 = -1 * ones(D[38])\nxmin39[117: 126] = 0\nxmax39 = +1 * ones(D[38])\nxmin40 = -1 * ones(D[39])\nxmin40[75: 76] = 0\nxmax40 = +1 * ones(D[39])\nxmax40[75: 76] = 2\nxmin41 = -1 * ones(D[40])\nxmax41 = +1 * ones(D[40])\nxmin42 = -1 * ones(D[41])\nxmin42[75: 76] = 0\nxmin42[77: 86] = 0\nxmax42 = +1 * ones(D[41])\nxmax42[75: 76] = 2\nxmax42[77: 86] = 500\nxmin43 = -1 * ones(D[42])\nxmin43[75: 76] = 0\nxmin43[77: 86] = 0\nxmax43 = +1 * ones(D[42])\nxmax43[75: 76] = 2\nxmax43[77: 86] = 500\nxmin44 = 40 * ones(D[43])\nxmax44 = 1960 * ones(D[43])\nxmin45 = zeros(D[44])\nxmax45 = +90 * ones(D[44])\nxmin46 = zeros(D[45])\nxmax46 = +90 * ones(D[45])\nxmin47 = zeros(D[46])\nxmax47 = +90 * ones(D[46])\nxmin48 = zeros(D[47])\nxmax48 = +90 * ones(D[47])\nxmin49 = zeros(D[48])\nxmax49 = +90 * ones(D[48])\nxmin50 = zeros(D[49])\nxmax50 = +90 * ones(D[49])\nxmin51 = zeros(D[50])\nxmax51 = 10. * ones(D[50])\nxmin52 = zeros(D[51])\nxmax52 = 10. * ones(D[51])\nxmin53 = zeros(D[52])\nxmax53 = 10. * ones(D[52])\nxmin54 = zeros(D[53])\nxmax54 = 10. * ones(D[53])\nxmin55 = zeros(D[54])\nxmax55 = 10. * ones(D[54])\nxmin56 = zeros(D[55])\nxmax56 = 10. * ones(D[55])\nxmin57 = zeros(D[56])\nxmax57 = 10. * ones(D[56])\n\ndef benchmark_function(idx):\n    # % prob_k -> Index of problem.\n    # % D[idx  -> Dimension of the problem.\n    # % par.g  -> Number of inequility constraints.\n    # % par.h  -> Number of equality constraints.\n    # % par.xmin -> lower bound of decision variables.\n    # % par.xmax -> upper bound of decision variables.\n    xmin = globals()['xmin' + str(idx)]\n    xmax = globals()['xmax' + str(idx)]\n    return {\"D\": D[idx-1], \"g\": gn[idx-1], \"h\": hn[idx-1], \"xmin\": xmin, \"xmax\": xmax}", "meta": {"hexsha": "5b67a454bb8a69e058af26033a8092040962c0bc", "size": 6191, "ext": "py", "lang": "Python", "max_stars_repo_path": "opfunu/cec/cec2020/constant.py", "max_stars_repo_name": "ElliottP-13/opfunu", "max_stars_repo_head_hexsha": "7f4de3c34a91bb37fd8784fd28dbcf550e06d8a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2020-09-12T09:19:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:25:01.000Z", "max_issues_repo_path": "opfunu/cec/cec2020/constant.py", "max_issues_repo_name": "ElliottP-13/opfunu", "max_issues_repo_head_hexsha": "7f4de3c34a91bb37fd8784fd28dbcf550e06d8a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-05-22T10:16:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-06T15:46:39.000Z", "max_forks_repo_path": "opfunu/cec/cec2020/constant.py", "max_forks_repo_name": "ElliottP-13/opfunu", "max_forks_repo_head_hexsha": "7f4de3c34a91bb37fd8784fd28dbcf550e06d8a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-02-16T05:00:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-21T19:40:18.000Z", "avg_line_length": 37.981595092, "max_line_length": 158, "alphanum_fraction": 0.5081570021, "include": true, "reason": "from numpy", "num_tokens": 3192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.1956343204913146}}
{"text": "import os\n# os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"   # see issue #152\n# os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"2\"\n\nimport torch as T\nfrom torch.autograd import Variable\nimport numpy as np\nimport pdb\nimport copy\nimport time\n\ncuda = True\nif cuda:\n    floatX = T.cuda.FloatTensor\n    intX = T.cuda.IntTensor\n    byteX = T.cuda.ByteTensor\n    longX = T.cuda.LongTensor\nelse:\n    floatX = T.FloatTensor\n    intX = T.IntTensor\n    byteX = T.ByteTensor\n    longX = T.LongTensor\n\n\ndef m_eye(n, k=0):\n    assert k < n and k >= 0\n    if k == 0:\n        return T.eye(n).type(floatX)\n    else:\n        return T.cat((T.cat((T.zeros(n-k, k), T.eye(n-k)), dim=1), T.zeros(k, n)), dim=0).type(floatX)\n\ndef ctc_loss(pred, pred_len, token, token_len, blank=0):\n    '''\n    :param pred: (Time, batch, voca_size+1)\n    :param pred_len: (batch)\n    :param token: (batch, U)\n    :param token_len: (batch)\n    '''\n    Time, batch = pred.size(0), pred.size(1)\n    U = token.size(1)\n    eps = 0\n\n    # token_with_blank\n    token_with_blank = T.cat((T.zeros(batch, U, 1).type(longX), token[:, :, None]), dim=2).view(batch, -1)    # (batch, 2U)\n    token_with_blank = T.cat((token_with_blank, T.zeros(batch, 1).type(longX)), dim=1)  # (batch, 2U+1)\n    length = token_with_blank.size(1)\n\n    pred = pred[T.arange(0, Time).type(longX)[:, None, None], T.arange(0, batch).type(longX)[None, :, None], token_with_blank[None, :]]  # (T, batch, 2U+1)\n\n    # recurrence relation\n    sec_diag = T.cat((T.zeros((batch, 2)).type(floatX), T.ne(token_with_blank[:, :-2], token_with_blank[:, 2:]).type(floatX)), dim=1) * T.ne(token_with_blank, blank).type(floatX)\t# (batch, 2U+1)\n    recurrence_relation = (m_eye(length) + m_eye(length, k=1)).repeat(batch, 1, 1) + m_eye(length, k=2).repeat(batch, 1, 1) * sec_diag[:, None, :]\t# (batch, 2U+1, 2U+1)\n\n    # alpha\n    alpha_t = T.cat((pred[0, :, :2], T.zeros(batch, 2*U-1).type(floatX)), dim=1) # (batch, 2U+1)\n    probability = alpha_t[None] # (1, batch, 2U+1)\n\n    # dynamic programming\n    # (T, batch, 2U+1)\n    for t in T.arange(1, Time).type(longX):\n        alpha_t = T.bmm(alpha_t[:, None], recurrence_relation)[:, 0] * pred[t]\n        probability = T.cat((probability, alpha_t[None]), dim=0)\n\n    labels_2 = probability[pred_len-1, T.arange(batch).type(longX), 2*token_len-1]\n    labels_1 = probability[pred_len-1, T.arange(batch).type(longX), 2*token_len]\n    labels_prob = labels_2 + labels_1\n\n    cost = -T.log(labels_prob+eps)\n    return cost\n\ndef log_batch_dot(alpha_t, rec):\n    '''\n    alpha_t: (batch, 2U+1)\n    rec: (batch, 2U+1, 2U+1)\n    '''\n    eps_nan = -1e8\n    # a+b\n    _sum = alpha_t[:, :, None] + rec\n    _max_sum = T.max(_sum, dim=1)[0]\n    nz_mask1 = T.gt(_max_sum, eps_nan) # max > eps_nan\n    nz_mask2 = T.gt(_sum, eps_nan)     # item > eps_nan\n\n    # a+b-max\n    _sum = _sum - _max_sum[:, None]\n\n    # exp\n    _exp = T.zeros_like(_sum).type(floatX)\n    _exp[nz_mask2] = T.exp(_sum[nz_mask2])\n\n    # sum exp\n    _sum_exp = T.sum(_exp, dim=1)\n\n    out = T.ones_like(_max_sum).type(floatX) * eps_nan\n    out[nz_mask1] = T.log(_sum_exp[nz_mask1]) + _max_sum[nz_mask1]\n    return out\n\ndef log_sum_exp_axis(a, uniform_mask=None, dim=0):\n    assert dim == 0\n    eps_nan = -1e8\n    eps = 1e-26\n    _max = T.max(a, dim=dim)[0]\n\n    if not uniform_mask is None:\n        nz_mask2 = T.gt(a, eps_nan) * uniform_mask\n        nz_mask1 = T.gt(_max, eps_nan) * T.ge(T.max(uniform_mask, dim=dim)[0], 1)\n    else:\n        nz_mask2 = T.gt(a, eps_nan)\n        nz_mask1 = T.gt(_max, eps_nan)\n\n    # a-max\n    a = a - _max[None]\n\n    # exp\n    _exp_a = T.zeros_like(a).type(floatX)\n    _exp_a[nz_mask2] = T.exp(a[nz_mask2])\n\n    # sum exp\n    _sum_exp_a = T.sum(_exp_a, dim=dim)\n\n    out = T.ones_like(_max).type(floatX) * eps_nan\n    out[nz_mask1] = T.log(_sum_exp_a[nz_mask1] + eps) + _max[nz_mask1]\n    return out\n\ndef log_sum_exp(*arrs):\n#    return T.max(a.clone(), b.clone()) + T.log1p(T.exp(-T.abs(a.clone()-b.clone())))\n    c = T.cat(list(map(lambda x:x[None], arrs)), dim=0)\n    return log_sum_exp_axis(c, dim=0)\n\ndef ctc_loss_log(pred, pred_len, token, token_len, blank=0):\n    '''\n    :param pred: (Time, batch, voca_size+1)\n    :param pred_len: (batch)\n    :param token: (batch, U)\n    :param token_len: (batch)\n    '''\n    Time, batch = pred.size(0), pred.size(1)\n    U = token.size(1)\n    eps_nan = -1e8\n\n    # token_with_blank\n    token_with_blank = T.cat((T.zeros(batch, U, 1).type(longX), token[:, :, None]), dim=2).view(batch, -1)    # (batch, 2U)\n    token_with_blank = T.cat((token_with_blank, T.zeros(batch, 1).type(longX)), dim=1)  # (batch, 2U+1)\n    length = token_with_blank.size(1)\n\n    pred = pred[T.arange(0, Time).type(longX)[:, None, None], T.arange(0, batch).type(longX)[None, :, None], token_with_blank[None, :]]  # (T, batch, 2U+1)\n\n    # recurrence relation\n    sec_diag = T.cat((T.zeros((batch, 2)).type(floatX), T.ne(token_with_blank[:, :-2], token_with_blank[:, 2:]).type(floatX)), dim=1) * T.ne(token_with_blank, blank).type(floatX)\t# (batch, 2U+1)\n    recurrence_relation = (m_eye(length) + m_eye(length, k=1)).repeat(batch, 1, 1) + m_eye(length, k=2).repeat(batch, 1, 1) * sec_diag[:, None, :]\t# (batch, 2U+1, 2U+1)\n    recurrence_relation = eps_nan * (T.ones_like(recurrence_relation) - recurrence_relation)\n\n    # alpha\n    alpha_t = T.cat((pred[0, :, :2], T.ones(batch, 2*U-1).type(floatX)*eps_nan), dim=1) # (batch, 2U+1)\n    probability = alpha_t[None] # (1, batch, 2U+1)\n\n    # dynamic programming\n    # (T, batch, 2U+1)\n    for t in T.arange(1, Time).type(longX):\n        alpha_t = log_batch_dot(alpha_t, recurrence_relation) + pred[t]\n        probability = T.cat((probability, alpha_t[None]), dim=0)\n\n    labels_2 = probability[pred_len-1, T.arange(batch).type(longX), 2*token_len-1]\n    labels_1 = probability[pred_len-1, T.arange(batch).type(longX), 2*token_len]\n    labels_prob = log_sum_exp(labels_2, labels_1)\n#     pdb.set_trace()\n\n    cost = -labels_prob\n    return cost\n\ndef ctc_cost(out, targets, sizes, target_sizes):\n#    A batched version for uni_alpha_cost\n#    param out: (Time, batch, voca_size+1)\n#    param targets: targets without splited\n#    param sizes: size for out (N)\n#    param target_sizes: size for targets (N)\n\n    Time = out.size(0)\n    pred = T.nn.functional.log_softmax(out, dim=-1)\n\n    offset = 0\n    batch = target_sizes.size(0)\n    target_max = target_sizes.max().item()\n    target = T.zeros(batch, target_max).type(longX)\n\n    for index, (target_size, size) in enumerate(zip(target_sizes, sizes)):\n        target[index, :target_size.item()] = targets[offset: offset+target_size.item()].data\n        offset += target_size.item()\n\n    if not cuda:\n        costs = ctc_loss_log(pred.cpu(), sizes.data.type(longX), target, target_sizes.data.type(longX))\n    else:\n        costs = ctc_loss_log(pred, sizes.data.type(longX), target, target_sizes.data.type(longX))\n    return costs.sum()\n\ndef test_seg_ctc(use_mine=True):\n    # (T, voca_size+1)\n    pred_np = np.array([[0.5, 0.4, 0.1], [0.3, 0.1, 0.6], [0.7, 0.2, 0.1], [0.3, 0.5, 0.2]])[:, None]\n    pred_np = np.log(np.tile(pred_np, (1,2,1)))\n    # (U)\n    token_np = np.array([2, 2, 1, 2])\n\n    pred = Variable(floatX(pred_np), requires_grad=True)\n    token = Variable(T.IntTensor(token_np))\n    sizes = Variable(T.IntTensor(np.array([4, 4])))\n    target_sizes = Variable(T.IntTensor(np.array([2, 2])))\n\n    for i in range(40):\n        if use_mine:\n            cost = ctc_cost(pred, token, sizes, target_sizes)\n            print(cost.data.item())\n        else:\n            from warpctc_pytorch import CTCLoss\n            criterion = CTCLoss().cuda()\n            cost = criterion(pred, token, sizes, target_sizes)\n            print(cost.data.item())\n\n        optimizer = T.optim.SGD([pred], lr=3e-2, momentum=0.9, nesterov=True)\n        optimizer.zero_grad()\n        cost.backward()\n        optimizer.step()\n\nif __name__ == '__main__':\n    print('_________')\n    test_seg_ctc(use_mine=True)", "meta": {"hexsha": "bc215eab71149d4dead33e1308c7150872c21674", "size": 7937, "ext": "py", "lang": "Python", "max_stars_repo_path": "Recognition/pytorch_enctc/m_ctc.py", "max_stars_repo_name": "MengLcool/Ac-OCR", "max_stars_repo_head_hexsha": "370152cc33995f41ee79374b3f5d62e94fea09d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-11T10:24:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-11T10:24:58.000Z", "max_issues_repo_path": "Recognition/pytorch_enctc/m_ctc.py", "max_issues_repo_name": "MengLcool/Oc-OCR", "max_issues_repo_head_hexsha": "370152cc33995f41ee79374b3f5d62e94fea09d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Recognition/pytorch_enctc/m_ctc.py", "max_forks_repo_name": "MengLcool/Oc-OCR", "max_forks_repo_head_hexsha": "370152cc33995f41ee79374b3f5d62e94fea09d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4330357143, "max_line_length": 194, "alphanum_fraction": 0.6221494267, "include": true, "reason": "import numpy", "num_tokens": 2614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3629692124105862, "lm_q1q2_score": 0.1956343151155299}}
{"text": "\"\"\"\nFile: pylinex/nonlinear/loglikelihood/Loglikelihood.py\nAuthor: Keith Tauscher\nDate: 25 Feb 2018\n\nDescription: File containing a base class representing a likelihood that can be\n             evaluated using a data vector and a Model object (and possibly\n             other things, depending on the subclass).\n\"\"\"\nimport numpy as np\nimport numpy.linalg as la\nfrom distpy import TransformList, GaussianDistribution, WindowedDistribution,\\\n    DistributionSet\nfrom ..util import Savable, Loadable\n\ncannot_instantiate_loglikelihood_error = NotImplementedError(\"The \" +\\\n    \"Loglikelihood class cannot be instantiated directly!\")\n\nclass Loglikelihood(Savable, Loadable):\n    \"\"\"\n    Abstract class representing a likelihood which is Gaussian in the data.\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        \"\"\"\n        Initializer throws error because Loglikelihood is supposed to be an\n        abstract class that is not directly instantiated.\n        \"\"\"\n        raise cannot_instantiate_loglikelihood_error\n    \n    @property\n    def parameters(self):\n        \"\"\"\n        Property storing the names of the parameters of the model defined by\n        this likelihood.\n        \"\"\"\n        raise cannot_instantiate_loglikelihood_error\n    \n    @property\n    def num_parameters(self):\n        \"\"\"\n        Property storing the number of parameters needed by the Model at the\n        heart of this Loglikelihood.\n        \"\"\"\n        if not hasattr(self, '_num_parameters'):\n            self._num_parameters = len(self.parameters)\n        return self._num_parameters\n    \n    def fill_hdf5_group(self, group, *args, **kwargs):\n        \"\"\"\n        Fills the given hdf5 group with information about this Loglikelihood.\n        \n        group: the group to fill with information about this Loglikelihood\n        \"\"\"\n        raise cannot_instantiate_loglikelihood_error\n    \n    @staticmethod\n    def load_from_hdf5_group(group):\n        \"\"\"\n        Loads a Loglikelihood object from an hdf5 file group in which it was\n        previously saved.\n        \n        group: the hdf5 file group from which to load a Loglikelihood object\n        \n        returns: the Loglikelihood object loaded from the given hdf5 file group\n        \"\"\"\n        raise cannot_instantiate_loglikelihood_error\n    \n    def check_parameter_dimension(self, pars):\n        \"\"\"\n        Checks to ensure that the given array is 1D and has one element for\n        each parameter. The only thing this function does is throw an error if\n        the array is the wrong shape.\n        \n        pars: array to check\n        \"\"\"\n        if pars.shape != (self.num_parameters,):\n            raise ValueError(\"The array of parameters given to this \" +\\\n                \"Loglikelihood object was not of the correct size.\")\n    \n    def __call__(self, pars, return_negative=False):\n        \"\"\"\n        Gets the value of this Loglikelihood at the given parameters.\n        \"\"\"\n        raise cannot_instantiate_loglikelihood_error\n    \n    @property\n    def gradient_computable(self):\n        \"\"\"\n        Property storing whether the gradient of this Loglikelihood can be\n        computed.\n        \"\"\"\n        raise cannot_instantiate_loglikelihood_error\n    \n    def gradient(self, pars, return_negative=False):\n        \"\"\"\n        Computes the gradient of this Loglikelihood for minimization purposes.\n        \n        pars: value of the parameters at which to evaluate the gradient\n        return_negative: if true, the negative of the gradient of the\n                         loglikelihood is returned (this is useful for times\n                         when the loglikelihood must be maximized since scipy\n                         optimization functions only deal with minimization\n        \n        returns: 1D numpy.ndarray of length num_parameters containing gradient\n                 of loglikelihood value\n        \"\"\"\n        if self.gradient_computable:\n            return self.auto_gradient(pars, return_negative=return_negative)\n        else:\n            raise NotImplementedError(\"gradient is not computable in an \" +\\\n                \"exact form. Use auto_gradient instead to do a numerical \" +\\\n                \"approximation.\")\n    \n    def auto_gradient(self, pars, return_negative=False, differences=1e-6,\\\n        transform_list=None):\n        \"\"\"\n        Computes the gradient of this Loglikelihood for minimization purposes.\n        \n        pars: value of the parameters at which to evaluate the gradient\n        return_negative: if true, the negative of the gradient of the\n                         loglikelihood is returned (this is useful for times\n                         when the loglikelihood must be maximized since scipy\n                         optimization functions only deal with minimization\n        differences: either single number or 1D array of numbers to use as the\n                     numerical difference in parameter. Default: 10^(-6)\n        transform_list: TransformList object (or something which can be cast to\n                        one) defining the transforms to apply to the parameters\n                        before computing the gradient. Default: None, parameter\n                        space is not transformed\n        \n        returns: 1D numpy.ndarray of length num_parameters containing gradient\n                 of loglikelihood value\n        \"\"\"\n        raise cannot_instantiate_loglikelihood_error\n    \n    @property\n    def hessian_computable(self):\n        \"\"\"\n        Property storing whether the hessian of this Loglikelihood can be\n        computed. The hessian of this Loglikelihood is computable as long as\n        the model's gradient and hessian are computable.\n        \"\"\"\n        raise cannot_instantiate_loglikelihood_error\n    \n    def hessian(self, pars, return_negative=False):\n        \"\"\"\n        Computes the hessian of this Loglikelihood for minimization purposes.\n        \n        pars: value of the parameters at which to evaluate the hessian\n        return_negative: if true, the negative of the hessian of the\n                         loglikelihood is returned (this is useful for times\n                         when the loglikelihood must be maximized since scipy\n                         optimization functions only deal with minimization\n        \n        returns: square 2D numpy.ndarray of side length num_parameters\n                 containing hessian of loglikelihood value\n        \"\"\"\n        if self.hessian_computable:\n            return self.auto_hessian(pars, return_negative=return_negative)\n        else:\n            raise NotImplementedError(\"hessian is not computable in an \" +\\\n                \"exact form. Use auto_hessian instead to do a numerical \" +\\\n                \"approximation.\")\n    \n    def auto_hessian(self, pars, return_negative=False,\\\n        larger_differences=1e-5, smaller_differences=1e-6,\\\n        transform_list=None):\n        \"\"\"\n        Computes the hessian of this Loglikelihood for minimization purposes.\n        \n        pars: value of the parameters at which to evaluate the hessian\n        return_negative: if true, the negative of the hessian of the\n                         loglikelihood is returned (this is useful for times\n                         when the loglikelihood must be maximized since scipy\n                         optimization functions only deal with minimization\n        larger_differences: either single number or 1D array of numbers to use\n                            as the numerical difference in parameters.\n                            Default: 10^(-5). This is the amount by which the\n                            parameters are shifted between evaluations of the\n                            gradient. Only used if gradient is not explicitly\n                            computable.\n        smaller_differences: either single_number or 1D array of numbers to use\n                             as the numerical difference in parameters.\n                             Default: 10^(-6). This is the amount by which the\n                             parameters are shifted during each approximation\n                             of the gradient. Only used if hessian is not\n                             explicitly computable\n        transform_list: TransformList object (or something which can be cast to\n                        one) defining the transforms to apply to the parameters\n                        before computing the gradient. Default: None, parameter\n                        space is not transformed\n        \n        returns: square 2D numpy.ndarray of side length num_parameters\n                 containing hessian of loglikelihood value\n        \"\"\"\n        raise cannot_instantiate_loglikelihood_error\n    \n    def __eq__(self, other):\n        \"\"\"\n        Checks if self is equal to other.\n        \n        other: a Loglikelihood object to check for equality\n        \n        returns: True if other and self have the same properties\n        \"\"\"\n        raise NotImplementedError(\"The __eq__ magic method must be defined \" +\\\n            \"by each subclass of Loglikelihood individually. The class \" +\\\n            \"being used does not have the method defined.\")\n    \n    def __ne__(self, other):\n        \"\"\"\n        Checks if self is equal to other.\n        \n        other: a Loglikelihood object to check for equality\n        \n        returns: True if other and self do not have the same properties\n        \"\"\"\n        return (not self.__eq__(other))\n    \n    def fisher_information(self, maximum_likelihood_parameters,\\\n        larger_differences=1e-5, smaller_differences=1e-6,\\\n        transform_list=None):\n        \"\"\"\n        Calculates the Fisher information matrix of this likelihood assuming\n        that the argument associated with the maximum of this likelihood is\n        reasonably approximated by the given parameters.\n        \n        maximum_likelihood_parameters: the maximum likelihood  parameter vector\n                                       (or some approximation of it)\n        larger_differences: either single number or 1D array of numbers to use\n                            as the numerical difference in parameters.\n                            Default: 10^(-5). This is the amount by which the\n                            parameters are shifted between evaluations of the\n                            gradient. Only used if gradient is not explicitly\n                            computable.\n        smaller_differences: either single_number or 1D array of numbers to use\n                             as the numerical difference in parameters.\n                             Default: 10^(-6). This is the amount by which the\n                             parameters are shifted during each approximation\n                             of the gradient. Only used if hessian is not\n                             explicitly computable\n        transform_list: TransformList object (or something which can be cast to\n                        one) defining the transforms to apply to the parameters\n                        before computing the gradient. Default: None, parameter\n                        space is not transformed. No matter what,\n                        maximum_likelihood_parameters should be the parameters\n                        that maximize the likelihood when plugged into the\n                        model of this likelihood untransformed.\n        \n        returns: numpy.ndarray of shape (num_parameters, num_parameters)\n                 containing the Fisher information matrix\n        \"\"\"\n        return self.auto_hessian(maximum_likelihood_parameters,\\\n            larger_differences=larger_differences,\\\n            smaller_differences=smaller_differences,\\\n            transform_list=transform_list, return_negative=True)\n    \n    def parameter_covariance_fisher_formalism(self,\\\n        maximum_likelihood_parameters, transform_list=None,\\\n        max_standard_deviations=np.inf, larger_differences=1e-5,\\\n        smaller_differences=1e-6):\n        \"\"\"\n        Finds the parameter covariance assuming maximum_likelihood_parameters\n        contains a reasonable approximation of the true maximum likelihood\n        parameter vector.\n        \n        maximum_likelihood_parameters: the maximum likelihood parameter vector\n                                       (or some approximation of it), given in\n                                       untransformed space, no matter the value\n                                       of the transform_list argument\n        transform_list: TransformList object (or something which can be cast to\n                        one) defining the transforms to apply to the parameters\n                        before computing the gradient. Default: None, parameter\n                        space is not transformed. No matter what,\n                        maximum_likelihood_parameters should be the parameters\n                        that maximize the likelihood when plugged into the\n                        model of this likelihood untransformed.\n        max_standard_deviations: single value or array of values containing the\n                                 maximum allowable standard deviations of each\n                                 parameter. This will stop the covariance from\n                                 producing extremely wide results in the case\n                                 of an unconstrained parameter. The default\n                                 value is numpy.inf, which causes this\n                                 correction to be unimportant in all cases.\n        larger_differences: either single number or 1D array of numbers to use\n                            as the numerical difference in parameters.\n                            Default: 10^(-5). This is the amount by which the\n                            parameters are shifted between evaluations of the\n                            gradient. Only used if gradient is not explicitly\n                            computable.\n        smaller_differences: either single_number or 1D array of numbers to use\n                             as the numerical difference in parameters.\n                             Default: 10^(-6). This is the amount by which the\n                             parameters are shifted during each approximation\n                             of the gradient. Only used if hessian is not\n                             explicitly computable\n        \n        returns: numpy.ndarray of shape (num_parameters, num_parameters)\n                 containing the inverse Fisher information matrix\n        \"\"\"\n        inverse_covariance = self.fisher_information(\\\n            maximum_likelihood_parameters, transform_list=transform_list,\\\n            larger_differences=larger_differences,\\\n            smaller_differences=smaller_differences)\n        if np.any(max_standard_deviations == 0):\n            raise ValueError(\"At least one of the max_standard deviations \" +\\\n                \"was set to 0, which implies the existence of at least one \" +\\\n                \"element in the null space of the covariance matrix, which \" +\\\n                \"does not make sense.\")\n        max_standard_deviations =\\\n            max_standard_deviations * np.ones(self.num_parameters)\n        inverse_covariance = inverse_covariance +\\\n            np.diag(np.power(max_standard_deviations, -2))\n        return la.inv(inverse_covariance)\n    \n    def parameter_distribution_fisher_formalism(self,\\\n        maximum_likelihood_parameters, transform_list=None,\\\n        max_standard_deviations=np.inf,\\\n        prior_to_impose_in_transformed_space=None,\\\n        larger_differences=1e-5, smaller_differences=1e-6,\\\n        covariance_reduction_factor=1):\n        \"\"\"\n        Finds the parameter distribution assuming maximum_likelihood_parameters\n        contains a reasonable approximation of the true maximum likelihood\n        parameter vector.\n        \n        maximum_likelihood_parameters: the maximum likelihood  parameter vector\n                                       (or some approximation of it)\n        transform_list: TransformList object (or something which can be cast to\n                        one) defining the transforms to apply to the parameters\n                        before computing the gradient. Default: None, parameter\n                        space is not transformed. No matter what,\n                        maximum_likelihood_parameters should be the parameters\n                        that maximize the likelihood when plugged into the\n                        model of this likelihood untransformed.\n        max_standard_deviations: single value or array of values containing the\n                                 maximum allowable standard deviations of each\n                                 parameter. This will stop the covariance from\n                                 producing extremely wide results in the case\n                                 of an unconstrained parameter. The default\n                                 value is numpy.inf, which causes this\n                                 correction to be unimportant in all cases.\n        prior_to_impose_in_transformed_space: if None (default), no prior is\n                                                                 imposed and a\n                                                                 Gaussian is\n                                                                 returned\n                                                                 through the\n                                                                 Fisher matrix\n                                                                 formalism\n                                              otherwise, prior_to_impose should\n                                                         be a Distribution\n                                                         object whose log_value\n                                                         function returns\n                                                         -np.inf in disallowed\n                                                         regions. The prior has\n                                                         no effect inside the\n                                                         region in which it is\n                                                         finite.\n        larger_differences: either single number or 1D array of numbers to use\n                            as the numerical difference in parameters.\n                            Default: 10^(-5). This is the amount by which the\n                            parameters are shifted between evaluations of the\n                            gradient. Only used if gradient is not explicitly\n                            computable.\n        smaller_differences: either single_number or 1D array of numbers to use\n                             as the numerical difference in parameters.\n                             Default: 10^(-6). This is the amount by which the\n                             parameters are shifted during each approximation\n                             of the gradient. Only used if hessian is not\n                             explicitly computable\n        covariance_reduction_factor: factor by which to decrease the magnitude\n                                     of the covariance distribution: default 1\n        \n        returns: DistributionSet object containing GaussianDistribution object\n                 approximating distribution in transformed space\n        \"\"\"\n        transform_list = TransformList.cast(transform_list,\\\n            num_transforms=self.num_parameters)\n        mean = transform_list(maximum_likelihood_parameters)\n        covariance = self.parameter_covariance_fisher_formalism(\\\n            maximum_likelihood_parameters, transform_list=transform_list,\\\n            max_standard_deviations=max_standard_deviations,\\\n            larger_differences=larger_differences,\\\n            smaller_differences=smaller_differences) /\\\n            covariance_reduction_factor\n        distribution = GaussianDistribution(mean, covariance)\n        if type(prior_to_impose_in_transformed_space) is not type(None):\n            distribution = WindowedDistribution(distribution,\\\n                prior_to_impose_in_transformed_space)\n        return\\\n            DistributionSet([(distribution, self.parameters, transform_list)])\n\n", "meta": {"hexsha": "1bff1e377bfd53da8ef0a65fac6643a2d0c2b050", "size": 20406, "ext": "py", "lang": "Python", "max_stars_repo_path": "pylinex/loglikelihood/Loglikelihood.py", "max_stars_repo_name": "CU-NESS/pylinex", "max_stars_repo_head_hexsha": "b6f342595b6a154e129eb303782e5268088f34d5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pylinex/loglikelihood/Loglikelihood.py", "max_issues_repo_name": "CU-NESS/pylinex", "max_issues_repo_head_hexsha": "b6f342595b6a154e129eb303782e5268088f34d5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pylinex/loglikelihood/Loglikelihood.py", "max_forks_repo_name": "CU-NESS/pylinex", "max_forks_repo_head_hexsha": "b6f342595b6a154e129eb303782e5268088f34d5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.9236641221, "max_line_length": 79, "alphanum_fraction": 0.5911986671, "include": true, "reason": "import numpy", "num_tokens": 3420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.195634311401413}}
{"text": "\"\"\" Build the resource task network for steel plants.\n\nNotations\n    Resource Category\n    EAF     -   equipment unit in the EAF stage (first stage)\n    EAF1    -   (if multiple units in this stage) one equipment unit in the EAF stage\n    H_A_S3  -   (RTN1) intermediate product after stage 3\n    H_B_S4  -   (RTN1) intermediate product before stage 4\n    H_A_LF2 -   (RTN2) intermediate product before unit LF2\n    EN      -   electric energy\n    Task Category\n    EAF     -   process task by unit EAF, i.e. melting\n    TR_S3   -   (RTN1) transportation task between stage 3 and stage 4\n    TR_LF2_CC1    -   (RTN2) transportation task between units LF2 and CC1\n\n__author__ = xxxzhang\n\"\"\"\n\nfrom collections import OrderedDict\nimport math\n\nimport numpy as np\nimport json\nimport logging\n\nlog = logging.getLogger('steel')\n\n\nclass PlantRtnBuilder():\n    \"\"\" resources, tasks, and their interaction networks for steel plant scheduling\n    \"\"\"\n\n    def __init__(self, plant):\n        self.rtn_t0 = plant['rtn_t0']  # time grid interval for RTN\n        self.price_energy = []\n        for price in plant['energy_price']:\n            self.price_energy += [price] * (60 / self.rtn_t0)\n        self.num_t = 24 * 60 / self.rtn_t0\n        self.num_stage = len(plant['stage2units'].keys())\n        self.num_groups = len(plant['group2heats'].keys())\n        self.num_heats = 0\n        for group, heats in plant['group2heats'].items():\n            self.num_heats += len(heats)\n\n        # basic information\n        self.group2heats = plant['group2heats']\n        self.stage2units = plant['stage2units']\n        self.time_trans_max = plant['trans_time_max']\n        self.time_trans = plant['trans_time']\n        self.time_setup = plant['setup_time']\n        self.time_process = plant['equip2process_time']\n\n        # resources and tasks\n        # todo instead using arrays, using dicts in tasks/res\n        [self.resources, self.num_resources] = self.build_resources(plant)\n        [self.tasks, self.num_tasks] = self.build_tasks(plant)\n        [self.task_duration, self.task_cleanup_duration] = self.cal_task_duration(plant)\n        [self.rtn_profile, self.heat_consume_time_in_group, self.heat_generate_time_in_group] \\\n            = self.build_resource_task_profile(plant)\n\n        # redundant information\n        self.equip2num = {}\n        for unit2num in self.stage2units.values():\n            for unit, num in unit2num.items():\n                self.equip2num[unit] = num\n        self.maxPower = sum([float(plant['equip2mw'][unit])*num for unit, num in self.equip2num.items()])\n        self.casters = [unit for unit, num in self.stage2units['4'].items()]\n        self.heat_sequence = ['EAF', 'TR_EA', 'AOD', 'TR_AL', 'LF', 'TR_LC']\n        self.main_process = ['EAF', 'AOD', 'LF', 'CC1', 'CC2']\n\n        log.debug('TaskCategory : (Task, Duration)')\n        for task_type, task_list in self.tasks.items():\n            log.debug('%s : %s' % (task_type, ','.join('(%s,%d)' % (x, self.task_duration[x]) for x in task_list)))\n        log.debug('ResourceCategory : Resource')\n        for res_cat, res_list in self.resources.items():\n            log.debug('%s : %s' % (res_cat, ','.join(str(x) for x in res_list)))\n        # log.info('ResourceTaskInteraction')\n        # log.info(json.dumps(self.rtn_profile, indent=2))\n\n    def build_resources(self, plant):\n        # todo, do you need the reverse mapping\n        res_cat2idx = OrderedDict()\n        r_idx = 1\n        # equipment resources\n        for stage in range(1, self.num_stage + 1):\n            for unit in plant['stage2units'][str(stage)].keys():\n                res_cat2idx[unit] = [r_idx]\n                r_idx += 1\n        # intermediate products and final products, A - after, B - before\n        for stage in range(1, self.num_stage+1):\n            res_cat2idx['H_A_S%s' % stage] = range(r_idx, r_idx + self.num_heats)\n            r_idx += self.num_heats\n            if int(stage) == 1:\n                continue\n            res_cat2idx['H_B_S%s' % stage] = range(r_idx, r_idx + self.num_heats)\n            r_idx += self.num_heats\n        # energy resource\n        res_cat2idx['EN'] = [r_idx]\n        res_num = r_idx\n        return [res_cat2idx, res_num]\n\n    def build_tasks(self, plant):\n        tasks = OrderedDict()\n        i_idx = 1\n        for stage in range(1, self.num_stage + 1):\n            for unit in plant['stage2units'][str(stage)].keys():\n                if int(stage) == 4:\n                    tasks[unit] = range(i_idx, i_idx + self.num_groups)\n                    i_idx += self.num_groups\n                else:\n                    tasks[unit] = range(i_idx, i_idx + self.num_heats)\n                    i_idx += self.num_heats\n                    tasks['TR_S%s' % stage] = range(i_idx, i_idx + self.num_heats)\n                    i_idx += self.num_heats\n        task_num = i_idx - 1\n        return [tasks, task_num]\n\n    def cal_task_duration(self, plant):\n        \"\"\"calculate time slots duration of tasks\"\"\"\n        task_duration = dict()\n        task_cleanup_duration = dict()\n        for heat in range(1, self.num_heats + 1):\n            for task_type in ['EAF', 'AOD', 'LF']:\n                task_duration[self.tasks[task_type][heat - 1]] = \\\n                    int(math.ceil(float(plant['equip2process_time'][task_type][str(heat)])/self.rtn_t0))\n            for task_type in ['TR_S1', 'TR_S2', 'TR_S3']:\n                task_duration[self.tasks[task_type][heat - 1]] = \\\n                    int(math.ceil(float(plant['trans_time'][task_type])/self.rtn_t0))\n        for group in range(1, self.num_groups + 1):\n            for task_type in ['CC1', 'CC2']:\n                cast_time = [plant['equip2process_time'][task_type][str(heat)] for heat in self.group2heats[str(group)]]\n                total_time = float(sum(cast_time))\n                task_duration[self.tasks[task_type][group - 1]] = int(math.ceil(total_time/self.rtn_t0))\n                total_time = float(sum(cast_time) + self.time_setup[task_type])\n                task_cleanup_duration[self.tasks[task_type][group - 1]] = int(math.ceil(total_time/self.rtn_t0))\n        return task_duration, task_cleanup_duration\n\n    def build_resource_task_profile(self, plant):\n        \"\"\"calculate resource task profile, i.e. the interactions between resource and task\"\"\"\n        rtn_profile = dict()\n        for res_category, res_idxes in self.resources.items():\n            for res_idx in res_idxes:\n                rtn_profile[res_idx] = dict()\n        # equipment usage\n        for stage in range(1, self.num_stage + 1):\n            for unit in plant['stage2units'][str(stage)].keys():\n                res = self.resources[unit][0]\n                for task in self.tasks[unit]:\n                    rtn_profile[res][task] = [-1] + [0] * (self.task_duration[task] - 1) + [1]\n                    if stage == 4:\n                        rtn_profile[res][task] = [-1] + [0] * (self.task_cleanup_duration[task] - 1) + [1]\n        # heat consumption and generation for the first three stages\n        for heat_idx in range(0, self.num_heats):\n            # process task generate intermediate heat H_A_S (after stage)\n            for task_cat, res_cat in [('EAF', 'H_A_S1'), ('AOD', 'H_A_S2'), ('LF', 'H_A_S3')]:\n                task = self.tasks[task_cat][heat_idx]\n                resource = self.resources[res_cat][heat_idx]\n                rtn_profile[resource][task] = [0] * self.task_duration[task] + [1]\n            # process task consume intermediate heat H_B_S (before stage)\n            for task_cat, res_cat in [('AOD', 'H_B_S2'), ('LF', 'H_B_S3')]:\n                task = self.tasks[task_cat][heat_idx]\n                resource = self.resources[res_cat][heat_idx]\n                rtn_profile[resource][task] = [-1] + [0] * self.task_duration[task]\n            # transfer task transports heat\n            for task_cat, res_cat in [('TR_S1', ['H_A_S1', 'H_B_S2']),\n                                      ('TR_S2', ['H_A_S2', 'H_B_S3']),\n                                      ('TR_S3', ['H_A_S3', 'H_B_S4'])]:\n                task = self.tasks[task_cat][heat_idx]\n                resource1 = self.resources[res_cat[0]][heat_idx]\n                rtn_profile[resource1][task] = [-1] + [0] * self.task_duration[task]\n                resource2 = self.resources[res_cat[1]][heat_idx]\n                rtn_profile[resource2][task] = [0] * self.task_duration[task] + [1]\n        # group-heat consumption and generation\n        heat_consume_time_in_group = dict()\n        heat_generate_time_in_group = dict()\n        for unit in plant['stage2units']['4']:\n            heat_consume_time_in_group[unit] = dict()\n            heat_generate_time_in_group[unit] = dict()\n            for group, heats in self.group2heats.items():\n                # todo because the task numbers are stored in an array, can we do a better mapping?\n                task = self.tasks[unit][int(group)-1]\n                duration = 0\n                for heat in heats:\n                    consume_time = int(math.floor(duration/self.rtn_t0))\n                    resource = self.resources['H_B_S4'][heat - 1]\n                    rtn_profile[resource][task] = [0] * (self.task_duration[task] + 1)\n                    rtn_profile[resource][task][consume_time] = -1\n                    duration += plant['equip2process_time'][unit][str(heat)]\n                    generate_time = int(math.ceil(duration/self.rtn_t0))\n                    resource = self.resources['H_A_S4'][heat - 1]\n                    rtn_profile[resource][task] = [0] * (self.task_duration[task] + 1)\n                    rtn_profile[resource][task][generate_time] = 1\n                    heat_consume_time_in_group[unit][heat] = consume_time\n                    heat_generate_time_in_group[unit][heat] = generate_time\n        # energy usage\n        for stage, units in plant['stage2units'].items():\n            stage = int(stage)\n            for unit in units.keys():\n                norm_mw = float(plant['equip2mw'][unit])\n                for task in self.tasks[unit]:\n                    total_energy = 0\n                    if stage < 4:\n                        heat = task - self.tasks[unit][0] + 1\n                        total_energy = norm_mw * plant['equip2process_time'][unit][str(heat)] / 60\n                    elif stage == 4:\n                        group = task - self.tasks[unit][0] + 1\n                        for heat in self.group2heats[str(group)]:\n                            total_energy += norm_mw * plant['equip2process_time'][unit][str(heat)] / 60\n                    profile = [norm_mw * self.rtn_t0 / 60] * (self.task_duration[task] - 1)\n                    profile = profile + [total_energy - sum(profile)] + [0]\n                    rtn_profile[self.resources['EN'][0]][task] = profile\n        return rtn_profile, heat_consume_time_in_group, heat_generate_time_in_group\n\n    def cal_initial_resource(self, res):\n        # todo, here needs reverse mapping\n        # only equipment initial value not zero\n        for stage, stage_units in self.stage2units.items():\n            for unit in stage_units.keys():\n                if res in self.resources[unit]:\n                    return stage_units[unit]\n        return 0\n\n    # todo delete this\n    def get_unit2num(self):\n        unit2num = dict()\n        for stage, units in self.stage2units.items():\n            for key, value in units.items():\n                unit2num[key] = value\n        return unit2num\n\n    def get_same_heats(self):\n        \"\"\"find heats which share same processing times\"\"\"\n        process_time = np.zeros((self.num_heats, len(self.main_process)))\n        for i in range(len(self.main_process)):\n            for heat_ in range(self.num_heats):\n                process_time[heat_, i] = self.time_process[self.main_process[i]][heat_ + 1]\n        visited = []\n        same_heat = dict()\n        for row in range(self.num_heats):\n            if row not in visited:\n                visited.append(row)\n                same_heat[row + 1] = [row + 1]\n                for row2 in range(row + 1, self.num_heats):\n                    if np.array_equal(process_time[row2], process_time[row]):\n                        same_heat[row + 1].append(row2 + 1)\n                        visited.append(row2)\n        return same_heat\n\n\nclass PlantRtn2Builder(PlantRtnBuilder):\n    \"\"\"Build RTN2 model.\"\"\"\n\n    def build_resources(self, plant):\n        res_cat2idx = OrderedDict()\n        r_idx = 1\n        # equipment resources\n        for stage in range(1, self.num_stage + 1):\n            for unit in plant['stage2units'][str(stage)].keys():\n                res_cat2idx[unit] = [r_idx]\n                r_idx += 1\n        # intermediate products, A - after, B - before\n        for stage in range(1, self.num_stage+1):\n            for unit in plant['stage2units'][str(stage)].keys():\n                if int(stage) != 1:\n                    res_cat2idx['H_B_%s' % unit] = range(r_idx, r_idx + self.num_heats)\n                    r_idx += self.num_heats\n                if int(stage) != 4:\n                    res_cat2idx['H_A_%s' % unit] = range(r_idx, r_idx + self.num_heats)\n                    r_idx += self.num_heats\n        # final products\n        res_cat2idx['H_FINAL'] = range(r_idx, r_idx + self.num_heats)\n        r_idx += self.num_heats\n        # energy resource\n        res_cat2idx['EN'] = [r_idx]\n        res_num = r_idx\n        return [res_cat2idx, res_num]\n\n    def build_tasks(self, plant):\n        tasks = OrderedDict()\n        i_idx = 1\n        for stage in range(1, self.num_stage + 1):\n            for unit in plant['stage2units'][str(stage)].keys():\n                if int(stage) == 4:\n                    # casting task\n                    tasks[unit] = range(i_idx, i_idx + self.num_groups)\n                    i_idx += self.num_groups\n                else:\n                    # process task for first 3 stages\n                    tasks[unit] = range(i_idx, i_idx + self.num_heats)\n                    i_idx += self.num_heats\n                    # transfer task\n                    for unit_2 in plant['stage2units'][str(stage+1)].keys():\n                        tasks['TR_%s_%s' % (unit, unit_2)] = range(i_idx, i_idx + self.num_heats)\n                        i_idx += self.num_heats\n        task_num = i_idx - 1\n        return [tasks, task_num]\n\n    def cal_task_duration(self, plant):\n        \"\"\"calculate time slots duration of tasks\"\"\"\n        task_duration = dict()\n        task_cleanup_duration = dict()\n        for heat in range(1, self.num_heats + 1):\n            for stage in range(1, self.num_stage):\n                for unit in plant['stage2units'][str(stage)].keys():\n                    # process task\n                    task_duration[self.tasks[unit][heat - 1]] = \\\n                        int(math.ceil(float(plant['equip2process_time'][unit][str(heat)])/self.rtn_t0))\n                    if stage == 4:\n                        continue\n                    # transfer task\n                    for unit_2 in plant['stage2units'][str(stage+1)].keys():\n                        transfer_task = 'TR_%s_%s' % (unit, unit_2)\n                        transfer = '%s-%s' % (unit, unit_2)\n                        task_duration[self.tasks[transfer_task][heat - 1]] = \\\n                            int(math.ceil(float(plant['trans_time'][transfer])/self.rtn_t0))\n        for group in range(1, self.num_groups + 1):\n            for task_type in ['CC1', 'CC2']:\n                cast_time = [plant['equip2process_time'][task_type][str(heat)] for heat in self.group2heats[str(group)]]\n                total_time = float(sum(cast_time))\n                task_duration[self.tasks[task_type][group - 1]] = int(math.ceil(total_time/self.rtn_t0))\n                total_time = float(sum(cast_time) + self.time_setup[task_type])\n                task_cleanup_duration[self.tasks[task_type][group - 1]] = int(math.ceil(total_time/self.rtn_t0))\n        return task_duration, task_cleanup_duration\n\n    def build_resource_task_profile(self, plant):\n        \"\"\"calculate resource task profile, i.e. the interactions between resource and task\"\"\"\n        rtn_profile = dict()\n        for res_category, res_indices in self.resources.items():\n            for res_idx in res_indices:\n                rtn_profile[res_idx] = dict()\n        # equipment usage\n        for stage in range(1, self.num_stage + 1):\n            for unit in plant['stage2units'][str(stage)].keys():\n                res = self.resources[unit][0]\n                for task in self.tasks[unit]:\n                    rtn_profile[res][task] = [-1] + [0] * (self.task_duration[task] - 1) + [1]\n                    if stage == 4:\n                        rtn_profile[res][task] = [-1] + [0] * (self.task_cleanup_duration[task] - 1) + [1]\n        # intermediate product with processes and transfers in the first 3 stages\n        for heat_idx in range(0, self.num_heats):\n            for stage in range(1, self.num_stage + 1):\n                if stage == 4:\n                    continue\n                for unit in plant['stage2units'][str(stage)].keys():\n                    # process task generate intermediate heat\n                    task_cat = unit\n                    res_cat = 'H_A_%s' % unit\n                    task = self.tasks[task_cat][heat_idx]\n                    resource = self.resources[res_cat][heat_idx]\n                    rtn_profile[resource][task] = [0] * self.task_duration[task] + [1]\n                    # process task consume intermediate heat\n                    if stage != 1:\n                        task_cat = unit\n                        res_cat = 'H_B_%s' % unit\n                        task = self.tasks[task_cat][heat_idx]\n                        resource = self.resources[res_cat][heat_idx]\n                        rtn_profile[resource][task] = [-1] + [0] * self.task_duration[task]\n                    # transfer task\n                    for unit_2 in plant['stage2units'][str(stage+1)].keys():\n                        task_cat = 'TR_%s_%s' % (unit, unit_2)\n                        res_from = 'H_A_%s' % unit\n                        res_to = 'H_B_%s' % unit_2\n                        task = self.tasks[task_cat][heat_idx]\n                        resource1 = self.resources[res_from][heat_idx]\n                        rtn_profile[resource1][task] = [-1] + [0] * self.task_duration[task]\n                        resource2 = self.resources[res_to][heat_idx]\n                        rtn_profile[resource2][task] = [0] * self.task_duration[task] + [1]\n        # group-heat consumption and generation\n        heat_consume_time_in_group = dict()\n        heat_generate_time_in_group = dict()\n        for unit in plant['stage2units']['4']:\n            heat_consume_time_in_group[unit] = dict()\n            heat_generate_time_in_group[unit] = dict()\n            for group, heats in self.group2heats.items():\n                task = self.tasks[unit][int(group)-1]\n                duration = 0\n                res_cat_before = 'H_B_%s' % unit\n                res_cat_after = 'H_FINAL'\n                for heat in heats:\n                    consume_time = int(math.floor(duration/self.rtn_t0))\n                    resource = self.resources[res_cat_before][heat - 1]\n                    rtn_profile[resource][task] = [0] * (self.task_duration[task] + 1)\n                    rtn_profile[resource][task][consume_time] = -1\n                    duration += plant['equip2process_time'][unit][str(heat)]\n                    generate_time = int(math.ceil(duration/self.rtn_t0))\n                    resource = self.resources[res_cat_after][heat - 1]\n                    rtn_profile[resource][task] = [0] * (self.task_duration[task] + 1)\n                    rtn_profile[resource][task][generate_time] = 1\n                    heat_consume_time_in_group[unit][heat] = consume_time\n                    heat_generate_time_in_group[unit][heat] = generate_time\n        # energy usage\n        for stage, units in plant['stage2units'].items():\n            stage = int(stage)\n            for unit in units.keys():\n                norm_mw = float(plant['equip2mw'][unit])\n                for task in self.tasks[unit]:\n                    total_energy = 0\n                    if stage < 4:\n                        heat = task - self.tasks[unit][0] + 1\n                        total_energy = norm_mw * plant['equip2process_time'][unit][str(heat)] / 60\n                    elif stage == 4:\n                        group = task - self.tasks[unit][0] + 1\n                        for heat in self.group2heats[str(group)]:\n                            total_energy += norm_mw * plant['equip2process_time'][unit][str(heat)] / 60\n                    profile = [norm_mw * self.rtn_t0 / 60] * (self.task_duration[task] - 1)\n                    profile = profile + [total_energy - sum(profile)] + [0]\n                    rtn_profile[self.resources['EN'][0]][task] = profile\n        return rtn_profile, heat_consume_time_in_group, heat_generate_time_in_group\n\n\n\n\n\n", "meta": {"hexsha": "7aa4c3d0f2879a2b5ca28bdecfca0ba85d0ffbfa", "size": 20945, "ext": "py", "lang": "Python", "max_stars_repo_path": "steel/build_plant_rtn.py", "max_stars_repo_name": "xxxzhang/IndustrialScheduling", "max_stars_repo_head_hexsha": "f5283bef78fe37462490549c182676aab7693fd0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-10-06T14:07:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-06T10:08:52.000Z", "max_issues_repo_path": "steel/build_plant_rtn.py", "max_issues_repo_name": "xxxzhang/IndustrialScheduling", "max_issues_repo_head_hexsha": "f5283bef78fe37462490549c182676aab7693fd0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "steel/build_plant_rtn.py", "max_forks_repo_name": "xxxzhang/IndustrialScheduling", "max_forks_repo_head_hexsha": "f5283bef78fe37462490549c182676aab7693fd0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2016-12-17T18:28:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-06T10:09:39.000Z", "avg_line_length": 50.5917874396, "max_line_length": 120, "alphanum_fraction": 0.5531630461, "include": true, "reason": "import numpy", "num_tokens": 4979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.19563431140141296}}
{"text": "import os\nimport sys\n\nimport gym\nimport eplus_env\n\n# Assign mpc_path to be the file path where mpc.torch is located.\nmpc_path = os.path.abspath(os.path.join(__file__, '..', '..' ))\nsys.path.insert(0, mpc_path)\n\nimport argparse\nfrom numpy import genfromtxt\nimport numpy as np\nimport pickle\nimport pandas as pd\n\nfrom diff_mpc import mpc\nfrom diff_mpc.mpc import QuadCost, LinDx\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nfrom utils import make_dict, R_func\n\nDEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nDEVICE\n\nparser = argparse.ArgumentParser(description='GruRL-Imitation Learning')\nparser.add_argument('--seed', type=int, default=42, metavar='N',\n                    help='random seed (default: 42)')\nparser.add_argument('--lr', type=float, default=5e-4, metavar='G',\n                    help='Learning Rate')\nparser.add_argument('--T', type=int, default=12, metavar='N',\n                    help='Planning Horizon (default: 12)')\nparser.add_argument('--step', type=int, default=900, metavar='N',\n                    help='Time Step in Simulation, Unit in Seconds (default: 900)') # 15 Minutes Now!\nparser.add_argument('--eta', type=int, default=5,\n                    help='Hyper Parameter for Balancing Comfort and Energy')\nparser.add_argument('--batch_size', type=int, default=256,\n                    help='Size of Mini-batch')\nparser.add_argument('--save_name', type=str, default='rl',\n                    help='save name')\nargs = parser.parse_args()\n\ntorch.manual_seed(args.seed)\n\n# Modify here: Outputs from EnergyPlus; Match the variables.cfg file.\nobs_name = [\"Outdoor Temp.\", \"Outdoor RH\", \"Wind Speed\", \"Wind Direction\", \"Diff. Solar Rad.\", \"Direct Solar Rad.\", \"Htg SP\", \"Clg SP\", \"Indoor Temp.\", \"Indoor Temp. Setpoint\", \"PPD\", \"Occupancy Flag\", \"Coil Power\", \"HVAC Power\", \"Sys In Temp.\", \"Sys In Mdot\", \"OA Temp.\", \"OA Mdot\", \"MA Temp.\", \"MA Mdot\", \"Sys Out Temp.\", \"Sys Out Mdot\"]\n\n# Modify here: Change based on the specific control problem\nstate_name = [\"Indoor Temp.\"]\ndist_name = [\"Outdoor Temp.\", \"Outdoor RH\", \"Wind Speed\", \"Wind Direction\", \"Diff. Solar Rad.\", \"Direct Solar Rad.\", \"Occupancy Flag\"]\n# Caveat: The RL agent controls the difference between Supply Air Temp. and Mixed Air Temp., i.e. the amount of heating from the heating coil. But, the E+ expects Supply Air Temp. Setpoint.\nctrl_name = [\"Delta T\"]\ntarget_name = [\"Indoor Temp. Setpoint\"]\n\nn_state = len(state_name)\nn_ctrl = len(ctrl_name)\nn_dist = len(dist_name)\n\neta = [0.1, args.eta] # eta: Weight for comfort during unoccupied and occupied mode\nstep = args.step # step: Timestep; Unit in seconds\nT = args.T # T: Number of timesteps in the planning horizon\ntol_eps = 90 # tol_eps: Total number of episodes; Each episode is a natural day\n\n# Read Historical Data\ndataset = pd.read_pickle(\"results/Sim-TMY2.pkl\")\ntarget = dataset[target_name]\ndisturbance = dataset[dist_name]\n# Min-Max Normalization\ndisturbance = (disturbance-disturbance.min())/(disturbance.max()-disturbance.min())\n\ndataset[\"Delta T\"] = dataset[\"Sys Out Temp.\"]-dataset[\"MA Temp.\"]\n\n# Train-Test Split\nn_samples = len(dataset)\nn_train = int(0.7*n_samples)\nn_test = n_samples - n_train\ntrain_set = dataset[:n_train]\ntest_set = dataset[n_train:]\n\nclass Learner():\n    def __init__(self, n_state, n_ctrl, n_dist, disturbance, target, u_upper, u_lower):\n        self.n_state = n_state\n        self.n_ctrl = n_ctrl\n        self.n_dist = n_dist\n        self.disturbance = disturbance\n        self.target = target\n        \n        # My Initial Guess\n        self.F_hat = torch.ones((self.n_state, self.n_state+self.n_ctrl))\n        self.F_hat[0, 0] = 0.9\n        self.F_hat[0, 1] = 0.3\n        self.F_hat = self.F_hat.double().requires_grad_()\n        \n        self.Bd_hat = np.random.rand(self.n_state, self.n_dist)\n        self.Bd_hat = torch.tensor(self.Bd_hat).requires_grad_()\n        \n        self.optimizer = optim.Adam([self.F_hat, self.Bd_hat], lr=args.lr)\n    \n        self.u_lower = u_lower * torch.ones(T, 1, n_ctrl).double()\n        self.u_upper = u_upper * torch.ones(T, 1, n_ctrl).double()\n    \n    def Cost_function(self, cur_time):\n        diag = torch.zeros(T, self.n_state + self.n_ctrl)\n        occupied = self.disturbance[\"Occupancy Flag\"][cur_time:cur_time + pd.Timedelta(seconds = (T-1) * step)]\n        occupied = np.array(occupied)\n        if len(occupied)<T:\n            occupied = np.pad(occupied, ((0, T-len(occupied)), ), 'edge')\n        eta_w_flag = torch.tensor([eta[int(flag)] for flag in occupied]).unsqueeze(1).double() # Tx1\n        diag[:, :n_state] = eta_w_flag\n        diag[:, n_state:] = 0.001\n        \n        C = []\n        for i in range(T):\n            C.append(torch.diag(diag[i]))\n        C = torch.stack(C).unsqueeze(1) # T x 1 x (m+n) x (m+n)\n        \n        x_target = self.target[cur_time : cur_time + pd.Timedelta(seconds = (T-1) * step)] # in pd.Series\n        x_target = np.array(x_target)\n        if len(x_target)<T:\n            x_target = np.pad(x_target, ((0, T-len(x_target)), (0, 0)), 'edge')\n        x_target = torch.tensor(x_target)\n        \n        c = torch.zeros(T, self.n_state+self.n_ctrl) # T x (m+n)\n        c[:, :n_state] = -eta_w_flag*x_target\n        c[:, n_state:] = 1 # L1-norm now! Check\n        c = c.unsqueeze(1) # T x 1 x (m+n)\n        return C, c\n    \n    def forward(self, x_init, C, c, cur_time):\n        dt = np.array(self.disturbance[cur_time : cur_time + pd.Timedelta(seconds = (T-2) * step)]) # T-1 x n_dist\n        if len(dt)<T-1:\n            dt = np.pad(dt, ((0, T-1-len(dt)), (0, 0)), 'edge')\n        dt = torch.tensor(dt).transpose(0, 1) # n_dist x T-1\n        \n        ft = torch.mm(self.Bd_hat, dt).transpose(0, 1) # T-1 x n_state\n        ft = ft.unsqueeze(1) # T-1 x 1 x n_state\n        \n        x_pred, u_pred, _ = mpc.MPC(n_state=self.n_state,\n                                    n_ctrl=self.n_ctrl,\n                                    T=T,\n                                    u_lower = self.u_lower,\n                                    u_upper = self.u_upper,\n                                    lqr_iter=20,\n                                    verbose=0,\n                                    exit_unconverged=False,\n                                    )(x_init, QuadCost(C.double(), c.double()),\n                                      LinDx(self.F_hat.repeat(T-1, 1, 1, 1),  ft))\n        \n        return x_pred[1, 0, :], u_pred[0, 0, :] # Dim.\n    \n    def predict(self, x_init, action, cur_time):\n        dt = np.array(self.disturbance.loc[cur_time]) # n_dist\n        dt = torch.tensor(dt).unsqueeze(1) # n_dist x 1\n        ft = torch.mm(self.Bd_hat, dt) # n_state x 1\n        tau = torch.stack([x_init, action]) # (n_state + n_ctrl) x 1\n        next_state  = torch.mm(self.F_hat, tau) + ft # n_state x 1\n        return next_state\n                                    \n    def update_parameters(self, x_true, u_true, x_pred, u_pred):\n        # Every thing in T x Dim.\n        state_loss = torch.mean((x_true.double() - x_pred)**2)\n        action_loss = torch.mean((u_true.double() - u_pred)**2)\n        \n        # Note: args.eta balances the importance between predicting states and predicting actions\n        traj_loss = args.eta*state_loss + action_loss\n        print(\"From state {}, From action {}\".format(state_loss, action_loss))\n        self.optimizer.zero_grad()\n        traj_loss.backward()\n        self.optimizer.step()\n        print(self.F_hat)\n        print(self.Bd_hat)\n        return state_loss.detach(), action_loss.detach()\n        \ndef evaluate_performance(x_true, u_true, x_pred, u_pred):\n    state_loss = torch.mean((x_true.double() - x_pred)**2)\n    action_loss = torch.mean((u_true.double() - u_pred)**2)\n    return state_loss, action_loss\n\ndef main():\n    dir = 'results'\n    if not os.path.exists(dir):\n        os.mkdir(dir)\n    \n    perf = []\n    n_step = 96 # n_step: Number of Steps per Day\n    numOfEpoches = 20\n    \n    timeStamp = []\n    record_name =[\"Learner nState\", \"Expert nState\", \"Learner action\", \"Expert action\"]\n    losses = []\n    losses_name = [\"train_state_loss\", \"train_action_loss\", \"val_state_loss\", \"val_action_loss\"]\n    \n    # Initialize the learner\n    u_upper = 5\n    u_lower = 0\n    learner = Learner(n_state, n_ctrl, n_dist, disturbance, target, u_upper, u_lower)\n     \n    for epoch in range(numOfEpoches):\n        x_true = []\n        u_true = []\n        x_pred = []\n        u_pred = []\n        \n        train_state_loss = []\n        train_action_loss = []\n        for i in range(n_train): # By number of entries in the historical data\n            idx = np.random.randint(n_train)\n            cur_time = train_set.index[idx]\n           \n            expert_moves = train_set[cur_time:cur_time+pd.Timedelta(seconds = step)]\n            if len(expert_moves)<2:\n                print(cur_time)\n                continue\n            \n            expert_state = torch.tensor(expert_moves[state_name].values).reshape(-1, n_state) # 2 x n_state\n            expert_action = torch.tensor(expert_moves[ctrl_name].values).reshape(-1, n_ctrl) # 2 x n_ctrl\n            x_true.append(expert_state[-1])\n            u_true.append(expert_action[0])\n\n            obs = train_set.loc[cur_time]\n            x_init = torch.tensor(np.array([obs[name] for name in state_name])).unsqueeze(0) # n_batch x n_state, i.e. 1 x n_state\n            C, c = learner.Cost_function(cur_time)\n            learner_state, learner_action = learner.forward(x_init, C, c, cur_time)\n                \n            # Predict next state based on expert's action\n            next_state = learner.predict(x_init.squeeze(0), expert_action[0], cur_time)\n            x_pred.append(next_state)\n            u_pred.append(learner_action)\n            \n            if (i % args.batch_size == 0) & (i>0):\n                x_true = torch.stack(x_true).reshape(-1, n_state)\n                u_true = torch.stack(u_true).reshape(-1, n_ctrl)\n                x_pred = torch.stack(x_pred).reshape(-1, n_state)\n                u_pred = torch.stack(u_pred).reshape(-1, n_ctrl)\n                b_state_loss, b_action_loss = learner.update_parameters(x_true, u_true, x_pred, u_pred)\n                train_state_loss.append(b_state_loss)\n                train_action_loss.append(b_action_loss)\n                x_true = []\n                u_true = []\n                x_pred = []\n                u_pred = []\n\n        # Evaluate performance at the end of each epoch\n        x_true = []\n        u_true = []\n        x_pred = []\n        u_pred = []\n        timeStamp = []\n        for idx in range(n_test):\n            cur_time = test_set.index[idx]\n            expert_moves = test_set[cur_time:cur_time+pd.Timedelta(seconds = step)]\n            if len(expert_moves)<2:\n                print(cur_time)\n                continue\n            expert_state = torch.tensor(expert_moves[state_name].values).reshape(-1, n_state) # 2 x n_state\n            expert_action = torch.tensor(expert_moves[ctrl_name].values).reshape(-1, n_ctrl) # 2 x n_ctrl\n            x_true.append(expert_state[-1])\n            u_true.append(expert_action[0])\n            \n            timeStamp.append(cur_time+pd.Timedelta(seconds = step))\n            \n            obs = test_set.loc[cur_time]\n            x_init = torch.tensor(np.array([obs[name] for name in state_name])).unsqueeze(0) # 1 x n_state\n            C, c = learner.Cost_function(cur_time)\n            learner_state, learner_action = learner.forward(x_init, C, c, cur_time)\n            next_state = learner.predict(x_init.squeeze(0), expert_action[0], cur_time)\n            x_pred.append(next_state.detach())\n            u_pred.append(learner_action.detach())\n            \n        x_true = torch.stack(x_true).reshape(-1, n_state)\n        u_true = torch.stack(u_true).reshape(-1, n_ctrl)\n        x_pred = torch.stack(x_pred).reshape(-1, n_state)\n        u_pred = torch.stack(u_pred).reshape(-1, n_ctrl)\n        val_state_loss, val_action_loss = evaluate_performance(x_true, u_true, x_pred, u_pred)\n        print(\"At Epoch {0}, the loss from the state is {1} and from the action is {2}\".format(epoch, val_state_loss, val_action_loss))\n        losses.append((np.mean(train_state_loss), np.mean(train_action_loss), val_state_loss, val_action_loss))\n       \n        record = pd.DataFrame(torch.cat((x_pred, x_true, u_pred, u_true), dim = 1).numpy(), index = np.array(timeStamp), columns = record_name)\n        record_df = pd.DataFrame(np.array(record), index = np.array(timeStamp), columns = record_name)\n        record_df.to_pickle(\"results/Imit_{}_{}.pkl\".format(args.save_name, epoch))\n        \n        # Save weights\n        F_hat = learner.F_hat.detach().numpy()\n        Bd_hat = learner.Bd_hat.detach().numpy()\n        np.save(\"results/weights/F-{}.npy\".format(epoch), F_hat)\n        np.save(\"results/weights/Bd-{}.npy\".format(epoch), Bd_hat)\n        \n    # Save losses at each epoch\n    losses_df = pd.DataFrame(np.array(losses), index = np.arange(numOfEpoches), columns = losses_name)\n    losses_df.to_pickle(\"results/Imit_loss_\"+args.save_name+\".pkl\")\n    \nif __name__ == '__main__':\n    main()\n\n", "meta": {"hexsha": "85eef625bf15d375af43e47ca138c4a253b3f0d6", "size": 13113, "ext": "py", "lang": "Python", "max_stars_repo_path": "agent/Imit_EP.py", "max_stars_repo_name": "gbaasch/Gnu-RL", "max_stars_repo_head_hexsha": "04621c3cd299eb0fa361d303699676d662aa147d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2019-12-16T17:52:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T08:25:12.000Z", "max_issues_repo_path": "agent/Imit_EP.py", "max_issues_repo_name": "gbaasch/Gnu-RL", "max_issues_repo_head_hexsha": "04621c3cd299eb0fa361d303699676d662aa147d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-11T19:06:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-11T19:06:25.000Z", "max_forks_repo_path": "agent/Imit_EP.py", "max_forks_repo_name": "gbaasch/Gnu-RL", "max_forks_repo_head_hexsha": "04621c3cd299eb0fa361d303699676d662aa147d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2019-11-19T12:52:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T10:38:11.000Z", "avg_line_length": 43.856187291, "max_line_length": 339, "alphanum_fraction": 0.604972165, "include": true, "reason": "import numpy,from numpy", "num_tokens": 3307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.19563430602562834}}
{"text": "# Copyright © 2017 Ondrej Martinsky, All rights reserved\n# http://github.com/omartinsky/pybor\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\nfrom yc_convention import *\nimport scipy.interpolate\nimport pylab, re, collections, matplotlib\n\nclass PlottingHelper:\n    @staticmethod\n    def set_tenors_on_axis(axis, start_date):\n        tenors = \"6M,1Y,2Y,3Y,4Y,5Y,7Y,10Y,15Y,20Y,30Y,40Y,50Y,60Y,70Y\".split(\",\")\n        tenordates = [date_step(int(start_date), Tenor(t)) for t in tenors]\n        axis.xaxis.set_ticks(tenordates)\n        axis.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, pos: tenors[pos]))\n\nclass CurveMap:\n    def __init__(self, *arg, **kw):\n        super(CurveMap, self).__init__(*arg, **kw)\n        self.curves_ = collections.OrderedDict()\n\n    def add_curve(self, c):\n        assert_type(c, Curve)\n        self.curves_[c.get_id()] = c\n\n    def get_all_dofs(self, curves_for_stage):\n        dofs = list()\n        for k, v in self.curves_.items():\n            if k in curves_for_stage:\n                dofs.extend(v.get_all_dofs())\n        return dofs\n\n    def set_all_dofs(self, curves_for_stage, dofs):\n        i = 0\n        for k, v in self.curves_.items():\n            if k in curves_for_stage:\n                j = i + v.get_dofs_count()\n                v.set_all_dofs(dofs[i:j])\n                i = j\n\n    def __getitem__(self, item):\n        return self.curves_[item]\n\n    def __len__(self):\n        return len(self.curves_)\n\n    def keys(self):\n        return self.curves_.keys()\n\n    def plot(self, reg=\".*\", *arg, **kwargs):\n        for name, curve in sorted(self.curves_.items()):\n            if re.match(reg, name):\n                curve.plot(*arg, **kwargs)\n\n\nclass InterpolationMode(enum.Enum):\n    LINEAR_LOGDF = 0\n    LINEAR_CCZR = 1\n    CUBIC_LOGDF = 2\n\nclass PlotMode(enum.Enum):\n    DF = 0\n    ZR = 1\n    FWD = 2\n\nclass PlotDate(enum.Enum):\n    YMD = 0\n    EXCEL = 1\n    TENOR = 2\n\nclass ExponentialInterpolator:\n    def __init__(self, interp):\n        self.interp = interp\n    def value(self, t):\n        return exp(self.interp(t))\n\nclass ZeroRateInterpolator:\n    def __init__(self, interp, t_eval):\n        self.interp = interp\n        self.t_eval = t_eval\n    def value(self, t):\n        return exp(self.interp(t) * (t - self.t_eval))\n\nclass Curve:\n    def __init__(self, curve_id, eval_date, times, dfs, interpolation_mode):\n        try:\n            times, dfs = array(times), array(dfs)\n            assert_type(interpolation_mode, InterpolationMode)\n            assert len(times) > 0, \"Vector of times is empty\"\n            assert times[0] != eval_date, \"DF at eval date cannot be provided externally. It is assumed to be 1.0 always.\"\n            self.id_ = curve_id\n            self.times_ = append(eval_date, times)\n            self.dfs_ = append([1.], dfs)\n            self.set_interpolator(interpolation_mode)\n        except BaseException as ex:\n            raise BaseException(\"Unable to create curve %s\" % curve_id) from ex\n\n    def add_another_curve(self, another_curve):\n        assert isinstance(another_curve, Curve)\n        assert all(self.times_ == another_curve.times_)\n        self.dfs_ = another_curve.dfs_ * self.dfs_\n        self.set_interpolator(self.interpolation_mode_)\n\n    def set_interpolator(self, interpolation_mode=None):\n        if interpolation_mode is not None:\n            self.interpolation_mode_ = interpolation_mode\n        if self.interpolation_mode_ in [InterpolationMode.LINEAR_LOGDF, InterpolationMode.LINEAR_CCZR]:\n            kind = 'linear'\n        elif self.interpolation_mode_ in [InterpolationMode.CUBIC_LOGDF]:\n            kind = 'cubic'\n        else:\n            raise BaseException(\"Invalid interpolation mode. Allowed modes are %s\" % enum_values_as_string(InterpolationMode))\n        #\n        assert len(self.times_) == len(self.dfs_), (len(self.times_), len(self.dfs_))\n        #\n        if self.interpolation_mode_ in [InterpolationMode.LINEAR_LOGDF, InterpolationMode.CUBIC_LOGDF]:\n            logdf = log(self.dfs_)\n            interp = scipy.interpolate.interp1d(self.times_, logdf, kind=kind)\n            self.interpolator_ = ExponentialInterpolator(interp)\n        elif self.interpolation_mode_ in [InterpolationMode.LINEAR_CCZR]:\n            t_eval = self.times_[0]\n            t_rel = self.times_-t_eval\n            cczr1 = log(self.dfs_[1:]) / t_rel[1:]\n            cczr = insert(cczr1, 0, cczr1[0]) # ZZCR at t0 is undefined, take it from t1 instead\n            interp = scipy.interpolate.interp1d(self.times_, cczr, kind=kind)\n            self.interpolator_ = ZeroRateInterpolator(interp, t_eval)\n        else:\n            raise BaseException(\"Invalid interpolation mode\")\n\n    def __str__(self):\n        return self.id_\n\n    def get_id(self):\n        return self.id_\n\n    def get_df(self, t):\n        try:\n            return self.interpolator_.value(t)\n        except BaseException as ex:\n            raise BaseException(\"Unable to get discount factor for dates [%i..%i] from curve with dates range [%i..%i]\" % (t[0],t[-1],self.times_[0], self.times_[-1])) from ex\n\n    def get_zero_rate(self, t, freq, dcc):\n        dfs = self.get_df(t)\n        dcf = calculate_dcf(self.times_[0], t, dcc)\n        if freq == CouponFreq.ZERO:\n            return (1. / dfs - 1.) / dcf\n        if freq == CouponFreq.CONTINUOUS:\n            return -log(dfs) / dcf\n\n    def get_fwd_rate(self, t_start, t_end, freq, dcc):\n        dfs_start = self.get_df(t_start)\n        dfs_end = self.get_df(t_end)\n        dcf = calculate_dcf(t_start, t_end, dcc)\n        if freq == CouponFreq.ZERO:\n            return (dfs_start / dfs_end - 1) / dcf\n        if freq == CouponFreq.CONTINUOUS:\n            return log(dfs_start / dfs_end) / dcf\n\n    def get_fwd_rate_aligned(self, t, freq, dcc):\n        # Slightly faster version which relies on the fact that calculation periods are aligned (no overlaps, no gaps)\n        dfs = self.get_df(t)\n        t1 = t[:-1]\n        t2 = t[1:]\n        df1 = dfs[:-1]\n        df2 = dfs[1:]\n        dcf = calculate_dcf(t1, t2, dcc)\n        if freq == CouponFreq.ZERO:\n            return (df1 / df2 - 1) / dcf\n        if freq == CouponFreq.CONTINUOUS:\n            return log(df1 / df2) / dcf\n\n    def set_all_dofs(self, dofs):\n        self.dfs_ = append([1], dofs)\n        self.set_interpolator()\n\n    def get_all_dofs(self):\n        return self.dfs_[1:]\n\n    def get_dofs_count(self):\n        return len(self.dfs_) - 1\n\n    def plot(self, date_style=PlotDate.YMD, mode=PlotMode.FWD, samples=1000, label=None, convention=None):\n        timesample = linspace(self.times_[0], self.times_[-1], samples)\n        X = timesample\n        if date_style==PlotDate.YMD:\n            X = [exceldate_to_pydate(int(x)) for x in X]\n        elif date_style==PlotDate.TENOR:\n            ax = matplotlib.pyplot.subplot()\n            PlottingHelper.set_tenors_on_axis(ax, self.times_[0])\n        elif date_style==PlotDate.EXCEL:\n            pass\n        else:\n            raise BaseException(\"Unknown PlottingDateStyle\")\n        ###\n        if mode==PlotMode.FWD:\n            convention = global_conventions.get(self.id_) if convention is None else convention\n            Y = self.get_fwd_rate_aligned(timesample, CouponFreq.ZERO, convention.dcc)\n            pylab.plot(X[:-1], Y, label=self.id_ if label is None else label)\n        elif mode==PlotMode.ZR:\n            convention = global_conventions.get(self.id_) if convention is None else convention\n            Y = self.get_zero_rate(timesample[1:], CouponFreq.ZERO, convention.dcc)\n            pylab.plot(X[:-1], Y, label=self.id_ if label is None else label)\n        elif mode==PlotMode.DF:\n            Y = self.get_df(timesample)\n            pylab.plot(X, Y, label=self.id_ if label is None else label)\n        else:\n            raise BaseException(\"Unknown PlottingMode\")\n\nclass CurveConstructor:\n    @staticmethod\n    def FromShortRateModel(curve_id, times, r0, speed, mean, sigma, interpolation):\n        import random\n        times = array(times)\n        assert_type(r0, float)\n        assert_type(speed, float)\n        assert_type(mean, float)\n        assert_type(sigma, float)\n        assert_type(interpolation, InterpolationMode)\n        r = r0\n        rates = []\n        dts = times[1:] - times[:-1]\n        dts = dts / 365.\n        for dt in dts:\n            rates.append(r)\n            dr = speed * (mean - r) * dt + sigma * random.gauss(0, 1) * dt ** .5\n            r += dr\n        rates = array(rates)\n        dfs_fwd = exp(-rates * dts)\n        dfs = cumprod(dfs_fwd)\n        return Curve(curve_id, times[0], times[1:], dfs, interpolation)\n", "meta": {"hexsha": "2db4452b6e118a2a6e7271449929e24c1de88d9a", "size": 9623, "ext": "py", "lang": "Python", "max_stars_repo_path": "yc_curve.py", "max_stars_repo_name": "ioancw/PYBOR", "max_stars_repo_head_hexsha": "b4a3e7f2ca3588f515ed01eca0bd0fe246d12449", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-25T11:36:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-25T11:36:30.000Z", "max_issues_repo_path": "yc_curve.py", "max_issues_repo_name": "ioancw/PYBOR", "max_issues_repo_head_hexsha": "b4a3e7f2ca3588f515ed01eca0bd0fe246d12449", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "yc_curve.py", "max_forks_repo_name": "ioancw/PYBOR", "max_forks_repo_head_hexsha": "b4a3e7f2ca3588f515ed01eca0bd0fe246d12449", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6465863454, "max_line_length": 175, "alphanum_fraction": 0.6319235166, "include": true, "reason": "import scipy", "num_tokens": 2441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.36296919173767833, "lm_q1q2_score": 0.1956343039731794}}
{"text": "import numpy as np\n\n\"\"\"\nIt is created for using MTC in Mujoco. The dynamics in this model is not continuous. The integration error will be\naccumulated overtime. And the system might get unstable if the timestep is too large. It is recommended to set the\ntimestamp lower than 5e-4 to get decent results.\n\nThe model is created based on Song's and Geyer's 2015 paper:\nSong, S. and Geyer, H., 2015. A neural circuitry that emphasizes spinal feedback generates diverse behaviours of human\nlocomotion. The Journal of physiology, 593(16), pp.3493-3511.\n\nV0.1\nPassed basic tests. There're slightly difference compared to the simmechanics model.\n\nV0.2\n1. Verified with the simmechanics model. Difference in most of the cases can be ignored.\n2. Changed the integration method from forward Euler to trapezoid.\n3. Muscle force vce etc might vibrate/jitter if in some cases if the timestep is not low enough.\n   Need to improve this in the next version.\n   \n\"\"\"\n\nclass MuscleTendonComplex:\n    def __init__(self, paraMuscle, stateMuscle, paraMusAttach, offsetCorr, timestep, nameMuscle, angJoi):\n        self.frcmax, self.vmax, self.eref, self.lslack, self.lopt, self.tau, self.w, self.c, self.N, self.K = paraMuscle\n        self.stim, self.act, self.lmtc, self.lce, self.vce, self.frcmtc = stateMuscle\n        self.timestep = timestep\n        self.nameMuscle = nameMuscle\n        self.angJoi = angJoi\n        self.offsetCorr = offsetCorr\n        self.r, self.phiref, self.phimaxref, self.rho, self.dirAng, self.phiScale = paraMusAttach\n        self.MR =  0.01\n        self.typeMuscle = self.angJoi.size\n        nJoi = self.typeMuscle\n        self.levelArm = np.zeros(nJoi)\n\n        tmpL = np.zeros(nJoi)\n        for i in range(0, nJoi):\n            if self.offsetCorr[i] == 0:\n                tmpL[i] = self.dirAng[i] * (self.angJoi[i] - self.phiref[i]) * self.r[i] * self.rho[i]\n                self.levelArm[i] = self.r[i]\n            elif self.offsetCorr[i] == 1:\n                tmp1 = np.sin((self.phiref[i] - self.phimaxref[i]) * self.phiScale[i])\n                tmp2 = np.sin((self.angJoi[i] - self.phimaxref[i]) * self.phiScale[i])\n                tmpL[i] = self.dirAng[i] * (tmp2 - tmp1) * self.r[i] * self.rho[i] / self.phiScale[i]\n                self.levelArm[i] = np.cos((self.angJoi[i] - self.phimaxref[i]) * self.phiScale[i]) * self.r[i]\n            else:\n                raise ValueError('Invalid muscle level arm offset correction type. ')\n        self.lmtc = self.lslack + self.lopt + np.sum(tmpL)\n\n        self.lce = self.lmtc - self.lslack\n        self.lse = self.lmtc - self.lce\n        # unitless parameters\n        self.Lse = self.lse / self.lslack\n        self.Lce = self.lce / self.lopt\n\n        self.actsubstep = (self.stim - self.act) * self.timestep / 2.0 / self.tau + self.act\n        self.lcesubstep = self.vce * self.timestep / 2.0 + self.lce\n\n        # test\n        self.lce_avg = self.lce\n        self.vce_avg = self.vce\n        self.frcmtc_avg = 0\n        self.act_avg = self.act\n        self.frame = 0\n        # self.Fse = 0.0\n        # self.Fbe = 0.0\n        # self.Fpe = 0.0\n        # self.Fce = 0.0\n\n\n    def stepUpdateState(self, angJoi):\n        \"\"\"\n        Muscle Tendon Complex Dynamics\n        update muscle states based on the muscle dynamics\n        Muscle state stim has to be updated outside before this function is called\n        \"\"\"\n        # update lmtc and level arm based on the geometry\n        self.angJoi = angJoi\n        nJoi = self.typeMuscle\n        tmpL = np.zeros(nJoi)\n        for i in range(0, nJoi):\n            if self.offsetCorr[i] == 0:\n                tmpL[i] = self.dirAng[i] * (self.angJoi[i] - self.phiref[i]) * self.r[i] * self.rho[i]\n                self.levelArm[i] = self.r[i]\n            elif self.offsetCorr[i] == 1:\n                tmp1 = np.sin((self.phiref[i] - self.phimaxref[i]) * self.phiScale[i])\n                tmp2 = np.sin((self.angJoi[i] - self.phimaxref[i]) * self.phiScale[i])\n                tmpL[i] = self.dirAng[i] * (tmp2 - tmp1) * self.r[i] * self.rho[i] / self.phiScale[i]\n                self.levelArm[i] = np.cos((self.angJoi[i] - self.phimaxref[i]) * self.phiScale[i]) * self.r[i]\n            else:\n                raise ValueError('Invalid muscle level arm offset correction type. ')\n        self.lmtc = self.lslack + self.lopt + np.sum(tmpL)\n\n        # update muscle activation\n        # integration, forward-Euler method\n        # self.act = (self.stim - self.act) * self.timestep / self.tau + self.act\n        # integration, trapezoidal method, 2-step\n        self.act = (self.stim - self.actsubstep) * self.timestep / 2.0 / self.tau + self.actsubstep\n        self.actsubstep = (self.stim - self.act) * self.timestep / 2.0 / self.tau + self.act\n\n        # update lce and lse based on the lmtc\n        # integration, forward-Euler method\n        # self.lce = self.vce * self.timestep + self.lce\n        # integration, trapezoidal method, 2-step\n        self.lce = self.vce * self.timestep / 2.0 + self.lcesubstep\n        self.lcesubstep = self.vce * self.timestep / 2.0 + self.lce\n\n        self.lse = self.lmtc - self.lce\n        self.Lse = self.lse / self.lslack\n        self.Lce = self.lce / self.lopt\n\n        # Serial Elastic element (tendon) force-length relationship\n        if self.Lse > 1.0:\n            Fse = np.power((self.Lse - 1.0) / self.eref, 2)\n        else:\n            Fse = 0.0\n\n        # Parallel Elasticity PE\n        if self.Lce > 1.0:\n            Fpe = np.power((self.Lce - 1.0) / self.w, 2)\n        else:\n            Fpe = 0.0\n\n        # update frcmtc\n        self.frcmtc = Fse * self.frcmax\n        #self.frcmtc =  np.clip(self.frcmtc, 0, self.frcmax)\n\n        # Buffer Elasticity BE\n        if (self.Lce - (1.0 - self.w)) < 0:\n            Fbe = np.power((self.Lce - (1.0 - self.w)) / (self.w / 2), 2)\n        else:\n            Fbe = 0.0\n\n        # Contractile Element force-length relationship\n        tmp = np.power(np.absolute(self.Lce - 1.0) / self.w, 3)\n        Fce = np.exp(tmp * np.log(self.c))\n\n        #Fv = (Fse + Fbe) / (Fpe + Fce * self.act)\n        if (Fpe + Fce * self.act) < 1e-10:  # avoid numerical error\n            if (Fse + Fbe) < 1e-10:\n                Fv = 1.0\n            else:\n                Fv = (Fse + Fbe) / 1e-10\n        else:\n            Fv = (Fse + Fbe) / (Fpe + Fce * self.act)\n\n        # Contractile Element inverse force-velocity relationship\n        if Fv <= 1.0:\n            # Concentric\n            v = (Fv - 1) / (Fv * self.K + 1.0)\n        elif Fv <= self.N:\n            # excentric\n            tmp = (Fv - self.N) / (self.N - 1.0)\n            v = (tmp + 1.0) / (1.0 - tmp * 7.56 * self.K)\n        else:\n            # excentric overshoot\n            v = ((Fv - self.N) * 0.01 + 1)\n\n        self.vce = v * self.lopt * self.vmax\n        v_frac = self.vce /  self.vmax\n        mr_scale =  self.act * np.absolute(self.frcmax*self.vmax) *self.timestep\n        if self.vce <= 1:\n            self.MR =  0.01 - 0.11*(v_frac) + 0.06*np.exp(-8*v_frac)\n        else:\n            self.MR =  0.23 - 0.16*np.exp(-8*v_frac) \n        self.MR *= mr_scale\n        self.frame += 1\n        self.lce_avg = (self.lce_avg*(self.frame - 1) +  self.lce) / self.frame\n        self.vce_avg = (self.vce_avg*(self.frame - 1) +  self.vce) / self.frame\n        self.frcmtc_avg = (self.frcmtc_avg*(self.frame - 1) +  self.frcmtc) / self.frame\n        self.act_avg = (self.act_avg*(self.frame - 1) +  self.act) / self.frame\n        #self.MR = np.exp(-self.MR)\n        # print(self.MR, np.exp(-self.MR))\n        # self.Fv = Fv\n        # self.Fse = Fse\n        # self.Fbe = Fbe\n        # self.Fpe = Fpe\n        # self.Fce = Fce\n\n    def reset_state(self):\n        self.frame = 0\n        self.lce_avg = 0\n        self.frcmtc_avg = 0\n        self.act_avg = 0\n        self.vce_avg = 0\n\n", "meta": {"hexsha": "4fda88e07a7d5763add5321ef0cfe0319e550f49", "size": 7802, "ext": "py", "lang": "Python", "max_stars_repo_path": "mushroom_rl/environments/mujoco_envs/humanoid_gait/_external_simulation/mtc_model.py", "max_stars_repo_name": "PuzeLiu/mushroom-rl", "max_stars_repo_head_hexsha": "99942b425e66b4ddcc26009d7105dde23841e95d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 344, "max_stars_repo_stars_event_min_datetime": "2020-01-10T09:45:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:48:28.000Z", "max_issues_repo_path": "mushroom_rl/environments/mujoco_envs/humanoid_gait/_external_simulation/mtc_model.py", "max_issues_repo_name": "AmmarFahmy/mushroom-rl", "max_issues_repo_head_hexsha": "2625ee7f64d5613b3b9fba00f0b7a39fece88ca5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44, "max_issues_repo_issues_event_min_datetime": "2020-01-23T03:00:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T17:14:22.000Z", "max_forks_repo_path": "mushroom_rl/environments/mujoco_envs/humanoid_gait/_external_simulation/mtc_model.py", "max_forks_repo_name": "AmmarFahmy/mushroom-rl", "max_forks_repo_head_hexsha": "2625ee7f64d5613b3b9fba00f0b7a39fece88ca5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 93, "max_forks_repo_forks_event_min_datetime": "2020-01-10T21:17:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T17:58:52.000Z", "avg_line_length": 41.5, "max_line_length": 120, "alphanum_fraction": 0.5697257114, "include": true, "reason": "import numpy", "num_tokens": 2423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.2782567877172032, "lm_q1q2_score": 0.1954837570455722}}
{"text": "\nimport sys, os\ncur_file_path = os.path.dirname(os.path.realpath(__file__))\nsys.path.append(os.path.join(cur_file_path, '..'))\n\nimport shutil, glob\nimport os.path as osp\nimport cv2\nimport numpy as np\nimport json\nimport torch\n\nfrom body_model.body_model import BodyModel\n\nfrom utils.transforms import rotation_matrix_to_angle_axis, batch_rodrigues, convert_to_rotmat\nfrom utils.logging import mkdir, Logger\n\nNSTAGES = 3 # number of stages in the optimization\nDEFAULT_FOCAL_LEN = (1060.531764702488, 1060.3856705041237) # fx, fy\n\ndef read_keypoints(keypoint_fn):\n    '''\n    Only reads body keypoint data of first person.\n    '''\n    with open(keypoint_fn) as keypoint_file:\n        data = json.load(keypoint_file)\n\n    if len(data['people']) == 0:\n        print('WARNING: Found no keypoints in %s! Returning zeros!' % (keypoint_fn))\n        return np.zeros((OP_NUM_JOINTS, 3), dtype=np.float)\n\n    person_data = data['people'][0]\n    body_keypoints = np.array(person_data['pose_keypoints_2d'],\n                                dtype=np.float)\n    body_keypoints = body_keypoints.reshape([-1, 3])\n\n    return body_keypoints\n\ndef resize_points(points_arr, num_pts):\n    '''\n    Either randomly subsamples or pads the given points_arr to be of the desired size.\n    - points_arr : N x 3\n    - num_pts : desired num point \n    '''\n    is_torch = isinstance(points_arr, torch.Tensor)\n    N = points_arr.size(0) if is_torch else points_arr.shape[0]\n    if N > num_pts:\n        samp_inds = np.random.choice(np.arange(N), size=num_pts, replace=False)\n        points_arr = points_arr[samp_inds]\n    elif N < num_pts:\n        while N < num_pts:\n            pad_size = num_pts - N\n            if is_torch:\n                points_arr = torch.cat([points_arr, points_arr[:pad_size]], dim=0)\n                N = points_arr.size(0)\n            else:\n                points_arr = np.concatenate([points_arr, points_arr[:pad_size]], axis=0)\n                N = points_arr.shape[0]\n    return points_arr\n\ndef compute_plane_intersection(point, direction, plane):\n    '''\n    Given a ray defined by a point in space and a direction, compute the intersection point with the given plane.\n    Detect intersection in either direction or -direction so the given ray may not actually intersect with the plane.\n\n    Returns the intersection point as well as s such that point + s*direction = intersection_point. if s < 0 it means\n    -direction intersects.\n\n    - point : B x 3\n    - direction : B x 3\n    - plane : B x 4 (a, b, c, d) where (a, b, c) is the normal and (d) the offset.\n    '''\n    plane_normal = plane[:,:3]\n    plane_off = plane[:,3]\n    s = (plane_off - bdot(plane_normal, point)) / bdot(plane_normal, direction)\n    itsct_pt = point + s.reshape((-1, 1))*direction\n    return itsct_pt, s\n\ndef bdot(A1, A2, keepdim=False):\n    ''' \n    Batched dot product.\n    - A1 : B x D\n    - A2 : B x D.\n    Returns B.\n    '''\n    return (A1*A2).sum(dim=-1, keepdim=keepdim) \n\ndef parse_floor_plane(floor_plane):\n    '''\n    Takes floor plane in the optimization form (Bx3 with a,b,c * d) and parses into\n    (a,b,c,d) from with (a,b,c) normal facing \"up in the camera frame and d the offset.\n    '''\n    floor_offset = torch.norm(floor_plane, dim=1, keepdim=True)\n    floor_normal = floor_plane / floor_offset\n    \n    # in camera system -y is up, so floor plane normal y component should never be positive\n    #       (assuming the camera is not sideways or upside down)\n    neg_mask = floor_normal[:,1:2] > 0.0\n    floor_normal = torch.where(neg_mask.expand_as(floor_normal), -floor_normal, floor_normal)\n    floor_offset = torch.where(neg_mask, -floor_offset, floor_offset)\n    floor_plane_4d = torch.cat([floor_normal, floor_offset], dim=1)\n\n    return floor_plane_4d\n\ndef load_planercnn_res(res_path):\n    '''\n    Given a directory containing PlaneRCNN plane detection results, loads the first image result \n    and heuristically finds and returns the floor plane.\n    '''\n    planes_param_path = glob.glob(res_path + '/*_plane_parameters_*.npy')[0]\n    planes_mask_path = glob.glob(res_path + '/*_plane_masks_*.npy')[0]\n    planes_params = np.load(planes_param_path)\n    planes_masks = np.load(planes_mask_path)\n    \n    # heuristically determine the ground plane\n    #   the plane with the most labeled pixels in the bottom N rows\n    nrows = 10\n    label_count = np.sum(planes_masks[:, -nrows:, :], axis=(1, 2))\n    floor_idx = np.argmax(label_count)\n    valid_floor = False\n    floor_plane = None\n    while not valid_floor:\n        # loop until we find a plane with many pixels on the bottom\n        #       and doesn't face in the complete wrong direction\n        # we assume the y component is larger than any others\n        # i.e. that the floor is not > 45 degrees relative rotation from the camera\n        floor_plane = planes_params[floor_idx]\n        # transform to our system\n        floor_plane = np.array([floor_plane[0], -floor_plane[2], floor_plane[1]])\n        # determine 4D parameterization\n        # for this data we know y should always be negative\n        floor_offset = np.linalg.norm(floor_plane)\n        floor_normal = floor_plane / floor_offset\n        if floor_normal[1] > 0.0:\n            floor_offset *= -1.0\n            floor_normal *= -1.0\n        a, b, c = floor_normal\n        d = floor_offset\n        floor_plane = np.array([a, b, c, d])\n\n        valid_floor = np.abs(b) > np.abs(a) and np.abs(b) > np.abs(c)\n        if not valid_floor:\n            label_count[floor_idx] = 0\n            floor_idx = np.argmax(label_count)\n\n    return floor_plane\n\n\ndef compute_cam2prior(floor_plane, trans, root_orient, joints):\n    '''\n    Computes rotation and translation from the camera frame to the canonical coordinate system\n    used by the motion and initial state priors.\n    - floor_plane : B x 3\n    - trans : B x 3\n    - root_orient : B x 3\n    - joints : B x J x 3\n    '''\n    B = floor_plane.size(0)\n    if floor_plane.size(1) == 3:\n        floor_plane_4d = parse_floor_plane(floor_plane)\n    else:\n        floor_plane_4d = floor_plane\n    floor_normal = floor_plane_4d[:,:3]\n    floor_trans, _ = compute_plane_intersection(trans, -floor_normal, floor_plane_4d)\n\n    # compute prior frame axes within the camera frame\n    # up is the floor_plane normal\n    up_axis = floor_normal\n    # right is body -x direction projected to floor plane\n    root_orient_mat = batch_rodrigues(root_orient)\n    body_right = -root_orient_mat[:, :, 0]\n    floor_body_right, s = compute_plane_intersection(trans, body_right, floor_plane_4d)\n    right_axis = floor_body_right - floor_trans \n    # body right may not actually intersect - in this case must negate axis because we have the -x\n    right_axis = torch.where(s.reshape((B, 1)) < 0, -right_axis, right_axis)\n    right_axis = right_axis / torch.norm(right_axis, dim=1, keepdim=True)\n    # forward is their cross product\n    fwd_axis = torch.cross(up_axis, right_axis)\n    fwd_axis = fwd_axis / torch.norm(fwd_axis, dim=1, keepdim=True)\n\n    prior_R = torch.stack([right_axis, fwd_axis, up_axis], dim=2)\n    cam2prior_R = prior_R.transpose(2, 1)\n\n    # translation takes translation to origin plus offset to the floor\n    cam2prior_t = -trans\n\n    _, s_root = compute_plane_intersection(joints[:,0], -floor_normal, floor_plane_4d)\n    root_height = s_root.reshape((B, 1))\n\n    return cam2prior_R, cam2prior_t, root_height\n\ndef apply_robust_weighting(res, robust_loss_type='bisquare', robust_tuning_const=4.6851):\n    '''\n    Returns robustly weighted squared residuals.\n    - res : torch.Tensor (B x N), take the MAD over each batch dimension independently.\n    '''\n    robust_choices = ['none', 'bisquare']\n    if robust_loss_type not in robust_choices:\n        print('Not a valid robust loss: %s. Please use %s' % (robust_loss_type, str(robust_choices)))\n    \n    w = None\n    detach_res = res.clone().detach() # don't want gradients flowing through the weights to avoid degeneracy\n    if robust_loss_type == 'none':\n        w = torch.ones_like(detach_res)\n    elif robust_loss_type == 'bisquare':\n        w = bisquare_robust_weights(detach_res, tune_const=robust_tuning_const)\n\n    # apply weights to squared residuals\n    weighted_sqr_res = w * (res**2)\n    return weighted_sqr_res, w\n\ndef robust_std(res):\n    ''' \n    Compute robust estimate of standarad deviation using median absolute deviation (MAD)\n    of the given residuals independently over each batch dimension.\n\n    - res : (B x N)\n\n    Returns:\n    - std : B x 1\n    '''\n    B = res.size(0)\n    med = torch.median(res, dim=-1)[0].reshape((B,1))\n    abs_dev = torch.abs(res - med)\n    MAD = torch.median(abs_dev, dim=-1)[0].reshape((B, 1))\n    std = MAD / 0.67449\n    return std\n\ndef bisquare_robust_weights(res, tune_const=4.6851):\n    '''\n    Bisquare (Tukey) loss.\n    See https://www.mathworks.com/help/curvefit/least-squares-fitting.html\n\n    - residuals\n    '''\n    # print(res.size())\n    norm_res = res / (robust_std(res) * tune_const)\n    # NOTE: this should use absolute value, it's ok right now since only used for 3d point cloud residuals\n        #   which are guaranteed positive, but generally this won't work)\n    outlier_mask = norm_res >= 1.0\n\n    # print(torch.sum(outlier_mask))\n    # print('Outlier frac: %f' % (float(torch.sum(outlier_mask)) / res.size(1)))\n\n    w = (1.0 - norm_res**2)**2\n    w[outlier_mask] = 0.0\n\n    return w\n\ndef gmof(res, sigma):\n    \"\"\"\n    Geman-McClure error function\n    - residual\n    - sigma scaling factor\n    \"\"\"\n    x_squared = res ** 2\n    sigma_squared = sigma ** 2\n    return (sigma_squared * x_squared) / (sigma_squared + x_squared)\n\n\ndef log_cur_stats(stats_dict, loss, iter=None):\n    Logger.log('LOSS: %f' % (loss.cpu().item()))\n    print('----')\n    for k, v in stats_dict.items():\n        if isinstance(v, float):\n            Logger.log('%s: %f' % (k, v))\n        else:\n            Logger.log('%s: %f' % (k, v.cpu().item()))\n    if iter is not None:\n        print('======= iter %d =======' % (int(iter)))\n    else:\n        print('========')\n\ndef save_optim_result(cur_res_out_paths, optim_result, per_stage_results, gt_data, observed_data, data_type,\n                      optim_floor=True,\n                      obs_img_paths=None,\n                      obs_mask_paths=None):\n    # final optim results\n    res_betas = optim_result['betas'].cpu().numpy()\n    res_trans = optim_result['trans'].cpu().numpy()\n    res_root_orient = optim_result['root_orient'].cpu().numpy()\n    res_body_pose = optim_result['pose_body'].cpu().numpy()\n    res_contacts = None\n    res_floor_plane = None\n    if 'contacts' in optim_result:\n        res_contacts = optim_result['contacts'].cpu().numpy()\n    if 'floor_plane' in optim_result:\n        res_floor_plane = optim_result['floor_plane'].cpu().numpy()\n    for bidx, cur_res_out_path in enumerate(cur_res_out_paths):\n        cur_res_out_path = os.path.join(cur_res_out_path, 'stage3_results.npz')\n        save_dict = { \n            'betas' : res_betas[bidx],\n            'trans' : res_trans[bidx],\n            'root_orient' : res_root_orient[bidx],\n            'pose_body' : res_body_pose[bidx]\n        }\n        if res_contacts is not None:\n            save_dict['contacts'] = res_contacts[bidx]\n        if res_floor_plane is not None:\n            save_dict['floor_plane'] = res_floor_plane[bidx]\n        np.savez(cur_res_out_path, **save_dict)\n\n    # in prior coordinate frame\n    if 'stage3' in per_stage_results and optim_floor:\n        res_trans = per_stage_results['stage3']['prior_trans'].detach().cpu().numpy()\n        res_root_orient = per_stage_results['stage3']['prior_root_orient'].detach().cpu().numpy()\n        for bidx, cur_res_out_path in enumerate(cur_res_out_paths):\n            cur_res_out_path = os.path.join(cur_res_out_path, 'stage3_results_prior.npz')\n            save_dict = { \n                'betas' : res_betas[bidx],\n                'trans' : res_trans[bidx],\n                'root_orient' : res_root_orient[bidx],\n                'pose_body' : res_body_pose[bidx]\n            }\n            if res_contacts is not None:\n                save_dict['contacts'] = res_contacts[bidx]\n            np.savez(cur_res_out_path, **save_dict)\n\n    # ground truth\n    save_gt = 'betas' in gt_data and \\\n                'trans' in gt_data and \\\n                'root_orient' in gt_data and \\\n                'pose_body' in gt_data\n    if save_gt:\n        gt_betas = gt_data['betas'].cpu().numpy()\n        if data_type not in ['PROX-RGB', 'PROX-RGBD']:\n            gt_betas = gt_betas[:,0] # only need frame 1 for e.g. 3d data since it's the same over time.\n        gt_trans = gt_data['trans'].cpu().numpy()\n        gt_root_orient = gt_data['root_orient'].cpu().numpy()\n        gt_body_pose = gt_data['pose_body'].cpu().numpy()\n        gt_contacts = None\n        if 'contacts' in gt_data:\n            gt_contacts = gt_data['contacts'].cpu().numpy()\n        cam_mat = None\n        if 'cam_matx' in gt_data:\n            cam_mat = gt_data['cam_matx'].cpu().numpy()\n        for bidx, cur_res_out_path in enumerate(cur_res_out_paths):\n            gt_res_name = 'proxd_results.npz' if data_type in ['PROX-RGB', 'PROX-RGBD'] else 'gt_results.npz'\n            cur_gt_out_path = os.path.join(cur_res_out_path, gt_res_name)\n            save_dict = { \n                'betas' : gt_betas[bidx],\n                'trans' : gt_trans[bidx],\n                'root_orient' : gt_root_orient[bidx],\n                'pose_body' : gt_body_pose[bidx]\n            }\n            if gt_contacts is not None:\n                save_dict['contacts'] = gt_contacts[bidx]\n            if cam_mat is not None:\n                save_dict['cam_mtx'] = cam_mat[bidx]\n            np.savez(cur_gt_out_path, **save_dict)\n\n            # if these are proxd results also need to save a GT with cam matrix\n            if data_type in ['PROX-RGB', 'PROX-RGBD']:\n                cur_gt_out_path = os.path.join(cur_res_out_path, 'gt_results.npz')\n                np.savez(cur_gt_out_path, cam_mtx=cam_mat[bidx])\n\n    elif 'joints3d' in gt_data:\n        # don't have smpl params, but have 3D joints (e.g. imapper)\n        gt_joints = gt_data['joints3d'].cpu().numpy()\n        cam_mat = occlusions = None\n        if 'cam_matx' in gt_data:\n            cam_mat = gt_data['cam_matx'].cpu().numpy()\n        if 'occlusions' in gt_data:\n            occlusions = gt_data['occlusions'].cpu().numpy()\n        for bidx, cur_res_out_path in enumerate(cur_res_out_paths):\n            cur_res_out_path = os.path.join(cur_res_out_path, 'gt_results.npz')\n            save_dict = { \n                'joints3d' : gt_joints[bidx]\n            }\n            if cam_mat is not None:\n                save_dict['cam_mtx'] = cam_mat[bidx]\n            if occlusions is not None:\n                save_dict['occlusions'] = occlusions[bidx]\n            np.savez(cur_res_out_path, **save_dict)\n    elif 'cam_matx' in gt_data:\n        # need the intrinsics even if we have nothing else\n        cam_mat = gt_data['cam_matx'].cpu().numpy()\n        for bidx, cur_res_out_path in enumerate(cur_res_out_paths):\n            cur_res_out_path = os.path.join(cur_res_out_path, 'gt_results.npz')\n            save_dict = { \n                'cam_mtx' : cam_mat[bidx]\n            }\n            np.savez(cur_res_out_path, **save_dict)\n\n    # observations\n    obs_out = {k : v.cpu().numpy() for k, v in observed_data.items() if k != 'prev_batch_overlap_res'}\n    for bidx, cur_res_out_path in enumerate(cur_res_out_paths):\n        obs_out_path = os.path.join(cur_res_out_path, 'observations.npz')\n        cur_obs_out = {k : v[bidx] for k, v in obs_out.items() if k not in ['RGB']}\n        if obs_img_paths is not None:\n            cur_obs_out['img_paths'] = [frame_tup[bidx] for frame_tup in obs_img_paths]\n            # print(cur_obs_out['img_paths'])\n        if obs_mask_paths is not None:\n            cur_obs_out['mask_paths'] = [frame_tup[bidx] for frame_tup in obs_mask_paths]\n        np.savez(obs_out_path, **cur_obs_out)    \n\n\ndef save_rgb_stitched_result(seq_intervals, all_res_out_paths, res_out_path, device,\n                                body_model_path, num_betas, use_joints2d):\n    import cv2\n    seq_overlaps = [0]\n    for int_idx in range(len(seq_intervals)-1):\n        prev_end = seq_intervals[int_idx][1]\n        cur_start = seq_intervals[int_idx+1][0]\n        seq_overlaps.append(prev_end - cur_start)\n\n    # if arbitray RGB video data, stitch together to save full sequence output\n    all_res_dirs = all_res_out_paths\n    print(all_res_dirs)\n\n    final_res_out_path = os.path.join(res_out_path, 'final_results')\n    mkdir(final_res_out_path)\n\n    concat_cam_res = None\n    concat_contacts = None\n    concat_ground_planes = None\n    concat_joints2d = None\n    concat_img_paths = None\n    gt_cam_mtx = None\n    for res_idx, res_dir in enumerate(all_res_dirs):\n        # camera view\n        cur_stage3_res = load_res(res_dir, 'stage3_results.npz')\n        cur_contacts = torch.Tensor(cur_stage3_res['contacts']).to(device)\n        if concat_ground_planes is None: \n            concat_ground_planes = torch.Tensor(cur_stage3_res['floor_plane']).to(device).reshape((1, -1))\n        else:\n            concat_ground_planes = torch.cat([concat_ground_planes, torch.Tensor(cur_stage3_res['floor_plane']).to(device).reshape((1, -1))], dim=0)\n        cur_stage3_res = {k : v for k, v in cur_stage3_res.items() if k in ['betas', 'trans', 'root_orient', 'pose_body']}\n        cur_stage3_res = prep_res(cur_stage3_res, device, cur_stage3_res['trans'].shape[0])\n        if concat_cam_res is None: \n            concat_cam_res = cur_stage3_res\n            concat_contacts = cur_contacts\n        else:\n            for k, v in concat_cam_res.items():\n                concat_cam_res[k] = torch.cat([concat_cam_res[k], cur_stage3_res[k][seq_overlaps[res_idx]:]], dim=0)\n            concat_contacts = torch.cat([concat_contacts, cur_contacts[seq_overlaps[res_idx]:]], dim=0)\n\n        # gt\n        if gt_cam_mtx is None:\n            gt_res = load_res(res_dir, 'gt_results.npz')\n            gt_cam_mtx = gt_res['cam_mtx']\n\n        # obs\n        cur_obs = load_res(res_dir, 'observations.npz')\n        if concat_joints2d is None:\n            concat_joints2d = cur_obs['joints2d']\n        else:\n            concat_joints2d = np.concatenate([concat_joints2d, cur_obs['joints2d'][seq_overlaps[res_idx]:]], axis=0)\n        if concat_img_paths is None:\n            concat_img_paths = list(cur_obs['img_paths'])\n        else:\n            concat_img_paths = concat_img_paths + list(cur_obs['img_paths'][seq_overlaps[res_idx]:])\n        \n        # ignore if we don't have an interval for this directory (was an extra due to even batching requirement)\n        if res_idx >= len(seq_overlaps):\n            break\n\n    # copy meta\n    src_meta_path = os.path.join(all_res_dirs[0], 'meta.txt')\n    shutil.copyfile(src_meta_path, os.path.join(final_res_out_path, 'meta.txt'))\n\n    #  gt results (cam matx)\n    np.savez(os.path.join(final_res_out_path, 'gt_results.npz'), cam_mtx=gt_cam_mtx)\n\n    # obs results (joints2d and img_paths)\n    np.savez(os.path.join(final_res_out_path, 'observations.npz'), joints2d=concat_joints2d, img_paths=concat_img_paths)\n\n    #  save the actual results npz for viz later\n    concat_res_out_path = os.path.join(final_res_out_path, 'stage3_results.npz')\n    res_betas = concat_cam_res['betas'].clone().detach().cpu().numpy()\n    res_trans = concat_cam_res['trans'].clone().detach().cpu().numpy()\n    res_root_orient = concat_cam_res['root_orient'].clone().detach().cpu().numpy()\n    res_body_pose = concat_cam_res['pose_body'].clone().detach().cpu().numpy()\n    res_floor_plane = concat_ground_planes[0].clone().detach().cpu().numpy() # NOTE: saves estimate from first subsequence\n    res_contacts = concat_contacts.clone().detach().cpu().numpy()\n    np.savez(concat_res_out_path, betas=res_betas,\n                                trans=res_trans,\n                                root_orient=res_root_orient,\n                                pose_body=res_body_pose,\n                                floor_plane=res_floor_plane,\n                                contacts=res_contacts)\n\n    # get body model\n    num_viz_frames = concat_cam_res['trans'].size(0)\n    viz_body_model = BodyModel(bm_path=body_model_path,\n                            num_betas=num_betas,\n                            batch_size=num_viz_frames,\n                            use_vtx_selector=use_joints2d).to(device)\n    viz_body = run_smpl(concat_cam_res, viz_body_model)\n    \n    # transform full camera-frame sequence into a shared prior frame based on a single ground plane\n    viz_joints3d = viz_body.Jtr\n    # compute the transformation based on t=0 and the first sequence floor plane\n    cam2prior_R, cam2prior_t, cam2prior_root_height = compute_cam2prior(concat_ground_planes[0].unsqueeze(0),\n                                                                        concat_cam_res['trans'][0].unsqueeze(0),\n                                                                        concat_cam_res['root_orient'][0].unsqueeze(0),\n                                                                        viz_joints3d[0].unsqueeze(0))\n    # transform the whole sequence\n    input_data_dict = {kb : vb.unsqueeze(0) for kb, vb in concat_cam_res.items() if kb in ['trans', 'root_orient', 'pose_body', 'betas']}\n    viz_prior_data_dict = apply_cam2prior(input_data_dict, cam2prior_R, cam2prior_t, cam2prior_root_height, \n                                            input_data_dict['pose_body'],\n                                            input_data_dict['betas'],\n                                            0,\n                                            viz_body_model)\n    concat_prior_res = {\n        'trans' : viz_prior_data_dict['trans'][0],\n        'root_orient' : viz_prior_data_dict['root_orient'][0],\n        'pose_body' : concat_cam_res['pose_body'],\n        'betas' : concat_cam_res['betas']\n    }\n\n    # save pose prior frame\n    concat_prior_res_out_path = os.path.join(final_res_out_path, 'stage3_results_prior.npz')\n    res_betas = concat_prior_res['betas'].clone().detach().cpu().numpy()\n    res_trans = concat_prior_res['trans'].clone().detach().cpu().numpy()\n    res_root_orient = concat_prior_res['root_orient'].clone().detach().cpu().numpy()\n    res_body_pose = concat_prior_res['pose_body'].clone().detach().cpu().numpy()\n    res_contacts = concat_contacts.clone().detach().cpu().numpy()\n    np.savez(concat_prior_res_out_path, betas=res_betas,\n                                trans=res_trans,\n                                root_orient=res_root_orient,\n                                pose_body=res_body_pose,\n                                contacts=res_contacts)\n\n\ndef load_res(result_dir, file_name):\n    '''\n    Load np result from our model or GT\n    '''\n    res_path = os.path.join(result_dir, file_name)\n    if not os.path.exists(res_path):\n        return None\n    res = np.load(res_path)\n    res_dict = {k : res[k] for k in res.files}\n    return res_dict\n\ndef prep_res(np_res, device, T):\n    '''\n    Load np result dict into dict of torch objects for use with SMPL body model.\n    '''\n    betas = np_res['betas']\n    betas = torch.Tensor(betas).to(device)\n    if len(betas.size()) == 1:\n        num_betas = betas.size(0)\n        betas = betas.reshape((1, num_betas)).expand((T, num_betas))\n    else:\n        num_betas = betas.size(1)\n        assert(betas.size(0) == T)\n    trans = np_res['trans']\n    trans = torch.Tensor(trans).to(device)\n    root_orient = np_res['root_orient']\n    root_orient = torch.Tensor(root_orient).to(device)\n    pose_body = np_res['pose_body']\n    pose_body = torch.Tensor(pose_body).to(device)\n\n    res_dict = {\n        'betas' : betas,\n        'trans' : trans,\n        'root_orient' : root_orient,\n        'pose_body' : pose_body\n    }\n\n    for k, v in np_res.items():\n        if k not in ['betas', 'trans', 'root_orient', 'pose_body']:\n            res_dict[k] = v\n    return res_dict\n\ndef run_smpl(res_dict, body_model):\n    smpl_body = body_model(pose_body=res_dict['pose_body'], \n                            pose_hand=None, \n                            betas=res_dict['betas'],\n                            root_orient=res_dict['root_orient'],\n                            trans=res_dict['trans'])\n    return smpl_body\n\ndef apply_cam2prior(data_dict, R, t, root_height, body_pose, betas, key_frame_idx, body_model, inverse=False):\n    '''\n    Applies the camera2prior tranformation made up of R, t to the data in data dict and\n    returns a new dictionary with the transformed data.\n    Right now supports: trans, root_orient.\n\n    NOTE: If the number of timesteps in trans/root_orient is 1, this function assumes they are at key_frame_idx.\n            (othherwise the calculation of cur_root_height or trans_offset in inverse case is not correct)\n\n    key_frame_idx : the timestep used to compute cam2prior size (B) tensor\n    inverse : if true, applies the inverse transformation from prior space to camera\n    '''\n    prior_dict = dict()\n    if 'root_orient' in data_dict:\n        # B x T x 3\n        root_orient = data_dict['root_orient']\n        B, T, _ = root_orient.size()\n        R_time = R.unsqueeze(1).expand((B, T, 3, 3))\n        t_time = t.unsqueeze(1).expand((B, T, 3))\n        root_orient_mat = batch_rodrigues(root_orient.reshape((-1, 3))).reshape((B, T, 3, 3))\n        if inverse:\n            prior_root_orient_mat = torch.matmul(R_time.transpose(3, 2), root_orient_mat)\n        else:\n            prior_root_orient_mat = torch.matmul(R_time, root_orient_mat)\n        prior_root_orient = rotation_matrix_to_angle_axis(prior_root_orient_mat.reshape((B*T, 3, 3))).reshape((B, T, 3))\n        prior_dict['root_orient'] = prior_root_orient\n\n    if 'trans' in data_dict and 'root_orient' in data_dict:\n        # B x T x 3\n        trans = data_dict['trans']\n        B, T, _ = trans.size()\n        R_time = R.unsqueeze(1).expand((B, T, 3, 3))\n        t_time = t.unsqueeze(1).expand((B, T, 3))\n        if inverse:\n            # transform so key frame at origin\n            if T > 1:\n                trans_offset = trans[np.arange(B),key_frame_idx,:].unsqueeze(1)\n            else:\n                trans_offset = trans[:,0:1,:]\n            trans = trans - trans_offset\n            # rotates to camera frame\n            trans = torch.matmul(R_time.transpose(3, 2), trans.reshape((B, T, 3, 1)))[:,:,:,0]\n            # translate to camera frame\n            trans = trans - t_time\n        else:\n            # first transform so the trans of key frame is at origin\n            trans = trans + t_time\n            # then rotate to canonical frame\n            trans = torch.matmul(R_time, trans.reshape((B, T, 3, 1)))[:,:,:,0]\n            # then apply floor offset so the root joint is at the desired height\n            cur_smpl_body = body_model(pose_body=body_pose.reshape((-1, body_pose.size(2))), \n                                    pose_hand=None, \n                                    betas=betas.reshape((-1, betas.size(2))),\n                                    root_orient=prior_dict['root_orient'].reshape((-1, 3)),\n                                    trans=trans.reshape((-1, 3)))\n            smpl_joints3d = cur_smpl_body.Jtr.reshape((B, T, -1, 3))\n            if T > 1:\n                cur_root_height = smpl_joints3d[np.arange(B),key_frame_idx,0,2:3]\n            else:\n                cur_root_height = smpl_joints3d[:,0,0,2:3]\n            height_diff = root_height - cur_root_height\n            trans_offset = torch.cat([torch.zeros((B, 2)).to(height_diff), height_diff], axis=1)\n            trans = trans + trans_offset.reshape((B, 1, 3))\n        prior_dict['trans'] = trans\n    elif 'trans' in data_dict:\n        Logger.log('Cannot apply cam2prior on translation without root orient data!')\n        exit()\n\n    return prior_dict\n\n\ndef perspective_projection(points, rotation, translation,\n                           focal_length, camera_center):\n    \"\"\"\n    Adapted from https://github.com/mkocabas/VIBE/blob/master/lib/models/spin.py\n    This function computes the perspective projection of a set of points.\n    Input:\n        points (bs, N, 3): 3D points\n        rotation (bs, 3, 3): Camera rotation\n        translation (bs, 3): Camera translation\n        focal_length (bs, 2): Focal length\n        camera_center (bs, 2): Camera center\n    \"\"\"\n    batch_size = points.shape[0]\n    K = torch.zeros([batch_size, 3, 3], device=points.device)\n    K[:,0,0] = focal_length[:,0]\n    K[:,1,1] = focal_length[:,1]\n    K[:,2,2] = 1.\n    K[:,:-1, -1] = camera_center\n\n    # Transform points\n    points = torch.einsum('bij,bkj->bki', rotation, points)\n    points = points + translation.unsqueeze(1)\n\n    # Apply perspective distortion\n    projected_points = points / points[:,:,-1].unsqueeze(-1)\n\n    # Apply camera intrinsics\n    projected_points = torch.einsum('bij,bkj->bki', K, projected_points)\n\n    return projected_points[:, :, :-1]\n\nOP_NUM_JOINTS = 25\nOP_IGNORE_JOINTS = [1, 9, 12] # neck and left/right hip\nOP_EDGE_LIST = [[1,8], [1,2], [1,5], [2,3], [3,4], [5,6], [6,7], [8,9], [9,10], [10,11], [8,12], [12,13], [13,14], [1,0], [0,15], [15,17], [0,16], [16,18], [14,19], [19,20], [14,21], [11,22], [22,23], [11,24]]\n# indices to map an openpose detection to its flipped version\nOP_FLIP_MAP = [0, 1, 5, 6, 7, 2, 3, 4, 8, 12, 13, 14, 9, 10, 11, 16, 15, 18, 17, 22, 23, 24, 19, 20, 21]\n\n#\n# The following 2 functions are borrowed from VPoser (https://github.com/nghorbani/human_body_prior).\n# See their license for usage restrictions.\n#\ndef expid2model(expr_dir):\n    from configer import Configer\n\n    if not os.path.exists(expr_dir): raise ValueError('Could not find the experiment directory: %s' % expr_dir)\n\n    best_model_fname = sorted(glob.glob(os.path.join(expr_dir, 'snapshots', '*.pt')), key=os.path.getmtime)[-1]\n    try_num = os.path.basename(best_model_fname).split('_')[0]\n\n    print(('Found Trained Model: %s' % best_model_fname))\n\n    default_ps_fname = glob.glob(os.path.join(expr_dir,'*.ini'))[0]\n    if not os.path.exists(\n        default_ps_fname): raise ValueError('Could not find the appropriate vposer_settings: %s' % default_ps_fname)\n    ps = Configer(default_ps_fname=default_ps_fname, work_dir = expr_dir, best_model_fname=best_model_fname)\n\n    return ps, best_model_fname\n\ndef load_vposer(expr_dir, vp_model='snapshot'):\n    '''\n    :param expr_dir:\n    :param vp_model: either 'snapshot' to use the experiment folder's code or a VPoser imported module, e.g.\n    from human_body_prior.train.vposer_smpl import VPoser, then pass VPoser to this function\n    :param if True will load the model definition used for training, and not the one in current repository\n    :return:\n    '''\n    import importlib\n    import os\n    import torch\n\n    ps, trained_model_fname = expid2model(expr_dir)\n    if vp_model == 'snapshot':\n\n        vposer_path = sorted(glob.glob(os.path.join(expr_dir, 'vposer_*.py')), key=os.path.getmtime)[-1]\n\n        spec = importlib.util.spec_from_file_location('VPoser', vposer_path)\n        module = importlib.util.module_from_spec(spec)\n        spec.loader.exec_module(module)\n\n        vposer_pt = getattr(module, 'VPoser')(num_neurons=ps.num_neurons, latentD=ps.latentD, data_shape=ps.data_shape)\n    else:\n        vposer_pt = vp_model(num_neurons=ps.num_neurons, latentD=ps.latentD, data_shape=ps.data_shape)\n\n    vposer_pt.load_state_dict(torch.load(trained_model_fname, map_location='cpu'))\n    vposer_pt.eval()\n\n    return vposer_pt, ps", "meta": {"hexsha": "90bff9f7f50e4d1380b71c4baf495fa1c7f9f2f4", "size": 31469, "ext": "py", "lang": "Python", "max_stars_repo_path": "humor/fitting/fitting_utils.py", "max_stars_repo_name": "davrempe/humor", "max_stars_repo_head_hexsha": "0577f342863be6190bedbc1f27fe3dd0fecb63db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 143, "max_stars_repo_stars_event_min_datetime": "2021-10-09T22:10:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:33:19.000Z", "max_issues_repo_path": "humor/fitting/fitting_utils.py", "max_issues_repo_name": "davrempe/humor", "max_issues_repo_head_hexsha": "0577f342863be6190bedbc1f27fe3dd0fecb63db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2021-10-12T07:49:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T09:44:34.000Z", "max_forks_repo_path": "humor/fitting/fitting_utils.py", "max_forks_repo_name": "davrempe/humor", "max_forks_repo_head_hexsha": "0577f342863be6190bedbc1f27fe3dd0fecb63db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2021-10-10T10:41:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T02:37:33.000Z", "avg_line_length": 42.931787176, "max_line_length": 209, "alphanum_fraction": 0.6317645937, "include": true, "reason": "import numpy", "num_tokens": 8035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118791767282, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.1954629594083306}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec  4 11:35:36 2019\n\n@author: aaussel\n\"\"\"\n\nfrom cells.RE_mdPul import *\nfrom cells.TC_mdPul import *\n#from cells.HTC_mdPul import *\nfrom cells.HTC_buffer_mdPul_Destxhe_tests import *\nfrom scipy import signal\n\n\nprefs.codegen.target = 'numpy'\n\n\ndefaultclock.dt = 0.01*ms\nruntime=2*second\n\n\nstart_scope()\n\ndef generate_syn(source,target,syntype,connection_pattern,g_i,taur_i,taud_i,V_i):\n    eq_syn='''_post=s_i*g_i*(V_post-V_i) : amp * meter ** -2 (summed)\n        ds_i/dt=-s_i/taud_i+(1-s_i)/taur_i*0.5*(1+tanh(V_pre/10/mV)) : 1\n        g_i : siemens * meter**-2\n        V_i : volt\n        taud_i : second\n        taur_i : second\n    '''\n\n    S=Synapses(source,target,model=syntype+eq_syn,method='exact')\n    if connection_pattern=='':\n        S.connect()\n    else :\n        S.connect(j=connection_pattern, skip_if_invalid=True)\n    S.g_i=g_i\n    S.taur_i=taur_i\n    S.taud_i=taud_i\n    S.V_i=V_i  \n    return S\n\ndef mon_delay(mon,i,t_delay):\n    return mon.V[i][-t_delay]\n\ndef generate_syn_delay(source,target,syntype,connection_pattern,g_i,taur_i,taud_i,V_i):\n    eq_syn_delay='''_post=s_i*g_i*(V_post-V_i) : amp * meter ** -2 (summed)\n        ds_i/dt=-s_i/taud_i+(1-s_i)/taur_i*0.5*(1+tanh(voltage_delayed_pre/10/mV)) : 1\n        g_i : siemens * meter**-2\n        V_i : volt\n        taud_i : second\n        taur_i : second\n    '''\n\n    S=Synapses(source,target,model=syntype+eq_syn_delay,method='exact')\n    if connection_pattern=='':\n        S.connect()\n    else :\n        S.connect(j=connection_pattern, skip_if_invalid=True)\n    S.g_i=g_i\n    S.taur_i=taur_i\n    S.taud_i=taud_i\n    S.V_i=V_i  \n    return S\n\ndef generate_spike_timing(N,f,start_time,end_time=runtime):\n    list_time_and_i=[]\n    for i in range(N):\n        list_time=[(start_time,i)]\n        next_spike=list_time[-1][0]+(1+0.1*rand())/f\n        while next_spike<end_time:\n            list_time.append((next_spike,i))\n            next_spike=list_time[-1][0]+(1+0.1*rand())/f\n        list_time_and_i+=list_time\n    return array(list_time_and_i)\n\ndef create_mdPul_column(N_HTC,N_TC,N_RE,condition,in_mode,theta_phase):\n    HTC=NeuronGroup(N_HTC,eq_HTC_buffer_mdPul,threshold='V>0*mvolt',refractory=3*ms,method='rk4')\n    HTC.V = '-25*mvolt'\n    HTC.Ca_iTLT = '1e-7 * mole * metre**-3'\n    HTC.Ca_iTHT = '0.01*mmolar'\n    HTC.J='0 * uA * cmeter ** -2'\n    HTC.mAHP='0.3'\n    \n    TC=NeuronGroup(N_TC,eq_TC_mdPul,threshold='V>0*mvolt',refractory=3*ms,method='rk4')\n    TC.V = '-45*mvolt+20*mvolt*rand()'\n    TC.J='0 * nA * cmeter ** -2'\n    TC.Ca_i = '1e-7 * mole * metre**-3'\n    \n    RE=NeuronGroup(N_RE,eq_RE_mdPul,threshold='V>0*mvolt',refractory=3*ms,method='rk4')\n    RE.V = '-70*mvolt+20*mvolt*rand()'\n    RE.J = '0 * nA * cmeter ** -2'\n    RE.Ca_i = '1e-7 * mole * metre**-3'\n\n\n    ##Define monitors\n    R1=SpikeMonitor(HTC,record=True)\n    R2=SpikeMonitor(TC,record=True)\n    R3=SpikeMonitor(RE,record=True)\n    \n    V1=StateMonitor(HTC,'V',record=True)\n    V2=StateMonitor(TC,'V',record=True)\n    V3=StateMonitor(RE,'V',record=True)\n    \n    I2=StateMonitor(HTC,'ITHT',record=[0])\n    I3=StateMonitor(HTC,'ITLT',record=[0])\n    \n    \n    ##Synapses\n        \n    gAMPA_HTC_RE= 0.1 * msiemens * cm **-2 #0.42 - 0.70\n    gGABA_A_RE_RE = 0.1 * msiemens * cm **-2 #0.42 - 0.70\n    gGABA_A_RE_TC = 0.4 * msiemens * cm **-2\n#    gGABA_A_RE_TC = 0 * msiemens * cm **-2\n#    gGABA_A_HTC_TC = 0.2 * msiemens * cm **-2\n    gGABA_A_HTC_TC = 0.2 * msiemens * cm **-2\n    gGABA_B_RE_TC= gGABA_A_RE_TC*0.1\n    gGABA_A_RE_HTC = 1 * msiemens * cm **-2\n    gGABA_B_RE_HTC= 1 * msiemens * cm **-2\n#    gGABA_A_RE_HTC = 0 * msiemens * cm **-2\n#    gGABA_B_RE_HTC= 0 * msiemens * cm **-2\n    \n    \n    synHTCRE_AMPA=None\n    if condition=='mGluR1':\n        synHTCRE_AMPA = generate_syn(HTC,RE,'IsynHTC','',gAMPA_HTC_RE,0.125*ms,1*ms,0*mV)\n        synHTCRE_AMPA.connect() #all-to-all connection \n\n    synRERE_GABA = generate_syn(RE,RE,'IsynREA','',gGABA_A_RE_RE,0.25*ms,5*ms,-80*mV)\n    synRETC_A=generate_syn(RE,TC,'IsynREA','',gGABA_A_RE_TC,0.25*ms,5*ms,-80*mV)\n    synRETC_B=generate_syn(RE,TC,'IsynREB','',gGABA_B_RE_TC,20*ms,100*ms,-80*mV)\n    synREHTC_A=generate_syn(RE,HTC,'IsynREintGABAA','',gGABA_A_RE_HTC,0.25*ms,5*ms,-80*mV)\n    synREHTC_B=generate_syn(RE,HTC,'IsynREintGABAB','',gGABA_B_RE_HTC,20*ms,100*ms,-80*mV)\n    \n    synHTCTC=generate_syn_delay(HTC,TC,'IsynHTC','',gGABA_A_HTC_TC,0.25*ms,5*ms,-80*mV)\n#    synHTCTC=generate_syn(HTC,TC,'IsynHTC','',gGABA_A_HTC_TC,0.25*ms,5*ms,-80*mV)\n#    if in_mode=='burst':\n#        if condition=='mAChR':\n#            synHTCTC=generate_syn_delay(HTC,TC,'IsynHTC','',gGABA_A_HTC_TC,0.25*ms,5*ms,-80*mV)\n#    #        synHTCTC.delay=delayTC\n#            \n#        if condition=='mGluR1':\n#            synHTCTC=generate_syn_delay(HTC,TC,'IsynHTC','',gGABA_A_HTC_TC,0.25*ms,5*ms,-80*mV)\n#    #        synHTCTC.delay=delayTC\n#    else :\n#        if condition=='mAChR':\n#            synHTCTC=generate_syn(HTC,TC,'IsynHTC','',gGABA_A_HTC_TC,0.25*ms,5*ms,-80*mV)\n#    #        synHTCTC.delay=delayTC\n#            \n#        if condition=='mGluR1':\n#            synHTCTC=generate_syn(HTC,TC,'IsynHTC','',gGABA_A_HTC_TC,0.25*ms,5*ms,-80*mV)\n#    #        synHTCTC.delay=delayTC\n        \n    GJ_HTC=Synapses(HTC,HTC,'''\n                 w : siemens * meter **-2 # gap junction conductance\n                 IGJ_post = w * (V_post - V_pre) : amp * meter ** -2 (summed)\n                 ''')\n    GJ_HTC.connect()\n    #GJ_HTC.w = 0.003e-3 * siemens * cm **-2\n    GJ_HTC.w = 0.08e-3 * siemens * cm **-2\n    \n    gEPSP_RE = 20 * msiemens * cm **-2 #0.42 - 0.70\n#    gEPSP_TC = 0.5 * msiemens * cm **-2 #0.42 - 0.70\n    gEPSP_TC = 0 * msiemens * cm **-2 #0.42 - 0.70\n    gEPSP_TC2 = 10 * msiemens * cm **-2 #0.42 - 0.70\n    gIPSP_TC = -1.5 * gEPSP_TC    \n    #Inputs : \n    inputs_TC=generate_spike_timing(N_TC,100*Hz,0*ms,end_time=3000*ms)\n    G_in = SpikeGeneratorGroup(N_TC, inputs_TC[:,1], inputs_TC[:,0]*second)\n    Syn_in=Synapses(G_in,TC,on_pre='Vinp=Vhigh')\n    Syn_in.connect(j='i')\n    TC.ginp_TC=gEPSP_TC\n    \n    inputs_RE=generate_spike_timing(N_RE,13*Hz,0*ms,end_time=3000*ms)\n    G_in2 = SpikeGeneratorGroup(N_RE, inputs_RE[:,1], inputs_RE[:,0]*second)\n    Syn_in2=Synapses(G_in2,RE,on_pre='Vinp=Vhigh')\n    Syn_in2.connect(j='i')\n    \n    inputs_TC3=generate_spike_timing(N_TC,13*Hz,0*ms,end_time=3000*ms)\n    G_in3 = SpikeGeneratorGroup(N_TC, inputs_TC3[:,1], inputs_TC3[:,0]*second)\n    Syn_in3=Synapses(G_in3,TC,on_pre='Vinp=Vhigh')\n    Syn_in3.connect(j='i')\n    \n#    inputs_HTC=generate_spike_timing(N_HTC,13*Hz,0*ms,end_time=3000*ms)\n#    G_in4 = SpikeGeneratorGroup(N_HTC, inputs_HTC[:,1], inputs_HTC[:,0]*second)\n#    Syn_in4=Synapses(G_in4,HTC,on_pre='Vinp=Vhigh')\n#    Syn_in4.connect(j='i')  \n#    HTC.ginp_HTC=0e-3 * siemens * cm **-2\n    \n    if theta_phase=='bad':\n        RE.ginp_RE=gEPSP_RE\n        TC.ginp_TC2=gEPSP_TC2\n    \n    all_neurons=HTC,TC,RE,G_in,G_in2,G_in3\n    all_synapses=synHTCRE_AMPA,synRERE_GABA,synRETC_A,synRETC_B,synREHTC_A,synREHTC_B,synHTCTC,Syn_in,Syn_in2,Syn_in3\n    all_synapses=tuple([y for y in all_synapses if y])\n    all_monitors=R1,R2,R3,V1,V2,V3,I2,I3\n    all_gap_junctions=(GJ_HTC,)\n    \n#    if in_mode=='single_spike':\n#        HTC.delay_steps = [1]  # delay in time steps per neuron\n#        buffer_size = 2  # 1+Maximum delay (in time steps)\n#    else :\n#        HTC.delay_steps = [3999]  # delay in time steps per neuron\n#        buffer_size = 4000  # 1+Maximum delay (in time steps)\n#        \n#    print(HTC.delay_steps)\n#    HTC.variables.add_array('voltage_buffer', dimensions=volt.dim, size=(buffer_size, len(HTC)))\n#    \n#    update_code = '''buffer_pointer = (buffer_pointer + 1) % buffer_size\n#                     voltage_delayed = update_voltage_buffer(V, voltage_buffer, buffer_pointer, delay_steps, buffer_size)'''\n#       \n#    buffer_updater = HTC.run_regularly(update_code, codeobj_class=NumpyCodeObject)\n#        \n#    @check_units(V=volt, voltage_buffer=volt, buffer_pointer=1, delay_steps=1, buffer_size=1, result=volt)\n#    def update_voltage_buffer(V, voltage_buffer, buffer_pointer, delay_steps, buffer_size):\n#        # Write current rate into the buffer\n#        voltage_buffer[buffer_pointer, :] = V\n#        # Get delayed rates \n#        rows = (buffer_pointer - delay_steps) % buffer_size    \n#        return voltage_buffer[rows, arange(len(rows))]\n    \n    return all_neurons,all_synapses,all_gap_junctions,all_monitors\n\n\nif __name__=='__main__':\n    close('all')\n    runtime=1*second\n    f=13*Hz #rythmic input frequency\n    input_on=False\n    N_HTC,N_TC,N_RE= 20,80,100 #Number of neurons of RE, TC, and HTC type\n#    N_HTC,N_TC,N_RE= 1,80,100 #Number of neurons of RE, TC, and HTC type\n\n    Vrev_inp=0*mV\n    taurinp=0.1*ms\n    taudinp=0.5*ms\n    tauinp=taudinp\n    Vhigh=0*mV\n    Vlow=-80*mV\n    ginp_IB=0* msiemens * cm **-2\n    ginp=0* msiemens * cm **-2\n    \n    Vrev_inp2=0*mV\n    taurinp2=0.1*ms\n    taudinp2=0.5*ms\n    tauinp2=taudinp2\n    Vhigh2=0*mV\n    Vlow2=-80*mV\n    \n    #condition='mGluR1'\n    condition='mAChR'\n#    in_mode='single_spike'\n    in_mode='burst'\n    theta_phase='good'\n\n    if condition=='mGluR1':\n        gKL_TC=0.0028e-3 * siemens * cm **-2\n        gKL_HTC=0.0069e-3 * siemens * cm **-2\n        gKL_RE=0.05e-3 * siemens * cm **-2   \n    elif condition=='mAChR':\n        gKL_TC=0.0028e-3 * siemens * cm **-2\n        gKL_HTC=0.0069e-3 * siemens * cm **-2\n        gKL_RE=0.08e-3 * siemens * cm **-2\n        \n#    Cm_HTC = 2.5* ufarad * cm ** -2\n#    gNa_HTC=90e-3 * siemens * cm **-2\n#    ENa_HTC=50*mV\n#    gK_HTC=10e-3 * siemens * cm **-2\n#    EK_HTC=-100*mV\n#    gL_HTC=0.001e-3 * siemens * cm **-2  \n#    EL_HTC=-70*mV\n    gKL_HTC=0.001e-3 * siemens * cm **-2  \n#    EKL_HTC=-100*mV\n#    gTLT_HTC= 2.1e-3 * siemens * cm **-2\n#    gTHT_HTC= 15e-3 * siemens * cm **-2\n#    gAHP_HTC= 45e-3 * siemens * cm **-2\n#    EAHP=-95*mV\n#    gH_HTC = 0.36e-3 * siemens * cm **-2\n#    EH_HTC = -40 * mV\n    gapp=0.1*mamp * cmeter ** -2 # in HTC cells\n#    gapp=0.001*mamp * cmeter ** -2 # in HTC cells\n    \n    net=Network()\n    all_neurons,all_synapses,all_gap_junctions,all_monitors=create_mdPul_column(N_HTC,N_TC,N_RE,condition,in_mode,theta_phase)\n#    R1,R2,R3,V1,V2,V3=all_monitors\n    R1,R2,R3,V1,V2,V3,I2,I3=all_monitors\n    \n    HTC=all_neurons[0]\n    if in_mode=='single_spike':\n        HTC.delay_steps = [1]  # delay in time steps per neuron\n        buffer_size = 2  # 1+Maximum delay (in time steps)\n    else :\n        HTC.delay_steps = [3999]  # delay in time steps per neuron\n        buffer_size = 4000  # 1+Maximum delay (in time steps)\n    \n    init_array=-70*mV*ones((buffer_size, len(HTC)))\n    HTC.variables.add_array('voltage_buffer', dimensions=volt.dim, size=(buffer_size, len(HTC)))#,values=init_array)\n    HTC.voltage_buffer=init_array\n    \n    update_code = '''buffer_pointer = (buffer_pointer + 1) % buffer_size\n                     voltage_delayed = update_voltage_buffer(V, voltage_buffer, buffer_pointer, delay_steps, buffer_size)'''\n       \n    buffer_updater = HTC.run_regularly(update_code, codeobj_class=NumpyCodeObject)\n        \n    @check_units(V=volt, voltage_buffer=volt, buffer_pointer=1, delay_steps=1, buffer_size=1, result=volt)\n    def update_voltage_buffer(V, voltage_buffer, buffer_pointer, delay_steps, buffer_size):\n        # Write current rate into the buffer\n        voltage_buffer[buffer_pointer, :] = V\n        # Get delayed rates \n        rows = (buffer_pointer - delay_steps) % buffer_size    \n        return voltage_buffer[rows, arange(len(rows))]\n        \n#    print(HTC.delay_steps)\n        \n    SynHTCTC=all_synapses[5]\n    \n    net.add(all_neurons)\n    net.add(all_synapses)\n    net.add(all_gap_junctions)\n    net.add(all_monitors)\n\n    TC=all_neurons[1]\n    M=StateMonitor(TC,'Isyn', record=True)\n    M2=StateMonitor(HTC,'voltage_delayed', record=True)\n    M3=StateMonitor(SynHTCTC,'s_i',record=[0])\n    net.add(M,M2,M3)\n            \n    prefs.codegen.target = 'cython'\n    net.run(runtime,report='text',report_period=300*second)\n    \n    \n    figure()\n    plot(R1.t,R1.i+0,'r.',label='HTC')\n    plot(R2.t,R2.i+20,'b.',label='TC')\n    plot(R3.t,R3.i+100,'g.',label='RE')\n    xlim(0,runtime/second)\n    legend()  \n    \n    figure()\n    plot(V1.t,V1.V[0],label='HTC V')\n    plot(V2.t,V2.V[0],label='TC V')\n    plot(V3.t,V3.V[0],label='RE V')\n    legend()\n    \n#    figure()\n#    plot(I1.t,I1.ISK[0],label='I_SK HTC')\n#    legend()\n    \n#    figure()\n#    plot(I2.t,I2.ITHT[0],label='I_THT HTC')\n#    legend()\n#    \n#    figure()\n#    plot(I3.t,I3.ITLT[0],label='I_TLT HTC')\n#    legend()\n        \n#    f,Spectrum_LFP_V1=signal.periodogram(V1.V[0], 100000,'flattop', scaling='spectrum')\n#    figure()\n#    plot(f,Spectrum_LFP_V1)\n#    xlim(0,100)\n    Isyn_calc=(V2.V[0]+80*mV)*0.2 * msiemens * cm **-2*M3.s_i[0]\n    \n    figure()\n    plot(M.t,M.Isyn[0],label='I_syn HTC-TC')\n    plot(M2.t,M2.voltage_delayed[0],label='HTC voltage_delayed')\n    plot(V2.t,V2.V[0],label='TC V')\n    plot(V1.t,V1.V[0],label='HTC V')\n    plot(M3.t,M3.s_i[0],label='s_i syn HTC-TC')\n    plot(M3.t,Isyn_calc,label='Isyn HTC-TC calc')\n    legend()\n    \n\n    clear_cache('cython') \n    \n", "meta": {"hexsha": "e0d390a2bd500c9f1e284e78b82031a0a38cd921", "size": 13169, "ext": "py", "lang": "Python", "max_stars_repo_path": "mdPul_one_column.py", "max_stars_repo_name": "benpolletta/egly-driver-network", "max_stars_repo_head_hexsha": "cff36a857e22358d122f24fb0100be26483a3caf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-06T18:13:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-06T18:13:12.000Z", "max_issues_repo_path": "mdPul_one_column.py", "max_issues_repo_name": "benpolletta/egly-driver-network", "max_issues_repo_head_hexsha": "cff36a857e22358d122f24fb0100be26483a3caf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mdPul_one_column.py", "max_forks_repo_name": "benpolletta/egly-driver-network", "max_forks_repo_head_hexsha": "cff36a857e22358d122f24fb0100be26483a3caf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0239361702, "max_line_length": 126, "alphanum_fraction": 0.6273824892, "include": true, "reason": "from scipy", "num_tokens": 4785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19546295367409278}}
{"text": "\"\"\"\nPlease cite this paper if you re-use parts of the code\nS. Koehler, T. Hussain, Z. Blair, T. Huffaker, F. Ritzmann, A. Tandon, T. Pickardt, S. Sarikouch, H. Latus, G. Greil, I. Wolf, S. Engelhardt, \n\"Unsupervised Domain Adaptation from Axial to Short-Axis Multi-Slice Cardiac MR Images by Incorporating Pretrained Task Networks,\" \nin IEEE Transactions on Medical Imaging (TMI), early access, doi: 10.1109/TMI.2021.3052972.\n\nThe spatial transformer layer is based on the neuron project:\nUnsupervised Learning for Fast Probabilistic Diffeomorphic Registration\nAdrian V. Dalca, Guha Balakrishnan, John Guttag, Mert R. Sabuncu\nMICCAI 2018.\n\"\"\"\n\n# main imports\nimport logging\nimport sys\n\n# third party\nimport numpy as np\nimport tensorflow\nimport tensorflow as tf\nimport tensorflow.keras.initializers\nfrom tensorflow.keras.initializers import RandomNormal\nfrom tensorflow.keras.layers import Input\nfrom tensorflow.keras.models import Model\n\nimport src.utils.Loss_and_metrics as metr\nfrom src.models.KerasLayers import Euler2Matrix, UnetWrapper, ConvEncoder, Inverse3DMatrix\nfrom src.models.ModelUtils import get_optimizer\n\nsys.path.append('src/models/ext/neuron')\nsys.path.append('src/models/ext/pynd-lib')\nsys.path.append('src/models/ext/pytools-lib')\nimport src.models.ext.neuron.neuron.layers as nrn_layers\n\n\ndef create_affine_cycle_transformer_model(config, networkname='affine_cycle_transformer', unet=None):\n    \"\"\"\n    Create a compiled Domain adaption (AX2SAX) spatial transformer model with three loss functions.\n\n    :param config: Key value pairs for image size and other network parameters\n    :param metrics: list of tensorflow or keras compatible metrics\n    :param networkname: string, name of this model scope\n    :param unet: tf.keras.Model, pre-trained 2D U-net\n    :return: compiled tf.keras.Model\n\n    The returned tf.keras.Model expects the following input during training:\n    [ax_cmr,  sax_cmr]\n    and returns the following elements:\n    [ax2sax_cmr, sax2ax_cmr, ax2sax_mod_cmr,sax_msk, ax_msk, m, m_mod]\n    During inference sax_cmr could be None or a zero initialised ndarray\n\n    This model has the following flow:\n    inputs = [AX, SAX]\n    m, m_mod = Encoder(AX)\n    m_inv = Inverse(m)\n    ax2sax = SpatialTransformer(AX, m)\n    ax2sax = SpatialTransformer(AX, m_mod)\n    sax2ax = SpatialTransformer(SAX, m_inv)\n    sax_msk = Unet(SAX)\n    ax_msk = SpatialTransformer(sax_msk, m_mod)\n    outputs = [ax2sax, sax2ax, ax2sax_mod, sax_msk, ax_msk, m, m_mod]\n\n    This model calculates the gradients according to the following loss functions:\n    MSE_mod(ax2sax_gt, ax2sax_pred) # learn an affine transformation that fits to our gt\n    MSE_mod(sax2ax_gt, sax2ax_pred) # apply the opposite transformation to align the cycle consistency\n    Loss_focus(ax_msk) or Loss_focus(sax_msk)\n\n    - MSE_mod = MSE(y_true, y_pred) * weighting[None, None,: , : ],\n    Example in-plane weighting with an in-plane resolution of 10 x 10 pixels:\n    weighting =\n    [[0.   0.   0.   0.   0.   0.   0.   0.   0.   0.  ]\n     [0.   0.25 0.25 0.25 0.25 0.25 0.25 0.25 0.25 0.  ]\n     [0.   0.25 0.5  0.5  0.5  0.5  0.5  0.5  0.25 0.  ]\n     [0.   0.25 0.5  0.75 0.75 0.75 0.75 0.5  0.25 0.  ]\n     [0.   0.25 0.5  0.75 1.   1.   0.75 0.5  0.25 0.  ]\n     [0.   0.25 0.5  0.75 1.   1.   0.75 0.5  0.25 0.  ]\n     [0.   0.25 0.5  0.75 0.75 0.75 0.75 0.5  0.25 0.  ]\n     [0.   0.25 0.5  0.5  0.5  0.5  0.5  0.5  0.25 0.  ]\n     [0.   0.25 0.25 0.25 0.25 0.25 0.25 0.25 0.25 0.  ]\n     [0.   0.   0.   0.   0.   0.   0.   0.   0.   0.  ]]\n\n    - Loss_focus =\n        # ignore background, we want to maximize the number of captured ventricle voxel\n        y_pred = y_pred[...,1:] if background given by the U-Net predictions\n        y_pred = tf.cast(y_pred, dtype=tf.float32)\n        # keep only the highest prob\n        sum_bigger_than = tf.reduce_max(y_pred, axis=-1)\n        # create a mask of voxels greater than the threshold\n        mask_bigger_than = tf.cast(sum_bigger_than > min_probabillity, tf.float32)\n        # we cant use the mask directly as this creates no gradients, this keeps also the prob value\n        sum_bigger_than = sum_bigger_than * mask_bigger_than\n        # return a scalar between 0 and 1, the loss is typically close to 1, as the background class is overrepresented\n        return 1- tf.reduce_mean(sum_bigger_than)\n    \"\"\"\n\n    if tf.distribute.has_strategy():\n        strategy = tf.distribute.get_strategy()\n    else:\n        # distribute the training with the \"mirrored data\"-paradigm across multiple gpus if available, if not use gpu 0\n        strategy = tf.distribute.MirroredStrategy(devices=config.get('GPUS', [\"/gpu:0\"]))\n    with strategy.scope():\n\n        input_shape = config.get('DIM', [10, 224, 224])\n        inputs_ax = Input((*input_shape, config.get('IMG_CHANNELS', 1)))\n        inputs_sax = Input((*input_shape, config.get('IMG_CHANNELS', 1)))\n        # define standard values according to the convention over configuration paradigm\n        activation = config.get('ACTIVATION', 'elu')\n        batch_norm = config.get('BATCH_NORMALISATION', False)\n        pad = config.get('PAD', 'same')\n        kernel_init = config.get('KERNEL_INIT', 'he_normal')\n        m_pool = config.get('M_POOL', (1, 2, 2))\n        f_size = config.get('F_SIZE', (3, 3, 3))\n        filters = config.get('FILTERS', 16)\n        drop_1 = config.get('DROPOUT_min', 0.3)\n        drop_3 = config.get('DROPOUT_max', 0.5)\n        bn_first = config.get('BN_FIRST', False)\n        ndims = len(config.get('DIM', [10, 224, 224]))\n        depth = config.get('DEPTH', 4)\n        dense_weights = config.get('DENSE_WEIGHTS', 256)\n        indexing = config.get('INDEXING', 'ij')\n\n        weight_mse_inplane = config.get('WEIGHT_MSE_INPLANE',\n                                        True)  # weight the MSE loss pixels in the center have greater weights\n        mask_smaller_than_threshold = config.get('MASK_SMALLER_THAN_THRESHOLD',\n                                                 0.01)  # calc the MSe loss only where our image has values greater than\n        ax_weight = config.get('AX_LOSS_WEIGHT', 2)\n\n        cycle_loss = config.get('CYCLE_LOSS', False)\n        sax_weight = config.get('SAX_LOSS_WEIGHT', 2)\n\n        focus_loss = config.get('FOCUS_LOSS', False)\n        focus_weight = config.get('FOCUS_LOSS_WEIGHT', 1)\n        min_unet_probability = config.get('MIN_UNET_PROBABILITY',\n                                          0.9)  # sum the foreground voxels with a prob higher than\n        use_mask2ax_prob = config.get('USE_SAX2AX_PROB', True)  # otherwise use the SAX probability\n\n        # increase the dropout through the layer depth\n        dropouts = list(np.linspace(drop_1, drop_3, depth))\n        dropouts = [round(i, 1) for i in dropouts]\n\n        enc, _ = ConvEncoder(activation=activation,\n                             batch_norm=batch_norm,\n                             bn_first=bn_first,\n                             depth=depth,\n                             drop_3=drop_3,\n                             dropouts=dropouts,\n                             f_size=f_size,\n                             filters=filters,\n                             kernel_init=kernel_init,\n                             m_pool=m_pool,\n                             ndims=ndims,\n                             pad=pad)(inputs_ax)\n\n        # Shrink the encoding towards the euler angles and translation params,\n        # no additional dense layers before the GAP layer\n        m_raw = tensorflow.keras.layers.GlobalAveragePooling3D()(enc)  # m.shape --> b, 512\n        m_raw = tensorflow.keras.layers.Dense(dense_weights, kernel_initializer=kernel_init, activation=activation,\n                                              name='dense1')(m_raw)\n        m_raw = tensorflow.keras.layers.Dense(9, kernel_initializer=RandomNormal(mean=0.0, stddev=1e-10),\n                                              activation=activation, name='dense2')(m_raw)\n        m = Euler2Matrix(name='ax2sax_matrix')(m_raw[:, 0:6])\n\n        # Cycle flow - use M and the inverse M to transform the SAX and AX input\n        ax2sax = nrn_layers.SpatialTransformer(interp_method='linear', indexing=indexing, ident=False, fill_value=0,\n                                               name='ax2sax')([inputs_ax, m])\n        m_inv = Inverse3DMatrix()(m)\n        sax2ax = nrn_layers.SpatialTransformer(interp_method='linear', indexing=indexing, ident=False, fill_value=0,\n                                               name='sax2ax')([inputs_sax, m_inv])\n\n        if unet:\n            logging.info('unet given, use it to max probability')\n\n            # concat the rotation parameters with the second set of translation params\n            m_mod = tf.keras.layers.Concatenate(axis=-1)([m_raw[:, 0:3], m_raw[:, 6:9]])  # rot + translation\n            m_mod = Euler2Matrix(name='ax2sax_mod_matrix')(m_mod)  #\n            ax2sax_mod = nrn_layers.SpatialTransformer(interp_method='linear', indexing=indexing, ident=False,\n                                                       fill_value=0, name='ax2sax_mod_st')([inputs_ax, m_mod])\n\n            # we use the probabilities of a pre-trained U-net with fixed weights\n            # to learn a second set of translation parameters which maximize the Unet probability\n            mask_prob = UnetWrapper(unet, name='mask_prob')(ax2sax_mod)  #\n            m_mod_inv = Inverse3DMatrix()(m_mod)  #\n            mask2ax = nrn_layers.SpatialTransformer(interp_method='nearest', indexing=indexing, ident=False,\n                                                    fill_value=0, name='mask2ax')([mask_prob, m_mod_inv])\n            # Define the model output\n            outputs = [ax2sax, sax2ax, ax2sax_mod, mask_prob, mask2ax, m, m_mod]\n\n            # baseline loss\n            logging.info('adding ax2sax MSE loss with a weighting of {}'.format(ax_weight))\n            losses = {'ax2sax': metr.loss_with_zero_mask(mask_smaller_than=mask_smaller_than_threshold,\n                                                         weight_inplane=weight_mse_inplane, xy_shape=input_shape[-2])}\n            loss_w = {'ax2sax': ax_weight}\n\n            # extend losses by cycle MSE loss\n            if cycle_loss:\n                logging.info('adding cycle loss with a weighting of {}'.format(sax_weight))\n                losses['sax2ax'] = metr.loss_with_zero_mask(mask_smaller_than=mask_smaller_than_threshold,\n                                                            weight_inplane=weight_mse_inplane, xy_shape=input_shape[-2])\n                loss_w['sax2ax'] = sax_weight\n\n            # extend losses by probability loss\n            if focus_loss:\n                # Use the SAX predictions or the SAX2AX predictions to maximise the unet probability\n                # probability_object must fit a output-layer name\n                if use_mask2ax_prob:\n                    probability_object = 'mask2ax'\n                else:\n                    probability_object = 'mask_prob'\n                logging.info('adding focus loss on {} with a weighting of {}'.format(probability_object, focus_weight))\n                losses[probability_object] = metr.max_volume_loss(min_probability=min_unet_probability)\n                loss_w[probability_object] = focus_weight\n\n\n        else:  # no u-net given\n            outputs = [ax2sax, sax2ax, m]\n            # baseline loss\n            logging.info('adding ax2sax MSE loss with a weighting of {}'.format(ax_weight))\n            losses = {'ax2sax': metr.loss_with_zero_mask(mask_smaller_than=mask_smaller_than_threshold,\n                                                         weight_inplane=weight_mse_inplane,\n                                                         xy_shape=input_shape[-2])}\n            loss_w = {'ax2sax': ax_weight}\n\n            # extend losses by cycle MSE loss\n            if cycle_loss:\n                logging.info('adding cycle MSE loss with a weighting of {}'.format(sax_weight))\n                losses['sax2ax'] = metr.loss_with_zero_mask(mask_smaller_than=mask_smaller_than_threshold,\n                                                            weight_inplane=weight_mse_inplane,\n                                                            xy_shape=input_shape[-2])\n                loss_w['sax2ax'] = sax_weight\n\n        model = Model(inputs=[inputs_ax, inputs_sax], outputs=outputs, name=networkname)\n        model.compile(optimizer=get_optimizer(config, networkname), loss=losses, loss_weights=loss_w)\n\n        return model\n\n\n# ST to apply m to an volume\ndef create_affine_transformer_fixed(config, metrics=None, networkname='affine_transformer_fixed', fill_value=0,\n                                    interp_method='linear'):\n    \"\"\"\n    Apply a learned transformation matrix to an input image, no training possible\n    :param config:  Key value pairs for image size and other network parameters\n    :param metrics: list of tensorflow or keras compatible metrics\n    :param networkname: string, name of this model scope\n    :param fill_value:\n    :return: compiled tf.keras model\n    \"\"\"\n    if tf.distribute.has_strategy():\n        strategy = tf.distribute.get_strategy()\n    else:\n        # distribute the training with the mirrored data paradigm across multiple gpus if available, if not use gpu 0\n        strategy = tf.distribute.MirroredStrategy(devices=config.get('GPUS', [\"/gpu:0\"]))\n\n    with strategy.scope():\n\n        inputs = Input((*config.get('DIM', [10, 224, 224]), config.get('IMG_CHANNELS', 1)))\n        input_matrix = Input((12), dtype=np.float32)\n        indexing = config.get('INDEXING', 'ij')\n\n        # warp the source with the flow\n        y = nrn_layers.SpatialTransformer(interp_method=interp_method, indexing=indexing, ident=False,\n                                          fill_value=fill_value)([inputs, input_matrix])\n\n        model = Model(inputs=[inputs, input_matrix], outputs=[y, input_matrix], name=networkname)\n\n        return model\n", "meta": {"hexsha": "d08d45ced822cfe8c0bb90a05835cf2702d8b2a6", "size": 13922, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/models/SpatialTransformer.py", "max_stars_repo_name": "Cardio-AI/3d-mri-domain-adaptation", "max_stars_repo_head_hexsha": "2a1b8332039aa25b8291cfd746cbcf87f71068c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-12-16T14:18:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-11T11:20:22.000Z", "max_issues_repo_path": "src/models/SpatialTransformer.py", "max_issues_repo_name": "HabibMrad/3d-mri-domain-adaptation", "max_issues_repo_head_hexsha": "2a1b8332039aa25b8291cfd746cbcf87f71068c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/models/SpatialTransformer.py", "max_forks_repo_name": "HabibMrad/3d-mri-domain-adaptation", "max_forks_repo_head_hexsha": "2a1b8332039aa25b8291cfd746cbcf87f71068c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-16T18:37:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T18:37:52.000Z", "avg_line_length": 52.1423220974, "max_line_length": 142, "alphanum_fraction": 0.6236172964, "include": true, "reason": "import numpy", "num_tokens": 3538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19546295367409278}}
{"text": "#! -*- coding: utf-8 -*-\n# 自定义层\n\nimport numpy as np\nimport tensorflow as tf\nfrom .backend import keras, K, get_all_attributes\n\n# 等价于 from keras.layers import *\nlocals().update(get_all_attributes(keras.layers))\n# 等价于 from keras.models import Model\nlocals()['Model'] = keras.models.Model\n# 等价于 from keras.utils import get_custom_objects\nlocals()['get_custom_objects'] = keras.utils.get_custom_objects\n\n\ndef gelu_erf(x):\n    # 基于Erf直接计算的gelu函数\n    return 0.5 * x * (1.0 + tf.math.erf(x / np.sqrt(2.0)))\n\n\ndef gelu_tanh(x):\n    # 基于Tanh近似计算的gelu函数\n    cdf = 0.5 * (1.0 + K.tanh(\n        (np.sqrt(2 / np.pi) * (x + 0.044715 * K.pow(x, 3)))))\n    return x * cdf\n\n\ndef add_seq_mask(x, mask, mode=0, axis=None, heads=1):\n    \"\"\"为序列条件mask的函数\n    mask: 形如(batch_size, seq_len)的0-1矩阵；\n    mode: 如果是0，则直接乘以mask；\n          如果是1，则在padding部分减去一个大正数。\n    axis: 序列所在轴，默认为1；\n    heads: 相当于batch这一维要被重复的次数。\n    \"\"\"\n    if mask is None or mode not in [0, 1]:\n        return x\n    else:\n        if heads is not 1:\n            mask = K.expand_dims(mask, 1)\n            mask = K.tile(mask, (1, heads, 1))\n            mask = K.reshape(mask, (-1, K.shape(mask)[2]))\n        if axis is None:\n            axis = 1\n        if axis == -1:\n            axis = K.ndim(x) - 1\n        assert axis > 0, 'axis muse be greater than 0'\n        for _ in range(axis - 1):\n            mask = K.expand_dims(mask, 1)\n        for _ in range(K.ndim(x) - K.ndim(mask) - axis + 1):\n            mask = K.expand_dims(mask, K.ndim(mask))\n        if mode == 0:\n            return x * mask\n        else:\n            return x - (1 - mask) * 1e12\n\n\nclass MultiHeadAttention(Layer):\n    \"\"\"多头注意力机制\n    \"\"\"\n    def __init__(self, heads, head_size, key_size=None, **kwargs):\n        super(MultiHeadAttention, self).__init__(**kwargs)\n        self.heads = heads\n        self.head_size = head_size\n        self.out_dim = heads * head_size\n        self.key_size = key_size if key_size else head_size\n\n    def build(self, input_shape):\n        super(MultiHeadAttention, self).build(input_shape)\n        self.q_dense = Dense(self.key_size * self.heads)\n        self.k_dense = Dense(self.key_size * self.heads)\n        self.v_dense = Dense(self.out_dim)\n        self.o_dense = Dense(self.out_dim)\n\n    def call(self, inputs, q_mask=False, v_mask=False, a_mask=False):\n        \"\"\"实现多头注意力\n        q_mask: 对输入的query序列的mask。\n                主要是将输出结果的padding部分置0。\n        v_mask: 对输入的value序列的mask。\n                主要是防止attention读取到padding信息。\n        a_mask: 对attention矩阵的mask。\n                不同的attention mask对应不同的应用。\n        \"\"\"\n        q, k, v = inputs[:3]\n        # 处理mask\n        idx = 3\n        if q_mask:\n            q_mask = inputs[idx]\n            idx += 1\n        else:\n            q_mask = None\n        if v_mask:\n            v_mask = inputs[idx]\n            idx += 1\n        else:\n            v_mask = None\n        if a_mask:\n            if len(inputs) > idx:\n                a_mask = inputs[idx]\n            else:\n                a_mask = 'history_only'\n        else:\n            a_mask = None\n        # 线性变换\n        qw = self.q_dense(q)\n        kw = self.k_dense(k)\n        vw = self.v_dense(v)\n        # 形状变换\n        qw = K.reshape(qw, (-1, K.shape(q)[1], self.heads, self.key_size))\n        kw = K.reshape(kw, (-1, K.shape(k)[1], self.heads, self.key_size))\n        vw = K.reshape(vw, (-1, K.shape(v)[1], self.heads, self.head_size))\n        # 维度置换\n        qw = K.permute_dimensions(qw, (0, 2, 1, 3))\n        kw = K.permute_dimensions(kw, (0, 2, 1, 3))\n        vw = K.permute_dimensions(vw, (0, 2, 1, 3))\n        # 转为三阶张量\n        qw = K.reshape(qw, (-1, K.shape(q)[1], self.key_size))\n        kw = K.reshape(kw, (-1, K.shape(k)[1], self.key_size))\n        vw = K.reshape(vw, (-1, K.shape(v)[1], self.head_size))\n        # Attention\n        a = K.batch_dot(qw, kw, [2, 2]) / np.sqrt(self.key_size)\n        a = add_seq_mask(a, v_mask, 1, -1, self.heads)\n        if a_mask is not None:\n            if a_mask == 'history_only':\n                ones = K.ones_like(a[:1])\n                a_mask = (ones - tf.matrix_band_part(ones, -1, 0)) * 1e12\n                a = a - a_mask\n            else:\n                a = a - (1 - a_mask) * 1e12\n        a = K.softmax(a)\n        # 完成输出\n        o = K.batch_dot(a, vw, [2, 1])\n        o = K.reshape(o, (-1, self.heads, K.shape(q)[1], self.head_size))\n        o = K.permute_dimensions(o, (0, 2, 1, 3))\n        o = K.reshape(o, (-1, K.shape(o)[1], self.out_dim))\n        o = self.o_dense(o)\n        o = add_seq_mask(o, q_mask, 0)\n        return o\n\n    def compute_output_shape(self, input_shape):\n        return (input_shape[0][0], input_shape[0][1], self.out_dim)\n\n    def get_config(self):\n        config = {\n            'heads': self.heads,\n            'head_size': self.head_size,\n            'key_size': self.key_size\n        }\n        base_config = super(MultiHeadAttention, self).get_config()\n        return dict(list(base_config.items()) + list(config.items()))\n\n\nclass LayerNormalization(Layer):\n    \"\"\"实现基本的Layer Norm，只保留核心运算部分\n    \"\"\"\n    def __init__(self, **kwargs):\n        super(LayerNormalization, self).__init__(**kwargs)\n        self.epsilon = K.epsilon() * K.epsilon()\n\n    def build(self, input_shape):\n        super(LayerNormalization, self).build(input_shape)\n        shape = (input_shape[-1], )\n        self.gamma = self.add_weight(shape=shape,\n                                     initializer='ones',\n                                     name='gamma')\n        self.beta = self.add_weight(shape=shape,\n                                    initializer='zeros',\n                                    name='beta')\n\n    def call(self, inputs):\n        mean = K.mean(inputs, axis=-1, keepdims=True)\n        variance = K.mean(K.square(inputs - mean), axis=-1, keepdims=True)\n        std = K.sqrt(variance + self.epsilon)\n        outputs = (inputs - mean) / std\n        outputs *= self.gamma\n        outputs += self.beta\n        return outputs\n\n\nclass FactorizedEmbedding(Layer):\n    \"\"\"基于低秩分解的Embedding层\n    \"\"\"\n    def __init__(self, input_dim, output_dim, hidden_dim=None, **kwargs):\n        super(FactorizedEmbedding, self).__init__(**kwargs)\n        self.input_dim = input_dim\n        self.output_dim = output_dim\n        if hidden_dim is None:\n            self.hidden_dim = output_dim\n        else:\n            self.hidden_dim = hidden_dim\n\n    def build(self, input_shape):\n        super(FactorizedEmbedding, self).build(input_shape)\n        self._embeddings = self.add_weight(name='embeddings',\n                                           shape=(self.input_dim,\n                                                  self.hidden_dim),\n                                           initializer='uniform')\n        self._project_kernel = self.add_weight(name='project_kernel',\n                                               shape=(self.hidden_dim,\n                                                      self.output_dim),\n                                               initializer='glorot_uniform')\n        self.embeddings = K.dot(self._embeddings, self._project_kernel)\n\n    def call(self, inputs):\n        if K.dtype(inputs) != 'int32':\n            inputs = K.cast(inputs, 'int32')\n        outputs = K.gather(self._embeddings, inputs)\n        outputs = K.dot(outputs, self._project_kernel)\n        return outputs\n\n    def compute_output_shape(self, input_shape):\n        return input_shape + (self.output_dim, )\n\n    def get_config(self):\n        config = {\n            'input_dim': self.input_dim,\n            'output_dim': self.output_dim,\n            'hidden_dim': self.hidden_dim\n        }\n        base_config = super(FactorizedEmbedding, self).get_config()\n        return dict(list(base_config.items()) + list(config.items()))\n\n\nclass PositionEmbedding(Layer):\n    \"\"\"定义位置Embedding，这里的Embedding是可训练的。\n    \"\"\"\n    def __init__(self, input_dim, output_dim, merge_mode='add', **kwargs):\n        super(PositionEmbedding, self).__init__(**kwargs)\n        self.input_dim = input_dim\n        self.output_dim = output_dim\n        self.merge_mode = merge_mode\n\n    def build(self, input_shape):\n        super(PositionEmbedding, self).build(input_shape)\n        self.embeddings = self.add_weight(name='embeddings',\n                                          shape=(self.input_dim,\n                                                 self.output_dim),\n                                          initializer='zeros')\n\n    def call(self, inputs):\n        input_shape = K.shape(inputs)\n        batch_size, seq_len = input_shape[0], input_shape[1]\n        pos_embeddings = self.embeddings[:seq_len]\n        pos_embeddings = K.expand_dims(pos_embeddings, 0)\n        pos_embeddings = K.tile(pos_embeddings, [batch_size, 1, 1])\n        if self.merge_mode == 'add':\n            return inputs + pos_embeddings\n        else:\n            return K.concatenate([inputs, pos_embeddings])\n\n    def compute_output_shape(self, input_shape):\n        if self.merge_mode == 'add':\n            return input_shape\n        else:\n            return input_shape[:2] + (input_shape[2] + self.v_dim, )\n\n    def get_config(self):\n        config = {\n            'input_dim': self.input_dim,\n            'output_dim': self.output_dim,\n            'merge_mode': self.merge_mode\n        }\n        base_config = super(PositionEmbedding, self).get_config()\n        return dict(list(base_config.items()) + list(config.items()))\n\n\nclass FeedForward(Layer):\n    \"\"\"FeedForward层，其实就是两个Dense层的叠加\n    \"\"\"\n    def __init__(self, units, activation='relu', **kwargs):\n        super(FeedForward, self).__init__(**kwargs)\n        self.units = units\n        self.activation = activation\n\n    def build(self, input_shape):\n        super(FeedForward, self).build(input_shape)\n        output_dim = input_shape[-1]\n        self.dense_1 = Dense(self.units, activation=self.activation)\n        self.dense_2 = Dense(output_dim)\n\n    def call(self, inputs):\n        x = self.dense_1(inputs)\n        x = self.dense_2(x)\n        return x\n\n    def get_config(self):\n        config = {'units': self.units, 'activation': self.activation}\n        base_config = super(FeedForward, self).get_config()\n        return dict(list(base_config.items()) + list(config.items()))\n\n\nclass EmbeddingDense(Layer):\n    \"\"\"运算跟Dense一致，但kernel用Embedding层的embeddings矩阵。\n    根据Embedding层的名字来搜索定位Embedding层。\n    \"\"\"\n    def __init__(self, embedding_name, activation='softmax', **kwargs):\n        super(EmbeddingDense, self).__init__(**kwargs)\n        self.embedding_name = embedding_name\n        self.activation = activation\n\n    def call(self, inputs):\n        if not hasattr(self, 'kernel'):\n            embedding_layer = inputs._keras_history[0]\n\n            if embedding_layer.name != self.embedding_name:\n\n                def recursive_search(layer):\n                    \"\"\"递归向上搜索，根据名字找Embedding层\n                    \"\"\"\n                    last_layer = layer._inbound_nodes[0].inbound_layers\n                    if isinstance(last_layer, list):\n                        if len(last_layer) == 0:\n                            return None\n                        else:\n                            last_layer = last_layer[0]\n                    if last_layer.name == self.embedding_name:\n                        return last_layer\n                    else:\n                        return recursive_search(last_layer)\n\n                embedding_layer = recursive_search(embedding_layer)\n                if embedding_layer is None:\n                    raise Exception('Embedding layer not found')\n\n                self.kernel = K.transpose(embedding_layer.embeddings)\n                self.units = K.int_shape(self.kernel)[1]\n                self.bias = self.add_weight(name='bias',\n                                            shape=(self.units, ),\n                                            initializer='zeros')\n\n        outputs = K.dot(inputs, self.kernel)\n        outputs = K.bias_add(outputs, self.bias)\n        outputs = Activation(self.activation).call(outputs)\n        return outputs\n\n    def compute_output_shape(self, input_shape):\n        return input_shape[:-1] + (self.units, )\n\n    def get_config(self):\n        config = {\n            'embedding_name': self.embedding_name,\n            'activation': self.activation\n        }\n        base_config = super(EmbeddingDense, self).get_config()\n        return dict(list(base_config.items()) + list(config.items()))\n\n\ncustom_objects = {\n    'gelu_erf': gelu_erf,\n    'gelu_tanh': gelu_tanh,\n    'MultiHeadAttention': MultiHeadAttention,\n    'LayerNormalization': LayerNormalization,\n    'FactorizedEmbedding': FactorizedEmbedding,\n    'PositionEmbedding': PositionEmbedding,\n    'FeedForward': FeedForward,\n    'EmbeddingDense': EmbeddingDense\n}\n\nget_custom_objects().update(custom_objects)", "meta": {"hexsha": "aaa5b984d1973eeb5140fc1222cc17c7a023101b", "size": 12741, "ext": "py", "lang": "Python", "max_stars_repo_path": "keras_bert_ner/bert4keras/.ipynb_checkpoints/layers-checkpoint.py", "max_stars_repo_name": "qianrenjian/keras-bert-ner", "max_stars_repo_head_hexsha": "5258f68421817008d2c2c9f8420ebf0dce9d5b34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-04-14T02:49:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T03:41:55.000Z", "max_issues_repo_path": "keras_bert_ner/bert4keras/.ipynb_checkpoints/layers-checkpoint.py", "max_issues_repo_name": "qianrenjian/keras-bert-ner", "max_issues_repo_head_hexsha": "5258f68421817008d2c2c9f8420ebf0dce9d5b34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "keras_bert_ner/bert4keras/.ipynb_checkpoints/layers-checkpoint.py", "max_forks_repo_name": "qianrenjian/keras-bert-ner", "max_forks_repo_head_hexsha": "5258f68421817008d2c2c9f8420ebf0dce9d5b34", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-04-14T06:57:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T05:55:04.000Z", "avg_line_length": 35.4902506964, "max_line_length": 76, "alphanum_fraction": 0.5602385998, "include": true, "reason": "import numpy", "num_tokens": 3217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19546295367409278}}
{"text": "'''\nDeconvolution Pipeline\n----------------------\n\nThe deconvolution process can be pipelined from start to finish\nusing the :class:`~.ScanProcessor` class. This includes precursor recalculation and\ncoisolation detection. :class:`~.ScanProcessor` is intended to be used either as a\nreplacement for :class:`~.ScanIterator` when deconvolution is desired, or that it's\n:meth:`ScanProcessor.process` method will be used to handle individual :class:`~.ScanBunch`\nobjects/pairs of precursor :class:`~.Scan` objects and a :class:`list` of product :class:`~.Scan`\nobjects.\n\nThe free-function :func:`~.process` is a convenience wrapper around :class:`~.ScanProcessor`,\nwith fewer configurable parameters.\n\n.. code:: python\n\n    from ms_deisotope import ScanProcessor, glycopeptide, peptide\n    from ms_deisotope.scoring import PenalizedMSDeconVFitter, MSDeconVFitter\n    from ms_deisotope.test.common import datafile\n\n    # Locate example dataset\n    path = datafile(\"20150710_3um_AGP_001_29_30.mzML.gz\")\n\n    proc = processor.ScanProcessor(path, ms1_deconvolution_args={\n        \"averagine\": glycopeptide,\n        \"scorer\": PenalizedMSDeconVFitter(20., 2.),\n        \"truncate_after\": 0.95\n    }, msn_deconvolution_args={\n        \"averagine\": peptide,\n        \"scorer\": MSDeconVFitter(10.),\n        \"truncate_after\": 0.8\n    })\n\n    bunch = next(proc)\n    print(bunch)\n    print(bunch.precursor.deconvoluted_peak_set)\n'''\nimport logging\n\nfrom six import string_types as basestring\n\nimport numpy as np\n\nfrom ms_peak_picker import pick_peaks, PeakSet, PeakIndex\nfrom ms_peak_picker.scan_filter import FTICRBaselineRemoval\n\nfrom .averagine import AveragineCache, peptide\nfrom .scoring import PenalizedMSDeconVFitter, MSDeconVFitter\nfrom .deconvolution import deconvolute_peaks\nfrom .data_source import MSFileLoader, ScanIterator\nfrom .data_source.common import Scan, ScanBunch, ChargeNotProvided\nfrom .utils import Base\nfrom .peak_dependency_network import NoIsotopicClustersError\nfrom .qc.isolation import PrecursorPurityEstimator\nfrom .task import LogUtilsMixin\n\nlogger = logging.getLogger(\"deconvolution_scan_processor\")\nlogger.addHandler(logging.NullHandler())\n\n\ndef _get_nearest_index(query_mz, peak_list):\n    best_index = None\n    best_error = float('inf')\n\n    for i, peak in enumerate(peak_list):\n        error = abs(peak.mz - query_mz)\n        if error < best_error:\n            best_error = error\n            best_index = i\n    return best_index\n\n\nclass PriorityTarget(Base):\n    \"\"\"Represent a targeted envelope deconvolution's parameters and constraints.\n\n    This class is used to tell :func:`ms_deisotope.deconvolution.deconvolute_peaks`\n    that the solution produced by this peak should be preferentially extracted.\n\n    Attributes\n    ----------\n    info : :class:`~.PrecursorInformation`\n        The associated precursor information block which contains\n        the charge state hint.\n    peak : :class:`~.FittedPeak`\n        The peak from which to start the deconvolution\n    trust_charge_hint : bool\n        Whether or not to force the deconvoluter to only consider\n        the charge specified in the hint.\n    mz : float\n        The m/z of :attr:`peak`\n    charge : int\n        The charge state hint from :attr:`info`\n    isolation_window : :class:`~.IsolationWindow`\n        The isolation window for this precursor ion. May be `None`\n    \"\"\"\n\n    def __init__(self, peak, info, trust_charge_hint=True, precursor_scan_id=None,\n                 product_scan_id=None, isolation_window=None):\n        self.peak = peak\n        self.info = info\n        self.trust_charge_hint = trust_charge_hint\n        self.precursor_scan_id = precursor_scan_id\n        self.product_scan_id = product_scan_id\n        self.isolation_window = isolation_window\n\n    def __iter__(self):\n        yield self.peak\n        yield self.info\n\n    @property\n    def mz(self):\n        '''\n        The m/z of the matched peak\n\n        Returns\n        -------\n        float\n        '''\n        return self.peak.mz\n\n    @property\n    def charge(self):\n        '''\n        The charge state of the precursor ion reported by the source.\n\n        Returns\n        -------\n        int\n        '''\n        try:\n            return int(self.info.charge)\n        except TypeError:\n            return 0\n\n    def charge_range_hint(self, charge_range):\n        \"\"\"Create an updated charge range for a Deconvoluter to search.\n\n        At the moment, this only amounts to either returning the charge\n        range unchanged or returning a charge range that only contains\n        the hinted charge state, depending upon whether :attr:`trust_charge_hint`\n        is `False` or not.\n\n        Parameters\n        ----------\n        charge_range : tuple\n            The charge range to update\n\n        Returns\n        -------\n        tuple\n            The updated charge range\n        \"\"\"\n        if self.trust_charge_hint and self.info.charge is not ChargeNotProvided:\n            return (self.charge, self.charge)\n        else:\n            return charge_range\n\n    def __repr__(self):\n        return \"PriorityTarget(mz=%0.4f, intensity=%0.4f, charge_hint=%d)\" % (\n            self.mz, self.peak.intensity, self.charge)\n\n\ndef _loader_creator(specification):\n    if isinstance(specification, basestring):\n        return MSFileLoader(specification)\n    elif isinstance(specification, ScanIterator):\n        return specification\n    else:\n        raise ValueError(\"Cannot determine how to get a ScanIterator from %r\" % (specification,))\n\n\ndef _simplify_peak_set(peaks, bin_width=5.0):\n    bin_edges = np.arange(0, peaks[-1].mz + bin_width, bin_width)\n    bins = []\n    for i, bin_edge in enumerate(bin_edges, 1):\n        if i == len(bin_edges):\n            next_edge = bin_edges[-1] + bin_width\n        else:\n            next_edge = bin_edges[i]\n        subset = peaks.between(bin_edge, next_edge)\n        bins.append(subset)\n\n    thresholds = []\n    reduced_subsets = {}\n    k = 0\n    for b in bins:\n        if len(b) > 0:\n            bin_intensities = np.array([p.intensity for p in b])\n            thresholds.append(np.max(bin_intensities) / 3.)\n            for p in b:\n                if p.intensity > thresholds[-1]:\n                    reduced_subsets[p.peak_count] = p\n            k += (bin_intensities > thresholds[-1]).sum()\n        else:\n            thresholds.append(0.0)\n    subset_peaks = PeakSet(\n        sorted(reduced_subsets.values(), key=lambda x: x.mz)).clone()\n    subset_peaks.reindex()\n    return PeakIndex(np.array([]), np.array([]), subset_peaks)\n\n\nclass ScanProcessor(Base, LogUtilsMixin):\n    \"\"\"Orchestrates the deconvolution of a :class:`~.ScanIterator` scan by scan. This process will\n    apply different rules for MS1 scans and MSn scans. This type itself mimics a :class:`~.ScanIterator`,\n    consuming (raw) mass spectral data and producing deisotoped and charge deconvolved spectra.\n\n    The algorithms used for each task are independent and can be specified in the appropriate\n    attribute dictionary, however there is information sharing between each MS1 scan and its\n    MSn scans as the precursor monoisotopic mass is recalibrated according to the MS1 processing\n    arguments, and the selected charge state is used to limit the charge range used in the matching\n    MSn scan. These are described by :class:`PriorityTarget` objects.\n\n    If an averagine-based deconvoluter is used, the averagine cache will be pre-populated.\n\n    At the moment, MSn assumes only MS2. Until MS3 data become available for testing, this limit\n    will remain.\n\n    Attributes\n    ----------\n    data_source : :class:`str`, :class:`~.ScanIterator` or file-like\n        Any valid object to be passed to the `loader_type` callable to produce\n        a :class:`~.ScanIterator` instance. A path to a mass spectrometry data file,\n        a file-like object, or an instance of :class:`~.ScanIterator`. Used to populate :attr:`reader`\n    loader_type : callable\n        A callable, which when passed :attr:`data_source` returns an instance of :class:`~.ScanIterator`.\n        By default, this is :func:`~.MSFileLoader`. Used to populate :attr:`reader`\n    reader: ScanIterator\n        Any object implementing the :class:`~.ScanIterator` interface, produced by calling\n        :attr:`loader_type` on :attr:`data_source`.\n    ms1_deconvolution_args : :class:`dict`\n        The arguments passed to :func:`~ms_deisotope.deconvolution.deconvolute_peaks` for MS1\n        scans.\n    ms1_peak_picking_args : :class:`dict`\n        The arguments passed to :func:`ms_peak_picker.pick_peaks` for MS1 scans.\n    msn_deconvolution_args : :class:`dict`\n        The arguments passed to :func:`~ms_deisotope.deconvolution.deconvolute_peaks` for MSn\n        scans.\n    msn_peak_picking_args : :class:`dict`\n        The arguments passed to :func:`ms_peak_picker.pick_peaks` for MSn scans.\n    pick_only_tandem_envelopes : :class:`bool`\n        Whether or not to process whole MS1 scans or just the regions around those peaks\n        chosen for MSn\n    default_precursor_ion_selection_window : :class:`float`\n        Size of the selection window to use when :attr:`pick_only_tandem_envelopes` is `True`\n        and the information is not available in the scan.\n    trust_charge_hint : :class:`bool`\n        Whether or not to trust the charge provided by the data source when determining\n        the charge state of precursor isotopic patterns. Defaults to `True`\n    respect_isolation_window: :class:`bool`\n        Whether to use the bounds of the isolation window to reject a monoisotopic peak\n        solution\n    terminate_on_error: :class:`bool`\n        Whether or not  to stop processing on an error. Defaults to `True`\n    ms1_averaging: :class:`int`\n        The number of adjacent MS1 scans to average prior to picking peaks.\n    \"\"\"\n\n    def __init__(self, data_source, ms1_peak_picking_args=None,\n                 msn_peak_picking_args=None,\n                 ms1_deconvolution_args=None,\n                 msn_deconvolution_args=None,\n                 pick_only_tandem_envelopes=False,\n                 default_precursor_ion_selection_window=1.5,\n                 trust_charge_hint=True,\n                 loader_type=None,\n                 envelope_selector=None,\n                 terminate_on_error=True,\n                 ms1_averaging=0,\n                 respect_isolation_window=False,\n                 too_many_peaks_threshold=7000):\n        if loader_type is None:\n            loader_type = _loader_creator\n\n        self.data_source = data_source\n        self.ms1_peak_picking_args = ms1_peak_picking_args or {}\n        self.msn_peak_picking_args = msn_peak_picking_args or ms1_peak_picking_args or {}\n        self.ms1_deconvolution_args = ms1_deconvolution_args or {}\n        self.ms1_deconvolution_args.setdefault(\"charge_range\", (1, 8))\n        self.msn_deconvolution_args = msn_deconvolution_args or {}\n        self.msn_deconvolution_args.setdefault(\"charge_range\", (1, 8))\n        self.pick_only_tandem_envelopes = pick_only_tandem_envelopes\n\n        self.too_many_peaks_threshold = too_many_peaks_threshold\n\n        self.default_precursor_ion_selection_window = default_precursor_ion_selection_window\n        self.respect_isolation_window = respect_isolation_window\n\n        self.trust_charge_hint = trust_charge_hint\n        self.ms1_averaging = int(ms1_averaging) if ms1_averaging else 0\n\n        self.loader_type = loader_type\n\n        self._signal_source = self.loader_type(data_source)\n        self.envelope_selector = envelope_selector\n        self.terminate_on_error = terminate_on_error\n        self._prepopulate_averagine_cache()\n\n    def _prepopulate_averagine_cache(self):\n        if 'averagine' in self.ms1_deconvolution_args:\n            averagine = self.ms1_deconvolution_args['averagine']\n            if isinstance(averagine, (list, tuple)):\n                averagine = [AveragineCache(a).populate() for a in averagine]\n            else:\n                averagine = AveragineCache(averagine).populate()\n            self.ms1_deconvolution_args['averagine'] = averagine\n        if 'averagine' in self.msn_deconvolution_args:\n            averagine = self.msn_deconvolution_args['averagine']\n            if isinstance(averagine, (list, tuple)):\n                averagine = [AveragineCache(a).populate() for a in averagine]\n            else:\n                averagine = AveragineCache(averagine).populate()\n            self.msn_deconvolution_args['averagine'] = averagine\n\n    def _reject_candidate_precursor_peak(self, peak, product_scan):\n        isolation = product_scan.isolation_window\n        if isolation is None or isolation.is_empty():\n            pinfo = product_scan.precursor_information\n            err = peak.mz - pinfo.mz\n            return abs(err) > self.default_precursor_ion_selection_window\n        else:\n            return peak.mz not in isolation and self.respect_isolation_window\n\n    @property\n    def reader(self):\n        '''The :class:`~.ScanIterator` which generates the raw scans that will\n        be processed.\n\n        Returns\n        -------\n        :class:`~.ScanIterator`\n        '''\n        return self._signal_source\n\n    def _get_envelopes(self, precursor_scan):\n        \"\"\"Get the m/z intervals to pick peaks from for the\n        given MS1 scan\n\n        Parameters\n        ----------\n        precursor_scan: Scan\n\n        Returns\n        -------\n        list or None\n        \"\"\"\n        if not self.pick_only_tandem_envelopes and self.envelope_selector is None:\n            return None\n        elif self.envelope_selector is None:\n            chosen_envelopes = [s.precursor_information for s in precursor_scan.product_scans]\n            chosen_envelopes = sorted([(p.mz - 5, p.mz + 10) for p in chosen_envelopes])\n        else:\n            chosen_envelopes = self.envelope_selector(precursor_scan)\n        return chosen_envelopes\n\n    def _pick_precursor_scan_peaks(self, precursor_scan, chosen_envelopes=None):\n        \"\"\"Pick peaks from the given precursor scan\n\n        Parameters\n        ----------\n        precursor_scan: Scan\n            Scan to pick peaks from\n        chosen_envelopes: list, optional\n            list of m/z intervals to pick peaks for\n\n        Returns\n        -------\n        PeakSet\n        \"\"\"\n        if precursor_scan.is_profile:\n            peak_mode = 'profile'\n        else:\n            peak_mode = 'centroid'\n        prec_mz, prec_intensity = precursor_scan.arrays\n        if not self.pick_only_tandem_envelopes and self.envelope_selector is None:\n            prec_peaks = pick_peaks(prec_mz, prec_intensity, peak_mode=peak_mode, **self.ms1_peak_picking_args)\n        else:\n            if chosen_envelopes is None:\n                chosen_envelopes = self._get_envelopes(precursor_scan)\n            prec_peaks = pick_peaks(prec_mz, prec_intensity, peak_mode=peak_mode,\n                                    target_envelopes=chosen_envelopes,\n                                    **self.ms1_peak_picking_args)\n        return prec_peaks\n\n    def _average_ms1(self, precursor_scan):\n        \"\"\"Average signal from :attr:`self.ms1_averaging` scans from\n        before and after ``precursor_scan`` and pick peaks from the\n        averaged arrays.\n\n        Parameters\n        ----------\n        precursor_scan: Scan\n            The scan to use as a point of reference\n\n        Returns\n        -------\n        PeakSet\n        \"\"\"\n        # averaged scans are always profile mode\n        new_scan = precursor_scan.average(self.ms1_averaging)\n        prec_peaks = pick_peaks(*new_scan.arrays,\n                                target_envelopes=self._get_envelopes(precursor_scan),\n                                **self.ms1_peak_picking_args)\n        return prec_peaks\n\n    def pick_precursor_scan_peaks(self, precursor_scan):\n        \"\"\"Picks peaks for the given ``precursor_scan`` using the\n        appropriate strategy.\n\n        If :attr:`ms1_averaging` > 0, then the signal averaging strategy\n        is used, otherwise peaks are picked directly.\n\n        Parameters\n        ----------\n        precursor_scan: Scan\n\n        Returns\n        -------\n        PeakSet\n        \"\"\"\n        self.log(\"Picking Precursor Scan Peaks: %r\" % (precursor_scan, ))\n        if self.ms1_averaging > 0:\n            prec_peaks = self._average_ms1(precursor_scan)\n        else:\n            prec_peaks = self._pick_precursor_scan_peaks(precursor_scan)\n        n_peaks = len(prec_peaks)\n        if n_peaks > self.too_many_peaks_threshold:\n            self.log(\"%d peaks found for %r, applying local intensity threshold.\" % (n_peaks, precursor_scan))\n            prec_peaks = _simplify_peak_set(prec_peaks)\n        precursor_scan.peak_set = prec_peaks\n        return prec_peaks\n\n    def pick_product_scan_peaks(self, product_scan):\n        \"\"\"Pick the peaks of product scan\n\n        Parameters\n        ----------\n        product_scan: :class:`~.Scan`\n            The scan to pick peaks from.\n\n        Returns\n        -------\n        PeakSet\n        \"\"\"\n        if product_scan.is_profile:\n            peak_mode = 'profile'\n        else:\n            peak_mode = 'centroid'\n        product_mz, product_intensity = product_scan.arrays\n        peaks = pick_peaks(product_mz, product_intensity, peak_mode=peak_mode, **self.msn_peak_picking_args)\n\n        if peaks is None:\n            raise EmptyScanError(\n                \"Could not pick peaks for empty product scan\", self)\n\n        product_scan.peak_set = peaks\n        return peaks\n\n    def get_precursor_peak_for_product_scans(self, precursor_scan):  # pragma: no cover\n        \"\"\"A utility method to obtain :class:`PriorityTarget` objects for\n        each product scan of `precursor_scan`.\n\n        Parameters\n        ----------\n        precursor_scan: :class:`~.Scan`\n            The scan to extract.\n\n        Returns\n        -------\n        :class:`list` of :class:`PriorityTarget`\n        \"\"\"\n        priorities = []\n        peaks = precursor_scan.peak_set\n        for scan in precursor_scan.product_scans:\n            precursor_ion = scan.precursor_information\n            if peaks is None:\n                peaks = self.pick_precursor_scan_peaks(precursor_scan)\n            peak, _ = peaks.get_nearest_peak(precursor_ion.mz)\n            precursor_ion.peak = peak\n            target = PriorityTarget(\n                peak,\n                precursor_ion,\n                self.trust_charge_hint,\n                isolation_window=scan.isolation_window)\n            if self._reject_candidate_precursor_peak(peak, scan):\n                self.log(\n                    \"Unable to locate a peak for precursor ion %r for tandem scan %s of precursor scan %s\" % (\n                        precursor_ion, scan.title,\n                        precursor_scan.title))\n            else:\n                priorities.append(target)\n        return priorities\n\n    def process_scan_group(self, precursor_scan, product_scans):\n        \"\"\"Performs the initial extraction of information relating\n        `precursor_scan` to `product_scans` and picks peaks for ``precursor_scan``.\n        Called by :meth:`process`. May be used separately if doing the process step\n        by step.\n\n        Parameters\n        ----------\n        precursor_scan : :class:`~.Scan`\n            An MS1 Scan\n        product_scans : :class:`list` of :class:`~.Scan`\n            A :class:`list` of MSn Scans related to `precursor_scan`\n\n        Returns\n        -------\n        precursor_scan: :class:`~.Scan`\n            As Parameter\n        prioritiies: :class:`list` of :class:`~PriorityTarget`\n            :class:`list` of the peak target windows in `precursor_scan` which\n            are related to `product_scans`\n        product_scans: :class:`list` of :class:`~.Scan`\n            As Parameter\n        \"\"\"\n        prec_peaks = self.pick_precursor_scan_peaks(precursor_scan)\n        priorities = []\n\n        if prec_peaks is None:\n            raise EmptyScanError(\n                \"Could not pick peaks for empty precursor scan\", self)\n\n        for scan in product_scans:\n            precursor_ion = scan.precursor_information\n            peak = prec_peaks.has_peak(precursor_ion.mz)\n            if peak is not None:\n                err = abs(peak.mz - precursor_ion.mz)\n            else:\n                peak, err = prec_peaks.get_nearest_peak(precursor_ion.mz)\n            self.debug(\"For Precursor at %0.4f, found Peak at %0.4f with error %0.4f\" % (\n                precursor_ion.mz, peak.mz, err))\n            precursor_ion.peak = peak\n            target = PriorityTarget(\n                peak, precursor_ion, self.trust_charge_hint,\n                scan.precursor_information.precursor_scan_id,\n                scan.precursor_information.product_scan_id,\n                isolation_window=scan.isolation_window)\n            if self._reject_candidate_precursor_peak(peak, scan):\n                self.log(\n                    \"Unable to locate a peak for precursor ion %r for tandem scan %s of precursor scan %s\" % (\n                        precursor_ion, scan.id,\n                        precursor_scan.id))\n            else:\n                priorities.append(target)\n\n        return precursor_scan, priorities, product_scans\n\n    def _default_all_precursor_information(self, scans):\n        for scan in scans:\n            if scan.ms_level > 1:\n                scan.precursor_information.default(orphan=True)\n\n    def deconvolute_precursor_scan(self, precursor_scan, priorities=None):\n        \"\"\"Deconvolute the given precursor scan, giving priority to its product ions,\n        correcting the :attr:`precursor_information` attributes of priority targets,\n        as well as calculating the degree of precursor purity and coisolating ions.\n\n        Parameters\n        ----------\n        precursor_scan : :class:`~.Scan`\n            The precursor scan to deconvolute\n        priorities : :class:`list` of :class:`PriorityTarget`, optional\n            The priority targets for the product ions derived from `precursor_scan`\n\n        Returns\n        -------\n        :class:`~DeconvolutedPeakSet`\n            The deconvoluted peaks of ``precursor_scan``\n        :class:`list` of :class:`PriorityTarget`\n            The precursor ions selected, with updated mass and charge information\n\n        Raises\n        ------\n        Exception\n            Any errors which are thrown during the deconvolution process may be thrown\n            if :attr:`terminate_on_error` is `True`.\n        \"\"\"\n        if priorities is None:\n            priorities = []\n\n        self.log(\"Deconvoluting Precursor Scan %r\" % precursor_scan)\n        self.log(\"Priorities: %r\" % priorities)\n\n        ms1_deconvolution_args = self.ms1_deconvolution_args.copy()\n\n        if precursor_scan.polarity in (1, -1):\n            polarity = precursor_scan.polarity\n            ms1_deconvolution_args['charge_range'] = tuple(\n                polarity * abs(c) for c in ms1_deconvolution_args['charge_range'])\n        try:\n            decon_result = deconvolute_peaks(\n                precursor_scan.peak_set, priority_list=priorities,\n                **ms1_deconvolution_args)\n        except NoIsotopicClustersError as e:\n            e.scan_id = precursor_scan.id\n            if self.terminate_on_error:\n                raise e\n            else:\n                self.log(\"No isotopic clusters found in %r\" % precursor_scan.id)\n\n        dec_peaks, priority_results = decon_result\n        if decon_result.errors:\n            self.error(\"Errors occurred during deconvolution of %s, %r\" % (\n                precursor_scan.id, decon_result.errors))\n        precursor_scan.deconvoluted_peak_set = dec_peaks\n        for pr in priority_results:\n            if pr is None:\n                continue\n            else:\n                pr.chosen_for_msms = True\n\n        # `priorities` and `priority_results` are parallel lists. The\n        # ith position in `priorities` corresponds to the ith deconvoluted\n        # priority result in `priority_results`. The entry in `priority_results`\n        # may be `None` if the deconvolution failed, but elements of `priorities`\n        # should always be FittedPeak or Peak-like instances\n\n        coisolation_detection = PrecursorPurityEstimator(default_width=self.default_precursor_ion_selection_window)\n        self.debug(\"Priority Targets for %s: %r\" % (\n            precursor_scan.id, [\n                (p.mz, p.charge) if p is not None else None for p in priorities\n            ]))\n        for product_scan in precursor_scan.product_scans:\n            precursor_information = product_scan.precursor_information\n\n            # unknown precursor purity\n            product_scan.annotations['precursor purity'] = 0.0\n            i = _get_nearest_index(precursor_information.mz, priorities)\n\n            # If no peak is found in the priority list, it means the priority list is empty.\n            # This should never happen in the current implementation. If it did, then we forgot\n            # to pass the priority list to this function.\n            if i is None:\n                self.log(\n                    \"Could not find deconvolution for %r (No nearby peak in the priority list)\" %\n                    precursor_information)\n                precursor_information.default(orphan=True)\n                continue\n\n            peak = priority_results[i]\n            # If the deconvolution result is None, then we have no answer\n            if peak is None:\n                self.log(\n                    \"Could not find deconvolution for %r (No solution was found for this region)\" %\n                    precursor_information)\n                precursor_information.default(orphan=True)\n\n                continue\n            elif peak.charge == 1 or (peak.charge != precursor_information.charge and self.trust_charge_hint):\n                if precursor_information.charge != ChargeNotProvided:\n                    self.log(\n                        \"Could not find deconvolution for %r (Unacceptable solution was proposed: %r)\" %\n                        (precursor_information, peak))\n                    precursor_information.default()\n                    continue\n\n            precursor_purity = -1.0\n            if peak is not None:\n                precursor_purity, coisolation = coisolation_detection(\n                    precursor_scan,\n                    peak,\n                    product_scan.isolation_window)\n                precursor_information.coisolation = coisolation\n                self.debug(\n                    \"Precursor m/z %f\\nExperimental = %r\\nTheoretical = %r\" % (\n                        peak.mz,\n                        ', '.join([\"(%0.4f, %0.1f)\" % (p.mz, p.intensity) for p in peak.envelope]),\n                        ', '.join([\"(%0.4f, %0.1f)\" % (p.mz, p.intensity) for p in peak.fit.theoretical]))\n                )\n\n            product_scan.annotations['precursor purity'] = precursor_purity\n            precursor_information.extract(peak)\n        return dec_peaks, priority_results\n\n    def deconvolute_product_scan(self, product_scan):\n        \"\"\"Deconvolute the peaks of `product_scan`.\n\n        This method will override the upper limit \"charge_range\" of\n        :attr:`msn_deconvolution_args` to the charge information of\n        the precursor ion.\n\n        This method sets the :attr:`~.Scan.deconvoluted_peak_set` of\n        `product_scan`.\n\n        Parameters\n        ----------\n        product_scan : :class:`~.Scan`\n            The scan to deconvolute.\n\n        Returns\n        -------\n        :class:`~.DeconvolutedPeakSet`\n\n        Raises\n        ------\n        Exception\n            Any errors which are thrown during the deconvolution process may be thrown\n            if :attr:`terminate_on_error` is `True`.\n        \"\"\"\n        self.log(\"Deconvoluting Product Scan %r\" % (product_scan, ))\n        precursor_ion = product_scan.precursor_information\n        top_charge_state = precursor_ion.extracted_charge\n        if not top_charge_state:\n            top_charge_state = precursor_ion.charge\n        deconargs = dict(self.msn_deconvolution_args)\n        charge_range = list(deconargs.get(\"charge_range\", [1, top_charge_state]))\n        if top_charge_state is not None and top_charge_state is not ChargeNotProvided and\\\n           top_charge_state != 0 and abs(top_charge_state) < abs(charge_range[1]):\n            charge_range[1] = top_charge_state\n\n        deconargs[\"charge_range\"] = charge_range\n\n        if product_scan.polarity in (-1, 1):\n            polarity = product_scan.polarity\n            deconargs[\"charge_range\"] = [\n                polarity * abs(c) for c in deconargs[\"charge_range\"]]\n\n        try:\n            dec_peaks, _ = deconvolute_peaks(product_scan.peak_set, **deconargs)\n        except NoIsotopicClustersError as e:\n            self.log(\"No Isotopic Clusters found in %r\" % product_scan.id)\n            e.scan_id = product_scan.id\n            if self.terminate_on_error:\n                raise e\n\n        product_scan.deconvoluted_peak_set = dec_peaks\n        return dec_peaks\n\n    def _get_next_scans(self):\n        bunch = next(self.reader)\n        try:\n            precursor, products = bunch\n        except ValueError:\n            if isinstance(bunch, Scan):\n                if bunch.ms_level == 1:\n                    precursor = bunch\n                    products = []\n                else:\n                    precursor = None\n                    products = [bunch]\n\n        if self.pick_only_tandem_envelopes:\n            while len(products) == 0:\n                precursor, products = next(self.reader)\n\n        return precursor, products\n\n    def process(self, precursor, products):\n        \"\"\"Fully preprocesses the `precursor` and `products` scans, performing\n        any necessary information sharing.\n\n        This method may be used to process scans from other sources not from the\n        wrapped :class:`~.ScanIterator`.\n\n        Parameters\n        ----------\n        precursor : :class:`~.Scan`\n            An MS1 Scan\n        products : :class:`list` of :class:`~.Scan`\n            A list of MSn Scans related to `precursor`\n\n        Returns\n        -------\n        :class:`~.ScanBunch`\n            The fully processed version of `precursor` and `products`\n        \"\"\"\n        precursor_scan, priorities, product_scans = self.process_scan_group(precursor, products)\n        if precursor_scan is not None:\n            self.deconvolute_precursor_scan(precursor_scan, priorities)\n        else:\n            self._default_all_precursor_information(product_scans)\n\n        for product_scan in product_scans:\n            self.pick_product_scan_peaks(product_scan)\n            self.deconvolute_product_scan(product_scan)\n\n        return ScanBunch(precursor_scan, product_scans)\n\n    def next(self):\n        \"\"\"Fetches the next bunch of scans from :attr:`reader` and\n        invokes :meth:`process` on them, picking peaks and deconvoluting them.\n\n        Returns\n        -------\n        ScanBunch\n        \"\"\"\n        precursor, products = self._get_next_scans()\n        bunch = self.process(precursor, products)\n        return bunch\n\n    def __next__(self):\n        \"\"\"Fetches the next bunch of scans from :attr:`reader` and\n        invokes :meth:`process` on them, picking peaks and deconvoluting them.\n\n        Returns\n        -------\n        ScanBunch\n        \"\"\"\n        return self.next()\n\n    def __iter__(self):\n        return self\n\n    def pack_next(self):\n        \"\"\"As :meth:`next`, except instead of producing :class:`ScanBunch` of\n        :class:`Scan` instances, instead it uses :class:`ProcessedScan` to strip away\n        much of the heavy information like the raw data arrays.\n\n        Returns\n        -------\n        ScanBunch\n        \"\"\"\n        precursor, products = self._get_next_scans()\n        precursor_scan, product_scans = self.process(precursor, products)\n        return ScanBunch(precursor_scan.pack() if precursor_scan else None, [p.pack() for p in product_scans])\n\n    def start_from_scan(self, *args, **kwargs):\n        \"\"\"A wrapper around :meth:`~.RandomAccessScanSource.start_from_scan` provided by\n        :attr:`reader`, if available.\n\n        Returns\n        -------\n        self\n\n        See Also\n        --------\n        :meth:`~.RandomAccessScanSource.start_from_scan`\n        \"\"\"\n        self.reader.start_from_scan(*args, **kwargs)\n        return self\n\n\nScanProcessor.log_with_logger(logger)\n\n\ndef process(data_source, ms1_averagine=peptide, msn_averagine=peptide,\n            ms1_score_threshold=20, msn_score_threshold=5, denoise=False,\n            ms1_max_missed_peaks=1, pick_only_tandem_envelopes=False,\n            trust_charge_hint=True, envelope_selector=None, terminate_on_error=True,\n            ms1_averaging=0, respect_isolation_window=False, use_quick_charge=True):\n    \"\"\"Construct a deconvolution pipeline for common applications.\n\n    Parameters\n    ----------\n    data_source : :class:`str` or :class:`~.ScanIterator` or file-like object\n        The scan data source to read raw spectra from\n    ms1_averagine : :class:`~.Averagine` or :class:`~.AveragineCache`, optional\n        The :class:`~.Averagine` model to use for MS1 scans. Defaults to\n        :data:`ms_deisotope.averagine.peptide`.\n    msn_averagine : :class:`~.Averagine` or :class:`~.AveragineCache`, optional\n        The :class:`~.Averagine` model to use for MSn scans. Defaults to\n        :data:`ms_deisotope.averagine.peptide`.\n    ms1_score_threshold : float, optional\n        The score threshold to use to reject isotopic pattern fits for MS1 scans.\n        The default is 20.0.\n    msn_score_threshold : float, optional\n        The score threshold to use to reject isotopic pattern fits for MS1 scans.\n        The default is 5.0.\n    denoise : :class:`bool` or :class:`float`, optional\n        Whether to denoise MS1 scans. If the value is not false-y, it may either be\n        a float to set the scale of the denoising process, or 5.0 if the value is\n        :const:`True`.\n    ms1_max_missed_peaks : :class:`int`, optional\n        The maximum number of missed peaks to permit for MS1 scans. The default is 1.\n    pick_only_tandem_envelopes : :class:`bool`\n        Whether or not to process whole MS1 scans or just the regions around those peaks\n        chosen for MSn\n    default_precursor_ion_selection_window : :class:`float`\n        Size of the selection window to use when :attr:`pick_only_tandem_envelopes` is `True`\n        and the information is not available in the scan.\n    trust_charge_hint : :class:`bool`\n        Whether or not to trust the charge provided by the data source when determining\n        the charge state of precursor isotopic patterns. Defaults to `True`\n    terminate_on_error: :class:`bool`\n        Whether or not  to stop processing on an error. Defaults to `True`\n    ms1_averaging: :class:`int`\n        The number of adjacent MS1 scans to average prior to picking peaks.\n    respect_isolation_window: :class:`bool`\n        Whether to use the bounds of the isolation window to reject a monoisotopic peak\n        solution\n    use_quick_charge : :class:`bool`, optional\n        Whether or not to used the QuickCharge algorithm for expediting charge calculation.\n\n    Returns\n    -------\n    :class:`ScanProcessor`\n    \"\"\"\n    if denoise:\n        ms1_peak_picking_args = {\n            \"filters\": [\n                FTICRBaselineRemoval(\n                    scale=denoise if denoise is not True else 5., window_length=2)\n            ]\n        }\n    else:\n        ms1_peak_picking_args = None\n\n    ms1_deconvolution_args = {\n        \"averagine\": ms1_averagine,\n        \"scorer\": PenalizedMSDeconVFitter(ms1_score_threshold, 2.0),\n        \"use_quick_charge\": use_quick_charge,\n        \"max_missed_peaks\": ms1_max_missed_peaks,\n        \"truncate_after\": 0.95,\n    }\n    msn_deconvolution_args = {\n        \"averagine\": msn_averagine,\n        \"scorer\": MSDeconVFitter(msn_score_threshold),\n        \"use_quick_charge\": use_quick_charge,\n        \"truncate_after\": 0.8,\n    }\n    processor = ScanProcessor(\n        data_source, ms1_peak_picking_args,\n        None, ms1_deconvolution_args,\n        msn_deconvolution_args, pick_only_tandem_envelopes,\n        trust_charge_hint=trust_charge_hint,\n        envelope_selector=envelope_selector,\n        terminate_on_error=terminate_on_error,\n        ms1_averaging=ms1_averaging,\n        respect_isolation_window=respect_isolation_window)\n    return processor\n\n\nclass EmptyScanError(ValueError):\n    \"\"\"A sub-type of :class:`ValueError` which is used to indicate\n    that a spectrum is empty and could not be manipulated.\n    \"\"\"\n    def __init__(self, msg, scan_id=None):\n        ValueError.__init__(self, msg)\n        self.scan_id = scan_id\n", "meta": {"hexsha": "0cb9bc6267e22ddb3a0ee5cc65cfccdd49852fe0", "size": 36627, "ext": "py", "lang": "Python", "max_stars_repo_path": "ms_deisotope/processor.py", "max_stars_repo_name": "WEHI-Proteomics/ms_deisotope", "max_stars_repo_head_hexsha": "24a289a7903e033b8b6cf6e3a1e6931ab75668b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-26T04:12:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T04:12:51.000Z", "max_issues_repo_path": "ms_deisotope/processor.py", "max_issues_repo_name": "WEHI-Proteomics/ms_deisotope", "max_issues_repo_head_hexsha": "24a289a7903e033b8b6cf6e3a1e6931ab75668b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ms_deisotope/processor.py", "max_forks_repo_name": "WEHI-Proteomics/ms_deisotope", "max_forks_repo_head_hexsha": "24a289a7903e033b8b6cf6e3a1e6931ab75668b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3415682062, "max_line_length": 115, "alphanum_fraction": 0.6362519453, "include": true, "reason": "import numpy", "num_tokens": 8258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791786991753929, "lm_q2_score": 0.2877678218692626, "lm_q1q2_score": 0.19544577492170193}}
{"text": "import numpy as np\nimport typing\nfrom collections import namedtuple\nfrom .materials import _IMMaterial\nfrom ._elastic_sub_surface_stresses import normal_conv_kernels, tangential_conv_kernels\n\n__all__ = ['Elastic', 'elastic_influence_matrix_spatial', 'elastic_influence_matrix_frequency', 'get_angular_velocity']\n\nElasticProps = namedtuple('ElasticProperties', 'K E v Lam M G', defaults=(None,) * 6)\n\n\n# noinspection PyPep8Naming\nclass Elastic(_IMMaterial):\n    \"\"\" A Class for defining elastic materials\n\n    Parameters\n    ----------\n    name: str\n        The name of the material\n    properties: dict\n        dict of properties, dicts must have exactly 2 items.\n        Allowed keys are : 'E', 'v', 'G', 'K', 'M', 'Lam'\n        See notes for definitions\n    max_load: float, optional (float('inf'))\n        The maximum load on the surface, loads above this will be cropped during analysis, if this is specified a\n        plastic deformation sub model should be added to the end of each model step to make the deformation permanent\n    use_frequency_domain: bool, optional (True)\n        If True the frequency domain definition of the influence matrix is used, otherwise the spatial domain definition\n        is used.\n    periodic_im_repeats: tuple, optional (1,1)\n        The number of times the influence matrix should be wrapped in each dimension, used with spatially defined\n        influence matrices and to set the zero frequency value for frequency domain influence matrices. Should not\n        be used with non periodic contacts, for periodic contacts the total size should match the physical size. This\n        is necessary to ensure truly periodic behaviour, no physical limit exists:\n        (an infinitely long contact with any load per unit length will cause infinite displacement).\n    zero_frequency_value: float, optional (None)\n        If the frequency domain influence matrix is used the zero frequency value can be set, this defaults to the sum\n        of the spatial influence matrix of the correct size. Should be set to 0 for fully periodic contacts.\n\n    Methods\n    -------\n    speed_of_sound\n\n    See Also\n    --------\n\n    Notes\n    -----\n\n    Keys refer to:\n        - E   - Young's modulus\n        - v   - Poission's ratio\n        - K   - Bulk Modulus\n        - Lam - Lame's first parameter\n        - G   - Shear modulus\n        - M   - P wave modulus\n\n    Examples\n    --------\n    >>> # Make a material model for elastic steel\n    >>> steel = Elastic('steel', {'E': 200e9, 'v': 0.3})\n    >>> # Find it's p-wave modulus:\n    >>> pwm = steel.M\n    >>> # Find the speeds of sound:\n    >>> sos = steel.speed_of_sound(7890)\n    \"\"\"\n\n    material_type = 'Elastic'\n\n    _properties = {'E': None,\n                   'v': None,\n                   'G': None,\n                   'K': None,\n                   'Lam': None,\n                   'M': None, }\n\n    _last_set = []\n    density = None\n\n    def __init__(self, name: str, properties: dict, max_load: float = np.inf,\n                 use_frequency_domain: bool = True, periodic_im_repeats: tuple = (1, 1),\n                 zero_frequency_value: float = None):\n        super().__init__(name, use_frequency_domain, max_load,\n                         periodic_im_repeats, zero_frequency_value)\n\n        if len(properties) > 2:\n            raise ValueError(\"Too many properties supplied, must be 1 or 2\")\n\n        for item in properties.items():\n            self._set_props(*item)\n\n    def _influence_matrix_spatial(self, components: typing.Union[typing.Sequence[str], str],\n                                  grid_spacing: {typing.Sequence[float], float}, span: typing.Sequence[int]):\n        \"\"\"\n        Influence matrix for an elastic material\n\n        Parameters\n        ----------\n        grid_spacing: tuple\n            The spacing between grid points in the x and y directions\n        span: tuple\n            The span required in the x and y directions in number of grid points\n        components: str or Sequence {'xx','xy','xz','yx','yy','yz','zx','zy','zz','all'}\n            The required components eg the 'xy' component represents the x\n            deflection caused by loads in the y direction\n\n        Returns\n        -------\n        dict\n            dict of the requested influence matrix or matrices\n\n        See Also\n        --------\n        elastic_loading\n        elastic_deflection\n\n        Notes\n        -----\n\n        K^{ij i'j'}_zz=(1-v)/(2*pi*G)*Czz\n\n        Czz=(hx*(k*log((m+sqrt(k**2+m**2))/(n+sqrt(k**2+n**2)))+\n                 l*log((n+sqrt(l**2+n**2))/(m+sqrt(l**2+m**2))))+\n             hy*(m*log((k+sqrt(k**2+m**2))/(l+sqrt(l**2+m**2)))+\n                 n*log((l+sqrt(l**2+n**2))/(k+sqrt(k**2+n**2)))))\n\n        In which:\n\n        k=i'-i+0.5\n        l=i'-i-0.5\n        m=j'-j+0.5\n        n=j'-j-0.5\n        hx=grid_spacing[0]\n        hy=grid_spacing[1]\n\n        If both shear_modulus_2 and v_2 are supplied and are not None the combined IM is returned for the surface\n        pair\n\n        Examples\n        --------\n\n\n        References\n        ----------\n        Complete boundary element method formulation for normal and tangential\n        contact problems\n\n        \"\"\"\n        shear_modulus_2 = None\n        v_2 = None\n\n        shear_modulus = self.G\n        v = self.v\n\n        components = {comp: elastic_influence_matrix_spatial(comp, span, grid_spacing, shear_modulus, v,\n                                                             shear_mod_2=shear_modulus_2, v_2=v_2) for comp in\n                      components}\n\n        return components\n\n    def _influence_matrix_frequency(self, components: typing.Sequence[str], grid_spacing: typing.Sequence[float],\n                                    span: typing.Sequence[int]):\n        x_omega, y_omega = get_angular_velocity(span, grid_spacing)\n        norm_2 = x_omega ** 2 + y_omega ** 2\n        norm = np.sqrt(norm_2)\n        rtn_dict = {key: elastic_influence_matrix_frequency(y_omega, x_omega, norm, norm_2, key, self.E, self.v)\n                    for key in components}\n        return rtn_dict\n\n    def _del_props(self, prop):\n        # delete any of the material properties\n        keys = list(self._properties.keys())\n        if self._last_set == prop:\n            self._properties = {key: None for key in keys}\n            self._last_set = None\n        else:\n            self._properties = {key: None for key in keys\n                                if not key == self._last_set}\n\n    def _set_props(self, prop, value):\n        allowed_props = ['E', 'v', 'G', 'K', 'Lam', 'M']\n        if prop not in allowed_props:\n            msg = (f'property {prop} not recognised allowed propertied are: ' +\n                   ' '.join(allowed_props))\n            raise ValueError(msg)\n\n        self._properties[prop] = np.float64(value)\n\n        if len(self._last_set) == 0:\n            self._last_set.append(prop)  # if none ever set just set it\n        elif self._last_set[-1] != prop:\n            self._last_set.append(prop)  # if the last set is different replace it\n\n        if len(self._last_set) > 1:  # if 2 props have been set update all\n            set_props = {prop: np.float64(value),\n                         self._last_set[-2]: self._properties[self._last_set[-2]]}\n            self._properties = _get_properties(set_props)\n        return\n\n    @property\n    def E(self):\n        \"\"\"The Young's modulus of the material\"\"\"\n        return self._properties['E']\n\n    @E.deleter\n    def E(self):\n        self._del_props('E')\n\n    @E.setter\n    def E(self, value):\n        self._set_props('E', value)\n\n    @property\n    def v(self):\n        \"\"\"The Poissions's ratio of the material\"\"\"\n        return self._properties['v']\n\n    @v.deleter\n    def v(self):\n        self._del_props('v')\n\n    @v.setter\n    def v(self, value):\n        self._set_props('v', value)\n\n    @property\n    def G(self):\n        \"\"\"The shear modulus of the material\"\"\"\n        return self._properties['G']\n\n    @G.deleter\n    def G(self):\n        self._del_props('G')\n\n    @G.setter\n    def G(self, value):\n        self._set_props('G', value)\n\n    @property\n    def K(self):\n        \"\"\"The bulk modulus of the material\"\"\"\n        return self._properties['K']\n\n    @K.deleter\n    def K(self):\n        self._del_props('K')\n\n    @K.setter\n    def K(self, value):\n        self._set_props('K', value)\n\n    @property\n    def Lam(self):\n        \"\"\"Lame's first parameter for the material\"\"\"\n        return self._properties['Lam']\n\n    @Lam.deleter\n    def Lam(self):\n        self._del_props('Lam')\n\n    @Lam.setter\n    def Lam(self, value):\n        self._set_props('Lam', value)\n\n    @property\n    def M(self):\n        \"\"\"The p wave modulus of the material\"\"\"\n        return self._properties['M']\n\n    @M.deleter\n    def M(self):\n        self._del_props('M')\n\n    @M.setter\n    def M(self, value):\n        self._set_props('M', value)\n\n    def speed_of_sound(self, density: float = None):\n        \"\"\"find the speed of sound in the material\n\n        Parameters\n        ----------\n        density : float optional (None)\n            The density of the material\n\n        Returns\n        -------\n\n        speeds : dict\n            With keys 's' and 'p' giving the s and p wave speeds\n\n        Notes\n        -----\n\n        Finds speeds according to the following equations:\n\n        Vs=sqrt(G/rho)\n        Vp=sqrt(M/rho)\n\n        Where rho is the density, G is the shear modulus and M is the p wave\n        modulus\n\n        Examples\n        --------\n        >>> # Find the speed of sound in steel\n        >>> my_material = Elastic({'E': 200e9, 'v': 0.3})\n        >>> my_material.speed_of_sound(7850)\n\n        \"\"\"\n        if density is not None:\n            self.density = density\n        elif self.density is None:\n            raise ValueError(\"Density not given or set\")\n\n        speeds = {'s': np.sqrt(self.G / self.density),\n                  'p': np.sqrt(self.M / self.density)}\n\n        return speeds\n\n    def sss_influence_matrices_normal(self, components: typing.Sequence[str], grid_spacing: typing.Sequence[float],\n                                      span: typing.Sequence[int], z: typing.Sequence[float] = None, cuda: bool = False):\n        if z is None:\n            z_len = min(span)\n            print(span)\n            gs = grid_spacing[span.index(z_len)]\n            print(gs)\n            z = gs * np.arange(z_len // 2)\n            z[0] = z[1] * 1e-4\n        all_matrices = normal_conv_kernels(span, z, grid_spacing, self.E, self.v, cuda=cuda)\n        return {comp: all_matrices[comp] for comp in components}\n\n    def sss_influence_matrices_tangential_x(self, components: typing.Sequence[str],\n                                            grid_spacing: typing.Sequence[float], span: typing.Sequence[int],\n                                            z: typing.Sequence[float] = None, cuda: bool = False):\n        if z is None:\n            z_len = min(span)\n            gs = grid_spacing[span.index(z_len)]\n            z = gs * np.arange(z_len // 2)\n            z[0] = z[1] * 1e-4\n        all_matrices = tangential_conv_kernels(span, z, grid_spacing, self.v, cuda=cuda)\n        return {comp: all_matrices[comp] for comp in components}\n\n    def __repr__(self):\n        return \"Elastic(name = '\" + self.name + f\"', properties = {{ 'E':{self.E}, 'v':{self.v} }}\"\n\n\ndef _get_properties(set_props: dict):\n    \"\"\"Get all elastic properties from any pair\n\n    Parameters\n    ----------\n    set_props : dict\n        dict of properties must have exactly 2 members valid keys are: 'K',\n        'E', 'v', 'Lam', 'M', 'G'\n\n    Returns\n    -------\n    out : dict\n        dict of all material properties keys are: 'K', 'E', 'v', 'Lam', 'M', 'G'\n\n    Notes\n    -----\n\n    Keys refer to:\n        - E - Young's modulus\n        - v - Poission's ratio\n        - K - Bulk Modulus\n        - Lam - Lame's first parameter\n        - G - Shear modulus\n        - M - P wave modulus\n\n    \"\"\"\n    if len(set_props) != 2:\n        raise ValueError(\"Exactly 2 properties must be set,\"\n                         \" {} found\".format(len(set_props)))\n\n    valid_keys = ['K', 'E', 'v', 'G', 'Lam', 'M']\n\n    set_params = [key for key in list(set_props.keys()) if key in valid_keys]\n\n    if len(set_params) != 2:\n        msg = (\"Invalid keys in set_props keys found are: \" +\n               \"{}\".format(set_props.keys()) +\n               \". Valid keys are: \" + \" \".join(valid_keys))\n        raise ValueError(msg)\n\n    out = set_props.copy()\n\n    set_params = list(set_props.keys())\n    set_params.sort()\n    # p is properties this saves a lot of space\n    p = ElasticProps(**set_props)\n\n    if set_params[0] == 'E':\n        if set_params[1] == 'G':\n            out['K'] = p.E * p.G / (3 * (3 * p.G - p.E))\n            out['Lam'] = p.G * (p.E - 2 * p.G) / (3 * p.G - p.E)\n            out['M'] = p.G * (4 * p.G - p.E) / (3 * p.G - p.E)\n            out['v'] = p.E / (2 * p.G) - 1\n        elif set_params[1] == 'K':\n            out['G'] = 3 * p.K * p.E / (9 * p.K - p.E)\n            out['Lam'] = 3 * p.K * (3 * p.K - p.E) / (9 * p.K - p.E)\n            out['M'] = 3 * p.K * (3 * p.K + p.E) / (9 * p.K - p.E)\n            out['v'] = (3 * p.K - p.E) / (6 * p.K)\n        elif set_params[1] == 'Lam':\n            R = np.sqrt(p.E ** 2 + 9 * p.Lam ** 2 + 2 * p.E * p.Lam)\n            out['G'] = (p.E - 3 * p.Lam + R) / 4\n            out['K'] = (p.E + 3 * p.Lam + R) / 6\n            out['M'] = (p.E - p.Lam + R) / 2\n            out['v'] = 2 * p.Lam / (p.E + p.Lam + R)\n        elif set_params[1] == 'M':\n            S = np.sqrt(p.E ** 2 + 9 * p.M ** 2 - 10 * p.E * p.M)\n            out['G'] = (3 * p.M + p.E - S) / 8\n            out['K'] = (3 * p.M - p.E + S) / 6\n            out['Lam'] = (p.M - p.E + S) / 4\n            out['v'] = (p.E - p.M + S) / (4 * p.M)\n        else:  # set_params[1]=='v'\n            out['G'] = p.E / (2 * (1 + p.v))\n            out['K'] = p.E / (3 * (1 - 2 * p.v))\n            out['Lam'] = p.E * p.v / ((1 + p.v) * (1 - 2 * p.v))\n            out['M'] = p.E * (1 - p.v) / ((1 + p.v) * (1 - 2 * p.v))\n    elif set_params[0] == 'G':\n        if set_params[1] == 'K':\n            out['E'] = 9 * p.K * p.G / (3 * p.K + p.G)\n            out['Lam'] = p.K - 2 * p.G / 3\n            out['M'] = p.K + 4 * p.G / 3\n            out['v'] = (3 * p.K - 2 * p.G) / (2 * (3 * p.K + p.G))\n        elif set_params[1] == 'Lam':\n            out['E'] = p.G * (3 * p.Lam + 2 * p.G) / (p.Lam + p.G)\n            out['K'] = p.Lam + 2 * p.G / 3\n            out['M'] = p.Lam + 2 * p.G\n            out['v'] = p.Lam / (2 * (p.Lam + p.G))\n        elif set_params[1] == 'M':\n            out['E'] = p.G * (3 * p.M - 4 * p.G) / (p.M - p.G)\n            out['K'] = p.M - 4 * p.G / 3\n            out['Lam'] = p.M - 2 * p.G\n            out['v'] = (p.M - 2 * p.G) / (2 * p.M - 2 * p.G)\n        else:  # set_params[1]=='v'\n            out['E'] = 2 * p.G * (1 + p.v)\n            out['K'] = 2 * p.G * (1 + p.v) / (3 * (1 - 2 * p.v))\n            out['Lam'] = 2 * p.G * p.v / (1 - 2 * p.v)\n            out['M'] = 2 * p.G * (1 - p.v) / (1 - 2 * p.v)\n    elif set_params[0] == 'K':\n        if set_params[1] == 'Lam':\n            out['E'] = 9 * p.K * (p.K - p.Lam) / (3 * p.K - p.Lam)\n            out['G'] = 3 * (p.K - p.Lam) / 2\n            out['M'] = 3 * p.K - 2 * p.Lam\n            out['v'] = p.Lam / (3 * p.K - p.Lam)\n        elif set_params[1] == 'M':\n            out['E'] = 9 * p.K * (p.M - p.K) / (3 * p.K + p.M)\n            out['G'] = 3 * (p.M - p.K) / 4\n            out['Lam'] = (3 * p.K - p.M) / 2\n            out['v'] = (3 * p.K - p.M) / (3 * p.K + p.M)\n        else:  # set_params[1]=='v'\n            out['E'] = 3 * p.K * (1 - 2 * p.v)\n            out['G'] = (3 * p.K * (1 - 2 * p.v)) / (2 * (1 + p.v))\n            out['Lam'] = 3 * p.K * p.v / (1 + p.v)\n            out['M'] = 3 * p.K * (1 - p.v) / (1 + p.v)\n    elif set_params[0] == 'Lam':\n        if set_params[1] == 'M':\n            out['E'] = (p.M - p.Lam) * (p.M + 2 * p.Lam) / (p.M + p.Lam)\n            out['G'] = (p.M - p.Lam) / 2\n            out['K'] = (p.M + 2 * p.Lam) / 3\n            out['v'] = p.Lam / (p.M + p.Lam)\n        else:\n            out['E'] = p.Lam * (1 + p.v) * (1 - 2 * p.v) / p.v\n            out['G'] = p.Lam(1 - 2 * p.v) / (2 * p.v)\n            out['K'] = p.Lam * (1 + p.v) / (3 * p.v)\n            out['M'] = p.Lam * (1 - p.v) / p.v\n    else:\n        out['E'] = p.M * (1 + p.v) * (1 - 2 * p.v) / (1 - p.v)\n        out['G'] = p.M * (1 - 2 * p.v) / (2 * (1 - p.v))\n        out['K'] = p.M * (1 + p.v) / (3 * (1 - p.v))\n        out['Lam'] = p.M * p.v / (1 - p.v)\n\n    return out\n\n\ndef get_angular_velocity(span, gs):\n    r_omega = np.fft.fftfreq(span[1], d=gs[1]) * (2 * np.pi)\n    c_omega = np.fft.fftfreq(span[0], d=gs[0]) * (2 * np.pi)\n    return np.meshgrid(r_omega, c_omega)\n\n\ndef elastic_influence_matrix_frequency(y_omega, x_omega, norm, norm_2, comp: str, e: float, v: float):\n    \"\"\"\n\n    Parameters\n    ----------\n    y_omega: np.ndarray\n        rotational velocity components in the y direction\n    x_omega: np.ndarray\n        rotational velocity components in the x direction\n    norm: np.ndarray\n        The norm of the velocity vectors\n    norm_2: np.ndarray\n        The squared norm of the velocity vectors\n    comp: str\n        The component to find for example 'xy' gives the deformations in the y direction caused by a load in the x\n        direction\n    e: float\n        The Young's modulus of the material\n    v: float\n        The Poission's ratio of the material\n\n    Returns\n    -------\n    The influence matrix component in the frequency domain\n\n    \"\"\"\n    with np.errstate(divide='ignore', invalid='ignore'):\n        if comp == 'zz':\n            fact = 2 * (1 - v ** 2)\n        elif comp == 'yy':\n            fact = 2 * (1 + v) * (1 - v * y_omega ** 2 / norm_2)\n        elif comp == 'xx':\n            fact = 2 * (1 + v) * (1 - v * x_omega ** 2 / norm_2)\n        elif comp in ('xy', 'yx'):\n            fact = y_omega * x_omega * 2 * v * (1 + v) / norm_2\n        elif comp in ('yz', 'zy'):\n            fact = 1j * y_omega * (1 + v) * (1 - 2 * v) / norm * (-1 if comp == 'zy' else 1)\n        elif comp in ('xz', 'zx'):\n            fact = 1j * x_omega * (1 + v) * (1 - 2 * v) / norm * (-1 if comp == 'zx' else 1)\n        else:\n            raise ValueError('component name not recognised: ' + comp + ', components must be lower case')\n        rtn = fact * (1 / (e * norm))\n    rtn[0, 0] = 0.0\n    return rtn\n\n\n# noinspection PyTypeChecker\ndef elastic_influence_matrix_spatial(comp: str, span: typing.Sequence[int], grid_spacing: typing.Sequence[float],\n                                     shear_mod: float, v: float,\n                                     shear_mod_2: typing.Optional[float] = None,\n                                     v_2: typing.Optional[float] = None) -> np.array:\n    \"\"\"Find influence matrix components for an elastic contact problem\n\n    Parameters\n    ----------\n    comp : str {'xx','xy','xz','yx','yy','yz','zx','zy','zz'}\n        The component to be returned\n    span: Sequence[int]\n        The span of the influence matrix in the x and y directions\n    grid_spacing: Sequence[float]\n        The grid spacings in the x and y directions\n    shear_mod : float\n        The shear modulus of the surface material\n    v : float\n        The Poission's ratio of the surface material\n    shear_mod_2: float (optional) None\n        The shear modulus of the second surface for a combined stiffness matrix\n    v_2: float (optional) None\n        The Poisson's ratio of the second surface for a combined stiffness matrix\n    fft: bool\n        If true the fft of the influence matrix will be returned\n\n    Returns\n    -------\n    C : array\n        The influence matrix component requested\n\n    See Also\n    --------\n    elastic_im\n\n    Notes\n    -----\n\n    Don't use this function, used by: elastic_im\n\n    References\n    ----------\n    Complete boundary element method formulation for normal and tangential\n    contact problems\n\n    \"\"\"\n    span = tuple(span)\n    try:\n        # lets just see how this changes\n        # i'-i and j'-j\n        idmi = (np.arange(span[1]) - span[1] // 2 + (1 - span[1] % 2))\n        jdmj = (np.arange(span[0]) - span[0] // 2 + (1 - span[0] % 2))\n        mesh_idmi = np.tile(idmi, (span[0], 1))\n        mesh_jdmj = np.tile(np.expand_dims(jdmj, -1), (1, span[1]))\n\n    except TypeError:\n        raise TypeError(\"Span should be a tuple of integers\")\n\n    k = mesh_idmi + 0.5\n    el = mesh_idmi - 0.5\n    m = mesh_jdmj + 0.5\n    n = mesh_jdmj - 0.5\n\n    hy = grid_spacing[1]\n    hx = grid_spacing[0]\n\n    second_surface = (shear_mod_2 is not None) and (v_2 is not None)\n    if not second_surface:\n        v_2 = 1\n        shear_mod_2 = 1\n\n    if (shear_mod_2 is not None) != (v_2 is not None):\n        raise ValueError('Either both or neither of the second surface parameters must be set')\n\n    if comp == 'zz':\n        c_zz = (hx * (k * np.log((m + np.sqrt(k ** 2 + m ** 2)) / (n + np.sqrt(k ** 2 + n ** 2))) +\n                      el * np.log((n + np.sqrt(el ** 2 + n ** 2)) / (m + np.sqrt(el ** 2 + m ** 2)))) +\n                hy * (m * np.log((k + np.sqrt(k ** 2 + m ** 2)) / (el + np.sqrt(el ** 2 + m ** 2))) +\n                      n * np.log((el + np.sqrt(el ** 2 + n ** 2)) / (k + np.sqrt(k ** 2 + n ** 2)))))\n\n        const = (1 - v) / (2 * np.pi * shear_mod) + second_surface * ((1 - v_2) / (2 * np.pi * shear_mod_2))\n        ret = const * c_zz\n    elif comp == 'xx':\n        c_xx = (hx * (1 - v) * (k * np.log((m + np.sqrt(k ** 2 + m ** 2)) / (n + np.sqrt(k ** 2 + n ** 2))) +\n                                el * np.log(\n                (n + np.sqrt(el ** 2 + n ** 2)) / (m + np.sqrt(el ** 2 + m ** 2)))) +\n                hy * (m * np.log((k + np.sqrt(k ** 2 + m ** 2)) / (el + np.sqrt(el ** 2 + m ** 2))) +\n                      n * np.log((el + np.sqrt(el ** 2 + n ** 2)) / (k + np.sqrt(k ** 2 + n ** 2)))))\n        const = 1 / (2 * np.pi * shear_mod) + second_surface * (1 / (2 * np.pi * shear_mod_2))\n        ret = const * c_xx\n    elif comp == 'yy':\n        c_yy = (hx * (k * np.log((m + np.sqrt(k ** 2 + m ** 2)) / (n + np.sqrt(k ** 2 + n ** 2))) +\n                      el * np.log((n + np.sqrt(el ** 2 + n ** 2)) / (m + np.sqrt(el ** 2 + m ** 2)))) +\n                hy * (1 - v) * (m * np.log((k + np.sqrt(k ** 2 + m ** 2)) / (el + np.sqrt(el ** 2 + m ** 2))) +\n                                n * np.log((el + np.sqrt(el ** 2 + n ** 2)) / (k + np.sqrt(k ** 2 + n ** 2)))))\n        const = 1 / (2 * np.pi * shear_mod) + second_surface * (1 / (2 * np.pi * shear_mod_2))\n        ret = const * c_yy\n    elif comp in ['xz', 'zx']:\n        c_xz = (hy / 2 * (m * np.log((k ** 2 + m ** 2) / (el ** 2 + m ** 2)) +\n                          n * np.log((el ** 2 + n ** 2) / (k ** 2 + n ** 2))) +\n                hx * (k * (np.arctan(m / k) - np.arctan(n / k)) +\n                      el * (np.arctan(n / el) - np.arctan(m / el))))\n        const = ((2 * v - 1) / (4 * np.pi * shear_mod) + second_surface * (\n            (2 * v_2 - 1) / (4 * np.pi * shear_mod_2))) * (-1 if comp == 'zx' else 1)\n        ret = const * c_xz\n    elif comp in ['yx', 'xy']:\n        c_yx = (np.sqrt(hy ** 2 * n ** 2 + hx ** 2 * k ** 2) -\n                np.sqrt(hy ** 2 * m ** 2 + hx ** 2 * k ** 2) +\n                np.sqrt(hy ** 2 * m ** 2 + hx ** 2 * el ** 2) -\n                np.sqrt(hy ** 2 * n ** 2 + hx ** 2 * el ** 2))\n        const = v / (2 * np.pi * shear_mod) + second_surface * (v_2 / (2 * np.pi * shear_mod_2))\n        ret = const * c_yx\n    elif comp in ['zy', 'yz']:\n        c_zy = (hx / 2 * (k * np.log((k ** 2 + m ** 2) / (n ** 2 + k ** 2)) +\n                          el * np.log((el ** 2 + n ** 2) / (m ** 2 + el ** 2))) +\n                hy * (m * (np.arctan(k / m) - np.arctan(el / m)) +\n                      n * (np.arctan(el / n) - np.arctan(k / n))))\n        const = ((1 - 2 * v) / (4 * np.pi * shear_mod) + second_surface * (1 - 2 * v_2) / (\n            4 * np.pi * shear_mod_2)) * (-1 if comp == 'zy' else 1)\n        ret = const * c_zy\n    else:\n        ValueError('component name not recognised: ' + comp + ', components must be lower case')\n    return ret\n", "meta": {"hexsha": "70654813d75958fdab956901cbf8e764ee2586b0", "size": 24074, "ext": "py", "lang": "Python", "max_stars_repo_path": "slippy/core/elastic_material.py", "max_stars_repo_name": "FrictionTribologyEnigma/SlipPY", "max_stars_repo_head_hexsha": "a97fc5470ce5008ef4c049b82077cd1871f6ef2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-10-30T03:30:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-18T17:09:55.000Z", "max_issues_repo_path": "slippy/core/elastic_material.py", "max_issues_repo_name": "FrictionTribologyEnigma/SlipPY", "max_issues_repo_head_hexsha": "a97fc5470ce5008ef4c049b82077cd1871f6ef2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slippy/core/elastic_material.py", "max_forks_repo_name": "FrictionTribologyEnigma/SlipPY", "max_forks_repo_head_hexsha": "a97fc5470ce5008ef4c049b82077cd1871f6ef2c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8103975535, "max_line_length": 120, "alphanum_fraction": 0.497673839, "include": true, "reason": "import numpy", "num_tokens": 7143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.19544577077313618}}
{"text": "\"\"\"\nModule for dealing with LSFs of various astronomical instruments.\n\"\"\"\nfrom __future__ import print_function, absolute_import, division, unicode_literals\n\nimport numpy as np\nfrom scipy.interpolate import interp1d\nfrom astropy.io import fits, ascii\nfrom astropy.units import Quantity\nimport astropy.units as u\nfrom astropy.table import Table, QTable, Column\nimport glob, imp\nfrom linetools.analysis.interp import interp_Akima\nimport warnings\n\nlt_path = imp.find_module('linetools')[1]\n\nclass LSF(object):\n    \"\"\"Class to deal with line-spread-functions (LSFs) from\n    various different astronomical spectrographs.\n\n    Note: only implemented for HST/COS and HST/STIS at the moment.\n\n    Parameters\n    ----------\n    instr_config : dict\n        A dictionary with the instrument configuration details relevant\n        to the required LSF. Mandatory keywords of the dict are: ['name'], \n        all of which must be either string or None. \n        Note: There must be extra relevant keywords specific to each instrument.\n\n    \"\"\"\n\n    def __init__(self, instr_config):\n        # mandatory keys for characterizing a spectrograph mode\n        self.mandatory_dict_keys = ['name']\n                \n        # Check correct format\n        if not isinstance(instr_config, dict):\n            raise TypeError('`instr_config` must be a dictionary.')\n        elif not all([key in instr_config.keys() for key in self.mandatory_dict_keys]):\n            raise SyntaxError('`instr_config` must have the following mandatory keys {}:'.format(self.mandatory_dict_keys))\n\n        # Initialize basics\n        self.instr_config = instr_config\n        self.name = instr_config['name']\n        if self.name not in ['COS', 'STIS']:\n            raise NotImplementedError('Not ready for this instrument: {}'.format(self.name))\n        \n        # initialize specific to given instrument name\n        # only implemented for HST/COS  and HST/STIS so far\n        if self.name == 'COS':\n            self.pixel_scale, self._data = self.load_COS_data()\n        elif self.name == 'STIS':\n            self.pixel_scale, self._data = self.load_STIS_data()\n        # IMPORTANT: make sure that LSFs are given in linear wavelength scales !!!\n\n        #reformat self._data\n        self.check_and_reformat_data()\n        \n        #other relevant values to initialize?\n\n    def get_lsf(self, wv_array, kind='Akima'):\n        \"\"\" Given a wavelength array `wv_array`, it returns\n        the LSF kernel at the central wavelength of the array, \n        using the same pixel scale and extent of `wv_array`. \n\n        Method for non-Gaussian kernels: First, tabulated LSFs\n        are linearly interpolated to the center of `wv_array`\n        (see LSF.interpolate_to_wv0() for details); then, the\n        LSF is interpolated to match the `wv_array`\n        scale and extent using Akima (or cubic) interpolation (see\n        LSF.interpolate_to_wv_array() for details).\n\n        Parameters\n        ----------\n        wv_array : Quantity numpy.ndarray, shape(N,)\n            Wavelength array for which the LSF kernel is defined. The \n            central wavelength value of `wv_array` define the wavelength\n            at which the LSF is defined, while the limits of `wv_array` \n            define the extent of the kernel.\n        kind : str, optional\n            Specifies the kind of interpolation as a string either \n            ('cubic', 'Akima')\n\n        Returns\n        -------\n        lsf_array : numpy.ndarray, shape(N,)\n            The lsf kernel.\n\n        \"\"\"\n        lsf_array = self.interpolate_to_wv_array(wv_array, kind=kind)\n        return lsf_array['kernel'].data\n\n    def check_and_reformat_data(self):\n        \"\"\"Any re-formating of self._data should happen here.\n\n        At the moment this function does the following:\n         - Make sure that the number of relative pixels of the LSF is odd integer\n         - Impose the middle value to define the 0 relative pixel\n         - Make sure tables with 'rel_pix' given in fraction of pixels (e.g. COS NUV) work properly\n         - Normalize tabulated LSFs\n        \"\"\"\n\n        self._data['rel_pix'] = self.check_and_reformat_relpix(self._data['rel_pix'].data)\n\n        #normalize given LSFs\n        for col_name in self._data.keys()[1:]:\n            self._data[col_name] /= np.sum(self._data[col_name])\n\n    def check_and_reformat_relpix(self, relpix):\n        \"\"\"Performs checks and reformating on a relative pixel array.\n\n        At the moment this function does the following:\n         - Make sure that the number of relative pixels of the LSF is an odd integer\n         - Impose the middle value to define the 0 relative pixel\n\n        Parameters\n        ----------\n        relpix : np.array\n            Relative pixel array\n\n        Returns\n        -------\n        new_relpix array that conforms to the LSF class standards.\n        \"\"\"\n\n        # odd integer for total number of relative pixels\n        n_pix = len(relpix)\n        assert n_pix % 2 != 0, ValueError('LSF tables must be given as odd integers!')\n\n        # make sure relpix == 0 is in the middle of the array\n        n_half = int( (n_pix - 1) / 2)\n        mid_value = relpix[n_half]\n        new_relpix = relpix - mid_value  # 0 in the middle\n\n\n        return new_relpix\n\n    def load_COS_data(self):\n        \"\"\"Load the right data according to `instr_config` for HST/COS \n        instrument\"\"\"\n\n        # define pixel scales; values obtained from STScI\n        # these values must be consistent with the given LSFs\n        pixel_scale_dict = {'G130M': 9.97 / 1000. * u.AA,\n                    'G160M': 12.23 / 1000. * u.AA,\n                    'G140L': 80.3 / 1000. * u.AA,\n                    'G230L': 390. / 1000. * u.AA,\n                    'G185M': 37. / 1000. * u.AA,\n                    'G225M': 33. / 1000. * u.AA,\n                    'G285M': 40. / 1000. * u.AA}\n        # define channel based on grating name\n        channel_dict = {'G130M':  'FUV',\n                    'G160M': 'FUV',\n                    'G140L': 'FUV',\n                    'G230L': 'NUV',\n                    'G185M': 'NUV',\n                    'G225M': 'NUV',\n                    'G285M': 'NUV'}\n\n        try:\n            grating = self.instr_config['grating']\n        except:\n            raise SyntaxError('`grating` keyword missing in `instr_config` dictionary.')\n        \n        if grating not in channel_dict.keys():\n            raise NotImplementedError('Not ready for this HST/COS grating: {}'.format(grating))\n\n        if channel_dict[grating] == 'NUV': #there is only 1 LSF file for NUV data\n            file_name = 'nuv_all_lp1.txt'\n        # COS\n        elif channel_dict[grating] == 'FUV':\n            # Use the ones corrected by scattering when possible\n            # (currently, these are only available for lifetime-position 1)\n            # check: http://www.stsci.edu/hst/cos/performance/spectral_resolution\n            try:\n                life_position = self.instr_config['life_position']\n            except:\n                raise SyntaxError('`life_position` keyword missing in `instr_config` dictionary.')\n\n            if life_position not in ['1','2','3']:\n                raise ValueError('HST/COS `life_position` should be either `1` or `2` or `3` (strings)')\n\n            if life_position == '1':\n                if grating == 'G140L': #use theoretical values \n                    file_name = 'fuv_G140L_lp1.txt'\n                    \n                elif grating == 'G130M': #use empirical values corrected by scattering\n                    file_name = 'fuv_G130M_lp1_empir.txt'\n\n                elif grating == 'G160M': #use empirical values corrected by scattering\n                    file_name = 'fuv_G160M_lp1_empir.txt'\n            \n            elif life_position in ['2','3']:\n                try:\n                    cen_wave = self.instr_config['cen_wave']\n                except:\n                    raise SyntaxError('`cen_wave` keyword missing in `instr_config` dictionary. This should provide the central wavelength of the grating in Angstroms as a string.')\n                #adjust format in cases where cen_wave is of the form: str(1230A)\n                if cen_wave.endswith('A'): #adjust format\n                    cen_wave = cen_wave[:-1]\n                \n                #filenames in this case have a well defined naming convention, and strict format.\n                if life_position == '2':\n                    file_name = 'fuv_{}_{}_lp2.txt'.format(grating,cen_wave)\n                elif life_position == '3':\n                    file_name = 'fuv_{}_{}_lp3.txt'.format(grating,cen_wave)\n                else: # this should never happen\n                    raise NotImplementedError('Unexpected error: please contact linetools developers!')\n\n        else: # Wrong COS channel\n            raise NotImplementedError('Not ready for the given HST/COS channel; only `NUV` and `FUV` channels allowed.')\n        \n        # point to the right file\n        file_name = lt_path + '/data/lsf/{}/{}'.format(self.name,file_name)\n        \n        # get column names\n        f = open(file_name,'r')\n        line = f.readline()  # first line of file\n        f.close()\n        # get rid of '\\n' in first line\n        line = line.split('\\n')[0]\n        # by construction first column should be separated by `,`\n        col_names = line.split(',')\n        col_names[0] = 'rel_pix'\n        \n        pixel_scale = pixel_scale_dict[grating]  # read from dictionary defined above\n        # read data\n        data = ascii.read(file_name, data_start=1, names=col_names)\n        \n        return pixel_scale, data\n\n    def load_STIS_data(self):\n        \"\"\"Load the right data according to `instr_config` for HST/STIS\n        instrument\"\"\"\n\n        # define pixel scales; values obtained from STScI\n        # these values must be consistent with the given LSFs\n        pixel_scale_dict = {\n            'G140L': 0.60 * u.AA,\n            'G140M': 0.05 * u.AA,\n            'G230L': 1.58 * u.AA,\n            'G230M': 0.09 * u.AA,\n            'E140M': 'lambda/91700',\n            'E140H': 'lambda/228000',\n            'E230M': 'lambda/60000',\n            'E230H': 'lambda/228000',\n            'G230LB': 1.35 * u.AA,\n            'G230MB': 0.15 * u.AA,\n            'G430L': 2.73 * u.AA,\n            'G430M': 0.28 * u.AA,\n            'G750L': 4.92 * u.AA,\n            'G750M': 0.56 * u.AA\n        }\n        # define channel based on grating name\n        channel_dict = {\n            'G140L': 'FUV-MAMA',\n            'G140M': 'FUV-MAMA',\n            'G230L': 'NUV-MAMA',\n            'G230M': 'NUV_MAMA',\n            'E140M': 'FUV-MAMA',\n            'E140H': 'FUV-MAMA',\n            'E230M': 'NUV-MAMA',\n            'E230H': 'NUV-MAMA',\n            'G230LB': 'CCD',\n            'G230MB': 'CCD',\n            'G430L': 'CCD',\n            'G430M': 'CCD',\n            'G750L': 'CCD',\n            'G750M': 'CCD'\n        }\n        # also need slits\n        available_slits = {\n            'G140L': ['52x0.1', '52x0.2', '52x0.5', '52x2.0'],\n            'G140M': ['52x0.1', '52x0.2', '52x0.5', '52x2.0'],\n            'G230L': ['52x0.1', '52x0.2', '52x0.5', '52x2.0'],\n            'G230M': ['52x0.1', '52x0.2', '52x0.5', '52x2.0'],\n            'E140H': ['0.1x0.03', '0.2x0.09', '0.2x0.2', '6x0.2'],\n            'E140M': ['0.1x0.03', '0.2x0.06', '0.2x0.2', '6x0.2'],\n            'E230H': ['0.1x0.03', '0.1x0.09', '0.1x0.2', '6x0.2'],\n            'E230M': ['0.1x0.03', '0.2x0.06', '0.2x0.2', '6x0.2'],\n            'G430L': ['52x0.1', '52x0.2', '52x0.5', '52x2.0'],\n            'G750L': ['52x0.1', '52x0.2', '52x0.5', '52x2.0']\n        }\n\n        try:\n            grating = self.instr_config['grating']\n        except:\n            raise SyntaxError('`grating` keyword missing in `instr_config` dictionary.')\n        if grating not in channel_dict.keys():\n            raise NotImplementedError('Not ready for this HST/STIS grating: {}. '\n                                      'Available gratings for HST/STIS are: {}'.format(grating, channel_dict.keys()))\n        if grating in ['G750M', 'G430M', 'G430L']:\n            raise NotImplementedError('{} not implemented yet; coming soon...'.format(grating))\n\n        # We also need to know the slit width\n        try:\n            slit = self.instr_config['slit']\n        except:\n            raise SyntaxError('`slit` keyword missing in `instr_config` dictionary.')\n        if slit not in available_slits[grating]:\n            raise NotImplementedError('Not ready for this HST/STIS slit: {}. '\n                                      'Available slits for HST/STIS grating {} are: {}'.format(slit, grating, available_slits[grating]))\n\n        # now we need to read the right files (new ones for echelle modes)\n        if grating[0]=='E':\n            lsf_files = glob.glob(lt_path + '/data/lsf/STIS/stis_LSF_{}_????_LTmod.txt'.format(grating))\n            # figure relevant wavelengths from file names\n            wa_names = [fname.split('/')[-1].split('_')[-2].split('.')[0] for fname in lsf_files]\n        else:\n            lsf_files = glob.glob(lt_path + '/data/lsf/STIS/stis_LSF_{}_????.txt'.format(grating))\n            # figure relevant wavelengths from file names\n            wa_names = [fname.split('/')[-1].split('_')[-1].split('.')[0] for fname in lsf_files]\n        #TODO: Remove following lines upon testing\n        '''\n        # figure relevant wavelengths from file names\n        #wa_names = [fname.split('/')[-1].split('_')[-1].split('.')[0] for fname in lsf_files]\n        '''\n        # sort them\n        sorted_inds = np.argsort(wa_names)\n        lsf_files = np.array(lsf_files)[sorted_inds]\n        wa_names = np.array(wa_names)[sorted_inds]\n\n        # read the relevant kernels; they may have different rel_pix values depending on wave\n        kernels_dict = dict()\n        for ii, file_name in enumerate(lsf_files):\n            # get the column names\n            f = open(file_name,'r')\n            lines = f.readlines()  # get all lines\n            f.close()\n            col_names = lines[1] # column names are in second line\n            # get rid of '\\n'\n            col_names = col_names.split('\\n')[0]\n            # split by blank space(s) and remove the first element\n            col_names = col_names.split()[1:]\n            # rename new first column\n            col_names[0] = 'rel_pix'\n\n            # get original data\n            data_aux = ascii.read(file_name, data_start=2, names=col_names)\n            # reformat rel_pix\n            data_aux['rel_pix'] = self.check_and_reformat_relpix(data_aux['rel_pix'])\n\n            #TODO: remove the following block upon testing\n            '''\n            # handle asymmetric STIS LSF\n            if data_aux['rel_pix'][len(data_aux['rel_pix']) // 2] == 0.:\n                pass\n            elif data_aux['rel_pix'][(len(data_aux['rel_pix']) // 2) - 1 ] ==0.:\n                data_aux.insert_row(0,data_aux[-1])\n                data_aux['rel_pix'][0]=-data_aux['rel_pix'][-1]\n            elif data_aux['rel_pix'][(len(data_aux['rel_pix']) // 2) + 1 ] ==0.:\n                data_aux.add_row(data_aux[0])\n                data_aux['rel_pix'][-1]=-data_aux['rel_pix'][0]\n            '''\n\n            # create column with absolute wavelength based on pixel scales\n            if isinstance(pixel_scale_dict[grating],np.unicode):\n                # deal with wavelength-dependent pixel scale (i.e., STIS echelle)\n                scalefac = 1./float(pixel_scale_dict[grating].split('/')[-1])\n                wave_aux = float(wa_names[ii])*u.AA * (1. + data_aux['rel_pix']*scalefac)\n            else:\n                wave_aux = float(wa_names[ii])*u.AA + data_aux['rel_pix']*pixel_scale_dict[grating]\n            data_aux['wv'] = wave_aux  # not used for now, but may be useful with a different approach\n            # create column with normalized kernel for relevant slit\n            kernel = data_aux[slit] / np.sum(data_aux[slit])\n            data_aux['kernel'] = kernel\n\n            # store only rel_pix, wv, kernel as Table\n            kernels_dict[wa_names[ii]] = data_aux['rel_pix', 'wv', 'kernel']\n\n        # at this point the kernels_dict have the original information as given by the STScI\n        # tables, in their various formats...\n\n        # project to a single rel_pix scale using interpolation; for simplicity use a\n        # custom rel_pix because STScI sometimes provide them as non-constant pixel fractions.\n        # This new rel_pix grid will apply to all the wavelengths\n\n        rel_pix = kernels_dict[wa_names[0]]['rel_pix']  # use the first one as reference\n        rel_pix = np.linspace(-1*np.max(rel_pix), np.max(rel_pix), len(rel_pix))  # impose them linear and symmetric\n        rel_pix = self.check_and_reformat_relpix(rel_pix)  # again just in case something odd happened\n        data_table = Table()\n        data_table['rel_pix'] = rel_pix\n        for wa_name in wa_names:\n            kernel_aux = interp_Akima(data_table['rel_pix'],\n                                      kernels_dict[wa_name]['rel_pix'], kernels_dict[wa_name]['kernel'])\n            data_table['{}A'.format(wa_name)] = kernel_aux\n\n        pixel_scale = pixel_scale_dict[grating]  # read from dictionary defined above\n        # import pdb; pdb.set_trace()\n        # todo: work out a cleverer approach to this whole issue of having different rel_pix, pixel_scales, etc\n        return pixel_scale, data_table\n\n    def interpolate_to_wv0(self, wv0):\n        \"\"\"Retrieves a unique LSF valid at wavelength wv0\n\n        This is done by linearly interpolating from tabulated values\n        at different wavelengths. These tabulated values (stored\n        internally in self._data) are usually given as calibration\n        products by instrument developers and should be loaded by\n        self.load_XX_data() in the initialization stage of LSF(),\n        where XX is the name of the instrument)\n\n        Parameters\n        ----------\n        wv0 : Quantity \n            Wavelength at which an LSF solution is required\n\n        Returns\n        -------\n        lsf_table : Table\n            The interpolated lsf at wv0. This table has two \n            columns: 'wv' and 'kernel'\n        \"\"\"\n        # get wa0 to Angstroms\n        wv0 = wv0.to('AA').value\n\n        # transform to wavelength in float() form assuming Angstroms\n        col_names = self._data.keys()\n        col_waves = np.array([float(name.split('A')[0]) for name in col_names[1:]])\n\n        # find out the closest 2 columns in self._data to wv0 (on each side); these kernels will be used for interpolation\n        seps =  np.fabs(col_waves - wv0)\n        closest_ind = np.argsort(seps)[0]  # the 1 closest\n        if closest_ind == 0:  # lower edge\n            ind_blue = closest_ind\n        elif closest_ind == len(col_waves) - 1:  # upper edge\n            ind_blue = closest_ind - 1\n        elif (col_waves[closest_ind] - wv0) > 0:  # middle case 1\n            ind_blue = closest_ind - 1\n        else:  # middle case 2\n            ind_blue = closest_ind\n        ind_red = ind_blue + 1\n\n        # create a smaller version of self._data with the 2 most relevant columns\n        good_keys = col_names[1:]  # get rid of the first name, i.e. 'rel_pix'\n        good_keys = good_keys[ind_blue : ind_red + 1]\n        data_aux = self._data[good_keys]\n        col_waves_aux = col_waves[ind_blue : ind_red + 1]\n        lsf_vals = []\n        for row in data_aux:\n            aux_val = []\n            for i in range(0, len(row)):\n                aux_val += [row[i]]\n\n            # we don't want to extrapolate wildly, but allow LSF instantiations for wv0 outside range of 'col_waves'\n            if (wv0 >= col_waves_aux[0]) & (wv0 <= col_waves_aux[-1]):\n                f = interp1d(col_waves_aux,aux_val,bounds_error=True,kind='linear')  # no need to extrapolate\n                lsf_vals += [f(wv0)]\n\n            elif (wv0 < col_waves[0]) & ((col_waves[0] - wv0) < np.abs(col_waves[1] - col_waves[0])):\n                f = interp1d(col_waves_aux, aux_val, bounds_error=False,\n                             fill_value=aux_val[0], kind='linear')  # assign shortest wv LSF definition\n                lsf_vals += [f(wv0)]\n\n                # warning\n                if (col_waves[0] - wv0) > (np.abs(col_waves[1] - col_waves[0])/2.):\n                    warnings.warn(\n                        \"LSF may result from extrapolation outside wavelength range characterized for current grating.\")\n\n            elif (wv0 > col_waves[-1]) & ((wv0 - col_waves[-1]) < np.abs(col_waves[-1] - col_waves[-2])):\n                f = interp1d(col_waves_aux, aux_val, bounds_error=False,\n                             fill_value=aux_val[-1], kind='linear') #assign longest wv LSF definition\n                lsf_vals += [f(wv0)]\n\n                # warning\n                if (wv0 - col_waves[-1]) > (np.abs(col_waves[-1] - col_waves[-2])/2.):\n                    warnings.warn(\n                        \"LSF may result from extrapolation outside wavelength range characterized for current grating.\")\n            else:\n                raise ValueError(\"wv0 too far outside range of defined LSFs. Perhaps you've chosen the wrong grating?\")\n        lsf_vals = np.array(lsf_vals)\n\n        # normalize\n        lsf_vals /= np.sum(lsf_vals)\n\n        # create Column to store the interpolated LSF\n        # lsf_vals = Column(name='{:.0f}A'.format(wv0.value),data=lsf_vals)\n        lsf_vals = Column(name='kernel', data=lsf_vals)\n\n        # create column of relative pixel in absolute wavelength\n        if isinstance(self.pixel_scale,np.unicode):\n            # deal with wavelength-dependent pixel scale (i.e., STIS echelle)\n            scalefac = 1./float(self.pixel_scale.split('/')[-1])\n            wv_array = [(wv0*u.AA * (1. + scalefac * self._data['rel_pix'][i])).value\n                        for i in range(len(self._data))]\n        else:\n            wv_array = [(self.pixel_scale * self._data['rel_pix'][i] + wv0*u.AA).value for i in range(len(self._data))]\n        wv = Column(name='wv',data=wv_array, unit=u.AA)\n\n        # create lsf Table\n        lsf = Table()\n        lsf.add_column(wv)\n        lsf.add_column(lsf_vals)\n\n        # return lsf Table()\n        return lsf\n\n    def interpolate_to_wv_array(self, wv_array, kind='Akima', debug=False):\n        \"\"\" Interpolate an LSF to a wavelength array.\n        \n        Given `wv_array` this function interpolates an LSF\n        to match both scale and extent of `wv_array` using the \n        Akima or cubic-spline interpolators (default is Akima). \n        Some checks are performed too.\n\n        Parameters\n        ----------\n        wv_array : Quantity numpy.ndarray, shape(N,)\n            Wavelength array for which the LSF kernel is defined. The \n            central wavelength value of `wv_array` define the wavelength\n            at which the LSF is defined, while the limits of `wv_array` \n            define the extent of the kernel.\n        kind : str, optional\n            Specifies the kind of interpolation as a string either \n            ('cubic', 'Akima'); default is `Akima`.\n\n        Returns\n        -------\n        lsf_table : Table\n            The interpolated lsf using at the central wavelength of \n            `wv_array`, using the same pixel scale as `wv_array`. \n            This table has two columns: 'wv' and 'kernel'. (lst_table['wv'] \n            is equal to `wv_array` by construction.)\n\n        \"\"\"\n        # Check correct format\n        if not ((isinstance(wv_array, np.ndarray)) or (isinstance(wv_array, Quantity))):\n            raise SyntaxError('`wv_array` must be Quantity numpy.ndarray')\n        elif len(wv_array.shape) != 1:\n            raise SyntaxError('`wv_array` must be of shape(N,), i.e. 1-dimensional array')\n        if kind not in ['cubic','Akima','akima']:\n            raise ValueError('Only `cubic` or `Akima` interpolation available.')\n\n        # define useful quantities\n        wv_min = np.min(wv_array)\n        wv_max = np.max(wv_array)\n        wv0 = 0.5 * (wv_max + wv_min)\n\n        lsf_tab = self.interpolate_to_wv0(wv0)\n\n        # make sure the wv_array is dense enough to sample the LSF kernel\n        kernel_wvmin = np.min(lsf_tab['wv']) * u.AA\n        kernel_wvmax = np.max(lsf_tab['wv']) * u.AA\n        cond = (wv_array >= kernel_wvmin) & (wv_array <= kernel_wvmax)\n        if np.sum(cond) < 10:  # this number is somewhat arbitrary but reasonable\n            raise ValueError('The input `wv_array` is undersampling the LSF kernel! Try a finer grid.')\n\n        # convert to Angstroms\n        wv_array_AA = np.array([wv.to('AA').value for wv in wv_array])\n        \n        # interpolate to wv_array\n        if kind == 'cubic':\n            f = interp1d(lsf_tab['wv'], lsf_tab['kernel'], kind='cubic', bounds_error= False, fill_value=0)\n            lsf_vals =  f(wv_array_AA)\n        elif kind in ('Akima','akima'):\n            # f = Akima1DInterpolator(lsf_tab['wv'],lsf_tab['kernel']) \n            # NT: I tried Akima interpolator from scipy.interpolate\n            # and is not robust in extreme situations where the\n            # wv_array is large compared to the kernel FWHM.\n            # Let's try linetools.analysis.interp Akima version\n            lsf_vals = interp_Akima(wv_array_AA,lsf_tab['wv'],lsf_tab['kernel'])\n\n        # make sure the kernel is never negative\n        cond = lsf_vals < 0\n        if np.sum(cond) > 0:\n            warnings.warn('The interpolated kernel has negative values; imposing them to be 0.')\n            if debug:\n                import matplotlib.pyplot as plt\n                plt.plot(wv_array_AA, lsf_vals, 'k-')\n                # import pdb; pdb.set_trace()\n            lsf_vals = np.where(lsf_vals < 0, 0., lsf_vals)\n\n        # normalize\n        lsf_vals /= np.sum(lsf_vals)\n\n        # re-define Table\n        lsf_tab = Table()\n        lsf_tab.add_column(Column(name='wv', data=wv_array))\n        lsf_tab.add_column(Column(name='kernel', data=lsf_vals))\n\n        return lsf_tab\n", "meta": {"hexsha": "be8c941f0192fbc3b3bbe900b46e74e85e722409", "size": 25913, "ext": "py", "lang": "Python", "max_stars_repo_path": "linetools/spectra/lsf.py", "max_stars_repo_name": "marijana777/linetools", "max_stars_repo_head_hexsha": "73720a2f6df42b7dde1f35055cd40ad970200f7f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linetools/spectra/lsf.py", "max_issues_repo_name": "marijana777/linetools", "max_issues_repo_head_hexsha": "73720a2f6df42b7dde1f35055cd40ad970200f7f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linetools/spectra/lsf.py", "max_forks_repo_name": "marijana777/linetools", "max_forks_repo_head_hexsha": "73720a2f6df42b7dde1f35055cd40ad970200f7f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.3715753425, "max_line_length": 181, "alphanum_fraction": 0.5802878864, "include": true, "reason": "import numpy,from scipy,import astropy,from astropy", "num_tokens": 6623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.19543223558968217}}
{"text": "'''\nCommonly used global constants. **New users should change\n`ANCILLARY_DATA_PATHS` if it doesn't match their file system.**\n\nSource for EASE-Grid 2.0 parameters:\n\n    https://nsidc.org/ease/ease-grid-projection-gt\n\nNOTE: EASE-Grid 2.0 parameters do not match exactly those specified at NSIDC\nbecause, in fact, they must be 1000 or 9000, depending on the grid size, in\norder to get the right number of rows and columns in the output image.\nGrid resolution is only a whole number for the polar (north or south\nhemisphere) grids.\n'''\n\nimport csv\nimport numpy as np\nfrom collections import OrderedDict\n\nANCILLARY_DATA_PATHS = {\n    'smap_l4c_ancillary_data_file_path': 'SPL4C_Vv4040_SMAP_L4_C.Ancillary.h5',\n    'smap_l4c_1km_ancillary_data_lc_path': 'MCD12Q1_M01_lc_dom_uint8',\n    'smap_l4c_9km_ancillary_data_lc_path': 'MOD12Q1_M09_lc_dom_uint8',\n    'smap_l4c_1km_ancillary_data_x_coord_path': 'SMAP_L4_C_LON_14616_x_34704_M01_flt32',\n    'smap_l4c_1km_ancillary_data_y_coord_path': 'SMAP_L4_C_LAT_14616_x_34704_M01_flt32',\n    'smap_l4c_9km_ancillary_data_x_coord_path': 'SMAP_L4_C_LON_1624_x_3856_M09_flt32',\n    'smap_l4c_9km_ancillary_data_y_coord_path': 'SMAP_L4_C_LAT_1624_x_3856_M09_flt32',\n    'smap_l4c_9km_pft_subgrid_counts_CONUS': 'SMAP_L4C_Vv4040_1km_subgrid_PFT_counts_CONUS.h5',\n    'smap_l4c_9km_sparse_col_index': 'MCD12Q1_M09land_col.uint16',\n    'smap_l4c_9km_sparse_row_index': 'MCD12Q1_M09land_row.uint16',\n    'transcom_netcdf_path': 'CarbonTracker_TransCom_and_other_regions.nc'\n}\n\n\n# Version 4020 BPLUT parameters in order of PFT numeric code (PFT 0 through 9)\nBPLUT = OrderedDict({\n    # Only reason for OrderedDict (instead of dict) is for consistency with\n    #   pyl4c.data.fixtures.BPLUT()\n    '_version': '4',\n    'LUE': np.array([[ # gC per MJ\n        np.nan, 1.71, 1.38, 1.71, 1.19, 1.95, 1.68, 2.53, 3.6, np.nan\n    ]]),\n    'CUE': np.array([[\n        np.nan, 0.7, 0.57, 0.79, 0.78, 0.65, 0.6, 0.72, 0.71, np.nan\n    ]]),\n    'tmin': np.array([ # degrees K\n        [np.nan, 235, 230, 259, 260, 259, 251, 246, 266, np.nan],\n        [np.nan, 309, 303, 301, 284, 304, 302, 314, 319, np.nan]\n    ]),\n    'vpd': np.array([ # Pascals\n        [np.nan, 0, 15, 869, 1500, 4, 0, 228, 1500, np.nan],\n        [np.nan, 4169, 7000, 3452, 5401, 4282, 4229, 4516, 7000, np.nan]\n    ]),\n    'smrz': np.array([ # Percent saturation\n        [np.nan, -30, 18, -30, -26, 22, -30, -15, 10, np.nan],\n        [np.nan, 74, 26, 49, 87, 72, 76, 30, 68, np.nan]\n    ]),\n    'smsf': np.array([ # Percent saturation\n        [np.nan, -50, -46, -9, -50, -15, -3, -42, -49, np.nan],\n        [np.nan, 46, 59, 43, 53, 48, 51, 41, 30, np.nan]\n    ]),\n    'ft': np.array([ # Frozen = 0, Thawed = 1\n        [np.nan, 0.58, 0.36, 0.55, 0.9, 0.91, 0.85, 0.77, 1, np.nan],\n        [np.nan, 1, 1, 1, 1, 1, 1, 1, 1, np.nan]\n    ]),\n    'tsoil': np.array([[ # degrees K\n        np.nan, 265.04, 477.83, 238.81, 267.26, 292.82, 232.24, 263.97, 329.63, np.nan\n    ]]),\n    # NOTE: The medium/structural and slow/recalcitrant decay constants\n    #   (2nd and 3rd rows) are true decay constants, unlike in Ops\n    #   BPLUT which presents only dimensionless scalars.\n    'decay_rates': np.array([ # days^-1\n        [np.nan, 0.027, 0.028, 0.028, 0.03, 0.015, 0.025, 0.019, 0.035, np.nan],\n        [np.nan, 1.08e-2, 1.12e-2, 1.12e-2, 1.2e-2, 0.6e-2, 1e-2, 0.76e-2, 1.4e-2, np.nan],\n        [np.nan, 2.51e-4, 2.6e-4, 2.6e-4, 2.79e-4, 1.4e-4, 2.33e-4, 1.77e-4, 3.26e-4, np.nan]\n    ]),\n    'f_metabolic': np.array([[ # Fraction of daily litterfall entering \"fast\" or metabolic pool\n        np.nan, 0.49, 0.71, 0.67, 0.67, 0.62, 0.76, 0.78, 0.78, np.nan\n    ]]), # Also known as \"f_met\"\n    'f_structural': np.array([[ # Fraction of structural (str) pool transferred in \"humification\"\n        np.nan, 0.3, 0.3, 0.7, 0.3, 0.35, 0.55, 0.5, 0.8, np.nan\n    ]]) # Also known as \"f_str\" -- See Jones et al. (2017, IEEE TGARS, p.5)\n})\n\n\nEASE2_GRID_PARAMS = {\n    # A GeoTransform for a north-up raster is:\n    #   (x_min, pixel_width, 0, y_max, 0, -pixel_height)\n    'M01': {\n        'epsg': 6933,\n        'geotransform': (-17367530.45, 1000, 0, 7314540.83, 0, -1000),\n        'resolution': 1000.89502334956, # From Brodzik et al.\n        'shape': (14616, 34704),\n        'size': 14616*34704\n    },\n    'M09': {\n        'epsg': 6933,\n        'geotransform': (-17367530.45, 9000, 0, 7314540.83, 0, -9000),\n        'resolution': 9008.055210146, # From Brodzik et al.\n        'shape': (1624, 3856),\n        'size': 1624*3856\n    },\n    'N09': {\n        'epsg': 6931,\n        'geotransform': (-9000000.0, 9000, 0, 9000000.0, 0, -9000),\n        'resolution': 9000,\n        'shape': (2000, 2000),\n        'size': 2000*2000\n    },\n    'M25': {\n        'epsg': 6933,\n        'geotransform': (-17367530.45, 25000, 0, 7307375.92, 0, -25000),\n        'resolution': 25000,\n        'shape': (584, 1388),\n        'size': 584*1388\n    },\n    'M36': {\n        'epsg': 6933,\n        'geotransform': (-17367530.45, 36000, 0, 7314540.83, 0, -36000),\n        'resolution': 36032.22,\n        'shape': (406, 964),\n        'size': 406*964\n    }\n}\n\n\nHDF_PATHS = { # Where in the HDF hierarchy certain variables live\n    'SPL4CMDL': { # By Earthdata Dataset ID\n        '4': { # By Version number\n            'longitude': 'GEO/longitude',\n            'latitude': 'GEO/latitude',\n            'SOC': 'SOC/soc_mean',\n            'SOC*': 'SOC/soc_pft%d_mean',\n            'GPP': 'GPP/gpp_mean',\n            'GPP*': 'GPP/gpp_pft%d_mean',\n            'NEE': 'NEE/nee_mean',\n            'NEE*': 'NEE/nee_pft%d_mean',\n            'RH': 'RH/rh_mean',\n            'RH*': 'RH/rh_pft%d_mean',\n        }\n    },\n    'SPL4SMGP': {\n        '4': {'longitude': 'cell_lon', 'latitude': 'cell_lat',}\n    }\n}\n\n\nPFT = OrderedDict({\n    0: ('Water', 'WET'),\n    1: ('Evergreen Needleleaf', 'ENF'),\n    2: ('Evergreen Broadleaf', 'EBF'),\n    3: ('Deciduous Needleleaf', 'DNF'),\n    4: ('Deciduous Broadleaf', 'DBF'),\n    5: ('Shrub', 'SHB'),\n    6: ('Grass', 'GRS'),\n    7: ('Cereal Crop', 'CCR'),\n    8: ('Broadleaf Crop', 'BCR'),\n    9: ('Urban and Built-Up', 'URB')\n})\n\n\n# BBOX extents, in decimal degrees, based on gdal_rasterize -te option:\n#   https://gdal.org/programs/gdal_rasterize.html#cmdoption-gdal-translate-te\nSUBSETS_BBOX = { # <xmin>, <ymin>, <xmax>, <ymax>\n    'CONUS': [-124.5, 24.4, -66.7, 50.0],\n    'WesternHemisphere': [-180, -90, 0, 90],\n    'WesternHemisphere2': [-180, -90, -25, 90],\n    'NorthernHemisphere': [-180, 0, 180, 90],\n    'NorthernHemisphere45': [-180, 45, 180, 90],\n    'NorthernHemisphere40': [-180, 40, 180, 90],\n    'Nigeria': [2.3, 4, 14.8, 14],\n    # AOI for: Chiodi and Harrison (2013) Journal of Climate 26 (3):822–837\n    'ChiodiHarrison2013': [-160, -5, -110, 5],\n    'Kang2014EMS': [-125, 47, -113, 49],\n    'NorthernPlains': [-116.1, 40.9, -96.4, 49],\n    'Montana': [-116.1, 44.4, -104.01, 49],\n    'Iowa': [-96.7, 40.58, -90.1, 43.5],\n    'Bangladesh1kmSubset': [78.9, 23.2, 96.1, 29.3]\n}\n\n\ndef parameter_mapped(name, pft_array, bplut = BPLUT):\n    '''\n    Given a BPLUT parameter and a PFT array, returns an array with the\n    corresponding parameter values for each PFT code.\n\n    Parameters\n    ----------\n    name : str\n        The name of the BPLUT parameter\n    pft_array : numpy.ndarray\n        Array of any size or shape with numeric elements corresponding to\n        PFT codes\n    bplut : dict\n        (Optional) A collection of BPLUT parameters\n\n    Returns\n    -------\n    numpy.ndarray\n        Array of same size, shape as pft_array but with parameter values\n        in place of PFT codes\n    '''\n    param = bplut[name]\n    # Basically, index the <name> array, in PFT order, by PFT numeric codes\n    return np.asarray(param)[np.ravel(pft_array)].reshape(pft_array.shape)\n\n\ndef restore_bplut(csv_file_path, version_id = None):\n    '''\n    Translates a BPLUT CSV file to a Python internal representation\n    (OrderedDict instance).\n\n    Parameters\n    ----------\n    csv_file_path : str\n        File path to the CSV representation of the BPLUT\n    version_id : str\n        (Optional) Version identifier for the BPLUT\n\n    Returns\n    -------\n    OrderedDict\n    '''\n    header = ('LC_index', 'LC_Label', 'model_code', 'NDVItoFPAR_scale',\n        'NDVItoFPAR_offset', 'LUEmax', 'Tmin_min_K', 'Tmin_max_K',\n        'VPD_min_Pa', 'VPD_max_Pa', 'SMrz_min', 'SMrz_max', 'FT_min',\n        'FT_max', 'SMtop_min', 'SMtop_max', 'Tsoil_beta0', 'Tsoil_beta1',\n        'Tsoil_beta2', 'fraut', 'fmet', 'fstr', 'kopt', 'kstr', 'kslw',\n        'Nee_QA_Rank_min', 'Nee_QA_Rank_max', 'Nee_QA_Error_min',\n        'Nee_QA_Error_max', 'Fpar_QA_Rank_min', 'Fpar_QA_Rank_max',\n        'Fpar_QA_Error_min', 'Fpar_QA_Error_max', 'FtMethod_QA_mult',\n        'FtAge_QA_Rank_min', 'FtAge_QA_Rank_max', 'FtAge_QA_Error_min',\n        'FtAge_QA_Error_max', 'Par_QA_Error', 'Tmin_QA_Error',\n        'Vpd_QA_Error', 'Smrz_QA_Error', 'Tsoil_QA_Error', 'Smtop_QA_Error')\n    contents = []\n    with open(csv_file_path, 'r') as stream:\n        reader = csv.DictReader(\n            filter(lambda row: row[0] != '#', stream), fieldnames = header)\n        for row in reader:\n            contents.append(row)\n\n    result = BPLUT.copy()\n    result['_version'] = 'UNKNOWN' if version_id is None else version_id\n    result['LUE'] = np.array([[\n        contents[p-1]['LUEmax'] if p in range(1, 9) else np.nan\n        for p in range(0, 10)\n    ]], dtype = np.float32).round(4)\n    result['CUE'] = np.array([[\n        (1 - float(contents[p-1]['fraut'])) if p in range(1, 9) else np.nan\n        for p in range(0, 10)\n    ]], dtype = np.float32).round(4)\n    result['tmin'] = np.array([\n        [contents[p-1]['Tmin_min_K'] if p in range(1, 9) else np.nan\n            for p in range(0, 10)],\n        [contents[p-1]['Tmin_max_K'] if p in range(1, 9) else np.nan\n            for p in range(0, 10)],\n    ], dtype = np.float32).round(1)\n    result['vpd'] = np.array([\n        [contents[p-1]['VPD_min_Pa'] if p in range(1, 9) else np.nan\n            for p in range(0, 10)],\n        [contents[p-1]['VPD_max_Pa'] if p in range(1, 9) else np.nan\n            for p in range(0, 10)],\n    ], dtype = np.float32).round(2)\n    result['smrz'] = np.array([\n        [contents[p-1]['SMrz_min'] if p in range(1, 9) else np.nan\n            for p in range(0, 10)],\n        [contents[p-1]['SMrz_max'] if p in range(1, 9) else np.nan\n            for p in range(0, 10)],\n    ], dtype = np.float32).round(1)\n    result['smsf'] = np.array([\n        [contents[p-1]['SMtop_min'] if p in range(1, 9) else np.nan\n            for p in range(0, 10)],\n        [contents[p-1]['SMtop_max'] if p in range(1, 9) else np.nan\n            for p in range(0, 10)],\n    ], dtype = np.float32).round(1)\n    result['ft'] = np.array([\n        [contents[p-1]['FT_min'] if p in range(1, 9) else np.nan\n            for p in range(0, 10)],\n        [contents[p-1]['FT_max'] if p in range(1, 9) else np.nan\n            for p in range(0, 10)],\n    ], dtype = np.float32).round(3)\n    result['tsoil'] = np.array([[\n        contents[p-1]['Tsoil_beta0'] if p in range(1, 9) else np.nan\n        for p in range(0, 10)\n    ]], dtype = np.float32).round(1)\n    result['f_metabolic'] = np.array([[\n        contents[p-1]['fmet'] if p in range(1, 9) else np.nan\n        for p in range(0, 10)\n    ]], dtype = np.float32).round(3)\n    result['f_structural'] = np.array([[\n        contents[p-1]['fstr'] if p in range(1, 9) else np.nan\n        for p in range(0, 10)\n    ]], dtype = np.float32).round(1)\n    result['decay_rates'] = np.array([\n        [contents[p-1]['kopt'] if p in range(1, 9) else np.nan\n            for p in range(0, 10)],\n        [contents[p-1]['kstr'] if p in range(1, 9) else np.nan\n            for p in range(0, 10)],\n        [contents[p-1]['kslw'] if p in range(1, 9) else np.nan\n            for p in range(0, 10)],\n    ], dtype = np.float32).round(3)\n    # The \"kstr\" and \"kslw\" values are really the fraction of kopt\n    #   assigned to the second and third pools\n    result['decay_rates'][1,:] = np.multiply(\n        result['decay_rates'][0,:], result['decay_rates'][1,:])\n    result['decay_rates'][2,:] = np.multiply(\n        result['decay_rates'][0,:], result['decay_rates'][2,:])\n    return result\n", "meta": {"hexsha": "ef3ffa07905187399b6ba8a73c91e44786b9f33b", "size": 12199, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyl4c/data/fixtures.py", "max_stars_repo_name": "arthur-e/pyl4c", "max_stars_repo_head_hexsha": "97e1225c8b70ed9b21edc9e54ee66c78a02cded8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-01T18:30:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-01T18:30:21.000Z", "max_issues_repo_path": "pyl4c/data/fixtures.py", "max_issues_repo_name": "arthur-e/pyl4c", "max_issues_repo_head_hexsha": "97e1225c8b70ed9b21edc9e54ee66c78a02cded8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyl4c/data/fixtures.py", "max_forks_repo_name": "arthur-e/pyl4c", "max_forks_repo_head_hexsha": "97e1225c8b70ed9b21edc9e54ee66c78a02cded8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4789644013, "max_line_length": 97, "alphanum_fraction": 0.5875891467, "include": true, "reason": "import numpy", "num_tokens": 4497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.3276682876897044, "lm_q1q2_score": 0.1954322230568963}}
{"text": "# Reduce the PolSpice CIB measurement and make GP plots\n\nimport os\n\nimport numpy as np\n\nimport sys\nsys.path.append(\"../tools/\")\nfrom misc_utils import create_beam_operator, file_header\nfrom CIB_model import CIBModel\n\n# KCAP_PATH = \"../../KiDS/kcap/\"\n# sys.path.append(os.path.join(KCAP_PATH, \"kcap\"))\n# import cosmosis_utils\n\n\nPI = np.pi\n\n\ndef plot_Cls(Cls, xlabel=r\"$\\ell$\", ylabel=r\"$\\ell^2/2\\pi\\ C_\\ell$\",\n             z_cuts=None, scaling=lambda ell: ell**2/(2*PI),\n             xscale=\"log\", yscale=\"linear\",\n             ylim=None, title=\"\", filename=\"\"):\n    import matplotlib.pyplot as plt\n\n    fig, ax = plt.subplots(2, 3, sharex=True, sharey=True, figsize=(8, 5))\n    fig.subplots_adjust(hspace=0, wspace=0)\n\n    if z_cuts is None:\n        z_cuts = [(0.1, 0.3),\n                  (0.3, 0.5),\n                  (0.5, 0.7),\n                  (0.7, 0.9),\n                  (0.9, 1.2),\n                  ]\n    for i, z_cut in enumerate(z_cuts):\n        ax.flatten()[i].axhline(0, c=\"k\", lw=1)\n        \n        for Cl_spec in Cls:\n            c = Cl_spec.copy()\n            Y = c.pop(\"Y\")\n            X = c.pop(\"X\")\n            n_ell_bin = X.size\n            u = scaling(X)\n            if Y.ndim == 1 and len(z_cuts) > 1:\n                Y = Y[n_ell_bin*i:n_ell_bin*(i+1)]\n            elif Y.ndim == 2:\n                Y = Y[i]\n\n            Y_err = c.pop(\"Y_err\", None)\n            Y_lower = c.pop(\"Y_lower\", None)\n            Y_upper = c.pop(\"Y_upper\", None)\n            if Y_err is not None:\n                if Y_err.ndim == 1 and len(z_cuts) > 1:\n                    Y_err = Y_err[n_ell_bin*i:n_ell_bin*(i+1)]\n                elif Y_err.ndim == 2:\n                    Y_err = Y_err[i]\n                ax.flatten()[i].errorbar(X, u*Y, u*Y_err, **c)\n            elif Y_lower is not None and Y_upper is not None:\n                if Y_lower.ndim == 1 and len(z_cuts) > 1:\n                    Y_lower = Y_lower[n_ell_bin*i:n_ell_bin*(i+1)]\n                    Y_upper = Y_upper[n_ell_bin*i:n_ell_bin*(i+1)]\n                elif Y_lower.ndim == 2:\n                    Y_lower = Y_lower[i]\n                    Y_upper = Y_upper[i]\n                label_CI = c.pop(\"label_CI\", None)\n                label_mean = c.pop(\"label\", None)\n                color = c.pop(\"c\", None)\n                ax.flatten()[i].fill_between(X, u*Y_lower, u*Y_upper, **c,\n                                             label=label_CI, facecolor=color)\n                ax.flatten()[i].plot(X, u*Y, **c, c=color, label=label_mean)\n            else:\n                ax.flatten()[i].plot(X, u*Y, **c)\n\n        ax.flatten()[i].set_xlabel(xlabel)\n        ax.flatten()[i].set_title(f\"z: {z_cut[0]}-{z_cut[1]}\", x=0.25, y=0.85)\n\n    ax[0,0].set_xscale(xscale)\n    ax[0,0].set_yscale(yscale)\n\n    [p[0].set_ylabel(ylabel) for p in ax]\n    ax.flatten()[-1].axis(\"off\")\n    ax.flatten()[-2].legend(frameon=False, loc=\"upper left\",\n                            bbox_to_anchor=(1, 0.8))\n\n    if ylim is not None:\n        ax[0,0].set_ylim(**ylim)\n\n    fig.suptitle(title)\n    fig.dpi = 300\n    if filename != \"\":\n        fig.savefig(filename) \n\nif __name__ == \"__main__\":\n\n    mode = \"namaster\"\n\n    if mode == \"namaster\":\n        compute_prediction_for_cov = False\n        make_plots = True\n\n        probe = \"TE\"\n        field = \"545GHz_CIB\"\n        label = f\"KiDS-1000 x 545 GHz CIB, {probe}\"\n        units = r\"[mJy]\"\n\n        # field = \"100GHz_HFI\"\n        # probe = \"TE\"\n        # label = f\"KiDS-1000 x 100 GHz HFI, {probe}\"\n        # units = r\"[$\\mathrm{K}_\\mathrm{CMB}$]\"\n\n        data_file = f\"../results/measurements/shear_KiDS1000_{field}/likelihood/data/Cl_{probe}_shear_KiDS1000_gal_{field}.txt\"\n        cov_file = f\"../results/measurements/shear_KiDS1000_{field}/likelihood/cov/covariance_gaussian_nka_{probe}{probe}.txt\"\n\n        data = np.loadtxt(data_file)\n        ell_data = data[:, 0]\n        data = data[:, 1:]\n\n        cov = np.loadtxt(cov_file)\n\n    elif mode == \"polspice\":\n        import base_config\n\n        defaults = {**base_config.PATHS, **base_config.DATA_DIRS}\n\n        # binning_operator = np.loadtxt(\n        #                         cosmosis_utils.emulate_configparser_interpolation(\n        #                             base_config.bin_op_file, defaults))\n        binning_operator = np.loadtxt(\"../data/xcorr/bin_operator_log_n_bin_12_ell_51-2952.txt\")\n\n        OLD_MEASUREMENT_DIR = \"../../project-triad-obsolete/results/measurements/\"\n\n        target_beam = 10.0\n\n        # CIB_maps = [\"353\", \"545\", \"857\"]\n        CIB_maps = [\"545\"]\n\n        z_cuts = [(0.1, 0.3),\n                (0.3, 0.5),\n                (0.5, 0.7),\n                (0.7, 0.9),\n                (0.9, 1.2),\n                ]\n\n        Cl_CIB_shear = {z: {c: {} for c in CIB_maps} for z in z_cuts}\n\n        for z_cut in z_cuts:\n            for CIB_map in CIB_maps:\n                ell, TE, TB = np.loadtxt(\n                                os.path.join(OLD_MEASUREMENT_DIR,\n                                            f\"shear_KiDS1000_CIB/\"\n                                            f\"z{z_cut[0]:.1f}-{z_cut[1]:.1f}-Planck-{CIB_map}/spice.cl\"),\n                                unpack=True, usecols=[0, 7, 8])\n\n                beam_operator = create_beam_operator(ell, \n                                                    fwhm_map=5.0,\n                                                    fwhm_target=target_beam)\n\n                Cl_CIB_shear[z_cut][CIB_map] = {\"ell_raw\"             : ell,\n                                                \"Cl_TE_raw\"           : TE,\n                                                \"Cl_TB_raw\"           : TB,\n                                                \"Cl_TE_raw_beam10\"    : beam_operator @ TE,\n                                                \"Cl_TB_raw_beam10\"    : beam_operator @ TB,\n                                                \"ell_binned\"          : binning_operator @ ell,\n                                                \"Cl_TE_binned\"        : binning_operator @ TE,\n                                                \"Cl_TB_binned\"        : binning_operator @ TB,\n                                                \"Cl_TE_beam_binned\" : binning_operator @ beam_operator @ TE,\n                                                \"Cl_TB_beam_binned\" : binning_operator @ beam_operator @ TB}\n\n        CIB_jk_data = np.load(\n                        os.path.join(OLD_MEASUREMENT_DIR,\n                                    f\"shear_KiDS1000_CIB/shear_KiDS1000_CIB_jk_data.npz\"),\n                        allow_pickle=True)\n\n        jk_resolutions = [64,]# 128, 256]\n\n        cov_CIB_shear = {c: {j: {\"TE\": None, \"TB\": None} for j in jk_resolutions}\n                        for c in CIB_maps}\n\n        ell = np.arange(3001)\n\n        for CIB_map in CIB_maps:\n            for jk_res in jk_resolutions:\n                d_CIB = []\n                for z_cut in z_cuts:\n                    tag = f\"z{z_cut[0]:.1f}-{z_cut[1]:.1f}-Planck-{CIB_map}\"\n                    Cl = CIB_jk_data[tag][str(jk_res)]\n                    binned = np.einsum(\"ij,kjl->lik\", binning_operator @ beam_operator, Cl)\n                    d_CIB.append(binned)\n\n                d = np.concatenate(d_CIB, axis=1)\n                print(d.shape)\n                n_jk = d.shape[-1]\n                effective_n_jk = n_jk\n\n                cov_CIB_shear[CIB_map][jk_res][\"TE\"] = (\n                    np.cov(d[0], ddof=1) * (effective_n_jk-1)**2/effective_n_jk)\n                cov_CIB_shear[CIB_map][jk_res][\"TB\"] = (\n                    np.cov(d[1], ddof=1) * (effective_n_jk-1)**2/effective_n_jk)\n\n        # Save files\n\n        header = file_header(\n                    f\"ell TE ({CIB_map} x KiDS-1000, beam {target_beam}' \"\n                    f\"FWHM, z-bins: {', '.join([str(z) for z in z_cuts])})\")\n\n        for CIB_map in CIB_maps:\n            data = [Cl_CIB_shear[z_cuts[0]][CIB_map][\"ell_binned\"]]\n            for z_cut in z_cuts:\n                data.append(Cl_CIB_shear[z_cut][CIB_map][\"Cl_TE_beam_binned\"])\n\n            np.savetxt(f\"../data/xcorr/CIB/\"\n                    f\"shear_CIB_KiDS1000_{CIB_map}_TE_beam{target_beam}.txt\",\n                    np.array(data).T,\n                    header=header)\n\n        header = file_header(\n                    f\"TE covariance ({CIB_map} x KiDS-1000, beam {target_beam}' \"\n                    f\"FWHM, z-bins: {', '.join([str(z) for z in z_cuts])})\")\n\n        for CIB_map in CIB_maps:\n            for name, cov in [(\"jk_3.4deg2\", cov_CIB_shear[CIB_map][64][\"TE\"]),\n                            #(\"jk_13.4deg2\", cov_CIB_shear[CIB_map][128][\"TE\"]),\n                            #(\"jk_53.7deg2\", cov_CIB_shear[CIB_map][256][\"TE\"])\n                            ]:\n                np.savetxt(\n                    f\"../data/xcorr/CIB/\"\n                    f\"shear_CIB_KiDS1000_{CIB_map}_TE_{name}\"\n                    f\"_beam{target_beam}_cov.txt\",\n                    cov,\n                    header=header)\n\n        CIB_map = \"545\"\n        ell_data = Cl_CIB_shear[z_cuts[0]][CIB_map][\"ell_binned\"]\n        data = []\n        for z_cut in z_cuts:\n            data.append(Cl_CIB_shear[z_cut][CIB_map][\"Cl_TE_beam_binned\"])\n        data = np.array(data).T\n\n        cov = cov_CIB_shear[CIB_map][64][\"TE\"]\n\n    check_GP = True\n    if check_GP:\n        # Normalize the CIB a bit\n        scaling_factor = 1e5 * ell_data**2/(2*np.pi)\n        Y = scaling_factor[:, None] * data\n        S = np.diag(np.tile(scaling_factor, Y.shape[1]))\n\n        Y_cov = S @ cov @ S\n        X = np.log10(ell_data)\n\n        CIB_model = CIBModel(X, Y, Y_cov)\n\n        # CIB_model.load_state(f\"../results/measurements/shear_KiDS1000_{field}/GP_model/GP_state\")\n        CIB_model.train(n_step=5000, lr=1e-2)\n        CIB_model.print_model_parameters()\n        print(\"Chi2:\", CIB_model.chi2())\n\n        CIB_model.save_state(f\"../results/measurements/shear_KiDS1000_{field}/GP_model/GP_state.torchstate\")\n\n        # ell_pred = np.geomspace(51, 3000, 100)\n        ell_pred = np.arange(51, 2953)\n        CIB_prediction, CI = CIB_model.predict(np.log10(ell_pred), CI=True)\n        # Undo normalisation to get Cl\n        CIB_prediction *= 1/(1e5 * ell_pred**2/(2*np.pi))[:, None]\n        CIB_prediction_CI_l = CI[0] * 1/(1e5 * ell_pred**2/(2*np.pi))[:, None]\n        CIB_prediction_CI_u = CI[1] * 1/(1e5 * ell_pred**2/(2*np.pi))[:, None]\n\n        n_ell, n_z = CIB_prediction.shape\n\n        if make_plots:\n            plot_Cls(Cls=[{\"X\": ell_data, \"Y\": data.T,\n                        \"Y_err\": np.sqrt(np.diag(cov)),\n                        \"marker\": \"o\", \"ls\": \"none\", \"c\": \"C0\",\n                        \"label\": label},\n                        {\"X\": ell_pred, \"Y\": CIB_prediction.T,\n                        \"Y_lower\": CIB_prediction_CI_l.T,\n                        \"Y_upper\": CIB_prediction_CI_u.T,\n                        \"alpha\": 0.5,  \"c\": \"C1\",\n                        \"label\": \"GP\"}],\n                    ylabel=r\"$\\ell^2/2\\pi\\ C_\\ell$ \" + units,\n                    title=f\"{label}, GP model\",\n                    filename=f\"../notebooks/plots/CIB_model_{field}_{probe}_beam10.png\")\n\n\n        if compute_prediction_for_cov:\n            ell_pred = np.arange(51, 2953)\n            CIB_prediction = CIB_model.predict(np.log10(ell_pred))\n            # Undo normalisation to get Cl\n            CIB_prediction *= 1/(1e5 * ell_pred**2/(2*np.pi))[:, None]\n\n            ell = np.arange(3*2048)\n            for i in range(n_z):\n                Cl = np.zeros((2, ell.size))\n                Cl[0, 51:2953] = CIB_prediction[:, i]\n\n                np.savez(f\"../results/measurements/shear_KiDS1000_{field}/cov_Cls/Cl_cov_GP_{i}-0.npz\", ell=ell, Cl_cov=Cl, Cl_noise_cov=np.zeros_like(Cl))\n", "meta": {"hexsha": "fd6267be0b1fef4881492e276278ba49430a978c", "size": 11645, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/reduce_CIB_data.py", "max_stars_repo_name": "tilmantroester/KiDS-1000xtSZ", "max_stars_repo_head_hexsha": "190f193d5d2fc514bcbe96ea15d882ea59c7a1cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-24T16:02:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T16:02:32.000Z", "max_issues_repo_path": "scripts/reduce_CIB_data.py", "max_issues_repo_name": "tilmantroester/KiDS-1000xtSZ", "max_issues_repo_head_hexsha": "190f193d5d2fc514bcbe96ea15d882ea59c7a1cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/reduce_CIB_data.py", "max_forks_repo_name": "tilmantroester/KiDS-1000xtSZ", "max_forks_repo_head_hexsha": "190f193d5d2fc514bcbe96ea15d882ea59c7a1cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0771812081, "max_line_length": 155, "alphanum_fraction": 0.4883641048, "include": true, "reason": "import numpy", "num_tokens": 3203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.19533598758092333}}
{"text": "'''\nInfers average ELBO values from DeepSequence VAE models.\nBased on open source code from DeepSequence repo.\n'''\nimport argparse\nimport numpy as np\nimport os\nimport pathlib\nfrom shutil import copyfile\nimport sys\nimport time\n\nimport utils\n\nWORKING_DIR=\"\" # Put in the DeepSequence directory here\nN_ELBO_SAMPLES=400\n\nmodule_path = os.path.abspath(WORKING_DIR)\nif module_path not in sys.path:\n        sys.path.append(module_path)\n\nfrom DeepSequence.model import VariationalAutoencoder\nfrom DeepSequence import helper\nfrom DeepSequence import train\n\nmodel_params = {\n    \"bs\"                :   100,\n    \"encode_dim_zero\"   :   1500,\n    \"encode_dim_one\"    :   1500,\n    \"decode_dim_zero\"   :   100,\n    \"decode_dim_one\"    :   500,\n    \"n_latent\"          :   30,\n    \"logit_p\"           :   0.001,\n    \"sparsity\"          :   \"logit\",\n    \"final_decode_nonlin\":  \"sigmoid\",\n    \"final_pwm_scale\"   :   True,\n    \"n_pat\"             :   4,\n    \"r_seed\"            :   12345,\n    \"conv_pat\"          :   True,\n    \"d_c_size\"          :   40\n}\n\n\ndef main():\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"model_prefix\", type=str)\n    parser.add_argument(\"fasta_file\", type=str)\n    parser.add_argument(\"wt_fasta_file\", type=str)\n    parser.add_argument(\"output_dir\", type=str)\n    args = parser.parse_args()\n    data_helper = helper.DataHelper(\n            working_dir=WORKING_DIR,\n            alignment_file=args.fasta_file,\n            calc_weights=False,\n    )\n\n    vae_model   = VariationalAutoencoder(data_helper,\n        batch_size                     =   model_params[\"bs\"],\n        encoder_architecture           =   [model_params[\"encode_dim_zero\"],\n                                                model_params[\"encode_dim_one\"]],\n        decoder_architecture           =   [model_params[\"decode_dim_zero\"],\n                                                model_params[\"decode_dim_one\"]],\n        n_latent                       =   model_params[\"n_latent\"],\n        logit_p                        =   model_params[\"logit_p\"],\n        sparsity                       =   model_params[\"sparsity\"],\n        encode_nonlinearity_type       =   \"relu\",\n        decode_nonlinearity_type       =   \"relu\",\n        final_decode_nonlinearity      =   model_params[\"final_decode_nonlin\"],\n        final_pwm_scale                =   model_params[\"final_pwm_scale\"],\n        conv_decoder_size              =   model_params[\"d_c_size\"],\n        convolve_patterns              =   model_params[\"conv_pat\"],\n        n_patterns                     =   model_params[\"n_pat\"],\n        random_seed                    =   model_params[\"r_seed\"],\n        working_dir                    =   WORKING_DIR,\n        )\n    vae_model.load_parameters(args.model_prefix)\n\n    pathlib.Path(args.output_dir).mkdir(parents=True, exist_ok=True)\n\n    focuscols = set(data_helper.uniprot_focus_cols_list)\n\n    seqs = utils.read_fasta(os.path.join(WORKING_DIR, \"datasets\",\n        args.fasta_file))\n    wt, des = utils.read_fasta(args.wt_fasta_file, return_ids=True)\n    wt = wt[0]\n    des = des[0]\n    offset = int(des.split('/')[-1].split('-')[0])\n    delta_elbos = np.zeros(len(seqs))\n    for i, s in enumerate(seqs):\n        if i % 100 == 0:\n            print(f'Computed elbos for {i} out of {len(seqs)} seqs')\n            np.savetxt(os.path.join(args.output_dir, \"elbo.npy\"), delta_elbos)\n        mut_tups = utils.seq2mutation_fromwt(s, wt, offset=offset)\n        mut_tups = [t for t in mut_tups if t[0] in focuscols]\n        delta_elbos[i] = data_helper.delta_elbo(vae_model, mut_tups,\n                N_pred_iterations=N_ELBO_SAMPLES) \n    np.savetxt(os.path.join(args.output_dir, \"elbo.npy\"), delta_elbos)\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "99bab3753dc24bfa53cb00cbf9c4ca5fed88b2c9", "size": 3739, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/vae_inference.py", "max_stars_repo_name": "brycejoh16/combining-evolutionary-and-assay-labelled-data", "max_stars_repo_head_hexsha": "36ffcf10ad6eacf5d44c81d69f0bc6f7f9cae73b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2022-01-19T02:39:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T21:55:29.000Z", "max_issues_repo_path": "src/vae_inference.py", "max_issues_repo_name": "brycejoh16/combining-evolutionary-and-assay-labelled-data", "max_issues_repo_head_hexsha": "36ffcf10ad6eacf5d44c81d69f0bc6f7f9cae73b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-03-09T06:18:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T14:55:59.000Z", "max_forks_repo_path": "src/vae_inference.py", "max_forks_repo_name": "brycejoh16/combining-evolutionary-and-assay-labelled-data", "max_forks_repo_head_hexsha": "36ffcf10ad6eacf5d44c81d69f0bc6f7f9cae73b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2022-01-22T07:27:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T23:23:17.000Z", "avg_line_length": 36.6568627451, "max_line_length": 80, "alphanum_fraction": 0.5916020326, "include": true, "reason": "import numpy", "num_tokens": 896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.19533597995602867}}
{"text": "from __future__ import print_function\n\n\"\"\"\nThe main class in this module `ElasticScatter` holds the experimental details,\nand processor information needed to calculate the elastic powder scattering\nfrom a collection of atoms.\n\"\"\"\nimport math\nimport numpy as np\nfrom numba import cuda\nfrom pyiid.experiments.elasticscatter.cpu_wrappers.nxn_cpu_wrap import \\\n    wrap_fq_grad as cpu_wrap_fq_grad, wrap_fq as cpu_wrap_fq\nfrom pyiid.experiments.elasticscatter.kernels.master_kernel import \\\n    grad_pdf as cpu_grad_pdf, get_pdf_at_qmin, get_scatter_array\nfrom scipy.interpolate import griddata\n\n__author__ = 'christopher'\n\nall_changes = ['positions', 'numbers', 'cell', 'pbc', 'charges', 'magmoms',\n               'exp']\n\n\ndef check_mpi():\n    # Test if MPI GPU is viable\n    # Currently no working MPI GPU implementation\n    return False\n\n\ndef check_gpu():\n    \"\"\"\n    Check if GPUs are available on this machine\n    \"\"\"\n    try:\n        cuda.gpus.lst\n        tf = True\n    except cuda.CudaSupportError:\n        tf = False\n    return tf\n\n\ndef check_cudafft():\n    try:\n        from accelerate.cudalib import cufft\n        tf = True\n    except ImportError:\n        tf = False\n        print('no cudafft')\n        cufft = None\n    return tf\n\n\nclass ElasticScatter(object):\n    \"\"\"\n    Scatter contains all the methods associated with producing theoretical\n    diffraction patterns and PDFs from atomic configurations.  It does not\n    include potential energies, such as Rw and chi**2 which are under the\n    Calculator object.\n    >>>from ase.atoms import Atoms\n    >>>import matplotlib.pyplot as plt\n    >>>atoms = Atoms('Au4', [[0, 0, 0], [3, 0, 0], [0, 3, 0], [3, 3, 0]])\n    >>>a = np.random.random(atoms.positions.shape) * .1\n    >>>s = ElasticScatter({'rmax': 5., 'rmin': 2.})\n    >>>fq = s.get_pdf(atoms)\n    >>>fq2 = s.get_pdf(atoms)\n    >>>plt.plot(s.get_r(), fq)\n    >>>plt.show()\n\n    \"\"\"\n\n    def __init__(self, exp_dict=None, verbose=False, seed=None):\n        self.verbose = verbose\n        self.wrap_atoms_state = None\n        if seed is None:\n            self.seed = int(np.random.random() * 2 ** 32)\n        elif isinstance(seed, int):\n            self.seed = seed\n        else:\n            raise ValueError('Expected an integer!')\n        self.rs = np.random.RandomState(self.seed)\n\n        # Currently supported processor architectures, in order of most\n        # advanced to least\n        self.avail_pro = ['MPI-GPU', 'Multi-GPU', 'CPU']\n\n        # needed parameters to specify an experiment\n        self.exp_dict_keys = ['qmin', 'qmax', 'qbin', 'rmin', 'rmax', 'rstep',\n                              'sampling']\n        # default experimental parameters\n        self.default_values = [0.0, 25, .1, 0.0, 40.0, .01, 'full']\n        # Initiate the algorithm, processor, and experiments\n        self.alg = None\n        self.processor = None\n        self.exp = None\n        self.pdf_qbin = None\n\n        # set the experimental parameters\n        self.update_experiment(exp_dict)\n\n        # Just in case something blows up down the line set to the most base\n        # processor\n        self.fq = cpu_wrap_fq\n        self.grad = cpu_wrap_fq_grad\n        self.grad_pdf = cpu_grad_pdf\n        self.processor = 'CPU'\n        self.alg = 'nxn'\n\n        # Get the fastest processor architecture available\n        self.set_processor()\n\n    def _wrap_atoms(self, atoms):\n        \"\"\"\n        Call this function before applying calculator, it will generate static\n        arrays for the scattering, preventing recalculation\n    \n        Parameters\n        -----------\n        atoms: ase.Atoms\n            The atoms to which scatter factors are added\n        \"\"\"\n        if 'qbin' not in self.exp.keys():\n            self.exp['qbin'] = .1\n        n = len(atoms)\n        e_num = atoms.get_atomic_numbers()\n        e_set = set(e_num)\n        e_list = list(e_set)\n\n        for qbin, name in zip(\n                [self.exp['qbin'],\n                 self.pdf_qbin],\n                ['F(Q) scatter', 'PDF scatter']\n        ):\n            qmax_bin = int(math.floor(self.exp['qmax'] / qbin))\n            set_scatter_array = np.zeros((len(e_set), qmax_bin),\n                                         dtype=np.float32)\n\n            # Calculate the element-wise scatter factor array\n            get_scatter_array(set_scatter_array, e_num, self.exp['qbin'])\n            scatter_array = np.zeros((n, qmax_bin), dtype=np.float32)\n\n            # Disseminate the element wise scatter factors\n            for i in range(len(e_set)):\n                scatter_array[np.where(atoms.numbers == e_list[i])[0], :] = \\\n                    set_scatter_array[i, :]\n\n            # Set the new scatter factor array\n            if name in atoms.arrays.keys():\n                del atoms.arrays[name]\n            atoms.set_array(name, scatter_array)\n\n        atoms.info['exp'] = self.exp\n        atoms.info['scatter_atoms'] = n\n\n    def _check_wrap_atoms_state(self, atoms):\n        \"\"\"\n        Check if we need to recalculate the atomic scatter factors\n        Parameters\n        ----------\n        atoms: ase.Atoms\n            The atomic configuration\n\n        Returns\n        -------\n\n        \"\"\"\n        t_value = True\n        if self.wrap_atoms_state is None:\n            t_value = False\n        elif 'F(Q) scatter' not in atoms.arrays.keys():\n            t_value = False\n        elif atoms.info['exp'] != self.exp or atoms.info[\n            'scatter_atoms'] != len(atoms):\n            t_value = False\n        if not t_value:\n            if self.verbose:\n                print('calculating new scatter factors')\n            self._wrap_atoms(atoms)\n            self.wrap_atoms_state = atoms\n        return t_value\n\n    def update_experiment(self, exp_dict):\n        \"\"\"\n        Change the scattering experiment parameters.\n\n        Parameters\n        ----------\n        exp_dict: dict or None\n            Dictionary of parameters to be updated, if None use defaults\n        \"\"\"\n        # Should be read in from the gr file, but if not here are some defaults\n        if exp_dict is None or bool(exp_dict) is False:\n            exp_dict = {}\n        for key, dv in zip(self.exp_dict_keys, self.default_values):\n            if key not in exp_dict.keys():\n                exp_dict[key] = dv\n\n        # If sampling is ns then generate the PDF at\n        # the Nyquist Shannon Sampling Frequency\n        if exp_dict['sampling'] == 'ns':\n            exp_dict['rstep'] = np.pi / exp_dict['qmax']\n\n        self.exp = exp_dict\n        # Technically we should use this for qbin\n        self.pdf_qbin = np.pi / (self.exp['rmax'] + 6 * 2 * np.pi /\n                                 self.exp['qmax'])\n\n    def set_processor(self, processor=None, kernel_type='flat'):\n        \"\"\"\n        Set the processor to use for calculating the scattering.  If no\n        parameter is given then check for the fastest possible processor\n        configuration\n\n        Parameters\n        -----------\n        processor: ['MPI-GPU', 'Multi-GPU', 'Serial-CPU']\n            The processor to use\n        kernel_type: ['nxn', 'flat-serial', 'flat']\n            The type of algorithm to use\n\n        Returns\n        -------\n        bool:\n            True on successful setup of the algorithm and processor\n        \"\"\"\n        # If a processor is given try to use that processor,\n        # but check if it is viable first.\n\n        # Changing the processor invalidates the previous results\n        if processor is None:\n            # Test each processor in order of most advanced to least\n            for pro in self.avail_pro:\n                if self.set_processor(\n                        processor=pro, kernel_type=kernel_type) is not None:\n                    break\n\n        elif processor == self.avail_pro[0] and check_mpi() is True:\n            from pyiid.experiments.elasticscatter.mpi_wrappers.mpi_gpu_wrap \\\n                import \\\n                wrap_fq as multi_node_gpu_wrap_fq\n            from pyiid.experiments.elasticscatter.mpi_wrappers.mpi_gpu_wrap \\\n                import \\\n                wrap_fq_grad as multi_node_gpu_wrap_fq_grad\n\n            self.fq = multi_node_gpu_wrap_fq\n            self.grad = multi_node_gpu_wrap_fq_grad\n            self.processor = processor\n            return True\n\n        elif processor == self.avail_pro[1] and check_gpu() is True:\n            from pyiid.experiments.elasticscatter.gpu_wrappers.gpu_wrap import \\\n                wrap_fq as flat_fq\n            from pyiid.experiments.elasticscatter.gpu_wrappers.gpu_wrap import \\\n                wrap_fq_grad as flat_grad\n\n            self.fq = flat_fq\n            self.grad = flat_grad\n            self.alg = 'flat'\n            if check_cudafft():\n                from pyiid.experiments.elasticscatter.gpu_wrappers.gpu_wrap import \\\n                    grad_pdf\n                self.grad_pdf = grad_pdf\n            else:\n                self.grad_pdf = cpu_grad_pdf\n            self.processor = processor\n            return True\n\n        elif processor == self.avail_pro[2]:\n            if kernel_type == 'nxn':\n                self.fq = cpu_wrap_fq\n                self.grad = cpu_wrap_fq_grad\n                self.alg = 'nxn'\n\n            elif kernel_type == 'flat':\n                from pyiid.experiments.elasticscatter.cpu_wrappers \\\n                    .flat_multi_cpu_wrap import \\\n                    wrap_fq, wrap_fq_grad\n\n                self.fq = wrap_fq\n                self.grad = wrap_fq_grad\n                self.alg = 'flat'\n\n            elif kernel_type == 'flat-serial':\n                from pyiid.experiments.elasticscatter.cpu_wrappers \\\n                    .flat_serial_cpu_wrap import \\\n                    wrap_fq, wrap_fq_grad\n\n                self.fq = wrap_fq\n                self.grad = wrap_fq_grad\n                self.alg = 'flat-serial'\n\n            self.grad_pdf = cpu_grad_pdf\n            self.processor = processor\n            return True\n\n    def check_wrap_atoms_state(self, atoms):\n        if self.wrap_atoms_state is None:\n            return False\n        if 'F(Q) scatter' not in atoms.arrays.keys():\n            return False\n        if atoms.info['exp'] != self.exp or \\\n                        atoms.info['scatter_atoms'] != len(atoms):\n            return False\n        return True\n\n    def get_fq(self, atoms, iq_std=None, noise_distribution=None):\n        \"\"\"\n        Calculate the reduced structure factor F(Q)\n\n        Parameters\n        ----------\n        atoms: ase.Atoms\n            The atomic configuration for which to calculate F(Q)\n        iq_std: {None, float, ndarray}, optional\n            Add noise to the data, if `noise` is a float then assume flat\n            gaussian noise with a standard deviation of noise, if an array\n            then assume that each point has a gaussian distribution of noise\n            with a standard deviation given by noise. Note that this noise is\n            noise in I(Q) which is propagated to F(Q)\n        noise_distribution: distribution function\n            The distribution function to take the scattering pattern\n\n        Returns\n        -------\n        1darray:\n            The reduced structure factor\n        \"\"\"\n        if self.check_wrap_atoms_state(atoms) is False:\n            if self.verbose:\n                print('calculating new scatter factors')\n            self._wrap_atoms(atoms)\n            self.wrap_atoms_state = atoms\n        fq = self.fq(atoms, self.exp['qbin'])\n        fq = fq[int(np.floor(self.exp['qmin'] / self.exp['qbin'])):]\n        if iq_std is not None:\n            fq_std = iq_std * np.abs(self.get_scatter_vector()) / np.abs(\n                np.average(atoms.get_array('F(Q) scatter'), axis=0) ** 2)[int(\n                np.floor(self.exp['qmin'] / self.exp['qbin'])):]\n            if fq_std[0] == 0.0:\n                fq_std[0] += 1e-9  # added because we can't have zero noise\n            exp_noise = self.rs.normal(0, fq_std)\n            fq += exp_noise\n        return fq\n\n    def get_pdf(self, atoms, iq_std=None, noise_distribution=np.random.normal):\n        \"\"\"\n        Calculate the atomic pair distribution factor, PDF, G(r)\n\n        Parameters\n        ----------\n        atoms: ase.Atoms\n            The atomic configuration for which to calculate the PDF\n        iq_std: {None, float, ndarray}, optional\n            Add noise to the data, if `noise` is a float then assume flat\n            gaussian noise with a standard deviation of noise, if an array\n            then assume that each point has a gaussian distribution of noise\n            with a standard deviation given by noise. Note that this noise is\n            noise in I(Q) which is propagated to F(Q)\n        noise_distribution: distribution function\n            The distribution function to take the scattering pattern\n\n        Returns\n        -------\n        1darray:\n            The PDF\n        \"\"\"\n        if self.check_wrap_atoms_state(atoms) is False:\n            if self.verbose:\n                print('calculating new scatter factors')\n            self._wrap_atoms(atoms)\n            self.wrap_atoms_state = atoms\n        fq = self.fq(atoms, self.pdf_qbin, 'PDF')\n        if iq_std is not None:\n            a = np.abs(self.get_scatter_vector(pdf=True))\n            b = np.abs(np.average(atoms.get_array('PDF scatter') ** 2, axis=0))\n            if hasattr(iq_std, 'shape') and iq_std.shape != a.shape:\n                iq_std = griddata(np.arange(0, iq_std.shape), iq_std,\n                                  np.arange(\n                                      a.shape))\n            fq_noise = iq_std * a / b\n            if fq_noise[0] == 0.0:\n                fq_noise[0] += 1e-9  # added because we can't have zero noise\n            exp_noise = self.rs.normal(0, fq_noise)\n            fq += exp_noise\n        r = self.get_r()\n        pdf0 = get_pdf_at_qmin(\n            fq,\n            self.exp['rstep'],\n            self.pdf_qbin,\n            r,\n            self.exp['qmin']\n        )\n        return pdf0\n\n    def get_sq(self, atoms, iq_std=None, noise_distribution=np.random.normal):\n        \"\"\"\n        Calculate the structure factor S(Q)\n\n        Parameters\n        ----------\n        atoms: ase.Atoms\n            The atomic configuration for which to calculate S(Q)\n        iq_std: {None, float, ndarray}, optional\n            Add noise to the data, if `noise` is a float then assume flat\n            gaussian noise with a standard deviation of noise, if an array\n            then assume that each point has a gaussian distribution of noise\n            with a standard deviation given by noise. Note that this noise is\n            noise in I(Q) which is propagated to F(Q)\n        noise_distribution: distribution function\n            The distribution function to take the scattering pattern\n        Returns\n        -------\n        1darray:\n            The structure factor\n        \"\"\"\n        fq = self.get_fq(atoms, iq_std, noise_distribution)\n        old_settings = np.seterr(all='ignore')\n        sq = (fq / self.get_scatter_vector()) + np.ones(\n            self.get_scatter_vector().shape)\n        np.seterr(**old_settings)\n        sq[np.isinf(sq)] = 0.\n        return sq\n\n    def get_iq(self, atoms, iq_std=None, noise_distribution=np.random.normal):\n        \"\"\"\n        Calculate the scattering intensity, I(Q)\n\n        Parameters\n        ----------\n        atoms: ase.Atoms\n            The atomic configuration for which to calculate I(Q)\n        iq_std: {None, float, ndarray}, optional\n            Add noise to the data, if `noise` is a float then assume flat\n            gaussian noise with a standard deviation of noise, if an array\n            then assume that each point has a gaussian distribution of noise\n            with a standard deviation given by noise. Note that this noise is\n            noise in I(Q) which is propagated to F(Q)\n        noise_distribution: distribution function\n            The distribution function to take the scattering pattern\n        Returns\n        -------\n        1darray:\n            The scattering intensity\n        \"\"\"\n        sq = self.get_sq(atoms, iq_std, noise_distribution)\n        f2 = np.average(atoms.get_array('F(Q) scatter'), axis=0) ** 2\n        iq = sq * f2[int(np.floor(self.exp['qmin'] / self.exp['qbin'])):]\n        return iq\n\n    def get_2d_scatter(self, atoms, pixel_array):\n        \"\"\"\n        Calculate the scattering intensity as projected onto a detector\n\n        Parameters\n        ----------\n        atoms: ase.Atoms\n            The atomic configuration for which to calculate I(Q)\n        pixel_array: 2darray\n            A map from Q to the xy coordinates of the detector, each element\n            has a Q value\n        Returns\n        -------\n        2darray:\n            The scattering intensity on the detector\n        \"\"\"\n\n        iq = self.get_iq(atoms)\n        s = self.get_scatter_vector()\n        qb = self.exp['qbin']\n        final_shape = pixel_array.shape\n        fp = pixel_array.ravel()\n        img = np.zeros(fp.shape)\n        for sub_s, i in zip(s, iq):\n            c = np.intersect1d(np.where(sub_s - qb / 2. < fp)[0],\n                               np.where(sub_s + qb / 2. > fp)[0])\n            img[c] = i\n        return img.reshape(final_shape)\n\n    def get_grad_fq(self, atoms):\n        \"\"\"\n        Calculate the gradient of the reduced structure factor F(Q)\n\n        Parameters\n        ----------\n        atoms: ase.Atoms\n            The atomic configuration for which to calculate grad F(Q)\n        Returns\n        -------\n        3darray:\n            The gradient of the reduced structure factor\n        \"\"\"\n        if self.check_wrap_atoms_state(atoms) is False:\n            if self.verbose:\n                print('calculating new scatter factors')\n            self._wrap_atoms(atoms)\n            self.wrap_atoms_state = atoms\n        g = self.grad(atoms, self.exp['qbin'])\n        return g[:, :, int(np.floor(self.exp['qmin'] / self.exp['qbin'])):]\n\n    def get_grad_pdf(self, atoms):\n        \"\"\"\n        Calculate the gradient of the PDF\n\n        Parameters\n        ----------\n        atoms: ase.Atoms\n            The atomic configuration for which to calculate grad PDF\n        Returns\n        -------\n        3darray:\n            The gradient of the PDF\n        \"\"\"\n        if self.check_wrap_atoms_state(atoms) is False:\n            if self.verbose:\n                print('calculating new scatter factors')\n            self._wrap_atoms(atoms)\n            self.wrap_atoms_state = atoms\n        fq_grad = self.grad(atoms, self.pdf_qbin, 'PDF')\n        qmin_bin = int(self.exp['qmin'] / self.pdf_qbin)\n        fq_grad[:, :, :qmin_bin] = 0.\n        rgrid = self.get_r()\n\n        pdf_grad = self.grad_pdf(fq_grad, self.exp['rstep'], self.pdf_qbin,\n                                 rgrid,\n                                 self.exp['qmin'])\n        return pdf_grad\n\n    def get_scatter_vector(self, pdf=False):\n        \"\"\"\n        Calculate the scatter vector Q for the current experiment\n\n        Parameters\n        ----------\n        pdf: bool\n            If true return the PDF rendering scatter vector\n\n        Returns\n        -------\n        1darray:\n            The Q range for this experiment\n        \"\"\"\n        if pdf:\n            return np.arange(0.,\n                             math.floor(self.exp['qmax'] / self.pdf_qbin) *\n                             self.pdf_qbin, self.pdf_qbin)\n        return np.arange(self.exp['qmin'], math.floor(self.exp['qmax'] /\n                                                      self.exp['qbin']) *\n                         self.exp['qbin'],\n                         self.exp['qbin'])\n\n    def get_r(self):\n        \"\"\"\n        Calculate the inter-atomic distance range for the current experiment\n\n        Returns\n        -------\n        1darray:\n            The r range for this experiment\n        \"\"\"\n        return np.arange(self.exp['rmin'], self.exp['rmax'], self.exp['rstep'])\n", "meta": {"hexsha": "5e8c4a55fc46e1804dd4043f19fdcc28205dd5f8", "size": 19868, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyiid/experiments/elasticscatter/__init__.py", "max_stars_repo_name": "ZhouHUB/pyIID", "max_stars_repo_head_hexsha": "6114fb5ae4388061c7aae9f5b0b2e41aa4ca4341", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyiid/experiments/elasticscatter/__init__.py", "max_issues_repo_name": "ZhouHUB/pyIID", "max_issues_repo_head_hexsha": "6114fb5ae4388061c7aae9f5b0b2e41aa4ca4341", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2016-04-25T18:36:42.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-12T20:57:35.000Z", "max_forks_repo_path": "pyiid/experiments/elasticscatter/__init__.py", "max_forks_repo_name": "ZhouHUB/pyIID", "max_forks_repo_head_hexsha": "6114fb5ae4388061c7aae9f5b0b2e41aa4ca4341", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.542039356, "max_line_length": 84, "alphanum_fraction": 0.5628145762, "include": true, "reason": "import numpy,from scipy,from numba", "num_tokens": 4412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.19533596727831776}}
{"text": "import numpy as np\nimport scipy\nimport os\nimport sys\nimport re\nimport dis\nimport hashlib\nimport glob\nimport importlib\nimport inspect\nimport shutil\nimport numbers\nfrom contextlib import contextmanager\nfrom collections import defaultdict\nfrom setuptools import setup, Extension\ntry:\n    from Cython.Build import cythonize\nexcept ImportError:\n    pass\nfrom warnings import warn\n\nfrom ..settings import settings as qset\nfrom ..optionsclass import optionsclass\nfrom .data import Data\nfrom .interpolate import Cubic_Spline\nfrom .cy.coefficient import (InterpolateCoefficient, InterCoefficient,\n                             StepCoefficient, FunctionCoefficient,\n                             ConjCoefficient, NormCoefficient,\n                             ShiftCoefficient, StrFunctionCoefficient,\n                             Coefficient)\n\n\n__all__ = [\"coefficient\", \"CompilationOptions\", \"Coefficient\",\n           \"clean_compiled_coefficient\"]\n\n\nclass StringParsingWarning(Warning):\n    pass\n\n\ndef coefficient(base, *, tlist=None, args={}, args_ctypes={},\n                _stepInterpolation=False, compile_opt=None,\n                function_style=None):\n    \"\"\"Coefficient for time dependent systems.\n\n    The coefficients are either a function, a string or a numpy array.\n\n    For function based coefficients, the function signature must be either:\n\n    * ``f(t, ...)`` where the other arguments are supplied as ordinary\n      \"pythonic\" arguments (e.g. ``f(t, w, a=5))\n    * ``f(t, args)`` where the arguments are supplied in a \"dict\" named\n      ``args``\n\n    By default the signature style is controlled by the\n    ``qutip.settings.core[\"function_coefficient_style\"]`` setting, but it\n    may be overriden here by specifying either ``function_style=\"pythonic\"``\n    or ``function_style=\"dict\"``.\n\n    *Examples*\n        # pythonic style function signature\n\n        def f1_t(t, w):\n            return np.exp(-1j * t * w)\n\n        coeff1 = coefficient(f1_t, args={\"w\": 1.})\n\n        # dict style function signature\n\n        def f2_t(t, args):\n            return np.exp(-1j * t * args[\"w\"])\n\n        coeff2 = coefficient(f2_t, args={\"w\": 1.})\n\n    For string based coeffients, the string must be a compilable python code\n    resulting in a complex. The following symbols are defined:\n        sin cos tan asin acos atan pi\n        sinh cosh tanh asinh acosh atanh\n        exp log log10 erf zerf sqrt\n        real imag conj abs norm arg proj\n        numpy as np,\n        scipy.special as spe (python interface)\n        and cython_special (cython interface)\n        [https://docs.scipy.org/doc/scipy/reference/special.cython_special.html].\n\n    *Examples*\n        coeff = coefficient('exp(-1j*w1*t)', args={\"w1\":1.})\n    'args' is needed for string coefficient at compilation.\n    It is a dict of (name:object). The keys must be a valid variables string.\n\n    Compilation options can be passed as \"compile_opt=CompilationOptions(...)\".\n\n    For numpy array format, the array must be an 1d of dtype float or complex.\n    A list of times (float64) at which the coeffients must be given (tlist).\n    The coeffients array must have the same len as the tlist.\n    The time of the tlist do not need to be equidistant, but must be sorted.\n    By default, a cubic spline interpolation will be used for the coefficient\n    at time t.\n    If the coefficients are to be treated as step function, use the arguments:\n    _stepInterpolation=True\n\n    *Examples*\n        tlist = np.logspace(-5,0,100)\n        H = QobjEvo(np.exp(-1j*tlist), tlist=tlist)\n    \"\"\"\n    if isinstance(base, Coefficient):\n        return base\n\n    if isinstance(base, Cubic_Spline):\n        return InterpolateCoefficient(base)\n\n    elif isinstance(base, np.ndarray):\n        if len(base.shape) != 1:\n            raise ValueError(\"The array to interpolate must be a 1D array\")\n        if base.shape != tlist.shape:\n            raise ValueError(\"tlist must be the same len \"\n                             \"as the array to interpolate\")\n        base = base.astype(np.complex128)\n        tlist = tlist.astype(np.float64)\n        if not _stepInterpolation:\n            return InterCoefficient(base, tlist)\n        else:\n            return StepCoefficient(base, tlist)\n\n    elif isinstance(base, str):\n        if compile_opt is None:\n            compile_opt = CompilationOptions()\n        return coeff_from_str(base, args, args_ctypes, compile_opt)\n\n    elif callable(base):\n        op = FunctionCoefficient(base, args.copy(), style=function_style)\n        if not isinstance(op(0), numbers.Number):\n            raise TypeError(\"The coefficient function must return a number\")\n        return op\n    else:\n        raise ValueError(\"coefficient format not understood\")\n\n\ndef norm(coeff):\n    \"\"\" return a Coefficient with is the norm: |c|^2.\n    \"\"\"\n    return NormCoefficient(coeff)\n\n\ndef conj(coeff):\n    \"\"\" return a Coefficient with is the conjugate.\n    \"\"\"\n    return ConjCoefficient(coeff)\n\n\ndef shift(coeff, _t0=0):\n    \"\"\" return a Coefficient in which t is shifted by _t0.\n    \"\"\"\n    return ShiftCoefficient(coeff, _t0)\n\n\n# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n# %%%%%%%%%      Everything under this is for string compilation      %%%%%%%%%\n# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n@optionsclass(\"compile\", qset.core)\nclass CompilationOptions:\n    \"\"\"\n    Options for compilation.\n    use_cython: bool\n        execute strings as python code instead of cython.\n\n    Type management options.\n    accept_int : None, bool\n        Whether integer constants and args are kept or upgraded to float\n        If `None`, use in if array subscrition is used.\n    accept_float : bool\n        Whether float are kept as float or upgraded to complex.\n    no_types : bool\n        Give up on detecting and using c types.\n    recompile : bool\n        Do not use previously made files but build a new one.\n    compiler_flags : str\n        Flags to pass to the compiler, ex: \"-Wall -O3\"...\n        Flags not matching your comiler and OS may cause compilation to fail.\n        Use \"recompile=True\", when trying to if the string pattern was\n        previously used.\n    link_flags : str\n        Libraries to link to pass to the compiler. They can not be used to add\n        function to the string coefficient.\n    extra_import : str\n        Cython code to add at the head of the file. Can be used to add extra\n        import or import c code etc. ex:\n        \"from scipy.linalg import det\"\n        \"from qutip.core.data import CSR\"\n    \"\"\"\n    try:\n        import cython\n        _use_cython = True\n    except ImportError:\n        _use_cython = False\n\n    _link_flags = \"\"\n    _compiler_flags = \"\"\n    if sys.platform == 'win32':\n        _compiler_flags = ''\n    elif sys.platform == 'darwin':\n        _compiler_flags = '-w -O3 -funroll-loops -mmacosx-version-min=10.9'\n        _link_flags += '-mmacosx-version-min=10.9'\n    else:\n        _compiler_flags = '-w -O3 -funroll-loops'\n\n    options = {\n        # use cython for compiling string coefficient\n        \"use_cython\": _use_cython,\n        # try to parse the string so qutip recognise similar string as one\n        # compiled coefficient:\n        # \"a*t\", \"a * t\", \"b*t\" would all use one compiled version\n        \"try_parse\": True,\n        # In compiled Coefficient, are int kept as int?\n        # None indicate to look for list subscription\n        \"accept_int\": None,\n        # In compiled Coefficient, are float considered as complex?\n        \"accept_float\": True,\n        # In compiled Coefficient, is static typing used?\n        # Result is faster, but can cause errors if subscription\n        # (a[1], b[\"a\"]) if used.\n        \"no_types\": False,\n        # Skip saved previously compiled files and force compilation\n        \"recompile\": False,\n        # Compilation flags and link flags to pass to the compiler\n        \"compiler_flags\": _compiler_flags,\n        \"link_flags\": _link_flags,\n        # Extra_header\n        \"extra_import\": \"\"\n    }\n\n\n# Version number of the Coefficient\nCOEFF_VERSION = \"1.1\"\n\n\ndef get_root():\n    \"\"\"\n    Find the location of the compiled coefficient and ensure they are in\n    the import path.\n    \"\"\"\n    # qset.install['tmproot'] can be changed by the user without updating\n    # PYTHONPATH. If optionsclass allows for property like options,\n    # the logic could be moved there\n    tmproot = qset.install['tmproot']\n    root = os.path.join(tmproot, 'qutip_coeffs_{}'.format(COEFF_VERSION))\n    if not os.path.exists(root):\n        os.mkdir(root)\n    if not os.access(root, os.W_OK):\n        root = \".\"\n    if root not in sys.path:\n        sys.path.insert(0, root)\n    return root\n\n\ndef clean_compiled_coefficient(all=False):\n    \"\"\"\n    Remove previouly compiled string Coefficient.\n\n    Parameter:\n    ----------\n    all: bool\n        If not `all` will remove only previous version.\n    \"\"\"\n    import glob\n    import shutil\n    tmproot = qset.install['tmproot']\n    root = os.path.join(tmproot, 'qutip_coeffs_{}'.format(COEFF_VERSION))\n    folders = glob.glob(os.path.join(tmproot, 'qutip_coeffs_') + \"*\")\n    for folder in folders:\n        if all or folder != root:\n            shutil.rmtree(folder)\n\n\n\ndef proj(x):\n    if np.isfinite(x):\n        return (x)\n    else:\n        return np.inf + 0j * np.imag(x)\n\n\nstr_env = {\n    \"sin\": np.sin,\n    \"cos\": np.cos,\n    \"tan\": np.tan,\n    \"asin\": np.arcsin,\n    \"acos\": np.arccos,\n    \"atan\": np.arctan,\n    \"pi\": np.pi,\n    \"sinh\": np.sinh,\n    \"cosh\": np.cosh,\n    \"tanh\": np.tanh,\n    \"asinh\": np.arcsinh,\n    \"acosh\": np.arccosh,\n    \"atanh\": np.arctanh,\n    \"exp\": np.exp,\n    \"log\": np.log,\n    \"log10\": np.log10,\n    \"erf\": scipy.special.erf,\n    \"zerf\": scipy.special.erf,\n    \"sqrt\": np.sqrt,\n    \"real\": np.real,\n    \"imag\": np.imag,\n    \"conj\": np.conj,\n    \"abs\": np.abs,\n    \"norm\": lambda x: np.abs(x)**2,\n    \"arg\": np.angle,\n    \"proj\": proj,\n    \"np\": np,\n    \"spe\": scipy.special}\n\n\ndef coeff_from_str(base, args, args_ctypes, compile_opt):\n    \"\"\"\n    Entry point for string based coefficients\n    - Test if the string is valid\n    - Parse: \"cos(a*t)\" and \"cos( w1 * t )\"\n        should be recognised as the same compiled object.\n    - Verify if already compiled and compile if not\n    \"\"\"\n    # First, a sanity check before thinking of compiling\n    if not compile_opt['extra_import']:\n        try:\n            env = {\"t\": 0}\n            env.update(args)\n            exec(base, str_env, env)\n        except Exception as err:\n            raise Exception(\"Invalid string coefficient\") from err\n    # Do we even compile?\n    if not compile_opt['use_cython']:\n        return StrFunctionCoefficient(base, args)\n    # Parsing tries to make the code in common pattern\n    parsed, variables, constants, raw = try_parse(base, args,\n                                                  args_ctypes, compile_opt)\n    # Once parsed, the code should be unique enough to get a filename\n    hash_ = hashlib.sha256(bytes(parsed, encoding='utf8'))\n    file_name = \"qtcoeff_\" + hash_.hexdigest()[:30]\n    # See if it already exist, if not write and cythonize it\n    coeff = try_import(file_name, parsed)\n    if coeff is None or compile_opt['recompile']:\n        code = make_cy_code(parsed, variables, constants,\n                            raw, compile_opt)\n        coeff = compile_code(code, file_name, parsed, compile_opt)\n    keys = [key for _, key, _ in variables]\n    const = [fromstr(val) for _, val, _ in constants]\n    return coeff(base, keys, const, args)\n\n\ndef try_import(file_name, parsed_in):\n    \"\"\" Import the compiled coefficient if existing and check for\n    name collision.\n    \"\"\"\n    get_root()\n    coeff = None\n    try:\n        mod = importlib.import_module(file_name)\n    except ModuleNotFoundError:\n        # Coefficient does not exist, to compile as file_name\n        return None\n\n    if mod.parsed_code == parsed_in:\n        # Coefficient found!\n        return mod.StrCoefficient\n    else:\n        raise ValueError(\"string hash collision, change the string \"\n                         \"or clean files in qutip.settings.install['tmproot']\")\n\n\ndef make_cy_code(code, variables, constants, raw, compile_opt):\n    \"\"\"\n    Generate the code for the string coefficients.\n    \"\"\"\n    cdef_cte = \"\"\n    init_cte = \"\"\n    copy_cte = \"\"\n    for i, (name, val, ctype) in enumerate(constants):\n        cdef_cte += \"        {} {}\\n\".format(ctype, name[5:])\n        copy_cte += \"        out.{} = {}\\n\".format(name[5:], name)\n        init_cte += \"        {} = cte[{}]\\n\".format(name, i)\n    cdef_var = \"\"\n    init_var = \"\"\n    init_arg = \"\"\n    replace_var = \"\"\n    call_var = \"\"\n    copy_var = \"\"\n    for i, (name, val, ctype) in enumerate(variables):\n        cdef_var += \"        str key{}\\n\".format(i)\n        cdef_var += \"        {} {}\\n\".format(ctype, name[5:])\n        copy_var += \"        out.key{} = self.key{}\\n\".format(i, i)\n        copy_var += \"        out.{} = {}\\n\".format(name[5:], name)\n        if not raw:\n            init_var += \"        self.key{} = var[{}]\\n\".format(i, i)\n        else:\n            init_var += \"        self.key{} = '{}'\\n\".format(i, val)\n        init_arg += \"        {} = args[self.key{}]\\n\".format(name, i)\n        replace_var += \"            if self.key{} in kwargs:\\n\".format(i)\n        replace_var += (\"                out.{}\"\n                        \" = kwargs[self.key{}]\\n\".format(name[5:], i))\n        if raw:\n            call_var += \"        cdef {} {} = {}\\n\".format(ctype, val, name)\n\n    code = f\"\"\"#cython: language_level=3\n# This file is generated automatically by QuTiP.\n\nimport numpy as np\nimport scipy.special as spe\nfrom scipy.special cimport cython_special\ncimport cython\nfrom qutip.core.cy.coefficient cimport Coefficient\nfrom qutip.core.cy.math cimport erf, zerf\nfrom qutip.core.cy.complex_math cimport *\nfrom qutip.core.data cimport Data\ncdef double pi = 3.14159265358979323\n{compile_opt['extra_import']}\n\nparsed_code = \"{code}\"\n\n@cython.auto_pickle(True)\ncdef class StrCoefficient(Coefficient):\n    \\\"\\\"\\\"\n    String compiled as a :obj:`Coefficient` using cython.\n    \\\"\\\"\\\"\n    cdef:\n        str codeString\n{cdef_cte}{cdef_var}\n\n    def __init__(self, base, var, cte, args):\n        self.codeString = base\n{init_cte}{init_var}{init_arg}\n\n    cpdef Coefficient copy(self):\n        \\\"\\\"\\\"Return a copy of the :obj:`Coefficient`.\\\"\\\"\\\"\n        cdef StrCoefficient out = StrCoefficient.__new__(StrCoefficient)\n        out.codeString = self.codeString\n{copy_cte}{copy_var}\n        return out\n\n    def replace_arguments(self, _args=None, **kwargs):\n        \\\"\\\"\\\"\n        Return a :obj:`Coefficient` with args changed for :obj:`Coefficient`\n        built from 'str' or a python function. Or a the :obj:`Coefficient`\n        itself if the :obj:`Coefficient` does not use arguments. New arguments\n        can be passed as a dict or as keywords.\n\n        Parameters\n        ----------\n        _args : dict\n            Dictionary of arguments to replace.\n\n        **kwargs\n            Arguments to replace.\n        \\\"\\\"\\\"\n        cdef StrCoefficient out\n\n        if _args:\n            kwargs.update(_args)\n        if kwargs:\n            out = self.copy()\n{replace_var}\n            return out\n        return self\n\n    @cython.initializedcheck(False)\n    @cython.cdivision(True)\n    cdef complex _call(self, double t) except *:\n{call_var}        return {code}\n\"\"\"\n    return code\n\n\ndef compile_code(code, file_name, parsed, c_opt):\n    pwd = os.getcwd()\n    root = get_root()\n    try:\n        os.chdir(root)\n        [os.remove(file) for file in glob.glob(file_name + \"*\")]\n        full_file_name = os.path.join(root, file_name)\n        file_ = open(full_file_name + \".pyx\", \"w\")\n        file_.writelines(code)\n        file_.close()\n        oldargs = sys.argv\n        try:\n            sys.argv = [\"setup.py\", \"build_ext\", \"--inplace\"]\n            coeff_file = Extension(file_name,\n                                   sources=[full_file_name + \".pyx\"],\n                                   extra_compile_args=c_opt['compiler_flags'].split(),\n                                   extra_link_args=c_opt['link_flags'].split(),\n                                   include_dirs=[np.get_include()],\n                                   language='c++')\n            setup(ext_modules=cythonize(coeff_file, force=c_opt['recompile']))\n        except Exception as e:\n            raise Exception(\"Could not compile\") from e\n        finally:\n            sys.argv = oldargs\n    finally:\n        os.chdir(pwd)\n    return try_import(file_name, parsed)\n\n\n# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n# %%%%%%%%%        Everything under this is for parsing string        %%%%%%%%%\n# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n# Parsing here is extracting constants and args name to replace them with\n# attribute of the Coefficient so similar string like:\n# \"2.*cos(a*t)\", \"5.2 * cos(w1 *t)\", \"5 * cos(w3 * t)\"\n# are all reconized as the same compiled object and only compiled once.\n# Weakness:\n#   typing: \"1\" and \"1j\" or the type of args (\"w1\") make different object\n#   complex: \"1+1j\" is seens as cte(double) + cte(complex)\n#   negative: \"-1\" is not seens as a constant but \"- constant\"\n#\n# int and double can be seens as complex with flags in CompilationOptions\n\ndef fromstr(base):\n    \"\"\"Read a varibles in a string\"\"\"\n    ls = {}\n    exec(\"out = \" + base, {}, ls)\n    return ls[\"out\"]\n\n\ntypeCodes = {\n    \"Data\": \"_datalayer\",\n    \"complex\": \"_cpl\",\n    \"double\": \"_dbl\",\n    \"int\": \"_int\",\n    \"str\": \"_str\",\n    \"object\": \"_obj\"\n}\n\n\ndef compileType(value):\n    \"\"\"Obtain the index of typeCodes that correspond to the value\n    4.5 -> 'double'...\"\"\"\n    if isinstance(value, Data):\n        ctype = \"Data\"\n    elif isinstance(value, numbers.Integral):\n        ctype = \"int\"\n    elif isinstance(value, numbers.Real):\n        ctype = \"double\"\n    elif isinstance(value, numbers.Complex):\n        ctype = \"complex\"\n    elif isinstance(value, str):\n        ctype = \"str\"\n    else:\n        ctype = \"object\"\n    return ctype\n\n\ndef find_type_from_str(chars):\n    \"\"\" '1j' -> complex \"\"\"\n    try:\n        lc = {}\n        exec(\"out = \" + chars, {}, lc)\n        return compileType(lc[\"out\"])\n    except Exception:\n        return None\n\n\ndef fix_type(ctype, accept_int, accept_float):\n    \"\"\"int and double could be complex to limit the number of compiled object.\n    change the types is we choose not to support all.\n    \"\"\"\n    if ctype == \"int\" and not accept_int:\n        ctype = \"double\"\n    if ctype == \"double\" and not accept_float:\n        ctype = \"complex\"\n    return ctype\n\n\ndef extract_constant(code):\n    \"\"\"Look for floating and complex constants and replace them with variable.\n    \"\"\"\n    code = \" \" + code + \" \"\n    contants = []\n    code = extract_cte_pattern(code, contants,\n                               \"[^0-9a-zA-Z_][0-9]*[.]?[0-9]+e[+-]?[0-9]*[j]?\")\n    code = extract_cte_pattern(code, contants,\n                               \"[^0-9a-zA-Z_][0-9]+[.]?[0-9]*e[+-]?[0-9]*[j]?\")\n    code = extract_cte_pattern(code, contants,\n                               \"[^0-9a-zA-Z_][0-9]+[.]?[0-9]*[j]?\")\n    code = extract_cte_pattern(code, contants,\n                               \"[^0-9a-zA-Z_][0-9]*[.]?[0-9]+[j]?\")\n    return code, contants\n\n\ndef extract_cte_pattern(code, constants, pattern):\n    \"\"\"replace the constant following a pattern with variable\"\"\"\n    const_strs = re.findall(pattern, code)\n    for cte in const_strs:\n        name = \" _cte_temp{}_ \".format(len(constants))\n        code = code.replace(cte, cte[0] + name, 1)\n        constants.append((name[1:-1], cte[1:], find_type_from_str(cte[1:])))\n    return code\n\n\ndef space_parts(code, names):\n    \"\"\"Force spacing: single space between element\"\"\"\n    for name in names:\n        code = re.sub(\"(?<=[^0-9a-zA-Z_])\" + name + \"(?=[^0-9a-zA-Z_])\",\n                      \" \" + name + \" \", code)\n    code = \" \".join(code.split())\n    return code\n\n\ndef parse(code, args, compile_opt):\n    \"\"\"\n    Read the code and rewrite it in a reutilisable form:\n    Ins:\n        '2.*cos(a*t)', {\"a\":5+1j}\n    Outs:\n        code = 'self._cte_dbl0 * cos ( self._arg_cpl0 * t )'\n        variables = [('self._arg_cpl0', 'a', 'complex')]\n        ordered_constants = [('self._cte_dbl0', 2, 'double')]\n    \"\"\"\n    code, constants = extract_constant(code)\n    names = re.findall(\"[0-9a-zA-Z_]+\", code)\n    code = space_parts(code, names)\n    constants_names = [const[0] for const in constants]\n    new_code = []\n    ordered_constants = []\n    variables = []\n    typeCounts = defaultdict(lambda: 0)\n    accept_int = compile_opt['accept_int']\n    accept_float = compile_opt['accept_float']\n    if accept_int is None:\n        # If there is a subscript: a[b] int are always accepted to be safe\n        # with TypeError\n        accept_int = \"SUBSCR\" in dis.Bytecode(code).dis()\n    for word in code.split():\n        if word not in names:\n            # syntax\n            new_code.append(word)\n        elif word in args:\n            # find first if the variable is use more than once and reuse\n            var_name = [var_name for var_name, name, _ in variables\n                        if word == name]\n            if var_name:\n                var_name = var_name[0]\n            else:\n                ctype = compileType(args[word])\n                ctype = fix_type(ctype, accept_int, accept_float)\n                var_name = (\"self._arg\" + typeCodes[ctype] +\n                            str(typeCounts[ctype]))\n                typeCounts[ctype] += 1\n                variables.append((var_name, word, ctype))\n            new_code.append(var_name)\n        elif word in constants_names:\n            name, val, ctype = constants[int(word[9:-1])]\n            ctype = fix_type(ctype, accept_int, accept_float)\n            cte_name = \"self._cte\" + typeCodes[ctype] +\\\n                       str(len(ordered_constants))\n            new_code.append(cte_name)\n            ordered_constants.append((cte_name, val, ctype))\n        else:\n            # Hopefully a buildin or known object\n            new_code.append(word)\n        code = \" \".join(new_code)\n    return code, variables, ordered_constants\n\n\ndef use_hinted_type(variables, code, args_ctypes):\n    variables_manually_typed = []\n    for i, (name, key, type_) in enumerate(variables):\n        if key in args_ctypes:\n            new_name = \"self._custom_\" + args_ctypes[key] + str(i)\n            code = code.replace(name, new_name)\n            variables_manually_typed.append((new_name, key, args_ctypes[key]))\n        else:\n            variables_manually_typed.append((name, key, type_))\n    return code, variables_manually_typed\n\n\ndef try_parse(code, args, args_ctypes, compile_opt):\n    \"\"\"\n    Try to parse and verify that the result is still usable.\n    \"\"\"\n    if not compile_opt['try_parse']:\n        variables = [(\"self.\" + name, name, \"object\") for name in args\n                     if name in code]\n        code, variables = use_hinted_type(variables, code, args_ctypes)\n        return code, variables, [], True\n    ncode, variables, constants = parse(code, args, compile_opt)\n    if compile_opt['no_types']:\n        # Fallback to all object\n        variables = [(f, s, \"object\") for f, s, _ in variables]\n        constants = [(f, s, \"object\") for f, s, _ in constants]\n    ncode, variables = use_hinted_type(variables, ncode, args_ctypes)\n    if (\n        (compile_opt['extra_import']\n        and not compile_opt['extra_import'].isspace())\n        or test_parsed(ncode, variables, constants, args)\n    ):\n        return ncode, variables, constants, False\n    else:\n        warn(\"Could not find c types\", StringParsingWarning)\n        remaped_variable = []\n        for _, name, ctype in variables:\n            remaped_variable.append((\"self.\" + name, name, \"object\"))\n        return code, remaped_variable, [], True\n\n\ndef test_parsed(code, variables, constants, args):\n    \"\"\"\n    Test if parsed code broke anything.\n    \"\"\"\n    class DummySelf:\n        pass\n    [setattr(DummySelf, cte[0][5:], fromstr(cte[1])) for cte in constants]\n    [setattr(DummySelf, var[0][5:], args[var[1]]) for var in variables]\n    loc_env = {\"t\": 0, 'self': DummySelf}\n    try:\n        exec(code, str_env, loc_env)\n    except Exception as e:\n        return False\n    return True\n", "meta": {"hexsha": "c3b49272b7aed7bc115b9ad7aed10cc4f2a47c3a", "size": 24305, "ext": "py", "lang": "Python", "max_stars_repo_path": "qutip/core/coefficient.py", "max_stars_repo_name": "jakelishman/qutip", "max_stars_repo_head_hexsha": "fbb7fad5bc205910228db622d90601c82db45e4b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "qutip/core/coefficient.py", "max_issues_repo_name": "jakelishman/qutip", "max_issues_repo_head_hexsha": "fbb7fad5bc205910228db622d90601c82db45e4b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-07-13T12:11:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-09T22:45:05.000Z", "max_forks_repo_path": "qutip/core/coefficient.py", "max_forks_repo_name": "jakelishman/qutip", "max_forks_repo_head_hexsha": "fbb7fad5bc205910228db622d90601c82db45e4b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8981868898, "max_line_length": 86, "alphanum_fraction": 0.5957210451, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 5942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.19533596727831776}}
{"text": "import sys\nsys.path.append('.') #get rid of this at some point with central test script or when package is built\nimport os\nos.chdir('C:\\\\Users\\\\Skoron\\\\Desktop')\nimport MSI.simulations.instruments.flames as f\nimport MSI.cti_core.cti_processor as pr\nimport cantera as ct\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n\ntest_p=pr.Processor('C:\\\\Users\\\\Skoron\\\\Google Drive\\\\Burke Group\\\\Codes\\\\Mechanisms\\\\FFCM-1\\\\FFCM1.cti')\nf1 = f.flamespeed_multi_condition(pressures=[1.00],\n                         temperatures=[298.0],\n                         kineticSens=1,\n\t\t\t\t\t\t physicalSens=0,\n                         conditions=[{'H2':0.5,'O2':0.5,'He':4.0},\n                                     {'H2':0.75,'O2':0.5,'He':4.0},\n                                     {'H2':1.0,'O2':0.5,'He':4.0},\n                                     {'H2':1.25,'O2':0.5,'He':4.0},\n                                     {'H2':1.5,'O2':0.5,'He':4.0},\n                                     {'H2':1.75,'O2':0.5,'He':4.0},\n                                     {'H2':2.0,'O2':0.5,'He':4.0},\n                                     {'H2':2.25,'O2':0.5,'He':4.0},\n                                     {'H2':2.5,'O2':0.5,'He':4.0}],\n                         thermalBoundary='Adiabatic'                         ,\n                         processor=test_p,\n                         save_physSensHistories=0,save_timeHistories=1,loglevel=0)\t\t\t\t\t\t \nsolution,ksens=f1.run()\nmethane_profile=[]\n#for i in jsr1.JSR_objects:\n#\tprint(i.pressure,i.temperature,i.conditions)\n#\tprint(i.solution['ch4'],i.reactorPressure)\n#for i in range(len(jsr1.JSR_objects)):\n#\tmethane_profile.append(jsr1.JSR_objects[i].solution['ch4'])\n\n\t\n#plt.plot(np.linspace(858,1258,25),methane_profile)\n#plt.savefig('C:\\\\Users\\\\HP USER\\\\Google Drive\\\\Burke Group\\\\Mark\\\\MSI\\\\data\\\\jsr_test\\\\methane.pdf',\n#\t\t\t\tdpi=1200, bbox_inches='tight')\n#print(solution['ch4'])\n#print(ksen\nplt.figure()\nplt.plot(solution['H2'],solution['u0'],'k-')\nplt.xlabel('Equivalence Ratio')\nplt.ylabel('Flame Speed (m/s)')\nplt.title('H2/O2/He Flame speed, O2/(O2+He)=0.125')\n\n\n", "meta": {"hexsha": "f8cb806c22ec38f741646fa313bbcd1a5c86e226", "size": 2082, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/flamespeed_multicond_test.py", "max_stars_repo_name": "carlylagrotta/MSI", "max_stars_repo_head_hexsha": "e958beb5df2a2d1018bbb2f96382b5c99b08c3ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-25T15:46:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T15:46:06.000Z", "max_issues_repo_path": "tests/flamespeed_multicond_test.py", "max_issues_repo_name": "TheBurkeLab/MSI", "max_issues_repo_head_hexsha": "e958beb5df2a2d1018bbb2f96382b5c99b08c3ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/flamespeed_multicond_test.py", "max_forks_repo_name": "TheBurkeLab/MSI", "max_forks_repo_head_hexsha": "e958beb5df2a2d1018bbb2f96382b5c99b08c3ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-12-18T23:45:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T20:37:20.000Z", "avg_line_length": 40.8235294118, "max_line_length": 105, "alphanum_fraction": 0.530259366, "include": true, "reason": "import numpy", "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.19528549103791348}}
{"text": "#####################################################\n#\n# PyRAI2MD 2 module for interfacing to NNsForMD\n#\n# Author Jingbai Li\n# Sep 22 2021\n#\n######################################################\n\nimport time, os, sys\nimport numpy as np\nfrom PyRAI2MD.Machine_Learning.hypernn import SetHyperEG, SetHyperNAC, SetHyperSOC\nfrom PyRAI2MD.Machine_Learning.permutation import PermuteMap\nfrom PyRAI2MD.Utils.timing import WhatIsTime, HowLong\n\nfrom pyNNsMD.nn_pes import NeuralNetPes\nfrom pyNNsMD.nn_pes_src.device import set_gpu\n\nclass DNN:\n    \"\"\" pyNNsMD interface\n\n        Parameters:          Type:\n            keywords         dict        keywords dict\n            id               int         calculation index\n\n        Attribute:           Type:\n            hyp_eg           dict        Hyperparameters of energy gradient NN\n       \t    hyp_nac          dict        Hyperparameters of nonadiabatic coupling NN\n       \t    hyp_soc          dict     \t  Hyperparameters of spin-orbit coupling NN\n            x                ndarray     input structure array\n            y_dict           dict        target value dict \n            pred_x           ndarray     input structure array in set prediction set\n            pred_y           ndarray     target values in the prediction set\n\n        Functions:           Returns:\n            train            self        train NN for a given training set\n            load             self        load trained NN for prediction\n            appendix         self        fake function\n            evaluate         self        run prediction\n\n    \"\"\"\n\n    def __init__(self, keywords = None, id = None):\n\n        set_gpu([]) #No GPU for prediction\n        title           = keywords['control']['title']\n        variables       = keywords['nn'].copy()\n        modeldir        = variables['modeldir']\n        data            = variables['data']\n        nn_eg_type      = variables['nn_eg_type']\n        nn_nac_type     = variables['nn_nac_type']\n        nn_soc_type     = variables['nn_soc_type']\n        hyp_eg          = variables['eg'].copy()\n        hyp_nac         = variables['nac'].copy()\n        hyp_eg2         = variables['eg2'].copy()\n        hyp_nac2        = variables['nac2'].copy()\n        hyp_soc         = variables['soc'].copy()\n        hyp_soc2        = variables['soc2'].copy()\n        eg_unit         = variables['eg_unit']\n        nac_unit        = variables['nac_unit']\n        soc_unit        = variables['soc_unit']\n        seed            = variables['ml_seed']\n        permute         = variables['permute_map']\n        gpu             = variables['gpu']\n        self.jobtype    = keywords['control']['jobtype']\n        self.version    = keywords['version']\n        self.ncpu       = keywords['control']['ml_ncpu']\n        self.pred_data  = variables['pred_data']\n        self.train_mode = variables['train_mode']\n        self.shuffle    = variables['shuffle']\n        self.natom      = data.natom\n        self.nstate     = data.nstate\n        self.nnac       = data.nnac\n        self.nsoc       = data.nsoc\n\n        ## set hyperparamters\n        hyp_dict_eg     = SetHyperEG(hyp_eg, eg_unit, data.info)\n        hyp_dict_eg2    = SetHyperEG(hyp_eg2, eg_unit, data.info)\n        hyp_dict_nac    = SetHyperNAC(hyp_nac, nac_unit, data.info)\n        hyp_dict_nac2   = SetHyperNAC(hyp_nac2, nac_unit, data.info)\n        hyp_dict_soc    = SetHyperSOC(hyp_soc, soc_unit, data.info)\n        hyp_dict_soc2   = SetHyperSOC(hyp_soc2, soc_unit, data.info)\n\n        ## retraining has some bug at the moment, do not use\n        if self.train_mode not in ['training', 'retraining', 'resample']:\n            self.train_mode = 'training'\n        if id == None or id == 1:\n            self.name   = f\"NN-{title}\"\n        else:\n            self.name   = f\"NN-{title}-{id}\"\n        self.silent     = variables['silent']\n        self.x          = data.x\n        self.pred_x     = data.pred_x\n        self.pred_y     = data.pred_y\n\n        ## convert unit of energy and force. au or si. data are in au.\n        if   eg_unit == 'si':\n            self.H_to_eV        = 27.211396132\n            self.H_Bohr_to_eV_A = 27.211396132/0.529177249\n            self.keep_eV        = 1\n            self.keep_eVA       = 1\n        else:\n            self.H_to_eV        = 1\n            self.H_Bohr_to_eV_A = 1\n       \t    self.keep_eV       \t= 27.211396132\n       \t    self.keep_eVA      \t= 27.211396132/0.529177249\n\n        if   nac_unit == 'si':\n            self.Bohr_to_A  = 0.529177249/27.211396132 # convert to eV/A\n            self.keep_A     = 1\n        elif nac_unit == 'au':\n            self.Bohr_to_A  = 1                             # convert to Eh/B\n            self.keep_A     = 0.529177249/27.211396132\n        elif nac_unit == 'eha':\n            self.Bohr_to_A  = 0.529177249                   # convert to Eh/A\n            self.keep_A     = 1/27.211396132\n        else:\n            self.Bohr_to_A  = 1                             # convert to Eh/B\n            self.keep_A     = 0.529177249/27.211396132\n\n        ## combine y_dict\n        self.y_dict = {}\n        if nn_eg_type > 0:\n            self.y_dict['energy_gradient'] = [data.energy * self.H_to_eV, data.grad * self.H_Bohr_to_eV_A]\n        if nn_nac_type > 0:\n            self.y_dict['nac'] = data.nac/self.Bohr_to_A\n        if nn_soc_type > 0:\n            self.y_dict['soc'] = data.soc\n\n        ## check permuation map\n        self.x, self.y_dict = PermuteMap(self.x,self.y_dict,permute,hyp_eg['val_split'])\n\n        ## combine hypers\n        self.hyper = {}\n        if   nn_eg_type == 1:  # same architecture with different weight\n            self.hyper['energy_gradient'] = hyp_dict_eg\n        elif nn_eg_type > 1:\n       \t    self.hyper['energy_gradient'] = [hyp_dict_eg, hyp_dict_eg2]\n\n        if   nn_nac_type == 1: # same architecture with different weight\n       \t    self.hyper['nac'] = hyp_dict_nac\n       \telif nn_nac_type > 1:\n            self.hyper['nac'] = [hyp_dict_nac, hyp_dict_nac2]\n\n        if   nn_soc_type == 1: # same architecture with different weight\n            self.hyper['soc'] = hyp_dict_soc\n        elif nn_soc_type > 1:\n            self.hyper['soc'] = [hyp_dict_soc, hyp_dict_soc2]\n\n        ## setup GPU list\n        self.gpu_list = {}\n        if   gpu == 1:\n            self.gpu_list['energy_gradient'] = [0, 0]\n            self.gpu_list['nac'] = [0, 0]\n            self.gpu_list['soc'] = [0, 0]\n       \telif gpu == 2:\n            self.gpu_list['energy_gradient'] = [0, 1]\n            self.gpu_list['nac'] = [0, 1]\n            self.gpu_list['soc'] = [0, 1]\n       \telif gpu == 3:\n            self.gpu_list['energy_gradient'] = [0, 0]\n            self.gpu_list['nac'] = [1, 1]\n            self.gpu_list['soc'] = [2, 2]\n       \telif gpu == 4:\n            self.gpu_list['energy_gradient'] = [0, 1]\n            self.gpu_list['nac'] = [2, 2]\n            self.gpu_list['soc'] = [3, 3]\n        elif gpu == 5:\n            self.gpu_list['energy_gradient'] = [0, 1]\n            self.gpu_list['nac'] = [2, 3]\n            self.gpu_list['soc'] = [4, 4]\n        elif gpu == 6:\n            self.gpu_list['energy_gradient'] = [0, 1]\n            self.gpu_list['nac'] = [2, 3]\n            self.gpu_list['soc'] = [4, 5]\n\n        ## initialize model\n        if   modeldir == None or id not in [None, 1]:\n            self.model = NeuralNetPes(self.name)\n        else:\n            self.model = NeuralNetPes(modeldir)\n\n    def _heading(self):\n\n        headline=\"\"\"\n%s\n *---------------------------------------------------*\n |                                                   |\n |                  Neural Networks                  |\n |                                                   |\n *---------------------------------------------------*\n\n Number of atoms:  %s\n Number of state:  %s\n Number of NAC:    %s\n Number of SOC:    %s\n\n\"\"\" % ( self.version,\n        self.natom,\n        self.nstate,\n        self.nnac,\n        self.nsoc)\n \n       \treturn headline\n\n    def train(self):\n        start = time.time()\n\n        self.model.create(self.hyper)\n\n        topline = 'Neural Networks Start: %20s\\n%s' % (WhatIsTime(), self._heading())\n        runinfo = \"\"\"\\n  &nn fitting \\n\"\"\"\n\n        if self.silent == 0:\n            print(topline)\n            print(runinfo)\n\n        with open('%s.log' % (self.name), 'w') as log:\n            log.write(topline)\n            log.write(runinfo)\n\n\n        if self.train_mode == 'resample':\n            out_index, out_errr, out_fiterr, out_testerr = self.model.resample(\n                self.x, \n                self.y_dict,\n                gpu_dist = self.gpu_list,\n                proc_async = self.ncpu >= 4)\n        else:\n            ferr = self.model.fit(\n                self.x,\n                self.y_dict,\n                gpu_dist = self.gpu_list,\n                proc_async = self.ncpu >= 4,\n                fitmode = self.train_mode,\n                random_shuffle = self.shuffle)\n\n            #self.model.save()\n            err_e1 = 0\n            err_e2 = 0\n            err_g1 = 0\n            err_g2 = 0\n            err_n1 = 0\n            err_n2 = 0\n            err_s1 = 0\n            err_s2 = 0\n            if 'energy_gradient' in ferr.keys():\n                err_e1 = ferr['energy_gradient'][0][0]\n                err_e2 = ferr['energy_gradient'][1][0]\n                err_g1 = ferr['energy_gradient'][0][1]\n       \t       \terr_g2 = ferr['energy_gradient'][1][1]\n\n            if 'nac' in ferr.keys():\n                err_n1 = ferr['nac'][0]\n                err_n2 = ferr['nac'][1]\n\n            if 'soc' in ferr.keys():\n                err_s1 = ferr['soc'][0]\n                err_s2 = ferr['soc'][1]\n\n            metrics = {\n                'e1' : err_e1 * self.keep_eV,\n                'g1' : err_g1 * self.keep_eVA,\n                'n1' : err_n1 / self.keep_A,\n                's1' : err_s1,\n                'e2' : err_e2 * self.keep_eV,\n                'g2' : err_g2 * self.keep_eVA,\n                'n2' : err_n2 / self.keep_A,\n                's2' : err_s2}\n\n            train_info=\"\"\"\n  &nn validation mean absolute error\n-------------------------------------------------------\n      energy       gradient       nac          soc\n        eV           eV/A         eV/A         cm-1\n  %12.8f %12.8f %12.8f %12.8f\n  %12.8f %12.8f %12.8f %12.8f\n\n\"\"\" % (metrics['e1'], metrics['g1'], metrics['n1'], metrics['s1'],\n       metrics['e2'], metrics['g2'], metrics['n2'], metrics['s2'])\n\n        end = time.time()\n        walltime = HowLong(start,end)\n        endline = 'Neural Networks End: %20s Total: %20s\\n' % (WhatIsTime(), walltime)\n\n        if self.silent == 0:\n            print(train_info)\n            print(endline)\n\n        with open('%s.log' % (self.name), 'a') as log:\n            log.write(train_info)\n            log.write(endline)\n\n        metrics['time'] = end - start\n        metrics['walltime'] = walltime\n        metrics['path'] = os.getcwd()\n        metrics['status'] = 1\n\n        return metrics\n\n    def load(self):\n        self.model.load()\n\n        return self\n\n    def\tappendix(self,addons):\n       \t## fake\tfunction does nothing\n\n       \treturn self\n\n    def _qm(self, traj):\n        ## run psnnsmd for QM calculation\n\n        xyz = traj.coord.reshape((1, self.natom, 3))\n        y_pred,y_std=self.model.call(xyz)\n\n        ## initialize return values\n        energy = []\n        gradient = []\n        nac = []\n        soc = []\n        err_e = 0\n       \terr_g =\t0\n       \terr_n =\t0\n       \terr_s =\t0\n\n        ## update return values\n        if 'energy_gradient' in y_pred.keys():\n            e_pred = y_pred['energy_gradient'][0] / self.H_to_eV\n            g_pred = y_pred['energy_gradient'][1] / self.H_Bohr_to_eV_A\n            e_std = y_std['energy_gradient'][0] / self.H_to_eV\n            g_std = y_std['energy_gradient'][1] / self.H_Bohr_to_eV_A\n            energy = e_pred[0]\n            gradient = g_pred[0]\n            err_e = np.amax(e_std)\n            err_g = np.amax(g_std)\n\n        if 'nac' in y_pred.keys():\n            n_pred = y_pred['nac']*self.Bohr_to_A\n            n_std = y_std['nac']*self.Bohr_to_A\n            nac = n_pred[0]\n            err_n = np.amax(n_std)\n\n        if 'soc' in y_pred.keys():\n            s_pred = y_pred['soc']\n            s_std = y_std['soc']\n            soc = s_pred[0]\n            err_s = np.amax(s_std)\n\n        return energy, gradient, nac, soc, err_e, err_g, err_n, err_s\n\n    def _predict(self, x):\n        ## run psnnsmd for model testing\n\n        batch = len(x)\n\n        y_pred, y_std = self.model.predict(x)\n\n        ## load values from prediction set\n        pred_e = self.pred_y['energy']\n        pred_g = self.pred_y['grad']\n        pred_n = self.pred_y['nac']\n        pred_s = self.pred_y['soc']\n\n        ## initialize errors\n        de_max = np.zeros(batch)\n        dg_max = np.zeros(batch)\n        dn_max = np.zeros(batch)\n        ds_max = np.zeros(batch)\n\n        ## update errors\n        if 'energy_gradient' in y_pred.keys():\n            e_pred = y_pred['energy_gradient'][0] / self.H_to_eV\n            g_pred = y_pred['energy_gradient'][1] / self.H_Bohr_to_eV_A\n            e_std = y_std['energy_gradient'][0] / self.H_to_eV \n            g_std = y_std['energy_gradient'][1] / self.H_Bohr_to_eV_A\n            de = np.abs(pred_e - e_pred)\n            dg = np.abs(pred_g - g_pred)\n            de_max = np.amax(de.reshape((batch, -1)), axis = 1)\n            dg_max = np.amax(dg.reshape((batch, -1)), axis = 1)\n\n            val_out = np.concatenate((pred_e.reshape((batch, -1)), e_pred.reshape((batch, -1))), axis = 1)\n            std_out = np.concatenate((de.reshape((batch, -1)), e_std.reshape((batch, -1))), axis = 1)\n            np.savetxt('%s-e.pred.txt' % (self.name), np.concatenate((val_out, std_out), axis = 1))\n\n            val_out = np.concatenate((pred_g.reshape((batch, -1)), g_pred.reshape((batch, -1))), axis = 1)\n       \t    std_out = np.concatenate((dg.reshape((batch, -1)), g_std.reshape((batch, -1))), axis = 1)\n            np.savetxt('%s-g.pred.txt' % (self.name), np.concatenate((val_out, std_out), axis = 1))\n\n        if 'nac' in y_pred.keys():\n            n_pred = y_pred['nac'] * self.Bohr_to_A\n            n_std = y_std['nac'] * self.Bohr_to_A\n            dn = np.abs(pred_n - n_pred)\n            dn_max = np.amax(dn.reshape((batch, -1)), axis = 1)\n\n            val_out = np.concatenate((pred_n.reshape((batch, -1)), n_pred.reshape((batch, -1))), axis = 1)\n       \t    std_out = np.concatenate((dn.reshape((batch, -1)), n_std.reshape((batch, -1))), axis = 1)\n            np.savetxt('%s-n.pred.txt' % (self.name), np.concatenate((val_out, std_out), axis = 1))\n\n\n        if 'soc' in y_pred.keys():\n            s_pred = y_pred['soc']\n            s_std = y_std['soc']\n       \t    ds = np.abs(pred_s - s_pred)\n            ds_max = np.amax(ds.reshape((batch, -1)), axis = 1)\n\n            val_out = np.concatenate((pred_s.reshape((batch, -1)), s_pred.reshape((batch, -1))), axis = 1)\n       \t    std_out = np.concatenate((ds.reshape((batch, -1)), s_std.reshape((batch, -1))), axis = 1)\n            np.savetxt('%s-s.pred.txt' % (self.name), np.concatenate((val_out, std_out), axis = 1))\n\n        output = ''\n        for i in range(batch):\n            output += '%5s %8.4f %8.4f %8.4f %8.4f\\n' % (i + 1, de_max[i], dg_max[i], dn_max[i], ds_max[i])\n\n        with open('max_abs_dev.txt', 'w') as out:\n            out.write(output)\n\n        return self\n\n    def evaluate(self, traj):\n        ## main function to run pyNNsMD and communicate with other PyRAIMD modules\n\n        if   self.jobtype == 'prediction' or self.jobtype == 'predict':\n            self._predict(self.pred_x)\n        else:\n            energy, gradient, nac, soc, err_energy, err_grad, err_nac, err_soc = self._qm(traj)\n            traj.energy = np.copy(energy)\n            traj.grad = np.copy(gradient)\n            traj.nac = np.copy(nac)\n            traj.soc = np.copy(soc)\n            traj.err_energy = err_energy\n            traj.err_grad = err_grad\n            traj.err_nac = err_nac\n            traj.err_soc = err_soc\n            traj.status = 1\n\n            return traj\n", "meta": {"hexsha": "ac84fc8fa44641f76e717334ac155ee0004c6e94", "size": 16086, "ext": "py", "lang": "Python", "max_stars_repo_path": "PyRAI2MD/Machine_Learning/model_NN.py", "max_stars_repo_name": "lopez-lab/PyRAI2MD", "max_stars_repo_head_hexsha": "43e27fbc9bc5b6ab6a8f170791951f316fcd0964", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2021-10-20T23:41:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T23:29:21.000Z", "max_issues_repo_path": "PyRAI2MD/Machine_Learning/model_NN.py", "max_issues_repo_name": "lopez-lab/PyRAI2MD", "max_issues_repo_head_hexsha": "43e27fbc9bc5b6ab6a8f170791951f316fcd0964", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PyRAI2MD/Machine_Learning/model_NN.py", "max_forks_repo_name": "lopez-lab/PyRAI2MD", "max_forks_repo_head_hexsha": "43e27fbc9bc5b6ab6a8f170791951f316fcd0964", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-06T04:27:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T23:29:28.000Z", "avg_line_length": 36.7260273973, "max_line_length": 107, "alphanum_fraction": 0.5067760786, "include": true, "reason": "import numpy", "num_tokens": 4265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.19528548962214484}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#\n\nfrom functools import reduce\nimport numpy\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf.ao2mo import _ao2mo\nfrom pyscf.tdscf import uhf\nfrom pyscf.scf import uhf_symm\nfrom pyscf.pbc.tdscf.krhf import _get_e_ia\nfrom pyscf.pbc.scf.newton_ah import _gen_uhf_response\nfrom pyscf import __config__\n\nREAL_EIG_THRESHOLD = getattr(__config__, 'pbc_tdscf_uhf_TDDFT_pick_eig_threshold', 1e-3)\nPOSTIVE_EIG_THRESHOLD = getattr(__config__, 'pbc_tdscf_uhf_TDDFT_positive_eig_threshold', 1e-3)\n\nclass TDA(uhf.TDA):\n\n    conv_tol = getattr(__config__, 'pbc_tdscf_rhf_TDA_conv_tol', 1e-6)\n\n    def __init__(self, mf):\n        from pyscf.pbc import scf\n        assert(isinstance(mf, scf.khf.KSCF))\n        self.cell = mf.cell\n        uhf.TDA.__init__(self, mf)\n        from pyscf.pbc.df.df_ao2mo import warn_pbc2d_eri\n        warn_pbc2d_eri(mf)\n\n    def gen_vind(self, mf):\n        '''Compute Ax'''\n        singlet = self.singlet\n        cell = mf.cell\n        kpts = mf.kpts\n\n        mo_coeff = mf.mo_coeff\n        mo_energy = mf.mo_energy\n        mo_occ = mf.mo_occ\n        nkpts = len(mo_occ)\n        nao, nmo = mo_coeff[0][0].shape\n        occidxa = [numpy.where(mo_occ[0][k]> 0)[0] for k in range(nkpts)]\n        occidxb = [numpy.where(mo_occ[1][k]> 0)[0] for k in range(nkpts)]\n        viridxa = [numpy.where(mo_occ[0][k]==0)[0] for k in range(nkpts)]\n        viridxb = [numpy.where(mo_occ[1][k]==0)[0] for k in range(nkpts)]\n        orboa = [mo_coeff[0][k][:,occidxa[k]] for k in range(nkpts)]\n        orbob = [mo_coeff[1][k][:,occidxb[k]] for k in range(nkpts)]\n        orbva = [mo_coeff[0][k][:,viridxa[k]] for k in range(nkpts)]\n        orbvb = [mo_coeff[1][k][:,viridxb[k]] for k in range(nkpts)]\n\n        e_ia_a = _get_e_ia(mo_energy[0], mo_occ[0])\n        e_ia_b = _get_e_ia(mo_energy[1], mo_occ[1])\n        hdiag = numpy.hstack([x.ravel() for x in (e_ia_a + e_ia_b)])\n        tot_x_a = sum(x.size for x in e_ia_a)\n        tot_x_b = sum(x.size for x in e_ia_b)\n\n        mem_now = lib.current_memory()[0]\n        max_memory = max(2000, self.max_memory*.8-mem_now)\n        vresp = _gen_uhf_response(mf, hermi=0, max_memory=max_memory)\n\n        def vind(zs):\n            nz = len(zs)\n            zs = [_unpack(z, mo_occ) for z in zs]\n            dmov = numpy.empty((2,nz,nkpts,nao,nao), dtype=numpy.complex128)\n            for i in range(nz):\n                dm1a, dm1b = zs[i]\n                for k in range(nkpts):\n                    dmov[0,i,k] = reduce(numpy.dot, (orboa[k], dm1a[k], orbva[k].conj().T))\n                    dmov[1,i,k] = reduce(numpy.dot, (orbob[k], dm1b[k], orbvb[k].conj().T))\n\n            with lib.temporary_env(mf, exxdiv=None):\n                dmov = dmov.reshape(2*nz,nkpts,nao,nao)\n                v1ao = vresp(dmov)\n                v1ao = v1ao.reshape(2,nz,nkpts,nao,nao)\n\n            v1s = []\n            for i in range(nz):\n                dm1a, dm1b = zs[i]\n                v1as = []\n                v1bs = []\n                for k in range(nkpts):\n                    v1a = reduce(numpy.dot, (orboa[k].conj().T, v1ao[0,i,k], orbva[k]))\n                    v1b = reduce(numpy.dot, (orbob[k].conj().T, v1ao[1,i,k], orbvb[k]))\n                    v1a += e_ia_a[k] * dm1a[k]\n                    v1b += e_ia_b[k] * dm1b[k]\n                    v1as.append(v1a.ravel())\n                    v1bs.append(v1b.ravel())\n                v1s += v1as + v1bs\n            return numpy.hstack(v1s).reshape(nz,-1)\n\n        return vind, hdiag\n\n    def init_guess(self, mf, nstates=None):\n        if nstates is None: nstates = self.nstates\n\n        mo_energy = mf.mo_energy\n        mo_occ = mf.mo_occ\n        e_ia_a = _get_e_ia(mo_energy[0], mo_occ[0])\n        e_ia_b = _get_e_ia(mo_energy[1], mo_occ[1])\n        e_ia = numpy.hstack([x.ravel() for x in (e_ia_a + e_ia_b)])\n        nov = e_ia.size\n        nroot = min(nstates, nov)\n        x0 = numpy.zeros((nroot, nov))\n        idx = numpy.argsort(e_ia)\n        for i in range(nroot):\n            x0[i,idx[i]] = 1  # lowest excitations\n        return x0\n\n    def kernel(self, x0=None):\n        '''TDA diagonalization solver\n        '''\n        self.check_sanity()\n        self.dump_flags()\n\n        vind, hdiag = self.gen_vind(self._scf)\n        precond = self.get_precond(hdiag)\n        if x0 is None:\n            x0 = self.init_guess(self._scf, self.nstates)\n\n        self.converged, self.e, x1 = \\\n                lib.davidson1(vind, x0, precond,\n                              tol=self.conv_tol,\n                              nroots=self.nstates, lindep=self.lindep,\n                              max_space=self.max_space,\n                              verbose=self.verbose)\n\n        mo_occ = self._scf.mo_occ\n        tot_x_a = sum((occ>0).sum()*(occ==0).sum() for occ in mo_occ[0])\n        self.xy = [(_unpack(xi, mo_occ),  # (X_alpha, X_beta)\n                    (0, 0))  # (Y_alpha, Y_beta)\n                   for xi in x1]\n        #TODO: analyze CIS wfn point group symmetry\n        return self.e, self.xy\nCIS = KTDA = TDA\n\n\nclass TDHF(TDA):\n    def gen_vind(self, mf):\n        singlet = self.singlet\n        cell = mf.cell\n        kpts = mf.kpts\n\n        mo_coeff = mf.mo_coeff\n        mo_energy = mf.mo_energy\n        mo_occ = mf.mo_occ\n        nkpts = len(mo_occ)\n        nao, nmo = mo_coeff[0][0].shape\n        occidxa = [numpy.where(mo_occ[0][k]> 0)[0] for k in range(nkpts)]\n        occidxb = [numpy.where(mo_occ[1][k]> 0)[0] for k in range(nkpts)]\n        viridxa = [numpy.where(mo_occ[0][k]==0)[0] for k in range(nkpts)]\n        viridxb = [numpy.where(mo_occ[1][k]==0)[0] for k in range(nkpts)]\n        orboa = [mo_coeff[0][k][:,occidxa[k]] for k in range(nkpts)]\n        orbob = [mo_coeff[1][k][:,occidxb[k]] for k in range(nkpts)]\n        orbva = [mo_coeff[0][k][:,viridxa[k]] for k in range(nkpts)]\n        orbvb = [mo_coeff[1][k][:,viridxb[k]] for k in range(nkpts)]\n\n        e_ia_a = _get_e_ia(mo_energy[0], mo_occ[0])\n        e_ia_b = _get_e_ia(mo_energy[1], mo_occ[1])\n        hdiag = numpy.hstack([x.ravel() for x in (e_ia_a + e_ia_b)])\n        hdiag = numpy.hstack((hdiag, hdiag))\n        tot_x_a = sum(x.size for x in e_ia_a)\n        tot_x_b = sum(x.size for x in e_ia_b)\n        tot_x = tot_x_a + tot_x_b\n\n        mem_now = lib.current_memory()[0]\n        max_memory = max(2000, self.max_memory*.8-mem_now)\n        vresp = _gen_uhf_response(mf, hermi=0, max_memory=max_memory)\n\n        def vind(xys):\n            nz = len(xys)\n            x1s = [_unpack(x[:tot_x], mo_occ) for x in xys]\n            y1s = [_unpack(x[tot_x:], mo_occ) for x in xys]\n            dmov = numpy.empty((2,nz,nkpts,nao,nao), dtype=numpy.complex128)\n            for i in range(nz):\n                xa, xb = x1s[i]\n                ya, yb = y1s[i]\n                for k in range(nkpts):\n                    dmx = reduce(numpy.dot, (orboa[k], xa[k]  , orbva[k].conj().T))\n                    dmy = reduce(numpy.dot, (orbva[k], ya[k].T, orboa[k].conj().T))\n                    dmov[0,i,k] = dmx + dmy  # AX + BY\n                    dmx = reduce(numpy.dot, (orbob[k], xb[k]  , orbvb[k].conj().T))\n                    dmy = reduce(numpy.dot, (orbvb[k], yb[k].T, orbob[k].conj().T))\n                    dmov[1,i,k] = dmx + dmy  # AX + BY\n\n            with lib.temporary_env(mf, exxdiv=None):\n                dmov = dmov.reshape(2*nz,nkpts,nao,nao)\n                v1ao = vresp(dmov)\n                v1ao = v1ao.reshape(2,nz,nkpts,nao,nao)\n\n            v1s = []\n            for i in range(nz):\n                xa, xb = x1s[i]\n                ya, yb = y1s[i]\n                v1xsa = []\n                v1xsb = []\n                v1ysa = []\n                v1ysb = []\n                for k in range(nkpts):\n                    v1xa = reduce(numpy.dot, (orboa[k].conj().T, v1ao[0,i,k], orbva[k]))\n                    v1xb = reduce(numpy.dot, (orbob[k].conj().T, v1ao[1,i,k], orbvb[k]))\n                    v1ya = reduce(numpy.dot, (orbva[k].conj().T, v1ao[0,i,k], orboa[k])).T\n                    v1yb = reduce(numpy.dot, (orbvb[k].conj().T, v1ao[1,i,k], orbob[k])).T\n                    v1xa+= e_ia_a[k] * xa[k]\n                    v1xb+= e_ia_b[k] * xb[k]\n                    v1ya+= e_ia_a[k] * ya[k]\n                    v1yb+= e_ia_b[k] * yb[k]\n                    v1xsa.append(v1xa.ravel())\n                    v1xsb.append(v1xb.ravel())\n                    v1ysa.append(-v1ya.ravel())\n                    v1ysb.append(-v1yb.ravel())\n                v1s += v1xsa + v1xsb + v1ysa + v1ysb\n            return numpy.hstack(v1s).reshape(nz,-1)\n\n        return vind, hdiag\n\n    def init_guess(self, mf, nstates=None, wfnsym=None):\n        x0 = TDA.init_guess(self, mf, nstates)\n        y0 = numpy.zeros_like(x0)\n        return numpy.hstack((x0,y0))\n\n    def kernel(self, x0=None):\n        '''TDHF diagonalization with non-Hermitian eigenvalue solver\n        '''\n        self.check_sanity()\n        self.dump_flags()\n\n        vind, hdiag = self.gen_vind(self._scf)\n        precond = self.get_precond(hdiag)\n        if x0 is None:\n            x0 = self.init_guess(self._scf, self.nstates)\n\n        real_system = (gamma_point(self._scf.kpts) and\n                       self._scf.mo_coeff[0][0].dtype == numpy.double)\n\n        # We only need positive eigenvalues\n        def pickeig(w, v, nroots, envs):\n            realidx = numpy.where((abs(w.imag) < REAL_EIG_THRESHOLD) &\n                                  (w.real > POSTIVE_EIG_THRESHOLD))[0]\n            return lib.linalg_helper._eigs_cmplx2real(w, v, realidx, real_system)\n\n        self.converged, w, x1 = \\\n                lib.davidson_nosym1(vind, x0, precond,\n                                    tol=self.conv_tol,\n                                    nroots=self.nstates, lindep=self.lindep,\n                                    max_space=self.max_space, pick=pickeig,\n                                    verbose=self.verbose)\n\n        mo_occ = self._scf.mo_occ\n        e = []\n        xy = []\n        for i, z in enumerate(x1):\n            xs, ys = z.reshape(2,-1)\n            norm = lib.norm(xs)**2 - lib.norm(ys)**2\n            if norm > 0:\n                norm = 1/numpy.sqrt(norm)\n                xs *= norm\n                ys *= norm\n                e.append(w[i])\n                xy.append((_unpack(xs, mo_occ), _unpack(ys, mo_occ)))\n        self.e = numpy.array(e)\n        self.xy = xy\n        return self.e, self.xy\nRPA = KTDHF = TDHF\n\ndef _unpack(vo, mo_occ):\n    za = []\n    zb = []\n    p1 = 0\n    for k, occ in enumerate(mo_occ[0]):\n        no = numpy.count_nonzero(occ > 0)\n        nv = occ.size - no\n        p0, p1 = p1, p1 + no * nv\n        za.append(vo[p0:p1].reshape(no,nv))\n\n    for k, occ in enumerate(mo_occ[1]):\n        no = numpy.count_nonzero(occ > 0)\n        nv = occ.size - no\n        p0, p1 = p1, p1 + no * nv\n        zb.append(vo[p0:p1].reshape(no,nv))\n    return za, zb\n\n\nfrom pyscf.pbc import scf\nscf.kuhf.KUHF.TDA  = lib.class_as_method(KTDA)\nscf.kuhf.KUHF.TDHF = lib.class_as_method(KTDHF)\n\n\nif __name__ == '__main__':\n    from pyscf.pbc import gto\n    from pyscf.pbc import scf\n    from pyscf.pbc import df\n    cell = gto.Cell()\n    cell.unit = 'B'\n    cell.atom = '''\n    C  0.          0.          0.        \n    C  1.68506879  1.68506879  1.68506879\n    '''\n    cell.a = '''\n    0.          3.37013758  3.37013758\n    3.37013758  0.          3.37013758\n    3.37013758  3.37013758  0.\n    '''\n\n    cell.basis = 'gth-szv'\n    cell.pseudo = 'gth-pade'\n    cell.mesh = [37]*3\n    cell.build()\n    mf = scf.KUHF(cell, cell.make_kpts([2,1,1])).set(exxdiv=None)\n#    mf.with_df = df.DF(cell, cell.make_kpts([2,1,1]))\n#    mf.with_df.auxbasis = 'weigend'\n#    mf.with_df._cderi = 'eri3d-df.h5'\n#    mf.with_df.build(with_j3c=False)\n    mf.run()\n\n    td = TDA(mf)\n    td.verbose = 5\n    td.nstates = 5\n    print(td.kernel()[0] * 27.2114)\n\n    td = TDHF(mf)\n    td.verbose = 5\n    td.nstates = 5\n    print(td.kernel()[0] * 27.2114)\n\n    cell.spin = 2\n    mf = scf.KUHF(cell, cell.make_kpts([2,1,1])).set(exxdiv=None)\n    mf.run()\n\n    td = TDA(mf)\n    td.verbose = 5\n    td.nstates = 5\n    print(td.kernel()[0] * 27.2114)\n\n    td = TDHF(mf)\n    td.verbose = 5\n    td.nstates = 5\n    print(td.kernel()[0] * 27.2114)\n", "meta": {"hexsha": "0f75becdb7a844c05ab06d4c135644c3b746db4c", "size": 12832, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/pbc/tdscf/kuhf.py", "max_stars_repo_name": "LeonOtis/pyscf", "max_stars_repo_head_hexsha": "98ba8106396ac4c90dc65207059773ce048b0ebf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-03T12:32:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T08:19:02.000Z", "max_issues_repo_path": "pyscf/pbc/tdscf/kuhf.py", "max_issues_repo_name": "LeonOtis/pyscf", "max_issues_repo_head_hexsha": "98ba8106396ac4c90dc65207059773ce048b0ebf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscf/pbc/tdscf/kuhf.py", "max_forks_repo_name": "LeonOtis/pyscf", "max_forks_repo_head_hexsha": "98ba8106396ac4c90dc65207059773ce048b0ebf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-06-01T05:31:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T02:38:33.000Z", "avg_line_length": 36.4545454545, "max_line_length": 95, "alphanum_fraction": 0.5367830424, "include": true, "reason": "import numpy", "num_tokens": 4038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878696277512, "lm_q2_score": 0.31742627850202554, "lm_q1q2_score": 0.19524505340767612}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n# pylint: disable=no-member\n#\n# @Author: oesteban\n# @Date:   2016-02-23 19:25:39\n# @Email:  code@oscaresteban.es\n# @Last Modified by:   oesteban\n# @Last Modified time: 2018-03-12 11:44:09\n\"\"\"\n\nMeasures for the structural information\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nDefinitions are given in the\n:ref:`summary of structural IQMs <iqms_t1w>`.\n\n.. _iqms_efc:\n\n- **Entropy-focus criterion** (:py:func:`~mriqc.qc.anatomical.efc`).\n\n.. _iqms_fber:\n\n- **Foreground-Background energy ratio** (:py:func:`~mriqc.qc.anatomical.fber`,  [Shehzad2015]_).\n\n.. _iqms_fwhm:\n\n- **Full-width half maximum smoothness** (``fwhm_*``).\n\n.. _iqms_snr:\n\n- **Signal-to-noise ratio** (:py:func:`~mriqc.qc.anatomical.snr`).\n\n.. _iqms_summary:\n\n- **Summary statistics** (:py:func:`~mriqc.qc.anatomical.summary_stats`).\n\n\nMeasures for the temporal information\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. _iqms_dvars:\n\n- **DVARS** - D referring to temporal derivative of timecourses, VARS referring to\n  RMS variance over voxels ([Power2012]_ ``dvars_nstd``) indexes the rate of change of\n  BOLD signal across the entire brain at each frame of data. DVARS is calculated\n  `with nipype <http://nipype.readthedocs.io/en/latest/interfaces/generated/\\\nnipype.algorithms.confounds.html#computedvars>`_ after motion correction:\n\n  .. math ::\n\n      \\\\text{DVARS}_t = \\\\sqrt{\\\\frac{1}{N}\\\\sum_i \\\\left[x_{i,t} - x_{i,t-1}\\\\right]^2}\n\n\n  .. note ::\n\n    Intensities are scaled to 1000 leading to the units being expressed in x10\n    :math:`\\\\%\\\\Delta\\\\text{BOLD}` change.\n\n  .. note ::\n\n    MRIQC calculates two additional standardized values of the DVARS.\n    The ``dvars_std`` metric is normalized with the standard deviation of the\n    temporal difference time series. The ``dvars_vstd`` is a voxel-wise\n    standardization of DVARS, where the temporal difference time series is\n    normalized across time by that voxel standard deviation across time, before\n    computing the RMS of the temporal difference [Nichols2013]_.\n\n.. _iqms_gcor:\n\n- **Global Correlation** (``gcor``) calculates an optimized summary of time-series\n    correlation as in [Saad2013]_ using AFNI's ``@compute_gcor``:\n\n  .. math ::\n\n      \\\\text{GCOR} = \\\\frac{1}{N}\\\\mathbf{g}_u^T\\\\mathbf{g}_u\n\n  where :math:`\\\\mathbf{g}_u` is the average of all unit-variance time series in a\n  :math:`T` (\\# timepoints) :math:`\\\\times` :math:`N` (\\# voxels) matrix.\n\n.. _iqms_tsnr:\n\n- **Temporal SNR** (:abbr:`tSNR (temporal SNR)`, ``tsnr``) is a simplified\n  interpretation of the tSNR definition [Kruger2001]_. We report the median value\n  of the `tSNR map <http://nipype.readthedocs.io/en/latest/interfaces/generated/\\\nnipype.algorithms.confounds.html#tsnr>`_ calculated like:\n\n  .. math ::\n\n      \\\\text{tSNR} = \\\\frac{\\\\langle S \\\\rangle_t}{\\\\sigma_t},\n\n  where :math:`\\\\langle S \\\\rangle_t` is the average BOLD signal (across time),\n  and :math:`\\\\sigma_t` is the corresponding temporal standard-deviation map.\n\n\nMeasures for artifacts and other\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. _iqms_fd:\n\n- **Framewise Displacement**: expresses instantaneous head-motion.\n  MRIQC reports the average FD, labeled as ``fd_mean``.\n  Rotational displacements are calculated as the displacement on the surface of a\n  sphere of radius 50 mm [Power2012]_:\n\n  .. math ::\n\n      \\\\text{FD}_t = |\\\\Delta d_{x,t}| + |\\\\Delta d_{y,t}| + \\\n|\\\\Delta d_{z,t}| + |\\\\Delta \\\\alpha_t| + |\\\\Delta \\\\beta_t| + |\\\\Delta \\\\gamma_t|\n\n  Along with the base framewise displacement, MRIQC reports the\n  **number of timepoints above FD threshold** (``fd_num``), and the\n  **percent of FDs above the FD threshold** w.r.t. the full timeseries (``fd_perc``).\n  In both cases, the threshold is set at 0.20mm.\n\n.. _iqms_gsr:\n\n- **Ghost to Signal Ratio** (:py:func:`~mriqc.qc.functional.gsr`, labeled\n  in the reports as ``gsr_x`` and ``gsr_y``):\n  along the two possible phase-encoding axes **x**, **y**:\n\n  .. math ::\n\n      \\\\text{GSR} = \\\\frac{\\\\mu_G - \\\\mu_{NG}}{\\\\mu_S}\n\n  .. image :: ../_static/epi-gsrmask.png\n    :width: 200px\n    :align: center\n\n.. _iqms_aor:\n\n- **AFNI's outlier ratio** (``aor``) - Mean fraction of outliers per fMRI volume\n  as given by AFNI's ``3dToutcount``.\n\n.. _iqms_aqi:\n\n- **AFNI's quality index** (``aqi``) - Mean quality index as computed by AFNI's ``3dTqual``.\n\n.. _iqms_dummy:\n\n- **Number of *dummy* scans** (``dummy``) - A number of volumes in the begining of the\n  fMRI timeseries identified as non-steady state.\n\n.. topic:: References\n\n  .. [Atkinson1997] Atkinson et al., *Automatic correction of motion artifacts\n    in magnetic resonance images using an entropy\n    focus criterion*, IEEE Trans Med Imag 16(6):903-910, 1997.\n    doi:`10.1109/42.650886 <http://dx.doi.org/10.1109/42.650886>`_.\n\n  .. [Friedman2008] Friedman, L et al., *Test--retest and between‐site reliability in a multicenter\n    fMRI study*. Hum Brain Mapp, 29(8):958--972, 2008. doi:`10.1002/hbm.20440\n    <http://dx.doi.org/10.1002/hbm.20440>`_.\n\n  .. [Giannelli2010] Giannelli et al., *Characterization of Nyquist ghost in\n    EPI-fMRI acquisition sequences implemented on two clinical 1.5 T MR scanner\n    systems: effect of readout bandwidth and echo spacing*. J App Clin Med Phy,\n    11(4). 2010.\n    doi:`10.1120/jacmp.v11i4.3237 <http://dx.doi.org/10.1120/jacmp.v11i4.3237>`_.\n\n  .. [Jenkinson2002] Jenkinson et al., *Improved Optimisation for the Robust and\n    Accurate Linear Registration and Motion Correction of Brain Images*.\n    NeuroImage, 17(2), 825-841, 2002.\n    doi:`10.1006/nimg.2002.1132 <http://dx.doi.org/10.1006/nimg.2002.1132>`_.\n\n  .. [Kruger2001] Krüger et al., *Physiological noise in oxygenation-sensitive\n    magnetic resonance imaging*, Magn. Reson. Med. 46(4):631-637, 2001.\n    doi:`10.1002/mrm.1240 <http://dx.doi.org/10.1002/mrm.1240>`_.\n\n  .. [Nichols2013] Nichols, `Notes on Creating a Standardized Version of DVARS\n      <http://www2.warwick.ac.uk/fac/sci/statistics/staff/academic-research\\\n/nichols/scripts/fsl/standardizeddvars.pdf>`_, 2013.\n\n  .. [Power2012] Power et al., *Spurious but systematic correlations in\n    functional connectivity MRI networks arise from subject motion*,\n    NeuroImage 59(3):2142-2154,\n    2012, doi:`10.1016/j.neuroimage.2011.10.018\n    <http://dx.doi.org/10.1016/j.neuroimage.2011.10.018>`_.\n\n  .. [Saad2013] Saad et al. *Correcting Brain-Wide Correlation Differences\n     in Resting-State FMRI*, Brain Conn 3(4):339-352,\n     2013, doi:`10.1089/brain.2013.0156\n     <http://dx.doi.org/10.1089/brain.2013.0156>`_.\n\n\nmriqc.qc.functional module\n^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n\"\"\"\nfrom __future__ import print_function, division, absolute_import, unicode_literals\nimport os.path as op\nimport numpy as np\n\nRAS_AXIS_ORDER = {'x': 0, 'y': 1, 'z': 2}\n\n\ndef gsr(epi_data, mask, direction=\"y\", ref_file=None, out_file=None):\n    \"\"\"\n    Computes the :abbr:`GSR (ghost to signal ratio)` [Giannelli2010]_. The\n    procedure is as follows:\n\n      #. Create a Nyquist ghost mask by circle-shifting the original mask by :math:`N/2`.\n\n      #. Rotate by :math:`N/2`\n\n      #. Remove the intersection with the original mask\n\n      #. Generate a non-ghost background\n\n      #. Calculate the :abbr:`GSR (ghost to signal ratio)`\n\n\n    .. warning ::\n\n      This should be used with EPI images for which the phase\n      encoding direction is known.\n\n    :param str epi_file: path to epi file\n    :param str mask_file: path to brain mask\n    :param str direction: the direction of phase encoding (x, y, all)\n    :return: the computed gsr\n\n    \"\"\"\n\n    direction = direction.lower()\n    if direction[-1] not in ['x', 'y', 'all']:\n        raise Exception(\"Unknown direction {}, should be one of x, -x, y, -y, all\".format(\n            direction))\n\n    if direction == 'all':\n        result = []\n        for newdir in ['x', 'y']:\n            ofile = None\n            if out_file is not None:\n                fname, ext = op.splitext(ofile)\n                if ext == '.gz':\n                    fname, ext2 = op.splitext(fname)\n                    ext = ext2 + ext\n                ofile = '{0}_{1}{2}'.format(fname, newdir, ext)\n            result += [gsr(epi_data, mask, newdir,\n                           ref_file=ref_file, out_file=ofile)]\n        return result\n\n    # Roll data of mask through the appropriate axis\n    axis = RAS_AXIS_ORDER[direction]\n    n2_mask = np.roll(mask, mask.shape[axis] // 2, axis=axis)\n\n    # Step 3: remove from n2_mask pixels inside the brain\n    n2_mask = n2_mask * (1 - mask)\n\n    # Step 4: non-ghost background region is labeled as 2\n    n2_mask = n2_mask + 2 * (1 - n2_mask - mask)\n\n    # Step 5: signal is the entire foreground image\n    ghost = np.mean(epi_data[n2_mask == 1]) - np.mean(epi_data[n2_mask == 2])\n    signal = np.median(epi_data[n2_mask == 0])\n    return float(ghost / signal)\n", "meta": {"hexsha": "355b2e34a30dc465f40e497538ae395fcee49f69", "size": 8939, "ext": "py", "lang": "Python", "max_stars_repo_path": "mriqc/qc/functional.py", "max_stars_repo_name": "Jordan-Theriault/mriqc", "max_stars_repo_head_hexsha": "7a84b28e17c9f137bde75aa264b6f0e7e5804eed", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mriqc/qc/functional.py", "max_issues_repo_name": "Jordan-Theriault/mriqc", "max_issues_repo_head_hexsha": "7a84b28e17c9f137bde75aa264b6f0e7e5804eed", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mriqc/qc/functional.py", "max_forks_repo_name": "Jordan-Theriault/mriqc", "max_forks_repo_head_hexsha": "7a84b28e17c9f137bde75aa264b6f0e7e5804eed", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3807692308, "max_line_length": 99, "alphanum_fraction": 0.6566730059, "include": true, "reason": "import numpy", "num_tokens": 2738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.1952450449565267}}
{"text": "#!/usr/bin/env python\n\n'''\n    Construct SoS using integrated orbits.\n'''\n\nimport numpy as np\nfrom scipy.interpolate import interp1d\nfrom scipy.optimize import brentq\n\ndef sos(orb, axis=0, direction='+'):\n\n    ''' Construct SoS for integrated orbits. '''\n\n    # interpolator,\n    k_intp = interp1d(np.arange(orb.shape[0]), orb[:, axis], \\\n                      copy=True, assume_sorted=True)\n\n    # find zeros,\n    sign_t = 1.0 if direction == '+' else -1.0\n    i_zeros = np.arange(orb.shape[0] - 1)[ \\\n              (orb[1:, axis] * orb[:-1, axis] < 0.) \\\n            * (np.sign(orb[1:, axis + 2]) * sign_t > 0.)]\n    t_zeros = np.array([brentq(k_intp, zi, zi + 1) for zi in i_zeros])\n\n    # interpolate other axes,\n    w_intp = interp1d(np.arange(orb.shape[0]), orb, \\\n                      axis=0, copy=False, assume_sorted=True)\n\n    # return surface if sectuibm\n    return w_intp(t_zeros)", "meta": {"hexsha": "cd857166e2e6794f6a8ccbd36f68cb6660711e93", "size": 893, "ext": "py", "lang": "Python", "max_stars_repo_path": "freeman-cross-section/makesos.py", "max_stars_repo_name": "shiaki/valses-nobles-et-sentimentales", "max_stars_repo_head_hexsha": "f4c7ea1dc7e1bb24008a40dd9d078ccdd91eac50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "freeman-cross-section/makesos.py", "max_issues_repo_name": "shiaki/valses-nobles-et-sentimentales", "max_issues_repo_head_hexsha": "f4c7ea1dc7e1bb24008a40dd9d078ccdd91eac50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "freeman-cross-section/makesos.py", "max_forks_repo_name": "shiaki/valses-nobles-et-sentimentales", "max_forks_repo_head_hexsha": "f4c7ea1dc7e1bb24008a40dd9d078ccdd91eac50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8064516129, "max_line_length": 70, "alphanum_fraction": 0.5879059351, "include": true, "reason": "import numpy,from scipy", "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.19523797227197665}}
{"text": "#!/usr/bin/env python\n# coding=utf-8\n\n__author__ = 'Minglong Li'\n__date__ = 'Nov. 2017'\n\nimport numpy as np\nimport random\nimport math\nimport copy\nimport sys\n''' A Python program using MCTS-UC (Monte Carlo Tree Search with useful cycles) for multi-robot patrol.'''\n\nROBOT_NUM = 2;\n#MCTS scalar.  Larger scalar will increase exploitation, smaller will increase exploration. \nSCALAR= math.sqrt(2.0)\nGLOBAL_ID = 0 #维护一个全局ＩＤ，每个ｎｏｄｅ有且仅有一个独立ＩＤ，包括cyclic_node.\n\n#robot_init_pose: robot_0:[1, 0]; roobt_1:[2, 2]\n#create a map, 0 represents 'free', 1 represents 'obstacle'.  \nclass Map():\n    def __init__(self):\n        self.map = [[0, 0, 1, 0, 0],\n                    [0, 0, 1, 0, 0],\n                    [1, 0, 0, 0, 1],\n                    [0, 1, 0, 1, 0],\n                    [0, 0, 0, 0, 0]]\n        self.horizontal_length = 5\n        self.vertical_length = 5\n     \n    def obstacles_in_map(self):\n        temp_obstacles = []\n        for i in range(self.horizontal_length):\n            for j in range(self.vertical_length):\n                if(self.map[i][j] == 1):\n                    temp_obstacles.append([i,j])\n        return temp_obstacles\n        \n    def random_pose_without_obstacles(self):\n        obstacles = self.obstacles_in_map()\n        while(True):\n            temp_x = random.randint(0, self.horizontal_length-1)\n            temp_y = random.randint(0, self.vertical_length-1)\n            obstacle_flag = False\n            for i in range(len(obstacles)):\n                if(obstacles[i] == [temp_x, temp_y]):\n                    obstacle_flag = True\n                    break\n            if(obstacle_flag == False):\n                return [temp_x, temp_y]    \n               \n    def change_scale(self):\n        pass\n    \n    def add_obstacle(self):\n        pass\n\nclass DynamicIntruder():\n    def __init__(self):\n        self.time_e = 0\n        self.time_step = 0\n        pass #TODO: version 0.0 of mcts_patrol, we use a stationary intruder.    \n    \n    def update_time_step(self):\n        pass\n        \n    def time_e(self):\n        pass\n        \n    def time_e(self):\n        pass\n        \n    def time_p(self):\n        pass\n        \n    def pose(self, time):\n        pass \n    \nclass StationaryIntruder():\n    def __init__(self):\n        self.time_e = random.randint(2,10)#intruder出现的时刻，从第3个时间步开始计算，０，１时刻，ｉｎｔｒｕｄｅｒ机器人肯定不会出现。\n        #从直觉上讲，time_p越大，在一定budget内，捕捉到intruder的概率越大，作者最小设置为９\n        self.time_p = 9#intruder停留的时间为10个时间步。\n        self.time_step = self.time_e\n        self.map = Map()\n        self.pose = self.map.random_pose_without_obstacles()\n        \n    def update_time_step(self):\n        self.time_step = self.time_step + 1\n    \n    def update_initial_pose(self):\n        self.pose = self.map.random_pose_without_obstacles()\n        \n    def get_time_e(self):\n        return self.time_e\n        \n    def get_time_p(self):\n        return self.time_p\n\n    def get_pose(self):\n        return self.pose\n\nclass Node():\n    def __init__(self, actions = None, poses = None, parent = None, time_step = None, map = None, node_ID = None):\n        self.visits = 1#初始化的时候就是为１的，只要ｃｈｉｌｄ被添加上，ｖｉｓｉｔｓ就是１．\n        self.reward = 0.0\t\n        self.children = []\n        self.actions = actions\n        self.poses = poses\n        self.parent = parent\t\n        self.time_step = time_step\n        self.is_cyclic_arm = False\n        self.cyclic_head_ID = None\n        self.node_ID = node_ID\n        \n        if(time_step == None):\n            time_step = 0#default parameter\n        self.map = map\n        if(self.map == None):\n            self.map = Map()#default parameter      \n    \n    #已经检查过的child\n    def add_child(self, child):\n        global GLOBAL_ID\n        temp_child = copy.deepcopy(child)\n        temp_child.node_ID = GLOBAL_ID\n        self.children.append(temp_child) \n        GLOBAL_ID += 1    \n    \n    #根据当前节点的actions和poses算出child_poses,　child_actions经过传参得到,再算出grand_son，检查合法性。\n    def check_and_add_child_actions(self,child_actions):\n        global ROBOT_NUM\n        global GLOBAL_ID\n        #temp_actions = []#temp_actions是个一维数组，维度是robot_num\n        child_poses = []#child_poses是个二维数组,第一个维度是robot_num\n        #子节点的位置是由当前节点的动作和位置决定的，子节点对应的各个机器人动作可以指定。    \n        \n        child_poses = NEXT_POSES(copy.deepcopy(self.actions), copy.deepcopy(self.poses))\n        '''\n        for(i = 0; i < ROBOT_NUM; i+=1):\n            j = self.actions[i]#up, down, left, right\n            if(j == 0):#up\n                child_poses[i][0] = self.poses[0] \n                child_poses[i][1] = self.poses[1] - 1\n            if(j == 1):#down\n                child_poses[i][0] = self.poses[0] \n                child_poses[i][1] = self.poses[1] + 1\n            if(j == 2):#left\n                child_poses[i][0] = self.poses[0] - 1\n                child_poses[i][1] = self.poses[1] \n            if(j == 3):#right\n                child_poses[i][0] = self.poses[0] + 1\n                child_poses[i][1] = self.poses[1]    \n        '''             \n        #因为self节点的上一层节点在add_child的时候，会检测碰撞，所以，当前节点的poses不会有碰撞。  \n        #但是，根据child_poses和指定的child_actions加入grandson节点的poses，就会可能碰撞\n        grandson_poses = []\n        \n        grandson_poses = NEXT_POSES(copy.deepcopy(child_actions), copy.deepcopy(child_poses))\n        '''\n        for(i = 0; i < ROBOT_NUM; i+=1):\n            j = child_actions[i]\n            if(j == 0):#up\n                grandson_poses[i][0] = child.poses[0] \n                grandson_poses[i][1] = child_poses[1] - 1\n            if(j == 1):#down\n                grandson_poses[i][0] = child_poses[0] \n                grandson_poses[i][1] = child_poses[1] + 1\n            if(j == 2):#left\n                grandson_poses[i][0] = child_poses[0] - 1\n                grandson_poses[i][1] = child_poses[1] \n            if(j == 3):#right\n                grandson_poses[i][0] = child_poses[0] + 1\n                grandson_poses[i][1] = child_poses[1]         \n        '''\n        #child节点的位置已经是无碰撞的了，需要用grandson的位置判断是否加入child节点。        \n        bump_flag = self.check_bump(copy.deepcopy(grandson_poses))  \n        if(not bump_flag):\n            temp_child_actions = copy.deepcopy(child_actions)\n            temp_child_poses = copy.deepcopy(child_poses)\n            child = Node(actions = temp_child_actions, poses = temp_child_poses, parent = self, time_step = self.time_step + 1)\n            child.node_ID = GLOBAL_ID\n            self.children.append(child)\n            GLOBAL_ID +=1\n\n    def check_and_add_child_actions_poses(self, child_actions, child_poses):\n        global GLOBAL_ID\n        grandson_poses = NEXT_POSES(child_actions, child_poses)\n        bump_flag = self.check_bump(grandson_poses)\n        if(not bump_flag):\n            temp_child_actions = copy.deepcopy(child_actions)\n            temp_child_poses = copy.deepcopy(child_poses)\n            child = Node(actions = temp_child_actions, poses = temp_child_poses, parent = self, time_step = self.time_step + 1)\n            child.node_ID = GLOBAL_ID\n            self.children.append(child)\n            GLOBAL_ID += 1\n    \n    def check_bump(self, poses):\n        global ROBOT_NUM\n        #bump_flag = False#bump into obstacles, or bump into boundings\n        for i in range(ROBOT_NUM):\n            if(poses[i][0] == -1 or poses[i][0] == self.map.horizontal_length):#bump into left or right boundings\n                #bump_flag = True\n                #break\n                return True\n            if(poses[i][1] == -1 or poses[i][1] == self.map.vertical_length):#bump into up or down boundings\n                #bump_flag = True\n                #break\n                return True\n            else:\n                obstacles = self.map.obstacles_in_map()#a list storing the coordinates of the obstacles\n                for j in range(len(obstacles)):\n                    if poses[i] == obstacles[j]:\n                    #if(poses[i][0] == obstacles[j][0] and poses[i][1] == obstacles[j][1]):\n                        #bump_flag == True\n                        #break\n                        return True\n                #break\n        #return bump_flag\n        return False\n        \n    def update(self,reward):\n        self.reward+=reward\n        self.visits+=1\n    \n    def ucb(self):\n        visits_parent = self.parent.visits\n        visits_child = self.visits\n        w_pi = self.reward\n        return w_pi + SCALAR * math.sqrt(math.log(visits_parent/visits_child))\n    \n    def create_cyclic_sibling_arm(self, cyclic_head_ID):\n        global GLOBAL_ID\n        temp_parent = self.parent\n        new_node = copy.deepcopy(self)\n        new_node.cyclic_head_ID = cyclic_head_ID\n        new_node.is_cyclic_arm = True\n        new_node.visits = 1\n        new_node.node_ID = GLOBAL_ID\n        temp_parent.children.append(new_node)\n        GLOBAL_ID += 1\n    \n    def get_is_cyclic_arm(self):\n        return self.is_cyclic_arm\n        \n    def node_equal(self, other):\n        self_node_ID = self.node_ID\n        other_node_ID = other.node_ID\n        \n        if(self_node_ID == other_node_ID):\n            return True\n        else:\n            return False\n  \n    \n    def is_fully_expanded(self):\n        #To be verified: Version 0 of mucts_patrol, all of the nodes are fully expanded\n        pass       \n\n#global functions\n#UCT search\n#def SELECT(budget, root):\n#TODO:关于深度拷贝的检查，看到了这里。\ndef SELECT(root):\n    #pass\n    selected_node = Node()\n    global_ucb = 0\n    temp_ucb = 0\n    temp_children = root.children #'children' is a list\n    #print \"244: SELECT 1\"\n    while(len(temp_children) != 0):\n        #print \"246: SELECT while\"\n        for i in range(len(temp_children)):\n            '''\n            print \"248: SELECT for\"\n            print \"temp_ucb: \"\n            print temp_children[i].parent.visits\n            print temp_children[i].visits\n            print temp_children[i].reward\n            '''            \n            temp_ucb = temp_children[i].ucb()\n            #print temp_ucb\n            if(global_ucb < temp_ucb or global_ucb == temp_ucb):\n                #print \"SELECT if\"\n                global_ucb = temp_ucb\n                selected_node = temp_children[i]\n        #如果始终找不到比当前ｕｃｂ还小的，那么temp_children应该就是不发生变化的？\n        #print \"SELECT 2\"        \n        temp_children = selected_node.children#TODO:还是这里存在问题，一直下去肯定是一个Ｎｏｎｅ。２１点４２分。\n        #len(temp_children)　等于０的时候不就跳出了吗？此时Ｓｅｌｅｃｔｅｄ应该不是０啊。\n        global_ucb = 0#TODO:这里对吗？很有可能是个雷啊。\n        #print \"len(temp_children):\"\n        #print len(temp_children)\n    return selected_node   \n  \ndef ITERATIVE_LOOP(temp_node, cycles, temp_actions):\n    global ROBOT_NUM\n    cycles -= 1\n    index = ROBOT_NUM - cycles -1\n \n    if(cycles==-1):\n        return \n    else:\n        if(cycles == 0):\n            for i in range(4):\n                temp_actions[index] = i\n                temp_node.check_and_add_child_actions(child_actions = temp_actions);\n        else:\n            for i in range(4):\n                temp_actions[index] = i\n                ITERATIVE_LOOP(temp_node, cycles, temp_actions)\n                              \n#fully expand the node\ndef EXPAND(node):\n    global ROBOT_NUM\n    temp_actions = []\n    for i in range(ROBOT_NUM):\n        temp_actions.append(-1)   \n    ITERATIVE_LOOP(node, ROBOT_NUM, temp_actions)\n    i = random.randint(0, len(node.children)-1)\n    return node.children[i]\n\ndef NEXT_POSES(actions, poses):\n    child_poses = []\n    for index in range(ROBOT_NUM):\n        child_poses.append([0,0])\n    #print child_poses\n    #print child_poses[0][0]\n    #print actions[0]\n    #print poses[0]\n    for i in range(ROBOT_NUM):\n        j = actions[i]#up, down, left, right\n        if(j == 0):#up\n            child_poses[i][0] = poses[i][0] \n            child_poses[i][1] = poses[i][1] + 1\n        if(j == 1):#down\n            child_poses[i][0] = poses[i][0] \n            child_poses[i][1] = poses[i][1] - 1\n        if(j == 2):#left\n            child_poses[i][0] = poses[i][0] - 1\n            child_poses[i][1] = poses[i][1] \n        if(j == 3):#right\n            child_poses[i][0] = poses[i][0] + 1\n            child_poses[i][1] = poses[i][1]  \n    return child_poses \n\ndef ITERATIVE_LOOP_ROOT_CHILD_ACTION(root, cycles, child_poses, child_actions):\n    global ROBOT_NUM\n    cycles -= 1\n    index = ROBOT_NUM - cycles - 1\n\n    if cycles == -1:\n        return \n    else:\n        if cycles == 0:\n            for i in range(4):\n                child_actions[index] = i\n                #if bump, not add. if not bump, add.\n                root.check_and_add_child_actions_poses(child_actions, child_poses)            \n        else:\n            for i in range(4):\n                child_actions[index] = i\n                ITERATIVE_LOOP_ROOT_CHILD_ACTION(root, cycles, child_poses, child_actions)\n\n#root节点的初始化当中，action为空，poses是初始化指定的值。\ndef ITERATIVE_LOOP_ROOT_ACTION(root, cycles, root_actions):\n    global ROBOT_NUM\n    cycles -= 1\n    index = ROBOT_NUM - cycles - 1\n    count_num = 0\n    #print \"cycles in ITERATIVE_LOOP_ROOT_ACTION: \"\n    #print cycles\n    #print \"index in ITERATIVE_LOOP_ROOT_ACTION: \"\n    #print index\n    if(cycles == -1):\n        return\n    else:\n        if(cycles == 0):\n            for i in range(4):\n                #print \"count_num:\"\n                #print count_num\n                #print \"index in if part: \"\n                #print index\n                count_num +=1\n                root_actions[index] = i\n                #print \"root_actions in if part:\"\n                print root_actions\n                child_poses = NEXT_POSES(root_actions, root.poses)\n                #print \"child_poses\"\n                #print child_poses\n                bump_flag = root.check_bump(child_poses)\n                #print \"bump_flag\"\n                #print bump_flag\n                if bump_flag == True:\n                    pass#检查合法性，如果不合法，continue。\n                elif(bump_flag == False):\n                    child_actions = []\n                    for i in range(ROBOT_NUM):\n                        child_actions.append(-1)\n                    ITERATIVE_LOOP_ROOT_CHILD_ACTION(root=root, cycles=ROBOT_NUM, child_poses=child_poses,child_actions = child_actions)\n        else:\n            for i in range(4):\n                #print \"index in else part: \"\n                #print index\n                root_actions[index] = i\n                #print \"root_actions in else part: \"\n                #print root_actions\n                ITERATIVE_LOOP_ROOT_ACTION(root, cycles, root_actions)\n\ndef EXPAND_ROOT(root):\n    global ROBOT_NUM\n    root_actions = []\n    for i in range(ROBOT_NUM):\n        root_actions.append(-1)\n    ITERATIVE_LOOP_ROOT_ACTION(root, ROBOT_NUM, root_actions)\n    i = random.randint(0, len(root.children)-1)\n    return root.children[i]\n\n'''\n#TODO:根据loop的逻辑写两个ITERATIVE LOOP\ndef loop(cycles):\n    for a0 in range(4):\n        for a1 in range(4):\n            for a2 in range(4):\n   　    　　　　    root_actions[0] = a0\n   　    　　　　    root_actions[1] = a1\n   　    　　　　    root_actions[2] = a2\n   　    　　　　    root_poses = [[1,1],[2,2]]   　    　　　　    \n   　    　　　　    child_poses = function(root_actions, root_poses)\n                #对于root的话，CHILD_POSES在这里也要检查吗？\n   　    　　　　    \n                for b0 in range(4):\n                    for b1 in range(4):\n                        for b2 in range(4):   　    　　　　    \n                       　    child_actions[0] = a0\n               　    　　　　    child_actions[1] = a1\n               　    　　　　    child_actions[2] = a2 　    　　　　    \n               　    　　　　    \n               　    　　　　       　    　　　　    \n               　    　　　　    grandson_poses = function2(child_actions, child_poses);\n               　    　　　　    bump_flag = check_bump(grandson_poses)\n               　    　　　　    \n               　    　　　　    if bump_flag == False\n               　    　　　　        add_child(child_poses, child_actions)\n   　\n    for a0 in range(4):\n       　root_actions[0] = a0\n        for a1 in range(4):\n           　root_actions[1] = a1\n            for a2 in range(4):\n                root_actions[2] = a2  \n                add_child(root_actions)\n                \n                print root_actions 　\n''' \n\ndef RANDOM_ROLLOUT_FOR_ONE_STEP(actions, poses):\n    global ROBOT_NUM\n    map = Map()\n    current_actions = actions\n    current_poses = poses\n    \n    next_actions = []\n    next_poses = []\n    \n    obstacles =  map.obstacles_in_map()\n        \n    for i in range(ROBOT_NUM):\n        if(current_actions[i] == 0):#up\n            next_poses.append( [current_poses[i][0], current_poses[i][1]-1] )\n        if(current_actions[i] == 1):#down\n            next_poses.append( [current_poses[i][0], current_poses[i][1]+1] )                  \n        if(current_actions[i] == 2):#left\n            next_poses.append( [current_poses[i][0]-1, current_poses[i][1]] )               \n        if(current_actions[i] == 3):#right\n            next_poses.append( [current_poses[i][0]+1, current_poses[i][1]] )        \n                   \n    for i in range(ROBOT_NUM):\n        while(True):\n            temp_poses = [0,0]\n            random_action = random.randint(0, 3)            \n            if(random_action == 0):#up\n                temp_poses[0] = next_poses[i][0]\n                temp_poses[1] = next_poses[i][1] + 1\n            if(random_action == 1):#down\n                temp_poses[0] = next_poses[i][0]\n                temp_poses[1] = next_poses[i][1] - 1   \n            if(random_action == 2):#left\n                temp_poses[0] = next_poses[i][0] - 1\n                temp_poses[1] = next_poses[i][1]         \n            if(random_action == 3):#right\n                temp_poses[0] = next_poses[i][0] + 1\n                temp_poses[1] = next_poses[i][1]\n            obstacle_flag = False\n            for j in range(len(obstacles)):\n                if(temp_poses == obstacles[j]):\n                    obstacle_flag = True\n                    break\n            if(obstacle_flag == False):\n                next_actions.append(random_action)\n                break\n    return next_actions, next_poses                        \n\ndef PERFORM_CYCLIC_ACTIONS(node, intruder):\n    time_e = intruder.get_time_e()\n    time_p = intruder.get_time_p()\n    intruder_pose = intruder.get_pose()\n    \n    #status of the node to be evaluated\n    temp_time_step = node.time_step\n    #temp_poses = node.poses \n    \n    #temp_node = node.parent\n    temp_node = node    \n    head_mark_node_ID = node.cyclic_head_ID\n    #指针赋值＃TODO: TO BE REVISED>\n    head_mark_node = node\n    #arm_mark_node = node\n    \n    poses_buffer = []\n    poses_buffer.append(temp_poses)\n    while(not temp_node.node_equal(head_mark_node)):\n        poses_buffer.append(temp_node.poses)        \n        temp_node = temp_node.parent\n        \n    index = 0    \n    index_increase_flag = True\n    while(True):\n        win_flag = False\n        for i in range(len(poses_buffer[index])):\n            if poses_buffer[index][i] == intruder_pose:\n                win_flag = True\n                break\n        if temp_time_step < time_e + time_p:\n            if win_flag == True:\n                return 1\n        elif temp_time_step == time_e + time_p:        \n            if win_flag == True:\n                return 1\n            elif win_flag == False:\n                return 0\n        \n        if(index_increase_flag):\n            index +=1\n            temp_time_step+=1\n            if index == len(poses_buffer):\n                index-=1\n                temp_time_step-=1\n                index_increase_flag = False\n        elif(not index_increase_flag):\n            index -= 1\n            temp_time_step+=1\n            if index == -1:\n                index+=2\n                index_increase_flag = True\n            \ndef ROLLOUT(node, intruder):\n    #有两个前提：\n    #第一个前提是当前ｎｏｄｅ上层的ｎｏｄｅ一定不是终止节点，ｓｅｌｅｃｔ和ｒｏｌｌｏｕｔ的都不是终止节点，只有当前ｎｏｄｅ和之后的ｎｏｄｅ可能是终止节点。\n    #第二个前提是当前ｎｏｄｅ是经过ｅｘｐａｎｄ选出来的唯一一个待评估节点。\n    #status of the intruder\n    time_e = intruder.get_time_e()\n    time_p = intruder.get_time_p()\n    intruder_pose = intruder.get_pose()\n    #status of the node to be evaluated\n    temp_time_step = node.time_step\n    temp_actions = node.actions\n    temp_poses = node.poses    \n    \n    next_actions = temp_actions\n    next_poses = temp_poses\n    \n    #print \"rollout 1\"\n    \n    if(node.get_is_cyclic_arm() == True):\n        #print \"rollout 2\"\n        return PERFORM_CYCLIC_ACTIONS(node, intruder)\n    else:\n        #print \"rollout 3\"\n        while(True):\n            #print \"rollout 4\"\n            win_flag = False\n            for i in range(len(next_poses)):\n                if(next_poses[i] == intruder_pose):\n                    win_flag = True\n                    break\n            #if the intruder completing intruding or capture the intruder\n            if(temp_time_step < time_e + time_p):\n                if win_flag == True:\n                    return 1\n                elif win_flag == False:\n                    #侵入完成时间也没到，机器人也没找着，继续搜索,TODO:一个idea，是否把找到的时间也算在内呢？\n                    temp_time_step += 1\n                    next_actions, next_poses = RANDOM_ROLLOUT_FOR_ONE_STEP(next_actions, next_poses)\n            elif(temp_time_step == time_e + time_p):#入侵完成时间到了\n                if(win_flag == True):\n                    return 1\n                elif(win_flag == False):\n                    return 0\n\n\ndef ONE_EQUAL_IN_LIST_DEL(list_0, list_1):\n    equal_flag = False\n    for i in range(len(list_0)):\n        for j in range(len(list_1)):\n            if(list_0[i] == list_1[j]):\n                del list_0[i]\n                del list_1[j]\n                equal_flag = True\n                return list_0, list_1                \n    if(equal_flag == False):\n        list_0[0] = \"none\"\n        return list_0, list_1\n        \n#只需要node_0和node_1当中的所有的机器人的位置都有一一相等的，不用顺序相等。    　　　\ndef STATUS_EQUAL(node_0, node_1):\n    global ROBOT_NUM\n    poses_0 = []\n    poses_1 = []\n    for i in range(ROBOT_NUM):\n        poses_0.append(node_0.poses[i])\n        poses_1.append(node_1.poses[i])\n    #poses_0 = node_0.poses\n    #poses_1 = node_1.poses\n    if(len(poses_0) != len(poses_1)):\n        return False\n    else:    \n        equal_flag = False\n        while(True):\n            poses_0, poses_1 = ONE_EQUAL_IN_LIST_DEL(poses_0, poses_1)\n            if(len(poses_0) == 0 and len(poses_1) == 0):\n                return True\n            if(poses_0[0] == \"none\"):\n                return False\n                #TODO:对应的ｉ个机器人的概念在这里没有考虑，索引号没有加进来。\n                \ndef BACK_PROPAGATION(leaf_node, reward):\n    leaf_node.update(reward)\n    temp_node = leaf_node.parent\n\n    while(True):\n        if(STATUS_EQUAL(temp_node, leaf_node)):\n            temp_node_ID = temp_node.node_ID\n            leaf_node.create_cyclic_sibling_arm(cyclic_head_ID = temp_node_ID)#it is an arm\n        temp_node.update(reward)\n        temp_node = temp_node.parent\n        if temp_node == None:\n            break\n\ndef IS_INTRUDER_CAPTURED(node, intruder):\n    temp_poses = node.poses;\n    intruder_pose = intruder.pose\n    win_flag = False\n    for i in range(len(temp_poses)):\n        if(temp_poses[i] == intruder_pose):\n            win_flag = True\n            break\n    if win_flag:\n        return True\n    else:\n        return False\n\n        \nif __name__==\"__main__\":\n    map = Map()\n    intruder = StationaryIntruder()\n    BUDGET = 100000;\n    reward = 0.0;\n    #初始的机器人的位置是(1, 0), (1, 1)\n    root = Node(actions = None, poses = [[1,0],[1,1]], parent = None, time_step = 0, map = map)\n    root.node_ID = -1    \n    print \"Hello 1\"\n    EXPAND_ROOT(root)   \n    \n    #print len(root.children)\n    print len(root.children)  \n    \n    cycle_count = 0\n    print \"Hello 2\"\n    while(cycle_count < BUDGET):\n        print \"Hello 3\"\n        leaf_node = SELECT(root)#TODO:这里需要判断node是不是时间终止节点。\n        '''\n        print \"639, leaf_node.actions: \"\n        print leaf_node.actions\n        print \"641, leaf_node.poses: \"\n        print leaf_node.poses\n        '''    \n        print \"Hello 4\"\n        if leaf_node.time_step == intruder.time_e + intruder.time_p:\n            print \"Hello 5\"\n            if IS_INTRUDER_CAPTURED(leaf_node, intruder) == True:\n                reward = 1\n            else:\n                reward = 0\n            BACK_PROPAGATION(leaf_node, reward)    \n        elif leaf_node.time_step < intruder.time_e + intruder.time_p:    \n            print \"Hello 6\"\n            if leaf_node.get_is_cyclic_arm():\n                print \"Hello 7\"\n                reward = ROLLOUT(leaf_node, intruder)\n                BACK_PROPAGATION(leaf_node, reward)\n            else:\n                \n                print \"Hello 8\"\n                \n                print \"664, leaf_node.actions: \"\n                print leaf_node.actions\n                print \"666, leaf_node.poses: \"\n                print leaf_node.poses\n                \n\n                added_node = EXPAND(leaf_node)#TODO:测试过程中，这一步极其花费时间。？？？？？？？？\n                #TODO：leaf_node是不是一定不是cyclic arm？？？？？？？？？？？\n                print len(leaf_node.children)#只有12的是肯定不对的。\n                print \"Hello 9\"\n                reward = ROLLOUT(added_node, intruder)\n                print \"Hello 10\"\n                BACK_PROPAGATION(added_node, reward)\n                print \"Hello 11\"\n        elif leaf_node.time_step > intruder.time_e + intruder.time_p:\n            print \"程序异常，异常点标号为１\"           \n        intruder.update_initial_pose()\n        print \"cycle_count :\"\n        print cycle_count\n        cycle_count += 1\n        \n\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n", "meta": {"hexsha": "16001e766f06c7833139bf981e7f73625464bed1", "size": 25412, "ext": "py", "lang": "Python", "max_stars_repo_path": "mcts_patrol.py", "max_stars_repo_name": "liminglong/dynamic_task_plan", "max_stars_repo_head_hexsha": "6974917db7ddacc16c181ede1aeb175b634ad7ec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-12-16T01:24:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-28T01:37:48.000Z", "max_issues_repo_path": "mcts_patrol.py", "max_issues_repo_name": "liminglong/dynamic_task_plan", "max_issues_repo_head_hexsha": "6974917db7ddacc16c181ede1aeb175b634ad7ec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mcts_patrol.py", "max_forks_repo_name": "liminglong/dynamic_task_plan", "max_forks_repo_head_hexsha": "6974917db7ddacc16c181ede1aeb175b634ad7ec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-20T16:12:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T16:12:32.000Z", "avg_line_length": 33.6137566138, "max_line_length": 136, "alphanum_fraction": 0.5438375571, "include": true, "reason": "import numpy", "num_tokens": 7015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.19523796842054864}}
{"text": "# Generate adversarial examples for EAT\n\nimport numpy as np\nimport tensorflow as tf\n\n\n\ndef gen_examples_fgs(discriminator, train_data, config):\n    x = train_data[0]\n    x = 2.0*x - 1.0\n\n    epsilon = config['epsilon']\n    d_out = discriminator(x)\n    y = tf.stop_gradient(tf.argmax(d_out, 1))\n    d_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n        logits=d_out, labels=tf.one_hot(y,10)))\n\n    grad_x, = tf.gradients(d_loss, x)\n    x_adv = tf.stop_gradient(x + epsilon*tf.sign(grad_x))\n    x_adv = tf.clip_by_value(x_adv, -1.0, 1.0)\n\n    x_adv = (x_adv+1.0)/2.0\n\n    return x_adv\n\n\n# least likely class\ndef gen_examples_ll(discriminator, train_data, config):\n    x = train_data[0]\n    x = 2.0*x - 1.0\n    epsilon = config['epsilon']\n\n    d_out = discriminator(x)\n    yhat = tf.stop_gradient(tf.argmin(d_out, 1))\n\n    d_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n        logits=d_out, labels=tf.one_hot(yhat,10)))\n\n    grad_x, = tf.gradients(d_loss, x)\n    x_adv = tf.stop_gradient(x - epsilon*tf.sign(grad_x))\n    x_adv = tf.clip_by_value(x_adv, -1.0, 1.0)\n\n    x_adv = (x_adv+1.0)/2.0\n\n    return x_adv\n\n\ndef gen_examples_pgd(discriminator, train_data, config):\n    x0 = train_data[0]\n\n    x0 = 2.0*x0 - 1.0\n    y = train_data[1]\n    epsilon = config['epsilon']\n    class_num = config['class_num']\n    pgd_iter = config['pgd_iter']\n\n    step_size = epsilon*0.25\n\n    # randomize\n    x = x0 + tf.random_uniform(x0.shape, -epsilon, epsilon)\n    for i in range(pgd_iter):\n        d_out = discriminator(x)\n        d_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n            logits=d_out, labels=tf.one_hot(y,class_num)))\n\n        grad_x, = tf.gradients(d_loss, x)\n        x = tf.stop_gradient(x + step_size*tf.sign(grad_x))\n        x = tf.clip_by_value(x, x0 - epsilon, x0 + epsilon)\n        x = tf.clip_by_value(x, -1.0, 1.0)\n\n    x_adv = (x+1.0)/2.0\n\n    return x_adv\n\n\n# one model def for one model filename\ndef gen_adv_examples(discriminator, ckpt_filename, train_data, test_data, config):\n\n    batch_size = config['batch_size']\n    x_fgs = gen_examples_fgs(discriminator, train_data, config)\n    x_pgd = gen_examples_pgd(discriminator, train_data, config)\n    x_ll = gen_examples_ll(discriminator, train_data, config)\n\n    var_list = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='discriminator')\n    saver = tf.train.Saver(var_list)\n\n    global_step = tf.Variable(0, trainable=False)\n    global_step_op = global_step.assign_add(1)\n\n    time_diff = tf.placeholder(tf.float32)\n    Wall_clock_time = tf.Variable(0., trainable=False)\n    update_Wall_op = Wall_clock_time.assign_add(time_diff)\n\n\n    #with sv.managed_session() as sess:\n    with tf.Session() as sess:\n        sess.run(tf.global_variables_initializer())\n\n        coord = tf.train.Coordinator()\n        threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n\n        saver.restore(sess, ckpt_filename)\n\n\n        train_size = config['train_size']\n        samples_fgs, samples_pgd, samples_ll, x, y = sess.run([x_fgs, x_pgd, x_ll, train_data[0], train_data[1]])\n\n        num_steps = int(train_size/batch_size)\n        my_dim = list(samples_fgs.shape)\n        my_dim = [my_dim[0]*4*num_steps] + my_dim[1:]\n        examples = np.zeros(my_dim)\n        labels = np.zeros(4*num_steps*batch_size)\n        i=0\n        examples[(4*i*batch_size):((4*i+1)*batch_size),:,:,:] = samples_fgs\n        examples[((4*i+1)*batch_size):((4*i+2)*batch_size),:,:,:] = samples_pgd\n        examples[((4*i+2)*batch_size):((4*i+3)*batch_size),:,:,:] = samples_ll\n        examples[((4*i+3)*batch_size):((4*i+4)*batch_size),:,:,:] = x\n\n        labels[(4*i*batch_size):((4*i+1)*batch_size)] = y\n        labels[((4*i+1)*batch_size):((4*i+2)*batch_size)] = y\n        labels[((4*i+2)*batch_size):((4*i+3)*batch_size)] = y\n        labels[((4*i+3)*batch_size):((4*i+4)*batch_size)] = y\n\n        for i in range(1, num_steps):\n            samples_fgs, samples_pgd, samples_ll, x, y = sess.run([x_fgs, x_pgd, x_ll, train_data[0], train_data[1]])\n\n            examples[(4*i*batch_size):((4*i+1)*batch_size),:,:,:] = samples_fgs\n            examples[((4*i+1)*batch_size):((4*i+2)*batch_size),:,:,:] = samples_pgd\n            examples[((4*i+2)*batch_size):((4*i+3)*batch_size),:,:,:] = samples_ll\n            examples[((4*i+3)*batch_size):((4*i+4)*batch_size),:,:,:] = x\n\n            labels[(4*i*batch_size):((4*i+1)*batch_size)] = y\n            labels[((4*i+1)*batch_size):((4*i+2)*batch_size)] = y\n            labels[((4*i+2)*batch_size):((4*i+3)*batch_size)] = y\n            labels[((4*i+3)*batch_size):((4*i+4)*batch_size)] = y\n\n\n\n        # test data\n        test_size = config['test_size']\n        num_test_steps = int(test_size/batch_size)\n        x_test, y_test = sess.run([test_data[0], test_data[1]])\n        test_dim = list(x_test.shape)\n        test_dim = [num_test_steps*batch_size]+test_dim[1:]\n        test_examples = np.zeros(test_dim)\n        test_labels = np.zeros(num_test_steps*batch_size)\n        i = 0\n        test_examples[(i*batch_size):((i+1)*batch_size),:,:,:] = x_test\n        test_labels[(i*batch_size):((i+1)*batch_size)] = y_test\n\n        for i in range(1, num_test_steps):\n            x_test, y_test = sess.run([test_data[0], test_data[1]])\n            test_examples[(i*batch_size):((i+1)*batch_size),:,:,:] = x_test\n            test_labels[(i*batch_size):((i+1)*batch_size)] = y_test\n\n\n        coord.request_stop()\n        #sess.run(model.queue.close(cancel_pending_enqueues=True))\n        coord.join(threads)\n\n    # save numpy examples\n    np.savez(config['sample_file'], examples=examples, labels=labels)\n    np.savez(config['test_sample_file'], examples=test_examples, labels=test_labels)\n\n\n\n\n\n", "meta": {"hexsha": "aabcfc274bad15d68c9ea42a46324256fd0f4716", "size": 5728, "ext": "py", "lang": "Python", "max_stars_repo_path": "cifar10/adversarial_networks/gen_static_adversarial_examples.py", "max_stars_repo_name": "whxbergkamp/RobustDL_GAN", "max_stars_repo_head_hexsha": "a622faf1c7d5e803bca3091dd035c616b5736bd7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2019-02-27T12:37:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-19T04:08:36.000Z", "max_issues_repo_path": "cifar10/adversarial_networks/gen_static_adversarial_examples.py", "max_issues_repo_name": "whxbergkamp/RobustDL_GAN", "max_issues_repo_head_hexsha": "a622faf1c7d5e803bca3091dd035c616b5736bd7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-06-28T21:51:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-19T08:08:50.000Z", "max_forks_repo_path": "cifar10/adversarial_networks/gen_static_adversarial_examples.py", "max_forks_repo_name": "whxbergkamp/RobustDL_GAN", "max_forks_repo_head_hexsha": "a622faf1c7d5e803bca3091dd035c616b5736bd7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-04-07T08:18:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T00:45:19.000Z", "avg_line_length": 33.8934911243, "max_line_length": 117, "alphanum_fraction": 0.6337290503, "include": true, "reason": "import numpy", "num_tokens": 1680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.19523796456912063}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*\n\n\"\"\"\ndecomp module\n\"\"\"\n\n__author__ = 'Dr. Janus Juul Eriksen, University of Bristol, UK'\n__license__ = 'MIT'\n__version__ = '0.8'\n__maintainer__ = 'Dr. Janus Juul Eriksen'\n__email__ = 'janus.eriksen@bristol.ac.uk'\n__status__ = 'Development'\n\nimport numpy as np\nfrom pyscf import gto\nfrom typing import List, Dict, Union, Any\n\n\n# component keys\nCOMP_KEYS = ['coul', 'exch', 'kin', 'solvent', 'nuc_att_glob', 'nuc_att_loc', 'nuc_att', 'xc', 'el', 'struct']\n\nclass DecompCls(object):\n        \"\"\"\n        this class contains all decomp attributes\n        \"\"\"\n        def __init__(self, loc: str = '', pop: str = 'mulliken', \\\n                     part = 'atoms', ndo: bool = False, multiproc: bool = False, \\\n                     gauge_origin: Union[List[Any], np.ndarray] = np.zeros(3), \\\n                     prop: str = 'energy', write: str = '', verbose: int = 0) -> None:\n                \"\"\"\n                init molecule attributes\n                \"\"\"\n                # set system defaults\n                self.loc = loc\n                self.pop = pop\n                self.part = part\n                self.ndo = ndo\n                self.multiproc = multiproc\n                self.gauge_origin = gauge_origin\n                self.prop = prop\n                self.write = write\n                self.verbose = verbose\n                # set internal defaults\n                self.res: Dict[str, np.ndarray] = {comp_key: None for comp_key in COMP_KEYS}\n                self.charge_atom: np.ndarray = None\n                self.dist: np.ndarray = None\n                self.weights: np.ndarray = None\n                self.centres: np.ndarray = None\n\n\ndef sanity_check(mol: gto.Mole, decomp: DecompCls) -> None:\n        \"\"\"\n        this function performs sanity checks of decomp attributes\n        \"\"\"\n        # localization procedure\n        assert decomp.loc in ['', 'fb', 'pm', 'ibo-2', 'ibo-4'], \\\n            'invalid localization procedure. valid choices: none (default), `fb`, `pm`, `ibo-2`, and `ibo-4`'\n        # population scheme\n        assert decomp.pop in ['mulliken', 'iao'], \\\n            'invalid population scheme. valid choices: `mulliken` (default) or `iao`'\n        # partitioning\n        assert decomp.part in ['atoms', 'eda', 'orbitals'], \\\n            'invalid partitioning. valid choices: `atoms` (default), `eda`, or `orbitals`'\n        # ndo decomposition\n        assert isinstance(decomp.ndo, bool), \\\n            'invalid ndo argument. must be a bool'\n        # multiprocessing\n        assert isinstance(decomp.multiproc, bool), \\\n            'invalid multiprocessing argument. must be a bool'\n        # gauge origin\n        assert isinstance(decomp.gauge_origin, (list, np.ndarray)), \\\n            'invalid gauge origin. must be a list or numpy array of ints/floats'\n        # property\n        assert decomp.prop in ['energy', 'dipole'], \\\n            'invalid property. valid choices: `energy` (default) and `dipole`'\n        # write\n        assert isinstance(decomp.write, str), \\\n            'invalid write format argument. must be a str'\n        assert decomp.write in ['', 'cube', 'numpy'], \\\n            'invalid write format. valid choices: `cube` and `numpy`'\n        # verbosity\n        assert isinstance(decomp.verbose, int), \\\n            'invalid verbosity. valid choices: 0 <= `verbose` (default: 0)'\n        assert 0 <= decomp.verbose, \\\n            'invalid verbosity. valid choices: 0 <= `verbose` (default: 0)'\n\n\n", "meta": {"hexsha": "13a7c71e31368cfb94c2edfcadfe624a90cbc20f", "size": 3496, "ext": "py", "lang": "Python", "max_stars_repo_path": "decodense/decomp.py", "max_stars_repo_name": "luna-component/decodense", "max_stars_repo_head_hexsha": "2579b7a3b7500b32ab231ebacb35c91e87e96735", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "decodense/decomp.py", "max_issues_repo_name": "luna-component/decodense", "max_issues_repo_head_hexsha": "2579b7a3b7500b32ab231ebacb35c91e87e96735", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "decodense/decomp.py", "max_forks_repo_name": "luna-component/decodense", "max_forks_repo_head_hexsha": "2579b7a3b7500b32ab231ebacb35c91e87e96735", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2808988764, "max_line_length": 110, "alphanum_fraction": 0.5612128146, "include": true, "reason": "import numpy", "num_tokens": 856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.19522597421863325}}
{"text": "\"\"\" Tools for parsing Line List data\n\"\"\"\nfrom __future__ import print_function, absolute_import, division, unicode_literals\n\nimport numpy as np\nimport os, imp, glob, pdb, gzip, sys\nif not sys.version_info[0] > 2:\n    import codecs\n    open = codecs.open\n\nfrom astropy import units as u\nfrom astropy.units.quantity import Quantity\nfrom astropy.io import fits, ascii\nfrom astropy.table import Column, Table, vstack\n\nfrom ..abund import roman, ions\nfrom ..abund.elements import ELEMENTS\n\nlt_path = imp.find_module('linetools')[1]\n\n\n# TODO\n# Ingest AGN lines\n# Add Ej, Ek, Ex for emission lines (specially Balmer, Paschen and Brackett)\n\n#\ndef line_data(nrows=1):\n    \"\"\" Defines the dict (and/or Table) for spectral line Data\n\n    Parameters\n    ----------\n    nrows : int, optional\n      Number of rows in Table [default = 1]\n\n    Notes\n    -----\n    Group definition:\n       *    0: None\n       *    1: \"All\" ISM (intended to be all atomic lines ever observed)\n       *    2: Strong ISM\n       *    4: HI Lyman series\n       *    8: H2\n       *   16: CO\n       *   32: EUV\n       *   64: Galaxy Emission\n       *  128: Galaxy Absorption\n       *  256: AGN\n       *  512: ??\n       * 1024: User1 (Reserved)\n       * 2048: User2 (Reserved)\n    \"\"\"\n    ldict = {\n        'name': ' '*20,       # Name\n        'wrest': 0.*u.AA,     # Rest Wavelength (Quantity)\n        'f':  0.,             # Oscillator strength\n        'Ej': 0./u.cm,        # Energy of lower level (relative to ground state)\n        'Ek': 0./u.cm,        # Energy of upper level (relative to ground state)\n        'Ex': 0./u.cm,        # Excitation energy (cm^-1)\n        'A': 0./u.s,          # Einstein coefficient\n        'gj': 0,              # Lower statistical weight (2J+1)\n        'gk': 0,              # Upper statistical weight (2J+1)\n        'gamma': 0./u.s,      # Sum of A\n        'nj': 0,              # Orbital level of lower state (or vibrational level)\n        'nk': 0,              # Orbital level of upper state (or vibrational level)\n        'Jj': 0.,             # Tot ang mom (z projection) of lower state (or rotation level)\n        'Jk': 0.,             # Tot ang mom (z projection) of upper state (or rotation level)\n        'el': 0,              # Electronic transition (2=Lyman (B-X), 3=Werner (C-X)) \n        'Z': 0,               # Atomic number (for atoms)\n        'Am': 0,              # Mass number (often written as \"A\"; only used for D)\n        'ion': 0,             # Ionic state (1=Neutral)\n        'mol': ' '*10,        # Molecular name (H2, HD, CO, C13O)\n        'Ref': ' '*50,        # References\n        'group': 0            # Flag for grouping\n        }\n\n    # Table\n    clms = []\n    for key in ldict.keys():\n        if type(ldict[key]) is Quantity:\n            clm = Column( ([ldict[key].value]*nrows), name=key)\n            clm.unit = ldict[key].unit\n        else:\n            clm = Column( [ldict[key]]*nrows, name=key)\n        # Append\n        clms.append(clm)\n\n    # make it a masked Table so we can deal with Galaxy\n    # emission and ISM absorption simultaneously by masking\n    # out what does not make sense in one case or the other\n    tbl = Table(clms, masked=True)\n    # import pdb\n    # pdb.set_trace()\n\n    return ldict, tbl\n\n\ndef read_sets(infil=None):\n    \"\"\" Read sets file\n\n    Parameters\n    ----------\n    infil : str, optional\n      Set file\n    \"\"\"\n    if infil is None:\n        fils = glob.glob(lt_path+'/lists/sets/llist_v*')\n        fils.sort()\n        infil = fils[-1] # Should grab the lateset\n    # Read\n    print('read_sets: Using set file -- \\n  {:s}'.format(infil))\n    set_data = ascii.read(infil, format='fixed_width')\n\n    # Return\n    return set_data\n\n\ndef read_euv():\n    \"\"\" read additional EUV lines\n\n    Returns\n    -------\n    Table of EUV lines\n    \"\"\"\n    EUV_fil = lt_path + '/data/lines/EUV_lines.ascii'\n    print('linetools.lists.parse: Reading linelist --- \\n   {:s}'.format(EUV_fil))\n    data = Table.read(EUV_fil, format='ascii', guess=False, comment=';',delimiter='|')\n\n    # Units\n    data['wrest'].unit = u.AA\n\n    # Return\n    return data\n\n\ndef read_H2():\n    \"\"\" Simple def to read H2 data\n\n    Returns\n    -------\n    Table of H2 lines\n\n    References\n    ----------\n    * Abgrall et al. 1993, A&AS, 101, 323\n    * Abgrall et al. 1993, A&AS, 101, 273\n\n    Kindly provide by co-author E. Roueff to JC Howk to JXP\n\n    \"\"\"\n    H2_fil = lt_path + '/data/lines/H2_resonance.ascii'\n    print('linetools.lists.parse: Reading linelist --- \\n   {:s}'.format(H2_fil))\n    data = Table.read(H2_fil, format='ascii', guess=False, comment=';')\n\n    # Units\n    data['wrest'].unit = u.AA\n    data['gamma'].unit = 1./u.s\n\n    # Rename some columns\n    data.rename_column('Jp', 'Jj')\n    data.rename_column('Jpp', 'Jk')\n    data.rename_column('np', 'nj')\n    data.rename_column('npp', 'nk')\n\n    # Molecule column\n    cmol = Column(['H2']*len(data), name='mol')\n    data.add_column(cmol)\n\n    # Group\n    cgroup = Column(np.ones(len(data),dtype='int')*(2**3), name='group')\n    data.add_column(cgroup)\n\n    # Return\n    return data\n\n\ndef read_CO():\n    \"\"\" Simple def to read CO UV data\n\n    Generated by JXP with some great effort.  See GRB 080607 paper.\n\n    Returns\n    -------\n    Table of CO lines\n    \"\"\"\n    CO_fil = lt_path + '/data/lines/CO_UV.ascii'\n    print('linetools.lists.parse: Reading linelist --- \\n   {:s}'.format(CO_fil))\n    data = ascii.read(CO_fil)\n\n    # Units\n\n    # Rename some columns\n    data.rename_column('Jp', 'Jj')\n    data.rename_column('Jpp', 'Jk')\n    data.rename_column('np', 'nj')\n    data.rename_column('npp', 'nk')\n    data.rename_column('iso', 'Am') # Isotope\n    data.rename_column('wave', 'wrest') \n\n    data['wrest'].unit = u.AA\n\n    # Fvalues\n    data['fv'] = 10.**data['fv']\n    data.rename_column('fv', 'f')\n\n    # Molecule column\n    cmol = Column(['CO']*len(data), name='mol')\n    data.add_column(cmol)\n\n    # Group\n    cgroup = Column(np.ones(len(data),dtype='int')*(2**4), name='group')\n    data.add_column(cgroup)\n\n    # Return\n    return data\n\n\n\ndef read_verner94():\n    \"\"\" Read Verner1994 Table\n    \"\"\"\n    # Read\n    verner94 = lt_path + '/data/lines/verner94_tab6.fits'\n    print(\n        'linetools.lists.parse: Reading linelist --- \\n   {:s}'.format(\n            verner94))\n    tbl_6 = Table.read(verner94)\n\n    # Deal with bad unit\n    tbl_6['lambda'].unit = u.AA\n    tbl_6 = Table(tbl_6)\n\n    # My table\n    ldict, data = line_data(nrows=len(tbl_6))\n\n    # Fill\n    data['wrest'] = tbl_6['lambda']\n    data['f'] = tbl_6['Fik']\n    data['gj'] = tbl_6['Gi']\n    data['gk'] = tbl_6['Gk']\n    data['Z'] = tbl_6['Z']\n    data['ion'] = tbl_6['Z'] - tbl_6['N'] + 1\n    for ii,row in enumerate(tbl_6):\n        data[ii]['name'] = (\n            row['Species'][0:2].strip() + row['Species'][2:].strip() + \n            ' {:d}'.format(int(row['lambda'])))\n    # name\n    names = []\n    for row in data:\n        ionnm = ions.ion_name((row['Z'], row['ion']))\n        names.append('{:s} {:d}'.format(ionnm, int(row['wrest'])))\n    data['name'] = names\n    #  Finish\n    data['group'] = 1\n    data['Ref'] = 'Verner1994'\n    data['mol'] = ''\n\n    # Return\n    return data\n\n\ndef read_forbidden():\n    \"\"\" read galaxy emission lines (forbidden)\n\n    There may be more here: https://github.com/moustakas/impro/blob/master/pro/hiiregions/im_getmatrix.pro\n\n    Returns\n    -------\n    Table of forbidden lines\n    \"\"\"\n    forb_fil = lt_path + '/data/lines/galaxy_forbidden.ascii'\n    print('linetools.lists.parse: Reading linelist --- \\n   {:s}'.format(forb_fil))\n    aux = Table.read(forb_fil, format='ascii')\n\n    # My table\n    ldict, data = line_data(nrows=len(aux))\n\n    # load values using convention names\n    data['wrest'] = aux['wave']\n    data['wrest'].unit = u.AA\n    data['Z'] = aux['Z']\n    data['ion'] = aux['ion']\n    for ii, row in enumerate(data):\n        row['name'] = aux['name'][ii].replace('_', ' ')\n    data['Ref'] = 'DESI_NIST_JM'\n\n    # mask the galaxy data using default mask_keys\n    data = mask_gal(data)\n\n    # Return\n    return data\n\n\ndef read_recomb():\n    \"\"\" read galaxy emission lines (recombination)\n\n    Returns\n    -------\n    Table of recombination lines\n    \"\"\"\n    recomb_fil = lt_path + '/data/lines/galaxy_recomb.ascii'\n    print('linetools.lists.parse: Reading linelist --- \\n   {:s}'.format(recomb_fil))\n    aux = Table.read(recomb_fil, format='ascii')\n\n    # My table\n    ldict, data = line_data(nrows=len(aux))\n\n    # load values using convention names\n    data['wrest'] = aux['wave']\n    data['wrest'].unit = u.AA\n    data['Z'] = aux['Z']\n    data['ion'] = aux['ion']\n    for ii, row in enumerate(data):\n        row['name'] = aux[ii]['name'].replace('_', ' ')\n    data['Ref'] = 'DESI_NIST_JM'\n\n    # mask the galaxy data using default mask_keys\n    data = mask_gal(data)\n\n    # Return\n    return data\n\ndef read_galabs():\n    \"\"\" read galaxy absorption lines\n\n    Returns\n    -------\n    Table of recombination lines\n    \"\"\"\n    galabs_fil = lt_path + '/data/lines/galaxy_abs.ascii'\n    print('linetools.lists.parse: Reading linelist --- \\n   {:s}'.format(galabs_fil))\n    aux = Table.read(galabs_fil, format='ascii')\n\n    # My table\n    ldict, data = line_data(nrows=len(aux))\n\n    # load values using convention names\n    data['wrest'] = aux['wave']\n    data['wrest'].unit = u.AA\n    data['Z'] = aux['Z']\n    data['ion'] = aux['ion']\n    for ii, row in enumerate(data):\n        row['name'] = aux[ii]['name'].replace('_', ' ')\n    data['Ref'] = 'JXP_DK_Unknown'\n\n    # mask the galaxy data using default mask_keys\n    data = mask_gal(data)\n\n    # Return\n    return data\n\n\ndef mask_gal(data, mask_keys=None):\n    \"\"\"Masks linelist attributes for all galaxy lines\n\n    Parameters\n    ----------\n    data : Table (masked)\n        The original table to mask columns for\n    mask_keys : list of strings, optional\n        List of column names to be masked if given\n        Otherwise it uses the default:\n\n    Returns\n    -------\n    data_masked : Table (masked)\n        The masked version of `data`\n    \"\"\"\n    # check input\n    if not isinstance(data, (Table)):\n        raise RuntimeError('The input table has to be astropy Table')\n\n    if data.masked is not True:\n        raise RuntimeError('The input Table has to be masked.')\n\n    # set default keys to mask\n    if mask_keys is None:\n        mask_keys = ['A', 'el', 'nj', 'nk','group','Ek','f','mol',\n                     'Ej','Am','Ex','Jj','Jk','gk','gj','gamma']\n\n    for key in mask_keys:\n        data[key].mask = True\n\n    return data\n\n\ndef parse_verner96(orig=False, write=False):\n    \"\"\"Parse tables from Verner, Verner, & Ferland (1996, Atomic Data and Nuclear Data Tables, Vol. 64, p.1)\n\n    Parameters\n    ----------\n    orig : bool, optional\n      Use original code to parse the ASCII file\n      Else, read from a FITS file\n\n    Returns\n    -------\n    data : Table\n      Atomic data\n    \"\"\"\n    # Look for FITS\n    fitsf = lt_path + '/data/lines/verner96_tab1.fits.gz'\n    verner96_tab1 = glob.glob(fitsf)\n\n    if (len(verner96_tab1) > 0) & (not orig):\n        print('linetools.lists.parse: Reading linelist --- \\n   {:s}'.format(\n            verner96_tab1[0]))\n        data = Table.read(verner96_tab1[0])\n    else:\n        # File\n        verner96_tab1 = lt_path + '/data/lines/verner96_tab1.txt'\n        # Read\n        with open(verner96_tab1) as f:\n            lines = f.readlines()\n        # Grab the 'good' ones\n        gdlines = [iline.strip() for iline in lines if len(iline.strip()) > 113]\n        ldict, data = line_data(nrows=len(gdlines))\n        # Loop\n        for kk, line in enumerate(gdlines):\n            # Z, ion\n            data[kk]['Z'] = ELEMENTS[line[0:2].strip()].number\n            data[kk]['ion'] = int(line[2:4].strip())\n            # wrest\n            data[kk]['wrest'] = float(line[47:56].strip())\n            # name\n            ionnm = ions.ion_name((data[kk]['Z'], data[kk]['ion']))\n            data[kk]['name'] = '{:s} {:d}'.format(ionnm,\n                    int(data[kk]['wrest']))\n            # Ej, Ek\n            data[kk]['Ej'] = float(line[59:73].strip())\n            data[kk]['Ek'] = float(line[73:89].strip())\n            # gj, gk\n            data[kk]['gj'] = int(line[89:92].strip())\n            data[kk]['gk'] = int(line[92:95].strip())\n            # Ak\n            data[kk]['A'] = float(line[95:103].strip())\n            # f\n            data[kk]['f'] = float(line[104:112].strip())\n        # Update\n        data['Ref'] = 'Verner1996'\n\n        # Write\n        if write:\n            outfil = lt_path + '/data/lines/verner96_tab1.fits'\n            data.write(outfil,overwrite=True)\n            print('parse_verner96: Wrote {:s}'.format(outfil))\n            # Compress and delete\n            print('Now compressing...')\n            with open(outfil) as src:\n                with gzip.open(outfil+'.gz', 'wb') as dst:\n                    dst.writelines(src)\n            os.unlink(outfil)\n\n    # Return\n    return data\n\n\ndef parse_morton00(orig=False):\n    \"\"\"Parse tables from Morton 2000, ApJS, 130, 403\n\n    Parameters\n    ----------\n    orig : bool, optional\n      Use original code to parse the ASCII file\n\n    Returns\n    -------\n    data : Table\n      Atomic data\n    \"\"\"\n    # Look for FITS\n    fitsf = lt_path + '/data/lines/morton00_table2.fits.gz'\n    morton00_tab2 = glob.glob(fitsf)\n\n    if (len(morton00_tab2) > 0) & (not orig):\n        print('linetools.lists.parse: Reading linelist --- \\n   {:s}'.format(\n            morton00_tab2[0]))\n        data = Table.read(morton00_tab2[0])\n    else:\n        # File\n        morton00_tab2 = lt_path + '/data/lines/morton00_table2.dat'\n        # Call\n        data = parse_morton03(orig=True, tab_fil=morton00_tab2)\n        # Update\n        data['Ref'] = 'Morton2000'\n\n    # Return\n    return data\n\n#\ndef parse_morton03(orig=False, tab_fil=None, HIcombine=True):\n    \"\"\"Parse tables from Morton 2003, ApJS, 149, 205\n\n    Parameters\n    ----------\n    orig : bool, optional\n      Use original code to parse the ASCII file\n    tab_fil : str, optional\n      Filename to use.  Default = /data/lines/morton03_table2.dat \n    HIcombine : bool, optional\n      Combine doublet for HI [True]\n\n    Returns\n    -------\n    data : Table\n      Atomic data\n    \"\"\"\n    # Look for FITS\n    fitsf = lt_path + '/data/lines/morton03_table2.fits.gz'\n    morton03_tab2 = glob.glob(fitsf)\n\n    if (len(morton03_tab2) > 0) & (not orig):\n        print('linetools.lists.parse: Reading linelist --- \\n   {:s}'.format(\n            morton03_tab2[0]))\n        data = Table.read(morton03_tab2[0])\n    else:\n        ## Read Table 2\n        if tab_fil is None:\n            morton03_tab2 = lt_path + '/data/lines/morton03_table2.dat'\n        else:\n            morton03_tab2 = tab_fil\n        print(\n            'linetools.lists.parse: Reading linelist --- \\n   {:s}'.format(\n                morton03_tab2))\n        f = open(morton03_tab2, 'r', encoding=\"ISO-8859-1\")\n        lines = f.readlines()\n        f.close()\n\n        ## Find Elements and Ions\n        elmi = []\n        elmZ = []\n        elmc = []\n        ioni = []\n        isoi = []\n        ionv = []\n        for kk,line in enumerate(lines):\n            #print('kk = {:d}'.format(kk))\n            try: # Deals with bad Byte in Morton00\n                tmp = ('Z = ' in line) & ('A =' in line)  \n            except UnicodeDecodeError:\n                tmp = False\n            if tmp:\n                # Grab Z\n                ipos = line.find('Z = ')\n                elmZ.append(int(line[ipos+4:ipos+7]))\n                ipos2 = line.find('= ')\n                elmc.append(line[ipos2+2:ipos].strip())\n                #xdb.set_trace()\n                # Line index\n                elmi.append(kk)\n\n            # ISOTOPE and ION\n            try: # Deals with bad Byte in Morton00\n                tmp2 = ( (('I ' in line[0:13]) | ('V ' in line[0:13]))\n                    & (line[0:3] not in ['IOD','VAN']) & (line[0:2] != 'I ') )\n            except UnicodeDecodeError:\n                tmp2 = False\n            if tmp2:\n                # Grab ion\n                ipos = line[0:10].find(' ')\n                if ipos > 4:\n                    ipos3 = line[0:10].find('I')\n                    iionv = line[ipos3:ipos]\n                else:\n                    iionv = line[ipos:6].strip()\n                if (len(iionv) == 0) | (iionv == '5s') | (iionv == 'B I'):\n                    pdb.set_trace()\n                ionv.append(iionv)\n                if iionv == 'Z =':\n                    pdb.set_trace()\n\n                # Line index\n                ioni.append(kk)\n\n                # Deal with Isotope\n                if line[0] in ['0','1','2','3','4','5','6','7','8','9']:\n                    # Skip ArI !\n                    if 'Ar I' in line:\n                        pass\n                    else:\n                        isoi.append(kk)\n                # Deuterium\n                if line[0] == 'D':\n                    Dline = kk\n\n        #pdb.set_trace()\n        ## Initialize table\n        ldict, tbl = line_data(nrows=len(lines))\n\n        ## Parse lines with UV rest wavelength\n        count = 0\n        for kk,line in enumerate(lines):\n            try:\n                tmp = line[23] == '.'\n            except IndexError:\n                pass\n            else:\n                if tmp: # UV wavelength?\n                    # Parse\n\n                    # Ion/Isotope\n                    if kk > np.max(ioni):\n                        gdi = len(ioni)-1\n                    else:\n                        gdi = np.where( (kk > np.array(ioni)) & (kk < np.roll(np.array(ioni),-1)))[0]\n                        if len(gdi) != 1:\n                            pdb.set_trace()\n                            raise ValueError('Uh oh ion')\n                        else:\n                            gdi = gdi[0]\n                    if ioni[gdi] in isoi: # Isotope\n                        continue\n                    # Ion\n                    tbl[count]['ion'] = roman.fromRoman(ionv[gdi])\n\n                    # Wavelength\n                    tbl[count]['wrest'] = float(line[19:28]) #* u.AA\n                    # Z\n                    gdZ = np.where( (kk > np.array(elmi)) & (kk < np.roll(np.array(elmi),-1)))[0]\n                    if len(gdZ) != 1:\n                        if kk > np.max(elmi):\n                            gdZ = len(elmi)-1\n                        else:\n                            #xdb.set_trace()\n                            raise ValueError('Uh oh elm')\n                    else:\n                        gdZ = gdZ[0]\n                    tbl[count]['Z'] = elmZ[gdZ]\n                    # Name\n                    tbl[count]['name'] = elmc[gdZ]+ionv[gdi]+' {:d}'.format(\n                        int(tbl[count]['wrest']))\n                    # Isotope (Atomic number)\n                    if ioni[gdi] == Dline:\n                        tbl[count]['Am'] = 2\n                        tbl[count]['name'] = 'D'+ionv[gdi]+' {:d}'.format(\n                            int(tbl[count]['wrest']))\n                    # f\n                    try:\n                        tbl[count]['f'] = float(line[79:89])\n                    except ValueError:\n                        continue # Skip ones without f-value\n                    # Ej, Ek\n                    tbl[count]['Ej'] = float(line[29:38]) #/ u.cm\n                    tbl[count]['Ek'] = float(line[40:50]) #/ u.cm\n                    # A\n                    try:\n                        tbl[count]['A'] = float(line[59:68]) #/ u.s\n                    except ValueError:\n                        pass\n                    # gamma\n                    try:\n                        tbl[count]['gamma'] = float(line[69:79]) #/ u.s\n                    except ValueError:\n                        pass\n                    # gl, gu\n                    tbl[count]['gj'] = int(line[52:54])\n                    tbl[count]['gk'] = int(line[56:58])           \n\n                    # Only use combined HI lines\n                    if HIcombine:\n                        if ((tbl[count]['Z'] == 1) & (tbl[count]['ion']==1) \n                            & (tbl[count]['gk'] != 6)):\n                            #print('Skipping HI line {:g}'.format(tbl[count]['wrest']))\n                            continue \n                    # Ex\n                    #all_dict[count]['Ex'] = 0.  # Zero out units (for Table)\n\n                    # Increment\n                    count += 1\n        # Trim\n        data = tbl[0:count]\n\n        # Last\n        data['group'] = 1\n        data['Ref'] = 'Morton2003'\n        data['mol'] = ''\n\n    # Return\n    #pdb.set_trace()\n    return data\n\ndef mktab_morton03(do_this=False, outfil=None, fits=True):\n    \"\"\"Used to generate a VO or FITS Table for the Morton2003 paper\n\n    Only intended for builder usage (1.5Mb file; gzip FITS is 119kb)\n\n    Parameters\n    ----------\n    do_this : bool, optional\n      Set to True to actually do this. Default=False\n    outfil : str, optional\n      Name of output file.  Defaults to a given value\n    fits :  bool, optional\n      Generate a FITS file?  Default=True\n    \"\"\"\n    if not do_this:\n        print('mktab_morton03: It is very unlikely you want to do this')\n        print('mktab_morton03: Returning...')\n        return\n\n    # Read Morton2003 ASCII file\n    m03 = parse_morton03(orig=True)\n\n    # Write\n    if fits:\n        if outfil is None:\n            outfil = lt_path + '/data/lines/morton03_table2.fits'\n        m03.write(outfil,overwrite=True)\n    else:\n        if outfil is None:\n            outfil = lt_path + '/data/lines/morton03_table2.vot'\n        m03.write(outfil, format='votable', overwrite=True)\n    print('mktab_morton03: Wrote {:s}'.format(outfil))\n    # Compress and delete\n    print('mktab_morton03: Now compressing...')\n    with open(outfil) as src:\n        with gzip.open(outfil+'.gz', 'wb') as dst:\n            dst.writelines(src)\n    os.unlink(outfil)\n\n\ndef mktab_morton00(do_this=False, outfil=None):\n    \"\"\"Used to generate a FITS Table for the Morton2000 paper\n\n    Only intended for builder usage\n\n    Parameters\n    ----------\n    do_this : bool, optional\n      Set to True to actually do this. Default=False\n    outfil : str, optional\n      Name of output file.  Defaults to a given value\n    \"\"\"\n    if not do_this:\n        print('mktab_morton00: It is very unlikely you want to do this')\n        print('mktab_morton00: Returning...')\n        return\n\n    # Read Morton2003\n    m00 = parse_morton00(orig=True)\n\n    # Write\n    if outfil is None:\n        outfil = lt_path + '/data/lines/morton00_table2.fits'\n    m00.write(outfil, overwrite=True)\n    print('mktab_morton00: Wrote {:s}'.format(outfil))\n    #\n    print('mktab_morton03: Now compressing...')\n    with open(outfil) as src:\n        with gzip.open(outfil+'.gz', 'wb') as dst:\n            dst.writelines(src)\n    os.unlink(outfil)\n\n\ndef grab_galaxy_linelists(do_this=False):\n    \"\"\" Pulls galaxy emission line lists from DESI project\n\n    Specifically, desisim\n    Writes to hard-drive\n    Only run if you are building\n\n    Parameters\n    ----------\n    do_this : bool, optional\n      Set to True to actually do this. Default=False\n\n    \"\"\"\n    if not do_this:\n        print('mktab_morton00: It is very unlikely you want to do this')\n        print('mktab_morton00: Returning...')\n        return\n\n    try:\n        # For Python 3.0 and later\n        from urllib.request import urlopen\n    except ImportError:\n        # Fall back to Python 2's urllib2\n        from urllib2 import urlopen\n\n    # Forbidden\n    url = 'https://raw.githubusercontent.com/desihub/desisim/master/data/forbidden_lines.dat'\n    f = urlopen(url)\n    tab_fil = lt_path+'/data/lines/galaxy_forbidden.ascii'\n    print('Writing {:s}'.format(tab_fil))\n    with open(tab_fil, \"wb\") as code:\n        code.write(f.read())\n\n    # Recombination\n    url = 'https://raw.githubusercontent.com/desihub/desisim/master/data/recombination_lines.dat'\n    f = urlopen(url)\n    tab_fil = lt_path+'/data/lines/galaxy_recomb.ascii'\n    print('Writing {:s}'.format(tab_fil))\n    with open(tab_fil, \"wb\") as code:\n        code.write(f.read())\n\n\ndef update_fval(table, verbose=False):\n    \"\"\"Update f-values from the literature\n\n    Primarily for modifying lines in the ISM lists (e.g. Morton2003)\n\n    Parameters\n    ----------\n    table : Table\n      Data to be updated\n    verbose : bool, optional\n\n    Returns\n    -------\n    table : Table\n      Updated table.\n      Note: This return is required to handle the vstack, i.e.\n      as opposed to modifying the input table in place.\n    \"\"\"\n    # Shectman et al. 1998, ApJ, 504, 921 \n    #   Morton2003 cites this but uses a different f-value\n    imn = np.argmin(np.abs(table['wrest']-1526.707))\n    table['f'][imn] = 0.127\n\n    # Howk 2000 (using Weise 2002 as in Morton for FeII 1142,1143,1144)\n    howk00_fil = lt_path + '/data/lines/howk00_table1.ascii'\n    howk00 = ascii.read(howk00_fil, comment='#')\n\n    # Dress up\n    howk00['wrest'].unit = u.AA\n\n    fval = []\n    fsig = []\n    for row in howk00:\n        ipos1 = row['fval_sig'].find('(')\n        ipos2 = row['fval_sig'].find(')')\n        # \n        fval.append(float(row['fval_sig'][0:ipos1]))\n        fsig.append(float(row['fval_sig'][ipos1+1:ipos2]))\n    # Add columns\n    howk00.add_column(Column(np.array(fval), name='f'))\n    howk00.add_column(Column(np.array(fsig), name='fsig')) # Error in last decimal\n\n    # Now, finally, update\n    for row in howk00:\n        mt = np.where( (np.abs(table['wrest']-row['wrest']*u.AA) < 1e-3*u.AA) & \n            (table['Z'] == 26) & (table['ion'] == 2))[0]\n        if len(mt) == 0:\n            if verbose:\n                print('update_fval: Line {:g} not in your table.'.format(row['wrest']))\n        elif len(mt) == 1:\n            table['f'][mt[0]] = row['f']\n        else:\n            raise ValueError('Uh oh')\n\n    ## ##\n    # Lines without f-value but of interest\n\n    # AsII\n    mn = np.min(np.abs(table['wrest']-1355.934))  # In Morton2000\n    if mn > 0.05:  # Ang\n        _, new_row = line_data()\n        new_row['Z'] = 33\n        new_row['ion'] = 2\n        new_row['wrest'] = 1355.934\n        new_row['name'] = 'AsII 1355'\n        new_row['f'].mask = True\n        # Stack\n        table = vstack([table, new_row])\n\n    return table\n\n\ndef update_gamma(table):\n    \"\"\"Update/add-in gamma values\n\n    Parameters\n    ----------\n    table : Table\n      Data to be updated\n    verbose : bool, optional\n    \"\"\"\n    # HI - Morton doesn't give these for the combined HI lines (sensible)\n    #  Nor does he give them for the lines beyond Ly-d (not sure why)\n    try:\n        HI = np.where((table['Z']==1) & (table['ion']==1))[0]\n    except KeyError: # Molecules\n        pass\n    else:\n        if len(HI) > 0:\n            # Same kludge as in atom.dat of VPFIT for higher order lines\n            table['gamma'] = table['A']\n            # More accurate for stronger lines (pulled from Morton) [all in units of s^-1]\n            gdict = {1215.670: 6.265E+08, 1025.7222: 1.897E+08, # From Morton\n                972.5367: 8.127E+07, 949.7430: 4.204E+07, 937.8034: 2.450E+07}\n            for key in gdict.keys():\n                mt = np.where( (np.abs(table['wrest']-key) < 1e-4))[0]\n                if len(mt) > 0:\n                    table['gamma'][mt[0]] = gdict[key]\n\n\ndef update_wrest(table, verbose=True):\n    \"\"\"Update wrest values (and Ej,Ek)\n\n    Parameters\n    ----------\n    table : Table\n      Data to be updated\n    verbose : bool, optional\n    \"\"\"\n\n    '''\n    # TiII line (Morton 2003 vs Weise 2001) \n    # Went back to Morton 2003.  If you go to Weise, you have\n    #  to expunge the Verner94 row\n    mt = np.where( (np.abs(table['wrest']-1910.9538*u.AA) < 1e-3*u.AA))[0] \n    table['wrest'][mt[0]] = 1910.938 * u.AA\n    table['Ek'][mt[0]] = 52330.33 / u.cm\n    '''\n#\n\n\ndef _write_ref_ISM_table():\n    \"\"\" Write a reference table enabling faster I/O for ISM-related lists\n\n    For developer use only.\n\n    Note that after running this, you need to manually copy the table\n    produced to linetools/data/lines/ISM_table.fits inside the github\n    repository, and then check it in.\n    \"\"\"\n    from linetools.lists.linelist import LineList\n\n    ism = LineList('ISM', use_ISM_table=False)\n    strong = LineList('Strong', use_ISM_table=False)\n    euv = LineList('EUV', use_ISM_table=False)\n    hi = LineList('HI', use_ISM_table=False)\n\n    # need a Table to write\n    tab = ism._data.copy()\n    tab.sort(('wrest'))\n\n    # Using np.in1d doesn't work for some reason. Do it the long way\n    cond = []\n    for table in (strong, euv, hi):\n        igood = []\n        for row in Table(table._data):\n            ind = tab['wrest'].searchsorted(row['wrest'])\n            dw = abs(tab['wrest'][ind] - row['wrest'])\n            if abs(tab['wrest'][ind+1] - row['wrest']) < dw:\n                ind = ind + 1\n            rism = tab[ind]\n            # check this is the right row.\n            if all(row[k] == rism[k] for k in hi._data.colnames if\n                   not hasattr(row[k], 'mask') or not row[k].mask):\n                igood.append(ind)\n            else:\n                raise RuntimeError('No match found!')\n\n        cond.append(np.zeros(len(tab), dtype=bool))\n        cond[-1][np.array(igood)] = True\n\n    col1 = Column(cond[0], name='is_Strong')\n    col2 = Column(cond[1], name='is_EUV')\n    col3 = Column(cond[2], name='is_HI')\n    tab.add_columns([col1, col2, col3])\n\n    tab.write('ISM_table.fits', overwrite=True)\n", "meta": {"hexsha": "cdc33a8fd2b7297d50724c940b1b8d2870c0ecbb", "size": 29407, "ext": "py", "lang": "Python", "max_stars_repo_path": "linetools/lists/parse.py", "max_stars_repo_name": "marijana777/linetools", "max_stars_repo_head_hexsha": "73720a2f6df42b7dde1f35055cd40ad970200f7f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linetools/lists/parse.py", "max_issues_repo_name": "marijana777/linetools", "max_issues_repo_head_hexsha": "73720a2f6df42b7dde1f35055cd40ad970200f7f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linetools/lists/parse.py", "max_forks_repo_name": "marijana777/linetools", "max_forks_repo_head_hexsha": "73720a2f6df42b7dde1f35055cd40ad970200f7f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5368639668, "max_line_length": 108, "alphanum_fraction": 0.5292277349, "include": true, "reason": "import numpy,from astropy", "num_tokens": 8122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.19522597239066197}}
{"text": "# -*- coding: utf-8 -*-\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n#\n# Copyright (C) 2014-2016 GEM Foundation\n#\n# OpenQuake is free software: you can redistribute it and/or modify it\n# under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# OpenQuake is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"\nModule exports :class:`SomervilleEtAl2001NSHMP2008`.\n\"\"\"\nfrom __future__ import division\n\nimport numpy as np\n\nfrom openquake.hazardlib.gsim.base import CoeffsTable, GMPE\nfrom openquake.hazardlib.gsim.utils import clip_mean\nfrom openquake.hazardlib import const\nfrom openquake.hazardlib.imt import PGA, SA\n\n\nclass SomervilleEtAl2001NSHMP2008(GMPE):\n    \"\"\"\n    Implements GMPE developed by P. Somerville, N. Collins, N. Abrahamson,\n    R. Graves, and C. Saika and documented in \"GROUND MOTION ATTENUATION\n    RELATIONS FOR THE CENTRAL AND EASTERN UNITED STATES\" (Final report, June\n    30, 2001: Report to U.S. Geological Survey for award 99HQGR0098). This GMPE\n    is used by the National Seismic Hazard Mapping Project (NSHMP) for the 2008\n    US hazard model.\n\n    Document available at:\n    http://earthquake.usgs.gov/hazards/products/conterminous/2002/99HQGR0098.pdf\n\n    This class replicates the algorithm for the Somerville et. al. 2001 GMPE as\n    coded in the subroutine ``getSomer`` in the ``hazgridXnga2.f``\n    Fortran code available at:\n    http://earthquake.usgs.gov/hazards/products/conterminous/2008/software/\n\n    Coefficients are given for the B/C site conditions.\n    \"\"\"\n    #: Supported tectonic region type is stable continental crust,\n    #: given that the equations have been derived for central and eastern\n    #: north America\n    DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.STABLE_CONTINENTAL\n\n    #: Supported intensity measure types are spectral acceleration,\n    #: and peak ground acceleration\n    DEFINED_FOR_INTENSITY_MEASURE_TYPES = set([\n        PGA,\n        SA\n    ])\n\n    #: Supported intensity measure component is the geometric mean of\n    #two : horizontal components\n    #:attr:`~openquake.hazardlib.const.IMC.AVERAGE_HORIZONTAL`,\n    DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = const.IMC.AVERAGE_HORIZONTAL\n\n    #: Supported standard deviation type is only total.\n    DEFINED_FOR_STANDARD_DEVIATION_TYPES = set([\n        const.StdDev.TOTAL\n    ])\n\n    #: No site parameters required\n    REQUIRES_SITES_PARAMETERS = set()\n\n    #: Required rupture parameter is only magnitude (Mw).\n    REQUIRES_RUPTURE_PARAMETERS = set(('mag', ))\n\n    #: Required distance measure is rjb\n    REQUIRES_DISTANCES = set(('rjb', ))\n\n    def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):\n        \"\"\"\n        See :meth:`superclass method\n        <.base.GroundShakingIntensityModel.get_mean_and_stddevs>`\n        for spec of input and result values.\n        \"\"\"\n        assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES\n                   for stddev_type in stddev_types)\n\n        C = self.COEFFS[imt]\n\n        mean = self._compute_mean(C, rup.mag, dists.rjb)\n        mean = clip_mean(imt, mean)\n\n        stddevs = self._compute_stddevs(C, dists.rjb.size, stddev_types)\n\n        return mean, stddevs\n\n    def _compute_mean(self, C, mag, rjb):\n        \"\"\"\n        Compute and return mean value (table 8, page 8)\n        \"\"\"\n        d1 = np.sqrt(50. ** 2 + 6. ** 2)\n        d = np.sqrt(rjb ** 2 + 6 ** 2)\n\n        mean = np.zeros_like(rjb)\n\n        mean += (\n            C['a1'] + C['a2'] * (mag - 6.4) +\n            C['a7'] * (8.5 - mag) ** 2\n        )\n\n        idx = rjb < 50.\n        mean[idx] += (\n            C['a3'] * np.log(d[idx]) +\n            C['a4'] * (mag - 6.4) * np.log(d[idx]) +\n            C['a5'] * rjb[idx]\n        )\n\n        idx = rjb >=50.\n        mean[idx] += (\n            C['a3'] * np.log(d1) +\n            C['a4'] * (mag - 6.4) * np.log(d[idx]) +\n            C['a5'] * rjb[idx] + C['a6'] * (np.log(d[idx]) - np.log(d1))\n        )\n\n        return mean\n\n    def _compute_stddevs(self, C, num_sites, stddev_types):\n        \"\"\"\n        Return total standard deviation.\n        \"\"\"\n        stddevs = []\n        for _ in stddev_types:\n            stddevs.append(np.zeros(num_sites) + C['sigma'])\n\n        return stddevs\n\n    #: Coefficient table obtained from coefficient arrays (a1, a2, a3, a4,\n    #: a5, a6, a7, sig0) defined in subroutine getSomer in hazgridXnga2.f\n    COEFFS = CoeffsTable(sa_damping=5, table=\"\"\"\\\n    IMT    a1      a2      a3        a4       a5           a6         a7         sigma\n    pga    0.658   0.805  -0.679     0.0861  -0.00498     -0.477      0.0        0.587\n    0.1    1.442   0.805  -0.679     0.0861  -0.00498     -0.477      0.0        0.595\n    0.2    1.358   0.805  -0.679     0.0861  -0.00498     -0.477      0.0        0.611\n    0.3    1.2353  0.805  -0.67023   0.0861  -0.0048045   -0.523792  -0.030298   0.6057\n    0.5    0.8532  0.805  -0.671792  0.0861  -0.00442189  -0.605213  -0.0640237  0.6242\n    1.0   -0.0143  0.805  -0.696     0.0861  -0.00362     -0.755     -0.102      0.693\n    2.0   -0.9497  0.805  -0.728     0.0861  -0.00221     -0.946     -0.140      0.824\n    \"\"\")\n", "meta": {"hexsha": "4c1afcbee269ca5bac5275484f5a9d33a94359bf", "size": 5560, "ext": "py", "lang": "Python", "max_stars_repo_path": "openquake.hazardlib/openquake/hazardlib/gsim/somerville_2001.py", "max_stars_repo_name": "rainzhop/ConvNetQuake", "max_stars_repo_head_hexsha": "a3e6de3f7992eac72f1b9883fec36b8c7fdefd48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "openquake.hazardlib/openquake/hazardlib/gsim/somerville_2001.py", "max_issues_repo_name": "rainzhop/ConvNetQuake", "max_issues_repo_head_hexsha": "a3e6de3f7992eac72f1b9883fec36b8c7fdefd48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openquake.hazardlib/openquake/hazardlib/gsim/somerville_2001.py", "max_forks_repo_name": "rainzhop/ConvNetQuake", "max_forks_repo_head_hexsha": "a3e6de3f7992eac72f1b9883fec36b8c7fdefd48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5789473684, "max_line_length": 87, "alphanum_fraction": 0.6260791367, "include": true, "reason": "import numpy", "num_tokens": 1690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.19522596689034008}}
{"text": "#!/usr/bin/python\n# author: Charlotte Bunne\n\n# imports\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch\nimport pickle\nimport os\nfrom time import time\nfrom torchvision import datasets, transforms\nfrom torchvision.utils import save_image\n\n# internal imports\nfrom model.utils import *\nfrom model.model_cnn import Generator, Adversary\nfrom model.model_cnn import weights_init_generator, weights_init_adversary\nfrom model.loss import gwnorm_distance, loss_total_variation, loss_procrustes\n\n# get arguments\nargs = get_args()\n\n# system preferences\nseed = np.random.randint(100)\ntorch.set_default_dtype(torch.double)\nnp.random.seed(seed)\ntorch.manual_seed(seed)\n\n# settings\nbatch_size = 256\nz_dim = 100\nlr = 0.0002\nngen = 3\nbeta = args.beta\nlam = 0.5\nniter = 10\nepsilon = 0.005\nnum_epochs = args.num_epochs\ncuda = args.cuda\nchannels = args.n_channels\nid = args.id\n\nmodel = 'gwgan_{}_eps_{}_tv_{}_procrustes_{}_ngen_{}_channels_{}_{}' \\\n        .format(args.data, epsilon, lam, beta, ngen, channels, id)\nsave_fig_path = 'out_' + model\nif not os.path.exists(save_fig_path):\n    os.makedirs(save_fig_path)\n\n# data import\nif args.data == 'mnist':\n    dataloader = torch.utils.data.DataLoader(\n        datasets.MNIST('./data/mnist', train=True, download=True,\n                       transform=transforms.Compose([\n                           transforms.Resize(32),\n                           transforms.ToTensor(),\n                           transforms.Normalize((0.5, 0.5, 0.5),\n                                                (0.5, 0.5, 0.5))])),\n        batch_size=batch_size, drop_last=True, shuffle=True)\nelif args.data == 'fmnist':\n    dataloader = torch.utils.data.DataLoader(\n        datasets.FashionMNIST('./data/fmnist', train=True, download=True,\n                              transform=transforms.Compose([\n                                  transforms.Resize(32),\n                                  transforms.ToTensor(),\n                                  transforms.Normalize((0.5, 0.5, 0.5),\n                                                       (0.5, 0.5, 0.5))])),\n        batch_size=batch_size, drop_last=True, shuffle=True)\nelif args.data == 'cifar_gray':\n    dataloader = torch.utils.data.DataLoader(\n        datasets.CIFAR10('./data/cifar10', train=True, download=True,\n                         transform=transforms.Compose([\n                            # transform RGB to grayscale\n                            transforms.Grayscale(num_output_channels=1),\n                            transforms.ToTensor(),\n                            transforms.Normalize((0.5, 0.5, 0.5),\n                                                 (0.5, 0.5, 0.5))])),\n        batch_size=batch_size, drop_last=True, shuffle=True)\nelif args.data == 'cifar':\n    dataloader = torch.utils.data.DataLoader(\n        datasets.CIFAR10('./data/cifar10', train=True, download=True,\n                         transform=transforms.Compose([\n                            transforms.ToTensor(),\n                            transforms.Normalize((0.5, 0.5, 0.5),\n                                                 (0.5, 0.5, 0.5))])),\n        batch_size=batch_size, drop_last=True, shuffle=True)\nelse:\n    raise NotImplementedError('dataset does not exist or not integrated.')\n\n# print example images\nsave_image(next(iter(dataloader))[0][:25],\n           os.path.join(save_fig_path, 'real.pdf'), nrow=5, normalize=True)\n\n# define networks and parameters\ngenerator = Generator(output_dim=channels)\nadversary = Adversary(input_dim=channels)\n\n# weight initialisation\ngenerator.apply(weights_init_generator)\nadversary.apply(weights_init_adversary)\n\nif cuda:\n    generator = generator.cuda()\n    adversary = adversary.cuda()\n\n# create optimizer\ng_optimizer = torch.optim.Adam(generator.parameters(), lr, betas=(0.5, 0.99))\n# zero gradients\ngenerator.zero_grad()\n\nc_optimizer = torch.optim.Adam(adversary.parameters(), lr, betas=(0.5, 0.99))\n# zero gradients\nadversary.zero_grad()\n\n# sample for plotting\nnum_test_samples = batch_size\nz_ex = torch.randn(num_test_samples, z_dim)\nif cuda:\n    z_ex = z_ex.cuda()\n\nloss_history = list()\nloss_tv = list()\nloss_orth = list()\nloss_og = 0\nis_hist = list()\n\nfor epoch in range(num_epochs):\n    t0 = time()\n\n    for it, (image, _) in enumerate(dataloader):\n        train_c = ((it + 1) % (ngen + 1) == 0)\n\n        x = image.double()\n        if cuda:\n            x = x.cuda()\n\n        # sample random number z from Z\n        z = torch.randn(image.shape[0], z_dim)\n\n        if cuda:\n            z = z.cuda()\n\n        if train_c:\n            for q in generator.parameters():\n                q.requires_grad = False\n            for p in adversary.parameters():\n                p.requires_grad = True\n        else:\n            for q in generator.parameters():\n                q.requires_grad = True\n            for p in adversary.parameters():\n                p.requires_grad = False\n\n        # result generator\n        g = generator.forward(z)\n\n        # result adversary\n        f_x = adversary.forward(x)\n        f_g = adversary.forward(g)\n\n        # compute inner distances\n        D_g = get_inner_distances(f_g, metric='euclidean', concat=False)\n        D_x = get_inner_distances(f_x, metric='euclidean', concat=False)\n\n        # distance matrix normalisation\n        D_x_norm = normalise_matrices(D_x)\n        D_g_norm = normalise_matrices(D_g)\n\n        # compute normalized gromov-wasserstein distance\n        loss, T = gwnorm_distance((D_x, D_x_norm), (D_g, D_g_norm),\n                                  epsilon, niter, loss_fun='square_loss',\n                                  coupling=True, cuda=cuda)\n\n        if train_c:\n            # train adversary\n            loss_og = loss_procrustes(f_x, x.view(x.shape[0], -1), cuda)\n            loss_to = -loss + beta * loss_og\n            loss_to.backward()\n\n            # parameter updates\n            c_optimizer.step()\n            # zero gradients\n            reset_grad(generator, adversary)\n\n        else:\n            # train generator\n            loss_t = loss_total_variation(g)\n            loss_to = loss + lam * loss_t\n            loss_to.backward()\n\n            # parameter updates\n            g_optimizer.step()\n            # zero gradients\n            reset_grad(generator, adversary)\n\n    # plotting\n    # get generator example\n    g_ex = generator.forward(z_ex)\n    g_plot = g_ex.cpu().detach()\n\n    # plot result\n    save_image(g_plot.data[:25],\n               os.path.join(save_fig_path, 'g_%d.pdf' % epoch),\n               nrow=5, normalize=True)\n\n    fig1, ax = plt.subplots(1, 3, figsize=(15, 5))\n    ax0 = ax[0].imshow(T.cpu().detach().numpy(), cmap='RdBu_r')\n    colorbar(ax0)\n    ax1 = ax[1].imshow(D_x.cpu().detach().numpy(), cmap='Blues')\n    colorbar(ax1)\n    ax2 = ax[2].imshow(D_g.cpu().detach().numpy(), cmap='Blues')\n    colorbar(ax2)\n    ax[0].set_title(r'$T$')\n    ax[1].set_title(r'inner distances of $D$')\n    ax[2].set_title(r'inner distances of $G$')\n    plt.tight_layout(h_pad=1)\n    fig1.savefig(os.path.join(save_fig_path, '{}_ccc.pdf'.format(\n            str(epoch).zfill(3))), bbox_inches='tight')\n\n    loss_history.append(loss)\n    loss_tv.append(loss_t)\n    loss_orth.append(loss_og)\n    plt.close('all')\n\n# plot loss history\nfig2 = plt.figure(figsize=(2.4, 2))\nax2 = fig2.add_subplot(111)\nax2.plot(loss_history, 'k.')\nax2.set_xlabel('Iterations')\nax2.set_ylabel(r'$\\overline{GW}_\\epsilon$ Loss')\nplt.tight_layout()\nplt.grid()\nfig2.savefig(save_fig_path + '/loss_history.pdf')\n\nfig3 = plt.figure(figsize=(2.4, 2))\nax3 = fig3.add_subplot(111)\nax3.plot(loss_tv, 'k.')\nax3.set_xlabel('Iterations')\nax3.set_ylabel(r'Total Variation Loss')\nplt.tight_layout()\nplt.grid()\nfig3.savefig(save_fig_path + '/loss_tv.pdf')\n\nfig4 = plt.figure(figsize=(2.4, 2))\nax4 = fig4.add_subplot(111)\nax4.plot(loss_orth, 'k.')\nax4.set_xlabel('Iterations')\nax4.set_ylabel(r'$R_\\beta(f_\\omega(X), X)$ Loss')\nplt.tight_layout()\nplt.grid()\nfig4.savefig(save_fig_path + '/loss_orth.pdf')\n", "meta": {"hexsha": "5cc152ef573bd28ab06e559d5ab0388cd90bb744", "size": 7956, "ext": "py", "lang": "Python", "max_stars_repo_path": "main_gwgan_cnn.py", "max_stars_repo_name": "bunnech/gw_gan", "max_stars_repo_head_hexsha": "fc8d7a2232c92282037ac829bfbdabc5b9ad820e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2019-05-14T14:14:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T03:21:49.000Z", "max_issues_repo_path": "main_gwgan_cnn.py", "max_issues_repo_name": "bunnech/gw_gan", "max_issues_repo_head_hexsha": "fc8d7a2232c92282037ac829bfbdabc5b9ad820e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-07-12T01:14:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T14:20:42.000Z", "max_forks_repo_path": "main_gwgan_cnn.py", "max_forks_repo_name": "bunnech/gw_gan", "max_forks_repo_head_hexsha": "fc8d7a2232c92282037ac829bfbdabc5b9ad820e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-05-14T08:23:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T01:33:34.000Z", "avg_line_length": 31.6972111554, "max_line_length": 77, "alphanum_fraction": 0.6047008547, "include": true, "reason": "import numpy", "num_tokens": 1925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.1952259540617253}}
{"text": "#!/usr/bin/env python\n\n#nknguyen at soe ucsc edu\n#Feb 07 2012\n#TCR repertoire simulation\n\n'''\nSimulate CDR3 TCR repertoires to assess the overlapping of clones/sequences between two independent samplings of certain size.\n(Purpose: use to determine what is the sufficient sampling size to get all the important, clonally expanded CDR3)\n\nThere are 4 main steps involved:\n1/ Generate a set of m unique CDR3 nucleotide sequences, call this set R (it is estimated that each individual has about 3x10^6 uniq seqs)\n   This steps take into account the CDR3-length distribution and the Amino-acid usage at each position of the CDR3.\n   Input: a/ len2count.txt with format: <aa-cdr3Length>\\t<count>\n          b/ aaUsage.txt with format: <aa-cdr3Length>\\t<Position>\\t<aa-Letter>\\t<count>\n          c/ m = size of the repertoire to be created\n   Generate: m nucleotide sequences such that when translated to amino acid sequences, follows the input length distribution and aaUsage.\n\n2/ Generate the repertoire (say P) of CDR3 of an individual from set R in (1):\n   Let M be the number of cells (number of total sequences) an individual has. It is estimated that there are about 6x10^7 CD8+ T cells per individual.\n   Populate repertoire P with the n sequences in R until P has M sequences. This step can assume a lognormal (previously used uniform) distribution of the uniq sequences or model clonal expansion.\n   The program model clonal expansion by in input pseudo repertoire with format <topFreq>,<secondTopFreq>,...,<ith-topFreq>. A random sequence will be drawn from n sequences in (a), and will populate P with topFreq*M counts. Then a second random seq will be drawn, etc until there are M sequences or the frequency list is done. If freq list is done and there are < M sequences in P, just randomly fill in P with the rest of the m sequences\n   Generate: M CDR3 nucleotide sequences\n\n3/ Sampling:\n   Repeat step (1) and (2) to generate another TCR repertoire for the second individual.\n   For each individual, randomly choose S sequences from the corresponding repertoire.\n   Calculate how much overlap the two samplings have.\n   Repeat this step with difference sampling size\n\n4/ a. Repeat step (3) -numSamplingPerSim times. Calculate mean & std\n(Or/And)\n   b. Repeat steps (1,2,3) N times (N simulations). Calculate mean statistics\n\n(5/ Plots)\n'''\n\nimport os, sys, re, time, random, copy, gzip\nimport cPickle as pickle\nfrom optparse import OptionParser\nimport xml.etree.ElementTree as ET\n\nfrom jobTree.scriptTree.target import Target\nfrom jobTree.scriptTree.stack import Stack\n\nfrom sonLib.bioio import logger\nfrom sonLib.bioio import system\nfrom sonLib.bioio import getTempDirectory\nfrom sonLib.bioio import setLogLevel\nimport numpy as np\nfrom scipy.stats import poisson, lognorm\n\n#from immunoseq.lib import *\n\n################## SEQUENCE OBJECTS ######################\nclass Seq:\n    def __init__(self, nuc, aa):\n        self.nuc = nuc\n        self.aa = aa\n        self.count = 0\n\n    def __cmp__(self, other):\n        return cmp(self.nuc, other.nuc)\n\n    def setCount(self, count):\n        self.count = count\n\n    def updateCount(self, add):\n        self.count += add\n\nclass Aaseq:\n    def __init__(self, aa):\n        self.aa = aa\n        self.count = 0\n\n    def __cmp__(self, other):\n        return cmp(self.aa, other.aa)\n\n    def setCount(self, count):\n        self.count = count\n\n    def updateCount(self, add):\n        self.count += add\n\n    def setFreq(self, total):\n        if total == 0:\n            self.freq = 0\n        else:\n            self.freq = 100.0*self.count/total\n\nclass Seqs(list):\n    def add(self, seq):\n        leftIndex = 0\n        rightIndex = len(self) -1\n        \n        if len(self) == 0 or seq > self[rightIndex]:\n            self.append(seq)\n        elif seq < self[leftIndex]:\n            self.insert(0, seq)\n        elif seq == self[leftIndex] or seq == self[rightIndex]:\n            return\n        else:\n            while True:\n                middleIndex = int( (leftIndex + rightIndex)/2 )\n                compare = cmp( self[middleIndex], seq )\n                if compare == 0: #sequence is already in the list, do not add, just return\n                    break\n                elif leftIndex == middleIndex: #add seq to the right of leftIndex\n                    self.insert(rightIndex, seq)\n                    break\n                elif compare > 0: #seq lies somewhere btw [middleIndex, rightIndex]\n                    rightIndex = middleIndex\n                elif compare < 0: \n                    leftIndex = middleIndex\n            \n    def search(self, seq):\n        leftIndex = 0\n        rightIndex = len(self) -1\n        \n        if len(self) == 0 or seq > self[rightIndex] or seq < self[leftIndex]: #not in list\n            return -1\n        elif seq == self[leftIndex]:\n            return leftIndex\n        elif seq == self[rightIndex]:\n            return rightIndex\n        else:\n            while True:\n                middleIndex = int( (leftIndex + rightIndex)/2 )\n                compare = cmp( self[middleIndex], seq )\n                if compare == 0: #sequence is already in the list, do not add, just return\n                    return middleIndex\n                elif leftIndex == middleIndex: #Not found\n                    return -1\n                elif compare > 0: #seq lies somewhere btw [middleIndex, rightIndex]\n                    rightIndex = middleIndex\n                elif compare < 0: \n                    leftIndex = middleIndex\n\n######################### MAIN PIPELINE ################################\n\n#============= SETTING UP SIMULATIONS ==============\nclass Setup( Target ):\n    \"\"\"Setting up simulations\n    \"\"\"\n    def __init__(self, options, doneSims):\n        Target.__init__(self, time = 0.00025)\n        self.options = options\n        self.doneSims = doneSims\n\n    def run(self):\n        setLogLevel(\"DEBUG\")\n        numSim = self.options.numSim\n        maxSimPerRun = self.options.maxSimPerRun\n        sims = min( [maxSimPerRun, numSim - self.doneSims] )\n        \n        outdir = os.path.join( self.options.outdir, \"sims\", str(self.doneSims) ) #outdir/sims/batchId\n        system(\"mkdir -p %s\" %outdir)\n        self.addChildTarget( SimulationBatch(self.options, outdir, sims, self.doneSims) )\n        \n        doneSims = self.doneSims + sims\n        if doneSims < numSim:\n            self.setFollowOnTarget( Setup(self.options, doneSims) ) #recusion call for next batch of simulations\n        else:\n            summarydir = os.path.join(self.options.outdir, \"summary\") #outdir/summary\n            statsdir = os.path.join(self.options.outdir, \"stats\") #outdir/stats\n            system(\"mkdir -p %s\" % statsdir)\n            readPickle = True\n            writePickle = False\n            writeSummary = True\n            self.setFollowOnTarget( Summary(summarydir, self.options.samSize, self.options.numSamples, statsdir, writePickle, writeSummary, readPickle) )\n\nclass SimulationBatch( Target ):\n    def __init__(self, options, outdir, numSim, batchid):\n        Target.__init__(self, time=0.00025)\n        self.options = options\n        self.outdir = outdir #outdir/sims/batchId\n        self.numSim = numSim\n        self.batchid = batchid\n\n    def run(self):\n        for i in xrange(self.numSim):\n            outdir = os.path.join(self.outdir, \"sim-%d\" %i) #outdir/sims/batchId/sim-Id\n            system(\"mkdir -p %s\" %outdir)\n            self.addChildTarget( Simulation(self.options, outdir, self.batchid, i) )\n         \n        #Combine the results\n        samplingsDir = os.path.join(self.options.outdir, \"samplings\", str(self.batchid)) #outdir/samplings/batchid\n        sumdir = os.path.join(self.options.outdir, \"summary\", str(self.batchid)) #outdir/summary/batchid\n        system(\"mkdir -p %s\" %sumdir) \n        readPickle = False\n        writePickle = True\n        writeSummary = False\n        #self.setFollowOnTarget( Summary(self.outdir, self.options.samSize, self.options.numSamples, sumdir, writePickle, writeSummary, readPickle) )\n        self.setFollowOnTarget( Summary(samplingsDir, self.options.samSize, self.options.numSamples, sumdir, writePickle, writeSummary, readPickle) )\n\n#------------- SIMULATION ---------------------\nclass Simulation( Target ):\n    \"\"\"Generate s simulations (corresponding to s samples (s individuals))\n       Creating TCR repertoire for each individuals\n       After got repertoires for All individuals, call following job to sampling from these repertoires\n    \"\"\"\n    def __init__(self, options, outdir, batchid, simid):\n        Target.__init__(self, time=0.00025)\n        self.options = options\n        self.outdir = outdir #outdir/sims/batchId/sim-Id\n        self.batchid = batchid\n        self.simid = simid\n    \n    def run(self):\n        globalTempDir = self.getGlobalTempDir()\n        for i in xrange(self.options.numSamples):\n            outdir = os.path.join(globalTempDir, str(i))\n            system(\"mkdir -p %s\" %outdir) #simTempDir/sampleID/\n            self.addChildTarget( SimulationSingle(self.options, outdir) )\n        \n        #Sampling from these repertoire:\n        samplingsOutdir = os.path.join(self.options.outdir, \"samplings\", str(self.batchid), \"sim-%d\" %self.simid)\n        system(\"mkdir -p %s\" %samplingsOutdir) #outdir/samplings/batchId/sim-id\n        self.setFollowOnTarget( Samplings(globalTempDir, self.outdir, self.options.numSamples, self.options.samSize, self.options.cutoffs, self.options.numSamplingPerSim, samplingsOutdir) )\n        #Calculate pair-wise overlap between the samples \n        #self.setFollowOnTarget( Overlap(globalTempDir, self.outdir, self.options.numSamples, self.options.samSize, self.options.cutoffs) )\n\nclass SimulationSingle( Target ):\n    \"\"\"Generate repertoire for one sample/individual\n       Starts by generating the uniq sequences of certain CDR3 length\n       Then calls follow on jobs to use these sequences to create the repertoire\n    \"\"\"\n    def __init__(self, options, outdir):\n        Target.__init__(self, time = 0.00025)\n        self.outdir = outdir #simTempDir/sampleID\n        self.options = options\n\n    def run(self):\n        globalTempDir = self.getGlobalTempDir()\n        #Generate repertoire of uniq sequences for each length:\n        for l in self.options.len2freq:#each length\n            size = self.options.totalClones*self.options.len2freq[l]\n            if l not in self.options.len2aaUsage or size == 0:\n                continue\n            aaUsage = self.options.len2aaUsage[l]\n            aa2codons = self.options.aa2codons\n            self.addChildTarget( UniqSeqs(globalTempDir, size, aaUsage, aa2codons) )\n        \n        self.setFollowOnTarget( Repertoire(globalTempDir, self.outdir, self.options.totalSeqs, self.options.topFreqs, self.options.samSize) )\n\n#+++++++++++ REPERTOIRE OF UNIQ SEQS/ CLONES ++++++++++++++\nclass UniqSeqs( Target ):\n    \"\"\"Generate repertoire of uniq sequences of a certain length\n    \"\"\"\n    def __init__(self, outdir, size, aaUsage, aa2codons):\n        Target.__init__(self)\n        self.outdir = outdir\n        self.size = size\n        self.aaUsage = aaUsage\n        self.aa2codons = aa2codons\n    \n    def run(self):\n        #Generate the sequences\n        seqs = getUniqSeqRep(self.size, self.aaUsage, self.aa2codons)\n        #Pickling the sequences to outdir\n        pickleFile = os.path.join( self.outdir, \"uSeqs-l%d.pickle\" %len(self.aaUsage) )\n        pickle.dump(seqs, gzip.open(pickleFile, \"wb\"))\n\n#+++++++++++++ PSEUDO REPERTOIRE ++++++++++++++++++\nclass Repertoire( Target ):\n    \"\"\"Combine the len-specific uniqSeqs repertoires\n       From uniqSeq repertoire, generate a pseudo repertoire, using topFreqs if available\n       Add jobs to run samplings with different sizes\n    \"\"\"\n    def __init__(self, indir, outdir, size, topFreqs, samSizes):\n        Target.__init__(self)\n        self.indir = indir #simSampleTempDir\n        self.outdir = outdir #simTempDir/sampleID\n        self.size = size\n        self.topFreqs = topFreqs\n        self.samSizes = samSizes\n\n    def run(self):\n        #Load pickles to get uniqSeqs\n        pickleFiles = os.listdir( self.indir )\n        seqs = []\n        for file in pickleFiles:\n            if re.search(\"pickle\", file):\n                seqs.extend( pickle.load( gzip.open( os.path.join(self.indir, file) , \"rb\") ) )\n                system( \"rm -f %s\" %(os.path.join(self.indir, file)) ) #Remove the uniq-sequences pickle file of the specific length after done loading\n\n        getRep( seqs, self.size, self.topFreqs )\n        \n        #Print repertoire to server so that it can be read by following jobs:\n        pickleFile = os.path.join(self.outdir, \"rep.pickle\") #simTempDir/sampleID/rep.pickle\n        pickle.dump( seqs, gzip.open(pickleFile, \"wb\") )\n\n#++++++++++++++ SAMPLING from pseudoRepertoire ++++++++++++++++\nclass Samplings( Target ):\n    \"\"\"(For each repertoier simulation,) Set up samplings for all pairs, all sampling sizes, all number of samplings.\n    \"\"\"\n    def __init__(self, indir, outdir, numSamples, samSizes, cutoffs, numSamplings, samplingsOutdir):\n        Target.__init__(self, time=0.00025)\n        self.indir = indir #simTempDir\n        self.outdir = outdir #outdir/sims/batchId/sim-Id\n        self.numSamples = numSamples\n        self.samSizes = samSizes\n        self.cutoffs = cutoffs\n        self.numSamplings = numSamplings\n        self.samplingsOutdir = samplingsOutdir #outdir/samplings/batchId/sim-id\n\n    def run(self):\n        for i in xrange(self.numSamplings):#Each sampling\n            for samsize in self.samSizes: #Each sampling size\n                outdir = os.path.join(self.outdir, \"sampling-%d\" %i) #outdir/sims/batchId/sim-Id/sampling-Id\n                for j in xrange(self.numSamples - 1):\n                    for k in xrange(self.numSamples): #Each pair\n                        pair = [j, k]\n                        self.addChildTarget( SamplingPair(self.indir, outdir, samsize, pair, self.cutoffs) )\n        #Summary the overlapping stats:\n        readPickle = False\n        writePickle = False\n        writeSummary = True\n        self.setFollowOnTarget( Summary(self.outdir, self.samSizes, self.numSamples, self.samplingsOutdir, writePickle, writeSummary, readPickle) )\n\nclass SamplingPair( Target ):\n    \"\"\"\n    \"\"\"\n    def __init__(self, indir, outdir, size, pair, cutoffs):\n        Target.__init__(self, time=0.00025)\n        self.indir = indir #simTempDir (which has simTempDir/sampleId/rep.pickle)\n        self.outdir = outdir #outdir/sims/batchId/sim-Id/sampling-Id\n        self.size = size\n        self.pair = pair\n        self.cutoffs = cutoffs\n\n    def run(self):\n        globalTempDir = self.getGlobalTempDir()\n        seqfiles = []\n        for i, p in enumerate(self.pair):\n            repertoireFile = os.path.join(self.indir, str(p), \"rep.pickle\") #simTempDir/sampleId/rep.pickle\n            outfile = os.path.join(globalTempDir, \"%d.pickle\" %i) #samplingPairTempDir/sampleId.pickle\n            seqfiles.append(outfile)\n            self.addChildTarget( Sampling(outfile, repertoireFile, self.size) )\n        \n        overlapOutdir = os.path.join( self.outdir, \"%d-%d\" %(self.pair[0], self.pair[1]) ) #outdir/sims/batchId/sim-Id/sampling-Id/sam1-sam2\n        system(\"mkdir -p %s\" %overlapOutdir)\n        overlapOutfile = os.path.join( overlapOutdir, \"%d.txt\" %self.size )\n        self.setFollowOnTarget( OverlapPairwise(seqfiles, overlapOutfile, self.cutoffs) )\n\nclass Sampling( Target ):\n    \"\"\"Sample from the input repertoire for \"size\" sequences\n    \"\"\"\n    def __init__(self, outfile, repertoireFile, samsize):\n        Target.__init__(self)\n        self.outfile = outfile\n        self.repfile = repertoireFile\n        self.size = samsize\n\n    def run(self):\n        seqs = pickle.load( gzip.open(self.repfile, \"rb\") ) \n        samseqs = sampling(seqs, self.size)\n\n        #Pickling seqs:\n        pickle.dump( samseqs, gzip.open(self.outfile, \"wb\") )\n\n#----------- OVERLAP -----------\nclass OverlapPairwise( Target ):\n    \"\"\"Output file: %cutoff\\tclones1\\tclones2\\toverlap\\t%1overlap2\\t%2overlap1\\t%reads1overlap2\\t%reads2overlap1\n    \"\"\"\n    def __init__(self, seqsFiles, outfile, cutoffs):\n        Target.__init__(self, time=0.001)\n        self.outfile = outfile\n        self.seqsFile1 = seqsFiles[0]\n        self.seqsFile2 = seqsFiles[1]\n        self.cutoffs = cutoffs\n\n    def run(self):\n        seqs1 = pickle.load( gzip.open(self.seqsFile1, \"rb\") )\n        seqs2 = pickle.load( gzip.open(self.seqsFile2, \"rb\") )\n        reads1, reads2, clones1, clones2, stats1, stats2 = getOverlap(seqs1, seqs2, self.cutoffs)\n        \n        #Print stats\n        f = open(self.outfile, \"w\")\n        f.write(\"#%Cutoff\\tClones1\\tClones2\\tOverlap1\\tOverlap2\\t%1overlap2\\t%2overlap1\\t%reads1overlap2\\t%reads2overlap1\\n\")\n        for i,c in enumerate(self.cutoffs):\n            oc1 = stats1[\"oclones\"][i]\n            or1 = stats1[\"oreads\"][i]\n            t1 = clones1[i]\n            r1 = reads1[i]\n            \n            oc2 = stats2[\"oclones\"][i]\n            or2 = stats2[\"oreads\"][i]\n            t2 = clones2[i]\n            r2 = reads2[i]\n            \n            f.write(\"%.3f\\t%d\\t%d\\t%d\\t%d\\t%.2f\\t%.2f\\t%.2f\\t%.2f\\n\" %( c, t1, t2, oc1, oc2, getPc(oc1, t1), getPc(oc2, t2), getPc(or1, r1), getPc(or2, r2) ))\n        f.close()\n\n#================ AVERAGE ACROSS THE SIMULATIONS ====================\nclass Summary( Target ):\n    def __init__(self, indir, samSizes, numSamples, outdir, writePickle, writeSummary, readPickle):\n        Target.__init__(self, time=0.001)\n        self.indir = indir #outdir/sims/batchId/sim-Id; #outdir/samplings/batchId; #outdir/summary\n        self.samSizes = samSizes\n        self.numSamples = numSamples\n        self.outdir = outdir #outdir/samplings/batchId/sim-Id; #outdir/summary/batchid; #outdir/stats\n        self.writePickle = writePickle\n        self.writeSummary = writeSummary\n        self.readPickle = readPickle\n\n    def run(self):\n        #Get the pairs:\n        for i in xrange(self.numSamples - 1):\n            for j in xrange(self.numSamples):\n                pair = \"%d-%d\" %( i, j )\n                outdir = os.path.join(self.outdir, pair) #outdir/samplings/batchId/sim-Id/pair; #outdir/summary/batchid/pair \n                system(\"mkdir -p %s\" %outdir)\n                for samsize in self.samSizes:\n                    self.addChildTarget( SummarySamsize(self.indir, samsize, pair, outdir, self.writePickle, self.writeSummary, self.readPickle) )\n        if not self.writePickle:\n            self.setFollowOnTarget( CleanupSummary(self.indir) )\n\nclass SummarySamsize( Target ):\n    def __init__(self, indir, samsize, pair, outdir, writePickle, writeSummary, readPickle):\n        Target.__init__(self, time=0.001)\n        self.indir = indir #outdir/sims/batchId/sim-Id; #outdir/samplings/batchId; #outdir/summary\n        self.samsize = samsize\n        self.pair = pair\n        self.outdir = outdir #outdir/samplings/batchId/sim-Id/pair; #outdir/summary/batchid/pair; #outdir/stats/pair\n        self.writePickle = writePickle\n        self.writeSummary = writeSummary\n        self.readPickle = readPickle\n\n    def run(self):\n        #Get the stats:\n        cutoff2stats = {} #key = cutoff, val = [clones1, clones2, overlap1, overlap2, %1oc2, %2oc1, %1or2, %2or1]\n        indirs = os.listdir(self.indir)\n        for indir in indirs:\n            if not os.path.isdir( os.path.join(self.indir,indir) ):\n                continue\n            file = os.path.join(os.path.join(self.indir,indir), self.pair, \"%d.txt\" %self.samsize)\n            if self.readPickle:\n                file = os.path.join(os.path.join(self.indir,indir), self.pair, \"%d.pickle\" %self.samsize)\n            \n            if not os.path.exists(file):\n                raise NonExistFileError(\"File %s does not exist\\n\" %file)\n            \n            if not self.readPickle:\n                currCutoff2stats = readStats(file)\n            else:\n                currCutoff2stats = pickle.load( gzip.open(file, \"rb\") )\n            for c, stats in currCutoff2stats.iteritems():\n                if c not in cutoff2stats:\n                    cutoff2stats[c] = stats\n                else:\n                    for i, s in enumerate(stats):\n                        cutoff2stats[c][i].extend(s)\n        \n        #Calculate average and standard deviation:\n        if self.writePickle:\n            outfile = os.path.join(self.outdir, \"%d.pickle\" %self.samsize)\n            pickle.dump(cutoff2stats, gzip.open(outfile, \"wb\"))\n        \n        if self.writeSummary:\n            for c, stats in cutoff2stats.iteritems():\n                for i, s in enumerate(stats):\n                    cutoff2stats[c][i] = [np.mean( s ), np.std( s )]\n                    #cutoff2stats[c][i] = float(s)/self.denom\n\n            #Print to output file:\n            outfile = os.path.join(self.outdir, \"%d.txt\" %self.samsize)\n            f = open(outfile, 'w')\n            f.write(\"#%Cutoff\\tClones1\\tClones2\\toverlap1\\toverlap2\\t%1overlap2\\t%2overlap1\\t%reads1overlap2\\t%reads2overlap1\\t\")\n            f.write(\"StdClones1\\tStdClones2\\tStdOverlap1\\tStdOverlap2\\tStd%1overlap2\\tStd%2overlap1\\tStd%reads1overlap2\\tStd%reads2overlap1\\n\")\n            for c in sorted( cutoff2stats.keys() ):\n                stats = cutoff2stats[c]\n                meanStats = [ \"%.4f\" % s[0] for s in stats ]\n                stdStats = [ \"%.4f\" % s[1] for s in stats ]\n                f.write( \"%.3f\\t%s\\t%s\\n\" %(c, \"\\t\".join(meanStats), \"\\t\".join(stdStats)) )\n            f.close()\n\n#=============== CLEANUP =================\nclass CleanupSummary ( Target ):\n    def __init__(self, indir):\n        Target.__init__(self, time = 0.00025)\n        self.indir = indir\n\n    def run(self):\n        system(\"rm -fR %s\" %self.indir)\n\n####################### UTILITIES FUNCTIONS ##########################\n\n#============== calculate overlap =================\ndef getOverlap( seqs1, seqs2, cutoffs ):\n    #Initialize stats:\n    stats1 = {\"oclones\":[], \"oreads\":[]}\n    stats2 = {\"oclones\":[], \"oreads\":[]}\n    for i in xrange( len(cutoffs) ):\n        for k in stats1:\n            stats1[k].append(0)\n            stats2[k].append(0)\n\n    #get number of clones that pass the cutoff:\n    reads1, clones1, total1 = getNumClones(seqs1, cutoffs)\n    reads2, clones2, total2 = getNumClones(seqs2, cutoffs)\n\n    if total1 == 0 or total2 == 0:\n        return\n    #get overlap:\n    for s1 in seqs1:\n        i2 = seqs2.search(s1)\n        if i2 == -1:#not found in repertoire 2\n            continue\n        s2 = seqs2[i2]\n        for i, cutoff in enumerate(cutoffs):\n            #if s1.freq >= cutoff and s2.freq >= cutoff:\n            if s1.freq >= cutoff:\n                stats1[\"oclones\"][i] += 1\n                stats1[\"oreads\"][i] += s1.count\n            if s2.freq >= cutoff:\n                stats2[\"oclones\"][i] += 1\n                stats2[\"oreads\"][i] += s2.count \n    return reads1, reads2, clones1, clones2, stats1, stats2\n\ndef getNumClones(seqs, cutoffs):\n    reads = [ 0 for c in cutoffs ] \n    clones = [ 0 for c in cutoffs ]\n    total = sum([ s.count for s in seqs ])\n    for s in seqs:\n        s.setFreq(total)\n        for i,c in enumerate(cutoffs):\n            if s.freq >= c:\n                clones[i] += 1\n                reads[i] += s.count\n    return reads, clones, total\n\n#================ GENERATE PSEUDO REPERTOIRE =========\ndef sampling( seqs, size ):\n    samseqs = Seqs()\n    indexList = []\n    for i, s in enumerate(seqs):\n        indexList.extend( [ i for j in xrange( int(s.count)) ] )\n    \n    for j in xrange(size):\n        i = random.randint(0, len(indexList) -1) #randomly pick one sequence from the repertoire\n        s = Aaseq( seqs[indexList[i]].aa )\n        #s = copy.copy( seqs[indexList[i]] )\n        sindex = samseqs.search(s) #Search for this sequence in the current set of picked sequences\n        \n        #print [ seq.aa for seq in samseqs]\n        #print \"%s\" %s.aa\n        #print sindex\n        \n        if sindex >=0:\n            samseqs[sindex].updateCount(1)\n        else:#sequence hasn't picked yet\n            s.setCount(1)\n            samseqs.add(s)\n    return samseqs\n\n#get the repertoire using topFreqs if available, otherwise assume lognormal distribution\n#IMCOMPLETE\ndef getRepLognorm( seqs, size, mean, std ):\n    #mean = #mean of log(clonesize)\n    #std = #standard deviation of log(clonesize)\n    \n    #Generate repertoire:\n    topindices = []\n    sizeToFill = size\n\n    if topFreqs:\n        for i, f in enumerate(topFreqs):\n            index = random.randint(0, len(seqs) -1)\n            while (index in topindices):\n                index = random.randint(0, len(seqs) -1)\n            topindices.append(index)\n            count = int(f*size)\n            seqs[index].setCount( count )\n        sizeToFill = size - int( sum(topFreqs)*size )\n    \n    for i in xrange(sizeToFill):\n        index = random.randint(0, len(seqs) -1)\n        while (index in topindices):\n            index = random.randint(0, len(seqs) -1)\n     \n\n#get the repertoire using topFreqs if available, otherwise assume uniform distribution\ndef getRep( seqs, size, topFreqs ):\n    #Generate repertoire:\n    topindices = []\n    sizeToFill = size\n    if topFreqs:\n        for i, f in enumerate(topFreqs):\n            index = random.randint(0, len(seqs) -1)\n            while (index in topindices):\n                index = random.randint(0, len(seqs) -1)\n            topindices.append(index)\n            count = int(f*size)\n            seqs[index].setCount( count )\n        sizeToFill = size - int( sum(topFreqs)*size )\n    \n    for i in xrange(sizeToFill):\n        index = random.randint(0, len(seqs) -1)\n        while (index in topindices):\n            index = random.randint(0, len(seqs) -1)\n        seqs[index].updateCount(1)\n\ndef getUniqSeqRep(size, aaUsage, aa2codons):\n    \"\"\"Generate \"size\" number of unique nucleotide sequences with length (len(aaUsage))\n    Using the amino-acid Usage from aaUsage, and codon usage from aa2codons\n    \"\"\"\n    seqs = Seqs() #list of sequences\n    while len(seqs) < size:\n        aa = getAaSeq(aaUsage)\n        nuc = aa2nuc(aa, aa2codons)\n        seq = Seq(nuc, aa)\n        seqs.add(seq)\n    return seqs\n\ndef readStats( file ):\n    cutoff2stats = {} #key = cutoff, val = [clones1, clones2, overlap, %1oc2, %2oc1, %1or2, %2or1]\n    f = open(file, 'r')\n    for line in f:\n        if line[0] == \"#\":\n            continue\n        items = line.split(\"\\t\")\n        if len(items) < 9:\n            raise FileFormatError(\"Wrong file format, 9 fields are required, see %d. File %s\\n\" %(len(items), file))\n        cutoff = float(items[0])\n        #stats = [int(items[1]), int(items[2]), int(items[3]), int(items[4]), float(items[5]), float(items[6]), float(items[7]), float(items[8])]\n        stats = [ [float(items[i])] for i in xrange(1,9) ]\n        #stats = [float(items[1]), float(items[2]), float(items[3]), float(items[4]), float(items[5]), float(items[6]), float(items[7]), float(items[8])]\n        cutoff2stats[cutoff] = stats\n    f.close()\n    return cutoff2stats\n\ndef getPc(count, total):\n    if total == 0:\n        return 0\n    return 100.0*count/total\n\ndef getAaSeq(aaUsage):\n    aa = \"\"\n    seqlen = len(aaUsage)\n    for i in xrange(seqlen):\n        letters = aaUsage[i]\n        j = random.randint(0, len(letters) -1)\n        aa += letters[j] \n    return aa\n\ndef aa2nuc(aaseq, aa2codons):\n    nucseq = ''\n    for aa in aaseq:\n        codons = aa2codons[aa]\n        i = random.randint( 0, len(codons) -1 )\n        nucseq += codons[i]\n    return nucseq\n\n#================ ERROR CLASSES ============\nclass FileFormatError(Exception):\n    pass\n\nclass TopFreqError(Exception): \n    pass\n\nclass NonExistFileError(Exception):\n    pass\n\n#================ READ INPUT FILES ================\ndef readCodonUsage(file):\n    \"\"\"\n    \"\"\"\n    aa2codons = {} #key = aa, val = {codon:freq}\n    aa2codon2freq = {}\n    f = open(file, 'r')\n    for line in f:\n        line.strip()\n        if line == \"\" or line[0] == \"#\":\n            continue\n        items = line.split()\n        if len(items) %4 > 0:\n            raise FileFormatError(\"Wrong codonUsage format\\n\")\n        for i in xrange(0, len(items), 4):\n            codon = items[i]\n            aa = items[i+1]\n            freq = float( items[i+2] )\n            if aa not in aa2codon2freq:\n                aa2codon2freq[aa] = {codon: freq}\n            else:\n                aa2codon2freq[aa][codon] = freq\n    f.close()\n    \n    #Normalize\n    normlen = 100\n    for aa in aa2codon2freq:\n        aa2codons[aa] = []\n        for codon, freq in aa2codon2freq[aa].iteritems():\n            for i in xrange( int(freq*normlen) ):\n                aa2codons[aa].append(codon)\n\n    return aa2codons\n\ndef readAaUsage(file):\n    '''\n    Return: len2aaUsage = {} #key = length, val= position-array, each item represent a.a usage of that position.\n    Example: \n    9 1 C 10\n    9 2 A 7\n    9 2 R 1\n    9 2 S 3\n    9 2 V 1\n    len2aaUsage = {9:[\"CCCCCCCCCC\", \"AAAAAAARSSSV\"]}\n    '''\n    len2aaUsage = {} #key = length, val= position-array, each item represent a.a usage of that position.\n    len2listLetter2freq = {}\n    f = open(file, 'r')\n    for line in f:\n        line = line.strip()\n        if line == \"\" or line[0] == \"#\":\n            continue\n        items = line.split()\n        if len(items) != 4:\n            raise FileFormatError(\"Wrong aaUsage file format. Required 4 fields, have %d. Line: %s\\n\" %(len(items), line) )\n        l = int( items[0] )\n        pos = int( items[1] ) - 1\n        letter = items[2]\n        count = int( items[3] )\n\n        if l < 0 or pos < 0 or count < 0:\n            raise ValueError(\"readAaUsage: length, position, count must >=0\")\n        if pos >= l:\n            raise FileFormatError(\"readAaUsage: Column 2 value (Position) must <= col 1 value (length)\\n\")\n        if l not in len2listLetter2freq:\n            len2listLetter2freq[ l ] = [{} for i in xrange(l)]\n        len2listLetter2freq[ l ][ pos ][ letter ] = count\n    f.close()\n\n    #Make sure that for each length, usage for all positions are provided from input file:\n    for l in len2listLetter2freq:\n        for i in xrange(l):\n            if len( len2listLetter2freq[l][i].keys() ) == 0:\n                raise FileFormatError(\"readAaUsage requires input file to have AA usage for all positions of each length. Could not find usage for length %d, position %d.\" %(l, i + 1))\n\n    #Normalize counts:\n    normLen = 10000 #equivalent the number of digits of the frequencies got taken into account\n    for l in len2listLetter2freq:\n        posList = len2listLetter2freq[l]\n        len2aaUsage[ l ] = []\n        for i, letter2count in enumerate(posList):\n            total = sum([ letter2count[letter] for letter in letter2count ])\n            if total > 0:\n                for letter, count in letter2count.iteritems():\n                    letter2count[letter] = normLen*count/total\n            posLetters = \"\".join([ letter*count for letter, count in letter2count.iteritems()])\n            len2aaUsage[l].append(posLetters)\n\n    return len2aaUsage\n\ndef getUniAaUsage(lens):\n    aas = \"ARNDCEQGHILKFPSTWYV\"\n    len2aaUsage = {}\n    for l in lens:\n        if not isinstance(l, int):\n            raise ValueError(\"getUniAaUsage, input lengths contain non-integer items\\n\")\n        len2aaUsage[l] = []\n        for i in xrange(l):#each position\n            len2aaUsage[l].append(aas)\n    return len2aaUsage\n\ndef readCdr3LenDist(file):\n    '''Get length distribution of CDR3 amino-acid sequences. Format of input file: <length>\\t<count>\n    Return a dictionary len2freq, where key=length and val = freq of that length\n    '''\n    len2freq = {} #key = length, val=frequency\n    f = open(file, 'r')\n    total = 0\n    for line in f:\n        line = line.strip()\n        if line == \"\" or line[0] == \"#\":\n            continue\n        #items = line.split(\"\\t\")\n        items = line.split()\n        if len(items) < 2:\n            raise FileFormatError(\"Wrong cdr3LenDist file format. Require two fields: <length>\\\\t<count>\\n.%s\\n\" %line)\n        if items[0] == \"TOTAL\":\n            continue\n        try:\n            l = int( (items[0].split(\".\"))[0] )\n            c = int( items[1] )\n        except ValueError:\n            raise ValueError(\"First and Second columns in cdr3LenDist file %s must be integer\\n\" %file)\n\n        total += c\n        if l not in len2freq:\n            len2freq[l] = c\n        else:\n            len2freq[l] += c\n    #Normalize counts to frequencies:\n    if total > 0: \n        for l, c in len2freq.iteritems():\n            len2freq[l] = float(c)/total\n    f.close()\n    return len2freq\n\ndef getUniCdr3LenDist():\n    len2freq = {}\n    minlen = 9\n    maxlen = 23\n    r = maxlen + 1 - minlen\n    for l in xrange(minlen, maxlen + 1):\n        len2freq[l] = 1.0/r\n    return len2freq\n\ndef getTopFreqs( topFreqs, totalClones, totalSeqs ):\n    f = open(topFreqs, \"r\")\n    freqs = []\n    for line in f:\n        line = line.strip()\n        freq = float(line)\n        if not isinstance(freq, float):\n            raise ValueError(\"Wrong format topFreqs file. Requires floats.\\n\")\n        if freq <= 0:\n            raise ValueError(\"Frequencies in topFreqs file (%s) must be positive. Got %f\\n\" %(topFreqs, freq))\n\n        freqs.append( freq )\n    #Make sure that sum of freqs <= 1 - (totalClones - len(freqs))/totalSeqs\n    if sum(freqs) > 1 - float((totalClones - len(freqs)))/totalSeqs:\n        raise TopFreqError(\"Frequencies of top clones add up to be larger than permitted\")\n    topFreqs = freqs\n    f.close()\n    return topFreqs\n    \n################### OPTIONS #########################\ndef checkOptions( parser, options, args ):\n    #Check output directory\n    if not os.path.exists( options.outdir ):\n        system( \"mkdir %s\\n\" %(options.outdir) )\n    \n    #Number of samples:\n    if not isinstance(options.numSamples, int):\n        parser.error(\"Number of samples must be in integer\\n\")\n    if options.numSamples < 2:\n        parser.error(\"Number of samples must > 2. %d was given\\n\" %options.numSamples)\n    \n    #Make sure the number of totalClones < totalSeqs:\n    if options.totalClones > options.totalSeqs:\n        raise ValueError(\"Total number of clones must be smaller than total number of sequences. %d clones and %d sequences were given\" %(options.totalClones, options.totalSeqs) ) \n\n    #sampling sizes:\n    options.samSize = [long(s) for s in options.samSize.split(\",\")]\n\n    #Top Freqs:\n    if options.topFreqs:\n        if not os.path.exists( options.topFreqs ):\n            parser.error(\"TopFreqs file %s does not exists\\n\" %options.topFreqs)\n        options.topFreqs = getTopFreqs( options.topFreqs, options.totalClones, options.totalSeqs )\n\n    #Cutoffs:\n    options.cutoffs = [ float(c) for c in options.cutoffs.split(\",\") ]\n     \n    #CDR3 length distribution\n    if options.cdr3LenDist:\n        if not os.path.exists(options.cdr3LenDist):\n            parser.error(\"cdr3LenDist file %s does not exist\\n\" %options.cdr3LenDist)\n        options.len2freq = readCdr3LenDist(options.cdr3LenDist)\n    else:\n        options.len2freq = getUniCdr3LenDist() \n\n    if options.aaUsage:\n        if not os.path.exists(options.aaUsage):\n            parser.error(\"aaUsage file %s does not exist\\n\" %options.aaUsage)\n        options.len2aaUsage = readAaUsage(options.aaUsage)\n    else:\n        options.len2aaUsage = getUniAaUsage( range(9, 24) )\n    \n    if not options.codonUsage:\n        parser.error(\"Required argument codonUsage. None was given\\n\")\n    if not os.path.exists(options.codonUsage):\n        parser.error(\"codonUsage file %s does not exist\\n\" %options.codonUsage)\n    options.aa2codons = readCodonUsage(options.codonUsage)\n\ndef addOptions( parser ):\n    #parser.add_option(\"-i\", \"--indir\", dest = 'indir', help=\"Required argument. Input directory that contains input fastq files (each represents a sample)\\n\")\n    #parser.add_option(\"-n\", \"--popCdr3\", dest='popCdr3', type=\"long\", default=5*(10**11), help=\"Estimated number of unique CDR3 nucleotide sequences in the population. Default=5x10^11\")\n    parser.add_option(\"-o\", \"--outdir\", dest = 'outdir', default=\".\", help=\"Output directory. Default: current directory\\n\")\n    parser.add_option(\"-N\", \"--numSim\", dest=\"numSim\", type=\"int\", default=100, help=\"Number of repertoire simulations. Default = 100\")\n    parser.add_option(\"--numSamplingPerSim\", dest=\"numSamplingPerSim\", type=\"int\", default=100, help=\"Number of samplings per repertoire simulation. Default = %default\")\n    parser.add_option(\"-m\", \"--totalClones\", dest=\"totalClones\", type=\"long\", default=3*(10**6), help=\"Estimated number of unique CDR3 nucleotide sequences in one individual. Default=3x10^6\")\n    parser.add_option(\"-M\", \"--totalSeqs\", dest=\"totalSeqs\", type=\"long\", default=6*(10**7), help=\"Estimated number of CDR3 nucleotide sequences in one individual. Default=6x10^7 (number of CD8+ T cells per person)\")\n    parser.add_option(\"-S\", \"--samplingSize\", dest=\"samSize\", default=\"50000,100000,150000,200000\", help=\"Comma separated string of sampling sizes. Default=%default\")\n    #parser.add_option(\"-a\", \"--aaUsage\", dest=\"aaUsage\", help=\"Amino acid usage of the CDR3 sequences. Format:<aa-cdr3-length>\\t<position>\\t<letter>\\t<count>. If not specified, use uniform distribution\")\n    parser.add_option(\"-a\", \"--aaUsage\", dest=\"aaUsage\", help=\"Amino acid usage of the CDR3 sequences. Format:<aa-cdr3-length>\\t<position>\\t<letter>\\t<count>. If not specified, use lognormal distribution\")\n    parser.add_option(\"-l\", \"--cdr3LenDist\", dest=\"cdr3LenDist\", help=\"CDR3 length distribution. Format: <aa-cdr3-length>\\t<count>\")\n    parser.add_option(\"-c\", \"--codonUsage\", dest=\"codonUsage\", default=\"~/codonUsage.txt\", help=\"Codon usage table\")\n    #parser.add_option(\"-f\", \"--topFreqs\", dest=\"topFreqs\", help=\"Frequencies of x top clones. Sum of these freqs must <= (M - (m-x))/M. If not specified, use uniform distribution\")\n    parser.add_option(\"-f\", \"--topFreqs\", dest=\"topFreqs\", help=\"Frequencies of x top clones. Sum of these freqs must <= (M - (m-x))/M. If not specified, use lognormal distribution\")\n    parser.add_option(\"-s\", \"--numSamples\", dest=\"numSamples\", type=\"int\", default=2, help=\"Number of samples (individuals/repertoires) to compare. Default=2.\")\n    parser.add_option(\"-p\", \"--cutoffs\", dest=\"cutoffs\", default=\"0,0.001,0.01,0.05,0.1,0.5,1,5,10\", help=\"Comma separated clonesize percentage cutoffs. Default='0,0.001,0.01,0.05,0.1,0.5,1,5'\")\n    parser.add_option(\"--maxSimPerRun\", dest=\"maxSimPerRun\", type='int', default=100, help=\"Maximum number of simulations per batch. Default=100\")\n\n################# MAIN ##############################\ndef main():\n    parser = OptionParser()\n    Stack.addJobTreeOptions( parser )\n\n    addOptions( parser )\n\n    options, args = parser.parse_args()\n    checkOptions( parser, options, args )\n\n    i = Stack( Setup(options, 0) ).startJobTree( options )\n    if i:\n        raise RuntimeError(\"The jobtree contains %d failed jobs.\\n\" %i)\n\nif __name__ == \"__main__\":\n    #from tcrRepSim import *\n    from immunoseq.src.tcrRepSim import *\n    main()\n\n\n\n\n", "meta": {"hexsha": "c8d411e9ae38c0075f38a9df3fb89654fe68d15d", "size": 39026, "ext": "py", "lang": "Python", "max_stars_repo_path": "bin/tcrRepSim.py", "max_stars_repo_name": "ngannguyen/immunoseq", "max_stars_repo_head_hexsha": "dfaac691e7b8ab93337f6d1619b6d67533ff9394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-15T12:18:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T03:31:23.000Z", "max_issues_repo_path": "src/tcrRepSim.py", "max_issues_repo_name": "ngannguyen/immunoseq", "max_issues_repo_head_hexsha": "dfaac691e7b8ab93337f6d1619b6d67533ff9394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tcrRepSim.py", "max_forks_repo_name": "ngannguyen/immunoseq", "max_forks_repo_head_hexsha": "dfaac691e7b8ab93337f6d1619b6d67533ff9394", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4657236126, "max_line_length": 439, "alphanum_fraction": 0.6143084098, "include": true, "reason": "import numpy,from scipy", "num_tokens": 10405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.1950856071454125}}
{"text": "## Requirements\n\n### Packages\nimport os\nimport json\nimport gzip\nimport numpy as np\n\nfrom bandits_to_rank.environment import Environment_PBM, PositionsRanking\nfrom bandits_to_rank.opponents import greedy\nfrom bandits_to_rank.opponents.pbm_pie import PBM_PIE_Greedy_SVD, PBM_PIE_semi_oracle, PBM_PIE_Greedy_MLE\nfrom bandits_to_rank.opponents.pbm_ucb import PBM_UCB_Greedy_SVD, PBM_UCB_semi_oracle, PBM_UCB_Greedy_MLE\nfrom bandits_to_rank.opponents.pbm_ts import PBM_TS_Greedy_SVD, PBM_TS_semi_oracle, PBM_TS_Greedy_MLE\nfrom bandits_to_rank.opponents.bc_mpts import BC_MPTS_Greedy_SVD, BC_MPTS_semi_oracle,BC_MPTS_Greedy_MLE\n#from bandits_to_rank.opponents.pmed import PMED   # loaded only before usage to load tensorflow library only when required\nfrom bandits_to_rank.opponents.top_rank import TOP_RANK\nfrom bandits_to_rank.opponents.grab import GRAB\nfrom bandits_to_rank.opponents.f_grab import sGRAB\nfrom bandits_to_rank.opponents.combucb import CombUCB1, KL_CombUCB1\nfrom bandits_to_rank.opponents.pb_mhb import *\nfrom bandits_to_rank.referee import Referee\n\n# set.seed(123)\n\n\n# Path to bandits-to-rank module\nimport bandits_to_rank\n\npackagedir = os.path.dirname(bandits_to_rank.__path__[0])\n\n\nclass NdArrayEncoder(json.JSONEncoder):\n    def default(self, obj):\n        if isinstance(obj, np.ndarray):\n            return obj.tolist()\n        if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,\n                            np.int16, np.int32, np.int64, np.uint8,\n                            np.uint16, np.uint32, np.uint64)):\n            return int(obj)\n        # Let the base class default method raise the TypeError\n        return json.JSONEncoder.default(self, obj)\n\n\ndef record_zip(filename, dico):\n    print(type(dico))\n    print('file', filename)\n    json_str = json.dumps(dico, cls=NdArrayEncoder)\n    json_bytes = json_str.encode('utf-8')\n    with gzip.GzipFile(filename, 'w') as fout:\n        fout.write(json_bytes)\n    return 'done'\n\n\nclass Parameters():\n    \"\"\" Parameters used for the experiment\n\n    # Environement\n        env\n        env_name        str used for name of files\n        logs_env_name   (only for merge)\n\n    # Player\n        player\n        player_name\n\n    # Rules\n        rules_name\n        referee\n\n    # Sub-experiment\n        first_game      (only for play)\n        end_game        (only for play)\n        input_path      (only for merge)\n        output_path\n        force           (only for play)\n    \"\"\"\n\n    def __init__(self):\n        self.env = Environment_PBM([1], [1], label=\"fake\")\n        self.positions_ranking = PositionsRanking.SHUFFLE_EXCEPT_FIRST  # default: shuffle kappas before each game\n        self.nb_relevant_positions = None  # default: compute reward at each position\n        self.rng = np.random.default_rng()\n\n    #########\" PBM_Setting\n    def set_positions_ranking(self, positions_ranking):\n        self.positions_ranking = positions_ranking\n\n        # tag for file names and logs\n        if positions_ranking == PositionsRanking.FIXED:\n            raise ValueError('fixed ranking of positions should be set by the player')\n        elif positions_ranking == PositionsRanking.DECREASING:\n            # TODO: better naming for PBM '__decreasing_kappa'\n            # TODO: better naming for CM '__std_order_on_views'\n            tag = '__sorted_kappa' if type(self.env) == Environment_PBM else ''\n        elif positions_ranking == PositionsRanking.SHUFFLE:\n            # TODO: better naming for CM '__random_order_on_views'\n            tag = '__shuffled_kappa' if type(self.env) == Environment_PBM else '_order_view_shuffle'\n        elif positions_ranking == PositionsRanking.SHUFFLE_EXCEPT_FIRST:\n            # TODO: better naming for PBM __shuffled_kappa_except_first\n            tag = '' if type(self.env) == Environment_PBM else '__random_order_on_views_except_first'\n        elif positions_ranking == PositionsRanking.INCREASING:\n            tag = ('__increasing_kappa' if type(self.env) == Environment_PBM else '__reverse_order_on_views')\n        elif positions_ranking == PositionsRanking.INCREASING_EXCEPT_FIRST:\n            tag = ('__increasing_kappa_except_first' if type(self.env) == Environment_PBM\n                   else '__reverse_order_on_views_except_first')\n        else:\n            raise ValueError(f'unhandled ranking on positions: {positions_ranking}')\n        self.env_name += tag\n        self.logs_env_name += tag\n        self.env.label += tag\n\n    def set_env_KDD_all(self):\n        \"\"\"!!! only to merge logs from several queries of KDD data !!!\"\"\"\n        self.env_name = f'KDD_all'\n        self.logs_env_name = f'KDD_[0-9]*_query'\n\n    def set_env_KDD(self, query):\n        # load KDD data\n        # todo: to put in bandits_to_rank.data\n        with open(packagedir + '/data/param_KDD.txt', 'r') as file:\n            dict_theta_query = json.load(file)\n        query_name, query_params = list(dict_theta_query.items())[query]\n\n        # set environement\n        self.env_name = f'KDD_{query}_query'\n        self.logs_env_name = self.env_name\n        self.env = Environment_PBM(query_params['thetas'], query_params['kappas']\n                                   , label='%s (%d for us)' % (query_name, query))\n\n    def set_env_Yandex_all(self):\n        \"\"\"!!! only to merge logs from several queries of Yandex data !!!\"\"\"\n        self.env_name = f'Yandex_all'\n        self.logs_env_name = f'Yandex_[0-9]*_query'\n\n    def set_env_Yandex(self, query):\n        # load Yandex data\n        # todo: to put in bandits_to_rank.data\n        with open(packagedir + '/data/param_Yandex.txt', 'r') as file:\n            dict_theta_query = json.load(file)\n        query_name, query_params = list(dict_theta_query.items())[query]\n\n        # reduce to 10 products, 5 positions\n        thetas = np.sort(query_params['thetas'])[:-11:-1]\n        kappas = np.sort(query_params['kappas'])[:-6:-1]\n\n        # set environement\n        self.env_name = f'Yandex_{query}_query'\n        self.logs_env_name = self.env_name\n        self.env = Environment_PBM(thetas, kappas\n                                   , label='%s (%d for us)' % (query_name, query))\n\n    def set_env_Yandex_equi_all(self, K):\n        \"\"\"!!! only to merge logs from several queries of Yandex data !!!\"\"\"\n        self.env_name = f'Yandex_equi_{K}_K_all'\n        self.logs_env_name = f'Yandex_equi_{K}_K__[0-9]*_query'\n\n    def set_env_Yandex_equi(self, query, K):\n        # load Yandex data\n        with open(packagedir + '/data/param_Yandex.txt', 'r') as file:\n            dict_theta_query = json.load(file)\n        query_name, query_params = list(dict_theta_query.items())[query]\n\n        # reduce to 10 products, 10 positions\n        index_max = 1 + K\n        thetas = np.sort(query_params['thetas'])[:-index_max:-1]\n        kappas = np.sort(query_params['kappas'])[:-index_max:-1]\n\n        # set environement\n        self.env_name = f'Yandex_equi_{K}_K__{query}_query'\n        self.logs_env_name = self.env_name\n        self.env = Environment_PBM(thetas, kappas, label=f'Yandex equi K={K} {query} ({query_name} for Yandex)')\n\n    def set_env_test(self):\n        \"\"\"Purely simulated environment with standard click's probabilities\"\"\"\n        kappas = [1, 0.6, 0.3]\n        thetas = [0.1, 0.5, 0.1, 0.6, 0.1, 0.4, 0.1, 0.1, 0.1, 0.1]\n        self.env_name = f'purely_simulated__test'\n        self.logs_env_name = self.env_name\n        self.env = Environment_PBM(thetas, kappas, label=\"purely simulated, test\")\n\n    def set_env_std(self):\n        \"\"\"Purely simulated environment with standard click's probabilities\"\"\"\n        kappas = [1, 0.75, 0.6, 0.3, 0.1]\n        thetas = [0.3, 0.2, 0.15, 0.15, 0.15, 0.10, 0.05, 0.05, 0.01, 0.01]\n        self.env_name = 'purely_simulated__std'\n        self.logs_env_name = self.env_name\n        self.env = Environment_PBM(thetas, kappas, label=\"purely simulated, std\")\n\n    def set_env_small(self):\n        \"\"\"Purely simulated environment with click's probabilities close to 0\"\"\"\n        kappas = [1, 0.75, 0.6, 0.3, 0.1]\n        thetas = [0.15, 0.1, 0.1, 0.05, 0.05, 0.01, 0.01, 0.01, 0.01, 0.01]\n        self.env_name = 'purely_simulated__small'\n        self.logs_env_name = self.env_name\n        self.env = Environment_PBM(thetas, kappas, label=\"purely simulated, small\")\n\n    def set_env_big(self):\n        \"\"\"Purely simulated environment with click's probabilities close to 1\"\"\"\n        kappas = [1, 0.75, 0.6, 0.3, 0.1]\n        thetas = [0.99, 0.95, 0.9, 0.85, 0.8, 0.75, 0.75, 0.75, 0.75, 0.75]\n        self.env_name = 'purely_simulated__big'\n        self.logs_env_name = self.env_name\n        self.env = Environment_PBM(thetas, kappas, label=\"purely simulated, big\")\n\n    def set_env_extra_small(self):\n        \"\"\"Purely simulated environment with click's probabilities close to 0\"\"\"\n        kappas = [1, 0.75, 0.6, 0.3, 0.1]\n        thetas = [0.10, 0.05, 0.01, 0.005, 0.001, 0.0001, 0.0001, 0.0001, 0.0001, 0.0001]\n        self.env_name = 'purely_simulated__xsmall'\n        self.logs_env_name = self.env_name\n        self.env = Environment_PBM(thetas, kappas, label=\"purely simulated, extra small\")\n\n    def set_env_xx_small(self):\n        \"\"\"Purely simulated environment with click's probabilities close to 0\"\"\"\n        kappas = [1, 0.75, 0.6, 0.3, 0.1]\n        thetas = [1e-3, 5e-4, 1e-4, 5e-5, 1e-5, 1e-6, 1e-6, 1e-6, 1e-6, 1e-6]\n        self.env_name = 'purely_simulated__xxsmall'\n        self.logs_env_name = self.env_name\n        self.env = Environment_PBM(thetas, kappas, label=\"purely simulated, xx small\")\n\n    def set_env_simul(self, label):\n        if label == \"std\":\n            self.set_env_std()\n        elif label == \"big\":\n            self.set_env_big()\n        elif label == \"small\":\n            self.set_env_small()\n        elif label == \"xsmall\":\n            self.set_env_extra_small()\n        elif label == \"xxsmall\":\n            self.set_env_xx_small()\n        else:\n            raise ValueError(\"unknown label of environment\")\n\n    def set_rules(self, nb_trials, nb_records=1000):\n        # Check inputs\n        if nb_records > nb_trials:\n            nb_records = -1\n\n        self.rules_name = f'games_{nb_trials}_nb_trials_{nb_records}_record_length'\n        self.referee = Referee(self.env, nb_trials, all_time_record=False, len_record_short=nb_records)\n\n    def set_player_eGreedy(self, c, update=100, noSVD=False):\n        nb_prop, nb_place = self.env.get_setting()\n        if noSVD:\n            self.player_name = f'Bandit_EGreedy_EM_{c}_c_{update}_update'\n            self.player = greedy.greedy_EGreedy_EM(c, nb_prop, nb_place, update)\n        else:\n            self.player_name = f'Bandit_EGreedy_SVD_{c}_c_{update}_update'\n            self.player = greedy.greedy_EGreedy(c, nb_prop, nb_place, update)\n\n    def set_player_PBM_TS(self, type=\"oracle\"):\n        nb_prop, nb_place = self.env.get_setting()\n        if type ==\"oracle\":\n            self.player_name = 'Bandit_PBM-TS_oracle'\n            self.player = PBM_TS_semi_oracle(nb_prop, nb_place, discount_factor=self.env.kappas, count_update=1)\n            self.positions_ranking = PositionsRanking.FIXED\n        elif type ==\"greedyMLE\":\n            self.player_name = 'Bandit_PBM_TS_greedy_MLE'\n            self.player = PBM_TS_Greedy_MLE(nb_prop, nb_place, count_update=1)\n        elif type ==\"greedySVD\":\n            self.player_name = 'Bandit_PBM_TS_greedy_SVD'\n            self.player = PBM_TS_Greedy_SVD(nb_prop, nb_place, count_update=1)\n        else:\n            self.player_name = 'Bandit_PBM-TS_greedy_SVD'\n            self.player = PBM_TS_Greedy_SVD(nb_prop, nb_place, count_update=1)\n\n    def set_player_PBM_PIE(self, epsilon, T, type =\"oracle\"):\n        nb_prop, nb_place = self.env.get_setting()\n        if type ==\"oracle\":\n            self.player_name = f'Bandit_PBM-PIE_oracle_{epsilon}_epsilon'\n            self.player = PBM_PIE_semi_oracle(nb_prop, epsilon, T, nb_place, discount_factor=self.env.kappas, count_update=1)\n            self.positions_ranking = PositionsRanking.FIXED\n        elif type ==\"greedyMLE\":\n            self.player_name = 'Bandit_PBM_PIE_greedy_MLE'\n            self.player = PBM_PIE_Greedy_MLE(nb_prop, epsilon, nb_place, count_update=1)\n        elif type ==\"greedySVD\":\n            self.player_name = 'Bandit_PBM_PIE_greedy_SVD'\n            self.player = PBM_PIE_Greedy_SVD(nb_prop, epsilon, nb_place, count_update=1)\n        else:\n            self.player_name = f'Bandit_PBM-PIE_greedy_SVD_{epsilon}_epsilon'\n            self.player = PBM_PIE_Greedy_SVD(nb_prop, epsilon, T, nb_place, count_update=1)\n\n    def set_player_PBM_UCB(self, epsilon, type =\"oracle\"):\n        nb_prop, nb_place = self.env.get_setting()\n        if type ==\"oracle\":\n            self.player_name = f'Bandit_PBM_UCB_oracle_{epsilon}_epsilon'\n            self.player = PBM_UCB_semi_oracle(nb_prop, epsilon, nb_place, discount_factor=self.env.kappas, count_update=1)\n            self.positions_ranking = PositionsRanking.FIXED\n        elif type ==\"greedyMLE\":\n            self.player_name = 'Bandit_PBM_UCB_greedy_MLE'\n            self.player = PBM_UCB_Greedy_MLE(nb_prop, epsilon, nb_place, count_update=1)\n        elif type ==\"greedySVD\":\n            self.player_name = 'Bandit_PBM_UCB_greedy_SVD'\n            self.player = PBM_UCB_Greedy_SVD(nb_prop, epsilon, nb_place, count_update=1)\n        else:\n            self.player_name = f'Bandit_PBM_UCB_greedy_SVD_{epsilon}_epsilon'\n            self.player = PBM_UCB_Greedy_SVD(nb_prop, epsilon, nb_place, count_update=1)\n\n\n    def set_player_BC_MPTS(self, type =\"oracle\"):\n        nb_prop, nb_place = self.env.get_setting()\n        if type ==\"oracle\":\n            self.player_name = 'Bandit_BC-MPTS_oracle'\n            self.player = BC_MPTS_semi_oracle(nb_prop, nb_place, self.env.kappas)\n            self.positions_ranking = PositionsRanking.FIXED\n        elif type ==\"greedyMLE\":\n            self.player_name = 'Bandit_BC-MPTS_greedy_MLE'\n            self.player = BC_MPTS_Greedy_MLE(nb_prop, nb_place, count_update=1)\n        elif type ==\"greedySVD\":\n            self.player_name = 'Bandit_BC-MPTS_greedy_SVD'\n            self.player = BC_MPTS_Greedy_SVD(nb_prop, nb_place, count_update=1)\n        else:\n            self.player_name = 'Bandit_BC-MPTS_greedy_SVD'\n            self.player = BC_MPTS_Greedy_SVD(nb_prop, nb_place, count_update=1)\n\n    def set_player_PMED(self, alpha, gap_MLE, gap_q, run=True):\n        nb_prop, nb_place = self.env.get_setting()\n\n        self.player_name = f'Bandit_PMED_{alpha}_alpha_{gap_MLE}_gap_MLE_{gap_q}_gap_q'\n\n        if run:\n            from bandits_to_rank.opponents.pmed import PMED\n            self.player = PMED(nb_prop, nb_place, alpha, gap_MLE, gap_q)\n\n    def set_player_CombUCB1(self, exploration_factor=2.):\n        nb_prop, nb_place = self.env.get_setting()\n\n        self.player_name = f'Bandit_CombUCB1_{exploration_factor}_exploration'\n        self.player = CombUCB1(nb_arms=nb_prop, nb_positions=nb_place, exploration_factor=exploration_factor)\n\n    def set_player_KL_COMB(self, horizon):\n        nb_prop, nb_place = self.env.get_setting()\n\n        self.player_name = f'Bandit_KL-COMB_{horizon}_horizon'\n        self.player = KL_CombUCB1(nb_arms=nb_prop, nb_positions=nb_place, horizon=horizon)\n\n    def set_player_PB_MHB(self, nb_steps, random_start=False):\n        nb_prop, nb_place = self.env.get_setting()\n        if random_start:\n            self.player_name = f'Bandit_PB-MHB_random_start_{nb_steps}_step_{self.proposal_name}_proposal'\n            self.player = PB_MHB(nb_prop, nb_place, proposal_method=self.proposal, step=nb_steps,\n                                 part_followed=False)\n        else:\n            self.player_name = f'Bandit_PB-MHB_warm-up_start_{nb_steps}_step_{self.proposal_name}_proposal'\n            self.player = PB_MHB(nb_prop, nb_place, proposal_method=self.proposal, step=nb_steps,\n                                 part_followed=True)\n\n    def set_player_TopRank(self, T, horizon_time_known=True, doubling_trick=False, oracle=False):\n        nb_prop, nb_place = self.env.get_setting()\n        if oracle:\n            self.player_name = f'Bandit_TopRank_oracle_{T}_delta_{\"TimeHorizonKnown\" if horizon_time_known else \"\"}_{\"doubling_trick\" if doubling_trick else \"\"}'\n            self.player = TOP_RANK(nb_arms=nb_prop,\n                                   T=T, horizon_time_known=horizon_time_known,doubling_trick_active=doubling_trick,\n                                   discount_factor=self.env.kappas)\n            self.positions_ranking = PositionsRanking.FIXED\n        else:\n            self.player_name = f'Bandit_TopRank_{T}_delta_{\"TimeHorizonKnown\" if horizon_time_known else \"\"}_{\"doubling_trick\" if doubling_trick else \"\"}'\n            self.player = TOP_RANK(nb_arms=nb_prop,\n                                   T=T, horizon_time_known=horizon_time_known, doubling_trick_active=doubling_trick,\n                                   discount_factor=np.arange(nb_place - 1, -1, -1))\n        \"\"\"\n            self.player_name = f'Bandit_TopRank_greedy_{T}_delta_{\"TimeHorizonKnown\" if horizon_time_known else \"\"}_{\"doubling_trick\" if doubling_trick else \"\"}'\n            self.player = TOP_RANK(nb_arms=nb_prop,\n                                   T=T, horizon_time_known=horizon_time_known,doubling_trick_active=doubling_trick,\n                                   nb_positions=nb_place, lag=1)\n        \"\"\"\n\n\n    def set_player_SGRAB(self, T, gamma, forced_initiation):\n        nb_prop, nb_place = self.env.get_setting()\n        if gamma == 0:\n            gamma_use = nb_prop * nb_place\n        else:\n            gamma_use = gamma\n        self.player_name = f'Bandit_SGRAB_{T}_T_{gamma_use}_gamma{\"_forced\" if forced_initiation else \"\"}'\n        self.player = sGRAB(nb_arms=nb_prop, nb_positions=nb_place, T=T)\n\n    def set_player_GRAB(self, T, gamma, forced_initiation):\n        nb_prop, nb_place = self.env.get_setting()\n        if gamma == 0:\n            gamma_use = nb_prop - nb_place\n        else:\n            gamma_use = gamma\n        self.player_name = f'Bandit_GRAB_{T}_T_{gamma_use}_gamma{\"_forced\" if forced_initiation else \"\"}'\n        self.player = GRAB(nb_arms=nb_prop, nb_positions=nb_place, T=T, gamma=gamma_use,\n                                forced_initiation=forced_initiation)\n\n    def set_proposal_TGRW(self, c, vari_sigma=True):\n        self.proposal_name = f'TGRW_{c}_c{\"_vari_sigma\" if vari_sigma else \"\"}'\n        self.proposal = propos_trunk_GRW(c, vari_sigma)\n\n    def set_proposal_LGRW(self, c, vari_sigma=True):\n        self.proposal_name = f'LGRW_{c}_c{\"_vari_sigma\" if vari_sigma else \"\"}'\n        self.proposal = propos_logit_RW(c, vari_sigma)\n\n    def set_proposal_RR(self, c, str_proposal_possible, vari_sigma=True):\n        list_proposal_possible = list(str_proposal_possible.split(\"-\"))\n        self.proposal_name = f'RR_{c}_c_{len(list_proposal_possible)}_proposals'\n        self.proposal = propos_Round_Robin(c, vari_sigma, list_proposal_possible)\n\n    def set_proposal_MaxPos(self):\n        self.proposal_name = f'MaxPos'\n        self.proposal = propos_max_position()\n\n    def set_proposal_PseudoView(self):\n        self.proposal_name = f'PseudoView'\n        self.proposal = propos_pseudo_view()\n\n    def set_exp(self, first_game=-1, nb_games=-1, nb_checkpoints=10, input_path=None, output_path=None, force=True):\n        self.first_game = first_game\n        self.end_game = first_game + nb_games\n        self.nb_checkpoints = nb_checkpoints\n        self.input_path = input_path if input_path is not None else output_path\n        self.output_path = output_path if output_path is not None else input_path\n        self.force = force\n\n\n", "meta": {"hexsha": "a65aacc81d1a0149eea8c9bff42f8b8d173110bb", "size": 19579, "ext": "py", "lang": "Python", "max_stars_repo_path": "param.py", "max_stars_repo_name": "gaudel/ranking_bandits", "max_stars_repo_head_hexsha": "1fe4a38b17a3bb7ccab3ae0f4d0afb70fe54dbc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-22T14:46:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T08:55:01.000Z", "max_issues_repo_path": "param.py", "max_issues_repo_name": "gaudel/ranking_bandits", "max_issues_repo_head_hexsha": "1fe4a38b17a3bb7ccab3ae0f4d0afb70fe54dbc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "param.py", "max_forks_repo_name": "gaudel/ranking_bandits", "max_forks_repo_head_hexsha": "1fe4a38b17a3bb7ccab3ae0f4d0afb70fe54dbc9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.7279236277, "max_line_length": 161, "alphanum_fraction": 0.6581030696, "include": true, "reason": "import numpy", "num_tokens": 5294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3593641588823761, "lm_q1q2_score": 0.19508560714541248}}
{"text": "\"\"\"\nCode for top level interface.\n\nThis code is added to the main package level in __init__.py\n\"\"\"\nimport numpy as np\nimport abcgan.constants as const\nimport abcgan.transforms as trans\nfrom abcgan import persist\nfrom abcgan.mask import mask_altitude\nfrom abcgan.transforms import compute_valid, compute_valid_hfp\nimport torch\nimport h5py\nfrom tqdm import tqdm\nfrom warnings import warn\n\n\ndef generate(drivers, measurements=None,\n             driver_names=const.driver_names, n_alt=const.max_alt,\n             bv_model='bv_gan', hfp_model='hfp_gan', bv_type='radar',\n             generate_hfps=False, return_z_scale=False, cuda_index=None,\n             verbose=1):\n    \"\"\"\n    Generate background variable profiles and HFP waves\n    consistent with the historical distribution.\n\n    Parameters\n    -------------\n    drivers: np.ndarray\n        n_samples x n_drivers input list of driving parameters (not z-scaled).\n    driver_names: list\n        list of names of driving parameters\n    measurements: np.ndarray, optional\n        n_samples x n_alt_in x n_meas input list of altitude measurements,\n        n_alt_in should be less than n_alt. These represent fixed\n        measurements for the lowest altitudes to condition on.\n        Usually left as default (None)\n    n_alt: int, optional\n        number of altitude measurements to draw, defaults to max_alt\n    return_z_scale: bool, optional\n        set to have the function return z scaled feature data\n    bv_model: str, optional\n        name of bv GAN to use\n    bv_type: str. optional\n        name of the type of background variables to use (lidar or radar)\n    hfp_model: str, optional\n        name of hfp GAN to use\n    generate_hfps: bool, optional\n        Set to generate hfps and return generated hfps\n    cuda_index: int, optional\n        GPU index to use when generating BVs and HFPs\n    verbose: bool, optional\n        set to show loading bar\n    Returns\n    -------------\n    samples: (np.ndarray, np.ndarray, np.ndarray)\n        1) n_samples x n_alt x n_bvs output measurements at each requested altitude.\n        2) n_samples x n_hfps generated hfp waves\n        3) n_sample probabilities that the generated wave is present\n    \"\"\"\n\n    with torch.no_grad():\n        disable1 = bool(verbose < 1)\n        if n_alt > const.max_alt and bv_type == 'radar':\n            raise ValueError(f\"Requested {n_alt} altitudes but only {const.max_alt}\"\n                             f\" can be simulated for {bv_type}.\")\n        elif n_alt > const.max_alt_lidar and bv_type == 'lidar':\n            raise ValueError(f\"Requested {n_alt} altitudes but only {const.max_alt_lidar}\"\n                             f\" can be simulated for {bv_type}.\")\n        if bv_type == 'lidar':\n            n_bv = const.n_lidar_bv\n        else:\n            n_bv = const.n_bv\n\n        if measurements is None:\n            # put placeholder measurements if none provided\n            measurements = np.zeros((drivers.shape[0], 0, n_bv))\n\n        n_batch = drivers.shape[0]\n        n_alt_start = measurements.shape[1]\n\n        # verify the correct shapes for the inputs\n        if drivers.shape != (n_batch, len(driver_names)):\n            raise ValueError(f\"driver and driver_names must have the \"\n                             f\"same length ({drivers.shape[-1]} != {len(driver_names)}\")\n        if measurements.shape != (n_batch, n_alt_start, n_bv):\n            raise ValueError(f\"Measurement shape must be n_batch x \"\n                             f\"{n_alt_start} x {n_bv}.\")\n\n        # z scale inputs and place into tensors\n        driver_feat = trans.scale_driver(drivers, driver_names=driver_names)\n        bv_feat, valid_mask = trans.scale_bv(measurements, bv_type)\n        driver_feat = torch.tensor(driver_feat, dtype=torch.float)\n        bv_feat = torch.tensor(bv_feat, dtype=torch.float)\n        bv_feat, alt_mask = mask_altitude(bv_feat)\n        hfp_feats = torch.zeros(len(drivers), const.n_waves, const.n_hfp_feat)\n        G_b = torch.zeros(len(drivers))\n\n        if torch.cuda.is_available() and cuda_index is not None:\n            device = torch.device('cuda:' + str(cuda_index))\n            if len(drivers) >= 500:\n                batch_size = 500\n            else:\n                batch_size = len(drivers)\n        else:\n            device = torch.device('cpu')\n            if len(drivers) >= 100:\n                batch_size = 100\n            else:\n                batch_size = len(drivers)\n\n        batch_idxs = np.hstack((np.arange(0, len(drivers), step=batch_size), [len(drivers)]))\n\n        # Load bv models\n        bv_gen, _ = persist.recreate(name=bv_model)\n        if bv_gen.transformer.dr_emb.shape[0] != driver_feat.shape[-1]:\n            raise ValueError(f\"Model must be trained with \"\n                             f\"{driver_feat.shape[-1]} drivers.\")\n        bv_gen.to(device)\n        bv_gen.eval()\n\n        # iteratively build altitude profile\n        for i in tqdm(range(len(batch_idxs) - 1), desc='Generate BV Profile', disable=disable1):\n            for i_alt in range(n_alt_start, n_alt):\n                dr_src = driver_feat[batch_idxs[i]:batch_idxs[i + 1]].to(device)\n                bv_src = bv_feat[batch_idxs[i]:batch_idxs[i + 1]].to(device)\n\n                bv_out = bv_gen(dr_src, bv_src)\n                # fill in next altitude\n                bv_feat[batch_idxs[i]:batch_idxs[i + 1], i_alt, :] = bv_out[:, i_alt, :].detach().cpu()\n        G_bv_feats = bv_feat[:, :n_alt, :]\n        G_bvs = trans.get_bv(bv_feat[:, :n_alt, :].numpy(), bv_type)\n        if measurements is not None:\n            G_bvs[:, :n_alt_start, :] = measurements\n        bv_gen.cpu()\n\n        if generate_hfps:\n            # Load hfp GAN\n            hfp_gen, _ = persist.recreate(name=hfp_model)\n            hfp_gen.to(device)\n            hfp_gen.eval()\n\n            # Generate waves\n            for i in tqdm(range(len(batch_idxs) - 1), desc='Generate HFP Batches', disable=disable1):\n                dr_src = driver_feat[batch_idxs[i]:batch_idxs[i + 1]].to(device)\n                gbv_src = G_bv_feats[batch_idxs[i]:batch_idxs[i + 1]].to(device)\n                hfp_tgt = hfp_feats[batch_idxs[i]:batch_idxs[i + 1]].to(device)\n\n                hfp_out, gb = hfp_gen(dr_src, gbv_src, hfp_tgt)\n                hfp_feats[batch_idxs[i]:batch_idxs[i + 1], ...] = hfp_out.detach().cpu()\n                G_b[batch_idxs[i]:batch_idxs[i + 1]] = gb.detach().cpu()\n            G_hfps_feats = hfp_feats.numpy()\n            G_hfps = trans.get_hfp(hfp_feats.numpy())\n            G_b = G_b.numpy()\n\n        if generate_hfps:\n            if return_z_scale:\n                return G_bv_feats.numpy(), G_hfps_feats, G_b\n            else:\n                return G_bvs, G_hfps, G_b\n        else:\n            if return_z_scale:\n                return G_bv_feats.numpy()\n            else:\n                return G_bvs\n\n\ndef generate_multi(drivers, bvs=None, n_repeat=10,\n                   bv_model='bv_gan', hfp_model='hfp_gan',\n                   bv_type='radar', generate_hfps=False,\n                   cuda_index=None, verbose=1):\n    \"\"\"\n    Generate multiple background variable profiles and HFP waves\n    consistent with the historical distribution for each driver sample\n\n    Parameters\n    -------------\n    drivers: np.ndarray\n        n_samples x n_drivers input list of driving parameters (not z-scaled).\n    bvs: np.ndarray, optional\n        n_samples x n_alt_in x n_meas input list of altitude measurements,\n        n_alt_in should be less than n_alt. These represent fixed\n        measurements for the lowest altitudes to condition on.\n        Usually left as default (None)\n    n_repeat: int, optional\n        number of bv profiles/waves to generate for each driver sample\n    bv_model: str, optional\n        name of bv GAN to use\n    bv_type: str. optional\n        name of the type of background variables to use (lidar or radar)\n    hfp_model: str, optional\n        name of hfp GAN to use\n    generate_hfps: bool, optional\n        Set to generate hfps and return generated hfps\n    cuda_index: int, optional\n        GPU index to use when generating BVs and HFPs\n    verbose: bool, optional\n        set to show loading bar\n    Returns\n    -------------\n    samples: (np.ndarray, np.ndarray, np.ndarray)\n        1) (n_samples x n_repeat x n_alt x n_bvs) output measurements at each requested altitude.\n        2) (n_samples x n_repeat x 1 x n_hfps) generated hfp waves\n        3) (n_sample x n_repeat) probabilities that the generated wave is present\n    \"\"\"\n    disable = bool(verbose < 1)\n    G_bvs = np.zeros((len(drivers), n_repeat, const.max_alt, const.n_bv))\n    G_hfps = np.zeros((len(drivers), n_repeat, const.n_waves, const.n_hfp))\n    G_b = np.zeros((len(drivers), n_repeat))\n\n    for i in tqdm(range(len(drivers)), desc='Generating Samples', disable=disable):\n        sampled_driver = drivers[[i], ...].repeat(n_repeat, 0)\n        if bvs is not None:\n            sampled_bv = bvs[[i], ...].repeat(n_repeat, 0)\n        else:\n            sampled_bv = None\n        if generate_hfps:\n            gen_data = generate(sampled_driver,\n                                measurements=sampled_bv,\n                                bv_model=bv_model,\n                                hfp_model=hfp_model,\n                                bv_type=bv_type,\n                                generate_hfps=True,\n                                cuda_index=cuda_index,\n                                verbose=False)\n            G_bvs[i, ...] = gen_data[0]\n            G_hfps[i, ...] = gen_data[1]\n            G_b[i, ...] = gen_data[2]\n        else:\n            G_bvs[i, ...] = generate(sampled_driver,\n                                     measurements=sampled_bv,\n                                     bv_model=bv_model,\n                                     hfp_model=hfp_model,\n                                     bv_type=bv_type,\n                                     generate_hfps=False,\n                                     cuda_index=cuda_index,\n                                     verbose=False)\n    if generate_hfps:\n        return G_bvs, G_hfps, G_b\n    else:\n        return G_bvs\n\n\ndef discriminate(drivers, bvs, hfps=None,\n                 driver_names=const.driver_names,\n                 bv_model='bv_gan', hfp_model='hfp_gan',\n                 bv_type='radar'):\n    \"\"\"\n    Score how well the measurements match with historical observations.\n\n    Parameters\n    -------------\n    drivers: np.ndarray\n        n_samples x n_drivers input list of driving parameters (not z-scaled).\n    driver_names: list\n        list of names of driving parameters\n    bvs: np.ndarray\n        n_samples x n_alt_in x n_meas input list of altitude measurements,\n        n_alt_in should be less than max_alt.\n    hfps: np.ndarray, optional\n        n_samples x n_wave x n_hfps input list of wave measurements,\n    bv_model: str, optional\n        name of bv model to use\n    hfp_model: str, optional\n        name of model hfp to use\n    bv_type: str. optional\n        name of the type of background variables to use (lidar or radar)\n    Returns\n    -------------\n    scores: (np.ndarray, np.ndarray)\n        1) n_samples x n_alt bv normalcy scores in the range [0, 1.0].\n        2) n_samples hfp wave normalcy scores in the range [0, 1.0].\n    \"\"\"\n    warn(f'The discriminate function is deprecated. Does not produce credible results '\n         f'outside of the training process. Please use the anomaly modules in place of'\n         f'the discriminator', DeprecationWarning, stacklevel=2)\n    with torch.no_grad():\n        n_batch, n_alt = bvs.shape[:2]\n        _, bv_crit = persist.recreate(name=bv_model)\n        bv_crit.eval()\n\n        driver_feat = trans.scale_driver(drivers, driver_names)\n        bv_feat, _ = trans.scale_bv(bvs, bv_type)\n\n        if bv_crit.transformer.dr_emb.shape[0] != driver_feat.shape[-1]:\n            raise ValueError(f\"Model must be trained with \"\n                             f\"{driver_feat.shape[-1]} drivers.\")\n\n        driver_feat = torch.tensor(driver_feat, dtype=torch.float)\n        bv_feat = torch.tensor(bv_feat, dtype=torch.float)\n        bv_feat, alt_mask = mask_altitude(bv_feat)\n\n        # Get bvs scores\n        bv_scores = bv_crit(bv_feat, driver_feat, bv_feat, ~alt_mask)\n        bv_scores = bv_scores.view(n_batch, -1)[:, :n_alt].cpu().numpy()\n\n        if hfps is not None:\n            if hfps.shape[-1] != const.n_hfp:\n                raise ValueError(f\"HFPs data must have \"\n                                 f\"{const.n_hfp} features.\")\n\n            _, hfp_crit = persist.recreate(name=hfp_model)\n            hfp_crit.eval()\n            hfp_feat, _ = trans.scale_hfp(hfps)\n            hfp_feat = torch.tensor(hfp_feat, dtype=torch.float)\n\n            # Get hfp scores\n            hfp_scores = hfp_crit(driver_feat, bv_feat, hfp_feat, hfp_feat, ~alt_mask)\n            hfp_scores = hfp_scores.view(n_batch, -1).cpu().numpy()\n\n        if hfps is None:\n            return bv_scores\n        else:\n            return bv_scores, hfp_scores\n\n\ndef estimate_drivers(drivers, model='dr_gan'):\n    \"\"\"\n    Predict drivers 2 hours into the future driver GAN model. Used for real-time\n    background predictions using drivers from 2 hours ago.\n\n    Parameters\n    -------------\n    drivers: np.ndarray\n        n_samples x n_drivers input list of driving parameters (not z-scaled).\n    model: str, optional\n        name of model to use\n\n    Returns\n    -------------\n    predicted_drivers: np.ndarray\n        estimation of driver features two hours from the drivers inputted\n    \"\"\"\n    driver_feats = torch.tensor(trans.scale_driver(drivers), dtype=torch.float)\n    dr_gen, _ = persist.recreate(name=model)\n    dr_gen.eval()\n\n    with torch.no_grad():\n        predicted_feats = dr_gen(driver_feats)\n\n    predicted_drivers = trans.get_driver(predicted_feats.cpu().numpy())\n    return predicted_drivers\n\n\ndef hellinger_scores_bv(real, fake, mask=None, bins=None, filter_length=None,\n                        return_hist_info=False, z_scale=True, bv_type='radar'):\n    \"\"\"\n    Returns the hellinger distance score that measures how similarity between\n    real and generated background variable profiles.\n    ----------------\n    real: np.ndarray\n        tensor of real values for a particular alt and bv feat\n    fake: np.ndarray\n        tensor of generated values for a particular alt and bv feat\n    bins: int\n        number of bins to use in histogram calculations\n        (If None # of bins will be calculated based on number of samples)\n    filter_length: int\n        averaging filter length to smooth out noise in histograms\n        (If None filter length will be calculated based on number of samples)\n    return_hist_info: bool\n        set to have function return the histograms and bin edges used which\n        were used to calculate the hellinger distance metric.\n    bv_type:\n        type of data (radar or lidar)\n    Returns\n    -------------\n    dist:\n        the hellinger distance (n_alts x n_feats)\n    \"\"\"\n    if mask is None:\n        mask = np.ones((real.shape[0], real.shape[1]), dtype=bool)\n\n    if bins is None:\n        bins = max(15, int((real.shape[0])**const.bin_exp))\n    if filter_length is None:\n        filter_length = max(2, int(len(real)**const.filter_exp))\n\n    dists = np.zeros((real.shape[1], real.shape[2]))\n    r_hists = np.zeros((bins, real.shape[1], real.shape[2]))\n    f_hists = np.zeros((bins, real.shape[1], real.shape[2]))\n    edges = np.zeros((bins + 1, real.shape[1], real.shape[2]))\n\n    for i in range(real.shape[1]):\n        for j in range(real.shape[2]):\n            if z_scale:\n                r = trans.scale_bv(real, bv_type)[0][mask[:, i], i, j]\n                f = trans.scale_bv(fake, bv_type)[0][mask[:, i], i, j]\n                args = {'bins': bins, 'range': (-3, 3), 'density': True}\n            else:\n                r = real[mask[:, i], i, j]\n                f = fake[mask[:, i], i, j]\n                args = {'bins': bins, 'range': (const.bv_thresholds[j, 0], const.bv_thresholds[j, 1]),\n                        'density': True}\n            r_hist, edg = np.histogram(r, **args)\n            f_hist, edg = np.histogram(f, **args)\n            if filter_length:\n                r_hist = np.convolve(r_hist, np.ones(filter_length), mode='same') / filter_length\n                f_hist = np.convolve(f_hist, np.ones(filter_length), mode='same') / filter_length\n            r_area = r_hist * np.diff(edg)\n            f_area = f_hist * np.diff(edg)\n            dists[i, j] = (1 / np.sqrt(2)) * np.sqrt(np.sum((np.sqrt(r_area) - np.sqrt(f_area)) ** 2))\n            r_hists[:, i, j] = r_hist\n            f_hists[:, i, j] = f_hist\n            edges[:, i, j] = edg\n\n    if return_hist_info:\n        return dists, (r_hists, f_hists, edges)\n    else:\n        return dists\n\n\ndef hellinger_scores_hfp(real, fake, r_mask=None, f_mask=None,\n                         bins=None, filter_length=None, z_scale=True,\n                         return_hist_info=False):\n    \"\"\"\n    Returns the hellinger distance score that measures the similarity between\n    real and generated background variable profiles.\n    ----------------\n    real:\n        tensor of real values for a particular alt and bv feat\n    fake:\n        tensor of generated values for a particular alt and bv feat\n    bins:\n        tensor of real values for a particular alt and bv feat\n    filter_length:\n        averaging filter length to smooth out histograms\n    z_scale: bool\n        used z-scaled values (recommended)\n    return_hist_info: bool\n        set to have function return the real hist,\n        fake hist, and bin edges used in calculation\n    Returns\n    -------------\n    dist:\n        the hellinger distance (n_alts or n_waves x n_feats)\n    \"\"\"\n    if r_mask is None:\n        r_mask = np.ones((real.shape[0], real.shape[1]), dtype=bool)\n    if f_mask is None:\n        f_mask = np.ones((fake.shape[0], fake.shape[1]), dtype=bool)\n\n    if bins is None:\n        bins = max(15, int(r_mask.sum() ** const.bin_exp))\n    if filter_length is None:\n        filter_length = max(2, int(r_mask.sum() ** const.filter_exp))\n\n    dists = np.zeros((real.shape[1], real.shape[2]))\n    r_hists = np.zeros((bins, real.shape[1], real.shape[2]))\n    f_hists = np.zeros((bins, real.shape[1], real.shape[2]))\n    edges = np.zeros((bins + 1, real.shape[1], real.shape[2]))\n\n    for i in range(real.shape[1]):\n        for j in range(real.shape[2]):\n            if z_scale:\n                r = trans.scale_hfp(real)[0][r_mask[:, i], i, j]\n                f = trans.scale_hfp(fake)[0][f_mask[:, i], i, j]\n                args = {'bins': bins, 'range': const.hfp_z_ranges[j], 'density': True}\n            else:\n                r = real[r_mask[:, i], i, j]\n                f = fake[f_mask[:, i], i, j]\n                args = {'bins': bins,\n                        # 'range': (min(np.min(r), np.min(f)), max(np.max(r), np.max(f))),\n                        'range': (const.hfp_thresholds[j, 0], const.hfp_thresholds[j, 1]),\n                        'density': True}\n            r_hist, edg = np.histogram(r, **args)\n            f_hist, edg = np.histogram(f, **args)\n            if filter_length:\n                r_hist = np.convolve(r_hist, np.ones(filter_length), mode='same') / filter_length\n                f_hist = np.convolve(f_hist, np.ones(filter_length), mode='same') / filter_length\n            r_area = r_hist * np.diff(edg)\n            f_area = f_hist * np.diff(edg)\n            dists[i, j] = (1 / np.sqrt(2)) * np.sqrt(np.sum((np.sqrt(r_area) -\n                                                             np.sqrt(f_area)) ** 2))\n            r_hists[:, i, j] = r_hist\n            f_hists[:, i, j] = f_hist\n            edges[:, i, j] = edg\n\n    if return_hist_info:\n        return dists, (r_hists, f_hists, edges)\n    else:\n        return dists\n\n\ndef stack_drivers(driver_dict, driver_names=const.driver_names):\n    \"\"\"\n    Stacks drivers in appropriate format.\n\n    This function is provided for convenience.\n\n\n    Parameters\n    ----------------\n    driver_dict: dict\n        Dictionary mapping names of drivers to the numpy arrays\n        with values for those drivers. Each array has a single\n        dimension of the same length n_samples.\n        Can also use an `h5py.Group`.\n    driver_names: list\n        names of the drivers to load\n\n    Valid names for drivers can be found at `abcgan.driver_names`\n\n    Raises\n    ------------------\n    ValueError:\n        If the driver values have the wrong type or shape.\n    KeyError:\n        If one of the required drivers is missing.\n    \"\"\"\n    if isinstance(driver_dict, h5py.Group):\n        driver_dict = {k: v[()] for k, v in driver_dict.items()}\n    shp = None\n    for v in driver_dict.values():\n        if not isinstance(v, np.ndarray):\n            raise ValueError(f\"Values in driver_dict must have\"\n                             f\" type np.ndarray not {type(v)}.\")\n        if shp is None:\n            shp = v.shape\n            if len(shp) != 1:\n                raise ValueError(\"Driver dict values must have only one\"\n                                 \" dimension for the number of samples.\")\n        if shp != v.shape:\n            raise ValueError(\"All values in driver_dict must have\"\n                             \" the same length.\")\n    return np.stack([driver_dict[k] for k in driver_names],\n                    axis=-1)\n\n\ndef stack_bvs(bv_dict, bv_type='radar'):\n    \"\"\"\n    Stacks drivers in appropriate format.\n\n    This function is provided for convenience.\n\n    Parameters\n    ----------------\n    bv_dict: dict\n        Dictionary mapping names of background variables\n        to numpy arrays with values for those bvs. Each\n        array should have shape n_sapmles x n_altitudes.\n        Can also use `h5py.Group`.\n    bv_type: str\n        string specifying weather to stack radar or\n        lidar data\n\n    Valid names for drivers can be found at `abcgan.bv_names`\n\n    Raises\n    ------------------\n    ValueError:\n        If the input shape of the bv dict values is not corrects\n    KeyError:\n        If one of the required bvs is missing.\n    \"\"\"\n    if isinstance(bv_dict, h5py.Group):\n        bv_dict = {k: v[()] for k, v in bv_dict.items()}\n    shp = None\n    for v in bv_dict.values():\n        if not isinstance(v, np.ndarray):\n            raise ValueError(f\"Values in bv_dict must have\"\n                             f\" type np.ndarray not {type(v)}.\")\n        if shp is None:\n            shp = v.shape\n            if len(shp) != 2:\n                raise ValueError(\"BV dict values must have 2 \"\n                                 \"dimensions [n_samples x n_altitudes].\")\n        if shp != v.shape:\n            raise ValueError(\"All values in bv_dict must have the\"\n                             \" same shape.\")\n    if bv_type == 'lidar':\n        bvs = np.stack([bv_dict[k] for k in const.lidar_bv_names],\n                       axis=-1)[:, :const.max_alt_lidar, :]\n    else:\n        bvs = np.stack([bv_dict[k] for k in const.bv_names],\n                       axis=-1)[:, 26:26 + const.max_alt, :]\n    return bvs\n\n\ndef load_h5_data(fname, bv_type='radar', load_hfp=False, n_samples=None):\n    \"\"\"\n    loads and returns external drivers, background variables, HFP waves and data\n    mask all aligned in time with outlier/invalid data filtered out\n\n    Parameters\n    -------------\n    fname: str\n        name of h5 file to load the data from\n    bv_type: str. optional\n        name of the type of background variables to use (lidar or radar)\n    load_hfp: bool. optional\n        set to load HFP waves along with the background variables\n    n_samples: int. optional\n        number of samples to load (None to load all samples)\n    Returns\n    -------------\n    drivers: np.ndarray\n        (n_samples x n_dr) external drivers.\n    bvs: np.ndarray\n        (n_samples x n_alt x n_bv) background variables.\n    alt_mask: np.ndarray\n        (n_samples x n_alt) background variables alt mask.\n    hfps: np.ndarray\n        (n_samples x 1 x n_hpf) HPF waves.\n    wave_mask: np.ndarray\n        (n_samples x 1) HFP wave mask.\n    unix_time: np.ndarray\n        (n_samples, ) time stamp of each sample\n    \"\"\"\n    with h5py.File(fname, 'r') as f:\n        # --------------------------------------\n        # Read driver and time stamps from file\n        # --------------------------------------\n        dr_dict = f['Drivers']\n        unix_time = f['UnixTime'][()]\n        drivers = np.stack([dr_dict[driver_name][:]\n                            for driver_name in const.driver_names\n                            if driver_name in dr_dict.keys()],\n                           axis=-1)\n        # --------------------------------------\n        # Read background variable data from file\n        # --------------------------------------\n        bv_dict = f['BackgroundValues']\n        if bv_type == 'lidar':\n            bvs = np.stack([bv_dict[bv_name][:]\n                            for bv_name in const.lidar_bv_names],\n                           axis=-1)[:, :const.max_alt_lidar, :]\n            bv_thresholds = const.lidar_thresholds\n        else:\n            bvs = np.stack([bv_dict[bv_name][:]\n                            for bv_name in const.bv_names],\n                           axis=-1)[:, 26:26 + const.max_alt]\n            bv_thresholds = const.bv_thresholds\n\n        if load_hfp:\n            # --------------------------------------\n            # Read HFP data from file\n            # --------------------------------------\n            hfp_dict = f['HFPValues']\n            hfps = np.stack([hfp_dict[hfp_name]\n                             for hfp_name in const.hfp_names\n                             if hfp_name in hfp_dict.keys()],\n                            axis=-1)\n            hfps = hfps[:, None, :]\n\n    # Get valid bvs and altitude mask\n    valid_bv_mask = compute_valid(bvs, bv_thresholds)\n\n    if load_hfp:\n        valid_hfp_mask = compute_valid_hfp(hfps)\n        valid_mask = valid_bv_mask & valid_hfp_mask & ~(np.isnan(drivers).any(-1))\n    else:\n        valid_mask = valid_bv_mask & ~(np.isnan(drivers).any(-1))\n\n    # Filter out any invalid samples\n    if n_samples is not None:\n        drivers = drivers[valid_mask][:n_samples]\n        bvs = bvs[valid_mask][:n_samples]\n        unix_time = unix_time[valid_mask][:n_samples]\n    else:\n        drivers = drivers[valid_mask]\n        bvs = bvs[valid_mask]\n        unix_time = unix_time[valid_mask]\n\n    # Get altitude mask for bvs\n    _, alt_mask = mask_altitude(torch.tensor(bvs, dtype=torch.float))\n    alt_mask = alt_mask.detach().numpy()\n\n    if load_hfp:\n        # Filter out invalid samples and get wave mask\n        if n_samples is not None:\n            hfps = hfps[valid_mask][:n_samples]\n        else:\n            hfps = hfps[valid_mask]\n        wave_mask = ~(np.isnan(hfps).any(-1))\n\n        return drivers, bvs, alt_mask, hfps, wave_mask, unix_time\n\n    else:\n        return drivers, bvs, alt_mask, unix_time\n", "meta": {"hexsha": "7342c1582227d3749ed4efd438c1a03a0e89f477", "size": 26876, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/abcgan/interface.py", "max_stars_repo_name": "sam-austin-sri/atmosense-abcgan", "max_stars_repo_head_hexsha": "b046676f70da69313126aaa323145af2a0e7b404", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/abcgan/interface.py", "max_issues_repo_name": "sam-austin-sri/atmosense-abcgan", "max_issues_repo_head_hexsha": "b046676f70da69313126aaa323145af2a0e7b404", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/abcgan/interface.py", "max_forks_repo_name": "sam-austin-sri/atmosense-abcgan", "max_forks_repo_head_hexsha": "b046676f70da69313126aaa323145af2a0e7b404", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-04T21:20:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T21:20:18.000Z", "avg_line_length": 39.4654919236, "max_line_length": 103, "alphanum_fraction": 0.5786947462, "include": true, "reason": "import numpy", "num_tokens": 6379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.19508560342075307}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 18 14:05:10 2018\n\n@author: yoelr\n\"\"\"\nfrom . import _Q\nimport numpy as np\nfrom .utils import property_array, PropertyFactory, DisplayUnits, \\\n                    tuple_array, fraction, Sink, Source, MissingStream\nfrom ._flowsheet import find\nfrom ._species import Species, WorkingSpecies\nfrom ._exceptions import SolverError, EquilibriumError, DimensionError\nfrom ._equilibrium import Dortmund, VLE, BubblePoint, DewPoint\n\n\n__all__ = ('Stream',)\n\n# %% TODOs\n\n# TODO: add material property interphase when using Cape Open package\n\n# %% Functions\n\ndef nonzero_species(species, flow):\n    index_ = []\n    IDs_ = []\n    IDs = species._IDs\n    for i in species._index:\n        if flow[i] != 0:\n            index_.append(i)\n            IDs_.append(IDs[i])\n    return index_, IDs_\n\ndef _print_helpdata(helpdata):\n    \"\"\"Print help data.\"\"\"\n    # Only one helplist, print a nice string\n    if isinstance(helpdata[0], str):\n        propID, description, dependency, units, datatype = helpdata\n        if dependency == 'TP':\n            dependency = 'as a function of T and P '\n        elif dependency == 'T':\n            dependency = 'as a function of T '\n        elif dependency == 'P':\n            dependency = 'as a function of P '\n        print(f\"{propID}: [{datatype}] {description.capitalize()} \"\n              \"{dependency}({units}).\")\n\n    # Many helpdata, print all the nice strings\n    else:\n        for i in helpdata:\n            _print_helpdata(i)\n\n\n# %% Units of measure\n\n# Biosteam units of measure\nunits_of_measure = dict(cost='USD/hr',\n                        MW='g/mol',\n                        mass='kg/hr',\n                        mol='kmol/hr',\n                        vol='m^3/hr',\n                        massnet='kg/hr',\n                        molnet='kmol/hr',\n                        volnet='m^3/hr',\n                        massfrac='kg/kg',\n                        molfrac='kmol/kmol',\n                        volfrac='m^3/m^3',\n                        T='K',\n                        P='Pa',\n                        H='kJ/hr',\n                        S='kJ/hr',\n                        G='kJ/hr',\n                        U='kJ/hr',\n                        A='kJ/hr',\n                        Hf='kJ/hr',\n                        C='kJ/K/hr',\n                        Vm='m^3/mol',\n                        Cpm='J/mol/K',\n                        Cp='J/g/K',\n                        rho='kg/m^3',\n                        rhom='mol/m^3',\n                        nu='m^2/s',\n                        mu='Pa*s',\n                        sigma='N/m',\n                        k='W/m/K',\n                        alpha='m^2/s')\n\nmol_flow_dim = _Q(0, units_of_measure['mol']).dimensionality\nmass_flow_dim = _Q(0, units_of_measure['mass']).dimensionality\nvol_flow_dim = _Q(0, units_of_measure['vol']).dimensionality\n\n# %% Flow properties\n\n@PropertyFactory\ndef MassFlow(self):\n    \"\"\"Mass flow (kg/hr).\"\"\"\n    return self.data[0][0] * self.data[1] # mol[0] * MW\n\n@MassFlow.setter\ndef MassFlow(self, value):\n    self.data[0][0] = value/self.data[1] # mol[0] = value/MW\n\n@PropertyFactory    \ndef VolumetricFlow(self):\n    \"\"\"Volumetric flow (m^3/hr).\"\"\"\n    stream, mol = self.data\n    m = mol[0]\n    if m:\n        c = self.name # c = compound\n        c.T = stream.T\n        c.P = stream.P\n        c.phase = stream._phase\n        return c.Vm * m * 1000\n    else:\n        return 0.\n\n@VolumetricFlow.setter\ndef VolumetricFlow(self, value):\n    stream, mol = self.data\n    if value:\n        c = self.name # c = compound\n        c.T = stream.T\n        c.P = stream.P\n        c.phase = stream._phase\n        mol[0] = value/(c.Vm * 1000)\n    else:\n        mol[0] = 0.\n\nphases = ('s', 'l', 'L', 'g')\nphase_index = dict(zip(phases, (0, 1, 2, 3)))\n\ndef flow(fget):\n    def fset(self, value):\n        if fget(self) is not value: raise AttributeError(f\"can't set attribute\")\n    return property(fget, fset)\n\n\n# %% Stream classes\n\nclass metaStream(type):\n    \"\"\"Metaclass for Stream.\"\"\"\n    @property\n    def species(cls):\n        \"\"\"[Species] Contains pure component thermodynamic properties for computing overall properties of Stream instances.\"\"\"\n        return cls._cls_species\n    @species.setter\n    def species(cls, species):\n        # Set Species object and related parameters\n        if isinstance(species, Species):\n            Stream._cls_species = WorkingSpecies(species)\n        elif isinstance(species, WorkingSpecies):\n            Stream._cls_species = species\n        else: raise ValueError('must pass a Species object')\n    _species = species\n    @property\n    def indices(self):\n        return self._cls_species.indices\n    @property\n    def index(self):\n        return self._cls_species.index\n    @property\n    def MW(cls):\n        return cls._MW\n\nclass Stream(metaclass=metaStream):\n    \"\"\"Create a Stream object that defines material flow rates along its thermodynamic state. Thermodynamic and transport properties of a stream are readily available. Ideal mixture is assumed for stream properties and excess thermodynamic energies are neglected as a simplifying assumption for low pressure processes.\n\n    Parameters\n    ----------\n    ID='' : str, defaults to a unique ID\n        A unique identification. If ID is None, stream will not be\n        registered in flowsheet.\n\n    flow=() : tuple, optional\n        All flow rates corresponding to `species`.\n\n    species=() : tuple[str] or Species, defaults to Stream.species\n        Species corresponding to `flow`.\n\n    units='kmol/hr' : str, optional\n        Flow rate units of measure (only mass, molar, and\n        volumetric flow rates are valid)\n\n    phase='l' : {'l', 'g', 's'}, optional\n        Either gas (\"g\"), liquid (\"l\"), or solid (\"s\").\n\n    T=298.15 : float, optional\n        Temperature (K).\n\n    P=101325 : float, optional\n        Pressure (Pa).\n\n    price=0 : float, optional\n        Price in USD/kg.\n    \n    **flow_pairs : float\n                   Compound-flow pairs\n\n    Examples\n    --------\n    Before making a stream, set the species using a Species object:\n\n    .. code-block:: python\n\n       >>> # Set Species object\n       >>> Stream.species = Species('Ethanol', 'Water') \n\n    Stream objects may be created a variety of ways:\n\n    .. code-block:: python\n\n       >>> # Create a stream specifying compound and flow rate pairs:\n       >>> s1 = Stream(ID='s1', Water=2)\n       >>> s1.show()\n       Stream: s1\n        phase: 'l', T: 298.15 K, P: 101325 Pa\n        flow (kmol/hr): Water  2\n\n       >>> # Create a stream assuming same order as given in species:\n       >>> s2 = Stream(ID='s2', flow=(1, 2))\n       >>> s2.show()\n       Stream: s2\n        phase: 'l', T: 298.15 K, P: 101325 Pa\n        flow (kmol/hr): Ethanol  1\n                        Water    2\n\n       >>> # Create a stream passing flow rate units, phase, temperature and pressure:\n       >>> s3 = Stream(ID='s3', flow=(0.278, 0.556), units='mol/s', phase='g', T=400, P=101325)\n       >>> s3.show()\n       Stream: s3\n        phase: 'g', T: 400 K, P: 101325 Pa\n        flow (kmol/hr): Ethanol  1.\n                        Water    2.\n\n       >>> # The working units do not change\n       >>> s3.mol \n       array([1., 2.])\n\n    .. Warning:: Stream objects do not automatically calculate thermodynamic equilibrium. They simply assume the given phase, temperature and pressure are correct. To find equilibrium, use the VLE or LLE method.\n\n    Use the `show` method to print all specifications with desired units:\n\n    .. code-block:: python\n\n       >>> # Temperature in degree Celsius\n       >>> s2.show(T='degC')\n       Stream: s2 \n        phase: 'l', T: 25. degC, P: 101325 Pa\n        flow (kmol/hr): Ethanol  1\n                        Water    2\n       \n       >>> # Flow in kg/hr\n       >>> s2.show(flow='kg/hr')\n       Stream: s2 \n        phase: 'l', T: 298.15 K, P: 101325 Pa\n        flow (kg/hr): Ethanol  46.1\n                      Water    36\n\n       >>> # Flow in fractions\n       >>> s2.show(fraction=True)\n       Stream: s2\n        phase: 'l', T: 298.15 K, P: 101325 Pa\n        flow: Ethanol  0.333\n              Water    0.667\n              net      3 kmol/hr\n\n    Flow rates are stored internally as an array in the ‘mol’ attribute.\n\n    .. code-block:: python\n\n       >>> # Set Water flow rate\n       >>> s2.mol[1] = 18\n       >>> s2.mol # kmol/hr\n       array([1, 18])\n\n    Mass and volumetric flow rates are also available as property_arrays of the molar flow rate. As such, they are always up to date with the molar flow rate and altering them also alters the molar flow rate:\n\n    .. code-block:: python\n\n       >>> # Altering mass or volumetric flows alters the molar flow\n       >>> s2.vol # m^3/hr\n       property_array([0.059, 0.036])\n       >>> s2.vol[:] = [1, 1]\n       >>> s2.mol\n       array([17.06 , 55.343])\n       >>> # Values are always up to date with the molar flow\n       >>> s2.mol[:] = [1, 2]\n       >>> s2.vol\n       property_array([0.059, 0.036])\n\n    .. Note::\n\n       property_array objects are significantly slower than array objects. This is because flow rate data is internally stored as molar flow rates. Also, property_array objects are arrays of python objects, which add overhead over the C implementation of numpy. Whenever possible, use the array to manage flow rates. \n\n    Some thermodynamic/material properties, including enthalpy and heat capacity, are dependent only on temperature:\n\n    .. code-block:: python\n    \n       >>> s2.T = 298.15\n       >>> s2.Cp # Heat capacity (kJ/(kg-K))\n       3.200382054794244\n       >>> s2.H  # Enthalpy (kJ/hr)\n       0.0\n       \n       >>> # Change of temperature\n       >>> s2.T = 310\n       >>> s2.H\n       3140.9389548625936\n       >>> s2.Cp\n       3.2590872180092956\n       \n    .. Note:: Thermodynamic energies are relative to 25 degC and 1 atm.\n    \n    Some thermodynamic/material properties, including volume and density, are dependent on both temperature and pressure:\n\n    .. code-block:: python\n    \n       >>> s1.volnet # Volumetric flow rate (m^3/hr)\n       0.036138079740245625\n       >>> s1.rho # Density (kg/m^3)\n       997.0247522552814\n      \n       >>> # Change of pressure\n       >>> s1.P *= 4\n       >>> s1.volnet\n       0.036136231155141196\n       >>> s1.rho\n       997.0757560552587\n      \n       >>> # Change of temperature\n       >>> s1.T += 30\n       >>> s1.volnet\n       0.03663597700908213\n       >>> s1.rho\n       983.4747955832584\n\n    A dictionary of available stream properties and respective units of measure is available in `Stream.units`. You may also find it useful to use the `help` method to search for a property:\n        \n    .. code-block:: python\n\n       >>> Stream.help('conductivity')\n       k: [float] Thermal conductivity as a function of T and P (W/m/K).\n\n    \"\"\"\n    \n    # [dict] Units of measure for material properties (class attribute). \n    units = units_of_measure\n\n    # Information regarding properties\n    _prop_info = (\n        # ID         # Description               # Dependency # Units      # Type\n        ('T',        'temperature',              '',          'K',         'float'),\n        ('H',        'enthalpy',                 'T',         'kJ/hr',     'float'),\n        ('S',        'entropy',                  'TP',        'kJ/hr',     'float'),\n        ('G',        'Gibbs free energy',        'TP',        'kJ/hr',     'float'),\n        ('U',        'interal energy',           'TP',        'kJ/hr',     'float'),\n        ('A',        'Helmholtz free energy',    'TP',        'kJ/hr',     'float'),\n        ('Hf',       'enthalpy of formation',    '',          'kJ/hr',     'float'),\n        ('P',        'pressure',                 '',          'Pa',        'float'),\n        ('Cpm',      'molar heat capacity',      'T',         'J/mol/K',   'float'),\n        ('Cp',       'specific heat capacity',   'T',         'J/kg/K',    'float'),\n        ('Vm',       'molar volume',             'TP',        'm^3/mol',   'float'),\n        ('rho',      'density',                  'TP',        'kg/m^3',    'float'),\n        ('rhom',     'molar density',            'TP',        'mol/m^3',   'float'),\n        ('nu',       'kinematic viscosity',      'TP',        'm^2/s',     'float'),\n        ('mu',       'hydraulic viscosity',      'TP',        'Pa*s',      'float'),\n        ('sigma',    'surface tension',          'T',         'N/m',       'float'),\n        ('k',        'thermal conductivity',     'TP',        'W/m/K',     'float'),\n        ('alpha',    'thermal diffusivity',      'TP',        'm^2/s',     'float'),\n        ('Pr',       'Prantl number',            'TP',        \"''\",        'float'),\n        ('mass',     'mass flow rates',          '',          'kg/hr',     'ndarray'),\n        ('mol',      'molar flow rates',         '',          'kmol/hr',   'ndarray'),\n        ('vol',      'volumetric flow rates',    'TP',        'm^3/hr',    'ndarray'),\n        ('massnet',  'net mass flow rate',       '',          'kg/hr',     'float'),\n        ('molnet',   'net molar flow rate',      '',          'kmol/hr',   'float'),\n        ('volnet',   'net volumetric flow rate', 'TP',        'm^3/hr',    'float'),\n        ('massfrac', 'mass fractions',           '',          'kg/kg',     'ndarray'),\n        ('molfrac',  'molar fractions',          '',          'kmol/kmol', 'ndarray'),\n        ('volfrac',  'volumetric fractions',     'TP',        'm^3/m^3',   'ndarray'))\n\n    __slots__ = ('T', 'P', '_mol', '_mass', '_vol', 'price', '_ID', '_link',\n                 '_species', '_sink', '_source', '_dew_point',\n                 '_bubble_point', '_gamma', '_phase', '_lL_split_cached',\n                 '__weakref__', '_source_link', '_VLE')\n\n    line = 'Stream'\n\n    ### Class attributes for working species ###    \n    _cls_species = _MW = None\n    \n    #: [str] Default ID for all streams (class attribute)\n    default_ID = 'd'\n    \n    #: [int] Current number for default IDs (class attribute)\n    default_ID_number = 0\n    \n    #: [bool] If True, approximate energy balance. False otherwise.\n    lazy_energy_balance = True\n\n    #: [DisplayUnits] Units of measure for IPython display\n    display_units = DisplayUnits(T='K', P='Pa',\n                                 flow=('kmol/hr', 'kg/hr', 'm3/hr'),\n                                 fraction=False,\n                                 N=5)\n\n    def __init__(self, ID='', flow=(), species=(), units='kmol/hr',\n                 phase='l', T=298.15, P=101325, *, price=0, **flow_pairs):\n        # Get species and set species information\n        if isinstance(species, Species):\n            self._species = WorkingSpecies(species)\n            species = ()\n        elif isinstance(species, WorkingSpecies):\n            self._species = species\n            species = ()\n        else: \n            assert self._cls_species, 'must define Stream.species first'\n            self._species = self._cls_species\n        self._link = self._ID = self._sink = self._source = None\n        self._source_link = self\n        self.phase = phase\n        self.T = T  #: [float] Temperature (K)\n        self.P = P  #: [float] Pressure (Pa)\n        self.price = price  #: Price of stream (USD/kg)\n        \n        # Initialize flows\n        self._setflows(flow, species, flow_pairs)\n        mol = self._mol\n        MW = self._species._MW\n        mass = [] # Mass flow rates\n        vol = [] # Volumetric flow rates    \n        cmps = self._species._compounds\n        for i in self._species._index:\n            mol_i = mol[i:i+1]\n            s = cmps[i]\n            mass.append(MassFlow(s.ID, (mol_i, MW[i])))\n            vol.append(VolumetricFlow(s, (self, mol_i)))\n        self._mass = property_array(mass)\n        self._vol = property_array(vol)\n        if units == 'kmol/hr': pass\n        if units == 'kg/hr': self._mass[:] = mol\n        elif units == 'm3/hr': self._vol[:] = mol\n        else:\n            q = _Q(mol, units)\n            dim = q.dimensionality\n            if dim == mol_flow_dim:\n                self._mol[:] = q.to('kmol/hr').magnitude\n            elif dim == mass_flow_dim:\n                self._mass[:] = q.to('kg/hr').magnitude\n            elif dim == vol_flow_dim:\n                self._vol[:] = q.to('m3/hr').magnitude\n            else:\n                raise DimensionError(f\"dimensions for flow units must be in molar, mass or volumetric flow rates, not '{dim}'\")\n        self.ID = ID\n        self._gamma = gamma = Dortmund()\n        self._bubble_point = BubblePoint(gamma)\n        self._dew_point = DewPoint(gamma)\n\n    def setflow(self, flow=(), species=(), units='kmol/hr', inplace='', **flow_pairs):\n        \"\"\"Set `flow` rates according to the `species` order and `flow_pairs`. `inplace` can be any operation that can be performed in place (e.g. +, -, *, /, |, **, etc.).\"\"\"\n        species = (*species, *flow_pairs.keys())\n        flow = (*flow, *flow_pairs.values())\n        index = self.indices(species) if species else ... \n        q = _Q(flow, units)\n        dim = q.dimensionality\n        if dim == mol_flow_dim:\n            exec(f\"self._mol[index] {inplace}= q.to('kmol/hr').magnitude\", locals())\n        elif dim == mass_flow_dim:\n            exec(f\"self._mass[index] {inplace}= q.to('kg/hr').magnitude\", locals())\n        elif dim == vol_flow_dim:\n            exec(f\"self._vol[index] {inplace}= q.to('m3/hr').magnitude\", locals())\n        else:\n            raise DimensionError(f\"dimensions for flow units must be in molar, \"\n                                 f\"mass or volumetric flow rates, not '{dim}'\")\n    \n    def getflow(self, *species, units='kmol/hr'):\n        \"\"\"Get flow rates of species in given units.\"\"\"\n        index = self.indices(species) if species else ...\n        q = _Q(1, units)\n        dim = q.dimensionality\n        if dim == mol_flow_dim:\n            return self._mol[index]*q.to('kmol/hr').magnitude\n        elif dim == mass_flow_dim:\n            return self._mass[index]*q.to('kg/hr').magnitude\n        elif dim == vol_flow_dim:\n            return self._vol[index]*q.to('m3/hr').magnitude\n        else:\n            raise DimensionError(f\"dimensions for flow units must be in molar, \"\n                                 f\"mass or volumetric flow rates, not '{dim}'\")\n    \n    def _setflows(self, flow, species, flow_pairs):\n        \"\"\"Initialize molar flow rates according to the species order, and flow_pairs. Instance species do not change.\"\"\"\n        flowlen = len(flow)\n        specieslen = len(species)\n        if flowlen:\n            if flow_pairs:\n                raise ValueError('cannot specify both \"flow\" and '\n                                 '\"flow_pairs\" when species is passed')\n            elif flowlen == specieslen:\n                self._mol = self._species.array(species, flow)\n            elif (not specieslen) and (flowlen == self._species._N):\n                self._mol = np.array(flow, float)\n            else:\n                raise ValueError('length of flow rates must be equal to '\n                                 'length of species')\n        elif flow_pairs:\n            self._mol = self._species.array(flow_pairs, [*flow_pairs.values()])\n        else:\n            self._mol = np.zeros(self.species._N, float)\n                \n    # Forward pipping\n    def __sub__(self, index):\n        if isinstance(index, int):\n            return Sink(self, index)\n        elif isinstance(index, Stream):\n            raise TypeError(\"unsupported operand type(s) for -: \"\n                            f\"'{type(self)}' and '{type(index)}'\")\n        return index.__rsub__(self)\n        \n    def __rsub__(self, index):\n        if isinstance(index, int):\n            return Source(self, index)\n        elif isinstance(index, Stream):\n            raise TypeError(\"unsupported operand type(s) for -: \"\n                            \"'{type(self)}' and '{type(index)}'\")\n        return index.__sub__(self)\n\n    # Backward pipping    \n    __pow__ = __sub__\n    __rpow__ = __rsub__\n    \n    @property\n    def phase(self):\n        \"\"\"[str] 'l' for liquid, 'g' for gas, or 's' for solid.\"\"\"\n        return self._phase\n    @phase.setter\n    def phase(self, phase):\n        if phase not in ('l', 'g', 's'):\n            raise ValueError(f\"phase must be either 's', 'l', or 'g'\")\n        self._phase = phase\n    \n    @staticmethod\n    def proxy(ID, link=MissingStream):\n        \"\"\"Create a Stream object that serves as a proxy for its `link` stream.\"\"\"\n        self = object.__new__(Stream)\n        self._source = self._sink = self._ID = None\n        self._source_link = MissingStream\n        self.ID = ID\n        self.price = 0\n        if link: self.link = link\n        else: self._link = MissingStream\n        return self\n    \n    @property\n    def link(self):\n        \"\"\"When another Stream object is set as a link, it will share data with that object.\"\"\"\n        return self._link\n    \n    @link.setter\n    def link(self, stream):\n        try:\n            if self._source_link is stream._source_link:\n                self._link = stream\n            elif stream is None:\n                self.__init__(ID=self._ID, flow=self._mol,\n                              species=self._species,\n                              T=self.T, P=self.P, phase=self._phase)\n            else:\n                self._species = stream._species\n                self._mass = stream._mass\n                self._mol = stream._mol\n                self._vol = stream._vol\n                self._dew_point = stream._dew_point\n                self._bubble_point = stream._bubble_point\n                self._gamma = stream._gamma\n                self._source_link = stream._source_link\n                self._link = stream\n                self.P = stream.P\n                self.T = stream.T\n                self._phase = stream.phase\n        except Exception as Error:\n            if isinstance(stream, Stream): raise Error\n            else: raise TypeError(f\"link must be a Stream object, not a \"\n                                  \"'{type(stream).__name__}' object.\")\n    \n    @property\n    def species(self):\n        \"\"\"[Species] Contains pure component thermodynamic properties for computing overall properties of Stream instances.\"\"\"\n        return self._species\n    \n    @property\n    def ID(self):\n        \"\"\"Unique identification (str). If set as '', it will choose a default ID.\"\"\"\n        return self._ID\n\n    @ID.setter\n    def ID(self, ID):\n        if ID == '':\n            # Select a default ID\n            self.__class__.default_ID_number += 1\n            ID = self.default_ID + str(self.default_ID_number)\n            self._ID = ID\n            setattr(find.stream, ID, self)\n        elif ID and ID != self._ID:\n            setattr(find.stream, ID, self)\n\n    @property\n    def cost(self):\n        \"\"\"Cost of stream (USD/hr)\"\"\"\n        return self.price*self.massnet\n\n    @property\n    def MW(self):\n        \"\"\"Molecular weight of all species (array g/mol):     \n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Water', 'Ethanol')\n        >>> Stream.MW\n        tuple_array([18.01528, 46.06844])\n        \"\"\"\n        return self._species._MW.view(tuple_array)\n\n    ### Flow properties ###\n    \n    @property\n    def indices(self):\n        \"\"\"Return indices of specified species.\n\n        Parameters\n        ----------\n        IDs : iterable\n              Species IDs or CAS numbers.\n\n        Examples\n        --------\n        Indices by ID:\n        \n        >>> from biosteam import *\n        >>> Stream.species = Species(['Ethanol', 'Water'])\n        >>> s1 = Stream()\n        >>> s1.indices(['Water', 'Ethanol'])\n        [1, 0]\n\n        Indices by CAS number:\n        \n        >>> s1.indices(['7732-18-5', '64-17-5']):\n        [1, 0]\n\n        \"\"\"\n        return self._species.indices\n    \n    @property\n    def index(self):\n        \"\"\"Return index of specified compound.\n\n        Parameters\n        ----------\n        ID: str\n            Compound ID\n\n        Examples\n        --------\n        Index by ID:\n        \n        >>> from biosteam import *\n        >>> Stream.species = Species(['Ethanol', 'Water'])\n        >>> s1 = Stream()\n        >>> s1.index('Water')\n        1\n\n        Indices by CAS number:\n        \n        >>> s1.index('7732-18-5'):\n        1\n\n        \"\"\"\n        return self._species.index\n    \n    # Molar flow\n    @flow\n    def mol(self):\n        \"\"\"Array of molar flow rates (kmol/hr):\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Water', 'Ethanol')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s1.mol\n        array([0, 2])\n        >>> s1.mol[:] = [1, 2]\n        >>> s1.mol\n        array([1, 2])\n        \"\"\"\n        return self._mol\n\n    @property\n    def molfrac(self):\n        \"\"\"Array of molar fractions.\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Water', 'Ethanol')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s1.molfrac\n        tuple_array([0., 1.])\n        \"\"\"\n        return fraction(self._mol).view(tuple_array)\n\n    @property\n    def molnet(self):\n        \"\"\"Net molar flow rate (kmol/hr)\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Water', 'Ethanol')\n        >>> s1 = Stream(Ethanol=2, Water=1)\n        >>> s1.molnet\n        3\n        \"\"\"\n        return self._mol.sum()\n\n    # Mass flow\n    @flow\n    def mass(self):\n        \"\"\"Array of mass flow rates (kg/hr)\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Water=2)\n        >>> s1.mass\n        property_array([ 0.   , 36.031])\n        \"\"\"\n        return self._mass\n\n    @property\n    def massfrac(self):\n        \"\"\"Array of mass fractions.\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Water=2)\n        >>> s1.massfrac\n        tuple_array([0, 1])\n        \"\"\"\n        return fraction(self._mol * self._species._MW).view(tuple_array)\n\n    @property\n    def massnet(self):\n        \"\"\"Net mass flow rate (kg/hr)\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Water=2)\n        >>> s1.mass\n        36.031\n        \"\"\"\n        return (self._species._MW * self._mol).sum()\n\n    # Volumetric flow\n    @flow\n    def vol(self):\n        \"\"\"Array of volumetric flow rates as a function of T and P (m^3/hr).\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Water=2)\n        >>> s1.vol\n        property_array([0.   , 0.036])\n        \n        \"\"\"\n        return self._vol\n\n    @property\n    def volfrac(self):\n        \"\"\"Array of volumetric fractions as a function of T and P.\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Water=2)\n        >>> s1.volfrac\n        tuple_array([0.0, 1.0], dtype=object)\n                \"\"\"\n        return fraction(self._vol).view(tuple_array)\n        \n    @property\n    def volnet(self):\n        \"\"\"Net volumetric flow rate as a function of T and P (m^3/hr).\n\n        from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Water=2)\n        >>> s1.volnet\n        0.036138079740245625\n        \"\"\"\n        return self._species._propflow('Vm', self._mol, self.T, self.P, self._phase)*1000\n\n    ### Energy flows ###\n\n    def H_at(self, mol=None, T=None, P=None, phase=None):\n        \"\"\"Return enthalpy flow rate at given arguments, excluding formation energies (kJ/hr). Arguments with None values default to stream specifications.\"\"\"\n        return self._species._propflow('H', mol or self._mol, T or self.T,\n                                       P or self.P, phase or self._phase)\n\n    # Enthalpy\n    @property\n    def H(self):\n        \"\"\"Enthalpy flow rate as a function of T, excluding formation energies (kJ/hr).\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Water=2)\n        >>> s1.H # The stream is at the reference state\n        0.0\n        >>> s1.H = 1000\n        >>> s1.T\n        304.7888167493753\n        >>> s1.H\n        999.5728716085112\n\n        .. Note:: The solver reaches a level of tolerance and the new temperature is an approximation.\n        \"\"\"\n        return self._species._propflow('H', self._mol, self.T, self.P, self._phase)\n\n    @H.setter\n    def H(self, H):\n        try:\n            if self.lazy_energy_balance:\n                self.T += (H - self.H)/self.C    \n            else:\n                # First approximation\n                T_old = self.T\n                C = self.C\n                self.T += (H - self.H)/C\n            \n                # Solve enthalpy by iteration\n                it = 0\n                it2 = 0\n                while abs(self.T - T_old) > 0.01:\n                    T_old = self.T\n                    self.T += (H - self.H)/C\n                    if it == 5:\n                        it = 0\n                        it2 += 1\n                        C = self.C\n                        if it2 > 10:\n                            raise SolverError(\"could not solve temperature \"\n                                              \"given enthalpy\")\n                    else: it += 1\n        except Exception as Error:\n            if (self._mol == 0).all():\n                raise ValueError(f\"cannot set enthalpy to empty stream\")\n            else:\n                raise Error\n\n    @property\n    def Hnet(self):\n        \"\"\"Total enthaly flow rate including heats of formation\"\"\"\n        return self.Hf + self.H\n\n    @property\n    def Hf(self):\n        \"\"\"Heat of formation flow rate (kJ/hr).\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Water=2)\n        >>> s1.Hf\n        -483640.0\n        \"\"\"\n        return (self.mol * [i.Hf or 0 for i in self._species._compounds]).sum()\n\n    @property\n    def Hc(self):\n        \"\"\"Heat of combustion flow rate (kJ/hr).\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s1.Hc\n        -2819966.0\n        \"\"\"\n        return (self.mol * [i.Hc or 0 for i in self._species._compounds]).sum()\n        \n    # Entropy\n    @property\n    def S(self):\n        \"\"\"Entropy flow rate as a function of T and P, excluding formation energies (kJ/hr).\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s1.S # The stream is at the reference state\n        0.0\n        >>> s1.T = 320\n        >>> s1.S\n        16.503899351682694\n        \"\"\"\n        return self._species._propflow('S', self._mol, self.T, self.P, self._phase)\n\n    # Gibbs free energy\n    @property\n    def G(self):\n        \"\"\"Gibbs free energy flow rate as a function of T and P, excluding formation energies (kJ/hr).\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s1.G # The stream is at the reference state\n        0.0\n        >>> s1.T = 320\n        >>> s1.G\n        -182.43024800100193\n        \"\"\"\n        return self.H - self.S*self.T\n\n    # Internal energy\n    @property\n    def U(self):\n        \"\"\"Internal energy flow rate as a function of T and P, excluding formation energies (kJ/hr).\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s1.U # The stream is at the reference state\n        0.0\n        >>> s1.T = 320\n        >>> s1.U\n        -7090.732710112934\n        \"\"\"\n        return self.H - self.P*self.volnet\n\n    # Helmholtz\n    @property\n    def A(self):\n        \"\"\"Helmholtz energy flow rate as a function of T and P, excluding formation energies (kJ/hr).\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s1.A # The stream is at the reference state\n        0.0\n        >>> s1.T = 320\n        >>> s1.A\n        -12371.980502651397\n        \"\"\"\n        return self.U - self.T*self.S\n\n    # Capacity flow rate\n    @property\n    def C(self):\n        \"\"\"Heat capacity flow rate as a function of T (kJ/K/hr).\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s2.C\n        243.41704115214097\n        \"\"\"\n        return self._species._propflow('Cpm', self._mol, self.T, self.P, self._phase)\n\n    # Material properties\n    @property\n    def Cp(self):\n        \"\"\"Specific heat capacity as a function of T (kJ/kg/K).\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s1.Cp\n        2.641906706110962\n        \"\"\"\n        return self.Cpm*self.molnet/self.massnet\n\n    @property\n    def Cpm(self):\n        \"\"\"Molar heat capacity as a function of T (kJ/kmol/K).\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s1.Cpm # (J/mol/K)\n        121.70852057607048\n        \"\"\"\n        return self.C/self.molnet\n\n    @property\n    def Vm(self):\n        \"\"\"Molar volume as a function of T and P (m^3/mol).\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s1.Vm\n        0.00012030150757118572\n        \"\"\"\n        return self._species._prop('Vm', self._mol, self.T, self.P, self._phase)\n\n    @property\n    def rho(self):\n        \"\"\"Density as a function of T (kg/m^3).\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s1.rho\n        765.8830039638536\n        \"\"\"\n        return self.massnet/self.volnet\n\n    @property\n    def rhom(self):\n        \"\"\"Molar density as a function of T and P (mol/m^3).\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s1.rhom\n        16.624895567634884\n        \"\"\"\n        return self.molnet/self.volnet\n\n    @property\n    def nu(self):\n        \"\"\"Kinematic viscosity as a function of T and P (m^2/s).\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s1.nu\n        5.733020843964377e-06\n        \"\"\"\n        return self.mu/self.rho\n\n    @property\n    def mu(self):\n        \"\"\"Hydraulic viscosity as a function of T and P (Pa*s).\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s1.mu\n        0.0010780252844121937\n        \"\"\"\n        # Katti, P.K.; Chaudhri, M.M. (1964). \"Viscosities of Binary Mixtures of Benzyl Acetate with Dioxane, Aniline, and m-Cresol\". Journal of Chemical and Engineering Data. 9 (1964): 442–443.\n        # molfrac = self.molfrac\n        # props = self._species._props\n        # mus = np.array(props('mu', self._mol, self.T, self.P, self._phase))\n        # Vms = np.array(props('mu', self._mol, self.T, self.P, self._phase))\n        # pos = np.where(molfrac != 0)\n        # return np.exp((molfrac[pos]*np.log(mus[pos]*Vms[pos])).sum())/self.Vm\n        return self._species._prop('mu', self._mol, self.T, self.P, self._phase)\n\n    @property\n    def k(self):\n        \"\"\"Thermal conductivity as a function of T and P (W/m/k).\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s1.k\n        0.16476716002011285\n        \"\"\"\n        return self._species._prop('k', self._mol, self.T, self.P, self._phase)\n\n    @property\n    def alpha(self):\n        \"\"\"Thermal diffusivity as a function of T and P (m^2/s).\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s1.alpha\n        8.614274122585474e-08\n        \"\"\"\n        return self._species._prop('alpha', self._mol, self.T, self.P, self._phase)\n\n    @property\n    def sigma(self):\n        \"\"\"Surface tension as a function of T (N/m).\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s1.sigma\n        0.02188440412824106\n        \"\"\"\n        return self._species._prop('sigma', self._mol, self.T, self.P, self._phase)\n\n    @property\n    def Pr(self):\n        \"\"\"Prandtl number as a function of T and P (non-dimensional).\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s1.Pr\n        15.923321696004477\n        \"\"\"\n        return self._species._prop('Pr', self._mol, self.T, self.P, self._phase)\n\n    @property\n    def P_vapor(self):\n        \"\"\"Vapor pressure (Pa), not taking into account light species always in gas phase.\n        \n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s1.P_vapor\n        array([7872.1566667784855, 0 ])\n        \"\"\"\n        mol = self.mol\n        species = self._species\n        indices = species._equilibrium_indices(mol>0)\n        compounds = species._compounds\n        N = len(indices)\n        P_vapor = np.zeros_like(mol)\n        if N==0: return P_vapor\n        species = [compounds[i] for i in indices]\n        mol = self.mol[indices]\n        x = mol/mol.sum()\n        T = self.T\n        Psat = [s.VaporPressure(T) for s in species]\n        self._gamma.species = species\n        P_vapor[indices] = x * Psat * self._gamma(x, T)\n        return P_vapor\n        \n    # Other properties\n    @property\n    def source(self):\n        \"\"\"Unit source.\"\"\"\n        return self._source\n\n    @property\n    def sink(self):\n        \"\"\"Unit sink.\"\"\"\n        return self._sink\n\n    @property\n    def nonzero_species(self):\n        \"\"\"Flow indices and species that have a non-zero flow rate.\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Water=2)\n        >>> s1.nonzero_species\n        [1], ['Water']\n        \"\"\"\n        return nonzero_species(self._species, self.mol)\n    \n    def quantity(self, prop_ID):\n        \"\"\"Return a property as a Quantity object as described in the `pint package <https://pint.readthedocs.io/en/latest/>`__ \n\n        Parameters\n        ----------\n        prop_ID : str\n                  Name of the property (e.g. 'mol', 'H', 'k' ...)\n\n        Examples\n        --------\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s1.quantity('Cp')\n        2.4337467143619698 J/K/g\n\n        \"\"\"\n        attr = getattr(self, prop_ID)\n        if isinstance(attr, np.ndarray):\n            attr = np.array(attr.astype(float))\n        return _Q(attr, self.units[prop_ID])\n\n    # Derivative of a property and sensivity analysis\n    def derivative(self, prop_ID, var_ID, index=None):\n        \"\"\"Return the derivative of property 'prop_ID' and variable 'var_ID'. If the property given by var_ID is an array, use index to specify which element.\n\n        Parameters\n        ----------\n        prop_ID : str\n                  Name of the property (e.g. 'rho', 'Cp', 'H', 'volnet' ...)\n        var_ID : str\n                 Name of the variable (e.g 'T', 'P', 'molnet' ...)\n        index : array_like, optional\n                Indices if the variable is an array\n\n        Examples\n        --------\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Ethanol=2)\n        >>> s1.derivative('rho', 'T')\n        -0.8917376157800969\n\n        \"\"\"\n        if index is not None:\n            def getvar():\n                return getattr(self, var_ID)[index]\n\n            def setvar(xf):\n                getattr(self, var_ID)[index] = xf\n        else:\n            def getvar():\n                return getattr(self, var_ID)\n\n            def setvar(xf):\n                setattr(self, var_ID, xf)\n        x0 = getvar()\n        y0 = getattr(self, prop_ID)\n        xf = x0 + 10**-6\n        setvar(xf)\n        yf = getattr(self, prop_ID)\n        setvar(x0)\n        return (yf-y0)/(xf-x0)\n\n    # Specifications\n    @staticmethod\n    def like(stream, ID=''):\n        \"\"\"Create either a Stream or MixedStream object just like the given stream, depending on whether multiple phases are present.\"\"\"\n        s = stream\n        if isinstance(stream, MS.MixedStream):\n            out = MS.MixedStream(ID,\n                                 species=stream._species,\n                                 T=s.T, P=s.P)\n            out._molarray[:] = stream._molarray\n        else:\n            out = Stream(ID, flow=s._mol, species=s._species,\n                         phase=s._phase, T=s.T, P=s.P)\n        return out\n    \n    def copylike(self, stream):\n        \"\"\"Copy flow rates, T, P, and phase of stream to self.\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream()\n        >>> s2 = Stream(Ethanol=1, Water=2, T=400, phase='g')\n        >>> s1.copylike(s2)\n        >>> s1.show()\n        Stream: s1\n         phase: 'g', T: 400.00 K, P: 101325 Pa\n         flow (kmol/hr): Ethanol  1\n                         Water    2\n        \"\"\"\n        if isinstance(stream, MS.MixedStream):\n            self.enable_phases()\n            self.copylike(stream)\n        elif not (self._species is stream._species):\n            raise ValueError('species must be the same to copy stream specifications')\n        else:\n            self._mol[:] = stream.mol\n            self.P = stream.P\n            self._phase = stream.phase\n            self.T = stream.T\n            \n    def copyflow(self, stream, species=None, *, remove=False, exclude=False):\n        \"\"\"Copy flow rates of stream to self.\n        \n        Parameters\n        ----------\n        stream : Stream\n            Flow rates will be copied from here.\n        species=None : iterable[str], defaults to all species.\n            Species IDs. \n        remove=False: bool, optional\n            If True, copied species will be removed from `stream`.\n        exclude=False: bool, optional\n            If True, exclude `species` when copying.\n        \n        Notes\n        -----\n        \n        Species that are not included will be set to zero.\n        \n        \"\"\"\n        assert self._species is stream._species, ('species must be the same to '\n                                                  'copy stream specifications')\n        if species is None:\n            self._mol[:] = stream.mol\n            if remove: stream._mol[:] = 0\n        else:\n            indices = self.indices(species)\n            if exclude:\n                self._mol[:] = stream.mol\n                self._mol[indices] = 0\n                if remove:\n                    mol = stream._mol\n                    if isinstance(stream, MS.MixedStream):\n                        mol[:], mol[:, indices] = 0, mol[:, indices]\n                    else:\n                        mol[:], mol[indices] = 0, mol[indices]\n            else:\n                self._mol[:] = 0\n                self._mol[indices] = stream.mol[indices]\n                if remove: \n                    if isinstance(stream, MS.MixedStream):\n                        stream._mol[phase_index[self.phase], indices] = 0\n                    else:\n                        stream._mol[indices] = 0\n\n    def recieve_vent(self, stream, efficiency=1):\n        assert self._species is stream._species, 'species must be the same to recieve vent'\n        y = stream.P_vapor/self.P\n        Y = y.sum()\n        vent_mol = self._mol\n        mol2vent = vent_mol.sum()*y*Y/(1-Y)*efficiency\n        stream._mol[:] -= mol2vent\n        vent_mol += mol2vent\n\n    def empty(self):\n        \"\"\"Set flow rates to zero\n\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Water=1)\n        >>> s1.empty()\n        >>> s1.mol\n        array([0, 0])\n        \"\"\"\n        self._mol[:] = 0\n    \n    def bubble_T(self):\n        \"\"\"Bubble point at current composition and pressure.\n\n        Returns\n        -------\n        T : float\n            Bubble point temperature (T).\n        y : numpy.ndarray\n            Vapor phase composition.\n        indices : list[int]\n                  Indices of species in equilibrium\n        \n        Examples\n        --------\n        >>> from biosteam import *\n        >>> stream = Stream(flow=(0.6, 0.4),\n        ...                 species=Species('Ethanol', 'Water'))\n        >>> stream.bubble_T()\n        (352.2820850833474, array([0.703, 0.297]), [0, 1])\n\n        \"\"\"\n        mol = self.mol\n        # If just one specie in equilibrium, return Tsat\n        indices = self._species._equilibrium_indices(mol>0)\n        cmps = self._species._compounds\n        N = len(indices)\n        if N == 1:\n            return (cmps[indices[0]].Tsat(self.P), np.array((1,)), indices)\n        elif N == 0:\n            raise EquilibriumError('no species available for phase equilibrium')\n        mol = mol[indices]\n        self._gamma.species = [cmps[i] for i in indices]\n        # Solve and return bubble point\n        return (*self._bubble_point.solve_Ty(mol/mol.sum(), self.P), indices)\n    \n    def bubble_P(self):\n        \"\"\"Bubble point at current composition and temperature.\n\n        Returns\n        -------\n        P : float\n            Bubble point pressure (Pa).\n        y : numpy.ndarray\n            Vapor phase composition.\n        indices : list[int]\n                  Indices of species in equilibrium.\n\n        Examples\n        --------\n        >>> from biosteam import *\n        >>> s1 = Stream(flow=(0.703, 0.297), T=352.28,\n                        species=Species('Ethanol', 'Water'))\n        >>> s1.bubble_P()\n        (103494.17209657285, array([0.757, 0.243]), [0, 1])\n\n        \"\"\"\n        mol = self.mol\n        # If just one specie in equilibrium, return Tsat\n        indices = self._species._equilibrium_indices(mol>0)\n        cmps = self._species._compounds\n        N = len(indices)\n        if N == 1:\n            return (cmps[indices[0]].VaporPressure(self.T), np.array((1,)), indices)\n        elif N == 0:\n            raise EquilibriumError('no species available for phase equilibrium')\n        mol = mol[indices]\n        self._gamma.species = [cmps[i] for i in indices]\n        # Solve and return bubble point\n        return (*self._bubble_point.solve_Py(mol/mol.sum(), self.T), indices)\n\n    def dew_T(self):\n        \"\"\"Dew point at current composition and pressure.\n        \n        Returns\n        -------\n        T : float\n            Dew point temperature (K).\n        x : numpy.ndarray\n            Liquid phase composition.\n        indices : list[int]\n                  Indices of species in equilibrium\n\n        Examples\n        --------\n        >>> from biosteam import Stream, Species\n        >>> stream = Stream(flow=(0.5, 0.5),\n        ...                 species=Species('Ethanol', 'Water'))\n        >>> stream.dew_T()\n        (357.45184742263075, array([0.151, 0.849]), [0, 1])\n        \n        \"\"\"\n        mol = self.mol\n        # If just one specie in equilibrium, return Tsat\n        indices = self._species._equilibrium_indices(mol>0)\n        cmps = self._species._compounds\n        N = len(indices)\n        if N == 1:\n            return (cmps[0].Tsat(self.P), np.array((1,)), indices)\n        elif N == 0:\n            raise EquilibriumError('no species available for phase equilibrium')\n        mol = mol[indices]\n        self._gamma.species = [cmps[i] for i in indices]\n        # Solve and return dew point\n        return (*self._dew_point.solve_Tx(mol/mol.sum(), self.P), indices)\n    \n    def dew_P(self):\n        \"\"\"Dew point at current composition and temperature.\n        \n        Returns\n        -------\n        P : float\n            Dew point pressure (Pa).\n        x : numpy.ndarray\n            Liquid phase composition.\n        indices : list[int]\n                  Indices of species in equilibrium.\n\n        Examples\n        --------\n        >>> from biosteam import *\n        >>> stream = Stream(flow=(0.703, 0.297), T=352.28,\n        ...                 species=Species('Ethanol', 'Water'))\n        >>> stream.dew_P()\n        (101328.47030327446, array([0.6, 0.4]), [0, 1])\n        \n        \"\"\"\n        mol = self.mol\n        # If just one specie in equilibrium, return Tsat\n        indices = self._species._equilibrium_indices(mol>0)\n        cmps = self._species._compounds\n        N = len(indices)\n        if N == 1:\n            return (cmps[0].VaporPressure(self.T), np.array((1,)), indices)\n        elif N == 0:\n            raise EquilibriumError('no species available for phase equilibrium')        \n        mol = mol[indices]    \n        self._gamma.species = [cmps[i] for i in indices]\n        # Solve and return dew point\n        return (*self._dew_point.solve_Px(mol/mol.sum(), self.T), indices)\n\n    # Dimensionless number methods\n    def Re(self, L, A=None):\n        \"\"\"Return Reynolds number.\n\n        Parameters\n        ----------\n        L : float\n            Characteristic length (m).\n        A=None : float, optional\n            Cross-sectional area (m^2). If A is None, assume flow through a cylindrical pipe.\n\n        Examples\n        --------\n        >>> from biosteam import *\n        >>> Stream.species = Species('Ethanol', 'Water')\n        >>> s1 = Stream(Water=200)\n        >>> s1.Re(0.2, 0.031416)\n        27639.956372923512\n        \n        \"\"\"\n        volnet = self.volnet/3600 # m3/s\n        if A is None:  # Assume pipe\n            return 4*volnet/(self.nu*np.pi*L)\n        return volnet*L/(self.nu*A)\n\n    # Class methods\n    @classmethod\n    def _helpdata(cls, prop):\n        \"\"\"Return information related to a property.\n\n        Parameters\n        ----------\n        prop : str\n               Name or description of a property.\n\n        Returns\n        --------\n        ID : str\n             Name of the property\n        description : str\n                      Description of the property\n        dependency : str\n                     TP dependency\n        units : str\n                Units of measure\n        datatype : str\n                   object type returned by property.\n\n        Examples\n        --------\n        >>> from biosteam import Stream\n        >>> Stream._helplist('k')\n        ('k', 'thermal conductivity', 'TP', 'W/m/K', 'float')\n\n        >>> Stream._helplist('viscosity')\n        (('nu', 'kinematic viscosity', 'TP', 'm^2/s', 'float'),\n         ('mu', 'hydraulic viscosity', 'TP', 'Pa*s', 'float'))\n\n        >>> Stream._helplist('kmol/hr')\n        (('mol', 'molar flow rates', '', 'kmol/hr', 'np.array'),\n         ('molnet', 'net molar flow rate', '', 'kmol/hr', 'float'))\n        \"\"\"\n        # Compare by both ID and description\n        for index in (0, 1):\n            # Search for exact matches\n            for l in cls._prop_info:\n                if prop == l[index]: return l\n        \n        out = []\n        for index in (0, 1):    \n            # If no matches found, search harder\n            for l in cls._prop_info:\n                if prop.lower() in l[index].lower(): out.append(l)\n        return out\n\n    @classmethod\n    def help(cls, prop):\n        \"\"\"Print information related to a property.\n\n        Parameters\n        ----------\n        prop : str\n               Name or description of a property.\n\n        Examples\n        --------\n        >>> from biosteam import Stream\n        >>> Stream.help('rho')\n        rho: [float] Density as a function of T and P (kg/m^3).\n        >>> Stream.help('density')\n        rho: [float] Density as a function of T and P (kg/m^3).\n        \"\"\"\n        data = cls._helpdata(prop)\n        if data: _print_helpdata(data)\n        else: print(f\"No matching property '{prop}'.\")\n\n    @staticmethod\n    def T_equilibrium(streams, T_guess=None, Q_in=0, approximate=True):\n        \"\"\"Bring all streams to temperature equilibrium.\n\n        Parameters\n        ----------\n        streams : iterable[Stream]\n            All streams in temperature equilibrium.\n        \n        T_guess=None : float, optional\n            Equilibrium temperature guess (K).\n\n        Q_in=0 : float, optional\n            Heat addition to streams (kJ/hr).\n            \n        approximate=True : bool\n            If True, approximate energy balance with constant heat capacity.\n\n        Returns\n        -------\n        T : float\n            New temperature (K).\n\n        Examples\n        --------\n        >>> from biosteam import *\n        >>> Stream.species = Species('Water', 'Ethanol')\n        >>> s1 = Stream(Water=2, T=300)\n        >>> s2 = Stream(Ethanol=1, Water=2, T=340)\n        >>> Stream.T_equilibrium([s1, s2])\n        >>> (s1.T, s2.T)\n        (325.8281231556553, 325.8281231556553)\n        \"\"\"\n        sum_ = sum\n        # Set up problem\n        C = sum_([s.C for s in streams])\n        H_ = sum_([s.H for s in streams]) + Q_in\n        \n        # Set initial temperature\n        if not T_guess:\n            T_guess = sum_([s.T for s in streams])/len(streams)\n        for s in streams:\n            s.T = T_guess\n        \n        # Find new T\n        H = sum_([s.H for s in streams])\n        T = T_guess + (H_ - H)/C\n        \n        # Update\n        for s in streams:\n            s.T = T_guess\n        if approximate: return\n        \n        # Solve enthalpy by iteration\n        it = 1\n        while abs(T - T_guess) > 0.01:\n            # Calculate\n            H_ = sum_([s.H for s in streams])\n            T = T_guess + (H_- H)/C\n            \n            # Check iteration\n            if it > 40:\n                raise SolverError(f\"could not solve temperature\")\n            \n            # Update\n            T_guess = T\n            for s in streams:\n                s.T = T_guess\n            it += 1\n\n    @staticmethod\n    def sum(s_sum, streams):\n        \"\"\"Mixes streams and sets resulting mass and energy in 's_sum'. Assumes the same pressure as streams[0], and no phase equilibrium. \n\n        Parameters\n        ----------\n        s_sum : Stream\n                Container for the resulting mixture of streams.\n        streams : iterable[Stream]\n                  Stream objects to be mixed\n\n        Examples\n        --------\n        >>> from biosteam import *\n        >>> Stream.species = Species('Water', 'Ethanol')\n        >>> s1 = Stream(Water=2, T=300)\n        >>> s2 = Stream(Ethanol=1, Water=2, T=340)\n        >>> s_sum = Stream('s_sum')\n        >>> Stream.sum(s_sum, [s1, s2])\n        >>> s_sum.show()\n        Stream: s_sum\n         phase: 'l', T: 326.29 K, P: 101325 Pa\n         flow (kmol/hr): Ethanol  1\n                         Water    4\n        \"\"\"\n        # Check if energy balance is required\n        T_init = streams[0].T\n        other_streams = streams[1:]\n        energy_balance = any([T_init!=s.T for s in other_streams])\n        if energy_balance: H = sum([s.H for s in streams])\n\n        # Copy starting values\n        s_sum.copylike(streams[0])\n\n        # Mass balance\n        inst = isinstance\n        MStream = MS.MixedStream\n        try:\n            if inst(s_sum, MStream):\n                # For MixedStream objects\n                for s in other_streams:\n                    if inst(s, MStream):\n                        s_sum._mol[:] += s._mol\n                    else:\n                        s_sum._mol[phase_index[s._phase]] += s._mol\n            else:\n                # For Stream objects\n                for s in other_streams:\n                    s_sum._mol[:] += s.mol\n        except Exception as Error:\n            if not inst(s_sum, Stream):\n                raise TypeError('s_sum must be a Stream object, not '\n                                \"'{type(s_sum).__name__}'\")\n            for s in streams:\n                if not inst(s, Stream):\n                    raise TypeError('streams must only contain Stream '\n                                    f'objects, not {type(s).__name__} objects')\n            raise Error\n\n        # Energy Balance\n        if energy_balance: s_sum.H = H\n\n    # MixedStream compatibility\n    def enable_phases(self):\n        \"\"\"Cast stream into a MixedStream object.\"\"\"\n        mol = self._mol\n        self.__class__ = MS.MixedStream\n        self._setflows(np.zeros((4, self._species._N)))\n        self._mol[phase_index[self._phase]] = mol\n        self._lL_split_cached = (None,)\n        self._VLE = VLE(self)\n\n    def disable_phases(self, phase):\n        \"\"\"Cast stream into a Stream object.\n        \n        Parameters\n        ----------\n        phase : {'s', 'l', 'g'}\n                Desired phase of stream\n            \n        \"\"\"\n        self._phase = phase\n            \n    @property\n    def VLE(self):\n        \"\"\"A callable VLE object for vapor-liquid equilibrium.\n\n        Parameters\n        ----------\n        Specify two:\n            * **P:** Operating pressure (Pa)\n            * **Q:** Energy input (kJ/hr)\n            * **T:** Operating temperature (K)\n            * **V:** Molar vapor fraction\n            * **x:** Molar composition of liquid (for binary mixture)\n            * **y:** Molar composition of vapor (for binary mixture)\n        species_IDs=None : tuple, optional\n            IDs of species in equilibrium.\n        LNK=None : tuple[str], optional\n            Light non-keys that remain as a vapor (disregards equilibrium).\n        LNK=None : tuple[str], optional\n            Heavy non-keys that remain as a liquid (disregards equilibrium).\n\n        \"\"\"\n        self.enable_phases()\n        return self._VLE\n        \n    def LLE(self, species_IDs=(), split=None, lNK=(), LNK=(),\n            solvents=(), solvent_split=(),\n            P=None, T=None, Q=None):\n        self.enable_phases()\n        self.LLE(species_IDs, split, lNK, LNK,\n                 solvents, solvent_split, P, T, Q)\n\n    def _info_header(self):\n        \"\"\"Return stream information header.\"\"\"\n        # First line\n        unit = self._source\n        if unit is None:\n            source = ''\n        else:\n            source = f'  from  {type(unit).__name__}-{unit}'\n        unit = self._sink\n        if unit is None:\n            sink = ''\n        else:\n            sink = f'  to  {type(unit).__name__}-{unit}'\n        if self.ID:\n            return f\"{type(self).__name__}: {self.ID}{source}{sink}\"\n        else:\n            return f\"{type(self).__name__}{source}{sink}\"\n        \n    def _info_phaseTP(self, phases, T_units, P_units):\n        T = _Q(self.T, self.units['T']).to(T_units).magnitude\n        P = _Q(self.P, self.units['P']).to(P_units).magnitude\n        return f\" phase: '{phases}', T: {T:.5g} {T_units}, P: {P:.6g} {P_units}\\n\"\n\n    # Representation\n    def _info(self, T, P, flow, fraction, N):\n        \"\"\"Return string with all specifications.\"\"\"\n        units = self.units\n        basic_info = self._info_header() + '\\n'\n        if hasattr(self, '_mol'):\n            nonzero, species = self.nonzero_species\n        else:\n            return basic_info + f' link: {self._link}'\n        T_units, P_units, flow_units, fraction, N = [(i if i is not None else j) for i, j in\n                                                     zip((T, P, flow, fraction, N), self.display_units)]\n        basic_info += self._info_phaseTP(self._phase, T_units, P_units)\n        len_ = len(nonzero)\n        if len_ == 0:\n            return basic_info + ' flow: 0' \n        # Start of third line (flow rates)\n        flow_dim = _Q(0, flow_units).dimensionality\n        if fraction:\n            if flow_dim == mol_flow_dim:\n                flownet = _Q(self.molnet, units['molnet']).to(flow_units).magnitude\n                flow = 'molfrac'\n            elif flow_dim == mass_flow_dim:\n                flownet = _Q(self.massnet, units['massnet']).to(flow_units).magnitude\n                flow = 'massfrac'\n            elif flow_dim == vol_flow_dim:\n                flownet = _Q(self.volnet, units['volnet']).to(flow_units).magnitude\n                flow = 'volfrac'\n            else:\n                raise DimensionError(f\"dimensions for flow units must be in molar, mass or volumetric flow rates, not '{flow_dim}'\")\n            beginning = ' flow: '\n            end = f'\\n*{flownet:.3g} {flow_units} '\n        else:\n            beginning = f' flow ({flow_units}): '\n            end = ''\n            if flow_dim == mol_flow_dim:\n                flow = 'mol'\n            elif flow_dim == mass_flow_dim:\n                flow = 'mass'\n            elif flow_dim == vol_flow_dim:\n                flow = 'vol'\n            else:\n                raise DimensionError(f\"dimensions for flow units must be in molar, mass or volumetric flow rates, not '{flow_dim}'\")\n        # Remaining lines (all flow rates)\n        new_line_spaces = len(beginning) * ' '\n        if 'frac' in flow:\n            flow = getattr(self, flow)[nonzero]\n        else:\n            flow = _Q(getattr(self, flow)[nonzero], units[flow]).to(flow_units).magnitude\n        \n        flowrates = ''\n        lengths = [len(sp) for sp in species]\n        maxlen = max(lengths) + 1\n        _N = N - 1\n        for i in range(len_-1):\n            spaces = ' ' * (maxlen - lengths[i])\n            if i == _N:\n                flowrates += '...\\n' + new_line_spaces\n                break\n            flowrates += species[i] + spaces + f' {flow[i]:.3g}\\n' + new_line_spaces\n        spaces = ' ' * (maxlen - lengths[len_-1])\n        flowrates += species[len_-1] + spaces + f' {flow[len_-1]:.3g}'\n        return (basic_info \n              + beginning\n              + flowrates\n              + end.replace('*', new_line_spaces + 'net' + (maxlen-4)*' ' + '  '))\n\n    def show(self, T=None, P=None, flow=None, fraction=None, N=None):\n        \"\"\"Print all specifications.\n        \n        Parameters\n        ----------\n        T: str, optional\n            Temperature units.\n        P: str, optional\n            Pressure units.\n        flow: str, optional\n            Flow rate units.\n        fraction: bool, optional\n            Display flows as net flow rate and fractions (i.e composition).\n        N: int, optional\n            Number of compounds to display.\n        \n        Notes\n        -----\n        Default values are stored in `Stream.display_units`.\n        \n        \"\"\"\n        print(self._info(T, P, flow, fraction, N))\n    _ipython_display_ = show\n\n    def _disconnect(self):\n        outs = self._source and self._source._outs\n        if outs: outs[outs.index(self)] = MissingStream\n        ins = self._sink and self._sink._ins\n        if ins: ins[ins.index(self)] = MissingStream\n        self._source = self._sink = None\n\n    def __str__(self):\n        if self.ID: return self.ID\n        else: return type(self).__name__\n\n    def __repr__(self):\n        if self.ID: return f'<{type(self).__name__}: {self.ID}>'\n        else: return f'<{type(self).__name__}>'\n        \n        \nfrom . import _mixed_stream as MS", "meta": {"hexsha": "a65a33dc502de8924127e3df3672dc41e3db33ec", "size": 63087, "ext": "py", "lang": "Python", "max_stars_repo_path": "biosteam/_stream.py", "max_stars_repo_name": "lilanyu/biosteam", "max_stars_repo_head_hexsha": "b025bbe138bfd0b016af58583792fb4f3ff9186e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-17T13:14:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-17T13:14:19.000Z", "max_issues_repo_path": "build/lib/biosteam/_stream.py", "max_issues_repo_name": "lilanyu/biosteam", "max_issues_repo_head_hexsha": "b025bbe138bfd0b016af58583792fb4f3ff9186e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/lib/biosteam/_stream.py", "max_forks_repo_name": "lilanyu/biosteam", "max_forks_repo_head_hexsha": "b025bbe138bfd0b016af58583792fb4f3ff9186e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7905731119, "max_line_length": 318, "alphanum_fraction": 0.5177453358, "include": true, "reason": "import numpy", "num_tokens": 15639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.3593641588823761, "lm_q1q2_score": 0.19508560182982296}}
{"text": "\"\"\"solver.py\"\"\"\n\nimport os\nimport numpy.random as random\nfrom tqdm import tqdm\n\nimport torch\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nfrom utils import mkdirs, save_args_outputs\nfrom ops import recon_loss, ad_loss, kl_divergence, permute_dims\nfrom model import FactorVAE, Discriminator\nfrom dataset import return_data\nfrom disentanglement import disentanglement_score\nfrom gradcam import GradCAM\n\n\nclass Solver(object):\n    def __init__(self, args):\n        self.args = args\n\n        # Misc\n        use_cuda = args.cuda and torch.cuda.is_available()\n        self.device = 'cuda' if use_cuda else 'cpu'\n        self.name = args.name\n        self.max_iter = int(args.max_iter)\n        self.print_iter = args.print_iter\n        self.global_iter = 0\n        self.pbar = tqdm(total=self.max_iter)\n\n        # Data\n        assert args.dataset == 'dsprites', 'Only dSprites is implemented'\n        self.dset_dir = args.dset_dir\n        self.dataset = args.dataset\n        self.batch_size = args.batch_size\n        self.data_loader, self.dataset = return_data(args)\n\n        # Networks & Optimizers\n        self.z_dim = args.z_dim\n        self.gamma = args.gamma\n\n        self.lr_VAE = args.lr_VAE\n        self.beta1_VAE = args.beta1_VAE\n        self.beta2_VAE = args.beta2_VAE\n\n        self.lr_D = args.lr_D\n        self.beta1_D = args.beta1_D\n        self.beta2_D = args.beta2_D\n\n        # Disentanglement score\n        self.L = args.L\n        self.vote_count = args.vote_count\n        self.dis_score = args.dis_score\n        self.dis_batch_size = args.dis_batch_size\n\n        # Models and optimizers\n        self.VAE = FactorVAE(self.z_dim).to(self.device)\n        self.nc = 1\n\n        self.optim_VAE = optim.Adam(self.VAE.parameters(), lr=self.lr_VAE,\n                                    betas=(self.beta1_VAE, self.beta2_VAE))\n\n        self.D = Discriminator(self.z_dim).to(self.device)\n        self.optim_D = optim.Adam(self.D.parameters(), lr=self.lr_D,\n                                  betas=(self.beta1_D, self.beta2_D))\n\n        self.nets = [self.VAE, self.D]\n\n        # Attention Disentanglement loss\n        self.ad_loss = args.ad_loss\n        self.lamb = args.lamb\n        if self.ad_loss:\n            self.gcam = GradCAM(self.VAE.encode, args.target_layer, self.device, args.image_size)\n            self.pick2 = True\n\n        # Checkpoint\n        self.ckpt_dir = os.path.join(args.ckpt_dir, args.name+'_'+str(args.seed))\n        self.ckpt_save_iter = args.ckpt_save_iter\n        if self.max_iter >= args.ckpt_save_iter:\n            mkdirs(self.ckpt_dir)\n        if args.ckpt_load:\n            self.load_checkpoint(args.ckpt_load)\n\n        # Results\n        self.results_dir = os.path.join(args.results_dir, args.name+'_'+str(args.seed))\n        self.results_save = args.results_save\n\n        self.outputs = {'vae_recon_loss': [], 'vae_kld': [], 'vae_tc_loss': [], 'D_tc_loss': [], 'ad_loss': [], 'dis_score': [], 'iteration': []}\n\n    def train(self):\n        self.net_mode(train=True)\n\n        ones = torch.ones(self.batch_size, dtype=torch.long, device=self.device)\n        zeros = torch.zeros(self.batch_size, dtype=torch.long, device=self.device)\n\n        out = False\n        while not out:\n            for x_true1, x_true2 in self.data_loader:\n                self.global_iter += 1\n                self.pbar.update(1)\n\n                x_true1 = x_true1.to(self.device)\n                x_recon, mu, logvar, z = self.VAE(x_true1)\n                vae_recon_loss = recon_loss(x_true1, x_recon)\n                vae_ad_loss = self.get_ad_loss(z)\n                vae_kld = kl_divergence(mu, logvar)\n\n                D_z = self.D(z)\n                vae_tc_loss = (D_z[:, :1] - D_z[:, 1:]).mean()\n\n                vae_loss = vae_recon_loss + vae_kld + self.gamma*vae_tc_loss + self.lamb*vae_ad_loss\n\n                x_true2 = x_true2.to(self.device)\n                z_prime = self.VAE(x_true2, no_dec=True)\n                z_pperm = permute_dims(z_prime).detach()\n                D_z_pperm = self.D(z_pperm)\n                D_tc_loss = 0.5*(F.cross_entropy(D_z, zeros) + F.cross_entropy(D_z_pperm, ones))\n\n                self.optim_VAE.zero_grad()\n                vae_loss.backward(retain_graph=True)\n\n                self.optim_D.zero_grad()\n                D_tc_loss.backward()\n\n                self.optim_VAE.step()\n                self.optim_D.step()\n\n                if self.global_iter%self.print_iter == 0:\n                    if self.dis_score:\n                        dis_score = disentanglement_score(self.VAE.eval(), self.device, self.dataset, self.z_dim, self.L, self.vote_count, self.dis_batch_size)\n                        self.VAE.train()\n                    else:\n                        dis_score = torch.tensor(0)\n\n                    self.pbar.write('[{}] vae_recon_loss:{:.3f} vae_kld:{:.3f} vae_tc_loss:{:.3f} ad_loss:{:.3f} D_tc_loss:{:.3f} dis_score:{:.3f}'.format(\n                        self.global_iter, vae_recon_loss.item(), vae_kld.item(), vae_tc_loss.item(), vae_ad_loss.item(), D_tc_loss.item(), dis_score.item()))\n\n                    if self.results_save:\n                        self.outputs['vae_recon_loss'].append(vae_recon_loss.item())\n                        self.outputs['vae_kld'].append(vae_kld.item())\n                        self.outputs['vae_tc_loss'].append(vae_tc_loss.item())\n                        self.outputs['D_tc_loss'].append(D_tc_loss.item())\n                        self.outputs['ad_loss'].append(vae_ad_loss.item())\n                        self.outputs['dis_score'].append(dis_score.item())\n                        self.outputs['iteration'].append(self.global_iter)\n\n                if self.global_iter%self.ckpt_save_iter == 0:\n                    self.save_checkpoint(self.global_iter)\n\n                if self.global_iter >= self.max_iter:\n                    out = True\n                    break\n\n        self.pbar.write(\"[Training Finished]\")\n        self.pbar.close()\n\n        if self.results_save:\n            save_args_outputs(self.results_dir, self.args, self.outputs)\n\n    def get_ad_loss(self, z):\n        if not self.ad_loss:\n            return torch.tensor(0)\n\n        z_picked = z[:, random.randint(0, self.z_dim, size=2)]\n        M = self.gcam.generate(z_picked)\n\n        return ad_loss(M.flatten(1), self.batch_size, self.pick2)\n\n    def net_mode(self, train):\n        if not isinstance(train, bool):\n            raise ValueError('Only bool type is supported. True|False')\n\n        for net in self.nets:\n            if train:\n                net.train()\n            else:\n                net.eval()\n\n    def save_checkpoint(self, ckptname='last', verbose=True):\n        model_states = {'D':self.D.state_dict(),\n                        'VAE':self.VAE.state_dict()}\n        optim_states = {'optim_D':self.optim_D.state_dict(),\n                        'optim_VAE':self.optim_VAE.state_dict()}\n        states = {'iter':self.global_iter,\n                  'model_states':model_states,\n                  'optim_states':optim_states}\n\n        filepath = os.path.join(self.ckpt_dir, str(ckptname))\n        with open(filepath, 'wb+') as f:\n            torch.save(states, f)\n        if verbose:\n            self.pbar.write(\"=> saved checkpoint '{}' (iter {})\".format(filepath, self.global_iter))\n\n    def load_checkpoint(self, ckptname='last', verbose=True):\n        if ckptname == 'last':\n            ckpts = os.listdir(self.ckpt_dir)\n            if not ckpts:\n                if verbose:\n                    self.pbar.write(\"=> no checkpoint found\")\n                return\n\n            ckpts = [int(ckpt) for ckpt in ckpts]\n            ckpts.sort(reverse=True)\n            ckptname = str(ckpts[0])\n\n        filepath = os.path.join(self.ckpt_dir, ckptname)\n        if os.path.isfile(filepath):\n            with open(filepath, 'rb') as f:\n                checkpoint = torch.load(f)\n\n            self.global_iter = checkpoint['iter']\n            self.VAE.load_state_dict(checkpoint['model_states']['VAE'])\n            self.D.load_state_dict(checkpoint['model_states']['D'])\n            self.optim_VAE.load_state_dict(checkpoint['optim_states']['optim_VAE'])\n            self.optim_D.load_state_dict(checkpoint['optim_states']['optim_D'])\n            self.pbar.update(self.global_iter)\n            if verbose:\n                self.pbar.write(\"=> loaded checkpoint '{} (iter {})'\".format(filepath, self.global_iter))\n        else:\n            if verbose:\n                self.pbar.write(\"=> no checkpoint found at '{}'\".format(filepath))\n", "meta": {"hexsha": "ff93c9b349517ea282bc18643c73f1b829c18301", "size": 8523, "ext": "py", "lang": "Python", "max_stars_repo_path": "solver.py", "max_stars_repo_name": "FrankBrongers/FactorVAE", "max_stars_repo_head_hexsha": "a9e357ee7f38189507f5ab7389065f68a81b3ec5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "solver.py", "max_issues_repo_name": "FrankBrongers/FactorVAE", "max_issues_repo_head_hexsha": "a9e357ee7f38189507f5ab7389065f68a81b3ec5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-01-12T10:39:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-28T16:29:24.000Z", "max_forks_repo_path": "solver.py", "max_forks_repo_name": "FrankBrongers/FactorVAE", "max_forks_repo_head_hexsha": "a9e357ee7f38189507f5ab7389065f68a81b3ec5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2197309417, "max_line_length": 159, "alphanum_fraction": 0.5778481755, "include": true, "reason": "import numpy", "num_tokens": 1961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.542863297964157, "lm_q2_score": 0.3593641382989649, "lm_q1q2_score": 0.1950856012870235}}
{"text": "# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------------\n# Copyright (c) 2014, Nicolas P. Rougier\n# Distributed under the (new) BSD License.\n#\n# Contributors: Nicolas P. Rougier (Nicolas.Rougier@inria.fr)\n# -----------------------------------------------------------------------------\n# References:\n#\n# * Interaction between cognitive and motor cortico-basal ganglia loops during\n#   decision making: a computational study. M. Guthrie, A. Leblois, A. Garenne,\n#   and T. Boraud. Journal of Neurophysiology, 109:3025–3040, 2013.\n# -----------------------------------------------------------------------------\nimport numpy as np\nfrom model import *\nfrom display import *\n\n\ndef debug(time, cues, choice, reward):\n    n = len(cues)\n    cues = np.sort(cues)\n\n    R.append(reward)\n    if choice == cues[0]:\n        P.append(1)\n    else:\n        P.append(0)\n\n    print \"Choice:         \",\n    for i in range(n):\n        if choice == cues[i]:\n            print \"[%d]\" % cues[i],\n        else:\n            print \"%d\" % cues[i],\n        if i < (n-1):\n            print \"/\",\n    if choice == cues[0]:\n        print \" (good)\"\n    else:\n        print \" (bad)\"\n\n    print \"Reward (%3d%%) :   %d\" % (int(100*CUE[\"reward\"][choice]),reward)\n    print \"Mean performance: %.3f\" % np.array(P).mean()\n    print \"Mean reward:      %.3f\" % np.array(R).mean()\n    print \"Response time:    %d ms\" % (time)\n    print \"CTX.cog->CTX.ass:\", connections[\"CTX.cog -> CTX.ass\"].weights\n    print\n\n\nn_experiments = 250\nn_trials      = 150\n\nif 1:\n    for k in range(n_experiments):\n        reset()\n        learning = True\n        P,RT = [], []\n        connections[\"GPI.cog -> THL.cog\"].active = True\n        connections[\"GPI.mot -> THL.mot\"].active = True\n\n        for j in range(n_trials):\n            reset_activities()\n            # Settling phase (500ms)\n            for i in xrange(0,500):\n                iterate(dt)\n            # Trial setup\n            set_trial(n=2)\n            # Learning phase (2500ms)\n            for i in xrange(500,3000):\n                iterate(dt)\n                # Test if a decision has been made\n                if CTX.mot.delta > decision_threshold:\n                    RT.append(i-500)\n                    cues, choice, reward = process(n=2, learning=learning)\n                    cues = np.sort(cues)\n                    if choice == cues[0]:\n                        P.append(1)\n                    else:\n                        P.append(0)\n                    break\n\n            if j == 100:\n                print \"BG Performance:     %g\" % np.mean(P)\n                print \"BG RT:              %g (+/- %g)\"% (np.mean(RT), np.std(RT))\n                P,RT = [], []\n                # print \"-------------------------------------------------------\"\n                learning = False\n                connections[\"GPI.cog -> THL.cog\"].active = False\n                connections[\"GPI.mot -> THL.mot\"].active = False\n\n        print \"Cortex Performance: %g\" % np.mean(P)\n        print \"Cortex RT:          %g (+/- %g)\"% (np.mean(RT), np.std(RT))\n        print \"CTX.cog->CTX.ass:\", connections[\"CTX.cog -> CTX.ass\"].weights\n        print \"CUE['value']:    \", CUE[\"value\"]\n        print \"---\"\n", "meta": {"hexsha": "645bf6c145a2298176dcf48e7c242524c7d37eb0", "size": 3236, "ext": "py", "lang": "Python", "max_stars_repo_path": "basal-ganglia/topalidou-et-al-2014/cython/Guthrie_cortical.py", "max_stars_repo_name": "mtopalid/Neurosciences", "max_stars_repo_head_hexsha": "8531d59f8370f0cf7f1b4b1f72e4bf11b96e1354", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2015-01-24T01:14:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T06:50:46.000Z", "max_issues_repo_path": "basal-ganglia/topalidou-et-al-2014/cython/Guthrie_cortical.py", "max_issues_repo_name": "mtopalid/Neurosciences", "max_issues_repo_head_hexsha": "8531d59f8370f0cf7f1b4b1f72e4bf11b96e1354", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:44:27.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-24T15:44:27.000Z", "max_forks_repo_path": "basal-ganglia/topalidou-et-al-2014/cython/Guthrie_cortical.py", "max_forks_repo_name": "mtopalid/Neurosciences", "max_forks_repo_head_hexsha": "8531d59f8370f0cf7f1b4b1f72e4bf11b96e1354", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2015-10-05T23:02:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-31T23:46:14.000Z", "avg_line_length": 33.7083333333, "max_line_length": 82, "alphanum_fraction": 0.4502472188, "include": true, "reason": "import numpy", "num_tokens": 798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.19508559969609368}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nPhotosynthesis and Stomatal Conductance Model \nCreated 9/27/2016\nKatherine Wentz\n\nThis is a program that runs photosynthesis and\nstomatal conductance models given changes in leaf-\nlevel traits. \n\nThe end product is graphs of NUE vs. WUE.\n\n\nUpdate: I am going to run the model for plants with \ntraits that are distinctive of the meadow moisture \ngradient in the alpine tundra.\n\nFix: correct for atmospheric pressure differences in co2, o2, and vapor pressure\n\nFix: vcmax temp dependence (pg 63 in plant physiological ecology book)\n\nFix: NEW VARIBALE TRAIT-->make the fraction of leaf N in rubisco go down with increasing SLA,\nchlorophyll content, and decreasing light (wet meadow)--more N is allocated\nto thylakoids. The only way for chl/m2 to increase even when g N/m2 goes down\nor is constant is for the leaf to allocate more of leaf N to chl...also, note\nthat there is more organic N designated to photo in leaf when SLA goes up\nbecause less N is used in structure. see \"Photosynthesis or persistence: N allocation\nin leaves of evergreen and deciduous... by Takashima et al. 2004. Also see Photosynthetic\nnitrogen-use efficiency of species...by Poorter and Evans 1998\n\nNote to self: NUE and WUE relationship flipflops with change in air temperature;\nNUE makes sense because C:N decreases from dry to wet meadows; WUE increasing\nin snowbed does not necessarilly make sense--look in the literature for this\n\nherbs have a higher NUE\n\n\"\"\"\n\n#---------------Import Modules---------------#\n\nimport itertools as it\nimport numpy as np\nimport operator\nfrom matplotlib import pyplot as plt\nfrom matplotlib import rcParams\nfrom scipy.optimize import curve_fit\n\n#Import combinations of variable parameters \nfrom uncertain_params import monte_carlo_all\n\n#Import photosynthesis model\nfrom Photosynthesis_Model import photo_bound_meso_eqstom as photo\n\n#Import functions to switch between Pa and umol/mol at sea level\nfrom photo_functions import pa_con_atmfrac\n\n\n#for doing letters on graphs for multiple plots in same figure\ndef get_axis_limits(ax, scale1=.95,scale2=0.9):\n    return ax.get_xlim()[1]*scale1, ax.get_ylim()[1]*scale2\n\n\n#---------------Determine if I Want to Keep Any of the Variable Parameters Constant---------------#\n\nconst_params=[]\nfor xx in it.combinations(['ht','t'],0): #keep ht and t constant for constant vpd\n    const_params+=[xx]\n\n#do this when I do not put any of the variable parameters as constant. instead I \n#vary each parameter one at a time while keeping the other parameters constant.\nif const_params==[()]:\n    const_params=[[-999999]]   \n\n#---------------Begin Looping Through Photosynthesis Model---------------#\n\n#each loop is for a constant value, or combinatin of constant values, of variable parameter as determined above\nfor ii in range(len(const_params)):\n    \n    #---------------Initialize Plots---------------#\n\n    ##---Figure With Subplots Blueprint---##\n\n    #fb1=plt.figure(1,figsize=(12,2)) \n    #axA = fb1.add_subplot(121)\n    #axB = fb1.add_subplot(122)\n\n    ##---Figures Without Subplots Blueprint---##\n    \n    #--figure 1--#\n    \n    #simulated and empirical NUE in plant communities \n    fig1, (ax1A,ax1B) = plt.subplots(2,figsize=(9,20),sharex=True)   \n    ax1A.set_ylabel('NUE ($\\mu$mol CO$_2$/g N s)',fontsize=20, fontname='Times New Roman')\n    ax1A.set_ylim([0,5])\n#    ax1A.set_title('NUE in Plant Communities', fontname='Times New Roman',fontsize=30)\n    \n    ax1B.set_ylabel('NUE (g biomass/g N)',fontsize=20, fontname='Times New Roman')\n    ax1B.set_ylim([60,100])\n\n\n     #-----figure 2----#\n    \n    #simulated and empirical WUE in plant communities\n    fig2,(ax2A,ax2B,ax2C) = plt.subplots(3,figsize=(9,20),sharex=True,sharey=True) \n    ax2B.set_ylabel('WUE ($\\mu$mol CO$_2$/mmol H$_2$O)',fontsize=20, fontname='Times New Roman')\n    ax2A.set_ylim([0,5])\n#    ax2A.set_title('WUE in Plant Communities', fontname='Times New Roman',fontsize=30)\n   \n\n    #--figure 3--#\n    \n    #simulated and empirical Assimilation in plant communities \n    fig3, (ax3A,ax3B) = plt.subplots(2,figsize=(9,20),sharex=True)   \n    ax3A.set_ylabel('Assimilation ($\\mu$mol CO$_2$/m$^2$s)',fontsize=20, fontname='Times New Roman')\n    ax3A.set_ylim([0,30])\n#    ax3A.set_title('Assimilation in Plant Communities', fontname='Times New Roman',fontsize=30)\n    \n    ax3B.set_ylabel('Growth Rate (g C/m$^2$ day)',fontsize=20, fontname='Times New Roman')\n    ax3B.set_ylim([0,5])\n\n\n    #--figure 4--#\n    \n    #leaf height vs. temperature\n    fig4,ax4 = plt.subplots(figsize=(11,11))\n    ax4.set_xlabel('Leaf Height (cm)',fontsize=25, fontname='Times New Roman')\n    ax4.set_ylabel('Difference Between Leaf and Air Temperature ($^\\circ$C)',fontsize=25, fontname='Times New Roman')\n#    ax4.set_title('Leaf Height vs. Leaf & Air Temperature Difference', fontname='Times New Roman',fontsize=30)\n\n\n    #-----figure 5----#\n\n    #assimilation vs. stomatal conductance\n    fig5,ax5 = plt.subplots(figsize=(11,11))\n\n    ax5.set_xlabel('Assimilation ($\\mu$mol CO$_2$/m$^2$s)',fontsize=25, fontname='Times New Roman')\n    ax5.set_ylabel('Stomatal Conductance (mol CO$_2$/m$^2$s)',fontsize=25, fontname='Times New Roman')\n#    ax5.set_title('Simulated Assimilation vs. Stomatal Conductance', fontname='Times New Roman',fontsize=30)\n    ax5.set_ylim([0,0.55])\n    ax5.set_xlim([0,25])\n  \n    \n    #--figure 6--#\n    \n    #vpd vs. wue\n    fig6, (ax6A,ax6B) = plt.subplots(2,figsize=(9,20),sharex=False)   \n #   ax6A.set_xlabel('VPD (cmol H$_2$O/mol air)',fontsize=25, fontname='Times New Roman')\n    ax6A.set_ylabel('WUE ($\\mu$mol CO$_2$/mmol H$_2$O)',fontsize=20, fontname='Times New Roman')\n#    ax6A.set_title('Vapor Pressure Deficit vs. WUE', fontname='Times New Roman',fontsize=30)\n    ax6B.set_xlabel('VPD (cmol H$_2$O/mol air)',fontsize=20, fontname='Times New Roman')\n    ax6B.set_ylabel('WUE ($\\mu$mol CO$_2$/mmol H$_2$O)',fontsize=20, fontname='Times New Roman')\n    \n    \n\n\n\n\n    #---------------Initialize Arrays for Each Meadow---------------#\n        \n    #total nue and wue\n    nue_tot=[]\n    wue_tot=[]\n   \n    #wue and nue arrays\n    wue_d=[]\n    nue_d=[]\n    wue_d_const=[]\n    \n    wue_m_const=[]\n\n    wue_w=[]\n    wue_w_const=[]\n    nue_w=[]    \n     \n\n    \n    \n    #gsw arrays\n\n    gsw_d=[]\n    gsw_d_tms=[]        \n    gsw_m=[]\n    gsw_m_tms=[]\n    gsw_w=[]\n    gsw_w_tms=[]\n    \n    gs_d=[]\n    gs_m=[]\n    gs_w=[]    \n    #assimilation arrays\n\n    A_d=[]\n    A_d_tms=[]\n    A_m=[]\n    A_m_tms=[]\n    A_w=[]\n    A_w_tms=[]\n\n    #evapo arrays\n\n    E_d=[]\n    E_d_tms=[]        \n    E_m=[]\n    E_m_tms=[]\n    E_w=[]\n    E_w_tms=[]  \n    \n    #vapor pressure deficit arrays\n    vpd_d=[]\n    vpd_d_tms=[]\n    vpd_m=[]\n    vpd_m_tms=[]\n    vpd_w=[]\n    vpd_w_tms=[]    \n\n\n    #leaf temp\n    tl_d=[]\n    tl_m=[]\n    tl_w=[]\n\n\n\n\n    #---------------Photosynthesis + Stomatal Conductance Model---------------#\n\n    \n    ##---Constant Parameter Arrays for Model---##\n\n    #----Params Used in Model Currently----#\n      \n    tk_25=298.16; #absolute temperature at 25 C\n    ekc=80500.0 #Activation energy for K of CO2 (J mol-1)\n    eko=14500.0 #Activation energy for K of O2 (J mol-1)\n    etau=-29000.0  #Activation energy for tau (???) (J mol-1)\n    ev=55000.0 #Activation energy for carboxylation (J mol-1)\n    ej=55000.0 #Activation energy for electron transport (J mol-1)\n    toptv=303.0 #Optimum temperature for maximum carboxylation (K)\n    toptj=303.0 #Optimum temperature for maximum electron transport (K)\n    ra=np.zeros(shape=1)+20.7 #specific rubisco activity (umol CO2/g Rub s)\n    flnr=np.zeros(shape=1)+0.1 #fraction of leaf nitrogen in rubisco (g N Rub/g N leaf)\n    frnr=np.zeros(shape=1)+6.25 #weight fraction of nitrogen in rubisco molecule (g Rub/g N Rub) \n    rh=np.zeros(shape=1)+0.5 #relative humidity (kPa/kPa)\n    ca=np.zeros(shape=1)+405 #ambient carbon dioxide (umol CO2/mol air)\n    ko25=np.zeros(shape=1)+30000 #Michaelis-Menten kinetic coefficient for oxygen at 25 C(Pa) \n    kc25=np.zeros(shape=1)+30 #Michaelis-Menten kinetic coefficient for carbon dioxide at 25 C (Pa)\n    o=np.zeros(shape=1)+210000 #concentration of ambient oxygen (umol/mol)\n    g0=np.zeros(shape=1)+0.002 #Ball-Berry stomatal conductance intercept parameter (mol H2O/m2s)\n    a=np.zeros(shape=1)+1.6 #Conversion Coefficient between stomatal conductance to water and carbon dioxide (unitless)\n    ij=np.zeros(shape=1)+1.0 #leaf angle index--downregulates jmax\n    m=np.zeros(shape=1)+9.0 #ball-berry parameter (unitless)\n    b=1.37 #Conversion Coefficient between boundary layer conductance to water and carbon dioxide \n    u=5.0 #windspeed (m/s)\n    qeff=0.32 #leaf quantum yield, electrons\n    PAR=2000 #photosynthetic active radiation (umol/m2s)\n    jm=2.68 #slope coefficient \n    vwc_min=0.08 #minimum soil water content for photosynthesis to occur (permanent wilting point) (cm3/cm3) \n    vwc_max=0.68 #maximum soil water content where increases in soil water do not affect photosynthesis (field capacity?) (cm3/cm3)\n    q=0.2 #parameter for soil water affect on photosynthesis (unitless)\n   \n    \n    #------constant variable params for sensitivty analysis-----#\n    \n    chl_c=np.zeros(shape=1)+(np.mean([396,465,476])) #Chlorophyll Content of the Leaf (umol chl/m2)\n    ht_c=np.zeros(shape=1)+10.0 #Temperature of the Leaf (K)\n    dia_c=np.zeros(shape=1)+(np.mean([1.4,2.3,2.6])/100.) #Mean diameter or size of leaf (m)\n    na_c=np.zeros(shape=1)+(np.mean([2.5,5.6,6.3])) #leaf nitrogen (g N/ m2)\n    t_c=np.zeros(shape=1)+15.0 #temp (C)\n    \n\n#---------------Import Variable Parameter Arrays from Leaf Parameter File---------------#\n    params=monte_carlo_all()        \n    \n    for xx in range(len(params)):\n        for yy in range(len(params[xx])):\n            for key,val in params[xx][yy].items():\n                exec(key + '=val')\n        \n        \n            #set variable parameters constant if I specify this above\n            if 'na' in const_params[ii]:\n                na=na_c\n            if 'dia' in const_params[ii]:\n                dia=dia_c\n            if 'chl' in const_params[ii]:\n                chl=chl_c\n            if 'ht' in const_params[ii]:\n                ht=ht_c\n            if 't' in const_params[ii]:\n                temp=t_c\n    \n                \n            \n            \n            #------calculate vapor pressure-----#\n            pa_v=611*np.exp((17.27*temp)/(temp+237.3)) #saturation vapor pressure of air (Pa)\n            ea_str=pa_con_atmfrac(pa_v,3528) #saturation vapor pressure of air (Pa-->umol h20/mol air)\n            ea=rh*ea_str #vapor pressure (umol h2O/mol air)                \n    \n    \n            #correct for leaf temperatures using leaf height\n       \n            t_diff=18-0.4*ht\n        \n            tl=temp+t_diff\n    \n            \n\n            \n            if xx==0: \n    \n                z=0.2\n                #---------------Photosynthesis Function---------------#\n            \n                #alter this line of code for when implementing different photosynthesis functions\n                wue, nue, A, E, cs, ci, gsw, gs, gbw, gb, gm, cc,dd =photo(tk_25,ekc,eko,etau,ev,ej,toptv,toptj,na, qeff, PAR,tl,ea,chl,ij,kc25,ko25,o,ca,rh,m,a,frnr,flnr,ra,jm,g0,b,dia,u,q,vwc_min,vwc_max,vwc,z)\n     \n           \n                if isinstance(wue, np.ndarray):\n                    wue=wue[0]\n        \n                if isinstance(nue, np.ndarray):\n                    nue=nue[0]\n            \n                if isinstance(A, np.ndarray):\n                    A=A[0]        \n\n                if isinstance(gs, np.ndarray):\n                    gs=gs[0]      \n\n                if isinstance(gsw, np.ndarray):\n                    gsw=gsw[0]   \n\n                if isinstance(E, np.ndarray):\n                    E=E[0]   \n\n                if isinstance(dd, np.ndarray):\n                    dd=dd[0] \n            \n                if isinstance(wue, list):\n                    wue=wue[0]\n            \n                if isinstance(nue, list):\n                    nue=nue[0]\n            \n                if isinstance(A, list):\n                    A=A[0]      \n\n                if isinstance(gs, list):\n                    gs=gs[0]                     \n\n                if isinstance(gsw, list):\n                    gsw=gsw[0]     \n                    \n                if isinstance(E, list):\n                    E=E[0]                         \n                    \n                if isinstance(dd, list):\n                    dd=dd[0]  \n                    \n                wue_d+=[wue]\n                nue_d+=[nue]\n                gsw_d+=[gsw]\n                A_d+=[A]\n                E_d+=[E]\n                vpd_d+=[dd]\n                tl_d+=[tl]\n                gs_d+=[gs]\n\n                    \n\n            elif xx==1:\n                \n                z=0.4\n                #---------------Photosynthesis Function---------------#\n            \n                #alter this line of code for when implementing different photosynthesis functions\n                wue, nue, A, E, cs, ci, gsw, gs, gbw, gb, gm, cc,dd =photo(tk_25,ekc,eko,etau,ev,ej,toptv,toptj,na, qeff, PAR,tl,ea,chl,ij,kc25,ko25,o,ca,rh,m,a,frnr,flnr,ra,jm,g0,b,dia,u,q,vwc_min,vwc_max,vwc,z)\n     \n                if isinstance(wue, np.ndarray):\n                    wue=wue[0]\n        \n                if isinstance(nue, np.ndarray):\n                    nue=nue[0]\n            \n                if isinstance(A, np.ndarray):\n                    A=A[0]        \n\n                if isinstance(gs, np.ndarray):\n                    gs=gs[0]      \n\n                if isinstance(gsw, np.ndarray):\n                    gsw=gsw[0]   \n\n                if isinstance(E, np.ndarray):\n                    E=E[0]   \n\n                if isinstance(dd, np.ndarray):\n                    dd=dd[0] \n            \n                if isinstance(wue, list):\n                    wue=wue[0]\n            \n                if isinstance(nue, list):\n                    nue=nue[0]\n            \n                if isinstance(A, list):\n                    A=A[0]      \n\n                if isinstance(gs, list):\n                    gs=gs[0]                     \n\n                if isinstance(gsw, list):\n                    gsw=gsw[0]     \n                    \n                if isinstance(E, list):\n                    E=E[0]                         \n                    \n                if isinstance(dd, list):\n                    dd=dd[0] \n                    \n                wue_m+=[wue]\n\n                \n     \n            \n            elif xx==2:\n                \n                z=0.4\n                #---------------Photosynthesis Function---------------#\n            \n                #alter this line of code for when implementing different photosynthesis functions\n                wue, nue, A, E, cs, ci, gsw, gs, gbw, gb, gm, cc,dd =photo(tk_25,ekc,eko,etau,ev,ej,toptv,toptj,na, qeff, PAR,tl,ea,chl,ij,kc25,ko25,o,ca,rh,m,a,frnr,flnr,ra,jm,g0,b,dia,u,q,vwc_min,vwc_max,vwc,z)\n     \n                if isinstance(wue, np.ndarray):\n                    wue=wue[0]\n        \n                if isinstance(nue, np.ndarray):\n                    nue=nue[0]\n            \n                if isinstance(A, np.ndarray):\n                    A=A[0]        \n\n                if isinstance(gs, np.ndarray):\n                    gs=gs[0]      \n\n                if isinstance(gsw, np.ndarray):\n                    gsw=gsw[0]   \n\n                if isinstance(E, np.ndarray):\n                    E=E[0]   \n\n                if isinstance(dd, np.ndarray):\n                    dd=dd[0] \n            \n                if isinstance(wue, list):\n                    wue=wue[0]\n            \n                if isinstance(nue, list):\n                    nue=nue[0]\n            \n                if isinstance(A, list):\n                    A=A[0]      \n\n                if isinstance(gs, list):\n                    gs=gs[0]                     \n\n                if isinstance(gsw, list):\n                    gsw=gsw[0]     \n                    \n                if isinstance(E, list):\n                    E=E[0]                         \n                    \n                if isinstance(dd, list):\n                    dd=dd[0] \n                    \n                wue_w+=[wue]\n                nue_w+=[nue]\n                gsw_w+=[gsw]\n                A_w+=[A]\n                E_w+=[E]\n                vpd_w+=[dd]\n                tl_w+=[tl]\n                gs_w+=[gs]\n                \n\n\n\n\n#---------------Constant WUE---------------#\n    params=monte_carlo_all()        \n    \n    for xx in range(len(params)):\n        for yy in range(len(params[xx])):\n            for key,val in params[xx][yy].items():\n                exec(key + '=val')\n        \n        \n           \n            ht=ht_c\n\n            temp=t_c\n\n                \n            \n            \n            #------calculate vapor pressure-----#\n            pa_v=611*np.exp((17.27*temp)/(temp+237.3)) #saturation vapor pressure of air (Pa)\n            ea_str=pa_con_atmfrac(pa_v,3528) #saturation vapor pressure of air (Pa-->umol h20/mol air)\n            ea=rh*ea_str #vapor pressure (umol h2O/mol air)                \n    \n    \n            #correct for leaf temperatures using leaf height\n       \n            t_diff=18-0.4*ht\n        \n            tl=temp+t_diff\n    \n            \n\n            \n            if xx==0: \n    \n                z=0.2\n                #---------------Photosynthesis Function---------------#\n            \n                #alter this line of code for when implementing different photosynthesis functions\n                wue, nue, A, E, cs, ci, gsw, gs, gbw, gb, gm, cc,dd =photo(tk_25,ekc,eko,etau,ev,ej,toptv,toptj,na, qeff, PAR,tl,ea,chl,ij,kc25,ko25,o,ca,rh,m,a,frnr,flnr,ra,jm,g0,b,dia,u,q,vwc_min,vwc_max,vwc,z)\n     \n           \n                if isinstance(wue, np.ndarray):\n                    wue=wue[0]\n        \n                if isinstance(nue, np.ndarray):\n                    nue=nue[0]\n            \n                if isinstance(A, np.ndarray):\n                    A=A[0]        \n\n                if isinstance(gs, np.ndarray):\n                    gs=gs[0]      \n\n                if isinstance(gsw, np.ndarray):\n                    gsw=gsw[0]   \n\n                if isinstance(E, np.ndarray):\n                    E=E[0]   \n\n                if isinstance(dd, np.ndarray):\n                    dd=dd[0] \n            \n                if isinstance(wue, list):\n                    wue=wue[0]\n            \n                if isinstance(nue, list):\n                    nue=nue[0]\n            \n                if isinstance(A, list):\n                    A=A[0]      \n\n                if isinstance(gs, list):\n                    gs=gs[0]                     \n\n                if isinstance(gsw, list):\n                    gsw=gsw[0]     \n                    \n                if isinstance(E, list):\n                    E=E[0]                         \n                    \n                if isinstance(dd, list):\n                    dd=dd[0]  \n                    \n                wue_d_const+=[wue]\n                \n            if xx==1: \n    \n                z=0.2\n                #---------------Photosynthesis Function---------------#\n            \n                #alter this line of code for when implementing different photosynthesis functions\n                wue, nue, A, E, cs, ci, gsw, gs, gbw, gb, gm, cc,dd =photo(tk_25,ekc,eko,etau,ev,ej,toptv,toptj,na, qeff, PAR,tl,ea,chl,ij,kc25,ko25,o,ca,rh,m,a,frnr,flnr,ra,jm,g0,b,dia,u,q,vwc_min,vwc_max,vwc,z)\n     \n           \n                if isinstance(wue, np.ndarray):\n                    wue=wue[0]\n        \n                if isinstance(nue, np.ndarray):\n                    nue=nue[0]\n            \n                if isinstance(A, np.ndarray):\n                    A=A[0]        \n\n                if isinstance(gs, np.ndarray):\n                    gs=gs[0]      \n\n                if isinstance(gsw, np.ndarray):\n                    gsw=gsw[0]   \n\n                if isinstance(E, np.ndarray):\n                    E=E[0]   \n\n                if isinstance(dd, np.ndarray):\n                    dd=dd[0] \n            \n                if isinstance(wue, list):\n                    wue=wue[0]\n            \n                if isinstance(nue, list):\n                    nue=nue[0]\n            \n                if isinstance(A, list):\n                    A=A[0]      \n\n                if isinstance(gs, list):\n                    gs=gs[0]                     \n\n                if isinstance(gsw, list):\n                    gsw=gsw[0]     \n                    \n                if isinstance(E, list):\n                    E=E[0]                         \n                    \n                if isinstance(dd, list):\n                    dd=dd[0]  \n                    \n                wue_m_const+=[wue]\n    \n            \n            elif xx==2:\n                \n                z=0.4\n                #---------------Photosynthesis Function---------------#\n            \n                #alter this line of code for when implementing different photosynthesis functions\n                wue, nue, A, E, cs, ci, gsw, gs, gbw, gb, gm, cc,dd =photo(tk_25,ekc,eko,etau,ev,ej,toptv,toptj,na, qeff, PAR,tl,ea,chl,ij,kc25,ko25,o,ca,rh,m,a,frnr,flnr,ra,jm,g0,b,dia,u,q,vwc_min,vwc_max,vwc,z)\n     \n                if isinstance(wue, np.ndarray):\n                    wue=wue[0]\n        \n                if isinstance(nue, np.ndarray):\n                    nue=nue[0]\n            \n                if isinstance(A, np.ndarray):\n                    A=A[0]        \n\n                if isinstance(gs, np.ndarray):\n                    gs=gs[0]      \n\n                if isinstance(gsw, np.ndarray):\n                    gsw=gsw[0]   \n\n                if isinstance(E, np.ndarray):\n                    E=E[0]   \n\n                if isinstance(dd, np.ndarray):\n                    dd=dd[0] \n            \n                if isinstance(wue, list):\n                    wue=wue[0]\n            \n                if isinstance(nue, list):\n                    nue=nue[0]\n            \n                if isinstance(A, list):\n                    A=A[0]      \n\n                if isinstance(gs, list):\n                    gs=gs[0]                     \n\n                if isinstance(gsw, list):\n                    gsw=gsw[0]     \n                    \n                if isinstance(E, list):\n                    E=E[0]                         \n                    \n                if isinstance(dd, list):\n                    dd=dd[0] \n                    \n                wue_w_const+=[wue]\n\n\n    \n#---------------Figure 1: Plant Communities vs. NUE ---------------#      \n\n\n    #model simulations\n\n    nue_bp=ax1A.boxplot([nue_d,nue_w], patch_artist=True, showmeans=True, showfliers=False)\n\n    ax1A.set_xticks([1.0,2.0])\n    ax1A.set_xticklabels(['Dry Meadow','Wet Meadow'],fontname='Times New Roman',fontsize=20)\n\n    for box in nue_bp['boxes']:\n        #change outline color\n        box.set(color='black',linewidth=2)\n        #change fill color\n        box.set(facecolor='black',alpha=0.2)\n\n    for whisker in nue_bp['whiskers']:\n        whisker.set(color='black',linewidth=2)\n    \n    for cap in nue_bp['caps']:\n        cap.set(color='black',linewidth=2)\n\n    for median in nue_bp['medians']:\n        median.set(color='black', linewidth=2)\n\n    for flier in nue_bp['fliers']:\n        flier.set(marker='*',color='black',alpha=0.5)\n\n    for means in nue_bp['means']:\n        means.set(marker='o',markerfacecolor='black')    \n\n    ax1A.annotate('A', xy=get_axis_limits(ax1A,scale1=0.95,scale2=0.88),fontsize=20,fontname=\"Times New Roman\")\n\n    #model validation\n    \n    ax1B.bar(ax1A.get_xticks(),[72,88], yerr=[2.08,3.81], edgecolor='black', align=\"center\",width=0.2, color='black',alpha=0.5,error_kw={'ecolor':'black', 'lw':2, 'capsize':5, 'capthick':2})\n    ax1B.text(0.97,76,\"a\",fontsize=20)\n    ax1B.text(1.98,93.5,\"b\",fontsize=20)\n    ax1B.annotate('B', xy=get_axis_limits(ax1B,scale2=0.95),fontsize=20,fontname=\"Times New Roman\")  \n    ax1B.set_xticklabels(['Dry Meadow','Wet Meadow'],fontname='Times New Roman',fontsize=25)\n\n\n\n#---------------Figure 2: Plant Communities vs. WUE ---------------#      \n\n    #model simulations\n\n    wue_bp=ax2A.boxplot([wue_d,wue_w], patch_artist=True, showmeans=True, showfliers=False)\n\n    ax2A.set_xticks([1.0,2.0])\n    ax2A.set_xticklabels(['Dry Meadow','Moist Meadow'],fontname='Times New Roman',fontsize=25)\n\n    for box in wue_bp['boxes']:\n        #change outline color\n        box.set(color='black',linewidth=2)\n        #change fill color\n        box.set(facecolor='black',alpha=0.2)\n\n    for whisker in wue_bp['whiskers']:\n        whisker.set(color='black',linewidth=2)\n    \n    for cap in wue_bp['caps']:\n        cap.set(color='black',linewidth=2)\n\n    for median in wue_bp['medians']:\n        median.set(color='black', linewidth=2)\n\n    for flier in wue_bp['fliers']:\n        flier.set(marker='*',color='black',alpha=0.5)\n\n    for means in wue_bp['means']:\n        means.set(marker='o',markerfacecolor='black')    \n\n    ax2A.annotate('A', xy=get_axis_limits(ax2A,scale1=0.95,scale2=0.85),fontsize=20,fontname=\"Times New Roman\")\n\n    #model validation\n        \n    ax2B.bar([1.0,2.0],[1.49,1.57], yerr=[0.06,0.04], edgecolor='black', align=\"center\",width=0.2, color='black',alpha=0.5,error_kw={'ecolor':'black', 'lw':2, 'capsize':5, 'capthick':2})    \n    ax2B.text(0.97,2,\"a\",fontsize=20)\n    ax2B.text(1.98,2,\"a\",fontsize=20)\n    ax2B.annotate('B', xy=get_axis_limits(ax2B,scale1=0.95,scale2=0.85),fontsize=20,fontname=\"Times New Roman\")  \n    ax2B.set_xticklabels(['Dry Meadow','Moist Meadow'],fontname='Times New Roman',fontsize=20)\n\n\n    #model simulations when temp and leaf height are constant\n    wue_bp_2=ax2C.boxplot([wue_d_const,wue_m_const], patch_artist=True, showmeans=True, showfliers=False)\n\n    ax2C.set_xticks([1.0,2.0])\n    ax2C.set_xticklabels(['Dry Meadow','Moist Meadow'],fontname='Times New Roman',fontsize=30)\n\n    for box in wue_bp_2['boxes']:\n        #change outline color\n        box.set(color='black',linewidth=2)\n        #change fill color\n        box.set(facecolor='black',alpha=0.2)\n\n    for whisker in wue_bp_2['whiskers']:\n        whisker.set(color='black',linewidth=2)\n    \n    for cap in wue_bp_2['caps']:\n        cap.set(color='black',linewidth=2)\n\n    for median in wue_bp_2['medians']:\n        median.set(color='black', linewidth=2)\n\n    for flier in wue_bp_2['fliers']:\n        flier.set(marker='*',color='black',alpha=0.5)\n\n    for means in wue_bp_2['means']:\n        means.set(marker='o',markerfacecolor='black')    \n\n    ax2C.annotate('C', xy=get_axis_limits(ax2C,scale1=0.95,scale2=0.85),fontsize=20,fontname=\"Times New Roman\")\n           \n\n#---------------Figure 3: Plant Communities vs. Assimilation--------------- #     \n\n    A_bp=ax3A.boxplot([A_d,A_w], patch_artist=True, showmeans=True, showfliers=False)\n\n    ax3A.set_xticks([1.0,2.0])\n    ax3A.set_xticklabels(['Dry Meadow','Wet Meadow'],fontname='Times New Roman')\n\n    \n    #A boxplot specs\n    for box in A_bp['boxes']:\n        #change outline color\n        box.set(color='black',linewidth=2)\n        #change fill color\n        box.set(facecolor='black',alpha=0.2)\n\n    for whisker in A_bp['whiskers']:\n        whisker.set(color='black',linewidth=2)\n    \n    for cap in A_bp['caps']:\n        cap.set(color='black',linewidth=2)\n\n    for median in A_bp['medians']:\n        median.set(color='black', linewidth=2)\n\n    for flier in A_bp['fliers']:\n        flier.set(marker='*',color='black',alpha=0.5)\n\n    for means in A_bp['means']:\n        means.set(marker='o',markerfacecolor='black')  \n        \n    ax3A.annotate('A', xy=get_axis_limits(ax3A),fontsize=20,fontname=\"Times New Roman\")\n        \n      \n    ax3B.bar([1.0,2.0],[0.91,1.92], yerr=[0.44, 0.81], edgecolor='black', align=\"center\",width=0.2, color='black',alpha=0.5,error_kw={'ecolor':'black', 'lw':2, 'capsize':5, 'capthick':2})\n    ax3B.text(0.97,1.6,\"a\",fontsize=20)\n    ax3B.text(1.98,3.0,\"b\",fontsize=20)\n    ax3B.annotate('B', xy=get_axis_limits(ax3B),fontsize=20,fontname=\"Times New Roman\")  \n    ax3B.set_xticklabels(['Dry Meadow','Wet Meadow'],fontname='Times New Roman',fontsize=30)\n\n\n\n#---------------Figure 4: leaf height vs. air temperature plot        \n    ax4.scatter([25,25,25,9,9,5,5,5,5,3,3,3,3,10,10,10,2],[3.6,5.8,12.5,17.2,20.8,13.1,7.2,5.8,11.2,14.,17.7,15.5,24.,14.5,6.3,24.,30.],edgecolors=\"black\",facecolors=\"black\",marker='o',s=30)\n    ax4.plot(np.unique([25,25,25,9,9,5,5,5,5,3,3,3,3,10,10,10,2]), np.poly1d(np.polyfit([25,25,25,9,9,5,5,5,5,3,3,3,3,10,10,10,2], [3.6,5.8,12.5,17.2,20.8,13.1,7.2,5.8,11.2,14.,17.7,15.5,24.,14.5,6.3,24.,30.], 1))(np.unique([25,25,25,9,9,5,5,5,5,3,3,3,3,10,10,10,2])),color=\"black\",linewidth=3)\n\n\n    \n\n#---------------Figure 5: Regression Plot Assimilation vs. Stomatal Conductance---------------#   \n    ax5.scatter(A_d+A_w,gs_d+gs_w,edgecolors='black',facecolors='black',marker='o',s=30)\n    ax5.plot(np.unique(A_d+A_w), np.poly1d(np.polyfit(A_d+A_w, gs_d+gs_w, 1))(np.unique(A_d+A_w)),color='black',linewidth=3)\n\n\n    \n#---------------Figure 6: Plot VPD vs. WUE for validation (use all points rather than mean of points)-------------#\n    def func(x, a, b, c):\n        return a * np.exp(-b * x) + c\n    xdata=np.array(vpd_d+vpd_w)/10000.\n    ydata=np.array(wue_d+wue_w)\n    L=sorted(zip(xdata,ydata),key=operator.itemgetter(0))\n    new_x,new_y=zip(*L)\n    popt, pcov = curve_fit(func, np.array(new_x), np.array(new_y))\n    \n    ax6B.plot(np.array(new_x), func(np.array(new_x), *popt), 'k-', linewidth=3,label='Model Simulation')\n    ax6B.scatter(xdata,ydata,edgecolors='black',facecolors='black',marker='o',s=30)\n    ax6B.annotate('B', xy=get_axis_limits(ax6B),fontsize=20,fontname=\"Times New Roman\")\n\n\n\n    def func(x, a, b, c):\n        return a * np.exp(-b * x) + c\n    xdata=np.array([13734.61196533664,13734.61196533664,13734.61196533664,13734.61196533664,21364.95194607922,21364.95194607922,21364.95194607922,21364.95194607922,28995.2919268218,28995.2919268218,28995.2919268218,28995.2919268218,13734.61196533664,13734.61196533664,13734.61196533664,13734.61196533664,21364.95194607922,21364.95194607922,21364.95194607922,21364.95194607922,28995.2919268218,28995.2919268218,28995.2919268218,28995.2919268218])/10000.\n    ydata=np.array([11,12,11,3,5,4.5,1,5,4,2,1,.5,9,9,10,11,5,5,5,5,5,5,5,2])*.4091\n    L=sorted(zip(xdata,ydata),key=operator.itemgetter(0))\n    new_x,new_y=zip(*L)\n    popt, pcov = curve_fit(func, np.array(new_x), np.array(new_y))\n    \n    ax6A.plot(np.array(new_x), func(np.array(new_x), *popt), 'k-', linewidth=3,label='fit')\n    ax6A.scatter(xdata,ydata,edgecolors=\"black\",facecolors=\"black\",marker='o',s=30,label='Empirical Data')\n    ax6A.annotate('A', xy=get_axis_limits(ax6A),fontsize=20,fontname=\"Times New Roman\")\n    \n\n    \n#-----------FINALIZE PLOT------#\n\n\n    figs=[fig1,fig2,fig3,fig4,fig5,fig6]\n    axes=[ax1A,ax2A,ax3A,ax1B,ax2B,ax3B,ax2C,ax4,ax5,ax6A,ax6B]\n    \n    for i in range(len(axes)):\n        axes[i].tick_params(axis='y', labelsize=15)\n        axes[i].tick_params(axis='x', labelsize=15)\n        for tick in axes[i].get_xticklabels():\n            tick.set_fontname(\"Times New Roman\")\n        for tick in axes[i].get_yticklabels():\n            tick.set_fontname(\"Times New Roman\")\n\n\n    ax1B.set_xticklabels(['Dry Meadow','Wet Meadow'],fontname='Times New Roman',fontsize=20)\n    ax2C.set_xticklabels(['Dry Meadow','Moist Meadow'],fontname='Times New Roman',fontsize=20)\n    ax3B.set_xticklabels(['Dry Meadow','Wet Meadow'],fontname='Times New Roman',fontsize=20)\n\n        \n#    for i in range(len(figs)):        \n#        figs[i].tight_layout()\n\n#---------------Finalize Figure---------------#    \n\n    ##---Save Figure--##\n    fig1.savefig('NUE_val.png') \n    fig2.savefig('WUE_val.png')\n    fig3.savefig('Assimilation_val.png')\n    fig4.savefig('Leaf_Ht_Temp.png')\n    fig5.savefig('Assimilation_vs_Conductance.png')\n    fig6.savefig('VPD_vs_WUE.png')\n\n", "meta": {"hexsha": "d991d975d7672c85ad7cf3d44ee8df87a65df924", "size": 31924, "ext": "py", "lang": "Python", "max_stars_repo_path": "Trait_Based_Photo_Model_InterSpecificVariation.py", "max_stars_repo_name": "kwentz10/Photosynthesis_Optimization_Modeling", "max_stars_repo_head_hexsha": "864c174ae4298bfdabee36fd0305c6a3649c38bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Trait_Based_Photo_Model_InterSpecificVariation.py", "max_issues_repo_name": "kwentz10/Photosynthesis_Optimization_Modeling", "max_issues_repo_head_hexsha": "864c174ae4298bfdabee36fd0305c6a3649c38bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Trait_Based_Photo_Model_InterSpecificVariation.py", "max_forks_repo_name": "kwentz10/Photosynthesis_Optimization_Modeling", "max_forks_repo_head_hexsha": "864c174ae4298bfdabee36fd0305c6a3649c38bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9660460022, "max_line_length": 452, "alphanum_fraction": 0.5358977572, "include": true, "reason": "import numpy,from scipy", "num_tokens": 8832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.19508559969609368}}
{"text": "import numpy as np\nimport pandas as pd\n\nfrom pvlib.tools import cosd, sind, tand\nfrom pvlib.pvsystem import _combine_localized_attributes\nfrom pvlib.pvsystem import PVSystem\nfrom pvlib.location import Location\nfrom pvlib import irradiance, atmosphere\nfrom pvlib._deprecation import deprecated\n\n\nclass SingleAxisTracker(PVSystem):\n    \"\"\"\n    A class for single-axis trackers that inherits the PV modeling methods from\n    :py:class:`~pvlib.pvsystem.PVSystem`. For details on calculating tracker\n    rotation see :py:func:`pvlib.tracking.singleaxis`.\n\n    Parameters\n    ----------\n    axis_tilt : float, default 0\n        The tilt of the axis of rotation (i.e, the y-axis defined by\n        axis_azimuth) with respect to horizontal, in decimal degrees.\n\n    axis_azimuth : float, default 0\n        A value denoting the compass direction along which the axis of\n        rotation lies. Measured in decimal degrees east of north.\n\n    max_angle : float, default 90\n        A value denoting the maximum rotation angle, in decimal degrees,\n        of the one-axis tracker from its horizontal position (horizontal\n        if axis_tilt = 0). A max_angle of 90 degrees allows the tracker\n        to rotate to a vertical position to point the panel towards a\n        horizon. max_angle of 180 degrees allows for full rotation.\n\n    backtrack : bool, default True\n        Controls whether the tracker has the capability to \"backtrack\"\n        to avoid row-to-row shading. False denotes no backtrack\n        capability. True denotes backtrack capability.\n\n    gcr : float, default 2.0/7.0\n        A value denoting the ground coverage ratio of a tracker system\n        which utilizes backtracking; i.e. the ratio between the PV array\n        surface area to total ground area. A tracker system with modules\n        2 meters wide, centered on the tracking axis, with 6 meters\n        between the tracking axes has a gcr of 2/6=0.333. If gcr is not\n        provided, a gcr of 2/7 is default. gcr must be <=1.\n\n    cross_axis_tilt : float, default 0.0\n        The angle, relative to horizontal, of the line formed by the\n        intersection between the slope containing the tracker axes and a plane\n        perpendicular to the tracker axes. Cross-axis tilt should be specified\n        using a right-handed convention. For example, trackers with axis\n        azimuth of 180 degrees (heading south) will have a negative cross-axis\n        tilt if the tracker axes plane slopes down to the east and positive\n        cross-axis tilt if the tracker axes plane slopes up to the east. Use\n        :func:`~pvlib.tracking.calc_cross_axis_tilt` to calculate\n        `cross_axis_tilt`. [degrees]\n\n    **kwargs\n        Passed to :py:class:`~pvlib.pvsystem.PVSystem`.\n\n    See also\n    --------\n    pvlib.tracking.singleaxis\n    pvlib.tracking.calc_axis_tilt\n    pvlib.tracking.calc_cross_axis_tilt\n    \"\"\"\n\n    def __init__(self, axis_tilt=0, axis_azimuth=0, max_angle=90,\n                 backtrack=True, gcr=2.0/7.0, cross_axis_tilt=0.0, **kwargs):\n\n        self.axis_tilt = axis_tilt\n        self.axis_azimuth = axis_azimuth\n        self.max_angle = max_angle\n        self.backtrack = backtrack\n        self.gcr = gcr\n        self.cross_axis_tilt = cross_axis_tilt\n\n        kwargs['surface_tilt'] = None\n        kwargs['surface_azimuth'] = None\n\n        super().__init__(**kwargs)\n\n    def __repr__(self):\n        attrs = ['axis_tilt', 'axis_azimuth', 'max_angle', 'backtrack', 'gcr',\n                 'cross_axis_tilt']\n        sat_repr = ('SingleAxisTracker:\\n  ' + '\\n  '.join(\n            f'{attr}: {getattr(self, attr)}' for attr in attrs))\n        # get the parent PVSystem info\n        pvsystem_repr = super().__repr__()\n        # remove the first line (contains 'PVSystem: \\n')\n        pvsystem_repr = '\\n'.join(pvsystem_repr.split('\\n')[1:])\n        return sat_repr + '\\n' + pvsystem_repr\n\n    def singleaxis(self, apparent_zenith, apparent_azimuth):\n        \"\"\"\n        Get tracking data. See :py:func:`pvlib.tracking.singleaxis` more\n        detail.\n\n        Parameters\n        ----------\n        apparent_zenith : float, 1d array, or Series\n            Solar apparent zenith angles in decimal degrees.\n\n        apparent_azimuth : float, 1d array, or Series\n            Solar apparent azimuth angles in decimal degrees.\n\n        Returns\n        -------\n        tracking data\n        \"\"\"\n        tracking_data = singleaxis(apparent_zenith, apparent_azimuth,\n                                   self.axis_tilt, self.axis_azimuth,\n                                   self.max_angle, self.backtrack,\n                                   self.gcr, self.cross_axis_tilt)\n\n        return tracking_data\n\n    @deprecated('0.8',\n                alternative='SingleAxisTracker, Location, and ModelChain',\n                name='SingleAxisTracker.localize', removal='0.9')\n    def localize(self, location=None, latitude=None, longitude=None,\n                 **kwargs):\n        \"\"\"\n        Creates a :py:class:`LocalizedSingleAxisTracker` object using\n        this object and location data. Must supply either location\n        object or latitude, longitude, and any location kwargs\n\n        Parameters\n        ----------\n        location : None or Location, default None\n        latitude : None or float, default None\n        longitude : None or float, default None\n        **kwargs : see Location\n\n        Returns\n        -------\n        localized_system : LocalizedSingleAxisTracker\n        \"\"\"\n\n        if location is None:\n            location = Location(latitude, longitude, **kwargs)\n\n        return LocalizedSingleAxisTracker(pvsystem=self, location=location)\n\n    def get_aoi(self, surface_tilt, surface_azimuth, solar_zenith,\n                solar_azimuth):\n        \"\"\"Get the angle of incidence on the system.\n\n        For a given set of solar zenith and azimuth angles, the\n        surface tilt and azimuth parameters are typically determined\n        by :py:method:`~SingleAxisTracker.singleaxis`. The\n        :py:method:`~SingleAxisTracker.singleaxis` method also returns\n        the angle of incidence, so this method is only needed\n        if using a different tracking algorithm.\n\n        Parameters\n        ----------\n        surface_tilt : numeric\n            Panel tilt from horizontal.\n        surface_azimuth : numeric\n            Panel azimuth from north\n        solar_zenith : float or Series.\n            Solar zenith angle.\n        solar_azimuth : float or Series.\n            Solar azimuth angle.\n\n        Returns\n        -------\n        aoi : Series\n            The angle of incidence in degrees from normal.\n        \"\"\"\n\n        aoi = irradiance.aoi(surface_tilt, surface_azimuth,\n                             solar_zenith, solar_azimuth)\n        return aoi\n\n    def get_irradiance(self, surface_tilt, surface_azimuth,\n                       solar_zenith, solar_azimuth, dni, ghi, dhi,\n                       dni_extra=None, airmass=None, model='haydavies',\n                       **kwargs):\n        \"\"\"\n        Uses the :func:`irradiance.get_total_irradiance` function to\n        calculate the plane of array irradiance components on a tilted\n        surface defined by the input data and ``self.albedo``.\n\n        For a given set of solar zenith and azimuth angles, the\n        surface tilt and azimuth parameters are typically determined\n        by :py:meth:`~SingleAxisTracker.singleaxis`.\n\n        Parameters\n        ----------\n        surface_tilt : numeric\n            Panel tilt from horizontal.\n        surface_azimuth : numeric\n            Panel azimuth from north\n        solar_zenith : numeric\n            Solar zenith angle.\n        solar_azimuth : numeric\n            Solar azimuth angle.\n        dni : float or Series\n            Direct Normal Irradiance\n        ghi : float or Series\n            Global horizontal irradiance\n        dhi : float or Series\n            Diffuse horizontal irradiance\n        dni_extra : float or Series, default None\n            Extraterrestrial direct normal irradiance\n        airmass : float or Series, default None\n            Airmass\n        model : String, default 'haydavies'\n            Irradiance model.\n\n        **kwargs\n            Passed to :func:`irradiance.get_total_irradiance`.\n\n        Returns\n        -------\n        poa_irradiance : DataFrame\n            Column names are: ``total, beam, sky, ground``.\n        \"\"\"\n\n        # not needed for all models, but this is easier\n        if dni_extra is None:\n            dni_extra = irradiance.get_extra_radiation(solar_zenith.index)\n\n        if airmass is None:\n            airmass = atmosphere.get_relative_airmass(solar_zenith)\n\n        return irradiance.get_total_irradiance(surface_tilt,\n                                               surface_azimuth,\n                                               solar_zenith,\n                                               solar_azimuth,\n                                               dni, ghi, dhi,\n                                               dni_extra=dni_extra,\n                                               airmass=airmass,\n                                               model=model,\n                                               albedo=self.albedo,\n                                               **kwargs)\n\n\n@deprecated('0.8', alternative='SingleAxisTracker, Location, and ModelChain',\n            name='LocalizedSingleAxisTracker', removal='0.9')\nclass LocalizedSingleAxisTracker(SingleAxisTracker, Location):\n    \"\"\"\n    The :py:class:`~pvlib.tracking.LocalizedSingleAxisTracker` class defines a\n    standard set of installed PV system attributes and modeling functions. This\n    class combines the attributes and methods of the\n    :py:class:`~pvlib.tracking.SingleAxisTracker` (a subclass of\n    :py:class:`~pvlib.pvsystem.PVSystem`) and\n    :py:class:`~pvlib.location.Location` classes.\n\n    The :py:class:`~pvlib.tracking.LocalizedSingleAxisTracker` may have bugs\n    due to the difficulty of robustly implementing multiple inheritance. See\n    :py:class:`~pvlib.modelchain.ModelChain` for an alternative paradigm\n    for modeling PV systems at specific locations.\n    \"\"\"\n\n    def __init__(self, pvsystem=None, location=None, **kwargs):\n\n        new_kwargs = _combine_localized_attributes(\n            pvsystem=pvsystem,\n            location=location,\n            **kwargs,\n        )\n\n        SingleAxisTracker.__init__(self, **new_kwargs)\n        Location.__init__(self, **new_kwargs)\n\n    def __repr__(self):\n        attrs = ['latitude', 'longitude', 'altitude', 'tz']\n        return ('Localized' +\n                super().__repr__() + '\\n  ' +\n                '\\n  '.join(\n                    f'{attr}: {getattr(self, attr)}' for attr in attrs))\n\n\ndef singleaxis(apparent_zenith, apparent_azimuth,\n               axis_tilt=0, axis_azimuth=0, max_angle=90,\n               backtrack=True, gcr=2.0/7.0, cross_axis_tilt=0):\n    \"\"\"\n    Determine the rotation angle of a single-axis tracker when given particular\n    solar zenith and azimuth angles.\n\n    See [1]_ for details about the equations. Backtracking may be specified,\n    and if so, a ground coverage ratio is required.\n\n    Rotation angle is determined in a right-handed coordinate system. The\n    tracker `axis_azimuth` defines the positive y-axis, the positive x-axis is\n    90 degrees clockwise from the y-axis and parallel to the Earth's surface,\n    and the positive z-axis is normal to both x & y-axes and oriented skyward.\n    Rotation angle `tracker_theta` is a right-handed rotation around the y-axis\n    in the x, y, z coordinate system and indicates tracker position relative to\n    horizontal. For example, if tracker `axis_azimuth` is 180 (oriented south)\n    and `axis_tilt` is zero, then a `tracker_theta` of zero is horizontal, a\n    `tracker_theta` of 30 degrees is a rotation of 30 degrees towards the west,\n    and a `tracker_theta` of -90 degrees is a rotation to the vertical plane\n    facing east.\n\n    Parameters\n    ----------\n    apparent_zenith : float, 1d array, or Series\n        Solar apparent zenith angles in decimal degrees.\n\n    apparent_azimuth : float, 1d array, or Series\n        Solar apparent azimuth angles in decimal degrees.\n\n    axis_tilt : float, default 0\n        The tilt of the axis of rotation (i.e, the y-axis defined by\n        axis_azimuth) with respect to horizontal, in decimal degrees.\n\n    axis_azimuth : float, default 0\n        A value denoting the compass direction along which the axis of\n        rotation lies. Measured in decimal degrees east of north.\n\n    max_angle : float, default 90\n        A value denoting the maximum rotation angle, in decimal degrees,\n        of the one-axis tracker from its horizontal position (horizontal\n        if axis_tilt = 0). A max_angle of 90 degrees allows the tracker\n        to rotate to a vertical position to point the panel towards a\n        horizon. max_angle of 180 degrees allows for full rotation.\n\n    backtrack : bool, default True\n        Controls whether the tracker has the capability to \"backtrack\"\n        to avoid row-to-row shading. False denotes no backtrack\n        capability. True denotes backtrack capability.\n\n    gcr : float, default 2.0/7.0\n        A value denoting the ground coverage ratio of a tracker system\n        which utilizes backtracking; i.e. the ratio between the PV array\n        surface area to total ground area. A tracker system with modules\n        2 meters wide, centered on the tracking axis, with 6 meters\n        between the tracking axes has a gcr of 2/6=0.333. If gcr is not\n        provided, a gcr of 2/7 is default. gcr must be <=1.\n\n    cross_axis_tilt : float, default 0.0\n        The angle, relative to horizontal, of the line formed by the\n        intersection between the slope containing the tracker axes and a plane\n        perpendicular to the tracker axes. Cross-axis tilt should be specified\n        using a right-handed convention. For example, trackers with axis\n        azimuth of 180 degrees (heading south) will have a negative cross-axis\n        tilt if the tracker axes plane slopes down to the east and positive\n        cross-axis tilt if the tracker axes plane slopes up to the east. Use\n        :func:`~pvlib.tracking.calc_cross_axis_tilt` to calculate\n        `cross_axis_tilt`. [degrees]\n\n    Returns\n    -------\n    dict or DataFrame with the following columns:\n        * `tracker_theta`: The rotation angle of the tracker.\n          tracker_theta = 0 is horizontal, and positive rotation angles are\n          clockwise. [degrees]\n        * `aoi`: The angle-of-incidence of direct irradiance onto the\n          rotated panel surface. [degrees]\n        * `surface_tilt`: The angle between the panel surface and the earth\n          surface, accounting for panel rotation. [degrees]\n        * `surface_azimuth`: The azimuth of the rotated panel, determined by\n          projecting the vector normal to the panel's surface to the earth's\n          surface. [degrees]\n\n    See also\n    --------\n    pvlib.tracking.calc_axis_tilt\n    pvlib.tracking.calc_cross_axis_tilt\n\n    References\n    ----------\n    .. [1] Kevin Anderson and Mark Mikofski, \"Slope-Aware Backtracking for\n       Single-Axis Trackers\", Technical Report NREL/TP-5K00-76626, July 2020.\n       https://www.nrel.gov/docs/fy20osti/76626.pdf\n    \"\"\"\n\n    # MATLAB to Python conversion by\n    # Will Holmgren (@wholmgren), U. Arizona. March, 2015.\n\n    if isinstance(apparent_zenith, pd.Series):\n        index = apparent_zenith.index\n    else:\n        index = None\n\n    # convert scalars to arrays\n    apparent_azimuth = np.atleast_1d(apparent_azimuth)\n    apparent_zenith = np.atleast_1d(apparent_zenith)\n\n    if apparent_azimuth.ndim > 1 or apparent_zenith.ndim > 1:\n        raise ValueError('Input dimensions must not exceed 1')\n\n    # Calculate sun position x, y, z using coordinate system as in [1], Eq 1.\n\n    # NOTE: solar elevation = 90 - solar zenith, then use trig identities:\n    # sin(90-x) = cos(x) & cos(90-x) = sin(x)\n    sin_zenith = sind(apparent_zenith)\n    x = sin_zenith * sind(apparent_azimuth)\n    y = sin_zenith * cosd(apparent_azimuth)\n    z = cosd(apparent_zenith)\n\n    # Assume the tracker reference frame is right-handed. Positive y-axis is\n    # oriented along tracking axis; from north, the y-axis is rotated clockwise\n    # by the axis azimuth and tilted from horizontal by the axis tilt. The\n    # positive x-axis is 90 deg clockwise from the y-axis and parallel to\n    # horizontal (e.g., if the y-axis is south, the x-axis is west); the\n    # positive z-axis is normal to the x and y axes, pointed upward.\n\n    # Calculate sun position (xp, yp, zp) in tracker coordinate system using\n    # [1] Eq 4.\n\n    cos_axis_azimuth = cosd(axis_azimuth)\n    sin_axis_azimuth = sind(axis_azimuth)\n    cos_axis_tilt = cosd(axis_tilt)\n    sin_axis_tilt = sind(axis_tilt)\n    xp = x*cos_axis_azimuth - y*sin_axis_azimuth\n    yp = (x*cos_axis_tilt*sin_axis_azimuth\n          + y*cos_axis_tilt*cos_axis_azimuth\n          - z*sin_axis_tilt)\n    zp = (x*sin_axis_tilt*sin_axis_azimuth\n          + y*sin_axis_tilt*cos_axis_azimuth\n          + z*cos_axis_tilt)\n\n    # The ideal tracking angle wid is the rotation to place the sun position\n    # vector (xp, yp, zp) in the (y, z) plane, which is normal to the panel and\n    # contains the axis of rotation.  wid = 0 indicates that the panel is\n    # horizontal. Here, our convention is that a clockwise rotation is\n    # positive, to view rotation angles in the same frame of reference as\n    # azimuth. For example, for a system with tracking axis oriented south, a\n    # rotation toward the east is negative, and a rotation to the west is\n    # positive. This is a right-handed rotation around the tracker y-axis.\n\n    # Calculate angle from x-y plane to projection of sun vector onto x-z plane\n    # using [1] Eq. 5.\n\n    wid = np.degrees(np.arctan2(xp, zp))\n\n    # filter for sun above panel horizon\n    zen_gt_90 = apparent_zenith > 90\n    wid[zen_gt_90] = np.nan\n\n    # Account for backtracking\n    if backtrack:\n        # distance between rows in terms of rack lengths relative to cross-axis\n        # tilt\n        axes_distance = 1/(gcr * cosd(cross_axis_tilt))\n\n        # NOTE: account for rare angles below array, see GH 824\n        temp = np.abs(axes_distance * cosd(wid - cross_axis_tilt))\n\n        # backtrack angle using [1], Eq. 14\n        with np.errstate(invalid='ignore'):\n            wc = np.degrees(-np.sign(wid)*np.arccos(temp))\n\n        # NOTE: in the middle of the day, arccos(temp) is out of range because\n        # there's no row-to-row shade to avoid, & backtracking is unnecessary\n        # [1], Eqs. 15-16\n        with np.errstate(invalid='ignore'):\n            tracker_theta = wid + np.where(temp < 1, wc, 0)\n    else:\n        tracker_theta = wid\n\n    # NOTE: max_angle defined relative to zero-point rotation, not the\n    # system-plane normal\n    tracker_theta = np.clip(tracker_theta, -max_angle, max_angle)\n\n    # Calculate panel normal vector in panel-oriented x, y, z coordinates.\n    # y-axis is axis of tracker rotation. tracker_theta is a compass angle\n    # (clockwise is positive) rather than a trigonometric angle.\n    # NOTE: the *0 is a trick to preserve NaN values.\n    panel_norm = np.array([sind(tracker_theta),\n                           tracker_theta*0,\n                           cosd(tracker_theta)])\n\n    # sun position in vector format in panel-oriented x, y, z coordinates\n    sun_vec = np.array([xp, yp, zp])\n\n    # calculate angle-of-incidence on panel\n    aoi = np.degrees(np.arccos(np.abs(np.sum(sun_vec*panel_norm, axis=0))))\n\n    # Calculate panel tilt and azimuth in a coordinate system where the panel\n    # tilt is the angle from horizontal, and the panel azimuth is the compass\n    # angle (clockwise from north) to the projection of the panel's normal to\n    # the earth's surface. These outputs are provided for convenience and\n    # comparison with other PV software which use these angle conventions.\n\n    # Project normal vector to earth surface. First rotate about x-axis by\n    # angle -axis_tilt so that y-axis is also parallel to earth surface, then\n    # project.\n\n    # Calculate standard rotation matrix\n    rot_x = np.array([[1, 0, 0],\n                      [0, cosd(-axis_tilt), -sind(-axis_tilt)],\n                      [0, sind(-axis_tilt), cosd(-axis_tilt)]])\n\n    # panel_norm_earth contains the normal vector expressed in earth-surface\n    # coordinates (z normal to surface, y aligned with tracker axis parallel to\n    # earth)\n    panel_norm_earth = np.dot(rot_x, panel_norm).T\n\n    # projection to plane tangent to earth surface, in earth surface\n    # coordinates\n    projected_normal = np.array([panel_norm_earth[:, 0],\n                                 panel_norm_earth[:, 1],\n                                 panel_norm_earth[:, 2]*0]).T\n\n    # calculate vector magnitudes\n    projected_normal_mag = np.sqrt(np.nansum(projected_normal**2, axis=1))\n\n    # renormalize the projected vector, avoid creating nan values.\n    non_zeros = projected_normal_mag != 0\n    projected_normal[non_zeros] = (projected_normal[non_zeros].T /\n                                   projected_normal_mag[non_zeros]).T\n\n    # calculation of surface_azimuth\n    surface_azimuth = \\\n        np.degrees(np.arctan2(projected_normal[:, 1], projected_normal[:, 0]))\n\n    # Rotate 0 reference from panel's x-axis to its y-axis and then back to\n    # north.\n    surface_azimuth = 90 - surface_azimuth + axis_azimuth\n\n    # Map azimuth into [0,360) domain.\n    with np.errstate(invalid='ignore'):\n        surface_azimuth = surface_azimuth % 360\n\n    # Calculate surface_tilt\n    dotproduct = (panel_norm_earth * projected_normal).sum(axis=1)\n    surface_tilt = 90 - np.degrees(np.arccos(dotproduct))\n\n    # Bundle DataFrame for return values and filter for sun below horizon.\n    out = {'tracker_theta': tracker_theta, 'aoi': aoi,\n           'surface_tilt': surface_tilt, 'surface_azimuth': surface_azimuth}\n    if index is not None:\n        out = pd.DataFrame(out, index=index)\n        out = out[['tracker_theta', 'aoi', 'surface_azimuth', 'surface_tilt']]\n        out[zen_gt_90] = np.nan\n    else:\n        out = {k: np.where(zen_gt_90, np.nan, v) for k, v in out.items()}\n\n    return out\n\n\ndef calc_axis_tilt(slope_azimuth, slope_tilt, axis_azimuth):\n    \"\"\"\n    Calculate tracker axis tilt in the global reference frame when on a sloped\n    plane.\n\n    Parameters\n    ----------\n    slope_azimuth : float\n        direction of normal to slope on horizontal [degrees]\n    slope_tilt : float\n        tilt of normal to slope relative to vertical [degrees]\n    axis_azimuth : float\n        direction of tracker axes on horizontal [degrees]\n\n    Returns\n    -------\n    axis_tilt : float\n        tilt of tracker [degrees]\n\n    See also\n    --------\n    pvlib.tracking.singleaxis\n    pvlib.tracking.calc_cross_axis_tilt\n\n    Notes\n    -----\n    See [1]_ for derivation of equations.\n\n    References\n    ----------\n    .. [1] Kevin Anderson and Mark Mikofski, \"Slope-Aware Backtracking for\n       Single-Axis Trackers\", Technical Report NREL/TP-5K00-76626, July 2020.\n       https://www.nrel.gov/docs/fy20osti/76626.pdf\n    \"\"\"\n    delta_gamma = axis_azimuth - slope_azimuth\n    # equations 18-19\n    tan_axis_tilt = cosd(delta_gamma) * tand(slope_tilt)\n    return np.degrees(np.arctan(tan_axis_tilt))\n\n\ndef _calc_tracker_norm(ba, bg, dg):\n    \"\"\"\n    Calculate tracker normal, v, cross product of tracker axis and unit normal,\n    N, to the system slope plane.\n\n    Parameters\n    ----------\n    ba : float\n        axis tilt [degrees]\n    bg : float\n        ground tilt [degrees]\n    dg : float\n        delta gamma, difference between axis and ground azimuths [degrees]\n\n    Returns\n    -------\n    vector : tuple\n        vx, vy, vz\n    \"\"\"\n    cos_ba = cosd(ba)\n    cos_bg = cosd(bg)\n    sin_bg = sind(bg)\n    sin_dg = sind(dg)\n    vx = sin_dg * cos_ba * cos_bg\n    vy = sind(ba)*sin_bg + cosd(dg)*cos_ba*cos_bg\n    vz = -sin_dg*sin_bg*cos_ba\n    return vx, vy, vz\n\n\ndef _calc_beta_c(v, dg, ba):\n    \"\"\"\n    Calculate the cross-axis tilt angle.\n\n    Parameters\n    ----------\n    v : tuple\n        tracker normal\n    dg : float\n        delta gamma, difference between axis and ground azimuths [degrees]\n    ba : float\n        axis tilt [degrees]\n\n    Returns\n    -------\n    beta_c : float\n        cross-axis tilt angle [radians]\n    \"\"\"\n    vnorm = np.sqrt(np.dot(v, v))\n    beta_c = np.arcsin(\n        ((v[0]*cosd(dg) - v[1]*sind(dg)) * sind(ba) + v[2]*cosd(ba)) / vnorm)\n    return beta_c\n\n\ndef calc_cross_axis_tilt(\n        slope_azimuth, slope_tilt, axis_azimuth, axis_tilt):\n    \"\"\"\n    Calculate the angle, relative to horizontal, of the line formed by the\n    intersection between the slope containing the tracker axes and a plane\n    perpendicular to the tracker axes.\n\n    Use the cross-axis tilt to avoid row-to-row shade when backtracking on a\n    slope not parallel with the axis azimuth. Cross-axis tilt should be\n    specified using a right-handed convention. For example, trackers with axis\n    azimuth of 180 degrees (heading south) will have a negative cross-axis tilt\n    if the tracker axes plane slopes down to the east and positive cross-axis\n    tilt if the tracker axes plane slopes up to the east.\n\n    Parameters\n    ----------\n    slope_azimuth : float\n        direction of the normal to the slope containing the tracker axes, when\n        projected on the horizontal [degrees]\n    slope_tilt : float\n        angle of the slope containing the tracker axes, relative to horizontal\n        [degrees]\n    axis_azimuth : float\n        direction of tracker axes projected on the horizontal [degrees]\n    axis_tilt : float\n        tilt of trackers relative to horizontal [degrees]\n\n    Returns\n    -------\n    cross_axis_tilt : float\n        angle, relative to horizontal, of the line formed by the intersection\n        between the slope containing the tracker axes and a plane perpendicular\n        to the tracker axes [degrees]\n\n    See also\n    --------\n    pvlib.tracking.singleaxis\n    pvlib.tracking.calc_axis_tilt\n\n    Notes\n    -----\n    See [1]_ for derivation of equations.\n\n    References\n    ----------\n    .. [1] Kevin Anderson and Mark Mikofski, \"Slope-Aware Backtracking for\n       Single-Axis Trackers\", Technical Report NREL/TP-5K00-76626, July 2020.\n       https://www.nrel.gov/docs/fy20osti/76626.pdf\n    \"\"\"\n    # delta-gamma, difference between axis and slope azimuths\n    delta_gamma = axis_azimuth - slope_azimuth\n    # equation 22\n    v = _calc_tracker_norm(axis_tilt, slope_tilt, delta_gamma)\n    # equation 26\n    beta_c = _calc_beta_c(v, delta_gamma, axis_tilt)\n    return np.degrees(beta_c)\n", "meta": {"hexsha": "5397055935a6a51d1ec458c553341690ee1441bb", "size": 26706, "ext": "py", "lang": "Python", "max_stars_repo_path": "pvlib/tracking.py", "max_stars_repo_name": "veronicaguo/pvlib-python", "max_stars_repo_head_hexsha": "04a523fafbd61bc2e49420963b84ed8e2bd1b3cf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pvlib/tracking.py", "max_issues_repo_name": "veronicaguo/pvlib-python", "max_issues_repo_head_hexsha": "04a523fafbd61bc2e49420963b84ed8e2bd1b3cf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pvlib/tracking.py", "max_forks_repo_name": "veronicaguo/pvlib-python", "max_forks_repo_head_hexsha": "04a523fafbd61bc2e49420963b84ed8e2bd1b3cf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8168604651, "max_line_length": 79, "alphanum_fraction": 0.6488429566, "include": true, "reason": "import numpy", "num_tokens": 6313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3593641382989649, "lm_q1q2_score": 0.19508559597143432}}
{"text": "# FIXME: make pylint happy !\n#pylint: disable=all\n\nfrom sympy.utilities.codegen import CodeGen, CodeGenError, ResultBase, Result, InputArgument, InOutArgument, OutputArgument\nfrom sympy.core import Symbol, S, Expr, Tuple, Equality, Function, sympify\nfrom sympy.core.compatibility import is_sequence, StringIO, string_types\nfrom sympy.printing.codeprinter import AssignmentError\nfrom sympy.core.sympify import _sympify, sympify\n\nfrom sympy.tensor import Idx, Indexed, IndexedBase\nfrom sympy.matrices import (MatrixSymbol, ImmutableMatrix, MatrixBase,\n                            MatrixExpr, MatrixSlice)\nfrom sympy.core.basic import Basic\n\ndefault_settings = {'export': True}\n\nfrom .ast import For, If\nfrom .printing.cython import cython_code, CythonCodePrinter\nfrom .printing.numpy import numpy_code, NumpyCodePrinter\nfrom .printing.loopy import loopy_code, LoopyCodePrinter\n\nclass Routine(object):\n    \"\"\"Generic description of evaluation routine for set of expressions.\n\n    A CodeGen class can translate instances of this class into code in a\n    particular language.  The routine specification covers all the features\n    present in these languages.  The CodeGen part must raise an exception\n    when certain features are not present in the target language.  For\n    example, multiple return values are possible in Python, but not in C or\n    Fortran.  Another example: Fortran and Python support complex numbers,\n    while C does not.\n\n    \"\"\"\n\n    def __init__(self, name, arguments, instructions, idx_vars, local_vars, settings={}):\n        \"\"\"Initialize a Routine instance.\n\n        Parameters\n        ==========\n\n        name : string\n            Name of the routine.\n\n        arguments : list of Arguments\n            These are things that appear in arguments of a routine, often\n            appearing on the right-hand side of a function call.  These are\n            commonly InputArguments but in some languages, they can also be\n            OutputArguments or InOutArguments (e.g., pass-by-reference in C\n            code).\n\n        instructions : list\n            Instructions of the routine.\n\n        local_vars : list of Symbols\n            These are used internally by the routine.\n\n        global_vars : list of Symbols\n            Variables which will not be passed into the function.\n\n        \"\"\"\n\n        # extract all input symbols and all symbols appearing in an expression\n        input_symbols = set([])\n        symbols = set([])\n        for arg in arguments:\n            if isinstance(arg, OutputArgument):\n                symbols.update(arg.expr.free_symbols)\n            elif isinstance(arg, InputArgument):\n                input_symbols.add(arg.name)\n            elif isinstance(arg, InOutArgument):\n                input_symbols.add(arg.name)\n                symbols.update(arg.expr.free_symbols)\n            else:\n                raise ValueError(\"Unknown Routine argument: %s\" % arg)\n\n        for i in instructions:\n            symbols.update(i.free_symbols)\n\n        symbols = set([s.label if isinstance(s, Idx) else s for s in symbols])\n\n        # Check that all symbols in the expressions are covered by\n        # InputArguments/InOutArguments---subset because user could\n        # specify additional (unused) InputArguments or local_vars.\n        dummy = [i.label for i in idx_vars]\n        symbol_indexed_local = set()\n        for l in local_vars:\n            for ll in l.atoms(IndexedBase):\n                symbol_indexed_local.update(ll.atoms(Symbol) - ll.shape.atoms(Symbol))\n\n        notcovered = symbols.difference(\n            input_symbols.union(dummy).union(local_vars).union(symbol_indexed_local))\n        if notcovered != set([]):\n            raise ValueError(\"Symbols needed for output are not in input \" +\n                             \", \".join([str(x) for x in notcovered]))\n\n        self.name = name\n        self.arguments = arguments\n        self.instructions = instructions\n        self.idx_vars = idx_vars\n        self.local_vars = local_vars\n        self.settings = settings\n\n    def __str__(self):\n        return self.__class__.__name__ + \"({name!r}, {arguments}, {instructions}, {idx_vars}, {local_vars})\".format(**self.__dict__)\n\n    __repr__ = __str__\n\n    @property\n    def variables(self):\n        \"\"\"Returns a set of all variables possibly used in the routine.\n\n        For routines with unnamed return values, the dummies that may or\n        may not be used will be included in the set.\n\n        \"\"\"\n        v = set(self.local_vars)\n        for arg in self.arguments:\n            v.add(arg.name)\n        for res in self.results:\n            v.add(res.result_var)\n        return v\n\n\ndef get_dims_and_symbol(expr):\n    if isinstance(expr, Indexed):\n        dims = tuple([ (S.Zero, dim - 1) for dim in expr.shape])\n        symbol = expr.base.label\n    elif isinstance(expr, Symbol):\n        dims = []\n        symbol = expr\n    elif isinstance(expr, MatrixSymbol):\n        dims = tuple([ (S.Zero, dim - 1) for dim in expr.shape if dim != 1])\n        symbol = expr\n    elif isinstance(expr, MatrixBase):\n        # if we have a Matrix, we set line by line the code\n        # useful when you have indexes like\n        # A[i, j, 0] = B[i, j, 4]\n\n        # todo: regarder que les matrices pour le in et out ont la meme taille\n        # todo: regarder si le symbole est toujours le meme dans le terme de gauche (expr)\n        for i in range(expr.shape[0]):\n            symbol = expr[i].base.label\n            dims = tuple([ (S.Zero, dim - 1) for dim in expr[i].base.shape if dim != 1])\n    elif isinstance(expr, MatrixSlice):\n        symbol = expr.parent\n        dims = tuple([ (S.Zero, dim - 1) for dim in symbol.shape if dim != 1])\n    else:\n        raise CodeGenError(\"Only Indexed, Symbol, or MatrixSymbol \"\n                            \"can define output arguments.\")\n    return dims, symbol\n\ndef extract(expressions, symbols):\n    # extract arguments and instructions of the routine\n    output_args = []\n    instructions = []\n    for expr in expressions:\n        instructions.append(expr)\n        if isinstance(expr, Equality):\n            out_arg = expr.lhs\n            expr = expr.rhs\n            dims, symbol = get_dims_and_symbol(out_arg)\n\n            if symbol in symbols:\n                output_args.append(\n                    InOutArgument(symbol, out_arg, expr, dimensions=dims))\n\n                # avoid duplicate arguments\n                symbols.remove(symbol)\n        elif isinstance(expr, For):\n            args, vals = extract(expr.expr, symbols)\n            output_args += args\n        elif isinstance(expr, If):\n            for c, e in expr.statement:\n                args, vals = extract(e, symbols)\n                output_args += args\n        else:\n            raise TypeError(\"The expression must be a For or an equality (Eq).\")\n    return output_args, instructions\n\n\nclass LBMCodeGen(CodeGen):\n    \"\"\"Generator for Cython code.\n\n    The .write() method inherited from CodeGen will output a code file <prefix>.pyx.\n\n    \"\"\"\n\n    code_extension = None\n\n    def routine(self, name, expr, argument_sequence, local_vars, settings):\n        \"\"\"Specialized Routine creation for Cython.\"\"\"\n\n        if is_sequence(expr) and not isinstance(expr, (MatrixBase, MatrixExpr)):\n            if not expr:\n                raise ValueError(\"No expression given\")\n            expressions = Tuple(*expr)\n        else:\n            expressions = Tuple(expr)\n\n        self.settings = settings\n\n        # local variables\n        idx_vars = set()\n        symbol_idx_vars = set()\n        for l in expressions.atoms(For):\n            idx_vars.update({i for i in l.atoms(Idx)})\n            # remove symbols that have the same name of Idx in loop\n            name_idx = [i.label.name for i in l.atoms(Idx)]\n            symbol_idx_vars.update({i for i in l.atoms(Symbol) if i.name in name_idx})\n\n        score_table = {}\n        for i in idx_vars:\n            score_table[i] = 0\n\n        def rate_index_position(p):\n            return p*5\n\n        arrays = expressions.atoms(Indexed)\n        for arr in arrays:\n            for p, ind in enumerate(arr.indices):\n                try:\n                    score_table[ind] += rate_index_position(p)\n                except KeyError:\n                    pass\n\n        idx_order = sorted(idx_vars, key=lambda x: score_table[x])\n\n        # local variables\n        local_vars = set() if local_vars is None else set(local_vars)\n\n        # symbols that should be arguments\n        symbol_indexed_local = set()\n        for l in local_vars:\n            for ll in l.atoms(IndexedBase):\n                symbol_indexed_local.update(ll.atoms(Symbol) - ll.shape.atoms(Symbol))\n\n        symbols = expressions.free_symbols - idx_vars - local_vars - symbol_idx_vars - symbol_indexed_local\n\n        new_symbols = set([])\n        new_symbols.update(symbols)\n\n        for symbol in symbols:\n            if isinstance(symbol, Idx):\n                new_symbols.remove(symbol)\n                if symbol.label in idx_vars:\n                    new_symbols.update(symbol.args[1].free_symbols)\n                else:\n                    new_symbols.update([symbol.label])\n        symbols = new_symbols\n\n        output_args, instructions = extract(expressions, symbols)\n\n        arg_list = []\n\n        # setup input argument list\n        array_symbols = {}\n        for array in expressions.atoms(Indexed):\n            array_symbols[array.base.label] = array\n        for array in expressions.atoms(MatrixSymbol):\n            array_symbols[array] = array\n\n        for symbol in sorted(symbols, key=str):\n            if symbol in array_symbols:\n                dims = []\n                array = array_symbols[symbol]\n                for dim in array.shape:\n                    if dim != 1:\n                        dims.append((S.Zero, dim - 1))\n                metadata = {'dimensions': dims}\n            else:\n                metadata = {}\n\n            arg_list.append(InputArgument(symbol, **metadata))\n\n        output_args.sort(key=lambda x: str(x.name))\n        arg_list.extend(output_args)\n\n        if argument_sequence is not None:\n            # if the user has supplied IndexedBase instances, we'll accept that\n            new_sequence = []\n            for arg in argument_sequence:\n                if isinstance(arg, IndexedBase):\n                    new_sequence.append(arg.label)\n                else:\n                    new_sequence.append(arg)\n            argument_sequence = new_sequence\n\n            missing = [x for x in arg_list if x.name not in argument_sequence]\n            if missing:\n                msg = \"Argument list didn't specify: {0} \"\n                msg = msg.format(\", \".join([str(m.name) for m in missing]))\n                raise CodeGenArgumentListError(msg, missing)\n\n            # create redundant arguments to produce the requested sequence\n            name_arg_dict = {x.name: x for x in arg_list}\n            new_args = []\n            for symbol in argument_sequence:\n                try:\n                    new_args.append(name_arg_dict[symbol])\n                except KeyError:\n                    new_args.append(InputArgument(symbol))\n            arg_list = new_args\n\n        return Routine(name, arg_list, instructions, idx_order, local_vars, settings)\n\n    def code_generator(self, expr, assign_to=None):\n        pass\n\n    def _get_symbol(self, s):\n        \"\"\"Print the symbol appropriately.\"\"\"\n        return self.code_generator(s).strip()\n\n    def _call_printer(self, routine):\n        code_lines = []\n\n        # Compose a list of symbols to be dereferenced in the function\n        # body. These are the arguments that were passed by a reference\n        # pointer, excluding arrays.\n        dereference = []\n        for arg in routine.arguments:\n            if isinstance(arg, ResultBase) and not arg.dimensions:\n                dereference.append(arg.name)\n\n        for instruction in routine.instructions:\n            constants, not_supported, expr = self.code_generator(instruction, human=False)\n            code_lines.append(\"%s\\n\" % (expr))\n        return code_lines\n\n        # declarations = []\n        # code_lines = []\n        # for i, result in enumerate(routine.results):\n        #     print(self.settings)\n        #     constants, not_supported, jl_expr = self.code_generator(result, human=False, **self.settings)\n\n        #     for obj, v in sorted(constants, key=str):\n        #         declarations.append(\n        #             \"%s = %s\\n\" % (obj, v))\n        #     for obj in sorted(not_supported, key=str):\n        #         if isinstance(obj, Function):\n        #             name = obj.func\n        #         else:\n        #             name = obj\n        #         declarations.append(\n        #             \"# unsupported: %s\\n\" % (name))\n        #     code_lines.append(\"%s\\n\" % (jl_expr))\n        # return declarations + code_lines\n\n    def _get_routine_opening(self, routine):\n        return []\n\n    def _get_routine_ending(self, routine):\n        return []\n\n\nclass CythonCodeGen(LBMCodeGen):\n    \"\"\"Generator for Cython code.\n\n    The .write() method inherited from CodeGen will output a code file <prefix>.pyx.\n\n    \"\"\"\n\n    code_extension = \"pyx\"\n\n    def code_generator(self, expr, assign_to=None, **settings):\n        return cython_code(expr, assign_to, **settings)\n\n    def _get_header(self):\n        code_lines = [\"#!python\\n\",\n                      \"#cython: boundscheck=False\\n\",\n                      \"#cython: wraparound=False\\n\",\n                      \"#cython: cdivision=True\\n\",\n                      \"#cython: binding=True\\n\",\n                      \"#import cython\\n\",\n                      \"from libc.math cimport *\\n\",\n                      \"import numpy as np\\n\",\n                     ]\n        return code_lines + [\"\\n\\n\"]\n\n    def _preprocessor_statements(self, prefix):\n        # code_lines = [\"#!python\\n\",\n        #               \"#cython: boundscheck=False\\n\",\n        #               \"#cython: wraparound=False\\n\",\n        #               \"#cython: cdivision=True\\n\",\n        #               \"#cython: binding=True\\n\",\n        #               \"#import cython\\n\",\n        #               \"from libc.math cimport *\\n\",\n        #              ]\n        # return code_lines + [\"\\n\\n\"]\n        return []\n\n    def _get_routine_opening(self, routine):\n        \"\"\"Returns the opening statements of the routine.\"\"\"\n        code_list = []\n        export = True\n        # export = self.settings.pop('export', True)\n        if export:\n            code_list.append(\"def \")\n        else:\n            code_list.append(\"cdef void \")\n\n        # Inputs\n        args = []\n        for i, arg in enumerate(routine.arguments):\n            if isinstance(arg, OutputArgument):\n                raise CodeGenError(\"Cython: invalid argument of type %s\" %\n                                   str(type(arg)))\n\n            if isinstance(arg, (InputArgument, InOutArgument)):\n                name = self._get_symbol(arg.name)\n                if not arg.dimensions:\n                    # If it is a scalar\n                    if isinstance(arg, ResultBase):\n                        # if it is an output\n                        args.append((arg.get_datatype('C'), \"*%s\" % name))\n                    else:\n                        # if it is an output\n                        args.append((arg.get_datatype('C'), name))\n                else:\n                    if not export and len(arg.dimensions) == 1:\n                        # if the dimension is 1\n                        args.append((arg.get_datatype('C'), \"*%s\" % name))\n                    else:\n                        args.append((arg.get_datatype('C') + '[' + ', '.join([':']*len(arg.dimensions)) + ':1]', \"%s\" % name))\n\n        args = \", \".join([ \"%s %s\" % t for t in args])\n        code_list.append(\"%s(%s)%s\\n\" % (routine.name, args, \":\" if export else \" nogil:\"))\n        code_list = [ \"\".join(code_list) ]\n\n        return code_list\n\n    def _declare_arguments(self, routine):\n        return []\n\n    def _declare_globals(self, routine):\n        args = []\n        for g in routine.local_vars:\n            if isinstance(g, Symbol):\n                args.append(\"cdef double %s\\n\"%(self._get_symbol(g)))\n            else:\n                shape = [d for d in g.shape if d!=1]\n                if isinstance(g, Indexed):\n                    args.append(\"cdef double[%s] %s = np.zeros((%s))\\n\"%(', '.join([':']*len(shape)) + ':1', g.base, ','.join(\"%s\"%s for s in shape)))\n                else:\n                    args.append(\"cdef double %s[%s]\\n\"%(self._get_symbol(g), ','.join(\"%s\"%s for s in shape)))\n        return [\"\".join(args)]\n\n    def _declare_locals(self, routine):\n        s = []\n        for l in routine.idx_vars:\n            s.append(\"cdef int %s\\n\" % l.label)\n        return s + ['\\n']\n\n    def _get_routine_ending(self, routine):\n        return [\"#end\\n\"]\n\n    def _indent_code(self, codelines):\n        p = CythonCodePrinter()\n        return p.indent_code(codelines)\n\n    def dump_pyx(self, routines, f, prefix, header=True, empty=True):\n        self.dump_code(routines, f, prefix, header, empty)\n\n    dump_pyx.extension = code_extension\n    dump_pyx.__doc__ = CodeGen.dump_code.__doc__\n\n    # This list of dump functions is used by CodeGen.write to know which dump\n    # functions it has to call.\n    dump_fns = [dump_pyx]\n\n\nclass NumpyCodeGen(LBMCodeGen):\n    \"\"\"Generator for Cython code.\n\n    The .write() method inherited from CodeGen will output a code file <prefix>.pyx.\n\n    \"\"\"\n\n    code_extension = \"py\"\n\n    def code_generator(self, expr, assign_to=None, **settings):\n        return numpy_code(expr, assign_to, **settings)\n\n    def _get_header(self):\n        code_lines = [\"import numpy as np\\n\",\n                     ]\n        return code_lines + [\"\\n\\n\"]\n\n    def _preprocessor_statements(self, prefix):\n        return []\n\n    def _get_routine_opening(self, routine):\n        \"\"\"Returns the opening statements of the routine.\"\"\"\n        code_list = []\n        code_list.append(\"def \")\n\n        # Inputs\n        args = []\n        for i, arg in enumerate(routine.arguments):\n            if isinstance(arg, OutputArgument):\n                raise CodeGenError(\"Numpy: invalid argument of type %s\" %\n                                   str(type(arg)))\n\n            if isinstance(arg, (InputArgument, InOutArgument)):\n                name = self._get_symbol(arg.name)\n                args.append(name)\n        args = \", \".join(args)\n        code_list.append(\"%s(%s):\\n\" % (routine.name, args))\n        code_list = [ \"\".join(code_list) ]\n\n        return code_list\n\n    def _declare_arguments(self, routine):\n        return []\n\n    def _declare_globals(self, routine):\n        return []\n\n    def _declare_locals(self, routine):\n        return []\n\n    def _get_routine_ending(self, routine):\n        return [\"#end\\n\"]\n\n    def _indent_code(self, codelines):\n        p = NumpyCodePrinter()\n        return p.indent_code(codelines)\n\n    def dump_py(self, routines, f, prefix, header=True, empty=True):\n        self.dump_code(routines, f, prefix, header, empty)\n\n    dump_py.extension = code_extension\n    dump_py.__doc__ = CodeGen.dump_code.__doc__\n\n    # This list of dump functions is used by CodeGen.write to know which dump\n    # functions it has to call.\n    dump_fns = [dump_py]\n\nclass LoopyCodeGen(LBMCodeGen):\n    \"\"\"Generator for Cython code.\n\n    The .write() method inherited from CodeGen will output a code file <prefix>.pyx.\n\n    \"\"\"\n\n    code_extension = \"py\"\n\n    _default_settings = {\"prefetch\": None}\n\n    def code_generator(self, expr, assign_to=None, **settings):\n        return loopy_code(expr, assign_to, **settings)\n\n    def _preprocessor_statements(self, prefix):\n        return []\n\n    def _get_header(self):\n        code_lines = [\"import loopy as lp\\n\",\n                      \"import numpy as np\\n\"\n                     ]\n        return code_lines + [\"\\n\\n\"]\n\n    def _get_routine_opening(self, routine):\n        \"\"\"Returns the opening statements of the routine.\"\"\"\n        code_list = []\n        code_list.append(\"%s = lp.make_kernel(\"%routine.name)\n        name = []\n        bounds = []\n        for i in routine.idx_vars:\n            if isinstance(i, Idx):\n                name.append(\"%s_\"%i.label)\n                bounds.append(\"0<={ilabel}_<{upper}\".format(ilabel=i.label, upper=i.upper-i.lower))\n\n        if len(name) > 0:\n            code_list.append('\"{[%s]:%s}\",'%(\",\".join(name), \" and \".join(bounds)))\n        code_list.append('\"\"\"  # noqa (silences flake8 line length warning)\\n')\n        code_list = [ \"\\n\".join(code_list) ]\n        return code_list\n\n    def _declare_arguments(self, routine):\n        return []\n\n    def _declare_globals(self, routine):\n        return []\n\n    def _declare_locals(self, routine):\n        return []\n\n    def _get_routine_ending(self, routine):\n        code_list = []\n        code_list.append('\"\"\",')\n\n        # Inputs\n        args = []\n        dtypes = []\n        for i, arg in enumerate(routine.arguments):\n            if isinstance(arg, OutputArgument):\n                raise CodeGenError(\"Loopy: invalid argument of type %s\" %\n                                   str(type(arg)))\n\n            if isinstance(arg, (InputArgument, InOutArgument)):\n                name = self._get_symbol(arg.name)\n                if arg.dimensions:\n                    dims = [\"{}\".format(d[1]-d[0]+1) for d in arg.dimensions]\n                    dtype = arg.get_datatype('PYTHON')\n                    if dtype == 'int':\n                        dtype = 'np.int32'\n                    args.append('lp.GlobalArg(\"{name}\", dtype={dtype}, shape=\"{shape}\")'.format(name=name, dtype=dtype, shape=\", \".join(dims)))\n                else:\n                    args.append('lp.ValueArg(\"{name}\", dtype={dtype})'.format(name=name, dtype=arg.get_datatype('PYTHON')))\n        for i, arg in enumerate(routine.local_vars):\n            if isinstance(arg, Symbol):\n                args.append('lp.TemporaryVariable(\"{name}\", dtype=float)'.format(name=self._get_symbol(arg)))    \n            else:\n                dims = [d for d in arg.shape if d!=1]\n                args.append('lp.TemporaryVariable(\"{name}\", dtype=float, shape=\"{shape}\")'.format(name=self._get_symbol(arg), shape=','.join(\"%s\"%s for s in dims)))\n\n        code_list.append('[')\n        args = \",\\n\".join(args)\n        code_list.append(args)\n        code_list.append('])#endArg\\n')\n\n        # add type\n        dim = len(routine.idx_vars)\n        if dim == 1:\n            block_size = [256]\n        if dim == 2:\n            block_size = [16, 16]\n        if dim == 3:\n            block_size = [4, 4, 4]\n\n        for i, idx in enumerate(routine.idx_vars[-1::-1]):\n            code_list.append('{name} = lp.split_iname({name}, \"{label}\", {block}, outer_tag=\"g.{ilabel}\", inner_tag=\"l.{ilabel}\")'.format(name = routine.name,\n            label = \"%s_\"%idx.label, ilabel=i, block=block_size[i]))\n        code_list.append('{name} = lp.expand_subst({name})\\n'.format(name=routine.name))\n        code_list.append('{name} = lp.set_options({name}, no_numpy = True)\\n'.format(name=routine.name))\n\n        prefetch = routine.settings.get(\"prefetch\", None)\n\n        if prefetch:\n            for var in prefetch:\n                indices = []\n                for idx in routine.idx_vars:\n                    indices.append(\"%s__inner\"%idx.label)\n                # for i in range(var.rank):\n                #     if isinstance(var.indices[i], Idx):\n                #         indices.append(\"%s__inner\"%var.indices[i].label)\n                code_list.append('{name} = lp.add_prefetch({name}, \"{var}\", \"{label}\", fetch_bounding_box=True)\\n'.format(name=routine.name, var=var.base.label, label=\",\".join(indices)))\n#            print(\"PREFETCH\")\n        #     label = []\n        #     for var in self._settings[\"prefetch\"]:\n        #         indices = []\n        #         for i in var.indices:\n        #             if isinstance(i, Idx):\n        #                 indices.append(\"%s__inner\"%i.label)\n        #         code_list.append('{name} = lp.add_prefetch({name}, \"{var}\", \"{label}\", fetch_bounding_box=True)'.format(name=routine.name, var=var.label, label=\",\".join(indices)))\n        #print(LoopyCodePrinter()._sort_optimized(routine.local_vars, routine.instructions))\n# one_time_step = lp.split_iname(one_time_step, \"ii\", 16, outer_tag=\"g.1\", inner_tag=\"l.1\")\n# one_time_step = lp.split_iname(one_time_step, \"jj\", 16, outer_tag=\"g.0\", inner_tag=\"l.0\")\n# one_time_step = lp.expand_subst(one_time_step)\n# one_time_step = lp.add_prefetch(one_time_step, \"f\", \"ii_inner,jj_inner\", fetch_bounding_box=True)\n        code_list = [ \"\\n\".join(code_list) ]\n        return code_list\n\n    def _indent_code(self, codelines):\n        p = LoopyCodePrinter()\n        return p.indent_code(codelines)\n\n    def dump_py(self, routines, f, prefix, header=True, empty=True):\n        self.dump_code(routines, f, prefix, header, empty)\n\n    dump_py.extension = code_extension\n    dump_py.__doc__ = CodeGen.dump_code.__doc__\n\n    # This list of dump functions is used by CodeGen.write to know which dump\n    # functions it has to call.\n    dump_fns = [dump_py]\n\ndef get_code_generator(language, project):\n    CodeGenClass = {\"NUMPY\" : NumpyCodeGen,\n                    \"CYTHON\": CythonCodeGen,\n                    \"LOOPY\": LoopyCodeGen}.get(language.upper())\n    if CodeGenClass is None:\n        raise ValueError(\"Language '%s' is not supported.\" % language)\n    return CodeGenClass(project)\n\ndef codegen(name_expr, language, prefix=None, project=\"project\",\n            to_files=False, header=True, empty=True, argument_sequence=None,\n            global_vars=None, settings={}):\n    # Initialize the code generator.\n    code_gen = get_code_generator(language, project)\n\n    if isinstance(name_expr[0], string_types):\n        # single tuple is given, turn it into a singleton list with a tuple.\n        name_expr = [name_expr]\n\n    if prefix is None:\n        prefix = name_expr[0][0]\n\n    # Construct Routines appropriate for this code_gen from (name, expr) pairs.\n    routines = []\n    for name, expr in name_expr:\n        routines.append(code_gen.routine(name, expr, argument_sequence,\n                                         global_vars, settings))\n\n    # Write the code.\n    return code_gen.write(routines, prefix, to_files, header, empty)\n\ndef make_routine(name_expr, argument_sequence=None, local_vars=None, settings={}):\n    if isinstance(name_expr[0], string_types):\n        # single tuple is given, turn it into a singleton list with a tuple.\n        name_expr = [name_expr]\n\n    routines = []\n    for name, expr in name_expr:\n        routines.append(LBMCodeGen().routine(name, expr, argument_sequence,\n                                             local_vars, settings))\n\n    return routines\n", "meta": {"hexsha": "eb3c5bb60ba87c0d3b6897bbde63c2efc341223a", "size": 26763, "ext": "py", "lang": "Python", "max_stars_repo_path": "pylbm/generator/codegen.py", "max_stars_repo_name": "Mopolino8/pylbm", "max_stars_repo_head_hexsha": "b457ccdf1e7a1009807bd1136a276886f81a9e7d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pylbm/generator/codegen.py", "max_issues_repo_name": "Mopolino8/pylbm", "max_issues_repo_head_hexsha": "b457ccdf1e7a1009807bd1136a276886f81a9e7d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pylbm/generator/codegen.py", "max_forks_repo_name": "Mopolino8/pylbm", "max_forks_repo_head_hexsha": "b457ccdf1e7a1009807bd1136a276886f81a9e7d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-24T17:13:26.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-24T17:13:26.000Z", "avg_line_length": 37.2743732591, "max_line_length": 186, "alphanum_fraction": 0.5787841423, "include": true, "reason": "import numpy,from sympy", "num_tokens": 5876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3812195803163618, "lm_q1q2_score": 0.19507638928623552}}
{"text": "#!/usr/bin/env python2.7\n\n'''A tool for determining the UVIT FUV and NUV filters.\n\n\n   Copyright 2018 Prajwel Joseph\n  \n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n  \n       http://www.apache.org/licenses/LICENSE-2.0\n  \n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License. \n\n   Changes; when, what\n   -------------------\n   Jan 10, 2018: Galactic latitude check incorporated.\n\n\n   The author would like to acknowledge inputs from Dr. Koshy George\n   which greatly helped the developement of this script.\n   \n'''\n\n\nimport os\nimport sys\nimport string\nimport urllib\nimport matplotlib\n# Force matplotlib to not use any Xwindows backend.\nmatplotlib.use('Agg')\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom astropy.io import fits\nfrom astropy.wcs import WCS\nfrom astropy.io import ascii\nfrom requests import Session\nfrom bs4 import BeautifulSoup\nfrom astropy import units as u\nfrom matplotlib.colors import LogNorm\nfrom astropy.table import Table, hstack\nfrom astropy.coordinates import SkyCoord\n\n\n# To get the user input. \ninstrument = str(sys.argv[1])\nRA = str(sys.argv[2])\nDEC = str(sys.argv[3])\n#working_arena = str(sys.argv[4])\n\n#instrument = 'uvit'\n#RA = \"7:36:51.396\"\n#DEC = \"65:36:9.170\"\nworking_arena = '.'\n\n# To do all the stuff in a specific directory.\nos.chdir(working_arena)\n\n# To read the TD1 catalogue.\ntry:\n    catalogue = 'td1_catalogue.fits'\n    hdu = fits.open(catalogue)\nexcept IOError:\n    print('Could not find the catalogue file: {}'.format(catalogue))\n    sys.exit(1)\n\n# instrument and radius of search in arsec.\nfield_radius = {'uvit'  : 1200,\n                'sxt'   : 1500,\n                'czti'  : 1680,\n                'laxpc' : 1680}\n\n# Functions to convert magnitude to UVIT count rates.\nflux_norm = 2E-13\ndef countnuv(flux):\n    silica = 955.0\n    b4 = 218.5\n    b13 = 275.8\n    b15 = 59.6\n    n2 = 50.6\n    flux_ratio = flux / flux_norm\n    cr1 =  silica * flux_ratio\n    cr2 =  b4 * flux_ratio\n    cr3 =  b13 * flux_ratio\n    cr4 =  b15 * flux_ratio\n    cr5 =  n2 * flux_ratio\n    return flux, cr1, cr2, cr3, cr4, cr5\n\ndef countfuv(flux):\n    caf2 = 74.5\n    baf2 = 60.0\n    sapphire = 50.0\n    silica = 17.3\n    flux_ratio = flux / flux_norm\n    cr1 =  caf2 * flux_ratio    \n    cr2 =  baf2 * flux_ratio\n    cr3 =  sapphire * flux_ratio\n    cr4 =  silica * flux_ratio \n    return flux, cr1, cr2, cr3, cr4\n\n# Function to find seperation in celestial coordinates.\ncc = SkyCoord(RA, DEC, unit = (u.hourangle, u.deg))\ndef cel_separation(a, b):\n    coo = SkyCoord(a, b, frame = 'icrs', unit = 'deg')\n    return coo.separation(cc)\n\n# To check if Galactic latitude is between -30 to 30.\ngal_lat = cc.galactic.b.value\ngal_plane = 'no'\nif -30.0 <= gal_lat <= 30.0:\n    gal_plane_warning = 'The galactic latitude is between -30 to 30. \\\n                        \\nYour field cannot be checked using TD1 catalogue!'\n    print('\\n{}\\n'.format(gal_plane_warning))\n    with open('gal_plane_warning.txt', 'w') as gal_warn:\n        gal_warn.write(gal_plane_warning)\n    sys.exit(1)\n\n# Reading coordinates and fluxes from catalogue.\nhdu = fits.open(catalogue)\nalpha = hdu[1].data['ra']\ndelta = hdu[1].data['dec']\nnuv_flux = hdu[1].data['flux_2365_a']\nfuv_flux = hdu[1].data['flux_1565_a']\n\n# NUV \nrefined_set = [(al, de, nf) for al, de, nf \n                            in zip(alpha, delta, nuv_flux)\n                            if (cc.ra.value - 5) <= al <= (cc.ra.value + 5)\n                                and (cc.dec.value - 5) <= de <= (cc.dec.value + 5)]\n\nnalpha, ndelta, nuv_flux = zip(*refined_set)\n\nconfined_set = [nf for al, de, nf \n                   in zip(nalpha, ndelta, nuv_flux) \n                   if cel_separation(al, de) <= field_radius[instrument] * u.arcsec]\n\n# If list is empty, normal value need to be taken.\nif len(confined_set) == 0:\n    confined_set.append(flux_norm)\n\nnd = sorted(confined_set)[-1]\nflux, ta, tb, tc, td, te = countnuv(nd)\nnuv_res = Table([[flux], [ta], [tb], [tc], [td], [te]],\n               names = ('flux_2365_a',\n                        'silica',\n                        'b4',\n                        'b13',\n                        'b15',\n                        'n2'), \n               meta = {'name': 'NUV counts'})\n\n#nuv_res['flux_2365_a'].format = '\nnuv_res['silica'].format = '4.1f'\nnuv_res['b4'].format = '4.1f'\nnuv_res['b13'].format = '4.1f'\nnuv_res['b15'].format = '4.1f'\nnuv_res['n2'].format = '4.1f'\n\nprint('\\n\\n### NUV\\n\\n{}\\n'.format(nuv_res))\n\n# To select NUV safe filters.\nnuv_filter_dict = {0: 'Silica', 1: 'NUV-B4', 2: 'NUV-B13', 3: 'NUV-B15', 4: 'NUV-N2'}\ni = 0\nnuv_safe = []\nfor Filter in zip(*nuv_res['silica','b4','b13','b15','n2']):\n     if sum(np.array(Filter) > 1500) == 0: \n         nuv_safe.append(nuv_filter_dict[i])\n     if i == 0:\n         if sum(np.array(Filter) > 1133) == 0:\n             nuv_safe.append('NUV-grating')\n     i = i + 1\n\nnuv_declaration = 'Safe filters in NUV: {}'.format(nuv_safe)\nprint('\\n\\n{}\\n'.format(nuv_declaration))\n\n# To write to file.\nnuv_table = 'NUV_td1-nd-int.txt'\nascii.write(nuv_res, nuv_table, format = 'csv', overwrite = True)\n\nwith open('safe_NUV_filters.txt', 'w') as safe_file:\n    safe_file.write(nuv_declaration)\n\n# FUV \nrefined_set = [(al, de, ff) for al, de, ff \n                            in zip(alpha, delta, fuv_flux)\n                            if (cc.ra.value - 5) <= al <= (cc.ra.value + 5)\n                                and (cc.dec.value - 5) <= de <= (cc.dec.value + 5)]\n\nnalpha, ndelta, fuv_flux = zip(*refined_set)\n\nconfined_set = [ff for al, de, ff \n                   in zip(nalpha, ndelta, fuv_flux) \n                   if cel_separation(al, de) <= field_radius[instrument] * u.arcsec]\n\n# If list is empty, normal value need to be taken.\nif len(confined_set) == 0:\n    confined_set.append(flux_norm)\n\nfd = sorted(confined_set)[-1]\nflux, ta, tb, tc, td = countfuv(fd)\nfuv_res = Table([[flux], [ta], [tb], [tc], [td]],\n               names = ('flux_1565_a',\n                        'caf2',\n                        'baf2',\n                        'sapphire',\n                        'silica'), \n               meta = {'name': 'NUV counts'})\n\n#fuv_res['flux_1565_a'].format = '\nfuv_res['caf2'].format = '4.1f'\nfuv_res['baf2'].format = '4.1f'\nfuv_res['sapphire'].format = '4.1f'\nfuv_res['silica'].format = '4.1f'\n\nprint('\\n### FUV \\n\\n{}\\n\\n'.format(fuv_res))\n\n# To select FUV safe filters.\nfuv_filter_dict = {0: 'CaF2', 1: 'BaF2', 2: 'Sapphire', 3: 'Silica'}\nj = 0\nfuv_safe = []\nfor Filter in zip(*fuv_res['caf2','baf2','sapphire','silica']):\n     if sum(np.array(Filter) > 1500) == 0: \n         fuv_safe.append(fuv_filter_dict[j])\n     if j == 0:\n         if sum(np.array(Filter) > 892) == 0:\n             fuv_safe.append('FUV-grating')\n     j = j + 1\n\nfuv_declaration = 'Safe filters in FUV: {}'.format(fuv_safe)\nprint('\\n\\n{}\\n'.format(fuv_declaration))\n\n# To write to file.\nfuv_table = 'FUV_td1-fd-int.txt'\nascii.write(fuv_res, fuv_table, format = 'csv', overwrite = True)\n\nwith open('safe_FUV_filters.txt', 'w') as safe_file:\n    safe_file.write(fuv_declaration)\n\nprint('Done!\\n')\n\n\n\n\n\n", "meta": {"hexsha": "f10b098616311c8577445e1af154ad681ea8fab6", "size": 7443, "ext": "py", "lang": "Python", "max_stars_repo_path": "Gaia (UV filter checking tool)/td1_gaia_V.2.5.py", "max_stars_repo_name": "prajwel/UVIT-POC", "max_stars_repo_head_hexsha": "eaaeb26f11b2c6e19cd96d3a99017b7bb39ee7aa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Gaia (UV filter checking tool)/td1_gaia_V.2.5.py", "max_issues_repo_name": "prajwel/UVIT-POC", "max_issues_repo_head_hexsha": "eaaeb26f11b2c6e19cd96d3a99017b7bb39ee7aa", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Gaia (UV filter checking tool)/td1_gaia_V.2.5.py", "max_forks_repo_name": "prajwel/UVIT-POC", "max_forks_repo_head_hexsha": "eaaeb26f11b2c6e19cd96d3a99017b7bb39ee7aa", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5357142857, "max_line_length": 85, "alphanum_fraction": 0.6072820099, "include": true, "reason": "import numpy,from astropy", "num_tokens": 2262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3812195803163618, "lm_q1q2_score": 0.19507638928623552}}
{"text": "\"\"\"multipy: Python library for multicomponent mass transfer\"\"\"\n\n__author__ = \"James C. Sutherland, Kamila Zdybal\"\n__copyright__ = \"Copyright (c) 2022, James C. Sutherland, Kamila Zdybal\"\n__license__ = \"MIT\"\n__version__ = \"1.0.0\"\n__maintainer__ = [\"Kamila Zdybal\"]\n__email__ = [\"kamilazdybal@gmail.com\"]\n__status__ = \"Production\"\n\nimport numpy as np\nimport pandas as pd\nimport random\nimport copy\nimport scipy\nimport multipy\nimport warnings\n\ngas_constant = 8.31446261815324\n\n################################################################################\n################################################################################\n####\n####    Class: Flux\n####\n################################################################################\n################################################################################\n\nclass Flux:\n    \"\"\"\n    Supports computing and storing fluxes. This class assumes that the species velocities, :math:`\\\\mathbf{u}_i`, are known.\n\n    Diffusive fluxes:\n\n    - mass diffusive flux relative to a mass-averaged velocity, :math:`\\mathbf{j}_i`\n    - mass diffusive flux relative to a molar-averaged velocity, :math:`\\mathbf{j}_i^u`\n    - molar diffusive flux relative to a mass-averaged velocity, :math:`\\mathbf{J}_i^v`\n    - molar diffusive flux relative to a molar-averaged velocity, :math:`\\mathbf{J}_i`\n\n    :param species_velocities:\n        vector ``numpy.ndarray`` specifying the species velocities :math:`\\mathbf{u}_i` in :math:`[m/s]`. It should be of size ``(n_species,n_observations)``.\n\n    **Getters:**\n\n    - **get_species_velocities**\n    - **get_diffusive_molar_molar** (is set to ``None`` at class init)\n    - **get_diffusive_molar_mass** (is set to ``None`` at class init)\n    - **get_diffusive_mass_molar** (is set to ``None`` at class init)\n    - **get_diffusive_mass_mass** (is set to ``None`` at class init)\n\n    **Setters:**\n\n    - **set_species_velocities**\n    - **set_diffusive_molar_molar** (is set to ``None`` at class init)\n    - **set_diffusive_molar_mass** (is set to ``None`` at class init)\n    - **set_diffusive_mass_molar** (is set to ``None`` at class init)\n    - **set_diffusive_mass_mass** (is set to ``None`` at class init)\n    \"\"\"\n\n    # --------------------------------------------------------------------------\n\n    def __init__(self, species_velocities):\n\n        if not isinstance(species_velocities, np.ndarray):\n            raise ValueError(\"Parameter `species_velocities` has to be of type `numpy.ndarray`.\")\n\n        try:\n            (n_species, n_observations) = np.shape(species_velocities)\n        except:\n            raise ValueError(\"Parameter `species_velocities` has to be a matrix.\")\n\n        if n_species < 2:\n            raise ValueError(\"Parameter `species_velocities` has to have at least two species.\")\n\n        self.__species_velocities = species_velocities\n        self.__velocity = multipy.Velocity(self.get_species_velocities)\n        self.__diffusive_molar_molar = None\n        self.__diffusive_molar_mass = None\n        self.__diffusive_mass_molar = None\n        self.__diffusive_mass_mass = None\n\n    @property\n    def get_species_velocities(self):\n        return self.__species_velocities\n\n    @property\n    def get_diffusive_molar_molar(self):\n        return self.__diffusive_molar_molar\n\n    @property\n    def get_diffusive_molar_mass(self):\n        return self.__diffusive_molar_mass\n\n    @property\n    def get_diffusive_mass_molar(self):\n        return self.__diffusive_mass_molar\n\n    @property\n    def get_diffusive_mass_mass(self):\n        return self.__diffusive_mass_mass\n\n    @get_species_velocities.setter\n    def set_species_velocities(self, new_species_velocities):\n\n        if new_species_velocities is not None:\n            if not isinstance(new_species_velocities, np.ndarray):\n                raise ValueError(\"Parameter `species_velocities` has to be of type `numpy.ndarray`.\")\n\n            try:\n                (n_species, n_observations) = np.shape(new_species_velocities)\n            except:\n                raise ValueError(\"Parameter `species_velocities` has to be a matrix.\")\n\n        self.__species_velocities = new_species_velocities\n\n    @get_diffusive_molar_molar.setter\n    def set_diffusive_molar_molar(self, new_diffusive_molar_molar):\n\n        if new_diffusive_molar_molar is not None:\n            if not isinstance(new_diffusive_molar_molar, np.ndarray):\n                raise ValueError(\"Parameter `diffusive_molar_molar` has to be of type `numpy.ndarray`.\")\n\n            try:\n                (n_species, n_observations) = np.shape(new_diffusive_molar_molar)\n            except:\n                raise ValueError(\"Parameter `diffusive_molar_molar` has to be a matrix.\")\n\n        self.__diffusive_molar_molar = new_diffusive_molar_molar\n\n    @get_diffusive_molar_mass.setter\n    def set_diffusive_molar_mass(self, new_diffusive_molar_mass):\n\n        if new_diffusive_molar_mass is not None:\n            if not isinstance(new_diffusive_molar_mass, np.ndarray):\n                raise ValueError(\"Parameter `diffusive_molar_mass` has to be of type `numpy.ndarray`.\")\n\n            try:\n                (n_species, n_observations) = np.shape(new_diffusive_molar_mass)\n            except:\n                raise ValueError(\"Parameter `diffusive_molar_mass` has to be a matrix.\")\n\n        self.__diffusive_molar_mass = new_diffusive_molar_mass\n\n    @get_diffusive_mass_molar.setter\n    def set_diffusive_mass_molar(self, new_diffusive_mass_molar):\n\n        if new_diffusive_mass_molar is not None:\n            if not isinstance(new_diffusive_mass_molar, np.ndarray):\n                raise ValueError(\"Parameter `diffusive_mass_molar` has to be of type `numpy.ndarray`.\")\n\n            try:\n                (n_species, n_observations) = np.shape(new_diffusive_mass_molar)\n            except:\n                raise ValueError(\"Parameter `diffusive_mass_molar` has to be a matrix.\")\n\n        self.__diffusive_mass_molar = new_diffusive_mass_molar\n\n    @get_diffusive_mass_mass.setter\n    def set_diffusive_mass_mass(self, new_diffusive_mass_mass):\n\n        if new_diffusive_mass_mass is not None:\n            if not isinstance(new_diffusive_mass_mass, np.ndarray):\n                raise ValueError(\"Parameter `diffusive_mass_mass` has to be of type `numpy.ndarray`.\")\n\n            try:\n                (n_species, n_observations) = np.shape(new_diffusive_mass_mass)\n            except:\n                raise ValueError(\"Parameter `diffusive_mass_mass` has to be a matrix.\")\n\n        self.__diffusive_mass_mass = new_diffusive_mass_mass\n\n    # --------------------------------------------------------------------------\n\n    def plot_diffusive_flux(self, species_names=None, colors=None, figsize=(10,5), filename=None):\n        \"\"\"\n        Plots the computed diffusive fluxes.\n\n        **Example:**\n\n        .. image:: ../images/stefan-tube-diffusive-flux-molar-diff-molar-avg.svg\n          :width: 400\n\n        :param species_names: (optional)\n            ``list`` of ``str`` specifying the species names.\n        :param colors: (optional)\n            ``list`` of ``str`` specifying the plotting colors for each species. Example: ``colors=['#C7254E', '#BBBBBB', '#008CBA']``.\n        :param figsize: (optional)\n            ``tuple`` specifying the figure size.\n        :param filename: (optional)\n            ``str`` specifying the filename. If set to ``None``, plot will not be saved to a file.\n        \"\"\"\n\n        if filename is not None:\n\n            path = False\n\n            if filename[0:2] == '..':\n                __filename = filename[2::]\n                path = True\n            else:\n                __filename = filename\n\n            __base = __filename.split('.')[0]\n            __extension = __filename.split('.')[1]\n\n            if path:\n                __filename = '..' + __base\n            else:\n                __filename = __base\n\n        if self.get_diffusive_molar_molar is not None:\n            if filename is not None:\n                plt = multipy.plot.plot_1d_diffusive_flux(self.get_diffusive_molar_molar, flux='molar', velocity='molar', species_names=species_names, colors=colors, figsize=figsize, filename=__filename + '-molar-diff-molar-avg.' + __extension)\n            else:\n                plt = multipy.plot.plot_1d_diffusive_flux(self.get_diffusive_molar_molar, flux='molar', velocity='molar', species_names=species_names, colors=colors, figsize=figsize, filename=None)\n\n        if self.get_diffusive_molar_mass is not None:\n            if filename is not None:\n                plt = multipy.plot.plot_1d_diffusive_flux(self.get_diffusive_molar_mass, flux='molar', velocity='mass', species_names=species_names, colors=colors, figsize=figsize, filename=__filename + '-molar-diff-mass-avg.' + __extension)\n            else:\n                plt = multipy.plot.plot_1d_diffusive_flux(self.get_diffusive_molar_mass, flux='molar', velocity='mass', species_names=species_names, colors=colors, figsize=figsize, filename=None)\n\n        if self.get_diffusive_mass_molar is not None:\n            if filename is not None:\n                plt = multipy.plot.plot_1d_diffusive_flux(self.get_diffusive_mass_molar, flux='mass', velocity='molar', species_names=species_names, colors=colors, figsize=figsize, filename=__filename + '-mass-diff-molar-avg.' + __extension)\n            else:\n                plt = multipy.plot.plot_1d_diffusive_flux(self.get_diffusive_mass_molar, flux='mass', velocity='molar', species_names=species_names, colors=colors, figsize=figsize, filename=None)\n\n        if self.get_diffusive_mass_mass is not None:\n            if filename is not None:\n                plt = multipy.plot.plot_1d_diffusive_flux(self.get_diffusive_mass_mass, flux='mass', velocity='mass', species_names=species_names, colors=colors, figsize=figsize, filename=__filename + '-mass-diff-mass-avg.' + __extension)\n            else:\n                plt = multipy.plot.plot_1d_diffusive_flux(self.get_diffusive_mass_mass, flux='mass', velocity='mass', species_names=species_names, colors=colors, figsize=figsize, filename=None)\n\n    # --------------------------------------------------------------------------\n\n    def diffusive_molar_molar(self, species_mole_fractions, species_molar_densities):\n        \"\"\"\n        Computes the molar diffusive flux relative to a molar-averaged velocity:\n\n        .. math::\n\n            \\mathbf{J}_i = c_i \\mathbf{u}_i + c_i \\mathbf{u}\n\n        :param species_mole_fractions:\n            scalar ``numpy.ndarray`` specifying the species mole fractions, :math:`X_i`, in :math:`[-]`. It should be of size ``(n_species,n_observations)``.\n        :param species_molar_densities:\n            scalar ``numpy.ndarray`` specifying the molar densities of species, :math:`c_i`, in :math:`[mole/m^3]`. It should be of size ``(n_species,n_observations)``.\n\n        :return:\n            - **diffusive_flux** - vector ``numpy.ndarray`` of molar diffusive fluxes relative to a molar-averaged velocity :math:`\\mathbf{J}_i` in :math:`[mole/(m^2s)]`. It has size ``(n_species,n_observations)``.\n        \"\"\"\n\n        if not isinstance(species_mole_fractions, np.ndarray):\n            raise ValueError(\"Parameter `species_mole_fractions` has to be of type `numpy.ndarray`.\")\n\n        try:\n            (n_species_1, n_observations_1) = np.shape(species_mole_fractions)\n        except:\n            raise ValueError(\"Parameter `species_mole_fractions` has to be a matrix.\")\n\n        if not isinstance(species_molar_densities, np.ndarray):\n            raise ValueError(\"Parameter `species_molar_densities` has to be of type `numpy.ndarray`.\")\n\n        try:\n            (n_species_2, n_observations_2) = np.shape(species_molar_densities)\n        except:\n            raise ValueError(\"Parameter `species_molar_densities` has to be a matrix.\")\n\n        if n_observations_1 != n_observations_2:\n            raise ValueError(\"Parameters `species_mole_fractions` and `species_molar_densities` have different number of observations `n_observations`.\")\n\n        if n_species_1 != n_species_2:\n            raise ValueError(\"Parameters `species_mole_fractions` and `species_molar_densities` have different number of species `n_species`.\")\n\n        (n_species, n_observations) = np.shape(self.get_species_velocities)\n\n        if n_observations != n_observations_1:\n            raise ValueError(\"Parameters `species_mole_fractions`, `species_molar_densities` and `species_velocities` have different number of observations `n_observations`.\")\n\n        if n_species != n_species_1:\n            raise ValueError(\"Parameters `species_mole_fractions`, `species_molar_densities` and `species_velocities` have different number of species `n_species`.\")\n\n        molar_averaged_velocity = self.__velocity.molar_averaged(species_mole_fractions)\n\n        diffusive_flux = np.multiply(species_molar_densities, self.get_species_velocities) - np.multiply(species_molar_densities, molar_averaged_velocity)\n        self.__diffusive_molar_molar = diffusive_flux\n\n        return diffusive_flux\n\n    # --------------------------------------------------------------------------\n\n    def diffusive_molar_mass(self, species_mass_fractions, species_molar_densities):\n        \"\"\"\n        Computes the molar diffusive flux relative to a mass-averaged velocity:\n\n        .. math::\n\n            \\mathbf{J}_i^v = c_i \\mathbf{u}_i + c_i \\mathbf{v}\n\n        :param species_mass_fractions:\n            scalar ``numpy.ndarray`` specifying the species mass fractions, :math:`Y_i`, in :math:`[-]`. It should be of size ``(n_species,n_observations)``.\n        :param species_molar_densities:\n            scalar ``numpy.ndarray`` specifying the species molar densities :math:`c_i` in :math:`[mole/m^3]`. It should be of size ``(n_species,n_observations)``.\n\n        :return:\n            - **diffusive_flux** - vector ``numpy.ndarray`` of molar diffusive fluxes relative to a mass-averaged velocity :math:`\\mathbf{J}_i^v` in :math:`[mole/(m^2s)]`. It has size ``(n_species,n_observations)``.\n        \"\"\"\n\n        if not isinstance(species_mass_fractions, np.ndarray):\n            raise ValueError(\"Parameter `species_mass_fractions` has to be of type `numpy.ndarray`.\")\n\n        try:\n            (n_species_1, n_observations_1) = np.shape(species_mass_fractions)\n        except:\n            raise ValueError(\"Parameter `species_mass_fractions` has to be a matrix.\")\n\n        if not isinstance(species_molar_densities, np.ndarray):\n            raise ValueError(\"Parameter `species_molar_densities` has to be of type `numpy.ndarray`.\")\n\n        try:\n            (n_species_2, n_observations_2) = np.shape(species_molar_densities)\n        except:\n            raise ValueError(\"Parameter `species_molar_densities` has to be a matrix.\")\n\n        if n_observations_1 != n_observations_2:\n            raise ValueError(\"Parameters `species_mass_fractions` and `species_molar_densities` have different number of observations `n_observations`.\")\n\n        if n_species_1 != n_species_2:\n            raise ValueError(\"Parameters `species_mass_fractions` and `species_molar_densities` have different number of species `n_species`.\")\n\n        (n_species, n_observations) = np.shape(self.get_species_velocities)\n\n        if n_observations != n_observations_1:\n            raise ValueError(\"Parameters `species_mass_fractions`, `species_molar_densities` and `species_velocities` have different number of observations `n_observations`.\")\n\n        if n_species != n_species_1:\n            raise ValueError(\"Parameters `species_mass_fractions`, `species_molar_densities` and `species_velocities` have different number of species `n_species`.\")\n\n        mass_averaged_velocity = self.__velocity.mass_averaged(species_mass_fractions)\n\n        diffusive_flux = np.multiply(species_molar_densities, self.get_species_velocities) - np.multiply(species_molar_densities, mass_averaged_velocity)\n        self.__diffusive_molar_mass = diffusive_flux\n\n        return diffusive_flux\n\n    # --------------------------------------------------------------------------\n\n    def diffusive_mass_molar(self, species_mole_fractions, species_mass_densities):\n        \"\"\"\n        Computes the mass diffusive flux relative to a molar-averaged velocity:\n\n        .. math::\n\n            \\mathbf{j}_i^u = \\\\rho_i \\mathbf{u}_i + \\\\rho_i \\mathbf{u}\n\n        :param species_mole_fractions:\n            scalar ``numpy.ndarray`` specifying the species mole fractions :math:`X_i` in :math:`[-]`. It should be of size ``(n_species,n_observations)``.\n        :param species_mass_densities:\n            scalar ``numpy.ndarray`` specifying the species mass densities :math:`\\mathbf{\\\\rho}_i` in :math:`[kg/m^3]`. It should be of size ``(n_species,n_observations)``.\n\n        :return:\n            - **diffusive_flux** - vector ``numpy.ndarray`` of mass diffusive fluxes relative to a molar-averaged velocity :math:`\\mathbf{j}_i^u` in :math:`[kg/(m^2s)]`. It has size ``(n_species,n_observations)``.\n        \"\"\"\n\n        if not isinstance(species_mole_fractions, np.ndarray):\n            raise ValueError(\"Parameter `species_mole_fractions` has to be of type `numpy.ndarray`.\")\n\n        try:\n            (n_species_1, n_observations_1) = np.shape(species_mole_fractions)\n        except:\n            raise ValueError(\"Parameter `species_mole_fractions` has to be a matrix.\")\n\n        if not isinstance(species_mass_densities, np.ndarray):\n            raise ValueError(\"Parameter `species_mass_densities` has to be of type `numpy.ndarray`.\")\n\n        try:\n            (n_species_2, n_observations_2) = np.shape(species_mass_densities)\n        except:\n            raise ValueError(\"Parameter `species_mass_densities` has to be a matrix.\")\n\n        if n_observations_1 != n_observations_2:\n            raise ValueError(\"Parameters `species_mole_fractions` and `species_mass_densities` have different number of observations `n_observations`.\")\n\n        if n_species_1 != n_species_2:\n            raise ValueError(\"Parameters `species_mole_fractions` and `species_mass_densities` have different number of species `n_species`.\")\n\n        (n_species, n_observations) = np.shape(self.get_species_velocities)\n\n        if n_observations != n_observations_1:\n            raise ValueError(\"Parameters `species_mole_fractions`, `species_mass_densities` and `species_velocities` have different number of observations `n_observations`.\")\n\n        if n_species != n_species_1:\n            raise ValueError(\"Parameters `species_mole_fractions`, `species_mass_densities` and `species_velocities` have different number of species `n_species`.\")\n\n        molar_averaged_velocity = self.__velocity.molar_averaged(species_mole_fractions)\n\n        diffusive_flux = np.multiply(species_mass_densities, self.get_species_velocities) - np.multiply(species_mass_densities, molar_averaged_velocity)\n        self.__diffusive_mass_molar = diffusive_flux\n\n        return diffusive_flux\n\n    # --------------------------------------------------------------------------\n\n    def diffusive_mass_mass(self, species_mass_fractions, species_mass_densities):\n        \"\"\"\n        Computes the mass diffusive flux relative to a mass-averaged velocity:\n\n        .. math::\n\n            \\mathbf{j}_i = \\\\rho_i \\mathbf{u}_i + \\\\rho_i \\mathbf{v}\n\n        :param species_mass_fractions:\n            scalar ``numpy.ndarray`` specifying the species mass fractions :math:`Y_i` in :math:`[-]`. It should be of size ``(n_species, n_observations)``.\n        :param species_mass_densities:\n            scalar ``numpy.ndarray`` specifying the species mass densities :math:`\\mathbf{\\\\rho}_i` in :math:`[kg/m^3]`. It should be of size ``(n_species, n_observations)``.\n\n        :return:\n            - **diffusive_flux** - vector ``numpy.ndarray`` of mass diffusive fluxes relative to a mass-averaged velocity :math:`\\mathbf{j}_i` in :math:`[kg/(m^2s)]`. It has size ``(n_species, n_observations)``.\n        \"\"\"\n        if not isinstance(species_mass_fractions, np.ndarray):\n            raise ValueError(\"Parameter `species_mass_fractions` has to be of type `numpy.ndarray`.\")\n\n        try:\n            (n_species_1, n_observations_1) = np.shape(species_mass_fractions)\n        except:\n            raise ValueError(\"Parameter `species_mass_fractions` has to be a matrix.\")\n\n        if not isinstance(species_mass_densities, np.ndarray):\n            raise ValueError(\"Parameter `species_mass_densities` has to be of type `numpy.ndarray`.\")\n\n        try:\n            (n_species_2, n_observations_2) = np.shape(species_mass_densities)\n        except:\n            raise ValueError(\"Parameter `species_mass_densities` has to be a matrix.\")\n\n        if n_observations_1 != n_observations_2:\n            raise ValueError(\"Parameters `species_mass_fractions` and `species_mass_densities` have different number of observations `n_observations`.\")\n\n        if n_species_1 != n_species_2:\n            raise ValueError(\"Parameters `species_mass_fractions` and `species_mass_densities` have different number of species `n_species`.\")\n\n        (n_species, n_observations) = np.shape(self.get_species_velocities)\n\n        if n_observations != n_observations_1:\n            raise ValueError(\"Parameters `species_mass_fractions`, `species_mass_densities` and `species_velocities` have different number of observations `n_observations`.\")\n\n        if n_species != n_species_1:\n            raise ValueError(\"Parameters `species_mass_fractions`, `species_mass_densities` and `species_velocities` have different number of species `n_species`.\")\n\n        mass_averaged_velocity = self.__velocity.mass_averaged(species_mass_fractions)\n\n        diffusive_flux = np.multiply(species_mass_densities, self.get_species_velocities) - np.multiply(species_mass_densities, mass_averaged_velocity)\n        self.__diffusive_mass_mass = diffusive_flux\n\n        return diffusive_flux\n\n    # --------------------------------------------------------------------------\n", "meta": {"hexsha": "da1cd997565c598625d3fbc3be2100124fc27c2c", "size": 21915, "ext": "py", "lang": "Python", "max_stars_repo_path": "multipy/flux.py", "max_stars_repo_name": "kamilazdybal/multipy", "max_stars_repo_head_hexsha": "ebdcddb63bfb1cd647ca99bbf9002b04a9b50ed9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "multipy/flux.py", "max_issues_repo_name": "kamilazdybal/multipy", "max_issues_repo_head_hexsha": "ebdcddb63bfb1cd647ca99bbf9002b04a9b50ed9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multipy/flux.py", "max_forks_repo_name": "kamilazdybal/multipy", "max_forks_repo_head_hexsha": "ebdcddb63bfb1cd647ca99bbf9002b04a9b50ed9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.7450980392, "max_line_length": 244, "alphanum_fraction": 0.6579055441, "include": true, "reason": "import numpy,import scipy", "num_tokens": 5145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3812195803163617, "lm_q1q2_score": 0.1950763892862355}}
{"text": "#!/bin/python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport pandas as pd\nimport os\nimport time\nimport tqdm\nfrom datetime import datetime\nfrom .mpile import get_par\n\n\ndef mcmc(\n    self,\n    p0=None,\n    nsteps=3000,\n    nwalks=None,\n    tune=None,\n    moves=None,\n    temp=False,\n    seed=None,\n    backend=True,\n    suffix=None,\n    linear=None,\n    resume=False,\n    append=False,\n    update_freq=None,\n    lprob_seed=None,\n    report=None,\n    maintenance_interval=10,\n    verbose=False,\n    debug=False,\n    **samplerargs\n):\n    \"\"\"Run the emcee ensemble MCMC sampler.\n\n    Parameters:\n    ----------\n\n    p0 : ndarray of initial states of the walkers in the parameterspace\n    moves : emcee.moves object\n    lprob_seed : lprob_seed must be one of ('vec', 'rand', 'set').\n    \"\"\"\n\n    import emcee\n    from grgrlib.multiprocessing import serializer\n\n    if not hasattr(self, \"ndim\"):\n        # if it seems to be missing, lets do it.\n        # but without guarantee...\n        self.prep_estim(load_R=True)\n\n    if seed is None:\n        seed = self.fdict[\"seed\"]\n\n    self.tune = tune\n    if tune is None:\n        self.tune = int(nsteps * 1 / 5.0)\n\n    if update_freq is None:\n        update_freq = int(nsteps / 5.0)\n\n    if linear is None:\n        linear = self.filter.name == \"KalmanFilter\"\n\n    if \"description\" in self.fdict.keys():\n        self.description = self.fdict[\"description\"]\n\n    if hasattr(self, \"pool\"):\n        from .estimation import create_pool\n\n        create_pool(self)\n\n    lprob_global = serializer(self.lprob)\n\n    if isinstance(temp, bool) and not temp:\n        temp = 1\n\n    def lprob(par):\n        return lprob_global(\n            par,\n            linear=linear,\n            verbose=verbose,\n            temp=temp,\n            lprob_seed=lprob_seed or \"set\",\n        )\n\n    bnd = np.array(self.fdict[\"prior_bounds\"])\n\n    if self.pool:\n        self.pool.clear()\n\n    if p0 is None and not resume:\n        if temp < 1:\n            p0 = get_par(\n                self,\n                \"prior_mean\",\n                asdict=False,\n                full=False,\n                nsample=nwalks,\n                verbose=verbose,\n            )\n        else:\n            p0 = get_par(\n                self, \"best\", asdict=False, full=False, nsample=nwalks, verbose=verbose\n            )\n    elif not resume:\n        nwalks = p0.shape[0]\n\n    if backend:\n\n        if isinstance(backend, str):\n            # backend_file will only be loaded later if explicitely defined before\n            self.fdict[\"backend_file\"] = backend\n        try:\n            backend = self.fdict[\"backend_file\"]\n        except KeyError:\n            # this is the default case\n            suffix = str(suffix) if suffix else \"_sampler.h5\"\n            backend = os.path.join(self.path, self.name + suffix)\n\n            if os.path.exists(backend) and not (resume or append):\n                print(\n                    \"[mcmc:]\".ljust(15, \" \")\n                    + \" HDF backend at %s already exists. Deleting...\" % backend\n                )\n                os.remove(backend)\n\n        backend = emcee.backends.HDFBackend(backend)\n\n        if not (resume or append):\n            if not nwalks:\n                raise TypeError(\n                    \"If neither `resume`, `append` or `p0` is given I need to know the number of walkers (`nwalks`).\"\n                )\n            try:\n                backend.reset(nwalks, self.ndim)\n            except KeyError as e:\n                raise KeyError(str(e) + \". Your `*.h5` file is likely to be damaged...\")\n    else:\n        backend = None\n\n    if resume:\n        nwalks = backend.get_chain().shape[1]\n\n    if debug:\n        sampler = emcee.EnsembleSampler(nwalks, self.ndim, lprob)\n    else:\n        sampler = emcee.EnsembleSampler(\n            nwalks, self.ndim, lprob, moves=moves, pool=self.pool, backend=backend\n        )\n\n    if resume and not p0:\n        p0 = sampler.get_last_sample()\n\n    self.sampler = sampler\n    self.temp = temp\n\n    if not verbose:\n        np.warnings.filterwarnings(\"ignore\")\n\n    if verbose > 2:\n        report = report or print\n    else:\n        pbar = tqdm.tqdm(total=nsteps, unit=\"sample(s)\", dynamic_ncols=True)\n        report = report or pbar.write\n\n    old_tau = np.inf\n    cnt = 0\n\n    for result in sampler.sample(p0, iterations=nsteps, **samplerargs):\n\n        if not verbose:\n            lls = list(result)[1]\n            maf = np.mean(sampler.acceptance_fraction[-update_freq:]) * 100\n            pbar.set_description(\n                \"[ll/MAF:%s(%1.0e)/%1.0f%%]\" % (str(np.max(lls))[:7], np.std(lls), maf)\n            )\n\n        if cnt and update_freq and not cnt % update_freq:\n\n            prnttup = \"[mcmc:]\".ljust(\n                15, \" \"\n            ) + \"Summary from last %s of %s iterations\" % (update_freq, cnt)\n\n            if temp < 1:\n                prnttup += \" with temp of %s%%\" % (np.round(temp * 100, 6))\n\n            if self.description is not None:\n                prnttup += \" (%s)\" % str(self.description)\n\n            prnttup += \":\"\n\n            report(prnttup)\n\n            sample = sampler.get_chain()\n\n            tau = emcee.autocorr.integrated_time(sample, tol=0)\n            min_tau = np.min(tau).round(2)\n            max_tau = np.max(tau).round(2)\n            dev_tau = np.max(np.abs(old_tau - tau) / tau)\n\n            tau_sign = \">\" if max_tau > sampler.iteration / 50 else \"<\"\n            dev_sign = \">\" if dev_tau > 0.01 else \"<\"\n\n            self.mcmc_summary(\n                chain=sample,\n                tune=update_freq,\n                calc_mdd=False,\n                calc_ll_stats=True,\n                out=lambda x: report(str(x)),\n            )\n\n            report(\n                \"Convergence stats: tau is in (%s,%s) (%s%s) and change is %s (%s0.01).\"\n                % (\n                    min_tau,\n                    max_tau,\n                    tau_sign,\n                    sampler.iteration / 50,\n                    dev_tau.round(3),\n                    dev_sign,\n                )\n            )\n\n        if cnt and update_freq and not (cnt + 1) % update_freq:\n            sample = sampler.get_chain()\n            old_tau = emcee.autocorr.integrated_time(sample, tol=0)\n\n        if not verbose:\n            pbar.update(1)\n\n        # avoid mem leakage\n        if cnt and not cnt % maintenance_interval:\n            self.pool.clear()\n\n        cnt += 1\n\n    pbar.close()\n    if self.pool:\n        self.pool.close()\n\n    if not verbose:\n        np.warnings.filterwarnings(\"default\")\n\n    log_probs = sampler.get_log_prob()[-self.tune :]\n    chain = sampler.get_chain()[-self.tune :]\n    chain = chain.reshape(-1, chain.shape[-1])\n\n    arg_max = log_probs.argmax()\n    mode_f = log_probs.flat[arg_max]\n    mode_x = chain[arg_max].flatten()\n\n    if temp == 1:\n\n        self.fdict[\"mcmc_mode_x\"] = mode_x\n        self.fdict[\"mcmc_mode_f\"] = mode_f\n\n        if \"mode_f\" in self.fdict.keys() and mode_f < self.fdict[\"mode_f\"]:\n            print(\n                \"[mcmc:]\".ljust(15, \" \")\n                + \" New mode of %s is below old mode of %s. Rejecting...\"\n                % (mode_f, self.fdict[\"mode_f\"])\n            )\n        else:\n            self.fdict[\"mode_x\"] = mode_x\n            self.fdict[\"mode_f\"] = mode_f\n\n    self.fdict[\"datetime\"] = str(datetime.now())\n\n    return\n\n\ndef tmcmc(\n    self,\n    nsteps,\n    nwalks,\n    ntemps,\n    target,\n    update_freq=False,\n    test_lprob=False,\n    verbose=True,\n    debug=False,\n    **mcmc_args\n):\n    \"\"\"Run Tempered Ensemble MCMC\n\n    Parameters\n    ----------\n    ntemps : int\n    target : float\n    nsteps : float\n    \"\"\"\n\n    from grgrlib.core import map2arr\n    from .mpile import prior_sampler\n\n    update_freq = update_freq if update_freq <= nsteps else False\n\n    # sample pars from prior\n    pars = prior_sampler(\n        self, nwalks, test_lprob=test_lprob, verbose=max(verbose, 2 * debug)\n    )\n\n    x = get_par(self, \"prior_mean\", asdict=False, full=False, verbose=verbose > 1)\n\n    pbar = tqdm.tqdm(total=ntemps, unit=\"temp(s)\", dynamic_ncols=True)\n    tmp = 0\n\n    for i in range(ntemps):\n\n        # update tmp\n        ll = self.lprob(x)\n        lp = self.lprior(x)\n\n        tmp = tmp * (ntemps - i - 1) / (ntemps - i) + (target - lp) / (ntemps - i) / (\n            ll - lp\n        )\n        aim = lp + (ll - lp) * tmp\n\n        if tmp >= 1:\n            # print only once\n            pbar.write(\n                \"[tmcmc:]\".ljust(15, \" \")\n                + \"Increasing temperature to %s°. Too hot! I'm out...\"\n                % np.round(100 * tmp, 3)\n            )\n            pbar.update()\n            self.temp = 1\n            # skip for-loop to exit\n            continue\n\n        pbar.write(\n            \"[tmcmc:]\".ljust(15, \" \")\n            + \"Increasing temperature to %2.5f°, aiming @ %4.3f.\" % (100 * tmp, aim)\n        )\n        pbar.set_description(\"[tmcmc: %2.3f°\" % (100 * tmp))\n\n        self.mcmc(\n            p0=pars,\n            nsteps=nsteps,\n            temp=tmp,\n            update_freq=update_freq,\n            verbose=verbose > 1,\n            append=i,\n            report=pbar.write,\n            debug=debug,\n            **mcmc_args\n        )\n\n        self.temp = tmp\n        self.mcmc_summary(tune=int(nsteps / 10), calc_mdd=False, calc_ll_stats=True)\n\n        pbar.update()\n\n        pars = self.get_chain()[-1]\n        lprobs_adj = self.get_log_prob()[-1]\n        x = pars[lprobs_adj.argmax()]\n\n    pbar.close()\n    self.fdict[\"datetime\"] = str(datetime.now())\n\n    return pars\n", "meta": {"hexsha": "b476afdaa1c26d2b63ab9795e5f1065f99b5f37c", "size": 9494, "ext": "py", "lang": "Python", "max_stars_repo_path": "pydsge/mcmc.py", "max_stars_repo_name": "pcschreiber1/pydsge_OSE_Project_Fork", "max_stars_repo_head_hexsha": "4222dbe187e47958d2f5b732615c9ba97547f67a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pydsge/mcmc.py", "max_issues_repo_name": "pcschreiber1/pydsge_OSE_Project_Fork", "max_issues_repo_head_hexsha": "4222dbe187e47958d2f5b732615c9ba97547f67a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-12-31T16:27:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-27T17:16:19.000Z", "max_forks_repo_path": "pydsge/mcmc.py", "max_forks_repo_name": "pcschreiber1/pydsge_OSE_Project_Fork", "max_forks_repo_head_hexsha": "4222dbe187e47958d2f5b732615c9ba97547f67a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0824175824, "max_line_length": 117, "alphanum_fraction": 0.5241204972, "include": true, "reason": "import numpy", "num_tokens": 2393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19507638209139166}}
{"text": "# -*- coding: utf-8 -*-\n# Copyright (c) Vlachos Group, Jung Group\n# GNU v3.0 license\n\n__author__ = 'Geun Ho Gu'\n__copyright__ = \"Copyright 2019, Vlachos Group, Jung Group\"\n__version__ = \"1.0\"\n__maintainer__ = \"Geun Ho Gu\"\n__email__ = \"googhgoo@hotmail.com\"\n__date__ = \"July 31, 2019\"\n\nimport tensorflow as tf\nimport numpy as np\n\n__all__ = [\n        'ModelBuilder',\n        ]\n\nclass ModelBuilder(object):\n    def __init__(self,n_occupancy,n_neighbor_sites_list,n_permutation_list,\\\n                 X_mean, X_std, Y_mean, Y_std,\n                 n_conv=1,n_feature=150,sitewise_n_feature=25,\n                 ):\n        \"\"\"\n        Model builder. \n        \n        Parameters\n        ----------\n        n_occupancy: int. number of possible occupancy\n        n_neighbor_sites_list: list of int. Number of neighbors of each site. \n        X_mean : no. list of float. Mean of the one hot encoding matrix by column.\n            no is the number of occupancy state.\n        X_std : no. list of float. Standard deviation of the one hot encoding matrix by column.\n        Y_mean : float. Mean of target property\n        Y_std : float. Standard deviation of target property\n        nconv: int. number of convolutions performed\n        n_feature: int. number of feature for each site\n        sitewise_n_feature: int. number of features for atoms for site-wise activation\n        \"\"\"\n        tf.Graph()\n        tf.reset_default_graph()\n        # Not to be used within the graph.. Used in Trainer. \n        if X_mean is None: # None is used when evaluation mode is activated\n            self.X_mean = tf.get_variable('X_mean',\n                shape=(n_occupancy,),trainable=False)\n            self.X_std = tf.get_variable('X_std',\n                shape=(n_occupancy,),trainable=False)\n            self.Y_mean = tf.get_variable('Y_mean',\n                shape=(),trainable=False)\n            self.Y_std = tf.get_variable('Y_std',\n                shape=(),trainable=False)\n        else:\n            self.X_mean = tf.get_variable('X_mean',\n                initializer=tf.convert_to_tensor(np.array(X_mean,dtype=np.float32)),\n                trainable=False)\n            self.X_std = tf.get_variable('X_std',\n                initializer=tf.convert_to_tensor(np.array(X_std,dtype=np.float32)),\n                trainable=False)\n            self.Y_mean = tf.get_variable('Y_mean',\n                initializer=tf.convert_to_tensor(np.array(Y_mean,dtype=np.float32)),\n                trainable=False)\n            self.Y_std = tf.get_variable('Y_std',\n                initializer=tf.convert_to_tensor(np.array(Y_std,dtype=np.float32)),\n                trainable=False)\n        \n        \n        self.Y = tf.placeholder(dtype=tf.float32, shape = [None])\n        self.Idx_config = tf.placeholder(dtype=tf.int32, shape = [None,1])\n        self.N_Sites = tf.placeholder(dtype=tf.int32, shape = ())\n        self.N_Sites_per_config = tf.placeholder(dtype=tf.float32, shape = [None])\n        self.X_Sites = tf.placeholder(dtype=tf.float32, shape = [None,n_occupancy])\n        \n        \n        self.X_NSs = []\n        for n_neighbor_sites,n_permutation in zip(n_neighbor_sites_list,n_permutation_list):\n            self.X_NSs.append(tf.placeholder(dtype=tf.int32, shape = [None,n_permutation,n_neighbor_sites]))\n        self.X_NSs = tuple(self.X_NSs)\n        self.Lambda = tf.placeholder(dtype=tf.float32, shape = [])\n        self.Dropout_rate = tf.placeholder(dtype=tf.float32, shape = [])\n        self.is_training = tf.placeholder(dtype=tf.bool, shape = [])\n        \n        \"\"\" initiaite Model Helper \"\"\"\n        self.ModelHelper = CNNHelper(dropout_rate = self.Dropout_rate, UseBN=True,is_training=self.is_training)\n\n        \"\"\" keeps tracks of site layer \"\"\"\n        self.SiteLayer = [self.X_Sites]\n\n        \"\"\" Featurize one-hot-encoding \"\"\"\n        #self.SiteLayer.append(self.ModelHelper.Atom_Wise_Linear(self.X_Sites,n_feature))\n        \n        \"\"\" Perform Convolution \"\"\"\n        for i in range(0,n_conv):\n            self.SiteLayer.append(self.ModelHelper.LCNNConvolution(self.SiteLayer[-1],self.X_NSs,self.N_Sites,depth=n_feature))    \n        self.SiteLayer.append(self.ModelHelper.Atom_Wise_Convolution(self.SiteLayer[-1],depth=sitewise_n_feature))\n        \n        \"\"\" Perform Linear Multiplication \"\"\"            \n        self.Y_atom_wise = tf.expand_dims(tf.reduce_sum(self.ModelHelper.Atom_Wise_Linear(self.SiteLayer[-1]),axis=1),axis=1)\n        \n        \"\"\" Sum up contributions \"\"\"\n        self.Y_conf_wise = self.ModelHelper.Unflatten(self.Y_atom_wise,self.Idx_config,self.N_Sites_per_config)\n        \n        \"\"\" Loss + L2 norm \"\"\"\n        Params = self.ModelHelper.Params\n        Params = tf.concat(Params,0)\n        self.Loss = tf.losses.mean_squared_error(labels=self.Y, predictions=self.Y_conf_wise) + self.Lambda*tf.norm(Params)\n    \n    def GetStatistics(self):\n        \"\"\"Returns statistics for site layer and target property. Used in trainer in Train.py\n        \"\"\"\n        return self.X_mean,self.X_std,self.Y_mean,self.Y_std\n    \n\n\nclass CNNHelper(object):\n    \"\"\"This code is a helper for constructing CNN model.\n    \"\"\"\n    def __init__(self,dropout_rate = tf.constant(1,dtype=tf.float32) ,UseBN = False, is_training = None,e = 1e-3,initializer=tf.contrib.layers.xavier_initializer()):\n        \"\"\"\n        Initialize a CNN model builder. For the low level tensorflow models, \n        keeping track of model weights can be difficult. This code automates\n        this process. \n        \n        parameters\n        ----------\n        dropout_rate: 0D tensor. drop out rate\n        UseBN: boolean . Flag for using batch normalization. Recommended to turn it on.\n        is_training: 0D placeholder boolean tensor. Whether training or not. Used for batch norm\n        e: float. This is a offset value for batch normalization for convergence\n        initializer: tensorflow intializer class. tensorflow initializer for weights. Default(xavier) works well\n        \"\"\"\n        if UseBN and is_training == None:\n            raise NotImplemented('When Batch normalization is used, is_training boolean placeholder must be provided')\n        self.e = e\n        self.init = initializer\n        self.UseBN = UseBN\n        self._nCNNLayer = 0  # Number of CNN layers\n        self.dropout_rate = dropout_rate\n        self.Params = []\n        self.is_training = is_training\n        \n   \n    def LCNNConvolution(self,X_Sites, X_NSs, N_Sites, depth=1):\n        \"\"\"Construct convolution layer\n        \n        parameters\n        ----------\n        X_Sites: 2D tensor of shape (?,one hot encoding classification size)\n            Site layer flattened over data index\n        \n        X_NSs: 3D tensor list of (?,number of permutation, 1 (site itself) + number of neighbors)\n              given that the shape is (x,y,z), x is the site index which has been\n              flattened over data, y is the permutation index, and z is the\n              site itself index and neighbor site index. \n        \n        depth: int. depth/feature of convolution\n    \n        Return\n        ----------\n        X_Sites: 2D tensor\n          Convoluted tensor\n        \"\"\"\n        \n        with tf.variable_scope(\"layer\"+str(self._nCNNLayer)):\n            indices = []\n            updates = []\n            for i in range(0,len(X_NSs)): # iterating over each site type\n                \n                with tf.variable_scope(\"site\"+str(i)):\n                    X_NSs_i = X_NSs[i]\n                    # Apply permutations\n                    # X_Sites_Permed : R^Number of Site x Permutation Index x Neighbor Indicex x Depth\n                    X_Sites_Permed = tf.gather(X_Sites,X_NSs_i,axis=0)\n                    # X_Sites_Concatenated : R^Number of Site x Permutation Index x (Neighbor Indicex x Depth)\n                    X_Sites_Concatenated = tf.reshape(X_Sites_Permed,[-1,X_Sites_Permed.shape[1],X_Sites_Permed.shape[2]*X_Sites_Permed.shape[3]])\n                    ## Filter shape: [filter height, in_channels, out_channels] \n                    ## Stride shape: Filter height\n                    w = tf.get_variable(\"w\",[1,X_Sites_Concatenated.shape[2],depth],dtype=tf.float32,initializer=self.init)\n                    self.Params.append(tf.reshape(w,[-1]))\n                    b = tf.get_variable(\"b\",[depth],dtype=tf.float32,initializer=self.init)\n                    self.Params.append(tf.reshape(b,[-1]))\n        \n                    Conv1d = tf.nn.conv1d(X_Sites_Concatenated,w,1,\"SAME\")\n                    Conv1dB = tf.nn.bias_add(Conv1d,b)\n                    ## Batch Normalization\n                    # See https://stackoverflow.com/questions/33949786/how-could-i-use-batch-normalization-in-tensorflow/38320613#38320613\n                    if self.UseBN:\n                        u = tf.get_variable(\"u\",[1,1,depth],dtype=tf.float32,initializer=self.init)\n                        v = tf.get_variable(\"v\",[1,1,depth],dtype=tf.float32,initializer=self.init)\n                        def updateuv():\n                            ut,vt = tf.nn.moments(Conv1dB,[0,1],keep_dims=True)\n                            return (u.assign(ut),v.assign(vt))\n                        u,v = tf.cond(self.is_training,updateuv,lambda: (u,v))\n        \n                        o = tf.get_variable(\"o\",[1,1,depth],dtype=tf.float32,initializer=self.init)\n                        self.Params.append(tf.reshape(o,[-1]))\n                        s = tf.get_variable(\"s\",[1,1,depth],dtype=tf.float32,initializer=self.init)\n                        self.Params.append(tf.reshape(s,[-1]))\n                        Conv1dBN = tf.nn.batch_normalization(Conv1dB,u,v,o,s,self.e)\n                    X_Sites1 = activation(Conv1dBN)\n                    X_Sites2 = tf.nn.dropout(X_Sites1,self.dropout_rate,noise_shape=[1,1,depth]) # Dropout\n                    X_Sites3 = tf.reduce_sum(X_Sites2,axis=1) # Sum over each permutations\n                    indices.append(X_NSs_i[:,0,0])\n                    updates.append(X_Sites3)\n            # gather over multiple site types\n            indices = tf.expand_dims(tf.concat(indices,axis=0),1)\n            updates = tf.concat(updates,axis=0)\n            NewSiteLayer = tf.scatter_nd(indices,updates,[N_Sites,depth])\n            self._nCNNLayer += 1\n            return NewSiteLayer\n    \n\n    def Atom_Wise_Linear(self,X_Sites, depth=1):\n        \"\"\"\n        Perform Matrix Multiplication\n        \n        parameters\n        ----------\n        X_Sites: 2D tensor of shape (?,one hot encoding classification size)\n            Site layer flattened over data index\n        \n        depth: int. depth/feature of convolution\n    \n        return\n        ------\n        X_Sites: 2D tensor. Convoluted tensor\n        \"\"\"\n        with tf.variable_scope(\"layer\"+str(self._nCNNLayer)):\n            ## Filter shape: [filter height, in_channels, out_channels] \n            ## Stride shape: Filter height\n            w = tf.get_variable(\"w\",[X_Sites.shape[1],depth],dtype=tf.float32,initializer=self.init)\n            self.Params.append(tf.reshape(w,[-1]))\n            b = tf.get_variable(\"b\",[depth],dtype=tf.float32,initializer=self.init)\n            self.Params.append(tf.reshape(b,[-1]))\n\n            X_Sites = tf.matmul(X_Sites,w)\n            X_Sites = tf.nn.bias_add(X_Sites,b)\n\n            self._nCNNLayer += 1\n            return X_Sites\n\n\n    def Atom_Wise_Convolution(self,X_Sites, depth=1):\n        \"\"\"\n        Perform self convolution to a site layer.\n        \n        parameters\n        ----------\n        X_Sites: 2D tensor of shape (?,one hot encoding classification size)\n            Site layer flattened over data index\n        depth: int. depth of convolution\n        \"\"\"\n        \n        with tf.variable_scope(\"layer\"+str(self._nCNNLayer)):\n            ## Filter shape: [filter height, in_channels, out_channels] \n            ## Stride shape: Filter height\n            w = tf.get_variable(\"w\",[X_Sites.shape[1],depth],dtype=tf.float32,initializer=self.init)\n            self.Params.append(tf.reshape(w,[-1]))\n            b = tf.get_variable(\"b\",[depth],dtype=tf.float32,initializer=self.init)\n            self.Params.append(tf.reshape(b,[-1]))\n\n            Conv = tf.matmul(X_Sites,w)\n            Conv = tf.nn.bias_add(Conv,b)\n            ## Batch Normalization\n            if self.UseBN:\n                u = tf.get_variable(\"u\",[1,depth],dtype=tf.float32,initializer=self.init)\n                v = tf.get_variable(\"v\",[1,depth],dtype=tf.float32,initializer=self.init)\n                def updateuv():\n                    ut,vt = tf.nn.moments(Conv,[0],keep_dims=True)\n                    return (u.assign(ut),v.assign(vt))\n                u,v = tf.cond(self.is_training,updateuv,lambda: (u,v))\n                \n                o = tf.get_variable(\"o\",[1,depth],dtype=tf.float32,initializer=self.init)\n                self.Params.append(tf.reshape(o,[-1]))\n                s = tf.get_variable(\"s\",[1,depth],dtype=tf.float32,initializer=self.init)\n                self.Params.append(tf.reshape(s,[-1]))\n                Conv = tf.nn.batch_normalization(Conv,u,v,o,s,self.e)\n            X_Sites = activation(Conv)\n            X_Sites = tf.nn.dropout(X_Sites,self.dropout_rate,noise_shape=[1,depth]) # Dropout\n            \n            self._nCNNLayer += 1\n            return X_Sites\n\n    def SoftMax(self,X_Sites,depth = 1):\n        \"\"\"Perform Convolution to a site layer.\n        \n        parameters\n        ----------\n        X_Sites: 2D tensor of shape (?,one hot encoding classification size)\n            Site layer flattened over data index\n        depth: int. depth/features of the softmax\n          \n        return\n        ------\n        X_Sites: 2D tensor. softmaxed sitelayer\n        \"\"\"\n        with tf.variable_scope(\"SoftMax\"):\n            w = tf.get_variable(\"w\",[X_Sites.shape[1],depth],dtype=tf.float32,initializer=self.init)\n            self.Params.append(tf.reshape(w,[-1]))\n            b = tf.get_variable(\"b\",[depth],dtype=tf.float32,initializer=self.init)\n            self.Params.append(tf.reshape(b,[-1]))\n            X_Sites = tf.matmul(X_Sites,w)\n            X_Sites = tf.nn.bias_add(X_Sites,b)\n            if self.UseBN:\n                u = tf.get_variable(\"u\",[1,depth],dtype=tf.float32,initializer=self.init)\n                v = tf.get_variable(\"v\",[1,depth],dtype=tf.float32,initializer=self.init)\n                def updateuv():\n                    ut,vt = tf.nn.moments(X_Sites,[0],keep_dims=True)\n                    return (u.assign(ut),v.assign(vt))\n                u,v = tf.cond(self.is_training,updateuv,lambda: (u,v))\n                \n                o = tf.get_variable(\"o\",[1,depth],dtype=tf.float32,initializer=self.init)\n                self.Params.append(tf.reshape(o,[-1]))\n                s = tf.get_variable(\"s\",[1,depth],dtype=tf.float32,initializer=self.init)\n                self.Params.append(tf.reshape(s,[-1]))\n                X_Sites = tf.nn.batch_normalization(X_Sites,u,v,o,s,self.e)\n            X_Sites = tf.nn.softmax(X_Sites,1)\n            return X_Sites\n    \n    def Unflatten(self,X_Sites,Idx_config,N_Sites):\n        \"\"\"This function unflattens the flattened site layer by summation. Then\n        the unflattened values are dvidided by number of sites. \n        \n        parameters\n        ----------\n        X_Sites: 2D tensor. Site layer flattened over data index\n        Idx_config: 1D tensor of integer. In the algorithm, Site layer is \n            flattened over each data points. This way, we avoid using padding, \n            and having an upper limit for the maximum number of sites. calculations \n            are faster, too. To do this, we need data index for each site.\n            This vector contains that information.\n          \n        N_Sites: 1D tensor. Each integer indicates number of sites in each\n            configuration. Used to compute per site formation energy\n          \n        return\n        ------\n        ConfigLayer: 1D tensor. Unflattened per each datum\n        \n        \"\"\"\n        # All the other failed attempts to densifying X_Sites\n#        ConfigLayer = tf.Variable(tf.zeros([Idx_config[-1]+1,X_Sites.shape[1]]), tf.float32)\n#        ConfigLayer = tf.Variable(tf.zeros([N_Sites.get_shape()[0],X_Sites.shape[1]]), tf.float32)\n#        ConfigLayer = tf.fill([Idx_config[-1]+1,X_Sites.shape[1]],0.0)\n#        ConfigLayer = tf.scatter_add(ConfigLayer,Idx_config,X_Sites)\n#        ConfigLayer = tf.scatter_nd(Idx_config,X_Sites,[Idx_config[-1]+1,X_Sites.shape[1]])\n#        ConfigLayer = tf.scatter_nd(Idx_config,X_Sites,[N_Sites.shape[0],X_Sites.shape[1]])\n#        ConfigLayer = tf.scatter_nd(Idx_config,X_Sites,[Idx_config[-1]+1,tf.constant([1])])\n#        ConfigLayer = tf.scatter_nd(Idx_config,X_Sites,[Idx_config[-1]+1,[1]])\n#        ConfigLayer = tf.scatter_nd(Idx_config,X_Sites,Idx_config[-1]+1)\n#        ConfigLayer = tf.scatter_nd(Idx_config,X_Sites,[1,1])\n        ConfigLayer = tf.scatter_nd(Idx_config,X_Sites,[tf.reshape(Idx_config[-1]+1,[]),X_Sites.shape[1]])\n        ConfigLayer = tf.reshape(ConfigLayer,[-1])\n        ConfigLayer = tf.div(ConfigLayer,N_Sites)\n        return ConfigLayer\n        \ndef activation(tensor):\n    \"\"\"Return activation function\"\"\"\n    return tf.nn.softplus(tensor)-np.log(2.0)", "meta": {"hexsha": "a2f3e330dfef13351450807a9a6d05b287af77f7", "size": 17193, "ext": "py", "lang": "Python", "max_stars_repo_path": "lcnn/model/Models.py", "max_stars_repo_name": "VlachosGroup/lcnn", "max_stars_repo_head_hexsha": "90bec040296b8faa4c28230cbc440df8185da715", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-03-27T22:34:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-20T13:49:09.000Z", "max_issues_repo_path": "lcnn/model/Models.py", "max_issues_repo_name": "VlachosGroup/lcnn", "max_issues_repo_head_hexsha": "90bec040296b8faa4c28230cbc440df8185da715", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-08-01T04:13:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-16T04:52:36.000Z", "max_forks_repo_path": "lcnn/model/Models.py", "max_forks_repo_name": "VlachosGroup/lcnn", "max_forks_repo_head_hexsha": "90bec040296b8faa4c28230cbc440df8185da715", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.0251396648, "max_line_length": 165, "alphanum_fraction": 0.5970453091, "include": true, "reason": "import numpy", "num_tokens": 3971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19507638209139166}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"QLearning.ipynb\n\nAutomatically generated by Colaboratory.\n\"\"\"\n\n#remove \" > /dev/null 2>&1\" to see what is going on under the hood\n# !pip install gym pyvirtualdisplay > /dev/null 2>&1\n# !apt-get install -y xvfb python-opengl ffmpeg > /dev/null 2>&1\n\n# !apt-get update > /dev/null 2>&1\n# !apt-get install cmake > /dev/null 2>&1\n# !pip install --upgrade setuptools 2>&1\n# !pip install ez_setup > /dev/null 2>&1\n# !pip install gym[atari] > /dev/null 2>&1\n\nimport gym\nfrom gym import logger as gymlogger\nfrom gym.wrappers import Monitor\ngymlogger.set_level(40) #error only\nimport numpy as np\nimport random\nimport matplotlib\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nimport glob\nimport io\nimport base64\nfrom IPython.display import HTML\n\nfrom IPython import display as ipythondisplay\n\nfrom pyvirtualdisplay import Display\ndisplay = Display(visible=0, size=(1400, 900))\ndisplay.start()\n\n\"\"\"\nUtility functions to enable video recording of gym environment and displaying it\nTo enable video, just do \"env = wrap_env(env)\"\"\n\"\"\"\n\ndef show_video():\n  mp4list = glob.glob('video/*.mp4')\n  if len(mp4list) > 0:\n    mp4 = mp4list[0]\n    video = io.open(mp4, 'r+b').read()\n    encoded = base64.b64encode(video)\n    ipythondisplay.display(HTML(data='''<video alt=\"test\" autoplay \n                loop controls style=\"height: 400px;\">\n                <source src=\"data:video/mp4;base64,{0}\" type=\"video/mp4\" />\n             </video>'''.format(encoded.decode('ascii'))))\n  else: \n    print(\"Could not find video\")\n    \n\ndef wrap_env(env):\n  env = Monitor(env, './video', force=True)\n  return env\n\nenv = wrap_env(gym.make('MountainCar-v0'))\nenv.reset()\n\n#check out the Mountain Car action space!\nprint(env.action_space)\n\ndef QLearning(env, learning, discount, epsilon, min_eps, episodes):\n    # Determine size of discretized state space\n    num_states = (env.observation_space.high - env.observation_space.low)*\\\n                    np.array([10, 100])\n    num_states = np.round(num_states, 0).astype(int) + 1\n    \n    # Initialize Q table\n    Q = np.random.uniform(low = -1, high = 1, \n                          size = (num_states[0], num_states[1], \n                                  env.action_space.n))\n    \n    # Initialize variables to track rewards\n    reward_list = []\n    ave_reward_list = []\n    \n    # Calculate episodic reduction in epsilon\n    reduction = (epsilon - min_eps)/episodes\n    \n    # Run Q learning algorithm\n    for i in range(episodes):\n        # Initialize parameters\n        done = False\n        tot_reward, reward = 0,0\n        state = env.reset()\n        \n        # Discretize state\n        state_adj = (state - env.observation_space.low)*np.array([10, 100])\n        state_adj = np.round(state_adj, 0).astype(int)\n    \n        while done != True:   \n            # Render environment for last five episodes\n            if i >= (episodes - 20):\n                env.render()\n                \n            # Determine next action - epsilon greedy strategy\n            if np.random.random() < 1 - epsilon:\n                action = np.argmax(Q[state_adj[0], state_adj[1]]) \n            else:\n                action = np.random.randint(0, env.action_space.n)\n                \n            # Get next state and reward\n            state2, reward, done, info = env.step(action) \n            \n            # Discretize state2\n            state2_adj = (state2 - env.observation_space.low)*np.array([10, 100])\n            state2_adj = np.round(state2_adj, 0).astype(int)\n            \n            #Allow for terminal states\n            if done and state2[0] >= 0.5:\n                Q[state_adj[0], state_adj[1], action] = reward\n                \n            # Adjust Q value for current state\n            else:\n                delta = learning*(reward + \n                                 discount*np.max(Q[state2_adj[0], \n                                                   state2_adj[1]]) - \n                                 Q[state_adj[0], state_adj[1],action])\n                Q[state_adj[0], state_adj[1],action] += delta\n                                     \n            # Update variables\n            tot_reward += reward\n            state_adj = state2_adj\n        \n        # Decay epsilon\n        if epsilon > min_eps:\n            epsilon -= reduction\n        \n        # Track rewards\n        reward_list.append(tot_reward)\n        \n        if (i+1) % 100 == 0:\n            ave_reward = np.mean(reward_list)\n            ave_reward_list.append(ave_reward)\n            reward_list = []\n            \n        if (i+1) % 100 == 0:    \n            print('Episode {} Average Reward: {}'.format(i+1, ave_reward))\n            \n    env.close()\n    \n    return ave_reward_list\n\n# Run Q-learning algorithm\nrewards = QLearning(env, 0.2, 0.9, 0.8, 0, 10000)\n\n# Plot Rewards\nplt.plot(100*(np.arange(len(rewards)) + 1), rewards)\nplt.xlabel('Episodes')\nplt.ylabel('Average Reward')\nplt.title('Average Reward vs Episodes')\nplt.savefig('rewards.jpg') \nplt.show()\nplt.close()\nshow_video()\n\n", "meta": {"hexsha": "ad5a7120240c38d2c853fc8e2388f74abcf423da", "size": 5006, "ext": "py", "lang": "Python", "max_stars_repo_path": "QLearning.py", "max_stars_repo_name": "DhruvUpadhyay/MointainCar-QLearning", "max_stars_repo_head_hexsha": "de95b18653cbb6372d0a50954520942a5dffa364", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-22T17:00:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-22T17:00:32.000Z", "max_issues_repo_path": "QLearning.py", "max_issues_repo_name": "DhruvUpadhyay/MointainCar-QLearning", "max_issues_repo_head_hexsha": "de95b18653cbb6372d0a50954520942a5dffa364", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QLearning.py", "max_forks_repo_name": "DhruvUpadhyay/MointainCar-QLearning", "max_forks_repo_head_hexsha": "de95b18653cbb6372d0a50954520942a5dffa364", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-21T05:37:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-30T17:08:15.000Z", "avg_line_length": 31.0931677019, "max_line_length": 81, "alphanum_fraction": 0.5783060328, "include": true, "reason": "import numpy", "num_tokens": 1228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.19507638209139164}}
{"text": "import os\n\nimport sympy.physics.units.definitions as u\nfrom sympy.physics.units.quantities import Quantity\nfrom sympy.physics.units.systems.si import dimsys_SI\n\nfrom mathpad.val import Val\nimport mathpad.dimensions as dims\n\nHERE = os.path.dirname(__file__)\n\nAUTOGEN_WARNING = '\"WARNING: this file was automatically generated by commented code within mathpad.py, and then modified slightly\"\\n'\n\nprint(\"writing to \" + f\"{HERE}/units.py\\nand {HERE}/constants.py\")\n\nwith open(f\"{HERE}/units.py\", \"w\") as units_f, open(\n    f\"{HERE}/constants.py\", \"w\"\n) as constants_f:\n\n    # top of 'units.py'\n    units_f.write(AUTOGEN_WARNING)\n    units_f.write(\"import sympy.physics.units.definitions.unit_definitions as u\\n\")\n    units_f.write(\"from mathpad.physical_quantities import *\\n\")\n\n    # top of 'constants.py'\n    constants_f.write(AUTOGEN_WARNING)\n    constants_f.write(\"import sympy.physics.units.definitions.unit_definitions as u\\n\")\n    constants_f.write(\"from mathpad.physical_quantities import *\\n\")\n\n    for name in dir(u):\n        qty = getattr(u, name)\n\n        if name.endswith(\"constant\"):\n            constants_f.write(\n                f\"\"\"\n{name} = OutputVal(u.{name})\"\"\"\n            )\n\n        elif isinstance(qty, Quantity):\n\n            for quantity_cls_name in dir(dims):\n                if quantity_cls_name in \"du\":\n                    continue\n\n                quantity_cls = getattr(dims, quantity_cls_name)\n\n                # handle the Angle dimension specially\n                if str(qty).startswith(\"angular\") or str(qty).startswith(\"rad\"):\n                    units_f.write(\n                        f\"\"\"\n{name} = Angle(u.{name})\"\"\"\n                    )\n                    break\n\n                elif (\n                    isinstance(quantity_cls, type)\n                    and issubclass(quantity_cls, Val)\n                    and quantity_cls is not Val\n                    and dimsys_SI.equivalent_dims(qty.dimension, quantity_cls.dimension)\n                ):\n                    units_f.write(\n                        f\"\"\"\n{name} = {quantity_cls_name}(u.{name})\"\"\"\n                    )\n                    break\n            else:\n                print(f\"Warning: Quantity '{name}' could not be matched; skipping...\")\n", "meta": {"hexsha": "240f9e6751808c84f4cba0bf53175542009dd917", "size": 2243, "ext": "py", "lang": "Python", "max_stars_repo_path": "mathpad/_generate_units.py", "max_stars_repo_name": "CallumJHays/mathpad", "max_stars_repo_head_hexsha": "bb2aab07ead67cd95637d9bd7cd952f0ac7161e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-08T09:29:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T05:12:20.000Z", "max_issues_repo_path": "mathpad/_generate_units.py", "max_issues_repo_name": "CallumJHays/mathpad", "max_issues_repo_head_hexsha": "bb2aab07ead67cd95637d9bd7cd952f0ac7161e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-29T05:13:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-06T05:11:22.000Z", "max_forks_repo_path": "mathpad/_generate_units.py", "max_forks_repo_name": "CallumJHays/mathpad", "max_forks_repo_head_hexsha": "bb2aab07ead67cd95637d9bd7cd952f0ac7161e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9852941176, "max_line_length": 134, "alphanum_fraction": 0.5853767276, "include": true, "reason": "import sympy,from sympy", "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.19507638209139164}}
{"text": "\"\"\"\nCore for the backend of the project.\nAll the computations on the Neural Networks are done here.\nAuthor: Antonio Strippoli\n\"\"\"\n# General imports\nimport os\nimport sys\nimport PIL.Image as pil\nimport numpy as np\n\nimport matplotlib\n\n# Set non interactive backend for matplolib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\n\n# Project's imports\nfrom flaskr import paths\n\n# TensorFlow & Keras\nimport tensorflow as tf\nfrom tensorflow.keras.models import Model\n\n# TF-Keras-Vis\nfrom tf_keras_vis.gradcam import GradcamPlusPlus\nfrom tf_keras_vis.utils import normalize\n\n# Utilities\nfrom .utils import np_array_to_img_rgb\nfrom utils import pickle_load\nfrom capslayers import compute_vectors_length\n\n\ndef load_model(model_name):\n    \"\"\"\n    \"\"\"\n    # Import model (HACK)\n    sys.path.append(os.path.join(paths[\"trainer\"], model_name))\n    from capsnet import CapsuleNet\n\n    sys.path.pop()\n\n    # Load model\n    try:\n        model_params = pickle_load(\n            os.path.join(paths[\"trainer\"], model_name, \"outs\", \"model_params.pkl\")\n        )\n    except FileNotFoundError:\n        return None, None\n\n    dataset = model_params.pop(\"dataset\")\n    _, model = CapsuleNet(**model_params)\n    model_params[\"dataset\"] = dataset\n\n    # Clean modules (HACK)\n    del sys.modules[\"capsnet\"]\n\n    return model, model_params\n\n\ndef get_processable_layers(layers):\n    \"\"\"\n    Returns computable layers from a list of layers, along with their types. \n    We check that by searching specific keywords in layer's name,\n    since we can't be sure about layer's type.\n\n    If you wish to extend the project and add compatibility\n    for more layers, you should as well update this function.\n    \"\"\"\n    processable_layers = []\n\n    for layer in layers:\n        layer_name = layer.name.lower()\n\n        if \"conv\" in layer_name:\n            processable_layers.append([layer_name, \"CONVOLUTIONAL\"])\n        elif \"primary\" in layer_name and \"caps\" in layer_name:\n            processable_layers.append([layer_name, \"PRIMARY_CAPS\"])\n        elif \"caps\" in layer_name:\n            processable_layers.append([layer_name, \"DENSE_CAPS\"])\n        elif \"mask\" in layer_name:\n            processable_layers.append([layer_name, \"MASK\"])\n\n    return processable_layers\n\n\ndef conv_out_process(act, img_mode, layer_img_dir):\n    # Extract from batch\n    act = act[0]\n\n    # Prepare new image to contain convolutional's features\n    new_img_width = act.shape[0] * act.shape[-1]\n    new_img_height = act.shape[1]\n    new_img = pil.new(\"RGB\", (new_img_width, new_img_height))\n\n    # Save features\n    act = tf.multiply(act, 255.0)\n    for i in range(act.shape[-1]):\n        feature = act[:, :, i].numpy().astype(\"int8\")\n        feature_image = pil.fromarray(np.uint8(matplotlib.cm.viridis(feature) * 255))\n\n        new_img.paste(\n            feature_image, (act.shape[0] * i, 0),\n        )\n\n    # Save the new image\n    new_img.save(os.path.join(layer_img_dir, f\"out.jpeg\"))\n\n    # Save filters (TODO?)\n    pass\n\n    return {\n        \"Activations after ReLU\": {\n            \"filename\": \"out.jpeg\",\n            \"rows\": 1,\n            \"cols\": act.shape[-1],\n            \"chunk_width\": act.shape[0],\n            \"chunk_height\": act.shape[1],\n        }\n    }\n\n\ndef pcap_out_process(act, prep_img, img_mode, layer, layer_conf, layer_img_dir):\n    # Extract from batch\n    act = act[0]\n    prep_img = prep_img[0]\n\n    # Move preprocessed image to RGB domain (if not)\n    prep_img = np_array_to_img_rgb(prep_img, img_mode)\n\n    # Get new features' dimension\n    feature_dim = int(\n        (layer.input_shape[1] - layer_conf[\"kernel_size\"] + 1) / layer_conf[\"strides\"]\n    )\n    # Compute vectors' length and reshape\n    act = tf.reshape(compute_vectors_length(act), (feature_dim, feature_dim, -1))\n\n    # Prepare new image to contain capsules' activations\n    chunk_width, chunk_height = prep_img.size\n    new_img_width = chunk_width * act.shape[-1]\n    new_img_height = chunk_height\n    new_img = pil.new(\"RGB\", (new_img_width, new_img_height))\n\n    # Save as images with the same size of the inputs\n    act = tf.multiply(act, 255)\n    for i in range(act.shape[-1]):\n        capsules_length = act[:, :, i].numpy()\n        capsules_length = np.interp(\n            capsules_length, (capsules_length.min(), capsules_length.max()), (0.0, 1.0),\n        )\n        heatmap = pil.fromarray(np.uint8(matplotlib.cm.jet(capsules_length) * 255))\n\n        # If we stop here, we can get a visualized matrix showing capsules activations,\n        # but we go further, rescaling and superimposing the heatmap to the original image\n        heatmap = heatmap.resize((chunk_width, chunk_height))\n        pcaps_img = pil.blend(prep_img, heatmap, alpha=0.7)\n\n        new_img.paste(\n            pcaps_img, (chunk_width * i, 0),\n        )\n\n    # Save the new image\n    new_img.save(os.path.join(layer_img_dir, f\"out.jpeg\"))\n\n    return {\n        \"Capsules' length as heatmap\": {\n            \"filename\": \"out.jpeg\",\n            \"rows\": 1,\n            \"cols\": act.shape[-1],\n            \"chunk_width\": chunk_width,\n            \"chunk_height\": chunk_height,\n        }\n    }\n\n\ndef dcap_out_process(prev_layer_pack, layer_pack, prep_img, img_mode, layer_img_dir):\n    # --------------------------\n    # The following is a compact version of routing path visualization. All the credits goes to Aman Bhullar:\n    # https://atrium.lib.uoguelph.ca/xmlui/bitstream/handle/10214/17834/Bhullar_Aman_202003_Msc.pdf?sequence=1&isAllowed=y\n    # --------------------------\n\n    # TODO: Implement the complete routing path visualization.\n    # Also, atm we assume that the previous layer is always a primary caps, which is not always be the case\n\n    # Unpack variables\n    ((pl, _), prev_act) = prev_layer_pack\n    ((cl, _), curr_act) = layer_pack\n\n    pl_conf = pl.get_config()\n    cl_conf = cl.get_config()\n\n    # Get new features' dimension\n    feature_dim = int(\n        (pl.input_shape[1] - pl_conf[\"kernel_size\"] + 1) / pl_conf[\"strides\"]\n    )\n\n    # HACK: Assume that every input image to the network is squared,\n    # which would produce squared features as well\n    dims = [\n        feature_dim,\n        feature_dim,\n        pl_conf[\"n_caps\"],\n        cl_conf[\"n_caps\"],\n    ]\n\n    # Prepare output of previous caps layer\n    tmp_dims = dims[0:3] + [1] * (len(dims) - 3)\n    prev_caps_lengths = tf.reshape(compute_vectors_length(prev_act), tmp_dims)\n    tmp_dims = [1] * (3) + dims[3 : len(dims)]\n    prev_caps_lengths_tiled = tf.tile(prev_caps_lengths, tmp_dims)\n\n    # Prepare routing weights\n    tmp_dims = dims[0:4] + [1] * (len(dims) - 4)\n    routing_weights_reshape = tf.reshape(curr_act[1], tmp_dims)\n    tmp_dims = [1] * (4) + dims[4 : len(dims)]\n    routing_weights_reshape_tiled = tf.tile(routing_weights_reshape, tmp_dims)\n\n    # Prepare output of current caps layer\n    tmp_dims = [1, 1, 1, dims[3]] + [1] * (len(dims) - 4)\n    curr_caps_lengths = tf.reshape(compute_vectors_length(curr_act[0]), tmp_dims)\n    tmp_dims = dims[0:3] + [1] + dims[4 : len(dims)]\n    curr_caps_lengths_tiled = tf.tile(curr_caps_lengths, tmp_dims)\n\n    # Calculate routing path visualization\n    tmp = tf.multiply(routing_weights_reshape_tiled, curr_caps_lengths_tiled)\n    all_paths = tf.multiply(prev_caps_lengths_tiled, tmp)\n    all_paths_average = tf.reduce_sum(all_paths, axis=2)\n\n    # Preprocess input image\n    input_img_width, input_img_height = prep_img.shape[1:3]\n    prep_img = prep_img[0]\n\n    # Move preprocessed image to RGB domain (if not)\n    prep_img = np_array_to_img_rgb(prep_img, img_mode)\n\n    # Prepare new image to contain capsules' activations\n    new_img = pil.new(\"RGB\", (input_img_width * dims[-1], input_img_height))\n\n    # Save outputs as a single image\n    all_paths_average = all_paths_average.numpy()\n    all_paths_average = np.interp(\n        all_paths_average,\n        (all_paths_average.min(), all_paths_average.max()),\n        (0.0, 1.0),\n    )\n    for i in range(all_paths_average.shape[-1]):\n        rpv = all_paths_average[:, :, i]\n        heatmap = pil.fromarray(np.uint8(matplotlib.cm.jet(rpv) * 255))\n\n        # Rescale and blend\n        heatmap = heatmap.resize((input_img_width, input_img_height))\n        dcaps_img = pil.blend(prep_img, heatmap, alpha=0.7)\n\n        new_img.paste(dcaps_img, (i * input_img_width, 0))\n\n    # Save the new image\n    new_img.save(os.path.join(layer_img_dir, f\"out.jpeg\"))\n\n    return {\n        \"Routing Path Visualization\": {\n            \"filename\": \"out.jpeg\",\n            \"rows\": 1,\n            \"cols\": dims[-1],\n            \"chunk_width\": input_img_width,\n            \"chunk_height\": input_img_height,\n        }\n    }\n\n\ndef dcap_gradcam(model, layer, prep_img, img_mode, layer_img_dir):\n    # Edit model to stop at the current layer\n    def model_modifier(model):\n        return tf.keras.Model(inputs=model.inputs, outputs=layer.output)\n\n    # Instantiate gradcam\n    gradcam = GradcamPlusPlus(model, model_modifier, clone=False)\n\n    def loss(output):\n        \"\"\"Maximize the prediction with greater probability\"\"\"\n        output = compute_vectors_length(output)\n        i = np.argmax(output, 1)[0]\n        return output[0, i]\n\n    # Compute gradcam\n    cam = normalize(\n        gradcam(\n            [loss, lambda x: tf.convert_to_tensor(0.0)],\n            prep_img,\n            penultimate_layer=layer,\n        )\n    )\n    heatmap = pil.fromarray(np.uint8(matplotlib.cm.jet(cam[0]) * 255))\n\n    # Move preprocessed image to RGB domain (if not)\n    prep_img = prep_img[0]\n    prep_img = np_array_to_img_rgb(prep_img, img_mode)\n\n    # Superimpose heatmap\n    gradcam_final = pil.blend(prep_img, heatmap, alpha=0.7)\n\n    # Save the new image\n    gradcam_final.convert(\"RGB\").save(os.path.join(layer_img_dir, f\"out.jpeg\"))\n\n    return {\"filename\": \"out.jpeg\"}\n\n\ndef mask_out_process(act, img_mode, layer, model_params, layer_img_dir):\n    # Extract from batch and convert to numpy\n    act = act[0]\n    act_numpy = act.numpy()\n\n    # Get next layer ( suppose decoder (HACK) )\n    next_layer = layer._outbound_nodes[1].outbound_layer\n\n    # Prepare dictionary for outputs\n    out = {}\n\n    # === MANIPULATIONS ON MAGNITUDE ===\n    n_manip = 11\n\n    # Prepare new output image\n    new_img_width = model_params[\"input_shape\"][0] * n_manip\n    new_img_height = model_params[\"input_shape\"][1]\n    new_img = pil.new(img_mode, (new_img_width, new_img_height))\n\n    # Edit tensor values and feed the activation forward to get reconstruction\n    for i_r, r in enumerate(np.linspace(0, 1, n_manip)):\n        r = round(r, 1)\n        # Rescale magnitude value\n        act_to_feed = np.copy(act_numpy)\n        act_to_feed *= r / compute_vectors_length(act_to_feed)\n\n        # Convert back to tensor and feed-forward\n        act_to_feed = tf.expand_dims(tf.convert_to_tensor(act_to_feed), 0)\n        reconstructed_image = next_layer(act_to_feed)\n\n        # Pre-process reconstruction\n        reconstructed_image = tf.squeeze(reconstructed_image)\n        reconstructed_image = tf.multiply(reconstructed_image, 255.0)\n        reconstructed_image = reconstructed_image.numpy().astype(\"int8\")\n\n        # Convert to image and paste to the new image\n        reconstructed_image = pil.fromarray(reconstructed_image, mode=img_mode)\n        new_img.paste(\n            reconstructed_image, (model_params[\"input_shape\"][0] * i_r, 0,),\n        )\n\n    # Save the new image\n    new_img.save(os.path.join(layer_img_dir, f\"magnitude.jpeg\"))\n\n    # Prepare partial output\n    out[\"1) Manipulations on magnitude\"] = {\n        \"filename\": \"magnitude.jpeg\",\n        \"rows\": 1,\n        \"cols\": n_manip,\n        \"chunk_width\": model_params[\"input_shape\"][0],\n        \"chunk_height\": model_params[\"input_shape\"][1],\n    }\n\n    # === MANIPULATIONS ON DIMENSIONS ===\n    # Prepare variables for the iterations\n    start = np.argmax(act != 0)\n    n_dims = act.shape[0] // model_params[\"n_class\"]\n    n_manip = 11\n\n    # Prepare new output image\n    new_img_width = model_params[\"input_shape\"][0] * n_manip\n    new_img_height = model_params[\"input_shape\"][1] * n_dims\n    new_img = pil.new(img_mode, (new_img_width, new_img_height))\n\n    # Edit tensor values and feed the activation forward to get reconstruction\n    for i_dim in range(start, start + n_dims):\n        for i_r, r in enumerate(np.linspace(-0.25, 0.25, n_manip)):\n            r = round(r, 2)\n            # Edit dimension value\n            act_to_feed = np.copy(act_numpy)\n            act_to_feed[i_dim] += r\n\n            # Convert back to tensor and feed-forward\n            act_to_feed = tf.expand_dims(tf.convert_to_tensor(act_to_feed), 0)\n            reconstructed_image = next_layer(act_to_feed)\n\n            # Pre-process reconstruction\n            reconstructed_image = tf.squeeze(reconstructed_image)\n            reconstructed_image = tf.multiply(reconstructed_image, 255.0)\n            reconstructed_image = reconstructed_image.numpy().astype(\"int8\")\n\n            # Convert to image and paste to the new image\n            reconstructed_image = pil.fromarray(reconstructed_image, mode=img_mode)\n            new_img.paste(\n                reconstructed_image,\n                (\n                    model_params[\"input_shape\"][0] * i_r,\n                    model_params[\"input_shape\"][1] * (i_dim - start),\n                ),\n            )\n\n    # Save the new image\n    new_img.save(os.path.join(layer_img_dir, f\"dimensions.jpeg\"))\n\n    out[\"2) Manipulations on dimensions\"] = {\n        \"filename\": \"dimensions.jpeg\",\n        \"rows\": n_dims,\n        \"cols\": n_manip,\n        \"chunk_width\": model_params[\"input_shape\"][0],\n        \"chunk_height\": model_params[\"input_shape\"][1],\n    }\n\n    return out\n\n\ndef model_out_process(predictions, model_out_dir):\n    \"\"\"\n    Visualize model's predictions in an histogram.\n    \"\"\"\n    plt.rcdefaults()\n    fig, ax = plt.subplots()\n\n    classes = np.arange(len(predictions))\n\n    ax.barh(classes, predictions, align=\"center\")\n    ax.set_yticks(classes)\n    ax.set_yticklabels(classes)\n    ax.set_xlim(0, 1.0)\n\n    plt.title(\n        f\"Prediction: {np.argmax(predictions)}\",\n        fontsize=30.0,\n        color=\"blue\",\n        fontweight=\"bold\",\n    )\n    ax.invert_yaxis()\n    ax.spines[\"right\"].set_visible(False)\n    ax.spines[\"top\"].set_visible(False)\n    ax.tick_params(axis=\"both\", colors=\"blue\", labelsize=20.0)\n\n    for i, v in enumerate(predictions):\n        ax.text(\n            v + 0.01,\n            i + 0.06,\n            str(round(v, 4)),\n            color=\"blue\",\n            fontweight=\"bold\",\n            verticalalignment=\"center\",\n            size=15.0,\n        )\n\n    plt.savefig(os.path.join(model_out_dir, \"out.png\"), transparent=True)\n    plt.close(\"all\")\n    return {\"filename\": \"out.png\"}\n\n\ndef compute_step(model, model_params, prep_img, img_mode, req_out_dir):\n    \"\"\"\n    Computes and saves the outputs of the processable layers in the given model.\n    \"\"\"\n    # Create a temporary model to retrieve all the layers' activations\n    processable_layers = get_processable_layers(model.layers)\n    processable_layers = [(model.get_layer(pl[0]), pl[1]) for pl in processable_layers]\n\n    activation_model = Model(model.input, [pl[0].output for pl in processable_layers])\n    activations = activation_model(prep_img)\n\n    # Prepare dictionary to contain outputs\n    out_dir = req_out_dir.replace(\"\\\\\", \"/\")\n    out_dir = out_dir[out_dir.find(\"/static\") :] + \"/\"\n\n    out_info = {\"out_dir\": out_dir}\n    outs = {}\n\n    layer_pack = list(zip(processable_layers, activations))\n    for i, ((layer, layer_type), act) in enumerate(layer_pack):\n        # Get layer config\n        layer_conf = layer.get_config()\n\n        # Prepare directory for the layer\n        layer_name = layer_conf[\"name\"]\n        layer_img_dir = os.path.join(req_out_dir, layer_name)\n        os.mkdir(layer_img_dir)\n\n        # === PROCESS LAYER ACTIVATION BASED ON TYPE ===\n        if layer_type == \"CONVOLUTIONAL\":\n            outs[layer_name] = conv_out_process(act, img_mode, layer_img_dir)\n        elif layer_type == \"PRIMARY_CAPS\":\n            outs[layer_name] = pcap_out_process(\n                act, prep_img, img_mode, layer, layer_conf, layer_img_dir\n            )\n        elif layer_type == \"DENSE_CAPS\":\n            curr_lp = layer_pack[i]\n            prev_lp = layer_pack[i - 1]\n            outs[layer_name] = dcap_out_process(\n                prev_lp, curr_lp, prep_img, img_mode, layer_img_dir\n            )\n\n            # Compute GradCAM++\n            gradcam_dir = os.path.join(req_out_dir, \"gradcam\")\n            os.mkdir(gradcam_dir)\n            out_info[\"gradcam\"] = dcap_gradcam(\n                model, layer, prep_img, img_mode, gradcam_dir\n            )\n        elif layer_type == \"MASK\":\n            outs[layer_name] = mask_out_process(\n                act, img_mode, layer, model_params, layer_img_dir\n            )\n        else:\n            raise TypeError(f\"Layer type '{layer_type}' cannot be computed.\")\n\n    # Add layers outputs\n    out_info[\"layers_outs\"] = outs\n\n    # Process model's output\n    model_out_dir = os.path.join(req_out_dir, \"model_out\")\n    os.mkdir(model_out_dir)\n\n    model_outs = model(prep_img)\n    if type(model_outs) == list:\n        predictions = model_outs[0][0].numpy()\n    else:\n        predictions = model_outs[0].numpy()\n\n    out_info[\"model_out\"] = model_out_process(predictions, model_out_dir)\n\n    return out_info\n", "meta": {"hexsha": "8d15205366cb190c6d652fbb444dc4694e83a4e8", "size": 17321, "ext": "py", "lang": "Python", "max_stars_repo_path": "flaskr/api_nn.py", "max_stars_repo_name": "CoffeeStraw/CapsNet-Knowledge-Extractor", "max_stars_repo_head_hexsha": "99dc665bcce394e4dfa0b8a6deda28d1e3713509", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-09-29T13:34:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T15:27:53.000Z", "max_issues_repo_path": "flaskr/api_nn.py", "max_issues_repo_name": "CoffeeStraw/CapsNet-Knowledge-Extractor", "max_issues_repo_head_hexsha": "99dc665bcce394e4dfa0b8a6deda28d1e3713509", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "flaskr/api_nn.py", "max_forks_repo_name": "CoffeeStraw/CapsNet-Knowledge-Extractor", "max_forks_repo_head_hexsha": "99dc665bcce394e4dfa0b8a6deda28d1e3713509", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9923809524, "max_line_length": 122, "alphanum_fraction": 0.6419375325, "include": true, "reason": "import numpy", "num_tokens": 4263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1950763820913916}}
{"text": "'''\nPersonalised argumentation paper: are user features are required or latent variables sufficient/correlated with observed features?\nIs prior stance a useful user feature for predicting belief change? It should be, since a user can only be convinced by\nan argument if they did not previously believe in it.\nTopic-specific nature means predictions based on linguistic features are likely to be weak?\n\nCreated on 19 Jun 2017\n\n@author: simpson\n'''\nimport os\nimport sys\nimport logging\nimport matplotlib.pyplot as plt # do this here so we don't get the debugging crap later from the logger\n\nfrom sklearn.gaussian_process.gpr import GaussianProcessRegressor\nfrom sklearn.gaussian_process.kernels import Matern\nfrom sklearn.metrics import accuracy_score\n\nlogging.basicConfig(level=logging.DEBUG)\n\nsys.path.append(\"./python/analysis/habernal_comparison\")\n\nfrom tests import TestRunner\nfrom gp_regressor_svi import GPRegressorSVI\nfrom collab_pref_learning_svi import CollabPrefLearningSVI\nimport numpy as np\n\nnfactors = 50\nmax_Kw_size = 2000\n\nrate_s = 200\n\nrate_sy0 = 10\n\ndelay = 0 # some default will be used depending on the function unless this is set to > 0\n\nclass PersonalisedTestRunner(TestRunner):\n\n    def run_crowd_bt(self):\n\n        nitems = self.items_feat.shape[0]\n        workers = np.unique(self.person_train)\n        nworkers = np.max(workers) + 1\n\n        scales = [1]  # [0.01, 0.1, 1, 10, 100]  # 10 was found to be optimal on the random selection tests.\n\n        tr_acc_best = 0\n\n        for scale in scales:\n\n            # initialise variational parameters\n            Es = np.zeros(nitems)\n            Eeta = np.ones(nworkers) * 0.9\n            sigma = np.ones(nitems) * scale\n            alpha = np.ones(nworkers) * 9\n            beta = np.ones(nworkers)\n\n            balance = 0#1e-6 # tiny amount to ensure numerical stability\n\n            for pair_idx in range(len(self.a1_train)):\n\n                # get the indices\n                a1 = self.a1_train[pair_idx]\n                a2 = self.a2_train[pair_idx]\n\n                if self.prefs_train[pair_idx] == 1:\n                    continue\n\n                if self.prefs_train[pair_idx] != 2:  # swap so a2 is the preferred one\n                    tmp = a1\n                    a1 = a2\n                    a2 = tmp\n\n                k = self.person_train[pair_idx]\n\n                # update the means\n                prob_incr = alpha[k] * np.exp(Es[a1]) / (alpha[k] * np.exp(Es[a1]) + beta[k] * np.exp(Es[a2]) + balance) \\\n                             - np.exp(Es[a1]) / (np.exp(Es[a1]) + np.exp(Es[a2]) + balance)\n                Es[a1] = Es[a1] + sigma[a1] ** 2 * prob_incr\n                Es[a2] = Es[a2] - sigma[a2] ** 2 * prob_incr\n\n                var_diff = alpha[k]  *np.exp(Es[a1]) * beta[k] * np.exp(Es[a2]) / \\\n                           ((alpha[k] * np.exp(Es[a1]) + beta[k] * np.exp(Es[a2]))**2 + balance) \\\n                           - np.exp(Es[a1]) * np.exp(Es[a2]) / ((np.exp(Es[a1]) + np.exp(Es[a2]))**2 + balance)\n                sigma[a1] = np.sqrt(sigma[a1] ** 2 * np.max([1 + sigma[a1] ** 2 * (var_diff), 10e-4]))\n                sigma[a2] = np.sqrt(sigma[a2] ** 2 * np.max([1 + sigma[a2] ** 2 * (var_diff), 10e-4]))\n\n                C1 = np.exp(Es[a1]) / (np.exp(Es[a1]) + np.exp(Es[a2]) + balance) \\\n                     + 0.5 * (sigma[a1] ** 2 + sigma[a2] ** 2) \\\n                     * np.exp(Es[a1]) * np.exp(Es[a2]) * (np.exp(Es[a2]) - np.exp(Es[a1])) \\\n                     / (np.exp(Es[a1]) + np.exp(Es[a2]) + balance) ** 3\n\n                C2 = 1 - C1\n\n                C = (C1 * alpha[k] + C2 * beta[k]) / (alpha[k] + beta[k] + balance)  # normalisation constant for p( 1 > 2 | worker k)\n\n                Eeta[k] = (C1 * (alpha[k] + 1) * alpha[k] + C2 * alpha[k] * beta[k]) / (\n                            C * (alpha[k] + beta[k] + 1) * (alpha[k] + beta[k]) + balance)\n                Eeta_sq_k = (C1 * (alpha[k] + 2) * (alpha[k] + 1) * alpha[k] + C2 * (alpha[k] + 1) * alpha[k] * beta[k]) / \\\n                            (C * (alpha[k] + beta[k] + 2) * (alpha[k] + beta[k] + 1) * (alpha[k] + beta[k]) + balance)\n\n                alpha[k] = (Eeta[k] - Eeta_sq_k) * Eeta[k] / (Eeta_sq_k - Eeta[k] ** 2 + balance)\n                beta[k] = (Eeta[k] - Eeta_sq_k) * (1 - Eeta[k]) / (Eeta_sq_k - Eeta[k] ** 2 + balance)\n\n                if np.mod(pair_idx, 1000) == 0:\n                    print('Learning crowdBT, iteration %i' % pair_idx)\n\n            if np.any(np.isnan(Es)):\n                continue\n\n            tr_proba = np.exp(Es[self.a1_train]) / (np.exp(Es[self.a1_train]) + np.exp(Es[self.a2_train]) + balance)\n            tr_acc = accuracy_score(self.prefs_train[self.prefs_train != 1]==2, np.round(tr_proba[self.prefs_train != 1]))\n            print('training set accuracy = %f with scale %f' % (tr_acc, scale) )\n            if tr_acc > tr_acc_best:\n                Es_best = Es\n                scale_best = scale\n                tr_acc_best = tr_acc\n\n        Es = Es_best\n\n        print('Completed online learning of crowd BT. Found best scale is %f' % scale_best)\n\n        proba = np.exp(Es[self.a1_test]) / (np.exp(Es[self.a1_test]) + np.exp(Es[self.a2_test]) + balance)\n\n        self.crowdBT_sigma = sigma\n        self.crowdBT_s = Es\n\n        scores = Es[self.a_rank_test]\n\n        tr_proba = np.exp(Es[self.a1_unseen]) / (\n                    np.exp(Es[self.a1_unseen]) + np.exp(Es[self.a2_unseen]) + balance)\n\n        return proba, scores, tr_proba, Es[self.a_rank_train]\n\n\n    def run_crowd_bt_gpr(self):\n\n        # we first train crowd_bt as above. Then, we use the scores for items that were compared in training\n        # to train a GP regression model. The GP then predicts the scores of all items. This means we can generalise\n        # from the training items to all items, plus the GP will do some smoothing over the training items in case they\n        # had sparse noisy data.\n\n        proba, predicted_f, tr_proba, tr_f = self.run_crowd_bt()\n\n        if 'additive' in self.method:\n            kernel_combination = '+'\n        else:\n            kernel_combination = '*'\n\n        if 'shrunk' in self.method:\n            ls_initial = self.ls_initial / float(len(self.ls_initial))\n        else:\n            ls_initial = self.ls_initial\n\n        if 'weaksprior' in self.method:\n            shape_s0 = 2.0\n            rate_s0 = 200.0\n        elif 'lowsprior' in self.method:\n            shape_s0 = 1.0\n            rate_s0 = 1.0\n        elif 'weakersprior' in self.method:\n            shape_s0 = 2.0\n            rate_s0 = 2000.0\n        else:\n            shape_s0 = 200.0\n            rate_s0 = 20000.0\n\n        if '_M' in self.method:\n            validx = self.method.find('_M') + 2\n            M = int(self.method[validx:])\n        else:\n            M = 500\n\n        if '_SS' in self.method:\n            validx = self.method.find('_SS') + 3\n            SS = int(self.method[validx:])\n        else:\n            SS = 200\n\n        self.model = GPRegressorSVI(ninput_features=self.ndims, ls_initial=ls_initial, verbose=self.verbose,\n                                    shape_s0=2, rate_s0=200, rate_ls=1.0 / np.mean(ls_initial),\n                                    use_svi=True,\n                                    ninducing=M, max_update_size=SS, kernel_combination=kernel_combination,\n                                    forgetting_rate=0.7,\n                                    delay=1.0)\n        self.model.max_iter_VB = 2  #00\n        new_items_feat = self.items_feat  # pass only when initialising\n\n        print(\"no. features: %i\" % new_items_feat.shape[1])\n        self.model.fit(self.items_feat, self.crowdBT_s, obs_noise=self.crowdBT_sigma ** 2)\n\n        predicted_f, _ = self.model.predict_f()  #self.model.obs_f\n\n        balance = 0\n        proba = np.exp(predicted_f[self.a1_test]) / (\n                    np.exp(predicted_f[self.a1_test]) + np.exp(predicted_f[self.a2_test]) + balance)\n\n        f = predicted_f[self.a_rank_test]\n\n        tr_f = predicted_f[self.a_rank_train]\n\n        tr_proba = np.exp(predicted_f[self.a1_unseen]) / (\n                    np.exp(predicted_f[self.a1_unseen]) + np.exp(predicted_f[self.a2_unseen]) + balance)\n\n        return proba, f, tr_proba, tr_f\n\n\n    def _train_persgppl(self, delay):\n        common_mean = False\n\n        if '_commonmean' in self.method:\n            common_mean = True\n\n        if 'weaksprior' in self.method:\n            shape_s0 = 2.0\n            rate_s0 = rate_s #200.0\n        elif 'lowsprior' in self.method:\n            shape_s0 = 1.0\n            rate_s0 = 1.0\n        elif 'weakersprior' in self.method:\n            shape_s0 = 2.0\n            rate_s0 = 2000.0\n        else:\n            shape_s0 = 200.0\n            rate_s0 = 20000.0\n\n        if '_M' in self.method:\n            validx = self.method.find('_M') + 2\n            M = int(self.method[validx:].split('_')[0])\n        else:\n            M = 500\n\n        if M == 0:\n            M = self.items_feat.shape[0]\n\n        if '_F' in self.method:\n            valididx = self.method.find('_F') + 2\n            F = int(self.method[valididx:].split('_')[0])\n        else:\n            F = nfactors\n\n        if '_SS' in self.method:\n            validx = self.method.find('_SS') + 3\n            SS = int(self.method[validx:])\n\n            niter = 200 #* (200.0 / float(SS))\n        else:\n            SS = 200\n            niter = 200\n\n        self.model = CollabPrefLearningSVI(nitem_features=self.ndims, ls=self.ls_initial, verbose=self.verbose,\n                                           nfactors=F, rate_ls=1.0 / np.mean(self.ls_initial),\n                                           use_common_mean_t=common_mean, max_update_size=SS, use_lb=True,\n                                           shape_s0=shape_s0, rate_s0=rate_s0,\n                                           shape_st0=shape_s0, rate_st0=rate_s0,\n                                           shape_sy0=1, rate_sy0=rate_sy0,\n                                           ninducing=M, forgetting_rate=0.9,\n                                           delay=delay,\n                                           exhaustive_train_count=1)\n\n        self.model.max_iter = niter # same as for single user GPPL\n        self.model.max_Kw_size = max_Kw_size\n\n        zero_centered_prefs = np.array(self.prefs_train, dtype=float) - 1\n\n        # subsample for debugging!!!\n        # self.chosen_people = np.unique(self.person_test)[:50]\n        # tridxs = np.in1d(self.person_train, self.chosen_people)\n\n        #self.model.uselowerbound = False\n        self.model.use_local_obs_posterior_y = False\n\n        self.model.fit(self.person_train, self.a1_train, self.a2_train, self.items_feat, zero_centered_prefs,\n                       optimize=self.optimize_hyper, nrestarts=1, input_type='zero-centered')\n\n\n    def run_persgppl(self):\n        '''\n        Make personalised predictions\n        :return:\n        '''\n        global delay\n        if delay == 0:\n            delay = 10\n        self._train_persgppl(delay=delay)\n\n        if self.vscales is not None:\n            self.vscales.append(np.sort((self.model.rate_sw / self.model.shape_sw) *\n                                        (self.model.rate_sw / self.model.shape_sw))[::-1])\n\n        proba = self.model.predict(self.person_test, self.a1_test, self.a2_test)\n        tr_proba = self.model.predict(self.person_unseen, self.a1_unseen, self.a2_unseen)\n\n        # what did we change?\n        # - more iterations ( 200 --> 500 )\n        # - smaller rates ( 200 --> 20 ) because there are multiple factors whose scales all add up\n        # next: try increasing delay so that y doesn't disappear to zero so easily when the person is not seen until\n        # later batch of training data\n        # Also: consider that when users are independent, then the stochastic updates are also updating only some of\n        # the variables. But the others are getting set back to zero... this is only a problem in this model because\n        # if they are initialised to zero, they don't move much because w and y are scaled by each other's current\n        # estimates. It might be okay if variance of w and y is large because this is added to the scale factor\n\n        if self.a_rank_test is not None:\n            predicted_f = self.model.predict_f_item_person(self.a_rank_test, self.person_rank_test)\n        else:\n            predicted_f = None\n\n        if self.a_rank_train is not None:\n            tr_f = self.model.predict_f_item_person(self.a_rank_train, self.person_rank_train)\n        else:\n            tr_f = None\n\n        return proba, predicted_f, tr_proba, tr_f\n\n    def run_persgppl_consensus(self):\n        '''\n        Predict the consensus from multiple people's opinions.\n        '''\n\n        # look for a file that was trained on the same data but with the personalised predictions instead of MACE consensus.\n        # pretrainedmodelfile = self.modelfile.replace('_evalMACE', '')\n        # pretrainedmodelfile = pretrainedmodelfile.replace('Consensus', '')\n        #\n        # logging.info('Looking for a pretrained model at %s' % pretrainedmodelfile)\n        #\n        # if os.path.exists(pretrainedmodelfile):\n        #     with open(pretrainedmodelfile, 'rb') as fh:\n        #         self.model = pickle.load(fh)\n        #         logging.info('Reloaded a pretrained model :)')\n        # else:\n        #     logging.info('I didnae find any pretrained model :(')\n        #     self._train_persgppl()\n\n        print('Training crowdGPPL to predict consensus...')\n        global delay\n        if delay == 0:\n            delay = 10\n\n        self._train_persgppl(delay=delay)\n\n        if self.vscales is not None:\n            self.vscales.append(np.sort(self.model.rate_sw / self.model.shape_sw)[::-1])\n\n\n        print('Testing crowdGPPL on consensus -- making predictions now.')\n        proba = self.model.predict_common(None, self.a1_test, self.a2_test)\n        tr_proba = self.model.predict_common(None, self.a1_unseen, self.a2_unseen)\n\n        if self.a_rank_test is not None:\n            predicted_f = self.model.predict_t()[self.a_rank_test]\n        else:\n            predicted_f = None\n\n        if self.a_rank_train is not None:\n            tr_f = self.model.predict_t()[self.a_rank_train]\n        else:\n            predicted_f = None\n\n        print('Max probability = %f, min = %f' % (np.max(proba), np.min(proba)))\n\n        return proba, predicted_f, tr_proba, tr_f\n\n    def _choose_method_fun(self, feature_type):\n        if 'PersPrefGP' in self.method:\n            method_runner_fun = self.run_persgppl\n        elif 'PersConsensusPrefGP' in self.method:\n            method_runner_fun = self.run_persgppl_consensus\n        elif 'IndPrefGP' in self.method:\n            method_runner_fun = self.run_persgppl # switches to correct class inside the method\n        elif 'crowdBT' in self.method:\n            method_runner_fun = self.run_crowd_bt\n        elif 'cBT_GP' in self.method:\n            method_runner_fun = self.run_crowd_bt_gpr\n        else:\n            method_runner_fun = super(PersonalisedTestRunner, self)._choose_method_fun(feature_type)\n\n        return method_runner_fun\n\nif __name__ == '__main__':\n\n    test_to_run = int(sys.argv[1])\n\n    if len(sys.argv) > 2:\n        npairs = int(sys.argv[2])\n    else:\n        npairs = 0 #5000\n\n    if len(sys.argv) > 3:\n        lsm = int(sys.argv[3])\n    else:\n        lsm = 1\n\n    test_dir = 'D05-%i_P%i' % (lsm, npairs)  #'rate_s_tests_single'\n\n    methods = ['SinglePrefGP_noOpt_weaksprior']\n    datasets = ['UKPConvArgCrowdSample_evalMACE']\n    dataset_increment = 0\n    # UKPConvArgCrowdSample tests prediction of personal data.\n    # UKPConvArgCrowdSample_evalMACE uses the personal data as input, but predicts the global labels/rankings.\n    feature_types = ['both']  # can be 'embeddings' or 'ling' or 'both' or 'debug'\n    embeddings_types = ['word_mean']\n\n    datasets = ['UKPConvArgCrowdSample']\n    methods = ['PersPrefGP_commonmean_noOpt_weaksprior']\n\n    runner = PersonalisedTestRunner(test_dir, datasets, feature_types, embeddings_types, methods,\n                                    dataset_increment)\n\n    max_fold = 32\n\n    rate_sy0 = 10\n\n    # PERSONALISED PREDICTION\n    if test_to_run == 0:\n        runner.run_test_set(min_no_folds=0, max_no_folds=max_fold, npairs=npairs, ls_factor=lsm)\n\n    elif test_to_run == 13:\n        # tune up on training set accuracy\n\n        rateyvals = [1, 10, 100]\n        delays = [1, 10]\n\n        for ratey in rateyvals:\n            for delay in delays:\n                rate_sy0 = ratey\n\n                test_dir = 'D05-%i_P%i-ratey%i-delay%i' % (lsm, npairs, ratey, delay)  # 'rate_s_tests_single'\n                runner = PersonalisedTestRunner(test_dir, datasets, feature_types, embeddings_types, methods,\n                                            dataset_increment)\n                runner.run_test_set(min_no_folds=0, max_no_folds=10, npairs=npairs, ls_factor=lsm)\n\n    elif test_to_run == 14:\n\n        rateyvals = [1, 10, 100]\n        delays = [1, 10]\n\n        for ratey in rateyvals:\n            for delay in delays:\n                rate_sy0 = ratey\n\n                test_dir = 'D05-%i_P%i-ratey%i-delay%i' % (lsm, npairs, ratey, delay)  # 'rate_s_tests_single'\n                runner = PersonalisedTestRunner(test_dir, datasets, feature_types, embeddings_types, methods,\n                                            dataset_increment)\n                runner.datasets = ['UKPConvArgCrowdSample_evalMACE']\n                runner.methods = ['PersConsensusPrefGP_commonmean_noOpt_weaksprior']\n                runner.run_test_set(min_no_folds=0, max_no_folds=10, npairs=npairs, ls_factor=lsm)\n\n\n    elif test_to_run == 12:\n        runner.datasets = ['UKPConvArgCrowdSample']\n        runner.methods = ['PersPrefGP_noOpt_weaksprior']\n        runner.run_test_set(min_no_folds=0, max_no_folds=max_fold, npairs=npairs, ls_factor=lsm)\n\n\n    # CONSENSUS PREDICTION\n    elif test_to_run == 1:\n        runner.datasets = ['UKPConvArgCrowdSample_evalMACE']\n        runner.methods = ['PersConsensusPrefGP_commonmean_noOpt_weaksprior']\n        runner.run_test_set(min_no_folds=0, max_no_folds=max_fold, npairs=npairs, ls_factor=lsm)\n\n    # Plot the scales of the latent factors ----------------------------------------------------------------------\n    if test_to_run < 4 and len(runner.vscales):\n        vscales = np.mean(runner.vscales, axis=0)\n\n        logging.getLogger().setLevel(logging.WARNING) # matplotlib prints loads of crap to the debug and info outputs\n\n        import matplotlib\n        matplotlib.use('Agg')\n        import matplotlib.pyplot as plt\n\n        fig = plt.figure(figsize=(5, 4))\n\n        markers = ['x', 'o', '+', '>', '<', '*']\n\n        plt.plot(np.arange(vscales.shape[0]), vscales, marker=markers[0], label='UKPConvArgCrowdSample',\n                 linewidth=2, markersize=8)\n\n        plt.ylabel('Inverse scale 1/s')\n        plt.xlabel('Factor ID')\n\n        plt.grid('on', axis='y')\n        plt.legend(loc='best')\n        plt.tight_layout()\n\n        figure_root_path = './results/conv_factors'\n        if not os.path.exists(figure_root_path):\n            os.mkdir(figure_root_path)\n\n        plt.savefig(figure_root_path + '/UKPConvArgCrowdSample_factor_scales.pdf')\n\n        np.savetxt(figure_root_path + '/UKPConvArgCrowdSample_factor_scales.csv', vscales, delimiter=',', fmt='%f')\n\n        logging.getLogger().setLevel(logging.DEBUG)\n\n    # PERSONALISED PREDICTION for other methods -----------------------------------------------------------------\n    elif test_to_run == 6:\n        methods = [\n               'SinglePrefGP_noOpt_weaksprior' # 'SinglePrefGP_noOpt_weaksprior',\n            ]\n        runner.datasets = ['UKPConvArgCrowdSample']\n        runner.methods = methods\n        runner.run_test_set(min_no_folds=0, max_no_folds=max_fold, npairs=npairs, ls_factor=lsm)\n\n    elif test_to_run == 7:\n        methods = [\n               'SinglePrefGP_noOpt_weaksprior' # 'SinglePrefGP_noOpt_weaksprior',\n            ]\n        runner.datasets = ['UKPConvArgCrowdSample_evalMACE']\n        runner.methods = methods\n        runner.run_test_set(min_no_folds=0, max_no_folds=max_fold, npairs=npairs, ls_factor=lsm)\n\n    elif test_to_run == 8:\n        methods = [\n               #'crowdBT', # no point running this because it cannot predict on the test instances, for aggregation only\n               'cBT_GP',\n            ]\n        runner.datasets = ['UKPConvArgCrowdSample']\n        runner.methods = methods\n        runner.run_test_set(min_no_folds=0, max_no_folds=max_fold, npairs=npairs, ls_factor=lsm)\n\n    elif test_to_run == 9: # commented so we run both tests with cBT\n        methods = [\n               #'crowdBT', # no point running this because it cannot predict on the test instances, for aggregation only\n               'cBT_GP',\n        ]\n        runner.datasets = ['UKPConvArgCrowdSample_evalMACE']\n        runner.methods = methods\n        runner.run_test_set(min_no_folds=0, max_no_folds=max_fold, npairs=npairs, ls_factor=lsm)\n\n    elif test_to_run == 11: # commented so we run both tests with cBT\n        methods = [\n               'crowdBT', # no point running this because it cannot predict on the test instances, for aggregation only\n        ]\n        runner.datasets = ['UKPConvArgCrowdSample_evalMACE']\n        runner.methods = methods\n        runner.run_test_set(min_no_folds=0, max_no_folds=max_fold, npairs=npairs, ls_factor=lsm)", "meta": {"hexsha": "7809e6e91d4a4e036478809fa69899acf25c6883", "size": 21402, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/analysis/habernal_comparison/personalised_tests.py", "max_stars_repo_name": "UKPLab/tacl2018-preference-convincing", "max_stars_repo_head_hexsha": "65eb1cd3bf76f8068889880e0f80178e790350ce", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2019-03-01T19:40:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T05:53:47.000Z", "max_issues_repo_path": "python/analysis/habernal_comparison/personalised_tests.py", "max_issues_repo_name": "UKPLab/tacl2018-preference-convincing", "max_issues_repo_head_hexsha": "65eb1cd3bf76f8068889880e0f80178e790350ce", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-11-13T17:54:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T23:39:11.000Z", "max_forks_repo_path": "python/analysis/habernal_comparison/personalised_tests.py", "max_forks_repo_name": "UKPLab/tacl2018-preference-convincing", "max_forks_repo_head_hexsha": "65eb1cd3bf76f8068889880e0f80178e790350ce", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-02-06T12:08:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T20:40:22.000Z", "avg_line_length": 39.780669145, "max_line_length": 134, "alphanum_fraction": 0.5858798243, "include": true, "reason": "import numpy", "num_tokens": 5474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.38121955219593834, "lm_q1q2_score": 0.19507637489654792}}
{"text": "\"\"\"This is a module for calcuating groups and integrations with JWST on\nthe fly. The main function (``perform_calculation``) takes a dictionary\nof inputs (modeled around how the web tool takes inputs) which must\ninclude: ``observation_time``, ``num_groups``, ``magnitude``,\n``model``, ``band``, ``filt``, ``filt_ta``, ``instrument``,\n``subarray``, ``subarray_ta``, ``saturation_mode``, ``max_saturation``,\nand ``infile``. It produces and dictionary of outputs that includes all\nof the original information as well as groups, integrations, saturation\nlevels, and observation time estimates for target acquisition and\nscience observations with JWST.\n\nAuthors\n-------\n\n    Jules Fowler, April 2017\n    Matthew Bourque, February 2021\n\nUse\n---\n\n    This is mostly a module to be used by the ExoCTK web application,\n    but the main function can be run standalone as such:\n    ::\n\n        from exoctk.groups_integrations.groups_integrations import perform_calculation\n        perform_calculation()\n\nDependencies\n------------\n\n    - ``astropy``\n    - ``numpy``\n    - ``scipy``\n\"\"\"\n\nimport json\nimport math\n\nimport numpy as np\nfrom scipy import interpolate\n\n\ndef calc_duration_time(num_groups, num_integrations, num_reset_frames, frame_time, frames_per_group=1):\n    \"\"\"Calculates duration time (or exposure duration as told by APT)\n\n    Parameters\n    ----------\n    num_groups : int\n        Groups per integration\n    num_integrations : int\n        Integrations per exposure\n    num_reset_frames : int\n        Reset frames per integration\n    frame_time : float\n        Frame time (in seconds)\n    frames_per_group : int, optional\n        Frames per group -- always one except brown dwarves\n\n    Returns\n    -------\n    duration_time : float\n        Duration time (in seconds).\n    \"\"\"\n\n    duration_time = frame_time * (num_groups * frames_per_group + num_reset_frames) * num_integrations\n\n    return duration_time\n\n\ndef calc_exposure_time(num_integrations, ramp_time):\n    \"\"\"Calculates exposure time (or photon collection duration as told\n    by APT.)\n\n    Parameters\n    ----------\n    num_integrations : int\n        Integrations per exposure.\n    ramp_time : float\n        Ramp time (in seconds).\n\n    Returns\n    -------\n    exposure_time : float\n        Exposure time (in seconds).\n    \"\"\"\n\n    exposure_time = num_integrations * ramp_time\n\n    return exposure_time\n\n\ndef calc_frame_time(num_columns, num_rows, num_amps, instrument):\n    \"\"\"Calculates the frame time for a given\n    instrument/readmode/subarray.\n\n    Parameters\n    ----------\n    num_columns : int\n        Number of columns\n    num_rows : int\n        Number of rows\n    num_amps : int\n        Amplifiers reading data\n    instrument : str\n        The instrument\n\n    Returns\n    -------\n    frame_time : float\n        The frame time (in seconds)\n    \"\"\"\n\n    num_columns, num_amps, num_rows = int(num_columns), int(num_amps), int(num_rows)\n\n    if instrument == 'nirspec':\n        n = 2\n    if instrument in ['nircam', 'niriss']:\n        n = 1\n\n    frame_time = (num_columns / num_amps + 12) * (num_rows + n) * (1e-5)\n\n    return frame_time\n\n\ndef calc_groups_from_exp_time(max_exptime_per_int, frame_time):\n    \"\"\"Given the maximum saturation time, calculates the number of\n    frames per group.\n\n    Parameters\n    ----------\n    max_exptime_per_int : float\n        The maximum number of seconds an integration can last before\n        it's oversaturated\n    frame_time : float\n        The time per frame\n\n    Returns\n    -------\n    groups : int\n        The required number of groups.\n    \"\"\"\n\n    groups = np.floor(max_exptime_per_int / frame_time)\n\n    return groups\n\n\ndef calc_integration_time(num_groups, frame_time, frames_per_group, num_skips):\n    \"\"\"Calculates the integration time.\n\n    Parameters\n    ----------\n    num_groups : int\n        Groups per integration.]\n    frame_time : float\n        Frame time (in seconds)\n    frames_per_group : int\n        Frames per group -- always 1 except maybe brown dwarves\n    num_skips : int\n        Skips per integration -- always 0 except maybe brown dwarves\n\n    Returns\n    -------\n    integration_time : float\n        Integration time (in seconds)\n    \"\"\"\n\n    integration_time = (num_groups * (frames_per_group + num_skips) - num_skips) * frame_time\n\n    return integration_time\n\n\ndef calc_num_integrations(transit_time, num_groups, num_reset_frames, frame_time, frames_per_group):\n    \"\"\"Calculates number of integrations required.\n\n    Parameters\n    ----------\n    transit_time : float\n        The time of the transit (in hours)\n    num_groups : int\n        Groups per integration\n    num_reset_frames : int\n        Number of reset frames per integration\n    frame_time : float\n        The frame time (in seconds)\n    frames_per_group : int\n        Frames per group -- always 1 except maybe for brown dwarves\n\n    Returns\n    -------\n    num_integrations : float\n        The required number of integraitions.\n    \"\"\"\n\n    num_integrations = math.ceil((float(transit_time) * 3600) / (frame_time * (num_groups * frames_per_group + num_reset_frames)))\n\n    return num_integrations\n\n\ndef calc_observation_efficiency(exposure_time, duration_time):\n    \"\"\"Calculates the observation efficiency.\n\n    Parameters\n    ----------\n    exposure_time : float\n        Exposure time (in seconds).\n    duration_time : float\n        Duration time (in seconds).\n\n    Returns\n    -------\n    observation_efficiency : float\n        Observation efficiency.\n    \"\"\"\n\n    observation_efficiency = exposure_time / duration_time\n\n    return observation_efficiency\n\n\ndef calc_ramp_time(integration_time, num_reset_frames, frame_time):\n    \"\"\"Calculates the ramp time -- or the integration time plus overhead\n    for resets.\n\n    Parameters\n    ----------\n    integration_time : float\n        Integration time (in seconds)\n    num_reset_frames : int\n        Rest frames per integration\n    frame_time : float\n        Frame time (in seconds)\n\n    Returns\n    -------\n    ramp_time : float\n        Ramp time (in seconds).\n    \"\"\"\n\n    ramp_time = integration_time + (num_reset_frames - 1) * frame_time\n\n    return ramp_time\n\n\ndef convert_saturation(max_saturation, saturation_mode, instrument, infile, target_acq_mode=False):\n    \"\"\"Converts full well fraction to a saturation in counts OR\n    provides the max fullwell for TA mode.\n\n    Parameters\n    ----------\n    max_saturation : float\n        Either a full well fraction or counts\n    saturation_mode : str\n        ``well`` or ``counts``\n    instrument : str\n        The instrument\n    infile : str\n        The path to the data file\n    target_acq_mode : bool, optional\n        Whether or not it's TA mode\n\n    Returns\n    -------\n    max_saturation : float\n        The fullwell to use in counts.\n    \"\"\"\n\n    with open(infile) as f:\n        data = json.load(f)\n\n    instrument_dict = data['fullwell']\n\n    if saturation_mode == 'well':\n        max_saturation = float(max_saturation) * float(instrument_dict[instrument])\n\n    if target_acq_mode:\n        max_saturation = instrument_dict[instrument]\n\n    return max_saturation\n\n\ndef interpolate_from_pandeia(magnitude, instrument, filt, subarray, model, band, frame_time, saturation_level, infile, target_acq_mode=False):\n    \"\"\"Interpolates the precalculated ``pandeia`` data to estimate the\n    saturation limit.\n\n    Parameters\n    ----------\n    magnitude : float\n        The magnitude of the source. (Takes between 4.5-12.5)\n    instrument : str\n       The instrument, allowable ``miri``, ``niriss``, ``nirspec``,\n       ``nircam``\n    filt : str\n        The filter\n    subarray : str\n        The subarray\n    model : str\n        Phoenix model key\n    band : str\n        Magnitude band\n    frame_time : float\n        Frame time\n    saturation_level : float\n        The maximum fullwell saturation we'll allow\n    infile : str\n        The data file to use\n    target_acq_mode : bool, optional\n        Whether or not we're running this for TA\n\n    Returns\n    -------\n    num_groups : int\n        The number of groups that won't oversaturate the detector\n    max_sat : int\n        The maximum saturation level reached by that number of groups\n    \"\"\"\n\n    # Create the dictionaries for each filter and select out the prerun data\n    with open(infile) as f:\n        data = json.load(f)\n\n    ta_or_sci = 'sci_sat'\n\n    if target_acq_mode:\n        ta_or_sci = 'ta_sat'\n\n    # The data\n    magnitudes = np.array(data['mags'])\n    saturation = data[ta_or_sci][instrument][filt][subarray][model]\n    log_saturation = np.log10(saturation)\n\n    # Interpolate the given magnitude\n    func_log = interpolate.interp1d(magnitudes, log_saturation)\n    max_log_saturation = func_log(float(magnitude))\n    max_saturation = 10**(max_log_saturation)\n\n    # Figure out what it means in wake of the given saturation lvl\n    max_exptime = float(saturation_level) / max_saturation\n\n    # Calculate the nearest number of groups\n    num_groups = calc_groups_from_exp_time(max_exptime, frame_time)\n\n    # Can't have zero groups\n    num_groups = num_groups or 1\n\n    return num_groups, max_saturation\n\n\ndef map_to_ta_modes(instrument, max_num_groups, min_num_groups):\n    \"\"\"Turns the min/max groups into the closest allowable TA group\n    mode.\n\n    Parameters\n    ----------\n    instrument : str\n        The instrument\n    max_num_groups : int\n        The maximum number of groups without oversaturating\n    min_num_groups : int\n        The groups needed to hit the target SNR\n\n    Returns\n    -------\n    min_ta_groups : int\n        The min possible groups to hit target SNR\n    max_ta_groups : int\n        The max possible groups before saturation\n    \"\"\"\n\n    # Allowable group modes for each instrument\n    groups = {'miri': [3, 5, 9, 15, 23, 33, 45, 59, 75, 93, 113, 135, 159, 185, 243, 275, 513],\n              'niriss': [3, 5, 7, 9, 1, 13, 15, 17, 19],\n              'nirspec': [3],\n              'nircam': [3, 5, 9, 17, 33, 65]}\n\n    # Match the literal min and max groups to the nearest mode.\n    allowable_groups = groups[instrument]\n    min_ta_groups = min(allowable_groups, key=lambda x: abs(x - min_num_groups))\n    max_ta_groups = min(allowable_groups, key=lambda x: abs(x - max_num_groups))\n\n    # Unless it was oversaturated from the get-go OR there aren't enough groups\n    # for SNR\n    if min_num_groups == 0:\n        min_ta_groups = 0\n        max_ta_groups = 0\n    if min_num_groups > max(allowable_groups):\n        min_ta_groups = -1\n        max_ta_groups = 0\n\n    return max_ta_groups, min_ta_groups\n\n\ndef min_num_groups_for_sat(magnitude, instrument, filt, subarray, model, band, infile):\n    \"\"\"Estimates the minimum number of groups to reach target acq\n    saturation requirements.\n\n    Parameters\n    ----------\n    magnitude : float\n        Magnitude of star.\n    instrument : str\n        Instrument.\n    filt : str\n        Filter.\n    subarray : str\n        Subarray.\n    model : str\n        Phoenix model key.\n    band : str, currently unused?\n        The band -- right now only k sooo?\n    infile : str\n        The file with the pandeia data.\n\n    Returns\n    -------\n    min_num_groups_for_sat : int\n        The minimum number of groups to reach target snr.\n    \"\"\"\n\n    with open(infile) as f:\n        data = json.load(f)\n\n    # Match to closest magnitude\n    magnitudes = [float(i) for i in data['mags']]\n    closest_magnitude = min(magnitudes, key=lambda x: abs(x - float(magnitude)))\n    index = magnitudes.index(closest_magnitude)\n\n    # Match to data\n    minimum_num_groups_for_sat = data['ta_snr'][instrument][filt][subarray][model][index]\n\n    return minimum_num_groups_for_sat\n\n\ndef perform_calculation(params, frames_per_group=1, num_skips=0):\n    \"\"\"Calculates all of the outputs and puts them in a dictionary for\n    easy access.\n\n    Parameters\n    ----------\n    params : dict\n        Dictionary of all the needed parameters. Must include:\n        ``obs_time``, ``n_group``, ``mag``, ``mod``, ``band``,\n        ``filt``, ``filt_ta``, ``ins``, ``subarray``, ``subarray_ta``,\n        ``sat_mode``, ``max_sat``, ``infile``\n    frames_per_group : int, optional\n        The number of frames -- almost always 1\n    num_skips: int, optional\n        Number of skips -- almost always 0\n\n    Returns\n    -------\n    params : dict, str\n        Dictionary of outputs and inputs. If the calculation throws an\n        error it will return a string error message instead\n    \"\"\"\n\n    # TARGET ACQ\n    ta_frame_time = set_frame_time(\n        params['infile'], params['ins'], params['subarray_ta'], target_acq_mode=True)\n\n    max_saturation_ta_level = convert_saturation(\n        params['sat_max'], params['sat_mode'], params['ins'], params['infile'], target_acq_mode=True)\n\n    max_num_groups, saturation_rate_ta = interpolate_from_pandeia(\n        params['mag'], params['ins'], params['filt_ta'], params['subarray_ta'], params['mod'], params['band'],\n        ta_frame_time, max_saturation_ta_level, params['infile'], target_acq_mode=True)\n\n    min_num_groups = min_num_groups_for_sat(\n        params['mag'], params['ins'], params['filt_ta'], params['subarray_ta'], params['mod'], params['band'], params['infile'])\n\n    min_ta_groups, max_ta_groups = map_to_ta_modes(params['ins'], max_num_groups, min_num_groups)\n\n    duration_time_ta_min = calc_duration_time(min_ta_groups, 1, 1, ta_frame_time)\n\n    duration_time_ta_max = calc_duration_time(max_ta_groups, 1, 1, ta_frame_time)\n\n    # Science obs\n    # Figure out the rows/cols/amps/pixel_size and saturation\n    instrument_params = set_params_from_instrument(params['ins'], params['subarray'])\n    frame_time = set_frame_time(params['infile'], params['ins'], params['subarray'])\n\n    # Run all the calculations\n    num_rows, num_columns, num_amps, pixel_size, frame_time, num_reset_frames = instrument_params\n    params['sat_max'] = convert_saturation(params['sat_max'], params['sat_mode'], params['ins'], params['infile'])\n\n    # Calculate countrate and n_groups if it isn't supplied\n    num_groups, saturation_rate = interpolate_from_pandeia(\n        params['mag'], params['ins'], params['filt'], params['subarray'], params['mod'], params['band'],\n        frame_time, params['sat_max'], params['infile'])\n    if str(params['n_group']) == 'optimize':\n        params['n_group'] = int(num_groups)\n    else:\n        params['n_group'] = int(float(params['n_group']))\n\n    # Aditional helpful params\n    # Calculate times/ramps/etc\n    integration_time = calc_integration_time(params['n_group'], frame_time, frames_per_group, num_skips)\n    ramp_time = calc_ramp_time(integration_time, num_reset_frames, frame_time)\n\n    # Calculate nubmer of integrations (THE MEAT)\n    num_integrations = calc_num_integrations(params['obs_time'], params['n_group'], num_reset_frames, frame_time, frames_per_group)\n\n    # Other things that may come in handy who knows?\n    exposure_time = calc_exposure_time(num_integrations, ramp_time)\n    duration_time = calc_duration_time(params['n_group'], num_integrations, num_reset_frames, frame_time, frames_per_group)\n    observation_efficiency = calc_observation_efficiency(exposure_time, duration_time)\n\n    # Update params with new information\n    params['duration_time'] = round(duration_time / 3600, 3)\n    params['duration_time_ta_max'] = duration_time_ta_max\n    params['duration_time_ta_min'] = duration_time_ta_min\n    params['exposure_time'] = round(exposure_time / 3600, 3)\n    params['frames_per_group'] = frames_per_group\n    params['frame_time'] = round(frame_time, 3)\n    params['integration_time'] = round(integration_time, 3)\n    params['max_saturation_prediction'] = round(saturation_rate * frame_time * params['n_group'], 3)\n    params['max_saturation_ta'] = round(saturation_rate_ta * ta_frame_time * max_ta_groups, 3)\n    params['min_saturation_ta'] = round(saturation_rate_ta * ta_frame_time * min_ta_groups, 3)\n    params['max_ta_groups'] = int(max_ta_groups)\n    params['min_ta_groups'] = int(min_ta_groups)\n    params['num_amps'] = num_amps\n    params['num_columns'] = num_columns\n    params['num_integrations'] = num_integrations\n    params['num_reset_frames'] = num_reset_frames\n    params['num_rows'] = num_rows\n    params['num_skips'] = num_skips\n    params['observation_efficiency'] = round(observation_efficiency, 3)\n    params['ramp_time'] = round(ramp_time, 3)\n    params['ta_frame_time'] = ta_frame_time\n\n    return params\n\n\ndef set_params_from_instrument(instrument, subarray):\n    \"\"\"Sets/collects the running parameters from the instrument.\n\n    Parameters\n    ----------\n    instrument : str\n        Instrument, options are ``nircam``, ``niriss``, ``nirpec``, and\n        ``miri``\n    subarray : str\n        Subarray mode\n\n    Returns\n    -------\n    rows : int\n        The number of pixels per row.\n    cols : int\n        The number of columns per row.\n    amps : int\n        The number of amplifiers.\n    pixel_size : int\n        The pixel size.\n    frame_time : float\n        The frame time.\n    num_reset_frames : int\n        The number of reset frames.\n    \"\"\"\n\n    num_reset_frames = 1\n\n    if instrument == 'nirspec':\n\n        pixel_size = (40e-4)**2\n        if subarray == 'sub2048':\n            rows, cols = 2048, 32\n        elif subarray in ['sub1024a', 'sub1024b']:\n            rows, cols = 1024, 32\n        elif subarray == 'sub512':\n            rows, cols = 512, 32\n        amps = 1  # 4 if not NRSRAPID????\n        frame_time = calc_frame_time(cols, rows, amps, instrument)\n\n    elif instrument == 'nircam':\n\n        pixel_size = (18e-4)**2\n        if subarray == 'full':\n            rows, cols, amps = 2048, 2048, 4\n        elif subarray == 'subgrism256':\n            rows, cols, amps = 256, 256, 1\n        elif subarray == 'subgrism128':\n            rows, cols, amps = 128, 2048, 1\n        elif subarray == 'subgrism64':\n            rows, cols, amps = 64, 2048, 1\n        frame_time = calc_frame_time(cols, rows, amps, instrument)\n\n    elif instrument == 'miri':\n\n        pixel_size = (25e-4)**2\n        if subarray == 'slitlessprism':\n            rows, cols, frame_time = 416, 72, .159\n        amps = 4\n        num_reset_frames = 0\n\n    elif instrument == 'niriss':\n        pixel_size = (40e-4)**2\n        if subarray == 'substrip96':\n            rows, cols = 2048, 96\n        elif subarray == 'substrip256':\n            rows, cols = 2048, 256\n        amps = 1\n        frame_time = calc_frame_time(cols, rows, amps, instrument)\n\n    return rows, cols, amps, pixel_size, frame_time, num_reset_frames\n\n\ndef set_frame_time(infile, instrument, subarray, target_acq_mode=False):\n    \"\"\"Assign the appropriate frame time based on the instrument and\n    subarray. For now, modes are implied.\n\n    Parameters\n    ----------\n    infile: str\n        The path to the data file.\n    instrument : str\n        The instrument : ``miri``, ``niriss``, ``nirspec``, or\n        ``nircam``\n    subarray : str\n        The subarray\n    target_acq_mode : bool\n        Whether this is for TA or not.\n\n    Returns\n    -------\n    frame_time : float\n        The frame time for this instrument/subarray combo.\n    \"\"\"\n\n    # Read in dict with frame times\n    with open(infile) as f:\n        frame_time = json.load(f)['frame_time']\n\n    if target_acq_mode:\n        frame_time = frame_time[instrument]['ta'][subarray]\n    else:\n        frame_time = frame_time[instrument][subarray]\n\n    return frame_time\n", "meta": {"hexsha": "e200ffed8bea0151e3add9c4e6c62127ea97a44c", "size": 19320, "ext": "py", "lang": "Python", "max_stars_repo_path": "exoctk/groups_integrations/groups_integrations.py", "max_stars_repo_name": "nespinoza/exoctk", "max_stars_repo_head_hexsha": "bb50f592c1143195ee20b4a838ce39c0522d3216", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2018-10-28T09:44:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T18:33:16.000Z", "max_issues_repo_path": "exoctk/groups_integrations/groups_integrations.py", "max_issues_repo_name": "nespinoza/exoctk", "max_issues_repo_head_hexsha": "bb50f592c1143195ee20b4a838ce39c0522d3216", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 358, "max_issues_repo_issues_event_min_datetime": "2018-10-19T19:02:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T19:15:34.000Z", "max_forks_repo_path": "exoctk/groups_integrations/groups_integrations.py", "max_forks_repo_name": "nespinoza/exoctk", "max_forks_repo_head_hexsha": "bb50f592c1143195ee20b4a838ce39c0522d3216", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-11-13T16:47:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-18T18:37:19.000Z", "avg_line_length": 30.1875, "max_line_length": 142, "alphanum_fraction": 0.6570393375, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.27512972382317524, "lm_q1q2_score": 0.19507223846363966}}
{"text": "#cython: profile=True,boundscheck=False\n\nfrom lattice_extension import validate_rxn as validate_rxn\nfrom lattice_extension import propensity as rxn_propensity\nfrom lattice_extension import update_propensities as agents_propensity\nfrom lattice_extension import update_agents_react_prop\nfrom lattice_extension import choose_biased_index as cbindex\nfrom lattice_extension import pick_agent_to_act as pick_agent\n\nfrom math import log\nimport numpy as np\nimport itertools as it\nimport time as ti\n\nimport random as rm\n\nimport modular_core.libprofile as lprf\n\nimport pdb\n\ndef set_state(state, surface_state, time, latt):\n    state[0] = time\n    state[1] = latt.agent_count\n    state[2] = np.mean(surface_state[0])\n    #state[1] = latt.total_population()\n    #state[2:] = spectrum_population(\n    #    latt.spec_count, latt.agent_count, \n    #    latt.species_index_dict, latt.agents)\n    state[3:] = latt.spectrum_population()\n\ndef set_surface_state(surf_state, time, latt):\n    surf_state[0] = latt.population_grid()\n    surf_state[1] = latt.identity_grid()\n    if latt.has_resources:\n        surf_state[2:] = latt.spectrum_resource_grid()\n\ndef capture(data, state, capture_dex, target_dexes):\n    data[:,capture_dex] = [state[dex] for dex in target_dexes]\n\nclass agent(object):\n\n    def __init__(self, variety, motion_prop = 0.0, react_prop = 0.0):\n        self.variety = variety\n        self.motion_prop = motion_prop\n        self.react_prop = react_prop\n        self.total_prop = self.react_prop + self.motion_prop\n        self.behaviors = [self.move, self.react]\n\n    def move_to(self, pos, lattice):\n        site = lattice._lattice_[self.pos]\n        site.agents.remove(self)\n        newpopulace = site.populace.replace(self.variety, '', 1)\n        site.populace = newpopulace\n        site.population = len(newpopulace)\n        site.who = site.identity()\n        lattice.flagged_locs.append(self.pos)\n\n        self.pos = pos\n        newsite = lattice._lattice_[pos]\n        newsite.agents.append(self)\n        newsite.populace += self.variety\n        newsite.population = len(newsite.populace)\n        newsite.who = newsite.identity()\n        lattice.flagged_locs.append(pos)\n\n    def act(self, lattice):\n        prtot = self.total_prop\n        if prtot > 0.0:\n            #normed = [self.motion_prop/prtot, self.react_prop/prtot]\n            #behvs = [normed[0], normed[0] + normed[1]]\n            #rd = rm.random()\n            #if behvs[0] > rd:\n            #    self.move(lattice)\n            #elif behvs[1] > rd:\n            #    self.react(lattice)\n            #else: pdb.set_trace()\n            behvs = [self.motion_prop, self.react_prop]\n            behv = cbindex(behvs,2)\n            self.behaviors[behv](lattice)\n        else: print 'PASSING!'\n\n    def move(self, lattice):\n        new_pos = lattice._lattice_[self.pos].diffuse_pressure()\n        #new_pos = lattice._lattice_[self.pos].diffuse_random()\n        self.move_to(new_pos, lattice)\n\n    def react(self, lattice):\n        site = lattice._lattice_[self.pos]\n        populace = site.populace\n        resources = site.resources\n        valid = [rx for rx in lattice.reactions\t\n            if validate_rxn(rx.used, populace, resources)]\n        rxn_props = [rxn_propensity(\n            rx.used, populace, rx.rate) \n                for rx in valid]\n        rxdex = pick_rxn(rxn_props)\n        rxn = valid[rxdex]\n        rxn.react(site, lattice)\n        lattice.flagged_locs.append(self.pos)\n\n    def update_propensity(self, lattice):\n        lattice.total_agent_propensity -= self.total_prop\n        self.update_react_prop(lattice)\n        self.update_motion_prop(lattice)\n        self.total_prop = self.react_prop + self.motion_prop\n        lattice.total_agent_propensity += self.total_prop\n\n    def update_react_prop(self, lattice):\n        site = lattice._lattice_[self.pos]\n        rxns = lattice.reactions\n        self.react_prop = update_agents_react_prop(\n            site, rxns, lattice.reaction_count)\n\n    def update_motion_prop(self, lattice):            \n        self.motion_prop = lattice._lattice_[\n            self.pos].population**lattice.dimensions\n\nclass agent_immobile(agent):\n\n    def move_to(self, pos, lattice):\n        print 'immobile should not be asked to move!'\n\n    def act(self, lattice):\n        self.react(lattice)\n\n    def update_propensity(self, lattice):\n        lattice.total_agent_propensity -= self.total_prop\n        self.update_react_prop(lattice)\n        self.total_prop = self.react_prop\n        lattice.total_agent_propensity += self.total_prop\n\n    def update_motion_prop(self, lattice):            \n        print 'immobile agent should not be asked up update motion_prop!!'\n        self.motion_prop = 0.0\n\ndef pick_rxn(rxn_props):\n    table = []\n    ptot = sum(rxn_props)\n    rd = rm.uniform(0.0, ptot)\n    for p in rxn_props: table.append(sum(table) + p)\n    for tx, t in enumerate(table):\n        if rd < t: return tx\n\nclass reaction(object):\n\n    def __init__(self, rxn, specs):\n        def convert(ag):\n            stoch = int(ag[ag.find('(')+1:ag.find(')')])\n            spec = ag[ag.find(')')+1:]\n            isresource = not spec in specs\n            return (stoch, spec, isresource)\n        self.rxnstr = rxn\n        rxnspl = rxn.split('->')\n        front = rxnspl[0]\n        self.rate = float(front[front.find('[')+1:front.find(']')])\n        used, prod = front[:front.find('[')], rxnspl[1]\n        if not used == '': used = used.split('+')\n        else: used = []\n        if not prod == '': prod = prod.split('+')\n        else: prod = []\n        self.used = [convert(us) for us in used]\n        self.prod = [convert(pr) for pr in prod]\n        self.flux = len(self.prod) - len(self.used)\n\n    def react(self, site, lattice):\n        pop = site.populace[:]\n        resources = site.resources\n        res_varis = [res.variety for res in resources]\n        for u in self.used:\n            if u[2]:\n                rdex = res_varis.index(u[1])\n                resource = resources[rdex]\n                resource.quantity -= u[0]\n            else: pop = pop.replace(u[1], '', u[0])\n        for p in self.prod:\n            if p[2]:\n                rdex = res_varis.index(p[1])\n                resource = resources[rdex]\n                resource.quantity += p[0]\n            else: pop += p[1]*p[0]\n        site.resolve_agents(lattice, pop)\n\nclass site_resource(object):\n    def __init__(self, pos, quantity = 1, variety = 'food'):\n        self.variety = variety\n        self.quantity = quantity\n\n#site_topology instances describe the connectivity of an N\n# dimensional lattice site to its neighboring sites\nclass site_topology(object):\n    def __init__(self, pos, lshape, max_occupancy = None):\n        self.pos = pos\n        self.lshape = lshape\n        self.dims = len(pos)\n        self.max_occupancy = max_occupancy\n        self.set_step_positions()\n\n    def set_step_positions(self):\n        pos = self.pos\n        self.dn_steps = [list(pos[:]) for x in range(self.dims)]\n        self.up_steps = [list(pos[:]) for x in range(self.dims)]\n        axlen = self.lshape[0]\n        for d in range(self.dims):\n            if pos[d] == 0:\n                dstep = 1 - axlen\n                ustep = 1\n            elif pos[d] == axlen - 1:\n                dstep = 1\n                ustep = 1 - axlen\n            else:\n                dstep = 1\n                ustep = 1\n\n            self.dn_steps[d][d] -= dstep\n            self.up_steps[d][d] += ustep\n\n        self.up_steps = [tuple(x) for x in self.up_steps]\n        self.dn_steps = [tuple(x) for x in self.dn_steps]\n        self.all_steps = self.up_steps + self.dn_steps\n        self.neighbor_count = len(self.all_steps)\n\n    def step(self, axdex, dir_):\n        if dir_: new = self.up_steps[axdex]\n        else: new = self.dn_steps[axdex]\n        return new\n\nclass lattice_site(object):\n\n    def __init__(self, args, pop = ''):\n        self.position = args[0]\n        self.lshape = args[1]\n        self.species = args[2].species\n        self.resources = args[3]\n        #self.resources = [site_resource(self.position)]\n        self.resource_names = [r.variety for r in self.resources]\n        self.dims = len(self.position)\n        self.agents = []\n        self.populace = pop\n        self.population = len(pop)\n        self.who = self.identity()\n        self.lattice = args[2]\n        max_occupancy = args[2].max_occupancy\n        self.topology = site_topology(\n            self.position, self.lshape, max_occupancy)\n                \n    def resolve_agents(self, lattice, pop):\n        local_ags = [ag for ag in self.agents if not ag.variety == '_']\n        #local_ags = [ag for ag in lattice.agents if ag.pos == self.position]\n        local_pop = [ag.variety for ag in local_ags]\n        left = []\n        for ag in local_ags:\n            if ag.variety in pop: pop = pop.replace(ag.variety, '', 1)\n            else: left.append(ag)\n\n        for p in pop: lattice.put_onto_lattice_at_site(self.position, agent(p))\n        for p in left: lattice.remove_from_lattice_site(self.position, p)\n\n    def diffuse_pressure(self):\n        adjacents = self.topology.all_steps\n        ncnt = self.topology.neighbor_count\n        latt = self.lattice._lattice_\n        adjac_pops = [latt[pos].population for pos in adjacents]\n        max_po = max(adjac_pops)\n        adjac_pops = [-1.0*po + max_po for po in adjac_pops]\n        lookup = cbindex(adjac_pops, ncnt)\n        step = adjacents[lookup]\n        return step\n\n    def diffuse_random(self):\n        step_dim = rm.randrange(self.dims)\n        dir_ = rm.random() > 0.5\n        step = self.topology.step(step_dim, dir_)\n        return step\n\n    def identity(self):\n        if not self.populace: return 0\n        for sdx in range(len(self.species)):\n            sp = self.species[sdx]\n            if sp in self.populace: return sdx + 1\n        return 0\n\n    def what(self, resource_dex):\n        res = self.resources[resource_dex]\n        return res.quantity\n\nclass lattice(object):\n\n    def __init__(self, *args, **kwargs):\n        if 'dims' in kwargs.keys(): dims = kwargs['dims']\n        else: dims = 2\n        if 'ax_length' in kwargs.keys(): ax_length = kwargs['ax_length']\n        else: ax_length = 5\n        if 'species' in kwargs.keys(): specs = kwargs['species']\n        else: specs = []\n        if 'reactions' in kwargs.keys(): rxns = kwargs['reactions']\n        else: rxns = []\n        if 'birthing_flag' in kwargs.keys(): bflag = kwargs['birthing_flag']\n        else: bflag = False\n        if 'max_occupancy' in kwargs.keys():\n            max_occupancy = kwargs['max_occupancy']\n        else: max_occupancy = None\n        if 'resources' in kwargs.keys(): ress = kwargs['resources']\n        else: ress = []\n        self.agents = []\n        self.agent_count = 0\n        self.species = specs\n        self.spec_count = len(specs)\n        self.total_agent_propensity = 0\n        self.agents_propensities = []\n        #spdxdict = {}\n        #for sdx in xrange(self.spec_count):\n        #    spec = self.species[sdx]\n        #    spdxdict[spec] = sdx\n        #self.species_index_dict = spdxdict\n        self.species_spectrum = {}\n        for ke in self.species: self.species_spectrum[ke] = 0\n        self.reactions = [reaction(rx, specs) for rx in rxns]\n        self.reaction_count = len(rxns)\n        #self.birth_reactions =\\\n        #    [rx for rdx, rx in enumerate(self.reactions) if rdx in brxns]\n        self.birth_flag = bflag\n        self.max_occupancy = max_occupancy\n        self.resources = ress\n        if len(ress) == 0: self.has_resources = False\n        else: self.has_resources = True\n        self.make_lattice(dims, ax_length, ress)\n\n    def make_lattice(self, dims, maxax, ress):\n        #must add ress contents here; right now its hardcoded\n        self.dimensions = dims\n        self.max_axis_size = maxax\n        v_site = np.vectorize(lattice_site)\n        init_arry = np.empty((maxax,)*dims,dtype = object)\n        self.locs = [x for x in it.product(*[range(maxax)]*dims)]\n        lattice = np.empty((maxax,)*dims,dtype = object)\n        shp = lattice.shape\n        for pos in self.locs:\n            res = []\n            for re in ress:\n                if re[0] == 'all' or re[0].count(pos) > 0:\n                    res.append(site_resource(pos, re[2], re[1]))\n            init_arry[pos] = (pos, shp, self, res)\n        lattice[:] = v_site(init_arry)\n        self._lattice_ = lattice\n        self.flagged_locs = []\n        if self.birth_flag:\n            for pos in self.locs:\n                bagent = agent_immobile('_')\n                self.put_onto_lattice_at_site(pos, bagent)\n                self.flagged_locs.append(pos)\n\n    def put_onto_lattice_at_site(self, pos, agent):\n        self.agents.append(agent)\n        if pos == 'random':pos = rm.choice(self.locs)\n        agent.pos = pos\n        site = self._lattice_[pos]\n        site.agents.append(agent)\n        if not agent.variety == '_':\n            self.species_spectrum[agent.variety] += 1\n            site.populace += agent.variety\n            self.agent_count += 1\n        site.population = len(site.populace)\n        site.who = site.identity()\n\n    def remove_from_lattice_site(self, pos, agent):\n        self.species_spectrum[agent.variety] -= 1\n        site = self._lattice_[pos]\n        site.populace = site.populace.replace(agent.variety, '', 1)\n        site.population = len(site.populace)\n        site.who = site.identity()\n        site.agents.remove(agent)\n        self.agents.remove(agent)\n        self.agent_count -= 1\n\n    def total_propensity(self):\n        return self.total_agent_propensity\n\n    def act_agent(self, agdex):\n        agent = self.agents[agdex]\n        agent.act(self)\n\n    def get_clean_fixed_surf(self):\n        def fix(d):\n            if d in relev: return slice(None)\n            else: return fixins[d]\n        fixins = [0 for d in range(self.dimensions)]\n        relev = [0,1]\n        fixed = [fix(d) for d in range(len(fixins))]\n        maxax = self.max_axis_size\n        surf = np.zeros((maxax, maxax), dtype = np.int)\n        return surf, fixed\n\n    def population_grid(self):\n        surf, fixed = self.get_clean_fixed_surf()\n        surf[:,:] = [[sit.population for sit in ax] \n            for ax in self._lattice_[fixed]]\n        return surf\n\n    def identity_grid(self):\n        surf, fixed = self.get_clean_fixed_surf()\n        surf[:,:] = [[sit.who for sit in ax] \n            for ax in self._lattice_[fixed]]\n        return surf\n\n    def spectrum_population(self):\n        spectrum = [0]*self.spec_count\n        for sdx in xrange(self.spec_count):\n            sp = self.species[sdx]\n            spectrum[sdx] = self.species_spectrum[sp]\n        return spectrum\n\n    def spectrum_resource_grid(self):\n        def resource_grid(res):\n            surf, fixed = self.get_clean_fixed_surf()\n            surf[:,:] = [[sit.what(res) for sit in ax] \n                for ax in self._lattice_[fixed]]\n            return surf\n        grids = []\n        #for res in self.resources:\n        for rsdx in range(len(self.resources)):\n            grids.append(resource_grid(rsdx))\n        return grids\n\ndef_string = ''\ndef simulate(sys_string = def_string):\n    species = ['A', 'B', 'C']\n    #agents = [\n    #    ((1,3),'A'),((4,3),'B'),((8,7),'C'), \n    #    ((95,7),'A'),((84,9),'B'),((88,2),'C'), \n    #    ((93,83),'A'),((84,93),'B'),((88,87),'C'), \n    #    ((2,93),'A'),((6,83),'B'),((4,97),'C'), \n    #        ]\n    agents =\\\n        [('random', 'A')]*3333 +\\\n        [('random', 'B')]*3333 +\\\n        [('random', 'C')]*3333 \n    reactions = [\n        #'(1)A+(1)food[5.0]->(2)A', \n        #'(1)B+(1)food[5.0]->(2)B', \n        #'(1)C+(1)food[5.0]->(2)C', \n        '(1)A+(1)B[5.0]->(2)A', \n        '(1)B+(1)C[5.0]->(2)B', \n        '(1)C+(1)A[5.0]->(2)C', \n        #'(1)A[0.01]->', \n        #'(1)B[0.01]->', \n        #'(1)C[0.01]->', \n        #'[0.01]->(1)A', \n        #'[0.01]->(1)B', \n        #'[0.01]->(1)C', \n                ]\n    #birthing_rxns = [6]\n    birthing_flag = False#True\n    resources = []#[('all', 'food', 3)]\n    lattice_dims = 2\n    lattice_size = 100\n    max_occupancy = 2\n    timed_out = False\n    timed_out_limit = 3600.0\n\n    # I TREAT AGENTS AT EACH LATTICE SITE AS INDISTINGUISHABLE\n    #  BUT THE LOCAL AGENTS ARE REMOVED IN REVERSE ORDER OF ENTERING THE SITE\n    ### to properly include birth reactions - treat lattice sites as agents\n    ###  with zero motion propensity\n    # still want occupancy handling\n    # species can only have a single letter to identify\n    # voxel visualization pipeline for 3-d subspaces (perfectly analogous to\n    #  surface_data pipeline)\n    # statistics on average agent (average agent trajectory really....)\n    # add full function/variable pipeline for reactions\n    # add full mcfg/sys_string pipeline\n    # introduce concept of nations (groups of agents)\n    # i double count propensities since which agent initiates a reaction\n    #  is never relevant - only the variety of agents post reaction\n\n    time = 0.0\n    last_time = 0.0\n    end_time = 50.0\n    incr_time = 0.1\n\n    total_captures = end_time/incr_time\n    capture_count = 0                               \n    res_names = [r[1] for r in resources]\n    targets = ['time', 'population', 'mean_occupancy'] + species[:]# + res_names\n    plot_targets = ['time', 'population', 'mean_occupancy'] + species[:]# + res_names\n    surf_targets = [\n        'population_surfaces', \n        'identity_surfaces'] + ['resource_surface_' + r for r in res_names]\n    plot_surf_targets = [\n        'population_surfaces', \n        'identity_surfaces'] + ['resource_surface_' + r for r in res_names] \n    #voxel_targets = ['identity_voxels']\n    #plot_voxel_targets = ['identity_voxels']\n    target_dexes = [targets.index(ta) for ta in plot_targets]\n    surf_target_dexes = [surf_targets.index(ta) for ta in plot_surf_targets]\n    #voxel_target_dexes = [voxel_targets.index(ta) for ta in plot_voxel_targets]\n    _lattice_ = lattice(\n        dims = lattice_dims, ax_length = lattice_size, species = species, \n        reactions = reactions, max_occupancy = max_occupancy, \n        birthing_flag = birthing_flag, resources = resources)\n    for ag in agents: _lattice_.put_onto_lattice_at_site(ag[0],agent(ag[1]))\n    for ag in _lattice_.agents: ag.update_propensity(_lattice_)\n    maxax = _lattice_.max_axis_size\n    state = np.zeros(shape = (len(targets)), dtype = np.float)\n    surface_state = np.zeros(shape=(len(surf_targets),maxax,maxax),dtype=np.float)\n    #voxel_state = np.zeros(shape=(len(voxel_targets),maxax,maxax,maxax),dtype=np.float)\n    data = np.zeros(shape=(len(plot_targets),total_captures),dtype=np.float)\n    surface_data = np.zeros(shape = (len(surf_targets), \n    \ttotal_captures, maxax, maxax), dtype = np.float)\n    #voxel_data = np.zeros(shape = (len(voxel_targets), \n    #\ttotal_captures, maxax, maxax, maxax), dtype = np.float)\n    #set_voxel_state(voxel_state, time, _lattice_)\n    set_surface_state(surface_state, time, _lattice_)\n    set_state(state, surface_state, time, _lattice_)\n\n    start_time = ti.time()\n    if birthing_flag: dead_eco_check = lambda : False\n    else: dead_eco_check = lambda : not _lattice_.agent_count > 0\n    dead_eco = dead_eco_check()\n    while capture_count < total_captures and not dead_eco and not timed_out:\n        propensity_total = _lattice_.total_propensity()\n        if propensity_total > 0.0 and _lattice_.agent_count > 0:\n            propensity_total_inv = 1.0/propensity_total\n            time_step = -1.0 * log(rm.random()) * propensity_total_inv\n            acnt = len(_lattice_.agents)\n            agrand = rm.uniform(0.0, propensity_total)\n            agent_dex = pick_agent(_lattice_.agents, acnt, agrand)\n        else:\n            time_step = incr_time\n            agent_dex = -1\n\n        time += time_step\n        #set_surface_state(surface_state, time, _lattice_)\n        set_state(state, surface_state, time, _lattice_)\n\n        real_time = state[0]\n        if last_time < real_time and capture_count < total_captures:\n            #set_voxel_state(voxel_state, time, _lattice_)\n            set_surface_state(surface_state, time, _lattice_)\n            set_state(state, surface_state, time, _lattice_)\n        while last_time < real_time and capture_count < total_captures:\n            state[0] = last_time\n            last_time += incr_time\n            capture(data, state, capture_count, target_dexes)\n            capture(surface_data, surface_state, capture_count, surf_target_dexes)\n            #capture(voxel_data, voxel_state, capture_count, voxel_target_dexes)\n            capture_count += 1\n            print 'time', last_time, 'pop', len(_lattice_.agents)\n        state[0] = real_time\n\n        #agent activity cant depend on state/surface_state...\n        if agent_dex >= 0: _lattice_.act_agent(agent_dex)\n        agents_propensity(_lattice_)\n\n        if ti.time() - start_time > timed_out_limit: timed_out = True\n        dead_eco = dead_eco_check()\n\n    if timed_out or dead_eco:                        \n        #set_surface_state(surface_state, time, _lattice_)\n        state[0] = last_time\n        last_time += incr_time\n        capture(data, state, capture_count, target_dexes)\n        capture(surface_data, surface_state, capture_count, surf_target_dexes)\n        #capture(voxel_data, voxel_state, capture_count, voxel_target_dexes)\n        capture_count += 1\n        print 'time', last_time, 'pop', len(_lattice_.agents)\n\n        toss = capture_count\n        #voxel_data = voxel_data[:,:toss,:,:]\n        surface_data = surface_data[:,:toss,:,:]\n        data = data[:,:toss]\n        return data,surface_data,targets + surf_targets\n    return data, surface_data, targets + surf_targets\n\nif __name__ == '__main__':\n    import sys\n    if len(sys.argv) > 1: use_pyx = sys.argv[1]\n    else: use_pyx = False\n    if use_pyx:\n        import lattice_simulator as lsim\n        print 'USING CYTHON!'\n        lprf.profile_function(lsim.simulate)\n    else:\n        lprf.profile_function(simulate)\n    #lprf.profile_function(simulate)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "9ad159c483aa45108fb54ef881b22d12887216b3", "size": 22046, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/support/liblattice_sim.py", "max_stars_repo_name": "ctogle/lattice", "max_stars_repo_head_hexsha": "6f9e64102786899a4119757d2a12e1c63fd4b640", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/support/liblattice_sim.py", "max_issues_repo_name": "ctogle/lattice", "max_issues_repo_head_hexsha": "6f9e64102786899a4119757d2a12e1c63fd4b640", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/support/liblattice_sim.py", "max_forks_repo_name": "ctogle/lattice", "max_forks_repo_head_hexsha": "6f9e64102786899a4119757d2a12e1c63fd4b640", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6821963394, "max_line_length": 88, "alphanum_fraction": 0.6068220992, "include": true, "reason": "import numpy", "num_tokens": 5811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.33111975283019596, "lm_q1q2_score": 0.1949928234242335}}
{"text": "\"\"\" Functions used to assign restframe g-r and r-i SDSS colors to mock galaxies.\n\"\"\"\nimport numpy as np\nfrom .sawtooth_binning import sawtooth_bin_indices\nfrom astropy.utils.misc import NumpyRNGContext\nfrom halotools.empirical_models import polynomial_from_table\nfrom ..sdss_colors.sdss_completeness_model import retrieve_sdss_sample_mask\n\n\n__all__ = ('mc_sdss_gr_ri', )\n\n\ndefault_seed = 43\n\n\ndef assign_data_source(mock_logsm, table_abscissa=np.array([8.5, 9, 9.5, 10]),\n            table_ordinates=np.array([1, 0.8, 0.35, 0]), seed=default_seed):\n    \"\"\"\n    Determine the source of observational data that will be used\n    to map colors onto mock galaxies.\n\n    For entries in the returned ndarray equal to zero, real SDSS objects\n    will be used to map colors onto mock galaxies.\n\n    For entries in the returned ndarray equal to one, fake SDSS objects will be used.\n\n    Parameters\n    ----------\n    mock_logsm : ndarray\n        Numpy array of shape (ngals, ) storing the stellar mass of mock galaxies\n\n    table_abscissa : ndarray, optional\n        Control points in log10 stellar mass at which the data source probability is defined\n\n    table_ordinates : ndarray, optional\n        Control points defining the probability that\n        a mock galaxy will be assigned to data source one.\n\n    seed : int, optional\n        Random number seed. Default is default_seed, set at the top of\n        the module where the function is defined.\n\n    Returns\n    -------\n    data_source : ndarray\n        Numpy array of shape (ngals, ) storing an integer indicating the data source\n        from which colors will be drawn\n    \"\"\"\n    input_abscissa = np.linspace(table_abscissa.min(), table_abscissa.max(), 100)\n    ordinates = polynomial_from_table(table_abscissa, table_ordinates, input_abscissa)\n\n    prob_fake = np.interp(mock_logsm, input_abscissa, ordinates)\n    with NumpyRNGContext(seed):\n        fake_mask = np.random.rand(len(mock_logsm)) < prob_fake\n    data_source = np.zeros_like(fake_mask).astype(int)\n    data_source[fake_mask] = 1\n\n    return data_source\n\n\ndef fuzzy_sawtooth_magr_binning(mock_rmag, data_source, magr_bins=None, seed=default_seed):\n    \"\"\" Assign galaxies to overlapping bins based on their restframe absolute r-band magnitude.\n\n    Binning will be done separately for mock galaxies above and below the SDSS completeness limit.\n\n    Parameters\n    ----------\n    mock_rmag : ndarray\n        Numpy array of shape (ngals, ) storing the\n        restframe absolute r-band magnitude of mock galaxies\n\n    data_source : ndarray\n        Numpy array of shape (ngals, ) storing an integer indicating the data source\n        from which colors will be drawn (zero for real data, one for fake data).\n\n    magr_bins : ndarray, optional\n        Numpy array of shape (nbins, ) storing the bin boundaries.\n        Must strictly encompass the range spanned by the mock.\n        Default is to use 25 bins linearly spaced in Magr covering a range that\n        just beyond the boundaries of the data.\n\n    seed : int, optional\n        Random number seed. Default is default_seed, set at the top of\n        the module where the function is defined.\n\n    Returns\n    -------\n    rmag_bin_number : ndarray\n        Numpy integer array of shape (ngals, ) storing the bin number of each mock galaxy\n    \"\"\"\n    if magr_bins is None:\n        epsilon = 0.01\n        rmin, rmax, dr = mock_rmag.min()-epsilon, mock_rmag.max()+epsilon, 0.2\n        magr_bins = np.arange(rmin, rmax+dr, dr)\n\n    source0_mask = data_source == 0\n    rmag_bin_number = -np.ones_like(mock_rmag).astype('i4')\n    rmag_bin_number[source0_mask] = sawtooth_bin_indices(mock_rmag[source0_mask], magr_bins, seed=seed)\n    rmag_bin_number[~source0_mask] = sawtooth_bin_indices(mock_rmag[~source0_mask], magr_bins, seed=seed)\n    return rmag_bin_number\n\n\ndef mc_true_sdss_gr_ri(sdss_redshift, sdss_magr, sdss_gr, sdss_ri,\n        mock_magr_bin_number, mock_magr, mock_sfr_percentile, sigma=0., k=10, seed=default_seed):\n    \"\"\" Given {Mr, SFR-percentile} for mock galaxies, search SDSS data\n    to select galaxies with matching {Mr, g-r-percentile}, and use the colors\n    {g-r, r-i} of the selected SDSS galaxies to paint on to the mock galaxies.\n    \"\"\"\n    from scipy.spatial import cKDTree\n    from scipy.stats import gaussian_kde\n\n    mock_gr = np.zeros_like(mock_magr)\n    mock_ri = np.zeros_like(mock_magr)\n\n    #  We loop over probabilistically overlapping bins of r-band magnitude\n    magr_bin_numbers = list(set(mock_magr_bin_number))\n    for bin_number in magr_bin_numbers:\n        mock_magr_mask = mock_magr_bin_number == bin_number\n        npts_mock_bin = np.count_nonzero(mock_magr_mask)\n\n        mock_magr_bin = mock_magr[mock_magr_mask]\n        mock_sfr_percentile_bin = mock_sfr_percentile[mock_magr_mask]\n\n        #  Make a cut to apply a color-completeness limiting redshift\n        Mr_min, Mr_max = mock_magr_bin.min(), mock_magr_bin.max()\n        sdss_mask = retrieve_sdss_sample_mask(sdss_redshift, sdss_magr, Mr_min, Mr_max)\n        sdss_rmag_bin = sdss_magr[sdss_mask]\n        sdss_gr_bin = sdss_gr[sdss_mask]\n        sdss_ri_bin = sdss_ri[sdss_mask]\n\n        #  Use Gaussian kernel density estimation on the SDSS data\n        #  to generate a random sampling of colors for each mock galaxy\n        #  This step helps smooth out artificial clustering of mock galaxies\n        #  around outlier fluctuations in the observed data\n        X_bin = np.vstack((sdss_rmag_bin, sdss_gr_bin, sdss_ri_bin))\n        kde_bin = gaussian_kde(X_bin)\n        with NumpyRNGContext(seed):\n            resampled_bin = kde_bin.resample(npts_mock_bin)\n        sdss_rmag_bin_resampled = resampled_bin[0, :]\n        sdss_gr_bin_resampled = resampled_bin[1, :]\n        sdss_ri_bin_resampled = resampled_bin[2, :]\n\n        #  Sort the mock galaxies in the bin by their SFR-rank-order-percentile (at fixed M*)\n        #  Sort the Monte Carlo realization of g-r\n        #  Apply the implicit non-parametric map to paint g-r onto mock galaxies\n        idx_mock_percentile_sorted = np.argsort(mock_sfr_percentile_bin)\n        mock_gr_bin = np.zeros(npts_mock_bin).astype('f4')\n        mock_gr_bin[idx_mock_percentile_sorted] = np.sort(sdss_gr_bin_resampled)[::-1]\n\n        #  Now run a nearest-neighbor search on the KDE-resampled SDSS data\n        #  to identify an r-i color of a galaxy with a closely matching {Mr, g-r}.\n        #  Randomly selecting one of the 10 nearest neighbors helps smear out\n        #  artificial amplification of hard edges in the observed data\n        Y = np.vstack((sdss_rmag_bin_resampled, sdss_gr_bin_resampled)).T\n        sdss_tree = cKDTree(Y)\n        knn = min(k, len(sdss_rmag_bin_resampled))\n        result = sdss_tree.query(np.vstack((mock_magr_bin, mock_gr_bin)).T, k=knn)\n        nn_indices = result[1]\n        with NumpyRNGContext(seed):\n            a = np.random.randint(0, nn_indices.shape[1], nn_indices.shape[0])\n        idx = nn_indices[np.arange(nn_indices.shape[0]), a]\n        mock_ri_bin = sdss_ri_bin_resampled[idx]\n\n        mock_gr[mock_magr_mask] = mock_gr_bin\n        mock_ri[mock_magr_mask] = mock_ri_bin\n\n    return mock_gr, mock_ri\n\n\ndef mc_fake_sdss_gr_ri(sdss_gr, sdss_ri, rmag_bin_number, mock_log10_mstar, seed=default_seed):\n    \"\"\" Set up a simple multivariate Gaussian model to extrapolate SDSS colors\n    {g-r, r-i} into the very faint end.\n    \"\"\"\n    gr_center = np.median(sdss_gr)-0.35\n    ri_center = np.median(sdss_ri)-0.15\n    median_gr = np.interp(mock_log10_mstar, [6, 9], [gr_center-0.2, gr_center])\n    median_ri = np.interp(mock_log10_mstar, [6, 9], [ri_center-0.3, ri_center])\n    median_array = np.vstack((median_gr, median_ri)).T\n\n    ngals_mock = len(mock_log10_mstar)\n    X = np.vstack((sdss_gr, sdss_ri))\n    cov = np.cov(X)/2.\n\n    with NumpyRNGContext(seed):\n        Z = np.random.multivariate_normal(\n            mean=(0, 0), cov=cov, size=ngals_mock) + median_array\n    mock_gr, mock_ri = Z[:, 0], Z[:, 1]\n    return mock_gr, mock_ri\n\n\ndef mc_sdss_gr_ri(mock_rmag, mock_mstar, mock_sfr_percentile,\n            sdss_redshift, sdss_magr, sdss_gr, sdss_ri, k=10, seed=default_seed):\n    \"\"\" Divide mock galaxies into a sample for which colors from real SDSS galaxies\n    will be drawn, and another sample for which colors from the extrapolation model\n    will be drawn, creating a fuzzy boundary in stellar mass that stitches the\n    two samples together. Then for each sample, call the appropriate\n    Monte Carlo function to generate {g-r, r-i} colors.\n    \"\"\"\n    mock_data_source = assign_data_source(np.log10(mock_mstar), seed=seed)\n    mock_rmag_bin_number = fuzzy_sawtooth_magr_binning(mock_rmag, mock_data_source, seed=seed)\n\n    source0_mask = mock_data_source == 0\n\n    mock_source0_gr, mock_source0_ri = mc_true_sdss_gr_ri(\n        sdss_redshift, sdss_magr, sdss_gr, sdss_ri,\n        mock_rmag_bin_number[source0_mask], mock_rmag[source0_mask],\n        mock_sfr_percentile[source0_mask], k, seed=seed)\n\n    mock_source1_gr, mock_source1_ri = mc_fake_sdss_gr_ri(sdss_gr, sdss_ri,\n            mock_rmag_bin_number[~source0_mask], np.log10(mock_mstar[~source0_mask]), seed=seed)\n\n    output_mock_gr = np.zeros_like(mock_rmag) - 999.\n    output_mock_ri = np.zeros_like(mock_rmag) - 999.\n    output_mock_gr[source0_mask] = mock_source0_gr\n    output_mock_ri[source0_mask] = mock_source0_ri\n    output_mock_gr[~source0_mask] = mock_source1_gr\n    output_mock_ri[~source0_mask] = mock_source1_ri\n\n    return output_mock_gr, output_mock_ri\n", "meta": {"hexsha": "a29cdf0cfebad63c16d320994e2821e4dea57e57", "size": 9489, "ext": "py", "lang": "Python", "max_stars_repo_path": "cosmodc2/sdss_colors/restframe_sdss_gr_ri.py", "max_stars_repo_name": "ArgonneCPAC/skysim", "max_stars_repo_head_hexsha": "f271debe3439efd1ae5230c6020b2dbc5f79d824", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-08-08T10:01:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T07:21:00.000Z", "max_issues_repo_path": "cosmodc2/sdss_colors/restframe_sdss_gr_ri.py", "max_issues_repo_name": "ArgonneCPAC/skysim", "max_issues_repo_head_hexsha": "f271debe3439efd1ae5230c6020b2dbc5f79d824", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 67, "max_issues_repo_issues_event_min_datetime": "2018-07-16T22:12:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-02T01:12:48.000Z", "max_forks_repo_path": "cosmodc2/sdss_colors/restframe_sdss_gr_ri.py", "max_forks_repo_name": "aphearin/cosmodc2", "max_forks_repo_head_hexsha": "5bc2abebd7123f29b424efc11c3ef374a51cd6c1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.1318181818, "max_line_length": 105, "alphanum_fraction": 0.7120876805, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 2534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376236, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.19499281475908362}}
{"text": "\"\"\"\nThis is to generate interaction energies and corresponding translational vectors, \ngiven a fixed receptor and an ensemble of ligand coordinates (including rotations and/or configurations)\n\"\"\"\nfrom __future__ import print_function\n\nimport numpy as np\nimport netCDF4\n\ntry:\n    from bpmfwfft.grids import RecGrid\n    from bpmfwfft.grids import LigGrid\n\nexcept:\n    from grids import RecGrid\n    from grids import LigGrid\n\n\nKB = 0.001987204134799235\n\n\nclass Sampling(object):\n    def __init__(self, rec_prmtop, lj_sigma_scal_fact, rec_inpcrd, \n                        bsite_file, grid_nc_file,\n                        lig_prmtop, lig_inpcrd,\n                        lig_coord_ensemble,\n                        energy_sample_size_per_ligand,\n                        output_nc,\n                        temperature=300.):\n        \"\"\"\n        :param rec_prmtop: str, name of receptor prmtop file\n        :param lj_sigma_scal_fact: float, used to check consitency when loading receptor and ligand grids\n        :param rec_inpcrd: str, name of receptor inpcrd file\n        :param bsite_file: None or str, name of file defining the box, the same as\n        from AlGDock pipeline. \"measured_binding_site.py\"\n        :param grid_nc_file: str, name of receptor precomputed grid netCDF file\n        :param lig_prmtop: str, name of ligand prmtop file\n        :param lig_inpcrd: str, name of ligand inpcrd file\n        :param lig_coord_ensemble: list of 2d array, each array is an ligand coordinate\n        :param energy_sample_size_per_ligand: int, number of energies and translational vectors to store for each ligand crd\n        :param output_nc: str, name of nc file\n        :param temperature: float\n        \"\"\"\n        self._energy_sample_size_per_ligand = energy_sample_size_per_ligand\n        self._beta = 1./ temperature / KB\n\n        rec_grid = self._create_rec_grid(rec_prmtop, lj_sigma_scal_fact, rec_inpcrd, \n                                        bsite_file, grid_nc_file)\n        self._rec_crd = rec_grid.get_crd()\n\n        self._lig_grid = self._create_lig_grid(lig_prmtop, lj_sigma_scal_fact, lig_inpcrd, rec_grid)\n\n        self._lig_coord_ensemble = self._load_ligand_coor_ensemble(lig_coord_ensemble)\n\n        self._nc_handle = self._initialize_nc(output_nc)\n\n    def _create_rec_grid(self, rec_prmtop, lj_sigma_scal_fact, rec_inpcrd, bsite_file, grid_nc_file):\n        rec_grid = RecGrid(rec_prmtop, lj_sigma_scal_fact, rec_inpcrd, bsite_file, \n                            grid_nc_file, new_calculation=False)\n        return rec_grid\n\n    def _create_lig_grid(self, lig_prmtop, lj_sigma_scal_fact, lig_inpcrd, rec_grid):\n        lig_grid = LigGrid(lig_prmtop, lj_sigma_scal_fact, lig_inpcrd, rec_grid)\n        return lig_grid\n\n    def _load_ligand_coor_ensemble(self, lig_coord_ensemble):\n        assert len(lig_coord_ensemble.shape) == 3, \"lig_coord_ensemble must be 3-D array.\"\n        ensemble = lig_coord_ensemble\n        natoms = self._lig_grid.get_natoms()\n        \n        for i in range(len(ensemble)):\n            if (ensemble[i].shape[0] != natoms) or (ensemble[i].shape[1] != 3):\n                raise RuntimeError(\"Ligand crd %d does not have correct shape\"%i)\n        return ensemble\n\n    def _initialize_nc(self, output_nc):\n        nc_handle = netCDF4.Dataset(output_nc, mode=\"w\", format=\"NETCDF4\")\n\n        nc_handle.createDimension(\"three\", 3)\n        rec_natoms = self._rec_crd.shape[0]\n        nc_handle.createDimension(\"rec_natoms\", rec_natoms)\n\n        lig_natoms = self._lig_grid.get_natoms()\n        nc_handle.createDimension(\"lig_natoms\", lig_natoms)\n        nc_handle.createDimension(\"lig_sample_size\", self._lig_coord_ensemble.shape[0])\n\n        nc_handle.createDimension(\"energy_sample_size_per_ligand\", self._energy_sample_size_per_ligand)\n\n\n        nc_handle.createVariable(\"rec_positions\", \"f8\", (\"rec_natoms\", \"three\"))\n        nc_handle.variables[\"rec_positions\"][:,:] = self._rec_crd\n\n        nc_handle.createVariable(\"lig_positions\", \"f8\", (\"lig_sample_size\", \"lig_natoms\", \"three\"))\n        nc_handle.createVariable(\"lig_com\", \"f8\", (\"lig_sample_size\", \"three\"))\n        nc_handle.createVariable(\"volume\", \"f8\", (\"lig_sample_size\"))\n        nc_handle.createVariable(\"nr_grid_points\", \"i8\", (\"lig_sample_size\"))\n\n        nc_handle.createVariable(\"exponential_sums\", \"f8\", (\"lig_sample_size\"))\n        nc_handle.createVariable(\"log_of_divisors\",  \"f8\", (\"lig_sample_size\"))\n\n        nc_handle.createVariable(\"mean_energy\",  \"f8\", (\"lig_sample_size\"))\n        nc_handle.createVariable(\"min_energy\",  \"f8\", (\"lig_sample_size\"))\n        nc_handle.createVariable(\"energy_std\",  \"f8\", (\"lig_sample_size\"))\n\n        nc_handle.createVariable(\"resampled_energies\", \"f8\", (\"lig_sample_size\", \"energy_sample_size_per_ligand\"))\n        nc_handle.createVariable(\"resampled_trans_vectors\", \"i8\", (\"lig_sample_size\", \"energy_sample_size_per_ligand\", \"three\"))\n\n        nc_handle = self._write_grid_info(nc_handle)\n        return nc_handle\n\n    def _write_grid_info(self, nc_handle):\n        \"\"\"\n        write grid info, \"x\", \"y\", \"z\" ...\n        \"\"\"\n        data = self._lig_grid.get_grids()\n        grid_func_names = self._lig_grid.get_grid_func_names()\n        keys = [key for key in data.keys() if key not in grid_func_names]\n\n        for key in keys:\n            for dim in data[key].shape:\n                dim_name = \"%d\"%dim\n                if dim_name not in nc_handle.dimensions.keys():\n                    nc_handle.createDimension(dim_name, dim)\n\n        for key in keys:\n            if data[key].dtype == int:\n                store_format = \"i8\"\n            elif data[key].dtype == float:\n                store_format = \"f8\"\n            else:\n                raise RuntimeError( \"Unsupported dtype %s\"%data[key].dtype )\n            dimensions = tuple([ \"%d\"%dim for dim in data[key].shape ])\n            nc_handle.createVariable(key, store_format, dimensions)\n\n        for key in keys:\n            nc_handle.variables[key][:] = data[key]\n        return nc_handle\n\n    def _save_data_to_nc(self, step):\n        self._nc_handle.variables[\"lig_positions\"][step, :, :] = self._lig_grid.get_crd()\n\n        self._nc_handle.variables[\"lig_com\"][step, :] = self._lig_grid.get_initial_com()\n\n        self._nc_handle.variables[\"volume\"][step] = self._lig_grid.get_box_volume()\n\n        self._nc_handle.variables[\"nr_grid_points\"][step] = self._lig_grid.get_number_translations()\n\n        self._nc_handle.variables[\"exponential_sums\"][step] = self._exponential_sum\n\n        self._nc_handle.variables[\"log_of_divisors\"][step] = self._log_of_divisor\n\n        self._nc_handle.variables[\"mean_energy\"][step] = self._mean_energy\n        self._nc_handle.variables[\"min_energy\"][step] = self._min_energy\n        self._nc_handle.variables[\"energy_std\"][step] = self._energy_std\n\n        self._nc_handle.variables[\"resampled_energies\"][step,:] = self._resampled_energies\n\n        self._nc_handle.variables[\"resampled_trans_vectors\"][step,:,:] = self._resampled_trans_vectors\n        return None\n\n    def _do_fft(self, step):\n        print(\"Doing FFT for step %d\"%step, \"test\")\n        lig_conf = self._lig_coord_ensemble[step]\n        self._lig_grid.cal_grids(molecular_coord = lig_conf)\n\n        energies = self._lig_grid.get_meaningful_energies()\n        print(\"Energies shape:\", energies.shape)\n        self._mean_energy = energies.mean()\n        self._min_energy  = energies.min()\n        self._energy_std  = energies.std()\n        print(\"Number of finite energy samples\", energies.shape[0])\n\n        exp_energies = -self._beta * energies\n        print(f\"Max exp energy {exp_energies.max()}, Min exp energy {exp_energies.min()}\")\n        self._log_of_divisor = exp_energies.max()\n        exp_energies[exp_energies < 0] = 0\n        exp_energies = np.exp(exp_energies - self._log_of_divisor)\n        self._exponential_sum = exp_energies.sum()\n        exp_energies /= self._exponential_sum\n        print(\"Number of exponential energy samples\", exp_energies.sum())\n        # sel_ind = np.random.choice(exp_energies.shape[0], size=self._energy_sample_size_per_ligand, p=exp_energies, replace=True)\n        try:\n            sel_ind = np.random.choice(exp_energies.shape[0], size=self._energy_sample_size_per_ligand, p=exp_energies, replace=False)\n        except:\n            print(f\"Only {np.count_nonzero(exp_energies)} non-zero entries in p, falling back to replacement\")\n            sel_ind = np.random.choice(exp_energies.shape[0], size=self._energy_sample_size_per_ligand, p=exp_energies, replace=True)\n\n        del exp_energies\n\n        self._resampled_energies = [energies[ind] for ind in sel_ind]\n        del energies\n        self._lig_grid.set_meaningful_energies_to_none()\n\n        trans_vectors = self._lig_grid.get_meaningful_corners()\n        self._resampled_trans_vectors = [trans_vectors[ind] for ind in sel_ind]\n        del trans_vectors\n\n        self._resampled_energies = np.array(self._resampled_energies, dtype=float)\n        self._resampled_trans_vectors = np.array(self._resampled_trans_vectors, dtype=int)\n\n        self._save_data_to_nc(step)\n        return None\n\n    def run_sampling(self):\n        \"\"\"\n        \"\"\"\n        for step in range(self._lig_coord_ensemble.shape[0]):\n            self._do_fft(step)\n\n            print(\"Min energy\", self._min_energy)\n            print(\"Mean energy\", self._mean_energy)\n            print(\"STD energy\", self._energy_std)\n            print(\"Initial center of mass\", self._lig_grid.get_initial_com())\n            print(\"Grid volume\", self._lig_grid.get_box_volume())\n            print(\"Number of translations\", self._lig_grid.get_number_translations())\n            print(\"-------------------------------\\n\\n\")\n\n        self._nc_handle.close()\n        return None\n\n#\n#TODO   the class above assumes that the resample size is smaller than number of meaningful energies\n#       in general, the number of meaningful energies can be very smaller or even zero (no energy)\n#       when the number of meaningful energies is zero, that stratum contributes n_points zeros to the exponential mean\n#\n#       so when needs to consider separately 3 cases:\n#           len(meaningful energies) == 0\n#           0< len(meaningful energies) <= resample size\n#           len(meaningful energies) > resample size\n#\n\n\nclass Sampling_PL(Sampling):\n    \n    def _write_data_key_2_nc(self, data, key):\n        if data.shape[0] == 0:\n            return None\n\n        for dim in data.shape:\n            dim_name = \"%d\"%dim\n            if dim_name not in self._nc_handle.dimensions.keys():\n                self._nc_handle.createDimension(dim_name, dim)\n\n        if data.dtype == int:\n            store_format = \"i8\"\n        elif data.dtype == float:\n            store_format = \"f8\"\n        else:\n            raise RuntimeError(\"unsupported dtype %s\"%data.dtype)\n        dimensions = tuple([\"%d\"%dim for dim in data.shape])\n        self._nc_handle.createVariable(key, store_format, dimensions)\n\n        self._nc_handle.variables[key][:] = data\n        return None\n\n    def _initialize_nc(self, output_nc):\n        \"\"\"\n        \"\"\"\n        nc_handle = netCDF4.Dataset(output_nc, mode=\"w\", format=\"NETCDF4\")\n\n        nc_handle.createDimension(\"three\", 3)\n        rec_natoms = self._rec_crd.shape[0]\n        nc_handle.createDimension(\"rec_natoms\", rec_natoms)\n\n        lig_natoms = self._lig_grid.get_natoms()\n        nc_handle.createDimension(\"lig_natoms\", lig_natoms)\n        nc_handle.createDimension(\"lig_sample_size\", self._lig_coord_ensemble.shape[0])\n\n        #nc_handle.createDimension(\"energy_sample_size_per_ligand\", self._energy_sample_size_per_ligand)\n\n        nc_handle.createVariable(\"rec_positions\", \"f8\", (\"rec_natoms\", \"three\"))\n        nc_handle.variables[\"rec_positions\"][:,:] = self._rec_crd\n\n        nc_handle.createVariable(\"lig_positions\", \"f8\", (\"lig_sample_size\", \"lig_natoms\", \"three\"))\n        nc_handle.createVariable(\"lig_com\", \"f8\", (\"lig_sample_size\", \"three\"))\n        nc_handle.createVariable(\"volume\", \"f8\", (\"lig_sample_size\"))\n        nc_handle.createVariable(\"nr_grid_points\", \"i8\", (\"lig_sample_size\"))\n        nc_handle.createVariable(\"nr_finite_energy\", \"i8\", (\"lig_sample_size\"))\n\n        nc_handle.createVariable(\"exponential_sums\", \"f8\", (\"lig_sample_size\"))\n        nc_handle.createVariable(\"log_of_divisors\",  \"f8\", (\"lig_sample_size\"))\n\n        nc_handle.createVariable(\"mean_energy\",  \"f8\", (\"lig_sample_size\"))\n        nc_handle.createVariable(\"min_energy\",  \"f8\", (\"lig_sample_size\"))\n        nc_handle.createVariable(\"energy_std\",  \"f8\", (\"lig_sample_size\"))\n\n        #nc_handle.createVariable(\"resampled_energies\", \"f8\", (\"lig_sample_size\", \"energy_sample_size_per_ligand\"))\n        #nc_handle.createVariable(\"resampled_trans_vectors\", \"i8\", (\"lig_sample_size\", \"energy_sample_size_per_ligand\", \"three\"))\n\n        nc_handle = self._write_grid_info(nc_handle)\n        return nc_handle\n\n    def _save_data_to_nc(self, step):\n        self._nc_handle.variables[\"lig_positions\"][step, :, :] = self._lig_grid.get_crd()\n\n        self._nc_handle.variables[\"lig_com\"][step, :] = self._lig_grid.get_initial_com()\n\n        self._nc_handle.variables[\"volume\"][step] = self._lig_grid.get_box_volume()\n\n        self._nc_handle.variables[\"nr_grid_points\"][step] = self._lig_grid.get_number_translations()\n\n        self._nc_handle.variables[\"nr_finite_energy\"][step] = self._nr_finite_energy\n\n        self._nc_handle.variables[\"exponential_sums\"][step] = self._exponential_sum\n\n        self._nc_handle.variables[\"log_of_divisors\"][step] = self._log_of_divisor\n\n        self._nc_handle.variables[\"mean_energy\"][step] = self._mean_energy\n\n        self._nc_handle.variables[\"min_energy\"][step] = self._min_energy\n\n        self._nc_handle.variables[\"energy_std\"][step] = self._energy_std\n\n        self._write_data_key_2_nc(self._resampled_energies, \"resampled_energies_%d\"%step)\n\n        self._write_data_key_2_nc(self._resampled_trans_vectors, \"resampled_trans_vectors_%d\"%step)\n        return None\n\n    def _do_fft(self, step):\n        print(\"Doing FFT for step %d\"%step)\n        lig_conf = self._lig_coord_ensemble[step]\n        print(self._lig_grid[\"SASAr\"])\n        self._lig_grid.cal_grids(molecular_coord = lig_conf)\n\n        energies = self._lig_grid.get_meaningful_energies()\n        self._nr_finite_energy = energies.shape[0]\n        print(\"Number of finite energy samples\", self._nr_finite_energy)\n\n        if energies.shape[0] > 0:\n\n            self._mean_energy = energies.mean()\n            self._min_energy  = energies.min()\n            self._energy_std  = energies.std()\n\n            exp_energies = -self._beta * energies\n            self._log_of_divisor = exp_energies.max()\n            exp_energies = np.exp(exp_energies - self._log_of_divisor)\n            self._exponential_sum = exp_energies.sum()\n            exp_energies /= self._exponential_sum\n            \n            sample_size = min(exp_energies.shape[0], self._energy_sample_size_per_ligand)\n            sel_ind = np.random.choice(exp_energies.shape[0], size=sample_size, p=exp_energies, replace=True)\n\n            del exp_energies\n\n            self._resampled_energies = [energies[ind] for ind in sel_ind]\n            del energies\n            self._lig_grid.set_meaningful_energies_to_none()\n\n            trans_vectors = self._lig_grid.get_meaningful_corners()\n            self._resampled_trans_vectors = [trans_vectors[ind] for ind in sel_ind]\n            del trans_vectors\n\n            self._resampled_energies = np.array(self._resampled_energies, dtype=float)\n            self._resampled_trans_vectors = np.array(self._resampled_trans_vectors, dtype=int)\n\n        else:\n\n            self._mean_energy = np.inf\n            self._min_energy  = np.inf\n            self._energy_std  = np.inf\n\n            self._log_of_divisor  = 1.\n            self._exponential_sum = 0.\n\n            self._resampled_energies = np.array([], dtype=float)\n            del energies\n            self._lig_grid.set_meaningful_energies_to_none()\n\n            self._resampled_trans_vectors = np.array([], dtype=float)\n\n        self._save_data_to_nc(step)\n        return None\n\n\nif __name__ == \"__main__\":\n    # test\n    rec_prmtop = \"../examples/amber/ubiquitin_ligase/receptor.prmtop\"\n    lj_sigma_scal_fact = 0.8\n    rec_inpcrd = \"../examples/amber/ubiquitin_ligase/receptor.inpcrd\"\n\n    # bsite_file = \"../examples/amber/t4_lysozyme/measured_binding_site.py\"\n    bsite_file = None\n    grid_nc_file = \"../examples/grid/ubiquitin_ligase/grid.nc\"\n\n    lig_prmtop = \"../examples/amber/ubiquitin/ligand.prmtop\"\n    lig_inpcrd = \"../examples/amber/ubiquitin/ligand.inpcrd\"\n\n    energy_sample_size_per_ligand = 200\n    output_nc = \"../examples/fft_sampling/ubql_ubiquitin/fft_sampling.nc\"\n\n    ligand_md_trj_file = \"../examples/ligand_md/ubiquitin/rotation.nc\"\n    lig_coord_ensemble = netCDF4.Dataset(ligand_md_trj_file, \"r\").variables[\"positions\"][:]\n\n    sampler = Sampling(rec_prmtop, lj_sigma_scal_fact, rec_inpcrd,\n                        bsite_file, grid_nc_file, \n                        lig_prmtop, lig_inpcrd,\n                        lig_coord_ensemble,\n                        energy_sample_size_per_ligand, \n                        output_nc,\n                        temperature=300.)\n    sampler.run_sampling()\n\n\n\n\n\n", "meta": {"hexsha": "274fe43fa546672495660673160348de8f0a6c2e", "size": 17257, "ext": "py", "lang": "Python", "max_stars_repo_path": "bpmfwfft/fft_sampling.py", "max_stars_repo_name": "jimtufts/bpmfwfft", "max_stars_repo_head_hexsha": "091d2269b122f00b9dd8a01e34303e3e946f8ea0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bpmfwfft/fft_sampling.py", "max_issues_repo_name": "jimtufts/bpmfwfft", "max_issues_repo_head_hexsha": "091d2269b122f00b9dd8a01e34303e3e946f8ea0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bpmfwfft/fft_sampling.py", "max_forks_repo_name": "jimtufts/bpmfwfft", "max_forks_repo_head_hexsha": "091d2269b122f00b9dd8a01e34303e3e946f8ea0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.2965686275, "max_line_length": 134, "alphanum_fraction": 0.6651214, "include": true, "reason": "import numpy", "num_tokens": 4230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.19499281176316477}}
{"text": "'''Collection of functions that generate figures from the fit outputs. Creates figures from fit results using both simulated and real datasets.'''\n\nfrom fancy.analysis import results\nimport numpy as np\nimport os\nimport h5py\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nfrom pandas import DataFrame\nfrom astropy.coordinates import SkyCoord\nfrom astropy import units as u\n\nfrom fancy import Data, Results\nfrom fancy.plotting import Corner\nfrom fancy.plotting.allskymap_cartopy import AllSkyMapCartopy as AllSkyMap\nfrom fancy.plotting.colours import *\nfrom fancy.interfaces.stan import Direction\n\n# use minimalist style\nplt.style.use(\"minimalist\")\n\n# paths to important files\npath_to_this_file = os.path.abspath(os.path.dirname(__file__))\nstan_path = os.path.join(path_to_this_file, \"..\", \"stan\")\nsource_file = os.path.join(path_to_this_file, \"..\", \"data\", \"sourcedata.h5\")\nuhecr_file = os.path.join(path_to_this_file, \"..\", \"data\", \"UHECRdata.h5\")\ntable_path = os.path.join(path_to_this_file, \"..\", \"tables\")\noutput_path = os.path.join(path_to_this_file, \"..\", \"output\")\n\n\nclass OutputFigures():\n    def __init__(self,\n                 fig_args,\n                 sim_model=None,\n                 sim_output_file=None,\n                 tight_B=False,\n                 skymap_label_fmt=\"default\"):\n        '''Collection of figures obtained from output of fitting.'''\n        # parameters set from argparse\n        self.source_type = fig_args[\"source\"]\n        self.detector_type = fig_args[\"detector\"]\n        self.model_type = fig_args[\"model\"]\n        self.data_type = fig_args[\"dtype\"]\n        self.ptype = fig_args[\"ptype\"]\n        self.seed = fig_args[\"seed\"]\n        self.sim_model_type = sim_model\n        self.sim_output_file = sim_output_file\n\n        # output file from simulation / fitting\n        if tight_B:\n            self.output_file = os.path.join(\n                output_path,\n                \"tmp_{0}_fit_{5}_{1}_{2}_{3}_{4}_tightB.h5\".format(\n                    self.model_type, self.source_type, self.detector_type,\n                    self.seed, self.ptype, self.data_type))\n        else:\n            self.output_file = os.path.join(\n                output_path, \"tmp_{0}_fit_{5}_{1}_{2}_{3}_{4}.h5\".format(\n                    self.model_type, self.source_type, self.detector_type,\n                    self.seed, self.ptype, self.data_type))\n\n        if sim_output_file is not None:\n            self.output_file = os.path.join(\n                output_path, \"{0}_fit_{5}_{1}_{2}_{3}_{4}_{6}.h5\".format(\n                    self.model_type, self.source_type, self.detector_type,\n                    self.seed, self.ptype, self.data_type,\n                    self.sim_model_type))\n            # if self.detector_type == \"joint_gmf\":\n            #     self.output_file = os.path.join(\n            #         output_path, \"{0}_fit_{5}_{1}_{2}_{3}_{4}_{5}.h5\".format(\n            #             self.model_type, self.source_type, self.detector_type,\n            #             self.seed, self.ptype, self.data_type,\n            #             self.sim_model_type))\n\n            # else:\n            #     self.output_file = os.path.join(\n            #         output_path, \"{0}_fit_{5}_{1}_{2}_{3}_{4}.h5\".format(\n            #             self.model_type, self.source_type, self.detector_type,\n            #             self.seed, self.ptype, self.data_type))\n\n        # obtain detector properties / params from imports\n        self.detector_properties, self.detector_params = self._get_detectorimports(\n        )\n\n        # initialize the data object and add relevant data into it\n        self._initialize_data()\n\n        # format style for skymap labels (from \"mpl\" or \"TA\")\n        self.skymap_label_fmt = skymap_label_fmt\n\n    def _get_detectorimports(self):\n        '''Get variables imported by (detector_name).py'''\n        if self.detector_type == \"TA2015\":\n            from fancy.detector.TA2015 import detector_properties, detector_params\n        elif self.detector_type == \"auger2014\":\n            from fancy.detector.auger2014 import detector_properties, detector_params\n        elif self.detector_type == \"auger2010\":\n            from fancy.detector.auger2010 import detector_properties, detector_params\n        else:\n            raise Exception(\"Undefined detector type!\")\n\n        return detector_properties, detector_params\n\n    def _initialize_data(self):\n        '''Initialize data object based on sim / real data'''\n        self.data = Data()\n\n        if self.data_type == \"sim\":\n            self.data.from_file(self.sim_output_file)\n\n        elif self.data_type == \"real\":\n            self.data.add_source(source_file, self.source_type)\n            self.data.add_uhecr(uhecr_file, self.detector_type)\n            self.data.add_detector(self.detector_properties)\n\n    def src_uhecr_skymap(self, savefile=None, coord=\"G\", exposure=\"map\"):\n        '''\n        Plot skymap with sources + UHECR, obtained from Data object.\n        Optionally add either exposure map or exposure limit.\n        '''\n        # labels\n        src_label = self.data.source.label\n        uhecr_label = self.data.uhecr.label\n        # read in initializations\n        omega_src = Direction(self.data.source.unit_vector)\n        omega_arr = Direction(self.data.uhecr.unit_vector)\n        energy_arr = self.data.uhecr.energy\n\n        # convert source / arrival directions to equatorial / galactic\n        if coord == \"G\":\n            x_src, y_src = omega_src.glons, omega_src.glats\n            x_arr, y_arr = omega_arr.glons, omega_arr.glats\n        elif coord == \"E\":\n            x_src, y_src = omega_src.ras, omega_src.decs\n            x_arr, y_arr = omega_arr.ras, omega_arr.decs\n\n        Eth = self.data.detector.Eth\n        Emax = np.ceil(np.max(energy_arr) / 10.) * 10.\n\n        uhecr_color = [lightblue, midblue, darkblue]\n        uhecr_cmap = mpl.colors.ListedColormap(uhecr_color)\n        energy_bins = np.logspace(np.log(Eth), np.log(Emax), 4, base=np.e)\n        uhecr_norm = mpl.colors.BoundaryNorm(energy_bins, uhecr_cmap.N)\n\n        # Legend\n        legend_elements = [\n            mpl.lines.Line2D([0], [0],\n                             marker='o',\n                             color='w',\n                             label='sources',\n                             markersize=10,\n                             markerfacecolor='k'),\n            mpl.lines.Line2D([0], [0],\n                             marker='o',\n                             color='w',\n                             label='UHECRs',\n                             markersize=15,\n                             markerfacecolor=midblue,\n                             alpha=0.8)\n        ]\n\n        # create skymap\n        skymap = AllSkyMap(projection='moll', lon_0=180)\n        skymap.set_gridlines(label_fmt=self.skymap_label_fmt)\n\n        # sources\n        skymap.scatter(x_src, y_src, s=10.0, color='k', alpha=1.0, zorder=5)\n\n        # UHECRs\n        for lon, lat, E in np.nditer([x_arr, y_arr, energy_arr]):\n            i = np.digitize(E, energy_bins) - 1\n            skymap.tissot(lon,\n                          lat,\n                          3.0 + (i * 2),\n                          30,\n                          facecolor=uhecr_cmap.colors[i],\n                          alpha=0.8,\n                          zorder=i + 2)\n\n        # exposure\n        if exposure == \"map\":\n            skymap.exposure_map(self.data.detector.params, coord=coord)\n        elif exposure == \"limit\":\n            skymap.exposure_limit(self.data.detector.limiting_dec.deg,\n                                  coord=coord,\n                                  s=2,\n                                  color=grey,\n                                  alpha=1)\n        else:\n            raise ValueError(\n                \"Exposure plot type {0} not defined.\".format(exposure))\n\n        # Annotations\n        skymap.legend(handles=legend_elements,\n                      loc='upper right',\n                      bbox_to_anchor=(1., 1.),\n                      fontsize=16,\n                      fancybox=True)\n        skymap.title(\"{0} + {1}\".format(src_label, uhecr_label))\n\n        # Colorbar\n        cb_ax = plt.axes([0.25, 0.07, .5, .05], frameon=False)\n        bar = mpl.colorbar.ColorbarBase(cb_ax,\n                                        norm=uhecr_norm,\n                                        cmap=uhecr_cmap,\n                                        orientation='horizontal',\n                                        drawedges=True,\n                                        alpha=1)\n        bar.set_label('$\\hat{E}$ / EeV', color='k', fontsize=16)\n        bar.ax.tick_params(labelsize=16)\n\n        skymap.save(savefile, bbox_inches='tight')\n\n    def eval_association_probs(self):\n        '''\n        Evaluate the assocation probabilities between sources and UHECR\n        from some output file\n        '''\n\n        # Log probability\n        results = Results(self.output_file)\n        keys = ['lp']\n        chain = results.get_chain(keys)\n        logprob = chain['lp'].transpose(1, 2, 0)\n        N = np.shape(logprob)[0]\n\n        # Account for background component\n        Ns = np.shape(logprob)[1] - 1\n\n        # Calculate association probabilities for each source-UHECR combo\n        uhecr_p = []\n        for lp in logprob:\n            lps = []\n            for src in range(Ns + 1):\n                lps.append(np.mean(np.exp(lp[src])))\n\n            norm = sum(lps)\n            ps = []\n            for src in range(Ns + 1):\n                ps.append(lps[src] / norm)\n            uhecr_p.append(ps)\n\n        # Normalise line weights\n        pmax = max(max(uhecr_p))\n\n        # Find names of dominant sources\n        threshold_probability = 0.1\n\n        dominant = []\n        for p in uhecr_p:\n            # for i in range(data.source.N):\n            for i in range(Ns):\n                if p[i] > threshold_probability:\n                    dominant.append(i)\n\n        seen = set()\n        inds = []\n        for d in dominant:\n            if d not in seen:\n                inds.append(d)\n                seen.add(d)\n\n        # dominant_sources = [self.data.source.name[i] for i in inds]\n\n        # sort so that those with largest assossations appear first\n        N_assos = {}\n        for i in inds:\n            N_assos[self.data.source.name[i].decode(\"UTF-8\")] = len(\n                np.argwhere([d == i for d in dominant]))\n\n        N_assos_sorted = {\n            k: v\n            for k, v in sorted(N_assos.items(), key=lambda item: item[1])[::-1]\n        }\n\n        # print(\"Dominant sources: \", [self.data.source.name[i] for i in inds])\n\n        return uhecr_p, N_assos_sorted\n\n    def association_skymap(self, savefile, coord=\"G\"):\n        '''Plot association skymap between sources and UHECRs'''\n\n        uhecr_p, N_assos_sorted = self.eval_association_probs()\n\n        # labels\n        # src_label = self.data.source.label\n\n        src_label = \"Swift-BAT\" if self.data.source.label == \"swift_BAT_213\" else self.data.source.label.split(\n            \"_\")[0]\n\n        # uhecr_label = self.data.uhecr.label\n        # read in initializations\n        omega_src = Direction(self.data.source.unit_vector)\n        omega_arr = Direction(self.data.uhecr.unit_vector)\n        energy_arr = self.data.uhecr.energy\n\n        # convert source / arrival directions to equatorial / galactic\n        if coord == \"G\":\n            x_src, y_src = 180. - omega_src.glons, omega_src.glats\n            x_arr, y_arr = 180. - omega_arr.glons, omega_arr.glats\n        elif coord == \"E\":\n            x_src, y_src = omega_src.ras, omega_src.decs\n            x_arr, y_arr = omega_arr.ras, omega_arr.decs\n\n        Eth = self.data.detector.Eth\n        Emax = np.ceil(np.max(energy_arr) / 10.) * 10.\n\n        uhecr_color = [lightblue, midblue, darkblue]\n        uhecr_cmap = mpl.colors.ListedColormap(uhecr_color)\n        energy_bins = np.logspace(np.log(Eth), np.log(Emax), 4, base=np.e)\n        uhecr_norm = mpl.colors.BoundaryNorm(energy_bins, uhecr_cmap.N)\n\n        # Legend\n        legend_elements = [\n            mpl.lines.Line2D([0], [0],\n                             marker='o',\n                             color='w',\n                             label=src_label,\n                             markersize=10,\n                             markerfacecolor='k'),\n            mpl.lines.Line2D([0], [0],\n                             marker='o',\n                             color='w',\n                             label='UHECRs',\n                             markersize=15,\n                             markerfacecolor=midblue,\n                             alpha=0.8)\n        ]\n\n        # plot\n        skymap = AllSkyMap(projection='moll', lon_0=180)\n        skymap.set_gridlines(label_fmt=self.skymap_label_fmt)\n\n        # sources\n        skymap.scatter(x_src, y_src, s=10.0, color='k', alpha=1.0, zorder=5)\n\n        # UHECRs\n        for lon, lat, E in np.nditer([x_arr, y_arr, energy_arr]):\n            i = np.digitize(E, energy_bins) - 1\n            skymap.tissot(lon,\n                          lat,\n                          3.0 + (i * 2),\n                          30,\n                          facecolor=uhecr_cmap.colors[i],\n                          alpha=0.8,\n                          zorder=i + 2)\n\n        # Association\n        # add some way to include dominant sources with this association plot later\n        pmax = np.max(np.max(uhecr_p))\n\n        for i, p in enumerate(uhecr_p):\n            for j, psrc in enumerate(p[0:self.data.source.N]):\n                if psrc > 0.001:\n                    skymap.geodesic(x_arr[i],\n                                    y_arr[i],\n                                    x_src[j],\n                                    y_src[j],\n                                    color='k',\n                                    lw=3,\n                                    alpha=psrc / pmax,\n                                    zorder=10)\n\n        # Annotations\n        skymap.legend(handles=legend_elements,\n                      loc='upper right',\n                      bbox_to_anchor=(1.1, 1.),\n                      fontsize=16,\n                      fancybox=True)\n\n        # exposure limit\n        skymap.exposure_limit(\n            self.data.detector.limiting_dec.deg,\n            coord=coord,\n            s=0.5,\n            marker=\"o\",\n            color=lightpurple,\n            alpha=0.01,\n        )\n\n        # Colorbar\n        cb_ax = plt.axes([0.25, 0.07, .5, .05], frameon=True)\n        bar = mpl.colorbar.ColorbarBase(cb_ax,\n                                        norm=uhecr_norm,\n                                        cmap=uhecr_cmap,\n                                        orientation='horizontal',\n                                        drawedges=True,\n                                        alpha=1)\n        bar.set_label('$\\hat{E}$ / EeV', color='k', fontsize=16)\n        bar.ax.tick_params(labelsize=16)\n        skymap.save(savefile)\n\n        return N_assos_sorted\n\n    def corner(self, savefile):\n        '''Plot corner plot'''\n\n        if self.dtype == \"sim\":\n            self.corner_sim(savefile)\n        elif self.dtype == \"real\":\n            self.corner_data(savefile)\n\n    def corner_data(self, savefile):\n        '''Plot corner plot of data'''\n        # Get chains from joint fit\n        results_fit = Results(self.output_file)\n\n        # get keys and corresponding labels\n        labels = {}\n        if self.model_type.find(\"join\") != -1:\n            keys = ['alpha', 'B', 'f']\n\n            labels['B'] = r'$B$ / $\\mathrm{nG}$'\n            labels['alpha'] = r'$\\alpha$'\n            labels['f'] = r'$f$'\n\n        elif self.model_type == \"arrival_direction\":\n            keys = ['kappa', 'L', 'f']\n\n            labels['L'] = r'$L$'\n            labels['kappa'] = r'$\\kappa$'\n            labels['f'] = r'$f$'\n\n        chain = results_fit.get_chain(keys)\n\n        # Make nicely labelled dict\n        chain_for_df = {}\n        for key in keys:\n            chain_for_df[labels[key]] = chain[key]\n\n        # Make ordered dataframe\n        df = DataFrame(data=chain_for_df)\n        df = df[[labels[keys[0]], labels[keys[1]], labels[keys[2]]]]\n\n        corner = Corner(df, color=midblue, contour_color=midblue_contour)\n        corner.save(savefile)\n\n    def corner_sim(self, savefile, cumul=False, output_files=None):\n\n        if cumul:\n            self.corner_sim_cumul(output_files, savefile)\n        else:\n            results_fit = Results(self.output_file)\n\n            results_sim = Results(self.sim_output_file)\n            truth_keys = ['F0', 'L', 'alpha', 'B', 'f']\n            truth = results_sim.get_truths(truth_keys)\n            info_keys = ['Eth', 'Eth_sim']\n            info = results_sim.get_truths(info_keys)\n\n            # Correct for different Eth in sim and fit\n            # Also scale to plot units\n            flux_scale = (info['Eth'] / info['Eth_sim'])**(1 - truth['alpha'])\n            truth['F0'] = truth['F0'] * flux_scale  # km^-2 yr^-1\n            truth[\n                'L'] = truth['L'][0] * flux_scale / 1.0e39 * 10  # 10^-38 yr^-1\n\n            if self.model_type == \"arrival_direction\":\n                self.corner_sim_arrival(results_fit, truth, savefile)\n            else:\n                self.corner_sim_joint(results_fit, truth, savefile)\n\n    def corner_sim_arrival(self, results_fit, truth, savefile):\n        '''Corner plot for Arrival Direction model'''\n\n        keys = ['kappa', 'L', 'f']\n        chain = results_fit.get_chain(keys)\n\n        chain['L'] = chain['L'] * 10  # 10^-38 yr^-1\n\n        labels = {}\n        labels['L'] = r'$L$ / $10^{38}$ $\\mathrm{yr}^{-1}$'\n        labels['kappa'] = r'$\\kappa$'\n        labels['f'] = r'$f$'\n\n        truths = [truth[\"L\"], truth[\"f\"]]\n\n        # Make nicely labelled dict\n        chain_for_df = {}\n        for key in keys:\n            chain_for_df[labels[key]] = chain[key]\n\n        # Make ordered dataframe\n        df = DataFrame(data=chain_for_df)\n        df = df[[labels['L'], labels['f'], labels['kappa']]]\n\n        corner = Corner(df,\n                        truths,\n                        color=midblue,\n                        contour_color=midblue_contour)\n\n        corner.save(savefile)\n\n    def corner_sim_joint(self, results_fit, truth, savefile):\n        '''Plot corner plot resulting from simulations'''\n\n        keys = ['F0', 'L', 'alpha', 'B', 'f']\n        chain = results_fit.get_chain(keys)\n\n        # Convert form Stan units to plot units\n        chain['F0'] = chain['F0'] / 1.0e3  # km^-2 yr^-1\n        chain['L'] = chain['L'] * 10  # 10^-38 yr^-1\n\n        labels = {}\n        labels['L'] = r'$L$ / $10^{38}$ $\\mathrm{yr}^{-1}$'\n        labels['F0'] = r'$F_0$ / $\\mathrm{km}^{-2} \\ \\mathrm{yr}^{-1}$'\n        labels['B'] = r'$B$ / $\\mathrm{nG}$'\n        labels['alpha'] = r'$\\alpha$'\n        labels['f'] = r'$f$'\n\n        params = np.column_stack([chain[key] for key in keys])\n        truths = [truth[key] for key in keys]\n\n        # Make nicely labelled dict\n        chain_for_df = {}\n        for key in keys:\n            chain_for_df[labels[key]] = chain[key]\n\n        # Make ordered dataframe\n        df = DataFrame(data=chain_for_df)\n        df = df[[\n            labels['F0'], labels['L'], labels['alpha'], labels['B'],\n            labels['f']\n        ]]\n\n        corner = Corner(df, truths, color=purple, contour_color=purple_contour)\n        corner.save(savefile)\n\n    def corner_sim_cumul(self, output_files, savefile):\n        '''Cumulative distribution of corner plots from simulation'''\n\n        keys = ['F0', 'L', 'alpha', 'B', 'f']\n        chain_avgs = {key: 0 for key in keys}\n        chain_list = []\n        Nseeds = len(output_files)\n\n        # get chains for each output file\n        # ignores self.outpuf_file\n        for output_file in output_files:\n            chain = Results(output_file).get_chain(keys)\n\n            chain_list.append(chain)\n\n        # evaluate averaged value for each seed\n        for key in keys:\n            chain_sum = 0\n            for i in range(Nseeds):\n                chain_sum += chain_list[i][key]\n\n            chain_sum /= Nseeds\n\n            chain_avgs[key] = chain_sum\n\n        # Convert form Stan units to plot units\n        chain_avgs['F0'] = chain_avgs['F0'] / 1.0e3  # km^-2 yr^-1\n        chain_avgs['L'] = chain_avgs['L'] * 10  # 10^-38 yr^-1\n\n        # Get truths from simulation\n        results_sim = Results(self.sim_output_file)\n\n        truth_keys = ['F0', 'L', 'alpha', 'B', 'f']\n        truth = results_sim.get_truths(truth_keys)\n        info_keys = ['Eth', 'Eth_sim']\n        info = results_sim.get_truths(info_keys)\n\n        # Correct for different Eth in sim and fit\n        # Also scale to plot units\n        flux_scale = (info['Eth'] / info['Eth_sim'])**(1 - truth['alpha'])\n        truth['F0'] = truth['F0'] * flux_scale  # km^-2 yr^-1\n        truth['L'] = truth['L'][0] * flux_scale / 1.0e39 * 10  # 10^-38 yr^-1\n\n        labels = {}\n        labels['L'] = r'$L$ / $10^{38}$ $\\mathrm{yr}^{-1}$'\n        labels['F0'] = r'$F_0$ / $\\mathrm{km}^{-2} \\ \\mathrm{yr}^{-1}$'\n        labels['B'] = r'$B$ / $\\mathrm{nG}$'\n        labels['alpha'] = r'$\\alpha$'\n        labels['f'] = r'$f$'\n\n        params = np.column_stack([chain_avgs[key] for key in keys])\n        truths = [truth[key] for key in keys]\n\n        # Make nicely labelled dict\n        chain_for_df = {}\n        for key in keys:\n            chain_for_df[labels[key]] = chain_avgs[key]\n\n        # Make ordered dataframe\n        df = DataFrame(data=chain_for_df)\n        df = df[[\n            labels['F0'], labels['L'], labels['alpha'], labels['B'],\n            labels['f']\n        ]]\n\n        corner = Corner(df, truths, color=purple, contour_color=purple_contour)\n        corner.save(savefile)\n\n\nclass SourceUHECRDist():\n    def __init__(self, figsize=(6, 4), sim_output_file=None):\n        '''Class that organizes plotting of source-UHECR association fraction distribution'''\n        self.fig, self.ax = plt.subplots(figsize=figsize)\n\n        self.color_list = [grey, lightpurple, lightblue]\n\n        self.sim_output_file = sim_output_file\n\n    def get_fs(self, fname_list, cumul=False):\n        '''Get source-UHECR association fraction from output files'''\n\n        self.f_list = []\n\n        if cumul:  # evaluate cumulative distribution\n            # then each element in fname_list must be a list of fnames with different models\n            # each of this list will contain fnames with different seeds\n            for fname_models_list in fname_list:\n                f_list = []\n                for output_file in fname_models_list:\n                    f_i = Results(output_file).get_chain(['f'])['f']\n                    f_list.append(f_i)\n\n                f_avg = np.mean(np.array(f_list), axis=0)\n                self.f_list.append(f_avg)\n\n        else:\n            for output_file in fname_list:\n                try:\n                    f_i = Results(output_file).get_chain(['f'])['f']\n                except KeyError:\n                    f_i = np.zeros(100)\n                self.f_list.append(f_i)\n\n        return self.f_list\n\n    def plotdist(self, labels, extend=False, title=None):\n        '''Plot the distribution'''\n        for i, label in enumerate(labels):\n            # for arrival_direction -> arrival direction\n            label = label.replace(\"_\", \" \") if \"_\" in label else label\n\n            sns.distplot(self.f_list[i],\n                         hist=False,\n                         kde_kws={\n                             'shade': True,\n                             'lw': 2,\n                             'zorder': i\n                         },\n                         color=self.color_list[i],\n                         label=label)\n\n        if self.sim_output_file is not None:\n            f_true = Results(self.sim_output_file).get_truths(['f'])['f']\n            self.ax.axvline(f_true,\n                            0,\n                            10,\n                            color='k',\n                            zorder=3,\n                            lw=2.,\n                            alpha=0.7)\n\n        self._annotate(title=title, extend=extend)\n\n    def _annotate(self, title=None, extend=False):\n        '''Plot the annotations'''\n        # annotations\n        self.ax.set_xlim(0, 1)\n        if title:\n            self.ax.set_title(title, fontsize=24)\n        self.ax.set_xlabel('$f$')\n        self.ax.set_ylabel('$P(f | \\hat{E}, \\hat{\\omega})$')\n\n        legend_loc = (1.6, 1) if extend else (1.3, 1)\n        self.ax.legend(fontsize=22, bbox_to_anchor=legend_loc)\n\n    def save(self, savefile):\n        '''Save the distribution'''\n        # save\n        self.fig.savefig(savefile, bbox_inches='tight')", "meta": {"hexsha": "d7d0f098b3cfb75f51c36733239715eaada3db3f", "size": 24667, "ext": "py", "lang": "Python", "max_stars_repo_path": "uhecr_model/legacy/output_figures_old.py", "max_stars_repo_name": "uhecr-project/uhecr_model", "max_stars_repo_head_hexsha": "8a2e8ab6f11cd2700f6455dff54c746cf3ffb143", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "uhecr_model/legacy/output_figures_old.py", "max_issues_repo_name": "uhecr-project/uhecr_model", "max_issues_repo_head_hexsha": "8a2e8ab6f11cd2700f6455dff54c746cf3ffb143", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-07-12T08:01:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T03:01:30.000Z", "max_forks_repo_path": "uhecr_model/legacy/output_figures_old.py", "max_forks_repo_name": "uhecr-project/uhecr_model", "max_forks_repo_head_hexsha": "8a2e8ab6f11cd2700f6455dff54c746cf3ffb143", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3820058997, "max_line_length": 146, "alphanum_fraction": 0.5242226456, "include": true, "reason": "import numpy,from astropy", "num_tokens": 5816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.3311197396289915, "lm_q1q2_score": 0.19499281087206077}}
{"text": "# coding: utf-8\n\nimport numpy as np\n\nfrom sympy import IndexedBase, Indexed\nfrom sympy import Mul, Matrix, Expr\nfrom sympy import Add, And, StrictLessThan, Eq\nfrom sympy import Abs, Not, floor\nfrom sympy import Symbol, Idx\nfrom sympy import Basic, Function\nfrom sympy.simplify import cse_main\nfrom sympy.core.containers import Tuple\n\n\nfrom psydac.pyccel.ast.core      import Assign, Product, AugAssign, For\nfrom psydac.pyccel.ast.core      import Variable, IndexedVariable, IndexedElement\nfrom psydac.pyccel.ast.core      import Slice, String, ValuedArgument\nfrom psydac.pyccel.ast.core      import EmptyNode, Import, While, Return, If\nfrom psydac.pyccel.ast.core      import CodeBlock, FunctionDef, Comment\nfrom psydac.pyccel.ast.builtins  import Range\n\nfrom sympde.topology import (dx1, dx2, dx3)\nfrom sympde.topology import SymbolicExpr\nfrom sympde.topology import LogicalExpr, Jacobian\nfrom sympde.expr.evaluation import _split_test_function\nfrom sympde.calculus.matrices import SymbolicDeterminant\nfrom sympde.topology import SymbolicWeightedVolume, InterfaceMapping\nfrom sympde.topology import Boundary, NormalVector, Interface\n\nfrom sympde.topology.derivatives import get_index_logical_derivatives\n\nfrom .nodes import AtomicNode\nfrom .nodes import BasisAtom\nfrom .nodes import PhysicalBasisValue\nfrom .nodes import LogicalBasisValue\nfrom .nodes import TensorQuadrature\nfrom .nodes import LocalTensorQuadratureBasis\nfrom .nodes import LocalTensorQuadratureTestBasis\nfrom .nodes import LocalTensorQuadratureTrialBasis\nfrom .nodes import GlobalTensorQuadratureTestBasis\nfrom .nodes import GlobalTensorQuadratureTrialBasis\nfrom .nodes import GlobalTensorQuadratureBasis\nfrom .nodes import TensorQuadratureBasis\nfrom .nodes import SplitArray\nfrom .nodes import Reduction\nfrom .nodes import LogicalValueNode\nfrom .nodes import TensorIteration\nfrom .nodes import TensorIterator\nfrom .nodes import TensorGenerator\nfrom .nodes import ProductIteration\nfrom .nodes import ProductIterator\nfrom .nodes import ProductGenerator\nfrom .nodes import StencilMatrixLocalBasis\nfrom .nodes import StencilMatrixGlobalBasis, ScalarLocalBasis\nfrom .nodes import BlockStencilMatrixLocalBasis\nfrom .nodes import BlockStencilMatrixGlobalBasis\nfrom .nodes import BlockStencilVectorLocalBasis, BlockScalarLocalBasis\nfrom .nodes import BlockStencilVectorGlobalBasis\nfrom .nodes import StencilVectorLocalBasis\nfrom .nodes import StencilVectorGlobalBasis\nfrom .nodes import GlobalElementBasis\nfrom .nodes import LocalElementBasis\nfrom .nodes import TensorQuadratureTestBasis, TensorQuadratureTrialBasis\nfrom .nodes import Span\nfrom .nodes import Loop\nfrom .nodes import WeightedVolumeQuadrature\nfrom .nodes import LengthDofTest\n\nfrom .nodes import index_outer_dof_test\nfrom .nodes import index_dof_test, index_dof_trial\nfrom .nodes import index_deriv, Max, Min\n\nfrom .nodes import Zeros, ZerosLike, Array\nfrom .fem import expand, expand_hdiv_hcurl\nfrom psydac.api.ast.utilities import variables, math_atoms_as_str\nfrom psydac.api.utilities     import flatten\nfrom psydac.api.ast.utilities import build_pythran_types_header\nfrom psydac.api.ast.utilities import build_pyccel_types_decorator\n\n#==============================================================================\n# TODO move it\nimport string\nimport random\ndef random_string( n ):\n    chars    = string.ascii_lowercase + string.digits\n    selector = random.SystemRandom()\n    return ''.join( selector.choice( chars ) for _ in range( n ) )\n\nclass Shape(Basic):\n    @property\n    def arg(self):\n        return self._args[0]\n\ndef is_scalar_array(var):\n    indices = var.indices\n    for ind in indices:\n        if isinstance(ind, Slice):\n            return False\n    return True\n#==============================================================================\n\ndef parse(expr, settings, backend=None):\n    \"\"\"\n    This function takes a Psydac Ast and returns a Pyccel Ast\n\n    Parameters\n    ----------\n\n    expr: <Psydac Ast>\n        psydac ast node\n\n    settings : <dict>\n        dictionary that continas number of dimension, mappings and target if provided\n\n    Returns\n    -------\n\n    ast : Pyccel Ast\n        pyccel abstract syntax tree that can be translated into a Python code\n\n    \"\"\"\n    psy_parser = Parser(settings, backend)\n    ast = psy_parser.doit(expr)\n    return ast\n\n#==============================================================================\nclass Parser(object):\n    \"\"\"\n    This class takes a Psyadac Ast and transforms it to a Pyccel Ast\n    by calling the Parser.doit method\n\n    \"\"\"\n    def __init__(self, settings, backend=None):\n\n        settings = settings.copy()\n\n        dim = settings.pop('dim', None)\n        if dim is None:\n            raise ValueError('dim not provided')\n\n        self._dim = dim\n        # ...\n\n        nderiv = settings.pop('nderiv', None)\n        if nderiv is None:\n            raise ValueError('nderiv not provided')\n\n        self._nderiv = nderiv\n\n        target = settings.pop('target', None)\n        if target is None:\n            raise ValueError('target not provided')\n\n        self._target = target\n\n        self._mapping = settings.pop('mapping', None)\n\n        self._settings = settings\n        self.backend   = backend\n\n        # TODO improve\n        self.indices          = {}\n        self.shapes           = {}\n        self.functions        = {}\n        self.variables        = {}\n        self.arguments        = {}\n        self.allocated        = {}\n        self._math_functions  = ()\n        \n\n    @property\n    def settings(self):\n        return self._settings\n\n    @property\n    def dim(self):\n        return self._dim\n\n    @property\n    def nderiv(self):\n        return self._nderiv\n\n    @property\n    def mapping(self):\n        return self._mapping\n\n    @property\n    def target(self):\n        return self._target\n\n    def doit(self, expr, **settings):\n        return self._visit(expr, **settings)\n\n    def insert_variables(self, *args):\n        args = flatten(args)\n        for arg in args:\n            self.variables[str(arg)] = arg\n\n    def get_shape(self, expr):\n        lhs = expr.lhs\n        rhs = expr.rhs\n\n        rhs_indices = []\n        if isinstance(rhs, (Indexed, IndexedElement)):\n            rhs_indices = rhs.indices\n        lhs_indices = lhs.indices\n\n        #TODO fix probleme of indices we should have a unique way of getting indices\n        lhs_indices = [None if isinstance(i, Slice) and i.start is None else i for i in lhs_indices]\n        rhs_indices = [None if isinstance(i, Slice) and i.start is None else i for i in rhs_indices]\n        shape_lhs = None\n        shape = []\n\n        if all(i is None for i in lhs_indices):\n            for i in rhs_indices:\n                if i is None:\n                    shape.append(None)\n                elif str(i) in self.indices:\n                    shape.append(self.indices[str(i)]-1)\n                elif isinstance(i, Slice) and i.start and i.end:\n                    shape.append(i.end-i.start)\n            if len(shape) == len(rhs_indices):\n                if any(s is None for s in shape):\n                    shape = tuple(Slice(None,None) if i is None else 0 for i in shape)\n                    rhs = rhs.base\n                    shape_lhs = Shape(rhs[shape])\n                else:\n                    shape_lhs = tuple(shape)\n\n        elif all(i is not None for i in lhs_indices):\n            for i in lhs_indices:\n                if str(i) in self.indices:\n                    shape.append(self.indices[str(i)])\n            if len(shape) == len(lhs_indices):\n                shape_lhs = tuple(shape)\n\n        return shape_lhs\n\n    def _visit(self, expr, **settings):\n        classes = type(expr).__mro__\n        for cls in classes:\n            annotation_method = '_visit_' + cls.__name__\n            if hasattr(self, annotation_method):\n                return getattr(self, annotation_method)(expr, **settings)\n        # Unknown object, we raise an error.\n        raise NotImplementedError('{}'.format(type(expr)))\n\n    # ....................................................\n    def _visit_VectorAssign(self, expr, **kwargs):\n        lhs = self._visit(expr.lhs)\n        rhs = self._visit(expr.rhs)\n        if expr.op is None:\n            return [Assign(l,r) for l,r in zip(lhs, rhs) if l is not None and r is not None]\n        else:\n            return [AugAssign(l,expr.op, r) for l,r in zip(lhs, rhs) if l is not None and r is not None]\n    # ....................................................\n    def _visit_Assign(self, expr, **kwargs):\n\n        lhs = self._visit(expr.lhs)\n        rhs = self._visit(expr.rhs)\n\n        # ... extract slices from rhs\n        slices = []\n        if isinstance(rhs, IndexedElement):\n            slices = [i for i in rhs.indices if isinstance(i, Slice)]\n        # ...\n\n        # ... update lhs with slices\n        if len(slices) > 0:\n            # TODO add assert on type lhs\n            if isinstance(lhs, (IndexedBase, IndexedVariable)):\n                lhs = lhs[slices]\n\n            elif isinstance(lhs, Symbol):\n                lhs = IndexedBase(lhs.name)[slices]\n\n        expr = Assign(lhs, rhs)\n        # ..\n\n        if isinstance(lhs, (IndexedElement, Indexed)):\n            name = str(lhs.base)\n\n            shape = self.get_shape(expr)\n            if shape:\n                self.shapes[name] = shape\n\n        return expr\n\n    # ....................................................\n    def _visit_AugAssign(self, expr, **kwargs):\n\n        lhs = self._visit(expr.lhs)\n        rhs = self._visit(expr.rhs)\n        op  = expr.op\n\n        # ... extract slices from rhs\n        slices = []\n        if isinstance(rhs, IndexedElement):\n            slices = [i for i in indices if isinstance(i, Slice)]\n        # ...\n\n        # ... update lhs with slices\n        if len(slices) > 0:\n            # TODO add assert on type lhs\n            if isinstance(lhs, (IndexedBase, IndexedVariable)):\n                lhs = lhs[slices]\n            else:\n                raise NotImplementedError('{}'.format(type(lhs)))\n\n        expr = AugAssign(lhs,op,rhs)\n        # ...\n        if isinstance(lhs, (IndexedElement,Indexed)):\n            name = str(lhs.base)\n\n            shape = self.get_shape(expr)\n            if shape:\n                self.shapes[name] = shape\n\n        return expr\n\n    def _visit_Allocate(self, expr, **kwargs):\n        arr = self._visit(expr.array)\n        shape = [self._visit(i) for i in expr.shape]\n        self.allocated[arr.name] = arr\n        return Assign(arr, Zeros(tuple(shape), arr.dtype))\n\n    # ....................................................\n    def _visit_AddNode(self, expr, **kwargs):\n        return self._visit_Add(expr)\n\n    def _visit_MulNode(self, expr, **kwargs):\n        return self._visit_Mul(expr)\n\n    # ....................................................\n    def _visit_IntDivNode(self, expr, **kwargs):\n        args = [self._visit(a) for a in expr.args]\n        return args[0]//args[1]\n\n    # ....................................................\n    def _visit_AndNode(self, expr, **kwargs):\n        args = [self._visit(a) for a in expr.args]\n        return And(*args)\n\n    def _visit_NotNode(self, expr, **kwargs):\n        return Not(self._visit(expr.args[0]))\n\n    def _visit_EqNode(self, expr, **kwargs):\n        return Eq(self._visit(expr.args[0]), self._visit(expr.args[1]))\n\n    # ....................................................\n    def _visit_StrictLessThanNode(self, expr, **kwargs):\n        a = self._visit(expr.args[0])\n        b = self._visit(expr.args[1])\n        return StrictLessThan(a,b)\n\n    # ....................................................\n    def _visit_Add(self, expr, **kwargs):\n        args = [self._visit(i) for i in expr.args]\n        tuples = [e for e in args if isinstance(e, tuple)]\n        args   = [e for e in args if not e in tuples]\n        expr   =  Add(*args)\n        if tuples:\n            args  = list(tuples[0])\n            for e in tuples[1:]:\n                args = [args[i]+e[i] for i in range(len(args))]\n            tuples = tuple(Add(expr,e) for e in args)\n            return tuples\n        return expr\n\n    # ....................................................\n    def _visit_Mul(self, expr, **kwargs):\n        args = [self._visit(i) for i in expr.args]\n        return Mul(*args)\n\n    # ....................................................\n    def _visit_Symbol(self, expr, **kwargs):\n        return expr\n\n    # ....................................................\n    def _visit_Variable(self, expr, **kwargs):\n        return expr\n\n    # ....................................................\n    def _visit_IndexedVariable(self, expr, **kwargs):\n        return expr\n\n    # ....................................................\n    def _visit_Tuple(self, expr, **kwargs):\n        args = [self._visit(i) for i in expr]\n        return Tuple(*args)\n\n    def _visit_Array(self, expr, **kwargs):\n        data  = self._visit(expr.data)\n        dtype = expr.dtype\n        return Array(data, dtype=dtype)\n\n    # ....................................................\n    def _visit_Block(self, expr, **kwargs):\n        body = [self._visit(i) for i in expr.body]\n        body = flatten(body)\n        if len(body) == 1:\n            return body[0]\n\n        else:\n            return CodeBlock(body)\n\n    # ....................................................\n    def _visit_ParallelBlock(self, expr, **kwargs):\n        body         = [self._visit(i) for i in expr.body]\n        body         = list(flatten(body))\n        default      = expr.default\n        shared       = [self._visit(i) for i in expr.shared]\n        private      = [self._visit(i) for i in expr.private]\n        firstprivate = [self._visit(i) for i in expr.firstprivate]\n        lastprivate  = [self._visit(i) for i in expr.lastprivate]\n        shared       = flatten([list(i.values())[0] if isinstance(i, dict) else i for i in shared])\n        private      = flatten([list(i.values())[0] if isinstance(i, dict) else i for i in private])\n        firstprivate = flatten([list(i.values())[0] if isinstance(i, dict)else i for i in firstprivate])\n        lastprivate  = flatten([list(i.values())[0] if isinstance(i, dict) else i for i in lastprivate])\n        txt          = '#$ omp parallel default({}) &\\n'.format(default)\n        txt         += '#$ shared({}) &\\n'.format(','.join(str(i) for i in shared if i)) if shared else ''\n        txt         += '#$ private({}) &\\n'.format(','.join(str(i) for i in private if i)) if private else ''\n        txt         += '#$ firstprivate({}) &\\n'.format(','.join(str(i) for i in firstprivate if i)) if firstprivate else ''\n        txt         += '#$ lastprivate({})'.format(','.join(str(i) for i in lastprivate if i)) if lastprivate else ''\n        cmt          = [Comment(txt.rstrip().rstrip('&'))]\n        endcmt       = [Comment('#$ omp end parallel')]\n        return CodeBlock(cmt + body + endcmt)\n    # ....................................................\n    def _visit_DefNode(self, expr, **kwargs):\n\n        args   = expr.arguments.copy()\n        f_args = ()\n\n        tests_basis = args.pop('tests_basis')\n        trial_basis = args.pop('trial_basis',[])\n\n        g_span = args.pop('spans')\n        g_quad = args.pop('quads')\n\n        lengths_tests  = args.pop('tests_degrees')\n        lengths_trials = args.pop('trials_degrees', {})\n\n        lengths = args.pop('quads_degree')\n        g_pads  = args.pop('global_pads')\n        l_pads  = args.pop('local_pads', None)\n\n        mats = args.pop('mats')\n        \n        map_coeffs  = args.pop('mapping', None)\n        map_degrees = args.pop('mapping_degrees', None)\n        map_basis   = args.pop('mapping_basis', None)\n        map_span    = args.pop('mapping_spans', None)\n        thread_args = args.pop('thread_args', None)\n\n        if map_coeffs:\n            map_coeffs  = map_coeffs\n            map_degrees = [map_degrees]\n            map_basis   = [map_basis]\n            map_span    = [map_span]\n        else:\n            map_coeffs  = []\n            map_degrees = []\n            map_basis   = []\n            map_span    = []\n\n        constants  = args.pop('constants', None)\n\n        f_coeffs   = args.pop('f_coeffs',    None)\n\n        starts = args.pop('starts', [])\n        ends   = args.pop('ends', [])\n        if f_coeffs:\n            f_span     = args.pop('f_span',      [])\n            f_basis    = args.pop('field_basis', [])\n            f_degrees  = args.pop('fields_degrees', [])\n            f_pads     = args.pop('f_pads', [])\n            f_args     = (*f_basis, *f_span, *f_degrees, *f_pads, *f_coeffs)\n\n\n        args = [*tests_basis, *trial_basis, *map_basis, *g_span, *map_span, *g_quad, *lengths_tests.values(), *lengths_trials.values(), *map_degrees, *lengths, *g_pads, *map_coeffs]\n\n        if mats:\n            exprs     = [mat.expr for mat in mats]\n\n            mats      = [self._visit(mat) for mat in mats]\n            mats      = [[a for a,e in zip(mat[:],expr[:]) if e] for mat,expr in zip(mats, exprs)]\n            mats      = flatten(mats)\n\n        args = [self._visit(i, **kwargs) for i in args]\n\n        args = [tuple(arg.values())[0] if isinstance(arg, dict) else arg for arg in args]\n        arguments = flatten(args) + mats\n\n        if constants:\n            arguments += [self._visit(i, **kwargs) for i in constants]\n\n        if f_args:\n            f_args     = [self._visit(i, **kwargs) for i in f_args]\n            f_args     = [tuple(arg.values())[0] if isinstance(arg, dict) else arg for arg in f_args]\n            arguments += flatten(f_args)\n\n        arguments += starts + ends\n\n        if thread_args:\n            arguments += flatten([self._visit(i, **kwargs) for i in thread_args])\n\n        body = flatten(tuple(self._visit(i, **kwargs) for i in expr.body))\n\n        inits = []\n        for k,i in self.shapes.items():\n            var = self.variables[k]\n            if var in arguments or var.name in self.allocated:\n                continue\n            if isinstance(i, Shape):\n                inits.append(Assign(var, ZerosLike(i.arg)))\n            else:\n                inits.append(Assign(var, Zeros(i)))\n\n        inits.append(EmptyNode())\n        body =  tuple(inits) + body\n        name = expr.name\n        numpy_imports = ('array', 'zeros', 'zeros_like', 'floor')\n        math_imports  = (*self._math_functions,)\n        imports = [Import('numpy', numpy_imports)] + \\\n                 ([Import('math', math_imports)] if math_imports else []) + \\\n                  [*expr.imports]\n        results = [self._visit(a) for a in expr.results]\n\n        if self.backend['name'] == 'pyccel':\n            a = [String(str(i)) for i in build_pyccel_types_decorator(arguments)]\n            decorators = {'types': Function('types')(*a)}\n        elif self.backend['name'] == 'numba':\n            decorators = {'njit': Function('njit')(ValuedArgument(Symbol('fastmath'), self.backend['fastmath']))}\n        elif self.backend['name'] == 'pythran':\n            header = build_pythran_types_header(name, arguments)\n        else:\n            decorators = {}\n\n        if self.backend['name'] == 'numba':\n            func = FunctionDef(name, arguments, results, body, decorators=decorators)\n            stmts = CodeBlock([*imports , func])\n        else:\n            func = FunctionDef(name, arguments, results, body, imports=imports, decorators=decorators)\n            stmts = func\n\n        self.functions[name] = func\n        return stmts\n\n    def _visit_EvalField(self, expr, **kwargs):\n        g_coeffs   = expr.g_coeffs\n        l_coeffs   = expr.l_coeffs\n        tests      = list(expr._tests)\n        ex_tests   = list(expand(tests))\n        mats       = expr.atoms\n        dim        = self._dim\n        lhs_slices = [Slice(None,None)]*dim\n        mats       = [self._visit(mat, **kwargs) for mat in mats]\n        inits      = {mat:Assign(mat[lhs_slices], 0.) for mat in mats}\n        body       = self._visit(expr.body, **kwargs)\n        stmts      = {}\n        pads       = self._visit_Pads(expr.pads)\n\n        for l_coeff,g_coeff in zip(l_coeffs, g_coeffs):\n            basis        = g_coeff.test\n            index        = ex_tests.index(basis)\n            basis        = basis if basis in tests else basis.base\n            degrees      = self._visit_LengthDofTest(LengthDofTest(basis))\n            spans        = flatten(self._visit_Span(Span(basis))[basis])\n            rhs_starts   = [spans[i]-degrees[i] + pads[index,0][i] for i in range(dim)]\n            rhs_ends     = [spans[i]+pads[index,0][i]+1          for i in range(dim)]\n            rhs_slices   = [Slice(s, e) for s,e in zip(rhs_starts, rhs_ends)]\n            l_coeff      = self._visit(l_coeff, **kwargs)\n            g_coeff      = self._visit(g_coeff, **kwargs)\n            stmt         = self._visit_Assign(Assign(l_coeff[lhs_slices], g_coeff[rhs_slices]), **kwargs)\n            stmts[stmt.lhs.base] = stmt\n        return CodeBlock([*inits.values() , *stmts.values() , body])\n\n    def _visit_EvalMapping(self, expr, **kwargs):\n        if self._mapping.is_analytical:\n            return EmptyNode()\n        values  = expr.values\n        coeffs  = expr.coeffs\n        l_coeffs = expr.local_coeffs\n        stmts   = []\n        dim = self._dim\n        test = coeffs[0].test\n        lhs_slices = [Slice(None,None)]*dim\n        multiplicity = expr.multiplicity\n        pads         = expr.pads\n        for coeff, l_coeff in zip(coeffs, l_coeffs):\n            spans   = flatten(self._visit_Span(Span(test))[test])\n            degrees = self._visit_LengthDofTest(LengthDofTest(test))\n            coeff   = self._visit(coeff)\n            l_coeff = self._visit(l_coeff)\n            rhs_starts = [multiplicity[i]*pads[i] + spans[i]-degrees[i] for i in range(dim)]\n            rhs_ends   = [multiplicity[i]*pads[i] + spans[i]+1          for i in range(dim)]\n            rhs_slices = [Slice(s, e) for s,e in zip(rhs_starts, rhs_ends)]\n            stmt       = self._visit_Assign(Assign(l_coeff[lhs_slices], coeff[rhs_slices]), **kwargs)\n            stmts.append(stmt)\n\n        inits = []\n        for val in values:\n            val = self._visit(val, **kwargs)\n            inits.append(Assign(val[lhs_slices], 0.))\n        loop = self._visit(expr.loop, **kwargs)\n        stmts.append(loop)\n        return CodeBlock(inits+stmts)\n\n    # ....................................................\n    def _visit_Grid(self, expr, **kwargs):\n        raise NotImplementedError('TODO')\n\n    # ....................................................\n    def _visit_Element(self, expr, **kwargs):\n        raise NotImplementedError('TODO')\n\n    # ....................................................\n    def _visit_GlobalTensorQuadratureGrid(self, expr, **kwargs):\n        dim  = self.dim\n        rank = expr.rank\n\n        names = 'global_x1:%s'%(dim+1)\n        points   = variables(names, dtype='real', rank=rank, cls=IndexedVariable)\n\n        if expr.weights:\n            names = 'global_w1:%s'%(dim+1)\n            weights  = variables(names, dtype='real', rank=rank, cls=IndexedVariable)\n\n            # gather by axis\n            targets = tuple(zip(points, weights))\n        else:\n            weights = []\n            targets = tuple(zip(points))\n\n        self.insert_variables(*points, *weights)\n\n        return {0: targets}\n\n    # ....................................................\n    def _visit_LocalTensorQuadratureGrid(self, expr, **kwargs):\n        dim  = self.dim\n        rank = expr.rank\n\n        names = 'local_x1:%s'%(dim+1)\n        points   = variables(names, dtype='real', rank=rank, cls=IndexedVariable)\n\n        if expr.weights:\n            names = 'local_w1:%s'%(dim+1)\n            weights  = variables(names, dtype='real', rank=rank, cls=IndexedVariable)\n\n            # gather by axis\n            targets = tuple(zip(points, weights))\n        else:\n            weights = []\n            targets = tuple(zip(points))\n\n        self.insert_variables(*points, *weights)\n\n        return {0: targets}\n\n    # ....................................................\n    def _visit_PlusGlobalTensorQuadratureGrid(self, expr, **kwargs):\n        dim  = self.dim\n        rank = expr.rank\n\n        names = 'global_x1:%s_plus'%(dim+1)\n        points   = variables(names, dtype='real', rank=rank, cls=IndexedVariable)\n\n        # gather by axis\n        self.insert_variables(*points)\n\n        points = tuple(zip(points))\n        return dict([(0,points)])\n\n    # ....................................................\n    def _visit_PlusLocalTensorQuadratureGrid(self, expr, **kwargs):\n        dim  = self.dim\n        rank = expr.rank\n\n        names = 'local_x1:%s_plus'%(dim+1)\n        points   = variables(names, dtype='real', rank=rank, cls=IndexedVariable)\n\n        self.insert_variables(*points)\n\n        points = tuple(zip(points))\n        return dict([(0,points)])\n\n    # ....................................................\n    def _visit_TensorQuadrature(self, expr, **kwargs):\n        dim = self.dim\n        names   = 'x1:%s'%(dim+1)\n        points  = variables(names, dtype='real', cls=Variable)\n\n        if expr.weights:\n            names   = 'w1:%s'%(dim+1)\n            weights = variables(names, dtype='real', cls=Variable)\n\n            # gather by axis\n            targets = tuple(zip(points, weights))\n        else:\n            weights  = []\n            targets  = tuple(zip(points))\n\n        self.insert_variables(*points, *weights)\n\n        return {0: targets}\n\n    # ....................................................\n    def _visit_PlusTensorQuadrature(self, expr, **kwargs):\n        dim = self.dim\n        names   = 'x1:%s_plus'%(dim+1)\n        points  = variables(names, dtype='real', cls=Variable)\n\n        targets = tuple(zip(points))\n\n        self.insert_variables(*points)\n\n        return dict([(0,targets)])\n\n    # ....................................................\n    def _visit_GlobalThreadSpan(self, expr, **kwargs):\n        dim    = self.dim\n        rank   = expr.rank\n        target = SymbolicExpr(expr.target)\n        name   = 'thread_spans_{}'.format(target)\n        targets = variables('{}1:{}'.format(name, dim+1), dtype='int', rank=1, cls=IndexedVariable)\n        if expr.index is not None:\n            return targets[expr.index]\n        return targets\n\n    # ....................................................\n    def _visit_GlobalThreadStarts(self, expr, **kwargs):\n        dim    = self.dim\n        targets = variables('global_thread_starts_1:{}'.format(dim+1), dtype='int', rank=1, cls=IndexedVariable)\n        if expr.index is not None:\n            return targets[expr.index]\n        return targets\n\n    # ....................................................\n    def _visit_GlobalThreadEnds(self, expr, **kwargs):\n        dim    = self.dim\n        targets = variables('global_thread_ends_1:{}'.format(dim+1), dtype='int', rank=1, cls=IndexedVariable)\n        if expr.index is not None:\n            return targets[expr.index]\n        return targets\n\n    # ....................................................\n    def _visit_GlobalThreadSizes(self, expr, **kwargs):\n        dim    = self.dim\n        targets = variables('global_thread_size_1:{}'.format(dim+1), dtype='int')\n        if expr.index is not None:\n            return targets[expr.index]\n        return targets\n\n    # ....................................................\n    def _visit_LocalThreadStarts(self, expr, **kwargs):\n        dim    = self.dim\n        targets = variables('local_thread_starts_1:{}'.format(dim+1), dtype='int', rank=1, cls=IndexedVariable)\n        if expr.index is not None:\n            return targets[expr.index]\n        return targets\n\n    # ....................................................\n    def _visit_LocalThreadEnds(self, expr, **kwargs):\n        dim    = self.dim\n        targets = variables('local_thread_ends_1:{}'.format(dim+1), dtype='int', rank=1, cls=IndexedVariable)\n        if expr.index is not None:\n            return targets[expr.index]\n        return targets\n\n    # ....................................................\n    def _visit_MatrixQuadrature(self, expr, **kwargs):\n        rank   = self._visit(expr.rank)\n        target = SymbolicExpr(expr.target)\n\n        name = 'arr_{}'.format(target.name)\n        var  =  IndexedVariable(name, dtype='real', rank=rank)\n        self.insert_variables(var)\n        return var\n    # ....................................................\n    def _visit_GlobalTensorQuadratureBasis(self, expr, **kwargs):\n        # TODO add label\n        dim = self.dim\n        rank = expr.rank\n        unique_scalar_space = expr.unique_scalar_space\n        is_scalar           = expr.is_scalar\n        target              = expr.target\n        label               = str(SymbolicExpr(target))\n        if isinstance(expr, GlobalTensorQuadratureTestBasis):\n            if not unique_scalar_space:\n                names = 'global_test_basis_{label}(1:{j})_1:{i}'.format(label=label,i=dim+1,j=dim+1)\n            else:\n                names = 'global_test_basis_{label}_1:{i}'.format(label=label,i=dim+1)\n\n        elif isinstance(expr, GlobalTensorQuadratureTrialBasis):\n            if not unique_scalar_space:\n                names = 'global_trial_basis_{label}(1:{j})_1:{i}'.format(label=label,i=dim+1,j=dim+1)\n            else:\n                names = 'global_trial_basis_{label}_1:{i}'.format(label=label,i=dim+1)\n\n        else:\n            if not unique_scalar_space:\n                names = 'global_basis_{label}(1:{j})_1:{i}'.format(label=label,i=dim+1,j=dim+1)\n            else:\n                names = 'global_basis_{label}_1:{i}'.format(label=label,i=dim+1)\n\n        targets = variables(names, dtype='real', rank=rank, cls=IndexedVariable)\n\n        self.insert_variables(*targets)\n\n        arrays = {}\n        if unique_scalar_space and not is_scalar:\n            for i in range(dim):\n                arrays[target[i]] = tuple(zip(targets))\n        elif not unique_scalar_space:\n            for i in range(dim):\n                arrays[target[i]] = tuple(zip(targets[i::dim]))\n        else:\n            arrays[target] = tuple(zip(targets))\n        return arrays\n    # ....................................................\n    def _visit_LocalTensorQuadratureBasis(self, expr, **kwargs):\n        dim = self.dim\n        rank = expr.rank\n        unique_scalar_space = expr.unique_scalar_space\n        is_scalar           = expr.is_scalar\n        target              = expr.target\n        label               = str(SymbolicExpr(target))\n        if isinstance(expr, LocalTensorQuadratureTestBasis):\n            if not unique_scalar_space:\n                names = 'local_test_basis_{label}(1:{j})_1:{i}'.format(label=label,i=dim+1,j=dim+1)\n            else:\n                names = 'local_test_basis_{label}_1:{i}'.format(label=label,i=dim+1)\n\n        elif isinstance(expr, LocalTensorQuadratureTrialBasis):\n            if not unique_scalar_space:\n                names = 'local_trial_basis_{label}(1:{j})_1:{i}'.format(label=label,i=dim+1,j=dim+1)\n            else:\n                names = 'local_trial_basis_{label}_1:{i}'.format(label=label,i=dim+1)\n\n        else:\n            if not unique_scalar_space:\n                names = 'local_basis_{label}(1:{j})_1:{i}'.format(label=label,i=dim+1,j=dim+1)\n            else:\n                names = 'local_basis_{label}_1:{i}'.format(label=label,i=dim+1)\n\n        targets = variables(names, dtype='real', rank=rank, cls=IndexedVariable)\n        self.insert_variables(*targets)\n\n        arrays = {}\n        if unique_scalar_space and not is_scalar:\n            for i in range(dim):\n                arrays[target[i]] = tuple(zip(targets))\n        elif not unique_scalar_space:\n            for i in range(dim):\n                arrays[target[i]] = tuple(zip(targets[i::dim]))\n        else:\n            arrays[target] = tuple(zip(targets))\n        return arrays\n\n    # ....................................................\n    def _visit_TensorQuadratureBasis(self, expr, **kwargs):\n        dim  = self.dim\n        rank = expr.rank\n        unique_scalar_space = expr.unique_scalar_space\n        is_scalar           = expr.is_scalar\n        target              = expr.target\n        label               = str(SymbolicExpr(target))\n\n        if isinstance(expr, TensorQuadratureTestBasis):\n            if not unique_scalar_space:\n                names = 'test_basis_{label}(1:{j})_1:{i}'.format(label=label,i=dim+1,j=dim+1)\n            else:\n                names = 'test_basis_{label}_1:{i}'.format(label=label,i=dim+1)\n\n        elif isinstance(expr, TensorQuadratureTrialBasis):\n            if not unique_scalar_space:\n                names = 'trial_basis_{label}(1:{j})_1:{i}'.format(label=label,i=dim+1,j=dim+1)\n            else:\n                names = 'trial_basis_{label}_1:{i}'.format(label=label,i=dim+1)\n        else:\n            if not unique_scalar_space:\n                names = 'array_basis_{label}(1:{j})_1:{i}'.format(label=label,i=dim+1,j=dim+1)\n            else:\n                names = 'array_basis_{label}_1:{i}'.format(label=label,i=dim+1)\n        # ...\n\n        targets = variables(names, dtype='real', rank=rank, cls=IndexedVariable)\n\n        self.insert_variables(*targets)\n        arrays = {}\n        if unique_scalar_space and not is_scalar:\n            for i in range(dim):\n                arrays[target[i]] = tuple(zip(targets))\n        elif not unique_scalar_space:\n            for i in range(dim):\n                arrays[target[i]] = tuple(zip(targets[i::dim]))\n        else:\n            arrays[target] = tuple(zip(targets))\n        return arrays\n\n    # ....................................................\n    def _visit_GlobalSpan(self, expr, **kwargs):\n        dim    = self.dim\n        rank   = expr.rank\n        target = expr.target\n        label = SymbolicExpr(target).name\n\n        names  = 'global_span_{}_1:{}'.format(label, str(dim+1))\n        targets = variables(names, dtype='int', rank=rank, cls=IndexedVariable)\n        if expr.index is not None:\n            return targets[expr.index]\n\n        self.insert_variables(*targets)\n        if not isinstance(targets[0], (tuple, list, Tuple)):\n            targets = [targets]\n        target = {target: tuple(zip(*targets))}\n        return target\n    # ....................................................\n    def _visit_Span(self, expr, **kwargs):\n        dim = self.dim\n        target = expr.target\n        label  = SymbolicExpr(target).name\n        names  = 'span_{}_1:{}'.format(label,str(dim+1))\n        targets = variables(names, dtype='int')\n\n        if expr.index is not None:\n            return targets[expr.index]\n\n        self.insert_variables(*targets)\n        if not isinstance(targets[0], (tuple, list, Tuple)):\n            targets = [targets]\n\n        target = {target: tuple(zip(*targets))}\n        return target\n\n    def _visit_Pads(self, expr, **kwargs):\n        dim           = self.dim\n        tests         = expand(expr.tests)\n        tests_degree  = expr.tests_degree\n        trials_degree = expr.trials_degree\n        m_tests       = expr.tests_multiplicity\n        m_trials      = expr.trials_multiplicity\n\n        if expr.trials is not None:\n            trials = expand(expr.trials)\n            pads = Matrix.zeros(len(tests),len(trials))\n            for i in range(pads.shape[0]):\n                for j in range(pads.shape[1]):\n                    label1 = SymbolicExpr(tests[i]).name\n                    label2 = SymbolicExpr(trials[j]).name\n                    names  = 'pad_{}_{}_1:{}'.format(label2, label1, str(dim+1))\n                    targets = variables(names, dtype='int')\n                    pads[i,j] = Tuple(*targets)\n                    self.insert_variables(*targets)\n        else:\n            pads = Matrix.zeros(len(tests),1)\n            for i in range(pads.shape[0]):\n                label1 = SymbolicExpr(tests[i]).name\n                names  = 'pad_{}_1:{}'.format(label1, str(dim+1))\n                targets = variables(names, dtype='int')\n                pads[i,0] = Tuple(*targets)\n                self.insert_variables(*targets)\n        return pads\n    # ....................................................\n    def _visit_TensorBasis(self, expr, **kwargs):\n        # TODO label\n        dim = self.dim\n        nderiv = self.nderiv\n        target = expr.target\n\n        ops = [dx1, dx2, dx3][:dim]\n        atoms =  _split_test_function(target)\n        args = {}\n        for atom in atoms:\n            sub_args = [None]*dim\n            for i in range(dim):\n                d = ops[i]\n                a = atoms[atom][i]\n                ls = [a]\n                for _ in range(1, nderiv+1):\n                    a = d(a)\n                    ls.append(a)\n                sub_args[i] = tuple(ls)\n            args[atom] = tuple(sub_args)\n        return args\n\n    # ....................................................\n    def _visit_CoefficientBasis(self, expr, **kwargs):\n        target = SymbolicExpr(expr.target)\n        name = 'coeff_{}'.format(target.name)\n        var  = IndexedVariable(name, dtype='real', rank=self.dim)\n        self.insert_variables(var)\n        return var\n\n    def _visit_MatrixCoordsFromRank(self, expr, **kwargs):\n        var  = IndexedVariable('coords_from_rank', dtype='int', rank=2)\n        return var\n\n    def _visit_MatrixRankFromCoords(self, expr, **kwargs):\n        var  = IndexedVariable('rank_from_coords', dtype='int', rank=self.dim)\n        return var\n    # ....................................................\n    def _visit_MatrixLocalBasis(self, expr, **kwargs):\n        rank   = self._visit(expr.rank)\n        target = SymbolicExpr(expr.target)\n        name = 'arr_coeffs_{}'.format(target.name)\n        var  = IndexedVariable(name, dtype='real', rank=rank)\n        self.insert_variables(var)\n        return var\n    # ....................................................\n\n    def _visit_MatrixGlobalBasis(self, expr, **kwargs):\n        rank   = self._visit(expr.rank)\n        target = SymbolicExpr(expr.target)\n\n        name = 'global_arr_coeffs_{}'.format(target.name)\n        var  = IndexedVariable(name, dtype='real', rank=rank)\n        self.insert_variables(var)\n        return var\n    # ....................................................\n    def _visit_Reset(self, expr, **kwargs):\n        var = expr.var\n        lhs  = self._visit(var, **kwargs)\n        if isinstance(var, (LocalElementBasis, GlobalElementBasis)):\n            return Assign(lhs, 0.)\n\n        elif isinstance(var, BlockScalarLocalBasis):\n            expr = var.expr\n            return tuple(Assign(a, 0.) for a,b in zip(lhs[:], expr[:]) if b)\n\n        expr = var.expr\n        rank = lhs[0,0].rank\n        args  = [Slice(None, None)]*rank\n        return tuple(Assign(a[args], 0.) for a,b in zip(lhs[:], expr[:]) if b)\n\n    # ....................................................\n    def _visit_Reduce(self, expr, **kwargs):\n        op   = expr.op\n        lhs  = expr.lhs\n        rhs  = expr.rhs\n        loop = expr.loop\n        parallel     = loop.parallel\n        default      = loop.default\n        shared       = loop.shared\n        private      = loop.private\n        firstprivate = loop.firstprivate\n        lastprivate  = loop.lastprivate\n        reduction    = None\n        if parallel:\n            reduction = 'reduction({}:{})'.format(expr.op, self._visit(lhs).name)\n\n        stmts = list(loop.stmts) + [Reduction(op, rhs, lhs)]\n        loop  = Loop(loop.iterable, loop.index, stmts=stmts, mask=loop.mask, parallel=parallel,\n                    default=default, shared=shared, private=private,\n                    firstprivate=firstprivate, lastprivate=lastprivate, reduction=reduction)\n        return self._visit(loop, **kwargs)\n\n    # ....................................................\n    def _visit_Reduction(self, expr, **kwargs):\n        op   = expr.op\n        lhs  = expr.lhs\n        expr = expr.expr\n\n        if isinstance(lhs, (GlobalElementBasis, LocalElementBasis)):\n            lhs = self._visit(lhs, **kwargs)\n            rhs = self._visit(expr, **kwargs)\n            return (AugAssign(lhs, op, rhs),)\n\n        elif isinstance(lhs, BlockStencilMatrixLocalBasis):\n            lhs = self._visit_BlockStencilMatrixLocalBasis(lhs)\n            expr = self._visit(expr, op=op, lhs=lhs)\n            return expr\n        elif isinstance(lhs, BlockStencilMatrixGlobalBasis):\n\n            dim  = self.dim\n            rank = lhs.rank\n            pads = lhs.pads\n            multiplicity = lhs.multiplicity\n            tests = expand(lhs._tests)\n\n            tests_2 = lhs._tests\n            lhs = self._visit_BlockStencilMatrixGlobalBasis(lhs)\n            rhs = self._visit(expr)\n\n            pads    = self._visit(pads)\n            rhs_slices = [Slice(None, None)]*rank\n            for k1 in range(lhs.shape[0]):\n                test = tests[k1]\n                test = test if test in tests_2 else test.base\n                spans   = self._visit_Span(Span(test))\n                degrees = self._visit_LengthDofTest(LengthDofTest(test))\n                spans   = flatten(*spans.values())\n                m    = multiplicity[test] if test in multiplicity else multiplicity[test.base]\n                lhs_starts = [spans[i]+m[i]*pads[i]-degrees[i] for i in range(dim)]\n                lhs_ends   = [spans[i]+m[i]*pads[i]+1          for i in range(dim)]\n                if isinstance(self._target, Interface):\n                    axis = self._target.axis\n                    lhs_starts[axis] = pads[axis]\n                    lhs_ends[axis]   = pads[axis] + degrees[axis] + 1\n\n                for k2 in range(lhs.shape[1]):\n                    if expr.expr[k1,k2]:\n                        lhs_slices  = [Slice(s, e) for s,e in zip(lhs_starts, lhs_ends)]\n                        lhs_slices += [Slice(None, None)]*dim\n                        lhs[k1,k2] = [lhs[k1,k2][lhs_slices]]\n                        rhs[k1,k2] = [rhs[k1,k2][rhs_slices]]\n\n            return tuple( AugAssign(a, op, b) for a,b,e in zip(lhs[:], rhs[:], expr.expr[:]) if e)\n\n        elif isinstance(lhs, BlockStencilVectorLocalBasis):\n            lhs = self._visit_BlockStencilVectorLocalBasis(lhs)\n            expr = self._visit(expr, op=op, lhs=lhs)\n            return expr\n        elif isinstance(lhs, BlockStencilVectorGlobalBasis):\n            dim   = self.dim\n            rank  = lhs.rank\n            pads  = lhs.pads\n            multiplicity = lhs.multiplicity\n            tests = expand(lhs._tests)\n            tests_2 = lhs._tests\n            lhs = self._visit_BlockStencilVectorGlobalBasis(lhs)\n            rhs = self._visit(expr)\n            pads    = self._visit(pads)\n            rhs_slices = [Slice(None, None)]*rank\n\n            for k in range(lhs.shape[0]):\n                if expr.expr[k,0]:\n                    test = tests[k]\n                    m    = multiplicity[test] if test in multiplicity else multiplicity[test.base]\n                    test = test if test in tests_2 else test.base\n                    spans   = self._visit_Span(Span(test))\n                    spans   = flatten(*spans.values())\n                    degrees = self._visit_LengthDofTest(LengthDofTest(test))\n                    lhs_starts = [spans[i]+m[i]*pads[i]-degrees[i] for i in range(dim)]\n                    lhs_ends   = [spans[i]+m[i]*pads[i]+1          for i in range(dim)]\n                    lhs_slices = [Slice(s, e) for s,e in zip(lhs_starts, lhs_ends)]\n                    lhs[k,0] = lhs[k,0][lhs_slices]\n                    rhs[k,0] = rhs[k,0][rhs_slices]\n\n            return tuple( AugAssign(a, op, b) for a,b,e in zip(lhs[:], rhs[:], expr.expr[:]) if e)\n        else:\n            if not( lhs is None ):\n                lhs = self._visit(lhs)\n\n            return self._visit(expr, op=op, lhs=lhs)\n    # ....................................................\n    def _visit_ComputeLogical(self, expr, op=None, lhs=None, **kwargs):\n        expr = expr.expr\n        if lhs is None:\n            if not isinstance(expr, (Add, Mul)):\n                lhs = self._visit_AtomicNode(AtomicNode(expr), **kwargs)\n            else:\n                lhs = random_string( 6 )\n                lhs = Symbol('tmp_{}'.format(lhs))\n\n        node = LogicalValueNode(expr)\n        rhs = self._visit_LogicalValueNode(node, **kwargs)\n\n        if op is None:\n            stmt = Assign(lhs, rhs)\n        else:\n            stmt = AugAssign(lhs, op, rhs)\n\n        return self._visit(stmt, **kwargs)\n\n    # ....................................................\n    def _visit_ComputeLogicalBasis(self, expr, op=None, lhs=None, **kwargs):\n        expr = expr.expr\n        if lhs is None:\n            if not isinstance(expr, (Add, Mul)):\n                atom = BasisAtom(expr)\n                lhs  = self._visit_BasisAtom(atom, **kwargs)\n            else:\n                lhs = random_string( 6 )\n                lhs = Symbol('tmp_{}'.format(lhs))\n\n        expr = LogicalBasisValue(expr)\n        rhs = self._visit_LogicalBasisValue(expr, **kwargs)\n\n        if op is None:\n            stmt = Assign(lhs, rhs)\n        else:\n            stmt = AugAssign(lhs, op, rhs)\n\n        return self._visit(stmt, **kwargs)\n\n    # ....................................................\n    def _visit_ComputeKernelExpr(self, expr, op=None, lhs=None, **kwargs):\n        if lhs is None:\n            if not isinstance(expr, (Add, Mul)):\n                lhs = self._visit_BasisAtom(BasisAtom(expr), **kwargs)\n            else:\n                lhs = random_string( 6 )\n                lhs = Symbol('tmp_{}'.format(lhs))\n\n        exprs   = expr.expr\n        mapping = self.mapping\n\n        if expr.weights:\n            weight  = SymbolicWeightedVolume(mapping)\n            weight  = SymbolicExpr(weight)\n        else:\n            weight  = 1\n\n        rhs = [weight*self._visit(expr, **kwargs) for expr in exprs[:]]\n        lhs = lhs[:]\n\n        temps = []\n        temps, rhs = cse_main.cse(rhs, symbols=cse_main.numbered_symbols(prefix='temp'))\n\n        normal_vec_stmts = []\n        normal_vectors = expr.expr.atoms(NormalVector)\n        target         = self._target\n        dim            = self._dim\n\n        if normal_vectors:\n            axis    = target.axis\n            ext     = target.ext if isinstance(target, Boundary) else 1\n\n        vars_plus = []\n        if isinstance(target, Interface):\n            mapping = mapping.minus\n            target  = target.minus\n            axis    = target.axis\n            ext     = target.ext\n        elif isinstance(target, Boundary):\n            ext  = target.ext\n            axis = target.axis\n\n\n        for vec in normal_vectors:\n\n            J_inv   = LogicalExpr(mapping.jacobian_inv_expr, mapping(target))\n            J_inv   = SymbolicExpr(J_inv)\n            values  = ext * J_inv[axis, :]\n            normalization = values.dot(values)**0.5\n            values  = [v for v in values]\n            values  = [v1/normalization for v1 in values]\n            normal_vec_stmts += [Assign(SymbolicExpr(vec[i]), values[i]) for i in range(dim)]\n\n        if op is None:\n            stmts = [Assign(i, j) for i,j in zip(lhs,rhs) if j]\n        else:\n            stmts = [AugAssign(i, op, j) for i,j in zip(lhs,rhs) if j]\n\n        temps = tuple(Assign(a,b) for a,b in temps)\n        stmts = tuple(self._visit(stmt, **kwargs) for stmt in stmts)\n        stmts = tuple(vars_plus) + tuple(normal_vec_stmts) + temps + stmts\n\n        math_functions = math_atoms_as_str(list(exprs)+normal_vec_stmts, 'math')\n        math_functions = tuple(m for m in math_functions if m not in self._math_functions)\n        self._math_functions = math_functions + self._math_functions\n        return stmts\n\n    # ....................................................\n    def _visit_BasisAtom(self, expr, **kwargs):\n        symbol = SymbolicExpr(expr.expr)\n        self.variables[str(symbol.name)] = symbol\n        return symbol\n\n    # ....................................................\n    def _visit_AtomicNode(self, expr, **kwargs):\n        if isinstance(expr.expr, WeightedVolumeQuadrature):\n            expr = SymbolicWeightedVolume(self.mapping)\n            return self._visit(expr, **kwargs )\n\n        else:\n            return SymbolicExpr(expr.expr)\n\n    # ....................................................\n    def _visit_LogicalBasisValue(self, expr, **kwargs):\n        # ...\n        dim = self.dim\n        coords = ['x1', 'x2', 'x3'][:dim]\n\n        expr   = expr.expr\n        atom   = BasisAtom(expr).atom\n        atoms  = _split_test_function(atom)\n        ops = [dx1, dx2, dx3][:dim]\n        d_atoms = dict(zip(coords, atoms[atom]))\n        d_ops   = dict(zip(coords, ops))\n        d_indices = get_index_logical_derivatives(expr)\n        args = []\n        for k,u in d_atoms.items():\n            d = d_ops[k]\n            n = d_indices[k]\n            for _ in range(n):\n                u = d(u)\n            args.append(u)\n        # ...\n\n        expr = Mul(*args)\n        expr =  SymbolicExpr(expr)\n        return expr\n\n    # ....................................................\n    def _visit_LogicalValueNode(self, expr, **kwargs):\n\n        expr = expr.expr\n        target = self.target\n\n        if isinstance(expr, WeightedVolumeQuadrature):\n            #TODO improve l_quad should not be used like this\n            l_quad = TensorQuadrature()\n            l_quad = self._visit_TensorQuadrature(l_quad, **kwargs)\n            _, weights = list(zip(*list(l_quad.values())[0]))\n            if isinstance(target, Boundary):\n                weights = list(weights)\n                weights.pop(target.axis)\n            wvol = Mul(*weights)\n            return wvol\n        else:\n            raise TypeError('{} not available'.format(type(expr)))\n\n    # ....................................................\n    def _visit_PhysicalGeometryValue(self, expr, **kwargs):\n        target  = self._target\n        expr = LogicalExpr(expr.expr, mapping(target))\n\n        return SymbolicExpr(expr)\n\n    # ....................................................\n    def _visit_ElementOf(self, expr, **kwargs):\n        dim    = self.dim\n        target = expr.target\n        #improve we shouldn't use index_dof_test\n        if isinstance(target, BlockStencilMatrixLocalBasis):\n            rows = self._visit(index_dof_test)\n            outer = self._visit(target.outer) if target.outer else rows\n            cols = self._visit(index_dof_trial)\n            pads = target.pads\n            tests  = expand(target._tests)\n            trials = expand(target._trials)\n\n            targets = self._visit_BlockStencilMatrixLocalBasis(target)\n            for i in range(targets.shape[0]):\n                for j in range(targets.shape[1]):\n                    if targets[i,j] is None:\n                        continue\n                    if trials[j] in pads.trials_multiplicity:\n                        trials_m  = pads.trials_multiplicity[trials[j]]\n                        trials_d  = pads.trials_degree[trials[j]]\n                    else:\n                        trials_m = pads.trials_multiplicity[trials[j].base]\n                        trials_d = pads.trials_degree[trials[j].base]\n\n                    if tests[i] in pads.tests_multiplicity:\n                        tests_m  = pads.tests_multiplicity[tests[i]]\n                        tests_d  = pads.tests_degree[tests[i]]\n                    else:\n                        tests_m = pads.tests_multiplicity[tests[i].base]\n                        tests_d = pads.tests_degree[tests[i].base]\n\n                    pp1     = [max(tests_d[k], trials_d[k]) for k in range(dim)]\n                    pp2     = [int((np.ceil((pp1[k]+1)/tests_m[k])-1)*trials_m[k]) for k in range(dim)]\n                    padding = [p2-min(0,p2-p1) for p1,p2 in zip(pp1, pp2)]\n                    indices = tuple(rows) + tuple(cols[k]+padding[k]-outer[k]*trials_m[k] for k in range(dim))\n                    targets[i,j] = targets[i,j][indices]\n            return targets\n\n        elif isinstance(target, BlockStencilVectorLocalBasis):\n            targets = self._visit_BlockStencilVectorLocalBasis(target, **kwargs)\n\n            rows = self._visit(index_dof_test)\n            indices = list(rows)\n            for i in range(targets.shape[0]):\n                for j in range(targets.shape[1]):\n                    if targets[i,j] is None:\n                        continue\n                    targets[i,j] = targets[i,j][indices]\n            return targets\n        elif isinstance(target, LocalElementBasis):\n            target = self._visit(target, **kwargs)\n            return (target,)\n\n        elif isinstance(target, BlockScalarLocalBasis):\n            targets = self._visit(target)\n            return targets\n        else:\n            raise NotImplementedError('TODO')\n\n    # .............................................................................\n    def _visit_BlockStencilMatrixLocalBasis(self, expr, **kwargs):\n        pads   = self._visit_Pads(expr.pads)\n        tests  = expr._tests\n        trials = expr._trials\n        tag    = expr.tag\n        tests   = expand(tests)\n        trials  = expand(trials)\n        targets = Matrix.zeros(len(tests), len(trials))\n        for i,v in enumerate(tests):\n            for j,u in enumerate(trials):\n                if expr.expr[i,j] == 0:\n                    targets[i,j] = None\n                    continue\n                mat = StencilMatrixLocalBasis(u, v, pads[i,j], tag)\n                mat = self._visit_StencilMatrixLocalBasis(mat, **kwargs)\n                targets[i,j] = mat\n        return targets\n\n    def _visit_BlockStencilMatrixGlobalBasis(self, expr, **kwargs):\n        pads   = expr.pads\n        tests  = expr._tests\n        trials = expr._trials\n        tag    = expr.tag\n        tests   = expand(tests)\n        trials  = expand(trials)\n        targets = Matrix.zeros(len(tests), len(trials))\n        for i,v in enumerate(tests):\n            for j,u in enumerate(trials):\n                if expr.expr[i,j] == 0:\n                    targets[i,j] = None\n                    continue\n                mat = StencilMatrixGlobalBasis(u, v, pads, tag)\n                mat = self._visit_StencilMatrixGlobalBasis(mat, **kwargs)\n                targets[i,j] = mat\n        return targets\n\n    def _visit_BlockStencilVectorLocalBasis(self, expr, **kwargs):\n        pads   = expr.pads\n        tests  = expr._tests\n        tag    = expr.tag\n        tests   = expand(tests)\n        targets = Matrix.zeros(len(tests), 1)\n        for i,v in enumerate(tests):\n            if expr.expr[i,0] == 0:\n                targets[i,0] = None\n                continue\n            mat = StencilVectorLocalBasis(v, pads, tag)\n            mat = self._visit_StencilVectorLocalBasis(mat, **kwargs)\n            targets[i,0] = mat\n        return targets\n\n    def _visit_BlockStencilVectorGlobalBasis(self, expr, **kwargs):\n        pads   = expr.pads\n        tests  = expr._tests\n        tag    = expr.tag\n        tests   = expand(tests)\n        targets = Matrix.zeros(len(tests), 1)\n        for i,v in enumerate(tests):\n            if expr.expr[i,0] == 0:\n                targets[i,0] = None\n                continue\n            mat = StencilVectorGlobalBasis(v, pads, tag)\n            mat = self._visit_StencilVectorGlobalBasis(mat, **kwargs)\n            targets[i,0] = mat\n        return targets\n\n    # .............................................................................\n    def _visit_BlockScalarLocalBasis(self, expr, **kwargs):\n        tag    = expr.tag\n        tests   = expand(expr._tests)\n        trials  = expand(expr._trials) if expr._trials else (None,)\n        targets = Matrix.zeros(len(tests), len(trials))\n        for i,v in enumerate(tests):\n            for j,u in enumerate(trials):\n                if expr.expr[i,j] == 0:\n                    targets[i,j] = None\n                    continue\n                var = ScalarLocalBasis(u, v, tag)\n                var = self._visit_ScalarLocalBasis(var, **kwargs)\n                targets[i,j] = var\n        return targets\n\n    # .............................................................................\n    def _visit_StencilMatrixLocalBasis(self, expr, **kwargs):\n        rank = expr.rank\n        tag  = expr.tag\n        name = '_'.join(str(SymbolicExpr(e)) for e in expr.name)\n\n        name = 'l_mat_{}_{}'.format(name, tag)\n        var  = IndexedVariable(name, dtype='real', rank=rank)\n        self.insert_variables(var)\n        return var\n\n    # ....................................................\n    def _visit_StencilVectorLocalBasis(self, expr, **kwargs):\n        rank = expr.rank\n        tag  = expr.tag\n        name = str(SymbolicExpr(expr.name))\n        name = 'l_vec_{}_{}'.format(name, tag)\n        var  = IndexedVariable(name, dtype='real', rank=rank) \n        self.insert_variables(var)\n        return var\n\n    # ....................................................\n    def _visit_StencilMatrixGlobalBasis(self, expr, **kwargs):\n        rank = expr.rank\n        tag  = expr.tag\n        name = '_'.join(str(SymbolicExpr(e)) for e in expr.name)\n        name = 'g_mat_{}_{}'.format(name, tag)\n        var  = IndexedVariable(name, dtype='real', rank=rank)\n        self.insert_variables(var)\n        return var\n\n    # ....................................................\n    def _visit_StencilVectorGlobalBasis(self, expr, **kwargs):\n        rank = expr.rank\n        tag  = expr.tag\n        name = str(SymbolicExpr(expr.name))\n        name = 'g_vec_{}_{}'.format(name, tag)        \n        var  = IndexedVariable(name, dtype='real', rank=rank)\n        self.insert_variables(var)\n        return var\n\n    def _visit_GlobalElementBasis(self, expr, **kwargs):\n        tag  = expr.tag\n        name = 'g_el_{}'.format(tag)\n        var  = variables(name, dtype='real')\n        self.insert_variables(var)\n        return var\n\n    def _visit_LocalElementBasis(self, expr, **kwargs):\n        tag  = expr.tag\n        name = 'l_el_{}'.format(tag)\n        var  = variables(name, dtype='real') \n        self.insert_variables(var)\n        return var\n\n    def _visit_ScalarLocalBasis(self, expr, **kwargs):\n        tag  = expr.tag\n        basis = (expr._test,)\n        if expr._trial:\n            basis = (expr._test, expr._trial)\n        name = '_'.join(str(SymbolicExpr(e)) for e in basis)\n        name = 'contribution_{}_{}'.format(name, tag)\n        var  = variables(name, dtype='real') \n        self.insert_variables(var)\n        return var\n\n    # ....................................................\n    def _visit_Pattern(self, expr, **kwargs):\n        # this is for multi-indices for the moment\n        dim = self.dim\n        args = []\n        for a in expr:\n            if a is None:\n                args.append([Slice(None, None)]*dim)\n\n            elif isinstance(a, int):\n                args.append([a]*dim)\n\n            else:\n                v = self._visit(a)\n                args.append(v)\n        args = list(zip(*args))\n        return args\n\n    def _visit_TensorIntDiv(self, expr, **kwargs):\n        args = [self._visit(a, **kwargs) for a in expr.args]\n        arg1 = args[0]\n        arg2 = args[1]\n        newargs = []\n        for i,j in zip(arg1, arg2):\n            newargs.append(i//j)\n            \n        return tuple(newargs)\n\n    def _visit_TensorAdd(self, expr, **kwargs):\n        args = [self._visit(a, **kwargs) for a in expr.args]\n        arg1 = args[0]\n        arg2 = args[1]\n        newargs = []\n        for i,j in zip(arg1, arg2):\n            newargs.append(i+j)\n            \n        return tuple(newargs)\n\n    def _visit_TensorMul(self, expr, **kwargs):\n        args = [self._visit(a, **kwargs) for a in expr.args]\n        arg1 = args[0]\n        arg2 = args[1]\n        newargs = []\n        for i,j in zip(arg1, arg2):\n            newargs.append(i*j)\n            \n        return tuple(newargs)\n\n    def _visit_TensorMax(self, expr, **kwargs):\n        args = [self._visit(a, **kwargs) for a in expr.args]\n        arg1 = args[0]\n        arg2 = args[1]\n        newargs = []\n        for i,j in zip(arg1, arg2):\n            newargs.append(Max(i,j))\n\n        return tuple(newargs)\n\n    def _visit_TensorInteger(self, expr, **kwargs):\n        return (expr.args[0],)*self.dim\n    # ....................................................\n\n    def _visit_Max(self, expr, **kwargs):\n        args = [self._visit(i) for i in expr.args]\n        return Max(*args)\n\n    def _visit_Min(self, expr, **kwargs):\n        args = [self._visit(i) for i in expr.args]\n        return Min(*args)\n\n    def _visit_Expr(self, expr, **kwargs):\n        return SymbolicExpr(expr)\n\n    def _visit_Return( self, expr, **kwargs):\n        return Return(self._visit(expr.expr))\n\n    def _visit_NumThreads(self, expr, **kwargs):\n        target =  variables('num_threads', dtype='int')\n        self.insert_variables(target)\n        return target\n\n    def _visit_BooleanTrue(self, expr, **kwargs):\n        return int(True)\n\n    def _visit_BooleanFalse(self, expr, **kwargs):\n        return int(False)\n    # ....................................................\n    def _visit_ThreadId(self, expr, **kwargs):\n        return variables('thread_id', dtype='int')\n    # ...................................................\n    def _visit_NeighbourThreadCoordinates(self, expr, **kwargs):\n        dim    = self.dim\n        target =  variables('next_thread_coords_1:%d'%(dim+1), dtype='int')\n        if expr.index is not None:\n            return target[expr.index]\n        self.insert_variables(*target)\n        return target\n    # ....................................................\n    def _visit_ThreadCoordinates(self, expr, **kwargs):\n        dim    = self.dim\n        target =  variables('thread_coords_1:%d'%(dim+1), dtype='int')\n        if expr.index is not None:\n            return target[expr.index]\n        return target\n    # ....................................................\n    def _visit_IndexElement(self, expr, **kwargs):\n        dim    = self.dim\n        target =  variables('i_element_1:%d'%(dim+1), dtype='int')\n        self.insert_variables(*target)\n        return target\n    # ....................................................\n    def _visit_LocalIndexElement(self, expr, **kwargs):\n        dim    = self.dim\n        target =  variables('local_i_element_1:%d'%(dim+1), dtype='int')\n        if expr.index is not None:\n            return target[expr.index]\n        return target\n    # ....................................................\n    def _visit_IndexQuadrature(self, expr, **kwargs):\n        dim = self.dim\n        target = variables('i_quad_1:%d'%(dim+1), dtype='int')\n        self.insert_variables(*target)\n        return target\n    # ....................................................\n    def _visit_IndexDof(self, expr, **kwargs):\n        dim = self.dim\n        target = variables('i_basis_1:%d'%(dim+1), dtype='int')\n        self.insert_variables(*target)\n        return target\n    # ....................................................\n    def _visit_IndexDofTrial(self, expr, **kwargs):\n        dim = self.dim\n        target = variables('j_basis_1:%d'%(dim+1), dtype='int')\n        self.insert_variables(*target)\n        return target\n    # ....................................................\n    def _visit_IndexDofTest(self, expr, **kwargs):\n        dim = self.dim\n        target = variables('i_basis_1:%d'%(dim+1), dtype='int')\n        self.insert_variables(*target)\n        return target\n    # ....................................................\n    def _visit_IndexOuterDofTest(self, expr, **kwargs):\n        dim = self.dim\n        target = variables('outer_i_basis_1:%d'%(dim+1), dtype='int')\n        self.insert_variables(*target)\n        return target\n    # ....................................................\n    def _visit_IndexInnerDofTest(self, expr, **kwargs):\n        dim = self.dim\n        target = variables('inner_i_basis_1:%d'%(dim+1), dtype='int')\n        self.insert_variables(*target)\n        return target\n    # ....................................................\n    def _visit_IndexDerivative(self, expr, **kwargs):\n        raise NotImplementedError('TODO')\n\n    # ....................................................\n    def _visit_LengthElement(self, expr, **kwargs):\n        dim = self.dim\n        names = 'n_element_1:%d'%(dim+1)\n        target = variables(names, dtype='int', cls=Variable)\n        if expr.index is not None:\n            return target[expr.index]\n        self.insert_variables(*target)\n        return target\n    # ....................................................\n    def _visit_LengthQuadrature(self, expr, **kwargs):\n        dim = self.dim\n        names = 'k1:%d'%(dim+1)\n        target = variables(names, dtype='int', cls=Variable)\n        self.insert_variables(*target)\n        return target\n    # ....................................................\n    def _visit_LengthDof(self, expr, **kwargs):\n        dim = self.dim\n        names = 'p1:%d'%(dim+1)\n        target = variables(names, dtype='int')\n        self.insert_variables(*target)\n        return target\n    # ....................................................\n    def _visit_LengthDofTest(self, expr, **kwargs):\n        dim = self.dim\n        target = expr.target\n        if target:\n            target = '_' + str(SymbolicExpr(target))\n        else:\n            target = ''\n\n        names = 'test{}_p1:{}'.format(target, dim+1)\n        target = variables(names, dtype='int')\n        self.insert_variables(*target)\n        return target\n    # ....................................................\n    def _visit_LengthOuterDofTest(self, expr, **kwargs):\n        dim = self.dim\n        target = expr.target\n        if target:\n            target = '_' + str(SymbolicExpr(target))\n        else:\n            target = ''\n\n        names = 'test_outer{}_p1:{}'.format(target, dim+1)\n        target = variables(names, dtype='int')\n        self.insert_variables(*target)\n        return target\n    # ....................................................\n    def _visit_LengthInnerDofTest(self, expr, **kwargs):\n        dim = self.dim\n        target = expr.target\n        if target:\n            target = '_' + str(SymbolicExpr(target))\n        else:\n            target = ''\n\n        names = 'test_inner{}_p1:{}'.format(target, dim+1)\n        target = variables(names, dtype='int')\n        self.insert_variables(*target)\n        return target\n\n    # ....................................................\n    def _visit_LengthDofTrial(self, expr, **kwargs):\n        dim = self.dim\n        target = expr.target\n        if target:\n            target = '_' + str(SymbolicExpr(target))\n        else:\n            target = ''\n\n        names = 'trial{}_p1:{}'.format(target, dim+1)\n        target = variables(names, dtype='int')\n        self.insert_variables(*target)\n        return target\n    # ....................................................\n    def _visit_RankDimension(self, expr, **kwargs):\n        return self.dim\n\n    # ....................................................\n    def _visit_TensorIterator(self, expr, **kwargs):\n        target = self._visit(expr.target)\n        return target\n\n    # ....................................................\n    def _visit_ProductIterator(self, expr, **kwargs):\n        target = self._visit(expr.target)\n        return target\n\n    # ....................................................\n    def _visit_TensorGenerator(self, expr, **kwargs):\n\n        targets = self._visit(expr.target)\n        if expr.dummies is None:\n            #TODO check if we never pass this condition\n            return expr.target\n\n        if not hasattr(expr.target, 'pattern'):\n            return targets\n\n        patterns = expr.target.pattern()\n        patterns = self._visit_Pattern(patterns)\n        args = {}\n        for i,target in targets.items():\n            args[i] = []\n            for p, xs in zip(patterns, target):\n                ls = []\n                for x in xs:\n                    ls.append(x[p])\n                args[i].append(tuple(ls))\n            args[i] = tuple(args[i])\n\n        return args\n    # ....................................................\n    def _visit_ProductGenerator(self, expr, **kwargs):\n        target = self._visit(expr.target)\n\n        # treat dummies and put them in the namespace\n        dummies = self._visit(expr.dummies)\n        dummies = dummies[0] # TODO add comment\n        return target[dummies]\n\n    # ....................................................\n    def _visit_TensorIteration(self, expr, **kwargs):\n        dim       = self.dim\n        iterator  = self._visit(expr.iterator)\n        generator = self._visit(expr.generator)\n\n        if isinstance(iterator, (tuple, Tuple, list)):\n            inits = []\n            for i,g in zip(iterator, generator):\n                inits.append([Assign(i,g)])\n            return inits\n\n        inits = [()]*dim\n\n        for (i, l_xs),(j, g_xs) in zip(iterator.items(), generator.items()):\n            if isinstance(expr.generator.target, GlobalTensorQuadratureBasis):\n                positions = [expr.generator.target.positions[index_deriv]]\n                g_xs = [SplitArray(xs[0], positions, [self.nderiv+1]) for xs in g_xs]\n                g_xs = [tuple(self._visit(xs, **kwargs)) for xs in g_xs]\n\n            for i in  range(dim):\n                ls = []\n                for l_x,g_x in zip(l_xs[i], g_xs[i]):\n                    if isinstance(expr.generator.target, GlobalTensorQuadratureBasis):\n                        lhs = self._visit_BasisAtom(BasisAtom(l_x))\n                    else:\n                        lhs = l_x\n                    ls += [self._visit(Assign(lhs, g_x))]\n                inits[i] += tuple(ls)\n        inits = [flatten(init) for init in inits]\n        return  inits\n\n    # ....................................................\n    def _visit_ProductIteration(self, expr, **kwargs):\n        # TODO for the moment, we do not return indices and lengths\n        iterator  = self._visit(expr.iterator)\n        generator = self._visit(expr.generator)\n    \n        return Assign(iterator, generator)\n\n    def _visit_RAT(self, expr):\n        return str(expr)\n\n    def _visit_WhileLoop(self, expr, **kwargs):\n        cond = self._visit(expr.condition)\n        body = [self._visit(a) for a in expr.body]\n        return While(cond, body)\n\n    def _visit_IfNode(self, expr, **kwargs):\n        args = []\n        for a in expr.args:\n            cond = self._visit(a[0])\n            body = [self._visit(i) for i in a[1]]\n            args += [(cond, body)]\n        return If(*args)\n    # ....................................................\n    def _visit_Loop(self, expr, **kwargs):\n        # we first create iteration statements\n        # these iterations are splitted between what is tensor or not\n\n        # ... treate tensor iterations\n\n        t_iterator   = [i for i in expr.iterator  if isinstance(i, TensorIterator)]\n        t_generator  = [i for i in expr.generator if isinstance(i, TensorGenerator)]\n        t_iterations = [TensorIteration(i,j)\n                        for i,j in zip(t_iterator, t_generator)]\n\n        indices = list(self._visit(expr.index))\n        starts, stops, lengths = list(self._visit(expr.index.start)), list(self._visit(expr.index.stop)), list(self._visit(expr.index.length))\n\n        for i,j in zip(flatten(indices), flatten(lengths)):\n            self.indices[str(i)] = j\n\n        inits = [()]*self._dim\n        if t_iterations:\n            t_iterations = [self._visit_TensorIteration(i) for i in t_iterations]\n\n            # indices and lengths are supposed to be repeated here\n            # we only take the first occurence\n            for init in t_iterations:\n                for i in range(self._dim):\n                    inits[i] += tuple(init[i])\n\n        # ...\n        # ... treate product iterations\n        p_iterator   = [i for i in expr.iterator  if isinstance(i, ProductIterator)]\n        p_generator  = [i for i in expr.generator if isinstance(i, ProductGenerator)]\n        p_iterations = [ProductIteration(i,j)\n                        for i,j in zip(p_iterator, p_generator)]\n\n        p_inits = []\n        if p_iterations:\n            p_inits = [self._visit_ProductIteration(i) for i in p_iterations]\n        # ...\n\n        # ... add weighted volume if local quadrature loop\n        mapping = self.mapping\n        geo_stmts = expr.get_geometry_stmts(mapping)\n        geo_stmts = self._visit(geo_stmts, **kwargs)\n        # ...\n\n        # ...\n        # visit loop statements\n\n        stmts = self._visit(expr.stmts, **kwargs)\n        stmts = flatten(stmts)\n\n        # update with product statements if available\n        body = list(p_inits) + list(geo_stmts) + list(stmts)\n        mask = expr.mask\n\n        if isinstance(mask,(tuple,Tuple,list)):\n            mask_init = []         \n            for axis,T in enumerate(mask):\n                if T:\n                    indices[axis] = None\n                    starts [axis] = None\n                    stops  [axis] = None\n                    mask_init    += list(inits[axis])\n                    inits[axis]   = None\n            indices = [i for i in indices if i is not None]\n            starts  = [i for i in starts  if i is not None]\n            stops   = [i for i in stops   if i is not None]\n            inits   = [i for i in inits   if i is not None]\n\n        elif mask:\n            axis      = mask.axis\n            index     = indices.pop(axis)\n            start     = starts.pop(axis)\n            stop      = stops.pop(axis)\n            init      = inits.pop(axis)\n            mask_init = [Assign(index, 0), *init]\n\n        if expr.parallel:\n            body = list(flatten(inits)) + body\n            for index, s, e in zip(indices[::-1], starts[::-1], stops[::-1]):\n                body = [For(index, Range(s, e), body)]\n        else:\n            for index, s, e, init in zip(indices[::-1], starts[::-1], stops[::-1], inits[::-1]):\n\n                body = list(init) + body\n                body = [For(index, Range(s, e), body)]\n        # ...\n        # remove the list and return the For Node only\n\n        if mask:\n            body = [*mask_init, *body]\n\n        if expr.parallel:\n            default      = expr.default\n            shared       = [self._visit(i) for i in expr.shared] if expr.shared  else []\n            private      = [self._visit(i) for i in expr.private] if expr.private  else []\n            firstprivate = [self._visit(i) for i in expr.firstprivate] if expr.firstprivate  else []\n            lastprivate  = [self._visit(i) for i in expr.lastprivate] if expr.lastprivate  else []\n            shared       = flatten([list(i.values())[0] if isinstance(i, dict) else i for i in shared])\n            private      = flatten([list(i.values())[0] if isinstance(i, dict) else i for i in private])\n            firstprivate = flatten([list(i.values())[0] if isinstance(i, dict)else i for i in firstprivate])\n            lastprivate  = flatten([list(i.values())[0] if isinstance(i, dict) else i for i in lastprivate])\n            txt          = '#$ omp parallel default({}) &\\n'.format(default)\n            txt         += '#$ shared({}) &\\n'.format(','.join(str(i) for i in shared if i)) if shared else ''\n            txt         += '#$ private({}) &\\n'.format(','.join(str(i) for i in private if i)) if private else ''\n            txt         += '#$ firstprivate({}) &\\n'.format(','.join(str(i) for i in firstprivate if i)) if firstprivate else ''\n            txt         += '#$ lastprivate({})'.format(','.join(str(i) for i in lastprivate if i)) if lastprivate else ''\n            for_pragmas  = '#$ omp for schedule(static) collapse({})'.format(self._dim)\n            if expr.reduction:\n                for_pragmas = for_pragmas + expr.reduction \n\n            cmt          = [Comment(txt.rstrip().rstrip('&')), Comment(for_pragmas)]\n            endcmt       = [Comment('#$ omp end parallel')]\n            body         = [*cmt, *body, *endcmt]\n\n        if len(body) > 1:\n            body = CodeBlock(body)\n        elif len(body) == 1:\n            body = body[0]\n\n        return body\n\n    # ....................................................\n    def _visit_SplitArray(self, expr, **kwargs):\n        target    = expr.target\n        positions = expr.positions\n        lengths   = expr.lengths\n        base      = target.base\n\n        args = []\n        for p,n in zip(positions, lengths):\n            indices = target.indices # sympy is return a tuple of tuples\n            indices = [i for i in indices] # make a copy\n            for i in range(n):\n                indices[p] = i\n                x = base[tuple(indices)]\n                args.append(x)\n        return args\n\n    def _visit_Comment(self, expr, **kwargs):\n        return expr\n\n    # ....................................................\n    def _visit_IndexedElement(self, expr, **kwargs):\n        return expr\n\n    # ....................................................\n    # TODO to be removed. usefull for testing\n    def _visit_Pass(self, expr, **kwargs):\n        return expr\n\n    def _visit_Continue(self, expr, **kwargs):\n        return expr\n\n    def _visit_EmptyNode(self ,expr, **kwargs):\n        return expr\n\n    def _visit_NoneType(self, expr, **kwargs):\n        return expr\n\n\n", "meta": {"hexsha": "3da2808ac8ef1c171f0f88ae8b92139b8c4ea429", "size": 77088, "ext": "py", "lang": "Python", "max_stars_repo_path": "psydac/api/ast/parser.py", "max_stars_repo_name": "mayuri-dhote/psydac", "max_stars_repo_head_hexsha": "01ddbe2d049a599684c45060912d01c2658160a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-03-13T13:50:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-22T14:04:11.000Z", "max_issues_repo_path": "psydac/api/ast/parser.py", "max_issues_repo_name": "mayuri-dhote/psydac", "max_issues_repo_head_hexsha": "01ddbe2d049a599684c45060912d01c2658160a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-02-08T13:29:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-06T17:23:08.000Z", "max_forks_repo_path": "psydac/api/ast/parser.py", "max_forks_repo_name": "mayuri-dhote/psydac", "max_forks_repo_head_hexsha": "01ddbe2d049a599684c45060912d01c2658160a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-12-15T09:55:12.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-15T09:55:12.000Z", "avg_line_length": 37.9931000493, "max_line_length": 181, "alphanum_fraction": 0.5277085928, "include": true, "reason": "import numpy,from sympy", "num_tokens": 17571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.32082131381216084, "lm_q1q2_score": 0.19495130106000555}}
{"text": "#############################################################################\n##Mooring simulator, 2014                                                ####\n##Edited by Arnaud Le Fur, IFREMER                                       ####\n#############################################################################\n\nfrom PyQt4 import QtGui\nimport copy\nimport numpy as np\nfrom math import cos, sin, atan, sqrt\nfrom mySimulateCanvas import MySimulateCanvas\n\n\nclass Simulate_wind(QtGui.QWidget):\n    \"\"\"Classe contenant la fenetre de simulation \"\"\"\n\n    def __init__(self, data, parent=None):\n        \"\"\"initialisation, calcul et affichage des resultats de la simulation\n        Input : data : Tableau reunissant toutes les donnees necessaires a la simulation\n                data[0] : Liste des objets constituants le mouillage\n                data[1] : Les profondeurs et valeurs de courants\n                data[2] : Liste des profondeur fixe des instruments\n                data[3] : Trainee induite par les elements lors de la chute du lest\n                data[4] : Largeur de l ecran\n                data[5] : Chemin du programme\n                data[6] : Liste des ratio de clampage des instruments\n                \"\"\"\n        super(Simulate_wind, self).__init__(parent)\n\n        l_max = 10.  # Longueur max d un element\n        count = 0\n        self.release_ind = 0\n        self.data = data\n        self.table_match = np.zeros(len(self.data[0]))\n\n        # Corrige la saisie de lutilisateur en cas de saisie positive du poids du lest\n        if float(eval(self.data[0][-1].mass)) > 0:\n            self.data[0][-1].mass = str(-1*float(eval(self.data[0][-1].mass)))\n\n        # Calcul l inventaire des elements utilise sur la ligne\n        self.inventory = self.calculate_inventory()\n        # Calcul des profondeurs en statique, sans courant, ni allongement\n        self.static_depth = self.calculate_static()\n        # Calcul du temps, de la vitesse de chute et des tensions max lors de cette chute\n        self.T, self.V_chute_t, self.T_max = self.resolve_max_Tension()\n        self.percent_max_T = []\n        self.weight_kg = []\n        self.old_depth = []\n        # Calcul du poids minimal,ideal,maximal pour le lest\n        self.max_value_anchor = self.Anchor_max_value()\n\n        #Calcul_des_tensions_max/Breaking_strenght#\n        for i in range(len(self.T_max)):\n            if type(self.data[0][i]) != list:\n                if hasattr(self.data[0][i], \"breaking_strength\"):\n                    self.percent_max_T.append(\n                        100*self.T_max[i]/(9.81*eval(self.data[0][i].breaking_strength)))\n                else:\n                    self.percent_max_T.append(0.0)\n                # On recupere egalement le poids de chaque element en kg\n                self.weight_kg.append(eval(self.data[0][i].mass))\n            else:\n                if hasattr(self.data[0][i][0], \"breaking_strength\"):\n                    self.percent_max_T.append(\n                        100*self.T_max[i]/(9.81*eval(self.data[0][i][0].breaking_strength)))\n                else:\n                    self.percent_max_T.append(0.0)\n                self.weight_kg.append(\n                    eval(self.data[0][i][0].mass)+eval(self.data[0][i][1].mass))\n\n        # On calcul la flottabilite en cas de rupture de la partie superieure en kg\n        self.get_buoyancy_kg()\n\n        # On met en place une table de correspondance entre la ligne dorigine et la ligne decoupee en troncon\n        for i in range(len(self.data[0])):\n            self.table_match[i] = i+count\n            if type(self.data[0][i]) != list:\n                if eval(self.data[0][i].length) > l_max:\n                    coeff = round(eval(self.data[0][i].length)/l_max)\n                    count = count+coeff-1\n            else:\n                if eval(self.data[0][i][0].length) > l_max:\n                    coeff = round(eval(self.data[0][i][0].length)/l_max)\n                    count = count+coeff-1\n\n        i = 0\n        # On decoupe les cables en troncon de longueur minimale : cable de 100m = 10 x cable de 10 m\n        while i < len(self.data[0]):\n            if type(self.data[0][i]) != list:\n                if eval(self.data[0][i].length) > l_max:\n                    #on met a jour le poids, la longueur, et la surface#\n                    coeff = round(eval(self.data[0][i].length)/l_max)\n                    new_length = str(eval(self.data[0][i].length)/coeff)\n                    new_mass = str(eval(self.data[0][i].mass)/coeff)\n                    new_projected_area = str(\n                        eval(self.data[0][i].projected_area)/coeff)\n                    self.data[0][i].length = new_length\n                    self.data[0][i].mass = new_mass\n                    self.data[0][i].projected_area = new_projected_area\n\n                    # on ajoute le nouveau troncon en position i+1\n                    for j in range(int(coeff)-1):\n                        self.data[0].insert(\n                            i+1, copy.deepcopy(self.data[0][i]))\n                        self.data[2].insert(i+1, 0)\n\n            else:  # Element clampes\n                if eval(self.data[0][i][0].length) > l_max:\n                    coeff = round(eval(self.data[0][i][0].length)/l_max)\n                    new_length = str(eval(self.data[0][i][0].length)/coeff)\n                    new_mass = str(eval(self.data[0][i][0].mass)/coeff)\n                    new_projected_area = str(\n                        eval(self.data[0][i][0].projected_area)/coeff)\n                    self.data[0][i][0].length = new_length\n                    self.data[0][i][0].mass = new_mass\n                    self.data[0][i][0].projected_area = new_projected_area\n                    count = 0\n                    for j in range(int(coeff)-1):\n                        self.data[0].insert(\n                            i+1, copy.deepcopy(self.data[0][i][0]))\n                        self.data[2].insert(i+1, 0)\n                        count = count+1\n            i = i+1\n\n        self.depth = self.make_vector()  # Initialisation du vecteur profondeur\n        self.current_vector(self.depth)  # Initialisation du vecteur de courant\n        alpha, F, P = self.resolve()  # Resolution du systeme\n        self.calculate_stretch(F)  # Calcul des allongements\n        self.calculate_ratio(alpha)  # Calcul des ratios de clampage\n        self.plot_figure(alpha, P, F)  # Plot des 4 graphiques de la simulation\n        # Genere le tableau recapitulatif de la simulation\n        self.make_table(alpha, F)\n\n    def calculate_inventory(self):\n        \"\"\"Cette fonction permet de retourner un tableau contenant la liste des elements,longueurs et le nombre dutilisation\n        Output : Result : Tableau contenant l inventaire\"\"\"\n        inventory_name = []\n        inventory_length = []\n        Result = [[\"Name\", \"Length (m) / Number\"]]\n        #On recupere d abord tout les noms des elements#\n        for i in range(len(self.data[0])):\n            if type(self.data[0][i]) != list:\n                if not(self.data[0][i].name) in inventory_name:\n                    inventory_name.append(self.data[0][i].name)\n                    inventory_length.append(0)\n            else:\n                if not(self.data[0][i][0].name) in inventory_name:\n                    inventory_name.append(self.data[0][i][0].name)\n                    inventory_length.append(0)\n                if not(self.data[0][i][1].name) in inventory_name:\n                    inventory_name.append(self.data[0][i][1].name)\n                    inventory_length.append(0)\n        #On incremente ensuite soit son nombre dutilisation soit la longueur si c est un cable#\n        for i in range(len(self.data[0])):\n            if type(self.data[0][i]) != list:\n                ind = inventory_name.index(self.data[0][i].name)\n                if self.data[0][i].__class__.__name__ == \"Ropes\":\n                    inventory_length[ind] = inventory_length[ind] + \\\n                        eval(self.data[0][i].length)\n                else:\n                    inventory_length[ind] = inventory_length[ind]+1\n            else:  # Elements clampes\n                ind = inventory_name.index(self.data[0][i][0].name)\n                if self.data[0][i][0].__class__.__name__ == \"Ropes\":\n                    inventory_length[ind] = inventory_length[ind] + \\\n                        eval(self.data[0][i][0].length)\n                else:\n                    inventory_length[ind] = inventory_length[ind]+1\n                ind = inventory_name.index(self.data[0][i][1].name)\n                if self.data[0][i][1].__class__.__name__ == \"Ropes\":\n                    inventory_length[ind] = inventory_length[ind] + \\\n                        eval(self.data[0][i][1].length)\n                else:\n                    inventory_length[ind] = inventory_length[ind]+1\n        for i in range(len(inventory_name)):\n            Result.append([inventory_name[i], inventory_length[i]])\n        return Result\n\n    def calculate_static(self):\n        \"\"\"Cette fonction permet de sauvegarder les longueurs d origines et retourne un vecteur avec les profondeurs(en haut de l element) \n        en statique : sans allongement ni courant\n        Output : subduct : vecteur de profondeur statique\"\"\"\n        subduct = [self.data[1][1][-1]+eval(self.data[0][-1].length)]\n        self.original_length = []\n        for b in self.data[0]:\n            if type(b) != list:\n                self.original_length.append(round(eval(b.length), 1))\n            else:\n                self.original_length.append(\n                    [round(eval(b[0].length), 1), round(eval(b[1].length), 1)])\n\n        for i in range(2, len(self.data[0])+1):\n\n            if type(self.data[0][-i]) != list:\n                subduct.insert(0, subduct[0]+eval(self.data[0][-i].length))\n            else:\n                subduct.insert(0, subduct[0]+eval(self.data[0][-i][0].length))\n        return subduct\n\n    def resolve_max_Tension(self):\n        \"\"\"Cette fonction permet de calculer la vitesse, le temps de chute et les tensions maximales lors de cette chute \n        Output : T : Vecteur temps\n                V_chute_t : Vecteur vitesse de chute en fonction du temps\n                T_max : Tension max pour chaque element \"\"\"\n\n        Tension = []\n        T_max = []\n        g = 9.81\n        h = 0\n        T = [0]\n        t = 0.\n        mass_lest = eval(self.data[0][-1].mass)\n        floor_depth = abs(self.data[1][1][len(self.data[1][0])-1])\n        #Calcul de la flottabilite#\n        for i in range(len(self.data[0])):\n            Tension.append(0)\n            for j in range(i+1):\n                if j == len(self.data[0]):\n                    break\n                else:\n                    if type(self.data[0][j]) != list:\n                        Tension[i] = Tension[i]+g*eval(self.data[0][j].mass)\n                    else:\n                        Tension[i] = Tension[i]+g * \\\n                            (eval(self.data[0][j][0].mass) +\n                            eval(self.data[0][j][1].mass))\n\n        # Trainee induite par les elements superieures au lest\n        a = (self.data[3][-1])/(-mass_lest)\n        b = g-(Tension[-2]/(-mass_lest))  # Tension au niveau du lest\n        if b > 0:\n            i = 0\n            cond = 0\n            t = 0.1\n            Time = 0.\n            V_chute_t = [0]\n            while cond == 0:\n                # Evaluation de la variation de la vitesse de chute en fonction du temps cf L.MARIE\n                Time = Time+t\n                T.append(Time)\n                V_chute_t.append((b-a*V_chute_t[-1]**2)*t+V_chute_t[-1])\n                h = h+V_chute_t[i]*t\n                if h >= floor_depth:  # On touche le fond\n                    cond = 1\n                i = i+1\n\n            v_chute = V_chute_t[-1]  # Vitesse en regime permanent\n            for i in range(len(Tension)):\n                T_max.append(0)\n                # Calcul des Tensions max\n                T_max[i] = (self.data[3][i]*(v_chute**2)+Tension[i])\n            T_max[-1] = 0.0\n            return T, V_chute_t, T_max\n        else:\n            QtGui.QMessageBox.warning(\n                self, 'Message', \"Your Anchor is too light\")\n\n    def Anchor_max_value(self):\n        \"\"\"Cette fonction permet de calculer quel est le poids maximal du lest qui entraine une Tension max \n        egale a la charge de rupture \n        Output : masse maximale\"\"\"\n        vec_v_chute = []\n        Tension = []\n        g = 9.81\n        #Calcul de la flottabilite#\n        for i in range(len(self.data[0])):\n            Tension.append(0)\n            for j in range(i+1):\n                if j == len(self.data[0]):\n                    break\n                else:\n                    if type(self.data[0][j]) != list:\n                        Tension[i] = Tension[i]+g*eval(self.data[0][j].mass)\n                    else:\n                        Tension[i] = Tension[i]+g * \\\n                            (eval(self.data[0][j][0].mass) +\n                            eval(self.data[0][j][1].mass))\n        #On evalue la vitesse de chute maximale que supporte les elements du mouillage, depend de leur charge de rupture#\n        for i in range(len(self.data[0])):\n            if type(self.data[0][i]) != list:\n                if hasattr(self.data[0][i], \"breaking_strength\"):\n                    v_chute = sqrt(\n                        (eval(self.data[0][i].breaking_strength)*g-Tension[i])/(self.data[3][i]))\n                    vec_v_chute.append(v_chute)\n            else:\n                if hasattr(self.data[0][i][0], \"breaking_strength\"):\n                    v_chute = sqrt(\n                        (eval(self.data[0][i][0].breaking_strength)*g-Tension[i])/(self.data[3][i]))\n                    vec_v_chute.append(v_chute)\n\n        # On prend l element qui supporte la vitesse de chute la plus petite, cas le plus defavorable\n        mass_max = (Tension[-2]+self.data[3][-1]*(min(vec_v_chute))**2)/g\n        return mass_max\n\n    def get_buoyancy_kg(self):\n        \"\"\"Cette fonction permet de calculer la flottabilite restante en cas de sectionnement de la partie superieure en kg \"\"\"\n        release_ind = 0\n        for i in range(len(self.data[0])):\n            # On recupere l indice du largueur car ce calcule nest pas pertinent en dessous de celui-ci\n            if(self.data[0][i].__class__.__name__) == \"Releases\":\n                release_ind = i\n        self.Buoyancy_kg = [self.weight_kg[release_ind]]\n        for i in reversed(range(release_ind)):\n            self.Buoyancy_kg.insert(0, self.Buoyancy_kg[0]+self.weight_kg[i])\n        while len(self.Buoyancy_kg) != len(self.weight_kg):\n            self.Buoyancy_kg.append(0.0)\n\n    def make_vector(self):\n        \"\"\"Cette fonction permet de calculer la profondeur de chaque element(en son centre) \n        Output : depth : vecteur profondeur\"\"\"\n        depth = [self.data[1][1][len(self.data[1][0])-1]]\n\n        #Calcul de la profondeur en haut de l element#\n        for i in range(2, len(self.data[0])+2):\n            depth.insert(0, 0)\n            if type(self.data[0][-i+1]) != list:\n                depth[-i] = depth[-i+1]+eval(self.data[0][-i+1].length)\n            else:\n                depth[-i] = depth[-i+1]+eval(self.data[0][-i+1][0].length)\n        depth.remove(self.data[1][1][len(self.data[1][0])-1])\n        #On enleve la moitie pour obtenir la profondeur du milieu de lelement#\n        for i in range(len(self.data[0])):\n            if type(self.data[0][i]) != list:\n                depth[i] = depth[i]-eval(self.data[0][i].length)/2\n            else:\n                depth[i] = depth[i]-eval(self.data[0][i][0].length)/2\n        return depth\n\n    def current_vector(self, depth):\n        \"\"\"Cette fonction permet dobtenir une valeur de courant par interpolation pour chaque profondeur du vecteur depth \n        Input : Vecteur profondeur\n        Output : Vecteur courant \"\"\"\n        current_vector = []\n        # On interpole lineairement, on calcul donc les coefficients k et b de la droite y=k*x+b\n        for i in range(len(depth)):\n            a = 0\n\n            while(depth[i] < self.data[1][1][a]):\n                a = a+1\n            k = (self.data[1][0][a-1]-self.data[1][0][a]) / \\\n                (self.data[1][1][a-1]-self.data[1][1][a])\n            b = self.data[1][0][a-1]-k*self.data[1][1][a-1]\n            current_vector.append(k*depth[i]+b)\n\n        return current_vector\n\n    def update_depth(self, depth, alpha):\n        \"\"\"Cette fonction permet de mettre a jour le vecteur profondeur en fonction de l inclinaison de la ligne \n        Input : depth : vecteur profondeur d origine\n                alpha : vecteur angle \n        Output : depth : vecteur profondeur mis a jour\"\"\"\n        depth = [self.data[1][1][len(self.data[1][0])-1]]\n\n        #Calcul de la profondeur en haut de l element#\n        for i in range(2, len(self.data[0])+2):\n            depth.insert(0, 0)\n            if type(self.data[0][-i+1]) != list:\n                depth[-i] = depth[-i+1] + \\\n                    cos(alpha[-i+1])*eval(self.data[0][-i+1].length)\n            else:\n                depth[-i] = depth[-i+1] + \\\n                    cos(alpha[-i+1])*eval(self.data[0][-i+1][0].length)\n        depth.remove(self.data[1][1][len(self.data[1][0])-1])\n\n        #Calcul de la profondeur au milieu de l element#\n        for i in range(len(self.data[0])):\n            if type(self.data[0][i]) != list:\n                depth[i] = depth[i]-cos(alpha[i]) * \\\n                    eval(self.data[0][i].length)/2\n            else:\n                depth[i] = depth[i]-cos(alpha[i]) * \\\n                    eval(self.data[0][i][0].length)/2\n\n        return depth\n\n    def resolve(self):\n        \"\"\"Resolution du comportement de la ligne de mouillage \n        Output : F : Effort sur chaque element\n                alpha : Inclinaison\n                P : Poids en newton\n        \"\"\"\n        alpha = []\n        alpha_new = []\n        Fx = []\n        Fy = []\n        F = []\n        Tn = []\n        Tt = []\n        P = []\n        new_depth = []\n        rho = 1028\n        cond = 1\n        fact_convergence = 1\n        it = 0\n        g = 9.81\n        for i in range(len(self.depth)):\n            alpha.append(0)\n            alpha_new.append(0)\n            Fx.append(0)\n            Fy.append(0)\n            Tn.append(0)\n            Tt.append(0)\n            F.append(0)\n            new_depth.append(self.depth[i])  # Vecteur initialise precedemment\n            #Calculate Weight#\n            if type(self.data[0][i]) != list:\n                P.append(eval(self.data[0][i].mass)*g)\n            else:\n                inter = [eval(self.data[0][i][0].mass)*g,\n                        eval(self.data[0][i][1].mass)*g]\n                P.append(inter)\n\n        while (cond == 1):  # Tant que le systeme nest pas stable\n            it = it+1\n            for i in range(len(alpha)):  # On met a jour la valeur de alpha\n                alpha[i] = alpha_new[i]\n            # On met a jour le vecteur profondeur\n            new_depth = self.update_depth(new_depth, alpha)\n            # On met a jour le vecteur de courant\n            V = self.current_vector(new_depth)\n            #On commence par la tete de mouillage#\n            Tn[0] = 0.5*rho*eval(self.data[0][0].nl_drag_cf)*eval(self.data[0]\n                                                                [0].projected_area)*(V[0]*cos(alpha[0]))**2  # Calcul trainee normal\n            Tt[0] = 0.5*rho*eval(self.data[0][0].tl_drag_cf)*eval(self.data[0]\n                                                                [0].projected_area)*(V[0]*sin(alpha[0]))**2  # Calcul trainee tangentielle\n            Fx[0] = Tn[0]*cos(alpha[0])+Tt[0] * \\\n                sin(alpha[0])  # Resultante selon x\n            Fy[0] = Tt[0]*cos(alpha[0])-Tn[0]*sin(alpha[0]) + \\\n                P[0]  # Resultante selon y\n            alpha_new[0] = atan(Fx[0]/Fy[0])  # Angle\n            F[0] = sqrt(Fx[0]**2+Fy[0]**2)  # Norme\n            #On calcule element par element en partant du haut#\n            for i in range(1, len(self.depth)-1):\n                if type(self.data[0][i]) != list:\n                    Tn[i] = 0.5*rho*eval(self.data[0][i].nl_drag_cf)*eval(\n                        self.data[0][i].projected_area)*(V[i]*cos(alpha[i]))**2  # Calcul trainee normal\n                    Tt[i] = 0.5*rho*eval(self.data[0][i].tl_drag_cf)*eval(self.data[0][i].projected_area)*(\n                        V[i]*sin(alpha[i]))**2  # Calcul trainee tangentielle\n                    Fx[i] = Tn[i]*cos(alpha[i])+Tt[i] * \\\n                        sin(alpha[i])+Fx[i-1]  # Resultante selon x\n                    Fy[i] = Tt[i]*cos(alpha[i])-Tn[i]*sin(alpha[i]) + \\\n                        P[i]+Fy[i-1]  # Resultante selon y\n                    alpha_new[i] = fact_convergence*atan(Fx[i]/Fy[i])  # Angle\n                    F[i] = sqrt(Fx[i]**2+Fy[i]**2)  # Norme\n                #ELement clampe#\n                else:\n\n                    Tn[i] = 0.5*rho*(V[i]*cos(alpha[i])**2)*(eval(self.data[0][i][0].nl_drag_cf)*eval(self.data[0][i][0].projected_area) +  # Calcul trainee normal\n                                                            eval(self.data[0][i][1].nl_drag_cf)*eval(self.data[0][i][1].projected_area))\n\n                    Tt[i] = 0.5*rho*(V[i]*sin(alpha[i])**2)*(eval(self.data[0][i][0].tl_drag_cf)*eval(self.data[0][i][0].projected_area) +  # Calcul trainee tangentielle\n                                                            eval(self.data[0][i][1].tl_drag_cf)*eval(self.data[0][i][1].projected_area))\n\n                    Fx[i] = Tn[i]*cos(alpha[i])+Tt[i] * \\\n                        sin(alpha[i])+Fx[i-1]  # Resultante selon x\n                    Fy[i] = Tt[i]*cos(alpha[i])-Tn[i]*sin(alpha[i]) + \\\n                        P[i][0]+P[i][1]+Fy[i-1]  # Resultante selon y\n                    alpha_new[i] = fact_convergence*atan(Fx[i]/Fy[i])  # Angle\n                    F[i] = sqrt(Fx[i]**2+Fy[i]**2)  # Norme\n\n            cond = 0\n\n            for i in range(len(self.depth)):  # Condition d arret\n                if abs(alpha[i]-alpha_new[i]) > 0.0001:\n                    cond = 1\n                    break\n\n        return alpha, F, P\n\n    def calculate_stretch(self, F):\n        \"\"\"Cette fonction permet de calculer l allongement dun cable en fonction de leffort qui lui est applique\n        Input : F : Effort subit par le cable \"\"\"\n        new_stretch = 0\n        self.percent_stretch = []\n        for i in range(len(self.data[0])):\n            new_stretch = 0\n            if type(self.data[0][i]) != list:\n                if self.data[0][i].__class__.__name__ == \"Ropes\":\n                    # On calcule  le pourcentage de la charge de rupture qui est applique au cable\n                    ratio = 100/9.81 * \\\n                        (F[i]/eval(self.data[0][i].breaking_strength))\n                    new_stretch = (round(eval(self.data[0][i].poly_1), 2)*ratio**2+round(eval(\n                        self.data[0][i].poly_2), 2)*ratio+round(eval(self.data[0][i].poly_3), 2))/100\n                    # En fonction des 3 coefficients polynomiales entre pour le materiau on calcul lallongement : allongement (%) = coeff1*(%Charge de rupture)^2+coeff2*(%Charge de rupture)+coeff3\n                    # On met a jour la nouvelle longueur\n                    self.data[0][i].length = str(\n                        eval(self.data[0][i].length)*(1+new_stretch))\n            #Element clampe#\n            else:\n                if self.data[0][i][0].__class__.__name__ == \"Ropes\":\n                    ratio = 100/9.81 * \\\n                        (F[i]/eval(self.data[0][i][0].breaking_strength))\n                    new_stretch = (round(eval(self.data[0][i][0].poly_1), 2)*ratio**2+round(eval(\n                        self.data[0][i][0].poly_2), 2)*ratio+round(eval(self.data[0][i][0].poly_3), 2))/100\n                    self.data[0][i][0].length = str(\n                        eval(self.data[0][i][0].length)*(1+new_stretch))\n            self.percent_stretch.append(100*new_stretch)\n\n    def calculate_ratio(self, alpha):\n        \"\"\"Cette fonction permet de calculer le ratio de clampage definie par lutilisateur comme automatique \n        Input : alpha : vecteur angle d inclinaison\"\"\"\n\n        #Calcul des coordonnees x et y en fonction de l inclinaison#\n        y_float = [self.data[1][1][len(self.data[1][0])-1]]\n        for i in range(len(self.data[2])):\n            if type(self.data[2][i]) != list:\n                if self.data[2][i] > 0:\n                    self.data[2][i] = self.data[2][i]+y_float[-1]\n            else:\n                if self.data[2][i][1] > 0:\n                    self.data[2][i][1] = self.data[2][i][1]+y_float[-1]\n\n        x_float = [0]\n        for i in range(2, len(self.data[0])+2):\n            y_float.insert(0, 0)\n            x_float.insert(0, 0)\n            if type(self.data[0][-i+1]) != list:\n                y_float[-i] = y_float[-i+1] + \\\n                    cos(alpha[-i+1])*eval(self.data[0][-i+1].length)\n                x_float[-i] = x_float[-i+1] + \\\n                    sin(alpha[-i+1])*eval(self.data[0][-i+1].length)\n            else:\n                y_float[-i] = y_float[-i+1] + \\\n                    cos(alpha[-i+1])*eval(self.data[0][-i+1][0].length)\n                x_float[-i] = x_float[-i+1] + \\\n                    sin(alpha[-i+1])*eval(self.data[0][-i+1][0].length)\n        y_float.remove(self.data[1][1][len(self.data[1][0])-1])\n        x_float.remove(x_float[-1])\n        self.myxfloat = x_float\n        self.myyfloat = y_float\n        # Coordonnee x de la bouee de tete\n        self.x_instru = [x_float[0] -\n                        sin(alpha[0])*eval(self.data[0][0].length)/2]\n        # Coordonnee y de la bouee de tete\n        self.y_instru = [y_float[0] -\n                        cos(alpha[0])*eval(self.data[0][0].length)/2]\n        self.x_instru_top = []\n        self.y_instru_top = []\n        self.name_instru = [self.data[0][0].name]  # Nom de la bouee de tete\n        for i in range(len(self.data[6])):\n            if self.data[6][i] == 0.0:  # Ratio defini comme auto\n                calc = 0\n                # Si la profondeur choisi par lutilisateur est plus haut que le support de clampage\n                if self.data[2][self.find_match(i)][1] > self.myyfloat[self.find_match(i)]:\n                    # le ratio est fixe au minimum c est a dire 0\n                    self.data[6][i] = 0\n                    calc = 1\n                # Si la profondeur choisi par lutilisateur est plus basse que le support de clampage\n                if self.data[2][self.find_match(i)][1] < self.myyfloat[self.find_match(i+1)]:\n                    # le ratio est fixe au minimum c est a dire 1\n                    self.data[6][i] = 1\n                    calc = 1\n                if calc == 0:\n                    malongueur = eval(\n                        self.data[0][self.find_match(i)][0].length)\n                    lon = 0\n                    p = 1\n                    for j in range(int(self.table_match[i])+1, int(self.table_match[i+1])):\n                        malongueur = malongueur+eval(self.data[0][j].length)\n                    while(self.myyfloat[self.find_match(i)+p] > self.data[2][self.find_match(i)][1]):\n                        if type(self.data[0][self.find_match(i)+p-1]) != list:\n                            lon = lon + \\\n                                eval(self.data[0]\n                                    [self.find_match(i)+p-1].length)\n                        else:\n                            lon = lon + \\\n                                eval(\n                                    self.data[0][self.find_match(i)+p-1][0].length)\n                        p = p+1\n                    ratio = ((self.myyfloat[self.find_match(i)+p-1]-self.data[2][self.find_match(i)][1])/(cos(alpha[self.find_match(i)+p-1]))\n                            + 0.5*eval(self.data[0][self.find_match(i)][1].length)+lon)/malongueur\n                    self.data[6][i] = ratio\n\n                if self.data[6][i] >= 1 or self.data[6][i] <= 0:\n                    QtGui.QMessageBox.warning(\n                        self, 'Message', \"An instrument is clamped beyond it support\")\n\n        #Calcul de la profondeur des instruments#\n        for i in range(len(self.data[6])):\n            if type(self.data[0][self.find_match(i)]) != list:\n                if (self.data[0][self.find_match(i)]).__class__.__name__ == \"Instruments\":\n                    self.name_instru.append(\n                        self.data[0][self.find_match(i)].name)\n                    self.x_instru.append(self.myxfloat[self.find_match(\n                        i)]-0.5*eval(self.data[0][self.find_match(i)].length)*sin(alpha[self.find_match(i)]))\n                    self.y_instru.append(self.myyfloat[self.find_match(\n                        i)]-0.5*eval(self.data[0][self.find_match(i)].length)*cos(alpha[self.find_match(i)]))\n                    # coordonnee x en haut de l instrument\n                    self.x_instru_top.append(self.myxfloat[self.find_match(i)])\n                    # coordonnee y en haut de l instrument\n                    self.y_instru_top.append(self.myyfloat[self.find_match(i)])\n        #Element clampe#\n            else:\n                if (self.data[0][self.find_match(i)][1]).__class__.__name__ == \"Instruments\":\n                    self.name_instru.append(\n                        self.data[0][self.find_match(i)][1].name)\n                    malongueur = eval(\n                        self.data[0][self.find_match(i)][0].length)\n                    lon = eval(self.data[0][self.find_match(i)][0].length)\n                    lon2 = lon\n                    p = 0\n                    ratio = self.data[6][i]\n                    for j in range(int(self.table_match[i])+1, int(self.table_match[i+1])):\n                        malongueur = malongueur+eval(self.data[0][j].length)\n                    while(lon < malongueur*self.data[6][i]):\n                        ratio = ratio-lon2/malongueur\n                        p = p+1\n                        lon = lon + \\\n                            eval(self.data[0]\n                                [int(self.table_match[i])+p].length)\n                        lon2 = eval(\n                            self.data[0][int(self.table_match[i])+p].length)\n\n                    self.x_instru.append(self.myxfloat[self.find_match(\n                        i)+p]-ratio*malongueur*sin(alpha[self.find_match(i)+p]))\n                    self.y_instru.append(self.myyfloat[self.find_match(\n                        i)+p]-ratio*malongueur*cos(alpha[self.find_match(i)+p]))\n                    self.x_instru_top.append(self.myxfloat[self.find_match(i)+p]-(ratio*malongueur-0.5*eval(\n                        self.data[0][self.find_match(i)][1].length))*sin(alpha[self.find_match(i)+p]))  # coordonnee x en haut de l instrument\n                    self.y_instru_top.append(self.myyfloat[self.find_match(i)+p]-(ratio*malongueur-0.5*eval(\n                        self.data[0][self.find_match(i)][1].length))*cos(alpha[self.find_match(i)+p]))  # coordonnee y en haut de l instrument\n\n    def calculate_subduction(self):\n        \"\"\"Cette fonction permet de calculer la subduction entrainee par le courant et les allongements \n        Output : vecteur subduct \"\"\"\n        subduct = []\n        for i in range(len(self.static_depth)):\n            subduct.append(self.static_depth[i]-self.myyfloat[i])\n        return subduct\n\n    def find_match(self, ind):\n        \"\"\"Cette fonction utilise la table de correspondance \n        Input : Indice sans troncon de cable\n        Output : Indice avec troncon\"\"\"\n        return int(self.table_match[ind])\n\n    def resolve_backup(self, P):\n        \"\"\"Cette fonction permet de resoudre le backup jusqu au largueurs \n        Input : poids en newton \n        Output : backup,zero de flottabilite\"\"\"\n        result2 = []\n        zero = []\n        for i in range(len(self.data[0])):\n            if(self.data[0][i].__class__.__name__) == \"Releases\":\n                self.release_ind = i+1\n\n        for i in range(self.release_ind):\n            result = 0\n            for j in range(i, self.release_ind):\n                if type(P[j]) != list:\n                    result = result+P[j]\n                else:\n                    result = result+P[j][0]+P[j][1]\n            result2.append(result)\n        for i in range(len(result2)):\n            zero.append(0)\n        return result2, zero\n\n    def plot_figure(self, alpha, P, F):\n        \"\"\"Cette fonction permet de tracer les quatres graphes \n        Input : alpha : angle d inclinaison\n                : P : Poids\n                F : Effort\n                \"\"\"\n\n        if hasattr(self, \"plot_mooring\"):\n            self.plot_mooring.hide()\n\n        backup, zero = self.resolve_backup(P)\n\n        for i in range(len(self.T_max)):\n            self.old_depth.append(self.myyfloat[self.find_match(i)])\n\n        self.groupLayout = QtGui.QVBoxLayout()\n        self.scrollArea = QtGui.QScrollArea()\n        self.groupLayout.addWidget(self.scrollArea)\n        self.scrolledWidget = QtGui.QWidget()  # Zone de defilement verticale\n        self.scrolledWidget.setMinimumWidth(self.data[4])\n        self.layout = QtGui.QVBoxLayout(self.scrolledWidget)\n\n        self.widget_graph = QtGui.QWidget(self)\n\n        sc1 = MySimulateCanvas(self.myxfloat, self.myyfloat, backup, self.T_max, self.T,\n                            self.old_depth, self.V_chute_t, self.release_ind, self.name_instru,\n                            self.x_instru, self.y_instru, self.data[5], self.widget_graph)\n        self.layout.addWidget(sc1)\n        min_value_anchor = F[-2]/9.81  # Valeur minimale lest\n        # Valeur safe lest formule visbeck runmoor\n        safe_value_anchor = (1.5/9.81) * \\\n            (F[-2]*(cos(alpha[-2])+0.6*sin(alpha[-2])))\n        self.anchor_value = [round(safe_value_anchor, 1), -1*round(\n            float(self.data[0][-1].mass), 1), round(max(self.percent_max_T), 1)]\n        #Affichage valeurs lest#\n        self.widget_anchors = QtGui.QWidget(self)\n        self.anchors_layout = QtGui.QGridLayout()\n        label1 = QtGui.QLabel(\"Anchors's WET weight (kg)\")\n        label1.setStyleSheet(\n            \"QLabel { background-color : white; color : black;border: 2px solid black }\")\n        label2 = QtGui.QLabel(\"Min\")\n        label2.setStyleSheet(\n            \"QLabel { background-color : white; color : black;border: 2px solid black }\")\n        label3 = QtGui.QLabel(\"Max\")\n        label3.setStyleSheet(\n            \"QLabel { background-color : white; color : black;border: 2px solid black }\")\n        label4 = QtGui.QLabel(str(round(min_value_anchor, 1)))\n        label4.setStyleSheet(\n            \"QLabel { background-color : white; color : black;border: 1px solid black }\")\n        label5 = QtGui.QLabel(str(round(self.max_value_anchor, 1)))\n        label5.setStyleSheet(\n            \"QLabel { background-color : white; color : black;border: 1px solid black }\")\n        label6 = QtGui.QLabel(\"Safe Anchor's weight\")\n        label6.setStyleSheet(\n            \"QLabel { background-color : white; color : black;border: 2px solid black }\")\n        label7 = QtGui.QLabel(\"Selected Anchor's weight\")\n        label7.setStyleSheet(\n            \"QLabel { background-color : white; color : black;border: 2px solid black }\")\n        label8 = QtGui.QLabel(str(self.anchor_value[0]))\n        label8.setStyleSheet(\n            \"QLabel { background-color : white; color : black;border: 1px solid black }\")\n        label9 = QtGui.QLabel(str(self.anchor_value[1]))\n        # Valeur choisie < valeur recommande\n        if self.anchor_value[1] < self.anchor_value[0]:\n            label9.setStyleSheet(\n                \"QLabel { background-color : red; color : white ;border: 2px solid black }\")\n        else:\n            label9.setStyleSheet(\n                \"QLabel { background-color : green; color : white;border: 1px solid black }\")\n\n        label10 = QtGui.QLabel(\"Max Launch Tension / Breaking Strength (%)\")\n        label10.setStyleSheet(\n            \"QLabel { background-color : white; color : black;border: 2px solid black }\")\n        label11 = QtGui.QLabel(str(self.anchor_value[2]))\n        if round(max(self.percent_max_T), 1) > 40:  # T_max/Ultimate_load >40%\n            label11.setStyleSheet(\n                \"QLabel { background-color : red; color : white ;border: 2px solid black }\")\n        else:\n            label11.setStyleSheet(\n                \"QLabel { background-color : green; color : white;border: 1px solid black }\")\n\n        self.anchors_layout.addWidget(label2, 0, 1)\n        self.anchors_layout.addWidget(label3, 0, 3)\n        self.anchors_layout.addWidget(label1, 1, 0)\n        self.anchors_layout.addWidget(label4, 1, 1)\n        self.anchors_layout.addWidget(label5, 1, 3)\n        self.anchors_layout.addWidget(label6, 0, 2)\n        self.anchors_layout.addWidget(label7, 0, 4)\n        self.anchors_layout.addWidget(label8, 1, 2)\n        self.anchors_layout.addWidget(label9, 1, 4)\n        self.anchors_layout.addWidget(label10, 2, 0)\n        self.anchors_layout.addWidget(label11, 2, 1)\n\n        self.widget_anchors.setLayout(self.anchors_layout)\n        self.layout.addWidget(self.widget_anchors)\n\n    def make_table(self, alpha, F):\n        \"\"\"Cette fonction permet de creer le tableau qui contient toutes les informations de la simulation\n        Input : alpha : Vecteur angle d inclinaison\n                F : Vecteur effort \"\"\"\n        name = []\n        length = []\n        length_stretch = []\n        Tab_final = []\n        self.Tab_report = []\n        ind_instrum = []\n        my_prof = []\n        F_Kp = []\n        warn = []\n        count = 0\n        release_ind = 0\n        #Reconstitue les troncons en un seul cable#\n        for i in range(len(self.table_match)):\n            for j in range(i, int(self.table_match[i])-count):\n                if type(self.data[0][i-1]) != list:\n                    self.data[0][i-1].length = str(\n                        eval(self.data[0][i-1].length)+eval(self.data[0][i].length))\n                    self.data[0][i-1].mass = str(eval(self.data[0]\n                                                    [i-1].mass)+eval(self.data[0][i].mass))\n                    self.data[0][i-1].projected_area = str(\n                        eval(self.data[0][i-1].projected_area)+eval(self.data[0][i].projected_area))\n                else:\n                    self.data[0][i-1][0].length = str(\n                        eval(self.data[0][i-1][0].length)+eval(self.data[0][i].length))\n                    self.data[0][i-1][0].mass = str(\n                        eval(self.data[0][i-1][0].mass)+eval(self.data[0][i].mass))\n                    self.data[0][i-1][0].projected_area = str(\n                        eval(self.data[0][i-1][0].projected_area)+eval(self.data[0][i].projected_area))\n                del(self.data[0][i])\n                del(alpha[i])\n                del(F[i])\n                del(self.myxfloat[i])\n                del(self.myyfloat[i])\n                del(self.percent_stretch[i])\n                count = count+1\n\n        size = len(self.data[0])-1\n        for i in range(len(alpha)):\n            alpha[i] = alpha[i]*(180/(3.14))  # Converti radian en degre\n\n        subduct = self.calculate_subduction()  # Calcule de la subduction\n\n        for p in self.data[0]:\n            if type(p) != list:\n                name.append(p.name)\n            else:\n                # Recuperation des noms\n                name.append(p[0].name+' '+'+'+' '+p[1].name)\n\n        count = 0\n        for i in range(len(self.data[0])):\n\n            F_Kp.append(F[i]/9.81)  # Convertion des efforts en Kp\n            if type(self.data[0][i]) != list:\n                length.append(self.original_length[i])\n                my_prof.append(str(round(self.myyfloat[i], 1)))\n                # Detection des instruments\n                if self.data[0][i].__class__.__name__ == \"Instruments\":\n                    ind_instrum.append(i)\n                    count = count+1\n                if self.data[0][i].__class__.__name__ == \"Releases\":  # Detection du release\n                    release_ind = i\n\n                if self.data[0][i].__class__.__name__ == \"Ropes\":\n                    length_stretch.append(str(round(eval(self.data[0][i].length), 1))+' '+'('+str(\n                        round(self.percent_stretch[i], 1))+'%'+')')  # Recuperation des longueurs allongees\n                else:\n                    length_stretch.append('')\n\n            #Element clampe#\n            else:\n                length.append(self.original_length[i][0])\n                if self.data[0][i][1].__class__.__name__ == \"Instruments\":\n                    ind_instrum.append(i)\n                    my_prof.append(str(round(self.myyfloat[i], 1))+' '+'+'+' '+str(round(self.y_instru_top[count], 1))+' '+'ratio = '+str(\n                        round(self.data[6][i], 2)))  # Affichage profondeur support+profondeur element clampe+clamp_ratio\n                    if self.data[6][i] >= 1 or self.data[6][i] <= 0:\n                        warn.append(i)\n                    count = count+1\n                else:\n                    my_prof.append(str(round(self.myyfloat[i], 1)))\n                if self.data[0][i].__class__.__name__ == \"Ropes\":\n                    length_stretch.append(\n                        self.data[0][i][0].length+' '+'('+self.percent_stretch[i]+')')\n                else:\n                    length_stretch.append('')\n\n        Tab = np.zeros((size+1, 8))\n        Tab[:, 0] = length\n        Tab[:, 1] = F_Kp\n        Tab[:, 2] = alpha\n        Tab[:, 3] = self.myxfloat\n        Tab[:, 4] = subduct\n        Tab[:, 5] = self.Buoyancy_kg\n        Tab[:, 6] = self.weight_kg\n        Tab[:, 7] = self.percent_max_T\n\n        for i in range(Tab.shape[0]):\n            inter = [name[i]]  # On commence par les noms\n            for j in range(1):\n                inter.append(Tab[i][j])  # Longueur\n            inter.append(my_prof[i])  # Profondeur\n            for j in range(1, Tab.shape[1]):  # Reste du tableau\n                inter.append(Tab[i][j])\n            inter.append(length_stretch[i])\n            Tab_final.append(inter)\n        Tab_final.insert(0, [\"Name\", \"Static Length (m)\", \"Depth (m)\", \"Tension (Kp)\", \"Angle (deg)\",\n                            \"Dx (m)\", \"Dz (m)\", \"Buoy (kg)\", \"Weight (kg)\", \"Launch Tension (%)\", \"Length Stretched (m)\"])\n        tab_grid = QtGui.QGridLayout()\n        inter = []\n        for j in range(len(Tab_final[0])):  # Affichage du nom des categories\n            label = QtGui.QLabel(Tab_final[0][j])\n            label.setStyleSheet(\n                \"QLabel { background-color : white; color : black;border: 2px solid black }\")\n            tab_grid.addWidget(label, 0, j)\n            inter.append(Tab_final[0][j])\n\n        self.Tab_report.append(inter)\n        for k in range(1, len(Tab_final)):\n            # Affichage de chaque element sauf terminaison\n            if self.data[0][k-1].__class__.__name__ != \"Terminals\":\n                inter = []\n                for l in range(len(Tab_final[k])):\n                    if type(Tab_final[k][l]) != str:\n                        Tab_final[k][l] = str(round(Tab_final[k][l], 1))\n                    inter.append(Tab_final[k][l])\n                    label = QtGui.QLabel(Tab_final[k][l])\n                    # On repere en bleu ciel : la bouee de tete, les instruments, les largueurs, et le lest\n                    if k-1 in ind_instrum or k == 1 or k-1 == release_ind or k == len(Tab_final)-1:\n                        label.setStyleSheet(\n                            \"QLabel { background-color : rgb(168, 211, 255); color : black;border: 1px solid black }\")\n                        if k-1 in warn:  # Un instrument clampe au dela de son support\n                            label.setStyleSheet(\n                                \"QLabel { background-color : red; color : black;border: 1px solid black }\")\n\n                    else:\n                        label.setStyleSheet(\n                            \"QLabel { background-color : white; color : black;border: 1px solid black }\")\n                    tab_grid.addWidget(label, k, l)\n                self.Tab_report.append(inter)\n        tab_grid.setSpacing(0)\n\n        self.layout.addLayout(tab_grid)\n\n        self.scrollArea.setWidget(self.scrolledWidget)\n        self.setLayout(self.groupLayout)\n", "meta": {"hexsha": "0f042db9051fa336847452ec73a2991963857428", "size": 44357, "ext": "py", "lang": "Python", "max_stars_repo_path": "simulate_window.py", "max_stars_repo_name": "jgrelet/Mooring-simulator", "max_stars_repo_head_hexsha": "e032b3f6d853d2df32d8c2c449c243d9632c7abb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulate_window.py", "max_issues_repo_name": "jgrelet/Mooring-simulator", "max_issues_repo_head_hexsha": "e032b3f6d853d2df32d8c2c449c243d9632c7abb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulate_window.py", "max_forks_repo_name": "jgrelet/Mooring-simulator", "max_forks_repo_head_hexsha": "e032b3f6d853d2df32d8c2c449c243d9632c7abb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.0674778761, "max_line_length": 196, "alphanum_fraction": 0.5184074667, "include": true, "reason": "import numpy", "num_tokens": 11103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.28140561345566495, "lm_q1q2_score": 0.1949133421691788}}
{"text": "import math\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom mmcv.cnn import kaiming_init\nfrom mmdet.ops import DeformConv\n\nclass NovelKQRAttention(nn.Module):\n    \"\"\"Modified GeneralizedAttention module.\n\n    See 'An Empirical Study of Spatial Attention Mechanisms in Deep Networks'\n    (https://arxiv.org/abs/1711.07971) for details.\n\n    Args:\n        in_dim (int): Channels of the input feature map.\n        spatial_range (int): The spatial range.\n            -1 indicates no spatial range constraint.\n        num_heads (int): The head number of empirical_attention module.\n        position_embedding_dim (int): The position embedding dimension.\n        position_magnitude (int): A multiplier acting on coord difference.\n        kv_stride (int): The feature stride acting on key/value feature map.\n        q_stride (int): The feature stride acting on query feature map.\n        attention_type (str): A binary indicator string for indicating which\n            items in generalized empirical_attention module are used.\n            '1000' indicates 'query and key content' (appr - appr) item,\n            '0100' indicates 'query content and relative position'\n              (appr - position) item,\n            '0010' indicates 'key content only' (bias - appr) item,\n            '0001' indicates 'relative position only' (bias - position) item.\n    \"\"\"\n\n    def __init__(self,\n                 in_dim,\n                 spatial_range=-1,\n                 num_heads=9,\n                 position_embedding_dim=-1,\n                 position_magnitude=1,\n                 kv_stride=2,\n                 q_stride=1,\n                 attention_type='0110',\n                 deformable_group=1,\n                 dconv_stride = 1,\n                 dconv_groups =1,\n                 dconv_learnable_vector = True):\n\n        super(NovelKQRAttention, self).__init__()\n\n        # hard range means local range for non-local operation\n        self.position_embedding_dim = (\n            position_embedding_dim if position_embedding_dim > 0 else in_dim)\n\n        self.position_magnitude = position_magnitude\n        self.num_heads = num_heads\n        self.channel_in = in_dim\n        self.spatial_range = spatial_range\n        self.kv_stride = kv_stride\n        self.q_stride = q_stride\n        self.attention_type = [bool(int(_)) for _ in attention_type]\n        self.qk_embed_dim = in_dim // num_heads\n        self.deformable_group = deformable_group\n        self.dconv_stride = dconv_stride\n        self.dconv_learnable_vector = dconv_learnable_vector\n        self.dconv_groups = dconv_groups\n        out_c = self.qk_embed_dim * num_heads\n\n\n        if self.attention_type[2]:\n            self.key_conv = nn.Conv2d(\n                in_channels=in_dim,\n                out_channels=out_c,\n                kernel_size=1,\n                bias=False)\n            self.key_conv.kaiming_init = True\n\n        if self.attention_type[1]:\n            self.query_conv_offset = nn.Conv2d(\n                in_channels=in_dim,\n                out_channels=self.deformable_group * 18,\n                kernel_size=3,\n                padding=1,\n                stride = self.dconv_stride,\n                dilation=1,\n                bias=False)\n\n            self.query_dconv=DeformConv(\n                in_channels =in_dim,\n                out_channels = out_c,\n                kernel_size=3,\n                stride = self.dconv_stride,\n                padding = 1,\n                dilation =1,\n                deformable_groups = self.deformable_group,\n                groups= self.dconv_groups,\n                bias = False)\n\n        self.v_dim = in_dim // num_heads\n        self.value_conv = nn.Conv2d(\n            in_channels=in_dim,\n            out_channels=self.v_dim * num_heads,\n            kernel_size=1,\n            bias=False)\n        self.value_conv.kaiming_init = True\n\n\n        if self.attention_type[2]:\n            stdv = 1.0 / math.sqrt(self.qk_embed_dim * 2)\n            appr_bias_value = -2 * stdv * torch.rand(out_c) + stdv\n            self.appr_bias = nn.Parameter(appr_bias_value)\n\n        if self.attention_type[1] and self.dconv_learnable_vector == True :\n            stdv = 1.0 / math.sqrt(self.qk_embed_dim * 2)\n            appr_bias_qRelPos = -2 * stdv * torch.rand(out_c) + stdv\n            self.appr_bias_qRelPos = nn.Parameter(appr_bias_qRelPos)\n\n\n        self.proj_conv = nn.Conv2d(\n            in_channels=self.v_dim * num_heads,\n            out_channels=in_dim,\n            kernel_size=1,\n            bias=True)\n        self.proj_conv.kaiming_init = True\n        self.gamma = nn.Parameter(torch.zeros(1))\n\n        if self.spatial_range >= 0:\n            # only works when non local is after 3*3 conv\n            if in_dim == 256:\n                max_len = 84\n            elif in_dim == 512:\n                max_len = 42\n\n            max_len_kv = int((max_len - 1.0) / self.kv_stride + 1)\n            local_constraint_map = np.ones(\n                (max_len, max_len, max_len_kv, max_len_kv), dtype=np.int)\n            for iy in range(max_len):\n                for ix in range(max_len):\n                    local_constraint_map[iy, ix,\n                                         max((iy - self.spatial_range) //\n                                             self.kv_stride, 0):min(\n                                                 (iy + self.spatial_range +\n                                                  1) // self.kv_stride +\n                                                 1, max_len),\n                                         max((ix - self.spatial_range) //\n                                             self.kv_stride, 0):min(\n                                                 (ix + self.spatial_range +\n                                                  1) // self.kv_stride +\n                                                 1, max_len)] = 0\n\n            self.local_constraint_map = nn.Parameter(\n                torch.from_numpy(local_constraint_map).byte(),\n                requires_grad=False)\n\n        if self.q_stride > 1:\n            self.q_downsample = nn.AvgPool2d(\n                kernel_size=1, stride=self.q_stride)\n        else:\n            self.q_downsample = None\n\n        if self.kv_stride > 1:\n            self.kv_downsample = nn.AvgPool2d(\n                kernel_size=1, stride=self.kv_stride)\n        else:\n            self.kv_downsample = None\n\n        self.init_weights()\n\n\n    def forward(self, x_input):\n        num_heads = self.num_heads\n\n        # use empirical_attention\n        if self.q_downsample is not None:\n            x_q = self.q_downsample(x_input)\n        else:\n            x_q = x_input\n        n, _, h, w = x_q.shape\n\n        if self.dconv_stride > 1:\n            h,w = h//self.dconv_stride, w//self.dconv_stride\n\n        if self.kv_downsample is not None:\n            x_kv = self.kv_downsample(x_input)\n        else:\n            x_kv = x_input\n        _, _, h_kv, w_kv = x_kv.shape\n\n\n        if self.attention_type[2]:\n            proj_key = self.key_conv(x_kv).view(\n                (n, num_heads, self.qk_embed_dim, h_kv * w_kv))\n\n        if self.attention_type[1]:\n            offset = self.query_conv_offset(x_q)\n            proj_query_relativePos =self.query_dconv(x_q,offset).view(n,num_heads,self.qk_embed_dim,h*w)\n\n\n        # accelerate for saliency only\n        if (np.sum(self.attention_type) == 1) and self.attention_type[2]:\n            appr_bias = self.appr_bias.\\\n                view(1, num_heads, 1, self.qk_embed_dim).\\\n                repeat(n, 1, 1, 1)\n\n            energy = torch.matmul(appr_bias, proj_key).\\\n                view(n, num_heads, 1, h_kv * w_kv)\n\n            h = 1\n            w = 1\n        else:\n            if not self.attention_type[0]:\n                energy = torch.zeros(\n                    n,\n                    num_heads,\n                    h,\n                    w,\n                    h_kv,\n                    w_kv,\n                    dtype=x_input.dtype,\n                    device=x_input.device)\n\n            # Key Content\n            if self.attention_type[2]:\n                appr_bias = self.appr_bias.\\\n                    view(1, num_heads, 1, self.qk_embed_dim).\\\n                    repeat(n, 1, 1, 1)\n\n                energy += torch.matmul(appr_bias, proj_key).\\\n                        view(n, num_heads, 1, 1, h_kv, w_kv)\n\n            # Query Content and Relative Position\n            if self.attention_type[1]:\n\n                if self.dconv_learnable_vector == False :\n                    energy+=proj_query_relativePos.view(n,num_heads,h,w,1,1)\n\n                else:\n                    appr_bias_qRelPos = self.appr_bias_qRelPos.\\\n                        view(1,num_heads,1,self.qk_embed_dim).\\\n                        repeat(n,1,1,1)\n                    energy+= torch.matmul(appr_bias_qRelPos,proj_query_relativePos).\\\n                            view(n,num_heads,h,w,1,1)\n\n\n            energy = energy.view(n,num_heads,h*w,h_kv*w_kv)\n\n        if self.spatial_range >= 0:\n            cur_local_constraint_map = \\\n                self.local_constraint_map[:h, :w, :h_kv, :w_kv].\\\n                contiguous().\\\n                view(1, 1, h*w, h_kv*w_kv)\n\n            energy = energy.masked_fill_(cur_local_constraint_map,\n                                         float('-inf'))\n\n\n        attention = F.softmax(energy, 3)\n\n\n        proj_value = self.value_conv(x_kv)\n        proj_value_reshape = proj_value.\\\n            view((n, num_heads, self.v_dim, h_kv * w_kv)).\\\n            permute(0, 1, 3, 2)\n\n        out = torch.matmul(attention, proj_value_reshape).\\\n            permute(0, 1, 3, 2).\\\n            contiguous().\\\n            view(n, self.v_dim * self.num_heads, h, w)\n\n        out = self.proj_conv(out)\n\n        if self.dconv_stride > 1:\n            out = F.interpolate(out,scale_factor=self.dconv_stride)\n\n        if self.q_stride > 1:\n            out = F.interpolate(out,size=x_input.size()[2:])\n\n        out = self.gamma * out + x_input\n\n        return out\n\n    def init_weights(self):\n        for m in self.modules():\n            if hasattr(m, 'kaiming_init') and m.kaiming_init:\n                kaiming_init(\n                    m,\n                    mode='fan_in',\n                    nonlinearity='leaky_relu',\n                    bias=0,\n                    distribution='uniform',\n                    a=1)\n", "meta": {"hexsha": "672d2599a93a740f26f10192bc0ee35541092f28", "size": 10382, "ext": "py", "lang": "Python", "max_stars_repo_path": "mmdetection/mmdet/models/plugins/novelKQR_self_attention.py", "max_stars_repo_name": "muditchaudhary/RepPoints-x-Libra-R-CNN-x-Transformer-self-attention", "max_stars_repo_head_hexsha": "b4c20fad012da3382de83a37481c767f66985ead", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-01T03:48:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-01T03:48:13.000Z", "max_issues_repo_path": "mmdetection/mmdet/models/plugins/novelKQR_self_attention.py", "max_issues_repo_name": "muditchaudhary/RepPoints-x-Libra-R-CNN-x-Transformer-self-attention", "max_issues_repo_head_hexsha": "b4c20fad012da3382de83a37481c767f66985ead", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-10T02:43:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-10T03:20:46.000Z", "max_forks_repo_path": "mmdetection/mmdet/models/plugins/novelKQR_self_attention.py", "max_forks_repo_name": "muditchaudhary/RepPoints-x-Libra-R-CNN-x-Transformer-self-attention", "max_forks_repo_head_hexsha": "b4c20fad012da3382de83a37481c767f66985ead", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.676975945, "max_line_length": 104, "alphanum_fraction": 0.5261991909, "include": true, "reason": "import numpy", "num_tokens": 2322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982315512488, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.19482245012500862}}
{"text": "import logging\n\nimport numpy as np\nimport pandas as pd\nfrom numba import njit\nfrom scipy.special import expn\nfrom scipy.interpolate import PchipInterpolator\nfrom collections import Counter as counter\nfrom tardis import constants as const\n\nfrom tardis.plasma.properties.base import (\n    ProcessingPlasmaProperty,\n    HiddenPlasmaProperty,\n    BaseAtomicDataProperty,\n)\nfrom tardis.plasma.exceptions import IncompleteAtomicData\nfrom tardis.plasma.properties.continuum_processes import (\n    get_ground_state_multi_index,\n    K_B,\n    BETA_COLL,\n    H,\n    A0,\n    M_E,\n    C,\n)\n\nlogger = logging.getLogger(__name__)\n\n__all__ = [\n    \"Levels\",\n    \"Lines\",\n    \"LinesLowerLevelIndex\",\n    \"LinesUpperLevelIndex\",\n    \"AtomicMass\",\n    \"IonizationData\",\n    \"ZetaData\",\n    \"NLTEData\",\n    \"MacroAtomData\",\n    \"PhotoIonizationData\",\n    \"YgData\",\n    \"YgInterpolator\",\n    \"LevelIdxs2LineIdx\",\n    \"LevelIdxs2TransitionIdx\",\n    \"TwoPhotonData\",\n    \"ContinuumInteractionHandler\",\n]\n\n\nclass Levels(BaseAtomicDataProperty):\n    \"\"\"\n    Attributes\n    ----------\n    levels : pandas.MultiIndex\n        (atomic_number, ion_number, level_number)\n        Index of filtered atomic data. Index used for all other attribute dataframes for this class\n    excitation_energy : pandas.DataFrame, dtype float\n        Excitation energies of atomic levels.\n        Index is levels.\n    metastability : pandas.DataFrame, dtype bool\n        Records whether atomic levels are metastable.\n        Index is levels.\n    g : pandas.DataFrame (index=levels), dtype float\n        Statistical weights of atomic levels.\n    \"\"\"\n\n    outputs = (\"levels\", \"excitation_energy\", \"metastability\", \"g\")\n    latex_name = (\n        r\"\\textrm{levels}\",\n        r\"\\epsilon_{\\textrm{k}}\",\n        r\"\\textrm{metastability}\",\n        \"g\",\n    )\n\n    def _filter_atomic_property(self, levels, selected_atoms):\n        return levels\n        # return levels[levels.atomic_number.isin(selected_atoms)]\n\n    def _set_index(self, levels):\n        # levels = levels.set_index(['atomic_number', 'ion_number',\n        #                          'level_number'])\n        return (\n            levels.index,\n            levels[\"energy\"],\n            levels[\"metastable\"],\n            levels[\"g\"],\n        )\n\n\nclass Lines(BaseAtomicDataProperty):\n    \"\"\"\n    Attributes\n    ----------\n    lines : pandas.DataFrame\n        Atomic lines data. Columns are wavelength, atomic_number,ion_number,\n        f_ul, f_lu, level_number_lower, level_number_upper, nu, B_lu, B_ul, A_ul,\n        wavelength. Index is line_id.\n    nu : pandas.DataFrame, dtype float\n        Line frequency data. Index is line_id.\n    f_lu : pandas.DataFrame, dtype float\n        Transition probability data. Index is line_id.\n    wavelength_cm : pandas.DataFrame, dtype float\n        Line wavelengths in cm. Index is line_id.\n    \"\"\"\n\n    # Would like for lines to just be the line_id values\n    outputs = (\"lines\", \"nu\", \"f_lu\", \"wavelength_cm\")\n\n    latex_name = (\n        r\"\\textrm{lines}\",\n        r\"\\nu\",\n        r\"f_lu\",\n        r\"\\lambda_{cm}\",\n    )\n\n    def _filter_atomic_property(self, lines, selected_atoms):\n        # return lines[lines.atomic_number.isin(selected_atoms)]\n        return lines\n\n    def _set_index(self, lines):\n        # lines.set_index('line_id', inplace=True)\n        return lines, lines[\"nu\"], lines[\"f_lu\"], lines[\"wavelength_cm\"]\n\n\nclass MacroAtomData(BaseAtomicDataProperty):\n    outputs = (\"macro_atom_data\",)\n\n    def _filter_atomic_property(self, macro_atom_data, selected_atoms):\n        return macro_atom_data\n\n    def _set_index(self, macro_atom_data):\n        return macro_atom_data\n\n\nclass PhotoIonizationData(ProcessingPlasmaProperty):\n    \"\"\"\n    Attributes\n    ----------\n    photo_ion_cross_sections : pandas.DataFrame, dtype float\n        Photoionization cross sections as a function of frequency.\n        Columns are nu, x_sect, index=('atomic_number','ion_number','level_number')\n    photo_ion_block_references : numpy.ndarray, dtype int\n        Indices where the photoionization data for\n        a given level starts. Needed for calculation\n        of recombination rates.\n    nu_i : pandas.Series, dtype float\n        Threshold frequencies for ionization\n    energy_i : pandas.Series, dtype float\n        Energies of levels with bound-free transitions. Needed to calculate\n        for example internal transition probabilities in the macro atom scheme.\n    photo_ion_index : pandas.MultiIndex, dtype int\n        Atomic, ion and level numbers for which photoionization data exists.\n    level2continuum_idx : pandas.Series, dtype int\n        Maps a level MultiIndex (atomic_number, ion_number, level_number) to\n        the continuum_idx of the corresponding bound-free continuum (which are\n        sorted by decreasing frequency).\n    level_idxs2continuum_idx : pandas.DataFrame, dtype int\n        Maps a source_level_idx destination_level_idx pair to a continuum_idx.\n    \"\"\"\n\n    outputs = (\n        \"photo_ion_cross_sections\",\n        \"photo_ion_block_references\",\n        \"photo_ion_index\",\n        \"nu_i\",\n        \"energy_i\",\n        \"photo_ion_idx\",\n        \"level2continuum_idx\",\n        \"level_idxs2continuum_idx\",\n    )\n    latex_name = (\n        r\"\\xi_{\\textrm{i}}(\\nu)\",\n        \"\",\n        \"\",\n        r\"\\nu_i\",\n        r\"\\epsilon_i\",\n        \"\",\n        \"\",\n    )\n\n    def calculate(self, atomic_data, continuum_interaction_species):\n        #photoionization_data = atomic_data.photoionization_data.set_index(\n        #    [\"atomic_number\", \"ion_number\", \"level_number\"]\n        #)\n        photoionization_data = atomic_data.photoionization_data\n        mask_selected_species = photoionization_data.index.droplevel(\n            \"level_number\"\n        ).isin(continuum_interaction_species)\n        photoionization_data = photoionization_data[mask_selected_species]\n        phot_nus = photoionization_data[\"nu\"]\n        block_references = np.pad(\n            phot_nus.groupby(level=[0, 1, 2]).count().values.cumsum(), [1, 0]\n        )\n        photo_ion_index = photoionization_data.index.unique()\n        nu_i = photoionization_data.groupby(level=[0, 1, 2]).first().nu\n        energy_i = atomic_data.levels.loc[photo_ion_index].energy\n\n        source_idx = atomic_data.macro_atom_references.loc[\n            photo_ion_index\n        ].references_idx\n        destination_idx = atomic_data.macro_atom_references.loc[\n            get_ground_state_multi_index(photo_ion_index)\n        ].references_idx\n        photo_ion_idx = pd.DataFrame(\n            {\n                \"source_level_idx\": source_idx.values,\n                \"destination_level_idx\": destination_idx.values,\n            },\n            index=photo_ion_index,\n        )\n\n        level2continuum_edge_idx = pd.Series(\n            np.arange(len(nu_i)),\n            nu_i.sort_values(ascending=False).index,\n            name=\"continuum_idx\",\n        )\n\n        level_idxs2continuum_idx = photo_ion_idx.copy()\n        level_idxs2continuum_idx[\"continuum_idx\"] = level2continuum_edge_idx\n        level_idxs2continuum_idx = level_idxs2continuum_idx.set_index(\n            [\"source_level_idx\", \"destination_level_idx\"]\n        )\n        return (\n            photoionization_data,\n            block_references,\n            photo_ion_index,\n            nu_i,\n            energy_i,\n            photo_ion_idx,\n            level2continuum_edge_idx,\n            level_idxs2continuum_idx,\n        )\n\n\nclass ContinuumInteractionHandler(ProcessingPlasmaProperty):\n    outputs = (\n        \"get_current_bound_free_continua\",\n        \"determine_bf_macro_activation_idx\",\n        \"determine_continuum_macro_activation_idx\",\n    )\n\n    def calculate(\n        self,\n        photo_ion_cross_sections,\n        level2continuum_idx,\n        photo_ion_idx,\n        k_packet_idx,\n    ):\n        nus = photo_ion_cross_sections.nu.loc[\n            level2continuum_idx.index\n        ]  # Sort by descending frequency\n        nu_mins = nus.groupby(level=[0, 1, 2], sort=False).first().values\n        nu_maxs = nus.groupby(level=[0, 1, 2], sort=False).last().values\n\n        @njit(error_model=\"numpy\", fastmath=True)\n        def get_current_bound_free_continua(nu):\n            \"\"\"\n            Determine bound-free continua for which absorption is possible.\n\n            Parameters\n            ----------\n            nu : float\n                Comoving frequency of the r-packet.\n\n            Returns\n            -------\n            numpy.ndarray, dtype int\n                Continuum ids for which absorption is possible for frequency `nu`.\n            \"\"\"\n            # searchsorted would be faster but would need stricter format for photoionization data\n            current_continua = np.where(\n                np.logical_and(nu >= nu_mins, nu <= nu_maxs)\n            )[0]\n            return current_continua\n\n        destination_level_idxs = photo_ion_idx.loc[\n            level2continuum_idx.index, \"destination_level_idx\"\n        ].values\n\n        @njit(error_model=\"numpy\", fastmath=True)\n        def determine_bf_macro_activation_idx(\n            nu, chi_bf_contributions, active_continua\n        ):\n            \"\"\"\n            Determine the macro atom activation level after bound-free absorption.\n\n            Parameters\n            ----------\n            nu : float\n                Comoving frequency of the r-packet.\n            chi_bf_contributions : numpy.ndarray, dtype float\n                Cumulative distribution of bound-free opacities at frequency\n                `nu`.\n            active_continua : numpy.ndarray, dtype int\n                Continuum ids for which absorption is possible for frequency `nu`.\n\n            Returns\n            -------\n            float\n                Macro atom activation idx.\n            \"\"\"\n            # Perform a MC experiment to determine the continuum for absorption\n            index = np.searchsorted(chi_bf_contributions, np.random.random())\n            continuum_id = active_continua[index]\n\n            # Perform a MC experiment to determine whether thermal or\n            # ionization energy is created\n            nu_threshold = nu_mins[continuum_id]\n            fraction_ionization = nu_threshold / nu\n            if (\n                np.random.random() < fraction_ionization\n            ):  # Create ionization energy (i-packet)\n                destination_level_idx = destination_level_idxs[continuum_id]\n            else:  # Create thermal energy (k-packet)\n                destination_level_idx = k_packet_idx\n            return destination_level_idx\n\n        @njit(error_model=\"numpy\", fastmath=True)\n        def determine_continuum_macro_activation_idx(\n            nu, chi_bf, chi_ff, chi_bf_contributions, active_continua\n        ):\n            \"\"\"\n            Determine the macro atom activation level after a continuum absorption.\n\n            Parameters\n            ----------\n            nu : float\n                Comoving frequency of the r-packet.\n            chi_bf : numpy.ndarray, dtype float\n                Bound-free opacity.\n            chi_bf : numpy.ndarray, dtype float\n                Free-free opacity.\n            chi_bf_contributions : numpy.ndarray, dtype float\n                Cumulative distribution of bound-free opacities at frequency\n                `nu`.\n            active_continua : numpy.ndarray, dtype int\n                Continuum ids for which absorption is possible for frequency `nu`.\n\n            Returns\n            -------\n            float\n                Macro atom activation idx.\n            \"\"\"\n            fraction_bf = chi_bf / (chi_bf + chi_ff)\n            # TODO: In principle, we can also decide here whether a Thomson\n            # scattering event happens and need one less RNG call.\n            if np.random.random() < fraction_bf:  # Bound-free absorption\n                destination_level_idx = determine_bf_macro_activation_idx(\n                    nu, chi_bf_contributions, active_continua\n                )\n            else:  # Free-free absorption (i.e. k-packet creation)\n                destination_level_idx = k_packet_idx\n            return destination_level_idx\n\n        return (\n            get_current_bound_free_continua,\n            determine_bf_macro_activation_idx,\n            determine_continuum_macro_activation_idx,\n        )\n\n\nclass TwoPhotonData(ProcessingPlasmaProperty):\n    outputs = (\"two_photon_data\", \"two_photon_idx\")\n    \"\"\"\n    Attributes\n    ----------\n    two_photon_data : pandas.DataFrame, dtype float\n    A DataFrame containing the *two photon decay data* with:\n        index: atomic_number, ion_number, level_number_lower, level_number_upper\n        columns: A_ul[1/s], nu0[Hz], alpha, beta, gamma\n        alpha, beta, gamma are fit coefficients for the frequency dependent\n        transition probability A(y) of the two photon decay. See Eq. 2 in\n        Nussbaumer & Schmutz (1984).\n    two_photon_idx : pandas.DataFrame, dtype int\n    \"\"\"\n\n    def calculate(self, atomic_data, continuum_interaction_species):\n        two_photon_data = atomic_data.two_photon_data\n        mask_selected_species = two_photon_data.index.droplevel(\n            [\"level_number_lower\", \"level_number_upper\"]\n        ).isin(continuum_interaction_species)\n        if not mask_selected_species.sum():\n            raise IncompleteAtomicData(\n                \"two photon transition data for the requested \"\n                \"continuum_interactions species: {}\".format(\n                    continuum_interaction_species.values.tolist()\n                )\n            )\n        two_photon_data = two_photon_data[mask_selected_species]\n        index_lower = two_photon_data.index.droplevel(\"level_number_upper\")\n        index_upper = two_photon_data.index.droplevel(\"level_number_lower\")\n        source_idx = atomic_data.macro_atom_references.loc[\n            index_upper\n        ].references_idx\n        destination_idx = atomic_data.macro_atom_references.loc[\n            index_lower\n        ].references_idx\n        two_photon_idx = pd.DataFrame(\n            {\n                \"source_level_idx\": source_idx.values,\n                \"destination_level_idx\": destination_idx.values,\n            },\n            index=two_photon_data.index,\n        )\n        if len(two_photon_data) != 1:\n            raise NotImplementedError(\n                \"Currently only one two-photon decay is supported but there \"\n                f\"are {len(two_photon_data)} in the atomic data.\"\n            )\n        return two_photon_data, two_photon_idx\n\n\nclass LinesLowerLevelIndex(HiddenPlasmaProperty):\n    \"\"\"\n    Attributes\n    ----------\n    lines_lower_level_index : numpy.ndrarray, dtype int\n        Levels data for lower levels of particular lines\n    \"\"\"\n\n    outputs = (\"lines_lower_level_index\",)\n\n    def calculate(self, levels, lines):\n        levels_index = pd.Series(\n            np.arange(len(levels), dtype=np.int64), index=levels\n        )\n        lines_index = lines.index.droplevel(\"level_number_upper\")\n        return np.array(levels_index.loc[lines_index])\n\n\nclass LinesUpperLevelIndex(HiddenPlasmaProperty):\n    \"\"\"\n    Attributes\n    ----------\n    lines_upper_level_index : numpy.ndarray, dtype int\n        Levels data for upper levels of particular lines\n    \"\"\"\n\n    outputs = (\"lines_upper_level_index\",)\n\n    def calculate(self, levels, lines):\n        levels_index = pd.Series(\n            np.arange(len(levels), dtype=np.int64), index=levels\n        )\n        lines_index = lines.index.droplevel(\"level_number_lower\")\n        return np.array(levels_index.loc[lines_index])\n\n\nclass LevelIdxs2LineIdx(HiddenPlasmaProperty):\n    \"\"\"\n    Attributes\n    ----------\n    level_idxs2line_idx : pandas.Series, dtype int\n        Maps a source_level_idx destination_level_idx pair to a line_idx.\n    \"\"\"\n\n    outputs = (\"level_idxs2line_idx\",)\n\n    def calculate(self, atomic_data):\n        index = pd.MultiIndex.from_arrays(\n            [\n                atomic_data.lines_upper2level_idx,\n                atomic_data.lines_lower2level_idx,\n            ],\n            names=[\"source_level_idx\", \"destination_level_idx\"],\n        )\n        level_idxs2line_idx = pd.Series(\n            np.arange(len(index)), index=index, name=\"lines_idx\"\n        )\n        return level_idxs2line_idx\n\n\nclass LevelIdxs2TransitionIdx(HiddenPlasmaProperty):\n    \"\"\"\n    Attributes\n    ----------\n    level_idxs2transition_idx : pandas.DataFrame, dtype int\n       Maps a source_level_idx destination_level_idx pair to a transition_idx\n       and transition type.\n    \"\"\"\n\n    outputs = (\"level_idxs2transition_idx\",)\n\n    def calculate(self, level_idxs2line_idx, level_idxs2continuum_idx):\n        level_idxs2line_idx = level_idxs2line_idx.to_frame()\n        level_idxs2line_idx.insert(1, \"transition_type\", -1)\n\n        level_idxs2continuum_idx = level_idxs2continuum_idx.copy()\n        level_idxs2continuum_idx.insert(1, \"transition_type\", -2)\n        level_idxs2continuum_idx = level_idxs2continuum_idx.rename(\n            columns=({\"continuum_idx\": \"lines_idx\"})\n        )\n\n        names = level_idxs2continuum_idx.index.names\n        level_idxs2continuum_idx = level_idxs2continuum_idx.swaplevel()\n        level_idxs2continuum_idx.index.names = names\n\n        # TODO: This should probably be defined somewhere else.\n        # One possibility would be to attach it to the cooling properties as\n        # a class attribute.\n        index_cooling = pd.MultiIndex.from_product(\n            [[\"k\"], [\"ff\", \"adiabatic\", \"bf\"]], names=names\n        )\n        num_cool = len(index_cooling)\n        level_idxs2cooling_idx = pd.DataFrame(\n            {\n                \"lines_idx\": np.ones(num_cool, dtype=int) * -1,\n                \"transition_type\": np.arange(-3, -3 - num_cool, -1),\n            },\n            index=index_cooling,\n        )\n        level_idxs2transition_idx = pd.concat(\n            [\n                level_idxs2continuum_idx,\n                level_idxs2line_idx,\n                level_idxs2cooling_idx,\n            ]\n        )\n\n        # TODO: Add two-photon processes\n\n        return level_idxs2transition_idx\n\n\nclass AtomicMass(ProcessingPlasmaProperty):\n    \"\"\"\n    Attributes\n    ----------\n    atomic_mass : pandas.Series\n        Atomic masses of the elements used. Indexed by atomic number.\n    \"\"\"\n\n    outputs = (\"atomic_mass\",)\n\n    def calculate(self, atomic_data, selected_atoms):\n        if getattr(self, self.outputs[0]) is not None:\n            return (getattr(self, self.outputs[0]),)\n        else:\n            return atomic_data.atom_data.loc[selected_atoms].mass\n\n\nclass IonizationData(BaseAtomicDataProperty):\n    \"\"\"\n    Attributes\n    ----------\n    ionization_data : pandas.Series\n        Holding ionization energies\n        Indexed by atomic number, ion number.\n    \"\"\"\n\n    outputs = (\"ionization_data\",)\n\n    def _filter_atomic_property(self, ionization_data, selected_atoms):\n        mask = ionization_data.index.isin(selected_atoms, level=\"atomic_number\")\n        ionization_data = ionization_data[mask]\n        counts = ionization_data.groupby(level=\"atomic_number\").count()\n\n        if np.alltrue(counts.index == counts):\n            return ionization_data\n        else:\n            raise IncompleteAtomicData(\n                f\"ionization data for the ion ({str(counts.index[counts.index != counts])}, {str(counts[counts.index != counts])})\"\n            )\n\n    def _set_index(self, ionization_data):\n        return ionization_data\n\n\nclass ZetaData(BaseAtomicDataProperty):\n    \"\"\"\n    Attributes\n    ----------\n    zeta_data : pandas.DataFrame, dtype float\n        Zeta data for the elements used. Indexed by atomic number, ion number.\n        Columns are temperature values up to 40,000 K in iterations of 2,000 K.\n        The zeta value represents the fraction of recombination events\n        from the ionized state that go directly to the ground state.\n    \"\"\"\n\n    outputs = (\"zeta_data\",)\n\n    def _filter_atomic_property(self, zeta_data, selected_atoms):\n        zeta_data[\"atomic_number\"] = zeta_data.index.codes[0] + 1\n        zeta_data[\"ion_number\"] = zeta_data.index.codes[1] + 1\n        zeta_data = zeta_data[zeta_data.atomic_number.isin(selected_atoms)]\n        zeta_data_check = counter(zeta_data.atomic_number.values)\n        keys = np.array(list(zeta_data_check.keys()))\n        values = np.array(zeta_data_check.values())\n        if np.alltrue(keys + 1 == values):\n            return zeta_data\n        else:\n            #            raise IncompleteAtomicData('zeta data')\n            # This currently replaces missing zeta data with 1, which is necessary with\n            # the present atomic data. Will replace with the error above when I have\n            # complete atomic data.\n            missing_ions = []\n            updated_index = []\n            for atom in selected_atoms:\n                for ion in range(1, atom + 2):\n                    if (atom, ion) not in zeta_data.index:\n                        missing_ions.append((atom, ion))\n                    updated_index.append([atom, ion])\n            logger.warn(\n                f\"Zeta_data missing - replaced with 1s. Missing ions: {missing_ions}\"\n            )\n            updated_index = np.array(updated_index)\n            updated_dataframe = pd.DataFrame(\n                index=pd.MultiIndex.from_arrays(\n                    updated_index.transpose().astype(int)\n                ),\n                columns=zeta_data.columns,\n            )\n            for value in range(len(zeta_data)):\n                updated_dataframe.loc[\n                    zeta_data.atomic_number.values[value],\n                    zeta_data.ion_number.values[value],\n                ] = zeta_data.loc[\n                    zeta_data.atomic_number.values[value],\n                    zeta_data.ion_number.values[value],\n                ]\n            updated_dataframe = updated_dataframe.astype(float)\n            updated_index = pd.DataFrame(updated_index)\n            updated_dataframe[\"atomic_number\"] = np.array(updated_index[0])\n            updated_dataframe[\"ion_number\"] = np.array(updated_index[1])\n            updated_dataframe.fillna(1.0, inplace=True)\n            return updated_dataframe\n\n    def _set_index(self, zeta_data):\n        return zeta_data.set_index([\"atomic_number\", \"ion_number\"])\n\n\nclass NLTEData(ProcessingPlasmaProperty):\n    \"\"\"\n    Attributes\n    ----------\n    nlte_data :\n        #Finish later (need atomic dataset with NLTE data).\n    \"\"\"\n\n    outputs = (\"nlte_data\",)\n\n    def calculate(self, atomic_data):\n        if getattr(self, self.outputs[0]) is not None:\n            return (getattr(self, self.outputs[0]),)\n        else:\n            return atomic_data.nlte_data\n\n\nclass YgData(ProcessingPlasmaProperty):\n    \"\"\"\n    Attributes\n    ----------\n    yg_data : pandas.DataFrame\n        Table of thermally averaged effective collision strengths\n        (divided by the statistical weight of the lower level) Y_ij / g_i .\n        Columns are temperatures.\n    t_yg : numpy.ndarray\n        Temperatures at which collision strengths are tabulated.\n    yg_index : Pandas MultiIndex\n    delta_E_yg : pandas.DataFrame\n        Energy difference between upper and lower levels coupled by collisions.\n    yg_idx : pandas.DataFrame\n        Source_level_idx and destination_level_idx of collision transitions.\n        Indexed by atomic_number, ion_number, level_number_lower,\n        level_number_upper.\n    \"\"\"\n\n    outputs = (\"yg_data\", \"t_yg\", \"yg_index\", \"delta_E_yg\", \"yg_idx\")\n    latex_name = (\n        r\"\\frac{Y_{ij}}{g_i}\",\n        r\"T_\\textrm{Yg}\",\n        r\"\\textrm{yg_index}\",\n        r\"\\delta E_{ij}\",\n        r\"\\textrm{yg_idx}\",\n    )\n\n    def calculate(self, atomic_data, continuum_interaction_species):\n        yg_data = atomic_data.yg_data\n\n        mask_selected_species = yg_data.index.droplevel(\n            [\"level_number_lower\", \"level_number_upper\"]\n        ).isin(continuum_interaction_species)\n        yg_data = yg_data[mask_selected_species]\n\n        t_yg = yg_data.columns.values.astype(float)\n        yg_data.columns = t_yg\n        approximate_yg_data = self.calculate_yg_van_regemorter(\n            atomic_data, t_yg, continuum_interaction_species\n        )\n\n        yg_data = yg_data.combine_first(approximate_yg_data)\n\n        energies = atomic_data.levels.energy\n        index = yg_data.index\n        lu_index = index.droplevel(\"level_number_lower\")\n        ll_index = index.droplevel(\"level_number_upper\")\n        delta_E = energies.loc[lu_index].values - energies.loc[ll_index].values\n        delta_E = pd.Series(delta_E, index=index)\n\n        source_idx = atomic_data.macro_atom_references.loc[\n            ll_index\n        ].references_idx\n        destination_idx = atomic_data.macro_atom_references.loc[\n            lu_index\n        ].references_idx\n        yg_idx = pd.DataFrame(\n            {\n                \"source_level_idx\": source_idx.values,\n                \"destination_level_idx\": destination_idx.values,\n            },\n            index=index,\n        )\n        return yg_data, t_yg, index, delta_E, yg_idx\n\n    @staticmethod\n    def calculate_yg_van_regemorter(\n        atomic_data, t_electrons, continuum_interaction_species\n    ):\n        \"\"\"\n        Calculate collision strengths in the van Regemorter approximation.\n\n        This function calculates thermally averaged effective collision\n        strengths (divided by the statistical weight of the lower level)\n        Y_ij / g_i using the van Regemorter approximation.\n\n        Parameters\n        ----------\n        atomic_data : tardis.io.atom_data.AtomData\n        t_electrons : numpy.ndarray\n        continuum_interaction_species : pandas.MultiIndex\n\n        Returns\n        -------\n        pandas.DataFrame\n            Thermally averaged effective collision strengths\n            (divided by the statistical weight of the lower level) Y_ij / g_i\n\n        Notes\n        -----\n        See Eq. 9.58 in [2].\n\n        References\n        ----------\n        .. [1] van Regemorter, H., “Rate of Collisional Excitation in Stellar\n               Atmospheres.”, The Astrophysical Journal, vol. 136, p. 906, 1962.\n               doi:10.1086/147445.\n        .. [2] Hubeny, I. and Mihalas, D., \"Theory of Stellar Atmospheres\". 2014.\n        \"\"\"\n        I_H = atomic_data.ionization_data.loc[(1, 1)]\n\n        mask_selected_species = atomic_data.lines.index.droplevel(\n            [\"level_number_lower\", \"level_number_upper\"]\n        ).isin(continuum_interaction_species)\n        lines_filtered = atomic_data.lines[mask_selected_species]\n        f_lu = lines_filtered.f_lu.values\n        nu_lines = lines_filtered.nu.values\n\n        yg = f_lu * (I_H / (H * nu_lines)) ** 2\n        coll_const = A0 ** 2 * np.pi * np.sqrt(8 * K_B / (np.pi * M_E))\n        yg = 14.5 * coll_const * t_electrons * yg[:, np.newaxis]\n\n        u0 = nu_lines[np.newaxis].T / t_electrons * (H / K_B)\n        gamma = 0.276 * np.exp(u0) * expn(1, u0)\n        gamma[gamma < 0.2] = 0.2\n        yg *= u0 * gamma / BETA_COLL\n        yg = pd.DataFrame(yg, index=lines_filtered.index, columns=t_electrons)\n\n        return yg\n\n\nclass YgInterpolator(ProcessingPlasmaProperty):\n    \"\"\"\n    Attributes\n    ----------\n    yg_interp : scipy.interpolate.PchipInterpolator\n        Interpolates the thermally averaged effective collision strengths\n        (divided by the statistical weight of the lower level) Y_ij / g_i as\n        a function of electron temperature.\n    \"\"\"\n\n    outputs = (\"yg_interp\",)\n    latex_name = (\"\\\\frac{Y_ij}{g_i}_{\\\\textrm{interp}}\",)\n\n    def calculate(self, yg_data, t_yg):\n        yg_interp = PchipInterpolator(t_yg, yg_data, axis=1, extrapolate=True)\n        return yg_interp\n", "meta": {"hexsha": "447dae42e9ddac71bb66dedb569b0fe3baa00b19", "size": 27595, "ext": "py", "lang": "Python", "max_stars_repo_path": "tardis/plasma/properties/atomic.py", "max_stars_repo_name": "ahmedo42/tardis", "max_stars_repo_head_hexsha": "e86ade324d94000a206742b12bc8d04d6c200ba2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tardis/plasma/properties/atomic.py", "max_issues_repo_name": "ahmedo42/tardis", "max_issues_repo_head_hexsha": "e86ade324d94000a206742b12bc8d04d6c200ba2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tardis/plasma/properties/atomic.py", "max_forks_repo_name": "ahmedo42/tardis", "max_forks_repo_head_hexsha": "e86ade324d94000a206742b12bc8d04d6c200ba2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1081424936, "max_line_length": 131, "alphanum_fraction": 0.6267077369, "include": true, "reason": "import numpy,from scipy,from numba", "num_tokens": 5997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.1948114893743221}}
{"text": "import sys\nimport base64\n\nimport numpy as np\n\nfrom . import _marching_cubes_lewiner_luts as mcluts\nfrom . import _marching_cubes_lewiner_cy\n\n\nif sys.version_info >= (3, ):\n    base64decode = base64.decodebytes\nelse:\n    base64decode = base64.decodestring\n\n\ndef marching_cubes_lewiner(volume, level=None, spacing=(1., 1., 1.),\n                           gradient_direction='descent', step_size=1,\n                           allow_degenerate=True, use_classic=False):\n    \"\"\"\n    Lewiner marching cubes algorithm to find surfaces in 3d volumetric data.\n\n    In contrast to ``marching_cubes_classic()``, this algorithm is faster,\n    resolves ambiguities, and guarantees topologically correct results.\n    Therefore, this algorithm generally a better choice, unless there\n    is a specific need for the classic algorithm.\n\n    Parameters\n    ----------\n    volume : (M, N, P) array\n        Input data volume to find isosurfaces. Will internally be\n        converted to float32 if necessary.\n    level : float\n        Contour value to search for isosurfaces in `volume`. If not\n        given or None, the average of the min and max of vol is used.\n    spacing : length-3 tuple of floats\n        Voxel spacing in spatial dimensions corresponding to numpy array\n        indexing dimensions (M, N, P) as in `volume`.\n    gradient_direction : string\n        Controls if the mesh was generated from an isosurface with gradient\n        descent toward objects of interest (the default), or the opposite,\n        considering the *left-hand* rule.\n        The two options are:\n        * descent : Object was greater than exterior\n        * ascent : Exterior was greater than object\n    step_size : int\n        Step size in voxels. Default 1. Larger steps yield faster but\n        coarser results. The result will always be topologically correct\n        though.\n    allow_degenerate : bool\n        Whether to allow degenerate (i.e. zero-area) triangles in the\n        end-result. Default True. If False, degenerate triangles are\n        removed, at the cost of making the algorithm slower.\n    use_classic : bool\n        If given and True, the classic marching cubes by Lorensen (1987)\n        is used. This option is included for reference purposes. Note\n        that this algorithm has ambiguities and is not guaranteed to\n        produce a topologically correct result. The results with using\n        this option are *not* generally the same as the\n        ``marching_cubes_classic()`` function.\n\n    Returns\n    -------\n    verts : (V, 3) array\n        Spatial coordinates for V unique mesh vertices. Coordinate order\n        matches input `volume` (M, N, P).\n    faces : (F, 3) array\n        Define triangular faces via referencing vertex indices from ``verts``.\n        This algorithm specifically outputs triangles, so each face has\n        exactly three indices.\n    normals : (V, 3) array\n        The normal direction at each vertex, as calculated from the\n        data.\n    values : (V, ) array\n        Gives a measure for the maximum value of the data in the local region\n        near each vertex. This can be used by visualization tools to apply\n        a colormap to the mesh.\n\n    Notes\n    -----\n    The algorithm [1] is an improved version of Chernyaev's Marching\n    Cubes 33 algorithm. It is an efficient algorithm that relies on\n    heavy use of lookup tables to handle the many different cases,\n    keeping the algorithm relatively easy. This implementation is\n    written in Cython, ported from Lewiner's C++ implementation.\n\n    To quantify the area of an isosurface generated by this algorithm, pass\n    verts and faces to `skimage.measure.mesh_surface_area`.\n\n    Regarding visualization of algorithm output, to contour a volume\n    named `myvolume` about the level 0.0, using the ``mayavi`` package::\n\n      >>> from mayavi import mlab # doctest: +SKIP\n      >>> verts, faces, normals, values = marching_cubes_lewiner(myvolume, 0.0) # doctest: +SKIP\n      >>> mlab.triangular_mesh([vert[0] for vert in verts],\n      ...                      [vert[1] for vert in verts],\n      ...                      [vert[2] for vert in verts],\n      ...                      faces) # doctest: +SKIP\n      >>> mlab.show() # doctest: +SKIP\n\n    Similarly using the ``visvis`` package::\n\n      >>> import visvis as vv # doctest: +SKIP\n      >>> verts, faces, normals, values = marching_cubes_lewiner(myvolume, 0.0) # doctest: +SKIP\n      >>> vv.mesh(np.fliplr(verts), faces, normals, values) # doctest: +SKIP\n      >>> vv.use().Run() # doctest: +SKIP\n\n    References\n    ----------\n    .. [1] Thomas Lewiner, Helio Lopes, Antonio Wilson Vieira and Geovan\n           Tavares. Efficient implementation of Marching Cubes' cases with\n           topological guarantees. Journal of Graphics Tools 8(2)\n           pp. 1-15 (december 2003).\n           DOI: 10.1080/10867651.2003.10487582\n\n    See Also\n    --------\n    skimage.measure.marching_cubes_classic\n    skimage.measure.mesh_surface_area\n    \"\"\"\n\n    # Check volume and ensure its in the format that the alg needs\n    if not isinstance(volume, np.ndarray) or (volume.ndim != 3):\n        raise ValueError('Input volume should be a 3D numpy array.')\n    if volume.shape[0] < 2 or volume.shape[1] < 2 or volume.shape[2] < 2:\n        raise ValueError(\"Input array must be at least 2x2x2.\")\n    volume = np.ascontiguousarray(volume, np.float32)  # no copy if not necessary\n\n    # Check/convert other inputs:\n    # level\n    if level is None:\n        level = 0.5 * (volume.min() + volume.max())\n    else:\n        level = float(level)\n        if level < volume.min() or level > volume.max():\n            raise ValueError(\"Surface level must be within volume data range.\")\n    # spacing\n    if len(spacing) != 3:\n        raise ValueError(\"`spacing` must consist of three floats.\")\n    # step_size\n    step_size = int(step_size)\n    if step_size < 1:\n        raise ValueError('step_size must be at least one.')\n    # use_classic\n    use_classic = bool(use_classic)\n\n    # Get LutProvider class (reuse if possible)\n    L = _get_mc_luts()\n\n    # Apply algorithm\n    func = _marching_cubes_lewiner_cy.marching_cubes\n    vertices, faces , normals, values = func(volume, level, L, step_size, use_classic)\n\n    if not len(vertices):\n        raise RuntimeError('No surface found at the given iso value.')\n\n    # Output in z-y-x order, as is common in skimage\n    vertices = np.fliplr(vertices)\n    normals = np.fliplr(normals)\n\n    # Finishing touches to output\n    faces.shape = -1, 3\n    if gradient_direction == 'descent':\n        # MC implementation is right-handed, but gradient_direction is left-handed\n        faces = np.fliplr(faces)\n    elif not gradient_direction == 'ascent':\n        raise ValueError(\"Incorrect input %s in `gradient_direction`, see \"\n                         \"docstring.\" % (gradient_direction))\n    if spacing != (1, 1, 1):\n        vertices = vertices * np.r_[spacing]\n\n    if allow_degenerate:\n        return vertices, faces, normals, values\n    else:\n        fun = _marching_cubes_lewiner_cy.remove_degenerate_faces\n        return fun(vertices.astype(np.float32), faces, normals, values)\n\n\ndef _to_array(args):\n    shape, text = args\n    byts = base64decode(text.encode('utf-8'))\n    ar = np.frombuffer(byts, dtype='int8')\n    ar.shape = shape\n    return ar\n\n\n# Map an edge-index to two relative pixel positions. The ege index\n# represents a point that lies somewhere in between these pixels.\n# Linear interpolation should be used to determine where it is exactly.\n#   0\n# 3   1   ->  0x\n#   2         xx\nEDGETORELATIVEPOSX = np.array([ [0,1],[1,1],[1,0],[0,0], [0,1],[1,1],[1,0],[0,0], [0,0],[1,1],[1,1],[0,0] ], 'int8')\nEDGETORELATIVEPOSY = np.array([ [0,0],[0,1],[1,1],[1,0], [0,0],[0,1],[1,1],[1,0], [0,0],[0,0],[1,1],[1,1] ], 'int8')\nEDGETORELATIVEPOSZ = np.array([ [0,0],[0,0],[0,0],[0,0], [1,1],[1,1],[1,1],[1,1], [0,1],[0,1],[0,1],[0,1] ], 'int8')\n\n\ndef _get_mc_luts():\n    \"\"\" Kind of lazy obtaining of the luts.\n    \"\"\"\n    if not hasattr(mcluts, 'THE_LUTS'):\n\n        mcluts.THE_LUTS = _marching_cubes_lewiner_cy.LutProvider(\n                EDGETORELATIVEPOSX, EDGETORELATIVEPOSY, EDGETORELATIVEPOSZ,\n\n                _to_array(mcluts.CASESCLASSIC), _to_array(mcluts.CASES),\n\n                _to_array(mcluts.TILING1), _to_array(mcluts.TILING2), _to_array(mcluts.TILING3_1), _to_array(mcluts.TILING3_2),\n                _to_array(mcluts.TILING4_1), _to_array(mcluts.TILING4_2), _to_array(mcluts.TILING5), _to_array(mcluts.TILING6_1_1),\n                _to_array(mcluts.TILING6_1_2), _to_array(mcluts.TILING6_2), _to_array(mcluts.TILING7_1),\n                _to_array(mcluts.TILING7_2), _to_array(mcluts.TILING7_3), _to_array(mcluts.TILING7_4_1),\n                _to_array(mcluts.TILING7_4_2), _to_array(mcluts.TILING8), _to_array(mcluts.TILING9),\n                _to_array(mcluts.TILING10_1_1), _to_array(mcluts.TILING10_1_1_), _to_array(mcluts.TILING10_1_2),\n                _to_array(mcluts.TILING10_2), _to_array(mcluts.TILING10_2_), _to_array(mcluts.TILING11),\n                _to_array(mcluts.TILING12_1_1), _to_array(mcluts.TILING12_1_1_), _to_array(mcluts.TILING12_1_2),\n                _to_array(mcluts.TILING12_2), _to_array(mcluts.TILING12_2_), _to_array(mcluts.TILING13_1),\n                _to_array(mcluts.TILING13_1_), _to_array(mcluts.TILING13_2), _to_array(mcluts.TILING13_2_),\n                _to_array(mcluts.TILING13_3), _to_array(mcluts.TILING13_3_), _to_array(mcluts.TILING13_4),\n                _to_array(mcluts.TILING13_5_1), _to_array(mcluts.TILING13_5_2), _to_array(mcluts.TILING14),\n\n                _to_array(mcluts.TEST3), _to_array(mcluts.TEST4), _to_array(mcluts.TEST6),\n                _to_array(mcluts.TEST7), _to_array(mcluts.TEST10), _to_array(mcluts.TEST12),\n                _to_array(mcluts.TEST13), _to_array(mcluts.SUBCONFIG13),\n                )\n\n    return mcluts.THE_LUTS\n", "meta": {"hexsha": "163721c247a7efa30132ca2785377d795a20f96b", "size": 9884, "ext": "py", "lang": "Python", "max_stars_repo_path": "skimage/measure/_marching_cubes_lewiner.py", "max_stars_repo_name": "portugueslab/scikit-image", "max_stars_repo_head_hexsha": "0fa3bcb118bb208a0cc7d3e8b96cd96c1ce7a75b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-02-24T02:24:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T11:44:34.000Z", "max_issues_repo_path": "skimage/measure/_marching_cubes_lewiner.py", "max_issues_repo_name": "portugueslab/scikit-image", "max_issues_repo_head_hexsha": "0fa3bcb118bb208a0cc7d3e8b96cd96c1ce7a75b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "skimage/measure/_marching_cubes_lewiner.py", "max_forks_repo_name": "portugueslab/scikit-image", "max_forks_repo_head_hexsha": "0fa3bcb118bb208a0cc7d3e8b96cd96c1ce7a75b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-06-16T06:38:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-19T11:44:48.000Z", "avg_line_length": 43.7345132743, "max_line_length": 131, "alphanum_fraction": 0.6588425739, "include": true, "reason": "import numpy", "num_tokens": 2719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.1947359095582749}}
{"text": "# Copyright (c) 2012-2018, University of Strathclyde\n# Authors: Lawrence T. Campbell\n# License: BSD-3-Clause\n#\n# Python script containing the code to write the input files for \n# Puffin.\n#\n# The three files are:\n#\n#   1) The main input file, describing free parameters and the \n#      integration sampling\n#\n#   2) The beam input file, which can describe multiple electron \n#      beams if necessary\n#\n#   3) The seed input file, which can describe multiple seeds\n#\n# This approach is (hopefully) quite flexible, allowing Puffin to \n# generate a simple, more conventional FEL, or a more esoteric \n# configuration with multiple seeds and electron beams, with different \n# powers, frequencies, energies, and distributions.\n#\n# In addition, for more fun, a lattice file may be constructed to \n# describe a series of undulator modules seperated by chicane/slippage \n# sections and/or quads. The name of this lattice file should be entered\n# in the 'lattfile' variable in the input file. \n#\n#\n#     DESCRIBE UNDULATOR LATTICE FILE\n#\n#\n# Also note that if aw is decreased in an undulator module you should\n# ensure the radiation mesh is fine enough to model the higher frequency\n# content which will arise.\n#\n# The strength of the dispersive chicanes can be given in the 'Dfact' \n# variable in the main input file. Currently, only this one strength \n# factor may be specified which will be shared by all chicanes.\n# \n# An undulator taper can also be added in the main input file.\n# Presently, if a lattice file is used, this taper will be applied\n# to ALL undulator modules, and the taper will be applied to the\n# undulator parameter of each module. Only a linear taper may be\n# supplied.\n# \n# - Lawrence Campbell\n#   University of Strathclyde\n#   July 2013\n\n\n# simple setup\n  # define beam and undulator - frame is assumed the same as the beam and undulator\n  # scale parameters\n\n# - OR - \n\n# advanced setup\n  # define frame\n  # define beam in frame\n    # use same beam as reference beam?\n  # scale parameters\n\nimport math\nimport beamClass\nimport seedClass\nimport fBoolean\nimport numpy as np\n\ntorf = fBoolean.torf\n\npow = math.pow\npi = math.pi\nsqrt = math.sqrt\nlog = math.log\nbm = beamClass.bm\nsd = seedClass.sd\n\n# Physical constants\n\nm_e = 9.109e-31\nq_e = 1.602e-19\neps_0 = 8.85e-12\nc = 2.997924e8\n\n# File names for input files\n\ninputfile = 'example.in'\nbeamfile = 'beam_file.in'\nseedfile = 'seed_file.in'\nlattFile = ''\n\nnbeams = 1\nnseeds = 1\n\n### Sampling\n\nelms_per_wave = 20         # Field nodes per resonant wavelength \nemps_per_wave = 24         # Electron macroparticles per resonant wavelength\nsteps_per_per = 30        # should be roughly 4-5* elms_per_wave\n\n# Undulator and beam parameters\n# Below similar to CLARA parameters\n\nEr = 240e6            # Beam energy (reference particle)\ngamma = Er / ( (m_e * pow(c,2) / q_e) ) # Rel. factor\naw = 1.01               # PEAK wiggler parameter\nlambda_w = 0.0275        # Undulator period\nN_w = 200              # Number of undulator periods\nundtype = 'planepole'\nux = 0\nuy = 1\n\n\n# RMS wiggler param depends on undulator type / polarization:\n\nif (undtype == 'planepole'):\n  ux = 0\n  uy = 1\n  awrms = aw / np.sqrt(2)\n\nelif (undtype == 'curved'):\n  ux = 0\n  uy = 1\n  awrms = aw / np.sqrt(2.)\n\nelif (undtype == 'helical'):\n  ux = 1\n  uy = 1\n  awrms = aw\n\nelse:\n  awrms = aw / np.sqrt(2.) * np.sqrt(ux**2 + uy**2)\n\n\n\nqFlatTopZ2 = np.array([1])         # =1 if flat top current profile, else gaussian.\nqHardEdgeX = np.array([0])         # =1 if disk (circle) in transverse plane, else gaussian.\nqRoundZ2 = np.array([1])           # If rounding off edges of flat top in z2\nsigRound_lam = np.array([6])       # Sigma of gaussian used to round off the flat top edges, in resonant wavelengths\nbEnOscMag = np.array([0])          # Magnitude of oscillation on beam energy | Units of gamma\nbEnOscFr = np.array([7E3])         # Frequency (2pi/lambda, where lambda in units of ct) of oscillation on beam energy \n#E = 300e6            # Beam energy\n#gamma = E / (m_e * pow(c,2)) # Rel. factor\nsig_gamma = np.array([0.0004])      # Energy spread (relative to Er i.e. sig_gam / gamma_r)\n\n\nEj = np.array([240e6])\neratio = Ej / Er # [ij / Er for ij in Ej] # Rel. factor\ngammaj = Ej / ( (m_e * pow(c,2) / q_e) ) # [ij / ( (m_e * pow(c,2) / q_e) ) for ij in Ej] # Rel. factor\nemitx = np.array([1e-6 / gamma])       # Unnormalised Emittance in x\nemity = np.array([1e-6 / gamma])       # Unnormalised Emittance in y\nQ = np.array([0.1e-9])                # Charge\n\n\nk_w = 2 * pi / lambda_w             # Get wiggler wavenumber\nsigt = np.array([250e-15]) # 0.005570423008216 / c        # Get sigma in t dimension\nsigz = c * sigt                     # Convert sigma in t to z\n\n\n\n\n#if \nff = np.sqrt(2)\n\nk_beta = aw * k_w / ( ff * gamma )  # Betatron wavenumber\nN = [ij / q_e for ij in Q]                         # Number of real electrons in pulse\nlambda_r = lambda_w / (2 * np.power(gamma,2)) * (1 + np.power(awrms,2))\n                                    # ^ Resonant wavelength\n\nsigRoundz = sigRound_lam * lambda_r\n\nk_betax = k_beta\nk_betay = k_beta   #...else strong...\n\nalphax = np.array([0.])\nalphay = np.array([0.])\n\n#sigx = np.sqrt(emitx / k_betax)     # Beam standard deviation in x...\n#sigy = np.sqrt(emity / k_betay)     # ...and y\n\nsigx = np.array([50e-6])\nsigy = np.array([50e-6])\n\nsig_av = np.sqrt((np.power(sigx,2) + np.power(sigy,2))/2.0)\n\n\n########################################\n# Beam area and FEL parameter\n\nif qHardEdgeX == 1:\n    r_av = sig_av                 # Hard edged circle in x and y\nelse:\n    r_av = np.sqrt(2.) * sig_av  # Gaussian dist in x and y\n\ntArea = np.pi * np.power(r_av,2)          # Tranverse beam area\n\nif qFlatTopZ2[0] == 1:\n    if qRoundZ2[0] == 1:\n        lArea = np.sqrt(2*pi) * sigRoundz  + sigz     # flat top + gaussian\n    else:\n        lArea = sigz                  # longitudinal integral over charge dist (flat top)\nelse:\n    lArea = sqrt(2*pi) * sigz     # longitudinal integral over charge dist(gaussian)\n\nn_p = N / (tArea * lArea)              # Electron number density\nwp = np.sqrt(np.power(q_e,2) * n_p / (eps_0 * m_e) )         # plasma frequency\n\nrho = 1.0 / gamma * np.power((aw * wp[0] / ( 4.0 * c * k_w )),(2.0/3.0))  # FEL parameter\n\n#######################################\n# Scaled parameters for Puffin\n\n\nlambda_z2 = 4*pi*rho              # Resonant wavelength in z2\nLg = lambda_w / lambda_z2         # Gain length\nLc = lambda_r / lambda_z2         # Cooperation length\nzbarprop = N_w * lambda_z2        # Length of undulator in zbar (gain lengths)\nsigz2 = sigz / Lc                 # Length of pulse in z2 (cooperation lengths)\n\nsigRoundZ2 = sigRoundz / Lc       # Sigma of tail off in z2 (cooperation lengths)\n\nbEnOscFr = bEnOscFr * Lc\n\nbeta = sqrt(np.power(gamma,2) - 1.0 - np.power(awrms,2))/gamma    # Average velocity over c\neta = (1-beta)/beta                                # Scaled average velocity (of reference electron)\n\nk_beta_bar = k_beta * Lg                           # Scaled betatron wavenumber\nemitx_bar = emitx / (rho * Lc)                       # Scaled emittance\nemity_bar = emity / (rho * Lc)                       # Scaled emittance\nZ_R = pi * np.power(r_av,2) / lambda_r                  # Rayleigh range\nZ_bar_R = np.power(r_av,2) / (Lg * Lc) / (4.0 * rho)      # Scaled Rayleigh Range\nB = np.power((2 * Z_bar_R),(3.0/2.0))                       # Saldin diffraction parameter\n\n\nNL = N/sigz2 * lambda_z2                           # electrons per radiation period\n\nAnoise = 6 * sqrt(pi) * rho / (NL * sqrt(log(NL/rho)))  # Spontaneous noise estimate (in scaled units)\nAcse = 16 * np.power(rho,2)                             # CSE estimate for flat-top current\n\n\n###################################################\n\n\nif (undtype == 'planepole'):\n  kbxn = 0.\n  kbyn = aw / 2. / np.sqrt(2) / rho / gamma # 'natural' focusing wavenumber\n\nelif (undtype == 'curved'):\n  kxu = np.sqrt(eta / 8. / rho**2)\n  kyu = np.sqrt(eta / 8. / rho**2)\n  kbxn = aw / np.sqrt(2.*eta) / gamma *kxu\n  kbyn = aw / np.sqrt(2.*eta) / gamma *kyu\n\nelif (undtype == 'helical'):\n  kbxn = aw / 2. / np.sqrt(2) / rho / gamma # 'natural' focusing wavenumber\n  kbyn = aw / 2. / np.sqrt(2) / rho / gamma # 'natural' focusing wavenumber\n\nelse:\n  kbxn = aw / 2. / np.sqrt(2) / rho / gamma # 'natural' focusing wavenumber\n  kbyn = aw / 2. / np.sqrt(2) / rho / gamma # 'natural' focusing wavenumber\n  awrms = aw / np.sqrt(2.) * np.sqrt(ux**2 + uy**2)\n\n\n\n\n\n##################################################\n# Sampling\n\nif qFlatTopZ2[0] == 1:\n    if qRoundZ2[0] == 1:\n        lez2 = (7.5 * sigRoundZ2)  + sigz2     # flat top + gaussian\n    else:\n        lez2     = sigz2       # flat-top\n        sigz2_in = 1.0e8 \nelse:\n    lez2     = 9.*sigz2     # gaussian\n    sigz2_in = sigz2 \n\nlwz2 = 50.0                # Total size of sampled field in z2\nlsys_z2 = lwz2 + lez2[0]      # Total length of sampled system in z2\n\ndz2 = lambda_z2 / elms_per_wave    # Node spacing in z2\nNNodesZ2 = lsys_z2 / dz2 + 1       # Number of radiation field nodes\n\ndz2e = lambda_z2 / emps_per_wave   # Macroparticle spacing in z2\nNMElecsZ2 = lez2 / dz2e            # Number of macroparticles in z2\nNMElecsP2 = 19                     # Number of macroparticles to sample energy spread\n\ndz = lambda_z2 / steps_per_per     # Step size in zbar\nNsteps = zbarprop / dz             # Number of steps\n\n\n###################################################\n# Chirp - 1% per sigma_z\n\ndcgamma = 0.0 # 0.01 * gamma;   # Change in gamma per sigma_z due to chirp\nchirp = -dcgamma / sigz;   # Energy chirp in z\nchirpz2 = Lc * chirp;    # Energy chirp in z2\n\n\n###################################################\n\n# Set up the beam and seed classes, which will contain\n# the data to write in the beam and seed files\n\n#beam = [bm() for ib in range(nbeams)] # list of electron beams\n\n#seeds = [sd() for ic in range(nseeds)] # list of seeds\n\n# Assign electron pulse data to beams\n\n\n\nsigx = sigx / (sqrt(Lg) * sqrt(Lc))\nsigy = sigy / (sqrt(Lg) * sqrt(Lc))\n\nlex = 6.*sigx\nley = 6.*sigy\n\nbeam = bm()\nbeam.nbeams = nbeams\nbeam.bftype = 'simple'\n\nfor ij in range(nbeams):\n  if qFlatTopZ2[ij] == 1:\n      sigz2[ij] = 1e8          # Flat top case\n  else:\n      sigz2[ij] = sigz2[ij]\n      lez2[ij] = sigz2[ij] * 8.\n\nsigpx = np.array([1.])\nsigpy = np.array([1.])\nsiggam = sig_gamma\n\nlepx = 6. * sigpx\nlepy = 6. * sigpy\nlegam = siggam * 7.\n\n\nnmpx = np.array([10])\nnmpy = np.array([10])\nnmpz2 = NMElecsZ2\n\nnmppx = np.array([10])\nnmppy = np.array([10])\nnmpgam = np.array([10])\nqmatch = [False]\ntrloadmeth = (np.array([np.int_(2)]))\nqequixy = [False]\n\nbcenter = np.array([0.0])\n\n\n#beam.sig = np.append(sigx, np.append(sigy, np.append(sigz2, np.append(sigpx, \\\n#                          np.append( sigpy, siggam) ) ) ))\n\n\nbeam.sig = np.concatenate( (sigx, sigy, sigz2, sigpx, sigpy, siggam) )\nbeam.le = np.concatenate( (lex, ley, lez2, lepx, lepy, legam) )\nbeam.nmps = np.int_(np.round(np.concatenate( (nmpx, nmpy, nmpz2, nmppx, nmppy, nmpgam) )))\nbeam.eratio = eratio\nbeam.emitx = emitx\nbeam.emity = emity\nbeam.alphax = alphax\nbeam.alphay = alphay\nbeam.chirp = chirp\nbeam.bcenz2 = bcenter\nbeam.Q = Q\nbeam.qRoundEj = qRoundZ2\nbeam.sigEj = sigRoundZ2\nbeam.bosc_Mag = bEnOscMag\nbeam.bosc_Fr  = bEnOscFr\nbeam.qmatch  = qmatch\nbeam.trload = trloadmeth\n\n\n#beam.sig = sigx + sigy + sigz2 + sigpy + sigpy + siggam\n#beam.le = lex + ley + lez2 + lepy + lepy + legam\n#beam.nmps = nmpx + nmpy + nmpz2 + nmppx + nmppy + nmpgam\n#beam.eratio = eratio\n#beam.emitx = emitx\n#beam.emity = emity\n#beam.emitx = alphax\n#beam.emity = alphay\n#beam.chirp = chirp\n#beam.bcenz2 = bcenter\n#beam.Q = Q\n#beam.qRoundEj = qRoundZ2\n#beam.sigEj = sigRoundZ2\n#beam.bosc_Mag = bEnOscMag\n#beam.bosc_Fr  = bEnOscFr\n#beam.qmatch  = qmatch\n#beam.trload = trloadmeth\n\n\n##################################################\n# Field info\n\nNNodesX = 1 # Next, create a class for the field vars\nNNodesY = 1 # and a routine to write the seed file\n\nlwx = 1E0\nlwy = 1E0\n\nlsys_x = lwx\nlsys_y = lwy\n\nfiltFrac = 0.3\ndiffFrac = 1.0\n\n#################################################\n# Flags\n\nqoned = True\nqfieldevo = True\nqEevolve  = True\nqEFcouple = True\nqFocusing = False\nqMatchedBeam = False\nqDiffraction = False\nqFilter = True\nqNoise = True\nqDump = False\nqResume = False\nqStepFiles = True\nqFormatFiles = True\nqWriteZ = True\nqWriteA = True\nqWritePperp = True\nqWritep2 = True\nqWritez2 = True\nqWritex = True\nqWritey = True\n\n\n########  OTHER DATA TEMP! #################\n\nqScaled = True\nqUndEnds = True\nqFMesh = True\n\ntaper = 0.0\nsZ0 = 0.0\nkbetax_SF = 0.0\nkbetay_SF = 0.0\nwrFile = ''  # 'wr_cl.txt'\nwrFreq_Full = 30\nwrFreq_integrated = 30\n\n\n################################################\n# Write data\n\n# Main input file:\n\nf = open(inputfile, 'w')\n\n\n\n# Header\n\nf.write('! The main input parameters are described below - Puffin takes the namelist blocks at the\\n')\nf.write('! bottom of this file as input. This is the \\'main\\' input file, containing info about the\\n')\nf.write('! wiggler, field sampling, and general flags and other numerical instructions for the\\n')\nf.write('! simulation. This file also points to a beam file, describing the electron beam,\\n')\nf.write('! and optionally, a seed file (describing a radiation seed) and/or a lattice file.\\n')\nf.write('!\\n')\nf.write('!\\n')\n# Options\n\n\nf.write('!                       OPTIONS\\n')\nf.write('!\\n')\nf.write('!\\n')\nf.write('! qOneD                      If TRUE, model 1D FEL, with only 1 node and 1 macroparticle in transverse dimensions\\n')\nf.write('! qFieldEvolve               if letting the radiation field evolve\\n')\nf.write('! qElectronsEvolve           if integrating electron equations\\n')\nf.write('! qElectronFieldCoupling     if allowing field to feedback onto the electron equations\\n')\nf.write('! qFocussing                 if strong intra-undulator focussing is included in the transverse plane\\n')\nf.write('! qMatchedBeam               if matching beam to undulator. If TRUE, electron pulse sigma and length in x,y,px,py are automatically calculated\\n')\nf.write('! qDiffraction               if modelling diffraction\\n')\nf.write('! qFilter                    TRUE to filter, if FALSE the low frequencies will just be ignored during diffraction\\n')\nf.write('! q_noise                    Shot noise in initial electron beam distribution\\n')\nf.write('! qResume                    If resuming from dump files left from a previous run\\n')\nf.write('! qMeasure                   If .TRUE., then use measured FFT plans in FFTW\\n')\nf.write('! qDumpEnd                   If .TRUE., the do full data dump at end of simulation\\n')\nf.write('! qInitWrLat\\n')\nf.write('!\\n')\nf.write('!\\n')\nf.write('!\\n')\nf.write('!\\n')\n\n# Field Sampling\n\nf.write('!                  FIELD MESH DESCRIPTION\\n')\nf.write('!\\n')\nf.write('!\\n')\nf.write('! iNumNodesX               Number of nodes to sample radiation field in x direction\\n')\nf.write('! iNumNodesY               Number of nodes to sample radiation field in y direction\\n')\nf.write('! nodesPerLambdar            Number of nodes per resonant wavelength\\n')\nf.write('! sFModelLengthX             Length of radiation field model in x direction\\n')\nf.write('! sFModelLengthY             Length of radiation field model in y direction\\n')\nf.write('! sWigglerLengthZ2           Length of field model in z2-bar direction\\n')\nf.write('! iRedNodesX                 Length of central field section in x where electrons will not leave\\n')\nf.write('! iRedNodesY                 Length of central field section in y where electrons will not leave\\n')\nf.write('! sFiltFrac                  Specifies cutoff for high pass filter as fraction of resonant frequency - used in diffraction step\\n')\nf.write('! sDiffFrac                  Specifies diffraction step size as fraction of the undulator period\\n')\nf.write('! beta                       Absorption coefficient\\n')\n\nf.write('!\\n')\nf.write('!\\n')\n\n\nf.write('!                  INDEPENDANT VARIABLES\\n')\nf.write('!\\n')\nf.write('!\\n')\nf.write('! Scaled independent vars. These describe the reference beam and undulator \\n')\nf.write('! used for the scaling of the system. \\n')\nf.write('!\\n')\nf.write('!\\n')\nf.write('! srho       Pierce or FEL parameter, describing the strength of the interaction (or efficiency)\\n')\nf.write('! sux        Normalised magnitude of wiggler magnetic field x-vector: H=1 is helical, H=0 is planar\\n')\nf.write('! suy        Normalised magnitude of wiggler magnetic field y-vector: H=1 is helical, H=0 is planar\\n')\nf.write('! saw        peak undulator parameter\\n')\nf.write('! sgamma_r   Resonant, or reference, beam energy\\n')\nf.write('! lambda_w   Undulator period\\n')\n\nf.write('!')\nf.write('!')\nf.write('!                  SIMPLE UNDULATOR SETUP')\nf.write('!')\nf.write('! \\'Quick\\' or \\'simple\\' undulator. If not using a lattice file, then this \\n')\nf.write('! undulator will be used. If a lattice file is used then these parameters \\n')\nf.write('! are ignored.\\n')\nf.write('!')\nf.write('!')\nf.write('! zundType     Undulator type - \\'curved\\' , \\'planepole\\', \\'helical\\' or blank\\n')\nf.write('! taper        gradient of taper - d/dz of alpha\\n')\nf.write('! nPeriods           Number of wiggler periods\\n')\nf.write('! stepsPerPeriod     Number of integration steps per wiggler period\\n')\nf.write('!\\n')\nf.write('!\\n')\nf.write('!                  EXTERNAL FILES\\n')\nf.write('!\\n')\nf.write('! The beam file is required, if not specified then the beam file is\\n')\nf.write('! assumed = \\'beam_file.in\\', which must be in working directory.\\n')\nf.write('!\\n')\nf.write('! beam_file     Name of the beam file\\n')\nf.write('! seed_file     Name of the seed file\\n')\nf.write('! lattFile      Name of lattice file (optional).\\n')\nf.write('! wr_file       Name of the write file (optional).\\n')\n\n\nf.write('!\\n')\nf.write('!\\n')\nf.write('!               DATA WRITING FREQUENCY\\n')\nf.write('!\\n')\nf.write('! iWriteNthSteps     Steps to write data at\\n')\nf.write('! iWriteIntNthSteps  Steps to write integrated data at\\n')\nf.write('! sZ0                Starting zbar position\\n')\n\nf.write('!\\n')\nf.write('!\\n')\nf.write('!  Additional Beam Loading Options... (rarely used!!!) \\n')\nf.write('!\\n')\nf.write('! sPEOut        Percentage of macroparticles to write out\\n')\nf.write('! sEThreshold   Below the threshold level(%) * the average of real electrons are removed(ignored)\\n')\n\nf.write('\\n')\nf.write('\\n')\nf.write('\\n')\nf.write('\\n')\n\nf.write('&MDATA\\n')\nf.write(' qScaled                = ' + torf(qScaled) + '\\n')\nf.write(' qOneD                  = ' + torf(qoned) + '\\n')\nf.write(' qFieldEvolve           = ' + torf(qfieldevo) + '\\n')\nf.write(' qElectronsEvolve       = ' + torf(qEevolve) + '\\n')\nf.write(' qElectronFieldCoupling = ' + torf(qEFcouple) + '\\n')\nf.write(' qFocussing             = ' + torf(qFocusing) + '\\n')\nf.write(' qDiffraction           = ' + torf(qDiffraction) + '\\n')\nf.write(' qUndEnds               = ' + torf(qUndEnds) + '\\n')\nf.write(' qFMesh_G               = ' + torf(qFMesh) + '\\n')\nf.write(' beam_file              = ' +  '\\'' + beamfile + '\\'' + '\\n')\nif (seedfile != ''):\n  f.write(' seed_file              = ' + '\\'' + seedfile + '\\'' + '\\n')\n#f.write(' lattFile               = ' + '\\'' + lattFile + '\\'' + '\\n')\nf.write(' wr_file                = ' + '\\'' + wrFile + '\\'' + '\\n')\n\n\n# Field Mesh:\n\nf.write(' iNumNodesX             = ' + '{:d}'.format(int(math.floor(NNodesX))) + '\\n')\nf.write(' iNumNodesY             = ' + '{:d}'.format(int(math.floor(NNodesY))) + '\\n')\nf.write(' nodesPerLambdar        = ' + '{:d}'.format(int(math.floor(elms_per_wave)))  + '\\n')\nf.write(' sFModelLengthX         = ' + '{:.15E}'.format(lsys_x) + '\\n')\nf.write(' sFModelLengthY         = ' + '{:.15E}'.format(lsys_y) + '\\n')\nf.write(' sFModelLengthZ2        = ' + '{:.15E}'.format(lsys_z2) + '\\n')\nf.write(' iRedNodesX             = ' + '{:d}'.format(1) + '\\n')\nf.write(' iRedNodesY             = ' + '{:d}'.format(1) + '\\n')\nf.write(' sFiltFrac              = ' + '{:.15E}'.format(filtFrac) + '\\n')\nf.write(' sDiffFrac              = ' + '{:.15E}'.format(diffFrac) + '\\n')\nf.write(' sBeta                  = ' + '{:.15E}'.format(0.1) + '\\n')\n\n\n# Scaling parameters - sets up the frame\n\nf.write(' srho                   = ' + '{:.15E}'.format(rho) + '\\n')\nf.write(' saw                    = ' + '{:.15E}'.format(aw) + '\\n')\nf.write(' sgamma_r               = ' + '{:.15E}'.format(gamma) + '\\n')\nf.write(' lambda_w               = ' + '{:.15E}'.format(lambda_w) + '\\n')\nf.write(' zundType               = ' + '\\'' + undtype + '\\'' + '\\n')\n\n# 'base' wiggler - with lambda_w above. Ignored with a lattice file\n\nf.write(' lambda_w               = ' + '{:.15E}'.format(lambda_w) + '\\n')\nf.write(' taper                  = ' + '{:.15E}'.format(taper) + '\\n')\nf.write(' sKBetaXSF              = ' + '{:.15E}'.format(kbetax_SF) + '\\n')\nf.write(' sKBetaYSF              = ' + '{:.15E}'.format(kbetay_SF) + '\\n')\nf.write(' nPeriods               = ' + '{:d}'.format(int(N_w)) + '\\n')\n\n# integration/write options\nf.write(' stepsPerPeriod         = ' + '{:d}'.format(steps_per_per) + '\\n')\nf.write(' sZ0                    = ' + '{:.15E}'.format(sZ0) + '\\n')\nf.write(' iWriteNthSteps         = ' + '{:d}'.format(wrFreq_Full) + '\\n')\nf.write(' iWriteIntNthSteps      = ' + '{:d}'.format(wrFreq_integrated) + '\\n')\nf.write(' /\\n')\n\nf.close()\n\n\nprint 'Main data file written to: ' + inputfile\n\n\n#\n# beam file\n\nf = open(beamfile, 'w')\n\n\n# Write beam files\n\n#for ib in range(nbeams):\n#    beam[ib].wrbeam(f,ib+1)\nbeam.wrbeam(f,1)\nf.close()\n\nprint 'Beam file written to: ' + beamfile\n\n#\n# seed file\n\nif (seedfile != ''):\n\n  seed = sd()\n  f = open(seedfile, 'w')\n\n# Write seed data\n\n  for ic in range(nseeds):\n      seed.wrseed(f,ic+1)\n\n\n  f.close()\n\n  print 'Radiation seed file written to: ' + seedfile\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "b17db0181cc82b80061e70889d4fab822865328d", "size": 21738, "ext": "py", "lang": "Python", "max_stars_repo_path": "utilities/setup/genInputs/write_df.py", "max_stars_repo_name": "mightylorenzo/Puffin", "max_stars_repo_head_hexsha": "6631eb91a5d98d8bc3d40fe9f09b90932f20776a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2017-08-29T10:50:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T07:21:49.000Z", "max_issues_repo_path": "utilities/setup/genInputs/write_df.py", "max_issues_repo_name": "mightylorenzo/Puffin", "max_issues_repo_head_hexsha": "6631eb91a5d98d8bc3d40fe9f09b90932f20776a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2017-06-20T09:40:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-18T22:35:47.000Z", "max_forks_repo_path": "utilities/setup/genInputs/write_df.py", "max_forks_repo_name": "mightylorenzo/Puffin", "max_forks_repo_head_hexsha": "6631eb91a5d98d8bc3d40fe9f09b90932f20776a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2017-06-21T21:00:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T02:15:59.000Z", "avg_line_length": 31.8272327965, "max_line_length": 155, "alphanum_fraction": 0.5997331861, "include": true, "reason": "import numpy", "num_tokens": 6639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.1947359095582749}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2020 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Paul J. Robinson <pjrobinson@ucla.edu>\n#         Qiming Sun <osirpt.sun@gmail.com>\n#\n\n'''\nVasp CHGCAR file format\n\nSee also\nhttps://cms.mpi.univie.ac.at/vasp/vasp/CHGCAR_file.html\n'''\n\nimport sys\nimport collections\nimport time\nimport numpy\nimport pyscf\nfrom pyscf import lib\nfrom pyscf import gto\nfrom pyscf.pbc import gto as pbcgto\nfrom pyscf.tools import cubegen\n\nif sys.version_info >= (3,):\n    unicode = str\n\nRESOLUTION = cubegen.RESOLUTION\nBOX_MARGIN = cubegen.BOX_MARGIN\n\n\ndef density(cell, outfile, dm, nx=60, ny=60, nz=60, resolution=RESOLUTION):\n    '''Calculates electron density and write out in CHGCAR format.\n\n    Args:\n        cell : Mole or Cell object\n            Mole or pbc Cell. If Mole object is given, the program will guess\n            a cubic lattice for the molecule.\n        outfile : str\n            Name of Cube file to be written.\n        dm : ndarray\n            Density matrix of molecule.\n\n    Kwargs:\n        nx : int\n            Number of grid point divisions in x direction.\n            Note this is function of the molecule's size; a larger molecule\n            will have a coarser representation than a smaller one for the\n            same value.\n        ny : int\n            Number of grid point divisions in y direction.\n        nz : int\n            Number of grid point divisions in z direction.\n\n    Returns:\n        No return value. This function outputs a VASP chgcarlike file\n        (with phase if desired)...it can be opened in VESTA or VMD or\n        many other softwares\n    \n    Examples:\n\n        >>> # generates the first MO from the list of mo_coefficents \n        >>> from pyscf.pbc import gto, scf\n        >>> from pyscf.tools import chgcar\n        >>> cell = gto.M(atom='H 0 0 0; H 0 0 1', a=numpy.eye(3)*3)\n        >>> mf = scf.RHF(cell).run()\n        >>> chgcar.density(cell, 'h2.CHGCAR', mf.make_rdm1())\n\n    '''\n    cc = CHGCAR(cell, nx=nx, ny=ny, nz=nz, resolution=resolution)\n\n    coords = cc.get_coords()\n    ngrids = cc.get_ngrids()\n    blksize = min(8000, ngrids)\n    rho = numpy.empty(ngrids)\n    for ip0, ip1 in lib.prange(0, ngrids, blksize):\n        if isinstance(cell, pbcgto.cell.Cell):\n            ao = cell.pbc_eval_gto('GTOval', coords[ip0:ip1])\n        else:\n            ao = cell.eval_gto('GTOval', coords[ip0:ip1])\n        rho[ip0:ip1] = lib.einsum('pi,ij,pj->p', ao, dm, ao)\n    rho = rho.reshape(nx,ny,nz)\n\n    cc.write(rho, outfile)\n\n\ndef orbital(cell, outfile, coeff, nx=60, ny=60, nz=60, resolution=RESOLUTION):\n    '''Calculate orbital value on real space grid and write out in\n    CHGCAR format.\n\n    Args:\n        cell : Mole or Cell object\n            Mole or pbc Cell. If Mole object is given, the program will guess\n            a cubic lattice for the molecule.\n        outfile : str\n            Name of Cube file to be written.\n        dm : ndarray\n            Density matrix of molecule.\n\n    Kwargs:\n        nx : int\n            Number of grid point divisions in x direction.\n            Note this is function of the molecule's size; a larger molecule\n            will have a coarser representation than a smaller one for the\n            same value.\n        ny : int\n            Number of grid point divisions in y direction.\n        nz : int\n            Number of grid point divisions in z direction.\n\n    Returns:\n        No return value. This function outputs a VASP chgcarlike file\n        (with phase if desired)...it can be opened in VESTA or VMD or\n        many other softwares\n    \n    Examples:\n\n        >>> # generates the first MO from the list of mo_coefficents \n        >>> from pyscf.pbc import gto, scf\n        >>> from pyscf.tools import chgcar\n        >>> cell = gto.M(atom='H 0 0 0; H 0 0 1', a=numpy.eye(3)*3)\n        >>> mf = scf.RHF(cell).run()\n        >>> chgcar.orbital(cell, 'h2_mo1.CHGCAR', mf.mo_coeff[:,0])\n\n    '''\n    cc = CHGCAR(cell, nx=nx, ny=ny, nz=nz, resolution=resolution)\n\n    coords = cc.get_coords()\n    ngrids = cc.get_ngrids()\n    blksize = min(8000, ngrids)\n    orb_on_grid = numpy.empty(ngrids)\n    for ip0, ip1 in lib.prange(0, ngrids, blksize):\n        if isinstance(cell, pbcgto.cell.Cell):\n            ao = cell.pbc_eval_gto('GTOval', coords[ip0:ip1])\n        else:\n            ao = cell.eval_gto('GTOval', coords[ip0:ip1])\n        orb_on_grid[ip0:ip1] = numpy.dot(ao, coeff)\n    orb_on_grid = orb_on_grid.reshape(nx,ny,nz)\n\n    cc.write(orb_on_grid, outfile, comment='Orbital value in real space (1/Bohr^3)')\n\n\nclass CHGCAR(cubegen.Cube):\n    '''  Read-write of the Vasp CHGCAR files  '''\n    def __init__(self, cell, nx=60, ny=60, nz=60, resolution=RESOLUTION,\n                 margin=BOX_MARGIN):\n        if not isinstance(cell, pbcgto.cell.Cell):\n            coord = cell.atom_coords()\n            box = numpy.max(coord,axis=0) - numpy.min(coord,axis=0) + margin*2\n            boxorig = numpy.min(coord,axis=0) - margin\n            if resolution is not None:\n                nx, ny, nz = numpy.ceil(box / resolution).astype(int)\n            self.box = numpy.diag(box)\n            lib.logger.warn(cell, 'Molecular system is found. FFT-grid is not '\n                            'available for Molecule. Lattice (in Bohr)\\n'\n                            '%s\\nand FFT grids %s are applied.',\n                            self.box, (nx,ny,nz))\n            self.mol = cell\n            cell = cell.view(pbcgto.Cell)\n            if (isinstance(cell.unit, (str, unicode)) and\n                cell.unit.startswith(('B','b','au','AU'))):\n                cell.a = self.box\n            else:\n                cell.a = self.box * lib.param.BOHR\n            ptr = cell._atm[:,gto.PTR_COORD]\n            cell._env[ptr+0] = coord[:,0] - boxorig[0]\n            cell._env[ptr+1] = coord[:,1] - boxorig[1]\n            cell._env[ptr+2] = coord[:,2] - boxorig[2]\n\n        self.nx = nx\n        self.ny = ny\n        self.nz = nz\n        self.cell = cell\n        self.box = cell.lattice_vectors()\n        self.boxorig = numpy.zeros(3)\n        self.vol = cell.vol\n\n    def get_coords(self) :\n        \"\"\"  Result: set of coordinates to compute a field which is to be stored\n        in the file.\n        \"\"\"\n        xs = numpy.arange(self.nx) * (1./self.nx)\n        ys = numpy.arange(self.ny) * (1./self.ny)\n        zs = numpy.arange(self.nz) * (1./self.nz)\n        xyz = lib.cartesian_prod((xs, ys, zs))\n        coords = numpy.dot(xyz, self.box)\n        return numpy.asarray(coords, order='C')\n\n    def write(self, field, fname, comment=None):\n        \"\"\"  Result: .vasp file with the field in the file fname.  \"\"\"\n        assert(field.ndim == 3)\n        assert(field.shape == (self.nx, self.ny, self.nz))\n        if comment is None:\n            comment = 'VASP file: Electron density in real space (e/Bohr^3)  '\n\n        cell = self.cell\n\n        # See CHGCAR format https://cms.mpi.univie.ac.at/vasp/vasp/CHGCAR_file.html\n        # the value of (total density * volume) was dumped\n        field = field * self.vol\n\n        boxA = self.box * lib.param.BOHR\n        atomList= [cell.atom_pure_symbol(i) for i in range(cell.natm)]\n        Axyz = zip(atomList, cell.atom_coords().tolist())\n        Axyz = sorted(Axyz, key = lambda x: x[0])\n        swappedCoords = [(vec[1]+self.boxorig) * lib.param.BOHR for vec in Axyz]\n        vaspAtomicInfo = collections.Counter([xyz[0] for xyz in Axyz])\n        vaspAtomicInfo = sorted(vaspAtomicInfo.items())\n        with open(fname, 'w') as f:\n            f.write(comment)\n            f.write('PySCF Version: %s  Date: %s\\n' % (pyscf.__version__, time.ctime()))\n            f.write('1.0000000000\\n')\n            f.write('%14.8f %14.8f %14.8f \\n' % (boxA[0,0],boxA[0,1],boxA[0,2]))\n            f.write('%14.8f %14.8f %14.8f \\n' % (boxA[1,0],boxA[1,1],boxA[1,2]))\n            f.write('%14.8f %14.8f %14.8f \\n' % (boxA[2,0],boxA[2,1],boxA[2,2]))\n            f.write(''.join(['%5.3s'%atomN[0] for atomN in vaspAtomicInfo]) + '\\n')\n            f.write(''.join(['%5d'%atomN[1] for atomN in vaspAtomicInfo]) + '\\n')\n            f.write('Cartesian \\n')\n            for ia in range(cell.natm):\n                f.write(' %14.8f %14.8f %14.8f\\n' % tuple(swappedCoords[ia]))\n            f.write('\\n')\n            f.write('%6.5s %6.5s %6.5s \\n' % (self.nx,self.ny,self.nz))\n            fmt = ' %14.8e '\n            for iz in range(self.nz):\n                for iy in range(self.ny):\n                    f.write('\\n')\n                    for ix in range(self.nx):\n                        f.write(fmt % field[ix,iy,iz])\n\n    def read(self, chgcar_file):\n        raise NotImplementedError\n\n\nif __name__ == '__main__':\n    from pyscf.pbc import scf\n    from pyscf.tools import chgcar\n    cell = gto.M(atom='H 0 0 0; H 0 0 1', a=numpy.eye(3)*3)\n    mf = scf.RHF(cell).run()\n    chgcar.density(cell, 'h2.CHGCAR', mf.make_rdm1()) #makes total density\n    chgcar.orbital(cell, 'h2_mo1.CHGCAR', mf.mo_coeff[:,0]) # makes mo#1 (sigma)\n    chgcar.orbital(cell, 'h2_mo2.CHGCAR', mf.mo_coeff[:,1]) # makes mo#2 (sigma*)\n\n", "meta": {"hexsha": "c320bf94cacb938e6643435ba4a8f63afab32487", "size": 9588, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/tools/chgcar.py", "max_stars_repo_name": "mfkasim1/pyscf", "max_stars_repo_head_hexsha": "7be5e015b2b40181755c71d888449db936604660", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-12T11:55:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T11:55:25.000Z", "max_issues_repo_path": "pyscf/tools/chgcar.py", "max_issues_repo_name": "mfkasim1/pyscf", "max_issues_repo_head_hexsha": "7be5e015b2b40181755c71d888449db936604660", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2018-08-22T19:44:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-09T10:02:36.000Z", "max_forks_repo_path": "pyscf/tools/chgcar.py", "max_forks_repo_name": "mfkasim1/pyscf", "max_forks_repo_head_hexsha": "7be5e015b2b40181755c71d888449db936604660", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-02-14T16:28:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-12T16:40:30.000Z", "avg_line_length": 37.6, "max_line_length": 88, "alphanum_fraction": 0.5887567793, "include": true, "reason": "import numpy", "num_tokens": 2724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.36658974324230986, "lm_q1q2_score": 0.19473590779299363}}
{"text": "\"\"\" Function that adds common arguments for all input formats to the argument parser handle. \"\"\"\n\n\nimport os\n\nimport numpy as np\n\nfrom wmpl.Trajectory.Trajectory import Trajectory\nfrom wmpl.Trajectory.GuralTrajectory import GuralTrajectory\nfrom wmpl.Utils.TrajConversions import J2000_JD, jd2Date, equatorialCoordPrecession_vect, raDec2AltAz_vect\n\n\n\nclass MeteorObservation(object):\n    \"\"\" Container for meteor observations. \n        \n        The points in arrays are RA and Dec in J2000 epoch, in radians.\n\n        Arguments:\n            jdt_ref: [float] Reference Julian date when the relative time is t = 0s.\n            station_id: [str] Station ID.\n            latitude: [float] Latitude +N in radians.\n            longitude: [float] Longitude +E in radians.\n            height: [float] Elevation above sea level (MSL) in meters.\n            fps: [float] Frames per second.\n\n        Keyword arguments:\n            ff_name: [str] Name of the originating FF file.\n\n    \"\"\"\n    def __init__(self, jdt_ref, station_id, latitude, longitude, height, fps, ff_name=None):\n\n        self.jdt_ref = jdt_ref\n        self.station_id = station_id\n        self.latitude = latitude\n        self.longitude = longitude\n        self.height = height\n        self.fps = fps\n\n        self.ff_name = ff_name\n\n        self.frames = []\n        self.time_data = []\n        self.x_data = []\n        self.y_data = []\n        self.azim_data = []\n        self.elev_data = []\n        self.ra_data = []\n        self.dec_data = []\n        self.mag_data = []\n        self.abs_mag_data = []\n\n\n\n    def addPoint(self, frame_n, x, y, azim, elev, ra, dec, mag):\n        \"\"\" Adds the measurement point to the meteor.\n\n        Arguments:\n            frame_n: [flaot] Frame number from the reference time.\n            x: [float] X image coordinate.\n            y: [float] X image coordinate.\n            azim: [float] Azimuth, J2000 in degrees.\n            elev: [float] Elevation angle, J2000 in degrees.\n            ra: [float] Right ascension, J2000 in degrees.\n            dec: [float] Declination, J2000 in degrees.\n            mag: [float] Visual magnitude.\n\n        \"\"\"\n\n        self.frames.append(frame_n)\n\n        # Calculate the time in seconds w.r.t. to the reference JD\n        point_time = float(frame_n)/self.fps\n\n        self.time_data.append(point_time)\n\n        self.x_data.append(x)\n        self.y_data.append(y)\n\n        # Angular coordinates converted to radians\n        self.azim_data.append(np.radians(azim))\n        self.elev_data.append(np.radians(elev))\n        self.ra_data.append(np.radians(ra))\n        self.dec_data.append(np.radians(dec))\n        self.mag_data.append(mag)\n\n\n\n    def finish(self):\n        \"\"\" When the initialization is done, convert data lists to numpy arrays. \"\"\"\n\n        self.frames = np.array(self.frames)\n        self.time_data = np.array(self.time_data)\n        self.x_data = np.array(self.x_data)\n        self.y_data = np.array(self.y_data)\n        self.azim_data = np.array(self.azim_data)\n        self.elev_data = np.array(self.elev_data)\n        self.ra_data = np.array(self.ra_data)\n        self.dec_data = np.array(self.dec_data)\n        self.mag_data = np.array(self.mag_data)\n\n        # Sort by frame\n        temp_arr = np.c_[self.frames, self.time_data, self.x_data, self.y_data, self.azim_data, \\\n        self.elev_data, self.ra_data, self.dec_data, self.mag_data]\n        temp_arr = temp_arr[np.argsort(temp_arr[:, 0])]\n        self.frames, self.time_data, self.x_data, self.y_data, self.azim_data, self.elev_data, self.ra_data, \\\n            self.dec_data, self.mag_data = temp_arr.T\n\n\n\n\n    def __repr__(self):\n\n        out_str = ''\n\n        out_str += 'Station ID = ' + str(self.station_id) + '\\n'\n        out_str += 'JD ref = {:f}'.format(self.jdt_ref) + '\\n'\n        out_str += 'DT ref = {:s}'.format(jd2Date(self.jdt_ref, \\\n            dt_obj=True).strftime(\"%Y/%m/%d-%H%M%S.%f\")) + '\\n'\n        out_str += 'Lat = {:f}, Lon = {:f}, Ht = {:f} m'.format(np.degrees(self.latitude), \n            np.degrees(self.longitude), self.height) + '\\n'\n        out_str += 'FPS = {:f}'.format(self.fps) + '\\n'\n\n        out_str += 'Points:\\n'\n        out_str += 'Time, X, Y, azimuth, elevation, RA, Dec, Mag:\\n'\n\n        for point_time, x, y, azim, elev, ra, dec, mag in zip(self.time_data, self.x_data, self.y_data, \\\n            self.azim_data, self.elev_data, self.ra_data, self.dec_data, self.mag_data):\n\n            if mag is None:\n                mag = 0\n\n            out_str += '{:.4f}, {:.2f}, {:.2f}, {:.2f}, {:.2f}, {:.2f}, {:+.2f}, {:.2f}\\n'.format(point_time,\\\n                x, y, np.degrees(azim), np.degrees(elev), np.degrees(ra), np.degrees(dec), mag)\n\n\n        return out_str\n\n\n\ndef prepareObservations(meteor_list):\n    \"\"\" Takes a list of MeteorObservation objects, normalizes all data points to the same reference Julian \n        date, precesses the observations from J2000 to the epoch of date. \n    \n    Arguments:\n        meteor_list: [list] List of MeteorObservation objects\n\n    Return:\n        (jdt_ref, meteor_list):\n            - jdt_ref: [float] reference Julian date for which t = 0\n            - meteor_list: [list] A list a MeteorObservations whose time is normalized to jdt_ref, and are\n                precessed to the epoch of date\n\n    \"\"\"\n\n    if meteor_list:\n\n        # The reference meteor is the one with the first time of the first frame\n        ref_ind = np.argmin([met.jdt_ref + met.time_data[0]/86400.0 for met in meteor_list])\n        tsec_delta = meteor_list[ref_ind].time_data[0] \n        jdt_delta = tsec_delta/86400.0\n\n\n        ### Normalize all times to the beginning of the first meteor\n\n        # Apply the normalization to the reference meteor\n        meteor_list[ref_ind].jdt_ref += jdt_delta\n        meteor_list[ref_ind].time_data -= tsec_delta\n\n\n        meteor_list_tcorr = []\n\n        for i, meteor in enumerate(meteor_list):\n\n            # Only correct non-reference meteors\n            if i != ref_ind:\n\n                # Calculate the difference between the reference and the current meteor\n                jdt_diff = meteor.jdt_ref - meteor_list[ref_ind].jdt_ref\n                tsec_diff = jdt_diff*86400.0\n\n                # Normalize all meteor times to the same reference time\n                meteor.jdt_ref -= jdt_diff\n                meteor.time_data += tsec_diff\n\n            meteor_list_tcorr.append(meteor)\n\n        ######\n\n        # The reference JD for all meteors is thus the reference JD of the first meteor\n        jdt_ref = meteor_list_tcorr[ref_ind].jdt_ref\n\n\n        ### Precess observations from J2000 to the epoch of date\n        meteor_list_epoch_of_date = []\n        for meteor in meteor_list_tcorr:\n\n            jdt_ref_vect = np.zeros_like(meteor.ra_data) + jdt_ref\n\n            # Precess from J2000 to the epoch of date\n            ra_prec, dec_prec = equatorialCoordPrecession_vect(J2000_JD.days, jdt_ref_vect, meteor.ra_data, \n                meteor.dec_data)\n\n            meteor.ra_data = ra_prec\n            meteor.dec_data = dec_prec\n\n            # Convert preccesed Ra, Dec to altitude and azimuth\n            meteor.azim_data, meteor.elev_data = raDec2AltAz_vect(meteor.ra_data, meteor.dec_data, jdt_ref,\n                meteor.latitude, meteor.longitude)\n\n            meteor_list_epoch_of_date.append(meteor)\n\n\n        ######\n\n\n        return jdt_ref, meteor_list_epoch_of_date\n\n    else:\n        return None, None\n\n\n\ndef solveTrajectoryGeneric(jdt_ref, meteor_list, dir_path, solver='original', **kwargs):\n    \"\"\" Feed the list of meteors in the trajectory solver and run it. \n    \n    Arguments:\n        jdt_ref: [float] Reference Julian date for all objects in meteor_list.\n        meteor_list: [list] A list of MeteorObservation objects.\n        dir_path: [str] Path to the data directory.\n\n    Keyword arguments:\n        solver: [str] Solver choice:\n            - \"original\" is the Monte Carlo solver\n            - \"gural\" is the Gural solver (through C++ bindings)\n        **kwargs: Keyword arguments for the trajectory solver.\n\n    \"\"\"\n\n    # Create name of output directory\n    output_dir = os.path.join(dir_path, jd2Date(jdt_ref, dt_obj=True).strftime(\"%Y%m%d-%H%M%S.%f\"))\n\n\n    # Init the trajectory solver\n    if solver == 'original':\n        traj = Trajectory(jdt_ref, output_dir=output_dir, meastype=1, **kwargs)\n\n    elif solver.lower().startswith('gural'):\n        velmodel = solver.lower().strip('gural')\n        if len(velmodel) == 1:\n            velmodel = int(velmodel)\n        else:\n            velmodel = 0\n\n        traj = GuralTrajectory(len(meteor_list), jdt_ref, velmodel=velmodel, meastype=1, verbose=1, \n            output_dir=output_dir)\n\n    else:\n        print('No such solver:', solver)\n        return \n\n\n    # Add meteor observations to the solver\n    for meteor in meteor_list:\n\n        if solver == 'original':\n\n            comment = ''\n            if hasattr(meteor, \"ff_name\"):\n                comment = meteor.ff_name\n\n            traj.infillTrajectory(meteor.ra_data, meteor.dec_data, meteor.time_data, meteor.latitude, \n                meteor.longitude, meteor.height, station_id=meteor.station_id, \\\n                magnitudes=meteor.mag_data, comment=comment)\n\n        elif solver.lower().startswith('gural'):\n\n            # Extract velocity model is given\n            try:\n                velmodel = int(solver[-1])\n\n            except: \n                # Default to the exponential model\n                velmodel = 3\n\n            traj.infillTrajectory(meteor.ra_data, meteor.dec_data, meteor.time_data, meteor.latitude, \n                meteor.longitude, meteor.height)\n\n\n    # Solve the trajectory\n    traj = traj.run()\n\n    return traj\n\n\n\ndef addSolverOptions(arg_parser, skip_velpart=False):\n    \"\"\" Adds common arguments for all input formats to the argument parser handle. \"\"\"\n\n    arg_parser.add_argument('-s', '--solver', metavar='SOLVER', help=\"\"\"Trajectory solver to use. \\n\n        - 'original' - Monte Carlo solver\n        - 'gural0' - Gural constant velocity\n        - 'gural1' - Gural linear deceleration\n        - 'gural2' - Gural quadratic deceleration\n        - 'gural3' - Gural exponential deceleration\n         \"\"\", type=str, nargs='?', default='original')\n\n    arg_parser.add_argument('-t', '--maxtoffset', metavar='MAX_TOFFSET', nargs=1, \\\n        help='Maximum time offset between the stations.', type=float)\n\n    arg_parser.add_argument('-v', '--vinitht', metavar='V_INIT_HT', nargs=1, \\\n        help='The initial veloicty will be estimated as the average velocity above this height (in km). If not given, the initial velocity will be estimated using the sliding fit which can be controlled with the --velpart option.', \\\n        type=float)\n\n    if not skip_velpart:\n        arg_parser.add_argument('-p', '--velpart', metavar='VELOCITY_PART', \\\n            help='Fixed part from the beginning of the meteor on which the initial velocity estimation using the sliding fit will start. Default is 0.25 (25 percent), but for noisier data this might be bumped up to 0.5.', \\\n            type=float, default=0.25)\n\n    arg_parser.add_argument('-d', '--disablemc', \\\n        help='Do not use the Monte Carlo solver, but only run the geometric solution.', action=\"store_true\")\n\n    arg_parser.add_argument('-e', '--notimefit', \\\n        help=\"Do not estimate timing and velocity together. The times are assumed to be fixed. A list of time offsets per station can be provided, e.g. \\\"'CA001A':0.42,'CA0005':-0.3\\\" for speciflying offsets of 0.42 and -0.3 seconds for stations CA001A and CA0005, respectively. Make sure there are no spaces between the arguments, although spaces are fine in the station name.\", \\\n        type=str, nargs=\"?\", default=True)\n    \n    arg_parser.add_argument('-r', '--mcruns', metavar=\"MC_RUNS\", \\\n        help='Number of Monte Carlo runs.', type=int, default=100)\n\n    arg_parser.add_argument('-u', '--uncertgeom', \\\n        help='Compute purely geometric uncertainties.', action=\"store_true\")\n\n    arg_parser.add_argument('-m', '--mcstd', metavar='MC_STDDEVS', \\\n        help='Standard deviations of noise to add to measurements during the Monte Carlo procedure. 1.0 by default.', \\\n        type=float, default=1.0)\n    \n    arg_parser.add_argument('-g', '--disablegravity', \\\n        help='Disable gravity compensation.', action=\"store_true\")\n\n    arg_parser.add_argument('-l', '--plotallspatial', \\\n        help='Plot a collection of plots showing the residuals vs. time, lenght and height.', \\\n        action=\"store_true\")\n\n    arg_parser.add_argument('-j', '--jacchia', \\\n        help='Show the Jacchia exponential deceleration fit on plots with the dynamics.', \\\n        action=\"store_true\")\n\n    arg_parser.add_argument('-i', '--imgformat', metavar='IMG_FORMAT', nargs=1, \\\n        help=\"Plot image format. 'png' by default, can be 'pdf', 'eps',... \", type=str, default='png')\n\n    arg_parser.add_argument('-x', '--hideplots', \\\n        help=\"Don't show generated plots on the screen, just save them to disk.\", action=\"store_true\")\n\n\n    return arg_parser", "meta": {"hexsha": "4cf0680573d3fdda0b1bebaae23cc43f45419ec0", "size": 13062, "ext": "py", "lang": "Python", "max_stars_repo_path": "wmpl/Formats/GenericFunctions.py", "max_stars_repo_name": "markmac99/WesternMeteorPyLib", "max_stars_repo_head_hexsha": "c5104974c3f1e2259b0d0ea63a9bbaa15d236be2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "wmpl/Formats/GenericFunctions.py", "max_issues_repo_name": "markmac99/WesternMeteorPyLib", "max_issues_repo_head_hexsha": "c5104974c3f1e2259b0d0ea63a9bbaa15d236be2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wmpl/Formats/GenericFunctions.py", "max_forks_repo_name": "markmac99/WesternMeteorPyLib", "max_forks_repo_head_hexsha": "c5104974c3f1e2259b0d0ea63a9bbaa15d236be2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7943661972, "max_line_length": 381, "alphanum_fraction": 0.6276221099, "include": true, "reason": "import numpy", "num_tokens": 3177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.19473590411694508}}
{"text": "from torch.utils.data import Dataset, DataLoader\nimport os,glob,random,cv2,json,torch,util,cv2,h5py,math\nimport numpy as np\nimport config as cfg\nfrom SMPL_layer import SMPL_Layer\n\nclass Surreal(Dataset):\n    # Note for the surreal data\n    # The 3D keyps (in world frame), after aligning\n    # by pelvis, match the output of smpl(theta,beta),\n    # where (theta,beta) are the smpl params given in\n    # in the world frame\n    def __init__(self,phase):\n        self.dataPhase=phase #\"train\", \"val\", or \"test\"\n        self.pathPrefix=\"/data/cmu/extracted/data/{}\".format(self.dataPhase)\n        self.normalize=True\n        self.cropSize=cfg.surrealCropSize\n        self.pixFormat=\"NCHW\"\n        self.cameraSpace=cfg.surrealCameraSpace\n        self.loadData()\n\n    def pathFilter(self,rgbP,depthP):\n        s1=rgbP.split(\"rgb\")\n        s2=depthP.split(\"depth\")\n        check1=s1[0]==s2[0]\n        s11=s1[1].split(\".\")\n        s22=s2[1].split(\".\")\n        check2=s11[0]==s22[0]\n        if check1 and check2:\n            return True\n        else:\n            return False\n\n    def swapRightLeftPose(self,pose):\n        swapInds = np.array([\n                0, 1, 2, 6, 7, 8, 3, 4, 5, 9, 10, 11, 15, 16, 17, 12, 13, 14, 18,\n                19, 20, 24, 25, 26, 21, 22, 23, 27, 28, 29, 33, 34, 35, 30, 31, 32,\n                36, 37, 38, 42, 43, 44, 39, 40, 41, 45, 46, 47, 51, 52, 53, 48, 49,\n                50, 57, 58, 59, 54, 55, 56, 63, 64, 65, 60, 61, 62, 69, 70, 71, 66,\n                67, 68\n            ], np.int32)\n\n        signFlip = np.array([   \n                    1, 1, 1, 1, -1, -1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1\n                ], dtype=pose.dtype)\n\n        newPose=np.take(pose,swapInds)*signFlip\n\n        return newPose\n\n    def swapRightLeftJoints(self,joints):\n        assert joints.shape[1] == 24\n        swapInds = np.array([0, 2, 1, 3, 5, 4, 6, 8, 7, 9, 11,10,12,14,13, 15, 17,16, 19,18,21,20,23,22], np.int32)\n        jointsSwap=np.take(joints,swapInds,axis=1)\n        return jointsSwap\n    \n    def loadData(self):\n        self.keyps2d=[]\n        self.keyps3d=[]\n        self.smplShapeParams=[]\n        self.smplPoseParams=[]\n        self.rgbImages=[]\n        self.depthImages=[]\n        self.zrot=[]\n        self.camLoc=[]\n        self.gender=[]\n\n\n        fp=h5py.File(cfg.pathToSurreal+self.pathPrefix+\"/annot.h5\",\"r\")\n        keyps2d=np.array(fp[\"gt2d\"])\n        keyps3d=np.array(fp[\"gt3d\"])\n        smplShapeParams=np.array(fp[\"shape\"])\n        smplPoseParams=np.array(fp[\"pose\"])\n        rgbImages=np.array(fp[\"imageNameRGB\"])\n        depthImages=np.array(fp[\"imageNameDepth\"])\n        camLoc=np.array(fp[\"camLoc\"])\n        zRot=np.array(fp[\"zRot\"])\n        gender=np.array(fp[\"gender\"])\n        nData=min(len(rgbImages),len(depthImages))\n\n        for idx in range(1000): #range(nData):\n            #idx=3764   #2586 #1987\n            currRgbPath=rgbImages[idx]\n            currDepthPath=depthImages[idx]\n            ret=self.pathFilter(currRgbPath,currDepthPath)\n            if ret:\n                fullRgbImgPath=cfg.pathToSurreal+self.pathPrefix+currRgbPath\n                fullDepthImgPath=cfg.pathToSurreal+self.pathPrefix+currDepthPath\n                if (not os.path.isfile(fullRgbImgPath)) or (not os.path.isfile(fullDepthImgPath)):\n                    continue\n                if np.any(keyps2d[:,:,idx]<0):\n                    continue\n                # check if all zero depth, if so remove\n                tmp=np.load(fullDepthImgPath)\n                loc=tmp!=float(1e10)\n                if np.min(tmp)==np.max(tmp):\n                    continue\n                if np.min(tmp[loc])==np.max(tmp[loc]):\n                    continue\n                if gender[idx][0]==1:\n                    continue\n                self.keyps2d.append(keyps2d[:,:,idx])\n                self.keyps3d.append(keyps3d[:,:,idx])\n                self.smplShapeParams.append(smplShapeParams[idx])\n                self.smplPoseParams.append(smplPoseParams[idx])\n                self.rgbImages.append(fullRgbImgPath)\n                self.depthImages.append(fullDepthImgPath)\n                self.zrot.append(zRot[idx,0])\n                self.camLoc.append(camLoc[idx,:])\n                self.gender.append(gender[idx])\n\n        assert(len(self.keyps2d)==len(self.keyps3d)) \n        assert(len(self.keyps2d)==len(self.smplShapeParams)) \n        assert(len(self.keyps2d)==len(self.smplPoseParams)) \n        assert(len(self.keyps2d)==len(self.rgbImages))\n        assert(len(self.keyps2d)==len(self.depthImages))\n        assert(len(self.keyps2d)==len(self.zrot))\n        assert(len(self.keyps2d)==len(self.camLoc))\n        assert(len(self.keyps2d)==len(self.gender))\n\n    def normalizeDepth(self,depthImg):\n        loc=depthImg!=float(1e10)\n        normDepth=depthImg\n        normDepth[loc]=(depthImg[loc]-np.min(depthImg[loc]))/(np.max(depthImg[loc])-np.min(depthImg[loc]))\n        normDepth[~loc]=0\n\n        return normDepth\n\n    def __len__(self):\n        return len(self.rgbImages)\n\n    def __getitem__(self,index):\n        rgbImg=cv2.imread(self.rgbImages[index])\n        keyps2d=self.keyps2d[index].copy()\n        \n        \"\"\"# plot points on image and save\n        imgVis=rgbImg\n        for r in range(len(keyps2d[0])):\n            currX=int(keyps2d[0][r])\n            currY=int(keyps2d[1][r])\n            cv2.circle(imgVis,(currX,currY),2,(0,0,255),4)\n        cv2.imwrite(\"/mnt/data/tmp/tmp/tmpKeyps1.png\",imgVis)\"\"\"\n\n        keyps2d[0]=[x*(1.0*self.cropSize/rgbImg.shape[1]) for x in keyps2d[0]]\n        keyps2d[1]=[x*(1.0*self.cropSize/rgbImg.shape[0]) for x in keyps2d[1]]\n        keyps2d/=self.cropSize\n        keyps2d=np.asarray(keyps2d)\n        resImg=cv2.resize(rgbImg,(self.cropSize,self.cropSize),interpolation=cv2.INTER_CUBIC)\n        resImg=util.convert_image_by_pixformat_normalize(resImg,self.pixFormat,self.normalize)\n        #resImg=rgbImg\n\n        depthImg=self.normalizeDepth(np.load(self.depthImages[index]))\n        #depthImg=cv2.resize(depthImg,(self.cropSize,self.cropSize),interpolation=cv2.INTER_NEAREST)\n        depthImg=cv2.resize(depthImg,(self.cropSize,self.cropSize))\n        depthImgCh=np.zeros((3,depthImg.shape[0],depthImg.shape[1]))\n        depthImgCh[0,:,:]=depthImg\n        depthImgCh[1,:,:]=depthImg\n        depthImgCh[2,:,:]=depthImg\n        keyps3d=self.keyps3d[index].copy()\n        keyps3d=np.asarray(keyps3d)\n        keyps3dw=keyps3d.copy()\n\n        shape,pose=self.smplShapeParams[index].copy(),self.smplPoseParams[index].copy()\n        currCamLoc=self.camLoc[index].copy()\n        currExtrinsic,currR,currT=util.getSurrealExtrinsic(np.expand_dims(np.transpose(currCamLoc),axis=1))\n        currZRot=self.zrot[index].copy()\n        RzBody=np.array(((math.cos(currZRot),-math.sin(currZRot),0),(math.sin(currZRot),math.cos(currZRot),0),(0,0,1)))        \n        pose[0:3]=util.rotateBodyForVisSurreal(RzBody,pose[0:3]) \n\n        ############ swap l/r pose, flip y/z\n        pose=self.swapRightLeftPose(pose)\n        pose[1]=-pose[1]\n        pose[2]=-pose[2]\n        ############\n\n        theta=np.concatenate((pose,shape),axis=0)\n\n        ############ Swap keyps l/r\n        keyps2d=self.swapRightLeftJoints(keyps2d)\n        keyps3d=self.swapRightLeftJoints(keyps3d)        \n        keyps3dw=keyps3d.copy()\n        ############\n\n        if self.cameraSpace:\n            # move 3d joints to camera space         \n            keyps3d=np.concatenate([keyps3d.transpose(),np.ones((keyps3d.shape[1],1))],axis=1).transpose()\n            keyps3d=np.dot(currExtrinsic,keyps3d)   \n        pelvis=keyps3d[:,0].copy() \n        keyps3d-=np.expand_dims(pelvis,1)\n\n        currGender=self.gender[index].copy()\n        currGender=currGender[0]\n\n        return {\n            \"rgbImage\":torch.from_numpy(resImg).float(),\n            \"depthImage\":torch.from_numpy(depthImgCh).float(),\n            \"kp_2d\":torch.from_numpy(keyps2d).float(),\n            \"kp_3d\":torch.from_numpy(keyps3d).float(),\n            \"pelvis\":torch.from_numpy(np.expand_dims(pelvis,1)).float(),\n            \"kp_3d_world\":torch.from_numpy(np.asarray(keyps3dw)).float(),\n            \"theta\":torch.from_numpy(theta).float(),\n            \"zrot\":torch.from_numpy(np.asarray(currZRot)).float(),\n            \"camLoc\":torch.from_numpy(np.asarray(currCamLoc)).float(),\n            \"extrinsic\":torch.from_numpy(np.asarray(currExtrinsic)).float(),\n            \"intrinsic\":torch.from_numpy(np.asarray(cfg.surrealIntrinsic)).float(),\n            \"rgbImageName\":self.rgbImages[index],\n            \"depthImageName\":self.depthImages[index],\n            \"gender\":currGender,\n            \"data_set\":\"Surreal\"\n        }\n\n\nclass Human36M(Dataset):\n    def __init__(self):\n        self.onlySinglePerson=False\n        self.normalize=True\n        self.minPtsRequired=7\n        self.scaleRange=[1.05,1.3]\n        self.maxIntersectRatio=0.5\n        self.cropSize=224\n        self.pixFormat=\"NCHW\"\n        self.loadData()\n\n    def loadData(self):\n        self.keyps2d=[]\n        self.keyps3d=[]\n        self.smplShapeParams=[]\n        self.smplPoseParams=[]\n        self.images=[]\n        self.boxes=[]\n\n        fp=h5py.File(os.path.join(cfg.pathToHuman36m,\"data\",\"annot-copy.h5\"),\"r\")\n        keyps2d=np.array(fp[\"gt2d\"])\n        keyps3d=np.array(fp[\"gt3d\"])\n        smplShapeParams=np.array(fp[\"shape\"])\n        smplPoseParams=np.array(fp[\"pose\"])\n        images=np.array(fp[\"imagename\"])\n\n        assert(len(keyps2d)==len(keyps3d)) \n        assert(len(keyps2d)==len(smplShapeParams)) \n        assert(len(keyps2d)==len(smplPoseParams)) \n        assert(len(keyps2d)==len(images))\n\n        def isValid(pts):\n            r=[]\n            for pt in pts:\n                if pt[2]!=0:\n                    r.append(pt)\n            return r\n\n        for idx in cfg.imgsLoad: #range(cfg.nImgsLoad): #range(len(keyps2d)): \n            fullImgPath=os.path.join(cfg.pathToHuman36m,\"data\")+images[idx].decode()\n            if not os.path.isfile(fullImgPath):\n                continue\n            keyp2d=keyps2d[idx].reshape((-1,3))\n            if np.sum(keyp2d[:,2])<self.minPtsRequired:\n                continue\n            lt,rb,v=util.calc_aabb(isValid(keyp2d))\n            self.keyps2d.append(np.array(keyp2d.copy(),dtype=np.float))\n            self.boxes.append((lt,rb))\n            self.keyps3d.append(keyps3d[idx].copy().reshape(-1,3))\n            self.smplShapeParams.append(smplShapeParams[idx].copy())\n            self.smplPoseParams.append(smplPoseParams[idx].copy())\n            self.images.append(fullImgPath)\n\n    def __len__(self):\n        return len(self.images)\n\n    def __getitem__(self,index):\n        imgPath=self.images[index]\n        keyps2d=self.keyps2d[index].copy()\n        # remove head and neck points\n        keyps2d=keyps2d[0:12,:]\n        bbox=self.boxes[index]\n        keyps3d=self.keyps3d[index].copy()\n        keyps3d=keyps3d[0:12,:]\n\n        \"\"\"# plot points on image and save\n        imgVis=cv2.imread(imgPath)\n        for r in range(keyps2d.shape[0]):\n            currX=int(keyps2d[r,0])\n            currY=int(keyps2d[r,1])\n            cv2.circle(imgVis,(currX,currY),2,(0,0,255),4)\n            cv2.putText(imgVis,str(r),(currX,currY),cv2.FONT_HERSHEY_SIMPLEX,0.2,(255,255,255))\n        cv2.imwrite(\"/home/BaseCode/trainedModels/5/tmpFull.png\",imgVis)\"\"\"\n\n        #scale=np.random.rand(4)*(self.scaleRange[1]-self.scaleRange[0])+self.scaleRange[0]\n        scale=1\n        bboxImg,bboxKps=util.cut_image(imgPath,keyps2d,scale,bbox[0],bbox[1])\n        bboxKps=bboxKps[:,0:2]\n        bboxKps[:,0]*=(1.0*self.cropSize/bboxImg.shape[0])\n        bboxKps[:,1]*=(1.0*self.cropSize/bboxImg.shape[1])\n        resImg=cv2.resize(bboxImg,(self.cropSize,self.cropSize),interpolation=cv2.INTER_CUBIC)\n        #bboxKps[:,:2]=2.0*bboxKps[:, :2]*ratio-1.0\n        bboxKps=(2.0*bboxKps*1.0/self.cropSize) - 1.0\n        #print(bboxKps)\n\n\n        shape,pose=self.smplShapeParams[index],self.smplPoseParams[index]\n        #theta=np.concatenate((np.zeros(3),pose,shape),axis = 0)\n        theta=np.concatenate((pose,shape),axis = 0)\n\n        return {\n            \"image\":torch.from_numpy(util.convert_image_by_pixformat_normalize(resImg,self.pixFormat,self.normalize)).float(),\n            \"kp_2d\":torch.from_numpy(bboxKps).float(),\n            \"kp_3d\":torch.from_numpy(keyps3d).float(),\n            \"theta\":torch.from_numpy(theta).float(),\n            \"image_name\":self.images[index],\n            \"w_smpl\":1.0,\n            \"w_3d\":1.0,\n            \"data_set\":\"Human3.6M\"\n        }\n\nclass MoSH(Dataset):\n    def __init__(self):\n        self.smpl=SMPL_Layer(\"neutral\",cfg.smplModelPath)\n        self.loadData()\n\n    def loadData(self):\n        fp=h5py.File(os.path.join(cfg.pathToMoSh,\"data\",\"mosh_gen\",\"mosh_joints_annot.h5\"),\"r\")\n        self.smplShapeParams=np.array(fp[\"shape\"])\n        self.smplPoseParams=np.array(fp[\"pose\"])\n        self.smplJoints=np.array(fp[\"joints\"])\n        \n        #self.smplShapeParams=self.smplShapeParams[:cfg.nSamplesXyz2Smpl,:]\n        #self.smplPoseParams=self.smplPoseParams[:cfg.nSamplesXyz2Smpl,:]\n        #self.smplJoints=self.smplJoints[:cfg.nSamplesXyz2Smpl,:]\n        assert(len(self.smplShapeParams)==len(self.smplPoseParams)) \n        assert(len(self.smplShapeParams)==len(self.smplJoints))\n\n    def __len__(self):\n        return len(self.smplShapeParams)\n\n    def __getitem__(self,index):\n        shape,pose,joints=self.smplShapeParams[index],self.smplPoseParams[index],self.smplJoints[index]\n        theta=np.concatenate((pose,shape),axis=0)\n        pelv=joints[0,:]\n        currXYZ=joints-pelv\n        currXYZ=currXYZ[1:,:]\n        return {\n            \"theta\":torch.from_numpy(theta).float(),\n            \"xyz\":torch.from_numpy(currXYZ).float(),\n            \"pelvis\":torch.from_numpy(pelv).float(),\n            \"data_set\":\"MoSH\"\n        }\n\n\n\nclass COCO2017(Dataset):\n    def __init__(self,datasetPath):\n        self.onlySinglePerson=False\n        self.normalize=True\n        self.minPtsRequired=7\n        self.scaleRange=[1.05,1.3]\n        self.maxIntersectRatio=0.5\n        self.cropSize=224\n        self.pixFormat=\"NCHW\"\n        self.loadData(datasetPath)\n\n    def convertToLsp14Pts(self,cocoPts):\n        kpMap=[15,13,11,10,12,14,9,7,5,4,6,8,0,0]\n        kpMap=[16,14,12,11,13,15,10,8,6,5,7,9,0,0]\n        kps=np.array(cocoPts, dtype = np.float).reshape(-1, 3)[kpMap].copy()\n        kps[12:,2]=0.0 #no neck, top head\n        kps[:,2]/=2.0\n        return kps\n    \n    def loadData(self,datasetPath):\n        self.images=[]\n        self.keyps=[]\n        self.boxes=[]\n        with open(os.path.join(datasetPath,\"annotations\",\"person_keypoints_train2017.json\"),\"r\") as f:\n            annotations=json.load(f)\n        f.close()\n\n        imgsIdInfo={}\n        for inf in annotations[\"images\"]:\n            imgId=inf[\"id\"]\n            imgName=inf[\"file_name\"]\n            currAnno={}\n            currAnno[\"image_path\"]=os.path.join(datasetPath,\"images\",\"train-valid2017\",imgName)\n            currAnno[\"kps\"]=[]\n            currAnno[\"box\"]=[]\n            assert not (imgId in imgsIdInfo)\n            imgsIdInfo[imgId]=currAnno\n        \n        for inf in annotations[\"annotations\"]:\n            imgId=inf[\"image_id\"]\n            kps=inf[\"keypoints\"]\n            boxInfo=inf[\"bbox\"]\n            box=[np.array([int(boxInfo[0]),int(boxInfo[1])]),np.array([int(boxInfo[0]+boxInfo[2]),int(boxInfo[1]+boxInfo[3])])]\n            assert imgId in imgsIdInfo\n            anno=imgsIdInfo[imgId]\n            anno[\"box\"].append(box)\n            anno[\"kps\"].append(self.convertToLsp14Pts(kps))\n\n        self.createData(imgsIdInfo)\n\n    def createData(self,imgsIdInfo):\n        def checkCurrBboxOverlap(currBox,allOtherBoxes):\n            for box in allOtherBoxes:\n                if util.get_rectangle_intersect_ratio(currBox[0],currBox[1],box[0],box[1])>self.maxIntersectRatio:\n                    return True\n            return False\n        for key,value in imgsIdInfo.items():\n            currPath=value[\"image_path\"]\n            currKpsSet=value[\"kps\"]\n            currBoxSet=value[\"box\"]\n            if len(currBoxSet)>1:\n                if self.onlySinglePerson:\n                    continue\n                \n            for r in range(len(currBoxSet)):\n                currKeyp=currKpsSet[r]\n                currBox=currBoxSet[r]\n                if np.sum(currKeyp[:,2])<self.minPtsRequired:\n                    continue\n                allOtherBoxes=currBoxSet.copy()\n                allOtherBoxes.pop(r)\n                if checkCurrBboxOverlap(currBox,allOtherBoxes):\n                    continue\n                self.images.append(currPath)\n                self.keyps.append(currKeyp.copy())\n                self.boxes.append(currBox.copy())\n\n    def __len__(self):\n        return len(self.images)\n\n    def __getitem__(self,index):\n        imgPath=self.images[index]\n        keyps=self.keyps[index].copy()\n        bbox=self.boxes[index]\n\n        scale = np.random.rand(4)*(self.scaleRange[1]-self.scaleRange[0])+self.scaleRange[0]\n        bboxImg,bboxKps=util.cut_image(imgPath,keyps,scale,bbox[0],bbox[1])\n        ratio=1.0*self.cropSize/bboxImg.shape[0]\n        bboxKps[:,:2]*=ratio\n        resImg=cv2.resize(bboxImg,(self.cropSize,self.cropSize),interpolation=cv2.INTER_CUBIC)\n        ratio=1.0/self.cropSize\n        bboxKps[:,:2]=2.0*bboxKps[:, :2]*ratio-1.0\n\n        return {\n            \"image\":torch.tensor(util.convert_image_by_pixformat_normalize(resImg,self.pixFormat,self.normalize)).float(),\n            \"kp_2d\":torch.tensor(bboxKps).float(),\n            \"image_name\":imgPath,\n            \"data_set\":\"COCO 2017\"\n        }\n\n", "meta": {"hexsha": "85d7be687c529c2497f4af7df817bc2841633e8d", "size": 17762, "ext": "py", "lang": "Python", "max_stars_repo_path": "xyz2LspSmpl_PyTorch/dataloader.py", "max_stars_repo_name": "ccj5351/hmr_rgbd", "max_stars_repo_head_hexsha": "d1dcf81d72c11e1f502f2c494cd86425f384d9cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "xyz2LspSmpl_PyTorch/dataloader.py", "max_issues_repo_name": "ccj5351/hmr_rgbd", "max_issues_repo_head_hexsha": "d1dcf81d72c11e1f502f2c494cd86425f384d9cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-09T07:29:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-09T07:29:00.000Z", "max_forks_repo_path": "xyz2LspSmpl_PyTorch/dataloader.py", "max_forks_repo_name": "ccj5351/hmr_rgbd", "max_forks_repo_head_hexsha": "d1dcf81d72c11e1f502f2c494cd86425f384d9cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5590200445, "max_line_length": 274, "alphanum_fraction": 0.58332395, "include": true, "reason": "import numpy", "num_tokens": 5065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.19473590411694508}}
{"text": "#!/usr/bin/env python\n# coding: utf8\n#\n# Copyright (c) 2021 Centre National d'Etudes Spatiales (CNES).\n#\n# This file is part of PANDORA_MCCNN\n#\n#     https://github.com/CNES/Pandora_MCCNN\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\"\"\"\nThis module contains functions to test mc-cnn fast and accurate\n\"\"\"\n\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom mc_cnn.model.mc_cnn_fast import FastMcCnn\nfrom mc_cnn.model.mc_cnn_accurate import AccMcCnnInfer\n\n\ndef point_interval(ref_features, sec_features, disp):\n    \"\"\"\n    Computes the range of points over which the similarity measure will be applied\n\n    :param ref_features: reference features\n    :type ref_features: Tensor of shape (64, row, col)\n    :param sec_features: secondary features\n    :type sec_features: Tensor of shape (64, row, col)\n    :param disp: current disparity\n    :type disp: float\n    :return: the range of the reference and secondary image over which the similarity measure will be applied\n    :rtype: tuple\n    \"\"\"\n    _, _, nx_ref = ref_features.shape\n    _, _, nx_sec = sec_features.shape\n\n    # range in the reference image\n    left = (max(0 - disp, 0), min(nx_ref - disp, nx_ref))\n    # range in the secondary image\n    right = (max(0 + disp, 0), min(nx_sec + disp, nx_sec))\n\n    return left, right\n\n\ndef run_mc_cnn_fast(img_ref, img_sec, disp_min, disp_max, model_path):\n    \"\"\"\n    Computes the cost volume for a pair of images with mc-cnn fast\n\n    :param img_ref: reference Dataset image\n    :type img_ref:\n    xarray.Dataset containing :\n        - im : 2D (row, col) xarray.DataArray\n    :param img_sec: secondary Dataset image\n    :type img_sec:\n    xarray.Dataset containing :\n        - im : 2D (row, col) xarray.DataArray\n    :param disp_min: minimum disparity\n    :type disp_min: int\n    :param disp_max: maximum disparity\n    :type disp_max: int\n    :param model_path: path to the trained network\n    :type model_path: string\n    :return: the cost volume ( similarity score is converted to a matching cost )\n    :rtype: 3D np.array (row, col, disp)\n    \"\"\"\n    device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n    # Create the network\n    net = FastMcCnn()\n    # Load the network\n    net.load_state_dict(torch.load(model_path, map_location=device)[\"model\"])\n    net.to(device)\n    net.eval()\n\n    # Normalize images\n    ref = img_ref[\"im\"].copy(deep=True).data\n    ref = (ref - ref.mean()) / ref.std()\n\n    sec = img_sec[\"im\"].copy(deep=True).data\n    sec = (sec - sec.mean()) / sec.std()\n\n    # Extracts the image features by propagating the images in the mc_cnn fast network\n    # Right and left features of shape : (64, row-10, col-10)\n    ref_features = net(torch.from_numpy(ref).to(device=device, dtype=torch.float), training=False)\n    sec_features = net(torch.from_numpy(sec).to(device=device, dtype=torch.float), training=False)\n\n    cv = computes_cost_volume_mc_cnn_fast(ref_features, sec_features, disp_min, disp_max)\n\n    return cv\n\n\ndef computes_cost_volume_mc_cnn_fast(ref_features, sec_features, disp_min, disp_max):\n    \"\"\"\n    Computes the cost volume using the reference and secondary features computing by mc_cnn fast\n\n    :param ref_features: reference features\n    :type ref_features: Tensor of shape (64, row, col)\n    :param sec_features: secondary features\n    :type sec_features: Tensor of shape (64, row, col)\n    :return: the cost volume ( similarity score is converted to a matching cost )\n    :rtype: 3D np.array (row, col, disp)\n    \"\"\"\n    # Construct the cost volume\n    disparity_range = np.arange(disp_min, disp_max + 1)\n\n    # Allocate the numpy cost volume cv = (disp, col, row), for efficient memory management\n    cv = np.zeros((len(disparity_range), ref_features.shape[2], ref_features.shape[1]), dtype=np.float32)\n    cv += np.nan\n\n    cos = nn.CosineSimilarity(dim=0, eps=1e-6)\n\n    for disp in disparity_range:\n        # Columns range in left and right image\n        left, right = point_interval(ref_features, sec_features, disp)\n        ind_d = int(disp - disp_min)\n        cv[ind_d, left[0] : left[1], :] = np.swapaxes(\n            (\n                cos(ref_features[:, :, left[0] : left[1]], sec_features[:, :, right[0] : right[1]])\n                .cpu()\n                .detach()\n                .numpy()\n            ),\n            0,\n            1,\n        )\n\n    # Releases cache memory\n    torch.cuda.empty_cache()\n\n    # The minus sign converts the similarity score to a matching cost\n    cv *= -1\n\n    return np.swapaxes(cv, 0, 2)\n\n\ndef run_mc_cnn_accurate(img_ref, img_sec, disp_min, disp_max, model_path):\n    \"\"\"\n    Computes the cost volume for a pair of images with mc-cnn accurate\n\n    :param img_ref: reference Dataset image\n    :type img_ref:\n    xarray.Dataset containing :\n        - im : 2D (row, col) xarray.DataArray\n    :param img_sec: secondary Dataset image\n    :type img_sec:\n    xarray.Dataset containing :\n        - im : 2D (row, col) xarray.DataArray\n    :param disp_min: minimum disparity\n    :type disp_min: int\n    :param disp_max: maximum disparity\n    :type disp_max: int\n    :param model_path: path to the trained network\n    :type model_path: string\n    :return: the cost volume ( similarity score is converted to a matching cost )\n    :rtype: 3D np.array (row, col, disp)\n    \"\"\"\n    device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n    # Create the network\n    net = AccMcCnnInfer()\n    # Load the network\n    net.load_state_dict(torch.load(model_path, map_location=device)[\"model\"])\n    net.to(device)\n    net.eval()\n\n    # Normalize images\n    ref = img_ref[\"im\"].copy(deep=True).data\n    ref = (ref - ref.mean()) / ref.std()\n\n    sec = img_sec[\"im\"].copy(deep=True).data\n    sec = (sec - sec.mean()) / sec.std()\n\n    cv = net(\n        torch.from_numpy(ref).to(device=device, dtype=torch.float),\n        torch.from_numpy(sec).to(device=device, dtype=torch.float),\n        disp_min,\n        disp_max,\n    )\n    # Releases cache memory\n    torch.cuda.empty_cache()\n    return cv\n", "meta": {"hexsha": "7c82ae4bcf742a695e91a90fdaa7987bad4759b5", "size": 6507, "ext": "py", "lang": "Python", "max_stars_repo_path": "mc_cnn/run.py", "max_stars_repo_name": "qfardet/Pandora_MCCNN", "max_stars_repo_head_hexsha": "0bd26d78f2f4dc1d8571f2cdf47e327dc1628c9e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-09T15:14:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T08:28:00.000Z", "max_issues_repo_path": "mc_cnn/run.py", "max_issues_repo_name": "qfardet/Pandora_MCCNN", "max_issues_repo_head_hexsha": "0bd26d78f2f4dc1d8571f2cdf47e327dc1628c9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mc_cnn/run.py", "max_forks_repo_name": "qfardet/Pandora_MCCNN", "max_forks_repo_head_hexsha": "0bd26d78f2f4dc1d8571f2cdf47e327dc1628c9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1989795918, "max_line_length": 109, "alphanum_fraction": 0.6721991701, "include": true, "reason": "import numpy", "num_tokens": 1667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.19473590411694505}}
{"text": "#!/usr/bin/env python\r\n# coding: utf-8\r\n\r\n# raspir\r\n# Contact details: pust.marie-madlen@mh-hannover.de\r\n# Last updated: 07 April 2021\r\n\r\n# import\r\nfrom __future__ import print_function\r\n## batteries\r\nimport os\r\nimport sys\r\nimport argparse\r\nimport logging\r\nimport itertools\r\nimport random\r\nfrom itertools import count, takewhile\r\n## 3rd party\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nfrom scipy import fftpack, stats\r\nfrom scipy.stats import linregress\r\n\r\n# matplotlib init\r\nmatplotlib.use('Agg')\r\n\r\n# logging\r\nlogging.basicConfig(format='%(asctime)s - %(message)s', level=logging.DEBUG)\r\nlogging.getLogger('matplotlib.font_manager').disabled = True\r\n\r\n# argparse# \r\nclass CustomFormatter(argparse.ArgumentDefaultsHelpFormatter,\r\n                      argparse.RawDescriptionHelpFormatter):\r\n    pass\r\n\r\ndesc = 'raspir: rare species identifier'\r\nepi = \"\"\"DESCRIPTION:\r\nInput: csv file (see raspir repo README)\r\nOutput: \r\n* $PREFIX_[organism]_freq.png\r\n  * graph: spectrum ~ frequence_per_cycle\r\n* $PREFIX_final_stats.csv\r\n  * csv table of final results (see raspir repo README)\r\n\"\"\"\r\nparser = argparse.ArgumentParser(description=desc, epilog=epi,\r\n                                 formatter_class=CustomFormatter)\r\nargparse.ArgumentDefaultsHelpFormatter\r\nparser.add_argument('csv_file', metavar='csv_file', type=str,\r\n                    help='Input csv file')\r\nparser.add_argument('out_prefix', metavar='out_prefix', type=str,\r\n                    help='output file prefix')\r\nparser.add_argument('-e', '--error', type=float, default=0.01,\r\n                    help='std-error cutoff parameter')\r\nparser.add_argument('-a', '--alpha', type=float, default=0.05,\r\n                    help='alpha parameter')\r\nparser.add_argument('--version', action='version', version='0.0.1')\r\n\r\n\r\n# Global parameters\r\nnorm_cpm = 1000000\r\n\r\n# functions\r\ndef frange(start, stop, step):\r\n    \"\"\"\r\n    Define range of the reference's read distance\r\n    \"\"\"\r\n    return takewhile(lambda x: x < stop, count(start, step))\r\n\r\ndef read_count(x, min_reads=4):\r\n    \"\"\"\r\n    Read count table\r\n    \"\"\"\r\n    items_diff = [abs(j - i) for i, j in zip(x['Position'], x['Position'][1:])]\r\n    a = [0]\r\n    items_diff = a + items_diff\r\n    x['items_diff'] = items_diff\r\n    x['gap'] = np.where(x['items_diff'] == 1, 0, 1)\r\n    x['readCount'] = np.cumsum(x['gap'])\r\n    x = x.drop_duplicates(subset='readCount', keep='first')\r\n    x = x.drop(['items_diff', 'gap'], 1)\r\n    \r\n    # remove all Organisms with less than `min_read` reads\r\n    x['indexNames'] = x['readCount'].sum()\r\n    store_index = x[x['indexNames'] < int(min_reads)].index\r\n    x.drop(store_index, inplace=True)\r\n    return x\r\n \r\ndef normalise_genome_position(x):\r\n    \"\"\"\r\n    Normalise position (circular genome)\r\n    \"\"\"\r\n    x['PositionNorm0'] = np.where(x['Position'] > (x['GenomeLength'] / 2),\r\n                                  (x['GenomeLength'] - x['Position']),\r\n                                  x['Position'])\r\n    x['PositionNorm'] = x['PositionNorm0']**(1/2)\r\n    \r\n    # Reference position\r\n    n_reads = x['readCount'].max()\r\n    start_position_ref = int(1)\r\n    end_position_ref = x['GenomeLength'].iloc[0]\r\n    end_position_ref = end_position_ref + n_reads\r\n    increase_by = (end_position_ref / n_reads)\r\n    x['ref_Position'] = list(frange(start_position_ref, end_position_ref,\r\n                                    increase_by))\r\n    x['ref_Position'] = x['ref_Position'].astype(int)\r\n    x['PositionNorm_ref0'] = np.where(x['ref_Position'] > (x['GenomeLength'] / 2),\r\n                                      (x['GenomeLength'] - x['ref_Position']),\r\n                                      x['ref_Position'])\r\n    x['PositionNorm_ref'] = x['PositionNorm_ref0'].astype(int)\r\n    return x\r\n\r\n\r\ndef make_time_domain(x):\r\n    \"\"\"\r\n    Time domain signal\r\n    \"\"\"\r\n    # check if read count of organism matches with minimum requirement\r\n    mean_depth = int(x['Depth'].mean())\r\n    n_reads = int(x['readCount'].max())\r\n    species_name = x['Organism'].iloc[0]\r\n    x['PositionNorm'] = x['PositionNorm'] * x['Depth']\r\n    x['PositionNorm_ref'] = x['PositionNorm_ref'] * mean_depth\r\n\r\n    reference_combinations_distances_sort = []\r\n    real_combinations_distances_sort = []\r\n\r\n    # calculate the biological distance\r\n    real_read_positions = sorted(x['PositionNorm'])\r\n    reference_read_positions = sorted(x['PositionNorm_ref'])\r\n\r\n    if n_reads > int(1000):\r\n        random.seed(222)\r\n        real_select_random = random.sample(real_read_positions, 400)\r\n        real_read_combinations_sub = list(itertools.combinations(real_select_random, 2))\r\n        real_combinations_distances_sub = [abs(i - j) for i, j in real_read_combinations_sub]\r\n        real_combinations_distances_sort_sub = sorted(real_combinations_distances_sub)\r\n        real_combinations_distances_sort.append(real_combinations_distances_sort_sub)\r\n\r\n        # calculate the reference distance\r\n        reference_select_random = random.sample(reference_read_positions, 400)\r\n        reference_read_combinations_sub = list(itertools.combinations(reference_select_random, 2))\r\n        reference_combinations_distances_sub = [abs(i - j) for i, j in reference_read_combinations_sub]\r\n        reference_combinations_distances_sort_sub = sorted(reference_combinations_distances_sub)\r\n        reference_combinations_distances_sort.append(reference_combinations_distances_sort_sub)\r\n    else:\r\n        real_read_combinations = list(itertools.combinations(real_read_positions, 2))\r\n        real_combinations_distances = [abs(i - j) for i, j in real_read_combinations]\r\n        real_combinations_distances_sort1 = sorted(real_combinations_distances)\r\n        real_combinations_distances_sort.append(real_combinations_distances_sort1)\r\n\r\n        # calculate the reference distance\r\n        reference_read_combinations = list(itertools.combinations(reference_read_positions, 2))\r\n        reference_combinations_distances = [abs(i - j) for i, j in reference_read_combinations]\r\n        reference_combinations_distances_sort1 = sorted(reference_combinations_distances)\r\n        reference_combinations_distances_sort.append(reference_combinations_distances_sort1)\r\n\r\n    # create output data frame\r\n    df = pd.DataFrame(list(zip(reference_combinations_distances_sort, real_combinations_distances_sort)),\r\n                      columns=['Reference', 'Real'])\r\n    df['Organism'] = species_name\r\n    df2 = df.apply(lambda i: i.explode() if i.name in ['Reference', 'Real'] else i)\r\n    return df2\r\n\r\n\r\n# frequency domain signal (fds)\r\ndef fourier_trans(x):\r\n    species_name = x['Organism'].iloc[0]\r\n\r\n    x['fft_ref1'] = np.fft.fft(x['Reference'])\r\n    x['fft_bio1'] = np.fft.fft(x['Real'])\r\n\r\n    x['fft_ref'] = [complex(np.around(items2.real), np.around(items2.imag)) for items2 in x['fft_ref1']]\r\n    x['fft_bio'] = [complex(np.around(items2.real), np.around(items2.imag)) for items2 in x['fft_bio1']]\r\n    \r\n    x['fft_abs_ref'] = np.abs(x['fft_ref'])\r\n    x['fft_abs_bio'] = np.abs(x['fft_bio'])\r\n    x['fft_abs_ref_sqrt'] = np.around(x['fft_abs_ref'] / norm_cpm, 2)\r\n    x['fft_abs_bio_sqrt'] = np.around(x['fft_abs_bio'] / norm_cpm, 2)\r\n    \r\n    # Pearson correlation\r\n    if (sum(x['fft_abs_ref_sqrt']) > 0) & (sum(x['fft_abs_bio_sqrt']) > 0):\r\n        pearson_corr = linregress(x['fft_abs_ref_sqrt'], x['fft_abs_bio_sqrt'])\r\n        pearson_standard_error0 = pearson_corr[4]\r\n        pearson_corr_r0, pearson_corr_p0 = stats.pearsonr(x['fft_abs_ref_sqrt'], x['fft_abs_bio_sqrt'])\r\n        pearson_corr_r = round(pearson_corr_r0, 4)\r\n        pearson_corr_p = round(pearson_corr_p0, 10)\r\n        euclidean_dist_0 = np.linalg.norm(x['fft_abs_ref_sqrt']-x['fft_abs_bio_sqrt'])\r\n        euclidean_dist = round(euclidean_dist_0, 1)\r\n        pearson_standard_error = round(pearson_standard_error0, 5)\r\n        return species_name, pearson_corr_r, pearson_corr_p, pearson_standard_error, euclidean_dist\r\n    else:\r\n        pearson_corr_r2 = 0\r\n        pearson_corr_p2 = 0\r\n        pearson_standard_error2 = 1\r\n        euclidean_dist2 = 1\r\n        return species_name, pearson_corr_r2, pearson_corr_p2, pearson_standard_error2, euclidean_dist2\r\n\r\n\r\ndef make_freq_images(x):\r\n    logging.basicConfig(level=logging.ERROR)\r\n    species_name = x['Organism'].iloc[0]\r\n    path_real = x['PathName'].iloc[0]\r\n\r\n    x['fft_ref1'] = np.fft.fft(x['Reference'])\r\n    x['fft_bio1'] = np.fft.fft(x['Real'])\r\n\r\n    x['fft_ref'] = [complex(np.around(items2.real), np.around(items2.imag)) for items2 in x['fft_ref1']]\r\n    x['fft_bio'] = [complex(np.around(items2.real), np.around(items2.imag)) for items2 in x['fft_bio1']]\r\n\r\n    x['fft_abs_ref'] = np.abs(x['fft_ref'])\r\n    x['fft_abs_bio'] = np.abs(x['fft_bio'])\r\n    x['fft_abs_ref_sqrt'] = np.around(x['fft_abs_ref'] / norm_cpm, 2)\r\n    x['fft_abs_bio_sqrt'] = np.around(x['fft_abs_bio'] / norm_cpm, 2)\r\n\r\n    # plot frequency signal\r\n    val_bio = x['Real']\r\n    val_ref = x['Reference']\r\n    x_bio0 = x['fft_abs_bio_sqrt']\r\n    x_reference0 = x['fft_abs_ref_sqrt']\r\n\r\n    x_bio1 = x_bio0.sort_values()\r\n    x_bio2 = pd.concat([x_bio1[::2], x_bio1[len(x_bio1)-2:0:-2]])\r\n    x_bio = x_bio2.tolist()\r\n    x_reference1 = x_reference0.sort_values()\r\n    x_reference2 = pd.concat([x_reference1[::2], x_reference1[len(x_reference1)-2:0:-2]])\r\n    x_reference = x_reference2.tolist()\r\n    freqs_bio0 = fftpack.fftfreq(len(val_bio))\r\n    freqs_bio = sorted(freqs_bio0)\r\n\r\n    freqs_ref0 = fftpack.fftfreq(len(val_ref))\r\n    freqs_ref = sorted(freqs_ref0)\r\n    a = (len(freqs_ref) - len(x_reference))\r\n    b = (len(freqs_bio) - len(x_bio))\r\n    x_reference += [0]*a\r\n    x_bio += [0]*b\r\n    x_reference3 = np.sqrt(x_reference)\r\n    sep = '_'\r\n\r\n    fig, ax1 = plt.subplots(1, 1, figsize=(2.5, 2))\r\n    ax1.plot(freqs_ref, x_reference3, \"black\", linewidth=1, linestyle='--', label=\"Reference\", alpha=0.4)\r\n    ax1.plot(freqs_bio, x_bio, 'blue', linewidth=1, linestyle='--', label=\"Sample\")\r\n    ax1.legend(framealpha=1, loc='upper right', fontsize=3)\r\n    ax1.fill_between(freqs_ref, x_reference3, x_bio, facecolor='pink', alpha=0.2, interpolate=True)\r\n    fig.text(0.5, 0.025, \"Frequency per cycle\",  ha='center', va='center', fontsize=4)\r\n    fig.text(0.010, 0.5, \"Spectrum\", ha='center', va='center', rotation='vertical', fontsize=4)\r\n    plt.xticks(fontsize=3)\r\n    plt.yticks(fontsize=3)\r\n    outfile = '_'.join([path_real, species_name, 'freq.png'])\r\n    plt.savefig(outfile, dpi=600)\r\n    logging.basicConfig(level=logging.DEBUG)\r\n    logging.info('  File written: {}'.format(outfile))\r\n    plt.close()\r\n\r\ndef final_table(x, set_error, set_alpha):\r\n    \"\"\"\r\n    Create file data table\r\n    \"\"\"\r\n    a0 = pd.DataFrame(x, columns=['Pearson'])\r\n    a = a0.dropna(axis=0, how='all')\r\n    a = a[['Species', 'r_value', 'p_value', 'stError', 'euclideanR0']] = pd.DataFrame(a['Pearson'].tolist())\r\n    a.columns = ['a', 'b', 'c', 'd', 'e',\r\n                 'Species', 'r_value', 'p_value', 'stError', 'euclideanR0']\r\n    a.reset_index(drop=True, inplace=True)\r\n    a = a.drop(a.columns[[0, 1]], axis=1)\r\n    a = a[['Species', 'r_value', 'p_value', 'stError', 'euclideanR0']]\r\n    a['euclidean'] = np.around((1 / a['euclideanR0']) * 1000, 3)\r\n    a['distribution'] = np.where(\r\n        (a['p_value'] < set_alpha) & (a['r_value'] > 0.5) & (a['stError'] < set_error) & (a['euclidean'] < 0.5),\r\n        'uniform', 'nonuniform')\r\n    b1 = a[['Species', 'r_value', 'p_value', 'stError', 'euclidean', 'distribution']]\r\n    b2 = b1[b1.distribution == 'uniform']\r\n    return b2\r\n    \r\n\r\ndef process_csv(file_name, out_prefix, args):    \r\n    with open(file_name, newline='') as inF:\r\n        df = pd.read_csv(inF, delimiter=',')\r\n\r\n        # filtering human reads\r\n        pattern_del = '1_1_1_'\r\n        filter_approach = df['Organism'].str.contains(pattern_del, na=False)\r\n        df = df[~filter_approach]\r\n        logging.info('1) Human reads have been removed')\r\n\r\n        # counting reads per organism\r\n        df = df.dropna(subset=['GenomeLength'])\r\n        df_filter1 = df.groupby('Organism').apply(read_count)\r\n        logging.info('2) Continue with the first position of each read')\r\n\r\n        if df_filter1.empty is True:\r\n            logging.warning('Note: Dataset is empty')\r\n            outfile = '{}_filtered.csv'.format(out_prefix)\r\n            df_filter1.to_csv(outfile, index=False)\r\n            logging.info('  File written: {}'.format(outfile))\r\n            return None\r\n        else:\r\n            df_filter = df_filter1.reset_index(drop=True)\r\n            df_filter2 = df_filter.groupby('Organism').apply(normalise_genome_position)\r\n            logging.info('3) Genome position normalised')\r\n\r\n            position_domain0 = df_filter2.reset_index(drop=True)\r\n            position_domain = position_domain0.groupby(\"Organism\").apply(make_time_domain)\r\n            logging.info('4) Time-domain signal built')\r\n\r\n            frequency_domain0 = position_domain.reset_index(drop=True)\r\n            frequency_domain0['PathName'] = os.path.join(out_prefix)\r\n            frequency_domain = frequency_domain0.groupby('Organism').apply(fourier_trans)\r\n            logging.info('5) Frequency-domain signal generated')\r\n\r\n            frequency_domain0.groupby('Organism').apply(make_freq_images)\r\n            logging.info('6) Frequency plots produced')\r\n\r\n            stat_table = final_table(frequency_domain,\r\n                                     set_error=args.error,\r\n                                     set_alpha=args.alpha)\r\n            logging.info('7) Output table has been generated')\r\n\r\n            outfile = '{}_final_stats.csv'.format(out_prefix)\r\n            stat_table.to_csv(outfile, index=False)\r\n            logging.info('  File written: {}'.format(outfile))\r\n            logging.info('8) Run successful')\r\n\r\ndef main(args):\r\n    \"\"\"\r\n    Main interface\r\n    \"\"\"\r\n    # output directory\r\n    outdir = os.path.split(args.out_prefix)[0]\r\n    if outdir != '' and not os.path.isdir(outdir):\r\n        os.makedirs(args.outdir)\r\n    # processing each file\r\n    process_csv(args.csv_file, out_prefix=args.out_prefix, args=args)\r\n    \r\nif __name__ == \"__main__\":\r\n    args = parser.parse_args()\r\n    main(args)", "meta": {"hexsha": "435eb2c9f31df71aac5bd8478a6c9605549b7fc9", "size": 14202, "ext": "py", "lang": "Python", "max_stars_repo_path": "raspir_with_customised_refdb/raspir_own_refSeq.py", "max_stars_repo_name": "colindaven/raspir", "max_stars_repo_head_hexsha": "33a1721487a5fa65298f7d6d31d9d97772fa9e68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-12-11T12:37:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T17:22:21.000Z", "max_issues_repo_path": "raspir_with_customised_refdb/raspir_own_refSeq.py", "max_issues_repo_name": "colindaven/raspir", "max_issues_repo_head_hexsha": "33a1721487a5fa65298f7d6d31d9d97772fa9e68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-12-14T13:39:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T06:59:34.000Z", "max_forks_repo_path": "raspir_with_customised_refdb/raspir_own_refSeq.py", "max_forks_repo_name": "colindaven/raspir", "max_forks_repo_head_hexsha": "33a1721487a5fa65298f7d6d31d9d97772fa9e68", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-26T13:43:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-04T06:39:37.000Z", "avg_line_length": 42.0177514793, "max_line_length": 113, "alphanum_fraction": 0.6437121532, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.19473590411694505}}
{"text": "# Copyright 2020 Makani Technologies LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Functions for working with state-space models.\"\"\"\n\n\nimport copy\n\nimport numpy as np\n\n\n# pylint doesn't like capital letters in variable names, in contrast\n# to control systems conventions.\n# pylint: disable=invalid-name\n\n\nclass SignalListInvalidArgumentException(Exception):\n  \"\"\"Raised if an invalid argument is passed to a method of SignaList.\"\"\"\n  pass\n\n\nclass SignalList(object):\n  \"\"\"Representation of a named list of signals.\n\n  A signal list consists of a non-repeating ordered set of signal\n  names (each representing a scalar valued signal).\n  \"\"\"\n\n  def __init__(self, names):\n    \"\"\"Constructor.\n\n    Args:\n      names: List of signal names.\n\n    Raises:\n      SignalListInvalidArgumentException: If there are repeated names.\n    \"\"\"\n    self.names = copy.copy(names)\n    if not all([isinstance(name, str) for name in self.names]):\n      raise SignalListInvalidArgumentException('Names must be strings.', names)\n    # Test that there are not repeated names.\n    if len(self.names) != len(set(self.names)):\n      raise SignalListInvalidArgumentException('Repeated signal name.', names)\n    self._names_to_indices = {\n        name: i for i, name in enumerate(self.names)\n    }\n\n  def __repr__(self):\n    return ', '.join(self.names)\n\n  def __getitem__(self, indices):\n    \"\"\"Select a subset of an input list.\n\n    Args:\n      indices: Can be a slice or a list.  If a list, may contain\n          a mixture of integer entries and string entries.\n\n    Raises:\n      SignalListInvalidArgumentException: If indices is not a list.\n\n    Returns:\n      A new signal list consisting of a subset of the existing list\n      in the given order (units are tracked appropriately).\n    \"\"\"\n    if isinstance(indices, slice):\n      selection = range(len(self))[indices]\n    elif not isinstance(indices, list):\n      raise SignalListInvalidArgumentException(indices)\n    else:\n      selection = copy.copy(indices)\n\n    for i in range(len(selection)):\n      if isinstance(selection[i], int):\n        selection[i] = self.names[selection[i]]\n\n    return SignalList(selection)\n\n  def __len__(self):\n    return len(self.names)\n\n  def __add__(self, other):\n    return SignalList(self.names + other.names)\n\n  def GetIndices(self, names):\n    \"\"\"Get the integer indices corresponding to a list of signal names.\"\"\"\n    return [self._names_to_indices[name] for name in names]\n\n  def AddSuffix(self, suffix):\n    return SignalList([name + suffix for name in self.names])\n\n\nclass SystemInvalidArgumentException(Exception):\n  \"\"\"Raised if an invalid argument is passed to a method of System.\"\"\"\n  pass\n\n\nclass SystemBadDimensionException(Exception):\n  \"\"\"Raised if there is a mismatch in dimensions of arguments.\"\"\"\n  pass\n\n\nclass SystemSamplePeriodMismatchException(Exception):\n  \"\"\"Raised if there is a mismatch in sample periods.\"\"\"\n  pass\n\n\nclass SystemBadSamplePeriodException(Exception):\n  \"\"\"Raised if an illegal sample period is given.\"\"\"\n  pass\n\n\nclass SystemIllPosedException(Exception):\n  \"\"\"Raised if an ill-posed feedback loop is closed.\"\"\"\n  pass\n\n\nclass System(object):\n  \"\"\"Class for representing as state-space model with named inputs.\"\"\"\n\n  def __init__(self, A, B, C, D, Ts, state_list, input_list, output_list):\n    \"\"\"Constructor for a new system.\n\n    If A, B, or C are empty, then all three must be empty and\n    the system represents a constant gain matrix determined\n    by D.\n\n    If A is non-empty and D is empty, then D is taken to be all zeros.\n\n    Args:\n      A: nx-by-nx matrix.\n      B: nx-by-nu matrix.\n      C: ny-by-nx matrix.\n      D: ny-by-nu matrix.\n      Ts: Sample period (zero indicates continuous time models, -1.0\n          indicates a DT model with unspecified sample period).\n      state_list: SignalList of length nx.\n      input_list: SignalList of length nu.\n      output_list: SignalList of length ny.\n\n    Raises:\n      SystemBadSamplePeriodException: If Ts has an invalid value.\n      SystemBadDimensionException: If the arguments have inconsistent\n          dimensions.\n    \"\"\"\n    if not state_list:\n      state_list = SignalList([])\n    if isinstance(state_list, list):\n      state_list = SignalList(state_list)\n    if isinstance(input_list, list):\n      input_list = SignalList(input_list)\n    if isinstance(output_list, list):\n      output_list = SignalList(output_list)\n    if Ts < 0.0 and Ts != -1.0:\n      raise SystemBadSamplePeriodException()\n    self.Ts = Ts\n\n    self._A = np.matrix(A)\n    self._B = np.matrix(B)\n    self._C = np.matrix(C)\n    self._D = np.matrix(D)\n    if self._A.size == 0:\n      if self._B.size > 0 or self._C.size > 0:\n        raise SystemBadDimensionException(A, B, C, D)\n      self.nx = 0\n      self.ny = self._D.shape[0]\n      self.nu = self._D.shape[1]\n      self._A = np.matrix(np.zeros((self.nx, self.nx)))\n      self._B = np.matrix(np.zeros((self.nx, self.nu)))\n      self._C = np.matrix(np.zeros((self.ny, self.nx)))\n    else:\n      self.nx = self._A.shape[0]\n      self.nu = self._B.shape[1]\n      self.ny = self._C.shape[0]\n    if self._D.size == 0:\n      self._D = np.matrix(np.zeros((self.ny, self.nu)))\n\n    if (not np.array_equal(self._A.shape, [self.nx, self.nx])\n        or not np.array_equal(self._B.shape, [self.nx, self.nu])\n        or not np.array_equal(self._C.shape, [self.ny, self.nx])\n        or not np.array_equal(self._D.shape, [self.ny, self.nu])):\n      raise SystemBadDimensionException(self._A.shape, self._B.shape,\n                                        self._C.shape, self._D.shape)\n\n    if not isinstance(state_list, SignalList) or len(state_list) != self.nx:\n      raise SystemBadDimensionException('Bad state list.', state_list)\n\n    if not isinstance(input_list, SignalList) or len(input_list) != self.nu:\n      raise SystemBadDimensionException('Bad input list.', input_list)\n\n    if not isinstance(output_list, SignalList) or len(output_list) != self.ny:\n      raise SystemBadDimensionException('Bad output list.', output_list)\n\n    self.states = state_list\n    self.inputs = input_list\n    self.outputs = output_list\n\n  def __repr__(self):\n    return ('%d-by-%d state-space model (Ts = %g) with %d states.' %\n            (self.ny, self.nu, self.Ts, self.nx)\n            + '\\nInputs: ' + self.inputs.__repr__()\n            + '\\nOutputs: ' + self.outputs.__repr__()\n            + '\\nA:\\n' + str(self._A) + '\\nB:\\n' + str(self._B)\n            + '\\nC:\\n' + str(self._C) + '\\nD:\\n' + str(self._D))\n\n  def __getitem__(self, io):\n    \"\"\"Construct a new system with a subset of the inputs and outputs.\n\n    Args:\n      io: A tuple of two lists of strings.  The first list selects a subset\n        of the outputs of the system, the second selects a subset of the inputs.\n        Either can be the trivial slice ':'.\n\n    Raises:\n      SystemInvalidArgumentException: If an invalid argument is passed.\n\n    Returns:\n      A new System object with the reduced input and output dimensions.\n    \"\"\"\n    if not isinstance(io, tuple) or len(io) != 2:\n      raise SystemInvalidArgumentException('Index must be a tuple.')\n\n    if isinstance(io[1], slice):\n      if io[1] != slice(None, None, None):\n        raise SystemInvalidArgumentException('Only \":\" slices are allowed.')\n      input_names = [self.inputs.names[i] for i in range(self.nu)]\n    else:\n      input_names = io[1]\n\n    if isinstance(io[0], slice):\n      if io[0] != slice(None, None, None):\n        raise SystemInvalidArgumentException('Only \":\" slices are allowed.')\n      output_names = [self.outputs.names[i] for i in range(self.ny)]\n    else:\n      output_names = io[0]\n\n    (inputs, _, B, _) = self._PartitionInputs(self._B, input_names)\n    (outputs, _, C, _) = self._PartitionOutputs(self._C, output_names)\n    (_, _, D, _) = self._PartitionInputs(self._D, input_names)\n    (_, _, D, _) = self._PartitionOutputs(D, output_names)\n\n    return System(self._A, B, C, D, self.Ts, self.states, inputs, outputs)\n\n  def _PartitionOutputs(self, matrix, output_names):\n    \"\"\"Partition the rows of an ny-by-m matrix.\n\n    Args:\n      matrix: An ny-by-m matrix.\n      output_names: Names of the outputs to be included in the first\n          part of the partition.\n\n    Raises:\n      SystemBadDimensionException: If matrix has the wrong number of rows.\n\n    Returns:\n      A tuple (outputs, other_outputs, output_matrix,\n      other_output_matrix).  The first two entries are SignalLists\n      containing the outputs in output_names and the other outputs.\n      The first matrix is the sub-matrix corresponding to the\n      output_names and the remaining rows are in other_output_matrix.\n    \"\"\"\n    if matrix.shape[0] != self.ny:\n      raise SystemBadDimensionException(matrix)\n\n    outputs = self.outputs[output_names]\n    output_indices = self.outputs.GetIndices(output_names)\n    other_output_indices = [\n        i for i in range(self.ny) if i not in output_indices\n    ]\n    other_outputs = self.outputs[other_output_indices]\n\n    output_matrix = matrix[output_indices, :]\n    other_output_matrix = matrix[other_output_indices, :]\n\n    return (outputs, other_outputs, output_matrix, other_output_matrix)\n\n  def _PartitionInputs(self, matrix, input_names):\n    \"\"\"Partition the columns of an m-by-nu matrix.\n\n    Args:\n      matrix: An m-by-nu matrix.\n      input_names: Names of the inputs to be included in the first\n          part of the partition.\n\n    Raises:\n      SystemBadDimensionException:  If matrix has the wrong number of columns.\n\n    Returns:\n      A tuple (inputs, other_inputs, input_matrix,\n      other_input_matrix).  The first two entries are SignalLists\n      containing the inputs in input_names and the other inputs.\n      The first matrix is the sub-matrix corresponding to the\n      input_names and the remaining rows are in other_input_matrix.\n    \"\"\"\n    if matrix.shape[1] != self.nu:\n      raise SystemBadDimensionException(matrix)\n\n    inputs = self.inputs[input_names]\n    input_indices = self.inputs.GetIndices(input_names)\n    other_input_indices = [\n        i for i in range(self.nu) if i not in input_indices\n    ]\n    other_inputs = self.inputs[other_input_indices]\n\n    input_matrix = matrix[:, input_indices]\n    other_input_matrix = matrix[:, other_input_indices]\n\n    return (inputs, other_inputs, input_matrix, other_input_matrix)\n\n  def GetStateSpaceModel(self):\n    \"\"\"Return the state-space description of the system.\"\"\"\n    return self._A, self._B, self._C, self._D, self.Ts\n\n  def ReduceStates(self, state_names):\n    \"\"\"Returns a new system model that keeps only a subset of the states.\n\n    Args:\n      state_names: List of state names to retain.\n\n    Returns:\n      A new state-space model with only the desired states retained.\n    \"\"\"\n    state_indices = self.states.GetIndices(state_names)\n    states = self.states[state_names]\n\n    A = self._A[[[s] for s in state_indices], state_indices]\n    B = self._B[[s for s in state_indices], :]\n    C = self._C[:, state_indices]\n\n    return System(A, B, C, self._D, self.Ts, states, self.inputs, self.outputs)\n", "meta": {"hexsha": "edc64c56b45ba5f3fd26d1d46275cf688dbce62a", "size": 11547, "ext": "py", "lang": "Python", "max_stars_repo_path": "analysis/control/systems.py", "max_stars_repo_name": "leozz37/makani", "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1178, "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_issues_repo_path": "analysis/control/systems.py", "max_issues_repo_name": "leozz37/makani", "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_forks_repo_path": "analysis/control/systems.py", "max_forks_repo_name": "leozz37/makani", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 107, "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "avg_line_length": 33.862170088, "max_line_length": 80, "alphanum_fraction": 0.6793106435, "include": true, "reason": "import numpy", "num_tokens": 2733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.19473590220617773}}
{"text": "import time\nimport os\nimport pickle\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom django.core.management.base import BaseCommand\n\nfrom Key import Key\nfrom plot import plot_direct\n\nfrom cycling.models import id_dict_from_id_list\nfrom machine_learning.DegradationModelBlackbox import DegradationModel\nfrom machine_learning.LossRecordBlackbox import LossRecord\n\n# TODO(sam): For each cell_id, needs a multigrid of (S, V, I, T) (current\n#  needs to be adjusted)\n# TODO(sam): Each cycle must have an index mapping to the nearest reference\n#  cycle.\n# TODO(sam): to evaluate a cycle, there must be the multigrid, the reference\n#  cycle scaled by cycle number, the cell features, pasted together and ran\n#  through a neural net.\n\nNEIGH_MIN_CYC = 0\nNEIGH_MAX_CYC = 1\nNEIGH_RATE = 2\nNEIGH_CELL_ID = 3\nNEIGH_ABSOLUTE_CYC = 4\nNEIGH_VALID_CYC = 5\nNEIGH_SIGN_GRID = 6\nNEIGH_VOLTAGE_GRID = 7\nNEIGH_CURRENT_GRID = 8\nNEIGH_TMP_GRID = 9\nNEIGH_ABSOLUTE_REFERENCE = 10\nNEIGH_REFERENCE = 11\n\nNEIGH_TOTAL = 12\n\n\ndef ml_smoothing(options):\n    \"\"\"\n    The main function to carry out the machine learning training and evaluation\n    procedure.\n\n    Todo(harvey): Add more description about what this does.\n\n    Args:\n        options: Dictionary defining various fitting-related arguments.\n\n    Returns: None\n    \"\"\"\n    if len(tf.config.experimental.list_physical_devices(\"GPU\")) == 1:\n        strategy = tf.distribute.OneDeviceStrategy(device = \"/gpu:0\")\n    elif len(tf.config.experimental.list_physical_devices(\"GPU\")) > 1:\n        strategy = tf.distribute.MirroredStrategy()\n    else:\n        strategy = tf.distribute.OneDeviceStrategy(\"/cpu:0\")\n\n    if not os.path.exists(options[Key.PATH_PLOTS]):\n        os.makedirs(options[Key.PATH_PLOTS])\n\n    with open(\n        os.path.join(options[Key.PATH_PLOTS], \"fit_args_log.txt\"), \"w\",\n    ) as f:\n        my_str = \"\"\n        for k in options:\n            my_str = \"{} \\n {}: {}\".format(my_str, k, str(options[k]))\n        f.write(my_str)\n\n    dataset_path = os.path.join(\n        options[Key.PATH_DATASET],\n        \"dataset_ver_{}.file\".format(options[Key.DATA_VERSION])\n    )\n\n    dataset_names_path = os.path.join(\n        options[Key.PATH_DATASET],\n        \"dataset_ver_{}_names.file\".format(options[Key.DATA_VERSION])\n    )\n\n    if not os.path.exists(dataset_path):\n        print(\"Path \\\"\" + dataset_path + \"\\\" does not exist.\")\n        return\n\n    with open(dataset_path, \"rb\") as f:\n        dataset = pickle.load(f)\n\n    dataset_names = None\n    if os.path.exists(dataset_names_path):\n        with open(dataset_names_path, \"rb\") as f:\n            dataset_names = pickle.load(f)\n\n    cell_ids = list(dataset[Key.ALL_DATA].keys())\n\n    if len(options[Key.CELL_IDS]) != 0:\n        cell_ids = list(set(cell_ids).intersection(set(options[Key.CELL_IDS])))\n\n    if len(cell_ids) == 0:\n        print(\"no cell_ids\")\n        return\n\n    train_and_evaluate(\n        initial_processing(\n            dataset, dataset_names, cell_ids, options, strategy = strategy,\n        ),\n        cell_ids,\n        options,\n    )\n\n\n# TODO(sam): these huge tensors would be much easier to understand with\n#  ragged tensors. Right now, I am just flattening everything.\ndef numpy_acc(dict, key, data):\n    if key in dict.keys():\n        dict[key] = np.concatenate((dict[key], data))\n    else:\n        dict[key] = data\n\n    return dict\n\n\ndef three_level_flatten(iterables):\n    for it1 in iterables:\n        for it2 in it1:\n            for element in it2:\n                yield element\n\n\ndef initial_processing(\n    dataset: dict, dataset_names, cell_ids, options: dict, strategy,\n) -> dict:\n    \"\"\" Handle the initial data processing\n\n    Args:\n        dataset: Contains the quantities given in the dataset.\n        dataset_names: TODO(harvey)\n        cell_ids: TODO(harvey)\n        options: Parameters used to tune the machine learning fitting process.\n        strategy: TODO(harvey)\n\n    Returns:\n        { Key.STRAT, Key.MODEL, Key.TENSORS, Key.TRAIN_DS, Key.CYC_M,\n          Key.CYC_V, Key.OPT, Key.MY_DATA }\n\n    \"\"\"\n    # TODO (harvey): Cleanup Docstring, maybe put detailed description elsewhere\n    #   An appropriate place might be in the docstring for\n    #   classes inside cycling.Key\n\n    compiled_data = {}\n    number_of_compiled_cycs = 0\n    number_of_reference_cycs = 0\n\n    dataset[Key.Q_MAX] = 250\n    max_cap = dataset[Key.Q_MAX]\n\n    keys = [Key.V_GRID, Key.TEMP_GRID, Key.SIGN_GRID]\n    for key in keys:\n        numpy_acc(compiled_data, key, np.array([dataset[key]]))\n\n    dataset[Key.I_GRID] = dataset[Key.I_GRID] - np.log(max_cap)\n    # the current grid is adjusted by the max capacity of the cell_id. It is\n    # in log space, so I/q becomes log(I) - log(q)\n    numpy_acc(compiled_data, Key.I_GRID, np.array([dataset[Key.I_GRID]]))\n\n    # TODO (harvey): simplify the following using loops\n    # cell ID array\n    cell_id_array = np.array(cell_ids)\n    # cell ID to positive electrode ID\n    cell_id_to_pos_id = {}\n    # cell ID to negative electrode ID\n    cell_id_to_neg_id = {}\n    # cell ID to electrolyte ID\n    cell_id_to_lyte_id = {}\n    # cell ID to dry cell ID\n    cell_id_to_dry_cell_id = {}\n    # dry cell ID to meta\n    dry_cell_id_to_meta = {}\n    # cell ID to latent\n    cell_id_to_latent = {}\n\n    # electrolyte ID to latent ID weight\n    lyte_to_latent = {}\n    # electrolyte ID to solvent ID weight\n    lyte_to_sol_weight = {}\n    # electrolyte ID to salt ID weight\n    lyte_to_salt_weight = {}\n    # electrolyte ID to additive ID weight\n    lyte_to_addi_weight = {}\n\n    for cell_id in cell_id_array:\n        if cell_id in dataset[Key.CELL_TO_POS].keys():\n            cell_id_to_pos_id[cell_id] = dataset[Key.CELL_TO_POS][cell_id]\n        if cell_id in dataset[Key.CELL_TO_NEG].keys():\n            cell_id_to_neg_id[cell_id] = dataset[Key.CELL_TO_NEG][cell_id]\n        if cell_id in dataset[Key.CELL_TO_LYTE].keys():\n            cell_id_to_lyte_id[cell_id] = dataset[Key.CELL_TO_LYTE][cell_id]\n        if cell_id in dataset[Key.CELL_TO_DRY].keys():\n            dry_cell_id = dataset[Key.CELL_TO_DRY][cell_id]\n            cell_id_to_dry_cell_id[cell_id] = dry_cell_id\n\n            if dry_cell_id in dataset[Key.DRY_TO_META].keys():\n                dry_cell_id_to_meta[dry_cell_id]\\\n                    = dataset[Key.DRY_TO_META][dry_cell_id]\n\n        if cell_id in dataset[Key.CELL_TO_LAT].keys():\n            cell_id_to_latent[cell_id] = dataset[Key.CELL_TO_LAT][cell_id]\n\n        if cell_id_to_latent[cell_id] < 0.5:\n            lyte_id = cell_id_to_lyte_id[cell_id]\n            if lyte_id in dataset[Key.LYTE_TO_SOL].keys():\n                lyte_to_sol_weight[lyte_id] = dataset[Key.LYTE_TO_SOL][lyte_id]\n            if lyte_id in dataset[Key.LYTE_TO_SALT].keys():\n                lyte_to_salt_weight[lyte_id] = dataset[Key.LYTE_TO_SALT][\n                    lyte_id]\n            if lyte_id in dataset[Key.LYTE_TO_ADD].keys():\n                lyte_to_addi_weight[lyte_id] = dataset[Key.LYTE_TO_ADD][lyte_id]\n            if lyte_id in dataset[Key.LYTE_TO_LAT].keys():\n                lyte_to_latent[lyte_id] = dataset[Key.LYTE_TO_LAT][lyte_id]\n\n    mess = [\n        [\n            [s[0] for s in siw] for siw in lyte_to_sol_weight.values()\n        ], [\n            [s[0] for s in siw] for siw in lyte_to_salt_weight.values()\n        ], [\n            [s[0] for s in siw] for siw in lyte_to_addi_weight.values()\n        ],\n    ]\n\n    mol_ids = to_sorted_array(list(three_level_flatten(mess)))\n    dry_cell_ids = to_sorted_array(cell_id_to_dry_cell_id.values())\n    pos_ids = to_sorted_array(cell_id_to_pos_id.values())\n    neg_ids = to_sorted_array(cell_id_to_neg_id.values())\n    lyte_id_list = to_sorted_array(cell_id_to_lyte_id.values())\n\n    for cell_id_count, cell_id in enumerate(cell_ids):\n\n        all_data = dataset[Key.ALL_DATA][cell_id]\n        cyc_grp_dict = all_data[Key.CYC_GRP_DICT]\n\n        for k_count, k in enumerate(cyc_grp_dict.keys()):\n\n            if any([\n                abs(cyc_grp_dict[k][Key.I_PREV_END_AVG]) < 1e-5,\n                abs(cyc_grp_dict[k][Key.I_CC_AVG]) < 1e-5,\n                abs(cyc_grp_dict[k][Key.I_END_AVG]) < 1e-5,\n                abs(cyc_grp_dict[k][Key.V_PREV_END_AVG]) < 1e-1,\n                abs(cyc_grp_dict[k][Key.V_END_AVG]) < 1e-1,\n            ]):\n                continue\n\n            main_data = cyc_grp_dict[k][Key.MAIN]\n\n            # normalize capacity_vector with max_cap\n            normalize_keys = [\n                Key.Q_CC_VEC, Key.Q_CV_VEC, Key.Q_CC_LAST, Key.Q_CV_LAST,\n                Key.I_CV_VEC, Key.I_CC, Key.I_PREV_END,\n            ]\n            for key in normalize_keys:\n                main_data[key] = 1. / max_cap * main_data[key]\n\n            normalize_keys = [Key.I_CC_AVG, Key.I_END_AVG, Key.I_PREV_END_AVG]\n            for key in normalize_keys:\n                cyc_grp_dict[k][key] = 1. / max_cap * cyc_grp_dict[k][key]\n\n            # range of cycles which exist for this cycle group\n            min_cyc = min(main_data[Key.N])\n            max_cyc = max(main_data[Key.N])\n\n            \"\"\"\n            - now create neighborhoods, which contains the cycles,\n              grouped by proximity\n            - want to sample neighborhoods equally\n            - neighborhoods have a central cycle and a delta on each side\n            - to a first approximation, we want a delta_cyc = 300, but we have\n              to vary this near the beginning of data and near the end.\n            \"\"\"\n            number_of_centers = 10\n\n            # the centers of neighborhoods we will try to create\n            all_neigh_center_cycs = np.linspace(\n                min_cyc, max_cyc, number_of_centers,\n            )\n            delta = (\n                1.2 * (all_neigh_center_cycs[1] - all_neigh_center_cycs[0]) + 10\n            )\n            # check all tentative neighborhood centers and\n            # commit the ones that contain good data to the dataset\n            neigh_data = []\n\n            valid_cycs = 0\n            for cyc in all_neigh_center_cycs:\n                # max_cyc and min_cyc are the limits of existing cycles.\n\n                below_cyc = cyc - delta\n                above_cyc = cyc + delta\n\n                # numpy array of True and False; same length as cyc_grp_dict[k]\n                # False when cycle_number falls outside out of\n                # [below_cyc, above_cyc] interval\n                mask = np.logical_and(\n                    below_cyc <= main_data[Key.N],\n                    main_data[Key.N] <= above_cyc,\n                )\n\n                # the indices for the cyc_grp_dict[k] array which correspond\n                # to a True mask\n                all_valid_indices = np.arange(len(mask))[mask]\n\n                # if there are less than 1 valid cycles, skip that neighborhood\n                if len(all_valid_indices) == 0:\n                    continue\n\n                \"\"\"\n                at this point, we know that this neighborhood\n                will be added to the dataset.\n                \"\"\"\n\n                min_cyc_index = all_valid_indices[0]\n                max_cyc_index = all_valid_indices[-1]\n\n                valid_cycs += 1\n\n                \"\"\"\n                this commits the neighborhood to the dataset\n\n                - record the info about the center of the neighborhood\n                  (cycle number, voltage, rate of charge, rate of discharge)\n                - record the relative index (within the cycle group)\n                  of the min cycle, max cycle\n                - record a voltage index, and a cycle group index,\n                  and a cell index\n                - record the absolute index into the table of cycles\n                  (len(cycles_full)).\n                - keep a slot empty for later\n\n                \"\"\"\n\n                neigh_data_i = np.zeros(NEIGH_TOTAL, dtype = np.int32)\n\n                neigh_data_i[NEIGH_MIN_CYC] = min_cyc_index\n                neigh_data_i[NEIGH_MAX_CYC] = max_cyc_index\n                neigh_data_i[NEIGH_RATE] = k_count\n                neigh_data_i[NEIGH_CELL_ID] = cell_id_count\n                neigh_data_i[NEIGH_ABSOLUTE_CYC] = number_of_compiled_cycs\n                # a weight based on prevalence. Set later\n                neigh_data_i[NEIGH_VALID_CYC] = 0\n                neigh_data_i[NEIGH_SIGN_GRID] = 0\n                neigh_data_i[NEIGH_VOLTAGE_GRID] = 0\n                neigh_data_i[NEIGH_CURRENT_GRID] = 0\n                neigh_data_i[NEIGH_TMP_GRID] = 0\n\n                center_cyc = float(cyc)\n                reference_cycs = all_data[Key.REF_ALL_MATS][Key.N]\n\n                index_of_closest_reference = np.argmin(\n                    abs(center_cyc - reference_cycs)\n                )\n\n                neigh_data_i[NEIGH_ABSOLUTE_REFERENCE]\\\n                    = number_of_reference_cycs\n                neigh_data_i[NEIGH_REFERENCE] = index_of_closest_reference\n\n                neigh_data.append(neigh_data_i)\n\n            if valid_cycs != 0:\n                neigh_data = np.array(neigh_data, dtype = np.int32)\n\n                # the empty slot becomes the count of added neighborhoods, which\n                # are used to counterbalance the bias toward longer cycle life\n                neigh_data[:, NEIGH_VALID_CYC] = valid_cycs\n\n                numpy_acc(compiled_data, Key.NEIGH_DATA, neigh_data)\n\n            number_of_compiled_cycs += len(main_data[Key.N])\n            number_of_reference_cycs += len(all_data[Key.REF_ALL_MATS][Key.N])\n\n            dict_to_acc = {\n                Key.REF_CYC: all_data[Key.REF_ALL_MATS][Key.N],\n                Key.COUNT_MATRIX: all_data[Key.REF_ALL_MATS][Key.COUNT_MATRIX],\n                Key.CYC: main_data[Key.N],\n                Key.V_CC_VEC: main_data[Key.V_CC_VEC],\n                Key.Q_CC_VEC: main_data[Key.Q_CC_VEC],\n                Key.MASK_CC_VEC: main_data[Key.MASK_CC_VEC],\n                Key.I_CV_VEC: main_data[Key.I_CV_VEC],\n                Key.Q_CV_VEC: main_data[Key.Q_CV_VEC],\n                Key.MASK_CV_VEC: main_data[Key.MASK_CV_VEC],\n                Key.I_CC: main_data[Key.I_CC],\n                Key.I_PREV_END: main_data[Key.I_PREV_END],\n                Key.V_PREV_END: main_data[Key.V_PREV_END],\n                Key.V_END: main_data[Key.V_END],\n            }\n\n            for key in dict_to_acc:\n                numpy_acc(compiled_data, key, dict_to_acc[key])\n\n    neigh_data = tf.constant(compiled_data[Key.NEIGH_DATA])\n\n    compiled_tensors = {}\n    # cycles go from 0 to 6000, but nn prefers normally distributed variables\n    # so cycle numbers is normalized with mean and variance\n    cycle_tensor = tf.constant(compiled_data[Key.CYC])\n    cycle_m, cycle_v = tf.nn.moments(cycle_tensor, axes = [0])\n    cycle_m = 0.  # we shall leave the cycle 0 at 0\n    cycle_v = cycle_v.numpy()\n    cycle_tensor = (cycle_tensor - cycle_m) / tf.sqrt(cycle_v)\n    compiled_tensors[Key.CYC] = cycle_tensor\n\n    labels = [\n        Key.V_CC_VEC, Key.Q_CC_VEC, Key.MASK_CC_VEC, Key.Q_CV_VEC, Key.I_CV_VEC,\n        Key.MASK_CV_VEC, Key.I_CC, Key.I_PREV_END, Key.V_PREV_END, Key.V_END,\n        Key.COUNT_MATRIX, Key.SIGN_GRID, Key.V_GRID, Key.I_GRID, Key.TEMP_GRID,\n    ]\n    for label in labels:\n        compiled_tensors[label] = tf.constant(compiled_data[label])\n\n    batch_size = options[Key.BATCH]\n\n    with strategy.scope():\n        train_ds_ = tf.data.Dataset.from_tensor_slices(\n            neigh_data\n        ).repeat(2).shuffle(100000).batch(batch_size)\n\n        train_ds = strategy.experimental_distribute_dataset(train_ds_)\n\n        dry_cell_to_dry_cell_name = {}\n        pos_to_pos_name = {}\n        neg_to_neg_name = {}\n        lyte_to_lyte_name = {}\n        mol_to_mol_name = {}\n\n        if dataset_names is not None:\n            pos_to_pos_name = dataset_names[Key.NAME_POS]\n            neg_to_neg_name = dataset_names[Key.NAME_NEG]\n            lyte_to_lyte_name = dataset_names[Key.NAME_LYTE]\n            mol_to_mol_name = dataset_names[Key.NAME_MOL]\n            dry_cell_to_dry_cell_name = dataset_names[Key.NAME_DRY]\n\n        degradation_model = DegradationModel(\n            width = options[Key.WIDTH],\n            depth = options[Key.DEPTH],\n            cell_dict = id_dict_from_id_list(cell_id_array),\n            pos_dict = id_dict_from_id_list(pos_ids),\n            neg_dict = id_dict_from_id_list(neg_ids),\n            lyte_dict = id_dict_from_id_list(lyte_id_list),\n            mol_dict = id_dict_from_id_list(mol_ids),\n            dry_cell_dict = id_dict_from_id_list(dry_cell_ids),\n\n            cell_to_pos = cell_id_to_pos_id,\n            cell_to_neg = cell_id_to_neg_id,\n            cell_to_lyte = cell_id_to_lyte_id,\n            cell_to_dry_cell = cell_id_to_dry_cell_id,\n            dry_cell_to_meta = dry_cell_id_to_meta,\n\n            cell_latent_flags = cell_id_to_latent,\n\n            lyte_to_solvent = lyte_to_sol_weight,\n            lyte_to_salt = lyte_to_salt_weight,\n            lyte_to_additive = lyte_to_addi_weight,\n            lyte_latent_flags = lyte_to_latent,\n\n            names = (\n                pos_to_pos_name,\n                neg_to_neg_name,\n                lyte_to_lyte_name,\n                mol_to_mol_name,\n                dry_cell_to_dry_cell_name,\n            ),\n            n_sample = options[Key.N_SAMPLE],\n            options = options,\n            min_latent = options[Key.MIN_LAT],\n        )\n\n        optimizer = tf.keras.optimizers.Adam(\n            learning_rate = options[Key.LRN_RATE],\n        )\n\n    return {\n        Key.STRAT: strategy,\n        Key.MODEL: degradation_model,\n        Key.TENSORS: compiled_tensors,\n        Key.TRAIN_DS: train_ds,\n        Key.CYC_M: cycle_m,\n        Key.CYC_V: cycle_v,\n        Key.OPT: optimizer,\n        Key.DATASET: dataset,\n    }\n\n\ndef to_sorted_array(unsorted) -> np.array:\n    \"\"\" Remove duplicates from a list or a view object (of a dictionary) and\n        turn it into to a sorted array.\n\n    Args:\n        unsorted: Unsorted list or view object (of a dictionary).\n\n    Returns:\n        Sorted array of `unsorted`.\n    \"\"\"\n    return np.array(sorted(list(set(unsorted))))\n\n\ndef train_and_evaluate(\n    init_returns: dict, cell_ids: list, options: dict,\n) -> None:\n    \"\"\"\n\n    Args:\n        init_returns: Return value of `initial_processing`.\n        cell_ids: Specified cell IDs (identifiers for different cells).\n        options:\n    \"\"\"\n    strategy = init_returns[Key.STRAT]\n\n    epochs = 100000\n    count = 0\n\n    end = time.time()\n\n    train_step_params = {\n        Key.TENSORS: init_returns[Key.TENSORS],\n        Key.OPT: init_returns[Key.OPT],\n        Key.MODEL: init_returns[Key.MODEL],\n    }\n\n    @tf.function\n    def dist_train_step(strategy, neigh):\n        return strategy.experimental_run_v2(\n            lambda neigh: train_step(neigh, train_step_params, options),\n            args = (neigh,),\n        )\n\n    # TODO(harvey, confusion): what is `l`?\n    l = None\n    loss_record = LossRecord()\n    with strategy.scope():\n        for epoch in range(epochs):\n            sub_count = 0\n            for neigh in init_returns[Key.TRAIN_DS]:\n                count += 1\n                sub_count += 1\n\n                l_ = dist_train_step(strategy, neigh)\n                if l is None:\n                    l = l_\n                else:\n                    l += l_\n\n                if count != 0:\n                    if (count % options[Key.PRINT_LOSS]) == 0:\n                        tot = l / tf.cast(sub_count, dtype = tf.float32)\n                        l = None\n                        sub_count = 0\n                        loss_record.record(count, tot.numpy())\n                        loss_record.print_recent(options)\n\n                    plot_params = {\n                        \"cell_ids\": cell_ids,\n                        \"count\": count,\n                        Key.OPTIONS: options,\n                    }\n\n                    if (count % options[Key.VIS_FIT]) == 0:\n                        start = time.time()\n                        print(\"time to simulate: \", start - end)\n                        loss_record.plot(count, options)\n                        plot_direct(\n                            \"generic_vs_cycle\", plot_params, init_returns,\n                        )\n                        plot_direct(\n                            \"generic_vs_capacity\", plot_params, init_returns,\n                        )\n\n                        end = time.time()\n                        print(\"time to plot: \", end - start)\n                        print()\n\n                if count >= options[Key.STOP]:\n                    return\n\n\ndef train_step(neigh, params: dict, options: dict):\n    \"\"\" One training step.\n\n    Args:\n        neigh: Neighbourhood.\n        params: Contains all necessary parameters.\n        options: Options for `ml_smoothing`.\n    \"\"\"\n    # need to split the range\n    batch_size2 = neigh.shape[0]\n\n    degradation_model = params[Key.MODEL]\n    optimizer = params[Key.OPT]\n    compiled_tensors = params[Key.TENSORS]\n\n    sign_grid_tensor = compiled_tensors[Key.SIGN_GRID]\n    voltage_grid_tensor = compiled_tensors[Key.V_GRID]\n    current_grid_tensor = compiled_tensors[Key.I_GRID]\n    tmp_grid_tensor = compiled_tensors[Key.TEMP_GRID]\n\n    count_matrix_tensor = compiled_tensors[Key.COUNT_MATRIX]\n\n    cycle_tensor = compiled_tensors[Key.CYC]\n    constant_current_tensor = compiled_tensors[Key.I_CC]\n    end_current_prev_tensor = compiled_tensors[Key.I_PREV_END]\n    end_voltage_prev_tensor = compiled_tensors[Key.V_PREV_END]\n    end_voltage_tensor = compiled_tensors[Key.V_END]\n\n    cc_voltage_tensor = compiled_tensors[Key.V_CC_VEC]\n    cc_capacity_tensor = compiled_tensors[Key.Q_CC_VEC]\n    cc_mask_tensor = compiled_tensors[Key.MASK_CC_VEC]\n    cv_capacity_tensor = compiled_tensors[Key.Q_CV_VEC]\n    cv_current_tensor = compiled_tensors[Key.I_CV_VEC]\n    cv_mask_tensor = compiled_tensors[Key.MASK_CV_VEC]\n\n    \"\"\"\n    if you have the minimum cycle and maximum cycle for a neighborhood,\n    you can sample cycle from this neighborhood by sampling real numbers\n    x from [0,1] and computing min_cyc*(1.-x) + max_cyc*x,\n    but here this computation is done in index space,\n    then cycle numbers and vq curves are gathered\n    \"\"\"\n\n    cyc_indices_lerp = tf.random.uniform(\n        [batch_size2], minval = 0., maxval = 1., dtype = tf.float32,\n    )\n    cyc_indices = tf.cast(\n        (1. - cyc_indices_lerp) * tf.cast(\n            neigh[:, NEIGH_MIN_CYC] + neigh[:, NEIGH_ABSOLUTE_CYC],\n            tf.float32,\n        ) + cyc_indices_lerp * tf.cast(\n            neigh[:, NEIGH_MAX_CYC] + neigh[:, NEIGH_ABSOLUTE_CYC],\n            tf.float32,\n        ),\n        tf.int32,\n    )\n\n    sign_grid = tf.gather(\n        sign_grid_tensor, indices = neigh[:, NEIGH_SIGN_GRID], axis = 0,\n    )\n    sign_grid_dim = sign_grid.shape[1]\n\n    voltage_grid = tf.gather(\n        voltage_grid_tensor, indices = neigh[:, NEIGH_VOLTAGE_GRID], axis = 0,\n    )\n    voltage_grid_dim = voltage_grid.shape[1]\n\n    current_grid = tf.gather(\n        current_grid_tensor, indices = neigh[:, NEIGH_CURRENT_GRID], axis = 0,\n    )\n    current_grid_dim = current_grid.shape[1]\n\n    tmp_grid = tf.gather(\n        tmp_grid_tensor, indices = neigh[:, NEIGH_TMP_GRID], axis = 0,\n    )\n    tmp_grid_dim = tmp_grid.shape[1]\n\n    svit_tuple = (\n        tf.tile(\n            tf.reshape(\n                sign_grid, [batch_size2, sign_grid_dim, 1, 1, 1, 1],\n            ),\n            [1, 1, voltage_grid_dim, current_grid_dim, tmp_grid_dim, 1],\n        ),\n        tf.tile(\n            tf.reshape(\n                voltage_grid, [batch_size2, 1, voltage_grid_dim, 1, 1, 1],\n            ),\n            [1, sign_grid_dim, 1, current_grid_dim, tmp_grid_dim, 1],\n        ),\n        tf.tile(\n            tf.reshape(\n                current_grid, [batch_size2, 1, 1, current_grid_dim, 1, 1],\n            ),\n            [1, sign_grid_dim, voltage_grid_dim, 1, tmp_grid_dim, 1],\n        ),\n        tf.tile(\n            tf.reshape(\n                tmp_grid, [batch_size2, 1, 1, 1, tmp_grid_dim, 1],\n            ),\n            [1, sign_grid_dim, voltage_grid_dim, current_grid_dim, 1, 1],\n        ),\n    )\n    svit_grid = tf.concat(svit_tuple, axis = -1)\n\n    count_matrix = tf.reshape(\n        tf.gather(\n            count_matrix_tensor,\n            neigh[:, NEIGH_ABSOLUTE_REFERENCE] + neigh[:, NEIGH_REFERENCE],\n            axis = 0,\n        ),\n        [\n            batch_size2, sign_grid_dim, voltage_grid_dim, current_grid_dim,\n            tmp_grid_dim, 1,\n        ],\n    )\n\n    cycle = tf.gather(cycle_tensor, indices = cyc_indices, axis = 0)\n    constant_current = tf.gather(\n        constant_current_tensor, indices = cyc_indices, axis = 0,\n    )\n    end_current_prev = tf.gather(\n        end_current_prev_tensor, indices = cyc_indices, axis = 0,\n    )\n    end_voltage_prev = tf.gather(\n        end_voltage_prev_tensor, indices = cyc_indices, axis = 0,\n    )\n    end_voltage = tf.gather(\n        end_voltage_tensor, indices = cyc_indices, axis = 0,\n    )\n\n    cc_capacity = tf.gather(cc_capacity_tensor, indices = cyc_indices)\n    cc_voltage = tf.gather(cc_voltage_tensor, indices = cyc_indices)\n    cc_mask = tf.gather(cc_mask_tensor, indices = cyc_indices)\n    cc_mask_2 = tf.tile(\n        tf.reshape(\n            1. / tf.cast(neigh[:, NEIGH_VALID_CYC], tf.float32),\n            [batch_size2, 1],\n        ),\n        [1, cc_voltage.shape[1]],\n    )\n\n    cv_capacity = tf.gather(cv_capacity_tensor, indices = cyc_indices)\n    cv_current = tf.gather(cv_current_tensor, indices = cyc_indices)\n    cv_mask = tf.gather(cv_mask_tensor, indices = cyc_indices)\n    cv_mask_2 = tf.tile(\n        tf.reshape(\n            1. / tf.cast(neigh[:, NEIGH_VALID_CYC], tf.float32),\n            [batch_size2, 1],\n        ),\n        [1, cv_current.shape[1]],\n    )\n\n    cell_indices = neigh[:, NEIGH_CELL_ID]\n\n    with tf.GradientTape() as tape:\n        train_results = degradation_model(\n            {\n                Key.CYC: tf.expand_dims(cycle, axis = 1),\n                Key.I_CC: tf.expand_dims(constant_current, axis = 1),\n                Key.I_PREV_END: tf.expand_dims(end_current_prev, axis = 1),\n                Key.V_PREV_END: tf.expand_dims(end_voltage_prev, axis = 1),\n                Key.V_END: tf.expand_dims(end_voltage, axis = 1),\n                Key.INDICES: cell_indices,\n                Key.V_TENSOR: cc_voltage,\n                Key.I_TENSOR: cv_current,\n                Key.SVIT_GRID: svit_grid,\n                Key.COUNT_MATRIX: count_matrix,\n            },\n            training = True,\n        )\n\n        pred_cc_capacity = train_results[Key.Pred.I_CC]\n        pred_cv_capacity = train_results[Key.Pred.I_CV]\n\n        cc_capacity_loss = get_loss(\n            cc_capacity, pred_cc_capacity, cc_mask, cc_mask_2,\n        )\n        cv_capacity_loss = get_loss(\n            cv_capacity, pred_cv_capacity, cv_mask, cv_mask_2,\n        )\n\n        main_losses = (\n            options[Key.Coeff.Q_CV] * cv_capacity_loss\n            + options[Key.Coeff.Q_CC] * cc_capacity_loss\n        )\n        loss = main_losses + tf.stop_gradient(main_losses) * (\n            options[Key.Coeff.Q] * train_results[Key.Loss.Q]\n            + options[Key.Coeff.CELL] * train_results[Key.Loss.CELL]\n        )\n\n    gradients = tape.gradient(loss, degradation_model.trainable_variables)\n\n    gradients_no_nans = [\n        tf.where(tf.math.is_nan(x), tf.zeros_like(x), x) for x in gradients\n    ]\n\n    gradients_norm_clipped, _ = tf.clip_by_global_norm(\n        gradients_no_nans, options[Key.GLB_NORM_CLIP],\n    )\n\n    optimizer.apply_gradients(\n        zip(gradients_norm_clipped, degradation_model.trainable_variables)\n    )\n\n    return tf.stack(\n        [\n            cc_capacity_loss,\n            cv_capacity_loss,\n            train_results[Key.Loss.Q],\n            train_results[Key.Loss.CELL],\n        ],\n    )\n\n\ndef get_loss(measured, predicted, mask, mask_2):\n    return tf.reduce_mean(\n        (1e-10 + mask * mask_2) * tf.square(measured - predicted)\n    ) / (1e-10 + tf.reduce_mean(mask * mask_2))\n\n\nclass Command(BaseCommand):\n\n    def add_arguments(self, parser):\n\n        required_args = [\n            Key.PATH_DATASET,\n            Key.DATA_VERSION,\n            Key.PATH_PLOTS,\n        ]\n\n        float_args = {\n            Key.GLB_NORM_CLIP: 10.,\n\n            Key.LRN_RATE: 5e-4,\n            Key.MIN_LAT: .05,\n\n            Key.COEFF_FEAT_CELL_DER: .001,\n            Key.COEFF_FEAT_CELL_DER2: .01,\n\n            Key.COEFF_CELL: 1.,\n            Key.COEFF_CELL_OUT: .1,\n            Key.COEFF_CELL_IN: .1,\n            Key.COEFF_CELL_DER: .1,\n            Key.COEFF_CELL_EQ: 10.,\n\n            Key.COEFF_LYTE: 1.,\n            Key.COEFF_LYTE_OUT: .1,\n            Key.COEFF_LYTE_IN: .1,\n            Key.COEFF_LYTE_DER: .1,\n            Key.COEFF_LYTE_EQ: 10.,\n\n            Key.COEFF_Q_CV: 1.,\n            Key.COEFF_Q_CC: 1.,\n\n            Key.COEFF_Q: 1.,\n            Key.COEFF_Q_GEQ: 1.,\n            Key.COEFF_Q_LEQ: 1.,\n            Key.COEFF_Q_V_MONO: .1,\n            Key.COEFF_Q_DER3_V: 1.,\n            Key.COEFF_Q_DER3_I: 1.,\n            Key.COEFF_Q_DER3_N: 1.,\n            Key.COEFF_Q_DER_I: 1.,\n            Key.COEFF_Q_DER_N: 10.,\n        }\n\n        vis = 10000\n        int_args = {\n            Key.N_SAMPLE: 8 * 16,\n\n            Key.DEPTH: 3,\n            Key.WIDTH: 50,\n            Key.BATCH: 4 * 16,\n\n            Key.PRINT_LOSS: 500,\n            Key.VIS_FIT: vis,\n            Key.VIS_VQ: vis,\n\n            Key.STOP: 1000004,\n            Key.CELL_ID_SHOW: 10,\n        }\n\n        for arg in required_args:\n            parser.add_argument(\"--\" + arg, required = True)\n        for arg in float_args:\n            parser.add_argument(\n                \"--\" + arg, type = float, default = float_args[arg],\n            )\n        for arg in int_args:\n            parser.add_argument(\"--\" + arg, type = int, default = int_args[arg])\n\n        cell_ids = [\n            57706, 57707, 57710, 57711, 57714, 57715, 64260, 64268, 83010,\n            83011, 83012, 83013, 83014, 83015, 83016, 81602, 81603, 81604,\n            81605, 81606, 81607, 81608, 81609, 81610, 81611, 81612, 81613,\n            81614, 81615, 81616, 81617, 81618, 81619, 81620, 81621, 81622,\n            81623, 81624, 81625, 81626, 81627, 81712, 81713, 82300, 82301,\n            82302, 82303, 82304, 82305, 82306, 82307, 82308, 82309, 82310,\n            82311, 82406, 82407, 82410, 82411, 82769, 82770, 82771, 82775,\n            82776, 82777, 82779, 82992, 82993, 83083, 83092, 83101, 83106,\n            83107, 83220, 83221, 83222, 83223, 83224, 83225, 83226, 83227,\n            83228, 83229, 83230, 83231, 83232, 83233, 83234, 83235, 83236,\n            83237, 83239, 83240, 83241, 83242, 83243, 83310, 83311, 83312,\n            83317, 83318, 83593, 83594, 83595, 83596, 83741, 83742, 83743,\n            83744, 83745, 83746, 83747, 83748,\n        ]\n\n        parser.add_argument(\n            \"--\" + Key.CELL_IDS, type = int, nargs = \"+\", default = cell_ids,\n        )\n\n    def handle(self, *args, **options):\n        ml_smoothing(options)\n", "meta": {"hexsha": "9068da85e4cd66b7606960779d456c1940c20647", "size": 30903, "ext": "py", "lang": "Python", "max_stars_repo_path": "machine_learning/management/commands/ml_smoothing.py", "max_stars_repo_name": "Samuel-Buteau/universal-battery-database", "max_stars_repo_head_hexsha": "55e64db74eb05cd9f0541a243bb540c0deba7d60", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2020-06-16T16:25:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T12:38:32.000Z", "max_issues_repo_path": "machine_learning/management/commands/ml_smoothing.py", "max_issues_repo_name": "agafonovslava/universal-battery-database", "max_issues_repo_head_hexsha": "55e64db74eb05cd9f0541a243bb540c0deba7d60", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 66, "max_issues_repo_issues_event_min_datetime": "2020-04-14T17:18:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T13:46:09.000Z", "max_forks_repo_path": "machine_learning/management/commands/ml_smoothing.py", "max_forks_repo_name": "agafonovslava/universal-battery-database", "max_forks_repo_head_hexsha": "55e64db74eb05cd9f0541a243bb540c0deba7d60", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-04-27T01:31:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-13T18:04:53.000Z", "avg_line_length": 34.4899553571, "max_line_length": 80, "alphanum_fraction": 0.5942788726, "include": true, "reason": "import numpy", "num_tokens": 7887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.19473590044089656}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"EEG-driven deep learning classifications and model generation\nSoftware tools used generate results in submitted work to (tentative citation pending review):\n\nDavid O. Nahmias, Eugene F. Civillico, and Kimberly L. Kontson. \nDeep Learning and Feature Based Medication Classifications from EEG in a Large Clinical Data Set \nIn review (2020)\n\n\nIf you have found this software useful please consider citing our publication.\n\nPublic domain license\n\"\"\"\n\n\"\"\" Disclaimer:\nThis software and documentation (the \"Software\") were developed at the Food and Drug Administration (FDA) by employees\nof the Federal Government in the course of their official duties. Pursuant to Title 17, Section 105 of the United States Code,\nthis work is not subject to copyright protection and is in the public domain. Permission is hereby granted, free of charge,\nto any person obtaining a copy of the Software, to deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense, or sell copies of the Software or derivatives,\nand to permit persons to whom the Software is furnished to do so. FDA assumes no responsibility whatsoever for use by other\nparties of the Software, its source code, documentation or compiled executables, and makes no guarantees, expressed or implied,\nabout its quality, reliability, or any other characteristic. Further, use of this code in no way implies endorsement by the FDA\nor confers any advantage in regulatory decisions. Although this software can be redistributed and/or modified freely, we ask that\nany derivative works bear some notice that they are derived from it, and any modified versions bear some notice that they have been modified.\n\"\"\"\n\n__author__ = 'David Nahmias'\n__copyright__ = 'No copyright - US Government, 2020 , DeepEEG classification'\n__credits__ = ['David Nahmias']\n__license__ = 'Public domain'\n__version__ = '0.0.1'\n__maintainer__ = 'David Nahmias'\n__email__ = 'david.nahmias@fda.hhs.gov'\n__status__ = 'alpha'\n\nimport logging\nimport time\nfrom copy import copy\nimport sys\n\nfrom collections import Counter\nimport random\nimport numpy as np\nfrom numpy.random import RandomState\nimport resampy\nfrom torch import optim\nimport torch.nn.functional as F\nimport torch as th\nfrom torch.nn.functional import elu\nfrom torch import nn\n\nfrom braindecode.datautil.signal_target import SignalAndTarget\nfrom braindecode.torch_ext.util import np_to_var\nfrom braindecode.torch_ext.util import set_random_seeds\nfrom braindecode.torch_ext.modules import Expression\nfrom braindecode.experiments.experiment import Experiment\nfrom braindecode.datautil.iterators import CropsFromTrialsIterator\nfrom braindecode.experiments.monitors import (RuntimeMonitor, LossMonitor,\n                                              MisclassMonitor)\nfrom braindecode.experiments.stopcriteria import MaxEpochs\nfrom braindecode.models.shallow_fbcsp import ShallowFBCSPNet\nfrom braindecode.models.deep4 import Deep4Net\nfrom braindecode.models.util import to_dense_prediction_model\nfrom braindecode.datautil.iterators import get_balanced_batches\nfrom braindecode.torch_ext.constraints import MaxNormDefaultConstraint\nfrom braindecode.torch_ext.util import var_to_np\nfrom braindecode.torch_ext.functions import identity\n\nfrom dataset import DiagnosisSet\nfrom monitors import compute_preds_per_trial, CroppedDiagnosisMonitor\n\nlog = logging.getLogger(__name__)\nlog.setLevel('DEBUG')\n\nimport pdb\nfrom loadNEDC import loadNEDCdata,loadSubNormData,addDataNoise\n\nif len(sys.argv)>1:\n    if ',' in sys.argv[1]:\n        CLASSY = sys.argv[1].split(',')\n        CLASSY[2] = int(CLASSY[2])\n        if len(CLASSY) == 4:\n            CLASSY[3] = int(CLASSY[3])\n    else:\n        CLASSY = str(sys.argv[1])\n\ndef splitDataRandom(allData,allLabels,setNum=0,shuffle=0):\n    numberEqSamples = min(Counter(allLabels).values())\n    trainSamplesNum = int(np.ceil(numberEqSamples*0.9))\n    testSamplesNum = numberEqSamples-trainSamplesNum\n\n    labels0 = allLabels[allLabels == 0]\n    labels1 = allLabels[allLabels == 1]\n    data0 = allData[allLabels == 0]\n    data1 = allData[allLabels == 1]\n\n\n    fullRange = list(range(numberEqSamples))\n    random.shuffle(fullRange)\n\n\n    testIndecies = fullRange[trainSamplesNum:]\n    trainIndecies = fullRange[:trainSamplesNum]\n\n    allDataTrain = np.concatenate((data0[trainIndecies],data1[trainIndecies]),axis=0)\n    allLabelsTrain = np.concatenate((labels0[trainIndecies],labels1[trainIndecies]),axis=0)\n\n    allDataTest = np.concatenate((data0[testIndecies],data1[testIndecies]),axis=0)\n    allLabelsTest = np.concatenate((labels0[testIndecies],labels1[testIndecies]),axis=0)\n\n    if shuffle == 1:\n        random.shuffle(allLabelsTrain)\n        np.save('sessionsData/trainLabels%s-shuffle-sessions'%CLASSY,allLabelsTrain)\n        np.save('sessionsData/dataRangeOrder%s-shuffle-sessions'%CLASSY,fullRange)\n    else:\n        np.save('sessionsData/dataRangeOrder%s-sessions'%CLASSY,fullRange)\n\n\n    return allDataTrain,allLabelsTrain,allDataTest,allLabelsTest\n\n\ndef create_set(X, y, inds):\n    \"\"\"\n    X list and y nparray\n    :return: \n    \"\"\"\n    new_X = []\n    for i in inds:\n        new_X.append(X[i])\n    new_y = y[inds]\n    return SignalAndTarget(new_X, new_y)\n\n\nclass TrainValidTestSplitter(object):\n    def __init__(self, n_folds, i_test_fold, shuffle):\n        self.n_folds = n_folds\n        self.i_test_fold = i_test_fold\n        self.rng = RandomState(39483948)\n        self.shuffle = shuffle\n\n    def split(self, X, y,):\n        if len(X) < self.n_folds:\n            raise ValueError(\"Less Trials: {:d} than folds: {:d}\".format(\n                len(X), self.n_folds\n            ))\n        folds = get_balanced_batches(len(X), self.rng, self.shuffle,\n                                     n_batches=self.n_folds)\n        test_inds = folds[self.i_test_fold]\n        valid_inds = folds[self.i_test_fold - 1]\n        all_inds = list(range(len(X)))\n        train_inds = np.setdiff1d(all_inds, np.union1d(test_inds, valid_inds))\n        assert np.intersect1d(train_inds, valid_inds).size == 0\n        assert np.intersect1d(train_inds, test_inds).size == 0\n        assert np.intersect1d(valid_inds, test_inds).size == 0\n        assert np.array_equal(np.sort(\n            np.union1d(train_inds, np.union1d(valid_inds, test_inds))),\n            all_inds)\n\n        train_set = create_set(X, y, train_inds)\n        valid_set = create_set(X, y, valid_inds)\n        test_set = create_set(X, y, test_inds)\n\n        return train_set, valid_set, test_set\n\n\nclass TrainValidSplitter(object):\n    def __init__(self, n_folds, i_valid_fold, shuffle):\n        self.n_folds = n_folds\n        self.i_valid_fold = i_valid_fold\n        self.rng = RandomState(39483948)\n        self.shuffle = shuffle\n\n    def split(self, X, y):\n        if len(X) < self.n_folds:\n            raise ValueError(\"Less Trials: {:d} than folds: {:d}\".format(\n                len(X), self.n_folds\n            ))\n        folds = get_balanced_batches(len(X), self.rng, self.shuffle,\n                                     n_batches=self.n_folds)\n        valid_inds = folds[self.i_valid_fold]\n        all_inds = list(range(len(X)))\n        train_inds = np.setdiff1d(all_inds, valid_inds)\n        assert np.intersect1d(train_inds, valid_inds).size == 0\n        assert np.array_equal(np.sort(np.union1d(train_inds, valid_inds)),\n            all_inds)\n\n        train_set = create_set(X, y, train_inds)\n        valid_set = create_set(X, y, valid_inds)\n        return train_set, valid_set\n\n\ndef run_exp(data_folders,\n            n_recordings,\n            sensor_types,\n            n_chans,\n            max_recording_mins,\n            sec_to_cut, duration_recording_mins,\n            test_recording_mins,\n            max_abs_val,\n            sampling_freq,\n            divisor,\n            test_on_eval,\n            n_folds, i_test_fold,\n            shuffle,\n            model_name,\n            n_start_chans, n_chan_factor,\n            input_time_length, final_conv_length,\n            model_constraint,\n            init_lr,\n            batch_size, max_epochs,cuda,):\n    \n    import torch.backends.cudnn as cudnn\n    cudnn.benchmark = True\n    preproc_functions = []\n    preproc_functions.append(\n        lambda data, fs: (data[:, int(sec_to_cut * fs):-int(\n            sec_to_cut * fs)], fs))\n    preproc_functions.append(\n        lambda data, fs: (data[:, :int(duration_recording_mins * 60 * fs)], fs))\n    if max_abs_val is not None:\n        preproc_functions.append(lambda data, fs:\n                                 (np.clip(data, -max_abs_val, max_abs_val), fs))\n\n    preproc_functions.append(lambda data, fs: (resampy.resample(data, fs,\n                                                                sampling_freq,\n                                                                axis=1,\n                                                                filter='kaiser_fast'),\n                                               sampling_freq))\n\n    if divisor is not None:\n        preproc_functions.append(lambda data, fs: (data / divisor, fs))\n\n    dataset = DiagnosisSet(n_recordings=n_recordings,\n                           max_recording_mins=max_recording_mins,\n                           preproc_functions=preproc_functions,\n                           data_folders=data_folders,\n                           train_or_eval='train',\n                           sensor_types=sensor_types)\n    if test_on_eval:\n        if test_recording_mins is None:\n            test_recording_mins = duration_recording_mins\n        test_preproc_functions = copy(preproc_functions)\n        test_preproc_functions[1] = lambda data, fs: (\n            data[:, :int(test_recording_mins * 60 * fs)], fs)\n        test_dataset = DiagnosisSet(n_recordings=n_recordings,\n                                max_recording_mins=None,\n                                preproc_functions=test_preproc_functions,\n                                data_folders=data_folders,\n                                train_or_eval='eval',\n                                sensor_types=sensor_types)\n    #X,y = dataset.load()\n    #test_X, test_y = test_dataset.load()\n\n    #X,y = loadNEDCdata(mode='train')\n    print(CLASSY)\n    #X,y,test_X,test_y = loadNEDCdata(mode='all',classy=CLASSY)\n\n    data = np.load('sessionsData/data%s-sessions.npy'%CLASSY[:3])\n    labels = np.load('sessionsData/labels%s-sessions.npy'%CLASSY[:3])\n\n    #pdb.set_trace()\n\n    if len(CLASSY) > 3:\n        random.seed(11081992 + int(CLASSY[3]))\n    else:\n        random.seed(11081992)\n\n    X,y,test_X,test_y = splitDataRandom(data,labels,shuffle=0)\n\n    #X = np.load('trainData%s.npy'%CLASSY)\n    #y = np.load('trainLabels%s.npy'%CLASSY)\n    #test_X = np.load('testData%s.npy'%CLASSY)\n    #test_y = np.load('testLabels%s.npy'%CLASSY)\n\n    #return False\n\n    #pdb.set_trace()\n\n    #X,y,test_X,test_y = loadSubNormData(mode='all')\n\n    #X = addDataNoise(X,band=[1,4])\n    #test_X = addDataNoise(test_X,band=[1,4])\n    #pdb.set_trace()\n\n    \n    max_shape = np.max([list(x.shape) for x in X],\n                       axis=0)\n    assert max_shape[1] == int(duration_recording_mins *\n                               sampling_freq * 60)\n    if test_on_eval:\n        #test_X, test_y = test_dataset.load()\n        #test_X, test_y = loadNEDCdata(mode='eval')\n        max_shape = np.max([list(x.shape) for x in test_X],\n                           axis=0)\n        assert max_shape[1] == int(test_recording_mins *\n                                   sampling_freq * 60)\n    if not test_on_eval:\n        splitter = TrainValidTestSplitter(n_folds, i_test_fold,\n                                          shuffle=shuffle)\n        train_set, valid_set, test_set = splitter.split(X, y)\n    else:\n        splitter = TrainValidSplitter(n_folds, i_valid_fold=i_test_fold,\n                                          shuffle=shuffle)\n        train_set, valid_set = splitter.split(X, y)\n        test_set = SignalAndTarget(test_X, test_y)\n        del test_X, test_y\n    del X,y # shouldn't be necessary, but just to make sure\n\n    #pdb.set_trace()\n\n    set_random_seeds(seed=20170629, cuda=cuda)\n    n_classes = 2\n    if model_name == 'shallow':\n        model = ShallowFBCSPNet(in_chans=n_chans, n_classes=n_classes,\n                                n_filters_time=n_start_chans,\n                                n_filters_spat=n_start_chans,\n                                input_time_length=input_time_length,\n                                final_conv_length=final_conv_length).create_network()\n    elif model_name == 'deep':\n        model = Deep4Net(n_chans, n_classes,\n                         n_filters_time=n_start_chans,\n                         n_filters_spat=n_start_chans,\n                         input_time_length=input_time_length,\n                         n_filters_2 = int(n_start_chans * n_chan_factor),\n                         n_filters_3 = int(n_start_chans * (n_chan_factor ** 2.0)),\n                         n_filters_4 = int(n_start_chans * (n_chan_factor ** 3.0)),\n                         final_conv_length=final_conv_length,\n                        stride_before_pool=True).create_network()\n    elif (model_name == 'deep_smac'):\n        if model_name == 'deep_smac':\n            do_batch_norm = False\n        else:\n            assert model_name == 'deep_smac_bnorm'\n            do_batch_norm = True\n        double_time_convs = False\n        drop_prob = 0.244445\n        filter_length_2 = 12\n        filter_length_3 = 14\n        filter_length_4 = 12\n        filter_time_length = 21\n        final_conv_length = 1\n        first_nonlin = elu\n        first_pool_mode = 'mean'\n        first_pool_nonlin = identity\n        later_nonlin = elu\n        later_pool_mode = 'mean'\n        later_pool_nonlin = identity\n        n_filters_factor = 1.679066\n        n_filters_start = 32\n        pool_time_length = 1\n        pool_time_stride = 2\n        split_first_layer = True\n        n_chan_factor = n_filters_factor\n        n_start_chans = n_filters_start\n        model = Deep4Net(n_chans, n_classes,\n                 n_filters_time=n_start_chans,\n                 n_filters_spat=n_start_chans,\n                 input_time_length=input_time_length,\n                 n_filters_2=int(n_start_chans * n_chan_factor),\n                 n_filters_3=int(n_start_chans * (n_chan_factor ** 2.0)),\n                 n_filters_4=int(n_start_chans * (n_chan_factor ** 3.0)),\n                 final_conv_length=final_conv_length,\n                 batch_norm=do_batch_norm,\n                 double_time_convs=double_time_convs,\n                 drop_prob=drop_prob,\n                 filter_length_2=filter_length_2,\n                 filter_length_3=filter_length_3,\n                 filter_length_4=filter_length_4,\n                 filter_time_length=filter_time_length,\n                 first_nonlin=first_nonlin,\n                 first_pool_mode=first_pool_mode,\n                 first_pool_nonlin=first_pool_nonlin,\n                 later_nonlin=later_nonlin,\n                 later_pool_mode=later_pool_mode,\n                 later_pool_nonlin=later_pool_nonlin,\n                 pool_time_length=pool_time_length,\n                 pool_time_stride=pool_time_stride,\n                 split_first_layer=split_first_layer,\n                 stride_before_pool=True).create_network()\n    elif model_name == 'shallow_smac':\n        conv_nonlin = identity\n        do_batch_norm = True\n        drop_prob = 0.328794\n        filter_time_length = 56\n        final_conv_length = 22\n        n_filters_spat = 73\n        n_filters_time = 24\n        pool_mode = 'max'\n        pool_nonlin = identity\n        pool_time_length = 84\n        pool_time_stride = 3\n        split_first_layer = True\n        model = ShallowFBCSPNet(in_chans=n_chans, n_classes=n_classes,\n                                n_filters_time=n_filters_time,\n                                n_filters_spat=n_filters_spat,\n                                input_time_length=input_time_length,\n                                final_conv_length=final_conv_length,\n                                conv_nonlin=conv_nonlin,\n                                batch_norm=do_batch_norm,\n                                drop_prob=drop_prob,\n                                filter_time_length=filter_time_length,\n                                pool_mode=pool_mode,\n                                pool_nonlin=pool_nonlin,\n                                pool_time_length=pool_time_length,\n                                pool_time_stride=pool_time_stride,\n                                split_first_layer=split_first_layer,\n                                ).create_network()\n    elif model_name == 'linear':\n        model = nn.Sequential()\n        model.add_module(\"conv_classifier\",\n                         nn.Conv2d(n_chans, n_classes, (600,1)))\n        model.add_module('softmax', nn.LogSoftmax(dim=1))\n        model.add_module('squeeze', Expression(lambda x: x.squeeze(3)))\n    else:\n        assert False, \"unknown model name {:s}\".format(model_name)\n    to_dense_prediction_model(model)\n    log.info(\"Model:\\n{:s}\".format(str(model)))\n    if cuda:\n        model.cuda()\n    # determine output size\n    test_input = np_to_var(\n        np.ones((2, n_chans, input_time_length, 1), dtype=np.float32))\n    if cuda:\n        test_input = test_input.cuda()\n    log.info(\"In shape: {:s}\".format(str(test_input.cpu().data.numpy().shape)))\n\n    out = model(test_input)\n    log.info(\"Out shape: {:s}\".format(str(out.cpu().data.numpy().shape)))\n    n_preds_per_input = out.cpu().data.numpy().shape[2]\n    log.info(\"{:d} predictions per input/trial\".format(n_preds_per_input))\n    iterator = CropsFromTrialsIterator(batch_size=batch_size,\n                                       input_time_length=input_time_length,\n                                       n_preds_per_input=n_preds_per_input)\n    optimizer = optim.Adam(model.parameters(), lr=init_lr)\n\n    loss_function = lambda preds, targets: F.nll_loss(\n        th.mean(preds, dim=2, keepdim=False), targets)\n\n    if model_constraint is not None:\n        assert model_constraint == 'defaultnorm'\n        model_constraint = MaxNormDefaultConstraint()\n    monitors = [LossMonitor(), MisclassMonitor(col_suffix='sample_misclass'),\n                CroppedDiagnosisMonitor(input_time_length, n_preds_per_input),\n                RuntimeMonitor(),]\n    stop_criterion = MaxEpochs(max_epochs)\n    batch_modifier = None\n    run_after_early_stop = True\n    exp = Experiment(model, train_set, valid_set, test_set, iterator,\n                     loss_function, optimizer, model_constraint,\n                     monitors, stop_criterion,\n                     remember_best_column='valid_misclass',\n                     run_after_early_stop=run_after_early_stop,\n                     batch_modifier=batch_modifier,\n                     cuda=cuda)\n    exp.run()\n    return exp\n\n\n\nif __name__ == \"__main__\":\n    import config\n    print('Classifying: {}'.format(CLASSY))\n    #pdb.set_trace()\n    start_time = time.time()\n    logging.basicConfig(format='%(asctime)s %(levelname)s : %(message)s',\n                     level=logging.DEBUG, stream=sys.stdout)\n    exp = run_exp(\n        config.data_folders,\n        config.n_recordings,\n        config.sensor_types,\n        config.n_chans,\n        config.max_recording_mins,\n        config.sec_to_cut, config.duration_recording_mins,\n        config.test_recording_mins,\n        config.max_abs_val,\n        config.sampling_freq,\n        config.divisor,\n        config.test_on_eval,\n        config.n_folds, config.i_test_fold,\n        config.shuffle,\n        config.model_name,\n        config.n_start_chans, config.n_chan_factor,\n        config.input_time_length, config.final_conv_length,\n        config.model_constraint,\n        config.init_lr,\n        config.batch_size, config.max_epochs,config.cuda,)\n    end_time = time.time()\n    run_time = end_time - start_time\n\n    log.info(\"Experiment runtime: {:.2f} sec\".format(run_time))\n    \n    #pdb.set_trace()\n    if len(CLASSY) == 3:\n        CLASSY[2] = str(CLASSY[2])\n        CLASSY = '-'.join(CLASSY)\n    elif len(CLASSY) == 4:       \n        CLASSY[2] = str(CLASSY[2])\n        CLASSY[3] = str(CLASSY[3])\n        CLASSY = '-'.join(CLASSY)\n\n    th.save(exp.model.state_dict(),'sessionsData/'+CLASSY+'Model-sessions.pt')\n    #th.save(exp.model.state_dict(),CLASSY+'Model-shuffle.pt')\n\n    #savedModel = th.load('subNormModel.pt')\n    \n    # In case you want to recompute predictions for further analysis:\n    exp.model.eval()\n    for setname in ('train', 'valid', 'test'):\n        log.info(\"Compute predictions for {:s}...\".format(\n            setname))\n        dataset = exp.datasets[setname]\n        if config.cuda:\n            preds_per_batch = [var_to_np(exp.model(np_to_var(b[0]).cuda()))\n                      for b in exp.iterator.get_batches(dataset, shuffle=False)]\n        else:\n            preds_per_batch = [var_to_np(exp.model(np_to_var(b[0])))\n                      for b in exp.iterator.get_batches(dataset, shuffle=False)]\n        preds_per_trial = compute_preds_per_trial(\n            preds_per_batch, dataset,\n            input_time_length=exp.iterator.input_time_length,\n            n_stride=exp.iterator.n_preds_per_input)\n        mean_preds_per_trial = [np.mean(preds, axis=(0, 2)) for preds in\n                                    preds_per_trial]\n        mean_preds_per_trial = np.array(mean_preds_per_trial)\n\n", "meta": {"hexsha": "f17def3422ab5d3b4e0ee4883cea9d1218755616", "size": 21462, "ext": "py", "lang": "Python", "max_stars_repo_path": "auto_diagnosis.py", "max_stars_repo_name": "dbp-osel/PEASI", "max_stars_repo_head_hexsha": "11845fbfe235403bae80a4707a5a4460d87ab088", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-16T04:18:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-22T23:32:18.000Z", "max_issues_repo_path": "auto_diagnosis.py", "max_issues_repo_name": "dbp-osel/easyPEASI", "max_issues_repo_head_hexsha": "11845fbfe235403bae80a4707a5a4460d87ab088", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "auto_diagnosis.py", "max_forks_repo_name": "dbp-osel/easyPEASI", "max_forks_repo_head_hexsha": "11845fbfe235403bae80a4707a5a4460d87ab088", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5708884688, "max_line_length": 141, "alphanum_fraction": 0.6271549716, "include": true, "reason": "import numpy,from numpy", "num_tokens": 4885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.1947358986756152}}
{"text": "import os\nimport datetime as dt\nfrom collections import OrderedDict\nimport shutil\nfrom copy import copy\n\nimport matplotlib\nimport matplotlib.dates\nimport pylab as plt\nimport numpy as np\nfrom mpl_toolkits.basemap import Basemap\nfrom scipy import stats\nfrom matplotlib_venn import venn2, venn2_circles\n\n\nfrom ..processing.c20data import C20Data\nfrom plotting import lon_convert\nfrom ..results import StormtracksResultsManager\nfrom ..analysis import StormtracksAnalysis, ClassificationAnalysis\nfrom .. import analysis\nfrom ..ibtracsdata import IbtracsData\nimport plotting\nfrom ..load_settings import settings\nfrom ..analysis.classification import SCATTER_ATTRS\nfrom .. import classification\nfrom .. import processing.matching\n\n\ndef load_20th_century():\n    cla_analysis = ClassificationAnalysis()\n    cal_cd = cla_analysis.load_cal_classification_data()\n    val_cd = cla_analysis.load_val_classification_data()\n\n    sgdc = classification.SGDClassifier()\n    sgdc_best = sgdc.load('sgdc_best')\n    sgdc.train(cal_cd, **sgdc_best)\n\n    sgdc.predict(cal_cd)\n    cal_res = copy(sgdc.res)\n    cal_sens, cal_ppv = sgdc.sensitivity, sgdc.ppv\n\n    sgdc.predict(val_cd)\n    val_sens, val_ppv = sgdc.sensitivity, sgdc.ppv\n    val_res = copy(sgdc.res)\n\n    sens = (cal_sens + val_sens) / 2\n    ppv = (cal_ppv + val_ppv) / 2\n    adjustment_ratio_old = ppv / sens\n    print('OLD sens: {0}, ppv: {1}, ar: {2}'.format(sens, ppv, adjustment_ratio_old))\n\n    tp = cal_res['tp'] + val_res['tp']\n    fn = cal_res['fn'] + val_res['fn']\n    fp = cal_res['fp'] + val_res['fp']\n    sens = 1. * tp / (tp + fn)\n    ppv = 1. * tp / (tp + fp)\n    adjustment_ratio = ppv / sens\n    print('NEW sens: {0}, ppv: {1}, ar: {2}'.format(sens, ppv, adjustment_ratio))\n\n    ib_hurrs, ib_pdis, cla_hurrs, cla_pdis = cla_analysis.run_yearly_analysis(sgdc)\n    return ib_hurrs, ib_pdis, cla_hurrs, cla_pdis, adjustment_ratio\n\n\ndef load_thresh_metric_vs_vort_lo():\n    cla_analysis = ClassificationAnalysis()\n    cal_cd = cla_analysis.load_cal_classification_data()\n    cc = classification.CutoffClassifier()\n    cc_best = cc.load('cc_best')\n    print(cc_best)\n\n    metrics = []\n    for vort_lo in np.arange(0.00001, 0.0005, 0.00001):\n        cc_best['vort_lo'] = vort_lo\n        print(vort_lo)\n        cc.train(cal_cd, **cc_best)\n        cc.predict(cal_cd)\n        metrics.append((vort_lo, cc.sensitivity, cc.ppv, cc.fpr))\n\n    return np.array(metrics)\n\n\ndef load_classifier_metrics():\n    cla_analysis = ClassificationAnalysis()\n\n    cal_cd, val_cd, clas = cla_analysis.get_trained_classifiers()\n\n    metrics = OrderedDict()\n    for (cla, settings, fmt, name) in clas:\n        metrics[name] = {'fmt': fmt}\n\n        cla.predict(cal_cd)\n        metrics[name]['cal'] = (cla.sensitivity, cla.ppv, cla.fpr)\n\n        cla.predict(val_cd)\n        metrics[name]['val'] = (cla.sensitivity, cla.ppv, cla.fpr)\n\n    return metrics\n\n\ndef load_ibtracs_info():\n    yearly_hurr_distribution, hurr_per_year = analysis.analyse_ibtracs_data(False)\n    return yearly_hurr_distribution, hurr_per_year\n\n\ndef plot_20th_century(ib_hurrs, cla_hurrs, adjustment_ratio):\n    ar = adjustment_ratio\n    fig = plt.figure()\n    ax = plt.subplot(211)\n    plt.plot(range(1890, 2010), ib_hurrs, 'r-')\n    plt.plot(range(1890, 2010), cla_hurrs.mean(axis=1) * ar, 'b--')\n    plt.xlim((1890, 2010))\n    plt.ylim((0, 350))\n    plt.fill_between(range(1890, 2010),\n                     cla_hurrs.min(axis=1) * ar,\n                     cla_hurrs.max(axis=1) * ar,\n                     color=(0, 0, 1, 0.2))\n    plt.plot((1914, 1914), (0, 350), 'k--')\n    plt.plot((1944, 1944), (0, 350), 'k--')\n    plt.plot((1966, 1966), (0, 350), 'k--')\n\n    plt.annotate('Panama\\nCanal', xy=(1914, 290), xytext=(1915, 290), fontsize=10)\n    plt.annotate('Aircraft\\nRecon.', xy=(1944, 290), xytext=(1945, 290), fontsize=10)\n    plt.annotate('Satellite', xy=(1966, 290), xytext=(1967, 290), fontsize=10)\n    plt.setp(ax.get_xticklabels(), visible=False)\n\n    plt.ylabel('Hurricane-timesteps')\n    ax.yaxis.set_label_coords(-0.12, 0.5)\n\n    ax = plt.subplot(212)\n    plt.plot(range(1890, 2010), np.array(ib_hurrs) - cla_hurrs.mean(axis=1) * ar, 'b-')\n    plt.plot((1890, 2010), (0, 0), 'k-')\n\n    plt.xlim((1890, 2010))\n    ylim = (-150, 200)\n    plt.ylim(ylim)\n\n    plt.plot((1914, 1914), ylim, 'k--')\n    plt.plot((1944, 1944), ylim, 'k--')\n    plt.plot((1966, 1966), ylim, 'k--')\n\n    yoffset = 60\n    plt.annotate('Panama\\nCanal', xy=(1914, ylim[1] - yoffset),\n                 xytext=(1915, ylim[1] - yoffset), fontsize=10)\n    plt.annotate('Aircraft\\nRecon.', xy=(1944, ylim[1] - yoffset),\n                 xytext=(1945, ylim[1] - yoffset), fontsize=10)\n    plt.annotate('Satellite', xy=(1966, ylim[1] - yoffset),\n                 xytext=(1967, ylim[1] - yoffset), fontsize=10)\n\n    plt.ylabel('$\\Delta$ Hurricane-timesteps')\n    ax.yaxis.set_label_coords(-0.12, 0.5)\n    fig.set_size_inches(6.3, 6)\n    _save_figure('20th_century_hurricane_timesteps.png')\n\n\ndef plot_poster_20th_century(ib_hurrs, cla_hurrs, adjustment_ratio):\n    ar = adjustment_ratio\n    fig = plt.figure()\n    ax = plt.subplot(211)\n    plt.plot(range(1890, 2010), ib_hurrs, 'r-')\n    plt.plot(range(1890, 2010), cla_hurrs.mean(axis=1) * ar, 'b--')\n    plt.xlim((1890, 2010))\n    plt.ylim((0, 350))\n    plt.fill_between(range(1890, 2010),\n                     cla_hurrs.min(axis=1) * ar,\n                     cla_hurrs.max(axis=1) * ar,\n                     color=(0, 0, 1, 0.2))\n    plt.plot((1914, 1914), (0, 350), 'k--')\n    plt.plot((1944, 1944), (0, 350), 'k--')\n    plt.plot((1966, 1966), (0, 350), 'k--')\n\n    plt.annotate('Panama\\nCanal', xy=(1914, 290), xytext=(1915, 290), fontsize=10)\n    plt.annotate('Aircraft\\nRecon.', xy=(1944, 290), xytext=(1945, 290), fontsize=10)\n    plt.annotate('Satellite', xy=(1966, 290), xytext=(1967, 290), fontsize=10)\n    plt.setp(ax.get_xticklabels(), visible=False)\n\n    plt.ylabel('Hurricane-timesteps', fontsize=16)\n    ax.yaxis.set_label_coords(-0.12, 0.5)\n\n    ax = plt.subplot(212)\n    plt.plot(range(1890, 2010), np.array(ib_hurrs) - cla_hurrs.mean(axis=1) * ar, 'b-')\n    plt.plot((1890, 2010), (0, 0), 'k-')\n\n    plt.xlim((1890, 2010))\n    ylim = (-150, 200)\n    plt.ylim(ylim)\n\n    plt.plot((1914, 1914), ylim, 'k--')\n    plt.plot((1944, 1944), ylim, 'k--')\n    plt.plot((1966, 1966), ylim, 'k--')\n\n    yoffset = 60\n    plt.annotate('Panama\\nCanal', xy=(1914, ylim[1] - yoffset),\n                 xytext=(1915, ylim[1] - yoffset), fontsize=10)\n    plt.annotate('Aircraft\\nRecon.', xy=(1944, ylim[1] - yoffset),\n                 xytext=(1945, ylim[1] - yoffset), fontsize=10)\n    plt.annotate('Satellite', xy=(1966, ylim[1] - yoffset),\n                 xytext=(1967, ylim[1] - yoffset), fontsize=10)\n\n    plt.ylabel('$\\Delta$ Hurricane-timesteps', fontsize=16)\n    ax.yaxis.set_label_coords(-0.12, 0.5)\n    fig.set_size_inches(6.3, 6)\n    _save_figure('20th_century_hurricane_timesteps_poster.png')\n\n\ndef plot_poster_20th_century_trends(ib_hurrs, cla_hurrs, adjustment_ratio):\n    ar = adjustment_ratio\n    fig = plt.figure()\n    ax = plt.subplot(211)\n    plt.plot(range(1890, 2010), ib_hurrs, 'r-')\n    plt.xlim((1890, 2010))\n    plt.ylim((0, 350))\n    plt.plot((1914, 1914), (0, 350), 'k--')\n    plt.plot((1944, 1944), (0, 350), 'k--')\n    plt.plot((1966, 1966), (0, 350), 'k--')\n\n    plt.annotate('Panama\\nCanal', xy=(1914, 290), xytext=(1915, 290), fontsize=10)\n    plt.annotate('Aircraft\\nRecon.', xy=(1944, 290), xytext=(1945, 290), fontsize=10)\n    plt.annotate('Satellite', xy=(1966, 290), xytext=(1967, 290), fontsize=10)\n    plt.setp(ax.get_xticklabels(), visible=False)\n\n    plt.ylabel('Hurricane-timesteps', fontsize=16)\n    ax.yaxis.set_label_coords(-0.12, 0.5)\n\n    ax = plt.subplot(212)\n    plt.plot(range(1890, 2010), cla_hurrs.mean(axis=1) * ar, 'b-')\n    plt.xlim((1890, 2010))\n    ylim = (0, 350)\n    plt.ylim(ylim)\n\n    plt.plot((1914, 1914), ylim, 'k--')\n    plt.plot((1944, 1944), ylim, 'k--')\n    plt.plot((1966, 1966), ylim, 'k--')\n\n    yoffset = 60\n    plt.annotate('Panama\\nCanal', xy=(1914, ylim[1] - yoffset),\n                 xytext=(1915, ylim[1] - yoffset), fontsize=10)\n    plt.annotate('Aircraft\\nRecon.', xy=(1944, ylim[1] - yoffset),\n                 xytext=(1945, ylim[1] - yoffset), fontsize=10)\n    plt.annotate('Satellite', xy=(1966, ylim[1] - yoffset),\n                 xytext=(1967, ylim[1] - yoffset), fontsize=10)\n\n    ar = adjustment_ratio\n\n    for i, name, sl in ((1, 'pre-Panama Canal', slice(0, 24)),\n                        (2, 'Panama Canal', slice(24, 54)),\n                        (3, 'Aircraft', slice(54, 76)),\n                        (4, 'Satellite', slice(76, 120))):\n        corr_ib = stats.linregress(range(sl.stop - sl.start), ib_hurrs[sl] * ar)\n        corr_c2 = stats.linregress(range(sl.stop - sl.start), cla_hurrs.mean(axis=1)[sl] * ar)\n        plt.subplot(211)\n        if corr_ib[3] < 0.05:\n            fmt = 'r-'\n        else:\n            fmt = 'r--'\n\n        plt.plot((sl.start + 1890, sl.stop + 1890),\n                 (corr_ib[1], (sl.stop - sl.start) * corr_ib[0] + corr_ib[1]), fmt)\n        plt.subplot(212)\n        if corr_c2[3] < 0.05:\n            fmt = 'b-'\n        else:\n            fmt = 'b--'\n        plt.plot((sl.start + 1890, sl.stop + 1890),\n                 (corr_c2[1], (sl.stop - sl.start) * corr_c2[0] + corr_c2[1]), fmt)\n\n        latex = False\n        if not latex:\n            print(name)\n            print('IB: gradient: {0}, inter: {1}, r2: {2}, p: {3}'.format(corr_ib[0],\n                                                                          corr_ib[1],\n                                                                          corr_ib[2] ** 2,\n                                                                          corr_ib[3]))\n            print('C2: gradient: {0}, inter: {1}, r2: {2}, p: {3}'.format(corr_c2[0],\n                                                                          corr_c2[1],\n                                                                          corr_c2[2] ** 2,\n                                                                          corr_c2[3]))\n        else:\n            print('{0} & {1:.2f} & {2:.3f} & {3:.2f} & {4:.3f} \\\\\\\\'.format(name,\n                                                                            corr_ib[0],\n                                                                            corr_ib[3],\n                                                                            corr_c2[0],\n                                                                            corr_c2[3]))\n    plt.ylabel('Hurricane-timesteps', fontsize=16)\n    ax.yaxis.set_label_coords(-0.12, 0.5)\n\n    fig.set_size_inches(6.3, 6)\n    _save_figure('20th_century_trends.png')\n\n\ndef print_20th_century_trends(ib_hurrs, cla_hurrs, adjustment_ratio, latex=True):\n    ar = adjustment_ratio\n    for i, name, sl in ((1, 'pre-Panama Canal', slice(0, 24)),\n                        (2, 'Panama Canal', slice(24, 54)),\n                        (3, 'Aircraft', slice(54, 76)),\n                        (4, 'Satellite', slice(76, 120))):\n        corr_ib = stats.linregress(range(sl.stop - sl.start), ib_hurrs[sl] * ar)\n        corr_c2 = stats.linregress(range(sl.stop - sl.start), cla_hurrs.mean(axis=1)[sl] * ar)\n        if not latex:\n            print(name)\n            print('IB: gradient: {0}, inter: {1}, r2: {2}, p: {3}'.format(corr_ib[0],\n                                                                          corr_ib[1],\n                                                                          corr_ib[2] ** 2,\n                                                                          corr_ib[3]))\n            print('C2: gradient: {0}, inter: {1}, r2: {2}, p: {3}'.format(corr_c2[0],\n                                                                          corr_c2[1],\n                                                                          corr_c2[2] ** 2,\n                                                                          corr_c2[3]))\n        else:\n            print('{0} & {1:.2f} & {2:.3f} & {3:.2f} & {4:.3f} \\\\\\\\'.format(name,\n                                                                            corr_ib[0],\n                                                                            corr_ib[3],\n                                                                            corr_c2[0],\n                                                                            corr_c2[3]))\n\n\ndef plot_20th_century_corr(ib_hurrs, cla_hurrs, adjustment_ratio):\n    ar = adjustment_ratio\n    fig = plt.figure()\n    plt.subplot(121)\n    plt.plot(ib_hurrs, cla_hurrs.mean(axis=1) * ar, 'k+')\n    corr = stats.linregress(ib_hurrs, cla_hurrs.mean(axis=1) * ar)\n    print(corr)\n    label = 'grad.: {0:.2f}\\nintercept: {1:.2f}\\nr$^2$: {2:.2f}'.format(corr[0], corr[1],\n                                                                        corr[2] ** 2)\n    plt.plot((0, 300), (corr[0] * 0 + corr[1], corr[0] * 300 + corr[1]), 'k--', label=label)\n    plt.xlim((0, 300))\n    plt.ylim((0, 300))\n    plt.legend(bbox_to_anchor=(0.75, 1.1), numpoints=1, prop={'size': 10})\n\n    plt.xlabel('IBTrACS Hurricane-timesteps')\n    plt.ylabel('Estimated Hurricane-timesteps')\n    # fig.set_size_inches(4, 4)\n\n    ax = plt.subplot(122)\n    for label, sl, c, fmt in (('pre-1944', slice(0, 54), 'r', '+'),\n                              ('post-1944', slice(54, 120), 'b', 'x')):\n        plt.plot(ib_hurrs[sl], cla_hurrs.mean(axis=1)[sl] * ar, '{0}{1}'.format(c, fmt),\n                 label=label)\n        corr = stats.linregress(ib_hurrs[sl], cla_hurrs.mean(axis=1)[sl] * ar)\n        print(corr)\n        # label = 'grad.: {0:.2f}\\nintercept: {1:.2f}\\nr$^2$: {2:.2f}'.format(corr[0],\n        # corr[1], corr[2] ** 2)\n        plt.plot((0, 300), (corr[0] * 0 + corr[1], corr[0] * 300 + corr[1]), '{0}--'.format(c))\n\n    plt.setp(ax.get_yticklabels(), visible=False)\n    plt.xlim((0, 300))\n    plt.ylim((0, 300))\n    plt.legend(bbox_to_anchor=(0.60, 1.1), numpoints=1, prop={'size': 10})\n\n    plt.xlabel('IBTrACS Hurricane-timesteps')\n    # plt.ylabel('Estimated Hurricane timesteps')\n    fig.set_size_inches(6.3, 3)\n    _save_figure('20th_century_corr.png')\n\n    fig = plt.figure()\n\n    for i, label, sl, c, fmt, bbox in ((1, 'pre-Panama', slice(0, 24), 'r', '+', (0.97, 0.35)),\n                                       (2, 'Panama', slice(24, 54), 'b', 'x', (0.97, 0.35)),\n                                       (3, 'aircraft', slice(54, 76), 'g', '^', (0.65, 1.1)),\n                                       (4, 'satellite', slice(76, 120), 'c', 'o', (0.71, 1.1))):\n        ax = plt.subplot(2, 2, i)\n        plt.plot(ib_hurrs[sl], cla_hurrs.mean(axis=1)[sl] * ar, '{0}{1}'.format(c, fmt),\n                 label=label)\n        corr = stats.linregress(ib_hurrs[sl], cla_hurrs.mean(axis=1)[sl] * ar)\n        print(label)\n        print(corr[2] ** 2)\n        label = 'grad.: {0:.2f}\\ninter.: {1:.2f}'.format(corr[0], corr[1])\n        plt.plot((0, 300), (corr[0] * 0 + corr[1], corr[0] * 300 + corr[1]), '{0}--'.format(c),\n                 label=label)\n\n        if i in (1, 2):\n            plt.setp(ax.get_xticklabels(), visible=False)\n        else:\n            plt.xlabel('IBTrACS Hurricane-timesteps')\n\n        if i in (1, 3):\n            plt.ylabel('Estimated Hurricane-timesteps')\n        else:\n            plt.setp(ax.get_yticklabels(), visible=False)\n\n        plt.xlim((0, 300))\n        plt.ylim((0, 300))\n\n        plt.legend(bbox_to_anchor=bbox, numpoints=1, prop={'size': 10})\n\n    # plt.xlabel('IBTrACS Hurricane timesteps')\n    # plt.ylabel('Estimated Hurricane timesteps')\n    fig.set_size_inches(6.3, 6.3)\n    _save_figure('20th_century_corr_split.png')\n\n\ndef plot_galveston():\n    c20data = C20Data(1900, fields=['prmsl', 'u', 'v'])\n    c20data.set_date(dt.datetime(1900, 9, 7, 18, 0))\n    loc = {'llcrnrlat': 15, 'urcrnrlat': 35, 'llcrnrlon': -100, 'urcrnrlon': -70}\n\n    fig = plt.figure()\n    plt.subplot(121)\n    m = _raster_on_earth(c20data.lons, c20data.lats, c20data.vort * 10000, loc=loc, colorbar=None)\n    m.colorbar(location='bottom', pad='7%', ticks=(-1, 0, 1, 2))\n    plt.xlabel('Vorticity ($10^{-4}$ s$^{-1}$)', labelpad=30)\n    plt.subplot(122)\n    m = _raster_on_earth(c20data.lons, c20data.lats, c20data.prmsl / 100, loc=loc, colorbar=None)\n    m.colorbar(location='bottom', pad='7%', ticks=(970, 1000, 1030))\n    plt.xlabel('Pressure (hPa)', labelpad=30)\n\n    fig.set_size_inches(6.3, 3)\n    _save_figure('galveston_1900-9-7_18-00_em0.png')\n\n\ndef plot_venn():\n    fig = plt.figure()\n    plt.clf()\n    fig.set_size_inches(6, 5)\n\n    v = venn2(subsets=(5, 6, 7), set_labels=('', ''))\n    v.get_label_by_id('10').set_text('False\\nPositives')\n    v.get_label_by_id('01').set_text('False\\nNegatives')\n    v.get_label_by_id('11').set_text('True\\nPositives')\n    c = venn2_circles(subsets=(5, 6, 7), linestyle='dashed')\n    c[0].set_lw(1.0)\n    c[0].set_ls('dotted')\n\n    plt.annotate('True Negatives', xy=np.array([0, 0]),\n                 xytext=(0, -140),\n                 ha='center', textcoords='offset points')\n    _save_figure('tf_np_venn.png')\n\n\ndef plot_thresh_metric_vs_vort_lo(metrics):\n    fig = plt.figure()\n    ax = plt.subplot(211)\n    plt.plot(metrics[:40, 0] * 10000, metrics[:40, 1] + metrics[:40, 2], 'k-', label='Sum')\n    plt.legend(loc='best', prop={'size': 10})\n    plt.setp(ax.get_xticklabels(), visible=False)\n    plt.ylim((1, 1.4))\n    ax.set_yticks((1, 1.1, 1.2, 1.3, 1.4))\n\n    plt.subplot(212)\n    plt.plot(metrics[:40, 0] * 10000, metrics[:40, 1], 'b--', label='sensitivity')\n    plt.plot(metrics[:40, 0] * 10000, metrics[:40, 2], 'g--', label='PPV')\n    plt.legend(loc='best', prop={'size': 10})\n    plt.xlabel('Vorticity threshold ($10^{-4}$ s$^{-1}$)')\n\n    fig.set_size_inches(6.3, 4)\n\n    _save_figure('threshold_sens_ppv_vort.png')\n\n\ndef plot_classifer_metrics(metrics):\n    plt.figure()\n\n    for name in metrics:\n        metric = metrics[name]\n        fmt = metric['fmt']\n        plt.subplot(2, 2, 1)\n        plt.plot(metric['cal'][1], metric['cal'][0], fmt, label=name)\n\n        plt.subplot(2, 2, 2)\n        plt.plot(metric['cal'][2], metric['cal'][0], fmt, label=name)\n\n        plt.subplot(2, 2, 3)\n        plt.plot(metric['val'][1], metric['cal'][0], fmt, label=name)\n\n        plt.subplot(2, 2, 4)\n        plt.plot(metric['val'][2], metric['cal'][0], fmt, label=name)\n\n    plt.subplot(2, 2, 1)\n    # plt.xlabel('PPV')\n    plt.ylabel('Calibration\\nsensitivity')\n    plt.xlim((0, 1))\n    plt.ylim((0, 1))\n\n    plt.subplot(2, 2, 2)\n    # plt.xlabel('FPR')\n    # plt.ylabel('sensitivity')\n    plt.xlim((0, 0.1))\n    plt.ylim((0, 1))\n    plt.legend(bbox_to_anchor=(1.1, 1.1), numpoints=1)\n\n    plt.subplot(2, 2, 3)\n    plt.xlabel('PPV')\n    plt.ylabel('Validation\\nsensitivity')\n    plt.xlim((0, 1))\n    plt.ylim((0, 1))\n\n    plt.subplot(2, 2, 4)\n    plt.xlabel('FPR')\n    # plt.ylabel('sensitivity')\n    plt.xlim((0, 0.1))\n    plt.ylim((0, 1))\n\n    _save_figure('ppv_and_fpr_vs_sens.png')\n    return metrics\n\n\ndef plot_wld(stormtracks_analysis=None, years=None):\n    if not stormtracks_analysis:\n        stormtracks_analysis = StormtracksAnalysis(2000)\n\n    if not years:\n        years = range(2000, 2010)\n\n    wlds = {}\n    wlds['draws'] = []\n\n    for year in years:\n        print(year)\n        stormtracks_analysis.set_year(year)\n        k0, w0, k1, w1, d = stormtracks_analysis.run_wld_analysis(active_configs={'scale': 3})\n\n        if k0 not in wlds:\n            wlds[k0] = []\n        wlds[k0].append(w0)\n\n        if k1 not in wlds:\n            wlds[k1] = []\n        wlds[k1].append(w1)\n\n        wlds['draws'].append(d)\n\n    print(wlds)\n\n    plt.figure()\n    plt.title('wld')\n    for k in wlds:\n        plt.plot(years, wlds[k], label=k)\n    plt.legend(loc='best')\n\n\ndef plot_tracking_stats(stormtracks_analysis=None, years=None, sort_col='cumoveroverlap'):\n    if not stormtracks_analysis:\n        stormtracks_analysis = StormtracksAnalysis(2000)\n\n    k995 = []\n    for scale in (1, 2, 3):\n        config = {'pressure_level': 995, 'scale': scale, 'tracker': 'nearest_neighbour'}\n        k995.append(stormtracks_analysis.good_matches_key(config))\n\n    keys = ('pl995', 'pl850', 'scale3')\n\n    config_keys = {}\n    for key in keys:\n        config_keys[key] = []\n\n    for scale in (1, 2, 3):\n        config = {'pressure_level': 995, 'scale': scale, 'tracker': 'nearest_neighbour'}\n        config_keys['pl995'].append(stormtracks_analysis.good_matches_key(config))\n\n        config = {'pressure_level': 850, 'scale': scale, 'tracker': 'nearest_neighbour'}\n        config_keys['pl850'].append(stormtracks_analysis.good_matches_key(config))\n\n    for pl in (995, 850):\n        config = {'pressure_level': pl, 'scale': 3, 'tracker': 'nearest_neighbour'}\n        config_keys['scale3'].append(stormtracks_analysis.good_matches_key(config))\n\n    all_wins = {}\n    for key in keys:\n        all_wins[key] = []\n\n    if not years:\n        years = range(2000, 2010)\n\n    for year in years:\n        print(year)\n        stormtracks_analysis.set_year(year)\n\n        res = {}\n        res['pl995'] =\\\n            stormtracks_analysis.run_position_analysis(sort_on=sort_col,\n                                                       active_configs={'pressure_level': 995})\n        res['pl850'] =\\\n            stormtracks_analysis.run_position_analysis(sort_on=sort_col,\n                                                       active_configs={'pressure_level': 850})\n        res['scale3'] =\\\n            stormtracks_analysis.run_position_analysis(sort_on=sort_col,\n                                                       active_configs={'scale': 3})\n\n        for key in keys:\n            print(key)\n            wins = []\n            for config_key in config_keys[key]:\n                print('  {0}'.format(config_key))\n                try:\n                    wins.append(res[key][config_key][0])\n                except KeyError:\n                    wins.append(0)\n\n            all_wins[key].append(wins)\n\n    for key in keys:\n        all_wins[key] = np.array(all_wins[key])\n\n    _plot_all_wins(years, all_wins)\n    return years, all_wins\n\n\ndef _plot_all_wins(years, all_wins):\n    fmt = matplotlib.ticker.ScalarFormatter(useOffset=False)\n    fig = plt.figure()\n    fmt.set_scientific(False)\n    ax = plt.subplot(311)\n    plt.title('Near Surface Pressure Level (NSPL)')\n    plt.plot(years, all_wins['pl995'][:, 0], 'r-', label='Scale 1')  # scale 1\n    plt.plot(years, all_wins['pl995'][:, 1], 'g-', label='Scale 2')  # scale 2\n    plt.plot(years, all_wins['pl995'][:, 2], 'b-', label='Scale 3')  # scale 3\n    plt.ylim(0, 60)\n    plt.setp(ax.get_xticklabels(), visible=False)\n    plt.legend(bbox_to_anchor=(1.1, 1.14), numpoints=1, prop={'size': 10})\n    ax.xaxis.set_major_formatter(fmt)\n\n    ax = plt.subplot(312)\n    plt.title('850 hPa Pressure Level')\n    plt.plot(years, all_wins['pl850'][:, 0], 'r--', label='Scale 1')  # scale 1\n    plt.plot(years, all_wins['pl850'][:, 1], 'g--', label='Scale 2')  # scale 2\n    plt.plot(years, all_wins['pl850'][:, 2], 'b--', label='Scale 3')  # scale 3\n    plt.ylim(0, 60)\n    plt.setp(ax.get_xticklabels(), visible=False)\n    plt.legend(bbox_to_anchor=(1.1, 1.14), numpoints=1, prop={'size': 10})\n    ax.xaxis.set_major_formatter(fmt)\n\n    ax = plt.subplot(313)\n    plt.title('Scale 3')\n    plt.plot(years, all_wins['scale3'][:, 0], 'b-', label='NSPL')  # pl 995\n    plt.plot(years, all_wins['scale3'][:, 1], 'b--', label='850 hPa')  # pl 850\n    plt.ylim(0, 60)\n    plt.legend(bbox_to_anchor=(1.1, 1.14), numpoints=1, prop={'size': 10})\n    ax.xaxis.set_major_formatter(fmt)\n\n    fig.set_size_inches(6.3, 6)\n    _save_figure('tracking_wins_losses.png')\n\n\ndef plot_poster_katrina():\n    loc = {'llcrnrlat': 15, 'urcrnrlat': 35, 'llcrnrlon': -100, 'urcrnrlon': -70}\n    fig = plt.figure(1)\n    plt.clf()\n    c20data = C20Data(2005, fields=['u', 'v'])\n    c20data.set_date(dt.datetime(2005, 8, 27, 18))\n\n    m = _raster_on_earth(c20data.lons, c20data.lats, c20data.vort * 10000, loc=loc, colorbar=False)\n    fig.set_size_inches(6.4, 3)\n    _save_figure('katrina.png')\n\n\ndef plot_poster_2005_best_tracks():\n    loc = {'llcrnrlat': 10, 'urcrnrlat': 60, 'llcrnrlon': -100, 'urcrnrlon': -20}\n    fig = plt.figure(2)\n    plt.clf()\n    c20data = C20Data(2005, fields=['u', 'v'])\n    ibdata = IbtracsData()\n    bts = ibdata.load_ibtracks_year(2005)\n    m = _raster_on_earth(c20data.lons, c20data.lats, None, loc=loc, colorbar=False, labels=False)\n    fig.set_size_inches(6.4, 3)\n\n    for bt in bts:\n        plotting.plot_track(bt)\n    _save_figure('2005_best_tracks.png')\n\n\ndef plot_data_processing_figures():\n    _plot_katrina()\n    _plot_katrina_maxs_mins()\n\n\ndef _plot_katrina():\n    c20data = C20Data(2005, fields=['u', 'v'])\n    c20data.set_date(dt.datetime(2005, 8, 27, 18))\n\n    fig = plt.figure(1)\n    plt.clf()\n\n    loc = {'llcrnrlat': 15, 'urcrnrlat': 35, 'llcrnrlon': -100, 'urcrnrlon': -70}\n    ax = plt.subplot(131)\n    # plt.title('Wind')\n\n    m = _vec_plot_on_earth(c20data.lons, c20data.lats, -c20data.u, c20data.v, loc=loc)\n    m.colorbar(location='bottom', pad='7%', ticks=(0, 8, 16, 24))\n    plt.xlabel('Wind speed (ms$^{-1}$)')\n    ax.xaxis.set_label_coords(0.5, -0.33)\n\n    ax = plt.subplot(132)\n    # plt.title('Vorticity')\n    m = _raster_on_earth(c20data.lons, c20data.lats, c20data.vort * 10000, loc=loc, colorbar=False)\n    m.colorbar(location='bottom', pad='7%', ticks=(-1, 0, 1, 2))\n    plt.xlabel('Vorticity ($10^{-4}$ s$^{-1}$)')\n    ax.xaxis.set_label_coords(0.5, -0.33)\n\n    c20data = C20Data(2005, fields=['u', 'v'], upscaling=True, scale_factor=3)\n    c20data.set_date(dt.datetime(2005, 8, 27, 18))\n    ax = plt.subplot(133)\n    # plt.title('Downscaled\\nVorticity')\n    m = _raster_on_earth(c20data.up_lons, c20data.up_lats, c20data.up_vort * 10000,\n                         loc=loc, colorbar=False)\n    m.colorbar(location='bottom', pad='7%', ticks=(-1, 0, 1, 2))\n    plt.xlabel('Vorticity ($10^{-4}$ s$^{-1}$)')\n    ax.xaxis.set_label_coords(0.5, -0.33)\n\n    fig.set_size_inches(7, 4)\n    _save_figure('katrina_data_proc.png')\n\n\ndef _plot_katrina_maxs_mins():\n    c20data = C20Data(2005, fields=['prmsl', 'u', 'v'])\n    c20data.set_date(dt.datetime(2005, 8, 27, 18))\n    loc = {'llcrnrlat': 0, 'urcrnrlat': 45, 'llcrnrlon': -120, 'urcrnrlon': -60}\n\n    fig = plt.figure(2)\n    plt.clf()\n\n    plt.subplot(221)\n    _raster_on_earth(c20data.lons, c20data.lats, c20data.vort, loc=loc, colorbar=False)\n    plt.ylabel('Vorticity')\n\n    plt.subplot(222)\n    _raster_on_earth(c20data.lons, c20data.lats, None, loc=loc)\n    points = c20data.vmaxs\n    for p_val, p_loc in points:\n        _plot_point_on_earth(p_loc[0] + 1, p_loc[1] + 1, 'ro')\n    points = c20data.vmins\n    for p_val, p_loc in points:\n        _plot_point_on_earth(p_loc[0] + 1, p_loc[1] + 1, 'kx')\n\n    plt.subplot(223)\n    _raster_on_earth(c20data.lons, c20data.lats, c20data.prmsl,\n                     vmin=99000, vmax=103000, loc=loc, colorbar=False)\n    plt.ylabel('Pressure')\n\n    plt.subplot(224)\n    _raster_on_earth(c20data.lons, c20data.lats, None, loc=loc)\n    points = c20data.pmaxs\n    for p_val, p_loc in points:\n        _plot_point_on_earth(p_loc[0] + 1, p_loc[1] + 1, 'ro')\n    points = c20data.pmins\n    for p_val, p_loc in points:\n        _plot_point_on_earth(p_loc[0] + 1, p_loc[1] + 1, 'kx')\n\n    _save_figure('katrina_max_mins.png')\n\n\ndef plot_matching_figures():\n    _plot_six_configs_figure()\n    _plot_individual_katrina_figure()\n\n\ndef plot_yearly_hurr_dist(yearly_hurr_distribution):\n    start_doy = dt.datetime(2001, 6, 1).timetuple().tm_yday\n    end_doy = dt.datetime(2001, 12, 1).timetuple().tm_yday\n\n    fig = plt.figure()\n    # plt.title('Hurricane Distribution over the Year')\n    plt.plot(yearly_hurr_distribution.keys(), yearly_hurr_distribution.values())\n    plt.plot((start_doy, start_doy), (0, 250), 'k--')\n    plt.plot((end_doy, end_doy), (0, 250), 'k--')\n    plt.xlabel('Day of Year')\n    plt.ylabel('Hurricane-timesteps')\n    fig.set_size_inches(6.3, 3)\n    _save_figure('yearly_hurr_dist.png')\n\n\ndef plot_hurr_per_year(hurr_per_year):\n    fig = plt.figure()\n    # plt.title('Hurricanes per Year')\n    plt.plot(hurr_per_year.keys(), hurr_per_year.values())\n    plt.xlim((1890, 2010))\n    plt.ylim((0, 300))\n\n    plt.plot((1914, 1914), (0, 300), 'k--')\n    plt.plot((1944, 1944), (0, 300), 'k--')\n    plt.plot((1966, 1966), (0, 300), 'k--')\n\n    plt.annotate('Panama\\nCanal', xy=(1914, 250), xytext=(1915, 250), fontsize=10)\n    plt.annotate('Aircraft\\nRecon.', xy=(1944, 250), xytext=(1945, 250), fontsize=10)\n    plt.annotate('Satellite', xy=(1966, 250), xytext=(1967, 250), fontsize=10)\n\n    plt.xlabel('Year')\n    plt.ylabel('Hurricane-timesteps')\n    fig.set_size_inches(6.3, 3)\n    _save_figure('hurr_per_year.png')\n\n\ndef plot_cdp_with_hurr_info(cla_analysis=None):\n    if not cla_analysis:\n        cla_analysis = ClassificationAnalysis()\n\n    val_cd = cla_analysis.load_val_classification_data()\n    _plot_2005_cdp(val_cd)\n    return val_cd\n\n\ndef plot_cal_cd(cal_cd):\n    m = cal_cd.are_hurr_actual\n\n    i1 = SCATTER_ATTRS['vort']['index']\n    i2 = SCATTER_ATTRS['pmin']['index']\n\n    fig = plt.figure()\n\n    ax = plt.subplot(131)\n    plt.plot(cal_cd.data[:, i1][m] * 10000, cal_cd.data[:, i2][m] / 100.,\n             'ro', zorder=0, label='hurricane')\n    plt.plot(cal_cd.data[:, i1][~m] * 10000, cal_cd.data[:, i2][~m] / 100.,\n             'bx', zorder=1, label='not hurricane')\n    plt.xlim((0, 4.5))\n    plt.ylim((920, 1040))\n    ax.set_xticks((0, 1.5, 3, 4.5))\n\n    plt.ylabel('Pressure (hPa)')\n    plt.xlabel('Vorticity ($10^{-4}$ s$^{-1}$)')\n\n    ax = plt.subplot(132)\n    plt.plot(cal_cd.data[:, i1][m] * 10000, cal_cd.data[:, i2][m] / 100.,\n             'ro', zorder=0, label='hurricane')\n    plt.xlim((0, 4.5))\n    plt.ylim((920, 1040))\n    ax.set_xticks((0, 1.5, 3, 4.5))\n\n    plt.xlabel('Vorticity ($10^{-4}$ s$^{-1}$)')\n    plt.setp(ax.get_yticklabels(), visible=False)\n\n    ax = plt.subplot(133)\n    plt.plot(cal_cd.data[:, i1][~m] * 10000, cal_cd.data[:, i2][~m] / 100.,\n             'bx', zorder=1, label='not hurricane')\n    plt.plot(-10, -10, 'ro', zorder=1, label='hurricane')  # dummy point.\n    plt.xlim((0, 4.5))\n    plt.ylim((920, 1040))\n    ax.set_xticks((0, 1.5, 3, 4.5))\n\n    plt.xlabel('Vorticity ($10^{-4}$ s$^{-1}$)')\n    plt.legend(bbox_to_anchor=(1.3, 1.16), numpoints=1, prop={'size': 10})\n    plt.setp(ax.get_yticklabels(), visible=False)\n\n    fig.set_size_inches(6.3, 2.3)\n\n    _save_figure('cal_cdp_with_hurrs.png')\n\n\ndef _plot_2005_cdp(val_cd):\n    m = val_cd.are_hurr_actual\n    m2005 = val_cd.data[:, -2] == 2005  # -2 is year col.\n    data = val_cd.data[m2005]\n    m = m[m2005]\n\n    i1 = SCATTER_ATTRS['vort']['index']\n    i2 = SCATTER_ATTRS['pmin']['index']\n\n    fig = plt.figure()\n\n    labelx = -0.35\n    ax = plt.subplot(231)\n    plt.plot(data[:, i1][m] * 10000, data[:, i2][m] / 100., 'ro', zorder=0, label='hurricane')\n    plt.plot(data[:, i1][~m] * 10000, data[:, i2][~m] / 100., 'bx', zorder=1, label='not hurricane')\n    plt.xlim((0, 3))\n    plt.ylim((940, 1040))\n    ax.set_xticks((0, 1, 2, 3))\n    ax.yaxis.set_label_coords(labelx, 0.5)\n\n    plt.ylabel('Pressure (hPa)')\n    # plt.xlabel('Vorticity ($10^{-4}$ s$^{-1}$)')\n\n    ax = plt.subplot(232)\n    plt.plot(data[:, i1][m] * 10000, data[:, i2][m] / 100., 'ro', zorder=0, label='hurricane')\n    plt.xlim((0, 3))\n    plt.ylim((940, 1040))\n    ax.set_xticks((0, 1, 2, 3))\n\n    # plt.xlabel('Vorticity ($10^{-4}$ s$^{-1}$)')\n    plt.setp(ax.get_yticklabels(), visible=False)\n\n    ax = plt.subplot(233)\n    plt.plot(data[:, i1][~m] * 10000, data[:, i2][~m] / 100., 'bx', zorder=1, label='not hurricane')\n    plt.plot(-10, -10, 'ro', zorder=1, label='hurricane')  # dummy point.\n    plt.xlim((0, 3))\n    plt.ylim((940, 1040))\n    ax.set_xticks((0, 1, 2, 3))\n\n    # plt.xlabel('Vorticity ($10^{-4}$ s$^{-1}$)')\n    plt.legend(bbox_to_anchor=(1.3, 1.16), numpoints=1, prop={'size': 10})\n    plt.setp(ax.get_yticklabels(), visible=False)\n\n    i2 = SCATTER_ATTRS['t850']['index']\n\n    ax = plt.subplot(234)\n    plt.plot(data[:, i1][m] * 10000, data[:, i2][m], 'ro', zorder=0, label='hurricane')\n    plt.plot(data[:, i1][~m] * 10000, data[:, i2][~m], 'bx', zorder=1, label='not hurricane')\n    plt.xlim((0, 3))\n    plt.ylim((250, 310))\n    ax.set_xticks((0, 1, 2, 3))\n    ax.yaxis.set_label_coords(labelx, 0.5)\n\n    plt.ylabel('Temp. at 850 hPa (K)')\n    # plt.xlabel('Vorticity ($10^{-4}$ s$^{-1}$)')\n\n    ax = plt.subplot(235)\n    plt.plot(data[:, i1][m] * 10000, data[:, i2][m], 'ro', zorder=0, label='hurricane')\n    plt.xlim((0, 3))\n    plt.ylim((250, 310))\n    ax.set_xticks((0, 1, 2, 3))\n\n    plt.xlabel('Vorticity ($10^{-4}$ s$^{-1}$)')\n    plt.setp(ax.get_yticklabels(), visible=False)\n\n    ax = plt.subplot(236)\n    plt.plot(data[:, i1][~m] * 10000, data[:, i2][~m], 'bx', zorder=1, label='not hurricane')\n    plt.plot(-10, -10, 'ro', zorder=1, label='hurricane')  # dummy point.\n    plt.xlim((0, 3))\n    plt.ylim((250, 310))\n    ax.set_xticks((0, 1, 2, 3))\n\n    # plt.xlabel('Vorticity ($10^{-4}$ s$^{-1}$)')\n    # plt.legend(bbox_to_anchor=(1.3, 1.16), numpoints=1, prop={'size': 10})\n    plt.setp(ax.get_yticklabels(), visible=False)\n\n    fig.set_size_inches(6.3, 4.6)\n\n    _save_figure('cdp_2005_with_hurrs.png')\n\n\ndef _plot_individual_katrina_figure(em=7):\n    c20data = C20Data(2005, fields=['prmsl', 'u', 'v'])\n    srm = StormtracksResultsManager('pyro_tracking_analysis')\n    ta = StormtracksAnalysis(2005)\n    ibdata = IbtracsData()\n    w, k = ibdata.load_wilma_katrina()\n    bt = k\n    loc = {'llcrnrlat': 10, 'urcrnrlat': 45, 'llcrnrlon': -100, 'urcrnrlon': -65}\n\n    config = {'pressure_level': 850, 'scale': 1, 'tracker': 'nearest_neighbour'}\n\n    fig = plt.figure()\n    plt.clf()\n\n    print(config)\n    all_matches = []\n\n    key = ta.good_matches_key(config)\n    good_matches = srm.get_result(2005, em, key)\n\n    for good_match in good_matches:\n        if good_match.best_track.name == bt.name:\n            break\n\n    _raster_on_earth(c20data.lons, c20data.lats, None, loc=loc)\n    plotting.plot_match_with_date(good_match, None)\n    _save_figure('katrina_individual_match_em7')\n\n\ndef _plot_six_configs_figure():\n    c20data = C20Data(2005, fields=['prmsl', 'u', 'v'])\n    srm = StormtracksResultsManager('pyro_tracking_analysis')\n    ta = StormtracksAnalysis(2005)\n    ibdata = IbtracsData()\n    w, k = ibdata.load_wilma_katrina()\n    bt = k\n    loc = {'llcrnrlat': 10, 'urcrnrlat': 45, 'llcrnrlon': -100, 'urcrnrlon': -65}\n    fig3 = plt.figure(3)\n    plt.clf()\n\n    for j, config in enumerate(ta.analysis_config_options):\n        plt.subplot(3, 2, j + 1)\n        print(config)\n        if config['pressure_level'] == 995:\n            title = 'NSLP, Scale: {scale}'.format(**config)\n        else:\n            title = '850 hPa, Scale: {scale}'.format(**config)\n        plt.title(title, fontsize=10)\n        all_matches = []\n        _raster_on_earth(c20data.lons, c20data.lats, None, loc=loc, labels=False)\n        plotting.plot_track(bt, zorder=2)\n\n        for i in range(56):\n            key = ta.good_matches_key(config)\n            good_matches = srm.get_result(2005, i, key)\n            matches = []\n            for good_match in good_matches:\n                if good_match.best_track.name == bt.name:\n                    matches.append(good_match)\n\n            if matches:\n                all_matches.append(matches)\n                for match in matches:\n                    vt = match.vort_track\n                    mask = (vt.dates >= bt.dates[0]) & (vt.dates <= bt.dates[-1])\n                    plotting.plot_path_on_earth(vt.lons[mask], vt.lats[mask], 'b--')\n\n                    # plotting.plot_track(vt, 'b--')\n                    # return vt, bt\n            else:\n                print('Could not find wilma in {0}-{1}'.format(i, key))\n\n    fig3.set_size_inches(5.4, 7.8)\n\n    _save_figure('katrina_six_tracking_configs')\n\n\ndef plot_katrina_correlation(ca=None, em=7):\n    fig = plt.figure()\n    ibdata = IbtracsData()\n    w, k = ibdata.load_wilma_katrina()\n    if not ca:\n        ca = ClassificationAnalysis()\n    cs, ms, ums = ca.run_individual_cla_analysis(2005, em)\n\n    pressures = []\n    winds = []\n    dates = []\n\n    for cm in ms:\n        if cm.best_track.name == k.name:\n            for date, bt_pres, bt_wind in zip(cm.best_track.dates,\n                                              cm.best_track.pressures,\n                                              cm.best_track.winds):\n                if date in cm.cyclone.pmins and cm.cyclone.pmins[date]:\n                    dates.append(date)\n                    pressures.append((bt_pres, cm.cyclone.pmins[date] / 100.))\n                    winds.append((bt_wind, cm.cyclone.max_windspeeds[date]))\n\n    pressures, winds = np.array(pressures), np.array(winds)\n\n    labelx = -0.1\n    ax = plt.subplot(211)\n    plt.plot_date(dates, pressures[:, 0], 'b-', label='best track')\n    plt.plot_date(dates, pressures[:, 1], 'b--', label='derived track')\n    plt.ylabel('pressure (hPa)')\n    plt.legend(bbox_to_anchor=(1.07, 1.16), numpoints=1, prop={'size': 10})\n    # ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%b %d'))\n    plt.setp(ax.get_xticklabels(), visible=False)\n    ax.yaxis.set_label_coords(labelx, 0.5)\n\n    ax = plt.subplot(212)\n    plt.plot_date(dates, winds[:, 0], 'r-', label='best track')\n    plt.plot_date(dates, winds[:, 1], 'r--', label='derived track')\n    plt.ylabel('max. wind speed (ms$^{-1}$)')\n    plt.legend(bbox_to_anchor=(1.07, 1.07), numpoints=1, prop={'size': 10})\n    ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%b %d'))\n    ax.yaxis.set_label_coords(-0.09, 0.5)\n\n    fig.set_size_inches(6.3, 5)\n    _save_figure('katrina_best_derived_comparison.png')\n\n\ndef plot_2005_pressure_wind_corr(ca=None):\n    if not ca:\n        ca = ClassificationAnalysis()\n\n    # c20data = C20Data(2005, fields=['prmsl', 'u', 'v'])\n    key = 'cyclones'\n\n    pressures = []\n    winds = []\n\n    for em in range(56):\n        print(em)\n        cs, ms, ums = ca.run_individual_cla_analysis(2005, em)\n\n        for cm in ms:\n            for date, bt_pres, bt_wind in zip(cm.best_track.dates,\n                                              cm.best_track.pressures,\n                                              cm.best_track.winds):\n                if date in cm.cyclone.pmins and cm.cyclone.pmins[date]:\n                    pressures.append((bt_pres, cm.cyclone.pmins[date] / 100.))\n                    winds.append((bt_wind, cm.cyclone.max_windspeeds[date]))\n    pressures, winds = np.array(pressures), np.array(winds)\n    _plot_pres_wind(pressures, winds)\n    return pressures, winds\n\n\ndef _plot_pres_wind(pressures, winds):\n    fig = plt.figure()\n    ax = plt.subplot(121)\n    plt.plot(pressures[:, 0], pressures[:, 1], 'b+')\n    rp = stats.linregress(pressures)\n    label = 'grad.: {0:.2f}\\nintercept: {1:.1f}\\n r$^2$: {2:.2f}'.format(rp[0], rp[1], rp[2] ** 2)\n    plt.plot((880, 1040), (880 * rp[0] + rp[1], 1040 * rp[0] + rp[1]), 'r--', label=label)\n    plt.ylabel('derived track pressure (hPa)')\n    plt.xlabel('best track\\npressure (hPa)')\n    plt.legend(bbox_to_anchor=(0.9, 1.23), numpoints=1, prop={'size': 10})\n    ax.set_xticks((880, 920, 960, 1000, 1040))\n\n    ax = plt.subplot(122)\n    plt.plot(winds[:, 0], winds[:, 1], 'b+')\n    rw = stats.linregress(winds)\n    label = 'grad.: {0:.2f}\\nintercept: {1:.1f}\\n r$^2$: {2:.2f}'.format(rw[0], rw[1], rw[2] ** 2)\n    plt.plot((0, 160), (0 * rw[0] + rw[1], 160 * rw[0] + rw[1]), 'r--', label=label)\n    plt.ylabel('derived track max. wind speed (ms$^{-1}$)')\n    plt.xlabel('best track\\nmax. wind speed (ms$^{-1}$)')\n    plt.legend(bbox_to_anchor=(0.9, 1.23), numpoints=1, prop={'size': 10})\n    ax.set_xticks((0, 40, 80, 120, 160))\n    ax.yaxis.tick_right()\n    ax.yaxis.set_label_position(\"right\")\n\n    fig.set_size_inches(6.3, 3)\n    _save_figure('press_max_ws_corr_2005.png')\n\n\ndef _plot_point_on_earth(lon, lat, plot_fmt=None):\n    if plot_fmt:\n        plt.plot(lon_convert(lon), lat, plot_fmt)\n    else:\n        plt.plot(lon_convert(lon), lat)\n\n\ndef _raster_on_earth(lons, lats, data, vmin=None, vmax=None, loc=None, colorbar=True, labels=True):\n    if not loc:\n        m = Basemap(projection='cyl', resolution='c',\n                    llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180)\n    else:\n        m = Basemap(projection='cyl', resolution='c', **loc)\n\n    if data is not None:\n        plot_lons, plot_data = _extend_data(lons, lats, data)\n        lons, lats = np.meshgrid(plot_lons, lats)\n        x, y = m(lons, lats)\n        if vmin:\n            m.pcolormesh(x, y, plot_data, vmin=vmin, vmax=vmax)\n        else:\n            m.pcolormesh(x, y, plot_data)\n\n    m.drawcoastlines()\n\n    if labels:\n        p_labels = [0, 1, 0, 0]\n        m.drawparallels(np.arange(-90., 90.1, 45.), labels=p_labels, fontsize=10)\n        m.drawmeridians(np.arange(-180., 180., 60.), labels=[0, 0, 0, 1], fontsize=10)\n\n    if colorbar and data is not None:\n        m.colorbar(location='right', pad='7%')\n    return m\n\n\ndef _vec_plot_on_earth(lons, lats, x_data, y_data, vmin=-4, vmax=12, loc=None, colorbar=False):\n    plot_lons, plot_x_data = _extend_data(lons, lats, x_data)\n    plot_lons, plot_y_data = _extend_data(lons, lats, y_data)\n\n    lons, lats = np.meshgrid(plot_lons, lats)\n\n    if not loc:\n        m = Basemap(projection='cyl', resolution='c',\n                    llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180)\n    else:\n        m = Basemap(projection='cyl', resolution='c', **loc)\n    x, y = m(lons, lats)\n\n    mag = np.sqrt(plot_x_data**2 + plot_y_data**2)\n    vmin, vmax = mag.min(), mag.max()\n    m.contourf(x, y, mag)\n    # m.pcolormesh(x, y, mag, vmin=vmin, vmax=vmax)\n    # m.quiver(x, y, plot_x_data, plot_y_data)\n    skip = 1\n    m.quiver(x[::skip, ::skip], y[::skip, ::skip],\n             plot_x_data[::skip, ::skip], plot_y_data[::skip, ::skip], scale=500)\n\n    m.drawcoastlines()\n    m.drawparallels(np.arange(-90., 90., 45.), labels=[1, 0, 0, 0], fontsize=10)\n    m.drawmeridians(np.arange(-180., 180., 60.), labels=[0, 0, 0, 1], fontsize=10)\n\n    if colorbar:\n        m.colorbar(location='right', pad='7%')\n    return m\n\n\ndef _extend_data(lons, lats, data):\n    if False:\n        # TODO: probably doesn't work!\n        # Adds extra data at the end.\n        plot_offset = 2\n        plot_lons = np.zeros((lons.shape[0] + plot_offset,))\n        plot_lons[:-plot_offset] = lons\n        plot_lons[-plot_offset:] = lons[-plot_offset:] + 3.75 * plot_offset\n\n        plot_data = np.zeros((data.shape[0], data.shape[1] + plot_offset))\n        plot_data[:, :-plot_offset] = data\n        plot_data[:, -plot_offset:] = data[:, :plot_offset]\n    else:\n        # Adds extra data before the start.\n        delta = lons[1] - lons[0]\n        plot_offset = 180\n        plot_lons = np.ma.zeros((lons.shape[0] + plot_offset,))\n        plot_lons[plot_offset:] = lons\n        plot_lons[:plot_offset] = lons[-plot_offset:] - delta * (lons.shape[0])\n\n        plot_data = np.ma.zeros((data.shape[0], data.shape[1] + plot_offset))\n        plot_data[:, plot_offset:] = data\n        plot_data[:, :plot_offset] = data[:, -plot_offset:]\n\n    return plot_lons, plot_data\n\n\ndef _save_figure(name):\n    if not os.path.exists(settings.FIGURE_OUTPUT_DIR):\n        os.makedirs(settings.FIGURE_OUTPUT_DIR)\n    plt.savefig(os.path.join(settings.FIGURE_OUTPUT_DIR, name), bbox_inches='tight')\n\n\ndef main():\n    import sys\n    import inspect\n\n    print('Loading all data from: {}'.format(settings.DATA_DIR))\n    ib_hurrs, ib_pdis, cla_hurrs, cla_pdis, adjustment_ratio = load_20th_century()\n    thresh_metrics = load_thresh_metric_vs_vort_lo()\n    classifier_metrics = load_classifier_metrics()\n    yearly_hurr_distribution, hurr_per_year = load_ibtracs_info()\n    print('Data loaded')\n\n    functions = inspect.getmembers(sys.modules[__name__], inspect.isfunction)\n    for name, fn in functions:\n        if name[:5] == 'plot_':\n            try:\n                print(name)\n                if name in ('plot_20th_century',\n                            'plot_poster_20th_century',\n                            'plot_poster_20th_century_trends',\n                            'plot_20th_century_corr'):\n                    fn(ib_hurrs, cla_hurrs, adjustment_ratio)\n                elif name == 'plot_thresh_metric_vs_vort_lo':\n                    fn(thresh_metrics)\n                elif name == 'plot_classifer_metrics':\n                    fn(classifier_metrics)\n                elif name == 'plot_yearly_hurr_dist':\n                    fn(yearly_hurr_distribution)\n                elif name == 'plot_hurr_per_year':\n                    fn(hurr_per_year)\n                elif name == 'plot_cal_cd':\n                    cla_analysis = ClassificationAnalysis()\n                    cal_cd = cla_analysis.load_cal_classification_data()\n                    plot_cal_cd(cal_cd)\n                else:\n                    fn()\n            except:\n                print('PROBLEM PLOTTING {0}, SKIPPING'.format(name))\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "7f695ca7a396b56e3605a6a92a33fcc5cdb33d27", "size": 45034, "ext": "py", "lang": "Python", "max_stars_repo_path": "stormtracks/analysis/figure_plotting.py", "max_stars_repo_name": "subond/stormtracks", "max_stars_repo_head_hexsha": "63556053d71013ec044aa207d0978c0e9e76d859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2016-08-29T20:35:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T05:12:58.000Z", "max_issues_repo_path": "stormtracks/analysis/figure_plotting.py", "max_issues_repo_name": "xiaoxiaoyu0302/stormtracks", "max_issues_repo_head_hexsha": "63556053d71013ec044aa207d0978c0e9e76d859", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2015-02-23T17:21:25.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-14T11:15:31.000Z", "max_forks_repo_path": "stormtracks/analysis/figure_plotting.py", "max_forks_repo_name": "xiaoxiaoyu0302/stormtracks", "max_forks_repo_head_hexsha": "63556053d71013ec044aa207d0978c0e9e76d859", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2017-01-29T23:29:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-22T11:16:46.000Z", "avg_line_length": 36.4647773279, "max_line_length": 100, "alphanum_fraction": 0.5734556113, "include": true, "reason": "import numpy,from scipy", "num_tokens": 14034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.1946674878277107}}
{"text": "\"\"\"\nLow-level functions for complex arithmetic.\n\"\"\"\n\nimport sys\n\nfrom .backend import MPZ, MPZ_ZERO, MPZ_ONE, MPZ_TWO, BACKEND\n\nfrom .libmpf import (\\\n    round_floor, round_ceiling, round_down, round_up,\n    round_nearest, round_fast, bitcount,\n    bctable, normalize, normalize1, reciprocal_rnd, rshift, lshift, giant_steps,\n    negative_rnd,\n    to_str, to_fixed, from_man_exp, from_float, to_float, from_int, to_int,\n    fzero, fone, ftwo, fhalf, finf, fninf, fnan, fnone,\n    mpf_abs, mpf_pos, mpf_neg, mpf_add, mpf_sub, mpf_mul,\n    mpf_div, mpf_mul_int, mpf_shift, mpf_sqrt, mpf_hypot,\n    mpf_rdiv_int, mpf_floor, mpf_ceil, mpf_nint, mpf_frac,\n    mpf_sign, mpf_hash,\n    ComplexResult\n)\n\nfrom .libelefun import (\\\n    mpf_pi, mpf_exp, mpf_log, mpf_cos_sin, mpf_cosh_sinh, mpf_tan, mpf_pow_int,\n    mpf_log_hypot,\n    mpf_cos_sin_pi, mpf_phi,\n    mpf_cos, mpf_sin, mpf_cos_pi, mpf_sin_pi,\n    mpf_atan, mpf_atan2, mpf_cosh, mpf_sinh, mpf_tanh,\n    mpf_asin, mpf_acos, mpf_acosh, mpf_nthroot, mpf_fibonacci\n)\n\n# An mpc value is a (real, imag) tuple\nmpc_one = fone, fzero\nmpc_zero = fzero, fzero\nmpc_two = ftwo, fzero\nmpc_half = (fhalf, fzero)\n\n_infs = (finf, fninf)\n_infs_nan = (finf, fninf, fnan)\n\ndef mpc_is_inf(z):\n    \"\"\"Check if either real or imaginary part is infinite\"\"\"\n    re, im = z\n    if re in _infs: return True\n    if im in _infs: return True\n    return False\n\ndef mpc_is_infnan(z):\n    \"\"\"Check if either real or imaginary part is infinite or nan\"\"\"\n    re, im = z\n    if re in _infs_nan: return True\n    if im in _infs_nan: return True\n    return False\n\ndef mpc_to_str(z, dps, **kwargs):\n    re, im = z\n    rs = to_str(re, dps)\n    if im[0]:\n        return rs + \" - \" + to_str(mpf_neg(im), dps, **kwargs) + \"j\"\n    else:\n        return rs + \" + \" + to_str(im, dps, **kwargs) + \"j\"\n\ndef mpc_to_complex(z, strict=False, rnd=round_fast):\n    re, im = z\n    return complex(to_float(re, strict, rnd), to_float(im, strict, rnd))\n\ndef mpc_hash(z):\n    if sys.version >= \"3.2\":\n        re, im = z\n        h = mpf_hash(re) + sys.hash_info.imag * mpf_hash(im)\n        # Need to reduce either module 2^32 or 2^64\n        h = h % (2**sys.hash_info.width)\n        return int(h)\n    else:\n        try:\n            return hash(mpc_to_complex(z, strict=True))\n        except OverflowError:\n            return hash(z)\n\ndef mpc_conjugate(z, prec, rnd=round_fast):\n    re, im = z\n    return re, mpf_neg(im, prec, rnd)\n\ndef mpc_is_nonzero(z):\n    return z != mpc_zero\n\ndef mpc_add(z, w, prec, rnd=round_fast):\n    a, b = z\n    c, d = w\n    return mpf_add(a, c, prec, rnd), mpf_add(b, d, prec, rnd)\n\ndef mpc_add_mpf(z, x, prec, rnd=round_fast):\n    a, b = z\n    return mpf_add(a, x, prec, rnd), b\n\ndef mpc_sub(z, w, prec=0, rnd=round_fast):\n    a, b = z\n    c, d = w\n    return mpf_sub(a, c, prec, rnd), mpf_sub(b, d, prec, rnd)\n\ndef mpc_sub_mpf(z, p, prec=0, rnd=round_fast):\n    a, b = z\n    return mpf_sub(a, p, prec, rnd), b\n\ndef mpc_pos(z, prec, rnd=round_fast):\n    a, b = z\n    return mpf_pos(a, prec, rnd), mpf_pos(b, prec, rnd)\n\ndef mpc_neg(z, prec=None, rnd=round_fast):\n    a, b = z\n    return mpf_neg(a, prec, rnd), mpf_neg(b, prec, rnd)\n\ndef mpc_shift(z, n):\n    a, b = z\n    return mpf_shift(a, n), mpf_shift(b, n)\n\ndef mpc_abs(z, prec, rnd=round_fast):\n    \"\"\"Absolute value of a complex number, |a+bi|.\n    Returns an mpf value.\"\"\"\n    a, b = z\n    return mpf_hypot(a, b, prec, rnd)\n\ndef mpc_arg(z, prec, rnd=round_fast):\n    \"\"\"Argument of a complex number. Returns an mpf value.\"\"\"\n    a, b = z\n    return mpf_atan2(b, a, prec, rnd)\n\ndef mpc_floor(z, prec, rnd=round_fast):\n    a, b = z\n    return mpf_floor(a, prec, rnd), mpf_floor(b, prec, rnd)\n\ndef mpc_ceil(z, prec, rnd=round_fast):\n    a, b = z\n    return mpf_ceil(a, prec, rnd), mpf_ceil(b, prec, rnd)\n\ndef mpc_nint(z, prec, rnd=round_fast):\n    a, b = z\n    return mpf_nint(a, prec, rnd), mpf_nint(b, prec, rnd)\n\ndef mpc_frac(z, prec, rnd=round_fast):\n    a, b = z\n    return mpf_frac(a, prec, rnd), mpf_frac(b, prec, rnd)\n\n\ndef mpc_mul(z, w, prec, rnd=round_fast):\n    \"\"\"\n    Complex multiplication.\n\n    Returns the real and imaginary part of (a+bi)*(c+di), rounded to\n    the specified precision. The rounding mode applies to the real and\n    imaginary parts separately.\n    \"\"\"\n    a, b = z\n    c, d = w\n    p = mpf_mul(a, c)\n    q = mpf_mul(b, d)\n    r = mpf_mul(a, d)\n    s = mpf_mul(b, c)\n    re = mpf_sub(p, q, prec, rnd)\n    im = mpf_add(r, s, prec, rnd)\n    return re, im\n\ndef mpc_square(z, prec, rnd=round_fast):\n    # (a+b*I)**2 == a**2 - b**2 + 2*I*a*b\n    a, b = z\n    p = mpf_mul(a,a)\n    q = mpf_mul(b,b)\n    r = mpf_mul(a,b, prec, rnd)\n    re = mpf_sub(p, q, prec, rnd)\n    im = mpf_shift(r, 1)\n    return re, im\n\ndef mpc_mul_mpf(z, p, prec, rnd=round_fast):\n    a, b = z\n    re = mpf_mul(a, p, prec, rnd)\n    im = mpf_mul(b, p, prec, rnd)\n    return re, im\n\ndef mpc_mul_imag_mpf(z, x, prec, rnd=round_fast):\n    \"\"\"\n    Multiply the mpc value z by I*x where x is an mpf value.\n    \"\"\"\n    a, b = z\n    re = mpf_neg(mpf_mul(b, x, prec, rnd))\n    im = mpf_mul(a, x, prec, rnd)\n    return re, im\n\ndef mpc_mul_int(z, n, prec, rnd=round_fast):\n    a, b = z\n    re = mpf_mul_int(a, n, prec, rnd)\n    im = mpf_mul_int(b, n, prec, rnd)\n    return re, im\n\ndef mpc_div(z, w, prec, rnd=round_fast):\n    a, b = z\n    c, d = w\n    wp = prec + 10\n    # mag = c*c + d*d\n    mag = mpf_add(mpf_mul(c, c), mpf_mul(d, d), wp)\n    # (a*c+b*d)/mag, (b*c-a*d)/mag\n    t = mpf_add(mpf_mul(a,c), mpf_mul(b,d), wp)\n    u = mpf_sub(mpf_mul(b,c), mpf_mul(a,d), wp)\n    return mpf_div(t,mag,prec,rnd), mpf_div(u,mag,prec,rnd)\n\ndef mpc_div_mpf(z, p, prec, rnd=round_fast):\n    \"\"\"Calculate z/p where p is real\"\"\"\n    a, b = z\n    re = mpf_div(a, p, prec, rnd)\n    im = mpf_div(b, p, prec, rnd)\n    return re, im\n\ndef mpc_reciprocal(z, prec, rnd=round_fast):\n    \"\"\"Calculate 1/z efficiently\"\"\"\n    a, b = z\n    m = mpf_add(mpf_mul(a,a),mpf_mul(b,b),prec+10)\n    re = mpf_div(a, m, prec, rnd)\n    im = mpf_neg(mpf_div(b, m, prec, rnd))\n    return re, im\n\ndef mpc_mpf_div(p, z, prec, rnd=round_fast):\n    \"\"\"Calculate p/z where p is real efficiently\"\"\"\n    a, b = z\n    m = mpf_add(mpf_mul(a,a),mpf_mul(b,b), prec+10)\n    re = mpf_div(mpf_mul(a,p), m, prec, rnd)\n    im = mpf_div(mpf_neg(mpf_mul(b,p)), m, prec, rnd)\n    return re, im\n\ndef complex_int_pow(a, b, n):\n    \"\"\"Complex integer power: computes (a+b*I)**n exactly for\n    nonnegative n (a and b must be Python ints).\"\"\"\n    wre = 1\n    wim = 0\n    while n:\n        if n & 1:\n            wre, wim = wre*a - wim*b, wim*a + wre*b\n            n -= 1\n        a, b = a*a - b*b, 2*a*b\n        n //= 2\n    return wre, wim\n\ndef mpc_pow(z, w, prec, rnd=round_fast):\n    if w[1] == fzero:\n        return mpc_pow_mpf(z, w[0], prec, rnd)\n    return mpc_exp(mpc_mul(mpc_log(z, prec+10), w, prec+10), prec, rnd)\n\ndef mpc_pow_mpf(z, p, prec, rnd=round_fast):\n    psign, pman, pexp, pbc = p\n    if pexp >= 0:\n        return mpc_pow_int(z, (-1)**psign * (pman<<pexp), prec, rnd)\n    if pexp == -1:\n        sqrtz = mpc_sqrt(z, prec+10)\n        return mpc_pow_int(sqrtz, (-1)**psign * pman, prec, rnd)\n    return mpc_exp(mpc_mul_mpf(mpc_log(z, prec+10), p, prec+10), prec, rnd)\n\ndef mpc_pow_int(z, n, prec, rnd=round_fast):\n    a, b = z\n    if b == fzero:\n        return mpf_pow_int(a, n, prec, rnd), fzero\n    if a == fzero:\n        v = mpf_pow_int(b, n, prec, rnd)\n        n %= 4\n        if n == 0:\n            return v, fzero\n        elif n == 1:\n            return fzero, v\n        elif n == 2:\n            return mpf_neg(v), fzero\n        elif n == 3:\n            return fzero, mpf_neg(v)\n    if n == 0: return mpc_one\n    if n == 1: return mpc_pos(z, prec, rnd)\n    if n == 2: return mpc_square(z, prec, rnd)\n    if n == -1: return mpc_reciprocal(z, prec, rnd)\n    if n < 0: return mpc_reciprocal(mpc_pow_int(z, -n, prec+4), prec, rnd)\n    asign, aman, aexp, abc = a\n    bsign, bman, bexp, bbc = b\n    if asign: aman = -aman\n    if bsign: bman = -bman\n    de = aexp - bexp\n    abs_de = abs(de)\n    exact_size = n*(abs_de + max(abc, bbc))\n    if exact_size < 10000:\n        if de > 0:\n            aman <<= de\n            aexp = bexp\n        else:\n            bman <<= (-de)\n            bexp = aexp\n        re, im = complex_int_pow(aman, bman, n)\n        re = from_man_exp(re, int(n*aexp), prec, rnd)\n        im = from_man_exp(im, int(n*bexp), prec, rnd)\n        return re, im\n    return mpc_exp(mpc_mul_int(mpc_log(z, prec+10), n, prec+10), prec, rnd)\n\ndef mpc_sqrt(z, prec, rnd=round_fast):\n    \"\"\"Complex square root (principal branch).\n\n    We have sqrt(a+bi) = sqrt((r+a)/2) + b/sqrt(2*(r+a))*i where\n    r = abs(a+bi), when a+bi is not a negative real number.\"\"\"\n    a, b = z\n    if b == fzero:\n        if a == fzero:\n            return (a, b)\n        # When a+bi is a negative real number, we get a real sqrt times i\n        if a[0]:\n            im = mpf_sqrt(mpf_neg(a), prec, rnd)\n            return (fzero, im)\n        else:\n            re = mpf_sqrt(a, prec, rnd)\n            return (re, fzero)\n    wp = prec+20\n    if not a[0]:                               # case a positive\n        t  = mpf_add(mpc_abs((a, b), wp), a, wp)  # t = abs(a+bi) + a\n        u = mpf_shift(t, -1)                      # u = t/2\n        re = mpf_sqrt(u, prec, rnd)               # re = sqrt(u)\n        v = mpf_shift(t, 1)                       # v = 2*t\n        w  = mpf_sqrt(v, wp)                      # w = sqrt(v)\n        im = mpf_div(b, w, prec, rnd)             # im = b / w\n    else:                                      # case a negative\n        t = mpf_sub(mpc_abs((a, b), wp), a, wp)   # t = abs(a+bi) - a\n        u = mpf_shift(t, -1)                      # u = t/2\n        im = mpf_sqrt(u, prec, rnd)               # im = sqrt(u)\n        v = mpf_shift(t, 1)                       # v = 2*t\n        w  = mpf_sqrt(v, wp)                      # w = sqrt(v)\n        re = mpf_div(b, w, prec, rnd)             # re = b/w\n        if b[0]:\n            re = mpf_neg(re)\n            im = mpf_neg(im)\n    return re, im\n\ndef mpc_nthroot_fixed(a, b, n, prec):\n    # a, b signed integers at fixed precision prec\n    start = 50\n    a1 = int(rshift(a, prec - n*start))\n    b1 = int(rshift(b, prec - n*start))\n    try:\n        r = (a1 + 1j * b1)**(1.0/n)\n        re = r.real\n        im = r.imag\n        re = MPZ(int(re))\n        im = MPZ(int(im))\n    except OverflowError:\n        a1 = from_int(a1, start)\n        b1 = from_int(b1, start)\n        fn = from_int(n)\n        nth = mpf_rdiv_int(1, fn, start)\n        re, im = mpc_pow((a1, b1), (nth, fzero), start)\n        re = to_int(re)\n        im = to_int(im)\n    extra = 10\n    prevp = start\n    extra1 = n\n    for p in giant_steps(start, prec+extra):\n        # this is slow for large n, unlike int_pow_fixed\n        re2, im2 = complex_int_pow(re, im, n-1)\n        re2 = rshift(re2, (n-1)*prevp - p - extra1)\n        im2 = rshift(im2, (n-1)*prevp - p - extra1)\n        r4 = (re2*re2 + im2*im2) >> (p + extra1)\n        ap = rshift(a, prec - p)\n        bp = rshift(b, prec - p)\n        rec = (ap * re2 + bp * im2) >> p\n        imc = (-ap * im2 + bp * re2) >> p\n        reb = (rec << p) // r4\n        imb = (imc << p) // r4\n        re = (reb + (n-1)*lshift(re, p-prevp))//n\n        im = (imb + (n-1)*lshift(im, p-prevp))//n\n        prevp = p\n    return re, im\n\ndef mpc_nthroot(z, n, prec, rnd=round_fast):\n    \"\"\"\n    Complex n-th root.\n\n    Use Newton method as in the real case when it is faster,\n    otherwise use z**(1/n)\n    \"\"\"\n    a, b = z\n    if a[0] == 0 and b == fzero:\n        re = mpf_nthroot(a, n, prec, rnd)\n        return (re, fzero)\n    if n < 2:\n        if n == 0:\n            return mpc_one\n        if n == 1:\n            return mpc_pos((a, b), prec, rnd)\n        if n == -1:\n            return mpc_div(mpc_one, (a, b), prec, rnd)\n        inverse = mpc_nthroot((a, b), -n, prec+5, reciprocal_rnd[rnd])\n        return mpc_div(mpc_one, inverse, prec, rnd)\n    if n <= 20:\n        prec2 = int(1.2 * (prec + 10))\n        asign, aman, aexp, abc = a\n        bsign, bman, bexp, bbc = b\n        pf = mpc_abs((a,b), prec)\n        if pf[-2] + pf[-1] > -10  and pf[-2] + pf[-1] < prec:\n            af = to_fixed(a, prec2)\n            bf = to_fixed(b, prec2)\n            re, im = mpc_nthroot_fixed(af, bf, n, prec2)\n            extra = 10\n            re = from_man_exp(re, -prec2-extra, prec2, rnd)\n            im = from_man_exp(im, -prec2-extra, prec2, rnd)\n            return re, im\n    fn = from_int(n)\n    prec2 = prec+10 + 10\n    nth = mpf_rdiv_int(1, fn, prec2)\n    re, im = mpc_pow((a, b), (nth, fzero), prec2, rnd)\n    re = normalize(re[0], re[1], re[2], re[3], prec, rnd)\n    im = normalize(im[0], im[1], im[2], im[3], prec, rnd)\n    return re, im\n\ndef mpc_cbrt(z, prec, rnd=round_fast):\n    \"\"\"\n    Complex cubic root.\n    \"\"\"\n    return mpc_nthroot(z, 3, prec, rnd)\n\ndef mpc_exp(z, prec, rnd=round_fast):\n    \"\"\"\n    Complex exponential function.\n\n    We use the direct formula exp(a+bi) = exp(a) * (cos(b) + sin(b)*i)\n    for the computation. This formula is very nice because it is\n    pefectly stable; since we just do real multiplications, the only\n    numerical errors that can creep in are single-ulp rounding errors.\n\n    The formula is efficient since mpmath's real exp is quite fast and\n    since we can compute cos and sin simultaneously.\n\n    It is no problem if a and b are large; if the implementations of\n    exp/cos/sin are accurate and efficient for all real numbers, then\n    so is this function for all complex numbers.\n    \"\"\"\n    a, b = z\n    if a == fzero:\n        return mpf_cos_sin(b, prec, rnd)\n    if b == fzero:\n        return mpf_exp(a, prec, rnd), fzero\n    mag = mpf_exp(a, prec+4, rnd)\n    c, s = mpf_cos_sin(b, prec+4, rnd)\n    re = mpf_mul(mag, c, prec, rnd)\n    im = mpf_mul(mag, s, prec, rnd)\n    return re, im\n\ndef mpc_log(z, prec, rnd=round_fast):\n    re = mpf_log_hypot(z[0], z[1], prec, rnd)\n    im = mpc_arg(z, prec, rnd)\n    return re, im\n\ndef mpc_cos(z, prec, rnd=round_fast):\n    \"\"\"Complex cosine. The formula used is cos(a+bi) = cos(a)*cosh(b) -\n    sin(a)*sinh(b)*i.\n\n    The same comments apply as for the complex exp: only real\n    multiplications are pewrormed, so no cancellation errors are\n    possible. The formula is also efficient since we can compute both\n    pairs (cos, sin) and (cosh, sinh) in single stwps.\"\"\"\n    a, b = z\n    if b == fzero:\n        return mpf_cos(a, prec, rnd), fzero\n    if a == fzero:\n        return mpf_cosh(b, prec, rnd), fzero\n    wp = prec + 6\n    c, s = mpf_cos_sin(a, wp)\n    ch, sh = mpf_cosh_sinh(b, wp)\n    re = mpf_mul(c, ch, prec, rnd)\n    im = mpf_mul(s, sh, prec, rnd)\n    return re, mpf_neg(im)\n\ndef mpc_sin(z, prec, rnd=round_fast):\n    \"\"\"Complex sine. We have sin(a+bi) = sin(a)*cosh(b) +\n    cos(a)*sinh(b)*i. See the docstring for mpc_cos for additional\n    comments.\"\"\"\n    a, b = z\n    if b == fzero:\n        return mpf_sin(a, prec, rnd), fzero\n    if a == fzero:\n        return fzero, mpf_sinh(b, prec, rnd)\n    wp = prec + 6\n    c, s = mpf_cos_sin(a, wp)\n    ch, sh = mpf_cosh_sinh(b, wp)\n    re = mpf_mul(s, ch, prec, rnd)\n    im = mpf_mul(c, sh, prec, rnd)\n    return re, im\n\ndef mpc_tan(z, prec, rnd=round_fast):\n    \"\"\"Complex tangent. Computed as tan(a+bi) = sin(2a)/M + sinh(2b)/M*i\n    where M = cos(2a) + cosh(2b).\"\"\"\n    a, b = z\n    asign, aman, aexp, abc = a\n    bsign, bman, bexp, bbc = b\n    if b == fzero: return mpf_tan(a, prec, rnd), fzero\n    if a == fzero: return fzero, mpf_tanh(b, prec, rnd)\n    wp = prec + 15\n    a = mpf_shift(a, 1)\n    b = mpf_shift(b, 1)\n    c, s = mpf_cos_sin(a, wp)\n    ch, sh = mpf_cosh_sinh(b, wp)\n    # TODO: handle cancellation when c ~=  -1 and ch ~= 1\n    mag = mpf_add(c, ch, wp)\n    re = mpf_div(s, mag, prec, rnd)\n    im = mpf_div(sh, mag, prec, rnd)\n    return re, im\n\ndef mpc_cos_pi(z, prec, rnd=round_fast):\n    a, b = z\n    if b == fzero:\n        return mpf_cos_pi(a, prec, rnd), fzero\n    b = mpf_mul(b, mpf_pi(prec+5), prec+5)\n    if a == fzero:\n        return mpf_cosh(b, prec, rnd), fzero\n    wp = prec + 6\n    c, s = mpf_cos_sin_pi(a, wp)\n    ch, sh = mpf_cosh_sinh(b, wp)\n    re = mpf_mul(c, ch, prec, rnd)\n    im = mpf_mul(s, sh, prec, rnd)\n    return re, mpf_neg(im)\n\ndef mpc_sin_pi(z, prec, rnd=round_fast):\n    a, b = z\n    if b == fzero:\n        return mpf_sin_pi(a, prec, rnd), fzero\n    b = mpf_mul(b, mpf_pi(prec+5), prec+5)\n    if a == fzero:\n        return fzero, mpf_sinh(b, prec, rnd)\n    wp = prec + 6\n    c, s = mpf_cos_sin_pi(a, wp)\n    ch, sh = mpf_cosh_sinh(b, wp)\n    re = mpf_mul(s, ch, prec, rnd)\n    im = mpf_mul(c, sh, prec, rnd)\n    return re, im\n\ndef mpc_cos_sin(z, prec, rnd=round_fast):\n    a, b = z\n    if a == fzero:\n        ch, sh = mpf_cosh_sinh(b, prec, rnd)\n        return (ch, fzero), (fzero, sh)\n    if b == fzero:\n        c, s = mpf_cos_sin(a, prec, rnd)\n        return (c, fzero), (s, fzero)\n    wp = prec + 6\n    c, s = mpf_cos_sin(a, wp)\n    ch, sh = mpf_cosh_sinh(b, wp)\n    cre = mpf_mul(c, ch, prec, rnd)\n    cim = mpf_mul(s, sh, prec, rnd)\n    sre = mpf_mul(s, ch, prec, rnd)\n    sim = mpf_mul(c, sh, prec, rnd)\n    return (cre, mpf_neg(cim)), (sre, sim)\n\ndef mpc_cos_sin_pi(z, prec, rnd=round_fast):\n    a, b = z\n    if b == fzero:\n        c, s = mpf_cos_sin_pi(a, prec, rnd)\n        return (c, fzero), (s, fzero)\n    b = mpf_mul(b, mpf_pi(prec+5), prec+5)\n    if a == fzero:\n        ch, sh = mpf_cosh_sinh(b, prec, rnd)\n        return (ch, fzero), (fzero, sh)\n    wp = prec + 6\n    c, s = mpf_cos_sin_pi(a, wp)\n    ch, sh = mpf_cosh_sinh(b, wp)\n    cre = mpf_mul(c, ch, prec, rnd)\n    cim = mpf_mul(s, sh, prec, rnd)\n    sre = mpf_mul(s, ch, prec, rnd)\n    sim = mpf_mul(c, sh, prec, rnd)\n    return (cre, mpf_neg(cim)), (sre, sim)\n\ndef mpc_cosh(z, prec, rnd=round_fast):\n    \"\"\"Complex hyperbolic cosine. Computed as cosh(z) = cos(z*i).\"\"\"\n    a, b = z\n    return mpc_cos((b, mpf_neg(a)), prec, rnd)\n\ndef mpc_sinh(z, prec, rnd=round_fast):\n    \"\"\"Complex hyperbolic sine. Computed as sinh(z) = -i*sin(z*i).\"\"\"\n    a, b = z\n    b, a = mpc_sin((b, a), prec, rnd)\n    return a, b\n\ndef mpc_tanh(z, prec, rnd=round_fast):\n    \"\"\"Complex hyperbolic tangent. Computed as tanh(z) = -i*tan(z*i).\"\"\"\n    a, b = z\n    b, a = mpc_tan((b, a), prec, rnd)\n    return a, b\n\n# TODO: avoid loss of accuracy\ndef mpc_atan(z, prec, rnd=round_fast):\n    a, b = z\n    # atan(z) = (I/2)*(log(1-I*z) - log(1+I*z))\n    # x = 1-I*z = 1 + b - I*a\n    # y = 1+I*z = 1 - b + I*a\n    wp = prec + 15\n    x = mpf_add(fone, b, wp), mpf_neg(a)\n    y = mpf_sub(fone, b, wp), a\n    l1 = mpc_log(x, wp)\n    l2 = mpc_log(y, wp)\n    a, b = mpc_sub(l1, l2, prec, rnd)\n    # (I/2) * (a+b*I) = (-b/2 + a/2*I)\n    v = mpf_neg(mpf_shift(b,-1)), mpf_shift(a,-1)\n    # Subtraction at infinity gives correct real part but\n    # wrong imaginary part (should be zero)\n    if v[1] == fnan and mpc_is_inf(z):\n        v = (v[0], fzero)\n    return v\n\nbeta_crossover = from_float(0.6417)\nalpha_crossover = from_float(1.5)\n\ndef acos_asin(z, prec, rnd, n):\n    \"\"\" complex acos for n = 0, asin for n = 1\n    The algorithm is described in\n    T.E. Hull, T.F. Fairgrieve and P.T.P. Tang\n    'Implementing the Complex Arcsine and Arcosine Functions\n    using Exception Handling',\n    ACM Trans. on Math. Software Vol. 23 (1997), p299\n    The complex acos and asin can be defined as\n    acos(z) = acos(beta) - I*sign(a)* log(alpha + sqrt(alpha**2 -1))\n    asin(z) = asin(beta) + I*sign(a)* log(alpha + sqrt(alpha**2 -1))\n    where z = a + I*b\n    alpha = (1/2)*(r + s); beta = (1/2)*(r - s) = a/alpha\n    r = sqrt((a+1)**2 + y**2); s = sqrt((a-1)**2 + y**2)\n    These expressions are rewritten in different ways in different\n    regions, delimited by two crossovers alpha_crossover and beta_crossover,\n    and by abs(a) <= 1, in order to improve the numerical accuracy.\n    \"\"\"\n    a, b = z\n    wp = prec + 10\n    # special cases with real argument\n    if b == fzero:\n        am = mpf_sub(fone, mpf_abs(a), wp)\n        # case abs(a) <= 1\n        if not am[0]:\n            if n == 0:\n                return mpf_acos(a, prec, rnd), fzero\n            else:\n                return mpf_asin(a, prec, rnd), fzero\n        # cases abs(a) > 1\n        else:\n            # case a < -1\n            if a[0]:\n                pi = mpf_pi(prec, rnd)\n                c = mpf_acosh(mpf_neg(a), prec, rnd)\n                if n == 0:\n                    return pi, mpf_neg(c)\n                else:\n                    return mpf_neg(mpf_shift(pi, -1)), c\n            # case a > 1\n            else:\n                c = mpf_acosh(a, prec, rnd)\n                if n == 0:\n                    return fzero, c\n                else:\n                    pi = mpf_pi(prec, rnd)\n                    return mpf_shift(pi, -1), mpf_neg(c)\n    asign = bsign = 0\n    if a[0]:\n        a = mpf_neg(a)\n        asign = 1\n    if b[0]:\n        b = mpf_neg(b)\n        bsign = 1\n    am = mpf_sub(fone, a, wp)\n    ap = mpf_add(fone, a, wp)\n    r = mpf_hypot(ap, b, wp)\n    s = mpf_hypot(am, b, wp)\n    alpha = mpf_shift(mpf_add(r, s, wp), -1)\n    beta = mpf_div(a, alpha, wp)\n    b2 = mpf_mul(b,b, wp)\n    # case beta <= beta_crossover\n    if not mpf_sub(beta_crossover, beta, wp)[0]:\n        if n == 0:\n            re = mpf_acos(beta, wp)\n        else:\n            re = mpf_asin(beta, wp)\n    else:\n        # to compute the real part in this region use the identity\n        # asin(beta) = atan(beta/sqrt(1-beta**2))\n        # beta/sqrt(1-beta**2) = (alpha + a) * (alpha - a)\n        # alpha + a is numerically accurate; alpha - a can have\n        # cancellations leading to numerical inaccuracies, so rewrite\n        # it in differente ways according to the region\n        Ax = mpf_add(alpha, a, wp)\n        # case a <= 1\n        if not am[0]:\n            # c = b*b/(r + (a+1)); d = (s + (1-a))\n            # alpha - a = (1/2)*(c + d)\n            # case n=0: re = atan(sqrt((1/2) * Ax * (c + d))/a)\n            # case n=1: re = atan(a/sqrt((1/2) * Ax * (c + d)))\n            c = mpf_div(b2, mpf_add(r, ap, wp), wp)\n            d = mpf_add(s, am, wp)\n            re = mpf_shift(mpf_mul(Ax, mpf_add(c, d, wp), wp), -1)\n            if n == 0:\n                re = mpf_atan(mpf_div(mpf_sqrt(re, wp), a, wp), wp)\n            else:\n                re = mpf_atan(mpf_div(a, mpf_sqrt(re, wp), wp), wp)\n        else:\n            # c = Ax/(r + (a+1)); d = Ax/(s - (1-a))\n            # alpha - a = (1/2)*(c + d)\n            # case n = 0: re = atan(b*sqrt(c + d)/2/a)\n            # case n = 1: re = atan(a/(b*sqrt(c + d)/2)\n            c = mpf_div(Ax, mpf_add(r, ap, wp), wp)\n            d = mpf_div(Ax, mpf_sub(s, am, wp), wp)\n            re = mpf_shift(mpf_add(c, d, wp), -1)\n            re = mpf_mul(b, mpf_sqrt(re, wp), wp)\n            if n == 0:\n                re = mpf_atan(mpf_div(re, a, wp), wp)\n            else:\n                re = mpf_atan(mpf_div(a, re, wp), wp)\n    # to compute alpha + sqrt(alpha**2 - 1), if alpha <= alpha_crossover\n    # replace it with 1 + Am1 + sqrt(Am1*(alpha+1)))\n    # where Am1 = alpha -1\n    # if alpha <= alpha_crossover:\n    if not mpf_sub(alpha_crossover, alpha, wp)[0]:\n        c1 = mpf_div(b2, mpf_add(r, ap, wp), wp)\n        # case a < 1\n        if mpf_neg(am)[0]:\n            # Am1 = (1/2) * (b*b/(r + (a+1)) + b*b/(s + (1-a))\n            c2 = mpf_add(s, am, wp)\n            c2 = mpf_div(b2, c2, wp)\n            Am1 = mpf_shift(mpf_add(c1, c2, wp), -1)\n        else:\n            # Am1 = (1/2) * (b*b/(r + (a+1)) + (s - (1-a)))\n            c2 = mpf_sub(s, am, wp)\n            Am1 = mpf_shift(mpf_add(c1, c2, wp), -1)\n        # im = log(1 + Am1 + sqrt(Am1*(alpha+1)))\n        im = mpf_mul(Am1, mpf_add(alpha, fone, wp), wp)\n        im = mpf_log(mpf_add(fone, mpf_add(Am1, mpf_sqrt(im, wp), wp), wp), wp)\n    else:\n        # im = log(alpha + sqrt(alpha*alpha - 1))\n        im = mpf_sqrt(mpf_sub(mpf_mul(alpha, alpha, wp), fone, wp), wp)\n        im = mpf_log(mpf_add(alpha, im, wp), wp)\n    if asign:\n        if n == 0:\n            re = mpf_sub(mpf_pi(wp), re, wp)\n        else:\n            re = mpf_neg(re)\n    if not bsign and n == 0:\n        im = mpf_neg(im)\n    if bsign and n == 1:\n        im = mpf_neg(im)\n    re = normalize(re[0], re[1], re[2], re[3], prec, rnd)\n    im = normalize(im[0], im[1], im[2], im[3], prec, rnd)\n    return re, im\n\ndef mpc_acos(z, prec, rnd=round_fast):\n    return acos_asin(z, prec, rnd, 0)\n\ndef mpc_asin(z, prec, rnd=round_fast):\n    return acos_asin(z, prec, rnd, 1)\n\ndef mpc_asinh(z, prec, rnd=round_fast):\n    # asinh(z) = I * asin(-I z)\n    a, b = z\n    a, b =  mpc_asin((b, mpf_neg(a)), prec, rnd)\n    return mpf_neg(b), a\n\ndef mpc_acosh(z, prec, rnd=round_fast):\n    # acosh(z) = -I * acos(z)   for Im(acos(z)) <= 0\n    #            +I * acos(z)   otherwise\n    a, b = mpc_acos(z, prec, rnd)\n    if b[0] or b == fzero:\n        return mpf_neg(b), a\n    else:\n        return b, mpf_neg(a)\n\ndef mpc_atanh(z, prec, rnd=round_fast):\n    # atanh(z) = (log(1+z)-log(1-z))/2\n    wp = prec + 15\n    a = mpc_add(z, mpc_one, wp)\n    b = mpc_sub(mpc_one, z, wp)\n    a = mpc_log(a, wp)\n    b = mpc_log(b, wp)\n    v = mpc_shift(mpc_sub(a, b, wp), -1)\n    # Subtraction at infinity gives correct imaginary part but\n    # wrong real part (should be zero)\n    if v[0] == fnan and mpc_is_inf(z):\n        v = (fzero, v[1])\n    return v\n\ndef mpc_fibonacci(z, prec, rnd=round_fast):\n    re, im = z\n    if im == fzero:\n        return (mpf_fibonacci(re, prec, rnd), fzero)\n    size = max(abs(re[2]+re[3]), abs(re[2]+re[3]))\n    wp = prec + size + 20\n    a = mpf_phi(wp)\n    b = mpf_add(mpf_shift(a, 1), fnone, wp)\n    u = mpc_pow((a, fzero), z, wp)\n    v = mpc_cos_pi(z, wp)\n    v = mpc_div(v, u, wp)\n    u = mpc_sub(u, v, wp)\n    u = mpc_div_mpf(u, b, prec, rnd)\n    return u\n\ndef mpf_expj(x, prec, rnd='f'):\n    raise ComplexResult\n\ndef mpc_expj(z, prec, rnd='f'):\n    re, im = z\n    if im == fzero:\n        return mpf_cos_sin(re, prec, rnd)\n    if re == fzero:\n        return mpf_exp(mpf_neg(im), prec, rnd), fzero\n    ey = mpf_exp(mpf_neg(im), prec+10)\n    c, s = mpf_cos_sin(re, prec+10)\n    re = mpf_mul(ey, c, prec, rnd)\n    im = mpf_mul(ey, s, prec, rnd)\n    return re, im\n\ndef mpf_expjpi(x, prec, rnd='f'):\n    raise ComplexResult\n\ndef mpc_expjpi(z, prec, rnd='f'):\n    re, im = z\n    if im == fzero:\n        return mpf_cos_sin_pi(re, prec, rnd)\n    sign, man, exp, bc = im\n    wp = prec+10\n    if man:\n        wp += max(0, exp+bc)\n    im = mpf_neg(mpf_mul(mpf_pi(wp), im, wp))\n    if re == fzero:\n        return mpf_exp(im, prec, rnd), fzero\n    ey = mpf_exp(im, prec+10)\n    c, s = mpf_cos_sin_pi(re, prec+10)\n    re = mpf_mul(ey, c, prec, rnd)\n    im = mpf_mul(ey, s, prec, rnd)\n    return re, im\n\n\nif BACKEND == 'sage':\n    try:\n        import sage.libs.mpmath.ext_libmp as _lbmp\n        mpc_exp = _lbmp.mpc_exp\n        mpc_sqrt = _lbmp.mpc_sqrt\n    except (ImportError, AttributeError):\n        print(\"Warning: Sage imports in libmpc failed\")\n", "meta": {"hexsha": "d9c309864fe2f68a885198b7b52deead61f96073", "size": 26869, "ext": "py", "lang": "Python", "max_stars_repo_path": "CodeIA/venv/Lib/site-packages/mpmath/libmp/libmpc.py", "max_stars_repo_name": "Finasty-lab/IA-Python", "max_stars_repo_head_hexsha": "286113504906fec11a5aa5fd1d12e38536b1c859", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 445, "max_stars_repo_stars_event_min_datetime": "2019-01-26T13:50:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T05:17:38.000Z", "max_issues_repo_path": "Library/lib/python3.7/site-packages/mpmath/libmp/libmpc.py", "max_issues_repo_name": "gengyong/Carnets", "max_issues_repo_head_hexsha": "8930a14f69360d4db115a85ff9e0f6efa80fa2e7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 242, "max_issues_repo_issues_event_min_datetime": "2019-01-29T15:48:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:09:21.000Z", "max_forks_repo_path": "Library/lib/python3.7/site-packages/mpmath/libmp/libmpc.py", "max_forks_repo_name": "gengyong/Carnets", "max_forks_repo_head_hexsha": "8930a14f69360d4db115a85ff9e0f6efa80fa2e7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2019-03-10T09:51:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T23:11:12.000Z", "avg_line_length": 32.1399521531, "max_line_length": 80, "alphanum_fraction": 0.5440470431, "include": true, "reason": "import sage", "num_tokens": 9514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.19465799805800993}}
{"text": "# coding: utf-8\n# Copyright (c) Materials Virtual Lab\n# Distributed under the terms of the BSD License.\n\nimport re\nimport os\nimport glob\nimport itertools\nimport subprocess\nfrom collections import OrderedDict\n\nimport numpy as np\nimport pandas as pd\nfrom monty.io import zopen\nfrom monty.os.path import which\nfrom monty.tempfile import ScratchDir\nfrom monty.serialization import loadfn\nfrom pymatgen import Structure, Lattice, Element\nfrom pymatgen.core import units\n\nfrom mlearn.potentials import Potential\nfrom mlearn.data import pool_from, convert_docs\nfrom mlearn.potentials.lammps.calcs import EnergyForceStress\n\nmodule_dir = os.path.dirname(__file__)\nNNinput_params = loadfn(os.path.join(module_dir, 'params', 'NNinput.json'))\n\nclass NNPotential(Potential):\n    \"\"\"\n    This class implements Neural Network Potential.\n    \"\"\"\n    bohr_to_angstrom = units.bohr_to_angstrom\n    eV_to_Ha = units.eV_to_Ha\n    pair_style = 'pair_style        nnp dir \"./\" showew no showewsum 0 ' \\\n                 'maxew 10000000 resetew yes cflength 1.8897261328 cfenergy 0.0367493254'\n    pair_coeff = 'pair_coeff        * * {}'\n    def __init__(self, name=None, param=None, weight_param=None, scaling_param=None):\n        \"\"\"\n\n        Args:\n            name (str): Name of force field.\n        \"\"\"\n        self.name = name if name else \"NNPotential\"\n        self.specie = None\n        self.weights = []\n        self.bs = []\n        self.atom_energy = None\n        self.normalized_nodes = None\n        self.epochs = None\n        self.param = param if param else {}\n        self.weight_param = weight_param if weight_param else None\n        self.scaling_param = scaling_param if scaling_param else None\n        self.fitted = False\n\n    def _line_up(self, structure, energy, forces, virial_stress):\n        \"\"\"\n        Convert input structure, energy, forces, virial_stress to\n        proper configuration format for RuNNer usage. Note that\n        RuNNer takes bohr as length unit and Hatree as energy unit.\n\n        Args:\n            structure (Structure): Pymatgen Structure object.\n            energy (float): DFT-calculated energy of the system.\n            forces (list): The forces should have dimension\n                (num_atoms, 3).\n            virial_stress (list): stress should has 6 distinct\n                elements arranged in order [xx, yy, zz, xy, yz, xz].\n\n        Returns:\n        \"\"\"\n        if len(structure.symbol_set) > 1:\n            raise ValueError(\"Structure is not unary.\")\n\n        inputs = OrderedDict(Size=structure.num_sites, \\\n                             SuperCell=structure.lattice, \\\n                             AtomData=(structure, forces), \\\n                             Energy=energy, \\\n                             Stress=virial_stress)\n\n        lines = ['begin']\n\n        if 'SuperCell' in inputs:\n            bohr_matrix = inputs['SuperCell'].matrix / self.bohr_to_angstrom\n            for vec in bohr_matrix:\n                lines.append('lattice {:>15.6f}{:>15.6f}{:>15.6f}'.format(*vec))\n        if 'AtomData' in inputs:\n            format_float = \\\n                'atom{:>16.9f}{:>16.9f}{:>16.9f}{:>4s}{:>15.9f}{:>15.9f}{:>15.9f}{:>15.9f}{:>15.9f}'\n            for i, (site, force) in enumerate(zip(structure, forces)):\n                lines.append(format_float.format(*site.coords / self.bohr_to_angstrom, \\\n                                site.species_string, 0.0, 0.0,\n                                *np.array(force) * self.eV_to_Ha * self.bohr_to_angstrom))\n        if 'Energy' in inputs:\n            lines.append('energy  {:f}'.format(energy * self.eV_to_Ha))\n\n        lines.append('charge  {:f}'.format(structure.charge))\n        lines.append('end')\n\n        return '\\n'.join(lines)\n\n    def write_cfgs(self, filename, cfg_pool):\n\n        lines = []\n        for dataset in cfg_pool:\n            if isinstance(dataset['structure'], dict):\n                structure = Structure.from_dict(dataset['structure'])\n            else:\n                structure = dataset['structure']\n            energy = dataset['outputs']['energy']\n            forces = dataset['outputs']['forces']\n            virial_stress = dataset['outputs']['virial_stress']\n\n            lines.append(self._line_up(structure, energy, forces, virial_stress))\n\n            # dist = np.unique(structure.distance_matrix.ravel())[1]\n            # if self.shortest_distance > dist:\n            #     self.shortest_distance = dist\n\n        self.specie = Element(structure.symbol_set[0])\n\n        with open(filename, 'w') as f:\n            f.write('\\n'.join(lines))\n\n        return filename\n\n    def write_input(self, **kwargs):\n        \"\"\"\n        Write input.nn file to train the Neural Network Potential.\n\n        Args:\n            atom_energy (float): Atomic reference energy.\n\n            kwargs:\n                General nnp settings:\n                    atom_energy (None): Free atom reference energy.\n                    cutoff_type (int): Type of cutoff function. Default to 1\n                        (i.e., cosine function).\n                    scale_features (int): Determine the method to scale the\n                        symmetry function.\n                        0: no scaling.\n                        1: scale_symmetry_functions.\n                        2: center_symmetry_functions.\n                        3. scale_symmetry_functions_sigma.\n                    scale_min_short (float): Minimum value for scaling.\n                        Default to 0.0.\n                    scale_max_short (float): Maximum value for scaling.\n                        Default to 1.\n                    hidden_layers (list): List of the numbers of\n                        nodes in each hidden layer.\n                    activations (str): Activation function for each hidden layer.\n                        't': tanh, 's': logistic, 'p': softplus.\n                    normalize_nodes (boolean): Whether to normalize input of nodes.\n\n                Additional settings for training:\n                    epoch (int): Number of training epochs.\n                    updater_type (int): Weight update method\n                        0: gradient Descent, 1: Kalman filter.\n                    parallel_mode (int): Training parallelization used.\n                        Default to serial mode.\n                    update_strategy (int): Update strategy.\n                        0: combined, 1: per-element.\n                    selection_mode (int): Update candidate selection mode.\n                        0: random, 1: sort, 2: threshold\n                    test_fraction (float): Fraction of structures kept for\n                        testing.\n                    force_weight (float): Weight of force updates relative\n                        to energy updates. Default to 10.0\n                    short_energy_fraction (float): Fraction of energy updates\n                        per epoch. Default to 1.0.\n                    short_force_fraction (float): Fraction of force updates\n                        per epoch. Default to 0.02315.\n                    short_energy_error_threshold (float): RMSE threshold for\n                        energy update candidates. Default to 0.0.\n                    short_force_error_threshold (float): RMSE threshold for\n                        force update candidates. Default to 1.0.\n                    rmse_threshold_trials (int): Maximum number of RMSE\n                        threshold trials. Default to 3.\n                    weights_min (float): Minimum value for initial random\n                        weights. Default to -1.\n                    weights_max (float): Maximum value for initial random\n                        weights. Default to 1.\n                    write_trainpoints (int): Write energy comparison every\n                        this many epochs. Default to 1.\n                    write_trainforces (int): Write force comparison every\n                        this many epochs. Default to 1.\n                    write_weights_epoch (int): Write weights every this many\n                        epochs. Default to 1.\n                    write_neuronstats (int): Write neuron statistics every\n                        this many epochs. Default to 1.\n\n                    # Kalman Filter\n                    kalman_type (int): Kalman filter type. Default to 0.\n                    kalman_epsilon (float): General Kalman filter parameter\n                        epsilon. Default to 0.01.\n                    kalman_q0 (float): General Kalman filter parameter q0.\n                        Default to 0.01.\n                    kalman_qtau (float): General Kalman filter parameter\n                        qtau. Default to 2.302.\n                    kalman_qmin (float): General Kalman filter parameter qmin.\n                        Default to 1e-6.\n                    kalman_eta (float): Standard Kalman filter parameter eta.\n                        Default to 0.01.\n                    kalman_etatau (float): Standard Kalman filter parameter\n                        etatau. Defaul to 2.302.\n                    kalman_etamax (float): Standard Kalman filter parameter\n                        etamax. Default to 1.0.\n\n                Symmetry functions:\n                    r_cut (float): Cutoff distance (unit: Å).\n                    r_etas (numpy.array): η in radial function.\n                    r_shift (numpy.array): Rs in radial function.\n                    a_etas (numpy.array): η in angular function.\n                    zetas (numpy.array): ζ in angular function.\n                    lambdas (numpy.array): λ in angular function. Default to (1, -1).\n        \"\"\"\n        filename = 'input.nn'\n\n        head_formatter = '{:<32s}{value}'\n        type2_format = 'symfunction_short {central_atom}  2 {neighbor_atom}' \\\n                       '    {r_eta:.7f}    {rs:.7f}    {rcut:.7f}'\n        type3_format = 'symfunction_short {central_atom}  3 {neighbor_atom1} ' \\\n                       '{neighbor_atom2}    {a_eta:.7f} {lambd:>2d} {zeta:.7f}   '\\\n                       '{rcut:.7f}'\n\n        specie = self.specie.name\n        lines = [head_formatter.format('number_of_elements', value=1),\n                 head_formatter.format('elements', value=specie)]\n\n        PARAMS = {'general': ['cutoff_type', 'scale_features', 'scale_min_short',\n                              'scale_max_short', 'hidden_layers'],\n                  'additional': ['epochs', 'updater_type', 'parallel_mode',\n                                 'update_strategy', 'selection_mode', 'random_seed',\n                                 'test_fraction', 'force_weight', 'short_energy_fraction',\n                                 'short_force_fraction', 'short_energy_error_threshold',\n                                 'short_force_error_threshold', 'rmse_threshold_trials',\n                                 'weights_min', 'weights_max', 'write_trainpoints',\n                                 'write_trainforces', 'write_weights_epoch',\n                                 'write_neuronstats', 'kalman_type', 'kalman_epsilon',\n                                 'kalman_q0', 'kalman_qtau', 'kalman_qmin', 'kalman_eta',\n                                 'kalman_etatau', 'kalman_etamax']}\n        if self.fitted:\n            if self.param.get('atom_energy'):\n                lines.append(head_formatter.format('atom_energy',\n                                value=' '.join([specie, str(self.param.get('atom_energy'))])))\n            for tag in PARAMS.get('general'):\n                if tag == 'scale_features':\n                    lines.append(NNinput_params.get('general').get(tag).get(self.param.get(tag)))\n                elif tag == 'hidden_layers':\n                    layers = self.param.get('hidden_layers')\n                    activations = self.param.get('activations')\n                    lines.append(head_formatter.format('global_hidden_layers_short',\n                                                       value=len(layers)))\n                    lines.append(head_formatter.format('global_nodes_short',\n                                                       value=' '.join([str(i) for i in layers])))\n                    lines.append(head_formatter.format('global_activation_short',\n                                                       value=' '.join([activations] \\\n                                                        * len(layers) + ['l'])))\n                else:\n                    lines.append(head_formatter.format(tag, value=self.param.get(tag)))\n            if self.normalized_nodes:\n                lines.append('normalize_nodes')\n\n            for tag in PARAMS.get('additional'):\n                lines.append(head_formatter.format(tag, value=self.param.get(tag)))\n            lines.append('use_short_forces')\n\n            central_atom, neighbor_atom1, neighbor_atom2 = specie, specie, specie\n\n            r_cut = self.param.get('r_cut')\n            r_cut /= self.bohr_to_angstrom\n            r_shift = np.array(self.param.get('r_shift'))\n            r_shift /= self.bohr_to_angstrom\n\n            for r_eta, rs in itertools.product(self.param.get('r_etas'), r_shift):\n                lines.append(type2_format.format(central_atom=central_atom,\n                                                 neighbor_atom=neighbor_atom1,\n                                                 r_eta=r_eta, rs=rs, rcut=r_cut))\n\n            for a_eta, lambd, zeta in itertools.product(self.param.get('a_etas'),\n                                                        self.param.get('lambdas'), \\\n                                                        self.param.get('zetas')):\n                lines.append(type3_format.format(central_atom=central_atom,\n                                                 neighbor_atom1=neighbor_atom1,\n                                                 neighbor_atom2=neighbor_atom2,\n                                                 a_eta=a_eta, lambd=lambd,\n                                                 zeta=zeta, rcut=r_cut))\n        else:\n            if kwargs.get('atom_energy'):\n                lines.append(head_formatter.format('atom_energy',\n                                value=' '.join([specie, str(kwargs.get('atom_energy'))])))\n                self.param.update({'atom_energy': kwargs.get('atom_energy')})\n            for tag in PARAMS.get('general'):\n                if tag == 'scale_features':\n                    value = kwargs.get(tag) if kwargs.get(tag) is not None else '1'\n                    lines.append(NNinput_params.get('general').get(tag).get(value))\n                    self.param.update({tag: value})\n                elif tag == 'hidden_layers':\n                    layers = kwargs.get(tag) if kwargs.get(tag) is not None \\\n                            else NNinput_params.get('general').get(tag)\n                    self.param.update({tag: layers})\n                    activations = kwargs.get('activations') if kwargs.get('activations') \\\n                            is not None else NNinput_params.get('general').get('activations')\n                    self.param.update({'activations': activations})\n                    lines.append(head_formatter.format('global_hidden_layers_short',\n                                                       value=len(layers)))\n                    lines.append(head_formatter.format('global_nodes_short',\n                                                       value=' '.join([str(i) for i in layers])))\n                    lines.append(head_formatter.format('global_activation_short',\n                                                       value=' '.join([activations] * len(layers) \\\n                                                                      + ['l'])))\n                else:\n                    value = kwargs.get(tag) if kwargs.get(tag) is not None \\\n                                else NNinput_params.get('general').get(tag)\n                    lines.append(head_formatter.format(tag, value=value))\n                    self.param.update({tag: value})\n            if kwargs.get('normalize_nodes'):\n                lines.append('normalize_nodes')\n                self.param.update({'normalize_nodes': True})\n\n            for tag in PARAMS.get('additional'):\n                value = kwargs.get(tag) if kwargs.get(tag) is not None \\\n                            else NNinput_params.get('additional').get(tag)\n                lines.append(head_formatter.format(tag, value=value))\n                self.param.update({tag: value})\n            lines.append('use_short_forces')\n\n            central_atom, neighbor_atom1, neighbor_atom2 = specie, specie, specie\n\n            r_cut = kwargs.get('r_cut') if kwargs.get('r_cut') is not None \\\n                            else NNinput_params.get('symmetry_function').get('r_cut')\n            self.param.update({'r_cut': r_cut})\n            r_cut /= self.bohr_to_angstrom\n            r_etas = kwargs.get('r_etas') if kwargs.get('r_etas') is not None \\\n                            else NNinput_params.get('symmetry_function').get('r_etas')\n            self.param.update({'r_etas': r_etas})\n            r_shift = kwargs.get('r_shift') if kwargs.get('r_shift') is not None \\\n                            else NNinput_params.get('symmetry_function').get('r_shift')\n            self.param.update({'r_shift': r_shift})\n            r_shift = np.array(r_shift)\n            r_shift /= self.bohr_to_angstrom\n            a_etas = kwargs.get('a_etas') if kwargs.get('a_etas') is not None \\\n                            else NNinput_params.get('symmetry_function').get('a_etas')\n            self.param.update({'a_etas': a_etas})\n            zetas = kwargs.get('zetas') if kwargs.get('zetas') is not None \\\n                            else NNinput_params.get('symmetry_function').get('zetas')\n            self.param.update({'zetas': zetas})\n            lambdas= kwargs.get('lambdas') if kwargs.get('lambdas') is not None \\\n                            else NNinput_params.get('symmetry_function').get('lambdas')\n            self.param.update({'lambdas': lambdas})\n\n            for r_eta, rs in itertools.product(r_etas, r_shift):\n                lines.append(type2_format.format(central_atom=central_atom,\n                                                 neighbor_atom=neighbor_atom1,\n                                                 r_eta=r_eta, rs=rs, rcut=r_cut))\n\n            for a_eta, lambd, zeta in itertools.product(a_etas, lambdas, zetas):\n                lines.append(type3_format.format(central_atom=central_atom,\n                                                 neighbor_atom1=neighbor_atom1,\n                                                 neighbor_atom2=neighbor_atom2,\n                                                 a_eta=a_eta, lambd=lambd,\n                                                 zeta=zeta, rcut=r_cut))\n\n            self.num_symm_functions = len(list(itertools.product(r_etas, r_shift))) \\\n                                      + len(list(itertools.product(a_etas, lambdas, zetas)))\n            self.layer_sizes = [self.num_symm_functions] + self.param.get('hidden_layers')\n\n        with open(filename, 'w') as f:\n            f.write('\\n'.join(lines))\n\n        self.fitted = True\n\n        return filename\n\n    def load_input(self, filename='input.nn'):\n        \"\"\"\n        Load input file from trained Neural Network Potential.\n\n        Args:\n            filename (str): The input filename.\n        \"\"\"\n        PARAMS = {'general': ['cutoff_type', 'scale_features', 'scale_min_short',\n                              'scale_max_short', 'hidden_layers'],\n                  'additional': ['epochs', 'updater_type', 'parallel_mode',\n                                 'update_strategy', 'selection_mode', 'random_seed',\n                                 'test_fraction', 'force_weight', 'short_energy_fraction',\n                                 'short_force_fraction', 'short_energy_error_threshold',\n                                 'short_force_error_threshold', 'rmse_threshold_trials',\n                                 'weights_min', 'weights_max', 'write_trainpoints',\n                                 'write_trainforces', 'write_weights_epoch',\n                                 'write_neuronstats', 'kalman_type', 'kalman_epsilon',\n                                 'kalman_q0', 'kalman_qtau', 'kalman_qmin', 'kalman_eta',\n                                 'kalman_etatau', 'kalman_etamax']}\n        str_formatify = lambda string: float(string) if '.' in string or 'e' in string \\\n                            else int(string)\n        param = {}\n        with open(filename, 'r') as f:\n            lines = f.readlines()\n        df = pd.DataFrame([line.split() for line in lines if \"#\" not in line])\n        specie = Element(np.array(df[df[0] == 'elements'][1])[0])\n        self.specie = specie\n        self.suffix = '{:0>3d}'.format(specie.Z)\n\n        atom_energy = float(np.array(df[df[0] == 'atom_energy'][2])[0])\n        param.update({'atom_energy': atom_energy})\n        for tag in PARAMS.get('general'):\n            if tag == 'scale_features':\n                scale_features = '1' \\\n                    if len(df[df[0] == 'scale_symmetry_functions']) != 0 else 0\n                param.update({'scale_features': scale_features})\n            elif tag == 'hidden_layers':\n                hidden_layers = [int(neuron) for neuron in np.array(df[df[0] \\\n                                    == 'global_nodes_short'])[0][1:] if neuron]\n                param.update({'hidden_layers': hidden_layers})\n                activations = np.array(df[df[0] == 'global_activation_short'])[0][1]\n                param.update({'activations': activations})\n            else:\n                value = str_formatify(np.array(df[df[0] == tag])[0][1])\n                param.update({tag: value})\n        if len(df[df[0] == 'normalize_nodes']) != 0:\n            param.update({'normalize_nodes': True})\n\n        for tag in PARAMS.get('additional'):\n            value = str_formatify(np.array(df[df[0] == tag])[0][1])\n            param.update({tag: value})\n\n        r_cut = np.array(df[(df[0] == 'symfunction_short') & (df[2] == '2')][6],\n                         dtype=np.float)[0]\n        r_cut = float('{:.1f}'.format(r_cut * units.bohr_to_angstrom))\n        param.update({'r_cut': r_cut})\n        r_etas = np.array(np.unique(df[(df[0] == 'symfunction_short') & (df[2] == '2')][4]),\n                          dtype=np.float).tolist()\n        param.update({'r_etas': r_etas})\n        r_shift = np.array(np.unique(df[(df[0] == 'symfunction_short') & (df[2] == '2')][5]),\n                           dtype=np.float)\n        r_shift = [float('{:.1f}'.format(r * units.bohr_to_angstrom)) for r in r_shift]\n        param.update({'r_shift': r_shift})\n        a_etas = np.array(np.unique(df[(df[0] == 'symfunction_short') & (df[2] == '3')][5]),\n                          dtype=np.float).tolist()\n        param.update({'a_etas': a_etas})\n        lambdas = np.array(np.unique(df[(df[0] == 'symfunction_short') & (df[2] == '3')][6]),\n                           dtype=np.int).tolist()\n        param.update({'lambdas': lambdas})\n        zetas = np.array(np.unique(df[(df[0] == 'symfunction_short') & (df[2] == '3')][7]),\n                         dtype=np.float).tolist()\n        param.update({'zetas': zetas})\n        self.num_symm_functions = len(list(itertools.product(r_etas, r_shift))) \\\n                                  + len(list(itertools.product(a_etas, lambdas, zetas)))\n        self.layer_sizes = [self.num_symm_functions] + hidden_layers\n        self.param = param\n\n    def load_weights(self, weights_filename):\n        \"\"\"\n        Load weights file of trained Neural Network Potential.\n\n        Args\n            weights_filename (str): The weights file.\n        \"\"\"\n        with open(weights_filename) as f:\n            weights_lines = f.readlines()\n\n        weight_param = pd.DataFrame([line.split() for line in weights_lines \\\n                                     if \"#\" not in line])\n        weight_param.columns = ['value', 'type', 'index', 'start_layer',\n                                'start_neuron', 'end_layer', 'end_neuron']\n\n        for layer_index in range(1, len(self.layer_sizes)):\n            weights_group = weight_param[(weight_param['start_layer'] == str(layer_index - 1)) \\\n                                         & (weight_param['end_layer'] == str(layer_index))]\n\n            weights = np.reshape(np.array(weights_group['value'], dtype=np.float),\n                                 (self.layer_sizes[layer_index - 1],\n                                  self.layer_sizes[layer_index]))\n            self.weights.append(weights)\n\n            bs_group = weight_param[(weight_param['type'] == 'b') &\n                                    (weight_param['start_layer'] == str(layer_index))]\n            bs = np.array(bs_group['value'], dtype=np.float)\n            self.bs.append(bs)\n\n        self.weight_param = weight_param\n\n    def load_scaler(self, scaling_filename):\n        \"\"\"\n        Load scaling info of trained Neural Network Potential.\n\n        Args:\n            scaling_filename (str): The scaling file.\n        \"\"\"\n        with open(scaling_filename) as f:\n            scaling_lines = f.readlines()\n        scaling_param = pd.DataFrame([line.split() for line in scaling_lines \\\n                                      if '#' not in line])\n        scaling_param.column = ['e_index', 'sf_index', 'sf_min', 'sf_max', \\\n                                'sf_mean', 'sf_sigma']\n        self.scaling_param = scaling_param\n\n    def read_cfgs(self, filename='output.data'):\n        \"\"\"\n        Args:\n            filename (str): The configuration file to be read.\n        \"\"\"\n        data_pool = []\n        with zopen(filename, 'rt') as f:\n            lines = f.read()\n\n        block_pattern = re.compile('begin\\n(.*?)end', re.S)\n        lattice_pattern = re.compile('lattice(.*?)\\n')\n        position_pattern = re.compile('atom(.*?)\\n')\n        energy_pattern = re.compile('energy(.*?)\\n')\n\n        for block in block_pattern.findall(lines):\n            d = {'outputs':{}}\n            lattice_str = lattice_pattern.findall(block)\n            lattice = Lattice(np.array([latt.split() for latt in lattice_str],\n                                        dtype=np.float) * self.bohr_to_angstrom)\n            position_str = position_pattern.findall(block)\n            positions = pd.DataFrame([pos.split() for pos in position_str])\n            positions.columns = \\\n                ['x', 'y', 'z', 'specie', 'charge', 'atomic_energy', 'fx', 'fy', 'fz']\n            coords = np.array(positions.loc[:, ['x', 'y', 'z']], dtype=np.float)\n            coords = coords * self.bohr_to_angstrom\n            species = np.array(positions['specie'])\n            forces = np.array(positions.loc[:, ['fx', 'fy', 'fz']], dtype=np.float)\n            forces = forces / self.eV_to_Ha / self.bohr_to_angstrom\n            energy_str = energy_pattern.findall(block)[0]\n            energy = float(energy_str.lstrip()) / self.eV_to_Ha\n            struct = Structure(lattice=lattice, species=species, coords=coords,\n                               coords_are_cartesian=True)\n            d['structure'] = struct.as_dict()\n            d['outputs']['energy'] = energy\n            d['outputs']['forces'] = forces\n            d['num_atoms'] = len(struct)\n\n            data_pool.append(d)\n        _, df = convert_docs(docs=data_pool)\n        return data_pool, df\n\n    def write_param(self):\n        \"\"\"\n        Write optimized weights file to perform energy and force prediction.\n        \"\"\"\n        if self.weight_param is None or self.scaling_param is None:\n            raise RuntimeError(\"The parameters should be provided.\")\n        weights_filename = '.'.join(['weights', self.suffix, 'data'])\n        weight_formatter = '{:>18s}{:>2s}{:>10s}{:>6s}{:>6s}{:>6s}{:>6s}'\n        bias_formatter = '{:>18s}{:>2s}{:>10s}{:>6s}{:>6}'\n        lines = []\n        for i in range(self.weight_param.shape[0]):\n            if self.weight_param.iloc[i]['type'] == 'a':\n                lines.append(weight_formatter.format(*self.weight_param.iloc[i]))\n            else:\n                lines.append(bias_formatter.format(*self.weight_param.iloc[i]))\n\n        with open(weights_filename, 'w') as f:\n            f.writelines('\\n'.join(lines))\n\n        scaling_filename = 'scaling.data'\n        scaling_formatter = '{:>4s}{:>5s}  {:>22s} {:>22s} {:>22s} {:.>22s}'\n        scaling_lines = []\n        for i in range(self.num_symm_functions):\n            scaling_lines.append(scaling_formatter.format(*self.scaling_param.iloc[i]))\n        with open(scaling_filename, 'w') as f:\n            f.writelines('\\n'.join(scaling_lines))\n\n        self.write_input()\n\n        ff_settings = [self.pair_style, self.pair_coeff.format(self.param.get('r_cut') + 1e-2)]\n\n        return ff_settings\n\n    def train(self, train_structures, energies=None, forces=None, stresses=None,\n                                    **kwargs):\n        \"\"\"\n        Training data with moment tensor method.\n\n        Args:\n            train_structures ([Structure]): The list of Pymatgen Structure object.\n                energies ([float]): The list of total energies of each structure\n                in structures list.\n            energies ([float]): List of total energies of each structure in\n                structures list.\n            forces ([np.array]): List of (m, 3) forces array of each structure\n                with m atoms in structures list. m can be varied with each\n                single structure case.\n            stresses (list): List of (6, ) virial stresses of each\n                structure in structures list.\n            kwargs: Parameters in write_input method.\n        \"\"\"\n        if not which('nnp-train'):\n            raise RuntimeError(\"NNP Trainer has not been found.\")\n\n        train_pool = pool_from(train_structures, energies, forces, stresses)\n        atoms_filename = 'input.data'\n\n        with ScratchDir('.'):\n            atoms_filename = self.write_cfgs(filename=atoms_filename, cfg_pool=train_pool)\n            output = 'training_output'\n\n            input_filename = self.write_input(**kwargs)\n            p_scaling = subprocess.Popen(['nnp-scaling', input_filename])\n            stdout = p_scaling.communicate()[0]\n\n            p_train = subprocess.Popen(['nnp-train', input_filename],\n                                       stdout=open(output, 'w'))\n            stdout = p_train.communicate()[0]\n\n            rc = p_train.returncode\n            if rc != 0:\n                error_msg = 'RuNNer exited with return code %d' % rc\n                msg = stdout.decode(\"utf-8\").split('\\n')[:-1]\n                try:\n                    error_line = [i for i, m in enumerate(msg)\n                                  if m.startswith('ERROR')][0]\n                    error_msg += ', '.join([e for e in msg[error_line:]])\n                except:\n                    error_msg += msg[-1]\n                raise RuntimeError(error_msg)\n\n            with zopen(output) as f:\n                error_lines = f.read()\n\n            energy_rmse_pattern = re.compile('ENERGY\\s*\\S*\\s*(\\S*)\\s*(\\S*).*?\\n')\n            forces_rmse_pattern = re.compile('FORCES\\s*\\S*\\s*(\\S*)\\s*(\\S*).*?\\n')\n            self.train_energy_rmse, self.validation_energy_rmse = \\\n                    np.array([line for line in energy_rmse_pattern.findall(error_lines)],\n                             dtype=np.float).T\n            self.train_forces_rmse, self.validation_forces_rmse = \\\n                    np.array([line for line in forces_rmse_pattern.findall(error_lines)],\n                             dtype=np.float).T\n\n            weights_filename_pattern = 'weights*{}.out'.format(self.param.get('epochs'))\n            weights_filename = glob.glob(weights_filename_pattern)[0]\n\n            self.suffix = weights_filename.split('.')[1]\n\n            self.load_weights(weights_filename)\n            self.load_scaler('scaling.data')\n\n        return rc\n\n    def evaluate(self, test_structures, ref_energies, ref_forces, ref_stresses):\n        \"\"\"\n        Evaluate energies, forces and stresses of structures with trained\n        interatomic potentials.\n\n        Args:\n            test_structures ([Structure]): List of Pymatgen Structure Objects.\n            ref_energies ([float]): List of DFT-calculated total energies of\n                each structure in structures list.\n            ref_forces ([np.array]): List of DFT-calculated (m, 3) forces of\n                each structure with m atoms in structures list. m can be varied\n                with each single structure case.\n            ref_stresses (list): List of DFT-calculated (6, ) viriral stresses\n                of each structure in structures list.\n        \"\"\"\n        if not which('nnp-predict'):\n            raise RuntimeError(\"NNP Predictor has not been found.\")\n\n        original_file = 'input.data'\n        predict_file = 'output.data'\n\n        predict_pool = pool_from(test_structures, ref_energies,\n                                 ref_forces, ref_stresses)\n        with ScratchDir('.'):\n            _, _ = self.write_param()\n            original_file = self.write_cfgs(original_file, cfg_pool=predict_pool)\n            _, df_orig = self.read_cfgs(original_file)\n\n            input_filename = self.write_input()\n\n            dfs = []\n            for data in predict_pool:\n                _ = self.write_cfgs(original_file, cfg_pool=[data])\n                p = subprocess.Popen(['nnp-predict', input_filename], stdout=subprocess.PIPE)\n                stdout = p.communicate()[0]\n\n                rc = p.returncode\n                if rc != 0:\n                    error_msg = 'RuNNer exited with return code %d' % rc\n                    msg = stdout.decode(\"utf-8\").split('\\n')[:-1]\n                    try:\n                        error_line = [i for i, m in enumerate(msg)\n                                      if m.startswith('ERROR')][0]\n                        error_msg += ', '.join([e for e in msg[error_line:]])\n                    except:\n                        error_msg += msg[-1]\n                    raise RuntimeError(error_msg)\n\n                _, df = self.read_cfgs(predict_file)\n                dfs.append(df)\n            df_predict = pd.concat(dfs, ignore_index=True)\n\n        return df_orig, df_predict\n\n    def predict(self, structure):\n        \"\"\"\n        Predict energy, forces and stresses of the structure.\n\n        Args:\n            structure (Structure): Pymatgen Structure object.\n\n        Returns:\n            energy, forces, stress\n        \"\"\"\n        calculator = EnergyForceStress(self)\n        energy, forces, stress = calculator.calculate(structures=[structure])[0]\n        return energy, forces, stress\n\n    @staticmethod\n    def from_config(input_filename, scaling_filename, weights_filename):\n        \"\"\"\n        Initialize potentials with parameters file.\n\n        Args:\n            input_filename (str): The file storing the input configuration of\n                Neural Network Potential.\n            scaling_filename (str): The file storing scaling info of\n                Neural Network Potential.\n            weights_filename (str): The file storing weights of\n                Neural Network Potential.\n        \"\"\"\n        nnp = NNPotential()\n        nnp.load_input(input_filename)\n        nnp.load_scaler(scaling_filename)\n        nnp.load_weights(weights_filename)\n        nnp.fitted = True\n\n        return nnp", "meta": {"hexsha": "37e2e13c039eaf615b1db56e6b0fcc77d6650308", "size": 35375, "ext": "py", "lang": "Python", "max_stars_repo_path": "mlearn/potentials/nnp.py", "max_stars_repo_name": "ruoitrau86/mlearn", "max_stars_repo_head_hexsha": "5b24690344836f53047ede409966d5dd3859098f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-05T05:11:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-05T05:11:56.000Z", "max_issues_repo_path": "mlearn/potentials/nnp.py", "max_issues_repo_name": "ruoitrau86/mlearn", "max_issues_repo_head_hexsha": "5b24690344836f53047ede409966d5dd3859098f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mlearn/potentials/nnp.py", "max_forks_repo_name": "ruoitrau86/mlearn", "max_forks_repo_head_hexsha": "5b24690344836f53047ede409966d5dd3859098f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.592032967, "max_line_length": 100, "alphanum_fraction": 0.534869258, "include": true, "reason": "import numpy", "num_tokens": 7266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.3486451285660856, "lm_q1q2_score": 0.1946579918464927}}
{"text": "\"\"\"\nThis module contains the main class that describes an isotherm through discrete points.\n\"\"\"\n\nimport textwrap\nimport typing as t\n\nimport numpy\nimport pandas\n\nfrom pygaps import logger\nfrom pygaps.core.baseisotherm import BaseIsotherm\nfrom pygaps.units.converter_mode import c_loading\nfrom pygaps.units.converter_mode import c_material\nfrom pygaps.units.converter_mode import c_pressure\nfrom pygaps.utilities.exceptions import CalculationError\nfrom pygaps.utilities.exceptions import ParameterError\nfrom pygaps.utilities.isotherm_interpolator import IsothermInterpolator\n\n\nclass PointIsotherm(BaseIsotherm):\n    \"\"\"\n    Class which contains the points from an adsorption isotherm.\n\n    This class is designed to be a complete description of a discrete isotherm.\n    It extends the BaseIsotherm class, which contains all the description of the\n    isotherm parameters, but also holds the datapoints recorded during an\n    experiment or simulation.\n\n    The minimum arguments required to instantiate the class, besides those\n    required for the parent BaseIsotherm, is the actual data, specified either\n    as `pressure` + `loading` arrays or as `isotherm_data` (a\n    `pandas.DataFrame`) + keys for the columns of the dataframe which have the\n    loading and the pressure data.\n\n    Parameters\n    ----------\n    pressure : list\n        Create an isotherm directly from an array. Values for pressure.\n        If the ``isotherm_data`` dataframe is specified, these values are ignored.\n    loading : list\n        Create an isotherm directly from an array. Values for loading.\n        If the ``isotherm_data`` dataframe is specified, these values are ignored.\n    isotherm_data : `pandas.DataFrame`\n        Pure-component adsorption isotherm data.\n    pressure_key : str\n        The title of the pressure data in the DataFrame provided.\n    loading_key : str\n        The title of the loading data in the DataFrame provided.\n    branch : ['guess', ads', 'des', iterable], optional\n        The branch of the isotherm. The code will automatically attempt to\n        guess if there's an adsorption and desorption branch.\n        The user can instead tell the framework that all points are\n        part of an adsorption ('ads') or desorption ('des') curve.\n        Alternatively, an iterable can be passed which contains\n        detailed info for each data point if adsorption points ('False')\n        or desorption points ('True'). eg: [False, False, True, True...]\n        or as a column of the isotherm_data.\n    material : str\n        Name of the material on which the isotherm is measured.\n    adsorbate : str\n        Isotherm adsorbate.\n    temperature : float\n        Isotherm temperature.\n\n    Other Parameters\n    ----------------\n    pressure_mode : str, optional\n        The pressure mode, either 'absolute' pressure or 'relative'\n        ('relative%') in the form of p/p0.\n    pressure_unit : str, optional\n        Unit of pressure, if applicable.\n    loading_basis : str, optional\n        Whether the adsorbed amount is in terms of either 'volume_gas'\n        'volume_liquid', 'molar', 'mass', or a fractional/percent basis.\n    loading_unit : str, optional\n        Unit in which the loading basis is expressed.\n    material_basis : str, optional\n        Whether the underlying material is in terms of 'per volume'\n        'per molar amount' or 'per mass' of material.\n    material_unit : str, optional\n        Unit in which the material basis is expressed.\n\n    Notes\n    -----\n    This class assumes that the datapoints do not contain noise.\n    Detection of adsorption/desorption branches will not work if\n    data is noisy.\n\n    \"\"\"\n\n    _reserved_params = BaseIsotherm._reserved_params + [\n        'data_raw',\n        'l_interpolator',\n        'p_interpolator',\n        'loading_key',\n        'pressure_key',\n        'other_keys',\n    ]\n\n    ##########################################################\n    #   Instantiation and classmethods\n\n    def __init__(\n        self,\n        pressure: t.List[float] = None,\n        loading: t.List[float] = None,\n        isotherm_data: pandas.DataFrame = None,\n        pressure_key: str = None,\n        loading_key: str = None,\n        branch: t.Union[str, t.List[bool]] = 'guess',\n        **other_properties\n    ):\n        \"\"\"\n        Instantiation is done by passing the discrete data as a pandas\n        DataFrame, the column keys as string as well as the parameters\n        required by parent class.\n        \"\"\"\n        # Run base class constructor\n        super().__init__(**other_properties)\n\n        # Checks\n        if isotherm_data is not None:\n            if None in [pressure_key, loading_key]:\n                raise ParameterError(\n                    \"Pass loading_key and pressure_key, the names of the loading and\"\n                    \" pressure columns in the DataFrame, to the constructor.\"\n                )\n\n            # Save column names\n            # Name of column in the dataframe that contains adsorbed amount.\n            self.loading_key = loading_key\n\n            # Name of column in the dataframe that contains pressure.\n            self.pressure_key = pressure_key\n\n            # Pandas DataFrame that stores the data.\n            columns = [self.pressure_key, self.loading_key]\n            if not all(a in isotherm_data.columns for a in columns):\n                raise ParameterError(\n                    \"Could not find columns \"\n                    f\"({[a for a in columns if a not in isotherm_data.columns]})\"\n                    \" in the adsorption DataFrame.\"\n                )\n            if 'branch' not in isotherm_data.columns:\n                columns.append('branch')\n            other_keys = [c for c in isotherm_data.columns if c not in columns]\n            columns = columns + sorted(other_keys)\n            self.data_raw = isotherm_data.reindex(columns=columns)\n\n        elif pressure is not None or loading is not None:\n            if pressure is None or loading is None:\n                raise ParameterError(\n                    \"If you've chosen to pass loading and pressure directly as\"\n                    \" arrays, make sure both are specified!\"\n                )\n            if len(pressure) != len(loading):\n                raise ParameterError(\"Pressure and loading arrays are not equal!\")\n\n            # Standard column names\n            self.pressure_key = 'pressure'\n            self.loading_key = 'loading'\n\n            # DataFrame creation\n            self.data_raw = pandas.DataFrame({\n                self.pressure_key: pressure,\n                self.loading_key: loading\n            })\n        else:\n            raise ParameterError(\n                \"Pass either the isotherm data in a pandas.DataFrame as ``isotherm_data``\"\n                \" or directly ``pressure`` and ``loading`` as arrays.\"\n            )\n\n        # Deal with the isotherm branches\n        if isotherm_data is not None and 'branch' in isotherm_data.columns:\n            pass\n        elif isinstance(branch, str):\n            if branch == 'guess':\n                # Split the data in adsorption/desorption\n                self.data_raw['branch'] = self._splitdata(self.data_raw, self.pressure_key)\n            elif branch == 'ads':\n                self.data_raw['branch'] = 0\n            elif branch == 'des':\n                self.data_raw['branch'] = 1\n            else:\n                raise ParameterError(\n                    \"Isotherm branch parameter must be 'guess ,'ads' or 'des'\"\n                    \" or an array of booleans.\"\n                )\n        else:\n            try:\n                self.data_raw['branch'] = branch\n            except Exception as e_info:\n                raise ParameterError(e_info)\n\n        # The internal interpolator for loading given pressure.\n        self.l_interpolator = None\n\n        # The internal interpolator for pressure given loading.\n        self.p_interpolator = None\n\n    @classmethod\n    def from_isotherm(\n        cls,\n        isotherm: BaseIsotherm,\n        pressure: t.List[float] = None,\n        loading: t.List[float] = None,\n        isotherm_data: pandas.DataFrame = None,\n        pressure_key: str = None,\n        loading_key: str = None,\n    ):\n        \"\"\"\n        Construct a point isotherm using a parent isotherm as the template for\n        all the parameters.\n\n        Parameters\n        ----------\n        isotherm : Isotherm\n            An instance of the Isotherm parent class.\n        pressure : list\n            Create an isotherm directly from an array. Values for pressure.\n            If the ``isotherm_data`` dataframe is specified, these values are ignored.\n        loading : list\n            Create an isotherm directly from an array. Values for loading.\n            If the ``isotherm_data`` dataframe is specified, these values are ignored.\n        isotherm_data : pandas.DataFrame\n            Pure-component adsorption isotherm data.\n        loading_key : str\n            Column of the pandas DataFrame where the loading is stored.\n        pressure_key : str\n            Column of the pandas DataFrame where the pressure is stored.\n        \"\"\"\n        # get isotherm parameters as a dictionary\n        iso_params = isotherm.to_dict()\n        # add pointisotherm values to dict\n        iso_params['pressure'] = pressure\n        iso_params['loading'] = loading\n        iso_params['isotherm_data'] = isotherm_data\n        iso_params['pressure_key'] = pressure_key\n        iso_params['loading_key'] = loading_key\n\n        return cls(**iso_params)\n\n    @classmethod\n    def from_modelisotherm(\n        cls,\n        modelisotherm,\n        pressure_points: t.List[float] = None,\n        loading_points: t.List[float] = None,\n    ):\n        \"\"\"\n        Construct a PointIsotherm from a ModelIsothem class.\n\n        This class method allows for the model to be converted into\n        a list of points calculated by using the model in the isotherm.\n\n        Parameters\n        ----------\n        modelisotherm : ModelIsotherm\n            The isotherm containing the model.\n        pressure_points : None or List or PointIsotherm\n            How the pressure points should be chosen for the resulting PointIsotherm.\n\n            - If ``None``, the PointIsotherm returned has a fixed number of\n              equidistant points\n            - If an array, the PointIsotherm returned has points at each of the\n              values of the array\n            - If a PointIsotherm is passed, the values will be calculated at\n              each of the pressure points in the passed isotherm. This is useful\n              for comparing a model overlap with the real isotherm.\n        \"\"\"\n        if pressure_points is not None and loading_points is not None:\n            raise ParameterError(\"\"\"Cannot specify both pressure and loading points.\"\"\")\n\n        pressure = None\n        loading = None\n        if modelisotherm.model.calculates == \"loading\":\n            # The user may request loading even if the model calculates pressure\n            if loading_points is None:\n                if pressure_points is None:\n                    pressure = modelisotherm.pressure()\n                elif isinstance(pressure_points, PointIsotherm):\n                    pressure = pressure_points.pressure(branch=modelisotherm.branch)\n                else:\n                    pressure = pressure_points\n                loading = modelisotherm.loading_at(pressure)\n            else:\n                loading = loading_points\n                pressure = modelisotherm.pressure_at(loading_points)\n        elif modelisotherm.model.calculates == \"pressure\":\n            # The user may request pressure even if the model calculates loading\n            if pressure_points is None:\n                if loading_points is None:\n                    loading = modelisotherm.loading()\n                elif isinstance(loading_points, PointIsotherm):\n                    loading = loading_points.loading(branch=modelisotherm.branch)\n                else:\n                    loading = loading_points\n                pressure = modelisotherm.pressure_at(loading)\n            else:\n                pressure = pressure_points\n                loading = modelisotherm.loading_at(pressure)\n\n        return PointIsotherm(\n            pressure=pressure,\n            loading=loading,\n            model_from=modelisotherm.model.name,\n            **modelisotherm.to_dict()\n        )\n\n    ##########################################################\n    #   Conversion functions\n\n    def convert(\n        self,\n        pressure_mode: str = None,\n        pressure_unit: str = None,\n        loading_basis: str = None,\n        loading_unit: str = None,\n        material_basis: str = None,\n        material_unit: str = None,\n        verbose: bool = False,\n    ):\n        \"\"\"\n        Convenience function for permanently converting any isotherm\n        mode/basis/units.\n\n        Parameters\n        ----------\n        pressure_mode : {'absolute', 'relative', 'relative%'}\n            The mode in which the isotherm should be converted.\n        pressure_unit : str\n            The unit into which the internal pressure should be converted to.\n            Only makes sense if converting to absolute pressure.\n        loading_basis : {'mass', 'molar', 'volume_gas', 'volume_liquid', 'percent', 'fraction'}\n            The basis in which the isotherm should be converted.\n        loading_unit : str\n            The unit into which the internal loading should be converted to.\n        material_basis : {'mass', 'molar', 'volume'}\n            The basis in which the isotherm should be converted.\n        material_unit : str\n            The unit into which the material should be converted to.\n        verbose : bool\n            Print out steps taken.\n\n        \"\"\"\n        if pressure_mode or pressure_unit:\n            self.convert_pressure(\n                mode_to=pressure_mode,\n                unit_to=pressure_unit,\n                verbose=verbose,\n            )\n\n        if material_basis or material_unit:\n            self.convert_material(\n                basis_to=material_basis,\n                unit_to=material_unit,\n                verbose=verbose,\n            )\n\n        if loading_basis or loading_unit:\n            self.convert_loading(\n                basis_to=loading_basis,\n                unit_to=loading_unit,\n                verbose=verbose,\n            )\n\n    def convert_pressure(\n        self,\n        mode_to: str = None,\n        unit_to: str = None,\n        verbose: bool = False,\n    ):\n        \"\"\"\n        Convert isotherm pressure from one unit to another\n        and the pressure mode from absolute to relative.\n\n        Only applicable in the case of isotherms taken below critical\n        point of adsorbate.\n\n        Parameters\n        ----------\n        mode_to : {'absolute', 'relative', 'relative%'}\n            The mode in which the isotherm should be converted.\n        unit_to : str\n            The unit into which the internal pressure should be converted to.\n            Only makes sense if converting to absolute pressure.\n        verbose : bool\n            Print out steps taken.\n\n        \"\"\"\n        if not mode_to:\n            mode_to = self.pressure_mode\n\n        if mode_to == self.pressure_mode and unit_to == self.pressure_unit:\n            if verbose:\n                logger.info(\"Mode and units are the same, no changes made.\")\n            return\n\n        self.data_raw[self.pressure_key] = c_pressure(\n            self.data_raw[self.pressure_key],\n            mode_from=self.pressure_mode,\n            mode_to=mode_to,\n            unit_from=self.pressure_unit,\n            unit_to=unit_to,\n            adsorbate=self.adsorbate,\n            temp=self.temperature\n        )\n\n        if mode_to != self.pressure_mode:\n            self.pressure_mode = mode_to\n        if unit_to != self.pressure_unit and mode_to == 'absolute':\n            self.pressure_unit = unit_to\n        else:\n            self.pressure_unit = None\n\n        # Reset interpolators\n        self.l_interpolator = None\n        self.p_interpolator = None\n\n        if verbose:\n            logger.info(f\"Changed pressure to mode '{mode_to}', unit '{unit_to}'.\")\n\n    def convert_loading(\n        self,\n        basis_to: str = None,\n        unit_to: str = None,\n        verbose: bool = False,\n    ):\n        \"\"\"\n        Convert isotherm loading from one unit to another\n        and the basis of the isotherm loading to be\n        either 'mass', 'molar' or 'percent'/'fraction'.\n\n        Parameters\n        ----------\n        basis_to : {'mass', 'molar', 'volume_gas', 'volume_liquid', 'percent', 'fraction'}\n            The basis in which the isotherm should be converted.\n        unit_to : str\n            The unit into which the internal loading should be converted to.\n        verbose : bool\n            Print out steps taken.\n\n        \"\"\"\n        if not basis_to:\n            basis_to = self.loading_basis\n\n        if basis_to == self.loading_basis and unit_to == self.loading_unit:\n            if verbose:\n                logger.info(\"Basis and units are the same, no changes made.\")\n            return\n\n        if self.loading_basis in ['percent', 'fraction']:\n            # TODO this is\n            if basis_to == self.loading_basis and unit_to != self.loading_unit:\n                if verbose:\n                    logger.info(\"There are no loading units in this mode.\")\n                return\n\n        self.data_raw[self.loading_key] = c_loading(\n            self.data_raw[self.loading_key],\n            basis_from=self.loading_basis,\n            basis_to=basis_to,\n            unit_from=self.loading_unit,\n            unit_to=unit_to,\n            adsorbate=self.adsorbate,\n            temp=self.temperature,\n            basis_material=self.material_basis,\n            unit_material=self.material_unit,\n        )\n\n        if basis_to != self.loading_basis:\n            self.loading_basis = basis_to\n        if basis_to in ['percent', 'fraction']:\n            self.loading_unit = None\n        else:\n            self.loading_unit = unit_to\n\n        # Reset interpolators\n        self.l_interpolator = None\n        self.p_interpolator = None\n\n        if verbose:\n            logger.info(f\"Changed loading to basis '{basis_to}', unit '{unit_to}'.\")\n\n    def convert_material(\n        self,\n        basis_to: str = None,\n        unit_to: str = None,\n        verbose: bool = False,\n    ):\n        \"\"\"\n        Convert the material of the isotherm from one unit to another and the\n        basis of the isotherm loading to be either 'per mass' or 'per volume' or\n        'per mole' of material.\n\n        Only applicable to materials that have been loaded in memory with a\n        'density' or 'molar mass' property respectively.\n\n        Parameters\n        ----------\n        basis : {'mass', 'molar', 'volume'}\n            The basis in which the isotherm should be converted.\n        unit_to : str\n            The unit into which the material should be converted to.\n        verbose : bool\n            Print out steps taken.\n\n        \"\"\"\n        if not basis_to:\n            basis_to = self.material_basis\n\n        if basis_to == self.material_basis and unit_to == self.material_unit:\n            if verbose:\n                logger.info(\"Basis and units are the same, no changes made.\")\n            return\n\n        if (\n            self.loading_basis in ['percent', 'fraction'] and basis_to == self.material_basis\n            and unit_to != self.material_unit\n        ):\n            # We \"virtually\" change the unit without any conversion\n            self.material_unit = unit_to\n            if verbose:\n                logger.info(\"There are no material units in this mode.\")\n            return\n\n        self.data_raw[self.loading_key] = c_material(\n            self.data_raw[self.loading_key],\n            basis_from=self.material_basis,\n            basis_to=basis_to,\n            unit_from=self.material_unit,\n            unit_to=unit_to,\n            material=self.material\n        )\n\n        # A special case is when conversion is performed from\n        # a \"fractional\" basis to another \"fractional\" basis.\n        # Here, the loading must be simultaneously converted.\n        # e.g.: wt% = g/g -> cm3/cm3 = vol%\n        if self.loading_basis in ['percent', 'fraction']:\n            if basis_to == 'volume':\n                _basis_to = 'volume_liquid'\n            else:\n                _basis_to = basis_to\n            if self.material_basis == 'volume':\n                _basis_from = 'volume_liquid'\n            else:\n                _basis_from = self.material_basis\n            self.data_raw[self.loading_key] = c_loading(\n                self.data_raw[self.loading_key],\n                basis_from=_basis_from,\n                basis_to=_basis_to,\n                unit_from=self.material_unit,\n                unit_to=unit_to,\n                adsorbate=self.adsorbate,\n                temp=self.temperature,\n            )\n            if verbose:\n                logger.info(f\"Changed loading to basis '{basis_to}', unit '{unit_to}'.\")\n\n        if unit_to != self.material_unit:\n            self.material_unit = unit_to\n        if basis_to != self.material_basis:\n            self.material_basis = basis_to\n\n        # Reset interpolators\n        self.l_interpolator = None\n        self.p_interpolator = None\n\n        if verbose:\n            logger.info(f\"Changed material to basis '{basis_to}', unit '{unit_to}'.\")\n\n    ###########################################################\n    #   Info functions\n\n    def print_info(self, **plot_iso_args):\n        \"\"\"\n        Print a short summary of all the isotherm parameters and a graph.\n\n        Parameters\n        ----------\n        show : bool, optional\n            Specifies if the graph is shown automatically or not.\n\n        Other Parameters\n        ----------------\n        plot_iso_args : dict\n            options to be passed to pygaps.plot_iso()\n\n        Returns\n        -------\n        axes : matplotlib.axes.Axes or numpy.ndarray of them\n\n        \"\"\"\n        print(self)\n        return self.plot(**plot_iso_args)\n\n    def plot(self, **plot_iso_args):\n        \"\"\"\n        Plot the isotherm using pygaps.plot_iso().\n\n        Parameters\n        ----------\n        show : bool, optional\n            Specifies if the graph is shown automatically or not.\n\n        Other Parameters\n        ----------------\n        plot_iso_args : dict\n            options to be passed to pygaps.plot_iso()\n\n        Returns\n        -------\n        axes : matplotlib.axes.Axes or numpy.ndarray of them\n\n        \"\"\"\n        plot_dict = dict(\n            y2_data=self.other_keys[0] if self.other_keys else None,\n            material_basis=self.material_basis,\n            material_unit=self.material_unit,\n            loading_basis=self.loading_basis,\n            loading_unit=self.loading_unit,\n            pressure_unit=self.pressure_unit,\n            pressure_mode=self.pressure_mode,\n        )\n        plot_dict.update(plot_iso_args)\n\n        from pygaps.graphing.isotherm_graphs import plot_iso\n        return plot_iso(self, **plot_dict)\n\n    ##########################################################\n    #   Functions that return part of the isotherm data\n\n    def data(self, branch: str = None) -> pandas.DataFrame:\n        \"\"\"\n        Return underlying isotherm data.\n\n        Parameters\n        ----------\n        branch : {None, 'ads', 'des'}\n            The branch of the isotherm to return. If ``None``, returns entire\n            dataset.\n\n        Returns\n        -------\n        DataFrame\n            The pandas DataFrame containing all isotherm data.\n\n        \"\"\"\n        if branch is None or branch.startswith('all'):\n            return self.data_raw\n        if branch == 'ads':\n            return self.data_raw.loc[self.data_raw['branch'] == 0]\n        if branch == 'des':\n            return self.data_raw.loc[self.data_raw['branch'] == 1]\n        raise ParameterError('Bad branch specification.')\n\n    def pressure(\n        self,\n        branch: str = None,\n        pressure_unit: str = None,\n        pressure_mode: str = None,\n        limits: t.Tuple[float, float] = None,\n        indexed: bool = False,\n    ) -> t.Union[numpy.ndarray, pandas.Series]:\n        \"\"\"\n        Return pressure points as an array.\n\n        Parameters\n        ----------\n        branch : {None, 'ads', 'des'}\n            The branch of the pressure to return. If ``None``, returns entire\n            dataset.\n        pressure_unit : str, optional\n            Unit in which the pressure should be returned. If ``None``\n            it defaults to which pressure unit the isotherm is currently in.\n        pressure_mode : {None, 'absolute', 'relative', 'relative%'}\n            The mode in which to return the pressure, if possible. If ``None``,\n            returns mode the isotherm is currently in.\n        limits : [float, float], optional\n            Minimum and maximum pressure limits.\n            Put None or -+np.inf for no limit.\n        indexed : bool, optional\n            If this is specified to true, then the function returns an indexed\n            pandas.Series instead of an array.\n\n        Returns\n        -------\n        array or Series\n            The pressure slice corresponding to the parameters passed.\n\n        \"\"\"\n        ret = self.data(branch=branch).loc[:, self.pressure_key]\n\n        if not ret.empty:\n            # Convert if needed\n            if pressure_mode or pressure_unit:\n                # If pressure mode not given, try current\n                if not pressure_mode:\n                    pressure_mode = self.pressure_mode\n                # If pressure unit not given, try current\n                if not pressure_unit:\n                    pressure_unit = self.pressure_unit\n\n                ret = c_pressure(\n                    ret,\n                    mode_from=self.pressure_mode,\n                    mode_to=pressure_mode,\n                    unit_from=self.pressure_unit,\n                    unit_to=pressure_unit,\n                    adsorbate=self.adsorbate,\n                    temp=self.temperature\n                )\n\n            # Select required points\n            if limits and any(limits):\n                ret = ret.loc[ret.between(\n                    -numpy.inf if limits[0] is None else limits[0],\n                    numpy.inf if limits[1] is None else limits[1]\n                )]\n\n        if indexed:\n            return ret\n        return ret.values\n\n    def loading(\n        self,\n        branch: str = None,\n        loading_unit: str = None,\n        loading_basis: str = None,\n        material_unit: str = None,\n        material_basis: str = None,\n        limits: t.Tuple[float, float] = None,\n        indexed: bool = False\n    ) -> t.Union[numpy.ndarray, pandas.Series]:\n        \"\"\"\n        Return loading points as an array.\n\n        Parameters\n        ----------\n        branch : {None, 'ads', 'des'}\n            The branch of the loading to return. If ``None``, returns entire\n            dataset.\n        loading_unit : str, optional\n            Unit in which the loading should be returned. If ``None``\n            it defaults to which loading unit the isotherm is currently in.\n        loading_basis : {None, 'mass', 'volume_gas', 'volume_liquid', 'molar'}\n            The basis on which to return the loading, if possible. If ``None``,\n            returns on the basis the isotherm is currently in.\n        material_unit : str, optional\n            Unit in which the material should be returned. If ``None``\n            it defaults to which loading unit the isotherm is currently in.\n        material_basis : {None, 'mass', 'volume', 'molar'}\n            The basis on which to return the material, if possible. If ``None``,\n            returns on the basis the isotherm is currently in.\n        limits : [float, float], optional\n            Minimum and maximum loading limits.\n            Put None or -+np.inf for no limit.\n        indexed : bool, optional\n            If this is specified to true, then the function returns an indexed\n            pandas.Series instead of an array.\n\n        Returns\n        -------\n        Array or Series\n            The loading slice corresponding to the parameters passed.\n\n        \"\"\"\n        ret = self.data(branch=branch).loc[:, self.loading_key]\n\n        if not ret.empty:\n            # Convert if needed\n\n            # First adsorbent is converted\n            if material_basis or material_unit:\n                if not material_basis:\n                    material_basis = self.material_basis\n\n                ret = c_material(\n                    ret,\n                    basis_from=self.material_basis,\n                    basis_to=material_basis,\n                    unit_from=self.material_unit,\n                    unit_to=material_unit,\n                    material=self.material\n                )\n\n            # Then loading\n            if loading_basis or loading_unit:\n                if not loading_basis:\n                    loading_basis = self.loading_basis\n\n                # These must be specified\n                # in the case of fractional conversions\n                if not material_basis:\n                    material_basis = self.material_basis\n                if not material_unit:\n                    material_unit = self.material_unit\n\n                ret = c_loading(\n                    ret,\n                    basis_from=self.loading_basis,\n                    basis_to=loading_basis,\n                    unit_from=self.loading_unit,\n                    unit_to=loading_unit,\n                    adsorbate=self.adsorbate,\n                    temp=self.temperature,\n                    basis_material=material_basis,\n                    unit_material=material_unit,\n                )\n\n            # Select required points\n            if limits and any(limits):\n                ret = ret.loc[ret.between(\n                    -numpy.inf if limits[0] is None else limits[0],\n                    numpy.inf if limits[1] is None else limits[1]\n                )]\n\n        if indexed:\n            return ret\n        return ret.values\n\n    @property\n    def other_keys(self):\n        \"\"\"\n        Return column names of any supplementary data points.\n        \"\"\"\n        return [\n            c for c in self.data_raw.columns\n            if c not in (self.pressure_key, self.loading_key, 'branch')\n        ]\n\n    def other_data(\n        self,\n        key: str,\n        branch: str = None,\n        limits: t.Tuple[float, float] = None,\n        indexed: bool = False,\n    ) -> t.Union[numpy.ndarray, pandas.Series]:\n        \"\"\"\n        Return supplementary data points as an array.\n\n        Parameters\n        ----------\n        key : str\n            Key in the isotherm DataFrame containing the data to select.\n        branch : {None, 'ads', 'des'}\n            The branch of the data to return. If ``None``, returns entire\n            dataset.\n        limits : [float, float], optional\n            Minimum and maximum data limits.\n            Put None or -+np.inf for no limit.\n        indexed : bool, optional\n            If this is specified to true, then the function returns an indexed\n            pandas.Series instead of an array.\n\n        Returns\n        -------\n        array or Series\n            The data slice corresponding to the parameters passed.\n\n        \"\"\"\n        if key in self.other_keys:\n            ret = self.data(branch=branch).loc[:, key]\n\n            if not ret.empty:\n                # Select required points\n                if limits and any(limits):\n                    ret = ret.loc[ret.between(\n                        -numpy.inf if limits[0] is None else limits[0],\n                        numpy.inf if limits[1] is None else limits[1]\n                    )]\n\n            if indexed:\n                return ret\n            return ret.values\n\n        raise ParameterError(f\"Isotherm does not contain any {key} data.\")\n\n    def has_branch(self, branch: str) -> bool:\n        \"\"\"\n        Check if the isotherm has an specific branch.\n\n        Parameters\n        ----------\n        branch : {None, 'ads', 'des'}\n            The branch of the data to check for.\n\n        Returns\n        -------\n        bool\n            Whether the data exists or not.\n\n        \"\"\"\n        return not self.data(branch=branch).empty\n\n    ##########################################################\n    #   Functions that interpolate values of the isotherm data\n\n    def pressure_at(\n        self,\n        loading: t.List[float],\n        branch: str = 'ads',\n        interpolation_type: str = 'linear',\n        interp_fill: t.Union[float, t.Tuple[float, float], str] = None,\n        pressure_unit: str = None,\n        pressure_mode: str = None,\n        loading_unit: str = None,\n        loading_basis: str = None,\n        material_unit: str = None,\n        material_basis: str = None,\n    ) -> numpy.ndarray:\n        \"\"\"\n        Interpolate isotherm to compute pressure at any loading given.\n\n        Parameters\n        ----------\n        loading : float\n            Loading at which to compute pressure.\n        branch : {'ads', 'des'}\n            The branch of the use for calculation. Defaults to adsorption.\n        interpolation_type : str\n            The type of scipy.interp1d used: `linear`, `nearest`, `zero`,\n            `slinear`, `quadratic`, `cubic`. It defaults to `linear`.\n        interp_fill : array-like or (array-like, array_like) or “extrapolate”, optional\n            Parameter to determine what to do outside data bounds.\n            Passed to the scipy.interpolate.interp1d function as ``fill_value``.\n            If blank, interpolation will not predict outside the bounds of data.\n\n        pressure_unit : str\n            Unit the pressure is returned in. If ``None``, it defaults to\n            internal isotherm units.\n        pressure_mode : str\n            The mode the pressure is returned in. If ``None``, it defaults to\n            internal isotherm mode.\n\n        loading_unit : str\n            Unit the loading is specified in. If ``None``, it defaults to\n            internal isotherm units.\n        loading_basis : {None, 'mass', 'molar', 'volume_gas', 'volume_liquid'}\n            The basis the loading is specified in. If ``None``,\n            assumes the basis the isotherm is currently in.\n        material_unit : str, optional\n            Unit in which the material is passed in. If ``None``\n            it defaults to which loading unit the isotherm is currently in\n        material_basis : str\n            The basis the loading is passed in. If ``None``, it defaults to\n            internal isotherm basis.\n\n        Returns\n        -------\n        float\n            Predicted pressure at loading specified.\n\n        \"\"\"\n        # Convert to numpy array just in case\n        loading = numpy.asarray(loading)\n\n        # Check if interpolator is applicable\n        if (\n            self.p_interpolator is None or self.p_interpolator.interp_branch != branch\n            or self.p_interpolator.interp_kind != interpolation_type\n            or self.p_interpolator.interp_fill != interp_fill\n        ):\n            self.p_interpolator = IsothermInterpolator(\n                self.loading(branch=branch),\n                self.pressure(branch=branch),\n                interp_branch=branch,\n                interp_kind=interpolation_type,\n                interp_fill=interp_fill\n            )\n\n        # Ensure loading is in correct units and basis for the internal model\n        if material_basis or material_unit:\n            if not material_basis:\n                material_basis = self.material_basis\n            if not material_unit:\n                raise ParameterError(\n                    \"Must specify an material unit if the input is in another basis.\"\n                )\n\n            loading = c_material(\n                loading,\n                basis_from=material_basis,\n                basis_to=self.material_basis,\n                unit_from=material_unit,\n                unit_to=self.material_unit,\n                material=self.material\n            )\n\n        if loading_basis or loading_unit:\n            if not loading_basis:\n                loading_basis = self.loading_basis\n            if not loading_unit:\n                raise ParameterError(\n                    \"Must specify a loading unit if the input is in another basis.\"\n                )\n\n            loading = c_loading(\n                loading,\n                basis_from=loading_basis,\n                basis_to=self.loading_basis,\n                unit_from=loading_unit,\n                unit_to=self.loading_unit,\n                adsorbate=self.adsorbate,\n                temp=self.temperature,\n                basis_material=self.material_basis,\n                unit_material=self.material_unit,\n            )\n\n        # Interpolate using the internal interpolator\n        pressure = self.p_interpolator(loading)\n\n        # Ensure pressure is in correct units and mode requested\n        if pressure_mode or pressure_unit:\n            if not pressure_mode:\n                pressure_mode = self.pressure_mode\n\n            pressure = c_pressure(\n                pressure,\n                mode_from=self.pressure_mode,\n                mode_to=pressure_mode,\n                unit_from=self.pressure_unit,\n                unit_to=pressure_unit,\n                adsorbate=self.adsorbate,\n                temp=self.temperature\n            )\n\n        return pressure\n\n    def loading_at(\n        self,\n        pressure: t.List[float],\n        branch: str = 'ads',\n        interpolation_type: str = 'linear',\n        interp_fill: t.Union[float, t.Tuple[float, float], str] = None,\n        pressure_unit: str = None,\n        pressure_mode: str = None,\n        loading_unit: str = None,\n        loading_basis: str = None,\n        material_unit: str = None,\n        material_basis: str = None,\n    ) -> numpy.ndarray:\n        \"\"\"\n        Interpolate isotherm to compute loading at any pressure given.\n\n        Parameters\n        ----------\n        pressure : float or array\n            Pressure at which to compute loading.\n        branch : {'ads', 'des'}\n            The branch the interpolation takes into account.\n        interpolation_type : str\n            The type of scipy.interp1d used: `linear`, `nearest`, `zero`,\n            `slinear`, `quadratic`, `cubic`. It defaults to `linear`.\n        interp_fill : array-like or (array-like, array_like) or “extrapolate”, optional\n            Parameter to determine what to do outside data bounds.\n            Passed to the scipy.interpolate.interp1d function as ``fill_value``.\n            If blank, interpolation will not predict outside the bounds of data.\n\n        pressure_unit : str\n            Unit the pressure is specified in. If ``None``, it defaults to\n            internal isotherm units.\n        pressure_mode : str\n            The mode the pressure is passed in. If ``None``, it defaults to\n            internal isotherm mode.\n\n        loading_unit : str, optional\n            Unit in which the loading should be returned. If ``None``\n            it defaults to which loading unit the isotherm is currently in.\n        loading_basis : {None, 'mass', 'molar', 'volume_gas', 'volume_liquid'}\n            The basis on which to return the loading, if possible. If ``None``,\n            returns on the basis the isotherm is currently in.\n        material_unit : str, optional\n            Material unit in which the data should be returned. If ``None``\n            it defaults to which loading unit the isotherm is currently in.\n        material_basis : {None, 'mass', 'volume', 'molar'}\n            Material basis on which to return the data, if possible. If ``None``,\n            returns on the basis the isotherm is currently in.\n\n        Returns\n        -------\n        float or array\n            Predicted loading at pressure P.\n\n        \"\"\"\n        # Convert to a numpy array just in case\n        pressure = numpy.asarray(pressure)\n\n        # Check if interpolator is applicable\n        if (\n            self.l_interpolator is None or self.l_interpolator.interp_branch != branch\n            or self.l_interpolator.interp_kind != interpolation_type\n            or self.l_interpolator.interp_fill != interp_fill\n        ):\n            self.l_interpolator = IsothermInterpolator(\n                self.pressure(branch=branch),\n                self.loading(branch=branch),\n                interp_branch=branch,\n                interp_kind=interpolation_type,\n                interp_fill=interp_fill\n            )\n\n        # Ensure pressure is in correct units and mode for the internal model\n        if pressure_mode or pressure_unit:\n            if not pressure_mode:\n                pressure_mode = self.pressure_mode\n            if pressure_mode == 'absolute' and not pressure_unit:\n                raise ParameterError(\n                    \"Must specify a pressure unit if the input is in an absolute mode.\"\n                )\n\n            pressure = c_pressure(\n                pressure,\n                mode_from=pressure_mode,\n                mode_to=self.pressure_mode,\n                unit_from=pressure_unit,\n                unit_to=self.pressure_unit,\n                adsorbate=self.adsorbate,\n                temp=self.temperature\n            )\n\n        # Interpolate using the internal interpolator\n        loading = self.l_interpolator(pressure)\n\n        # Ensure loading is in correct units and basis requested\n        if material_basis or material_unit:\n\n            if not material_basis:\n                material_basis = self.material_basis\n\n            loading = c_material(\n                loading,\n                basis_from=self.material_basis,\n                basis_to=material_basis,\n                unit_from=self.material_unit,\n                unit_to=material_unit,\n                material=self.material\n            )\n\n        if loading_basis or loading_unit:\n            if not loading_basis:\n                loading_basis = self.loading_basis\n\n            loading = c_loading(\n                loading,\n                basis_from=self.loading_basis,\n                basis_to=loading_basis,\n                unit_from=self.loading_unit,\n                unit_to=loading_unit,\n                adsorbate=self.adsorbate,\n                temp=self.temperature,\n                basis_material=self.material_basis,\n                unit_material=self.material_unit,\n            )\n\n        return loading\n\n    def spreading_pressure_at(\n        self,\n        pressure: t.List[float],\n        branch: str = 'ads',\n        pressure_unit: str = None,\n        pressure_mode: str = None,\n        loading_unit: str = None,\n        loading_basis: str = None,\n        material_unit: str = None,\n        material_basis: str = None,\n        interp_fill: t.Union[float, t.Tuple[float, float], str] = None,\n    ) -> numpy.ndarray:\n        r\"\"\"\n        Calculate reduced spreading pressure at a bulk adsorbate pressure P.\n\n        Use numerical quadrature on isotherm data points to compute the reduced\n        spreading pressure via the integral:\n\n        .. math::\n\n            \\Pi(p) = \\int_0^p \\frac{q(\\hat{p})}{ \\hat{p}} d\\hat{p}.\n\n        In this integral, the isotherm :math:`q(\\hat{p})` is represented by a\n        linear interpolation of the data.\n\n        For in-detail explanations, check reference [#]_.\n\n        Parameters\n        ----------\n        pressure : float\n            Pressure (in corresponding units as data in instantiation).\n        branch : {'ads', 'des'}\n            The branch of the use for calculation. Defaults to adsorption.\n        loading_unit : str\n            Unit the loading is specified in. If ``None``, it defaults to\n            internal isotherm units.\n        pressure_unit : str\n            Unit the pressure is returned in. If ``None``, it defaults to\n            internal isotherm units.\n        material_basis : str\n            The basis the loading is passed in. If ``None``, it defaults to\n            internal isotherm basis.\n        pressure_mode : str\n            The mode the pressure is returned in. If ``None``, it defaults to\n            internal isotherm mode.\n        interp_fill : array-like or (array-like, array_like) or “extrapolate”, optional\n            Parameter to determine what to do outside data bounds.\n            Passed to the scipy.interpolate.interp1d function as ``fill_value``.\n            If blank, interpolation will not predict outside the bounds of data.\n\n        Returns\n        -------\n        float\n            Spreading pressure, :math:`\\Pi`.\n\n        References\n        ----------\n        .. [#] C. Simon, B. Smit, M. Haranczyk. pyIAST: Ideal Adsorbed Solution\n           Theory (IAST) Python Package. Computer Physics Communications.\n\n        \"\"\"\n        # Get all data points\n        pressures = self.pressure(\n            branch=branch, pressure_unit=pressure_unit, pressure_mode=pressure_mode\n        )\n        loadings = self.loading(\n            branch=branch,\n            loading_unit=loading_unit,\n            loading_basis=loading_basis,\n            material_unit=material_unit,\n            material_basis=material_basis\n        )\n\n        # throw exception if interpolating outside the range.\n        if (self.l_interpolator is not None and self.l_interpolator.interp_fill is None) & \\\n                (pressure > pressures.max() or pressure < pressures.min()):\n            raise CalculationError(\n                textwrap.dedent(\n                    f\"\"\"\n                To compute the spreading pressure at this bulk adsorbate pressure,\n                we would need to extrapolate the isotherm since this pressure ({pressure:.3g} {self.pressure_unit})\n                is outside the range of the highest pressure in your pure-component\n                isotherm data ({pressures.max()} {self.pressure_unit}).\n\n                At present, the PointIsotherm class is set to throw an exception\n                when this occurs, as we do not have data outside this pressure range\n                to characterize the isotherm at higher pressures.\n\n                Option 1: fit an analytical model to extrapolate the isotherm\n                Option 2: pass a `interp_fill` to the spreading pressure function of the\n                    PointIsotherm object. Then, that PointIsotherm will\n                    assume that the uptake beyond {pressures.max()} {self.pressure_unit} is given by\n                    `interp_fill`. This is reasonable if your isotherm data exhibits\n                    a plateau at the highest pressures.\n                Option 3: Go back to the lab or computer to collect isotherm data\n                    at higher pressures. (Extrapolation can be dangerous!)\n                \"\"\"\n                )\n            )\n\n        # approximate loading up to first pressure point with Henry's law\n        # loading = henry_const * P\n        # henry_const is the initial slope in the adsorption isotherm\n        henry_const = loadings[0] / pressures[0]\n\n        # get how many of the points are less than pressure P\n        n_points = numpy.sum(pressures < pressure)\n\n        if n_points == 0:\n            # if this pressure is between 0 and first pressure point...\n            # \\int_0^P henry_const P /P dP = henry_const * P ...\n            return henry_const * pressure\n\n        # P > first pressure point\n        area = loadings[0]  # area of first segment \\int_0^P_1 n(P)/P dP\n\n        # get area between P_1 and P_k, where P_k < P < P_{k+1}\n        for i in range(n_points - 1):\n            # linear interpolation of isotherm data\n            slope = (loadings[i + 1] - loadings[i]) / (pressures[i + 1] - pressures[i])\n            intercept = loadings[i] - slope * pressures[i]\n            # add area of this segment\n            area += slope * (pressures[i + 1] - pressures[i]) + intercept * \\\n                numpy.log(pressures[i + 1] / pressures[i])\n\n        # finally, area of last segment\n        slope = (\n            self.loading_at(\n                pressure,\n                branch=branch,\n                pressure_unit=pressure_unit,\n                pressure_mode=pressure_mode,\n                loading_unit=loading_unit,\n                loading_basis=loading_basis,\n                material_unit=material_unit,\n                material_basis=material_basis,\n                interp_fill=interp_fill\n            ) - loadings[n_points - 1]\n        ) / (pressure - pressures[n_points - 1])\n\n        intercept = loadings[n_points - 1] - \\\n            slope * pressures[n_points - 1]\n        area += slope * (pressure - pressures[n_points - 1]) + intercept * \\\n            numpy.log(pressure / pressures[n_points - 1])\n\n        return area\n", "meta": {"hexsha": "b91c9bc76a43d3952383923710368047d7e15cb3", "size": 48687, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/pygaps/core/pointisotherm.py", "max_stars_repo_name": "pauliacomi/adsutils", "max_stars_repo_head_hexsha": "062653b38924d419d1235edf7909078ff98a163f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pygaps/core/pointisotherm.py", "max_issues_repo_name": "pauliacomi/adsutils", "max_issues_repo_head_hexsha": "062653b38924d419d1235edf7909078ff98a163f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pygaps/core/pointisotherm.py", "max_forks_repo_name": "pauliacomi/adsutils", "max_forks_repo_head_hexsha": "062653b38924d419d1235edf7909078ff98a163f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2509563887, "max_line_length": 115, "alphanum_fraction": 0.5738492821, "include": true, "reason": "import numpy", "num_tokens": 9837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3486451353339457, "lm_q1q2_score": 0.19465799050065177}}
{"text": "# coding: utf-8\n\n\"\"\" Transform a proper motion to/from Galactic to/from ICRS coordinates \"\"\"\n\nfrom __future__ import division, print_function\n\n# Standard library\nimport warnings\n\n# Third-party\nimport numpy as np\nimport astropy.coordinates as coord\n\n__all__ = ['transform_proper_motion', 'pm_gal_to_icrs', 'pm_icrs_to_gal']\n\ndef transform_proper_motion(coordinate, pm, new_frame):\n    \"\"\"\n    Transform the proper motion vector ``pm`` at the sky coordinate\n    ``coordinate`` to the desired coordinate frame ``new_frame``.\n\n    Parameters\n    ----------\n    coordinate : :class:`~astropy.coordinates.SkyCoord`, :class:`~astropy.coordinates.BaseCoordinateFrame`\n        An instance of an Astropy coordinate object.\n    pm : :class:`~astropy.units.Quantity`, iterable\n        Proper motion components (longitude, latitude) in the same frame\n        as the input coordinates. Can either be an iterable of two\n        :class:`~astropy.units.Quantity` objects or a single\n        :class:`~astropy.units.Quantity` with shape (2,N).\n        The proper motion in longitude is assumed to already include\n        the cos(latitude) term.\n    new_frame : :class:`~astropy.coordinates.BaseCoordinateFrame` subclass\n        The desired coordinate frame of the proper motion.\n\n    Returns\n    -------\n    new_pm : tuple\n        A length-2 tuple containing the proper motion components\n        (longitude, latitude) in the new frame. The longitude component is\n        includes the cos(latitude) term.\n\n    Examples\n    --------\n\n        >>> import astropy.units as u\n        >>> import astropy.coordinates as coord\n        >>> c = coord.SkyCoord(ra=196.5*u.degree, dec=-10.33*u.deg, distance=16.2*u.kpc)\n        >>> pm = [-1.53, 3.5]*u.mas/u.yr\n        >>> transform_proper_motion(c, pm, coord.Galactic) # doctest: +FLOAT_CMP\n        <Quantity [-1.19944367, 3.62660101] mas / yr>\n\n    \"\"\"\n    url = \"http://docs.astropy.org/en/stable/coordinates/velocities.html\"\n    warnings.warn(\"This function is now deprecated. Use the velocity \"\n                  \"transformation functionality in Astropy instead. For more \"\n                  \"information, see: {0}\".format(url), DeprecationWarning)\n\n    if hasattr(coordinate, 'frame'):\n        coordinate = coordinate.frame\n\n    frame_cls = coordinate.__class__\n    c = frame_cls(coordinate.data.with_differentials(\n        coord.UnitSphericalCosLatDifferential(*pm)))\n    new_c = c.transform_to(new_frame)\n    diff = new_c.data.differentials['s']\n    pm = np.vstack((diff.d_lon_coslat.value, diff.d_lat.value)) * diff.d_lat.unit\n\n    return pm.reshape((2,) + c.shape)\n\n# ----------------------------------------------------------------------------\n# Deprecated:\n#\n\ndef pm_gal_to_icrs(coordinate, pm):\n    r\"\"\"\n    Convert proper motion in Galactic coordinates (l,b) to\n    ICRS coordinates (RA, Dec).\n\n    Parameters\n    ----------\n    coordinate : :class:`~astropy.coordinates.SkyCoord`, :class:`~astropy.coordinates.BaseCoordinateFrame`\n        An instance of an Astropy coordinate object. Can be in any\n        frame that is transformable to ICRS coordinates.\n    pm : :class:`~astropy.units.Quantity`, iterable\n        Full description of proper motion in Galactic longitude and\n        latitude. Can either be a tuple of two\n        :class:`~astropy.units.Quantity` objects or a single\n        :class:`~astropy.units.Quantity` with shape (2,N).\n        The proper motion in longitude is assumed to be multipled by\n        cosine of Galactic latitude, :math:`\\mu_l\\cos b`.\n\n    Returns\n    -------\n    pm : :class:`~astropy.units.Quantity`\n        An astropy :class:`~astropy.units.Quantity` object specifying the\n        proper motion vector array in ICRS coordinates. Will have shape\n        (2,N).\n\n    Examples\n    --------\n\n        >>> import astropy.units as u\n        >>> import astropy.coordinates as coord\n        >>> c = coord.SkyCoord(ra=196.5*u.degree, dec=-10.33*u.deg, distance=16.2*u.kpc)\n        >>> pm = [-1.53, 3.5]*u.mas/u.yr\n        >>> pm_gal_to_icrs(c, pm) # doctest: +FLOAT_CMP\n        <Quantity [-1.84741767, 3.34334366] mas / yr>\n\n    \"\"\"\n\n    # Note: Deprecation warning gets emitted from calling\n    #       transform_proper_motion below.\n    g = coordinate.transform_to(coord.Galactic)\n    return transform_proper_motion(g, pm, coord.ICRS)\n\ndef pm_icrs_to_gal(coordinate, pm):\n    r\"\"\"\n    Convert proper motion in ICRS coordinates (RA, Dec) to\n    Galactic coordinates (l,b).\n\n    Parameters\n    ----------\n    coordinate : :class:`~astropy.coordinates.SkyCoord`, :class:`~astropy.coordinates.BaseCoordinateFrame`\n        An instance of an Astropy coordinate object. Can be in any\n        frame that is transformable to ICRS coordinates.\n    pm : :class:`~astropy.units.Quantity`, iterable\n        Full description of proper motion in Right ascension (RA) and\n        declination (Dec). Can either be a tuple of two\n        :class:`~astropy.units.Quantity` objects or a single\n        :class:`~astropy.units.Quantity` with shape (2,N).\n        The proper motion in RA is assumed to be multipled by\n        cosine of declination, :math:`\\mu_\\alpha\\cos\\delta`.\n\n    Returns\n    -------\n    pm : :class:`~astropy.units.Quantity`\n        An astropy :class:`~astropy.units.Quantity` object specifying the\n        proper motion vector array in Galactic coordinates. Will have shape\n        (2,N).\n\n    Examples\n    --------\n\n        >>> import astropy.units as u\n        >>> import astropy.coordinates as coord\n        >>> c = coord.SkyCoord(ra=196.5*u.degree, dec=-10.33*u.deg, distance=16.2*u.kpc)\n        >>> pm = [-1.84741767, 3.34334366]*u.mas/u.yr\n        >>> pm_icrs_to_gal(c, pm) # doctest: +FLOAT_CMP\n        <Quantity [-1.52999988, 3.49999973] mas / yr>\n\n    \"\"\"\n\n    # Note: Deprecation warning gets emitted from calling\n    #       transform_proper_motion below.\n    i = coordinate.transform_to(coord.ICRS)\n    return transform_proper_motion(i, pm, coord.Galactic)\n\n", "meta": {"hexsha": "9bf17cd553aca6e19f418db6d5f85cd03a1beda4", "size": 5930, "ext": "py", "lang": "Python", "max_stars_repo_path": "gala/coordinates/propermotion.py", "max_stars_repo_name": "ltlancas/gala", "max_stars_repo_head_hexsha": "2621bb599d67e74a85446abf72d5930ef70ca181", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-14T03:36:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-14T03:36:15.000Z", "max_issues_repo_path": "gala/coordinates/propermotion.py", "max_issues_repo_name": "ltlancas/gala", "max_issues_repo_head_hexsha": "2621bb599d67e74a85446abf72d5930ef70ca181", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gala/coordinates/propermotion.py", "max_forks_repo_name": "ltlancas/gala", "max_forks_repo_head_hexsha": "2621bb599d67e74a85446abf72d5930ef70ca181", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5316455696, "max_line_length": 106, "alphanum_fraction": 0.650084317, "include": true, "reason": "import numpy,import astropy", "num_tokens": 1445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.19465799050065175}}
{"text": "#!/usr/bin/python\n#-*- coding: utf-8 -*-\n\n# >.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.\n# Licensed under the Apache License, Version 2.0 (the \"License\")\n# You may obtain a copy of the License at\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# --- File Name: tpl_score.py\n# --- Creation Date: 13-10-2020\n# --- Last Modified: Wed 18 Nov 2020 18:42:10 AEDT\n# --- Author: Xinqi Zhu\n# .<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<\n\"\"\"Implementation of the TPL score.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport os\nimport sys\nimport pickle\nsys.path.insert(\n    0,\n    os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))),\n                 'disentanglement_lib'))\nsys.path.insert(\n    0,\n    os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))),\n                 'stylegan2'))\nimport dnnlib.tflib\nfrom absl import logging\nfrom disentanglement_lib.evaluation.metrics import utils\nimport numpy as np\nfrom six.moves import range\nfrom scipy import stats\nimport gin.tf\n\n\n@gin.configurable(\"tpl_score\",\n                  blacklist=[\n                      \"ground_truth_data\", \"generator_function\",\n                      \"random_state\", \"activation_str\", \"latent_size\",\n                      \"artifact_dir\"\n                  ])\ndef compute_tpl_score(ground_truth_data,\n                      generator_function,\n                      random_state,\n                      activation_str,\n                      latent_size,\n                      artifact_dir=None,\n                      batch_size=gin.REQUIRED,\n                      num_traversals=gin.REQUIRED,\n                      num_samples_per_dim=gin.REQUIRED,\n                      traversal_bound=gin.REQUIRED,\n                      active_thresh=gin.REQUIRED):\n    \"\"\"Computes the FactorVAE disentanglement metric.\n\n  Args:\n    ground_truth_data: GroundTruthData to be sampled from.\n    generator_function: Function that takes latent code as input and\n      outputs an image.\n    random_state: Numpy random state used for randomness.\n    artifact_dir: Optional path to directory where artifacts can be saved.\n    latent_size: Latent code size.\n    batch_size: Number of points to be used to in a GPU.\n    num_traversals: Number of traversals to sample.\n    num_samples_per_dim: Number of samples per dim.\n    traversal_bound: The bound for traversal.\n    active_thresh: Threshold for determining active dims.\n\n  Returns:\n    Dictionary with scores:\n      avg_tpl_dim: Mean TPL score for each dim.\n      avg_tpl: Overall mean TPL score.\n      active_mask: Mask of which dims are active.\n      active_distances: Latent distances of active dims.\n      active_stds: Latent stds of active dims.\n      n_active_dims: Number of active dims.\n  \"\"\"\n    del ground_truth_data\n    del artifact_dir\n    dnnlib.tflib.init_tf()\n    distance_measure = load_pkl(\n        '.stylegan2-cache/vgg16_zhang_perceptual.pkl'\n        # 'http://d36zk2xti64re0.cloudfront.net/stylegan1/networks/metrics/vgg16_zhang_perceptual.pkl'\n    )\n    if activation_str == \"'logits'\":\n        activation = sigmoid\n    elif activation_str == \"'tanh'\":\n        activation = tanh\n    else:\n        raise ValueError(\n            \"Activation function  could not be infered from gin config.\")\n    tpl_dim_ls = []\n    for i in range(num_traversals):\n        sample = random_state.normal(size=(1, latent_size))\n        # factor_index = random_state.randint(ground_truth_data.num_factors)\n        tpl_dim = compute_tpl_for(\n            sample, generator_function, batch_size, num_samples_per_dim,\n            latent_size, activation,\n            distance_measure, traversal_bound)  # np.array of [latent_size]\n        tpl_dim_ls.append(tpl_dim)\n    tpl_dim_np = np.array(tpl_dim_ls)  # np.array of [n_trav, latent_size]\n    avg_tpl_dim = np.mean(tpl_dim_np, axis=0)  # np.array of [latent_size]\n    std_tpl_dim = np.std(tpl_dim_np, axis=0)  # np.array of [latent_size]\n\n    active_mask = avg_tpl_dim > active_thresh\n    active_distances = np.extract(active_mask, avg_tpl_dim)\n    active_stds = np.extract(active_mask, std_tpl_dim)\n    avg_tpl = np.sum(active_distances)\n    n_active_dims = active_mask.astype(int).sum()\n\n    scores_dict = {}\n    scores_dict['avg_tpl_dim'] = avg_tpl_dim.tolist()\n    scores_dict['avg_tpl'] = avg_tpl\n    scores_dict['active_mask'] = active_mask.tolist()\n    scores_dict['active_distances'] = active_distances.tolist()\n    scores_dict['active_stds'] = active_stds.tolist()\n    scores_dict['n_active_dims'] = n_active_dims\n    # print('scores_dict:', scores_dict)\n    return scores_dict\n\n\ndef compute_tpl_for(sample, generator_function, batch_size,\n                    num_samples_per_dim, latent_size, activation,\n                    distance_measure, traversal_bound):\n    '''\n    Return: np.array of [latent_size]\n    '''\n    tpl_sample_dim_ls = []\n    for i in range(latent_size):\n        samples_traversal = np.tile(sample, [num_samples_per_dim, 1])\n        samples_traversal[:, i] = np.linspace(-traversal_bound, traversal_bound, num=num_samples_per_dim)\n        raw_imgs_traversal = generator_function(\n            samples_traversal)  # size: [b, h, w, c]\n        imgs_traversal = activation(raw_imgs_traversal)\n        j = 0\n        traversal_score = 0\n        while j < num_samples_per_dim:\n            b_j = min(batch_size, num_samples_per_dim - j)\n            cur_imgs_traversal = imgs_traversal[j:j + b_j, ...]\n            j += b_j\n            traversal_score += measure_distance(cur_imgs_traversal,\n                                                distance_measure)\n        tpl_sample_dim_ls.append(traversal_score)\n    return np.array(tpl_sample_dim_ls)\n\n\ndef measure_distance(imgs_traversal, distance_measure):\n    images = np.transpose(imgs_traversal, [0, 3, 1, 2])  # bhwc -> bchw\n    images = images * 255  # [0, 1] -> [0, 255]\n    v = get_return_v(distance_measure.run(images[:-1, ...], images[1:, ...]),\n                     1)\n    return v.sum()\n\n\ndef sigmoid(x):\n    return stats.logistic.cdf(x)\n\n\ndef tanh(x):\n    return np.tanh(x) / 2. + .5\n\n\ndef get_return_v(x, topk=1):\n    if (not isinstance(x, tuple)) and (not isinstance(x, list)):\n        return x if topk == 1 else tuple([x] + [None] * (topk - 1))\n    if topk > len(x):\n        return tuple(list(x) + [None] * (topk - len(x)))\n    else:\n        if topk == 1:\n            return x[0]\n        else:\n            return tuple(x[:topk])\n\n\ndef load_pkl(file_or_url):\n    with open(file_or_url, 'rb') as file:\n        return pickle.load(file, encoding='latin1')\n", "meta": {"hexsha": "77014f26bec08a48649b376fc779068588a0bf94", "size": 6556, "ext": "py", "lang": "Python", "max_stars_repo_path": "tpl_score.py", "max_stars_repo_name": "zhuxinqimac/Israfel", "max_stars_repo_head_hexsha": "1f1ff8c494ac93a5284477dcafc487b1915d3570", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-14T16:19:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T04:55:19.000Z", "max_issues_repo_path": "tpl_score.py", "max_issues_repo_name": "zhuxinqimac/TPL-Evaluate", "max_issues_repo_head_hexsha": "1f1ff8c494ac93a5284477dcafc487b1915d3570", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tpl_score.py", "max_forks_repo_name": "zhuxinqimac/TPL-Evaluate", "max_forks_repo_head_hexsha": "1f1ff8c494ac93a5284477dcafc487b1915d3570", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4222222222, "max_line_length": 105, "alphanum_fraction": 0.6404820012, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3486451285660856, "lm_q1q2_score": 0.19465798672197274}}
{"text": "# -*- coding: utf-8 -*-\n'''\nCreated on Nov 24, 2014\n\n@author: pascale\n'''\n\nimport rmodel\nimport numpy as np\nimport logging\nimport rttov\nimport copy\nimport matplotlib.pyplot as plt\nimport os\nimport h5py\nimport shutil\nfrom r1Dvar import r1dvarObjects\n\n\nq_mixration_to_ppmv = 1.60771704e+6\n\n\ndef vector2profile(vector, exprofile):\n    \"\"\" convert vector to profile \"\"\"\n    \"\"\" take exprofile to begin with \"\"\"\n    \"\"\" a vector contains only T values, \"\"\"\n    \"\"\" lnq bottom lnq vales , Tsurf, lnq surf and Tskin\"\"\"\n    \"\"\" temperature, and ln q are stored from top of atmosphere to ground \"\"\"\n\n    nlevels = vector.shape[0] - 29 - 3\n    if nlevels != exprofile['NLEVELS']:\n        logging.error(\"vector and profile are not of the same dimension\")\n        return None\n\n    profile = copy.deepcopy(exprofile)\n\n    for i in range(nlevels):\n        profile[\"T\"][i] = vector[i]\n\n    for i in range(29):\n        profile[\"Q\"][nlevels - 29 + i] = vector[nlevels + i]\n\n    profile[\"S2M\"][\"T\"] = vector[nlevels + 29]\n    profile[\"S2M\"][\"Q\"] = vector[nlevels + 29 + 1]\n    profile[\"SKIN\"][\"T\"] = vector[nlevels + 29 + 2]\n\n    return profile\n\n\nclass Project1dvar(object):\n\n    def __init__(self, pTrue, pBg, satellite, instrument,\n                 matrixBfile=None, channel_list=None,\n                 changeTheBackground=False):\n        \"\"\" initialize a 1DvarProject with a True and a Background project \"\"\"\n        \"\"\" if channel_list is present : we work on a restricted list \"\"\"\n        \"\"\" of channel \"\"\"\n        \"\"\" but in fact channel_list is set from the Coefficient \"\"\"\n        \"\"\" object of pBg \"\"\"\n        \"\"\" so we use this list to extract a sub-matrix from the Rmatrix \"\"\"\n        \"\"\" satellite must be = platform-num (ex : metop-1 , noaa-19) \"\"\"\n        \"\"\" if changeTheBackground=False we don not change the Background \"\"\"\n        \"\"\" if changeTheBackground=False at each new step the previously  \"\"\"\n        \"\"\" retrieved profile becomes the new background \"\"\"\n\n        self.changeTheBackground = changeTheBackground\n        self.ENV = {}\n        self.pTrue = pTrue\n        self.pBg = pBg\n        # set distinct filenames for the true and the background project\n        # (we will run rttov with different files)\n        self.pTrue.setFileNameMark(\"True\")\n        self.pBg.setFileNameMark(\"Bg\")\n        logging.info(\"Initialize a Project1dvar object\")\n        logging.info(\"are pBg coefficients loaded ? \" +\n                     str(self.pBg.myCoeffs.loadCoeffs))\n        self.satellite = satellite\n        self.instrument = instrument\n\n        self.BgInitialProfile = copy.deepcopy(self.pBg.myProfile)\n        self.BmatrixFileName = None\n        self.RmatrixFilename = None\n\n        self._SetConfig()\n        self.factorB = 1.\n        self.factorR = 1.\n        self.MaxNoise = 1.\n        self.retrievedVectors = []\n        self.retrievedProfiles = []\n        self.Rmatrix = Rmatrix()\n        self.Bmatrix = Bmatrix()\n        # read R matrix\n        self.initCoeffsandReadRmatrix()\n        # Bmatrix\n        if matrixBfile:\n            self.BmatrixFileName = matrixBfile\n        if not os.path.exists(self.BmatrixFileName):\n            logging.error(\n                \"Sorry something is wrong : I cannot find the Bmatrix :\"\n                \" check the presence of the nwpsaf-1dvar files \")\n            raise IOError\n        # read the Bmatrix\n        B = Bmatrix()\n        B.read_matrices(self.BmatrixFileName)\n        # The file contains 4 matrix but according to Peter the 4 matrix are\n        # identical\n        self.Bmat = B.matrices[1]\n        self.step_counter = 0\n\n    def initCoeffsandReadRmatrix(self):\n        \"\"\" initialise myCoeffs for pBg project and read the R matrix \"\"\"\n        \"\"\" the R matrix is computed according to the list of channels \"\"\"\n        if not self.pBg.myCoeffs.loadCoeffs:\n            logging.info(\"load coefficients for pBg\")\n            err = self.pBg.loadCoefficients()\n            if err != 0:\n                raise RuntimeError(\"Cannot load coefficient in r1dvar project\")\n        nbChannels = self.pBg.myCoeffs.nchannels\n        logging.info(\"nbChannels: {}\".format(nbChannels))\n        # initialise the  1dvarproject channel_list used by readRmatrix\n        my_chan_list = self.pBg.myCoeffs.getFF_ORI_CHN()\n        # must start at 0\n        self.channel_list = [my_chan_list[i] -\n                             1 for i in range(len(my_chan_list))]\n        # read the R matrix\n\n        self.readRmatrix(self.satellite, self.instrument)\n\n    def reinitCoeff(self, satellite, instrument, coeffs):\n        \"\"\" must be called if we change the coefficients \"\"\"\n        \"\"\" (select channel or change instrument ) \"\"\"\n        \"\"\"  satellite must be = platform-num (ex : metop-1 , noaa-19) \"\"\"\n        self.pBg.myCoeffs = coeffs\n        self.satellite = satellite\n        self.instrument = instrument\n\n        self.initCoeffsandReadRmatrix()\n\n    def _SetConfig(self):\n        try:\n            self.ENV[\"NWPSAF_1DVAR_HOME\"] = os.environ(\"NWPSAF_1DVAR_HOME\")\n        except:\n            logging.warning(\n                \"The environment variable NWPSAF_1DVAR_HOME is not set :\"\n                \" no worries I can use my matrix ..\")\n            self.ENV[\"NWPSAF_1DVAR_HOME\"] = os.environ[\n                \"RTTOV_GUI_PREFIX\"] + \"/r1Dvar/data\"\n        self.BmatrixFileName = self.ENV[\n            \"NWPSAF_1DVAR_HOME\"] + \"/Sample_Bmatrices/Bmatrix_54L\"\n\n        self.RmatrixFilenames = {\n            \"AIRS\": os.path.join(self.ENV[\"NWPSAF_1DVAR_HOME\"],\n                                 \"AIRS_COEFFS_DIR/Rmatrix_orig\"),\n            \"ATMS\": os.path.join(self.ENV[\"NWPSAF_1DVAR_HOME\"],\n                                 \"ATMS_COEFFS_DIR/Rmatrix_orig\"),\n            \"AMSU-A\": os.path.join(self.ENV[\"NWPSAF_1DVAR_HOME\"],\n                                   \"ATOVS_COEFFS_DIR/Rmatrix_orig\"),\n            \"AMSU-B\": os.path.join(self.ENV[\"NWPSAF_1DVAR_HOME\"],\n                                   \"ATOVS_COEFFS_DIR/Rmatrix_orig\"),\n            \"HIRS\": os.path.join(self.ENV[\"NWPSAF_1DVAR_HOME\"],\n                                 \"ATOVS_COEFFS_DIR/Rmatrix_orig\"),\n            \"MHS\": os.path.join(self.ENV[\"NWPSAF_1DVAR_HOME\"],\n                                \"ATOVS_COEFFS_DIR/Rmatrix_orig\"),\n            \"mhs\": os.path.join(self.ENV[\"NWPSAF_1DVAR_HOME\"],\n                                \"ATOVS_COEFFS_DIR/Rmatrix_orig\"),\n            \"IASI\": os.path.join(self.ENV[\"NWPSAF_1DVAR_HOME\"],\n                                 \"IASI_COEFFS_DIR/Rmatrix_orig\"),\n            \"CRIS\": os.path.join(self.ENV[\"NWPSAF_1DVAR_HOME\"],\n                                 \"CrIS_COEFFS_DIR/Rmatrix_orig\"),\n            \"SSMIS\": os.path.join(self.ENV[\"NWPSAF_1DVAR_HOME\"],\n                                  \"SSMIS_COEFFS_DIR/Rmatrix_orig\"),\n            \"CrIS\": os.path.join(self.ENV[\"NWPSAF_1DVAR_HOME\"],\n                                 \"CrIS_COEFFS_DIR/Rmatrix_orig\"),\n            \"amsua\": os.path.join(self.ENV[\"NWPSAF_1DVAR_HOME\"],\n                                  \"ATOVS_COEFFS_DIR/Rmatrix_orig\"),\n            \"amsub\": os.path.join(self.ENV[\"NWPSAF_1DVAR_HOME\"],\n                                  \"ATOVS_COEFFS_DIR/Rmatrix_orig\"),\n            \"hirs\": os.path.join(self.ENV[\"NWPSAF_1DVAR_HOME\"],\n                                 \"ATOVS_COEFFS_DIR/Rmatrix_orig\")\n        }\n\n    def readRmatrix(self, satellite, instrument, filename=None):\n        \"\"\" read the observation error matrix file and init self.Rmat \"\"\"\n        \"\"\" if filename is specified then it has the priority \"\"\"\n        \"\"\" first step : determine the file name from the instrument \"\"\"\n        \"\"\" (stored in rge Rmatrixfilenames dictionary\"\"\"\n        \"\"\" create a Rmatrix objet which will contains all the Rmatrix \"\"\"\n        \"\"\" read in a file \"\"\"\n        \"\"\" then determine the actual Rmat from satellite and instrument \"\"\"\n        \"\"\" ATOVS case is particular : must retrieve HIRS, AMSU-A and MHS\"\"\"\n        \"\"\" for some other files it is trivial : they contains just one \"\"\"\n        \"\"\" matrix \"\"\"\n        \"\"\"  satellite must be = platform-num (ex : metop-1 , noaa-19) \"\"\"\n        # when this method is call self.channel_list exit and is ready (no need\n        # to shift indices)\n        logging.info(\"read R matrix for \" + satellite + \" \" + instrument)\n        isATOV = False\n        if instrument in (\"hirs\", \"amsua\", \"amsub\", \"mhs\"):\n            isATOV = True\n        else:\n            if instrument == \"cris\":\n                instrument = \"CrIS\"\n            else:\n                instrument = instrument.upper()\n        if satellite == \"metop-2\":\n            satellite = \"MetOp-A\"\n        else:\n            if satellite == \"metop-1\":\n                satellite = \"MetOp-B\"\n            else:\n                satellite = satellite.upper()\n\n        logging.info(\"instrument :\" + str(instrument) + \" \" +\n                     str(satellite) + \" is ATOV ?: \" + str(isATOV))\n        if filename is not None:\n            self.RmatrixFilename = filename\n        else:\n            self.instrument = instrument\n            self.satellite = satellite\n\n            self.RmatrixFilename = self.RmatrixFilenames[instrument]\n            try:\n                self.RmatrixFilename = self.RmatrixFilenames[instrument]\n                logging.info(\" RmatrixFilename : \" + self.RmatrixFilename +\n                             \" for \" +\n                             instrument + \" \" + satellite +\n                             \" is ATOV ?: \" + str(isATOV))\n            except (KeyError):\n                raise ValueError(\"wrong instrument\" + str(instrument))\n\n            self.Rmatrix = Rmatrix()\n            logging.info(\"Read the Rmatrix\")\n            self.Rmatrix.read(self.RmatrixFilename)\n            logging.info(\"R matrix successfully read\")\n\n            try:\n                if len(self.Rmatrix.Rmatrix.keys()) == 1:\n                    self.Rmat = self.Rmatrix.Rmatrix.values()[0][\"matrix\"]\n                else:\n                    if isATOV:\n\n                        if self.instrument == \"amsua\":\n                            self.Rmat = self.Rmatrix.Rmatrix[\n                                satellite + \" \" + \"ATOVS\"][\"matrix\"][\n                                                                20:35, 20:35]\n                        else:\n                            if (\n                                    self.instrument == \"amsub\" or\n                                    self.instrument == \"MHS\" or\n                                    self.instrument == \"mhs\"):\n                                self.Rmat = self.Rmatrix.Rmatrix[\n                                    satellite + \" \" + \"ATOVS\"][\"matrix\"][\n                                    35:40, 35:40]\n                                print self.Rmat\n                            else:\n                                if self.instrument == \"hirs\":\n                                    # HIRS : 1 vis channel, 19 IR channels :\n                                    # take only the IR channels !\n                                    # in this case we start at 1 because the\n                                    # first channel is vis !!!!\n                                    self.Rmat = self.Rmatrix.Rmatrix[\n                                        satellite + \" \" + \"ATOVS\"][\"matrix\"][\n                                        1:20, 1:20]\n                                else:\n                                    raise ValueError(\n                                        \"wrong satellite and instrument\" +\n                                        str(satellite) + \" \" + str(instrument))\n                    else:\n                        raise ValueError(\n                            \"wrong satellite and instrument \" +\n                            str(satellite) +\n                            \" \" + str(instrument))\n            except (KeyError):\n\n                raise ValueError(\"wrong satellite and instrument \" +\n                                 str(satellite) + \" \" + str(instrument))\n        # keep only selected channels\n\n        if self.channel_list is None:\n            logging.info(\"no channel list take all of the matrix\")\n            self.channel_list = range(0, self.Rmat.shape[0])\n        else:\n            # this channel list already begin with 0\n            foo = self.Rmat[self.channel_list, :]\n            bar = foo[:, self.channel_list]\n            self.Rmat = bar\n\n    def plotRmat(self):\n        plt.imshow(self.Rmat, origin=\"lower\", interpolation=\"nearest\")\n        plt.title(\"Rmatrix for \" + self.instrument + \" \" + self.satellite)\n        plt.colorbar()\n        plt.show()\n\n    def setFactorB(self, factor):\n        self.factorB = factor\n\n    def setFactorR(self, factor):\n        self.factorR = factor\n\n    def setMaxNoise(self, maxNoise):\n        self.MaxNoise = maxNoise\n\n    def stepRetrieve1d(self):\n        \"\"\" perform a step of retrieval\n          the retrieved vector becomes the new background profile\"\"\"\n        if self.Xr is not None:\n            if self.changeTheBackground:\n                # make a new profile object with the retrieved vector and the\n                # former background profile\n                newBgProfile = vector2profile(self.Xr, self.pBg.myProfile)\n                self.pBg.myProfile = newBgProfile\n                self.pBg.myProfile = self.retrievedProfiles[-1]\n                logging.info(\"new profile background initialised \" +\n                             self.pBg.profileFileName)\n                self.retrieve1d()\n            else:\n                # we do not change the Background\n                self.retrieve1d()\n\n    def set1dvarRequiredOptionsAndValues(self, project):\n        \"\"\" set the required option and valuesfor the 1dvar algorithm \"\"\"\n        \"\"\" this options are CFRACTION=0 \"\"\"\n        \"\"\" Nadir condition \"\"\"\n        logging.info(\n            \"set 1dvar required options and values (CFRACTION=0, no gas,\"\n            \" calculation at nadir etc) \")\n        project.myOption[\"SWITCHRAD\"] = True\n        # No gas\n        project.myOption[\"CO2_DATA\"] = False\n        project.myOption[\"CH4_DATA\"] = False\n        project.myOption[\"OZONE_DATA\"] = False\n        project.myOption[\"CO_DATA\"] = False\n        project.myOption[\"N2O_DATA\"] = False\n        # no cloud\n        project.myOption[\"ADDCLOUDS\"] = False\n        project.myProfile[\"CFRACTION\"] = 0\n        # no aerosols\n        project.myOption[\"ADDAEROSL\"] = False\n        # no solar\n        project.myOption[\"ADDSOLAR\"] = False\n\n        # calculation at nadir\n        project.myProfile[\"ZENANGLE\"] = 0\n        project.myProfile[\"SUNZENANGLE\"] = 0\n\n    def assumptionOnSurfaceParameters(self, profileTrue, profileBg):\n        \"\"\" restrictions the surface parameters of the Bg are applied\n             on the True except for T skin and T 2m  \"\"\"\n        profileBg[\"SKIN\"]['SURFTYPE'] = 1  # (0=Land, 1=Sea, 2=sea-ice)\n        for item in [\"LATITUDE\", \"LONGITUDE\", \"ELEVATION\", \"AZANGLE\", \"BE\",\n                     \"COSBK\", \"SNOW_FRAC\", \"SOIL_MOISTURE\"]:\n            profileTrue[item] = profileBg[item]\n        for item in [\"Q\", \"O\", \"P\", \"U\", \"V\", \"WFETC\"]:\n            profileTrue[\"S2M\"][item] = profileBg[\"S2M\"][item]\n        for item in [\"SURFTYPE\", \"WATERTYPE\", \"SALINITY\", \"FASTEM\"]:\n            profileTrue[\"SKIN\"][item] = profileBg[\"SKIN\"][item]\n\n    def retrieve1d(self):\n        \"\"\" perform the basic retrieval algorithm \"\"\"\n        \"\"\" must put switchrad a true et cfraction a 0 \"\"\"\n        # load coefficients\n        self.step_counter = self.step_counter + 1\n        self.pTrue.myCoeffs = self.pBg.myCoeffs\n        self.pTrue.myOption = self.pBg.myOption\n        # we are making assumption on surface parameters some must be the same\n        self.assumptionOnSurfaceParameters(\n            self.pTrue.myProfile, self.pBg.myProfile)\n\n        # at this point the coefficient must be loaded\n        if not self.pBg.myCoeffs.loadCoeffs:\n            logging.warning(\n                \"strange : coefficients would have been \"\n                \"loaded at this point ...\")\n            err = self.pBg.loadCoefficients()\n            if err != 0:\n                raise RuntimeError(\"Cannot load coefficient in r1dvar project\")\n\n        if len(self.channel_list) != self.pTrue.myCoeffs.nchannels:\n            logging.warning(\"wrong channel list : take all\")\n            self.channel_list = range(1, self.pTrue.myCoeffs.nchannels + 1)\n            self.readRmatrix(self.satellite, self.instrument)\n\n        nbChannels = self.pTrue.myCoeffs.nchannels\n        logging.info(\"nbChannels: {}\".format(nbChannels))\n\n        logging.debug(\"coefficients file: \" +\n                      self.pBg.myCoeffs.fileName[\"standard\"])\n        if self.step_counter > 1:\n            # test if we have a different number of channels\n            if len(self.Y_Xt) == 1:\n                previousNumberOfChannels = 1\n            else:\n                previousNumberOfChannels = self.Y_Xt.shape[0]\n            notSameNumberOfChannels = (\n                self.pBg.myCoeffs.nchannels != previousNumberOfChannels)\n            if notSameNumberOfChannels:\n                logging.info(\"not the same number of channels\")\n\n        # Run direct on True\n\n        logging.info(\">>>>>>>>> Run direct on True\")\n        # must put switchrad a true et cfraction a 0 and other things on\n        # options\n        self.set1dvarRequiredOptionsAndValues(self.pTrue)\n        err = self.pTrue.runDirect()\n        if (err != 0):\n            raise RuntimeError(\"Run Direct failed on true\")\n        # put radiance to 0 in the radiance file for plotting\n        self.changeRadianceFile(self.pTrue.radianceFileName)\n        # 1) Y(Xt) brightness temperatures from Xt\n        YXt = rttov.radiance.Radiance()\n        logging.info(\">>>>>>>>>>>reading BT from : \")\n        YXt.read(self.pTrue.radianceFileName)\n        self.Y_Xt = YXt[\"BT_CLEAR\"]  # No clouds so BT_CLEAR=BT\n        Xt = self.pTrue.myProfile.to1DvarVect()\n        self.Xt = Xt\n\n        # Run direct on Background\n        logging.info(\">>>>>>>> Run direct on Background\")\n        # must put switchrad a true et cfraction a 0 and other things on\n        # options\n        self.set1dvarRequiredOptionsAndValues(self.pBg)\n        err = self.pBg.runDirect()\n        if (err != 0):\n            raise RuntimeError(\"Run Direct failed on background\")\n        # put radiance to 0 in the radiance file for plotting\n        self.changeRadianceFile(self.pBg.radianceFileName)\n\n        logging.info(\">>>>>>>> Run K on Background\")\n        err = self.pBg.runK()\n        if (err != 0):\n            raise RuntimeError(\"Run K failed on background\")\n        else:\n            logging.info(\"run K on background OK\")\n\n        # 2) Y((Xb) brightness temperarures from Xb\n        YXb = rttov.radiance.Radiance()\n        logging.info(\">>>>>>>>>>reading BT \" + self.pBg.radianceFileName)\n        YXb.read(self.pBg.radianceFileName)\n        Y_Xb = YXb[\"BT_CLEAR\"]\n\n        # 3) compute jacobian matrix K(Xb) and transpose KT(Xb)\n        KXb = r1dvarObjects.R1dvarKmatrix()\n        logging.info(\"reading kmatrix \" + self.pBg.KMatrixFileName)\n        KXb.read(self.pBg.KMatrixFileName)\n\n        logging.info(\">>>>>>>KmatrixVectorAndTranspose \")\n        # extract the jacobian matrix from the KMatrix Object\n        K_Xb = KXb.toKmatrix1dvar()\n        # transpose this matrix\n        KT_Xb = K_Xb.T\n\n        # 4) apply scaling factor to background errors B --> fb x B\n        # the Bmatrix has been read in init and has been put in self.Bmat\n        myBmat = self.Bmat * self.factorB\n\n        # 5) apply scaling factor to observation errors R --> fr x R\n        # The R matrix has been read in init and has been put in self.Rmat\n\n        myRmat = self.Rmat * self.factorR\n\n        # 6) compute add random noise to Y(Xt)\n\n#\n        # Noise in BT = +/- MaxNoise degree\n        logging.info(\"Max Noise : \" + str(self.MaxNoise))\n        self.N = self.MaxNoise * (np.random.rand(nbChannels) * 2 - 1)\n        self.Y_Xt = self.Y_Xt + self.N\n\n        # save the file with True BT+Noise in order to be able to plot it after\n        new_name = self.pTrue.radianceFileName.replace(\".h5\", \"_Noise.h5\")\n        self.changeRadianceFile(self.pTrue.radianceFileName, self.N, new_name)\n\n        # 7) compute linear 1DVAR weights W where\n        # W = B . KT . [ K .B . KT + R ](-1)\n        # W =  fact1 . [ foo1 .KT  + R ](-1)\n        # W =  fact1 .  [  foo2   +  R ](-1)\n        # W =  fact1 .  [       foo3   ](-1)\n        # W =  fact1 . Matrice_inverse\n        fact1 = myBmat.dot(KT_Xb)\n        foo1 = K_Xb.dot(myBmat)\n        foo2 = foo1.dot(KT_Xb)\n        foo3 = foo2 + myRmat\n        # matrix inversion\n        logging.info(\"matrix inversion\")\n        Matrice_inverse = np.linalg.inv(foo3)\n        logging.info(\"compute the linear 1DVAR weight \")\n        W = fact1.dot(Matrice_inverse)\n\n        # 8) compute linear 1Dvar retrieved profile (Xr)\n        Xb = self.pBg.myProfile.to1DvarVect()\n        # we have already added N to Y_Xt earlier\n        YtminusYb = self.Y_Xt - Y_Xb\n\n        Xr = Xb + W.dot(YtminusYb)\n        # if Q <0 alors Q=0\n        for k in range(Xr.shape[0] - 29 - 3, (Xr.shape[0] - 3)):\n            if Xr[k] <= 0:\n                # if find something negative for Q : stick to the background\n                # ....\n                Xr[k] = Xb[k]\n        k = Xr.shape[0] - 2\n        if Xr[k] <= 0:\n            # if find something negative for Q : stick to the background ....\n            Xr[k] = Xb[k]\n\n        self.Xr = Xr\n        self.Y_Xb = Y_Xb\n        self.Xb = Xb\n        # append the retrieved Vector and the retrieved profile to list\n        self.retrievedVectors.append(Xr)\n        retrievedProfile = vector2profile(self.Xr, self.pBg.myProfile)\n        self.retrievedProfiles.append(retrievedProfile)\n        return Xr\n\n    def changeRadianceFile(self, radianceFileName, Noise=None, NewName=None):\n        \"\"\"   change the radiance file set radiance to 0 add Noise to BT) \"\"\"\n        if NewName:\n            shutil.copyfile(radianceFileName, NewName)\n            rf = h5py.File(radianceFileName, 'r+')\n        else:\n            rf = h5py.File(radianceFileName, 'r+')\n        group = rf[\"RADIANCE\"]\n        bt = rf[\"RADIANCE/BT\"][:]\n        bt_clear = rf[\"RADIANCE/BT_CLEAR\"][:]\n        rad_clear = rf[\"RADIANCE/CLEAR\"]\n        a = rad_clear[:]\n\n        a_new = np.zeros_like(a)\n        del rf[\"RADIANCE/CLEAR\"]\n        del rf[\"RADIANCE/CLOUDY\"]\n        del rf[\"RADIANCE/TOTAL\"]\n        del rf[\"RADIANCE/OVERCAST\"]\n        group.create_dataset(\"CLEAR\", a_new.shape, data=a_new)\n        group.create_dataset(\"CLOUDY\", a_new.shape, data=a_new)\n        group.create_dataset(\"TOTAL\", a_new.shape, data=a_new)\n        group.create_dataset(\"OVERCAST\", a_new.shape, data=a_new)\n        if Noise is not None:\n            bt_new = bt + Noise\n            bt_clear_new = bt_clear + Noise\n            del rf[\"RADIANCE/BT\"]\n            del rf[\"RADIANCE/BT_CLEAR\"]\n            group.create_dataset(\"BT\", bt_new.shape, data=bt_new)\n            group.create_dataset(\"BT_CLEAR\", bt_new.shape, data=bt_clear_new)\n        rf.close()\n\n    def plot(self):\n        colors = {0: \"red\",\n                  1: \"orange\",\n                  2: \"yellow\",\n                  3: \"magenta\",\n                  4: \"brown\"\n                  }\n        ax = plt.subplot(2, 2, 1)\n        Xb0 = self.BgInitialProfile.to1DvarVect()\n        Y = self.pTrue.myProfile[\"P\"]\n        pression = Y\n        print (\"pression\")\n        for k in range(0, pression.shape[0]):\n            print (\"%.2f\" % pression[k])\n        ax.set_ylim((pression[-1] + 30, pression[0]))\n        ax.set_yscale(\"log\")\n        ax.plot(self.Xt[:54], Y, color=\"black\", label=\"T true\")\n        ax.plot(Xb0[:54], Y, color=\"blue\", label=\"T background\")\n        for k in range(len(self.retrievedVectors)):\n            ax.plot(self.retrievedVectors[k][\n                    :54], Y, color=\"red\", label=\"T retrieved step \" + str(k))\n        ax.plot(self.Xt[85], Y[-1] + 20, color=\"black\",\n                marker=\"*\", label=\"T skin True\")\n        ax.plot(Xb0[85], Y[-1] + 20, color=\"blue\",\n                marker=\"*\", label=\"T skin background\")\n        for k in range(len(self.retrievedVectors)):\n            ax.plot(self.retrievedVectors[k][85],\n                    Y[-1] + 20, color=\"red\", marker=\"*\",\n                    label=\"T skin retrieved step\" + str(k))\n        ax.legend(prop={'size': 10}, shadow=True, fancybox=True, loc='best')\n        ax = plt.subplot(2, 2, 2)\n\n        pression = Y[:29]\n        print(pression.shape)\n\n        ax.set_ylim((pression[-1], pression[0]))\n        ax.set_yscale(\"log\")\n\n        ax.plot(self.Xt[54:83], pression, color=\"black\", label=\"Q true\")\n        ax.plot(Xb0[54:83], pression, color=\"blue\", label=\"Q background\")\n        print \"q true\"\n        print self.Xt[54:83]\n        print \"Q initial\"\n        print Xb0[54:83]\n        for k in range(len(self.retrievedVectors)):\n            ax.plot(self.retrievedVectors[k][54:83], pression, color=colors[\n                    k], label=\"Q retrieved step \" + str(k))\n            print \"Q retrieved k\", k\n            print self.retrievedVectors[k][54:83]\n        ax.legend(prop={'size': 10}, shadow=True, fancybox=True, loc='best')\n\n        ax = plt.subplot(2, 2, 3)\n        if len(self.Y_Xb.shape) == 0:\n            nbchannels = 1\n        else:\n            nbchannels = self.Y_Xb.shape[0]\n\n        channels = np.arange(1, nbchannels + 1)\n\n        print(self.Y_Xb.shape)\n        print(channels.shape)\n        ax.plot(channels, self.Y_Xt, color=\"black\", label=\"BT True\")\n        ax.plot(channels, self.Y_Xb, color=\"blue\", label=\"BT Background\")\n        ax.plot(channels, self.Y_Xt + self.N,\n                color=\"yellow\", label=\"BT True+Noise\")\n        ax.legend(prop={'size': 10}, shadow=True, fancybox=True, loc='best')\n        plt.title(self.satellite + \" \" + self.instrument)\n        plt.show()\n\n\nclass Bmatrix(object):\n    \"\"\" Class for dealing with the background error covariance\n        matrices used by the 1DVar sheme \"\"\"\n\n    def __init__(self):\n        self.matrices = {}\n        self.header = {}\n        self.dimension = {}\n\n    def _read(self, f, dim=86):\n\n        data = np.zeros((dim * dim), dtype=np.float64)\n        indice = 0\n        while indice < dim * dim:\n            lin = f.readline().split()\n            for value_str in lin:\n                data[indice] = np.float64(value_str)\n                indice = indice + 1\n        return data.reshape(dim, dim)\n\n    def read_matrices(self, filename):\n        f = open(filename)\n        for j in (1, 2, 3, 4):\n            self.header[j] = []\n            for i in (0, 1, 3):\n                k = f.readline()\n                self.header[j].append(k)\n            self.dimension[j] = int(k)\n            self.matrices[j] = self._read(f, dim=self.dimension[j])\n\n            # convert lnq g/kg in ppmv for Q\n            dim = self.dimension[j]\n            for k in range(dim - 29 - 3, dim - 3):\n                for l in range(dim - 29 - 3, dim - 3):\n                    self.matrices[j][k, l] = q_mixration_to_ppmv * \\\n                        np.exp(self.matrices[j][k, l]) * 0.001\n            self.matrices[j][dim - 2, dim - 2] = q_mixration_to_ppmv * \\\n                np.exp(self.matrices[j][dim - 2, dim - 2]) * 0.001\n\n        f.close()\n\n    def plot(self, j):\n        print \"Bmatrice :\", j\n        print self.matrices[j]\n\n        plt.imshow(self.matrices[j], origin=\"lower\", interpolation=\"nearest\")\n        plt.title(self.header[j][0])\n        plt.colorbar()\n        plt.show()\n\n\nclass RmatrixBase(object):\n    \"\"\" Class for dealing with mesurement error covariance matrix\n        used by the 1DVar scheme \"\"\"\n\n    def __init__(self):\n        pass\n\n    def read(self, filename):\n        pass\n\n\nclass Rmatrix(RmatrixBase):\n\n    def read(self, filename):\n        \"\"\" Rmatrix fila structure is explained  here : \"\"\"\n        \"\"\" https://nwpsaf.eu/deliverables/nwpsaf_1dvar/\n            nwpsaf-mo-ud-032_NWPSAF_1DVar_Manual.html#aux \"\"\"\n        \"\"\" read the entire file : populate a dictionary named Rmatrx with :\"\"\"\n        \"\"\" nchannels : number of channels\"\"\"\n        \"\"\" nband : number of band \"\"\"\n        \"\"\" inverse : \"\"\"\n        \"\"\" type :\"\"\"\n        \"\"\" data : the data\"\"\"\n        \"\"\" finaly with the __mkMatrix method is called to make the Matrix \"\"\"\n        \"\"\" dictionary which will contain numpy arrays \"\"\"\n\n        self.Rmatrix = {}\n        logging.debug(\"open \" + filename)\n        f = open(filename)\n        cond = True\n        while cond:\n            l = f.readline()\n            if len(l) == 0:\n                cond = False\n                continue\n            satint = l.replace(\"\\n\", \"\")\n            logging.debug(\"read\" + str(satint))\n            self.Rmatrix[satint] = {}\n            line = f.readline()\n            self.Rmatrix[satint][\"type\"], self.Rmatrix[satint][\n                \"nchannel\"], self.Rmatrix[\n                    satint][\"nband\"], self.Rmatrix[satint][\"inverse\"] = [\n                        int(x) for x in line.split()]\n            logging.debug(str(self.Rmatrix[satint][\"type\"]) +\n                          str(self.Rmatrix[satint][\"nchannel\"]) +\n                          str(self.Rmatrix[satint][\"nband\"]) +\n                          str(self.Rmatrix[satint][\"inverse\"]))\n            if self.Rmatrix[satint][\"type\"] == 2:\n                self.Rmatrix[satint][\"channel\"] = []\n                self.Rmatrix[satint][\"data\"] = {}\n                while (len(self.Rmatrix[satint][\"channel\"]) <\n                       self.Rmatrix[satint][\"nchannel\"]):\n                    l = f.readline().split()\n                    for x in l:\n                        self.Rmatrix[satint][\"channel\"].append(int(x))\n                for band in range(self.Rmatrix[satint][\"nband\"]):\n                    self.Rmatrix[satint][\"data\"][band] = []\n                    while (len(self.Rmatrix[satint][\"data\"][band]) <\n                           self.Rmatrix[satint][\"nchannel\"]):\n                        l = f.readline().split()\n                        for x in l:\n                            self.Rmatrix[satint][\"data\"][band].append(float(x))\n                logging.debug(\"end\")\n            else:\n                logging.debug('cannot read matrix')\n                cond = False\n        self._mkMatrix()\n\n    def _mkMatrix(self):\n        \"\"\" create the matrix from the data read \"\"\"\n        logging.debug(\"create the matrix\")\n        for satint in self.Rmatrix.keys():\n            logging.debug(\"create the matrix for satellite\" + satint +\n                          str(self.Rmatrix[satint][\"type\"]) +\n                          str(self.Rmatrix[satint][\"nband\"]))\n            self.Rmatrix[satint][\"matrix\"] = np.zeros(\n                (self.Rmatrix[satint][\"nchannel\"],\n                 self.Rmatrix[satint][\"nchannel\"]), dtype=float)\n            if (\n                    self.Rmatrix[satint][\"type\"] == 2 and\n                    self.Rmatrix[satint][\"nband\"] == 1):\n                for i in range(self.Rmatrix[satint][\"nchannel\"]):\n                    self.Rmatrix[satint][\"matrix\"][\n                        i, i] = self.Rmatrix[satint][\"data\"][0][i]\n\n            if (\n                    self.Rmatrix[satint][\"type\"] == 2 and\n                    self.Rmatrix[satint][\"nband\"] != 1):\n                # diagonal case\n                for i in range(self.Rmatrix[satint][\"nchannel\"]):\n                    self.Rmatrix[satint][\"matrix\"][\n                        i, i] = self.Rmatrix[satint][\"data\"][0][i]\n\n                for band in range(1, self.Rmatrix[satint][\"nband\"]):\n                    logging.debug(\"band\" + str(band))\n\n                    for i in range(0, self.Rmatrix[satint][\"nchannel\"] - band):\n                        self.Rmatrix[satint][\"matrix\"][\n                            i + band, i] = self.Rmatrix[satint][\"data\"][band][\n                            i]\n                        self.Rmatrix[satint][\"matrix\"][\n                            i, i + band] = self.Rmatrix[satint][\"data\"][band][\n                            i]\n\n    def plot_matrix(self):\n        for satint in self.Rmatrix.keys():\n            plt.imshow(self.Rmatrix[satint][\"matrix\"],\n                       origin=\"upper\", interpolation=\"nearest\")\n            plt.title(satint)\n            plt.colorbar()\n            plt.show()\n\n\nclass Nwpsaf1dvarProfile(object):\n\n    def __init__(self):\n        self.data = {}\n\n    def toRttovGuiProfile(self):\n        \"\"\" convert Background to profile \"\"\"\n\n        self.profile = rmodel.project.pProfile()\n        self.option = rmodel.project.pOption()\n        self.option.default()\n        self.profile.setDefaultAttributes()\n        self.profile[\"NLEVELS\"] = self.data[\"P\"][::-1].shape[0]\n        self.profile[\"LAYERS\"] = self.profile[\"NLEVELS\"] - 1\n        self.profile[\"P\"] = self.data[\"P\"][::-1]\n        self.profile[\"T\"] = self.data[\"T\"][::-1]\n        self.profile[\"Q\"] = self.data[\"Q\"][::-1]\n        self.profile[\"O3\"] = self.data[\"O3\"][::-1]\n        self.profile[\"S2M\"][\"T\"] = self.data[\"Surface Temperature (K)\"]\n        self.profile[\"SKIN\"][\"T\"] = self.data[\"Skin Temperature (K)\"]\n        for k, v in self.data.items():\n            if k.startswith(\"Surface Humidity\"):\n                self.profile[\"S2M\"][\"Q\"] = v\n        self.profile[\"S2M\"][\"U\"] = self.data[\"10m U-Wind (m/s)\"]\n        self.profile[\"S2M\"][\"V\"] = self.data[\"10m U-Wind (m/s)\"]\n        self.profile[\"S2M\"][\"P\"] = self.data[\"Surface Pressure (hPa)\"]\n        self.profile.setDefaultProfileAsciiInput()\n        return self.profile\n\n\nclass RetrievedProfile(object):\n    \"\"\" class for dealing with 1D var ascii Retrieved_Profile files\n        from the NWPDAF 1DVAR software \"\"\"\n    \"\"\" read them and transform it in profile object \"\"\"\n\n    def __init__(self):\n        self.retrieved = Nwpsaf1dvarProfile()\n        self.background = Nwpsaf1dvarProfile()\n        self.header = {}\n\n    def read(self, filename):\n        data = np.genfromtxt(filename, skip_header=3, skip_footer=8)\n        self.retrieved.data[\"P\"] = data[:, 0]\n        self.retrieved.data[\"T\"] = data[:, 1]\n        self.retrieved.data[\"Q\"] = data[:, 2]\n        self.retrieved.data[\"O3\"] = data[:, 3]\n        self.background.data[\"P\"] = data[:, 0]\n        self.background.data[\"T\"] = data[:, 4]\n        self.background.data[\"Q\"] = data[:, 5]\n        self.background.data[\"O3\"] = data[:, 5]\n\n    def plot(self):\n        colors = {0: \"red\",\n                  1: \"orange\",\n                  2: \"yellow\",\n                  3: \"magenta\",\n                  4: \"brown\"\n                  }\n        ax = plt.subplot(2, 2, 1)\n        Xb = self.background\n        Xr = self.retrieved\n\n        Y = self.background.data[\"P\"][:]\n        pression = Y\n        print (\"pression\")\n        for k in range(0, pression.shape[0]):\n            print (\"%.2f\" % pression[k])\n        ax.set_ylim((pression[0] + 30, pression[-1]))\n        ax.set_yscale(\"log\")\n        ax.plot(Xb.data[\"T\"], Y, color=\"blue\", label=\"T background\")\n        ax.plot(Xr.data[\"T\"], Y, color=\"red\", label=\"T retrieved\")\n\n        ax.legend(prop={'size': 10}, shadow=True, fancybox=True, loc='best')\n        ax = plt.subplot(2, 2, 2)\n        ax.set_ylim((pression[0] + 30, pression[-1]))\n\n        ax.set_yscale(\"log\")\n\n        ax.plot(Xb.data[\"Q\"], pression, color=\"blue\", label=\"Q background\")\n\n        ax.plot(Xr.data[\"Q\"], pression, color=\"red\", label=\"Q retrieved  \")\n\n        ax.legend(prop={'size': 10}, shadow=True, fancybox=True, loc='best')\n\n        plt.show()\n\n\nclass Background(object):\n    \"\"\" class for dealing with 1D var ascii Backround files from the\n        NWPDAF 1DVAR software \"\"\"\n    \"\"\" read them and transform it in profile object \"\"\"\n\n    def __init__(self):\n        self.prof = Nwpsaf1dvarProfile()\n        self.data = {}\n        self.header = {}\n\n    def read(self, filename):\n        data = np.genfromtxt(filename, skip_header=16, skip_footer=6)\n\n        self.data[\"P\"] = data[:, 0]\n        self.data[\"T\"] = data[:, 1]\n        self.data[\"Q\"] = data[:, 2]\n        self.data[\"O3\"] = data[:, 3]\n        self.nlevels = data.shape[0]\n\n        labels = np.genfromtxt(\n            filename, usecols=0, dtype=str, skip_header=16 + data.shape[0],\n            delimiter=\":\")\n        raw_data = np.genfromtxt(\n            filename, skip_header=16 + data.shape[0], delimiter=\":\")[:, 1:]\n\n        self.data_surf = {label: row for label,\n                          row in zip(labels, raw_data[:, 0])}\n        for key in (\"P\", \"Q\", \"T\", \"O3\"):\n            self.prof.data[key] = self.data[key]\n        self.prof.data[\"Surface Temperature (K)\"] = self.data_surf[\n            \"Surface Temperature (K)\"]\n        self.prof.data[\"Skin Temperature (K)\"] = self.data_surf[\n            \"Skin Temperature (K)\"]\n        self.prof.data[\"10m U-Wind (m/s)\"] = self.data_surf[\"10m U-Wind (m/s)\"]\n        self.prof.data[\"10m U-Wind (m/s)\"] = self.data_surf[\"10m U-Wind (m/s)\"]\n        self.prof.data[\"Surface Pressure (hPa)\"] = self.data_surf[\n            \"Surface Pressure (hPa)\"]\n\n    def toProfile(self):\n        return self.prof.toRttovGuiProfile()\n\n    def print_data(self):\n        print (\"P\")\n        print (self.data[\"P\"])\n        print (\"T\")\n        print (self.data[\"T\"])\n        print (\"Q\")\n        print (self.data[\"Q\"])\n        print (\"O3\")\n        print (self.data[\"P\"])\n        print (self.data_surf)\n\n\nif __name__ == '__main__':\n\n    rmatrixfilename = \"./data/IASI_COEFFS_DIR/Rmatrix_orig\"\n\n    print (\"rmatrixfilename\")\n    R = Rmatrix()\n    R.read(rmatrixfilename)\n    R.plot_matrix()\n", "meta": {"hexsha": "1a2c6d080daf533775c54240529b2612d708e873", "size": 37287, "ext": "py", "lang": "Python", "max_stars_repo_path": "source/gui/r1Dvar/r1dvar.py", "max_stars_repo_name": "bucricket/projectMAScorrection", "max_stars_repo_head_hexsha": "89489026c8e247ec7c364e537798e766331fe569", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/gui/r1Dvar/r1dvar.py", "max_issues_repo_name": "bucricket/projectMAScorrection", "max_issues_repo_head_hexsha": "89489026c8e247ec7c364e537798e766331fe569", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-12T12:19:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T12:19:59.000Z", "max_forks_repo_path": "source/gui/r1Dvar/r1dvar.py", "max_forks_repo_name": "bucricket/projectMAScorrection", "max_forks_repo_head_hexsha": "89489026c8e247ec7c364e537798e766331fe569", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1367061356, "max_line_length": 79, "alphanum_fraction": 0.5375063695, "include": true, "reason": "import numpy", "num_tokens": 9104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.19465798294329376}}
{"text": "# pulsar.py\n\n# Class containing pulsar data from timing package [tempo2/PINT].\n\nfrom __future__ import (absolute_import, division,\n                        print_function, unicode_literals)\n\nimport enterprise\nimport numpy as np\nfrom ephem import Ecliptic, Equatorial\nimport os\nimport json\nfrom enterprise.signals import utils\nimport logging\n\ntry:\n    import cPickle as pickle\nexcept:\n    import pickle\n\ntry:\n    import libstempo as t2\nexcept ImportError:\n    print('Ooh, no libstempo?')\n    t2 = None\n\ntry:\n    import pint\n    import pint.toa as toa\n    import pint.models.model_builder as mb\n    from pint.models import TimingModel\n    from pint.residuals import Residuals as resids\nexcept ImportError:\n    print('Cannot import PINT? Meh...')\n    pint = None\n\nimport astropy.units as u\n\nif pint is None and t2 is None:\n    err_msg = 'Must have either PINT or libstempo timing package installed'\n    raise ImportError(err_msg)\n\nlogging.basicConfig(format='%(levelname)s: %(name)s: %(message)s',\n                    level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\ndef get_maxobs(timfile):\n    \"\"\"Utility function to return number of lines in tim file.\n\n    :param timfile:\n        Full path to tim-file. For tim-files that use INCLUDEs this\n        should be the base tim file.\n\n    :returns: Number of lines in tim-file\n    \"\"\"\n\n    maxobs = 0\n    with open(timfile) as tfile:\n        flines = tfile.readlines()\n        lines = [ln for ln in flines if not ln.startswith('C')]\n        if any(map(lambda x: 'INCLUDE' in x, lines)):\n            for line in filter(lambda x: 'INCLUDE' in x, lines):\n                maxobs += get_maxobs(line.split()[-1])\n        else:\n            maxobs = sum(1 for line in lines if line.rstrip('\\n'))\n    return maxobs\n\n\nclass BasePulsar(object):\n    \"\"\"Abstract Base Class for Pulsar objects.\"\"\"\n\n    def _get_pdist(self):\n        dfile = enterprise.__path__[0] + '/datafiles/pulsar_distances.json'\n        with open(dfile, 'r') as fl:\n            pdict = json.load(fl)\n\n        if self.name[0] not in ['J', 'B']:\n            if 'J' + self.name in pdict:\n                pdist = tuple(pdict.get('J'+self.name))\n            elif 'B' + self.name in pdict:\n                pdist = tuple(pdict.get('B'+self.name))\n        else:\n            pdist = tuple(pdict.get(self.name, (1.0, 0.2)))\n\n        if pdist == (1.0, 0.2):\n            msg = 'WARNING: Could not find pulsar distance for '\n            msg += 'PSR {0}.'.format(self.name)\n            msg += ' Setting value to 1 with 20% uncertainty.'\n            logger.warning(msg)\n        return pdist\n\n    def _get_radec_from_ecliptic(self, elong, elat):\n        # convert via pyephem\n        try:\n            ec = Ecliptic(elong, elat)\n\n            # check for B name\n            if 'B' in self.name:\n                epoch = '1950'\n            else:\n                epoch = '2000'\n            eq = Equatorial(ec, epoch=str(epoch))\n            raj = np.double(eq.ra)\n            decj = np.double(eq.dec)\n\n        except TypeError:\n            msg = 'WARNING: Cannot fine sky location coordinates '\n            msg += 'for PSR {0}. '.format(self.name)\n            msg += 'Setting values to 0.0'\n            logger.warning(msg)\n            raj = 0.0\n            decj = 0.0\n\n        return raj, decj\n\n    def _get_pos(self):\n        return np.array([np.cos(self._raj) * np.cos(self._decj),\n                         np.sin(self._raj) * np.cos(self._decj),\n                         np.sin(self._decj)])\n\n    def sort_data(self):\n        \"\"\"Sort data by time.\"\"\"\n        if self._sort:\n            self._isort = np.argsort(self._toas, kind='mergesort')\n            self._iisort = np.zeros(len(self._isort), dtype=np.int)\n            for ii, p in enumerate(self._isort):\n                self._iisort[p] = ii\n        else:\n            self._isort = slice(None, None, None)\n            self._iisort = slice(None, None, None)\n\n    def filter_data(self, start_time=None, end_time=None):\n        \"\"\"Filter data to create a time-slice of overall dataset.\"\"\"\n        if start_time is None and end_time is None:\n            mask = np.ones(self._toas.shape, dtype=bool)\n        else:\n            mask = np.logical_and(self._toas >= start_time * 86400,\n                                  self._toas <= end_time * 86400)\n\n        self._toas = self._toas[mask]\n        self._toaerrs = self._toaerrs[mask]\n        self._residuals = self._residuals[mask]\n        self._ssbfreqs = self._ssbfreqs[mask]\n\n        self._designmatrix = self._designmatrix[mask, :]\n        dmx_mask = np.sum(self._designmatrix, axis=0) != 0.0\n        self._designmatrix = self._designmatrix[:, dmx_mask]\n\n        for key in self._flags:\n            self._flags[key] = self._flags[key][mask]\n\n        if self._planetssb is not None:\n            self._planetssb = self.planetssb[mask, :, :]\n\n        self.sort_data()\n\n    def to_pickle(self, outdir=None):\n        \"\"\"Save object to pickle file.\"\"\"\n\n        # drop t2pulsar object\n        if hasattr(self, 't2pulsar'):\n            del self.t2pulsar\n\n        if outdir is None:\n            outdir = os.getcwd()\n\n        if not os.path.exists(outdir):\n            os.makedirs(outdir)\n\n        with open(outdir + '/{0}.pkl'.format(self.name), 'wb') as f:\n            pickle.dump(self, f)\n\n    @property\n    def isort(self):\n        \"\"\"Return sorting indices.\"\"\"\n        return self._isort\n\n    @property\n    def iisort(self):\n        \"\"\"Return inverse of sorting indices.\"\"\"\n        return self._iisort\n\n    @property\n    def toas(self):\n        \"\"\"Return array of TOAs in seconds.\"\"\"\n        return self._toas[self._isort]\n\n    @property\n    def stoas(self):\n        \"\"\"Return array of observatory TOAs in seconds.\"\"\"\n        return self._stoas[self._isort]\n\n    @property\n    def residuals(self):\n        \"\"\"Return array of residuals in seconds.\"\"\"\n        return self._residuals[self._isort]\n\n    @property\n    def toaerrs(self):\n        \"\"\"Return array of TOA errors in seconds.\"\"\"\n        return self._toaerrs[self._isort]\n\n    @property\n    def freqs(self):\n        \"\"\"Return array of radio frequencies in MHz.\"\"\"\n        return self._ssbfreqs[self._isort]\n\n    @property\n    def Mmat(self):\n        \"\"\"Return ntoa x npar design matrix.\"\"\"\n        return self._designmatrix[self._isort, :]\n\n    @property\n    def pdist(self):\n        \"\"\"Return tuple of pulsar distance and uncertainty in kpc.\"\"\"\n        return self._pdist\n\n    @property\n    def dm(self):\n        \"\"\"Return DM parameter from parfile.\"\"\"\n        return self._dm\n\n    @property\n    def dmx(self):\n        \"\"\"Return a dictionary of DMX-parameter values and stoa ranges\n        from parfile.\"\"\"\n        return self._dmx\n\n    @property\n    def flags(self):\n        \"\"\"Return a dictionary of tim-file flags.\"\"\"\n\n        return dict((k, v[self._isort]) for k, v in self._flags.items())\n\n    @property\n    def backend_flags(self):\n        \"\"\"Return array of backend flags.\n\n        Not all TOAs have the same flags for all data sets. In order to\n        facilitate this we have a ranked ordering system that will look\n        for flags. The order is `group`, `g`, `sys`, `i`, `f`, `fe`+`be`.\n\n        \"\"\"\n\n        nobs = len(self._toas)\n        bflags = ['flag'] * nobs\n        check = lambda i, fl: fl in self._flags and self._flags[fl][i] != ''\n        flags = [['group'], ['g'], ['sys'], ['i'], ['f'], ['fe', 'be']]\n        for ii in range(nobs):\n            # TODO: make this cleaner\n            for f in flags:\n                if np.all(list(map(lambda xx: check(ii, xx), f))):\n                    bflags[ii] = '_'.join(self._flags[x][ii] for x in f)\n                    break\n        return np.array(bflags)[self._isort]\n\n    @property\n    def theta(self):\n        \"\"\"Return polar angle of pulsar in radians.\"\"\"\n        return np.pi / 2 - self._decj\n\n    @property\n    def phi(self):\n        \"\"\"Return azimuthal angle of pulsar in radians.\"\"\"\n        return self._raj\n\n    @property\n    def pos(self):\n        \"\"\"Return unit vector to pulsar.\"\"\"\n        return self._pos\n\n    @property\n    def pos_t(self):\n        \"\"\"Return unit vector to pulsar as function of time.\"\"\"\n        return self._pos_t[self._isort, :]\n\n    @property\n    def planetssb(self):\n        \"\"\"Return planetary position vectors at all timestamps\"\"\"\n        return self._planetssb[self._isort, :, :]\n\n\nclass PintPulsar(BasePulsar):\n\n    def __init__(self, toas, model, sort=True, planets=True):\n\n        self._sort = sort\n        self.planets = planets\n        self.name = model.PSR.value\n\n        self._toas = np.array(toas.table['tdbld'], dtype='float64') * 86400\n        self._residuals = np.array(resids(toas, model).time_resids.to(u.s),\n                                   dtype='float64')\n        self._toaerrs = np.array(toas.get_errors().to(u.s), dtype='float64')\n        self._designmatrix = model.designmatrix(toas)[0]\n        self._ssbfreqs = np.array(model.barycentric_radio_freq(toas),\n                                  dtype='float64')\n\n        # fitted parameters\n        self.fitpars = ['Offset'] + [par for par in model.params\n                                     if not getattr(model, par).frozen]\n\n        # set parameters\n        spars = [par for par in model.params]\n        self.setpars = [sp for sp in spars if sp not in self.fitpars]\n\n        self._flags = {}\n        for ii, obsflags in enumerate(toas.get_flags()):\n            for jj, flag in enumerate(obsflags):\n\n                if flag not in list(self._flags.keys()):\n                    self._flags[flag] = [''] * toas.ntoas\n\n                self._flags[flag][ii] = obsflags[flag]\n\n        # convert flags to arrays\n        # TODO probably better way to do this\n        for key, val in self._flags.items():\n            if isinstance(val[0], u.quantity.Quantity):\n                self._flags[key] = np.array([v.value for v in val])\n            else:\n                self._flags[key] = np.array(val)\n\n        self._pdist = self._get_pdist()\n        self._raj, self._decj = self._get_radec(model)\n        self._pos = self._get_pos()\n        self._planetssb = self._get_planetssb()\n\n        # TODO: pos_t not currently implemented\n        self._pos_t = np.zeros((len(self._toas), 3))\n\n        self.sort_data()\n\n    def _get_radec(self, model):\n        if hasattr(model, 'RAJ') and hasattr(model, 'DECJ'):\n            return (model.RAJ.value, model.DECJ.value)\n        else:\n            # TODO: better way of dealing with units\n            d2r = np.pi / 180\n            elong, elat = model.ELONG.value, model.ELAT.value\n            return self._get_radec_from_ecliptic(elong*d2r, elat*d2r)\n\n    def _get_planetssb(self):\n        return np.zeros((len(self._toas), 9, 6))\n\n\nclass Tempo2Pulsar(BasePulsar):\n\n    def __init__(self, t2pulsar, sort=True,\n                 drop_t2pulsar=True, planets=True):\n\n        self._sort = sort\n        self.t2pulsar = t2pulsar\n        self.planets = planets\n        self.name = str(t2pulsar.name)\n\n        self._toas = np.double(t2pulsar.toas()) * 86400\n        # saving also stoas (e.g., for DMX comparisons)\n        self._stoas = np.double(t2pulsar.stoas) * 86400\n        self._residuals = np.double(t2pulsar.residuals())\n        self._toaerrs = np.double(t2pulsar.toaerrs) * 1e-6\n        self._designmatrix = np.double(t2pulsar.designmatrix())\n        self._ssbfreqs = np.double(t2pulsar.ssbfreqs()) / 1e6\n\n        # fitted parameters\n        self.fitpars = ['Offset'] + list(map(str, t2pulsar.pars()))\n\n        # set parameters\n        spars = list(map(str, t2pulsar.pars(which='set')))\n        self.setpars = [sp for sp in spars if sp not in self.fitpars]\n\n        self._flags = {}\n        for key in t2pulsar.flags():\n            self._flags[key] = t2pulsar.flagvals(key)\n\n        self._pdist = self._get_pdist()\n        self._raj, self._decj = self._get_radec(t2pulsar)\n        self._pos = self._get_pos()\n        self._planetssb = self._get_planetssb(t2pulsar)\n\n        # gather DM/DMX information if available\n        self._set_dm(t2pulsar)\n\n        self._pos_t = t2pulsar.psrPos.copy()\n        if 'ELONG' and 'ELAT' in np.concatenate((t2pulsar.pars(which='fit'),\n                                                 t2pulsar.pars(which='set'))):\n            self._pos_t = utils.ecl2eq_vec(self._pos_t)\n\n        self.sort_data()\n\n        if drop_t2pulsar:\n            del self.t2pulsar\n\n    # gather DM/DMX information if available\n    def _set_dm(self, t2pulsar):\n        pars = t2pulsar.pars(which='set')\n\n        if 'DM' in pars:\n            self._dm = t2pulsar['DM'].val\n\n        dmx = {par: {'DMX': t2pulsar[par].val,\n                     'DMXerr': t2pulsar[par].err,\n                     'DMXR1': t2pulsar[par[:3] + 'R1' + par[3:]].val,\n                     'DMXR2': t2pulsar[par[:3] + 'R2' + par[3:]].val,\n                     'fit': par in pars}\n               for par in pars if 'DMX_' in par}\n\n        if dmx:\n            self._dmx = dmx\n\n    def _get_radec(self, t2pulsar):\n        if 'RAJ' in np.concatenate((t2pulsar.pars(which='fit'),\n                                    t2pulsar.pars(which='set'))):\n            return (np.double(t2pulsar['RAJ'].val),\n                    np.double(t2pulsar['DECJ'].val))\n\n        else:\n            # use ecliptic coordinates\n            elong = t2pulsar['ELONG'].val\n            elat = t2pulsar['ELAT'].val\n            return self._get_radec_from_ecliptic(elong, elat)\n\n    def _get_planetssb(self, t2pulsar):\n        planetssb = None\n        if self.planets:\n            for ii in range(1, 10):\n                tag = 'DMASSPLANET' + str(ii)\n                self.t2pulsar[tag].val = 0.0\n            self.t2pulsar.formbats()\n            planetssb = np.zeros((len(self._toas), 9, 6))\n            planetssb[:, 0, :] = self.t2pulsar.mercury_ssb\n            planetssb[:, 1, :] = self.t2pulsar.venus_ssb\n            planetssb[:, 2, :] = self.t2pulsar.earth_ssb\n            planetssb[:, 3, :] = self.t2pulsar.mars_ssb\n            planetssb[:, 4, :] = self.t2pulsar.jupiter_ssb\n            planetssb[:, 5, :] = self.t2pulsar.saturn_ssb\n            planetssb[:, 6, :] = self.t2pulsar.uranus_ssb\n            planetssb[:, 7, :] = self.t2pulsar.neptune_ssb\n            planetssb[:, 8, :] = self.t2pulsar.pluto_ssb\n\n            if 'ELONG' and 'ELAT' in np.concatenate((t2pulsar.pars(),\n                                                     t2pulsar.pars(\n                                                         which='set'))):\n                for ii in range(9):\n                    planetssb[:,ii,:3] = utils.ecl2eq_vec(planetssb[:,ii,:3])\n                    planetssb[:,ii,3:] = utils.ecl2eq_vec(planetssb[:,ii,3:])\n        return planetssb\n\n\ndef Pulsar(*args, **kwargs):\n\n    ephem = kwargs.get('ephem', None)\n    clk = kwargs.get('clk', None)\n    planets = kwargs.get('planets', True)\n    sort = kwargs.get('sort', True)\n    drop_t2pulsar = kwargs.get('drop_t2pulsar', True)\n    timing_package = kwargs.get('timing_package', 'tempo2')\n\n    if pint is not None:\n        toas = list(filter(lambda x: isinstance(x, toa.TOAs), args))\n        model = list(filter(lambda x: isinstance(x, TimingModel), args))\n\n    if t2 is not None:\n        t2pulsar = list(filter(lambda x: isinstance(x, t2.tempopulsar), args))\n\n    parfile = list(filter(lambda x: isinstance(x, str) and\n                          x.split('.')[-1] == 'par', args))\n    timfile = list(filter(lambda x: isinstance(x, str) and\n                          x.split('.')[-1] in ['tim', 'toa'], args))\n\n    if pint and toas and model:\n        return PintPulsar(toas[0], model[0], sort=sort, planets=planets)\n    elif t2 and t2pulsar:\n        return Tempo2Pulsar(t2pulsar[0], sort=sort,\n                            drop_t2pulsar=drop_t2pulsar,\n                            planets=planets)\n    elif parfile and timfile:\n        # Check whether the two files exist\n        if not os.path.isfile(parfile[0]) or not os.path.isfile(timfile[0]):\n            msg = 'Cannot find parfile {0} or timfile {1}!'.format(\n                parfile[0], timfile[0])\n            raise IOError(msg)\n\n        # Obtain the directory name of the timfile, and change to it\n        timfiletup = os.path.split(timfile[0])\n        dirname = timfiletup[0] or './'\n        reltimfile = timfiletup[-1]\n        relparfile = os.path.relpath(parfile[0], dirname)\n\n        # get current directory\n        cwd = os.getcwd()\n\n        # Change directory to the base directory of the tim-file to deal with\n        # INCLUDE statements in the tim-file\n        os.chdir(dirname)\n\n        if timing_package.lower() == 'pint':\n            if ephem is None:\n                ephem = 'DE421'\n            if clk is None:\n                bipm_version = 'BIPM2015'\n            else:\n                bipm_version = clk.split('(')[1][:-1]\n            toas = toa.get_TOAs(reltimfile, ephem=ephem, planets=planets,\n                                bipm_version=bipm_version)\n            model = mb.get_model(relparfile)\n            os.chdir(cwd)\n            return PintPulsar(toas, model, sort=sort, planets=planets)\n\n        elif timing_package.lower() == 'tempo2':\n\n            # hack to set maxobs\n            maxobs = get_maxobs(reltimfile) + 100\n            t2pulsar = t2.tempopulsar(relparfile, reltimfile,\n                                      maxobs=maxobs, ephem=ephem, clk=clk)\n            os.chdir(cwd)\n            return Tempo2Pulsar(t2pulsar, sort=sort,\n                                drop_t2pulsar=drop_t2pulsar,\n                                planets=planets)\n    else:\n        print('Unknown arguments {}'.format(args))\n", "meta": {"hexsha": "8aa29a0896fcc40c4020f3de9689154ffb2742a8", "size": 17517, "ext": "py", "lang": "Python", "max_stars_repo_path": "enterprise/pulsar.py", "max_stars_repo_name": "stevertaylor/enterprise", "max_stars_repo_head_hexsha": "a18bc0e2535bf50cc5cc74a346f7f50ccfe4727f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-10-10T15:24:16.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-10T18:05:32.000Z", "max_issues_repo_path": "enterprise/pulsar.py", "max_issues_repo_name": "potatoxia/enterprise", "max_issues_repo_head_hexsha": "bd12f4165827e83dda8daedd20c6b2194cb90158", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-03-20T18:46:48.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-20T18:46:48.000Z", "max_forks_repo_path": "enterprise/pulsar.py", "max_forks_repo_name": "stevertaylor/enterprise", "max_forks_repo_head_hexsha": "a18bc0e2535bf50cc5cc74a346f7f50ccfe4727f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-30T12:22:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-30T12:22:27.000Z", "avg_line_length": 33.4933078394, "max_line_length": 78, "alphanum_fraction": 0.5611120626, "include": true, "reason": "import numpy,import astropy", "num_tokens": 4679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.34864512179822543, "lm_q1q2_score": 0.19465798294329373}}
{"text": "#################################################################################\n# Copyright (c) 2011-2013, Pacific Biosciences of California, Inc.\n#\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# * Redistributions of source code must retain the above copyright\n#   notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n#   notice, this list of conditions and the following disclaimer in the\n#   documentation and/or other materials provided with the distribution.\n# * Neither the name of Pacific Biosciences nor the names of its\n#   contributors may be used to endorse or promote products derived from\n#   this software without specific prior written permission.\n#\n# NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY\n# THIS LICENSE.  THIS SOFTWARE IS PROVIDED BY PACIFIC BIOSCIENCES AND ITS\n# CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PACIFIC BIOSCIENCES OR\n# ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#################################################################################\n\nfrom math import sqrt\nimport math\nimport scipy.stats as s\nimport array as a\nimport sys\n\nfrom numpy import log, pi, log10, e, log1p, exp\nimport numpy as np\nimport re\n\nlog10e = log10(e)\n\ncanonicalBaseMap = {'A': 'A', 'C': 'C', 'G': 'G', 'T': 'T', 'H': 'A', 'I': 'C', 'J': 'C', 'K': 'C'}\nmodNames = {'H': 'm6A', 'I': 'm5C', 'J': 'm4C', 'K': 'm5C'}\n\nm5CCode = 'I'\n\niupacMap = {\n    'A': 'A',\n    'C': 'C',\n    'G': 'G',\n    'T': 'T',\n    'K': 'GT',\n    'M': 'AC',\n    'R': 'AG',\n    'Y': 'CT',\n    'S': 'CG',\n    'W': 'AT',\n    'B': 'CGT',\n    'D': 'AGT',\n    'H': 'ACT',\n    'V': 'ACG',\n    'N': 'ACGT'\n}\n\n\ndef findMotifPositions(seq, motifs):\n    regexs = []\n\n    # Generate a regex for each motif, honouring degenerate bases\n    for m in motifs:\n        regex = ''\n\n        for c in m:\n            regex = regex + \"[\" + iupacMap[c] + \"]\"\n\n        regexs.append(regex)\n\n    allMatches = []\n\n    # Return a list of matching positions in the sequence\n    for r in regexs:\n        rr = re.compile(r)\n        matches = [x.start() for x in rr.finditer(seq)]\n        allMatches.extend(matches)\n\n    allMatches.sort()\n\n    return allMatches\n\n\nclass MultiSiteDetection(object):\n\n    def __init__(self, gbmModel, sequence, rawKinetics, callBounds, methylMinCov, motifs=['CG']):\n        \"\"\"\n\n        \"\"\"\n\n        self.methylMinCov = methylMinCov\n        self.motifs = motifs\n\n        self.gbmModel = gbmModel\n        self.sequence = sequence\n\n        self.callStart = callBounds[0]\n        self.callEnd = callBounds[1]\n\n        # Extents that we will attempt to call a modification\n        self.callRange = xrange(self.callStart, self.callEnd)\n\n        # These switch because we changing viewpoints\n        self.pre = gbmModel.post\n        self.post = gbmModel.pre\n\n        self.lStart = self.pre\n        self.lEnd = len(self.sequence) - self.post\n\n        # Extents that we will use for likelihoods\n        self.likelihoodRange = xrange(self.lStart, self.lEnd)\n\n        self.alternateBases = dict((x, list(sequence[x])) for x in xrange(len(sequence)))\n\n        self.rawKinetics = rawKinetics\n\n    def getConfigs(self, centerIdx):\n        ''' Enumerate all the contexts centered at centerIdx with one\n            modification added '''\n        start = centerIdx - self.pre\n        end = centerIdx + self.post\n        return self._possibleConfigs(start, end)\n\n    def _possibleConfigs(self, start, end):\n        ''' Enumerate all the contexts coming from the substring self.sequence[start,end] with one\n            modification added '''\n\n        if start == end:\n            return self.alternateBases[start]\n        else:\n            r = []\n            allSuffixes = self._possibleConfigs(start + 1, end)\n\n            # The first suffix is alway the one with no modifications\n            # Only add the alternate to that one -- that way we only\n            # get configurations with a single modification, not all combos\n\n            noModsSuffix = allSuffixes[0]\n            if len(allSuffixes) > 1:\n                    restSuffixes = allSuffixes[1:]\n            else:\n                    restSuffixes = []\n\n            # The noMods suffix get the alternates\n            for c in self.alternateBases[start]:\n                    r.append(c + noModsSuffix)\n\n            # the other suffixes already have mods -- they just get the unmodified base\n            for suffix in restSuffixes:\n                    r.append(self.alternateBases[start][0] + suffix)\n\n            return r\n\n        # Compute something for all the windows in [start, end]\n    def getContexts(self, start, end, sequence):\n        contexts = []\n\n        for pos in xrange(start, end + 1):\n            ctx = sequence[(pos - self.pre):(pos + self.post + 1)].tostring()\n            contexts.append(ctx)\n\n        return contexts\n\n    def computeContextMeans(self):\n        \"\"\"Generate a hash of the mean ipd for all candidate contexts\"\"\"\n\n        allContexts = []\n\n        for pos in self.motifPositions:\n            for offsetPos in xrange(pos - self.post, pos + self.pre + 1):\n                cfgs = self.getConfigs(offsetPos)\n                allContexts.extend(cfgs)\n\n        predictions = self.gbmModel.getPredictions(allContexts)\n        self.contextMeanTable = dict(zip(allContexts, predictions))\n\n    def decode(self):\n        \"\"\"Use this method to do the full modification finding protocol\"\"\"\n\n        # Find sites matching the desired motif\n        self.findMotifs()\n\n        # Compute all the required mean ipds under all possible composite hypotheses\n        self.computeContextMeans()\n\n        # Compute a confidence for each mod and return results\n        return self.scorePositions()\n\n    def findMotifs(self):\n        \"\"\" Mark all the positions matching the requested motif \"\"\"\n\n        # Generate list of matching positions\n        allMotifPositions = findMotifPositions(self.sequence, self.motifs)\n        self.motifPositions = []\n\n        for pos in allMotifPositions:\n            # Only use bases that are inside the callBounds\n            if self.callStart <= pos < self.callEnd:\n                self.alternateBases[pos].append('I')\n                self.motifPositions.append(pos)\n\n    def multiSiteDetection(self, positions, nullPred, modPred, centerPosition):\n        ''' kinetics, nullPred, and modifiedPred are parallel arrays \n            containing the observations and predictions surrounding a \n            single candidate motif site.  Estimate the p-value of\n            modification and the modified fraction here'''\n\n        # Apply the error model to the predictions\n        nullErr = 0.01 + 0.03 * nullPred + 0.06 * nullPred ** (1.7)\n        modErr = 0.01 + 0.03 * modPred + 0.06 * modPred ** (1.7)\n\n        obsMean = np.zeros(nullPred.shape)\n        obsErr = np.zeros(nullPred.shape)\n\n        # Get the observations into the same array format\n        for i in xrange(len(positions)):\n            position = positions[i]\n\n            if position in self.rawKinetics:\n                siteObs = self.rawKinetics[position]\n                obsMean[i] = siteObs['tMean']\n                obsErr[i] = siteObs['tErr']\n            else:\n                # Crank up the variance -- we don't have an observation at this\n                # position, so we should ignore it.\n                obsMean[i] = 0.0\n                obsErr[i] = 999999999\n\n        # Subtract off the background model from the observations and the modified prediction\n        dObs = obsMean - nullPred\n        # Error of observation and prediction are uncorrelated\n        obsSigma = obsErr ** 2 + nullErr ** 2\n        invObsSigma = 1.0 / obsSigma\n\n        # Error of null prediction and mod prediction are probably correlated -- need a better estimate of the error of the difference!!\n        dPred = modPred - nullPred\n        dPredSigma = (obsErr ** 2 + nullErr ** 2) / 2  # Just stubbing in a factor of 2 here...\n\n        weightsNumerator = invObsSigma * dPred\n        weights = weightsNumerator / (dPred * weightsNumerator).sum()\n\n        signalEstimate = (weights * dObs).sum()\n        varianceEstimate = (np.abs(weights) * obsSigma).sum()\n\n        maxSignal = (weights * dPred).sum()\n        maxSignalVariance = (np.abs(weights) * dPredSigma).sum()\n\n        # Now just run the standard erf on this Gaussian to quantify the probability that there is some signal\n        # What we want now:\n        #\n        # 1. p-value that dObs * dPred (dot product) is greater than 0.\n        # 2. Distribution of \\alpha, where dObs = \\alpha dPred, where \\alpha \\in [0,1], with appropriate error propagation\n        # 2a. Is it possible to summarize 2 with a Beta distribution?\n\n        pvalue = s.norm._cdf(-signalEstimate / varianceEstimate)\n        pvalue = max(sys.float_info.min, pvalue)\n        score = -10.0 * log10(pvalue)\n\n        centerPosition['MSscore'] = score\n        centerPosition['MSpvalue'] = pvalue\n\n        centerPosition['signal'] = signalEstimate\n        centerPosition['variance'] = varianceEstimate\n\n        centerPosition['modelSignal'] = maxSignal\n        centerPosition['modelVariance'] = maxSignalVariance\n\n        centerPosition['Mask'] = []\n\n        return centerPosition\n\n    def scorePositions(self):\n        \"\"\"\n        Score each motif site in the sequence.\n        \"\"\"\n\n        qvModCalls = dict()\n\n        dnaSeq = a.array('c')\n        dnaSeq.fromstring(self.sequence)\n\n        for pos in self.motifPositions:\n            if pos in self.rawKinetics:\n\n                # Fetch unmodified positions\n                nullPred = self.getRegionPredictions(pos - self.post, pos + self.pre, dnaSeq)\n\n                # Fetch modified positions and reset sequence\n                originalBase = dnaSeq[pos]\n                dnaSeq[pos] = m5CCode\n                modifiedPred = self.getRegionPredictions(pos - self.post, pos + self.pre, dnaSeq)\n                dnaSeq[pos] = originalBase\n\n                # Position that contribute to this call\n                positions = xrange(pos - self.post, pos + self.pre + 1)\n\n                # Run the multi-site detection and save the results\n                centerStats = self.rawKinetics[pos]\n                centerStats = self.multiSiteDetection(positions, nullPred, modifiedPred, centerStats)\n\n                qvModCalls[pos] = centerStats\n\n        return qvModCalls\n\n    def getRegionPredictions(self, start, end, sequence):\n        predictions = np.zeros(end - start + 1)\n\n        for pos in xrange(start, end + 1):\n            ctx = sequence[(pos - self.pre):(pos + self.post + 1)].tostring()\n            predictions[pos - start] = self.contextMeanTable[ctx]\n\n        return predictions\n", "meta": {"hexsha": "96fb4ddd290977822cddf31ccb24e8017f13d605", "size": 11427, "ext": "py", "lang": "Python", "max_stars_repo_path": "SLpackage/private/pacbio/pythonpkgs/kineticstools/lib/python2.7/site-packages/kineticsTools/MultiSiteDetection.py", "max_stars_repo_name": "fanglab/6mASCOPE", "max_stars_repo_head_hexsha": "3f1fdcb7693ff152f17623ce549526ec272698b1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2022-02-20T07:10:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T17:47:53.000Z", "max_issues_repo_path": "SLpackage/private/pacbio/pythonpkgs/kineticstools/lib/python2.7/site-packages/kineticsTools/MultiSiteDetection.py", "max_issues_repo_name": "fanglab/6mASCOPE", "max_issues_repo_head_hexsha": "3f1fdcb7693ff152f17623ce549526ec272698b1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SLpackage/private/pacbio/pythonpkgs/kineticstools/lib/python2.7/site-packages/kineticsTools/MultiSiteDetection.py", "max_forks_repo_name": "fanglab/6mASCOPE", "max_forks_repo_head_hexsha": "3f1fdcb7693ff152f17623ce549526ec272698b1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5981308411, "max_line_length": 136, "alphanum_fraction": 0.6150345673, "include": true, "reason": "import numpy,from numpy,import scipy", "num_tokens": 2664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.19465170062065518}}
{"text": "# Copyright 2020 Arthur Coqué, Guillaume Morin, Pôle OFB-INRAE ECLA, UR RECOVER\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"This module gathers wc algorithms used for estimating SPM concentrations.\n\nEach class of this module correspond to one algorithm. An algorithm can have\nseveral calibrations (a calibration is a set of parameters), either\npackaged within SISPPEO (these default calibrations are located in\n'resources/wc_algo_calibration') or provided by the user.\nBefore its utilisation, an algorithm has to be instantiate with specific\nsettings like the product_type of further input products, the calibration\nused, the band used (if needed), etc.\n\nExample:\n\n    algo1 = SPMNechad('S2_GRS', 'B4', 'Nechad_2016')\n    out_array2 = algo1(input_array, 'rho')\n\n    algo2 = SPMGet('L8_GRS', 'GET_2018')\n    out_array2 = algo2(red_array, nir_array, 'rrs')\n\"\"\"\n\nfrom pathlib import Path\nfrom typing import Optional, Union\n\nimport numpy as np\nimport xarray as xr\n\nfrom sisppeo.utils.algos import load_calib, producttype_to_sat\nfrom sisppeo.utils.config import wc_algo_config as algo_config, wc_calib\nfrom sisppeo.utils.exceptions import InputError\n\n# pylint: disable=invalid-name\n# Ok for a custom type.\nP = Union[str, Path]\nN = Union[int, float]\n\n\ndef _nechad(rho, a, c):\n    ssc = a * rho / (1 - (rho / c))\n    return ssc\n\n\nclass SPMNechad:\n    \"\"\"Semi-analytical algorithm to retrieve SPM concentration (in mg/l) from reflectance.\n\n    Semi-analytical algorithm to retrieve SPM concentrations (in mg/L) from\n    surface reflectances (rho, unitless) or remote sensing reflectances (Rrs,\n    in sr-1).\n    This algorithm was presented in Nechad et al., 2010 and 2016.\n\n    Attributes:\n        name: The name of the algorithm used. This is the key used by\n            L3AlgoBuilder and that you must provide in config or when using\n            the CLI.\n        requested_bands: A list of bands further used by the algorithm.\n        meta: A dict of metadata (calibration name, model coefficients, etc).\n    \"\"\"\n    _default_band = 'B4'\n    _default_calibration_file = wc_calib / 'spm_nechad.yaml'\n    _default_calibration_name = 'Nechad_2016'\n    name = 'spm-nechad'\n\n    def __init__(self,\n                 product_type: str,\n                 requested_band: str = _default_band,\n                 calibration: Optional[P] = None,\n                 **_ignored) -> None:\n        \"\"\"Inits an 'SPMNechad' instance with specific settings.\n\n        Args:\n            product_type: The type of the input satellite product (e.g.\n                S2_ESA_L2A or L8_USGS_L1GT).\n            requested_band: Optional; The band used by the algorithm (\n                default=_default_band).\n            calibration: The calibration (set of parameters) used by the\n                algorithm (default=_default_calibration_name).\n            **_ignored: Unused kwargs sent to trash.\n        \"\"\"\n        self.requested_bands = [requested_band]\n        calibration_dict, calibration_name = load_calib(\n            calibration,\n            self._default_calibration_file,\n            self._default_calibration_name\n        )\n        self._valid_limit = calibration_dict['validity_limit']\n        try:\n            params = calibration_dict[producttype_to_sat(product_type)][\n                requested_band]\n        except KeyError as invalid_input:\n            msg = (f'{product_type} or {requested_band} is not allowed with '\n                   f'{self.name}/this calibration')\n            raise InputError(msg) from invalid_input\n        self.__dict__.update(params)\n        self.meta = {'band': requested_band,\n                     'calibration': calibration_name,\n                     'validity_limit': self._valid_limit,\n                     **params}\n\n    def __call__(self,\n                 rho: xr.DataArray,\n                 data_type: str,\n                 **_ignored) -> xr.DataArray:\n        \"\"\"Runs the algorithm on the input array ('rho').\n\n        Args:\n            rho: An array (dimension 1 * N * M) of 'data_type'.\n            data_type: Either 'rho' or 'rrs' (respectively surface reflectance\n                and remote sensing reflectance).\n            **_ignored: Unused kwargs sent to trash.\n\n        Returns:\n            An array (dimension 1 * N * M) of SPM concentration (in mg/L).\n        \"\"\"\n\n        if data_type == 'rrs':\n            rho = np.pi * rho\n\n        np.warnings.filterwarnings('ignore')\n        # pylint: disable=no-member\n        # Loaded in __init__ with \"__dict__.update\".\n        spm = _nechad(rho, self.a, self.c)\n        spm = spm.where((rho >= 0) & (spm >= 0) & (spm < self._valid_limit))\n        return spm\n\n\nclass SPMHan:\n    \"\"\"Switching Semi-analytical algorithm to retrieve SPM (in mg/l) from reflectance.\n\n    Switching Semi-analytical algorithm to retrieve suspended particulate\n    matter (in mg/l) from surface reflectances (rho, unitless) or remote\n    sensing reflectances (Rrs, in sr-1).\n    This algorithm was published in Han et al., 2016\n\n    Attributes:\n        name: The name of the algorithm used. This is the key used by\n            L3AlgoBuilder and that you must provide in config or when using\n            the CLI.\n        requested_bands: A list of bands further used by the algorithm.\n        meta: A dict of metadata (calibration name, model coefficients, etc).\n    \"\"\"\n    _default_calibration_file = wc_calib / 'spm_han.yaml'\n    _default_calibration_name = 'Han_2016'\n    name = 'spm-han'\n\n    def __init__(self,\n                 product_type: str,\n                 calibration: Optional[P] = None,\n                 **_ignored) -> None:\n        \"\"\"Inits an 'SPMHan' instance with specific settings.\n\n        Args:\n            product_type: The type of the input satellite product (e.g.\n                S2_ESA_L2A or L8_USGS_L1GT)\n            calibration: The calibration (set of parameters) used by the\n                algorithm (default=_default_calibration_name).\n            **_ignored: Unused kwargs sent to trash.\n        \"\"\"\n        try:\n            self.requested_bands = algo_config[self.name][\n                producttype_to_sat(product_type)]\n        except KeyError as invalid_product:\n            msg = f'{product_type} is not allowed with {self.name}'\n            raise InputError(msg) from invalid_product\n        calibration_dict, calibration_name = load_calib(\n            calibration,\n            self._default_calibration_file,\n            self._default_calibration_name\n        )\n        self._valid_limit = calibration_dict['validity_limit']\n        try:\n            params = calibration_dict[producttype_to_sat(product_type)]\n        except KeyError as invalid_product:\n            msg = f'{product_type} is not allowed with this calibration'\n            raise InputError(msg) from invalid_product\n        self.__dict__.update(params)\n        self.meta = {'calibration': calibration_name,\n                     'validity_limit': self._valid_limit,\n                     **params}\n\n    def __call__(self,\n                 refl_red: xr.DataArray,\n                 data_type: str,\n                 **_ignored) -> xr.DataArray:\n        \"\"\"Runs the algorithm on the input array ('rho').\n\n        Args:\n            refl_red: An array (dimension 1 * N * M) of 'data_type'.\n            data_type: Either 'rho' or 'rrs' (respectively surface reflectance\n                and remote sensing reflectance).\n            **_ignored: Unused kwargs sent to trash.\n\n        Returns:\n            An array (dimension 1 * N * M) of SPM concentration (in mg/L).\n        \"\"\"\n        if data_type == 'rho':\n            refl_red = refl_red / np.pi\n            print(data_type)\n\n        np.warnings.filterwarnings('ignore')\n        rrs_red = refl_red.where(refl_red >= 0)\n        # pylint: disable=no-member\n        # Loaded in __init__ whit \"__dict__.update\".\n        spm_low = _nechad(rrs_red, self.a_low, self.c_low)\n        spm_high = _nechad(rrs_red, self.a_high, self.c_high)\n\n        w_low = np.log10(self.switch_sup) - np.log10(rrs_red)\n        w_high = np.log10(rrs_red) - np.log10(self.switch_inf)\n        spm_mixing = (w_low * spm_low + w_high * spm_high) / (w_low + w_high)\n\n        spm = rrs_red.where(rrs_red > self.switch_inf, spm_low)\n        spm = spm.where(rrs_red < self.switch_sup, spm_high)\n        spm = spm.where((rrs_red <= self.switch_inf)\n                        | (rrs_red >= self.switch_sup), spm_mixing)\n        spm = spm.where((spm >= 0) & (spm <= self._valid_limit))\n        return spm\n\n\nclass SPMGet:\n    \"\"\"Switching Semi-analytical algorithm to retrieve SPM (in mg/l) from reflectance.\n\n    Switching Semi-analytical algorithm to retrieve suspended particulate\n    matter (in mg/l) from surface reflectances (rho, unitless) or remote\n    sensing reflectances (Rrs, in sr-1).\n    This algorithm was calibrated on GET radiometric database in 2018.\n\n    Attributes:\n        name: The name of the algorithm used. This is the key used by\n            L3AlgoBuilder and that you must provide in config or when using\n            the CLI.\n        requested_bands: A list of bands further used by the algorithm.\n        meta: A dict of metadata (calibration name, model coefficients, etc).\n    \"\"\"\n    _default_calibration_file = wc_calib / 'spm_get.yaml'\n    _default_calibration_name = 'GET_2018'\n    name = 'spm-get'\n\n    def __init__(self,\n                 product_type: str,\n                 calibration: Optional[P] = None,\n                 **_ignored) -> None:\n        \"\"\"Inits an 'SPMGet' instance with specific settings.\n\n        Args:\n            product_type: The type of the input satellite product (e.g.\n                S2_ESA_L2A or L8_USGS_L1GT)\n            calibration: The calibration (set of parameters) used by the\n                algorithm (default=_default_calibration_name).\n            **_ignored: Unused kwargs sent to trash.\n        \"\"\"\n        try:\n            self.requested_bands = algo_config[self.name][\n                producttype_to_sat(product_type)]\n        except KeyError as invalid_product:\n            msg = f'{product_type} is not allowed with {self.name}'\n            raise InputError(msg) from invalid_product\n        calibration_dict, calibration_name = load_calib(\n            calibration,\n            self._default_calibration_file,\n            self._default_calibration_name\n        )\n        self._switch_inf = calibration_dict['switch_inf']\n        self._switch_sup = calibration_dict['switch_sup']\n        self._valid_limit = calibration_dict['validity_limit']\n        try:\n            params = calibration_dict[producttype_to_sat(product_type)]\n        except KeyError as invalid_product:\n            msg = f'{product_type} is not allowed with this calibration'\n            raise InputError(msg) from invalid_product\n        self.__dict__.update(params)\n        self.meta = {'calibration': calibration_name,\n                     'switch inf': self._switch_inf,\n                     'switch sup': self._switch_sup,\n                     'validity_limit': self._valid_limit,\n                     **params}\n\n    def __call__(self,\n                 refl_red: xr.DataArray,\n                 refl_nir: xr.DataArray,\n                 data_type: str,\n                 **_ignored) -> xr.DataArray:\n        \"\"\"Runs the algorithm on the input array ('rho').\n\n        Args:\n            refl_red: An array (dimension 1 * N * M) of 'data_type'.\n            data_type: Either 'rho' or 'rrs' (respectively surface reflectance\n                and remote sensing reflectance).\n            **_ignored: Unused kwargs sent to trash.\n\n        Returns:\n            An array (dimension 1 * N * M) of SPM concentration (in mg/L).\n        \"\"\"\n        if data_type == 'rrs':\n            refl_red = np.pi * refl_red\n            refl_nir = np.pi * refl_nir\n\n        np.warnings.filterwarnings('ignore')\n        rho_red = refl_red.where(refl_red >= 0)\n        rho_nir = refl_red.where(refl_nir >= 0)\n\n        # pylint: disable=no-member\n        # Loaded in __init__ whit \"__dict__.update\".\n        spm_low = _nechad(rho_red, self.a_nechad, self.c_nechad)\n        spm_high = self.coef_br * np.power((rho_nir / rho_red), self.exp_br)\n\n        w = ((rho_red - self._switch_inf)\n             / (self._switch_sup - self._switch_inf))\n        spm_mixing = (1 - w) * spm_low + w * spm_high\n\n        spm = rho_red.where(rho_red > self._switch_inf, spm_low)\n        spm = spm.where(rho_red < self._switch_sup, spm_high)\n        spm = spm.where((rho_red <= self._switch_inf)\n                        | (rho_red >= self._switch_sup), spm_mixing)\n        spm = spm.where((spm >= 0) & (spm <= self._valid_limit))\n        return spm\n\n\nclass TURBIDogliotti:\n    \"\"\"Switching Semi-analytical algorithm to retrieve Turbidity (in FNU) from reflectance.\n\n    Switching Semi-analytical algorithm to retrieve Turbidity (in FNU) from\n    surface reflectances (rho, unitless) or remote sensing reflectances (Rrs,\n    in sr-1).\n    This algorithm was published in Dogliotti et al., 2015\n\n    Attributes:\n        name: The name of the algorithm used. This is the key used by\n            L3AlgoBuilder and that you must provide in config or when using\n            the CLI.\n        requested_bands: A list of bands further used by the algorithm.\n        meta: A dict of metadata (calibration name, model coefficients, etc).\n    \"\"\"\n    _default_calibration_file = wc_calib / 'turbi_dogliotti.yaml'\n    _default_calibration_name = 'Dogliotti_2015'\n    name = 'turbi-dogliotti'\n\n    def __init__(self,\n                 product_type: str,\n                 calibration: Optional[P] = None,\n                 **_ignored) -> None:\n        \"\"\"Inits an 'TURBIDogliotti' instance with specific settings.\n\n        Args:\n            product_type: The type of the input satellite product (e.g.\n                S2_ESA_L2A or L8_USGS_L1GT)\n            calibration: The calibration (set of parameters) used by the\n                algorithm (default=_default_calibration_name).\n            **_ignored: Unused kwargs sent to trash.\n        \"\"\"\n        try:\n            self.requested_bands = algo_config[self.name][\n                producttype_to_sat(product_type)]\n        except KeyError as invalid_product:\n            msg = f'{product_type} is not allowed with {self.name}'\n            raise InputError(msg) from invalid_product\n        calibration_dict, calibration_name = load_calib(\n            calibration,\n            self._default_calibration_file,\n            self._default_calibration_name\n        )\n        self._switch_inf = calibration_dict['switch_inf']\n        self._switch_sup = calibration_dict['switch_sup']\n        self._valid_limit = calibration_dict['validity_limit']\n        try:\n            params = calibration_dict[producttype_to_sat(product_type)]\n        except KeyError as invalid_product:\n            msg = f'{product_type} is not allowed with this calibration'\n            raise InputError(msg) from invalid_product\n        self.__dict__.update(params)\n        self.meta = {'calibration': calibration_name,\n                     'switch inf': self._switch_inf,\n                     'switch sup': self._switch_sup,\n                     'validity_limit': self._valid_limit,\n                     **params}\n\n    def __call__(self,\n                 rho_red: xr.DataArray,\n                 rho_nir: xr.DataArray,\n                 data_type: str,\n                 **_ignored) -> xr.DataArray:\n        \"\"\"Runs the algorithm on the input array ('rho').\n\n        Args:\n            rho_red: An array (dimension 1 * N * M) of 'data_type'.\n            rho_nir: An array (dimension 1 * N * M) of 'data_type'.\n            data_type: Either 'rho' or 'rrs' (respectively surface reflectance\n                and remote sensing reflectance).\n            **_ignored: Unused kwargs sent to trash.\n\n        Returns:\n            An array (dimension 1 * N * M) of Turbidity (in FNU).\n        \"\"\"\n\n        if data_type == 'rrs':\n            rho_red = np.pi * rho_red\n            rho_nir = np.pi * rho_nir\n\n        np.warnings.filterwarnings('ignore')\n        rho_red = rho_red.where(rho_red >= 0)\n        rho_nir = rho_red.where(rho_nir >= 0)\n        # pylint: disable=no-member\n        # Loaded in __init__ whit \"__dict__.update\".\n        t_low = _nechad(rho_red, self.a_low, self.c_low)\n        t_high = _nechad(rho_nir, self.a_high, self.c_high)\n        w = ((rho_red - self._switch_inf)\n             / (self._switch_sup - self._switch_inf))\n        t_mixing = (1 - w) * t_low + w * t_high\n\n        turb = rho_red.where(rho_red > self._switch_inf, t_low)\n        turb = turb.where(rho_red < self._switch_sup, t_high)\n        turb = turb.where((rho_red <= self._switch_inf)\n                          | (rho_red >= self._switch_sup), t_mixing)\n        turb = turb.where((turb >= 0) & (turb <= self._valid_limit))\n        return turb\n", "meta": {"hexsha": "c6899f30fa92d2a4fc03d94a8e9aab1abfbf08dd", "size": 17286, "ext": "py", "lang": "Python", "max_stars_repo_path": "sisppeo/wcproducts/spm.py", "max_stars_repo_name": "inrae/SISPPEO", "max_stars_repo_head_hexsha": "f516bb778b505739fdf320affe651b715ed75324", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-11-05T09:23:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T10:39:13.000Z", "max_issues_repo_path": "sisppeo/wcproducts/spm.py", "max_issues_repo_name": "inrae/SISPPEO", "max_issues_repo_head_hexsha": "f516bb778b505739fdf320affe651b715ed75324", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sisppeo/wcproducts/spm.py", "max_forks_repo_name": "inrae/SISPPEO", "max_forks_repo_head_hexsha": "f516bb778b505739fdf320affe651b715ed75324", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5774647887, "max_line_length": 91, "alphanum_fraction": 0.6194029851, "include": true, "reason": "import numpy", "num_tokens": 4076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.19465170062065518}}
{"text": "# Author: Roman Goj <roman.goj@gmail.com>\n#\n# License: BSD (3-clause)\n\nimport copy as cp\n\nimport numpy as np\nfrom scipy.fftpack import fftfreq\n\nfrom ..io.pick import pick_types\nfrom ..utils import logger, verbose, warn\nfrom ..time_frequency.multitaper import (dpss_windows, _mt_spectra,\n                                         _csd_from_mt, _psd_from_mt_adaptive)\n\n\nclass CrossSpectralDensity(object):\n    \"\"\"Cross-spectral density\n\n    Parameters\n    ----------\n    data : array of shape (n_channels, n_channels)\n        The cross-spectral density matrix.\n    ch_names : list of string\n        List of channels' names.\n    projs :\n        List of projectors used in CSD calculation.\n    bads :\n        List of bad channels.\n    frequencies : float | list of float\n        Frequency or frequencies for which the CSD matrix was calculated. If a\n        list is passed, data is a sum across CSD matrices for all frequencies.\n    n_fft : int\n        Length of the FFT used when calculating the CSD matrix.\n    \"\"\"\n    def __init__(self, data, ch_names, projs, bads, frequencies, n_fft):\n        self.data = data\n        self.dim = len(data)\n        self.ch_names = cp.deepcopy(ch_names)\n        self.projs = cp.deepcopy(projs)\n        self.bads = cp.deepcopy(bads)\n        self.frequencies = np.atleast_1d(np.copy(frequencies))\n        self.n_fft = n_fft\n\n    def __repr__(self):\n        s = 'frequencies : %s' % self.frequencies\n        s += ', size : %s x %s' % self.data.shape\n        s += ', data : %s' % self.data\n        return '<CrossSpectralDensity  |  %s>' % s\n\n\n@verbose\ndef compute_epochs_csd(epochs, mode='multitaper', fmin=0, fmax=np.inf,\n                       fsum=True, tmin=None, tmax=None, n_fft=None,\n                       mt_bandwidth=None, mt_adaptive=False, mt_low_bias=True,\n                       projs=None, verbose=None):\n    \"\"\"Estimate cross-spectral density from epochs\n\n    Note: Baseline correction should be used when creating the Epochs.\n          Otherwise the computed cross-spectral density will be inaccurate.\n\n    Note: Results are scaled by sampling frequency for compatibility with\n          Matlab.\n\n    Parameters\n    ----------\n    epochs : instance of Epochs\n        The epochs.\n    mode : str\n        Spectrum estimation mode can be either: 'multitaper' or 'fourier'.\n    fmin : float\n        Minimum frequency of interest.\n    fmax : float | np.inf\n        Maximum frequency of interest.\n    fsum : bool\n        Sum CSD values for the frequencies of interest. Summing is performed\n        instead of averaging so that accumulated power is comparable to power\n        in the time domain. If True, a single CSD matrix will be returned. If\n        False, the output will be a list of CSD matrices.\n    tmin : float | None\n        Minimum time instant to consider. If None start at first sample.\n    tmax : float | None\n        Maximum time instant to consider. If None end at last sample.\n    n_fft : int | None\n        Length of the FFT. If None the exact number of samples between tmin and\n        tmax will be used.\n    mt_bandwidth : float | None\n        The bandwidth of the multitaper windowing function in Hz.\n        Only used in 'multitaper' mode.\n    mt_adaptive : bool\n        Use adaptive weights to combine the tapered spectra into PSD.\n        Only used in 'multitaper' mode.\n    mt_low_bias : bool\n        Only use tapers with more than 90% spectral concentration within\n        bandwidth. Only used in 'multitaper' mode.\n    projs : list of Projection | None\n        List of projectors to use in CSD calculation, or None to indicate that\n        the projectors from the epochs should be inherited.\n    verbose : bool, str, int, or None\n        If not None, override default verbose level (see mne.verbose).\n\n    Returns\n    -------\n    csd : instance of CrossSpectralDensity\n        The computed cross-spectral density.\n    \"\"\"\n    # Portions of this code adapted from mne/connectivity/spectral.py\n\n    # Check correctness of input data and parameters\n    if fmax < fmin:\n        raise ValueError('fmax must be larger than fmin')\n    tstep = epochs.times[1] - epochs.times[0]\n    if tmin is not None and tmin < epochs.times[0] - tstep:\n        raise ValueError('tmin should be larger than the smallest data time '\n                         'point')\n    if tmax is not None and tmax > epochs.times[-1] + tstep:\n        raise ValueError('tmax should be smaller than the largest data time '\n                         'point')\n    if tmax is not None and tmin is not None:\n        if tmax < tmin:\n            raise ValueError('tmax must be larger than tmin')\n    if epochs.baseline is None and epochs.info['highpass'] < 0.1:\n        warn('Epochs are not baseline corrected or enough highpass filtered. '\n             'Cross-spectral density may be inaccurate.')\n\n    if projs is None:\n        projs = cp.deepcopy(epochs.info['projs'])\n    else:\n        projs = cp.deepcopy(projs)\n\n    picks_meeg = pick_types(epochs[0].info, meg=True, eeg=True, eog=False,\n                            ref_meg=False, exclude='bads')\n    ch_names = [epochs.ch_names[k] for k in picks_meeg]\n\n    # Preparing time window slice\n    tstart, tend = None, None\n    if tmin is not None:\n        tstart = np.where(epochs.times >= tmin)[0][0]\n    if tmax is not None:\n        tend = np.where(epochs.times <= tmax)[0][-1] + 1\n    tslice = slice(tstart, tend, None)\n    n_times = len(epochs.times[tslice])\n    n_fft = n_times if n_fft is None else n_fft\n\n    # Preparing frequencies of interest\n    sfreq = epochs.info['sfreq']\n    orig_frequencies = fftfreq(n_fft, 1. / sfreq)\n    freq_mask = (orig_frequencies > fmin) & (orig_frequencies < fmax)\n    frequencies = orig_frequencies[freq_mask]\n    n_freqs = len(frequencies)\n\n    if n_freqs == 0:\n        raise ValueError('No discrete fourier transform results within '\n                         'the given frequency window. Please widen either '\n                         'the frequency window or the time window')\n\n    # Preparing for computing CSD\n    logger.info('Computing cross-spectral density from epochs...')\n    if mode == 'multitaper':\n        # Compute standardized half-bandwidth\n        if mt_bandwidth is not None:\n            half_nbw = float(mt_bandwidth) * n_times / (2 * sfreq)\n        else:\n            half_nbw = 2\n\n        # Compute DPSS windows\n        n_tapers_max = int(2 * half_nbw)\n        window_fun, eigvals = dpss_windows(n_times, half_nbw, n_tapers_max,\n                                           low_bias=mt_low_bias)\n        n_tapers = len(eigvals)\n        logger.info('    using multitaper spectrum estimation with %d DPSS '\n                    'windows' % n_tapers)\n\n        if mt_adaptive and len(eigvals) < 3:\n            warn('Not adaptively combining the spectral estimators due to a '\n                 'low number of tapers.')\n            mt_adaptive = False\n    elif mode == 'fourier':\n        logger.info('    using FFT with a Hanning window to estimate spectra')\n        window_fun = np.hanning(n_times)\n        mt_adaptive = False\n        eigvals = 1.\n        n_tapers = None\n    else:\n        raise ValueError('Mode has an invalid value.')\n\n    csds_mean = np.zeros((len(ch_names), len(ch_names), n_freqs),\n                         dtype=complex)\n\n    # Picking frequencies of interest\n    freq_mask_mt = freq_mask[orig_frequencies >= 0]\n\n    # Compute CSD for each epoch\n    n_epochs = 0\n    for epoch in epochs:\n        epoch = epoch[picks_meeg][:, tslice]\n\n        # Calculating Fourier transform using multitaper module\n        x_mt, _ = _mt_spectra(epoch, window_fun, sfreq, n_fft)\n\n        if mt_adaptive:\n            # Compute adaptive weights\n            _, weights = _psd_from_mt_adaptive(x_mt, eigvals, freq_mask,\n                                               return_weights=True)\n            # Tiling weights so that we can easily use _csd_from_mt()\n            weights = weights[:, np.newaxis, :, :]\n            weights = np.tile(weights, [1, x_mt.shape[0], 1, 1])\n        else:\n            # Do not use adaptive weights\n            if mode == 'multitaper':\n                weights = np.sqrt(eigvals)[np.newaxis, np.newaxis, :,\n                                           np.newaxis]\n            else:\n                # Hack so we can sum over axis=-2\n                weights = np.array([1.])[:, None, None, None]\n\n        x_mt = x_mt[:, :, freq_mask_mt]\n\n        # Calculating CSD\n        # Tiling x_mt so that we can easily use _csd_from_mt()\n        x_mt = x_mt[:, np.newaxis, :, :]\n        x_mt = np.tile(x_mt, [1, x_mt.shape[0], 1, 1])\n        y_mt = np.transpose(x_mt, axes=[1, 0, 2, 3])\n        weights_y = np.transpose(weights, axes=[1, 0, 2, 3])\n        csds_epoch = _csd_from_mt(x_mt, y_mt, weights, weights_y)\n\n        # Scaling by number of samples and compensating for loss of power due\n        # to windowing (see section 11.5.2 in Bendat & Piersol).\n        if mode == 'fourier':\n            csds_epoch /= n_times\n            csds_epoch *= 8 / 3.\n\n        # Scaling by sampling frequency for compatibility with Matlab\n        csds_epoch /= sfreq\n\n        csds_mean += csds_epoch\n        n_epochs += 1\n\n    csds_mean /= n_epochs\n\n    logger.info('[done]')\n\n    # Summing over frequencies of interest or returning a list of separate CSD\n    # matrices for each frequency\n    if fsum is True:\n        csd_mean_fsum = np.sum(csds_mean, 2)\n        csd = CrossSpectralDensity(csd_mean_fsum, ch_names, projs,\n                                   epochs.info['bads'],\n                                   frequencies=frequencies, n_fft=n_fft)\n        return csd\n    else:\n        csds = []\n        for i in range(n_freqs):\n            csds.append(CrossSpectralDensity(csds_mean[:, :, i], ch_names,\n                                             projs, epochs.info['bads'],\n                                             frequencies=frequencies[i],\n                                             n_fft=n_fft))\n        return csds\n", "meta": {"hexsha": "4d5d25ff35e6f6c0a1e1d3e4a51d69aacdb24d41", "size": 9953, "ext": "py", "lang": "Python", "max_stars_repo_path": "mne/time_frequency/csd.py", "max_stars_repo_name": "mmagnuski/mne-python", "max_stars_repo_head_hexsha": "8b4aa6731b828430453b6e36405313e1bea3d701", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-08T22:53:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-08T22:53:49.000Z", "max_issues_repo_path": "mne/time_frequency/csd.py", "max_issues_repo_name": "mmagnuski/mne-python", "max_issues_repo_head_hexsha": "8b4aa6731b828430453b6e36405313e1bea3d701", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mne/time_frequency/csd.py", "max_forks_repo_name": "mmagnuski/mne-python", "max_forks_repo_head_hexsha": "8b4aa6731b828430453b6e36405313e1bea3d701", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-04-20T12:21:15.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-20T12:21:15.000Z", "avg_line_length": 38.5775193798, "max_line_length": 79, "alphanum_fraction": 0.6033356777, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.1946516979722317}}
{"text": "#!/usr/bin/python\r\n\r\n\r\n###Sterimol (and Tolman CA) Calculator###\r\n\r\n###############################################################\r\n#                       sterimoltools.py                      #\r\n#                                                             #\r\n###############################################################\r\n\r\n\r\n#Python Libraries\r\nimport subprocess, sys, os\r\nfrom numpy import *\r\nfrom scipy import *\r\nfrom math import *\r\nimport numpy as np\r\n#from vpython import *\r\n\r\n#Chemistry Libaries\r\n#from radialdata import *\r\n#from pars import *\r\n\r\n#Avoid number error warnings\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\n#Chemistry Arrays\r\nperiodictable = [\"Bq\",\"H\",\"He\",\"Li\",\"Be\",\"B\",\"C\",\"N\",\"O\",\"F\",\"Ne\",\"Na\",\"Mg\",\"Al\",\"Si\",\"P\",\"S\",\"Cl\",\"Ar\",\"K\",\"Ca\",\"Sc\",\"Ti\",\"V\",\"Cr\",\"Mn\",\"Fe\",\"Co\",\"Ni\",\"Cu\",\"Zn\",\"Ga\",\"Ge\",\"As\",\"Se\",\"Br\",\"Kr\",\"Rb\",\"Sr\",\"Y\",\"Zr\",\r\n             \"Nb\",\"Mo\",\"Tc\",\"Ru\",\"Rh\",\"Pd\",\"Ag\",\"Cd\",\"In\",\"Sn\",\"Sb\",\"Te\",\"I\",\"Xe\",\"Cs\",\"Ba\",\"La\",\"Ce\",\"Pr\",\"Nd\",\"Pm\",\"Sm\",\"Eu\",\"Gd\",\"Tb\",\"Dy\",\"Ho\",\"Er\",\"Tm\",\"Yb\",\"Lu\",\"Hf\",\"Ta\",\"W\",\"Re\",\"Os\",\"Ir\",\"Pt\",\"Au\",\"Hg\",\"Tl\",\r\n             \"Pb\",\"Bi\",\"Po\",\"At\",\"Rn\",\"Fr\",\"Ra\",\"Ac\",\"Th\",\"Pa\",\"U\",\"Np\",\"Pu\",\"Am\",\"Cm\",\"Bk\",\"Cf\",\"Es\",\"Fm\",\"Md\",\"No\",\"Lr\",\"Rf\",\"Db\",\"Sg\",\"Bh\",\"Hs\",\"Mt\",\"Ds\",\"Rg\",\"Uub\",\"Uut\",\"Uuq\",\"Uup\",\"Uuh\",\"Uus\",\"Uuo\"]\r\n\r\nmetals = [\"Li\",\"Be\",\"Na\",\"Mg\",\"Al\",\"K\",\"Ca\",\"Sc\",\"Ti\",\"V\",\"Cr\",\"Mn\",\"Fe\",\"Co\",\"Ni\",\"Cu\",\"Zn\",\"Ga\",\"Rb\",\"Sr\",\"Y\",\"Zr\",\"Nb\",\"Mo\",\"Tc\",\"Ru\",\"Rh\",\"Pd\",\"Ag\",\"Cd\",\"In\",\"Sn\",\"Cs\",\"Ba\",\"La\",\"Ce\",\"Pr\",\"Nd\",\"Pm\",\"Sm\",\"Eu\",\"Gd\",\"Tb\",\"Dy\",\"Ho\",\"Er\",\"Tm\",\"Yb\",\"Lu\",\"Hf\",\"Ta\",\"W\",\"Re\",\"Os\",\"Ir\",\"Pt\",\"Au\",\"Hg\",\"Tl\",\"Pb\",\"Bi\",\"Po\",\"Fr\",\"Ra\",\"Ac\",\"Th\",\"Pa\",\"U\",\"Np\",\"Pu\",\"Am\",\"Cm\",\"Bk\",\"Cf\",\"Es\",\"Fm\",\"Md\",\"No\",\"Lr\",\"Rf\",\"Db\",\"Sg\",\"Bh\",\"Hs\",\"Mt\",\"Ds\",\"Rg\",\"Cn\",\"Uut\",\"Fl\",\"Uup\",\"Lv\"]\r\n\r\n# Verloop's original Sterimol parameters use CPK atomic VdW radii based on atom-type definitions\r\nsterimol_atomtypes = [\"C\", \"C2\", \"C3\", \"C4\", \"C5/N5\", \"C6/N6\", \"C7\", \"C8\", \"H\", \"N\", \"C66\", \"N4\", \"O\", \"O2\", \"P\", \"S\", \"S1\", \"F\", \"C1\", \"S4\", \"B1\", \"I\"]\r\n\r\n# CPK VdW radii in pm\r\ncpk_radii = [150,160,160,150,170,170,170,150,100,150,170,145,135,135,140,170,100,135,180,140,195,215]\r\n\r\ndef getfragment(atom,molcart):\r\n   bondlist=[atom]\r\n   for a in range(len(molcart)):\r\n      if calcdist(atom,a,molcart)<1.92 and a not in bondlist:bondlist.append(a)\r\n\r\n      for b in range(len(bondlist)):\r\n         for c in range(len(molcart)):\r\n\r\n            if calcdist(bondlist[b],c,molcart)<1.92 and c not in bondlist:bondlist.append(c)\r\n   return bondlist\r\n\r\ndef connectivity(atom,molcart,aty):\r\n   con=[]\r\n   for a in range(len(molcart)):\r\n      if aty[a]in metals and molcart[a] != molcart[atom] and 0.1<calcdist(a,atom,molcart)<2:con.append(a)\r\n      if molcart[a] != molcart[atom] and 0.1<calcdist(a,atom,molcart)<1.7:con.append(a)\r\n   return len(con)\r\ndef genradii(atom,molcart,aty):\r\n   #molcart=fileData.CARTESIANS\r\n   con=connectivity(atom,molcart,aty)\r\n   if con==0:con=1\r\n   type=aty[atom]\r\n   arow=periodictable.index(type)\r\n   radius=molmod[arow][con]\r\n   if radius==0:radius=1;print \"Warning: No atomic radii found\", arow, con\r\n   return radius\r\n\r\ndef rotrel(vect1,vect2,vect3):\r\n   ax=np.cross(vect1,vect2)\r\n   ang=math.acos((np.dot(vect1,vect2))/(np.linalg.norm(vect1)*np.linalg.norm(vect2)))\r\n   norm=1/(np.linalg.norm(ax))\r\n   axnorm=np.dot(ax,norm)\r\n   ux=axnorm[0]\r\n   uy=axnorm[1]\r\n   uz=axnorm[2]\r\n   a=math.cos(ang)+((ux*ux)*(1-math.cos(ang)))\r\n   b=(ux*uy*(1-math.cos(ang)))-(uz*math.sin(ang))\r\n   c=(ux*uz*(1-math.cos(ang)))+(uy*math.sin(ang))\r\n   d=(uy*ux*(1-math.cos(ang)))+(uz*math.sin(ang))\r\n   e=(math.cos(ang))+(uy*uy*(1-math.cos(ang)))\r\n   f=(uy*uz*(1-math.cos(ang)))-(ux*math.sin(ang))\r\n   g=(uz*ux*(1-math.cos(ang)))-(uy*math.sin(ang))\r\n   h=(uz*uy*(1-math.cos(ang)))+(ux*math.sin(ang))\r\n   i=math.cos(ang)+(uz*uz*(1-math.cos(ang)))\r\n   bigmat=([[a,b,c],[d,e,f,],[g,h,i]])\r\n   vect=np.dot(bigmat,vect3)\r\n   return vect\r\n\r\ndef calcdist(a,b,carts):\r\n   return np.linalg.norm(np.subtract(carts[a],carts[b]))\r\n\r\ndef elementID(massno):\r\n   if massno < len(periodictable): return periodictable[massno]\r\n   else: return \"XX\"\r\n\r\ndef bondiRadius(massno):\r\n   #Bondi van der Waals radii for all atoms from: Bondi, A. J. Phys. Chem. 1964, 68, 441-452, except hydrogen, which is taken from Rowland, R. S.; Taylor, R. J. Phys. Chem. 1996, 100, 7384-7391\r\n   #Radii that are not available in either of these publications have RvdW = 2.00 Angstrom\r\n\r\n   bondi = [0.0,1.09, 1.40, 1.82,2.00,2.00,1.70,1.55,1.52,1.47,1.54,2.27,1.73,2.00,2.10,1.80,1.80,1.75,1.88,2.75,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,1.63,1.40,1.39,1.87,2.00,1.85,1.90,\r\n            1.85,2.02,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,1.63,1.72,1.58,1.93,2.17,2.00,2.06,1.98,2.16,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,1.72,1.66,1.55,1.96,2.02,2.00,2.00,2.00,\r\n            2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,2.00,1.86]\r\n   if massno<len(bondi): radius = bondi[massno]\r\n   else: radius = 2.0\r\n   return radius\r\n\r\n\r\ndef calcopposite(atom1,atom2,angle,molcart):\r\n   h=calcdist(atom1,atom2,molcart)\r\n   d=h*math.sin(angle)\r\n   return d\r\ndef calcadj(atom1,atom2,angle,molcart):\r\n   h=calcdist(atom1,atom2,molcart)\r\n   d=h*math.cos(angle)\r\n   return d\r\n\r\ndef getcoords(atom,molcart):\r\n   coords=[]\r\n   for i in range(3):\r\n      coords.append(molcart[atom][i])\r\n   return coords\r\n\r\ndef avpoints(atomnos,molcart):\r\n   xcoords=[]\r\n   ycoords=[]\r\n   zcoords=[]\r\n   for a in atomnos:\r\n      xcoords.append(molcart[a][0])\r\n      ycoords.append(molcart[a][1])\r\n      zcoords.append(molcart[a][2])\r\n   syslength=len(xcoords)\r\n   x=0;y=0;z=0\r\n   for i in range(syslength):\r\n      x=x+xcoords[i]\r\n      y=y+ycoords[i]\r\n      z=z+zcoords[i]\r\n   x=x/syslength; y=y/syslength; z=z/syslength\r\n   return round(x,8),round(y,8),round(z,8)\r\n\r\ndef distcalc(atom1,atom2):\r\n   x=atom1[0]-atom2[0]\r\n   y=atom1[1]-atom2[1]\r\n   z=atom1[2]-atom2[2]\r\n   dist = (x**2+y**2+z**2)**0.5\r\n   return dist\r\n\r\ndef dprod(v1, v2): return sum((a*b) for a, b in zip(v1, v2))\r\n\r\ndef length(v): return math.sqrt(dprod(v, v))\r\n\r\ndef angle(v1, v2):\r\n   val = dprod(v1, v2) / length(v1) / length(v2)\r\n   if val > 0.999999: val = 1.0\r\n   if val < -0.999999: val = -1.0\r\n   return math.acos(val)\r\n\r\ndef dihedral(atoma,atomb,atomc,atomd):\r\n   x1=atoma[0]\r\n   y1=atoma[1]\r\n   z1=atoma[2]\r\n   x2=atomb[0]\r\n   y2=atomb[1]\r\n   z2=atomb[2]\r\n   x3=atomc[0]\r\n   y3=atomc[1]\r\n   z3=atomc[2]\r\n   x4=atomd[0]\r\n   y4=atomd[1]\r\n   z4=atomd[2]\r\n   ax= (y2-y1)*(z2-z3)-(z2-z1)*(y2-y3)\r\n   ay= (z2-z1)*(x2-x3)-(x2-x1)*(z2-z3)\r\n   az= (x2-x1)*(y2-y3)-(y2-y1)*(x2-x3)\r\n   bx= (y3-y2)*(z3-z4)-(z3-z2)*(y3-y4)\r\n   by= (z3-z2)*(x3-x4)-(x3-x2)*(z3-z4)\r\n   bz= (x3-x2)*(y3-y4)-(y3-y2)*(x3-x4)\r\n   nbx= (y2-y3)*(z4-z3)-(z2-z3)*(y4-y3)\r\n   nby= (z2-z3)*(x4-x3)-(x2-x3)*(z4-z3)\r\n   nbz= (x2-x3)*(y4-y3)-(y2-y3)*(x4-x3)\r\n   torsion=180.0/math.pi*math.acos((ax*bx+ay*by+az*bz)/(math.sqrt(ax*ax+ay*ay+az*az)*math.sqrt(bx*bx+by*by+bz*bz)))\r\n   sign=180.0/math.pi*math.acos((nbx*(x2-x1)+nby*(y2-y1)+nbz*(z2-z1))/(math.sqrt(nbx*nbx+nby*nby+nbz*nbz)*math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)+(z2-z1)*(z2-z1))))\r\n   if sign<90.0:\r\n      torsion=torsion*-1.0\r\n   return torsion\r\n\r\n#Get PDB data?\r\n\r\nclass getinData:\r\n   def __init__(self, file):\r\n      if not os.path.exists(file+\".com\"):\r\n         print (\"\\nFATAL ERROR: Input file [ %s ] does not exist\"%file)\r\n      def getATOMTYPES(self, inlines):\r\n         self.ATOMTYPES = []\r\n         self.LEVELTYPES = []\r\n         for i in range(0,len(inlines)):\r\n            if inlines[i].find(\"#\") > -1:\r\n               if len(inlines[i+1].split()) == 0: start = i+5\r\n               if len(inlines[i+2].split()) == 0: start = i+6\r\n               break\r\n         for i in range(start,len(inlines)):\r\n            if len(inlines[i].split()) ==0:\r\n               break\r\n            else:\r\n               self.ATOMTYPES.append(inlines[i].split()[0].split(\"-\")[0])\r\n               for oniomlevel in [\"H\", \"M\", \"L\"]:\r\n                  if inlines[i].rfind(oniomlevel)>1:\r\n                     self.LEVELTYPES.append(inlines[i][inlines[i].rfind(\"H\"):])\r\n                     break\r\n      def getCARTESIANS(self, inlines, natoms):\r\n         self.CARTESIANS = []\r\n         for i in range(0,len(inlines)):\r\n            if inlines[i].find(\"#\") > -1:\r\n               start = i+5\r\n               break\r\n\r\n         for i in range(start,len(inlines)):\r\n            if len(inlines[i].split()) == 0:\r\n               break\r\n            elif len(inlines[i].split()) == 4:\r\n               self.CARTESIANS.append([float(inlines[i].split()[1]), float(inlines[i].split()[2]), float(inlines[i].split()[3])])\r\n\r\n      infile = open(file+\".com\",\"r\")\r\n      inlines = infile.readlines()\r\n      getATOMTYPES(self, inlines)\r\n      self.NATOMS=len(self.ATOMTYPES)\r\n\r\n      getCARTESIANS(self, inlines, self.NATOMS)\r\n\r\nclass getinData2:\r\n   def __init__(self, file):\r\n      start=2\r\n      if not os.path.exists(file+\".xyz\"):\r\n         print (\"\\nFATAL ERROR: Input file [ %s ] does not exist\"%file)\r\n      def getATOMTYPES(self, inlines):\r\n         self.ATOMTYPES = []\r\n         self.LEVELTYPES = []\r\n         for i in range(2,len(inlines)):\r\n            if len(inlines[i].split()) ==0:\r\n               break\r\n            else:\r\n               self.ATOMTYPES.append(inlines[i].split()[0].split(\"-\")[0])\r\n               for oniomlevel in [\"H\", \"M\", \"L\"]:\r\n                  if inlines[i].rfind(oniomlevel)>1:\r\n                     self.LEVELTYPES.append(inlines[i][inlines[i].rfind(\"H\"):])\r\n                     break\r\n      def getCARTESIANS(self, inlines, natoms):\r\n         self.CARTESIANS = []\r\n#         for i in range(0,len(inlines)):\r\n#            if inlines[i].find(\"#\") > -1:\r\n#               start = i+5\r\n#               break\r\n         for i in range(start,len(inlines)):\r\n            if len(inlines[i].split()) == 0:\r\n               break\r\n            elif len(inlines[i].split()) == 4:\r\n               self.CARTESIANS.append([float(inlines[i].split()[1]), float(inlines[i].split()[2]), float(inlines[i].split()[3])])\r\n\r\n#         print self.CARTESIANS\r\n#         for i in range(0,len(inlines)):\r\n      infile = open(file+\".xyz\",\"r\")\r\n      inlines = infile.readlines()\r\n      getATOMTYPES(self, inlines)\r\n      self.NATOMS=len(self.ATOMTYPES)\r\n\r\n      getCARTESIANS(self, inlines, self.NATOMS)\r\n\r\nclass getoutData:\r\n   def __init__(self, file):\r\n      if not os.path.exists(file+\".out\"):\r\n         if not os.path.exists(file+\".log\"):\r\n            print (\"\\nFATAL ERROR: Output file [ %s ] does not exist\"%file)\r\n      def getFORMAT(self, outlines):\r\n         for i in range(0,len(outlines)):\r\n            if outlines[i].find(\"Gaussian\") > -1: self.FORMAT = \"Gaussian\"; break\r\n      def getATOMTYPES(self, outlines, format):\r\n         self.ATOMTYPES = []\r\n         self.CARTESIANS = []\r\n         if format == \"Gaussian\":\r\n            for i in range(0,len(outlines)):\r\n\r\n               if outlines[i].find(\"Standard orientation\") > -1:\r\n                  standor = i\r\n                  arb=0\r\n               if outlines[i].find(\"Input orientation\") > -1:\r\n                  standor2 = i\r\n                  arb=1\r\n               if outlines[i].find(\"Rotational constants\") > -1 and outlines[i-1].find(\"-------\") > -1 and arb==0:\r\n                  self.NATOMS = i-standor-6\r\n               if outlines[i].find(\"Rotational constants\") > -1 and outlines[i-1].find(\"-------\") > -1 and arb==1:\r\n                  self.NATOMS = i-standor2-6\r\n                  arb=2\r\n               if outlines[i].find(\"Distance matrix\") > -1 and outlines[i-1].find(\"-------\") > -1:\r\n                  self.NATOMS = i-standor2-6\r\n            try: standor, standor2\r\n            except NameError: pass\r\n            else:\r\n               if standor2>standor:del standor\r\n               if standor>standor2:del standor2\r\n            try: standor\r\n            except NameError: pass\r\n            else:\r\n               for i in range (standor+5,standor+5+self.NATOMS):\r\n                  self.ATOMTYPES.append(elementID(int(outlines[i].split()[1])))\r\n                  if len(outlines[i].split())==6:self.CARTESIANS.append([float(outlines[i].split()[3]),float(outlines[i].split()[4]),float(outlines[i].split()[5])])\r\n                  else: self.CARTESIANS.append([float(outlines[i].split()[2]),float(outlines[i].split()[3]),float(outlines[i].split()[4])])\r\n            try: standor2\r\n            except NameError: pass\r\n            else:\r\n               for i in range (standor2+5,standor2+5+self.NATOMS):\r\n                     self.ATOMTYPES.append(elementID(int(outlines[i].split()[1])))\r\n                     self.CARTESIANS.append([float(outlines[i].split()[3]),float(outlines[i].split()[4]),float(outlines[i].split()[5])])\r\n\r\n      if os.path.exists(file+\".out\"):outfile = open(file+\".out\",\"r\")\r\n      else: outfile = open(file+\".log\",\"r\")\r\n      outlines = outfile.readlines()\r\n      getFORMAT(self, outlines)\r\n      getATOMTYPES(self, outlines, self.FORMAT)\r\n      self.NATOMS=len(self.ATOMTYPES)\r\n\r\ndef concheck(conpar,val):\r\n   cons=[]\r\n   for a in range(len(conpar)):\r\n      for b in range(len(conpar[a])):\r\n         if val ==conpar[a][0]:\r\n            for c in range(len(conpar[a])-1):\r\n               cons.append(conpar[a][c+1])\r\n            return cons\r\n\r\ndef twod_dist(a,b,c):\r\n   vect1=np.subtract(a,b)\r\n   vect2=np.subtract(b,c)\r\n   ang=angle(vect1,vect2)\r\n   return math.sin(ang)*np.linalg.norm(vect1)\r\n\r\ndef twod_vect(a,b,c):\r\n   vect1=np.subtract(a,b)\r\n   vect2=np.subtract(b,c)\r\n   ang=angle(vect1,vect2)\r\n   nvect2=vect2/np.linalg.norm(vect2)\r\n   return ((math.cos(ang)*np.linalg.norm(vect1))*nvect2)+b\r\n\r\ndef twod_rot(vect,theta):\r\n   a=math.cos(theta)\r\n   b=math.sin(theta)\r\n   mat=[[a,-b],[b,a]]\r\n   vect=np.dot(mat,vect)\r\n   return vect\r\n\r\n# Generate Sterimol atom type from connectivity data\r\ndef generate_atom_types(atomtype, cn):\r\n   st_types = []\r\n   for i in range(0,len(atomtype)):\r\n      atom = atomtype[i]\r\n      if atom == \"H\": st_types.append(\"H\")\r\n      elif atom == \"P\": st_types.append(\"P\")\r\n      elif atom == \"F\": st_types.append(\"F\")\r\n      elif atom == \"Cl\": st_types.append(\"C1\")\r\n      elif atom == \"Br\": st_types.append(\"B1\")\r\n      elif atom == \"I\": st_types.append(\"I\")\r\n      elif atom == \"O\": #Sterimol distinguishes between \"normal\", and double-bonded O atoms\r\n         if cn[i] < 1.5: st_types.append(\"O2\")\r\n         if cn[i] > 1.5: st_types.append(\"O\")\r\n      elif atom == \"S\": #Sterimol distinguishes between \"normal\", tetrahedral, and octohedral S atoms\r\n         if cn[i] < 2.5: st_types.append(\"S\")\r\n         if 5.5 > cn[i] > 2.5: st_types.append(\"S4\")\r\n         if cn[i] > 5.5: st_types.append(\"S1\")\r\n      elif atom == \"N\": #Sterimol distinguishes between tetrahedral and planar (amide) N atoms\r\n         if cn[i] > 2.5: st_types.append(\"N\")\r\n         if cn[i] < 2.5: st_types.append(\"C6/N6\")\r\n      elif atom == \"C\": #Sterimol distinguishes between myriad types of C atoms ...\r\n         if cn[i] < 2.5: st_types.append(\"C3\")\r\n         if 3.5 > cn[i] > 2.5: # need to differentiate between sp2 carbon and aromatic carbon ...\r\n            st_types.append(\"C6/N6\") # assumes aromatic rather than sp2\r\n         if cn[i] > 3.5: st_types.append(\"C\")\r\n   return st_types\r\n\r\n\r\n# Calculation of atomic coordination numbers (taken from Grimme's DFTD3 definitions)\r\ndef ncoord(natom, rcov, atomtype, coords):\r\n   max_elem = 94\r\n   k1 = 16.0\r\n   k2 = 4.0/3.0\r\n   cn =[]\r\n   for i in range(0,natom):\r\n      xn = 0.0\r\n      for iat in range(0,natom):\r\n         if iat != i:\r\n            dx = coords[iat][0] - coords[i][0]\r\n            dy = coords[iat][1] - coords[i][1]\r\n            dz = coords[iat][2] - coords[i][2]\r\n            r2 = dx*dx+dy*dy+dz*dz\r\n            r = math.pow(r2,0.5)\r\n            r = r\r\n            for k in range(0,max_elem):\r\n               if atomtype[i].find(elements[k])>-1:Zi=k\r\n               if atomtype[iat].find(elements[k])>-1:Ziat=k\r\n\r\n            rco = rcov[Zi]+rcov[Ziat]\r\n            rco = rco*k2\r\n            rr=rco/r\r\n            damp=1.0/(1.0+math.exp(-k1*(rr-1.0)))\r\n            xn=xn+damp\r\n      cn.append(xn)\r\n   return cn\r\n\r\ndef linearcheck(carts):\r\n   ans=0;xgrad=[];ygrad=[]\r\n   for row in carts:xgrad.append(round(np.gradient(row)[0],4));ygrad.append(round(np.gradient(row)[1],4))\r\n   if min(xgrad)==max(xgrad) and min(ygrad)==max(ygrad):ans=1\r\n   return ans\r\n\r\nclass calcSterimol:\r\n   def __init__(self, file, radii, atomA, atomB,verbose):\r\n      if len(file.split(\".com\"))>1 or len(file.split(\".gjf\"))>1: \r\n            fileData = getinData(file.split(\".\")[0])\r\n      if len(file.split(\".xyz\"))>1: \r\n            fileData = getinData2(file.split(\".\")[0])\r\n      if len(file.split(\".out\"))>1 or len(file.split(\".log\"))>1: fileData = getoutData(file.split(\".\")[0])\r\n\r\n      # initialize the array of atomic vdw radii\r\n      molcart = fileData.CARTESIANS; atomtype = fileData.ATOMTYPES; natoms = len(molcart); vdw_radii = []\r\n#      print fileData.ATOMTYPES\r\n\r\n      if radii == \"cpk\":\r\n         atomic_co_no = ncoord(natoms, rcov, atomtype, molcart)\r\n         sterimol_types = generate_atom_types(atomtype, atomic_co_no)\r\n         print(sterimol_types)\r\n         #print sterimol_types\r\n         for i in range(0,natoms):\r\n            for j in range(0,len(sterimol_atomtypes)):\r\n               if sterimol_types[i] == sterimol_atomtypes[j]: vdw_radii.append(cpk_radii[j]/100.00)\r\n\r\n      if radii == \"bondi\":\r\n         for i in range(0,natoms): \r\n               vdw_radii.append(bondiRadius(periodictable.index(fileData.ATOMTYPES[i])))\r\n\r\n# Define vector along the L-axis connecting base atom and the next attached atom\r\n# subtract one since the array starts from zero not one\r\n      atomA = atomA - 1; atomB = atomB - 1\r\n      next_atom = molcart[atomB]\r\n      vect1=np.subtract(getcoords(atomA,molcart),next_atom)\r\n      if verbose == True:\r\n            pass\r\n          #print \"   Atoms\", atomA, \"and\", atomB, \"define the L-axis and direction\", vect1\r\n\r\n#          print \"\\n\", \"   Atom \".ljust(9), \"  Xco/A\".rjust(9), \"  Yco/A\".rjust(9), \"  Zco/A\".rjust(9), \" VdW/pm\".rjust(9)\r\n          #print \"   ##############################################\"\r\n      # Remove the base atom from the list of atoms to be considered for sterics (after printing all)\r\n      atomlist = list(xrange(0,natoms))\r\n      if verbose == True:\r\n          for atom in atomlist:\r\n             pass\r\n#             if radii == \"cpk\": print \"  \", sterimol_types[atom].ljust(6),\r\n#             if radii == \"bondi\": print \"  \", atomtype[atom].ljust(6),\r\n             for coord in molcart[atom]:\r\n                pass\r\n#                if coord < 0.0: print \"   %.3f\".rjust(6) % coord,\r\n#                else: print \"    %.3f\".rjust(6) % coord,\r\n#             print \"    %.1f\" % round(vdw_radii[atom]*100)\r\n      atomlist.remove(atomA)\r\n\r\n      adjlist=[]; opplist=[]; theta=[]\r\n      for i in atomlist:\r\n         vect2=np.subtract(getcoords(atomA,molcart),getcoords(i,molcart))\r\n         oppdist=calcopposite(atomA,i,angle(vect1,vect2),molcart)\r\n         opplist.append(oppdist+vdw_radii[i])\r\n         adjdist=calcadj(atomA,i,angle(vect1,vect2),molcart)\r\n         #minadjlist.append(adjdist-vdw_radii[i])\r\n         adjlist.append(adjdist+vdw_radii[i])\r\n\r\n      B5=max(opplist)\r\n   #self.lval=max(adjlist)-minval\r\n   # A bit weird, but seems like original sterimol adds on the difference between the bond length and vdw radius of atom B. For a C-H bond this is 1.50 - 1.10 = 0.40 Angstrom)\r\n      self.lval=max(adjlist)+0.40\r\n\r\n      ###Useful - do not delete!\r\n      #print \"   B5 atom\", atomlist[opplist.index(max(opplist))]+1, \"distance\", max(opplist)\r\n      #print \"   Highest atom\", atomlist[adjlist.index(max(adjlist))]+1,\"distance\", max(adjlist),\"\\n   Lowest atom\", atomlist[minadjlist.index(min(minadjlist))]+1,\"distance\", min(minadjlist)\r\n\r\n      zcarts=[]#zeroed carts\r\n      for i in atomlist: zcarts.append(np.subtract(molcart[i],molcart[atomA]))\r\n      zvect=[0,0,1]\r\n      zcent=np.subtract(next_atom,molcart[atomA])\r\n      for cart in range(len(zcarts)):\r\n         zcoord= rotrel(zcent,zvect,zcarts[cart])\r\n         zcarts[cart]=zcoord\r\n      twodcarts=[]\r\n      for row in zcarts: twodcarts.append([row[0],row[1]])\r\n      fragrad=[]#radii of fragment atoms\r\n      for t in atomlist: fragrad.append(vdw_radii[t])\r\n      singledist=[]\r\n      for t in range(len(fragrad)):\r\n         d=np.linalg.norm(twodcarts[t])#;print d\r\n         d=d+fragrad[t]\r\n         singledist.append(d)\r\n      self.newB5=max(singledist) #This is the same as the 3D calculated value from above\r\n\r\n      center=[0,0]\r\n      vlist=[]#list of distances from the origin to the tangential vectors\r\n      alist=[]#list of atoms between which the tangential vectors pass through no other atoms\r\n      iav=[]#interatomic vectors\r\n      sym=symcheck(twodcarts)\r\n      for x in range(len(twodcarts)):\r\n         if sym==1:\r\n            twodcarts[x][0]=twodcarts[x][0]+0.000001\r\n            twodcarts[x][1]=twodcarts[x][1]+0.000001\r\n         for y in range(len(twodcarts)):\r\n            if x!=y:\r\n               try:nvect= (twod_vect(center,twodcarts[x],twodcarts[y]))#origin normal vector to connecting atomic centers vector\r\n               except ValueError:nvect=[0,0]\r\n               iav=np.subtract(twodcarts[x],twodcarts[y])#interatomic vector\r\n               iad=np.linalg.norm(iav)#interatomic distance\r\n               try:theta=math.asin((fragrad[y]-fragrad[x])/iad)#calculates angle by which to rotate vdw radii before adding\r\n               except ValueError: theta=np.pi/2\r\n               try:unvect=nvect/np.linalg.norm(nvect)\r\n               except RuntimeWarning:pass#unvect=[0,0]\r\n               xradv=twod_rot(unvect*fragrad[x],theta)\r\n               yradv=twod_rot(unvect*fragrad[y],theta)\r\n               mvect= (twod_vect(center,twodcarts[x]-xradv,twodcarts[y]-yradv))\r\n               nvect= (twod_vect(center,twodcarts[x]+xradv,twodcarts[y]+yradv))#origin normal vector to connecting atomic surfaces tangential vector\r\n               newx=twodcarts[x]+xradv\r\n               newy=twodcarts[y]+yradv\r\n               mewx=twodcarts[x]-xradv\r\n               mewy=twodcarts[y]-yradv\r\n               if np.cross(nvect,xradv)<0.000000001 and theta!=np.pi/2:\r\n                  satpoint=[]#Satisfied points not within range of tangential vector\r\n                  for z in range(len(twodcarts)):\r\n                     pvdist=twod_dist(twodcarts[z],newx,newy)\r\n                     if z!=x and z!=y and pvdist>(fragrad[z]-0.0001):satpoint.append(pvdist)\r\n                  if len(satpoint)==len(atomlist)-2:vlist.append(np.linalg.norm(nvect));alist.append([x,y]);#print x,y\r\n                  satpoint=[]\r\n                  for z in range(len(twodcarts)):\r\n                     pvdist=twod_dist(twodcarts[z],mewx,mewy)\r\n                     if z!=x and z!=y and pvdist>(fragrad[z]-0.0001):satpoint.append(pvdist)\r\n                  if len(satpoint)==len(atomlist)-2:vlist.append(np.linalg.norm(mvect));alist.append([x,y])\r\n      if linearcheck(twodcarts)==1:self.B1 = max(fragrad)\r\n      elif len(vlist) > 0: self.B1=min(vlist)\r\n      else: self.B1 = max(fragrad)\r\n\r\ndef symcheck(carts):#Add symmetry criteria\r\n   center=[0,0]\r\n   distlist=[]\r\n   distlist.append(10)\r\n   for a in range(len(carts)):\r\n      for b in range(len(carts)):\r\n         if a!=b:\r\n            dist=np.linalg.norm(twod_vect(center,carts[a],carts[b]))\r\n            distlist.append(dist)\r\n   if min(distlist)<0.0000000001:ans=1\r\n   else:ans=0\r\n   return ans\r\n\r\ndef calcSandwich(file):\r\n   metalatoms=[]\r\n   if file.split(\".\")[1]==\"log\" or file.split(\".\")[1]==\"out\":fileData=getoutData(file.split(\".\")[0])\r\n#   if file.split(\".\")[1]==\"xyz\": \r\n#    fileData=getinData2(file.split(\".\")[0])\r\n   if file.split(\".\")[1]==\"com\" or file.split(\".\")[1]==\"gjf\":fileData=getinData(file.split(\".\")[0])\r\n   for i in range(len(fileData.ATOMTYPES)):\r\n      if fileData.ATOMTYPES[i] in metals:metalatoms.append(i)\r\n\r\n   ivals=[]\r\n   jvals=[]\r\n   for i in range(len(fileData.ATOMTYPES)):\r\n      for j in range(len(fileData.ATOMTYPES)):\r\n         dist = ((fileData.CARTESIANS[i][0]-fileData.CARTESIANS[j][0])**2 +(fileData.CARTESIANS[i][1]-fileData.CARTESIANS[j][1])**2+(fileData.CARTESIANS[i][2]-fileData.CARTESIANS[j][2])**2)**0.5\r\n         if 0.01<dist<1.511 and fileData.ATOMTYPES[j] == \"C\" and fileData.ATOMTYPES[i] == \"C\":\r\n            ivals.append(i)\r\n            jvals.append(j)\r\n   conpar=[]\r\n   for a in range(len(ivals)):\r\n      rar=[]\r\n      rar.append(ivals[a])\r\n\r\n      for b in range(len(ivals)):\r\n         if ivals[a]==ivals[b]:rar.append(jvals[b])\r\n      if rar not in conpar:conpar.append(rar)\r\n\r\n   allrings=[]\r\n   for a in range(len(conpar)):\r\n      z=conpar[a][0]\r\n      for b in concheck(conpar,z):\r\n         y=b\r\n         for c in concheck(conpar,y):\r\n            x=c\r\n            for d in concheck(conpar,x):\r\n               w=d\r\n               for e in concheck(conpar,w):\r\n                  v=e\r\n                  rar=[]\r\n                  rar.extend([z,y,x,w,v])\r\n                  if z in concheck(conpar,v) and sorted(rar) not in allrings and len(set(rar))==5:allrings.append(sorted(rar))\r\n                  for f in concheck(conpar,v):\r\n                     u=f\r\n                     tar=[]\r\n                     tar.extend([z,y,x,w,v,u])\r\n                     if z in concheck(conpar,u) and sorted(tar) not in allrings and len(set(tar))==6:allrings.append(sorted(tar))\r\n\r\n\r\n\r\n   if not allrings:\r\n      for ma in metalatoms:\r\n         for s in range(len(fileData.CARTESIANS)):\r\n            if 0.1<np.linalg.norm(np.subtract(fileData.CARTESIANS[ma],fileData.CARTESIANS[s]))<2.1:allrings.append([s,s,s,s,s])\r\n\r\n   mcdists=[]\r\n   mcdist=9999\r\n   for ring in allrings:\r\n\r\n      if len(ring)==5:\r\n         tolman=[]\r\n         cent=avpoints(ring,fileData.CARTESIANS)\r\n         m=fileData.CARTESIANS[metalatoms[0]]\r\n         tempmcdist=mcdist\r\n         mcdist=distcalc(m,cent)\r\n         for b in metalatoms:#find closest metal to ring\r\n            m=fileData.CARTESIANS[b]\r\n            if mcdist>=distcalc(m,cent):mcdist=distcalc(m,cent);metal=b\r\n         mcdists.append([mcdist,metal])\r\n         frag=getfragment(ring[0],fileData.CARTESIANS)\r\n         vect1=np.subtract(getcoords(metal,fileData.CARTESIANS),cent)\r\n         if tempmcdist==mcdist:break#Stops if dealing with identical ring system as before (intended for symmetric dimers)\r\n         adjlist=[]\r\n         minadjlist=[]\r\n         opplist=[]\r\n         alpha=[]\r\n         beta=[]\r\n         theta=[]#Candidate Tolman angle substituent\r\n         omega=[]#standardised atom \"dihedral\" orientation\r\n         ringang=[]\r\n         for i in frag:\r\n            vect2=np.subtract(getcoords(metal,fileData.CARTESIANS),getcoords(i,fileData.CARTESIANS))\r\n            oppdist=calcopposite(metal,i,angle(vect1,vect2),fileData.CARTESIANS)\r\n            opplist.append(oppdist+genradii(i,fileData.CARTESIANS,fileData.ATOMTYPES))\r\n            adjdist=calcadj(metal,i,angle(vect1,vect2),fileData.CARTESIANS)\r\n            minadjlist.append(adjdist-genradii(i,fileData.CARTESIANS,fileData.ATOMTYPES))\r\n            adjlist.append(adjdist+genradii(i,fileData.CARTESIANS,fileData.ATOMTYPES))\r\n            alpha.append(angle(vect1,vect2))\r\n            hyp=distcalc(getcoords(i,fileData.CARTESIANS),getcoords(metal,fileData.CARTESIANS))\r\n            beta.append(math.asin(genradii(i,fileData.CARTESIANS,fileData.ATOMTYPES)/hyp))\r\n            theta.append(alpha[-1]+beta[-1])\r\n            if ring[0]!=ring[1]:omega.append(dihedral([10,10,10],getcoords(metal,fileData.CARTESIANS),cent,getcoords(i,fileData.CARTESIANS)))\r\n            if ring[0]!=ring[1] and i in ring:ringang.append(dihedral([10,10,10],getcoords(metal,fileData.CARTESIANS),cent,getcoords(i,fileData.CARTESIANS)))\r\n         B5=max(opplist)#Bondi\r\n         lval=max(adjlist)-min(minadjlist)\r\n         interval=180/len(ring)\r\n         if ring[0]!=ring[1]:\r\n            for k in ringang:\r\n               tlist=[];tang=[];tfrag=[]\r\n\r\n               for h in range(len(frag)):\r\n                  if k-interval<omega[h]<k+interval:tlist.append(frag[h])\r\n                  if k>(180-interval) and k-interval<omega[h]+360<k+interval:tlist.append(frag[h])\r\n                  if k<-(180-interval) and k-interval<omega[h]-360<k+interval:tlist.append(frag[h])\r\n               for t in range(len(frag)):\r\n                  if frag[t] in tlist: tang.append(theta[t]);tfrag.append(frag[t])\r\n               tolman.append(math.degrees(max(tang)))\r\n            x=0\r\n            for c in tolman:\r\n               x=x+c\r\n            tolmanCA=round(2*(x/len(tolman)),3)\r\n         else:tolmanCA=0\r\n         smcdist=round(mcdist,3);lval=round(lval,3);lval=round(lval,3);B5=round(B5,3)\r\n         molcart=fileData.CARTESIANS\r\n         zcarts=[]\r\n         for i in frag:\r\n            zcarts.append(np.subtract(molcart[i],molcart[metal]))\r\n         zvect=[0,0,1]\r\n         zcent=np.subtract(cent,molcart[metal])\r\n         for cart in range(len(zcarts)):\r\n            zcoord= rotrel(zcent,zvect,zcarts[cart])\r\n            zcarts[cart]=zcoord\r\n         twodcarts=[]\r\n         for row in zcarts:\r\n            twodcarts.append([row[0],row[1]])\r\n         fragrad=[]#radii of fragment atoms\r\n         for t in frag:\r\n            fragrad.append(genradii(t,fileData.CARTESIANS,fileData.ATOMTYPES))\r\n         singledist=[]\r\n         for t in range(len(fragrad)):\r\n            d=np.linalg.norm(twodcarts[t])#;print d\r\n            d=d+fragrad[t]\r\n            singledist.append(d)\r\n         newB5=round(max(singledist),3)#This is the same as the 3D calculated value from above\r\n\r\n         center=[0,0]\r\n         vlist=[]#list of distances from the origin to the tangential vectors\r\n         alist=[]#list of atoms between which the tangential vectors pass through no other atoms\r\n         iav=[]#interatomic vectors\r\n\r\n         for x in range(len(twodcarts)):\r\n            for y in range(len(twodcarts)):\r\n               if x!=y:\r\n                  try:nvect= (twod_vect(center,twodcarts[x],twodcarts[y]))#origin normal vector to connecting atomic centers vector\r\n                  except ValueError:nvect=[0,0]\r\n                  iav=np.subtract(twodcarts[x],twodcarts[y])#interatomic vector\r\n                  iad=np.linalg.norm(iav)#interatomic distance\r\n                  try:theta=math.asin((fragrad[y]-fragrad[x])/iad)#calculates angle by which to rotate vdw radii before adding\r\n                  except ValueError: theta=np.pi/2\r\n                  try:unvect=nvect/np.linalg.norm(nvect)\r\n                  except RuntimeWarning:pass#unvect=[0,0]\r\n                  xradv=twod_rot(unvect*fragrad[x],theta)\r\n                  yradv=twod_rot(unvect*fragrad[y],theta)\r\n                  nvect= (twod_vect(center,twodcarts[x]+xradv,twodcarts[y]+yradv))#origin normal vector to connecting atomic surfaces tangential vector\r\n                  newx=twodcarts[x]+xradv\r\n                  newy=twodcarts[y]+yradv\r\n                  if np.cross(nvect,xradv)<0.000000001 and theta!=np.pi/2:\r\n                     satpoint=[]#Satisfied points not within range of tangential vector\r\n                     for z in range(len(twodcarts)):\r\n                        pvdist=twod_dist(twodcarts[z],newx,newy)\r\n                        if z!=x and z!=y and pvdist>fragrad[z]:satpoint.append(pvdist)\r\n                     if len(satpoint)==len(frag)-2:vlist.append(np.linalg.norm(nvect));alist.append([x,y])#;print x,y\r\n         B1=round(min(vlist),3)\r\n#         print \"   \"+file.ljust(25),str(tolmanCA).rjust(9), str(smcdist).rjust(9), str(lval).rjust(9),str(B1).rjust(9), str(newB5).rjust(9)\r\n\r\nmolmod=[['Bq', 0, 0, 0, 0],\r\n        ['H', 1, 1, 1, 1],\r\n        ['He', 0, 0, 0, 0],\r\n        ['Li', 0, 0, 0, 0],\r\n        ['Be', 0, 0, 0, 0],\r\n        ['B', 0, 0, 0, 0],\r\n        ['C', 0, 1.6, 1.6, 1.5],\r\n        ['N', 1.45, 1.45, 1.5, 1.25],\r\n        ['O', 1.35, 1.35, 1.35, 0],\r\n        ['F', 1.35, 1.35, 0, 0],\r\n        ['Ne', 0, 0, 0, 0],\r\n        ['Na', 0, 0, 0, 0],\r\n        ['Mg', 0, 0, 0, 0],\r\n        ['Al', 0, 0, 0, 0],\r\n        ['Si', 2.1, 2.1, 2.1, 2.1],\r\n        ['P', 0, 0, 0, 0],\r\n        ['S', 0, 0, 0, 0],\r\n        ['Cl', 1.8, 0, 0, 0],\r\n        ['Ar', 0, 0, 0, 0],\r\n        ['K', 0, 0, 0, 0],\r\n        ['Ca', 0, 0, 0, 0],\r\n        ['Sc', 0, 0, 0, 0],\r\n        ['Ti', 0, 0, 0, 0],\r\n        ['V', 0, 0, 0, 0],\r\n        ['Cr', 0, 0, 0, 0],\r\n        ['Mn', 0, 0, 0, 0],\r\n        ['Fe', 0, 0, 0, 0],\r\n        ['Co', 0, 0, 0, 0],\r\n        ['Ni', 0, 0, 0, 0],\r\n        ['Cu', 0, 0, 0, 0],\r\n        ['Zn', 0, 0, 0, 0],\r\n        ['Ga', 0, 0, 0, 0],\r\n        ['Ge', 0, 0, 0, 0],\r\n        ['As', 0, 0, 0, 0],\r\n        ['Se', 0, 0, 0, 0],\r\n        ['Br', 1.95, 0, 0, 0],\r\n        ['Kr', 0, 0, 0, 0],\r\n        ['Rb', 0, 0, 0, 0],\r\n        ['Sr', 0, 0, 0, 0],\r\n        ['Y', 0, 0, 0, 0],\r\n        ['Zr', 0, 0, 0, 0],\r\n        ['Nb', 0, 0, 0, 0],\r\n        ['Mo', 0, 0, 0, 0],\r\n        ['Tc', 0, 0, 0, 0],\r\n        ['Ru', 0, 0, 0, 0],\r\n        ['Rh', 0, 0, 0, 0],\r\n        ['Pd', 0, 0, 0, 0],\r\n        ['Ag', 0, 0, 0, 0],\r\n        ['Cd', 0, 0, 0, 0],\r\n        ['In', 0, 0, 0, 0],\r\n        ['Sn', 0, 0, 0, 0],\r\n        ['Sb', 0, 0, 0, 0],\r\n        ['Te', 0, 0, 0, 0],\r\n        ['I', 2.15, 0, 0, 0],\r\n        ['Xe', 0, 0, 0, 0],\r\n        ['Cs', 0, 0, 0, 0],\r\n        ['Ba', 0, 0, 0, 0],\r\n        ['La', 0, 0, 0, 0],\r\n        ['Ce', 0, 0, 0, 0],\r\n        ['Pr', 0, 0, 0, 0],\r\n        ['Nd', 0, 0, 0, 0],\r\n        ['Pm', 0, 0, 0, 0],\r\n        ['Sm', 0, 0, 0, 0],\r\n        ['Eu', 0, 0, 0, 0],\r\n        ['Gd', 0, 0, 0, 0],\r\n        ['Tb', 0, 0, 0, 0],\r\n        ['Dy', 0, 0, 0, 0],\r\n        ['Ho', 0, 0, 0, 0],\r\n        ['Er', 0, 0, 0, 0],\r\n        ['Tm', 0, 0, 0, 0],\r\n        ['Yb', 0, 0, 0, 0],\r\n        ['Lu', 0, 0, 0, 0],\r\n        ['Hf', 0, 0, 0, 0],\r\n        ['Ta', 0, 0, 0, 0],\r\n        ['W', 0, 0, 0, 0],\r\n        ['Re', 0, 0, 0, 0],\r\n        ['Os', 0, 0, 0, 0],\r\n        ['Ir', 0, 0, 0, 0],\r\n        ['Pt', 0, 0, 0, 0],\r\n        ['Au', 0, 0, 0, 0],\r\n        ['Hg', 0, 0, 0, 0],\r\n        ['Tl', 0, 0, 0, 0],\r\n        ['Pb', 0, 0, 0, 0],\r\n        ['Bi', 0, 0, 0, 0],\r\n        ['Po', 0, 0, 0, 0],\r\n        ['At', 0, 0, 0, 0],\r\n        ['Rn', 0, 0, 0, 0],\r\n        ['Fr', 0, 0, 0, 0],\r\n        ['Ra', 0, 0, 0, 0],\r\n        ['Ac', 0, 0, 0, 0],\r\n        ['Th', 0, 0, 0, 0],\r\n        ['Pa', 0, 0, 0, 0],\r\n        ['U', 0, 0, 0, 0],\r\n        ['Np', 0, 0, 0, 0],\r\n        ['Pu', 0, 0, 0, 0],\r\n        ['Am', 0, 0, 0, 0],\r\n        ['Cm', 0, 0, 0, 0],\r\n        ['Bk', 0, 0, 0, 0],\r\n        ['Cf', 0, 0, 0, 0],\r\n        ['Es', 0, 0, 0, 0],\r\n        ['Fm', 0, 0, 0, 0],\r\n        ['Md', 0, 0, 0, 0],\r\n        ['No', 0, 0, 0, 0],\r\n        ['Lr', 0, 0, 0, 0],\r\n        ['Rf', 0, 0, 0, 0],\r\n        ['Db', 0, 0, 0, 0],\r\n        ['Sg', 0, 0, 0, 0],\r\n        ['Bh', 0, 0, 0, 0],\r\n        ['Hs', 0, 0, 0, 0],\r\n        ['Mt', 0, 0, 0, 0],\r\n        ['Ds', 0, 0, 0, 0],\r\n        ['Rg', 0, 0, 0, 0],\r\n        ['Uub', 0, 0, 0, 0],\r\n        ['Uut', 0, 0, 0, 0],\r\n        ['Uuq', 0, 0, 0, 0],\r\n        ['Uup', 0, 0, 0, 0],\r\n        ['Uuh', 0, 0, 0, 0],\r\n        ['Uus', 0, 0, 0, 0],\r\n        ['Uuo', 0, 0, 0, 0],]\r\n\r\nelements = [\"H\",\"He\",\"Li\",\"Be\",\"B\",\"C\",\"N\",\"O\",\"F\",\"Ne\",\"Na\",\"Mg\",\"Al\",\"Si\",\r\n\t\t\t\"P\",\"S\",\"Cl\",\"Ar\",\"K\",\"Ca\",\"Sc\",\"Ti\",\"V\",\"Cr\",\"Mn\",\"Fe\",\"Co\",\"Ni\",\r\n\t\t\t\"Cu\",\"Zn\",\"Ga\",\"Ge\",\"As\",\"Se\",\"Br\",\"Kr\",\"Rb\",\"Sr\",\"Y\",\"Zr\",\"Nb\",\"Mo\",\r\n\t\t\t\"Tc\",\"Ru\",\"Rh\",\"Pd\",\"Ag\",\"Cd\",\"In\",\"Sn\",\"Sb\",\"Te\",\"I\",\"Xe\",\"Cs\",\"Ba\",\r\n\t\t\t\"La\",\"Ce\",\"Pr\",\"Nd\",\"Pm\",\"Sm\",\"Eu\",\"Gd\",\"Tb\",\"Dy\",\"Ho\",\"Er\",\"Tm\",\"Yb\",\r\n\t\t\t\"Lu\",\"Hf\",\"Ta\",\"W\",\"Re\",\"Os\",\"Ir\",\"Pt\",\"Au\",\"Hg\",\"Tl\",\"Pb\",\"Bi\",\"Po\",\"At\",\r\n\t\t\t\"Rn\",\"Fr\",\"Ra\",\"Ac\",\"Th\",\"Pa\",\"U\",\"Np\",\"Pu\",\"Am\",\"Cm\",\"Bk\",\"Cf\",\"Es\",\"Fm\",\r\n\t\t\t\"Md\",\"No\",\"Lr\",\"Rf\",\"Db\",\"Sg\",\"Bh\",\"Hs\",\"Mt\",\"Ds\",\"Rg\",\"Uub\",\"Uut\",\"Uuq\",\r\n\t\t\t\"Uup\",\"Uuh\",\"Uus\",\"Uuo\"]\r\n\r\n## covalent radii (taken from Pyykko and Atsumi, Chem. Eur. J. 15, 2009, 188-197 ##\r\n## values for metals decreased by 10 % ##\r\nrcov = [0.32, 0.46, 1.20, 0.94, 0.77, 0.75, 0.71, 0.63, 0.64, 0.67,\r\n\t\t1.40, 1.25, 1.13, 1.04, 1.10, 1.02, 0.99, 0.96, 1.76, 1.54,\r\n\t\t1.33, 1.22, 1.21, 1.10, 1.07, 1.04, 1.00, 0.99, 1.01, 1.09,\r\n\t\t1.12, 1.09, 1.15, 1.10, 1.14, 1.17, 1.89, 1.67, 1.47, 1.39,\r\n\t\t1.32, 1.24, 1.15, 1.13, 1.13, 1.08, 1.15, 1.23, 1.28, 1.26,\r\n\t\t1.26, 1.23, 1.32, 1.31, 2.09, 1.76, 1.62, 1.47, 1.58, 1.57,\r\n\t\t1.56, 1.55, 1.51, 1.52, 1.51, 1.50, 1.49, 1.49, 1.48, 1.53,\r\n\t\t1.46, 1.37, 1.31, 1.23, 1.18, 1.16, 1.11, 1.12, 1.13, 1.32,\r\n\t\t1.30, 1.30, 1.36, 1.31, 1.38, 1.42, 2.01, 1.81, 1.67, 1.58,\r\n\t\t1.52, 1.53, 1.54, 1.55]\r\n", "meta": {"hexsha": "f2f127587c98275166007707332c00e1ecd79279", "size": 36533, "ext": "py", "lang": "Python", "max_stars_repo_path": "sterimoltools.py", "max_stars_repo_name": "ipendlet/Sterimol", "max_stars_repo_head_hexsha": "1951f56dfc5b01f9b5982c2fe1ac4e249aa21b7e", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sterimoltools.py", "max_issues_repo_name": "ipendlet/Sterimol", "max_issues_repo_head_hexsha": "1951f56dfc5b01f9b5982c2fe1ac4e249aa21b7e", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sterimoltools.py", "max_forks_repo_name": "ipendlet/Sterimol", "max_forks_repo_head_hexsha": "1951f56dfc5b01f9b5982c2fe1ac4e249aa21b7e", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.6289381564, "max_line_length": 468, "alphanum_fraction": 0.523444557, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 12634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.1946516929815998}}
{"text": "# Copyright 2014-2019 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Samragni Banerjee <samragnibanerjee4@gmail.com>\n#         Alexander Sokolov <alexander.y.sokolov@gmail.com>\n#\n\n'''\nRestricted algebraic diagrammatic construction\n'''\nimport time\nimport numpy as np\nimport pyscf.ao2mo as ao2mo\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf.adc import radc_ao2mo\nfrom pyscf.adc import dfadc\nfrom pyscf import __config__\nfrom pyscf import df\n\ndef kernel(adc, nroots=1, guess=None, eris=None, verbose=None):\n\n    adc.method = adc.method.lower()\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n       raise NotImplementedError(adc.method)\n\n    cput0 = (time.clock(), time.time())\n    log = logger.Logger(adc.stdout, adc.verbose)\n    if adc.verbose >= logger.WARN:\n        adc.check_sanity()\n    adc.dump_flags()\n\n    if eris is None:\n        eris = adc.transform_integrals()\n\n    imds = adc.get_imds(eris)\n    matvec, diag = adc.gen_matvec(imds, eris)\n\n    guess = adc.get_init_guess(nroots, diag, ascending = True)\n\n    conv, E, U = lib.linalg_helper.davidson_nosym1(lambda xs : [matvec(x) for x in xs], guess, diag, nroots=nroots, verbose=log, tol=adc.conv_tol, max_cycle=adc.max_cycle, max_space=adc.max_space)\n\n    U = np.array(U)\n\n    T = adc.get_trans_moments()\n\n    spec_factors = adc.get_spec_factors(T, U, nroots)\n   \n    nfalse = np.shape(conv)[0] - np.sum(conv)\n    if nfalse >= 1:\n        print (\"*************************************************************\")\n        print (\" WARNING : \", \"Davidson iterations for \",nfalse, \"root(s) not converged\")\n        print (\"*************************************************************\")\n\n    if adc.verbose >= logger.INFO:\n        if nroots == 1:\n            logger.info(adc, '%s root %d    Energy (Eh) = %.10f    Energy (eV) = %.8f    Spec factors = %.8f    conv = %s',\n                         adc.method, 0, E, E*27.2114, spec_factors, conv)\n        else :\n            for n, en, pn, convn in zip(range(nroots), E, spec_factors, conv):\n                logger.info(adc, '%s root %d    Energy (Eh) = %.10f    Energy (eV) = %.8f    Spec factors = %.8f    conv = %s',\n                          adc.method, n, en, en*27.2114, pn, convn)\n        log.timer('ADC', *cput0)\n\n    return E, U, spec_factors\n\n\ndef compute_amplitudes_energy(myadc, eris, verbose=None):\n\n    t1, t2 = myadc.compute_amplitudes(eris)\n    e_corr = myadc.compute_energy(t1, t2, eris)\n\n    return e_corr, t1, t2\n\n\ndef compute_amplitudes(myadc, eris):\n\n    if myadc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(myadc.method)\n\n    nocc = myadc._nocc\n    nvir = myadc._nvir\n\n    eris_oooo = eris.oooo\n    eris_ovoo = eris.ovoo\n    eris_ovov = eris.ovov\n    eris_oovv = eris.oovv\n    eris_ovvo = eris.ovvo\n    eris_ovvv = eris.ovvv\n\n    e = myadc.mo_energy\n\n    d_ij = e[:nocc][:,None] + e[:nocc]\n\n    d_ab = e[nocc:][:,None] + e[nocc:]\n\n    D2 = d_ij.reshape(-1,1) - d_ab.reshape(-1)\n\n    D2 = D2.reshape((nocc,nocc,nvir,nvir))\n\n    D1 = e[:nocc][:None].reshape(-1,1) - e[nocc:].reshape(-1)\n    D1 = D1.reshape((nocc,nvir))\n\n    # Compute first-order doubles t2 (tijab)\n\n    v2e_oovv = eris_ovov[:].transpose(0,2,1,3).copy()\n\n    t2_1 = v2e_oovv/D2\n\n    # Compute second-order singles t1 (tij)\n\n    t2_1_a = t2_1 - t2_1.transpose(1,0,2,3).copy()\n\n    eris_ovvv = radc_ao2mo.unpack_eri_1(eris.ovvv, nvir)\n    t1_2 = 0.5*lib.einsum('kdac,ikcd->ia',eris_ovvv,t2_1_a,optimize=True)\n    t1_2 -= 0.5*lib.einsum('kcad,ikcd->ia',eris_ovvv,t2_1_a,optimize=True)\n    t1_2 += lib.einsum('kdac,ikcd->ia',eris_ovvv,t2_1,optimize=True)\n    del eris_ovvv\n    t1_2 -= 0.5*lib.einsum('lcki,klac->ia',eris_ovoo,t2_1_a,optimize=True)\n    t1_2 -= 0.5*lib.einsum('kcli,lkac->ia',eris_ovoo,t2_1_a,optimize=True)\n    t1_2 -= lib.einsum('lcki,klac->ia',eris_ovoo,t2_1,optimize=True)\n\n    t1_2 = t1_2/D1\n\n    t2_2 = None\n    t1_3 = None\n\n    if (myadc.method == \"adc(2)-x\" or myadc.method == \"adc(3)\"):\n\n    # Compute second-order doubles t2 (tijab)\n\n        eris_oooo = eris.oooo\n        eris_ovvo = eris.ovvo\n\n        if isinstance(eris.vvvv, np.ndarray):\n            eris_vvvv = eris.vvvv\n            temp = t2_1.reshape(nocc*nocc,nvir*nvir)\n            t2_2 = np.dot(temp,eris_vvvv.T).reshape(nocc,nocc,nvir,nvir)\n        elif isinstance(eris.vvvv, list):\n            t2_2 = contract_ladder(myadc,t2_1,eris.vvvv)\n        else:\n            t2_2 = contract_ladder(myadc,t2_1,eris.Lvv)\n\n        t2_2 += lib.einsum('kilj,klab->ijab',eris_oooo,t2_1,optimize=True)\n        t2_2 += lib.einsum('kcbj,kica->ijab',eris_ovvo,t2_1_a,optimize=True)\n        t2_2 += lib.einsum('kcbj,ikac->ijab',eris_ovvo,t2_1,optimize=True)\n        t2_2 -= lib.einsum('kjbc,ikac->ijab',eris_oovv,t2_1,optimize=True)\n        t2_2 -= lib.einsum('kibc,kjac->ijab',eris_oovv,t2_1,optimize=True)\n        t2_2 -= lib.einsum('kjac,ikcb->ijab',eris_oovv,t2_1,optimize=True)\n        t2_2 += lib.einsum('kcai,kjcb->ijab',eris_ovvo,t2_1_a,optimize=True)\n        t2_2 += lib.einsum('kcai,kjcb->ijab',eris_ovvo,t2_1,optimize=True)\n        t2_2 -= lib.einsum('kiac,kjcb->ijab',eris_oovv,t2_1,optimize=True)\n\n        t2_2 = t2_2/D2\n        \n    if (myadc.method == \"adc(3)\"):\n    # Compute third-order singles (tij)\n\n        t2_2_a = t2_2 - t2_2.transpose(1,0,2,3).copy()\n\n        eris_ovoo = eris.ovoo\n\n        t1_3 = lib.einsum('d,ilad,ld->ia',e[nocc:],t2_1_a,t1_2,optimize=True)\n        t1_3 += lib.einsum('d,ilad,ld->ia',e[nocc:],t2_1,t1_2,optimize=True)\n \n        t1_3 -= lib.einsum('l,ilad,ld->ia',e[:nocc],t2_1_a, t1_2,optimize=True)\n        t1_3 -= lib.einsum('l,ilad,ld->ia',e[:nocc],t2_1,t1_2,optimize=True)\n \n        t1_3 += 0.5*lib.einsum('a,ilad,ld->ia',e[nocc:],t2_1_a, t1_2,optimize=True)\n        t1_3 += 0.5*lib.einsum('a,ilad,ld->ia',e[nocc:],t2_1,t1_2,optimize=True)\n \n        t1_3 -= 0.5*lib.einsum('i,ilad,ld->ia',e[:nocc],t2_1_a, t1_2,optimize=True)\n        t1_3 -= 0.5*lib.einsum('i,ilad,ld->ia',e[:nocc],t2_1,t1_2,optimize=True)\n \n        t1_3 += lib.einsum('ld,iald->ia',t1_2,eris_ovov,optimize=True)\n        t1_3 -= lib.einsum('ld,laid->ia',t1_2,eris_ovov,optimize=True)\n        t1_3 += lib.einsum('ld,iald->ia',t1_2,eris_ovov,optimize=True)\n \n        t1_3 += lib.einsum('ld,ldai->ia',t1_2,eris_ovvo ,optimize=True)\n        t1_3 -= lib.einsum('ld,liad->ia',t1_2,eris_oovv ,optimize=True)\n        t1_3 += lib.einsum('ld,ldai->ia',t1_2,eris_ovvo,optimize=True)\n \n        t1_3 -= 0.5*lib.einsum('lmad,mdli->ia',t2_2_a,eris_ovoo,optimize=True)\n        t1_3 += 0.5*lib.einsum('lmad,ldmi->ia',t2_2_a,eris_ovoo,optimize=True)\n        t1_3 -=     lib.einsum('lmad,mdli->ia',t2_2,eris_ovoo,optimize=True)\n \n        eris_ovvv = radc_ao2mo.unpack_eri_1(eris.ovvv, nvir)\n        t1_3 += 0.5*lib.einsum('ilde,lead->ia',t2_2_a,eris_ovvv,optimize=True)\n        t1_3 -= 0.5*lib.einsum('ilde,ldae->ia',t2_2_a,eris_ovvv,optimize=True)\n        t1_3 -= lib.einsum('ildf,mefa,lmde->ia',t2_1_a, eris_ovvv,  t2_1_a ,optimize=True)\n        t1_3 += lib.einsum('ildf,mafe,lmde->ia',t2_1_a, eris_ovvv,  t2_1_a ,optimize=True)\n        t1_3 += lib.einsum('ilfd,mefa,mled->ia',t2_1,eris_ovvv, t2_1,optimize=True)\n        t1_3 -= lib.einsum('ilfd,mafe,mled->ia',t2_1,eris_ovvv, t2_1,optimize=True)\n        t1_3 += 0.5*lib.einsum('ilaf,mefd,lmde->ia',t2_1_a,eris_ovvv,t2_1_a,optimize=True)\n        t1_3 -= 0.5*lib.einsum('ilaf,mdfe,lmde->ia',t2_1_a,eris_ovvv,t2_1_a,optimize=True)\n        t1_3 += 0.5*lib.einsum('lmdf,iaef,lmde->ia',t2_1_a,eris_ovvv,t2_1_a,optimize=True)\n        t1_3 -= 0.5*lib.einsum('lmdf,ifea,lmde->ia',t2_1_a,eris_ovvv,t2_1_a,optimize=True)\n        t1_3 += lib.einsum('mlfd,iaef,mled->ia',t2_1,eris_ovvv,t2_1,optimize=True)\n        t1_3 -= lib.einsum('mlfd,ifea,mled->ia',t2_1,eris_ovvv,t2_1,optimize=True)\n        t1_3 -= 0.25*lib.einsum('lmef,iedf,lmad->ia',t2_1_a,eris_ovvv,t2_1_a,optimize=True)\n        t1_3 += 0.25*lib.einsum('lmef,ifde,lmad->ia',t2_1_a,eris_ovvv,t2_1_a,optimize=True)\n\n        t1_3 += 0.5*lib.einsum('ilaf,mefd,lmde->ia',t2_1,eris_ovvv,t2_1_a,optimize=True)\n        t1_3 -= 0.5*lib.einsum('ilaf,mdfe,lmde->ia',t2_1,eris_ovvv,t2_1_a,optimize=True)\n\n        t1_3 -= lib.einsum('ildf,mafe,mlde->ia',t2_1,eris_ovvv,t2_1,optimize=True)\n        t1_3 += lib.einsum('ilaf,mefd,mled->ia',t2_1,eris_ovvv,t2_1,optimize=True)\n        t1_3 += 0.5*lib.einsum('lmdf,iaef,lmde->ia',t2_1_a,eris_ovvv,t2_1_a,optimize=True)\n        t1_3 += lib.einsum('lmdf,iaef,lmde->ia',t2_1,eris_ovvv,t2_1,optimize=True)\n        t1_3 -= lib.einsum('lmef,iedf,lmad->ia',t2_1,eris_ovvv,t2_1,optimize=True)\n\n        t1_3 += lib.einsum('ilde,lead->ia',t2_2,eris_ovvv,optimize=True)\n        t1_3 -= lib.einsum('ildf,mefa,lmde->ia',t2_1_a,eris_ovvv, t2_1,optimize=True)\n        t1_3 += lib.einsum('ilfd,mefa,lmde->ia',t2_1,eris_ovvv,t2_1_a ,optimize=True)\n        t1_3 += lib.einsum('ilaf,mefd,lmde->ia',t2_1_a,eris_ovvv,t2_1,optimize=True)\n        del eris_ovvv\n\n        t1_3 += 0.25*lib.einsum('inde,lamn,lmde->ia',t2_1_a,eris_ovoo,t2_1_a,optimize=True)\n        t1_3 -= 0.25*lib.einsum('inde,maln,lmde->ia',t2_1_a,eris_ovoo,t2_1_a,optimize=True)\n        t1_3 += lib.einsum('inde,lamn,lmde->ia',t2_1,eris_ovoo,t2_1,optimize=True)\n \n        t1_3 += 0.5*lib.einsum('inad,lemn,lmde->ia',t2_1_a,eris_ovoo,t2_1_a,optimize=True)\n        t1_3 -= 0.5*lib.einsum('inad,meln,lmde->ia',t2_1_a,eris_ovoo,t2_1_a,optimize=True)\n        t1_3 -= 0.5 * lib.einsum('inad,lemn,mlde->ia',t2_1_a,eris_ovoo,t2_1,optimize=True)\n        t1_3 -= 0.5 * lib.einsum('inad,meln,lmde->ia',t2_1_a,eris_ovoo,t2_1,optimize=True)\n        t1_3 -= 0.5 *lib.einsum('inad,lemn,lmed->ia',t2_1,eris_ovoo,t2_1,optimize=True)\n        t1_3 -= 0.5*lib.einsum('inad,meln,mled->ia',t2_1,eris_ovoo,t2_1,optimize=True)\n        t1_3 += 0.5*lib.einsum('inad,lemn,lmde->ia',t2_1,eris_ovoo,t2_1_a,optimize=True)\n        t1_3 -= 0.5*lib.einsum('inad,meln,lmde->ia',t2_1,eris_ovoo,t2_1_a,optimize=True)\n \n        t1_3 -= 0.5*lib.einsum('lnde,ianm,lmde->ia',t2_1_a,eris_ovoo,t2_1_a,optimize=True)\n        t1_3 += 0.5*lib.einsum('lnde,naim,lmde->ia',t2_1_a,eris_ovoo,t2_1_a,optimize=True)\n        t1_3 -= lib.einsum('nled,ianm,mled->ia',t2_1,eris_ovoo,t2_1,optimize=True)\n        t1_3 += lib.einsum('nled,naim,mled->ia',t2_1,eris_ovoo,t2_1,optimize=True)\n        t1_3 -= 0.5*lib.einsum('lnde,ianm,lmde->ia',t2_1_a,eris_ovoo,t2_1_a,optimize=True)\n        t1_3 -= lib.einsum('lnde,ianm,lmde->ia',t2_1,eris_ovoo,t2_1,optimize=True)\n \n        t1_3 -= lib.einsum('lnde,ienm,lmad->ia',t2_1_a,eris_ovoo,t2_1_a,optimize=True)\n        t1_3 += lib.einsum('lnde,neim,lmad->ia',t2_1_a,eris_ovoo,t2_1_a,optimize=True)\n        t1_3 += lib.einsum('lnde,neim,lmad->ia',t2_1,eris_ovoo,t2_1_a,optimize=True)\n        t1_3 += lib.einsum('nled,ienm,mlad->ia',t2_1,eris_ovoo,t2_1,optimize=True)\n        t1_3 -= lib.einsum('nled,neim,mlad->ia',t2_1,eris_ovoo,t2_1,optimize=True)\n        t1_3 += lib.einsum('lned,ienm,lmad->ia',t2_1,eris_ovoo,t2_1,optimize=True)\n        t1_3 -= lib.einsum('lnde,neim,mlad->ia',t2_1_a,eris_ovoo,t2_1,optimize=True)\n \n        t1_3 = t1_3/D1\n\n    t1 = (t1_2, t1_3)\n    t2 = (t2_1, t2_2)\n\n    return t1, t2\n\n\ndef compute_energy(myadc, t1, t2, eris):\n\n    if myadc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(myadc.method)\n\n    nocc = myadc._nocc\n    nvir = myadc._nvir\n\n    eris_ovov = eris.ovov\n\n    t2_1  = t2[0]\n\n    #Compute MP2 correlation energy\n\n    e_mp2 = 0.5 * lib.einsum('ijab,iajb', t2_1, eris_ovov,optimize=True)\n    e_mp2 -= 0.5 * lib.einsum('ijab,ibja', t2_1, eris_ovov,optimize=True)\n    e_mp2 -= 0.5 * lib.einsum('jiab,iajb', t2_1, eris_ovov,optimize=True)\n    e_mp2 += 0.5 * lib.einsum('jiab,ibja', t2_1, eris_ovov,optimize=True)\n    e_mp2 += lib.einsum('ijab,iajb', t2_1, eris_ovov,optimize=True)\n\n    e_corr = e_mp2\n\n    if (myadc.method == \"adc(3)\"):\n\n        t2_1_a = t2_1 - t2_1.transpose(1,0,2,3).copy()\n\n        #Compute MP3 correlation energy\n        eris_oovv = eris.oovv\n        eris_ovvo = eris.ovvo\n        eris_oooo = eris.oooo\n\n        temp_t2_a = None\n        temp_t2_ab = None\n        temp_t2_t2 = None\n        temp_t2a_t2a = None\n        temp_t2_a_vvvv = None\n        temp_t2_ab_vvvv = None\n\n        eris_vvvv = eris.vvvv\n\n        if isinstance(eris.vvvv, np.ndarray):\n            temp_t2_a = t2_1_a.reshape(nocc*nocc,nvir*nvir)\n            temp_t2_a_vvvv = np.dot(temp_t2_a,eris_vvvv.T).reshape(nocc,nocc,nvir,nvir)\n        elif isinstance(eris.vvvv, list): \n            temp_t2_a_vvvv = contract_ladder(myadc,t2_1_a,eris.vvvv)\n        else : \n            temp_t2_a_vvvv = contract_ladder(myadc,t2_1_a,eris.Lvv)\n\n        if isinstance(eris.vvvv, np.ndarray):\n            temp_t2_ab = t2_1.reshape(nocc*nocc,nvir*nvir)\n            temp_t2_ab_vvvv = np.dot(temp_t2_ab,eris_vvvv.T).reshape(nocc,nocc,nvir,nvir)\n        elif isinstance(eris.vvvv, list): \n            temp_t2_ab_vvvv = contract_ladder(myadc,t2_1,eris.vvvv)\n        else : \n            temp_t2_ab_vvvv = contract_ladder(myadc,t2_1,eris.Lvv)\n\n\n        e_mp3 =  lib.einsum('ijcd,ijcd',temp_t2_ab_vvvv, t2_1,optimize=True)\n        del temp_t2_ab_vvvv\n\n\n        if isinstance(eris.vvvv, np.ndarray):\n            temp_t2_a = temp_t2_a.reshape(nocc,nocc,nvir,nvir)\n            temp_t2_a = np.ascontiguousarray(temp_t2_a.transpose(0,1,3,2))\n            temp_t2_a = temp_t2_a.reshape(nocc*nocc,nvir*nvir)\n            temp_t2_a_vvvv -= np.dot(temp_t2_a,eris_vvvv.T).reshape(nocc,nocc,nvir,nvir)\n        elif isinstance(eris.vvvv, list): \n            t2_1_a_t = np.ascontiguousarray(t2_1_a.transpose(0,1,3,2))\n            temp_t2_a_vvvv_n = contract_ladder(myadc,t2_1_a_t,eris.vvvv)\n            temp_t2_a_vvvv -= temp_t2_a_vvvv_n\n        else: \n            t2_1_a_t = np.ascontiguousarray(t2_1_a.transpose(0,1,3,2))\n            temp_t2_a_vvvv_n = contract_ladder(myadc,t2_1_a_t,eris.Lvv)\n            temp_t2_a_vvvv -= temp_t2_a_vvvv_n\n\n        e_mp3 += 0.25 * lib.einsum('ijcd,ijcd',temp_t2_a_vvvv, t2_1_a,optimize=True)\n       \n        temp_t2a_t2a =  lib.einsum('ijab,klab', t2_1_a, t2_1_a,optimize=True)\n        e_mp3 += 0.25 * lib.einsum('ijkl,ikjl',temp_t2a_t2a, eris_oooo,optimize=True)\n        e_mp3 -= 0.25 * lib.einsum('ijkl,iljk',temp_t2a_t2a, eris_oooo,optimize=True)\n        del temp_t2a_t2a\n\n        temp_t2_t2 =  lib.einsum('ijab,klab', t2_1, t2_1,optimize=True)\n        e_mp3 +=  lib.einsum('ijkl,ikjl',temp_t2_t2, eris_oooo,optimize=True)\n        del temp_t2_t2\n\n        temp_t2_t2 = lib.einsum('ijab,ikcb->akcj', t2_1_a, t2_1_a,optimize=True)\n        temp_t2_t2 += lib.einsum('jiab,kicb->akcj', t2_1, t2_1,optimize=True)\n        e_mp3 -= 2 * lib.einsum('akcj,kjac',temp_t2_t2, eris_oovv,optimize=True)\n        e_mp3 += 2 * lib.einsum('akcj,kcaj',temp_t2_t2, eris_ovvo,optimize=True)\n        del temp_t2_t2\n\n        temp_t2_t2 = lib.einsum('ijab,ikcb->akcj', t2_1, t2_1,optimize=True)\n        e_mp3 -= lib.einsum('akcj,kjac',temp_t2_t2, eris_oovv,optimize=True)\n        del temp_t2_t2\n   \n        temp_t2_t2 = lib.einsum('jiba,kibc->akcj', t2_1, t2_1,optimize=True)\n        e_mp3 -= lib.einsum('akcj,kjac',temp_t2_t2, eris_oovv,optimize=True)\n        del temp_t2_t2\n\n        temp_t2_t2 = -lib.einsum('ijab,ikbc->akcj', t2_1_a, t2_1,optimize=True)\n        temp_t2_t2 -= lib.einsum('jiab,ikcb->akcj', t2_1, t2_1_a,optimize=True)\n        e_mp3 += lib.einsum('akcj,kcaj',temp_t2_t2, eris_ovvo,optimize=True)\n        del temp_t2_t2\n\n        temp_t2_t2 = -lib.einsum('ijba,ikcb->akcj', t2_1, t2_1_a,optimize=True)\n        temp_t2_t2 -= lib.einsum('ijab,kicb->akcj', t2_1_a, t2_1,optimize=True)\n        e_mp3 += lib.einsum('akcj,kcaj',temp_t2_t2, eris_ovvo,optimize=True)\n        del temp_t2_t2\n    \n        e_corr += e_mp3\n\n    return e_corr\n\n\ndef contract_ladder(myadc,t_amp,vvvv):\n\n    nocc = myadc._nocc\n    nvir = myadc._nvir\n\n    t_amp_t = np.ascontiguousarray(t_amp.reshape(nocc*nocc,nvir*nvir).T)\n    t = np.zeros((nvir,nvir, nocc*nocc))\n    chnk_size = radc_ao2mo.calculate_chunk_size(myadc)\n\n    a = 0\n    if isinstance(vvvv, list):\n        for dataset in vvvv:\n             k = dataset.shape[0]\n             dataset = dataset[:].reshape(-1,nvir*nvir)\n             t[a:a+k] = np.dot(dataset,t_amp_t).reshape(-1,nvir,nocc*nocc)\n             a += k\n    elif getattr(myadc, 'with_df', None):\n        for p in range(0,nvir,chnk_size):\n            vvvv_p = dfadc.get_vvvv_df(myadc, vvvv, p, chnk_size)\n            k = vvvv_p.shape[0]\n            vvvv_p = vvvv_p.reshape(-1,nvir*nvir)\n            t[a:a+k] = np.dot(vvvv_p,t_amp_t).reshape(-1,nvir,nocc*nocc)\n            del (vvvv_p)\n            a += k\n    else :\n        raise Exception(\"Unknown vvvv type\") \n\n    t = np.ascontiguousarray(t.transpose(2,0,1)).reshape(nocc, nocc, nvir, nvir)\n\n    return t\n\n\ndef density_matrix(myadc, T=None):\n\n    if T is None:\n        T = RADCIP(myadc).get_trans_moments()\n\n    nocc = myadc._nocc\n    nvir = myadc._nvir\n\n    n_singles = nocc\n    n_doubles = nvir * nocc * nocc\n    ij_ind = np.tril_indices(nocc, k=-1)\n\n    s1 = 0\n    f1 = n_singles\n    s2 = f1\n    f2 = s2 + n_doubles\n\n    T_doubles = T[:,n_singles:]\n    T_doubles = T_doubles.reshape(-1,nvir,nocc,nocc)\n    T_doubles_transpose = T_doubles.transpose(0,1,3,2).copy()\n    T_bab = (2/3)*T_doubles + (1/3)*T_doubles_transpose\n\n    T_aaa = T_bab - T_bab.transpose(0,1,3,2)\n\n    T_a = T[:,s1:f1]\n    T_bab = T_bab.reshape(-1,n_doubles)\n    T_aaa = T_aaa.reshape(-1,n_doubles)\n\n    dm = 2 * np.dot(T_a,T_a.T) + np.dot(T_aaa, T_aaa.T) + 2 * np.dot(T_bab, T_bab.T)\n\n    return dm\n\n\nclass RADC(lib.StreamObject):\n    '''Ground state calculations\n\n    Attributes:\n        verbose : int\n            Print level.  Default value equals to :class:`Mole.verbose`\n        max_memory : float or int\n            Allowed memory in MB.  Default value equals to :class:`Mole.max_memory`\n        incore_complete : bool\n            Avoid all I/O. Default is False.\n        method : string\n            nth-order ADC method. Options are : ADC(2), ADC(2)-X, ADC(3). Default is ADC(2).\n\n            >>> mol = gto.M(atom = 'H 0 0 0; F 0 0 1.1', basis = 'ccpvdz')\n            >>> mf = scf.RHF(mol).run()\n            >>> myadc = adc.RADC(mf).run()\n\n    Saved results\n\n        e_corr : float\n            MPn correlation correction\n        e_tot : float\n            Total energy (HF + correlation)\n        t1, t2 :\n            T amplitudes t1[i,a], t2[i,j,a,b]  (i,j in occ, a,b in virt)\n    '''\n    incore_complete = getattr(__config__, 'adc_radc_RADC_incore_complete', False)\n    async_io = getattr(__config__, 'adc_radc_RADC_async_io', True)\n    blkmin = getattr(__config__, 'adc_radc_RADC_blkmin', 4)\n    memorymin = getattr(__config__, 'adc_radc_RADC_memorymin', 2000)\n    \n    def __init__(self, mf, frozen=0, mo_coeff=None, mo_occ=None):\n        from pyscf import gto\n        \n        if 'dft' in str(mf.__module__):\n            raise NotImplementedError('DFT reference for UADC')\n        \n        if mo_coeff  is None: mo_coeff  = mf.mo_coeff\n        if mo_occ    is None: mo_occ    = mf.mo_occ\n        \n        self.mol = mf.mol\n        self._scf = mf\n        self.verbose = self.mol.verbose\n        self.stdout = self.mol.stdout\n        self.max_memory = mf.max_memory\n\n        self.max_space = getattr(__config__, 'adc_radc_RADC_max_space', 12)\n        self.max_cycle = getattr(__config__, 'adc_radc_RADC_max_cycle', 50)\n        self.conv_tol = getattr(__config__, 'adc_radc_RADC_conv_tol', 1e-12)\n        self.scf_energy = mf.e_tot\n        \n        self.frozen = frozen\n        self.incore_complete = self.incore_complete or self.mol.incore_anyway\n        \n        self.mo_coeff = mo_coeff\n        self.mo_occ = mo_occ\n        self.e_corr = None\n        self.e_tot = None\n        self.t1 = None\n        self.t2 = None\n        self._nocc = mf.mol.nelectron//2\n        self._nmo = mo_coeff.shape[1]\n        self._nvir = self._nmo - self._nocc\n        self.mo_energy = mf.mo_energy\n        self.chkfile = mf.chkfile\n        self.method = \"adc(2)\"\n        self.method_type = \"ip\"\n        self.with_df = None\n\n        keys = set(('conv_tol', 'e_corr', 'method', 'mo_coeff', 'mol', 'mo_energy', 'max_memory', 'incore_complete', 'scf_energy', 'e_tot', 't1', 'frozen', 'chkfile', 'max_space', 't2', 'mo_occ', 'max_cycle'))\n\n        self._keys = set(self.__dict__.keys()).union(keys)\n    \n    compute_amplitudes = compute_amplitudes\n    compute_energy = compute_energy\n    transform_integrals = radc_ao2mo.transform_integrals_incore\n    make_rdm1 = density_matrix \n    \n    def dump_flags(self, verbose=None):\n        logger.info(self, '')\n        logger.info(self, '******** %s ********', self.__class__)\n        logger.info(self, 'max_space = %d', self.max_space)\n        logger.info(self, 'max_cycle = %d', self.max_cycle)\n        logger.info(self, 'conv_tol = %s', self.conv_tol)\n        logger.info(self, 'max_memory %d MB (current use %d MB)',\n                    self.max_memory, lib.current_memory()[0])\n        return self\n    \n    def dump_flags_gs(self, verbose=None):\n        logger.info(self, '')\n        logger.info(self, '******** %s ********', self.__class__)\n        logger.info(self, 'max_memory %d MB (current use %d MB)',\n                    self.max_memory, lib.current_memory()[0])\n        return self\n    \n    def kernel_gs(self):\n        assert(self.mo_coeff is not None)\n        assert(self.mo_occ is not None)\n    \n        self.method = self.method.lower()\n        if self.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n            raise NotImplementedError(self.method)\n    \n        if self.verbose >= logger.WARN:\n            self.check_sanity()\n        self.dump_flags_gs()\n    \n        nmo = self._nmo\n        nao = self.mo_coeff.shape[0]\n        nmo_pair = nmo * (nmo+1) // 2\n        nao_pair = nao * (nao+1) // 2\n        mem_incore = (max(nao_pair**2, nmo**4) + nmo_pair**2) * 8/1e6\n        mem_now = lib.current_memory()[0]\n\n        if getattr(self, 'with_df', None) or getattr(self._scf, 'with_df', None):  \n           if getattr(self, 'with_df', None): \n               self.with_df = self.with_df\n           else :\n               self.with_df = self._scf.with_df\n\n           def df_transform():\n               return radc_ao2mo.transform_integrals_df(self)\n           self.transform_integrals = df_transform\n        elif (self._scf._eri is None or\n            (mem_incore+mem_now >= self.max_memory and not self.incore_complete)):\n           def outcore_transform():\n               return radc_ao2mo.transform_integrals_outcore(self)\n           self.transform_integrals = outcore_transform\n\n        eris = self.transform_integrals()\n        \n        self.e_corr, self.t1, self.t2 = compute_amplitudes_energy(self, eris=eris, verbose=self.verbose)\n        self.e_tot = self.scf_energy + self.e_corr\n\n        self._finalize()\n\n        return self.e_corr, self.t1, self.t2\n\n    def kernel(self, nroots=1, guess=None, eris=None):\n        assert(self.mo_coeff is not None)\n        assert(self.mo_occ is not None)\n    \n        self.method = self.method.lower()\n        if self.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n            raise NotImplementedError(self.method)\n    \n        if self.verbose >= logger.WARN:\n            self.check_sanity()\n        self.dump_flags_gs()\n    \n        nmo = self._nmo\n        nao = self.mo_coeff.shape[0]\n        nmo_pair = nmo * (nmo+1) // 2\n        nao_pair = nao * (nao+1) // 2\n        mem_incore = (max(nao_pair**2, nmo**4) + nmo_pair**2) * 8/1e6\n        mem_now = lib.current_memory()[0]\n\n        if getattr(self, 'with_df', None) or getattr(self._scf, 'with_df', None):  \n           if getattr(self, 'with_df', None): \n               self.with_df = self.with_df\n           else :\n               self.with_df = self._scf.with_df\n\n           def df_transform():\n              return radc_ao2mo.transform_integrals_df(self)\n           self.transform_integrals = df_transform\n        elif (self._scf._eri is None or\n            (mem_incore+mem_now >= self.max_memory and not self.incore_complete)):\n           def outcore_transform():\n               return radc_ao2mo.transform_integrals_outcore(self)\n           self.transform_integrals = outcore_transform\n\n        eris = self.transform_integrals() \n            \n        self.e_corr, self.t1, self.t2 = compute_amplitudes_energy(self, eris=eris, verbose=self.verbose)\n        self.e_tot = self.scf_energy + self.e_corr\n\n        self._finalize()\n\n        self.method_type = self.method_type.lower()\n        if(self.method_type == \"ea\"):\n            e_exc, v_exc, spec_fac = self.ea_adc(nroots=nroots, guess=guess, eris=eris)\n\n        elif(self.method_type == \"ip\"):\n            e_exc, v_exc, spec_fac = self.ip_adc(nroots=nroots, guess=guess, eris=eris)\n\n        else:\n            raise NotImplementedError(self.method_type)\n\n        return e_exc, v_exc, spec_fac\n\n    def _finalize(self):\n        '''Hook for dumping results and clearing up the object.'''\n        logger.note(self, 'E_corr = %.8f  E_tot = %.8f',\n                    self.e_corr, self.e_tot)\n        return self\n    \n    def ea_adc(self, nroots=1, guess=None, eris=None):\n        return RADCEA(self).kernel(nroots, guess, eris)\n    \n    def ip_adc(self, nroots=1, guess=None, eris=None):\n        return RADCIP(self).kernel(nroots, guess, eris)\n\n    def density_fit(self, auxbasis=None, with_df = None):\n        if with_df is None:\n            self.with_df = df.DF(self._scf.mol)\n            self.with_df.max_memory = self.max_memory\n            self.with_df.stdout = self.stdout\n            self.with_df.verbose = self.verbose\n            if auxbasis is None:\n                self.with_df.auxbasis = self._scf.with_df.auxbasis\n            else :\n                self.with_df.auxbasis = auxbasis\n        else :\n            self.with_df = with_df\n        return self\n\n\ndef get_imds_ea(adc, eris=None):\n\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    t1 = adc.t1\n    t2 = adc.t2\n\n    t1_2 = t1[0]\n    t2_1 = t2[0]\n\n    t2_1_a = t2_1 - t2_1.transpose(1,0,2,3).copy()\n\n    nocc = adc._nocc\n    nvir = adc._nvir\n\n    e_occ = adc.mo_energy[:nocc]\n    e_vir = adc.mo_energy[nocc:]\n\n    idn_occ = np.identity(nocc)\n    idn_vir = np.identity(nvir)\n\n    if eris is None:\n        eris = adc.transform_integrals()\n\n    eris_ovov = eris.ovov\n\n    # a-b block\n    # Zeroth-order terms\n\n    M_ab = lib.einsum('ab,a->ab', idn_vir, e_vir)\n\n   # Second-order terms\n\n    M_ab +=  lib.einsum('l,lmad,lmbd->ab',e_occ ,t2_1_a, t2_1_a,optimize=True)\n    M_ab +=  lib.einsum('l,lmad,lmbd->ab',e_occ,t2_1, t2_1,optimize=True)\n    M_ab +=  lib.einsum('l,mlad,mlbd->ab',e_occ,t2_1, t2_1,optimize=True)\n\n    M_ab -= 0.5 *  lib.einsum('d,lmad,lmbd->ab',e_vir,t2_1_a, t2_1_a,optimize=True)\n    M_ab -= 0.5 *  lib.einsum('d,lmad,lmbd->ab',e_vir,t2_1, t2_1,optimize=True)\n    M_ab -= 0.5 *  lib.einsum('d,mlad,mlbd->ab',e_vir,t2_1, t2_1,optimize=True)\n\n    M_ab -= 0.25 *  lib.einsum('a,lmad,lmbd->ab',e_vir,t2_1_a, t2_1_a,optimize=True)\n    M_ab -= 0.25 *  lib.einsum('a,lmad,lmbd->ab',e_vir,t2_1, t2_1,optimize=True)\n    M_ab -= 0.25 *  lib.einsum('a,mlad,mlbd->ab',e_vir,t2_1, t2_1,optimize=True)\n\n    M_ab -= 0.25 *  lib.einsum('b,lmad,lmbd->ab',e_vir,t2_1_a, t2_1_a,optimize=True)\n    M_ab -= 0.25 *  lib.einsum('b,lmad,lmbd->ab',e_vir,t2_1, t2_1,optimize=True)\n    M_ab -= 0.25 *  lib.einsum('b,mlad,mlbd->ab',e_vir,t2_1, t2_1,optimize=True)\n\n    M_ab -= 0.5 *  lib.einsum('lmad,lbmd->ab',t2_1_a, eris_ovov,optimize=True)\n    M_ab += 0.5 *  lib.einsum('lmad,ldmb->ab',t2_1_a, eris_ovov,optimize=True)\n    M_ab -=        lib.einsum('lmad,lbmd->ab',t2_1, eris_ovov,optimize=True)\n\n    M_ab -= 0.5 *  lib.einsum('lmbd,lamd->ab',t2_1_a, eris_ovov,optimize=True)\n    M_ab += 0.5 *  lib.einsum('lmbd,ldma->ab',t2_1_a, eris_ovov,optimize=True)\n    M_ab -=        lib.einsum('lmbd,lamd->ab',t2_1, eris_ovov,optimize=True)\n\n    #Third-order terms\n\n    if(method =='adc(3)'):\n\n        t2_2 = t2[1]\n        t2_2_a = t2_2 - t2_2.transpose(1,0,2,3).copy()\n\n        eris_oovv = eris.oovv\n        eris_ovvo = eris.ovvo\n        eris_oooo = eris.oooo\n        \n        eris_ovvv = radc_ao2mo.unpack_eri_1(eris.ovvv, nvir)\n        M_ab += 4. * lib.einsum('ld,ldab->ab',t1_2, eris_ovvv,optimize=True)\n        M_ab -=  lib.einsum('ld,lbad->ab',t1_2, eris_ovvv,optimize=True)\n        M_ab -= lib.einsum('ld,ladb->ab',t1_2, eris_ovvv,optimize=True)\n        del eris_ovvv\n\n        M_ab -= 0.5 *  lib.einsum('lmad,lbmd->ab',t2_2_a, eris_ovov,optimize=True)\n        M_ab += 0.5 *  lib.einsum('lmad,ldmb->ab',t2_2_a, eris_ovov,optimize=True)\n        M_ab -=        lib.einsum('lmad,lbmd->ab',t2_2, eris_ovov,optimize=True)\n\n        M_ab -= 0.5 * lib.einsum('lmbd,lamd->ab',t2_2_a,eris_ovov,optimize=True)\n        M_ab += 0.5 * lib.einsum('lmbd,ldma->ab',t2_2_a, eris_ovov,optimize=True)\n        M_ab -=       lib.einsum('lmbd,lamd->ab',t2_2,eris_ovov,optimize=True)\n\n        M_ab += lib.einsum('l,lmbd,lmad->ab',e_occ, t2_1_a, t2_2_a, optimize=True)\n        M_ab += lib.einsum('l,lmbd,lmad->ab',e_occ, t2_1, t2_2, optimize=True)\n        M_ab += lib.einsum('l,mlbd,mlad->ab',e_occ, t2_1, t2_2, optimize=True)\n\n        M_ab += lib.einsum('l,lmad,lmbd->ab',e_occ, t2_1_a, t2_2_a, optimize=True)\n        M_ab += lib.einsum('l,lmad,lmbd->ab',e_occ, t2_1, t2_2, optimize=True)\n        M_ab += lib.einsum('l,mlad,mlbd->ab',e_occ, t2_1, t2_2, optimize=True)\n\n        M_ab -= 0.5*lib.einsum('d,lmbd,lmad->ab', e_vir, t2_1_a ,t2_2_a, optimize=True)\n        M_ab -= 0.5*lib.einsum('d,lmbd,lmad->ab', e_vir, t2_1 ,t2_2, optimize=True)\n        M_ab -= 0.5*lib.einsum('d,mlbd,mlad->ab', e_vir, t2_1 ,t2_2, optimize=True)\n\n        M_ab -= 0.5*lib.einsum('d,lmad,lmbd->ab', e_vir, t2_1_a, t2_2_a, optimize=True)\n        M_ab -= 0.5*lib.einsum('d,lmad,lmbd->ab', e_vir, t2_1, t2_2, optimize=True)\n        M_ab -= 0.5*lib.einsum('d,mlad,mlbd->ab', e_vir, t2_1, t2_2, optimize=True)\n\n        M_ab -= 0.25*lib.einsum('a,lmbd,lmad->ab',e_vir, t2_1_a, t2_2_a, optimize=True)\n        M_ab -= 0.25*lib.einsum('a,lmbd,lmad->ab',e_vir, t2_1, t2_2, optimize=True)\n        M_ab -= 0.25*lib.einsum('a,mlbd,mlad->ab',e_vir, t2_1, t2_2, optimize=True)\n\n        M_ab -= 0.25*lib.einsum('a,lmad,lmbd->ab',e_vir, t2_1_a, t2_2_a, optimize=True)\n        M_ab -= 0.25*lib.einsum('a,lmad,lmbd->ab',e_vir, t2_1, t2_2, optimize=True)\n        M_ab -= 0.25*lib.einsum('a,mlad,mlbd->ab',e_vir, t2_1, t2_2, optimize=True)\n\n        M_ab -= 0.25*lib.einsum('b,lmbd,lmad->ab',e_vir, t2_1_a, t2_2_a, optimize=True)\n        M_ab -= 0.25*lib.einsum('b,lmbd,lmad->ab',e_vir, t2_1, t2_2, optimize=True)\n        M_ab -= 0.25*lib.einsum('b,mlbd,mlad->ab',e_vir, t2_1, t2_2, optimize=True)\n\n        M_ab -= 0.25*lib.einsum('b,lmad,lmbd->ab',e_vir, t2_1_a, t2_2_a, optimize=True)\n        M_ab -= 0.25*lib.einsum('b,lmad,lmbd->ab',e_vir, t2_1, t2_2, optimize=True)\n        M_ab -= 0.25*lib.einsum('b,mlad,mlbd->ab',e_vir, t2_1, t2_2, optimize=True)\n\n        M_ab -= lib.einsum('lned,mlbd,nmae->ab',t2_1_a, t2_1_a, eris_oovv, optimize=True)\n        M_ab += lib.einsum('lned,mlbd,mane->ab',t2_1_a, t2_1_a, eris_ovov, optimize=True)\n        M_ab += lib.einsum('nled,mlbd,nmae->ab',t2_1, t2_1, eris_oovv, optimize=True)\n        M_ab -= lib.einsum('nled,mlbd,mane->ab',t2_1, t2_1, eris_ovov, optimize=True)\n        M_ab -= lib.einsum('lnde,mlbd,neam->ab',t2_1, t2_1_a, eris_ovvo, optimize=True)\n        M_ab += lib.einsum('lned,mlbd,neam->ab',t2_1_a, t2_1, eris_ovvo, optimize=True)\n        M_ab += lib.einsum('lned,lmbd,nmae->ab',t2_1, t2_1, eris_oovv, optimize=True)\n\n        M_ab -= lib.einsum('mled,lnad,nmeb->ab',t2_1_a, t2_1_a, eris_oovv, optimize=True)\n        M_ab += lib.einsum('mled,lnad,nbem->ab',t2_1_a, t2_1_a, eris_ovvo, optimize=True)\n        M_ab += lib.einsum('mled,nlad,nmeb->ab',t2_1, t2_1, eris_oovv, optimize=True)\n        M_ab -= lib.einsum('mled,nlad,nbem->ab',t2_1, t2_1, eris_ovvo, optimize=True)\n        M_ab += lib.einsum('lmed,lnad,nmeb->ab',t2_1, t2_1, eris_oovv, optimize=True)\n        M_ab -= lib.einsum('mled,nlad,nbem->ab',t2_1_a, t2_1, eris_ovvo, optimize=True)\n        M_ab += lib.einsum('lmde,lnad,nbem->ab',t2_1, t2_1_a, eris_ovvo, optimize=True)\n\n        M_ab -= lib.einsum('mlbd,lnae,nmde->ab',t2_1_a, t2_1_a,   eris_oovv, optimize=True)\n        M_ab += lib.einsum('mlbd,lnae,nedm->ab',t2_1_a, t2_1_a,   eris_ovvo, optimize=True)\n        M_ab += lib.einsum('lmbd,lnae,nmde->ab',t2_1, t2_1, eris_oovv, optimize=True)\n        M_ab -= lib.einsum('lmbd,lnae,nedm->ab',t2_1, t2_1, eris_ovvo, optimize=True)\n        M_ab += lib.einsum('mlbd,lnae,nedm->ab',t2_1_a, t2_1,  eris_ovvo, optimize=True)\n        M_ab -= lib.einsum('lmbd,lnae,nedm->ab',t2_1, t2_1_a,  eris_ovvo, optimize=True)\n        M_ab += lib.einsum('mlbd,nlae,nmde->ab',t2_1, t2_1, eris_oovv, optimize=True)\n\n        M_ab += 0.5*lib.einsum('lned,mled,nmab->ab',t2_1_a, t2_1_a, eris_oovv, optimize=True)\n        M_ab -= 0.5*lib.einsum('lned,mled,nbam->ab',t2_1_a, t2_1_a, eris_ovvo, optimize=True)\n        M_ab -= lib.einsum('nled,mled,nmab->ab',t2_1, t2_1, eris_oovv, optimize=True)\n        M_ab += lib.einsum('nled,mled,nbam->ab',t2_1, t2_1, eris_ovvo, optimize=True)\n        M_ab += 0.5*lib.einsum('lned,mled,nmab->ab',t2_1_a, t2_1_a, eris_oovv, optimize=True)\n        M_ab -= lib.einsum('lned,lmed,nmab->ab',t2_1, t2_1, eris_oovv, optimize=True)\n\n        M_ab -= 0.25*lib.einsum('mlbd,noad,nmol->ab',t2_1_a, t2_1_a, eris_oooo, optimize=True)\n        M_ab += 0.25*lib.einsum('mlbd,noad,nlom->ab',t2_1_a, t2_1_a, eris_oooo, optimize=True)\n        M_ab -= lib.einsum('mlbd,noad,nmol->ab',t2_1, t2_1, eris_oooo, optimize=True)\n\n\n        if isinstance(eris.vvvv, np.ndarray):\n            t2_1_a_r = t2_1_a.reshape(nocc*nocc,nvir*nvir)\n            t2_1_r = t2_1.reshape(nocc*nocc,nvir*nvir)\n            eris_vvvv = eris.vvvv\n            temp_t2a = np.dot(t2_1_a_r,eris_vvvv)\n            temp_t2 = np.dot(t2_1_r,eris_vvvv)\n            temp_t2a = temp_t2a.reshape(nocc,nocc,nvir,nvir)\n            temp_t2 = temp_t2.reshape(nocc,nocc,nvir,nvir)\n            M_ab -= 0.25*lib.einsum('mlaf,mlbf->ab',t2_1_a, temp_t2a, optimize=True)\n            M_ab += 0.25*lib.einsum('mlaf,mlfb->ab',t2_1_a, temp_t2a, optimize=True)\n            M_ab -= lib.einsum('mlaf,mlbf->ab',t2_1, temp_t2, optimize=True)\n            temp_vvvv_t2a = np.dot(eris_vvvv,t2_1_a_r.T)\n            temp_vvvv_t2a = temp_vvvv_t2a.reshape(nvir,nvir,nocc,nocc)\n            M_ab += 0.25*lib.einsum('adlm,mlbd->ab',temp_vvvv_t2a, t2_1_a, optimize=True)\n        else:\n            if isinstance(eris.vvvv, list):\n                temp_t2a_vvvv = contract_ladder(adc,t2_1_a,eris.vvvv)\n                temp_t2_vvvv = contract_ladder(adc,t2_1,eris.vvvv)\n            else :\n                temp_t2a_vvvv = contract_ladder(adc,t2_1_a,eris.Lvv)\n                temp_t2_vvvv = contract_ladder(adc,t2_1,eris.Lvv)\n\n            M_ab -= 0.25*lib.einsum('mlaf,mlbf->ab',t2_1_a, temp_t2a_vvvv, optimize=True)\n            M_ab += 0.25*lib.einsum('mlaf,mlfb->ab',t2_1_a, temp_t2a_vvvv, optimize=True)\n            M_ab -= lib.einsum('mlaf,mlbf->ab',t2_1, temp_t2_vvvv, optimize=True)\n            M_ab += 0.25*lib.einsum('lmad,mlbd->ab',temp_t2a_vvvv, t2_1_a, optimize=True)\n\n\n        if isinstance(eris.vvvv, np.ndarray):\n            t2_1_a_temp = t2_1_a.reshape(nocc*nocc,nvir*nvir)\n            t2_1_temp = t2_1.reshape(nocc*nocc,nvir*nvir)\n            temp_1 = np.dot(t2_1_temp,eris_vvvv.T).reshape(nocc,nocc,nvir,nvir)\n            temp_1_a = np.dot(t2_1_a_temp,eris_vvvv.T).reshape(nocc,nocc,nvir,nvir)\n\n            M_ab -= 0.25*lib.einsum('mlad,mlbd->ab', temp_1_a, t2_1_a, optimize=True)\n            M_ab -= lib.einsum('mlad,mlbd->ab', temp_1, t2_1, optimize=True)\n\n            eris_vvvv = eris_vvvv.reshape(nvir,nvir,nvir,nvir)\n            M_ab -= lib.einsum('mldf,mled,aebf->ab',t2_1_a, t2_1_a, eris_vvvv, optimize=True)\n            M_ab += 0.5*lib.einsum('mldf,mled,aefb->ab',t2_1_a, t2_1_a, eris_vvvv, optimize=True)\n            M_ab += 2.*lib.einsum('mlfd,mled,aebf->ab',t2_1, t2_1, eris_vvvv, optimize=True)\n            M_ab -= lib.einsum('mlfd,mled,aefb->ab',t2_1, t2_1, eris_vvvv, optimize=True)\n            eris_vvvv = eris_vvvv.reshape(nvir*nvir,nvir*nvir)\n        else :\n            if isinstance(eris.vvvv, list):\n                temp_t2_a_vvvv = contract_ladder(adc,t2_1_a,eris.vvvv)\n                temp_t2_vvvv = contract_ladder(adc,t2_1,eris.vvvv)\n            else:\n                temp_t2_a_vvvv = contract_ladder(adc,t2_1_a,eris.Lvv)\n                temp_t2_vvvv = contract_ladder(adc,t2_1,eris.Lvv)\n            M_ab -= 0.25*lib.einsum('mlad,mlbd->ab', temp_t2_a_vvvv, t2_1_a, optimize=True)\n            M_ab -= lib.einsum('mlad,mlbd->ab', temp_t2_vvvv, t2_1, optimize=True)\n\n            chnk_size = radc_ao2mo.calculate_chunk_size(adc)\n            a = 0 \n            temp = np.zeros((nvir,nvir))\n\n            if isinstance(eris.vvvv, list):\n                for dataset in eris.vvvv:\n                    k = dataset.shape[0]\n                    eris_vvvv = dataset[:].reshape(-1,nvir,nvir,nvir)\n                    temp[a:a+k] -= lib.einsum('mldf,mled,aebf->ab',t2_1_a, t2_1_a,  eris_vvvv, optimize=True)\n                    temp[a:a+k] += 0.5*lib.einsum('mldf,mled,aefb->ab',t2_1_a, t2_1_a,  eris_vvvv, optimize=True)\n                    temp[a:a+k] += 2.*lib.einsum('mlfd,mled,aebf->ab',t2_1, t2_1, eris_vvvv, optimize=True)\n                    temp[a:a+k] -= lib.einsum('mlfd,mled,aefb->ab',t2_1, t2_1, eris_vvvv, optimize=True)\n                    del eris_vvvv\n                    a += k\n            else :\n\n                for p in range(0,nvir,chnk_size):\n\n                    vvvv = dfadc.get_vvvv_df(adc, eris.Lvv, p, chnk_size).reshape(-1,nvir,nvir,nvir)\n                    k = vvvv.shape[0]\n                    temp[a:a+k] -= lib.einsum('mldf,mled,aebf->ab',t2_1_a, t2_1_a,  vvvv, optimize=True)\n                    temp[a:a+k] += 0.5*lib.einsum('mldf,mled,aefb->ab',t2_1_a, t2_1_a,  vvvv, optimize=True)\n                    temp[a:a+k] += 2.*lib.einsum('mlfd,mled,aebf->ab',t2_1, t2_1, vvvv, optimize=True)\n                    temp[a:a+k] -= lib.einsum('mlfd,mled,aefb->ab',t2_1, t2_1, vvvv, optimize=True)\n                    del vvvv\n                    a += k\n\n            M_ab += temp\n\n        \n    return M_ab\n\n\ndef get_imds_ip(adc, eris=None):\n\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    t1 = adc.t1\n    t2 = adc.t2\n\n    t1_2 = t1[0]\n    t2_1 = t2[0]\n\n    t2_1_a = t2_1 - t2_1.transpose(1,0,2,3).copy()\n\n    nocc = adc._nocc\n    nvir = adc._nvir\n\n    e_occ = adc.mo_energy[:nocc]\n    e_vir = adc.mo_energy[nocc:]\n\n    idn_occ = np.identity(nocc)\n    idn_vir = np.identity(nvir)\n\n    if eris is None:\n        eris = adc.transform_integrals()\n\n    eris_ovov = eris.ovov\n\n    # i-j block\n    # Zeroth-order terms\n\n    M_ij = lib.einsum('ij,j->ij', idn_occ ,e_occ)\n\n    # Second-order terms\n\n    M_ij +=  lib.einsum('d,ilde,jlde->ij',e_vir,t2_1_a, t2_1_a, optimize=True)\n    M_ij +=  lib.einsum('d,ilde,jlde->ij',e_vir,t2_1, t2_1, optimize=True)\n    M_ij +=  lib.einsum('d,iled,jled->ij',e_vir,t2_1, t2_1, optimize=True)\n\n    M_ij -= 0.5 *  lib.einsum('l,ilde,jlde->ij',e_occ,t2_1_a, t2_1_a, optimize=True)\n    M_ij -= 0.5*lib.einsum('l,ilde,jlde->ij',e_occ,t2_1, t2_1, optimize=True)\n    M_ij -= 0.5*lib.einsum('l,ilde,jlde->ij',e_occ,t2_1, t2_1, optimize=True)\n\n    M_ij -= 0.25 *  lib.einsum('i,ilde,jlde->ij',e_occ,t2_1_a, t2_1_a, optimize=True)\n    M_ij -= 0.25 *  lib.einsum('i,ilde,jlde->ij',e_occ,t2_1, t2_1, optimize=True)\n    M_ij -= 0.25 *  lib.einsum('i,ilde,jlde->ij',e_occ,t2_1, t2_1, optimize=True)\n\n    M_ij -= 0.25 *  lib.einsum('j,ilde,jlde->ij',e_occ,t2_1_a, t2_1_a, optimize=True)\n    M_ij -= 0.25 *  lib.einsum('j,ilde,jlde->ij',e_occ,t2_1, t2_1, optimize=True)\n    M_ij -= 0.25 *  lib.einsum('j,ilde,jlde->ij',e_occ,t2_1, t2_1, optimize=True)\n\n    M_ij += 0.5 *  lib.einsum('ilde,jdle->ij',t2_1_a, eris_ovov,optimize=True)\n    M_ij -= 0.5 *  lib.einsum('ilde,jeld->ij',t2_1_a, eris_ovov,optimize=True)\n    M_ij += lib.einsum('ilde,jdle->ij',t2_1, eris_ovov,optimize=True)\n\n    M_ij += 0.5 *  lib.einsum('jlde,idle->ij',t2_1_a, eris_ovov,optimize=True)\n    M_ij -= 0.5 *  lib.einsum('jlde,ldie->ij',t2_1_a, eris_ovov,optimize=True)\n    M_ij += lib.einsum('jlde,idle->ij',t2_1, eris_ovov,optimize=True)\n\n    # Third-order terms\n\n    if (method == \"adc(3)\"):\n\n        t2_2 = t2[1]\n        t2_2_a = t2_2 - t2_2.transpose(1,0,2,3).copy()\n\n        eris_oovv = eris.oovv\n        eris_ovvo = eris.ovvo\n        eris_ovoo = eris.ovoo\n        eris_oooo = eris.oooo\n\n        M_ij += lib.einsum('ld,ldji->ij',t1_2, eris_ovoo,optimize=True)\n        M_ij -= lib.einsum('ld,jdli->ij',t1_2, eris_ovoo,optimize=True)\n        M_ij += lib.einsum('ld,ldji->ij',t1_2, eris_ovoo,optimize=True)\n\n        M_ij += lib.einsum('ld,ldij->ij',t1_2, eris_ovoo,optimize=True)\n        M_ij -= lib.einsum('ld,idlj->ij',t1_2, eris_ovoo,optimize=True)\n        M_ij += lib.einsum('ld,ldij->ij',t1_2, eris_ovoo,optimize=True)\n\n        M_ij += 0.5* lib.einsum('ilde,jdle->ij',t2_2_a, eris_ovov,optimize=True)\n        M_ij -= 0.5* lib.einsum('ilde,jeld->ij',t2_2_a, eris_ovov,optimize=True)\n        M_ij += lib.einsum('ilde,jdle->ij',t2_2, eris_ovov,optimize=True)\n\n        M_ij += 0.5* lib.einsum('jlde,leid->ij',t2_2_a, eris_ovov,optimize=True)\n        M_ij -= 0.5* lib.einsum('jlde,ield->ij',t2_2_a, eris_ovov,optimize=True)\n        M_ij += lib.einsum('jlde,leid->ij',t2_2, eris_ovov,optimize=True)\n\n        M_ij +=  lib.einsum('d,ilde,jlde->ij',e_vir,t2_1_a, t2_2_a,optimize=True)\n        M_ij +=  lib.einsum('d,ilde,jlde->ij',e_vir,t2_1, t2_2,optimize=True)\n        M_ij +=  lib.einsum('d,iled,jled->ij',e_vir,t2_1, t2_2,optimize=True)\n\n        M_ij +=  lib.einsum('d,jlde,ilde->ij',e_vir,t2_1_a, t2_2_a,optimize=True)\n        M_ij +=  lib.einsum('d,jlde,ilde->ij',e_vir,t2_1, t2_2,optimize=True)\n        M_ij +=  lib.einsum('d,jled,iled->ij',e_vir,t2_1, t2_2,optimize=True)\n\n        M_ij -= 0.5 *  lib.einsum('l,ilde,jlde->ij',e_occ,t2_1_a, t2_2_a,optimize=True)\n        M_ij -= 0.5*lib.einsum('l,ilde,jlde->ij',e_occ,t2_1, t2_2,optimize=True)\n        M_ij -= 0.5*lib.einsum('l,ilde,jlde->ij',e_occ,t2_1, t2_2,optimize=True)\n\n        M_ij -= 0.5 *  lib.einsum('l,jlde,ilde->ij',e_occ,t2_1_a, t2_2_a,optimize=True)\n        M_ij -= 0.5*lib.einsum('l,jlde,ilde->ij',e_occ,t2_1, t2_2,optimize=True)\n        M_ij -= 0.5*lib.einsum('l,jlde,ilde->ij',e_occ,t2_1, t2_2,optimize=True)\n\n        M_ij -= 0.25 *  lib.einsum('i,ilde,jlde->ij',e_occ,t2_1_a, t2_2_a,optimize=True)\n        M_ij -= 0.25 *  lib.einsum('i,ilde,jlde->ij',e_occ,t2_1, t2_2,optimize=True)\n        M_ij -= 0.25 *  lib.einsum('i,ilde,jlde->ij',e_occ,t2_1, t2_2,optimize=True)\n\n        M_ij -= 0.25 *  lib.einsum('i,jlde,ilde->ij',e_occ,t2_1_a, t2_2_a,optimize=True)\n        M_ij -= 0.25 *  lib.einsum('i,jlde,ilde->ij',e_occ,t2_1, t2_2,optimize=True)\n        M_ij -= 0.25 *  lib.einsum('i,jlde,ilde->ij',e_occ,t2_1, t2_2,optimize=True)\n\n        M_ij -= 0.25 *  lib.einsum('j,jlde,ilde->ij',e_occ,t2_1_a, t2_2_a,optimize=True)\n        M_ij -= 0.25 *  lib.einsum('j,jlde,ilde->ij',e_occ,t2_1, t2_2,optimize=True)\n        M_ij -= 0.25 *  lib.einsum('j,jlde,ilde->ij',e_occ,t2_1, t2_2,optimize=True)\n\n        M_ij -= 0.25 *  lib.einsum('j,ilde,jlde->ij',e_occ,t2_1_a, t2_2_a,optimize=True)\n        M_ij -= 0.25 *  lib.einsum('j,ilde,jlde->ij',e_occ,t2_1, t2_2,optimize=True)\n        M_ij -= 0.25 *  lib.einsum('j,ilde,jlde->ij',e_occ,t2_1, t2_2,optimize=True)\n\n        M_ij -= lib.einsum('lmde,jldf,mefi->ij',t2_1_a, t2_1_a, eris_ovvo,optimize = True)\n        M_ij += lib.einsum('lmde,jldf,mife->ij',t2_1_a, t2_1_a, eris_oovv,optimize = True)\n        M_ij += lib.einsum('mled,jlfd,mefi->ij',t2_1, t2_1, eris_ovvo ,optimize = True)\n        M_ij -= lib.einsum('mled,jlfd,mife->ij',t2_1, t2_1, eris_oovv ,optimize = True)\n        M_ij -= lib.einsum('lmde,jldf,mefi->ij',t2_1, t2_1_a, eris_ovvo,optimize = True)\n        M_ij -= lib.einsum('mlde,jldf,mife->ij',t2_1, t2_1, eris_oovv ,optimize = True)\n        M_ij += lib.einsum('lmde,jlfd,mefi->ij',t2_1_a, t2_1, eris_ovvo ,optimize = True)\n\n        M_ij -= lib.einsum('lmde,ildf,mefj->ij',t2_1_a, t2_1_a, eris_ovvo ,optimize = True)\n        M_ij += lib.einsum('lmde,ildf,mjfe->ij',t2_1_a, t2_1_a, eris_oovv ,optimize = True)\n        M_ij += lib.einsum('mled,ilfd,mefj->ij',t2_1, t2_1, eris_ovvo ,optimize = True)\n        M_ij -= lib.einsum('mled,ilfd,mjfe->ij',t2_1, t2_1, eris_oovv ,optimize = True)\n        M_ij -= lib.einsum('lmde,ildf,mefj->ij',t2_1, t2_1_a, eris_ovvo,optimize = True)\n        M_ij -= lib.einsum('mlde,ildf,mjfe->ij',t2_1, t2_1, eris_oovv ,optimize = True)\n        M_ij += lib.einsum('lmde,ilfd,mefj->ij',t2_1_a, t2_1, eris_ovvo ,optimize = True)\n\n        M_ij += 0.25*lib.einsum('lmde,jnde,limn->ij',t2_1_a, t2_1_a,eris_oooo, optimize = True)\n        M_ij -= 0.25*lib.einsum('lmde,jnde,lnmi->ij',t2_1_a, t2_1_a,eris_oooo, optimize = True)\n        M_ij += lib.einsum('lmde,jnde,limn->ij',t2_1 ,t2_1, eris_oooo, optimize = True)\n\n        if isinstance(eris.vvvv, np.ndarray):\n            eris_vvvv = eris.vvvv\n            t2_1_a_r = t2_1_a.reshape(nocc*nocc,nvir*nvir)\n            t2_1_r = t2_1.reshape(nocc*nocc,nvir*nvir)\n            temp_t2a_vvvv = np.dot(t2_1_a_r,eris_vvvv)\n            temp_t2_vvvv = np.dot(t2_1_r,eris_vvvv)\n            temp_t2a_vvvv = temp_t2a_vvvv.reshape(nocc,nocc,nvir,nvir)\n            temp_t2_vvvv = temp_t2_vvvv.reshape(nocc,nocc,nvir,nvir)\n        elif isinstance(eris.vvvv, list):\n            temp_t2a_vvvv = contract_ladder(adc,t2_1_a,eris.vvvv)\n            temp_t2_vvvv = contract_ladder(adc,t2_1,eris.vvvv)\n        else :\n            temp_t2a_vvvv = contract_ladder(adc,t2_1_a,eris.Lvv)\n            temp_t2_vvvv = contract_ladder(adc,t2_1,eris.Lvv)\n\n        M_ij += 0.25*lib.einsum('ilde,jlde->ij',t2_1_a, temp_t2a_vvvv, optimize = True)\n        M_ij -= 0.25*lib.einsum('ilde,jled->ij',t2_1_a, temp_t2a_vvvv, optimize = True)\n        M_ij +=lib.einsum('ilde,jlde->ij',t2_1, temp_t2_vvvv, optimize = True)\n\n        M_ij += 0.25*lib.einsum('inde,lmde,jlnm->ij',t2_1_a, t2_1_a, eris_oooo, optimize = True)\n        M_ij -= 0.25*lib.einsum('inde,lmde,jmnl->ij',t2_1_a, t2_1_a, eris_oooo, optimize = True)\n        M_ij +=lib.einsum('inde,lmde,jlnm->ij',t2_1, t2_1, eris_oooo, optimize = True)\n\n        M_ij += 0.5*lib.einsum('lmdf,lmde,jief->ij',t2_1_a, t2_1_a, eris_oovv, optimize = True)\n        M_ij -= 0.5*lib.einsum('lmdf,lmde,jfei->ij',t2_1_a, t2_1_a, eris_ovvo, optimize = True)\n        M_ij +=lib.einsum('mlfd,mled,jief->ij',t2_1, t2_1, eris_oovv , optimize = True)\n        M_ij -=lib.einsum('mlfd,mled,jfei->ij',t2_1, t2_1, eris_ovvo , optimize = True)\n        M_ij +=lib.einsum('lmdf,lmde,jief->ij',t2_1, t2_1, eris_oovv , optimize = True)\n        M_ij +=0.5*lib.einsum('lmdf,lmde,jief->ij',t2_1_a, t2_1_a, eris_oovv , optimize = True)\n\n        M_ij -= lib.einsum('ilde,jmdf,lmfe->ij',t2_1_a, t2_1_a, eris_oovv, optimize = True)\n        M_ij += lib.einsum('ilde,jmdf,lefm->ij',t2_1_a, t2_1_a, eris_ovvo, optimize = True)\n        M_ij += lib.einsum('ilde,jmdf,lefm->ij',t2_1_a, t2_1, eris_ovvo, optimize = True)\n        M_ij += lib.einsum('ilde,jmdf,lefm->ij',t2_1, t2_1_a, eris_ovvo, optimize = True)\n        M_ij -= lib.einsum('ilde,jmdf,lmfe->ij',t2_1, t2_1, eris_oovv, optimize = True)\n        M_ij += lib.einsum('ilde,jmdf,lefm->ij',t2_1, t2_1, eris_ovvo, optimize = True)\n        M_ij -= lib.einsum('iled,jmfd,lmfe->ij',t2_1, t2_1, eris_oovv, optimize = True)\n\n        M_ij -= 0.5*lib.einsum('lnde,lmde,jinm->ij',t2_1_a, t2_1_a, eris_oooo, optimize = True)\n        M_ij += 0.5*lib.einsum('lnde,lmde,jmni->ij',t2_1_a, t2_1_a, eris_oooo, optimize = True)\n        M_ij -= lib.einsum('nled,mled,jinm->ij',t2_1, t2_1, eris_oooo, optimize = True)\n        M_ij += lib.einsum('nled,mled,jmni->ij',t2_1, t2_1, eris_oooo, optimize = True)\n        M_ij -= lib.einsum('lnde,lmde,jinm->ij',t2_1, t2_1, eris_oooo, optimize = True)\n        M_ij -= 0.5 * lib.einsum('lnde,lmde,jinm->ij',t2_1_a, t2_1_a, eris_oooo, optimize = True)\n\n    return M_ij\n\n\ndef ea_adc_diag(adc,M_ab=None,eris=None):\n\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    if M_ab is None:\n        M_ab = adc.get_imds()\n\n    nocc = adc._nocc\n    nvir = adc._nvir\n\n    n_singles = nvir\n    n_doubles = nocc * nvir * nvir\n\n    dim = n_singles + n_doubles\n\n    e_occ = adc.mo_energy[:nocc]\n    e_vir = adc.mo_energy[nocc:]\n\n    idn_occ = np.identity(nocc)\n    idn_vir = np.identity(nvir)\n\n    s1 = 0\n    f1 = n_singles\n    s2 = f1\n    f2 = s2 + n_doubles\n\n    d_ab = e_vir[:,None] + e_vir\n    d_i = e_occ[:,None]\n    D_n = -d_i + d_ab.reshape(-1)\n    D_iab = D_n.reshape(-1)\n\n    diag = np.zeros(dim)\n\n    # Compute precond in p1-p1 block\n\n    M_ab_diag = np.diagonal(M_ab)\n\n    diag[s1:f1] = M_ab_diag.copy()\n\n    # Compute precond in 2p1h-2p1h block\n\n    diag[s2:f2] = D_iab\n\n    ###### Additional terms for the preconditioner ####\n\n    if (method == \"adc(2)-x\" or method == \"adc(3)\"):\n\n        if eris is None:\n            eris = adc.transform_integrals()\n\n            if isinstance(eris.vvvv, np.ndarray):\n\n                eris_oovv = eris.oovv\n                eris_ovvo = eris.ovvo\n                eris_vvvv = eris.vvvv\n\n                temp = np.zeros((nocc, eris_vvvv.shape[0]))\n                temp[:] += np.diag(eris_vvvv)\n                diag[s2:f2] += temp.reshape(-1)\n\n                eris_ovov_p = np.ascontiguousarray(eris_oovv[:].transpose(0,2,1,3))\n                eris_ovov_p = eris_ovov_p.reshape(nocc*nvir, nocc*nvir)\n\n                temp = np.zeros((nvir, nocc, nvir))\n                temp[:] += np.diagonal(eris_ovov_p).reshape(nocc, nvir)\n                temp = np.ascontiguousarray(temp.transpose(1,0,2))\n                diag[s2:f2] += -temp.reshape(-1)\n\n                eris_ovov_p = np.ascontiguousarray(eris_oovv[:].transpose(0,2,1,3))\n                eris_ovov_p = eris_ovov_p.reshape(nocc*nvir, nocc*nvir)\n\n                temp = np.zeros((nvir, nocc, nvir))\n                temp[:] += np.diagonal(eris_ovov_p).reshape(nocc, nvir)\n                temp = np.ascontiguousarray(temp.transpose(1,2,0))\n                diag[s2:f2] += -temp.reshape(-1)\n\n    return diag\n\n\ndef ip_adc_diag(adc,M_ij=None,eris=None):\n   \n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    if M_ij is None:\n        M_ij = adc.get_imds()\n\n    nocc = adc._nocc\n    nvir = adc._nvir\n\n    n_singles = nocc\n    n_doubles = nvir * nocc * nocc\n\n    dim = n_singles + n_doubles\n\n    e_occ = adc.mo_energy[:nocc]\n    e_vir = adc.mo_energy[nocc:]\n\n    idn_occ = np.identity(nocc)\n    idn_vir = np.identity(nvir)\n\n    s1 = 0\n    f1 = n_singles\n    s2 = f1\n    f2 = s2 + n_doubles\n\n    d_ij = e_occ[:,None] + e_occ\n    d_a = e_vir[:,None]\n    D_n = -d_a + d_ij.reshape(-1)\n    D_aij = D_n.reshape(-1)\n\n    diag = np.zeros(dim)\n\n    # Compute precond in h1-h1 block\n    M_ij_diag = np.diagonal(M_ij)\n\n    diag[s1:f1] = M_ij_diag.copy()\n\n    # Compute precond in 2p1h-2p1h block\n\n    diag[s2:f2] = D_aij.copy()\n\n    ###### Additional terms for the preconditioner ####\n    if (method == \"adc(2)-x\" or method == \"adc(3)\"):\n\n        if eris is None:\n            eris = adc.transform_integrals()\n\n            if isinstance(eris.vvvv, np.ndarray):\n\n                eris_oooo = eris.oooo\n                eris_oovv = eris.oovv\n                eris_ovvo = eris.ovvo\n\n                eris_oooo_p = np.ascontiguousarray(eris_oooo.transpose(0,2,1,3))\n                eris_oooo_p = eris_oooo_p.reshape(nocc*nocc, nocc*nocc)\n  \n                temp = np.zeros((nvir, eris_oooo_p.shape[0]))\n                temp[:] += np.diag(eris_oooo_p)\n                diag[s2:f2] += -temp.reshape(-1)\n\n                eris_ovov_p = np.ascontiguousarray(eris_oovv.transpose(0,2,1,3)) \n                eris_ovov_p = eris_ovov_p.reshape(nocc*nvir, nocc*nvir)\n\n                temp = np.zeros((nocc, nocc, nvir))\n                temp[:] += np.diagonal(eris_ovov_p).reshape(nocc, nvir)\n                temp = np.ascontiguousarray(temp.transpose(2,1,0))\n                diag[s2:f2] += temp.reshape(-1)\n\n                eris_ovov_p = np.ascontiguousarray(eris_oovv.transpose(0,2,1,3)) \n                eris_ovov_p = eris_ovov_p.reshape(nocc*nvir, nocc*nvir)\n\n                temp = np.zeros((nocc, nocc, nvir))\n                temp[:] += np.diagonal(eris_ovov_p).reshape(nocc, nvir)\n                temp = np.ascontiguousarray(temp.transpose(2,0,1))\n                diag[s2:f2] += temp.reshape(-1)\n\n    diag = -diag\n\n    return diag\n\ndef ea_contract_r_vvvv(myadc,r2,vvvv):\n\n    nocc = myadc._nocc\n    nvir = myadc._nvir\n\n    r2_vvvv = np.zeros((nocc,nvir,nvir))\n    r2 = np.ascontiguousarray(r2.reshape(nocc,-1))\n    chnk_size = radc_ao2mo.calculate_chunk_size(myadc)\n\n    a = 0\n    if isinstance(vvvv, list):\n        for dataset in vvvv:\n             k = dataset.shape[0]\n             dataset = dataset[:].reshape(-1,nvir*nvir)\n             r2_vvvv[:,a:a+k] = np.dot(r2,dataset.T).reshape(nocc,-1,nvir)\n             del (dataset)\n             a += k\n    elif getattr(myadc, 'with_df', None):\n        for p in range(0,nvir,chnk_size):\n            vvvv_p = dfadc.get_vvvv_df(myadc, vvvv, p, chnk_size)\n            k = vvvv_p.shape[0]\n            vvvv_p = vvvv_p.reshape(-1,nvir*nvir)\n            r2_vvvv[:,a:a+k] = np.dot(r2,vvvv_p.T).reshape(nocc,-1,nvir)\n            del (vvvv_p)\n            a += k\n    else :\n        raise Exception(\"Unknown vvvv type\") \n\n    r2_vvvv = r2_vvvv.reshape(-1)\n\n    return r2_vvvv\n\n\ndef ea_adc_matvec(adc, M_ab=None, eris=None):\n\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    t2_1 = adc.t2[0]\n    t1_2 = adc.t1[0]\n\n    nocc = adc._nocc\n    nvir = adc._nvir\n\n    ab_ind = np.tril_indices(nvir, k=-1)\n\n    n_singles = nvir\n    n_doubles = nocc * nvir * nvir\n\n    dim = n_singles + n_doubles\n\n    e_occ = adc.mo_energy[:nocc]\n    e_vir = adc.mo_energy[nocc:]\n\n    idn_occ = np.identity(nocc)\n    idn_vir = np.identity(nvir)\n\n    if eris is None:\n        eris = adc.transform_integrals()\n\n    s1 = 0\n    f1 = n_singles\n    s2 = f1\n    f2 = s2 + n_doubles\n\n    d_ab = e_vir[:,None] + e_vir\n    d_i = e_occ[:,None]\n    D_n = -d_i + d_ab.reshape(-1)\n    D_iab = D_n.reshape(-1)\n\n    if M_ab is None:\n        M_ab = adc.get_imds()\n    \n    #Calculate sigma vector\n    def sigma_(r):\n\n        s = np.zeros((dim))\n\n        r1 = r[s1:f1]\n        r2 = r[s2:f2]\n\n        r2 = r2.reshape(nocc,nvir,nvir)\n\n############ ADC(2) ab block ############################\n\n        s[s1:f1] = lib.einsum('ab,b->a',M_ab,r1)\n\n############# ADC(2) a - ibc and ibc - a coupling blocks #########################\n\n        eris_ovvv = radc_ao2mo.unpack_eri_1(eris.ovvv, nvir)\n\n        s[s1:f1] +=  2. * lib.einsum('icab,ibc->a', eris_ovvv, r2, optimize = True)\n        s[s1:f1] -=  lib.einsum('ibac,ibc->a',   eris_ovvv, r2, optimize = True)\n\n        temp = lib.einsum('icab,a->ibc', eris_ovvv, r1, optimize = True)\n        s[s2:f2] +=  temp.reshape(-1)\n        del eris_ovvv\n\n################ ADC(2) iab - jcd block ############################\n\n        s[s2:f2] +=  D_iab * r2.reshape(-1)\n\n############### ADC(3) iab - jcd block ############################\n\n        if (method == \"adc(2)-x\" or method == \"adc(3)\"):\n\n               r2_a = r2 - r2.transpose(0,2,1).copy()\n               t2_2 = adc.t2[1]\n\n               eris_oovv = eris.oovv\n               eris_ovvo = eris.ovvo\n\n               r2 = r2.reshape(nocc, nvir, nvir)\n\n               if isinstance(eris.vvvv, np.ndarray):\n                   r_bab_t = r2.reshape(nocc,-1)\n                   eris_vvvv = eris.vvvv\n                   s[s2:f2] += np.dot(r_bab_t,eris_vvvv.T).reshape(-1)\n               elif isinstance(eris.vvvv, list):\n                   s[s2:f2] += ea_contract_r_vvvv(adc,r2,eris.vvvv)\n               else :\n                   s[s2:f2] += ea_contract_r_vvvv(adc,r2,eris.Lvv)\n\n               s[s2:f2] -= 0.5*lib.einsum('jzyi,jzx->ixy',eris_ovvo,r2_a,optimize = True).reshape(-1)\n               s[s2:f2] -= 0.5*lib.einsum('jiyz,jxz->ixy',eris_oovv,r2,optimize = True).reshape(-1)\n               s[s2:f2] += 0.5*lib.einsum('jzyi,jxz->ixy',eris_ovvo,r2,optimize = True).reshape(-1)\n               s[s2:f2] -=  0.5*lib.einsum('jixz,jzy->ixy',eris_oovv,r2,optimize = True).reshape(-1)\n               s[s2:f2] -=  0.5*lib.einsum('jixw,jwy->ixy',eris_oovv,r2,optimize = True).reshape(-1)\n               s[s2:f2] -= 0.5*lib.einsum('jiyw,jxw->ixy',eris_oovv,r2,optimize = True).reshape(-1)\n               s[s2:f2] += 0.5*lib.einsum('jwyi,jxw->ixy',eris_ovvo,r2,optimize = True).reshape(-1)\n               s[s2:f2] += 0.5*lib.einsum('jwyi,jxw->ixy',eris_ovvo,r2_a,optimize = True).reshape(-1)\n\n            #print(\"Calculating additional terms for adc(3)\")\n        if (method == \"adc(3)\"):\n\n               eris_ovoo = eris.ovoo\n\n############### ADC(3) a - ibc block and ibc-a coupling blocks ########################\n\n               t2_1_a = t2_1 - t2_1.transpose(1,0,2,3).copy()\n               t2_1_a_t = t2_1_a.reshape(nocc,nocc,-1)\n               r2_a = r2_a.reshape(nocc,-1)\n               temp =  0.25 * lib.einsum('lmp,jp->lmj',t2_1_a_t,r2_a)\n               s[s1:f1] += lib.einsum('lmj,lamj->a',temp, eris_ovoo, optimize=True)\n               s[s1:f1] -= lib.einsum('lmj,malj->a',temp, eris_ovoo, optimize=True)\n\n               temp_1 = -lib.einsum('lmzw,jzw->jlm',t2_1,r2)\n               s[s1:f1] -= lib.einsum('jlm,lamj->a',temp_1, eris_ovoo, optimize=True)\n\n               r2_a = r2_a.reshape(nocc,nvir,nvir)\n               temp_s_a = np.zeros_like(r2)\n               temp_s_a = lib.einsum('jlwd,jzw->lzd',t2_1_a,r2_a,optimize=True)\n               temp_s_a += lib.einsum('ljdw,jzw->lzd',t2_1,r2,optimize=True)\n\n               temp_s_a_1 = np.zeros_like(r2)\n               temp_s_a_1 = -lib.einsum('jlzd,jwz->lwd',t2_1_a,r2_a,optimize=True)\n               temp_s_a_1 += -lib.einsum('ljdz,jwz->lwd',t2_1,r2,optimize=True)\n\n               eris_ovvv = radc_ao2mo.unpack_eri_1(eris.ovvv, nvir)\n\n               temp_1_1 = lib.einsum('ldxb,b->lxd', eris_ovvv,r1,optimize=True)\n               temp_1_1 -= lib.einsum('lbxd,b->lxd', eris_ovvv,r1,optimize=True)\n               temp_2_1 = lib.einsum('ldxb,b->lxd', eris_ovvv,r1,optimize=True)\n\n               s[s1:f1] += 0.5*lib.einsum('lzd,ldza->a',temp_s_a,eris_ovvv,optimize=True)\n               s[s1:f1] -= 0.5*lib.einsum('lzd,lazd->a',temp_s_a,eris_ovvv,optimize=True)\n               s[s1:f1] -= 0.5*lib.einsum('lwd,ldwa->a',temp_s_a_1,eris_ovvv,optimize=True)\n               s[s1:f1] += 0.5*lib.einsum('lwd,lawd->a',temp_s_a_1,eris_ovvv,optimize=True)\n\n               temp_1 = np.zeros_like(r2)\n               temp_1 = lib.einsum('jlwd,jzw->lzd',t2_1,r2_a,optimize=True)\n               temp_1 += lib.einsum('jlwd,jzw->lzd',t2_1_a,r2,optimize=True)\n               s[s1:f1] += 0.5*lib.einsum('lzd,ldza->a',temp_1,eris_ovvv,optimize=True)\n\n               temp_1 = np.zeros_like(r2)\n               temp_1 = -lib.einsum('jlzd,jwz->lwd',t2_1,r2_a,optimize=True)\n               temp_1 += -lib.einsum('jlzd,jwz->lwd',t2_1_a,r2,optimize=True)\n               s[s1:f1] -= 0.5*lib.einsum('lwd,ldwa->a',temp_1,eris_ovvv,optimize=True)\n\n               temp_2 = -lib.einsum('ljzd,jzw->lwd',t2_1,r2,optimize=True)\n               s[s1:f1] += 0.5*lib.einsum('lwd,lawd->a',temp_2,eris_ovvv,optimize=True)\n\n               temp_a = t2_1.transpose(0,3,1,2).copy()\n               temp_b = temp_a.reshape(nocc*nvir,nocc*nvir)\n               r2_t = r2.reshape(nocc*nvir,-1)\n               temp_c = np.dot(temp_b,r2_t).reshape(nocc,nvir,nvir)\n               temp_2 = temp_c.transpose(0,2,1).copy()\n               s[s1:f1] -= 0.5*lib.einsum('lzd,lazd->a',temp_2,eris_ovvv,optimize=True)\n\n               temp  = -lib.einsum('lbyd,b->lyd',eris_ovvv,r1,optimize=True)\n               temp_1= -lib.einsum('lyd,lixd->ixy',temp,t2_1,optimize=True)\n               s[s2:f2] -= temp_1.reshape(-1)\n               del eris_ovvv\n\n               temp_1 = lib.einsum('b,lbmi->lmi',r1,eris_ovoo)\n               s[s2:f2] += lib.einsum('lmi,lmxy->ixy',temp_1, t2_1, optimize=True).reshape(-1)\n\n               temp  = lib.einsum('lxd,lidy->ixy',temp_1_1,t2_1,optimize=True)\n               temp  += lib.einsum('lxd,ilyd->ixy',temp_2_1,t2_1_a,optimize=True)\n               s[s2:f2] += temp.reshape(-1)\n\n        return s\n\n    return sigma_\n\n\ndef ip_adc_matvec(adc, M_ij=None, eris=None):\n\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    t2_1 = adc.t2[0]\n    t1_2 = adc.t1[0]\n\n    nocc = adc._nocc\n    nvir = adc._nvir\n\n    ij_ind = np.tril_indices(nocc, k=-1)\n\n    n_singles = nocc\n    n_doubles = nvir * nocc * nocc\n\n    dim = n_singles + n_doubles\n\n    e_occ = adc.mo_energy[:nocc]\n    e_vir = adc.mo_energy[nocc:]\n\n    idn_occ = np.identity(nocc)\n    idn_vir = np.identity(nvir)\n\n    if eris is None:\n        eris = adc.transform_integrals()\n\n    s1 = 0\n    f1 = n_singles\n    s2 = f1\n    f2 = s2 + n_doubles\n\n    d_ij = e_occ[:,None] + e_occ\n    d_a = e_vir[:,None]\n    D_n = -d_a + d_ij.reshape(-1)\n    D_aij = D_n.reshape(-1)\n\n    if M_ij is None:\n        M_ij = adc.get_imds()\n\n    #Calculate sigma vector\n    def sigma_(r):\n\n        s = np.zeros((dim))\n\n        r1 = r[s1:f1]\n        r2 = r[s2:f2]\n\n        r2 = r2.reshape(nvir,nocc,nocc)\n\n        eris_ovoo = eris.ovoo\n\n############ ADC(2) ij block ############################\n\n        s[s1:f1] = lib.einsum('ij,j->i',M_ij,r1)\n\n############ ADC(2) i - kja block #########################\n\n        s[s1:f1] += 2. * lib.einsum('jaki,ajk->i', eris_ovoo, r2, optimize = True)\n        s[s1:f1] -= lib.einsum('kaji,ajk->i', eris_ovoo, r2, optimize = True)\n\n############## ADC(2) ajk - i block ############################\n\n        temp = lib.einsum('jaki,i->ajk', eris_ovoo, r1, optimize = True).reshape(-1)\n        s[s2:f2] += temp.reshape(-1)\n\n################ ADC(2) ajk - bil block ############################\n\n        s[s2:f2] += D_aij * r2.reshape(-1)\n\n############### ADC(3) ajk - bil block ############################\n\n        if (method == \"adc(2)-x\" or method == \"adc(3)\"):\n        \n               r2_a = r2 - r2.transpose(0,2,1).copy()\n               t2_2 = adc.t2[1]\n\n               eris_oooo = eris.oooo\n               eris_oovv = eris.oovv\n               eris_ovvo = eris.ovvo\n               \n               s[s2:f2] -= 0.5*lib.einsum('kijl,ali->ajk',eris_oooo, r2, optimize = True).reshape(-1)\n               s[s2:f2] -= 0.5*lib.einsum('klji,ail->ajk',eris_oooo ,r2, optimize = True).reshape(-1)\n               \n               s[s2:f2] += 0.5*lib.einsum('klba,bjl->ajk',eris_oovv,r2,optimize = True).reshape(-1)\n               \n               s[s2:f2] +=  0.5*lib.einsum('jabl,bkl->ajk',eris_ovvo,r2_a,optimize = True).reshape(-1)\n               s[s2:f2] +=  0.5*lib.einsum('jlba,blk->ajk',eris_oovv,r2,optimize = True).reshape(-1)\n               s[s2:f2] -=  0.5*lib.einsum('jabl,blk->ajk',eris_ovvo,r2,optimize = True).reshape(-1)\n               \n               s[s2:f2] += 0.5*lib.einsum('kiba,bji->ajk',eris_oovv,r2,optimize = True).reshape(-1)\n               \n               s[s2:f2] += 0.5*lib.einsum('jiba,bik->ajk',eris_oovv,r2,optimize = True).reshape(-1)\n               s[s2:f2] -= 0.5*lib.einsum('jabi,bik->ajk',eris_ovvo,r2,optimize = True).reshape(-1)\n               s[s2:f2] -= 0.5*lib.einsum('jabi,bik->ajk',eris_ovvo,r2_a,optimize = True).reshape(-1)\n               \n        if (method == \"adc(3)\"):\n\n               eris_ovoo = eris.ovoo\n\n################ ADC(3) i - kja block and ajk - i ############################\n\n               eris_ovvv = radc_ao2mo.unpack_eri_1(eris.ovvv, nvir)\n               t2_1_a = t2_1 - t2_1.transpose(1,0,2,3).copy()\n               r2_a = r2_a.reshape(nvir,-1)\n               t2_1_a_t = t2_1_a.reshape(-1,nvir,nvir)\n               temp = 0.25 * lib.einsum('pbc,ap->abc',t2_1_a_t,r2_a, optimize=True)\n               s[s1:f1] += lib.einsum('abc,icab->i',temp, eris_ovvv, optimize=True)\n               s[s1:f1] -= lib.einsum('abc,ibac->i',temp, eris_ovvv, optimize=True)\n               temp_1 = lib.einsum('kjcb,ajk->abc',t2_1,r2, optimize=True)\n               s[s1:f1] += lib.einsum('abc,icab->i',temp_1, eris_ovvv, optimize=True)\n\n               temp_1 = lib.einsum('i,icab->cba',r1,eris_ovvv,optimize=True)\n               s[s2:f2] += lib.einsum('cba,kjcb->ajk',temp_1, t2_1, optimize=True).reshape(-1)\n               del eris_ovvv\n\n               r2_a = r2_a.reshape(nvir,nocc,nocc)\n\n               temp = np.zeros_like(r2)\n               temp = lib.einsum('jlab,ajk->blk',t2_1_a,r2_a,optimize=True)\n               temp += lib.einsum('ljba,ajk->blk',t2_1,r2,optimize=True)\n\n               temp_1 = np.zeros_like(r2)\n               temp_1 = lib.einsum('jlab,ajk->blk',t2_1,r2_a,optimize=True)\n               temp_1 += lib.einsum('jlab,ajk->blk',t2_1_a,r2,optimize=True)\n\n               temp_2 = lib.einsum('jlba,akj->blk',t2_1,r2, optimize=True)\n\n               s[s1:f1] += 0.5*lib.einsum('blk,lbik->i',temp,eris_ovoo,optimize=True)\n               s[s1:f1] -= 0.5*lib.einsum('blk,iblk->i',temp,eris_ovoo,optimize=True)\n               s[s1:f1] += 0.5*lib.einsum('blk,lbik->i',temp_1,eris_ovoo,optimize=True)\n               s[s1:f1] -= 0.5*lib.einsum('blk,iblk->i',temp_2,eris_ovoo,optimize=True)\n\n               temp = np.zeros_like(r2)\n               temp = -lib.einsum('klab,akj->blj',t2_1_a,r2_a,optimize=True)\n               temp -= lib.einsum('lkba,akj->blj',t2_1,r2,optimize=True)\n\n               temp_1 = np.zeros_like(r2)\n               temp_1 = -lib.einsum('klab,akj->blj',t2_1,r2_a,optimize=True)\n               temp_1 -= lib.einsum('klab,akj->blj',t2_1_a,r2,optimize=True)\n\n               temp_2 = -lib.einsum('klba,ajk->blj',t2_1,r2,optimize=True)\n\n               s[s1:f1] -= 0.5*lib.einsum('blj,lbij->i',temp,eris_ovoo,optimize=True)\n               s[s1:f1] += 0.5*lib.einsum('blj,iblj->i',temp,eris_ovoo,optimize=True)\n               s[s1:f1] -= 0.5*lib.einsum('blj,lbij->i',temp_1,eris_ovoo,optimize=True)\n               s[s1:f1] += 0.5*lib.einsum('blj,iblj->i',temp_2,eris_ovoo,optimize=True)\n\n               temp_1  = lib.einsum('i,lbik->kbl',r1,eris_ovoo)\n               temp_1  -= lib.einsum('i,iblk->kbl',r1,eris_ovoo)\n               temp_2  = lib.einsum('i,lbik->kbl',r1,eris_ovoo)\n\n               temp  = lib.einsum('kbl,ljba->ajk',temp_1,t2_1,optimize=True)\n               temp += lib.einsum('kbl,jlab->ajk',temp_2,t2_1_a,optimize=True)\n               s[s2:f2] += temp.reshape(-1)\n\n               temp  = -lib.einsum('i,iblj->jbl',r1,eris_ovoo,optimize=True)\n               temp_1 = -lib.einsum('jbl,klba->ajk',temp,t2_1,optimize=True)\n               s[s2:f2] -= temp_1.reshape(-1)\n\n        s *= -1.0\n\n        return s\n\n    return sigma_\n\n\ndef ea_compute_trans_moments(adc, orb):\n\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    t2_1 = adc.t2[0]\n    t1_2 = adc.t1[0]\n    t2_1_a = t2_1 - t2_1.transpose(1,0,2,3).copy()\n\n    nocc = adc._nocc\n    nvir = adc._nvir\n\n    n_singles = nvir\n    n_doubles = nocc * nvir * nvir\n\n    dim = n_singles + n_doubles\n\n    e_occ = adc.mo_energy[:nocc]\n    e_vir = adc.mo_energy[nocc:]\n\n    idn_occ = np.identity(nocc)\n    idn_vir = np.identity(nvir)\n\n    s1 = 0\n    f1 = n_singles\n    s2 = f1\n    f2 = s2 + n_doubles\n\n    T = np.zeros((dim))\n\n######## ADC(2) part  ############################################\n\n    if orb < nocc:\n\n        T[s1:f1] = -t1_2[orb,:]\n\n        t2_1_t = -t2_1.transpose(1,0,2,3).copy()\n\n        T[s2:f2] += t2_1_t[:,orb,:,:].reshape(-1)\n\n    else :\n\n        T[s1:f1] += idn_vir[(orb-nocc), :]\n        T[s1:f1] -= 0.25*lib.einsum('klc,klac->a',t2_1_a[:,:,(orb-nocc),:], t2_1_a, optimize = True)\n        T[s1:f1] -= 0.25*lib.einsum('klc,klac->a',t2_1[:,:,(orb-nocc),:], t2_1, optimize = True)\n        T[s1:f1] -= 0.25*lib.einsum('lkc,lkac->a',t2_1[:,:,(orb-nocc),:], t2_1, optimize = True)\n\n######## ADC(3) 2p-1h  part  ############################################\n\n    if(method==\"adc(2)-x\"or adc.method==\"adc(3)\"):\n\n        t2_2 = adc.t2[1]\n        t2_2_a = t2_2 - t2_2.transpose(1,0,2,3).copy()\n\n        if orb < nocc:\n\n            t2_2_t = -t2_2.transpose(1,0,2,3).copy()\n\n            T[s2:f2] += t2_2_t[:,orb,:,:].reshape(-1)\n\n########## ADC(3) 1p part  ############################################\n\n    if(adc.method==\"adc(3)\"):\n\n        t1_3 = adc.t1[1]\n\n        if orb < nocc:\n\n            T[s1:f1] += 0.5*lib.einsum('kac,ck->a',t2_1_a[:,orb,:,:], t1_2.T,optimize = True)\n            T[s1:f1] -= 0.5*lib.einsum('kac,ck->a',t2_1[orb,:,:,:], t1_2.T,optimize = True)\n\n            T[s1:f1] -= t1_3[orb,:]\n\n        else:\n\n            T[s1:f1] -= 0.25*lib.einsum('klc,klac->a',t2_1_a[:,:,(orb-nocc),:], t2_2_a, optimize = True)\n            T[s1:f1] -= 0.25*lib.einsum('klc,klac->a',t2_1[:,:,(orb-nocc),:], t2_2, optimize = True)\n            T[s1:f1] -= 0.25*lib.einsum('lkc,lkac->a',t2_1[:,:,(orb-nocc),:], t2_2, optimize = True)\n\n            T[s1:f1] -= 0.25*lib.einsum('klac,klc->a',t2_1_a, t2_2_a[:,:,(orb-nocc),:],optimize = True)\n            T[s1:f1] -= 0.25*lib.einsum('klac,klc->a',t2_1, t2_2[:,:,(orb-nocc),:],optimize = True)\n            T[s1:f1] -= 0.25*lib.einsum('lkac,lkc->a',t2_1, t2_2[:,:,(orb-nocc),:],optimize = True)\n\n    T_aaa = T[n_singles:].reshape(nocc,nvir,nvir).copy()\n    T_aaa = T_aaa - T_aaa.transpose(0,2,1)\n    T[n_singles:] += T_aaa.reshape(-1)\n\n    return T\n\n\ndef ip_compute_trans_moments(adc, orb):\n\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    t2_1 = adc.t2[0]\n    t1_2 = adc.t1[0]\n    t2_1_a = t2_1 - t2_1.transpose(1,0,2,3).copy()\n\n    nocc = adc._nocc\n    nvir = adc._nvir\n\n    n_singles = nocc\n    n_doubles = nvir * nocc * nocc\n\n    dim = n_singles + n_doubles\n\n    e_occ = adc.mo_energy[:nocc]\n    e_vir = adc.mo_energy[nocc:]\n\n    idn_occ = np.identity(nocc)\n    idn_vir = np.identity(nvir)\n\n    s1 = 0\n    f1 = n_singles\n    s2 = f1\n    f2 = s2 + n_doubles\n\n    T = np.zeros((dim))\n\n######## ADC(2) 1h part  ############################################\n\n    if orb < nocc:\n        T[s1:f1]  = idn_occ[orb, :]\n        T[s1:f1] += 0.25*lib.einsum('kdc,ikdc->i',t2_1_a[:,orb,:,:], t2_1_a, optimize = True)\n        T[s1:f1] -= 0.25*lib.einsum('kdc,ikdc->i',t2_1[orb,:,:,:], t2_1, optimize = True)\n        T[s1:f1] -= 0.25*lib.einsum('kcd,ikcd->i',t2_1[orb,:,:,:], t2_1, optimize = True)\n    else :\n        T[s1:f1] += t1_2[:,(orb-nocc)]\n\n######## ADC(2) 2h-1p  part  ############################################\n\n        t2_1_t = t2_1.transpose(2,3,1,0).copy()\n\n        T[s2:f2] = t2_1_t[(orb-nocc),:,:,:].reshape(-1)\n\n######## ADC(3) 2h-1p  part  ############################################\n\n    if(method=='adc(2)-x'or method=='adc(3)'):\n\n        t2_2 = adc.t2[1]\n        t2_2_a = t2_2 - t2_2.transpose(1,0,2,3).copy()\n\n        if orb >= nocc:\n            t2_2_t = t2_2.transpose(2,3,1,0).copy()\n\n            T[s2:f2] += t2_2_t[(orb-nocc),:,:,:].reshape(-1)\n\n######## ADC(3) 1h part  ############################################\n\n    if(method=='adc(3)'):\n\n        t1_3 = adc.t1[1]\n\n        if orb < nocc:\n            T[s1:f1] += 0.25*lib.einsum('kdc,ikdc->i',t2_1_a[:,orb,:,:], t2_2_a, optimize = True)\n            T[s1:f1] -= 0.25*lib.einsum('kdc,ikdc->i',t2_1[orb,:,:,:], t2_2, optimize = True)\n            T[s1:f1] -= 0.25*lib.einsum('kcd,ikcd->i',t2_1[orb,:,:,:], t2_2, optimize = True)\n\n            T[s1:f1] += 0.25*lib.einsum('ikdc,kdc->i',t2_1_a, t2_2_a[:,orb,:,:],optimize = True)\n            T[s1:f1] -= 0.25*lib.einsum('ikcd,kcd->i',t2_1, t2_2[orb,:,:,:],optimize = True)\n            T[s1:f1] -= 0.25*lib.einsum('ikdc,kdc->i',t2_1, t2_2[orb,:,:,:],optimize = True)\n        else:\n            T[s1:f1] += 0.5*lib.einsum('ikc,kc->i',t2_1_a[:,:,(orb-nocc),:], t1_2,optimize = True)\n            T[s1:f1] += 0.5*lib.einsum('ikc,kc->i',t2_1[:,:,(orb-nocc),:], t1_2,optimize = True)\n            T[s1:f1] += t1_3[:,(orb-nocc)]\n\n    T_aaa = T[n_singles:].reshape(nvir,nocc,nocc).copy()\n    T_aaa = T_aaa - T_aaa.transpose(0,2,1)\n    T[n_singles:] += T_aaa.reshape(-1)\n\n    return T\n\n\ndef get_trans_moments(adc):\n\n    nmo  = adc.nmo\n\n    T = []\n\n    for orb in range(nmo):\n\n            T_a = adc.compute_trans_moments(orb)\n            T.append(T_a)\n\n    T = np.array(T)\n    return T\n\n\ndef get_spec_factors_ea(adc, T, U, nroots=1):\n\n    nocc = adc._nocc\n    nvir = adc._nvir\n\n    n_singles = nvir\n    n_doubles = nocc * nvir * nvir\n\n    U = U.reshape(nroots,-1)\n\n    for I in range(U.shape[0]):\n        U1 = U[I, :n_singles]\n        U2 = U[I, n_singles:].reshape(nocc,nvir,nvir)\n        UdotU = np.dot(U1, U1) + 2.*np.dot(U2.ravel(), U2.ravel()) - np.dot(U2.ravel(), U2.transpose(0,2,1).ravel())\n        U[I,:] /= np.sqrt(UdotU)\n\n    X = np.dot(T, U.T).reshape(-1, nroots)\n\n    P = 2.0*lib.einsum(\"pi,pi->i\", X, X)\n\n    return P\n\ndef get_spec_factors_ip(adc, T, U, nroots=1):\n\n    nocc = adc._nocc\n    nvir = adc._nvir\n\n    n_singles = nocc\n    n_doubles = nvir * nocc * nocc\n\n    U = U.reshape(nroots,-1)\n\n    for I in range(U.shape[0]):\n        U1 = U[I, :n_singles]\n        U2 = U[I, n_singles:].reshape(nvir,nocc,nocc)\n        UdotU = np.dot(U1, U1) + 2.*np.dot(U2.ravel(), U2.ravel()) - np.dot(U2.ravel(), U2.transpose(0,2,1).ravel())\n        U[I,:] /= np.sqrt(UdotU)\n\n    X = np.dot(T, U.T).reshape(-1, nroots)\n\n    P = 2.0*lib.einsum(\"pi,pi->i\", X, X)\n\n    return P\n\n\nclass RADCEA(RADC):\n    '''restricted ADC for EA energies and spectroscopic amplitudes\n\n    Attributes:\n        verbose : int\n            Print level.  Default value equals to :class:`Mole.verbose`\n        max_memory : float or int\n            Allowed memory in MB.  Default value equals to :class:`Mole.max_memory`\n        incore_complete : bool\n            Avoid all I/O. Default is False.\n        method : string\n            nth-order ADC method. Options are : ADC(2), ADC(2)-X, ADC(3). Default is ADC(2).\n        conv_tol : float\n            Convergence threshold for Davidson iterations.  Default is 1e-12.\n        max_cycle : int\n            Number of Davidson iterations.  Default is 50.\n        max_space : int\n            Space size to hold trial vectors for Davidson iterative diagonalization.  Default is 12.\n\n    Kwargs:\n\tnroots : int\n\t    Number of roots (eigenvalues) requested. Default value is 1.\n\n            >>> myadc = adc.RADC(mf).run()\n            >>> myadcea = adc.RADC(myadc).run()\n\n    Saved results\n\n        e_ea : float or list of floats\n            EA energy (eigenvalue). For nroots = 1, it is a single float number. If nroots > 1, it is a list of floats for the lowest nroots eigenvalues.\n        v_ip : array\n            Eigenvectors for each EA transition.\n        p_ea : float\n            Spectroscopic amplitudes for each EA transition.\n    '''\n    def __init__(self, adc):\n        self.mol = adc.mol\n        self.verbose = adc.verbose\n        self.stdout = adc.stdout\n        self.max_memory = adc.max_memory\n        self.max_space = adc.max_space\n        self.max_cycle = adc.max_cycle\n        self.conv_tol  = adc.conv_tol\n        self.t1 = adc.t1\n        self.t2 = adc.t2\n        self.e_corr = adc.e_corr\n        self.method = adc.method\n        self.method_type = adc.method_type\n        self._scf = adc._scf\n        self._nocc = adc._nocc\n        self._nvir = adc._nvir\n        self._nmo = adc._nmo\n        self.mo_coeff = adc.mo_coeff\n        self.mo_energy = adc.mo_energy\n        self.nmo = adc._nmo\n        self.transform_integrals = adc.transform_integrals\n        self.with_df = adc.with_df\n\n        keys = set(('conv_tol', 'e_corr', 'method', 'mo_coeff', 'mo_energy', 'max_memory', 't1', 'max_space', 't2', 'max_cycle'))\n\n        self._keys = set(self.__dict__.keys()).union(keys)\n    \n    kernel = kernel\n    get_imds = get_imds_ea\n    matvec = ea_adc_matvec\n    get_diag = ea_adc_diag\n    compute_trans_moments = ea_compute_trans_moments\n    get_trans_moments = get_trans_moments\n    get_spec_factors = get_spec_factors_ea\n    \n    def get_init_guess(self, nroots=1, diag=None, ascending = True):\n       if diag is None :\n           diag = self.ea_adc_diag()\n       idx = None\n       if ascending:\n           idx = np.argsort(diag)\n       else:\n           idx = np.argsort(diag)[::-1]\n       guess = np.zeros((diag.shape[0], nroots))\n       min_shape = min(diag.shape[0], nroots)\n       guess[:min_shape,:min_shape] = np.identity(min_shape)\n       g = np.zeros((diag.shape[0], nroots))\n       g[idx] = guess.copy()\n       guess = []\n       for p in range(g.shape[1]):\n           guess.append(g[:,p])\n       return guess\n    \n\n    def gen_matvec(self, imds=None, eris=None):\n        if imds is None: imds = self.get_imds(eris)\n        diag = self.get_diag(imds, eris)\n        matvec = self.matvec(imds, eris)\n        return matvec, diag\n\n\nclass RADCIP(RADC):\n    '''restricted ADC for IP energies and spectroscopic amplitudes\n\n    Attributes:\n        verbose : int\n            Print level.  Default value equals to :class:`Mole.verbose`\n        max_memory : float or int\n            Allowed memory in MB.  Default value equals to :class:`Mole.max_memory`\n        incore_complete : bool\n            Avoid all I/O. Default is False.\n        method : string\n            nth-order ADC method. Options are : ADC(2), ADC(2)-X, ADC(3). Default is ADC(2).\n        conv_tol : float\n            Convergence threshold for Davidson iterations.  Default is 1e-12.\n        max_cycle : int\n            Number of Davidson iterations.  Default is 50.\n        max_space : int\n            Space size to hold trial vectors for Davidson iterative diagonalization.  Default is 12.\n\n    Kwargs:\n\tnroots : int\n\t    Number of roots (eigenvalues) requested. Default value is 1.\n\n            >>> myadc = adc.RADC(mf).run()\n            >>> myadcip = adc.RADC(myadc).run()\n\n    Saved results\n\n        e_ip : float or list of floats\n            IP energy (eigenvalue). For nroots = 1, it is a single float number. If nroots > 1, it is a list of floats for the lowest nroots eigenvalues.\n        v_ip : array\n            Eigenvectors for each IP transition.\n        p_ip : float\n            Spectroscopic amplitudes for each IP transition.\n    '''\n    def __init__(self, adc):\n        self.mol = adc.mol\n        self.verbose = adc.verbose\n        self.stdout = adc.stdout\n        self.max_memory = adc.max_memory\n        self.max_space = adc.max_space\n        self.max_cycle = adc.max_cycle\n        self.conv_tol  = adc.conv_tol\n        self.t1 = adc.t1\n        self.t2 = adc.t2\n        self.e_corr = adc.e_corr\n        self.method = adc.method\n        self.method_type = adc.method_type\n        self._scf = adc._scf\n        self._nocc = adc._nocc\n        self._nvir = adc._nvir\n        self._nmo = adc._nmo\n        self.mo_coeff = adc.mo_coeff\n        self.mo_energy = adc.mo_energy\n        self.nmo = adc._nmo\n        self.transform_integrals = adc.transform_integrals\n        self.with_df = adc.with_df\n\n        keys = set(('conv_tol', 'e_corr', 'method', 'mo_coeff', 'mo_energy_b', 'max_memory', 't1', 'mo_energy_a', 'max_space', 't2', 'max_cycle'))\n\n        self._keys = set(self.__dict__.keys()).union(keys)\n\n    kernel = kernel\n    get_imds = get_imds_ip\n    get_diag = ip_adc_diag\n    matvec = ip_adc_matvec\n    compute_trans_moments = ip_compute_trans_moments\n    get_trans_moments = get_trans_moments\n    get_spec_factors = get_spec_factors_ip\n\n    def get_init_guess(self, nroots=1, diag=None, ascending = True):\n        if diag is None :\n            diag = self.ip_adc_diag()\n        idx = None\n        if ascending:\n            idx = np.argsort(diag)\n        else:\n            idx = np.argsort(diag)[::-1]\n        guess = np.zeros((diag.shape[0], nroots))\n        min_shape = min(diag.shape[0], nroots)\n        guess[:min_shape,:min_shape] = np.identity(min_shape)\n        g = np.zeros((diag.shape[0], nroots))\n        g[idx] = guess.copy()\n        guess = []\n        for p in range(g.shape[1]):\n            guess.append(g[:,p])\n        return guess\n\n    def gen_matvec(self, imds=None, eris=None):\n        if imds is None: imds = self.get_imds(eris)\n        diag = self.get_diag(imds, eris)\n        matvec = self.matvec(imds, eris)\n        return matvec, diag\n\nif __name__ == '__main__':\n    from pyscf import scf\n    from pyscf import gto\n    from pyscf import adc\n\n    r = 1.098\n    mol = gto.Mole()\n    mol.atom = [\n        ['N', ( 0., 0.    , -r/2   )],\n        ['N', ( 0., 0.    ,  r/2)],]\n    mol.basis = {'N':'aug-cc-pvdz'}\n    mol.verbose = 0\n    mol.build()\n    mf = scf.RHF(mol)\n    mf.conv_tol = 1e-12\n    mf.kernel()\n\n    myadc = adc.ADC(mf)\n    ecorr, t_amp1, t_amp2 = myadc.kernel_gs()\n    print(ecorr -  -0.3220169236051954)\n\n    myadcip = RADCIP(myadc)\n    e,v,p = kernel(myadcip,nroots=3)\n    print(\"ADC(2) IP energies\")\n    print (e[0] - 0.5434389910483670)\n    print (e[1] - 0.6240296243595950)\n    print (e[2] - 0.6240296243595956)\n\n    print(\"ADC(2) IP spectroscopic factors\")\n    print (p[0] - 1.7688097076459075)\n    print (p[1] - 1.8192921131700284)\n    print (p[2] - 1.8192921131700293)\n\n    myadcea = RADCEA(myadc)\n    e,v,p = kernel(myadcea,nroots=3)\n    print(\"ADC(2) EA energies\")\n    print (e[0] - 0.0961781923822576)\n    print (e[1] - 0.1258326916409743)\n    print (e[2] - 0.1380779405750178)\n\n    print(\"ADC(2) EA spectroscopic factors\")\n    print (p[0] - 1.9832854445007961)\n    print (p[1] - 1.9634368668786559)\n    print (p[2] - 1.9783719593912672)\n\n    myadc = adc.ADC(mf)\n    myadc.method = \"adc(3)\"\n    ecorr, t_amp1, t_amp2 = myadc.kernel_gs()\n    print(ecorr - -0.31694173142858517)\n\n    myadcip = RADCIP(myadc)\n    e,v,p = kernel(myadcip,nroots=3)\n    print(\"ADC(3) IP energies\")\n    print (e[0] - 0.5667526829981027)\n    print (e[1] - 0.6099995170092525)\n    print (e[2] - 0.6099995170092529)\n\n    print(\"ADC(3) IP spectroscopic factors\")\n    print (p[0] - 1.8173191958988848)\n    print (p[1] - 1.8429224413853840)\n    print (p[2] - 1.8429224413853851)\n\n    myadcea = RADCEA(myadc)\n    e,v,p = kernel(myadcea,nroots=3)\n\n    print(\"ADC(3) EA energies\")\n    print (e[0] - 0.0936790850738445)\n    print (e[1] - 0.0983654552141278)\n    print (e[2] - 0.1295709313652367)\n\n    print(\"ADC(3) EA spectroscopic factors\")\n    print (p[0] - 1.8324175318668088)\n    print (p[1] - 1.9840991060607487)\n    print (p[2] - 1.9638550014980212)\n\n    myadc.method = \"adc(2)-x\"\n    e,v,p = myadc.kernel(nroots=4)\n    print(\"ADC(2)-x IP energies\")\n    print (e[0] - 0.5405255360673724)\n    print (e[1] - 0.6208026698756577)\n    print (e[2] - 0.6208026698756582)\n    print (e[3] - 0.6465332771967947)\n\n    myadc.method_type = \"ea\"\n    e,v,p = myadc.kernel(nroots=4)\n    print(\"ADC(2)-x EA energies\")\n    print (e[0] - 0.0953065329985665)\n    print (e[1] - 0.1238833070823509)\n    print (e[2] - 0.1365693811939308)\n    print (e[3] - 0.1365693811939316)\n", "meta": {"hexsha": "19e608428c881988a3a2270816776615aa1ee3b9", "size": 83564, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/adc/radc.py", "max_stars_repo_name": "mtreinish/pyscf", "max_stars_repo_head_hexsha": "b3c86bc145c180230cb6aba81e9c47b5764aeec4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-24T13:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T13:35:42.000Z", "max_issues_repo_path": "pyscf/adc/radc.py", "max_issues_repo_name": "holy0213/pyscf", "max_issues_repo_head_hexsha": "aff8a94003cc47ff5e741ce648d877b008a0c59e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscf/adc/radc.py", "max_forks_repo_name": "holy0213/pyscf", "max_forks_repo_head_hexsha": "aff8a94003cc47ff5e741ce648d877b008a0c59e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-30T14:38:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-30T14:38:46.000Z", "avg_line_length": 38.8489074849, "max_line_length": 209, "alphanum_fraction": 0.5904815471, "include": true, "reason": "import numpy", "num_tokens": 30942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.1946313496028689}}
{"text": "#!/usr/bin/env python\n\n\"\"\"\nThe alignment module contains functions used in aligning two channel\ndata with fluorescent dyes. See our `walkthrough\n<https://github.com/ReddingLab/Learning/blob\n/master/image-analysis-basics/Image-alignment-with-toolbox.ipynb/>`_\nof the alignment module's usage.\n\"\"\"\n\n__all__ = ['im_split', 'get_offset_distribution',\n           'plot_assigned_maxima', 'inspect_global_fit',\n           'inspect_individual_fits', 'align_by_offset',\n           'overlay']\n\n__version__ = '0.3.0'\n\n__author__ = 'Sy Redding and Liv Jensen'\n\n\n\n\n\nimport numpy as np\nimport random as ra\nimport matplotlib.pyplot as plt\nfrom smtools.misc import skewnormal\nfrom smtools.point_fitting import find_maxima, fit_routine\nfrom scipy.spatial import cKDTree\nfrom scipy.ndimage import map_coordinates\nfrom scipy.optimize import curve_fit\nfrom skimage.transform import warp_coords, rotate\n\n\n########################################################################\ndef im_split(Image, splitstyle=\"hsplit\"):\n    return getattr(np, splitstyle)(Image, 2)[0], \\\n           getattr(np, splitstyle)(Image, 2)[1]\n\n\ndef clean_duplicate_maxima(dist, indexes):\n    paired_indexes = []\n    count = -1\n    for i in set(indexes):\n        tmp_dist = np.inf\n        tmp = None\n        for j, k in zip(indexes, dist):\n            if i == j:\n                count += 1\n                if k < tmp_dist:\n                    tmp = [j, count]\n                    tmp_dist = k\n            else:\n                pass\n        if tmp is not None:\n            paired_indexes.append(tmp)\n    return paired_indexes\n\n\n\ndef make_bins(data, width):\n    return np.arange(min(data), max(data) + width, width)\n\ndef find_global_offset(im_stack, bbox=9, splitstyle=\"hsplit\",\n                       fsize=10, binwidth=.1):\n\n    pooled_x, pooled_y = [], []\n    for im in im_stack:\n        xdist, ydist = get_offset_distribution(im, bbox, splitstyle,\n                                               fsize)\n        pooled_x += xdist\n        pooled_y += ydist\n\n    p0 = [bincens[np.argmax(vals[0])],.2, 1, max(vals[0]), 0]\n    bins = make_bins(pooled_x, binwidth)\n    vals = np.histogram(pooled_x, bins)\n    bincens = [bins[j] + (binwidth / 2.) for j in range(len(bins) - 1)]\n    popt_x, pcov_x = curve_fit(skewnormal, np.array(bincens),\n                               np.array(vals[0]),p0)\n\n    bins = make_bins(pooled_y, binwidth)\n    vals = np.histogram(pooled_y, bins)\n    bincens = [bins[j] + (binwidth / 2.) for j in range(len(bins) - 1)]\n    p0 = [bincens[np.argmax(vals[0])],.2, 1, max(vals[0]), 0]\n    popt_y, pcov_y = curve_fit(skewnormal, np.array(bincens),\n                               np.array(vals[0]),p0)\n\n    return popt_x[0], popt_y[0]\n\n\n########################################################################\n\n\ndef get_offset_distribution(Image, bbox=9, splitstyle=\"hsplit\",\n                            fsize=10):\n    \"\"\"\n    This function in order:\n        * splits the image into channels\n        * locates and fits all of the points in each channel\n        * pairs up associated points from each channel, uses cDKTree\n        * and determines their offset\n\n    :param Image: 2D image array\n    :param bbox: int, passed to ``point_fitting.fit_routine``,\n        size of ROI around each point to apply gaussian fit. Default\n        is 9.\n    :param splitstyle: string, passed to ``im_split``; accepts\n        \"hsplit\", \"vsplit\". Default is \"hsplit\"\n    :param fsize: int, passed to ``point_fitting.find_maxima``,\n        size of average filters used in maxima determination. Default\n        is 10.\n\n    :return: Two lists containing all of the measured x- and y- offsets\n\n    :Example:\n\n        >>> from smtools.alignment import get_offset_distribution\n        >>> import smtools.testdata as test\n        >>> import matplotlib.pyplot as plt\n        >>> import numpy as np\n        >>> im = test.image_stack()[0]\n        >>> x_dist, y_dist = get_offset_distribution(im)\n        >>> print(np.mean(x_dist), np.mean(y_dist))\n        -1.9008888233326608 -2.042675546813981\n    \"\"\"\n    ch1, ch2 = im_split(Image, splitstyle)\n    ch1_maxima = find_maxima(ch1, fsize)\n    ch2_maxima = find_maxima(ch2, fsize)\n    Delta_x, Delta_y = [], []\n    mytree = cKDTree(ch1_maxima)\n    dist, indexes = mytree.query(ch2_maxima)\n    for i, j in clean_duplicate_maxima(dist, indexes):\n        fit_ch1 = fit_routine(ch1, [ch1_maxima[i]], bbox)\n        fit_ch2 = fit_routine(ch2, [ch2_maxima[j]], bbox)\n        try:\n            x1, y1 = fit_ch1[0]\n            x2, y2 = fit_ch2[0]\n            Delta_x.append(x1 - x2)\n            Delta_y.append(y1 - y2)\n\n        except TypeError:\n            pass\n    return (Delta_x, Delta_y)\n\n\n\n\ndef plot_assigned_maxima(Image, splitstyle=\"hsplit\", fsize=10):\n    \"\"\"\n    This function spits out a matplotlib plot with lines drawn\n    between each of the assigned pairs of maxima.\n    The purpose of this function is more for a sanity check than\n    anything useful.\n\n    :param Image: 2D image array\n    :param splitstyle: string, passed to ``im_split``; accepts\n        \"hsplit\", \"vsplit\". Default is \"hsplit\"\n    :param fsize: int, passed to ``point_fitting.find_maxima``,\n        size of average filters used in maxima determination. Default\n        is 10.\n\n    :return: fancy plot of assigned points.\n\n    :Example:\n\n        >>> from smtools.alignment import plot_assigned_maxima\n        >>> import smtools.testdata as test\n        >>> im = test.image_stack()[0]\n        >>> plot_assigned_maxima(im)\n    \"\"\"\n    ch1, ch2 = im_split(Image, splitstyle)\n    ch1_maxima = find_maxima(ch1, fsize)\n    ch2_maxima = find_maxima(ch2, fsize)\n    width = ch2.shape[1]\n    plt.figure(figsize=(Image.shape[0] / 64, Image.shape[1] / 64))\n    plt.axis('off')\n    plt.imshow(Image, cmap=\"binary_r\")\n    plt.title(\"Assigned matching points\")\n\n    mytree = cKDTree(ch1_maxima)\n    dist, indexes = mytree.query(ch2_maxima)\n    for i, j in clean_duplicate_maxima(dist, indexes):\n        x1, y1 = ch1_maxima[i]\n        x2, y2 = ch2_maxima[j]\n        tmp_color = (\n        ra.uniform(0, 1), ra.uniform(0, 1), ra.uniform(0, 1))\n        plt.plot(x1, y1, color=tmp_color, marker='+')\n        plt.plot(x2 + width, y2, color=tmp_color, marker='+')\n        plt.plot([x1, x2 + width], [y1, y2], color=tmp_color)\n    plt.show()\n\n\n\n\n\ndef inspect_global_fit(im_stack, bbox=9, fsize=10,\n                       binwidth=.1, init_params = None,\n                       splitstyle=\"hsplit\",showplot=True):\n\n    \"\"\"\n    Basic alignment function. Accepts a 1D list of image arrays,\n    then splits the images, locates corresponding maxima in each\n    channel and then calculates the best shift in x and y to align\n    each maxima pair. If showplot is set to True, this function also\n    produces a pair of histograms of all the measured offsets and\n    resulting fits to those data.\n\n\n    :param im_stack: 1D list of image arrays to be used in\n        determination of the offset\n    :param bbox: int, passed to ``point_fitting.fit_routine``,\n        size of ROI around each point to apply gaussian fit. Default\n        is 9.\n    :param fsize: int, passed to ``point_fitting.find_maxima``,\n        size of average filters used in maxima determination. Default\n        is 10.\n    :param binwidth: float, passed to ``make_bins``; resolution of\n        histogram for fitting\n    :param init_params: 1D array, initial conditions passed to\n        scipy.optimize.curve_fit. must be length 5,\n        p0 = [loc, scale, shape, amplitude, baseline]\n    :param splitstyle: string, passed to ``im_split``; orientation\n        of channels, vertical or horizontal\n    :param showplot:  bool, if True, will generate a plot of the\n        distribution and fit\n\n    :return: tuple containing optimal parameters and covariance\n        matrix from fit. (popt_x, pcov_x, popt_y, pcov_y)\n\n    :Example:\n\n        >>> from smtools.alignment import inspect_global_fit\n        >>> import smtools.testdata as test\n        >>> params = inspect_global_fit(test.image_stack())\n        >>> print(params[0][0],params[2][0])\n        5.612082237088681 -2.651765063702885\n    \"\"\"\n    ###\n    pooled_x, pooled_y = [], []\n    for im in im_stack:\n        xdist, ydist = get_offset_distribution(im, bbox, splitstyle,\n                                               fsize)\n        pooled_x += xdist\n        pooled_y += ydist\n\n    ###\n    bins = make_bins(pooled_x, binwidth)\n    x_bincens = [bins[j] + (binwidth / 2.) for j in\n                 range(len(bins) - 1)]\n    x_vals = np.histogram(pooled_x, bins)\n\n    if init_params is None:\n        p0 = [x_bincens[np.argmax(x_vals[0])],\n              .2, 1, max(x_vals[0]), 0]\n\n    try:\n        popt_x, pcov_x = curve_fit(skewnormal, np.array(x_bincens),\n                                   np.array(x_vals[0]),p0)\n    except RuntimeError:\n        popt_x, pcov_x = [], []\n        pass\n\n    ###\n    bins = make_bins(pooled_y, binwidth)\n    y_bincens = [bins[j] + (binwidth / 2.) for j in\n                 range(len(bins) - 1)]\n    y_vals = np.histogram(pooled_y, bins)\n\n    if init_params is None:\n        p0 = [y_bincens[np.argmax(y_vals[0])],\n              .2, 1, max(y_vals[0]), 0]\n\n    try:\n        popt_y, pcov_y = curve_fit(skewnormal, np.array(y_bincens),\n                                   np.array(y_vals[0]),p0)\n    except RuntimeError:\n        popt_y, pcov_y = [], []\n        pass\n\n    ###\n    if showplot == True:\n        fig = plt.figure()\n        ax1 = fig.add_subplot(121)\n        ax2 = fig.add_subplot(122)\n\n        ax1.set_xlim(x_bincens[np.argmax(x_vals[0])] - 1.5,\n                     x_bincens[np.argmax(x_vals[0])] + 1.5)\n        ax1.set_title(\"x-offsets\")\n        ax1.bar(x_bincens, x_vals[0], width=binwidth / 2,\n                color = \"#008fd5\")\n        if len(popt_x) > 1:\n            fit = skewnormal(np.array(x_bincens), *popt_x)\n            ax1.plot(x_bincens, fit, \"--\", color=\"#fc4f30\",\n                     linewidth=3)\n\n        ax2.set_xlim(y_bincens[np.argmax(y_vals[0])] - 1.5,\n                     y_bincens[np.argmax(y_vals[0])] + 1.5)\n        ax2.set_title(\"y-offsets\")\n        ax2.bar(y_bincens, y_vals[0], width=binwidth / 2,\n                color=\"#FFA622\")\n        if len(popt_y) > 1:\n            fit = skewnormal(np.array(y_bincens), *popt_y)\n            ax2.plot(y_bincens, fit, \"--\", color=\"#5D3EAF\",\n                     linewidth=3)\n\n        plt.show()\n\n    try:\n        return ((popt_x[0],popt_y[0],[popt_x, pcov_x, popt_y, pcov_y]))\n    except :\n        return None\n\n\n\n\ndef inspect_individual_fits(im_stack, bbox=9, fsize=10,\n                            binwidth=.1, init_params = None,\n                            splitstyle=\"hsplit\"):\n\n    \"\"\"\n    This function provides a method to plot each individual offset\n    distributions of images passed to the function. Common usage is\n    to get a sense of how similar groups of images are.\n\n    :param im_stack: 1D list of image arrays to be used in\n        determination of the offset\n    :param bbox: int, passed to ``point_fitting.fit_routine``,\n        size of ROI around each point to apply gaussian fit. Default\n        is 9.\n    :param fsize: int, passed to ``point_fitting.find_maxima``,\n        size of average filters used in maxima determination. Default\n        is 10.\n    :param binwidth: float, passed to ``make_bins``; resolution of\n        histogram for fitting\n    :param init_params: 1D array, initial conditions passed to\n        scipy.optimize.curve_fit. must be length 5,\n        p0 = [loc, scale, shape, amplitude, baseline]\n    :param splitstyle: string, passed to ``im_split``; orientation\n        of channels, vertical or horizontal\n\n\n    :return: produces a plot of histograms and fits for each\n        individual image passed in im_stack. Also returns list of tuples,\n        each contains optimal parameters and covariance matrix from\n        fit. If no fit was found, returns an empty list. The lists\n        alternate between x and y-offset fits.\n\n    :Example:\n        >>> from smtools.alignment import inspect_individual_fits\n        >>> import smtools.testdata as test\n        >>> params = inspect_individual_fits(test.image_stack())\n    \"\"\"\n    pooled_x, pooled_y = [], []\n    for im in im_stack:\n        xdist, ydist = get_offset_distribution(im)\n        pooled_x += xdist\n        pooled_y += ydist\n    spanx = [np.median(pooled_x) - 1.5, np.median(pooled_x) + 1.5]\n    spany = [np.median(pooled_y) - 1.5, np.median(pooled_y) + 1.5]\n\n    fig, axes = plt.subplots(nrows=len(im_stack), ncols=2)\n    plt.subplots_adjust(wspace=0, hspace=0)\n    axlist = [i for i in axes.flat]\n\n    count = 0\n    fitlist = []\n    for im in im_stack:\n        xdist, ydist = get_offset_distribution(im, bbox, splitstyle,\n                                               fsize)\n\n        bins = make_bins(xdist, binwidth)\n        x_bincens = [bins[j] + (binwidth / 2.) for j in\n                     range(len(bins) - 1)]\n        x_vals = np.histogram(xdist, bins)\n        axlist[count].set_xlim(spanx)\n        axlist[count].axes.get_yaxis().set_visible(False)\n        axlist[count].bar(x_bincens, x_vals[0], width=binwidth / 2,\n                          color=\"#008fd5\")\n\n        if init_params is None:\n            p0 = [x_bincens[np.argmax(x_vals[0])],\n                  .2, 1, max(x_vals[0]), 0]\n        try:\n            popt_x, pcov_x = curve_fit(skewnormal, np.array(x_bincens),\n                                       np.array(x_vals[0]),p0)\n            fitlist.append((popt_x, pcov_x))\n            fit = skewnormal(np.array(x_bincens), *popt_x)\n            axlist[count].plot(x_bincens, fit, \"--\",\n                               color=\"#fc4f30\", linewidth=2)\n\n        except RuntimeError:\n            fitlist.append([])\n            pass\n\n        count += 1\n        bins = make_bins(ydist, binwidth)\n        y_bincens = [bins[j] + (binwidth / 2.) for j in\n                     range(len(bins) - 1)]\n        y_vals = np.histogram(ydist, bins)\n        axlist[count].set_xlim(spany)\n        axlist[count].axes.get_yaxis().set_visible(False)\n        axlist[count].bar(y_bincens, y_vals[0], width=binwidth / 2,\n                          color=\"#FFA622\", linewidth=2)\n\n        if init_params is None:\n            p0 = [y_bincens[np.argmax(y_vals[0])],\n                  .2, 1, max(y_vals[0]), 0]\n        try:\n            popt_y, pcov_y = curve_fit(skewnormal, np.array(y_bincens),\n                                       np.array(y_vals[0]), p0)\n            fitlist.append((popt_y, pcov_y))\n            fit = skewnormal(np.array(y_bincens), *popt_y)\n            axlist[count].plot(y_bincens, fit, \"--\",\n                               color=\"#5D3EAF\")\n\n        except RuntimeError:\n            fitlist.append([])\n            pass\n\n        count += 1\n    plt.show()\n\n    return (fitlist)\n\n\n\n\n\ndef align_by_offset(Image, shift_x, shift_y, splitstyle=\"hsplit\",\n                    shift_channel=1):\n    \"\"\"\n    This function shifts one channel of the array based supplied\n    offset values. Retains the single image structure.\n\n    :param Image: 2D image array\n    :param shift_x: float, offset in x\n    :param shift_y: float, offset in y\n    :param splitstyle: string, passed to ``im_split``; accepts\n        \"hsplit\", \"vsplit\". Default is \"hsplit\"\n    :param shift_channel: int, which channel to shift by offsets,\n        default is channel 1.\n\n    :return: 2D image array of aligned image\n\n    :Example:\n        >>> from smtools.alignment import find_global_offset,\n        align_by_offset\n        >>> import smtools.testdata as test\n        >>> import matplotlib.pyplot as plt\n        >>> im = test.image_stack()\n        >>> dx, dy = find_global_offset(im)\n        >>> new_image = align_by_offset(im[0], dx, dy)\n        >>> plt.imshow(new_image), plt.show()\n    \"\"\"\n\n    ch1, ch2 = im_split(Image, splitstyle)\n    if shift_channel == 1:\n        new_coords = warp_coords(\n            lambda xy: xy - np.array([shift_x, shift_y]), ch2.shape)\n        warped_channel = map_coordinates(ch2, new_coords)\n        aligned_image = np.concatenate((ch1, warped_channel), axis=1)\n    else:\n        new_coords = warp_coords(\n            lambda xy: xy + np.array([shift_x, shift_y]), ch1.shape)\n        warped_channel = map_coordinates(ch1, new_coords)\n        aligned_image = np.concatenate((warped_channel, ch2), axis=1)\n    return aligned_image\n\n\n\n\n\ndef overlay(Image, splitstyle=\"hsplit\", rot=True, invert=False):\n    \"\"\"\n    Overlays the two channels derived from Image. Converts Image to\n    an 8-bit RGB array, with one channel colored magenta and the\n    other green.\n\n    :param Image: 2D image array\n    :param splitstyle: string, passed to ``im_split``; accepts\n        \"hsplit\", \"vsplit\". Default is \"hsplit\"\n    :param rot: bool, if True, image is rotated 90 degrees\n    :param invert: bool, if True, inverts the channel color assignment.\n\n    :return: 8-bit RGB image\n\n    :Example:\n        >>> from smtools.alignment import overlay\n        >>> import smtools.testdata as test\n        >>> import matplotlib.pyplot as plt\n        >>> im = test.image_stack()\n        >>> dx, dy = find_global_offset(im)\n        >>> aligned_image = align_by_offset(im[0], dx, dy)\n        >>> overlayed = overlay(aligned_image)\n        >>> plt.imshow(overlayed), plt.show()\n    \"\"\"\n    if not invert:\n        ch1, ch2 = im_split(Image,splitstyle)\n    else:\n        ch2, ch1 = im_split(Image,splitstyle)\n    ch1_max = ch1.max()\n    ch2_max = ch2.max()\n    shape = ch1.shape\n    red = np.zeros(shape)\n    green = np.zeros(shape)\n    for x in range(0, shape[0]):\n        for y in range(0, shape[1]):\n            red[x, y] = ch1[x, y] / ch1_max\n            green[x, y] = ch2[x, y] / ch2_max\n    rgb_stack = np.dstack((red, green, red))\n    if rot:\n        rgb_stack = rotate(rgb_stack, -90, resize=True)\n\n    rgb_stack *= 255\n    rgb_stack = rgb_stack.astype(np.uint8)\n    return rgb_stack\n\n", "meta": {"hexsha": "2bf87a6ef6c895b782c1d59c66e9c86dd6e68dd0", "size": 17825, "ext": "py", "lang": "Python", "max_stars_repo_path": "smtools/alignment.py", "max_stars_repo_name": "ReddingLab/smtools", "max_stars_repo_head_hexsha": "bd319909c9169d2f083a513e55f090fe721a000f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "smtools/alignment.py", "max_issues_repo_name": "ReddingLab/smtools", "max_issues_repo_head_hexsha": "bd319909c9169d2f083a513e55f090fe721a000f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-04-05T19:48:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-29T20:22:15.000Z", "max_forks_repo_path": "smtools/alignment.py", "max_forks_repo_name": "ReddingLab/smtools", "max_forks_repo_head_hexsha": "bd319909c9169d2f083a513e55f090fe721a000f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4111969112, "max_line_length": 73, "alphanum_fraction": 0.5943899018, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.19460231284678656}}
{"text": "import logging\nimport numpy as np\nimport resource\nimport random\nfrom sys import stdout\nimport os\nimport argparse\nimport pickle as Pickle\nimport scipy.optimize\nfrom flarestack.core.injector import read_injector_dict\nfrom flarestack.core.llh import LLH, generate_dynamic_flare_class, read_llh_dict\nfrom flarestack.shared import name_pickle_output_dir, \\\n    inj_dir_name, plot_output_dir, scale_shortener, flux_to_k\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfrom matplotlib.colors import Normalize, ListedColormap\nimport matplotlib as mpl\nfrom flarestack.core.time_pdf import TimePDF, Box, Steady\nfrom flarestack.core.angular_error_modifier import BaseAngularErrorModifier\nfrom flarestack.utils.catalogue_loader import load_catalogue, \\\n    calculate_source_weight\nfrom flarestack.utils.asimov_estimator import estimate_discovery_potential\n\nlogger = logging.getLogger(__name__)\n\ndef time_smear(inj):\n    inj_time = inj[\"injection_sig_time_pdf\"]\n    max_length = inj_time[\"max_offset\"] - inj_time[\"min_offset\"]\n    offset = np.random.random() * max_length + inj_time[\"min_offset\"]\n    inj_time[\"offset\"] = offset\n    return inj_time\n\n\ndef read_mh_dict(mh_dict):\n    \"\"\"Ensure backwards compatibility of MinimisationHandler dictionary objects\n\n    :param mh_dict: MinimisationHandler dictionary\n    :return: MinimisationHandler dictionary compatible with new format\n    \"\"\"\n\n    # Ensure backwards compatibility\n\n    maps = [\n        (\"inj kwargs\", \"inj_dict\"),\n        (\"datasets\", \"dataset\"),\n        (\"background TS\", \"background_ts\")\n    ]\n\n    for (old_key, new_key) in maps:\n\n        if old_key in list(mh_dict.keys()):\n            logger.warning(\"Deprecated mh_dict key '{0}' was used. Please use '{1}' in future.\".format(\n                old_key, new_key))\n            mh_dict[new_key] = mh_dict[old_key]\n\n    if \"name\" not in mh_dict.keys():\n        raise KeyError(\"mh_dict object is missing key 'name'.\"\n                       \"This should be the unique save path for results.\")\n\n    elif mh_dict[\"name\"][-1] != \"/\":\n        mh_dict[\"name\"] += \"/\"\n\n    pairs = [\n        (\"inj_dict\", read_injector_dict),\n        (\"llh_dict\", read_llh_dict)\n    ]\n\n    for (key, f) in pairs:\n        if key in list(mh_dict.keys()):\n            mh_dict[key] = f(mh_dict[key])\n\n    if np.logical_and(\"fixed_scale\" in mh_dict.keys(), \"n_steps\" in mh_dict.keys()):\n        raise Exception(f\"MinimisationHandler dictionary contained both 'fixed_scale' key for \"\n                        f\"set injection flux, and 'n_steps' key for stepped injection flux.\"\n                        f\"Please use only one of these options. \\n  mh_dict: \\n {mh_dict}\")\n\n    return mh_dict\n\n\nclass MinimisationHandler(object):\n    \"\"\"Generic Class to handle both dataset creation and llh minimisation from\n    experimental data and Monte Carlo simulation. Initialised with a set of\n    IceCube datasets, a list of sources, and independent sets of arguments for\n    the injector and the likelihood.\n    \"\"\"\n    subclasses = {}\n\n    # Each MinimisationHandler must specify which LLH classes are compatible\n    compatible_llh = []\n    compatible_negative_n_s = False\n\n    def __init__(self, mh_dict):\n\n        mh_dict = read_mh_dict(mh_dict)\n\n        sources = load_catalogue(mh_dict[\"catalogue\"])\n\n        self.name = mh_dict[\"name\"]\n\n        self.pickle_output_dir = name_pickle_output_dir(self.name)\n        self._injectors = dict()\n        self._llhs = dict()\n        self._aem = dict()\n        self.seasons = mh_dict[\"dataset\"]\n        self.sources = sources\n        self.mh_dict = mh_dict\n\n        if \"inj_dict\" in mh_dict.keys():\n\n            # Checks whether signal injection should be done with a sliding PDF\n            # within a larger window, or remain fixed at the specified time\n\n            inj = dict(mh_dict[\"inj_dict\"])\n\n            try:\n                self.time_smear = inj[\"injection_sig_time_pdf\"][\"time_smear_bool\"]\n            except KeyError:\n                self.time_smear = False\n\n            if self.time_smear:\n                inj[\"injection_sig_time_pdf\"] = time_smear(inj)\n\n            self.inj_dict = inj\n\n        # An independent set of Season objects can be used for the injector\n        # This enables, for example, different MC sets to be used for\n        # injection, to test the impact of different systematics\n\n        try:\n            self.inj_seasons = mh_dict[\"inj_dict\"][\"injection_dataset\"]\n            logger.debug(\"Using independent injection dataset.\")\n\n            if self.inj_seasons.keys() != self.seasons.keys():\n                raise Exception(\"Key mismatch between injection and llh \"\n                                \"Season objects. Injection Seasons have \"\n                                \"keys:\\n {0} \\n and LLH Seasons have keys: \\n\"\n                                \"{1}\". format(self.inj_seasons.keys(),\n                                              self.seasons.keys()))\n\n        except KeyError:\n            self.inj_seasons = self.seasons\n\n        self.llh_dict = mh_dict[\"llh_dict\"]\n\n        # Check if the specified MinimisationHandler is compatible with the\n        # chosen LLH class\n\n        if self.llh_dict[\"llh_name\"] not in self.compatible_llh:\n            raise ValueError(\"Specified LLH ({}) is not compatible with \"\n                             \"selected MinimisationHandler\".format(\n                              self.llh_dict[\"llh_name\"]))\n        else:\n            logger.info(\"Using '{0}' LLH class\".format(self.llh_dict[\"llh_name\"]))\n\n        # Checks if negative n_s is specified for use, and whether this is\n        # compatible with the chosen MinimisationHandler\n\n        try:\n            self.negative_n_s = self.llh_dict[\"negative_ns_bool\"]\n        except KeyError:\n            self.negative_n_s = False\n\n        if self.negative_n_s and not self.compatible_negative_n_s:\n            raise ValueError(\"MinimisationHandler has been instructed to \\n\"\n                             \"allow negative n_s, but this is not compatible \\n\"\n                             \"with the selected MinimisationHandler.\")\n\n        # Sets up whether what pull corrector should be used (default is\n        # none), and whether an angular error floor should be applied (\n        # default is a static floor.\n\n        try:\n            self.pull_name = self.llh_dict[\"pull_name\"]\n        except KeyError:\n            self.pull_name = \"no_pull\"\n\n        try:\n            self.floor_name = self.llh_dict[\"floor_name\"]\n        except KeyError:\n            self.floor_name = \"static_floor\"\n\n        p0, bounds, names = self.return_parameter_info(mh_dict)\n\n        self.p0 = p0\n        self.bounds = bounds\n        self.param_names = names\n\n        self.disc_guess = np.nan\n\n    @classmethod\n    def register_subclass(cls, mh_name):\n        \"\"\"Adds a new subclass of EnergyPDF, with class name equal to\n        \"energy_pdf_name\".\n        \"\"\"\n        def decorator(subclass):\n            cls.subclasses[mh_name] = subclass\n            return subclass\n\n        return decorator\n\n    @classmethod\n    def create(cls, mh_dict):\n        mh_dict = read_mh_dict(mh_dict)\n\n        mh_name = mh_dict[\"mh_name\"]\n\n        if mh_name not in cls.subclasses:\n            raise ValueError('Bad MinimisationHandler name {}'.format(mh_name))\n\n        return cls.subclasses[mh_name](mh_dict)\n\n    @classmethod\n    def find_parameter_info(cls, mh_dict):\n        read_mh_dict(mh_dict)\n        mh_name = mh_dict[\"mh_name\"]\n\n        if mh_name not in cls.subclasses:\n            raise ValueError('Bad MinimisationHandler name {}'.format(mh_name))\n\n        return cls.subclasses[mh_name].return_parameter_info(mh_dict)\n\n    def run_trial(self, full_dataset):\n        pass\n\n    def run(self, n_trials, scale=1., seed=None):\n        pass\n\n    @staticmethod\n    def trial_params(mh_dict):\n\n        if \"fixed_scale\" in list(mh_dict.keys()):\n            scale_range = [mh_dict[\"fixed_scale\"]]\n\n        # elif mh_dict.get(\"background_only\", False):\n        #     # Only do the background trials\n        #     # In this case only n_trials background trials are performed, not 10x n_trials!\n        #     scale_range = np.array([0])\n        #\n        # elif mh_dict.get(\"injection_only\", False):\n        #     # Only do trials with signal injection\n        #     scale = mh_dict[\"scale\"]\n        #     steps = int(mh_dict[\"n_steps\"])\n        #     scale_range = np.array(list(np.linspace(0., scale, steps)[1:]))\n\n        else:\n            scale = mh_dict[\"scale\"]\n            steps = int(mh_dict[\"n_steps\"])\n            background_ntrials_factor = mh_dict.get('background_ntrials_factor', 10)\n            scale_range = np.array(\n                [0. for _ in range(background_ntrials_factor)] +\n                list(np.linspace(0., scale, steps)[1:])\n            )\n\n        n_trials = int(mh_dict[\"n_trials\"])\n\n        return scale_range, n_trials\n\n    def iterate_run(self, scale=1., n_steps=5, n_trials=50):\n\n        scale_range = np.linspace(0., scale, n_steps)[1:]\n\n        self.run(n_trials*10, scale=0.0)\n\n        for scale in scale_range:\n            self.run(n_trials, scale)\n\n    @staticmethod\n    def return_parameter_info(mh_dict):\n        seeds = []\n        bounds = []\n        names = []\n        return seeds, names, bounds\n\n    @staticmethod\n    def return_injected_parameters(mh_dict):\n        return {}\n\n    def add_likelihood(self, season):\n        return LLH.create(season, self.sources, self.llh_dict)\n\n    def get_likelihood(self, season_name):\n\n        if season_name not in self._llhs.keys():\n            self._llhs[season_name] = self.add_likelihood(self.seasons[season_name])\n\n        return self._llhs[season_name]\n\n    def add_injector(self, season, sources):\n        return season.make_injector(sources, **self.inj_dict)\n\n    def get_injector(self, season_name):\n\n        if season_name not in self._injectors.keys():\n            self._injectors[season_name] = self.add_injector(self.seasons[season_name], self.sources)\n\n        return self._injectors[season_name]\n\n    def add_angular_error_modifier(self, season):\n        return BaseAngularErrorModifier.create(\n                season, self.llh_dict[\"llh_energy_pdf\"], self.floor_name,\n                self.pull_name,\n                gamma_precision=self.llh_dict.get('gamma_precision', 'flarestack')\n        )\n\n    def get_angular_error_modifier(self, season_name):\n\n        if season_name not in self._aem.keys():\n            self._aem[season_name] = self.add_angular_error_modifier(self.seasons[season_name])\n\n        return self._aem[season_name]\n\n    @staticmethod\n    def set_random_seed(seed):\n        np.random.seed(seed)\n\n    def guess_scale(self):\n        \"\"\"Method to guess flux scale for sensitivity + discovery potential\n        :return:\n        \"\"\"\n        return 1.5 * flux_to_k(self.guess_discovery_potential())\n\n    def guess_discovery_potential(self):\n        self.disc_guess = estimate_discovery_potential(\n            self.seasons, dict(self.inj_dict), self.sources, dict(self.llh_dict))\n        return self.disc_guess\n\n\n@MinimisationHandler.register_subclass('fixed_weights')\nclass FixedWeightMinimisationHandler(MinimisationHandler):\n    \"\"\"Class to perform generic minimisations using a 'fixed weights' matrix.\n    Sources are assigned intrinsic weights based on their assumed luminosity\n    and/or distance, which are fixed. In addition, time weighting is used\n    assuming a fixed fluence per source. The detector acceptance continues to\n    vary as a function of the parameters given in minimisation step.\n    \"\"\"\n\n    compatible_llh = [\"spatial\", \"fixed_energy\", \"standard\",\n                      \"standard_overlapping\", \"standard_matrix\"]\n    compatible_negative_n_s = True\n\n    def __init__(self, mh_dict):\n\n        MinimisationHandler.__init__(self, mh_dict)\n\n        self.fit_weights = False\n\n        # Checks if minimiser should be seeded from a brute scan\n\n        try:\n            self.brute = self.llh_dict[\"brute_seed\"]\n        except KeyError:\n            self.brute = False\n\n        # self.clean_true_param_values()\n\n    def clear(self):\n\n        self._injectors.clear()\n        self._llhs.clear()\n\n        del self\n\n    def dump_results(self, results, scale, seed):\n        \"\"\"Takes the results of a set of trials, and saves the dictionary as\n        a pickle pkl_file. The flux scale is used as a parent directory, and the\n        pickle pkl_file itself is saved with a name equal to its random seed.\n\n        :param results: Dictionary of Minimisation results from trials\n        :param scale: Scale of inputted flux\n        :param seed: Random seed used for running of trials\n        \"\"\"\n\n        if self.name == \" /\":\n            logger.warning(\"No field 'name' was specified in mh_dict object. \"\n                            \"Cannot save results without a unique directory\"\n                            \" name being specified.\")\n\n        else:\n\n            write_dir = os.path.join(self.pickle_output_dir, scale_shortener(scale))\n\n            # Tries to create the parent directory, unless it already exists\n            try:\n                os.makedirs(write_dir)\n            except OSError:\n                pass\n\n            file_name = os.path.join(write_dir, str(seed) + \".pkl\")\n\n            logger.debug(\"Saving to {0}\".format(file_name))\n\n            with open(file_name, \"wb\") as f:\n                Pickle.dump(results, f)\n\n    def dump_injection_values(self, scale):\n\n        if self.name == \" /\":\n            raise Exception(\"No field 'name' was specified in mh_dict object. \"\n                            \"Cannot save results without a unique directory\"\n                            \" name being specified.\")\n\n        else:\n\n            inj_dict = self.return_injected_parameters(scale)\n\n            inj_dir = inj_dir_name(self.name)\n\n            # Tries to create the parent directory, unless it already exists\n            try:\n                os.makedirs(inj_dir)\n            except OSError:\n                pass\n\n            file_name = os.path.join(inj_dir, scale_shortener(scale) + \".pkl\")\n\n            logger.debug(f\"Dumping Injection values to {file_name}\")\n\n            with open(file_name, \"wb\") as f:\n                Pickle.dump(inj_dict, f)\n\n    def run_trial(self, full_dataset):\n\n        raw_f = self.trial_function(full_dataset)\n\n        def llh_f(scale):\n            return -np.sum(raw_f(scale))\n\n        if self.brute:\n\n            brute_range = [\n                (max(x, -30), min(y, 30)) for (x, y) in self.bounds]\n\n            start_seed = scipy.optimize.brute(\n                llh_f, ranges=brute_range, finish=None, Ns=40)\n        else:\n            start_seed = self.p0\n\n        res = scipy.optimize.minimize(\n            llh_f, start_seed, bounds=self.bounds)\n\n        vals = res.x\n        flag = res.status\n        # If the minimiser does not converge, repeat with brute force\n        if flag == 1:\n            vals = scipy.optimize.brute(llh_f, ranges=self.bounds,\n                                        finish=None)\n\n        best_llh = raw_f(vals)\n\n        if np.logical_and(not res.x[0] > 0.0, self.negative_n_s):\n\n            bounds = list(self.bounds)\n            bounds[0] = (-1000., -0.)\n            start_seed = list(self.p0)\n            start_seed[0] = -1.\n\n            new_res = scipy.optimize.minimize(\n                llh_f, start_seed, bounds=bounds)\n\n            if new_res.status == 0:\n                res = new_res\n\n            vals = [res.x[0]]\n            best_llh = res.fun\n\n        ts = np.sum(best_llh)\n\n        if ts == -0.0:\n            ts = 0.0\n\n        parameters = dict()\n\n        for i, val in enumerate(vals):\n            parameters[self.param_names[i]] = val\n\n        res_dict = {\n            \"res\": res,\n            \"Parameters\": parameters,\n            \"TS\": ts,\n            \"Flag\": flag,\n            \"f\": llh_f\n        }\n\n        return res_dict\n\n    def run_single(self, full_dataset, scale, seed):\n\n        param_vals = {}\n        for key in self.param_names:\n            param_vals[key] = []\n        ts_vals = []\n        flags = []\n\n        res_dict = self.run_trial(full_dataset)\n\n        for (key, val) in res_dict[\"Parameters\"].items():\n            param_vals[key].append(val)\n\n        ts_vals.append(res_dict[\"TS\"])\n        flags.append(res_dict[\"Flag\"])\n\n        mem_use = str(\n            float(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) / 1.e6)\n        logger.debug('Memory usage max: {0} (Gb)'.format(mem_use))\n\n        results = {\n            \"TS\": ts_vals,\n            \"Parameters\": param_vals,\n            \"Flags\": flags,\n        }\n\n        self.dump_results(results, scale, seed)\n        return res_dict\n\n    def simulate_and_run(self, scale, seed=None):\n        if seed is None:\n            seed = np.random.randint(low=0, high=99999999)\n        self.set_random_seed(seed)\n        full_dataset = self.prepare_dataset(scale, seed)\n        return self.run_single(full_dataset, scale, seed)\n\n    def run(self, n_trials, scale=1., seed=None):\n\n        if seed is None:\n            seed = int(random.random() * 10 ** 8)\n        np.random.seed(seed)\n\n        # param_vals = [[] for x in self.p0]\n        param_vals = {}\n        for key in self.param_names:\n            param_vals[key] = []\n        ts_vals = []\n        flags = []\n\n        logger.info(\"Generating {0} trials!\".format(n_trials))\n\n        for i in range(int(n_trials)):\n\n            res_dict = self.simulate_and_run(scale)\n\n            for (key, val) in res_dict[\"Parameters\"].items():\n                param_vals[key].append(val)\n\n            ts_vals.append(res_dict[\"TS\"])\n            flags.append(res_dict[\"Flag\"])\n\n        n_inj = 0\n        for season in self.seasons.keys():\n            inj = self.get_injector(season)\n            n_inj += np.sum(inj.n_exp[\"n_exp\"] * scale)\n\n        logger.info(\"Injected with an expectation of {0} events.\".format(n_inj))\n\n        logger.info(\"FIT RESULTS:\")\n\n        for (key, param) in sorted(param_vals.items()):\n            if len(param) > 0:\n                logger.info(\"Parameter {0}: {1} {2} {3}\".format(key, np.mean(param),\n                      np.median(param), np.std(param)))\n        logger.info(\"Test Statistic: {0} {1} {2}\".format(np.mean(ts_vals),\n              np.median(ts_vals), np.std(ts_vals)))\n\n        logger.info(\"FLAG STATISTICS:\")\n        for i in sorted(np.unique(flags)):\n            logger.info(\"Flag {0}:{1}\".format(i, flags.count(i)))\n\n        results = {\n            \"TS\": ts_vals,\n            \"Parameters\": param_vals,\n            \"Flags\": flags,\n        }\n\n        self.dump_results(results, scale, seed)\n        self.dump_injection_values(scale)\n\n    def make_season_weight(self, params, season):\n\n        src = self.sources\n\n        weight_scale = calculate_source_weight(src)\n\n        # dist_weight = src[\"distance_mpc\"] ** -2\n        # base_weight = src[\"base_weight\"]\n\n        llh = self.get_likelihood(season.season_name)\n        acc = []\n\n        time_weights = []\n        source_weights = []\n\n        for source in src:\n            time_weights.append(llh.sig_time_pdf.effective_injection_time(\n                source))\n            acc.append(llh.acceptance(source, params))\n            source_weights.append(calculate_source_weight(source) /\n                                  weight_scale)\n\n        time_weights = np.array(time_weights)\n        source_weights = np.array(source_weights)\n\n        acc = np.array(acc).T[0]\n\n        w = acc * time_weights\n        w *= source_weights\n\n        w = w[:, np.newaxis]\n\n        return w\n\n    def make_weight_matrix(self, params):\n\n        # Creates a matrix fixing the fraction of the total signal that\n        # is expected in each Source+Season pair. The matrix is\n        # normalised to 1, so that for a given total n_s, the expectation\n        # for the ith season for the jth source is given by:\n        #  n_exp = n_s * weight_matrix[i][j]\n\n        weights_matrix = np.ones([len(self.seasons), len(self.sources)])\n\n        for i, season in enumerate(self.seasons.values()):\n            w = self.make_season_weight(params, season)\n\n            for j, ind_w in enumerate(w):\n                weights_matrix[i][j] = ind_w\n\n        return weights_matrix\n\n    def prepare_dataset(self, scale=1., seed=None):\n\n        if seed is None:\n            seed = int(random.random() * 10 ** 8)\n        np.random.seed(seed)\n\n        full_dataset = dict()\n\n        for name in self.seasons.keys():\n            full_dataset[name] = self.get_injector(name).create_dataset(\n                scale, self.get_angular_error_modifier(name)\n            )\n\n        return full_dataset\n\n    def trial_function(self, full_dataset):\n\n        llh_functions = dict()\n        n_all = dict()\n\n        for name in self.seasons:\n            dataset = full_dataset[name]\n            llh_f = self.get_likelihood(name).create_llh_function(\n                dataset, self.get_angular_error_modifier(name),\n                self.make_season_weight\n            )\n            llh_functions[name] = llh_f\n            n_all[name] = len(dataset)\n\n        def f_final(raw_params):\n\n            # If n_s is less than or equal to 0, set gamma to be 3.7 (equal to\n            # atmospheric background). This is continuous at n_s=0, but fixes\n            # relative weights of sources/seasons for negative n_s values.\n\n            params = list(raw_params)\n\n            if (len(params) > 1) and (params[0] < 0):\n                params[1] = 3.7\n\n            # Calculate relative contribution of each source/season\n\n            weights_matrix = self.make_weight_matrix(params)\n            weights_matrix /= np.sum(weights_matrix)\n\n            # Having created the weight matrix, loops over each season of\n            # data and evaluates the TS function for that season\n\n            ts_val = 0\n            for i, name in enumerate(self.seasons):\n                w = weights_matrix[i][:, np.newaxis]\n                ts_val += np.sum(llh_functions[name](params, w))\n\n            return ts_val\n\n        return f_final\n\n    def scan_likelihood(self, scale=0., scan_2d=False):\n        \"\"\"Generic wrapper to perform a likelihood scan a background scramble\n        with an injection of signal given by scale.\n\n        :param scale: Flux scale to inject\n        \"\"\"\n\n        res_dict = self.simulate_and_run(scale)\n\n        res = res_dict[\"res\"]\n        g = res_dict[\"f\"]\n\n        bounds = list(self.bounds)\n\n        if self.negative_n_s:\n            bounds[0] = (-30, 30)\n\n        # Scan 1D Likelihood\n\n        plt.figure(figsize=(8, 4 + 2*len(self.p0)))\n\n        u_ranges = []\n\n        for i, bound in enumerate(bounds):\n            ax = plt.subplot(len(self.p0), 1, 1 + i)\n\n            best = list(res.x)\n            min_llh = np.sum(float(g(best)))\n\n            factor = 0.9\n\n            if \"n_s\" in self.param_names[i]:\n\n                best[i] = bound[1]\n\n                while (g(best) > (min_llh + 5.0)):\n                    best[i] *= factor\n\n                ur = min(bound[1], max(best[i], 0))\n\n            else:\n                ur = bound[1]\n\n            u_ranges.append(ur)\n\n            n_range = np.linspace(float(max(bound[0], -100)), ur, int(1e2))\n\n            # n_range = np.linspace(-30, 30, 1e2)\n            y = []\n\n            for n in n_range:\n\n                best[i] = n\n\n                new = g(best)/2.0\n                try:\n                    y.append(new[0][0])\n                except IndexError:\n                    y.append(new)\n\n            plt.plot(n_range, y - min(y))\n            plt.xlabel(self.param_names[i])\n            plt.ylabel(r\"$\\Delta \\log(\\mathcal{L}/\\mathcal{L}_{0})$\")\n\n            logger.info(f\"PARAM: {self.param_names[i]}\")\n            min_y = np.min(y)\n\n            min_index = y.index(min_y)\n            min_n = n_range[min_index]\n\n            logger.info(f\"Minimum value of {min_y} at {min_n}\")\n\n            logger.info(\"One Sigma interval between\")\n\n            l_y = np.array(y[:min_index])\n            try:\n                l_y = min(l_y[l_y > (min_y + 0.5)])\n                l_lim = n_range[y.index(l_y)]\n                logger.info(l_lim)\n            except ValueError:\n                l_lim = min(n_range)\n                logger.info(f\"<{l_lim}\")\n\n            logger.info(\"and\")\n\n            u_y = np.array(y[min_index:])\n            try:\n                u_y = min(u_y[u_y > (min_y + 0.5)])\n                u_lim = n_range[y.index(u_y)]\n                logger.info(u_lim)\n            except ValueError:\n                u_lim = max(n_range)\n                logger.info(f\">{u_lim}\")\n\n            ax.axvspan(l_lim, u_lim, facecolor=\"grey\",\n                        alpha=0.2)\n            ax.set_ylim(bottom=0.0)\n\n        path = plot_output_dir(self.name) + \"llh_scan.pdf\"\n\n        title = os.path.basename(\n                    os.path.dirname(self.name[:-1])\n                ).replace(\"_\", \" \") + \" Likelihood Scans\"\n\n        plt.suptitle(title, y=1.02)\n\n        try:\n            os.makedirs(os.path.dirname(path))\n        except OSError:\n            pass\n\n        plt.savefig(path)\n        plt.close()\n\n        logger.info(\"Saved to {0}\".format(path))\n\n        # Scan 2D likelihood\n\n        if np.logical_and(scan_2d, \"gamma\" in self.param_names):\n\n            gamma_index = self.param_names.index(\"gamma\")\n\n            gamma_bounds = bounds[gamma_index]\n\n            x = np.linspace(gamma_bounds[0], gamma_bounds[1])\n\n            mask = np.array([\"n_s\" in b for b in self.param_names])\n\n            n_s_bounds = np.array(self.bounds)[mask]\n\n            for j, bound in enumerate(n_s_bounds):\n                best = list(res.x)\n                plt.figure(figsize=(5.85, 3.6154988341868854))\n                ax = plt.subplot(111)\n\n                index = np.arange(len(self.param_names))[mask][j]\n\n                plt.xlabel(r\"Spectral Index ($\\gamma$)\")\n\n                param_name = np.array(self.param_names)[mask][j]\n                ylabel = 'n$_{\\mathrm{signal}}$' if param_name == 'n_s' else param_name\n                plt.ylabel(ylabel)\n\n                y = np.linspace(\n                    float(max(bound[0], -100)),\n                    np.array(u_ranges)[index],\n                    int(1e2)\n                )\n\n                X, Y = np.meshgrid(x, y[::-1])\n                Z = []\n\n                for gamma in x:\n                    best[gamma_index] = gamma\n                    z_row = []\n\n                    for n in y:\n                        best[index] = n\n                        z_row.append((g(best) - g(res.x))/2.0)\n\n                    Z.append(z_row[::-1])\n\n                Z = np.array(Z).T\n\n                levels = 0.5 * np.array([1.0, 2.0, 5.0])**2\n\n                N = 2560\n                mmax = np.max(Z)\n                mmin = np.min(Z)\n                break_ind = int(round(N / (1 + mmax / abs(mmin))))\n                top = cm.get_cmap('gray')\n                bottom = cm.get_cmap('jet_r', N)\n                colorlist = np.empty((N, 4))\n                colorlist[break_ind:] = bottom(np.linspace(0, 1, N - break_ind))\n                colorlist[:break_ind] = top(np.linspace(1, 0, break_ind))\n                cmap = ListedColormap(colorlist)\n                norm = Normalize(vmin=mmin, vmax=mmax, clip=True)\n\n                plt.imshow(Z, aspect=\"auto\", cmap=cmap, norm=norm,\n                           extent=(x[0], x[-1], y[0], y[-1]),\n                           interpolation='bilinear')\n\n                cbar = plt.colorbar()\n                CS = ax.contour(X, Y, Z, levels=levels, colors=\"white\")\n\n                fmt = {}\n                strs = [r'1$\\sigma$', r'2$\\sigma$', r'5$\\sigma$']\n                for l, s in zip(CS.levels, strs):\n                    fmt[l] = s\n\n                try:\n                    ax.clabel(CS, fmt=fmt, inline=1, fontsize=10, levels=levels,\n                              colors=\"white\")\n                except TypeError:\n                    ax.clabel(CS, levels, fmt=fmt, inline=1, fontsize=10, #levels=levels,\n                              colors=\"white\")\n\n                ax.set_xlim((min(x), max(x)))\n                ax.set_ylim((min(y), max(y)))\n\n                cbar.set_label(r\"$\\Delta \\log(\\mathcal{L}/\\mathcal{L}_{0})$\",\n                               rotation=90)\n\n                path = plot_output_dir(self.name) + (param_name + \"_\")[4:] + \\\n                       \"contour_scan.pdf\"\n\n                title = os.path.basename(\n                    os.path.dirname(self.name[:-1])\n                ).replace(\"_\", \" \") + \" Contour Scans\"\n\n                plt.scatter(res.x[gamma_index], res.x[index],  color=\"white\",\n                            marker=\"*\")\n\n                plt.grid(color=\"white\", linestyle=\"--\", alpha=0.5)\n\n                #plt.suptitle(title)\n                plt.tight_layout()\n                plt.savefig(path)\n                plt.close()\n\n                logger.info(\"Saved to {0}\".format(path))\n\n        return res_dict\n\n    def neutrino_lightcurve(self, seed=None):\n\n        full_dataset = self.prepare_dataset(30., seed)\n\n        for source in self.sources:\n\n            f, (ax0, ax1) = plt.subplots(1, 2,\n                                       gridspec_kw={'width_ratios': [19, 1]})\n\n            logE = []\n            time = []\n            sig = []\n\n            for season in self.seasons:\n\n                # Generate a scrambled dataset, and save it to the datasets\n                # dictionary. Loads the llh for the season.\n                data = full_dataset[season]\n                llh = self.get_likelihood(season)\n\n                mask = llh.select_spatially_coincident_data(data, [source])\n\n                spatial_coincident_data = data[mask]\n\n                t_mask = np.logical_and(\n                    np.greater(\n                        spatial_coincident_data[\"time\"],\n                        llh.sig_time_pdf.sig_t0(source)),\n                    np.less(\n                        spatial_coincident_data[\"time\"],\n                        llh.sig_time_pdf.sig_t1(source))\n                )\n\n                coincident_data = spatial_coincident_data[t_mask]\n\n                SoB = llh.estimate_significance(coincident_data, source)\n\n                mask = SoB > 1.\n\n                y = np.log10(SoB[mask])\n\n                if np.sum(mask) > 0:\n\n                    logE += list(10 ** (coincident_data[\"logE\"][mask] - 3))\n                    time += list(coincident_data[\"time\"][mask])\n                    sig += list(y)\n\n                if llh.sig_time_pdf.sig_t0(source) > llh.sig_time_pdf.t0:\n\n                    ax0.axvline(llh.sig_time_pdf.sig_t0(source), color=\"k\", linestyle=\"--\", alpha=0.5)\n\n                if llh.sig_time_pdf.sig_t1(source) < llh.sig_time_pdf.t1:\n\n                    ax0.axvline(llh.sig_time_pdf.sig_t1(source), color=\"k\", linestyle=\"--\", alpha=0.5)\n\n            cmap = cm.get_cmap('jet')\n            norm = mpl.colors.Normalize(vmin=min(logE), vmax=max(logE),\n                                        clip=True)\n            m = cm.ScalarMappable(norm=norm, cmap=cmap)\n\n            for i, val in enumerate(sig):\n                x = time[i]\n                ax0.plot([x, x], [0, val], color=m.to_rgba(logE[i]))\n\n            if hasattr(self, \"res_dict\"):\n                params = self.res_dict[\"Parameters\"]\n                if len(params) > 1:\n                    ax0.axvspan(\n                        params[f\"t_start ({source['source_name']})\"],\n                        params[f\"t_end ({source['source_name']})\"],\n                        facecolor=\"grey\",\n                        alpha=0.2\n                    )\n            ax0.set_xlabel(\"Arrival Time (MJD)\")\n            ax0.set_ylabel(\"Log(Signal/Background)\")\n\n            cb1 = mpl.colorbar.ColorbarBase(ax1, cmap=cmap,\n                                            norm=norm,\n                                            orientation='vertical')\n            ax1.set_ylabel(\"Muon Energy Proxy (TeV)\")\n\n            ax0.set_ylim(bottom=0)\n            # plt.tight_layout()\n\n            path = f\"{plot_output_dir(self.name)}neutrino_lightcurve.pdf\"\n\n            try:\n                os.makedirs(os.path.dirname(path))\n            except OSError:\n                pass\n\n            logger.info(f\"Saving to {path}\")\n\n            plt.savefig(path)\n            plt.close()\n\n    @staticmethod\n    def return_parameter_info(mh_dict):\n        params = [[1.], [(0, 1000.)], [\"n_s\"]]\n\n        params = [\n            params[i] + x for i, x in enumerate(\n                LLH.get_parameters(mh_dict[\"llh_dict\"])\n            )\n        ]\n\n        return params[0], params[1], params[2]\n\n    def return_injected_parameters(self, scale):\n\n        n_inj = 0.\n        for season_name in self.seasons.keys():\n            n_inj += np.sum(self.get_injector(season_name).n_exp[\"n_exp\"] * scale)\n\n        inj_params = {\n            \"n_s\": n_inj\n        }\n        inj_params.update(LLH.get_injected_parameters(self.mh_dict))\n\n        return inj_params\n\n\n@MinimisationHandler.register_subclass('large_catalogue')\nclass LargeCatalogueMinimisationHandler(FixedWeightMinimisationHandler):\n    \"\"\"Class to perform generic minimisations using a 'fixed weights' matrix.\n    However, unlike the 'fixed_weight' class, it is optimised for large\n    numbers of sources. It uses a custom 'LowMemoryInjector' which is slower\n    but much less burdensome for memory.\n    \"\"\"\n\n    compatible_llh = [\"standard_matrix\"]\n    compatible_negative_n_s = False\n\n    def __init__(self, mh_dict):\n        FixedWeightMinimisationHandler.__init__(self, mh_dict)\n\n        if self.param_names != [\"n_s\", \"gamma\"]:\n            raise Exception(\"{0} parameters are given, when ['n_s','gamma']\"\n                            \"was expected\".format(self.param_names))\n\n    def add_injector(self, season, sources):\n\n        if \"injector_name\" in self.inj_dict.keys():\n            if self.inj_dict[\"injector_name\"] not in LargeCatalogueMinimisationHandler.compatible_injectors:\n                raise Exception(f\"'{self.inj_dict['injector_name']}' was provided as injection_name. \"\n                                f\"Please use any of {LargeCatalogueMinimisationHandler.compatible_injectors}.\")\n        else:\n            self.inj_dict[\"injector_name\"] = \"low_memory_injector\"\n\n        return season.make_injector(sources, **self.inj_dict)\n\n\n@MinimisationHandler.register_subclass('fit_weights')\nclass FitWeightMinimisationHandler(FixedWeightMinimisationHandler):\n    compatible_llh = [\"spatial\", \"fixed_energy\", \"standard\"]\n    compatible_negative_n_s = False\n\n    def __init__(self, mh_dict):\n        FixedWeightMinimisationHandler.__init__(self, mh_dict)\n\n        if self.negative_n_s:\n            raise ValueError(\n                \"Attempted to mix fitting weights with negative n_s.\")\n\n    def trial_function(self, full_dataset):\n\n        llh_functions = dict()\n        n_all = dict()\n\n        for name in self.seasons:\n            dataset = full_dataset[name]\n            llh_f = self.get_likelihood(name).create_llh_function(\n                dataset, self.get_angular_error_modifier(name),\n                self.make_season_weight\n            )\n            llh_functions[name] = llh_f\n            n_all[name] = len(dataset)\n\n        def f_final(params):\n\n            # Creates a matrix fixing the fraction of the total signal that\n            # is expected in each Source+Season pair. The matrix is\n            # normalised to 1, so that for a given total n_s, the expectation\n            # for the ith season for the jth source is given by:\n            #  n_exp = n_s * weight_matrix[i][j]\n\n            weights_matrix = self.make_weight_matrix(params)\n\n            for i, row in enumerate(weights_matrix.T):\n                if np.sum(row) > 0:\n                    row /= np.sum(row)\n\n            # Having created the weight matrix, loops over each season of\n            # data and evaluates the TS function for that season\n\n            ts_val = 0\n            for i, name in enumerate(self.seasons):\n                w = weights_matrix[i][:, np.newaxis]\n                ts_val += llh_functions[name](params, w)\n\n            return ts_val\n\n        return f_final\n\n    @staticmethod\n    def source_param_name(source):\n        return \"n_s ({0})\".format(source[\"source_name\"])\n\n    @staticmethod\n    def return_parameter_info(mh_dict):\n        sources = load_catalogue(mh_dict[\"catalogue\"])\n        p0 = [1. for _ in sources]\n        bounds = [(0., 1000.) for _ in sources]\n        names = [FitWeightMinimisationHandler.source_param_name(x)\n                 for x in sources]\n        params = [p0, bounds, names]\n\n        params = [\n            params[i] + x for i, x in enumerate(\n                LLH.get_parameters(mh_dict[\"llh_dict\"])\n            )\n        ]\n\n        return params[0], params[1], params[2]\n\n    def return_injected_parameters(self, scale):\n\n        inj_params = {}\n\n        for source in self.sources:\n            name = source[\"source_name\"]\n            key = self.source_param_name(source)\n            n_inj = 0\n            for season_name in self.seasons.keys():\n                try:\n                    names = [x[0] for x in self.get_injector(season_name).n_exp[\"source_name\"]]\n                    if isinstance(names[0], bytes):\n                        names = [x.decode() for x in names]\n\n                    if isinstance(name, bytes):\n                        name = name.decode()\n\n                    mask = np.array([x == name for x in names])\n\n                    n_inj += np.sum(self.get_injector(season_name).n_exp[\"n_exp\"][mask] * scale)\n\n                # If source not overlapping season, will not be in dict\n                except KeyError:\n                    pass\n\n            inj_params[key] = n_inj\n\n        inj_params.update(LLH.get_injected_parameters(self.mh_dict))\n\n        return inj_params\n\n\n@MinimisationHandler.register_subclass(\"flare\")\nclass FlareMinimisationHandler(FixedWeightMinimisationHandler):\n\n    compatible_llh = [\"spatial\", \"fixed_energy\", \"standard\"]\n    compatible_negative_n_s = False\n\n    def __init__(self, mh_dict):\n        MinimisationHandler.__init__(self, mh_dict)\n        # For each season, we create an independent likelihood, using the\n        # source list along with the sets of energy/time\n        # PDFs provided in llh_kwargs.\n        for name in self.seasons:\n\n            tpdf = self.get_likelihood(name).sig_time_pdf\n\n            # Check to ensure that no weird new untested time PDF is used\n            # with the flare search method, since uniform time PDFs over the\n            # duration of a given flare is an assumption baked into the PDF\n            # construction. New time PDFs could be added, but the Flare class\n            #  + LLH would need to be tested first and probably modified.\n\n            if np.sum([isinstance(tpdf, x) for x in [Box, Steady]]) == 0:\n                raise ValueError(\"Attempting to use a time PDF that is not a \"\n                                 \"Box or a Steady time PDF class. The flare \"\n                                 \"search method is only compatible with \"\n                                 \"time PDFs that are uniform over \"\n                                 \"fixed periods.\")\n\n    def run_trial(self, full_dataset):\n\n        datasets = dict()\n\n        livetime_calcs = dict()\n\n        time_dict = {\n            \"time_pdf_name\": \"custom_source_box\"\n        }\n\n        results = {\n            \"Parameters\": dict(),\n            \"Flag\": []\n        }\n\n        # Loop over each data season\n\n        for (name, season) in self.seasons.items():\n\n            # Generate a scrambled dataset, and save it to the datasets\n            # dictionary. Loads the llh for the season.\n\n            data = full_dataset[name]\n            llh = self.get_likelihood(name)\n\n            livetime_calcs[name] = TimePDF.create(time_dict, season.get_time_pdf())\n\n            # Loops over each source in catalogue\n\n            for source in self.sources:\n\n                # Identify spatially- and temporally-coincident data\n\n                mask = llh.select_spatially_coincident_data(data, [source])\n                spatial_coincident_data = data[mask]\n\n                t_mask = np.logical_and(\n                    np.greater(\n                        spatial_coincident_data[\"time\"],\n                        llh.sig_time_pdf.sig_t0(source)),\n                    np.less(\n                        spatial_coincident_data[\"time\"],\n                        llh.sig_time_pdf.sig_t1(source))\n                )\n\n                coincident_data = spatial_coincident_data[t_mask]\n\n                # If there are events in the window...\n\n                if len(coincident_data) > 0:\n\n                    # Creates empty dictionary to save info\n\n                    source_name = source[\"source_name\"]\n                    if source_name not in list(datasets.keys()):\n                        datasets[source_name] = dict()\n\n                    new_entry = {\n                        \"season_name\": season.season_name\n                    }\n                    new_entry[\"Coincident Data\"] = coincident_data\n                    new_entry[\"Start (MJD)\"] = llh.sig_time_pdf.t0\n                    new_entry[\"End (MJD)\"] = llh.sig_time_pdf.t1\n\n                    # Identify significant events (S/B > 1)\n\n                    significant = llh.find_significant_events(\n                        coincident_data, source)\n\n                    new_entry[\"Significant Times\"] = significant[\"time\"]\n\n                    new_entry[\"N_all\"] = len(data)\n\n                    datasets[source_name][name] = new_entry\n\n        stacked_ts = 0.0\n\n        # Minimisation of each source\n\n        for (source, source_dict) in datasets.items():\n\n            src = self.sources[self.sources[\"source_name\"] == source][0]\n            p0, bounds, names = self.source_fit_parameter_info(self.mh_dict,\n                                                               src)\n\n            # Create a full list of all significant times\n\n            all_times = []\n            n_tot = 0\n            for season_dict in source_dict.values():\n                new_times = season_dict[\"Significant Times\"]\n                all_times.extend(new_times)\n                n_tot += len(season_dict[\"Coincident Data\"])\n\n            all_times = np.array(sorted(all_times))\n\n            # Minimum flare duration (days)\n            min_flare = 0.25\n            # Conversion to seconds\n            min_flare *= 60 * 60 * 24\n\n            # Length of search window in livetime\n\n            search_window = np.sum([\n                self.get_likelihood(x).sig_time_pdf.effective_injection_time(src)\n                for x in self.seasons.keys()]\n            )\n\n            # If a maximum flare length is specified, sets that here\n\n            if \"max_flare\" in list(self.llh_dict[\"llh_sig_time_pdf\"].keys()):\n                # Maximum flare given in days, here converted to seconds\n                max_flare = self.llh_dict[\"llh_sig_time_pdf\"][\"max_flare\"] * (\n                        60 * 60 * 24\n                )\n            else:\n                max_flare = search_window\n\n            # Loop over all flares, and check which combinations have a\n            # flare length between the maximum and minimum values\n\n            pairs = []\n\n            # print \"There are\", len(all_times), \"significant neutrinos\",\n            # print \"out of\", n_tot, \"neutrinos\"\n\n            for x in all_times:\n                for y in all_times:\n                    if y > x:\n                        pairs.append((x, y))\n\n            # If there is are no pairs meeting this criteria, skip\n\n            if len(pairs) == 0:\n                logger.debug(\"Continuing because no pairs\")\n                continue\n\n            all_res = []\n            all_ts = []\n            all_f = []\n            all_pairs = []\n\n            # Loop over each possible significant neutrino pair\n\n            for i, pair in enumerate(pairs):\n                t_start = pair[0]\n                t_end = pair[1]\n\n                # Calculate the length of the neutrino flare in livetime\n\n                flare_time = np.array(\n                    (t_start, t_end),\n                    dtype=[\n                        (\"start_time_mjd\", np.float),\n                        (\"end_time_mjd\", np.float),\n                    ]\n                )\n\n                flare_length = np.sum([\n                    time_pdf.effective_injection_time(flare_time)\n                    for time_pdf in livetime_calcs.values()]\n                )\n\n                # If the flare is between the minimum and maximum length\n\n                if flare_length < min_flare:\n                    continue\n                elif flare_length > max_flare:\n                    continue\n\n\n                # Marginalisation term is length of flare in livetime\n                # divided by max flare length in livetime. Accounts\n                # for the additional short flares that can be fitted\n                # into a given window\n\n                overall_marginalisation = flare_length / max_flare\n\n                # Each flare is evaluated accounting for the\n                # background on the sky (the non-coincident\n                # data), which is given by the number of\n                # neutrinos on the sky during the given\n                # flare. (NOTE THAT IT IS NOT EQUAL TO THE\n                # NUMBER OF NEUTRINOS IN THE SKY OVER THE\n                # ENTIRE SEARCH WINDOW)\n\n                n_all = np.sum([np.sum(~np.logical_or(\n                    np.less(data[\"time\"], t_start),\n                    np.greater(data[\"time\"], t_end)))\n                                for data in full_dataset.values()])\n\n                llhs = dict()\n\n                # Loop over data seasons\n\n                for (name, season_dict) in sorted(source_dict.items()):\n\n                    llh = self.get_likelihood(name)\n\n                    # Check that flare overlaps with season\n\n                    inj_time = llh.sig_time_pdf.effective_injection_time(\n                        flare_time\n                    )\n\n                    if not inj_time > 0:\n                        continue\n\n                    coincident_data = season_dict[\"Coincident Data\"]\n\n                    data = full_dataset[name]\n\n                    n_season = np.sum(~np.logical_or(\n                        np.less(data[\"time\"], t_start),\n                        np.greater(data[\"time\"], t_end)))\n\n                    # Removes non-coincident data\n\n                    flare_veto = np.logical_or(\n                        np.less(coincident_data[\"time\"], t_start),\n                        np.greater(coincident_data[\"time\"], t_end)\n                    )\n\n                    # Checks to make sure that there are\n                    # neutrinos in the sky at all. There should\n                    # be, due to the definition of the flare window.\n\n                    if n_all > 0:\n                        pass\n                    else:\n                        raise Exception(\"Events are leaking somehow!\")\n\n                    # Creates the likelihood function for the flare\n\n                    flare_f = llh.create_flare_llh_function(\n                        coincident_data, flare_veto, n_all, src, n_season,\n                        self.get_angular_error_modifier(season_dict[\"season_name\"])\n                    )\n\n                    llhs[season_dict[\"season_name\"]] = {\n                        \"f\": flare_f,\n                        \"flare length\": flare_length\n                    }\n\n                # From here, we have normal minimisation behaviour\n\n                def f_final(params):\n\n                    # Marginalisation is done once, not per-season\n\n                    ts = 2 * np.log(overall_marginalisation)\n\n                    for llh_dict in llhs.values():\n                        ts += llh_dict[\"f\"](params)\n\n                    return -ts\n\n                res = scipy.optimize.fmin_l_bfgs_b(\n                    f_final, p0, bounds=bounds,\n                    approx_grad=True)\n\n                all_res.append(res)\n                all_ts.append(-res[1])\n                all_f.append(f_final)\n                all_pairs.append(pair)\n\n            max_ts = max(all_ts)\n            stacked_ts += max_ts\n            index = all_ts.index(max_ts)\n\n            best_start = all_pairs[index][0]\n            best_end = all_pairs[index][1]\n\n            best_time = np.array(\n                (best_start, best_end),\n                dtype=[\n                    (\"start_time_mjd\", np.float),\n                    (\"end_time_mjd\", np.float),\n                ]\n            )\n\n            best_length = np.sum([\n                time_pdf.effective_injection_time(best_time)\n                for time_pdf in livetime_calcs.values()]\n            ) / (60 * 60 * 24)\n\n            best = [x for x in all_res[index][0]] + [\n                best_start, best_end, best_length\n            ]\n\n            p0, bounds, names = self.source_parameter_info(self.mh_dict, src)\n\n            names += [self.source_param_name(x, src)\n                      for x in [\"t_start\", \"t_end\", \"length\"]]\n\n            for i, x in enumerate(best):\n                key = names[i]\n                results[\"Parameters\"][key] = x\n\n            results[\"Flag\"] += [all_res[index][2][\"warnflag\"]]\n\n            del all_res, all_f, all_times\n\n        results[\"TS\"] = stacked_ts\n\n        del datasets, full_dataset, livetime_calcs\n\n        return results\n\n    @staticmethod\n    def source_param_name(param, source):\n        return param + \" (\" + str(source[\"source_name\"]) + \")\"\n\n\n    @staticmethod\n    def source_fit_parameter_info(mh_dict, source):\n\n        p0 = [1.]\n        bounds = [(0., 1000.)]\n        names = [FlareMinimisationHandler.source_param_name(\"n_s\", source)]\n\n        llh_p0, llh_bounds, llh_names = LLH.get_parameters(\n            mh_dict[\"llh_dict\"])\n\n        p0 += llh_p0\n        bounds += llh_bounds\n        names += [FlareMinimisationHandler.source_param_name(x, source)\n                  for x in llh_names]\n\n        return p0, bounds, names\n\n    @staticmethod\n    def source_parameter_info(mh_dict, source):\n\n        p0, bounds, names = \\\n            FlareMinimisationHandler.source_fit_parameter_info(\n                mh_dict, source\n            )\n\n        p0 += [np.nan for _ in range(3)]\n        bounds += [(np.nan, np.nan)for _ in range(3)]\n        names += [FlareMinimisationHandler.source_param_name(x, source)\n                  for x in [\"t_start\", \"t_end\", \"length\"]]\n\n        return p0, bounds, names\n\n    @staticmethod\n    def return_parameter_info(mh_dict):\n        p0, bounds, names = [], [], []\n        sources = load_catalogue(mh_dict[\"catalogue\"])\n        for source in sources:\n            res = FlareMinimisationHandler.source_parameter_info(\n                mh_dict, source\n            )\n\n            for i, x in enumerate(res):\n                [p0, bounds, names][i] += x\n\n        return p0, bounds, names\n\n    def return_injected_parameters(self, scale):\n\n        inj_params = {}\n\n        for source in self.sources:\n            name = source[\"source_name\"]\n            key = self.source_param_name(\"n_s\", source)\n            n_inj = 0\n\n            for season_name in self.seasons.keys():\n\n                try:\n\n                    names = [x[0] for x in self.get_injector(season_name).n_exp[\"source_name\"]]\n\n                    if isinstance(names[0], bytes):\n                        names = [x.decode() for x in names]\n\n                    if isinstance(name, bytes):\n                        name = name.decode()\n\n                    mask = np.array([x == name for x in names])\n\n                    n_inj += np.sum(self.get_injector(season_name).n_exp[\"n_exp\"][mask] * scale)\n\n                # If source not overlapping season, will not be in dict\n                except KeyError:\n                    pass\n\n            inj_params[key] = n_inj\n\n            ts = min([self.get_injector(season_name).sig_time_pdf.sig_t0(source)\n                      for season_name in self.seasons.keys()])\n            te = max([self.get_injector(season_name).sig_time_pdf.sig_t1(source)\n                      for season_name in self.seasons.keys()])\n\n            inj_params[self.source_param_name(\"length\", source)] = te - ts\n\n            if self.time_smear:\n                inj_params[self.source_param_name(\"t_start\", source)] = np.nan\n                inj_params[self.source_param_name(\"t_end\", source)] = np.nan\n            else:\n                inj_params[self.source_param_name(\"t_start\", source)] = ts\n                inj_params[self.source_param_name(\"t_end\", source)] = te\n\n            for (key, val) in LLH.get_injected_parameters(\n                    self.mh_dict).items():\n                inj_params[self.source_param_name(key, source)] = val\n\n        return inj_params\n\n    def add_likelihood(self, season):\n        return generate_dynamic_flare_class(season, self.sources, self.llh_dict)\n\nif __name__ == '__main__':\n    from multiprocessing import Pool\n\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"-f\", \"--file\", help=\"Path for analysis pkl_file\")\n    parser.add_argument(\"-n\", \"--n_cpu\", default=2)\n    cfg = parser.parse_args()\n\n    with open(cfg.file, \"rb\") as f:\n        mh_dict = Pickle.load(f)\n\n    mh = MinimisationHandler.create(mh_dict)\n\n    scales, seeds = mh.trial_params(mh_dict[\"scale\"], n_steps=mh_dict[\"n_steps\"])\n\n    if \"fixed_scale\" in list(mh_dict.keys()):\n        scale = [mh_dict[\"fixed_scale\"] for _ in seeds]\n        n_trials = int(float(mh_dict[\"n_trials\"]) / float(cfg.n_cpu))\n    else:\n        n_trials = int(mh_dict[\"n_trials\"])\n\n    trials = [mh_dict[\"n_trials\"] for _ in seeds]\n    loop_args = zip(trials, scales, seeds)\n\n    logger.info(\"N CPUs:{0}\".format(cfg.n_cpu))\n\n    with Pool(int(cfg.n_cpu)) as p:\n        p.starmap(mh.run, loop_args)\n", "meta": {"hexsha": "b22f67ea98f9187de8cbbe9ecf774c78242ace39", "size": 53628, "ext": "py", "lang": "Python", "max_stars_repo_path": "flarestack/core/minimisation.py", "max_stars_repo_name": "Raimer/flarestack", "max_stars_repo_head_hexsha": "60659d368db93ead7b53addf3af9f1e8ac3a52bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-19T06:26:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-19T06:26:03.000Z", "max_issues_repo_path": "flarestack/core/minimisation.py", "max_issues_repo_name": "Raimer/flarestack", "max_issues_repo_head_hexsha": "60659d368db93ead7b53addf3af9f1e8ac3a52bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "flarestack/core/minimisation.py", "max_forks_repo_name": "Raimer/flarestack", "max_forks_repo_head_hexsha": "60659d368db93ead7b53addf3af9f1e8ac3a52bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7799511002, "max_line_length": 111, "alphanum_fraction": 0.5489110166, "include": true, "reason": "import numpy,import scipy", "num_tokens": 11797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.1946023114101248}}
{"text": "import os\nfrom functools import lru_cache\nimport warnings\nimport numpy as np\nfrom astropy.utils.data import download_file\nfrom astropy.io.votable import parse,exceptions\nimport astropy.units as u\nfrom . import spectrum\nfrom . import filter_info\nfrom . import utils\nfrom . import config as cfg\n\n# ignore warnings about SVO filter votables\nwarnings.simplefilter('ignore', exceptions.W42)\n\nc_micron = u.micron.to(u.Hz,equivalencies=u.spectral())\n\ndef common_x(x1,y1,x2,y2):\n    \"\"\"Interpolate two y arrays to a single common x array\"\"\"\n    if len(x1) == len(x2):\n        if np.all( np.equal(x1,x2) ):\n            _,srt = np.unique(x1,return_index=True)\n            return (x1[srt],y1[srt],y2[srt])\n    xall = np.append(x1,x2)\n    xmin = np.max([np.min(x1),np.min(x2)])\n    xmax = np.min([np.max(x1),np.max(x2)])\n    keep = (xall >= xmin) & ( xall <= xmax)\n    if np.any(keep) == False:\n        raise utils.SdfError(\"x arrays don't overlap {} to {} and {} to {}\".format(\n                         np.min(x1),np.max(x1),np.min(x2),np.max(x2)))\n    x = np.unique( xall[keep] )\n    srt = np.argsort(x1)\n    y1 = np.interp(x,x1[srt],y1[srt])\n    srt = np.argsort(x2)\n    y2 = np.interp(x,x2[srt],y2[srt])\n    return (x,y1,y2)\n    \n\nclass Filter(object):\n    \"\"\"Filter class to use for synthetic photometry\n\n    A good primer on filter responses is Appendix A 2012PASP..124..140B.\n    The key point is that photon-counting is equivalent to \n    energy-integration (A13), so synthetic photometry can always be done\n    with the same equation if the filter responses are changed \n    accordingly. A quantum-efficiency-based response is S, and \n    S'=lambda.S is the energy-integrating equivalent, which can be\n    integrated directly (F_lambda.S'.dlambda, A11). For 2MASS \n    multiplication by lambda was done already (2003AJ....126.1090C), but\n    this is not always the case so must be checked for each filter, and\n    photon-counting responses converted to energy-integrating.\n\n    We also need to know the reference spectrum to do synthetic \n    photometry in systems where the flux density is given at a specific\n    (e.g. mean) wavelength. This is commonly the case for IR photometry,\n    but not in the optical (e.g. see appendix of 2011AJ....141..173B).\n    It is also good to know how that reference wavelength was derived,\n    but it can also be taken as a number. This correction converts the\n    measurement (also the value that the reference spectrum would have\n    at this wavelength) to the value the true spectrum must have at this\n    wavelength in order to reproduce the observed signal. The most\n    common reference spectrum is nu.F_nu=const, but others are also used\n    (e.g. 10,000K blackbody for MIPS).\n    \n    Filter information comes from the filter_info.py file, all filters,\n    colours, indices etc. need to be named as keys to the filters \n    dictionary that comes from compiliing that file, otherwise they will\n    not be computed in the models.\n    \n    A zero point offset of zero is set by default.\n    \n    \"\"\"\n\n    # this needs to return all desired filters, colours, and indices\n    all = list(filter_info.filters.keys())\n    \n    def __init__(self,name=None,system=None,nu_hz=None,fileloc=None,\n                 response=None,response_type=None,\n                 zero_point=None,zero_point_offset=None,\n                 measurement_calibration=None,\n                 magnitude_system=None,ref_wavelength=None,ref_nu_hz=None,\n                 ref_spectrum=None,cc_denom=None,Af_Av=None):\n        self.name = name\n        self.nu_hz = nu_hz\n        self.response = response\n        self.response_type = response_type\n        self.magnitude_system = magnitude_system\n        self.zero_point = zero_point\n        self.zero_point_offset = zero_point_offset\n        self.measurement_calibration = measurement_calibration\n        self.ref_wavelength = ref_wavelength\n        self.ref_nu_hz = ref_nu_hz\n        self.ref_spectrum = ref_spectrum\n        self.cc_denom = cc_denom\n        self.Af_Av = Af_Av\n\n\n    @classmethod\n    def svo_get(cls,name):\n        \"\"\"Get response and details for a filter from Spanish VO\n            \n        Other properties still need to be set \"by hand\", as this\n        service doesn't provide either the reference spectrum or\n        wavelength. It doesn't appear that their detector type is\n        anything other than energy counting, so any conversion\n        between the response the and \"RSR\" [lambda.R(lambda)] also\n        needs to be figured out manually. All this is done in\n        filter_info.py\n        \"\"\"\n        \n        self = cls()\n        \n        # try loading from xml file in filter directory\n        # remove '/' from SVO names\n        self.fileloc = os.path.dirname(os.path.abspath(__file__))+ \\\n                              '/data/filters/'+name.replace('/','.')+'.xml'\n        if os.path.exists(self.fileloc):\n            votable = parse(self.fileloc)\n        else:\n\n            # get the filter, either from url or cache, if we want something\n            # other than Vega use the PhotCalID in the name given\n            if 'PhotCalID' in name:\n                url = \"http://svo2.cab.inta-csic.es/theory/fps3/fps.php?\"+name\n            else:\n                url = \"http://svo2.cab.inta-csic.es/theory/fps3/fps.php?ID=\"+name\n            loc = download_file(url,cache=True)\n            \n            # open the file and save to filters folder for posterity\n            votable = parse(loc)\n            votable.to_xml(self.fileloc)\n        \n        # grab the filter name\n        name_field = votable.get_field_by_id('filterID')\n        if isinstance(name_field.value, bytes):\n            self.name = name_field.value.decode()\n        else:\n            self.name = name_field.value\n        \n        # mean wavelength\n        wmean = votable.get_field_by_id('WavelengthMean')\n        self.ref_wavelength = wmean.value * wmean.unit\n        \n        # zero point in Jy, and offset in mag\n        zp = votable.get_field_by_id('ZeroPoint')\n        self.zero_point = (zp.value * zp.unit).to('Jy').value\n        self.zero_point_offset = 0.0\n        \n        # magnitude system\n        sys = votable.get_field_by_id('MagSys')\n        if isinstance(sys.value, bytes):\n            self.magnitude_system = sys.value.decode()\n        else:\n            self.magnitude_system = sys.value\n        \n        # and the response, assuming there is no masking [hence filled()]\n        vo_filt_table = votable.get_first_table()\n        filt_table = vo_filt_table.to_table().filled()\n        wav = filt_table['Wavelength']\n        self.nu_hz = np.array( wav.to('Hz',equivalencies=u.spectral()) )\n        self.response = np.array( filt_table['Transmission'] )\n        return self\n\n\n    @lru_cache(maxsize=128)\n    def get_memo(name):\n        \"\"\"Get response and details for a filter (via filter_info.py)\n            \n        This function is memoized for speed, the maxsize just needs\n        to be larger than the number of filters.\n        \"\"\"\n\n        f = filter_info.filters\n\n        # create (relatively narrow) generic filters\n        if name[0:3] == 'WAV':\n            self = Filter()\n            self.name = name\n            self.response_type = 'energy'\n            cwav = float(name[3:])\n            wave = np.arange( cwav*0.95, cwav*1.05, cwav/100. )\n            self.nu_hz = c_micron / wave\n            self.response = np.ones( len(wave) )\n        elif name not in f:\n            raise KeyError(\"Filter {} not in filter_info\".format(name))\n        else:\n            if 'svo_name' in f[name]:\n                self = Filter.svo_get(f[name]['svo_name'])\n            else:\n                self = Filter()\n                if f[name]['wav_micron'] is not None:\n                    self.nu_hz = c_micron / np.array(f[name]['wav_micron'])\n                if f[name]['response'] is not None:\n                    self.response = np.array(f[name]['response'])\n\n            self.name = name\n        \n            # fill fields from filter_info, these override SVO\n            if 'magnitude_system' in f[name]:\n                if f[name]['magnitude_system'] is not None:\n                    self.magnitude_system = f[name]['magnitude_system']\n            if 'zero_point' in f[name]:\n                if f[name]['zero_point'] is not None:\n                    self.zero_point = f[name]['zero_point']\n            if 'zero_point_offset' in f[name]:\n                if f[name]['zero_point_offset'] is not None:\n                    self.zero_point_offset = f[name]['zero_point_offset']\n            if 'measurement_calibration' in f[name]:\n                if f[name]['measurement_calibration'] is not None:\n                    self.measurement_calibration = f[name]['measurement_calibration']\n            if 'ref_wavelength' in f[name]:\n                if f[name]['ref_wavelength'] is not None:\n                    self.ref_wavelength = f[name]['ref_wavelength']\n            if 'ref_spectrum' in f[name]:\n                if f[name]['ref_spectrum'] is not None:\n                    self.ref_spectrum = f[name]['ref_spectrum']\n            if 'response_type' in f[name]:\n                if f[name]['response_type'] is not None:\n                    self.response_type = f[name]['response_type']\n            \n        # convert photon counting responses to energy\n        if 'photon' in self.response_type:\n            if self.nu_hz is not None and self.response is not None:\n                self.response /= self.nu_hz\n                self.response_type = 'photon -> energy'\n\n        # sort, normalise, and fill\n        if self.nu_hz is not None:\n            self.sort()\n            self.normalise_response()\n            self.fill_mean_wavelength()\n            self.fill_ref_nu_hz()\n            self.fill_cc_denom()\n        \n        # compute zero-point in Vega system\n        if self.magnitude_system == 'Vega':\n            v = spectrum.ObsSpectrum.vega_stis()\n            if (np.min(v.nu_hz) < np.min(self.nu_hz) and\n                np.max(v.nu_hz) > np.min(self.nu_hz)):\n                zp = self.synthphot(v)\n                self.zero_point = zp[0]\n            else:\n                self.zero_point = None\n\n        # or for AB\n        elif self.magnitude_system == 'AB':\n            self.zero_point = 3631.0\n\n        return self\n\n\n    def get_with_zpo(name,zpo_file='/Users/grant/astro/projects/sdf/sdf/calibration/zpos.txt'):\n        \"\"\"Get filter, using ZPO from file.\"\"\"\n        \n        f = Filter.get_memo(name)\n        t = np.genfromtxt(zpo_file,dtype=None)\n        fs = np.array([filt.decode() for filt in t[0]])\n        if name in fs:\n            f.zero_point_offset = float( t[1][ fs == name ][0] )\n\n        return f\n    \n    \n    # decide what get() points to\n    get = get_memo\n    \n\n    def mag2flux(self,mag):\n        \"\"\"Convert magnitudes to flux density.\n\n        Use zero point associated with this filter to convert a given\n        magnitude to flux density. Units returned are those associated\n        with the zero point.\n        \"\"\"\n\n        if self.zero_point is None or self.zero_point_offset is None:\n            raise utils.SdfError(\"no zero point or offset for filter {})\".\n                           format(self.name))\n        return self.zero_point * 10**(-0.4*(mag-self.zero_point_offset))\n    \n    \n    def flux2mag(self,flux):\n        \"\"\"Convert flux density to magnitudes.\n            \n        Use zero point associated with this filter to convert a given\n        flux density to magnitude. Units returned are those associated\n        with the zero point.\n        \"\"\"\n        \n        if self.zero_point is None or self.zero_point_offset is None:\n            raise utils.SdfError(\"no zero point or offset for filter {})\".\\\n                           format(self.name))\n        return self.zero_point_offset                               \\\n               - 2.5 * np.log10( flux / self.zero_point )\n\n\n    def measflux2flux(self,flux):\n        \"\"\"Convert a measured flux to an actual flux.\n        \n        Use flux calibration function given for this filter.\n        \"\"\"\n\n        if self.measurement_calibration is not None:\n            return self.measurement_calibration(flux)\n        else:\n            return flux\n\n\n    def sort(self):\n        \"\"\"Sort response in increasing order of frequency.\"\"\"\n        \n        _,srt = np.unique(self.nu_hz,return_index=True)\n        self.nu_hz = self.nu_hz[srt]\n        self.response = self.response[srt]\n\n\n    def normalise_response(self):\n        \"\"\"Normalise filter response so integral is one.\"\"\"\n        \n        norm = utils.sdf_int(self.response,self.nu_hz)\n        self.response /= norm\n\n    def actual_flux(self,spectrum):\n        \"\"\"Return the spectrum's flux at the reference wavelength.\n            \n        Interpolate in log space.\n        \"\"\"\n        \n        spectrum.sort('nu')\n        if hasattr(spectrum,'fnujy'):\n            log_fnu = np.log10(spectrum.fnujy)\n        elif hasattr(spectrum,'fnujy_sr'):\n            log_fnu = np.log10(spectrum.fnujy_sr)\n        \n        log_nu = np.log10(spectrum.nu_hz)\n        log_ref_fnu = np.interp(np.log10(self.ref_nu_hz),log_nu,log_fnu)\n        return np.power(10,log_ref_fnu)\n\n\n    def fill_ref_nu_hz(self):\n        \"\"\"Set the reference frequency of the filter.\"\"\"\n        \n        if self.ref_wavelength is not None:\n            self.ref_nu_hz = c_micron / self.ref_wavelength\n\n\n    def fill_mean_wavelength(self):\n        \"\"\"Set the mean wavelength of the filter.\"\"\"\n        \n        wave = c_micron / self.nu_hz\n        self.mean_wavelength = utils.sdf_int(self.response,wave)            \\\n                               / utils.sdf_int(self.response/wave,wave)\n\n\n    def pivot_wavelength(self):\n        \"\"\"Return the pivot wavelength.\n            \n        See Bessell & Murphy (2012) for definition. This wavelength is a\n        property of the filter only, and results in exact conversion\n        between mean F_lambda and mean F_nu.\n        \"\"\"\n    \n        wave = c_micron / self.nu_hz\n        fp = utils.sdf_int( self.response, wave )                           \\\n             / utils.sdf_int( self.response / wave / wave, wave )\n        return np.sqrt(fp)\n\n\n    def fill_cc_denom(self):\n        \"\"\"Compute the denominator of the colour correction\n        \n        This calculation is specific to the filter response (i.e. \n        independent of observed spectrum) so only needs to be calculated\n        once. See synthphot for details.\n        \"\"\"\n\n        if self.ref_spectrum is not None:\n            d = utils.sdf_int(self.response * self.ref_spectrum(self.nu_hz),\n                              self.nu_hz)\n            self.cc_denom = d / self.ref_spectrum(self.ref_nu_hz)\n\n\n    def synthphot(self,spectrum):\n        \"\"\"Synthetic photometry of supplied spectrum object\n\n        In the IR we have f_nu(quoted) (i.e. catalogue value) is:\n\n        f_nu(quoted) = f_nu(lam_eff) K\n\n        where the colour correction K is:\n\n        K =        1        S_nu(lam_eff)   int( f_nu R dnu )\n            ------------- -----------------\n            f_nu(lam_eff) int( S_nu R dnu )\n\n        For a correctly normalised bandpass R (energy counting), the\n        integral in the numerator is \"normal\" synthetic photoemtry as\n        done in the optical (e.g. appendix of 2011AJ....141..173B).\n\n        Method is to separate the terms in synthetic photometry so that\n        it can be done with a single set of equations. Separation is \n        into\n          1 the \"normal\" integration as done for the optical\n          2 the spectrum-independent part of the colour correction \n            (second term, which can be pre-computed)\n        The latter is only done if necessary. f_nu(lam_eff) cancels so\n        isn't needed to get f_nu(quoted), but is needed if we want to\n        know what the colour correction was.\n        \n        Returns a tuple of (quoted flux, colour correction), where the\n        colour correction will be None if there isn't one (i.e. no ref\n        spectrum).\n        \n        For colours and indices the call needs to be done using the\n        synthphot method for Spectrum objects.\n        \n        \"\"\"\n\n        if hasattr(spectrum,'fnujy'):\n            fnu = spectrum.fnujy\n        elif hasattr(spectrum,'fnujy_sr'):\n            fnu = spectrum.fnujy_sr\n        x,y1,y2 = common_x(self.nu_hz,self.response,spectrum.nu_hz,fnu)\n\n        # this is the basic synthetic photometry\n        cc_num = utils.sdf_int(y1 * y2, x)\n        \n        # if no reference spectrum we just return the integral because\n        # we normalised the bandpass when it was loaded\n        if self.ref_spectrum is None:\n            return (cc_num,None)\n        else:\n            fnu_eff = self.actual_flux(spectrum)\n            cc = cc_num / self.cc_denom / fnu_eff\n            return (cc*fnu_eff,cc)\n\n\n    @property\n    def name(self):\n        return self._name\n    @name.setter\n    def name(self, value):\n        self._name = utils.validate_string(value)\n\n    @property\n    def magnitude_system(self):\n        return self._magnitude_system\n    @magnitude_system.setter\n    def magnitude_system(self, value):\n        self._magnitude_system = utils.validate_string(value)\n        \n    @property\n    def zero_point(self):\n        return self._zero_point\n    @zero_point.setter\n    def zero_point(self, value):\n        self._zero_point = utils.validate_float(value)\n\n    @property\n    def zero_point_offset(self):\n        return self._zero_point_offset\n    @zero_point_offset.setter\n    def zero_point_offset(self, value):\n        self._zero_point_offset = utils.validate_float(value)\n    \n    @property\n    def measurement_calibration(self):\n        return self._measurement_calibration\n    @measurement_calibration.setter\n    def measurement_calibration(self, value):\n        self._measurement_calibration = utils.validate_function(value)\n\n    @property\n    def ref_spectrum(self):\n        return self._ref_spectrum\n    @ref_spectrum.setter\n    def ref_spectrum(self, value):\n        self._ref_spectrum = utils.validate_function(value)\n\n    @property\n    def response_type(self):\n        return self._response_type\n    @response_type.setter\n    def response_type(self, value):\n        self._response_type = utils.validate_string(value)\n\n    @property\n    def nu_hz(self):\n        return self._nu_hz\n    @nu_hz.setter\n    def nu_hz(self, value):\n        self._nu_hz = utils.validate_1d(value,None)\n\n    @property\n    def response(self):\n        return self._response\n    @response.setter\n    def response(self,value):\n        # always set nu_hz first, so no check for attribute nu_hz\n        if self.nu_hz is None:\n                expected_len = None\n        else:\n                expected_len = len(self.nu_hz)\n        self._response = utils.validate_1d(value,expected_len)\n\n\ndef mean_wavelength(filternames):\n    \"\"\"Return mean_wavelengths given tuple/list of filter names.\"\"\"\n    \n    wav = np.array([])\n    for f in filternames:\n        if iscolour(f):\n            col = Colour.get(f)\n            wav = np.append(wav,col.mean_wavelength)\n        else:\n            filt = Filter.get(f)\n            wav = np.append(wav,filt.mean_wavelength)\n    return wav\n\n\nclass Colour(object):\n    \"\"\"Class for colours/indices, largely for convenience.\"\"\"\n\n    def __init__(self,name=None,filters=None,weights=None,\n                 mean_wavelength=None):\n        self.name = name\n        self.filters = filters\n        self.weights = weights\n        self.mean_wavelength = mean_wavelength\n\n\n    @classmethod\n    def get(cls,name):\n        \"\"\"Get a Colour object given a name.\"\"\"\n    \n        if not iscolour(name):\n            raise utils.SdfError(\"name given ({}) not a colour\".format(name))\n\n        self = cls()\n        self.name = name\n        self.fill_info()\n        return self\n        \n        \n    def fill_info(self):\n        \"\"\"Set filters, weights, and other info for this colour.\"\"\"\n\n        # colour\n        if '_' in self.name:\n            self.filters = np.array(self.name.split('_'),dtype=str)\n            self.weights = np.array([1.,-1],dtype=float)\n                \n        # Stromgren M1, (v-b)-(b-y) or (v - 2b + y)\n        elif self.name == 'STROMM1':\n            self.filters = np.array(['VS','BS','YS'],dtype=str)\n            self.weights = np.array([1.,-2.,1.],dtype=float)\n\n        # Stromgren C1, (u-v)-(v-b) or (u - 2v + b)\n        elif self.name == 'STROMC1':\n            self.filters = np.array(['US','VS','BS'],dtype=str)\n            self.weights = np.array([1.,-2.,1.],dtype=float)\n\n        meanw = np.array([])\n        for f in self.filters:\n            filt = Filter.get(f)\n            meanw = np.append(meanw,filt.mean_wavelength)\n        self.mean_wavelength = np.mean(meanw)\n\n\n@lru_cache(maxsize=128)\ndef iscolour(filter):\n    \"\"\"Return True if the given filter name is a colour\n        \n    In practise this means either the name has a '_' in it,\n    e.g. BS_YS, indicating BS-YS, or that it's one of the\n    Stromgren indices M1 or C1.\n    \n    If passed an array, list, or tuple, then return a list of\n    booleans.\n    \"\"\"\n    \n    if isinstance(filter,(tuple,list,np.ndarray)):\n        iscol = np.array([],dtype=bool)\n        for f in filter:\n            iscol = np.append(iscol,iscolour(f))\n        return iscol\n    else:\n        if '_' in filter:\n            fs = filter.split('_')\n            if len(fs) != 2:\n                raise utils.SdfError(\"filter name {} \"\n                               \"has too many '_'s\".format(filter))\n            if fs[0] == fs[1]:\n                raise utils.SdfError(\"filters in colour {} \"\n                               \" are the same\".format(filter))\n            return True\n        elif filter == 'STROMM1':\n            return True\n        elif filter == 'STROMC1':\n            return True\n        else:\n            return False\n", "meta": {"hexsha": "8cda0c5554d5925ce2a92a5170142095aa7ab07d", "size": 21772, "ext": "py", "lang": "Python", "max_stars_repo_path": "sdf/filter.py", "max_stars_repo_name": "drgmk/sdf", "max_stars_repo_head_hexsha": "a44e66a82f876dda079686b32c767370276c38a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-01T15:55:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-01T15:55:16.000Z", "max_issues_repo_path": "sdf/filter.py", "max_issues_repo_name": "drgmk/sdf", "max_issues_repo_head_hexsha": "a44e66a82f876dda079686b32c767370276c38a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-03-28T19:18:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-21T08:17:45.000Z", "max_forks_repo_path": "sdf/filter.py", "max_forks_repo_name": "drgmk/sdf", "max_forks_repo_head_hexsha": "a44e66a82f876dda079686b32c767370276c38a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-13T19:39:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-13T19:39:15.000Z", "avg_line_length": 36.1061359867, "max_line_length": 95, "alphanum_fraction": 0.5959948558, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 5037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.19460231141012477}}
{"text": "\n# This code is based on: https://github.com/nutonomy/second.pytorch.git\n# \n# MIT License\n# Copyright (c) 2018 \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport numpy as np\nfrom second.core import box_np_ops\n\n\nclass AnchorGeneratorStride:\n    def __init__(self,\n                 sizes=[1.6, 3.9, 1.56],\n                 anchor_strides=[0.4, 0.4, 1.0],\n                 anchor_offsets=[0.2, -39.8, -1.78],\n                 rotations=[0, np.pi / 2],\n                 class_id=None,\n                 match_threshold=-1,\n                 unmatch_threshold=-1,\n                 dtype=np.float32):\n        self._sizes = sizes\n        self._anchor_strides = anchor_strides\n        self._anchor_offsets = anchor_offsets\n        self._rotations = rotations\n        self._dtype = dtype\n        self._class_id = class_id\n        self._match_threshold = match_threshold\n        self._unmatch_threshold = unmatch_threshold\n\n    @property\n    def class_id(self):\n        return self._class_id\n\n    @property\n    def match_threshold(self):\n        return self._match_threshold\n\n    @property\n    def unmatch_threshold(self):\n        return self._unmatch_threshold\n\n    @property\n    def num_anchors_per_localization(self):\n        num_rot = len(self._rotations)\n        num_size = np.array(self._sizes).reshape([-1, 3]).shape[0]\n        return num_rot * num_size\n\n    def generate(self, feature_map_size):\n        return box_np_ops.create_anchors_3d_stride(\n            feature_map_size, self._sizes, self._anchor_strides,\n            self._anchor_offsets, self._rotations, self._dtype)\n\nclass AnchorGeneratorRange:\n    def __init__(self,\n                 anchor_ranges,\n                 sizes=[1.6, 3.9, 1.56],\n                 rotations=[0, np.pi / 2],\n                 class_id=None,\n                 match_threshold=-1,\n                 unmatch_threshold=-1,\n                 dtype=np.float32):\n        self._sizes = sizes\n        self._anchor_ranges = anchor_ranges\n        self._rotations = rotations\n        self._dtype = dtype\n        self._class_id = class_id\n        self._match_threshold = match_threshold\n        self._unmatch_threshold = unmatch_threshold\n\n    @property\n    def class_id(self):\n        return self._class_id\n\n    @property\n    def match_threshold(self):\n        return self._match_threshold\n\n    @property\n    def unmatch_threshold(self):\n        return self._unmatch_threshold\n\n    @property\n    def num_anchors_per_localization(self):\n        num_rot = len(self._rotations)\n        num_size = np.array(self._sizes).reshape([-1, 3]).shape[0]\n        return num_rot * num_size\n\n    def generate(self, feature_map_size):\n        return box_np_ops.create_anchors_3d_range(\n            feature_map_size, self._anchor_ranges, self._sizes,\n            self._rotations, self._dtype)\n", "meta": {"hexsha": "dc5b17f03752cac925c3a6560cb85d304d25caa8", "size": 3802, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/AI-Model-Zoo/VAI-1.3-Model-Zoo-Code/PyTorch/pt_pointpillars_kitti_12000_100_10.8G_1.3/code/train/second/core/anchor_generator.py", "max_stars_repo_name": "guochunhe/Vitis-AI", "max_stars_repo_head_hexsha": "e86b6efae11f8703ee647e4a99004dc980b84989", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-18T14:49:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-18T14:49:19.000Z", "max_issues_repo_path": "models/AI-Model-Zoo/VAI-1.3-Model-Zoo-Code/PyTorch/pt_pointpillars_kitti_12000_100_10.8G_1.3/code/train/second/core/anchor_generator.py", "max_issues_repo_name": "guochunhe/Vitis-AI", "max_issues_repo_head_hexsha": "e86b6efae11f8703ee647e4a99004dc980b84989", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/AI-Model-Zoo/VAI-1.3-Model-Zoo-Code/PyTorch/pt_pointpillars_kitti_12000_100_10.8G_1.3/code/train/second/core/anchor_generator.py", "max_forks_repo_name": "guochunhe/Vitis-AI", "max_forks_repo_head_hexsha": "e86b6efae11f8703ee647e4a99004dc980b84989", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5327102804, "max_line_length": 80, "alphanum_fraction": 0.6633350868, "include": true, "reason": "import numpy", "num_tokens": 876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.19460231141012477}}
{"text": "#!/usr/bin/env python3\n# coding: utf-8\n\n#libraries\nimport keras\nimport tensorflow as tf\nfrom keras import backend as K\nimport cv2\nimport os\nimport numpy as np\nfrom keras.optimizers import Adam\nfrom keras.models import model_from_json, load_model\nfrom keras.layers import Input, Dense\nfrom keras.models import Model,Sequential\nfrom sklearn.model_selection import train_test_split\nfrom keras.layers import Convolution2D as Conv2D\nfrom keras.layers.convolutional import Deconv2D as Conv2DTranspose\nfrom keras.layers import Lambda, Input, Dense, MaxPooling2D, BatchNormalization,Input\nfrom keras.layers import UpSampling2D, Dropout, Flatten, Reshape, RepeatVector, LeakyReLU,Activation\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.losses import mse, binary_crossentropy\nfrom keras.callbacks import EarlyStopping\nkeras.callbacks.TerminateOnNaN()\nseed = 7\nnp.random.seed(seed)\nfrom keras.callbacks import CSVLogger\nfrom keras.callbacks import Callback, LearningRateScheduler\n\n# config = tf.ConfigProto( device_count = {'GPU': 1 , 'GPU': 2} )\n# sess = tf.Session(config=config)\n# keras.backend.set_session(sess)\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"1\"#Setting the script to run on GPU:1,2\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'\n\n\n#os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"1,2\"#Setting the script to run on GPU:1,2\n\nimport random\nimport os\nimport sys\nimport cv2\nimport csv\nimport glob\nimport numpy as np\nimport time\nfrom sklearn.utils import shuffle\n\n# path to USB\nUSBPath = \"/home/scope/Carla/autopilot_Carla_ad/sample_data/\"\n# list of folders used in training\ntrainingFolders = [\"run3\",\"run4\"]\n#Only parameters that has to be changed\nWorking_directory = \"/home/scope/Carla/autopilot_Carla_ad/leaderboard/team_code/detector_code/trial1/\"#working directory\nWorking_folder = 'new-B-1.2'#experiment\nWorking_path = Working_directory + Working_folder + '/'\ntrainfolder = 'train_reconstruction_result'#train folder\ndata = CSVLogger(Working_path + 'kerasloss.csv', append=True, separator=';')\n\n\n#Load complete input images without shuffling\ndef load_images(paths):\n    numImages = 0\n    inputs = []\n    for path in paths:\n        numFiles = len(glob.glob1(path,'*.png'))\n        numImages += numFiles\n        for img in glob.glob(path+'*.png'):\n            img = cv2.imread(img)\n            img = cv2.resize(img, (224, 224))\n            img = img / 255.\n            inputs.append(img)\n    #inpu = shuffle(inputs)\n    print(\"Total number of images:%d\" %(numImages))\n    return inputs\n\ndef createFolderPaths(folders):\n    paths = []\n    for folder in folders:\n        path = USBPath + folder + '/' + 'rgb_right_detector' + '/'\n        paths.append(path)\n    return paths\n\ndef load_training_images():\n    paths = createFolderPaths(trainingFolders)\n    return load_images(paths)\n\n\ndef load_data():\n    #Loading images from the datasets\n    csv_input = load_training_images()\n    len(csv_input)#length of the data\n    csv_input = shuffle(csv_input)\n\n    img_train, img_test = np.array(csv_input[0:len(csv_input)-200]), np.array(csv_input[len(csv_input)-200:len(csv_input)])\n    img_train = np.reshape(img_train, [-1, img_train.shape[1],img_train.shape[2],img_train.shape[3]])\n    img_test = np.reshape(img_test, [-1, img_test.shape[1],img_test.shape[2],img_test.shape[3]])\n    #Shuffle the data in order to get different images in train and test datasets.\n    #img_train = shuffle(img_train)\n    #img_test = shuffle(img_test)\n    inp = (img_train, img_test)\n    return inp\n\n#Sampling function used by the VAE\ndef sample_func(args):\n    z_mean, z_log_var = args\n    batch = K.shape(z_mean)[0]\n    dim = K.int_shape(z_mean)[1]\n    # by default, random_normal has mean = 0 and std = 1.0\n    epsilon = K.random_normal(shape=(batch, dim))\n    return z_mean + K.exp(0.5 * z_log_var) * epsilon\n\n#CNN-VAE model. Only important part is the N_latent variable which holds the latent space data.\ndef CreateModels(n_latent=100, sample_enc=sample_func, beta=1.2, C=0):\n    model = Sequential()\n    input_img = Input(shape=(224,224,3), name='image')\n    x = Conv2D(128, (3, 3),  use_bias=False, padding='same')(input_img)\n    x = BatchNormalization()(x)\n    x = LeakyReLU(0.1)(x)\n    x = MaxPooling2D((2, 2), padding='same')(x)\n\n    x = Conv2D(64, (3, 3), padding='same',use_bias=False)(x)\n    x = BatchNormalization()(x)\n    x = LeakyReLU(0.1)(x)\n    x = MaxPooling2D((2, 2), padding='same')(x)\n\n    x = Conv2D(32, (3, 3), padding='same',use_bias=False)(x)\n    x = BatchNormalization()(x)\n    x = LeakyReLU(0.1)(x)\n    x = MaxPooling2D((2, 2), padding='same')(x)\n\n    x = Conv2D(16, (3, 3), padding='same',use_bias=False)(x)\n    x = BatchNormalization()(x)\n    x = LeakyReLU(0.1)(x)\n    x = MaxPooling2D((2, 2), padding='same')(x)\n\n    x = Flatten()(x)\n    x = Dense(2048)(x)\n    x = LeakyReLU(0.1)(x)\n    x = Dense(1000)(x)\n    x = LeakyReLU(0.1)(x)\n    x = Dense(250)(x)\n    x = LeakyReLU(0.1)(x)\n#     x = Dense(50)(x)\n#     x = LeakyReLU(0.1)(x)\n\n    z_mean = Dense(n_latent, name='z_mean')(x)\n    z_log_var = Dense(n_latent, name='z_log_var')(x)\n    z = Lambda(sample_func, output_shape=(n_latent,), name='z')([z_mean, z_log_var])\n\n    encoder = Model(input_img, [z_mean, z_log_var, z], name='encoder')\n    #encoder.summary()\n\n    latent_inputs = Input(shape=(n_latent,), name='z_sampling')\n#     x = Dense(50)(latent_inputs)\n#     x = LeakyReLU(0.1)(x)\n    x = Dense(250)(latent_inputs)\n    x = LeakyReLU(0.1)(x)\n    x = Dense(1000)(x)\n    x = LeakyReLU(0.1)(x)\n    x = Dense(2048)(x)\n    x = LeakyReLU(0.1)(x)\n    x = Dense(3136)(x)\n    x = LeakyReLU(0.1)(x)\n\n    x = Reshape((14, 14, 16))(x)\n\n    x = Conv2D(16, (3, 3), padding='same', use_bias=False)(x)\n    x = BatchNormalization()(x)\n    x = LeakyReLU(0.1)(x)\n    x = UpSampling2D((2,2))(x)\n\n    x = Conv2D(32, (3, 3), padding='same', use_bias=False)(x)\n    x = BatchNormalization()(x)\n    x = LeakyReLU(0.1)(x)\n    x = UpSampling2D((2,2))(x)\n\n    x = Conv2D(64, (3, 3), padding='same', use_bias=False)(x)\n    x = BatchNormalization()(x)\n    x = LeakyReLU(0.1)(x)\n    x = UpSampling2D((2,2))(x)\n\n    x = Conv2D(128, (3, 3), padding='same', use_bias=False)(x)\n    x = BatchNormalization()(x)\n    x = LeakyReLU(0.1)(x)\n    x = UpSampling2D((2,2))(x)\n\n    x = Conv2D(3, (3, 3), padding='same', use_bias=False)(x)\n    x = BatchNormalization()(x)\n    decoded = Activation('sigmoid')(x)\n\n    decoder = Model(latent_inputs, decoded)\n    #decoder.summary()\n\n    outputs = decoder(encoder(input_img)[2])\n    autoencoder = Model(input_img,outputs)\n    #autoencoder.summary()\n\n    def vae_loss(true, pred):\n        rec_loss = mse(K.flatten(true), K.flatten(pred))\n        rec_loss *= 224*224*3\n        kl_loss = 1 + z_log_var - K.square(z_mean) - K.exp(z_log_var)\n        kl_loss = K.sum(kl_loss, axis=-1)\n        kl_loss *= -0.5\n        vae_loss = K.mean(rec_loss + beta*(kl_loss-C))\n        return vae_loss\n        #autoencoder.add_loss(vae_loss)\n\n    def lr_scheduler(epoch): #learningrate scheduler to adjust learning rate.\n        lr = 1e-6\n        if epoch > 50:\n            print(\"New learning rate\")\n            lr = 1e-8\n        if epoch > 75:\n            print(\"New learning rate\")\n            lr = 1e-8\n        return lr\n\n    scheduler = LearningRateScheduler(lr_scheduler)\n    #Define adam optimizer\n    adam = keras.optimizers.Adam(lr=1e-6, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)\n    autoencoder.compile(optimizer='adam',loss=vae_loss, metrics=[vae_loss])\n\n    #Define adam optimizer\n    #adam = keras.optimizers.Adam(lr=0.000001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)\n    #autoencoder.compile(optimizer='rmsprop',loss=vae_loss, metrics=[vae_loss])\n    #autoencoder.compile(optimizer='adam',loss=vae_loss, metrics=[vae_loss])\n\n    return autoencoder, encoder,decoder, z_log_var\n\n\n#Train function to fit the data to the model\ndef train(X,autoencoder):\n    X_train,X_test = X\n    filePath = Working_path + 'weights.best.hdf5'#checkpoint weights\n\n    checkpoint = ModelCheckpoint(filePath, monitor='vae_loss', verbose=1, save_best_only=True, mode='min')\n    EarlyStopping(monitor='vae_loss', patience=10, verbose=0),\n    callbacks_list = [checkpoint, data]\n    autoencoder.fit(X_train, X_train,epochs=75,batch_size=16,shuffle=True,validation_data=(X_test, X_test),callbacks=callbacks_list, verbose=2)\n\n    #checkpoint = ModelCheckpoint(filePath, monitor='vae_loss', verbose=2, save_best_only=True, mode='min')\n    #EarlyStopping(monitor='vae_loss', patience=5, verbose=0),\n    #es=EarlyStopping(monitor='vae_loss', min_delta=0, patience=5, verbose=0, mode='auto', baseline=None, restore_best_weights=False)\n    #callbacks_list = [checkpoint, data]\n    #autoencoder.fit(X_train, X_train,epochs=2,batch_size=16,shuffle=True,validation_data=(X_test, X_test),callbacks=callbacks_list, verbose=1)\n\n\n    #Save the autoencoder model\ndef SaveAutoencoderModel(autoencoder):\n\tauto_model_json = autoencoder.to_json()\n\twith open(Working_path + 'auto_model.json', \"w\") as json_file:\n\t\tjson_file.write(auto_model_json)\n\tautoencoder.save_weights(Working_path + 'auto_model.h5')\n\tprint(\"Saved Autoencoder model to disk\")\n\n#Save the encoder model\ndef SaveEncoderModel(encoder):\n\ten_model_json = encoder.to_json()\n\twith open(Working_path + 'en_model.json', \"w\") as json_file:\n\t\tjson_file.write(en_model_json)\n\tencoder.save_weights(Working_path + 'en_model.h5')\n\tprint(\"Saved Encoder model to disk\")\n\n#Test the trained models on a different test data\ndef test(autoencoder,encoder,test):\n    autoencoder_res = autoencoder.predict(test)\n    encoder_res = encoder.predict(test)\n    res_x = test.copy()\n    res_y = autoencoder_res.copy()\n    res_x = res_x * 255\n    res_y = res_y * 255\n\n    return res_x, res_y, encoder_res\n\n#Save the reconstructed test data in a separate folder.\n#For this create a folder named results in the directory you are working in.\ndef savedata(test_in, test_out, test_encoded, Working_path, trainfolder):\n    os.makedirs(Working_path + trainfolder + '/', exist_ok=True)\n    for i in range(len(test_in)):\n        test_in = np.reshape(test_in,[-1, 224,224,3])#Reshape the data\n        test_out = np.reshape(test_out,[-1, 224,224,3])#Reshape the data\n        cv2.imwrite(Working_path + trainfolder + '/' + str(i) +'_in.png', test_in[i])\n        cv2.imwrite(Working_path + trainfolder + '/' + str(i) +'_out.png', test_out[i])\n\n\nif __name__ == '__main__':\n    print(\"loading image\")\n    inp = load_data()\n    print(\"created model\")\n    autoencoder,encoder,decoder,z_log_var = CreateModels()# Running the autoencoder model\n    print(\"training model\")\n    train(inp,autoencoder)#Train the model with the data\n    print(\"testing model\")\n    test_in, test_out, test_encoded = test(autoencoder, encoder, inp[1])#Test the trained model with new data\n    print(\"save model performance\")\n    savedata(test_in, test_out, test_encoded, Working_path, trainfolder)#Save the data\n    print(\"save encoder model\")\n    SaveEncoderModel(encoder)\n    SaveAutoencoderModel(autoencoder)#Save the autoencoder and encoder models\n", "meta": {"hexsha": "b8e91901ae29da200ce08db0b2c7db0fc4697963", "size": 10995, "ext": "py", "lang": "Python", "max_stars_repo_path": "resonate-carla/leaderboard/team_code/detector_code/train-bvae.py", "max_stars_repo_name": "scope-lab-vu/Resonate-Dynamic-Risk", "max_stars_repo_head_hexsha": "46972bdb0a2b6b08cc188a9f1f6567971c9d263d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-08-15T05:02:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T11:25:45.000Z", "max_issues_repo_path": "resonate-carla/leaderboard/team_code/detector_code/train-bvae.py", "max_issues_repo_name": "scope-lab-vu/Resonate-Dynamic-Risk", "max_issues_repo_head_hexsha": "46972bdb0a2b6b08cc188a9f1f6567971c9d263d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "resonate-carla/leaderboard/team_code/detector_code/train-bvae.py", "max_forks_repo_name": "scope-lab-vu/Resonate-Dynamic-Risk", "max_forks_repo_head_hexsha": "46972bdb0a2b6b08cc188a9f1f6567971c9d263d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-21T02:35:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-02T22:40:07.000Z", "avg_line_length": 36.5282392027, "max_line_length": 143, "alphanum_fraction": 0.6885857208, "include": true, "reason": "import numpy", "num_tokens": 3130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.19460230820929084}}
{"text": "__version__ = '0.8.0'\n\nimport numpy as np\nimport warnings\n\nfrom phonopy.file_IO import write_FORCE_CONSTANTS, write_force_constants_to_hdf5, write_FORCE_SETS\nfrom phonolammps.arrange import get_correct_arrangement, rebuild_connectivity_tinker\nfrom phonolammps.phonopy_link import obtain_phonon_dispersion_bands, get_phonon\nfrom phonolammps.iofile import get_structure_from_poscar, generate_VASP_structure\nfrom phonolammps.iofile import generate_tinker_key_file, generate_tinker_txyz_file, parse_tinker_forces\nfrom phonolammps.iofile import get_structure_from_lammps, get_structure_from_txyz\nfrom phonolammps.iofile import get_structure_from_g96, get_structure_from_gro\nfrom phonolammps.iofile import generate_gro, generate_g96\n\nimport shutil, os\n\n\n# define the force unit conversion factors to LAMMPS metal style (eV/Angstrom)\nunit_factors = {'real': 4.336410389526464e-2,\n                'metal': 1.0,\n                'si': 624150636.3094,\n                'gromacs': 0.00103642723,\n                'tinker': 0.043  # kcal/mol to eV\n}\n\n\nclass PhonoBase:\n    \"\"\"\n    Base class for PhonoLAMMPS\n    This class is not designed to be called directly.\n    To use it make a subclass and implement the following methods:\n\n    * __init__()\n    * get_forces()\n\n    \"\"\"\n\n    def get_path_using_seek_path(self):\n\n        \"\"\" Obtain the path in reciprocal space to plot the phonon band structure\n\n        :return: dictionary with list of q-points and labels of high symmetry points\n        \"\"\"\n\n        try:\n            import seekpath\n\n            cell = self._structure.get_cell()\n            positions = self._structure.get_scaled_positions()\n            numbers = np.unique(self._structure.get_chemical_symbols(), return_inverse=True)[1]\n\n            path_data = seekpath.get_path((cell, positions, numbers))\n\n            labels = path_data['point_coords']\n\n            band_ranges = []\n            for set in path_data['path']:\n                band_ranges.append([labels[set[0]], labels[set[1]]])\n\n            return {'ranges': band_ranges,\n                    'labels': path_data['path']}\n        except ImportError:\n            print ('Seekpath not installed. Autopath is deactivated')\n            band_ranges = ([[[0.0, 0.0, 0.0], [0.5, 0.0, 0.5]]])\n            return {'ranges': band_ranges,\n                    'labels': [['GAMMA', '1/2 0 1/2']]}\n\n    def get_force_constants(self, include_data_set=False):\n        \"\"\"\n        calculate the force constants with phonopy using lammps to calculate forces\n\n        :return: ForceConstants type object containing force constants\n        \"\"\"\n\n        if self._force_constants is None:\n            phonon = get_phonon(self._structure,\n                                setup_forces=False,\n                                super_cell_phonon=self._supercell_matrix,\n                                primitive_matrix=self._primitive_matrix,\n                                NAC=self._NAC,\n                                symmetrize=self._symmetrize)\n\n            phonon.get_displacement_dataset()\n            phonon.generate_displacements(distance=self._displacement_distance)\n            cells_with_disp = phonon.get_supercells_with_displacements()\n            data_set = phonon.get_displacement_dataset()\n\n            # Check forces for non displaced supercell\n            forces_supercell = self.get_forces(phonon.get_supercell())\n            if np.max(forces_supercell) > 1e-1:\n                warnings.warn('Large atomic forces found for non displaced structure: '\n                              '{}. Make sure your unit cell is properly optimized'.format(np.max(forces_supercell)))\n\n            # Get forces from lammps\n            for i, cell in enumerate(cells_with_disp):\n                if self._show_progress:\n                    print('displacement {} / {}'.format(i+1, len(cells_with_disp)))\n                forces = self.get_forces(cell)\n                data_set['first_atoms'][i]['forces'] = forces\n\n            phonon.set_displacement_dataset(data_set)\n            phonon.produce_force_constants()\n            self._force_constants = phonon.get_force_constants()\n            self._data_set = data_set\n\n        if include_data_set:\n            return [self._force_constants, self._data_set]\n        else:\n            return self._force_constants\n\n    def plot_phonon_dispersion_bands(self):\n        \"\"\"\n        Plot phonon band structure using seekpath automatic k-path\n        Warning: The labels may be wrong if the structure is not standarized\n\n        \"\"\"\n        import matplotlib.pyplot as plt\n\n        def replace_list(text_string):\n            substitutions = {'GAMMA': u'$\\Gamma$',\n                             }\n\n            for item in substitutions.items():\n                text_string = text_string.replace(item[0], item[1])\n            return text_string\n\n        force_constants = self.get_force_constants()\n        bands_and_labels = self.get_path_using_seek_path()\n\n        _bands = obtain_phonon_dispersion_bands(self._structure,\n                                                bands_and_labels['ranges'],\n                                                force_constants,\n                                                self._supercell_matrix,\n                                                primitive_matrix=self._primitive_matrix,\n                                                band_resolution=30)\n\n        for i, freq in enumerate(_bands[1]):\n            plt.plot(_bands[1][i], _bands[2][i], color='r')\n\n        plt.ylabel('Frequency [THz]')\n        plt.xlabel('Wave vector')\n        plt.xlim([0, _bands[1][-1][-1]])\n        plt.axhline(y=0, color='k', ls='dashed')\n        plt.suptitle('Phonon dispersion')\n\n        if 'labels' in bands_and_labels:\n            plt.rcParams.update({'mathtext.default': 'regular'})\n\n            labels = bands_and_labels['labels']\n\n            labels_e = []\n            x_labels = []\n            for i, freq in enumerate(_bands[1]):\n                if labels[i][0] == labels[i - 1][1]:\n                    labels_e.append(replace_list(labels[i][0]))\n                else:\n                    labels_e.append(\n                        replace_list(labels[i - 1][1]) + '/' + replace_list(labels[i][0]))\n                x_labels.append(_bands[1][i][0])\n            x_labels.append(_bands[1][-1][-1])\n            labels_e.append(replace_list(labels[-1][1]))\n            labels_e[0] = replace_list(labels[0][0])\n\n            plt.xticks(x_labels, labels_e, rotation='horizontal')\n\n        plt.show()\n\n    def write_force_constants(self, filename='FORCE_CONSTANTS', hdf5=False):\n        \"\"\"\n        Write the force constants in a file in phonopy plain text format\n\n        :param filename: Force constants filename\n        \"\"\"\n\n        force_constants = self.get_force_constants()\n        if hdf5:\n            write_force_constants_to_hdf5(force_constants, filename=filename)\n        else:\n            write_FORCE_CONSTANTS(force_constants, filename=filename)\n\n    def write_force_sets(self, filename='FORCE_SETS'):\n        \"\"\"\n        Write the force sets in a file in phonopy plain text format\n\n        :param filename: Force sets filename\n        \"\"\"\n\n        data_set = self.get_force_constants(include_data_set=True)[1]\n\n        write_FORCE_SETS(data_set, filename=filename)\n\n    def get_unitcell(self):\n        \"\"\"\n        Get unit cell structure\n\n        :return unitcell: unit cell 3x3 matrix (lattice vectors in rows)\n        \"\"\"\n        return self._structure\n\n    def get_supercell_matrix(self):\n        \"\"\"\n        Get the supercell matrix\n\n        :return supercell: the supercell 3x3 matrix (list of lists)\n        \"\"\"\n        return self._supercell_matrix\n\n    def get_primitve_matrix(self):\n        return self._primitive_matrix\n\n    def get_seekpath_bands(self, band_resolution=30):\n        ranges = self.get_path_using_seek_path()['ranges']\n        bands =[]\n        for q_start, q_end in ranges:\n            band = []\n            for i in range(band_resolution+1):\n                band.append(np.array(q_start) + (np.array(q_end) - np.array(q_start)) / band_resolution * i)\n            bands.append(band)\n\n        return bands\n\n    def write_unitcell_POSCAR(self, filename='POSCAR'):\n        \"\"\"\n        Write unit cell in VASP POSCAR type file\n\n        :param filename: POSCAR file name (Default: POSCAR)\n        \"\"\"\n        poscar_txt = generate_VASP_structure(self._structure)\n\n        with open(filename, mode='w') as f:\n            f.write(poscar_txt)\n\n    def get_phonopy_phonon(self):\n        \"\"\"\n        Return phonopy phonon object with unitcell, primitive cell and\n        the force constants set.\n\n        :return:\n        \"\"\"\n\n        phonon = get_phonon(self._structure,\n                            setup_forces=False,\n                            super_cell_phonon=self._supercell_matrix,\n                            primitive_matrix=self._primitive_matrix,\n                            NAC=self._NAC,\n                            symmetrize=self._symmetrize)\n\n        phonon.set_force_constants(self.get_force_constants())\n\n        return phonon\n\n################################\n#            LAMMPS            #\n################################\nclass Phonolammps(PhonoBase):\n    def __init__(self,\n                 lammps_input,\n                 supercell_matrix=np.identity(3),\n                 primitive_matrix=np.identity(3),\n                 displacement_distance=0.01,\n                 show_log=False,\n                 show_progress=False,\n                 use_NAC=False,\n                 symmetrize=True):\n        \"\"\"\n        Main PhonoLAMMPS class\n\n        :param lammps_input: LAMMPS input file name or list of commands\n        :param supercell_matrix:  3x3 matrix supercell\n        :param primitive cell:  3x3 matrix primitive cell\n        :param displacement_distance: displacement distance in Angstroms\n        :param show_log: Set true to display lammps log info\n        :param show_progress: Set true to display progress of calculation\n        \"\"\"\n\n        # Check if input is file or list of commands\n        if type(lammps_input) is str:\n            # read from file name\n            self._lammps_input_file = lammps_input\n            self._lammps_commands_list = open(lammps_input).read().split('\\n')\n        else:\n            # read from commands\n            self._lammps_commands_list = lammps_input\n\n        self._structure = get_structure_from_lammps(self._lammps_commands_list)\n\n        self._supercell_matrix = supercell_matrix\n        self._primitive_matrix = primitive_matrix\n        self._displacement_distance = displacement_distance\n        self._show_log = show_log\n        self._show_progress = show_progress\n        self._symmetrize = symmetrize\n        self._NAC = use_NAC\n\n        self._force_constants = None\n        self._data_set = None\n\n        self.units = self.get_units(self._lammps_commands_list)\n\n        if not self.units in unit_factors.keys():\n            print ('Units style not supported, use: {}'.format(unit_factors.keys()))\n            exit()\n\n    def get_units(self, commands_list):\n        \"\"\"\n        Get the units label for LAMMPS \"units\" command from a list of LAMMPS input commands\n\n        :param commands_list: list of LAMMPS input commands (strings)\n        :return units: string containing the units\n        \"\"\"\n        for line in commands_list:\n                if line.startswith('units'):\n                    return line.split()[1]\n        return 'lj'\n\n    def get_forces(self, cell_with_disp):\n        \"\"\"\n        Calculate the forces of a supercell using lammps\n\n        :param cell_with_disp: supercell from which determine the forces\n        :return: numpy array matrix with forces of atoms [Natoms x 3]\n        \"\"\"\n\n        import lammps\n\n        supercell_sizes = np.diag(self._supercell_matrix)\n\n        cmd_list = ['-log', 'none']\n        if not self._show_log:\n            cmd_list += ['-echo', 'none', '-screen', 'none']\n\n        lmp = lammps.lammps(cmdargs=cmd_list)\n        lmp.commands_list(self._lammps_commands_list)\n        lmp.command('replicate {} {} {}'.format(*supercell_sizes))\n        lmp.command('run 0')\n\n        na = lmp.get_natoms()\n        # xc = lmp.gather_atoms(\"x\", 1, 3)\n        # reference2 = np.array([xc[i] for i in range(na * 3)]).reshape((na, 3))\n\n        id = lmp.extract_atom(\"id\", 0)\n        id = np.array([id[i]-1 for i in range(na)], dtype=int)\n\n        xp = lmp.extract_atom(\"x\", 3)\n        reference = np.array([[xp[i][0], xp[i][1], xp[i][2]] for i in range(na)], dtype=float)[id, :]\n\n        template = get_correct_arrangement(reference, self._structure, self._supercell_matrix)\n        indexing = np.argsort(template)\n\n        coordinates = cell_with_disp.get_positions()\n\n        for i in range(na):\n            lmp.command('set atom {} x {} y {} z {}'.format(i + 1,\n                                                            coordinates[template[i], 0],\n                                                            coordinates[template[i], 1],\n                                                            coordinates[template[i], 2]))\n\n        lmp.command('run 0')\n\n        # forces2 = lmp.gather_atoms(\"f\", 1, 3)\n        # forces2 = np.array([forces2[i] for i in range(na * 3)], dtype=float).reshape((na, 3))#[indexing,:]\n\n        id = lmp.extract_atom(\"id\", 0)\n        id = np.array([id[i]-1 for i in range(na)], dtype=int)\n\n        fp = lmp.extract_atom(\"f\", 3)\n        forces = np.array([[fp[i][0], fp[i][1], fp[i][2]] for i in range(na)], dtype=float)[id, :]\n\n        forces = forces[indexing, :] * unit_factors[self.units]\n\n        lmp.close()\n\n        return forces\n\n\n################################\n#            TINKER            #\n################################\nclass PhonoTinker(PhonoBase):\n\n    def __init__(self,\n                 txyz_input_file,\n                 key_input_file,\n                 force_field_file,\n                 supercell_matrix=np.identity(3),\n                 primitive_matrix=np.identity(3),\n                 displacement_distance=0.01,\n                 show_log=False,\n                 show_progress=False,\n                 use_NAC=False,\n                 symmetrize=True):\n        \"\"\"\n        Experimental class to use Tinker to calculate forces, can be used\n        as an example to how to expand phonoLAMMPS to other software\n\n        :param txyz_input_file:  TXYZ input file name (see example)\n        :param supercell_matrix:  3x3 matrix supercell\n        :param primitive cell:  3x3 matrix primitive cell\n        :param displacement_distance: displacement distance in Angstroms\n        :param show_log: set true to display lammps log info\n        :param show_progress: set true to display progress of calculation\n        :param use_NAC: set true to use Non-Analytical corrections or not\n        :param symmetrize: set true to use symmetrization of the force constants\n        \"\"\"\n\n        self._structure = get_structure_from_txyz(txyz_input_file, key_input_file)\n        self._txyz_input_file = txyz_input_file\n\n        self._supercell_matrix = supercell_matrix\n        self._primitive_matrix = primitive_matrix\n        self._displacement_distance = displacement_distance\n        self._show_log = show_log\n        self._show_progress = show_progress\n        self._symmetrize = symmetrize\n        self._NAC = use_NAC\n\n        self._force_constants = None\n        self._data_set = None\n\n        self.units = 'tinker'\n\n        self.force_field = force_field_file\n\n        if not self.units in unit_factors.keys():\n            print ('Units style not supported, use: {}'.format(unit_factors.keys()))\n            exit()\n\n    def get_forces(self, cell_with_disp):\n        \"\"\"\n        Calculate the forces of a supercell using tinker\n        :param cell_with_disp: supercell (PhonopyAtoms) from which determine the forces\n        :return array: numpy array matrix with forces of atoms [Natoms x 3]\n        \"\"\"\n\n        import tempfile\n        import subprocess\n        from subprocess import PIPE\n\n        temp_file_name = tempfile.gettempdir() + '/tinker_temp' + '_' + str(os.getpid())\n\n        # temp_file_name = 'test_calc'\n\n        supercell_wd = rebuild_connectivity_tinker(self._structure,\n                                                   cell_with_disp,\n                                                   self._supercell_matrix)\n\n        tinker_input_file = open(temp_file_name + '.txyz', mode='w')\n        tinker_input_file.write(generate_tinker_txyz_file(supercell_wd))\n\n        tinker_key_file = open(temp_file_name + '.key', mode='w')\n        tinker_key_file.write(generate_tinker_key_file(supercell_wd))\n\n        tinker_input_file.close()\n        tinker_key_file.close()\n\n        tinker_command = './testgrad ' + tinker_input_file.name + \\\n                         ' ' + self.force_field + ' Y N N ' + ' -k ' + tinker_key_file.name\n\n        tinker_process = subprocess.Popen(tinker_command, stdin=PIPE, stderr=PIPE, stdout=PIPE, shell=True)\n        (output, err) = tinker_process.communicate()\n        tinker_process.wait()\n\n        if len(err.split()) != 0:\n            print(err)\n            print('Something wrong in forces calculation!')\n            exit()\n\n        # print(output)\n        os.unlink(tinker_input_file.name)\n        os.unlink(tinker_key_file.name)\n\n        forces = parse_tinker_forces(output) * unit_factors[self.units]\n\n        return forces\n\n\n################################\n#           GROMACS            #\n################################\nclass PhonoGromacs(PhonoBase):\n\n    _work_dir = 'gromorg_{}/'.format(os.getpid())\n\n    # _work_dir = 'gromorg_test/'\n\n    def __init__(self,\n                 gro_file,\n                 supercell_matrix=np.identity(3),\n                 primitive_matrix=np.identity(3),\n                 displacement_distance=0.01,\n                 show_log=False,\n                 show_progress=False,\n                 use_NAC=False,\n                 symmetrize=True,\n                 gmx_params=None,\n                 base_ff='charmm27.ff/forcefield.itp',\n                 itp_file=None,\n                 silent=True,\n                 omp_num_threads=1):\n\n        \"\"\"\n        Experimental class to use Tinker to calculate forces, can be used\n        as an example to how to expand phonoLAMMPS to other software\n\n        :param xyz_input_file:  XYZ input file name (see example)\n        :param supercell_matrix:  3x3 matrix supercell\n        :param primitive cell:  3x3 matrix primitive cell\n        :param displacement_distance: displacement distance in Angstroms\n        :param show_log: set true to display lammps log info\n        :param show_progress: set true to display progress of calculation\n        :param use_NAC: set true to use Non-Analytical corrections or not\n        :param symmetrize: set true to use symmetrization of the force constants\n        \"\"\"\n\n        self._supercell_matrix = supercell_matrix\n        self._primitive_matrix = primitive_matrix\n        self._displacement_distance = displacement_distance\n        self._show_log = show_log\n        self._show_progress = show_progress\n        self._symmetrize = symmetrize\n        self._NAC = use_NAC\n\n        self._force_constants = None\n        self._data_set = None\n        self._silent = silent\n\n        self._base_fcc = base_ff\n\n        self.units = 'gromacs'\n\n        if not self.units in unit_factors.keys():\n            print ('Units style not supported, use: {}'.format(unit_factors.keys()))\n            exit()\n\n        # import openbabel\n\n        # a, b, c = [8.194, 5.968, 8.669]\n        # alpha, beta, gamma = [90.0, 123.57, 90.0]\n\n        # a1 = a\n        # b1 = b * np.cos(np.deg2rad(gamma))\n        # b2 = np.sqrt(b ** 2 - b1 ** 2)\n        # c1 = c * np.cos(np.deg2rad(beta))\n        # c2 = (b * c * np.cos(np.deg2rad(alpha)) - b1 * c1) / b2\n        # c3 = np.sqrt(c ** 2 - c1 ** 2 - c2 ** 2)\n\n        # unitcell = [[a1, 0, 0],\n        #             [b1, b2, 0],\n        #             [c1, c2, c3]]\n\n\n        self._structure = get_structure_from_g96(gro_file)\n\n\n        os.putenv('GMX_MAXBACKUP', '-1')\n        os.putenv('OMP_NUM_THREADS', '{}'.format(omp_num_threads))\n\n        self._filename = 'test'\n\n        # os.mkdir(self._work_dir)\n        try:\n            os.mkdir(self._work_dir)\n        except FileExistsError:\n            pass\n\n        self._filename_dir = self._work_dir + self._filename\n\n        # Default parameters\n\n        # Run paramters\n        if gmx_params is None:\n            gmx_params = {}\n\n        gmx_params.update({'integrator': 'steep',     # Verlet integrator\n                           'nsteps': 1,            # 0.001 * 5000 = 50 ps\n                           'nstxout': 1,  # save coordinates every 0.001 ps\n                           'nstvout': 1,  # save velocities every 0.001 ps\n                           'nstfout': 1,  # save forces every 0.001 ps\n                           'dt': 0.1})\n\n        self._params = gmx_params\n\n\n        self._supercell = np.diag(supercell_matrix)\n        self._box = [v/10 for v in self.cell_lengths(self._structure.cell)]\n        self._angles = self.cell_angles(self._structure.cell)\n        # alpha, beta, gamma = [90.0, 123.57, 90.0]\n\n        from phonolammps.swissparam import SwissParams\n\n        if itp_file is None:\n            sw = SwissParams(self._structure, silent=False)\n\n            files = {'itp': sw.get_itp_data(),\n                     'pdb': sw.get_pdb_data(),\n                     'top': self.get_topology(),\n                     'mdp': self.get_mdp()}\n\n            for ext, data in files.items():\n                with open(self._filename_dir + '.{}'.format(ext), 'w') as f:\n                    f.write(data)\n        else:\n            shutil.copy(itp_file, self._filename_dir + '.itp')\n\n            with open(self._filename_dir + '.top', 'w') as f:\n                f.write(self.get_topology())\n\n            with open(self._filename_dir + '.mdp', 'w') as f:\n                f.write(self.get_mdp())\n\n    def cell_lengths(self, cell):\n        \"\"\"\n        Get the lengths of cell lattice vectors in angstroms.\n        \"\"\"\n        import numpy\n\n        return [\n            numpy.linalg.norm(cell[0]),\n            numpy.linalg.norm(cell[1]),\n            numpy.linalg.norm(cell[2]),\n        ]\n\n    def cell_angles(self, cell):\n        \"\"\"\n        Get the angles between the cell lattice vectors in degrees.\n        \"\"\"\n        import numpy\n\n        lengths = self.cell_lengths(cell)\n        return [\n            float(numpy.arccos(x) / numpy.pi * 180) for x in [\n                numpy.vdot(cell[1], cell[2]) / lengths[1] / lengths[2],\n                numpy.vdot(cell[0], cell[2]) / lengths[0] / lengths[2],\n                numpy.vdot(cell[0], cell[1]) / lengths[0] / lengths[1],\n            ]\n        ]\n\n    def get_mdp(self):\n        file = ';Autogenerated MDP\\n'\n        for keys, values in self._params.items():\n            file += '{:30} = {}\\n'.format(keys, values)\n\n        return file\n\n    def get_topology(self):\n\n        num_mol = np.prod(self._supercell)\n        file = '; Autogenerated Topology\\n'\n\n        itp_files = [self._base_fcc, '{}.itp'.format(self._filename)]\n\n        params = {'system': ['molecular system name'],\n                  'molecules': ['{} {}\\n'.format(self._filename, num_mol)]}\n\n        for itp in itp_files:\n            file += '#include \"{}\"\\n'.format(itp)\n\n        for section, lines in params.items():\n            file += '[ {} ]\\n'.format(section)\n            for line in lines:\n                file += '{}\\n'.format(line)\n\n        return file\n\n    def get_tpr(self, supercell_wd):\n        import gmxapi as gmx\n\n        #gmx genconf -f molecule.gro -o multi_mol.gro -nbox 2 2 2\n\n            # print(self._filename_dir + '.gro')\n\n        #create_gro(supercell_wd, self._structure, self._filename_dir + '.gro')\n\n        generate_g96(supercell_wd, self._structure, self._filename_dir + '.g96')\n\n\n        grompp = gmx.commandline_operation('gmx', 'grompp',\n                                           input_files={'-f': self._filename_dir + '.mdp',\n                                                        # '-c': self._filename_dir + '.gro',\n                                                        '-c': self._filename_dir + '.g96',\n                                                        '-p': self._filename_dir + '.top',\n                                                        '-po': self._filename_dir + '_log.mdp'},\n                                           output_files={'-o': self._filename_dir + '.tpr'})\n        grompp.run()\n\n        if grompp.output.returncode.result() != 0:\n            print(grompp.output.erroroutput.result())\n\n        tpr_data = gmx.read_tpr(self._filename_dir + '.tpr')\n\n        return tpr_data\n\n    def get_forces(self, cell_with_disp):\n        \"\"\"\n        Calculate the forces of a supercell using tinker\n        :param cell_with_disp: supercell (PhonopyAtoms) from which determine the forces\n        :return array: numpy array matrix with forces of atoms [Natoms x 3]\n        \"\"\"\n\n        import gmxapi as gmx\n        from phonolammps.capture import captured_stdout\n\n        supercell_wd = rebuild_connectivity_tinker(self._structure,\n                                                   cell_with_disp,\n                                                   self._supercell_matrix)\n\n        # simulation_input = gmx.modify_input(input=self.get_tpr(supercell_wd), parameters={'nsteps': 1})\n\n        md = gmx.mdrun(input=self.get_tpr(supercell_wd))\n\n        if self._silent:\n            with captured_stdout(self._filename_dir + '.log'):\n                md.run()\n        else:\n            md.run()\n\n\n        trajectory_file = md.output.trajectory.result()\n        md_data_dir = md.output._work_dir.result()\n\n        # print('trajectory file:', trajectory_file)\n        # print('workdir: ', md.output._work_dir.result())\n\n        # reference = get_structure_from_gro(self._filename_dir + '.gro').positions\n        reference = get_structure_from_g96(self._filename_dir + '.g96').positions\n\n        template = get_correct_arrangement(reference, self._structure, self._supercell_matrix)\n        indexing = np.argsort(template)\n\n        # print('{}\\n'.format(len(supercell_wd.symbols)))\n        # for s, c in zip(supercell_wd.symbols, supercell_wd.positions):\n        #     print('{:5} '.format(s) + '{:15.5f} {:15.5f} {:15.5f}'.format(*c))\n\n        # import mdtraj\n        # self._trajectory = mdtraj.load_trr(trajectory_file, top=md_data_dir + '/confout.gro')\n        # self._trajectory.save('mdtraj.gro')\n        # exit()\n\n        def extract_forces(trajectory_file, tpr_file, output='forces.xvg', step=0):\n\n            grompp = gmx.commandline_operation('gmx', ['traj', '-of'],\n                                               stdin='0',\n                                               input_files={'-f': trajectory_file,\n                                                            '-s': tpr_file,\n                                                            '-b': '{}'.format(step),\n                                                            '-e': '{}'.format(step),\n                                                            },\n                                               )\n\n            if grompp.output.returncode.result() != 0:\n                print(grompp.output.erroroutput.result())\n\n            forces = np.loadtxt('force.xvg', comments=['#', '@'])[1:].reshape(-1, 3)\n            # print(forces)\n\n            os.remove('force.xvg')\n\n            return forces  # KJ/(mol nm) to eV/ang\n\n        # trajectory = mdtraj.load_trr(trajectory_file, top=md_data_dir + '/confout.gro')\n        # print(trajectory.n_frames)\n        forces = extract_forces(trajectory_file, self._filename_dir + '.tpr', step=1)\n\n        forces = forces[indexing, :] * unit_factors[self.units]\n\n        shutil.rmtree(md.output._work_dir.result())\n\n        return forces\n\n    def __del__(self):\n        if os.path.isdir(self._work_dir):\n            shutil.rmtree(self._work_dir)\n\n\nif __name__ == '__main__':\n\n    params = {'rvdw': 0.28,\n              'rlist': 0.28,\n              'rcoulomb': 0.28}\n\n    phg = PhonoGromacs('unitcell_whole.g96', supercell_matrix=np.identity(3)*3, displacement_distance=0.15,\n                       itp_file='gromorg_test_ref/test.itp', show_progress=True, gmx_params=params)\n\n    phg.write_unitcell_POSCAR()\n    phg.plot_phonon_dispersion_bands()\n    phg.write_force_constants()\n    phonon = phg.get_phonopy_phonon()\n    phonon.run_mesh([40, 40, 40])\n    phonon.run_total_dos()\n    phonon.plot_total_dos().show()\n\n\n    exit()\n    structure = get_structure_from_txyz('structure_wrap_min.txyz', 'structure.key')\n    print(structure)\n    print(structure.get_connectivity())\n    print(generate_VASP_structure(structure))\n    print(structure.get_scaled_positions())\n    print(structure.get_chemical_symbols())\n\n    phonon = get_phonon(structure,\n                        setup_forces=False,\n                        super_cell_phonon=[[2, 0, 0], [0, 2, 0], [0, 0, 2]],\n                        NAC=False,\n                        symmetrize=True)\n\n\n    phonon.get_displacement_dataset()\n    phonon.generate_displacements(distance=0.0001)\n    cells_with_disp = phonon.get_supercells_with_displacements()\n    print(cells_with_disp[0])\n    print(generate_VASP_structure(cells_with_disp[0]))\n\n    supercell_wd = rebuild_connectivity_tinker(structure,\n                                               cells_with_disp[0],\n                                               phonon.get_supercell_matrix())\n\n    print(generate_tinker_txyz_file(supercell_wd))\n    print(generate_tinker_key_file(supercell_wd))\n\n    print(generate_VASP_structure(structure))\n\n    import tempfile\n    import subprocess\n    import os\n    from subprocess import PIPE\n\n    force_field = 'mm3'\n    temp_file_name = tempfile.gettempdir() + '/tinker_temp'+ '_' + str(os.getpid())\n\n\n    tinker_input_file = open(temp_file_name + '.txyz',mode='w')\n    tinker_input_file.write(generate_tinker_txyz_file(supercell_wd))\n\n    tinker_key_file = open(temp_file_name + '.key',mode='w')\n    tinker_key_file.write(generate_tinker_key_file(supercell_wd))\n\n    tinker_input_file.close()\n    tinker_key_file.close()\n\n\n    print('filename', tinker_input_file)\n    tinker_command = './testgrad ' + tinker_input_file.name + \\\n                     ' ' + force_field + ' Y N N ' + ' -k ' + tinker_key_file.name\n\n    tinker_process = subprocess.Popen(tinker_command, stdin=PIPE, stderr=PIPE, stdout=PIPE, shell=True)\n    (output, err) = tinker_process.communicate()\n    tinker_process.wait()\n\n    os.unlink(tinker_input_file.name)\n    os.unlink(tinker_key_file.name)\n\n    forces = parse_tinker_forces(output)\n    print(forces)\n    print(forces.shape)\n", "meta": {"hexsha": "77ba970546cac26156e8aead4dfc9510f5c116a8", "size": 30650, "ext": "py", "lang": "Python", "max_stars_repo_path": "phonolammps/__init__.py", "max_stars_repo_name": "abelcarreras/phonolammps", "max_stars_repo_head_hexsha": "6c7a6655630f8c0bc60f69f327b0dc2a3cfaef19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2018-01-22T04:51:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T02:49:46.000Z", "max_issues_repo_path": "phonolammps/__init__.py", "max_issues_repo_name": "abelcarreras/phonolammps", "max_issues_repo_head_hexsha": "6c7a6655630f8c0bc60f69f327b0dc2a3cfaef19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-06-04T02:21:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-26T13:48:55.000Z", "max_forks_repo_path": "phonolammps/__init__.py", "max_forks_repo_name": "abelcarreras/phonolammps", "max_forks_repo_head_hexsha": "6c7a6655630f8c0bc60f69f327b0dc2a3cfaef19", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2018-11-30T11:06:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T13:58:43.000Z", "avg_line_length": 35.8060747664, "max_line_length": 116, "alphanum_fraction": 0.5726916803, "include": true, "reason": "import numpy", "num_tokens": 7049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.19460230820929084}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport abc\nimport logging\nimport numpy as np\nfrom astropy import units as u\nfrom gammapy.maps import MapAxes, MapAxis\nfrom gammapy.utils.gauss import MultiGauss2D\nfrom gammapy.utils.interpolation import ScaledRegularGridInterpolator\nfrom .core import PSF\n\n__all__ = [\"ParametricPSF\", \"EnergyDependentMultiGaussPSF\", \"PSFKing\"]\n\nlog = logging.getLogger(__name__)\n\n\nclass ParametricPSF(PSF):\n    \"\"\"Parametric PSF base class\n\n    Parameters\n    -----------\n    axes : list of `MapAxis` or `MapAxes`\n        Axes\n    data : dict of `~numpy.ndarray`, or `~numpy.recarray`\n        Data\n    unit : dict of str or `~astropy.units.Unit`\n        Unit\n    meta : dict\n        Meta data\n    \"\"\"\n\n    @property\n    @abc.abstractmethod\n    def required_parameters(self):\n        pass\n\n    @abc.abstractmethod\n    def evaluate_direct(self, rad, **kwargs):\n        pass\n\n    @abc.abstractmethod\n    def evaluate_containment(self, rad, **kwargs):\n        pass\n\n    def normalize(self):\n        \"\"\"Normalize parametric PSF\"\"\"\n        raise NotImplementedError\n\n    @property\n    def quantity(self):\n        \"\"\"Quantity\"\"\"\n        quantity = {}\n\n        for name in self.required_parameters:\n            quantity[name] = self.data[name] * self.unit[name]\n\n        return quantity\n\n    @property\n    def unit(self):\n        \"\"\"Map unit (`~astropy.units.Unit`)\"\"\"\n        return self._unit\n\n    @unit.setter\n    def unit(self, values):\n        self._unit = {key: u.Unit(val) for key, val in values.items()}\n\n    @property\n    def _interpolators(self):\n        interps = {}\n\n        for name in self.required_parameters:\n            points = [a.center for a in self.axes]\n            points_scale = tuple([a.interp for a in self.axes])\n            interps[name] = ScaledRegularGridInterpolator(\n                points, values=self.quantity[name], points_scale=points_scale\n            )\n\n        return interps\n\n    def evaluate_parameters(self, energy_true, offset):\n        \"\"\"Evaluate analytic PSF parameters at a given energy and offset.\n\n        Uses nearest-neighbor interpolation.\n\n        Parameters\n        ----------\n        energy_true : `~astropy.units.Quantity`\n            energy value\n        offset : `~astropy.coordinates.Angle`\n            Offset in the field of view\n\n        Returns\n        -------\n        values : `~astropy.units.Quantity`\n            Interpolated value\n        \"\"\"\n        pars = {}\n        for name in self.required_parameters:\n            value = self._interpolators[name]((energy_true, offset))\n            pars[name] = value\n\n        return pars\n\n    def to_table(self, format=\"gadf-dl3\"):\n        \"\"\"Convert PSF table data to table.\n\n        Parameters\n        ----------\n        format : {\"gadf-dl3\"}\n            Format specification\n\n\n        Returns\n        -------\n        hdu_list : `~astropy.io.fits.HDUList`\n            PSF in HDU list format.\n        \"\"\"\n        from gammapy.irf.io import IRF_DL3_HDU_SPECIFICATION\n\n        table = self.axes.to_table(format=\"gadf-dl3\")\n        spec = IRF_DL3_HDU_SPECIFICATION[self.tag][\"column_name\"]\n\n        for name in self.required_parameters:\n            column_name = spec[name]\n            table[column_name] = self.data[name].T[np.newaxis]\n            table[column_name].unit = self.unit[name]\n\n        # Create hdu and hdu list\n        return table\n\n    @classmethod\n    def from_table(cls, table, format=\"gadf-dl3\"):\n        \"\"\"Create parametric psf from `~astropy.table.Table`.\n\n        Parameters\n        ----------\n        table : `~astropy.table.Table`\n            Table  info.\n\n        Returns\n        -------\n        psf : `~ParametricPSF`\n            PSF class\n        \"\"\"\n        from gammapy.irf.io import IRF_DL3_HDU_SPECIFICATION\n\n        axes = MapAxes.from_table(table, format=format)[cls.required_axes]\n\n        dtype = {\n            \"names\": cls.required_parameters,\n            \"formats\": len(cls.required_parameters) * (np.float32,),\n        }\n\n        data = np.empty(axes.shape, dtype=dtype)\n        unit = {}\n\n        spec = IRF_DL3_HDU_SPECIFICATION[cls.tag][\"column_name\"]\n\n        for name in cls.required_parameters:\n            column = table[spec[name]]\n            values = column.data[0].transpose()\n\n            # TODO: this fixes some files where sigma is written as zero\n            if \"sigma\" in name:\n                values[values == 0] = 1.0\n\n            data[name] = values.reshape(axes.shape)\n            unit[name] = column.unit or \"\"\n\n        return cls(axes=axes, data=data, meta=table.meta.copy(), unit=unit)\n\n    def to_psf3d(self, rad=None):\n        \"\"\"Create a PSF3D from a parametric PSF.\n\n        It will be defined on the same energy and offset values than the input psf.\n\n        Parameters\n        ----------\n        rad : `~astropy.units.Quantity`\n            Rad values\n\n        Returns\n        -------\n        psf3d : `~gammapy.irf.PSF3D`\n            PSF3D.\n        \"\"\"\n        from gammapy.datasets.map import RAD_AXIS_DEFAULT\n        from gammapy.irf import PSF3D\n\n        offset_axis = self.axes[\"offset\"]\n        energy_axis_true = self.axes[\"energy_true\"]\n\n        if rad is None:\n            rad_axis = RAD_AXIS_DEFAULT.center\n        else:\n            rad_axis = MapAxis.from_edges(rad, name=\"rad\")\n\n        axes = MapAxes([energy_axis_true, offset_axis, rad_axis])\n        data = self.evaluate(**axes.get_coord())\n\n        return PSF3D(axes=axes, data=data.value, unit=data.unit, meta=self.meta.copy())\n\n    def __str__(self):\n        str_ = f\"{self.__class__.__name__}\\n\"\n        str_ += \"-\" * len(self.__class__.__name__) + \"\\n\\n\"\n        str_ += f\"\\taxes      : {self.axes.names}\\n\"\n        str_ += f\"\\tshape     : {self.data.shape}\\n\"\n        str_ += f\"\\tndim      : {len(self.axes)}\\n\"\n        str_ += f\"\\tparameters: {self.required_parameters}\\n\"\n        return str_.expandtabs(tabsize=2)\n\n    def containment(self, rad, **kwargs):\n        \"\"\"Containment of the PSF at given axes coordinates\n\n        Parameters\n        ----------\n        rad : `~astropy.units.Quantity`\n            Rad value\n        **kwargs : dict\n            Other coordinates\n\n        Returns\n        -------\n        containment : `~numpy.ndarray`\n            Containment\n        \"\"\"\n        pars = self.evaluate_parameters(**kwargs)\n        containment = self.evaluate_containment(rad=rad, **pars)\n        return containment\n\n    def evaluate(self, rad, **kwargs):\n        \"\"\"Evaluate the PSF model.\n\n        Parameters\n        ----------\n        rad : `~astropy.coordinates.Angle`\n            Offset from PSF center used for evaluating the PSF on a grid\n        **kwargs : dict\n            Other coordinates\n\n        Returns\n        -------\n        psf_value : `~astropy.units.Quantity`\n            PSF value\n        \"\"\"\n        pars = self.evaluate_parameters(**kwargs)\n        value = self.evaluate_direct(rad=rad, **pars)\n        return value\n\n\ndef get_sigmas_and_norms(**kwargs):\n    \"\"\"Convert scale and amplitude to norms\"\"\"\n    sigmas = u.Quantity([kwargs[f\"sigma_{idx}\"] for idx in [1, 2, 3]])\n\n    scale = kwargs[\"scale\"]\n    ones = np.ones(scale.shape)\n    amplitudes = u.Quantity([ones, kwargs[\"ampl_2\"], kwargs[\"ampl_3\"]])\n    norms = 2 * scale * amplitudes * sigmas ** 2\n    return sigmas, norms\n\n\nclass EnergyDependentMultiGaussPSF(ParametricPSF):\n    \"\"\"Triple Gauss analytical PSF depending on true energy and offset.\n\n    Parameters\n    ----------\n    axes : list of `MapAxis`\n        Required axes are [\"energy_true\", \"offset\"]\n    data : `~numpy.recarray`\n        Data array\n    meta : dict\n        Meta data\n\n    Examples\n    --------\n    Plot R68 of the PSF vs. offset and true energy:\n\n    .. plot::\n        :include-source:\n\n        import matplotlib.pyplot as plt\n        from gammapy.irf import EnergyDependentMultiGaussPSF\n        filename = '$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits'\n        psf = EnergyDependentMultiGaussPSF.read(filename, hdu='POINT SPREAD FUNCTION')\n        psf.plot_containment_radius(fraction=0.68)\n        plt.show()\n    \"\"\"\n\n    tag = \"psf_3gauss\"\n    required_axes = [\"energy_true\", \"offset\"]\n    required_parameters = [\"sigma_1\", \"sigma_2\", \"sigma_3\", \"scale\", \"ampl_2\", \"ampl_3\"]\n\n    @staticmethod\n    def evaluate_containment(rad, **kwargs):\n        \"\"\"Containment of the PSF at given axes coordinates\n\n        Parameters\n        ----------\n        rad : `~astropy.units.Quantity`\n            Rad value\n        **kwargs : dict\n            Parameters, see `required_parameters`\n\n        Returns\n        -------\n        containment : `~numpy.ndarray`\n            Containment\n        \"\"\"\n        sigmas, norms = get_sigmas_and_norms(**kwargs)\n        m = MultiGauss2D(sigmas=sigmas, norms=norms)\n        m.normalize()\n        containment = m.containment_fraction(rad)\n        return containment\n\n    @staticmethod\n    def evaluate_direct(rad, **kwargs):\n        \"\"\"Evaluate psf model\n\n        Parameters\n        ----------\n        rad : `~astropy.units.Quantity`\n            Rad value\n        **kwargs : dict\n            Parameters, see `required_parameters`\n\n        Returns\n        -------\n        value : `~numpy.ndarray`\n            PSF value\n        \"\"\"\n        sigmas, norms = get_sigmas_and_norms(**kwargs)\n        m = MultiGauss2D(sigmas=sigmas, norms=norms)\n        m.normalize()\n        return m(rad)\n\n\nclass PSFKing(ParametricPSF):\n    \"\"\"King profile analytical PSF depending on energy and offset.\n\n    This PSF parametrisation and FITS data format is described here: :ref:`gadf:psf_king`.\n\n    Parameters\n    ----------\n    axes : list of `MapAxis` or `MapAxes`\n        Data axes, required are [\"energy_true\", \"offset\"]\n    meta : dict\n        Meta data\n\n    \"\"\"\n\n    tag = \"psf_king\"\n    required_axes = [\"energy_true\", \"offset\"]\n    required_parameters = [\"gamma\", \"sigma\"]\n    default_interp_kwargs = dict(bounds_error=False, fill_value=None)\n\n    @staticmethod\n    def evaluate_containment(rad, gamma, sigma):\n        \"\"\"Containment of the PSF at given axes coordinates\n\n        Parameters\n        ----------\n        rad : `~astropy.units.Quantity`\n            Rad value\n        gamma : `~astropy.units.Quantity`\n            Gamma parameter\n        sigma : `~astropy.units.Quantity`\n            Sigma parameter\n\n        Returns\n        -------\n        containment : `~numpy.ndarray`\n            Containment\n        \"\"\"\n        with np.errstate(divide=\"ignore\", invalid=\"ignore\"):\n            term_1 = -((1 + rad ** 2 / (2 * gamma * sigma ** 2)) ** -gamma)\n            term_2 = rad ** 2 + 2 * gamma * sigma ** 2\n            term_3 = 2 * gamma * sigma ** 2\n            containment = term_1 * term_2 / term_3\n\n        return containment\n\n    @staticmethod\n    def evaluate_direct(rad, gamma, sigma):\n        \"\"\"Evaluate the PSF model.\n\n        Formula is given here: :ref:`gadf:psf_king`.\n\n        Parameters\n        ----------\n        rad : `~astropy.coordinates.Angle`\n            Offset from PSF center used for evaluating the PSF on a grid\n\n        Returns\n        -------\n        psf_value : `~astropy.units.Quantity`\n            PSF value\n        \"\"\"\n        with np.errstate(divide=\"ignore\"):\n            term1 = 1 / (2 * np.pi * sigma ** 2)\n            term2 = 1 - 1 / gamma\n            term3 = (1 + rad ** 2 / (2 * gamma * sigma ** 2)) ** (-gamma)\n\n        return term1 * term2 * term3\n", "meta": {"hexsha": "7329124c7028f4d055ad58c10bd8953b35927631", "size": 11375, "ext": "py", "lang": "Python", "max_stars_repo_path": "gammapy/irf/psf/parametric.py", "max_stars_repo_name": "Rishank2610/gammapy", "max_stars_repo_head_hexsha": "3cd64fdb2c53c8e5c697a9b85ef8d0486bff0b76", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-11-22T17:07:56.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-22T17:07:56.000Z", "max_issues_repo_path": "gammapy/irf/psf/parametric.py", "max_issues_repo_name": "Rishank2610/gammapy", "max_issues_repo_head_hexsha": "3cd64fdb2c53c8e5c697a9b85ef8d0486bff0b76", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gammapy/irf/psf/parametric.py", "max_forks_repo_name": "Rishank2610/gammapy", "max_forks_repo_head_hexsha": "3cd64fdb2c53c8e5c697a9b85ef8d0486bff0b76", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-04T14:03:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-04T14:03:33.000Z", "avg_line_length": 28.1559405941, "max_line_length": 93, "alphanum_fraction": 0.5741538462, "include": true, "reason": "import numpy,from astropy", "num_tokens": 2729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.19460230820929084}}
{"text": "\"\"\"\nCalculate the solar position using the NREL SPA algorithm either using\nnumpy arrays or compiling the code to machine language with numba.\n\"\"\"\n\n# Contributors:\n# Created by Tony Lorenzo (@alorenzo175), Univ. of Arizona, 2015\n\nfrom __future__ import division\nimport os\nimport threading\nimport warnings\n\nimport numpy as np\n\n\n# this block is a way to use an environment variable to switch between\n# compiling the functions with numba or just use numpy\ndef nocompile(*args, **kwargs):\n    return lambda func: func\n\n\nif os.getenv('PVLIB_USE_NUMBA', '0') != '0':\n    try:\n        from numba import jit, __version__\n    except ImportError:\n        warnings.warn('Could not import numba, falling back to numpy ' +\n                      'calculation')\n        jcompile = nocompile\n        USE_NUMBA = False\n    else:\n        major, minor = __version__.split('.')[:2]\n        if int(major + minor) >= 17:\n            # need at least numba >= 0.17.0\n            jcompile = jit\n            USE_NUMBA = True\n        else:\n            warnings.warn('Numba version must be >= 0.17.0, falling back to ' +\n                          'numpy')\n            jcompile = nocompile\n            USE_NUMBA = False\nelse:\n    jcompile = nocompile\n    USE_NUMBA = False\n\n\nTABLE_1_DICT = {\n    'L0': np.array(\n        [[175347046.0, 0.0, 0.0],\n         [3341656.0, 4.6692568, 6283.07585],\n         [34894.0, 4.6261, 12566.1517],\n         [3497.0, 2.7441, 5753.3849],\n         [3418.0, 2.8289, 3.5231],\n         [3136.0, 3.6277, 77713.7715],\n         [2676.0, 4.4181, 7860.4194],\n         [2343.0, 6.1352, 3930.2097],\n         [1324.0, 0.7425, 11506.7698],\n         [1273.0, 2.0371, 529.691],\n         [1199.0, 1.1096, 1577.3435],\n         [990.0, 5.233, 5884.927],\n         [902.0, 2.045, 26.298],\n         [857.0, 3.508, 398.149],\n         [780.0, 1.179, 5223.694],\n         [753.0, 2.533, 5507.553],\n         [505.0, 4.583, 18849.228],\n         [492.0, 4.205, 775.523],\n         [357.0, 2.92, 0.067],\n         [317.0, 5.849, 11790.629],\n         [284.0, 1.899, 796.298],\n         [271.0, 0.315, 10977.079],\n         [243.0, 0.345, 5486.778],\n         [206.0, 4.806, 2544.314],\n         [205.0, 1.869, 5573.143],\n         [202.0, 2.458, 6069.777],\n         [156.0, 0.833, 213.299],\n         [132.0, 3.411, 2942.463],\n         [126.0, 1.083, 20.775],\n         [115.0, 0.645, 0.98],\n         [103.0, 0.636, 4694.003],\n         [102.0, 0.976, 15720.839],\n         [102.0, 4.267, 7.114],\n         [99.0, 6.21, 2146.17],\n         [98.0, 0.68, 155.42],\n         [86.0, 5.98, 161000.69],\n         [85.0, 1.3, 6275.96],\n         [85.0, 3.67, 71430.7],\n         [80.0, 1.81, 17260.15],\n         [79.0, 3.04, 12036.46],\n         [75.0, 1.76, 5088.63],\n         [74.0, 3.5, 3154.69],\n         [74.0, 4.68, 801.82],\n         [70.0, 0.83, 9437.76],\n         [62.0, 3.98, 8827.39],\n         [61.0, 1.82, 7084.9],\n         [57.0, 2.78, 6286.6],\n         [56.0, 4.39, 14143.5],\n         [56.0, 3.47, 6279.55],\n         [52.0, 0.19, 12139.55],\n         [52.0, 1.33, 1748.02],\n         [51.0, 0.28, 5856.48],\n         [49.0, 0.49, 1194.45],\n         [41.0, 5.37, 8429.24],\n         [41.0, 2.4, 19651.05],\n         [39.0, 6.17, 10447.39],\n         [37.0, 6.04, 10213.29],\n         [37.0, 2.57, 1059.38],\n         [36.0, 1.71, 2352.87],\n         [36.0, 1.78, 6812.77],\n         [33.0, 0.59, 17789.85],\n         [30.0, 0.44, 83996.85],\n         [30.0, 2.74, 1349.87],\n         [25.0, 3.16, 4690.48]]),\n    'L1': np.array(\n        [[628331966747.0, 0.0, 0.0],\n         [206059.0, 2.678235, 6283.07585],\n         [4303.0, 2.6351, 12566.1517],\n         [425.0, 1.59, 3.523],\n         [119.0, 5.796, 26.298],\n         [109.0, 2.966, 1577.344],\n         [93.0, 2.59, 18849.23],\n         [72.0, 1.14, 529.69],\n         [68.0, 1.87, 398.15],\n         [67.0, 4.41, 5507.55],\n         [59.0, 2.89, 5223.69],\n         [56.0, 2.17, 155.42],\n         [45.0, 0.4, 796.3],\n         [36.0, 0.47, 775.52],\n         [29.0, 2.65, 7.11],\n         [21.0, 5.34, 0.98],\n         [19.0, 1.85, 5486.78],\n         [19.0, 4.97, 213.3],\n         [17.0, 2.99, 6275.96],\n         [16.0, 0.03, 2544.31],\n         [16.0, 1.43, 2146.17],\n         [15.0, 1.21, 10977.08],\n         [12.0, 2.83, 1748.02],\n         [12.0, 3.26, 5088.63],\n         [12.0, 5.27, 1194.45],\n         [12.0, 2.08, 4694.0],\n         [11.0, 0.77, 553.57],\n         [10.0, 1.3, 6286.6],\n         [10.0, 4.24, 1349.87],\n         [9.0, 2.7, 242.73],\n         [9.0, 5.64, 951.72],\n         [8.0, 5.3, 2352.87],\n         [6.0, 2.65, 9437.76],\n         [6.0, 4.67, 4690.48]]),\n    'L2': np.array(\n        [[52919.0, 0.0, 0.0],\n         [8720.0, 1.0721, 6283.0758],\n         [309.0, 0.867, 12566.152],\n         [27.0, 0.05, 3.52],\n         [16.0, 5.19, 26.3],\n         [16.0, 3.68, 155.42],\n         [10.0, 0.76, 18849.23],\n         [9.0, 2.06, 77713.77],\n         [7.0, 0.83, 775.52],\n         [5.0, 4.66, 1577.34],\n         [4.0, 1.03, 7.11],\n         [4.0, 3.44, 5573.14],\n         [3.0, 5.14, 796.3],\n         [3.0, 6.05, 5507.55],\n         [3.0, 1.19, 242.73],\n         [3.0, 6.12, 529.69],\n         [3.0, 0.31, 398.15],\n         [3.0, 2.28, 553.57],\n         [2.0, 4.38, 5223.69],\n         [2.0, 3.75, 0.98]]),\n    'L3': np.array(\n        [[289.0, 5.844, 6283.076],\n         [35.0, 0.0, 0.0],\n         [17.0, 5.49, 12566.15],\n         [3.0, 5.2, 155.42],\n         [1.0, 4.72, 3.52],\n         [1.0, 5.3, 18849.23],\n         [1.0, 5.97, 242.73]]),\n    'L4': np.array(\n        [[114.0, 3.142, 0.0],\n         [8.0, 4.13, 6283.08],\n         [1.0, 3.84, 12566.15]]),\n    'L5': np.array(\n        [[1.0, 3.14, 0.0]]),\n    'B0': np.array(\n        [[280.0, 3.199, 84334.662],\n         [102.0, 5.422, 5507.553],\n         [80.0, 3.88, 5223.69],\n         [44.0, 3.7, 2352.87],\n         [32.0, 4.0, 1577.34]]),\n    'B1': np.array(\n        [[9.0, 3.9, 5507.55],\n         [6.0, 1.73, 5223.69]]),\n    'R0': np.array(\n        [[100013989.0, 0.0, 0.0],\n         [1670700.0, 3.0984635, 6283.07585],\n         [13956.0, 3.05525, 12566.1517],\n         [3084.0, 5.1985, 77713.7715],\n         [1628.0, 1.1739, 5753.3849],\n         [1576.0, 2.8469, 7860.4194],\n         [925.0, 5.453, 11506.77],\n         [542.0, 4.564, 3930.21],\n         [472.0, 3.661, 5884.927],\n         [346.0, 0.964, 5507.553],\n         [329.0, 5.9, 5223.694],\n         [307.0, 0.299, 5573.143],\n         [243.0, 4.273, 11790.629],\n         [212.0, 5.847, 1577.344],\n         [186.0, 5.022, 10977.079],\n         [175.0, 3.012, 18849.228],\n         [110.0, 5.055, 5486.778],\n         [98.0, 0.89, 6069.78],\n         [86.0, 5.69, 15720.84],\n         [86.0, 1.27, 161000.69],\n         [65.0, 0.27, 17260.15],\n         [63.0, 0.92, 529.69],\n         [57.0, 2.01, 83996.85],\n         [56.0, 5.24, 71430.7],\n         [49.0, 3.25, 2544.31],\n         [47.0, 2.58, 775.52],\n         [45.0, 5.54, 9437.76],\n         [43.0, 6.01, 6275.96],\n         [39.0, 5.36, 4694.0],\n         [38.0, 2.39, 8827.39],\n         [37.0, 0.83, 19651.05],\n         [37.0, 4.9, 12139.55],\n         [36.0, 1.67, 12036.46],\n         [35.0, 1.84, 2942.46],\n         [33.0, 0.24, 7084.9],\n         [32.0, 0.18, 5088.63],\n         [32.0, 1.78, 398.15],\n         [28.0, 1.21, 6286.6],\n         [28.0, 1.9, 6279.55],\n         [26.0, 4.59, 10447.39]]),\n    'R1': np.array(\n        [[103019.0, 1.10749, 6283.07585],\n         [1721.0, 1.0644, 12566.1517],\n         [702.0, 3.142, 0.0],\n         [32.0, 1.02, 18849.23],\n         [31.0, 2.84, 5507.55],\n         [25.0, 1.32, 5223.69],\n         [18.0, 1.42, 1577.34],\n         [10.0, 5.91, 10977.08],\n         [9.0, 1.42, 6275.96],\n         [9.0, 0.27, 5486.78]]),\n    'R2': np.array(\n        [[4359.0, 5.7846, 6283.0758],\n         [124.0, 5.579, 12566.152],\n         [12.0, 3.14, 0.0],\n         [9.0, 3.63, 77713.77],\n         [6.0, 1.87, 5573.14],\n         [3.0, 5.47, 18849.23]]),\n    'R3': np.array(\n        [[145.0, 4.273, 6283.076],\n         [7.0, 3.92, 12566.15]]),\n    'R4': np.array(\n        [[4.0, 2.56, 6283.08]])\n}\n\n\nTABLE_1_DICT['L1'].resize((64, 3))\nTABLE_1_DICT['L2'].resize((64, 3))\nTABLE_1_DICT['L3'].resize((64, 3))\nTABLE_1_DICT['L4'].resize((64, 3))\nTABLE_1_DICT['L5'].resize((64, 3))\n\nTABLE_1_DICT['B1'].resize((5, 3))\n\nTABLE_1_DICT['R1'].resize((40, 3))\nTABLE_1_DICT['R2'].resize((40, 3))\nTABLE_1_DICT['R3'].resize((40, 3))\nTABLE_1_DICT['R4'].resize((40, 3))\n\n\nHELIO_LONG_TABLE = np.array([TABLE_1_DICT['L0'],\n                             TABLE_1_DICT['L1'],\n                             TABLE_1_DICT['L2'],\n                             TABLE_1_DICT['L3'],\n                             TABLE_1_DICT['L4'],\n                             TABLE_1_DICT['L5']])\n\n\nHELIO_LAT_TABLE = np.array([TABLE_1_DICT['B0'],\n                            TABLE_1_DICT['B1']])\n\n\nHELIO_RADIUS_TABLE = np.array([TABLE_1_DICT['R0'],\n                               TABLE_1_DICT['R1'],\n                               TABLE_1_DICT['R2'],\n                               TABLE_1_DICT['R3'],\n                               TABLE_1_DICT['R4']])\n\n\nNUTATION_ABCD_ARRAY = np.array([\n    [-171996, -174.2, 92025, 8.9],\n    [-13187, -1.6, 5736, -3.1],\n    [-2274, -0.2, 977, -0.5],\n    [2062, 0.2, -895, 0.5],\n    [1426, -3.4, 54, -0.1],\n    [712, 0.1, -7, 0],\n    [-517, 1.2, 224, -0.6],\n    [-386, -0.4, 200, 0],\n    [-301, 0, 129, -0.1],\n    [217, -0.5, -95, 0.3],\n    [-158, 0, 0, 0],\n    [129, 0.1, -70, 0],\n    [123, 0, -53, 0],\n    [63, 0, 0, 0],\n    [63, 0.1, -33, 0],\n    [-59, 0, 26, 0],\n    [-58, -0.1, 32, 0],\n    [-51, 0, 27, 0],\n    [48, 0, 0, 0],\n    [46, 0, -24, 0],\n    [-38, 0, 16, 0],\n    [-31, 0, 13, 0],\n    [29, 0, 0, 0],\n    [29, 0, -12, 0],\n    [26, 0, 0, 0],\n    [-22, 0, 0, 0],\n    [21, 0, -10, 0],\n    [17, -0.1, 0, 0],\n    [16, 0, -8, 0],\n    [-16, 0.1, 7, 0],\n    [-15, 0, 9, 0],\n    [-13, 0, 7, 0],\n    [-12, 0, 6, 0],\n    [11, 0, 0, 0],\n    [-10, 0, 5, 0],\n    [-8, 0, 3, 0],\n    [7, 0, -3, 0],\n    [-7, 0, 0, 0],\n    [-7, 0, 3, 0],\n    [-7, 0, 3, 0],\n    [6, 0, 0, 0],\n    [6, 0, -3, 0],\n    [6, 0, -3, 0],\n    [-6, 0, 3, 0],\n    [-6, 0, 3, 0],\n    [5, 0, 0, 0],\n    [-5, 0, 3, 0],\n    [-5, 0, 3, 0],\n    [-5, 0, 3, 0],\n    [4, 0, 0, 0],\n    [4, 0, 0, 0],\n    [4, 0, 0, 0],\n    [-4, 0, 0, 0],\n    [-4, 0, 0, 0],\n    [-4, 0, 0, 0],\n    [3, 0, 0, 0],\n    [-3, 0, 0, 0],\n    [-3, 0, 0, 0],\n    [-3, 0, 0, 0],\n    [-3, 0, 0, 0],\n    [-3, 0, 0, 0],\n    [-3, 0, 0, 0],\n    [-3, 0, 0, 0],\n])\n\n\nNUTATION_YTERM_ARRAY = np.array([\n    [0, 0, 0, 0, 1],\n    [-2, 0, 0, 2, 2],\n    [0, 0, 0, 2, 2],\n    [0, 0, 0, 0, 2],\n    [0, 1, 0, 0, 0],\n    [0, 0, 1, 0, 0],\n    [-2, 1, 0, 2, 2],\n    [0, 0, 0, 2, 1],\n    [0, 0, 1, 2, 2],\n    [-2, -1, 0, 2, 2],\n    [-2, 0, 1, 0, 0],\n    [-2, 0, 0, 2, 1],\n    [0, 0, -1, 2, 2],\n    [2, 0, 0, 0, 0],\n    [0, 0, 1, 0, 1],\n    [2, 0, -1, 2, 2],\n    [0, 0, -1, 0, 1],\n    [0, 0, 1, 2, 1],\n    [-2, 0, 2, 0, 0],\n    [0, 0, -2, 2, 1],\n    [2, 0, 0, 2, 2],\n    [0, 0, 2, 2, 2],\n    [0, 0, 2, 0, 0],\n    [-2, 0, 1, 2, 2],\n    [0, 0, 0, 2, 0],\n    [-2, 0, 0, 2, 0],\n    [0, 0, -1, 2, 1],\n    [0, 2, 0, 0, 0],\n    [2, 0, -1, 0, 1],\n    [-2, 2, 0, 2, 2],\n    [0, 1, 0, 0, 1],\n    [-2, 0, 1, 0, 1],\n    [0, -1, 0, 0, 1],\n    [0, 0, 2, -2, 0],\n    [2, 0, -1, 2, 1],\n    [2, 0, 1, 2, 2],\n    [0, 1, 0, 2, 2],\n    [-2, 1, 1, 0, 0],\n    [0, -1, 0, 2, 2],\n    [2, 0, 0, 2, 1],\n    [2, 0, 1, 0, 0],\n    [-2, 0, 2, 2, 2],\n    [-2, 0, 1, 2, 1],\n    [2, 0, -2, 0, 1],\n    [2, 0, 0, 0, 1],\n    [0, -1, 1, 0, 0],\n    [-2, -1, 0, 2, 1],\n    [-2, 0, 0, 0, 1],\n    [0, 0, 2, 2, 1],\n    [-2, 0, 2, 0, 1],\n    [-2, 1, 0, 2, 1],\n    [0, 0, 1, -2, 0],\n    [-1, 0, 1, 0, 0],\n    [-2, 1, 0, 0, 0],\n    [1, 0, 0, 0, 0],\n    [0, 0, 1, 2, 0],\n    [0, 0, -2, 2, 2],\n    [-1, -1, 1, 0, 0],\n    [0, 1, 1, 0, 0],\n    [0, -1, 1, 2, 2],\n    [2, -1, -1, 2, 2],\n    [0, 0, 3, 2, 2],\n    [2, -1, 0, 2, 2],\n])\n\n\n@jcompile('float64(int64, int64, int64, int64, int64, int64, int64)',\n          nopython=True)\ndef julian_day_dt(year, month, day, hour, minute, second, microsecond):\n    \"\"\"This is the original way to calculate the julian day from the NREL paper.\n    However, it is much faster to convert to unix/epoch time and then convert\n    to julian day. Note that the date must be UTC.\"\"\"\n    if month <= 2:\n        year = year-1\n        month = month+12\n    a = int(year/100)\n    b = 2 - a + int(a * 0.25)\n    frac_of_day = (microsecond + (second + minute * 60 + hour * 3600)\n                   ) * 1.0 / (3600*24)\n    d = day + frac_of_day\n    jd = (int(365.25 * (year + 4716)) + int(30.6001 * (month + 1)) + d +\n          b - 1524.5)\n    return jd\n\n\n@jcompile('float64(float64)', nopython=True)\ndef julian_day(unixtime):\n    jd = unixtime * 1.0 / 86400 + 2440587.5\n    return jd\n\n\n@jcompile('float64(float64, float64)', nopython=True)\ndef julian_ephemeris_day(julian_day, delta_t):\n    jde = julian_day + delta_t * 1.0 / 86400\n    return jde\n\n\n@jcompile('float64(float64)', nopython=True)\ndef julian_century(julian_day):\n    jc = (julian_day - 2451545) * 1.0 / 36525\n    return jc\n\n\n@jcompile('float64(float64)', nopython=True)\ndef julian_ephemeris_century(julian_ephemeris_day):\n    jce = (julian_ephemeris_day - 2451545) * 1.0 / 36525\n    return jce\n\n\n@jcompile('float64(float64)', nopython=True)\ndef julian_ephemeris_millennium(julian_ephemeris_century):\n    jme = julian_ephemeris_century * 1.0 / 10\n    return jme\n\n\n@jcompile('float64(float64)', nopython=True)\ndef heliocentric_longitude(jme):\n    l0 = 0.0\n    l1 = 0.0\n    l2 = 0.0\n    l3 = 0.0\n    l4 = 0.0\n    l5 = 0.0\n\n    for row in range(HELIO_LONG_TABLE.shape[1]):\n        l0 += (HELIO_LONG_TABLE[0, row, 0]\n               * np.cos(HELIO_LONG_TABLE[0, row, 1]\n                        + HELIO_LONG_TABLE[0, row, 2] * jme)\n               )\n        l1 += (HELIO_LONG_TABLE[1, row, 0]\n               * np.cos(HELIO_LONG_TABLE[1, row, 1]\n                        + HELIO_LONG_TABLE[1, row, 2] * jme)\n               )\n        l2 += (HELIO_LONG_TABLE[2, row, 0]\n               * np.cos(HELIO_LONG_TABLE[2, row, 1]\n                        + HELIO_LONG_TABLE[2, row, 2] * jme)\n               )\n        l3 += (HELIO_LONG_TABLE[3, row, 0]\n               * np.cos(HELIO_LONG_TABLE[3, row, 1]\n                        + HELIO_LONG_TABLE[3, row, 2] * jme)\n               )\n        l4 += (HELIO_LONG_TABLE[4, row, 0]\n               * np.cos(HELIO_LONG_TABLE[4, row, 1]\n                        + HELIO_LONG_TABLE[4, row, 2] * jme)\n               )\n        l5 += (HELIO_LONG_TABLE[5, row, 0]\n               * np.cos(HELIO_LONG_TABLE[5, row, 1]\n                        + HELIO_LONG_TABLE[5, row, 2] * jme)\n               )\n\n    l_rad = (l0 + l1 * jme + l2 * jme**2 + l3 * jme**3 + l4 * jme**4 +\n             l5 * jme**5)/10**8\n    l = np.rad2deg(l_rad)\n    return l % 360\n\n\n@jcompile('float64(float64)', nopython=True)\ndef heliocentric_latitude(jme):\n    b0 = 0.0\n    b1 = 0.0\n    for row in range(HELIO_LAT_TABLE.shape[1]):\n        b0 += (HELIO_LAT_TABLE[0, row, 0]\n               * np.cos(HELIO_LAT_TABLE[0, row, 1]\n                        + HELIO_LAT_TABLE[0, row, 2] * jme)\n               )\n        b1 += (HELIO_LAT_TABLE[1, row, 0]\n               * np.cos(HELIO_LAT_TABLE[1, row, 1]\n                        + HELIO_LAT_TABLE[1, row, 2] * jme)\n               )\n\n    b_rad = (b0 + b1 * jme)/10**8\n    b = np.rad2deg(b_rad)\n    return b\n\n\n@jcompile('float64(float64)', nopython=True)\ndef heliocentric_radius_vector(jme):\n    r0 = 0.0\n    r1 = 0.0\n    r2 = 0.0\n    r3 = 0.0\n    r4 = 0.0\n    for row in range(HELIO_RADIUS_TABLE.shape[1]):\n        r0 += (HELIO_RADIUS_TABLE[0, row, 0]\n               * np.cos(HELIO_RADIUS_TABLE[0, row, 1]\n                        + HELIO_RADIUS_TABLE[0, row, 2] * jme)\n               )\n        r1 += (HELIO_RADIUS_TABLE[1, row, 0]\n               * np.cos(HELIO_RADIUS_TABLE[1, row, 1]\n                        + HELIO_RADIUS_TABLE[1, row, 2] * jme)\n               )\n        r2 += (HELIO_RADIUS_TABLE[2, row, 0]\n               * np.cos(HELIO_RADIUS_TABLE[2, row, 1]\n                        + HELIO_RADIUS_TABLE[2, row, 2] * jme)\n               )\n        r3 += (HELIO_RADIUS_TABLE[3, row, 0]\n               * np.cos(HELIO_RADIUS_TABLE[3, row, 1]\n                        + HELIO_RADIUS_TABLE[3, row, 2] * jme)\n               )\n        r4 += (HELIO_RADIUS_TABLE[4, row, 0]\n               * np.cos(HELIO_RADIUS_TABLE[4, row, 1]\n                        + HELIO_RADIUS_TABLE[4, row, 2] * jme)\n               )\n\n    r = (r0 + r1 * jme + r2 * jme**2 + r3 * jme**3 + r4 * jme**4)/10**8\n    return r\n\n\n@jcompile('float64(float64)', nopython=True)\ndef geocentric_longitude(heliocentric_longitude):\n    theta = heliocentric_longitude + 180.0\n    return theta % 360\n\n\n@jcompile('float64(float64)', nopython=True)\ndef geocentric_latitude(heliocentric_latitude):\n    beta = -1.0*heliocentric_latitude\n    return beta\n\n\n@jcompile('float64(float64)', nopython=True)\ndef mean_elongation(julian_ephemeris_century):\n    x0 = (297.85036\n          + 445267.111480 * julian_ephemeris_century\n          - 0.0019142 * julian_ephemeris_century**2\n          + julian_ephemeris_century**3 / 189474)\n    return x0\n\n\n@jcompile('float64(float64)', nopython=True)\ndef mean_anomaly_sun(julian_ephemeris_century):\n    x1 = (357.52772\n          + 35999.050340 * julian_ephemeris_century\n          - 0.0001603 * julian_ephemeris_century**2\n          - julian_ephemeris_century**3 / 300000)\n    return x1\n\n\n@jcompile('float64(float64)', nopython=True)\ndef mean_anomaly_moon(julian_ephemeris_century):\n    x2 = (134.96298\n          + 477198.867398 * julian_ephemeris_century\n          + 0.0086972 * julian_ephemeris_century**2\n          + julian_ephemeris_century**3 / 56250)\n    return x2\n\n\n@jcompile('float64(float64)', nopython=True)\ndef moon_argument_latitude(julian_ephemeris_century):\n    x3 = (93.27191\n          + 483202.017538 * julian_ephemeris_century\n          - 0.0036825 * julian_ephemeris_century**2\n          + julian_ephemeris_century**3 / 327270)\n    return x3\n\n\n@jcompile('float64(float64)', nopython=True)\ndef moon_ascending_longitude(julian_ephemeris_century):\n    x4 = (125.04452\n          - 1934.136261 * julian_ephemeris_century\n          + 0.0020708 * julian_ephemeris_century**2\n          + julian_ephemeris_century**3 / 450000)\n    return x4\n\n\n@jcompile('float64(float64, float64, float64, float64, float64, float64)',\n          nopython=True)\ndef longitude_nutation(julian_ephemeris_century, x0, x1, x2, x3, x4):\n    delta_psi_sum = 0\n    for row in range(NUTATION_YTERM_ARRAY.shape[0]):\n        a = NUTATION_ABCD_ARRAY[row, 0]\n        b = NUTATION_ABCD_ARRAY[row, 1]\n        argsin = (NUTATION_YTERM_ARRAY[row, 0]*x0 +\n                  NUTATION_YTERM_ARRAY[row, 1]*x1 +\n                  NUTATION_YTERM_ARRAY[row, 2]*x2 +\n                  NUTATION_YTERM_ARRAY[row, 3]*x3 +\n                  NUTATION_YTERM_ARRAY[row, 4]*x4)\n        term = (a + b * julian_ephemeris_century) * np.sin(np.radians(argsin))\n        delta_psi_sum += term\n    delta_psi = delta_psi_sum*1.0/36000000\n    return delta_psi\n\n\n@jcompile('float64(float64, float64, float64, float64, float64, float64)',\n          nopython=True)\ndef obliquity_nutation(julian_ephemeris_century, x0, x1, x2, x3, x4):\n    delta_eps_sum = 0.0\n    for row in range(NUTATION_YTERM_ARRAY.shape[0]):\n        c = NUTATION_ABCD_ARRAY[row, 2]\n        d = NUTATION_ABCD_ARRAY[row, 3]\n        argcos = (NUTATION_YTERM_ARRAY[row, 0]*x0 +\n                  NUTATION_YTERM_ARRAY[row, 1]*x1 +\n                  NUTATION_YTERM_ARRAY[row, 2]*x2 +\n                  NUTATION_YTERM_ARRAY[row, 3]*x3 +\n                  NUTATION_YTERM_ARRAY[row, 4]*x4)\n        term = (c + d * julian_ephemeris_century) * np.cos(np.radians(argcos))\n        delta_eps_sum += term\n    delta_eps = delta_eps_sum*1.0/36000000\n    return delta_eps\n\n\n@jcompile('float64(float64)', nopython=True)\ndef mean_ecliptic_obliquity(julian_ephemeris_millennium):\n    U = 1.0*julian_ephemeris_millennium/10\n    e0 = (84381.448 - 4680.93 * U - 1.55 * U**2\n          + 1999.25 * U**3 - 51.38 * U**4 - 249.67 * U**5\n          - 39.05 * U**6 + 7.12 * U**7 + 27.87 * U**8\n          + 5.79 * U**9 + 2.45 * U**10)\n    return e0\n\n\n@jcompile('float64(float64, float64)', nopython=True)\ndef true_ecliptic_obliquity(mean_ecliptic_obliquity, obliquity_nutation):\n    e0 = mean_ecliptic_obliquity\n    deleps = obliquity_nutation\n    e = e0*1.0/3600 + deleps\n    return e\n\n\n@jcompile('float64(float64)', nopython=True)\ndef aberration_correction(earth_radius_vector):\n    deltau = -20.4898 / (3600 * earth_radius_vector)\n    return deltau\n\n\n@jcompile('float64(float64, float64, float64)', nopython=True)\ndef apparent_sun_longitude(geocentric_longitude, longitude_nutation,\n                           aberration_correction):\n    lamd = geocentric_longitude + longitude_nutation + aberration_correction\n    return lamd\n\n\n@jcompile('float64(float64, float64)', nopython=True)\ndef mean_sidereal_time(julian_day, julian_century):\n    v0 = (280.46061837 + 360.98564736629 * (julian_day - 2451545)\n          + 0.000387933 * julian_century**2 - julian_century**3 / 38710000)\n    return v0 % 360.0\n\n\n@jcompile('float64(float64, float64, float64)', nopython=True)\ndef apparent_sidereal_time(mean_sidereal_time, longitude_nutation,\n                           true_ecliptic_obliquity):\n    v = mean_sidereal_time + longitude_nutation * np.cos(\n        np.radians(true_ecliptic_obliquity))\n    return v\n\n\n@jcompile('float64(float64, float64, float64)', nopython=True)\ndef geocentric_sun_right_ascension(apparent_sun_longitude,\n                                   true_ecliptic_obliquity,\n                                   geocentric_latitude):\n    num = (np.sin(np.radians(apparent_sun_longitude))\n           * np.cos(np.radians(true_ecliptic_obliquity))\n           - np.tan(np.radians(geocentric_latitude))\n           * np.sin(np.radians(true_ecliptic_obliquity)))\n    alpha = np.degrees(np.arctan2(num, np.cos(\n        np.radians(apparent_sun_longitude))))\n    return alpha % 360\n\n\n@jcompile('float64(float64, float64, float64)', nopython=True)\ndef geocentric_sun_declination(apparent_sun_longitude, true_ecliptic_obliquity,\n                               geocentric_latitude):\n    delta = np.degrees(np.arcsin(np.sin(np.radians(geocentric_latitude)) *\n                                 np.cos(np.radians(true_ecliptic_obliquity)) +\n                                 np.cos(np.radians(geocentric_latitude)) *\n                                 np.sin(np.radians(true_ecliptic_obliquity)) *\n                                 np.sin(np.radians(apparent_sun_longitude))))\n    return delta\n\n\n@jcompile('float64(float64, float64, float64)', nopython=True)\ndef local_hour_angle(apparent_sidereal_time, observer_longitude,\n                     sun_right_ascension):\n    \"\"\"Measured westward from south\"\"\"\n    H = apparent_sidereal_time + observer_longitude - sun_right_ascension\n    return H % 360\n\n\n@jcompile('float64(float64)', nopython=True)\ndef equatorial_horizontal_parallax(earth_radius_vector):\n    xi = 8.794 / (3600 * earth_radius_vector)\n    return xi\n\n\n@jcompile('float64(float64)', nopython=True)\ndef uterm(observer_latitude):\n    u = np.arctan(0.99664719 * np.tan(np.radians(observer_latitude)))\n    return u\n\n\n@jcompile('float64(float64, float64, float64)', nopython=True)\ndef xterm(u, observer_latitude, observer_elevation):\n    x = (np.cos(u) + observer_elevation / 6378140\n         * np.cos(np.radians(observer_latitude)))\n    return x\n\n\n@jcompile('float64(float64, float64, float64)', nopython=True)\ndef yterm(u, observer_latitude, observer_elevation):\n    y = (0.99664719 * np.sin(u) + observer_elevation / 6378140\n         * np.sin(np.radians(observer_latitude)))\n    return y\n\n\n@jcompile('float64(float64, float64,float64, float64)', nopython=True)\ndef parallax_sun_right_ascension(xterm, equatorial_horizontal_parallax,\n                                 local_hour_angle, geocentric_sun_declination):\n    num = (-xterm * np.sin(np.radians(equatorial_horizontal_parallax))\n           * np.sin(np.radians(local_hour_angle)))\n    denom = (np.cos(np.radians(geocentric_sun_declination))\n             - xterm * np.sin(np.radians(equatorial_horizontal_parallax))\n             * np.cos(np.radians(local_hour_angle)))\n    delta_alpha = np.degrees(np.arctan2(num, denom))\n    return delta_alpha\n\n\n@jcompile('float64(float64, float64)', nopython=True)\ndef topocentric_sun_right_ascension(geocentric_sun_right_ascension,\n                                    parallax_sun_right_ascension):\n    alpha_prime = geocentric_sun_right_ascension + parallax_sun_right_ascension\n    return alpha_prime\n\n\n@jcompile('float64(float64, float64, float64, float64, float64, float64)',\n          nopython=True)\ndef topocentric_sun_declination(geocentric_sun_declination, xterm, yterm,\n                                equatorial_horizontal_parallax,\n                                parallax_sun_right_ascension,\n                                local_hour_angle):\n    num = ((np.sin(np.radians(geocentric_sun_declination)) - yterm\n            * np.sin(np.radians(equatorial_horizontal_parallax)))\n           * np.cos(np.radians(parallax_sun_right_ascension)))\n    denom = (np.cos(np.radians(geocentric_sun_declination)) - xterm\n             * np.sin(np.radians(equatorial_horizontal_parallax))\n             * np.cos(np.radians(local_hour_angle)))\n    delta = np.degrees(np.arctan2(num, denom))\n    return delta\n\n\n@jcompile('float64(float64, float64)', nopython=True)\ndef topocentric_local_hour_angle(local_hour_angle,\n                                 parallax_sun_right_ascension):\n    H_prime = local_hour_angle - parallax_sun_right_ascension\n    return H_prime\n\n\n@jcompile('float64(float64, float64, float64)', nopython=True)\ndef topocentric_elevation_angle_without_atmosphere(observer_latitude,\n                                                   topocentric_sun_declination,\n                                                   topocentric_local_hour_angle\n                                                   ):\n    e0 = np.degrees(np.arcsin(\n        np.sin(np.radians(observer_latitude))\n        * np.sin(np.radians(topocentric_sun_declination))\n        + np.cos(np.radians(observer_latitude))\n        * np.cos(np.radians(topocentric_sun_declination))\n        * np.cos(np.radians(topocentric_local_hour_angle))))\n    return e0\n\n\n@jcompile('float64(float64, float64, float64, float64)', nopython=True)\ndef atmospheric_refraction_correction(local_pressure, local_temp,\n                                      topocentric_elevation_angle_wo_atmosphere,\n                                      atmos_refract):\n    # switch sets delta_e when the sun is below the horizon\n    switch = topocentric_elevation_angle_wo_atmosphere >= -1.0 * (\n        0.26667 + atmos_refract)\n    delta_e = ((local_pressure / 1010.0) * (283.0 / (273 + local_temp))\n               * 1.02 / (60 * np.tan(np.radians(\n                   topocentric_elevation_angle_wo_atmosphere\n                   + 10.3 / (topocentric_elevation_angle_wo_atmosphere\n                             + 5.11))))) * switch\n    return delta_e\n\n\n@jcompile('float64(float64, float64)', nopython=True)\ndef topocentric_elevation_angle(topocentric_elevation_angle_without_atmosphere,\n                                atmospheric_refraction_correction):\n    e = (topocentric_elevation_angle_without_atmosphere\n         + atmospheric_refraction_correction)\n    return e\n\n\n@jcompile('float64(float64)', nopython=True)\ndef topocentric_zenith_angle(topocentric_elevation_angle):\n    theta = 90 - topocentric_elevation_angle\n    return theta\n\n\n@jcompile('float64(float64, float64, float64)', nopython=True)\ndef topocentric_astronomers_azimuth(topocentric_local_hour_angle,\n                                    topocentric_sun_declination,\n                                    observer_latitude):\n    num = np.sin(np.radians(topocentric_local_hour_angle))\n    denom = (np.cos(np.radians(topocentric_local_hour_angle))\n             * np.sin(np.radians(observer_latitude))\n             - np.tan(np.radians(topocentric_sun_declination))\n             * np.cos(np.radians(observer_latitude)))\n    gamma = np.degrees(np.arctan2(num, denom))\n    return gamma % 360\n\n\n@jcompile('float64(float64)', nopython=True)\ndef topocentric_azimuth_angle(topocentric_astronomers_azimuth):\n    phi = topocentric_astronomers_azimuth + 180\n    return phi % 360\n\n\n@jcompile('float64(float64)', nopython=True)\ndef sun_mean_longitude(julian_ephemeris_millennium):\n    M = (280.4664567 + 360007.6982779 * julian_ephemeris_millennium\n         + 0.03032028 * julian_ephemeris_millennium**2\n         + julian_ephemeris_millennium**3 / 49931\n         - julian_ephemeris_millennium**4 / 15300\n         - julian_ephemeris_millennium**5 / 2000000)\n    return M\n\n\n@jcompile('float64(float64, float64, float64, float64)', nopython=True)\ndef equation_of_time(sun_mean_longitude, geocentric_sun_right_ascension,\n                     longitude_nutation, true_ecliptic_obliquity):\n    E = (sun_mean_longitude - 0.0057183 - geocentric_sun_right_ascension +\n         longitude_nutation * np.cos(np.radians(true_ecliptic_obliquity)))\n    # limit between 0 and 360\n    E = E % 360\n    # convert to minutes\n    E *= 4\n    greater = E > 20\n    less = E < -20\n    other = (E <= 20) & (E >= -20)\n    E = greater * (E - 1440) + less * (E + 1440) + other * E\n    return E\n\n\n@jcompile('void(float64[:], float64[:], float64[:,:])', nopython=True,\n          nogil=True)\ndef solar_position_loop(unixtime, loc_args, out):\n    \"\"\"Loop through the time array and calculate the solar position\"\"\"\n    lat = loc_args[0]\n    lon = loc_args[1]\n    elev = loc_args[2]\n    pressure = loc_args[3]\n    temp = loc_args[4]\n    delta_t = loc_args[5]\n    atmos_refract = loc_args[6]\n    sst = loc_args[7]\n    esd = loc_args[8]\n\n    for i in range(unixtime.shape[0]):\n        utime = unixtime[i]\n        jd = julian_day(utime)\n        jde = julian_ephemeris_day(jd, delta_t)\n        jc = julian_century(jd)\n        jce = julian_ephemeris_century(jde)\n        jme = julian_ephemeris_millennium(jce)\n        R = heliocentric_radius_vector(jme)\n        if esd:\n            out[0, i] = R\n            continue\n        L = heliocentric_longitude(jme)\n        B = heliocentric_latitude(jme)\n        Theta = geocentric_longitude(L)\n        beta = geocentric_latitude(B)\n        x0 = mean_elongation(jce)\n        x1 = mean_anomaly_sun(jce)\n        x2 = mean_anomaly_moon(jce)\n        x3 = moon_argument_latitude(jce)\n        x4 = moon_ascending_longitude(jce)\n        delta_psi = longitude_nutation(jce, x0, x1, x2, x3, x4)\n        delta_epsilon = obliquity_nutation(jce, x0, x1, x2, x3, x4)\n        epsilon0 = mean_ecliptic_obliquity(jme)\n        epsilon = true_ecliptic_obliquity(epsilon0, delta_epsilon)\n        delta_tau = aberration_correction(R)\n        lamd = apparent_sun_longitude(Theta, delta_psi, delta_tau)\n        v0 = mean_sidereal_time(jd, jc)\n        v = apparent_sidereal_time(v0, delta_psi, epsilon)\n        alpha = geocentric_sun_right_ascension(lamd, epsilon, beta)\n        delta = geocentric_sun_declination(lamd, epsilon, beta)\n        if sst:\n            out[0, i] = v\n            out[1, i] = alpha\n            out[2, i] = delta\n            continue\n        m = sun_mean_longitude(jme)\n        eot = equation_of_time(m, alpha, delta_psi, epsilon)\n        H = local_hour_angle(v, lon, alpha)\n        xi = equatorial_horizontal_parallax(R)\n        u = uterm(lat)\n        x = xterm(u, lat, elev)\n        y = yterm(u, lat, elev)\n        delta_alpha = parallax_sun_right_ascension(x, xi, H, delta)\n        delta_prime = topocentric_sun_declination(delta, x, y, xi, delta_alpha,\n                                                  H)\n        H_prime = topocentric_local_hour_angle(H, delta_alpha)\n        e0 = topocentric_elevation_angle_without_atmosphere(lat, delta_prime,\n                                                            H_prime)\n        delta_e = atmospheric_refraction_correction(pressure, temp, e0,\n                                                    atmos_refract)\n        e = topocentric_elevation_angle(e0, delta_e)\n        theta = topocentric_zenith_angle(e)\n        theta0 = topocentric_zenith_angle(e0)\n        gamma = topocentric_astronomers_azimuth(H_prime, delta_prime, lat)\n        phi = topocentric_azimuth_angle(gamma)\n        out[0, i] = theta\n        out[1, i] = theta0\n        out[2, i] = e\n        out[3, i] = e0\n        out[4, i] = phi\n        out[5, i] = eot\n\n\ndef solar_position_numba(unixtime, lat, lon, elev, pressure, temp, delta_t,\n                         atmos_refract, numthreads, sst=False, esd=False):\n    \"\"\"Calculate the solar position using the numba compiled functions\n    and multiple threads. Very slow if functions are not numba compiled.\n    \"\"\"\n    # these args are the same for each thread\n    loc_args = np.array([lat, lon, elev, pressure, temp, delta_t,\n                         atmos_refract, sst, esd])\n\n    # construct dims x ulength array to put the results in\n    ulength = unixtime.shape[0]\n    if sst:\n        dims = 3\n    elif esd:\n        dims = 1\n    else:\n        dims = 6\n    result = np.empty((dims, ulength), dtype=np.float64)\n\n    if unixtime.dtype != np.float64:\n        unixtime = unixtime.astype(np.float64)\n\n    if ulength < numthreads:\n        warnings.warn('The number of threads is more than the length of '\n                      'the time array. Only using %s threads.'.format(ulength))\n        numthreads = ulength\n\n    if numthreads <= 1:\n        solar_position_loop(unixtime, loc_args, result)\n        return result\n\n    # split the input and output arrays into numthreads chunks\n    split0 = np.array_split(unixtime, numthreads)\n    split2 = np.array_split(result, numthreads, axis=1)\n    chunks = [[a0, loc_args, split2[i]] for i, a0 in enumerate(split0)]\n    # Spawn one thread per chunk\n    threads = [threading.Thread(target=solar_position_loop, args=chunk)\n               for chunk in chunks]\n    for thread in threads:\n        thread.start()\n    for thread in threads:\n        thread.join()\n    return result\n\n\ndef solar_position_numpy(unixtime, lat, lon, elev, pressure, temp, delta_t,\n                         atmos_refract, numthreads, sst=False, esd=False):\n    \"\"\"Calculate the solar position assuming unixtime is a numpy array. Note\n    this function will not work if the solar position functions were\n    compiled with numba.\n    \"\"\"\n\n    jd = julian_day(unixtime)\n    jde = julian_ephemeris_day(jd, delta_t)\n    jc = julian_century(jd)\n    jce = julian_ephemeris_century(jde)\n    jme = julian_ephemeris_millennium(jce)\n    R = heliocentric_radius_vector(jme)\n    if esd:\n        return (R, )\n    L = heliocentric_longitude(jme)\n    B = heliocentric_latitude(jme)\n    Theta = geocentric_longitude(L)\n    beta = geocentric_latitude(B)\n    x0 = mean_elongation(jce)\n    x1 = mean_anomaly_sun(jce)\n    x2 = mean_anomaly_moon(jce)\n    x3 = moon_argument_latitude(jce)\n    x4 = moon_ascending_longitude(jce)\n    delta_psi = longitude_nutation(jce, x0, x1, x2, x3, x4)\n    delta_epsilon = obliquity_nutation(jce, x0, x1, x2, x3, x4)\n    epsilon0 = mean_ecliptic_obliquity(jme)\n    epsilon = true_ecliptic_obliquity(epsilon0, delta_epsilon)\n    delta_tau = aberration_correction(R)\n    lamd = apparent_sun_longitude(Theta, delta_psi, delta_tau)\n    v0 = mean_sidereal_time(jd, jc)\n    v = apparent_sidereal_time(v0, delta_psi, epsilon)\n    alpha = geocentric_sun_right_ascension(lamd, epsilon, beta)\n    delta = geocentric_sun_declination(lamd, epsilon, beta)\n    if sst:\n        return v, alpha, delta\n    m = sun_mean_longitude(jme)\n    eot = equation_of_time(m, alpha, delta_psi, epsilon)\n    H = local_hour_angle(v, lon, alpha)\n    xi = equatorial_horizontal_parallax(R)\n    u = uterm(lat)\n    x = xterm(u, lat, elev)\n    y = yterm(u, lat, elev)\n    delta_alpha = parallax_sun_right_ascension(x, xi, H, delta)\n    delta_prime = topocentric_sun_declination(delta, x, y, xi, delta_alpha, H)\n    H_prime = topocentric_local_hour_angle(H, delta_alpha)\n    e0 = topocentric_elevation_angle_without_atmosphere(lat, delta_prime,\n                                                        H_prime)\n    delta_e = atmospheric_refraction_correction(pressure, temp, e0,\n                                                atmos_refract)\n    e = topocentric_elevation_angle(e0, delta_e)\n    theta = topocentric_zenith_angle(e)\n    theta0 = topocentric_zenith_angle(e0)\n    gamma = topocentric_astronomers_azimuth(H_prime, delta_prime, lat)\n    phi = topocentric_azimuth_angle(gamma)\n    return theta, theta0, e, e0, phi, eot\n\n\ndef solar_position(unixtime, lat, lon, elev, pressure, temp, delta_t,\n                   atmos_refract, numthreads=8, sst=False, esd=False):\n\n    \"\"\"\n    Calculate the solar position using the\n    NREL SPA algorithm described in [1].\n\n    If numba is installed, the functions can be compiled\n    and the code runs quickly. If not, the functions\n    still evaluate but use numpy instead.\n\n    Parameters\n    ----------\n    unixtime : numpy array\n        Array of unix/epoch timestamps to calculate solar position for.\n        Unixtime is the number of seconds since Jan. 1, 1970 00:00:00 UTC.\n        A pandas.DatetimeIndex is easily converted using .astype(np.int64)/10**9\n    lat : float\n        Latitude to calculate solar position for\n    lon : float\n        Longitude to calculate solar position for\n    elev : float\n        Elevation of location in meters\n    pressure : int or float\n        avg. yearly pressure at location in millibars;\n        used for atmospheric correction\n    temp : int or float\n        avg. yearly temperature at location in\n        degrees C; used for atmospheric correction\n    delta_t : float, optional\n        If delta_t is None, uses spa.calculate_deltat\n        using time.year and time.month from pandas.DatetimeIndex.\n        For most simulations specifing delta_t is sufficient.\n        Difference between terrestrial time and UT1.\n        *Note: delta_t = None will break code using nrel_numba,\n        this will be fixed in a future version.\n        By default, use USNO historical data and predictions\n    atmos_refrac : float, optional\n        The approximate atmospheric refraction (in degrees)\n        at sunrise and sunset.\n    numthreads: int, optional, default 8\n        Number of threads to use for computation if numba>=0.17\n        is installed.\n    sst : bool, default False\n        If True, return only data needed for sunrise, sunset, and transit\n        calculations.\n    esd : bool, default False\n        If True, return only Earth-Sun distance in AU\n\n    Returns\n    -------\n    Numpy Array with elements:\n        apparent zenith,\n        zenith,\n        elevation,\n        apparent_elevation,\n        azimuth,\n        equation_of_time\n\n    References\n    ----------\n    [1] I. Reda and A. Andreas, Solar position algorithm for solar radiation\n    applications. Solar Energy, vol. 76, no. 5, pp. 577-589, 2004.\n\n    [2] I. Reda and A. Andreas, Corrigendum to Solar position algorithm for\n    solar radiation applications. Solar Energy, vol. 81, no. 6, p. 838, 2007.\n    \"\"\"\n    if USE_NUMBA:\n        do_calc = solar_position_numba\n    else:\n        do_calc = solar_position_numpy\n\n    result = do_calc(unixtime, lat, lon, elev, pressure,\n                     temp, delta_t, atmos_refract, numthreads,\n                     sst, esd)\n\n    if not isinstance(result, np.ndarray):\n        try:\n            result = np.array(result)\n        except Exception:\n            pass\n\n    return result\n\n\ndef transit_sunrise_sunset(dates, lat, lon, delta_t, numthreads):\n    \"\"\"\n    Calculate the sun transit, sunrise, and sunset\n    for a set of dates at a given location.\n\n    Parameters\n    ----------\n    dates : array\n        Numpy array of ints/floats corresponding to the Unix time\n        for the dates of interest, must be midnight UTC (00:00+00:00)\n        on the day of interest.\n    lat : float\n        Latitude of location to perform calculation for\n    lon : float\n        Longitude of location\n    delta_t : float\n        Difference between terrestrial time and UT. USNO has tables.\n    numthreads : int\n        Number to threads to use for calculation (if using numba)\n\n    Returns\n    -------\n    tuple : (transit, sunrise, sunset) localized to UTC\n\n    \"\"\"\n\n    if ((dates % 86400) != 0.0).any():\n        raise ValueError('Input dates must be at 00:00 UTC')\n\n    utday = (dates // 86400) * 86400\n    ttday0 = utday - delta_t\n    ttdayn1 = ttday0 - 86400\n    ttdayp1 = ttday0 + 86400\n\n    # index 0 is v, 1 is alpha, 2 is delta\n    utday_res = solar_position(utday, 0, 0, 0, 0, 0, delta_t,\n                               0, numthreads, sst=True)\n    v = utday_res[0]\n\n    ttday0_res = solar_position(ttday0, 0, 0, 0, 0, 0, delta_t,\n                                0, numthreads, sst=True)\n    ttdayn1_res = solar_position(ttdayn1, 0, 0, 0, 0, 0, delta_t,\n                                 0, numthreads, sst=True)\n    ttdayp1_res = solar_position(ttdayp1, 0, 0, 0, 0, 0, delta_t,\n                                 0, numthreads, sst=True)\n    m0 = (ttday0_res[1] - lon - v) / 360\n    cos_arg = ((np.sin(np.radians(-0.8333)) - np.sin(np.radians(lat))\n               * np.sin(np.radians(ttday0_res[2]))) /\n               (np.cos(np.radians(lat)) * np.cos(np.radians(ttday0_res[2]))))\n    cos_arg[abs(cos_arg) > 1] = np.nan\n    H0 = np.degrees(np.arccos(cos_arg)) % 180\n\n    m = np.empty((3, len(utday)))\n    m[0] = m0 % 1\n    m[1] = (m[0] - H0 / 360)\n    m[2] = (m[0] + H0 / 360)\n\n    # need to account for fractions of day that may be the next or previous\n    # day in UTC\n    add_a_day = m[2] >= 1\n    sub_a_day = m[1] < 0\n    m[1] = m[1] % 1\n    m[2] = m[2] % 1\n    vs = v + 360.985647 * m\n    n = m + delta_t / 86400\n\n    a = ttday0_res[1] - ttdayn1_res[1]\n    a[abs(a) > 2] = a[abs(a) > 2] % 1\n    ap = ttday0_res[2] - ttdayn1_res[2]\n    ap[abs(ap) > 2] = ap[abs(ap) > 2] % 1\n    b = ttdayp1_res[1] - ttday0_res[1]\n    b[abs(b) > 2] = b[abs(b) > 2] % 1\n    bp = ttdayp1_res[2] - ttday0_res[2]\n    bp[abs(bp) > 2] = bp[abs(bp) > 2] % 1\n    c = b - a\n    cp = bp - ap\n\n    alpha_prime = ttday0_res[1] + (n * (a + b + c * n)) / 2\n    delta_prime = ttday0_res[2] + (n * (ap + bp + cp * n)) / 2\n    Hp = (vs + lon - alpha_prime) % 360\n    Hp[Hp >= 180] = Hp[Hp >= 180] - 360\n\n    h = np.degrees(np.arcsin(np.sin(np.radians(lat)) *\n                             np.sin(np.radians(delta_prime)) +\n                             np.cos(np.radians(lat)) *\n                             np.cos(np.radians(delta_prime))\n                             * np.cos(np.radians(Hp))))\n\n    T = (m[0] - Hp[0] / 360) * 86400\n    R = (m[1] + (h[1] + 0.8333) / (360 * np.cos(np.radians(delta_prime[1])) *\n                                   np.cos(np.radians(lat)) *\n                                   np.sin(np.radians(Hp[1])))) * 86400\n    S = (m[2] + (h[2] + 0.8333) / (360 * np.cos(np.radians(delta_prime[2])) *\n                                   np.cos(np.radians(lat)) *\n                                   np.sin(np.radians(Hp[2])))) * 86400\n\n    S[add_a_day] += 86400\n    R[sub_a_day] -= 86400\n\n    transit = T + utday\n    sunrise = R + utday\n    sunset = S + utday\n\n    return transit, sunrise, sunset\n\n\ndef earthsun_distance(unixtime, delta_t, numthreads):\n    \"\"\"\n    Calculates the distance from the earth to the sun using the\n    NREL SPA algorithm described in [1].\n\n    Parameters\n    ----------\n    unixtime : numpy array\n        Array of unix/epoch timestamps to calculate solar position for.\n        Unixtime is the number of seconds since Jan. 1, 1970 00:00:00 UTC.\n        A pandas.DatetimeIndex is easily converted using .astype(np.int64)/10**9\n    delta_t : float\n        Difference between terrestrial time and UT. USNO has tables.\n    numthreads : int\n        Number to threads to use for calculation (if using numba)\n\n    Returns\n    -------\n    R : array\n        Earth-Sun distance in AU.\n\n    References\n    ----------\n    [1] Reda, I., Andreas, A., 2003. Solar position algorithm for solar\n    radiation applications. Technical report: NREL/TP-560- 34302. Golden,\n    USA, http://www.nrel.gov.\n    \"\"\"\n\n    R = solar_position(unixtime, 0, 0, 0, 0, 0, delta_t,\n                       0, numthreads, esd=True)[0]\n\n    return R\n\n\ndef calculate_deltat(year, month):\n    \"\"\"Calculate the difference between Terrestrial Dynamical Time (TD)\n    and Universal Time (UT).\n\n    Note: This function is not yet compatible for calculations using\n    Numba.\n\n    Equations taken from http://eclipse.gsfc.nasa.gov/SEcat5/deltatpoly.html\n    \"\"\"\n\n    plw = 'Deltat is unknown for years before -1999 and after 3000. ' \\\n          'Delta values will be calculated, but the calculations ' \\\n          'are not intended to be used for these years.'\n\n    try:\n        if np.any((year > 3000) | (year < -1999)):\n            warnings.warn(plw)\n    except ValueError:\n        if (year > 3000) | (year < -1999):\n            warnings.warn(plw)\n    except TypeError:\n        return 0\n\n    y = year + (month - 0.5)/12\n\n    deltat = np.where(year < -500,\n\n                      -20+32*((y-1820)/100)**2, 0)\n\n    deltat = np.where((-500 <= year) & (year < 500),\n\n                      10583.6-1014.41*(y/100)\n                      + 33.78311*(y/100)**2\n                      - 5.952053*(y/100)**3\n                      - 0.1798452*(y/100)**4\n                      + 0.022174192*(y/100)**5\n                      + 0.0090316521*(y/100)**6, deltat)\n\n    deltat = np.where((500 <= year) & (year < 1600),\n\n                      1574.2-556.01*((y-1000)/100)\n                      + 71.23472*((y-1000)/100)**2\n                      + 0.319781*((y-1000)/100)**3\n                      - 0.8503463*((y-1000)/100)**4\n                      - 0.005050998*((y-1000)/100)**5\n                      + 0.0083572073*((y-1000)/100)**6, deltat)\n\n    deltat = np.where((1600 <= year) & (year < 1700),\n\n                      120-0.9808*(y-1600)\n                      - 0.01532*(y-1600)**2\n                      + (y-1600)**3/7129, deltat)\n\n    deltat = np.where((1700 <= year) & (year < 1800),\n\n                      8.83+0.1603*(y-1700)\n                      - 0.0059285*(y-1700)**2\n                      + 0.00013336*(y-1700)**3\n                      - (y-1700)**4/1174000, deltat)\n\n    deltat = np.where((1800 <= year) & (year < 1860),\n\n                      13.72-0.332447*(y-1800)\n                      + 0.0068612*(y-1800)**2\n                      + 0.0041116*(y-1800)**3\n                      - 0.00037436*(y-1800)**4\n                      + 0.0000121272*(y-1800)**5\n                      - 0.0000001699*(y-1800)**6\n                      + 0.000000000875*(y-1800)**7, deltat)\n\n    deltat = np.where((1860 <= year) & (year < 1900),\n\n                      7.6+0.5737*(y-1860)\n                      - 0.251754*(y-1860)**2\n                      + 0.01680668*(y-1860)**3\n                      - 0.0004473624*(y-1860)**4\n                      + (y-1860)**5/233174, deltat)\n\n    deltat = np.where((1900 <= year) & (year < 1920),\n\n                      -2.79+1.494119*(y-1900)\n                      - 0.0598939*(y-1900)**2\n                      + 0.0061966*(y-1900)**3\n                      - 0.000197*(y-1900)**4, deltat)\n\n    deltat = np.where((1920 <= year) & (year < 1941),\n\n                      21.20+0.84493*(y-1920)\n                      - 0.076100*(y-1920)**2\n                      + 0.0020936*(y-1920)**3, deltat)\n\n    deltat = np.where((1941 <= year) & (year < 1961),\n\n                      29.07+0.407*(y-1950)\n                      - (y-1950)**2/233\n                      + (y-1950)**3/2547, deltat)\n\n    deltat = np.where((1961 <= year) & (year < 1986),\n\n                      45.45+1.067*(y-1975)\n                      - (y-1975)**2/260\n                      - (y-1975)**3/718, deltat)\n\n    deltat = np.where((1986 <= year) & (year < 2005),\n\n                      63.86+0.3345*(y-2000)\n                      - 0.060374*(y-2000)**2\n                      + 0.0017275*(y-2000)**3\n                      + 0.000651814*(y-2000)**4\n                      + 0.00002373599*(y-2000)**5, deltat)\n\n    deltat = np.where((2005 <= year) & (year < 2050),\n\n                      62.92+0.32217*(y-2000)\n                      + 0.005589*(y-2000)**2, deltat)\n\n    deltat = np.where((2050 <= year) & (year < 2150),\n\n                      -20+32*((y-1820)/100)**2\n                      - 0.5628*(2150-y), deltat)\n\n    deltat = np.where(year > 2150,\n\n                      -20+32*((y-1820)/100)**2, deltat)\n\n    deltat = np.asscalar(deltat) if np.isscalar(year) & np.isscalar(month)\\\n        else deltat\n\n    return deltat\n", "meta": {"hexsha": "b486da73dc2af27adf4e59b8b8cd71bb6a716ed6", "size": 48442, "ext": "py", "lang": "Python", "max_stars_repo_path": "pvlib/spa.py", "max_stars_repo_name": "alamathe1/pvlib-python", "max_stars_repo_head_hexsha": "ec996611887747bdef43db874147095e3337721a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pvlib/spa.py", "max_issues_repo_name": "alamathe1/pvlib-python", "max_issues_repo_head_hexsha": "ec996611887747bdef43db874147095e3337721a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pvlib/spa.py", "max_forks_repo_name": "alamathe1/pvlib-python", "max_forks_repo_head_hexsha": "ec996611887747bdef43db874147095e3337721a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8992302309, "max_line_length": 80, "alphanum_fraction": 0.5466743735, "include": true, "reason": "import numpy,import numba,from numba", "num_tokens": 16709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3242353859211693, "lm_q1q2_score": 0.19460230429012595}}
{"text": "from __future__ import division\nfrom build.el_propagator_xf import el_run\nfrom mqc.mqc import MQC\nfrom misc import eps, au_to_K, au_to_A, call_name, typewriter\nimport random, os, shutil, textwrap\nimport numpy as np\nimport pickle\n\nclass Auxiliary_Molecule(object):\n    \"\"\" Class for auxiliary molecule that is used for the calculation of decoherence term\n\n        :param object molecule: Molecule object\n    \"\"\"\n    def __init__(self, molecule, l_xf1d):\n        # Initialize auxiliary molecule\n        if (l_xf1d):\n\n            self.nat = 1\n            self.ndim = 1\n            self.symbols = ['XX']\n\n            self.mass = np.zeros((self.nat))\n            self.mass[0] = 1. / np.sum(1. / molecule.mass[0:molecule.nat_qm])\n\n        else:\n\n            self.nat = molecule.nat_qm\n            self.ndim = molecule.ndim\n            self.symbols = np.copy(molecule.symbols[0:molecule.nat_qm])\n\n            self.mass = np.copy(molecule.mass[0:molecule.nat_qm])\n\n        self.pos = np.zeros((molecule.nst, self.nat, self.ndim))\n        self.vel = np.zeros((molecule.nst, self.nat, self.ndim))\n        self.vel_old = np.copy(self.vel)\n\n\nclass SHXF(MQC):\n    \"\"\" Class for DISH-XF dynamics\n\n        :param object molecule: Molecule object\n        :param object thermostat: Thermostat object\n        :param integer istate: Initial state\n        :param double dt: Time interval\n        :param integer nsteps: Total step of nuclear propagation\n        :param integer nesteps: Total step of electronic propagation\n        :param string elec_object: Electronic equation of motions\n        :param string propagator: Electronic propagator\n        :param boolean l_print_dm: Logical to print BO population and coherence\n        :param boolean l_adj_nac: Adjust nonadiabatic coupling to align the phases\n        :param string hop_rescale: Velocity rescaling method after successful hop\n        :param string hop_reject: Velocity rescaling method after frustrated hop\n        :param double rho_threshold: Electronic density threshold for decoherence term calculation\n        :param sigma: Width of nuclear wave packet of auxiliary trajectory\n        :type sigma: double or double,list\n        :param init_coef: Initial BO coefficient\n        :type init_coef: double, list or complex, list\n        :param boolean l_econs_state: Logical to use identical total energies for all auxiliary trajectories\n        :param string aux_econs_viol: How to treat trajectories violating the total energy conservation\n        :param string unit_dt: Unit of time interval\n        :param integer out_freq: Frequency of printing output\n        :param integer verbosity: Verbosity of output\n    \"\"\"\n    def __init__(self, molecule, thermostat=None, istate=0, dt=0.5, nsteps=1000, nesteps=20, \\\n        elec_object=\"density\", propagator=\"rk4\", l_print_dm=True, l_adj_nac=True, hop_rescale=\"augment\", \\\n        hop_reject=\"reverse\", rho_threshold=0.01, sigma=None, l_xf1d=False, init_coef=None, \\\n        l_econs_state=True, aux_econs_viol=\"fix\", unit_dt=\"fs\", out_freq=1, verbosity=0):\n        # Initialize input values\n        super().__init__(molecule, thermostat, istate, dt, nsteps, nesteps, \\\n            elec_object, propagator, l_print_dm, l_adj_nac, init_coef, unit_dt, out_freq, verbosity)\n\n        # Initialize SH variables\n        self.rstate = istate\n        self.rstate_old = self.rstate\n\n        self.rand = 0.\n        self.prob = np.zeros(self.mol.nst)\n        self.acc_prob = np.zeros(self.mol.nst + 1)\n\n        self.l_hop = False\n        self.l_reject = False\n\n        self.hop_rescale = hop_rescale.lower()\n        if not (self.hop_rescale in [\"energy\", \"velocity\", \"momentum\", \"augment\"]):\n            error_message = \"Invalid rescaling method for accepted hop!\"\n            error_vars = f\"hop_rescale = {self.hop_rescale}\"\n            raise ValueError (f\"( {self.md_type}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n        self.hop_reject = hop_reject.lower()\n        if not (self.hop_reject in [\"keep\", \"reverse\"]):\n            error_message = \"Invalid rescaling method for frustrated hop!\"\n            error_vars = f\"hop_reject = {self.hop_reject}\"\n            raise ValueError (f\"( {self.md_type}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n        # Check error for incompatible cases\n        if (self.mol.l_nacme):\n            # No analytical nonadiabatic couplings exist\n            if (self.hop_rescale in [\"velocity\", \"momentum\", \"augment\"]):\n                error_message = \"NACVs are not available with current QM object, only isotropic rescaling is possible!\"\n                error_vars = f\"hop_rescale = {self.hop_rescale}\"\n                raise ValueError (f\"( {self.md_type}.{call_name()} ) {error_message} ( {error_vars} )\")\n            # TODO : This error will be used after adding the 'flip' option for hop_reject\n#            if (self.hop_reject == \"reverse\"):\n#                error_message = \"NACVs are not available with current QM object, only keep rescaling is possible!\"\n#                error_vars = f\"hop_reject = {self.hop_reject}\"\n#                raise ValueError (f\"( {self.md_type}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n        # Initialize XF related variables\n        self.force_hop = False\n        self.l_econs_state = l_econs_state\n        self.l_xf1d = l_xf1d\n        self.l_coh = [False] * self.mol.nst\n        self.l_first = [False] * self.mol.nst\n        self.l_fix = [False] * self.mol.nst\n        self.l_collapse = False\n        self.rho_threshold = rho_threshold\n        self.aux_econs_viol = aux_econs_viol\n\n        if not (self.aux_econs_viol in [\"fix\", \"collapse\"]):\n            error_message = \"Invalid method to treat auxiliary trajectories that violate the total energy conservation!\"\n            error_vars = f\"aux_econs_viol = {self.aux_econs_viol}\"\n            raise ValueError (f\"( {self.md_type}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n        self.sigma = sigma\n        if (self.sigma == None):\n            error_message = \"Sigma for auxiliary trajectories must be set in running script!\"\n            error_vars = f\"sigma = {self.sigma}\"\n            raise ValueError (f\"( {self.md_type}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n        if (isinstance(self.sigma, float)):\n            # uniform value for sigma\n            pass\n        elif (isinstance(self.sigma, list)):\n            # atom-resolved values for sigma\n            if (len(self.sigma) != self.mol.nat_qm):\n                error_message = \"Number of elements for sigma must be equal to number of atoms!\"\n                error_vars = f\"len(sigma) = {len(self.sigma)}\"\n                raise ValueError (f\"( {self.md_type}.{call_name()} ) {error_message} ( {error_vars} )\")\n            if (self.l_xf1d):\n                error_message = \"Sigma must be float, not list in XF-1D scheme!\"\n                error_vars = f\"sigma = {self.sigma}\"\n                raise TypeError (f\"( {self.md_type}.{call_name()} ) {error_message} ( {error_vars} )\")\n        else:\n            error_message = \"Type of sigma must be float or list consisting of float!\"\n            error_vars = f\"sigma = {self.sigma}\"\n            raise TypeError (f\"( {self.md_type}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n        self.upper_th = 1. - self.rho_threshold\n        self.lower_th = self.rho_threshold\n\n        # Initialize auxiliary molecule object\n        self.aux = Auxiliary_Molecule(self.mol, self.l_xf1d)\n        self.pos_0 = np.zeros((self.aux.nat, self.aux.ndim))\n        self.phase = np.zeros((self.mol.nst, self.aux.nat, self.aux.ndim))\n\n        # Debug variables\n        self.dotpopdec = np.zeros(self.mol.nst)\n        self.dotpopnac = np.zeros(self.mol.nst)\n        self.qmom = np.zeros((self.aux.nat, self.aux.ndim))\n\n        # Initialize event to print\n        self.event = {\"HOP\": [], \"DECO\": []}\n\n    def run(self, qm, mm=None, output_dir=\"./\", l_save_qm_log=False, l_save_mm_log=False, l_save_scr=True, restart=None):\n        \"\"\" Run MQC dynamics according to decoherence-induced surface hopping dynamics\n\n            :param object qm: QM object containing on-the-fly calculation infomation\n            :param object mm: MM object containing MM calculation infomation\n            :param string output_dir: Name of directory where outputs to be saved.\n            :param boolean l_save_qm_log: Logical for saving QM calculation log\n            :param boolean l_save_mm_log: Logical for saving MM calculation log\n            :param boolean l_save_scr: Logical for saving scratch directory\n            :param string restart: Option for controlling dynamics restarting\n        \"\"\"\n        # Initialize PyUNIxMD\n        base_dir, unixmd_dir, qm_log_dir, mm_log_dir =\\\n             self.run_init(qm, mm, output_dir, l_save_qm_log, l_save_mm_log, l_save_scr, restart)\n        bo_list = [self.rstate]\n        qm.calc_coupling = True\n        self.print_init(qm, mm, restart)\n\n        if (restart == None):\n            # Initialize decoherence variables\n            self.append_sigma()\n\n            # Calculate initial input geometry at t = 0.0 s\n            self.istep = -1\n            self.mol.reset_bo(qm.calc_coupling)\n            qm.get_data(self.mol, base_dir, bo_list, self.dt, self.istep, calc_force_only=False)\n            if (self.mol.l_qmmm and mm != None):\n                mm.get_data(self.mol, base_dir, bo_list, self.istep, calc_force_only=False)\n            if (not self.mol.l_nacme):\n                self.mol.get_nacme()\n\n            self.hop_prob()\n            self.hop_check(bo_list)\n            self.evaluate_hop(bo_list)\n            if (qm.re_calc and self.l_hop):\n                qm.get_data(self.mol, base_dir, bo_list, self.dt, self.istep, calc_force_only=True)\n                if (self.mol.l_qmmm and mm != None):\n                    mm.get_data(self.mol, base_dir, bo_list, self.istep, calc_force_only=True)\n\n            self.update_energy()\n\n            self.check_decoherence()\n            self.check_coherence()\n            self.aux_propagator()\n            self.get_phase()\n            if (self.l_collapse):\n                self.check_decoherence()\n                self.check_coherence()\n\n            self.write_md_output(unixmd_dir, self.istep)\n            self.print_step(self.istep)\n\n        elif (restart == \"write\"):\n            # Reset initial time step to t = 0.0 s\n            self.istep = -1\n            self.write_md_output(unixmd_dir, self.istep)\n            self.print_step(self.istep)\n\n        elif (restart == \"append\"):\n            # Set initial time step to last successful step of previous dynamics\n            self.istep = self.fstep\n\n        self.istep += 1\n\n        # Main MD loop\n        for istep in range(self.istep, self.nsteps):\n\n            self.calculate_force()\n            self.cl_update_position()\n\n            self.mol.backup_bo()\n            self.mol.reset_bo(qm.calc_coupling)\n            qm.get_data(self.mol, base_dir, bo_list, self.dt, istep, calc_force_only=False)\n            if (self.mol.l_qmmm and mm != None):\n                mm.get_data(self.mol, base_dir, bo_list, istep, calc_force_only=False)\n\n            if (not self.mol.l_nacme and self.l_adj_nac):\n                self.mol.adjust_nac()\n\n            self.calculate_force()\n            self.cl_update_velocity()\n\n            if (not self.mol.l_nacme):\n                self.mol.get_nacme()\n\n            el_run(self)\n\n            self.hop_prob()\n            self.hop_check(bo_list)\n            self.evaluate_hop(bo_list)\n            if (self.l_hop):\n                if (qm.re_calc):\n                    qm.get_data(self.mol, base_dir, bo_list, self.dt, istep, calc_force_only=True)\n                if (self.mol.l_qmmm and mm != None):\n                    mm.get_data(self.mol, base_dir, bo_list, istep, calc_force_only=True)\n\n            if (self.thermo != None):\n                self.thermo.run(self)\n\n            self.update_energy()\n\n            self.check_decoherence()\n            self.check_coherence()\n            self.aux_propagator()\n            self.get_phase()\n            if (self.l_collapse):\n                self.check_decoherence()\n                self.check_coherence()\n\n            if ((istep + 1) % self.out_freq == 0):\n                self.write_md_output(unixmd_dir, istep)\n            if ((istep + 1) % self.out_freq == 0 or len(self.event[\"HOP\"]) > 0 or len(self.event[\"DECO\"]) > 0):\n                self.print_step(istep)\n            if (istep == self.nsteps - 1):\n                self.write_final_xyz(unixmd_dir, istep)\n\n            self.fstep = istep\n            restart_file = os.path.join(base_dir, \"RESTART.bin\")\n            with open(restart_file, 'wb') as f:\n                pickle.dump({'qm':qm, 'md':self}, f)\n\n        # Delete scratch directory\n        if (not l_save_scr):\n            tmp_dir = os.path.join(unixmd_dir, \"scr_qm\")\n            if (os.path.exists(tmp_dir)):\n                shutil.rmtree(tmp_dir)\n\n            if (self.mol.l_qmmm and mm != None):\n                tmp_dir = os.path.join(unixmd_dir, \"scr_mm\")\n                if (os.path.exists(tmp_dir)):\n                    shutil.rmtree(tmp_dir)\n\n    def hop_prob(self):\n        \"\"\" Routine to calculate hopping probabilities\n\n            :param integer istep: Current MD step\n        \"\"\"\n        # Reset surface hopping variables\n        self.rstate_old = self.rstate\n\n        self.prob = np.zeros(self.mol.nst)\n        self.acc_prob = np.zeros(self.mol.nst + 1)\n\n        self.l_hop = False\n        self.force_hop = False\n\n        accum = 0.\n\n        if (self.mol.rho.real[self.rstate, self.rstate] < self.lower_th):\n            self.force_hop = True\n\n        for ist in range(self.mol.nst):\n            if (ist != self.rstate):\n                if (self.force_hop):\n                    self.prob[ist] = self.mol.rho.real[ist, ist] / self.upper_th\n                else:\n                    self.prob[ist] = - 2. * self.mol.rho.real[ist, self.rstate] * \\\n                        self.mol.nacme[ist, self.rstate] * self.dt / self.mol.rho.real[self.rstate, self.rstate]\n\n                if (self.prob[ist] < 0.):\n                    self.prob[ist] = 0.\n                accum += self.prob[ist]\n            self.acc_prob[ist + 1] = accum\n        psum = self.acc_prob[self.mol.nst]\n\n        if (psum > 1.):\n            self.prob /= psum\n            self.acc_prob /= psum\n\n    def hop_check(self, bo_list):\n        \"\"\" Routine to check hopping occurs with random number\n\n            :param integer,list bo_list: List of BO states for BO calculation\n        \"\"\"\n        self.rand = random.random()\n        for ist in range(self.mol.nst):\n            if (ist == self.rstate):\n                continue\n            if (self.rand > self.acc_prob[ist] and self.rand <= self.acc_prob[ist + 1]):\n                self.l_hop = True\n                self.rstate = ist\n                bo_list[0] = self.rstate\n\n    def evaluate_hop(self, bo_list):\n        \"\"\" Routine to evaluate hopping and velocity rescaling\n\n            :param integer,list bo_list: List of BO states for BO calculation\n            :param integer istep: Current MD step\n        \"\"\"\n        if (self.l_hop):\n            # Calculate potential difference between hopping states\n            pot_diff = self.mol.states[self.rstate].energy - self.mol.states[self.rstate_old].energy\n\n            # Solve quadratic equation for scaling factor of velocities\n            a = 1.\n            b = 1.\n            det = 1.\n            if (self.hop_rescale == \"velocity\"):\n                a = np.sum(self.mol.mass[0:self.mol.nat_qm] * np.sum(self.mol.nac[self.rstate_old, self.rstate] ** 2., axis=1))\n                b = 2. * np.sum(self.mol.mass[0:self.mol.nat_qm] * np.sum(self.mol.nac[self.rstate_old, self.rstate] \\\n                    * self.mol.vel[0:self.mol.nat_qm], axis=1))\n                c = 2. * pot_diff\n                det = b ** 2. - 4. * a * c\n            elif (self.hop_rescale == \"momentum\"):\n                a = np.sum(1. / self.mol.mass[0:self.mol.nat_qm] * np.sum(self.mol.nac[self.rstate_old, self.rstate] ** 2., axis=1))\n                b = 2. * np.sum(np.sum(self.mol.nac[self.rstate_old, self.rstate] * self.mol.vel[0:self.mol.nat_qm], axis=1))\n                c = 2. * pot_diff\n                det = b ** 2. - 4. * a * c\n            elif (self.hop_rescale == \"augment\"):\n                a = np.sum(1. / self.mol.mass[0:self.mol.nat_qm] * np.sum(self.mol.nac[self.rstate_old, self.rstate] ** 2., axis=1))\n                b = 2. * np.sum(np.sum(self.mol.nac[self.rstate_old, self.rstate] * self.mol.vel[0:self.mol.nat_qm], axis=1))\n                c = 2. * pot_diff\n                det = b ** 2. - 4. * a * c\n\n            # Default: hopping is allowed\n            self.l_reject = False\n\n            # Velocities cannot be adjusted when zero kinetic energy is given\n            if (self.hop_rescale == \"energy\" and self.mol.ekin_qm < eps):\n                self.l_reject = True\n            # Clasically forbidden hop due to lack of kinetic energy\n            if (self.mol.ekin_qm < pot_diff):\n                self.l_reject = True\n            # Kinetic energy is enough, but there is no solution for scaling factor\n            if (det < 0.):\n                self.l_reject = True\n            # When kinetic energy is enough, velocities are always rescaled in 'augment' case\n            if (self.hop_rescale == \"augment\" and self.mol.ekin_qm > pot_diff):\n                self.l_reject = False\n\n            if (self.l_reject):\n                # Record event for frustrated hop\n                if (self.mol.ekin_qm < pot_diff):\n                    self.event[\"HOP\"].append(f\"Reject hopping: smaller kinetic energy than potential energy difference between {self.rstate} and {self.rstate_old}\")\n                # Set scaling constant with respect to 'hop_reject'\n                if (self.hop_reject == \"keep\"):\n                    self.event[\"HOP\"].append(\"Reject hopping: no solution to find rescale factor, velocity is not changed\")\n                elif (self.hop_reject == \"reverse\"):\n                    # x = - 1 when 'hop_rescale' is 'energy', otherwise x = - b / a\n                    self.event[\"HOP\"].append(\"Reject hopping: no solution to find rescale factor, velocity is reversed along coupling direction\")\n                    x = - b / a\n                # Recover old running state\n                self.l_hop = False\n\n                if (self.force_hop):\n                    self.event[\"HOP\"].append(f\"Collapse density: reset the density according to the current state {self.rstate_old}\")\n                    self.set_decoherence(self.rstate_old)\n\n                self.force_hop = False\n\n                self.rstate = self.rstate_old\n                bo_list[0] = self.rstate\n            else:\n                if (self.hop_rescale == \"energy\" or (det < 0. and self.hop_rescale == \"augment\")):\n                    if (det < 0.):\n                        self.event[\"HOP\"].append(\"Accept hopping: no solution to find rescale factor, but velocity is simply rescaled\")\n                    x = np.sqrt(1. - pot_diff / self.mol.ekin_qm)\n                else:\n                    if (b < 0.):\n                        x = 0.5 * (- b - np.sqrt(det)) / a\n                    else:\n                        x = 0.5 * (- b + np.sqrt(det)) / a\n\n            # Rescale velocities for QM atoms\n            if (not (self.hop_reject == \"keep\" and self.l_reject)):\n                if (self.hop_rescale == \"energy\"):\n                    self.mol.vel[0:self.mol.nat_qm] *= x\n\n                elif (self.hop_rescale == \"velocity\"):\n                    self.mol.vel[0:self.mol.nat_qm] += x * self.mol.nac[self.rstate_old, self.rstate]\n\n                elif (self.hop_rescale == \"momentum\"):\n                    self.mol.vel[0:self.mol.nat_qm] += x * self.mol.nac[self.rstate_old, self.rstate] / \\\n                        self.mol.mass[0:self.mol.nat_qm].reshape((-1, 1))\n\n                elif (self.hop_rescale == \"augment\"):\n                    if (det > 0. or self.mol.ekin_qm < pot_diff):\n                        self.mol.vel[0:self.mol.nat_qm] += x * self.mol.nac[self.rstate_old, self.rstate] / \\\n                            self.mol.mass[0:self.mol.nat_qm].reshape((-1, 1))\n                    else:\n                        self.mol.vel[0:self.mol.nat_qm] *= x\n\n            # Update kinetic energy\n            self.mol.update_kinetic()\n\n        # Record hopping event\n        if (self.rstate != self.rstate_old):\n            if (self.force_hop):\n                self.event[\"HOP\"].append(f\"Accept hopping: force hop {self.rstate_old} -> {self.rstate}\")\n            else:\n                self.event[\"HOP\"].append(f\"Accept hopping: hop {self.rstate_old} -> {self.rstate}\")\n\n    def calculate_force(self):\n        \"\"\" Routine to calculate the forces\n        \"\"\"\n        self.rforce = np.copy(self.mol.states[self.rstate].force)\n\n    def update_energy(self):\n        \"\"\" Routine to update the energy of molecules in surface hopping dynamics\n        \"\"\"\n        # Update kinetic energy\n        self.mol.update_kinetic()\n        self.mol.epot = self.mol.states[self.rstate].energy\n        self.mol.etot = self.mol.epot + self.mol.ekin\n\n    def check_decoherence(self):\n        \"\"\" Routine to check if the electronic state is decohered\n        \"\"\"\n        if (self.l_hop):\n            if (True in self.l_coh):\n                self.event[\"DECO\"].append(f\"Destroy auxiliary trajectories: hopping occurs\")\n            self.l_coh = [False] * self.mol.nst\n            self.l_first = [False] * self.mol.nst\n            self.l_fix = [False] * self.mol.nst\n        else:\n            for ist in range(self.mol.nst):\n                if (self.l_coh[ist]):\n                    rho = self.mol.rho.real[ist, ist]\n                    if (rho > self.upper_th):\n                        self.set_decoherence(ist)\n                        return\n\n    def check_coherence(self):\n        \"\"\" Routine to check coherence among BO states\n        \"\"\"\n        count = 0\n        tmp_st = \"\"\n        for ist in range(self.mol.nst):\n            rho = self.mol.rho.real[ist, ist]\n            if (rho > self.upper_th or rho < self.lower_th):\n                self.l_coh[ist] = False\n            else:\n                if (self.l_coh[ist]):\n                    self.l_first[ist] = False\n                else:\n                    self.l_first[ist] = True\n                    tmp_st += f\"{ist}, \"\n                self.l_coh[ist] = True\n                count += 1\n\n        if (count < 2):\n            self.l_coh = [False] * self.mol.nst\n            self.l_first = [False] * self.mol.nst\n            tmp_st = \"\"\n\n        if (len(tmp_st) >= 1):\n            tmp_st = tmp_st.rstrip(', ')\n            self.event[\"DECO\"].append(f\"Generate auxiliary trajectory on {tmp_st} state\")\n\n    def set_decoherence(self, one_st):\n        \"\"\" Routine to reset coefficient/density if the state is decohered\n\n            :param integer one_st: State index that its population is one\n        \"\"\"\n        self.phase = np.zeros((self.mol.nst, self.aux.nat, self.aux.ndim))\n        self.mol.rho = np.zeros((self.mol.nst, self.mol.nst), dtype=np.complex128)\n        self.mol.rho[one_st, one_st] = 1. + 0.j\n\n        self.l_coh = [False] * self.mol.nst\n        self.l_first = [False] * self.mol.nst\n        self.l_fix = [False] * self.mol.nst\n\n        self.event[\"DECO\"].append(f\"Destroy auxiliary trajectories: decohered to {one_st} state\")\n\n        if (self.elec_object == \"coefficient\"):\n            for ist in range(self.mol.nst):\n                if (ist == one_st):\n                    self.mol.states[ist].coef /= np.absolute(self.mol.states[ist].coef).real\n                else:\n                    self.mol.states[ist].coef = 0. + 0.j\n\n    def aux_propagator(self):\n        \"\"\" Routine to propagate auxiliary molecule\n        \"\"\"\n        # Get auxiliary position\n        for ist in range(self.mol.nst):\n            if (self.l_coh[ist]):\n                if (self.l_first[ist]):\n                    if (self.l_xf1d):\n                        self.aux.pos[ist] = np.zeros((self.aux.nat, self.aux.ndim))\n                    else:\n                        self.aux.pos[ist] = self.mol.pos[0:self.aux.nat]\n                else:\n                    if (self.l_xf1d):\n                        self.aux.pos[ist] += self.aux.vel[ist] * self.dt\n                    else:\n                        if (ist == self.rstate):\n                            self.aux.pos[ist] = self.mol.pos[0:self.aux.nat]\n                        else:\n                            self.aux.pos[ist] += self.aux.vel[ist] * self.dt\n\n        self.pos_0 = np.copy(self.aux.pos[self.rstate])\n\n        # Get auxiliary velocity\n        self.l_collapse = False\n        self.aux.vel_old = np.copy(self.aux.vel)\n        for ist in range(self.mol.nst):\n            # Calculate propagation factor alpha\n            if (self.l_coh[ist]):\n                if (self.l_fix[ist]):\n                    alpha = 0.\n                else:\n                    if (ist == self.rstate):\n                        alpha = self.mol.ekin_qm\n                    else:\n                        if (self.l_first[ist]):\n                            alpha = self.mol.ekin_qm\n                            if (self.l_econs_state):\n                                alpha += self.mol.states[self.rstate].energy - self.mol.states[ist].energy\n                        else:\n                            ekin_old = np.sum(0.5 * self.aux.mass * np.sum(self.aux.vel_old[ist] ** 2, axis=1))\n                            alpha = ekin_old + self.mol.states[ist].energy_old - self.mol.states[ist].energy\n                    if (alpha < 0.):\n                        alpha = 0.\n                        if (self.aux_econs_viol == \"fix\"):\n                            self.l_fix[ist] = True\n                            self.event[\"DECO\"].append(f\"Energy conservation violated, the auxiliary trajectory on state {ist} is fixed.\")\n                        elif (self.aux_econs_viol == \"collapse\"):\n                            self.l_collapse = True\n                            self.collapse(ist)\n                            self.event[\"DECO\"].append(f\"Energy conservation violated, collapse the {ist} state coefficient/density to zero.\")\n\n                # Calculate auxiliary velocity from alpha\n                if (self.l_xf1d):\n                    alpha /= 0.5 * self.aux.mass[0]\n                    self.aux.vel[ist] = np.sqrt(alpha)\n                else:\n                    alpha /= self.mol.ekin_qm\n                    self.aux.vel[ist] = self.mol.vel[0:self.aux.nat] * np.sqrt(alpha)\n\n    def collapse(self, cstate):\n        \"\"\" Routine to collapse coefficient/density of a state to zero\n        \"\"\"\n        fac = 1. - self.mol.rho.real[cstate, cstate]\n\n        if (self.elec_object == \"coefficient\"):\n            for ist in range(self.mol.nst):\n                if (ist == cstate):\n                    self.mol.states[ist].coef = 0. + 0.j\n                else:\n                    self.mol.states[ist].coef /= np.sqrt(fac)\n\n        self.mol.rho[cstate,:] = 0. + 0.j\n        self.mol.rho[:,cstate] = 0. + 0.j\n        self.mol.rho /= fac\n         \n    def get_phase(self):\n        \"\"\" Routine to calculate phase term\n        \"\"\"\n        for ist in range(self.mol.nst):\n            if (self.l_coh[ist]):\n                if (self.l_first[ist]):\n                    self.phase[ist] = 0.\n                else:\n                    for iat in range(self.aux.nat):\n                        self.phase[ist, iat] += self.aux.mass[iat] * \\\n                            (self.aux.vel[ist, iat] - self.aux.vel_old[ist, iat])\n\n    def append_sigma(self):\n        \"\"\" Routine to append sigma values when single float number is provided\n        \"\"\"\n        # Create a list from single float number\n        if (isinstance(self.sigma, float)):\n            sigma = self.sigma\n            self.sigma = self.aux.nat * [sigma]\n\n    def write_md_output(self, unixmd_dir, istep):\n        \"\"\" Write output files\n\n            :param string unixmd_dir: PyUNIxMD directory\n            :param integer istep: Current MD step\n        \"\"\"\n        # Write the common part\n        super().write_md_output(unixmd_dir, istep)\n\n        # Write hopping-related quantities\n        self.write_sh(unixmd_dir, istep)\n\n        # Write time-derivative BO population\n        self.write_dotpop(unixmd_dir, istep)\n\n        # Write decoherence information\n        self.write_dec(unixmd_dir, istep)\n\n    def write_sh(self, unixmd_dir, istep):\n        \"\"\" Write hopping-related quantities into files\n\n            :param string unixmd_dir: PyUNIxMD directory\n            :param integer istep: Current MD step\n        \"\"\"\n        # Write SHSTATE file\n        tmp = f'{istep + 1:9d}{\"\":14s}{self.rstate}'\n        typewriter(tmp, unixmd_dir, \"SHSTATE\", \"a\")\n\n        # Write SHPROB file\n        tmp = f'{istep + 1:9d}' + \"\".join([f'{self.prob[ist]:15.8f}' for ist in range(self.mol.nst)])\n        typewriter(tmp, unixmd_dir, \"SHPROB\", \"a\")\n\n    def write_dotpop(self, unixmd_dir, istep):\n        \"\"\" Write time-derivative BO population\n\n            :param string unixmd_dir: PyUNIxMD directory\n            :param integer istep: Current MD step\n        \"\"\"\n        if (self.verbosity >= 1):\n            # Write NAC term in DOTPOPNAC\n            tmp = f'{istep + 1:9d}' + \"\".join([f'{pop:15.8f}' for pop in self.dotpopnac])\n            typewriter(tmp, unixmd_dir, \"DOTPOPNAC\", \"a\")\n\n            # Write decoherence term in DOTPOPDEC\n            tmp = f'{istep + 1:9d}' + \"\".join([f'{pop:15.8f}' for pop in self.dotpopdec])\n            typewriter(tmp, unixmd_dir, \"DOTPOPDEC\", \"a\")\n\n    def write_dec(self, unixmd_dir, istep):\n        \"\"\" Write XF-based decoherence information\n\n            :param string unixmd_dir: PyUNIxMD directory\n            :param integer istep: Current MD step\n        \"\"\"\n        # Write auxiliary trajectories\n        if (self.verbosity >= 2 and True in self.l_coh):\n            # Write quantum momenta\n            tmp = f'{self.aux.nat:6d}\\n{\"\":2s}Step:{istep + 1:6d}{\"\":12s}Momentum (au)' + \\\n                \"\".join([\"\\n\" + f'{self.aux.symbols[iat]:5s}' + \\\n                \"\".join([f'{self.qmom[iat, isp]:15.8f}' for isp in range(self.aux.ndim)]) for iat in range(self.aux.nat)])\n            typewriter(tmp, unixmd_dir, f\"QMOM\", \"a\")\n\n            # Write auxiliary variables\n            for ist in range(self.mol.nst):\n                if (self.l_coh[ist]):\n                    # Write auxiliary phase\n                    tmp = f'{self.aux.nat:6d}\\n{\"\":2s}Step:{istep + 1:6d}{\"\":12s}Phase (au)' + \\\n                        \"\".join([\"\\n\" + f'{self.aux.symbols[iat]:5s}' + \\\n                        \"\".join([f'{self.phase[ist, iat, isp]:15.8f}' for isp in range(self.aux.ndim)]) for iat in range(self.aux.nat)])\n                    typewriter(tmp, unixmd_dir, f\"AUX_PHASE_{ist}\", \"a\")\n\n                    # Write auxiliary trajectory movie files\n                    tmp = f'{self.aux.nat:6d}\\n{\"\":2s}Step:{istep + 1:6d}{\"\":12s}Position(A){\"\":34s}Velocity(au)' + \\\n                        \"\".join([\"\\n\" + f'{self.aux.symbols[iat]:5s}' + \\\n                        \"\".join([f'{self.aux.pos[ist, iat, isp] * au_to_A:15.8f}' for isp in range(self.aux.ndim)]) + \\\n                        \"\".join([f\"{self.aux.vel[ist, iat, isp]:15.8f}\" for isp in range(self.aux.ndim)]) for iat in range(self.aux.nat)])\n                    typewriter(tmp, unixmd_dir, f\"AUX_MOVIE_{ist}.xyz\", \"a\")\n\n    def print_init(self, qm, mm, restart):\n        \"\"\" Routine to print the initial information of dynamics\n\n            :param object qm: QM object containing on-the-fly calculation infomation\n            :param object mm: MM object containing MM calculation infomation\n            :param string restart: Option for controlling dynamics restarting\n        \"\"\"\n        # Print initial information about molecule, qm, mm and thermostat\n        super().print_init(qm, mm, restart)\n\n        # Print dynamics information for start line\n        dynamics_step_info = textwrap.dedent(f\"\"\"\\\n\n        {\"-\" * 118}\n        {\"Start Dynamics\":>65s}\n        {\"-\" * 118}\n        \"\"\")\n\n        # Print INIT for each step\n        INIT = f\" #INFO{'STEP':>8s}{'State':>7s}{'Kinetic(H)':>14s}{'Potential(H)':>15s}{'Total(H)':>13s}{'Temperature(K)':>17s}{'Norm.':>8s}\"\n        dynamics_step_info += INIT\n\n        # Print DEBUG1 for each step\n        if (self.verbosity >= 1):\n            DEBUG1 = f\" #DEBUG1{'STEP':>6s}{'Rand.':>11s}{'Acc. Hopping Prob.':>28s}\"\n            dynamics_step_info += \"\\n\" + DEBUG1\n\n        print (dynamics_step_info, flush=True)\n\n    def print_step(self, istep):\n        \"\"\" Routine to print each steps infomation about dynamics\n\n            :param integer istep: Current MD step\n        \"\"\"\n        ctemp = self.mol.ekin * 2. / float(self.mol.ndof) * au_to_K\n        norm = 0.\n        for ist in range(self.mol.nst):\n            norm += self.mol.rho.real[ist, ist]\n\n        # Print INFO for each step\n        INFO = f\" INFO{istep + 1:>9d}{self.rstate:>5d}\"\n        INFO += f\"{self.mol.ekin:16.8f}{self.mol.epot:15.8f}{self.mol.etot:15.8f}\"\n        INFO += f\"{ctemp:13.6f}\"\n        INFO += f\"{norm:11.5f}\"\n        print (INFO, flush=True)\n\n        # Print DEBUG1 for each step\n        if (self.verbosity >= 1):\n            DEBUG1 = f\" DEBUG1{istep + 1:>7d}\"\n            DEBUG1 += f\"{self.rand:11.5f}\"\n            for ist in range(self.mol.nst):\n                DEBUG1 += f\"{self.acc_prob[ist]:12.5f} ({self.rstate}->{ist})\"\n            print (DEBUG1, flush=True)\n\n        # Print event in SHXF\n        for category, events in self.event.items():\n            if (len(events) != 0):\n                for ievent in events:\n                    print (f\" {category}{istep + 1:>9d}  {ievent}\", flush=True)\n        self.event[\"HOP\"] = []\n        self.event[\"DECO\"] = []\n\n\n", "meta": {"hexsha": "d9cc8a5ff4d1972e9bd42dd17382f5b9bef2db41", "size": 33757, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/mqc/shxf.py", "max_stars_repo_name": "skmin-lab/unixmd", "max_stars_repo_head_hexsha": "241b886a4d383e3ae107a22c6c0154c85e2729d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-04-18T08:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T03:29:54.000Z", "max_issues_repo_path": "src/mqc/shxf.py", "max_issues_repo_name": "skmin-lab/unixmd", "max_issues_repo_head_hexsha": "241b886a4d383e3ae107a22c6c0154c85e2729d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2021-04-14T08:43:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T10:26:42.000Z", "max_forks_repo_path": "src/mqc/shxf.py", "max_forks_repo_name": "skmin-lab/unixmd", "max_forks_repo_head_hexsha": "241b886a4d383e3ae107a22c6c0154c85e2729d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2021-04-14T05:59:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T03:05:23.000Z", "avg_line_length": 43.8402597403, "max_line_length": 164, "alphanum_fraction": 0.5537814379, "include": true, "reason": "import numpy", "num_tokens": 8563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.31069437683198775, "lm_q1q2_score": 0.19453325672826646}}
{"text": "#%%\nimport numpy as np\nimport copy\nimport matplotlib.pyplot as plt\nimport time \n\ndef split_cluster_new(tree,local_density,dc_eps,closest_denser_nodes_id,mixin_near_matrix):\n    '''\n        dc_eps: density_connectivity 阈值\n        使用父子节点的直接距离，与子节点与兄弟节点的连通距离进行聚簇划分；\n        使用平均密度划分outlier\n        返回：\n            outlier_forest\n            cluster_forest\n    '''\n    mean_density = np.mean(local_density)\n    outlier_forest = {}\n    cluster_forest = {}\n    uncertain_forest = {}\n    not_direct_reach = []\n    #* 计算不可直接可达的点：\n    for k in range(len(closest_denser_nodes_id)):\n        near_nodes = mixin_near_matrix[k]\n        if closest_denser_nodes_id[k] not in near_nodes:\n            not_direct_reach.append(k)\n        pass\n    not_direct_reach = np.array(not_direct_reach)\n    # not_direct_reach = np.where(closest_dis_denser>eps)[0]\n    #* 将不直接距离可达的点按层次排列：\n    # not_direct_reach = np.array(not_direct_reach)\n    depth_list_not_direct_reach= np.zeros(len(not_direct_reach),dtype=np.int16)\n    for i in range(len(not_direct_reach)):\n        # depth_list_not_direct_reach[i] = tree.node_dir[not_direct_reach[i]].getLvl()\n        depth_list_not_direct_reach[i] = tree.calcu_depth(not_direct_reach[i],0)\n        pass\n    not_direct_reach = list(not_direct_reach[np.argsort(depth_list_not_direct_reach)])\n    #* 模拟栈结构，层次深的先处理\n    start = time.clock()\n    while(len(not_direct_reach)>0):\n        #* 判断是否 连通：距离小于阈值，并且密度要大于子树的平均密度\n        node_id = not_direct_reach.pop()\n        if(node_id==129193 or node_id==61589 or node_id == 123593):\n            print(node_id)\n        if node_id in tree.sorted_gamma_index[0:10]:\n            cluster_forest[node_id] = tree.remove_subtree(node_id)\n            continue\n        node = tree.node_dir[node_id]\n        parent_id = node.parent_id\n        parent_node = tree.node_dir[parent_id]\n        children = parent_node.getChildren()\n        siblings_reliable = [ i for i in children if i not in not_direct_reach] #* 求得兄弟节点，其中兄弟节点不能是不直接可达的点\n        not_reliable_nodes = [i for i in children if i not in siblings_reliable]\n        if node_id in not_reliable_nodes:\n            not_reliable_nodes.remove(node_id)\n        if node_id in siblings_reliable:\n            siblings_reliable.remove(node_id)\n        pairs_nodes = is_connected_new(tree,local_density,dc_eps,node_id,siblings_reliable,not_reliable_nodes,mixin_near_matrix)\n        if len(pairs_nodes)==0:\n            if(node_id==tree.root_node.node_id):\n                continue\n            if(local_density[node_id]-mean_density*dc_eps)>=0:\n                #* 获取子节点个数:\n                offspring_id = tree.get_subtree_offspring_id(node_id,[node_id])\n                if(len(offspring_id)<local_density[node_id]):\n                    uncertain_forest[node_id] = tree.remove_subtree(node_id)\n                    pass\n                else:\n                    cluster_forest[node_id] = tree.remove_subtree(node_id)\n                    pass\n                pass\n            else:\n                outlier_forest[node_id] = tree.remove_subtree(node_id)\n                pass\n            pass\n        pass\n    end = time.clock()\n    print('切割树耗时 %s' % str(end - start))\n    cluster_forest[tree.root_node.node_id] = tree #* 添加根节点的树\n    return outlier_forest, cluster_forest, uncertain_forest\n\n\ndef is_connected_new(tree,local_density,dc_eps,cur_node_id,reliable_nodes,not_reliable_nodes,mixin_near_matrix):\n    '''\n        cur_node: 当前待判断与父节点连通度的点；\n        reliable_nodes：兄弟节点中与父节点直接相连的点；\n        not_reliable_nodes：兄弟节点中不与父节点直接相连的点，但可能间接相连；\n        连通度判断方案：\n            1. 判断 cur_node 与 reliable_nodes 是否可达，是则返回；没有则执行2；\n            2. 判断 cur_node 与 not_reliable_nodes(假设为[a,b,c,d,e]) 是否可达，若与[a,b,c]可达，与[d,e]不可达，执行3；\n            3. 循环遍历[a,b,c],递归调用本方法 is_connected_entropy(……,cur_node_id=[a],reliable_nodes,not_reliable_nodes=[b,c,d,e])\n    '''\n    #* 1. \n    if(len(reliable_nodes)==0):\n        return []\n    for reliable_node_id in reliable_nodes:\n        pairs_nodes, connected_nodes = tree.calcu_neighbor_btw_subtree(cur_node_id,reliable_node_id,mixin_near_matrix)\n        if(len(pairs_nodes)==0):\n            continue\n        # return pairs_nodes\n        cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id])\n        local_density_cur_offspring = np.mean(local_density[cur_node_offspring])\n        local_density_connected_nodes = np.mean(local_density[connected_nodes])\n        if(local_density_connected_nodes>local_density_cur_offspring*dc_eps):\n            return pairs_nodes\n        pass\n    #* 2. \n    for i in range(len(not_reliable_nodes)):\n        pairs_nodes, connected_nodes = tree.calcu_neighbor_btw_subtree(cur_node_id,not_reliable_nodes[i],mixin_near_matrix)\n        if(len(pairs_nodes)==0):\n            pairs_nodes = is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix)\n            if(len(pairs_nodes)>0):\n                return pairs_nodes\n        else:\n            cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id])\n            local_density_cur_offspring = np.mean(local_density[cur_node_offspring])\n            local_density_connected_nodes = np.mean(local_density[connected_nodes])\n            if(local_density_connected_nodes>local_density_cur_offspring*dc_eps):\n                return pairs_nodes\n\n\n            # return pairs_nodes\n        # #* 连通点平均密度大于局部密度阈值，则更新最大相似度\n        cur_node_offspring = tree.get_subtree_offspring_id(cur_node_id,[cur_node_id])\n        local_density_cur_offspring = np.mean(local_density[cur_node_offspring])\n        local_density_connected_nodes = np.mean(local_density[connected_nodes])\n        if(local_density_connected_nodes>local_density_cur_offspring*dc_eps):\n            return pairs_nodes\n        if(len(pairs_nodes)==0):\n            pairs_nodes = is_connected_new(tree,local_density,dc_eps,not_reliable_nodes[i],reliable_nodes,not_reliable_nodes[i+1:],mixin_near_matrix)\n            if(len(pairs_nodes)>0):\n                return pairs_nodes\n        # pass\n    return []\n\n\ndef label_these_node_new(outlier_forest,cluster_forest,node_num,uncertain_forest,mixin_near_matrix):\n    '''\n        给森林中的样本点贴标签\n        考虑不确定点的分配\n    '''\n    labels = np.full((node_num),-1,dtype=np.int32)\n    for outlier_id in outlier_forest:\n        outlier_tree = outlier_forest[outlier_id]\n        outlier_idlist = outlier_tree.get_subtree_offspring_id(outlier_id,[outlier_id])\n        labels[outlier_idlist] = -1\n        pass\n    \n    label = 0\n    for tree_id in cluster_forest:\n        cluster_tree = cluster_forest[tree_id]\n        cluster_idlist = cluster_tree.get_subtree_offspring_id(tree_id,[tree_id])\n        labels[cluster_idlist] = label\n        label = label + 1\n        pass\n\n    #todo 修改此处代码\n    for uncertain_tree_id in uncertain_forest:\n        uncertain_tree = uncertain_forest[uncertain_tree_id]\n        uncertain_nodes_id = uncertain_tree.get_subtree_offspring_id(uncertain_tree_id,[uncertain_tree_id])\n        all_near_nodes = np.array([],dtype=np.int32)\n        for node_id in uncertain_nodes_id:\n            all_near_nodes = np.append(all_near_nodes,mixin_near_matrix[node_id])\n            pass\n        # all_near_nodes = mixin_near_matrix[uncertain_nodes_id]\n        all_near_nodes = np.unique(all_near_nodes)\n        all_near_nodes = all_near_nodes[np.where(labels[all_near_nodes]!=-1)]\n        unique_labels,counts=np.unique(labels[all_near_nodes],return_counts=True)\n        if(len(counts)==0):\n            cur_label = -1\n        else:\n            cur_label = unique_labels[np.argmax(counts)]\n        labels[uncertain_nodes_id]=cur_label\n        pass\n\n    core_points = cluster_forest.keys()\n    return labels,core_points\n\n\n\n'''\n密度峰值树；\n根据cfsfdp算法生成的局部密度、高密度最近邻距离、决策指标来生成 DPTree；\n'''\nclass Node():\n    def __init__(self,node_id,attr_list,parent_id=None,dist_to_parent=None,density=None,gamma=None,children=[]):\n        self.node_id = node_id\n        self.attr_list = attr_list\n        self.parent_id = parent_id\n        self.dist_to_parent = dist_to_parent\n        self.density = density\n        self.children = children\n        self.gamma = gamma\n        self.offspring_num = None\n        self.lvl = None\n\n    def addChild(self,child):\n        self.children+=[child]\n\n    def removeChild(self,child):\n        self.children.remove(child)\n    \n    def resetChildren(self):\n        self.children = []\n\n    def setParentId(self,parent_id):\n        self.parent_id = parent_id\n\n    def setOffspringNum(self,num):\n        self.offspring_num = num\n\n    def setLvl(self,lvl):\n        self.lvl = lvl\n\n    def getAttr(self):\n        return self.attr_list\n\n    def getNodeId(self):\n        return self.node_id\n\n    def getParentId(self):\n        return self.parent_id\n    \n    def getDistToParent(self):\n        return self.dist_to_parent\n    \n    def getDensity(self):\n        return self.density\n\n    def getGamma(self):\n        return self.gamma\n\n    def getChildren(self):\n        return self.children\n    \n    def hasChildren(self,child_id):\n        if child_id in self.children:\n            return True\n        else:\n            return False\n\n    def getOffspringNum(self):\n        return self.offspring_num\n\n    def getLvl(self):\n        return self.lvl\n\n\n\n\nclass DPTree():\n    def __init__(self):\n        self.node_count = 0\n        self.node_dir = {}\n        self.root_node = None\n        self.node_offspring = {}\n        self.sorted_gamma_index = None\n        pass\n\n    def createTree(self,X,sorted_gamma_index,closest_node_id,closest_dis_denser,local_density,gamma):\n        #* 根据 gamma 顺序新建节点\n        node_dir = {}\n        node_created = np.zeros(len(sorted_gamma_index))\n        self.sorted_gamma_index = sorted_gamma_index\n        for i in range(len(sorted_gamma_index)):\n            node_id = sorted_gamma_index[i]\n            parent_id = closest_node_id[node_id] #* closest_node_id是根据排序后的gamma获得的\n            attr_list = X[node_id]\n            dist_to_parent = closest_dis_denser[node_id]\n            density = local_density[node_id]\n            if(node_created[node_id]==0):\n                node = Node(node_id,attr_list,parent_id,dist_to_parent=dist_to_parent,density=density,gamma[node_id],children=[])\n                node_created[node_id] = 1\n                node_dir[node_id] = node\n            node_dir[node_id].setParentId(parent_id)\n            if(node_created[parent_id]==0):\n                parent_node = Node(parent_id,X[parent_id],parent_id=None,dist_to_parent=closest_dis_denser[parent_id],density=local_density[parent_id],gamma=gamma[parent_id],children=[])\n                node_created[parent_id] = 1\n                node_dir[parent_id] = parent_node\n            parent_node = node_dir[parent_id]\n            cur_node = node_dir[node_id]\n            if(node_id != parent_id):#* 非根节点\n                parent_node.addChild(node_id)\n                # parent_lvl = parent_node.getLvl()\n                # cur_node.setLvl(parent_lvl+1)\n            else:\n                if(parent_node.getLvl()==None):\n                    parent_node.setLvl(0)\n\n        #* 设置节点层次信息\n        # for i in tree.node_dir:\n\n        #     pass\n                \n        self.root_node = node_dir[sorted_gamma_index[0]]\n        self.node_dir = node_dir\n        self.node_count = len(sorted_gamma_index)\n        pass\n\n    def printTree2(self,parent_id,spaceStr=''):\n        for node_id in self.node_dir:\n            if(node_id==self.root_node.node_id):\n                continue\n            node = self.node_dir[node_id]\n            if(node.parent_id==parent_id):\n                print(spaceStr, node.node_id, sep = '')\n                self.printTree2(node.node_id,spaceStr+'     ')\n        pass\n    \n    def calcu_subtree_offspring_num(self,node_id):\n        node = self.node_dir[node_id]\n        cur_offsprings = node.getOffspringNum()\n        if(cur_offsprings!=None):\n            return cur_offsprings\n        child_num = len(node.children)\n        if(child_num==0):\n            return 0\n        for i in node.children:\n            cur_offsprings = self.calcu_subtree_offspring_num(i)\n            child_num+=cur_offsprings\n        node.setOffspringNum(child_num)\n        return child_num\n\n    def get_subtree_offspring_id(self,node_id,other_idlist):\n        '''\n            获取所有子孙的node_id\n            考虑：是否需要存储在node属性中。\n        '''\n        def fn_get_subtree_offspring_id(node_id,offspring_idlist):\n            if(node_id in self.node_offspring.keys()):\n                return self.node_offspring[node_id]\n            else:\n                node = self.node_dir[node_id]\n                children = node.getChildren()\n                child_num = len(children)\n                if(child_num==0):\n                    self.node_offspring[node_id] = offspring_idlist\n                    return offspring_idlist\n                offspring_idlist= list(offspring_idlist) + children\n                for i in children:\n                    child_offspring_idlist = fn_get_subtree_offspring_id(i,[])\n                    self.node_offspring[i] = child_offspring_idlist\n                    offspring_idlist= list(offspring_idlist) + child_offspring_idlist\n                    pass\n                self.node_offspring[node_id] = offspring_idlist\n                return offspring_idlist             \n        offspring_idlist = fn_get_subtree_offspring_id(node_id,[])\n        return np.array(list(offspring_idlist) + other_idlist)\n        \n        \n\n    def calcu_subtree_entropy(self,offspring_id,local_density,closest_dis_denser):\n        p_sum = np.sum(local_density[offspring_id]/closest_dis_denser[offspring_id])\n        p = (local_density[offspring_id]/closest_dis_denser[offspring_id])/p_sum\n        entropy = -1*np.sum(p*np.log2(p))\n        #* 只有一个点的情况返回 0\n        if(entropy==0):\n            return 0\n        return entropy/(-1*np.log2(1/(len(offspring_id))))\n\n    \n    def remove_subtree(self,child_id):\n        '''\n            删除 node_id 节点的子树：child_id, 被删除的子树形成新的树并返回\n            1. 更新 self.node_dir, self.node_count\n            2. 更新 node_id 节点的 children[], 以及所有父级offspring_num\n            3. 生成新树\n        '''\n        # print(\"删除子节点：\",child_id)\n        offspring_id = self.get_subtree_offspring_id(child_id,[child_id])\n        offspring_len = len(offspring_id)\n        node_id = self.node_dir[child_id].parent_id\n        node = self.node_dir[node_id]\n        node.removeChild(child_id)\n        self.node_count = self.node_count-offspring_len\n        #* 删除存储的子孙节点\n        if(node_id in self.node_offspring.keys()):\n            for node_to_delete in offspring_id:\n                self.node_offspring[node_id].remove(node_to_delete)\n                print(\"删除子孙节点:\",node_to_delete)\n                pass\n            pass\n        # cur_id = child_id\n        # parent_id = node_id\n        # #* 设置父级 offspring_num:\n        # while(cur_id!=parent_id):\n        #     parent_node = self.node_dir[parent_id]\n        #     if(parent_node.getOffspringNum()!=None):\n        #         parent_node.setOffspringNum(parent_node.getOffspringNum()-offspring_len)\n        #     cur_id = parent_id\n        #     parent_id = parent_node.parent_id\n        #     pass\n        #* 更新 self.node_dir, 生成新树:\n        new_tree = DPTree()\n        for i in offspring_id:\n            removed_node = self.node_dir.pop(i)\n            new_tree.node_dir[i] = removed_node\n            pass\n        new_tree.node_count = offspring_len\n        new_tree.root_node = new_tree.node_dir[child_id]\n        new_tree.root_node.setParentId(child_id)\n        return new_tree\n\n    def calcu_dist_betw_subtree(self,node_id_one,node_id_two,dist_mat,eps):\n        '''\n            计算两个子树间的连通距离\n            return：\n                1. 最短距离\n                2. 小于距离阈值的点集\n        '''\n        connected_nodes = np.array([],dtype=np.int32)\n        offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one])\n        offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two])\n        dist = float('inf')\n        for i in offspring_two:\n            tmp_dist = np.min(dist_mat[i][offspring_one])\n            if(tmp_dist<dist):\n                dist = tmp_dist\n                pass\n            connected_nodes_index = np.where(dist_mat[i][offspring_one]<eps)[0]\n            if len(connected_nodes_index)>0:\n                connected_nodes = np.r_[[i],connected_nodes,offspring_one[connected_nodes_index]]\n                pass\n        return dist, np.unique(connected_nodes)\n\n    def calcu_neighbor_btw_subtree(self,node_id_one,node_id_two,mixin_near_matrix):\n        '''\n            计算两个子树间的邻近点\n            return:\n                邻近的点对\n                所有邻近点\n        '''\n        connected_nodes = np.array([],dtype=np.int32)\n        offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one])\n        offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two])\n        pairs_nodes = []\n        for i in offspring_two:\n            connected_nodes_index = np.intersect1d(mixin_near_matrix[i],offspring_one)\n            if len(connected_nodes_index)>0:\n                for j in connected_nodes_index:\n                    pairs_nodes.append([i,j])\n                    pass\n                pass\n        if(len(pairs_nodes)==0):\n            return pairs_nodes,connected_nodes\n        return np.array(pairs_nodes), np.unique(np.array(pairs_nodes).flatten())\n\n\n    def calcu_dist_betw_subtree_entropy(self,node_id_one,node_id_two,dist_mat,eps):\n        '''\n            计算两个子树间的连通距离\n            return：\n                1. 最大相似距离\n                2. 大于相似距离阈值的点集\n        '''\n        connected_nodes = np.array([],dtype=np.int32)\n        offspring_one = self.get_subtree_offspring_id(node_id_one,[node_id_one])\n        offspring_two = self.get_subtree_offspring_id(node_id_two,[node_id_two])\n        dist = -1\n        for i in offspring_two:\n            tmp_dist = np.max(dist_mat[i][offspring_one])\n            if(tmp_dist>=dist):\n                dist = tmp_dist\n                pass\n            connected_nodes_index = np.where(dist_mat[i][offspring_one]>=eps)[0]\n            if len(connected_nodes_index)>0:\n                connected_nodes = np.r_[[i],connected_nodes,offspring_one[connected_nodes_index]]\n                pass\n        return dist, np.unique(connected_nodes)\n\n\n    def calcu_depth(self,node_id, depth):\n        node = self.node_dir[node_id]\n        parent_id = node.parent_id\n        if(node_id==parent_id):\n            return depth\n        else:\n            return self.calcu_depth(parent_id,depth+1)\n", "meta": {"hexsha": "4c55db68c1c667219febb6705164366e8f8c7adb", "size": 18439, "ext": "py", "lang": "Python", "max_stars_repo_path": "ADPTC_LIB/DPTree_ST.py", "max_stars_repo_name": "SuilandCoder/ADPTC_LIB", "max_stars_repo_head_hexsha": "ef5c2b7fcf117c8c90a3841489471289ecbf4562", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ADPTC_LIB/DPTree_ST.py", "max_issues_repo_name": "SuilandCoder/ADPTC_LIB", "max_issues_repo_head_hexsha": "ef5c2b7fcf117c8c90a3841489471289ecbf4562", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ADPTC_LIB/DPTree_ST.py", "max_forks_repo_name": "SuilandCoder/ADPTC_LIB", "max_forks_repo_head_hexsha": "ef5c2b7fcf117c8c90a3841489471289ecbf4562", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5753138075, "max_line_length": 186, "alphanum_fraction": 0.6335484571, "include": true, "reason": "import numpy", "num_tokens": 4689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.19451570406757934}}
{"text": "#\n# The MIT License (MIT)\n#\n# Copyright (c) 2018-2020 azai/Rgveda/GolemQuant\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\nimport numpy as np\nimport numba as nb\nfrom numba import vectorize, float64, jit as njit\nimport scipy.stats as scs\nfrom datetime import datetime as dt, timezone, timedelta\n\nfrom analysis.timeseries import *\nfrom QUANTAXIS.QAUtil.QADate_Adv import (QA_util_print_timestamp,)\nimport pandas as pd\nimport empyrical\nfrom utils.parameter import (\n    AKA, \n    INDICATOR_FIELD as FLD, \n    TREND_STATUS as ST,\n    FEATURES as FTR,\n    )\n\n\"\"\"\n这里定义的是一些 fractal, strategy, portfolio 的绩效统计相关工具函数\n\"\"\"\n\ndef calc_fractal_stats(symbol, display_name, fractal_uid, fractal_triggers,\n                  ref_features=None, rsk_fre=0.04, annual=252, taxfee=0.0003, \n                  long=1, mode='lrc', format='pd'):\n    \"\"\"\n    explanation:\n        分型触发点(卖点or买点，取决于交易方向)绩效分析\n\n        什么是分型触发点呢？对大众认知的交易里，最通俗的含义就是特定交易策略的金叉/死叉点。\n        例如MACD金叉/死叉点，双MA金叉、死叉点，KDJ金叉、死叉点等。\n        它们全部都可以纳入这套 fractal_stats 评估体系中衡量。\n\n        它的功能用法有点像 alphalens，但是 alphalens 使用的框架体系是传统经济学量化金融\n        的那一套理论，跟我朴素的衡量标准并不一致。比如 alpha_beta 只计算当前 bar。\n        在我的交易系统内，并没有发现我认知的“趋势买点”和传统金融量化理论计算的 IC alpha值有\n        什么显著的相关性特征。\n        所以我只能另起炉灶，用统计学习的方式来量化衡量一个分型触发点的优劣。\n        这套分型系统的数学涵义上更类似深度学习中Attention模型的注意力关注点，能否与机器学习\n        结合有待后续研究。\n\n    params:\n        symbol: str, 交易标的代码\n        display_name: str, 交易标的显示名称\n        fractal_uid: str, 分型唯一标识编码\n        fractal_triggers : np.array, 分型触发信号\n        ref_features: np.array, 参考指标特征\n        rsk_fre: float32, 无风险利率\n        annual: int32, 年化周期\n        taxfee: float32, 税费\n        long: int32, 交易方向\n        mode: str, 'lrc' or 'zen' 趋势判断模式为 zen趋势 或者 lrc回归线趋势，\n                   'hmapower'为追踪hmapower120的MA逆序趋势，\n                   'raw'不进行趋势判断，完全跟随 fractal_triggers 状态信号\n        format : string, 返回格式\n\n    return:\n        pd.Series or np.array or string\n    \"\"\"\n    # 这里严格定义应该是考虑交易方向，但是暂时先偷懒简化了计算，以后做双向策略出现问题再完善\n    if (long > 0):\n        # 做多方向\n        fractal_cross_before = Timeline_duration(np.where(fractal_triggers > 0, 1, 0))\n    else:\n        # 做空方向\n        fractal_cross_before = Timeline_duration(np.where(fractal_triggers < 0, 1, 0))\n\n    if (annual > 125) and (annual < 366):\n        # 推断为日线级别的数据周期\n        fractal_forcast_position = np.where(fractal_cross_before < 3, 1, 0)\n        fractal_limited = 3\n    elif ((annual > 1680) and (annual < 2560)):\n        # 推断为数字币 4小时先级别的数据周期\n        fractal_limited = 24\n        fractal_forcast_position = np.where(fractal_cross_before < 24, 1, 0)\n    elif ((annual > 512) and (annual < 1280)):\n        # 推断为股票/证券1小时先级别的数据周期\n        fractal_limited = 12\n        fractal_forcast_position = np.where(fractal_cross_before < 12, 1, 0)\n    elif ((annual > 6180) and (annual < 9600)):\n        # 推断为股票/证券1小时先级别的数据周期\n        fractal_limited = 72\n        fractal_forcast_position = np.where(fractal_cross_before < 72, 1, 0)\n\n    # 固定统计3交易日内收益\n    fractal_forcast_3d_lag = calc_event_timing_lag(np.where(fractal_forcast_position > 0, 1, -1))\n    fractal_forcast_3d_lag = np.where(fractal_forcast_3d_lag <= fractal_limited, fractal_forcast_3d_lag, 0)\n    closep = ref_features[AKA.CLOSE].values\n\n    if (mode == 'lrc'):\n        # 统计到下一次 lineareg_band / 死叉等对等交易信号结束时的 收益，时间长度不固定\n        if (long > 0):\n            # 做多方向\n            lineareg_endpoint_before = Timeline_duration(np.where(ref_features[FLD.LINEAREG_BAND_TIMING_LAG] == -1, 1, 0))\n        else:\n            # 做空方向\n            lineareg_endpoint_before = Timeline_duration(np.where(ref_features[FLD.LINEAREG_BAND_TIMING_LAG] == 1, 1, 0))\n        fractal_lineareg_position = np.where(fractal_cross_before < lineareg_endpoint_before, 1, 0)\n        fractal_lineareg_lag = calc_event_timing_lag(np.where(fractal_lineareg_position > 0, 1, -1))\n\n        transcation_stats = calc_transcation_stats(fractal_triggers,\n                                                   closep,\n                                                   fractal_forcast_3d_lag,\n                                                   fractal_lineareg_lag,\n                                                   ref_features[FLD.LINEAREG_BAND_TIMING_LAG].values,\n                                                   taxfee=taxfee,\n                                                   long=long)\n\n        transcation_stats_df = pd.DataFrame(transcation_stats, columns=['trans_stats',\n                                                                        'trans_start',\n                                                                        'trans_act',\n                                                                        'trans_end', \n                                                                        'start_principle', \n                                                                        'ret_3d',\n                                                                        'ret_fractal',\n                                                                        'pric_settle',\n                                                                        'trans_3d',\n                                                                        'price_end_3d',\n                                                                        'price_end_fractal',\n                                                                        'ret_fractal_sim',\n                                                                        'long',\n                                                                        'duration_time',])\n    elif (mode == 'zen') or \\\n        (mode == 'mapower'):\n        if (long > 0):\n            # 做多方向\n            zen_wavelet_endpoint_before = Timeline_duration(np.where(ref_features[FLD.ZEN_WAVELET_TIMING_LAG] == -1, 1, 0))\n        else:\n            # 做空方向\n            zen_wavelet_endpoint_before = Timeline_duration(np.where(ref_features[FLD.ZEN_WAVELET_TIMING_LAG] == 1, 1, 0))\n        fractal_zen_wavelet_position = np.where(fractal_cross_before < zen_wavelet_endpoint_before, 1, 0)\n        fractal_zen_wavelet_lag = calc_event_timing_lag(np.where(fractal_zen_wavelet_position > 0, 1, -1))\n        transcation_stats = calc_transcation_stats_np(fractal_triggers,\n                                                   closep,\n                                                   fractal_forcast_3d_lag,\n                                                   fractal_zen_wavelet_lag,\n                                                   taxfee=taxfee,\n                                                   long=long)\n\n        transcation_stats_df = pd.DataFrame(transcation_stats, columns=['trans_stats',\n                                                                        'trans_start',\n                                                                        'trans_act',\n                                                                        'trans_end', \n                                                                        'start_principle', \n                                                                        'ret_3d',\n                                                                        'ret_fractal',\n                                                                        'pric_settle',\n                                                                        'trans_3d',\n                                                                        'price_end_3d',\n                                                                        'price_end_fractal',\n                                                                        'ret_fractal_sim',\n                                                                        'long',\n                                                                        'duration_time',])\n    elif (mode == 'hmapower') or \\\n        (mode == 'hmapower120') or \\\n        (mode == 'hmapower30'):\n        if (long > 0):\n            # 做多方向\n            hmapower120_endpoint_before = Timeline_duration(np.where(ref_features[FLD.HMAPOWER120_TIMING_LAG] == -1, 1, 0))\n        else:\n            # 做空方向\n            hmapower120_endpoint_before = Timeline_duration(np.where(ref_features[FLD.HMAPOWER120_TIMING_LAG] == 1, 1, 0))\n        fractal_hmapower120_position = np.where(fractal_cross_before < hmapower120_endpoint_before, 1, 0)\n        fractal_hmapower120_lag = calc_event_timing_lag(np.where(fractal_hmapower120_position > 0, 1, -1))\n        transcation_stats = calc_transcation_stats_np(fractal_triggers,\n                                                   closep,\n                                                   fractal_forcast_3d_lag,\n                                                   fractal_hmapower120_lag,\n                                                   taxfee=taxfee,\n                                                   long=long)\n\n        transcation_stats_df = pd.DataFrame(transcation_stats, columns=['trans_stats',\n                                                                        'trans_start',\n                                                                        'trans_act',\n                                                                        'trans_end', \n                                                                        'start_principle', \n                                                                        'ret_3d',\n                                                                        'ret_fractal',\n                                                                        'pric_settle',\n                                                                        'trans_3d',\n                                                                        'price_end_3d',\n                                                                        'price_end_fractal',\n                                                                        'ret_fractal_sim',\n                                                                        'long',\n                                                                        'duration_time',])\n    elif (mode == 'raw'):\n        fractal_position = np.where(fractal_triggers > 0, 1, 0)\n        fractal_timing_lag = calc_event_timing_lag(np.where(fractal_position > 0, 1, -1))\n        if (np.max(fractal_timing_lag) < 12):\n            #print('A spot Fractal, not a Complete Cycle Fractal')\n            pass\n        transcation_stats = calc_transcation_stats_np(fractal_triggers,\n                                                      closep,\n                                                      fractal_forcast_3d_lag,\n                                                      fractal_timing_lag,\n                                                      taxfee=taxfee,\n                                                      long=long)\n\n        transcation_stats_df = pd.DataFrame(transcation_stats, columns=['trans_stats',\n                                                                        'trans_start',\n                                                                        'trans_act',\n                                                                        'trans_end', \n                                                                        'start_principle', \n                                                                        'ret_3d',\n                                                                        'ret_fractal',\n                                                                        'pric_settle',\n                                                                        'trans_3d',\n                                                                        'price_end_3d',\n                                                                        'price_end_fractal',\n                                                                        'ret_fractal_sim',\n                                                                        'long',\n                                                                        'duration_time',])\n\n    transcation_stats_df[AKA.CODE] = symbol\n    transcation_stats_df['fractal_uid'] = fractal_uid\n\n    # bar ID索引 转换成交易时间戳\n    selected_trans_start = ref_features.iloc[transcation_stats[:, 1], :]\n    transcation_stats_df['trans_start'] = pd.to_datetime(selected_trans_start.index.get_level_values(level=0))\n    selected_trans_action = ref_features.iloc[transcation_stats[:, 2], :]\n    transcation_stats_df['trans_act'] = pd.to_datetime(selected_trans_action.index.get_level_values(level=0))\n    selected_trans_end = ref_features.iloc[transcation_stats[:, 3], :]\n    transcation_stats_df['trans_end'] = pd.to_datetime(selected_trans_end.index.get_level_values(level=0))\n\n    transcation_stats_df = transcation_stats_df.assign(datetime=pd.to_datetime(selected_trans_start.index.get_level_values(level=0))).drop_duplicates((['datetime',\n                                'code'])).set_index(['datetime',\n                                'code'],\n                                    drop=True)\n\n    return transcation_stats_df\n\n\n@nb.jit(nopython=True)\ndef calc_transcation_stats(fractal_triggers: np.ndarray, \n                           closep: np.ndarray,\n                           fractal_forcast_position: np.ndarray,\n                           fractal_sim_position: np.ndarray,\n                           principle_timing_lag: np.ndarray,\n                           taxfee: float=0.0003, \n                           long: int=1):\n\n    \"\"\"\n    explanation:\n        在“大方向”（规则）引导下，计算当前交易盈亏状况\n        np.ndarray 实现，编码规范支持JIT和Cython加速\n\n    params:\n        fractal_triggers : np.array, 分型触发信号\n        closep: np.array, 参考指标特征\n        fractal_forcast_position: np.ndarray,\n        fractal_principle_position: np.ndarray,\n        principle_timing_lag:np.ndarray,\n        taxfee: float32, 税费\n        long: int32, 交易方向\n\n    return:\n        np.array\n    \"\"\"\n    # 交易状态，状态机规则，低状态可以向高状态迁移\n    stats_nop = 0            # 无状态\n    stats_onhold = 1         # 执行交易并持有\n    stats_suspended = 2      # 挂起，不执行交易，观察走势\n    stats_closed = 3         # 结束交易\n    stats_teminated = 4      # 趋势走势不对，终止交易\n\n    idx_transcation = -1\n    idx_transcation_stats = 0\n    idx_transcation_start = 1\n    idx_transcation_action = 2\n    idx_transcation_endpoint = 3\n    idx_start_in_principle = 4\n    idx_forcast_returns = 5\n    idx_principle_returns = 6\n    idx_settle_price = 7\n    idx_transcation_3d = 8\n    idx_endpoint_price_3d = 9\n    idx_endpoint_price_principle = 10\n    idx_fractal_sim_returns = 11\n    idx_long = 12\n    idx_duration_time = 13\n    #idx_lineareg_band_lag = 12\n \n    ret_transcation_stats = np.zeros((len(closep), 14))\n    onhold_price = onhold_returns = 0.0\n    onhold_position_3d = onhold_position_lineareg = False\n    assert long == 1 or long == -1\n    ret_transcation_stats[:, idx_long] = long\n    for i in range(0, len(closep)):\n        # 开启交易判断\n        if (fractal_triggers[i] > 0) and \\\n            (not onhold_position_3d) and \\\n            (not onhold_position_lineareg):\n            onhold_position_3d = True\n            onhold_position_lineareg = True\n            idx_transcation = idx_transcation + 1\n            ret_transcation_stats[idx_transcation, idx_transcation_start] = i\n\n            if (principle_timing_lag[i] * long > 0):\n                ret_transcation_stats[idx_transcation, \n                                      idx_start_in_principle] = principle_timing_lag[i]\n                if (ret_transcation_stats[idx_transcation, \n                                          idx_start_in_principle] * long == -1):\n                    ret_transcation_stats[idx_transcation, \n                                          idx_transcation_stats] = stats_suspended\n                elif (ret_transcation_stats[idx_transcation, \n                                            idx_transcation_stats] < stats_onhold):\n                    ret_transcation_stats[idx_transcation, \n                                          idx_transcation_stats] = stats_onhold\n                    ret_transcation_stats[idx_transcation, \n                                          idx_transcation_action] = i\n            else:\n                ret_transcation_stats[idx_transcation, \n                                      idx_start_in_principle] = principle_timing_lag[i]\n                if (ret_transcation_stats[idx_transcation, \n                                          idx_transcation_stats] < stats_suspended):\n                    ret_transcation_stats[idx_transcation, \n                                          idx_transcation_stats] = stats_suspended\n\n            if (principle_timing_lag[i] * long > 0):\n                if (int(ret_transcation_stats[idx_transcation, \n                                              idx_transcation_stats]) == stats_onhold):\n                    onhold_price = closep[i]\n                    ret_transcation_stats[idx_transcation, \n                                          idx_settle_price] = onhold_price\n            elif (i != len(closep)):\n                if (int(ret_transcation_stats[idx_transcation, \n                                              idx_transcation_stats]) == stats_onhold):\n                    onhold_price = closep[i + 1]\n                    ret_transcation_stats[idx_transcation, \n                                          idx_settle_price] = onhold_price\n\n        if (onhold_position_lineareg) and (fractal_forcast_position[i] > 0):\n            if (principle_timing_lag[i] * long > 0):\n                if (int(ret_transcation_stats[idx_transcation, \n                                              idx_transcation_stats]) == stats_suspended):\n                    ret_transcation_stats[idx_transcation, \n                                          idx_transcation_stats] = stats_onhold\n                    ret_transcation_stats[idx_transcation, \n                                          idx_transcation_action] = i\n                    onhold_price = closep[i]\n                    ret_transcation_stats[idx_transcation, \n                                          idx_settle_price] = onhold_price\n            else:\n                ret_transcation_stats[idx_transcation, \n                                      idx_transcation_stats] = stats_suspended\n\n        # 结束交易判断\n        if (onhold_position_lineareg) and (fractal_sim_position[i] <= 0):\n            onhold_position_lineareg = False\n            onhold_position_3d = False\n            ret_transcation_stats[idx_transcation, \n                                  idx_transcation_endpoint] = i\n            onhold_sim_price = closep[int(ret_transcation_stats[idx_transcation, idx_transcation_start])]\n            ret_transcation_stats[idx_transcation, \n                                  idx_fractal_sim_returns] = (closep[i] - onhold_sim_price) / onhold_sim_price * long\n            if (int(ret_transcation_stats[idx_transcation, \n                                          idx_transcation_stats]) == stats_onhold):\n                ret_transcation_stats[idx_transcation, \n                                      idx_principle_returns] = (closep[i] - onhold_price) / onhold_price * long\n                ret_transcation_stats[idx_transcation, \n                                      idx_endpoint_price_principle] = closep[i]\n                ret_transcation_stats[idx_transcation, \n                                      idx_transcation_stats] = stats_closed\n                onhold_price = 0.0\n            elif (int(ret_transcation_stats[idx_transcation, \n                                            idx_transcation_stats]) == stats_suspended):\n                ret_transcation_stats[idx_transcation, \n                                      idx_transcation_stats] = stats_teminated\n                onhold_price = 0.0\n\n        if (onhold_position_3d) and (fractal_forcast_position[i] <= 0):\n            onhold_position_3d = False\n            ret_transcation_stats[idx_transcation, \n                                  idx_transcation_3d] = principle_timing_lag[i]\n            if (int(ret_transcation_stats[idx_transcation, \n                                          idx_transcation_stats]) == stats_onhold):\n                ret_transcation_stats[idx_transcation, \n                                      idx_forcast_returns] = (closep[i] - onhold_price) / onhold_price * long\n                ret_transcation_stats[idx_transcation, \n                                      idx_endpoint_price_3d] = closep[i]\n            elif (int(ret_transcation_stats[idx_transcation, \n                                            idx_transcation_stats]) == stats_suspended):\n                ret_transcation_stats[idx_transcation, \n                                      idx_transcation_stats] = stats_teminated\n                onhold_price = 0.0\n            else:\n                pass\n\n        if (onhold_position_lineareg) and (i == len(closep)):\n            # 交易当前处于未结束状态\n            if (int(ret_transcation_stats[idx_transcation, \n                                          idx_transcation_stats]) == stats_onhold):\n                ret_transcation_stats[idx_transcation, \n                                      idx_principle_returns] = (closep[i] - onhold_price) / onhold_price * long\n            pass\n        ret_transcation_stats[idx_transcation, \n                              idx_duration_time] = ret_transcation_stats[idx_transcation, \n                                                                         idx_transcation_endpoint] - ret_transcation_stats[idx_transcation, \n                                                                                                                           idx_transcation_action]\n\n    return ret_transcation_stats[:idx_transcation + 1, :]\n\n\n@nb.jit(nopython=True)\ndef calc_transcation_stats_np(fractal_triggers:np.ndarray, \n                              closep:np.ndarray,\n                              fractal_forcast_position:np.ndarray,\n                              fractal_timing_lag:np.ndarray,\n                              taxfee:float=0.0003, \n                              long:int=1):\n\n    \"\"\"\n    计算当前交易盈亏状况\n    np.ndarray 实现，编码规范支持JIT和Cython加速\n    \"\"\"\n    # 交易状态，状态机规则，低状态可以向高状态迁移\n    stats_nop = 0            # 无状态\n    stats_onhold = 1         # 执行交易并持有\n    stats_suspended = 2      # 挂起，不执行交易，观察走势\n    stats_closed = 3         # 结束交易\n    stats_teminated = 4      # 趋势走势不对，终止交易\n\n    idx_transcation = -1\n    idx_transcation_stats = 0\n    idx_transcation_start = 1\n    idx_transcation_action = 2\n    idx_transcation_endpoint = 3\n    idx_start_zen_wavelet = 4\n    idx_forcast_returns = 5\n    idx_fractal_returns = 6\n    idx_settle_price = 7\n    idx_transcation_3d = 8\n    idx_endpoint_price_3d = 9\n    idx_endpoint_price_fractal = 10\n    idx_fractal_sim_returns = 11\n    idx_long = 12\n    idx_duration_time = 13\n    #idx_lineareg_band_lag = 12\n \n    ret_transcation_stats = np.zeros((len(closep), 14))\n    onhold_price = onhold_returns = 0.0\n    onhold_position_3d = onhold_position_lineareg = False\n    assert long == 1 or long == -1\n    ret_transcation_stats[:, idx_long] = long\n    for i in range(0, len(closep)):\n        # 开启交易判断\n        if (fractal_triggers[i] > 0) and \\\n            (not onhold_position_3d) and \\\n            (not onhold_position_lineareg):\n            onhold_position_3d = True\n            onhold_position_lineareg = True\n            idx_transcation = idx_transcation + 1\n            ret_transcation_stats[idx_transcation, idx_transcation_start] = i\n            ret_transcation_stats[idx_transcation, \n                                  idx_transcation_stats] = stats_onhold\n            ret_transcation_stats[idx_transcation, idx_transcation_action] = i\n            onhold_price = closep[i]\n            ret_transcation_stats[idx_transcation, \n                                  idx_settle_price] = onhold_price\n\n        # 结束交易判断\n        if (onhold_position_lineareg) and (fractal_timing_lag[i] <= 0):\n            onhold_position_lineareg = False\n            onhold_position_3d = False\n            ret_transcation_stats[idx_transcation, \n                                  idx_transcation_endpoint] = i\n            ret_transcation_stats[idx_transcation, \n                                  idx_fractal_sim_returns] = (closep[i] - onhold_price) / onhold_price * long\n            ret_transcation_stats[idx_transcation, \n                                  idx_fractal_returns] = (closep[i] - onhold_price) / onhold_price * long\n            ret_transcation_stats[idx_transcation, \n                                  idx_endpoint_price_fractal] = closep[i]\n            ret_transcation_stats[idx_transcation, \n                                  idx_transcation_stats] = stats_closed\n            onhold_price = 0.0\n\n        if (onhold_position_3d) and (fractal_forcast_position[i] <= 0):\n            onhold_position_3d = False\n            ret_transcation_stats[idx_transcation, \n                                  idx_transcation_3d] = fractal_timing_lag[i]\n            if (onhold_position_lineareg):\n                ret_transcation_stats[idx_transcation, \n                                      idx_forcast_returns] = (closep[i] - onhold_price) / onhold_price * long\n                ret_transcation_stats[idx_transcation, \n                                      idx_endpoint_price_3d] = closep[i]\n            else:\n                ret_transcation_stats[idx_transcation, \n                                      idx_transcation_stats] = stats_teminated\n                onhold_price = 0.0\n\n        if (onhold_position_lineareg) and (i == len(closep)):\n            # 交易当前处于未结束状态\n            if (int(ret_transcation_stats[idx_transcation, \n                                          idx_transcation_stats]) == stats_onhold):\n                ret_transcation_stats[idx_transcation, \n                                      idx_fractal_returns] = (closep[i] - onhold_price) / onhold_price * long\n            pass\n        ret_transcation_stats[idx_transcation, \n                              idx_duration_time] = ret_transcation_stats[idx_transcation, \n                                                                         idx_transcation_endpoint] - ret_transcation_stats[idx_transcation, \n                                                                                                                         idx_transcation_action]\n\n    return ret_transcation_stats[:idx_transcation + 1, :]\n\n\ndef calc_strategy_stats(codelist, codename, strategy_name, timing_lag,\n                   ref_features=None, rsk_fre=0.04, annual=252, taxfee=0.0003, \n                   long=1, format='pd'):\n    \"\"\"\n    策略绩效分析，\n    包括年化 Sharpe Ratio，换手率, Max Drawdown 等\n\n    \"\"\"\n    portfolio_position = np.where(timing_lag > 0, 1, 0)\n    portfolio_returns = ref_features[idx_PCT_CHANGE] * np.r_[0, portfolio_position[:-1]]\n\n    # Turnover Analysis 简化计算，全仓操作 100%换手\n    portfolio_turnover = np.where(portfolio_position != np.r_[0, portfolio_position[:-1]], 1, 0)\n    portfolio_turnover_ratio = rolling_sum(portfolio_turnover, annual)\n\n    portfolio_annual_return = portfolio_returns.rolling(annual).apply(lambda x: \n                                                                      empyrical.annual_return(x, annualization=annual), \n                                                                      raw=True)\n    portfolio_sharpe_ratio = empyrical.roll_sharpe_ratio(portfolio_returns, risk_free=rsk_fre / annual, \n                                                         annualization=annual, window=annual)\n    portfolio_max_drawdown = empyrical.roll_max_drawdown(portfolio_returns, annual)\n\n    turnover_ratio_mean = np.mean(portfolio_turnover_ratio[annual:])\n    turnover_ratio_mean = turnover_ratio_mean if (turnover_ratio_mean > 2) else 24\n    annual_return_mean = np.mean((portfolio_annual_return.values - portfolio_turnover_ratio * taxfee)[annual:])\n\n    if (format != 'pd'):\n        ret_portfolio_state_template = 'Code {}, {}, {} sharpe:{:.2f}, annual_return:{:.2%}, max_drawdown:{:.2%}, turnover:{:.0%}'\n        ret_strategy_stats = ret_portfolio_state_template.format(codelist, \n                                         codename,\n                                         strategy_name,\n                                         portfolio_sharpe_ratio[-1], \n                                         (portfolio_annual_return.values - portfolio_turnover_ratio * taxfee)[-1], \n                                         portfolio_max_drawdown[-1],\n                                         portfolio_turnover_ratio[-1])\n        return ret_strategy_stats\n    else:\n        #print(ret_portfolio_state)\n        return pd.Series({'symbol':codelist,\n                          'name':codename,\n                          'portfolio':strategy_name,\n                          'sharpe':portfolio_sharpe_ratio[-1],\n                          'annual_return':(portfolio_annual_return.values - portfolio_turnover_ratio * taxfee)[-1],\n                          idx_TRANSACTION_RETURN_MEAN:annual_return_mean / (turnover_ratio_mean / 2),\n                          'max_drawdown': portfolio_max_drawdown[-1], \n                          'turnover_ratio': portfolio_turnover_ratio[-1]})\n\n\ndef portfolio_stats(codelist, codename, strategy_name, timing_lag, \n                    ref_features, rsk_fre=0.04, annual=252, taxfee=0.0003):\n    \"\"\"\n    策略组合/投资组合绩效分析\n\n    \"\"\"\n    portfolio_position = np.where(timing_lag > 0, 1, 0)\n    portfolio_returns = ref_features[idx_PCT_CHANGE] * np.r_[0, portfolio_position[:-1]]\n\n    # Turnover Analysis 简化计算，全仓操作 100%换手\n    portfolio_turnover = np.where(portfolio_position != np.r_[0, portfolio_position[:-1]], 1, 0)\n    portfolio_turnover_ratio = rolling_sum(portfolio_turnover, annual)\n\n    portfolio_annual_return = portfolio_returns.rolling(annual).apply(lambda x: \n                                                                      empyrical.annual_return(x, annualization=annual), \n                                                                      raw=True)\n    portfolio_sharpe_ratio = empyrical.roll_sharpe_ratio(portfolio_returns, risk_free=rsk_fre / annual, \n                                                         annualization=annual, window=annual)\n    portfolio_max_drawdown = empyrical.roll_max_drawdown(portfolio_returns, annual)\n\n    turnover_ratio_mean = np.mean(portfolio_turnover_ratio[annual:])\n    turnover_ratio_mean = turnover_ratio_mean if (turnover_ratio_mean > 2) else 24\n    annual_return_mean = np.mean((portfolio_annual_return.values - portfolio_turnover_ratio * taxfee)[annual:])\n\n    ret_portfolio_state_template = 'Code {}, {}, {} sharpe:{:.2f}, annual_return:{:.2%}, max_drawdown:{:.2%}, turnover:{:.0%}'\n    ret_portfolio_state = ret_portfolio_state_template.format(codelist, \n                                     codename,\n                                     strategy_name,\n                                     portfolio_sharpe_ratio[-1], \n                                     (portfolio_annual_return.values - portfolio_turnover_ratio * taxfee)[-1], \n                                     portfolio_max_drawdown[-1],\n                                     portfolio_turnover_ratio[-1])\n    #print(ret_portfolio_state)\n    return pd.Series({'symbol':codelist,\n                      'name':codename,\n                      'portfolio':strategy_name,\n                      'sharpe':portfolio_sharpe_ratio[-1],\n                      'annual_return':(portfolio_annual_return.values - portfolio_turnover_ratio * taxfee)[-1],\n                      idx_TRANSACTION_RETURN_MEAN:annual_return_mean / (turnover_ratio_mean / 2),\n                      'max_drawdown': portfolio_max_drawdown[-1], \n                      'turnover_ratio': portfolio_turnover_ratio[-1]})\n\n\ndef calc_onhold_positions(data, *args, **kwargs):\n    \"\"\"\n    计算复合仓位，支持QA add_func，第二个参数 默认为 indices= 为已经计算指标\n    理论上这个函数只计算单一标的，不要尝试传递复杂标的，indices会尝试拆分。\n    \"\"\"\n    # 针对多标的，拆分 indices 数据再自动合并\n    code = data.index.get_level_values(level=1)[0]\n    if ('indices' in kwargs.keys()):\n        indices = kwargs['indices'].loc[(slice(None), code), :]\n    elif (len(args) > 0):\n        indices = args[0].loc[(slice(None), code), :]\n    else:\n        print(u'Missing paramters: agrs[0] or kwargs[\\'indices\\']')\n        indices = None\n        \n    try:\n        indices[idx_ONHOLD_BEFORE] = Timeline_duration(np.where(((indices[ST.TRIGGER_R5] > 0).shift(1) == False) & \\\n                                                                (indices[ST.TRIGGER_R5] > 0), \n                                                                1, 0))\n        indices[idx_OFFHOLD_BEFORE] = Timeline_duration(np.where(((indices[ST.TRIGGER_R5] < 0).shift(1) == False) & \\\n                                                                 (indices[ST.TRIGGER_R5] < 0), \n                                                                 1, 0))\n    except:\n        print(code, \n              't1', indices.index.get_level_values(level=0)[0], \n              't2', indices.index.get_level_values(level=0)[-1])\n        raise Exception('fooo666:{}'.format(code))\n\n    indices[ST.POSITION_ONHOLD] = np.where(indices[idx_ONHOLD_BEFORE] < indices[idx_OFFHOLD_BEFORE], \n                                           1, 0)\n\n    # 平顺买点波动，平滑买点天数计数\n    indices[idx_ONHOLD_BEFORE] = Timeline_duration(np.where(((indices[ST.POSITION_ONHOLD] > 0).shift(1) == False) & \\\n                                                            (indices[ST.POSITION_ONHOLD] > 0), \n                                                            1, 0))\n    indices[idx_LEVERAGE_ONHOLD] = np.where(indices[ST.POSITION_ONHOLD] == 1, \n                                            indices[idx_LEVERAGE_NORM], 0)\n\n    #if (ST.VERBOSE in data.columns):\n    #    print(indices[[AKA.CLOSE,\n    #                   idx_BOLL_CROSS_SX_BEFORE,\n    #                   idx_ZSCORE_21,\n    #                   idx_ATR_CROSS,\n    #                   idx_MAXFACTOR_CROSS,\n    #                   idx_ZEN_TIDE_DENSITY,\n    #                   idx_COMBINE_DENSITY,\n    #                   ST.CANDIDATE]].tail(50))\n\n    return indices\n\n\n#@nb.jit(nopython=True)\n#def calc_onhold_returns_np(closep:np.ndarray,\n#                           features:np.ndarray,\n#                           long:int=1,\n#                           verbose:bool=True) -> np.ndarray:\n#    \"\"\"\n#    计算持仓利润，np.ndarray 实现，编码规范支持JIT和Cython加速\n#    \"\"\"\n#    idx_DATETIME = 0 # DATETIME\n#    idx_DAILY_RETURNS = 1 # DAILY_RETURNS\n#    idx_TRIGGER = 2 # BUY ACTION\n#    idx_ONHOLD_RETURNS = 2 # LEVERAGE 仓位 默认为 1\n#    idx_POSITION = 3 # ONHOLD STATE after BUY ACTION 1 bar\n#    idx_LEVERAGE = 4 # LEVERAGE 仓位 默认为 1\n\n#    ret_onhold_returns = np.zeros((len(closep), 4),)\n#    for i in range(1, len(features)):\n#        if (features[i, idx_POSITION] == 1) or \\\n#            ((features[i - 1, idx_TRIGGER] == 1)):\n#            if ((features[i - 1, idx_TRIGGER] == 1) and (features[i,\n#            idx_POSITION] != 1)):\n#                if (verbose):\n#                    print(u'买入状态设置，本应设置的状态没有设置。')\n#                features[i, idx_POSITION] == 1\n\n#            ret_onhold_returns[i, idx_DATETIME] = features[i, idx_DATETIME]\n#            ret_onhold_returns[i, idx_DAILY_RETURNS] = features[i,\n#            idx_DAILY_RETURNS]\n#            ret_onhold_returns[i, idx_POSITION] = features[i, idx_POSITION]\n#            ret_onhold_returns[i, idx_ONHOLD_RETURNS] = ret_onhold_returns[i,\n#            idx_ONHOLD_RETURNS] + features[i, idx_DAILY_RETURNS] *\n#            ret_onhold_returns[i, idx_POSITION]\n\n#    if (verbose):\n#        pass\n\n#    return ret_onhold_returns\n@nb.jit(nopython=True)\ndef calc_onhold_returns_v2(daily_returns:np.ndarray, \n                           daily_position:np.ndarray,\n                           long:int=1,) -> np.ndarray:\n    \"\"\"\n    计算当前持仓利润，当一次持仓状态结束的时候清零\n    np.ndarray 实现，编码规范支持JIT和Cython加速\n    \"\"\"\n    ret_onhold_returns = np.zeros(len(daily_returns),)\n    onhold_returns = 0.0\n    onhold_position = False\n    assert long == 1 or long == -1\n    for i in range(0, len(daily_position)):\n        if (onhold_position):\n            onhold_returns = onhold_returns + daily_returns[i] * long\n        else:\n            onhold_returns = 0.0            \n        ret_onhold_returns[i] = onhold_returns\n\n        if (daily_position[i] > 0):\n            onhold_position = True\n\n        if (daily_position[i] <= 0):\n            onhold_position = False\n\n    return ret_onhold_returns\n\n\n@nb.jit(nopython=True)\ndef calc_onhold_returns_np(closep:np.ndarray, \n                           daily_position:np.ndarray,\n                           long:int=1,) -> np.ndarray:\n    \"\"\"\n    计算当前持仓利润，当一次持仓状态结束的时候清零\n    np.ndarray 实现，编码规范支持JIT和Cython加速\n    \"\"\"\n    ret_onhold_returns = np.zeros(len(closep),)\n    onhold_price = onhold_returns = 0.0\n    onhold_position = False\n    assert long == 1 or long == -1\n    for i in range(0, len(daily_position)):\n        if (np.isnan(daily_position[i])):\n            continue\n\n        if (onhold_position):\n            if (daily_position[i - 1] <= 0):\n                onhold_price = closep[i]\n        else:\n            onhold_price = closep[i]\n        if (onhold_price > 0.001):\n            ret_onhold_returns[i] = (closep[i] - onhold_price) / onhold_price * long\n\n        if (daily_position[i] > 0):\n            onhold_position = True\n\n        if (daily_position[i] <= 0):\n            onhold_position = False\n\n    return ret_onhold_returns\n\n\ndef calc_onhold_returns(data, *args, **kwargs):\n    \"\"\"\n    计算持仓利润，支持QA add_func，第二个参数 默认为 indices= 为已经计算指标\n    理论上这个函数只计算单一标的，不要尝试传递复杂标的，indices会尝试拆分。\n    这是针对 pd 参数和 QA.add_func 的 Wrapper，因为不能JIT和Cython加速。\n    \"\"\"\n    # 针对多标的，拆分 indices 数据再自动合并\n    code = data.index.get_level_values(level=1)[0]\n    if ('indices' in kwargs.keys()):\n        indices = kwargs['indices'].loc[(slice(None), code), :]\n    elif (len(args) > 0):\n        indices = args[0].loc[(slice(None), code), :]\n    else:\n        print(u'Missing paramters: agrs[0] or kwargs[\\'indices\\']')\n        indices = None\n       \n    return indices\n\n\n#@nb.jit(nopython=True)\ndef calc_positions_StockCN(position:np.ndarray,\n                           indices:np.ndarray,\n                           upper_limit:int=1.0,\n                           lower_limit:int=0.0) -> np.ndarray:\n    \"\"\"\n    计算配合开仓条件的实际仓位变化，\n    \"\"\"\n    leverage_delta = position[:, 0]\n    position_norm = position[:, 1]\n    position_pre = position[:, 2]\n    position_signal = position[:, 3]\n\n    ma90_clearance = indices[:, 0]\n    ma120_clearance = indices[:, 1]\n    closep = indices[:, 2]\n\n    # 实际仓位变化为\n    position_delta = position_pre - position_norm\n\n    order_position = np.zeros((len(leverage_delta), 3))\n    for i in range(len(position_signal)):\n        if (i == 0):\n            order_position[i, 2] = 0.0\n        else:\n            order_position[i, 2] = np.nan\n\n        if (position_signal[i] > 0):\n            # 开仓模式\n            if (position_delta[i] > 0):\n                if ((ma90_clearance[i] + ma120_clearance[i]) > 1.24):\n                    # 高位冒险，尝试逐步加仓\n                    order_position[i, 0] = abs(max(position_delta[i], leverage_delta[i]))\n                else:\n                    # 直接一步到位建仓\n                    order_position[i, 0] = abs(position_norm[i])\n\n                order_position[i, 2] = order_position[i, 0]\n                continue\n        elif (position_signal[i] < 0):\n            if (position_delta[i] < 0):\n                if ((ma90_clearance[i] + ma120_clearance[i]) > 1.24) or \\\n                    (position_delta[i] < -0.168):\n                    # 高位冒险，直接清仓\n                    order_position[i, 0] = -max(position_pre[i], \n                                                order_position[i - 1, 2])\n                    order_position[i, 2] = 0.0\n                else:\n                    # 逐步减仓\n                    order_position[i, 0] = position_delta[i]\n                    order_position[i, 2] = order_position[i - 1, 2] + position_delta[i]\n                continue\n        \n        if (position_delta[i] < 0):\n            if ((order_position[i - 1, 2] + position_delta[i]) > 0):\n                # 逐步减仓\n                order_position[i, 0] = position_delta[i]\n                order_position[i, 2] = order_position[i - 1, 2] + position_delta[i]\n            else:\n                # 被动清仓\n                order_position[i, 0] = -max(position_pre[i],\n                                            order_position[i - 1, 2])\n                order_position[i, 2] = 0.0\n            continue\n        elif (position_delta[i] > 0):\n            if (order_position[i - 1, 2] > 0):\n                # 被动加仓\n                order_position[i, 0] = position_delta[i]\n                order_position[i, 2] = order_position[i - 1, 2] + position_delta[i]\n            else:\n                # 疑似踏空\n                order_position[i:, 1] = 1\n                order_position[i, 2] = order_position[i - 1, 2]\n        elif(abs(position_delta[i]) < 0.005):\n            # Do nothing 判断条件不足，阈值不足以做任何操作\n            order_position[i, 2] = order_position[i - 1, 2]\n\n    return order_position\n\n\n@nb.jit(nopython=True)\ndef calc_leverages(leverage_delta:np.ndarray,\n                   upper_limit:int=1.0,\n                   lower_limit:int=0.0) -> np.ndarray:\n    \"\"\"\n    计算连续加减杠杆（仓位）比例变化\n    \"\"\"\n    leverage_norm = np.zeros((len(leverage_delta),2))\n    for i in range(len(leverage_delta)):\n        leverage_norm[i, 1] = leverage_norm[i - 1, 0]\n        leverage_norm[i, 0] = leverage_norm[i - 1, 0] + leverage_delta[i]\n        if (leverage_norm[i, 0] > upper_limit):\n            leverage_norm[i, 0] = upper_limit\n        elif (leverage_norm[i, 0] < lower_limit):\n            leverage_norm[i, 0] = lower_limit\n    \n    return leverage_norm\n\n\ndef calc_massive_fractal_trend(features:pd.DataFrame=None,) -> pd.DataFrame:\n    \"\"\"\n    A股中某些特殊日子是建仓的黄道吉日，比如2020年8月20日，2020年8月27日，\n    2020年9月28~30日，20-12-28 29 30，2021年01月20日。\n    本函数用缠论折点的时间共振 + 高斯聚类判断(大雾) 其实只需要判断TIMING_LAG=1~4小时即可\n    计算出这些（决定性的建仓日）日子和在决定性的建仓日适合购买的股票。\n    \"\"\"\n    #print(u'calc_massive_fractal_trend')\n    symbol_list = sorted(features.index.get_level_values(level=1).unique())\n    column_list = [FLD.PEAK_LOW_TIMING_LAG,\n                   FLD.HMAPOWER120_TIMING_LAG,\n                   FLD.HMAPOWER120_QUARTER,\n                   FLD.MAPOWER30_TIMING_LAG,\n                   FLD.MAPOWER30_QUARTER,\n                   FLD.MA90_CLEARANCE,\n                   FLD.MA_CHANNEL,\n                   FLD.MACD_ZERO_TIMING_LAG,\n                   FLD.DIF_ZERO_TIMING_LAG,\n                   FLD.ZEN_WAVELET_TIMING_LAG,\n                   FLD.BOLL_RAISED_TIMING_LAG,\n                   FLD.POLYNOMIAL9_TIMING_LAG,\n                   FTR.POLYNOMIAL9_DUAL,\n                   FLD.MAPOWER30,\n                   FLD.MAPOWER30_MAJOR,\n                   FLD.HMAPOWER120_MAJOR,\n                   FLD.MAINFEST_UPRISING_COEFFICIENT,\n                   FTR.BOOTSTRAP_ENHANCED_TIMING_LAG,\n                   FLD.MAINFEST_DOWNRISK_TIMING_LAG,\n                   'dt']\n\n    #try:\n    if (True):\n        features['dt'] = pd.to_datetime(features.index.get_level_values(level=0),).tz_localize('Asia/Shanghai')\n        print(len(features.columns), len(set(features.columns.values)), len(features.columns), len(set(features.columns.values)))\n        # 对齐数据，DataFrame转为3维array数组，用于cython或者jit加速运行\n        features_aligned = features[column_list].unstack().ffill().bfill().stack()\n        features_np = features_aligned.drop(['dt'], \n                                            axis=1).values.reshape(*features.index.levshape,\n                                                                   -1)\n        #features_aligned['dt'] =\n        #pd.to_datetime(features_aligned.index.get_level_values(level=0),).tz_localize('Asia/Shanghai')\n        symbol_list = features_aligned.index.get_level_values(level=1).unique()\n        each_day = features_aligned['dt'].values\n        each_day_epoch = sorted(np.unique(each_day.astype(np.int64)) // 10 ** 9)\n        #print(type(np.array(each_day_epoch, dtype=np.int64)))\n        ret_massive_fractal_trend = calc_massive_uprising_func(np.array(each_day_epoch, dtype=np.int64), \n                                                               features_np)\n    #except Exception as e:\n    #    print(e)\n    #    each_day = features.index.get_level_values(level=0).unique()\n    #    symbol_list = features.index.get_level_values(level=1).unique()\n    #    each_day_epoch = sorted(each_day.astype(np.int64) // 10 ** 9)\n    #    ret_massive_fractal_trend = None\n\n    #print(u'calc_massive_fractal_trend phase #2')\n\n    if (ret_massive_fractal_trend is None):\n        features[FLD.MASSIVE_TREND] = np.nan\n        features[FLD.MASSIVE_TREND_BEFORE] = np.nan\n        features[FLD.MASSIVE_TREND_RETURNS] = np.nan\n        features[FLD.MASSIVE_TREND_CHECKOUT_CLOSE] = np.nan\n    else:\n        ret_massive_trend_pd = pd.DataFrame(ret_massive_fractal_trend, \n                                            index=pd.to_datetime(ret_massive_fractal_trend[:, 0],\n                                                                 unit='s').tz_localize('UTC').tz_convert('Asia/Shanghai').tz_localize(None),\n                                            columns=[AKA.DATETIME, FLD.MASSIVE_TREND, FLD.MAPOWER_MEDIAN])\n        #print(ret_massive_trend_pd.tail(100))\n        if (FLD.MASSIVE_TREND not in features.columns):\n            features = features.reindex(columns=[*features.columns,\n                                                 *[FLD.MASSIVE_TREND,\n                                                   FLD.MASSIVE_TREND_BEFORE,]])\n        for symbol in symbol_list:\n            features_slice = features.loc[(slice(None), symbol), :]\n            features.loc[(slice(None), symbol),\n                         FLD.MASSIVE_TREND] = np.where((features_slice[FLD.MAINFEST_DOWNRISK_TIMING_LAG] > 0) & \\\n                                                       (features_slice[FLD.MAINFEST_DOWNRISK_TIMING_LAG] <= 4) & \\\n                                                       (features_slice[FLD.SEMI_DOWNRISK] < 0.5) & \\\n                                                       (ret_massive_trend_pd.loc[features_slice.index.get_level_values(level=0), \n                                                                                 FLD.MASSIVE_TREND] > 0), 1, 0)\n            features.loc[(slice(None), symbol), \n                         FLD.MASSIVE_TREND_BEFORE] = Timeline_duration(features.loc[(slice(None), symbol),\n                                                                                    FLD.MASSIVE_TREND].values)\n            features.loc[(slice(None), symbol), \n                         FLD.MASSIVE_TREND_CHECKOUT_CLOSE] = np.where(features.loc[(slice(None), symbol), \n                                                                                   FLD.MASSIVE_TREND_BEFORE] == 0, \n                                                                      features_slice[AKA.CLOSE], np.nan)\n            features.loc[(slice(None), symbol), \n                         FLD.MASSIVE_TREND_CHECKOUT_CLOSE] = features.loc[(slice(None), symbol), \n                                                                          FLD.MASSIVE_TREND_CHECKOUT_CLOSE].ffill()\n            features.loc[(slice(None), symbol), \n                         FLD.MASSIVE_TREND_RETURNS] = np.log(features_slice[AKA.CLOSE] / features.loc[(slice(None), symbol), \n                                                                                                      FLD.MASSIVE_TREND_CHECKOUT_CLOSE])\n\n    return features, ret_massive_fractal_trend\n\n\n@nb.jit('f8[:,:](i8[:], f8[:,:,:])', nopython=True)\ndef calc_massive_fractal_trend_func(each_day_epoch:np.ndarray, \n                                    features_np:np.ndarray,) -> np.ndarray:\n    \"\"\"\n    在版块行情特征数据中提取上升浪\n    \"\"\"\n    #print(features.shape)\n    idx_PEAK_LOW_TIMING_LAG = 0\n    idx_HMAPOWER120_TIMING_LAG = 1\n    idx_HMAPOWER120_QUARTER = 2\n    idx_MAPOWER30_TIMING_LAG = 3\n    idx_MAPOWER30_QUARTER = 4\n    idx_MA90_CLEARANCE = 5\n    idx_MA_CHANNEL = 6\n    idx_MACD_ZERO_TIMING_LAG = 7\n    idx_DIF_ZERO_TIMING_LAG = 8\n    idx_ZEN_WAVELET_TIMING_LAG = 9\n    idx_BOLL_RAISED_TIMING_LAG = 10\n    idx_POLYNOMIAL9_TIMING_LAG = 11\n    idx_POLYNOMIAL9_DUAL = 12\n    idx_MAPOWER30 = 13\n    idx_MAPOWER30_MAJOR = 14\n    idx_HMAPOWER120_MAJOR = 15\n    idx_MAINFEST_UPRISING_COEFFICIENT = 16\n    idx_BOOTSTRAP_ENHANCED_TIMING_LAG = 17\n    idx_MAINFEST_DOWNRISK_TIMING_LAG = 18\n\n    ret_massive_fractal_trend = np.zeros((len(each_day_epoch),3))\n    ret_massive_fractal_trend[:, 0] = each_day_epoch\n    totals = len(features_np[0, :, idx_PEAK_LOW_TIMING_LAG])\n    polynomial9_sum_yesterday = 0\n    mapower_median_yesterday = 0\n    mainfest_uprising_median_yesterday = 0\n    bootstrap_enhanced_median_yesterday = 0\n    for i in range(0, len(each_day_epoch)):\n        mapower_median = np.median(features_np[i, :, idx_MAPOWER30]) + np.median(features_np[i, :, idx_MAPOWER30_MAJOR]) + np.median(features_np[i, :, idx_HMAPOWER120_MAJOR])\n        mainfest_uprising_median = np.median(features_np[i, :, idx_MAINFEST_UPRISING_COEFFICIENT])\n        bootstrap_enhanced_median = np.median(features_np[i, :, idx_BOOTSTRAP_ENHANCED_TIMING_LAG])\n        day_pieces = np.where(features_np[i, :, idx_POLYNOMIAL9_TIMING_LAG] > 0)\n        polynomial9_sum = np.sum(np.where(features_np[i, :, idx_POLYNOMIAL9_TIMING_LAG] > 0, 1, 0))\n        polynomial9_dual_sum = np.sum(np.where(features_np[i, :, idx_POLYNOMIAL9_DUAL] > 0, 1, 0))\n\n        if (np.median(features_np[i, :, idx_PEAK_LOW_TIMING_LAG]) > 0) and \\\n           (np.median(features_np[i, :, idx_HMAPOWER120_TIMING_LAG]) > 0) and \\\n           (np.median(features_np[i, :, idx_HMAPOWER120_QUARTER]) > 0) and \\\n           (np.median(features_np[i, :, idx_MAPOWER30_TIMING_LAG]) > 0) and \\\n           (np.median(features_np[i, :, idx_MAPOWER30_QUARTER]) > 0) and \\\n           (np.median(features_np[i, :, idx_MA90_CLEARANCE]) > 0) and \\\n           (np.median(features_np[i, :, idx_MA_CHANNEL]) > 0) and \\\n           ((np.median(features_np[i, :, idx_MACD_ZERO_TIMING_LAG]) > 0) or \\\n           ((np.median(features_np[i, :, idx_MA90_CLEARANCE]) < 0.618) and \\\n           (np.median(features_np[i, :, idx_ZEN_WAVELET_TIMING_LAG]) > 0))) and \\\n           (np.median(features_np[i, :, idx_DIF_ZERO_TIMING_LAG]) > 0):\n            if ((int(mainfest_uprising_median) != 1) and (int(bootstrap_enhanced_median) != 1) and \\\n                (mapower_median_yesterday > mapower_median)) or \\\n                ((int(mainfest_uprising_median) > 20) and (int(bootstrap_enhanced_median) > 20)):\n                pass\n            else:\n                ret_massive_fractal_trend[i, 1] = 1\n        \n        if ((polynomial9_sum / totals > 0.382) and (polynomial9_dual_sum / polynomial9_sum > 0.618) and \\\n            (polynomial9_sum_yesterday < polynomial9_sum / totals) and (mapower_median < 2.3)) or \\\n            ((polynomial9_sum / totals > 0.618) and (polynomial9_dual_sum / polynomial9_sum > 0.512) and \\\n            (polynomial9_sum_yesterday > 0.618) and (mapower_median < 1)) or \\\n            ((polynomial9_sum / totals > 0.618) and (polynomial9_dual_sum / polynomial9_sum > 0.618) and \\\n            (mapower_median < 1)) or \\\n            ((polynomial9_sum / totals > 0.618) and (polynomial9_dual_sum / polynomial9_sum > 0.512) and \\\n            (mapower_median < 0.618)) or \\\n            ((int(mainfest_uprising_median) == 1) and \\\n            (int(mainfest_uprising_median_yesterday) < 0.1) and (bootstrap_enhanced_median_yesterday < 0.1)) or \\\n            ((int(mainfest_uprising_median) == 1) and \\\n            (int(mainfest_uprising_median_yesterday) == 1) and (bootstrap_enhanced_median_yesterday < 0.1)) or \\\n            ((int(bootstrap_enhanced_median) == 1) and \\\n            ((mainfest_uprising_median - bootstrap_enhanced_median) > -0.1) and \\\n            ((mainfest_uprising_median - bootstrap_enhanced_median) < 6.1)):\n            if ((int(mainfest_uprising_median) != 1) and (int(bootstrap_enhanced_median) != 1) and \\\n                (mapower_median_yesterday > mapower_median)) or \\\n                ((int(mainfest_uprising_median) > 20) and (int(bootstrap_enhanced_median) > 20)):\n                pass\n            else:\n                if (ret_massive_fractal_trend[i, 1] == 0) :\n                    ret_massive_fractal_trend[i, 1] = 2\n                    #print(QA_util_print_timestamp(each_day[i]),\n                    #polynomial9_sum,\n                    #          '{:.2%}'.format(polynomial9_sum / totals),\n                    #          '{:3d}'.format(polynomial9_dual_sum),\n                    #          '{:.2%}'.format(polynomial9_dual_sum /\n                    #          polynomial9_sum),\n                    #          '{:.3f}'.format(np.median(features[i,\n                    #          day_pieces, idx_BOLL_RAISED_TIMING_LAG])),\n                    #          '{:.3f}'.format(np.quantile(features[i,\n                    #          day_pieces, idx_BOLL_RAISED_TIMING_LAG], 0.75)),\n                    #          '{:.3f}'.format(np.median(features[i, :,\n                    #          idx_MAPOWER30])),\n                    #          '{:.3f}'.format(np.median(features[i, :,\n                    #          idx_MAPOWER30_MAJOR])),\n                    #          '{:.3f}'.format(np.median(features[i, :,\n                    #          idx_HMAPOWER120_MAJOR])),\n                    #          '{:.1f}'.format(np.median(features[i, :,\n                    #          idx_MAINFEST_UPRISING_COEFFICIENT])),\n                    #          '{:.1f}'.format(np.median(features[i, :,\n                    #          idx_BOOTSTRAP_ENHANCED_TIMING_LAG])),\n                    #          '{:.3f}'.format(mapower_median), u'<<-- 建仓日')\n                else:\n                    ret_massive_fractal_trend[i, 1] = 3\n                    #print(QA_util_print_timestamp(each_day[i]),\n                    #polynomial9_sum,\n                    #          '{:.2%}'.format(polynomial9_sum / totals),\n                    #          '{:3d}'.format(polynomial9_dual_sum),\n                    #          '{:.2%}'.format(polynomial9_dual_sum /\n                    #          polynomial9_sum),\n                    #          '{:.3f}'.format(np.median(features[i, :,\n                    #          idx_BOLL_RAISED_TIMING_LAG])),\n                    #          '{:.3f}'.format(np.quantile(features[i, :,\n                    #          idx_BOLL_RAISED_TIMING_LAG], 0.75)),\n                    #          '{:.3f}'.format(np.median(features[i, :,\n                    #          idx_MAPOWER30])),\n                    #          '{:.3f}'.format(np.median(features[i, :,\n                    #          idx_MAPOWER30_MAJOR])),\n                    #          '{:.3f}'.format(np.median(features[i, :,\n                    #          idx_HMAPOWER120_MAJOR])),\n                    #          '{:.1f}'.format(np.median(features[i, :,\n                    #          idx_MAINFEST_UPRISING_COEFFICIENT])),\n                    #          '{:.1f}'.format(np.median(features[i, :,\n                    #          idx_BOOTSTRAP_ENHANCED_TIMING_LAG])),\n                    #          '{:.3f}'.format(mapower_median), u'<<-- 建仓日')\n        else:\n            #print(QA_util_print_timestamp(each_day[i]), polynomial9_sum,\n            #              '{:.2%}'.format(polynomial9_sum / totals),\n            #              '{:3d}'.format(polynomial9_dual_sum),\n            #              '{:.2%}'.format(polynomial9_dual_sum /\n            #              polynomial9_sum),\n            #              '{:.3f}'.format(np.median(features[i, :,\n            #              idx_BOLL_RAISED_TIMING_LAG])),\n            #              '{:.3f}'.format(np.quantile(features[i, :,\n            #              idx_BOLL_RAISED_TIMING_LAG], 0.75)),\n            #              '{:.3f}'.format(np.median(features[i, :,\n            #              idx_MAPOWER30])),\n            #              '{:.3f}'.format(np.median(features[i, :,\n            #              idx_MAPOWER30_MAJOR])),\n            #              '{:.3f}'.format(np.median(features[i, :,\n            #              idx_HMAPOWER120_MAJOR])),\n            #              '{:.1f}'.format(np.median(features[i, :,\n            #              idx_MAINFEST_UPRISING_COEFFICIENT])),\n            #              '{:.1f}'.format(np.median(features[i, :,\n            #              idx_BOOTSTRAP_ENHANCED_TIMING_LAG])),\n            #              '{:.3f}'.format(mapower_median))\n            pass\n        ret_massive_fractal_trend[i, 2] = mapower_median\n        polynomial9_sum_yesterday = polynomial9_sum / totals\n        mainfest_uprising_median_yesterday = mainfest_uprising_median\n        bootstrap_enhanced_median_yesterday = bootstrap_enhanced_median\n        mapower_median_yesterday = mapower_median\n            #print(i, each_day[i], 'Yes!')\n        #if (i % 100 == 0):\n        #    print(i, each_day[i])\n        #pass\n    #print('sum', np.sum(ret_massive_fractal_trend[:, 1]))\n    return ret_massive_fractal_trend\n\n\n@nb.jit('f8[:,:](i8[:], f8[:,:,:])', nopython=True)\ndef calc_massive_uprising_func(each_day_epoch:np.ndarray, \n                               features_np:np.ndarray,) -> np.ndarray:\n    \"\"\"\n    在版块行情特征数据中提取上升浪\n    \"\"\"\n    idx_PEAK_LOW_TIMING_LAG = 0\n    idx_HMAPOWER120_TIMING_LAG = 1\n    idx_HMAPOWER120_QUARTER = 2\n    idx_MAPOWER30_TIMING_LAG = 3\n    idx_MAPOWER30_QUARTER = 4\n    idx_MA90_CLEARANCE = 5\n    idx_MA_CHANNEL = 6\n    idx_MACD_ZERO_TIMING_LAG = 7\n    idx_DIF_ZERO_TIMING_LAG = 8\n    idx_ZEN_WAVELET_TIMING_LAG = 9\n    idx_BOLL_RAISED_TIMING_LAG = 10\n    idx_POLYNOMIAL9_TIMING_LAG = 11\n    idx_POLYNOMIAL9_DUAL = 12\n    idx_MAPOWER30 = 13\n    idx_MAPOWER30_MAJOR = 14\n    idx_HMAPOWER120_MAJOR = 15\n    idx_MAINFEST_UPRISING_COEFFICIENT = 16\n    idx_BOOTSTRAP_ENHANCED_TIMING_LAG = 17\n    idx_MAINFEST_DOWNRISK_TIMING_LAG = 18\n\n    ret_massive_fractal_trend = np.zeros((len(each_day_epoch),3))\n    ret_massive_fractal_trend[:, 0] = each_day_epoch\n    totals = len(features_np[0, :, idx_PEAK_LOW_TIMING_LAG])\n    for i in range(0, len(each_day_epoch)):\n        mapower_median = np.median(features_np[i, :, idx_MAPOWER30]) + np.median(features_np[i, :, idx_MAPOWER30_MAJOR]) + np.median(features_np[i, :, idx_HMAPOWER120_MAJOR])\n        ret_massive_fractal_trend[i, 2] = mapower_median\n        uprising_counts = np.where(features_np[i, :, idx_MAINFEST_DOWNRISK_TIMING_LAG] == 1)[0]\n        if ((len(uprising_counts) * 4 / totals > 0.1236) and not ((totals < 100) and (len(uprising_counts) < 4))) or \\\n            ((totals < 100) and (len(uprising_counts) > 5)) or \\\n            ((len(uprising_counts) * 4 / totals > 0.0927) and (len(uprising_counts) > 5)):\n            ret_massive_fractal_trend[i, 1] = 1\n            #print(QA_util_print_timestamp(each_day[i]), u'<<-- 建仓日',\n            #      'len {:d}, {:.02%}'.format(len(uprising_counts),\n            #                                (len(uprising_counts) * 4) /\n            #                                totals),\n            #      uprising_counts)\n        else:\n            #print(QA_util_print_timestamp(each_day[i]),\n            #      'len {:d}, {:.02%}'.format(len(uprising_counts),\n            #                                (len(uprising_counts) * 4) /\n            #                                totals),\n            #      uprising_counts)\n            pass\n\n    return ret_massive_fractal_trend\n\n\ndef calc_massive_csindex_trend(features:pd.DataFrame=None,) -> pd.DataFrame:\n    \"\"\"\n    \"\"\"\n    symbol_list = sorted(features.index.get_level_values(level=1).unique())\n   \n    column_list = [FLD.PEAK_OPEN,\n                   FLD.ZEN_PEAK_TIMING_LAG,\n                   FLD.ZEN_DASH_TIMING_LAG,\n                   FLD.ZEN_WAVELET_TIMING_LAG,\n                   FLD.ZEN_BOOST_TIMING_LAG,\n                   FLD.RENKO_BOOST_S_TIMING_LAG,\n                   FLD.RENKO_TREND_S_TIMING_LAG,\n                   FLD.PEAK_LOW_TIMING_LAG,\n                   FLD.HMAPOWER120_TIMING_LAG,\n                   FLD.MAPOWER30_TIMING_LAG,\n                   FLD.MACD_ZERO_TIMING_LAG,\n                   FLD.DIF_ZERO_TIMING_LAG,\n                   FLD.POLYNOMIAL9_TIMING_LAG,\n                   FLD.MAPOWER30,\n                   FLD.HMAPOWER120,]\n\n    # 对齐数据，DataFrame转为3维array数组，用于cython或者jit加速运行\n    try:\n        features_aligned = features[column_list].unstack().ffill().bfill().stack()\n        features_np = features_aligned.values.reshape(*features.index.levshape,-1)\n        features_aligned['dt'] = pd.to_datetime(kline.data.index.get_level_values(level=0),).tz_localize('Asia/Shanghai')\n        each_day = features_aligned['dt'].values\n        symbol_list = features_aligned.index.get_level_values(level=1).unique()\n        each_day_epoch = sorted(each_day.astype(np.int64) // 10 ** 9)\n\n        ret_massive_fractal_trend = calc_massive_csindex_trend_func(np.array(each_day_epoch, dtype=np.int64), \n                                                                    features_np)\n    except:\n        each_day = features.index.get_level_values(level=0).unique()\n        symbol_list = features.index.get_level_values(level=1).unique()\n        each_day_epoch = sorted(each_day.astype(np.int64) // 10 ** 9)\n        ret_massive_fractal_trend = None\n\n    if (ret_massive_fractal_trend is None):\n        features[FLD.MASSIVE_TREND] = np.nan\n    else:\n        ret_massive_trend_pd = pd.DataFrame(ret_massive_fractal_trend, \n                                            index=pd.to_datetime(ret_massive_fractal_trend[:, 0],\n                                                                 unit='s'),\n                                            columns=[AKA.DATETIME, FLD.MASSIVE_TREND, FLD.MAPOWER_MEDIAN])\n\n        features[FLD.MASSIVE_TREND] = ret_massive_trend_pd.loc[ret_codelist_combo.index.get_level_values(level=0), \n                                                                      FLD.MASSIVE_TREND].values\n\n    return features, ret_massive_fractal_trend\n\n\n#@nb.jit('f8[:,:](i8[:], f8[:,:,:])', nopython=True)\ndef calc_massive_csindex_trend_func(each_day:np.ndarray, \n                                    features:np.ndarray,) -> np.ndarray:\n    \"\"\"\n    在版块行情特征数据中提取上升浪\n    \"\"\"\n    #print(features.shape)\n    idx_PEAK_LOW_TIMING_LAG = 0\n    idx_HMAPOWER120_TIMING_LAG = 1\n    idx_HMAPOWER120_QUARTER = 2\n    idx_MAPOWER30_TIMING_LAG = 3\n    idx_MAPOWER30_QUARTER = 4\n    idx_MA90_CLEARANCE = 5\n    idx_MA_CHANNEL = 6\n    idx_MACD_ZERO_TIMING_LAG = 7\n    idx_DIF_ZERO_TIMING_LAG = 8\n    idx_ZEN_WAVELET_TIMING_LAG = 9\n    idx_PREDICT_GROWTH = 10\n    idx_POLYNOMIAL9_TIMING_LAG = 11\n    idx_POLYNOMIAL9_DUAL = 12\n    idx_MAPOWER30 = 13\n    idx_MAPOWER30_MAJOR = 14\n    idx_HMAPOWER120_MAJOR = 15\n    idx_MAINFEST_UPRISING_COEFFICIENT = 16\n    idx_BOOTSTRAP_ENHANCED_TIMING_LAG = 17\n\n    ret_massive_fractal_trend = np.zeros((len(each_day),3))\n    ret_massive_fractal_trend[:, 0] = each_day\n    totals = len(features[0, :, idx_PEAK_LOW_TIMING_LAG])\n    polynomial9_sum_yesterday = 0\n    mapower_median_yesterday = 0\n    mainfest_uprising_median_yesterday = 0\n    bootstrap_enhanced_median_yesterday = 0\n    for i in range(0, len(each_day)):\n        mapower_median = np.median(features[i, :, idx_MAPOWER30]) + np.median(features[i, :, idx_MAPOWER30_MAJOR]) + np.median(features[i, :, idx_HMAPOWER120_MAJOR])\n        mainfest_uprising_median = np.median(features[i, :, idx_MAINFEST_UPRISING_COEFFICIENT])\n        bootstrap_enhanced_median = np.median(features[i, :, idx_BOOTSTRAP_ENHANCED_TIMING_LAG])\n        day_pieces = np.where(features[i, :, idx_POLYNOMIAL9_TIMING_LAG] > 0)\n        polynomial9_sum = np.sum(np.where(features[i, :, idx_POLYNOMIAL9_TIMING_LAG] > 0, 1, 0))\n        polynomial9_dual_sum = np.sum(np.where(features[i, :, idx_POLYNOMIAL9_DUAL] > 0, 1, 0))\n\n        if (np.median(features[i, :, idx_PEAK_LOW_TIMING_LAG]) > 0) and \\\n           (np.median(features[i, :, idx_HMAPOWER120_TIMING_LAG]) > 0) and \\\n           (np.median(features[i, :, idx_HMAPOWER120_QUARTER]) > 0) and \\\n           (np.median(features[i, :, idx_MAPOWER30_TIMING_LAG]) > 0) and \\\n           (np.median(features[i, :, idx_MAPOWER30_QUARTER]) > 0) and \\\n           (np.median(features[i, :, idx_MA90_CLEARANCE]) > 0) and \\\n           (np.median(features[i, :, idx_MA_CHANNEL]) > 0) and \\\n           ((np.median(features[i, :, idx_MACD_ZERO_TIMING_LAG]) > 0) or \\\n           ((np.median(features[i, :, idx_MA90_CLEARANCE]) < 0.618) and \\\n           (np.median(features[i, :, idx_ZEN_WAVELET_TIMING_LAG]) > 0))) and \\\n           (np.median(features[i, :, idx_DIF_ZERO_TIMING_LAG]) > 0):\n            if ((int(mainfest_uprising_median) != 1) and (int(bootstrap_enhanced_median) != 1) and \\\n                (mapower_median_yesterday > mapower_median)) or \\\n                ((int(mainfest_uprising_median) > 20) and (int(bootstrap_enhanced_median) > 20)):\n                pass\n            else:\n                ret_massive_fractal_trend[i, 1] = 1\n        \n        if ((polynomial9_sum / totals > 0.382) and (polynomial9_dual_sum / polynomial9_sum > 0.618) and \\\n            (polynomial9_sum_yesterday < polynomial9_sum / totals) and (mapower_median < 2.3)) or \\\n            ((polynomial9_sum / totals > 0.618) and (polynomial9_dual_sum / polynomial9_sum > 0.512) and \\\n            (polynomial9_sum_yesterday > 0.618) and (mapower_median < 1)) or \\\n            ((polynomial9_sum / totals > 0.618) and (polynomial9_dual_sum / polynomial9_sum > 0.618) and \\\n            (mapower_median < 1)) or \\\n            ((polynomial9_sum / totals > 0.618) and (polynomial9_dual_sum / polynomial9_sum > 0.512) and \\\n            (mapower_median < 0.618)) or \\\n            ((int(mainfest_uprising_median) == 1) and \\\n            (int(mainfest_uprising_median_yesterday) < 0.1) and (bootstrap_enhanced_median_yesterday < 0.1)) or \\\n            ((int(mainfest_uprising_median) == 1) and \\\n            (int(mainfest_uprising_median_yesterday) == 1) and (bootstrap_enhanced_median_yesterday < 0.1)) or \\\n            ((int(bootstrap_enhanced_median) == 1) and \\\n            ((mainfest_uprising_median - bootstrap_enhanced_median) > -0.1) and \\\n            ((mainfest_uprising_median - bootstrap_enhanced_median) < 6.1)):\n            if ((int(mainfest_uprising_median) != 1) and (int(bootstrap_enhanced_median) != 1) and \\\n                (mapower_median_yesterday > mapower_median)) or \\\n                ((int(mainfest_uprising_median) > 20) and (int(bootstrap_enhanced_median) > 20)):\n                pass\n            else:\n                if (ret_massive_fractal_trend[i, 1] == 0) :\n                    ret_massive_fractal_trend[i, 1] = 2\n                    #print(QA_util_print_timestamp(each_day[i]),\n                    #polynomial9_sum,\n                    #          '{:.2%}'.format(polynomial9_sum / totals),\n                    #          '{:3d}'.format(polynomial9_dual_sum),\n                    #          '{:.2%}'.format(polynomial9_dual_sum /\n                    #          polynomial9_sum),\n                    #          '{:.3f}'.format(np.median(features[i,\n                    #          day_pieces, idx_PREDICT_GROWTH])),\n                    #          '{:.3f}'.format(np.quantile(features[i,\n                    #          day_pieces, idx_PREDICT_GROWTH], 0.75)),\n                    #          '{:.3f}'.format(np.median(features[i, :,\n                    #          idx_MAPOWER30])),\n                    #          '{:.3f}'.format(np.median(features[i, :,\n                    #          idx_MAPOWER30_MAJOR])),\n                    #          '{:.3f}'.format(np.median(features[i, :,\n                    #          idx_HMAPOWER120_MAJOR])),\n                    #          '{:.1f}'.format(np.median(features[i, :,\n                    #          idx_MAINFEST_UPRISING_COEFFICIENT])),\n                    #          '{:.1f}'.format(np.median(features[i, :,\n                    #          idx_BOOTSTRAP_ENHANCED_TIMING_LAG])),\n                    #          '{:.3f}'.format(mapower_median), u'<<-- 建仓日')\n                else:\n                    ret_massive_fractal_trend[i, 1] = 3\n                    #print(QA_util_print_timestamp(each_day[i]),\n                    #polynomial9_sum,\n                    #          '{:.2%}'.format(polynomial9_sum / totals),\n                    #          '{:3d}'.format(polynomial9_dual_sum),\n                    #          '{:.2%}'.format(polynomial9_dual_sum /\n                    #          polynomial9_sum),\n                    #          '{:.3f}'.format(np.median(features[i, :,\n                    #          idx_PREDICT_GROWTH])),\n                    #          '{:.3f}'.format(np.quantile(features[i, :,\n                    #          idx_PREDICT_GROWTH], 0.75)),\n                    #          '{:.3f}'.format(np.median(features[i, :,\n                    #          idx_MAPOWER30])),\n                    #          '{:.3f}'.format(np.median(features[i, :,\n                    #          idx_MAPOWER30_MAJOR])),\n                    #          '{:.3f}'.format(np.median(features[i, :,\n                    #          idx_HMAPOWER120_MAJOR])),\n                    #          '{:.1f}'.format(np.median(features[i, :,\n                    #          idx_MAINFEST_UPRISING_COEFFICIENT])),\n                    #          '{:.1f}'.format(np.median(features[i, :,\n                    #          idx_BOOTSTRAP_ENHANCED_TIMING_LAG])),\n                    #          '{:.3f}'.format(mapower_median), u'<<-- 建仓日')\n        else:\n            #print(QA_util_print_timestamp(each_day[i]), polynomial9_sum,\n            #              '{:.2%}'.format(polynomial9_sum / totals),\n            #              '{:3d}'.format(polynomial9_dual_sum),\n            #              '{:.2%}'.format(polynomial9_dual_sum /\n            #              polynomial9_sum),\n            #              '{:.3f}'.format(np.median(features[i, :,\n            #              idx_PREDICT_GROWTH])),\n            #              '{:.3f}'.format(np.quantile(features[i, :,\n            #              idx_PREDICT_GROWTH], 0.75)),\n            #              '{:.3f}'.format(np.median(features[i, :,\n            #              idx_MAPOWER30])),\n            #              '{:.3f}'.format(np.median(features[i, :,\n            #              idx_MAPOWER30_MAJOR])),\n            #              '{:.3f}'.format(np.median(features[i, :,\n            #              idx_HMAPOWER120_MAJOR])),\n            #              '{:.1f}'.format(np.median(features[i, :,\n            #              idx_MAINFEST_UPRISING_COEFFICIENT])),\n            #              '{:.1f}'.format(np.median(features[i, :,\n            #              idx_BOOTSTRAP_ENHANCED_TIMING_LAG])),\n            #              '{:.3f}'.format(mapower_median))\n            pass\n        ret_massive_fractal_trend[i, 2] = mapower_median\n        polynomial9_sum_yesterday = polynomial9_sum / totals\n        mainfest_uprising_median_yesterday = mainfest_uprising_median\n        bootstrap_enhanced_median_yesterday = bootstrap_enhanced_median\n        mapower_median_yesterday = mapower_median\n            #print(i, each_day[i], 'Yes!')\n        #if (i % 100 == 0):\n        #    print(i, each_day[i])\n        #pass\n    #print('sum', np.sum(ret_massive_fractal_trend[:, 1]))\n    return ret_massive_fractal_trend", "meta": {"hexsha": "130d1ee3411e9ee04186c111ba35341d663d6b55", "size": 71958, "ext": "py", "lang": "Python", "max_stars_repo_path": "portfolio/utils.py", "max_stars_repo_name": "xixigaga/GolemQ", "max_stars_repo_head_hexsha": "79640eaf34ab61c1591879e58c135ed2bab0c8ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "portfolio/utils.py", "max_issues_repo_name": "xixigaga/GolemQ", "max_issues_repo_head_hexsha": "79640eaf34ab61c1591879e58c135ed2bab0c8ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "portfolio/utils.py", "max_forks_repo_name": "xixigaga/GolemQ", "max_forks_repo_head_hexsha": "79640eaf34ab61c1591879e58c135ed2bab0c8ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.1792318634, "max_line_length": 174, "alphanum_fraction": 0.5287667806, "include": true, "reason": "import numpy,import scipy,import numba,from numba", "num_tokens": 17817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3557748866829643, "lm_q1q2_score": 0.19451570406757931}}
{"text": "# Author: Xavier Paredes-Fortuny (xparedesfortuny@gmail.com)\n# License: MIT, see LICENSE.md\n\nimport numpy as np\nimport time\nimport interpolation_methods as im\nfrom resamp_line import resamp_line\n\n\ndef buffer_present_line(xc, yc, ic, jc, densc, epsc, vxc, vyc,\n                        divc, tracerc, tc, line_values):\n    \"\"\"Keeps track of all the line parameters\"\"\"\n\n    line_values.append([xc, yc, ic, jc, densc, epsc,\n                        vxc, vyc, divc, tracerc, tc])\n    return\n\n\ndef buffer_all_lines(all_lines, line_values):\n    \"\"\"Keeps track of all the complete lines\"\"\"\n\n    all_lines.append(line_values)\n    return\n\n\ndef save_all_lines(output_file, all_lines):\n    \"\"\"Save all the lines to a file.\n       Two lines for each current line:\n       1) length of line\n       2) (xc, yc, ic, jc,  densc, epsc, vxc, vyc, divc, tracerc, tc)\n       times the length of the line\"\"\"\n\n    with open(output_file + '.dat', 'w') as f:\n        for line in all_lines:\n            line_length = len(line)\n            f.write(str(line_length) + '\\n')\n            for n in range(line_length):\n                for var in line[n]:\n                    f.write(str(var) + ' ')\n            f.write('\\n')\n    return\n\n\ndef save_one_file_per_line(output_file, all_lines, gammaad, c, fB0, tr0,\n                           sf0_array, excluded_lines, input_file):\n    \"\"\"Save one file per line. Each column:\n    x, y, z, vx, vy, vz, dens, P, B, -div(v)/3, S, tracer\n    We can not give the adiabatic losses because they are for the nonthermal\n    particles, and from the RHD simulation we do not have this information.\n    Therefore we just give -div(v)/3 instead of dE/dt.\n    The line surface is given by the flux conservation from the initial\n    surface for each line at the injection point (sf0). The surface\n    corresponds to that one perpendicular to the line directon.\"\"\"\n\n    # Discard the excluded lines from the \"sf0_array\" and add the excluded\n    # line surface to the previous line\n    #print np.sum(sf0_array[:, 0])\n    aux = 1\n    while aux == 1:\n        aux = 0\n        sf0 = sf0_array[:, 0]\n        for ll in range(len(sf0)):\n            sf0_ind =  (sf0_array[ll,1], sf0_array[ll,2])\n            if sf0_ind in excluded_lines:\n                if ll == 0:\n                    sf0[1] += sf0[0]\n                else:\n                    sf0[ll-1] += sf0[ll]\n                sf0_array = np.delete(sf0_array, ll, 0)\n                aux = 1\n                break\n\n    #print np.sum(sf0_array[:, 0]), len(sf0_array), len(all_lines)\n    if len(sf0) != len(all_lines):\n        raise RuntimeError('Surface indices do not match with line indices')\n\n    # Discard lines with mixing\n    aux = 1\n    while aux == 1:\n        aux = 0\n        sf0 = sf0_array[:, 0]\n        sf0_ind = sf0_array[:, 1]\n        for ll in range(len(sf0)):\n            x, y, i, j, dens, eps, vx, vy, div, tracer, time = zip(*all_lines[ll])\n            for tr in tracer:\n                if tr > tr0:\n                    aux = 1\n                    break\n            if aux == 1:\n                if ll == 0:\n                    sf0[1] += sf0[0]\n                else:\n                    sf0[ll-1] += sf0[ll]\n                sf0_array = np.delete(sf0_array, ll, 0)\n                del all_lines[ll]\n                break\n    #print np.sum(sf0_array[:, 0]), len(sf0_array), len(all_lines)\n    #print np.sum(sf0_array[:, 0])/(1e12)**2., len(sf0_array), len(all_lines)\n    #print 2010612.22971\n    if len(sf0) != len(all_lines):\n        raise RuntimeError('Surface indices do not match with line indices')\n\n    # Compute secondary variables and create the output files\n    for ll, line in enumerate(all_lines):\n        #with open('lines/'+output_file + '_' + str(ll+1) + '.dat', 'w') as f:\n        with open('lines/lines' + str(ll+1).zfill(3), 'w') as f:\n            x, y, i, j, dens, eps, vx, vy, div, tracer, time = zip(*line)\n            x = np.array(x)\n            y = np.array(y)\n            z = np.zeros_like(x) # WARNING: modify if 3D\n            dens = np.array(dens)\n            eps = np.array(eps)\n            vx = np.array(vx)\n            vy = np.array(vy)\n            vz = np.zeros_like(vx) # WARNING: modify if 3D\n            div = np.array(div)\n            tracer = np.array(tracer)\n            time = np.array(time)\n\n            # We will compute secondary variables only for nonzero cells\n            nz = np.ones_like(time, dtype=bool)\n            for l, t in enumerate(time):\n                if l != 0 and t==0:\n                    nz[l] = 0\n            v = np.zeros_like(time)\n            v[nz] = np.sqrt(vx[nz]**2.+vy[nz]**2.)\n\n            gamma = np.zeros_like(time)\n            gamma[nz] = 1./np.sqrt(1.-(v[nz]/c)**2.)\n\n            P = np.zeros_like(time)\n            P[nz] = (gammaad-1.)*dens[nz]*eps[nz]\n\n            h = np.zeros_like(time)\n            h[nz] = 1.+eps[nz]/c**2.+P[nz]/dens[nz]/c**2.\n            B = np.zeros_like(time)\n            #B0 = np.sqrt(fB0*8.*np.pi*(dens[0]*h[0]*c**2.-dens[0]*c**2.-P[0]))\n\n            # Energy flux equality\n            B0 = np.sqrt(fB0*4.*np.pi*(dens[0]*h[0]*c**2.))\n            B[nz] = B0*(dens[nz]*v[0]*gamma[0]/dens[0]/v[nz]/gamma[nz])**0.5\n\n            fe = np.zeros_like(time)\n            fe[nz] = dens[nz]*gamma[nz]**2.*h[nz]*v[nz]#-dens[nz]*gamma[nz]*v[nz]\n            sf = np.zeros_like(time)\n            sf[nz] = sf0[ll]*fe[0]/fe[nz] # Energy flux conservation\n#            Particle flux conservation\n#            sf[nz] = sf0[ll]*(dens[0]*v[0]*gamma[0]/dens[nz]/v[nz]/gamma[nz])\n\n            # Save to file\n            line_length = len(time)\n            for n in range(line_length):\n                f.write(str(x[n]) + ' ')\n                f.write(str(y[n]) + ' ')\n                f.write(str(z[n]) + ' ')\n                f.write(str(vx[n]) + ' ')\n                f.write(str(vy[n]) + ' ')\n                f.write(str(vz[n]) + ' ')\n                f.write(str(dens[n]) + ' ')\n                f.write(str(P[n]) + ' ')\n                f.write(str(B[n]) + ' ')\n                f.write(str(-div[n]/3.) + ' ')\n                f.write(str(sf[n]) + ' ')\n                f.write(str(tracer[n]))\n                f.write('\\n')\n    return all_lines\n\n\ndef initial_position(xc, yc):\n    \"\"\"Returns the initial position at t=0\"\"\"\n\n    return xc, yc\n\n\ndef initial_indices(ic, jc):\n    \"\"\"Returns the initial indices at t=0\"\"\"\n\n    return ic, jc\n\n\ndef initial_variables(densc, epsc, vxc, vyc, divc, tracerc):\n    \"\"\"Returns the initial variables at t=0\"\"\"\n\n    return densc, epsc, vxc, vyc, divc, tracerc\n\n\ndef update_position(xc, yc, vxc, vyc, tstep):\n    \"\"\"Returns the new position after a time step\"\"\"\n\n    xc = xc+vxc*tstep\n    yc = yc+vyc*tstep\n    return xc, yc\n\n\ndef update_indices(xc, yc, xl, yl, xr, yr, ic, jc, vxc, vyc, nx, ny):\n    \"\"\"Returns the cell indices for a given coordinates\"\"\"\n\n    if vxc > 0:\n        iend = nx\n        di = 1\n    else:\n        iend = -1  # xrange function does not include the last element\n        di = -1\n    for i in xrange(ic, iend, di):\n        if (xc >= xl[i]) and (xc < xr[i]):\n            ic = i\n            break\n\n    if vyc > 0:\n        jend = ny\n        dj = 1\n    else:\n        jend = -1\n        dj = -1\n    for j in xrange(jc, jend, dj):\n        if (yc >= yl[j]) and (yc < yr[j]):\n            jc = j\n            break\n    return ic, jc\n\n\ndef interpolate(xc, yc, ic, jc, x, y, dens, eps, vx, vy, div, tracer,\n                nx, ny, int_method, int_test):\n    \"\"\"Interpolate the physical variables at (xc, yc)\"\"\"\n\n    dens_test = 0\n    if int_test == 1:\n        dens_test = dens[ic, jc]\n    elif int_test == 2:\n        dens_test = im.bilinear(xc, yc, ic, jc, x, y, dens, nx, ny)\n    elif int_test == 3:\n        dens_test = im.one_dimensional(xc, yc, ic, jc, x, y, dens, nx, ny)\n\n    if int_method == 0:\n        return dens[ic, jc], eps[ic, jc], vx[ic, jc], vy[ic, jc], div[ic, jc], tracer[ic, jc], dens_test\n    elif int_method == 1:\n        densi = im.bilinear(xc, yc, ic, jc, x, y, dens, nx, ny)\n        epsi = im.bilinear(xc, yc, ic, jc, x, y, eps, nx, ny)\n        vxi = im.bilinear(xc, yc, ic, jc, x, y, vx, nx, ny)\n        vyi = im.bilinear(xc, yc, ic, jc, x, y, vy, nx, ny)\n        divi = im.bilinear_div(xc, yc, ic, jc, x, y, div, nx, ny)\n        traceri = im.bilinear(xc, yc, ic, jc, x, y, tracer, nx, ny)\n        return densi, epsi, vxi, vyi, divi, traceri, dens_test\n    elif int_method == 2:\n        densi = im.one_dimensional(xc, yc, ic, jc, x, y, dens, nx, ny)\n        epsi = im.one_dimensional(xc, yc, ic, jc, x, y, eps, nx, ny)\n        vxi = im.one_dimensional(xc, yc, ic, jc, x, y, vx, nx, ny)\n        vyi = im.one_dimensional(xc, yc, ic, jc, x, y, vy, nx, ny)\n        divi = div[ic, jc]\n        traceri = im.one_dimensional(xc, yc, ic, jc, x, y, tracer, nx, ny)\n        return densi, epsi, vxi, vyi, divi, traceri, dens_test\n\n\ndef buffer_diff(densc, densc2, int_diff):\n    \"\"\"Keeps the difference between the two interpolation methods\"\"\"\n\n    int_diff.append(abs(densc-densc2)/densc*100.)\n    return\n\n\ndef tstep_test(ic, jc, ic_aux, jc_aux):\n    \"\"\"Checks if the time step is too large\"\"\"\n\n    if abs(ic-ic_aux) > 1 or abs(jc-jc_aux) > 1:\n        raise RuntimeError('Step larger than 1 cell. '\n                           'Reduce the tstep parameter')\n\n\ndef code_units_to_CGS(all_lines, sf0, c, rho0, a):\n    \"\"\"Converts from code units to the CGS unit system.\"\"\"\n\n    sf0[:, 0] = sf0[:, 0]*a**2.\n    all_lines_new = []\n    for line in all_lines:\n        x, y, i, j, dens, eps, vx, vy, div, tracer, time = zip(*line)\n\n        x = np.array(x)*a\n        y = np.array(y)*a\n        i = np.array(i)\n        j = np.array(j)\n        dens = np.array(dens)*rho0\n        eps = np.array(eps)*c**2.\n        vx = np.array(vx)*c\n        vy = np.array(vy)*c\n        div = np.array(div)*c/a\n        tracer = np.array(tracer)\n        time = np.array(time)*a/c\n\n        line_new = []\n        for l in range(len(x)):\n            line_new.append([x[l], y[l], i[l], j[l], dens[l],\n                             eps[l], vx[l], vy[l], div[l], tracer[l],\n                             time[l]])\n        all_lines_new.append(line_new)\n    return all_lines_new, sf0\n\n\ndef compute_lines(x, y, xl, yl, xr, yr, vx, vy, dens, eps, tracer,\n                  injec, sf0, tstep,\n                  nx, ny, lx, ly, dx, dy, gammaad, div, itemax, resamp,\n                  int_method, int_test, CGS_units, c, rho0, a, fB0, tr0,\n                  input_file, output_file):\n    \"\"\"Returns the current lines for a given RHD simulation\"\"\"\n\n    print '\\nComputing the current lines...'\n\n    start_time = time.time()\n    all_lines = []\n    int_diff = []\n    excluded_lines = []\n\n    for i0, j0 in injec:\n        line_values = []\n        tc = 0.\n        xc, yc = initial_position(x[i0], y[j0])\n        ic, jc = initial_indices(i0, j0)\n        densc, epsc, vxc, vyc, divc, tracerc = initial_variables(dens[ic, jc],\n                                                 eps[ic, jc], vx[ic, jc],\n                                                 vy[ic, jc], div[ic,jc],\n                                                 tracer[ic, jc])\n        ic_aux, jc_aux = ic, jc\n        buffer_present_line(xc, yc, ic, jc, densc, epsc,\n                            vxc, vyc, divc, tracerc, tc, line_values)\n\n        ite = 1\n        while True:\n            tc += tstep\n            xc, yc = update_position(xc, yc, vxc, vyc, tstep)\n\n            if (xc > lx) or (xc < 0) or (yc > ly) or (yc < 0):\n                break\n\n            ic, jc = update_indices(xc, yc, xl, yl, xr, yr, ic, jc,\n                                        vxc, vyc, nx, ny)\n\n            tstep_test(ic, jc, ic_aux, jc_aux)\n            ic_aux, jc_aux = ic, jc\n\n            try:\n                (densc, epsc, vxc,\n                 vyc, divc, tracerc, densc2) = interpolate(xc, yc, ic, jc, x, y,\n                                                           dens, eps, vx, vy, div,\n                                                           tracer, nx, ny, int_method,\n                                                           int_test)\n            except Exception:\n                print 'WARNING: Interpolation failed for line starting at [{}, {}]'.format(i0,j0)\n\n            if int_test != 0:\n                buffer_diff(densc, densc2, int_diff)\n\n            buffer_present_line(xc, yc, ic, jc, densc, epsc,\n                                vxc, vyc, divc, tracerc, tc, line_values)\n            ite += 1\n            if ite == itemax:\n                print 'WARNING: Line starting at [{}, {}] did not converged. Increase itemax parameter?'.format(i0,j0)\n                excluded_lines += [(i0,j0)]\n                break\n\n        if ite != itemax:\n            buffer_all_lines(all_lines, line_values)\n\n    if resamp != 0:\n        all_lines = resamp_line(all_lines, resamp, a, CGS_units)\n\n    if CGS_units == 1:\n        all_lines, sf0 = code_units_to_CGS(all_lines, sf0, c, rho0, a)\n\n    save_all_lines(output_file, all_lines)\n\n    if CGS_units == 1:\n        all_lines = save_one_file_per_line(output_file, all_lines, gammaad, c, fB0,\n                                           tr0, sf0, excluded_lines, input_file)\n    else:\n        print 'WARNING: current lines not saved. CGS unit conversion is off'\n\n    if int_test != 0:\n        print \"Density difference between the two interpolation methods: \" \\\n            \"{:.2f} %\".format(np.average(np.array(int_diff)))\n    print \"Done (elapsed time: {:.0f} seconds) \"\\\n          .format(time.time() - start_time)\n    return all_lines\n", "meta": {"hexsha": "e1fd84feb6d078f583c4f4ff22d379daced1ce53", "size": 13457, "ext": "py", "lang": "Python", "max_stars_repo_path": "compute_lines.py", "max_stars_repo_name": "xparedesfortuny/pylines", "max_stars_repo_head_hexsha": "f61c1d818480cf1d209bc59f442c0df9081cf435", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-12-15T15:29:03.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-15T15:29:03.000Z", "max_issues_repo_path": "compute_lines.py", "max_issues_repo_name": "xparedesfortuny/pylines", "max_issues_repo_head_hexsha": "f61c1d818480cf1d209bc59f442c0df9081cf435", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "compute_lines.py", "max_forks_repo_name": "xparedesfortuny/pylines", "max_forks_repo_head_hexsha": "f61c1d818480cf1d209bc59f442c0df9081cf435", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2277486911, "max_line_length": 118, "alphanum_fraction": 0.5116296351, "include": true, "reason": "import numpy", "num_tokens": 3907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.19451570254702918}}
{"text": "#! /usr/bin/env python\n# -*- coding: utf8 -*-\n\n''' \n\nCopyright 2018 University of Liège\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. \n\ninterpolator.py\nInterface interpolator and communicator.\nAuthors : David THOMAS, Marco Lucio CERQUAGLIA, Romain BOMAN\n\n'''\n\n# ----------------------------------------------------------------------\n#  Imports\n# ----------------------------------------------------------------------\n\nimport numpy as np\nimport sys\n\nimport ccupydo\nfrom utilities import *\nfrom interfaceData import FlexInterfaceData\nfrom interfaceData import InterfaceMatrix\nfrom linearSolver import LinearSolver\n\nnp.set_printoptions(threshold=sys.maxsize)\n\n# ----------------------------------------------------------------------\n#    Interpolator class\n# ----------------------------------------------------------------------\n\nclass InterfaceInterpolator(ccupydo.CInterpolator):\n    \"\"\"\n    Interpolator of CUPyDO.\n    Perform inteporlation of fluid-structure meshes.\n    Inherited public members :\n        -matching_fillMatrix()\n        -TPS_fillMatrixA()\n        -TPS_fillMatrixB()\n        -RBF_fillMatrixA()\n        -RBF_fillMatrixB()\n        -PHI_TPS()\n        -PHI_RBF()\n        -distance()\n    \"\"\"\n\n    def __init__(self, Manager, FluidSolver, SolidSolver, mpiComm = None, chtTransferMethod=None, heatTransferCoeff=1.0):\n        \"\"\"\n        Description.\n        \"\"\"\n\n        mpiPrint('\\n***************************** Initializing FSI interpolator *****************************', mpiComm)\n\n        ccupydo.CInterpolator.__init__(self, Manager)\n\n        self.manager = Manager\n        self.SolidSolver = SolidSolver\n        self.FluidSolver = FluidSolver\n\n        self.mappingTimer = Timer()\n\n        self.nf = self.manager.getNumberOfFluidInterfaceNodes()\n        self.ns = self.manager.getNumberOfSolidInterfaceNodes()\n        self.nf_loc = self.manager.getNumberOfLocalFluidInterfaceNodes()\n        self.ns_loc = self.manager.getNumberOfLocalSolidInterfaceNodes()\n        self.nDim = self.manager.getnDim()\n\n        self.d = 0\n\n        if self.manager.thermal:\n            self.chtTransferMethod = chtTransferMethod\n            if self.chtTransferMethod not in ['TFFB','FFTB','hFTB','hFFB']:\n                mpiPrint('CHT transfer method not specified or not recognized, using default TFFB',mpiComm)\n                self.chtTransferMethod = 'TFFB'\n        else:\n            self.chtTransferMethod = None\n\n        if self.chtTransferMethod in ['hFTB','hFFB']:\n            self.heatTransferCoeff = heatTransferCoeff\n        else:\n            self.heatTransferCoeff = None\n\n        self.mpiComm = mpiComm\n\n        if self.mpiComm != None:\n            self.myid = self.mpiComm.Get_rank()\n            self.mpiSize = self.mpiComm.Get_size()\n        else:\n            self.myid = 0\n            self.mpiSize = 1\n\n        self.solidInterfaceDisplacement = None\n        self.fluidInterfaceDisplacement = None\n        self.solidInterfaceLoads = None\n        self.fluidInterfaceLoads = None\n\n        self.solidInterfaceHeatFlux = None\n        self.fluidInterfaceHeatFlux = None\n        self.solidInterfaceTemperature = None\n        self.fluidInterfaceTemperature = None\n        self.fluidInterfaceNormalHeatFlux = None\n        self.solidInterfaceNormalHeatFlux = None\n        self.fluidInterfaceRobinTemperature = None\n        self.solidInterfaceRobinTemperature = None\n\n    def checkTotalLoad(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        FX, FY, FZ = self.solidInterfaceLoads.sum()\n\n        FFX, FFY, FFZ = self.fluidInterfaceLoads.sum()\n\n        mpiPrint(\"Checking f/s interface total force...\", self.mpiComm)\n        mpiPrint('Solid side (Fx, Fy, Fz) = ({}, {}, {})'.format(FX, FY, FZ), self.mpiComm)\n        mpiPrint('Fluid side (Fx, Fy, Fz) = ({}, {}, {})'.format(FFX, FFY, FFZ), self.mpiComm)\n\n    def getDisplacementFromSolidSolver(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        if self.myid in self.manager.getSolidInterfaceProcessors():\n            localSolidInterfaceDisp_X, localSolidInterfaceDisp_Y, localSolidInterfaceDisp_Z = self.SolidSolver.getNodalDisplacements()\n            for iVertex in range(self.ns_loc):\n                iGlobalVertex = self.manager.getGlobalIndex('solid', self.myid, iVertex)\n                self.solidInterfaceDisplacement[iGlobalVertex] = [localSolidInterfaceDisp_X[iVertex], localSolidInterfaceDisp_Y[iVertex], localSolidInterfaceDisp_Z[iVertex]]\n\n        self.solidInterfaceDisplacement.assemble()\n\n    def getHeatFluxFromSolidSolver(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        if self.myid in self.manager.getSolidInterfaceProcessors():\n            localSolidInterfaceHeatFlux_X, localSolidInterfaceHeatFlux_Y, localSolidInterfaceHeatFlux_Z = self.SolidSolver.getNodalHeatFluxes()\n            for iVertex in range(self.ns_loc):\n                iGlobalVertex = self.manager.getGlobalIndex('solid', self.myid, iVertex)\n                self.solidInterfaceHeatFlux[iGlobalVertex] = [localSolidInterfaceHeatFlux_X[iVertex], localSolidInterfaceHeatFlux_Y[iVertex], localSolidInterfaceHeatFlux_Z[iVertex]]\n\n        self.solidInterfaceHeatFlux.assemble()\n\n    def getLoadsFromFluidSolver(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        if self.myid in self.manager.getFluidInterfaceProcessors():\n            localFluidInterfaceLoad_X, localFluidInterfaceLoad_Y, localFluidInterfaceLoad_Z = self.FluidSolver.getNodalLoads()\n            for iVertex in range(self.nf_loc):\n                iGlobalVertex = self.manager.getGlobalIndex('fluid', self.myid, iVertex)\n                self.fluidInterfaceLoads[iGlobalVertex] = [localFluidInterfaceLoad_X[iVertex], localFluidInterfaceLoad_Y[iVertex], localFluidInterfaceLoad_Z[iVertex]]\n\n        self.fluidInterfaceLoads.assemble()\n\n    def getTemperatureFromFluidSolver(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        if self.myid in self.manager.getFluidInterfaceProcessors():\n            localFluidInterfaceTemperature = self.FluidSolver.getNodalTemperatures()\n            for iVertex in range(self.nf_loc):\n                iGlobalVertex = self.manager.getGlobalIndex('fluid', self.myid, iVertex)\n                self.fluidInterfaceTemperature[iGlobalVertex] = [localFluidInterfaceTemperature[iVertex]]\n\n        self.fluidInterfaceTemperature.assemble()\n\n    def getRobinTemperatureFromFluidSolver(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        if self.myid in self.manager.getFluidInterfaceProcessors():\n            localFluidInterfaceNormalHeatFlux = self.FluidSolver.getNodalNormalHeatFlux()\n            localFluidInterfaceTemperature = self.FluidSolver.getNodalTemperatures()\n            localFluidInterfaceRobinTemperature = localFluidInterfaceTemperature - (localFluidInterfaceNormalHeatFlux/self.heatTransferCoeff)\n            for iVertex in range(self.nf_loc):\n                iGlobalVertex = self.manager.getGlobalIndex('fluid', self.myid, iVertex)\n                self.fluidInterfaceRobinTemperature[iGlobalVertex] = [localFluidInterfaceRobinTemperature[iVertex]]\n\n        self.fluidInterfaceRobinTemperature.assemble()\n\n    def getHeatFluxFromFluidSolver(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        if self.myid in self.manager.getFluidInterfaceProcessors():\n            localFluidInterfaceHeatFlux_X, localFluidInterfaceHeatFlux_Y, localFluidInterfaceHeatFlux_Z = self.FluidSolver.getNodalHeatFluxes()\n            localFluidInterfaceNormalHeatFlux = self.FluidSolver.getNodalNormalHeatFlux()\n            for iVertex in range(self.nf_loc):\n                iGlobalVertex = self.manager.getGlobalIndex('fluid', self.myid, iVertex)\n                self.fluidInterfaceHeatFlux[iGlobalVertex] = [localFluidInterfaceHeatFlux_X[iVertex], localFluidInterfaceHeatFlux_Y[iVertex], localFluidInterfaceHeatFlux_Z[iVertex]]\n                self.fluidInterfaceNormalHeatFlux[iGlobalVertex] = [localFluidInterfaceNormalHeatFlux[iVertex]]\n\n        self.fluidInterfaceHeatFlux.assemble()\n        self.fluidInterfaceNormalHeatFlux.assemble()\n\n    def redistributeDataToFluidSolver(self, fluidInterfaceData):\n        \"\"\"\n        Description\n        \"\"\"\n\n        localFluidInterfaceData_array = None\n        haloNodesData = {}\n\n        if self.mpiComm != None:\n            localSize = fluidInterfaceData.getDataArray(0).shape[0]\n            fluidInterfaceData_array_recon = []\n            for iDim in range(fluidInterfaceData.nDim):\n                array_recon = mpiGatherv(fluidInterfaceData.getDataArray(iDim), localSize, self.nf, self.mpiComm, 0)\n                fluidInterfaceData_array_recon.append(array_recon)\n            haloNodesData = {}\n            haloNodesData_bis = {}\n            if self.myid == 0:\n                for iProc in self.manager.getFluidInterfaceProcessors():\n                    fluidPhysicalInterfaceNodesDistribution = self.manager.getFluidPhysicalInterfaceNodesDistribution()\n                    fluidGlobalIndexRange = self.manager.getFluidGlobalIndexRange()\n                    sendBuff = []\n                    for iDim in range(fluidInterfaceData.nDim):\n                        sendBuff_i = np.zeros(fluidPhysicalInterfaceNodesDistribution[iProc])\n                        sendBuff.append(sendBuff_i)\n                    globalIndex = fluidGlobalIndexRange[iProc][0]\n                    sendBuffHalo = {}\n                    for iVertex in range(fluidPhysicalInterfaceNodesDistribution[iProc]):\n                        for iDim in range(fluidInterfaceData.nDim):\n                            sendBuff[iDim][iVertex] = fluidInterfaceData_array_recon[iDim][globalIndex]\n                        globalIndex += 1\n                    fluidHaloNodesList = self.manager.getFluidHaloNodesList()\n                    fluidIndexing = self.manager.getFluidIndexing()\n                    for key in fluidHaloNodesList[iProc].keys():\n                        globalIndex = fluidIndexing[key]\n                        sendBuffHalo[key] = []\n                        for iDim in range(fluidInterfaceData.nDim):\n                            sendBuffHalo[key].append(fluidInterfaceData_array_recon[iDim][globalIndex])\n                    iTagSend = 1\n                    if iProc == 0: # In the master node use non-blocking and immediately receive them\n                        for iDim in range(fluidInterfaceData.nDim):\n                            self.mpiComm.Isend(sendBuff[iDim], dest=iProc, tag = iTagSend)\n                            iTagSend += 1\n                        sendBuffHalo_key = np.array(list(sendBuffHalo.keys()))\n                        sendBuffHalo_values = np.empty((sendBuffHalo_key.size, 3),dtype=float)\n                        for ii in range(sendBuffHalo_key.size):\n                            sendBuffHalo_values[ii] = np.array(sendBuffHalo[sendBuffHalo_key[ii]])\n                        self.mpiComm.Isend(np.array(sendBuffHalo_key.size), dest=iProc, tag=101)\n                        self.mpiComm.Isend(sendBuffHalo_key, dest=iProc, tag=102)\n                        self.mpiComm.Isend(sendBuffHalo_values, dest=iProc, tag=103)\n                        localFluidInterfaceData_array = []\n                        iTagRec = 1\n                        for iDim in range(fluidInterfaceData.nDim):\n                            local_array = np.zeros(self.nf_loc)\n                            self.mpiComm.Recv(local_array, source=0, tag=iTagRec)\n                            localFluidInterfaceData_array.append(local_array)\n                            iTagRec += 1\n                        nHaloNodesRcv = np.empty(1, dtype=int)\n                        req = self.mpiComm.Irecv(nHaloNodesRcv, source=0, tag=101)\n                        req.Wait()\n                        rcvBuffHalo_keyBuff = np.empty(nHaloNodesRcv[0], dtype=int)\n                        req = self.mpiComm.Irecv(rcvBuffHalo_keyBuff, source=0, tag=102)\n                        req.Wait()\n                        rcvBuffHalo_values = np.empty((nHaloNodesRcv[0],3), dtype=float)\n                        req = self.mpiComm.Irecv(rcvBuffHalo_values, source=0, tag=103)\n                        req.Wait()\n                        for ii in range(len(rcvBuffHalo_keyBuff)):\n                            haloNodesData_bis[rcvBuffHalo_keyBuff[ii]] = list(rcvBuffHalo_values[ii])\n                        haloNodesData = haloNodesData_bis\n                    else: # In other processors it's ok to send the buffers with blocking comms\n                        for iDim in range(fluidInterfaceData.nDim):\n                            self.mpiComm.Send(sendBuff[iDim], dest=iProc, tag = iTagSend)\n                            iTagSend += 1\n                        #self.mpiComm.send(sendBuffHalo, dest = iProc, tag=iTagSend)\n                        sendBuffHalo_key = np.array(list(sendBuffHalo.keys()))\n                        sendBuffHalo_values = np.empty((sendBuffHalo_key.size, 3),dtype=float)\n                        for ii in range(sendBuffHalo_key.size):\n                            sendBuffHalo_values[ii] = np.array(sendBuffHalo[sendBuffHalo_key[ii]])\n                        self.mpiComm.Send(np.array(sendBuffHalo_key.size), dest=iProc, tag=101)\n                        self.mpiComm.Send(sendBuffHalo_key, dest=iProc, tag=102)\n                        self.mpiComm.Send(sendBuffHalo_values, dest=iProc, tag=103)\n            elif self.myid in self.manager.getFluidInterfaceProcessors():\n                localFluidInterfaceData_array = []\n                iTagRec = 1\n                for iDim in range(fluidInterfaceData.nDim):\n                    local_array = np.zeros(self.nf_loc)\n                    self.mpiComm.Recv(local_array, source=0, tag=iTagRec)\n                    localFluidInterfaceData_array.append(local_array)\n                    iTagRec += 1\n                #haloNodesData = self.mpiComm.recv(source=0, tag=iTagRec)\n                nHaloNodesRcv = np.empty(1, dtype=int)\n                req = self.mpiComm.Irecv(nHaloNodesRcv, source=0, tag=101)\n                req.Wait()\n                rcvBuffHalo_keyBuff = np.empty(nHaloNodesRcv[0], dtype=int)\n                self.mpiComm.Recv(rcvBuffHalo_keyBuff, source=0, tag=102)\n                rcvBuffHalo_values = np.empty((nHaloNodesRcv[0],3), dtype=float)\n                self.mpiComm.Recv(rcvBuffHalo_values, source=0, tag=103)\n                for ii in range(len(rcvBuffHalo_keyBuff)):\n                    haloNodesData_bis[rcvBuffHalo_keyBuff[ii]] = list(rcvBuffHalo_values[ii])\n                haloNodesData = haloNodesData_bis\n\n\n        return (localFluidInterfaceData_array, haloNodesData)\n\n    def redistributeDataToSolidSolver(self, solidInterfaceData):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        localSolidInterfaceData_array = None\n        haloNodesData = {}\n        haloNodesData_bis = {}\n\n        if self.mpiComm != None:\n            localSize = solidInterfaceData.getDataArray(0).shape[0]\n            solidInterfaceData_array_recon = []\n            for iDim in range(solidInterfaceData.nDim):\n                array_recon = mpiGatherv(solidInterfaceData.getDataArray(iDim), localSize, self.ns+self.d, self.mpiComm, 0)\n                solidInterfaceData_array_recon.append(array_recon)\n            haloNodesData = {}\n            if self.myid == 0:\n                for iProc in self.manager.getSolidInterfaceProcessors():\n                    solidPhysicalInterfaceNodesDistribution = self.manager.getSolidPhysicalInterfaceNodesDistribution()\n                    solidGlobalIndexRange = self.manager.getSolidGlobalIndexRange()\n                    sendBuff = []\n                    for iDim in range(solidInterfaceData.nDim):\n                        sendBuff_i = np.zeros(solidPhysicalInterfaceNodesDistribution[iProc])\n                        sendBuff.append(sendBuff_i)\n                    globalIndex = solidGlobalIndexRange[iProc][0]\n                    sendBuffHalo = {}\n                    for iVertex in range(solidPhysicalInterfaceNodesDistribution[iProc]):\n                        for iDim in range(solidInterfaceData.nDim):\n                            sendBuff[iDim][iVertex] = solidInterfaceData_array_recon[iDim][globalIndex]\n                        globalIndex += 1\n                    solidHaloNodesList = self.manager.getSolidHaloNodesList()\n                    solidIndexing = self.manager.getSolidIndexing()\n                    for key in solidHaloNodesList[iProc].keys():\n                        globalIndex = solidIndexing[key]\n                        sendBuffHalo[key] = []\n                        for iDim in range(solidInterfaceData.nDim):\n                            sendBuffHalo[key].append(solidInterfaceData_array_recon[iDim][globalIndex])\n                    iTagSend = 1\n                    for iDim in range(solidInterfaceData.nDim):\n                        self.mpiComm.Isend(sendBuff[iDim], dest=iProc, tag = iTagSend)\n                        iTagSend += 1\n                    #self.mpiComm.send(sendBuffHalo, dest = iProc, tag=iTagSend)\n                    sendBuffHalo_key = np.array(sendBuffHalo.keys())\n                    sendBuffHalo_values = np.empty((sendBuffHalo_key.size, 3),dtype=float)\n                    for ii in range(sendBuffHalo_key.size):\n                        sendBuffHalo_values[ii] = np.array(sendBuffHalo[sendBuffHalo_key[ii]])\n                    self.mpiComm.Isend(np.array(sendBuffHalo_key.size), dest=iProc, tag=101)\n                    self.mpiComm.Isend(sendBuffHalo_key, dest=iProc, tag=102)\n                    self.mpiComm.Isend(sendBuffHalo_values, dest=iProc, tag=103)\n            if self.myid in self.manager.getSolidInterfaceProcessors():\n                localSolidInterfaceData_array = []\n                iTagRec = 1\n                for iDim in range(solidInterfaceData.nDim):\n                    local_array = np.zeros(self.ns_loc)\n                    req = self.mpiComm.Irecv(local_array, source=0, tag = iTagRec)\n                    req.Wait()\n                    localSolidInterfaceData_array.append(local_array)\n                    iTagRec += 1\n                #haloNodesData = self.mpiComm.recv(source=0, tag=iTagRec)\n                nHaloNodesRcv = np.empty(1, dtype=int)\n                req = self.mpiComm.Irecv(nHaloNodesRcv, source=0, tag=101)\n                req.Wait()\n                rcvBuffHalo_keyBuff = np.empty(nHaloNodesRcv[0], dtype=int)\n                req = self.mpiComm.Irecv(rcvBuffHalo_keyBuff, source=0, tag=102)\n                req.Wait()\n                rcvBuffHalo_values = np.empty((nHaloNodesRcv[0],3), dtype=float)\n                req = self.mpiComm.Irecv(rcvBuffHalo_values, source=0, tag=103)\n                req.Wait()\n                for ii in range(len(rcvBuffHalo_keyBuff)):\n                    haloNodesData_bis[rcvBuffHalo_keyBuff[ii]] = list(rcvBuffHalo_values[ii])\n                haloNodesData = haloNodesData_bis\n\n        return (localSolidInterfaceData_array, haloNodesData)\n\n    def setLoadsToSolidSolver(self, time):\n        \"\"\"\n        des.\n        \"\"\"\n\n        FFX, FFY, FFZ = self.fluidInterfaceLoads.sum()\n\n\n        FX = 0.\n        FY = 0.\n        FZ = 0.\n\n        FXT = 0.\n        FYT = 0.\n        FZT = 0.\n\n        if self.mpiComm != None:\n            (localSolidLoads_array, haloNodesSolidLoads) = self.redistributeDataToSolidSolver(self.solidInterfaceLoads)\n            if self.myid in self.manager.getSolidInterfaceProcessors():\n                self.SolidSolver.applyNodalLoads(localSolidLoads_array[0], localSolidLoads_array[1], localSolidLoads_array[2], time)\n                FX = localSolidLoads_array[0].sum()\n                FY = localSolidLoads_array[1].sum()\n                FZ = localSolidLoads_array[2].sum()\n            FXT = mpiAllReduce(self.mpiComm, FX)\n            FYT = mpiAllReduce(self.mpiComm, FY)\n            FZT = mpiAllReduce(self.mpiComm, FZ)\n        else:\n            self.SolidSolver.applyNodalLoads(self.solidInterfaceLoads.getDataArray(0), self.solidInterfaceLoads.getDataArray(1), self.solidInterfaceLoads.getDataArray(2), time)\n            FXT, FYT, FZT = self.solidInterfaceLoads.sum()\n\n        mpiPrint(\"Checking f/s interface total force...\", self.mpiComm)\n        mpiPrint('Solid side (Fx, Fy, Fz) = ({}, {}, {})'.format(FXT, FYT, FZT), self.mpiComm)\n        mpiPrint('Fluid side (Fx, Fy, Fz) = ({}, {}, {})'.format(FFX, FFY, FFZ), self.mpiComm)\n\n    def setDisplacementToFluidSolver(self, time):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        self.checkConservation()\n\n        if self.mpiComm != None:\n            (localFluidInterfaceDisplacement, haloNodesDisplacements) = self.redistributeDataToFluidSolver(self.fluidInterfaceDisplacement)\n#            mpiBarrier(self.mpiComm)\n            if self.myid in self.manager.getFluidInterfaceProcessors():\n                self.FluidSolver.applyNodalDisplacements(localFluidInterfaceDisplacement[0], localFluidInterfaceDisplacement[1], localFluidInterfaceDisplacement[2], localFluidInterfaceDisplacement[0], localFluidInterfaceDisplacement[1], localFluidInterfaceDisplacement[2], haloNodesDisplacements, time)\n        else:\n            self.FluidSolver.applyNodalDisplacements(self.fluidInterfaceDisplacement.getDataArray(0), self.fluidInterfaceDisplacement.getDataArray(1), self.fluidInterfaceDisplacement.getDataArray(2), self.fluidInterfaceDisplacement.getDataArray(0), self.fluidInterfaceDisplacement.getDataArray(1), self.fluidInterfaceDisplacement.getDataArray(2), {}, time)\n\n    def setHeatFluxToFluidSolver(self, time):\n        \"\"\"\n        Description.\n        \"\"\"\n\n        if self.mpiComm != None:\n            (localFluidInterfaceHeatFlux, haloNodesHeatFlux) = self.redistributeDataToFluidSolver(self.fluidInterfaceHeatFlux)\n            if self.myid in self.manager.getFluidInterfaceProcessors():\n                self.FluidSolver.applyNodalHeatFluxes(localFluidInterfaceHeatFlux[0], localFluidInterfaceHeatFlux[1], localFluidInterfaceHeatFlux[2], time)\n        else:\n            self.FluidSolver.applyNodalHeatFluxes(self.fluidInterfaceHeatFlux.getDataArray(0), self.fluidInterfaceHeatFlux.getDataArray(1), self.fluidInterfaceHeatFlux.getDataArray(2), time)\n\n    def setTemperatureToFluidSolver(self, time):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        if self.mpiComm != None:\n            (localFluidInterfaceTemperature, haloNodesTemperature) = self.redistributeDataToFluidSolver(self.fluidInterfaceTemperature)\n            if self.myid in self.manager.getFluidInterfaceProcessors():\n                self.FluidSolver.applyNodalTemperatures(localFluidInterfaceTemperature[0], time)\n        else:\n            self.FluidSolver.applyNodalTemperatures(self.fluidInterfaceTemperature.getDataArray(0), time)\n\n    def setTemperatureToSolidSolver(self, time):\n        \"\"\"\n        Description\n        \"\"\"\n\n        if self.mpiComm != None:\n            (localSolidInterfaceTemperature, haloNodesTemperature) = self.redistributeDataToSolidSolver(self.solidInterfaceTemperature)\n            if self.myid in self.manager.getSolidInterfaceProcessors():\n                self.SolidSolver.applyNodalTemperatures(localSolidInterfaceTemperature[0], time)\n        else:\n            self.SolidSolver.applyNodalTemperatures(self.solidInterfaceTemperature.getDataArray(0), time)\n\n    def setRobinHeatFluxToSolidSolver(self, time):\n        \"\"\"\n        Def\n        \"\"\"\n\n        if self.mpiComm != None:\n            (localSolidInterfaceRobinTemperature, haloNodesRobinTemperature) = self.redistributeDataToSolidSolver(self.solidInterfaceRobinTemperature)\n            if self.myid in self.manager.getSolidInterfaceProcessors():\n                localSolidInterfaceTemperature = self.SolidSolver.getNodalTemperatures()\n                localSolidInterfaceRobinHeatFlux = self.heatTransferCoeff*(localSolidInterfaceTemperature-localSolidInterfaceRobinTemperature[0])\n                self.SolidSolver.applyNodalNormalHeatFluxes(localSolidInterfaceRobinHeatFlux, time)\n        else:\n            localSolidInterfaceTemperature = self.SolidSolver.getNodalTemperatures()\n            localSolidInterfaceRobinHeatFlux = self.heatTransferCoeff*(localSolidInterfaceTemperature-self.solidInterfaceRobinTemperature.getDataArray(0), time)\n            self.SolidSolver.applyNodalNormalHeatFluxes(localSolidInterfaceRobinHeatFlux, time)\n\n    def setHeatFluxToSolidSolver(self, time):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        if self.mpiComm != None:\n            (localSolidInterfaceNormalHeatFlux, haloNodesNormalHeatFlux) =  self.redistributeDataToSolidSolver(self.solidInterfaceNormalHeatFlux)\n            if self.myid in self.manager.getSolidInterfaceProcessors():\n                self.SolidSolver.applyNodalNormalHeatFluxes(localSolidInterfaceNormalHeatFlux[0], time)\n        else:\n            self.SolidSolver.applyNodalNormalHeatFluxes(self.solidInterfaceNormalHeatFlux.getDataArray(0), time)\n\n    def interpolateFluidLoadsOnSolidMesh(self):\n        \"\"\"\n        Description\n        \"\"\"\n\n        self.interpolateFluidToSolid(self.fluidInterfaceLoads, self.solidInterfaceLoads)\n\n    def interpolateSolidDisplacementOnFluidMesh(self):\n        \"\"\"\n        Description.\n        \"\"\"\n\n        self.interpolateSolidToFluid(self.solidInterfaceDisplacement, self.fluidInterfaceDisplacement)\n\n    def interpolateSolidHeatFluxOnFluidMesh(self):\n        \"\"\"\n        Description.\n        \"\"\"\n\n        self.interpolateSolidToFluid(self.solidInterfaceHeatFlux, self.fluidInterfaceHeatFlux)\n\n\n    def interpolateSolidTemperatureOnFluidMesh(self):\n        \"\"\"\n        Description\n        \"\"\"\n\n        self.interpolateSolidToFluid(self.solidInterfaceTemperature, self.fluidInterfaceTemperature)\n\n    def interpolateFluidHeatFluxOnSolidMesh(self):\n        \"\"\"\n        Description.\n        \"\"\"\n\n        self.interpolateFluidToSolid(self.fluidInterfaceHeatFlux, self.solidInterfaceHeatFlux)\n        self.interpolateFluidToSolid(self.fluidInterfaceNormalHeatFlux, self.solidInterfaceNormalHeatFlux)\n\n    def interpolateFluidTemperatureOnSolidMesh(self):\n        \"\"\"\n        Description.\n        \"\"\"\n\n        self.interpolateFluidToSolid(self.fluidInterfaceTemperature, self.solidInterfaceTemperature)\n\n    def interpolateFluidRobinTemperatureOnSolidMesh(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        self.interpolateFluidToSolid(self.fluidInterfaceRobinTemperature, self.solidInterfaceRobinTemperature)\n\n    def getNs(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        return self.ns\n\n    def getNf(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        return self.nf\n\n    def getd(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        return self.d\n\nclass MatchingMeshesInterpolator(InterfaceInterpolator):\n    \"\"\"\n    Description.\n    \"\"\"\n\n    def __init__(self, Manager, FluidSolver, SolidSolver, mpiComm = None, chtTransferMethod=None, heatTransferCoeff=1.0):\n        \"\"\"\n        Description\n        \"\"\"\n\n        InterfaceInterpolator.__init__(self, Manager, FluidSolver, SolidSolver, mpiComm, chtTransferMethod, heatTransferCoeff)\n\n        mpiPrint('\\nSetting matching meshes interpolator...', mpiComm)\n\n        if self.nf != self.ns:\n            raise Exception(\"Fluid and solid interface must have the same number of nodes for matching meshes ! \")\n        ccupydo.CInterpolator.matching_initSearch(self)\n\n        self.generateInterfaceData()\n\n        self.generateMapping()\n\n    def checkConservation(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        WSX, WSY, WSZ = self.solidInterfaceLoads.dot(self.solidInterfaceDisplacement)\n\n        WFX, WFY, WFZ = self.fluidInterfaceLoads.dot(self.fluidInterfaceDisplacement)\n\n        mpiPrint(\"Checking f/s interface conservation...\", self.mpiComm)\n        mpiPrint('Solid side (Wx, Wy, Wz) = ({}, {}, {})'.format(WSX, WSY, WSZ), self.mpiComm)\n        mpiPrint('Fluid side (Wx, Wy, Wz) = ({}, {}, {})'.format(WFX, WFY, WFZ), self.mpiComm)\n\n    def generateInterfaceData(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        if self.manager.mechanical:\n            self.solidInterfaceDisplacement = FlexInterfaceData(self.ns, 3, self.mpiComm)\n            self.fluidInterfaceDisplacement = FlexInterfaceData(self.nf, 3, self.mpiComm)\n            self.solidInterfaceLoads = FlexInterfaceData(self.ns, 3, self.mpiComm)\n            self.fluidInterfaceLoads = FlexInterfaceData(self.nf, 3, self.mpiComm)\n\n        if self.manager.thermal :\n            if self.chtTransferMethod == 'TFFB':\n                self.solidInterfaceTemperature = FlexInterfaceData(self.ns, 1, self.mpiComm)\n                self.fluidInterfaceTemperature = FlexInterfaceData(self.nf, 1, self.mpiComm)\n                self.solidInterfaceHeatFlux = FlexInterfaceData(self.ns, 3, self.mpiComm)\n                self.fluidInterfaceHeatFlux = FlexInterfaceData(self.nf, 3, self.mpiComm)\n            elif self.chtTransferMethod == 'FFTB':\n                self.solidInterfaceTemperature = FlexInterfaceData(self.ns, 1, self.mpiComm)\n                self.fluidInterfaceTemperature = FlexInterfaceData(self.nf, 1, self.mpiComm)\n                self.solidInterfaceHeatFlux = FlexInterfaceData(self.ns, 3, self.mpiComm)\n                self.fluidInterfaceHeatFlux = FlexInterfaceData(self.nf, 3, self.mpiComm)\n                self.fluidInterfaceNormalHeatFlux = FlexInterfaceData(self.nf, 1, self.mpiComm)\n                self.solidInterfaceNormalHeatFlux = FlexInterfaceData(self.ns, 1, self.mpiComm)\n            elif self.chtTransferMethod == 'hFTB':\n                self.fluidInterfaceRobinTemperature = FlexInterfaceData(self.nf, 1, self.mpiComm)\n                self.solidInterfaceRobinTemperature = FlexInterfaceData(self.ns, 1, self.mpiComm)\n                self.solidInterfaceTemperature = FlexInterfaceData(self.ns, 1, self.mpiComm)\n                self.fluidInterfaceTemperature = FlexInterfaceData(self.nf, 1, self.mpiComm)\n            elif self.chtTransferMethod == 'hFFB':\n                self.fluidInterfaceRobinTemperature = FlexInterfaceData(self.nf, 1, self.mpiComm)\n                self.solidInterfaceRobinTemperature = FlexInterfaceData(self.ns, 1, self.mpiComm)\n                self.solidInterfaceHeatFlux = FlexInterfaceData(self.ns, 3, self.mpiComm)\n                self.fluidInterfaceHeatFlux = FlexInterfaceData(self.nf, 3, self.mpiComm)\n\n        self.H = InterfaceMatrix((self.nf,self.ns), self.mpiComm)\n        self.H_T = InterfaceMatrix((self.ns,self.nf), self.mpiComm)\n        self.H.createSparse(1,1)\n        self.H_T.createSparse(1,1)\n\n    def generateMapping(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        solidInterfaceProcessors = self.manager.getSolidInterfaceProcessors()\n        fluidInterfaceProcessors = self.manager.getFluidInterfaceProcessors()\n        solidPhysicalInterfaceNodesDistribution = self.manager.getSolidPhysicalInterfaceNodesDistribution()\n\n        mpiPrint('\\nBuilding interpolation matrix...', self.mpiComm)\n        mpiPrint('\\nBuilding matrix H of size {} X {}...'.format(self.nf, self.ns), self.mpiComm)\n        self.mappingTimer.start()\n\n        if self.mpiComm != None:\n            for iProc in solidInterfaceProcessors:\n                if self.myid == iProc:\n                    localSolidInterface_array_X, localSolidInterface_array_Y, localSolidInterface_array_Z = self.SolidSolver.getNodalInitialPositions()\n                    for jProc in fluidInterfaceProcessors:\n                        self.mpiComm.Isend(localSolidInterface_array_X, dest=jProc, tag=1)\n                        self.mpiComm.Isend(localSolidInterface_array_Y, dest=jProc, tag=2)\n                        self.mpiComm.Isend(localSolidInterface_array_Z, dest=jProc, tag=3)\n                if self.myid in fluidInterfaceProcessors:\n                    sizeOfBuff = solidPhysicalInterfaceNodesDistribution[iProc]\n                    solidInterfaceBuffRcv_X = np.zeros(sizeOfBuff)\n                    solidInterfaceBuffRcv_Y = np.zeros(sizeOfBuff)\n                    solidInterfaceBuffRcv_Z = np.zeros(sizeOfBuff)\n                    req = self.mpiComm.Irecv(solidInterfaceBuffRcv_X, iProc, tag=1)\n                    req.Wait()\n                    req = self.mpiComm.Irecv(solidInterfaceBuffRcv_Y, iProc, tag=2)\n                    req.Wait()\n                    req = self.mpiComm.Irecv(solidInterfaceBuffRcv_Z, iProc, tag=3)\n                    req.Wait()\n                    self.mappingSearch(solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc)\n            if self.myid in fluidInterfaceProcessors:\n                self.fillMatrix()\n        else:\n            localSolidInterface_array_X, localSolidInterface_array_Y, localSolidInterface_array_Z = self.SolidSolver.getNodalInitialPositions()\n            self.mappingSearch(localSolidInterface_array_X, localSolidInterface_array_Y, localSolidInterface_array_Z, 0)\n            self.fillMatrix()\n\n        mpiBarrier(self.mpiComm)\n        mpiPrint(\"\\nAssembling H & H_T...\", self.mpiComm)\n        start = tm.time()\n        self.H.assemble()\n        mpiBarrier(self.mpiComm)\n        self.H_T.assemble()\n        mpiBarrier(self.mpiComm)\n        stop = tm.time()\n        mpiPrint('Assembly performed in {} s'.format(stop-start), self.mpiComm)\n        mpiPrint('Matrix H is built.', self.mpiComm)\n\n        self.mappingTimer.stop()\n        self.mappingTimer.cumul()\n\n    def mappingSearch(self, solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        localFluidInterface_array_X_init, localFluidInterface_array_Y_init, localFluidInterface_array_Z_init = self.FluidSolver.getNodalInitialPositions()\n\n        print('Matching mapping search on rank {}...'.format(self.myid))\n        start = tm.time()\n        ccupydo.CInterpolator.matching_search(self, localFluidInterface_array_X_init, localFluidInterface_array_Y_init, localFluidInterface_array_Z_init,\n                                              solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc)\n        stop = tm.time()\n        print('Search on rank {} in {} s'.format(self.myid,stop-start))\n\n    def fillMatrix(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        print('Building H on rank {}...'.format(self.myid))\n        start = tm.time()\n        ccupydo.CInterpolator.matching_fillMatrix(self, self.H, self.H_T)\n        stop = tm.time()\n        print('Built H on rank {} in {} s'.format(self.myid,stop-start))\n\n    def interpolateFluidToSolid(self, fluidInterfaceData, solidInterfaceData):\n        \"\"\"\n        des.\n        \"\"\"\n\n        self.H_T.mult(fluidInterfaceData, solidInterfaceData)\n\n    def interpolateSolidToFluid(self, solidInterfaceData, fluidInterfaceData):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        self.H.mult(solidInterfaceData, fluidInterfaceData)\n\nclass ConservativeInterpolator(InterfaceInterpolator):\n    \"\"\"\n    Description.\n    \"\"\"\n\n    def __init__(self, Manager, FluidSolver, SolidSolver, mpiComm = None, chtTransferMethod=None, heatTransferCoeff=1.0):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        InterfaceInterpolator.__init__(self, Manager, FluidSolver, SolidSolver, mpiComm, chtTransferMethod, heatTransferCoeff)\n\n        mpiPrint('\\nSetting non-matching conservative interpolator...', mpiComm)\n\n        self.d = self.nDim+1\n        self.SolverA = None\n        self.SolverA_T = None\n\n    def getLinearSolvers(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        return [self.SolverA, self.SolverA_T]\n\n    def checkConservation(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        WSX, WSY, WSZ = self.solidInterfaceLoads.dot(self.solidInterfaceDisplacement)\n\n        WFX, WFY, WFZ = self.fluidInterfaceLoads.dot(self.fluidInterfaceDisplacement)\n\n        mpiPrint(\"Checking f/s interface conservation...\", self.mpiComm)\n        mpiPrint('Solid side (Wx, Wy, Wz) = ({}, {}, {})'.format(WSX, WSY, WSZ), self.mpiComm)\n        mpiPrint('Fluid side (Wx, Wy, Wz) = ({}, {}, {})'.format(WFX, WFY, WFZ), self.mpiComm)\n\n    def generateInterfaceData(self):\n        \"\"\"\n        Description.\n        \"\"\"\n\n        if self.manager.mechanical:\n            self.solidInterfaceDisplacement = FlexInterfaceData(self.ns + self.d, 3, self.mpiComm)\n            self.fluidInterfaceDisplacement = FlexInterfaceData(self.nf, 3, self.mpiComm)\n            self.solidInterfaceLoads = FlexInterfaceData(self.ns + self.d, 3, self.mpiComm)\n            self.fluidInterfaceLoads = FlexInterfaceData(self.nf, 3, self.mpiComm)\n\n        if self.manager.thermal :\n            if self.chtTransferMethod == 'TFFB':\n                self.solidInterfaceTemperature = FlexInterfaceData(self.ns + self.d, 1, self.mpiComm)\n                self.fluidInterfaceTemperature = FlexInterfaceData(self.nf, 1, self.mpiComm)\n                self.solidInterfaceHeatFlux = FlexInterfaceData(self.ns + self.d, 3, self.mpiComm)\n                self.fluidInterfaceHeatFlux = FlexInterfaceData(self.nf, 3, self.mpiComm)\n            elif self.chtTransferMethod == 'FFTB':\n                self.solidInterfaceTemperature = FlexInterfaceData(self.ns + self.d, 1, self.mpiComm)\n                self.fluidInterfaceTemperature = FlexInterfaceData(self.nf, 1, self.mpiComm)\n                self.solidInterfaceHeatFlux = FlexInterfaceData(self.ns + self.d, 3, self.mpiComm)\n                self.fluidInterfaceHeatFlux = FlexInterfaceData(self.nf, 3, self.mpiComm)\n                self.fluidInterfaceNormalHeatFlux = FlexInterfaceData(self.nf, 1, self.mpiComm)\n                self.solidInterfaceNormalHeatFlux = FlexInterfaceData(self.ns, 1, self.mpiComm)\n            elif self.chtTransferMethod == 'hFTB':\n                self.fluidInterfaceRobinTemperature = FlexInterfaceData(self.nf, 1, self.mpiComm)\n                self.solidInterfaceRobinTemperature = FlexInterfaceData(self.ns, 1, self.mpiComm)\n                self.solidInterfaceTemperature = FlexInterfaceData(self.ns + self.d, 1, self.mpiComm)\n                self.fluidInterfaceTemperature = FlexInterfaceData(self.nf, 1, self.mpiComm)\n            elif self.chtTransferMethod == 'hFFB':\n                self.fluidInterfaceRobinTemperature = FlexInterfaceData(self.nf, 1, self.mpiComm)\n                self.solidInterfaceRobinTemperature = FlexInterfaceData(self.ns, 1, self.mpiComm)\n                self.solidInterfaceHeatFlux = FlexInterfaceData(self.ns + self.d, 3, self.mpiComm)\n                self.fluidInterfaceHeatFlux = FlexInterfaceData(self.nf, 3, self.mpiComm)\n\n        self.A = InterfaceMatrix((self.ns+self.d,self.ns+self.d), self.mpiComm)\n        self.A_T = InterfaceMatrix((self.ns+self.d,self.ns+self.d), self.mpiComm)\n        self.B = InterfaceMatrix((self.nf,self.ns+self.d), self.mpiComm)\n        self.B_T = InterfaceMatrix((self.ns+self.d,self.nf), self.mpiComm)\n\n    def generateMapping(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        solidInterfaceProcessors = self.manager.getSolidInterfaceProcessors()\n        fluidInterfaceProcessors = self.manager.getFluidInterfaceProcessors()\n        solidPhysicalInterfaceNodesDistribution = self.manager.getSolidPhysicalInterfaceNodesDistribution()\n\n        mpiPrint('\\nBuilding interpolation matrices...', self.mpiComm)\n\n        mpiPrint('\\nBuilding matrix A of size {} X {}...'.format(self.ns, self.ns), self.mpiComm)\n        # Fill the matrix A\n        if self.mpiComm != None:\n            for iProc in solidInterfaceProcessors:\n                if self.myid == iProc:\n                    localSolidInterface_array_X, localSolidInterface_array_Y, localSolidInterface_array_Z = self.SolidSolver.getNodalInitialPositions()\n                    for jProc in solidInterfaceProcessors:\n                        self.mpiComm.Isend(localSolidInterface_array_X, dest=jProc, tag=1)\n                        self.mpiComm.Isend(localSolidInterface_array_Y, dest=jProc, tag=2)\n                        self.mpiComm.Isend(localSolidInterface_array_Z, dest=jProc, tag=3)\n                if self.myid in solidInterfaceProcessors:\n                    sizeOfBuff = solidPhysicalInterfaceNodesDistribution[iProc]\n                    solidInterfaceBuffRcv_X = np.zeros(sizeOfBuff)\n                    solidInterfaceBuffRcv_Y = np.zeros(sizeOfBuff)\n                    solidInterfaceBuffRcv_Z = np.zeros(sizeOfBuff)\n                    req = self.mpiComm.Irecv(solidInterfaceBuffRcv_X, iProc, tag=1)\n                    req.Wait()\n                    req = self.mpiComm.Irecv(solidInterfaceBuffRcv_Y, iProc, tag=2)\n                    req.Wait()\n                    req = self.mpiComm.Irecv(solidInterfaceBuffRcv_Z, iProc, tag=3)\n                    req.Wait()\n                    self.fillMatrixA(solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc)\n        else:\n            localSolidInterface_array_X, localSolidInterface_array_Y, localSolidInterface_array_Z = self.SolidSolver.getNodalInitialPositions()\n            self.fillMatrixA(localSolidInterface_array_X, localSolidInterface_array_Y, localSolidInterface_array_Z, 0)\n\n        mpiBarrier(self.mpiComm)\n        mpiPrint(\"\\nAssembling A & A_T...\", self.mpiComm)\n        start = tm.time()\n        self.A.assemble()\n        mpiBarrier(self.mpiComm)\n        self.A_T.assemble()\n        mpiBarrier(self.mpiComm)\n        stop = tm.time()\n        mpiPrint('Assembly performed in {} s'.format(stop-start), self.mpiComm)\n        mpiPrint('Matrix A is built.', self.mpiComm)\n\n        mpiPrint('\\nBuilding matrix B of size {} X {}...'.format(self.nf, self.ns), self.mpiComm)\n        # Fill the matrix B\n        if self.mpiComm != None:\n            for iProc in solidInterfaceProcessors:\n                if self.myid == iProc:\n                    for jProc in fluidInterfaceProcessors:\n                        self.mpiComm.Isend(localSolidInterface_array_X, dest=jProc, tag=1)\n                        self.mpiComm.Isend(localSolidInterface_array_Y, dest=jProc, tag=2)\n                        self.mpiComm.Isend(localSolidInterface_array_Z, dest=jProc, tag=3)\n                if self.myid in fluidInterfaceProcessors:\n                    sizeOfBuff = solidPhysicalInterfaceNodesDistribution[iProc]\n                    solidInterfaceBuffRcv_X = np.zeros(sizeOfBuff)\n                    solidInterfaceBuffRcv_Y = np.zeros(sizeOfBuff)\n                    solidInterfaceBuffRcv_Z = np.zeros(sizeOfBuff)\n                    req = self.mpiComm.Irecv(solidInterfaceBuffRcv_X, iProc, tag=1)\n                    req.Wait()\n                    req = self.mpiComm.Irecv(solidInterfaceBuffRcv_Y, iProc, tag=2)\n                    req.Wait()\n                    req = self.mpiComm.Irecv(solidInterfaceBuffRcv_Z, iProc, tag=3)\n                    req.Wait()\n                    self.fillMatrixB(solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc)\n        else:\n            self.fillMatrixB(localSolidInterface_array_X, localSolidInterface_array_Y, localSolidInterface_array_Z, 0)\n\n        mpiBarrier(self.mpiComm)\n        mpiPrint(\"\\nAssembling B & B_T...\", self.mpiComm)\n        start = tm.time()\n        self.B.assemble()\n        mpiBarrier(self.mpiComm)\n        self.B_T.assemble()\n        mpiBarrier(self.mpiComm)\n        stop = tm.time()\n        mpiPrint('Assembly performed in {} s'.format(stop-start), self.mpiComm)\n        mpiPrint('Matrix B is built.', self.mpiComm)\n\n        self.SolverA = LinearSolver(self.A, self.mpiComm)\n        self.SolverA_T = LinearSolver(self.A_T, self.mpiComm)\n\n    def interpolateFluidToSolid(self, fluidInterfaceData, solidInterfaceData):\n        \"\"\"\n        des.\n        \"\"\"\n\n        dim = fluidInterfaceData.getDim()\n        gamma_array = FlexInterfaceData(self.ns + self.d, dim, self.mpiComm)\n\n        self.B_T.mult(fluidInterfaceData, gamma_array)\n        self.SolverA_T.solve(gamma_array, solidInterfaceData)\n\n    def interpolateSolidToFluid(self, solidInterfaceData, fluidInterfaceData):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        dim = solidInterfaceData.getDim()\n        gamma_array = FlexInterfaceData(self.ns + self.d, dim, self.mpiComm)\n\n        self.SolverA.solve(solidInterfaceData, gamma_array)\n        self.B.mult(gamma_array, fluidInterfaceData)\n\n\nclass ConsistentInterpolator(InterfaceInterpolator):\n    \"\"\"\n    Description.\n    \"\"\"\n\n    def __init__(self, Manager, FluidSolver, SolidSolver, mpiComm = None, chtTransferMethod=None, heatTransferCoeff=1.0):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        InterfaceInterpolator.__init__(self, Manager, FluidSolver, SolidSolver, mpiComm, chtTransferMethod, heatTransferCoeff)\n\n        mpiPrint('\\nSetting non-matching consistent interpolator...', mpiComm)\n\n        self.d = self.nDim+1\n        self.SolverA = None\n        self.SolverC = None\n\n    def getLinearSolvers(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        return [self.SolverA, self.SolverC]\n\n    def checkConservation(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        mpiPrint('No conservation check for consistent interpolation.', self.mpiComm)\n\n    def generateInterfaceData(self):\n        \"\"\"\n        Description.\n        \"\"\"\n\n        if self.manager.mechanical:\n            self.solidInterfaceDisplacement = FlexInterfaceData(self.ns + self.d, 3, self.mpiComm)\n            self.fluidInterfaceDisplacement = FlexInterfaceData(self.nf, 3, self.mpiComm)\n            self.solidInterfaceLoads = FlexInterfaceData(self.ns, 3, self.mpiComm)\n            self.fluidInterfaceLoads = FlexInterfaceData(self.nf + self.d, 3, self.mpiComm)\n\n        if self.manager.thermal :\n            if self.chtTransferMethod == 'TFFB':\n                self.solidInterfaceTemperature = FlexInterfaceData(self.ns, 1, self.mpiComm)\n                self.fluidInterfaceTemperature = FlexInterfaceData(self.nf + self.d, 1, self.mpiComm)\n                self.solidInterfaceHeatFlux = FlexInterfaceData(self.ns + self.d, 3, self.mpiComm)\n                self.fluidInterfaceHeatFlux = FlexInterfaceData(self.nf, 3, self.mpiComm)\n            elif self.chtTransferMethod == 'FFTB':\n                self.solidInterfaceTemperature = FlexInterfaceData(self.ns + self.d, 1, self.mpiComm)\n                self.fluidInterfaceTemperature = FlexInterfaceData(self.nf, 1, self.mpiComm)\n                self.solidInterfaceHeatFlux = FlexInterfaceData(self.ns, 3, self.mpiComm)\n                self.fluidInterfaceHeatFlux = FlexInterfaceData(self.nf + self.d, 3, self.mpiComm)\n                self.fluidInterfaceNormalHeatFlux = FlexInterfaceData(self.nf + self.d, 1, self.mpiComm)\n                self.solidInterfaceNormalHeatFlux = FlexInterfaceData(self.ns, 1, self.mpiComm)\n            elif self.chtTransferMethod == 'hFTB':\n                self.fluidInterfaceRobinTemperature = FlexInterfaceData(self.nf + self.d, 1, self.mpiComm)\n                self.solidInterfaceRobinTemperature = FlexInterfaceData(self.ns, 1, self.mpiComm)\n                self.solidInterfaceTemperature = FlexInterfaceData(self.ns + self.d, 1, self.mpiComm)\n                self.fluidInterfaceTemperature = FlexInterfaceData(self.nf, 1, self.mpiComm)\n            elif self.chtTransferMethod == 'hFFB':\n                self.fluidInterfaceRobinTemperature = FlexInterfaceData(self.nf + self.d, 1, self.mpiComm)\n                self.solidInterfaceRobinTemperature = FlexInterfaceData(self.ns, 1, self.mpiComm)\n                self.solidInterfaceHeatFlux = FlexInterfaceData(self.ns + self.d, 3, self.mpiComm)\n                self.fluidInterfaceHeatFlux = FlexInterfaceData(self.nf, 3, self.mpiComm)\n\n        self.A = InterfaceMatrix((self.ns+self.d,self.ns+self.d), self.mpiComm)\n        self.B = InterfaceMatrix((self.nf,self.ns+self.d), self.mpiComm)\n        self.C = InterfaceMatrix((self.nf+self.d,self.nf+self.d), self.mpiComm)\n        self.D = InterfaceMatrix((self.ns,self.nf+self.d), self.mpiComm)\n\n    def generateMapping(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        solidInterfaceProcessors = self.manager.getSolidInterfaceProcessors()\n        fluidInterfaceProcessors = self.manager.getFluidInterfaceProcessors()\n        solidPhysicalInterfaceNodesDistribution = self.manager.getSolidPhysicalInterfaceNodesDistribution()\n        fluidPhysicalInterfaceNodesDistribution = self.manager.getFluidPhysicalInterfaceNodesDistribution()\n\n        mpiPrint('\\nBuilding interpolation matrices...', self.mpiComm)\n\n        mpiPrint('\\nBuilding matrix A of size {} X {}...'.format(self.ns, self.ns), self.mpiComm)\n        # Fill the matrix A\n        if self.mpiComm != None:\n            for iProc in solidInterfaceProcessors:\n                if self.myid == iProc:\n                    localSolidInterface_array_X, localSolidInterface_array_Y, localSolidInterface_array_Z = self.SolidSolver.getNodalInitialPositions()\n                    for jProc in solidInterfaceProcessors:\n                        self.mpiComm.Isend(localSolidInterface_array_X, dest=jProc, tag=1)\n                        self.mpiComm.Isend(localSolidInterface_array_Y, dest=jProc, tag=2)\n                        self.mpiComm.Isend(localSolidInterface_array_Z, dest=jProc, tag=3)\n                if self.myid in solidInterfaceProcessors:\n                    sizeOfBuff = solidPhysicalInterfaceNodesDistribution[iProc]\n                    solidInterfaceBuffRcv_X = np.zeros(sizeOfBuff)\n                    solidInterfaceBuffRcv_Y = np.zeros(sizeOfBuff)\n                    solidInterfaceBuffRcv_Z = np.zeros(sizeOfBuff)\n                    req = self.mpiComm.Irecv(solidInterfaceBuffRcv_X, iProc, tag=1)\n                    req.Wait()\n                    req = self.mpiComm.Irecv(solidInterfaceBuffRcv_Y, iProc, tag=2)\n                    req.Wait()\n                    req = self.mpiComm.Irecv(solidInterfaceBuffRcv_Z, iProc, tag=3)\n                    req.Wait()\n                    self.fillMatrixA(solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc)\n        else:\n            localSolidInterface_array_X, localSolidInterface_array_Y, localSolidInterface_array_Z = self.SolidSolver.getNodalInitialPositions()\n            self.fillMatrixA(localSolidInterface_array_X, localSolidInterface_array_Y, localSolidInterface_array_Z, 0)\n\n        mpiBarrier(self.mpiComm)\n        mpiPrint(\"\\nAssembling A...\", self.mpiComm)\n        start = tm.time()\n        self.A.assemble()\n        mpiBarrier(self.mpiComm)\n        stop = tm.time()\n        mpiPrint('Assembly performed in {} s'.format(stop-start), self.mpiComm)\n        mpiPrint('Matrix A is built.', self.mpiComm)\n\n        mpiPrint('\\nBuilding matrix B & D of size {} X {} & {} X {}...'.format(self.nf, self.ns, self.ns, self.nf), self.mpiComm)\n        # Fill the matrix B & D\n        if self.mpiComm != None:\n            for iProc in solidInterfaceProcessors:\n                if self.myid == iProc:\n                    for jProc in fluidInterfaceProcessors:\n                        self.mpiComm.Isend(localSolidInterface_array_X, dest=jProc, tag=1)\n                        self.mpiComm.Isend(localSolidInterface_array_Y, dest=jProc, tag=2)\n                        self.mpiComm.Isend(localSolidInterface_array_Z, dest=jProc, tag=3)\n                if self.myid in fluidInterfaceProcessors:\n                    sizeOfBuff = solidPhysicalInterfaceNodesDistribution[iProc]\n                    solidInterfaceBuffRcv_X = np.zeros(sizeOfBuff)\n                    solidInterfaceBuffRcv_Y = np.zeros(sizeOfBuff)\n                    solidInterfaceBuffRcv_Z = np.zeros(sizeOfBuff)\n                    req = self.mpiComm.Irecv(solidInterfaceBuffRcv_X, iProc, tag=1)\n                    req.Wait()\n                    req = self.mpiComm.Irecv(solidInterfaceBuffRcv_Y, iProc, tag=2)\n                    req.Wait()\n                    req = self.mpiComm.Irecv(solidInterfaceBuffRcv_Z, iProc, tag=3)\n                    req.Wait()\n                    self.fillMatrixBD(solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc)\n        else:\n            self.fillMatrixBD(localSolidInterface_array_X, localSolidInterface_array_Y, localSolidInterface_array_Z, 0)\n\n        mpiBarrier(self.mpiComm)\n        mpiPrint(\"\\nAssembling B & D...\", self.mpiComm)\n        start = tm.time()\n        self.B.assemble()\n        mpiBarrier(self.mpiComm)\n        self.D.assemble()\n        mpiBarrier(self.mpiComm)\n        stop = tm.time()\n        mpiPrint('Assembly performed in {} s'.format(stop-start), self.mpiComm)\n        mpiPrint('Matrix B & D are built.', self.mpiComm)\n\n        mpiPrint('\\nBuilding matrix C of size {} X {}...'.format(self.nf, self.nf), self.mpiComm)\n        # Fill the matrix C\n        if self.mpiComm != None:\n            for iProc in fluidInterfaceProcessors:\n                if self.myid == iProc:\n                    localFluidInterface_array_X, localFluidInterface_array_Y, localFluidInterface_array_Z = self.FluidSolver.getNodalInitialPositions()\n                    for jProc in fluidInterfaceProcessors:\n                        self.mpiComm.Send(localFluidInterface_array_X, dest=jProc, tag=1)\n                        self.mpiComm.Send(localFluidInterface_array_Y, dest=jProc, tag=2)\n                        self.mpiComm.Send(localFluidInterface_array_Z, dest=jProc, tag=3)\n                if self.myid in fluidInterfaceProcessors:\n                    sizeOfBuff = fluidPhysicalInterfaceNodesDistribution[iProc]\n                    fluidInterfaceBuffRcv_X = np.zeros(sizeOfBuff)\n                    fluidInterfaceBuffRcv_Y = np.zeros(sizeOfBuff)\n                    fluidInterfaceBuffRcv_Z = np.zeros(sizeOfBuff)\n                    self.mpiComm.Recv(fluidInterfaceBuffRcv_X, iProc, tag=1)\n                    self.mpiComm.Recv(fluidInterfaceBuffRcv_Y, iProc, tag=2)\n                    self.mpiComm.Recv(fluidInterfaceBuffRcv_Z, iProc, tag=3)\n                    self.fillMatrixC(fluidInterfaceBuffRcv_X, fluidInterfaceBuffRcv_Y, fluidInterfaceBuffRcv_Z, iProc)\n        else:\n            localFluidInterface_array_X, localFluidInterface_array_Y, localFluidInterface_array_Z = self.FluidSolver.getNodalInitialPositions()\n            self.fillMatrixC(localFluidInterface_array_X, localFluidInterface_array_Y, localFluidInterface_array_Z, 0)\n\n        mpiBarrier(self.mpiComm)\n        mpiPrint(\"\\nAssembling C...\", self.mpiComm)\n        start = tm.time()\n        self.C.assemble()\n        mpiBarrier(self.mpiComm)\n        stop = tm.time()\n        mpiPrint('Assembly performed in {} s'.format(stop-start), self.mpiComm)\n        mpiPrint('Matrix C is built.', self.mpiComm)\n\n        self.SolverA = LinearSolver(self.A, self.mpiComm)\n        self.SolverC = LinearSolver(self.C, self.mpiComm)\n\n    def interpolateFluidToSolid(self, fluidInterfaceData, solidInterfaceData):\n        \"\"\"\n        des.\n        \"\"\"\n\n        dim = fluidInterfaceData.getDim()\n        gamma_array = FlexInterfaceData(self.nf + self.d, dim, self.mpiComm)\n\n        self.SolverC.solve(fluidInterfaceData, gamma_array)\n        self.D.mult(gamma_array, solidInterfaceData)\n\n    def interpolateSolidToFluid(self, solidInterfaceData, fluidInterfaceData):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        dim = solidInterfaceData.getDim()\n        gamma_array = FlexInterfaceData(self.ns + self.d, dim, self.mpiComm)\n\n        self.SolverA.solve(solidInterfaceData, gamma_array)\n        self.B.mult(gamma_array, fluidInterfaceData)\n\nclass RBFInterpolator(ConservativeInterpolator):\n    \"\"\"\n    Description.\n    \"\"\"\n\n    def __init__(self, Manager, FluidSolver, SolidSolver, RBFradius=0.1, mpiComm = None, chtTransferMethod=None, heatTransferCoeff=1.0):\n        \"\"\"\"\n        Description.\n        \"\"\"\n\n        ConservativeInterpolator.__init__(self, Manager, FluidSolver, SolidSolver, mpiComm, chtTransferMethod, heatTransferCoeff)\n\n        mpiPrint('\\nSetting interpolation with Radial Basis Functions...', mpiComm)\n\n        self.radius = RBFradius\n\n        self.generateInterfaceData()\n\n        self.generateMapping()\n\n\n    def generateInterfaceData(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        ConservativeInterpolator.generateInterfaceData(self)\n\n        mpiPrint('Generating interface data for conservative RBF interpolator...', self.mpiComm)\n\n        self.A.createSparseFullAlloc()\n        self.A_T.createSparseFullAlloc()\n        self.B.createSparseFullAlloc()\n        self.B_T.createSparseFullAlloc()\n\n    def fillMatrixA(self, solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc):\n        \"\"\"\n        Description.\n        \"\"\"\n\n        localSolidInterface_array_X_init, localSolidInterface_array_Y_init, localSolidInterface_array_Z_init = self.SolidSolver.getNodalInitialPositions()\n        start = tm.time()\n        ccupydo.CInterpolator.RBF_fillMatrixA(self, localSolidInterface_array_X_init, localSolidInterface_array_Y_init, localSolidInterface_array_Z_init,\n                                              solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, self.A, self.A_T, iProc, 1.01*self.radius)\n        stop = tm.time()\n        print('Built A on rank {} in {} s'.format(self.myid,stop-start))\n\n\n    def fillMatrixB(self, solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc):\n        \"\"\"\n        Description.\n        \"\"\"\n\n        localFluidInterface_array_X_init, localFluidInterface_array_Y_init, localFluidInterface_array_Z_init = self.FluidSolver.getNodalInitialPositions()\n        start = tm.time()\n        ccupydo.CInterpolator.RBF_fillMatrixB(self, localFluidInterface_array_X_init, localFluidInterface_array_Y_init, localFluidInterface_array_Z_init,\n                                              solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, self.B, self.B_T, iProc, 1.01*self.radius)\n        stop = tm.time()\n        print('Built B on rank {} in {} s'.format(self.myid,stop-start))\n\n\n\nclass ConsistentRBFInterpolator(ConsistentInterpolator):\n    \"\"\"\n    Description.\n    \"\"\"\n\n    def __init__(self, Manager, FluidSolver, SolidSolver, RBFradius = 0.1, mpiComm= None, chtTransferMethod=None, heatTransferCoeff=1.0):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        ConsistentInterpolator.__init__(self, Manager, FluidSolver, SolidSolver, mpiComm, chtTransferMethod, heatTransferCoeff)\n\n        mpiPrint('\\nSetting interpolation with Radial Basis Functions...', mpiComm)\n\n        self.radius = RBFradius\n\n        self.generateInterfaceData()\n\n        self.generateMapping()\n\n    def generateInterfaceData(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        ConsistentInterpolator.generateInterfaceData(self)\n\n        mpiPrint('Generating interface data for consistent RBF interpolator...', self.mpiComm)\n\n        self.A.createSparseFullAlloc()\n        self.B.createSparseFullAlloc()\n        self.C.createSparseFullAlloc()\n        self.D.createSparseFullAlloc()\n\n\n    def fillMatrixA(self, solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc):\n        \"\"\"\n        Description.\n        \"\"\"\n\n        localSolidInterface_array_X_init, localSolidInterface_array_Y_init, localSolidInterface_array_Z_init = self.SolidSolver.getNodalInitialPositions()\n        start = tm.time()\n        ccupydo.CInterpolator.consistent_RBF_fillMatrixA(self, localSolidInterface_array_X_init, localSolidInterface_array_Y_init, localSolidInterface_array_Z_init,\n                                              solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, self.A, iProc, 1.01*self.radius)\n        stop = tm.time()\n        print('Built A on rank {} in {} s'.format(self.myid,stop-start))\n\n    def fillMatrixBD(self, solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc):\n        \"\"\"\n        Description.\n        \"\"\"\n\n        localFluidInterface_array_X_init, localFluidInterface_array_Y_init, localFluidInterface_array_Z_init = self.FluidSolver.getNodalInitialPositions()\n        start = tm.time()\n        ccupydo.CInterpolator.consistent_RBF_fillMatrixBD(self, localFluidInterface_array_X_init, localFluidInterface_array_Y_init, localFluidInterface_array_Z_init,\n                                              solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, self.B, self.D, iProc, 1.01*self.radius)\n        stop = tm.time()\n        print('Built B & D on rank {} in {} s'.format(self.myid,stop-start))\n\n    def fillMatrixC(self, fluidInterfaceBuffRcv_X, fluidInterfaceBuffRcv_Y, fluidInterfaceBuffRcv_Z, iProc):\n        \"\"\"\n        Description.\n        \"\"\"\n\n        localFluidInterface_array_X_init, localFluidInterface_array_Y_init, localFluidInterface_array_Z_init = self.FluidSolver.getNodalInitialPositions()\n        start = tm.time()\n        ccupydo.CInterpolator.consistent_RBF_fillMatrixC(self, localFluidInterface_array_X_init, localFluidInterface_array_Y_init, localFluidInterface_array_Z_init,\n                                              fluidInterfaceBuffRcv_X, fluidInterfaceBuffRcv_Y, fluidInterfaceBuffRcv_Z, self.C, iProc, 1.01*self.radius)\n        stop = tm.time()\n        print('Built C on rank {} in {} s'.format(self.myid,stop-start))\n\nclass TPSInterpolator(ConservativeInterpolator):\n    \"\"\"\n    Des.\n    \"\"\"\n\n    def __init__(self, Manager, FluidSolver, SolidSolver, mpiComm=None, chtTransferMethod=None, heatTransferCoeff=1.0):\n        \"\"\"\n        des.\n        \"\"\"\n\n        ConservativeInterpolator.__init__(self, Manager, FluidSolver, SolidSolver, mpiComm, chtTransferMethod, heatTransferCoeff)\n\n        mpiPrint('\\nSetting interpolation with Thin Plate Spline...', self.mpiComm)\n\n        self.generateInterfaceData()\n\n        self.generateMapping()\n\n    def generateInterfaceData(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        ConservativeInterpolator.generateInterfaceData(self)\n\n        mpiPrint('Generating interface data for TPS interpolator...', self.mpiComm)\n\n        self.A.createDense()\n        self.A_T.createDense()\n        self.B.createDense()\n        self.B_T.createDense()\n\n    def fillMatrixA(self, solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc):\n        \"\"\"\n        Description.\n        \"\"\"\n\n        localSolidInterface_array_X_init, localSolidInterface_array_Y_init, localSolidInterface_array_Z_init = self.SolidSolver.getNodalInitialPositions()\n\n        start = tm.time()\n        ccupydo.CInterpolator.TPS_fillMatrixA(self, localSolidInterface_array_X_init, localSolidInterface_array_Y_init, localSolidInterface_array_Z_init,\n                                              solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, self.A, self.A_T, iProc)\n        stop = tm.time()\n        print('Built A on rank {} in {} s'.format(self.myid,stop-start))\n\n    def fillMatrixB(self, solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc):\n        \"\"\"\n        Description.\n        \"\"\"\n\n        localFluidInterface_array_X_init, localFluidInterface_array_Y_init, localFluidInterface_array_Z_init = self.FluidSolver.getNodalInitialPositions()\n\n        start = tm.time()\n        ccupydo.CInterpolator.TPS_fillMatrixB(self, localFluidInterface_array_X_init, localFluidInterface_array_Y_init, localFluidInterface_array_Z_init,\n                                              solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, self.B, self.B_T, iProc)\n        stop = tm.time()\n        print('Built B on rank {} in {} s'.format(self.myid,stop-start))\n\nclass ConsistentTPSInterpolator(ConsistentInterpolator):\n    \"\"\"\n    Description.\n    \"\"\"\n\n    def __init__(self, Manager, FluidSolver, SolidSolver, mpiComm= None, chtTransferMethod=None, heatTransferCoeff=1.0):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        ConsistentInterpolator.__init__(self, Manager, FluidSolver, SolidSolver, mpiComm, chtTransferMethod, heatTransferCoeff)\n\n        mpiPrint('\\nSetting consistent interpolation with Thin Plate Spline...', self.mpiComm)\n\n        self.generateInterfaceData()\n\n        self.generateMapping()\n\n    def generateInterfaceData(self):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        ConsistentInterpolator.generateInterfaceData(self)\n\n        mpiPrint('Generating interface data for consistent TPS interpolator...', self.mpiComm)\n\n        self.A.createDense()\n        self.B.createDense()\n        self.C.createDense()\n        self.D.createDense()\n\n    def fillMatrixA(self, solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        localSolidInterface_array_X_init, localSolidInterface_array_Y_init, localSolidInterface_array_Z_init = self.SolidSolver.getNodalInitialPositions()\n        start = tm.time()\n        ccupydo.CInterpolator.consistent_TPS_fillMatrixA(self, localSolidInterface_array_X_init, localSolidInterface_array_Y_init, localSolidInterface_array_Z_init,\n                                              solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, self.A, iProc)\n        stop = tm.time()\n        print('Built A on rank {} in {} s'.format(self.myid,stop-start))\n\n    def fillMatrixBD(self, solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc):\n        \"\"\"\n        des.\n        \"\"\"\n\n        localFluidInterface_array_X_init, localFluidInterface_array_Y_init, localFluidInterface_array_Z_init = self.FluidSolver.getNodalInitialPositions()\n        start = tm.time()\n        ccupydo.CInterpolator.consistent_TPS_fillMatrixBD(self, localFluidInterface_array_X_init, localFluidInterface_array_Y_init, localFluidInterface_array_Z_init,\n                                              solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, self.B, self.D, iProc)\n        stop = tm.time()\n        print('Built B & D on rank {} in {} s'.format(self.myid,stop-start))\n\n    def fillMatrixC(self, fluidInterfaceBuffRcv_X, fluidInterfaceBuffRcv_Y, fluidInterfaceBuffRcv_Z, iProc):\n        \"\"\"\n        Des.\n        \"\"\"\n\n        localFluidInterface_array_X_init, localFluidInterface_array_Y_init, localFluidInterface_array_Z_init = self.FluidSolver.getNodalInitialPositions()\n        start = tm.time()\n        ccupydo.CInterpolator.consistent_TPS_fillMatrixC(self, localFluidInterface_array_X_init, localFluidInterface_array_Y_init, localFluidInterface_array_Z_init,\n                                              fluidInterfaceBuffRcv_X, fluidInterfaceBuffRcv_Y, fluidInterfaceBuffRcv_Z, self.C, iProc)\n        stop = tm.time()\n        print('Built C on rank {} in {} s'.format(self.myid,stop-start))\n", "meta": {"hexsha": "e2e927f86630e11630fba2961f7d26653175c737", "size": 66490, "ext": "py", "lang": "Python", "max_stars_repo_path": "cupydo/interpolator.py", "max_stars_repo_name": "AxelDechamps/CUPyDO", "max_stars_repo_head_hexsha": "52b42804516ac95c7969d04ba9471b62c6f7b875", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2018-12-09T09:50:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T01:06:48.000Z", "max_issues_repo_path": "cupydo/interpolator.py", "max_issues_repo_name": "AxelDechamps/CUPyDO", "max_issues_repo_head_hexsha": "52b42804516ac95c7969d04ba9471b62c6f7b875", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2019-02-07T10:47:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T22:01:31.000Z", "max_forks_repo_path": "cupydo/interpolator.py", "max_forks_repo_name": "AxelDechamps/CUPyDO", "max_forks_repo_head_hexsha": "52b42804516ac95c7969d04ba9471b62c6f7b875", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-02-14T09:23:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T09:19:32.000Z", "avg_line_length": 47.4589578872, "max_line_length": 356, "alphanum_fraction": 0.6477365017, "include": true, "reason": "import numpy", "num_tokens": 15033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.19449787629743093}}
{"text": "#A library of code to examine properties of bulk water and near solutes\n#\n#Should eventually be able to handle local densities and fluctuations,\n#solute-water and water-water energies, 3-body angles, hydrogen bonds,\n#energy densities, and all of this as a function of space. Additionally,\n#should also be able to compute interfaces, such as Willard-Chandler\n#instantaneous interface, or vdW surface, SASA and volume of solute.\n#\n#Will work with pytraj interface for trajectory analysis, since this\n#should later allow easier energy decomposition?\n#If doesn't work out, will go back to sim package with netcdf plugin.\n#\n#Also, should have test script and some test system where know answers\n#\n\nimport sys, os\nimport numpy as np\nimport scipy.optimize as optimize\nfrom scipy.special import sph_harm\nimport waterlib as wl\n\n#Define constants and unit conversions\n\n#conversion for surface tension\nkBJ = 1.38064852*(10**(-23))\ntemp = 300.0\ntomJm2 = kBJ*temp*1000.0*(10**20) #converts kBT/Angstrom^2 to mJ/m^2\n\n#Convert potential energy to kBT\nkBTkcal = 0.0019858775*300.0\n\n#Water density\nwatdens = 0.033456 # molecules or oxygens per Angstrom ^ 3 near 300 K\n\n#Define library of useful functions\n\ndef SASAperAtom(pos, radii, radius=1.4, nPoints = 1000, nExpose = 10):\n  \"\"\"Inputs:\n     pos - Nx3 array of atomic positions\n     radii - N array of atomic radii\n     radius - solvent radius to \"roll\" over surface\n     nPoints - number points on each sphere\n     nExpose - number exposed points on atom (sphere) to be considered on surface\n     Outputs:\n     SASAper - SASA for each atom\n     surfAtoms - array of 1 for solvent exposed, 0 for not on surface\n  \"\"\"\n\n  points = wl.spherepoints(nPoints)\n  SASAper, surfAtoms = wl.spheresurfaceareas(pos, radii+radius, points, nExpose)\n\n  return SASAper, surfAtoms\n\n\ndef PepWatHBonds(allPos, pepAccInds, pepDonInds, watInds, distCut = 2.1, angCut = 30.0):\n  \"\"\"Currently kind of wack (does acceptor to hydrogen distance). Also, calculating \nH-bonds geometrically seems less useful.\n     Inputs:\n     allPos - full position array for trajectory frame (all atoms included)\n     pepAccInds - global indices of peptide acceptors\n     pepDonInds - global indices of peptide donors\n     watInds - global indices of water atoms in selected hydration shell(s)\n     distCut(=2.1) - distance cutoff for H-bond detection\n     angCut(=30.0) - angle cutoff for H-bond detection\n     Outputs:\n     NBonds - number of detected H-bonds\n     bondsPer - number H-bonds for each water molecule with peptide\n     donors - indices of donors (H atoms only) as string\n     acceptors - indices of acceptors as string\n  \"\"\"\n\n  #Get H-bond info\n  NBonds, watAcc, watDon, pepAcc, pepDon = wl.findhbonds(\n                             allPos[pepAccInds], allPos[pepDonInds], allPos[watInds], distCut, angCut)\n\n  #And sort nicely into just acceptors and donors\n  acceptorsList = []\n  donorsList = []\n  bondsWat = np.zeros(int(len(watInds)/3))\n\n  for (j, val) in enumerate(pepAcc):\n    acceptorsList = acceptorsList + (val*[pepAccInds[j]])\n\n  for (j, val) in enumerate(pepDon):\n    donorsList = donorsList + (val*[pepDonInds[j]])\n\n  for (j, val) in enumerate(watAcc):\n    acceptorsList = acceptorsList + (val*[watInds[j]])\n    bondsWat[int(j/3)] = bondsWat[int(j/3)] + val\n\n  for (j, val) in enumerate(watDon):\n    donorsList = donorsList + (val*[watInds[j]])\n    bondsWat[int(j/3)] = bondsWat[int(j/3)] + val\n\n  #Above uses properties of python lists to add each index the number of H-bonds it participates in\n\n  bondsPer = bondsWat\n  \n  #For easy file writing, make donors and acceptors into strings of indices\n  #Remember that the sim package indexes at zero!\n  donors = ''.join(str(e)+\"|\" for e in donorsList)\n  acceptors = ''.join(str(e)+\"|\" for e in acceptorsList)\n    \n  return NBonds, bondsPer, acceptors, donors\n\n\ndef BBHBonds(allPos, pepAccInds, pepDonInds, distCut = 2.1, angCut = 30.0):\n  \"\"\"Finds H bonds between two list of acceptors and donors. Intended for just peptide backbone.\n     Inputs:\n     allPos - full position array for trajectory frame\n     pepAccInds - global indics of peptide acceptors\n     pepDonInds - global indices of peptide doneors\n     distCut(=2.1) - distance cutoff for H-bond detection\n     angCut(=30.0) - angle cutoff for H-bond detection\n     Outputs:\n     NBonds - number of detected H-bonds\n     donors - indices of donors as string\n     acceptors - indices of acceptors as string\n  \"\"\"\n\n  #Get H-bonds\n  NBonds, pepAcc, pepDon = wl.bbhbonds(allPos[pepAccInds], allPos[pepDonInds], distCut, angCut)\n  \n  #Sort nicely\n  acceptorsList = []\n  donorsList = []\n\n  for (j, val) in enumerate(pepAcc):\n    acceptorsList = acceptorsList + (val*[pepAccInds[j]])\n\n  for (j, val) in enumerate(pepDon):\n    donorsList = donorsList + (val*[pepDonInds[j]])\n\n  #set lists to strings and return\n  donors = ''.join(str(e)+\"|\" for e in donorsList)\n  acceptors = ''.join(str(e)+\"|\" for e in acceptorsList)\n    \n  return NBonds, acceptors, donors\n\n\ndef WatHBonds(allPos, watInds, allWatInds, BoxDims, distCut = 2.1, angCut = 30.0):\n  \"\"\"Also kind of wack, but keeping since used in peptide-surface pulling analysis.\n     For a better, more general algorithm, use HBondsGeneral.\n     Inputs:\n     allPos - full position array for trajectory frame (all atoms included)\n     watInds - global indices of water atoms in selected hydration shell(s)\n     allWatInds - global indices of ALL water atoms\n     BoxDims - dimensions of box to account for periodic BCs (to turn off, set to zero)\n     distCut(=2.1) - distance cutoff for H-bond detection\n     angCut(=30.0) - angle cutoff for H-bond detection\n     Outputs:\n     NBonds - number of detected H-bonds\n     bondsPer - number of detected H-bonds for each water molecule in selection\n     acceptors - indices of acceptors as string\n     donors - indices of donors (H atoms only) as string\n  \"\"\"\n\n  #Get H-bond info\n  NBonds, watAcc, watDon = wl.wathbonds(allPos[watInds], allPos[allWatInds], BoxDims, distCut, angCut)\n\n  #And sort nicely into just acceptors and donors\n  #Also count number of H-bonds for each water to get estimate of average per water\n  acceptorsList = []\n  donorsList = []\n  bondsWat = np.zeros(int(len(watInds)/3))\n\n  for (j, val) in enumerate(watAcc):\n    acceptorsList = acceptorsList + (val*[watInds[j]])\n    bondsWat[int(j/3)] = bondsWat[int(j/3)] + val\n\n  for (j, val) in enumerate(watDon):\n    donorsList = donorsList + (val*[watInds[j]])\n    bondsWat[int(j/3)] = bondsWat[int(j/3)] + val\n\n  #Above uses properties of python lists to add each index the number of H-bonds it participates in\n\n  #print bondsWat\n  #bondsPer = np.average(bondsWat)\n  bondsPer = bondsWat\n  \n  #For easy file writing, make donors and acceptors into strings of indices\n  #Remember that the sim package indexes at zero!\n  donors = ''.join(str(e)+\"|\" for e in donorsList)\n  acceptors = ''.join(str(e)+\"|\" for e in acceptorsList)\n    \n  return NBonds, bondsPer, acceptors, donors\n\n\ndef getCosAngs(subPos, Pos, BoxDims, lowCut=0.0, highCut=3.413):\n  \"\"\"This is called getCosAngs, but actually just returns the angles themselves (faster to convert\n     from cos(theta) to theta in Fortran)\n     Inputs:\n     subPos - positions of set of atoms to measure tetrahedrality of (may be different, subset, or same as Pos)\n     Pos - positions of ALL atoms that can make tetrahedral configurations (needed if subPos not same as Pos)\n     BoxDims - current box dimensions to account for periodicity\n     lowCut - lower cutoff for nearest-neighbor shell (default 0.0)\n     highCut - higher cutoff for nearest-neighbor shell (default 3.413 - see Chaimovich, 2014, but should really\n               change to reflect first peak in g(r) for the chosen water model)\n     Outputs:\n     angVals - all angle values for current configuration of positions supplied\n     numAngs - number of angles for each central oxygen atom (i.e. number neighbors factorial)\n               This is useful for finding which angles belong to which central oxygens\n               This return value was added on 07/09/2017, so any code using this function\n               before then will break, unfortunately, but the fix is easy.\n  \"\"\"\n\n  #Set-up array to hold angle results and stack as go... list increases in size!\n  angVals = np.array([])\n  numAngs = np.zeros(len(subPos))\n\n  #Find nearest neighbors for ALL atoms in subPos\n  #But make sure using efficient algorithm...\n  #If subPos is same as Pos, use allnearneighbors instead\n  if np.array_equal(subPos, Pos):\n    nearNeighbs = wl.allnearneighbors(Pos, BoxDims, lowCut, highCut).astype(bool)\n  else:\n    nearNeighbs = wl.nearneighbors(subPos, Pos, BoxDims, lowCut, highCut).astype(bool)\n\n  #Loop over each position in subPos, finding angle made with all neighbor pairs\n  for (i, apos) in enumerate(subPos):\n    #Make sure have nearest neighbors...\n    if len(Pos[nearNeighbs[i]]) > 0:\n      #below returns symmetric, square array (zero diagonal)\n      tempAng = wl.tetracosang(apos, Pos[nearNeighbs[i]], BoxDims) \n      #Only want half of array, flattened\n      angVals = np.hstack((angVals, tempAng[np.triu_indices(len(tempAng),k=1)].tolist()))\n      numAngs[i] = tempAng.shape[0]\n\n  return angVals, numAngs\n  \n  \ndef tetrahedralMetrics(angVals, nBins=500, binRange=[0.0, 180.0]):\n  \"\"\"Inputs:\n     angVals - all angle values sampled\n     nBins - number histogram bins to use\n     binRange - histogram bin range to apply\n     Outputs:\n     angDist - distribution of angle\n     bins - bins used in histogramming\n     fracTet - fraction of distribution that is tetrahedral (integrate cosDist from -0.75 to 0.25 - see Chaimovich, 2014)\n     avgCos - average Cos(angle) within tetrahedral peak\n     stdCos - second moment of Cos(angle) within tetrahedral peak\n  \"\"\"\n  \n  #Histogram the data - note that density set so just returns number of counts, not normalized\n  angDist, bins = np.histogram(angVals, bins=nBins, range=binRange, density=False)\n\n  #Take index before since want histogram bin containing this value\n  startTet = np.argmax(bins>np.arccos(0.25)*180.0/np.pi) - 1\n  endTet = np.argmax(bins>np.arccos(-0.75)*180.0/np.pi) - 1 \n\n  fracTet = np.sum(angDist[startTet:endTet]) / np.sum(angDist)\n\n  #Take average and second moment within peak\n  avgCos = 0.0\n  stdCos = 0.0\n  angCount = 0\n\n  for ang in angVals:\n    if (ang >= np.arccos(0.25)*180.0/np.pi) and (ang <= np.arccos(-0.75)*180.0/np.pi):\n      avgCos = avgCos + np.cos(ang*np.pi/180.0)\n      stdCos = stdCos + np.cos(ang*np.pi/180.0)**2\n      angCount += 1\n\n  avgCos = avgCos / angCount\n  stdCos = stdCos / angCount\n\n  return angDist, bins, fracTet, avgCos, stdCos\n\n\ndef getOrderParamq(subPos, Pos, BoxDims, lowCut=0.0, highCut=8.0):\n  \"\"\"Finds angles for 4 nearest neighbors of each water and returns for all waters the \ntetrahedral order parameter, q, used by Errington and Debenedetti (2001).\n     Inputs: \n     subPos - positions of set of atoms to measure tetrahedrality of (may be different, subset, or same as Pos)\n     Pos - positions of ALL atoms that can make tetrahedral configurations (needed if subPos not same as Pos)\n     BoxDims - current box dimensions to account for periodicity\n     lowCut - lower cutoff for nearest-neighbor shell (default 0.0)\n     highCut - higher cutoff for nearest-neighbor shell used to find 4 nearest neighbors\n     Outputs:\n     qVals - returns an order parameter value for each water\n     distNeighbs - returns distances from central oxygen to 4 nearest neighbors\n  \"\"\"\n\n  #Set-up array to hold results\n  qVals = np.zeros(len(subPos))\n  distNeighbs = np.zeros((len(subPos), 4))\n\n  #Find nearest neighbors for ALL atoms in subPos\n  #But make sure using efficient algorithm...\n  #If subPos is same as Pos, use allnearneighbors instead\n  if np.array_equal(subPos, Pos):\n    nearNeighbs = wl.allnearneighbors(Pos, BoxDims, lowCut, highCut).astype(bool)\n  else:\n    nearNeighbs = wl.nearneighbors(subPos, Pos, BoxDims, lowCut, highCut).astype(bool)\n\n  #Loop over each position in subPos, finding angle made with the closest 4 neighbors, then q\n  for (i, apos) in enumerate(subPos):\n    #Make sure have nearest neighbors...\n    if np.sum(nearNeighbs[i]) > 0:\n      thisPos = wl.reimage(Pos[nearNeighbs[i]], apos, BoxDims)\n      thisDists = np.linalg.norm(thisPos - apos, axis=1)\n      sortInds = np.argsort(thisDists)\n      newPos = thisPos[sortInds][:4]\n      distNeighbs[i,:] = thisDists[sortInds][:4]\n      #below returns symmetric, square array (zero diagonal)\n      tempAng = wl.tetracosang(apos, newPos, BoxDims)\n      #Only want half of array, flattened\n      angVals = tempAng[np.triu_indices(len(tempAng),k=1)]\n      #Now compute q for this set of angles\n      qVals[i] = 1.0 - (3.0/8.0)*np.sum((np.cos(angVals*np.pi/180.0) + (1.0/3.0))**2)\n\n  #Return all of the order parameter values\n  return qVals, distNeighbs\n\n\ndef findSineCoeffs(allangs, Norder=180, doNormalize=False):\n  \"\"\"Given an array of angles, computes the sine coefficients to the given order.\nNote that to get right coefficients, will need to divide by total number of angles.\nThis is not done by default, assuming that angles provided are for each frame.\n     Inputs:\n             allangs - array or list of angles\n             Norder - (default 180) number of terms in sine series to use (excludes k=0)\n             doNormalize - (default False) if true, divides by number of samples to correctly normalize\n     Outputs:\n             coeffs - Norder x 2 array; 1st column is k, second column is coefficient\n                      Comes from fact that period is zero to Pi, so only keep sin(k*angle) in series\n  \"\"\"\n  #Check if angles in radians - if any values are greater than Pi, assume in degrees\n  if np.max(allangs) > np.pi:\n    allangs = allangs * np.pi / 180.0\n  coeffs = np.zeros((Norder,2))\n  for k in range(Norder):\n    coeffs[k,0] = k+1\n    coeffs[k,1] = np.sqrt(2.0/np.pi)*np.sum(np.sin((k+1)*allangs))\n  if doNormalize:\n    coeffs = coeffs / len(allangs)\n  return coeffs\n\n\ndef distFromCoeffs(coeffs, angvals=None, Norder=60):\n  \"\"\"Given an array of coefficients for a sine series, compute the distribution.\n     Inputs:\n             coeffs - coefficients for each term in a sine series\n                      assuming that for sin(k*angle) form, this array is sorted from small to large k\n             angvals - (default 0.0 to 180.0 by 0.01) angle values in degrees at which distribution \n                       should be evaluated - normalization will be done for PDF along degrees\n             Norder - (default 60) number of terms in the series to use (i.e. number of coeffs)\n     Outputs:\n             adist - returns a normalized distribution\n  \"\"\"\n  if angvals is None:\n    angvals = np.arange(0.0, 180.0, 0.01)\n  #Also define in radians\n  radvals = angvals * np.pi / 180.0\n  adist = np.zeros(len(angvals))\n  normfac = 0.0\n  for k in range(Norder):\n    adist += coeffs[k]*np.sin((k+1)*radvals)\n    if (k+1)%2 != 0:\n      normfac += coeffs[k]*2.0/(k+1)\n  adist = adist / (normfac*(angvals[1]-angvals[0]))\n  return adist\n\n\ndef fitDist(refDists, Dist, bruteNs=200):\n  \"\"\"Given a set of reference distributions, as a numpy array with each distribution as a row,\nfits the current distribution using a linear combination of the reference distributions.\n  Inputs:\n  refDists - array with each reference distribution as a row\n  Dist - (3-body angle) distribution to fit as linear combination of references with\n         the fitting parameters (linear coefficients) summing to one\n  bruteNs - number of discrete bins to use along each parameter when searching for brute minimum\n  Outputs:\n  fitParams - fit parameters resulting from fitting \n  resSq - sum of squared residuals for fit\n  resSigned - signed residuals at each point of fit\n  \"\"\"\n\n  #Define tolerance\n  tolf = 1.0e-12\n  tolx = 1.0e-12  \n\n  #Initialize parameters to seek for - start in 4 ways and take minimum of these\n  initParams = np.eye(refDists.shape[0])\n  initParams = np.vstack((initParams, np.ones(refDists.shape[0]) * (1.0/refDists.shape[0])))\n\n  #Define an objective function to be minimized\n  def funcMin(vals, *withcon):\n    #Give it parameter values, returns squared residuals\n    func = np.sum((np.dot(vals, refDists) - Dist)**2)\n    if withcon:\n      func = func + (np.sum(vals) - 1.0)**2\n    return func\n\n  def jacFunc(vals):\n    #Returns the Jacobian of the function to minimize\n    func = np.dot(refDists, 2.0*(np.dot(vals, refDists) - Dist))\n    return func\n\n  def funcSquares(vals):\n    #Gives vector of squared residuals to see where best/worst parts of fit are\n    func = (np.dot(vals, refDists) - Dist)**2\n    return func\n\n  #Define constraints... for now say that all parms must sum to one\n  cons = ({'type' : 'eq',\n           'fun' : lambda x: np.sum(x) - 1.0,\n           'jac' : lambda x: np.ones(len(x))})\n\n  #And define bounds to keep all params between 0 and 1\n  bnds = [(0.0,1.0)]*refDists.shape[0]\n\n  #For each set of starting conditions, do minimization, then pick global min\n  globMinInfo = None\n\n  #And will store squared residuals at found mins as go\n  #Checks if one part of curve fits better than another\n  resSq = np.zeros((refDists.shape[1], initParams.shape[0]))\n\n  for (i, params) in enumerate(initParams):\n\n    #If only one distribution given, don't use constraint\n    if refDists.shape[0] == 1:\n      mininfo = optimize.minimize(funcMin, params, jac=jacFunc, method='SLSQP',\n                                                bounds=bnds, options={'ftol':tolf})\n    else:\n      mininfo = optimize.minimize(funcMin, params, jac=jacFunc, method='SLSQP',\n                                constraints=cons, bounds=bnds, options={'ftol':tolf})\n   \n    #print \"Minimum sum of squares: %e  at values \"%mininfo.fun+str(mininfo.x)\n\n    if globMinInfo != None:\n      if mininfo.fun < globMinInfo.fun:\n        globMinInfo = mininfo\n    else:\n      globMinInfo = mininfo\n\n    resSq[:,i] = funcSquares(mininfo.x)\n\n  #Compare to global min with brute force\n  if refDists.shape[0] == 1:\n    (bruteMinInfo) = optimize.brute(funcMin, tuple(bnds), Ns=bruteNs, finish=None, full_output=True, disp=False)\n  else:\n    (bruteMinInfo) = optimize.brute(funcMin, tuple(bnds), args=(1,), Ns=bruteNs, finish=None, full_output=True, disp=False)\n\n  fitParams = bruteMinInfo[0]\n\n  #print \"Brute force finds minima at \"+str(fitParams)\n\n  #Also compute regular residuals, not squared\n  resSigned = np.dot(fitParams, refDists) - Dist\n\n  #print \"Best fit found at:\"\n  #print [float(q) for q in fitParams]\n  #print \"And with parameters summing to %f\" % np.sum(fitParams)\n  return fitParams, resSq, resSigned \n\n\ndef waterOrientationBinZ(Opos, Hpos, boxDim, refVec=[0.0, 0.0, 1.0], refBins=None, angBins=None):\n  \"\"\"Determines the angle between a reference vector and the dipoles and plane-normal vector\nof all water molecule positions provided.\n     Inputs:\n     Opos - all water oxygen positions\n     Hpos - all water hydrogen positions\n     boxDim - box dimensions for imaging\n     refVec - the reference vector for water orientation, default\n              is the z-direction [1, 0, 0]\n     refBins - bins along the direction of refVec that the waters \n               should be placed into (default is min and max along refVec)\n     angBins - bins for calculated angles, default 500 bins from 0 to 180\n     Outputs:\n     plane2Dhist - 2D histogram with angle bins varying over rows and \n                   refVec bins varying over rows (for the water plane vector angles)\n     dip2Dhist - 2D histogram as above, but for dipole vector angles\n  \"\"\"\n\n  #Get positions of oxygen atoms along refVec, then create \n  #this array with each entry repeated\n  refVec = refVec / np.linalg.norm(refVec)\n  zOpos = np.dot(Opos, refVec)\n  zOposforH = np.array([[z,z] for z in zOpos]).flatten()\n\n  #Compute all of the angles with respect to the reference\n  #Note that the dipole vector of each water molecule will be taken as\n  #the sum of the OH bond vectors\n  angDip, angPlane = wl.watorient(Opos, Hpos, refVec, boxDim)\n\n  #Set refBins if not set\n  if refBins is None:\n    refBins = np.arange(np.min(zOpos), np.max(zOpos), 0.2)\n\n  #Same for angBins\n  if angBins is None:\n    angBins = np.arange(0.0, 180.001, 180.0/500.0)\n\n  #And do 2D histogramming\n  plane2Dhist, angEdges, refEdges = np.histogram2d(angPlane, zOposforH, bins=[angBins, refBins], normed=False)\n  dip2Dhist, angEdges, refEdges = np.histogram2d(angDip, zOpos, bins=[angBins, refBins], normed=False)\n\n  return plane2Dhist, dip2Dhist\n\n\ndef waterOrientation(Opos, Hpos, boxDim, refVec=[0.0, 0.0, 1.0]):\n  \"\"\"This is a wrapper for the waterlib function watorient.\n     Inputs:\n     Opos - all water oxygen positions\n     Hpos - all water hydrogen positions\n     boxDim - box dimensions for imaging\n     refVec - the reference vector for water orientation, default\n              is the z-direction [1, 0, 0]\n     Outputs:\n     dipAngs - all angles of dipole vectors with reference vector for all waters\n     planeAngs - all angles of plane-normal vector to reference vector for all waters\n  \"\"\"\n\n  #Call watorient to get all angles\n  dipAngs, planeAngs = wl.watorient(Opos, Hpos, refVec, boxDim)\n\n  return dipAngs, planeAngs\n\n\ndef binnedVolumePofN(Opos, volBins, numBins, binMask=None):\n  \"\"\"Inputs:\n     Opos - array of oxygen 3D coordinates\n     volBins - volume (x,y,z coordinate) bin edges tiling the space to place waters into\n               Form should be tuple of x, y, and z bin edge arrays\n               Bins should be uniform (makes no sense to structure analysis this way otherwise)\n     numBins - bin edges for histogramming number of waters in each volume of volBins\n     binMask - boolean array of same dimension as number of bins in x, y, z\n               Use to exclude some bins by changing certain coordinates to False\n     Outputs:\n     numWatHist - counts for number of waters in sub-volume of size edgeLxedgeLxedgeL\n  \"\"\"\n\n  #Create mask if necessary\n  if binMask is None:\n    binMask = np.ones((len(volBins[0])-1, len(volBins[1])-1, len(volBins[2])-1), dtype=bool)\n  else:\n    if binMask.shape == (len(volBins[0])-1, len(volBins[1])-1, len(volBins[2])-1):\n      binMask = binMask\n    else:\n      print \"Dimensions of mask for spatial bins does not match dimensions of spatial bins. Quitting.\"\n      sys.exit(2)\n\n  #Want to use sphere rather than cube for statistics\n  #So first find which bin each oxygen belongs to, then find distance\n  #to center of bin and see if should exclude or not\n  #Written in Fortran for speed\n  hist = wl.binongrid(Opos, volBins[0], volBins[1], volBins[2])\n\n  #Use numpy histogramming to count how many oxygens in each cube volume (doesn't use interior spheres)\n  #hist, edges = np.histogramdd(Opos, bins=volBins, normed=False)\n\n  #Now histogram number of waters in each subvolume, which will be P(N)\n  numWatHist, watedges = np.histogram(hist[binMask].flatten(), bins=numBins, normed=False)\n\n  return numWatHist\n\n#Should also define some function \"pointsInVol\" that creates binMask based on given set of points or some geometry that should not be included when finding waters (i.e. like a hard sphere or protein)\n\n\ndef HBondsGeneral(accPos, donPos, donHPos, boxL, accInds, donInds, donHInds, distCut=3.5, angCut=150.0):\n  \"\"\"Wraps generalHbonds in the waterlib library to define H-bonds, and also returns their locations.\n     Inputs:\n     accPos - 3-dimensional vectors of acceptor heavy-atom positions\n     donPos - 3D vectors of donor heavy-atom positions (if have multiple hydrogens, must list multiple times)\n     donHPos - 3D vector of donor hydrogen positions (should be same length as donPos, which may have duplicates)\n     accInds - indices of acceptor atoms\n     donInds - indices of donor heavy-atoms\n     donHInds - indices of donor hydrogen atoms\n     boxL - box dimensions\n     distCut - (default 3.5) heavy-atom to heavy-atom distance below which an H-bond may be defined \n     angCut - (default 150.0) O-H---O angle cut-off, in degrees, above which an H-bond may be defined\n     Outputs:\n     NumHB - number of hydrogen bonds for acceptor/donor set provided\n     HBlist - NumHB x 2 array with acceptor index in the 1st column and donor index in the 2nd\n     HBloc - NumHB x 3 array of h-bond locations, which is halfway between the acceptor and donor H\n  \"\"\"\n\n  #First get H-bond matrix and locations\n  HBboolMat = wl.generalhbonds(accPos, donPos, donHPos, boxL, distCut, angCut)\n  HBboolMat = np.array(HBboolMat, dtype=bool)\n\n  #Now parse through matrix, counting H-bonds and creating list of index pairs\n  NumHB = np.sum(HBboolMat)\n  HBlist = (-1)*np.ones((NumHB, 2))\n  HBloc = np.zeros((NumHB, 3))\n  HBlistCount = 0\n  for i, abool in enumerate(HBboolMat):\n    theseDonors = donInds[abool]\n    if len(theseDonors) > 0:\n      theseDonHPos = donHPos[abool]\n      #Image donor H location around acceptor\n      theseDonHPos = wl.reimage(theseDonHPos, accPos[i], boxL)\n      for j, aDon in enumerate(theseDonors):\n        HBlist[HBlistCount,:] = [accInds[i], aDon]\n        HBloc[HBlistCount] = 0.5*(theseDonHPos[j] + accPos[i])\n        HBlistCount += 1\n\n  return NumHB, HBlist, HBloc\n\n\ndef computeSphericalFourierCoeffs(subPos, Pos, BoxDims, lowCut=0.0, highCut=3.413, minDegree=0, maxDegree=12):\n  \"\"\"Computes the vectors of Fourier coefficients for each degree of a spherical harmonic expansion \n     as described by Keys, Iacovella, and Glotzer, 2011. subPos is treated as the central atoms, \n     while Pos should include the atoms that may potentially be neighbors.\n     Inputs:\n     subPos - positions of atoms to treat as the central atoms\n     Pos - positions of all other atoms, which will be considered for neighbor-searching; can be same as subPos\n     BoxDims - box dimensions so that minimum images may be used\n     lowCut - (default 0.0) the lower cutoff for the radial shell\n     highCut - (default 3.413) the upper cutoff for the radial shell\n     minDegree - (default 0) the minimum spherical harmonic degree (l)\n     maxDegree - (default 12) the maximum spherical harmonic degree (l)\n     Outputs:\n     coeffVecs - a len(subPos) x (1 + maxDegree - minDegree) x (2*maxDegree + 1) matrix\n                 For each central atom in subPos, a matrix of the complex-valued vectors (as rows)\n                 is provided. This still allows magnitudes to be easily evaluated, since real and\n                 imaginary parts of zero will contribute nothing to the magnitude\n     numNeighbs - number of neighbors for each water molecule (necessary to compute global order parameters\n                  or coefficients by multiplying by this and the dividing by the total of the waters\n                  to \"average\" over)\n  \"\"\"\n\n  #Set up the output matrix now since know size\n  coeffVecs = np.zeros((len(subPos), 1+maxDegree-minDegree, 2*maxDegree+1), dtype=complex)\n  \n  #And array to return number of neighbors for each water\n  numNeighbs = np.zeros(len(subPos), dtype='float16')\n\n  #Would be nice to combine neighbor searching with 3-body angle computation or H-bonding code\n  #But then harder to efficiently implement different cutoffs...\n  #So that might be too ambitious\n  #Find neighbors within cutoff for ALL atoms in subPos\n  #But make sure using efficient algorithm...\n  #If subPos is same as Pos, use allnearneighbors instead\n  if np.array_equal(subPos, Pos):\n    nearNeighbs = wl.allnearneighbors(Pos, BoxDims, lowCut, highCut).astype(bool)\n  else:\n    nearNeighbs = wl.nearneighbors(subPos, Pos, BoxDims, lowCut, highCut).astype(bool)\n\n  #Loop over each position in subPos and find neighbor positions in spherical coordinates\n  for (i, apos) in enumerate(subPos):\n    #Make sure have nearest neighbors...\n    if len(Pos[nearNeighbs[i]]) > 0:\n      tempPos = wl.reimage(Pos[nearNeighbs[i]], apos, BoxDims) - apos\n      numNeighbs[i] = len(tempPos)\n      #Compute radial distances... unfortunate that have to do this again, but maybe improve later\n      rdists = np.linalg.norm(tempPos, axis=1)\n      #And get polar and azimuthal angles\n      polarang = np.arccos(tempPos[:,2]/rdists)\n      azimang = np.arctan2(tempPos[:,1], tempPos[:,0]) #Using special arctan2 function to get quadrant right\n      #Now compute Fourier coefficient vectors (i.e. have complex-valued component of coefficient vector\n      #associated with each m value, where m = -l, -l+1, ... , l)\n      #Loop over the desired number of coefficients to compute\n      for l in range(minDegree, maxDegree + 1):\n        thisvec = np.zeros(2*l + 1, dtype=complex)\n        #Also note that have one vector for each neighbor, so must loop over neighbors\n        for j in range(len(tempPos)):\n          thisvec += sph_harm(np.arange(-l, l+1), l, azimang[j], polarang[j])\n        thisvec /= len(tempPos)\n        #And compute the magnitude of this vector of complex numbers\n        coeffVecs[i,l-minDegree,:(2*l+1)] = thisvec\n\n  return coeffVecs, numNeighbs\n\n\ndef get1BodyDOFs(coordO, coordH1, coordH2):\n  \"\"\"Given O, H, and H 3D coordinates, identifies the 6 degrees of freedom for a single water\nNote that this is assuming an inhomogeneous system\nVector returned is oxygen x, y, z, followed by the spherical coordinate angles for the \ndipole vector relative to the oxygen, and the angle of rotation around the dipole vector\nCOORDINATES SHOULD ALREADY BE IMAGED.\n  \"\"\"\n  dofVec = np.zeros(6)\n  dofVec[:3] = coordO[:]\n\n  rOD = 0.5*(coordH1 + coordH2) - coordO\n  rOD /= np.linalg.norm(rOD) #Could hard-code the rOD length for speed... maybe later\n\n  rH1H2 = coordH2 - coordH1\n  rH1H2 /= np.linalg.norm(rH1H2) #And could also hard-code this, too...\n\n  #rOH1 = coordH1 - coordO\n  #rOH1 /= np.linalg.norm(rOH1)\n\n  #rOH2 = coordH2 - coordO\n  #rOH2 /= np.linalg.norm(rOH2)\n\n  unitX = np.array([0.0, 0.0, 1.0]) #Arbitrarily pick x axis to define reference plane for rotation about dipole\n\n  #cross1 = np.cross(rOH1, rOH2)\n  #cross1 /= np.linalg.norm(cross1)\n\n  crossX = np.cross(rOD, unitX)\n  crossX /= np.linalg.norm(crossX)\n\n  dofVec[3] = np.arctan2(rOD[1], rOD[0]) #Making sure to use arctan2 to cover range [-pi, pi]\n  dofVec[4] = np.arccos(rOD[2]) #Taking last element is same as dotting with unit Z vector\n  dofVec[5] = np.arccos(np.dot(rH1H2, crossX))\n  #dofVec[5] = np.arccos(np.dot(cross1, crossX))\n\n  return dofVec\n\n\ndef get2BodyDOFs(coordO1, coordH11, coordH12, coordO2, coordH21, coordH22):\n  \"\"\"Given 3D coordinates for all atoms in two water molecules, computes specifically 2-body degrees of freedom\nNote that returns only 6 degrees of freedom, so excludes the DOFs for the first water\nONLY gives those relevant to relative distance and orientation of two waters\nOrder in returned vector is rO1O2, theta1, theta2, phi, chi1, chi2 (see Lazaridis and Karplus for definitions)\nCOORDINATES SHOULD ALREADY BE IMAGED\n  \"\"\"\n  dofVec = np.zeros(6)\n\n  rO1O2 = coordO2 - coordO1\n  dofVec[0] = np.linalg.norm(rO1O2)\n  rO1O2 /= dofVec[0]\n  rO2O1 = -rO1O2\n\n  rO1D1 = 0.5*(coordH11 + coordH12) - coordO1\n  rO1D1 /= np.linalg.norm(rO1D1) #Could hard-code to speed up... may do later\n\n  rO2D2 = 0.5*(coordH21 + coordH22) - coordO2\n  rO2D2 /= np.linalg.norm(rO2D2)\n\n  #Need to figure out which H is closer to other oxygen to define rH11H12 according to Lazaridis and Karplus, 1996\n  if np.linalg.norm(coordH11 - coordO2) <= np.linalg.norm(coordH12 - coordO2):\n    rH11H12 = coordH12 - coordH11\n  else:\n    rH11H12 = coordH11 - coordH12\n  rH11H12 /= np.linalg.norm(rH11H12) #Again, could hard code if wanted\n\n  if np.linalg.norm(coordH21 - coordO1) <= np.linalg.norm(coordH22 - coordO1):\n    rH21H22 = coordH22 - coordH21\n  else:\n    rH21H22 = coordH21 - coordH22\n  rH21H22 /= np.linalg.norm(rH21H22)\n\n  cross1 = np.cross(rO1O2, rO1D1)\n  cross1 /= np.linalg.norm(cross1)\n\n  cross2 = np.cross(rO2D2, rO2O1)\n  cross2 /= np.linalg.norm(cross2)\n\n  dofVec[1] = np.arccos(np.dot(rO1D1, rO1O2))\n  dofVec[2] = np.arccos(np.dot(rO2D2, rO2O1))\n  dofVec[3] = np.arccos(np.dot(cross1, cross2))\n  dofVec[4] = np.arccos(np.dot(rH11H12, cross1))\n  dofVec[5] = np.arccos(np.dot(rH21H22, cross2))\n\n  return dofVec\n\n\ndef get3BodyDOFs(coordO1, coordH11, coordH12, coordO2, coordH21, coordH22, coordO3, coordH31, coordH32):\n  \"\"\"Like above function, but gives 6 DOFs pertaining to just the 3-body degrees of freedom\nOrder in returned vector  is rO1O3 (distance), theta3b (three-body angle),\nomega (rotation of 3rd water around O1-O3 vector), then theta3, phi3, and chi3\n(last three defined as for the second water in the 2-body DOFs, but for just the third water)\nCOORDINATES SHOULD ALREADY BE IMAGED\n  \"\"\"\n  dofVec = np.zeros(6)\n\n  rO1O2 = coordO2 - coordO1\n  rO1O2 /= np.linalg.norm(rO1O2)\n  rO2O1 = -rO1O2\n\n  rO1O3 = coordO3 - coordO1\n  dofVec[0] = np.linalg.norm(rO1O3)\n  rO1O3 /= dofVec[0]\n  rO3O1 = -rO1O3\n\n  rO1D1 = 0.5*(coordH11 + coordH12) - coordO1\n  rO1D1 /= np.linalg.norm(rO1D1)\n\n  rO3D3 = 0.5*(coordH31 + coordH32) - coordO3\n  rO3D3 /= np.linalg.norm(rO3D3)\n\n  if np.linalg.norm(coordH31 - coordO1) <= np.linalg.norm(coordH32 - coordO1):\n    rH31H32 = coordH32 - coordH31\n  else:\n    rH31H32 = coordH31 - coordH32\n  rH31H32 /= np.linalg.norm(rH31H32)\n\n  cross12 = np.cross(rO1O2, rO1D1)\n  cross12 /= np.linalg.norm(cross12)\n\n  cross13 = np.cross(rO1O3, rO1D1)\n  cross13 /= np.linalg.norm(cross13)\n\n  cross31 = np.cross(rO3D3, rO3O1)\n  cross31 /= np.linalg.norm(cross31)\n\n  rperp = rO1O3 - np.dot(rO1O2, rO1O3)*rO1O2\n  rperp /= np.linalg.norm(rperp)\n\n  dofVec[1] = np.arccos(np.dot(rO1O2, rO1O3))\n  dofVec[2] = np.arccos(np.dot(rperp, cross12))\n  dofVec[3] = np.arccos(np.dot(rO3D3, rO3O1))\n  dofVec[4] = np.arccos(np.dot(cross13, cross31))\n  dofVec[5] = np.arccos(np.dot(rH31H32, cross31))\n\n  return dofVec\n\n\ndef distanceMetric1B(vec1, vec2, Rsq=(0.09572**2), sintw=(np.sin(104.52*np.pi/180.0)**2)):\n  \"\"\"Computes distance metric appropriate to 1-body DOFs.\n     A direct Euclidean distance is not appropriate since using curvilinear coordinates, \n     so this defines a distance utilizing local curvature that is exact for very small\n     differences. It comes from Taylor-expanding the formula for Euclidean distance in \n     spherical coordinates with respect to both angles to second order.\n  \"\"\"\n  diffs = (vec2 - vec1)**2\n  dist = np.sqrt(diffs[0] + diffs[1] + diffs[2] + Rsq*diffs[3]\n                 + Rsq*np.sin(vec2[3])*np.sin(vec1[3])*diffs[4]\n                 + Rsq*sintw*diffs[5])\n  return dist\n\n\ndef distanceMetric2B(vec1, vec2, Rsq=(0.09572**2), sintw=(np.sin(104.52*np.pi/180.0)**2)):\n  \"\"\"Computes distance metric appropriate to 2-body DOFs.\n     A direct Euclidean distance is not appropriate since using curvilinear coordinates, \n     so this defines a distance utilizing local curvature that is exact for very small\n     differences. It comes from Taylor-expanding the formula for Euclidean distance in \n     spherical coordinates with respect to both angles to second order.\n     Note that this includes 1-body degrees of freedom, so expects 12-dimensional vectors.\n  \"\"\"\n  diffs = (vec2 - vec1)**2\n  dist = np.sqrt(diffs[0] + diffs[1] + diffs[2] + Rsq*diffs[3]\n                 + Rsq*np.sin(vec2[3])*np.sin(vec1[3])*diffs[4]\n                 + Rsq*sintw*diffs[5]\n                 + diffs[6] + Rsq*diffs[7] + Rsq*diffs[8]\n                 + Rsq*np.sin(vec2[8])*np.sin(vec1[8])*diffs[9]\n                 + Rsq*sintw*diffs[10] + Rsq*sintw*diffs[11])\n  return dist\n\n\ndef distanceMetric3B(vec1, vec2, Rsq=(0.09572**2), sintw=(np.sin(104.52*np.pi/180.0)**2)):\n  \"\"\"Computes distance metric appropriate to 3-body DOFs.\n     A direct Euclidean distance is not appropriate since using curvilinear coordinates, \n     so this defines a distance utilizing local curvature that is exact for very small\n     differences. It comes from Taylor-expanding the formula for Euclidean distance in \n     spherical coordinates with respect to both angles to second order.\n     Note that this includes 1- and 2-body degrees of freedom, so expects 18-dimensional vectors.\n  \"\"\"\n  diffs = (vec2 - vec1)**2\n  dist = np.sqrt(diffs[0] + diffs[1] + diffs[2] + Rsq*diffs[3]\n                 + Rsq*np.sin(vec2[3])*np.sin(vec1[3])*diffs[4]\n                 + Rsq*sintw*diffs[5]\n                 + diffs[6] + Rsq*diffs[7] + Rsq*diffs[8]\n                 + Rsq*np.sin(vec2[8])*np.sin(vec1[8])*diffs[9]\n                 + Rsq*sintw*diffs[10] + Rsq*sintw*diffs[11]\n                 + diffs[12] + vec2[12]*vec1[12]*diffs[13]\n                 + vec2[12]*vec1[12]*np.sin(vec2[13])*np.sin(vec1[13])*diffs[14]\n                 + Rsq*diffs[15]\n                 + Rsq*np.sin(vec2[15])*np.sin(vec1[15])*diffs[16]\n                 + Rsq*sintw*diffs[17])\n  return dist\n\n", "meta": {"hexsha": "7e0e24717ebd3426596a08735d739279019f3726", "size": 36462, "ext": "py", "lang": "Python", "max_stars_repo_path": "libraries/water_properties.py", "max_stars_repo_name": "JIMonroe/Surface_Affinities_Optimization", "max_stars_repo_head_hexsha": "94853571c690b099362431aac32d26611134a009", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libraries/water_properties.py", "max_issues_repo_name": "JIMonroe/Surface_Affinities_Optimization", "max_issues_repo_head_hexsha": "94853571c690b099362431aac32d26611134a009", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/water_properties.py", "max_forks_repo_name": "JIMonroe/Surface_Affinities_Optimization", "max_forks_repo_head_hexsha": "94853571c690b099362431aac32d26611134a009", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-07T11:52:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-07T11:52:27.000Z", "avg_line_length": 42.3976744186, "max_line_length": 199, "alphanum_fraction": 0.6938730733, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 10635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.19449786372939842}}
{"text": "import networkx as nx\nfrom networkx.algorithms import isomorphism\nimport math\nimport re\n\nORIG_PPI = [[\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 234) ('type_1' 'type_1') ('type_1' 234) (197 234) (234 197)]\", 844],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 478) ('type_1' 'type_1') ('type_1' 478) (197 234) (197 478) (234 197) (478 197)]\", 73],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 234) ('type_1' 'type_1') ('type_1' 234) (197 234) (234 197) (234 338) (338 234)]\", 53],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 234) ('type_1' 'type_1') ('type_1' 234) (197 234) (234 197) (234 738) (234 800) (738 234) (800 234)]\", 25],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 328) ('type_1' 'type_1') ('type_1' 328) (197 478) (478 197) (478 479) (328 479) (479 328) (479 478)]\", 4],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 314) ('type_1' 'type_1') ('type_1' 314) (114 314) (314 114) (314 331) (314 1120) (294 331) (331 294) (331 314)]\", 11],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 314) ('type_1' 'type_1') ('type_1' 314) (114 314) (314 114) (314 1120)]\", 14],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 275) ('type_1' 'type_1') ('type_1' 275) (275 334) (275 375) (275 589) (275 1069) (334 275) (375 275) (589 275) (1069 275)]\", 21],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 314) ('type_1' 'type_1') ('type_1' 314) (314 1120)]\", 60],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 558) ('type_1' 'type_1') ('type_1' 558) (558 559) (558 571) (558 654) (558 1328) (558 1329) (559 558) (571 558) (654 558) (1328 558) (1329 558)]\", 36],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 239) ('type_1' 'type_1') ('type_1' 239) (239 1056) (239 1107) (239 1331) (1056 239)]\", 12],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 43) ('type_1' 'type_1') ('type_1' 43) (42 43)]\", 7],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 1059) ('type_0' 925) ('type_1' 'type_1') ('type_1' 1059) ('type_1' 925) (925 1185) (1185 925) (1185 1059) (1059 1185)]\", 12],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 1440) ('type_0' 749) ('type_0' 1551) ('type_1' 'type_1') ('type_1' 1440) ('type_1' 749) ('type_1' 1551) (749 750) (750 749) (750 1440) (750 1551) (1440 750) (1551 750)]\", 4],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 1) ('type_0' 5) ('type_1' 'type_1') ('type_1' 1) ('type_1' 5) (1 12) (1 58) (1 188) (12 1) (12 5) (58 1) (58 5) (58 609) (188 1) (188 5) (5 12) (5 58) (5 188) (5 609) (609 5) (609 58)]\", 1]]\n\nCL_PPI =   [[\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 215) ('type_1' 'type_1') ('type_1' 215) (215 807)]\", 682],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 215) ('type_1' 'type_1') ('type_1' 215) (215 437) (215 807)]\", 15],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 602) ('type_1' 'type_1') ('type_1' 602) (215 807) (602 215)]\", 13],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 215) ('type_1' 'type_1') ('type_1' 215) (1064 215)]\", 488],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 770) ('type_1' 'type_1') ('type_1' 76) (76 770)]\", 392],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 64) ('type_1' 'type_1') ('type_1' 64) (5 64) (64 5)]\", 56],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 30) ('type_1' 'type_1') ('type_1' 30) (30 503) (503 30) (777 30)]\", 1],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 49) ('type_1' 'type_1') ('type_1' 9) (9 49) (49 9)]\", 12],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 10) ('type_1' 'type_1') ('type_1' 10) ('type_1' 6) (6 10) (10 6)]\", 2],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 9) ('type_0' 10) ('type_1' 'type_1') ('type_1' 9) ('type_1' 10) (9 10)]\", 2],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 10) ('type_0' 50) ('type_1' 'type_1') ('type_1' 50) (10 50) (50 10)]\", 4],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 20) ('type_0' 244) ('type_1' 'type_1') ('type_1' 33) ('type_1' 6) (3 6) (3 8) (3 33) (3 244) (6 8) (6 20) (8 20) (8 33) (8 244) (33 3) (33 6) (33 20) (244 3) (244 8) (244 20) (244 33) (20 8)]\", 1]]\n\nER_PPI =   [[\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 1480) ('type_1' 'type_1') ('type_1' 1281) (1281 1480)]\", 1303],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 1643) ('type_1' 'type_1') ('type_1' 1643) (1643 1281)]\", 127],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 1437) ('type_1' 'type_1') ('type_1' 1437) (1004 1437)]\", 155],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 581) ('type_1' 'type_1') ('type_1' 736) (581 736)]\", 102],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 650) ('type_1' 'type_1') ('type_1' 537) (537 650) (650 537)]\", 2],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 650) ('type_1' 'type_1') ('type_1' 650) (537 650) (650 537)]\", 6],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 32) ('type_1' 'type_1') ('type_1' 170) (4 32) (4 252) (170 4) (170 32) (252 4) (252 170)]\", 1],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 17) ('type_0' 74) ('type_1' 'type_1') ('type_1' 8) ('type_1' 13) (1 8) (1 13) (1 17) (3 1) (3 74) (8 3) (8 17) (13 1) (13 3) (17 74) (74 3)]\", 1]]\n\nORIG_BLOGS = [[\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 896) ('type_1' 'type_1') ('type_1' 446) (896 446)]\", 323],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 896) ('type_1' 'type_1') ('type_1' 446) (896 446) (913 446)]\", 6],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 515) ('type_1' 'type_1') ('type_1' 515) (515 446)]\", 127],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 772) ('type_1' 'type_1') ('type_1' 772) (446 772)]\", 226],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 652) ('type_1' 'type_1') ('type_1' 446) (446 652) (652 446)]\", 88],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 1068) ('type_1' 'type_1') ('type_1' 163) (92 163) (1066 163) (1068 163)]\", 3],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 887) ('type_1' 'type_1') ('type_1' 887) (885 887) (887 885)]\", 155],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 987) ('type_1' 'type_1') ('type_1' 871) (871 987)]\", 99],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 193) ('type_0' 265) ('type_1' 'type_1') ('type_1' 265) (193 265) (265 193)]\", 39],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 193) ('type_1' 'type_1') ('type_1' 193) (193 383) (193 679) (193 680)]\", 8],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 209) ('type_1' 'type_1') ('type_1' 209) ('type_1' 210) (209 210)]\", 14],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 4) ('type_0' 293) ('type_1' 'type_1') ('type_1' 4) (293 4)]\", 21],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 4) ('type_1' 'type_1') ('type_1' 4) (405 4) (657 4)]\", 9],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 135) ('type_1' 'type_1') ('type_1' 317) ('type_1' 135) (135 317) (317 135)]\", 13],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 106) ('type_0' 44) ('type_1' 'type_1') ('type_1' 106) ('type_1' 44) (44 106) (106 44)]\", 11],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 107) ('type_0' 44) ('type_1' 'type_1') ('type_1' 107) (107 44)]\", 16],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 512) ('type_1' 'type_1') ('type_1' 512) ('type_1' 511) (511 512)]\", 12],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 426) ('type_0' 427) ('type_1' 'type_1') ('type_1' 426) ('type_1' 427) (426 427)]\", 9],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 64) ('type_0' 42) ('type_0' 4) ('type_1' 'type_1') ('type_1' 64) ('type_1' 2) (2 4) (2 42) (4 42) (4 64) (42 2) (42 4) (42 64) (64 2) (64 4) (64 42)]\", 1],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 47) ('type_0' 7) ('type_1' 'type_1') ('type_1' 3) ('type_1' 47) (1 3) (1 7) (1 47) (3 1) (3 7) (3 47) (7 1) (7 3) (47 7)]\", 1]]\n\n\nCL_BLOGS = [[\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 208) ('type_1' 'type_1') ('type_1' 208) (208 257)]\", 191],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 208) ('type_1' 'type_1') ('type_1' 208) (208 257) (776 208)]\", 7],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 208) ('type_1' 'type_1') ('type_1' 514) (514 208)]\", 237],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 520) ('type_1' 'type_1') ('type_1' 208) (520 208)]\", 321],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 208) ('type_1' 'type_1') ('type_1' 208) (776 208)]\", 345],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 114) ('type_1' 'type_1') ('type_1' 114) ('type_1' 1155) (114 1155)]\", 5],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 128) ('type_1' 'type_1') ('type_1' 70) (70 128) (128 70)]\", 50],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 274) ('type_1' 'type_1') ('type_1' 274) (45 274) (274 45)]\", 26],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 14) ('type_1' 'type_1') ('type_1' 68) ('type_1' 14) (14 68) (68 14)]\", 7],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 29) ('type_0' 14) ('type_1' 'type_1') ('type_1' 14) (14 29) (29 14)]\", 10],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 29) ('type_0' 46) ('type_1' 'type_1') ('type_1' 29) (29 46)]\", 6],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 29) ('type_0' 14) ('type_1' 'type_1') ('type_1' 29) ('type_1' 14) (14 29) (29 14)]\", 4],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 17) ('type_0' 19) ('type_1' 'type_1') ('type_1' 17) ('type_1' 19) (19 17)]\", 4],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 1) ('type_0' 12) ('type_0' 5) ('type_1' 'type_1') ('type_1' 1) ('type_1' 5) (1 12) (1 26) (12 1) (12 5) (12 26) (26 1) (26 12) (5 12)]\", 1]]\n\nER_BLOGS = [[\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 877) ('type_1' 'type_1') ('type_1' 1121) (877 1121)]\", 54],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 1075) ('type_1' 'type_1') ('type_1' 877) (877 1075)]\", 1032],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 1109) ('type_1' 'type_1') ('type_1' 1109) (877 1109)]\", 48],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 1152) ('type_1' 'type_1') ('type_1' 1152) (1152 1117)]\", 18],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 141) ('type_1' 'type_1') ('type_1' 141) (141 1080) (1080 141)]\", 4],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 406) ('type_1' 'type_1') ('type_1' 540) (406 540) (540 406)]\", 57],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_0' 73) ('type_0' 6) ('type_1' 'type_1') ('type_1' 73) (73 6)]\", 5],\\\n            [\"[('type_0' 'type_0') ('type_0' 'type_1') ('type_1' 'type_1') (1 7) (1 23) (5 1) (5 7) (7 23) (10 1) (10 8) (23 1) (23 7) (23 8) (23 10) (8 5) (8 10)]\", 1]]\n\ndef graph_from_string(the_string):\n    pieces = re.split('\\[\\(| |\\) \\(|\\)\\]', the_string)\n    pieces = pieces[1:(len(pieces)-1)]\n    nodes = set()\n    for piece in pieces:\n        nodes.add(piece)\n    G = nx.DiGraph()\n    for node in nodes:\n        G.add_node(node)\n    idx = 0\n    while idx < len(pieces):\n        G.add_edge(pieces[idx], pieces[idx + 1])\n        idx += 2\n    return G\n\ndef make_graph_list(the_list):\n    return [[graph_from_string(x[0]), x[1]] for x in the_list]\n\ndef merge_graph_lists(list_a, list_b, list_c):\n    main_list = [[x[0], x[1], 0, 0] for x in list_a]\n    for graph_and_count_b in list_b:\n        found_match = False\n        for i in range(0, len(main_list)):\n            gm = isomorphism.DiGraphMatcher(graph_and_count_b[0], main_list[i][0])\n            if gm.is_isomorphic():\n                main_list[i][2] = graph_and_count_b[1]\n                found_match = True\n                break\n        if not found_match:\n            main_list.append([graph_and_count_b[0], 0, graph_and_count_b[1], 0])\n\n    for graph_and_count_c in list_c:\n        found_match = False\n        for main_gc in main_list:\n            gm = isomorphism.DiGraphMatcher(graph_and_count_c[0], main_gc[0])\n            if gm.is_isomorphic():\n                main_gc[3] = graph_and_count_c[1]\n                found_match = True\n                break\n        if not found_match:\n            main_list.append([graph_and_count_c[0], 0, 0, graph_and_count_c[1]])\n    return main_list\n\ndef merged_probabilities(merged_lists):\n    sum_a = 0.0\n    sum_b = 0.0\n    sum_c = 0.0\n    for list_element in merged_lists:\n        sum_a += list_element[1] + 1.0\n        sum_b += list_element[2] + 1.0\n        sum_c += list_element[3] + 1.0\n    return [[x[0], (x[1] + 1.0) / sum_a, (x[2] + 1.0) / sum_b, (x[3] + 1.0) / sum_c] for x in merged_lists]\n\ndef ratios(prob_list, idx_1, idx_2):\n    ratio_list = [[x[0], x[idx_1] / x[idx_2] if x[idx_1] > x[idx_2] else -1.0 * x[idx_2] / x[idx_1]] for x in prob_list]\n    ratio_list.sort(key=(lambda x: -1.0 * abs(x[1])))\n    return ratio_list\n\ndef kl_contributions(prob_list, idx_1, idx_2):\n    contributions = [[x[0], -1.0 * x[idx_1] * math.log(x[idx_2] / x[idx_1])] for x in prob_list]\n    contributions.sort(key=(lambda x: -1.0 * x[1]))\n    return contributions\n\ndef KL_divergence(kl_contributions):\n    kl = 0.0\n    for item in kl_contributions:\n        kl += item[1]\n    return kl\n\ndef display_kl_contributions(some_kl, title):\n    print(title)\n    for i in range(0, min(len(some_kl), 3)):\n        edges = list(some_kl[i][0].edges())\n        edges.sort()\n        print(\"%s %s\" % (edges, some_kl[i][1]))\n\norig_ppi_list = make_graph_list(ORIG_PPI)\ncl_ppi_list = make_graph_list(CL_PPI)\ner_ppi_list = make_graph_list(ER_PPI)\nmerged_list = merge_graph_lists(orig_ppi_list, cl_ppi_list, er_ppi_list)\nprobs_list = merged_probabilities(merged_list)\norig_cl_kl_contributions = kl_contributions(probs_list, 1, 2)\norig_er_kl_contributions = kl_contributions(probs_list, 1, 3)\ndisplay_kl_contributions(orig_cl_kl_contributions, \"PPI: Original vs CL\")\ndisplay_kl_contributions(orig_er_kl_contributions, \"PPI: Original vs ER\")\norig_cl_kl = KL_divergence(orig_cl_kl_contributions)\nprint(\"orig_cl_kl: %s\" % orig_cl_kl)\norig_er_kl = KL_divergence(orig_er_kl_contributions)\nprint(\"orig_er_kl: %s\" % orig_er_kl)\n\norig_blogs_list = make_graph_list(ORIG_BLOGS)\ncl_blogs_list = make_graph_list(CL_BLOGS)\ner_blogs_list = make_graph_list(ER_BLOGS)\nmerged_list = merge_graph_lists(orig_blogs_list, cl_blogs_list, er_blogs_list)\nprobs_list = merged_probabilities(merged_list)\norig_cl_kl_contributions = kl_contributions(probs_list, 1, 2)\norig_er_kl_contributions = kl_contributions(probs_list, 1, 3)\ndisplay_kl_contributions(orig_cl_kl_contributions, \"Blogs: Original vs CL\")\ndisplay_kl_contributions(orig_er_kl_contributions, \"Blogs: Original vs ER\")\norig_cl_kl = KL_divergence(orig_cl_kl_contributions)\nprint(\"orig_cl_kl: %s\" % orig_cl_kl)\norig_er_kl = KL_divergence(orig_er_kl_contributions)\nprint(\"orig_er_kl: %s\" % orig_er_kl)\n", "meta": {"hexsha": "7e63f0c03aba591391f3d69672f24b0feb4403e7", "size": 15555, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/bugge/difference_in_extracted_rules.py", "max_stars_repo_name": "Abdumaleek/infinity-mirror", "max_stars_repo_head_hexsha": "b493c5602d9e4bcf374b748e9b80e7c85be54a88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-03-13T02:54:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T02:33:12.000Z", "max_issues_repo_path": "src/bugge/difference_in_extracted_rules.py", "max_issues_repo_name": "Abdumaleek/infinity-mirror", "max_issues_repo_head_hexsha": "b493c5602d9e4bcf374b748e9b80e7c85be54a88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-11-10T19:47:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T01:24:59.000Z", "max_forks_repo_path": "src/bugge/difference_in_extracted_rules.py", "max_forks_repo_name": "Abdumaleek/infinity-mirror", "max_forks_repo_head_hexsha": "b493c5602d9e4bcf374b748e9b80e7c85be54a88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-24T21:54:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-24T21:54:44.000Z", "avg_line_length": 80.5958549223, "max_line_length": 262, "alphanum_fraction": 0.5540340726, "include": true, "reason": "import networkx,from networkx", "num_tokens": 7041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.3140505321516081, "lm_q1q2_score": 0.19432832450225898}}
{"text": "from os.path import join, basename\nfrom os import environ\nfrom sys import stderr\n\nimport numpy as np\nfrom SetCoverPy import setcover, mathutils\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nfrom astropy.io import fits\n\nfrom redmonster.datamgr.io2 import read_ndArch\nfrom _linelist import __linelist__\n\n# Dict of plates and corresponding MJDS\nplates = {8123:56931}\n\n# version of redmonster reductions to use\nrmver = 'v1_1_0'\n\n# chi2 threshold to use in set cover distance matrix\nmindist = 0.48\n\nrmdir = join( environ['REDMONSTER_SPECTRO_REDUX'], environ['RUN2D'],\n             '%s' % rmver)\n\n# loop over all plates\nfor plate in plates.keys():\n    # list of fibers classified as galaxy with zwarning=0\n    fibers = []\n    zs = []\n    # open redmonster file\n    hdu = fits.open( join( rmdir, '%s' % plate, 'redmonster-%s-%s.fits'\n                          % (plate, plates[plate]) ) )\n    # open data file\n    idlpath = join( environ['BOSS_SPECTRO_REDUX'], environ['RUN2D'],\n                   '%s' % plate, 'spPlate-%s-%s.fits' % (plate, plates[plate]) )\n    hduidl = fits.open(idlpath)\n\n    # create wavelength solution\n    wave = 10**(hduidl[0].header['COEFF0'] + hduidl[0].header['COEFF1'] *\n                np.arange(hduidl[0].header['NAXIS1']))\n\n    # loop over fibers and keep those classed as gal with zwarn=0\n    for i,fiber in enumerate(hdu[1].data.FIBERID):\n        if fiber != 516:\n            if hdu[1].data.ZWARNING[i] == 0:\n                if hdu[1].data.CLASS1[i] == 'ssp_galaxy_glob':\n                    fibers.append(fiber)\n                    zs.append(hdu[1].data.Z1[i])\n\n    # nfibers x nfibers matrix to hold distances\n    distmat = np.zeros( (len(fibers), len(fibers)) )\n\n    # binary distance matrix\n    #binmat = np.zeros( distmat.shape )\n\n\n    # calculate distance from each fiber to every other fiber\n    for i in range(len(fibers)):\n        # set data and such for this fiber\n        fiber1 = fibers[i]\n        data1 = hduidl[0].data[fiber1]\n        sigma1 = hduidl[1].data[fiber1]\n        wave1 = wave / (1+zs[i])\n        # normalize slow spectrum to mean value between 4500 and 4700 A, and\n        # scale errors accordingly\n        high1 = np.abs(wave1-4700).argmin()\n        low1 = np.abs(wave1-4500).argmin()\n        mean1 = np.mean(data1[low1:high1+1])\n        data1 /= mean1\n        sigma1 *= mean1**2\n        # loop over upper half of matrix and fill bottom half with symmetry\n        for j in range(i, len(fibers)):\n            fiber2 = fibers[j]\n            stderr.write(\"\\rTotal: %s i: %s j:%s\" % (len(fibers), (i+1), (j+1)) )\n            # convert to rest-frame wavelength\n            wave2 = wave / (1+zs[j])\n            # crop spectra to only overlapping region\n            if wave1[0] < wave2[0]:\n                low_bound = np.abs(wave1 - wave2[0]).argmin()\n                data1_2 = data1[low_bound:]\n                sigma1_2 = sigma1[low_bound:]\n                wave1_2 = wave1[low_bound:]\n                high_bound = np.abs(wave2 - wave1[-1]).argmin()\n                data2 = hduidl[0].data[fiber2][:high_bound+1]\n                sigma2 = hduidl[1].data[fiber2][:high_bound+1]\n                wave2 = wave2[:high_bound+1]\n            elif wave1[0] > wave2[0]:\n                low_bound = np.abs(wave2 - wave1[0]).argmin()\n                data2 = hduidl[0].data[fiber2][low_bound:]\n                sigma2 = hduidl[1].data[fiber2][low_bound:]\n                wave2 = wave2[low_bound:]\n                high_bound = np.abs(wave1 - wave2[-1]).argmin()\n                data1_2 = data1[:high_bound+1]\n                sigma1_2 = sigma1[:high_bound+1]\n                wave1_2 = wave1[:high_bound+1]\n            else: # same redshift (most likely same spectrum)\n                data1_2 = data1\n                sigma1_2 = sigma1\n                data2 = hduidl[0].data[fiber2]\n                sigma2 = hduidl[1].data[fiber2]\n            # normalize fast spectrum to mean value between 4500 and 4700 A, and\n            # scale errors accordingly\n            low2 = np.abs(wave2-4500).argmin()\n            high2 = np.abs(wave2-4700).argmin()\n            mean2 = np.mean(data2[low2:high2+1])\n            data2 /= mean2\n            sigma2 *= mean2**2\n            # convert inverse variance to sigma squared and add in quadrature\n            variance = (1/sigma1_2) + (1/sigma2)\n            # calculate reduced chi2 as distance\n            distmat[i][j] = distmat[j][i] = np.sum( (data1_2 - data2)**2 /\\\n                                                   variance ) / data1.shape[0]\n            #if distmat[i][j] < mindist:\n                #binmat[i][j] = 1\n    print \" \"\n    binmat = distmat < mindist\n    cost = np.ones(binmat.shape[0])\n    #cost = 1 / hdu\n\n    g = setcover.SetCover(binmat, cost)\n    #g.greedy()\n    g.SolveSCP()\n\n    # Get the archetype indices\n    iarchetype = np.nonzero(g.s)[0]\n    print \"Number of archetypes: %s\\n\" % iarchetype.shape\n\n    # How many are covered by each archetype?\n    n_rep = np.sum(binmat[:, iarchetype], axis=0)\n    for i,arch in enumerate(iarchetype):\n        if n_rep[i] == 1:\n            print \"Archetype #%s represents %s spectra.\" % (arch, n_rep[i])\n        elif n_rep[i] > 1:\n            print \"Archetype #%s represents %i spectra.\" % (arch, n_rep[i])\n\n    # Get instances represented by each archetype\n    stacks = [] # place to store stacks\n    all_counts = []\n    restwave = 10**(2.6990 + np.arange(20000) * 0.0001)\n    redshifts = []\n    fibnums = []\n    archfibs = []\n    j = -1\n    for i in xrange(iarchetype.size):\n        if n_rep[i] > 1:\n            j += 1\n            redshifts.append([])\n            fibnums.append([])\n            this_stack = np.zeros(20000)\n            counts = np.zeros(20000)\n            # binary vector of which spectra are represented by this archetype\n            itmp = binmat[:, iarchetype[i]]\n            # list of fiber numbers represented\n            fibrep = np.asarray(fibers)[itmp]\n            for fiber in fibrep:\n                fiberind = np.where((np.asarray(fibers)-fiber) == 0)[0][0]\n                fiberlen = hduidl[0].data[fiber-1].shape[-1]\n                this_wave = wave / (1 + zs[fiberind])\n                wave0 = np.abs(restwave - this_wave[0]).argmin()\n                this_stack[wave0:wave0+fiberlen] += hduidl[0].data[fiber-1]\n                counts[wave0:wave0+fiberlen] += 1\n                redshifts[j].append(zs[fiberind])\n                fibnums[j].append(fiber)\n            this_stack /= counts\n            stacks.append(this_stack)\n            all_counts.append(counts)\n            archfibs.append( fibers[iarchetype[i]] )\n\n    # Crop stacks to regions with at least XXX% of max counts\n    mastercounts = []\n    masterstacks = []\n    masterwave = []\n    for i,counts in enumerate(all_counts):\n        w = (counts >= (0.3*np.max(counts)))\n        mastercounts.append(counts[w])\n        masterstacks.append(stacks[i][w])\n        masterwave.append(restwave[w])\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "64cdc1e1c3da9da19f6a56b11a1b0e838261cb5b", "size": 6936, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/elg_templates/setcoverstacks.py", "max_stars_repo_name": "timahutchinson/elg-templates", "max_stars_repo_head_hexsha": "5cd2ec6e5b6a05ddb4b79cf64a8e4c79d31a0c72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/elg_templates/setcoverstacks.py", "max_issues_repo_name": "timahutchinson/elg-templates", "max_issues_repo_head_hexsha": "5cd2ec6e5b6a05ddb4b79cf64a8e4c79d31a0c72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/elg_templates/setcoverstacks.py", "max_forks_repo_name": "timahutchinson/elg-templates", "max_forks_repo_head_hexsha": "5cd2ec6e5b6a05ddb4b79cf64a8e4c79d31a0c72", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5692307692, "max_line_length": 81, "alphanum_fraction": 0.5625720877, "include": true, "reason": "import numpy,from astropy", "num_tokens": 1944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.682573734412324, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.19424410592221192}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 21 12:33:36 2019\n\nCombined new simulation using missing data and finite mutation model\n\n@author: marianne aspbury\n\"\"\"\n\nimport msprime\nimport tsinfer\nimport numpy as np\nfrom IPython.display import display\nfrom IPython.display import SVG\n\nimport pickle\nimport random # to pick from list of poss roots of subtree\nfrom IndividualClass import Individual # might say unused, but not true, needed to read pickled file\nfrom truncate_ts_samples import truncate_ts_samples as truncate_ts_samples\n\n### import the trees ###\nfile_loc = 'C:\\\\Users\\\\mazmysta\\OneDrive - Nexus365\\\\BDI_proj\\\\HIV_Transmission_Networks_WillProbert\\\\19-08-08-first_example_network\\\\'\n\nwith open(file_loc + 'pickled_data_all.pickle', 'rb') as f:\n    total_tree = pickle.load(f)\n\n#proof it works\nprint('Pickle loaded, 1st root num kids: {}'.format(total_tree['-1_-1'].total_children_num))\n\n# Saving list of people with desired num kids beneath\nsamples_poss = []\ndesired_overall_children = 5 ## Seemingly my max is 30 with 10 samples, 100 pop size and 1000 length genome.\n\nfor key in total_tree:\n    if total_tree[key].total_children_num == desired_overall_children:\n        samples_poss.append(key)\n\nprint(len(samples_poss))\n# 8 for kids = 100\n\n#pick only one random sample\nrandom.seed(4) # repeatable choice(s) - sequence same\nstart = random.choice(samples_poss)\n#start='58582_0'\nprint(start)\n\nprint(total_tree[start].infected_others)\n\ndef preorder_traversal(u):\n    all_nodes = []\n    stack = [u]\n    while len(stack) > 0:\n        v = stack.pop()\n        if total_tree[v].direct_children_num > 0: #Returns True if the specified node is not a leaf\n            stack.extend(total_tree[v].infected_others)\n        all_nodes.append(v)\n    return all_nodes\n\nlist_of_root_and_kids = preorder_traversal(start)\n\n#print(preorder_traversal(start), len(preorder_traversal(start)))\n\n#print(list(set(list_of_root_and_kids) - set(start)))\n\n# all info required for mini-transmission chain\n#for item in list_of_root_and_kids:\n#    print(item, total_tree[item].infected_others,\n#          total_tree[item].time_infected_others,\n#          total_tree[item].age_birth,\n#          total_tree[item].age_death)\n\n\n### msprime assimilation\n# Find total num of generations (days) to model over\ntimes_loop = []\n\nfor item in list_of_root_and_kids:\n    #float to take as number not string, and access list element with [0]\n    times_loop.append(float(total_tree[item].time_infected_by[0]))\n\n#since floats, can do maths\ntotal_time = (max(times_loop)-min(times_loop))*365\n\n#Furthest back in time is the smallest date (lowest year), do everything in diffs\ngens_list = []\nfor item in list_of_root_and_kids:\n    #float to take as number not string, and access list element with [0]\n    diff_calc = 365*(max(times_loop)-float(total_tree[item].time_infected_by[0]))\n    gens_list.append(diff_calc + 100) # add 100 so most recent infection is '100 gens (days) in past'\n\n#    print(float(total_tree[item].time_infected_by[0]))\n\n# info on dates so far\nfor i in range(len(gens_list)):\n    print((list_of_root_and_kids)[i],\n          #times_loop[i],\n          gens_list[i])\n\n######## msprime variable populations setup #########\n\n## source population\nPopSource = msprime.PopulationConfiguration(initial_size = 1e8, growth_rate = 0)\n\n## number of populations in present time of model, not including source pop...\nfinal_num_pops = len(list_of_root_and_kids)\n\n## sample_sizes for each population and effective pop sizes\nsample_size = 20\ninfection_size = 1\nstable_pop_size = 100\n# ## subpops based on infected people, all subpops that want to exist at end of sim (present time) need stated here\npop_list = [PopSource]\n\n#Setting up the end, so all pops exist and at stable pop size, no death in simulation time\nfor pop in range(final_num_pops):\n#    print(pop)\n    pop_list.append(\n        msprime.PopulationConfiguration(sample_size = sample_size, initial_size = stable_pop_size, growth_rate = 0)\n                  )\n\n# no migration between sources accross time, only infection events,\n    # so migration matrix is zeros\nM = np.zeros((final_num_pops+1,final_num_pops+1))\n\n# Now get transmission events from the data. Use index as population number, but +1 since have fake source pop at index 0.\n#for i in list_of_root_and_kids:\n#    print(list_of_root_and_kids.index(i) + 1)\n\n####--- new version with sub-pops ---####\n\n## a simple model where independent sub-pop is infection derived from source pop\n# if infected by true pop, need to state when diverged from past pop if that's the case\n# Oddly source is the destination, i.e. direction of migration is dest -> source if forwards in time view.\n# backwards in time means that destination is destination (but it's where the migration has come from)\n\ntransfers_list = []\nfor entry in range(len(pop_list)):\n#    print(entry)\n    if entry == 0: # ignore 0 since this is the source pop\n        pass\n\n    elif entry == 1: # 1 is root so needs own bit\n        entry_ID = list_of_root_and_kids[entry-1]\n#        print(entry, entry_ID)\n        dest_index = 0 #infected from source\n        transfer_time = gens_list[entry-1] # time infected still stored.\n#        print(transfer_time)\n        transfers_list.append(msprime.MassMigration(time = transfer_time, source = entry, dest = dest_index, proportion = 1))\n\n    elif entry > 1: # 1 is root so needs own bit\n        # get the index of the infected_by population\n        # index of current population is its index in pop_list (index in list_of_root... + 1)\n        entry_ID = list_of_root_and_kids[entry-1]\n#        print(entry, entry_ID)\n        dest_ID = total_tree[entry_ID].infected_by[0]\n        dest_index = list_of_root_and_kids.index(dest_ID) + 1\n#        print(dest_index, dest_ID)\n        transfer_time = gens_list[entry-1]\n#        print(transfer_time)\n        transfers_list.append(msprime.MassMigration(time = transfer_time, source = entry, dest = dest_index, proportion = 1))\n\n#check as expected\nprint(transfers_list)\n\n# compare\n#for i in range(len(gens_list)):\n#    print((list_of_root_and_kids)[i],\n#          #times_loop[i],\n#          gens_list[i])\n\n## now have set of populations, the transfers for pops (infection events)\n    # still need the bottlenecks (pop growth & stabilisation)\n    # then can order(sort) the complete demography list by time and simulate\n\n## Bottlenecks: add population growth in so infections from source pop are only ~ 1-5 virions, which then balloons to e.g. ~1000\n\n#### Bottleneck list initiation and creation\nPop_bottleneck_ie_growth_list = []\nfor entry in range(len(pop_list)):\n    if entry > 0: # ignore 0 since this is the source pop. Only need infection time for this so root doesn't need own case\n\n        transfer_time = gens_list[entry-1]\n\n        #infection size setting\n        pop_entry_bottleneck_start = msprime.PopulationParametersChange(\n                time = transfer_time, initial_size=infection_size, growth_rate=0, population = entry) #i.e. for epochs inf-> 100*entry, this is growth rate\n\n        #growth after infection setting - trial that 20 gens in future (less time back) gives appropriate growth for these params of pop_size = 100, rate = 0.25\n        pop_entry_bottleneck_end = msprime.PopulationParametersChange(\n                time = transfer_time-20, growth_rate = 0.23, initial_size=stable_pop_size, population = entry) #i.e. for epochs inf-> 100*entry, this is growth rate\n\n        #save to list for manip outside loop\n        Pop_bottleneck_ie_growth_list.extend((pop_entry_bottleneck_start, pop_entry_bottleneck_end))\n\n# put all events together then sort them\nevents = Pop_bottleneck_ie_growth_list + transfers_list\nevents_sorted = sorted(events, key=lambda x: x.time, reverse=False)\n\n#check\n#for event in events_sorted:\n#    print(event.__dict__) # just for easier digestion of output\n\n\nmy_history = msprime.DemographyDebugger(\n    population_configurations=pop_list, migration_matrix = M,\n    demographic_events = events_sorted)\n\n#my_history.print_history()\n\n\n\n### plot how pop changes ##\n#\n#time_steps= range(1,int(np.max(gens_list))+100,2)\n## print('pop0:', my_history.population_size_trajectory(time_steps)[:,0])\n## print('pop1:', my_history.population_size_trajectory(time_steps)[:,1])\n## print('time:', np.array(time_steps))\n## plot the populations, matplotlib understands array of y's as multiple y's so don't need to call individually\n#\n#import matplotlib.pyplot as plt\n#plt.figure(1)\n##plt.plot(time_steps, my_history.population_size_trajectory(time_steps)[:,0])\n##plt.plot(time_steps, my_history.population_size_trajectory(time_steps)[:,1])\n##plt.rc('axes', prop_cycle=(cycler(color=['r', 'g', 'b', 'y'])))\n#fig, ax = plt.subplots(figsize=(15, 6), dpi=80)\n#ax.set_prop_cycle(color=[\"green\", \"blue\", \"red\", \"orange\", \"grey\", \"cyan\", \"black\"][1:])\n#plt.plot(time_steps, my_history.population_size_trajectory(time_steps)[:,1:], '--', alpha=0.5) # this will plot each y (pop size var.) separately\n#plt.xlim(np.max(time_steps),0) # switch the order of time so present (0) is RHS and past is LHS (max time step)\n##plt.xlim(np.max(time_steps),1) # switch the order of time so present (0) is RHS and past is LHS (max time step)\n##plt.ylim(np.log(0.5), np.log(150))\n##plt.axvline(x=100, color='k', linestyle='-', alpha=0.5) # add a vertical line for migration step\n##plt.legend(('1','2','3','4','5','6'),loc='best')\n##box = ax.get_position()\n##ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])\n## Put a legend to the right of the current axis\n##plt.yscale(\"log\")\n##plt.xscale(\"log\")\n#ax.legend(('1: ' + list_of_root_and_kids[0],\n#           '2: ' + list_of_root_and_kids[1],\n#           '3: ' + list_of_root_and_kids[2],\n#           '4: ' + list_of_root_and_kids[3],\n#           '5: ' + list_of_root_and_kids[4],\n#           '6: ' + list_of_root_and_kids[5]),\n# loc='center left', bbox_to_anchor=(1.02, 0.5))\n#plt.show()\n## time = 0 is present, larger time is past\n\n\n\n\n############ Simulation time ############\n\n#file_loc = 'C:\\\\Users\\\\mazmysta\\\\OneDrive - Nexus365\\\\BDI_proj\\\\scripts\\\\PopulationsHIV\\\\'\n#\n##how to save\n#with open(file_loc + 'pickled_pop_list.pickle', 'wb') as f:\n#    pickle.dump(pop_list, f)\n#\n#with open(file_loc + 'pickled_events_sorted.pickle', 'wb') as f:\n#    pickle.dump(events_sorted, f)\n#\n#with open(file_loc + 'pickled_M.pickle', 'wb') as f:\n#    pickle.dump(M, f)\n#\n## loading example\n#with open(file_loc + 'pickled_pop_list.pickle', 'rb') as f:\n#    pop_list = pickle.load(f)\n#\n## simulate this extended simple model\nts2 = msprime.simulate(population_configurations=pop_list, migration_matrix = M,\n                       demographic_events = events_sorted,\n                       length = 1000,\n                       random_seed = 17, recombination_rate = 0.7e-4,\n                       mutation_rate=2e-5, end_time=60000)\n\n\n## simulate this extended simple model\n#ts2 = msprime.simulate(population_configurations=pop_list, migration_matrix = M,\n#                       demographic_events = events_sorted,\n#                       length = 1000,\n#                       random_seed = 17, recombination_rate = 0.7e-4)\n\n# 5 pops\ncolour_map = {0:\"grey\", 1:\"blue\", 2:\"red\", 3:\"orange\", 4:\"green\", 5:\"cyan\", 6:\"black\"}\nnode_colours = {u.id: colour_map[u.population] for u in ts2.nodes()}\n\n\nX = 1\ni = 0\nfor tree in ts2.trees():\n    if i < X:\n        display(SVG(tree.draw(node_colours = node_colours,\n                              height=800, width = 1000,\n                              format='SVG',\n                              tree_height_scale='log_time')))\n        print(\"Tree {} covers [{:.2f}, {:.2f}); TMRCA = {:.4f}\".format(\n            tree.index, *tree.interval, tree.time(tree.roots[0])))\n        print(tree.branch_length(46))\n    else:\n        break\n    i+=1\n\n#### truncation part\n\n# Having run\n# ReadingTransmissionNetworkCSV_OverallChildrenCalcs_save.py\n# have a ts2 = simulated data\n\n\n# ts2 from subsetting to msprime, length 100, picking just one population below\n# simplification and subsetting\n\n#ts3 = ts.simplify(samples=[3,8,0,4,7,2,6,5,1,9]\n#)\n\ntruncated_ts3 = truncate_ts_samples(ts2, average_span=200, random_seed=123)\n\n#print(truncated_ts3)\n#<tskit.trees.TreeSequence object at 0x000001ED52232710>\n\n#truncated_ts3.tables\n#Out[34]: <tskit.tables.TableCollection at 0x1ed4f6c1860>\n\n#truncated_ts3.tables.nodes\n#Out[35]: <tskit.tables.NodeTable at 0x1ed52232908>\n\n#print(truncated_ts3.tables)\n#prints the tables - long\nX = 10\ni = 0\nfor tree in truncated_ts3.trees():\n    if i < X:\n        display(SVG(tree.draw(height=800, width = 1000,\n                              format='SVG',\n                              tree_height_scale='log_time')))\n        print(\"Tree {} covers [{:.2f}, {:.2f}); TMRCA = {:.4f}\".format(\n            tree.index, *tree.interval, tree.time(tree.roots[0])))\n        print(tree.branch_length(46))\n    else:\n        break\n    i+=1\n\ntruncated_ts3.dump(file_loc + 'truncated_simulation_tree.trees')\n# ts infer\n\nsd = tsinfer.SampleData.from_tree_sequence(truncated_ts3, use_times=False)\n\nts_inferred = tsinfer.infer(sd, simplify=False)\n\nts_inferred = ts_inferred.simplify(filter_sites=False, keep_unary=True)\n\nts_inferred\nts_inferred.dump(file_loc + 'inferred_tree.trees')\n#Out[43]: <tskit.trees.TreeSequence at 0x1ed55ca9710>\n\nX = 10\ni = 0\nfor tree in ts_inferred.trees():\n    if i < X:\n        display(SVG(tree.draw(height=400, width=600,\n                              tree_height_scale='rank')))\n        print(\"Tree {} covers [{:.2f}, {:.2f}); TMRCA = {:.4f}\".format(\n            tree.index, *tree.interval, tree.time(tree.roots[0])))\n#        print(tree.branch_length(46))\n    else:\n        break\n    i+=1\n\nprint(ts_inferred.genotype_matrix())\nprint(truncated_ts3.genotype_matrix())\n\nhaps = []\nfor i in ts2.haplotypes():\n    haps.append(i)\n\nsequence_IDs = []\nfor i in range(len(haps)):\n    sequence_IDs.append(f'sample_{ts2.samples()[i]}_pop_{ts2.node(i).population}')\n\n#fasta printing\n#for i in range(len(haps)):\n#    print(f'>{sequence_IDs[i]}\\n{haps[i]}')\n\n## write and save fasta file\nwith open(file_loc + 'test_fasta_file.txt', 'w') as f:\n    for i in range(len(haps)):\n        f.write(f'>{sequence_IDs[i]}\\n{haps[i]}\\n')\n\n", "meta": {"hexsha": "944640c6cf919e30f2778b3be6d9811f57e90e00", "size": 14155, "ext": "py", "lang": "Python", "max_stars_repo_path": "Older_progress/FullSimFiniteMutMissingData-notyetfinite-fastaoutput.py", "max_stars_repo_name": "marianne-aspbury/HIVsimulation", "max_stars_repo_head_hexsha": "56e110f84474010f1866e299da4c41acd567e0b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Older_progress/FullSimFiniteMutMissingData-notyetfinite-fastaoutput.py", "max_issues_repo_name": "marianne-aspbury/HIVsimulation", "max_issues_repo_head_hexsha": "56e110f84474010f1866e299da4c41acd567e0b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Older_progress/FullSimFiniteMutMissingData-notyetfinite-fastaoutput.py", "max_forks_repo_name": "marianne-aspbury/HIVsimulation", "max_forks_repo_head_hexsha": "56e110f84474010f1866e299da4c41acd567e0b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-09T12:15:35.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-09T12:15:35.000Z", "avg_line_length": 36.3881748072, "max_line_length": 164, "alphanum_fraction": 0.6899328859, "include": true, "reason": "import numpy", "num_tokens": 3735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19423646169227826}}
{"text": "\"\"\"\ninvariants:\n- distinct prototype prefixes have distinct node in the prefix graph, regardless of wildcard matches\n- if a node has two or more distinct child nodes, all the node's links are tame\n\nimplies that any node with wild links has exactly one child node,\nand all rules descending from node match without wildcards through the child prefix\n\n- any node with two or more distinct child nodes must be tame (no wild links)\n- all descendent rules of a tamed node must have wildcard disabled at that position\n- except for root, wild nodes never have None links, and all links point to same child node\n- any two distinct prototype prefixes must have distinct node paths in the prefix tree\n\nif you're adding a new rule, nobody matched prototype (early tame None leaf)\nif you're disabling a wildcard, someone matched it (wild node with non-None links)\n\nshould never take some wild links and then fail unmatched if a different non-wild link would have matched\nall prototypes should have persistent trails with no wildcard links\nthat way, disabling wildcards for one rule does not break another rule\n\n\"\"\"\nimport numpy as np\n\nclass PrefixTreeNode:\n    def __init__(self, bound, value=None, added=0):\n        self.bound = bound # maximum number of outgoing links\n        self.value = value # value of incoming link\n        self.added = added # integer timestamp when node is added\n        self.tamed = np.iinfo(int).max # integer timestamp when node is tamed\n        self.rule = None # for leaf nodes, the associated rule\n        self.links = {} # links[v] = child node for value v\n    \n    def is_wild(self):\n        child_ids = set(map(id, self.links.values()))\n        return len(self.links) == self.bound and len(child_ids) == 1\n\n    def tame(self, tamed=0):\n        self.links = {value:node for value, node in self.links.items() if node.value == value}\n        self.tamed = tamed\n\n    def __str__(self, prefix=\"\"):\n        tamed = \"\" if self.tamed == np.iinfo(int).max else str(self.tamed)\n        if self.rule != None: return \"%sr%d [%d~>%s]\\n\" % (prefix, self.rule, self.added, tamed)\n        if self.is_wild():\n            result = prefix + \"* [%d~>%s]\\n\" % (self.added, tamed)\n            result += self.links[0].__str__(prefix+\" \")\n        else:\n            result = \"\"\n            p = \" \" if len(self.links) == 1 else \"|\"\n            for v in range(self.bound):\n                if v in self.links:\n                    result += prefix + \"%d [%d~>%s]\\n\" % (v, self.added, tamed)\n                    result += self.links[v].__str__(prefix+p)\n        return result\n\n    def rules(self):\n        if self.rule != None: return [self.rule]\n        if self.is_wild(): return self.links[0].rules()\n        result = []\n        for v in range(self.bound):\n            if v in self.links:\n                result += self.links[v].rules()\n        return result\n\n    def copy(self):\n        node = PrefixTreeNode(self.bound, self.value, self.added)\n        node.tamed = self.tamed\n        node.rule = self.rule\n        if self.is_wild():\n            child_node = self.links[0].copy()\n            node.links = {v: child_node for v in range(self.bound)}\n        else:\n            node.links = {v: child_node.copy() for v, child_node in self.links.items()}\n        return node\n\n    def rewind(self, i):\n\n        # Rewind current node and links\n        self.links = {v: node for v, node in self.links.items() if node.added <= i}\n        if self.tamed > i and len(self.links) > 0: # should imply len == 1\n            _, node = self.links.popitem()\n            for v in range(self.bound): self.links[v] = node\n            self.tamed = np.iinfo(int).max\n\n        # Recurse on children\n        if self.is_wild():\n            self.links[0].rewind(i)\n        else:\n            for child_node in self.links.values(): child_node.rewind(i)\n\nclass MacroDatabase:\n    def __init__(self, domain, max_rules):\n\n        self.domain = domain\n        self.max_rules = max_rules\n        self.num_rules = 0\n        self.bounds = (7,) * domain.state_size()\n        self.root = PrefixTreeNode(self.bounds[0])\n\n        self.prototypes = np.empty((max_rules, domain.state_size()), dtype=int)\n        self.wildcards = np.empty((max_rules, domain.state_size()), dtype=bool)\n        self.costs = np.empty(max_rules, dtype=int)\n        self.macros = [None] * max_rules\n        self.permutations = np.empty((max_rules, domain.state_size()), dtype=int)\n\n        self.added = np.ones(max_rules, dtype=int) * np.iinfo(int).max\n        self.tamed = np.ones((max_rules, domain.state_size()), dtype=int) * np.iinfo(int).max\n\n    def query(self, state):\n        node = self.root\n        for k,v in enumerate(state):\n            if v not in node.links: return None\n            node = node.links[v]\n        return node.rule\n\n    def tame(self, node, w, tamed=0):\n        node.tame(tamed)\n        for r in node.rules():\n            self.wildcards[r,w] = False\n            self.tamed[r,w] = tamed\n\n    def add_rule(self, prototype, macro, cost, added=0):\n        r = self.num_rules\n        self.prototypes[r] = prototype\n        self.costs[r] = cost\n        self.macros[r] = macro\n        self.permutations[r] = self.domain.execute(macro, np.arange(self.domain.state_size()))\n        self.added[r] = added\n\n        node = self.root\n        for k, value in enumerate(prototype):\n            child_bound = self.bounds[k+1] if k+1 < len(self.bounds) else 0\n            if len(node.links) == 0:\n                child_node = PrefixTreeNode(child_bound, value, added)\n                node.links = {v: child_node for v in range(node.bound)}\n            elif value not in node.links:\n                node.links[value] = PrefixTreeNode(child_bound, value, added)\n            elif node.links[value].value != value:\n                self.tame(node, k, tamed=added)\n                node.links[value] = PrefixTreeNode(child_bound, value, added)\n            self.wildcards[r,k] = node.is_wild()\n            node = node.links[value]\n        node.rule = r\n\n        self.num_rules += 1\n\n    def disable(self, r, w, tamed=0):\n        node = self.root\n        for k in range(w): node = node.links[self.prototypes[r,k]]\n        if node.is_wild(): self.tame(node, w, tamed)\n\n    def apply_rule(self, r, state):\n        return state[self.permutations[r]].copy()\n\n    def copy(self):\n        db = MacroDatabase(self.domain, self.max_rules)\n        db.num_rules = self.num_rules\n        db.root = self.root.copy()\n\n        db.prototypes = self.prototypes.copy()\n        db.wildcards = self.wildcards.copy()\n        db.costs = self.costs.copy()\n        db.macros = list(self.macros)\n        db.permutations = self.permutations.copy()\n\n        db.added = self.added.copy()\n        db.tamed = self.tamed.copy()\n        \n        return db\n\n    def rewind(self, i):\n        # keep all edits up to and including i\n        self.root.rewind(i)\n        if (self.added > i).any():\n            self.num_rules = np.argmax(self.added > i)\n        self.added[self.num_rules:] = np.iinfo(int).max\n        self.wildcards = self.tamed > i\n        self.tamed[self.wildcards] = np.iinfo(int).max\n        return self\n\n    def shrink_wrap(self):\n        # reduce max_rules to num_rules and shrink arrays in-place for lighter footprint\n        self.max_rules = self.num_rules\n\n        self.prototypes = self.prototypes[:self.num_rules].copy()\n        self.wildcards = self.wildcards[:self.num_rules].copy()\n        self.costs = self.costs[:self.num_rules].copy()\n        self.macros = tuple(self.macros[:self.num_rules])\n        self.permutations = self.permutations[:self.num_rules].copy()\n\n        self.added = self.added[:self.num_rules].copy()\n        self.tamed = self.tamed[:self.num_rules].copy()\n        \n        return self\n\nif __name__ == \"__main__\":\n\n    from cube import CubeDomain\n    domain = CubeDomain(2)\n    solved = domain.solved_state()\n\n    md = MacroDatabase(domain, max_rules=10)\n    \n    result = md.query(solved)\n    assert result == None\n    print(md.root)\n\n    md.add_rule(solved, (), 0)\n    assert md.query(solved) == 0\n    assert (md.wildcards[:md.num_rules] == True).all()\n    print(\"-\"*24)\n    print(md.root)\n\n    # disable all wildcards for solved\n    for w in range(len(solved)): md.disable(0, w)\n\n    assert md.query(solved) == 0\n    assert (md.wildcards[:md.num_rules] == False).all()\n    print(\"-\"*24)\n    print(md.root)\n\n    state = domain.perform((0,1,1), solved)\n    md.add_rule(state, ((0,1,3),), 1)\n\n    print(\"-\"*24)\n    print(md.root)\n    assert md.query(solved) == 0\n    assert md.query(state) == 1\n    assert not (md.wildcards[:md.num_rules] == True).all()\n    assert not (md.wildcards[:md.num_rules] == False).all()\n\n    state2 = domain.perform((0,1,2), solved)\n    md.add_rule(state2, ((0,1,2),), 1)\n    print(\"-\"*24)\n    print(md.root)\n\n    state3 = domain.perform((1,1,1), solved)\n    md.add_rule(state3, ((1,1,3),), 1)\n    print(\"-\"*24)\n    print(md.root)\n    \n    # simulate adding rules and check queries match after\n    md = MacroDatabase(domain, max_rules=10)\n    md.add_rule(solved, (), 0)\n    for w in range(len(solved)): md.disable(0, w)\n\n    rng = np.random.default_rng()\n    for r in range(1, 10):\n        state = domain.random_state(20, rng)\n        md.add_rule(state, (), 0)\n\n    for r in range(md.num_rules):\n        state = md.prototypes[r]\n        result = md.query(state)\n        brutes = np.flatnonzero(((md.prototypes == state) | md.wildcards).all(axis=1))\n        print(r, result, brutes)\n        if result not in brutes:\n            print(\"predisable\")\n            print(\"-\"*24)\n            print(md.root)\n        assert result in brutes\n\n    for r in range(md.num_rules):    \n        for w in range(len(state)):            \n            if rng.uniform() < 0.1:\n                md.disable(r, w)\n\n    for r in range(md.num_rules):\n        state = md.prototypes[r]\n        result = md.query(state)\n        brutes = np.flatnonzero(((md.prototypes == state) | md.wildcards).all(axis=1))\n        print(r, result, brutes)\n        if result not in brutes:\n            print(\"postdisable\")\n            print(\"-\"*24)\n            print(md.root)\n        assert result in brutes\n\n    print(\"-\"*24)\n    print(md.root)\n\n    # test rewinding\n    md = MacroDatabase(domain, max_rules=10)\n    md.add_rule(prototype=solved, macro=(), cost=0, added=0)\n    for w in range(len(solved)): md.disable(0, w, tamed=0)\n\n    rng = np.random.default_rng()\n    for r in range(1, 5):\n        state = domain.random_state(20, rng)\n        md.add_rule(prototype=state, macro=(), cost=0, added=r)\n        md.disable(rng.integers(r, endpoint=True), rng.integers(len(state)), tamed=r)\n\n    for r in range(md.num_rules):\n        state = md.prototypes[r]\n        result = md.query(state)\n        brutes = np.flatnonzero(((md.prototypes == state) | md.wildcards).all(axis=1))\n        if result not in brutes:\n            print(\"prerewind\")\n            print(\"-\"*24)\n            print(md.root)\n        assert result in brutes\n\n    print(\"prerewind\")\n    print(\"-\"*24)\n    print(md.root)\n\n    md.rewind(3)\n    md.rewind(2)\n    for r in range(md.num_rules):\n        state = md.prototypes[r]\n        result = md.query(state)\n        brutes = np.flatnonzero(((md.prototypes == state) | md.wildcards).all(axis=1))\n        if result not in brutes:\n            print(\"postrewind\")\n            print(\"-\"*24)\n            print(md.root)\n        assert result in brutes\n\n    print(\"postrewind\")\n    print(\"-\"*24)\n    print(md.root)\n\n    # test copy\n    md = MacroDatabase(domain, max_rules=10)\n    md.add_rule(prototype=solved, macro=(), cost=0, added=0)\n    for w in range(len(solved)): md.disable(0, w, tamed=0)\n\n    rng = np.random.default_rng()\n    num_rules = 4\n    states = []\n    for r in range(1, num_rules-1):\n        state = domain.random_state(20, rng)\n        md.add_rule(prototype=state, macro=(), cost=0, added=r)\n        md.disable(rng.integers(r, endpoint=True), rng.integers(len(state)), tamed=r)\n        states.append(state)\n\n    md2 = md.copy()\n    state = domain.random_state(20, rng)\n    md2.add_rule(prototype=state, macro=(), cost=0, added=num_rules-1)\n    for r in range(md.num_rules):\n        for w in range(len(state)):\n            md.disable(r, w, tamed=num_rules)\n\n    print(\"orig\")\n    print(\"-\"*24)\n    print(md.root)\n    print(\"copy\")\n    print(\"-\"*24)\n    print(md2.root)\n\n    assert md.num_rules + 1 == md2.num_rules\n    assert md.wildcards[:md.num_rules].sum() == 0\n    assert md2.wildcards[:md.num_rules].sum() > 0\n    assert md.query(state) == None\n    assert md2.query(state) != None\n    for state in states:\n        assert md.query(state) != None\n        assert md2.query(state) != None\n\n    # test macro permutations\n    md = MacroDatabase(domain, max_rules=1)\n    state = domain.perform((0, 1, 1), solved)\n    actions = ((1, 1, 1), (2, 1, 1))\n    md.add_rule(prototype=solved, macro=actions, cost=0, added=0)\n    for w in range(len(solved)):\n        if state[w] == solved[w]: md.disable(0, w, tamed=0)\n\n    print(\"one rule perm\")\n    print(\"-\"*24)\n    print(md.root)\n\n    r = md.query(state)\n    assert r == 0\n    new_state = md.apply_rule(r, state)\n    for action in actions: state = domain.perform(action, state)\n    assert (state == new_state).all()\n\n    # compare timing of prefix and brute queries, and array-based prefix\n    rule_count = 5000\n\n    md = MacroDatabase(domain, max_rules=rule_count)\n    md.add_rule(solved, (), 0)\n    for w in range(len(solved)): md.disable(0, w)\n\n    rng = np.random.default_rng()\n    for r in range(1, rule_count):\n        state = domain.random_state(20, rng)\n        md.add_rule(state, (), 0)\n\n    print(\"counting nodes...\")\n    def count_nodes(node):\n        if node.is_wild():\n            return 1 + count_nodes(node.links[0])\n        else:\n            count = 0\n            for v, child in node.links.items():\n                count += count_nodes(child)\n            return 1 + count\n    print(f\"{count_nodes(md.root)} total nodes\")\n\n    # make prefix tree array query\n    class ArrayPrefixTree:\n        def __init__(self, root):\n            self.links = -np.ones((rule_count * (domain.state_size()+1), 7), dtype=int)\n            self.rules = -np.ones(rule_count * (domain.state_size()+1), dtype=int)\n            self.num_nodes = 0\n            self.link(root)\n            # very marginal benefit after tuplifying, otherwise marginally worse\n            self.links = tuple(tuple(links) for links in self.links)\n            self.rules = tuple(self.rules)\n        def add(self, node):\n            n = self.num_nodes\n            if node.rule != None: self.rules[n] = node.rule\n            self.num_nodes += 1\n            return n\n        def link(self, node):\n            n = self.add(node)\n            if node.is_wild():\n                c = self.link(node.links[0])\n                self.links[n,:] = c\n            else:\n                for v, child in node.links.items():\n                    c = self.link(node.links[v])\n                    self.links[n,v] = c\n            return n\n        def query(self, state):\n            n = 0\n            for k,v in enumerate(state):\n                n = self.links[n][v]\n                if n == -1: return None\n            return self.rules[n]\n\n    apt = ArrayPrefixTree(md.root)\n\n    from time import perf_counter\n    prefix_time = 0\n    brute_time = 0\n    array_time = 0\n\n    for state in md.prototypes:\n\n        assert md.query(state) == apt.query(state)\n\n        start = perf_counter()\n        result = md.query(state)\n        prefix_time += perf_counter() - start\n\n        start = perf_counter()\n        result = np.flatnonzero(((state == md.prototypes) | md.wildcards).all(axis=1))\n        brute_time += perf_counter() - start\n\n        start = perf_counter()\n        result = apt.query(state)\n        array_time += perf_counter() - start\n\n    print(\"prototype queries:\")\n    print(\"prefix time\", prefix_time)\n    print(\"brute time\", brute_time)\n    print(\"array time\", array_time)\n\n    prefix_time = 0\n    brute_time = 0\n    array_time = 0\n\n    for s in range(rule_count):\n        state = domain.random_state(20, rng)\n\n        assert md.query(state) == apt.query(state)\n\n        start = perf_counter()\n        result = md.query(state)\n        prefix_time += perf_counter() - start\n\n        start = perf_counter()\n        result = np.flatnonzero(((state == md.prototypes) | md.wildcards).all(axis=1))\n        brute_time += perf_counter() - start\n\n        start = perf_counter()\n        result = apt.query(state)\n        array_time += perf_counter() - start\n\n    print(\"random state queries:\")\n    print(\"prefix time\", prefix_time)\n    print(\"brute time\", brute_time)\n    print(\"array time\", array_time)\n\n", "meta": {"hexsha": "c221f130bf1ec1eb8f88672f25583c164e6c503d", "size": 16643, "ext": "py", "lang": "Python", "max_stars_repo_path": "macro_database.py", "max_stars_repo_name": "garrettkatz/cubbies", "max_stars_repo_head_hexsha": "81850ffb9f0dcfed75a070f3344d931c6c74d96b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "macro_database.py", "max_issues_repo_name": "garrettkatz/cubbies", "max_issues_repo_head_hexsha": "81850ffb9f0dcfed75a070f3344d931c6c74d96b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "macro_database.py", "max_forks_repo_name": "garrettkatz/cubbies", "max_forks_repo_head_hexsha": "81850ffb9f0dcfed75a070f3344d931c6c74d96b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1745379877, "max_line_length": 105, "alphanum_fraction": 0.5920206694, "include": true, "reason": "import numpy", "num_tokens": 4237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.19423645444339122}}
{"text": "\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'''\nQSDsan: Quantitative Sustainable Design for sanitation and resource recovery systems\nCopyright (C) 2020, Quantitative Sustainable Design Group\n\nThis module is developed by:\n    Lewis Rowles <stetsonsc@gmail.com>\n    \n\nThis module is under the University of Illinois/NCSA Open Source License.\nPlease refer to https://github.com/QSD-Group/QSDsan/blob/master/LICENSE.txt\nfor license details.\n'''\n# %%\n\n\nimport numpy as np\nfrom qsdsan import SanUnit, Construction\nfrom qsdsan.utils.loading import load_data, data_path\nimport os\n__all__ = ('IonExchangeNH3',)\n\n#path to csv with all the inputs\n#data_path = '/Users/lewisrowles/opt/anaconda3/lib/python3.8/site-packages/exposan/biogenic_refinery/_ion_exchange_NH3.csv'\n#data_path = os.path.abspath(os.path.dirname('_ion_exchange_NH3.csv'))\ndata_path += 'sanunit_data/_ion_exchange_NH3.tsv'\n# data_path += 'sanunit_data/_carbonizer_base.csv'\n\n### \nclass IonExchangeNH3(SanUnit):\n    '''\n    Ion Exchange for N recovery from liquid stream. Concentrated NH3 is recovered.\n\n    \n    Reference documents\n    -------------------\n    N/A\n    \n    Parameters\n    ----------\n    ins : WasteStream (liquid), FreshResin, H2SO4\n        \n    outs : WasteStream, SpentResin, ConcentratedNH3\n        \n\n        \n    References\n    ----------\n    .. Lohman et al., Advancing Sustainable Sanitation and Agriculture \n    through Investments in Human-Derived Nutrient Systems. \n    Environ. Sci. Technol. 2020, 54, (15), 9217-9227.\n    https://dx.doi.org/10.1021/acs.est.0c03764\n    \n    .. Tarpeh et al., Evaluating ion exchange for nitrogen recovery from \n    source-separated urine in Nairobi, Kenya. Development Engineering. 2018, \n    3, 188–195.\n    https://doi.org/10.1016/j.deveng.2018.07.002\n    \n    '''\n    \n\n    def __init__(self, ID='', ins=None, outs=(), **kwargs):\n        \n        SanUnit.__init__(self, ID, ins, outs)\n\n# load data from csv each name will be self.name    \n        data = load_data(path=data_path)\n        for para in data.index:\n            value = float(data.loc[para]['expected'])\n            setattr(self, para, value)\n        del data\n        \n        for attr, value in kwargs.items():\n            setattr(self, attr, value)\n\n\n\n\n        \n# define the number of influent and effluent streams    \n    _N_ins = 3\n    _N_outs = 3\n\n# in _run: define influent and effluent streams and treatment processes \n    def _run(self):\n        waste, resin_in, H2SO4 = self.ins\n        treated, resin_out, conc_NH3 = self.outs\n        treated.copy_like(self.ins[0])\n        resin_in.phase = 'l'\n        resin_out.phase = 'l'\n        conc_NH3.phase = 'l'\n        \n        \n        #!!! During storage most N as urea goes to NH3, should that \n        # conversion be added or just use total N here? \n        N_recovered = waste.imass['NH3'] * (self.N_rec_2) # kg N / hr\n        treated.imass['NH3'] =  waste.imass['NH3'] - N_recovered # kg N / hr\n        conc_NH3.imass['NH3'] = N_recovered # kg N / hr\n        \n        # following Terpeh et al. 2018 estimates for regenerating resin\n        # assume volume of eluent = volume of urine\n        # !!! cost associated with this influent stream neg compared to cost of resin and acid?\n        #conc_NH3.F_vol = waste.F_vol\n        # 0.1 M H2SO4 (0.65%) used to regenerate resin\n        \n        # !!! need to add SO4 as a component? \n        # conc_NH3.imass['SO4'] = 0.1 * 98 * conc_NH3.F_vol # kg SO4 / hr\n        \n        # !!! add resin and H2SO4 as influent streams and spent resin as effluent\n        resin_demand_influent = (waste.TN / self.resin_lifetime / self.ad_density / 14) # kg resin / m3 treated\n        resin_demand_time = resin_demand_influent * waste.F_vol # kg resin / hr\n        resin_cost_day = resin_demand_time * 24 * self.cost_resin # $ resin / d\n        resin_in.imass['Polystyrene'] = resin_demand_time\n        resin_out.imass['Polystyrene'] = resin_demand_time\n\n        acid_demand_influent = waste.TN * self.vol_H2SO4 / self.ad_density / 14 # L acid / L treated\n        acid_demand_time = acid_demand_influent * waste.F_vol * 1000 * 1.83 # kg acid / hr\n        acid_cost_day = acid_demand_time * 24 / 1000 * self.cost_H2SO4 # $ acid / d\n        H2SO4.imass['H2SO4'] = acid_demand_time\n\n        # set values needed for _design and _cost as attributes\n        self.volume_treated = waste.F_vol * 1000 * 24 # L liq / d \n        \n\n        \n     \n    #_design will include all the construction or captial impacts  \n    def _design(self):\n        design = self.design_results\n        # defining the quantities of materials/items\n        # note that these items to be to be in the _impacts_items.xlsx\n        \n        self.quantity_columns = np.ceil(self.volume_treated / \n                                        self.column_daily_loading_rate) # number of 0.4 m columns\n        design['PVC'] = PVC_quant = (self.column_length * self.quantity_columns \n                                     * self.pvc_mass) # kg PVC\n        Tubing_quant = (self.tubing_length * self.quantity_columns \n                                           * self.tubing_mass) # kg PE\n        Tank_quant = (self.quantity_columns * self.tank_mass / 3) # number of tanks with one tank for three columns\n        design['PE'] = PE_quant = Tubing_quant + Tank_quant\n\n        \n        self.construction = (\n            Construction(item='PVC', quantity = PVC_quant, quantity_unit = 'kg'),\n            Construction(item='PE', quantity = PE_quant, quantity_unit = 'kg'),\n            )\n        self.add_construction()\n        \n    \n    #_cost based on amount of steel and stainless plus individual components\n    def _cost(self):\n        #purchase_costs is used for capital costs\n        #can use quantities from above (e.g., self.design_results['StainlessSteel'])\n        #can be broken down as specific items within purchase_costs or grouped (e.g., 'Misc. parts')\n        self.purchase_costs['PVC'] = (self.cost_PVC_column * self.column_length \n                                      * self.quantity_columns)\n        self.purchase_costs['Tubing'] = (self.cost_tubing * self.tubing_length \n                                         * self.quantity_columns)\n        self.purchase_costs['Tank'] = (self.quantity_columns * self.tank_cost / 3) # one tank for three columns\n        self._BM = dict.fromkeys(self.purchase_costs.keys(), 1)\n        \n        #certain parts need to be replaced based on an expected lifefime\n        #the cost of these parts is considered along with the cost of the labor to replace them\n        ix_replacement_parts_annual_cost = 0 # USD/yr only accounts for time running\n        \n        ix_annual_maintenance = 0 #USD/yr only accounts for time running\n        \n        self.add_OPEX =  (ix_replacement_parts_annual_cost + ix_annual_maintenance) / (365 * 24) # USD/hr (all items are per hour)\n        \n        # costs associated with full time opperators can be added in the TEA as staff\n      \n\n\n\n\n       \n", "meta": {"hexsha": "0453ad382d979062b8c8e69eaba0db75446b718a", "size": 6955, "ext": "py", "lang": "Python", "max_stars_repo_path": "qsdsan/sanunits/_ion_exchange_NH3.py", "max_stars_repo_name": "stetsonrowles/QSDsan", "max_stars_repo_head_hexsha": "a74949fcf9e6ff91e9160a75bedaf6fab2191efb", "max_stars_repo_licenses": ["NCSA", "CNRI-Python", "FTL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "qsdsan/sanunits/_ion_exchange_NH3.py", "max_issues_repo_name": "stetsonrowles/QSDsan", "max_issues_repo_head_hexsha": "a74949fcf9e6ff91e9160a75bedaf6fab2191efb", "max_issues_repo_licenses": ["NCSA", "CNRI-Python", "FTL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qsdsan/sanunits/_ion_exchange_NH3.py", "max_forks_repo_name": "stetsonrowles/QSDsan", "max_forks_repo_head_hexsha": "a74949fcf9e6ff91e9160a75bedaf6fab2191efb", "max_forks_repo_licenses": ["NCSA", "CNRI-Python", "FTL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6388888889, "max_line_length": 130, "alphanum_fraction": 0.6342199856, "include": true, "reason": "import numpy", "num_tokens": 1752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.19423645444339122}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCloud HR experiments\n\nCreated on Fri Dec  9 11:22:51 2016\n\n@author: maxwell\n\"\"\"\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport copy\n\n\nimport atmosphere as a\nfrom parm import ChemParm, LWParm, SWParm\nfrom solver import SolverFactory,HR\nfrom misc.humidity import manaberh\nimport misc.solargeometry as solar\n\n\n# %% set up\nst = time.clock()\ntimestr = \"Elapsed Time: {:4f}s\"\n\nplev =np.logspace(-2,np.log10(1013), 601)\nlat = 10\ndecl = 21.11\nrhlabel= ''\nholdrh=True\nrh = np.ones(len(plev))*0.5\nholdtsfc=True\ncpdair=1004.0\n\ntimestep=0.25\nradmodel='fu'\ngridstagger=False\nmaxsteps=300\ntol = .011\n\ncldprofiles=[ None,\n             'atmosphere/profiles/hr/yang/cf_allclouds/annual_mean_20Nto20S_cf.txt',\n             'atmosphere/profiles/hr/yang/cf_withoutcirrus/annual_mean_20Nto20S_cf_withoutcirrus.txt',\n              None,\n             'atmosphere/profiles/hr/yang/cf_allclouds/annual_mean_wp_cf.txt',\n             'atmosphere/profiles/hr/yang/cf_withoutcirrus/annual_mean_wp_cf_withoutcirrus.txt'\n              ]\no3profiles=['atmosphere/profiles/ozone/yang/annual_ozone_20Nto20S.dat',\n            'atmosphere/profiles/ozone/yang/annual_ozone_20Nto20S.dat',\n            'atmosphere/profiles/ozone/yang/annual_ozone_20Nto20S.dat',\n            'atmosphere/profiles/ozone/yang/annual_ozone_fiji.dat',\n            'atmosphere/profiles/ozone/yang/annual_ozone_fiji.dat',\n            'atmosphere/profiles/ozone/yang/annual_ozone_fiji.dat'\n             ]\n\nanames=['Trop', 'Trop CF', 'Trop CF (no Ci)', 'WP', 'WP CF', 'WP CF (no Ci)']\ncldconds = dict(zip(anames, cldprofiles))\no3conds = dict(zip(anames, o3profiles))\nts = 300.0\nnsim = len(anames)\natms=dict.fromkeys(anames)\natms_noco2 = dict.fromkeys(anames)\natms_noo3 = dict.fromkeys(anames)\natms_wvonly = dict.fromkeys(anames)\nhr=dict.fromkeys(anames)\nauxhr=dict.fromkeys(anames)\nhr_noco2=dict.fromkeys(anames)\nhr_noo3 = dict.fromkeys(anames)\nhr_wvonly= dict.fromkeys(anames)\nflx = dict.fromkeys(anames)\nflx_noco2 = dict.fromkeys(anames)\nflx_noo3 = dict.fromkeys(anames)\nflx_wvonly = dict.fromkeys(anames)\n\n\nswparm = dict.fromkeys(anames)\n\n\ncparm = ChemParm()\ncparm_noco2=ChemParm(co2ppmv=1.0e-4)\nlwparm = LWParm()\nslv = SolverFactory.create(kind='rce', timestep=timestep, holdtsfc=holdtsfc,\n                           radmodel=radmodel,cpdair=cpdair,tol=tol,\n                           maxsteps=maxsteps)\nradslv = SolverFactory.create(kind='rad',radmodel=radmodel,\n                              cpdair=cpdair)\n\n\n\nst2 = st\nfor name,cond in cldconds.items():\n    print('SOLVING {}'.format(name))\n    prof = 'jtrp'\n    atms[name] = a.Atmosphere.mcclatchy(prof, p=plev, rhlev=rh, holdrh=holdrh,\n                                        gridstagger=gridstagger,tsfc=ts)\n    atms[name].ozone_fromfile(o3conds[name])\n    atms_noco2[name] = copy.deepcopy(atms[name])\n    atms_noo3[name] = copy.deepcopy(atms[name])\n    atms_noo3[name].o3 = np.zeros(len(atms_noo3[name]))\n    atms_wvonly[name] = copy.deepcopy(atms[name])\n    atms_wvonly[name].o3 = np.zeros(len(atms_wvonly[name]))\n\n    mu=solar.mubar(lat,decl)\n    fday=solar.fday(lat,decl)\n    swparm[name] = SWParm(coszen=mu,fday=fday)\n\n    if cond is not None:\n        auxhr[name]=HR.fromfile(atms[name], cond)\n    else:\n        zeros = np.zeros(len(atms[name]))\n        auxhr[name]=HR(zeros, zeros)\n    slv.auxhr=auxhr[name]\n\n    atms[name],flx[name],hr[name] = slv.solve(\n                                        atms[name],cparm,lwparm,swparm[name])\n    atms_noco2[name], flx_noco2[name], hr_noco2[name] = radslv.solve(\n        atms_noco2[name],cparm_noco2, lwparm,swparm[name])\n    atms_noo3[name], flx_noo3[name], hr_noo3[name] = radslv.solve(\n        atms_noo3[name],cparm,lwparm,swparm[name])\n    atms_wvonly[name], flx_wvonly[name], hr_wvonly[name] = radslv.solve(\n        atms_wvonly[name], cparm_noco2, lwparm,swparm[name])\n    ed = time.clock()\n    print(timestr.format(ed-st2))\n    st2 = ed\n\n\nprint('Total time: {}'.format(ed-st))\n\n\n# %% plot temps\n\nplt.figure(1)\nplt.clf()\nyls = (8,1013)\n#ytcks = [10,20,40,60,80,100,200,400,600,800,1000]\nxls = (150,300)\nxtcks = np.linspace(150,300,3)\nplt.suptitle('Temperature (K)')\n\nif(gridstagger):\n    fstag='0'\nelse:\n    fstag='1'\n\nfor i, name in enumerate(anames):\n    ax = plt.subplot(1,nsim,i+1)\n    plt.hold('on')\n    try:\n        plt.semilogy(atms[name].t, atms[name].p)\n        plt.plot(atms[name].tconv, atms[name].pconv, 'ks')\n        plt.plot(atms[name].tcold, atms[name].pcold, 'ko')\n    except ValueError:\n        pass\n    finally:\n        plt.ylim(yls)\n    #    plt.yticks(ytcks)\n        plt.xlim(xls)\n        plt.xticks(xtcks)\n        plt.xlabel(name.upper())\n        ax.invert_yaxis()\n        if (i==0):\n            plt.ylabel('Pressure (hPa)')\n    #        ax.yaxis.set_ticklabels(['{:.0f}'.format(tick) for tick in ytcks])\n        else:\n            ax.yaxis.set_ticklabels([])\nelse:\n    plt.show()\n\nfigname = 'img/rce_{}g{}_cld_{}_eq.png'.format(\n                 radmodel,fstag,rhlabel)\nprint(\"Writing figure: {}\".format(figname))\nplt.savefig(\n    bbox_inches='tight', dpi=300, filename=figname)\n\n# %% plot hr (net)\nplt.figure(2)\nplt.clf()\nyls = (10,1013)\nxls = (-3,2)\nxtcks = np.linspace(xls[0],xls[1],2)\n#ytcks = np.linspace(,1000,10)\nplt.suptitle('HR (K/d)')\n\nfor i, name in enumerate(anames):\n    ax = plt.subplot(1,nsim,i+1)\n    plt.hold('on')\n    iconv = atms[name].iconv\n    icold = atms[name].icold\n    try:\n        plt.semilogy(hr[name].hrir, atms[name].p,color='crimson')\n        plt.semilogy(hr[name].hrsw, atms[name].p,'mediumblue')\n        plt.semilogy(hr[name].hr, atms[name].p,'orange')\n        plt.plot(np.zeros(len(atms[name])), atms[name].p, 'k--')\n        plt.plot(xtcks, np.ones(len(xtcks))*atms[name].pcold, 'k')\n        plt.plot(xtcks, np.ones(len(xtcks))*atms[name].pconv, 'k')\n\n    except ValueError:\n        pass\n    finally:\n        plt.ylim(yls)\n    #    plt.yticks(ytcks)\n        plt.xlim(xls)\n        plt.xticks(xtcks)\n        plt.xlabel(name.upper())\n        ax.invert_yaxis()\n\n        if (i==0):\n            plt.ylabel('Pressure (hPa)')\n    #        ax.yaxis.set_ticklabels(['{:.0f}'.format(tick) for tick in ytcks])\n        else:\n            ax.yaxis.set_ticklabels([])\nelse:\n    plt.show()\n\nfigname = 'img/rce_{}g{}_cld_{}_hr.png'.format(\n                 radmodel,fstag,rhlabel)\nprint(\"Writing figure: {}\".format(figname))\nplt.savefig(\n    bbox_inches='tight', dpi=300, filename=figname)\n\n# %% co2-only hr\nplt.figure(3)\nplt.clf()\nyls = (10,1013)\nxls = (-3,3)\nxtcks = np.linspace(xls[0],xls[1],3)\n#ytcks = np.linspace(100,1000,10)\nplt.suptitle('CO2 IR HR (K/d)')\n\nfor i, name in enumerate(anames):\n    ax = plt.subplot(1,nsim,i+1)\n    plt.hold('on')\n    iconv = atms[name].iconv\n    icold = atms[name].icold\n\n    try:\n        plt.plot(hr[name].hrir - hr_noco2[name].hrir, atms[name].p)\n        plt.plot(np.zeros(len(atms[name])), atms[name].p, 'k--')\n        plt.plot(xtcks, np.ones(len(xtcks))*atms[name].pcold, 'k')\n        plt.plot(xtcks, np.ones(len(xtcks))*atms[name].pconv, 'k')\n\n    except ValueError:\n        pass\n    finally:\n        plt.ylim(yls)\n        plt.xlim(xls)\n        plt.xticks(xtcks)\n        plt.xlabel(name.upper())\n        ax.invert_yaxis()\n        ax.set_yscale('log')\n    #    plt.yticks(ytcks)\n\n        if (i==0):\n            plt.ylabel('Pressure (hPa)')\n    #        ax.yaxis.set_ticklabels(['{:.0f}'.format(tick) for tick in ytcks])\n        else:\n            ax.yaxis.set_ticklabels([])\nelse:\n    plt.show()\n\nfigname = 'img/rce_{}g{}_cld_{}_hrco2.png'.format(\n                 radmodel,fstag,rhlabel)\nprint(\"Writing figure: {}\".format(figname))\nplt.savefig(\n    bbox_inches='tight', dpi=300, filename=figname)\n\n\n\n\n# %% o3-only hr\nplt.figure(4)\nplt.clf()\nyls = (10,1013)\nxls = (-1,2)\nxtcks = np.linspace(xls[0],xls[1],4)\n#ytcks = np.linspace(100,1000,10)\nplt.suptitle(' O3 HR (K/d)')\n\nfor i, name in enumerate(anames):\n    ax = plt.subplot(1,nsim,i+1)\n    plt.hold('on')\n    iconv = atms[name].iconv\n    icold = atms[name].icold\n    try:\n#        plt.plot(hr[name].hrir - hr_noo3[name].hrir, atms[name].p,color='crimson')\n#        plt.plot(hr[name].hrsw - hr_noo3[name].hrsw, atms[name].p,color='mediumblue')\n        plt.plot(hr[name].hr - hr_noo3[name].hr, atms[name].p,'orange')\n        plt.plot(np.zeros(len(atms[name])), atms[name].p, 'k--')\n        plt.plot(xtcks, np.ones(len(xtcks))*atms[name].pcold, 'k')\n        plt.plot(xtcks, np.ones(len(xtcks))*atms[name].pconv, 'k')\n    except ValueError:\n        pass\n    finally:\n        plt.ylim(yls)\n        plt.xlim(xls)\n        plt.xticks(xtcks)\n        plt.xlabel(name.upper())\n        ax.invert_yaxis()\n        ax.set_yscale('log')\n    #    plt.yticks(ytcks)\n\n        if (i==0):\n            plt.ylabel('Pressure (hPa)')\n    #        ax.yaxis.set_ticklabels(['{:.0f}'.format(tick) for tick in ytcks])\n        else:\n            ax.yaxis.set_ticklabels([])\nelse:\n    plt.show()\n\nfigname = 'img/rce_{}g{}_cld_{}_hro3.png'.format(\n                 radmodel,fstag,rhlabel)\nprint(\"Writing figure: {}\".format(figname))\nplt.savefig(\n    bbox_inches='tight', dpi=300, filename=figname)\n\n# %% wv-only hr\nplt.figure(5)\nplt.clf()\nyls = (10, 1013)\nxls = (-2, 2)\nxtcks = np.linspace(-2,2,3)\nplt.suptitle('H2O HR')\n\nfor i, name in enumerate(anames):\n    ax = plt.subplot(1,nsim,i+1)\n    plt.hold('on')\n    iconv = atms[name].iconv\n    icold = atms[name].icold\n    try:\n#        plt.plot(hr[name].hrir - hr_noo3[name].hrir, atms[name].p,color='crimson')\n#        plt.plot(hr[name].hrsw - hr_noo3[name].hrsw, atms[name].p,color='mediumblue')\n        plt.plot(hr_wvonly[name].hr, atms[name].p,'g')\n        plt.plot(np.zeros(len(atms[name])), atms[name].p, 'k--')\n        plt.plot(xtcks, np.ones(len(xtcks))*atms[name].pcold, 'k')\n        plt.plot(xtcks, np.ones(len(xtcks))*atms[name].pconv, 'k')\n    except ValueError:\n        pass\n    finally:\n        plt.ylim(yls)\n        plt.xlim(xls)\n        plt.xticks(xtcks)\n        plt.xlabel(name.upper())\n        ax.invert_yaxis()\n        ax.set_yscale('log')\n    #    plt.yticks(ytcks)\n\n        if (i==0):\n            plt.ylabel('Pressure (hPa)')\n    #        ax.yaxis.set_ticklabels(['{:.0f}'.format(tick) for tick in ytcks])\n        else:\n            ax.yaxis.set_ticklabels([])\nelse:\n    plt.show()\n\nfigname = 'img/rce_{}g{}_cld_{}_hrwv.png'.format(\n                 radmodel,fstag,rhlabel)\nprint(\"Writing figure: {}\".format(figname))\nplt.savefig(\n    bbox_inches='tight', dpi=300, filename=figname)\n\n# %% compare o3 profiles\nplt.figure(6)\nplt.clf()\nxls1 = (0,18)\nxls2 = (-1.6, 0.2)\nyls = (1, 1013)\n\nplt.subplot(1,2,1)\nplt.hold('on')\nplt.plot(atms['Trop'].o3*1e6,atms['Trop'].p, label='All Tropics')\nplt.plot(atms['WP'].o3*1e6, atms['WP'].p, label='WP')\nplt.ylim(yls)\nplt.xlim(xls1)\nax = plt.gca()\nax.set_yscale('log')\nax.invert_yaxis()\nplt.title('O3 Profile')\nplt.ylabel('Pressure (hPa)')\nplt.xlabel('Conc. ($10^{-6}$ g/g)')\nplt.legend(loc='best')\n\nplt.subplot(1,2,2)\nplt.hold('on')\nplt.plot(1e6*(atms['WP'].o3-atms['Trop'].o3), atms['WP'].p)\nplt.plot(np.zeros(len(atms['WP'])), atms['WP'].p, 'k--')\nplt.ylim(yls)\nplt.xlim(xls2)\nax = plt.gca()\nax.set_yscale('log')\nax.invert_yaxis()\nplt.title('$\\Delta$ O3')\nplt.xlabel('Conc. ($10^{-6}$ g/g)')\n\n\n\nfigname = 'img/rce_{}g{}_cld_{}_o3prof.png'.format(\n                 radmodel,fstag,rhlabel)\nprint(\"Writing figure: {}\".format(figname))\nplt.savefig(\n    bbox_inches='tight', dpi=300, filename=figname)\n\n\n\n\n# %% show delta T for clouds\nplt.figure(7)\nplt.clf()\nxls1 = (-10,10)\nxls2 = (-10, 10)\nyls = (40, 400)\n\nplt.subplot(1,2,1)\nplt.hold('on')\nnames = anames[1:3]\nref = anames[0]\nfor name in names:\n    plt.plot(atms[name].t-atms[ref].t,atms[name].p,label=name)\n    plt.plot(atms[name].tconv-atms[ref].t[atms[name].iconv], atms[name].pconv, 'ks')\n    plt.plot(atms[name].tcold-atms[ref].t[atms[name].icold], atms[name].pcold, 'ko')\n    plt.plot(np.zeros(len(atms[name])),atms[name].p, 'k--')\nplt.ylim(yls)\nplt.xlim(xls1)\nax = plt.gca()\nax.set_yscale('log')\nax.invert_yaxis()\nplt.title('')\nplt.ylabel('Pressure (hPa)')\nplt.xlabel('Temperature (K)')\nplt.legend(loc='best')\n\nplt.subplot(1,2,2)\nplt.hold('on')\nnames = anames[4:6]\nref = anames[3]\nfor name in names:\n    plt.plot(atms[name].t-atms[ref].t,atms[name].p,label=name)\n    plt.plot(atms[name].tconv-atms[ref].t[atms[name].iconv], atms[name].pconv, 'ks')\n    plt.plot(atms[name].tcold-atms[ref].t[atms[name].icold], atms[name].pcold, 'ko')\n    plt.plot(np.zeros(len(atms[name])),atms[name].p, 'k--')\nplt.ylim(yls)\nplt.xlim(xls1)\nax = plt.gca()\nax.set_yscale('log')\nax.invert_yaxis()\nplt.title('')\nplt.ylabel('Pressure (hPa)')\nplt.xlabel('Temperature (K)')\nplt.legend(loc='best')\n\n\n\n\nfigname = 'img/rce_{}g{}_cld_{}_tdiff.png'.format(\n                 radmodel,fstag,rhlabel)\nprint(\"Writing figure: {}\".format(figname))\nplt.savefig(\n    bbox_inches='tight', dpi=300, filename=figname)\n\n\n\n# %% plot of cloud heating rates\nplt.figure(8)\nplt.clf()\nxls = (-0.5,1.5)\nyls = (80, 1000)\n\nplt.subplot(131)\nplt.hold('on')\nnames = anames[1:3]\nfor name in names:\n    plt.plot(auxhr[name].hr,atms[name].p,label=name)\n    plt.plot(auxhr[name].hr[atms[name].iconv], atms[name].pconv, 'ks')\n    plt.plot(auxhr[name].hr[atms[name].icold], atms[name].pcold, 'ko')\n    plt.plot(np.zeros(len(atms[name])),atms[name].p, 'k--')\nnames = anames[4:6]\nfor name in names:\n    plt.plot(auxhr[name].hr,atms[name].p,'--',label=name)\n    plt.plot(auxhr[name].hr[atms[name].iconv], atms[name].pconv, 'ks')\n    plt.plot(auxhr[name].hr[atms[name].icold], atms[name].pcold, 'ko')\n    plt.plot(np.zeros(len(atms[name])),atms[name].p, 'k--')\nplt.ylim(yls)\nplt.xlim(xls)\nax = plt.gca()\nax.set_yscale('log')\nax.invert_yaxis()\nplt.title('')\nplt.ylabel('Pressure (hPa)')\nplt.xlabel('Cloud HR (K/d)')\n#plt.legend(loc='best')\n\nplt.subplot(132)\nplt.hold('on')\nnames = anames[1:3]\nfor name in names:\n    plt.plot(auxhr[name].hrir,atms[name].p,label=name)\n    plt.plot(auxhr[name].hrir[atms[name].iconv], atms[name].pconv, 'ks')\n    plt.plot(auxhr[name].hrir[atms[name].icold], atms[name].pcold, 'ko')\n    plt.plot(np.zeros(len(atms[name])),atms[name].p, 'k--')\nnames = anames[4:6]\nfor name in names:\n    plt.plot(auxhr[name].hrir,atms[name].p,'--',label=name)\n    plt.plot(auxhr[name].hrir[atms[name].iconv], atms[name].pconv, 'ks')\n    plt.plot(auxhr[name].hrir[atms[name].icold], atms[name].pcold, 'ko')\n    plt.plot(np.zeros(len(atms[name])),atms[name].p, 'k--')\nplt.ylim(yls)\nplt.xlim(xls)\nax = plt.gca()\nax.set_yscale('log')\nax.invert_yaxis()\nplt.title('')\nplt.ylabel('Pressure (hPa)')\nplt.xlabel('Cloud IR HR (K/d)')\n#plt.legend(loc='best')\n\nplt.subplot(133)\nplt.hold('on')\nnames = anames[1:3]\nfor name in names:\n    plt.plot(auxhr[name].hrsw,atms[name].p,label=name)\n    plt.plot(auxhr[name].hrsw[atms[name].iconv], atms[name].pconv, 'ks')\n    plt.plot(auxhr[name].hrsw[atms[name].icold], atms[name].pcold, 'ko')\n    plt.plot(np.zeros(len(atms[name])),atms[name].p, 'k--')\nnames = anames[4:6]\nfor name in names:\n    plt.plot(auxhr[name].hrsw,atms[name].p,'--',label=name)\n    plt.plot(auxhr[name].hrsw[atms[name].iconv], atms[name].pconv, 'ks')\n    plt.plot(auxhr[name].hrsw[atms[name].icold], atms[name].pcold, 'ko')\n    plt.plot(np.zeros(len(atms[name])),atms[name].p, 'k--')\nplt.ylim(yls)\nplt.xlim(xls)\nax = plt.gca()\nax.set_yscale('log')\nax.invert_yaxis()\nplt.title('')\nplt.ylabel('Pressure (hPa)')\nplt.xlabel('Cloud SW HR (K/d)')\n#plt.legend(loc='best')\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "1a5f290011d74e4b7a482ed4477db19177b7d656", "size": 15399, "ext": "py", "lang": "Python", "max_stars_repo_path": "experiment_cld.py", "max_stars_repo_name": "msmithsm/rce", "max_stars_repo_head_hexsha": "91e6fd2ee93b64a471aa7e0ca62bb4649c1b3b19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experiment_cld.py", "max_issues_repo_name": "msmithsm/rce", "max_issues_repo_head_hexsha": "91e6fd2ee93b64a471aa7e0ca62bb4649c1b3b19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "experiment_cld.py", "max_forks_repo_name": "msmithsm/rce", "max_forks_repo_head_hexsha": "91e6fd2ee93b64a471aa7e0ca62bb4649c1b3b19", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9981818182, "max_line_length": 102, "alphanum_fraction": 0.6245210728, "include": true, "reason": "import numpy", "num_tokens": 5053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.19422425520074343}}
{"text": "# required tensoefrlow version: 1.14.0\n# conda install -c anaconda tensorflow-gpu==1.14.0\n\nimport Utils\n# import tensorflow as tf\nimport tensorflow.compat.v1 as tf\ntf.disable_v2_behavior()\nimport CNN_Siamese\nimport ResNet_Siamese\nimport numpy as np\nimport matplotlib.pyplot as plt\n# import cv2\nfrom collections import OrderedDict  #--> for not repeating legends in plot\nimport umap\nimport os\nfrom Evaluate_embedding_space import Evaluate_embedding_space\nimport dataset_characteristics\n\n# import warnings\n# warnings.filterwarnings('ignore')\n\ndef main():\n    #================================ settings:\n    train_the_embedding_space = True\n    evaluate_the_embedding_space = False\n    assert train_the_embedding_space != evaluate_the_embedding_space\n    deep_model = \"ResNet\"  #--> \"CNN\", \"ResNet\"\n    loss_type = \"triplet\"   #--> \"triplet\", \"FDA\", \"contrastive\", \"FDA_contrastive\"\n    n_res_blocks = 18  #--> 18, 34, 50, 101, 152\n    batch_size = 32\n    learning_rate = 1e-5\n    margin_in_loss = 0.25\n    latent_space_dimension = 100\n    feature_space_dimension = 2\n    path_save_network_model = \".\\\\network_model\\\\\" + deep_model + \"\\\\\"\n    model_dir_ = model_dir(model_name=deep_model, n_res_blocks=n_res_blocks, batch_size=batch_size, learning_rate=learning_rate)\n    #================================ \n    if train_the_embedding_space:\n        train_embedding_space(deep_model, n_res_blocks, batch_size, learning_rate, path_save_network_model, model_dir_, feature_space_dimension, latent_space_dimension, margin_in_loss, loss_type)\n    if evaluate_the_embedding_space:\n        evaluate_embedding_space(path_save_network_model, model_dir_, deep_model, feature_space_dimension, latent_space_dimension, n_res_blocks, margin_in_loss, loss_type)\n\ndef evaluate_embedding_space(path_save_network_model, model_dir_, deep_model, feature_space_dimension, latent_space_dimension, n_res_blocks, margin_in_loss, loss_type):\n    which_epoch_to_load_NN_model = 45\n    path_save_embeddings_of_test_data = \".\\\\results\\\\\" + deep_model + \"\\\\embedding_test_set\\\\\"\n    image_height = dataset_characteristics.get_image_height()\n    image_width = dataset_characteristics.get_image_width()\n    image_n_channels = dataset_characteristics.get_image_n_channels()\n    # path_save_network_model = \"./network_model/ResNet/\"\n    if deep_model == \"CNN\":\n        siamese = CNN_Siamese.CNN_Siamese(loss_type=loss_type, feature_space_dimension=feature_space_dimension, margin_in_loss=margin_in_loss)\n    elif deep_model == \"ResNet\":\n        siamese = ResNet_Siamese.ResNet_Siamese(loss_type=loss_type, feature_space_dimension=feature_space_dimension, latent_space_dimension=latent_space_dimension,\n                                                n_res_blocks=n_res_blocks, margin_in_loss=margin_in_loss, is_train=True)\n    evaluate_ = Evaluate_embedding_space(checkpoint_dir=path_save_network_model+str(which_epoch_to_load_NN_model)+\"/\", model_dir_=model_dir_)\n    (X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data()\n    # X_train = X_train[:2000, :, :]\n    # X_train = X_train.reshape((X_train.shape[0], image_height, image_width, image_n_channels))\n    X_test = X_test.reshape((X_test.shape[0], image_height, image_width, image_n_channels))\n    # evaluate_.embed_the_data(X=X_train, labels=y_train, siamese=siamese, path_save_embeddings_of_test_data=path_save_embeddings_of_test_data)\n    embedding, labels = evaluate_.embed_the_data(X=X_test, labels=y_test, siamese=siamese, path_save_embeddings_of_test_data=path_save_embeddings_of_test_data)\n    evaluate_.classify_with_1NN(embedding, labels, path_to_save=path_save_embeddings_of_test_data + \"KNN/\")\n\n\ndef train_embedding_space(deep_model, n_res_blocks, batch_size, learning_rate, path_save_network_model, model_dir_, feature_space_dimension, latent_space_dimension, margin_in_loss, loss_type):\n    #================================ settings:\n    save_plot_embedding_space = True\n    save_points_in_embedding_space = True\n    load_saved_network_model = False\n    which_epoch_to_load_NN_model = 0\n    num_epoch = 51\n    save_network_model_every_how_many_epochs = 2\n    save_embedding_every_how_many_epochs = 2\n    # STEPS_PER_EPOCH_TRAIN = 704\n    # STEPS_PER_EPOCH_TRAIN = 16\n    STEPS_PER_EPOCH_TRAIN = 312  #--> 10000/32 (n_samples/batch_size)\n    n_samples_plot = None   #--> if None, plot all\n    image_height = dataset_characteristics.get_image_height()\n    image_width = dataset_characteristics.get_image_width()\n    image_n_channels = dataset_characteristics.get_image_n_channels()\n    # path_tfrecords_train = 'C:\\\\Users\\\\bghojogh\\\\Desktop\\\\My_PhD\\\\PhD_projects\\\\Pathology\\\\dataset\\\\TCGA_triplets\\\\tfrecord\\\\triplets.tfrecords'\n    # path_tfrecords_train = 'C:\\\\Users\\\\bghojogh\\\\Desktop\\\\My_PhD\\\\PhD_projects\\\\Fisher_loss\\\\codes\\\\4_make_triplets\\\\2_MNIST\\\\triplets\\\\MNIST_1024_triplets\\\\tfrecord\\\\triplets.tfrecords'\n    # path_tfrecords_train = 'C:\\\\Users\\\\bghojogh\\\\Desktop\\\\My_PhD\\\\PhD_projects\\\\Fisher_loss\\\\codes\\\\4_make_triplets\\\\2_MNIST\\\\triplets\\\\MNIST_500_triplets\\\\tfrecord\\\\triplets.tfrecords'\n    path_tfrecords_train = '.\\\\triplets.tfrecords'\n    path_save_embedding_space = \".\\\\results\\\\\" + deep_model + \"\\\\embedding_train_set\\\\\"\n    path_save_loss = \".\\\\loss_saved\\\\\"\n    #================================ \n\n    train_dataset = tf.data.TFRecordDataset([path_tfrecords_train])\n    train_dataset = train_dataset.map(Utils.parse_function)\n    train_dataset = train_dataset.map(Utils.normalize_triplets)\n\n    num_repeat = None\n    train_dataset = train_dataset.repeat(num_repeat)\n    train_dataset = train_dataset.shuffle(buffer_size=1024)\n    train_dataset = train_dataset.batch(batch_size)\n    handle = tf.placeholder(tf.string, shape=[])\n    iterator = tf.data.Iterator.from_string_handle(handle, train_dataset.output_types,\n                                                             train_dataset.output_shapes)\n\n    next_element = iterator.get_next()\n    # training_iterator = train_dataset.make_initializable_iterator()\n    training_iterator = tf.data.make_initializable_iterator(train_dataset)\n\n    # Siamese:\n    if deep_model == \"CNN\":\n        siamese = CNN_Siamese.CNN_Siamese(loss_type=loss_type, feature_space_dimension=feature_space_dimension, margin_in_loss=margin_in_loss)\n    elif deep_model == \"ResNet\":\n        siamese = ResNet_Siamese.ResNet_Siamese(loss_type=loss_type, feature_space_dimension=feature_space_dimension, latent_space_dimension=latent_space_dimension,\n                                                n_res_blocks=n_res_blocks, margin_in_loss=margin_in_loss, is_train=True)\n    # train_step = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(siamese.loss)\n    train_step = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(siamese.loss)\n    # tf.initialize_all_variables().run()\n\n    saver_ = tf.train.Saver(max_to_keep=None)  # https://www.tensorflow.org/api_docs/python/tf/compat/v1/train/Saver\n\n    with tf.Session() as sess:\n        sess.run(tf.global_variables_initializer())\n        sess.run(tf.local_variables_initializer())\n\n        training_handle = sess.run(training_iterator.string_handle())\n        sess.run(training_iterator.initializer)\n\n        if load_saved_network_model:\n            succesful_load, latest_epoch = load_network_model(saver_=saver_, session_=sess, checkpoint_dir=path_save_network_model+str(which_epoch_to_load_NN_model)+\"/\",\n                                                                model_dir_=model_dir_, model_name=deep_model)\n            assert (succesful_load == True)\n            loss_average_of_epochs = np.load(path_save_loss + \"loss.npy\")\n            loss_average_of_epochs = loss_average_of_epochs[:latest_epoch+1]\n            loss_average_of_epochs = list(loss_average_of_epochs)\n        else:\n            latest_epoch = -1\n            loss_average_of_epochs = []\n\n        for epoch in range(latest_epoch+1, num_epoch):\n            losses_in_epoch = []\n            print(\"============= epoch: \" + str(epoch) + \"/\" + str(num_epoch-1))\n            embeddings_in_epoch = np.zeros((STEPS_PER_EPOCH_TRAIN * batch_size * 3, feature_space_dimension))\n            labels_in_epoch = np.zeros((STEPS_PER_EPOCH_TRAIN * batch_size * 3,))\n            latent_space_dimension = 100  #--> see the file ResNet_siamese.py\n            embeddings_in_epoch_secondToLast = np.zeros((STEPS_PER_EPOCH_TRAIN * batch_size * 3, latent_space_dimension))\n            for i in range(STEPS_PER_EPOCH_TRAIN):\n                image_anchor, image_neighbor, image_distant, label_anchor, label_neighbor, label_distant = sess.run(next_element,\n                                                                       feed_dict={handle: training_handle})\n\n                image_anchor = image_anchor.reshape((batch_size, image_height, image_width, image_n_channels))\n                image_neighbor = image_neighbor.reshape((batch_size, image_height, image_width, image_n_channels))\n                image_distant = image_distant.reshape((batch_size, image_height, image_width, image_n_channels))\n\n                _, loss_v, embedding1, embedding2, embedding3, \\\n                embedding1_secondToLast, embedding2_secondToLast, embedding3_secondToLast = sess.run([train_step, siamese.loss, siamese.o1, siamese.o2, siamese.o3,\n                                                                                                    siamese.o1_secondToLast, siamese.o2_secondToLast, siamese.o3_secondToLast], feed_dict={\n                                                                                                    siamese.x1: image_anchor,\n                                                                                                    siamese.x2: image_neighbor,\n                                                                                                    siamese.x3: image_distant})\n\n                embeddings_in_epoch[ ((i*3*batch_size)+(0*batch_size)) : ((i*3*batch_size)+(1*batch_size)), : ] = embedding1\n                embeddings_in_epoch[ ((i*3*batch_size)+(1*batch_size)) : ((i*3*batch_size)+(2*batch_size)), : ] = embedding2\n                embeddings_in_epoch[ ((i*3*batch_size)+(2*batch_size)) : ((i*3*batch_size)+(3*batch_size)), : ] = embedding3\n\n                labels_in_epoch[ ((i*3*batch_size)+(0*batch_size)) : ((i*3*batch_size)+(1*batch_size)) ] = label_anchor\n                labels_in_epoch[ ((i*3*batch_size)+(1*batch_size)) : ((i*3*batch_size)+(2*batch_size)) ] = label_neighbor\n                labels_in_epoch[ ((i*3*batch_size)+(2*batch_size)) : ((i*3*batch_size)+(3*batch_size)) ] = label_distant\n\n                embeddings_in_epoch_secondToLast[ ((i*3*batch_size)+(0*batch_size)) : ((i*3*batch_size)+(1*batch_size)), : ] = embedding1_secondToLast\n                embeddings_in_epoch_secondToLast[ ((i*3*batch_size)+(1*batch_size)) : ((i*3*batch_size)+(2*batch_size)), : ] = embedding2_secondToLast\n                embeddings_in_epoch_secondToLast[ ((i*3*batch_size)+(2*batch_size)) : ((i*3*batch_size)+(3*batch_size)), : ] = embedding3_secondToLast\n\n                losses_in_epoch.extend([loss_v])\n                \n            # report average loss of epoch:\n            loss_average_of_epochs.append(np.average(np.asarray(losses_in_epoch)))\n            print(\"Average loss of epoch \" + str(epoch) + \": \" + str(loss_average_of_epochs[-1]))\n            if not os.path.exists(path_save_loss):\n                os.makedirs(path_save_loss)\n            np.save(path_save_loss + \"loss.npy\", np.asarray(loss_average_of_epochs))\n\n            # plot the embedding space:\n            if (epoch % save_embedding_every_how_many_epochs == 0):\n                if save_points_in_embedding_space:\n                    if not os.path.exists(path_save_embedding_space+\"numpy\\\\\"):\n                        os.makedirs(path_save_embedding_space+\"numpy\\\\\")\n                    np.save(path_save_embedding_space+\"numpy\\\\embeddings_in_epoch_\" + str(epoch) + \".npy\", embeddings_in_epoch)\n                    np.save(path_save_embedding_space+\"numpy\\\\labels_in_epoch_\" + str(epoch) + \".npy\", labels_in_epoch)\n                    # np.save(path_save_embedding_space+\"numpy\\\\embeddings_in_epoch_secondToLast_\" + str(epoch) + \".npy\", embeddings_in_epoch_secondToLast)\n                if save_plot_embedding_space:\n                    print(\"saving the plot of embedding space....\")\n                    plt.figure(200)\n                    # fig.clf()\n                    _, indices_to_plot = plot_embedding_of_points(embeddings_in_epoch, labels_in_epoch, n_samples_plot)\n                    if not os.path.exists(path_save_embedding_space+\"plots\\\\\"):\n                        os.makedirs(path_save_embedding_space+\"plots\\\\\")\n                    plt.savefig(path_save_embedding_space+\"plots\\\\\" + 'epoch' + str(epoch) + '_step' + str(i) + '.png')\n                    plt.clf()\n                    plt.close()\n                    # if not os.path.exists(path_save_embedding_space+\"plots_secondToLast\\\\\"):\n                    #     os.makedirs(path_save_embedding_space+\"plots_secondToLast\\\\\")\n                    # plot_embedding_of_points_secondToLast(embeddings_in_epoch_secondToLast, labels_in_epoch, indices_to_plot)\n                    # plt.savefig(path_save_embedding_space+\"plots_secondToLast\\\\\" + 'epoch' + str(epoch) + '_step' + str(i) + '.png')\n                    # plt.clf()\n                    # plt.close()\n\n            # save the network model:\n            if (epoch % save_network_model_every_how_many_epochs == 0):\n                # save_network_model(saver_=saver_, session_=sess, checkpoint_dir=path_save_network_model, step=epoch, model_name=deep_model, model_dir_=model_dir_)\n                save_network_model(saver_=saver_, session_=sess, checkpoint_dir=path_save_network_model+str(epoch)+\"/\", step=epoch, model_name=deep_model, model_dir_=model_dir_)\n                print(\"Model saved in path: %s\" % path_save_network_model)\n\ndef plot_embedding_of_points(embedding, labels, n_samples_plot=None):\n    n_samples = embedding.shape[0]\n    if n_samples_plot != None:\n        indices_to_plot = np.random.choice(range(n_samples), min(n_samples_plot, n_samples), replace=False)\n    else:\n        indices_to_plot = np.random.choice(range(n_samples), n_samples, replace=False)\n    embedding_sampled = embedding[indices_to_plot, :]\n    if embedding.shape[1] == 2:\n        pass\n    else:\n        embedding_sampled = umap.UMAP(n_neighbors=500).fit_transform(embedding_sampled)\n    n_points = embedding.shape[0]\n    # n_points_sampled = embedding_sampled.shape[0]\n    labels_sampled = labels[indices_to_plot]\n    _, ax = plt.subplots(1, figsize=(14, 10))\n    classes = dataset_characteristics.get_class_names()\n    n_classes = len(classes)\n    plt.scatter(embedding_sampled[:, 0], embedding_sampled[:, 1], s=10, c=labels_sampled, cmap='Spectral', alpha=1.0)\n    # plt.setp(ax, xticks=[], yticks=[])\n    cbar = plt.colorbar(boundaries=np.arange(n_classes+1)-0.5)\n    cbar.set_ticks(np.arange(n_classes))\n    cbar.set_ticklabels(classes)\n    return plt, indices_to_plot\n\ndef plot_embedding_of_points_secondToLast(embedding_secondToLast, labels, indices_to_plot):\n    embedding_sampled = embedding_secondToLast[indices_to_plot, :]\n    if embedding_secondToLast.shape[1] == 2:\n        pass\n    else:\n        embedding_sampled = umap.UMAP(n_neighbors=500).fit_transform(embedding_sampled)\n    n_points = embedding_secondToLast.shape[0]\n    # n_points_sampled = embedding_sampled.shape[0]\n    labels_sampled = labels[indices_to_plot]\n    _, ax = plt.subplots(1, figsize=(14, 10))\n    classes = dataset_characteristics.get_class_names()\n    n_classes = len(classes)\n    plt.scatter(embedding_sampled[:, 0], embedding_sampled[:, 1], s=10, c=labels_sampled, cmap='Spectral', alpha=1.0)\n    # plt.setp(ax, xticks=[], yticks=[])\n    cbar = plt.colorbar(boundaries=np.arange(n_classes+1)-0.5)\n    cbar.set_ticks(np.arange(n_classes))\n    cbar.set_ticklabels(classes)\n    return plt\n\ndef save_network_model(saver_, session_, checkpoint_dir, step, model_name, model_dir_):\n    # https://stackoverflow.com/questions/33759623/tensorflow-how-to-save-restore-a-model\n    # https://github.com/taki0112/ResNet-Tensorflow/blob/master/ResNet.py\n    checkpoint_dir = os.path.join(checkpoint_dir, model_dir_)\n    if not os.path.exists(checkpoint_dir):\n        os.makedirs(checkpoint_dir)\n    saver_.save(session_, os.path.join(checkpoint_dir, model_name+'.model'), global_step=step)\n\ndef load_network_model(saver_, session_, checkpoint_dir, model_dir_, model_name):\n    # https://stackoverflow.com/questions/33759623/tensorflow-how-to-save-restore-a-model\n    print(\" [*] Reading checkpoints...\")\n    checkpoint_dir = os.path.join(checkpoint_dir, model_dir_)\n    ckpt = tf.train.get_checkpoint_state(checkpoint_dir)\n    if ckpt and ckpt.model_checkpoint_path:\n        ckpt_name = os.path.basename(ckpt.model_checkpoint_path)\n        saver_.restore(session_, os.path.join(checkpoint_dir, ckpt_name))\n        print(\" [*] Success to read {}\".format(ckpt_name))\n        latest_epoch = int(ckpt_name.split(\"-\")[-1])\n        return True, latest_epoch\n    else:\n        print(\" [*] Failed to find a checkpoint\")\n        return False, 0\n\n\ndef model_dir(model_name, n_res_blocks, batch_size, learning_rate):\n    return \"{}_{}_{}_{}\".format(model_name, n_res_blocks, batch_size, learning_rate)\n\n\nif __name__ == \"__main__\":\n    main()", "meta": {"hexsha": "90ac58c74c734b3a4760bc4d0cea571e8039a3c1", "size": 17349, "ext": "py", "lang": "Python", "max_stars_repo_path": "2_deep_codes/3_Siamese_triplet/main.py", "max_stars_repo_name": "bghojogh/Quantile-Quantile-Embedding", "max_stars_repo_head_hexsha": "5daff878a838f6dbeb04cc0b15da2ad66ab9796c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-19T17:50:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-19T17:50:50.000Z", "max_issues_repo_path": "2_deep_codes/3_Siamese_triplet/main.py", "max_issues_repo_name": "bghojogh/Quantile-Quantile-Embedding", "max_issues_repo_head_hexsha": "5daff878a838f6dbeb04cc0b15da2ad66ab9796c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2_deep_codes/3_Siamese_triplet/main.py", "max_forks_repo_name": "bghojogh/Quantile-Quantile-Embedding", "max_forks_repo_head_hexsha": "5daff878a838f6dbeb04cc0b15da2ad66ab9796c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.7402135231, "max_line_length": 195, "alphanum_fraction": 0.6852268142, "include": true, "reason": "import numpy", "num_tokens": 4021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.19422424613138564}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 16 13:24:45 2016\n\n@author: Ent00002\n\"\"\"\n\n# delayed runs, comment the 2 lines below when unused\n# import time\n# time.sleep(100)\n\n#%% Import libraries\n\nimport numpy as np\nimport scipy.io as sio\nimport calendar\nimport datetime\nfrom getconstants import getconstants\nfrom timeit import default_timer as timer\nimport os\n\n#%%BEGIN OF INPUT1 (FILL THIS IN)\nyears\t\t= np.arange(1979,2016)\t# Note that this can be forward as tracking was already finished, whereas the masterscript must be in backward order\nyearpart\t= np.arange(0,366)\t# for a full (leap)year fill in np.arange(0,366)\ndaily\t\t= 0\t\t\t# 1 for writing out daily data, 0 for only monthly data\ntimetracking\t= 1\t\t\t# 0 for not tracking time and 1 for tracking time\n\n# Manage the extent of your dataset (FILL THIS IN)\n# Define the latitude and longitude cell numbers to consider and corresponding lakes that should be considered part of the land\nlatnrs = np.arange(7,114)\nlonnrs = np.arange(0,240)\n\n# the lake numbers below belong to the ERA-Interim data on 1.5 degree starting at Northern latitude 79.5 and longitude -180\nlake_mask_1 = np.array([9,9,9,12,12,21,21,22,22,23,24,25,23,23,25,25,53,54,61,23,24,23,24,25,27,22,23,24,25,26,27,28,22,25,26,27,28,23,23,12,18])\nlake_mask_2 = np.array([120+19,120+40,120+41,120+43,120+44,120+61,120+62,120+62,120+63,120+62,120+62,120+62,120+65,120+66,120+65,120+66,142-120,142-120,143-120,152-120,152-120,153-120,153-120,153-120,153-120,154-120,154-120,154-120,154-120,154-120,154-120,154-120,155-120,155-120,155-120,155-120,155-120,159-120,160-120,144-120,120+55])\nlake_mask = np.transpose(np.vstack((lake_mask_1,lake_mask_2))) #recreate the arrays of the matlab model\n\n# obtain the constants\ninvariant_data = '/home/users/lguo/CSSP/WAM2layersPython-master/download_scripts/invariants.nc'\t#invariants\nlatitude,longitude,lsm,g,density_water,timestep,A_gridcell,L_N_gridcell,L_S_gridcell,L_EW_gridcell,gridcell = getconstants(latnrs,lonnrs,lake_mask,invariant_data)\n\ninterdata_folder = r'/home/users/lguo/CSSP/WAM2layersPython-master/interdata'\noutput_folder = r'/home/users/lguo/CSSP/WAM2layersPython-master/output'\nsub_interdata_folder = os.path.join(interdata_folder, 'cn1_backward')\n\n#END OF INPUT\n\n#%% Datapaths (FILL THIS IN)\n\n\ndef data_path(y,a,years,timetracking):\n    load_Sa_track = os.path.join(sub_interdata_folder, str(y) + '-' + str(a) + 'Sa_track.mat')\n    load_Sa_time = os.path.join(sub_interdata_folder, str(y) + '-' + str(a) + 'Sa_time.mat')\n    load_fluxes_and_storages = os.path.join(interdata_folder, str(y) + '-' + str(a) + 'fluxes_storages.mat')\n\n    save_path = os.path.join(output_folder, 'E_track_cn1_full' + str(years[0]) + '-' + str(years[-1]) + '-timetracking' + str(timetracking) + '.mat')\n    save_path_daily = os.path.join(output_folder, 'E_track_cn1_daily_full' + str(y) + '-timetracking' + str(timetracking) + '.mat')\n\n    return load_Sa_track,load_Sa_time,load_fluxes_and_storages,save_path,save_path_daily\n\n\n#%% Runtime & Results\nstart1 = timer()\nstartyear = years[0]\n\nE_per_year_per_month\t\t= np.zeros((len(years),12,len(latitude),len(longitude)))\nE_track_per_year_per_month\t= np.zeros((len(years),12,len(latitude),len(longitude)))\nP_per_year_per_month\t\t= np.zeros((len(years),12,len(latitude),len(longitude)))\nSa_track_down_per_year_per_month= np.zeros((len(years),12,len(latitude),len(longitude)))\nSa_track_top_per_year_per_month = np.zeros((len(years),12,len(latitude),len(longitude)))\nW_down_per_year_per_month\t= np.zeros((len(years),12,len(latitude),len(longitude)))\nW_top_per_year_per_month\t= np.zeros((len(years),12,len(latitude),len(longitude)))\nnorth_loss_per_year_per_month\t= np.zeros((len(years),12,1,len(longitude)))\nsouth_loss_per_year_per_month\t= np.zeros((len(years),12,1,len(longitude)))\ndown_to_top_per_year_per_month\t= np.zeros((len(years),12,len(latitude),len(longitude)))\ntop_to_down_per_year_per_month\t= np.zeros((len(years),12,len(latitude),len(longitude)))\nwater_lost_per_year_per_month\t= np.zeros((len(years),12,len(latitude),len(longitude)))\n\nif timetracking == 1:\n    Sa_time_down_per_year_per_month\t= np.zeros((len(years),12,len(latitude),len(longitude)))\n    Sa_time_top_per_year_per_month\t= np.zeros((len(years),12,len(latitude),len(longitude)))\n    E_time_per_year_per_month\t\t= np.zeros((len(years),12,len(latitude),len(longitude)))\n    Sa_dist_down_per_year_per_month\t= np.zeros((len(years),12,len(latitude),len(longitude)))\n    Sa_dist_top_per_year_per_month\t= np.zeros((len(years),12,len(latitude),len(longitude)))\n    E_dist_per_year_per_month\t\t= np.zeros((len(years),12,len(latitude),len(longitude)))\n\nfor i in range(len(years)):\n    y = years[i]\n    ly = int(calendar.isleap(y))\n    final_time = 364+ly\n    \n    E_per_day\t\t\t= np.zeros((365+ly,len(latitude),len(longitude)))\n    E_track_per_day\t\t= np.zeros((365+ly,len(latitude),len(longitude)))\n    P_per_day\t\t\t= np.zeros((365+ly,len(latitude),len(longitude)))\n    Sa_track_down_per_day\t= np.zeros((365+ly,len(latitude),len(longitude)))\n    Sa_track_top_per_day\t= np.zeros((365+ly,len(latitude),len(longitude)))\n    W_down_per_day\t\t= np.zeros((365+ly,len(latitude),len(longitude)))\n    W_top_per_day\t\t= np.zeros((365+ly,len(latitude),len(longitude)))\n    north_loss_per_day\t\t= np.zeros((365+ly,1,len(longitude)))\n    south_loss_per_day\t\t= np.zeros((365+ly,1,len(longitude)))\n    down_to_top_per_day\t\t= np.zeros((365+ly,len(latitude),len(longitude)))\n    top_to_down_per_day\t\t= np.zeros((365+ly,len(latitude),len(longitude)))\n    water_lost_per_day\t\t= np.zeros((365+ly,len(latitude),len(longitude)))\n    if timetracking == 1:\n        Sa_time_down_per_day\t= np.zeros((365+ly,len(latitude),len(longitude)))\n        Sa_time_top_per_day\t= np.zeros((365+ly,len(latitude),len(longitude)))\n        E_time_per_day\t\t= np.zeros((365+ly,len(latitude),len(longitude)))\n        Sa_dist_down_per_day\t= np.zeros((365+ly,len(latitude),len(longitude)))\n        Sa_dist_top_per_day\t= np.zeros((365+ly,len(latitude),len(longitude)))\n        E_dist_per_day\t\t= np.zeros((365+ly,len(latitude),len(longitude)))\n    \n    for j in range(len(yearpart)):\n        start = timer()\n        a = yearpart[j]\n        datapath = data_path(y,a,years,timetracking)\n        if a > final_time: # a = 365 (366th index) and not a leapyear\\\n            pass\n        else:\n            # load tracked data [97,107,240]\n            loading_ST = sio.loadmat(datapath[0],verify_compressed_data_integrity=False)\n            Sa_track_top\t= loading_ST['Sa_track_top']\n            Sa_track_down\t= loading_ST['Sa_track_down']\n            north_loss\t\t= loading_ST['north_loss']\n            south_loss\t\t= loading_ST['south_loss']\n            down_to_top\t\t= loading_ST['down_to_top']\n            top_to_down\t\t= loading_ST['top_to_down']\n            water_lost\t\t= loading_ST['water_lost']\n            Sa_track\t\t= Sa_track_top + Sa_track_down\n            if timetracking == 1:\n                loading_STT = sio.loadmat(datapath[1],verify_compressed_data_integrity=False)\n                Sa_time_top\t= loading_STT['Sa_time_top']\n                Sa_time_down\t= loading_STT['Sa_time_down']\n                Sa_dist_top\t= loading_STT['Sa_dist_top']\n                Sa_dist_down\t= loading_STT['Sa_dist_down']\n            \n            # load the total moisture data [96/97,107,240]\n            loading_FS = sio.loadmat(datapath[2],verify_compressed_data_integrity=False)\n            Fa_E_top\t= loading_FS['Fa_E_top']\n            Fa_N_top\t= loading_FS['Fa_N_top']\n            Fa_E_down\t= loading_FS['Fa_E_down']\n            Fa_N_down\t= loading_FS['Fa_N_down']\n            Fa_Vert\t= loading_FS['Fa_Vert']\n            E\t\t= loading_FS['E']\n            P\t\t= loading_FS['P']\n            W_top\t= loading_FS['W_top']\n            W_down\t= loading_FS['W_down']\n            W = W_top + W_down\n            \n            # compute tracked evaporation [96,107,240]\n\t    # LG: E_track is calculated via the bottom layer Sa.\n            E_track = E[:,:,:] * (Sa_track_down[1:,:,:] / W_down[1:,:,:])\n            \n            # save per day\n            E_per_day[a,:,:]\t\t\t= np.sum(E, axis =0)\n            E_track_per_day[a,:,:]\t\t= np.sum(E_track, axis =0)\n            P_per_day[a,:,:]\t\t\t= np.sum(P, axis =0)\n            Sa_track_down_per_day[a,:,:]\t= np.mean(Sa_track_down[1:,:,:], axis =0)\n            Sa_track_top_per_day[a,:,:]\t\t= np.mean(Sa_track_top[1:,:,:], axis =0)\n            W_down_per_day[a,:,:]\t\t= np.mean(W_down[1:,:,:], axis =0)\n            W_top_per_day[a,:,:]\t\t= np.mean(W_top[1:,:,:], axis =0)\n            \n            north_loss_per_day[a,:,:]\t\t= np.sum(north_loss, axis =0)\n            south_loss_per_day[a,:,:]\t\t= np.sum(south_loss, axis =0)\n            down_to_top_per_day[a,:,:]\t\t= np.sum(down_to_top, axis =0)\n            top_to_down_per_day[a,:,:]\t\t= np.sum(top_to_down, axis =0)\n            water_lost_per_day[a,:,:]\t\t= np.sum(water_lost, axis =0)\n            \n            if timetracking == 1:\n                # compute tracked evaporation time [96,107,240]\n\t\t# LG: E_time is mean of two concecutive timesteps\n                E_time = 0.5 * ( Sa_time_down[:-1,:,:] + Sa_time_down[1:,:,:] )\t\t\t\t\t# seconds\n                # save per day\n                Sa_time_down_per_day[a,:,:]\t= np.mean(Sa_time_down[:-1,:,:], axis=0)\t\t\t# seconds\n                Sa_time_top_per_day[a,:,:]\t= np.mean(Sa_time_top[:-1,:,:], axis=0)\t\t\t\t# seconds\n                E_time_per_day[a,:,:]\t\t= np.sum((E_time * E_track), axis = 0) / E_track_per_day[a,:,:]\t# seconds\n                # remove nans                \n                where_are_NaNs = np.isnan(E_time_per_day)\n                E_time_per_day[where_are_NaNs] = 0\n\n                # compute tracked evaporation distance [96,107,240]\n                E_dist = 0.5 * ( Sa_dist_down[:-1,:,:] + Sa_dist_down[1:,:,:] )\t\t\t\t\t# m\n                # save per day\n                Sa_dist_down_per_day[a,:,:]\t= np.mean(Sa_dist_down[:-1,:,:], axis=0)\t\t\t# m\n                Sa_dist_top_per_day[a,:,:]\t= np.mean(Sa_dist_top[:-1,:,:], axis=0)\t\t\t\t# m\n                E_dist_per_day[a,:,:]\t\t= np.sum((E_dist * E_track), axis = 0) / E_track_per_day[a,:,:]\t# m\n                # remove nans                \n                where_are_NaNs = np.isnan(E_dist_per_day)\n                E_dist_per_day[where_are_NaNs] = 0\n        \n        end = timer()\n        print 'Runtime output for day ' + str(a+1) + ' in year ' + str(y) + ' is',(end - start),' seconds.'\n    \n    if daily == 1:\n        if timetracking == 0: # create dummy values\n            Sa_time_down_per_day\t= 0\n            Sa_time_top_per_day\t\t= 0\n            E_time_per_day\t\t= 0\n    \n        sio.savemat(datapath[4],\n                    {'E_per_day':E_per_day,'E_track_per_day':E_track_per_day,'P_per_day':P_per_day,\n                     'Sa_track_down_per_day':Sa_track_down_per_day,'Sa_track_top_per_day':Sa_track_top_per_day, \n                     'Sa_time_down_per_day':Sa_time_down_per_day,'Sa_time_top_per_day':Sa_time_top_per_day, \n                     'Sa_dist_down_per_day':Sa_dist_down_per_day,'Sa_dist_top_per_day':Sa_dist_top_per_day, \n                     'W_down_per_day':W_down_per_day,'W_top_per_day':W_top_per_day,\n                     'E_time_per_day':E_time_per_day,'E_dist_per_day':E_dist_per_day},do_compression=True)\n\n    # values per month        \n    for m in range(12):\n        first_day = int(datetime.date(y,m+1,1).strftime(\"%j\"))\n        last_day = int(datetime.date(y,m+1,calendar.monthrange(y,m+1)[1]).strftime(\"%j\"))\n        days = np.arange(first_day,last_day+1)-1\t\t\t\t\t\t# -1 because Python is zero-based\n        \n        E_per_year_per_month[y-startyear,m,:,:]\t\t\t= (np.squeeze(np.sum(E_per_day[days,:,:], axis = 0)))\n        E_track_per_year_per_month[y-startyear,m,:,:]\t\t= (np.squeeze(np.sum(E_track_per_day[days,:,:], axis = 0)))\n        P_per_year_per_month[y-startyear,m,:,:]\t\t\t= (np.squeeze(np.sum(P_per_day[days,:,:], axis = 0)))\n        Sa_track_down_per_year_per_month[y-startyear,m,:,:]\t= (np.squeeze(np.mean(Sa_track_down_per_day[days,:,:], axis = 0)))\n        Sa_track_top_per_year_per_month[y-startyear,m,:,:]\t= (np.squeeze(np.mean(Sa_track_top_per_day[days,:,:], axis = 0)))\n        W_down_per_year_per_month[y-startyear,m,:,:]\t\t= (np.squeeze(np.mean(W_down_per_day[days,:,:], axis = 0)))\n        W_top_per_year_per_month[y-startyear,m,:,:]\t\t= (np.squeeze(np.mean(W_top_per_day[days,:,:], axis = 0)))\n        north_loss_per_year_per_month[y-startyear,m,:,:]\t= (np.squeeze(np.sum(north_loss_per_day[days,:,:], axis = 0)))\n        south_loss_per_year_per_month[y-startyear,m,:,:]\t= (np.squeeze(np.sum(south_loss_per_day[days,:,:], axis = 0)))\n        down_to_top_per_year_per_month[y-startyear,m,:,:]\t= (np.squeeze(np.sum(down_to_top_per_day[days,:,:], axis = 0)))\n        top_to_down_per_year_per_month[y-startyear,m,:,:]\t= (np.squeeze(np.sum(top_to_down_per_day[days,:,:], axis = 0)))\n        water_lost_per_year_per_month[y-startyear,m,:,:]\t= (np.squeeze(np.sum(water_lost_per_day[days,:,:], axis = 0)))\n        \n        if timetracking == 1:\n            # tracked time\n            Sa_time_down_per_year_per_month[y-startyear,m,:,:]\t= (np.squeeze(np.mean(Sa_time_down_per_day[days,:,:], axis = 0)))\n            Sa_time_top_per_year_per_month[y-startyear,m,:,:]\t= (np.squeeze(np.mean(Sa_time_top_per_day[days,:,:], axis =0)))\n            E_time_per_year_per_month[y-startyear,m,:,:]\t= (np.squeeze(np.sum( E_time_per_day[days,:,:] \n                * E_track_per_day[days,:,:], axis=0)) / np.squeeze(E_track_per_year_per_month[y-startyear,m,:,:]))\n                \n            # remove nans                \n            where_are_NaNs = np.isnan(E_time_per_year_per_month)\n            E_time_per_year_per_month[where_are_NaNs] = 0\n\n            # tracked distance\n            Sa_dist_down_per_year_per_month[y-startyear,m,:,:]\t= (np.squeeze(np.mean(Sa_dist_down_per_day[days,:,:], axis = 0)))\n            Sa_dist_top_per_year_per_month[y-startyear,m,:,:]\t= (np.squeeze(np.mean(Sa_dist_top_per_day[days,:,:], axis =0)))\n            E_dist_per_year_per_month[y-startyear,m,:,:]\t= (np.squeeze(np.sum( E_dist_per_day[days,:,:] \n                * E_track_per_day[days,:,:], axis=0)) / np.squeeze(E_track_per_year_per_month[y-startyear,m,:,:]))\n                \n            # remove nans                \n            where_are_NaNs = np.isnan(E_dist_per_year_per_month)\n            E_dist_per_year_per_month[where_are_NaNs] = 0\n                \n        elif timetracking == 0:\n            Sa_time_down_per_year_per_month\t= 0\n            Sa_time_top_per_year_per_month\t= 0\n            E_time_per_year_per_month\t\t= 0\n            Sa_dist_down_per_year_per_month\t= 0\n            Sa_dist_top_per_year_per_month\t= 0\n            E_dist_per_year_per_month\t\t= 0\n\n# save monthly data\nsio.savemat(datapath[3],\n           {'E_per_year_per_month':E_per_year_per_month,'E_track_per_year_per_month':E_track_per_year_per_month,'P_per_year_per_month':P_per_year_per_month,\n            'Sa_track_down_per_year_per_month':Sa_track_down_per_year_per_month,'Sa_track_top_per_year_per_month':Sa_track_top_per_year_per_month, \n            'Sa_time_down_per_year_per_month':Sa_time_down_per_year_per_month,'Sa_time_top_per_year_per_month':Sa_time_top_per_year_per_month, \n            'E_time_per_year_per_month':E_time_per_year_per_month, 'Sa_dist_down_per_year_per_month':Sa_dist_down_per_year_per_month,'Sa_dist_top_per_year_per_month':Sa_dist_top_per_year_per_month, 'E_dist_per_year_per_month':E_dist_per_year_per_month, 'W_down_per_year_per_month':W_down_per_year_per_month,'W_top_per_year_per_month':W_top_per_year_per_month,\n            'north_loss_per_year_per_month':north_loss_per_year_per_month,'south_loss_per_year_per_month':south_loss_per_year_per_month,\n            'down_to_top_per_year_per_month':down_to_top_per_year_per_month,'top_to_down_per_year_per_month':top_to_down_per_year_per_month,\n            'water_lost_per_year_per_month':water_lost_per_year_per_month})\n\nend1 = timer()\nprint 'The total runtime of Con_E_Recyc_Output is',(end1-start1),' seconds.'\n", "meta": {"hexsha": "4b69b069f8b5dcf38f4a5aae996f9ce39d92420d", "size": 15955, "ext": "py", "lang": "Python", "max_stars_repo_path": "WAM-2layers/Con_E_Recyc_Output.py", "max_stars_repo_name": "nick-klingaman/dubstep", "max_stars_repo_head_hexsha": "576ac6efa1748933aa37ae28a41e77c8c0dbe2ab", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WAM-2layers/Con_E_Recyc_Output.py", "max_issues_repo_name": "nick-klingaman/dubstep", "max_issues_repo_head_hexsha": "576ac6efa1748933aa37ae28a41e77c8c0dbe2ab", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WAM-2layers/Con_E_Recyc_Output.py", "max_forks_repo_name": "nick-klingaman/dubstep", "max_forks_repo_head_hexsha": "576ac6efa1748933aa37ae28a41e77c8c0dbe2ab", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-21T06:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T06:35:51.000Z", "avg_line_length": 59.7565543071, "max_line_length": 359, "alphanum_fraction": 0.6612973989, "include": true, "reason": "import numpy,import scipy", "num_tokens": 4544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.1942242441387029}}
{"text": "#!/usr/bin/env python\n\"\"\"\nProgram for the regression of mlp about paramagnetic FCC Fe\n\"\"\"\n\nimport argparse\nimport copy\n\n# import time\n# import tqdm\nimport random\n\nimport numpy as np\nfrom mlptools.common.fileio import InputParams\nfrom mlptools.common.structure import Structure\nfrom mlptools.mlpgen.model import Terms\nfrom mlptools.mlpgen.myIO import ReadFeatureParams, read_regression_params\nfrom mlptools.mlpgen.regression import PotEstimation\n\n\ndef rearange_L(array, index_array):\n    \"\"\"Move designated columns to the head of array.\n\n    Args:\n        array (ndarray): input array(2D)\n        index_array (list): list of index by which columns are designated\n\n    Returns:\n        ndarray: changed array\n    \"\"\"\n    rest = np.delete(array, index_array, 1)\n    return np.hstack((array[:, index_array], rest))\n\n\nclass VirtualDataInput:\n    \"\"\"Generate a virtual DataInput from normal DataInput\"\"\"\n\n    def __init__(self, di):\n        self.vdi = copy.deepcopy(di)\n        self.vdi.n_type = 2\n\n    def get_data_input(self):\n        \"\"\"Return a newly generated DataInput.\n\n        Returns:\n            DataInput: virtual DataInput\n        \"\"\"\n        return self.vdi\n\n\nclass MagneticStructuralFeatures:\n    \"\"\"Data structure including magnetic structural features\"\"\"\n\n    def __init__(self, tr, spin_array, vdi):\n        st_set_all_train = self.get_virtual_structures(tr.train, spin_array)\n        n_st_dataset = [len(data.st_set) for data in tr.train]\n        term = Terms(st_set_all_train, vdi, n_st_dataset, vdi.train_force)\n        self.train_x = np.hstack((tr.train_x, term.get_x()))\n        st_set_all_test = self.get_virtual_structures(tr.test, spin_array)\n        n_st_dataset = [len(data.st_set) for data in tr.test]\n        force_dataset = [vdi.wforce for v in vdi.test_names]\n        term = Terms(st_set_all_test, vdi, n_st_dataset, force_dataset)\n        self.test_x = np.hstack((tr.test_x, term.get_x()))\n\n    def get_x(self):\n        \"\"\"Return the X matrices for regression\n\n        Returns:\n            ndarray: X matrices needed for training and test\n        \"\"\"\n        return self.train_x, self.test_x\n\n    def get_virtual_structures(self, dataset, spin_array):\n        \"\"\"Generate virtual structures from dataset based on spin_array and return the\n           list of them\n\n        Args:\n            dataset (dr_array): array of the instances, DataRegression\n            spin_array (ndarray): which spin each atom has\n\n        Returns:\n            list: list of rewrited structures\n        \"\"\"\n        index_array = np.nonzero(spin_array == 1)[0]\n        n_atom_1 = len(index_array)\n        n_atom_2 = sum(dataset[0].st_set[0].n_atoms) - len(index_array)\n        n_atoms = [n_atom_1, n_atom_2]\n        specie1 = [\"A\" for i in range(n_atom_1)]\n        specie2 = [\"B\" for i in range(n_atom_2)]\n        elements = specie1.extend(specie2)\n        type1 = [0 for i in range(n_atom_1)]\n        type2 = [1 for i in range(n_atom_2)]\n        types = type1.extend(type2)\n        st_list = [\n            Structure(\n                st.axis,\n                rearange_L(st.positions, index_array),\n                n_atoms,\n                elements,\n                types=types,\n                comment=st.comment,\n            )\n            for data in dataset\n            for st in data.st_set\n        ]\n        return st_list\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"-i\",\n        \"--infile\",\n        type=str,\n        required=True,\n        help=\"Input file name. Training is performed from vasprun files.\",\n    )\n    parser.add_argument(\n        \"-p\",\n        \"--pot\",\n        type=str,\n        default=\"mlp.pkl\",\n        help=\"Potential file name for mlptools\",\n    )\n    args = parser.parse_args()\n\n    # prepare temporary spin array\n    spin_array = np.array(random.choices([-1, 1], k=32))\n\n    p = InputParams(args.infile)\n    di = ReadFeatureParams(p).get_params()\n    vdi = VirtualDataInput(di).get_data_input()\n\n    # calculate structural features\n    tr = PotEstimation(di=di)\n    # calculate magnetic structural features\n    tr.train_x, tr.test_x = MagneticStructuralFeatures(tr, spin_array, vdi).get_x()\n    tr.set_regression_data()\n\n    # start regression\n    if args.noreg is False:\n        reg_method, alpha_min, alpha_max, n_alpha = read_regression_params(p)\n        if reg_method == \"ridge\" or reg_method == \"lasso\":\n            pot = tr.regularization_reg(\n                method=reg_method,\n                alpha_min=alpha_min,\n                alpha_max=alpha_max,\n                n_alpha=n_alpha,\n                svd=args.svd,\n            )\n        elif reg_method == \"normal\":\n            pot = tr.normal_reg()\n\n        pot.save_pot(file_name=args.pot)\n        pot.save_pot_for_lammps(file_name=args.lammps)\n\n        print(\" --- input parameters ----\")\n        pot.di.model_e.print()\n        print(\" --- best model ----\")\n        if reg_method == \"ridge\" or reg_method == \"lasso\":\n            print(\" alpha = \", tr.best_alpha)\n\n        (\n            rmse_train_e,\n            rmse_test_e,\n            rmse_train_f,\n            files_train,\n            rmse_test_f,\n            rmse_train_s,\n            rmse_test_s,\n            files_test,\n        ) = tr.get_best_rmse()\n\n        print(\" -- Prediction Error --\")\n        for re, rf, rs, f in zip(rmse_train_e, rmse_train_f, rmse_train_s, files_train):\n            print(\" structures :\", f)\n            print(\" rmse (energy, train) = \", re * 1000, \" (meV/atom)\")\n            if rf is not None:\n                print(\" rmse (force, train) = \", rf, \" (eV/ang)\")\n                print(\" rmse (stress, train) = \", rs, \" (GPa)\")\n        for re, rf, rs, f in zip(rmse_test_e, rmse_test_f, rmse_test_s, files_test):\n            print(\" structures :\", f)\n            print(\" rmse (energy, test) = \", re * 1000, \" (meV/atom)\")\n            if rf is not None:\n                print(\" rmse (force, test) = \", rf, \" (eV/ang)\")\n                print(\" rmse (stress, test) = \", rs, \" (GPa)\")\n", "meta": {"hexsha": "4056b751c293d98a603ec05dd914fca16e0d04b0", "size": 6010, "ext": "py", "lang": "Python", "max_stars_repo_path": "my_codes/mlpgen/_regression.py", "max_stars_repo_name": "iwamura-lab/my_codes", "max_stars_repo_head_hexsha": "70140fe81b70d7ea4969c442771db40054cc109e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "my_codes/mlpgen/_regression.py", "max_issues_repo_name": "iwamura-lab/my_codes", "max_issues_repo_head_hexsha": "70140fe81b70d7ea4969c442771db40054cc109e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "my_codes/mlpgen/_regression.py", "max_forks_repo_name": "iwamura-lab/my_codes", "max_forks_repo_head_hexsha": "70140fe81b70d7ea4969c442771db40054cc109e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1390374332, "max_line_length": 88, "alphanum_fraction": 0.5941763727, "include": true, "reason": "import numpy", "num_tokens": 1458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.19406868873478614}}
{"text": "\"\"\"\nCommon solar physics coordinate systems.\n\nThis submodule implements various solar physics coordinate frames for use with\nthe `astropy.coordinates` module.\n\"\"\"\nfrom contextlib import contextmanager\n\nimport numpy as np\n\nimport astropy.units as u\nfrom astropy.coordinates import ConvertError, QuantityAttribute\nfrom astropy.coordinates.baseframe import BaseCoordinateFrame, RepresentationMapping\nfrom astropy.coordinates.representation import (\n    CartesianDifferential,\n    CartesianRepresentation,\n    CylindricalRepresentation,\n    SphericalDifferential,\n    SphericalRepresentation,\n    UnitSphericalRepresentation,\n)\nfrom astropy.time import Time\n\nfrom sunpy import log\nfrom sunpy.sun.constants import radius as _RSUN\nfrom sunpy.time.time import _variables_for_parse_time_docstring\nfrom sunpy.util.decorators import add_common_docstring\nfrom sunpy.util.exceptions import warn_user\nfrom .frameattributes import ObserverCoordinateAttribute, TimeFrameAttributeSunPy\n\n_J2000 = Time('J2000.0', scale='tt')\n\n__all__ = ['SunPyBaseCoordinateFrame', 'BaseHeliographic',\n           'HeliographicStonyhurst', 'HeliographicCarrington',\n           'Heliocentric', 'Helioprojective',\n           'HeliocentricEarthEcliptic', 'GeocentricSolarEcliptic',\n           'HeliocentricInertial', 'GeocentricEarthEquatorial']\n\n\ndef _frame_parameters():\n    \"\"\"\n    Returns formatting dictionary to use with add_common_docstring to populate frame docstrings\n    \"\"\"\n    ret = {}\n\n    # Each text block is missing the first indent because it already exists in the frame docstring\n    ret['data'] = (\"data : `~astropy.coordinates.BaseRepresentation` or ``None``\\n\"\n                   \"        A representation object or ``None`` to have no data\\n\"\n                   \"        (or use the coordinate component arguments, see below).\")\n    ret['common'] = (f\"obstime : {_variables_for_parse_time_docstring()['parse_time_types']}\\n\"\n                     \"        The time of the observation.  This is used to determine the\\n\"\n                     \"        position of solar-system bodies (e.g., the Sun and the Earth) as\\n\"\n                     \"        needed to define the origin and orientation of the frame.\\n\"\n                     \"    representation_type : `~astropy.coordinates.BaseRepresentation`, str, optional\\n\"\n                     \"        A representation class or string name of a representation class.\\n\"\n                     \"        This may change the valid coordinate component arguments from the\\n\"\n                     \"        defaults (see above). For example, passing\\n\"\n                     \"        ``representation_type='cartesian'`` will make the frame expect\\n\"\n                     \"        Cartesian coordinate component arguments (typically, ``x``, ``y``,\\n\"\n                     \"        and ``z``).\\n\"\n                     \"    copy : bool, optional\\n\"\n                     \"        If `True` (default), make copies of the input coordinate arrays.\")\n    ret['lonlat'] = (\"lon : `~astropy.coordinates.Angle` or `~astropy.units.Quantity`, optional\\n\"\n                     \"        The longitude coordinate for this object (``lat`` must also be\\n\"\n                     \"        given and ``data`` must be ``None``).\\n\"\n                     \"        Not needed if ``data`` is given.\\n\"\n                     \"    lat : `~astropy.coordinates.Angle` or `~astropy.units.Quantity`, optional\\n\"\n                     \"        The latitude coordinate for this object (``lon`` must also be\\n\"\n                     \"        given and ``data`` must be ``None``).\\n\"\n                     \"        Not needed if ``data`` is given.\")\n    ret['radius'] = (\"radius : `~astropy.units.Quantity`, optional\\n\"\n                     \"        The radial distance coordinate from Sun center for this object.\\n\"\n                     \"        Defaults to the radius of the Sun. Not needed if ``data`` is given.\")\n    ret['distance_sun'] = (\"distance : `~astropy.units.Quantity`, optional\\n\"\n                           \"        The distance coordinate from Sun center for this object.\\n\"\n                           \"        Not needed if ``data`` is given.\")\n    ret['distance_earth'] = (\"distance : `~astropy.units.Quantity`, optional\\n\"\n                             \"        The distance coordinate from Earth center for this object.\\n\"\n                             \"        Not needed if ``data`` is given.\")\n    ret['xyz'] = (\"x : `~astropy.units.Quantity`, optional\\n\"\n                  \"        X-axis coordinate for this object. Not needed if ``data`` is given.\\n\"\n                  \"    y : `~astropy.units.Quantity`, optional\\n\"\n                  \"        Y-axis coordinate for this object. Not needed if ``data`` is given.\\n\"\n                  \"    z : `~astropy.units.Quantity`, optional\\n\"\n                  \"        Z-axis coordinate for this object. Not needed if ``data`` is given.\")\n    ret['observer'] = (\"observer : `~sunpy.coordinates.frames.HeliographicStonyhurst`, str\\n\"\n                       \"        The location of the observer. If a string is provided,\\n\"\n                       \"        it must be a solar system body that can be parsed by\\n\"\n                       \"        `~sunpy.coordinates.ephemeris.get_body_heliographic_stonyhurst`\\n\"\n                       \"        at the time ``obstime``. Defaults to Earth center.\")\n    ret['rsun'] = (\"rsun : `~astropy.units.Quantity`\\n\"\n                   \"        The radius of the Sun in length units. Used to convert a 2D\\n\"\n                   \"        coordinate (i.e., no ``radius`` component) to a 3D coordinate by\\n\"\n                   \"        assuming that the coordinate is on the surface of the Sun. Defaults\\n\"\n                   \"        to the photospheric radius as defined in `sunpy.sun.constants`.\")\n    ret['equinox'] = (f\"equinox : {_variables_for_parse_time_docstring()['parse_time_types']}\\n\"\n                      \"        The date for the mean vernal equinox.\\n\"\n                      \"        Defaults to the J2000.0 equinox.\")\n\n    return ret\n\n\nclass SunPyBaseCoordinateFrame(BaseCoordinateFrame):\n    \"\"\"\n    Base class for sunpy coordinate frames.\n\n    This class is not intended to be used directly and has no transformations defined.\n\n    * Defines the frame attribute ``obstime`` for observation time.\n    * Defines a default wrap angle of 180 degrees for longitude in spherical coordinates,\n      which can be overridden via the class variable ``_wrap_angle``.\n    * Inject a nice way of representing the object which the coordinate represents.\n    \"\"\"\n    obstime = TimeFrameAttributeSunPy()\n\n    default_representation = SphericalRepresentation\n    default_differential = SphericalDifferential\n\n    frame_specific_representation_info = {\n        SphericalDifferential: [RepresentationMapping('d_lon', 'd_lon', u.arcsec/u.s),\n                                RepresentationMapping('d_lat', 'd_lat', u.arcsec/u.s),\n                                RepresentationMapping('d_distance', 'd_distance', u.km/u.s)],\n    }\n\n    _wrap_angle = 180*u.deg  # for longitude in spherical coordinates\n\n    def __init__(self, *args, **kwargs):\n        self.object_name = None\n\n        # If wrap_longitude=False is passed in, do not impose a specific wrap angle for the frame\n        if not kwargs.pop('wrap_longitude', True):\n            self._wrap_angle = None\n\n        super().__init__(*args, **kwargs)\n\n        # If obstime is specified, treat the default observer (None) as explicitly set\n        if self.obstime is not None and self.is_frame_attr_default('observer'):\n            self._attr_names_with_defaults.remove('observer')\n\n        return\n\n    def represent_as(self, base, s='base', in_frame_units=False):\n        data = super().represent_as(base, s, in_frame_units=in_frame_units)\n\n        # If a frame wrap angle is set, use that wrap angle for any spherical representations.\n        if self._wrap_angle is not None and \\\n           isinstance(data, (UnitSphericalRepresentation, SphericalRepresentation)):\n            data.lon.wrap_angle = self._wrap_angle\n        return data\n\n    def __str__(self):\n        # We override this here so that when you print a SkyCoord it shows the\n        # observer as the string and not the whole massive coordinate.\n        if getattr(self, \"object_name\", None):\n            return f\"<{self.__class__.__name__} Coordinate for '{self.object_name}'>\"\n        else:\n            return super().__str__()\n\n    @property\n    def _is_2d(self):\n        return (self._data is not None and self._data.norm().unit is u.one\n                and u.allclose(self._data.norm(), 1*u.one))\n\n    def __init_subclass__(cls, **kwargs):\n        super().__init_subclass__(**kwargs)\n\n        # TODO: Remove this after the minimum Astropy dependency includes astropy/astropy#12005\n        cls._fix_property_docstrings()\n\n    @classmethod\n    def _fix_property_docstrings(cls):\n        # This class method adds docstrings to properties dynamically created by\n        # BaseCoordinateFrame.__init_subclass__().  Accordingly, this method needs to itself be\n        # called from SunPyBaseCoordinateFrame.__init_subclass__() to work for our subclasses.\n        property_docstrings = {\n            'default_representation': \"Default representation for position data\",\n            'default_differential': \"Default representation for differential data\",\n            'frame_specific_representation_info': \"Mapping for frame-specific component names\",\n        }\n        for prop, docstring in property_docstrings.items():\n            if getattr(cls, prop).__doc__ is None:\n                setattr(getattr(cls, prop), '__doc__', docstring)\n\n\n# TODO: Remove this after the minimum Astropy dependency includes astropy/astropy#12005\nSunPyBaseCoordinateFrame._fix_property_docstrings()\n\n\nclass BaseHeliographic(SunPyBaseCoordinateFrame):\n    \"\"\"\n    Base class for HeliographicCarrington (HGC) and HeliographicStonyhurst (HGS) frames.\n\n    This class is not intended to be used directly and has no transformations defined.\n    \"\"\"\n    frame_specific_representation_info = {\n        SphericalRepresentation: [RepresentationMapping('lon', 'lon', u.deg),\n                                  RepresentationMapping('lat', 'lat', u.deg),\n                                  RepresentationMapping('distance', 'radius', None)],\n        SphericalDifferential: [RepresentationMapping('d_lon', 'd_lon', u.arcsec/u.s),\n                                RepresentationMapping('d_lat', 'd_lat', u.arcsec/u.s),\n                                RepresentationMapping('d_distance', 'd_radius', u.km/u.s)],\n    }\n\n    rsun = QuantityAttribute(default=_RSUN, unit=u.km)\n\n    def make_3d(self):\n        \"\"\"\n        Returns a fully 3D coordinate based on this coordinate.\n\n        If this coordinate is only 2D (i.e., no ``radius`` component) or is a\n        unit vector (i.e., the norm of the coordinate is unity), a new\n        coordinate is created that corresponds to the surface of the Sun.\n        That is, the 3D coordinate will retain the ``lon`` and ``lat``, and\n        ``radius`` will be set to the frame's ``rsun`` frame attribute.\n\n        If this coordinate is already fully 3D, it is directly returned, even\n        if it does not lie on the surface of the Sun.\n\n        Returns\n        -------\n        frame : `~sunpy.coordinates.frames.BaseHeliographic`\n            The fully 3D coordinate\n        \"\"\"\n        if self._is_2d:\n            return self.realize_frame(self._data * self.rsun)\n\n        # The coordinate is already 3D\n        return self\n\n\n@add_common_docstring(**_frame_parameters())\nclass HeliographicStonyhurst(BaseHeliographic):\n    \"\"\"\n    A coordinate or frame in the Stonyhurst Heliographic (HGS) system.\n\n    - The origin is the center of the Sun.\n    - The Z-axis (+90 degrees latitude) is aligned with the Sun's north pole.\n    - The X-axis (0 degrees longitude and 0 degrees latitude) is aligned with the projection of\n      the Sun-Earth line onto the Sun's equatorial plane.\n\n    This system is also know as the Heliocentric Earth Equatorial (HEEQ) system when\n    represented using Cartesian components.\n\n    A new instance can be created using the following signatures\n    (note that if supplied, ``obstime`` and ``representation_type`` must be\n    keyword arguments)::\n\n        HeliographicStonyhurst(lon, lat, obstime=obstime)\n        HeliographicStonyhurst(lon, lat, radius, obstime=obstime)\n        HeliographicStonyhurst(x, y, z, representation_type='cartesian', obstime=obstime)\n\n    Parameters\n    ----------\n    {data}\n    {lonlat}\n    {radius}\n    {rsun}\n    {common}\n\n    Examples\n    --------\n    >>> from astropy.coordinates import SkyCoord\n    >>> import sunpy.coordinates\n    >>> import astropy.units as u\n    >>> sc = SkyCoord(1*u.deg, 1*u.deg, 2*u.km,\n    ...               frame=\"heliographic_stonyhurst\",\n    ...               obstime=\"2010/01/01T00:00:45\")\n    >>> sc\n    <SkyCoord (HeliographicStonyhurst: obstime=2010-01-01T00:00:45.000, rsun=695700.0 km): (lon, lat, radius) in (deg, deg, km)\n        (1., 1., 2.)>\n    >>> sc.frame\n    <HeliographicStonyhurst Coordinate (obstime=2010-01-01T00:00:45.000, rsun=695700.0 km): (lon, lat, radius) in (deg, deg, km)\n        (1., 1., 2.)>\n    >>> sc = SkyCoord(HeliographicStonyhurst(-10*u.deg, 2*u.deg))\n    >>> sc\n    <SkyCoord (HeliographicStonyhurst: obstime=None, rsun=695700.0 km): (lon, lat) in deg\n        (-10., 2.)>\n    >>> sc = SkyCoord(CartesianRepresentation(0*u.km, 45*u.km, 2*u.km),\n    ...               obstime=\"2011/01/05T00:00:50\",\n    ...               frame=\"heliographic_stonyhurst\")\n    >>> sc\n    <SkyCoord (HeliographicStonyhurst: obstime=2011-01-05T00:00:50.000, rsun=695700.0 km): (lon, lat, radius) in (deg, deg, km)\n    (90., 2.54480438, 45.04442252)>\n    \"\"\"\n    name = \"heliographic_stonyhurst\"\n\n    def _apply_diffrot(self, duration, rotation_model):\n        oldrepr = self.spherical\n\n        from sunpy.physics.differential_rotation import diff_rot\n        log.debug(f\"Applying {duration} of solar rotation\")\n        newlon = oldrepr.lon + diff_rot(duration,\n                                        oldrepr.lat,\n                                        rot_type=rotation_model,\n                                        frame_time='sidereal')\n        newrepr = SphericalRepresentation(newlon, oldrepr.lat, oldrepr.distance)\n\n        return self.realize_frame(newrepr)\n\n\n@add_common_docstring(**_frame_parameters())\nclass HeliographicCarrington(BaseHeliographic):\n    \"\"\"\n    A coordinate or frame in the Carrington Heliographic (HGC) system.\n\n    - The origin is the center of the Sun.\n    - The Z-axis (+90 degrees latitude) is aligned with the Sun's north pole.\n    - The X-axis and Y-axis rotate with a period of 25.38 days.\n\n    This system differs from Stonyhurst Heliographic (HGS) in its definition of longitude.  This\n    longitude is an \"apparent\" longitude because it takes into account the time it takes for light\n    to travel from the Sun's surface to the observer (see :ref:`sunpy-coordinates-carrington`).\n    Thus, the observer needs to be specified to be able to transform to any other coordinate frame.\n\n    A new instance can be created using the following signatures\n    (note that if supplied, ``obstime`` and ``observer`` must be a keyword argument)::\n\n        HeliographicCarrington(lon, lat, obstime=obstime, observer=observer)\n        HeliographicCarrington(lon, lat, radius, obstime=obstime, observer=observer)\n\n    If you want to define the location in HGC such that the observer for the coordinate frame is\n    the same as that location (e.g., the location of an observatory in its corresponding HGC\n    frame), use ``observer='self'``::\n\n        HeliographicCarrington(lon, lat, radius, obstime=obstime, observer='self')\n\n    Parameters\n    ----------\n    {data}\n    {lonlat}\n    {radius}\n    {observer}\n    {rsun}\n    {common}\n\n    Examples\n    --------\n    >>> from astropy.coordinates import SkyCoord\n    >>> import sunpy.coordinates\n    >>> import astropy.units as u\n    >>> sc = SkyCoord(1*u.deg, 2*u.deg, 3*u.km,\n    ...               frame=\"heliographic_carrington\",\n    ...               observer=\"earth\",\n    ...               obstime=\"2010/01/01T00:00:30\")\n    >>> sc\n    <SkyCoord (HeliographicCarrington: obstime=2010-01-01T00:00:30.000, rsun=695700.0 km, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (lon, lat, radius) in (deg, deg, km)\n        (1., 2., 3.)>\n\n    >>> sc = SkyCoord([1,2,3]*u.deg, [4,5,6]*u.deg, [5,6,7]*u.km,\n    ...               obstime=\"2010/01/01T00:00:45\",\n    ...               observer=\"self\",\n    ...               frame=\"heliographic_carrington\")\n    >>> sc\n    <SkyCoord (HeliographicCarrington: obstime=2010-01-01T00:00:45.000, rsun=695700.0 km, observer=self): (lon, lat, radius) in (deg, deg, km)\n        [(1., 4., 5.), (2., 5., 6.), (3., 6., 7.)]>\n\n    >>> sc = SkyCoord(CartesianRepresentation(0*u.km, 45*u.km, 2*u.km),\n    ...               obstime=\"2011/01/05T00:00:50\",\n    ...               frame=\"heliographic_carrington\")\n    >>> sc\n    <SkyCoord (HeliographicCarrington: obstime=2011-01-05T00:00:50.000, rsun=695700.0 km, observer=None): (lon, lat, radius) in (deg, deg, km)\n        (90., 2.54480438, 45.04442252)>\n    \"\"\"\n    name = \"heliographic_carrington\"\n    _wrap_angle = 360*u.deg\n\n    observer = ObserverCoordinateAttribute(HeliographicStonyhurst)\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        if not isinstance(self.observer, BaseCoordinateFrame) and self.observer == 'self' and self._is_2d:\n            raise ValueError(\"Full 3D coordinate (including radius) must be specified \"\n                             \"when observer='self'.\")\n\n\n@add_common_docstring(**_frame_parameters())\nclass Heliocentric(SunPyBaseCoordinateFrame):\n    \"\"\"\n    A coordinate or frame in the Heliocentric system, which is observer-based.\n\n    - The origin is the center of the Sun.\n    - The Z-axis is aligned with the Sun-observer line.\n    - The Y-axis is aligned with the component of the vector to the Sun's north pole that is\n      perpendicular to the Z-axis.\n\n    This frame defaults to a Cartesian component representation, which is known as Heliocentric\n    Cartesian (HCC).  This frame can also be represented using cylindrical components, where\n    where ``rho`` is the impact parameter and ``psi`` is the position angle.\n    ``psi`` is measured relative to the west limb, rather than solar north, so is shifted\n    by 90 degrees compared to the convention of the Heliocentric Radial (HCR) system.\n\n    A new instance can be created using the following signatures\n    (note that if supplied, ``obstime``, ``observer``, and ``representation_type`` must be\n    keyword arguments)::\n\n        Heliocentric(x, y, z, obstime=obstime, observer=observer)\n        Heliocentric(rho, psi, z, representation_type='cylindrical', obstime=obstime, observer=observer)\n\n    Parameters\n    ----------\n    {data}\n    {xyz}\n    {observer}\n    {common}\n\n    Examples\n    --------\n\n    >>> from astropy.coordinates import SkyCoord, CartesianRepresentation\n    >>> import sunpy.coordinates\n    >>> import astropy.units as u\n\n    >>> sc = SkyCoord(CartesianRepresentation(10*u.km, 1*u.km, 2*u.km),\n    ...               obstime=\"2011/01/05T00:00:50\", observer=\"earth\", frame=\"heliocentric\")\n    >>> sc\n    <SkyCoord (Heliocentric: obstime=2011-01-05T00:00:50.000, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (x, y, z) in km\n        (10., 1., 2.)>\n\n    >>> sc = SkyCoord([1,2]*u.km, [3,4]*u.m, [5,6]*u.cm,\n    ...               obstime=\"2011/01/01T00:00:54\", observer=\"earth\", frame=\"heliocentric\")\n    >>> sc\n    <SkyCoord (Heliocentric: obstime=2011-01-01T00:00:54.000, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (x, y, z) in (km, m, cm)\n        [(1., 3., 5.), (2., 4., 6.)]>\n\n    >>> sc = SkyCoord(CylindricalRepresentation(10*u.km, 60*u.deg, 10*u.km),\n    ...               obstime=\"2011/01/05T00:00:50\", observer=\"earth\", frame=\"heliocentric\")\n    >>> sc\n    <SkyCoord (Heliocentric: obstime=2011-01-05T00:00:50.000, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (x, y, z) in km\n        (5., 8.66025404, 10.)>\n    \"\"\"\n    default_representation = CartesianRepresentation\n    default_differential = CartesianDifferential\n\n    frame_specific_representation_info = {\n        CylindricalRepresentation: [RepresentationMapping('phi', 'psi', u.deg)]\n    }\n\n    observer = ObserverCoordinateAttribute(HeliographicStonyhurst)\n\n    def represent_as(self, base, s='base', in_frame_units=False):\n        data = super().represent_as(base, s, in_frame_units=in_frame_units)\n\n        # For cylindrical representations, wrap the `psi` component (natively `phi`) at 360 deg\n        if isinstance(data, CylindricalRepresentation):\n            data.phi.wrap_at(360*u.deg, inplace=True)\n        return data\n\n\n@add_common_docstring(**_frame_parameters())\nclass Helioprojective(SunPyBaseCoordinateFrame):\n    \"\"\"\n    A coordinate or frame in the Helioprojective Cartesian (HPC) system, which is observer-based.\n\n    - The origin is the location of the observer.\n    - ``Tx`` (aka \"theta_x\") is the angle relative to the plane containing the Sun-observer line\n      and the Sun's rotation axis, with positive values in the direction of the Sun's west limb.\n    - ``Ty`` (aka \"theta_y\") is the angle relative to the Sun's equatorial plane, with positive\n      values in the direction of the Sun's north pole.\n    - ``distance`` is the Sun-observer distance.\n\n    This system is frequently used in a projective form without ``distance`` specified.  For\n    observations looking very close to the center of the Sun, where the small-angle approximation\n    is appropriate, ``Tx`` and ``Ty`` can be approximated as Cartesian components.\n\n    A new instance can be created using the following signatures\n    (note that if supplied, ``obstime`` and ``observer`` must be keyword arguments)::\n\n        Helioprojective(Tx, Ty, obstime=obstime, observer=observer)\n        Helioprojective(Tx, Ty, distance, obstime=obstime, observer=observer)\n\n    Parameters\n    ----------\n    {data}\n    Tx : `~astropy.coordinates.Angle` or `~astropy.units.Quantity`\n        The theta_x coordinate for this object. Not needed if ``data`` is given.\n    Ty : `~astropy.coordinates.Angle` or `~astropy.units.Quantity`\n        The theta_y coordinate for this object. Not needed if ``data`` is given.\n    distance : `~astropy.units.Quantity`\n        The distance coordinate from the observer for this object.\n        Not needed if ``data`` is given.\n    {observer}\n    {rsun}\n    {common}\n\n    Examples\n    --------\n    >>> from astropy.coordinates import SkyCoord\n    >>> import sunpy.coordinates\n    >>> import astropy.units as u\n    >>> sc = SkyCoord(0*u.deg, 0*u.deg, 5*u.km,\n    ...               obstime=\"2010/01/01T00:00:00\", observer=\"earth\", frame=\"helioprojective\")\n    >>> sc\n    <SkyCoord (Helioprojective: obstime=2010-01-01T00:00:00.000, rsun=695700.0 km, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (Tx, Ty, distance) in (arcsec, arcsec, km)\n        (0., 0., 5.)>\n    >>> sc = SkyCoord(0*u.deg, 0*u.deg,\n    ...               obstime=\"2010/01/01T00:00:00\", observer=\"earth\", frame=\"helioprojective\")\n    >>> sc\n    <SkyCoord (Helioprojective: obstime=2010-01-01T00:00:00.000, rsun=695700.0 km, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (Tx, Ty) in arcsec\n        (0., 0.)>\n    >>> sc = SkyCoord(CartesianRepresentation(1*u.AU, 1e5*u.km, -2e5*u.km),\n    ...               obstime=\"2011/01/05T00:00:50\", observer=\"earth\", frame=\"helioprojective\")\n    >>> sc\n    <SkyCoord (Helioprojective: obstime=2011-01-05T00:00:50.000, rsun=695700.0 km, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (Tx, Ty, distance) in (arcsec, arcsec, AU)\n        (137.87948623, -275.75878762, 1.00000112)>\n    \"\"\"\n    frame_specific_representation_info = {\n        SphericalRepresentation: [RepresentationMapping('lon', 'Tx', u.arcsec),\n                                  RepresentationMapping('lat', 'Ty', u.arcsec),\n                                  RepresentationMapping('distance', 'distance', None)],\n        SphericalDifferential: [RepresentationMapping('d_lon', 'd_Tx', u.arcsec/u.s),\n                                RepresentationMapping('d_lat', 'd_Ty', u.arcsec/u.s),\n                                RepresentationMapping('d_distance', 'd_distance', u.km/u.s)],\n        UnitSphericalRepresentation: [RepresentationMapping('lon', 'Tx', u.arcsec),\n                                      RepresentationMapping('lat', 'Ty', u.arcsec)],\n    }\n\n    rsun = QuantityAttribute(default=_RSUN, unit=u.km)\n    observer = ObserverCoordinateAttribute(HeliographicStonyhurst)\n\n    @property\n    def angular_radius(self):\n        \"\"\"\n        Angular radius of the Sun as seen by the observer.\n\n        The ``rsun`` frame attribute is the radius of the Sun in length units.\n        The tangent vector from the observer to the edge of the Sun forms a\n        right-angle triangle with the radius of the Sun as the far side and the\n        Sun-observer distance as the hypotenuse. Thus, the sine of the angular\n        radius of the Sun is ratio of these two distances.\n        \"\"\"\n        from sunpy.coordinates.sun import _angular_radius  # avoiding a circular import\n\n        if not isinstance(self.observer, HeliographicStonyhurst):\n            if self.observer is None:\n                raise ValueError(\"The observer must be defined, not `None`.\")\n            raise ValueError(\"The observer must be fully defined by specifying `obstime`.\")\n        return _angular_radius(self.rsun, self.observer.radius)\n\n    def make_3d(self):\n        \"\"\"\n        This method calculates the third coordinate of the Helioprojective\n        frame. It assumes that the coordinate point is on the surface of the Sun.\n\n        If a point in the frame is off limb then NaN will be returned.\n\n        Returns\n        -------\n        new_frame : `~sunpy.coordinates.frames.Helioprojective`\n            A new frame instance with all the attributes of the original but\n            now with a third coordinate.\n        \"\"\"\n        # Skip if we already are 3D\n        if not self._is_2d:\n            return self\n\n        if not isinstance(self.observer, BaseCoordinateFrame):\n            raise ConvertError(\"Cannot calculate distance to the Sun \"\n                               f\"for observer '{self.observer}' \"\n                               \"without `obstime` being specified.\")\n\n        rep = self.represent_as(UnitSphericalRepresentation)\n        lat, lon = rep.lat, rep.lon\n\n        # Check for the use of floats with lower precision than the native Python float\n        if not set([lon.dtype.type, lat.dtype.type]).issubset([float, np.float64, np.longdouble]):\n            warn_user(\"The Helioprojective component values appear to be lower \"\n                      \"precision than the native Python float: \"\n                      f\"Tx is {lon.dtype.name}, and Ty is {lat.dtype.name}. \"\n                      \"To minimize precision loss, you may want to cast the values to \"\n                      \"`float` or `numpy.float64` via the NumPy method `.astype()`.\")\n\n        # Calculate the distance to the surface of the Sun using the law of cosines\n        cos_alpha = np.cos(lat) * np.cos(lon)\n        c = self.observer.radius**2 - self.rsun**2\n        b = -2 * self.observer.radius * cos_alpha\n        # Ignore sqrt of NaNs\n        with np.errstate(invalid='ignore'):\n            d = ((-1*b) - np.sqrt(b**2 - 4*c)) / 2  # use the \"near\" solution\n\n        if self._spherical_screen:\n            sphere_center = self._spherical_screen['center'].transform_to(self).cartesian\n            c = sphere_center.norm()**2 - self._spherical_screen['radius']**2\n            b = -2 * sphere_center.dot(rep)\n            # Ignore sqrt of NaNs\n            with np.errstate(invalid='ignore'):\n                dd = ((-1*b) + np.sqrt(b**2 - 4*c)) / 2  # use the \"far\" solution\n\n            d = np.fmin(d, dd) if self._spherical_screen['only_off_disk'] else dd\n\n        return self.realize_frame(SphericalRepresentation(lon=lon,\n                                                          lat=lat,\n                                                          distance=d))\n\n    _spherical_screen = None\n\n    @classmethod\n    @contextmanager\n    def assume_spherical_screen(cls, center, only_off_disk=False):\n        \"\"\"\n        Context manager to interpret 2D coordinates as being on the inside of a spherical screen.\n\n        The radius of the screen is the distance between the specified ``center`` and Sun center.\n        This ``center`` does not have to be the same as the observer location for the coordinate\n        frame.  If they are the same, then this context manager is equivalent to assuming that the\n        helioprojective \"zeta\" component is zero.\n\n        This replaces the default assumption where 2D coordinates are mapped onto the surface of the\n        Sun.\n\n        Parameters\n        ----------\n        center : `~astropy.coordinates.SkyCoord`\n            The center of the spherical screen\n        only_off_disk : `bool`, optional\n            If `True`, apply this assumption only to off-disk coordinates, with on-disk coordinates\n            still mapped onto the surface of the Sun.  Defaults to `False`.\n\n        Examples\n        --------\n        .. minigallery:: sunpy.coordinates.Helioprojective.assume_spherical_screen\n\n        >>> import astropy.units as u\n        >>> from sunpy.coordinates import Helioprojective\n        >>> h = Helioprojective(range(7)*u.arcsec*319, [0]*7*u.arcsec,\n        ...                     observer='earth', obstime='2020-04-08')\n        >>> print(h.make_3d())\n        <Helioprojective Coordinate (obstime=2020-04-08T00:00:00.000, rsun=695700.0 km, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (Tx, Ty, distance) in (arcsec, arcsec, AU)\n            [(   0., 0., 0.99660825), ( 319., 0., 0.99687244),\n             ( 638., 0., 0.99778472), ( 957., 0., 1.00103285),\n             (1276., 0.,        nan), (1595., 0.,        nan),\n             (1914., 0.,        nan)]>\n\n        >>> with Helioprojective.assume_spherical_screen(h.observer):\n        ...     print(h.make_3d())\n        <Helioprojective Coordinate (obstime=2020-04-08T00:00:00.000, rsun=695700.0 km, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (Tx, Ty, distance) in (arcsec, arcsec, AU)\n            [(   0., 0., 1.00125872), ( 319., 0., 1.00125872),\n             ( 638., 0., 1.00125872), ( 957., 0., 1.00125872),\n             (1276., 0., 1.00125872), (1595., 0., 1.00125872),\n             (1914., 0., 1.00125872)]>\n\n        >>> with Helioprojective.assume_spherical_screen(h.observer, only_off_disk=True):\n        ...     print(h.make_3d())\n        <Helioprojective Coordinate (obstime=2020-04-08T00:00:00.000, rsun=695700.0 km, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (Tx, Ty, distance) in (arcsec, arcsec, AU)\n            [(   0., 0., 0.99660825), ( 319., 0., 0.99687244),\n             ( 638., 0., 0.99778472), ( 957., 0., 1.00103285),\n             (1276., 0., 1.00125872), (1595., 0., 1.00125872),\n             (1914., 0., 1.00125872)]>\n        \"\"\"\n        try:\n            old_spherical_screen = cls._spherical_screen  # nominally None\n\n            center_hgs = center.transform_to(HeliographicStonyhurst(obstime=center.obstime))\n            cls._spherical_screen = {\n                'center': center,\n                'radius': center_hgs.radius,\n                'only_off_disk': only_off_disk\n            }\n            yield\n        finally:\n            cls._spherical_screen = old_spherical_screen\n\n\n@add_common_docstring(**_frame_parameters())\nclass HeliocentricEarthEcliptic(SunPyBaseCoordinateFrame):\n    \"\"\"\n    A coordinate or frame in the Heliocentric Earth Ecliptic (HEE) system.\n\n    - The origin is the center of the Sun.\n    - The X-axis (0 degrees longitude and 0 degrees latitude) is aligned with the Sun-Earth line.\n    - The Z-axis (+90 degrees latitude) is aligned with the component perpendicular to the X-axis\n      of the mean ecliptic pole at the observation time.\n\n    Parameters\n    ----------\n    {data}\n    {lonlat}\n    {distance_sun}\n    {common}\n    \"\"\"\n\n\n@add_common_docstring(**_frame_parameters())\nclass GeocentricSolarEcliptic(SunPyBaseCoordinateFrame):\n    \"\"\"\n    A coordinate or frame in the Geocentric Solar Ecliptic (GSE) system.\n\n    - The origin is the center of the Earth.\n    - The X-axis (0 degrees longitude and 0 degrees latitude) is aligned with the Earth-Sun line.\n    - The Z-axis (+90 degrees latitude) is aligned with the component perpendicular to the X-axis\n      of the mean ecliptic pole at the observation time.\n\n    Parameters\n    ----------\n    {data}\n    {lonlat}\n    {distance_earth}\n    {common}\n\n    Notes\n    -----\n    Aberration due to Earth motion is not included.\n    \"\"\"\n\n\n@add_common_docstring(**_frame_parameters())\nclass HeliocentricInertial(SunPyBaseCoordinateFrame):\n    \"\"\"\n    A coordinate or frame in the Heliocentric Inertial (HCI) system.\n\n    - The origin is the center of the Sun.\n    - The Z-axis (+90 degrees latitude) is aligned with the Sun's north pole.\n    - The X-axis (0 degrees longitude and 0 degrees latitude) is aligned with the solar ascending\n      node on the ecliptic (mean J2000.0).\n\n    Parameters\n    ----------\n    {data}\n    {lonlat}\n    {distance_sun}\n    {common}\n\n    Notes\n    -----\n    The solar ascending node on the ecliptic lies on the intersection of the solar equatorial\n    plane with the ecliptic plane, not on the intersection of the celestial equatorial plane with\n    the ecliptic plane.\n    \"\"\"\n\n\n@add_common_docstring(**_frame_parameters())\nclass GeocentricEarthEquatorial(SunPyBaseCoordinateFrame):\n    \"\"\"\n    A coordinate or frame in the Geocentric Earth Equatorial (GEI) system.\n\n    - The origin is the center of the Earth.\n    - The Z-axis (+90 degrees latitude) is aligned with the Earth's north pole.\n    - The X-axis (0 degrees longitude and 0 degrees latitude) is aligned with the mean (not true)\n      vernal equinox.\n\n    Parameters\n    ----------\n    {data}\n    {lonlat}\n    {distance_earth}\n    {equinox}\n    {common}\n\n    Notes\n    -----\n    Aberration due to Earth motion is not included.\n    \"\"\"\n    equinox = TimeFrameAttributeSunPy(default=_J2000)\n", "meta": {"hexsha": "54da0ae96fcdc260383b8948a94e81d91048ebba", "size": 34323, "ext": "py", "lang": "Python", "max_stars_repo_path": "sunpy/coordinates/frames.py", "max_stars_repo_name": "Octaves0911/sunpy", "max_stars_repo_head_hexsha": "d3dff03fe6cc404e40f22da90200ffbb3d38c1a7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sunpy/coordinates/frames.py", "max_issues_repo_name": "Octaves0911/sunpy", "max_issues_repo_head_hexsha": "d3dff03fe6cc404e40f22da90200ffbb3d38c1a7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sunpy/coordinates/frames.py", "max_forks_repo_name": "Octaves0911/sunpy", "max_forks_repo_head_hexsha": "d3dff03fe6cc404e40f22da90200ffbb3d38c1a7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.5816733068, "max_line_length": 189, "alphanum_fraction": 0.629694374, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 8538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.19401007745091106}}
{"text": "\"\"\"Given (x,wave,matrices, slit_profile), extract the flux from each order. For \nreadability, we keep this separate from the simulator.... but the simulator is\nrequired in order to run this.\n\nTo run, create a simulated fits file (e.g. \"test_blue.fits\") using ghost module then:\n\nblue_high = pymfe.Extractor(pymfe.ghost.Arm('blue', 'high'))\n\nflux,var = blue_high.two_d_extract(\"test_blue.fits\")\n\nplt.plot(blue_high.w_map[0,:], flux[0,:,0])\n\n\"\"\"\n\nfrom __future__ import division, print_function\nimport numpy as np\nimport matplotlib.pyplot as plt\ntry: \n    import pyfits\nexcept:\n    import astropy.io.fits as pyfits\nimport pdb\nfrom astropy.modeling import models, fitting\nimport matplotlib.cm as cm\n\nclass Extractor():\n    \"\"\"A class for each arm of the spectrograph. The initialisation function takes a \n    single string representing the configuration. For GHOST, it can be \"red\" or \"blue\".\n    \n    The extraction is defined by 3 key parameters: an \"x_map\", which is equivalent to\n    2dFDR's tramlines and contains a physical x-coordinate for every y (dispersion direction)\n    coordinate and order, and a \"w_map\", which is the wavelength corresponding to every y\n    (dispersion direction) coordinate and order. \n    \n    sim must include:\n    \n    spectral_format_with_matrix()\n    make_lenslets(fluxes)\n    \n    fluxes (nlenslets x nobj) array\n    nl (nlenslets)\n    szx (size in x [non-dispersion] direction)\n    mode (string,for error messages)\n    lenslet_width, im_slit_sz, microns_pix (together define the make_lenslets output)\n    \"\"\"\n    \n    def __init__(self,sim,transpose_data=True,badpixmask=[]):\n        self.sim = sim\n        self.transpose_data=transpose_data\n        self.badpixmask = badpixmask\n        self.x_map,self.w_map,self.blaze,self.matrices = self.sim.spectral_format_with_matrix()\n        #Fill in the slit dimensions in \"simulator pixel\"s. based on if we are in the \n        #high or standard resolution mode.\n        self.define_profile(sim.fluxes)\n            \n        #Set some default pixel offsets for each lenslet, as used for a square lenslet profile\n        ny = self.x_map.shape[1]\n        nm = self.x_map.shape[0]\n        pix_offset_ix = np.append(np.append([0],np.arange(1,sim.nl).repeat(2)),sim.nl)\n        self.square_offsets = np.empty( (2*sim.nl,nm) )\n        # The [0,0] component of \"matrices\" measures the size of a detector pixel in the \n        # simulated slit image space. i.e. slitmicrons/detpix.\n        for i in range(sim.nl):\n            self.square_offsets[:,i] = (pix_offset_ix - sim.nl/2.0) * sim.lenslet_width / self.matrices[i,self.x_map.shape[1]//2,0,0]\n        self.sim_offsets = np.empty( (self.sim.im_slit_sz,nm) )\n        #Creat an array of slit positions in microns. !!! Add an optional offset to this, i.e. a 1D offset !!!\n        im_slit_pix_in_microns = (np.arange(self.sim.im_slit_sz) - self.sim.im_slit_sz/2.0) * self.sim.microns_pix\n        for i in range(nm):\n            self.sim_offsets[:,i] = im_slit_pix_in_microns / self.matrices[i,self.x_map.shape[1]//2,0,0]\n        #To aid in 2D extraction, let's explicitly compute the y offsets corresponding to these x offsets...\n        #The \"matrices\" map pixels back to slit co-ordinates. \n        self.slit_tilt = np.zeros( (nm,ny) )\n        for i in range(nm):\n            for j in range(ny):\n                invmat = np.linalg.inv( self.matrices[i,j] )\n                #What happens to the +x direction?\n                x_dir_map = np.dot(invmat,[1,0])\n                self.slit_tilt[i,j] = x_dir_map[1]/x_dir_map[0]\n        \n    def define_profile(self,fluxes):\n        \"\"\" Manually define the slit profile as used in lenslet extraction. As this is\n        a low-level function, all lenslets must be defined. e.g. by convention, for the\n        star lenslets of the high resolution mode, lenslets 0,1 and 21 through 27 would \n        be zero. Also \"\"\"\n        \n        if fluxes.shape[0] != self.sim.nl:\n            print(\"Error: {0:s} resolution mode must have {1:d} lenslets\".format(self.sim.mode,self.sim.nl))\n        else:\n            self.square_profile = np.empty( (fluxes.shape[0]*2, fluxes.shape[1]) )\n            self.sim_profile = np.empty( (self.sim.im_slit_sz, fluxes.shape[1]) )\n            for i in range(fluxes.shape[1]):\n                self.square_profile[:,i] = np.array(fluxes[:,i]).repeat(2)\n                im_slit=self.sim.make_lenslets(fluxes=fluxes[:,i])\n                self.sim_profile[:,i] = np.sum(im_slit, axis=0)\n        \n    def one_d_extract(self, data=[], file='', lenslet_profile='sim', rnoise=3.0):\n        \"\"\" Extract flux by integrating down columns (the \"y\" direction), using an\n        optimal extraction method.\n        \n        Given that some of this code is in common with two_d_extract, the routines could\n        easily be merged... however that would make one_d_extract less readable.\n        \n        Parameters\n        ----------\n        data: numpy array (optional) \n            Image data, transposed so that dispersion is in the \"y\" direction. Note that\n            this is the transpose of a conventional echellogram. Either data or file\n            must be given\n            \n        file: string (optional)\n            A fits file with conventional row/column directions containing the data to be\n            extracted.\n        \n        lenslet_profile: 'square' or 'sim'\n            Shape of the profile of each fiber as used in the extraction. For a final\n            implementation, 'measured' should be a possibility. 'square' assigns each\n            pixel uniquely to a single lenslet. For testing only\n        \n        badpix: (float array, float array)\n            Output of e.g. np.where giving the bad pixel coordinates.\n        \n        rnoise: float\n            The assumed readout noise.\n        \n        WARNING: Binning not implemented yet\"\"\"\n        \n        if len(data)==0:\n            if len(file)==0:\n                print(\"ERROR: Must input data or file\")\n            else:\n                if self.transpose_data:\n                    #Transpose the data from the start.\n                    data = pyfits.getdata(file).T\n                else:\n                    data = pyfits.getdata(file)\n        \n        ny = self.x_map.shape[1]\n        nm = self.x_map.shape[0]\n        nx = self.sim.szx\n        \n        #Number of \"objects\"\n        no = self.square_profile.shape[1]\n        extracted_flux = np.zeros( (nm,ny,no) )\n        extracted_var = np.zeros( (nm,ny,no) )\n        \n        #Assuming that the data are in photo-electrons, construct a simple model for the\n        #pixel inverse variance.\n        pixel_inv_var = 1.0/(np.maximum(data,0)/self.sim.gain + rnoise**2)\n        pixel_inv_var[self.badpixmask]=0.0\n                \n        #Loop through all orders then through all y pixels.\n        for i in range(nm):\n            print(\"Extracting order: {0:d}\".format(i))\n            #Based on the profile we're using, create the local offsets and profile vectors\n            if lenslet_profile == 'square':\n                offsets = self.square_offsets[:,i]\n                profile = self.square_profile\n            elif lenslet_profile == 'sim':\n                offsets = self.sim_offsets[:,i]\n                profile = self.sim_profile\n            nx_cutout = 2*int( (np.max(offsets) - np.min(offsets))/2 ) + 2\n            phi = np.empty( (nx_cutout,no) )\n            for j in range(ny):\n                #Check for NaNs\n                if self.x_map[i,j] != self.x_map[i,j]:\n                    extracted_var[i,j,:] = np.nan\n                    continue\n                #Create our column cutout for the data and the PSF. !!! Is \"round\" correct on the next line??? \n                x_ix = int(np.round(self.x_map[i,j])) - nx_cutout//2 + np.arange(nx_cutout,dtype=int) + nx//2\n                for k in range(no):\n                    phi[:,k] = np.interp(x_ix - self.x_map[i,j] - nx//2, offsets, profile[:,k])\n                    phi[:,k] /= np.sum(phi[:,k])\n                #Deal with edge effects...\n                ww = np.where( (x_ix >= nx) | (x_ix < 0) )[0]\n                x_ix[ww]=0\n                phi[ww,:]=0.0\n                \n                #Stop here. \n#                if i==10:\n#                    pdb.set_trace()\n            \n                #Cut out our data and inverse variance.\n                col_data = data[j,x_ix]\n                col_inv_var = pixel_inv_var[j,x_ix]\n                #Fill in the \"c\" matrix and \"b\" vector from Sharp and Birchall equation 9\n                #Simplify things by writing the sum in the computation of \"b\" as a matrix\n                #multiplication. We can do this because we're content to invert the \n                #(small) matrix \"c\" here. Equation 17 from Sharp and Birchall \n                #doesn't make a lot of sense... so lets just calculate the variance in the\n                #simple explicit way.\n                col_inv_var_mat = np.reshape(col_inv_var.repeat(no), (nx_cutout,no) )\n                b_mat = phi * col_inv_var_mat\n                c_mat = np.dot(phi.T,phi*col_inv_var_mat)\n                pixel_weights = np.dot(b_mat,np.linalg.inv(c_mat))\n                extracted_flux[i,j,:] = np.dot(col_data,pixel_weights)\n                extracted_var[i,j,:] = np.dot(1.0/np.maximum(col_inv_var,1e-12),pixel_weights**2)\n                #if ((i % 5)==1) & (j==ny//2):\n                #if (i%5==1) & (j==ny//2):\n                #if (j==ny//2):\n                #    pdb.set_trace()\n                    \n        return extracted_flux, extracted_var\n        \n    def two_d_extract(self, file='', data=[], lenslet_profile='sim', rnoise=3.0, deconvolve=True):\n        \"\"\" Extract using 2D information. The lenslet model used is a collapsed profile, \n        in 1D but where we take into account the slit shear/rotation by interpolating this\n        1D slit profile to the nearest two pixels along each row (y-axis in code).\n        \n        One key difference to Sharp and Birchall is that c_kj (between equations 8 and 9)\n        is the correct normalisation for a (fictitious) 1-pixel wide PSF centered exactly\n        on a pixel, but not for a continuum. We normalise correctly for a continuum by\n        having one of the \\phi functions being one-pixel wide along the slit, and the \n        other being unbounded in the dispersion direction.\n        \n        Note that the input data has to be the transpose of a conventional echellogram\n       \n        TODO:\n        1) Neaten the approximate matrix inverse square root\n        \n        Parameters\n        ----------\n        data: numpy array (optional) \n            Image data, transposed so that dispersion is in the \"y\" direction. Note that\n            this is the transpose of a conventional echellogram. Either data or file\n            must be given\n            \n        file: string (optional)\n            A fits file with conventional row/column directions containing the data to be\n            extracted.\n        \n        lenslet_profile: 'square' or 'sim'\n            Shape of the profile of each fiber as used in the extraction. For a final\n            implementation, 'measured' should be a possibility. 'square' assigns each\n            pixel uniquely to a single lenslet. For testing only\n        \n        rnoise: float\n            The assumed readout noise.\n            \n        deconvolve: bool\n            Do we deconvolve so that neighboring extracted spectral points \n            are statistically independent? This is an approximate deconvolution (a linear \n            function of 5 neighboring pixels) so is reasonably robust. \"\"\"\n            \n        if len(data)==0:\n            if len(file)==0:\n                print(\"ERROR: Must input data or file\")\n            else:\n                #Transpose the data from the start.\n                data = pyfits.getdata(file).T\n\n        ny = self.x_map.shape[1]\n        nm = self.x_map.shape[0]\n        nx = self.sim.szx\n        \n        #Number of \"objects\"\n        no = self.square_profile.shape[1]\n        extracted_flux = np.zeros( (nm,ny,no) )\n        extracted_var = np.zeros( (nm,ny,no) )\n        extracted_covar = np.zeros( (nm,ny-1,no) )\n        \n        #Assuming that the data are in photo-electrons, construct a simple model for the\n        #pixel inverse variance.\n        pixel_inv_var = 1.0/(np.maximum(data,0) + rnoise**2)\n        pixel_inv_var[self.badpixmask]=0.0\n                \n        #Loop through all orders then through all y pixels.\n        for i in range(nm):\n            print(\"Extracting order index: {0:d}\".format(i))\n            #Based on the profile we're using, create the local offsets and profile vectors\n            if lenslet_profile == 'sim':\n                offsets = self.sim_offsets[:,i]\n                profile = self.sim_profile\n            else:\n                print(\"Only sim lenslet profile available for 2D extraction so far...\")\n                raise userwarning\n            nx_cutout = 2*int( (np.max(offsets) - np.min(offsets))/2 ) + 2\n            ny_cutout = 2*int(nx_cutout * np.nanmax(np.abs(self.slit_tilt)) / 2) + 3\n            for j in range(ny):\n                phi = np.zeros( (ny_cutout,nx_cutout,no) )\n                phi1d = np.zeros( (ny_cutout,nx_cutout,no) )\n                #Check for NaNs\n                if self.x_map[i,j] != self.x_map[i,j]:\n                    extracted_var[i,j,:] = np.nan\n                    continue\n                #Create our column cutout for the data and the PSF\n                x_ix = int(self.x_map[i,j]) - nx_cutout//2 + np.arange(nx_cutout,dtype=int) + nx//2\n                y_ix = j + np.arange(ny_cutout, dtype=int) - ny_cutout//2\n                for k in range(no):\n                    x_prof = np.interp(x_ix - self.x_map[i,j] - nx//2, offsets, profile[:,k])\n                    y_pix = (x_ix - self.x_map[i,j] - nx//2) * self.slit_tilt[i,j] + ny_cutout//2\n                    frac_y_pix = y_pix - y_pix.astype(int)\n                    subx_ix = np.arange(nx_cutout,dtype=int)\n                    phi[y_pix.astype(int),subx_ix,k] = (1-frac_y_pix)*x_prof\n                    phi[y_pix.astype(int)+1,subx_ix,k] = frac_y_pix*x_prof\n                    phi[:,:,k] /= np.sum(phi[:,:,k])  \n                    x_prof /= np.sum(x_prof)               \n                    phi1d[:,:,k] = np.tile(x_prof,ny_cutout).reshape( (ny_cutout, nx_cutout) )\n                #Deal with edge effects...\n                ww = np.where( (x_ix >= nx) | (x_ix < 0) )[0]\n                x_ix[ww]=0\n                phi[:,ww,:]=0.0\n                phi1d[:,ww,:]=0.0\n                ww = np.where( (y_ix >= ny) | (y_ix < 0) )[0]\n                y_ix[ww]=0\n                phi[ww,:,:]=0.0\n                xy = np.meshgrid(y_ix, x_ix, indexing='ij') \n                #Cut out our data and inverse variance.\n                col_data = data[xy].flatten()\n                col_inv_var = pixel_inv_var[xy].flatten()\n                #Fill in the \"c\" matrix and \"b\" vector from Sharp and Birchall equation 9\n                #Simplify things by writing the sum in the computation of \"b\" as a matrix\n                #multiplication. We can do this because we're content to invert the \n                #(small) matrix \"c\" here. Equation 17 from Sharp and Birchall \n                #doesn't make a lot of sense... so lets just calculate the variance in the\n                #simple explicit way.\n                col_inv_var_mat = np.reshape(col_inv_var.repeat(no), (ny_cutout*nx_cutout,no) )\n                phi = phi.reshape( (ny_cutout*nx_cutout,no) )\n                phi1d = phi1d.reshape( (ny_cutout*nx_cutout,no) )\n                b_mat = phi * col_inv_var_mat\n                c_mat = np.dot(phi.T,phi1d*col_inv_var_mat)\n                pixel_weights = np.dot(b_mat,np.linalg.inv(c_mat))\n#                if (j==1000):\n#                        pdb.set_trace()\n                extracted_flux[i,j,:] = np.dot(col_data,pixel_weights)\n                extracted_var[i,j,:] = np.dot(1.0/np.maximum(col_inv_var,1e-12),pixel_weights**2)\n                if (j > 0):\n                    extracted_covar[i,j-1,:] = np.dot(1.0/np.maximum(col_inv_var,1e-12),pixel_weights* \\\n                        np.roll(last_pixel_weights,-nx_cutout, axis=0))\n                last_pixel_weights = pixel_weights.copy()\n#                if (j > 591):\n#                    pdb.set_trace()\n        if (deconvolve):\n            #Create the diagonals of the matrix Q gradually, using the Taylor approximation for\n            #the matrix inverse.\n            #(Bolton and Schlegel 2009, equation 10)\n            #D = diag(C)\n            #A = D^{-1/2} (C-D) D^{-1/2}, so C = D^{1/2}(I + A)D^{1/2}\n            #Then if Q = (I - 1/2 A + 3/8 A^2) D^{-1/2}\n            #... then C^{-1} = QQ, approximately.\n            #Note that all of this effort doesn't really seem to achieve much at all in practice...\n            #an extremely marginal improvement in resolution... but at least formal pixel-to-pixel\n            #data independence is returned.\n            extracted_sig = np.sqrt(extracted_var)\n            a_diag_p1 = extracted_covar/extracted_sig[:,:-1,:]/extracted_sig[:,1:,:]\n#            a_diag_m1 = extracted_covar/extracted_var[:,1:,:]\n            Q_diag = np.ones( (nm,ny,no) )\n            Q_diag[:,:-1,:] += 3/8.0*a_diag_p1**2\n            Q_diag[:,1:,:]  += 3/8.0*a_diag_p1**2\n#            Q_diag[:,:-1,:] += 3/8.0*a_diag_p1*a_diag_m1\n#            Q_diag[:,1:,:]  += 3/8.0*a_diag_p1*a_diag_m1\n            Q_diag /= extracted_sig\n            extracted_sqrtsig = np.sqrt(extracted_sig)\n            Q_diag_p2 = 3/8.0*a_diag_p1[:,:-1,:]*a_diag_p1[:,1:,:]/extracted_sqrtsig[:,2:,:]/extracted_sqrtsig[:,:-2,:]\n#            Q_diag_m2 = 3/8.0*a_diag_m1[:,:-1,:]*a_diag_m1[:,1:,:]/extracted_sig[:,:-2,:]\n#            Q_diag_m1 = -0.5*a_diag_m1/extracted_sig[:,:-1,:]\n            Q_diag_p1 = -0.5*a_diag_p1/extracted_sqrtsig[:,1:,:]/extracted_sqrtsig[:,:-1,:]\n    #The approximation doesn't seem to be quite right, with the ~3% uncertainty on the diagonal of cinv, when there should\n    #only be a ~1% uncertainty (obtained by going to the next term in the Taylor expansion). But pretty close...\n    #Q = np.diag(Q_diag[0,:,0]) + np.diag(Q_diag_m1[0,:,0],k=-1) + np.diag(Q_diag_p1[0,:,0],k=+1) + np.diag(Q_diag_p2[0,:,0],k=+2) + np.diag(Q_diag_m2[0,:,0],k=-2)\n    #cinv_approx = np.dot(Q,Q)\n    #cinv = np.diag(extracted_var[0,:,0]) + np.diag(extracted_covar[0,:,0],k=1) + np.diag(extracted_covar[0,:,0],k=-1)\n    #cinv = np.linalg.inv(cinv)\n            #Now we have a sparse matrix with 5 terms. We need to sum down the rows, ignoring the \n            #edge pixels\n#            s_vect = Q_diag[:,2:-2,:] + Q_diag_p1[:,1:-2,:] + Q_diag_m1[:,2:-1,:] + Q_diag_p2[:,:-2,:] + Q_diag_m2[:,2:,:]\n            s_vect = Q_diag.copy()\n            s_vect[:,:-1,:] += Q_diag_p1\n            s_vect[:,:-2,:] += Q_diag_p2\n            s_vect[:,1:,:] += Q_diag_p1\n            s_vect[:,2:,:] += Q_diag_p2\n            new_var = 1.0/s_vect**2\n            new_flux = extracted_flux*Q_diag/s_vect\n            new_flux[:,:-1,:] += extracted_flux[:,1:,:]*Q_diag_p1/s_vect[:,1:,:]\n            new_flux[:,:-2,:] += extracted_flux[:,2:,:]*Q_diag_p2/s_vect[:,2:,:]\n            new_flux[:,1:,:] += extracted_flux[:,:-1,:]*Q_diag_p1/s_vect[:,:-1,:]\n            new_flux[:,2:,:] += extracted_flux[:,:-2,:]*Q_diag_p2/s_vect[:,:-2,:]\n            \n            #Fill in the Variance and Flux arrays with NaNs, so that the (not computed) edges \n            #are undefined.\n #           new_flux = np.empty_like(extracted_flux)\n #           new_var = np.empty_like(extracted_var)\n #           new_flux[:,:,:]=np.nan\n #           new_var[:,:,:]=np.nan\n            #Now fill in the arrays.\n #           new_var[:,2:-2,:] = 1.0/s_vect**2\n #           new_flux[:,2:-2,:] =  extracted_flux[:,2:-2,:]*Q_diag[:,2:-2,:]/s_vect \n            #\n #           new_flux[:,2:-2,:] += extracted_flux[:,1:-3,:]*Q_diag_p1[:,1:-2,:]/s_vect\n #           new_flux[:,2:-2,:] += extracted_flux[:,3:-1,:]*Q_diag_p1[:,2:-1,:]/s_vect\n #           new_flux[:,2:-2,:] += extracted_flux[:,:-4,:] *Q_diag_p2[:,:-2,:]/s_vect\n #           new_flux[:,2:-2,:] += extracted_flux[:,4:,:]  *Q_diag_p2[:,2:,:]/s_vect\n            \n            return new_flux, new_var\n        else:\n            return extracted_flux, extracted_var\n        \n        \n    def find_lines(self,data,arcfile='lines.txt',outfile='arclines.txt', hw=10,flat_data=[]):\n        \"\"\"Find lines near the locations of input arc lines.\n        \n        Parameters\n        ----------\n        data: numpy array\n            data array\n            \n        arcfile: string\n            file containing lines \"\"\"\n\n        #First, extract the data\n        flux,var = self.one_d_extract(data=data, rnoise=self.sim.rnoise)\n        #Read in the lines\n        lines = np.loadtxt(arcfile)\n        #Only use the first lenslet.\n        flux = flux[:,:,0]\n        ny = self.x_map.shape[1]\n        nm = self.x_map.shape[0]\n        nx = self.sim.szx\n        lines_out=[]\n        if len(flat_data)>0:\n            data_to_show = data - 0.05*flat_data\n        else:\n            data_to_show = data.copy()\n        plt.clf()\n        plt.imshow( np.arcsinh( (data_to_show-np.median(data_to_show))/1e2) , interpolation='nearest', aspect='auto', cmap=cm.gray)\n        for m_ix in range(nm):\n            w_ix = np.interp(lines,self.w_map[m_ix,:],np.arange(ny))\n            ww = np.where( (w_ix >= hw) & (w_ix < ny-hw) )[0]\n            w_ix = w_ix[ww]\n            arclines_to_fit = lines[ww]\n            for i,ix in enumerate(w_ix):\n                x = np.arange(ix-hw,ix+hw,dtype=np.int)\n                y = flux[m_ix,x]\n                y -= np.min(y) #Rough...\n                if np.max(y)< 25*self.sim.rnoise:\n                    continue\n                g_init = models.Gaussian1D(amplitude=np.max(y), mean=x[np.argmax(y)], stddev=1.5)\n                fit_g = fitting.LevMarLSQFitter()\n                g = fit_g(g_init, x, y)\n                #Wave, ypos, xpos, m, amplitude, fwhm\n                xpos = nx//2+np.interp(g.mean.value,np.arange(ny),self.x_map[m_ix])\n                ypos = g.mean.value\n                plt.plot(xpos,ix,'bx')\n                plt.plot(xpos,ypos,'rx') #!!! Maybe around the other way?\n                plt.text(xpos+10,ypos,str(arclines_to_fit[i]),color='green',fontsize=10)\n                lines_out.append( [arclines_to_fit[i],ypos,xpos,m_ix+self.sim.m_min,g.amplitude.value, g.stddev.value*2.3548] )\n        plt.axis([0,nx,ny,0])\n        lines_out = np.array(lines_out)\n        np.savetxt(outfile,lines_out,fmt='%9.4f %7.2f %7.2f %2d %7.1e %4.1f')\n        \n", "meta": {"hexsha": "8a0c2b6728a510bff40cc4bc5eaf968a33cc6975", "size": 22573, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymfe/extract.py", "max_stars_repo_name": "mikeireland/pymfe", "max_stars_repo_head_hexsha": "ce78392215bb40467a0d4efd453c2a6d062c12f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pymfe/extract.py", "max_issues_repo_name": "mikeireland/pymfe", "max_issues_repo_head_hexsha": "ce78392215bb40467a0d4efd453c2a6d062c12f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pymfe/extract.py", "max_forks_repo_name": "mikeireland/pymfe", "max_forks_repo_head_hexsha": "ce78392215bb40467a0d4efd453c2a6d062c12f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.1622222222, "max_line_length": 163, "alphanum_fraction": 0.5619988482, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 5847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.19401007366434198}}
{"text": "#!/usr/bin/env python\n\nimport copy\nfrom importlib import import_module\n\nimport numpy as np\n\nfrom openquake.hazardlib.gsim.base import GMPE\nfrom openquake.hazardlib.imt import PGA, PGV, SA\nfrom openquake.hazardlib import const\n\nfrom shakelib.conversions.imt.newmark_hall_1982 import NewmarkHall1982\nfrom shakelib.conversions.imc.boore_kishida_2017 import BooreKishida2017\nfrom shakelib.sites import Sites\n\n\nclass MultiGMPE(GMPE):\n    \"\"\"\n    Implements a GMPE that is the combination of multiple GMPEs.\n\n    To do\n\n        * Allow site to be based on a model that isn't a GMPE (e.g.,\n          Borcherdt).\n\n    \"\"\"\n\n    DEFINED_FOR_TECTONIC_REGION_TYPE = None\n    DEFINED_FOR_INTENSITY_MEASURE_TYPES = None\n    DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = None\n    DEFINED_FOR_STANDARD_DEVIATION_TYPES = None\n    REQUIRES_SITES_PARAMETERS = None\n    REQUIRES_RUPTURE_PARAMETERS = None\n    REQUIRES_DISTANCES = None\n\n    def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):\n        \"\"\"\n        See superclass `method <http://docs.openquake.org/oq-hazardlib/master/gsim/index.html#openquake.hazardlib.gsim.base.GroundShakingIntensityModel.get_mean_and_stddevs>`__.\n        \"\"\"  # noqa\n\n        # Evaluate MultiGMPE:\n        lnmu, lnsd = self.__get_mean_and_stddevs(\n            sites, rup, dists, imt, stddev_types)\n\n        # Check for large-distance cutoff/weights\n        if hasattr(self, 'CUTOFF_DISTANCE'):\n            lnmu_large, lnsd_large = self.__get_mean_and_stddevs(\n                sites, rup, dists, imt, stddev_types, large_dist=True)\n            # Stomp on lnmu and lnsd at large distances\n            dist_cutoff = self.CUTOFF_DISTANCE\n            lnmu[dists.rjb > dist_cutoff] = lnmu_large[dists.rjb > dist_cutoff]\n            for i in range(len(lnsd)):\n                lnsd[i][dists.rjb > dist_cutoff] = \\\n                    lnsd_large[i][dists.rjb > dist_cutoff]\n\n        return lnmu, lnsd\n\n    def __get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types,\n                               large_dist=False):\n\n        # ---------------------------------------------------------------------\n        # Sort out which set of weights to use\n        # ---------------------------------------------------------------------\n        if large_dist is False:\n            wts = self.WEIGHTS\n        else:\n            wts = self.WEIGHTS_LARGE_DISTANCE\n\n        # ---------------------------------------------------------------------\n        # Sort out shapes of sites and dists elements\n        # ---------------------------------------------------------------------\n\n        shapes = []\n        for k, v in sites.__dict__.items():\n            if (k is not 'lons') and (k is not 'lats'):\n                shapes.append(v.shape)\n        for k, v in dists.__dict__.items():\n            if (k is not 'lons') and (k is not 'lats'):\n                shapes.append(v.shape)\n\n        shapeset = set(shapes)\n        if len(shapeset) != 1:\n            raise Exception(\n                'All sites and dists elements must have same shape.')\n        else:\n            orig_shape = list(shapeset)[0]\n\n        # Need to turn all 2D arrays into 1D arrays because of\n        # inconsistencies in how arrays are handled in OpenQuake.\n        for k, v in dists.__dict__.items():\n            if (k is not 'lons') and (k is not 'lats'):\n                dists.__dict__[k] = np.reshape(dists.__dict__[k], (-1,))\n        for k, v in sites.__dict__.items():\n            if (k is not 'lons') and (k is not 'lats'):\n                sites.__dict__[k] = np.reshape(sites.__dict__[k], (-1,))\n\n        # ---------------------------------------------------------------------\n        # These are arrays to hold the weighted combination of the GMPEs\n        # ---------------------------------------------------------------------\n        lnmu = np.zeros_like(sites.vs30)\n        sd_avail = self.DEFINED_FOR_STANDARD_DEVIATION_TYPES\n        if not sd_avail.issuperset(set(stddev_types)):\n            raise Exception(\"Requested an unavailable stddev_type.\")\n\n        lnsd2 = [np.zeros_like(sites.vs30) for a in stddev_types]\n\n        for i in range(len(self.GMPES)):\n            # -----------------------------------------------------------------\n            # Loop over GMPE list\n            # -----------------------------------------------------------------\n\n            gmpe = self.GMPES[i]\n\n            sites = MultiGMPE.set_sites_depth_parameters(sites, gmpe)\n\n            # -----------------------------------------------------------------\n            # Evaluate GMPEs\n            # -----------------------------------------------------------------\n\n            gmpe_imts = [imt.__name__ for imt in\n                         gmpe.DEFINED_FOR_INTENSITY_MEASURE_TYPES]\n            if (isinstance(imt, PGV)) and (\"PGV\" not in gmpe_imts):\n                # -------------------------------------------------------------\n                # If IMT is PGV and PGV is not given by the GMPE, then\n                # convert from PSA10.\n                # -------------------------------------------------------------\n                if self.HAS_SITE[i] is True:\n                    psa10, psa10sd = gmpe.get_mean_and_stddevs(\n                        sites, rup, dists, SA(1.0), stddev_types)\n                else:\n                    lamps = self.get_site_factors(\n                        sites, rup, dists, SA(1.0), default=True)\n                    psa10, psa10sd = gmpe.get_mean_and_stddevs(\n                        sites, rup, dists, SA(1.0), stddev_types)\n                    psa10 = psa10 + lamps\n\n                lmean, lsd = NewmarkHall1982.psa102pgv(psa10, psa10sd[0])\n            else:\n                if self.HAS_SITE[i] is True:\n                    lmean, lsd = gmpe.get_mean_and_stddevs(\n                        sites, rup, dists, imt, stddev_types)\n                else:\n                    lamps = self.get_site_factors(\n                        sites, rup, dists, imt, default=True)\n                    lmean, lsd = gmpe.get_mean_and_stddevs(\n                        sites, rup, dists, imt, stddev_types)\n                    lmean = lmean + lamps\n\n            # -----------------------------------------------------------------\n            # Convertions due to component definition\n            # -----------------------------------------------------------------\n\n            imc_in = gmpe.DEFINED_FOR_INTENSITY_MEASURE_COMPONENT\n            imc_out = self.DEFINED_FOR_INTENSITY_MEASURE_COMPONENT\n            bk17 = BooreKishida2017(imc_in, imc_out)\n            lmean = bk17.convertAmps(imt, lmean, dists.rrup, rup.mag)\n            #\n            # The extra sigma from the component conversion appears to \n            # apply to the total sigma, so the question arises as to\n            # how to apportion it between the intra- and inter-event\n            # sigma. Here we assume it all enters as intra-event sigma.\n            # \n            for j in range(len(lnsd2)):\n                if stddev_types[j] == const.StdDev.INTER_EVENT:\n                    continue\n                lsd[j] = bk17.convertStddevs(imt, lsd[j], dists.rrup, rup.mag)\n\n            # -----------------------------------------------------------------\n            # Compute weighted mean and sd\n            # -----------------------------------------------------------------\n\n            lnmu = lnmu + wts[i] * lmean\n\n            # Note: the lnsd2 calculation isn't complete until we drop out of\n            # this loop and substract lnmu**2\n            for j in range(len(lnsd2)):\n                lnsd2[j] = lnsd2[j] + wts[i] * (lmean**2 + lsd[j]**2)\n\n        for j in range(len(lnsd2)):\n            lnsd2[j] = lnsd2[j] - lnmu**2\n\n        lnsd = [np.sqrt(a) for a in lnsd2]\n\n        # Undo reshapes of inputs\n        for k, v in dists.__dict__.items():\n            if (k is not 'lons') and (k is not 'lats'):\n                dists.__dict__[k] = np.reshape(dists.__dict__[k], orig_shape)\n        for k, v in sites.__dict__.items():\n            if (k is not 'lons') and (k is not 'lats'):\n                sites.__dict__[k] = np.reshape(sites.__dict__[k], orig_shape)\n\n        # Reshape output\n        lnmu = np.reshape(lnmu, orig_shape)\n        for i in range(len(lnsd)):\n            lnsd[i] = np.reshape(lnsd[i], orig_shape)\n\n        return lnmu, lnsd\n\n    @classmethod\n    def from_config(cls, conf, filter_imt=None, verbose=False):\n        \"\"\"\n        Construct a MultiGMPE from a config file.\n\n        Args:\n            conf (dict): Dictionary of config options.\n            filter_imt (IMT): An optional IMT to filter/reweight the GMPE list.\n            verbose (bool): Print verbose output for debugging.\n\n        Returns:\n            MultiGMPE object.\n\n        \"\"\"\n        IMC = getattr(const.IMC, conf['interp']['component'])\n        selected_gmpe = conf['modeling']['gmpe']\n\n        if verbose is True:\n            print('selected_gmpe: %s' % selected_gmpe)\n            print('IMC: %s' % IMC)\n\n        # ---------------------------------------------------------------------\n        # Allow for selected_gmpe to be found in either conf['gmpe_sets'] or\n        # conf['gmpe_modules'], if it is a GMPE set, then all entries must be\n        # either a GMPE or a GMPE set (cannot have a GMPE set that is a mix of\n        # GMPEs and GMPE sets).\n        # ---------------------------------------------------------------------\n\n        if selected_gmpe in conf['gmpe_sets'].keys():\n            selected_gmpe_sets = conf['gmpe_sets'][selected_gmpe]['gmpes']\n            gmpe_set_weights = \\\n                [float(w) for w in conf['gmpe_sets'][selected_gmpe]['weights']]\n            if verbose is True:\n                print('selected_gmpe_sets: %s' % selected_gmpe_sets)\n                print('gmpe_set_weights: %s' % gmpe_set_weights)\n\n            # -----------------------------------------------------------------\n            # If it is a GMPE set, does it contain GMPEs or GMPE sets?\n            # -----------------------------------------------------------------\n\n            set_of_gmpes = all([s in conf['gmpe_modules'] for s in\n                                selected_gmpe_sets])\n            set_of_sets = all([s in conf['gmpe_sets'] for s in\n                               selected_gmpe_sets])\n\n            if set_of_sets is True:\n                mgmpes = []\n                for s in selected_gmpe_sets:\n                    mgmpes.append(cls.__multigmpe_from_gmpe_set(\n                        conf, s, filter_imt=filter_imt, verbose=verbose))\n                out = MultiGMPE.from_list(mgmpes, gmpe_set_weights, imc=IMC)\n            elif set_of_gmpes is True:\n                out = cls.__multigmpe_from_gmpe_set(\n                    conf,\n                    selected_gmpe,\n                    filter_imt=filter_imt,\n                    verbose=verbose)\n            else:\n                raise Exception(\"%s must consist exclusively of keys in \"\n                                \"conf['gmpe_modules'] or conf['gmpe_sets']\"\n                                % selected_gmpe)\n        elif selected_gmpe in conf['gmpe_modules'].keys():\n            modinfo = conf['gmpe_modules'][selected_gmpe]\n            mod = import_module(modinfo[1])\n            tmpclass = getattr(mod, modinfo[0])\n            out = MultiGMPE.from_list([tmpclass()], [1.0], imc=IMC)\n        else:\n            raise Exception(\"conf['modeling']['gmpe'] must be a key in \"\n                            \"conf['gmpe_modules'] or conf['gmpe_sets']\")\n\n        out.DESCRIPTION = selected_gmpe\n        return out\n\n    def __multigmpe_from_gmpe_set(conf, set_name, filter_imt=None,\n                                 verbose=False):\n        \"\"\"\n        Private method for constructing a MultiGMPE from a set_name.\n\n        Args:\n            conf (ConfigObj): A ShakeMap config object.\n            filter_imt (IMT): An optional IMT to filter/reweight the GMPE list.\n            set_name (str): Set name; must correspond to a key in\n                conf['set_name'].\n\n        Returns:\n            MultiGMPE.\n\n        \"\"\"\n        IMC = getattr(const.IMC, conf['interp']['component'])\n\n        selected_gmpes = conf['gmpe_sets'][set_name]['gmpes']\n        selected_gmpe_weights = \\\n            [float(w) for w in conf['gmpe_sets'][set_name]['weights']]\n\n        # Check for large distance GMPEs\n        if 'weights_large_dist' in conf['gmpe_sets'][set_name].keys():\n            if not conf['gmpe_sets'][set_name]['weights_large_dist']:\n                selected_weights_large_dist = None\n            else:\n                selected_weights_large_dist = \\\n                    [float(w) for w in\n                     conf['gmpe_sets'][set_name]['weights_large_dist']]\n        else:\n            selected_weights_large_dist = None\n\n        if 'dist_cutoff' in conf['gmpe_sets'][set_name].keys():\n            if np.isnan(conf['gmpe_sets'][set_name]['dist_cutoff']):\n                selected_dist_cutoff = None\n            else:\n                selected_dist_cutoff = \\\n                    float(conf['gmpe_sets'][set_name]['dist_cutoff'])\n        else:\n            selected_dist_cutoff = None\n\n        if 'site_gmpes' in conf['gmpe_sets'][set_name].keys():\n            if not conf['gmpe_sets'][set_name]['site_gmpes']:\n                selected_site_gmpes = None\n            else:\n                selected_site_gmpes = \\\n                    conf['gmpe_sets'][set_name]['site_gmpes']\n        else:\n            selected_site_gmpes = None\n\n        if 'weights_site_gmpes' in conf['gmpe_sets'][set_name].keys():\n            if not conf['gmpe_sets'][set_name]['weights_site_gmpes']:\n                selected_weights_site_gmpes = None\n            else:\n                selected_weights_site_gmpes = \\\n                    conf['gmpe_sets'][set_name]['weights_site_gmpes']\n        else:\n            selected_weights_site_gmpes = None\n\n        # ---------------------------------------------------------------------\n        # Import GMPE modules and initialize classes into list\n        # ---------------------------------------------------------------------\n        gmpes = []\n        for g in selected_gmpes:\n            mod = import_module(conf['gmpe_modules'][g][1])\n            tmpclass = getattr(mod, conf['gmpe_modules'][g][0])\n            gmpes.append(tmpclass())\n\n        # ---------------------------------------------------------------------\n        # Filter out GMPEs not applicable to this period\n        # ---------------------------------------------------------------------\n        if filter_imt is not None:\n            filtered_gmpes, filtered_wts = filter_gmpe_list(\n                gmpes, selected_gmpe_weights, filter_imt)\n        else:\n            filtered_gmpes, filtered_wts = gmpes, selected_gmpe_weights\n\n        # ---------------------------------------------------------------------\n        # Import site GMPEs\n        # ---------------------------------------------------------------------\n        if selected_site_gmpes is not None:\n            if isinstance(selected_site_gmpes, str):\n                selected_site_gmpes = [selected_site_gmpes]\n            site_gmpes = []\n            for g in selected_site_gmpes:\n                mod = import_module(conf['gmpe_modules'][g][1])\n                tmpclass = getattr(mod, conf['gmpe_modules'][g][0])\n                site_gmpes.append(tmpclass())\n        else:\n            site_gmpes = None\n\n        # ---------------------------------------------------------------------\n        # Filter out site GMPEs not applicable to this period\n        # ---------------------------------------------------------------------\n        if site_gmpes is not None:\n            if filter_imt is not None:\n                filtered_site_gmpes, filtered_site_wts = filter_gmpe_list(\n                    site_gmpes, selected_weights_site_gmpes, filter_imt)\n            else:\n                filtered_site_gmpes = copy.copy(site_gmpes)\n                filtered_site_wts = copy.copy(selected_weights_site_gmpes)\n        else:\n            filtered_site_gmpes = None\n            filtered_site_wts = None\n\n        # ---------------------------------------------------------------------\n        # Construct MultiGMPE\n        # ---------------------------------------------------------------------\n        if verbose is True:\n            print('    filtered_gmpes: %s' % filtered_gmpes)\n            print('    filtered_wts: %s' % filtered_wts)\n\n        mgmpe = MultiGMPE.from_list(\n            filtered_gmpes, filtered_wts,\n            default_gmpes_for_site=filtered_site_gmpes,\n            default_gmpes_for_site_weights=filtered_site_wts,\n            imc=IMC)\n\n        # ---------------------------------------------------------------------\n        # Append large-distance info if specified\n        # ---------------------------------------------------------------------\n        if selected_dist_cutoff is not None:\n            if filter_imt is not None:\n                filtered_gmpes_ld, filtered_wts_ld = filter_gmpe_list(\n                    gmpes, selected_weights_large_dist, filter_imt)\n            else:\n                filtered_wts_ld = copy.copy(selected_weights_large_dist)\n\n            mgmpe.CUTOFF_DISTANCE = copy.copy(selected_dist_cutoff)\n            mgmpe.WEIGHTS_LARGE_DISTANCE = copy.copy(filtered_wts_ld)\n\n        return mgmpe\n\n    @classmethod\n    def from_list(cls, gmpes, weights,\n                  imc=const.IMC.GREATER_OF_TWO_HORIZONTAL,\n                  default_gmpes_for_site=None,\n                  default_gmpes_for_site_weights=None,\n                  reference_vs30=760):\n        \"\"\"\n        Construct a MultiGMPE instance from lists of GMPEs and weights.\n\n        Args:\n            gmpes (list): List of OpenQuake\n                `GMPE <http://docs.openquake.org/oq-hazardlib/master/gsim/index.html#built-in-gsims>`__\n                instances.\n\n            weights (list): List of weights; must sum to 1.0.\n\n            imc: Requested intensity measure component. Must be one listed\n                `here <http://docs.openquake.org/oq-hazardlib/master/const.html?highlight=imc#openquake.hazardlib.const.IMC>`__.\n                The amplitudes returned by the GMPEs will be converted to this\n                IMT. Default is 'GREATER_OF_TWO_HORIZONTAL', which is used by\n                ShakeMap. See discussion in\n                `this section <http://usgs.github.io/shakemap/tg_choice_of_parameters.html#use-of-peak-values-rather-than-mean>`__\n                of the ShakeMap manual.\n\n            default_gmpes_for_site (list):\n                Optional list of OpenQuake GMPE instance to use as a site term\n                for any of the GMPEs that do not have a site term.\n\n                Notes:\n\n                    * We do not check for consistency in the reference rock\n                      defintion, so the user nees to be aware of this issue and\n                      holds responsibiilty for ensuring compatibility.\n                    * We check whether or not a GMPE has a site term by c\n                      hecking the REQUIRES_SITES_PARAMETERS slot for vs30.\n\n            default_gmpes_for_site_weights: Weights for default_gmpes_for_site.\n                Must sum to one and be same length as default_gmpes_for_site.\n                If None, then weights are set to be equal.\n\n            reference_vs30:\n                Reference rock Vs30 in m/s. We do not check that this matches\n                the reference rock in the GMPEs so this is the responsibility\n                of the user.\n\n        \"\"\"  # noqa\n\n        # ---------------------------------------------------------------------\n        # Check that GMPE weights sum to 1.0:\n        # ---------------------------------------------------------------------\n\n        if np.abs(np.sum(weights) - 1.0) > 1e-7:\n            raise Exception('Weights must sum to one.')\n\n        # ---------------------------------------------------------------------\n        # Check that length of GMPE weights equals length of gmpe list\n        # ---------------------------------------------------------------------\n\n        if len(weights) != len(gmpes):\n            raise Exception(\n                'Length of weights must match length of GMPE list.')\n\n        # ---------------------------------------------------------------------\n        # Check that gmpes is a list of OQ GMPE instances\n        # ---------------------------------------------------------------------\n\n        for g in gmpes:\n            if not isinstance(g, GMPE):\n                raise Exception(\"\\\"%s\\\" is not a GMPE instance.\" % g)\n\n        self = cls()\n        self.GMPES = gmpes\n        self.WEIGHTS = weights\n\n        # ---------------------------------------------------------------------\n        # Combine the intensity measure types. This is problematic:\n        #   - Logically, we should only include the intersection of the sets\n        #     of imts for the different GMPEs.\n        #   - In practice, this is not feasible because most GMPEs in CEUS and\n        #     subduction zones do not have PGV.\n        #   - So instead we will use the union of the imts and then convert\n        #     to get the missing imts later in get_mean_and_stddevs.\n        # ---------------------------------------------------------------------\n\n        imts = [g.DEFINED_FOR_INTENSITY_MEASURE_TYPES for g in gmpes]\n        self.DEFINED_FOR_INTENSITY_MEASURE_TYPES = set.union(*imts)\n\n        # ---------------------------------------------------------------------\n        # For VirtualIPE class, we also want to know if ALL of the GMPEs are\n        # defined for PGV, in which case we will convert from PGV to MI,\n        # otherwise use PGA or Sa.\n        # ---------------------------------------------------------------------\n        haspgv = [PGV in g.DEFINED_FOR_INTENSITY_MEASURE_TYPES for g in gmpes]\n        self.ALL_GMPES_HAVE_PGV = all(haspgv)\n\n        # ---------------------------------------------------------------------\n        # Store intensity measure types for conversion in get_mean_and_stddevs.\n        # ---------------------------------------------------------------------\n        self.IMCs = [g.DEFINED_FOR_INTENSITY_MEASURE_COMPONENT for g in gmpes]\n\n        # ---------------------------------------------------------------------\n        # Store the component\n        # ---------------------------------------------------------------------\n        self.DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = imc\n\n        # ---------------------------------------------------------------------\n        # Intersection of GMPE standard deviation types\n        # ---------------------------------------------------------------------\n        stdlist = [set(g.DEFINED_FOR_STANDARD_DEVIATION_TYPES) for g in gmpes]\n        self.DEFINED_FOR_STANDARD_DEVIATION_TYPES = \\\n            set.intersection(*stdlist)\n\n        # ---------------------------------------------------------------------\n        # Need union of site parameters, but it is complicated by the\n        # different depth parameter flavors.\n        # ---------------------------------------------------------------------\n        sitepars = [g.REQUIRES_SITES_PARAMETERS for g in gmpes]\n        self.REQUIRES_SITES_PARAMETERS = set.union(*sitepars)\n\n        # ---------------------------------------------------------------------\n        # Construct a list of whether or not each GMPE has a site term\n        # ---------------------------------------------------------------------\n        self.HAS_SITE = ['vs30' in g.REQUIRES_SITES_PARAMETERS for g in gmpes]\n\n        # ---------------------------------------------------------------------\n        # Checks and sort out defaults\n        # ---------------------------------------------------------------------\n\n        # things to check if default_gmpes_for_site is provided\n        if default_gmpes_for_site is not None:\n            # check that default_gmpe_for_site are OQ GMPEs or None\n            for g in default_gmpes_for_site:\n                if not isinstance(g, GMPE):\n                    raise Exception(\"\\\"%s\\\" is not a GMPE instance.\" % g)\n\n            # apply default weights if necessary\n            if default_gmpes_for_site_weights is None:\n                n = len(default_gmpes_for_site)\n                default_gmpes_for_site_weights = [1 / n] * n\n\n        # Things to check if one or more GMPE does not have a site term\n        if not all(self.HAS_SITE):\n            # Raise an exception if no default site is provided\n            if default_gmpes_for_site is None:\n                raise Exception('Must provide default_gmpes_for_site if one or'\n                                ' more GMPE does not have site term.')\n\n            # If weights are unspecified, use equal weight\n            if default_gmpes_for_site_weights is None:\n                default_gmpes_for_site_weights = \\\n                    [1 / len(default_gmpes_for_site)] * \\\n                    len(default_gmpes_for_site)\n\n            # check that length of default_gmpe_for_site matches length of\n            # default_gmpe_for_site_weights\n            if len(default_gmpes_for_site_weights) != \\\n               len(default_gmpes_for_site):\n                raise Exception('Length of default_gmpes_for_site_weights '\n                                'must match length of default_gmpes_for_site '\n                                'list.')\n\n            # check weights sum to one if needed\n            if not all(self.HAS_SITE):\n                if np.sum(default_gmpes_for_site_weights) != 1.0:\n                    raise Exception('default_gmpes_for_site_weights must sum'\n                                    ' to one.')\n\n        # Note: if ALL of the GMPEs do not have a site term (requiring Vs30),\n        #       then REQUIRES_SITES_PARAMETERS for the MultiGMPE will not\n        #       include Vs30 even though it will be needed to compute the\n        #       default site term. So if the site checks have passed to this\n        #       point, we should add Vs30 to the set of required site pars:\n        self.REQUIRES_SITES_PARAMETERS = set.union(\n            self.REQUIRES_SITES_PARAMETERS, set(['vs30']))\n\n        self.DEFAULT_GMPES_FOR_SITE = default_gmpes_for_site\n        self.DEFAULT_GMPES_FOR_SITE_WEIGHTS = default_gmpes_for_site_weights\n        self.REFERENCE_VS30 = reference_vs30\n\n        # ---------------------------------------------------------------------\n        # Union of rupture parameters\n        # ---------------------------------------------------------------------\n        ruppars = [g.REQUIRES_RUPTURE_PARAMETERS for g in gmpes]\n        self.REQUIRES_RUPTURE_PARAMETERS = set.union(*ruppars)\n\n        # ---------------------------------------------------------------------\n        # Union of distance parameters\n        # ---------------------------------------------------------------------\n        distpars = [g.REQUIRES_DISTANCES for g in gmpes]\n        self.REQUIRES_DISTANCES = set.union(*distpars)\n\n        return self\n\n    def get_site_factors(self, sites, rup, dists, imt, default=False):\n        \"\"\"\n        Method for computing site amplification factors from the defalut GMPE\n        to be applied to GMPEs which do not have a site term.\n\n        **NOTE** Amps are calculated in natural log units and so the ln(amp)\n        is returned.\n\n        Args:\n            sites (SitesContext): Instance of SitesContext.\n            rup (RuptureContext): Instance of RuptureContext.\n            dists (DistancesContext): Instance of DistancesContext.\n            imt: An instance openquake.hazardlib.imt.\n            default (bool): Boolean of whether or not to return the\n                amplificaiton factors for the gmpes or default_gmpes_for_site.\n                This argument is primarily only intended to be used internally\n                for when we just need to access the default amplifications to\n                apply to those GMPEs that do not have site terms.\n\n        Returns:\n            Site amplifications in natural log units.\n        \"\"\"\n\n        # ---------------------------------------------------------------------\n        # Make reference sites context\n        # ---------------------------------------------------------------------\n\n        ref_sites = copy.deepcopy(sites)\n        ref_sites.vs30 = np.ones_like(sites.vs30) * self.REFERENCE_VS30\n\n        # ---------------------------------------------------------------------\n        # If default True, construct new MultiGMPE with default GMPE/weights\n        # ---------------------------------------------------------------------\n        if default is True:\n            tmp = MultiGMPE.from_list(\n                self.DEFAULT_GMPES_FOR_SITE,\n                self.DEFAULT_GMPES_FOR_SITE_WEIGHTS,\n                self.DEFINED_FOR_INTENSITY_MEASURE_COMPONENT)\n\n        # ---------------------------------------------------------------------\n        # If default False, just use self\n        # ---------------------------------------------------------------------\n        else:\n            tmp = self\n\n        lmean, lsd = tmp.get_mean_and_stddevs(\n                sites, rup, dists, imt,\n                list(tmp.DEFINED_FOR_STANDARD_DEVIATION_TYPES))\n        lmean_ref, lsd = tmp.get_mean_and_stddevs(\n                ref_sites, rup, dists, imt,\n                list(tmp.DEFINED_FOR_STANDARD_DEVIATION_TYPES))\n\n        lamps = lmean - lmean_ref\n\n        return lamps\n\n    @staticmethod\n    def set_sites_depth_parameters(sites, gmpe):\n        \"\"\"\n        Need to select the appropriate z1pt0 value for different GMPEs.\n        Note that these are required site parameters, so even though\n        OQ has these equations built into the class in most cases.\n        I have submitted an issue to OQ requesting subclasses of these\n        methods that do not require the depth parameters in the\n        SitesContext to make this easier.\n\n        Args:\n            sites:1 An OQ sites context.\n            gmpe: An OQ GMPE instance.\n\n        Returns:\n            An OQ sites context with the depth parameters set for the\n            requested GMPE.\n        \"\"\"\n\n        sites = Sites._addDepthParameters(sites)\n\n        if gmpe == 'AbrahamsonEtAl2014()':\n            sites.z1pt0 = sites.z1pt0_ask14_cal\n        if gmpe == 'ChiouYoungs2014()':\n            # Also BooreEtAl2014() if using subclass with depth parameter\n            sites.z1pt0 = sites.z1pt0_cy14_cal\n        if gmpe == 'CampbellBozorgnia2014()':\n            sites.z2pt5 = sites.z2pt5_cb14_cal\n        if gmpe == 'ChiouYoungs2008()':\n            sites.z1pt0 = sites.z1pt0_cy08\n        if gmpe == 'CampbellBozorgnia2008()':\n            sites.z2pt5 = sites.z2pt5_cb07\n\n        return sites\n\n\ndef filter_gmpe_list(gmpes, wts, imt):\n    \"\"\"\n    Method to remove GMPEs from the GMPE list that are not applicable\n    to a specific IMT. Rescales the weights to sum to one.\n\n    Args:\n        gmpes (list): List of GMPE instances.\n        wts (list): List of floats indicating the weight of the GMPEs.\n        imt (IMT): OQ IMT to filter GMPE list for.\n\n    Returns:\n        tuple: List of GMPE instances and list of weights.\n\n    \"\"\"\n    if wts is None:\n        n = len(gmpes)\n        wts = [1 / n] * n\n\n    per_max = [np.max(get_gmpe_sa_periods(g)) for g in gmpes]\n    per_min = [np.min(get_gmpe_sa_periods(g)) for g in gmpes]\n    if imt == PGA():\n        sgmpe = [g for g in gmpes if imt in\n                 get_gmpe_coef_table(g).non_sa_coeffs]\n        swts = [w for g, w in zip(gmpes, wts) if imt in\n                get_gmpe_coef_table(g).non_sa_coeffs]\n    elif imt == PGV():\n        sgmpe = []\n        swts = []\n        for i in range(len(gmpes)):\n            if (imt in get_gmpe_coef_table(gmpes[i]).non_sa_coeffs) or\\\n               (per_max[i] >= 1.0 and per_min[i] <= 1.0):\n                sgmpe.append(gmpes[i])\n                swts.append(wts[i])\n    else:\n        per = imt.period\n        sgmpe = []\n        swts = []\n        for i in range(len(gmpes)):\n            if (per_max[i] >= per and per_min[i] <= per):\n                sgmpe.append(gmpes[i])\n                swts.append(wts[i])\n\n    if len(sgmpe) == 0:\n        raise Exception('No applicable GMPEs from GMPE list for %s' % imt)\n\n    # Scale weights to sum to one\n    swts = np.array(swts)\n    swts = swts / np.sum(swts)\n\n    return sgmpe, swts\n\n\ndef get_gmpe_sa_periods(gmpe):\n    \"\"\"\n    Method to extract the SA periods defined by a GMPE.\n\n    Args:\n        gmpe (GMPE): A GMPE instance.\n\n    Retunrs:\n        list: List of periods.\n\n    \"\"\"\n    ctab = get_gmpe_coef_table(gmpe).sa_coeffs\n    ilist = list(ctab.keys())\n    per = [i.period for i in ilist]\n    return per\n\n\ndef get_gmpe_coef_table(gmpe):\n    \"\"\"\n    Method for finding the (or \"a\") GMPE table.\n\n    Notes:\n\n      *  The reason for the complexity here is that there can be multiple\n         coefficient tables, and some of them may not have the sa_coeffs\n         attribute, which is the main reason for getting the table.\n      *  We are also assuming that if there are more than one  coefficient\n         table, the range of periods will be the same across all of the\n         tables.\n\n    Args:\n        gmpe (GMPE): An OQ GMPE instance.\n\n    Returns:\n        The associated coefficient table.\n\n    \"\"\"\n    stuff = gmpe.__dir__()\n    coef_list = [s for s in stuff if 'COEFFS' in s]\n    for coef_sel in coef_list:\n        cobj = getattr(gmpe, coef_sel)\n        if \"sa_coeffs\" in cobj.__dir__():\n            return cobj\n    raise Exception(\"GMPE %s does not contain sa_coeffs attribute.\" % gmpe)\n", "meta": {"hexsha": "0c13d366bf4b27b8fc7cc296dc59444e15a00dbd", "size": 33517, "ext": "py", "lang": "Python", "max_stars_repo_path": "shakelib/multigmpe.py", "max_stars_repo_name": "ynthdhj/shakemap", "max_stars_repo_head_hexsha": "2771b8aee6b22f065cc80632c894a0ba77829619", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "shakelib/multigmpe.py", "max_issues_repo_name": "ynthdhj/shakemap", "max_issues_repo_head_hexsha": "2771b8aee6b22f065cc80632c894a0ba77829619", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shakelib/multigmpe.py", "max_forks_repo_name": "ynthdhj/shakemap", "max_forks_repo_head_hexsha": "2771b8aee6b22f065cc80632c894a0ba77829619", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.6424936387, "max_line_length": 177, "alphanum_fraction": 0.5030581496, "include": true, "reason": "import numpy", "num_tokens": 7278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.19401007366434198}}
{"text": "#pylint: disable=dangerous-default-value, unused-import\n\"\"\"\n  This module contains material models containing thermal, fluid, and\n  material properties.  These models can be stored to and recalled from\n  XML files for archiving.\n\"\"\"\n\nfrom collections import ChainMap\nimport xml.etree.ElementTree as ET\n\nimport numpy as np\nimport scipy.interpolate as inter\n\nfrom neml import parse, models\n\nclass DeformationMaterial:\n  \"\"\"\n    Incredibly thin wrapper around a NEML XML file\n  \"\"\"\n  def __init__(self, xmlfile, modelname):\n    \"\"\"\n      Parameters:\n        xmlfile:    file location for the input file\n        modelname:  which model to load\n    \"\"\"\n    self.xmlfile = xmlfile\n    self.modelname = modelname\n\n  def get_neml_model(self):\n    \"\"\"\n      Return the actual model for use in a solve\n    \"\"\"\n    return parse.parse_xml(self.xmlfile, self.modelname)\n\nclass ThermalMaterial:\n  \"\"\"\n    Material thermal properties.\n\n    This object needs to provide:\n      1) material name\n      2) the conductivity, as a function of temperature and its derivative\n      3) the diffusivity, as a function of temperature and its derivative\n  \"\"\"\n  def get_dict(self):\n    \"\"\"\n      Returns the data as a dictionary\n    \"\"\"\n    raise NotImplementedError()\n\n  def get_type(self):\n    \"\"\"\n      Return the string type for the data\n    \"\"\"\n    raise NotImplementedError()\n\n  @classmethod\n  def load(cls, fname, modelname):\n    \"\"\"\n      Load from a dictionary\n\n      Parameters:\n        fname       filename\n    \"\"\"\n    tag, typ = find_name(fname, modelname)\n    data = load_node(tag)[modelname]\n\n    if typ == \"PiecewiseLinearThermalMaterial\":\n      return PiecewiseLinearThermalMaterial.load(data)\n    elif typ == \"ConstantThermalMaterial\":\n      return ConstantThermalMaterial.load(data)\n    else:\n      raise ValueError(\"Unknown ThermalMaterial type %s\" % typ)\n\n  def save(self, fname, modelname):\n    \"\"\"\n      Save the model to an XML file as modelname\n\n      Parameters:\n        fname       filename to use\n        modelname   (base tag) to use\n    \"\"\"\n    root = ET.Element(\"models\")\n\n    save_node(modelname, self.get_dict(), root,\n        attrib = {\"type\": self.get_type()})\n\n    tree = ET.ElementTree(element = root)\n    tree.write(fname)\n\nclass PiecewiseLinearThermalMaterial(ThermalMaterial):\n  \"\"\"\n    Interpolate thermal properties linearly from a table\n  \"\"\"\n  def __init__(self, name, temps, cond, diff):\n    \"\"\"\n      Properties:\n        name:           material name\n        temps:          list of temperature points\n        cond:           list of conductivity values\n        diff:           list of diffusivity values\n    \"\"\"\n    if len(temps) != len(cond) or len(temps) != len(diff):\n      raise ValueError(\"The lists of temperatures, conductivity,\"\n          \"and diffusivity values must have equal lengths!\")\n\n    self.name = name\n    self.temps = np.array(temps)\n    self.cond = np.array(cond)\n    self.diff = np.array(diff)\n\n    self.fcond, self.dfcond = make_piecewise(self.temps, self.cond)\n    self.fdiff, self.dfdiff = make_piecewise(self.temps, self.diff)\n\n  def conductivity(self, T):\n    \"\"\"\n      Conductivity as a function of temperature\n\n      Parameters:\n        T       temperature\n    \"\"\"\n    return self.fcond(T)\n\n  def diffusivity(self, T):\n    \"\"\"\n      Diffusivity as a function of temperature\n\n      Parameters:\n        T       temperature\n    \"\"\"\n    return self.fdiff(T)\n\n  def dconductivity(self, T):\n    \"\"\"\n      Derivative of conductivity as a function of temperature\n\n      Parameters:\n        T       temperature\n    \"\"\"\n    return self.dfcond(T)\n\n  def ddiffusivity(self, T):\n    \"\"\"\n      Derivative of diffusivity as a function of temperature\n\n      Parameters:\n        T       temperature\n    \"\"\"\n    return self.dfdiff(T)\n\n  def get_type(self):\n    \"\"\"\n      String type\n    \"\"\"\n    return \"PiecewiseLinearThermalMaterial\"\n\n  def get_dict(self):\n    \"\"\"\n      Pickled dictionary\n    \"\"\"\n    return {\"name\": self.name, \"temps\": string_array(self.temps),\n        \"cond\": string_array(self.cond), \"diff\": string_array(self.diff)} \n\n  @classmethod\n  def load(cls, values):\n    \"\"\"\n      Load from a dictionary\n\n      Parameters:\n        values  dictionary values\n    \"\"\"\n    return cls(values[\"name\"], destring_array(values[\"temps\"]), destring_array(values[\"cond\"]),\n        destring_array(values[\"diff\"]))\n\nclass ConstantThermalMaterial(ThermalMaterial):\n  \"\"\"\n    Constant thermal properties\n  \"\"\"\n  def __init__(self, name, k, alpha):\n    \"\"\"\n      Properties:\n        name:           material name\n        k:              conductivity\n        alpha:          diffusivity\n    \"\"\"\n    self.name = name\n    self.cond = k\n    self.diff = alpha\n\n  def conductivity(self, T):\n    \"\"\"\n      Conductivity as a function of temperature\n\n      Parameters:\n        T       temperature\n    \"\"\"\n    return T * 0.0 + self.cond\n\n  def diffusivity(self, T):\n    \"\"\"\n      Diffusivity as a function of temperature\n\n      Parameters:\n        T       temperature\n    \"\"\"\n    return T * 0.0 + self.diff\n\n  def dconductivity(self, T):\n    \"\"\"\n      Derivative of conductivity as a function of temperature\n\n      Parameters:\n        T       temperature\n    \"\"\"\n    return T * 0.0\n\n  def ddiffusivity(self, T):\n    \"\"\"\n      Derivative of diffusivity as a function of temperature\n\n      Parameters:\n        T       temperature\n    \"\"\"\n    return T * 0.0\n\n  def get_type(self):\n    \"\"\"\n      String type\n    \"\"\"\n    return \"ConstantThermalMaterial\"\n\n  def get_dict(self):\n    \"\"\"\n      Pickled dictionary\n    \"\"\"\n    return {\"name\": self.name, \"k\": str(self.cond),\n        \"alpha\": str(self.diff)}\n\n  @classmethod\n  def load(cls, values):\n    \"\"\"\n      Load from a dictionary\n\n      Parameters:\n        values  dictionary values\n    \"\"\"\n    return cls(values[\"name\"], float(values[\"k\"]), float(values[\"alpha\"]))\n\nclass FluidMaterial:\n  \"\"\"\n    Properties for convective heat transfer.\n\n    This object needs to store:\n      1) Fluid name\n      2) A map between a ThermalMaterial name and the corresponding\n         temperature-dependent film coefficient and its derivative\n  \"\"\"\n  def get_dict(self):\n    \"\"\"\n      Returns the data as a dictionary\n    \"\"\"\n    raise NotImplementedError()\n\n  def get_type(self):\n    \"\"\"\n      Return the string type for the data\n    \"\"\"\n    raise NotImplementedError()\n\n  @classmethod\n  def load(cls, fname, modelname):\n    \"\"\"\n      Load a FluidMaterial object from a file\n\n      Parameters:\n        fname       file name to load from\n    \"\"\"\n    tag, typ = find_name(fname, modelname)\n    data = load_node(tag)[modelname]\n\n    if typ == \"PiecewiseLinearFluidMaterial\":\n      return PiecewiseLinearFluidMaterial.load(data)\n    elif typ == \"ConstantFluidMaterial\":\n      return ConstantFluidMaterial.load(data)\n    else:\n      raise ValueError(\"Unknown FluidMaterial type %s\" % typ)\n\n  def save(self, fname, modelname):\n    \"\"\"\n      Save the model to an XML file as modelname\n\n      Parameters:\n        fname       filename to use\n        modelname   (base tag) to use\n    \"\"\"\n    root = ET.Element(\"models\")\n\n    save_node(modelname, self.get_dict(), root,\n        attrib = {\"type\": self.get_type()})\n\n    tree = ET.ElementTree(element = root)\n    tree.write(fname)\n\nclass ConstantFluidMaterial(FluidMaterial):\n  \"\"\"\n    Supply a mapping between the material type and a constant\n    film coefficient\n  \"\"\"\n  def __init__(self, data):\n    \"\"\"\n      Dictionary of the form {name: value} mapping\n      a material name to the definition of the piecewise linear map\n\n      Parameters:\n        data:       the dictionary\n    \"\"\"\n    self.data = data\n  \n  def get_dict(self):\n    return {k: str(v) for k, v in self.data.items()} \n\n  def get_type(self):\n    return \"ConstantFluidMaterial\"\n\n  @classmethod\n  def load(cls, values):\n    \"\"\"\n      Load from a dictionary\n\n      Parameters:\n        values      dictionary data\n    \"\"\"\n    data = {k: float(val) for k, val in values.items()}\n    return cls(data)\n\n  def coefficient(self, material, T):\n    \"\"\"\n      Return the film coefficient for the given material and temperature\n\n      Parameters:\n        material:       material name\n        T:              temperatures\n\n    \"\"\"\n    if material in self.data:\n      return T*0.0 + self.data[material]\n    else:\n      return T*0.0 + self.data[\"default\"]\n\n  # pylint: disable=unused-argument\n  def dcoefficient(self, material, T):\n    \"\"\"\n      Return the derivative of the film coefficient with respect to\n      temperature for the give material and temperature.\n\n      Parameters:\n        material:       material name\n        T:              temperatures\n    \"\"\"\n    return T * 0.0\n\nclass PiecewiseLinearFluidMaterial(FluidMaterial):\n  \"\"\"\n    Supply a mapping between the material type and a piecewise linear\n    interpolate defining the film coefficient as a function of temperature.\n  \"\"\"\n  def __init__(self, data):\n    \"\"\"\n      Dictionary of the form {name: (temperatures, values)} mapping\n      a material name to the definition of the piecewise linear map\n\n      Parameters:\n        data:       the dictionary\n    \"\"\"\n    self.data = data\n\n    self.fns = {name: make_piecewise(T, v) for name, (T,v) in data.items()}\n\n  def get_dict(self):\n    return {k: {'temp': string_array(T),\n      'values': string_array(v)} for k, (T, v) in self.data.items()}\n\n  def get_type(self):\n    return \"PiecewiseLinearFluidMaterial\"\n\n  @classmethod\n  def load(cls, values):\n    \"\"\"\n      Load from a dictionary\n\n      Parameters:\n        values      dictionary data\n    \"\"\"\n    data = {k: (destring_array(pair['temp']),\n      destring_array(pair['values'])) for k, pair in values.items()}\n    return cls(data)\n\n  def coefficient(self, material, T):\n    \"\"\"\n      Return the film coefficient for the given material and temperature\n\n      Parameters:\n        material:       material name\n        T:              temperatures\n\n    \"\"\"\n    if material in self.fns.keys():\n      return self.fns[material][0](T)\n    else:\n      return self.fns[\"default\"][0](T)\n\n  def dcoefficient(self, material, T):\n    \"\"\"\n      Return the derivative of the film coefficient with respect to\n      temperature for the give material and temperature.\n\n      Parameters:\n        material:       material name\n        T:              temperatures\n    \"\"\"\n    if material in self.fns.keys():\n      return self.fns[material][1](T)\n    else:\n      return self.fns[\"default\"][1](T)\n\nclass StructuralMaterial:\n  \"\"\"\n  Properties for structural material\n\n  Supply\n    1) cycles to failure as a function of temperature and strain range\n    2) time to rupture as a function of temperaure and stress\n    3) checks creep-fatigue interaction diagram\n  \"\"\"\n  def __init__(self, data):\n    self.data = data\n\n  def cycles_to_fail(self, pname, temp, erange):\n    \"\"\"\n        Returns fatigue cycles to failure at a given temperature and strain range\n\n        Parameters:\n          pname:       property name (\"nominalFatigue\")\n          erange:      strain range in mm/mm\n          temp:        temperature in K\n    \"\"\"\n    pdata = self.data[pname]\n    T, a, n, cutoff = [],[],[],[]\n\n    for i in pdata:\n      T.append(destring_array(pdata[i][\"T\"]))\n      a.append(destring_array(pdata[i][\"a\"]))\n      n.append(destring_array(pdata[i][\"n\"]))\n      cutoff.append(destring_array(pdata[i][\"cutoff\"]))\n\n      if np.array(a).shape != np.array(n).shape:\n        raise ValueError(\"\\tThe lists of a and n must have equal lengths!\")\n\n    inds=np.array(T).argsort(axis=0)\n    T = np.array(T)[inds]\n    a = np.array(a)[inds]\n    n = np.array(n)[inds]\n    cutoff = np.array(cutoff)[inds]\n\n    if temp > max(T):\n      raise ValueError(\"\\ttemperature is out of range for cycle to failure determination\")\n\n    for i in range(np.size(T, axis=0)):\n      if temp<=T[i]:\n        polysum = 0.0\n        if erange<=cutoff[i]:\n          erange = cutoff[i][0][0]\n        for (b,m) in zip(a[i][0],n[i][0]):\n          polysum+=b*np.log10(erange)**m\n        break\n\n    return 10**polysum\n\n  def time_to_rupture(self, pname, temp, stress):\n    \"\"\"\n        Returns time to rupture at a given temperature and stress\n\n        Parameters:\n          pname:       property name (\"averageRupture\" or \"lowerboundRupture\")\n          stress:      stress in MPa\n          temp:        temperature in K\n      \"\"\"\n    pdata = self.data[pname]\n\n    a=destring_array(pdata[\"a\"])\n    n=destring_array(pdata[\"n\"])\n    C=destring_array(pdata[\"C\"])\n\n    if a.shape != n.shape:\n      raise ValueError(\"The lists of a and n must have equal lengths!\")\n    \n    if stress.shape != temp.shape:\n      raise ValueError(\"Stress and temperature must have the same shape!\")\n    \n    zeros = stress == 0.0\n    not_zeros = np.logical_not(zeros)\n\n    res = np.zeros(stress.shape)\n    for (b,m) in zip(a,n):\n      res[not_zeros] += b*np.log10(stress[not_zeros])**m\n    res[not_zeros] = 10.0**(res[not_zeros]/temp[not_zeros]-C)\n    res[zeros] = np.inf\n\n    return res\n\n  def inside_envelope(self, pname, damage_fatigue, damage_creep):\n    \"\"\"\n        Returns True if the point lies inside the design envelope and False if not\n\n        Parameters:\n          pname:               property name (\"cfinteraction\")\n          damage_fatigue:      fatigue damage fraction\n          creep_fatigue:       creep damage fraction\n      \"\"\"\n\n    if damage_fatigue < 0.0 or damage_creep < 0.0:\n      raise ValueError(\"\\tout of range: negative damage fraction\")\n\n    pdata = destring_array(self.data[pname])\n\n    x_1 = 0.0\n    y_1 = 1.0\n    x_2 = pdata[0]\n    y_2 = pdata[1]\n    x_3 = 1.0\n    y_3 = 0.0\n\n    if damage_fatigue < x_2:\n      return damage_creep <= ((y_2 - y_1) / (x_2 - x_1) * (damage_fatigue - x_1) + y_1)\n    return damage_creep <= ((y_3 - y_2) / (x_3 - x_2) * (damage_fatigue - x_2) + y_2)\n\n  @classmethod\n  def load(cls, fname, model):\n    \"\"\"\n      Load a Structural Material object from a file\n\n      Parameters:\n        fname:       file name to load from\n        material:    model name\n    \"\"\"\n    tag = ET.parse(fname).getroot().find(model)\n    return cls(load_node(tag)[model])\n\n  def save(self, fname, modelname):\n    \"\"\"\n      Save to a particular file under a particular model name\n    \"\"\"\n    root = ET.Element('models')\n    save_node(modelname, self.data, root)\n    tree = ET.ElementTree(element = root)\n    tree.write(fname)\n\ndef make_piecewise(x, y):\n  \"\"\"\n    Make two piecewise interpolation functions: a piecewise linear\n    interpolate between x and y and the corresponding derivative.\n  \"\"\"\n  ydiff = np.zeros(y.shape)\n  ydiff[:-1] = np.diff(y) / np.diff(x)\n  ydiff[-1] = ydiff[-2]\n\n  return inter.interp1d(x, y), inter.interp1d(x, ydiff, kind = \"previous\")\n\ndef find_name(xmlfile, name):\n  \"\"\"\n    Find the base tag with name in an XML file\n\n    Parameters:\n      xmlfile:        file name\n      name:           tag to look for\n  \"\"\"\n  root = ET.parse(xmlfile).getroot()\n  tag =  root.find(name)\n\n  return tag, tag.attrib[\"type\"]\n\ndef save_node(name, entry, node, attrib = {}):\n  \"\"\"\n    Save a dictionary to a particular node\n\n    Parameters:\n      name:     name of the new node\n      entry:    entry of interest\n      node:     ET parent node object\n\n    Additional parameters:\n      attribs   node attributes\n  \"\"\"\n  nnode = ET.SubElement(node, name, attrib)\n  if isinstance(entry, dict):\n    for k,v in entry.items():\n      save_node(k, v, nnode)\n  else:\n    nnode.text = entry\n\ndef load_node(node):\n  \"\"\"\n    The actual function that does the loading by walking the XML file\n\n    Parameters:\n      node:      xml node object from ET\n  \"\"\"\n  if len(node) > 0:\n    return {node.tag: dict(ChainMap(*(load_node(child) for child in node)))}\n  else:\n    return {node.tag: node.text}\n\ndef string_array(array):\n  \"\"\"\n    Make a numpy array a space separated string\n  \"\"\"\n  return \" \".join(map(str, array))\n\ndef destring_array(string):\n  \"\"\"\n    Make an array from a space separated string\n  \"\"\"\n  return np.array(list(map(float, string.split(\" \"))))\n", "meta": {"hexsha": "86a46276f058eeb8171a7e3a34c9da0249e6c2f3", "size": 15901, "ext": "py", "lang": "Python", "max_stars_repo_path": "srlife/materials.py", "max_stars_repo_name": "willietheboy/srlife-dev", "max_stars_repo_head_hexsha": "d4c2d28b40d2ee1bf64c7555a913b0a49adffe0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-10-05T20:36:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-09T00:33:41.000Z", "max_issues_repo_path": "srlife/materials.py", "max_issues_repo_name": "willietheboy/srlife-dev", "max_issues_repo_head_hexsha": "d4c2d28b40d2ee1bf64c7555a913b0a49adffe0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-12-02T16:10:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T19:45:32.000Z", "max_forks_repo_path": "srlife/materials.py", "max_forks_repo_name": "willietheboy/srlife-dev", "max_forks_repo_head_hexsha": "d4c2d28b40d2ee1bf64c7555a913b0a49adffe0f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:46:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T04:26:39.000Z", "avg_line_length": 25.5232744783, "max_line_length": 95, "alphanum_fraction": 0.6166907742, "include": true, "reason": "import numpy,import scipy", "num_tokens": 3887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.34510526422232046, "lm_q1q2_score": 0.19401006987777292}}
{"text": "from collections import namedtuple\nimport sys\nimport re\nimport warnings\nimport array\n\nimport numpy as np\n\nfrom scipy._lib._util import check_random_state\nfrom scipy.optimize import minimize, differential_evolution, least_squares\nimport scipy.optimize as sciopt\n\nfrom refnx.analysis import Objective, Interval, PDF, is_parameter\nfrom refnx._lib import (\n    unique as f_unique,\n    MapWrapper,\n    possibly_open_file,\n    flatten,\n)\nfrom refnx._lib.util import getargspec\nfrom refnx._lib._qmc import LatinHypercube\nfrom refnx._lib import emcee\nfrom refnx._lib.emcee.state import State\nfrom refnx._lib.emcee.pbar import get_progress_bar\n\n\nMCMCResult = namedtuple(\n    \"MCMCResult\", [\"name\", \"param\", \"stderr\", \"chain\", \"median\"]\n)\n\n\nclass PTSampler:\n    def __init__(self, ntemps, nwalkers, ndim, logl, logp, **kwargs):\n        \"\"\"\n        Shim class for a ptemcee.PTSampler.\n\n        Parameters\n        ----------\n        ntemps: int, np.array\n            Specifies the number of parallel tempering temperatures.\n            If an array specifies a ladder of Beta values.\n        nwalkers: int\n            Number of walkers\n        ndim: int\n            Dimensionality of the problem space\n        logl: callable\n            log-likelihood function\n        logp: callable\n            log-prior function\n        kwargs:\n            Other keyword arguments supplied to construct the ptemcee.Sampler.\n        \"\"\"\n        from refnx._lib.ptemcee import Sampler as _PTSampler\n\n        self.ntemps = ntemps\n        self.nwalkers = nwalkers\n        self.ndim = ndim\n        self.logl = logl\n        self.logp = logp\n        self.kwargs = kwargs\n\n        sig = {\n            \"betas\": ntemps,\n            \"nwalkers\": nwalkers,\n            \"ndim\": ndim,\n            \"logl\": logl,\n            \"logp\": logp,\n        }\n        sig.update(kwargs)\n        self.sampler = _PTSampler(**sig)\n\n        # chain stepper\n        self._ptchain = None\n        self._state = None\n\n    def sample(\n        self,\n        initial_state,\n        iterations=1,\n        thin_by=1,\n        progress=False,\n        mapper=None,\n        **kwds\n    ):\n        \"\"\"\n        Runs the PTSampler for a given number of iterations.\n\n        Parameters\n        ----------\n        initial_state: emcee.state.State\n            Holds the coordinates of the initial state\n        iterations: int\n            Number of steps to save into the chain\n        thin_by: int\n            The saved steps are separated by this many discarded steps.\n        progress: bool\n            Display a progress bar.\n        mapper: map-like callable\n            For parallelisation\n        kwds: dict\n            Unknown keywords\n\n        Yields\n        -------\n        state: emcee.state.State\n            The coordinates of the current state\n        \"\"\"\n        if isinstance(initial_state, State):\n            init_x = initial_state.coords\n            rstate0 = initial_state.random_state\n        else:\n            init_x = initial_state\n            rstate0 = np.random.RandomState().get_state()\n\n        if self._ptchain is None:\n            self._ptchain = self.sampler.chain(init_x)\n        else:\n            self._ptchain.ensemble.x = init_x\n\n        # set random state of stateful chain\n        self.random_state = rstate0\n\n        self._ptchain.thin_by = thin_by\n\n        if mapper is not None:\n            self._ptchain.ensemble._mapper = mapper\n\n        try:\n            with get_progress_bar(progress, iterations * thin_by) as pbar:\n                for e in self._ptchain.iterate(iterations):\n                    self._state = State(e.x, log_prob=e.logl + e.logP)\n                    yield self._state\n                    pbar.update(thin_by)\n        finally:\n            self._ptchain.ensemble._mapper = map\n\n    def thermodynamic_integration_log_evidence(self, fburnin=0.1):\n        if self._ptchain is not None:\n            return self._ptchain.log_evidence_estimate(fburnin)\n        return None, None\n\n    def reset(self):\n        if self._state is not None:\n            self._ptchain = self.sampler.chain(self._state.coords)\n\n    def get_chain(self):\n        if self._ptchain is not None:\n            return self._ptchain.x\n        return None\n\n    @property\n    def chain(self):\n        if self._ptchain is not None:\n            return self._ptchain.x\n        return None\n\n    def get_log_prob(self):\n        if self._ptchain is not None:\n            return self._ptchain.logP\n        return None\n\n    @property\n    def random_state(self):\n        if self._ptchain is not None:\n            self._ptchain.ensemble._random.get_state()\n\n    @random_state.setter\n    def random_state(self, rstate0):\n        if self._ptchain is not None:\n            self._ptchain.ensemble._random.set_state(rstate0)\n\n\nclass CurveFitter:\n    \"\"\"\n    Analyse a curvefitting system (with MCMC sampling)\n\n    Parameters\n    ----------\n    objective : refnx.analysis.Objective\n        The :class:`refnx.analysis.Objective` to be analysed.\n    nwalkers : int, optional\n        How many walkers you would like the sampler to have. Must be an\n        even number. The more walkers the better.\n    ntemps : int or None, optional\n        If `ntemps == -1`, then an :class:`emcee.EnsembleSampler` is used\n        during the `sample` method.\n        Otherwise, or if `ntemps is None` then parallel tempering is\n        used with a :class:`ptemcee.sampler.Sampler` object during the `sample`\n        method, with `ntemps` specifing the number of temperatures. Can be\n        `None`, in which case the `Tmax` keyword argument sets the maximum\n        temperature. Parallel Tempering is useful if you expect your\n        posterior distribution to be multi-modal.\n\n    mcmc_kws : dict\n        Keywords used to create the :class:`emcee.EnsembleSampler` or\n        :class:`ptemcee.sampler.Sampler` objects.\n\n    Notes\n    -----\n    See the documentation at http://dan.iel.fm/emcee/current/api/ for\n    further details on what keywords are permitted, and for further\n    information on Parallel Tempering. The `pool` and `threads` keywords\n    are ignored here. Specification of parallel threading is done with the\n    `pool` argument in the `sample` method.\n    \"\"\"\n\n    def __init__(self, objective, nwalkers=200, ntemps=-1, **mcmc_kws):\n        \"\"\"\n        Parameters\n        ----------\n        objective : refnx.analysis.Objective\n            The :class:`refnx.analysis.Objective` to be analysed.\n        nwalkers : int, optional\n            How many walkers you would like the sampler to have. Must be an\n            even number. The more walkers the better.\n        ntemps : int or None, optional\n            If `ntemps == -1`, then an :class:`emcee.EnsembleSampler` is used\n            during the `sample` method.\n            Otherwise, or if `ntemps is None` then parallel tempering is\n            used with a :class:`ptemcee.sampler.Sampler` object during the\n            `sample` method, with `ntemps` specifing the number of\n            temperatures. Can be `None`, in which case the `Tmax` keyword\n            argument sets the maximum temperature. Parallel Tempering is\n            useful if you expect your posterior distribution to be multi-modal.\n        mcmc_kws : dict\n            Keywords used to create the :class:`emcee.EnsembleSampler` or\n            :class:`ptemcee.sampler.PTSampler` objects.\n\n        Notes\n        -----\n        See the documentation at http://dan.iel.fm/emcee/current/api/ for\n        further details on what keywords are permitted. The `pool` and\n        keyword is ignored here. Specification of parallel threading is done\n        with the `pool` argument in the `sample` method.\n        To use parallel tempering you will need to install the\n        :package:`ptemcee` package.\n        \"\"\"\n        self.objective = objective\n        self._varying_parameters = []\n        self.__var_id = []\n\n        self.mcmc_kws = {}\n        if mcmc_kws is not None:\n            self.mcmc_kws.update(mcmc_kws)\n\n        if \"pool\" in self.mcmc_kws:\n            self.mcmc_kws.pop(\"pool\")\n        if \"threads\" in self.mcmc_kws:\n            self.mcmc_kws.pop(\"threads\")\n\n        self._nwalkers = nwalkers\n        self._ntemps = ntemps\n        self.make_sampler()\n        self._state = None\n\n    def __setstate__(self, state):\n        self.__dict__.update(state)\n        self.__var_id = [\n            id(obj) for obj in self.objective.varying_parameters()\n        ]\n\n    @property\n    def nvary(self):\n        return len(self._varying_parameters)\n\n    def __repr__(self):\n        # attempt to get a minimum repr for a CurveFitter. However,\n        # it has so much state when the sampling has been done, that\n        # will be ignored.\n        d = {\n            \"objective\": self.objective,\n            \"_nwalkers\": self._nwalkers,\n            \"_ntemps\": self._ntemps,\n            \"mcmc_kws\": self.mcmc_kws,\n        }\n        return (\n            \"CurveFitter({objective!r},\"\n            \" nwalkers={_nwalkers},\"\n            \" ntemps={_ntemps},\"\n            \" {mcmc_kws!r})\".format(**d)\n        )\n\n    def make_sampler(self):\n        \"\"\"\n        Make the samplers for the Objective.\n\n        Use this method if the number of varying parameters changes.\n        \"\"\"\n        self._varying_parameters = self.objective.varying_parameters()\n        self.__var_id = [id(obj) for obj in self._varying_parameters]\n\n        if not self.nvary:\n            raise ValueError(\"No parameters are being fitted\")\n\n        if self._ntemps == -1:\n            self.sampler = emcee.EnsembleSampler(\n                self._nwalkers,\n                self.nvary,\n                self.objective.logpost,\n                **self.mcmc_kws\n            )\n        # Parallel Tempering was requested.\n        else:\n            sig = {\n                \"ntemps\": self._ntemps,\n                \"nwalkers\": self._nwalkers,\n                \"ndim\": self.nvary,\n                \"logl\": self.objective.logl,\n                \"logp\": self.objective.logp,\n            }\n            sig.update(self.mcmc_kws)\n            self.sampler = PTSampler(**sig)\n\n        self._state = None\n\n    def _check_vars_unchanged(self):\n        \"\"\"\n        Keep track of whether the varying parameters have changed after\n        construction of CurveFitter object.\n\n        \"\"\"\n        var_ids = [id(obj) for obj in self.objective.varying_parameters()]\n        if not (np.array_equal(var_ids, self.__var_id)):\n            raise RuntimeError(\n                \"The Objective.varying_parameters() have\"\n                \" changed since the CurveFitter was created.\"\n                \" To keep on using the CurveFitter call\"\n                \" the CurveFitter.make_samplers() method.\"\n            )\n\n    def initialise(self, pos=\"covar\", random_state=None):\n        \"\"\"\n        Initialise the emcee walkers.\n\n        Parameters\n        ----------\n        pos : str or np.ndarray\n            Method for initialising the emcee walkers. One of:\n\n            - 'covar', use the estimated covariance of the system.\n            - 'jitter', add a small amount of gaussian noise to each parameter\n            - 'prior', sample random locations from the prior using Latin\n                Hyper Cube.\n            - pos, an array that specifies a snapshot of the walkers. Has shape\n                `(nwalkers, ndim)`, or `(ntemps, nwalkers, ndim)` if parallel\n                 tempering is employed. You can also provide a previously\n                 created chain.\n        random_state : {int, `np.random.RandomState`, `np.random.Generator`}\n            If `random_state` is not specified the `~np.random.RandomState`\n            singleton is used.\n            If `random_state` is an int, a new ``RandomState`` instance is\n            used, seeded with random_state.\n            If `random_state` is already a ``RandomState`` or a ``Generator``\n            instance, then that object is used.\n            Specify `random_state` for repeatable initialisations.\n        \"\"\"\n        nwalkers = self._nwalkers\n        nvary = self.nvary\n\n        # acquire a random number generator\n        rng = check_random_state(random_state)\n\n        # account for parallel tempering\n        _ntemps = self._ntemps\n\n        # If you're not doing parallel tempering, temporarily set the number of\n        # temperatures to be created to 1, thereby producing initial positions\n        # of (1, nwalkers, nvary), this first dimension should be removed at\n        # the end of the method\n        if self._ntemps == -1:\n            _ntemps = 1\n\n        # position is specified with array (no parallel tempering)\n        if (\n            isinstance(pos, np.ndarray)\n            and self._ntemps == -1\n            and pos.shape == (nwalkers, nvary)\n        ):\n            init_walkers = np.copy(pos)[np.newaxis]\n\n        # position is specified with array (with parallel tempering)\n        elif (\n            isinstance(pos, np.ndarray)\n            and self._ntemps > -1\n            and pos.shape == (_ntemps, nwalkers, nvary)\n        ):\n            init_walkers = np.copy(pos)\n\n        # position is specified with existing chain\n        elif isinstance(pos, np.ndarray):\n            self.initialise_with_chain(pos)\n            return\n\n        # position is to be created from covariance matrix\n        elif pos == \"covar\":\n            p0 = np.array(self._varying_parameters)\n            cov = self.objective.covar()\n            init_walkers = rng.multivariate_normal(\n                np.atleast_1d(p0), np.atleast_2d(cov), size=(_ntemps, nwalkers)\n            )\n\n        # position is specified by jittering the parameters with gaussian noise\n        elif pos == \"jitter\":\n            var_arr = np.array(self._varying_parameters)\n            pos = 1 + rng.standard_normal((_ntemps, nwalkers, nvary)) * 1.0e-4\n            pos *= var_arr\n            init_walkers = pos\n\n        # use the prior to initialise position\n        elif pos == \"prior\":\n            arr = np.zeros((_ntemps, nwalkers, nvary))\n            LHC = LatinHypercube(nvary, seed=random_state)\n            samples = LHC.random(n=_ntemps * nwalkers).reshape(\n                _ntemps, nwalkers, nvary\n            )\n\n            for i, param in enumerate(self._varying_parameters):\n                # bounds are not a closed interval, just jitter it.\n                if (\n                    isinstance(param.bounds, Interval)\n                    and not param.bounds._closed_bounds\n                ):\n                    vals = (\n                        1 + rng.standard_normal((_ntemps, nwalkers)) * 1.0e-1\n                    )\n                    vals *= param.value\n                    arr[..., i] = vals\n                else:\n                    sample_arr = samples[..., i]\n                    transformed = param.bounds.invcdf(sample_arr)\n                    arr[..., i] = transformed\n\n            init_walkers = arr\n\n        else:\n            raise RuntimeError(\n                \"Didn't use any known method for \" \"CurveFitter.initialise\"\n            )\n\n        # if you're not doing parallel tempering then remove the first\n        # dimension\n        if self._ntemps == -1:\n            init_walkers = init_walkers[0]\n\n        # now validate initialisation, ensuring all init pos have finite\n        # logpost\n        for i, param in enumerate(self._varying_parameters):\n            init_walkers[..., i] = param.valid(init_walkers[..., i])\n\n        rstate0 = None\n        if isinstance(rng, np.random.RandomState):\n            rstate0 = rng.get_state()\n\n        self._state = State(init_walkers, random_state=rstate0)\n\n        # finally reset the sampler to reset the chain\n        # you have to do this at the end, not at the start because resetting\n        # makes self.sampler.chain == None and the PTsampler creation doesn't\n        # work\n        self.sampler.reset()\n\n    def initialise_with_chain(self, chain):\n        \"\"\"\n        Initialise sampler with a pre-existing chain\n\n        Parameters\n        ----------\n        chain : array\n            Array of size `(steps, ntemps, nwalkers, ndim)` or\n            `(steps, nwalkers, ndim)`, containing a chain from a previous\n            sampling run.\n        \"\"\"\n        # we should be left with (nwalkers, ndim) or (ntemp, nwalkers, ndim)\n\n        if self._ntemps == -1:\n            required_shape = (self._nwalkers, self.nvary)\n        else:\n            required_shape = (self._ntemps, self._nwalkers, self.nvary)\n\n        chain_shape = chain.shape[1:]\n\n        # if the shapes are the same, then we can initialise\n        if required_shape == chain_shape:\n            self.initialise(pos=chain[-1])\n        else:\n            raise ValueError(\n                \"You tried to initialise with a chain, but it was\"\n                \" the wrong shape\"\n            )\n\n    @property\n    def chain(self):\n        \"\"\"\n        MCMC chain belonging to CurveFitter.sampler\n\n        Returns\n        -------\n        chain : array\n            The MCMC chain with shape `(steps, nwalkers, ndim)` or\n            `(steps, ntemps, nwalkers, ndim)`.\n        \"\"\"\n        return self.sampler.get_chain()\n\n    @property\n    def logpost(self):\n        \"\"\"\n        Log-probability for each of the entries in `self.chain`\n        \"\"\"\n        return self.sampler.get_log_prob()\n\n    @property\n    def index_max_prob(self):\n        \"\"\"\n        The index of the highest log-probability for the samples\n        \"\"\"\n        log_probs = self.sampler.get_log_prob()\n        if isinstance(self.sampler, PTSampler):\n            log_probs = log_probs[:, 0]\n\n        loc = np.argmax(log_probs)\n        idx = np.unravel_index(loc, log_probs.shape)\n\n        if isinstance(self.sampler, PTSampler):\n            idx = list(idx)\n            idx.insert(1, 0)\n            return tuple(idx)\n\n        return idx\n\n    def reset(self):\n        \"\"\"\n        Reset the sampled chain.\n\n        Typically used on a sampler after a burn-in period.\n        \"\"\"\n        self.sampler.reset()\n\n    def acf(self, nburn=0, nthin=1):\n        \"\"\"\n        Calculate the autocorrelation function\n\n        Returns\n        -------\n        acfs : np.ndarray\n            The autocorrelation function, acfs.shape=(lags, nvary)\n        \"\"\"\n        return autocorrelation_chain(self.chain, nburn=nburn, nthin=nthin)\n\n    def sample(\n        self,\n        steps,\n        nthin=1,\n        random_state=None,\n        f=None,\n        callback=None,\n        verbose=True,\n        pool=-1,\n    ):\n        \"\"\"\n        Performs sampling from the objective.\n\n        Parameters\n        ----------\n        steps : int\n            Collect `steps` samples into the chain. The sampler will run a\n            total of `steps * nthin` moves.\n        nthin : int, optional\n            Each chain sample is separated by `nthin` iterations.\n        random_state : {int, `np.random.RandomState`, `np.random.Generator`}\n            If `random_state` is not specified the `~np.random.RandomState`\n            singleton is used.\n            If `random_state` is an int, a new ``RandomState`` instance is\n            used, seeded with random_state.\n            If `random_state` is already a ``RandomState`` or a ``Generator``\n            instance, then that object is used.\n            Specify `random_state` for repeatable minimizations.\n        f : file-like or str\n            File to incrementally save chain progress to. Each row in the file\n            is a flattened array of size `(nwalkers, ndim)` or\n            `(ntemps, nwalkers, ndim)`. There are `steps` rows in the\n            file.\n        callback : callable\n            callback function to be called at each iteration step. Has the\n            signature `callback(coords, logprob)`.\n        verbose : bool, optional\n            Gives updates on the sampling progress\n        pool : int or map-like object, optional\n            If `pool` is an `int` then it specifies the number of threads to\n            use for parallelization. If `pool == -1`, then all CPU's are used.\n            If pool is a map-like callable that follows the same calling\n            sequence as the built-in map function, then this pool is used for\n            parallelisation.\n\n        Notes\n        -----\n        Please see :class:`emcee.EnsembleSampler` for its detailed behaviour.\n\n        >>> # we'll burn the first 500 steps\n        >>> fitter.sample(500)\n        >>> # after you've run those, then discard them by resetting the\n        >>> # sampler.\n        >>> fitter.sampler.reset()\n        >>> # Now collect 40 steps, each step separated by 50 sampler\n        >>> # generations.\n        >>> fitter.sample(40, nthin=50)\n\n        One can also burn and thin in `Curvefitter.process_chain`.\n        \"\"\"\n        self._check_vars_unchanged()\n\n        # setup a random number generator\n        rng = check_random_state(random_state)\n\n        if self._state is None:\n            self.initialise(random_state=rng)\n\n        # for saving progress to file\n        def _callback_wrapper(state, h=None):\n            if callback is not None:\n                callback(state.coords, state.log_prob)\n\n            if h is not None:\n                h.write(\" \".join(map(str, state.coords.ravel())))\n                h.write(\"\\n\")\n\n        # remove chains from each of the parameters because they slow down\n        # pickling but only if they are parameter objects.\n        flat_params = f_unique(flatten(self.objective.parameters))\n        flat_params = [param for param in flat_params if is_parameter(param)]\n        # zero out all the old parameter stderrs\n        for param in flat_params:\n            param.stderr = None\n            param.chain = None\n\n        # make sure the checkpoint file exists\n        if f is not None:\n            with possibly_open_file(f, \"w\") as h:\n                # write the shape of each step of the chain\n                h.write(\"# \")\n                shape = self._state.coords.shape\n                h.write(\", \".join(map(str, shape)))\n                h.write(\"\\n\")\n\n        # set the random state of the sampler\n        # normally one could give this as an argument to the sample method\n        # but PTSampler didn't historically accept that...\n        if isinstance(rng, np.random.RandomState):\n            rstate0 = rng.get_state()\n            self._state.random_state = rstate0\n            self.sampler.random_state = rstate0\n\n        # using context manager means we kill off zombie pool objects\n        # but does mean that the pool has to be specified each time.\n        with MapWrapper(pool) as g, possibly_open_file(f, \"a\") as h:\n            # these kwargs are provided to the sampler.sample method\n            kwargs = {\"iterations\": steps, \"thin\": nthin}\n\n            # if you're not creating more than 1 thread, then don't bother with\n            # a pool.\n            if isinstance(self.sampler, emcee.EnsembleSampler):\n                if pool == 1:\n                    self.sampler.pool = None\n                else:\n                    self.sampler.pool = g\n            else:\n                kwargs[\"mapper\"] = g\n\n            # new emcee arguments\n            sampler_args = getargspec(self.sampler.sample).args\n            if \"progress\" in sampler_args and verbose:\n                kwargs[\"progress\"] = True\n                verbose = False\n\n            if \"thin_by\" in sampler_args:\n                kwargs[\"thin_by\"] = nthin\n                kwargs.pop(\"thin\", 0)\n\n            # perform the sampling\n            for state in self.sampler.sample(self._state, **kwargs):\n                self._state = state\n                _callback_wrapper(state, h=h)\n\n        if isinstance(self.sampler, emcee.EnsembleSampler):\n            self.sampler.pool = None\n\n        # sets parameter value and stderr\n        return process_chain(self.objective, self.chain)\n\n    def fit(self, method=\"L-BFGS-B\", target=\"nll\", verbose=True, **kws):\n        \"\"\"\n        Obtain the maximum log-likelihood, or log-posterior, estimate (mode)\n        of the objective. Maximising the log-likelihood is equivalent to\n        minimising chi2 in a least squares fit.\n\n        Parameters\n        ----------\n        method : str\n            which method to use for the optimisation. One of:\n\n            - `'least_squares'`: :func:`scipy.optimize.least_squares`.\n            - `'L-BFGS-B'`: L-BFGS-B.\n            - `'differential_evolution'`:\n              :func:`scipy.optimize.differential_evolution`\n            - `'dual_annealing'`:\n              :func:`scipy.optimize.dual_annealing` (SciPy >= 1.2.0)\n            - `'shgo'`: :func:`scipy.optimize.shgo` (SciPy >= 1.2.0)\n\n            You can also choose many of the minimizers from\n            :func:`scipy.optimize.minimize`.\n\n        target : {'nll', 'nlpost'}, optional\n            Minimize the negative log-likelihood (`'nll'`) or the negative\n            log-posterior (`'nlpost'`). This is equivalent to maximising the\n            likelihood or posterior probabilities respectively.\n            Maximising the likelihood is equivalent to minimising chi^2 in a\n            least-squares fit.\n            This option only applies to the `differential_evolution`, `shgo`,\n            `dual_annealing` or `L-BFGS-B` methods.\n            These optimisers require lower and upper (box) bounds for each\n            parameter. If the `Bounds` on a parameter are not an `Interval`,\n            but a `PDF` specifying a statistical distribution, then the lower\n            and upper bounds are approximated as\n            ``PDF.rv.ppf([0.005, 0.995])``, covering 99 % of the statistical\n            distribution.\n        verbose : bool, optional\n            Gives fitting progress. To see a progress bar tqdm has to be\n            installed.\n        kws : dict\n            Additional arguments are passed to the underlying minimization\n            method.\n\n        Returns\n        -------\n        result, covar : :class:`scipy.optimize.OptimizeResult`, np.ndarray\n            `result.x` contains the best fit parameters\n            `result.covar` is the covariance matrix for the fit.\n            `result.stderr` is the uncertainties on each of the fit parameters.\n\n        Notes\n        -----\n        If the `objective` supplies a `residuals` method then `least_squares`\n        can be used. Otherwise the `nll` method of the `objective` is\n        minimised. Use this method just before a sampling run.\n        If `self.objective.parameters` is a `Parameters` instance, then each\n        of the varying parameters has its value updated by the fit, and each\n        `Parameter` has a `stderr` attribute which represents the uncertainty\n        on the fit parameter.\n\n        The use of `dual annealing` and `shgo` requires that `scipy >= 1.2.0`\n        be installed.\n\n        \"\"\"\n        _varying_parameters = self.objective.varying_parameters()\n        init_pars = np.array(_varying_parameters)\n\n        _min_kws = {}\n        _min_kws.update(kws)\n        _bounds = bounds_list(self.objective.varying_parameters())\n        _min_kws[\"bounds\"] = _bounds\n\n        # setup callback default\n        _min_kws.setdefault(\"callback\", None)\n\n        cost = self.objective.nll\n        if target == \"nlpost\":\n            cost = self.objective.nlpost\n\n        # a decorator for the progress bar updater\n        def _callback_wrapper(callback_func, pbar):\n            def callback(*args, **kwds):\n                pbar.update(1)\n                if callback_func is None:\n                    return None\n                else:\n                    return callback_func(*args, **kwds)\n\n            return callback\n\n        # least_squares Trust Region Reflective by default\n        if method == \"least_squares\":\n            b = np.array(_bounds)\n            _min_kws[\"bounds\"] = (b[..., 0], b[..., 1])\n\n            # least_squares doesn't have a callback\n            _min_kws.pop(\"callback\", None)\n\n            res = least_squares(\n                self.objective.residuals, init_pars, **_min_kws\n            )\n        # differential_evolution, dual_annealing, shgo require lower and upper\n        # bounds\n        elif method in [\"differential_evolution\", \"dual_annealing\", \"shgo\"]:\n            mini = getattr(sciopt, method)\n\n            if method == \"shgo\":\n                if \"n\" not in _min_kws:\n                    _min_kws[\"n\"] = 100\n                if \"iters\" not in kws:\n                    _min_kws[\"iters\"] = 5\n\n            with get_progress_bar(verbose, None) as pbar:\n                _min_kws[\"callback\"] = _callback_wrapper(\n                    _min_kws[\"callback\"], pbar\n                )\n\n                res = mini(cost, **_min_kws)\n        else:\n            # otherwise stick it to minimizer. Default being L-BFGS-B\n            _min_kws[\"method\"] = method\n            _min_kws[\"bounds\"] = _bounds\n\n            with get_progress_bar(verbose, None) as pbar:\n                _min_kws[\"callback\"] = _callback_wrapper(\n                    _min_kws[\"callback\"], pbar\n                )\n\n                res = minimize(cost, init_pars, **_min_kws)\n\n        # OptimizeResult.success may not be present (dual annealing)\n        if hasattr(res, \"success\") and res.success:\n            self.objective.setp(res.x)\n\n            # Covariance matrix estimation\n            covar = self.objective.covar()\n            errors = np.sqrt(np.diag(covar))\n            res[\"covar\"] = covar\n            res[\"stderr\"] = errors\n\n            # check if the parameters are all Parameter instances.\n            flat_params = list(f_unique(flatten(self.objective.parameters)))\n            if np.all([is_parameter(param) for param in flat_params]):\n                # zero out all the old parameter stderrs\n                for param in flat_params:\n                    param.stderr = None\n                    param.chain = None\n\n                for i, param in enumerate(_varying_parameters):\n                    param.stderr = errors[i]\n\n            # need to touch up the output to check we leave\n            # parameters as we found them\n            self.objective.setp(res.x)\n\n        return res\n\n\ndef load_chain(f):\n    \"\"\"\n    Loads a chain from disk. Does not change the state of a CurveFitter\n    object.\n\n    Parameters\n    ----------\n    f : str or file-like\n        File containing the chain.\n\n    Returns\n    -------\n    chain : array\n        The loaded chain - `(nsteps, nwalkers, ndim)` or\n        `(nsteps, ntemps, nwalkers, ndim)`\n    \"\"\"\n    with possibly_open_file(f, \"r\") as g:\n        # read header\n        header = g.readline()\n        expr = re.compile(r\"(\\d+)\")\n        matches = expr.findall(header)\n        if matches:\n            if len(matches) == 3:\n                ntemps, nwalkers, ndim = map(int, matches)\n            elif len(matches) == 2:\n                ntemps = None\n                nwalkers, ndim = map(int, matches)\n        else:\n            raise ValueError(\"Couldn't read header line of chain file\")\n\n    chain = np.loadtxt(f)\n\n    if ntemps is not None:\n        chain = np.reshape(chain, (-1, ntemps, nwalkers, ndim))\n    else:\n        chain = np.reshape(chain, (-1, nwalkers, ndim))\n\n    return chain\n\n\ndef process_chain(objective, chain, nburn=0, nthin=1, flatchain=False):\n    \"\"\"\n    Process the chain produced by a sampler for a given Objective\n\n    Parameters\n    ----------\n    objective : refnx.analysis.Objective\n        The Objective function that the Posterior was sampled for\n    chain : array\n        The MCMC chain\n    nburn : int, optional\n        discard this many steps from the start of the chain\n    nthin : int, optional\n        only accept every `nthin` samples from the chain\n    flatchain : bool, optional\n        collapse the walkers down into a single dimension.\n\n    Returns\n    -------\n    [(param, stderr, chain)] : list\n        List of (param, stderr, chain) tuples.\n        If `isinstance(objective.parameters, Parameters)` then `param` is a\n        `Parameter` instance. `param.value`, `param.stderr` and\n        `param.chain` will contain the median, stderr and chain samples,\n        respectively. Otherwise `param` will be a float representing the\n        median of the chain samples.\n        `stderr` is the half width of the [15.87, 84.13] spread (similar to\n        standard deviation) and `chain` is an array containing the MCMC\n        samples for that parameter.\n\n    Notes\n    -----\n    The chain should have the shape `(iterations, nwalkers, nvary)` or\n    `(iterations, ntemps, nwalkers, nvary)` if parallel tempering was\n    employed.\n    The burned and thinned chain is created via:\n    `chain[nburn::nthin]`.\n    Note, if parallel tempering is employed, then only the lowest temperature\n    of the parallel tempering chain is processed and returned as it\n    corresponds to the (lowest energy) target distribution.\n    If `flatten is True` then the burned/thinned chain is reshaped and\n    `arr.reshape(-1, nvary)` is returned.\n    This function has the effect of setting the parameter stderr's.\n    \"\"\"\n    chain = chain[nburn::nthin]\n    shape = chain.shape\n    nvary = shape[-1]\n\n    # nwalkers = shape[1]\n    if len(shape) == 4:\n        ntemps = shape[1]\n    elif len(shape) == 3:\n        ntemps = -1\n\n    if ntemps != -1:\n        # PTSampler, we require the target distribution in the first row.\n        chain = chain[:, 0]\n\n    _flatchain = chain.reshape((-1, nvary))\n    if flatchain:\n        chain = _flatchain\n\n    flat_params = list(f_unique(flatten(objective.parameters)))\n    varying_parameters = objective.varying_parameters()\n\n    # set the stderr of each of the Parameters\n    result_list = []\n    if np.all([is_parameter(param) for param in flat_params]):\n        # zero out all the old parameter stderrs\n        for param in flat_params:\n            param.stderr = None\n            param.chain = None\n\n        # do the error calcn for the varying parameters and set the chain\n        quantiles = np.percentile(_flatchain, [15.87, 50, 84.13], axis=0)\n        for i, param in enumerate(varying_parameters):\n            std_l, median, std_u = quantiles[:, i]\n            param.value = median\n            param.stderr = 0.5 * (std_u - std_l)\n\n            # copy in the chain\n            param.chain = np.copy(chain[..., i])\n            res = MCMCResult(\n                name=param.name,\n                param=param,\n                median=param.value,\n                stderr=param.stderr,\n                chain=param.chain,\n            )\n            result_list.append(res)\n\n        fitted_values = np.array(varying_parameters)\n\n        # give each constrained param a chain (to be reshaped later)\n        constrained_params = [\n            param for param in flat_params if param.constraint is not None\n        ]\n\n        for constrain_param in constrained_params:\n            constrain_param.chain = np.empty(chain.shape[:-1], float)\n\n        # now iterate through the varying parameters, set the values, thereby\n        # setting the constraint value\n        if len(constrained_params):\n            for index in np.ndindex(chain.shape[:-1]):\n                # iterate over parameter vectors\n                pvals = chain[index]\n                objective.setp(pvals)\n\n                for constrain_param in constrained_params:\n                    constrain_param.chain[index] = constrain_param.value\n\n            for constrain_param in constrained_params:\n                quantiles = np.percentile(\n                    constrain_param.chain, [15.87, 50, 84.13]\n                )\n\n                std_l, median, std_u = quantiles\n                constrain_param.value = median\n                constrain_param.stderr = 0.5 * (std_u - std_l)\n\n        # now reset fitted parameter values (they would've been changed by\n        # constraints calculations\n        objective.setp(fitted_values)\n\n    # the parameter set are not Parameter objects, an array was probably\n    # being used with BaseObjective.\n    else:\n        for i in range(nvary):\n            c = np.copy(chain[..., i])\n            median, stderr = uncertainty_from_chain(c)\n            res = MCMCResult(\n                name=\"\", param=median, median=median, stderr=stderr, chain=c\n            )\n            result_list.append(res)\n\n    return result_list\n\n\ndef uncertainty_from_chain(chain):\n    \"\"\"\n    Calculates the median and uncertainty of MC samples.\n\n    Parameters\n    ----------\n    chain : array-like\n\n    Returns\n    -------\n    median, stderr : float, float\n        `median` of the chain samples. `stderr` is half the width of the\n        [15.87, 84.13] spread.\n    \"\"\"\n    flatchain = chain.flatten()\n    std_l, median, std_u = np.percentile(flatchain, [15.87, 50, 84.13])\n    return median, 0.5 * (std_u - std_l)\n\n\ndef autocorrelation_chain(chain, nburn=0, nthin=1):\n    \"\"\"\n    Calculate the autocorrelation function\n\n    Parameters\n    ----------\n    chain : np.ndarray\n        The MCMC chain - `(nsteps, nwalkers, ndim)` or\n        `(nsteps, ntemps, nwalkers, ndim)`\n\n    Returns\n    -------\n    acfs : np.ndarray\n        The autocorrelation function, acfs.shape=(lags, nvary)\n    \"\"\"\n    lchain = chain\n    # parallel tempered chain\n    if len(chain.shape) == 4:\n        lchain = lchain[:, 0]\n\n    lchain = lchain[nburn::nthin]\n    # (iterations, walkers, vary) -> (vary, walkers, iterations)\n    lchain = np.swapaxes(lchain, 0, 2)\n    shape = lchain.shape[:-1]\n\n    acfs = np.zeros_like(lchain)\n\n    # iterate over each parameter/walker\n    for index in np.ndindex(*shape):\n        s = _function_1d(lchain[index])\n        acfs[index] = s\n\n    # now average over walkers\n    acfs = np.mean(acfs, axis=1)\n    return np.transpose(acfs)\n\n\ndef bounds_list(parameters):\n    \"\"\"\n    Approximates interval bounds for a parameter set.\n\n    Parameters\n    ----------\n    parameters : sequence\n        A sequence containing individual parameters\n\n    Returns\n    -------\n    bounds: tuple\n        ``(min, max)`` pairs that define the finite lower and upper bounds\n        every element in ``parameters``.\n\n    If the `Bounds` applied by a parameter are a `PDF` instance then the upper\n    and lower bound are approximated by ``PDF.rv.ppf([0.005, 0.995])``, which\n    covers 99% of the statistical distribution.\n    \"\"\"\n    bounds = []\n    for param in parameters:\n        if hasattr(param, \"bounds\") and isinstance(param.bounds, Interval):\n            bnd = param.bounds\n            bounds.append((bnd.lb, bnd.ub))\n        elif (\n            hasattr(param, \"bounds\")\n            and isinstance(param.bounds, PDF)\n            and hasattr(param.bounds.rv, \"ppf\")\n        ):\n            bounds.append(param.bounds.rv.ppf([0.005, 0.995]))\n        else:\n            # We can't handle this bound\n            bounds.append((-np.inf, np.inf))\n\n    return bounds\n\n\n# Following code is for autocorrelation analysis of chains and is taken from\n# emcee.autocorr\ndef _next_pow_two(n):\n    \"\"\"Returns the next power of two greater than or equal to `n`\"\"\"\n    i = 1\n    while i < n:\n        i = i << 1\n    return i\n\n\ndef _function_1d(x):\n    \"\"\"Estimate the normalized autocorrelation function of a 1-D series\n\n    Args:\n        x: The series as a 1-D numpy array.\n\n    Returns:\n        array: The autocorrelation function of the time series.\n\n    \"\"\"\n    x = np.atleast_1d(x)\n    if len(x.shape) != 1:\n        raise ValueError(\"invalid dimensions for 1D autocorrelation function\")\n    n = _next_pow_two(len(x))\n\n    # Compute the FFT and then (from that) the auto-correlation function\n    f = np.fft.fft(x - np.mean(x), n=2 * n)\n    acf = np.fft.ifft(f * np.conjugate(f))[: len(x)].real\n    acf /= acf[0]\n    return acf\n", "meta": {"hexsha": "e3e65299fd41406d97fa3068a6272543098ca697", "size": 39411, "ext": "py", "lang": "Python", "max_stars_repo_path": "refnx/analysis/curvefitter.py", "max_stars_repo_name": "dcortie/refnx", "max_stars_repo_head_hexsha": "037434fa0a64755f72c540d75063986bd517ab10", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2016-04-18T15:29:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T08:35:29.000Z", "max_issues_repo_path": "refnx/analysis/curvefitter.py", "max_issues_repo_name": "dcortie/refnx", "max_issues_repo_head_hexsha": "037434fa0a64755f72c540d75063986bd517ab10", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 116, "max_issues_repo_issues_event_min_datetime": "2015-10-27T04:33:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T02:02:47.000Z", "max_forks_repo_path": "refnx/analysis/curvefitter.py", "max_forks_repo_name": "dcortie/refnx", "max_forks_repo_head_hexsha": "037434fa0a64755f72c540d75063986bd517ab10", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2015-09-29T23:21:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-27T18:12:18.000Z", "avg_line_length": 34.3002610966, "max_line_length": 79, "alphanum_fraction": 0.58420238, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 9098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.19401006102825624}}
{"text": "\"\"\"\nCreated on 01 Apr 2021 21:40:47\n@author: jiahuei\n\"\"\"\nimport logging\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import Tensor\nfrom argparse import ArgumentParser, _ArgumentGroup\nfrom typing import Optional, Union, Dict\nfrom copy import deepcopy\nfrom models import register_model\nfrom models.transformer import (\n    CachedMultiHeadedAttention, MultiHeadedAttention, PositionwiseFeedForward, PositionalEncoding,\n    InputEmbedding as Embeddings, OutputEmbedding as Generator,\n    LayerNorm, SublayerConnection,\n    Decoder, DecoderLayer, CachedTransformerBase\n)\nfrom data.collate import ObjectRelationCollate\nfrom utils.model_utils import repeat_tensors, pack_wrapper, clones\nfrom utils.misc import str_to_bool\n\nlogger = logging.getLogger(__name__)\n\n\n# noinspection PyAbstractClass\nclass EncoderComputerDecoder(nn.Module):\n    \"\"\"\n    A standard Encoder-Decoder architecture. Base for this and many\n    other models.\n    \"\"\"\n\n    def __init__(self, encoder, computer, decoder, src_embed, tgt_embed, generator):\n        super().__init__()\n        self.encoder = encoder\n        self.computer = computer\n        self.decoder = decoder\n        self.src_embed = src_embed\n        self.tgt_embed = tgt_embed\n        self.generator = generator\n\n    def forward(self, src, boxes, tgt, src_mask, tgt_mask):\n        \"\"\"Take in and process masked src and target sequences.\"\"\"\n        enc_out = self.encode(src, boxes, src_mask)\n        assert enc_out.size(0) == src_mask.size(0)\n        if logger.isEnabledFor(logging.DEBUG):\n            logger.debug(\n                f\"{self.__class__.__name__}: \"\n                f\"Encoder output shape = `{enc_out.shape}`    \"\n                f\"Target shape = `{tgt.shape}`\"\n            )\n        com_out = self.compute(enc_out, src_mask)\n        if com_out.size(0) != tgt.size(0):\n            assert tgt.size(0) % com_out.size(0) == 0\n            seq_per_img = int(tgt.size(0) / com_out.size(0))\n            com_out = repeat_tensors(seq_per_img, com_out)\n        return self.decode(com_out, None, tgt, tgt_mask), com_out\n\n    def encode(self, src, boxes, src_mask):\n        return self.encoder(self.src_embed(src), boxes, src_mask)\n\n    def compute(self, memory, src_mask):\n        return self.computer(memory, src_mask)\n\n    def decode(self, memory, src_mask, tgt, tgt_mask):\n        return self.decoder(self.tgt_embed(tgt), memory, src_mask, tgt_mask)\n\n\n# noinspection PyAbstractClass\nclass Computer(nn.Module):\n    \"\"\"Generic N layer decoder with masking.\"\"\"\n\n    def __init__(self, layer, N):\n        super().__init__()\n        self.inputs = nn.Parameter(torch.Tensor(1, 5, layer.size))\n        self.layers = clones(layer, N)\n        self.norm = LayerNorm(layer.size)\n\n    def forward(self, memory, src_mask):\n        x = self.inputs\n        x = repeat_tensors(memory.size(0), x)\n        for layer in self.layers:\n            x = layer(x, memory, src_mask)\n        return self.norm(x)\n\n\n# noinspection PyAbstractClass\nclass ComputerLayer(nn.Module):\n    \"\"\"Decoder is made of self-attn, src-attn, and feed forward (defined below)\"\"\"\n\n    def __init__(self, size, self_attn, src_attn, feed_forward, dropout):\n        super().__init__()\n        self.size = size\n        self.self_attn = self_attn\n        self.src_attn = src_attn\n        self.feed_forward = feed_forward\n        self.sublayer = clones(SublayerConnection(size, dropout), 3)\n\n    def forward(self, x, memory, src_mask):\n        \"\"\"Follow Figure 1 (right) for connections.\"\"\"\n        m = memory\n        x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x))\n        x = self.sublayer[1](x, lambda x: self.src_attn(x, m, m, src_mask))\n        return self.sublayer[2](x, self.feed_forward)\n\n\n# noinspection PyAbstractClass\nclass Encoder(nn.Module):\n    \"\"\"Core encoder is a stack of N layers\"\"\"\n\n    def __init__(self, layer, N):\n        super().__init__()\n        self.layers = clones(layer, N)\n        self.norm = LayerNorm(layer.size)\n\n    def forward(self, x, box, mask):\n        \"\"\"Pass the input (and mask) through each layer in turn.\"\"\"\n        for layer in self.layers:\n            x = layer(x, box, mask)\n        return self.norm(x)\n\n\n# noinspection PyAbstractClass\nclass EncoderLayer(nn.Module):\n    \"\"\"Encoder is made up of self-attn and feed forward (defined below)\"\"\"\n\n    def __init__(self, size, self_attn, feed_forward, dropout):\n        super().__init__()\n        self.self_attn = self_attn\n        self.feed_forward = feed_forward\n        self.sublayer = clones(SublayerConnection(size, dropout), 2)\n        self.size = size\n\n    def forward(self, x, box, mask):\n        \"\"\"Follow Figure 1 (left) for connections.\"\"\"\n        x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, box, mask))\n        return self.sublayer[1](x, self.feed_forward)\n\n\n# noinspection PyAbstractClass\nclass BoxMultiHeadedAttention(nn.Module):\n    \"\"\"\n    Self-attention layer with relative position weights.\n    Following the paper \"Relation Networks for Object Detection\" in https://arxiv.org/pdf/1711.11575.pdf\n    \"\"\"\n\n    def __init__(self, h, d_model, trigonometric_embedding=True, dropout=0.1):\n        \"\"\"Take in model size and number of heads.\"\"\"\n        super().__init__()\n\n        assert d_model % h == 0\n        self.trigonometric_embedding = trigonometric_embedding\n\n        # We assume d_v always equals d_k\n        self.h = h\n        self.d_k = d_model // h\n        if self.trigonometric_embedding:\n            self.dim_g = 64\n        else:\n            self.dim_g = 4\n        geo_feature_dim = self.dim_g\n\n        # matrices W_q, W_k, W_v, and one last projection layer\n        self.linears = clones(nn.Linear(d_model, d_model), 4)\n        self.WGs = clones(nn.Linear(geo_feature_dim, 1, bias=True), 8)\n\n        # self.attn = None\n        self.dropout = nn.Dropout(p=dropout)\n\n    def forward(self, input_query, input_key, input_value, input_box, mask=None):\n        \"\"\"Implements Figure 2 of Relation Network for Object Detection\"\"\"\n        if mask is not None:\n            # Same mask applied to all h heads.\n            mask = mask.unsqueeze(1)\n        nbatches = input_query.size(0)\n\n        # tensor with entries R_mn given by a hardcoded embedding of the relative position between bbox_m and bbox_n\n        relative_geometry_embeddings = self.BoxRelationalEmbedding(\n            input_box,\n            trigonometric_embedding=self.trigonometric_embedding\n        )\n        flatten_relative_geometry_embeddings = relative_geometry_embeddings.view(-1, self.dim_g)\n\n        # 1) Do all the linear projections in batch from d_model => h x d_k\n        query, key, value = [\n            l(x).view(nbatches, -1, self.h, self.d_k).transpose(1, 2)\n            for l, x in zip(self.linears, (input_query, input_key, input_value))\n        ]\n        box_size_per_head = list(relative_geometry_embeddings.shape[:3])\n        box_size_per_head.insert(1, 1)\n        relative_geometry_weights_per_head = [\n            ly(flatten_relative_geometry_embeddings).view(box_size_per_head) for ly in self.WGs\n        ]\n        relative_geometry_weights = torch.cat(relative_geometry_weights_per_head, 1)\n        relative_geometry_weights = F.relu(relative_geometry_weights)\n\n        # 2) Apply attention on all the projected vectors in batch.\n        x, box_attn = self.box_attention(\n            query, key, value, relative_geometry_weights, mask=mask, dropout=self.dropout\n        )\n\n        # 3) \"Concat\" using a view and apply a final linear.\n        x = x.transpose(1, 2).contiguous().view(nbatches, -1, self.h * self.d_k)\n\n        # # Legacy\n        # x = input_value + x\n\n        return self.linears[-1](x)\n\n    @staticmethod\n    def BoxRelationalEmbedding(f_g, dim_g=64, wave_len=1000, trigonometric_embedding=True):\n        \"\"\"\n        Given a tensor with bbox coordinates for detected objects on each batch image,\n        this function computes a matrix for each image\n\n        with entry (i,j) given by a vector representation of the\n        displacement between the coordinates of bbox_i, and bbox_j\n\n        input: np.array of shape=(batch_size, max_nr_bounding_boxes, 4)\n        output: np.array of shape=(batch_size, max_nr_bounding_boxes, max_nr_bounding_boxes, 64)\n        \"\"\"\n        # returns a relational embedding for each pair of bboxes, with dimension = dim_g\n        # follow implementation of https://github.com/heefe92/Relation_Networks-pytorch/blob/master/model.py#L1014-L1055\n\n        batch_size = f_g.size(0)\n\n        x_min, y_min, x_max, y_max = torch.chunk(f_g, 4, dim=-1)\n\n        cx = (x_min + x_max) * 0.5\n        cy = (y_min + y_max) * 0.5\n        w = (x_max - x_min) + 1.\n        h = (y_max - y_min) + 1.\n\n        # cx.view(1,-1) transposes the vector cx, and so dim(delta_x) = (dim(cx), dim(cx))\n        delta_x = cx - cx.view(batch_size, 1, -1)\n        delta_x = torch.clamp(torch.abs(delta_x / w), min=1e-3)\n        delta_x = torch.log(delta_x)\n\n        delta_y = cy - cy.view(batch_size, 1, -1)\n        delta_y = torch.clamp(torch.abs(delta_y / h), min=1e-3)\n        delta_y = torch.log(delta_y)\n\n        delta_w = torch.log(w / w.view(batch_size, 1, -1))\n        delta_h = torch.log(h / h.view(batch_size, 1, -1))\n\n        matrix_size = delta_h.size()\n        delta_x = delta_x.view(batch_size, matrix_size[1], matrix_size[2], 1)\n        delta_y = delta_y.view(batch_size, matrix_size[1], matrix_size[2], 1)\n        delta_w = delta_w.view(batch_size, matrix_size[1], matrix_size[2], 1)\n        delta_h = delta_h.view(batch_size, matrix_size[1], matrix_size[2], 1)\n\n        position_mat = torch.cat((delta_x, delta_y, delta_w, delta_h), -1)\n\n        if trigonometric_embedding:\n            feat_range = torch.arange(dim_g / 8, device=f_g.device)\n            dim_mat = feat_range / (dim_g / 8)\n            dim_mat = 1. / (torch.pow(wave_len, dim_mat))\n\n            dim_mat = dim_mat.view(1, 1, 1, -1)\n            position_mat = position_mat.view(batch_size, matrix_size[1], matrix_size[2], 4, -1)\n            position_mat = 100. * position_mat\n\n            mul_mat = position_mat * dim_mat\n            mul_mat = mul_mat.view(batch_size, matrix_size[1], matrix_size[2], -1)\n            sin_mat = torch.sin(mul_mat)\n            cos_mat = torch.cos(mul_mat)\n            embedding = torch.cat((sin_mat, cos_mat), -1)\n        else:\n            embedding = position_mat\n        return embedding\n\n    @staticmethod\n    def box_attention(query, key, value, box_relation_embds_matrix, mask=None, dropout=None):\n        \"\"\"\n        Compute 'Scaled Dot Product Attention as in paper Relation Networks for Object Detection'.\n        Follow the implementation in\n        https://github.com/heefe92/Relation_Networks-pytorch/blob/master/model.py#L1026-L1055\n        \"\"\"\n\n        N = value.size()[:2]\n        dim_k = key.size(-1)\n        dim_g = box_relation_embds_matrix.size()[-1]\n\n        w_q = query\n        w_k = key.transpose(-2, -1)\n        w_v = value\n\n        # attention weights\n        scaled_dot = torch.matmul(w_q, w_k)\n        scaled_dot = scaled_dot / np.sqrt(dim_k)\n        if mask is not None:\n            scaled_dot = scaled_dot.masked_fill(mask == 0, -1e9)\n\n        # w_g = box_relation_embds_matrix.view(N,N)\n        w_g = box_relation_embds_matrix\n        w_a = scaled_dot\n        # w_a = scaled_dot.view(N,N)\n\n        # multiplying log of geometric weights by feature weights\n        w_mn = torch.log(torch.clamp(w_g, min=1e-6)) + w_a\n        w_mn = torch.nn.Softmax(dim=-1)(w_mn)\n        if dropout is not None:\n            w_mn = dropout(w_mn)\n\n        output = torch.matmul(w_mn, w_v)\n\n        return output, w_mn\n\n\n# noinspection PyAbstractClass,PyAttributeOutsideInit\n@register_model(\"ort_computer\")\nclass ORTComputerModel(CachedTransformerBase):\n    COLLATE_FN = ObjectRelationCollate\n\n    def __init__(self, config):\n        super().__init__(config)\n        self.box_trigonometric_embedding = True\n        self.make_model()\n\n    def make_model(self, h=8, dropout=0.1):\n        \"\"\"Helper: Construct a model from hyperparameters.\"\"\"\n        bbox_attn = BoxMultiHeadedAttention(h, self.d_model, self.box_trigonometric_embedding)\n        attn = CachedMultiHeadedAttention(h, self.d_model)\n        self_attn = deepcopy(attn)\n        self_attn.self_attention = True\n        ff = PositionwiseFeedForward(self.d_model, self.dim_feedforward, dropout)\n        position = PositionalEncoding(self.d_model, dropout)\n        model = EncoderComputerDecoder(\n            Encoder(EncoderLayer(\n                self.d_model, deepcopy(bbox_attn), deepcopy(ff), dropout), self.num_layers\n            ),\n            Computer(ComputerLayer(\n                self.d_model, MultiHeadedAttention(h, self.d_model), MultiHeadedAttention(h, self.d_model),\n                deepcopy(ff), dropout), self.num_layers\n            ),\n            Decoder(DecoderLayer(\n                self.d_model, self_attn, attn, deepcopy(ff), dropout), self.num_layers\n            ),\n            lambda x: x,  # nn.Sequential(Embeddings(self.d_model, src_vocab), deepcopy(position)),\n            nn.Sequential(Embeddings(self.d_model, self.vocab_size), deepcopy(position)),\n            Generator(self.d_model, self.vocab_size)\n        )\n        self.att_embed = nn.Sequential(\n            nn.Linear(self.att_feat_size, self.d_model),\n            nn.ReLU(),\n            nn.Dropout(self.drop_prob_src)\n        )\n        # This was important from their code.\n        # Initialize parameters with Glorot / fan_avg.\n        for p in model.parameters():\n            if p.dim() > 1:\n                nn.init.xavier_uniform_(p)\n        self.model = model\n\n    def _prepare_feature(\n            self,\n            att_feats: Tensor,\n            att_masks: Optional[Tensor] = None,\n            boxes: Optional[Tensor] = None,\n            seq: Optional[Tensor] = None\n    ):\n\n        att_feats, att_masks = self.clip_att(att_feats, att_masks)\n        att_feats = pack_wrapper(self.att_embed, att_feats, att_masks)\n\n        if att_masks is None:\n            att_masks = att_feats.new_ones(att_feats.shape[:2], dtype=torch.long)\n        att_masks = att_masks.unsqueeze(-2)\n\n        if seq is not None:\n            # crop the last one\n            seq = seq[:, :-1]\n            seq_mask = seq.data.ne(self.pad_idx)  # seq_mask: torch.Tensor\n            seq_mask = seq_mask.unsqueeze(-2)\n            seq_mask = seq_mask & self.subsequent_mask(seq.size(-1)).to(seq_mask)\n        else:\n            seq_mask = None\n\n        return att_feats, boxes, seq, att_masks, seq_mask\n\n    # noinspection PyMethodOverriding\n    def _forward(self, att_feats, boxes, seqs, att_masks=None, **kwargs):\n        att_feats, boxes, seq, att_masks, seq_mask = self._prepare_feature(att_feats, att_masks, boxes, seqs)\n        out = self.model(att_feats, boxes, seq, att_masks, seq_mask)\n        outputs = self.model.generator(out[0])\n        return outputs #, self.model.generator(out[1])\n\n    def get_logprobs_state(self, it, memory, mask, state):\n        \"\"\"\n        state = [ys.unsqueeze(0)]\n        \"\"\"\n        ys = it.unsqueeze(1)\n        if state is None:\n            pass\n        else:\n            # Retrieve reordered cache from state, and update them\n            self._update_caches(state[1:])\n        out = self.model.decode(\n            memory, mask, ys, self.subsequent_mask(ys.size(1)).to(memory.device)\n        )\n        logprobs = self.model.generator(out[:, -1])\n        # Add layer cache into state list, transposed so that beam_step can reorder them\n        return logprobs, [ys.unsqueeze(0)] + self._retrieve_caches()\n\n    # noinspection PyMethodOverriding\n    def _sample(self, att_feats, boxes, att_masks=None, opt=None, **kwargs):\n        if opt is None:\n            opt = {}\n        att_feats, boxes, seq, att_masks, seq_mask = self._prepare_feature(att_feats, att_masks, boxes)\n        memory = self.model.encode(att_feats, boxes, att_masks)\n        memory = self.model.compute(memory, att_masks)\n        state = None\n        mask = torch.ones(size=(memory.size(0), 1, memory.size(1)), dtype=memory.dtype, device=memory.device)\n        return self._generate_captions(att_feats, mask, memory, state, opt)\n\n    @staticmethod\n    def clip_att(att_feats, att_masks):\n        # Clip the length of att_masks and att_feats to the maximum length\n        if att_masks is not None:\n            max_len = att_masks.data.long().sum(1).max()\n            att_feats = att_feats[:, :max_len].contiguous()\n            att_masks = att_masks[:, :max_len].contiguous()\n        return att_feats, att_masks\n\n    @staticmethod\n    def subsequent_mask(size):\n        \"\"\"Mask out subsequent positions.\"\"\"\n        attn_shape = (1, size, size)\n        mask = torch.triu(torch.ones(attn_shape), diagonal=1).eq(0)\n        return mask\n\n    @staticmethod\n    def add_argparse_args(parser: Union[_ArgumentGroup, ArgumentParser]):\n        # fmt: off\n        ORTComputerModel.COLLATE_FN.add_argparse_args(parser)\n        CachedTransformerBase.add_argparse_args(parser)\n        # Relation args\n        parser.add_argument(\n            \"--box_trigonometric_embedding\", type=str_to_bool,\n            default=True\n        )\n        # fmt: on\n        # return parser\n", "meta": {"hexsha": "bcb0596931eb4492e1f7fcdcb3dddec8f8c7061d", "size": 17159, "ext": "py", "lang": "Python", "max_stars_repo_path": "caption_vae/models/relation_transformer_computer.py", "max_stars_repo_name": "jiahuei/test-caption-actions", "max_stars_repo_head_hexsha": "cbf68dc29a0fdafe92730bf4881319bcbd41eb7f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-01-24T00:28:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-04T12:34:07.000Z", "max_issues_repo_path": "caption_vae/models/relation_transformer_computer.py", "max_issues_repo_name": "jiahuei/test-caption-actions", "max_issues_repo_head_hexsha": "cbf68dc29a0fdafe92730bf4881319bcbd41eb7f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "caption_vae/models/relation_transformer_computer.py", "max_forks_repo_name": "jiahuei/test-caption-actions", "max_forks_repo_head_hexsha": "cbf68dc29a0fdafe92730bf4881319bcbd41eb7f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4730941704, "max_line_length": 120, "alphanum_fraction": 0.6374497348, "include": true, "reason": "import numpy", "num_tokens": 4176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.1939596047170351}}
{"text": "import sys\nimport os\nimport ctypes\nimport glob\nimport warnings\nimport numpy as np\nfrom math import fsum, sqrt\n\nimport MulensModel\nfrom MulensModel.utils import Utils\ntry:\n    import MulensModel.VBBL as mm_vbbl\nexcept Exception:\n    _vbbl_wrapped = False\nelse:\n    _vbbl_wrapped = True\ntry:\n    import MulensModel.AdaptiveContouring as mm_ac\nexcept Exception:\n    _adaptive_contouring_wrapped = False\nelse:\n    _adaptive_contouring_wrapped = True\n\n\ndef _try_load(path, name):\n    \"\"\"\n    Try loading compiled C library.\n    Input is *str* or *list* of *str*.\n    \"\"\"\n    if isinstance(path, str):\n        path = [path]\n    for path_ in path:\n        try:\n            out = ctypes.cdll.LoadLibrary(path_)\n        except OSError:\n            print(\"WARNING - File not loaded:\", path_)\n            print(\"Everything should work except:\", name)\n            pass\n        else:\n            return out\n    return None\n\n\ndef _get_path_2(name_1, name_2):\n    \"\"\"convenience function\"\"\"\n    module_path = os.path.abspath(__file__)\n    for i in range(3):\n        module_path = os.path.dirname(module_path)\n    return os.path.join(module_path, 'source', name_1, name_2)\n\n\ndef _import_compiled_VBBL():\n    \"\"\"try importing manually compiled VBBL package\"\"\"\n    vbbl = _try_load(\n        _get_path_2('VBBL', \"VBBinaryLensingLibrary_wrapper.so\"), \"VBBL\")\n    _vbbl_wrapped = (vbbl is not None)\n    if not _vbbl_wrapped:\n        return (_vbbl_wrapped, None, None)\n\n    vbbl.VBBinaryLensing_BinaryMagDark.argtypes = 7 * [ctypes.c_double]\n    vbbl.VBBinaryLensing_BinaryMagDark.restype = ctypes.c_double\n\n    vbbl.VBBL_SG12_5.argtypes = 12 * [ctypes.c_double]\n    vbbl.VBBL_SG12_5.restype = np.ctypeslib.ndpointer(\n        dtype=ctypes.c_double, shape=(10,))\n\n    return (_vbbl_wrapped,\n            vbbl.VBBinaryLensing_BinaryMagDark, vbbl.VBBL_SG12_5)\n\n\ndef _import_compiled_AdaptiveContouring():\n    \"\"\"try importing manually compiled AdaptiveContouring package\"\"\"\n    ac = \"AdaptiveContouring\"\n    adaptive_contour = _try_load(_get_path_2(ac, ac + \"_wrapper.so\"), ac)\n    _adaptive_contouring_wrapped = (adaptive_contour is not None)\n    if not _adaptive_contouring_wrapped:\n        return (_adaptive_contouring_wrapped, None)\n    adaptive_contour.Adaptive_Contouring_Linear.argtypes = (\n        8 * [ctypes.c_double])\n    adaptive_contour.Adaptive_Contouring_Linear.restype = ctypes.c_double\n    return (_adaptive_contouring_wrapped,\n            adaptive_contour.Adaptive_Contouring_Linear)\n\n\n# Check import and try manually compiled versions.\nif _vbbl_wrapped:\n    _vbbl_binary_mag_dark = mm_vbbl.VBBinaryLensing_BinaryMagDark\n    _vbbl_SG12_5 = mm_vbbl.VBBL_SG12_5\nelse:\n    out = _import_compiled_VBBL()\n    _vbbl_wrapped = out[0]\n    _vbbl_binary_mag_dark = out[1]\n    _vbbl_SG12_5 = out[2]\nif not _vbbl_wrapped:\n    _solver = 'numpy'\nelse:\n    _solver = 'Skowron_and_Gould_12'\nif _adaptive_contouring_wrapped:\n    _adaptive_contouring_linear = mm_ac.Adaptive_Contouring_Linear\nelse:\n    out = _import_compiled_AdaptiveContouring()\n    _adaptive_contouring_wrapped = out[0]\n    _adaptive_contouring_linear = out[1]\n\n\nclass BinaryLens(object):\n    \"\"\"\n    The binary lens equation - its solutions, images, parities,\n    magnifications, etc.\n\n    The binary lens equation is a 5th order complex polynomial.\n\n    Attributes :\n        mass_1: *float*\n            mass of the primary (left-hand object) as a fraction of\n            the total mass.\n\n        mass_2: *float*\n            mass of the secondary (right-hand object) as a fraction of the\n            total mass.\n\n        separation: *float*\n            separation between the two bodies as a fraction of the Einstein\n            ring.\n\n    Note: mass_1 and mass_2 may be defined as a fraction of some other\n    mass than the total mass. This is possible but not recommended -\n    make sure you know what you're doing before you start using this\n    possibility.\n\n    \"\"\"\n    def __init__(self, mass_1=None, mass_2=None, separation=None):\n        self.mass_1 = float(mass_1)  # This speeds-up code for np.float input.\n        self.mass_2 = float(mass_2)\n        self.separation = float(separation)\n        self._total_mass = None\n        self._mass_difference = None\n        self._position_z1 = None\n        self._position_z2 = None\n        self._last_polynomial_input = None\n        self._solver = _solver\n        self._use_planet_frame = True\n\n    def _calculate_variables(self, source_x, source_y):\n        \"\"\"calculates values of constants needed for polynomial coefficients\"\"\"\n        self._total_mass = 0.5 * (self.mass_1 + self.mass_2)\n        # This is total_mass in WM95 paper.\n\n        self._mass_difference = 0.5 * (self.mass_2 - self.mass_1)\n        self._zeta = source_x + source_y * 1.j\n        if self._use_planet_frame:\n            self._position_z1 = -self.separation + 0.j\n            self._position_z2 = 0. + 0.j\n        else:\n            self._position_z1 = -0.5 * self.separation + 0.j\n            self._position_z2 = 0.5 * self.separation + 0.j\n\n    def _get_polynomial(self, source_x, source_y):\n        \"\"\"get polynomial coefficients\"\"\"\n        if self._use_planet_frame:\n            return self._get_polynomial_planet_frame(source_x, source_y)\n        else:\n            return self._get_polynomial_WM95(source_x, source_y)\n\n    def _get_polynomial_WM95(self, source_x, source_y):\n        \"\"\"\n        calculate coefficients of the polynomial in geometric center frame\n        \"\"\"\n        # Calculate constants\n        self._calculate_variables(source_x=source_x, source_y=source_y)\n        total_m = self._total_mass\n        total_m_pow2 = total_m * total_m\n\n        m_diff = self._mass_difference\n        m_diff_pow2 = m_diff * m_diff\n\n        pos_z1 = self._position_z1\n\n        z1_pow2 = pos_z1 * pos_z1\n        z1_pow3 = z1_pow2 * pos_z1\n        z1_pow4 = z1_pow2 * z1_pow2\n\n        zeta = self._zeta\n        zeta_conj = zeta.conjugate()\n        zeta_conj_pow2 = zeta_conj * zeta_conj\n\n        # Calculate the coefficients of the 5th order complex polynomial\n        coeff_5 = Utils.complex_fsum([z1_pow2, -zeta_conj_pow2])\n        coeff_4 = Utils.complex_fsum(\n            [-2. * total_m * zeta_conj,\n             zeta * zeta_conj_pow2, -2. * m_diff * pos_z1,\n             -zeta * z1_pow2])\n        coeff_3 = Utils.complex_fsum(\n            [4. * total_m * zeta * zeta_conj,\n             4. * m_diff * zeta_conj * pos_z1,\n             2. * zeta_conj_pow2 * z1_pow2, -2. * z1_pow4])\n        coeff_2 = Utils.complex_fsum(\n            [4. * total_m_pow2 * zeta,\n             4. * total_m * m_diff * pos_z1,\n             -4. * m_diff * zeta * zeta_conj * pos_z1,\n             -2. * zeta * zeta_conj_pow2 * z1_pow2,\n             4. * m_diff * z1_pow3, 2. * zeta * z1_pow4])\n        coeff_1 = Utils.complex_fsum(\n            [-8. * total_m * m_diff * zeta * pos_z1,\n             -4. * m_diff_pow2 * z1_pow2,\n             -4. * total_m_pow2 * z1_pow2,\n             -4. * total_m * zeta * zeta_conj * z1_pow2,\n             -4. * m_diff * zeta_conj * z1_pow3,\n             -zeta_conj_pow2 * z1_pow4, z1_pow3 * z1_pow3])\n        coeff_0 = Utils.complex_fsum(\n            [4. * m_diff_pow2 * zeta,\n             4. * total_m * m_diff * pos_z1,\n             4. * m_diff * zeta * zeta_conj * pos_z1,\n             2. * total_m * zeta_conj * z1_pow2,\n             zeta * zeta_conj_pow2 * z1_pow2,\n             -2. * m_diff * z1_pow3 - zeta * z1_pow4])\n        coeff_0 *= z1_pow2\n\n        # Return the coefficients of the polynomial\n        coeffs_list = [coeff_0, coeff_1, coeff_2, coeff_3, coeff_4, coeff_5]\n        return np.array(coeffs_list).reshape(6)\n\n    def _get_polynomial_planet_frame(self, source_x, source_y):\n        \"\"\"calculate coefficients of the polynomial in planet frame\"\"\"\n        # Calculate constants\n        self._calculate_variables(source_x=source_x, source_y=source_y)\n        total_m = self._total_mass\n\n        m_diff = self._mass_difference\n\n        zeta = self._zeta\n        zeta_conj = zeta.conjugate()\n\n        c_sum = Utils.complex_fsum\n\n        z1 = self._position_z1\n\n        coeff_5 = c_sum([z1, -zeta_conj]) * zeta_conj\n        coeff_4 = c_sum([\n            (-m_diff + total_m) * z1,\n            -c_sum([2. * total_m, z1 * c_sum([2. * z1, zeta])]) * zeta_conj,\n            c_sum([2. * z1 + zeta]) * zeta_conj**2\n            ])\n        coeff_3 = c_sum([\n            z1 * c_sum([m_diff * z1, -total_m * c_sum([z1, 2. * zeta])]),\n            zeta_conj * c_sum([\n                2. * m_diff * z1,\n                c_sum([2. * total_m, z1**2]) * c_sum([z1, 2. * zeta])\n                ]),\n            -z1 * c_sum([z1, 2. * zeta]) * zeta_conj**2\n            ])\n        coeff_2 = c_sum([\n            m_diff * z1 * c_sum([2. * total_m, z1 * zeta]),\n            total_m * c_sum([\n                -2. * total_m * z1, 4. * total_m * zeta, 3. * z1**2 * zeta]),\n            -z1 * zeta_conj * c_sum([\n                zeta * c_sum([6. * total_m, z1**2]),\n                2. * m_diff * c_sum([z1, zeta])\n                ]),\n            z1**2 * zeta * zeta_conj**2\n            ])\n        coeff_1 = -z1 * (m_diff + total_m) * c_sum([\n            m_diff * z1, -total_m * z1, 4. * total_m * zeta, z1**2 * zeta,\n            -2. * z1 * zeta * zeta_conj\n            ])\n        coeff_0 = (m_diff + total_m)**2 * z1**2 * zeta\n\n        coeffs_list = [coeff_0, coeff_1, coeff_2, coeff_3, coeff_4, coeff_5]\n        return np.array(coeffs_list).reshape(6)\n\n    def _get_polynomial_roots(self, source_x, source_y):\n        \"\"\"roots of the polynomial\"\"\"\n        polynomial_input = [self.mass_1, self.mass_2, self.separation,\n                            source_x, source_y]\n\n        if polynomial_input == self._last_polynomial_input:\n            return self._polynomial_roots\n\n        polynomial = self._get_polynomial(\n            source_x=source_x, source_y=source_y)\n\n        np_polyroots = np.polynomial.polynomial.polyroots\n        if self._solver == 'numpy':\n            self._polynomial_roots = np_polyroots(polynomial)\n        elif self._solver == 'Skowron_and_Gould_12':\n            args = polynomial.real.tolist() + polynomial.imag.tolist()\n            try:\n                out = _vbbl_SG12_5(*args)\n            except ValueError as err:\n                err2 = \"\\n\\nSwitching from Skowron & Gould 2012 to numpy\"\n                warnings.warn(str(err) + err2, UserWarning)\n                self._solver = 'numpy'\n                self._polynomial_roots = np_polyroots(polynomial)\n            else:\n                self._polynomial_roots = np.array([\n                    out[0]+out[5]*1.j, out[1]+out[6]*1.j, out[2]+out[7]*1.j,\n                    out[3]+out[8]*1.j, out[4]+out[9]*1.j])\n        else:\n            raise ValueError('Unknown solver: {:}'.format(self._solver))\n        self._last_polynomial_input = polynomial_input\n\n        return self._polynomial_roots\n\n    def _polynomial_roots_ok(\n            self, source_x, source_y, return_distances=False):\n        \"\"\"verified roots of polynomial i.e. roots of lens equation\"\"\"\n        roots = self._get_polynomial_roots(\n            source_x=source_x, source_y=source_y)\n\n        # Two lines below are simplified assuming\n        # self._position_z1.imag = 0 and same for z2.\n        roots_conj = np.conjugate(roots)\n        solutions = (self._zeta +\n                     self.mass_1 / (roots_conj - self._position_z1) +\n                     self.mass_2 / (roots_conj - self._position_z2))\n        # This backs-up the lens equation.\n\n        out = []\n        distances = []\n        for (i, root) in enumerate(roots):\n            distances_from_root = abs((solutions-root)**2)\n            min_distance_arg = np.argmin(distances_from_root)\n\n            if i == min_distance_arg:\n                out.append(root)\n                distances.append(distances_from_root[min_distance_arg])\n            # The values in distances[] are a diagnostic on how good the\n            # numerical accuracy is.\n\n        # If the lens equation is solved correctly, there should be\n        # either 3 or 5 solutions (corresponding to 3 or 5 images)\n        if len(out) not in [3, 5]:\n            msg = (\"Wrong number of solutions to the lens equation of binary\" +\n                   \" lens.\\nGot {:} and expected 3 or 5.\\nThe parameters \" +\n                   \"(m1, m2, s, source_x, source_y, solver) are:\\n\" +\n                   \"{:} {:} {:} {:} {:}  {:}\\n\\n\" +\n                   \"Consider using 'point_source_point_lens' method for \" +\n                   \"epochs when the source is very far from the lens. Note \" +\n                   \"that it's different from 'point_source' method.\")\n            txt = msg.format(\n                len(out), repr(self.mass_1), repr(self.mass_2),\n                repr(self.separation), repr(source_x), repr(source_y),\n                self._solver)\n\n            if self._solver != \"Skowron_and_Gould_12\":\n                txt += (\n                    \"\\n\\nYou should switch to using Skowron_and_Gould_12\" +\n                    \" polynomial root solver. It is much more accurate than \" +\n                    \"numpy.polynomial.polynomial.polyroots(). \" +\n                    \"Skowron_and_Gould_12 method is selected in automated \" +\n                    \"way if VBBL is imported properly.\")\n            else:\n                distance = sqrt(source_x**2 + source_y**2)\n                if (self.mass_2 > 1.e-6 * self.mass_1 and\n                        (distance < 15. or distance < 2. * self.separation)):\n                    txt += (\"\\n\\nThis is surprising error - please contact \" +\n                            \"code authors and provide the above error \" +\n                            \"message.\")\n            txt += \"\\nMulensModel version: {:}\".format(MulensModel.__version__)\n\n            raise ValueError(txt)\n\n        if return_distances:\n            return (np.array(out), np.array(distances))\n        else:\n            return np.array(out)\n\n    def _jacobian_determinant_ok(self, source_x, source_y):\n        \"\"\"determinants of lens equation Jacobian for verified roots\"\"\"\n        roots_ok_bar = np.conjugate(self._polynomial_roots_ok(\n                                   source_x=source_x, source_y=source_y))\n        # Variable X_bar is conjugate of variable X.\n        add_1 = self.mass_1 / (self._position_z1 - roots_ok_bar)**2\n        add_2 = self.mass_2 / (self._position_z2 - roots_ok_bar)**2\n        derivative = add_1 + add_2\n\n        return 1. - derivative * np.conjugate(derivative)\n\n    def _signed_magnification(self, source_x, source_y):\n        \"\"\"signed magnification for each image separately\"\"\"\n        return 1. / self._jacobian_determinant_ok(\n                source_x=source_x, source_y=source_y)\n\n    def _point_source(self, source_x, source_y):\n        \"\"\"calculate point source magnification\"\"\"\n        signed_magnification = self._signed_magnification(\n            source_x=source_x, source_y=source_y)\n        return fsum(abs(signed_magnification))\n\n    def _point_source_Witt_Mao_95(self, source_x, source_y):\n        \"\"\"calculate point source magnification\"\"\"\n        return self._point_source(source_x=source_x, source_y=source_y)\n\n    def point_source_magnification(self, source_x, source_y):\n        \"\"\"\n        Calculate point source magnification for given position. The\n        origin of the coordinate system is at the center of mass and\n        both masses are on X axis with higher mass at negative X; this\n        means that the higher mass is at (X, Y)=(-s*q/(1+q), 0) and\n        the lower mass is at (s/(1+q), 0).\n\n        Parameters :\n            source_x: *float*\n                X-axis coordinate of the source.\n\n            source_y: *float*\n                Y-axis coordinate of the source.\n\n        Returns :\n            magnification: *float*\n                Point source magnification.\n        \"\"\"\n        if self._use_planet_frame:\n            x_shift = -self.mass_1 / (self.mass_1 + self.mass_2)\n        else:\n            x_shift = self.mass_2 / (self.mass_1 + self.mass_2) - 0.5\n        x_shift *= self.separation\n        # We need to add this because in order to shift to correct frame.\n        return self._point_source_Witt_Mao_95(\n                source_x=float(source_x)+x_shift, source_y=float(source_y))\n        # Casting to float speeds-up code for np.float input.\n\n    def _get_magnification_w_plus(self, source_x, source_y, radius,\n                                  magnification_center=None):\n        \"\"\"Evaluates Gould (2008) eq. 7\"\"\"\n        dx = [1., 0., -1., 0.]\n        dy = [0., 1., 0., -1.]\n        out = []\n        for (i, dxval) in enumerate(dx):\n            x = source_x + dxval * radius\n            y = source_y + dy[i] * radius\n            out.append(self.point_source_magnification(\n                                              source_x=x, source_y=y))\n        if magnification_center is None:\n            magnification_center = self.point_source_magnification(\n                                    source_x=source_x, source_y=source_y)\n        return 0.25 * fsum(out) - magnification_center\n\n    def _get_magnification_w_times(self, source_x, source_y, radius,\n                                   magnification_center=None):\n        \"\"\"Evaluates Gould (2008) eq. 8\"\"\"\n        shift = radius / sqrt(2.)\n        dx = [1., -1., -1., 1.]\n        dy = [1., 1., -1., -1.]\n        out = []\n        for (i, dxval) in enumerate(dx):\n            x = source_x + dxval * shift\n            y = source_y + dy[i] * shift\n            out.append(self.point_source_magnification(\n                                              source_x=x, source_y=y))\n        if magnification_center is None:\n            magnification_center = self.point_source_magnification(\n                                    source_x=source_x, source_y=source_y)\n        return 0.25 * fsum(out) - magnification_center\n\n    def _rho_check(self, rho):\n        \"\"\"\n        Check if rho is float and positive.\n        \"\"\"\n        if rho is None:\n            raise TypeError(\n                'rho must be positive float, but None was provided')\n        if not isinstance(rho, float):\n            raise TypeError(\n                'rho must be positive float, but ' + str(rho) +\n                str(type(rho)) + ' was provided')\n        if rho < 0:\n            raise ValueError(\n                'rho must be positive, got: {:}'.format(rho))\n\n    def hexadecapole_magnification(self, source_x, source_y, rho, gamma,\n                                   quadrupole=False, all_approximations=False):\n        \"\"\"\n        Magnification in hexadecapole approximation of the\n        binary-lens/finite-source event - based on `Gould 2008 ApJ\n        681, 1593\n        <https://ui.adsabs.harvard.edu/abs/2008ApJ...681.1593G/abstract>`_.\n\n        For coordinate system convention see\n        :py:func:`point_source_magnification()`\n\n        Parameters :\n            source_x: *float*\n                X-axis coordinate of the source.\n\n            source_y: *float*\n                Y-axis coordinate of the source.\n\n            rho: *float*\n                Source size relative to Einstein ring radius.\n\n            gamma: *float*\n                Linear limb-darkening coefficient in gamma convention.\n\n            quadrupole: *boolean*, optional\n                Return quadrupole approximation instead of hexadecapole?\n                Default is *False*.\n\n            all_approximations: *boolean*, optional\n                Return hexadecapole, quadrupole, and point source\n                approximations? Default is *False*.\n\n        Returns :\n            magnification: *float* or *sequence* of three *floats*\n                Hexadecapole approximation (*float*) by default.\n                Quadrupole approximation (*float*) if *quadrupole*\n                parameter is *True*. Hexadecapole, quadrupole, and\n                point source approximations (*sequence* of three\n                *floats*) if *all_approximations* parameter is *True*.\n        \"\"\"\n        # In this function, variables named a_* depict magnification.\n        if quadrupole and all_approximations:\n            raise ValueError('Inconsistent parameters of ' +\n                             'BinaryLens.hexadecapole_magnification()')\n        self._rho_check(rho)\n\n        a_center = self.point_source_magnification(\n            source_x=source_x, source_y=source_y)\n        a_rho_half_plus = self._get_magnification_w_plus(\n            source_x=source_x, source_y=source_y, radius=0.5*rho,\n            magnification_center=a_center)\n        a_rho_plus = self._get_magnification_w_plus(\n            source_x=source_x, source_y=source_y, radius=rho,\n            magnification_center=a_center)\n\n        # This is Gould 2008 eq. 9:\n        a_2_rho_square = (16. * a_rho_half_plus - a_rho_plus) / 3.\n\n        # Gould 2008 eq. 6 (part 1/2):\n        a_quadrupole = a_center + a_2_rho_square * (1. - 0.2 * gamma)\n\n        # At this point is quadrupole approximation is finished\n        if quadrupole:\n            return a_quadrupole\n\n        a_rho_times = self._get_magnification_w_times(\n            source_x=source_x, source_y=source_y, radius=rho,\n            magnification_center=a_center)\n\n        # This is Gould (2008) eq. 9:\n        a_4_rho_power4 = 0.5 * (a_rho_plus + a_rho_times) - a_2_rho_square\n        # This is Gould (2008) eq. 6 (part 2/2):\n        a_add = a_4_rho_power4 * (1. - 11. * gamma / 35.)\n        a_hexadecapole = a_quadrupole + a_add\n\n        if all_approximations:\n            return (a_hexadecapole, a_quadrupole, a_center)\n        else:\n            return a_hexadecapole\n\n    def adaptive_contouring_magnification(\n            self, source_x, source_y, rho, gamma=None, u_limb_darkening=None,\n            accuracy=0.1, ld_accuracy=0.001):\n        \"\"\"\n        Binary lens finite source magnification calculated using\n        Adaptive Contouring method by `Dominik 2007 MNRAS, 377, 1679\n        <https://ui.adsabs.harvard.edu/abs/2007MNRAS.377.1679D/abstract>`_\n\n        See also\n        `AdaptiveContouring website by Martin Dominik\n        <http://star-www.st-and.ac.uk/~md35/Software.html>`_\n\n        For coordinate system convention see\n        :py:func:`point_source_magnification()`\n\n        Parameters :\n            source_x: *float*\n                X-axis coordinate of the source.\n\n            source_y: *float*\n                Y-axis coordinate of the source.\n\n            rho: *float*\n                Source size relative to Einstein ring radius.\n\n            gamma: *float*, optional\n                Linear limb-darkening coefficient in gamma convention.\n\n            u_limb_darkening: *float*\n                Linear limb-darkening coefficient in u convention.\n                Note that either *gamma* or *u_limb_darkening* can be\n                set.  If neither of them is provided then limb\n                darkening is ignored.\n\n            accuracy: *float*, optional\n                Requested accuracy of the result defined as the sum of\n                the area of the squares that determine the contour\n                line and the estimated total enclosed area (see sec. 4\n                of the paper).  As M. Dominik states: *\"this vastly\n                overestimates the fractional error, and a suitable\n                value should be chosen by testing how its variation\n                affects the final results - I recommend starting at\n                acc = 0.1.\"* It significantly affects execution time.\n\n            ld_accuracy: *float*, optional\n                Requested limb-darkening accuracy. As M. Dominik\n                states: *\" Fractional uncertainty for the adaptive\n                Simpson integration of the limb-darkening\n                profile-related function during application of Green's\n                theorem.\"* It does not add execution time so can be\n                set to very small value.\n\n        Returns :\n            magnification: *float*\n                Magnification.\n\n\n        \"\"\"\n        if accuracy <= 0.:\n            raise ValueError('adaptive_contouring requires accuracy > 0')\n        if ld_accuracy <= 0.:\n            raise ValueError('adaptive_contouring requires ld_accuracy > 0')\n        # Note that this accuracy is not guaranteed.\n        self._rho_check(rho)\n\n        if not _adaptive_contouring_wrapped:\n            raise ValueError('Adaptive Contouring was not imported properly')\n\n        if gamma is not None and u_limb_darkening is not None:\n            raise ValueError(\n                'Only one limb darkening parameters can be set' +\n                ' in BinaryLens.adaptive_contouring_magnification()')\n        elif gamma is not None:\n            gamma = float(gamma)\n        elif u_limb_darkening is not None:\n            gamma = float(Utils.u_to_gamma(u_limb_darkening))\n        else:\n            gamma = float(0.0)\n\n        s = float(self.separation)\n        q = float(self.mass_2 / self.mass_1)\n        # AdaptiveContouring uses different coordinates conventions,\n        # so we have to transform the coordinates below.\n        x = float(-source_x)\n        y = float(-source_y)\n        rho = float(rho)\n        accuracy = float(accuracy)\n        ld_accuracy = float(ld_accuracy)\n\n        magnification = _adaptive_contouring_linear(\n            s, q, x, y, rho, gamma, accuracy, ld_accuracy)\n\n        return magnification\n\n    def vbbl_magnification(self, source_x, source_y, rho,\n                           gamma=None, u_limb_darkening=None,\n                           accuracy=0.001):\n        \"\"\"\n        Binary lens finite source magnification calculated using VBBL\n        library that implements advanced contour integration algorithm\n        presented by `Bozza 2010 MNRAS, 408, 2188\n        <https://ui.adsabs.harvard.edu/abs/2010MNRAS.408.2188B/abstract>`_.\n        See also `VBBL website by Valerio Bozza\n        <http://www.fisica.unisa.it/GravitationAstrophysics/VBBinaryLensing.htm>`_.\n\n        For coordinate system convention see\n        :py:func:`point_source_magnification()`\n\n        Parameters :\n            source_x: *float*\n                X-axis coordinate of the source.\n\n            source_y: *float*\n                Y-axis coordinate of the source.\n\n            rho: *float*\n                Source size relative to Einstein ring radius.\n\n            gamma: *float*, optional\n                Linear limb-darkening coefficient in gamma convention.\n\n            u_limb_darkening: *float*\n                Linear limb-darkening coefficient in u convention.\n                Note that either *gamma* or *u_limb_darkening* can be\n                set.  If neither of them is provided then limb\n                darkening is ignored.\n\n            accuracy: *float*, optional\n                Requested accuracy of the result.\n\n        Returns :\n            magnification: *float*\n                Magnification.\n\n        \"\"\"\n        self._rho_check(rho)\n        if accuracy <= 0.:\n            raise ValueError(\n                \"VBBL requires accuracy > 0 e.g. 0.01 or 0.001;\" +\n                \"\\n{:} was  provided\".format(accuracy))\n\n        if not _vbbl_wrapped:\n            raise ValueError('VBBL was not imported properly')\n\n        if gamma is not None and u_limb_darkening is not None:\n            raise ValueError('Only one limb darkening parameters can be set' +\n                             ' in BinaryLens.vbbl_magnification()')\n        elif gamma is not None:\n            u_limb_darkening = float(Utils.gamma_to_u(gamma))\n        elif u_limb_darkening is not None:\n            u_limb_darkening = float(u_limb_darkening)\n        else:\n            u_limb_darkening = float(0.0)\n\n        s = float(self.separation)\n        q = float(self.mass_2 / self.mass_1)\n        x = float(source_x)\n        y = float(source_y)\n        rho = float(rho)\n        accuracy = float(accuracy)\n\n        magnification = _vbbl_binary_mag_dark(\n            s, q, x, y, rho, u_limb_darkening, accuracy)\n\n        return magnification\n", "meta": {"hexsha": "7cd064c1143a74293e69b881dbd8b1405ee70b47", "size": 27863, "ext": "py", "lang": "Python", "max_stars_repo_path": "source/MulensModel/binarylens.py", "max_stars_repo_name": "pmehta08/MulensModel", "max_stars_repo_head_hexsha": "261738c445a8d116d09c90e65f6e847cfc8a7ad8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/MulensModel/binarylens.py", "max_issues_repo_name": "pmehta08/MulensModel", "max_issues_repo_head_hexsha": "261738c445a8d116d09c90e65f6e847cfc8a7ad8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/MulensModel/binarylens.py", "max_forks_repo_name": "pmehta08/MulensModel", "max_forks_repo_head_hexsha": "261738c445a8d116d09c90e65f6e847cfc8a7ad8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9148044693, "max_line_length": 83, "alphanum_fraction": 0.5928650899, "include": true, "reason": "import numpy", "num_tokens": 7045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19395960471703508}}
{"text": "\"\"\"\nGeneral utility functions for the pymodulon package\n\"\"\"\nimport json\nimport logging\nimport re\nfrom itertools import combinations\n\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats\nfrom scipy.special import digamma\nfrom sklearn.neighbors import BallTree, KDTree\n\nfrom pymodulon.enrichment import FDR\n\n\n################\n# Type Aliases #\n################\n\n\ndef _check_table(table, name, index=None, index_col=0):\n    # Set as empty dataframe if not input given\n    if table is None:\n        return pd.DataFrame(index=index)\n\n    # Load table if necessary\n    elif isinstance(table, str):\n        try:\n            table = pd.read_json(table)\n        except ValueError:\n            sep = \"\\t\" if table.endswith(\".tsv\") else \",\"\n            table = pd.read_csv(table, index_col=index_col, sep=sep)\n\n    # Coerce indices and columns to ints if necessary\n    newcols = []\n    for col in table.columns:\n        try:\n            newcols.append(int(col))\n        except ValueError:\n            newcols.append(col)\n    table.columns = newcols\n\n    newrows = []\n    for row in table.index:\n        try:\n            newrows.append(int(row))\n        except ValueError:\n            newrows.append(row)\n    table.index = newrows\n\n    # Replace empty strings with None\n    table = table.replace(\"\", np.nan)\n\n    if isinstance(table, pd.DataFrame):\n        # dont run _check_table_helper if no index is passed\n        return table if index is None else _check_table_helper(table, index, name)\n    else:\n        raise TypeError(\n            \"{}_table must be a pandas DataFrame \"\n            \"filename or a valid JSON string\".format(name)\n        )\n\n\ndef _check_table_helper(table, index, name):\n    if table.shape == (0, 0):\n        return pd.DataFrame(index=index)\n\n    # Check if all indices are in table\n    missing_index = list(set(index) - set(table.index))\n    if len(missing_index) > 0:\n        logging.warning(\n            \"Some {} are missing from the {} table: {}\".format(\n                name, name, missing_index\n            )\n        )\n\n    # Remove extra indices from table\n    table = table.reindex(index)\n    return table\n\n\ndef _check_dict(table, index_col=0):\n    try:\n        table = json.loads(table.replace(\"'\", '\"'))\n    except ValueError:\n        sep = \"\\t\" if table.endswith(\".tsv\") else \",\"\n        table = pd.read_csv(table, index_col=index_col, header=None, sep=sep)\n        table = table.to_dict()[1]\n    return table\n\n\ndef compute_threshold(ic, dagostino_cutoff):\n    \"\"\"\n    Computes D'agostino-test-based threshold for a component of an M matrix\n\n    Parameters\n    ----------\n    ic: ~pandas.Series\n        Pandas Series containing an independent component\n    dagostino_cutoff: int\n        Minimum D'agostino test statistic value to determine threshold\n\n    Returns\n    -------\n    iModulon threshold: list\n        List of thresholds for each iModulon\n    \"\"\"\n\n    i = 0\n\n    # Sort genes based on absolute value\n    ordered_genes = abs(ic).sort_values()\n\n    # Compute k2-statistic\n    k_square, p = stats.normaltest(ic)\n\n    # Iteratively remove gene w/ largest weight until k2-statistic < cutoff\n    while k_square > dagostino_cutoff:\n        i -= 1\n        k_square, p = stats.normaltest(ic.loc[ordered_genes.index[:i]])\n\n    # Select genes in iModulon\n    comp_genes = ordered_genes.iloc[i:]\n\n    # Slightly modify threshold to improve plotting visibility\n    if len(comp_genes) == len(ic.index):\n        return max(comp_genes) + 0.05\n    else:\n        return np.mean([ordered_genes.iloc[i], ordered_genes.iloc[i - 1]])\n\n\ndef dima(ica_data, sample1, sample2, threshold=5, fdr=0.1, alternate_A=None):\n    \"\"\"\n    Creates DIMA table of differentially expressed iModulons\n\n    Parameters\n    ----------\n    ica_data: ~pymodulon.core.IcaData\n        :class:`~pymodulon.core.IcaData` data object\n    sample1: str or list\n        List of sample IDs or name of \"project:condition\"\n    sample2: str or list\n        List of sample IDs or name of \"project:condition\"\n    threshold: float\n        Minimum activity difference to determine DiMAs (default = 5)\n    fdr: float\n        False Detection Rate (default = .1)\n    alternate_A: ~pandas.DataFrame\n        Alternate A to use (default = None)\n\n    Returns\n    -------\n    results: DataFrame\n        Table of differentially expressed iModulons\n\n    \"\"\"\n\n    # use the undocumented alternate_A option to allow custom-built DIMCA\n    # activity matrix to be used in lieu of standard activty matrix\n    if alternate_A is not None:\n        A_to_use = alternate_A\n    else:\n        A_to_use = ica_data.A\n\n    _diff = pd.DataFrame()\n\n    sample1_list = _parse_sample(ica_data, sample1)\n    sample2_list = _parse_sample(ica_data, sample2)\n\n    for name, group in ica_data.sample_table.groupby([\"project\", \"condition\"]):\n        for i1, i2 in combinations(group.index, 2):\n            _diff[\":\".join(name)] = abs(A_to_use[i1] - A_to_use[i2])\n    dist = {}\n\n    for k in A_to_use.index:\n        dist[k] = stats.lognorm(*stats.lognorm.fit(_diff.loc[k].values)).cdf\n\n    res = pd.DataFrame(index=A_to_use.index)\n    for k in res.index:\n        a1 = A_to_use.loc[k, sample1_list].mean()\n        a2 = A_to_use.loc[k, sample2_list].mean()\n        res.loc[k, \"difference\"] = a2 - a1\n        res.loc[k, \"pvalue\"] = 1 - dist[k](abs(a1 - a2))\n    result = FDR(res, fdr)\n    return result[(abs(result.difference) > threshold)].sort_values(\n        \"difference\", ascending=False\n    )\n\n\ndef _parse_sample(ica_data, sample):\n    \"\"\"\n    Parses sample inputs into a list of sample IDs\n\n    Parameters\n    ----------\n    ica_data: ~pymodulon.core.IcaData\n        :class:`~pymodulon.core.IcaData` data object\n    sample: list\n        Sequence of sample IDs or \"project:condition\"\n\n    Returns\n    -------\n    samples: list\n        A list of `samples`\n    \"\"\"\n\n    sample_table = ica_data.sample_table\n    if isinstance(sample, str):\n        proj, cond = re.search(\"(.*):(.*)\", sample).groups()\n        samples = sample_table[\n            (sample_table.project == proj) & (sample_table.condition == cond)\n        ].index\n        if len(samples) == 0:\n            raise ValueError(\n                f\"No samples exist for project={proj} condition=\" f\"{cond}\"\n            )\n        else:\n            return samples\n    else:\n        return sample\n\n\ndef explained_variance(\n    ica_data, genes=None, samples=None, imodulons=None, reference=None\n):\n    \"\"\"\n    Computes the fraction of variance explained by iModulons (from 0 to 1)\n\n    Parameters\n    ----------\n    ica_data: ~pymodulon.core.IcaData\n        :class:`~pymodulon.core.IcaData` data object\n    genes: str or list, optional\n        List of genes to use (default: all genes)\n    samples: str or list, optional\n        List of samples to use (default: all samples)\n    imodulons: int or str or list, optional\n        List of iModulons to use (default: all iModulons)\n    reference: list, optional\n        List of samples that represent the reference condition for the\n        set. If none are provided, uses the dataset-specific reference\n        condition.\n\n    Returns\n    -------\n    float\n        Fraction of variance explained by selected iModulons for selected\n        genes/samples\n    \"\"\"\n\n    # Check inputs\n    if genes is None:\n        genes = ica_data.X.index\n    elif isinstance(genes, str):\n        genes = [genes]\n\n    gene_loci = set(genes) & set(ica_data.X.index)\n    gene_names = set(genes) - set(ica_data.X.index)\n    name_loci = [ica_data.name2num(gene) for gene in gene_names]\n    genes = list(set(gene_loci) | set(name_loci))\n\n    if samples is None:\n        samples = ica_data.X.columns\n    elif isinstance(samples, str):\n        samples = [samples]\n\n    if imodulons is None:\n        imodulons = ica_data.M.columns\n    elif isinstance(imodulons, str) or isinstance(imodulons, int):\n        imodulons = [imodulons]\n\n    if reference is None:\n        centered = ica_data.X\n    else:\n        centered = ica_data.X.subtract(ica_data.X[reference].mean(axis=1), axis=0)\n\n    # Account for normalization procedures before ICA (X=SA-x_mean)\n    baseline = centered.subtract(centered.mean(axis=0), axis=1)\n    baseline = baseline.loc[genes, samples]\n\n    # Initialize variables\n    base_err = np.linalg.norm(baseline) ** 2\n    MA = np.zeros(baseline.shape)\n    rec_var = [0]\n    ma_arrs = {}\n    ma_weights = {}\n\n    # Get individual modulon contributions\n    for k in imodulons:\n        ma_arr = np.dot(\n            ica_data.M.loc[genes, k].values.reshape(len(genes), 1),\n            ica_data.A.loc[k, samples].values.reshape(1, len(samples)),\n        )\n        ma_arrs[k] = ma_arr\n        ma_weights[k] = np.sum(ma_arr ** 2)\n\n    # Sum components in order of most important component first\n    sorted_mods = sorted(ma_weights, key=ma_weights.get, reverse=True)\n    # Compute reconstructed variance\n    for k in sorted_mods:\n        MA = MA + ma_arrs[k]\n        sa_err = np.linalg.norm(MA - baseline) ** 2\n        rec_var.append((1 - sa_err / base_err))\n\n    return np.clip(rec_var[-1], 0, 1)\n\n\ndef infer_activities(ica_data, data):\n    \"\"\"\n    Infer iModulon activities for external data\n\n    Parameters\n    ----------\n    ica_data: ~pymodulon.core.IcaData\n        :class:`~pymodulon.core.IcaData` data object\n    data: ~pandas.DataFrame\n        External expression profiles (must be centered to a reference)\n\n    Returns\n    -------\n    new_activities: ~pandas.DataFrame\n        Inferred activities for the expression profiles\n    \"\"\"\n\n    shared_genes = ica_data.M.index & data.index\n    x = data.loc[shared_genes].values\n    m = ica_data.M.loc[shared_genes].values\n    m_inv = np.linalg.pinv(m)\n    a = np.dot(m_inv, x)\n    return pd.DataFrame(a, index=ica_data.imodulon_names, columns=data.columns)\n\n\ndef mutual_info_distance(x, y):\n    x = np.asarray(x).reshape(x.shape[0], 1)\n    y = np.asarray(y).reshape(x.shape[0], 1)\n    h = entropy(np.hstack([x, y]))\n    if h == 0:\n        return 1\n    else:\n        return 1 - mi(x, y) / h\n\n\n# the following code is taken from the NPEET package; it cannot be installed\n# via pip, so the necessary functions are copied here; the package appears to\n# be un-maintained, so updates are not very likely; this is the GitHub page:\n# https://github.com/gregversteeg/NPEET\n\n\ndef mi(x, y, z=None, k=3, base=2, alpha=0):\n    \"\"\"Mutual information of x and y (conditioned on z if z is not None)\n    x, y should be a list of vectors, e.g. x = [[1.3], [3.7], [5.1], [2.4]]\n    if x is a one-dimensional scalar and we have four samples\n    \"\"\"\n    assert len(x) == len(y), \"Arrays should have same length\"\n    assert k <= len(x) - 1, \"Set k smaller than num. samples - 1\"\n    x, y = np.asarray(x), np.asarray(y)\n    x, y = x.reshape(x.shape[0], -1), y.reshape(y.shape[0], -1)\n    x = add_noise(x)\n    y = add_noise(y)\n    points = [x, y]\n    if z is not None:\n        z = np.asarray(z)\n        z = z.reshape(z.shape[0], -1)\n        points.append(z)\n    points = np.hstack(points)\n    # Find nearest neighbors in joint space, p=inf means max-norm\n    tree = build_tree(points)\n    dvec = query_neighbors(tree, points, k)\n    if z is None:\n        a, b, c, d = (\n            avgdigamma(x, dvec),\n            avgdigamma(y, dvec),\n            digamma(k),\n            digamma(len(x)),\n        )\n        if alpha > 0:\n            d += lnc_correction(tree, points, k, alpha)\n    else:\n        xz = np.c_[x, z]\n        yz = np.c_[y, z]\n        a, b, c, d = (\n            avgdigamma(xz, dvec),\n            avgdigamma(yz, dvec),\n            avgdigamma(z, dvec),\n            digamma(k),\n        )\n    return max(0, (-a - b + c + d) / np.log(base))\n\n\ndef entropy(x, k=3, base=2):\n    \"\"\"The classic K-L k-nearest neighbor continuous entropy estimator\n    x should be a list of vectors, e.g. x = [[1.3], [3.7], [5.1], [2.4]]\n    if x is a one-dimensional scalar and we have four samples\n    \"\"\"\n    assert k <= len(x) - 1, \"Set k smaller than num. samples - 1\"\n    x = np.asarray(x)\n    n_elements, n_features = x.shape\n    x = add_noise(x)\n    tree = build_tree(x)\n    nn = query_neighbors(tree, x, k)\n    const = digamma(n_elements) - digamma(k) + n_features * np.log(2)\n    return max(0, (const + n_features * np.log(nn).mean()) / np.log(base))\n\n\ndef add_noise(x, intens=1e-10):\n    \"\"\"Small noise to break degeneracy, see doc.\"\"\"\n    return x + intens * np.random.random_sample(x.shape)\n\n\ndef build_tree(points):\n    if points.shape[1] >= 20:\n        return BallTree(points, metric=\"chebyshev\")\n    return KDTree(points, metric=\"chebyshev\")\n\n\ndef query_neighbors(tree, x, k):\n    return tree.query(x, k=k + 1)[0][:, k]\n\n\ndef avgdigamma(points, dvec):\n    \"\"\"This part finds number of neighbors in some radius in the marginal space\n    returns expectation value of <psi(nx)>\"\"\"\n    tree = build_tree(points)\n    dvec = dvec - 1e-15\n    num_points = count_neighbors(tree, points, dvec)\n    return np.mean(digamma(num_points))\n\n\ndef lnc_correction(tree, points, k, alpha):\n    e = 0\n    n_sample = points.shape[0]\n    for point in points:\n        # Find k-nearest neighbors in joint space, p=inf means max norm\n        knn = tree.query(point[None, :], k=k + 1, return_distance=False)[0]\n        knn_points = points[knn]\n        # Substract mean of k-nearest neighbor points\n        knn_points = knn_points - knn_points[0]\n        # Calculate covariance matrix of k-nearest neighbor points, obtain\n        # eigen vectors\n        covr = knn_points.T @ knn_points / k\n        _, v = np.linalg.eig(covr)\n        # Calculate PCA-bounding box using eigen vectors\n        V_rect = np.log(np.abs(knn_points @ v).max(axis=0)).sum()\n        # Calculate the volume of original box\n        log_knn_dist = np.log(np.abs(knn_points).max(axis=0)).sum()\n\n        # Perform local non-uniformity checking and update correction term\n        if V_rect < log_knn_dist + np.log(alpha):\n            e += (log_knn_dist - V_rect) / n_sample\n    return e\n\n\ndef count_neighbors(tree, x, r):\n    return tree.query_radius(x, r, count_only=True)\n", "meta": {"hexsha": "67ceee2f49a71c60418d405de83c87406ed525f3", "size": 13959, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/pymodulon/util.py", "max_stars_repo_name": "SBRG/pymodulon", "max_stars_repo_head_hexsha": "7de0d3f86203b3eeafbfa95f4184145c6edca03f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-06T15:52:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T09:42:04.000Z", "max_issues_repo_path": "src/pymodulon/util.py", "max_issues_repo_name": "SBRG/pymodulon", "max_issues_repo_head_hexsha": "7de0d3f86203b3eeafbfa95f4184145c6edca03f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2021-03-09T21:42:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T04:31:53.000Z", "max_forks_repo_path": "src/pymodulon/util.py", "max_forks_repo_name": "SBRG/pymodulon", "max_forks_repo_head_hexsha": "7de0d3f86203b3eeafbfa95f4184145c6edca03f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-10T14:50:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-14T20:57:35.000Z", "avg_line_length": 30.5448577681, "max_line_length": 82, "alphanum_fraction": 0.623683645, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19395960471703508}}
{"text": "from __future__ import division\nimport torch\n\n# Beam decoding with KL divergence\nimport numpy as np\nfrom scipy.stats import entropy\n\nclass Beam(object):\n    \"\"\"\n    Class for managing the internals of the beam search process.\n\n    Takes care of beams, back pointers, and scores.\n\n    Args:\n        size (int): beam size\n        pad, bos, eos (int): indices of padding, beginning, and ending.\n        vocab (vocab): vocab of the target\n        syntax_topics_model (Syntax and Topics module): This is an object of the class which will have the topics \n                                                        and classes word probabilities\n        source (list): list of source indices which will be the source sentence\n        targets (list of list): list of taget sentences each of which is a list of indices of the full hypothesis generated till now\n        n_best (int): nbest size to use\n        cuda (bool): use gpu\n        global_scorer (:obj:`GlobalScorer`)\n    \"\"\"\n    def __init__(self, size, pad, bos, eos,\n                 vocab, syntax_topics_model,\n                 source,\n                 n_best=1, cuda=False,\n                 global_scorer=None,\n                 min_length=0):\n\n        self.size = size\n        self.tt = torch.cuda if cuda else torch\n\n        # The score for each translation on the beam.\n        self.scores = self.tt.FloatTensor(size).zero_()\n        self.all_scores = []\n\n        # The backpointers at each time-step.\n        self.prev_ks = []\n\n        \n\n        # The outputs at each time-step.\n        self.next_ys = [self.tt.LongTensor(size)\n                        .fill_(pad)]\n        self.next_ys[0][0] = bos\n        ##NOTE: speical marker which tells which class is the previous word from\n        self.next_ys_topic_prior_sum = []        # Store the sum of the topic prior for the entire hypothesis\n        self.next_ys_class_prior_sum = []        # Store the sum of the class prior for the entire hypothesis\n        self.TOPIC_FLAG = 0\n        self.CLASS_FLAG = 1\n\n\n        # Has EOS topped the beam yet.\n        self._eos = eos\n        self.eos_top = False\n\n        # The attentions (matrix) for each time.\n        self.attn = []\n\n        # Time and k pair for finished.\n        self.finished = []\n        self.n_best = n_best\n\n        # Information for global scoring.\n        self.global_scorer = global_scorer\n        self.global_state = {}\n\n        # Minimum prediction length\n        self.min_length = min_length\n\n\n\n        ##NOTE: Custom code\n        self.vocab = vocab\n        self.finished_marker = [-1]*size\n        self.syntax_topics_model = syntax_topics_model\n        self.source = [self.vocab.itos[word_id] for word_id in source]\n        # Compute the topic prior probability for the source sentence\n        self.source_topic_prior = np.zeros(self.syntax_topics_model.num_topics+1, dtype=np.float)\n        print self.source\n        self.src_topic_word_count = 0\n        for word in self.source:\n            word_topic_prior = self.syntax_topics_model.get_topic_prior_for_word(word)\n            if word_topic_prior[self.syntax_topics_model.num_topics] != 1.0:\n                print word\n                self.src_topic_word_count += 1\n                self.source_topic_prior += word_topic_prior\n        self.source_class_prior = np.zeros(self.syntax_topics_model.num_classes, dtype=np.float)\n        for word in self.source:\n            self.source_class_prior += self.syntax_topics_model.get_class_prior_for_word(word)\n        \n        self.source_topic_prior /= len(self.source)\n        self.source_class_prior /= len(self.source)\n        self.beta = 0.0         # Additive smoothing\n        self.source_topic_prior += self.beta\n        self.source_class_prior += self.beta\n        print(self.source_topic_prior)\n        print(self.source_class_prior)\n        self.L = 50         # Number of words to be chosen for the similarity consideration\n        # temp = np.zeros_like(self.source_topic_prior) + self.beta\n        # least_KL = entropy(self.source_topic_prior, temp)\n        self.alpha = 1.5                # Multiplicative factor for topic KL divergence\n        self.gamma = 1.5                 # Multiplicative factor for class KL divergence\n        # self.alpha = 8/least_KL        # multiplicative factor for the KL divergence\n        # print vocab.itos[0]\n        # print vocab.itos[bos]\n        # print vocab.itos[self._eos]\n        # print vocab.__dict__.keys()\n        # print vocab.unk_init\n        # print type(vocab)\n        self.topic_KL_flag = False\n        self.class_KL_flag = True\n\n    def print_hyp(self, hyp, class_or_topic = None):\n        for i, word_id in enumerate(hyp):\n            if class_or_topic:\n                print \"{}_{} \".format(self.vocab.itos[word_id], class_or_topic[i]),\n            else:\n                print \"{} \".format(self.vocab.itos[word_id]),\n\n    ##NOTE: Custom function for debugging\n    def print_all_words_in_beam(self):\n        # Uses the vocab and prints the list of next_ys\n        for i in range(self.size):\n            timestep = len(self.next_ys)\n            # if self.finished_marker[i] != -1:\n            #     timestep = self.finished_marker[i]\n            if timestep > 1:\n                hyp, _ = self.get_hyp(timestep, i)\n                # print hyp\n                # print type(hyp)\n                self.print_hyp(hyp)\n                print \"$$$\"\n            # print \"\"\n\n    def print_received_targets(self):\n        for i in range(len(self.targets)):\n            self.print_hyp(self.targets[i])\n            print \"\"\n        print \"############### Received Targets ############\"\n\n    def print_the_top_choices(self, best_choices):\n        w, h = best_choices.size()\n        for i in range(w):\n            for j in range(h):\n                print \"{} \".format(self.vocab.itos[best_choices[i,j]]),\n            print \"\"\n\n\n    def get_current_state(self):\n        \"Get the outputs for the current timestep.\"\n        return self.next_ys[-1]\n\n    def get_current_origin(self):\n        \"Get the backpointers for the current timestep.\"\n        return self.prev_ks[-1]\n\n    def advance(self, word_probs, attn_out):\n        print \"Advancing beam\"\n        \"\"\"\n        Given prob over words for every last beam `wordLk` and attention\n        `attn_out`: Compute and update the beam search.\n\n        Parameters:\n\n        * `word_probs`- probs of advancing from the last step (K x words)\n        * `attn_out`- attention at the last step\n\n        Returns: True if beam search is complete.\n        \"\"\"\n        num_words = word_probs.size(1)\n\n        # force the output to be longer than self.min_length\n        cur_len = len(self.next_ys)\n        if cur_len < self.min_length:\n            for k in range(len(word_probs)):\n                word_probs[k][self._eos] = -1e20\n\n        # Sum the previous scores.\n        if len(self.prev_ks) > 0:\n            beam_scores = word_probs + \\\n                self.scores.unsqueeze(1).expand_as(word_probs)\n\n            # Don't let EOS have children.\n            for i in range(self.next_ys[-1].size(0)):\n                if self.next_ys[-1][i] == self._eos:\n                    beam_scores[i] = -1e20\n        else:\n            beam_scores = word_probs[0]\n\n        #TODO: 1) find the last word for each beam\n        #       2) For each possible hypothesis find the Topic modeling probability\n        #       3) Weighted add the syntax and topic scores to beam_scores and just calculate the next_ys and backpointers as normal\n        \n        if len(self.prev_ks) > 0:\n            per_beam_words = self.next_ys[-1]\n            if self.topic_KL_flag:\n                per_beam_hyp_topic_prior_sum = self.next_ys_topic_prior_sum[-1]\n            if self.class_KL_flag:\n                per_beam_hyp_class_prior_sum = self.next_ys_class_prior_sum[-1]\n\n            if self.topic_KL_flag:\n                topic_KL_divergence_scores = self.tt.zeros_like(beam_scores)\n            if self.class_KL_flag:\n                class_KL_divergence_scores = self.tt.zeros_like(beam_scores)\n            for i in range(self.size):\n                if self.topic_KL_flag:\n                    hyp_topic_prior = per_beam_hyp_topic_prior_sum[i]\n                if self.class_KL_flag:\n                    hyp_class_prior = per_beam_hyp_class_prior_sum[i]\n\n                len_hyp = len(self.next_ys)             # Includes current word because we want to skip the count added by the start word <bos>\n                for j in range(num_words):\n                    word = self.vocab.itos[j]\n                    #KL divergence for Topic Priors\n                    if self.topic_KL_flag:\n                        word_topic_prior = self.syntax_topics_model.get_topic_prior_for_word(word)\n                        hyp_topic_prior_sum = (hyp_topic_prior + word_topic_prior) + self.beta\n                        # topic_KL_divergence_scores[i][j] = entropy(self.source_topic_prior, hyp_topic_prior_sum)\n                        topic_KL_divergence_scores[i][j] = self.syntax_topics_model.KL_divergence(self.source_topic_prior, hyp_topic_prior_sum)\n                        if topic_KL_divergence_scores[i][j] == float('Inf'):\n                            print word\n                            print topic_KL_divergence_scores[i][j]\n                            print self.source_topic_prior\n                            print hyp_topic_prior_sum\n                    #KL divergence for Class Priors\n                    if self.class_KL_flag:\n                        if \"<unk>\" in word:\n                            class_KL_divergence_scores[i][j] = 1000000.0\n                            continue\n                        word_class_prior = self.syntax_topics_model.get_class_prior_for_word(word)\n                        hyp_class_prior_sum = (hyp_class_prior + word_class_prior) + self.beta\n                        # class_KL_divergence_scores[i][j] = entropy(self.source_class_prior, hyp_class_prior_sum)\n                        class_KL_divergence_scores[i][j] = self.syntax_topics_model.KL_divergence(self.source_class_prior, hyp_class_prior_sum)\n                        if class_KL_divergence_scores[i][j] == float('Inf'):\n                            print word\n                            print class_KL_divergence_scores[i][j]\n                            print self.source_class_prior\n                            print hyp_class_prior_sum\n\n            #TODO: Convert the zeros to max KL divergence\n            if self.topic_KL_flag:\n                max_topic_KL = topic_KL_divergence_scores.mean()\n                for i in range(self.size):\n                    for j in range(num_words):\n                        word = self.vocab.itos[j]\n                        if \"<unk>\" in word:\n                            topic_KL_divergence_scores[i][j] = 1000000.0\n                            continue\n                        if topic_KL_divergence_scores[i][j] == 0.0:\n                            topic_KL_divergence_scores[i][j] = max_topic_KL\n                print \"########\\n\", max_topic_KL, \"\\n#########\"\n                    # Manually discourage unk by setting large negative syntax_topic_probability\n                    # if \"<unk>\" in word:\n                    #     syntax_topic_score, best_class_or_topic, class_or_topic = -1000000.0, -1, \"C\"\n                    # else:\n                    #     syntax_topic_score, best_class_or_topic, class_or_topic = self.syntax_topics_model.get_log_prob(word, 0 if per_beam_words_class_or_topic[i] == self.TOPIC_FLAG else per_beam_words_class_or_topic_number[i])\n            overall_scores = beam_scores - ((self.alpha * topic_KL_divergence_scores) if self.topic_KL_flag else 0.0) - ((self.gamma * class_KL_divergence_scores) if self.class_KL_flag else 0.0)\n            # print \"Overall Score\"\n            # print overall_scores\n            # print overall_scores.size()\n        \n\n            size = int(overall_scores.size(1))\n            # print \"Size of the overall_scores = \", size\n            flat_beam_scores = overall_scores.view(-1)\n            best_scores, best_scores_id = flat_beam_scores.topk(self.size, 0,\n                                                                True, True)\n\n            # We will debug the individual scores of the best candidates\n            word_prob_best_scores = self.tt.zeros_like(best_scores)\n            for i in range(self.size):\n                word_prob_best_scores[i] = beam_scores[int(best_scores_id[i] / size)][best_scores_id[i] - int(best_scores_id[i] / size) * size]\n            if self.topic_KL_flag:\n                topic_KL_divergence_best_scores = self.tt.zeros_like(best_scores)\n                for i in range(self.size):\n                    topic_KL_divergence_best_scores[i] = topic_KL_divergence_scores[int(best_scores_id[i] / size)][best_scores_id[i] - int(best_scores_id[i] / size) * size]\n            if self.class_KL_flag:\n                class_KL_divergence_best_scores = self.tt.zeros_like(best_scores)\n                for i in range(self.size):\n                    class_KL_divergence_best_scores[i] = class_KL_divergence_scores[int(best_scores_id[i] / size)][best_scores_id[i] - int(best_scores_id[i] / size) * size]\n            print best_scores\n            print word_prob_best_scores\n            # print topic_KL_divergence_best_scores\n            # print class_KL_divergence_best_scores\n            if self.topic_KL_flag:\n                print self.alpha\n                print self.alpha * topic_KL_divergence_best_scores\n            if self.class_KL_flag:\n                print self.gamma\n                print self.gamma * class_KL_divergence_best_scores\n\n            if self.topic_KL_flag:\n                KL_size = int(topic_KL_divergence_scores.size(1))\n                # print \"Size of the overall_scores = \", size\n                flat_beam_scores = topic_KL_divergence_scores.view(-1)\n                debug_size = 25\n                best_topic_KL_scores, best_topic_KL_scores_id = flat_beam_scores.topk(debug_size, 0,\n                                                                False, True)\n                print \"Best words from topic KL\"\n                for i in range(debug_size):\n                    # print best_topic_KL_scores_id[i], best_topic_KL_scores_id[i] - int(best_topic_KL_scores_id[i] / KL_size) * KL_size\n                    word = self.vocab.itos[best_topic_KL_scores_id[i] - int(best_topic_KL_scores_id[i] / KL_size) * KL_size]\n                    word_topic_prior = self.syntax_topics_model.get_topic_prior_for_word(word)\n                    # print word, word_topic_prior, entropy(self.source_topic_prior, word_topic_prior + self.beta), \\\n                    print word, \\\n                                overall_scores[int(best_topic_KL_scores_id[i] / KL_size)][best_topic_KL_scores_id[i] - int(best_topic_KL_scores_id[i] / KL_size) * KL_size], \\\n                                best_topic_KL_scores[i], \\\n                                topic_KL_divergence_scores[int(best_topic_KL_scores_id[i] / KL_size)][best_topic_KL_scores_id[i] - int(best_topic_KL_scores_id[i] / KL_size) * KL_size]\n                                # class_KL_divergence_scores[int(best_topic_KL_scores_id[i] / KL_size)][best_topic_KL_scores_id[i] - int(best_topic_KL_scores_id[i] / KL_size) * KL_size], \\\n                # print word_prob_best_scores + self.alpha * syntax_topic_best_scores\n\n            prev_k = best_scores_id / num_words\n            # Update next_ys_topic_prior_sum for all beams\n            if self.topic_KL_flag:\n                best_hyp_topic_prior_sum = list()\n                for i in range(self.size):\n                    word = self.vocab.itos[best_scores_id[i] - int(best_scores_id[i] / size) * size]\n                    word_topic_prior = self.syntax_topics_model.get_topic_prior_for_word(word)\n                    if word_topic_prior[self.syntax_topics_model.num_topics] != 1.0:\n                        best_hyp_topic_prior_sum.append(self.next_ys_topic_prior_sum[-1][int(best_scores_id[i] / size)] + word_topic_prior)\n                    else:\n                        # Add the word_topic_prior only if its a topic word\n                        best_hyp_topic_prior_sum.append(self.next_ys_topic_prior_sum[-1][int(best_scores_id[i] / size)])\n                self.next_ys_topic_prior_sum.append(best_hyp_topic_prior_sum)\n            # Update next_ys_class_prior_sum for all beams\n            if self.class_KL_flag:\n                best_hyp_class_prior_sum = list()\n                for i in range(self.size):\n                    word = self.vocab.itos[best_scores_id[i] - int(best_scores_id[i] / size) * size]\n                    word_class_prior = self.syntax_topics_model.get_class_prior_for_word(word)\n                    best_hyp_class_prior_sum.append(self.next_ys_class_prior_sum[-1][int(best_scores_id[i] / size)] + word_class_prior)\n                self.next_ys_class_prior_sum.append(best_hyp_class_prior_sum)\n            self.prev_ks.append(prev_k)\n            self.next_ys.append((best_scores_id - prev_k * num_words))\n            self.attn.append(attn_out.index_select(0, prev_k))\n            # exit()\n\n            self.print_all_words_in_beam()\n            print \"############## After new words chosen ###########\"\n        else:\n            # beam_scores is only V dimensional vector\n            # Thus for every word add the KL divergence score to the beam score\n            if self.topic_KL_flag:\n                topic_KL_divergence_scores = self.tt.zeros_like(beam_scores)\n            if self.class_KL_flag:\n                class_KL_divergence_scores = self.tt.zeros_like(beam_scores)\n            for i in range(num_words):\n                word = self.vocab.itos[i]\n                if \"<unk>\" in word:\n                    if self.topic_KL_flag:\n                        topic_KL_divergence_scores[i] = 1000000.0\n                    if self.class_KL_flag:\n                        class_KL_divergence_scores[i] = 1000000.0\n                    beam_scores[i] = -1000000.0\n                    continue\n                # KL for Topic priors of the first word\n                if self.topic_KL_flag:\n                    word_topic_prior = self.syntax_topics_model.get_topic_prior_for_word(word)\n                    word_topic_prior += self.beta\n                    # topic_KL_divergence_scores[i] = entropy(self.source_topic_prior, word_topic_prior)\n                    topic_KL_divergence_scores[i] = self.syntax_topics_model.KL_divergence(self.source_topic_prior, word_topic_prior)\n                # KL for Class priors of the first word\n                if self.class_KL_flag:\n                    word_class_prior = self.syntax_topics_model.get_class_prior_for_word(word)\n                    word_class_prior += self.beta\n                    # class_KL_divergence_scores[i] = entropy(self.source_class_prior, word_class_prior)\n                    class_KL_divergence_scores[i] = self.syntax_topics_model.KL_divergence(self.source_class_prior, word_class_prior)\n                    \n            overall_scores = beam_scores - ((self.alpha * topic_KL_divergence_scores) if self.topic_KL_flag else 0.0) -  ((self.gamma * class_KL_divergence_scores) if self.class_KL_flag else 0.0)\n            # flat_beam_scores = overall_scores.view(-1)\n            flat_beam_scores = beam_scores.view(-1)             # For the first iteration use only the word probabilities\n            best_scores, best_scores_id = flat_beam_scores.topk(self.size, 0,\n                                                                True, True)\n\n            self.all_scores.append(self.scores)\n            # self.scores = best_scores           # will store the word_prob + the KL divergence for hypothesis\n            self.scores = best_scores           # will store the word_prob log prob for hypothesis\n\n            # best_scores_id is flattened, beam * word array, so calculate which\n            # word and beam each score came from\n            size = int(overall_scores.size(0))\n            prev_k = best_scores_id / num_words\n            # Update next_ys_topic_prior_sum for all beams\n            if self.topic_KL_flag:\n                best_hyp_topic_prior_sum = list()\n                for i in range(self.size):\n                    word = self.vocab.itos[best_scores_id[i]]\n                    word_topic_prior = self.syntax_topics_model.get_topic_prior_for_word(word)\n                    if word_topic_prior[self.syntax_topics_model.num_topics] != 1.0:\n                        best_hyp_topic_prior_sum.append(word_topic_prior)\n                    else:\n                        # starting word is a syntax word. Therefore we will set the prior to zeros\n                        best_hyp_topic_prior_sum.append(np.zeros((self.syntax_topics_model.num_topics+1), dtype=np.float))\n                self.next_ys_topic_prior_sum.append(best_hyp_topic_prior_sum)\n\n            # Update next_ys_class_prior_sum for all beams\n            if self.class_KL_flag:\n                best_hyp_class_prior_sum = list()\n                for i in range(self.size):\n                    word = self.vocab.itos[best_scores_id[i]]\n                    word_class_prior = self.syntax_topics_model.get_class_prior_for_word(word)\n                    best_hyp_class_prior_sum.append(word_class_prior)\n                self.next_ys_class_prior_sum.append(best_hyp_class_prior_sum)\n\n            self.prev_ks.append(prev_k)\n            self.next_ys.append((best_scores_id - prev_k * num_words))\n            self.attn.append(attn_out.index_select(0, prev_k))\n\n        if self.global_scorer is not None:\n            self.global_scorer.update_global_state(self)\n\n        for i in range(self.next_ys[-1].size(0)):\n            if self.next_ys[-1][i] == self._eos:\n                s = self.scores[i]\n                timestep = len(self.next_ys)\n                if self.global_scorer is not None:\n                    global_scores = self.global_scorer.score(self, self.scores)\n                    s = global_scores[i]\n                self.finished.append((s, len(self.next_ys) - 1, i))\n                # TODO: Experimental!! Dividing the finished scores by their lenghts to be fair\n                # self.finished.append((s/float(len(self.next_ys) - 1), len(self.next_ys) - 1, i))\n\n\n                ##NOTE: Custom code\n                if self.finished_marker[i] == -1:\n                    # print \"SET AND FORGET FOR \", i, \"#$#$#$#$##$\"\n                    self.finished_marker[i] = len(self.next_ys) - 1\n\n\n\n        # End condition is when top-of-beam is EOS and no global score.\n        if self.next_ys[-1][0] == self._eos:\n            # self.all_scores.append(self.scores)\n            self.eos_top = True\n\n\n\n        ##NOTE: Debugging\n        # print word_probs, \"$$\"\n        # print self.get_current_state(), \"$$\"        \n        # self.print_all_words_in_beam()\n        # print \"############## Beam Advance ###########\"\n\n    def done(self):\n        return self.eos_top and len(self.finished) >= self.n_best\n\n    def sort_finished(self, minimum=None):\n        if minimum is not None:\n            i = 0\n            # Add from beam until we have minimum outputs.\n            while len(self.finished) < minimum:\n                s = self.scores[i]\n                if self.global_scorer is not None:\n                    global_scores = self.global_scorer.score(self, self.scores)\n                    s = global_scores[i]\n                self.finished.append((s, len(self.next_ys) - 1, i))\n\n        # print self.finished\n        # exit()\n\n        self.finished.sort(key=lambda a: -a[0])\n        scores = [sc for sc, _, _ in self.finished]\n        ks = [(t, k) for _, t, k in self.finished]\n        return scores, ks\n\n    def get_hyp_with_class(self, timestep, k):\n        \"\"\"\n        Walk back to construct the full hypothesis while also storing the class/topic number\n        \"\"\"\n        hyp, class_or_topic = [], []\n        # print len(self.next_ys), len(self.next_class_or_topics), len(self.next_class_or_topic_numbers)\n        for j in range(len(self.prev_ks[:timestep]) - 1, -1, -1):\n            hyp.append(self.next_ys[j+1][k])\n            class_or_topic.append(\"{}{}\".format(\"C\" if self.next_class_or_topics[j][k] == 1 else \"T\", self.next_class_or_topic_numbers[j][k]))\n            k = self.prev_ks[j][k]\n        class_or_topic.reverse()\n        return hyp[::-1], class_or_topic\n\n    def get_hyp(self, timestep, k):\n        \"\"\"\n        Walk back to construct the full hypothesis.\n        \"\"\"\n        hyp, attn = [], []\n        for j in range(len(self.prev_ks[:timestep]) - 1, -1, -1):\n            hyp.append(self.next_ys[j+1][k])\n            attn.append(self.attn[j][k])\n            k = self.prev_ks[j][k]\n        return hyp[::-1], torch.stack(attn[::-1])\n\n\nclass GNMTGlobalScorer(object):\n    \"\"\"\n    NMT re-ranking score from\n    \"Google's Neural Machine Translation System\" :cite:`wu2016google`\n\n    Args:\n       alpha (float): length parameter\n       beta (float):  coverage parameter\n    \"\"\"\n    def __init__(self, alpha, beta):\n        self.alpha = alpha\n        self.beta = beta\n\n    def score(self, beam, logprobs):\n        \"Additional term add to log probability\"\n        cov = beam.global_state[\"coverage\"]\n        pen = self.beta * torch.min(cov, cov.clone().fill_(1.0)).log().sum(1)\n        l_term = (((5 + len(beam.next_ys)) ** self.alpha) /\n                  ((5 + 1) ** self.alpha))\n        return (logprobs / l_term) + pen\n\n    def update_global_state(self, beam):\n        \"Keeps the coverage vector as sum of attens\"\n        if len(beam.prev_ks) == 1:\n            beam.global_state[\"coverage\"] = beam.attn[-1]\n        else:\n            beam.global_state[\"coverage\"] = beam.global_state[\"coverage\"] \\\n                .index_select(0, beam.prev_ks[-1]).add(beam.attn[-1])\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "6b70cdd932e52e1e4edc4d014918e06322f43a09", "size": 25717, "ext": "py", "lang": "Python", "max_stars_repo_path": "onmt/translate/Beam_KL_divergence.py", "max_stars_repo_name": "abaheti95/DC-NeuralConversation", "max_stars_repo_head_hexsha": "14f3c03adfb7379b48a325c0b3416eee39af7fdb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2018-09-06T07:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:55:42.000Z", "max_issues_repo_path": "onmt/translate/Beam_KL_divergence.py", "max_issues_repo_name": "abaheti95/DC-NeuralConversation", "max_issues_repo_head_hexsha": "14f3c03adfb7379b48a325c0b3416eee39af7fdb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-10-12T13:33:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-07T14:25:48.000Z", "max_forks_repo_path": "onmt/translate/Beam_KL_divergence.py", "max_forks_repo_name": "abaheti95/DC-NeuralConversation", "max_forks_repo_head_hexsha": "14f3c03adfb7379b48a325c0b3416eee39af7fdb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-09-24T19:56:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T06:10:38.000Z", "avg_line_length": 46.0053667263, "max_line_length": 230, "alphanum_fraction": 0.5871602442, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19395960471703508}}
{"text": "\"\"\"\nJoseph Cook, Aarhus University, Jan 2022\n\nThis script contains functions that a) generate \nSNICAR-predicted spectral albedo that approximate\nfield-measured spectra for a variety of weathering \ncrust configurations; b) quantify the albedo change\nresulting from a range of WC development scenarios \n\n\nincludes:\n\nfind_best_params()\n    the forward modelling script that retrieves the snicar params that generate the\n    best-matching curve to a given field spectrum\n\ncall_snicar()\n    the function used to do multiple snicar runs with params provided as a named tuple\n\nmatch_field_spectra()\n    the function for plotting simulated and measured field spectra in a multipanel fig\n\nisolate_biological_effect()\n    the function for calculating the albedo reduction due to bio vs phys processes by spectral differencing\n\nbuild_LUT()\n    function for constructing lookup table to be used in the inverse model\n\ninverse_model()\n    function finds the best matching entry in the LUTs for each field spectrum and returns the params\n    used to generate it\n\n\n\"\"\"\nimport collections as c\nimport sys\n\nsys.path.append(\"./src\")\nimport dask\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport statsmodels.api as sm\nimport xarray as xr\nfrom call_snicar import call_snicar\n\n\ndef match_field_spectra(\n    FIELD_DATA_FNAME,\n    fnames,\n    rho,\n    rds,\n    dz,\n    alg,\n    measured_cells,\n    CIsites,\n    LAsites,\n    HAsites,\n    APPLY_ARF,\n    PLOT_ARF,\n    ARF_CI,\n    ARF_HA,\n    SAVEPATH,\n):\n\n    \"\"\"\n    plot field against SNICAR spectra\n    requires parameters to be known in advance and hard coded inside this function\n    the relevant params can be generated using the find_best_params() func\n\n    params:\n    FIELD_DATA_FNAME = filename for spectral database\n\n    The following params are parallel arrays - the order matters and\n    must match the filenames! Pairs of values represent values for\n    upper and lower layers in model. These are the values used to\n    generate snicar spectrum to match field spectrum with name = fname[i]\n\n    fnames = sample IDs for spectra to match model runs\n    rho = pairs of density values [upper, lower]\n    rds = pairs of r_eff values [upper, lower]\n    dz = layer thickness [upper, lower] NB. upper is always 0.001\n    alg = mass concentration of algae [upper, lower] NB. lower is always 0\n    measured_cells = array of the actual measured cell concentration for each spectrum\n\n    e.g.\n    fnames= ['2016_WI_8','14_7_SB6','14_7_SB9','14_7_SB1','21_7_SB2','14_7_SB2', '22_7_SB3', 'RAIN']\n    rho = [[550,550],[650,650],[800,800],[850,850],[750,750],[800,800],[800,800],[900,900]]\n    rds = [[550,550],[650,650],[850,850],[850,850],[800,800],[800,800],[750,750],[900,900]]\n    dz = [[0.001,0.3],[0.001,0.09],[0.001,0.03],[0.001,0.03],[0.001,0.02],[0.001,0.06],[0.001,0.05],[0.001,0.03]]\n    alg = [[0,0],[0,0],[20000,0],[30000,0],[45000,0],[3000,0],[8000,0],[0,0]]\n\n    returns:\n    None, but saves figure to SAVEPATH\n\n    \"\"\"\n\n    spectra = pd.read_csv(FIELD_DATA_FNAME)\n\n    # reformat feld spectra to match snicar resolution\n    spectra = spectra[::10]\n\n    # gather spectra for each surface type\n    CIspec = spectra[spectra.columns.intersection(CIsites)]\n    HAspec = spectra[spectra.columns.intersection(HAsites)]\n    LAspec = spectra[spectra.columns.intersection(LAsites)]\n    RAINspec = spectra[\"RAIN2\"]\n\n    if PLOT_ARF:\n        plt.plot(\n            spectra.Wavelength[0:100], ARF_CI[0:100], marker=\"x\", label=\"clean ice ARF\"\n        ),\n        plt.plot(\n            spectra.Wavelength[0:100],\n            ARF_HA[0:100],\n            marker=\"o\",\n            linestyle=\"dashed\",\n            label=\"algal ice ARF\",\n        )\n        plt.ylabel(\"Anitostropic Reflectance Factor\"), plt.xlabel(\"Wavelength (nm)\")\n        plt.legend(loc=\"best\")\n        plt.savefig(str(SAVEPATH + \"ARF.jpg\"), dpi=300)\n\n    # define local function for calling snicar\n    def simulate_albedo(rds, rho, dz, alg):\n\n        params = c.namedtuple(\n            \"params\",\n            \"rho_layers, grain_rds, layer_type, dz,\\\n                 mss_cnc_glacier_algae, c_factor_GA, solzen\",\n        )\n        params.grain_rds = rds\n        params.rho_layers = rho\n        params.layer_type = [1, 1]\n        params.dz = dz\n        params.mss_cnc_glacier_algae = alg\n        params.c_factor_GA = 20\n        params.solzen = 40\n        albedo, BBA = call_snicar(params)\n\n        return albedo, BBA\n\n    # set up output array\n    # and call snicar with each set of params\n    OutArray = np.zeros(shape=(len(fnames), 480))\n\n    for i in np.arange(0, len(fnames), 1):\n\n        albedo, BBA = simulate_albedo(rds[i], rho[i], dz[i], alg[i])\n        if APPLY_ARF:\n            if alg[i][0] > 5000:\n                albedo[15:230] = albedo[15:230] * ARF_HA\n            else:\n                albedo[15:230] = albedo[15:230] * ARF_CI\n\n        OutArray[i, :] = albedo\n\n    # calculate mean absolute error for model vs measured spectrum\n    error = []\n    for i in np.arange(0, len(fnames), 1):\n        error.append(\n            abs(np.mean(spectra[fnames[i]].iloc[0:130] - (OutArray[i, 15:145])))\n        )\n\n    # plot figure\n    fig, axes = plt.subplots(4, 2, figsize=(10, 10))\n\n    if APPLY_ARF:\n        ylabel = \"Reflectance\"\n        PlotName = \"FieldvsMeasuredReflectance.jpg\"\n    else:\n        ylabel = \"Albedo\"\n        PlotName = \"FieldvsMeasuredAlbedo.jpg\"\n\n    axes[0, 0].plot(spectra.Wavelength, spectra[\"23_7_SB1\"], label=\"field\")\n    axes[0, 0].plot(\n        spectra.Wavelength, OutArray[0, 15:230], label=\"model\", linestyle=\"--\"\n    )\n    axes[0, 0].set_ylim(0, 1), axes[0, 0].set_xlim(350, 1800)\n    axes[0, 0].text(\n        1400,\n        0.2,\n        \"r_eff: {}\\nrho: {}\\ndz: {}\\nC-factor: 30\\nerror: {:.3f}\".format(\n            rds[0][0], rho[0][0], dz[0][1], error[0]\n        ),\n    )\n    axes[0, 0].text(400, 0.1, \"{} \\n{} cells/mL \".format(fnames[0], measured_cells[0]))\n    axes[0, 0].set_ylabel(ylabel), axes[0, 0].set_xlabel(\"Wavelength (nm)\")\n    axes[0, 0].legend(loc=\"best\")\n\n    axes[0, 1].plot(spectra.Wavelength, spectra[\"14_7_SB6\"])\n    axes[0, 1].plot(spectra.Wavelength, OutArray[1, 15:230], linestyle=\"--\")\n    axes[0, 1].set_ylim(0, 1), axes[0, 1].set_xlim(350, 1800)\n    axes[0, 1].text(\n        1450,\n        0.3,\n        \"r_eff: {}\\nrho: {}\\ndz: {}\\nC-factor: 30\\nerror: {:.3f}\".format(\n            rds[1][0], rho[1][0], dz[1][1], error[1]\n        ),\n    )\n    axes[0, 1].text(400, 0.8, \"{}: \\n{} cells/mL\".format(fnames[1], measured_cells[1]))\n    axes[0, 1].set_ylabel(ylabel), axes[0, 1].set_xlabel(\"Wavelength (nm)\")\n\n    axes[1, 0].plot(spectra.Wavelength, spectra[\"14_7_SB9\"])\n    axes[1, 0].plot(spectra.Wavelength, OutArray[2, 15:230], linestyle=\"--\")\n    axes[1, 0].set_ylim(0, 1), axes[1, 0].set_xlim(350, 1800)\n    axes[1, 0].text(\n        1400,\n        0.3,\n        \"r_eff: {}\\nrho: {}\\ndz: {}\\nC-factor: 30\\nerror: {:.3f}\".format(\n            rds[2][0], rho[2][0], dz[2][1], error[2]\n        ),\n    )\n    axes[1, 0].text(400, 0.8, \"{}: \\n{} cells/mL\".format(fnames[2], measured_cells[2]))\n    axes[1, 0].set_ylabel(ylabel), axes[1, 0].set_xlabel(\"Wavelength (nm)\")\n\n    axes[1, 1].plot(spectra.Wavelength, spectra[\"14_7_SB1\"])\n    axes[1, 1].plot(spectra.Wavelength, OutArray[3, 15:230], linestyle=\"--\")\n    axes[1, 1].set_ylim(0, 1), axes[1, 1].set_xlim(350, 1800)\n    axes[1, 1].text(\n        1400,\n        0.3,\n        \"r_eff: {}\\nrho: {}\\ndz: {}\\nC-factor: 30\\nerror: {:.3f}\".format(\n            rds[3][0], rho[3][0], dz[3][1], error[3]\n        ),\n    )\n    axes[1, 1].text(400, 0.8, \"{}: \\n{} cells/mL\".format(fnames[3], measured_cells[3]))\n    axes[1, 1].set_ylabel(ylabel), axes[1, 1].set_xlabel(\"Wavelength (nm)\")\n\n    axes[2, 0].plot(spectra.Wavelength, spectra[\"22_7_SB5\"])\n    axes[2, 0].plot(spectra.Wavelength, OutArray[4, 15:230], linestyle=\"--\")\n    axes[2, 0].set_ylim(0, 1), axes[2, 0].set_xlim(350, 1800)\n    axes[2, 0].text(\n        1400,\n        0.3,\n        \"r_eff: {}\\nrho: {}\\ndz: {}\\nC-factor: 30\\nerror: {:.3f}\".format(\n            rds[4][0], rho[4][0], dz[4][1], error[4]\n        ),\n    )\n    axes[2, 0].text(400, 0.8, \"{}: \\n{} cells/mL\".format(fnames[4], measured_cells[4]))\n    axes[2, 0].set_ylabel(ylabel), axes[2, 0].set_xlabel(\"Wavelength (nm)\")\n\n    axes[2, 1].plot(spectra.Wavelength, spectra[\"14_7_SB2\"])\n    axes[2, 1].plot(spectra.Wavelength, OutArray[5, 15:230], linestyle=\"--\")\n    axes[2, 1].set_ylim(0, 1), axes[2, 1].set_xlim(350, 1800)\n    axes[2, 1].text(\n        1400,\n        0.3,\n        \"r_eff: {}\\nrho: {}\\ndz: {}\\nC-factor: 30\\nerror: {:.3f}\".format(\n            rds[5][0], rho[5][0], dz[5][1], error[5]\n        ),\n    )\n    axes[2, 1].text(400, 0.8, \"{}: \\n{} cells/mL\".format(fnames[5], measured_cells[5]))\n    axes[2, 1].set_ylabel(ylabel), axes[2, 1].set_xlabel(\"Wavelength (nm)\")\n\n    axes[3, 0].plot(spectra.Wavelength, spectra[\"22_7_SB3\"])\n    axes[3, 0].plot(spectra.Wavelength, OutArray[6, 15:230], linestyle=\"--\")\n    axes[3, 0].set_ylim(0, 1), axes[3, 0].set_xlim(350, 1800)\n    axes[3, 0].text(\n        1400,\n        0.3,\n        \"r_eff: {}\\nrho: {}\\ndz: {}\\nC-factor: 30\\nerror: {:.3f}\".format(\n            rds[6][0], rho[6][0], dz[6][1], error[6]\n        ),\n    )\n    axes[3, 0].text(400, 0.8, \"{}: \\n{} cells/mL\".format(fnames[6], measured_cells[6]))\n    axes[3, 0].set_ylabel(ylabel), axes[3, 0].set_xlabel(\"Wavelength (nm)\")\n\n    axes[3, 1].plot(spectra.Wavelength, RAINspec)\n    axes[3, 1].plot(spectra.Wavelength, OutArray[7, 15:230], linestyle=\"--\")\n    axes[3, 1].set_ylim(0, 1), axes[3, 1].set_xlim(350, 1800)\n    axes[3, 1].text(\n        1400,\n        0.3,\n        \"r_eff: {}\\nrho: {}\\ndz: {}\\nC-factor: 30\\nerror: {:.3f}\".format(\n            rds[7][0], rho[7][0], dz[7][1], error[7]\n        ),\n    )\n    axes[3, 1].text(400, 0.8, \"{}: \\n{} cells/mL\".format(fnames[1], measured_cells[1]))\n    axes[3, 1].set_ylabel(ylabel), axes[3, 1].set_xlabel(\"Wavelength (nm)\")\n\n    fig.tight_layout()\n    plt.savefig(str(SAVEPATH + PlotName), dpi=300)\n\n    return True\n\n\ndef build_LUT(\n    cfactor,\n    solzen,\n    dz,\n    densities,\n    radii,\n    algae,\n    wavelengths,\n    save_LUT,\n    APPLY_ARF,\n    ARF_CI,\n    ARF_HA,\n    LUT_PATH,\n):\n\n    \"\"\"\n    generates LUTs used to invert BioSNICAR in RISA project\n\n    params:\n    ice_rds: fixed effective bubble radius for solid ice layers (default = 525)\n    ice dens: fixed density for solid ice layers (default = 894)\n    zeniths: range of solar zenith angles to loop over\n    dz: thickness of each vertical layer\n    densities: densities for top layer. Lower layers predicted by exponential model\n    algae: mass mixing ratio of algae in top layer\n    wavelengths: wavelength range, default is np.arange(0.2, 5, 0.01)\n    save_LUT: Boolean to toggle saving to npy file\n    SAVEPATH: directory to save LUT\n\n    returns:\n    WCthickLUT: for each index position in the spectraLUT, this holds the WC\n                thickness in the corresponding index position\n    SpectraLUT: ND array containing 480element spectrum for each\n                dens/alg/zen combination\n\n    return spectraLUT\n\n\n    \"\"\"\n    LUT = []\n\n    @dask.delayed\n    def run_sims(cfactor, dens, rad, dz, alg, zen):\n\n        params = c.namedtuple(\n            \"params\",\n            \"rho_layers, grain_rds, layer_type, c_factor_GA, dz, mss_cnc_glacier_algae, solzen\",\n        )\n        params.rho_layers = [916, dens]\n        params.grain_rds = [rad, rad]  # set equal to density\n        params.layer_type = [1, 1]\n        params.dz = [0.001, dz]\n        params.mss_cnc_glacier_algae = [alg, 0]\n        params.solzen = zen\n        params.c_factor_GA = cfactor\n\n        albedo, BBA = call_snicar(params)\n\n        return albedo\n\n    for x in np.arange(0, len(cfactor), 1):\n        for z in np.arange(0, len(solzen), 1):\n            for i in np.arange(0, len(densities), 1):\n                for j in np.arange(0, len(radii), 1):\n                    for p in np.arange(0, len(dz), 1):\n                        for q in np.arange(0, len(algae), 1):\n\n                            albedo = run_sims(\n                                cfactor[x],\n                                densities[i],\n                                radii[j],\n                                dz[p],\n                                algae[q],\n                                solzen[z],\n                            )\n\n                            LUT.append(albedo)\n\n    LUT = dask.compute(*LUT, num_workers=12)\n    LUT = np.array(LUT).reshape(\n        len(cfactor),\n        len(solzen),\n        len(densities),\n        len(radii),\n        len(dz),\n        len(algae),\n        len(wavelengths),\n    )\n\n    # move the ARF application to new loop because dask compute objets are immutable\n    # i.e. modifications to albedo must be done post-compute\n    if APPLY_ARF:\n        for x in np.arange(0, len(cfactor), 1):\n            for z in np.arange(0, len(solzen), 1):\n                for i in np.arange(0, len(densities), 1):\n                    for j in np.arange(0, len(radii), 1):\n                        for p in np.arange(0, len(dz), 1):\n                            for q in np.arange(0, len(algae), 1):\n\n                                if algae[q] > 5000:\n\n                                    LUT[x, z, i, j, p, q, 15:230] = (\n                                        LUT[x, z, i, j, p, q, 15:230] * ARF_HA\n                                    )\n\n                                else:\n                                    LUT[x, z, i, j, p, q, 15:230] = (\n                                        LUT[x, z, i, j, p, q, 15:230] * ARF_CI\n                                    )\n\n    if save_LUT:\n        np.save(str(LUT_PATH + \"LUT.npy\"), LUT)\n\n    return LUT\n\n\ndef inverse_model(\n    FIELD_DATA_FNAME, LUT_PATH, SITES, DZ, DENSITIES, RADII, ZENS, ALGAE, SAVEPATH\n):\n    \"\"\"\n    function takes arrays of vals used to build LUT and runs a 2 step inversion.\n    First, each spectrum in the LUT is compared to each field spectrum\n    The parameters giving the smallest mean error are selected\n    Then those parameters are fixed and the process repeats, only varying algal concentration\n    This gives the parameter set that best simulates each field measurement\n\n    \"\"\"\n    # read in and reshape luts and field spectra\n    field_data = pd.read_csv(FIELD_DATA_FNAME, index_col=None)\n    field_spectra = field_data[::10]\n    lut = np.load(str(LUT_PATH + \"LUT.npy\"))\n    vis_start_idx = 15\n    vis_end_idx = 55\n    nir_start_idx = 55\n    nir_end_idx = 230\n    lut_nir = lut[:, :, :, :, :, nir_start_idx:nir_end_idx]\n    lut_vis = lut[:, :, :, :, :, vis_start_idx:vis_end_idx]\n    flat_nir_lut = lut_nir.reshape(\n        len(ZENS) * len(DENSITIES) * len(RADII) * len(DZ) * len(ALGAE), 175\n    )\n\n    output = pd.DataFrame()\n    retrieved_zen = []\n    retrieved_density = []\n    retrieved_radii = []\n    retrieved_dz = []\n    retrieved_algae = []\n    names = []\n    nir_errors = []\n    vis_errors = []\n    total_errors = []\n\n    for (name, data) in field_spectra.iteritems():\n        # filter to sites defined in config\n        if name in SITES:\n            names.append(name)\n\n            # step 1: find params that match best in NIR\n            error_array = np.sqrt(abs(flat_nir_lut**2 - np.array(data[40:]) ** 2))\n            error_array = np.nan_to_num(\n                error_array, nan=9999\n            )  # protect agaiunst nans being interpreted as low error\n            error_list = np.sum(error_array, axis=1)\n            index = np.argmin(error_list)\n            nir_errors.append(error_list[index])\n            param_idx_phys = np.unravel_index(\n                index, (len(ZENS), len(DENSITIES), len(RADII), len(DZ), len(ALGAE), 1)\n            )\n\n            # step 2: fix physical params and minimise error\n            # in vis by varying algae only\n            lut2 = lut_vis[\n                param_idx_phys[0],\n                param_idx_phys[1],\n                param_idx_phys[2],\n                param_idx_phys[3],\n                :,\n                :,\n            ]\n\n            np.sqrt(abs(flat_nir_lut**2 - np.array(data[40:]) ** 2))\n            error_array = np.sqrt(\n                abs(lut2**2 - np.array(data[vis_start_idx:vis_end_idx]) ** 2)\n            )\n            error_list = np.sum(error_array, axis=1)\n            index = np.argmin(error_list)\n            vis_errors.append(error_list[index])\n            param_idx_alg = np.unravel_index(index, [1, 1, 1, 1, len(ALGAE), 1])\n\n            # step 3: organize out data\n            retrieved_zen.append(ZENS[param_idx_phys[0]])\n            retrieved_density.append(DENSITIES[param_idx_phys[1]])\n            retrieved_radii.append(RADII[param_idx_phys[2]])\n            retrieved_dz.append(DZ[param_idx_phys[3]])\n            retrieved_algae.append(ALGAE[param_idx_alg[4]])\n\n            total_error = abs(\n                lut[\n                    param_idx_phys[0],\n                    param_idx_phys[1],\n                    param_idx_phys[2],\n                    param_idx_phys[3],\n                    param_idx_alg[4],\n                    vis_start_idx:nir_end_idx,\n                ]\n                - data\n            )\n            total_errors.append(np.mean(total_error))\n\n    output[\"fname\"] = names\n    output[\"solzen\"] = retrieved_zen\n    output[\"density\"] = retrieved_density\n    output[\"radii\"] = retrieved_radii\n    output[\"dz\"] = retrieved_dz\n    output[\"algae\"] = retrieved_algae\n    output[\"nir_error\"] = nir_errors\n    output[\"vis_error\"] = vis_errors\n    output[\"total_error\"] = total_errors\n\n    output.to_csv(str(SAVEPATH + \"inverse_model_output.csv\"))\n\n    return output\n\n\ndef isolate_biological_effect(FIELD_DATA_FNAME, CIsites, LAsites, HAsites, SAVEPATH):\n\n    \"\"\"\n    This function estimates the albedo reduction resulting from the ice physical changes\n    versus the biological growth.\n\n    Some nuance to the interpretation because the ce surface likely would not\n    degrade to the same extent without the algal bloom.\n\n    \"\"\"\n\n    # read in spectral database\n    spectra = pd.read_csv(FIELD_DATA_FNAME)\n\n    # reformat feld spectra to match snicar resolution\n    spectra = spectra[::10]\n    CIspec = spectra[spectra.columns.intersection(CIsites)]\n    HAspec = spectra[spectra.columns.intersection(HAsites)]\n    LAspec = spectra[spectra.columns.intersection(LAsites)]\n    meanCI = CIspec.mean(axis=1)\n    meanHA = HAspec.mean(axis=1)\n    meanLA = LAspec.mean(axis=1)\n\n    # define local function for calling snicar\n    def simulate_albedo(rds, rho, dz, alg):\n        params = c.namedtuple(\n            \"params\",\n            \"rho_layers, grain_rds, layer_type, dz, mss_cnc_glacier_algae, solzen\",\n        )\n        params.grain_rds = rds\n        params.rho_layers = rho\n        params.layer_type = [1, 1]\n        params.dz = dz\n        params.mss_cnc_glacier_algae = alg\n        params.solzen = 53\n        albedo, BBA = call_snicar(params)\n        return albedo, BBA\n\n    # call snicar to generat esimulated spectrum for LA and HA using predetermined params\n\n    SNICARalbedoLA, BBA = simulate_albedo([800, 800], [800, 800], [0.001, 0.1], [0, 0])\n    SNICARalbedoHA, BBA = simulate_albedo([900, 900], [800, 800], [0.001, 0.08], [0, 0])\n    SNICARalbedoLA = SNICARalbedoLA[15:230]\n    SNICARalbedoHA = SNICARalbedoHA[15:230]\n\n    # plot figure\n    x = np.arange(350, 2500, 10)\n    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))\n    ax1.plot(x, meanCI, linestyle=\"--\", alpha=0.4, label=\"Clean ice (mean)\")\n    ax1.plot(x, meanLA, linestyle=\"-.\", alpha=0.4, label=\"Algal ice (mean)\")\n    ax1.plot(\n        x, SNICARalbedoLA, linestyle=\"dotted\", alpha=0.4, label=\"Clean ice (model)\"\n    )\n    ax1.fill_between(x, meanCI, SNICARalbedoLA, alpha=0.2)\n    ax1.fill_between(x, SNICARalbedoLA, meanLA, color=\"k\", alpha=0.2)\n    ax1.set_xlim(350, 1500), ax1.legend(loc=\"best\")\n    ax1.set_ylabel(\"Albedo\"), ax1.set_xlabel(\"Wavelength (nm)\")\n\n    ax2.plot(x, meanCI, linestyle=\"--\", alpha=0.4, label=\"Clean ice (mean)\")\n    ax2.plot(x, meanHA, linestyle=\"-.\", alpha=0.4, label=\"Algal ice (mean)\")\n    ax2.plot(\n        x, SNICARalbedoHA, linestyle=\"dotted\", alpha=0.4, label=\"Clean ice (model)\"\n    )\n    ax2.fill_between(x, meanCI, SNICARalbedoHA, alpha=0.2)\n    ax2.fill_between(x, SNICARalbedoHA, meanHA, color=\"k\", alpha=0.2)\n    ax2.set_xlim(350, 1500), ax2.legend(loc=\"best\")\n    ax2.set_ylabel(\"Albedo\"), ax2.set_xlabel(\"Wavelength (nm)\")\n    fig.tight_layout()\n    plt.savefig(str(SAVEPATH + \"/BiovsPhysEffect.jpg\"), dpi=300)\n\n    # define incoming to calculate broadband albedo\n    incoming = xr.open_dataset(\n        \"/home/joe/Code/BioSNICAR_GO_PY/Data/Mie_files/480band/fsds/swnb_480bnd_sas_clr_SZA60.nc\"\n    )\n    incoming = incoming[\"flx_frc_sfc\"].values\n    incoming = incoming[15:230]\n\n    # calculate broadband albedo of each case\n    LA_BBA = np.sum(meanLA * incoming) / np.sum(incoming)\n    HA_BBA = np.sum(meanHA * incoming) / np.sum(incoming)\n    CI_BBA = np.sum(meanCI * incoming) / np.sum(incoming)\n    CI2_BBA_LA = np.sum(SNICARalbedoLA * incoming) / np.sum(incoming)\n    CI2_BBA_HA = np.sum(SNICARalbedoHA * incoming) / np.sum(incoming)\n\n    # calculate change due to bio/phys as BBA difference\n    delAbioLA = CI2_BBA_LA - LA_BBA\n    delAphysLA = CI_BBA - CI2_BBA_LA\n    delAbioHA = CI2_BBA_HA - HA_BBA\n    delAphysHA = CI_BBA - CI2_BBA_HA\n\n    return delAbioLA, delAphysLA, delAbioHA, delAphysHA\n\n\ndef run_best_params(\n    SAVEPATH,\n    ALL_FIELD_SAMPLES,\n    FIELD_DATA_FNAME,\n    CI_SITES,\n    LA_SITES,\n    HA_SITES,\n    WEIGHT,\n    CLEAN,\n):\n    \"\"\"\n    function calls out to find_best_params\n    \"\"\"\n    ResultArray = np.zeros(shape=(len(ALL_FIELD_SAMPLES), 6))\n\n    for i in np.arange(0, len(ALL_FIELD_SAMPLES), 1):\n\n        fn = ALL_FIELD_SAMPLES[i]\n        Results = find_best_params(\n            FIELD_DATA_FNAME, fn, CI_SITES, LA_SITES, HA_SITES, WEIGHT, CLEAN\n        )\n        Results = np.array(Results)\n        best_idx = Results[:, 1].argmin()\n        best_params = Results[best_idx, 0]\n        best_error = Results[best_idx, 1]\n        best_dens, best_rds, best_dz, best_alg, best_zen = zip(best_params)\n        ResultArray[i, :] = (\n            np.array(best_dens),\n            np.array(best_rds),\n            np.array(best_dz),\n            np.array(best_alg),\n            np.array(best_zen),\n            np.array(best_error),\n        )\n\n    Out = pd.DataFrame(\n        data=ResultArray, columns=[\"dens\", \"rds\", \"dz\", \"alg\", \"zen\", \"spec_err\"]\n    )\n    Out.index = ALL_FIELD_SAMPLES\n    Out.to_csv(str(SAVEPATH + \"retrieved_params.csv\"))\n\n    return True\n\n\ndef find_best_params(\n    FIELD_DATA_FNAME, sampleID, CIsites, LAsites, HAsites, weight, clean=True\n):\n\n    \"\"\"\n    This function will return the SNICAR parameter set that provides the\n    best approximation to a given field spectrum.\n\n    \"\"\"\n\n    spectra = pd.read_csv(FIELD_DATA_FNAME)\n    spectra = spectra[::10]\n\n    CIspec = spectra[spectra.columns.intersection(CIsites)]\n    HAspec = spectra[spectra.columns.intersection(HAsites)]\n    LAspec = spectra[spectra.columns.intersection(LAsites)]\n\n    if sampleID == \"CImean\":\n        field_spectrum = CIspec.mean(axis=1)\n    elif sampleID == \"HAmean\":\n        field_spectrum = HAspec.mean(axis=1)\n    elif sampleID == \"LAmean\":\n        field_spectrum = LAspec.mean(axis=1)\n    elif sampleID == \"RAIN\":\n        field_spectrum = spectra[\"RAIN2\"]\n    else:\n        field_spectrum = spectra[sampleID]\n\n    # calculate 2BDA index of field spectrum\n    BDA2idx = np.array(field_spectrum)[36] / np.array(field_spectrum)[31]\n\n    dens = [550, 600, 650, 700, 750, 800, 850]\n    dz = [0.02, 0.03, 0.04, 0.05, 0.06, 0.08, 0.1, 0.2]\n    rds = [600, 700, 800, 900, 1000]\n    alg = [0, 2500, 5000, 7500, 10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000]\n    c_factors = [10, 20, 30]\n    solzen = [40, 45, 50]\n\n    @dask.delayed\n    def run_sims(i, j, k, p, q, z):\n\n        params = c.namedtuple(\n            \"params\",\n            \"rho_layers, grain_rds, layer_type, dz, mss_cnc_glacier_algae, c_factor_GA, solzen\",\n        )\n        params.rho_layers = [i, i]\n        params.grain_rds = [j, j]\n        params.layer_type = [1, 1]\n        params.dz = [0.001, k]\n        params.mss_cnc_glacier_algae = [p, 0]\n        params.c_factor_GA = c_factors[q]\n        params.solzen = z\n\n        albedo, BBA = call_snicar(params)\n\n        error_vis = np.mean(abs(albedo[15:55] - field_spectrum[0:40]))\n        error_nir = np.mean(abs(albedo[55:100] - field_spectrum[40:85]))\n        error = ((error_vis * weight) + error_nir) / (1 + weight)\n\n        params = (i, j, k, p, z)\n        out = (params, error)\n\n        return out\n\n    Out = []\n    # now use the reduced LUT to call snicar and obtain best matching spectrum\n    for i in dens:\n        for j in rds:\n            for k in dz:\n                for p in alg:\n                    for z in solzen:\n                        out = run_sims(i, j, k, p, z)\n                        Out.append(out)\n\n    Result = dask.compute(*Out, num_workers=12)\n\n    return Result\n\n\ndef BDA2_of_field_samples():\n\n    \"\"\"\n    2DBA index calculated from field samples after field spectra are averaged over S2 band 4 and 5 wavelengths\n    weighted by the sensor spectral response function for each band. The index is then calculated as B5/B4\n    and the cell concentration predicted using Wang et al's (2018) conversion equation.\n\n    \"\"\"\n\n    spectra = pd.read_csv(\n        \"/home/joe/Code/Remote_Ice_Surface_Analyser/Training_Data/HCRF_master_16171819.csv\"\n    )\n\n    # reformat LUT: flatten LUT from 3D to 2D array with one column per combination\n    # of RT params, one row per wavelength\n\n    responsefunc = pd.read_csv(\n        \"/home/joe/Code/Remote_Ice_Surface_Analyser/S2SpectralResponse.csv\"\n    )\n    func04 = responsefunc[\"B4\"].loc[\n        (responsefunc[\"SR_WL\"] > 650) & (responsefunc[\"SR_WL\"] <= 680)\n    ]\n    func05 = responsefunc[\"B5\"].loc[\n        (responsefunc[\"SR_WL\"] > 698) & (responsefunc[\"SR_WL\"] <= 713)\n    ]\n\n    filenames = []\n    Idx2DBAList = []\n    prd2DBAList = []\n    Idx2DBA_S2List = []\n    prd2DBA_S2List = []\n    Idx2DBA_Ideal_List = []\n    prd2DBA_Ideal_List = []\n\n    for i in np.arange(0, len(spectra.columns), 1):\n\n        if i != \"Wavelength\":\n\n            colname = spectra.columns[i]\n            spectrum = np.array(spectra[colname])\n\n            B04 = np.mean(spectrum[300:330] * func04)\n            B05 = np.mean(spectrum[348:363] * func05)\n            Idx2DBA = spectrum[355] / spectrum[315]\n            prd2DBA = 10e-35 * Idx2DBA * np.exp(87.015 * Idx2DBA)\n            Idx2DBA_S2 = B05 / B04\n            prd2DBA_S2 = 10e-35 * Idx2DBA_S2 * np.exp(87.015 * Idx2DBA_S2)\n            Idx2DBA_Ideal = spectrum[360] / spectrum[330]\n            prd2DBA_Ideal = 10e-35 * Idx2DBA_Ideal * np.exp(87.015 * Idx2DBA_Ideal)\n\n            filenames.append(colname)\n            Idx2DBAList.append(Idx2DBA)\n            prd2DBAList.append(prd2DBA)\n            Idx2DBA_S2List.append(Idx2DBA_S2)\n            prd2DBA_S2List.append(prd2DBA_S2)\n            Idx2DBA_Ideal_List.append(Idx2DBA_Ideal)\n            prd2DBA_Ideal_List.append(prd2DBA_Ideal)\n\n    Out = pd.DataFrame()\n    Out[\"filename\"] = filenames\n    Out[\"2DBAIdx\"] = Idx2DBAList\n    Out[\"2DBAPrediction\"] = prd2DBAList\n    Out[\"2DBA_S2Idx\"] = Idx2DBA_S2List\n    Out[\"2DBA_S2Prediction\"] = prd2DBA_S2List\n    Out[\"2DBAIdx_Ideal\"] = Idx2DBA_Ideal_List\n    Out[\"2DBAPrediction_Ideal\"] = prd2DBA_Ideal_List\n\n    return Out\n\n\ndef compare_predicted_and_measured(SAVEPATH, path_to_metadata):\n\n    ## imports and data organisation\n    import numpy as np\n    import pandas as pd\n    import statsmodels.api as sm\n\n    DF = pd.read_csv(path_to_metadata)\n\n    measured_cells = DF[\"measured_cells\"]\n    modelled_cells = DF[\"algae_cells_inv_model_S2\"]\n    BDA2_cells = DF[\"cells_BDA2_centre_wang\"]\n    BDA2_idx = DF[\"BDA2_centre\"]\n\n    ## regression models\n\n    # Ordinary least squares regression\n    model1 = sm.OLS(modelled_cells, measured_cells).fit()\n    summary1 = model1.summary()\n    test_x = [\n        0,\n        1000,\n        5000,\n        7500,\n        10000,\n        12500,\n        15000,\n        17500,\n        20000,\n        25000,\n        30000,\n        35000,\n        40000,\n        50000,\n    ]\n    ypred1 = model1.predict(test_x)\n\n    # regress measured cells against band index\n    # use this to give predictive linear model\n\n    BDA2_PredModel = sm.OLS(measured_cells, sm.add_constant(BDA2_idx)).fit()\n    BDA2_PredModel_r2 = np.round(BDA2_PredModel.rsquared, 3)\n    BDA2_PredModel_y = BDA2_PredModel.predict(sm.add_constant(BDA2_idx))\n\n    # regress BDA2 predicted cells against measured cells\n    model2 = sm.OLS(BDA2_PredModel_y, measured_cells).fit()\n    summary2 = model2.summary()\n    test_x = [\n        0,\n        1000,\n        5000,\n        7500,\n        10000,\n        12500,\n        15000,\n        17500,\n        20000,\n        25000,\n        30000,\n        35000,\n        40000,\n        50000,\n    ]\n    ypred2 = model2.predict(test_x)\n\n    # multipanel figure\n    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 8))\n\n    ax1.plot(\n        measured_cells, color=\"k\", marker=\"x\", linestyle=\"None\", label=\"field-measured\"\n    )\n    ax1.plot(\n        modelled_cells,\n        color=\"b\",\n        marker=\"o\",\n        markerfacecolor=\"None\",\n        alpha=0.6,\n        linestyle=\"None\",\n        label=\"RTM model prediction\",\n    )\n    ax1.plot(\n        BDA2_PredModel_y,\n        color=\"r\",\n        marker=\"^\",\n        markerfacecolor=\"r\",\n        alpha=0.3,\n        linestyle=\"None\",\n        label=\"new 2BDA model prediction\",\n    )\n    ax1.set_ylabel(\"Algal concentration (cells/mL)\")\n    ax1.set_xticks(range(len(measured_cells)))\n    ax1.set_xticklabels([])\n    ax1.legend(loc=\"upper left\")\n    ax1.set_xlabel(\"Individual samples\")\n    ax1.set_ylim(0, 65000)\n\n    ax2.scatter(\n        measured_cells,\n        modelled_cells,\n        marker=\"o\",\n        facecolor=\"None\",\n        color=\"b\",\n        alpha=0.6,\n        label=\"RTM\\nr$^2$ = {}\\np = {}\".format(\n            np.round(model1.rsquared, 3), np.round(model1.pvalues[0], 8)\n        ),\n    )\n    ax2.plot(test_x, ypred1, linestyle=\"dotted\", color=\"b\", alpha=0.6)\n    ax2.scatter(\n        measured_cells,\n        BDA2_PredModel_y,\n        marker=\"^\",\n        facecolor=\"r\",\n        color=\"r\",\n        alpha=0.3,\n        label=\"2BDA\\nr$^2$ = {}\\np = {}\".format(\n            np.round(model2.rsquared, 3), np.round(model2.pvalues[0], 10)\n        ),\n    )\n    ax2.plot(test_x, ypred2, linestyle=\"dashed\", color=\"r\", alpha=0.3)\n    ax2.set_ylabel(\"Algal concentration,\\n cells/mL (field)\")\n    ax2.set_xlabel(\"Algal concentration,\\n clls/mL (predicted by model)\")\n    ax2.set_xlim(0, 50000), ax2.set_ylim(0, 60000)\n\n    ax2.legend(loc=\"upper left\")\n\n    fig.tight_layout()\n\n    SAVEPATH = \"/home/joe/Code/Remote_Ice_Surface_Analyser/Manuscript/Figures\"\n    fig.savefig(str(SAVEPATH + \"/measured_modelled_algae.png\"), dpi=300)\n\n    return\n", "meta": {"hexsha": "69bb6a469de95c5ac5542ff6e6d2c1ef7c8dbdd8", "size": 30835, "ext": "py", "lang": "Python", "max_stars_repo_path": "experiments/utils.py", "max_stars_repo_name": "jmcook1186/biosnicar-py", "max_stars_repo_head_hexsha": "7a2e224f7a30c746291c718fcddb908575f0f3c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experiments/utils.py", "max_issues_repo_name": "jmcook1186/biosnicar-py", "max_issues_repo_head_hexsha": "7a2e224f7a30c746291c718fcddb908575f0f3c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-03-28T14:31:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T14:31:51.000Z", "max_forks_repo_path": "experiments/utils.py", "max_forks_repo_name": "jmcook1186/biosnicar-py", "max_forks_repo_head_hexsha": "7a2e224f7a30c746291c718fcddb908575f0f3c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1559139785, "max_line_length": 113, "alphanum_fraction": 0.595654289, "include": true, "reason": "import numpy,import statsmodels", "num_tokens": 9333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19395960471703508}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n============================================================================\nGenerating simple pulses and pulse trains\n============================================================================\nThis example shows how to build and visualize basic types of stimuli such as\n:py:class:`~pulse2percept.stimuli.MonophasicPulse`,\n:py:class:`~pulse2percept.stimuli.BiphasicPulse` or a\n:py:class:`~pulse2percept.stimuli.PulseTrain` for a given implant.\n\nA monophasic pulse has a single phase and can be either anodic (by definition:\nhas a positive current amplitude) or cathodic (negative current amplitude).\n\nA biphasic pulse is generally charge-balanced for safety reasons (i.e., the\nnet current must sum to zero over time) and defined as either anodic-first\nor cathodic-first.\n\nMultiple pulses can form a pulse train.\n\n\n\"\"\"\n# sphinx_gallery_thumbnail_number = 7\n\n##############################################################################\n# Simplest stimulus\n# ---------------------\n# :py:class:`~pulse2percept.stimuli.Stimulus` is the base class to generate\n# different types of stimuli. The simplest way to instantiate a Stimulus is\n# to pass a scalar value which is interpreted as the current amplitude\n# for a single electrode.\n\n# Let's start by importing necessary modules\nfrom pulse2percept.stimuli import (MonophasicPulse, BiphasicPulse,\n                                   Stimulus, PulseTrain)\n\nimport numpy as np\n\nstim = Stimulus(10)\n\n##############################################################################\n# Parameters we don't specify will take on default values. We can inspect\n# all current model parameters as follows:\n\nprint(stim)\n\n##############################################################################\n# This command also reveals a number of other parameters to set, such as:\n#\n# * ``electrodes``: We can either specify the electrodes in the source\n#   or within the stimulus. If none are specified it looks up the source\n#   electrode.\n#\n# * ``metadata``: Optionally we can include metadata to the stimulus we\n#   generate as a dictionary.\n#\n# To change parameter values, either pass them directly to the constructor\n# above or set them by hand, like this:\n\nstim.metadata = {'name': 'A simple stimulus', 'date': '2020-01-01'}\nstim\n\n##############################################################################\n# A monophasic pulse\n# --------------------\n# We can specify the arguments of the monophasic pulse as follows:\n\npulse_type = 'anodic'  # anodic: positive amplitude, cathodic: negative\npulse_dur = 4.6 / 1000  # pulse duration in seconds\ndelay_dur = 10.0 / 1000  # pulse delivered after delay in seconds\nstim_dur = 0.5  # stimulus duration in seconds (pulse padded with zeros)\ntime_step = 0.1 / 1000  # temporal sampling step in seconds\n\n##############################################################################\n# The sampling step ``time_step`` defines at which temporal resolution the\n# stimulus is resolved. In the above example, the time step is 0.1 ms.\n#\n# By calling Stimulus with a ``MonophasicPulse`` source, we can generate a\n# single pulse:\nmonophasic_stim = Stimulus(MonophasicPulse(ptype=pulse_type, pdur=pulse_dur,\n                                           delay_dur=delay_dur,\n                                           stim_dur=stim_dur,\n                                           tsample=time_step))\nprint(monophasic_stim)\n\n##############################################################################\n# Here, ``data`` is a 2D NumPy array where rows are electrodes and columns are\n# the points in time. Since we did not specify any electrode names in\n# ``MonophasicPulse``, the number of electrodes is inferred from the input\n# source type. There is only one row in the above example, denoting a single\n# electrode.\n#\n# By default, the :py:class:`~pulse2percept.stimuli.MonophasicPulse` object\n# automatically assumes a current amplitude of 1 uA.\n\n##############################################################################\n# We can visualize the generated pulse using Matplotlib:\n\nimport matplotlib.pyplot as plt\nfig, ax = plt.subplots(figsize=(8, 5))\nax.plot(monophasic_stim.time, monophasic_stim.data[0, :])\nax.set_xlabel('Time (s)')\nax.set_ylabel('Amplitude ($\\mu$A)')\n\n###############################################################################\n# A biphasic pulse\n# ------------------\n# Similarly, we can generate a biphasic pulse by changing the source of the\n# stimulus to :py:class:`~pulse2percept.stimuli.BiphasicPulse`. This time\n# parameter ``ptype`` can either be 'anodicfirst' or 'cathodicfirst'.\n\n# set relevant parameters\npulse_type = 'cathodicfirst'\nbiphasic_stim = Stimulus(BiphasicPulse(ptype=pulse_type, pdur=pulse_dur,\n                                       tsample=time_step))\n\n###############################################################################\n# If we visualize this stimulus, we can see the difference between a monophasic\n# and biphasic pulse:\n\n# Create a figure with two subplots\nfig, axes = plt.subplots(1, 2, figsize=(8, 5))\n\n# First, plot monophasic pulse\naxes[0].plot(monophasic_stim.time, monophasic_stim.data[0])\nax.set_xlabel('Time (s)')\nax.set_ylabel('Amplitude ($\\mu$A)')\n\n# Second, plot biphasic pulse\naxes[1].plot(biphasic_stim.time, biphasic_stim.data[0])\nax.set_xlabel('Time (s)')\nax.set_ylabel('Amplitude ($\\mu$A)')\n\n###############################################################################\n# Changing pulse amplitude\n# ----------------------------------\n# For any given pulse, we can modify the amplitude by indexing into the ``data``\n# row that corresponds to the desired electrode. In the above example, we only\n# have one electrode (index 0).\n# Let's say we want the amplitude of the monophasic pulse to be 10 micro amps.\n# We have two options: either change the values of the ``data`` array directly:\n\n# get the data structure by indexing the electrode at 0\nmonophasic_stim.data[0] = 10 * monophasic_stim.data[0]\nprint(monophasic_stim)\n\n###############################################################################\n# Or we can create a NumPy array and assign that to the data structure of the\n# stimulus:\n\n# recreate the same stimulus with an amplitude 1 microAmps.\nmonophasic_stim = Stimulus(MonophasicPulse(ptype='anodic', pdur=pulse_dur,\n                                           delay_dur=delay_dur,\n                                           stim_dur=stim_dur,\n                                           tsample=time_step))\nmonophasic_stim.data[0] = 10 * np.ones_like(monophasic_stim.data[0])\nprint(monophasic_stim)\n\n###############################################################################\n# Similarly, let's say we want the cathodic part of the biphasic pulse to be -5\n# micro amps, and the anodic part to be +20 micro amps (note that this stimulus\n# wouldn't be charge-balanced).\n#\n# We first need to find the halfway point where the current switches from\n# cathodic to anodic. To do that we first get the length of the pulse by\n# indexing the single electrode at 0\nlength = len(biphasic_stim.data[0])\nprint(length)\n\n# Find the halfway where cathodic turns into anodic pulse\nhalf = int(len(biphasic_stim.data[0]) / 2)\nprint(\"Halfway index is\", half)\n\n# change the first half of the pulse to be 5 times larger\nbiphasic_stim.data[0][0:half] = 5 * biphasic_stim.data[0][0:half]\n\n# change the second half to be 20 times larger\nbiphasic_stim.data[0][half:length] = 20 * biphasic_stim.data[0][half:length]\n\n###############################################################################\n# Let's plot the monophasic and biphasic pulses again:\n\n# Create a figure with two subplots\nfig, axes = plt.subplots(ncols=2, figsize=(8, 5))\n\n# First, plot monophasic pulse\naxes[0].plot(monophasic_stim.time, monophasic_stim.data[0])\naxes[0].set_xlabel('Time (s)')\naxes[0].set_ylabel('Amplitude ($\\mu$A)')\n# Second, plot biphasic pulse\naxes[1].plot(biphasic_stim.time, biphasic_stim.data[0])\naxes[1].set_xlabel('Time (s)')\naxes[1].set_ylabel('Amplitude ($\\mu$A)')\nfig.tight_layout()\n\n\n###############################################################################\n# Generating standard pulse trains\n# ----------------------------------\n# The easiest way to generate a pulse train is to use the\n# :py:class:`~pulse2percept.stimuli.PulseTrain` object, which allows for\n# various stimulus attributes to be specified:\n\ntime_step = 0.1 / 1000  # temporal sampling in seconds\nfreq = 20  # frequency in Hz\namp = 100  # maximum amplitude of the pulse train in microAmps\ndur = 0.2  # total duration of the pulse train in seconds\npulse_type = 'cathodicfirst'  # whether the first phase is positive or negative\npulse_order = 'gapfirst'  # whether the train starts with gap or a pulse.\n\n# Define the pulse train with given parameters\nptrain = PulseTrain(tsample=time_step,\n                    freq=freq,\n                    dur=dur,\n                    amp=amp,\n                    pulsetype=pulse_type,\n                    pulseorder=pulse_order)\n\n# Create a new stimulus where the pulse train is the source\nptrain_stim = Stimulus(ptrain)\n\n# Visualize:\nfig, ax = plt.subplots(figsize=(8, 5))\nax.plot(ptrain_stim.time, ptrain_stim.data[0, :])\nax.set_xlabel('Time (s)')\nax.set_ylabel('Amplitude ($\\mu$A)')\n\n###############################################################################\n# Alternatively, we are free to specify a discrete set of points in time and\n# the current amplitude we would like to apply at those times.\n#\n# It is important to note that the :py:class:`~pulse2percept.stimuli.Stimulus`\n# object will linearly interpolate between specified time points.\n# For example, the following generates a simple sawtooth stimulus:\n\nstim = Stimulus([[0, -10, 10, -10, 10, -10, 0]],\n                time=[0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0])\nfig, ax = plt.subplots(figsize=(8, 5))\nax.plot(stim.time, stim.data[0, :])\nax.set_xlabel('Time (s)')\nax.set_ylabel('Amplitude ($\\mu$A)')\n\n##############################################################################\n# For a biphasic pulse, we need to specify both the rising edge (low-to-high\n# transition) and falling edge (high-to-low transition) of the signal:\n\nstim = Stimulus([[0, 0, 10, 10,  0, 0]],\n                time=[0, 0.1, 0.1, 0.2, 0.2, 1.0])\nfig, ax = plt.subplots(figsize=(8, 5))\nax.plot(stim.time, stim.data[0, :])\nax.set_xlabel('Time (s)')\nax.set_ylabel('Amplitude ($\\mu$A)')\n\n##############################################################################\n# We can thus generate arbitrarily complex stimuli:\n\nstim = Stimulus([[0, 0, 20, 20, -5, -5, 0, 0, 0, 20, 20, -5, -5, 0, 0]],\n                time=[0, 0.1, 0.1, 0.2, 0.2, 0.6, 0.6, 1.0, 1.1, 1.1, 1.2, 1.2, 1.6, 1.6, 2.0])\nfig, ax = plt.subplots(figsize=(8, 5))\nax.plot(stim.time, stim.data[0, :])\nax.set_xlabel('Time (s)')\nax.set_ylabel('Amplitude ($\\mu$A)')\n", "meta": {"hexsha": "e889bcfb0a81156b932dca193f562661d5f59897", "size": 10828, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/stimuli/plot_pulses.py", "max_stars_repo_name": "garethgeorge/pulse2percept", "max_stars_repo_head_hexsha": "14b85a7b7acfd740e8a2ac4a471aa8149a5152c5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-02T00:13:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-07T07:34:21.000Z", "max_issues_repo_path": "examples/stimuli/plot_pulses.py", "max_issues_repo_name": "NathanWoo/pulse2percept", "max_issues_repo_head_hexsha": "2a1e15159af234fb247092b88a465b7bdffd21db", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/stimuli/plot_pulses.py", "max_forks_repo_name": "NathanWoo/pulse2percept", "max_forks_repo_head_hexsha": "2a1e15159af234fb247092b88a465b7bdffd21db", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3282442748, "max_line_length": 95, "alphanum_fraction": 0.5966014038, "include": true, "reason": "import numpy", "num_tokens": 2643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.19395960471703505}}
{"text": "from __future__ import (absolute_import, division, print_function, unicode_literals)\nimport numpy as np\nimport multiprocessing\nfrom functools import partial\n\nfrom ..pair_counters.npairs_xy_z import _npairs_xy_z_process_args\nfrom ..pair_counters.mesh_helpers import _set_approximate_cell_sizes, _cell1_parallelization_indices\nfrom ..pair_counters.rectangular_mesh import RectangularDoubleMesh\nfrom .velocity_marked_npairs_3d import _velocity_marked_npairs_3d_process_weights\nfrom .engines import velocity_marked_npairs_xy_z_engine\n\n__author__ = ('Duncan Campbell', 'Andrew Hearin')\n\n\n__all__ = ('velocity_marked_npairs_xy_z', )\n\n\ndef velocity_marked_npairs_xy_z(sample1, sample2, rp_bins, pi_bins, period=None,\n        weights1=None, weights2=None, weight_func_id=1, num_threads=1,\n        approx_cell1_size=None, approx_cell2_size=None):\n    r\"\"\"\n    Calculate the number of velocity weighted pairs\n    with separations greater than or equal to\n    :math:`r_{\\perp}` and :math:`r_{\\parallel}`, :math:`W(>r_{\\perp},>r_{\\parallel})`.\n\n    :math:`r_{\\perp}` and :math:`r_{\\parallel}` are defined wrt the z-direction.\n\n    The weight given to each pair is determined by the weights for a pair,\n    :math:`w_1`, :math:`w_2`, and a user-specified \"velocity weighting function\", indicated\n    by the ``weight_func_id`` parameter, :math:`f(w_1,w_2)`.\n\n    Parameters\n    ----------\n    sample1 : array_like\n        Npts1 x 3 numpy array containing 3-D positions of points.\n        See the :ref:`mock_obs_pos_formatting` documentation page, or the\n        Examples section below, for instructions on how to transform\n        your coordinate position arrays into the\n        format accepted by the ``sample1`` and ``sample2`` arguments.\n        Length units are comoving and assumed to be in Mpc/h, here and throughout Halotools.\n\n    sample2 : array_like\n        Npts2 x 3 array containing 3-D positions of points.\n\n    rp_bins : array_like\n        array of boundaries defining the radial bins perpendicular to the LOS in which\n        pairs are counted.\n        Length units are comoving and assumed to be in Mpc/h, here and throughout Halotools.\n\n    pi_bins : array_like\n        array of boundaries defining the bins parallel to the LOS in which\n        pairs are counted.\n        Length units are comoving and assumed to be in Mpc/h, here and throughout Halotools.\n\n    period : array_like, optional\n        Length-3 sequence defining the periodic boundary conditions\n        in each dimension. If you instead provide a single scalar, Lbox,\n        period is assumed to be the same in all Cartesian directions.\n        If set to None (the default option), PBCs are set to infinity.\n        Length units are comoving and assumed to be in Mpc/h, here and throughout Halotools.\n\n    weights1 : array_like, optional\n        Either a 1-D array of length *Npts1*, or a 2-D array of length *Npts1* x *N_weights*,\n        containing the weights used for the weighted pair counts. If this parameter is\n        None, the weights are set to np.ones(*(Npts1,N_weights)*).\n\n    weights2 : array_like, optional\n        Either a 1-D array of length *Npts2*, or a 2-D array of length *Npts2* x *N_weights*,\n        containing the weights used for the weighted pair counts. If this parameter is\n        None, the weights are set to np.ones(*(Npts2,N_weights)*).\n\n    weight_func_id : int, optional\n        velocity weighting function integer ID. Each weighting function requires a specific\n        number of weights per point, *N_weights*.  See the Notes for a description of\n        available weighting functions.\n\n    num_threads : int, optional\n        Number of threads to use in calculation, where parallelization is performed\n        using the python ``multiprocessing`` module. Default is 1 for a purely serial\n        calculation, in which case a multiprocessing Pool object will\n        never be instantiated. A string 'max' may be used to indicate that\n        the pair counters should use all available cores on the machine.\n\n    approx_cell1_size : array_like, optional\n        Length-3 array serving as a guess for the optimal manner by how points\n        will be apportioned into subvolumes of the simulation box.\n        The optimum choice unavoidably depends on the specs of your machine.\n        Default choice is to use Lbox/10 in each dimension,\n        which will return reasonable result performance for most use-cases.\n        Performance can vary sensitively with this parameter, so it is highly\n        recommended that you experiment with this parameter when carrying out\n        performance-critical calculations.\n\n    approx_cell2_size : array_like, optional\n        Analogous to ``approx_cell1_size``, but for sample2.  See comments for\n        ``approx_cell1_size`` for details.\n\n    Returns\n    -------\n    w1N_pairs : numpy.array\n        2-D array of shape *(Nrp_bins,Npi_bins)* containing the weighted number counts\n        of pairs. The exact values depend on ``weight_func_id``\n        (which weighting function was chosen).\n\n    w2N_pairs : numpy.array\n        2-D array of shape *(Nrp_bins,Npi_bins)* containing the weighted number counts\n        of pairs. The exact values depend on ``weight_func_id``\n        (which weighting function was chosen).\n\n    w3N_pairs : numpy.array\n        2-D array of shape *(Nrp_bins,Npi_bins)* containing the weighted number counts\n        of pairs. The exact values depend on ``weight_func_id``\n        (which weighting function was chosen).\n\n    Examples\n    --------\n    For demonstration purposes we will work with\n    halos in the `~halotools.sim_manager.FakeSim`.\n\n    >>> from halotools.sim_manager import FakeSim\n    >>> halocat = FakeSim()\n\n    >>> x = halocat.halo_table['halo_x']\n    >>> y = halocat.halo_table['halo_y']\n    >>> z = halocat.halo_table['halo_z']\n\n    We transform our *x, y, z* points into the array shape used by the pair-counter by\n    taking the transpose of the result of `numpy.vstack`. This boilerplate transformation\n    is used throughout the `~halotools.mock_observables` sub-package:\n\n    >>> sample1 = np.vstack((x,y,z)).T\n\n    We will do the same to get a random set of velocities.\n\n    >>> vx = halocat.halo_table['halo_vx']\n    >>> vy = halocat.halo_table['halo_vy']\n    >>> vz = halocat.halo_table['halo_vz']\n    >>> velocities = np.vstack((x,y,z,vx,vy,vz)).T\n\n    >>> rp_bins = np.logspace(-2,-1,10)\n    >>> pi_bins = np.linspace(0, 10, 5)\n    >>> result = velocity_marked_npairs_xy_z(sample1, sample1, rp_bins, pi_bins, period=halocat.Lbox, weights1=velocities, weights2=velocities,)\n\n    \"\"\"\n    result = _npairs_xy_z_process_args(sample1, sample2, rp_bins, pi_bins, period,\n            num_threads, approx_cell1_size, approx_cell2_size)\n    x1in, y1in, z1in, x2in, y2in, z2in = result[0:6]\n    rp_bins, pi_bins, period, num_threads, PBCs, approx_cell1_size, approx_cell2_size = result[6:]\n    xperiod, yperiod, zperiod = period\n\n    rp_max = np.max(rp_bins)\n    pi_max = np.max(pi_bins)\n    search_xlength, search_ylength, search_zlength = rp_max, rp_max, pi_max\n\n    # Process the input weights and with the helper function\n    weights1, weights2 = (\n        _velocity_marked_npairs_3d_process_weights(sample1, sample2,\n            weights1, weights2, weight_func_id))\n\n    # Compute the estimates for the cell sizes\n    approx_cell1_size, approx_cell2_size = (\n        _set_approximate_cell_sizes(approx_cell1_size, approx_cell2_size, period)\n        )\n    approx_x1cell_size, approx_y1cell_size, approx_z1cell_size = approx_cell1_size\n    approx_x2cell_size, approx_y2cell_size, approx_z2cell_size = approx_cell2_size\n\n    # Build the rectangular mesh\n    double_mesh = RectangularDoubleMesh(x1in, y1in, z1in, x2in, y2in, z2in,\n        approx_x1cell_size, approx_y1cell_size, approx_z1cell_size,\n        approx_x2cell_size, approx_y2cell_size, approx_z2cell_size,\n        search_xlength, search_ylength, search_zlength, xperiod, yperiod, zperiod, PBCs)\n\n    # Create a function object that has a single argument, for parallelization purposes\n    engine = partial(velocity_marked_npairs_xy_z_engine, double_mesh,\n        x1in, y1in, z1in, x2in, y2in, z2in,\n        weights1, weights2, weight_func_id, rp_bins, pi_bins)\n\n    # Calculate the cell1 indices that will be looped over by the engine\n    num_threads, cell1_tuples = _cell1_parallelization_indices(\n        double_mesh.mesh1.ncells, num_threads)\n\n    if num_threads > 1:\n        pool = multiprocessing.Pool(num_threads)\n        result = np.array(pool.map(engine, cell1_tuples))\n        counts1, counts2, counts3 = result[:, 0], result[:, 1], result[:, 2]\n        counts1 = np.sum(counts1, axis=0)\n        counts2 = np.sum(counts2, axis=0)\n        counts3 = np.sum(counts3, axis=0)\n        pool.close()\n    else:\n        counts1, counts2, counts3 = np.array(engine(cell1_tuples[0]))\n\n    return counts1, counts2, counts3\n", "meta": {"hexsha": "d4abc03757260dd30d75b0f90f15a89c9eca5966", "size": 8874, "ext": "py", "lang": "Python", "max_stars_repo_path": "halotools/mock_observables/pairwise_velocities/velocity_marked_npairs_xy_z.py", "max_stars_repo_name": "pllim/halotools", "max_stars_repo_head_hexsha": "6499cff09e7e0f169e4f425ee265403f6be816e8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 83, "max_stars_repo_stars_event_min_datetime": "2015-01-15T14:54:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T11:28:02.000Z", "max_issues_repo_path": "halotools/mock_observables/pairwise_velocities/velocity_marked_npairs_xy_z.py", "max_issues_repo_name": "pllim/halotools", "max_issues_repo_head_hexsha": "6499cff09e7e0f169e4f425ee265403f6be816e8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 579, "max_issues_repo_issues_event_min_datetime": "2015-01-14T15:57:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-13T18:58:44.000Z", "max_forks_repo_path": "halotools/mock_observables/pairwise_velocities/velocity_marked_npairs_xy_z.py", "max_forks_repo_name": "pllim/halotools", "max_forks_repo_head_hexsha": "6499cff09e7e0f169e4f425ee265403f6be816e8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 70, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:15:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T18:18:31.000Z", "avg_line_length": 45.7422680412, "max_line_length": 144, "alphanum_fraction": 0.7110660356, "include": true, "reason": "import numpy", "num_tokens": 2245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.19394755383044382}}
{"text": "from dataclasses import dataclass\nfrom typing import Any, Dict, List, Optional, Tuple, Union, cast\n\nimport numpy as np\nimport tensorflow as tf\nfrom srl.base.rl.algorithms.continuous_action import ContinuousActionConfig, ContinuousActionWorker\nimport tensorflow.keras as keras\nimport tensorflow.keras.layers as kl\nfrom srl.base.define import RLObservationType\nfrom srl.base.env.base import EnvRun\nfrom srl.base.rl.algorithms.continuous_action import ContinuousActionConfig, ContinuousActionWorker\nfrom srl.base.rl.base import RLParameter, RLTrainer\nfrom srl.base.rl.registration import register\nfrom srl.base.rl.remote_memory import ExperienceReplayBuffer\nfrom srl.rl.functions.common_tf import compute_logprob_sgp\nfrom srl.rl.functions.model import ImageLayerType, create_input_layers_one_sequence\n\n\"\"\"\nDDPG\n    Replay buffer       : o\n    Target Network(soft): o\n    Target Network(hard): o\n    Add action noise    : x\nTD3\n    Clipped Double Q learning : o\n    Target Policy Smoothing   : x\n    Delayed Policy Update     : x\nSAC\n    Squashed Gaussian Policy: o\n\"\"\"\n\n\n# ------------------------------------------------------\n# config\n# ------------------------------------------------------\n@dataclass\nclass Config(ContinuousActionConfig):\n\n    # model\n    policy_hidden_layer_sizes: Tuple[int, ...] = (64, 64, 64)\n    q_hidden_layer_sizes: Tuple[int, ...] = (64, 64, 64)\n    activation: str = \"relu\"\n    image_layer_type: ImageLayerType = ImageLayerType.DQN\n\n    gamma: float = 0.9  # 割引率\n    lr: float = 0.005  # 学習率\n    soft_target_update_tau: float = 0.02\n    hard_target_update_interval: int = 100\n\n    batch_size: int = 32\n    capacity: int = 10_000\n    memory_warmup_size: int = 500\n\n    def __post_init__(self):\n        super().__init__()\n\n    @property\n    def observation_type(self) -> RLObservationType:\n        return RLObservationType.CONTINUOUS\n\n    @staticmethod\n    def getName() -> str:\n        return \"SAC\"\n\n    def assert_params(self) -> None:\n        super().assert_params()\n        assert self.memory_warmup_size < self.capacity\n        assert self.batch_size < self.memory_warmup_size\n\n\nregister(\n    Config,\n    __name__ + \":RemoteMemory\",\n    __name__ + \":Parameter\",\n    __name__ + \":Trainer\",\n    __name__ + \":Worker\",\n)\n\n\n# ------------------------------------------------------\n# RemoteMemory\n# ------------------------------------------------------\nclass RemoteMemory(ExperienceReplayBuffer):\n    def __init__(self, *args):\n        super().__init__(*args)\n        self.config = cast(Config, self.config)\n\n        self.init(self.config.capacity)\n\n\n# ------------------------------------------------------\n# network\n# ------------------------------------------------------\nclass _PolicyModel(keras.Model):\n    def __init__(self, config: Config):\n        super().__init__()\n\n        in_state, c = create_input_layers_one_sequence(\n            config.observation_shape,\n            config.env_observation_type,\n            config.image_layer_type,\n        )\n\n        # --- hidden layer\n        for h in config.policy_hidden_layer_sizes:\n            c = kl.Dense(h, activation=config.activation, kernel_initializer=\"he_normal\")(c)\n        c = kl.LayerNormalization()(c)  # 勾配爆発抑制用?\n\n        # --- out layer\n        pi_mean = kl.Dense(\n            config.action_num,\n            activation=\"linear\",\n            kernel_initializer=\"truncated_normal\",\n            bias_initializer=\"truncated_normal\",\n        )(c)\n        pi_stddev = kl.Dense(\n            config.action_num,\n            activation=\"linear\",\n            kernel_initializer=\"truncated_normal\",\n            bias_initializer=\"truncated_normal\",\n        )(c)\n        self.model = keras.Model(in_state, [pi_mean, pi_stddev])\n\n        # 重みを初期化\n        dummy_state = np.zeros(shape=(1,) + config.observation_shape, dtype=np.float32)\n        action, mean, stddev, action_org = self(dummy_state)\n        assert mean.shape == (1, config.action_num)\n        assert stddev.shape == (1, config.action_num)\n\n    @tf.function\n    def call(self, state):\n        mean, stddev = self.model(state)\n\n        # σ > 0\n        stddev = tf.exp(stddev)\n\n        # Reparameterization trick\n        normal_random = tf.random.normal(mean.shape, mean=0.0, stddev=1.0)\n        action_org = mean + stddev * normal_random\n\n        # Squashed Gaussian Policy\n        action = tf.tanh(action_org)\n\n        return action, mean, stddev, action_org\n\n\nclass _DualQNetwork(keras.Model):\n    def __init__(self, config: Config):\n        super().__init__()\n\n        in_state, c = create_input_layers_one_sequence(\n            config.observation_shape,\n            config.env_observation_type,\n            config.image_layer_type,\n        )\n        in_action = kl.Input(shape=(config.action_num,))\n        c = kl.Concatenate()([c, in_action])\n\n        for h in config.q_hidden_layer_sizes:\n            c = kl.Dense(h, activation=config.activation, kernel_initializer=\"he_normal\")(c)\n        c = kl.LayerNormalization()(c)  # 勾配爆発抑制用?\n\n        # q1\n        q1 = kl.Dense(\n            1, activation=\"linear\", kernel_initializer=\"truncated_normal\", bias_initializer=\"truncated_normal\"\n        )(c)\n\n        # q2\n        q2 = kl.Dense(\n            1, activation=\"linear\", kernel_initializer=\"truncated_normal\", bias_initializer=\"truncated_normal\"\n        )(c)\n\n        # out layer\n        self.model = keras.Model([in_state, in_action], [q1, q2])\n\n        # 重みを初期化\n        dummy_state = np.zeros(shape=(1,) + config.observation_shape, dtype=np.float32)\n        dummy_action = np.zeros(shape=(1, config.action_num), dtype=np.float32)\n        _q1, _q2 = self(dummy_state, dummy_action)\n        assert _q1.shape == (1, 1)\n        assert _q2.shape == (1, 1)\n\n    def call(self, state, action):\n        return self.model([state, action])\n\n\n# ------------------------------------------------------\n# Parameter\n# ------------------------------------------------------\nclass Parameter(RLParameter):\n    def __init__(self, *args):\n        super().__init__(*args)\n        self.config = cast(Config, self.config)\n\n        self.policy = _PolicyModel(self.config)\n        self.q_online = _DualQNetwork(self.config)\n        self.q_target = _DualQNetwork(self.config)\n\n    def restore(self, data: Any) -> None:\n        self.policy.set_weights(data[0])\n        self.q_online.set_weights(data[1])\n        self.q_target.set_weights(data[1])\n\n    def backup(self) -> Any:\n        return [\n            self.policy.get_weights(),\n            self.q_online.get_weights(),\n        ]\n\n    def summary(self):\n        self.policy.model.summary()\n        self.q_online.model.summary()\n\n\n# ------------------------------------------------------\n# Trainer\n# ------------------------------------------------------\nclass Trainer(RLTrainer):\n    def __init__(self, *args):\n        super().__init__(*args)\n        self.config = cast(Config, self.config)\n        self.parameter = cast(Parameter, self.parameter)\n        self.remote_memory = cast(RemoteMemory, self.remote_memory)\n\n        self.train_count = 0\n\n        self.q_optimizer = keras.optimizers.Adam(learning_rate=self.config.lr)\n        self.policy_optimizer = keras.optimizers.Adam(learning_rate=self.config.lr)\n        self.alpha_optimizer = keras.optimizers.Adam(learning_rate=self.config.lr)\n\n        # エントロピーαの目標値、-1×アクション数が良いらしい\n        self.target_entropy = -1 * self.config.action_num\n\n        # エントロピーα自動調整用\n        self.log_alpha = tf.Variable(0.5, dtype=tf.float32)\n\n    def get_train_count(self):\n        return self.train_count\n\n    def train(self):\n        if self.remote_memory.length() < self.config.memory_warmup_size:\n            return {}\n        batchs = self.remote_memory.sample(self.config.batch_size)\n\n        states = []\n        actions = []\n        n_states = []\n        rewards = []\n        dones = []\n        for b in batchs:\n            states.append(b[\"state\"])\n            actions.append(b[\"action\"])\n            n_states.append(b[\"next_state\"])\n            rewards.append(b[\"reward\"])\n            dones.append(b[\"done\"])\n        states = np.asarray(states)\n        n_states = np.asarray(n_states)\n        actions = np.asarray(actions)\n        dones = np.asarray(dones).reshape((-1, 1))\n        rewards = np.asarray(rewards).reshape((-1, 1))\n\n        # 方策エントロピーの反映率αを計算\n        alpha = tf.math.exp(self.log_alpha)\n\n        # ポリシーより次の状態のアクションを取得\n        n_actions, n_means, n_stddevs, n_action_orgs = self.parameter.policy(n_states)\n        # 次の状態のアクションのlogpiを取得(Squashed Gaussian Policy時)\n        n_logpi = compute_logprob_sgp(n_means, n_stddevs, n_action_orgs)\n\n        # 2つのQ値から小さいほうを採用(Clipped Double Q learning)して、\n        # Q値を計算 : reward if done else (reward + gamma * n_qval) - (alpha * H)\n        n_q1, n_q2 = self.parameter.q_target(n_states, n_actions)\n        q_vals = rewards + (1 - dones) * self.config.gamma * tf.minimum(n_q1, n_q2) - (alpha * n_logpi)\n\n        # --- Qモデルの学習\n        with tf.GradientTape() as tape:\n            q1, q2 = self.parameter.q_online(states, actions)\n            loss1 = tf.reduce_mean(tf.square(q_vals - q1))\n            loss2 = tf.reduce_mean(tf.square(q_vals - q2))\n            q_loss = (loss1 + loss2) / 2\n\n        grads = tape.gradient(q_loss, self.parameter.q_online.trainable_variables)\n        self.q_optimizer.apply_gradients(zip(grads, self.parameter.q_online.trainable_variables))\n\n        # --- ポリシーの学習\n        with tf.GradientTape() as tape:\n            # アクションを出力\n            selected_actions, means, stddevs, action_orgs = self.parameter.policy(states)\n\n            # logπ(a|s) (Squashed Gaussian Policy)\n            logpi = compute_logprob_sgp(means, stddevs, action_orgs)\n\n            # Q値を出力、小さいほうを使う\n            q1, q2 = self.parameter.q_online(states, selected_actions)\n            q_min = tf.minimum(q1, q2)\n\n            # alphaは定数扱いなので勾配が流れないようにする\n            policy_loss = q_min - (tf.stop_gradient(alpha) * logpi)\n\n            policy_loss = -tf.reduce_mean(policy_loss)  # 最大化\n\n        grads = tape.gradient(policy_loss, self.parameter.policy.trainable_variables)\n        self.policy_optimizer.apply_gradients(zip(grads, self.parameter.policy.trainable_variables))\n\n        # --- 方策エントロピーαの自動調整\n        _, means, stddevs, action_orgs = self.parameter.policy(states)\n        logpi = compute_logprob_sgp(means, stddevs, action_orgs)\n\n        with tf.GradientTape() as tape:\n            entropy_diff = -logpi - self.target_entropy\n            log_alpha_loss = tf.reduce_mean(tf.exp(self.log_alpha) * entropy_diff)\n\n        grad = tape.gradient(log_alpha_loss, self.log_alpha)\n        self.alpha_optimizer.apply_gradients([(grad, self.log_alpha)])\n\n        # --- soft target update\n        self.parameter.q_target.set_weights(\n            (1 - self.config.soft_target_update_tau) * np.array(self.parameter.q_target.get_weights(), dtype=object)\n            + (self.config.soft_target_update_tau) * np.array(self.parameter.q_online.get_weights(), dtype=object)\n        )\n\n        # --- hard target sync\n        if self.train_count % self.config.hard_target_update_interval == 0:\n            self.parameter.q_target.set_weights(self.parameter.q_online.get_weights())\n\n        self.train_count += 1\n        return {\n            \"q_loss\": q_loss.numpy(),\n            \"policy_loss\": policy_loss.numpy(),\n            \"alpha_loss\": log_alpha_loss.numpy(),\n        }\n\n\n# ------------------------------------------------------\n# Worker\n# ------------------------------------------------------\nclass Worker(ContinuousActionWorker):\n    def __init__(self, *args):\n        super().__init__(*args)\n        self.config = cast(Config, self.config)\n        self.parameter = cast(Parameter, self.parameter)\n        self.remote_memory = cast(RemoteMemory, self.remote_memory)\n\n    def call_on_reset(self, state: np.ndarray) -> None:\n        self.state = state\n\n    def call_policy(self, state: np.ndarray) -> List[float]:\n        self.state = state\n        action, mean, _, _ = self.parameter.policy(state.reshape(1, -1))\n\n        if self.training:\n            action = action.numpy()[0]\n        else:\n            # テスト時は平均を使う\n            action = mean.numpy()[0]\n\n        # Squashed Gaussian Policy (-1, 1) -> (action range)\n        action = (action + 1) / 2\n        action = self.config.action_low + action * (self.config.action_high - self.config.action_low)\n\n        self.action = action\n        return self.action\n\n    def call_on_step(\n        self,\n        next_state: np.ndarray,\n        reward: float,\n        done: bool,\n    ) -> Dict[str, Union[float, int]]:\n        if not self.training:\n            return {}\n\n        batch = {\n            \"state\": self.state,\n            \"action\": self.action,\n            \"next_state\": next_state,\n            \"reward\": reward,\n            \"done\": done,\n        }\n        self.remote_memory.add(batch)\n\n        return {}\n\n    def call_render(self, env: EnvRun) -> None:\n        state = self.state.reshape(1, -1)\n        action = np.asarray([self.action])\n        _, mean, stddev, _ = self.parameter.policy(state)\n        mean = mean.numpy()[0][0]\n        stddev = stddev.numpy()[0][0]\n        q1, q2 = self.parameter.q_online(state, action)\n        q1 = q1.numpy()[0][0]\n        q2 = q2.numpy()[0][0]\n\n        print(f\"mean {mean:.5f}, stddev {stddev:.5f}\")\n        print(f\"q1   {q1:.5f}, q2    {q2:.5f}\")\n", "meta": {"hexsha": "f3b5873d33467a61371014286d1d2a7053d01514", "size": 13295, "ext": "py", "lang": "Python", "max_stars_repo_path": "srl/rl/sac.py", "max_stars_repo_name": "pocokhc/simple_rl", "max_stars_repo_head_hexsha": "765f12f392f87e6897027905d74f1bced6a2b7bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-01T09:16:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T09:16:57.000Z", "max_issues_repo_path": "srl/rl/sac.py", "max_issues_repo_name": "pocokhc/simple_rl", "max_issues_repo_head_hexsha": "765f12f392f87e6897027905d74f1bced6a2b7bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "srl/rl/sac.py", "max_forks_repo_name": "pocokhc/simple_rl", "max_forks_repo_head_hexsha": "765f12f392f87e6897027905d74f1bced6a2b7bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5732323232, "max_line_length": 116, "alphanum_fraction": 0.5957878902, "include": true, "reason": "import numpy", "num_tokens": 3222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.3380771174808128, "lm_q1q2_score": 0.19394754728087965}}
{"text": "import sys, re, glob\nimport numpy as np\n\nfrom cctk import GaussianFile, Molecule\nfrom cctk import parse_gaussian as parse\n\nfilenames = sys.argv[1]\ninfo = []\n\nfor filename in sorted(glob.glob(filenames, recursive=True)):\n    try:\n        output_file, lines = GaussianFile.read_file(filename, return_lines=True)\n    except:\n        continue\n\n    success = \"NO\"\n    if output_file.success:\n        success = output_file.success\n    else:\n        continue\n\n    energy = output_file.energies[-1]\n    iters = len(output_file.energies)\n    mol = output_file.get_molecule()\n\n    cation_anion_dist = 0\n    mul_q = 0\n    hir_q = 0\n    if 29 in mol.atomic_numbers:\n        mul_q = float(parse.find_parameter(lines, \"    52  Cu\", 4, 2)[-1])\n        hir_q = float(parse.find_parameter(lines, \"    52  Cu\", 8, 2)[-1])\n\n        if 16 in mol.atomic_numbers:\n            cation_anion_dist = mol.get_distance(52, 54)\n        elif 51 in mol.atomic_numbers:\n            cation_anion_dist = mol.get_distance(52, 53)\n\n    imaginaries = \"--\"\n    try:\n        if output_file.num_imaginaries() > 0:\n            if output_file.num_imaginaries() > 1:\n                imaginaries = \", \".join(output_file.imaginaries())\n            else:\n                imaginaries = output_file.imaginaries()[0]\n    except:\n        #### Will raise ValueError if job is not of type \"FREQ\"\n        pass\n\n    info.append([filename, energy, energy * 627.509, iters, mul_q, hir_q, success, imaginaries, cation_anion_dist])\n\n\nif len(info) > 0:\n    min_energy = np.min([x[2] for x in info])\n    def adjust_energy(row):\n        if row[2] < 0:\n            row[2] = row[2] - min_energy\n        return row\n\n    info = list(map(adjust_energy, info))\n\n    print(\"{0},{1},{2},{3},{4},{5},{6},{7},{8}\".format(\n        \"File\", \"Energy (Hartree)\", \"Rel Energy (kcal)\", \"Iterations\", \"Mulliken Q\", \"Hirshfeld Q\", \"Success?\", \"Imaginaries?\",\"X-Cu Distance\"\n    ))\n\n    for row in info:\n        print(\"{0},{1:.4f},{2:.2f},{3},{4:.4f},{5:.4f},{6},{7:},{8:.2f}\".format(*row))\n\n", "meta": {"hexsha": "c8fc4913a180822d93c04f85fb98514c8e5b3a25", "size": 2011, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorial/tutorial_07/analyze.py", "max_stars_repo_name": "ekwan/cctk", "max_stars_repo_head_hexsha": "85cb8d0b714a80e8e353987dc24006695f1d0532", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-01-16T15:26:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T23:12:00.000Z", "max_issues_repo_path": "tutorial/tutorial_07/analyze.py", "max_issues_repo_name": "ekwan/cctk", "max_issues_repo_head_hexsha": "85cb8d0b714a80e8e353987dc24006695f1d0532", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-05-27T21:04:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-26T20:49:53.000Z", "max_forks_repo_path": "tutorial/tutorial_07/analyze.py", "max_forks_repo_name": "ekwan/cctk", "max_forks_repo_head_hexsha": "85cb8d0b714a80e8e353987dc24006695f1d0532", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-24T18:44:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-05T20:35:51.000Z", "avg_line_length": 29.5735294118, "max_line_length": 142, "alphanum_fraction": 0.5967180507, "include": true, "reason": "import numpy", "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.1939475461784997}}
{"text": "__doc__ = \"\"\"Symplectic time steppers and concepts for integrating the kinematic and dynamic equations of rod-like objects.  \"\"\"\nimport numpy as np\n\nfrom elastica.timestepper._stepper_interface import (\n    _TimeStepper,\n    _LinearExponentialIntegratorMixin,\n)\n\n\"\"\"\nDeveloper Note\n--------------\n\nFor the reasons why we define Mixin classes here, the developer\nis referred to the same section on `explicit_steppers.py`.\n\"\"\"\n\n\nclass _SystemInstanceStepperMixin:\n    def do_step(self, System, time: np.float64, dt: np.float64):\n        for (\n            kin_prefactor,\n            kin_step,\n            dyn_prefactor,\n            dyn_step,\n        ) in self._steps_and_prefactors[:-1]:\n            prefac = kin_prefactor(self, dt)\n            time = kin_step(self, System, time, prefac)\n            prefac = dyn_prefactor(self, dt)\n            time = dyn_step(self, System, time, prefac)\n\n        # Peel the last kinematic step and prefactor alone\n        last_kin_prefactor = self._steps_and_prefactors[-1][0]\n        last_kin_step = self._steps_and_prefactors[-1][1]\n\n        prefac = last_kin_prefactor(self, dt)\n        time = last_kin_step(self, System, time, prefac)\n        return time\n\n\nclass _SystemCollectionStepperMixin:\n    \"\"\"\n    Symplectic stepper mixin collection class\n    \"\"\"\n\n    def do_step(self, SystemCollection, time: np.float64, dt: np.float64):\n        \"\"\"\n        Function for doing symplectic stepper over the user defined rods (system).\n\n        Parameters\n        ----------\n        SystemCollection: rod object\n        time: float\n        dt: float\n\n        Returns\n        -------\n\n        \"\"\"\n        for (\n            kin_prefactor,\n            kin_step,\n            dyn_prefactor,\n            dyn_step,\n        ) in self._steps_and_prefactors[:-1]:\n            prefac = kin_prefactor(self, dt)\n            for system in SystemCollection[:-1]:\n                _ = kin_step(self, system, time, prefac)\n            time = kin_step(self, SystemCollection[-1], time, prefac)\n\n            # TODO: remove below lines and try to find a better call option to compute internal forces and torques\n            # We need internal forces and torques because they are used by interaction module.\n            update_internal_forces_torques = self._update_internal_forces_torques[\n                0\n            ]  # here 0 because you have one item in list\n            for system in SystemCollection[:-1]:\n                _ = update_internal_forces_torques(self, system, time)\n            time = update_internal_forces_torques(self, SystemCollection[-1], time)\n\n            # BoCos, External forces, controls etc.\n            SystemCollection.synchronize(time)\n            # TODO: remove below line, it should be some other function synchronizeBC\n            SystemCollection.synchronizeBC(time)\n            prefac = dyn_prefactor(self, dt)\n            for system in SystemCollection[:-1]:\n                _ = dyn_step(self, system, time, prefac)\n            time = dyn_step(self, SystemCollection[-1], time, prefac)\n\n            # TODO: remove below line, it should be some other function synchronizeBC\n            SystemCollection.synchronizeBC(time)\n\n        # Peel the last kinematic step and prefactor alone\n        last_kin_prefactor = self._steps_and_prefactors[-1][0]\n        last_kin_step = self._steps_and_prefactors[-1][1]\n\n        prefac = last_kin_prefactor(self, dt)\n        for system in SystemCollection[:-1]:\n            _ = last_kin_step(self, system, time, prefac)\n        time = last_kin_step(self, SystemCollection[-1], time, prefac)\n\n        # Call back function, will call the user defined call back functions and store data\n        SystemCollection.callBack(time, int(time / dt))\n\n        return time\n\n\nclass SymplecticStepper(_TimeStepper):\n    \"\"\"\n    Symplectic stepper constructor.\n\n    Attributes\n    ----------\n    _steps: list\n        List containing methods of symplectic time stepper.\n    _prefactors: list\n        List containing prefactors of symplectic time stepper.\n    _update_internal_forces_torques: list\n        List containing methods for computing internal forces and torques.\n    \"\"\"\n\n    def __init__(self, cls=None):\n        super(SymplecticStepper, self).__init__()\n        take_methods_from = self if cls is None else cls()\n        # Let the total number of steps for the Symplectic method\n        # be (2*n + 1) (for time-symmetry). What we do is collect\n        # the first n + 1 entries down in _steps and _prefac below, and then\n        # reverse and append it to itself.\n        self._steps = [\n            v\n            for (k, v) in take_methods_from.__class__.__dict__.items()\n            if k.endswith(\"step\")\n        ]\n        # Prefac here is necessary because the linear-exponential integrator\n        # needs only the prefactor and not the dt.\n        self._prefactors = [\n            v\n            for (k, v) in take_methods_from.__class__.__dict__.items()\n            if k.endswith(\"prefactor\")\n        ]\n\n        # We are getting function named as _update_internal_forces_torques from dictionary,\n        # it turns a list.\n        self._update_internal_forces_torques = [\n            v\n            for (k, v) in take_methods_from.__class__.__dict__.items()\n            if k.endswith(\"forces_torques\")\n        ]\n\n        def mirror(in_list):\n            \"\"\" Mirrors an input list ignoring the last element\n            If steps = [A, B, C]\n            then this call makes it [A, B, C, B, A]\n\n            Parameters\n            ----------\n            in_list : input list to be mirrored, modified in-place\n\n            Returns\n            -------\n\n            \"\"\"\n            #  syntax is very ugly\n            in_list.extend(in_list[-2::-1])\n\n        mirror(self._steps)\n        mirror(self._prefactors)\n\n        assert len(self._steps) == len(\n            self._prefactors\n        ), \"Size mismatch in the number of steps and prefactors provided for a Symplectic Stepper!\"\n\n        self._kinematic_steps = self._steps[::2]\n        self._dynamic_steps = self._steps[1::2]\n        self._kinematic_prefactors = self._prefactors[::2]\n        self._dynamic_prefactors = self._prefactors[1::2]\n\n        # Avoid this check for MockClasses\n        if len(self._kinematic_steps) > 0:\n            assert (\n                len(self._kinematic_steps) == len(self._dynamic_steps) + 1\n            ), \"Size mismatch in the number of kinematic and dynamic steps provided for a Symplectic Stepper!\"\n            assert (\n                len(self._kinematic_prefactors) == len(self._dynamic_prefactors) + 1\n            ), \"Size mismatch in the number of kinematic and dynamic prefactors provided for a Symplectic Stepper!\"\n\n        from itertools import zip_longest\n\n        self._steps_and_prefactors = tuple(\n            zip_longest(\n                self._kinematic_prefactors,\n                self._kinematic_steps,\n                self._dynamic_prefactors,\n                self._dynamic_steps,\n            )\n        )\n\n    @property\n    def n_stages(self):\n        return len(self._steps_and_prefactors)\n\n\nclass PositionVerlet(SymplecticStepper):\n    \"\"\"\n    Position Verlet symplectic time stepper class, which\n    includes methods for second-order position Verlet.\n    \"\"\"\n\n    def __init__(self):\n        super(PositionVerlet, self).__init__()\n\n    def _first_kinematic_prefactor(self, dt):\n        return 0.5 * dt\n\n    def _first_kinematic_step(self, System, time: np.float64, prefac: np.float64):\n        System.kinematic_states += prefac * System.kinematic_rates(time, prefac)\n        return time + prefac\n\n    def _first_dynamic_prefactor(self, dt):\n        return dt\n\n    def _first_dynamic_step(self, System, time: np.float64, prefac: np.float64):\n        System.dynamic_states += prefac * System.dynamic_rates(\n            time, prefac\n        )  # TODO : Why should we pass dt into System again?\n        return time\n\n    # TODO: find a better place for this or a better call option. We need to compute internal forces and torques before external because interaction uses it!\n    def _update_internal_forces_torques(self, System, time: np.float64):\n        System.update_internal_forces_and_torques(time)\n        return time\n\n    # Note : we don't need the second half of the calls as it simply forwards\n    # to its equivalent first half. This is taken care in the base class\n\n    # def _second_kinematic_step(self, System, time: np.float64, dt: np.float64):\n    #     return self._first_kinematic_step(System, time, dt)\n\n\nclass PEFRL(SymplecticStepper):\n    \"\"\"\n    Position Extended Forest-Ruth Like Algorithm of\n    I.M. Omelyan, I.M. Mryglod, and R. Folk, Computer Physics Communications 146, 188 (2002),\n    http://arxiv.org/abs/cond-mat/0110585\n    \"\"\"\n\n    # xi and chi are confusing, but be careful!\n    ξ = np.float64(0.1786178958448091e0)  # ξ\n    λ = -np.float64(0.2123418310626054e0)  # λ\n    χ = -np.float64(0.6626458266981849e-1)  # χ\n\n    # Pre-calculate other coefficients\n    lambda_dash_coeff = 0.5 * (1.0 - 2.0 * λ)\n    xi_chi_dash_coeff = 1.0 - 2.0 * (ξ + χ)\n\n    def __init__(self):\n        super(PEFRL, self).__init__()\n\n    def _first_kinematic_prefactor(self, dt):\n        return self.ξ * dt\n\n    def _first_kinematic_step(self, System, time: np.float64, prefac: np.float64):\n        System.kinematic_states += prefac * System.kinematic_rates(time, prefac)\n        return time + prefac\n\n    def _first_dynamic_prefactor(self, dt):\n        return self.lambda_dash_coeff * dt\n\n    def _first_dynamic_step(self, System, time: np.float64, prefac: np.float64):\n        System.dynamic_states += prefac * System.dynamic_rates(time, prefac)\n        return time\n\n    def _second_kinematic_prefactor(self, dt):\n        return self.χ * dt\n\n    def _second_kinematic_step(self, System, time: np.float64, prefac: np.float64):\n        System.kinematic_states += prefac * System.kinematic_rates(time, prefac)\n        return time + prefac\n\n    def _second_dynamic_prefactor(self, dt):\n        return self.λ * dt\n\n    def _second_dynamic_step(self, System, time: np.float64, prefac: np.float64):\n        System.dynamic_states += prefac * System.dynamic_rates(time, prefac)\n        return time\n\n    def _third_kinematic_prefactor(self, dt):\n        return self.xi_chi_dash_coeff * dt\n\n    def _third_kinematic_step(self, System, time: np.float64, prefac: np.float64):\n        # Need to fill in\n        System.kinematic_states += prefac * System.kinematic_rates(time, prefac)\n        return time + prefac\n\n    # TODO: find a better place for this or a better call option. We need to compute internal forces and torques before external because interaction uses it!\n    def _update_internal_forces_torques(self, System, time: np.float64):\n        System.update_internal_forces_and_torques(time)\n        return time\n\n    # Note : we don't need the second half of the calls as it simply forwards\n    # to its equivalent first half. This is taken care in the base class\n\n    # def _third_dynamic_step(self, System, time: np.float64, dt: np.float64):\n    #     return self._second_dynamic_step(System, time, dt)\n    #\n    # def _fourth_kinematic_step(self, System, time: np.float64, dt: np.float64):\n    #     return self._second_kinematic_step(System, time, dt)\n    #\n    # def _fourth_dynamic_step(self, System, time: np.float64, dt: np.float64):\n    #     return self._first_dynamic_step(System, time, dt)\n    #\n    # def _fifth_kinematic_step(self, System, time: np.float64, dt: np.float64):\n    #     return self._first_kinematic_step(System, time, dt)\n    #     # return time + dt # To avoid numerical precision errors\n\n\nclass SymplecticLinearExponentialIntegrator(\n    _LinearExponentialIntegratorMixin, SymplecticStepper\n):\n    def __init__(self):\n        _LinearExponentialIntegratorMixin.__init__(self)\n        SymplecticStepper.__init__(self, _LinearExponentialIntegratorMixin)\n", "meta": {"hexsha": "af9ecce9bbe8a515b479155aece68e1fba9ba34b", "size": 11865, "ext": "py", "lang": "Python", "max_stars_repo_path": "elastica/timestepper/symplectic_steppers.py", "max_stars_repo_name": "merozlab/PyElastica", "max_stars_repo_head_hexsha": "1d8c354a25846f63073809e3a809f27a150c3b9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "elastica/timestepper/symplectic_steppers.py", "max_issues_repo_name": "merozlab/PyElastica", "max_issues_repo_head_hexsha": "1d8c354a25846f63073809e3a809f27a150c3b9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "elastica/timestepper/symplectic_steppers.py", "max_forks_repo_name": "merozlab/PyElastica", "max_forks_repo_head_hexsha": "1d8c354a25846f63073809e3a809f27a150c3b9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-21T15:42:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-21T15:42:58.000Z", "avg_line_length": 36.9626168224, "max_line_length": 157, "alphanum_fraction": 0.6475347661, "include": true, "reason": "import numpy", "num_tokens": 2889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.1939475461784997}}
{"text": "\"\"\" @package forcebalance.lipid Matching of lipid bulk properties.  Under development.\n\nauthor Lee-Ping Wang\n@date 04/2012\n\"\"\"\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom builtins import str\nfrom builtins import zip\nfrom builtins import map\nfrom builtins import range\nimport abc\nimport os\nimport shutil\nfrom forcebalance.finite_difference import *\nfrom forcebalance.nifty import *\nfrom forcebalance.nifty import _exec\nfrom forcebalance.target import Target\nimport numpy as np\nfrom forcebalance.molecule import Molecule\nfrom re import match, sub\nimport subprocess\nfrom subprocess import PIPE\ntry:\n    from lxml import etree\nexcept: pass\nfrom pymbar import pymbar\nimport itertools\nfrom collections import defaultdict, namedtuple, OrderedDict\nimport csv\nimport copy\n\nfrom forcebalance.output import getLogger\nlogger = getLogger(__name__)\n\ndef weight_info(W, PT, N_k, verbose=True):\n    C = []\n    N = 0\n    W += 1.0e-300\n    I = np.exp(-1*np.sum((W*np.log(W))))\n    for ns in N_k:\n        C.append(sum(W[N:N+ns]))\n        N += ns\n    C = np.array(C)\n    if verbose:\n        logger.info(\"MBAR Results for Phase Point %s, Box, Contributions:\\n\" % str(PT))\n        logger.info(str(C) + '\\n')\n        logger.info(\"InfoContent: % .2f snapshots (%.2f %%)\\n\" % (I, 100*I/len(W)))\n    return C\n\n# NPT_Trajectory = namedtuple('NPT_Trajectory', ['fnm', 'Rhos', 'pVs', 'Energies', 'Grads', 'mEnergies', 'mGrads', 'Rho_errs', 'Hvap_errs'])\n\nclass Lipid(Target):\n    \n    \"\"\" Subclass of Target for lipid property matching.\"\"\"\n\n    def __init__(self,options,tgt_opts,forcefield):\n        # Initialize base class\n        super(Lipid,self).__init__(options,tgt_opts,forcefield)\n        # Weight of the density\n        self.set_option(tgt_opts,'w_rho',forceprint=True)\n        # Weight of the thermal expansion coefficient\n        self.set_option(tgt_opts,'w_alpha',forceprint=True)\n        # Weight of the isothermal compressibility\n        self.set_option(tgt_opts,'w_kappa',forceprint=True)\n        # Weight of the isobaric heat capacity\n        self.set_option(tgt_opts,'w_cp',forceprint=True)\n        # Weight of the dielectric constant\n        self.set_option(tgt_opts,'w_eps0',forceprint=True)\n        # Weight of the area per lipid\n        self.set_option(tgt_opts,'w_al',forceprint=True)\n        # Weight of the bilayer isothermal compressibility\n        self.set_option(tgt_opts,'w_lkappa',forceprint=True)\n        # Weight of the deuterium order parameter\n        self.set_option(tgt_opts,'w_scd',forceprint=True)\n        # Normalize the property contributions to the objective function\n        self.set_option(tgt_opts,'w_normalize',forceprint=True)\n        # Optionally pause on the zeroth step\n        self.set_option(tgt_opts,'manual')\n        # Number of time steps in the lipid \"equilibration\" run\n        self.set_option(tgt_opts,'lipid_eq_steps',forceprint=True)\n        # Number of time steps in the lipid \"production\" run\n        self.set_option(tgt_opts,'lipid_md_steps',forceprint=True)\n        # Number of time steps in the gas \"equilibration\" run\n        self.set_option(tgt_opts,'gas_eq_steps',forceprint=False)\n        # Number of time steps in the gas \"production\" run\n        self.set_option(tgt_opts,'gas_md_steps',forceprint=False)\n        # Cutoff for nonbonded interactions in the liquid\n        if tgt_opts['nonbonded_cutoff'] is not None:\n            self.set_option(tgt_opts,'nonbonded_cutoff')\n        # Cutoff for vdW interactions if different from other nonbonded interactions\n        if tgt_opts['vdw_cutoff'] is not None:\n            self.set_option(tgt_opts,'vdw_cutoff')\n        # Time step length (in fs) for the lipid production run\n        self.set_option(tgt_opts,'lipid_timestep',forceprint=True)\n        # Time interval (in ps) for writing coordinates\n        self.set_option(tgt_opts,'lipid_interval',forceprint=True)\n        # Time step length (in fs) for the gas production run\n        self.set_option(tgt_opts,'gas_timestep',forceprint=True)\n        # Time interval (in ps) for writing coordinates\n        self.set_option(tgt_opts,'gas_interval',forceprint=True)\n        # Minimize the energy prior to running any dynamics\n        self.set_option(tgt_opts,'minimize_energy',forceprint=True)\n        # Isolated dipole (debye) for analytic self-polarization correction.\n        self.set_option(tgt_opts,'self_pol_mu0',forceprint=True)\n        # Molecular polarizability (ang**3) for analytic self-polarization correction.\n        self.set_option(tgt_opts,'self_pol_alpha',forceprint=True)\n        # Set up the simulation object for self-polarization correction.\n        self.do_self_pol = (self.self_pol_mu0 > 0.0 and self.self_pol_alpha > 0.0)\n        # Enable anisotropic periodic box\n        self.set_option(tgt_opts,'anisotropic_box',forceprint=True)\n        # Whether to save trajectories (0 = never, 1 = delete after good step, 2 = keep all)\n        self.set_option(tgt_opts,'save_traj')\n\n        #======================================#\n        #     Variables which are set here     #\n        #======================================#\n        ## LPW 2018-02-11: This is set to True if the target calculates\n        ## a single-point property over several existing snapshots.\n        self.loop_over_snapshots = False\n        # List of trajectory files that may be deleted if self.save_traj == 1.\n        self.last_traj = []\n        # Extra files to be copied back at the end of a run.\n        self.extra_output = []\n        # Read the reference data\n        self.read_data()\n        # Read in lipid starting coordinates.\n        if 'n_ic' in self.RefData:\n            # Linked IC folder into the temp-directory.\n            self.nptfiles += [\"IC\"]\n            # Store IC frames in a dictionary.\n            self.lipid_mols = OrderedDict()\n            self.lipid_mols_new = OrderedDict()\n            for pt in self.PhasePoints:\n                pt_label = \"IC/%sK-%s%s\" % (pt[0], pt[1], pt[2])\n                if not os.path.exists(os.path.join(self.root, self.tgtdir, pt_label, self.lipid_coords)):\n                    raise RuntimeError(\"Initial condition files don't exist; please provide IC directory\")\n                # Create molecule object for each IC.\n                all_ic = Molecule(os.path.join(self.root, self.tgtdir, pt_label, self.lipid_coords))\n                self.lipid_mols[pt] = []\n                n_uniq_ic = int(self.RefData['n_ic'][pt])\n                if n_uniq_ic > len(all_ic):\n                    raise RuntimeError(\"Number of frames in initial conditions .gro file is less than the number of parallel simulations requested in data.csv\")\n                # Index ICs by pressure and temperature in a dictionary.\n                for ic in range(n_uniq_ic):\n                    self.lipid_mols[pt].append(all_ic[ic])\n        else:\n            # Read in lipid starting coordinates.\n            if not os.path.exists(os.path.join(self.root, self.tgtdir, self.lipid_coords)): \n                logger.error(\"%s doesn't exist; please provide lipid_coords option\\n\" % self.lipid_coords)\n                raise RuntimeError\n            self.lipid_mol = Molecule(os.path.join(self.root, self.tgtdir, self.lipid_coords), toppbc=True)\n            # Extra files to be linked into the temp-directory.\n            self.nptfiles += [self.lipid_coords]\n        # Scripts to be copied from the ForceBalance installation directory.\n        self.scripts += ['npt_lipid.py']\n        # Prepare the temporary directory.\n        self.prepare_temp_directory()\n        # Build keyword dictionary to pass to engine.\n        if self.do_self_pol:\n            self.gas_engine_args.update(self.OptionDict)\n            self.gas_engine_args.update(options)\n            del self.gas_engine_args['name']\n            # Create engine object for gas molecule to do the polarization correction.\n            self.gas_engine = self.engine_(target=self, mol=self.gas_mol, name=\"selfpol\", **self.gas_engine_args)\n        # Don't read indicate.log when calling meta_indicate()\n        self.read_indicate = False\n        self.write_indicate = False\n        # Don't read objective.p when calling meta_get()\n        self.read_objective = False\n        #======================================#\n        #          UNDER DEVELOPMENT           #\n        #======================================#\n        # Put stuff here that I'm not sure about. :)\n        np.set_printoptions(precision=4, linewidth=100)\n        np.seterr(under='ignore')\n        ## Saved force field mvals for all iterations\n        self.SavedMVal = {}\n        ## Saved trajectories for all iterations and all temperatures\n        self.SavedTraj = defaultdict(dict)\n        ## Evaluated energies for all trajectories (i.e. all iterations and all temperatures), using all mvals\n        self.MBarEnergy = defaultdict(lambda:defaultdict(dict))\n\n    def prepare_temp_directory(self):\n        \"\"\" Prepare the temporary directory by copying in important files. \"\"\"\n        abstempdir = os.path.join(self.root,self.tempdir)\n        for f in self.nptfiles:\n            LinkFile(os.path.join(self.root, self.tgtdir, f), os.path.join(abstempdir, f))\n        for f in self.scripts:\n            LinkFile(os.path.join(os.path.split(__file__)[0],\"data\",f),os.path.join(abstempdir,f))\n\n    def read_data(self):\n        # Read the 'data.csv' file. The file should contain guidelines.\n        with open(os.path.join(self.tgtdir,'data.csv'),'r') as f: R0 = list(csv.reader(f))\n        # All comments are erased.\n        R1 = [[sub('#.*$','',word) for word in line] for line in R0 if len(line[0]) > 0 and line[0][0] != \"#\"]\n        # All empty lines are deleted and words are converted to lowercase.\n        R = [[wrd.lower() for wrd in line] for line in R1 if any([len(wrd) for wrd in line]) > 0]\n        global_opts = OrderedDict()\n        found_headings = False\n        known_vars = ['mbar','rho','hvap','alpha','kappa','cp','eps0','cvib_intra',\n                      'cvib_inter','cni','devib_intra','devib_inter', 'al', 'scd', 'n_ic', 'lkappa']\n        self.RefData = OrderedDict()\n        for line in R:\n            if line[0] == \"global\":\n                # Global options are mainly denominators for the different observables.\n                if isfloat(line[2]):\n                    global_opts[line[1]] = float(line[2])\n                elif line[2].lower() == 'false':\n                    global_opts[line[1]] = False\n                elif line[2].lower() == 'true':\n                    global_opts[line[1]] = True\n            elif not found_headings:\n                found_headings = True\n                headings = line\n                if len(set(headings)) != len(headings):\n                    logger.error('Column headings in data.csv must be unique\\n')\n                    raise RuntimeError\n                if 'p' not in headings:\n                    logger.error('There must be a pressure column heading labeled by \"p\" in data.csv\\n')\n                    raise RuntimeError\n                if 't' not in headings:\n                    logger.error('There must be a temperature column heading labeled by \"t\" in data.csv\\n')\n                    raise RuntimeError\n            elif found_headings:\n                try:\n                    # Temperatures are in kelvin.\n                    t     = [float(val) for head, val in zip(headings,line) if head == 't'][0]\n                    # For convenience, users may input the pressure in atmosphere or bar.\n                    pval  = [float(val.split()[0]) for head, val in zip(headings,line) if head == 'p'][0]\n                    punit = [val.split()[1] if len(val.split()) >= 1 else \"atm\" for head, val in zip(headings,line) if head == 'p'][0]\n                    unrec = set([punit]).difference(['atm','bar']) \n                    if len(unrec) > 0:\n                        logger.error('The pressure unit %s is not recognized, please use bar or atm\\n' % unrec[0])\n                        raise RuntimeError\n                    # This line actually reads the reference data and inserts it into the RefData dictionary of dictionaries.\n                    for head, val in zip(headings,line):\n                        if head == 't' or head == 'p' : continue\n                        if isfloat(val):\n                            self.RefData.setdefault(head,OrderedDict([]))[(t,pval,punit)] = float(val.strip())\n                        elif val.lower() == 'true':\n                            self.RefData.setdefault(head,OrderedDict([]))[(t,pval,punit)] = True\n                        elif val.lower() == 'false':\n                            self.RefData.setdefault(head,OrderedDict([]))[(t,pval,punit)] = False\n                        elif head == 'scd':\n                            self.RefData.setdefault(head,OrderedDict([]))[(t,pval,punit)] = np.array(list(map(float, val.split())))\n                except:\n                    logger.error(line + '\\n')\n                    logger.error('Encountered an error reading this line!\\n')\n                    raise RuntimeError\n            else:\n                logger.error(line + '\\n')\n                logger.error('I did not recognize this line!\\n')\n                raise RuntimeError\n        # Check the reference data table for validity.\n        default_denoms = defaultdict(int)\n        PhasePoints = None\n        RefData_copy = copy.deepcopy(self.RefData)\n        for head in self.RefData:\n            if head == 'n_ic':\n                continue\n            if head not in known_vars+[i+\"_wt\" for i in known_vars]:\n                # Only hard-coded properties may be recognized.\n                logger.error(\"The column heading %s is not recognized in data.csv\\n\" % head)\n                raise RuntimeError\n            if head in known_vars:\n                if head+\"_wt\" not in self.RefData:\n                    # If the phase-point weights are not specified in the reference data file, initialize them all to one.\n                    RefData_copy[head+\"_wt\"] = OrderedDict([(key, 1.0) for key in self.RefData[head]])\n                wts = np.array(list(RefData_copy[head+\"_wt\"].values()))\n                dat = np.array(list(self.RefData[head].values()))\n                # S_cd specifies an array of averages (one for each tail node).  Find avg over axis 0.\n                avg = np.average(dat, weights=wts, axis=0)\n                if len(wts) > 1:\n                    # If there is more than one data point, then the default denominator is the\n                    # standard deviation of the experimental values.\n                    if head == 'scd':\n                        default_denoms[head+\"_denom\"] = np.average(np.sqrt(np.dot(wts, (dat-avg)**2)/wts.sum()))\n                    else:\n                        default_denoms[head+\"_denom\"] = np.sqrt(np.dot(wts, (dat-avg)**2)/wts.sum())\n                else:\n                    # If there is only one data point, then the denominator is just the single\n                    # data point itself.\n                    if head == 'scd':\n                        default_denoms[head+\"_denom\"] = np.average(np.sqrt(np.abs(dat[0])))\n                    else:\n                        default_denoms[head+\"_denom\"] = np.sqrt(np.abs(dat[0]))\n            self.PhasePoints = list(self.RefData[head].keys())\n            # This prints out all of the reference data.\n            # printcool_dictionary(self.RefData[head],head)\n        self.RefData = RefData_copy\n        # Create labels for the directories.\n        self.Labels = [\"%.2fK-%.1f%s\" % i for i in self.PhasePoints]\n        logger.debug(\"global_opts:\\n%s\\n\" % str(global_opts))\n        logger.debug(\"default_denoms:\\n%s\\n\" % str(default_denoms))\n        for opt in global_opts:\n            if \"_denom\" in opt:\n                # Record entries from the global_opts dictionary so they can be retrieved from other methods.\n                self.set_option(global_opts,opt,default=default_denoms[opt])\n            else:\n                self.set_option(global_opts,opt)\n\n    def check_files(self, there):\n        there = os.path.abspath(there)\n        havepts = 0\n        if all([i in os.listdir(there) for i in self.Labels]):\n            for d in os.listdir(there):\n                if d in self.Labels:\n                    if os.path.exists(os.path.join(there, d, 'npt_result.p')):\n                        havepts += 1\n        if (float(havepts)/len(self.Labels)) > 0.75:\n            return 1\n        else:\n            return 0\n    def npt_simulation(self, temperature, pressure, simnum):\n        \"\"\" Submit a NPT simulation to the Work Queue. \"\"\"\n        wq = getWorkQueue()\n        if not os.path.exists('npt_result.p'):\n            link_dir_contents(os.path.join(self.root,self.rundir),os.getcwd())\n            self.last_traj += [os.path.join(os.getcwd(), i) for i in self.extra_output]\n            self.lipid_mol[simnum%len(self.lipid_mol)].write(self.lipid_coords, ftype='tinker' if self.engname == 'tinker' else None)\n            cmdstr = '%s python npt_lipid.py %s %.3f %.3f' % (self.nptpfx, self.engname, temperature, pressure)\n            if wq is None:\n                logger.info(\"Running condensed phase simulation locally.\\n\")\n                logger.info(\"You may tail -f %s/npt.out in another terminal window\\n\" % os.getcwd())\n                _exec(cmdstr, copy_stderr=True, outfnm='npt.out')\n            else:\n                queue_up(wq, command = cmdstr+' &> npt.out',\n                         input_files = self.nptfiles + self.scripts + ['forcebalance.p'],\n                         output_files = ['npt_result.p', 'npt.out'] + self.extra_output, tgt=self)\n\n    def polarization_correction(self,mvals):\n        d = self.gas_engine.get_multipole_moments(optimize=True)['dipole']\n        if not in_fd():\n            logger.info(\"The molecular dipole moment is % .3f debye\\n\" % np.linalg.norm(d))\n        # Taken from the original OpenMM interface code, this is how we calculate the conversion factor.\n        # dd2 = ((np.linalg.norm(d)-self.self_pol_mu0)*debye)**2\n        # eps0 = 8.854187817620e-12 * coulomb**2 / newton / meter**2\n        # epol = 0.5*dd2/(self.self_pol_alpha*angstrom**3*4*np.pi*eps0)/(kilojoule_per_mole/AVOGADRO_CONSTANT_NA)\n        # In [2]: eps0 = 8.854187817620e-12 * coulomb**2 / newton / meter**2\n        # In [7]: 1.0 * debye ** 2 / (1.0 * angstrom**3*4*np.pi*eps0) / (kilojoule_per_mole/AVOGADRO_CONSTANT_NA)\n        # Out[7]: 60.240179789402056\n        convert = 60.240179789402056\n        dd2 = (np.linalg.norm(d)-self.self_pol_mu0)**2\n        epol = 0.5*convert*dd2/self.self_pol_alpha\n        return epol\n\n    def indicate(self): \n        AGrad = hasattr(self, 'Gp')\n        PrintDict = OrderedDict()\n        def print_item(key, heading, physunit):\n            if self.Xp[key] > 0:\n                printcool_dictionary(self.Pp[key], title='%s %s%s\\nTemperature  Pressure  Reference  Calculated +- Stdev     Delta    Weight    Term   ' % \n                                     (self.name, heading, \" (%s) \" % physunit if physunit else \"\"), bold=True, color=4, keywidth=15)\n                bar = printcool(\"%s objective function: % .3f%s\" % (heading, self.Xp[key], \", Derivative:\" if AGrad else \"\"))\n                if AGrad:\n                    self.FF.print_map(vals=self.Gp[key])\n                    logger.info(bar)\n                PrintDict[heading] = \"% 10.5f % 8.3f % 14.5e\" % (self.Xp[key], self.Wp[key], self.Xp[key]*self.Wp[key])\n\n        print_item(\"Rho\", \"Density\", \"kg m^-3\")\n        print_item(\"Alpha\", \"Thermal Expansion Coefficient\", \"10^-4 K^-1\")\n        print_item(\"Kappa\", \"Isothermal Compressibility\", \"10^-6 bar^-1\")\n        print_item(\"Cp\", \"Isobaric Heat Capacity\", \"cal mol^-1 K^-1\")\n        print_item(\"Eps0\", \"Dielectric Constant\", None)\n        print_item(\"Al\", \"Average Area per Lipid\", \"nm^2\")\n        print_item(\"Scd\", \"Deuterium Order Parameter\", None)\n        print_item(\"LKappa\", \"Bilayer Isothermal Compressibility\", \"mN/m\")\n\n        PrintDict['Total'] = \"% 10s % 8s % 14.5e\" % (\"\",\"\",self.Objective)\n\n        Title = \"%s Condensed Phase Properties:\\n %-20s %40s\" % (self.name, \"Property Name\", \"Residual x Weight = Contribution\")\n        printcool_dictionary(PrintDict,color=4,title=Title,keywidth=31)\n        return\n\n    def objective_term(self, points, expname, calc, err, grad, name=\"Quantity\", SubAverage=False):\n        if expname in self.RefData:\n            exp = self.RefData[expname]\n            Weights = self.RefData[expname+\"_wt\"]\n            Denom = getattr(self,expname+\"_denom\")\n        else:\n            # If the reference data doesn't exist then return nothing.\n            return 0.0, np.zeros(self.FF.np), np.zeros((self.FF.np,self.FF.np)), None\n            \n        Sum = sum(Weights.values())\n        for i in Weights:\n            Weights[i] /= Sum\n        logger.info(\"Weights have been renormalized to \" + str(sum(Weights.values())) + \"\\n\")\n        # Use least-squares or hyperbolic (experimental) objective.\n        LeastSquares = True\n\n        logger.info(\"Physical quantity %s uses denominator = % .4f\\n\" % (name, Denom))\n        if not LeastSquares:\n            # If using a hyperbolic functional form\n            # we still want the contribution to the \n            # objective function to be the same when\n            # Delta = Denom.\n            Denom /= 3 ** 0.5\n        \n        Objective = 0.0\n        Gradient = np.zeros(self.FF.np)\n        Hessian = np.zeros((self.FF.np,self.FF.np))\n        Objs = {}\n        GradMap = []\n        avgCalc = 0.0\n        avgExp  = 0.0\n        avgGrad = np.zeros(self.FF.np)\n        for i, PT in enumerate(points):\n            avgCalc += Weights[PT]*calc[PT]\n            avgExp  += Weights[PT]*exp[PT]\n            avgGrad += Weights[PT]*grad[PT]\n        for i, PT in enumerate(points):\n            if SubAverage:\n                G = grad[PT]-avgGrad\n                Delta = calc[PT] - exp[PT] - avgCalc + avgExp\n            else:\n                G = grad[PT]\n                Delta = calc[PT] - exp[PT]\n            if hasattr(Delta, \"__len__\"):\n                Delta = np.average(Delta)\n            if LeastSquares:\n                # Least-squares objective function.\n                ThisObj = Weights[PT] * Delta ** 2 / Denom**2\n                Objs[PT] = ThisObj\n                ThisGrad = 2.0 * Weights[PT] * Delta * G / Denom**2\n                GradMap.append(G)\n                Objective += ThisObj\n                Gradient += ThisGrad\n                # Gauss-Newton approximation to the Hessian.\n                Hessian += 2.0 * Weights[PT] * (np.outer(G, G)) / Denom**2\n            else:\n                # L1-like objective function.\n                D = Denom\n                S = Delta**2 + D**2\n                ThisObj  = Weights[PT] * (S**0.5-D) / Denom\n                ThisGrad = Weights[PT] * (Delta/S**0.5) * G / Denom\n                ThisHess = Weights[PT] * (1/S**0.5-Delta**2/S**1.5) * np.outer(G,G) / Denom\n                Objs[PT] = ThisObj\n                GradMap.append(G)\n                Objective += ThisObj\n                Gradient += ThisGrad\n                Hessian += ThisHess\n        GradMapPrint = [[\"#PhasePoint\"] + self.FF.plist]\n        for PT, g in zip(points,GradMap):\n            GradMapPrint.append([' %8.2f %8.1f %3s' % PT] + [\"% 9.3e\" % i for i in g])\n        o = wopen('gradient_%s.dat' % name)\n        for line in GradMapPrint:\n            print(' '.join(line), file=o)\n        o.close()\n            \n        Delta = np.array([calc[PT] - exp[PT] for PT in points])\n        delt = {PT : r for PT, r in zip(points,Delta)}\n        if expname == 'scd': \n            print_out = OrderedDict([('    %8.2f %8.1f %3s' % PT, '\\n %s' % (' '.join('\\t \\t \\t %9.6f    %9.6f +- %-7.6f % 7.6f \\n' % F for F in zip(exp[PT], calc[PT], flat(err[PT]), delt[PT])))) for PT in calc])\n        else:\n            print_out = OrderedDict([('    %8.2f %8.1f %3s' % PT, \"%9.3f    %9.3f +- %-7.3f % 7.3f % 9.5f % 9.5f\" % (exp[PT],calc[PT],err[PT],delt[PT],Weights[PT],Objs[PT])) for PT in calc])\n\n        return Objective, Gradient, Hessian, print_out\n\n    def submit_jobs(self, mvals, AGrad=True, AHess=True):\n        # This routine is called by Objective.stage() will run before \"get\".\n        # It submits the jobs to the Work Queue and the stage() function will wait for jobs to complete.\n        #\n        # First dump the force field to a pickle file\n        lp_dump((self.FF,mvals,self.OptionDict,AGrad),'forcebalance.p')\n\n        # Give the user an opportunity to copy over data from a previous (perhaps failed) run.\n        if (not self.evaluated) and self.manual:\n            warn_press_key(\"Now's our chance to fill the temp directory up with data!\\n(Considering using 'read' or 'continue' for better checkpointing)\", timeout=7200)\n\n        # If self.save_traj == 1, delete the trajectory files from a previous good optimization step.\n        if self.evaluated and self.goodstep and self.save_traj < 2:\n            for fn in self.last_traj:\n                if os.path.exists(fn):\n                    os.remove(fn)\n        self.last_traj = []\n\n        # Set up and run the NPT simulations.\n        snum = 0\n        for label, pt in zip(self.Labels, self.PhasePoints):\n            T = pt[0]\n            P = pt[1]\n            Punit = pt[2]\n            if Punit == 'bar':\n                P *= 1.0 / 1.01325\n            if not os.path.exists(label):\n                os.makedirs(label)\n                os.chdir(label)\n                if 'n_ic' in self.RefData:\n                    n_uniq_ic = int(self.RefData['n_ic'][pt])\n                    # Loop over parallel trajectories.\n                    for trj in range(n_uniq_ic):\n                        rel_trj = \"trj_%i\" % trj\n                        # Create directories for each parallel simulation.\n                        if not os.path.exists(rel_trj):\n                            os.makedirs(rel_trj)\n                            os.chdir(rel_trj)\n                            # Pull each simulation molecule from the lipid_mols dictionary.\n                            # lipid_mols is a dictionary of paths to either the initial \n                            # geometry files, or the geometries from the final frame of the \n                            # previous iteration.\n                            self.lipid_mol = self.lipid_mols[pt][trj]\n                            self.lipid_mol.write(self.lipid_coords)\n                            if not self.lipid_coords in self.nptfiles:\n                                self.nptfiles += [self.lipid_coords]\n                            self.npt_simulation(T,P,snum)\n                        os.chdir('..')\n                else:\n                    self.npt_simulation(T,P,snum)\n                os.chdir('..')\n                snum += 1\n\n    def get(self, mvals, AGrad=True, AHess=True):\n        \n        \"\"\"\n        Fitting of lipid bulk properties.  This is the current major\n        direction of development for ForceBalance.  Basically, fitting\n        the QM energies / forces alone does not always give us the\n        best simulation behavior.  In many cases it makes more sense\n        to try and reproduce some experimentally known data as well.\n\n        In order to reproduce experimentally known data, we need to\n        run a simulation and compare the simulation result to\n        experiment.  The main challenge here is that the simulations\n        are computationally intensive (i.e. they require energy and\n        force evaluations), and furthermore the results are noisy.  We\n        need to run the simulations automatically and remotely\n        (i.e. on clusters) and a good way to calculate the derivatives\n        of the simulation results with respect to the parameter values.\n\n        This function contains some experimentally known values of the\n        density and enthalpy of vaporization (Hvap) of lipid water.\n        It launches the density and Hvap calculations on the cluster,\n        and gathers the results / derivatives.  The actual calculation\n        of results / derivatives is done in a separate file.\n\n        After the results come back, they are gathered together to form\n        an objective function.\n\n        @param[in] mvals Mathematical parameter values\n        @param[in] AGrad Switch to turn on analytic gradient\n        @param[in] AHess Switch to turn on analytic Hessian\n        @return Answer Contribution to the objective function\n        \n        \"\"\"\n\n        mbar_verbose = False\n\n        Answer = {}\n\n        Results = {}\n        Points = []  # These are the phase points for which data exists.\n        BPoints = [] # These are the phase points for which we are doing MBAR for the condensed phase.\n        tt = 0\n        for label, PT in zip(self.Labels, self.PhasePoints):\n            if 'n_ic' in self.RefData:\n                self.lipid_mols[PT] = [Molecule(last_frame) for last_frame in self.lipid_mols[PT]]\n                n_uniq_ic = int(self.RefData['n_ic'][PT])\n                for ic in range(n_uniq_ic):\n                    if os.path.exists('./%s/trj_%s/npt_result.p' % (label, ic)):\n                        # Read in each each parallel simulation's data, and concatenate each property time series.\n                        ts = lp_load('./%s/trj_%s/npt_result.p' % (label, ic))\n                        if ic == 0:\n                            ts_concat = list(ts)\n                        else:\n                            for d_arr in range(len(ts)):\n                                if isinstance(ts[d_arr], np.ndarray):\n                                    # Gradients need a unique append format.\n                                    if d_arr == 5:\n                                        ts_concat[d_arr] = np.append(ts_concat[d_arr], ts[d_arr], axis = 1)\n                                    else:\n                                        ts_concat[d_arr] = np.append(ts_concat[d_arr], ts[d_arr], axis = 0)\n                                if isinstance(ts_concat[d_arr], list):\n                                    ts_concat[d_arr] = [np.append(ts_concat[d_arr][i], ts[d_arr][i], axis = 1) for i in range(len(ts_concat[d_arr]))]\n                        # Write concatenated time series to a pickle file.\n                        if ic == (int(n_uniq_ic) - 1):\n                            lp_dump((ts_concat), './%s/npt_result.p' % label)\n            if os.path.exists('./%s/npt_result.p' % label):\n                logger.info('Reading information from ./%s/npt_result.p\\n' % label)\n                Points.append(PT)\n                Results[tt] = lp_load('./%s/npt_result.p' % label)\n                tt += 1\n            else:\n                logger.warning('The file ./%s/npt_result.p does not exist so we cannot read it\\n' % label)\n                pass\n                # for obs in self.RefData:\n                #     del self.RefData[obs][PT]\n        if len(Points) == 0:\n            logger.error('The lipid simulations have terminated with \\x1b[1;91mno readable data\\x1b[0m - this is a problem!\\n')\n            raise RuntimeError\n\n        # Assign variable names to all the stuff in npt_result.p\n        Rhos, Vols, Potentials, Energies, Dips, Grads, GDips, \\\n            Rho_errs, Alpha_errs, Kappa_errs, Cp_errs, Eps0_errs, NMols, Als, Al_errs, Scds, Scd_errs, LKappa_errs = ([Results[t][i] for t in range(len(Points))] for i in range(18))\n        # Determine the number of molecules\n        if len(set(NMols)) != 1:\n            logger.error(str(NMols))\n            logger.error('The above list should only contain one number - the number of molecules\\n')\n            raise RuntimeError\n        else:\n            NMol = list(set(NMols))[0]\n    \n        R  = np.array(list(itertools.chain(*list(Rhos))))\n        V  = np.array(list(itertools.chain(*list(Vols))))\n        E  = np.array(list(itertools.chain(*list(Energies))))\n        Dx = np.array(list(itertools.chain(*list(d[:,0] for d in Dips))))\n        Dy = np.array(list(itertools.chain(*list(d[:,1] for d in Dips))))\n        Dz = np.array(list(itertools.chain(*list(d[:,2] for d in Dips))))\n        G  = np.hstack(tuple(Grads))\n        GDx = np.hstack(tuple(gd[0] for gd in GDips))\n        GDy = np.hstack(tuple(gd[1] for gd in GDips))\n        GDz = np.hstack(tuple(gd[2] for gd in GDips))\n        A  = np.array(list(itertools.chain(*list(Als))))\n        S  = np.array(list(itertools.chain(*list(Scds))))\n\n        Rho_calc = OrderedDict([])\n        Rho_grad = OrderedDict([])\n        Rho_std  = OrderedDict([])\n        Alpha_calc = OrderedDict([])\n        Alpha_grad = OrderedDict([])\n        Alpha_std  = OrderedDict([])\n        Kappa_calc = OrderedDict([])\n        Kappa_grad = OrderedDict([])\n        Kappa_std  = OrderedDict([])\n        Cp_calc = OrderedDict([])\n        Cp_grad = OrderedDict([])\n        Cp_std  = OrderedDict([])\n        Eps0_calc = OrderedDict([])\n        Eps0_grad = OrderedDict([])\n        Eps0_std  = OrderedDict([])\n        Al_calc = OrderedDict([])\n        Al_grad = OrderedDict([])\n        Al_std  = OrderedDict([])\n        LKappa_calc = OrderedDict([])\n        LKappa_grad = OrderedDict([])\n        LKappa_std  = OrderedDict([])\n        Scd_calc = OrderedDict([])\n        Scd_grad = OrderedDict([])\n        Scd_std  = OrderedDict([])\n\n        # The unit that converts atmospheres * nm**3 into kj/mol :)\n        pvkj=0.061019351687175\n \n        # Run MBAR using the total energies. Required for estimates that use the kinetic energy.\n        BSims = len(BPoints)\n        Shots = len(Energies[0])\n        Shots_m = [len(i) for i in Energies]\n        N_k = np.ones(BSims)*Shots\n        # Use the value of the energy for snapshot t from simulation k at potential m\n        U_kln = np.zeros([BSims,BSims,Shots])\n        for m, PT in enumerate(BPoints):\n            T = PT[0]\n            P = PT[1] / 1.01325 if PT[2] == 'bar' else PT[1]\n            beta = 1. / (kb * T)\n            for k in range(BSims):\n                # The correct Boltzmann factors include PV.\n                # Note that because the Boltzmann factors are computed from the conditions at simulation \"m\",\n                # the pV terms must be rescaled to the pressure at simulation \"m\".\n                kk = Points.index(BPoints[k])\n                U_kln[k, m, :]   = Energies[kk] + P*Vols[kk]*pvkj\n                U_kln[k, m, :]  *= beta\n        W1 = None\n        if len(BPoints) > 1:\n            logger.info(\"Running MBAR analysis on %i states...\\n\" % len(BPoints))\n            mbar = pymbar.MBAR(U_kln, N_k, verbose=mbar_verbose, relative_tolerance=5.0e-8)\n            W1 = mbar.getWeights()\n            logger.info(\"Done\\n\")\n        elif len(BPoints) == 1:\n            W1 = np.ones((BPoints*Shots,BPoints))\n            W1 /= BPoints*Shots\n        \n        def fill_weights(weights, phase_points, mbar_points, snapshots):\n            \"\"\" Fill in the weight matrix with MBAR weights where MBAR was run, \n            and equal weights otherwise. \"\"\"\n            new_weights = np.zeros([len(phase_points)*snapshots,len(phase_points)])\n            for m, PT in enumerate(phase_points):\n                if PT in mbar_points:\n                    mm = mbar_points.index(PT)\n                    for kk, PT1 in enumerate(mbar_points):\n                        k = phase_points.index(PT1)\n                        logger.debug(\"Will fill W2[%i:%i,%i] with W1[%i:%i,%i]\\n\" % (k*snapshots,k*snapshots+snapshots,m,kk*snapshots,kk*snapshots+snapshots,mm))\n                        new_weights[k*snapshots:(k+1)*snapshots,m] = weights[kk*snapshots:(kk+1)*snapshots,mm]\n                else:\n                    logger.debug(\"Will fill W2[%i:%i,%i] with equal weights\\n\" % (m*snapshots,(m+1)*snapshots,m))\n                    new_weights[m*snapshots:(m+1)*snapshots,m] = 1.0/snapshots\n            return new_weights\n        \n        W2 = fill_weights(W1, Points, BPoints, Shots)\n\n        if self.do_self_pol:\n            EPol = self.polarization_correction(mvals)\n            GEPol = np.array([(f12d3p(fdwrap(self.polarization_correction, mvals, p), h = self.h, f0 = EPol)[0] if p in self.pgrad else 0.0) for p in range(self.FF.np)])\n            bar = printcool(\"Self-polarization correction to \\nenthalpy of vaporization is % .3f kJ/mol%s\" % (EPol, \", Derivative:\" if AGrad else \"\"))\n            if AGrad:\n                self.FF.print_map(vals=GEPol)\n                logger.info(bar)\n            \n        for i, PT in enumerate(Points):\n            T = PT[0]\n            P = PT[1] / 1.01325 if PT[2] == 'bar' else PT[1]\n            PV = P*V*pvkj\n            H = E + PV\n            # The weights that we want are the last ones.\n            W = flat(W2[:,i])\n            C = weight_info(W, PT, np.ones(len(Points), dtype=int)*Shots, verbose=mbar_verbose)\n            Gbar = flat(np.dot(G,col(W)))\n            mBeta = -1/kb/T\n            Beta  = 1/kb/T\n            kT    = kb*T\n            # Define some things to make the analytic derivatives easier.\n            def avg(vec):\n                return np.dot(W,vec)\n            def covde(vec):\n                return flat(np.dot(G,col(W*vec))) - avg(vec)*Gbar\n            def deprod(vec):\n                return flat(np.dot(G,col(W*vec)))\n            ## Density.\n            Rho_calc[PT]   = np.dot(W,R)\n            Rho_grad[PT]   = mBeta*(flat(np.dot(G,col(W*R))) - np.dot(W,R)*Gbar)\n            ## Ignore enthalpy.\n            ## Thermal expansion coefficient.\n            Alpha_calc[PT] = 1e4 * (avg(H*V)-avg(H)*avg(V))/avg(V)/(kT*T)\n            GAlpha1 = -1 * Beta * deprod(H*V) * avg(V) / avg(V)**2\n            GAlpha2 = +1 * Beta * avg(H*V) * deprod(V) / avg(V)**2\n            GAlpha3 = deprod(V)/avg(V) - Gbar\n            GAlpha4 = Beta * covde(H)\n            Alpha_grad[PT] = 1e4 * (GAlpha1 + GAlpha2 + GAlpha3 + GAlpha4)/(kT*T)\n            ## Isothermal compressibility.\n            bar_unit = 0.06022141793 * 1e6\n            Kappa_calc[PT] = bar_unit / kT * (avg(V**2)-avg(V)**2)/avg(V)\n            GKappa1 = +1 * Beta**2 * avg(V**2) * deprod(V) / avg(V)**2\n            GKappa2 = -1 * Beta**2 * avg(V) * deprod(V**2) / avg(V)**2\n            GKappa3 = +1 * Beta**2 * covde(V)\n            Kappa_grad[PT] = bar_unit*(GKappa1 + GKappa2 + GKappa3)\n            ## Isobaric heat capacity.\n            Cp_calc[PT] = 1000/(4.184*NMol*kT*T) * (avg(H**2) - avg(H)**2)\n            if hasattr(self,'use_cvib_intra') and self.use_cvib_intra:\n                logger.debug(\"Adding \" + str(self.RefData['devib_intra'][PT]) + \" to the heat capacity\\n\")\n                Cp_calc[PT] += self.RefData['devib_intra'][PT]\n            if hasattr(self,'use_cvib_inter') and self.use_cvib_inter:\n                logger.debug(\"Adding \" + str(self.RefData['devib_inter'][PT]) + \" to the heat capacity\\n\")\n                Cp_calc[PT] += self.RefData['devib_inter'][PT]\n            GCp1 = 2*covde(H) * 1000 / 4.184 / (NMol*kT*T)\n            GCp2 = mBeta*covde(H**2) * 1000 / 4.184 / (NMol*kT*T)\n            GCp3 = 2*Beta*avg(H)*covde(H) * 1000 / 4.184 / (NMol*kT*T)\n            Cp_grad[PT] = GCp1 + GCp2 + GCp3\n            ## Static dielectric constant.\n            prefactor = 30.348705333964077\n            D2 = avg(Dx**2)+avg(Dy**2)+avg(Dz**2)-avg(Dx)**2-avg(Dy)**2-avg(Dz)**2\n            Eps0_calc[PT] = 1.0 + prefactor*(D2/avg(V))/T\n            GD2  = 2*(flat(np.dot(GDx,col(W*Dx))) - avg(Dx)*flat(np.dot(GDx,col(W)))) - Beta*(covde(Dx**2) - 2*avg(Dx)*covde(Dx))\n            GD2 += 2*(flat(np.dot(GDy,col(W*Dy))) - avg(Dy)*flat(np.dot(GDy,col(W)))) - Beta*(covde(Dy**2) - 2*avg(Dy)*covde(Dy))\n            GD2 += 2*(flat(np.dot(GDz,col(W*Dz))) - avg(Dz)*flat(np.dot(GDz,col(W)))) - Beta*(covde(Dz**2) - 2*avg(Dz)*covde(Dz))\n            Eps0_grad[PT] = prefactor*(GD2/avg(V) - mBeta*covde(V)*D2/avg(V)**2)/T\n            ## Average area per lipid\n            Al_calc[PT]   = np.dot(W,A)\n            Al_grad[PT]   = mBeta*(flat(np.dot(G,col(W*A))) - np.dot(W,A)*Gbar)\n            ## Bilayer Isothermal compressibility.\n            A_m2 = A * 1e-18\n            kbT = 1.3806488e-23 * T\n            LKappa_calc[PT] = (1e3 * 2 * kbT / 128) * (avg(A_m2) / (avg(A_m2**2)-avg(A_m2)**2))\n            al_avg = avg(A_m2)\n            al_sq_avg = avg(A_m2**2)\n            al_avg_sq = al_avg**2\n            al_var = al_sq_avg - al_avg_sq\n            GLKappa1 = covde(A_m2) / al_var\n            GLKappa2 = (al_avg / al_var**2) * (covde(A_m2**2) - (2 * al_avg * covde(A)))\n            LKappa_grad[PT] = (1e3 * 2 * kbT / 128) * (GLKappa1 - GLKappa2)\n            ## Deuterium order parameter\n            Scd_calc[PT]   = np.dot(W,S)\n            # LPW: In case I did not do the conversion correctly, the line of code previously here was:\n            # Scd_grad[PT]   = mBeta * (flat(np.average(np.mat(G) * (S * W[:, np.newaxis]), axis = 1)) - np.average(np.average(S * W[:, np.newaxis], axis = 0), axis = 0) * Gbar) \n            Scd_grad[PT]   = mBeta * (flat(np.average(np.dot(G, (S * W[:, np.newaxis])), axis = 1)) - np.average(np.average(S * W[:, np.newaxis], axis = 0), axis = 0) * Gbar) \n            ## Estimation of errors.\n            Rho_std[PT]    = np.sqrt(sum(C**2 * np.array(Rho_errs)**2))\n            Alpha_std[PT]   = np.sqrt(sum(C**2 * np.array(Alpha_errs)**2)) * 1e4\n            Kappa_std[PT]   = np.sqrt(sum(C**2 * np.array(Kappa_errs)**2)) * 1e6\n            Cp_std[PT]   = np.sqrt(sum(C**2 * np.array(Cp_errs)**2))\n            Eps0_std[PT]   = np.sqrt(sum(C**2 * np.array(Eps0_errs)**2))\n            Al_std[PT]    = np.sqrt(sum(C**2 * np.array(Al_errs)**2))\n            # LPW: In case I did not do the conversion correctly, the line of code previously here was:\n            # Scd_std[PT]    = np.sqrt(sum(np.mat(C**2) * np.array(Scd_errs)**2))\n            Scd_std[PT]    = np.sqrt(sum(np.dot(row(C**2), np.array(Scd_errs)**2)))\n            LKappa_std[PT]   = np.sqrt(sum(C**2 * np.array(LKappa_errs)**2)) * 1e6\n\n        # Get contributions to the objective function\n        X_Rho, G_Rho, H_Rho, RhoPrint = self.objective_term(Points, 'rho', Rho_calc, Rho_std, Rho_grad, name=\"Density\")\n        X_Alpha, G_Alpha, H_Alpha, AlphaPrint = self.objective_term(Points, 'alpha', Alpha_calc, Alpha_std, Alpha_grad, name=\"Thermal Expansion\")\n        X_Kappa, G_Kappa, H_Kappa, KappaPrint = self.objective_term(Points, 'kappa', Kappa_calc, Kappa_std, Kappa_grad, name=\"Compressibility\")\n        X_Cp, G_Cp, H_Cp, CpPrint = self.objective_term(Points, 'cp', Cp_calc, Cp_std, Cp_grad, name=\"Heat Capacity\")\n        X_Eps0, G_Eps0, H_Eps0, Eps0Print = self.objective_term(Points, 'eps0', Eps0_calc, Eps0_std, Eps0_grad, name=\"Dielectric Constant\")\n        X_Al, G_Al, H_Al, AlPrint = self.objective_term(Points, 'al', Al_calc, Al_std, Al_grad, name=\"Avg Area per Lipid\")\n        X_Scd, G_Scd, H_Scd, ScdPrint = self.objective_term(Points, 'scd', Scd_calc, Scd_std, Scd_grad, name=\"Deuterium Order Parameter\")\n        X_LKappa, G_LKappa, H_LKappa, LKappaPrint = self.objective_term(Points, 'lkappa', LKappa_calc, LKappa_std, LKappa_grad, name=\"Bilayer Compressibility\")\n\n        Gradient = np.zeros(self.FF.np)\n        Hessian = np.zeros((self.FF.np,self.FF.np))\n\n        if X_Rho == 0: self.w_rho = 0.0\n        if X_Alpha == 0: self.w_alpha = 0.0\n        if X_Kappa == 0: self.w_kappa = 0.0\n        if X_Cp == 0: self.w_cp = 0.0\n        if X_Eps0 == 0: self.w_eps0 = 0.0\n        if X_Al == 0: self.w_al = 0.0\n        if X_Scd == 0: self.w_scd = 0.0\n        if X_LKappa == 0: self.w_lkappa = 0.0\n\n        if self.w_normalize:\n            w_tot = self.w_rho + self.w_alpha + self.w_kappa + self.w_cp + self.w_eps0 + self.w_al + self.w_scd + self.w_lkappa\n        else:\n            w_tot = 1.0\n        w_1 = self.w_rho / w_tot\n        w_3 = self.w_alpha / w_tot\n        w_4 = self.w_kappa / w_tot\n        w_5 = self.w_cp / w_tot\n        w_6 = self.w_eps0 / w_tot\n        w_7 = self.w_al / w_tot\n        w_8 = self.w_scd / w_tot\n        w_9 = self.w_lkappa / w_tot\n\n        Objective    = w_1 * X_Rho + w_3 * X_Alpha + w_4 * X_Kappa + w_5 * X_Cp + w_6 * X_Eps0 + w_7 * X_Al + w_8 * X_Scd + w_9 * X_LKappa\n        if AGrad:\n            Gradient = w_1 * G_Rho + w_3 * G_Alpha + w_4 * G_Kappa + w_5 * G_Cp + w_6 * G_Eps0 + w_7 * G_Al + w_8 * G_Scd + w_9 * G_LKappa\n        if AHess:\n            Hessian  = w_1 * H_Rho + w_3 * H_Alpha + w_4 * H_Kappa + w_5 * H_Cp + w_6 * H_Eps0 + w_7 * H_Al + w_8 * H_Scd + w_9 * H_LKappa\n\n        if not in_fd():\n            self.Xp = {\"Rho\" : X_Rho, \"Alpha\" : X_Alpha, \n                           \"Kappa\" : X_Kappa, \"Cp\" : X_Cp, \"Eps0\" : X_Eps0, \"Al\" : X_Al, \"Scd\" : X_Scd, \"LKappa\" : X_LKappa}\n            self.Wp = {\"Rho\" : w_1, \"Alpha\" : w_3, \n                           \"Kappa\" : w_4, \"Cp\" : w_5, \"Eps0\" : w_6, \"Al\" : w_7, \"Scd\" : w_8, \"LKappa\" : w_9}\n            self.Pp = {\"Rho\" : RhoPrint, \"Alpha\" : AlphaPrint, \n                           \"Kappa\" : KappaPrint, \"Cp\" : CpPrint, \"Eps0\" : Eps0Print, \"Al\" : AlPrint, \"Scd\" : ScdPrint, \"LKappa\": LKappaPrint}\n            if AGrad:\n                self.Gp = {\"Rho\" : G_Rho, \"Alpha\" : G_Alpha, \n                               \"Kappa\" : G_Kappa, \"Cp\" : G_Cp, \"Eps0\" : G_Eps0, \"Al\" : G_Al, \"Scd\" : G_Scd, \"LKappa\" : G_LKappa}\n            self.Objective = Objective\n\n        Answer = {'X':Objective, 'G':Gradient, 'H':Hessian}\n        return Answer\n", "meta": {"hexsha": "1cf809b629306e177d82d1e4434ff7f82730f6ef", "size": 45099, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/lipid.py", "max_stars_repo_name": "cresset-group/forcebalance", "max_stars_repo_head_hexsha": "78a48d0e9ee9b5a8f3295cee8a811ad4cfcd2aa6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 98, "max_stars_repo_stars_event_min_datetime": "2015-03-31T06:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T12:07:37.000Z", "max_issues_repo_path": "src/lipid.py", "max_issues_repo_name": "cresset-group/forcebalance", "max_issues_repo_head_hexsha": "78a48d0e9ee9b5a8f3295cee8a811ad4cfcd2aa6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 121, "max_issues_repo_issues_event_min_datetime": "2015-07-13T15:57:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T20:07:10.000Z", "max_forks_repo_path": "src/lipid.py", "max_forks_repo_name": "cresset-group/forcebalance", "max_forks_repo_head_hexsha": "78a48d0e9ee9b5a8f3295cee8a811ad4cfcd2aa6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 66, "max_forks_repo_forks_event_min_datetime": "2015-04-06T03:05:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T05:11:59.000Z", "avg_line_length": 53.5617577197, "max_line_length": 212, "alphanum_fraction": 0.564181024, "include": true, "reason": "import numpy", "num_tokens": 11916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.19392490054465603}}
{"text": "# Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nQuantum chemistry module\n\"\"\"\n\nimport os\nimport re\nimport numpy as np\nimport psi4\nimport openfermion\nfrom openfermion import MolecularData, transforms\nfrom openfermion.ops import general_basis_change\nfrom paddle_quantum.utils import Hamiltonian\n\n__all__ = [\n    \"geometry\",\n    \"get_molecular_data\",\n    \"active_space\",\n    \"fermionic_hamiltonian\",\n    \"spin_hamiltonian\"\n]\n\n\ndef _hamiltonian_transformation(spin_h, tol=1e-8):\n    r\"\"\"将哈密顿量从 openfermion 格式转换成 Paddle Quantum 格式。\n\n    Warning:\n        输入的哈密顿量必须为埃尔米特的，输入的哈密顿中虚数的系数会和实数一起转换成他们的范数 (norm)。\n\n    Args:\n        spin_h (openfermion.ops.operators.qubit_operator.QubitOperator): openfermion 格式的哈密顿量\n        tol (float, optional): 系数小于 tol 的值将被忽略掉，默认为 1e-8\n\n    Returns:\n        paddle_quantum.Hamiltonian object: Paddle Quantum 格式的哈密顿量\n    \"\"\"\n    terms = spin_h.__str__().split('+\\n')\n    spin_h.compress(abs_tol=tol)\n    pauli_str = []\n    for term in terms:\n        decomposed_term = re.match(r\"(.*) \\[(.*)\\].*\", term).groups()\n        if decomposed_term[1] == '':\n            try:\n                pauli_str.append([float(decomposed_term[0]), 'I'])\n            except ValueError:\n                if complex(decomposed_term[0]).real > 0:\n                    pauli_str.append([abs(complex(decomposed_term[0])), 'I'])\n                else:\n                    pauli_str.append([-abs(complex(decomposed_term[0])), 'I'])\n        else:\n            term_str = ', '.join(re.split(r' ', decomposed_term[1]))\n            try:\n                pauli_str.append([float(decomposed_term[0]), term_str])\n            except ValueError:\n                if complex(decomposed_term[0]).real > 0:\n                    pauli_str.append([abs(complex(decomposed_term[0])), term_str])\n                else:\n                    pauli_str.append([-abs(complex(decomposed_term[0])), term_str])\n    return Hamiltonian(pauli_str)\n\n\ndef _geo_str(geometry):\n    r\"\"\"创建分子几何信息的字符串。\n\n    Args:\n        geometry (list): 包含了分子的几何信息，以 H2 分子为例\n        [['H', [-1.68666, 1.79811, 0.0]], ['H', [-1.12017, 1.37343, 0.0]]]。\n\n    Returns:\n        str: 分子几何信息的字符串。\n    \"\"\"\n    geo_str = ''\n    for item in geometry:\n        atom_symbol = item[0]\n        position = item[1]\n        line = '{} {} {} {}'.format(atom_symbol,\n                                    position[0],\n                                    position[1],\n                                    position[2])\n        if len(geo_str) > 0:\n            geo_str += '\\n'\n        geo_str += line\n    geo_str += '\\nsymmetry c1'\n    return geo_str\n\n\ndef _run_psi4(\n    molecule,\n    charge,\n    multiplicity,\n    method,\n    basis,\n    if_print,\n    if_save\n):\n    r\"\"\"计算分子的必要信息，包括单体积分 (one-body integrations) 和双体积分 (two-body integrations)，\n    以及用 scf 和 fci 的方法计算基态的能量。\n\n    Args:\n        molecule (MolecularData object): 包含分子所有信息的类 (class)。\n        charge (int): 分子的电荷。\n        multiplicity (int): 分子的多重度。\n        method (str): 用于计算基态能量的方法，包括 'scf'和 'fci'。\n        basis (str): 常用的基组是 'sto-3g', '6-31g'等。更多的基组选择可以参考网站。\n        https://psicode.org/psi4manual/master/basissets_byelement.html#apdx-basiselement。\n        if_print (Boolean): 是否需要打印出选定方法 (method) 计算出的分子基态能量。\n        if_save (Boolean): 是否需要将分子信息存储成 .hdf5 文件。\n    \"\"\"\n    psi4.set_memory('500 MB')\n    psi4.set_options({'soscf': 'false',\n                      'scf_type': 'pk'})\n    geo = molecule.geometry\n    mol = psi4.geometry(_geo_str(geo))\n    mol.set_multiplicity(multiplicity)\n    mol.set_molecular_charge(charge)\n\n    if molecule.multiplicity == 1:\n        psi4.set_options({'reference': 'rhf',\n                          'guess': 'sad'})\n    else:\n        psi4.set_options({'reference': 'rohf',\n                          'guess': 'gwh'})\n\n    # HF calculation\n    hf_energy, hf_wfn = psi4.energy('scf/' + basis, molecule=mol, return_wfn='on')\n    # Get orbitals and Fock matrix.\n    molecule.hf_energy = hf_energy\n    molecule.nuclear_repulsion = mol.nuclear_repulsion_energy()\n    molecule.canonical_orbitals = np.asarray(hf_wfn.Ca())\n    molecule.overlap_integrals = np.asarray(hf_wfn.S())\n    molecule.n_orbitals = molecule.canonical_orbitals.shape[0]\n    molecule.n_qubits = 2 * molecule.n_orbitals\n    molecule.orbital_energies = np.asarray(hf_wfn.epsilon_a())\n    molecule.fock_matrix = np.asarray(hf_wfn.Fa())\n\n    # Get integrals using MintsHelper.\n    mints = psi4.core.MintsHelper(hf_wfn.basisset())\n\n    molecule.one_body_integrals = general_basis_change(\n        np.asarray(mints.ao_kinetic()), molecule.canonical_orbitals, (1, 0))\n    molecule.one_body_integrals += general_basis_change(\n        np.asarray(mints.ao_potential()), molecule.canonical_orbitals, (1, 0))\n    two_body_integrals = np.asarray(mints.ao_eri())\n    two_body_integrals.reshape((molecule.n_orbitals, molecule.n_orbitals,\n                                molecule.n_orbitals, molecule.n_orbitals))\n    two_body_integrals = np.einsum('psqr', two_body_integrals)\n    two_body_integrals = general_basis_change(\n        two_body_integrals, molecule.canonical_orbitals, (1, 1, 0, 0))\n    molecule.two_body_integrals = two_body_integrals\n\n    # FCI calculation\n    psi4.set_options({'qc_module': 'detci'})\n    fci_energy, fci_wfn = psi4.energy('fci/' + basis, molecule=mol, return_wfn='on')\n    molecule.fci_energy = fci_energy\n\n    if if_save is True:\n        molecule.save()\n\n    if if_print is True:\n        if method == 'scf':\n            print('Hartree-Fock energy for {} ({} electrons) is {}.'.format(\n                molecule.name, molecule.n_electrons, hf_energy))\n\n        elif method == 'fci':\n            print('FCI energy for {} ({} electrons) is {}.'.format(\n                molecule.name, molecule.n_electrons, fci_energy))\n        elif method == '':\n            print('Calculation is done')\n\n\ndef geometry(structure=None, file=None):\n    r\"\"\"读取分子的几何信息。\n\n    Args:\n        structure (string, optional): 分子几何信息的字符串形式，以 H2 分子为例\n            ``[['H', [-1.68666, 1.79811, 0.0]], ['H', [-1.12017, 1.37343, 0.0]]]``\n        file (string, optional): .xyz 文件的路径\n\n    Returns:\n        str: 分子的几何信息\n\n    Raises:\n        AssertionError: 两个输入参数不可以同时为 ``None`` 。\n    \"\"\"\n    if ((structure is None) and (file is None)):\n        raise AssertionError('Input must be structure or .xyz file')\n    elif file is None:\n        shape = np.array(structure).shape\n        assert shape[1] == 2, 'The shape of structure must be (n, 2)'\n        for i in range(shape[0]):\n            assert type(np.array(structure)[:, 0][i]) == str, 'The first position must be element symbol'\n            assert len(np.array(structure)[:, 1][i]) == 3, 'The second position represents coordinate ' \\\n                                                           'of particle: x, y, z'\n        geo = structure\n    elif structure is None:\n        assert file[-4:] == '.xyz', 'The file is supposed to be .xyz'\n        geo = []\n        with open(file) as f:\n            for line in f.readlines()[2:]:\n                one_geo = []\n\n                symbol, x, y, z = line.split()\n                one_geo.append(symbol)\n                one_geo.append([float(x), float(y), float(z)])\n                geo.append(one_geo)\n\n    return geo\n\n\ndef get_molecular_data(\n    geometry,\n    charge=0,\n    multiplicity=1,\n    basis='sto-3g',\n    method='scf',\n    if_save=True,\n    if_print=True,\n    name=\"\",\n    file_path=\".\"\n):\n    r\"\"\"计算分子的必要信息，包括单体积分（one-body integrations）和双体积分（two-body integrations），\n    以及用选定的方法计算基态的能量。\n\n    Args:\n        geometry (str): 分子的几何信息\n        charge (int, optional): 分子的电荷，默认值为 0\n        multiplicity (int, optional): 分子的多重度，默认值为 1\n        basis (str, optional): 常用的基组是 ``'sto-3g'`` 、 ``'6-31g'`` 等，默认的基组是 ``'sto-3g'``，更多的基组选择可以参考网站\n            https://psicode.org/psi4manual/master/basissets_byelement.html#apdx-basiselement\n        method (str, optional): 用于计算基态能量的方法，包括 ``'scf'`` 和 ``'fci'`` ，默认方法为 ``'scf'``\n        if_save (bool, optional): 是否需要将分子信息存储成 .hdf5 文件，默认为 ``True``\n        if_print (bool, optional): 是否需要打印出选定方法 (method) 计算出的分子基态能量，默认为 ``True``\n        name (str, optional): 命名储存的文件，默认为 ``\"\"``\n        file_path (str, optional): 文件的储存路径，默认为 ``\".\"``\n\n    Returns:\n        MolecularData: 包含分子所有信息的类\n    \"\"\"\n    methods = ['scf', 'fci']\n    assert method in methods, 'We provide 2 methods: scf and fci'\n\n    if if_save is True:\n        path = file_path + '/qchem_data/'\n        folder = os.path.exists(path)\n        if not folder:\n            os.makedirs(path)\n        if name == \"\":\n            elements = np.array(geometry)[:, 0]\n            symbol, counts = np.unique(elements, return_counts=True)\n            filename = path\n            for i in range(len(symbol)):\n                filename += symbol[i]+str(counts[i])+'_'\n            filename += basis + '_' + method + '.hdf5'\n        else:\n            if name[-5:] == '.hdf5':\n                filename = name\n            else:\n                filename = name + '.hdf5'\n\n    molecule = MolecularData(geometry,\n                             basis=basis,\n                             multiplicity=multiplicity,\n                             charge=charge,\n                             filename=filename)\n\n    _run_psi4(molecule,\n              charge,\n              multiplicity,\n              method,\n              basis,\n              if_print,\n              if_save)\n\n    return molecule\n\n\ndef active_space(electrons,\n                 orbitals,\n                 multiplicity=1,\n                 active_electrons=None,\n                 active_orbitals=None):\n    r\"\"\"对于给定的活跃电子和活跃轨道计算相应的活跃空间（active space）。\n\n    Args:\n        electrons (int): 电子数\n        orbitals (int): 轨道数\n        multiplicity (int, optional): 自旋多重度\n        active_electrons (int, optional): 活跃 (active) 电子数，默认情况为所有电子均为活跃电子\n        active_orbitals (int, optional): 活跃 (active) 轨道数，默认情况为所有轨道均为活跃轨道\n\n    Returns:\n        tuple: 核心轨道和活跃轨道的索引\n    \"\"\"\n    assert type(electrons) == int and electrons > 0, 'Number of electrons must be positive integer.'\n    assert type(orbitals) == int and orbitals > 0, 'Number of orbitals must be positive integer.'\n    assert type(multiplicity) == int and multiplicity >= 0, 'The multiplicity must be non-negative integer.'\n\n    if active_electrons is None:\n        no_core_orbitals = 0\n        core_orbitals = []\n    else:\n        assert type(active_electrons) == int, 'The number of active electrons must be integer.'\n        assert active_electrons > 0, 'The number of active electrons must be greater than 0.'\n        assert electrons >= active_electrons, 'The number of electrons should more than or equal ' \\\n                                              'to the number of active electrons.'\n        assert active_electrons >= multiplicity - 1, 'The number of active electrons should greater than ' \\\n                                                     'or equal to multiplicity - 1.'\n        assert multiplicity % 2 != active_electrons % 2, 'Mulitiplicity and active electrons should be one odd ' \\\n                                                         'and the other one even.'\n\n        no_core_orbitals = (electrons - active_electrons) // 2\n        core_orbitals = list(np.arange(0, no_core_orbitals))\n\n    if active_orbitals is None:\n        active_orbitals = list(np.arange(no_core_orbitals, orbitals))\n    else:\n        assert type(active_orbitals) == int, 'The number of active orbitals must be integer.'\n        assert active_orbitals > 0, 'The number of active orbitals must be greater than 0.'\n        assert no_core_orbitals + active_orbitals <= orbitals, 'The summation of core orbitals and active ' \\\n                                                               'orbitals should be smaller than orbitals.'\n        assert no_core_orbitals + active_orbitals > (electrons + multiplicity - 1) / 2, \\\n            'The summation of core orbitals and active orbitals should be greater than ' \\\n            '(electrons + multiplicity - 1)/2.'\n\n        active_orbitals = list(np.arange(no_core_orbitals, no_core_orbitals + active_orbitals))\n\n    return core_orbitals, active_orbitals\n\n\ndef fermionic_hamiltonian(molecule,\n                          filename=None,\n                          multiplicity=1,\n                          active_electrons=None,\n                          active_orbitals=None):\n    r\"\"\"计算给定分子的费米哈密顿量。\n\n    Args:\n        molecule (MolecularData): 包含分子所有信息的类\n        filename (str, optional): 分子的 .hdf5 文件的路径\n        multiplicity (int, optional): 自旋多重度\n        active_electrons (int, optional): 活跃 (active) 电子数，默认情况为所有电子均为活跃电子\n        active_orbitals (int, optional): 活跃 (active) 轨道数，默认情况为所有轨道均为活跃轨道\n\n    Returns:\n        openfermion.ops.operators.qubit_operator.QubitOperator: openfermion 格式的哈密顿量\n    \"\"\"\n    if molecule is None:\n        assert type(filename) == str, 'Please provide the path of .hdf5 file.'\n        assert filename[-5:] == '.hdf5', 'The filename is supposed to be .hdf5 file'\n        molecule = MolecularData(filename=filename)\n    core_orbitals, active_orbitals = active_space(\n        molecule.n_electrons,\n        molecule.n_orbitals,\n        multiplicity,\n        active_electrons,\n        active_orbitals)\n    terms_molecular_hamiltonian = molecule.get_molecular_hamiltonian(\n        occupied_indices=core_orbitals, active_indices=active_orbitals\n    )\n    fermionic_hamiltonian = openfermion.transforms.get_fermion_operator(terms_molecular_hamiltonian)\n\n    return fermionic_hamiltonian\n\n\ndef spin_hamiltonian(molecule,\n                     filename=None,\n                     multiplicity=1,\n                     mapping_method='jordan_wigner',\n                     active_electrons=None,\n                     active_orbitals=None):\n    r\"\"\"生成 Paddle Quantum 格式的哈密顿量\n\n    Args:\n        molecule (openfermion.ops.operators.qubit_operator.QubitOperator): openfermion 格式的哈密顿量\n        filename (str, optional): 分子的 .hdf5 文件的路径\n        multiplicity (int, optional): 自旋多重度\n        mapping_method (str, optional): 映射方法，这里默认为 ``'jordan_wigner'`` ，此外还提供 ``'bravyi_kitaev'``\n        active_electrons (int, optional): 活跃 (active) 电子数，默认情况为所有电子均为活跃电子\n        active_orbitals (int, optional): 活跃 (active) 轨道数默认情况为所有轨道均为活跃轨道\n\n    Returns:\n        paddle_quantum.utils.Hamiltonian: Paddle Quantum 格式的哈密顿量\n    \"\"\"\n    assert mapping_method in ['jordan_wigner', 'bravyi_kitaev'], \"Please choose the mapping \" \\\n                                                                 \"in ['jordan_wigner', 'bravyi_kitaev'].\"\n    fermionic_h = fermionic_hamiltonian(molecule,\n                                        filename,\n                                        multiplicity,\n                                        active_electrons,\n                                        active_orbitals)\n\n    if mapping_method == 'jordan_wigner':\n        spin_h = transforms.jordan_wigner(fermionic_h)\n    elif mapping_method == 'bravyi_kitaev':\n        spin_h = transforms.bravyi_kitaev(fermionic_h)\n    return _hamiltonian_transformation(spin_h, tol=1e-8)\n", "meta": {"hexsha": "2e5a54fa29ac97b0008e8b4b65a9843d6feef787", "size": 15486, "ext": "py", "lang": "Python", "max_stars_repo_path": "paddle_quantum/qchem.py", "max_stars_repo_name": "gsq7474741/Quantum", "max_stars_repo_head_hexsha": "16e7d3bf2dba7e94e6faf5c853faf0e913e1f268", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-14T14:10:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-14T14:10:23.000Z", "max_issues_repo_path": "paddle_quantum/qchem.py", "max_issues_repo_name": "gsq7474741/Quantum", "max_issues_repo_head_hexsha": "16e7d3bf2dba7e94e6faf5c853faf0e913e1f268", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paddle_quantum/qchem.py", "max_forks_repo_name": "gsq7474741/Quantum", "max_forks_repo_head_hexsha": "16e7d3bf2dba7e94e6faf5c853faf0e913e1f268", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7707317073, "max_line_length": 114, "alphanum_fraction": 0.6007361488, "include": true, "reason": "import numpy", "num_tokens": 4421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.193924900544656}}
{"text": "from warnings import warn\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\n\nfrom astropy.nddata import CCDData, StdDevUncertainty\nfrom astropy.table import Table\nfrom astropy.io import fits\nimport ccdproc\nfrom ccdproc import combine, trim_image\n\nfrom .filemgmt import load_if_exists, make_summary\nfrom .ccdutil import CCDData_astype, load_ccd\nfrom .misc import chk_keyval\n\n__all__ = [\"sstd\", \"weighted_mean\", \"stack_FITS\", \"combine_ccd\"]\n\n\ndef sstd(a, **kwargs):\n    ''' Sample standard deviation function\n    '''\n    return np.std(a, ddof=1, **kwargs)\n\n\n# FIXME: Add this to Ccdproc esp. for mem_limit\ndef weighted_mean(ccds, unit='adu'):\n    datas = []\n    ws = []  # weights = 1 / sigma**2\n    for ccd in ccds:\n        datas.append(ccd.data)\n        ws.append(1 / ccd.uncertainty.array**2)\n    wmean = np.average(np.array(datas), axis=0, weights=ws)\n    wuncert = np.sqrt(1 / np.sum(np.array(ws), axis=0))\n    nccd = CCDData(data=wmean, header=ccds[0].header, unit=unit)\n    nccd.uncertainty = StdDevUncertainty(wuncert)\n    return nccd\n\n\ndef group_FITS(summary_table, type_key=None, type_val=None, group_key=None):\n    ''' Organize the group_by and type_key for stack_FITS\n    Parameters\n    ----------\n    summary_table: pandas.DataFrame or astropy.table.Table\n        The table which contains the metadata (header) of files. If it\n        is in the astropy table format, it will be converted to\n        `~pandas.DataFrame` object.\n\n    type_key, type_val: None, str, list of str, optional\n        The header keyword for the ccd type, and the value you want to\n        match.\n\n    group_key : None, str, list of str, optional\n        The header keyword which will be used to make groups for the\n        CCDs that have selected from ``type_key`` and ``type_val``. If\n        ``None`` (default), no grouping will occur, but it will return\n        the `~pandas.DataFrameGroupBy` object will be returned for the\n        sake of consistency.\n\n    Return\n    ------\n    grouped : ~pandas.DataFrameGroupBy\n        The table after the grouping process.\n\n    group_type_key : list of str\n        The ``type_key`` that can directly be used for ``stack_FITS``\n        for each element of ``grouped.groups``.\n        Basically this is ``type_key + group_key``.\n\n    Example\n    -------\n    >>> allfits = list(Path('.').glob(\"*.fits\"))\n    >>> summary_table = make_summary(allfits)\n    >>> type_key = [\"OBJECT\"]\n    >>> type_val = [\"dark\"]\n    >>> group_key = [\"EXPTIME\"]\n    >>> gs, g_key = group_FITS(summary_table,\n    ...                        type_key,\n    ...                        type_val,\n    ...                        group_key)\n    >>> for g_val, group in gs:\n    >>>     _ = combine_ccd(group[\"file\"],\n    ...                     type_key=g_key,\n    ...                     type_val=g_val)\n    '''\n    if ((not isinstance(summary_table, Table))\n            and (not isinstance(summary_table, pd.DataFrame))):\n        raise TypeError(\"summary_table must be an astropy Table or Pandas \"\n                        + f\"DataFrame. It's now {type(summary_table)}.\")\n    elif isinstance(summary_table, Table):\n        st = summary_table.to_pandas()\n    else:\n        st = summary_table.copy()\n\n    type_key, type_val, group_key = chk_keyval(type_key=type_key,\n                                               type_val=type_val,\n                                               group_key=group_key)\n\n    if len(group_key + type_key) == 0:\n        raise ValueError(\"At least one of type_key and group_key should not \"\n                         + \"be empty!\")\n\n    # For simplicity, crop the original data by type_key and type_val first.\n    for k, v in zip(type_key, type_val):\n        st = st[st[k] == v]\n\n    group_type_key = type_key + group_key\n    grouped = st.groupby(group_key)\n\n    return grouped, group_type_key\n\n\ndef stack_FITS(fitslist=None, summary_table=None, extension=0,\n               unit='adu', table_filecol=\"file\", trim_fits_section=None,\n               loadccd=True, type_key=None, type_val=None):\n    ''' Stacks the FITS files specified in fitslist\n    Parameters\n    ----------\n    fitslist: None, list of path-like, or list of CCDData\n        The list of path to FITS files or the list of CCDData to be\n        stacked. It is useful to give list of CCDData if you have\n        already stacked/loaded FITS file into a list by your own\n        criteria. If ``None`` (default), you must give ``fitslist`` or\n        ``summary_table``. If it is not ``None``, this function will do\n        very similar job to that of ``ccdproc.combine``. Although it is\n        not a good idea, a mixed list of CCDData and paths to the files\n        is also acceptable.\n\n    summary_table: None, pandas.DataFrame or astropy.table.Table\n        The table which contains the metadata of files. If there are\n        many FITS files and you want to use stacking many times, it is\n        better to make a summary table by ``filemgmt.make_summary`` and\n        use that instead of opening FITS files' headers every time you\n        call this function. If you want to use ``summary_table`` instead\n        of ``fitslist`` and have set ``loadccd=True``, you must not have\n        ``None`` or ``NaN`` value in the\n        ``summary_table[table_filecol]``.\n\n    extension: int or str\n        The extension of FITS to be stacked. For single extension, set\n        it as 0.\n\n    unit: Unit or str, optional\n        The unit of the CCDs to be loaded.\n        Used only when ``fitslist`` is not a list of ``CCDData`` and\n        ``loadccd`` is ``True``.\n\n    table_filecol: str\n        The column name of the ``summary_table`` which contains the path\n        to the FITS files.\n\n    trim_fits_section : str or None, optional\n        The ``fits_section`` of ``ccdproc.trim_image``. Region of\n        ``ccd`` from which the overscan is extracted; see\n        `~ccdproc.subtract_overscan` for details.\n        Default is ``None``.\n\n    loadccd: bool, optional\n        Whether to return file paths or loaded CCDData. If ``False``, it\n        is a function to select FITS files using ``type_key`` and\n        ``type_val`` without using much memory.\n        This is ignored if ``fitslist`` is given and composed of\n        ``CCDData`` objects.\n\n    type_key, type_val: str, list of str\n        The header keyword for the ccd type, and the value you want to\n        match.\n\n    Return\n    ------\n    matched: list of Path or list of CCDData\n        list containing Path to files if ``loadccd`` is ``False``.\n        Otherwise it is a list containing loaded CCDData after loading\n        the files. If ``ccdlist`` is given a priori, list of CCDData\n        will be returned regardless of ``loadccd``.\n    '''\n    def _parse_val(value):\n        val = str(value)\n        if val.lstrip('+-').isdigit():  # if int\n            result = int(val)\n        else:\n            try:\n                result = float(val)\n            except ValueError:\n                result = str(val)\n        return result\n\n    def _check_mismatch(row):\n        mismatch = False\n        for k, v in zip(type_key, type_val):\n            hdr_val = _parse_val(row[k])\n            parse_v = _parse_val(v)\n            if (hdr_val != parse_v):\n                mismatch = True\n                break\n        return mismatch\n\n    if ((fitslist is not None) + (summary_table is not None) != 1):\n        raise ValueError(\"One and only one of fitslist or summary_table must \"\n                         + \"be not None.\")\n\n    # If fitslist\n    if fitslist is not None:\n        table_mode = False\n        try:\n            fitslist = list(fitslist)\n        except TypeError:\n            raise TypeError(\"fitslist must be convertable to list. \"\n                            + f\"It's now {type(fitslist)}.\")\n\n    # If summary_table\n    if summary_table is not None:\n        table_mode = True\n        if ((not isinstance(summary_table, Table))\n                and (not isinstance(summary_table, pd.DataFrame))):\n            raise TypeError(\"summary_table must be an astropy Table or Pandas \"\n                            + f\"DataFrame. It's now {type(summary_table)}.\")\n\n    # Check for type_key and type_val\n    type_key, type_val, _ = chk_keyval(type_key=type_key,\n                                       type_val=type_val,\n                                       group_key=None)\n\n    # Setting whether to group\n    grouping = False\n    if len(type_key) > 0:\n        grouping = True\n\n    print(\"Analyzing FITS... \", end='')\n    # Set fitslist and summary_table based on the given input and grouping.\n    if table_mode:\n        if isinstance(summary_table, Table):\n            summary_table = summary_table.to_pandas()\n        fitslist = summary_table[table_filecol].tolist()\n    else:\n        if grouping:\n            summary_table = make_summary(fitslist,\n                                         extension=extension,\n                                         verbose=True,\n                                         fname_option='relative',\n                                         keywords=type_key,\n                                         sort_by=None,\n                                         pandas=True)\n        # else: no need to make summary_table.\n\n    print(\"Done\", end='')\n\n    if loadccd:\n        print(\" and loading FITS... \")\n    else:\n        print(\".\")\n\n    matched = []\n\n    # Append appropriate CCDs or filepaths to matched\n    if grouping:  # summary_table is used.\n        for i, row in summary_table.iterrows():\n            mismatch = _check_mismatch(row)\n            if mismatch:  # skip this row (file)\n                continue\n\n            # if not skipped:\n            # TODO: Is it better to remove Path here?\n            if isinstance(fitslist[i], CCDData):\n                matched.append(fitslist[i])\n            else:  # it must be a path to the file\n                fpath = Path(fitslist[i])\n                if loadccd:\n                    ccd_i = load_ccd(fpath, extension=extension, unit=unit)\n                    if trim_fits_section is not None:\n                        ccd_i = trim_image(ccd_i,\n                                           fits_section=trim_fits_section)\n                    matched.append(ccd_i)\n                else:\n                    matched.append(fpath)\n    else:  # summary_table is not used.\n        for item in fitslist:\n            if isinstance(item, CCDData):\n                matched.append(item)\n            else:\n                if loadccd:\n                    ccd_i = load_ccd(item, extension=extension, unit=unit)\n                    if trim_fits_section is not None:\n                        ccd_i = trim_image(\n                            ccd_i, fits_section=trim_fits_section)\n                    matched.append(ccd_i)\n                else:  # TODO: Is is better to remove Path here?\n                    matched.append(Path(item))\n\n    # Generate warning OR information messages\n    if len(matched) == 0:\n        if grouping:\n            warn('No FITS file had \"{:s} = {:s}\"'.format(str(type_key),\n                                                         str(type_val))\n                 + \"Maybe int/float/str confusing?\")\n        else:\n            warn('No FITS file found')\n    else:\n        if grouping:\n            N = len(matched)\n            ks = str(type_key)\n            vs = str(type_val)\n            if loadccd:\n                print(f'{N} FITS files with \"{ks} = {vs}\" are loaded.')\n            else:\n                print(f'{N} FITS files with \"{ks} = {vs}\" are selected.')\n        else:\n            if loadccd:\n                print('{:d} FITS files are loaded.'.format(len(matched)))\n\n    return matched\n\n\ndef combine_ccd(fitslist=None, summary_table=None, table_filecol=\"file\",\n                trim_fits_section=None, output=None, unit='adu',\n                subtract_frame=None, combine_method='median',\n                reject_method=None, normalize_exposure=False,\n                normalize_average=False,\n                exposure_key='EXPTIME', mem_limit=2e9,\n                combine_uncertainty_function=None,\n                extension=0, type_key=None, type_val=None,\n                dtype=\"float32\", uncertainty_dtype=\"float32\",\n                output_verify='fix', overwrite=False,\n                verbose=True, **kwargs):\n    ''' Combining images\n    Slight variant from ccdproc.\n    # TODO: accept the input like ``sigma_clip_func='median'``, etc.\n    Parameters\n    ----------\n    fitslist: path-like, list of path-like, or list of CCDData\n        The list of path to FITS files or the list of CCDData to be\n        stacked. It is useful to give list of CCDData if you have\n        already stacked/loaded FITS file into a list by your own\n        criteria. If ``None`` (default), you must give ``fitslist`` or\n        ``summary_table``. If it is not ``None``, this function will do\n        very similar job to that of ``ccdproc.combine``. Although it is\n        not a good idea, a mixed list of CCDData and paths to the files\n        is also acceptable.\n\n    summary_table: pandas.DataFrame or astropy.table.Table\n        The table which contains the metadata of files. If there are\n        many FITS files and you want to use stacking many times, it is\n        better to make a summary table by ``filemgmt.make_summary`` and\n        use that instead of opening FITS files' headers every time you\n        call this function. If you want to use ``summary_table`` instead\n        of ``fitslist`` and have set ``loadccd=True``, you must not have\n        ``None`` or ``NaN`` value in the\n        ``summary_table[table_filecol]``.\n\n    table_filecol: str\n        The column name of the ``summary_table`` which contains the path\n        to the FITS files.\n\n    trim_fits_section : str or None, optional\n        The ``fits_section`` of ``ccdproc.trim_image``. Region of\n        ``ccd`` from which the overscan is extracted; see\n        `~ccdproc.subtract_overscan` for details.\n        Default is ``None``.\n\n    output : path-like or None, optional.\n        The path if you want to save the resulting ``ccd`` object.\n        Default is ``None``.\n\n    unit : `~astropy.units.Unit` or str, optional.\n        The units of the data.\n        Default is ``'adu'``.\n\n    subtract_frame : array-like, optional.\n        The frame you want to subtract from the image after the\n        combination. It can be, e.g., dark frame, because it is easier\n        to calculate Poisson error before the dark subtraction and\n        subtract the dark later.\n        TODO: This maybe unnecessary.\n        Default is ``None``.\n\n    combine_method : str or None, optinal.\n        The ``method`` for ``ccdproc.combine``, i.e., {'average',\n        'median', 'sum'}\n        Default is ``None``.\n\n    reject_method : str\n        Made for simple use of ``ccdproc.combine``, [None, 'minmax',\n        'sigclip' == 'sigma_clip', 'extrema' == 'ext']. Automatically\n        turns on the option, e.g., ``clip_extrema = True`` or\n        ``sigma_clip = True``. Leave it blank for no rejection.\n        Default is ``None``.\n\n    normalize_exposure : bool, optional.\n        Whether to normalize the values by the exposure time of each\n        frame before combining.\n        Default is ``False``.\n\n    normalize_average : bool, optional.\n        Whether to normalize the values by the average value of each\n        frame before combining.\n        Default is ``False``.\n\n    exposure_key : str, optional\n        The header keyword for the exposure time.\n        Default is ``\"EXPTIME\"``.\n\n    combine_uncertainty_function : callable, None, optional\n        The uncertainty calculation function of ``ccdproc.combine``. If\n        ``None`` use the default uncertainty func when using average,\n        median or sum combine, otherwise use the function provided.\n        Default is ``None``.\n\n    extension: int or str, optional\n        The extension to be used.\n        Default is ``0``.\n\n    dtype : str or `numpy.dtype` or None, optional\n        Allows user to set dtype. See `numpy.array` ``dtype`` parameter\n        description. If ``None`` it uses ``np.float64``.\n        Default is ``None``.\n\n    type_key, type_val: str, list of str\n        The header keyword for the ccd type, and the value you want to\n        match. For an open HDU named ``hdu``, e.g., only the files which\n        satisfies ``hdu[extension].header[type_key] == type_val`` among\n        all the ``fitslist`` will be used.\n\n    output_verify : str\n        Output verification option.  Must be one of ``\"fix\"``,\n        ``\"silentfix\"``, ``\"ignore\"``, ``\"warn\"``, or ``\"exception\"``.\n        May also be any combination of ``\"fix\"`` or ``\"silentfix\"`` with\n        ``\"+ignore\"``, ``+warn``, or ``+exception\" (e.g.\n        ``\"fix+warn\"``).  See the astropy documentation below:\n        http://docs.astropy.org/en/stable/io/fits/api/verification.html#verify\n\n    mem_limit : float, optional\n        Maximum memory which should be used while combining (in bytes).\n        Default is ``2.e9``.\n\n    **kwarg:\n        kwargs for the ``ccdproc.combine``. See its documentation. This\n        includes (RHS are the default values)\n        ```\n        weights=None,\n        scale=None,\n        mem_limit=16000000000.0,\n        clip_extrema=False,\n        nlow=1,\n        nhigh=1,\n        minmax_clip=False,\n        minmax_clip_min=None,\n        minmax_clip_max=None,\n        sigma_clip=False,\n        sigma_clip_low_thresh=3,\n        sigma_clip_high_thresh=3,\n        sigma_clip_func=<numpy.ma.core._frommethod instance>,\n        sigma_clip_dev_func=<numpy.ma.core._frommethod instance>,\n        combine_uncertainty_function=None, **ccdkwargs\n        ```\n\n    Returns\n    -------\n    master: astropy.nddata.CCDData\n        Resulting combined ccd.\n    '''\n    def _set_reject_method(reject_method):\n        ''' Convenience function for ccdproc.combine reject switches\n        '''\n        clip_extrema, minmax_clip, sigma_clip = False, False, False\n\n        if reject_method in ['extrema', 'ext']:\n            clip_extrema = True\n        elif reject_method in ['minmax']:\n            minmax_clip = True\n        elif reject_method in ['sigma_clip', 'sigclip']:\n            sigma_clip = True\n        else:\n            if reject_method not in [None, 'no']:\n                raise KeyError(\"reject must be one in [None, 'minmax', \"\n                               + \"'sigclip'=='sigma_clip', 'extrema'=='ext']\")\n\n        return clip_extrema, minmax_clip, sigma_clip\n\n    def _print_info(combine_method, Nccd, reject_method, **kwargs):\n        if reject_method is None:\n            reject_method = 'no'\n\n        info_str = ('\"{:s}\" combine {:d} images by \"{:s}\" rejection')\n\n        print(info_str.format(combine_method, Nccd, reject_method))\n        print(dict(**kwargs))\n        return\n\n    # def _normalize_exptime(ccdlist, exposure_key):\n    #     _ccdlist = ccdlist.copy()\n    #     exptimes = []\n\n    #     for i in range(len(_ccdlist)):\n    #         exptime = _ccdlist[i].header[exposure_key]\n    #         exptimes.append(exptime)\n    #         _ccdlist[i] = _ccdlist[i].divide(exptime)\n\n    #     if verbose:\n    #         if len(np.unique(exptimes)) != 1:\n    #             print('There are more than one exposure times:\\n\\t', end=' ')\n    #             print(np.unique(exptimes), end=' ')\n    #             print('seconds')\n    #         print(f'Normalized images by exposure time (\"{exposure_key}\").')\n\n    #     return _ccdlist\n\n    def _add_and_print(s, header, verbose):\n        header.add_history(s)\n        if verbose:\n            print(s)\n    # Give only one\n    if ((fitslist is not None) + (summary_table is not None) != 1):\n        raise ValueError(\n            \"One and only one of [fitslist, summary_table] must be given.\")\n\n    # If fitslist\n    if fitslist is not None:\n        try:\n            fitslist = list(fitslist)\n        except TypeError:\n            raise TypeError(\"fitslist must be convertable to list. \"\n                            + f\"It's now {type(fitslist)}.\")\n\n    # If summary_table\n    if summary_table is not None:\n        if ((not isinstance(summary_table, Table))\n                and (not isinstance(summary_table, pd.DataFrame))):\n            raise TypeError(\"summary_table must be an astropy Table or Pandas \"\n                            + f\"DataFrame. It's now {type(summary_table)}.\")\n\n    # Check for type_key and type_val\n    if ((type_key is None) ^ (type_val is None)):\n        raise ValueError(\n            \"type_key and type_val must be both specified or both None.\")\n\n    if (output is not None) and (Path(output).exists()):\n        if overwrite:\n            print(f\"{output} already exists:\\n\\tBut will be overridden.\")\n        else:\n            print(f\"{output} already exists:\")\n            return load_if_exists(output, loader=CCDData.read, if_not=None)\n\n    # Do we really need to accept all three of normalize & scale?\n    # if scale is None:\n    #     scale = np.ones(len(ccdlist))\n    if (((normalize_average) + (normalize_exposure)) > 1):\n        raise ValueError(\"Only up to one of [normalize_average, \"\n                         + \"normalize_exposure] must be not None.\")\n\n    # Set history messages\n    str_history = ('{:d} images with {:s} = {:s} are \"{:s}\" combined '\n                   + 'using \"{:s}\" rejection (additional kwargs: {})')\n    str_nexp = \"Each frame normalized by exposure time before combination.\"\n    str_navg = \"Each frame normalized by average value before combination.\"\n    str_subt = \"Subtracted a user-provided frame\"\n    str_trim = \"Trim by FITS section {}\"\n\n    if reject_method is None:\n        reject_method = 'no'\n\n    # Select CCDs by\n    ccdlist = stack_FITS(fitslist=fitslist,\n                         summary_table=summary_table,\n                         table_filecol=table_filecol,\n                         extension=extension,\n                         unit=unit,\n                         type_key=type_key,\n                         type_val=type_val,\n                         loadccd=False)\n    #  trim_fits_section=trim_fits_section,\n    # loadccd=False: Loading CCD here may cause memory blast...\n\n    try:\n        header = ccdlist[0].header\n    except AttributeError:\n        header = fits.getheader(ccdlist[0])\n\n    if verbose:\n        _print_info(combine_method=combine_method,\n                    Nccd=len(ccdlist),\n                    reject_method=reject_method,\n                    dtype=dtype,\n                    **kwargs)\n\n    scale = None\n    # Normalize by exposure\n    if normalize_exposure:\n        tmp = make_summary(fitslist=fitslist,\n                           keywords=[exposure_key],\n                           verbose=False,\n                           sort_by=None)\n        exptimes = tmp[exposure_key].tolist()\n        scale = 1 / np.array(exptimes)\n        _add_and_print(str_nexp, header, verbose)\n\n    # Normalize by pixel average\n    if normalize_average:\n        def invavg(a):\n            return 1 / np.mean(a)\n        scale = invavg\n        _add_and_print(str_navg, header, verbose)\n\n    # Set rejection switches\n    clip_extrema, minmax_clip, sigma_clip = _set_reject_method(reject_method)\n\n    if len(ccdlist) == 1:\n        if isinstance(ccdlist[0], CCDData):\n            master = ccdlist[0]\n        else:\n            master = load_ccd(ccdlist[0], extension=extension, unit=unit)\n    else:\n        master = combine(img_list=ccdlist,\n                         method=combine_method,\n                         clip_extrema=clip_extrema,\n                         minmax_clip=minmax_clip,\n                         sigma_clip=sigma_clip,\n                         mem_limit=mem_limit,\n                         combine_uncertainty_function=combine_uncertainty_function,\n                         unit=unit,\n                         hdu=extension,\n                         scale=scale,\n                         dtype=dtype,\n                         **kwargs)\n\n    ncombine = len(ccdlist)\n    header[\"COMBVER\"] = (ccdproc.__version__,\n                         \"ccdproc version used for combine.\")\n    header[\"NCOMBINE\"] = (ncombine, \"Number of combined images\")\n    header[\"COMBMETH\"] = (combine_method, \"Combining method\")\n\n    header.add_history(str_history.format(ncombine,\n                                          str(type_key),\n                                          str(type_val),\n                                          str(combine_method),\n                                          str(reject_method),\n                                          kwargs))\n\n    if subtract_frame is not None:\n        subtract = CCDData(subtract_frame.copy())\n        master.data = master.subtract(subtract).data\n        _add_and_print(str_subt, header, verbose)\n\n    if trim_fits_section is not None:\n        master = trim_image(master, fits_section=trim_fits_section)\n        _add_and_print(str_trim.format(trim_fits_section), header, verbose)\n\n    master.header = header\n    master = CCDData_astype(master, dtype=dtype,\n                            uncertainty_dtype=uncertainty_dtype)\n\n    if output is not None:\n        if verbose:\n            print(f\"Writing FITS to {output}... \", end='')\n        master.write(output, output_verify=output_verify, overwrite=overwrite)\n        if verbose:\n            print(\"Saved.\")\n\n    return master\n", "meta": {"hexsha": "5a1c277e0c5950becd15cc7b674a19e8509983f3", "size": 25201, "ext": "py", "lang": "Python", "max_stars_repo_path": "photometry/ysfitsutilpy/ysfitsutilpy/combutil.py", "max_stars_repo_name": "ysBach/IshiguroM_etal_155140_2005UD", "max_stars_repo_head_hexsha": "37e0768f2a9dd59b3d4041c37c104d2d57e037ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-31T19:39:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-31T19:39:40.000Z", "max_issues_repo_path": "photometry/ysfitsutilpy/ysfitsutilpy/combutil.py", "max_issues_repo_name": "ysBach/IshiguroM_etal_155140_2005UD", "max_issues_repo_head_hexsha": "37e0768f2a9dd59b3d4041c37c104d2d57e037ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "photometry/ysfitsutilpy/ysfitsutilpy/combutil.py", "max_forks_repo_name": "ysBach/IshiguroM_etal_155140_2005UD", "max_forks_repo_head_hexsha": "37e0768f2a9dd59b3d4041c37c104d2d57e037ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-26T08:19:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-26T08:19:49.000Z", "avg_line_length": 38.2412746586, "max_line_length": 83, "alphanum_fraction": 0.5793420896, "include": true, "reason": "import numpy,from astropy", "num_tokens": 5714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.1939248916063125}}
{"text": "import os\nimport warnings\nimport pdb\nimport sys\nimport shutil\nimport pandas as pd\nimport numpy as np\nimport time\nimport multiprocessing as mp\nimport astropy.coordinates as astroCoords\nimport astropy.units as u\nfrom kbmodpy import kbmod as kb\nfrom astropy.io import fits\nfrom astropy.wcs import WCS\nfrom sklearn.cluster import DBSCAN\nfrom skimage import measure\nfrom analysis_utils import Interface, PostProcess\n\nclass region_search:\n    \"\"\"\n    CLASS CURRENTLY DOES NOT WORK\n    \"\"\"\n    def __init__(self,v_guess,radius,num_obs):\n        \"\"\"\n        INPUT-\n            v_guess : float array\n                Initial object velocity guess. Given as an array or tuple.\n                Algorithm will search velocities within 'radius' of 'v_guess'\n            radius : float\n                radius in velocity space to search, centered around 'v_guess'\n            num_obs : int\n                The minimum number of observations required to keep the object\n        \"\"\"\n        self.v_guess = v_guess\n        self.radius = radius\n        self.num_obs = num_obs\n        return\n\n    def run_search(self, im_filepath, res_filepath, out_suffix, time_file,\n                   likelihood_level=10., mjd_lims=None):\n        # Initialize some values\n        start = time.time()\n\n        memory_error = False\n        # Load images to search\n        search,image_params = self.load_images(\n            im_filepath, time_file, mjd_lims=mjd_lims)\n\n        # Run the region search\n        # Save values in image_params for use in filter_results\n\n        print(\"Starting Search\")\n        print('---------------------------------------')\n        param_headers = (\"X Velocity Guess\",\"Y Velocity Guess\",\n                         \"Radius in velocity space\")\n        param_values = (*self.v_guess,self.radius)\n        for header, val in zip(param_headers, param_values):\n            print('%s = %.4f' % (header, val))\n        results = search.region_search(\n            *self.v_guess, self.radius, likelihood_level, int(self.num_obs))\n        duration = image_params['times'][-1]-image_params['times'][0]\n        # Convert the results to the grid formatting\n        grid_results = kb.region_to_grid(results,duration)\n        # Process the search results\n        keep = self.process_region_results(\n            search, image_params, res_filepath, likelihood_level, grid_results)\n        del(search)\n\n        # Cluster the results\n        #keep = self.filter_results(keep,image_params)\n\n        # Save the results\n        self.save_results(res_filepath, out_suffix, keep)\n\n        end = time.time()\n\n        del(keep)\n        return\n\n    def process_region_results(\n        self,search,image_params,res_filepath,likelihood_level,results):\n        \"\"\"\n        Processes results that are output by the gpu search.\n        \"\"\"\n\n        keep = {'stamps': [], 'new_lh': [], 'results': [], 'times': [],\n                'lc': [], 'final_results': []}\n\n        print('---------------------------------------')\n        print(\"Processing Results\")\n        print('---------------------------------------')\n        print('Starting pooling...')\n        pool = mp.Pool(processes=16)\n        print('Getting results...')\n\n        psi_curves = []\n        phi_curves = []\n        # print(results)\n        for line in results:\n            psi_curve, phi_curve = search.lightcurve(line)\n            psi_curves.append(np.array(psi_curve).flatten())\n            phi_curve = np.array(phi_curve).flatten()\n            phi_curve[phi_curve == 0.] = 99999999.\n            phi_curves.append(phi_curve)\n\n        keep_idx_results = pool.starmap_async(\n            return_indices,\n            zip(psi_curves, phi_curves, [j for j in range(len(psi_curves))]))\n        pool.close()\n        pool.join()\n        keep_idx_results = keep_idx_results.get()\n        if (len(keep_idx_results) < 1):\n            keep_idx_results = [(0,[-1],0.)]\n\n        if (len(keep_idx_results[0]) < 3):\n            keep_idx_results = [(0, [-1], 0.)]\n\n        for result_on in range(len(psi_curves)):\n\n            if keep_idx_results[result_on][1][0] == -1:\n                continue\n            elif len(keep_idx_results[result_on][1]) < 3:\n                continue\n            elif keep_idx_results[result_on][2] < likelihood_level:\n                continue\n            else:\n                keep_idx = keep_idx_results[result_on][1]\n                new_likelihood = keep_idx_results[result_on][2]\n                keep['results'].append(results[result_on])\n                keep['new_lh'].append(new_likelihood)\n                stamps = search.sci_stamps(results[result_on], 10)\n                stamp_arr = np.array(\n                    [np.array(stamps[s_idx]) for s_idx in keep_idx])\n                keep['stamps'].append(np.sum(stamp_arr, axis=0))\n                keep['lc'].append(\n                    (psi_curves[result_on]/phi_curves[result_on])[keep_idx])\n                keep['times'].append(image_params['mjd'][keep_idx])\n        print(len(keep['results']))\n        # Needed for compatibility with grid_search save functions\n        keep['final_results'] = range(len(keep['results']))\n\n        return(keep)\n\nclass run_search:\n    \"\"\"\n    This class runs the grid search for kbmod.\n    \"\"\"\n    def __init__(self, input_parameters):\n\n        \"\"\"\n        INPUT-\n            input_parameters : dictionary\n                Dictionary containing input parameters. Merged with the\n                defaults dictionary. MUST include 'im_filepath',\n                'res_filepath', and 'time_file'. These are the filepaths to the\n                image directory, results directory, and time file,\n                respectively. Should contain 'v_arr', and 'ang_arr', which are\n                lists containing the lower and upper velocity and angle limits.\n        \"\"\"\n\n        defaults = { # Mandatory values\n            'im_filepath':None, 'res_filepath':None, 'time_file':None,\n            # Suggested values\n            'v_arr':[92.,526.,256], 'ang_arr':[np.pi/15,np.pi/15,128], \n            # Optional values\n            'output_suffix':'search', 'mjd_lims':None, 'average_angle':None,\n            'do_mask':True, 'mask_num_images':2, 'mask_threshold':120.,\n            'lh_level':10., 'psf_val':1.4, 'num_obs':10, 'num_cores':30,\n            'visit_in_filename':[0,6], 'file_format':'{0:06d}.fits',\n            'sigmaG_lims':[25,75], 'chunk_size':500000, 'max_lh':1000.,\n            'filter_type':'clipped_sigmaG', 'center_thresh':0.00,\n            'peak_offset':[2.,2.], 'mom_lims':[35.5,35.5,2.0,0.3,0.3],\n            'stamp_type':'sum', 'eps':0.03, 'gpu_filter':False,\n            'do_clustering':True, 'do_stamp_filter':True,\n            'clip_negative':False, 'sigmaG_filter_type':'lh'\n        }\n        # Make sure input_parameters contains valid input options\n        for key, val in input_parameters.items():\n            if key in defaults:\n                defaults[key] = val\n            else:\n                warnings.warn('Key \"{}\" is not a valid option. It is being ignored.'.format(key))\n        self.config = defaults\n        #self.config = {**defaults, **input_parameters}\n        if (self.config['im_filepath'] is None):\n            raise ValueError('Image filepath not set')\n        if (self.config['res_filepath'] is None):\n            raise ValueError('Results filepath not set')\n        if (self.config['time_file'] is None):\n            raise ValueError('Time filepath not set')\n        return\n\n    def do_gpu_search(self, search, image_params, post_process):\n\n        # Run the grid search\n        # Set min and max values for angle and velocity\n        if self.config['average_angle'] == None:\n            average_angle = image_params['ec_angle']\n        else:\n            average_angle = self.config['average_angle']\n        ang_min = average_angle - self.config['ang_arr'][0]\n        ang_max = average_angle + self.config['ang_arr'][1]\n        vel_min = self.config['v_arr'][0]\n        vel_max = self.config['v_arr'][1]\n        image_params['ang_lims'] = [ang_min, ang_max]\n        image_params['vel_lims'] = [vel_min, vel_max]\n\n        search_start = time.time()\n        print(\"Starting Search\")\n        print('---------------------------------------')\n        param_headers = (\"Ecliptic Angle\", \"Min. Search Angle\",\n                         \"Max Search Angle\", \"Min Velocity\", \"Max Velocity\")\n        param_values = (image_params['ec_angle'], *image_params['ang_lims'],\n                        *image_params['vel_lims'])\n        for header, val in zip(param_headers, param_values):\n            print('%s = %.4f' % (header, val))\n        if self.config['gpu_filter']:\n            print('Using in-line GPU filtering methods', flush=True)\n            self.config['sigmaG_coeff'] = post_process._find_sigmaG_coeff(\n                self.config['sigmaG_lims'])\n            search.gpuFilter(\n                int(self.config['ang_arr'][2]), int(self.config['v_arr'][2]),\n                *image_params['ang_lims'], *image_params['vel_lims'],\n                int(self.config['num_obs']),\n                np.array(self.config['sigmaG_lims'])/100.0,\n                self.config['sigmaG_coeff'], self.config['mom_lims'],\n                self.config['lh_level'])\n        else:\n            search.gpu(\n                int(self.config['ang_arr'][2]), int(self.config['v_arr'][2]),\n                *image_params['ang_lims'], *image_params['vel_lims'],\n                int(self.config['num_obs']))\n        print(\n            'Search finished in {0:.3f}s'.format(time.time()-search_start),\n            flush=True)\n        return(search, image_params)\n\n    def run_search(self):\n        \"\"\"\n        This function serves as the highest-level python interface for starting\n        a KBMOD search.\n        INPUT-\n            im_filepath : string\n                Path to the folder containing the images to be ingested into\n                KBMOD and searched over.\n            res_filepath : string\n                Path to the folder that will contain the results from the\n                search.\n            out_suffix : string\n                Suffix to append to the output files. Used to differentiate\n                between different searches over the same stack of images.\n            time_file : string\n                Path to the file containing the image times.\n            lh_level : float\n                Minimum acceptable likelihood level for a trajectory.\n                Trajectories with likelihoods below this value will be\n                discarded.\n            psf_val : float\n                Determines the size of the psf generated by the kbmod stack.\n            mjd_lims : numpy array\n                Limits the search to images taken within the limits input by\n                mjd_lims.\n            average_angle : float\n                Overrides the ecliptic angle calculation and instead centers\n                the average search around average_angle.\n        \"\"\"\n\n        start = time.time()\n        kb_interface = Interface()\n        kb_post_process = PostProcess(self.config)\n\n        # Load images to search\n        stack,image_params = kb_interface.load_images(\n            self.config['im_filepath'], self.config['time_file'],\n            self.config['mjd_lims'], self.config['visit_in_filename'],\n            self.config['file_format'])\n        # Save values in image_params for later use\n        if self.config['do_mask']:\n            stack = kb_post_process.apply_mask(\n                stack, mask_num_images=self.config['mask_num_images'],\n                mask_threshold=self.config['mask_threshold'])\n        psf = kb.psf(self.config['psf_val'])\n        search = kb.stack_search(stack, psf)\n\n        search, image_params = self.do_gpu_search(\n            search, image_params, kb_post_process)\n        # Load the KBMOD results into Python and apply a filter based on\n        # 'filter_type'\n        image_params['sigmaG_filter_type'] = self.config['sigmaG_filter_type']\n        keep = kb_post_process.load_results(\n            search, image_params, self.config['lh_level'],\n            chunk_size=self.config['chunk_size'], \n            filter_type=self.config['filter_type'],\n            max_lh=self.config['max_lh'])\n        if self.config['do_stamp_filter']:\n            keep = kb_post_process.apply_stamp_filter(\n                keep, search, center_thresh=self.config['center_thresh'],\n                peak_offset=self.config['peak_offset'], \n                mom_lims=self.config['mom_lims'],\n                stamp_type=self.config['stamp_type'])\n        if self.config['do_clustering']:\n            keep = kb_post_process.apply_clustering(keep, image_params)\n        keep = kb_post_process.get_all_stamps(keep, search)\n        del(search)\n        # Save the results\n        kb_interface.save_results(\n        self.config['res_filepath'], self.config['output_suffix'], keep)\n        end = time.time()\n        del(keep)\n        print(\"Time taken for patch: \", end-start)\n", "meta": {"hexsha": "60d38010a6c03782a9d9dd3280cd8cd90abe39a1", "size": 12937, "ext": "py", "lang": "Python", "max_stars_repo_path": "analysis/run_search.py", "max_stars_repo_name": "fraserw/kbmod", "max_stars_repo_head_hexsha": "65d69746d1dd8de867f8da147d73c09439d28b41", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2018-07-23T11:39:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T17:15:42.000Z", "max_issues_repo_path": "analysis/run_search.py", "max_issues_repo_name": "fraserw/kbmod", "max_issues_repo_head_hexsha": "65d69746d1dd8de867f8da147d73c09439d28b41", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2017-06-19T22:55:41.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-15T02:49:39.000Z", "max_forks_repo_path": "analysis/run_search.py", "max_forks_repo_name": "fraserw/kbmod", "max_forks_repo_head_hexsha": "65d69746d1dd8de867f8da147d73c09439d28b41", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-07-23T11:39:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T18:43:02.000Z", "avg_line_length": 41.5980707395, "max_line_length": 97, "alphanum_fraction": 0.5827471593, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 2779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.19392488786241954}}
{"text": "import numpy as np\r\nimport tensorflow as tf\r\nfrom keras import backend as K\r\nfrom keras.backend import epsilon,clip,mean\r\nfrom nets.ious import box_ciou\r\n\r\n\r\n\r\nimport numpy as np\r\nfrom keras.backend import exp\r\nfrom keras.layers import Softmax\r\n\r\nimport math\r\n\r\n\r\ndef DRloss(targets, logits):\r\n    pos_lambda = 1\r\n    margin = 0.5\r\n    neg_lambda = 0.1 / math.log(3.5)\r\n    L = 6.\r\n    tau = 4.\r\n    # 标注相关信息\r\n    num_classes = logits.shape[1]\r\n    dtype = targets.dtype\r\n    device = targets.device\r\n    class_range = np.arange(1, num_classes + 1, dtype=dtype, device=device).unsqueeze(0)\r\n    t = targets.unsqueeze(1)\r\n    # 获得正负样本id\r\n    pos_ind = (t == class_range)\r\n    neg_ind = (t != class_range) * (t >= 0)\r\n    # 概率p使用sigmoid求得\r\n    pos_prob = logits[pos_ind].sigmoid()\r\n    neg_prob = logits[neg_ind].sigmoid()\r\n    # 对应于式(3.9)\r\n    neg_q = Softmax(neg_prob/neg_lambda, dim=0)\r\n    neg_dist = np.sum(neg_q * neg_prob)\r\n    # 论文中提到，如果图像中没有正样本，则正样本的P使用1代替\r\n    if pos_prob.numel() > 0:\r\n        # 对应于式(3.9)\r\n        pos_q = Softmax(-pos_prob/pos_lambda, dim=0)\r\n        pos_dist = np.sum(pos_q * pos_prob)\r\n        # 对应于式(3.12)\r\n        loss = tau*np.log(1.+exp(L*(neg_dist - pos_dist+margin)))/L\r\n    else:\r\n        # 对应于式(3.12)\r\n        loss = tau*np.log(1.+exp(L*(neg_dist - 1. + margin)))/L\r\n    return loss\r\n\r\n\r\n#---------------------------------------------------#\r\n#   平滑标签\r\n#---------------------------------------------------#\r\ndef _smooth_labels(y_true, label_smoothing):\r\n    num_classes = tf.cast(K.shape(y_true)[-1], dtype=K.floatx())\r\n\r\n    label_smoothing = K.constant(label_smoothing, dtype=K.floatx())\r\n\r\n    return y_true * (1.0 - label_smoothing) + label_smoothing / num_classes\r\n\r\n\r\ndef focal(alpha=0.25, gamma=2.0):\r\n    def _focal(y_true, y_pred):\r\n        # y_true [batch_size, num_anchor, num_classes+1]\r\n        # y_pred [batch_size, num_anchor, num_classes]\r\n        labels         = y_true[:, :, :-1]\r\n        anchor_state   = y_true[:, :, -1]  # -1 是需要忽略的, 0 是背景, 1 是存在目标\r\n        classification = y_pred\r\n\r\n        # 找出存在目标的先验框\r\n        indices_for_object        = K.where(K.equal(anchor_state, 1))\r\n        labels_for_object         = K.gather_nd(labels, indices_for_object)\r\n        classification_for_object = K.gather_nd(classification, indices_for_object)\r\n\r\n        # 计算每一个先验框应该有的权重\r\n        alpha_factor_for_object = K.ones_like(labels_for_object) * alpha\r\n        alpha_factor_for_object = K.where(K.equal(labels_for_object, 1), alpha_factor_for_object, 1 - alpha_factor_for_object)\r\n        focal_weight_for_object = K.where(K.equal(labels_for_object, 1), 1 - classification_for_object, classification_for_object)\r\n        focal_weight_for_object = alpha_factor_for_object * focal_weight_for_object ** gamma\r\n\r\n        # 将权重乘上所求得的交叉熵\r\n        cls_loss_for_object = focal_weight_for_object * K.binary_crossentropy(labels_for_object, classification_for_object)\r\n\r\n        # 找出实际上为背景的先验框\r\n        indices_for_back        = K.where(K.equal(anchor_state, 0))\r\n        labels_for_back         = K.gather_nd(labels, indices_for_back)\r\n        classification_for_back = K.gather_nd(classification, indices_for_back)\r\n\r\n        # 计算每一个先验框应该有的权重\r\n        alpha_factor_for_back = K.ones_like(labels_for_back) * (1 - alpha)\r\n        focal_weight_for_back = classification_for_back\r\n        focal_weight_for_back = alpha_factor_for_back * focal_weight_for_back ** gamma\r\n\r\n        # 将权重乘上所求得的交叉熵\r\n        cls_loss_for_back = focal_weight_for_back * K.binary_crossentropy(labels_for_back, classification_for_back)\r\n\r\n        # 标准化，实际上是正样本的数量\r\n        normalizer = tf.where(K.equal(anchor_state, 1))\r\n        normalizer = K.cast(K.shape(normalizer)[0], K.floatx())\r\n        normalizer = K.maximum(K.cast_to_floatx(1.0), normalizer)\r\n\r\n        # 将所获得的loss除上正样本的数量\r\n        cls_loss_for_object = K.sum(cls_loss_for_object)\r\n        cls_loss_for_back = K.sum(cls_loss_for_back)\r\n\r\n        # 总的loss\r\n        loss = (cls_loss_for_object + cls_loss_for_back)/normalizer\r\n\r\n        return loss\r\n    return _focal\r\n\r\n\r\n\r\n\r\ndef binary_focal_loss(true_label,probs ):\r\n    gamma = 2\r\n    alpha = 0.25\r\n    alpha = tf.constant(alpha, dtype=tf.float32)\r\n    gamma = tf.constant(gamma, dtype=tf.float32)\r\n\r\n    epsilon = 1.e-8\r\n    # 得到y_true和y_pred\r\n    y_true = tf.one_hot(true_label, 2)\r\n    # probs = tf.nn.sigmoid(logits)\r\n    y_pred = tf.clip_by_value(probs, epsilon, 1. - epsilon)\r\n    # 得到调节因子weight和alpha\r\n    ## 先得到y_true和1-y_true的概率【这里是正负样本的概率都要计算哦！】\r\n    p_t = y_true * y_pred \\\r\n          + (tf.ones_like(y_true) - y_true) * (tf.ones_like(y_true) - y_pred)\r\n    ## 然后通过p_t和gamma得到weight\r\n    weight = tf.pow((tf.ones_like(y_true) - p_t), gamma)\r\n    ## 再得到alpha，y_true的是alpha，那么1-y_true的是1-alpha\r\n    alpha_t = y_true * alpha + (tf.ones_like(y_true) - y_true) * (1 - alpha)\r\n    # 最后就是论文中的公式，相当于：- alpha * (1-p_t)^gamma * log(p_t)\r\n    focal_loss = - alpha_t * weight * tf.log(p_t)\r\n    return tf.reduce_mean(focal_loss)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#---------------------------------------------------#\r\n#   将预测值的每个特征层调成真实值\r\n#---------------------------------------------------#\r\ndef yolo_head(feats, anchors, num_classes, input_shape, calc_loss=False):\r\n    num_anchors = len(anchors)\r\n    #---------------------------------------------------#\r\n    #   [1, 1, 1, num_anchors, 2]\r\n    #---------------------------------------------------#\r\n    anchors_tensor = K.reshape(K.constant(anchors), [1, 1, 1, num_anchors, 2])\r\n\r\n    #---------------------------------------------------#\r\n    #   获得x，y的网格\r\n    #   (13, 13, 1, 2)\r\n    #---------------------------------------------------#\r\n    grid_shape = K.shape(feats)[1:3]\r\n    grid_y = K.tile(K.reshape(K.arange(0, stop=grid_shape[0]), [-1, 1, 1, 1]),\r\n        [1, grid_shape[1], 1, 1])\r\n    grid_x = K.tile(K.reshape(K.arange(0, stop=grid_shape[1]), [1, -1, 1, 1]),\r\n        [grid_shape[0], 1, 1, 1])\r\n    grid = K.concatenate([grid_x, grid_y])\r\n    grid = K.cast(grid, K.dtype(feats))\r\n\r\n    #---------------------------------------------------#\r\n    #   将预测结果调整成(batch_size,13,13,3,85)\r\n    #   85可拆分成4 + 1 + 80\r\n    #   4代表的是中心宽高的调整参数\r\n    #   1代表的是框的置信度\r\n    #   80代表的是种类的置信度\r\n    #---------------------------------------------------#\r\n    feats = K.reshape(feats, [-1, grid_shape[0], grid_shape[1], num_anchors, num_classes + 5])\r\n\r\n    #---------------------------------------------------#\r\n    #   将预测值调成真实值\r\n    #   box_xy对应框的中心点\r\n    #   box_wh对应框的宽和高\r\n    #---------------------------------------------------#\r\n    box_xy = (K.sigmoid(feats[..., :2]) + grid) / K.cast(grid_shape[::-1], K.dtype(feats))\r\n    box_wh = K.exp(feats[..., 2:4]) * anchors_tensor / K.cast(input_shape[::-1], K.dtype(feats))\r\n    box_confidence = K.sigmoid(feats[..., 4:5])\r\n    box_class_probs = K.sigmoid(feats[..., 5:])\r\n\r\n    #---------------------------------------------------------------------#\r\n    #   在计算loss的时候返回grid, feats, box_xy, box_wh\r\n    #   在预测的时候返回box_xy, box_wh, box_confidence, box_class_probs\r\n    #---------------------------------------------------------------------#\r\n    if calc_loss == True:\r\n        return grid, feats, box_xy, box_wh\r\n    return box_xy, box_wh, box_confidence, box_class_probs\r\n\r\n\r\n#---------------------------------------------------#\r\n#   用于计算每个预测框与真实框的iou\r\n#---------------------------------------------------#\r\ndef box_iou(b1, b2):\r\n    # 13,13,3,1,4\r\n    # 计算左上角的坐标和右下角的坐标\r\n    b1 = K.expand_dims(b1, -2)\r\n    b1_xy = b1[..., :2]\r\n    b1_wh = b1[..., 2:4]\r\n    b1_wh_half = b1_wh/2.\r\n    b1_mins = b1_xy - b1_wh_half\r\n    b1_maxes = b1_xy + b1_wh_half\r\n\r\n    # 1,n,4\r\n    # 计算左上角和右下角的坐标\r\n    b2 = K.expand_dims(b2, 0)\r\n    b2_xy = b2[..., :2]\r\n    b2_wh = b2[..., 2:4]\r\n    b2_wh_half = b2_wh/2.\r\n    b2_mins = b2_xy - b2_wh_half\r\n    b2_maxes = b2_xy + b2_wh_half\r\n\r\n    # 计算重合面积\r\n    intersect_mins = K.maximum(b1_mins, b2_mins)\r\n    intersect_maxes = K.minimum(b1_maxes, b2_maxes)\r\n    intersect_wh = K.maximum(intersect_maxes - intersect_mins, 0.)\r\n    intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1]\r\n    b1_area = b1_wh[..., 0] * b1_wh[..., 1]\r\n    b2_area = b2_wh[..., 0] * b2_wh[..., 1]\r\n    iou = intersect_area / (b1_area + b2_area - intersect_area)\r\n\r\n    return iou\r\n\r\n#---------------------------------------------------#\r\n#   loss值计算\r\n#---------------------------------------------------#\r\ndef yolo_loss(args, anchors, num_classes, ignore_thresh=.5, label_smoothing=0.1, print_loss=False, normalize=True):\r\n    # 一共有两层\r\n    num_layers = len(anchors)//3 \r\n\r\n    #---------------------------------------------------------------------------------------------------#\r\n    #   将预测结果和实际ground truth分开，args是[*model_body.output, *y_true]\r\n    #   y_true是一个列表，包含两个特征层，shape分别为(m,13,13,3,85),(m,26,26,3,85)\r\n    #   yolo_outputs是一个列表，包含两个特征层，shape分别为(m,13,13,3,85),(m,26,26,3,85)\r\n    #---------------------------------------------------------------------------------------------------#\r\n    y_true = args[num_layers:]\r\n    yolo_outputs = args[:num_layers]\r\n\r\n    #-----------------------------------------------------------#\r\n    #   13x13的特征层对应的anchor是[81,82], [135,169], [344,319]\r\n    #   26x26的特征层对应的anchor是[23,27], [37,58], [81,82]\r\n    #-----------------------------------------------------------#\r\n    anchor_mask = [[6,7,8], [3,4,5], [0,1,2]] if num_layers==3 else [[3,4,5], [1,2,3]]\r\n\r\n    # 得到input_shpae为416,416 \r\n    input_shape = K.cast(K.shape(yolo_outputs[0])[1:3] * 32, K.dtype(y_true[0]))\r\n\r\n    loss = 0\r\n    num_pos = 0\r\n    #-----------------------------------------------------------#\r\n    #   取出每一张图片\r\n    #   m的值就是batch_size\r\n    #-----------------------------------------------------------#\r\n    m = K.shape(yolo_outputs[0])[0]\r\n    mf = K.cast(m, K.dtype(yolo_outputs[0]))\r\n\r\n    #---------------------------------------------------------------------------------------------------#\r\n    #   y_true是一个列表，包含两个特征层，shape分别为(m,13,13,3,85),(m,26,26,3,85)\r\n    #   yolo_outputs是一个列表，包含两个特征层，shape分别为(m,13,13,3,85),(m,26,26,3,85)\r\n    #---------------------------------------------------------------------------------------------------#\r\n    for l in range(num_layers):\r\n        #-----------------------------------------------------------#\r\n        #   以第一个特征层(m,13,13,3,85)为例子\r\n        #   取出该特征层中存在目标的点的位置。(m,13,13,3,1)\r\n        #-----------------------------------------------------------#\r\n        object_mask = y_true[l][..., 4:5]#[…, 4: 5]指的是该框的置信度,用1或0表示https://www.cnblogs.com/learningcaiji/p/14077315.html\r\n\r\n        #-----------------------------------------------------------#\r\n        #   取出其对应的种类(m,13,13,3,80)\r\n        #-----------------------------------------------------------#\r\n        true_class_probs = y_true[l][..., 5:]\r\n        if label_smoothing:\r\n            true_class_probs = _smooth_labels(true_class_probs, label_smoothing)\r\n\r\n        #-----------------------------------------------------------#\r\n        #   将yolo_outputs的特征层输出进行处理、获得四个返回值\r\n        #   其中：\r\n        #   grid        (13,13,1,2) 网格坐标\r\n        #   raw_pred    (m,13,13,3,85) 尚未处理的预测结果\r\n        #   pred_xy     (m,13,13,3,2) 解码后的中心坐标\r\n        #   pred_wh     (m,13,13,3,2) 解码后的宽高坐标\r\n        #-----------------------------------------------------------#\r\n        grid, raw_pred, pred_xy, pred_wh = yolo_head(yolo_outputs[l],\r\n             anchors[anchor_mask[l]], num_classes, input_shape, calc_loss=True)\r\n        \r\n        #-----------------------------------------------------------#\r\n        #   pred_box是解码后的预测的box的位置\r\n        #   (m,13,13,3,4)\r\n        #-----------------------------------------------------------#\r\n        pred_box = K.concatenate([pred_xy, pred_wh])\r\n\r\n        #-----------------------------------------------------------#\r\n        #   找到负样本群组，第一步是创建一个数组，[]\r\n        #-----------------------------------------------------------#\r\n        ignore_mask = tf.TensorArray(K.dtype(y_true[0]), size=1, dynamic_size=True)\r\n        object_mask_bool = K.cast(object_mask, 'bool')\r\n        \r\n        #-----------------------------------------------------------#\r\n        #   对每一张图片计算ignore_mask\r\n        #-----------------------------------------------------------#\r\n        def loop_body(b, ignore_mask):\r\n            #-----------------------------------------------------------#\r\n            #   取出n个真实框：n,4\r\n            #-----------------------------------------------------------#\r\n            true_box = tf.boolean_mask(y_true[l][b,...,0:4], object_mask_bool[b,...,0])\r\n            #-----------------------------------------------------------#\r\n            #   计算预测框与真实框的iou\r\n            #   pred_box    13,13,3,4 预测框的坐标\r\n            #   true_box    n,4 真实框的坐标\r\n            #   iou         13,13,3,n 预测框和真实框的iou\r\n            #-----------------------------------------------------------#\r\n            iou = box_iou(pred_box[b], true_box)\r\n\r\n            #-----------------------------------------------------------#\r\n            #   best_iou    13,13,3 每个特征点与真实框的最大重合程度\r\n            #-----------------------------------------------------------#\r\n            best_iou = K.max(iou, axis=-1)\r\n\r\n            #-----------------------------------------------------------#\r\n            #   判断预测框和真实框的最大iou小于ignore_thresh\r\n            #   则认为该预测框没有与之对应的真实框\r\n            #   该操作的目的是：\r\n            #   忽略预测结果与真实框非常对应特征点，因为这些框已经比较准了\r\n            #   不适合当作负样本，所以忽略掉。\r\n            #-----------------------------------------------------------#\r\n            ignore_mask = ignore_mask.write(b, K.cast(best_iou<ignore_thresh, K.dtype(true_box)))\r\n            return b+1, ignore_mask\r\n\r\n        #-----------------------------------------------------------#\r\n        #   在这个地方进行一个循环、循环是对每一张图片进行的\r\n        #-----------------------------------------------------------#\r\n        _, ignore_mask = K.control_flow_ops.while_loop(lambda b,*args: b<m, loop_body, [0, ignore_mask])\r\n\r\n        #-----------------------------------------------------------#\r\n        #   ignore_mask用于提取出作为负样本的特征点\r\n        #   (m,13,13,3)\r\n        #-----------------------------------------------------------#\r\n        ignore_mask = ignore_mask.stack()\r\n        #   (m,13,13,3,1)\r\n        ignore_mask = K.expand_dims(ignore_mask, -1)\r\n\r\n        #-----------------------------------------------------------#\r\n        #   真实框越大，比重越小，小框的比重更大。\r\n        #-----------------------------------------------------------#\r\n        box_loss_scale = 2 - y_true[l][...,2:3]*y_true[l][...,3:4]  #预测值\r\n\r\n        #-----------------------------------------------------------#\r\n        #   计算Ciou loss\r\n        #-----------------------------------------------------------#\r\n        raw_true_box = y_true[l][...,0:4]\r\n        ciou = box_ciou(pred_box, raw_true_box)\r\n        ciou_loss = object_mask * box_loss_scale * (1 - ciou)\r\n        \r\n        #------------------------------------------------------------------------------#\r\n        #   如果该位置本来有框，那么计算1与置信度的交叉熵\r\n        #   如果该位置本来没有框，那么计算0与置信度的交叉熵\r\n        #   在这其中会忽略一部分样本，这些被忽略的样本满足条件best_iou<ignore_thresh\r\n        #   该操作的目的是：\r\n        #   忽略预测结果与真实框非常对应特征点，因为这些框已经比较准了\r\n        #   不适合当作负样本，所以忽略掉。\r\n        #------------------------------------------------------------------------------#\r\n\r\n        #object_mask代表的是True\r\n        #列表中的三个点代表前面所有的维数\r\n        # print('object_ mask',object_mask.shape)\r\n        # print('raw',raw_pred[...,4:5].shape)\r\n\r\n\r\n\r\n        #confidence_loss，实际存在的框，预测结果中置信度的值与1对比；实际不存在的框，预测结果中置信度的值与0对比，该部分要去除被忽略的不包含目标的框。\r\n        confidence_loss = object_mask * K.binary_crossentropy(object_mask, raw_pred[...,4:5],from_logits=True)+ \\\r\n            (1-object_mask) * K.binary_crossentropy(object_mask, raw_pred[...,4:5],from_logits=True) * ignore_mask\r\n        # confidence_loss = binary_focal_loss(object_mask,raw_pred[...,4:5])\r\n        # print('confidence_loss',confidence_loss)\r\n        #置信度loss\r\n        '''正样本有坐标，置信度和类别损失函数，而负样本只有置信度损失函数'''\r\n\r\n        '''\r\n                alpha = 0.25\r\n        gamma = 2\r\n        alpha_factor = K.ones_like(object_mask) * alpha\r\n        alpha_factor = tf.where(K.equal(object_mask, 1), alpha_factor, 1 - alpha_factor)\r\n        focal_weight = tf.where(K.equal(object_mask, 1), 1 - raw_pred[..., 4:5], raw_pred[..., 4:5])\r\n        focal_weight = alpha_factor * focal_weight ** gamma\r\n        confidence_loss = focal_weight * K.binary_crossentropy(object_mask, raw_pred[..., 4:5],from_logits=True)\r\n        '''\r\n\r\n\r\n        class_loss = object_mask * K.binary_crossentropy(true_class_probs, raw_pred[...,5:],from_logits=True) #分类loss\r\n\r\n        location_loss = K.sum(ciou_loss) #回归框\r\n        confidence_loss = K.sum(confidence_loss)\r\n        class_loss = K.sum(class_loss)\r\n        #-----------------------------------------------------------#\r\n        #   计算正样本数量\r\n        #-----------------------------------------------------------#\r\n        num_pos += tf.maximum(K.sum(K.cast(object_mask, tf.float32)), 1)\r\n        loss += location_loss + confidence_loss + class_loss\r\n        # if print_loss:\r\n        #   loss = tf.Print(loss, [loss, location_loss, confidence_loss, class_loss, K.sum(ignore_mask)], message='loss: ')\r\n        \r\n    if normalize:\r\n        loss = loss / num_pos\r\n    else:\r\n        loss = loss / mf\r\n    return loss\r\n", "meta": {"hexsha": "357e23181b86f8464834ed40421f4cb94240ebc3", "size": 17139, "ext": "py", "lang": "Python", "max_stars_repo_path": "nets/loss.py", "max_stars_repo_name": "XiongDa0001/yolov4-tiny-keras", "max_stars_repo_head_hexsha": "cd469aaa7f7cb5d852dab9b444a9d043192bd261", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nets/loss.py", "max_issues_repo_name": "XiongDa0001/yolov4-tiny-keras", "max_issues_repo_head_hexsha": "cd469aaa7f7cb5d852dab9b444a9d043192bd261", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nets/loss.py", "max_forks_repo_name": "XiongDa0001/yolov4-tiny-keras", "max_forks_repo_head_hexsha": "cd469aaa7f7cb5d852dab9b444a9d043192bd261", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.8024390244, "max_line_length": 131, "alphanum_fraction": 0.4639127137, "include": true, "reason": "import numpy", "num_tokens": 5071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.1939248826679692}}
{"text": "#!/usr/bin/env python\n\n\"\"\"Variational Autoencoder class\n\n@author: Matt Whiteway, June 2017\nVAE class implements a variational autoencoder\n\n\"\"\"\n\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport os\nimport numpy as np\nimport tensorflow as tf\n\nimport sys\nsys.path.append('..')\nimport utils.exceptions as exc\n\n\nclass VAE(object):\n    \"\"\"Variational Autoencoder class\n    \n    Attributes:\n        layers_encoder (list of ints): size of each layer in encoder, excluding\n            input layer\n        input_size (int): size of input\n        layer_latent (int): size of latent layer\n        layers_decoder (list of ints): size of each layer in decoder, including\n            output layer\n        num_lvs (int): size of latent layer\n        num_layers_enc (int): number of layers in encoder, including input \n            layer\n        num_layers_dec (int): number of layers in decoder, including latent\n            layer and output layer\n        act_func (str): activation function for network layers\n        \n        weights_enc (list of tf.Variable): weights of the encoding network\n        biases_enc (list of tf.Variable): biases of the encoding network\n        weights_mean (tf.Variable): weights from encoding network to latent \n            variable distribution mean\n        biases_mean (tf.Variable): biases from encoding network to latent \n            variable distribution mean\n        weights_log_var (tf.Variable): weights from encoding network to log of\n            latent variable distribution variance\n        biases_log_var (tf.Variable): biases from encoding network to log of\n            latent variable distribution variance\n        weights_dec (list of tf.Variable): weights of the decoding network\n        biases_dec (list of tf.Variable): biases of the decoding network\n        \n        x (tf placeholder): ph for input to model\n        z_mean (tf op): mean value for each latent variable\n        z_log_var (tf op): log of the variance for each latent variable\n        z (tf op): sample value of latent variable\n        eps (tf placeholder): ph for N(0,1) input to stochastic layer\n        x_recon (tf op): reconstructed input values\n        cost (tf op): evaluates the cost function of the network\n        \n        learning_rate (float): global learning rate used by gradient descent \n            optimizers\n        train_step (tf op): evaluates one training step using the specified \n            cost function and learning algorithm\n        \n        graph (tf.Graph): dataflow graph for the network\n        saver (tf.train.Saver): for saving and restoring variables\n        merge_summaries (tf op): op that merges all summary ops\n        init (tf op): op that initializes global variables in graph \n    \n    \"\"\"\n\n    def __init__(\n            self,\n            layers_encoder=None,\n            layer_latent=None,\n            layers_decoder=None,\n            act_func='relu',\n            learning_rate=1e-3):\n        \"\"\"Constructor for VAE class\n        \n        Args:\n            layers_encoder (list of ints): size of each layer in encoder, \n                including input layer\n            layer_latent (int): size of latent layer\n            layers_decoder (list of ints): size of each layer in decoder, \n                including output layer\n            act_func (str): activation function for network layers\n                ['relu'] | 'sigmoid' | 'tanh' | 'linear' | 'softplus' | 'elu'\n            learning_rate (scalar): global learning rate for gradient descent \n                methods\n            \n        Raises:\n            InputError if layers_encoder is not specified\n            InputError if layers_latent is not specified\n            InputError if layers_decoder is not specified\n            InputError if act_func is not a valid string\n            \n        \"\"\"\n\n        # input checking\n        if layers_encoder is None:\n            raise exc.InputError('Must specify layer sizes for encoder')\n        if layer_latent is None:\n            raise exc.InputError('Must specify number of latent dimensions')\n        if layers_decoder is None:\n            raise exc.InputError('Must specify layer sizes for decoder')\n\n        self.input_size = layers_encoder[0]\n        self.layers_encoder = layers_encoder[1:]\n        self.layer_latent = layer_latent\n        self.layers_decoder = layers_decoder\n\n        if act_func == 'relu':\n            self.act_func = tf.nn.relu\n        elif act_func == 'sigmoid':\n            self.act_func = tf.sigmoid\n        elif act_func == 'tanh':\n            self.act_func = tf.tanh\n        elif act_func == 'linear':\n            self.act_func = tf.identity\n        elif act_func == 'softplus':\n            self.act_func = tf.nn.softplus\n        elif act_func == 'elu':\n            self.act_func = tf.nn.elu\n        else:\n            raise exc.InputError('Invalid activation function')\n\n        self.learning_rate = learning_rate\n\n        # define useful constants\n        self.num_lvs = self.layer_latent\n        self.num_layers_enc = len(self.layers_encoder)\n        self.num_layers_dec = len(self.layers_decoder)\n\n        # for saving and restoring models\n        self.graph = tf.Graph()  # must be initialized before graph creation\n\n        # build model graph\n        with self.graph.as_default():\n\n            # define pipeline for feeding data into model\n            with tf.variable_scope('data'):\n                self._initialize_data_pipeline()\n\n            # initialize weights and create encoder model\n            with tf.variable_scope('encoder'):\n                self._define_recognition_network()\n\n            # initialize weights and create decoder model\n            with tf.variable_scope('decoder'):\n                self._define_generator_network()\n\n            # define loss function\n            with tf.variable_scope('loss'):\n                self._define_loss()\n\n            # define optimizer\n            with tf.variable_scope('optimizer'):\n                self._define_optimizer()\n\n            # add additional ops\n            # for saving and restoring models\n            self.saver = tf.train.Saver()  # must be init after var creation\n            # collect all summaries into a single op\n            self.merge_summaries = tf.summary.merge_all()\n            # add variable initialization op to graph\n            self.init = tf.global_variables_initializer()\n\n    def _initialize_data_pipeline(self):\n        \"\"\"Create placeholders for input and random values\"\"\"\n\n        self.x = tf.placeholder(\n            dtype=tf.float32,\n            shape=[None, self.input_size],\n            name='input_ph')\n        self.eps = tf.placeholder(\n            dtype=tf.float32,\n            shape=[None, self.num_lvs],\n            name='rand_ph')\n\n    def _define_recognition_network(self):\n        \"\"\" \n        Create a recognition network to transform inputs into its latent \n        representation\n        \"\"\"\n\n        # push data through the encoding function to determine mean and std\n        # of latent vars\n        self.weights_enc = []\n        self.biases_enc = []\n        z_enc = [self.x]\n        for layer in range(self.num_layers_enc):\n            with tf.variable_scope(str('layer_%01i' % layer)):\n\n                # initialize weights\n                if layer == 0:\n                    in_size = self.input_size\n                else:\n                    in_size = self.layers_encoder[layer - 1]\n                out_size = self.layers_encoder[layer]\n                self.weights_enc.append(tf.get_variable(\n                    shape=[in_size, out_size],\n                    name='weights',\n                    initializer=tf.truncated_normal_initializer(stddev=0.1)))\n\n                # initialize biases\n                self.biases_enc.append(tf.get_variable(\n                    initializer=tf.zeros(shape=[1, out_size]),\n                    name='biases'))\n\n                # calculate layer activations\n                pre = tf.add(\n                    tf.matmul(z_enc[layer], self.weights_enc[layer]),\n                    self.biases_enc[layer])\n                post = self.act_func(pre)\n                z_enc.append(post)\n\n                # save summaries of layer activations\n                tf.summary.histogram('pre_act', pre)\n                tf.summary.histogram('post_act', post)\n\n        with tf.variable_scope('latent_layer'):\n\n            with tf.variable_scope('means'):\n                # initialize weights/biases for means of stochastic layer\n                self.weights_mean = tf.get_variable(\n                    shape=[self.layers_encoder[-1], self.num_lvs],\n                    name='weights',\n                    initializer=tf.truncated_normal_initializer(stddev=0.1))\n                self.biases_mean = tf.get_variable(\n                    initializer=tf.zeros(shape=[1, self.num_lvs]),\n                    name='biases')\n                # weights to estimate mean of normally distributed latent vars\n                self.z_mean = tf.add(\n                    tf.matmul(z_enc[-1], self.weights_mean), self.biases_mean,\n                    name='z_means')\n\n            with tf.variable_scope('log_vars'):\n                # initialize weights/biases for log vars of stochastic layer\n                self.weights_log_var = tf.get_variable(\n                    shape=[self.layers_encoder[-1], self.num_lvs],\n                    name='weights',\n                    initializer=tf.truncated_normal_initializer(stddev=0.1))\n                self.biases_log_var = tf.get_variable(\n                    initializer=tf.zeros(shape=[1, self.num_lvs]),\n                    name='biases')\n                # estimating log of the variance is easier since the latent\n                # loss has a log determinant term\n                self.z_log_var = tf.add(\n                    tf.matmul(z_enc[-1], self.weights_log_var),\n                    self.biases_log_var,\n                    name='z_log_vars')\n\n            # transform estimated mean and log variance into a sampled value\n            # of the latent state using z = mu + sigma*epsilon\n            self.z = tf.add(\n                self.z_mean,\n                tf.multiply(tf.sqrt(tf.exp(self.z_log_var)), self.eps))\n\n            # save summaries of means and log_vars\n            tf.summary.histogram('means', self.z_mean)\n            tf.summary.histogram('log_vars', self.z_log_var)\n\n    def _define_generator_network(self):\n        \"\"\" \n        Create a generator network to transform a random sample\n        in the latent space into an image\n        \"\"\"\n\n        self.weights_dec = []\n        self.biases_dec = []\n        z_dec = [self.z]\n        for layer in range(self.num_layers_dec):\n            with tf.variable_scope(str('layer_%01i' % layer)):\n\n                # initialize weights\n                if layer == 0:\n                    in_size = self.num_lvs\n                else:\n                    in_size = self.layers_decoder[layer - 1]\n                out_size = self.layers_decoder[layer]\n                self.weights_dec.append(tf.get_variable(\n                    shape=[in_size, out_size],\n                    name='weights',\n                    initializer=tf.truncated_normal_initializer(stddev=0.1)))\n\n                # initialize biases\n                self.biases_dec.append(tf.get_variable(\n                    initializer=tf.zeros(shape=[1, out_size]),\n                    name='biases'))\n\n                # calculate layer activations\n                pre = tf.add(\n                    tf.matmul(z_dec[layer], self.weights_dec[layer]),\n                    self.biases_dec[layer])\n                post = self.act_func(pre)\n                z_dec.append(post)\n\n                # save summaries of layer activations\n                tf.summary.histogram('pre_act', pre)\n                tf.summary.histogram('post_act', post)\n\n        # define this for easier access later\n        self.x_recon = z_dec[-1]\n\n    def _define_loss(self):\n        \"\"\"Define loss function that will be used to optimize model params\"\"\"\n\n        # define reconstruction loss\n        loss_recon = 0.5 * tf.reduce_sum(tf.square(self.x_recon - self.x), 1)\n\n        # define latent loss\n        loss_latent = 0.5 * tf.reduce_sum(tf.exp(self.z_log_var)\n                                          + tf.square(self.z_mean)\n                                          - 1 - self.z_log_var, 1)\n\n        # define cost\n        self.cost = tf.reduce_mean(loss_recon + loss_latent)\n        # save summaries of cost\n        tf.summary.scalar('cost', self.cost)\n\n    def _define_optimizer(self):\n        \"\"\"Define one step of the optimization routine\"\"\"\n        self.train_step = tf.train.AdamOptimizer(self.learning_rate). \\\n            minimize(self.cost)\n\n    def train(\n            self,\n            sess,\n            data=None,\n            batch_size=128,\n            epochs_training=10,\n            epochs_disp=None,\n            epochs_ckpt=None,\n            epochs_summary=None,\n            output_dir=None):\n        \"\"\"Network training\n        \n        Args:\n            sess (tf.Session object): current session object to run graph\n            data (DataReader object): input to network\n            batch_size (int, optional): batch size used by the gradient\n                descent-based optimizers\n            epochs_training (int, optional): number of epochs for gradient \n                descent-based optimizers\n            epochs_disp (int, optional): number of epochs between updates to \n                the console\n            epochs_ckpt (int, optional): number of epochs between saving \n                checkpoint files\n            epochs_summary (int, optional): number of epochs between saving\n                network summary information \n            output_dir (string, optional): absolute path for saving checkpoint\n                files and summary files; must be present if either epochs_ckpt  \n                or epochs_summary is not 'None'.\n\n        Returns:\n            None\n\n        Raises:\n            InputError: If epochs_ckpt is not None and output_dir is None\n            InputError: If epochs_summary is not None and output_dir is None\n            \n        \"\"\"\n\n        # check input\n        if data is None:\n            raise exc.InputError('data reader must be specified')\n        if epochs_ckpt is not None and output_dir is None:\n            raise exc.InputError('output_dir must be specified to save model')\n        if epochs_summary is not None and output_dir is None:\n            raise exc.InputError('output_dir must be specified to save ' +\n                                 'summaries')\n\n        # initialize file writers\n        if epochs_summary is not None:\n            test_writer = tf.summary.FileWriter(\n                os.path.join(output_dir, 'summaries', 'test'),\n                sess.graph)\n\n        # begin training\n        with self.graph.as_default():\n\n            num_batches = int(data.train.num_examples / batch_size)\n\n            # start training loop\n            for epoch in range(epochs_training):\n\n                for batch in range(num_batches):\n\n                    # get batch of data for this training step\n                    x = data.train.next_batch(batch_size)\n\n                    # draw random samples for latent layer\n                    eps = np.random.normal(size=(batch_size, self.num_lvs))\n\n                    # one step of optimization routine\n                    sess.run(\n                        self.train_step,\n                        feed_dict={self.x: x[0], self.eps: eps})\n\n                # print training updates\n                if epochs_disp is not None and epoch % epochs_disp == 0:\n\n                    # print updates using test set\n                    x = data.test.next_batch(data.test.num_examples)\n                    eps = np.random.normal(\n                        size=(data.test.num_examples, self.num_lvs))\n                    cost = sess.run(\n                        self.cost,\n                        feed_dict={self.x: x[0], self.eps: eps})\n                    print('Epoch %03d:' % epoch)\n                    print('   test cost = %2.5f' % cost)\n\n                # save model checkpoints\n                if epochs_ckpt is not None and epoch % epochs_ckpt == 0:\n                    save_file = os.path.join(\n                        output_dir, 'ckpts',\n                        str('epoch_%05g.ckpt' % epoch))\n                    self.save_model(sess, save_file)\n\n                # save model summaries\n                if epochs_summary is not None and \\\n                        epoch % epochs_summary == 0:\n                    # output summaries using test set\n                    x = data.test.next_batch(data.test.num_examples)\n                    eps = np.random.normal(\n                        size=(data.test.num_examples, self.num_lvs))\n                    summary = sess.run(\n                        self.merge_summaries,\n                        feed_dict={self.x: x[0], self.eps: eps})\n                    test_writer.add_summary(summary, epoch)\n\n    def train_iters(\n            self,\n            sess,\n            data=None,\n            batch_size=128,\n            iters_training=1000,\n            iters_disp=None,\n            iters_ckpt=None,\n            iters_summary=None,\n            output_dir=None):\n        \"\"\"\n        Network training by specifying number of iterations rather than \n        epochs. Used for easily generating sample outputs during training\n\n        Args:\n            sess (tf.Session object): current session object to run graph\n            data (DataReader object): input to network\n            batch_size (int, optional): batch size used by the gradient\n                descent-based optimizers\n            iters_training (int, optional): number of iters for gradient \n                descent-based optimizers\n            iters_disp (int, optional): number of iters between updates to \n                the console\n            iters_ckpt (int, optional): number of iters between saving \n                checkpoint files\n            iters_summary (int, optional): number of iters between saving\n                network summary information \n            output_dir (string, optional): absolute path for saving checkpoint\n                files and summary files; must be present if either iters_ckpt  \n                or iters_summary is not 'None'.\n\n        Returns:\n            None\n\n        Raises:\n            InputError: If iters_ckpt is not None and output_dir is None\n            InputError: If iters_summary is not None and output_dir is None\n\n        \"\"\"\n\n        # check input\n        if data is None:\n            raise exc.InputError('data reader must be specified')\n        if iters_ckpt is not None and output_dir is None:\n            raise exc.InputError('output_dir must be specified to save model')\n        if iters_summary is not None and output_dir is None:\n            raise exc.InputError('output_dir must be specified to save ' +\n                                 'summaries')\n\n        # initialize file writers\n        if iters_summary is not None:\n            test_writer = tf.summary.FileWriter(\n                os.path.join(output_dir, 'summaries', 'test'),\n                sess.graph)\n\n        # begin training\n        with self.graph.as_default():\n\n            # start training loop\n            for iter_ in range(iters_training):\n\n                # get batch of data for this training step\n                x = data.train.next_batch(batch_size)\n\n                # draw random samples for latent layer\n                eps = np.random.normal(size=(batch_size, self.num_lvs))\n\n                # one step of optimization routine\n                sess.run(\n                    self.train_step,\n                    feed_dict={self.x: x[0], self.eps: eps})\n\n                # print training updates\n                if iters_disp is not None and iter_ % iters_disp == 0:\n                    # print updates using test set\n                    x = data.test.next_batch(data.test.num_examples)\n                    eps = np.random.normal(\n                        size=(data.test.num_examples, self.num_lvs))\n                    cost = sess.run(\n                        self.cost,\n                        feed_dict={self.x: x[0], self.eps: eps})\n                    print('Iter %03d:' % iter_)\n                    print('   test cost = %2.5f' % cost)\n\n                # save model checkpoints\n                if iters_ckpt is not None and iter_ % iters_ckpt == 0:\n                    save_file = os.path.join(\n                        output_dir, 'ckpts',\n                        str('epoch_%05g.ckpt' % iter_))\n                    self.save_model(sess, save_file)\n\n                # save model summaries\n                if iters_summary is not None and iter_ % iters_summary == 0:\n                    # output summaries using test set\n                    x = data.test.next_batch(data.test.num_examples)\n                    eps = np.random.normal(\n                        size=(data.test.num_examples, self.num_lvs))\n                    summary = sess.run(\n                        self.merge_summaries,\n                        feed_dict={self.x: x[0], self.eps: eps})\n                    test_writer.add_summary(summary, iter_)\n\n    def generate(self, sess, z_mean=None):\n        \"\"\"Sample the network and generate an image \n\n        If z_mean is None, a random point is generated using the prior in\n        the latent space, else z_mean is used as the point in latent space\n        \"\"\"\n\n        if z_mean is None:\n            z_mean = np.random.normal(size=(1, self.num_lvs))\n\n        return sess.run(self.x_recon, feed_dict={self.z: z_mean})\n\n    def recognize(self, sess, x):\n        \"\"\"Transform a given input into its latent representation\"\"\"\n        return sess.run(self.z_mean, feed_dict={self.x: x})\n\n    def reconstruct(self, sess, x, eps):\n        \"\"\"Transform a given input into its reconstruction\"\"\"\n        return sess.run(self.x_recon, feed_dict={self.x: x, self.eps: eps})\n\n    def save_model(self, sess, save_file):\n        \"\"\"Save model parameters \n\n        Args:\n            sess (tf.Session object): current session object to run graph\n            save_file (str): full path to output file\n\n        \"\"\"\n\n        if not os.path.isdir(os.path.dirname(save_file)):\n            os.makedirs(os.path.dirname(save_file))\n\n        self.saver.save(sess, save_file)\n        print('Model saved to %s' % save_file)\n\n    def load_model(self, sess, save_file):\n        \"\"\"Load previously saved model parameters \n\n        Args:\n            sess (tf.Session object): current session object to run graph\n            save_file (str): full path to saved model\n\n        \"\"\"\n\n        if not os.path.isfile(save_file + '.meta'):\n            raise exc.InputError(str('%s is not a valid filename' % save_file))\n\n        self.saver.restore(sess, save_file)\n        print('Model loaded from %s' % save_file)\n", "meta": {"hexsha": "447f1771f676dc8e03f3555f44ebe489d0a54160", "size": 22906, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/VAE.py", "max_stars_repo_name": "themattinthehatt/dreamscape", "max_stars_repo_head_hexsha": "3ae2a4fd0fc19bc69b705aa309f3643fb739997f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-12-16T13:32:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T11:13:25.000Z", "max_issues_repo_path": "models/VAE.py", "max_issues_repo_name": "themattinthehatt/dreamscape", "max_issues_repo_head_hexsha": "3ae2a4fd0fc19bc69b705aa309f3643fb739997f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/VAE.py", "max_forks_repo_name": "themattinthehatt/dreamscape", "max_forks_repo_head_hexsha": "3ae2a4fd0fc19bc69b705aa309f3643fb739997f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-12-17T23:48:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T00:26:19.000Z", "avg_line_length": 39.2226027397, "max_line_length": 80, "alphanum_fraction": 0.5631275648, "include": true, "reason": "import numpy", "num_tokens": 4444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.37022539954425293, "lm_q1q2_score": 0.19378350781454284}}
{"text": "from os import stat\nfrom typing import Dict, List, Tuple\nfrom treehmm import initHMM, baumWelch\nfrom treehmm import fwd_seq_gen, forward\nfrom TreeHMM4Glycan.Glycan import Glycan\nimport csv\nfrom scipy.linalg import block_diag\nimport numpy as np\nimport re\nimport argparse\nfrom scipy.sparse.csr import csr_matrix\nfrom scipy.special import logsumexp\nimport logging\nimport sys\n\n#\n# Method read a file and then retunr a Dict of iupac names\n#\ndef get_iupcas(iupac_name_file:str) -> Dict[int, str]:\n    iupacs = {}\n    with open(iupac_name_file) as file_in:\n        csv_reader = csv.reader(file_in)\n        for idx,row in enumerate(csv_reader):\n            if idx == 0:\n                continue\n            id = int(row[0])\n            # remove right most part'(a1-sp14'\n            iupac = re.split(r\"\\([^\\)]*$\", row[1], 1)[0]\n            iupacs[id] = iupac\n    return iupacs\n\n# method to get a dict of glycans form input iupac snfg\ndef get_glycans(iupacs:Dict[int, str], start = None, end = None) -> Tuple[Dict[int, Glycan], List[str], List[str]]:\n    gylcans_dict = {}\n    monos = []\n    links = []\n    \n    for id in iupacs:\n        if start is not None and id < start:\n            continue\n        if end is not None and id > end:\n            continue \n        inpuac_text = iupacs[id]\n        gylcan = Glycan(inpuac_text)\n        \n        #if gylcan.get_num_nosaccharides() > 2:\n        gylcans_dict[id] = gylcan\n        monos += gylcan.get_filtered_monosaccharide_emssions()\n        links += gylcan.get_filtered_linkage_emssions()\n        \n    mono_emissions = list(set(monos))\n    link_emissions = list(set(links))\n\n    return gylcans_dict, mono_emissions, link_emissions\n\n# Method create foreset iputs from a dict collection of glycans\n# Input:\n#   glycans_dict: dict of glycans\n# Return:\n#   joint_adj_matrix - joint adjcent matrix \n#   joint_monosaccharide_emission_observations - joint emissions for monosaccharides types\n#   joint_linkage_emission_observations - joint emissions for linkage types\ndef create_forest_inputs(glycans_dict:Dict[int, Glycan]) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n    adj_matrices = []\n    joint_monosaccharide_emission_observations = []\n    joint_linkage_emission_observations = []\n\n    for id in glycans_dict:\n        glyan = glycans_dict[id]\n        # update list of adj_matrices we are going to join along the diagonal\n        adj_matrices.append(glyan.get_adj_matrix())\n        # update joint_monosaccharide_emission_observations and joint_linkage_emission_observations\n        joint_monosaccharide_emission_observations = joint_monosaccharide_emission_observations + glyan.get_filtered_monosaccharide_emssions()\n        joint_linkage_emission_observations = joint_linkage_emission_observations + glyan.get_filtered_linkage_emssions()\n\n    # join adj_martrix along diagonal\n    joint_adj_matrix = block_diag(*adj_matrices)\n    return joint_adj_matrix, joint_monosaccharide_emission_observations, joint_linkage_emission_observations\n\n# Method learn a treehmm from a forset\n# Input:\n#   joint_adj_matrix - joint adjcent matrix \n#   joint_emissions_observations - emissions observations for this foreset N * M, N is the number of emissions group eg,monosaccharide, linkage,\n#       M is number of emssions groups eg.  monosaccharide_emissions for group 1 and linkage_emissions for group 2\n#   number_state - number of states\n#   possible_emissions -  possible_ emissions for this foreset N * M, N is the number of emissions group eg,monosaccharide, linkage, \n#       M is number of emssions groups   eg.  monosaccharide_emissions for group 1 and linkage_emissions for group 2\ndef create_and_train_treehmm(number_state:int, iupacs, include_linkage = False, max_iterations=50, delta=1e-5):\n\n    gylcans, possible_monosaccharide_emissions, possible_linkage_emissions = get_glycans(iupacs, 50, 75)\n    \n    joint_adj_matrix, joint_monosaccharide_emission_observations, joint_linkage_emission_observations = create_forest_inputs(gylcans)\n\n    #print(possible_monosaccharide_emissions)\n    # monosaccharide_emission_observations_counts = {}\n    # for item in possible_monosaccharide_emissions:\n    #     monosaccharide_emission_observations_counts[item] = 0\n    # for item in joint_monosaccharide_emission_observations:\n    #     monosaccharide_emission_observations_counts[item] += 1\n    # print(monosaccharide_emission_observations_counts)\n\n    # possible_linkage_emissions_counts = {}\n    # for item in possible_linkage_emissions:\n    #     possible_linkage_emissions_counts[item] = 0\n    # for item in joint_linkage_emission_observations:\n    #     possible_linkage_emissions_counts[item] += 1\n    # print(possible_linkage_emissions_counts)\n\n    # we only use monosaccharide\n    if not include_linkage:\n        joint_emissions_observations = [joint_monosaccharide_emission_observations]\n        possible_emissions = [possible_monosaccharide_emissions]\n    else:\n    # if we want to use both of them\n        joint_emissions_observations = [joint_monosaccharide_emission_observations, joint_linkage_emission_observations]\n        possible_emissions = [possible_monosaccharide_emissions, possible_linkage_emissions]\n        \n    forest = csr_matrix(joint_adj_matrix)\n    # create states\n    states = [ str(i) for i in range(number_state)]\n    \n    #state_transition_probabilities = np.array([0.1,0.9,0.1,0.9]).reshape(2,2)\n    hmm = initHMM.initHMM(states, possible_emissions)\n    newparam = None\n    for i in range(5):\n        # The baumWelch part: To find the new parameters and result statistics\n        newparam = baumWelch.hmm_train_and_test(hmm, forest, joint_emissions_observations, maxIterations = max_iterations, delta = delta)\n        #newparam = baumWelch.baumWelchRecursion(hmm, emission_observation)\n\n\n        hmm = initHMM.initHMM(states, possible_emissions, state_transition_probabilities=newparam['hmm']['state_transition_probabilities'],\n                                                emission_probabilities=newparam['hmm']['emission_probabilities'])\n        \n        #print(newparam['hmm']['state_transition_probabilities'])\n        #print(newparam['hmm']['emission_probabilities'])\n        #fwd_tree_sequence = fwd_seq_gen.forward_sequence_generator(forest)\n        #bind_fwd_probs = forward.forward(hmm_trained, forest, joint_emissions_observations, fwd_tree_sequence)\n        #print(joint_emissions_observations)\n        \n        ll = 0\n        for glycan_idx in gylcans:\n            glycan = gylcans[glycan_idx]\n            #print(glycan.get_filtered_monosaccharide_emssions())\n            glycan_tree = csr_matrix(glycan.get_adj_matrix())\n            fwd_tree_sequence = fwd_seq_gen.forward_sequence_generator(glycan_tree)\n            emssions = glycan.get_filtered_monosaccharide_emssions()\n            if include_linkage:\n                emssions += glycan.get_filtered_linkage_emssions()\n            if fwd_tree_sequence[-1] != glycan.get_num_nosaccharides() - 1:\n                print('oops')\n            bind_fwd_probs = forward.forward(hmm, glycan_tree, [emssions], fwd_tree_sequence)\n            case_ll = logsumexp(bind_fwd_probs.iloc[:, -1])\n            ll += case_ll\n            \n        print(max_iterations * (i + 1), ll)\n    return newparam\n\nif __name__ == \"__main__\":\n\n    #log_format = '%(asctime)s %(message)s'\n    #$logging.basicConfig(stream=sys.stdout, level=logging.INFO,\n    #                    format=log_format, datefmt='%m/%d %I:%M:%S %p')\n    \n    # get arguments\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--num_states', help='num of hidden states', type = int, default = 2)\n    parser.add_argument('--include_linkage', help='0 for no, 1 for yes', type = int, default = 0)\n    args = parser.parse_args()\n\n    num_states = args.num_states\n    include_linkage = True if args.include_linkage > 0 else False\n\n    # read iupac and get gylcans\n    iupac_name_file = './Data/IUPAC.csv'\n    iupacs = get_iupcas(iupac_name_file)\n    #create_and_train_treehmm(num_states, iupacs, max_iterations = 5)\n    #create_and_train_treehmm(num_states, iupacs, max_iterations = 10)\n    #create_and_train_treehmm(num_states, iupacs, max_iterations = 20)\n    #create_and_train_treehmm(num_states, iupacs, max_iterations = 30)\n    #create_and_train_treehmm(num_states, iupacs, max_iterations = 40)\n    \n    gylcans, possible_monosaccharide_emissions, possible_linkage_emissions = get_glycans(iupacs)\n    joint_adj_matrix, joint_monosaccharide_emission_observations, joint_linkage_emission_observations = create_forest_inputs(gylcans)\n\n    #print(possible_monosaccharide_emissions)\n    monosaccharide_emission_observations_counts = {}\n    for item in possible_monosaccharide_emissions:\n        monosaccharide_emission_observations_counts[item] = 0\n    for item in joint_monosaccharide_emission_observations:\n        monosaccharide_emission_observations_counts[item] += 1\n    print(monosaccharide_emission_observations_counts)\n\n    possible_linkage_emissions_counts = {}\n    for item in possible_linkage_emissions:\n        possible_linkage_emissions_counts[item] = 0\n    for item in joint_linkage_emission_observations:\n        possible_linkage_emissions_counts[item] += 1\n    print(possible_linkage_emissions_counts)\n", "meta": {"hexsha": "5a3216a89938691c5c42d85a6949e980a771532a", "size": 9202, "ext": "py", "lang": "Python", "max_stars_repo_path": "treehmm4glycan.py", "max_stars_repo_name": "TreeHMM4Glycan/TreeHMM4Glycan", "max_stars_repo_head_hexsha": "3fe654307a0d6b0b2a5d727ef0e3b1e40c965e67", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "treehmm4glycan.py", "max_issues_repo_name": "TreeHMM4Glycan/TreeHMM4Glycan", "max_issues_repo_head_hexsha": "3fe654307a0d6b0b2a5d727ef0e3b1e40c965e67", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "treehmm4glycan.py", "max_forks_repo_name": "TreeHMM4Glycan/TreeHMM4Glycan", "max_forks_repo_head_hexsha": "3fe654307a0d6b0b2a5d727ef0e3b1e40c965e67", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.2412060302, "max_line_length": 144, "alphanum_fraction": 0.7276678983, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3702253925955867, "lm_q1q2_score": 0.19378350417746953}}
{"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 25 10:10:28 2017\n\n@author: Katherine\n\"\"\"\n\n#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 23 16:04:21 2017\n\n@author: Katherine\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nPhotosynthesis and Stomatal Conductance Model \nCreated 9/27/2016\nKatherine Wentz\n\nThis is a program that runs photosynthesis and\nstomatal conductance models given changes in leaf-\nlevel traits. \n\nThe end product is graphs of NUE vs. WUE.\n\n\nUpdate: I am going to run the model for plants with \ntraits that are distinctive of the meadow moisture \ngradient in the alpine tundra.\n\nFix: correct for atmospheric pressure differences in co2, o2, and vapor pressure\n\nFix: vcmax temp dependence (pg 63 in plant physiological ecology book)\n\nFix: NEW VARIBALE TRAIT-->make the fraction of leaf N in rubisco go down with increasing SLA,\nchlorophyll content, and decreasing light (wet meadow)--more N is allocated\nto thylakoids. The only way for chl/m2 to increase even when g N/m2 goes down\nor is constant is for the leaf to allocate more of leaf N to chl...also, note\nthat there is more organic N designated to photo in leaf when SLA goes up\nbecause less N is used in structure. see \"Photosynthesis or persistence: N allocation\nin leaves of evergreen and deciduous... by Takashima et al. 2004. Also see Photosynthetic\nnitrogen-use efficiency of species...by Poorter and Evans 1998\n\nNote to self: NUE and WUE relationship flipflops with change in air temperature;\nNUE makes sense because C:N decreases from dry to wet meadows; WUE increasing\nin snowbed does not necessarilly make sense--look in the literature for this\n\nherbs have a higher NUE\n\n\"\"\"\n\n#---------------Import Modules---------------#\n\nimport itertools as it\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n#Import combinations of variable parameters \nfrom uncertain_params import monte_carlo\n\n#Import photosynthesis model\nfrom Photosynthesis_Model import photo_bound_meso_eqstom as photo\n\n#Import functions to switch between Pa and umol/mol at sea level\nfrom photo_functions import pa_con_atmfrac\n\n\n#import timeseries of vwc and temp\nfrom time_dep_params import surtemp_dm, surtemp_wm, vwc_dm, vwc_wm, na_dm_min_inter,na_wm_min_inter,na_dm_max_inter,na_wm_max_inter\n\n\n#---------------Determine if I Want to Keep Any of the Variable Parameters Constant---------------#\n\nconst_params=[]\nfor xxx in it.combinations(['ht'],0): #keep ht and t constant for constant vpd\n    const_params+=[xxx]\n\n#do this when I do not put any of the variable parameters as constant. instead I \n#vary each parameter one at a time while keeping the other parameters constant.\nif const_params==[()]:\n    const_params=[[-999999]]   \n\n#---------------Begin Looping Through Photosynthesis Model---------------#\n\n#each loop is for a constant value, or combinatin of constant values, of variable parameter as determined above\nfor ii in range(len(const_params)):\n\n\n\n\n    #---------------Run through time series---------------#\n    \n    days=np.linspace(1,365,365)\n    \n    #dry meadow\n    tot_nue_dm_avg=[]\n    tot_wue_dm_avg=[]\n    tot_nue_dm_min=[]\n    tot_wue_dm_min=[]\n    tot_nue_dm_max=[]\n    tot_wue_dm_max=[]\n    tot_A_dm_avg=[]\n    tot_gs_dm_avg=[]\n    \n    #moist meadow\n    tot_nue_mm_avg=[]\n    tot_wue_mm_avg=[]\n    tot_nue_mm_min=[]\n    tot_wue_mm_min=[]\n    tot_nue_mm_max=[]\n    tot_wue_mm_max=[] \n    tot_A_mm_avg=[]\n    tot_gs_mm_avg=[]\n\n    #wet meadow\n    tot_nue_wm_avg=[]\n    tot_wue_wm_avg=[]\n    tot_nue_wm_min=[]\n    tot_wue_wm_min=[]\n    tot_nue_wm_max=[]\n    tot_wue_wm_max=[]\n    tot_A_wm_avg=[]\n    tot_gs_wm_avg=[]\n\n\n        \n\n    \n    \n\n\n\n    #---------------Photosynthesis + Stomatal Conductance Model---------------#\n\n    \n    ##---Constant Parameter Arrays for Model---##\n\n    #----Params Used in Model Currently----#\n      \n    tk_25=298.16; #absolute temperature at 25 C\n    ekc=80500.0 #Activation energy for K of CO2 (J mol-1)\n    eko=14500.0 #Activation energy for K of O2 (J mol-1)\n    etau=-29000.0  #Activation energy for tau (???) (J mol-1)\n    ev=55000.0 #Activation energy for carboxylation (J mol-1)\n    ej=55000.0 #Activation energy for electron transport (J mol-1)\n    toptv=303.0 #Optimum temperature for maximum carboxylation (K)\n    toptj=303.0 #Optimum temperature for maximum electron transport (K)\n    ra=np.zeros(shape=1)+20.7 #specific rubisco activity (umol CO2/g Rub s)\n    flnr=np.zeros(shape=1)+0.1 #fraction of leaf nitrogen in rubisco (g N Rub/g N leaf)\n    frnr=np.zeros(shape=1)+6.25 #weight fraction of nitrogen in rubisco molecule (g Rub/g N Rub) \n    rh=np.zeros(shape=1)+0.5 #relative humidity (kPa/kPa)\n    ca=np.zeros(shape=1)+405 #ambient carbon dioxide (umol CO2/mol air)\n    ko25=np.zeros(shape=1)+30000 #Michaelis-Menten kinetic coefficient for oxygen at 25 C(Pa) \n    kc25=np.zeros(shape=1)+30 #Michaelis-Menten kinetic coefficient for carbon dioxide at 25 C (Pa)\n    o=np.zeros(shape=1)+210000 #concentration of ambient oxygen (umol/mol)\n    g0=np.zeros(shape=1)+0.002 #Ball-Berry stomatal conductance intercept parameter (mol H2O/m2s)\n    a=np.zeros(shape=1)+1.6 #Conversion Coefficient between stomatal conductance to water and carbon dioxide (unitless)\n    ij=np.zeros(shape=1)+1.0 #leaf angle index--downregulates jmax\n    m=np.zeros(shape=1)+9.0 #ball-berry parameter (unitless)\n    b=1.37 #Conversion Coefficient between boundary layer conductance to water and carbon dioxide \n    u=5.0 #windspeed (m/s)\n    qeff=0.32 #leaf quantum yield, electrons\n    PAR=2000 #photosynthetic active radiation (umol/m2s)\n    jm=2.68 #slope coefficient \n    vwc_min=0.08 #minimum soil water content for photosynthesis to occur (permanent wilting point) (cm3/cm3) \n    vwc_max=0.68 #maximum soil water content where increases in soil water do not affect photosynthesis (field capacity?) (cm3/cm3)\n    q=0.2 #parameter for soil water affect on photosynthesis (unitless)\n   \n    \n    #------constant variable params for sensitivty analysis-----#\n    \n    chl_c=np.zeros(shape=1)+(np.mean([396,465,476])) #Chlorophyll Content of the Leaf (umol chl/m2)\n    ht_c=np.zeros(shape=1)+(np.mean([9.2,19.5,20.0])) #Temperature of the Leaf (K)\n    dia_c=np.zeros(shape=1)+(np.mean([1.4,2.3,2.6])/100.) #Mean diameter or size of leaf (m)\n    na_c=np.zeros(shape=1)+(np.mean([2.5,5.6,6.3])) #leaf nitrogen (g N/ m2)\n    t_c=np.zeros(shape=1)+15.0 #temp (C)\n\n\n    #-----which timeseries should I use--based on factorial meadow type---#\n    \n    na_min=[na_dm_min_inter, na_dm_min_inter, na_wm_min_inter, na_wm_min_inter]\n    na_max=[na_dm_max_inter, na_dm_max_inter, na_wm_max_inter, na_wm_max_inter]\n\n    vwc_type=[vwc_dm,vwc_dm,vwc_wm,vwc_wm]\n    temp_type=[surtemp_dm,surtemp_dm,surtemp_wm,surtemp_wm]\n\n    \n    A_tot_all=[]\n    \n    chl_mean=[[395.7132],[475.8913],[395.7132],[475.8913]]\n    chl_sd=[[24.410199999999975],[29.185099999999977],[24.410199999999975],[29.185099999999977]]\n    dia_mean=[[1.6/100.],[3.0/100.],[1.6/100.],[3.0/100.]]\n    dia_sd=[[0.9/100.0],[1.2/100.0],[0.9/100.0],[1.2/100.0]]\n    ht_mean=[[9.183549],[19.98519],[9.183549],[19.98519]]\n    ht_sd=[[1.5],[3.1],[1.5],[3.1]]\n    \n    depth=[0.2,0.2,0.2,0.4,0.4,0.4]\n    \n\n#---------------Import Variable Parameter Arrays from Leaf Parameter File---------------#\n    for iii in range(len(chl_mean)):\n        A_tot=0\n        for time in range(129):\n            params=monte_carlo(chl_mean[iii], chl_sd[iii], dia_mean[iii], dia_sd[iii], [na_min[iii][time]], [na_max[iii][time]], ht_mean[iii], ht_sd[iii])        \n            A_day=[]\n            for xx in range(len(params)):\n                for yy in range(len(params[xx])):\n                    for key,val in params[xx][yy].items():\n                        exec(key + '=val')\n                                 \n                    #set variable parameters constant if I specify this above\n                    if 'na' in const_params[ii]:\n                        na=na_c\n                    if 'dia' in const_params[ii]:\n                        dia=dia_c\n                    if 'chl' in const_params[ii]:\n                        chl=chl_c\n                    if 'ht' in const_params[ii]:\n                        ht=ht_c\n            \n              \n                    #------calculate vapor pressure-----#\n                    pa_v=611*np.exp((17.27*temp_type[iii][time])/(temp_type[iii][time]+237.3)) #saturation vapor pressure of air (Pa)\n                    ea_str=pa_con_atmfrac(pa_v,3528) #saturation vapor pressure of air (Pa-->umol h20/mol air)\n                    ea=rh*ea_str #vapor pressure (umol h2O/mol air)                \n        \n        \n                    #correct for leaf temperatures using leaf height\n           \n                    t_diff=18-0.4*ht\n                \n                    tl=temp_type[iii][time]+t_diff      \n                    \n                    z=depth[iii]\n                    \n                    #---------------Photosynthesis Function---------------#\n                \n                    #alter this line of code for when implementing different photosynthesis functions\n                    wue, nue, A, E, cs, ci, gsw, gs, gbw, gb, gm, cc,dd =photo(tk_25,ekc,eko,etau,ev,ej,toptv,toptj,na, qeff, PAR,tl,ea,chl,ij,kc25,ko25,o,ca,rh,m,a,frnr,flnr,ra,jm,g0,b,dia,u,q,vwc_min,vwc_max,vwc_type[iii][time],z)\n         \n               \n                    #test to make sure wue and nue are positive at not 'nan'\n                    if wue[0]==-999 and nue[0]==-999:\n                   \n                        continue                                \n                    \n                    if np.isnan(A[0]):\n                        A[0]=0.0\n                    \n                    A_day+=[(A[0]*3600*6)/1000000.*44.]\n                \n\n            A_tot+=np.mean(A_day)\n\n                \n            \n        A_tot_all+=[A_tot]\n        print A_tot_all\n\n        \n        \nprint A_tot_all                    \n    \n\n", "meta": {"hexsha": "25ec21860a4a7eb90ce6aa2fe9f2d92be59b0512", "size": 9910, "ext": "py", "lang": "Python", "max_stars_repo_path": "Traits_Physical_Factorial_CummulativeGS.py", "max_stars_repo_name": "kwentz10/Photosynthesis_Optimization_Modeling", "max_stars_repo_head_hexsha": "864c174ae4298bfdabee36fd0305c6a3649c38bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Traits_Physical_Factorial_CummulativeGS.py", "max_issues_repo_name": "kwentz10/Photosynthesis_Optimization_Modeling", "max_issues_repo_head_hexsha": "864c174ae4298bfdabee36fd0305c6a3649c38bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Traits_Physical_Factorial_CummulativeGS.py", "max_forks_repo_name": "kwentz10/Photosynthesis_Optimization_Modeling", "max_forks_repo_head_hexsha": "864c174ae4298bfdabee36fd0305c6a3649c38bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9776119403, "max_line_length": 232, "alphanum_fraction": 0.6206861756, "include": true, "reason": "import numpy", "num_tokens": 2710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.1937835041774695}}
{"text": "#Script to generate DSWE Version 2 Prototype 1 (V2_P1) Open Source Distribution Version 2 (distro_v3)\n#\n#\n#\n# *****************DEPENDENCIES*******************************************\n# Python 2.7 64 bit, will not run on 32 bit Python\n# GDAL 2.1+\n# numpy 1.12\n# lxml 3.7+\n#\n# *****************REVISION HISTORY*************************************** \n# Initiated on 08/13/16 by John W. Jones.\n# Modified on 8/15/16 by Jacob Shermeyer to improve efficiency and activate\n#  recoding scheme to produce the interpreted layer.\n# Modified on 11/08/16 by John W. Jones to improve documentation as well as\n#  revise the recode scheme to produce revised interpreted layer.\n# Modified on 11/14/2016 to add slope masking.\n# Modified on 1/18/2017 to enhance processing speed and remove a few unnecessary items\n# Modified on 2/22/2017 to change to open source implementation (GDAL and numpy)\n# Modified through March and April 2017 to add hillshade, modify slope masking, and update to the \n#   new SR naming convention\n# Modified April 27-28 2017 to remove NLCD masking, remove redundant opening and closing of files,\n#   generally improve performance, and change output bands to only those that will be distributed.\n#   Note also, that the calculation of percent slope and hillshade layers are assumed to occur\n#   outside of this code (in a pre-processing program).\n#\n# *****************INPUT FILE STRUCTURE***********************************\n#  Required inputs for DSWE are LSRP data, the CFMask file generated by EROS, percent slope and hillshade\n#   The input file directory should contain subdirectories in which all the geotiff formatted bands of a single\n#  input scene have been extracted from their zip files and are stored in seperate folders.\n#  Naming conventions of these files must not be edited in ANY way!  Use the default filenames as they were distributed by EROS.\n#   04/28/2017\n#  With this version, a percent slope file for the US is stored at the top level of the input directory. And hillshade data\n#   calculated using the scene-specific solar geometry included in the mtl or xml file is included in\n#   the same folder as each set of unzipped LSRP file associated with each scene. \n# This data derived from the DEM should be at 30m spatial resolution, snapped to your Landsat image and MUST be projected to match\n#   the Landsat UTM zone.  It should be slighlty larger than your path/row.\n# \n#\n# *****************VARIABLE DECLARATIONS***********************************\n#\n# Input (data) variables\n# BLUE = Landsat TM/ETM Band 1 or OLI Band 2\n# GREEN = Landsat TM/ETM Band 2 or OLI Band 3 \n# NIR = Landsat TM/ETM Band 4 or OLI Band 5\n# SWIR1 = Landsat TM/ETM Band 5 or OLI Band 6 \n# SWIR2 = Landsat TM/ETM Band 7 or OLI Band 7\n# CF= Landsat Cfmask- Cloud, Cloud Shadow, and Snow Mask distributed with LSRP data\n#\n# *****************CALCULATED VARIABLES ON WHICH DECISIONS ARE MADE*********\n#\n# NDVI = Normalized Difference Vegetation Index\n# MNDWI = Modified Normalized Difference Wetness Index\n# MBSRV = Multiband Spectral Relationship Visible\n# MBSRN = Multiband Spectral Relationship Near-infrared\n# AWEsh = Automated raster Extent Shadow\n# PSW1 = Partial Surface Water 1\n# PSW2 = Partial Surface Water 2\n#\n# *****************OUTPUT INFORMATION*****************************\n# Diagnostic layer- Layer indicating the combination of outcomes of the 5 water tests\n# Interpreted layer- Interpretation of the diagnostic layer:\n#     0= Non-Water, 1= High Confidence water, 2= Medium Confidence Water, 3= Potential Wetland, 4= Low Confidence Water or Wetland\n# Masked Interpreted layer- Cloud, Snow, Slope, and Hillshade\n# Mask Layer- A combination of all masks, combinations of these values indicate a pixel was masked multiple times:\n# 0- No masks applied\n# 2- CFMask Cloud Shadow Mask\n# 3- CFMask Snow Mask\n# 4- CFMask Cloud Mask\n# 10- Slope Mask\n# 20- Hillshade Mask\n# 30- Slope and Hillshade Combination Mask\n\n\n\n#Imports\nimport numpy as np\nimport gdal\nimport os\nimport datetime\nimport glob\nimport sys\nfrom lxml import etree\n\n\n# ******************REQUIRED INPUT PARAMETERS******************************** \nWIGT = 0.124\nAWGT = 0\nAWE_param1 = 2.5\nAWE_param2 = -1.5\nAWE_param3 = -0.25\nPSW1_MNDWI = -0.44\nPSW1_NIR = 1500\nPSW1_SWIR1 = 900\nPSW1_NDVI = 0.7\nPSW2_MNDWI = -0.5\nPSW2_BLUE = 1000\nPSW2_NIR = 2500\nPSW2_SWIR1 = 3000\nPSW2_SWIR2 = 1000\n# Cutoff value for hillshade, values for hillshade range from 1-255, the lower the more shaded.\nHS=110\n\n\n\n# ***************************REQUIRED PATH INFORMATION**************************\n# Specify the path for input and output data,  remember to use / insted of \\ if there are any numbers in the path\ninput_dir = \"H:\\DSWE\\DSWE_V2\\Cal_Val_Inputs_subset\"\noutput_dir = \"H:\\DSWE\\DSWE_V2\\Cal_Val_Outputs_subset\"\n\n\n\n# ***************************REQUIRED SLOPE INFORMATION**************************\n# Slope file you have created must be stored in the input_dir along with the LSRP data\n# The file must have the word \"perslp\" anywhere in the filename and be a .tif image.\n\n\n#Set the overwrite & output environment\ndriver = gdal.GetDriverByName(\"GTiff\")\nos.chdir(input_dir)\npaths = glob.glob('*/')\nprint paths\nfor folder in paths:\n    output_dir2=output_dir + \"/\" + folder\n    if not os.path.exists(output_dir2):\n        os.makedirs(output_dir2)   \n    folder=os.path.join(input_dir,folder)\n    os.chdir(folder)\n    # Identify our percent slope file\n    PerSlpL=[]\n    PerSlpL=glob.glob('*perslp*.tif')\n    if len(PerSlpL) > 1 or len(PerSlpL) < 1:\n        print \"multiple or no PerSlpL files, please place only one PerSlpL file in the LSRP input_dir\"\n        exit()\n    else:\n        print \"Using PerSlpL file:\"\n        print PerSlpL[0]\n        Perslp= os.path.abspath(PerSlpL[0])\n        print Perslp\n    count = 1\n    #Loop through the input directory and identitify our LSRP scenes and save them to the list\n    print datetime.datetime.now()\n    subdirs= glob.glob('*/')\n    print('Found directories: %s' % subdirs)\n    subdirnumber=0\n    subdirnumber+= len(subdirs)\n    print subdirnumber\n    cwd = os.getcwd()\n    print cwd\n    if count <= subdirnumber:\n        T1=datetime.datetime.now()\n        for directory in subdirs:\n            print \"\"\n            print \"\"\n            print \"\"\n            working_dir=folder + \"//\" + directory\n            print working_dir\n            os.chdir(working_dir)\n            inputRaster = []\n            inputRaster= glob.glob('L*')\n            print inputRaster\n          \n            #Identify bands  based upon satellite\n            for raster in inputRaster:\n                filetrim=raster[:5]\n                numtrim=filetrim[4:]\n                if numtrim == \"_\":\n                    filetrim=raster[:4]\n                    numtrim=filetrim[3:]\n                    LSnum=int(numtrim)\n                    length=40\n                    length2=21\n                else:\n                    filetrim=raster[:3]\n                    numtrim=filetrim[2:]\n                    LSnum=int(numtrim)\n                    length=21\n                    length2=13\n                    \n            #Landsat 4,5, and 7\n                if LSnum<=7 :\n                    Blue= working_dir +  '\\%s_sr_band1.tif'%(raster)[0:length]\n                    Green= working_dir +  '\\%s_sr_band2.tif'%(raster)[0:length]\n                    Red= working_dir +  '\\%s_sr_band3.tif'%(raster)[0:length]\n                    NIR= working_dir +  '\\%s_sr_band4.tif'%(raster)[0:length]\n                    SWIR1= working_dir +  '\\%s_sr_band5.tif'%(raster)[0:length]\n                    SWIR2= working_dir +  '\\%s_sr_band7.tif'%(raster)[0:length]\n                    CF = working_dir + '\\%s_cfmask.tif'%(raster)[0:length]\n                    Hillshade= working_dir + '\\%s_hillshade.tif'%(raster)[0:length]\n                    Metadata = working_dir + '\\%s.xml'%(raster)[0:length]\n                    yeartrim=raster[:length2]\n                    year=yeartrim[-4:]\n                    year=int(year)\n            #Landsat 8\n                elif LSnum==8:\n                    Blue= working_dir +  '\\%s_sr_band2.tif'%(raster)[0:length]\n                    Green= working_dir +  '\\%s_sr_band3.tif'%(raster)[0:length]                \n                    Red= working_dir +  '\\%s_sr_band4.tif'%(raster)[0:length]\n                    NIR= working_dir +  '\\%s_sr_band5.tif'%(raster)[0:length]\n                    SWIR1= working_dir +  '\\%s_sr_band6.tif'%(raster)[0:length]\n                    SWIR2= working_dir +  '\\%s_sr_band7.tif'%(raster)[0:length]\n                    CF = working_dir + '\\%s_cfmask.tif'%(raster)[0:length]\n                    Hillshade= working_dir + '\\%s_hillshade.tif'%(raster)[0:length]\n                    Metadata = working_dir + '\\%s.xml'%(raster)[0:length]\n                    yeartrim=raster[:length2]\n                    year=yeartrim[-4:]\n                    year=int(year)\n                else:\n                    print \"Wrong satellite or wonky input, check data.\"\n                    quit()\n                out_name = 'DSWE_V2_P1'\n\n            # Perform Water Index (MNDWI only based) Test- Working\n            GreenB= gdal.Open(Green)\n            SWIR1B= gdal.Open(SWIR1)\n            geo = GreenB.GetGeoTransform()  \n            proj = GreenB.GetProjection()\n            GreenB= GreenB.GetRasterBand(1).ReadAsArray()\n            SWIR1B= SWIR1B.GetRasterBand(1).ReadAsArray()\n            shape = GreenB.shape\n            MNDWI = ((GreenB - SWIR1B) /np.float32(GreenB + SWIR1B))\n            con_MNDWI=MNDWI.copy()\n            con_MNDWI[con_MNDWI <= WIGT] = 0\n            con_MNDWI[con_MNDWI > WIGT] = 1\n            con_MNDWI=np.int8(con_MNDWI)\n            #Optional to output MNDWI test\n            #con_MNDWI1_out = driver.Create( \"con_MNDWI1.tif\", shape[1], shape[0], 1, gdal.GDT_UInt16)\n            #con_MNDWI1_out.SetGeoTransform( geo )\n            #con_MNDWI1_out.SetProjection( proj ) \n            #con_MNDWI1_out.GetRasterBand(1).WriteArray(con_MNDWI)\n            #con_MNDWI1_out=None                                                   \n\n            # Perform MBSR Test- Working\n            RedB= gdal.Open(Red)\n            RedB= RedB.GetRasterBand(1).ReadAsArray()\n            MBSV = (GreenB + RedB)\n            NIRB= gdal.Open(NIR)\n            NIRB= NIRB.GetRasterBand(1).ReadAsArray()\n            MBSRN = (NIRB + SWIR1B)\n            con_MBSR=np.zeros(shape)\n            con_MBSR[MBSV > MBSRN] = 10\n            con_MBSR=np.int8(con_MBSR)\n            del MBSV\n            #Optional to output MBSR test\n            #con_MBSR_out = driver.Create( \"con_MBSR.tif\", shape[1], shape[0], 1, gdal.GDT_UInt16)\n            #con_MBSR_out.SetGeoTransform( geo )\n            #con_MBSR_out.SetProjection( proj ) \n            #con_MBSR_out.GetRasterBand(1).WriteArray(con_MBSR)\n            #con_MBSR_out=None\n\n            #Calculate AWEsh values- working\n            con_AWEsh = (np.float32(GreenB) * AWE_param1)\n            con_AWEsh += (np.float32(MBSRN) * AWE_param2)\n            MBSRN_out = driver.Create( \"MBSRN.tif\", shape[1], shape[0], 1, gdal.GDT_UInt32)\n            MBSRN_out.SetGeoTransform( geo )\n            MBSRN_out.SetProjection( proj ) \n            MBSRN_out.GetRasterBand(1).WriteArray(MBSRN)\n            MBSRN_out=None\n            SWIR2B= gdal.Open(SWIR2)\n            SWIR2B= SWIR2B.GetRasterBand(1).ReadAsArray()\n            con_AWEsh += (np.float32(SWIR2B) * AWE_param3)\n            BlueB= gdal.Open(Blue)\n            BlueB= BlueB.GetRasterBand(1).ReadAsArray()\n            con_AWEsh += np.float32(BlueB)\n            con_AWEsh[con_AWEsh > 0] = 100\n            con_AWEsh[con_AWEsh <= 0] = 0\n            con_AWEsh=np.int8(con_AWEsh)\n            #Optional to output AWEsh test\n            #con_AWEsh_out = driver.Create( \"con_AWEsh.tif\", shape[1], shape[0], 1, gdal.GDT_UInt16)\n            #con_AWEsh_out.SetGeoTransform( geo )\n            #con_AWEsh_out.SetProjection( proj ) \n            #con_AWEsh_out.GetRasterBand(1).WriteArray(con_AWEsh)\n            #con_AWEsh_out=None\n\n\n            # Perform Partial Surface Water test 1 (PSW1)-working\n            con_PSW1_MNDWI=((GreenB - SWIR1B) /np.float32(GreenB + SWIR1B))\n\n            con_PSW1_MNDWI[con_PSW1_MNDWI > PSW1_MNDWI] = 1\n            con_PSW1_MNDWI[con_PSW1_MNDWI <= PSW1_MNDWI] = 0\n            con_PSW1_MNDWI=np.int8(con_PSW1_MNDWI)\n            NIRB[NIRB < PSW1_NIR] = 1\n            NIRB[NIRB >= PSW1_NIR] = 0\n            PSW1= np.int8(con_PSW1_MNDWI) * np.int8(NIRB)\n            PSW1_SWIR1B=SWIR1B.copy()\n            PSW1_SWIR1B[PSW1_SWIR1B < PSW1_SWIR1] = 1\n            PSW1_SWIR1B[PSW1_SWIR1B >= PSW1_SWIR1] = 0\n            PSW1= np.int8(PSW1) * np.int8(PSW1_SWIR1B)\n            del PSW1_SWIR1B\n            \n            # Calculate NDVI\n            NIRB= gdal.Open(NIR)\n            NIRB= NIRB.GetRasterBand(1).ReadAsArray()            \n            NDVI = ((NIRB - RedB) /np.float32(NIRB + RedB))\n            con_NDVI=np.zeros(shape)\n            con_NDVI[NDVI < PSW1_NDVI] = 1\n            PSW1= np.int16(PSW1) * np.int16(con_NDVI) * 1000\n            #Optional to output PSW1 test\n            #PSW1_out = driver.Create( \"PSW1.tif\", shape[1], shape[0], 1, gdal.GDT_UInt16)\n            #PSW1_out.SetGeoTransform( geo )\n            #PSW1_out.SetProjection( proj ) \n            #PSW1_out.GetRasterBand(1).WriteArray(PSW1)\n            #PSW1_out=None\n            \n            #Perform PSW2 test- working\n            con_PSW2_MNDWI=((GreenB - SWIR1B) /np.float32(GreenB + SWIR1B))\n            con_PSW2_MNDWI[con_PSW2_MNDWI > PSW2_MNDWI] = 1\n            con_PSW2_MNDWI[con_PSW2_MNDWI <= PSW2_MNDWI] = 0\n            con_PSW2_MNDWI=np.int8(con_PSW2_MNDWI)\n            BlueB[BlueB < PSW2_BLUE] = 1\n            BlueB[BlueB >= PSW2_BLUE] = 0\n            BlueB=np.int8(BlueB) \n            NIRB[NIRB < PSW2_NIR] = 1\n            NIRB[NIRB >= PSW2_NIR] = 0\n            NIRB=np.int8(NIRB)\n            SWIR1B[SWIR1B < PSW2_SWIR1] = 1\n            SWIR1B[SWIR1B >= PSW2_SWIR1] = 0\n            SWIR1B=np.int8(SWIR1B) \n            SWIR2B[SWIR2B < PSW2_SWIR2] = 1\n            SWIR2B[SWIR2B >= PSW2_SWIR2] = 0\n            SWIR2B=np.int8(SWIR2B)\n            PSW2= con_PSW2_MNDWI * BlueB * NIRB * SWIR1B *  SWIR2B * 10000\n            #Optional to output PSW2 test\n            #PSW2_out = driver.Create( \"PSW2.tif\", shape[1], shape[0], 1, gdal.GDT_UInt16)\n            #PSW2_out.SetGeoTransform( geo )\n            #PSW2_out.SetProjection( proj ) \n            #PSW2_out.GetRasterBand(1).WriteArray(PSW2)\n            #PSW2_out=None\n            del GreenB, SWIR1B, MNDWI, RedB, NIRB, MBSRN, SWIR2B, BlueB, con_PSW1_MNDWI, con_NDVI, con_PSW2_MNDWI\n            diagmap= con_MNDWI + con_MBSR + con_AWEsh + PSW1 + PSW2\n            del con_MNDWI, con_MBSR, con_AWEsh, PSW1, PSW2\n            \n            os.chdir(input_dir)\n\n            \n            # Terrain Correction, here we are simply recoding slopes >=x degrees to PS (specified above), which will be reclassified as non-water.\n\n            perslp = gdal.Open(Perslp)\n            #Get extent and projection\n            perslpgeo = perslp.GetGeoTransform()\n            perslpproj = perslp.GetProjection()\n            # Calculate percent slope\n            #perslp= perslp.GetRasterBand(1).ReadAsArray()\n            os.chdir(working_dir)\n            CF = gdal.Open(CF)\n            #Get extent of CF mask (and our LS image by proxy)\n            geoTransform = CF.GetGeoTransform()\n            minx = geoTransform[0]\n            maxy = geoTransform[3]\n            maxx = minx + geoTransform[1] * CF.RasterXSize\n            miny = maxy + geoTransform[5] * CF.RasterYSize\n            #Clip our slope and hillshade mask to the image (have to do this for each image due to the variable extents of each image)\n            GeoClip= [minx, maxy, maxx, miny]\n            print GeoClip\n            hillshade= gdal.Open(Hillshade)\n            perslp_clip=gdal.Translate('perslp_clip.tif', perslp, projWin = GeoClip)\n            hillshade_clip=gdal.Translate('hillshade_clip.tif', hillshade, projWin = GeoClip)\n            hillshade= hillshade_clip.GetRasterBand(1).ReadAsArray()\n            hillshade[hillshade <= HS] = 0\n            hillshade[hillshade > HS] = 1\n            \n            #Read in the slope and hillshade masks and convert to an array\n            workingoutput_dir=output_dir2 + \"\\\\\" + directory\n            if not os.path.exists(workingoutput_dir):\n                os.makedirs(workingoutput_dir)\n                \n            #calculate our unmasked diagnostic map\n            CF= CF.GetRasterBand(1).ReadAsArray()\n            diagoutput=output_dir2 +  \"\\\\\" + directory + \"\\\\\" + out_name + \"_diag\" + \"_%s.tif\"%\"_\".join(raster.split('_'))[0:length]\n            diagmap[np.where((CF == 255))] = -9999\n            diagmap_out = driver.Create( diagoutput, shape[1], shape[0], 1, gdal.GDT_Int16)\n            diagmap_out.SetGeoTransform( geo )\n            diagmap_out.SetProjection( proj )\n            diagmap_out.GetRasterBand(1).WriteArray(diagmap)\n            diagmap_out.GetRasterBand(1).SetNoDataValue(-9999)\n                \n            \n            # Output unmasked interpreted map\n            interpoutput=output_dir2 +  \"\\\\\" + directory + \"\\\\\" + out_name + \"_interp\" + \"_%s.tif\"%\"_\".join(raster.split('_'))[0:length]\n            interpmap=diagmap.copy()\n            interpmap[np.where((diagmap == 0) | (diagmap == 1) | (diagmap == 10) | (diagmap == 100) | (diagmap == 1000))] = 0\n            interpmap[np.where((diagmap == 1111) | (diagmap == 10111) | (diagmap == 11011) | (diagmap == 11101) | (diagmap == 11110) | (diagmap == 11111)) ] = 1\n            interpmap[np.where((diagmap == 111) | (diagmap == 1011) | (diagmap == 1101) | (diagmap == 1110) | (diagmap == 10011) | (diagmap == 10101) | (diagmap == 10110) | (diagmap == 11001) | (diagmap == 11010) | (diagmap == 11100)) ] = 2\n            interpmap[np.where((diagmap == 11000)) ] = 3\n            interpmap[np.where((diagmap == 11) | (diagmap == 101) | (diagmap == 110) | (diagmap == 1001) | (diagmap == 1010) | (diagmap == 1100) | (diagmap == 10000) | (diagmap == 10001) | (diagmap == 10010) | (diagmap == 10100)) ] = 4\n            interpmap[np.where((diagmap == -9999)) ] = 255\n            interpmap_out = driver.Create( interpoutput, shape[1], shape[0], 1, gdal.GDT_Byte)\n            interpmap_out.SetGeoTransform( geo )\n            interpmap_out.SetProjection( proj )\n            interpmap_out.GetRasterBand(1).WriteArray(interpmap)\n            interpmap_out.GetRasterBand(1).SetNoDataValue(255)\n\n\n            # Mask interpreted map using the slope file\n            perslp= perslp_clip.GetRasterBand(1).ReadAsArray()\n            interpmap_copy=interpmap.copy()\n            interpmap[np.where((perslp >= 30) & (interpmap == 2))] = 0\n            interpmap[np.where((perslp >= 20) & (interpmap == 3))] = 0\n            interpmap[np.where((perslp >= 10) & (interpmap == 4))] = 0\n            interpmap[np.where((perslp >= 30) & (interpmap == 1))] = 0\n            interpmap_masked= interpmap * hillshade           \n\n   \n            \n            #Cloud and snow masking and outputing masked interpreted layer\n            interpmaskoutput=output_dir2 +  \"\\\\\" + directory + \"\\\\\" + out_name + \"_interp_masked\" + \"_%s.tif\"%\"_\".join(raster.split('_'))[0:length]\n            interpmap_masked=interpmap_masked.copy()\n            interpmap_masked[np.where((CF == 255))] = 255\n            interpmap_masked[np.where((CF >= 2) & (CF < 255))] = 9\n            interpmap_masked_out = driver.Create( interpmaskoutput, shape[1], shape[0], 1, gdal.GDT_Byte)\n            interpmap_masked_out.SetGeoTransform( geo )\n            interpmap_masked_out.SetProjection( proj )\n            interpmap_masked_out.GetRasterBand(1).WriteArray(interpmap_masked)\n            interpmap_masked_out.GetRasterBand(1).SetNoDataValue(255)\n            del interpmap_masked_out\n            del diagmap\n            del interpmap\n\n\n\n            #Create a full mask layer\n            CF[np.where((CF == 1)) ] = 0\n            perslp[np.where((perslp < 10) & (interpmap_copy == 4)) ] = 0\n            perslp[np.where((perslp < 20) & (interpmap_copy == 3)) ] = 0\n            perslp[np.where((perslp < 30) & (interpmap_copy == 2)) ] = 0\n            perslp[np.where((perslp < 30) & (interpmap_copy == 1)) ] = 0\n            perslp[np.where((perslp >= 10) & (interpmap_copy == 4)) ] = 10\n            perslp[np.where((perslp >= 20) & (interpmap_copy == 3)) ] = 10\n            perslp[np.where((perslp >= 30) & (interpmap_copy == 2)) ] = 10\n            perslp[np.where((perslp >= 30) & (interpmap_copy == 1)) ] = 10\n            perslp[np.where((interpmap_copy == 0)) ] = 0       \n            hillshade[np.where((hillshade == 0)) ] = 20\n            hillshade[np.where((hillshade == 1)) ] = 0\n            MaskLayer=CF + perslp + hillshade\n            MaskLayerOut=output_dir2 +  \"\\\\\" + directory + \"\\\\\" + out_name + \"_MaskLayer\" + \"_%s.tif\"%\"_\".join(raster.split('_'))[0:length]\n            MaskLayer[np.where((CF == 255))] = 255\n            MaskLayer_Output = driver.Create(MaskLayerOut, shape[1], shape[0], 1, gdal.GDT_Byte)\n            MaskLayer_Output.SetGeoTransform( geo )\n            MaskLayer_Output.SetProjection( proj )\n            MaskLayer_Output.GetRasterBand(1).WriteArray(MaskLayer)\n            MaskLayer_Output.GetRasterBand(1).SetNoDataValue(255)\n            del hillshade_clip, hillshade, MaskLayer, CF, MaskLayerOut, MaskLayer_Output, diagoutput\n            del Metadata, diagmap_out, interpmap_masked, interpmap_out, interpmaskoutput, interpoutput, perslp, perslp_clip           \n            \n            itemlist=[\"hillshade*.tif\", \"perslp*.tif\"]\n            for item in itemlist:\n                i=glob.glob(item)\n                for r in i:\n                    os.remove(r)\n\n           #Timer\n            print datetime.datetime.now()\n            T2=datetime.datetime.now()\n            T3=T2-T1\n            print T3\n     \n            if count == subdirnumber:\n                break                  \n            else:\n                count=count+1\n                print count\n\n                    \n                    \n\n    \n\n   \n\n\n", "meta": {"hexsha": "47546ad5336c58f2a0f80fbe7827137a506a9432", "size": 22019, "ext": "py", "lang": "Python", "max_stars_repo_path": "dswe/prototype_implementation/DSWE_P1_V2_ESPA_06_05_2017.py", "max_stars_repo_name": "jakebrinkmann/lagoon-water-dragon", "max_stars_repo_head_hexsha": "351db2afc99859e1c87398fdbdcb270a3a16cb83", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dswe/prototype_implementation/DSWE_P1_V2_ESPA_06_05_2017.py", "max_issues_repo_name": "jakebrinkmann/lagoon-water-dragon", "max_issues_repo_head_hexsha": "351db2afc99859e1c87398fdbdcb270a3a16cb83", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dswe/prototype_implementation/DSWE_P1_V2_ESPA_06_05_2017.py", "max_forks_repo_name": "jakebrinkmann/lagoon-water-dragon", "max_forks_repo_head_hexsha": "351db2afc99859e1c87398fdbdcb270a3a16cb83", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.7494692144, "max_line_length": 240, "alphanum_fraction": 0.5835869022, "include": true, "reason": "import numpy", "num_tokens": 6258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.19378350417746948}}
{"text": "\"\"\"Tensorflow implementation of adversarial autoencoders.\n\nOriginally based on [1] with significant changers.\n\n\n\nDemo (command line)\n===================\n\nconda activate tf114\npython -m dltb.thirdparty.tensorflow.aae\n\n\n\nDemo (interactive)\n==================\n\n# import tensorflow as tf\nimport tensorflow.compat.v1 as tf\nfrom ulf import SupervisedAdversarialAutoencoder\naae = SupervisedAdversarialAutoencoder(code_dim=2)\naae.prepare()\n\nsaver = tf.train.Saver(name='aae', filename=\"my_test_model\")\nsess = tf.InteractiveSession()\naae.set_tensorflow_session(sess)\nstart_epoch = aae._tf_initialize_variables(sess, saver)\n\naae.plot_data_codes_2d(test_xs, labels=test_ys)\n\naae.plot_recoded_images(test_xs[:100], labels=test_ys[:100])\n\naae.plot_decoded_codespace_2d(labels=3)\n\naae.plot_analogical_decoding()\n\nsess.close()\n\n\nData\n====\n# data are numpy.ndarray.\n# xs: image pixel data\n#     dtype=float64, min/max=0.0/1.0,\n#     shape=(batch, height, width, channels)\n# ys: one-hot encoded class labels\n#     dtype=float64, min/max=0.0/1.0\n#     shape=(batch, classes)\n\n      sellf._data_semi_pipeline = data_pipeline(self._conf.data)\n      self._valid_xs = self._valid_xs[:self._conf.num_samples]\n      self._valid_ys = self._valid_ys[:self._conf.num_samples]\n\n\nReferences\n==========\n[1] https://github.com/MINGUKKANG/Adversarial-AutoEncoder.git\n\"\"\"\n\n# pylint: disable=too-many-lines\n# pylint: disable=fixme\n# pylint: disable=unexpected-keyword-arg,no-value-for-parameter\n\n\n# standard imports\nfrom typing import Tuple, Optional, Sized, Union\nimport time\nimport datetime\n\n# third-party imports\nimport numpy as np\nfrom tqdm import tqdm\n\n# toolbox imports\nfrom dltb.datasource import Datasource\nfrom dltb.base.data import add_noise\nfrom dltb.util.plot import TilingPlotter\nfrom dltb.util.distributions import gaussian, gaussian_mixture, swiss_roll\nfrom . import v1 as tf\nfrom .v1 import Utils as tf_helper\nfrom .ae import Autoencoder\n\n\nclass AdversarialAutoencoder(Autoencoder):\n    \"\"\"Base class for the TensorFlow Adversarial Autoencoder (AAE)\n    implementation.  The AAE extends the basic Autoencoder (AE) by\n    introducing an additional training objective to force the encoder\n    to produces code that is distributed according to a given target\n    distribution (\"prior\").\n\n    The method :py:class:`_sample_prior` allows to samples codes\n    from the target distribution.  There are three different target\n    distributions implemented by this class: `'gaussian'`,\n    `'gaussian_mixture'`, and `'swiss_roll'`.\n\n    Training\n    --------\n    Training the AAE consists of two parts: on the one hand, the full\n    autoencoder stack (encoder + decoder) is trained to minimize the\n    reconstruction error.  On the other hand, the encoder part is\n    trained to fit the code distribution to a given target distribution\n    (\"prior\").  This training employs an adversarial training procedure\n    in which the encoder acts as generator that tries to mimic the\n    target distribution.\n\n    The autoencoder training aims to minimize the reconstruction loss,\n    which is accessible via the property `_tf_loss_reconstruction`.  It is\n    interpreted as the \"negative log likelihood\".  Computing this loss\n    only requires the input data values.\n\n    The adversarial training process consist of two parts: on the one\n    hand it aims to improve the discriminator in its ability to\n    discriminate codes output by the encode from codes sampled from\n    the target distribution. On the other hand it wants the encoder to\n    improve to create codes that follow the target distribution.\n\n    Arguments\n    ---------\n    data:\n        The dataset to use (either 'MNIST' or '')\n\n    \"\"\"\n\n    def __init__(self, data: str = 'MNIST',\n                 prior: str = 'gaussian', **kwargs) -> None:\n        super().__init__(**kwargs)\n        self._conf.data = data\n        self._conf.prior = prior\n\n        # tensorflow placeholders\n        self._tf_prior = None\n\n        # The model\n        self._tf_loss_discriminator = None\n        self._tf_loss_generator = None\n\n        # Optimizers\n        self._tf_optimize_discriminator = None\n        self._tf_optimize_generator = None\n\n        # loss values (per batch)\n        self._loss_discriminator_value = None\n        self._loss_generator_value = None\n\n    def _prepare_tensors(self) -> None:\n        \"\"\"\n        \"\"\"\n        if self._tf_prior is None:\n            self._tf_prior = \\\n                tf.placeholder(tf.float32, shape=[None, self.code_dim],\n                               name=\"z_prior\")\n\n        super()._prepare_tensors()\n\n    @staticmethod\n    def _sample_prior(prior: str, zdim: int, nclasses: int, batch_size: int,\n                      use_label_info: bool) -> Tuple[np.ndarray, np.ndarray]:\n        \"\"\"\n        Results\n        -------\n        prior_style:\n        prior_label_onehot:\n            A 2-dimensional numpy.ndarray of type float holding `prior_label`\n            in one-hot-encoding. The shape is (batch_size, nclasses).\n        \"\"\"\n        if prior == 'gaussian':\n            prior_style, prior_label = \\\n                gaussian(batch_size, labels=nclasses)\n\n        elif prior == 'gaussian_mixture':\n            prior_style, prior_label = \\\n                gaussian_mixture(batch_size, components=nclasses, labels=True)\n\n        elif prior == 'swiss_roll':\n            prior_style, prior_label = \\\n                swiss_roll(batch_size, labels=nclasses)\n\n        else:\n            raise ValueError(f\"Unknow prior: '{prior}'. Known values are: \"\n                             \"gaussian, gaussian_mixture, swiss_roll\")\n\n        prior_label_onehot = np.eye(nclasses, dtype=np.float32)[prior_label]\n        return prior_style, prior_label_onehot\n\n    def _tf_define_optimizers(self, variables) -> None:\n        \"\"\"Prepare the training process. Define optimizers.\n        \"\"\"\n        super()._tf_define_optimizers(variables)\n\n        var_generator = [var for var in variables\n                         if \"encoder\" in var.name]\n        var_discriminator = [var for var in variables\n                             if \"discriminator\" in var.name]\n\n        self._tf_optimize_discriminator = \\\n            tf.train.AdamOptimizer(learning_rate=self._tf_learning_rate/5).\\\n            minimize(self._tf_loss_discriminator,\n                     global_step=self._tf_global_step,\n                     var_list=var_discriminator)\n        self._tf_optimize_generator = \\\n            tf.train.AdamOptimizer(learning_rate=self._tf_learning_rate).\\\n            minimize(self._tf_loss_generator,\n                     global_step=self._tf_global_step,\n                     var_list=var_generator)\n\n    def _tf_train_step(self, sess, feed_dict) -> None:\n        \"\"\"Perform one training step.\n        \"\"\"\n        super()._tf_train_step(sess, feed_dict)\n        # Optmize the reconstruction loss. This requires\n        # 'inputs' and 'outputs' to be given in the 'feed_dict'\n        # _negative_log_likelihood_value, _, _g = \\\n        self._loss_reconstruction_value, _, _g = \\\n            sess.run([self._tf_loss_reconstruction,\n                      self._tf_optimize_reconstruction,\n                      self._tf_global_step],\n                     feed_dict=feed_dict)\n\n        # Discriminator phase\n        self._loss_discriminator_value, _ = \\\n            sess.run([self._tf_loss_discriminator,\n                      self._tf_optimize_discriminator],\n                     feed_dict=feed_dict)\n\n        # Generator phase\n        self._loss_generator_value, _ = \\\n            sess.run([self._tf_loss_generator,\n                      self._tf_optimize_generator],\n                     feed_dict=feed_dict)\n\n\nclass LabeledAutoencoder(Autoencoder):\n    \"\"\"A labeled autoencoder splits the code interpretation into two\n    parts: one part representing the class label (as one-hot encoded\n    vector) while the other part should hold other information\n    (sometimes referred to as \"style\").\n\n    A labeled autoencoder provides methods to compute and access the\n    two code parts (style and label) independently.\n\n    In a `LabeledAutoencoder`, the property :py:prop:`code_dim` refers\n    to the dimensionality of the style part of the code, while the\n    property :py:prop:`nclasses` contains the number of classes.\n    That is, the combined code vector (style + label) has dimensionality\n    `code_dim + nclasses`.\n    \"\"\"\n\n    def __init__(self, nclasses: Optional[int] = None, **kwargs) -> None:\n        super().__init__(**kwargs)\n\n        # properties\n        self._nclasses = nclasses\n\n        # tensorflow placeholders\n        self._tf_labels = None\n\n    @property\n    def nclasses(self) -> int:\n        \"\"\"The number of classes, that is the number of different labels,\n        in this :py:class:`LabeledAutoencoder`.\n        \"\"\"\n        return self._nclasses\n\n    def _prepare_tensors(self) -> None:\n        \"\"\"\n        \"\"\"\n        self._tf_labels = \\\n            tf.placeholder(dtype=tf.float32, shape=[None, self.nclasses],\n                           name=\"Input_labels\")\n\n        super()._prepare_tensors()\n\n    def one_hot(self, labels: np.ndarray,\n                length: Optional[int] = None) -> np.ndarray:\n        \"\"\"Get the given labels in one-hot encoding.\n        \"\"\"\n        if isinstance(labels, Sized):\n            if length is not None and len(labels) != length:\n                raise ValueError(f\"Labels have length {len(labels)} but \"\n                                 f\"should have lenght {length}.\")\n            if isinstance(labels, np.ndarray):\n                if labels.ndim == 2:\n                    return labels\n                if labels.ndim == 1:\n                    return np.eye(self.nclasses, dtype=np.float32)[labels]\n            elif isinstance(labels, list):\n                return np.eye(self.nclasses, dtype=np.float32)[labels]\n        elif isinstance(labels, int):\n            if length is None:\n                raise ValueError(\"You need to specify a length for \"\n                                 \"the one-hot vector\")\n            return np.eye(self.nclasses, dtype=np.float32)[[labels] * length]\n        raise TypeError(\"Unexpected type {type(labels)} for labels.\")\n\n\nclass LabeledAdversarialAutoencoder(LabeledAutoencoder,\n                                    AdversarialAutoencoder):\n    \"\"\"A labeled adversarial autoencoder combines the ideas of the labeled\n    autoencoder and the adversarial autoencoder.  It aims at forcing\n    both, the distribution of the style part of code and the\n    distribution of the label part of the code towards two given\n    priors using adversarial training techniques.\n    \"\"\"\n\n    def __init__(self, **kwargs) -> None:\n        super().__init__(**kwargs)\n\n        # tensorflow placeholders\n        self._tf_prior_style = None\n        self._tf_prior_label = None\n\n    def _prepare_tensors(self) -> None:\n        \"\"\"\n        \"\"\"\n        self._tf_prior_style = \\\n            tf.placeholder(tf.float32, shape=[None, self.code_dim],\n                           name=\"z_prior\")\n        self._tf_prior_label = \\\n            tf.placeholder(tf.float32, shape=[None, self.nclasses],\n                           name=\"prior_labels\")\n\n        self._tf_prior = \\\n            tf.concat([self._tf_prior_style, self._tf_prior_label], axis=1)\n\n        super()._prepare_tensors()\n\n    def plot_analogical_decoding(self, style: Union[np.ndarray, int] = 10,\n                                 plotter: Optional[TilingPlotter] = None,\n                                 **kwargs) -> None:\n        \"\"\"Plot the analogical reasoning results. For a given style,\n        generate analogical exemplas for each of the classes.\n\n        Arguments\n        ---------\n        style:\n            The styles to be used for generation. If an `int`\n            this will specify the number of random styles to\n            to be choosen.\n        \"\"\"\n        # generate random code style samples (styles)\n        if isinstance(style, int):  # number of examples\n            style = np.random.rand(style, self.code_dim)\n        examples = len(style)\n        style = np.repeat(style, self.nclasses, axis=0)\n\n        labels = np.arange(self.nclasses)\n        labels = np.tile(labels, examples)\n        one_hot = self.one_hot(labels)\n\n        codes = np.concatenate((style, one_hot), axis=1)\n\n        # use decoder to generate output data from the combined code.\n        data = self.decode(codes)\n\n        # plot the results\n        if plotter is None:\n            plotter = TilingPlotter()\n        plotter.plot_tiling(data, rows=examples, columns=self.nclasses,\n                            **kwargs)\n\n\nclass SupervisedAdversarialAutoencoder(LabeledAdversarialAutoencoder):\n    \"\"\"Specialized sublasse for a supervised Adversarial Autoencoder (AAE)\n    implementation.\n\n    Notice that the :py:class:`SupervisedAdversarialAutoencoder` is\n    not really an autoencoder, as the code does not contain sufficient\n    information to reconstruct the input.  Instead the decoder needs\n    additional label information.\n\n    The encoder encodes a given input just in the \"style\" part.  This\n    style code has to be combined with the label information to obtain\n    the full code.\n\n    The encoder uses `tf_inputs` to compute the style code which is\n    provided in `tf_encoded_style`.  This can be combined with\n    information from `tf_labels` to obtain the full code vector in\n    `tf_encoded`. The decoder uses `tf_encoded` to reconstruct the\n    data and provides it in `tf_decoded`.\n\n    This specific behavior results in a slight redesign of the\n    autoencoder interface: the methods :py:meth:`encode`,\n    :py:meth:`decode`, and :py:meth:`recode` accept an additional\n    argument `labels` that allows to provide the required class\n    labels.\n\n    \"\"\"\n\n    def __init__(self, **kwargs) -> None:\n        super().__init__(**kwargs)\n        self._conf.model = 'supervised'\n\n        self._tf_encoded_style = None\n\n    def encode(self, data: np.ndarray, batch_size: int = 128,\n               labels: Optional[np.ndarray] = None) -> np.ndarray:\n        \"\"\"Encode data using the encoder part of the autoencoder.\n\n        Arguments\n        ---------\n        data:\n            The data to be encoded.\n\n        Result\n        ------\n        code:\n            The codes obtained from the data. If no label information\n            is available, this will only be the style part of the code.\n        \"\"\"\n        length = len(data)\n        code = np.ndarray((length, self.code_dim))\n\n        offset = 0\n        batches = self._np_batcher(data, batch_size=batch_size)\n        code_batches = \\\n            self._tf_encode_batches(batches, tf_encoded=self._tf_encoded_style)\n        for batch in code_batches:\n            end = offset + len(batch)\n            code[offset: end] = batch\n            offset = end\n\n        if labels is None:\n            return code\n\n        labels_one_hot = self.one_hot(labels, length=length)\n        return np.concatenate((code, labels_one_hot), axis=1)\n\n    def decode(self, code: np.ndarray, batch_size: int = 128,\n               labels: Optional[np.ndarray] = None) -> np.ndarray:\n        \"\"\"Decode given code values into the data space using the decoder\n        part of the autoencoder.\n\n        Arguments\n        ---------\n        code:\n            The codes to be decoded.\n\n        Result\n        ------\n        data:\n            The reconstructed data.\n        \"\"\"\n        if code.shape[1] == self.code_dim:\n            if labels is None:\n                raise ValueError(\"The supervised autoencoder needs explicit \"\n                                 \"label information for decoding.\")\n            labels_one_hot = self.one_hot(labels, length=len(code))\n            code = np.concatenate((code, labels_one_hot), axis=1)\n        return super().decode(code, batch_size=batch_size)\n\n    def recode(self, data: np.ndarray, batch_size: int = 128,\n               labels: Optional[np.ndarray] = None) -> np.ndarray:\n        \"\"\"Reconstruct data values using the autoencoder, that is first\n        encode the data and the decode it back into the data space.\n\n        Arguments\n        ---------\n        data:\n            The data to be recoded.\n\n        Result\n        ------\n        recoded:\n            The reconstructed data.\n        \"\"\"\n        # FIXME[hack]: just encode + decode. A full tensorflow\n        # recoding would probably be more efficient\n        code = self.encode(data, batch_size=batch_size, labels=labels)\n        return self.decode(code, batch_size=batch_size)\n\n    def _prepare_tensors(self) -> None:\n        \"\"\"Setup TensorFlow properties for the supervised adversarial\n        autoencoder.\n\n        Prepare the tensorflow network (computational graph) realizing\n        the supervised adversarial autoencoder.\n\n        The constructed graph looks as follows:\n\n                 [inputs]           [labels]\n                    |                  |\n               inputs_flat             |\n                    |                  |\n          (encoder) |                  |\n                    V                  |\n             *encoded_style*           |      [prior_style]  [prior_label]\n                    |                  |             |            |\n                    +------------------+             +------+-----+\n                             |                              |\n                             V                              V\n                         *encoded*                        prior\n                             |                              |\n                    +----------------+                      |\n          (decoder) |                |                      |\n                    |                V                      V\n                    V             D_fake_logits        D_real_logits\n                *decoded*          |         |              |\n                    |              V         V              V\n                    +-----+     G_loss   D_loss_fake   D_loss_true\n                          |        |           |              |\n            [outputs]     |        V           +-------+------+\n                |         |   *loss_generator*         V\n            outputs_flat  |                   *loss_discriminator*\n                V         V\n             *loss_reconstruction*\n\n        [...]: input values (tf.placeholder)\n                 inputs\n                 outputs\n                 code\n                 prior_style\n                 prior_label\n        *...*: output values (tf.tensor)\n                 encoded: encoder output (just style, no label)\n                 decoded: decoder output (flat data)\n\n        Tensorflow properties are prefixed with '_tf_'.\n        \"\"\"\n        # Super class sets up a standard autoencoder from placeholders\n        # 'inputs', 'outputs', providing 'encoded', 'decoded' and\n        # 'loss_reconstruction'.\n        super()._prepare_tensors()\n\n        #\n        # The discriminators\n        #\n        prior = \\\n            tf.concat([self._tf_prior_style, self._tf_prior_label], axis=1)\n        discriminator_real_logits = \\\n            self._tf_discriminator(prior, self._tf_keep_prob)\n        discriminator_fake_logits = \\\n            self._tf_discriminator(self._tf_encoded, self._tf_keep_prob)\n\n        discriminator_fake_labels = tf.zeros_like(discriminator_fake_logits)\n        discriminator_loss_fake = tf.nn.\\\n            sigmoid_cross_entropy_with_logits(logits=discriminator_fake_logits,\n                                              labels=discriminator_fake_labels)\n        discriminator_real_labels = tf.ones_like(discriminator_real_logits)\n        discriminator_loss_true = tf.nn.\\\n            sigmoid_cross_entropy_with_logits(logits=discriminator_real_logits,\n                                              labels=discriminator_real_labels)\n\n        generator_fake_labels = tf.ones_like(discriminator_fake_logits)\n        generator_loss = tf.nn.\\\n            sigmoid_cross_entropy_with_logits(logits=discriminator_fake_logits,\n                                              labels=generator_fake_labels)\n\n        self._tf_loss_discriminator = \\\n            tf.reduce_mean(discriminator_loss_fake) + \\\n            tf.reduce_mean(discriminator_loss_true)\n        self._tf_loss_generator = tf.reduce_mean(generator_loss)\n\n    def _tf_encoder(self, data, keep_prob):\n        \"\"\"Encoder for an autoencoder.\n        \"\"\"\n        self._tf_encoded_style = super()._tf_encoder(data, keep_prob)\n        return tf.concat([self._tf_encoded_style, self._tf_labels], axis=1)\n\n    def train(self,\n              labeled_train_data: Datasource,\n              labeled_display_data: Datasource,\n              sess: tf.Session, saver) -> None:\n        \"\"\"Train the network.\n        \"\"\"\n        # display_data: (images, images_noised, labels)\n        # A batch of data used for plotting intermediate results\n        # during training (taken from the validation dataset)\n        # Each is a numpy array of length 100 and appropriate shape.\n        display_data = labeled_display_data[:100, ('array', 'array', 'label')]\n\n        #\n        # prepare the optimizers\n        #\n\n        # obtain the variables used in the model\n        total_vars = tf.trainable_variables()\n        # var_ae = [var for var in total_vars\n        #           if \"encoder\" in var.name or \"decoder\" in var.name]\n\n        # Optimizers\n        self._tf_define_optimizers(total_vars)\n\n        #\n        # Start the training\n        #\n        start_epoch = self._tf_initialize_variables(sess, saver)\n        start_time = time.time()\n\n        total_batch = len(labeled_train_data) // self._conf.batch_size\n        labeled_batch_iterator = \\\n            labeled_train_data(batch_size=self._conf.batch_size, loop=True,\n                               attributes=('array', 'noisy', 'label'))\n\n        for epoch in tqdm(range(start_epoch, self._conf.n_epoch),\n                          initial=start_epoch, total=self._conf.n_epoch):\n            likelihood = 0\n            discriminator_value = 0\n            generator_value = 0\n\n            # Adapt the learning rate depending on the epoch\n            lr_value = self._learning_rate_schedule(epoch)\n\n            for _batch_idx in tqdm(range(total_batch)):\n                batch_xs, batch_noised_xs, batch_ys = \\\n                    next(labeled_batch_iterator)\n\n                # Sample from the prior distribution\n                prior_style, prior_label_onehot = \\\n                    self._sample_prior(self._conf.prior, zdim=self.code_dim,\n                                       nclasses=self.nclasses,\n                                       batch_size=self._conf.batch_size,\n                                       use_label_info=True)\n\n                feed_dict = {\n                    self._tf_inputs: batch_noised_xs,\n                    self._tf_outputs: batch_xs,\n                    self._tf_labels: batch_ys,\n                    self._tf_prior_style: prior_style,\n                    self._tf_prior_label: prior_label_onehot,\n                    self._tf_learning_rate: lr_value,\n                    self._tf_keep_prob: self._conf.keep_prob\n                }\n\n                # AutoEncoder phase\n                self._tf_train_step(sess, feed_dict)\n\n                # Summary\n                likelihood += \\\n                    self._loss_reconstruction_value/total_batch\n                discriminator_value += \\\n                    self._loss_discriminator_value/total_batch\n                generator_value += \\\n                    self._loss_generator_value/total_batch\n\n            # every 5th epoch (except the last) plot the manifold canvas\n            if epoch % 5 == 0 or epoch == (self._conf.n_epoch - 1):\n                name = f\"Manifold_canvas_{epoch}\"\n                self.plot_recoded_images(display_data[1],\n                                         targets=display_data[0],\n                                         labels=display_data[2],\n                                         filename=name)\n\n            # output end of epoch information\n            runtime = time.time() - start_time\n            print(f\"Epoch: {epoch:3d}, \"\n                  f\"global step: {sess.run(self._tf_global_step)}, \"\n                  f\"Time: {datetime.timedelta(seconds=runtime)}\")\n            print(f\"             lr_AE: {lr_value:.5f}\"\n                  f\"   loss_AE: {likelihood:.4f}   \")\n            print(f\"             lr_D: {lr_value/5:.5f}\"\n                  f\"   loss_D: {discriminator_value:.4f}\")\n            print(f\"             lr_G: {lr_value:.5f}\"\n                  f\"   loss_G: {generator_value:.4f}\\n\")\n\n            if saver is not None:\n                saver.save(sess, 'checkpoints/my_test_model',\n                           global_step=self._tf_global_step,\n                           write_meta_graph=False)\n                print(f\"Saver: {saver.last_checkpoints}\")\n\n\nclass SemisupervisedAdversarialAutoencoder(LabeledAdversarialAutoencoder):\n    \"\"\"Specialized sublasse for a semi-supervised\n    Adversarial Autoencoder (AAE) implementation.\n\n    The main differences to the fully supervised AAE are\n    the following:\n    * the encoder (generator) also outputs class labels. That is the latent\n      representation is split into two parts: the continuous z and the one-hot\n      encoded label information y.\n    * there now are two discriminators, one for each part of the latent\n      representation, and two loss functions training them:\n      `_loss_discriminator_style` and `_loss_discriminator_label`.\n      Training the z part requires z value output from the encoder/generator\n      ()\n      as well as real z values sampled from the target distribution.\n      Training the y part requires the label output from the encoder/generator\n\n    * the produced class labels can be used as additional training objective\n      to train the encoder (generator) to minimize crossentropy loss, if\n      ground truth label are available (supervised case).  This loss function\n      is stored under the name `_crossentropy_labels`.  The training process\n      requires input data with real class labels.\n    \"\"\"\n\n    def __init__(self, **kwargs) -> None:\n        super().__init__(**kwargs)\n        self._conf.model = 'semi_supervised'\n\n        #\n        # data related properties\n        #\n\n        # model related properties\n        self._style = None\n        self._crossentropy_labels = None\n\n        # loss functions\n        self._tf_loss_discriminator_label = None\n        self._tf_loss_discriminator_style = None\n\n        # optimizers\n        self._op_z_discriminator = None\n        self._op_y_discriminator = None\n        self._op_generator = None\n        self._op_crossentropy_labels = None\n\n        self._l_z_discriminator = None\n        self._l_y_discriminator = None\n        self._l_generator = None\n        self._crossentropy = None\n\n    def _prepare_tensors(self) -> None:\n        \"\"\"Setup TensorFlow properties for the supervised adversarial\n        autoencoder.\n\n        \"\"\"\n        super()._prepare_tensors()\n\n        # placeholders\n        # FIXME[semi]: self._z_cat\n        # Y_cat = tf.placeholder(dtype=tf.float32,\n        #                        shape=[None, n_cls], name=\"labels_cat\")\n        # labels_cat = self._tf_prior_label\n\n        # FIXME[coding]: code duplication\n        flat_data_length = \\\n            self._data_shape[0] * self._data_shape[1] * self._data_shape[2]\n        inputs_flat = tf.reshape(self._tf_inputs, [-1, flat_data_length])\n        outputs_flat = tf.reshape(self._tf_outputs, [-1, flat_data_length])\n\n        # the encoder\n        self._style, labels_softmax = \\\n            self._tf_semi_encoder(inputs_flat, self._tf_keep_prob,\n                                  semi_supervised=False)\n        _, labels_generated = \\\n            self._tf_semi_encoder(inputs_flat, self._tf_keep_prob,\n                                  semi_supervised=True)\n        latent_inputs = tf.concat([self._style, labels_softmax], axis=1)\n\n        # the decoder\n        self._tf_decoded = \\\n            self._tf_semi_decoder(latent_inputs, self._tf_keep_prob)\n\n        #\n        # the discriminators\n        #\n\n        discriminator_label_fake = \\\n            self._tf_semi_y_discriminator(labels_softmax,\n                                          self._tf_keep_prob)\n        discriminator_label_real = \\\n            self._tf_semi_y_discriminator(self._tf_prior_label,\n                                          self._tf_keep_prob)\n\n        discriminator_style_fake = \\\n            self._tf_semi_z_discriminator(self._style,\n                                          self._tf_keep_prob)\n        discriminator_style_real = \\\n            self._tf_semi_z_discriminator(self._tf_prior_style,\n                                          self._tf_keep_prob)\n\n        #\n        # loss functions\n        #\n        self._tf_loss_reconstruction = \\\n            tf.reduce_mean(tf.squared_difference(self._tf_decoded,\n                                                 outputs_flat))\n\n        discriminator_label_zeros = tf.zeros_like(discriminator_label_fake)\n        discriminator_label_ones = tf.ones_like(discriminator_label_real)\n        discriminator_loss_label_real = tf.nn.\\\n            sigmoid_cross_entropy_with_logits(logits=discriminator_label_real,\n                                              labels=discriminator_label_ones)\n        discriminator_loss_label_fake = tf.nn.\\\n            sigmoid_cross_entropy_with_logits(logits=discriminator_label_fake,\n                                              labels=discriminator_label_zeros)\n        self._tf_loss_discriminator_label = \\\n            tf.reduce_mean(discriminator_loss_label_real) + \\\n            tf.reduce_mean(discriminator_loss_label_fake)\n\n        discriminator_style_zeros = tf.zeros_like(discriminator_style_fake)\n        discriminator_style_ones = tf.ones_like(discriminator_style_real)\n        discriminator_loss_style_real = tf.nn.\\\n            sigmoid_cross_entropy_with_logits(logits=discriminator_style_real,\n                                              labels=discriminator_style_ones)\n        discriminator_loss_style_fake = tf.nn.\\\n            sigmoid_cross_entropy_with_logits(logits=discriminator_style_fake,\n                                              labels=discriminator_style_zeros)\n        self._tf_loss_discriminator_style = \\\n            tf.reduce_mean(discriminator_loss_style_real) + \\\n            tf.reduce_mean(discriminator_loss_style_fake)\n\n        loss_generator_label = tf.nn.\\\n            sigmoid_cross_entropy_with_logits(logits=discriminator_label_fake,\n                                              labels=discriminator_label_ones)\n        loss_generator_style = tf.nn.\\\n            sigmoid_cross_entropy_with_logits(logits=discriminator_style_fake,\n                                              labels=discriminator_style_ones)\n        self._tf_loss_generator = \\\n            tf.reduce_mean(loss_generator_style) + \\\n            tf.reduce_mean(loss_generator_label)\n\n        crossentropy_labels = tf.nn.\\\n            softmax_cross_entropy_with_logits(logits=labels_generated,\n                                              labels=self._tf_labels)\n        self._crossentropy_labels = tf.reduce_mean(crossentropy_labels)\n\n    def _tf_semi_encoder(self, data, keep_prob, semi_supervised=False):\n        \"\"\"Encoder for semi-supervised AAE.\n\n        Arguments\n        ---------\n        \"\"\"\n        with tf.variable_scope(\"semi_encoder\", reuse=tf.AUTO_REUSE):\n            net = tf_helper.dense_layer(data, self._conf.semi_n_hidden,\n                                        name=\"dense_1\", keep_prob=keep_prob)\n            net = tf_helper.dense_layer(net, self._conf.semi_n_hidden,\n                                        name=\"dense_2\", keep_prob=keep_prob)\n            style = tf_helper.dense(net, self.code_dim, name=\"style\")\n\n            if semi_supervised is False:\n                labels_generated = \\\n                    tf.nn.softmax(tf_helper.dense(net, self.nclasses,\n                                                  name=\"labels\"))\n            else:\n                labels_generated = \\\n                    tf_helper.dense(net, self.nclasses,\n                                    name=\"label_logits\")\n\n        return style, labels_generated\n\n    def _tf_semi_decoder(self, code, keep_prob):\n        \"\"\"Decoder for semi-supervised AAE.\n\n        Result\n        ------\n        decoder:\n            A flat tensor holding the decoded data.\n        \"\"\"\n        flat_data_length = \\\n            self._data_shape[0] * self._data_shape[1] * self._data_shape[2]\n        with tf.variable_scope(\"semi_decoder\", reuse=tf.AUTO_REUSE):\n            net = tf_helper.dense_layer(code, self._conf.semi_n_hidden,\n                                        name=\"dense_1\", keep_prob=keep_prob)\n            net = tf_helper.dense_layer(net, self._conf.semi_n_hidden,\n                                        name=\"dense_2\", keep_prob=keep_prob)\n            net = tf.nn.sigmoid(tf_helper.dense(net, flat_data_length,\n                                                name=\"dense_3\"))\n        return net\n\n    def _tf_semi_z_discriminator(self, style, keep_prob):\n        \"\"\"Discriminator for style codes.\n        \"\"\"\n        with tf.variable_scope(\"semi_z_discriminator\", reuse=tf.AUTO_REUSE):\n            net = tf_helper.dense_layer(style, self._conf.semi_n_hidden,\n                                        name=\"dense_1\", keep_prob=keep_prob)\n            net = tf_helper.dense_layer(net, self._conf.semi_n_hidden,\n                                        name=\"dense_2\", keep_prob=keep_prob)\n            logits = tf_helper.dense(net, 1, name=\"dense_3\")\n        return logits\n\n    def _tf_semi_y_discriminator(self, label, keep_prob):\n        \"\"\"Discriminator for class labels.\n        \"\"\"\n        with tf.variable_scope(\"semi_y_discriminator\", reuse=tf.AUTO_REUSE):\n            net = tf_helper.dense_layer(label, self._conf.semi_n_hidden,\n                                        name=\"dense_1\", keep_prob=keep_prob)\n            net = tf_helper.dense_layer(net, self._conf.semi_n_hidden,\n                                        name=\"dense_2\", keep_prob=keep_prob)\n            logits = tf_helper.dense(net, 1, name=\"dense_3\")\n        return logits\n\n    def _tf_define_optimizers(self, variables) -> None:\n        \"\"\"Prepare the training process. Define optimizers.\n        \"\"\"\n        super()._tf_define_optimizers(variables)\n\n        # FIXME[semi]: z and y discriminator\n        var_z_discriminator = [var for var in variables\n                               if \"z_discriminator\" in var.name]\n        var_y_discriminator = [var for var in variables\n                               if \"y_discriminator\" in var.name]\n        var_generator = [var for var in variables\n                         if \"encoder\" in var.name]\n\n        self._op_z_discriminator = \\\n            tf.train.AdamOptimizer(learning_rate=self._tf_learning_rate/5).\\\n            minimize(self._tf_loss_discriminator,\n                     global_step=self._tf_global_step,\n                     var_list=var_z_discriminator)\n        self._op_y_discriminator = \\\n            tf.train.AdamOptimizer(learning_rate=self._tf_learning_rate/5).\\\n            minimize(self._tf_loss_discriminator,\n                     global_step=self._tf_global_step,\n                     var_list=var_y_discriminator)\n        self._op_generator = \\\n            tf.train.AdamOptimizer(learning_rate=self._tf_learning_rate).\\\n            minimize(self._tf_loss_generator,\n                     global_step=self._tf_global_step,\n                     var_list=var_generator)\n\n        # optimizer for supervised data: minimize cross-entropy between\n        # real and fake labels.\n        self._op_crossentropy_labels = \\\n            tf.train.AdamOptimizer(learning_rate=self._tf_learning_rate).\\\n            minimize(self._crossentropy_labels,\n                     global_step=self._tf_global_step,\n                     var_list=var_generator)\n\n    def _tf_train_step(self, sess, feed_dict) -> None:\n        \"\"\"Perform one training step.\n        \"\"\"\n        # AutoEncoder phase\n        super()._tf_train_step(sess, feed_dict)\n\n        # Discriminator phase\n        # FIXME[semi]: optimize both discriminators\n        self._l_z_discriminator, _ = \\\n            sess.run([self._tf_loss_discriminator_style,\n                      self._op_z_discriminator],\n                     feed_dict=feed_dict)\n        self._l_y_discriminator, _ = \\\n            sess.run([self._tf_loss_discriminator_label,\n                      self._op_y_discriminator],\n                     feed_dict=feed_dict)\n\n        # Generator phase\n        self._l_generator, _ = \\\n            sess.run([self._tf_loss_generator, self._op_generator],\n                     feed_dict=feed_dict)\n\n    def _tf_train_supervised_step(self, sess, feed_dict) -> None:\n        # Cross_Entropy phase\n        self._crossentropy, _ = \\\n            sess.run([self._crossentropy_labels,\n                      self._op_crossentropy_labels],\n                     feed_dict=feed_dict)\n\n    def train(self,\n              unlabeled_train_data: Datasource,\n              labeled_train_data: Datasource,\n              labeled_display_data: Datasource,\n              sess: tf.Session, saver) -> None:\n        \"\"\"Train the network.\n        \"\"\"\n        # display_data: (images, images_noised, labels)\n        # A batch of data used for plotting intermediate results\n        # during training (taken from the validation dataset)\n        # Each is a numpy array of length 100 and appropriate shape.\n        display_data = labeled_display_data[:100, ('array', 'array', 'label')]\n\n        # obtain the variables used in the model\n        total_vars = tf.trainable_variables()\n\n        # Optimizers\n        self._tf_define_optimizers(total_vars)\n\n        #\n        # Start the training\n        #\n        start_epoch = self._tf_initialize_variables(sess, saver)\n        start_time = time.time()\n\n        total_batch = len(labeled_train_data) // self._conf.batch_size\n        labeled_batch_iterator = \\\n            labeled_train_data(batch_size=self._conf.batch_size,\n                               attributes=('array', 'array', 'label'))\n        unlabeled_batch_iterator = \\\n            unlabeled_train_data(batch_size=self._conf.batch_size,\n                                 attributes=('array', 'noisy'))\n\n        for epoch in tqdm(range(start_epoch, self._conf.n_epoch),\n                          initial=start_epoch, total=self._conf.n_epoch):\n            likelihood = 0\n            discriminator_z_value = 0\n            discriminator_y_value = 0\n            generator_value = 0\n            crossentropy_value = 0\n\n            # Adapt the learning rate depending on the epoch\n            lr_value = self._learning_rate_schedule(epoch)\n\n            for _batch_idx in tqdm(range(total_batch)):\n\n                #\n                # Part 1: unsupervised learning\n                #\n                batch_xs, batch_noised_xs = next(unlabeled_batch_iterator)\n\n                # FIXME[semi]:\n                real_cat_labels = \\\n                    np.random.randint(low=0, high=self.nclasses,\n                                      size=self._conf.batch_size)\n                real_cat_labels = np.eye(self.nclasses)[real_cat_labels]\n\n                # Sample from the prior distribution\n                prior_style, _tf_prior_label_onehot = \\\n                    self._sample_prior(self._conf.prior, zdim=self.code_dim,\n                                       nclasses=self.nclasses,\n                                       batch_size=self._conf.batch_size,\n                                       use_label_info=False)\n\n                feed_dict = {\n                    self._tf_inputs: batch_noised_xs,\n                    self._tf_outputs: batch_xs,\n                    # self._tf_labels: batch_ys,\n                    self._tf_prior_style: prior_style,\n                    # FIXME[semi]: real_cat_labels instead of\n                    # prior_label_onehot\n                    self._tf_prior_label: real_cat_labels,\n                    self._tf_learning_rate: lr_value,\n                    self._tf_keep_prob: self._conf.keep_prob\n                }\n\n                # perform the actual training\n                self._tf_train_step(sess, feed_dict)\n\n                #\n                # Part 2: supervised training with labels\n                #\n\n                # Obtain a batch of labeled validation data to train\n                # the encoder to predict correct class labels\n                # (minimizing crossentropy)\n                batch_semi_xs, batch_noised_semi_xs, batch_semi_ys = \\\n                    next(labeled_batch_iterator)\n\n                feed_dict_semi = {\n                    self._tf_inputs: batch_noised_semi_xs,\n                    self._tf_outputs: batch_semi_xs,\n                    self._tf_labels: batch_semi_ys,\n                    # FIXME[semi]: _tf_prior_label was Y_cat\n                    self._tf_prior_label: real_cat_labels,\n                    self._tf_learning_rate: lr_value,\n                    self._tf_keep_prob: self._conf.keep_prob\n                }\n\n                self._tf_train_supervised_step(self, sess, feed_dict_semi)\n\n                # Summary\n                likelihood += \\\n                    self._loss_reconstruction_value/total_batch\n                discriminator_z_value += self._l_z_discriminator/total_batch\n                discriminator_y_value += self._l_y_discriminator/total_batch\n                generator_value += self._l_generator/total_batch\n                crossentropy_value += self._crossentropy/total_batch\n\n            # every 5th epoch (except the last) plot the manifold canvas\n            if epoch % 5 == 0 or epoch == (self._conf.n_epoch - 1):\n                name = f\"Manifold_semi_canvas_{epoch}\"\n                self.plot_recoded_images(display_data[1],\n                                         targets=display_data[0],\n                                         filename=name)\n\n            # output end of epoch information\n            runtime = time.time() - start_time\n            print(f\"Epoch: {epoch:3d}, \"\n                  f\"global step: {sess.run(self._tf_global_step)}, \"\n                  f\"Time: {datetime.timedelta(seconds=runtime)}\")\n            print(f\"             lr_AE: {lr_value:.5f}\"\n                  f\"   loss_AE: {likelihood:.4f}\")\n            print(f\"             lr_D: {lr_value/5:.5f}\"\n                  f\"   loss_z_D: {discriminator_z_value:.4f},\"\n                  f\"   loss_y_D: {discriminator_y_value:.4f}\")\n            print(f\"             lr_G: {lr_value:.5f}\"\n                  f\"   loss_G: {generator_value:.4f},\"\n                  f\"   loss_CE: {crossentropy_value:.4f}\\n\")\n\n\ndef main() -> None:\n    \"\"\"The main program.\n    \"\"\"\n    ModelClass = SupervisedAdversarialAutoencoder\n    # ModelClass = SemiSupervisedAdversarialAutoencoder\n\n    datasource_train = Datasource(module='mnist', one_hot=True)\n    datasource_train.add_postprocessor(add_noise)\n    datasource_test = Datasource(module='mnist', section='test', one_hot=True)\n\n    aae = ModelClass(shape=datasource_train.shape, code_dim=2,\n                     nclasses=len(datasource_train.label_scheme))\n    aae.prepare()\n\n    saver = tf.train.Saver(name='aae', filename=\"my_test_model\")\n    # print(f\"\\n\\n##### Saver: {saver.last_checkpoints}\\n\\n\")\n    # print(\"tf.train.latest_checkpoint(): \"\n    #       f\"{tf.train.latest_checkpoint('checkpoints')}\")\n    # print(f\"\\n\\n##### Saver: {saver.last_checkpoints}\\n\\n\")\n\n    with tf.Session() as sess:\n        aae.set_tensorflow_session(sess)\n        aae.train(datasource_train, datasource_test, sess, saver)\n\n        if aae.code_dim == 2:\n            print(\"-\" * 80)\n            print(\"plot 2D Scatter Result\")\n            aae.plot_data_codes_2d(datasource_test._array,\n                                   labels=datasource_test._labels,\n                                   filename='2D_latent_space.png')\n\n        if aae.code_dim and aae.conf.flag_plot_mlr:\n            print(\"-\" * 80)\n            print(\"plot Manifold Learning Result\")\n            # filename = \"PMLR/PMLR\"\n            aae.plot_decoded_codespace_2d(labels=5)\n\n        if aae.conf.flag_plot_arr:\n            print(\"-\"*80)\n            print(\"plot analogical reasoning result\")\n            aae.plot_analogical_decoding()\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "ddf19e93e72820d0cf65e8b012ae143cd8e9a2f7", "size": 44319, "ext": "py", "lang": "Python", "max_stars_repo_path": "dltb/thirdparty/tensorflow/aae.py", "max_stars_repo_name": "Petr-By/qtpyvis", "max_stars_repo_head_hexsha": "0b9a151ee6b9a56b486c2bece9c1f03414629efc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-10-04T14:51:26.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-22T09:35:50.000Z", "max_issues_repo_path": "dltb/thirdparty/tensorflow/aae.py", "max_issues_repo_name": "Petr-By/qtpyvis", "max_issues_repo_head_hexsha": "0b9a151ee6b9a56b486c2bece9c1f03414629efc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2017-09-05T12:56:11.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-22T10:38:27.000Z", "max_forks_repo_path": "dltb/thirdparty/tensorflow/aae.py", "max_forks_repo_name": "krumnack/qtpyvis", "max_forks_repo_head_hexsha": "0b9a151ee6b9a56b486c2bece9c1f03414629efc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-09-24T21:39:42.000Z", "max_forks_repo_forks_event_max_datetime": "2017-10-04T15:29:54.000Z", "avg_line_length": 39.7123655914, "max_line_length": 79, "alphanum_fraction": 0.5832261558, "include": true, "reason": "import numpy", "num_tokens": 9096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.19378350417746945}}
{"text": "\"\"\"\n针对brats数据集\n做包含预处理的数据管道(Python生成器)\n\n每次优先读取npy 不存在则读取nii 同时保存npy\n\n读取240*240 指定155中部切片\n或者读取240*240*155 3D\n\n以2D为例，进行中心附近剪裁，单个240*240切片 中心有效区域为196*144\n在这个区域内选取若然随机的128*128切片 进行训练 确保训练的数据是有监督的 对其的\n切片范围为中心的196-128 和144-128  即 68*16范围内去随机值\n\n\"\"\"\n\nimport os \nimport sys\nfrom PIL import Image\nimport numpy as np \nimport nibabel as nib\nfrom scipy import ndimage\nimport random\nbase = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(os.path.join(base, '../'))\nfrom utils import CutPadding\nimport random\nclass UnpairedError(Exception):\n    def __init__(self,path):\n        self.err_msg = \"There are not exixting paired samples! We can only find:\"\n        self.filename = path\nclass DataPipeLine():\n    def __init__(self,path,target_size,patch_size,remake_flag=False,random_flag=False,crop=\"crop_random\"):\n        self.path = path\n        self.datalist = self.__readDirFile(self.path,random_flag)\n        self.target_size = target_size\n        self.patch_size = patch_size\n        self.dims = len(target_size)\n        self.remake_flag = remake_flag\n        self.random_flag = random_flag\n        self.crop = crop.lower()\n    def __readDirFile(self,path,random_flag=False):\n        buf_A = []\n        buf_B = []\n        buf_A_mask_v0 = []\n        buf_B_mask_v0 = []\n        for (dirName, subdirList, fileList) in os.walk(path):\n            try:\n                for filename in fileList:\n                    if \"t1.nii\" in filename.lower():  \n                        buf_A.append(os.path.join(dirName,filename))\n                    if \"t2.nii\" in filename.lower(): \n                        buf_B.append(os.path.join(dirName,filename))\n                    if \"mask_t1_v0.nii\" in filename.lower():  \n                        buf_A_mask_v0.append(os.path.join(dirName,filename))\n                    if \"mask_t2_v0.nii\" in filename.lower(): \n                        buf_B_mask_v0.append(os.path.join(dirName,filename))\n                if len(buf_A) > len(buf_B):\n                    raise UnpairedError(buf_A.pop(-1))\n                elif len(buf_A) < len(buf_B):\n                    raise UnpairedError(buf_B.pop(-1))\n                else:\n                    pass\n            except UnpairedError as error:\n                print(error.err_msg)\n                print(error.filename)\n            else:# normal condition\n                pass\n            finally:# any way\n                pass\n        if random_flag:\n            \"\"\"\n            打乱A B之间的对应关系\n            \"\"\"\n            random_num1 = random.randint(0,200)\n            random_num2 = random.randint(0,200)\n            random.seed(random_num1)\n            random.shuffle(buf_A)\n            random.seed(random_num1)\n            random.shuffle(buf_A_mask_v0)\n            random.seed(random_num2)\n            random.shuffle(buf_B)\n            random.seed(random_num2)\n            random.shuffle(buf_B_mask_v0)\n            return list(zip(buf_A,buf_B,buf_A_mask_v0,buf_B_mask_v0))\n        else:\n            return list(zip(buf_A,buf_B,buf_A_mask_v0,buf_B_mask_v0))\n    def re_rand(self):\n        self.datalist = self.__readDirFile(self.path,random_flag=True)\n    def read_file(self,path):\n        if self.dims == 3:\n            temp_path = path[:-3]+\"npy\"\n            if (os.path.exists(temp_path)==True)and(self.remake_flag==False):\n                return np.load(temp_path)\n            else:\n                return self.load_nii_file(path)\n        elif self.dims == 2:\n            temp_path = path[:-3]+\"2D.npy\"\n            if (os.path.exists(temp_path)==True)and(self.remake_flag==False):\n                return np.load(temp_path)\n            else:\n                return self.load_nii_file(path)\n        else:\n            raise ValueError\n    def __read_nii_file(self,path):\n        img = nib.load(path)\n        img = np.array(img.dataobj[:,:,:])\n        return img\n    def __cut_nii_file(self,img):\n        return CutPadding.cut_img_3D(img)\n    def __save_nii2npy(self,img,path):\n        if self.dims == 3:\n            temp_path = path[:-3]+\"npy\"\n        elif self.dims ==2:\n            temp_path = path[:-3]+\"2D.npy\"\n        else:\n            raise ValueError\n        np.save(temp_path,img)\n        return img\n    def __cut_np_array(self,array,target_shape=[128,128,128]):\n        old_shape = array.shape\n        buf = [0,0,0]\n        for i in range(3):\n            buf[i]=old_shape[i]//2-target_shape[i]//2\n            #左半部右下标+1 减去目标点数的一半 获得新的起始点 10//2 -6//2 = 2 从下标2开始然后到下标2+6-1结束\n        return array[buf[0]:buf[0]+target_shape[0],buf[1]:buf[1]+target_shape[1],buf[2]:buf[2]+target_shape[2]]            \n    def __normalize(self,slice,dtype=np.float32):\n        tmp = slice/slice.max()\n        return tmp.astype(dtype)\n    def get_centro_ranges(self,target_size,patch_size):\n        ranges_buf = []\n        shape = target_size\n        for i in range(len(patch_size)):\n            if shape[i]<patch_size[i]:\n                raise ValueError(\"Unsupported target size\")\n            elif shape[i]==patch_size[i]:\n                pass\n            else:\n                diff = shape[i]-patch_size[i]\n                begin = diff//2\n                end = diff-begin\n                ranges_buf.append([begin,shape[i]-end])\n        return ranges_buf\n    def load_nii_file(self,path):\n        img = self.__read_nii_file(path)#读取3D源文件 \n        # img = self.__cut_nii_file(img)#去除文件周围无意义的区域 3D去黑边\n        #缩放到目标大小 最近邻插值\n        if len(self.target_size)==2:\n            # temp_targer_size = self.target_size[:]+[self.target_size[-1]]\n            temp_targer_size = self.target_size[:]+[155]\n        else:\n            temp_targer_size = self.target_size[:]\n        # ratio = [temp_targer_size[x]/img.shape[x] for x in range(3)]\n        # resize_image = ndimage.interpolation.zoom(img,ratio, mode='nearest')\n        # assert resize_image.shape==tuple(temp_targer_size)\n        # resize_image[resize_image<0]=0#去除插值后出现的负像素\n        resize_image = CutPadding.center_crop_3D(img=img,target_size=temp_targer_size)\n        if self.dims == 3:\n            resize_image = resize_image\n        elif self.dims ==2:\n            resize_image = resize_image[:,:,temp_targer_size[-1]//2]\n        else:\n            raise ValueError\n        img_norm = self.__normalize(resize_image,dtype=np.float32)#归一化\n        img_saved = self.__save_nii2npy(img_norm,path)#保存 并且返回保存的文件 将对2D 3D区别对待\n        return img_saved\n    def __iter__(self):\n        #实现__iter__ 本身就是一个迭代器 但是没有call方法 不能被tensorflow from_generator识别 所以必须在实现一个一般的生成器函数\n        length = len(self.datalist)\n        for i,(A,B,A_m0,B_m0) in enumerate(self.datalist):\n            imgA = self.read_file(A)\n            imgB = self.read_file(B)\n            imgA_m0 = self.read_file(A_m0)\n            imgB_m0 = self.read_file(B_m0)\n            if self.dims == 3:\n                buf = None\n                yield (imgA,imgB,imgA_m0,imgB_m0,buf)\n            elif self.dims == 2:\n                buf = None\n                yield (imgA,imgB,imgA_m0,imgB_m0,buf)\n            else:\n                raise ValueError(\"Unsupported dims\")\n            if (i+1)==length:\n                if self.random_flag:\n                    self.re_rand()\n                    print(\"lueluelue\")        \n        return None\n    def generator(self):\n        length = len(self.datalist)\n        for i,(A,B,A_m0,B_m0) in enumerate(self.datalist):\n            imgA = self.read_file(A)\n            imgB = self.read_file(B)\n            imgA_m0 = self.read_file(A_m0)\n            imgB_m0 = self.read_file(B_m0)\n            if self.dims == 3:\n                ranges_buf = self.get_centro_ranges(target_size=self.target_size,patch_size=self.patch_size)\n                slice_begin = ranges_buf[-1][0]\n                slice_end = ranges_buf[-1][1]\n                for slice_index in range(slice_begin,slice_end):\n                    slice_imgA=imgA[:,:,slice_index]\n                    slice_imgB=imgB[:,:,slice_index]\n                    slice_imgA_m0=imgA_m0[:,:,slice_index]\n                    slice_imgB_m0=imgB_m0[:,:,slice_index]\n                    buf = np.array(ranges_buf[0:2],dtype=np.int32)\n                    yield (slice_imgA,slice_imgB,slice_imgA_m0,slice_imgB_m0,buf)\n            elif self.dims == 2:\n                raise ValueError(\"Unsupported 2 dims\")\n            else:\n                raise ValueError(\"Unsupported dims\")\n            if (i+1)==28:\n                if self.random_flag:\n                    self.re_rand()\n                    print(\"lueluelue\")\n                break\n            \n        return None\n    def chenk_saved_npy(self):\n        #该方法直接进行一次全部迭代，将nii文件读取并且内容保存为预处理后的numpy矩阵 npy无压缩格式\n        for i,(A,B,A_m0,B_m0,buf) in enumerate(self):\n            print(i+1,A.shape,B.dtype,\n                    B_m0.shape,A_m0.dtype,\n                    A.max(),B.min(),\n                    A.max(),B.min())   \n    def save_png(self):\n        from PIL import Image\n        for i,(A,B) in enumerate(self.datalist):\n            imgA = np.array(255*self.read_file(A),dtype=np.uint8)\n            imgB = np.array(255*self.read_file(B),dtype=np.uint8)\n            imgA = Image.fromarray(imgA)\n            imgB = Image.fromarray(imgB)\n            imgA.save(A[:-4]+\".png\")\n            imgB.save(B[:-4]+\".png\")\n            print(i)\n        return \nif __name__ == \"__main__\":\n    import tensorflow as tf \n    a = DataPipeLine(path=\"G:\\\\Datasets\\\\BraTS\\\\ToCrop\\\\\",\n                     target_size=[240,240,155],\n                     patch_size=[128,128,101],\n                     remake_flag=False,\n                     random_flag=True)\n    # a.chenk_saved_npy()\n\n    import matplotlib.pyplot as plt\n    for i,(A,B,A_m0,B_m0,buf) in enumerate(a.generator()):\n        if i == 10:\n            plt.figure(figsize=(5,5))#图片大一点才可以承载像素\n            plt.subplot(2,2,1)\n            plt.imshow(A,cmap='gray')\n            plt.axis('off')\n            plt.subplot(2,2,2)\n            plt.imshow(A_m0,cmap='gray')\n            plt.axis('off')\n            plt.subplot(2,2,3)\n            plt.imshow(B,cmap='gray')\n            plt.axis('off')\n            plt.subplot(2,2,4)\n            plt.imshow(B_m0,cmap='gray')\n            plt.axis('off')\n            print(buf)\n            plt.show()\n    for i,(A,B,A_m0,B_m0,buf) in enumerate(a.generator()):\n        if i == 10:\n            plt.figure(figsize=(5,5))#图片大一点才可以承载像素\n            plt.subplot(2,2,1)\n            plt.imshow(A,cmap='gray')\n            plt.axis('off')\n            plt.subplot(2,2,2)\n            plt.imshow(A_m0,cmap='gray')\n            plt.axis('off')\n            plt.subplot(2,2,3)\n            plt.imshow(B,cmap='gray')\n            plt.axis('off')\n            plt.subplot(2,2,4)\n            plt.imshow(B_m0,cmap='gray')\n            plt.axis('off')\n            print(buf)\n            plt.show() \n", "meta": {"hexsha": "836b423d09b83111138c786e72e4cbe714ca3559", "size": 10699, "ext": "py", "lang": "Python", "max_stars_repo_path": "datasets/BratsPipeLine28M101S.py", "max_stars_repo_name": "Zhaopudark/MRI-Trans-GAN", "max_stars_repo_head_hexsha": "1af8f486202ded20328195ee636f2056894edebb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-11-09T11:08:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-09T07:49:40.000Z", "max_issues_repo_path": "datasets/BratsPipeLine28M101S.py", "max_issues_repo_name": "Zhaopudark/MRI-Trans-GAN", "max_issues_repo_head_hexsha": "1af8f486202ded20328195ee636f2056894edebb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-29T04:11:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-02T16:00:42.000Z", "max_forks_repo_path": "datasets/BratsPipeLine28M101S.py", "max_forks_repo_name": "Zhaopudark/MRI-Trans-GAN", "max_forks_repo_head_hexsha": "1af8f486202ded20328195ee636f2056894edebb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-12T03:50:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-12T03:50:46.000Z", "avg_line_length": 38.4856115108, "max_line_length": 123, "alphanum_fraction": 0.5510795401, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.37022539954425293, "lm_q1q2_score": 0.1937835023098586}}
{"text": "# Shree KRISHNAya Namaha\n# Warps frame using pose info\n# Author: Nagabhushan S N\n# Last Modified: 27/09/2021\n\nimport datetime\nimport time\nimport traceback\nfrom pathlib import Path\nfrom typing import Tuple, Optional\n\nimport numpy\nimport skimage.io\n\n\nclass Warper:\n    def __init__(self, resolution: tuple = None):\n        self.resolution = resolution\n        return\n\n    def forward_warp(self, frame1: numpy.ndarray, mask1: Optional[numpy.ndarray], depth1: numpy.ndarray,\n                     transformation1: numpy.ndarray, transformation2: numpy.ndarray, intrinsic1: numpy.ndarray,\n                     intrinsic2: Optional[numpy.ndarray]) -> Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray,\n                                                                   numpy.ndarray]:\n        \"\"\"\n        Given a frame1 and global transformations transformation1 and transformation2, warps frame1 to next view using\n        bilinear splatting.\n        :param frame1: (h, w, 3) uint8 numpy array\n        :param mask1: (h, w) bool numpy array. Wherever mask1 is False, those pixels are ignored while warping. Optional\n        :param depth1: (h, w) float numpy array.\n        :param transformation1: (4, 4) extrinsic transformation matrix of first view: [R, t; 0, 1]\n        :param transformation2: (4, 4) extrinsic transformation matrix of second view: [R, t; 0, 1]\n        :param intrinsic1: (3, 3) camera intrinsic matrix\n        :param intrinsic2: (3, 3) camera intrinsic matrix. Optional\n        \"\"\"\n        if self.resolution is not None:\n            assert frame1.shape[:2] == self.resolution\n        h, w = frame1.shape[:2]\n        if mask1 is None:\n            mask1 = numpy.ones(shape=(h, w), dtype=bool)\n        if intrinsic2 is None:\n            intrinsic2 = numpy.copy(intrinsic1)\n        assert frame1.shape == (h, w, 3)\n        assert mask1.shape == (h, w)\n        assert depth1.shape == (h, w)\n        assert transformation1.shape == (4, 4)\n        assert transformation2.shape == (4, 4)\n        assert intrinsic1.shape == (3, 3)\n        assert intrinsic2.shape == (3, 3)\n\n        trans_points1 = self.compute_transformed_points(depth1, transformation1, transformation2, intrinsic1,\n                                                        intrinsic2)\n        trans_coordinates = trans_points1[:, :, :2, 0] / trans_points1[:, :, 2:3, 0]\n        trans_depth1 = trans_points1[:, :, 2, 0]\n\n        grid = self.create_grid(h, w)\n        flow12 = trans_coordinates - grid\n\n        warped_frame2, mask2 = self.bilinear_splatting(frame1, mask1, trans_depth1, flow12, None, is_image=True)\n        warped_depth2 = self.bilinear_splatting(trans_depth1[:, :, None], mask1, trans_depth1, flow12, None,\n                                                is_image=False)[0][:, :, 0]\n        return warped_frame2, mask2, warped_depth2, flow12\n\n    def compute_transformed_points(self, depth1: numpy.ndarray, transformation1: numpy.ndarray,\n                                   transformation2: numpy.ndarray, intrinsic1: numpy.ndarray,\n                                   intrinsic2: Optional[numpy.ndarray]):\n        \"\"\"\n        Computes transformed position for each pixel location\n        \"\"\"\n        if self.resolution is not None:\n            assert depth1.shape == self.resolution\n        h, w = depth1.shape\n        if intrinsic2 is None:\n            intrinsic2 = numpy.copy(intrinsic1)\n        transformation = numpy.matmul(transformation2, numpy.linalg.inv(transformation1))\n\n        y1d = numpy.array(range(h))\n        x1d = numpy.array(range(w))\n        x2d, y2d = numpy.meshgrid(x1d, y1d)\n        ones_2d = numpy.ones(shape=(h, w))\n        ones_4d = ones_2d[:, :, None, None]\n        pos_vectors_homo = numpy.stack([x2d, y2d, ones_2d], axis=2)[:, :, :, None]\n\n        intrinsic1_inv = numpy.linalg.inv(intrinsic1)\n        intrinsic1_inv_4d = intrinsic1_inv[None, None]\n        intrinsic2_4d = intrinsic2[None, None]\n        depth_4d = depth1[:, :, None, None]\n        trans_4d = transformation[None, None]\n\n        unnormalized_pos = numpy.matmul(intrinsic1_inv_4d, pos_vectors_homo)\n        world_points = depth_4d * unnormalized_pos\n        world_points_homo = numpy.concatenate([world_points, ones_4d], axis=2)\n        trans_world_homo = numpy.matmul(trans_4d, world_points_homo)\n        trans_world = trans_world_homo[:, :, :3]\n        trans_norm_points = numpy.matmul(intrinsic2_4d, trans_world)\n        return trans_norm_points\n\n    def bilinear_splatting(self, frame1: numpy.ndarray, mask1: Optional[numpy.ndarray], depth1: numpy.ndarray,\n                           flow12: numpy.ndarray, flow12_mask: Optional[numpy.ndarray], is_image: bool = False) -> \\\n            Tuple[numpy.ndarray, numpy.ndarray]:\n        \"\"\"\n        Using inverse bilinear interpolation based splatting\n        :param frame1: (h, w, c)\n        :param mask1: (h, w): True if known and False if unknown. Optional\n        :param depth1: (h, w)\n        :param flow12: (h, w, 2)\n        :param flow12_mask: (h, w): True if valid and False if invalid. Optional\n        :param is_image: If true, the return array will be clipped to be in the range [0, 255] and type-casted to uint8\n        :return: warped_frame2: (h, w, c)\n                 mask2: (h, w): True if known and False if unknown\n        \"\"\"\n        if self.resolution is not None:\n            assert frame1.shape[:2] == self.resolution\n        h, w, c = frame1.shape\n        if mask1 is None:\n            mask1 = numpy.ones(shape=(h, w), dtype=bool)\n        if flow12_mask is None:\n            flow12_mask = numpy.ones(shape=(h, w), dtype=bool)\n        grid = self.create_grid(h, w)\n        trans_pos = flow12 + grid\n\n        trans_pos_offset = trans_pos + 1\n        trans_pos_floor = numpy.floor(trans_pos_offset).astype('int')\n        trans_pos_ceil = numpy.ceil(trans_pos_offset).astype('int')\n        trans_pos_offset[:, :, 0] = numpy.clip(trans_pos_offset[:, :, 0], a_min=0, a_max=w + 1)\n        trans_pos_offset[:, :, 1] = numpy.clip(trans_pos_offset[:, :, 1], a_min=0, a_max=h + 1)\n        trans_pos_floor[:, :, 0] = numpy.clip(trans_pos_floor[:, :, 0], a_min=0, a_max=w + 1)\n        trans_pos_floor[:, :, 1] = numpy.clip(trans_pos_floor[:, :, 1], a_min=0, a_max=h + 1)\n        trans_pos_ceil[:, :, 0] = numpy.clip(trans_pos_ceil[:, :, 0], a_min=0, a_max=w + 1)\n        trans_pos_ceil[:, :, 1] = numpy.clip(trans_pos_ceil[:, :, 1], a_min=0, a_max=h + 1)\n\n        prox_weight_nw = (1 - (trans_pos_offset[:, :, 1] - trans_pos_floor[:, :, 1])) * \\\n                         (1 - (trans_pos_offset[:, :, 0] - trans_pos_floor[:, :, 0]))\n        prox_weight_sw = (1 - (trans_pos_ceil[:, :, 1] - trans_pos_offset[:, :, 1])) * \\\n                         (1 - (trans_pos_offset[:, :, 0] - trans_pos_floor[:, :, 0]))\n        prox_weight_ne = (1 - (trans_pos_offset[:, :, 1] - trans_pos_floor[:, :, 1])) * \\\n                         (1 - (trans_pos_ceil[:, :, 0] - trans_pos_offset[:, :, 0]))\n        prox_weight_se = (1 - (trans_pos_ceil[:, :, 1] - trans_pos_offset[:, :, 1])) * \\\n                         (1 - (trans_pos_ceil[:, :, 0] - trans_pos_offset[:, :, 0]))\n\n        sat_depth1 = numpy.clip(depth1, a_min=0, a_max=1000)\n        log_depth1 = numpy.log(1 + sat_depth1)\n        depth_weights = numpy.exp(log_depth1 / log_depth1.max() * 50)\n\n        weight_nw = prox_weight_nw * mask1 * flow12_mask / depth_weights\n        weight_sw = prox_weight_sw * mask1 * flow12_mask / depth_weights\n        weight_ne = prox_weight_ne * mask1 * flow12_mask / depth_weights\n        weight_se = prox_weight_se * mask1 * flow12_mask / depth_weights\n\n        weight_nw_3d = weight_nw[:, :, None]\n        weight_sw_3d = weight_sw[:, :, None]\n        weight_ne_3d = weight_ne[:, :, None]\n        weight_se_3d = weight_se[:, :, None]\n\n        warped_image = numpy.zeros(shape=(h + 2, w + 2, c), dtype=numpy.float64)\n        warped_weights = numpy.zeros(shape=(h + 2, w + 2), dtype=numpy.float64)\n\n        numpy.add.at(warped_image, (trans_pos_floor[:, :, 1], trans_pos_floor[:, :, 0]), frame1 * weight_nw_3d)\n        numpy.add.at(warped_image, (trans_pos_ceil[:, :, 1], trans_pos_floor[:, :, 0]), frame1 * weight_sw_3d)\n        numpy.add.at(warped_image, (trans_pos_floor[:, :, 1], trans_pos_ceil[:, :, 0]), frame1 * weight_ne_3d)\n        numpy.add.at(warped_image, (trans_pos_ceil[:, :, 1], trans_pos_ceil[:, :, 0]), frame1 * weight_se_3d)\n\n        numpy.add.at(warped_weights, (trans_pos_floor[:, :, 1], trans_pos_floor[:, :, 0]), weight_nw)\n        numpy.add.at(warped_weights, (trans_pos_ceil[:, :, 1], trans_pos_floor[:, :, 0]), weight_sw)\n        numpy.add.at(warped_weights, (trans_pos_floor[:, :, 1], trans_pos_ceil[:, :, 0]), weight_ne)\n        numpy.add.at(warped_weights, (trans_pos_ceil[:, :, 1], trans_pos_ceil[:, :, 0]), weight_se)\n\n        cropped_warped_image = warped_image[1:-1, 1:-1]\n        cropped_weights = warped_weights[1:-1, 1:-1]\n\n        mask = cropped_weights > 0\n        with numpy.errstate(invalid='ignore'):\n            warped_frame2 = numpy.where(mask[:, :, None], cropped_warped_image / cropped_weights[:, :, None], 0)\n\n        if is_image:\n            assert numpy.min(warped_frame2) >= 0\n            assert numpy.max(warped_frame2) <= 256\n            clipped_image = numpy.clip(warped_frame2, a_min=0, a_max=255)\n            warped_frame2 = numpy.round(clipped_image).astype('uint8')\n        return warped_frame2, mask\n\n    def bilinear_interpolation(self, frame2: numpy.ndarray, mask2: Optional[numpy.ndarray], flow12: numpy.ndarray,\n                               flow12_mask: Optional[numpy.ndarray], is_image: bool = False) -> \\\n            Tuple[numpy.ndarray, numpy.ndarray]:\n        \"\"\"\n        Using bilinear interpolation\n        :param frame2: (h, w, c)\n        :param mask2: (h, w): True if known and False if unknown. Optional\n        :param flow12: (h, w, 2)\n        :param flow12_mask: (h, w): True if valid and False if invalid. Optional\n        :param is_image: If true, the return array will be clipped to be in the range [0, 255] and type-casted to uint8\n        :return: warped_frame1: (h, w, c)\n                 mask1: (h, w): True if known and False if unknown\n        \"\"\"\n        if self.resolution is not None:\n            assert frame2.shape[:2] == self.resolution\n        h, w, c = frame2.shape\n        if mask2 is None:\n            mask2 = numpy.ones(shape=(h, w), dtype=bool)\n        if flow12_mask is None:\n            flow12_mask = numpy.ones(shape=(h, w), dtype=bool)\n        grid = self.create_grid(h, w)\n        trans_pos = flow12 + grid\n\n        trans_pos_offset = trans_pos + 1\n        trans_pos_floor = numpy.floor(trans_pos_offset).astype('int')\n        trans_pos_ceil = numpy.ceil(trans_pos_offset).astype('int')\n        trans_pos_offset[:, :, 0] = numpy.clip(trans_pos_offset[:, :, 0], a_min=0, a_max=w + 1)\n        trans_pos_offset[:, :, 1] = numpy.clip(trans_pos_offset[:, :, 1], a_min=0, a_max=h + 1)\n        trans_pos_floor[:, :, 0] = numpy.clip(trans_pos_floor[:, :, 0], a_min=0, a_max=w + 1)\n        trans_pos_floor[:, :, 1] = numpy.clip(trans_pos_floor[:, :, 1], a_min=0, a_max=h + 1)\n        trans_pos_ceil[:, :, 0] = numpy.clip(trans_pos_ceil[:, :, 0], a_min=0, a_max=w + 1)\n        trans_pos_ceil[:, :, 1] = numpy.clip(trans_pos_ceil[:, :, 1], a_min=0, a_max=h + 1)\n\n        prox_weight_nw = (1 - (trans_pos_offset[:, :, 1] - trans_pos_floor[:, :, 1])) * \\\n                         (1 - (trans_pos_offset[:, :, 0] - trans_pos_floor[:, :, 0]))\n        prox_weight_sw = (1 - (trans_pos_ceil[:, :, 1] - trans_pos_offset[:, :, 1])) * \\\n                         (1 - (trans_pos_offset[:, :, 0] - trans_pos_floor[:, :, 0]))\n        prox_weight_ne = (1 - (trans_pos_offset[:, :, 1] - trans_pos_floor[:, :, 1])) * \\\n                         (1 - (trans_pos_ceil[:, :, 0] - trans_pos_offset[:, :, 0]))\n        prox_weight_se = (1 - (trans_pos_ceil[:, :, 1] - trans_pos_offset[:, :, 1])) * \\\n                         (1 - (trans_pos_ceil[:, :, 0] - trans_pos_offset[:, :, 0]))\n\n        weight_nw = prox_weight_nw * flow12_mask\n        weight_sw = prox_weight_sw * flow12_mask\n        weight_ne = prox_weight_ne * flow12_mask\n        weight_se = prox_weight_se * flow12_mask\n\n        weight_nw_3d = weight_nw[:, :, None]\n        weight_sw_3d = weight_sw[:, :, None]\n        weight_ne_3d = weight_ne[:, :, None]\n        weight_se_3d = weight_se[:, :, None]\n\n        frame2_offset = numpy.pad(frame2, pad_width=((1, 1), (1, 1), (0, 0)), mode='constant', constant_values=0)\n        mask2_offset = numpy.pad(mask2, pad_width=((1, 1), (1, 1)), mode='constant', constant_values=0)\n\n        f2_nw = frame2_offset[trans_pos_floor[:, :, 1], trans_pos_floor[:, :, 0]]\n        f2_sw = frame2_offset[trans_pos_ceil[:, :, 1], trans_pos_floor[:, :, 0]]\n        f2_ne = frame2_offset[trans_pos_floor[:, :, 1], trans_pos_ceil[:, :, 0]]\n        f2_se = frame2_offset[trans_pos_ceil[:, :, 1], trans_pos_ceil[:, :, 0]]\n\n        m2_nw = mask2_offset[trans_pos_floor[:, :, 1], trans_pos_floor[:, :, 0]]\n        m2_sw = mask2_offset[trans_pos_ceil[:, :, 1], trans_pos_floor[:, :, 0]]\n        m2_ne = mask2_offset[trans_pos_floor[:, :, 1], trans_pos_ceil[:, :, 0]]\n        m2_se = mask2_offset[trans_pos_ceil[:, :, 1], trans_pos_ceil[:, :, 0]]\n\n        m2_nw_3d = m2_nw[:, :, None]\n        m2_sw_3d = m2_sw[:, :, None]\n        m2_ne_3d = m2_ne[:, :, None]\n        m2_se_3d = m2_se[:, :, None]\n\n        nr = weight_nw_3d * f2_nw * m2_nw_3d + weight_sw_3d * f2_sw * m2_sw_3d + \\\n             weight_ne_3d * f2_ne * m2_ne_3d + weight_se_3d * f2_se * m2_se_3d\n        dr = weight_nw_3d * m2_nw_3d + weight_sw_3d * m2_sw_3d + weight_ne_3d * m2_ne_3d + weight_se_3d * m2_se_3d\n        warped_frame1 = numpy.where(dr > 0, nr / dr, 0)\n        mask1 = dr[:, :, 0] > 0\n\n        if is_image:\n            assert numpy.min(warped_frame1) >= 0\n            assert numpy.max(warped_frame1) <= 256\n            clipped_image = numpy.clip(warped_frame1, a_min=0, a_max=255)\n            warped_frame1 = numpy.round(clipped_image).astype('uint8')\n        return warped_frame1, mask1\n\n    @staticmethod\n    def create_grid(h, w):\n        x_1d = numpy.arange(0, w)[None]\n        y_1d = numpy.arange(0, h)[:, None]\n        x_2d = numpy.repeat(x_1d, repeats=h, axis=0)\n        y_2d = numpy.repeat(y_1d, repeats=w, axis=1)\n        grid = numpy.stack([x_2d, y_2d], axis=2)\n        return grid\n\n    @staticmethod\n    def read_image(path: Path) -> numpy.ndarray:\n        if path.suffix in ['.jpg', '.png', '.bmp']:\n            image = skimage.io.imread(path.as_posix())\n        elif path.suffix == '.npy':\n            image = numpy.load(path.as_posix())\n        else:\n            raise RuntimeError(f'Unknown image format: {path.as_posix()}')\n        return image\n\n    @staticmethod\n    def read_depth(path: Path) -> numpy.ndarray:\n        if path.suffix == '.png':\n            depth = skimage.io.imread(path.as_posix())\n        elif path.suffix == '.npy':\n            depth = numpy.load(path.as_posix())\n        elif path.suffix == '.npz':\n            with numpy.load(path.as_posix()) as depth_data:\n                depth = depth_data['depth']\n        elif path.suffix == '.exr':\n            import Imath\n            import OpenEXR\n\n            exr_file = OpenEXR.InputFile(path.as_posix())\n            raw_bytes = exr_file.channel('B', Imath.PixelType(Imath.PixelType.FLOAT))\n            depth_vector = numpy.frombuffer(raw_bytes, dtype=numpy.float32)\n            height = exr_file.header()['displayWindow'].max.y + 1 - exr_file.header()['displayWindow'].min.y\n            width = exr_file.header()['displayWindow'].max.x + 1 - exr_file.header()['displayWindow'].min.x\n            depth = numpy.reshape(depth_vector, (height, width))\n        else:\n            raise RuntimeError(f'Unknown depth format: {path.as_posix()}')\n        return depth\n\n    @staticmethod\n    def camera_intrinsic_transform(capture_width=1920, capture_height=1080, patch_start_point: tuple = (0, 0)):\n        start_y, start_x = patch_start_point\n        camera_intrinsics = numpy.eye(3)\n        camera_intrinsics[0, 0] = 2100\n        camera_intrinsics[0, 2] = capture_width / 2.0 - start_x\n        camera_intrinsics[1, 1] = 2100\n        camera_intrinsics[1, 2] = capture_height / 2.0 - start_y\n        return camera_intrinsics\n\n\ndef demo1():\n    frame1_path = Path('../Data/frame1.png')\n    frame2_path = Path('../Data/frame2.png')\n    depth1_path = Path('../Data/depth1.npy')\n    transformation1 = numpy.array([\n        4.067366123199462891e-01, 9.135454893112182617e-01, 2.251522164442576468e-05, -1.571802258491516113e+00,\n        -7.961163669824600220e-02, 3.546993434429168701e-02, -9.961947202682495117e-01, 1.842712044715881348e+00,\n        -9.100699424743652344e-01, 4.051870703697204590e-01, 8.715576678514480591e-02, -2.255212306976318359e+00,\n        0.000000000000000000e+00, 0.000000000000000000e+00, 0.000000000000000000e+00, 1.000000000000000000e+00\n    ]).reshape(4, 4)\n    transformation2 = numpy.array([\n        4.067366123199462891e-01, 9.135454893112182617e-01, 2.251522164442576468e-05, -1.616834521293640137e+00,\n        -7.961163669824600220e-02, 3.546993434429168701e-02, -9.961947202682495117e-01, 1.848096847534179688e+00,\n        -9.100699424743652344e-01, 4.051870703697204590e-01, 8.715576678514480591e-02, -2.275809526443481445e+00,\n        0.000000000000000000e+00, 0.000000000000000000e+00, 0.000000000000000000e+00, 1.000000000000000000e+00\n    ]).reshape(4, 4)\n\n    warper = Warper()\n    frame1 = warper.read_image(frame1_path)\n    frame2 = warper.read_image(frame2_path)\n    depth1 = warper.read_depth(depth1_path)\n    intrinsic = warper.camera_intrinsic_transform()\n\n    warped_frame2 = warper.forward_warp(frame1, None, depth1, transformation1, transformation2, intrinsic, None)[0]\n    skimage.io.imsave('frame1.png', frame1)\n    skimage.io.imsave('frame2.png', frame2)\n    skimage.io.imsave('frame2_warped.png', warped_frame2)\n    return\n\n\ndef main():\n    demo1()\n    return\n\n\nif __name__ == '__main__':\n    print('Program started at ' + datetime.datetime.now().strftime('%d/%m/%Y %I:%M:%S %p'))\n    start_time = time.time()\n    try:\n        main()\n    except Exception as e:\n        print(e)\n        traceback.print_exc()\n    end_time = time.time()\n    print('Program ended at ' + datetime.datetime.now().strftime('%d/%m/%Y %I:%M:%S %p'))\n    print('Execution time: ' + str(datetime.timedelta(seconds=end_time - start_time)))\n", "meta": {"hexsha": "55da69fb80ebcabf1e2f99bf5b4e90db84bc068b", "size": 18375, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Warper.py", "max_stars_repo_name": "NagabhushanSN95/Pose-Warping", "max_stars_repo_head_hexsha": "9d5400b6a0fe299ece3481c29b0f8fe9ba7bee4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-07-13T07:29:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T08:53:42.000Z", "max_issues_repo_path": "src/Warper.py", "max_issues_repo_name": "NagabhushanSN95/Pose-Warping", "max_issues_repo_head_hexsha": "9d5400b6a0fe299ece3481c29b0f8fe9ba7bee4e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-09-14T14:55:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-05T16:32:50.000Z", "max_forks_repo_path": "src/Warper.py", "max_forks_repo_name": "NagabhushanSN95/Pose-Warping", "max_forks_repo_head_hexsha": "9d5400b6a0fe299ece3481c29b0f8fe9ba7bee4e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-05T03:04:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T03:04:18.000Z", "avg_line_length": 50.4807692308, "max_line_length": 120, "alphanum_fraction": 0.6099047619, "include": true, "reason": "import numpy", "num_tokens": 5278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363242, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.1937835005403962}}
{"text": "#!/usr/bin/env python\n\nimport sys\nimport loco\nimport tinymath as tm\nimport numpy as np\n\nPHYSICS_BACKEND = loco.sim.PHYSICS_NONE\nRENDERING_BACKEND = loco.sim.RENDERING_GLVIZ_GLFW\n\nclass DoublePendulum(object):\n\n    def __init__(self, name='double_pendulum', pos=[0.0, 0.0, 2.0], l1=0.5, l2=0.5):\n        super(DoublePendulum, self).__init__()\n\n        self.kintree = loco.sim.kintree.KinematicTree(name, pos, tm.Matrix3f())\n        self.base = loco.sim.kintree.Box(name + '_base', [0.1, 0.1, 0.1])\n        self.link_1 = loco.sim.kintree.Capsule(name + '_link_1', 0.05, l1)\n        self.link_2 = loco.sim.kintree.Capsule(name + '_link_2', 0.04, l2)\n\n        jnt_1_axis = [1.0, 0.0, 0.0]\n        jnt_2_axis = [1.0, 0.0, 0.0]\n        self.jnt_base = loco.sim.kintree.FixedJoint(name + '_jnt_fixed')\n        self.jnt_1 = loco.sim.kintree.RevoluteJoint(name + '_jnt_rev_1', jnt_1_axis, [1.0, -1.0])\n        self.jnt_2 = loco.sim.kintree.RevoluteJoint(name + '_jnt_rev_2', jnt_2_axis, [1.0, -1.0])\n\n        tf_link_1_to_base = tm.Matrix4f(np.identity(3), [0.0, 0.0, -0.5 * l1])\n        tf_link_2_to_link_1 = tm.Matrix4f(np.identity(3), [0.0, 0.0, -0.5 * l1 - 0.5 * l2] )\n        tf_jnt_1_to_link_1 = tm.Matrix4f(np.identity(3), [0.0, 0.0, 0.5 * l1])\n        tf_jnt_2_to_link_2 = tm.Matrix4f(np.identity(3), [0.0, 0.0, 0.5 * l2])\n\n        self.kintree.SetRoot(self.base)\n        self.base.AddJoint(self.jnt_base, np.identity(4))\n        self.base.AddChild(self.link_1, tf_link_1_to_base)\n        self.link_1.AddJoint(self.jnt_1, tf_jnt_1_to_link_1)\n        self.link_1.AddChild(self.link_2, tf_link_2_to_link_1)\n        self.link_2.AddJoint(self.jnt_2, tf_jnt_2_to_link_2)\n\nif __name__ == '__main__' :\n\n    if len( sys.argv ) > 1 :\n        choice_backend = sys.argv[1]\n        if choice_backend == 'mujoco' :\n            PHYSICS_BACKEND = loco.sim.PHYSICS_MUJOCO\n        elif choice_backend == 'bullet' :\n            PHYSICS_BACKEND = loco.sim.PHYSICS_BULLET\n        elif choice_backend == 'dart' :\n            PHYSICS_BACKEND = loco.sim.PHYSICS_DART\n        elif choice_backend == 'raisim' :\n            PHYSICS_BACKEND = loco.sim.PHYSICS_RAISIM\n    print( 'Physics backend: {}'.format( PHYSICS_BACKEND ) )\n    print( 'Rendering backend: {}'.format( RENDERING_BACKEND ) )\n\n    scenario = loco.sim.Scenario()\n    floor = scenario.AddSingleBody( loco.sim.primitives.Plane( \"floor\", 10.0, 10.0, tm.Vector3f(), tm.Matrix3f() ) )\n    double_pendulum = DoublePendulum()\n    scenario.AddKinematicTree( double_pendulum.kintree )\n\n    runtime = loco.sim.Runtime( PHYSICS_BACKEND, RENDERING_BACKEND )\n    simulation = runtime.CreateSimulation( scenario )\n    visualizer = runtime.CreateVisualizer( scenario )\n\n    floor.drawable.texture = 'built_in_chessboard'\n    floor.drawable.ambient = [ 0.3, 0.5, 0.7 ]\n    floor.drawable.diffuse = [ 0.3, 0.5, 0.7 ]\n    floor.drawable.specular = [ 0.3, 0.5, 0.7 ]\n\n    while visualizer.IsActive() :\n        if visualizer.CheckSingleKeyPress( loco.sim.Keys.KEY_ESCAPE ) :\n            break\n        elif visualizer.CheckSingleKeyPress( loco.sim.Keys.KEY_R ) :\n            simulation.Reset()\n        elif visualizer.CheckSingleKeyPress( loco.sim.Keys.KEY_P ) :\n            simulation.Pause() if simulation.running else simulation.Resume()\n\n        double_pendulum.jnt_1.angle = double_pendulum.jnt_1.angle + 0.01\n        double_pendulum.jnt_2.angle = double_pendulum.jnt_2.angle + 0.005\n\n        simulation.Step( 1. / 60. )\n        visualizer.Render()\n\n    runtime.DestroySimulation()\n    runtime.DestroyVisualizer()", "meta": {"hexsha": "68c31879fdd5b978673d910f0e3634760f92c232", "size": 3535, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/python/kinematic_trees/example_programmatical.py", "max_stars_repo_name": "wpumacay/tysocTerrain", "max_stars_repo_head_hexsha": "78b6d9804ade89a483fb60952ed6e1bf50fbf3da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-17T00:57:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T00:57:11.000Z", "max_issues_repo_path": "examples/python/kinematic_trees/example_programmatical.py", "max_issues_repo_name": "wpumacay/tysocCore", "max_issues_repo_head_hexsha": "78b6d9804ade89a483fb60952ed6e1bf50fbf3da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2019-05-30T03:41:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-21T06:29:52.000Z", "max_forks_repo_path": "examples/python/kinematic_trees/example_programmatical.py", "max_forks_repo_name": "wpumacay/tysoc", "max_forks_repo_head_hexsha": "78b6d9804ade89a483fb60952ed6e1bf50fbf3da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.5903614458, "max_line_length": 116, "alphanum_fraction": 0.6574257426, "include": true, "reason": "import numpy", "num_tokens": 1146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.1937834969033229}}
{"text": "\"\"\"\nゲルフォントの定数\n\"\"\"\n\ndef gelfonds_constant(digit: int) -> str:\n\tfrom sympy import N, I\n\treturn str(N(\"(-1) ** -I\", digit))\n\nif __name__ == \"__main__\":\n\tdigit = 10000\n\tprint(gelfonds_constant(digit))\n", "meta": {"hexsha": "695ad4044fb90f7edf4bff6881b4f776d68a5d4f", "size": 197, "ext": "py", "lang": "Python", "max_stars_repo_path": "extra/gelfonds_constant.py", "max_stars_repo_name": "Fairy-Phy/Relium", "max_stars_repo_head_hexsha": "70ea037cea176f02e4768bde44dd5ee23af699b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "extra/gelfonds_constant.py", "max_issues_repo_name": "Fairy-Phy/Relium", "max_issues_repo_head_hexsha": "70ea037cea176f02e4768bde44dd5ee23af699b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extra/gelfonds_constant.py", "max_forks_repo_name": "Fairy-Phy/Relium", "max_forks_repo_head_hexsha": "70ea037cea176f02e4768bde44dd5ee23af699b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.4166666667, "max_line_length": 41, "alphanum_fraction": 0.654822335, "include": true, "reason": "from sympy", "num_tokens": 69, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.1937834969033229}}
{"text": "\"\"\"Plot figure 6: attack rates vs R0.\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import linregress\n\nimport matplotlib as mplt\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\nimport matplotlib.cm as cm\nimport matplotlib.font_manager as font_manager\n\nimport cmocean\nimport cmasher\nimport seaborn\nimport copy\nimport os\n\n\n# set the font family style\nmplt.rcParams['font.family'] = 'Myriad Pro'  # change to a font you have installed on your computer - checkout Google Fonts for free fonts available for download\n\n# set some initial paths\n\n# path to the directory where this script lives\nthisdir = os.path.abspath('')\n\n# path to the main directory of the repository\nmaindir = os.path.split(os.path.split(thisdir)[0])[0]\n\n# path to the analysis_results subdirectory\nanalysisdir = os.path.split(thisdir)[0]\n\n# path to the data subdirectory\ndatadir = os.path.join(os.path.split(os.path.split(thisdir)[0])[0], 'data')\n\n# path to the figures subdirectory within analysis_results\nfigdir = os.path.join(analysisdir, 'figures')\n\nlocation_file = os.path.join(analysisdir, 'location_country_names.csv')\nlocations_df = pd.read_csv(location_file, delimiter = ',')\n\nsetting_fractions_file = os.path.join(analysisdir, 'summary_fractions_by_location.csv')\nsetting_fractions_df = pd.read_csv(setting_fractions_file)\nsetting_codes = ['H','S','W','R']\n\n\ndef get_country_name(df,location):\n    \"\"\"\n    Return country name of the location\n\n    Args:\n        df (pandas Dataframe) : dataframe containing locations and corresponding countries\n        location (str)        : name of the location\n\n    Returns:\n        str: Name of the country the location is in.\n    \"\"\"\n    d = df[df.location == location]\n    return d.country.values[0]\n\n\ndef get_locations_by_country(df,country):\n    \"\"\"\n    Return locations in the country\n\n    Args:\n        df (pandas Dataframe) : dataframe containing locations and corresponding countries\n        country (str)         : name of the country\n\n    Returns:\n        str: Name of the country the location is in.\n    \"\"\"\n    locations = list(df[df.country == country].location.values)\n    return locations\n\n\ndef get_fractions(setting_fractions_df, location):\n    \"\"\"\n    Get the fraction of people with contacts in each setting of household (H), school (S), or work (W).\n\n    Args:\n        setting_fractions_df (pandas DataFrame) : a dataframe\n        location (str)                          : name of the location\n\n    Returns:\n        dict: A dictionary of fractions of people with contacts in each setting for the location.\n    \"\"\"\n    fractions = dict.fromkeys(['H','S','W','R'],1.)\n    d = setting_fractions_df[setting_fractions_df.location == location]\n    fractions['H'] = d.NhN.values[0]\n    fractions['S'] = d.NsN.values[0]\n    fractions['W'] = d.NwN.values[0]\n    return fractions\n\n\ndef read_contact_matrix(location, country, level, setting, num_agebrackets=85):\n    \"\"\"\n    Read in the contact for each setting.\n\n    Args:\n        location (str)        : name of the location\n        country (str)         : name of the country\n        level (str)           : name of level (country or subnational)\n        setting (str)         : name of the contact setting\n        num_agebrackets (int) : the number of age brackets for the matrix\n\n    Returns:\n        A numpy matrix of contact.\n    \"\"\"\n    setting_type, setting_suffix = 'F', 'setting'\n    if setting == 'overall':\n        setting_type, setting_suffix = 'M', 'contact_matrix'\n\n    if country == 'Europe':\n        country = location\n        level = 'country'\n\n    if level == 'country':\n        file_name = country + '_' + level + '_level_' + setting_type + '_' + setting + '_' + setting_suffix + '_' + '%i' % num_agebrackets + '.csv'\n    else:\n        file_name = country + '_' + level + '_' + location + '_' + setting_type + '_' + setting + '_' + setting_suffix + '_' + '%i' % num_agebrackets + '.csv'\n    file_path = os.path.join(datadir, 'contact_matrices', file_name)\n    M = np.loadtxt(file_path, delimiter=',')\n    return M\n\n\ndef get_ages(location, country, level, num_agebrackets=85):\n    \"\"\"\n    Get the age count for the synthetic population of the location.\n\n    Args:\n        location (str)        : name of the location\n        country (str)         : name of the country\n        level (str)           : name of level (country or subnational)\n        num_agebrackets (int) : the number of age brackets\n\n    Returns:\n        dict: A dictionary of the age count.\n    \"\"\"\n\n    if country == 'Europe':\n        country = location\n        level = 'country'\n\n    if level == 'country':\n        file_name = country + '_' + level + '_level_age_distribution_' + '%i' % num_agebrackets + '.csv'\n    else:\n        file_name = country + '_' + level + '_' + location + '_age_distribution_' + '%i' % num_agebrackets + '.csv'\n    file_path = os.path.join(datadir, 'age_distributions', file_name)\n    df = pd.read_csv(file_path, delimiter=',', header=None)\n    df.columns = ['age', 'age_count']\n    ages = dict(zip(df.age.values.astype(int), df.age_count.values))\n    return ages \n\n\ndef get_average_age(ages):\n    \"\"\"\n    Get the average age from a dictionary of age counts.\n\n    Args:\n        ages (dict): dictionary of age counts\n\n    Return:\n        float: The average age given the age count.\n    \"\"\"\n    average_age = 0\n    total_population = sum(ages.values())\n    for a in ages:\n        average_age += ages[a] * a\n    average_age = average_age/total_population\n    return average_age\n\n\ndef get_school_age_distribution(location):\n    \"\"\"\n    Get the age count of people active in the school setting.\n\n    Args:\n        location (str): name of the location\n\n    Returns:\n        dict: Age count of people active in the school setting.\n    \"\"\"\n    ages = {}\n    file_path = os.path.join(analysisdir, 'schools_age_distributions',\n                'schools_age_distributions_' + location + '.dat')\n    df = pd.read_csv(file_path, delimiter = ',')\n    ages = dict(zip(df.age.values, df.setting_count.values))\n    return ages\n\n\ndef get_percent_in_school(ages, school_ages):\n    \"\"\"\n    Get the percent of people in school.\n\n    Args: \n        ages (dict)        : age count\n        school_ages (dict) : school age count\n\n    Returns:\n        float: The percent of people in the school setting.\n    \"\"\"\n    total_in_school = np.sum([v for v in school_ages.values()], dtype = float)\n    total_population = np.sum([v for v in ages.values()], dtype = float)\n    return total_in_school/total_population * 100\n\n\ndef get_attack_rates_df(reference_location, reference_scenario, beta, susceptibility_drop_factor, gamma_inverse, num_agebrackets):\n    \"\"\"\n    Get attack rates dataframe for an SIR compartmental model with age specific contact patterns.\n\n    Args:\n        reference_location (str)           : name of reference location or locations\n        reference_scenario (str)           : specific reference scenario\n        beta (float)                       : the transmissibilty\n        susceptibility_drop_factor (float) : susceptibility of adults to those under 18\n        gamma_inverse (float)              : the mean recovery period\n        num_agebrackets (int)              : the number of age brackets for the matrix\n    \n    Returns:\n        Pandas dataframe of attack rates by location\n    \"\"\"\n\n    file_path = os.path.join(analysisdir, 'reference_location_' + reference_location, 'mcmc_beta_and_dropfactor_scenario_' + reference_scenario,\n                             'all_locations_attack_rates_by_age_reference_scenario_' + reference_scenario + '_beta_' + '%.2f' % beta + '_susceptibility_' + '%.2f' % susceptibility + '_gamma_inverse_' + '%.1f' % gamma_inverse + '_' + str(num_agebrackets) + '.csv')\n    return pd.read_csv(file_path)\n\n\ndef get_attack_rate(df, location):\n    \"\"\"\n    Get the total attack rate for the location from the dataframe for an SIR compartmental model with age specific contact patterns.\n\n    Args:\n        df (pd.DataFrame) : a dataframe of attack rates by location\n        location (str)    : name of the location\n\n    Returns:\n        float: The total attack rate for the location as a fraction from an SIR compartmental model with age specific contact patterns. Values between 0 and 1.\n    \"\"\"\n    return df.loc[df['location'] == location]['artotal'].values[0]\n\n\ndef get_homogeneous_attack_rate_df(gamma_inverse, num_agebrackets):\n    \"\"\"\n    Get a dataframe with the attack rate for an SIR model with the homogeneous mixing assumption for different basic reproduction, R0, values with a given average recovery period.\n\n    Args:\n        gamma_inverse (float): the mean recovery period\n        num_agebrackets (int): the number of age brackets for the matrix\n\n    Returns:\n        Pandas dataframe of attack rates by R0 value\n    \"\"\"\n    file_path = os.path.join(analysisdir, 'homogeneous_sir_attack_rates', 'attack_rates_SIR_homogeneous_mixing.csv')\n    df = pd.read_csv(file_path)\n    return df\n\n\ndef get_homogeneous_attack_rate(df, R0_star):\n    \"\"\"\n    Get the attack rate for an SIR model with the homogeneous mixing assumption for a given basic reproduction, R0_star, value.\n\n    Args:\n        df (pd.DataFrame) : a dataframe of attack rates by the basic reproduction number\n        R0_star (float)   : the basic reproduction number\n\n    Returns:\n        float: The total attack rate as a fraction from an SIR model with homogeneous mixing assumptions and specified basic reproduction number R0_star. Values between 0 and 1.\n    \"\"\"\n    return df.loc[df['R0'] == R0_star]['attack_rate'].values[0]\n\n\ndef get_eigenvalue(matrix):\n    \"\"\"\n    Get the real component of the leading eigenvalue of a square matrix.\n\n    Args:\n        matrix (np.ndarray): square matrix\n\n    Returns:\n        float: Real component of the leading eigenvalue of the matrix.\n    \"\"\"\n    eigenvalue = max(np.linalg.eigvals(matrix)).real\n    return eigenvalue\n\n\ndef get_R0(beta, gamma_inverse, matrix):\n    \"\"\"\n    Get the basic reproduction number, R0, for an SIR compartmental model given the basic reproduction number, the mean recovery period, and the contact matrix.\n    \n    Args:\n        beta (float)          : the transmissibility beta\n        gamma_inverse (float) : the mean recovery period\n        matrix (np.ndarray)   : the contact matrix\n\n    Returns:\n        float: The basic reproduction number R0 for an SIR compartmental model.\n    \"\"\"\n\n    gamma = 1./gamma_inverse\n    eigenvalue = get_eigenvalue(matrix)\n    return beta * eigenvalue / gamma\n\n\ndef get_beta(R0, gamma_inverse, matrix):\n    \"\"\"\n    Get the transmissibility from an SIR model with age specific contact patterns and basic reproduction number.\n\n    Args:\n        R0_star (float)       : the basic reproduction number\n        gamma_inverse (float) : the mean recovery period\n        matrix (np.ndarray)   : the age specific contact matrix\n\n    Returns:\n        float: The transmissibility from an SIR model with age specific contact patterns.\n    \"\"\"\n    gamma = float(1)/gamma_inverse\n    eigenvalue = get_eigenvalue(matrix)\n    return R0 * gamma / eigenvalue\n\n\ndef linear_function(x,m,b):\n    \"\"\"\n    Get the y value of a linear function given the x value.\n\n    Args:\n        m (float): the slope\n        b (float): the intercept\n\n    Returns:\n        The expected y value from a linear function at some specified x value.\n    \"\"\"\n    return m*x + b\n\n\ndef plot_fig(countries, reference_location, reference_scenario, beta, susceptibility_drop_factor, gamma_inverse, num_agebrackets):\n    \"\"\"\n    Plot the attack rates from an SIR model with age specific contact patterns vs the basic reproduction, the average age, \n    and the percent of the population with contacts in the school layer for subnational locations.\n\n    Args:\n        countries (list)                   : list of countries\n        reference_location (str)           : the reference location (or set of locations) the transmissibilty is calibrated to\n        reference_scenario (str)           : label of the reference scenario\n        beta (float)                       : the transmissibility\n        susceptibility_drop_factor (float) : susceptibility of adults to those under 18\n        gamma_inverse (float)              : the mean recovery period\n        num_agebrackets (int)              : the number of age brackets\n\n    Returns:\n        Matplotlib figure.\n    \"\"\"\n    countries = ['Australia', 'Canada', 'China', 'Europe', 'India', 'Israel', 'Japan', 'Russia', 'South_Africa', 'United_States']\n    locations = []\n\n    for country in countries:\n        locations += get_locations_by_country(locations_df, country)\n        if country in locations and country != 'Israel':\n            locations.remove(country)\n\n        if country == 'India':\n            locations.remove('Dadra_and_Nagar_Haveli')\n            locations.remove('Chandigarh')\n            locations.remove('Lakshadweep')\n\n    if 'Russian_Federation' in locations:\n        locations.remove('Russian_Federation')\n\n    country_colour_dic = {}\n    country_colour_dic['Australia'] = '#0000ff'\n    country_colour_dic['Canada'] = '#2ab207'\n    country_colour_dic['China'] = '#fcc200'\n    country_colour_dic['Europe'] = '#941cca'\n    country_colour_dic['India'] = 'darkorange'\n    country_colour_dic['Israel'] = '#9b9b9b'\n    country_colour_dic['Japan'] = '#000098'\n    country_colour_dic['Russia'] = '#dc142b'\n    country_colour_dic['South_Africa'] = '#b5d93c'\n    country_colour_dic['United_States'] = '#00ace7'\n\n    hdf = get_homogeneous_attack_rate_df(gamma_inverse, num_agebrackets)\n    df = get_attack_rates_df(reference_location, reference_scenario, beta, susceptibility_drop_factor, gamma_inverse, num_agebrackets)\n\n    width = 16\n    height = 5\n    left = 0.06\n    right = 0.865\n    bottom = 0.16\n    top = 0.88\n    wspace = 0.32\n\n    fig, ax = plt.subplots(1, 3, figsize=(width, height))\n    fig.subplots_adjust(left = left, right = right, top = top, bottom = bottom, wspace = wspace)\n\n\n    leg_left = right + 0.01\n    leg_right = 0.985\n    leg_bottom = bottom\n    leg_top = top\n    leg_width = leg_right - leg_left\n    leg_height = leg_top - leg_bottom\n\n    fontsize = 20\n\n    axleg = fig.add_axes([leg_left, leg_bottom, leg_width, leg_height])\n    axleg.axis('off')\n\n    attack_rates_list = []\n    R0_list = []\n    average_age_list = []\n    percent_in_school_list = []\n    color_list = []\n\n    beta_drop_age = 18\n\n    for n, location in enumerate(locations):\n        country = get_country_name(locations_df, location)\n        if location == 'Israel':\n            matrix = read_contact_matrix(location, country, 'country', 'overall')\n            ages = get_ages(location, country, 'country')\n        else:\n            matrix = read_contact_matrix(location, country, 'subnational', 'overall')\n            ages = get_ages(location, country, 'subnational')\n\n        R0 = get_R0(beta, gamma_inverse, matrix)\n        R0_list.append(R0)\n\n        average_age = get_average_age(ages)\n        average_age_list.append(average_age)\n\n        if country != 'Europe':\n            school_ages = get_school_age_distribution(location)\n            percent_in_school = get_percent_in_school(ages, school_ages)\n\n        else:\n            fractions = get_fractions(setting_fractions_df, location)\n            percent_in_school = fractions['S'] * 100\n\n        percent_in_school_list.append(percent_in_school)\n\n        ar = get_attack_rate(df, location) * 100\n        attack_rates_list.append(ar)\n        color = country_colour_dic[country]\n        color_list.append(color)\n\n    homogeneous_attack_rates_list = hdf.attack_rate.values * 100\n    homogeneous_R0_list = hdf.R0.values\n\n    size = 12\n\n    leg = []\n\n    ax[0].scatter(R0_list, attack_rates_list, marker='o', color=color_list, s=size)\n    ax[0].plot(homogeneous_R0_list, homogeneous_attack_rates_list, color='k', lw=1.5, label='Homogenous \\nmixing model')\n    leg.append(ax[0].legend(loc=2, fontsize=17))\n    ax[0].set_xlim(1.5, 2.0)\n    ax[0].set_xticks(np.arange(1.5, 2.01, 0.1))\n    ax[0].set_xlabel(r'$R_0$', fontsize = fontsize)\n    ax[0].text(1.39, 50, 'a', fontsize=fontsize+24, fontstyle='oblique')\n\n\n    m,b,r,p,std_err = linregress(average_age_list,attack_rates_list)\n    y_theory = np.array([linear_function(a,m,b) for a in average_age_list])\n    ax[1].plot(average_age_list, y_theory, color = 'k', lw = 1.5)\n    ax[1].scatter(average_age_list, attack_rates_list, marker='o', color=color_list, s=size)\n    ax[1].text(45,73, r'$\\rho$ = ' + '%.2f' % r , fontsize = 18, verticalalignment = 'center', horizontalalignment = 'center', color = 'k')\n    ax[1].set_xlim(20, 55)\n    ax[1].set_xticks(np.arange(20, 51, 10))\n    leg.append(ax[1].legend(loc = 7, fontsize = 16, ncol = 1))\n    ax[1].set_xlabel('Average Age', fontsize = fontsize)\n    ax[1].text(13.5, 50, 'b', fontsize=fontsize+24, fontstyle='oblique')\n\n\n    m,b,r,p,std_err = linregress(percent_in_school_list,attack_rates_list)\n    y_theory = np.array([linear_function(a,m,b) for a in percent_in_school_list])\n    ax[2].plot(percent_in_school_list, y_theory, color = 'k', lw = 1.5)\n    ax[2].scatter(percent_in_school_list, attack_rates_list, marker='o', color=color_list, s=size)\n    ax[2].text(20,73, r'$\\rho$ = ' + '%.2f' % r , fontsize = 18, verticalalignment = 'center', horizontalalignment = 'center', color = 'k')\n    ax[2].set_xlim(10, 45)\n    ax[2].set_xticks(np.arange(10, 50, 10))\n    ax[2].set_xlabel('% In Educational Institutions', fontsize = fontsize)\n    ax[2].text(3.5, 50, 'c', fontsize=fontsize+24, fontstyle='oblique')\n\n\n    for country in ['Australia','Canada','China','Europe','India','Israel','Japan','Russia','South_Africa','United_States']:\n        ax[2].scatter(0,0, color = country_colour_dic[country], s = size * 2, label = country.replace('-',' ').replace('_',' '))\n    leg.append(ax[2].legend(loc = 7, fontsize = 17, ncol = 1, bbox_to_anchor = (0.6,0.4,1,0.2)))\n\n    for i in range(len(ax)):\n        ax[i].set_ylabel('Attack Rate (%)', fontsize = fontsize)\n        ax[i].set_yticks(np.arange(55, 81, 5))\n        ax[i].set_ylim(54, 80)\n        ax[i].tick_params(labelsize=fontsize-2)\n        ax[i].tick_params(axis='x', which='minor', bottom=False)\n        ax[i].tick_params(axis='y', which='minor', left=False)\n        leg[i].draw_frame(False)\n\n    plt.minorticks_off()\n\n    fig_path = os.path.join(figdir, 'fig_6.pdf')\n    fig.savefig(fig_path, format='pdf')\n\n\n\nif __name__ == '__main__':\n    \n    reference_location = 'polymod_and_tomsk'\n    reference_scenario = 'all_locations'\n\n    beta = 0.04752\n    susceptibility = 1.0\n    gamma_inverse = 2.6\n    num_agebrackets = 85\n\n    countries = ['Australia', 'Canada', 'China', 'Europe', 'India', 'Israel', 'Japan', 'Russia', 'South_Africa', 'United_States']\n\n    plot_fig(countries, reference_location, reference_scenario, beta, susceptibility, gamma_inverse, num_agebrackets)\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "ffc6b88d977bbccfc1e9301514b3a2d799bc9548", "size": 18802, "ext": "py", "lang": "Python", "max_stars_repo_path": "analysis_results/scripts/fig_6.py", "max_stars_repo_name": "DongxiaW/mixing-patterns", "max_stars_repo_head_hexsha": "e841a934b826ecc98bf443026c32e7c6b7aa75bc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2020-03-03T07:05:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T22:40:49.000Z", "max_issues_repo_path": "analysis_results/scripts/fig_6.py", "max_issues_repo_name": "DongxiaW/mixing-patterns", "max_issues_repo_head_hexsha": "e841a934b826ecc98bf443026c32e7c6b7aa75bc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-03-03T07:22:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:51:47.000Z", "max_forks_repo_path": "analysis_results/scripts/fig_6.py", "max_forks_repo_name": "DongxiaW/mixing-patterns", "max_forks_repo_head_hexsha": "e841a934b826ecc98bf443026c32e7c6b7aa75bc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2020-12-10T08:39:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T00:12:54.000Z", "avg_line_length": 35.6774193548, "max_line_length": 263, "alphanum_fraction": 0.6642910329, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678568, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.19378349139863896}}
{"text": "from __future__ import annotations\n\n\nfrom collections import Counter\nimport datetime as dt\nimport json\nimport math\nfrom queue import PriorityQueue\nfrom typing import Union, Optional, Tuple, cast, TYPE_CHECKING, Dict\n\nimport numpy as np\n\nfrom slim import logger, LoggableMixin\nfrom slim.simulation.config import Config\nfrom slim.types.TreatmentTypes import GeneticMechanism, Money, ChemicalTreatment, \\\n    ThermalTreatment\nfrom slim.simulation.lice_population import (GenoDistrib, GrossLiceDistrib,\n                                             LicePopulation, GenoTreatmentDistrib, GenoTreatmentValue,\n                                             GenoLifeStageDistrib, largest_remainder, LifeStage, GenoDistribDict)\nfrom slim.types.QueueTypes import (DamAvailabilityBatch, EggBatch, TravellingEggBatch, TreatmentEvent,\n                                   pop_from_queue)\nfrom slim.JSONEncoders import CustomFarmEncoder\n\nif TYPE_CHECKING:  # pragma: no cover\n    from slim.simulation.farm import Farm, GenoDistribByHatchDate\n\nOptionalDamBatch = Optional[DamAvailabilityBatch]\nOptionalEggBatch = Optional[EggBatch]\n\nclass Cage(LoggableMixin):\n    \"\"\"\n    Fish cages contain the fish.\n    \"\"\"\n\n    def __init__(self, cage_id: int, cfg: Config, farm: Farm,\n                 initial_lice_pop: Optional[GrossLiceDistrib] = None):\n        \"\"\"\n        Create a cage on a farm.\n\n        :param cage_id: the label (id) of the cage within the farm\n        :param cfg: the farm configuration\n        :param farm: a Farm object\n        :param initial_lice_pop: if provided, overrides default generated lice population\n        \"\"\"\n        super().__init__()\n\n        self.cfg = cfg\n        self.id = cage_id\n\n        self.farm_id = farm.name\n        self.start_date = cfg.farms[self.farm_id].cages_start[cage_id]\n        self.date = cfg.start_date\n\n        # TODO: update with calculations\n        if initial_lice_pop is None:\n            lice_population = {\"L1\": cfg.min_ext_pressure, \"L2\": 0, \"L3\": 0, \"L4\": 0, \"L5f\": 0,\n                               \"L5m\": 0}\n        else:\n            lice_population = initial_lice_pop\n\n        self.farm = farm\n\n        self.egg_genotypes = GenoDistrib()\n        # TODO/Question: what's the best way to deal with having multiple possible genetic schemes?\n        # TODO/Question: I suppose some of this initial genotype information ought to come from the config file\n        # TODO/Question: the genetic mechanism will be the same for all lice in a simulation, so should it live in the driver?\n        self.genetic_mechanism = self.cfg.genetic_mechanism\n\n        geno_by_lifestage = {stage: GenoDistrib(self.cfg.initial_genetic_ratios).normalise_to(lice_population[stage])\n                             for stage in lice_population}\n\n        self.lice_population = LicePopulation(geno_by_lifestage, self.cfg.initial_genetic_ratios)\n\n        self.num_fish = cfg.farms[self.farm_id].num_fish\n        self.num_infected_fish = self.get_mean_infected_fish()\n\n        self.hatching_events: PriorityQueue[EggBatch] = PriorityQueue()\n        self.arrival_events: PriorityQueue[TravellingEggBatch] = PriorityQueue()\n        self.treatment_events: PriorityQueue[TreatmentEvent] = PriorityQueue()\n\n        self.last_effective_treatment: Optional[TreatmentEvent] = None\n\n    def to_json_dict(self):\n        \"\"\"\n        Create a JSON-serialisable dictionary version of a cage.\n        \"\"\"\n        filtered_vars = vars(self).copy()\n\n        del filtered_vars[\"farm\"]\n        del filtered_vars[\"cfg\"]\n        del filtered_vars[\"logged_data\"]\n\n        # May want to improve these or change them if we change the representation for genotype distribs\n        # Note: JSON encoders do not allow a default() being run on the _keys_ of dictionaries\n        # and GenotypePopulation is a dict subclass. The simplest option here is to trivially force to_json_dict()\n        # whenever possible,\n        filtered_vars[\"egg_genotypes\"] = self.egg_genotypes.to_json_dict()\n        filtered_vars[\"lice_population\"] = self.lice_population.to_json_dict()\n        filtered_vars[\"geno_by_lifestage\"] = self.lice_population.geno_by_lifestage.to_json_dict()\n        filtered_vars[\"genetic_mechanism\"] = str(filtered_vars[\"genetic_mechanism\"])[len(\"GeneticMechanism.\"):]\n\n        return filtered_vars\n\n    def __str__(self):\n        \"\"\"\n        Get a human readable string representation of the cage in json form.\n        :return: a description of the cage\n        \"\"\"\n\n        return json.dumps(self.to_json_dict(), cls=CustomFarmEncoder, indent=4)\n\n    def update(\n        self,\n        cur_date: dt.datetime,\n        pressure: int,\n        ext_pressure_ratio: GenoDistribDict\n    ) -> Tuple[GenoDistrib, Optional[dt.datetime], Money]:\n        \"\"\"Update the cage at the current time step.\n\n        :param cur_date: Current date of simulation\n        :param pressure: External pressure, planctonic lice coming from the reservoir\n        :param ext_pressure_ratio: The genotype ratio to use for the external pressure\n        :return: Tuple (egg genotype distribution, hatching date, cost)\n        \"\"\"\n\n        self.clear_log()\n\n        if cur_date >= self.start_date:\n            logger.debug(\"\\tUpdating farm {} / cage {}\".format(self.farm_id, self.id))\n            logger.debug(\"\\t\\tinitial fish population = {}\".format(self.num_fish))\n        else:\n            logger.debug(\"\\tUpdating farm {} / cage {} (non-operational)\".format(self.farm_id, self.id))\n\n        logger.debug(\"\\t\\tinitial lice population = {}\".format(self.lice_population))\n\n        logger.debug(f\"\\t\\tAdding {pressure} lice from external pressure\")\n\n        # Background lice mortality events\n        dead_lice_dist = self.get_background_lice_mortality()\n\n        # Development events\n        new_L2, new_L4, new_females, new_males = self.get_lice_lifestage(cur_date)\n\n        # Lice coming from other cages and farms\n        # NOTE: arrivals first then hatching\n        hatched_arrivals_dist = self.get_arrivals(cur_date)\n\n        # Egg hatching\n        new_offspring_distrib = self.create_offspring(cur_date)\n\n        # Lice coming from reservoir\n        lice_from_reservoir = self.get_reservoir_lice(pressure, ext_pressure_ratio)\n        logger.debug(f\"\\t\\tExternal pressure lice distribution = {lice_from_reservoir}\")\n\n        if cur_date < self.start_date or self.is_fallowing:\n            # Values that are not used before the start date\n            treatment_mortality = self.lice_population.get_empty_geno_distrib()\n            fish_deaths_natural, fish_deaths_from_lice = 0, 0\n            num_infection_events = 0\n            avail_dams_batch: OptionalDamBatch = None\n            new_egg_batch: OptionalEggBatch = None\n            cost = self.cfg.monthly_cost / 28\n\n        else:\n            # Events that happen when cage is populated with fish\n            # (after start date)\n            days_since_start = (cur_date - self.date).days\n\n            # Treatment mortality events\n            treatment_mortality, cost = self.get_lice_treatment_mortality(cur_date)\n\n            # Fish growth and death\n            fish_deaths_natural, fish_deaths_from_lice = self.get_fish_growth(days_since_start)\n\n            # Infection events\n            num_infection_events = self.do_infection_events(days_since_start)\n\n            # Mating events that create eggs\n            self.lice_population.free_dams(cur_date)\n            delta_avail_dams, delta_eggs = self.do_mating_events(cur_date)\n            avail_dams_batch = DamAvailabilityBatch(cur_date + dt.timedelta(days=self.cfg.dam_unavailability),\n                                                    delta_avail_dams)\n\n            new_egg_batch = self.get_egg_batch(cur_date, delta_eggs)\n\n        fish_deaths_from_treatment = self.get_fish_treatment_mortality(\n            (cur_date - self.start_date).days,\n            fish_deaths_from_lice,\n            fish_deaths_natural\n        )\n\n        self.update_deltas(\n            dead_lice_dist,\n            treatment_mortality,\n            fish_deaths_natural,\n            fish_deaths_from_lice,\n            fish_deaths_from_treatment,\n            new_L2,\n            new_L4,\n            new_females,\n            new_males,\n            num_infection_events,\n            lice_from_reservoir,\n            avail_dams_batch,\n            new_offspring_distrib,\n            hatched_arrivals_dist,\n        )\n\n        logger.debug(\"\\t\\tfinal lice population= {}\".format(self.lice_population))\n\n        egg_distrib = GenoDistrib()\n        hatch_date: Optional[dt.datetime] = None\n        if cur_date >= self.start_date and new_egg_batch:\n            logger.debug(\"\\t\\tfinal fish population = {}\".format(self.num_fish))\n            egg_distrib = new_egg_batch.geno_distrib\n            hatch_date = new_egg_batch.hatch_date\n            logger.debug(\"\\t\\tlice offspring = {}\".format(sum(egg_distrib.values())))\n\n        assert egg_distrib.is_positive()\n        return egg_distrib, hatch_date, cost\n\n    def get_temperature(self, cur_date: dt.datetime) -> float:\n        cur_month = cur_date.month\n        return self.farm.year_temperatures[cur_month - 1]\n\n    def get_lice_treatment_mortality_rate(self, cur_date: dt.datetime) -> GenoTreatmentDistrib:\n        \"\"\"Check if the cage is currently being treated. If yes, calculate the treatment rates.\n        Note: this method consumes the internal treatment event queue.\n\n        :param cur_date: the current date\n        :returns: the mortality rates broken down by geno data.\n        \"\"\"\n        susceptible_populations = [self.lice_population.geno_by_lifestage[stage] for stage in LicePopulation.susceptible_stages]\n        num_susc_per_geno = cast(GenoDistrib, GenoDistrib.batch_sum(susceptible_populations))\n\n        geno_treatment_distrib = {geno: GenoTreatmentValue(0.0, 0) for geno in num_susc_per_geno}\n\n        def cts(event):\n            nonlocal self\n            self.last_effective_treatment = event\n\n        pop_from_queue(self.treatment_events, cur_date, cts)\n\n        # if no treatment has been applied check if the previous treatment is still effective\n        if self.last_effective_treatment is None or \\\n                self.last_effective_treatment.affecting_date > cur_date or \\\n                cur_date > self.last_effective_treatment.treatment_window:\n            return geno_treatment_distrib\n\n        treatment_type = self.last_effective_treatment.treatment_type\n        ave_temp = self.get_temperature(cur_date)\n\n        logger.debug(\"\\t\\ttreating farm {}/cage {} on date {}\".format(self.farm_id,\n                                                                      self.id, cur_date))\n\n        geno_treatment_distrib = self.cfg.get_treatment(treatment_type).get_lice_treatment_mortality_rate(self.lice_population, ave_temp)\n\n        return geno_treatment_distrib\n\n    def get_lice_treatment_mortality(self, cur_date) -> Tuple[GenoLifeStageDistrib, Money]:\n        \"\"\"\n        Calculate the number of lice in each stage killed by treatment.\n\n        Note: this method consumes the internal event queue\n\n        :param cur_date: the current date\n        \"\"\"\n\n        dead_lice_dist = self.lice_population.get_empty_geno_distrib()\n\n        dead_mortality_distrib = self.get_lice_treatment_mortality_rate(cur_date)\n\n        cost = Money(\"0.00\")\n\n        for geno, (mortality_rate, num_susc) in dead_mortality_distrib.items():\n            if mortality_rate > 0:\n                num_dead_lice = self.cfg.rng.poisson(mortality_rate * num_susc)\n                num_dead_lice = min(num_dead_lice, num_susc)\n\n                # We emulate the top algorithm with a multivariate hypergeom distrib\n                population_by_stages = np.array([self.lice_population.geno_by_lifestage[stage][geno]\n                                                 for stage in LicePopulation.susceptible_stages])\n\n                # TODO: why is num_dead_lice not clamped?\n                num_dead_lice = min(population_by_stages.sum(), num_dead_lice)\n                dead_lice_nums = self.cfg.rng.multivariate_hypergeometric(\n                    population_by_stages, num_dead_lice).tolist()\n                for stage, dead_lice_num in zip(LicePopulation.susceptible_stages, dead_lice_nums):\n                    dead_lice_dist[stage][geno] = dead_lice_num\n\n                logger.debug(\"\\t\\tdistribution of dead lice on farm {}/cage {} = {}\"\n                             .format(self.farm_id, self.id, dead_lice_dist))\n\n        # Compute cost\n        if self.last_effective_treatment is not None and self.last_effective_treatment.end_application_date > cur_date:\n            treatment_type = self.last_effective_treatment.treatment_type\n            treatment_cfg = self.cfg.get_treatment(treatment_type)\n            cage_days = (cur_date - self.start_date).days\n            if isinstance(treatment_cfg, ChemicalTreatment):\n                cost = treatment_cfg.price_per_kg * int(self.average_fish_mass(cage_days) / 1e3)\n            elif isinstance(treatment_cfg, ThermalTreatment):\n                cost = treatment_cfg.price_per_application\n\n        return dead_lice_dist, cost\n\n    def get_stage_ages_distrib(self, stage: str, temp_c: float = 10.0):\n        \"\"\"\n        Create an age distribution (in days) for the sea lice within a lifecycle stage.\n\n        This distribution is computed by using a simplified version of formulae (4), (6), (8)\n        in Aldrin et al.: we assume that all lice of a stage m-1 that evolve at stage m\n        will be put at a stage-age of 0, and that this is going to be a constant/stable\n        amount.\n        \"\"\"\n\n        stage_age_max_days = int(self.cfg.stage_age_evolutions[stage])\n\n        if stage in (\"L2\", \"L5f\"):\n            # Bogus uniform distribution L5m/L5f follow different schemes.\n            # More realistically, this is an exponential/poisson distribution\n            return np.full(stage_age_max_days, 1/stage_age_max_days)\n\n        delta_p = self.cfg.delta_p[stage]\n        delta_m10 = self.cfg.delta_m10[stage]\n        delta_s = self.cfg.delta_s[stage]\n\n        ages = np.arange(stage_age_max_days)\n\n        weibull_median_rates = self._dev_rates(delta_p, delta_m10, delta_s, temp_c, ages)\n\n        probas = np.empty_like(ages, dtype=np.float64)\n        probas[0] = 1.0\n        for i in range(1, stage_age_max_days):\n            probas[i] = probas[i-1] * (1.0 - weibull_median_rates[i-1])\n\n        return probas / np.sum(probas)\n\n    @staticmethod\n    def _dev_rates(del_p: float, del_m10: float, del_s: float, temp_c: float, ages: np.ndarray):\n        \"\"\"\n        Probability of developing after n_days days in a stage as given by Aldrin et al 2017\n        See section 2.2.4 of Aldrin et al. (2017)\n        :param del_p: power transformation constant on temp_c\n        :param del_m10: 10 °C median reference value\n        :param del_s: fitted Weibull shape parameter\n        :param temp_c: average temperature in °C\n        :param ages: stage-age\n        :return: expected development rate\n        \"\"\"\n        epsilon = np.float64(1e-30)\n        del_m = del_m10 * (10 / temp_c) ** del_p\n\n        unbounded = np.clip(np.log(2) * del_s * ages ** (del_s - 1) * del_m ** (-del_s), epsilon, np.float64(1.0))\n        return unbounded\n\n    def get_lice_lifestage(self, cur_date: dt.datetime) -> Tuple[int, int, int, int]:\n        \"\"\"\n        Move lice between lifecycle stages.\n        See Section 2.1 of Aldrin et al. (2017)\n\n        :param cur_date: the current date\n        :returns: a tuple (new_l2, new_l4, new_l5f, new_l5m)\n        \"\"\"\n        logger.debug(\"\\t\\tupdating lice lifecycle stages\")\n\n        def evolve_next_stage(stage: LifeStage, temp_c: float) -> int:\n            # weibull params\n            del_p = self.cfg.delta_p[stage]\n            del_m10 = self.cfg.delta_m10[stage]\n            del_s = self.cfg.delta_s[stage]\n            num_lice = self.lice_population[stage]\n            if num_lice == 0:\n                return 0\n            max_dev_time = self.cfg.stage_age_evolutions[stage]\n            ages_distrib = self.get_stage_ages_distrib(stage, temp_c)\n            # let us sample from 1000 lice\n            ages = self.cfg.rng.choice(np.arange(max_dev_time), 1000, p=ages_distrib)\n\n            evolution_rates = self._dev_rates(del_p, del_m10, del_s, temp_c, ages)\n            average_rates = np.mean(evolution_rates)\n\n            # print(f\"Stage {stage} -> {average_rates}\")\n\n            return round(num_lice * average_rates) #int(min(self.cfg.rng.poisson(num_lice * average_rates), num_lice))\n\n        lice_dist = {}\n        ave_temp = self.get_temperature(cur_date)\n\n        # L4 -> L5\n        l4_to_l5 = evolve_next_stage(\"L4\", ave_temp)\n        new_females = int(self.cfg.rng.choice([math.floor(l4_to_l5 / 2.0), math.ceil(l4_to_l5 / 2.0)]))\n        new_males = (l4_to_l5 - new_females)\n\n        lice_dist[\"L5f\"] = new_females\n        lice_dist[\"L5m\"] = new_males\n\n        # L3 -> L4\n        new_L4 = lice_dist[\"L4\"] = evolve_next_stage(\"L3\", ave_temp)\n\n        # L2 -> L3 is done in do_infection_events(). Indeed, evolution from L2 to L3 is (virtually) age-independent\n\n        # L1 -> L2\n        new_L2 = lice_dist[\"L2\"] = evolve_next_stage(\"L1\", ave_temp)\n\n        logger.debug(\"\\t\\t\\tdistribution of new lice lifecycle stages on farm {}/cage {} = {}\"\n                     .format(self.farm_id, self.id, lice_dist))\n\n        return new_L2, new_L4, new_females, new_males\n\n    def get_fish_treatment_mortality(\n            self,\n            days_since_start: int,\n            fish_lice_deaths: int,\n            fish_backgroud_deaths: int) -> int:\n        \"\"\"\n        Get fish mortality due to treatment. Mortality due to treatment is defined in terms of\n        point percentage increases, thus we can only account for \"excess deaths\".\n        If treatment is not being applied the overall\n\n        :param days_since_start: the number of days since the beginning of the simulation\n        :param fish_lice_deaths: the number of fish dead by lice\n        :param fish_background_deaths: the number of fish dead by natural reasons\n\n        :returns: number of fish death events\n        \"\"\"\n        # See surveys/overton_treatment_mortalities.py for an explanation on what is going on\n        mortality_events = fish_lice_deaths + fish_backgroud_deaths\n\n        if mortality_events == 0 or self.num_fish == 0:\n            return 0\n\n        cur_date = self.start_date + dt.timedelta(days=days_since_start)\n        if not self.is_treated(cur_date):\n            return 0\n\n        efficacy_window = self.last_effective_treatment.effectiveness_duration_days\n\n        temperature = self.get_temperature(cur_date)\n        fish_mass = self.average_fish_mass(days_since_start)\n\n        last_treatment_params = self.cfg.get_treatment(self.last_effective_treatment.treatment_type)\n        predicted_deaths = last_treatment_params.get_fish_mortality_occurrences(\n            temperature, fish_mass, self.num_fish, efficacy_window, mortality_events)\n\n        treatment_mortality_occurrences = round(predicted_deaths)\n\n        return treatment_mortality_occurrences\n\n    def get_fish_growth(self, days_since_start) -> Tuple[int, int]:\n        \"\"\"\n        Get the number of fish that get killed either naturally or by lice.\n\n        :param: days_since_start: the number of days since the beginning.\n        :returns: a tuple (natural_deaths, lice_induced_deaths, lice_deaths)\n        \"\"\"\n\n        logger.debug(\"\\t\\tupdating fish population\")\n\n        def fb_mort(days):\n            \"\"\"\n            Fish background mortality rate, decreasing as in Soares et al 2011\n\n            Fish death rate: constant background daily rate 0.00057 originally based on\n            www.gov.scot/Resource/0052/00524803.pdf\n\n            According to Volsett it should be higher (around 0.005) , but that's unlikely.\n            However the authors used a trick: assuming that a mortality event takes 5 days one can\n            divide the actual mortality rate by 5.\n            Thus, 0.005 / 5 ~~ 0.0009-0.001 . It is still quite higher than expected.\n\n            Therefore, we'll stick to this constant.\n            TODO: what should we do with the formulae?\n\n            :param days: number of days elapsed\n            :return: fish background mortality rate\n            \"\"\"\n            return 0.000057  # (1000 + (days - 700)**2)/490000000\n\n        # Apply a sigmoid based on the number of lice per fish\n        pathogenic_lice = sum([self.lice_population[stage] for stage in LicePopulation.pathogenic_stages])\n        if self.num_infected_fish > 0:\n            lice_per_host_mass = pathogenic_lice / (self.num_infected_fish *\n                                                    (self.average_fish_mass(days_since_start) / 1e3))\n        else:\n            lice_per_host_mass = 0.0\n\n        # The daily mortality rate also takes into account a mortality event takes days (in this case, 5).\n        prob_lice_death = 0.2 / (1 + math.exp(-self.cfg.fish_mortality_k *\n                                            (lice_per_host_mass - self.cfg.fish_mortality_center)))\n\n        ebf_death = fb_mort(days_since_start) * self.num_fish\n        elf_death = self.num_infected_fish * prob_lice_death\n        fish_deaths_natural = round(ebf_death) # self.cfg.rng.poisson(ebf_death)\n        fish_deaths_from_lice = round(elf_death) # self.cfg.rng.poisson(elf_death)\n\n        logger.debug(\"\\t\\t\\tnumber of background fish death {}, from lice {}\"\n                     .format(fish_deaths_natural, fish_deaths_from_lice))\n\n        return fish_deaths_natural, fish_deaths_from_lice\n\n    def compute_eta_aldrin(self, num_fish_in_farm, days):\n        return self.cfg.infection_main_delta + math.log(num_fish_in_farm/1e5) + self.cfg.infection_weight_delta * \\\n               (math.log(self.average_fish_mass(days)/1e3) - self.cfg.delta_expectation_weight_log)\n\n    def get_infection_rates(self, days_since_start) -> Tuple[float, int]:\n        \"\"\"\n        Compute the number of lice that can infect and what their infection rate (number per fish) is\n\n        :param days_since_start: days since the cage has opened\n\n        :returns: a pair (Einf, num_avail_lice)\n        \"\"\"\n\n        # Based on Aldrin et al.\n        # Perhaps we can have a distribution which can change per day (the mean/median increaseѕ?\n        # but at what point does the distribution mean decrease)./\n        age_distrib = self.get_stage_ages_distrib(\"L2\")\n        num_avail_lice = round(self.lice_population[\"L2\"] * np.sum(age_distrib[1:]))\n        if num_avail_lice > 0:\n            num_fish_in_farm = self.farm.num_fish\n\n            # TODO: this has O(c^2) complexity\n            etas = np.array([c.compute_eta_aldrin(num_fish_in_farm, days_since_start) for c in self.farm.cages])\n            Einf = math.exp(etas[self.id]) / (1 + np.sum(np.exp(etas)))\n\n            return Einf, num_avail_lice\n\n        return 0.0, num_avail_lice\n\n    def do_infection_events(self, days: int) -> int:\n        \"\"\"Infect fish in this cage if the sea lice are in stage L2 and at least 1 day old\n\n        :param cur_date: current date of simulation\n        :param days: days the number of days elapsed\n\n        :return: number of evolving lice, or equivalently the new number of infections\n        \"\"\"\n        Einf, num_avail_lice = self.get_infection_rates(days)\n\n        if Einf == 0:\n            return 0\n\n        expected_events = Einf * num_avail_lice\n\n        inf_events = self.cfg.rng.poisson(expected_events)\n\n        return min(inf_events, num_avail_lice)\n\n    def get_infecting_population(self, *args) -> int:\n        if args is None or len(args) == 0:\n            infective_stages = [\"L3\", \"L4\", \"L5m\", \"L5f\"]\n        else:\n            infective_stages = list(args)\n        return sum(self.lice_population[stage] for stage in infective_stages)\n\n    def get_mean_infected_fish(self, *args) -> int:\n        \"\"\"\n        Get the average number of infected fish.\n\n        :param \\*args: the stages to consider (optional, by default all stages from the third onward are taken into account)\n\n        :returns: the number of infected fish\n        \"\"\"\n        if self.num_fish == 0:\n            return 0\n\n        attached_lice = self.get_infecting_population(*args)\n\n        # see: https://stats.stackexchange.com/a/296053\n        num_infected_fish = int(self.num_fish * (1 - ((self.num_fish - 1) / self.num_fish) ** attached_lice))\n        return num_infected_fish\n\n    def get_variance_infected_fish(self, n: int, k: int) -> float:\n        # Rationale: assuming that we generate N bins that sum to K, we can model this as a multinomial distribution\n        # where all p_i are the same. Therefore, the variance of each bin is k*(n-1)/(n**2)\n        # Because we are considering the total variance of k events at the same time we need to multiply by k,\n        # thus yielding k**2*(n-1)/(n**2).\n\n        if n == 0:\n            return 0.0\n        return k**2 * (n - 1) / (n ** 2)\n\n    def get_num_matings(self) -> int:\n        \"\"\"\n        Get the number of matings. Implement Cox's approach assuming an unbiased sex distribution\n        \"\"\"\n\n        # Background: AF and AM are randomly assigned to fish according to a negative multinomial distribution.\n        # What we want is determining what is the expected likelihood there is _at least_ one AF and _at\n        # least_ one AM on the same fish.\n\n        males = self.lice_population[\"L5m\"]\n        females = self.lice_population.available_dams.gross\n\n        if males == 0 or females == 0:\n            return 0\n\n        # VMR: variance-mean ratio; VMR = m/k + 1 -> k = m / (VMR - 1) with k being an \"aggregation factor\"\n        mean = (males + females) / self.get_mean_infected_fish(\"L5m\", \"L5f\")\n\n        n = self.num_fish\n        k = self.get_infecting_population(\"L5m\", \"L5f\")\n        variance = self.get_variance_infected_fish(n, k)\n        vmr = variance / mean\n        if vmr <= 1.0:\n            return 0\n        aggregation_factor = mean / (vmr - 1)\n\n        prob_matching = 1 - (1 + males / ((males + females) * aggregation_factor)) ** (-1 - aggregation_factor)\n        # TODO: using a poisson distribution can lead to a high std for high prob*females\n        return int(np.clip(self.cfg.rng.poisson(prob_matching * females), np.int32(0), np.int32(min(males, females))))\n\n    def do_mating_events(self, cur_date) -> Tuple[GenoDistrib, GenoDistrib]:\n        \"\"\"\n        Will generate two deltas:  one to add to unavailable dams and subtract from available dams, one to add to eggs\n        Assume males don't become unavailable? in this case we don't need a delta for sires\n\n        :param cur_date: the current date\n\n        :returns: a pair (mating_dams, new_eggs)\n        \"\"\"\n\n        delta_eggs = GenoDistrib()\n        num_matings = self.get_num_matings()\n\n        distrib_sire_available = self.lice_population.geno_by_lifestage[\"L5m\"]\n        distrib_dam_available = self.lice_population.available_dams\n\n        mating_dams = self.select_lice(distrib_dam_available, num_matings)\n        mating_sires = self.select_lice(distrib_sire_available, num_matings)\n\n        if distrib_sire_available.gross == 0 or distrib_dam_available.gross == 0:\n            return GenoDistrib(), GenoDistrib()\n\n        num_eggs = self.get_num_eggs(num_matings)\n        if self.genetic_mechanism == GeneticMechanism.DISCRETE:\n            delta_eggs = self.generate_eggs_discrete_batch(mating_sires, mating_dams, num_eggs)\n        elif self.genetic_mechanism == GeneticMechanism.MATERNAL:\n            delta_eggs = self.generate_eggs_maternal_batch(distrib_dam_available, num_eggs)\n\n        delta_eggs = self.mutate(delta_eggs, mutation_rate=self.cfg.geno_mutation_rate)\n\n        return mating_dams, delta_eggs\n\n    def generate_eggs_discrete_batch(self, sire_distrib: GenoDistrib, dam_distrib: GenoDistrib,\n                                     number_eggs: int) -> GenoDistrib:\n        \"\"\"\n        Get number of eggs based on discrete genetic mechanism.\n\n        The algorithm emulates the following scenario: each sire s_i is sampled from sire_distrib\n        and will have a given genomic :math:`g_{s_i}` and similarly a dam :math:`d_i` will have a genotype :math:`g_{d_i}`.\n        Because the genomic of a lice can only be dominant, recessive or partial dominant then\n        the mating will result in one of these happening depending on the usual Mendelevian\n        mechanism.\n        The algorithm terminates when all sires and dams have been mated.\n        Here we emulate such sampling strategy via a O(1) algorithm as follows: we compute\n        the probabilities of each combination arising and adopt a multinomial distribution\n        in order to achieve a given number of eggs.\n        The rationale for the formulae used here is the following:\n\n        - to get an A (dominant) one needs a combination of dominant and dominant allele, or dominant and the right half of partially dominant genes;\n\n        - to get an a (recessive) one does the same as above, but with fully recessive alleles instead;\n\n        - to get a partially dominant one, we use the inclusion-exclusion principle and subtract the cases above from all the possible pairings.\n\n        Together with being fast, this approach naturally models statistical uncertainty compared\n        to a perfect Mendelevian split. Unfortunately it does not naturally include mutation\n        to non-existent strains (e.g. a mating between pure dominant lice distributions can never\n        yield partial dominance or recessive genomics in the offspring).\n\n        :param sire_distrib: the genotype distribution of the sires\n        :param dam_distrib: the genotype distribution of the eggs\n        :param number_eggs: the total number of eggs\n\n        :returns: the newly sampled eggs as a :class:`GenoDistrib`.\n        \"\"\"\n\n        assert sire_distrib.gross == dam_distrib.gross\n\n        keys = [('A',), ('a',), ('A', 'a')]\n        x1, y1, z1 = tuple(sire_distrib[k] for k in keys)\n        x2, y2, z2 = tuple(dam_distrib[k] for k in keys)\n\n        N_A = (x1 + 1/2*z1)*(x2+1/2*z2)\n        N_a = (y1 + 1/2*z1)*(y2+1/2*z2)\n        denom = sire_distrib.gross * dam_distrib.gross\n        N_Aa = denom - N_A - N_a\n\n        if denom == 0:\n            return GenoDistrib()\n\n        # We need to follow GenoDistrib's ordering now\n        p = np.array([N_a, N_Aa, N_A]) / denom\n\n        return GenoDistrib.from_ratios(number_eggs, p, self.cfg.rng)\n\n    @staticmethod\n    def generate_eggs_maternal_batch(dams: GenoDistrib, number_eggs: int) -> GenoDistrib:\n        \"\"\"Get number of eggs based on maternal genetic mechanism.\n\n        Maternal-only inheritance - all eggs have mother's genotype.\n\n        :param dam: the genomics of the dams\n        :param number_eggs: the number of eggs produced\n        :return: genomics distribution of eggs produced\n        \"\"\"\n        return dams.normalise_to(number_eggs)\n\n    def mutate(self, eggs: GenoDistrib, mutation_rate: float) -> GenoDistrib:\n        \"\"\"\n        Mutate the genotype distribution\n\n        :param eggs: the genotype distribution of the newly produced eggs\n        :param mutation_rate: the rate of mutation with respect to the number of eggs.\n        \"\"\"\n        if mutation_rate == 0:\n            return eggs\n\n        mutations = self.cfg.rng.poisson(mutation_rate * sum(eggs.values()))\n\n        # generate a \"swap\" matrix\n        # rationale: since ('a',) actually represents a pair of genes ('a', 'a')\n        # there are only three directions: R->ID, ID->D, ID->R, D->ID. Note that\n        # R->D or D->R are impossible via a single mutation.\n        # Self-mutations are ignored.\n        # To model this, we create a \"masking\" swapping matrix and force to 0 masked entries\n        # and make sure they cannot be selected.\n\n        alleles = [('a',), ('A',), ('A', 'a')]\n        n = len(alleles)\n        mask_matrix = np.array([[0, 0, 1],\n                                [0, 0, 1],\n                                [1, 1, 0]])\n\n        p = mask_matrix.flatten() / np.sum(mask_matrix)\n\n        # since I can't really be bothered to avoid negative mutations, we simply roll the dice every time until we get\n        # a favourable outcome. Not ideal, but it works...\n\n        while True:\n            swap_matrix = self.cfg.rng.multinomial(mutations, p).reshape(n, n)\n            result = eggs.copy()\n            for idx, allele in enumerate(alleles):\n                to_add = np.sum(swap_matrix[idx, :]) - np.sum(swap_matrix[:, idx])\n                result[allele] += to_add\n                if result[allele] == 0:\n                    del result[allele]\n            if result.is_positive():\n                break\n\n        return result\n\n    def select_lice(self, distrib_lice_available: GenoDistrib, num_lice: int) -> GenoDistrib:\n        \"\"\"\n        From a geno distribution of eligible lice sample a given Genotype distribution\n\n        Note: this is very similar to GenoDistrib.normalise_to() but performs an explicit\n        sampling.\n\n        TODO: should we integrate this into GenoDistrib class\n\n        :param distrib_lice_available: the starting dam genomic distribution\n        :param num_lice: the wished number of dams to sample\n        \"\"\"\n        # TODO: this function is flexible enough to be renamed and used elsewhere\n        if sum(distrib_lice_available.values()) <= num_lice:\n            return distrib_lice_available.copy()\n\n        # \"we need to select k lice from the given population broken down into different allele\n        # bins and subtract\" -> \"select :math:`n` balls from the following :math`N_1, ..., N_k` bins without\n        # replacement -> use a multivariate hypergeometric distribution\n        lice_as_list = self.cfg.rng.multivariate_hypergeometric(\n            list(distrib_lice_available.values()), num_lice)\n        selected_lice = GenoDistrib(dict(zip(distrib_lice_available.keys(),\n                                                   lice_as_list)))\n\n        return selected_lice\n\n    def get_num_eggs(self, mated_females) -> int:\n        \"\"\"\n        Get the number of new eggs\n\n        :param mated_females: the number of mated females that reproduce\n\n        :returns: the number of eggs produced\n        \"\"\"\n\n        # See Aldrin et al. 2017, §2.2.6\n        age_distrib = self.get_stage_ages_distrib(\"L5f\")\n        age_range = np.arange(1, len(age_distrib) + 1)\n\n        mated_females_distrib = mated_females * age_distrib\n\n        # Hatching time is already covered in get_egg_batch\n        eggs = self.cfg.reproduction_eggs_first_extruded * \\\n               (age_range ** self.cfg.reproduction_age_dependence) * mated_females_distrib\n\n        return int(np.round(np.sum(eggs)))\n\n    def get_egg_batch(self, cur_date: dt.datetime, egg_distrib: GenoDistrib) -> EggBatch:\n        \"\"\"\n        Get the expected arrival date of an egg batch\n\n        :param cur_date: the current time\n        :param egg_distrib: the egg distribution\n\n        :returns: EggBatch representing egg distribution and expected hatching date\n        \"\"\"\n\n        # We use Stien et al (2005)'s regressed formula\n        # τE= [β1/(T – 10 + β1β2)]**2  (see equation 8)\n        # where β2**(-2) is the average temperature centered at around 10 degrees\n        # and β1 is a shaping factor. This function is formally known as Belehrádek’s function\n        cur_month = cur_date.month\n        ave_temp = self.get_temperature(cur_date)\n\n        beta_1 = self.cfg.delta_m10[\"L0_stien\"]\n        beta_2 = self.cfg.delta_p[\"L0\"]\n        expected_time = (beta_1 / (ave_temp - 10 + beta_1 * beta_2)) ** 2\n        expected_hatching_date = cur_date + dt.timedelta(self.cfg.rng.poisson(expected_time))\n        return EggBatch(expected_hatching_date, egg_distrib)\n\n    def create_offspring(self, cur_time: dt.datetime) -> GenoDistrib:\n        \"\"\"\n        Hatch the eggs from the event queue\n\n        :param cur_time: the current time\n\n        :returns: a delta egg genomics\n        \"\"\"\n\n        delta_egg_offspring = GenoDistrib({geno: 0 for geno in self.cfg.initial_genetic_ratios})\n\n        def cts(hatching_event: EggBatch):\n            nonlocal delta_egg_offspring\n            delta_egg_offspring += hatching_event.geno_distrib\n\n        pop_from_queue(self.hatching_events, cur_time, cts)\n        return delta_egg_offspring\n\n    def get_arrivals(self, cur_date: dt.datetime) -> GenoDistrib:\n        \"\"\"Process the arrivals queue.\n\n        :param cur_date: Current date of simulation\n\n        :returns: Genotype distribution of eggs hatched in travel\n        \"\"\"\n\n        hatched_dist = GenoDistrib()\n\n        # check queue for arrivals at current date\n        def cts(batch: TravellingEggBatch):\n            nonlocal self\n            nonlocal hatched_dist\n\n            # if the hatch date is after current date, add to stationary egg queue\n            if batch.hatch_date >= cur_date:\n                stationary_batch = EggBatch(batch.hatch_date, batch.geno_distrib)\n                self.hatching_events.put(stationary_batch)\n\n            # otherwise the egg has hatched during travel, so determine the life stage\n            # and add to population\n            else:\n                # TODO: determine life stage it arrives at; assumes all are L1 for now\n                hatched_dist = batch.geno_distrib\n\n        pop_from_queue(self.arrival_events, cur_date, cts)\n\n        return hatched_dist\n\n    def get_dying_lice_from_dead_fish(self, num_dead_fish: int) -> GrossLiceDistrib:\n        \"\"\"\n        Get the number of lice that die when fish die.\n\n        :param num_dead_fish: the number of dead fish\n        :returns: a gross distribution\n        \"\"\"\n\n        # Note: no paper actually provides a clear guidance on this.\n        # This is mere speculation.\n        # Basically, only consider PA and A males (for L4m = 0.5*L4)\n        # as potentially able to survive and find a new host.\n        # Only a fixed proportion can survive.\n\n        if self.get_infecting_population() == 0 or self.num_infected_fish == 0:\n            return {}\n\n        affected_lice_gross = round(self.get_infecting_population() *\n                                    num_dead_fish / self.num_infected_fish)\n        infecting_lice = self.get_infecting_population()\n\n        affected_lice_quotas = np.array([self.lice_population[stage] / infecting_lice * affected_lice_gross\n                         for stage in LicePopulation.susceptible_stages])\n        affected_lice_np = largest_remainder(affected_lice_quotas)\n\n        affected_lice = Counter(dict(zip(LicePopulation.susceptible_stages, affected_lice_np.tolist())))\n\n        surviving_lice_quotas = np.rint(np.trunc([\n            self.lice_population['L4'] / (2 * infecting_lice) *\n            affected_lice_gross * self.cfg.male_detachment_rate,\n            self.lice_population['L5m'] / infecting_lice *\n            affected_lice_gross * self.cfg.male_detachment_rate,\n        ]))\n        surviving_lice = Counter(dict(zip(['L4', 'L5m'], surviving_lice_quotas.tolist())))\n\n        dying_lice = affected_lice - surviving_lice\n\n        dying_lice_distrib = {k: int(v) for k, v in dying_lice.items() if v > 0}\n        logger.debug(f\"\\t\\tLice mortality due to fish mortality: {dying_lice_distrib}\")\n        return dying_lice_distrib\n\n    def promote_population(\n            self,\n            prev_stage: Union[str, GenoDistrib],\n            cur_stage: str,\n            leaving_lice: int,\n            entering_lice: Optional[int] = None\n    ):\n        \"\"\"\n        Promote the population by stage and respect the genotypes\n\n        :param prev_stage: the lice stage from which cur_stage evolves\n        :param cur_stage: the lice stage that is about to evolve\n        :param leaving_lice: the number of lice in the _cur_stage=>next_stage_ progression\n        :param entering_lice: the number of lice in the _prev_stage=>cur_stage_ progression. If _prev_stage_ is a a string, _entering_lice_ must be an _int_\n        \"\"\"\n        if isinstance(prev_stage, str):\n            if entering_lice is not None:\n                prev_stage_geno = self.lice_population.geno_by_lifestage[prev_stage]\n                entering_geno_distrib = prev_stage_geno.normalise_to(entering_lice)\n            else:\n                raise ValueError(\"entering_lice must be an int when prev_stage is a str\")\n        else:\n            entering_geno_distrib = prev_stage\n        cur_stage_geno = self.lice_population.geno_by_lifestage[cur_stage]\n\n        leaving_geno_distrib = cur_stage_geno.normalise_to(leaving_lice)\n        cur_stage_geno = cur_stage_geno + entering_geno_distrib - leaving_geno_distrib\n\n        # update gross population. This is a bit hairy but I cannot think of anything simpler.\n        self.lice_population.geno_by_lifestage[cur_stage] = cur_stage_geno\n\n    def update_deltas(\n            self,\n            dead_lice_dist: GrossLiceDistrib,\n            treatment_mortality: GenoLifeStageDistrib,\n            fish_deaths_natural: int,\n            fish_deaths_from_lice: int,\n            fish_deaths_from_treatment: int,\n            new_L2: int,\n            new_L4: int,\n            new_females: int,\n            new_males: int,\n            new_infections: int,\n            lice_from_reservoir: Dict[LifeStage, GenoDistrib],\n            delta_dams_batch: OptionalDamBatch,\n            new_offspring_distrib: GenoDistrib,\n            hatched_arrivals_dist: GenoDistrib,\n    ):\n        \"\"\"Update the number of fish and the lice in each life stage\n\n        :param dead_lice_dist: the number of dead lice due to background death (as a distribution)\n        :param treatment_mortality: the distribution of genotypes being affected by treatment\n        :param fish_deaths_natural: the number of natural fish death events\n        :param fish_deaths_from_lice: the number of lice-induced fish death events\n        :param fish_deaths_from_treatment: the number of treatment-induced fish death events\n        :param new_L2: number of new L2 fish\n        :param new_L4: number of new L4 fish\n        :param new_females: number of new adult females\n        :param new_males: number of new adult males\n        :param new_infections: the number of new infections (i.e. progressions from L2 to L3)\n        :param lice_from_reservoir: the number of lice taken from the reservoir\n        :param delta_dams_batch: the genotypes of now-unavailable females in batch events\n        :param new_offspring_distrib: the new offspring obtained from hatching and migrations\n        :param hatched_arrivals_dist: new offspring obtained from arrivals\n        \"\"\"\n\n        # Update dead_lice_dist to include fish-caused death as well\n        dead_lice_by_fish_death = self.get_dying_lice_from_dead_fish(\n            min(fish_deaths_natural + fish_deaths_from_lice, self.num_infected_fish))\n        for affected_stage, reduction in dead_lice_by_fish_death.items():\n            dead_lice_dist[affected_stage] += reduction\n\n        for stage in self.lice_population:\n            # update background mortality\n            bg_delta = self.lice_population[stage] - dead_lice_dist[stage]\n            self.lice_population[stage] = max(0, bg_delta)\n\n            # update population due to treatment\n            # TODO: __isub__ here is broken\n            self.lice_population.geno_by_lifestage[stage] = self.lice_population.geno_by_lifestage[stage] - \\\n                                                            treatment_mortality[stage]\n\n        self.lice_population.remove_negatives()\n\n        self.promote_population(\"L4\", \"L5m\", 0, new_males)\n        self.promote_population(\"L4\", \"L5f\", 0, new_females)\n        self.promote_population(\"L3\", \"L4\", new_males + new_females, new_L4)\n        self.promote_population(\"L2\", \"L3\", new_L4, new_infections)\n        self.promote_population(\"L1\", \"L2\", new_infections, new_L2)\n\n        self.promote_population(new_offspring_distrib, \"L1\", new_L2, None)\n        self.promote_population(hatched_arrivals_dist, \"L1\", 0, None)\n\n        self.lice_population.remove_negatives()\n\n        # in absence of wildlife genotype, simply upgrade accordingly\n        self.lice_population.geno_by_lifestage[\"L2\"] += lice_from_reservoir[\"L2\"]\n        self.lice_population.geno_by_lifestage[\"L1\"] += lice_from_reservoir[\"L1\"]\n\n        if delta_dams_batch:\n            self.lice_population.add_busy_dams_batch(delta_dams_batch)\n\n        self.num_fish -= (fish_deaths_natural + fish_deaths_from_lice + fish_deaths_from_treatment)\n        if self.num_fish < 0:\n            self.num_fish = 0\n\n        # treatment may kill some lice attached to the fish, thus update at the very end\n        self.num_infected_fish = self.get_mean_infected_fish()\n\n    # TODO: update arrivals dict type\n    def update_arrivals(self, arrivals_dict: GenoDistribByHatchDate, arrival_date: dt.datetime):\n        \"\"\"Update the arrivals queue\n\n        :param arrivals_dict: List of dictionaries of genotype distributions based on hatch date\n        :param arrival_date: Arrival date at this cage\n        \"\"\"\n\n        for hatch_date in arrivals_dict:\n\n            # skip if there are no eggs in the dictionary\n            if sum(arrivals_dict[hatch_date].values()) == 0:\n                continue\n\n            # create new travelling batch and update the queue\n            batch = TravellingEggBatch(arrival_date, hatch_date, arrivals_dict[hatch_date])\n            self.arrival_events.put(batch)\n\n    def get_background_lice_mortality(self) -> GrossLiceDistrib:\n        \"\"\"\n        Background death in a stage (remove entry) -> rate = number of\n        individuals in stage*stage rate (nauplii 0.17/d, copepods 0.22/d,\n        pre-adult female 0.05, pre-adult male ... Stien et al 2005)\n\n        :returns: the current background mortality. The return value is genotype-agnostic\n\n        \"\"\"\n        # TODO: this is dumb\n        lice_mortality_rates = self.cfg.background_lice_mortality_rates\n        lice_population = self.lice_population\n\n        dead_lice_dist = {}\n        for stage in lice_population:\n            mortality_rate = lice_population[stage] * lice_mortality_rates[stage] # some exp / different mortalities - but this gets quickly unwieldly\n            mortality: int = round(mortality_rate)#min(self.cfg.rng.poisson(mortality_rate), lice_population[stage])\n            dead_lice_dist[stage] = mortality\n\n        logger.debug(\"\\t\\tbackground mortality distribution of dead lice = {}\".format(dead_lice_dist))\n        return dead_lice_dist\n\n\n    def average_fish_mass(self, days):\n        \"\"\"\n        Average fish mass.\n\n        :params days: number of elapsed days\n        :returns: the average fish mass (in grams).\n        \"\"\"\n        smolt_params = self.cfg.smolt_mass_params\n        return smolt_params.max_mass / (1 + math.exp(smolt_params.skewness * (days - smolt_params.x_shift)))\n\n    def get_reservoir_lice(self, pressure: int, external_pressure_ratios: GenoDistribDict) -> Dict[LifeStage, GenoDistrib]:\n        \"\"\"Get distribution of lice coming from the reservoir\n\n        :param pressure: External pressure\n        :param external_pressure_ratios: the external pressure ratios to sample from\n\n        :return: Distribution of lice in L1 and L2\n        \"\"\"\n\n        if pressure == 0:\n            return {\"L1\": GenoDistrib(), \"L2\": GenoDistrib()}\n\n        new_L1_gross = self.cfg.rng.integers(low=0, high=pressure, size=1)[0]\n        new_L2_gross = pressure - new_L1_gross\n\n        keys = list(external_pressure_ratios.keys())\n        probas = list(external_pressure_ratios.values())\n        new_L1 = GenoDistrib.from_ratios(new_L1_gross, probas, self.cfg.rng)\n        new_L2 = GenoDistrib.from_ratios(new_L2_gross, probas, self.cfg.rng)\n        #new_L1 = GenoDistrib(dict(zip(keys, self.cfg.rng.multinomial(new_L1_gross, probas).tolist())))\n        #new_L2 = GenoDistrib(dict(zip(keys, self.cfg.rng.multinomial(new_L2_gross, probas).tolist())))\n\n        new_lice_dist = {\"L1\": new_L1, \"L2\": new_L2}\n        logger.debug(\"\\t\\tdistribution of new lice from reservoir = {}\".format(new_lice_dist))\n        return new_lice_dist\n\n    def fallow(self):\n        \"\"\"Put the cage in a fallowing state.\n\n        Implications:\n\n        1. All the fish would be removed.\n        2. L3/L4/L5 would therefore disappear as they are attached to fish.\n        3. Dam waiting and treatment queues will be flushed.\n        \"\"\"\n\n        for stage in LicePopulation.pathogenic_stages:\n            self.lice_population[stage] = 0\n\n        self.num_infected_fish = self.num_fish = 0\n        self.treatment_events = PriorityQueue()\n\n    @property\n    def is_fallowing(self):\n        return self.num_fish == 0\n\n    def is_treated(self, cur_date):\n        if self.last_effective_treatment is not None:\n            treatment = self.last_effective_treatment\n            if cur_date <= treatment.treatment_window:\n                return True\n\n        return False\n\n    @property\n    def aggregation_rate(self):\n        \"\"\"The aggregation rate is the number of lice over the total number of fish.\n        Elsewhere it is referred to as infection rate, but here \"infection rate\" only refers to host fish.\n\n        :returns: the aggregation rate\"\"\"\n        return self.lice_population[\"L5f\"] / self.num_fish if self.num_fish > 0 else 0.0\n", "meta": {"hexsha": "9bed84648a7f91a9e44bb5ca286f28f8ad118f00", "size": 49060, "ext": "py", "lang": "Python", "max_stars_repo_path": "slim/simulation/cage.py", "max_stars_repo_name": "magicicada/slim", "max_stars_repo_head_hexsha": "e6e966dfa88145f0f571e9479ea22ed7ce61fd57", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-10-06T20:09:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T11:40:57.000Z", "max_issues_repo_path": "slim/simulation/cage.py", "max_issues_repo_name": "resistance-modelling/slim", "max_issues_repo_head_hexsha": "ce05d40f56f5263cb039973af3e187cffc1d00b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 143, "max_issues_repo_issues_event_min_datetime": "2021-07-16T09:44:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T16:27:40.000Z", "max_forks_repo_path": "slim/simulation/cage.py", "max_forks_repo_name": "resistance-modelling/slim", "max_forks_repo_head_hexsha": "ce05d40f56f5263cb039973af3e187cffc1d00b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.2627865961, "max_line_length": 156, "alphanum_fraction": 0.6560538117, "include": true, "reason": "import numpy", "num_tokens": 11831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.2974699363766585, "lm_q1q2_score": 0.193758494177308}}
{"text": "from __future__ import print_function, division\nfrom clock_tree import ClockTree\nimport utils as ttutils\nimport config as ttconf\nimport numpy as np\nfrom scipy import optimize as sciopt\nfrom Bio import Phylo\nfrom version import tt_version as __version__\n\n\nclass TreeTime(ClockTree):\n    \"\"\"\n    TreeTime is a wrapper class to ClockTree that adds additional functionality\n    such as reroot, detection and exclusion of outliers, resolution of polytomies\n    using temporal information, and relaxed molecular clock models\n    \"\"\"\n\n    def __init__(self, *args,**kwargs):\n        \"\"\"\n        TreeTime constructor\n\n        Parameters\n        -----------\n         Arguments to construct ClockTree\n\n        Keyword Args\n        ------------\n         Kwargs to construct ClockTree\n\n        \"\"\"\n        super(TreeTime, self).__init__(*args, **kwargs)\n        self.n_iqd = ttconf.NIQD\n\n    def run(self, root=None, infer_gtr=True, relaxed_clock=None, n_iqd = None,\n            resolve_polytomies=True, max_iter=0, Tc=None, fixed_clock_rate=None,\n            time_marginal=False, use_input_branch_length = False, **kwargs):\n\n        \"\"\"\n        Run TreeTime reconstruction. Based on the input parameters, it divides\n        the analysis into semi-independent jobs and conquers them one-by one\n        gradually optimizing the tree given the temporal constarints and leaf\n        nodes sequences.\n\n        Parameters\n        ----------\n\n         root : str, None\n            Try to find better root position on a given tree. If string is passed,\n            the root will be searched according to the specified method. Available\n            reroot methods are: 'best', 'oldest', '<leaf_name>'\n\n            If None, use tree as-is.\n\n         infer_gtr : bool default True\n            Should infer GTR model?\n\n         relaxed_clock : dic, None\n            If not None, use autocorrelated molecular clock model. Specify the\n            clock parameters as {slack:<slack>, coupling:<coupling>} dictionary.\n\n         n_iqd : int, None\n            If not None, filter tree nodes, which do not obey molecular clock\n            for the particular tree. The nodes, which deviate more than\n            :code:`n_iqd` interquantile intervals from the molecular clock\n            regression will be marked as 'BAD' and not account in the TreeTime\n            analysis\n\n         resolve_polytomies : bool\n            Should attempt to resolve multiple mergers?\n\n         max_iter : int\n            Maximum number of iterations to optimize the tree\n\n         Tc : float, str, None\n            If not None, use coalescent model to correct the branch lengths by\n            introducing merger costs.\n\n            If Tc is float, it is interpreted as the coalescence time scale\n\n            If Tc is str, it should be one of (:code:`opt`, :code:`skyline`)\n\n         fixed_clock_rate : float, None\n            If None, infer clock rate from the molecular clock\n\n            If float, use this rate\n\n         time_marginal : bool default False\n            Should perform marginal reconstruction of the node's positions?\n\n         use_input_branch_length : bool\n            If True, rely on the branch lengths in the imput tree and skip directly\n            to the maximum-likelihood ancestral sequence reconstruction.\n            Otherwise, perform preliminary sequence reconstruction using parsimony\n            algorithm and do branch length optimization\n\n        Keyword Args\n        ------------\n\n         Additional arguments needed by the dowstream funcitons\n\n\n        \"\"\"\n        # determine how to reconstruct and sample sequences\n        seq_kwargs = {\"marginal\":False, \"sample_from_profile\":\"root\"}\n        if \"fixed_pi\" in kwargs:\n            seq_kwargs[\"fixed_pi\"] = kwargs[\"fixed_pi\"]\n        if \"do_marginal\" in kwargs:\n            time_marginal=kwargs[\"do_marginal\"]\n\n        # initially, infer ancestral sequences and infer gtr model if desired\n        if use_input_branch_length:\n            self.infer_ancestral_sequences(infer_gtr=infer_gtr, **seq_kwargs)\n            self.prune_short_branches()\n        else:\n            self.optimize_sequences_and_branch_length(infer_gtr=infer_gtr,\n                                                  max_iter=2, prune_short=True, **seq_kwargs)\n        avg_root_to_tip = np.mean([x.dist2root for x in self.tree.get_terminals()])\n\n        # optionally reroot the tree either by oldest, best regression or with a specific leaf\n        if n_iqd or root=='clock_filter':\n            if \"plot_rtt\" in kwargs and kwargs[\"plot_rtt\"]:\n                plot_rtt=True\n            else:\n                plot_rtt=False\n            self.clock_filter(reroot='best' if root=='clock_filter' else root,\n                              n_iqd=n_iqd, plot=plot_rtt)\n        elif root is not None:\n            self.reroot(root=root)\n\n        if use_input_branch_length:\n            self.infer_ancestral_sequences(**seq_kwargs)\n        else:\n            self.optimize_sequences_and_branch_length(max_iter=2,**seq_kwargs)\n\n        # infer time tree and optionally resolve polytomies\n        self.logger(\"###TreeTime.run: INITIAL ROUND\",0)\n        self.make_time_tree(clock_rate=fixed_clock_rate, time_marginal=False, **kwargs)\n\n        self.LH = [[self.tree.sequence_marginal_LH if seq_kwargs['marginal'] else self.tree.sequence_joint_LH,\n                    self.tree.positional_joint_LH, 0.0]]\n\n        # iteratively reconstruct ancestral sequences and re-infer\n        # time tree to ensure convergence.\n        niter = 0\n        while niter < max_iter:\n\n            self.logger(\"###TreeTime.run: ITERATION %d out of %d iterations\"%(niter+1,max_iter),0)\n            # add coalescent prior\n            if Tc and (Tc is not None):\n                from merger_models import Coalescent\n                self.logger('TreeTime.run: adding coalescent prior with Tc='+str(Tc),1)\n                self.merger_model = Coalescent(self.tree, Tc=avg_root_to_tip,\n                                               date2dist=self.date2dist, logger=self.logger)\n\n                if Tc=='skyline' and niter==max_iter-1: # restrict skyline model optimization to last iteration\n                    self.merger_model.optimize_skyline(**kwargs)\n                    self.logger(\"optimized a skyline \", 2)\n                else:\n                    if Tc in ['opt', 'skyline']:\n                        self.merger_model.optimize_Tc()\n                        self.logger(\"optimized Tc to %f\"%self.merger_model.Tc.y[0], 2)\n                    else:\n                        try:\n                            self.merger_model.set_Tc(Tc)\n                        except:\n                            self.logger(\"setting of coalescent time scale failed\", 1, warn=True)\n\n                self.merger_model.attach_to_tree()\n\n            # estimate a relaxed molecular clock\n            if relaxed_clock:\n                self.relaxed_clock(**relaxed_clock)\n\n            n_resolved=0\n            if resolve_polytomies:\n                # if polytomies are found, rerun the entire procedure\n                n_resolved = self.resolve_polytomies()\n                if n_resolved:\n                    self.prepare_tree()\n                    # when using the input branch length, only infer ancestral sequences\n                    if use_input_branch_length:\n                        self.infer_ancestral_sequences(**seq_kwargs)\n                    else: # otherwise reoptimize branch length while preserving branches without mutations\n                        self.optimize_sequences_and_branch_length(prune_short=False,\n                                                                  max_iter=0, **seq_kwargs)\n\n                    self.make_time_tree(clock_rate=fixed_clock_rate, time_marginal=False, **kwargs)\n                    ndiff = self.infer_ancestral_sequences('ml',**seq_kwargs)\n                else:\n                    ndiff = self.infer_ancestral_sequences('ml',**seq_kwargs)\n                    self.make_time_tree(clock_rate=fixed_clock_rate, time_marginal=False, **kwargs)\n            elif (Tc and (Tc is not None)) or relaxed_clock: # need new timetree first\n                self.make_time_tree(clock_rate=fixed_clock_rate, time_marginal=False, **kwargs)\n                ndiff = self.infer_ancestral_sequences('ml',**seq_kwargs)\n            else: # no refinements, just iterate\n                ndiff = self.infer_ancestral_sequences('ml',**seq_kwargs)\n                self.make_time_tree(clock_rate=fixed_clock_rate, time_marginal=False, **kwargs)\n\n            self.tree.coalescent_joint_LH = self.merger_model.total_LH() if Tc else 0.0\n\n            self.LH.append([self.tree.sequence_marginal_LH if seq_kwargs['marginal'] else self.tree.sequence_joint_LH,\n                            self.tree.positional_joint_LH, self.tree.coalescent_joint_LH])\n            niter+=1\n\n            if ndiff==0 & n_resolved==0:\n                self.logger(\"###TreeTime.run: CONVERGED\",0)\n                break\n\n        # if marginal reconstruction requested, make one more round with marginal=True\n        # this will set marginal_pos_LH, which to be used as error bar estimations\n        if time_marginal:\n            self.logger(\"###TreeTime.run: FINAL ROUND - confidence estimation via marginal reconstruction\", 0)\n            self.make_time_tree(clock_rate=fixed_clock_rate, time_marginal=time_marginal, **kwargs)\n\n\n\n\n    def clock_filter(self, reroot='best', n_iqd=None, plot=False):\n        '''\n        Labels outlier branches that don't seem to follow a molecular clock\n        and excludes them from subsequent the molecular clock estimate and\n        the timetree propagation\n\n        Parameters\n        ----------\n         reroot : str, None\n            Method to find the best root in the tree.\n\n         n_iqd : int, None\n            Number of iqd intervals. The outlier nodes are those which do not fall\n            into :math:`IQD\\cdot n_iqd` interval (:math:`IQD` is the interval between\n            75 and 25 percentiles)\n\n            if None, the default (3) assumed\n\n         plot : bool\n            Should plot the reults?\n\n        '''\n        if n_iqd is None:\n            n_iqd = self.n_iqd\n\n        terminals = self.tree.get_terminals()\n        if reroot:\n            self.reroot(root=reroot)\n            icpt, clock_rate = self.tree.root._alpha, self.tree.root._beta\n        else:\n            tmp_date2dist = ttutils.DateConversion.from_tree(self.tree)\n            icpt, clock_rate = tmp_date2dist.intercept, tmp_date2dist.clock_rate\n\n        res = {}\n        for node in terminals:\n            if hasattr(node, 'numdate_given') and  (node.numdate_given is not None):\n                res[node] = node.dist2root - clock_rate*np.mean(node.numdate_given) - icpt\n        residuals = np.array(res.values())\n        iqd = np.percentile(residuals,75) - np.percentile(residuals,25)\n        for node,r in res.iteritems():\n            if abs(r)>n_iqd*iqd and node.up.up is not None:\n                self.logger('TreeTime.ClockFilter: marking %s as outlier, residual %f interquartile distances'%(node.name,r/iqd), 3)\n                node.bad_branch=True\n            else:\n                node.bad_branch=False\n\n        if plot:\n            self.plot_root_to_tip()\n\n        # redo root estimation after outlier removal\n        if reroot:\n            self.reroot(root=reroot)\n\n\n    def plot_root_to_tip(self, add_internal=False, label=True, ax=None, **kwargs):\n        \"\"\"\n        Plot root-to-tip regression\n\n        Parameters\n        ----------\n\n         add_internal : bool\n            Should plot internal node positoins?\n\n         label : bool\n            Should label the plots?\n\n         ax: matplotlib axes, None\n            If not None, use the provided matplotlib axes to plot the results\n\n        Keyword Args\n        ------------\n         Additional arguments for matplotlib.pyplot.scatter function\n\n        \"\"\"\n        import matplotlib.pyplot as plt\n        tips = self.tree.get_terminals()\n        internal = self.tree.get_nonterminals()\n        if ax is None:\n            plt.figure()\n            ax=plt.subplot(111)\n        dates = np.array([np.mean(n.numdate_given) for n in tips if n.numdate_given is not None])\n        dist = np.array([n.dist2root for n in tips if n.numdate_given is not None])\n        ind = np.array([n.bad_branch for n in tips if n.numdate_given is not None])\n        # plot tips\n        ax.scatter(dates[ind], dist[ind]  , c='r', label=\"bad tips\" if label else \"\" , **kwargs)\n        ax.scatter(dates[~ind], dist[~ind], c='g', label=\"good tips\" if label else \"\", **kwargs)\n        if add_internal and hasattr(self.tree.root, \"numdate\"):\n            dates = np.array([n.numdate for n in internal])\n            dist = np.array([n.dist2root for n in internal])\n            ind = np.array([n.bad_branch for n in internal])\n            # plot internal\n            ax.scatter(dates[~ind], dist[~ind], c='b', marker='<', label=\"internal\" if label else \"\", **kwargs)\n\n        if label:\n            ax.legend(loc=2)\n        ax.set_ylabel('root-to-tip distance')\n        ax.set_xlabel('date')\n        ax.ticklabel_format(useOffset=False)\n        plt.tight_layout()\n\n\n    def reroot(self,root='best'):\n        \"\"\"\n        Find best root and re-root the tree to the new root\n\n        Parameters\n        ----------\n\n         root : str\n            Which method should be used to find the best root. Available methods are:\n\n            :code:`best` - maximize root-to-tip regression coefficient\n\n            :code:`oldest` - choose the oldest node\n\n            :code:`<node_name>` - reroot to the node with name :code:`<node_name>`\n\n            :code:`[<node_name1>, <node_name2>, ...]` - reroot to the MRCA of these nodes\n        \"\"\"\n        self.logger(\"TreeTime.reroot: with method or node: %s\"%root,1)\n        for n in self.tree.find_clades():\n            n.branch_length=n.mutation_length\n        from Bio import Phylo\n        if isinstance(root,Phylo.BaseTree.Clade):\n            new_root = root\n        elif isinstance(root, list):\n            new_root = self.tree.common_ancestor(*root)\n        elif root in self._leaves_lookup:\n            new_root = self._leaves_lookup[root]\n        elif root=='oldest':\n            new_root = sorted([n for n in self.tree.get_terminals()\n                               if n.numdate_given is not None],\n                               key=lambda x:np.mean(x.numdate_given))[0]\n        elif root=='best':\n            new_root = self.reroot_to_best_root(criterium='residual')\n        elif root=='rsq':\n            new_root = self.reroot_to_best_root(criterium='rsq')\n        elif root=='residual':\n            new_root = self.reroot_to_best_root(criterium='residual')\n        elif root=='min_dev':\n            new_root = self.reroot_to_best_root(criterium='min_dev')\n        else:\n            self.logger('TreeTime.reroot -- WARNING: unsupported rooting mechanisms or root not found',2,warn=True)\n            return\n\n        self.logger(\"TreeTime.reroot: Tree is being re-rooted to node \"\n                    +('new_node' if new_root.name is None else new_root.name), 2)\n        if isinstance(root, list):\n            #this forces a bifurcating root, as we want. Branch lengths will be reoptimized anyway.\n            #(Without outgroup_branch_length, gives a trifurcating root, but this will mean\n            #mutations may have to occur multiple times.)\n            self.tree.root_with_outgroup(new_root, outgroup_branch_length=new_root.branch_length/2)\n        else:\n            self.tree.root_with_outgroup(new_root)\n       # new nodes are produced when rooting with a terminal node, copy this clock info\n\n        if new_root.is_terminal():\n            if hasattr(new_root, \"_alpha\"):\n                self.tree.root._alpha = new_root._alpha\n            if hasattr(new_root, \"_beta\"):\n                self.tree.root._beta = new_root._beta\n            if hasattr(new_root, \"_R2\"):\n                self.tree.root._R2 = new_root._R2\n            if hasattr(new_root, \"_residual\"):\n                self.tree.root._residual = new_root._residual\n\n        self.tree.root.branch_length = self.one_mutation\n        for n in self.tree.find_clades():\n            n.mutation_length=n.branch_length\n        self.tree.root.numdate_given = None\n        # set root.gamma bc root doesn't have a branch_length_interpolator but gamma is needed\n        if not hasattr(self.tree.root, 'gamma'):\n            self.tree.root.gamma = 1.0\n        self.prepare_tree()\n\n\n    def resolve_polytomies(self, merge_compressed=False, rerun=True):\n        \"\"\"\n        Resolve the polytomies on the tree.\n        The function scans the tree, resolves polytomies in case there are any,\n        and re-optimizes the tree with new topology. Note that polytomies are only\n        resolved if that would result in higher likelihood. Sometimes, stretching\n        two or more branches that carry several mutations are less costly than\n        an additional branch with zero mutations (long branches are not stiff,\n        short branches are.)\n\n        Parameters\n        ----------\n         merge_compressed : bool\n            Whether to keep compressed branches as polytomies or\n            return a strictly binary tree.\n\n        \"\"\"\n        self.logger(\"TreeTime.resolve_polytomies: resolving multiple mergers...\",1)\n\n        poly_found=0\n        for n in self.tree.find_clades():\n            if len(n.clades) > 2:\n                prior_n_clades = len(n.clades)\n                self._poly(n, merge_compressed)\n                poly_found+=prior_n_clades - len(n.clades)\n\n        obsolete_nodes = [n for n in self.tree.find_clades() if len(n.clades)==1 and n.up is not None]\n        for node in obsolete_nodes:\n            self.logger('TreeTime.resolve_polytomies: remove obsolete node '+node.name,4)\n            if node.up is not None:\n                self.tree.collapse(node)\n\n        if poly_found:\n            self.logger('TreeTime.resolve_polytomies: introduces %d new nodes'%poly_found,3)\n        else:\n            self.logger('TreeTime.resolve_polytomies: No more polytomies to resolve',3)\n        return poly_found\n\n\n    def _poly(self, clade, merge_compressed, verbose=1):\n\n        \"\"\"\n        Function to resolve polytomies for a given parent node. If the\n        number of the direct decendants is less than three (not a polytomy), does\n        nothing. Otherwise, for each pair of nodes, assess the possible LH increase\n        which could be gained by merging the two nodes. The increase in the LH is\n        basically the tradeoff between the gain of the LH due to the changing the\n        branch lenghts towards the optimal values and the decrease due to the\n        introduction of the new branch with zero optimal length.\n        \"\"\"\n\n        from branch_len_interpolator import BranchLenInterpolator\n        from Bio import Phylo\n\n        zero_branch_slope = self.gtr.mu*self.seq_len\n\n        def _c_gain(t, n1, n2, parent):\n            \"\"\"\n            cost gain if nodes n1, n2 are joined and their parent is placed at time t\n            cost gain = (LH loss now) - (LH loss when placed at time t)\n            \"\"\"\n            cg2 = n2.branch_length_interpolator(parent.time_before_present - n2.time_before_present) - n2.branch_length_interpolator(t - n2.time_before_present)\n            cg1 = n1.branch_length_interpolator(parent.time_before_present - n1.time_before_present) - n1.branch_length_interpolator(t - n1.time_before_present)\n            cg_new = - zero_branch_slope * (parent.time_before_present - t) # loss in LH due to the new branch\n            return -(cg2+cg1+cg_new)\n\n        def cost_gain(n1, n2, parent):\n            \"\"\"\n            cost gained if the two nodes would have been connected.\n            \"\"\"\n            try:\n                cg = sciopt.minimize_scalar(_c_gain,\n                    bounds=[max(n1.time_before_present,n2.time_before_present), parent.time_before_present],\n                    method='Bounded',args=(n1,n2, parent))\n                return cg['x'], - cg['fun']\n            except:\n                self.logger(\"TreeTime._poly.cost_gain: optimization of gain failed\", 3, warn=True)\n                return parent.time_before_present, 0.0\n\n\n        def merge_nodes(source_arr, isall=False):\n            mergers = np.array([[cost_gain(n1,n2, clade) if i1<i2 else (0.0,-1.0)\n                                    for i1,n1 in enumerate(source_arr)]\n                                for i2, n2 in enumerate(source_arr)])\n            LH = 0\n            while len(source_arr) > 1 + int(isall):\n                # max possible gains of the cost when connecting the nodes:\n                # this is only a rough approximation because it assumes the new node positions\n                # to be optimal\n                new_positions = mergers[:,:,0]\n                cost_gains = mergers[:,:,1]\n                # set zero to large negative value and find optimal pair\n                np.fill_diagonal(cost_gains, -1e11)\n                idxs = np.unravel_index(cost_gains.argmax(),cost_gains.shape)\n                if (idxs[0] == idxs[1]) or cost_gains.max()<0:\n                    self.logger(\"TreeTime._poly.merge_nodes: node is not fully resolved \"+clade.name,4)\n                    return LH\n\n                n1, n2 = source_arr[idxs[0]], source_arr[idxs[1]]\n                LH += cost_gains[idxs]\n\n                new_node = Phylo.BaseTree.Clade()\n\n                # fix positions and branch lengths\n                new_node.time_before_present = new_positions[idxs]\n                new_node.branch_length = clade.time_before_present - new_node.time_before_present\n                new_node.clades = [n1,n2]\n                n1.branch_length = new_node.time_before_present - n1.time_before_present\n                n2.branch_length = new_node.time_before_present - n2.time_before_present\n\n                # set parameters for the new node\n                new_node.up = clade\n                n1.up = new_node\n                n2.up = new_node\n                new_node.cseq = clade.cseq\n                self._store_compressed_sequence_to_node(new_node)\n\n                new_node.mutations = []\n                new_node.mutation_length = 0.0\n                new_node.branch_length_interpolator = BranchLenInterpolator(new_node, self.gtr, one_mutation=self.one_mutation)\n                clade.clades.remove(n1)\n                clade.clades.remove(n2)\n                clade.clades.append(new_node)\n                self.logger('TreeTime._poly.merge_nodes: creating new node as child of '+clade.name,3)\n                self.logger(\"TreeTime._poly.merge_nodes: Delta-LH = \" + str(cost_gains[idxs].round(3)), 3)\n\n                # and modify source_arr array for the next loop\n                if len(source_arr)>2: # if more than 3 nodes in polytomy, replace row/column\n                    for ii in np.sort(idxs)[::-1]:\n                        tmp_ind = np.arange(mergers.shape[0])!=ii\n                        mergers = mergers[tmp_ind].swapaxes(0,1)\n                        mergers = mergers[tmp_ind].swapaxes(0,1)\n\n                    source_arr.remove(n1)\n                    source_arr.remove(n2)\n                    new_gains = np.array([[cost_gain(n1,new_node, clade) for n1 in source_arr]])\n                    mergers = np.vstack((mergers, new_gains)).swapaxes(0,1)\n\n                    source_arr.append(new_node)\n                    new_gains = np.array([[cost_gain(n1,new_node, clade) for n1 in source_arr]])\n                    mergers = np.vstack((mergers, new_gains)).swapaxes(0,1)\n                else: # otherwise just recalculate matrix\n                    source_arr.remove(n1)\n                    source_arr.remove(n2)\n                    source_arr.append(new_node)\n                    mergers = np.array([[cost_gain(n1,n2, clade) for n1 in source_arr]\n                                       for n2 in source_arr])\n\n            return LH\n\n        stretched = [c for c  in clade.clades if c.mutation_length < c.clock_length]\n        compressed = [c for c in clade.clades if c not in stretched]\n\n        if len(stretched)==1 and merge_compressed==False:\n            return 0.0\n\n        LH = merge_nodes(stretched, isall=len(stretched)==len(clade.clades))\n        if merge_compressed and len(compressed)>1:\n            LH += merge_nodes(compressed, isall=len(compressed)==len(clade.clades))\n\n        return LH\n\n\n    def print_lh(self, joint=True):\n        \"\"\"\n        Print the total likelihood of the tree given the constrained leaves\n\n        Parameters\n        ----------\n\n         joint : bool\n            Whether joint or marginal LH should be printed\n\n        \"\"\"\n        try:\n            u_lh = self.tree.unconstrained_sequence_LH\n            if joint:\n                s_lh = self.tree.sequence_joint_LH\n                t_lh = self.tree.positional_joint_LH\n                c_lh = self.tree.coalescent_joint_LH\n            else:\n                s_lh = self.tree.sequence_marginal_LH\n                t_lh = self.tree.positional_marginal_LH\n                c_ls = 0\n\n            print (\"###  Tree Log-Likelihood  ###\\n\"\n                \" Sequence log-LH without constraints: \\t%1.3f\\n\"\n                \" Sequence log-LH with constraints:    \\t%1.3f\\n\"\n                \" TreeTime sequence log-LH:            \\t%1.3f\\n\"\n                \" Coalescent log-LH:                   \\t%1.3f\\n\"\n               \"#########################\"%(u_lh, s_lh,t_lh, c_lh))\n        except:\n            print(\"ERROR. Did you run the corresponding inference (joint/marginal)?\")\n\n\n    def relaxed_clock(self, slack=None, coupling=None, **kwargs):\n        \"\"\"\n        Allow the mutation rate to vary on the tree (relaxed molecular clock).\n        Changes of the mutation rates from one branch to another are penalized.\n        In addition, deviation of the mutation rate from the mean rate are\n        penalized.\n\n        Parameters\n        ----------\n         slack : float\n            Maximum change in substitution rate between parent and child nodes\n\n         coupling : float\n            Maximum difference in substitution rates in sibling nodes\n\n        \"\"\"\n        if slack is None: slack=ttconf.MU_ALPHA\n        if coupling is None: coupling=ttconf.MU_BETA\n        self.logger(\"TreeTime.relaxed_clock: slack=%f, coupling=%f\"%(slack, coupling),2)\n\n        c=1.0/self.one_mutation\n        for node in self.tree.find_clades(order='postorder'):\n            opt_len = node.mutation_length\n\n            # opt_len \\approx 1.0*len(node.mutations)/node.profile.shape[0] but calculated via gtr model\n            # contact term: stiffness*(g*bl - bl_opt)^2 + slack(g-1)^2 =\n            #               (slack+bl^2) g^2 - 2 (bl*bl_opt+1) g + C= k2 g^2 + k1 g + C\n            node._k2 = slack + c*node.branch_length**2/(opt_len+self.one_mutation)\n            node._k1 = -2*(c*node.branch_length*opt_len/(opt_len+self.one_mutation) + slack)\n            # coupling term: \\sum_c coupling*(g-g_c)^2 + Cost_c(g_c|g)\n            # given g, g_c needs to be optimal-> 2*coupling*(g-g_c) = 2*child.k2 g_c  + child.k1\n            # hence g_c = (coupling*g - 0.5*child.k1)/(coupling+child.k2)\n            # substituting yields\n            for child in node.clades:\n                denom = coupling+child._k2\n                node._k2 += coupling*(1.0-coupling/denom)**2 + child._k2*coupling**2/denom**2\n                node._k1 += (coupling*(1.0-coupling/denom)*child._k1/denom \\\n                            - coupling*child._k1*child._k2/denom**2 \\\n                            + coupling*child._k1/denom)\n\n        for node in self.tree.find_clades(order='preorder'):\n            if node.up is None:\n                node.gamma =- 0.5*node._k1/node._k2\n            else:\n                if node.up.up is None:\n                    g_up = node.up.gamma\n                else:\n                    g_up = node.up.branch_length_interpolator.gamma\n                node.branch_length_interpolator.gamma = (coupling*g_up - 0.5*node._k1)/(coupling+node._k2)\n\n###############################################################################\n### rerooting\n###############################################################################\n    def find_best_root_and_regression(self, criterium='rsq'):\n        \"\"\"\n        Find the best root for the tree in linear time, given the timestamps of\n        the leaves. The branch lengths should be optimized prior to the run;\n        the terminal nodes should have the timestamps assigned as numdate_given\n        attribute.\n        \"\"\"\n        sum_ti =  np.sum([np.mean(node.numdate_given)*node.count for node in self.tree.get_terminals() if (not node.bad_branch)])\n        sum_ti2 = np.sum([np.mean(node.numdate_given)**2*node.count for node in self.tree.get_terminals() if (not node.bad_branch)])\n        N = 1.0*np.sum([node.count for node in self.tree.get_terminals() if not node.bad_branch])\n        tip_count = 1.0*np.sum([1.0 for node in self.tree.get_terminals() if not node.bad_branch])\n        if tip_count<2:\n            self.logger(\"****ERROR: TreeTime.find_best_root_and_regression: need at least two dates to reroot!\", 0, warn=True)\n            self.logger(\"****ERROR: only %d tips have valid dates!\"%N, 0, warn=True)\n            return selt.tree.root, np.nan, np.nan\n\n        Ninv = 1.0/N\n        time_variance = (N*sum_ti2 - sum_ti**2)*Ninv**2\n\n        #  fill regression terms for one of the two subtrees\n        for node in self.tree.find_clades(order='postorder'):  # children first, msg to parents\n            if node.is_terminal():  # inititalize the leaves\n                #  will not rely on the standard func - count terminals directly\n                node._st_n_leaves = 0 if node.bad_branch else node.count\n                node._st_di = 0.0\n                node._st_diti = 0.0\n                node._st_di2 = 0.0\n\n                if node.bad_branch:\n                    node._st_ti = 0\n                else:\n                    node._st_ti = np.mean(node.numdate_given)*node.count\n\n                node._ti = sum_ti\n            else:\n                #  for non-terminal nodes,\n                node._st_ti = np.sum([k._st_ti for k in node.clades])\n                node._st_n_leaves = np.sum([k._st_n_leaves for k in node.clades])\n                node._st_di   = np.sum([k._st_di + k._st_n_leaves*k.branch_length for k in node.clades])\n                node._st_diti = np.sum([k._st_diti + k.branch_length*k._st_ti for k in node.clades])\n                node._st_di2  = np.sum([k._st_di2 + 2*k._st_di*k.branch_length + k._st_n_leaves*k.branch_length**2\n                                       for k in node.clades])\n                node._ti = sum_ti\n                node.bad_branch = np.all([x.bad_branch for x in node])\n\n        best_root = self.tree.root\n        best_root_any = self.tree.root\n        for node in self.tree.find_clades(order='preorder'):  # root first\n\n            if node.up is None:\n                # assign the values for the root node\n                node._di   = node._st_di\n                node._diti = node._st_diti\n                node._di2  = node._st_di2\n\n                dist_variance = (N*node._di2 - node._di**2)*(Ninv**2)\n                disttime_cov = (N*node._diti - sum_ti*node._di)*(Ninv**2)\n                time_variance = time_variance\n\n                node._beta = disttime_cov/time_variance\n                node._alpha = (node._di - node._beta*sum_ti)/N\n                node._residual = (node._di2 - 2*node._beta*node._diti - 2*node._alpha*node._di\n                                   + node._beta**2*sum_ti2 + 2*node._alpha*node._beta*sum_ti + node._alpha**2*N)\n\n                node._R2 = disttime_cov**2/(time_variance*dist_variance)\n                node._R2_delta_x = 0.0 # there is no branch to move the root\n            elif node.bad_branch:\n                node._beta = np.nan\n                node._alpha = np.nan\n                node._R2 = 0.0\n                node._R2_delta_x = 0.0\n                node._residual = np.inf\n\n            elif criterium=='rsq': # calculate the r^2 of the root to tip regression and pick the best intermediate position on the branch\n                #  NOTE order of these computation matters\n                n_up = N - node._st_n_leaves\n                n_down = node._st_n_leaves\n                L = node.branch_length\n                node._di = node.up._di + (n_up-n_down)*L\n                node._di2 = (node.up._di2 + 2*L*node.up._di\n                            - 4*(L*(node._st_di + n_down*L))\n                            + N*L**2)\n                node._diti = node.up._diti + L*(sum_ti - 2*node._st_ti)\n\n\n                ## Express Node's sum_Di as the function of parent's sum_Di\n                # and **displacement from parent's node x** :\n                # sum_Di = A1 + A2 * x\n                A1 = node.up._di\n                A2 = n_up - n_down\n\n                ## Express Node's sum_Di**2 as the function of parent's params\n                # and **displacement from parent's node x** :\n                # sum_Di2 = B1 + B2 * x + B3 * x**2\n                B1 = node.up._di2\n                B2 = 2 * (node.up._di - 2 * node._st_di - 2 * L * n_down )\n                B3 = N\n\n                ## Express Node's sum_DiTi as the function of parent's params\n                # and **displacement from parent's node x** :\n                # sum_DiTi = C1 + C2 * x\n                C1 = node.up._diti\n                C2 = sum_ti - 2 * node._st_ti\n\n                ## Substituting Ai, Bi, Ci to the expression for R2, and\n                ## making all the algebra, we get the R2 as the function of the\n                ## displacement from the parent's node x:\n                # R2(x) = CONST * (alpha * x**2 + beta * x+ gamma) / (mu * x**2 + nu * x + delta)\n                # Expressions for alpha, beta, etc through Ai, Bi, Ci:\n                alpha = (N * C2 - sum_ti * A2)**2\n                beta = 2 * (N*C2 - sum_ti*A2) * (N*C1 - sum_ti*A1)\n                gamma = (N*C1 - sum_ti*A1)**2\n                mu = N * B3 - A2**2\n                nu = N * B2 - 2 * A1 * A2\n                delta = N * B1 - A1**2\n\n                # Search for the maximum of R2 in the middle of the branch.\n                # Eq: dR2/dx = 0 -> square equation:\n                # x**2*(alpha*nu - beta *  mu) + 2x*(alpha*delta-mu*gamma) + (beta*delta - nu*gamma) = 0\n                # look for the root(s):\n                # Determinant is\n                D2 =  (alpha * delta - mu * gamma) ** 2 - (alpha * nu - beta * mu) * (beta * delta - nu * gamma)\n\n                if D2 < 0:\n                    # somehow there is no extremum for the R2(x) function\n                    x1 = -1.0 # any arbitrary value out of range [0, L], see below\n                    x2 = -1.0\n                else:\n                    # actual roots - the extrema for the R2(x) function\n                    if np.abs(alpha * nu - beta * mu)>0:\n                        x1 = (-1 * (alpha * delta - mu * gamma) + D2**0.5) / (alpha * nu - beta * mu)\n                        x2 = (-1 * (alpha * delta - mu * gamma) - D2**0.5) / (alpha * nu - beta * mu)\n                    else:\n                        x1 = -(beta*delta - nu*gamma)/(alpha * delta - mu * gamma)\n                        x2 = x1\n\n                # possible positions, where the new root can possibly be located\n                # (restrict to the branch length)\n                max_points = [k for k in (x1,x2,L) if k >= 0 and k <= L]\n                # values of the R2 at these positions\n                R2s = [(alpha * x**2 + beta * x + gamma) / (mu * x**2 + nu * x + delta) / time_variance / N**2 for x in max_points]\n                # choose the best R2\n                node._R2 = np.max(R2s)\n                # and set the position for the best R2 value\n                node._R2_delta_x = L - max_points[np.argmax(R2s)]\n\n                # for this position, define the clock_rate and intercept:\n                node._beta = ((L - node._R2_delta_x) * (N * C2 - sum_ti * A2) + (N*C1-sum_ti*A1)) / time_variance / N**2\n                node._alpha = (L - node._R2_delta_x) * A2 / N  + (A1 - node._beta * sum_ti) / N\n            elif criterium in ['residual', 'min_dev']: # calculate the squared residuals and minimize as rooting criterium\n                L = node.branch_length\n                # number of nodes descendent and outgrouping this node\n                n_up = N - node._st_n_leaves\n                n_down = node._st_n_leaves\n                # sum of branch length of the descendent tree and the outgrouping one\n                node._di = node.up._di + (n_up-n_down)*L\n                nd_down = node._st_di\n                nd_up = node._di - node._st_di\n                # sum of times of descendent tips and outgrouping ones\n                nt_down = node._st_ti\n                nt_up = sum_ti - node._st_ti\n\n                # sum of squared branch length of the descendent tree and the outgrouping one\n                node._di2 = (node.up._di2 + 2*L*node.up._di\n                            - 4*(L*(node._st_di + n_down*L))\n                            + N*L**2)\n                nd2_down = node._st_di2\n                nd2_up = node._di2 - node._st_di2\n\n                # sum of timexbranch length of the descendent tree and the outgrouping one\n                node._diti = node.up._diti + L*(sum_ti - 2*node._st_ti)\n                ndt_down = node._st_diti\n                ndt_up = node._diti - node._st_diti\n\n                disttime_cov = (N*node._diti - sum_ti*node._di)*(Ninv**2)\n\n                # decompose expression for alpha and beta into parts independent and linear in epsilon\n                # where epsilon is the shift in root position along the branch\n                beta_0 = disttime_cov/time_variance\n                b = L*(nt_down - nt_up - (n_down-n_up)*sum_ti*Ninv)*Ninv/time_variance\n                alpha_0 = (node._di - beta_0*sum_ti)*Ninv\n                a = (-b*sum_ti + L*(n_down-n_up))*Ninv\n                eps = -(((nd_down - beta_0*nt_down - n_down*alpha_0) - (nd_up - beta_0*nt_up - n_up*alpha_0))/\n                      ((n_down*L - b*nt_down  - a*n_down) - (-n_up*L - b*nt_up - a*n_up)))\n\n                # only shifts between 0 and 1 are admissible (where 0 is the node itself and 1 is the parent)\n                eps = min(1,max(0,eps))\n                beta = beta_0 + eps*b\n                alpha = alpha_0 + eps*a\n\n                # calculate the residual and assign the regression coefficients\n                node._residual = (node._di2 - 2*beta*node._diti - 2*alpha*node._di\n                                   + beta**2*sum_ti2 + 2*alpha*beta*sum_ti + alpha**2*N)\n                node._residual += N*(L*eps)**2\n                node._residual += 2*eps*L*(nd_down - beta*nt_down - n_down*alpha) - 2*eps*L*(nd_up - beta*nt_up - n_up*alpha)\n                node._alpha = alpha\n                node._beta = beta\n                node._R2_delta_x = eps*L\n            else:\n                self.logger(\"TreeTime.find_best_root_and_regression: unknown criterium\",0)\n\n            if criterium=='rsq':\n                if node.up is None:\n                    self.logger(\"TreeTime.find_best_root_and_regression: Initial root: R2:%f\\tclock_rate:%.3e\"%(best_root._R2, best_root._beta),3)\n                if  node._R2 > best_root_any._R2:\n                    best_root_any = node\n                if  (node._R2 > best_root._R2 and node._beta>0) or best_root._beta<0:\n                    best_root = node\n                    self.logger(\"TreeTime.find_best_root_and_regression: Better root found: R2:%f\\tclock_rate:%.3e\\tbranch_displacement:%f\"\n                            %(best_root._R2, best_root._beta, (best_root._R2_delta_x) / ( best_root.branch_length + self.one_mutation)),4)\n            elif criterium in ['residual', 'min_dev']:\n                if node.up is None:\n                    self.logger(\"TreeTime.find_best_root_and_regression: Initial root: residual:%.3e\\tclock_rate:%.3e\"%(best_root._residual, best_root._beta),3)\n                if  node._residual < best_root_any._residual:\n                    best_root_any = node\n                if (node._residual < best_root._residual and node._beta>0) or best_root._beta<0:\n                    best_root = node\n                    self.logger(\"TreeTime.find_best_root_and_regression: Better root found: residual:%.3e\\tclock_rate:%.3e\\tbranch_displacement:%f\"\n                            %(best_root._residual, best_root._beta, (best_root._R2_delta_x) / ( best_root.branch_length + self.one_mutation)),4)\n\n\n        if criterium=='rsq':\n            if (best_root_any._R2 > best_root._R2):\n                self.logger(\"WARNING: TreeTime.find_best_root_and_regression: optimal regression has negative rate: R2:%f\\tclock_rate:%.3e\"\n                        %(best_root_any._R2, best_root_any._beta), 1)\n            self.logger(\"TreeTime.find_best_root_and_regression: Best root: R2:%f\\tclock_rate:%.3e\\tbranch_displacement:%f\"\n                        %(best_root._R2, best_root._beta, (best_root._R2_delta_x) / ( best_root.branch_length + 0.001*self.one_mutation)),3)\n        elif criterium=='residual':\n            if (best_root_any._residual < best_root._residual):\n                self.logger(\"WARNING: TreeTime.find_best_root_and_regression: optimal regression has negative rate: residual:%.3e\\tclock_rate:%.3e\"\n                        %(best_root_any._residual, best_root_any._beta), 1)\n            self.logger(\"TreeTime.find_best_root_an_R2_delta_xd_regression: Best root: residual:%.3e\\tclock_rate:%.3e\\tbranch_displacement:%f\"\n                        %(best_root._residual, best_root._beta, (best_root._R2_delta_x) / ( best_root.branch_length + 0.001*self.one_mutation)),3)\n        elif criterium=='min_dev':\n            if (best_root_any._residual < best_root._residual):\n                self.logger(\"WARNING: TreeTime.find_best_root_and_regression: optimal regression has negative rate\",1)\n                best_root = best_root_any\n            self.logger(\"TreeTime.find_best_root_an_R2_delta_xd_regression: Best root: residual:%.3e\\tclock_rate:%.3e\\tbranch_displacement:%f\"\n                        %(best_root._residual, best_root._beta, (best_root._R2_delta_x) / ( best_root.branch_length + 0.001*self.one_mutation)),3)\n\n        return best_root, best_root._alpha, best_root._beta\n\n\n    def reroot_to_best_root(self,infer_gtr = False, criterium='rsq', **kwarks):\n        '''\n        determine the node that, when the tree is rooted on this node, results\n        in the best regression of temporal constraints and root to tip distances\n\n        Parameters\n        ----------\n\n         infer_gtr : bool\n            Should infer new GTR model after re-root?\n\n        '''\n        from Bio import Phylo\n        self.logger(\"TreeTime.reroot_to_best_root: searching for the best root position...\",2)\n        best_root, a, b = self.find_best_root_and_regression(criterium=criterium)\n        # first, re-root the tree\n\n        if hasattr(best_root, \"_R2_delta_x\") and  best_root._R2_delta_x > 0 and best_root.up is not None:\n\n            # create new node in the branch and root the tree to it\n            new_node = Phylo.BaseTree.Clade()\n\n            # insert the new node in the middle of the branch\n            # by simple re-wiring the links on the both sides of the branch\n            # and fix the branch lengths\n            new_node.branch_length = best_root.branch_length - best_root._R2_delta_x\n            new_node.up = best_root.up\n            new_node._alpha = a\n            new_node._beta = b\n            new_node.clades = [best_root]\n            if hasattr(best_root, \"_R2\"):\n                new_node._R2 = best_root._R2\n            if hasattr(best_root, \"_residual\"):\n                new_node._residual = best_root._residual\n            new_node.up.clades = [k if k != best_root else new_node\n                                  for k in best_root.up.clades]\n\n            best_root.branch_length = best_root._R2_delta_x\n            best_root.up = new_node\n            self.logger(\"TreeTime.reroot_to_best_root:\"\n                        \" branch length of children of new root:\"\n                        \" %.3e, %.3e\"%(best_root.branch_length,\n                                       new_node.branch_length),2)\n            return new_node\n        else:\n            # simply use the existing node as the new root\n            return best_root\n\n\ndef plot_vs_years(tt, years = 1, ax=None, confidence=None, ticks=True, **kwargs):\n    '''\n    converts branch length to years and plots the time tree on a time axis.\n    Args:\n        tt:     treetime object after a time tree is inferred\n        years:  width of shaded boxes indicating blocks of years, default 1\n        ax:     axis object. will create new axis of none specified\n        confidence:     draw confidence intervals. This assumes that marginal\n                        time tree inference was run\n        **kwargs:   arbitrary kew word arguments that are passed down to Phylo.draw\n    '''\n    import matplotlib.pyplot as plt\n    tt.branch_length_to_years()\n    if ax is None:\n        fig = plt.figure()\n        ax = plt.subplot(111)\n    # draw tree\n    if \"label_func\" not in kwargs:\n        nleafs = tt.tree.count_terminals()\n        kwargs[\"label_func\"] = lambda x:x.name if (x.is_terminal() and nleafs<30) else \"\"\n    Phylo.draw(tt.tree, axes=ax, **kwargs)\n\n    # set axis labels\n    offset = tt.tree.root.numdate - tt.tree.root.branch_length\n    xticks = ax.get_xticks()\n    dtick = xticks[1]-xticks[0]\n    shift = offset - dtick*(offset//dtick)\n    tick_vals = [x+offset-shift for x in xticks]\n    ax.set_xticks(xticks - shift)\n    ax.set_xticklabels(map(str, tick_vals))\n    ax.set_xlabel('year')\n    ax.set_ylabel('')\n    ax.set_xlim((0,np.max([n.numdate for n in tt.tree.get_terminals()])+2-offset))\n\n    # put shaded boxes to delineate years\n    if years:\n        ylim = ax.get_ylim()\n        xlim = ax.get_xlim()\n        if type(years) in [int, float]:\n            dyear=years\n        from matplotlib.patches import Rectangle\n        for yi,year in enumerate(np.arange(tick_vals[0], tick_vals[-1],dyear)):\n            pos = year - offset\n            r = Rectangle((pos, ylim[1]-5),\n                          dyear, ylim[0]-ylim[1]+10,\n                          facecolor=[0.7+0.1*(1+yi%2)] * 3,\n                          edgecolor=[1,1,1])\n            ax.add_patch(r)\n            if year in tick_vals and pos>xlim[0] and pos<xlim[1] and ticks:\n                ax.text(pos,ylim[0]-0.04*(ylim[1]-ylim[0]),str(int(year)),\n                        horizontalalignment='center')\n        ax.set_axis_off()\n\n    # add confidence intervals to the tree graph -- grey bars\n    if confidence:\n        ttutils.tree_layout(tt.tree)\n        if not hasattr(tt.tree.root, \"marginal_inverse_cdf\"):\n            print(\"marginal time tree reconstruction required for confidence intervals\")\n        elif len(confidence)==2:\n            cfunc = tt.get_confidence_interval\n        elif len(confidence)==1:\n            cfunc = tt.get_max_posterior_region\n        else:\n            print(\"confidence needs to be either a float (for max posterior region) or a two numbers specifying lower and upper bounds\")\n            return\n\n        for n in tt.tree.find_clades():\n            pos = cfunc(n, confidence)\n            ax.plot(pos-offset, np.ones(len(pos))*n.ypos, lw=3, c=(0.5,0.5,0.5))\n\n\ndef treetime_to_newick(tt, outf):\n    Phylo.write(tt.tree, outf, 'newick')\n\n\nif __name__==\"__main__\":\n    pass\n\n\n", "meta": {"hexsha": "5a18c3e7c5ee66bce42b1c92a29519d66888da48", "size": 47387, "ext": "py", "lang": "Python", "max_stars_repo_path": "titer_model/implementation-nextstrain-augur/treetime_augur/treetime/treetime.py", "max_stars_repo_name": "blab/dengue", "max_stars_repo_head_hexsha": "5eacc47fbd77c59e7342d5be4aa81f7d3b4ff0bf", "max_stars_repo_licenses": ["CC-BY-4.0", "MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-03-31T22:03:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T21:04:24.000Z", "max_issues_repo_path": "titer_model/implementation-nextstrain-augur/treetime_augur/treetime/treetime.py", "max_issues_repo_name": "emmahodcroft/dengue-antigenic-dynamics", "max_issues_repo_head_hexsha": "5eacc47fbd77c59e7342d5be4aa81f7d3b4ff0bf", "max_issues_repo_licenses": ["CC-BY-4.0", "MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-10-12T02:13:10.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-24T02:44:53.000Z", "max_forks_repo_path": "titer_model/implementation-nextstrain-augur/treetime_augur/treetime/treetime.py", "max_forks_repo_name": "emmahodcroft/dengue-antigenic-dynamics", "max_forks_repo_head_hexsha": "5eacc47fbd77c59e7342d5be4aa81f7d3b4ff0bf", "max_forks_repo_licenses": ["CC-BY-4.0", "MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-09-10T23:14:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-27T20:57:34.000Z", "avg_line_length": 46.7327416174, "max_line_length": 160, "alphanum_fraction": 0.5793994133, "include": true, "reason": "import numpy,from scipy", "num_tokens": 11276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.2974699363766585, "lm_q1q2_score": 0.19375849015083815}}
{"text": "''' Class to convert Mimosa26 raw data.\n\nGeneral structure of Mimosa26 raw data (32 bit words):\n - First 8 bits are always 0x20 (Mimosa26 HEADER)\n - Next 4 bits are plane number 1 - 6 (plane identifier)\n - Next 2 bits always zero\n - Next two bits contain: data loss flag and frame start flag\n - Rest of 16 bits are actual data words\n\nThe raw data structure of Mimosa26 data looks as follows:\n - Frame header HIGH and LOW (contains timestamp, generated from R/O) [word index 0 + 1]\n - Frame number HIGH and LOW (frame number of Mimosa26) [word index 2 + 3]\n - Frame length HIGH and LOW (number of Mimosa26) [word index 4 + 5]\n - Hit data (column and row of hit pixel)\n - ...\n - ...\n - Frame trailer HIGH and LOW (indicates end of Mimosa26 frame) [word index 6 + 7]\n\n'''\nimport numba\nfrom numba import njit\nimport numpy as np\n\n\nMIMOSA_FRAME_CYCLE = 115.2  # us\nMIMOSA_FREQ = 40  # MHz\nN_ROWS_MIMOSA = 576  # Number of rows\nFRAME_UNIT_CYCLE = int(MIMOSA_FRAME_CYCLE * MIMOSA_FREQ)  # = 4608, time for one frame in units of 40 MHz clock cylces\nROW_UNIT_CYCLE = int(MIMOSA_FRAME_CYCLE * MIMOSA_FREQ / N_ROWS_MIMOSA)  # = 8, time to read one row in units of 40 MHz clock cycles\nTIMING_OFFSET = -112  # Correct for offset between M26 40 MHz clock and 40 MHz from R/O system. Offset determined by maximum correlation between the time reference and Mimosa26 telescope.\nMAX_BUFFER_TIME_SLIP = 5  # max. time (in seconds) for storing hits in buffer before they get removed if no trigger appears\nDEFAULT_PYMOSA_M26_HEADER_IDS = [1, 2, 3, 4, 5, 6]  # Default header IDs for the Mimosa26 data generated by the pymosa software. The header IDs are set in the pymosa readout software.\n\nhits_dtype = np.dtype([\n    ('plane', '<u1'),\n    ('event_number', '<i8'),\n    ('trigger_number', '<i8'),\n    ('trigger_time_stamp', '<i8'),\n    ('row_time_stamp', '<i8'),\n    ('frame_id', '<i8'),\n    ('column', '<u2'),\n    ('row', '<u2'),\n    ('event_status', '<u4')])\n\ntelescope_data_dtype = np.dtype([\n    ('plane', '<u1'),\n    ('time_stamp', '<i8'),\n    ('frame_id', '<i8'),\n    ('column', '<u2'),\n    ('row', '<u2'),\n    ('frame_status', '<u4')])\n\ntrigger_data_dtype = np.dtype([\n    ('event_number', '<i8'),\n    ('trigger_number', '<i8'),\n    ('trigger_time_stamp', '<i8'),\n    ('trigger_status', '<u4')])\n\n# Error codes\nTRIGGER_NUMBER_ERROR = 0x00000001  # Trigger number has not increased by one\nNO_TRIGGER_WORD_ERROR = 0x00000002  # Event has no trigger word associated\nTRIGGER_TIMESTAMP_OVERFLOW = 0x00000004  # Indicating the overflow of the trigger timestamp\nTRIGGER_NUMBER_OVERFLOW = 0x00000008  # Indicating the overflow of the trigger number\nDATA_ERROR = 0x00000010  # Indicating any occurrence of data errors in the Momosa26 protocol (e.g., invalid column/row, invalid data length, data loss)\nTIMESTAMP_OVERFLOW = 0x00000020  # Indicating the overflow of the Mimosa26 timestamp\nFRAME_ID_OVERFLOW = 0x00000040  # Indicating the overflow of the Mimosa26 frame ID\nOVERFLOW_FLAG = 0x00000080  # Indicating the occurrence of the overflow flag for a particular Mimosa26 row\n\n\n# Mimosa26 raw data\n@njit\ndef is_mimosa_data(word):  # Check for Mimosa data word\n    return (0xff000000 & word) == 0x20000000\n\n\n@njit\ndef get_plane_number(word):  # There are 6 planes in the stream, starting from 1; return plane number\n    return (word >> 20) & 0xf\n\n\n# Frame header\n@njit\ndef is_frame_header(word):  # Check if frame header high word (frame start flag is set by R/0)\n    return (0x00010000 & word) == 0x00010000\n\n\n@njit\ndef is_data_loss(word):  # Indicates data loss\n    return (0x00020000 & word) == 0x00020000\n\n\n@njit\ndef get_m26_timestamp_low(word):  # Timestamp of Mimosa26 data from frame header low (generated by R/0)\n    return 0x0000ffff & word\n\n\n@njit\ndef get_m26_timestamp_high(word):  # Timestamp of Mimosa26 data from frame header high (generated by R/0)\n    return (0x0000ffff & word) << 16\n\n\n@njit\ndef is_frame_header0(word):  # Check if frame header0 word\n    return (0x0000ffff & word) == 0x00005555\n\n\n@njit\ndef is_frame_header1(word, plane):  # Check if frame header1 word for the actual plane\n    return (0x0000ffff & word) == (0x00005550 | plane)\n\n\n# Frame counter\n@njit\ndef get_frame_id_low(word):  # Get the frame id from the frame id low word\n    return 0x0000ffff & word\n\n\n@njit\ndef get_frame_id_high(word):  # Get the frame id from the frame id high word\n    return (0x0000ffff & word) << 16\n\n\n# Data length\n@njit\ndef get_frame_length(word):  # Get length of Mimosa26 frame\n    return (0x0000ffff & word)\n\n\n# Status / line word\n@njit\ndef get_n_words(word):  # Return the number of data words for the actual row\n    return 0x0000000f & word\n\n\n@njit\ndef get_row(word):  # Extract row from Mimosa26 hit word\n    return (0x00007ff0 & word) >> 4\n\n\n@njit\ndef has_overflow(word):\n    return (0x00008000 & word) != 0\n\n\n# State word\n@njit\ndef get_n_hits(word):  # Returns the number of hits given by actual column word\n    return 0x00000003 & word\n\n\n@njit\ndef get_column(word):  # Extract column from Mimosa26 hit word\n    return (0x00001ffc & word) >> 2\n\n\n# Frame trailer\n@njit\ndef is_frame_trailer0(word):  # Check if frame trailer0 word\n    return (0x0000ffff & word) == 0xaa50\n\n\n@njit\ndef is_frame_trailer1(word, plane):  # Check if frame trailer1 word for the actual plane\n    return (0x0000ffff & word) == (0xaa50 | plane)\n\n\n# Trigger words\n@njit\ndef is_trigger_word(word):  # Check if TLU word (trigger)\n    return (0x80000000 & word) == 0x80000000\n\n\n@njit\ndef get_trigger_timestamp(word):  # Get timestamp of TLU word\n    return (word & 0x7fff0000) >> 16\n\n\n@njit\ndef get_trigger_number(word, trigger_data_format):  # Get trigger number of TLU word\n    if trigger_data_format == 2:\n        return word & 0x0000ffff\n    else:\n        return word & 0x7fffffff\n\n\nclass RawDataInterpreter(object):\n    ''' Class to convert the raw data chunks to hits'''\n\n    def __init__(self, analyze_m26_header_ids=None):\n        '''\n        Parameters:\n        -----------\n        analyze_m26_header_ids : list\n            List of Mimosa26 header IDs that will be interpreted.\n            If None, the value defaults to the global value raw_data_interpreter.DEFAULT_PYMOSA_M26_HEADER_IDS.\n        '''\n        if analyze_m26_header_ids is None:\n            self.analyze_m26_header_ids = DEFAULT_PYMOSA_M26_HEADER_IDS\n        else:\n            self.analyze_m26_header_ids = analyze_m26_header_ids\n        for analyze_m26_header_id in self.analyze_m26_header_ids:\n            if analyze_m26_header_id < 0 or analyze_m26_header_id >= 2**16:\n                raise ValueError('Invalid header ID.')\n        self.analyze_m26_header_ids = np.asarray(self.analyze_m26_header_ids, dtype=np.uint16)\n        self.plane_id_to_index = -1 * np.ones(shape=max(self.analyze_m26_header_ids) + 1, dtype=np.int32)\n        for plane_index, plane_id in enumerate(self.analyze_m26_header_ids):\n            self.plane_id_to_index[plane_id] = plane_index\n        self.reset()\n\n    def reset(self):  # Reset variables\n        # Temporary arrays\n        self.trigger_data = np.zeros(shape=0, dtype=trigger_data_dtype)\n        self.trigger_data_index = np.int64(-1)\n        self.telescope_data = np.zeros(shape=0, dtype=telescope_data_dtype)\n        self.telescope_data_index = np.int64(-1)\n\n        # Raw data interpreter\n        # Per frame variables\n        self.m26_frame_ids = np.zeros(shape=len(self.analyze_m26_header_ids), dtype=np.int64)  # The Mimosa26 frame ID of the actual frame\n        self.m26_frame_length = np.zeros(shape=len(self.analyze_m26_header_ids), dtype=np.uint32)  # The number of \"useful\" data words for the actual frame\n        self.m26_data_loss = np.ones(len(self.analyze_m26_header_ids), dtype=np.bool_)  # The data loss status for the actual frame\n        self.m26_word_index = np.zeros(shape=len(self.analyze_m26_header_ids), dtype=np.uint32)  # The word index per device of the actual frame\n        self.m26_timestamps = np.zeros(shape=len(self.analyze_m26_header_ids), dtype=np.int64)  # The timestamp for each plane (in units of 40 MHz)\n        self.last_m26_timestamps = np.zeros(shape=len(self.analyze_m26_header_ids), dtype=np.int64)\n        self.m26_n_words = np.zeros(shape=len(self.analyze_m26_header_ids), dtype=np.uint32)  # The number of words containing column / row info\n        self.m26_rows = np.zeros(shape=len(self.analyze_m26_header_ids), dtype=np.uint32)  # The actual readout row (rolling shutter)\n        self.m26_frame_status = np.zeros(shape=len(self.analyze_m26_header_ids), dtype=np.uint32)  # The status flags for the actual frames\n        self.last_completed_m26_frame_ids = -1 * np.ones(shape=len(self.analyze_m26_header_ids), dtype=np.int64)  # The status if the frame is complete for the actual frame\n        # Per event variables\n        self.event_number = np.int64(-1)  # The event number of the actual trigger, event number starts at 0\n        self.trigger_number = np.int64(-1)  # The trigger number of the actual trigger\n        self.trigger_timestamp = np.int64(0)  # The trigger timestamp of the actual trigger\n\n        # Event builder\n        self.hits = np.zeros(shape=0, dtype=hits_dtype)\n        self.hits_index = np.int64(-1)\n\n        # Properties\n        self._add_missing_events = False\n        self._timing_offset = TIMING_OFFSET\n\n    @property\n    def add_missing_events(self):\n        return self._add_missing_events\n\n    @add_missing_events.setter\n    def add_missing_events(self, value):\n        self._add_missing_events = bool(value)\n\n    @property\n    def timing_offset(self):\n        return self._timing_offset\n\n    @timing_offset.setter\n    def timing_offset(self, value):\n        self._timing_offset = int(value)\n\n    def interpret_raw_data(self, raw_data=None, build_all_events=False):\n        ''' Converting the raw data array to a hit array.\n        The is the only function that needs to be called to convert the raw data.\n\n        Parameters:\n        -----------\n        raw_data : np.array\n            The array with the raw data words.\n        build_all_events : bool\n            If True, build all events from the remaining trigger_data and telescope_data_array.\n            Use this only after the last raw data chunk to receive the the remaining events in the buffers.\n        '''\n        if raw_data is None:\n            raw_data = np.zeros(shape=0, dtype=np.uint32)\n        if self.telescope_data_index != -1:\n            telescope_data_index_start = self.telescope_data_index + 1\n        else:\n            telescope_data_index_start = 0\n        # Analyze raw data\n        self.trigger_data, self.trigger_data_index, self.telescope_data, self.telescope_data_index, self.m26_frame_ids, self.m26_frame_length, self.m26_data_loss, self.m26_word_index, self.m26_timestamps, self.last_m26_timestamps, self.m26_n_words, self.m26_rows, self.m26_frame_status, self.last_completed_m26_frame_ids, self.event_number, self.trigger_number, self.trigger_timestamp = _interpret_raw_data(\n            raw_data=raw_data,\n            trigger_data=self.trigger_data,\n            trigger_data_index=self.trigger_data_index,\n            telescope_data=self.telescope_data,\n            telescope_data_index=self.telescope_data_index,\n            m26_frame_ids=self.m26_frame_ids,\n            m26_frame_length=self.m26_frame_length,\n            m26_data_loss=self.m26_data_loss,\n            m26_word_index=self.m26_word_index,\n            m26_timestamps=self.m26_timestamps,\n            last_m26_timestamps=self.last_m26_timestamps,\n            m26_n_words=self.m26_n_words,\n            m26_rows=self.m26_rows,\n            m26_frame_status=self.m26_frame_status,\n            last_completed_m26_frame_ids=self.last_completed_m26_frame_ids,\n            event_number=self.event_number,\n            trigger_number=self.trigger_number,\n            trigger_timestamp=self.trigger_timestamp,\n            add_missing_events=self.add_missing_events,\n            build_all_events=build_all_events,\n            analyze_m26_header_ids=self.analyze_m26_header_ids,\n            plane_id_to_index=self.plane_id_to_index)\n\n        # Get data from telescope (just hit data, no assignment to events or data multiplication)\n        telescope_data = self.telescope_data[telescope_data_index_start:self.telescope_data_index + 1].copy()\n\n        # Build events\n        self.trigger_data, self.trigger_data_index, self.telescope_data, self.telescope_data_index, self.hits, self.hits_index = _build_events(\n            trigger_data=self.trigger_data,\n            trigger_data_index=self.trigger_data_index,\n            telescope_data=self.telescope_data,\n            telescope_data_index=self.telescope_data_index,\n            hits=self.hits,\n            hits_index=self.hits_index,\n            last_completed_m26_frame_ids=self.last_completed_m26_frame_ids,\n            timing_offset=self.timing_offset,\n            build_all_events=build_all_events,\n            analyze_m26_header_ids=self.analyze_m26_header_ids,\n            plane_id_to_index=self.plane_id_to_index)\n        # Create a copy of the hits array that is returned\n        hits = self.hits[:self.hits_index + 1].copy()\n        self.hits_index -= (self.hits_index + 1)\n\n        return hits, telescope_data\n\n\n@njit(locals={'trigger_data_index': numba.int64, 'telescope_data_index': numba.int64, 'trigger_status': numba.uint32, 'last_trigger_number': numba.int64, 'last_trigger_timestamp': numba.int64, 'n_missing_events': numba.uint32})\ndef _interpret_raw_data(raw_data, trigger_data, trigger_data_index, telescope_data, telescope_data_index, m26_frame_ids, m26_frame_length, m26_data_loss, m26_word_index, m26_timestamps, last_m26_timestamps, m26_n_words, m26_rows, m26_frame_status, last_completed_m26_frame_ids, event_number, trigger_number, trigger_timestamp, add_missing_events, build_all_events, analyze_m26_header_ids, plane_id_to_index):\n    ''' This function is interpreting the Mimosa26 telescope raw data and creates temporary trigger and telescope data arrays.\n    The interpreter checks for trigger and Mimosa26 data errors.\n\n    Parameters:\n    -----------\n    raw_data : np.array\n        The array with the raw data words.\n    TBD\n    '''\n    # Loop over the raw data words\n    for raw_data_word in raw_data:\n        if is_mimosa_data(raw_data_word):  # Check if word is from Mimosa26.\n            # Check to which plane the data belongs\n            plane_id = get_plane_number(raw_data_word)  # The actual_plane if the actual word belongs to (0 to 5)\n            for analyze_m26_header_id in analyze_m26_header_ids:\n                if plane_id == analyze_m26_header_id:\n                    break\n            else:\n                continue  # Do not interpret data of planes which should be skipped\n            plane_index = plane_id_to_index[plane_id]\n            # In the following, interpretation of the raw data words of the actual plane\n            # Check for data loss bit set by the M26 RX FSM\n            if is_data_loss(raw_data_word):\n                # Setting the data loss flag to true.\n                # The data loss bit is set by the M26 RX FSM.\n                # The bit is set only once after each data loss, i.e.,\n                # the first data word after the lost data words.\n                m26_data_loss[plane_index] = True\n            if is_frame_header(raw_data_word):  # New frame for actual plane, M26 timestamp (LSB), frame header0\n                # Get Mimosa26 timestamp from raw data word (LSB)\n                last_m26_timestamps[plane_index] = m26_timestamps[plane_index]\n                m26_timestamps[plane_index] = (m26_timestamps[plane_index] & 0x7fffffffffff0000) | get_m26_timestamp_low(raw_data_word)\n                m26_word_index[plane_index] = 0\n                # Reset parameters after header\n                m26_frame_length[plane_index] = 0\n                m26_n_words[plane_index] = 0\n                # Set the status bits for priviously incomplete frames\n                index = telescope_data_index\n                while index >= 0:\n                    if telescope_data[index]['plane'] == plane_id:\n                        if telescope_data[index]['frame_id'] > last_completed_m26_frame_ids[plane_index]:\n                            telescope_data[index]['frame_status'] |= DATA_ERROR\n                        else:\n                            break\n                    index -= 1\n                m26_data_loss[plane_index] = False\n                m26_frame_status[plane_index] = 0\n            elif m26_data_loss[plane_index] is True:  # Trash data\n                # Nothing to do, do not trust data\n                continue\n            else:  # Interpreting M26 raw data\n                m26_word_index[plane_index] += 1\n                if m26_word_index[plane_index] == 1:  # Mimosa26 timestamp, M26 timestamp (MSB), frame header1\n                    # Check for 32bit timestamp overflow\n                    if m26_timestamps[plane_index] >= 0 and get_m26_timestamp_high(raw_data_word) < (m26_timestamps[plane_index] & 0x00000000ffff0000):\n                        m26_frame_status[plane_index] |= TIMESTAMP_OVERFLOW\n                        m26_timestamps[plane_index] = np.int64(2**32) + m26_timestamps[plane_index]\n                    # Get Mimosa26 timestamp from raw data word (MSB)\n                    m26_timestamps[plane_index] = get_m26_timestamp_high(raw_data_word) | (m26_timestamps[plane_index] & 0x7fffffff0000ffff)\n                elif m26_word_index[plane_index] == 2:  # Mimosa26 frame ID\n                    # Get Mimosa26 frame ID from raw data word (LSB)\n                    m26_frame_ids[plane_index] = (m26_frame_ids[plane_index] & 0x7fffffffffff0000) | get_frame_id_low(raw_data_word)\n                elif m26_word_index[plane_index] == 3:  # Mimosa26 frame ID\n                    # Check for 32bit frame ID overflow\n                    if m26_frame_ids[plane_index] >= 0 and get_frame_id_high(raw_data_word) < (m26_frame_ids[plane_index] & 0x00000000ffff0000):\n                        m26_frame_status[plane_index] |= FRAME_ID_OVERFLOW\n                        m26_frame_ids[plane_index] = np.int64(2**32) + m26_frame_ids[plane_index]\n                    # Get Mimosa26 frame ID from raw data word (MSB)\n                    m26_frame_ids[plane_index] = get_frame_id_high(raw_data_word) | (m26_frame_ids[plane_index] & 0x7fffffff0000ffff)\n                elif m26_word_index[plane_index] == 4:  # Mimosa26 frame length\n                    m26_frame_length[plane_index] = get_frame_length(raw_data_word)\n                    if m26_frame_length[plane_index] > 570:  # Defined in the Mimosa26 protocol, no more than 570 \"useful\" data words\n                        m26_data_loss[plane_index] = True\n                        continue\n                elif m26_word_index[plane_index] == 5:  # Mimosa26 frame length, a second time\n                    if m26_frame_length[plane_index] != get_frame_length(raw_data_word):  # DO0 & DO1 should always have the same data length\n                        m26_data_loss[plane_index] = True\n                        continue\n                    else:\n                        m26_frame_length[plane_index] += get_frame_length(raw_data_word)\n                elif m26_word_index[plane_index] == 5 + m26_frame_length[plane_index] + 1:  # Frame trailer0\n                    if not is_frame_trailer0(raw_data_word):\n                        m26_data_loss[plane_index] = True\n                        continue\n                elif m26_word_index[plane_index] == 5 + m26_frame_length[plane_index] + 2:  # Frame trailer1\n                    if not is_frame_trailer1(raw_data_word, plane=plane_id):\n                        m26_data_loss[plane_index] = True\n                        continue\n                    else:\n                        last_completed_m26_frame_ids[plane_index] = m26_frame_ids[plane_index]\n                elif m26_word_index[plane_index] > 5 + m26_frame_length[plane_index] + 2:  # Ignore any occurrence of additional raw data words\n                    m26_data_loss[plane_index] = True\n                    continue\n                else:  # Column / Row words (actual data word with hits)\n                    if m26_n_words[plane_index] == 0:  # First word contains the row info and the number of data words for this row\n                        if m26_word_index[plane_index] == 5 + m26_frame_length[plane_index]:  # Always even amount of words or this fill word is used\n                            # Ignore this fill word\n                            continue\n                        else:\n                            m26_n_words[plane_index] = get_n_words(raw_data_word)\n                            m26_rows[plane_index] = get_row(raw_data_word)  # Get row from data word\n                            if m26_rows[plane_index] >= 576:  # Row overflow\n                                m26_data_loss[plane_index] = True\n                                continue\n                        if has_overflow(raw_data_word):\n                            m26_frame_status[plane_index] |= OVERFLOW_FLAG  # set overflow bit\n                        else:\n                            m26_frame_status[plane_index] & ~OVERFLOW_FLAG  # unset overflow bit\n                    else:\n                        m26_n_words[plane_index] = m26_n_words[plane_index] - 1  # Count down the words\n                        n_hits = get_n_hits(raw_data_word)\n                        column = get_column(raw_data_word)  # Get column from data word\n                        if column >= 1152:  # Column overflow\n                            m26_data_loss[plane_index] = True\n                            continue\n                        for k in range(n_hits + 1):\n                            if column + k >= 1152:\n                                m26_data_loss[plane_index] = True\n                                break\n                            # Increase index\n                            telescope_data_index += 1\n                            # extend telescope data array if neccessary\n                            if telescope_data_index >= telescope_data.shape[0]:\n                                # remove old hit data from array for each plane individually. Prevents the case that telescope data array gets too big in case\n                                # time until next trigger is very large, since telescope data has to be buffered until next trigger.\n                                select = (telescope_data['plane'] == plane_id)\n                                select &= (telescope_data['time_stamp'] < (m26_timestamps[plane_index] - MAX_BUFFER_TIME_SLIP * MIMOSA_FREQ * 10**6))\n                                count_outdated = np.sum(select)\n                                if count_outdated:\n                                    telescope_data = telescope_data[~select]\n                                    telescope_data_index = telescope_data_index - count_outdated\n                                # extend telescope data array if neccessary\n                                telescope_data_tmp = np.zeros(shape=max(1, int(raw_data.shape[0] / 2)), dtype=telescope_data_dtype)\n                                telescope_data = np.concatenate((telescope_data, telescope_data_tmp))\n\n                            # Store hits\n                            telescope_data[telescope_data_index]['plane'] = plane_id\n                            telescope_data[telescope_data_index]['time_stamp'] = m26_timestamps[plane_index]\n                            telescope_data[telescope_data_index]['frame_id'] = m26_frame_ids[plane_index]\n                            telescope_data[telescope_data_index]['column'] = column + k\n                            telescope_data[telescope_data_index]['row'] = m26_rows[plane_index]\n                            telescope_data[telescope_data_index]['frame_status'] = m26_frame_status[plane_index]\n        elif is_trigger_word(raw_data_word):  # Raw data word is TLU/trigger word\n            # Reset trigger status\n            trigger_status = 0\n            # Get latest telescope timestamp and set trigger timestamp\n            last_trigger_timestamp = trigger_timestamp\n            # Get largest M26 timestamp\n            for tmp_plane_index, _ in enumerate(analyze_m26_header_ids):\n                if last_m26_timestamps[tmp_plane_index] > trigger_timestamp:\n                    trigger_timestamp = last_m26_timestamps[tmp_plane_index]\n            # Calculating 63bit timestamp from 15bit trigger timestamp\n            # and last telescope timestamp (frame header timestamp).\n            # Assumption: the telescope timestamp is updated more frequent than\n            # the 15bit trigger timestamp can overflow. The frame is occurring\n            # every 4608 clock cycles (115.2 us).\n            # Get trigger timestamp from raw data word\n            trigger_timestamp = (0x7fffffffffff8000 & trigger_timestamp) | get_trigger_timestamp(raw_data_word)\n            # Check for 15bit trigger timestamp overflow\n            if last_trigger_timestamp >= 0 and trigger_timestamp <= last_trigger_timestamp:\n                trigger_status |= TRIGGER_TIMESTAMP_OVERFLOW\n                trigger_timestamp = np.int64(2**15) + trigger_timestamp\n            # Copy of trigger number\n            last_trigger_number = trigger_number\n            # Check for 16bit trigger number overflow\n            if trigger_number >= 0 and get_trigger_number(raw_data_word, trigger_data_format=2) <= (trigger_number & 0x000000000000ffff):\n                trigger_status |= TRIGGER_NUMBER_OVERFLOW\n                trigger_number = np.int64(2**16) + trigger_number\n            # Get trigger number from raw data word\n            if trigger_number < 0:\n                trigger_number = get_trigger_number(raw_data_word, trigger_data_format=2)\n            else:\n                trigger_number = (0x7fffffffffff0000 & trigger_number) | get_trigger_number(raw_data_word, trigger_data_format=2)\n            # Check validity of trigger number\n            # Trigger number has to increase by 1\n            if trigger_data_index >= 0:\n                # Check if trigger number has increased by 1\n                if last_trigger_number < 0:\n                    n_missing_events = 0\n                else:\n                    n_missing_events = trigger_number - (last_trigger_number + 1)\n                if n_missing_events != 0:\n                    if n_missing_events > 0 and add_missing_events:\n                        for i in range(n_missing_events):\n                            # Increase index\n                            trigger_data_index += 1\n                            # extend trigger data array if neccessary\n                            if trigger_data_index >= trigger_data.shape[0]:\n                                trigger_data_tmp = np.zeros(shape=max(1, int(raw_data.shape[0] / 6)), dtype=trigger_data_dtype)\n                                trigger_data = np.concatenate((trigger_data, trigger_data_tmp))\n                            # Increase event number\n                            event_number += 1\n                            # Store trigger data\n                            trigger_data[trigger_data_index]['event_number'] = event_number  # Timestamp of TLU word\n                            trigger_data[trigger_data_index]['trigger_time_stamp'] = -1  # Timestamp of TLU word\n                            trigger_data[trigger_data_index]['trigger_number'] = trigger_data[trigger_data_index - 1]['trigger_number'] + 1 + i\n                            trigger_data[trigger_data_index]['trigger_status'] = NO_TRIGGER_WORD_ERROR  # Trigger status\n                    else:\n                        trigger_status |= TRIGGER_NUMBER_ERROR\n            # Increase index\n            trigger_data_index += 1\n            # extend trigger data array if neccessary\n            if trigger_data_index >= trigger_data.shape[0]:\n                trigger_data_tmp = np.zeros(shape=max(1, int(raw_data.shape[0] / 6)), dtype=trigger_data_dtype)\n                trigger_data = np.concatenate((trigger_data, trigger_data_tmp))\n            # Increase event number\n            event_number += 1\n            # Store trigger data\n            trigger_data[trigger_data_index]['event_number'] = event_number  # Timestamp of TLU word\n            trigger_data[trigger_data_index]['trigger_number'] = trigger_number\n            trigger_data[trigger_data_index]['trigger_time_stamp'] = trigger_timestamp  # Timestamp of TLU word\n            trigger_data[trigger_data_index]['trigger_status'] = trigger_status  # Trigger status\n        else:  # Raw data contains unknown word, neither M26 nor TLU word\n            for tmp_plane_index, _ in enumerate(analyze_m26_header_ids):\n                m26_data_loss[tmp_plane_index] = True\n\n    # Set the status bits for priviously incomplete frames\n    if build_all_events:\n        for tmp_plane_index, tmp_plane_id in enumerate(analyze_m26_header_ids):\n            index = telescope_data_index\n            while index >= 0:\n                if telescope_data[index]['plane'] == tmp_plane_id:\n                    if telescope_data[index]['frame_id'] > last_completed_m26_frame_ids[tmp_plane_index]:\n                        telescope_data[index]['frame_status'] |= DATA_ERROR\n                    else:\n                        break\n                index -= 1\n\n    return trigger_data, trigger_data_index, telescope_data, telescope_data_index, m26_frame_ids, m26_frame_length, m26_data_loss, m26_word_index, m26_timestamps, last_m26_timestamps, m26_n_words, m26_rows, m26_frame_status, last_completed_m26_frame_ids, event_number, trigger_number, trigger_timestamp\n\n\n@njit(locals={'hits_index': numba.int64, 'curr_trigger_data_index': numba.int64, 'curr_telescope_data_index': numba.int64})\ndef _build_events(trigger_data, trigger_data_index, telescope_data, telescope_data_index, hits, hits_index, last_completed_m26_frame_ids, timing_offset, build_all_events, analyze_m26_header_ids, plane_id_to_index):\n    ''' This function is builds events from the temporary trigger and telescope data arrays.\n\n    Parameters:\n    -----------\n    TBD\n    '''\n    latest_trigger_data_index = -1\n    finished_telescope_data_indices = -1 * np.ones(shape=len(analyze_m26_header_ids), dtype=np.int64)\n    last_event_trigger_data_indices = -1 * np.ones(shape=len(analyze_m26_header_ids), dtype=np.int64)\n    finished_event = np.ones(shape=len(analyze_m26_header_ids), dtype=np.bool_)\n    curr_event_status = np.zeros(shape=len(analyze_m26_header_ids), dtype=np.uint32)\n\n    curr_trigger_data_index = 0\n    curr_hits_index = hits_index\n    # adding hits\n    while curr_trigger_data_index <= trigger_data_index and np.all(finished_event):\n        trigger_event_number = trigger_data[curr_trigger_data_index]['event_number']\n        trigger_number = trigger_data[curr_trigger_data_index]['trigger_number']\n        trigger_timestamp = trigger_data[curr_trigger_data_index]['trigger_time_stamp']\n        trigger_status = trigger_data[curr_trigger_data_index]['trigger_status']\n        curr_telescope_data_index = np.min(finished_telescope_data_indices) + 1\n        # Reset status\n        for tmp_plane_index, _ in enumerate(analyze_m26_header_ids):\n            finished_event[tmp_plane_index] = False\n            curr_event_status[tmp_plane_index] = 0\n        while curr_telescope_data_index <= telescope_data_index:\n            curr_plane_id = telescope_data[curr_telescope_data_index]['plane']\n            curr_plane_index = plane_id_to_index[curr_plane_id]\n            curr_frame_id = telescope_data[curr_telescope_data_index]['frame_id']\n            if not finished_event[curr_plane_index] and (build_all_events or curr_frame_id <= last_completed_m26_frame_ids[curr_plane_index]):\n                hit_timestamp_start = telescope_data[curr_telescope_data_index]['time_stamp'] + telescope_data[curr_telescope_data_index]['row'] * ROW_UNIT_CYCLE - 2 * FRAME_UNIT_CYCLE - timing_offset\n                hit_timestamp_stop = hit_timestamp_start + FRAME_UNIT_CYCLE + ROW_UNIT_CYCLE\n                if hit_timestamp_start <= trigger_timestamp and trigger_timestamp < hit_timestamp_stop:\n                    curr_hits_index += 1\n                    # extend hits array if neccessary\n                    if curr_hits_index >= hits.shape[0]:\n                        hits_tmp = np.zeros(shape=telescope_data.shape[0], dtype=hits_dtype)\n                        hits = np.concatenate((hits, hits_tmp))\n                    # Adding hits to event\n                    hits[curr_hits_index]['plane'] = curr_plane_id\n                    hits[curr_hits_index]['event_number'] = trigger_event_number\n                    hits[curr_hits_index]['trigger_number'] = trigger_number\n                    hits[curr_hits_index]['trigger_time_stamp'] = trigger_timestamp\n                    hits[curr_hits_index]['row_time_stamp'] = hit_timestamp_start\n                    hits[curr_hits_index]['frame_id'] = curr_frame_id\n                    hits[curr_hits_index]['column'] = telescope_data[curr_telescope_data_index]['column']\n                    hits[curr_hits_index]['row'] = telescope_data[curr_telescope_data_index]['row']\n                    hits[curr_hits_index]['event_status'] = 0\n                    curr_event_status[curr_plane_index] |= telescope_data[curr_telescope_data_index]['frame_status'] | trigger_status\n                elif hit_timestamp_start > trigger_timestamp:\n                    # latest_trigger_data_indices[plane_id_to_index[telescope_data[curr_telescope_data_index]['plane']]] = curr_trigger_data_index\n                    finished_event[plane_id_to_index[telescope_data[curr_telescope_data_index]['plane']]] = True\n                    if np.all(finished_event):\n                        latest_trigger_data_index = curr_trigger_data_index\n                        for tmp_plane_index, _ in enumerate(analyze_m26_header_ids):\n                            last_event_trigger_data_indices[tmp_plane_index] = finished_telescope_data_indices[tmp_plane_index]\n                        hits_index = curr_hits_index\n                        # Set event status for complete event\n                        index = curr_hits_index\n                        while trigger_event_number == hits[index]['event_number'] and index >= 0:\n                            hits[index]['event_status'] = curr_event_status[plane_id_to_index[hits[index]['plane']]]\n                            index -= 1\n                        break\n                else:  # trigger_timestamp >= hit_timestamp_stop\n                    finished_telescope_data_indices[plane_id_to_index[telescope_data[curr_telescope_data_index]['plane']]] = curr_telescope_data_index\n            curr_telescope_data_index += 1\n        # special case\n        if build_all_events:\n            hits_index = curr_hits_index\n            # Set event status for complete event\n            index = curr_hits_index\n            while index >= 0:\n                if hits[index]['event_number'] == trigger_event_number:\n                    hits[index]['event_status'] = curr_event_status[plane_id_to_index[hits[index]['plane']]]\n                elif hits[index]['event_number'] < trigger_event_number:\n                    break\n                index -= 1\n            for tmp_plane_index, _ in enumerate(analyze_m26_header_ids):\n                finished_event[tmp_plane_index] = True\n        curr_trigger_data_index += 1\n\n    if build_all_events:\n        telescope_data_start_index = telescope_data_index + 1\n    else:\n        telescope_data_start_index = np.min(last_event_trigger_data_indices) + 1\n    telescope_data = telescope_data[telescope_data_start_index:]\n    telescope_data_index -= telescope_data_start_index\n    if build_all_events:\n        trigger_data_start_index = trigger_data_index + 1\n    else:\n        trigger_data_start_index = latest_trigger_data_index + 1\n    trigger_data = trigger_data[trigger_data_start_index:]\n    trigger_data_index -= trigger_data_start_index\n\n    return trigger_data, trigger_data_index, telescope_data, telescope_data_index, hits, hits_index\n", "meta": {"hexsha": "55d503c8ce5cce93da23902fa44854d5aff7a512", "size": 35958, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymosa_mimosa26_interpreter/raw_data_interpreter.py", "max_stars_repo_name": "SiLab-Bonn/pymosa_mimosa26_interpreter", "max_stars_repo_head_hexsha": "ef43b72dfed65b072703627a18d6e47a8a344165", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pymosa_mimosa26_interpreter/raw_data_interpreter.py", "max_issues_repo_name": "SiLab-Bonn/pymosa_mimosa26_interpreter", "max_issues_repo_head_hexsha": "ef43b72dfed65b072703627a18d6e47a8a344165", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-03-07T12:05:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-08T09:11:37.000Z", "max_forks_repo_path": "pymosa_mimosa26_interpreter/raw_data_interpreter.py", "max_forks_repo_name": "SiLab-Bonn/pyBAR_mimosa26_interpreter", "max_forks_repo_head_hexsha": "ef43b72dfed65b072703627a18d6e47a8a344165", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-03-04T20:22:38.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-25T07:44:12.000Z", "avg_line_length": 54.9816513761, "max_line_length": 408, "alphanum_fraction": 0.6500917737, "include": true, "reason": "import numpy,import numba,from numba", "num_tokens": 8117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.19375419650535225}}
{"text": "\"\"\"Calculate collision matrix of direct solution of LBTE.\"\"\"\n# Copyright (C) 2020 Atsushi Togo\n# All rights reserved.\n#\n# This file is part of phono3py.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n#   notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n#   notice, this list of conditions and the following disclaimer in\n#   the documentation and/or other materials provided with the\n#   distribution.\n#\n# * Neither the name of the phonopy project nor the names of its\n#   contributors may be used to endorse or promote products derived\n#   from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport numpy as np\nfrom phonopy.units import Kb, THzToEv\n\nfrom phono3py.phonon3.imag_self_energy import ImagSelfEnergy\nfrom phono3py.phonon3.interaction import Interaction\n\n\nclass CollisionMatrix(ImagSelfEnergy):\n    \"\"\"Collision matrix of direct solution of LBTE for one grid point.\n\n    Main diagonal part (imag-self-energy) and\n    the other part are separately stored.\n\n    \"\"\"\n\n    def __init__(\n        self,\n        interaction: Interaction,\n        rotations_cartesian=None,\n        num_ir_grid_points=None,\n        rot_grid_points=None,\n        is_reducible_collision_matrix=False,\n        log_level=0,\n        lang=\"C\",\n    ):\n        \"\"\"Init method.\"\"\"\n        self._pp: Interaction\n        self._is_collision_matrix: bool\n        self._sigma = None\n        self._frequency_points = None\n        self._temperature = None\n        self._grid_point = None\n        self._lang = None\n        self._imag_self_energy = None\n        self._collision_matrix = None\n        self._pp_strength = None\n        self._frequencies = None\n        self._triplets_at_q = None\n        self._triplets_map_at_q = None\n        self._weights_at_q = None\n        self._band_indices = None\n        self._unit_conversion = None\n        self._cutoff_frequency = None\n        self._g = None\n        self._unit_conversion = None\n        self._log_level = log_level\n\n        super().__init__(interaction, lang=lang)\n\n        self._is_reducible_collision_matrix = is_reducible_collision_matrix\n        self._is_collision_matrix = True\n\n        if not self._is_reducible_collision_matrix:\n            self._num_ir_grid_points = num_ir_grid_points\n            self._rot_grid_points = np.array(\n                self._pp.bz_grid.bzg2grg[rot_grid_points], dtype=\"int_\", order=\"C\"\n            )\n            self._rotations_cartesian = rotations_cartesian\n\n    def run(self):\n        \"\"\"Calculate collision matrix at a grid point.\"\"\"\n        if self._pp_strength is None:\n            self.run_interaction()\n\n        num_band0 = self._pp_strength.shape[1]\n        num_band = self._pp_strength.shape[2]\n        self._imag_self_energy = np.zeros(num_band0, dtype=\"double\")\n\n        if self._is_reducible_collision_matrix:\n            num_mesh_points = np.prod(self._pp.mesh_numbers)\n            self._collision_matrix = np.zeros(\n                (num_band0, num_mesh_points, num_band), dtype=\"double\"\n            )\n        else:\n            self._collision_matrix = np.zeros(\n                (num_band0, 3, self._num_ir_grid_points, num_band, 3), dtype=\"double\"\n            )\n        self._run_with_band_indices()\n        self._run_collision_matrix()\n\n    def get_collision_matrix(self):\n        \"\"\"Return collision matrix at a grid point.\"\"\"\n        return self._collision_matrix\n\n    def set_grid_point(self, grid_point=None):\n        \"\"\"Set a grid point and prepare for collision matrix calculation.\"\"\"\n        if grid_point is None:\n            self._grid_point = None\n        else:\n            self._pp.set_grid_point(grid_point, store_triplets_map=True)\n            self._pp_strength = None\n            (\n                self._triplets_at_q,\n                self._weights_at_q,\n                self._triplets_map_at_q,\n                self._ir_map_at_q,\n            ) = self._pp.get_triplets_at_q()\n            self._grid_point = grid_point\n            self._frequencies, self._eigenvectors, _ = self._pp.get_phonons()\n\n    def _run_collision_matrix(self):\n        if self._temperature > 0:\n            if self._lang == \"C\":\n                if self._is_reducible_collision_matrix:\n                    self._run_c_reducible_collision_matrix()\n                else:\n                    self._run_c_collision_matrix()\n            else:\n                if self._is_reducible_collision_matrix:\n                    self._run_py_reducible_collision_matrix()\n                else:\n                    self._run_py_collision_matrix()\n\n    def _run_c_collision_matrix(self):\n        import phono3py._phono3py as phono3c\n\n        phono3c.collision_matrix(\n            self._collision_matrix,\n            self._pp_strength,\n            self._frequencies,\n            self._g,\n            self._triplets_at_q,\n            self._triplets_map_at_q,\n            self._ir_map_at_q,\n            self._rot_grid_points,  # in GRGrid\n            self._rotations_cartesian,\n            self._temperature,\n            self._unit_conversion,\n            self._cutoff_frequency,\n        )\n\n    def _run_c_reducible_collision_matrix(self):\n        import phono3py._phono3py as phono3c\n\n        phono3c.reducible_collision_matrix(\n            self._collision_matrix,\n            self._pp_strength,\n            self._frequencies,\n            self._g,\n            self._triplets_at_q,\n            self._triplets_map_at_q,\n            self._ir_map_at_q,\n            self._temperature,\n            self._unit_conversion,\n            self._cutoff_frequency,\n        )\n\n    def _run_py_collision_matrix(self):\n        r\"\"\"Sum over rotations, and q-points and bands for third phonons.\n\n        \\Omega' = \\sum_R' R' \\Omega_{kp,R'k'p'}\n\n        pp_strength.shape = (num_triplets, num_band0, num_band, num_band)\n\n        \"\"\"\n        num_band0 = self._pp_strength.shape[1]\n        num_band = self._pp_strength.shape[2]\n        gp2tp, tp2s, swapped = self._get_gp2tp_map()\n        for i in range(self._num_ir_grid_points):\n            r_gps = self._rot_grid_points[i]\n            for r, r_gp in zip(self._rotations_cartesian, r_gps):\n                inv_sinh = self._get_inv_sinh(tp2s[r_gp])\n                ti = gp2tp[r_gp]\n                for j, k in np.ndindex((num_band0, num_band)):\n                    if swapped[r_gp]:\n                        collision = (\n                            self._pp_strength[ti, j, :, k]\n                            * inv_sinh\n                            * self._g[2, ti, j, :, k]\n                        ).sum()\n                    else:\n                        collision = (\n                            self._pp_strength[ti, j, k]\n                            * inv_sinh\n                            * self._g[2, ti, j, k]\n                        ).sum()\n                    collision *= self._unit_conversion\n                    self._collision_matrix[j, :, i, k, :] += collision * r\n\n    def _run_py_reducible_collision_matrix(self):\n        r\"\"\"Sum over q-points and bands of third phonons.\n\n        This corresponds to the second term of right hand side of\n        \\Omega_{q0p0, q1p1} in Chaput's paper.\n\n        pp_strength.shape = (num_triplets, num_band0, num_band, num_band)\n\n        \"\"\"\n        num_mesh_points = np.prod(self._pp.mesh_numbers)\n        num_band0 = self._pp_strength.shape[1]\n        num_band = self._pp_strength.shape[2]\n        gp2tp, tp2s, swapped = self._get_gp2tp_map()\n        for gp1 in range(num_mesh_points):\n            inv_sinh = self._get_inv_sinh(tp2s[gp1])\n            ti = gp2tp[gp1]\n            for j, k in np.ndindex((num_band0, num_band)):\n                if swapped[gp1]:\n                    collision = (\n                        self._pp_strength[ti, j, :, k]\n                        * inv_sinh\n                        * self._g[2, ti, j, :, k]\n                    ).sum()\n                else:\n                    collision = (\n                        self._pp_strength[ti, j, k] * inv_sinh * self._g[2, ti, j, k]\n                    ).sum()\n                collision *= self._unit_conversion\n                self._collision_matrix[j, gp1, k] += collision\n\n    def _get_gp2tp_map(self):\n        \"\"\"Return mapping table from grid point index to triplet index.\n\n        triplets_map_at_q contains index mapping of q1 in (q0, q1, q2) to\n        independet q1 under q0+q1+q2=G with a fixed q0.\n\n        Note\n        ----\n        map_q[gp1] <= gp1.:\n            Symmetry relation of grid poi nts with a stabilizer q0.\n        map_triplets[gp1] <= gp1 :\n            map_q[gp1] == gp1 : map_q[gp2] if map_q[gp2] < gp1 otherwise gp1.\n            map_q[gp1] != gp1 : map_triplets[map_q[gp1]]\n\n\n\n        As a rule\n        1. map_triplets[gp1] == gp1 : [gp0, gp1, gp2]\n        2. map_triplets[gp1] != gp1 : [gp0, map_q[gp2], gp1'],\n                                      map_triplets[gp1] == map_q[gp2]\n\n        \"\"\"\n        map_triplets = self._triplets_map_at_q\n        map_q = self._ir_map_at_q\n        gp2tp = -np.ones(len(map_triplets), dtype=\"int_\")\n        tp2s = -np.ones(len(map_triplets), dtype=\"int_\")\n        swapped = np.zeros(len(map_triplets), dtype=\"bytes\")\n        num_tps = 0\n\n        bzg2grg = self._pp.bz_grid.bzg2grg\n\n        for gp1, tp_gp1 in enumerate(map_triplets):\n            if map_q[gp1] == gp1:\n                if gp1 == tp_gp1:\n                    gp2tp[gp1] = num_tps\n                    tp2s[gp1] = self._triplets_at_q[num_tps][2]\n                    assert bzg2grg[self._triplets_at_q[num_tps][1]] == gp1\n                    num_tps += 1\n                else:  # q1 <--> q2 swap if swappable.\n                    gp2tp[gp1] = gp2tp[tp_gp1]\n                    tp2s[gp1] = self._triplets_at_q[gp2tp[gp1]][1]\n                    swapped[gp1] = 1\n                    assert map_q[bzg2grg[self._triplets_at_q[gp2tp[gp1]][2]]] == gp1\n            else:  # q1 is not in ir-q1s.\n                gp2tp[gp1] = gp2tp[map_q[gp1]]\n                tp2s[gp1] = tp2s[map_q[gp1]]\n                swapped[gp1] = swapped[map_q[gp1]]\n\n            # Alternative implementation of tp2s\n            # grg2bzg = self._pp.bz_grid.grg2bzg\n            # addresses = self._pp.bz_grid.addresses\n            # q0 = addresses[self._triplets_at_q[0][0]]\n            # q1 = addresses[grg2bzg[gp1]]\n            # q2 = -q0 - q1\n            # gp2 = get_grid_point_from_address(q2, self._pp.bz_grid.D_diag)\n            # tp2s[gp1] = self._pp.bz_grid.grg2bzg[gp2]\n\n        return gp2tp, tp2s, swapped\n\n    def _get_inv_sinh(self, gp):\n        \"\"\"Return sinh term for bands at a q-point.\"\"\"\n        freqs = self._frequencies[gp]\n        sinh = np.where(\n            freqs > self._cutoff_frequency,\n            np.sinh(freqs * THzToEv / (2 * Kb * self._temperature)),\n            -1.0,\n        )\n        inv_sinh = np.where(sinh > 0, 1.0 / sinh, 0)\n\n        return inv_sinh\n", "meta": {"hexsha": "86e82557dac1386d92b68148fcf81c31069b90a5", "size": 11814, "ext": "py", "lang": "Python", "max_stars_repo_path": "phono3py/phonon3/collision_matrix.py", "max_stars_repo_name": "sjli47/phono3py-sjl", "max_stars_repo_head_hexsha": "22740415512d2f9bd00cbf2dc43594de003a37df", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "phono3py/phonon3/collision_matrix.py", "max_issues_repo_name": "sjli47/phono3py-sjl", "max_issues_repo_head_hexsha": "22740415512d2f9bd00cbf2dc43594de003a37df", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phono3py/phonon3/collision_matrix.py", "max_forks_repo_name": "sjli47/phono3py-sjl", "max_forks_repo_head_hexsha": "22740415512d2f9bd00cbf2dc43594de003a37df", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5047619048, "max_line_length": 85, "alphanum_fraction": 0.5879465041, "include": true, "reason": "import numpy", "num_tokens": 2912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.3208212943308302, "lm_q1q2_score": 0.1937541880095011}}
{"text": "#! /usr/bin/env python\n#S.rodney\n# 2011.05.04\n\"\"\"\nExtrapolate the Hsiao SED and the non1a SEDs \ndown to 300 angstroms to allow the W filter to \nreach out to z=2.5 smoothly in the k-correction \ntables and model light curves.\n\"\"\"\n\nimport os\nfrom numpy import *\nfrom pylab import * \n\ntry : sndataroot = os.environ['SNDATA_ROOT']\nexcept KeyError: \n    sndataroot = os.path.abspath( '.' )\n\nMINWAVE = 300     # min wavelength for extrapolation (Angstroms)\nMAXWAVE = 20000   # max wavelength for extrapolation (Angstroms)\n\ndef extendEverything( salt2dir = 'models/SALT2/SALT2.Guy10_UV2IR', \n                      doCC=True, doIa=True ) :\n    \"\"\" Run all the extrapolation functions, for both the SALT2 model \n    components and all the non1a SEDs \"\"\"\n\n    if doCC : \n        extendNon1a()\n\n    if doIa : \n        salt2dir = os.path.join( sndataroot, salt2dir ) \n        if not os.path.isdir( salt2dir ) : \n            os.makedirs( salt2dir )\n\n        # make the Hsiao07.extrap.dat template SED\n        hsiao07 = os.path.join( sndataroot, 'snsed/Hsiao07.dat')\n        hsiao07ext = os.path.join( sndataroot, 'snsed/Hsiao07.extrap.dat')\n        extrapolatesed_linfit( hsiao07, hsiao07ext, Npt=10, Nsmooth=0, forceslope=True )\n\n        extendSALT2_temp0()\n        extendSALT2_temp1()\n        extendSALT2_flatline()    \n\n\ndef getsed( sedfile = os.path.join( sndataroot, 'snsed/Hsiao07.dat'), day='all'  ) : \n    d,w,f = loadtxt( sedfile, unpack=True ) \n\n    #d = d.astype(int)\n    days = unique( d ) \n\n    if day == 'all' : \n        dlist = [ d[ where( d == day ) ] for day in days ]\n        wlist = [ w[ where( d == day ) ] for day in days ]\n        flist = [ f[ where( d == day ) ] for day in days ]\n        return( dlist, wlist, flist )\n    else : \n        return( w[ where( d == day ) ], f[ where( d == day ) ] )\n\n\ndef plotsed( sedfile= os.path.join( sndataroot, 'snsed/Hsiao07.dat'), \n             day='all', normalize=False, **kwarg): \n    dlist,wlist,flist = getsed( sedfile ) \n    #days = unique( dlist ) \n    for i in range( len(wlist) ) : \n        thisday = dlist[i][0]\n        \n        #defaults = { 'label':str(thisday) } \n        #plotarg = dict( kwarg.items() + defaults.items() )\n        if day!='all' : \n            if abs(thisday-day)>0.6 : continue\n        offset, normfactor = 0, 1\n        if normalize : \n            if normalize > 1 : \n                normfactor = (flist[i][:-1] * (wlist[i][1:]-wlist[i][:-1])).sum()\n            else : \n                normfactor = flist[i].max()\n                offset = thisday\n        plot( wlist[i], flist[i]/normfactor + offset, **kwarg )\n        # user_in=raw_input('%i : return to continue'%i)\n\n\ndef extrapolatesed( sedfile, newsedfile, minwave=MINWAVE, maxwave=MAXWAVE, \n                    Bzptwave=900, Bextwave=2000, Bfrac=0.2, Brefwave=2800, \n                    Nred = 10, Nsmooth=0, verbose=False ):\n    \"\"\"\n    Set bluewave and bluefrac to define an extrapolation point\n    blueward of the low-wavelength edge of the SED: \n      Bextwave = wavelength of the extrapolation point\n      Brefwave = reference wavelength for setting extrapolated flux \n      Bfrac = fraction of the flux at Brefwave to set as the \n          flux value at Bextwave\n    The linear extrapolation  uses only this fixed point and\n    the input SED point at Brefwave. \n\n    On the red side (where the SED tail is more well behaved)\n    we perform a linear fit to the last Nred points to define \n    the extrapolation.  Set Nsmooth to a positive integer to set \n    the window size for median smoothing of the input spectrum \n    before the linear fitting. \n\n    e.g.  Bzptwave, Bextwave, Bfrac, Brefwave = 900, 2000, 0.2, 2800 \n     fix the flux at 900 angstroms to be 0. \n     fix the flux at 2000 angstroms to be 20% of the input SED's\n     flux at 2800 angstrom, then define a piecewise linear extrapolation\n     connecting the three anchor points at 900, 2000, and the minimum \n     wavelength of the input SED.\n\n    Note: For CCSN SEDs, we use \n       Bzptwave=900, Bextwave=2000, Bfrac=0.2, Brefwave=2800, \n      \n    and for a SNIa SED, we might use \n       Bzptwave=600, Bextwave=800, Bfrac=0.1, Brefwave=1000\n     \n    \"\"\"\n    from scipy import interpolate as scint\n    from scipy import stats\n    import shutil\n\n    medsmooth = lambda f,N : array( [ median( f[max(0,i-N):min(len(f),max(0,i-N)+2*N)]) for i in range(len(f)) ] )\n\n    dlist,wlist,flist = getsed( sedfile )  # these are 2-D lists of SEDs at different phases\n    dlistnew, wlistnew, flistnew = [],[],[]\n\n    fout = open( newsedfile, 'w' )\n    for i in range( len(dlist) ) : \n        d,w,f = dlist[i],wlist[i],flist[i]\n\n        if minwave  < w[0] : \n            wavestep = w[1] - w[0]\n            irefpt = abs( w - Brefwave ).argmin()\n            wrefpt = w[irefpt]\n            frefpt = f[irefpt]\n            wextpt = Bextwave\n            fextpt = Bfrac * frefpt\n\n            if wextpt < w[0] : \n                # Blueward extrapolation from the minimum wavelength of the input \n                # SED down to the first extrapolation point\n                a = (f[0]-fextpt)/(w[0]-wextpt)  # slope of extrapolation line\n                b = f[0] - a*w[0] # intercept\n                wextBlue = arange( wextpt, w[0], wavestep )\n                fextBlue = array( [ max( 0, a * wave + b ) for wave in wextBlue ] ) \n                w = append( wextBlue, w )\n                f = append( fextBlue, f )\n            if minwave < w[0] : \n                # Blueward extrapolation to the min wavelength (fixed to zero flux at Bzptwave)\n                wextpt = Bzptwave\n                fextpt = 0\n                a = (f[0]-fextpt)/(w[0]-wextpt)  # slope of extrapolation line\n                b = f[0] - a*w[0] # intercept\n                wextBlue = arange( minwave, w[0], wavestep )\n                fextBlue = array( [ max( 0, a * wave + b ) for wave in wextBlue ] ) \n                w = append( wextBlue, w )\n                f = append( fextBlue, f )\n                \n        if maxwave > w[-1] : \n            # Redward linear extrapolation from last Nred points\n            wavestep = w[-1] - w[-2]\n            wN = w[-Nred:]\n\n            if Nsmooth : fN = medsmooth( f, Nsmooth )[-Nred:]\n            else : fN = f[-Nred:]\n            (a,b,rval,pval,stderr)=stats.linregress(wN,fN)\n\n            if a > 0 : \n                # re-do redward  linear extrapolation using the peak\n                # in order to guarantee a downward slope\n                if verbose : print( \"  re-fitting %s day %i to ensure downward slope to the red\"%(sedfile, d[0]) )\n                wN = [ w[ f.argmax() ], w[-1] ]\n                fN = [ f.max(), f[-1],  ]\n                (a,b,rval,pval,stderr)=stats.linregress(wN,fN)\n\n            wextRed = arange( w[-1]+wavestep, maxwave, wavestep )\n            fextRed = array( [ max( 0, a * wave + b ) for wave in wextRed ] )\n\n            w = append( w, wextRed )\n            f = append( f, fextRed )\n        \n        for i in range( len( w ) ) :\n            print >> fout, \"%7.2f  %10.2f  %12.7e\"%( d[0], w[i], f[i] )\n    fout.close() \n\n    return( newsedfile )\n\n\n\ndef extrapolatesed_linfit(sedfile, newsedfile, minwave=MINWAVE, maxwave=MAXWAVE, \n                          Npt=2, Nsmooth=0, forceslope=True, verbose=False ):\n    \"\"\" use a linear fit of the first/last Npt  points on the SED\n    to extrapolate to the blue and red.  \n\n    Set Nsmooth to a positive integer to set the window size for median \n    smoothing of the input spectrum before the linear fitting. \n    \n    With forceslope=True, check if the linear fit returns a slope that would \n    send the tail upward (i.e. a positive derivative on the red side, negative \n    on the  blue side).  If so, then re-do the fit using just the first/last \n    point and the peak flux point, in order to guarantee a downward sloping tail.\n    \"\"\"\n\n    from scipy import interpolate as scint\n    from scipy import stats\n    import shutil\n\n    medsmooth = lambda f,N : array( [ median( f[max(0,i-N):min(len(f),max(0,i-N)+2*N)]) for i in range(len(f)) ] )\n    \n    dlist,wlist,flist = getsed( sedfile ) \n    dlistnew, wlistnew, flistnew = [],[],[]\n\n    fout = open( newsedfile, 'w' )\n    for i in range( len(dlist) ) : \n        d,w,f = dlist[i],wlist[i],flist[i]\n\n        if Nsmooth : ffit = medsmooth( f, Nsmooth )\n        else : ffit = f\n        wavestep = w[1] - w[0]\n\n        # blueward linear extrapolation from first N points\n        wN = w[:Npt]\n        fN = ffit[:Npt]\n        (a,b,rval,pval,stderr)=stats.linregress(wN,fN)\n        if forceslope and a < 0 : \n            # re-do blueward linear extrapolation using the peak\n            # in order to guarantee a downward slope\n            print( \"  re-fitting %s day %i to ensure downward slope to the blue\"%(sedfile,d[0]))\n            wN = [ w[0], w[ ffit.argmax() ] ]\n            fN = [ f[0], ffit.max() ]\n            (a,b,rval,pval,stderr)=stats.linregress(wN,fN)\n        Nbluestep = len( arange( minwave, w[0], wavestep ) )\n        wextBlue = sorted( [ w[0] -(i+1)*wavestep for i in range(Nbluestep) ] )\n        fextBlue = array( [ max( 0, a * wave + b ) for wave in wextBlue ] )\n\n        # redward linear extrapolation from last N points\n        wN = w[-Npt:]\n        fN = ffit[-Npt:]\n        (a,b,rval,pval,stderr)=stats.linregress(wN,fN)\n        if forceslope and a > 0 : \n            # re-do redward  linear extrapolation using the peak\n            # in order to guarantee a downward slope\n            if verbose : print( \"  re-fitting %s day %i to ensure downward slope to the red\"%(sedfile, d[0]) )\n            wN = [ w[ ffit.argmax() ], w[-1] ]\n            fN = [ ffit.max(), ffit[-1],  ]\n            (a,b,rval,pval,stderr)=stats.linregress(wN,fN)\n        Nredstep = len( arange( w[-1], maxwave,  wavestep ) )\n        wextRed =  sorted( [ w[-1] + (i+1)*wavestep for i in range(Nredstep) ] )\n        fextRed = array( [ max( 0, a * wave + b ) for wave in wextRed ] )\n\n        wnew = append( append( wextBlue, w ), wextRed )\n        fnew = append( append( fextBlue, f ), fextRed )\n        # dnew = zeros( len(wnew) ) + d[0]\n        \n        for i in range( len( wnew ) ) :\n            print >> fout, \"%7.2f  %10.2f  %12.7e\"%( d[0], wnew[i], fnew[i] )\n    fout.close() \n\n    return( newsedfile )\n\n\ndef extrapolatesed_flatline(sedfile, newsedfile, minwave=MINWAVE, maxwave=MAXWAVE ):\n    \"\"\" extrapolate to the red and the blue using a flatline. i.e. the \n    extrapolated flux is fixed to the endpoint values\n    \"\"\"\n    from scipy import interpolate as scint\n    from scipy import stats\n    import shutil\n    \n    dlist,wlist,flist = getsed( sedfile ) \n    dlistnew, wlistnew, flistnew = [],[],[]\n\n    fout = open( newsedfile, 'w' )\n    for i in range( len(dlist) ) : \n        d,w,f = dlist[i],wlist[i],flist[i]\n\n        wavestep = w[1] - w[0]\n        # blueward flatline extrapolation from first point\n        Nbluestep = len( arange( minwave, w[0], wavestep ) )\n        wextBlue = sorted( [ w[0] -(i+1)*wavestep for i in range(Nbluestep) ] )\n        fextBlue = array( [ f[0] for wave in wextBlue ] )\n\n        # redward flatline extrapolation from last point\n        Nredstep = len( arange( w[-1], maxwave,  wavestep ) )\n        wextRed =  sorted( [ w[-1] + (i+1)*wavestep for i in range(Nredstep) ] )\n        fextRed = array( [ f[-1]  for wave in wextRed ] )\n\n        wnew = append( append( wextBlue, w ), wextRed )\n        fnew = append( append( fextBlue, f ), fextRed )\n        # dnew = zeros( len(wnew) ) + d[0]\n        \n        for i in range( len( wnew ) ) :\n            print >> fout, \"%5.1f  %10i  %12.7e\"%( d[0], wnew[i], fnew[i] )\n    fout.close() \n\n    return( newsedfile )\n\n\ndef extendNon1a(origdir = \"snsed/non1a.ORIG\", verbose=True ):\n    \"\"\" Extrapolate each of the Non-Ia template sed files,\n    preserving a pristine copy in $SNDATA_ROOT/snsed/non1a.ORIG\n    \"\"\"\n    import glob\n    import shutil\n\n    origdir = os.path.join(sndataroot, origdir)\n    non1adir = os.path.join(sndataroot, \"snsed/non1a\")\n    if not os.path.isdir( origdir ) :\n        os.rename( non1adir, origdir ) \n    if not os.path.isdir( non1adir ) :\n        os.mkdir( non1adir )\n\n    otherstufflist = glob.glob(\"%s/*.DAT\"%(origdir)) + glob.glob(\"%s/*.LIST\"%(origdir)) + glob.glob(\"%s/*.INPUT\"%(origdir))\n    for otherfile in otherstufflist : \n        newfile =  os.path.join( non1adir, os.path.basename( otherfile ) )\n        shutil.copy( otherfile, newfile )\n        \n    sedlist = glob.glob(\"%s/*.SED\"%origdir)\n    for sedfile in sedlist : \n        newsedfile =  os.path.join( non1adir, os.path.basename( sedfile ) )\n\n        if 'SDSS-012842' in sedfile or 'SDSS-013449' in sedfile : \n            # These are already super-smooth blackbodies for the IIn templates\n            # 2-pt linear extrapolation is best.\n            Npt = 2\n            Nsmooth=0\n            print(\"EXTRAPOLATING %s\\n    ==> %s\"%(sedfile, newsedfile) )\n            extrapolatesed_linfit(sedfile, newsedfile, minwave=MINWAVE, maxwave=MAXWAVE, \n                                  Npt=Npt, Nsmooth=Nsmooth, forceslope=True  )\n            print(\"     Done with %s.\\a\\a\\a\"%newsedfile)\n\n\n        else : \n            # for all other templates, we use a fixed blue anchor point \n            # and on the red side we fit a lot of points so we don't \n            # get thrown around by sharp spectral features\n            Nred = 100\n            Nsmooth = 20\n\n            print(\"EXTRAPOLATING %s\\n    ==> %s\"%(sedfile, newsedfile) )\n            extrapolatesed( sedfile, newsedfile, minwave=MINWAVE, maxwave=MAXWAVE, \n                            Bextwave=2000, Bfrac=0.2, Brefwave=2800, \n                            Nred = 100, Nsmooth=20, verbose=verbose )\n            print(\"     Done with %s.\\a\\a\\a\"%newsedfile)\n\n\n\ndef extendSALT2_temp0( salt2dir = 'models/SALT2/SALT2.Guy10_UV2IR', \n                       salt2srcdir = 'models/SALT2/SALT2.Guy10_LAMOPEN', \n                       tailsedfile = 'snsed/Hsiao07.extrap.dat',\n                       wjoinblue = 2800, wjoinred = 8500 ,\n                       wmin = MINWAVE, wmax = MAXWAVE ):\n    \"\"\" extend the salt2 Template_0 model component \n    by adopting the UV and IR tails from another SED model. \n    The default is to use SR's extrapolated modification \n    of the Hsiao 2007 sed model, scaled and joined at the \n    wjoin wavelengths, and extrapolated out to wmin and wmax. \n    \"\"\"\n    import shutil\n    sndataroot = os.environ['SNDATA_ROOT']\n \n    salt2dir = os.path.join( sndataroot, salt2dir ) \n    salt2srcdir = os.path.join( sndataroot, salt2srcdir ) \n    \n    temp0fileIN = os.path.join( salt2srcdir, 'salt2_template_0.dat' ) \n    temp0fileOUT = os.path.join( salt2dir, 'salt2_template_0.dat' ) \n    temp0dat = getsed( sedfile=temp0fileIN ) \n\n    tailsedfile = os.path.join( sndataroot, tailsedfile ) \n\n    taildat = getsed( sedfile=tailsedfile ) \n    \n    dt,wt,ft = loadtxt( tailsedfile, unpack=True ) \n    taildays = unique( dt ) \n\n    # build up modified template from day -20 to +50\n    outlines = []\n    for i in range( 71 ) : \n        thisday = i - 20\n\n        # get the tail SED for this day\n        it = where( taildays == thisday )[0]\n        dt = taildat[0][it]\n        wt = taildat[1][it]\n        ft = taildat[2][it]\n\n        #if thisday > 50 : \n        #    d0new = dt\n        #    w0new = wt\n        #    f0new = ft * (bluescale+redscale)/2.\n        #else : \n\n        # get the SALT2 template SED for this day\n        d0 = temp0dat[0][i]\n        w0 = temp0dat[1][i]\n        f0 = temp0dat[2][i]\n        print( 'splicing tail onto template for day : %i'%thisday )\n\n        i0blue = argmin(  abs(w0-wjoinblue) )\n        itblue = argmin( abs( wt-wjoinblue))\n\n        i0red = argmin(  abs(w0-wjoinred) )\n        itred = argmin( abs( wt-wjoinred))\n\n        itmin = argmin( abs( wt-wmin))\n        itmax = argmin( abs( wt-wmax))\n\n        bluescale = f0[i0blue]/ft[itblue] \n        redscale = f0[i0red]/ft[itred] \n\n        d0new = dt.tolist()[itmin:itblue] + d0.tolist()[i0blue:i0red-1] + dt.tolist()[itred:itmax+1]\n        w0new = wt.tolist()[itmin:itblue] + w0.tolist()[i0blue:i0red-1] + wt.tolist()[itred:itmax+1]\n        f0new = (bluescale*ft).tolist()[itmin:itblue] + f0.tolist()[i0blue:i0red-1] + (redscale*ft).tolist()[itred:itmax+1]\n\n        # plot it\n        clf()\n        plot( w0, f0, ls='-',color='b', lw=1, label='Input SALT2 Model')\n        plot( wt, (bluescale+redscale)/2. * ft, ls=':',color='r', lw=1, label='SED model')\n        plot( w0new, f0new, ls='--',color='k', lw=2, label='Extrapolated SALT2 model')\n        legend()\n        draw()\n        #raw_input('return to continue')\n\n        # append to the list of output data lines\n        for j in range( len( d0new ) ) :\n            outlines.append( \"%6.2f    %12i  %12.7e\\n\"%(\n                    d0new[j], w0new[j], f0new[j] ) )\n\n    # write it out to the new template sed .dat file\n    fout = open( temp0fileOUT, 'w' ) \n    fout.writelines( outlines ) \n    fout.close() \n        \n\n\ndef extendSALT2_temp1( salt2dir = 'models/SALT2/SALT2.Guy10_UV2IR', \n                       salt2srcdir = 'models/SALT2/SALT2.Guy10_LAMOPEN', \n                       # wjoinblue = 2000, wjoinred = 8500 ,\n                       wjoinblue = None, wjoinred = None,\n                       wmin = MINWAVE, wmax = MAXWAVE,\n                       wstep = 10 ):\n    \"\"\" extend the salt2 Template_1 model component \n    with a flat line at 0 to the blue and to the red.\n    If join wavelengths are not provided, uses the \n    end points of the input spectrum\n    \"\"\"\n    import shutil\n    sndataroot = os.environ['SNDATA_ROOT']\n \n    salt2dir = os.path.join( sndataroot, salt2dir ) \n    salt2srcdir = os.path.join( sndataroot, salt2srcdir ) \n    \n    temp1fileIN = os.path.join( salt2srcdir, 'salt2_template_1.dat' ) \n    temp1fileOUT = os.path.join( salt2dir, 'salt2_template_1.dat' ) \n    temp1dat = getsed( sedfile=temp1fileIN ) \n\n    # build up modified template from day -20 to +50\n    outlines = []\n    for i in range( 71 ) : \n        thisday = i - 20\n\n        # get the SALT2 template SED for this day\n        d1 = temp1dat[0][i]\n        w1 = temp1dat[1][i]\n        f1 = temp1dat[2][i]\n        print( 'extrapolating with flatline onto template for day : %i'%thisday )\n        \n        if wjoinblue==None : wjoinblue=w1[0]\n        if wjoinred==None : wjoinred=w1[-1]\n\n        i1blue = argmin(  abs(w1-wjoinblue) )\n        i1red = argmin(  abs(w1-wjoinred) )\n        \n        Nblue = int((wjoinblue-wmin )/wstep + 1)\n        Nred = int((wmax -wjoinred )/wstep + 1)\n\n        d1new =  (ones(Nblue)*thisday).tolist() + d1.tolist()[i1blue+1:i1red-1] + (ones(Nred)*thisday).tolist()\n        w1new = arange(wmin,wmin+Nblue*wstep,wstep).tolist() + w1.tolist()[i1blue+1:i1red-1] + arange(wjoinred,wjoinred+Nred*wstep,wstep).tolist()\n        f1new = zeros(Nblue).tolist() + f1.tolist()[i1blue+1:i1red-1] + zeros(Nred).tolist()\n\n        # plot it\n        clf()\n        plot( w1, f1, ls='-',color='r', lw=1)\n        plot( w1new, f1new, ls='--',color='k', lw=2)\n        draw()\n        #raw_input('return to continue')\n\n        # append to the list of output data lines\n        for j in range( len( d1new ) ) :\n            outlines.append( \"%6.2f    %12i  %12.7e\\n\"%(\n                    d1new[j], w1new[j], f1new[j] ) )\n\n    # write it out to the new template sed .dat file\n    fout = open( temp1fileOUT, 'w' ) \n    fout.writelines( outlines ) \n    fout.close() \n        \n\n\ndef extendSALT2_flatline( salt2dir = 'models/SALT2/SALT2.Guy10_UV2IR', \n                          salt2srcdir = 'models/SALT2/SALT2.Guy10_LAMOPEN', \n                          wjoinblue = 2000, wjoinred = 8500 ,\n                          wmin = MINWAVE, wmax = MAXWAVE,\n                          wstep = 10, showplots=False ):\n    \"\"\" extrapolate the *lc* and *spec* .dat files for SALT2\n    using a flatline to the blue and red \"\"\"\n\n    sndataroot = os.environ['SNDATA_ROOT']\n    salt2dir = os.path.join( sndataroot, salt2dir ) \n    salt2srcdir = os.path.join( sndataroot, salt2srcdir ) \n    \n    filelist = ['salt2_lc_dispersion_scaling.dat',\n                'salt2_lc_relative_covariance_01.dat',\n                'salt2_lc_relative_variance_0.dat',\n                'salt2_lc_relative_variance_1.dat',\n                'salt2_spec_covariance_01.dat',\n                'salt2_spec_variance_0.dat',\n                'salt2_spec_variance_1.dat']\n    \n    #for filename in  ['salt2_lc_dispersion_scaling.dat']: \n    #for filename in  ['salt2_lc_relative_covariance_01.dat']:\n    for filename in filelist : \n        infile = os.path.join( salt2srcdir, filename )\n        outfile = os.path.join( salt2dir, filename )\n\n        newsedfile = extrapolatesed_flatline( infile, outfile, minwave=wmin, maxwave=wmax,\n                                              wjoinblue=wjoinblue, wjoinred=wjoinred )\n        \n        # plot it\n        if showplots: \n            #for d in range(-20,50) : \n            for d in [-10,-5,0,5,10,15,20,25,30,35,40,45,50] : \n                clf()\n                plotsed( infile, day=d, ls='-',color='r', lw=1) \n                plotsed( outfile,day=d, ls='--',color='k', lw=2)\n                print( '%s : day %i'%(filename,d) )\n                draw()\n                # raw_input('%s : day %i.  return to continue'%(filename,d)) \n\n    \n\ndef plotAll(): \n    \"\"\" \n    read in and plot all the non1a template SEDs at peak, \n    in three panels, with the Ia template for comparison,\n    \"\"\"\n    ioff()\n    ax1 = subplot( 131 )\n    # plot the type II-L in purple\n    plotsed( os.path.join(sndataroot,'snsed/non1a/Nugent+Scolnic_IIL.SED'), day=0, normalize=2, color='b', lw=0.5, label='II-L' )\n    # plot the type IIn's in orange \n    for sed in ['SDSS-012842','SDSS-013449'] : \n        plotsed( os.path.join(sndataroot,'snsed/non1a/%s.SED'%sed), day=0.5, normalize=2, color='b', lw=0.5, label=sed )\n    # Ia in red\n    plotsed( os.path.join(sndataroot,'snsed/Hsiao07.extrap.dat'), day=0, normalize=2, color='r', label='Ia (Hsiao)', lw=2 )\n    plotsed( os.path.join(sndataroot,'snsed/Hsiao07.dat'), day=0, normalize=2, color='k', label='Ia (Hsiao)', lw=1, ls=':' )\n    title('Type II-L and IIn Templates')\n    #legend()\n    draw()\n\n    subplot( 132, sharex=ax1, sharey=ax1 )\n    # plot the type IIP's in blue \n    IIpsedlist = [ 'SDSS-000018','SDSS-003818','SDSS-013376','SDSS-014450','SDSS-014599','SDSS-015031','SDSS-015320',\n                   'SDSS-015339','SDSS-017564','SDSS-017862','SDSS-018109','SDSS-018297','SDSS-018408','SDSS-018441',\n                   'SDSS-018457','SDSS-018590','SDSS-018596','SDSS-018700','SDSS-018713','SDSS-018734','SDSS-018793',\n                   'SDSS-018834','SDSS-018892','SDSS-020038' ]\n    for sed in IIpsedlist :\n        plotsed( os.path.join(sndataroot,'snsed/non1a/%s.SED'%sed), day=0.5, normalize=2, color='b', lw=0.5, label=sed )\n    # Ia in red\n    plotsed( os.path.join(sndataroot,'snsed/Hsiao07.extrap.dat'), day=0, normalize=2, color='r', label='Ia (Hsiao)', lw=2 )\n    plotsed( os.path.join(sndataroot,'snsed/Hsiao07.dat'), day=0, normalize=2, color='k', label='Ia (Hsiao)', lw=1, ls=':' )\n    #legend()\n    title('Type II-P Templates')\n    draw()\n\n    subplot( 133, sharex=ax1, sharey=ax1  )\n    Ibclist =  [ 'CSP-2004gv','CSP-2006ep','CSP-2007Y','SDSS-000020','SDSS-002744','SDSS-014492',\n                 'SDSS-019323','SNLS-04D1la','SNLS-04D4jv','CSP-2004fe','CSP-2004gq','SDSS-004012',\n                 'SDSS-013195','SDSS-014475','SDSS-015475','SDSS-017548' ]\n    for sed in Ibclist :\n        plotsed( os.path.join(sndataroot,'snsed/non1a/%s.SED'%sed), day=0.5, normalize=2, color='g', lw=0.5, label=sed )\n    # Ia in red\n    plotsed( os.path.join(sndataroot,'snsed/Hsiao07.extrap.dat'), day=0, normalize=2, color='r', label='Ia (Hsiao)', lw=2 )\n    plotsed( os.path.join(sndataroot,'snsed/Hsiao07.dat'), day=0, normalize=2, color='k', label='Ia (Hsiao)', lw=1, ls=':' )\n    title('Type Ib and Ic Templates', color='g')\n    #legend()\n    ion()\n\n    suptitle( 'Comparing SNANA CC and Ia templates at peak' )\n    draw()\n\n\n\n\ndef extratest( sed, **kwarg ) :\n    sedorig = '/usr/local/SNDATA_ROOT/snsed/non1a.ORIG/'+sed+'.SED'\n    sednew  = '/usr/local/SNDATA_ROOT/snsed/non1a/'+sed+'test.SED'\n    extrapolatesed_linfit( sedorig, sednew, **kwarg )\n    clf()\n    plotsed( sednew, day=0.5, color='g', ls='-', lw=1, normalize=2, label='new'  )\n    plotsed( sedorig, day=0.5, color='b', ls='-', lw=3, normalize=2, label='orig'  )\n\n    plotsed( '/usr/local/SNDATA_ROOT/snsed/Hsiao07.extrap.dat', day=0, normalize=2, color='r', label='Ia (Hsiao)', lw=2 )\n\n    ax = gca()\n    text( 0.1,0.95, sed, ha='left',va='top', transform=ax.transAxes )\n    legend( )\n\n    \n", "meta": {"hexsha": "9c4282e92d97e145ab0d79043dec027af4c7d07e", "size": 24581, "ext": "py", "lang": "Python", "max_stars_repo_path": "snsed.py", "max_stars_repo_name": "srodney/stardust", "max_stars_repo_head_hexsha": "27742c17cfc17df2f6d016b33ecb32f9b0f9950d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "snsed.py", "max_issues_repo_name": "srodney/stardust", "max_issues_repo_head_hexsha": "27742c17cfc17df2f6d016b33ecb32f9b0f9950d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "snsed.py", "max_forks_repo_name": "srodney/stardust", "max_forks_repo_head_hexsha": "27742c17cfc17df2f6d016b33ecb32f9b0f9950d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-10-06T17:32:08.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-04T17:49:06.000Z", "avg_line_length": 40.4958813839, "max_line_length": 146, "alphanum_fraction": 0.5762174037, "include": true, "reason": "from numpy,from scipy", "num_tokens": 7765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.3007455789412415, "lm_q1q2_score": 0.19374785261872618}}
{"text": "import os\nimport numpy as np\nfrom .decoder import AmbiDecoder\nfrom .hrir import CIPIC_HRIR\nfrom .position import Position, PositionalSource, MovingSource\nfrom scipy.ndimage.interpolation import shift\n#from tdesigns import get_tDesign\n\nC = 343.     # Speed of sound [m/s]\n\n\nclass VirtualStereoMic(object):\n    def __init__(self, radius=0.1):\n        self.radius = radius\n        self.lmic_pos = Position(0, radius, 0, 'cartesian')\n        self.rmic_pos = Position(0, -radius, 0, 'cartesian')\n\n    def binauralize(self, sources):\n        if isinstance(sources, PositionalSource):\n            sources = [sources]\n\n        l_signal, r_signal = 0, 0.\n        for src in sources:\n            l_dist = np.sqrt(((src.position.coords('cartesian') - self.lmic_pos.coords('cartesian'))**2).sum())\n            r_dist = np.sqrt(((src.position.coords('cartesian') - self.rmic_pos.coords('cartesian'))**2).sum())\n\n            # Time delay\n            l_delay, r_delay = int(l_dist / C * src.sample_rate), int(r_dist / C * src.sample_rate)\n\n            # Attenuation is frequency dependent, but lets simplify.\n            l_attn, r_attn = 1 / (1. + l_dist), 1 / (1. + r_dist)\n\n            l_signal += l_attn * shift(src.signal, l_delay, cval=0.) / len(sources)\n            r_signal += r_attn * shift(src.signal, r_delay, cval=0.) / len(sources)\n\n        return np.stack((l_signal, r_signal), axis=1)\n\n    def binauralize_frame(self, sources, output, frame_no):\n        if isinstance(sources, PositionalSource):\n            sources = [sources]\n\n        for src in sources:\n            l_dist = np.sqrt(((src.position.coords('cartesian') - self.lmic_pos.coords('cartesian'))**2).sum())\n            r_dist = np.sqrt(((src.position.coords('cartesian') - self.rmic_pos.coords('cartesian'))**2).sum())\n\n            # Time delay\n            l_delay, r_delay = int(l_dist / C * src.sample_rate), int(r_dist / C * src.sample_rate)\n\n            # Attenuation is frequency dependent, but lets simplify.\n            l_attn, r_attn = 1 / (1. + l_dist), 1 / (1. + r_dist)\n\n            if frame_no-l_delay >= 0:\n                output[frame_no, 0] += l_attn * src.signal[frame_no-l_delay] / len(sources)\n            if frame_no-r_delay >= 0:\n                output[frame_no, 1] += r_attn * src.signal[frame_no-r_delay] / len(sources)\n\n\nclass Convolvotron(object):\n    def __init__(self, cipic_dir):\n        assert os.path.exists(cipic_dir)\n        self.hrir_db = CIPIC_HRIR(cipic_dir)\n\n    def binauralize(self, sources):\n        if isinstance(sources, PositionalSource):\n            sources = [sources]\n        num_frames = max([src.signal.shape[0] for src in sources])\n        stereo = np.zeros((num_frames, 2))\n        for src in sources:\n            left_hrir, right_hrir = self.hrir_db.get_closest(src.position)[1:]\n            left_signal = np.convolve(src.signal, np.flip(left_hrir, axis=0), 'valid')\n            right_signal = np.convolve(src.signal, np.flip(right_hrir, axis=0), 'valid')\n\n            n_valid, i_start = left_signal.shape[0], left_hrir.shape[0] - 1\n            stereo[i_start:(i_start + n_valid), 0] += left_signal\n            stereo[i_start:(i_start + n_valid), 1] += right_signal\n\n        return stereo\n\n    def binauralize_frame(self, sources, output, frame_no):\n        if isinstance(sources, PositionalSource):\n            sources = [sources]\n\n        for src in sources:\n            left_hrir, right_hrir = self.hrir_db.get_closest(src.position)[1:]\n\n            i_start = frame_no - left_hrir.size + 1 if frame_no >= left_hrir.size else 0\n            i_end = frame_no + 1\n            i_range = i_end - i_start\n\n            output[frame_no, 0] = (src.signal[i_start:i_end] * left_hrir[-i_range:]).sum()\n            output[frame_no, 1] = (src.signal[i_start:i_end] * right_hrir[-i_range:]).sum()\n\n\nclass SourceBinauralizer(object):\n    def __init__(self, use_hrtfs=True, cipic_dir=None):\n        self.use_hrts = use_hrtfs\n        if use_hrtfs:\n            self.convolvotron = Convolvotron(cipic_dir)\n        else:\n            self.stereo_mic = VirtualStereoMic()\n\n    def binauralize(self, sources):\n        if isinstance(sources, PositionalSource):\n            sources = [sources]\n        assert isinstance(sources, list) and all([isinstance(src, PositionalSource) for src in sources])\n        assert all([src.sample_rate == sources[0].sample_rate for src in sources])\n\n        if self.use_hrts:\n            return self.convolvotron.binauralize(sources)\n        else:\n            return self.stereo_mic.binauralize(sources)\n\n    def binauralize_frame(self, sources, output, frame_no):\n        if isinstance(sources, PositionalSource):\n            sources = [sources]\n        assert isinstance(sources, list) and all([isinstance(src, PositionalSource) for src in sources])\n        assert all([src.sample_rate == sources[0].sample_rate for src in sources])\n\n        if self.use_hrts:\n            return self.convolvotron.binauralize_frame(sources, output, frame_no)\n        else:\n            return self.stereo_mic.binauralize_frame(sources, output, frame_no)\n\n\nclass AmbisonicBinauralizer(object):\n    def __init__(self, ambi_format, method='projection', use_hrtfs=False, cipic_dir=None):\n        self.source_bin = SourceBinauralizer(cipic_dir=cipic_dir, use_hrtfs=use_hrtfs)\n        self.fmt = ambi_format\n        self.method = method\n\n        # Initialize speakers\n        if self.method == 'pseudoinv':\n            self.speaker_pos = map(lambda x: Position(x[0], x[1], x[2], 'cartesian'), get_tDesign(self.fmt.order))\n            map(lambda p: p.set_radius(self.fmt.radius), self.speaker_pos)\n            # speakers_phi = (2. * np.arange(2*self.fmt.num_channels) / float(2*self.fmt.num_channels) - 1.) * np.pi\n            # self.speaker_pos = map(lambda x: Position(x, 0, self.fmt.radius, 'polar'), speakers_phi)\n        elif self.method == 'projection':\n            speakers_phi = (2. * np.arange(2*self.fmt.num_channels) / float(2*self.fmt.num_channels) - 1.) * np.pi\n            # self.speaker_pos = map(lambda x: Position(x, 0, self.fmt.radius, 'polar'), speakers_phi)\n            self.speaker_pos = [Position(x, 0, self.fmt.radius, 'polar') for x in speakers_phi]\n        else:\n            raise ValueError('Unknown decoding method. Options: projection and pseudoinv')\n        self.n_speakers = len(self.speaker_pos)\n        self.ambi_decoder = AmbiDecoder(self.speaker_pos, self.fmt, method=self.method)\n\n    def binauralize(self, ambi):\n        # Decode ambisonics into speakers\n        speakers = self.ambi_decoder.decode(ambi)\n\n        # Binauralize speaker as if they were point sources\n        sources = [PositionalSource(speakers[:, i], self.speaker_pos[i], self.fmt.sample_rate) for i in range(self.n_speakers)]\n        stereo = self.source_bin.binauralize(sources)\n\n        return stereo\n\n\nclass DirectAmbisonicBinauralizer(object):\n    def __init__(self, ambi_format, method='projection'):\n        self.fmt = ambi_format\n        self.method = method\n\n        # Initialize ear position\n        self.ear_pos = [Position(0, 0.1, 0, 'cartesian'), Position(0, -0.1, 0, 'cartesian')]\n        self.ambi_decoder = AmbiDecoder(self.ear_pos, self.fmt, method=self.method)\n\n    def binauralize(self, ambi):\n        return self.ambi_decoder.decode(ambi)\n\n\ndef test_convolvotron():\n    from pyutils.iolib.audio import load_wav, save_wav\n    convolvotron = Convolvotron('hrtfs/cipic_subj3')\n    mono, rate = load_wav('wav_test/piano.wav')\n    mono = mono[:, 0]\n\n    positions = [[float(num) for num in l.strip().split()] for l in open('wav_test/piano_stat_position.txt', 'r')]\n    positions = [Position(p[0], p[1], p[2], 'polar') for p in positions]\n    source = PositionalSource(mono, positions[0], rate)\n\n    stereo = convolvotron.binauralize([source])\n    save_wav('/tmp/output.wav', stereo, rate)\n    os.system('play /tmp/output.wav')\n    os.remove('/tmp/output.wav')\n\n    positions = [[float(num) for num in l.strip().split()] for l in open('wav_test/piano_mov_position.txt', 'r')]\n    positions = [Position(p[0], p[1], p[2], 'polar') for p in positions]\n    source = MovingSource(mono, positions, rate)\n\n    stereo = np.zeros((mono.shape[0], 2))\n    while source.tic():\n        convolvotron.binauralize_frame([source], stereo, source.cur_idx)\n    save_wav('/tmp/output.wav', stereo, rate)\n    os.system('play /tmp/output.wav')\n    os.remove('/tmp/output.wav')\n\n\ndef test_virtual_mic():\n    from pyutils.iolib.audio import load_wav, save_wav\n    mic = VirtualStereoMic()\n    mono, rate = load_wav('wav_test/piano.wav')\n    mono = mono[:, 0]\n\n    positions = [[float(num) for num in l.strip().split()] for l in open('wav_test/piano_stat_position.txt', 'r')]\n    positions = [Position(p[0], p[1], p[2], 'polar') for p in positions]\n    source = PositionalSource(mono, positions[0], rate)\n\n    stereo = mic.binauralize([source])\n    save_wav('/tmp/output.wav', stereo, rate)\n    os.system('play /tmp/output.wav')\n    os.remove('/tmp/output.wav')\n\n    positions = [[float(num) for num in l.strip().split()] for l in open('wav_test/piano_mov_position.txt', 'r')]\n    positions = [Position(p[0], p[1], p[2], 'polar') for p in positions]\n    source = MovingSource(mono, positions, rate)\n\n    stereo = np.zeros((mono.shape[0], 2))\n    while source.tic():\n        mic.binauralize_frame([source], stereo, source.cur_idx)\n    save_wav('/tmp/output.wav', stereo, rate)\n    os.system('play /tmp/output.wav')\n    os.remove('/tmp/output.wav')\n\n\ndef test_source_binauralizer():\n    from pyutils.iolib.audio import load_wav, save_wav\n    from pyutils.iolib.position import read_position_file\n\n    # binauralizer = SourceBinauralizer(use_hrtfs=True, cipic_dir='hrtfs/cipic_subj3')\n    binauralizer = SourceBinauralizer(use_hrtfs=False)\n\n    # Static source\n    sample = 'wav_test/gen_synthetic-S1'\n    positions, wav_fns, _, sample_ids = read_position_file(sample+'-position.txt')\n    mono, rate = load_wav(wav_fns[sample_ids[0]])\n    source = PositionalSource(mono[:, 0], positions[sample_ids[0]][0], rate)\n    stereo = binauralizer.binauralize([source])\n\n    save_wav('/tmp/output.wav', stereo / np.abs(stereo).max(), rate)\n    os.system('play /tmp/output.wav')\n    os.remove('/tmp/output.wav')\n\n    # Moving source\n    sample = 'wav_test/gen_synthetic-M1'\n    positions, wav_fns, _, sample_ids = read_position_file(sample+'-position.txt')\n    mono, rate = load_wav(wav_fns[sample_ids[0]])\n    source = MovingSource(mono[:, 0], positions[sample_ids[0]], rate)\n    stereo = np.zeros((mono.shape[0], 2))\n    while source.tic():\n        binauralizer.binauralize_frame([source], stereo, source.cur_idx)\n\n    save_wav('/tmp/output.wav', stereo / np.abs(stereo).max(), rate)\n    os.system('play /tmp/output.wav')\n    os.remove('/tmp/output.wav')\n\n\ndef test_ambisonics_binauralizer():\n    from pyutils.iolib.audio import load_wav, save_wav\n    from pyutils.ambisonics.common import AmbiFormat\n\n    sample = 'wav_test/gen_synthetic-S1'\n    ambi, rate = load_wav(sample+'-ambix.wav')\n\n    fmt = AmbiFormat(1, rate)\n    binauralizer = DirectAmbisonicBinauralizer(fmt, method='pseudoinv')\n    # binauralizer = AmbisonicBinauralizer(fmt, method='projection', use_hrtfs=True, cipic_dir='hrtfs/cipic_subj3')\n\n    stereo = binauralizer.binauralize(ambi)\n\n    save_wav('/tmp/output.wav', stereo / np.abs(stereo).max(), rate)\n    os.system('play /tmp/output.wav')\n    os.remove('/tmp/output.wav')\n\n    sample = 'wav_test/gen_synthetic-M1'\n    ambi, rate = load_wav(sample+'-ambix.wav')\n    stereo = binauralizer.binauralize(ambi)\n\n    save_wav('/tmp/output.wav', stereo / np.abs(stereo).max(), rate)\n    os.system('play /tmp/output.wav')\n    os.remove('/tmp/output.wav')\n\n\nif __name__ == '__main__':\n    # test_ambisonics_binauralizer()\n    test_source_binauralizer()\n    # test_convolvotron()\n    # test_virtual_mic()\n", "meta": {"hexsha": "53a2c02906291c1dd7707a16839be893e7dc6a3f", "size": 11794, "ext": "py", "lang": "Python", "max_stars_repo_path": "ambisonics/binauralizer.py", "max_stars_repo_name": "realningzheng/BinauralAudioTools", "max_stars_repo_head_hexsha": "f7ad77d6dfc92068a29a01ab99ceb21497583475", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-04T14:11:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T14:11:14.000Z", "max_issues_repo_path": "ambisonics/binauralizer.py", "max_issues_repo_name": "realningzheng/BinauralAudioTools", "max_issues_repo_head_hexsha": "f7ad77d6dfc92068a29a01ab99ceb21497583475", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ambisonics/binauralizer.py", "max_forks_repo_name": "realningzheng/BinauralAudioTools", "max_forks_repo_head_hexsha": "f7ad77d6dfc92068a29a01ab99ceb21497583475", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-27T03:35:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T06:06:11.000Z", "avg_line_length": 41.0940766551, "max_line_length": 127, "alphanum_fraction": 0.6543157538, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.19373854569841625}}
{"text": "#!/usr/bin/env python\n## top-level script for generating probability distributions for component scores as part of CMS 2.0. \n## last updated: 06.24.2017 \tvitti@broadinstitute.org\n\nimport matplotlib as mp \nmp.use('agg') \nfrom dists.freqbins_func import run_traj, get_bin_strings, get_bins, check_create_dir, check_create_file, write_bin_paramfile, execute, get_concat_files, get_info_from_tped_name\nfrom dists.scores_func import calc_ihs, calc_delihh, calc_xpehh, calc_fst_deldaf, read_neut_normfile, norm_neut_ihs, norm_sel_ihs, norm_neut_xpehh, norm_sel_xpehh, get_sim_compscore_files, get_scores_from_files, get_compscores_from_files_flatten\nfrom dists.likes_func import plot_pdf_comparison_from_scores, get_plot_pdf_params, quick_load_likes, quick_cl_from_likes, quick_clr_from_likes, get_likes_filenames, write_master_likesfile, get_master_likefiles, get_likes_savestrings\nimport numpy as np\nimport argparse\nimport sys, os, subprocess\nimport matplotlib.pyplot as plt\n\n#############################\n## DEFINE ARGUMENT PARSER ###\n#############################\ndef full_parser_likes_from_model():\n\tparser=argparse.ArgumentParser(description=\"This script contains command-line utilities for generating probability distributions for component scores from pre-specified demographic model(s).\")\n\tsubparsers = parser.add_subparsers(help=\"sub-commands\")\n\tgenerate_sel_bins_parser = subparsers.add_parser('generate_sel_bins', help=\"Pre-processing step: generate directories with parameter files divided by selDAF, according to specified bins\") #nix or clean\n\tgenerate_sel_bins_parser.add_argument('outputDir', type=str, action='store', help='location to write cosi output')\n\t\n\t#####################################\n\t## SIMULATE SELECTION TRAJECTORIES ##\n\t#####################################\n\tget_sel_traj_parser = subparsers.add_parser('get_sel_traj', help='Run forward simulations of selection trajectories to populate selscenarios by final allele frequency before running coalescent simulations for entire sample.')\n\tget_sel_traj_parser.add_argument('traj_outputname', type=str, action='store', help=\"write to file\")\t\n\tget_sel_traj_parser.add_argument('--maxAttempts', type=int, action='store', help='maximum number of attempts to generate a trajectory before re-sampling selection coefficient / start time', default=100)\n\t\n\t##########################\n\t## RUN FULL SIMULATIONS ##\n\t##########################\n\trun_neut_sim_parser = subparsers.add_parser('run_neut_sim', help='run neutral simulations')\n\trun_sel_sim_parser = subparsers.add_parser('run_sel_sim', help='run sims with selection')\n\trun_sel_sim_parser.add_argument('traj_infilename', type=str, action='store', help=\"selection trajectory\")\n\n\t####################################\n\t## GENERATE SCORES FROM SIMULATES ##\n\t####################################\n\trun_repscores_parser = subparsers.add_parser('run_repscores', help=\"run composite score calculations for simulated tped\")\n\trun_repscores_parser.add_argument('score_basedir', type=str, action='store', help=\"parent directory in which to generate/populate folders for each composite score\")\n\trun_repscores_parser.add_argument('inputTpedFile', type=str, action='store', help=\"TPED file with simulate data for putative selected population\") \n\trun_repscores_parser.add_argument('--simRecomFile', type=str, action=\"store\", help=\"location of input recom file\", default=\"/n/home08/jvitti/params/test_recom.recom\")\n\tget_neut_norm_params_parser = subparsers.add_parser('get_neut_norm_params', help=\"jointly normalize scores from neutral replicates to get parameters with which to normalize all replicates\")\t\n\tnorm_from_neut_params_parser = subparsers.add_parser('norm_from_neut_params', help=\"normalize component scores according to neutral distribution\")\n\tnorm_from_neut_params_parser.add_argument('--selbin', action='store', help=\"e.g. 0.10 -- if excluded, normalize neutral simulates\")\n\tnorm_from_neut_params_parser.add_argument('--scenario_dir', action='store', help=\"neut/selsim dir\", default=\"neut\")\n\n\t##################################################\n\t## GATHER SCORES AND CALCULATE LIKELIHOOD TABLE ##\n\t##################################################\n\tlikes_from_scores_parser = subparsers.add_parser('likes_from_scores', help='Collate scores from simulated data in order to generate component test probability distributions.')\n\tlikes_from_scores_parser.add_argument('--nrep_neut', type=int, action=\"store\", help=\"number of neutral replicates\", default=1000)\n\tlikes_from_scores_parser.add_argument('--nrep_sel', type=int, action=\"store\", help=\"number of replicates per selection scenario bin\", default=500)\n\tlikes_from_scores_parser.add_argument('--binMerge', action=\"store_true\", help=\"if included, generate higher-order groupings of selscenario frequency bins\")\n\tlikes_from_scores_parser.add_argument('--foldDist', action=\"store_true\", help=\"if included, take absolute value of score values (fold distribution over y-axis)\", default=False)\n\tlikes_from_scores_parser.add_argument('--save_suffix', type=str, action=\"store\", help=\"optional string to add to filenames (e.g. to avoid overwrite)\", default=None)\n\tlikes_from_scores_parser.add_argument('--save_dir', type=str, action=\"store\", help=\"if included, specify alternate outpot location\", default=None)\n\tlikes_from_scores_parser.add_argument('--save_likelihoods', action=\"store_true\", help=\"in addition to plotting, save data\", default=False)\n\tif True:\n\t\tlikes_from_scores_parser.add_argument('--ihs', action=\"store_true\", help=\"visualize likelihoods for iHS\", default=False)\n\t\tlikes_from_scores_parser.add_argument('--delihh', action=\"store_true\", help=\"visualize likelihoods for delIHH\", default=False)\n\t\tlikes_from_scores_parser.add_argument('--nsl', action=\"store_true\", help=\"visualize likelihoods for nSL\", default=False)\n\t\tlikes_from_scores_parser.add_argument('--xpehh', action=\"store_true\", help=\"visualize likelihoods for XP-EHH\", default=False)\n\t\tlikes_from_scores_parser.add_argument('--deldaf', action=\"store_true\", help=\"visualize likelihoods for delDAF\", default=False)\n\t\tlikes_from_scores_parser.add_argument('--fst', action=\"store_true\", help=\"visualize likelihoods for Fst\", default=False)\n\n\t########################################################\n\t## ANALYZE AND BUNDLE SCORE PROBABILITY DISTRIBUTIONS ##\n\t########################################################\n\tplot_likes_vs_scores_parser = subparsers.add_parser('plot_likes_vs_scores', help='useful QC step; visualize the function that converts score values into likelihood contributions towards composite scores')\n\tplot_likes_vs_scores_parser.add_argument('inputLikesPrefix', action=\"store\", help=\"filename minus causal/linked/neutral.txt\")\n\tplot_likes_vs_scores_parser.add_argument('--default_nregion_snps', type=int, action=\"store\", help=\"presumptive number of SNPs in region (determines prior distributions for within-region CMS calculations)\", default=5000)\n\twrite_master_likes_parser = subparsers.add_parser('write_master_likes', help='specify and bundle together input distributions to pass to CMS. This allows the user to specify models, frequency of SNPs used to generated p(score|sel), etc.')\n\twrite_master_likes_parser.add_argument('--likes_masterDir', type=str, default=\"/n/regal/sabeti_lab/jvitti/\", help=\"location of likelihood tables, defined\")\n\t#write_master_likes_parser.add_argument('--likes_nonSel', type=str, default=\"vsNeut\", help='do we use completely neutral, or linked neutral SNPs for our non-causal distributions? by default, uses strict neutral (CMSgw)')\n\t#write_master_likes_parser.add_argument('--likes_freqSuffix', type=str, default=\"allFreqs\", help='for causal SNPs, include suffix to specify which selbins to include')\n\t#write_master_likes_parser.add_argument('--likes_savestring', type=str, default=\"allFreqs\", help='default savestring for individual likes files to cull')\n\twrite_master_likes_parser.add_argument('--model', type=str, default=\"nulldefault\", help='...')\n\twrite_master_likes_parser.add_argument('--likes_inDir', type=str, default=\"/n/regal/sabeti_lab/jvitti/\", help='...')\n\n\n\t#################\n\t## SHARED ARGS ## \n\t################# \n\tfor common_parser in [run_neut_sim_parser, run_sel_sim_parser, run_repscores_parser, get_neut_norm_params_parser, norm_from_neut_params_parser]:\n\t\tcommon_parser.add_argument('--checkOverwrite', action=\"store_true\", default=True)\n\tfor run_sim_parser in [run_neut_sim_parser, run_sel_sim_parser]:\n\t\trun_sim_parser.add_argument('writeBase', type=str, action='store', help=\"write prefix\")\n\t\trun_sim_parser.add_argument('--dropSings', type=float, action='store',  help='randomly thin global singletons from output dataset to model ascertainment bias', default=.25)\t\n\tfor cosi_parser in [get_sel_traj_parser, run_neut_sim_parser, run_sel_sim_parser]:\n\t\tcosi_parser.add_argument('--cosiBuild', type=str, action='store', help='which version of cosi to run', default=\"coalescent\")\n\t\tcosi_parser.add_argument('inputParamFile', type=str, action='store', help='file with model specifications for input')\n\t\t#cosi_parser.add_argument('--genmapRandomRegions', action='store_true', help='cosi option to sub-sample genetic map randomly from input')\t\n\tfor cms_preconda_parser in [run_repscores_parser, get_neut_norm_params_parser, norm_from_neut_params_parser]: #TEMPORARY; conda will obviate\n\t\tcms_preconda_parser.add_argument('--cmsdir', type=str, action='store', help=\"location of CMS scripts (TEMPORARY; conda will obviate)\", default=\"/n/home08/jvitti/cms/cms/\") \n\tfor interior_score_parser in [get_neut_norm_params_parser, likes_from_scores_parser]:\n\t\tinterior_score_parser.add_argument('--edge', type=int, action=\"store\", help=\"use interior of replicates; define per-end bp. (e.g. 1.5Mb -> 1Mb: 250000)\", default=250000)\n\t\tinterior_score_parser.add_argument('--chromlen', type=int, action=\"store\", help=\"per bp (1.5mb = 1500000)\", default=1500000)\n\tfor norm_parser in [get_neut_norm_params_parser, norm_from_neut_params_parser, write_master_likes_parser]:\n\t\tnorm_parser.add_argument('--score', type=str, action='store', default='ihs')\n\t\tnorm_parser.add_argument('--simpop', type=int, action='store', default=1)\n\t\tnorm_parser.add_argument('--altpop', type=int, action='store', default=2)\n\t\tnorm_parser.add_argument('--nrep', type=int, action='store', default=100)\n\tfor norm_sims_parser in [get_neut_norm_params_parser, norm_from_neut_params_parser, likes_from_scores_parser]:\n\t\tnorm_sims_parser.add_argument('modeldir', type=str, action=\"store\", help=\"location of component score folders for demographic scenario\")\n\tfor selbin_parser in [generate_sel_bins_parser, get_sel_traj_parser, likes_from_scores_parser]:\n\t\tselbin_parser.add_argument('--freqRange', type=str, help=\"range of final selected allele frequencies to simulate, e.g. .05-.95\", default='.05-.95')\n\t\tselbin_parser.add_argument('--nBins', type=int, help=\"number of frequency bins\", default=9)\t\t\n\treturn parser\n\n############################\n## DEFINE EXEC FUNCTIONS ###\n############################\n### Run simuates from specified demographic\n### model under various scenarios\ndef execute_generate_sel_bins(args):\n\t''' pre-processing step for sel_trajs(->sel_sim) ''' #hmmm nix this? or else, fix write_bin_paramfile: merge with quick_write_inclusive_sweep_paramfiles.py\n\tfreqRange = args.freqRange\n\tnBins = args.nBins\n\trunDir = args.outputDir\n\tneutParamfile = args.inputParamFile\n\tfullrange, bin_starts, bin_ends, bin_medians, bin_medians_str = get_bins(freqRange, nBins)\n\tfor ibin in range(nBins):\n\t\tpopulateDir = runDir + \"sel_\" + bin_medians_str[ibin]\n\t\tbinDir = check_create_dir(populateDir)\n\t\tbounds = bin_starts[ibin], bin_ends[ibin]\n\t\tparamfilename = populateDir + \"/params\"\n\t\twrite_bin_paramfile(neutParamfile, paramfilename, bounds)\n\t\tprint('wrote to: ' + paramfilename)\t\n\treturn\ndef execute_get_sel_traj(args):\n\t'''generate forward trajectories of simulated allele frequencies for demographic scenarios with selection'''\n\ttraj_outputname = args.traj_outputname\n\tcosibuild = args.cosiBuild\n\tparamfilename = args.inputParamFile\n\tmaxattempts = args.maxAttempts\n\trun_traj(traj_outputname, cosibuild, paramfilename, maxattempts)\n\treturn\ndef execute_run_neut_sim(args):\n\t''' generates tped data for one neutral replicate from a demographic model parameter file using coalescent simulator cosi '''\n\tcosibuild = args.cosiBuild\n\toutbase = args.writeBase\n\tparamfilename = args.inputParamFile\n\tdropSing = args.dropSings\n\tcmd = cosibuild\n\targstring = \"-p \" + paramfilename + \" --genmapRandomRegions --drop-singletons \" + str(dropSing) + \" --tped \" + outbase + \" --output-gen-map\"\n\t#print(cmd + \" \" + argstring)\t\n\tcosicreatefilename = outbase + \"_0_1.tped\"\n\tcosi_movedfilename = outbase + \"_1.tped\"\t\n\tproceed = check_create_file(cosicreatefilename, args.checkOverwrite)\n\tif proceed:\n\t#if not os.path.isfile(cosicreatefilename):\n\t\tfullCmd = cmd + \" \" + argstring\n\t\tprint(fullCmd)\n\t\texecute(fullCmd)\n\t\tfor ipop in [1, 2, 3, 4]:\n\t\t\ttorenamefile = outbase + \"_0_\" + str(ipop) + \".tped\"\n\t\t\t#print(torenamefile)\n\t\t\tassert os.path.isfile(torenamefile)\n\t\t\trenamed = outbase +\"_\" + str(ipop) + \".tped\"\n\t\t\trenamecmd = \"mv \"  + torenamefile + \" \" + renamed\n\t\t\texecute(renamecmd)\n\tprint(\"wrote simulates to e.g. \" + renamed)\n\treturn\ndef execute_run_sel_sim(args):\n\t''' generates tped data for one replicate from a demographic model parameter file and selection trajectory file using coalescent simulator cosi '''\n\ttrajectory = args.traj_infilename\n\tcosibuild = args.cosiBuild\n\toutbase = args.writeBase\n\tparamfilename = args.inputParamFile\n\tdropSing = args.dropSings\t\n\tcmd = \"env COSI_NEWSIM=1 env COSI_LOAD_TRAJ=\" + trajectory + \" \" + cosibuild \n\targstring = \"-p \" + paramfilename + \" --genmapRandomRegions --drop-singletons \" + str(dropSing) + \" --tped \" + outbase + \" --output-gen-map\"\n\t#print(cmd + \" \" + argstring)\n\tcosicreatefilename = outbase + \"_0_1.tped\"\n\tcosi_movedfilename = outbase + \"_1.tped\"\n\tproceed = check_create_file(cosi_movedfilename, args.checkOverwrite)\n\tif proceed:\n\t\tfullCmd = cmd + \" \" + argstring\n\t\tprint(fullCmd)\n\t\texecute(fullCmd)\n\t\tfor ipop in [1, 2, 3, 4]:\n\t\t\ttorenamefile = outbase + \"_0_\" + str(ipop) + \".tped\"\n\t\t\t#print(torenamefile)\n\t\t\tassert os.path.isfile(torenamefile)\n\t\t\trenamed = outbase +\"_\" + str(ipop) + \".tped\"\n\t\t\trenamecmd = \"mv \"  + torenamefile + \" \" + renamed\n\t\t\texecute(renamecmd)\n\tprint(\"wrote simulates to e.g. \" + renamed)\n\treturn\n\n### Calculate component scores from \n### simulated data\ndef execute_run_repscores(args):\n\t''' for one simulated replicate (agnostic wrt neut/sel), generate all component scores '''\n\tbasedir = args.score_basedir\n\tcmsdir = args.cmsdir \n\ttped = args.inputTpedFile\n\trepNum, pop, tpeddir = get_info_from_tped_name(tped)\n\tcheckOverwrite = args.checkOverwrite \n\tsimRecomFile = args.simRecomFile\n\tassert os.path.isfile(tped)\n\tfor scorefiledir in ['ihs', 'delihh', 'nsl', 'xpehh', 'freqs']:\n\t\tcheck_create_dir(basedir + scorefiledir)\n\n\t####### Calculate per-population\n\t####### scores: iHS, delIHH, nSL\n\tihs_commandstring = \"python \" + cmsdir + \"scans.py selscan_ihs\"\n\tihs_outfileprefix = basedir + \"ihs/rep\" + str(repNum) + \"_\" + str(pop) \n\tihs_unnormedfile = ihs_outfileprefix + \".ihs.out\"\n\tihs_argstring = tped + \" \" + ihs_outfileprefix + \" --threads 7 \"\n\tihs_fullcmd = ihs_commandstring + \" \" + ihs_argstring\n\tihs_normedfile = ihs_unnormedfile + \".norm\"\n\tproceed = check_create_file(ihs_unnormedfile, args.checkOverwrite)\n\tif proceed:\n\t\tprint(ihs_fullcmd)\n\t\texecute(ihs_fullcmd)\n\tdelihh_commandstring = \"python \" + cmsdir + \"composite.py delihh_from_ihs\"\n\tdelihh_unnormedfile =  basedir + \"delihh/rep\" + str(repNum) + \"_\" + str(pop) + \".txt\"\n\tdelihh_argstring = ihs_unnormedfile + \" \"+ delihh_unnormedfile\n\tdelihh_fullcmd = delihh_commandstring + \" \" + delihh_argstring \n\tdelihh_normedfile = delihh_unnormedfile + \".norm\"\n\tproceed = check_create_file(delihh_unnormedfile, args.checkOverwrite)\n\tif proceed:\n\t\tprint(delihh_fullcmd)\n\t\texecute(delihh_fullcmd)\t\t\n\tnsl_commandstring = \"python \" + cmsdir + \"scans.py selscan_nsl\" \n\tnsl_unnormedfileprefix = basedir + \"nsl/rep\" + str(repNum) + \"_\" + str(pop)\n\tnsl_argstring = tped + \" \" + nsl_unnormedfileprefix\n\tnsl_fullcmd = nsl_commandstring + \" \" + nsl_argstring\n\tnsl_unnormedfilename = nsl_unnormedfileprefix + \".nsl.out\"\n\tproceed = check_create_file(nsl_unnormedfilename, args.checkOverwrite)\n\tif proceed:\n\t\tprint(nsl_fullcmd)\n\t\texecute(nsl_fullcmd)\t\n\n\t####### Calculate per-population-pair\n\t####### scores: XP-EHH, Fst, delDAF\n\tpops = [1, 2, 3, 4]\n\taltpops = pops[:]\n\taltpops.remove(int(pop))\n\tfor altpop in altpops:\n\t\txpehh_commandstring = \"python \" + cmsdir + \"scans.py selscan_xpehh --threads 7\"\n\t\ttped2 = tpeddir + \"rep\" + str(repNum) + \"_\" + str(altpop) + \".tped\"\n\t\txpehh_outfileprefix = basedir + \"xpehh/rep\" + str(repNum) + \"_\" + str(pop) + \"_\" + str(altpop)\n\t\txpehh_unnormedfile = basedir + \"xpehh/rep\" + str(repNum) + \"_\" + str(pop) + \"_\" + str(altpop) + \".xpehh.out\"\n\t\txpehh_argumentstring = tped + \" \" + xpehh_outfileprefix + \" \" + tped2\n\t\txpehh_fullcmd = xpehh_commandstring + \" \" + xpehh_argumentstring\n\t\tproceed = check_create_file(xpehh_unnormedfile, args.checkOverwrite)\n\t\tif proceed:\n\t\t\tprint(xpehh_fullcmd)\n\t\t\texecute(xpehh_fullcmd)\n\n\t\tfstdeldaf_commandstring = \"python \" + cmsdir + \"composite.py freqscores\"\n\t\tfstdeldaf_outfilename = basedir + \"freqs/rep\" + str(repNum) + \"_\" + str(pop) + \"_\" + str(altpop)\n\t\tfstdeldaf_argumentstring = tped + \" \" + tped2 + \" \" + simRecomFile + \" \" + fstdeldaf_outfilename \n\t\tfstdeldaf_fullcmd = fstdeldaf_commandstring + \" \" + fstdeldaf_argumentstring \n\t\tproceed = check_create_file(fstdeldaf_outfilename, args.checkOverwrite)\n\t\tif proceed:\n\t\t\tprint(fstdeldaf_fullcmd)\n\t\t\texecute(fstdeldaf_fullcmd)\n\treturn\ndef execute_get_neut_norm_params(args):\n\t''' creates a concatenated file and saves bin output if run for the first time'''\n\tpop = args.simpop\n\tnumReps = args.nrep\n\tbasedir = args.modeldir \n\tif basedir[-1] != \"/\":\n\t\tbasedir += \"/\"\n\tcmsdir = args.cmsdir\n\tscore = args.score\n\taltpop = args.altpop\n\tchrlen, edge = args.chromlen, args.edge\n\tstartbound, endbound = int(edge), chrlen - int(edge) #define replicate interior (conservative strategy to avoid edge effects)\n\n\tif score in ['ihs', 'delihh', 'nsl']:\n\t\tconcatfilebase = basedir + \"neut/concat_\" + str(pop) + \"_\"\n\telif score in ['xpehh', 'fst']:\n\t\taltpop = args.altpop\n\t\tconcatfilebase = basedir + \"neut/concat_\" + str(pop) + \"_\" + str(altpop) + \"_\"\n\telse:\n\t\tprint('must call per composite score')\n\t\tsys.exit(0)\n\n\tconcatfilename = concatfilebase + score + \".txt\"\n\tbinfilename = concatfilebase + score + \".bins\"\n\n\tif not os.path.isfile(binfilename):\n\t\tif not os.path.isfile(concatfilename):\n\t\t\trepfiles = []\n\t\t\tfor irep in range(1, numReps+1):\n\t\t\t\tif score == 'ihs':\n\t\t\t\t\tunnormedfile = basedir + \"neut/ihs/rep\" + str(irep) + \"_\" + str(pop) + \".ihs.out\"\n\t\t\t\t\tphyspos_ind = 1\n\t\t\t\telif score == \"delihh\":\n\t\t\t\t\tunnormedfile = basedir + \"neut/delihh/rep\" + str(irep) + \"_\" + str(pop) + \".txt\"\n\t\t\t\t\tphyspos_ind = 1\n\t\t\t\telif score == \"nsl\":\n\t\t\t\t\tunnormedfile = basedir + \"neut/nsl/rep\" + str(irep) + \"_\" + str(pop) + \".nsl.out\"\n\t\t\t\t\tphyspos_ind = 1\n\t\t\t\telif score == \"xpehh\":\n\t\t\t\t\tunnormedfile = basedir + \"neut/xpehh/rep\" + str(irep) + \"_\" + str(pop) + \"_\" + str(altpop) + \".xpehh.out\"\n\t\t\t\t\tphyspos_ind = 1\n\t\t\t\telif score == \"fst\":\n\t\t\t\t\tunnormedfile = basedir + \"neut/freqs/rep\" + str(irep) + \"_\" + str(pop) + \"_\" + str(altpop)\n\t\t\t\t\tphyspos_ind = 0\n\t\t\t\tif os.path.isfile(unnormedfile):\n\t\t\t\t\trepfiles.append(unnormedfile)\n\t\t\t\telse:\n\t\t\t\t\tprint('missing: ' + unnormedfile)\n\t\t\tconcatfile = open(concatfilename, 'w')\n\t\t\tfor irepfile in range(len(repfiles)):\n\t\t\t\trepfile = repfiles[irepfile]\n\t\t\t\treadfile = open(repfile, 'r')\n\t\t\t\tfirstline = readfile.readline()\n\t\t\t\tif score in ['xpehh', 'fst']: #header\n\t\t\t\t\tif irepfile == 0:\n\t\t\t\t\t\tconcatfile.write(firstline)\n\t\t\t\t\telse:\n\t\t\t\t\t\tpass\n\t\t\t\tfor line in readfile:\n\t\t\t\t\tentries = line.split()\n\t\t\t\t\tphyspos = int(entries[physpos_ind])\n\t\t\t\t\tif physpos >= startbound and physpos <= endbound:\n\t\t\t\t\t\tconcatfile.write(line)\n\t\t\t\treadfile.close()\n\t\t\tconcatfile.close()\n\t\t\tprint('wrote to: ' + concatfilename)\n\n\t\t#already have concatfile\n\t\tinfilename = concatfilename\n\t\toutfilename = concatfilename + \".norm\" #or just write to /tmp ?\n\t\targstring = infilename #+ \" \" + outfilename\n\t\tif score in ['ihs', 'delihh']:\n\t\t\tcmd = \"python \" + cmsdir + \"scans.py selscan_norm_ihs\"\n\t\telif score in ['nsl']:\n\t\t\tcmd = \"python \" + cmsdir + \"scans.py selscan_norm_nsl\"\n\t\telif score in ['xpehh']:\n\t\t\tcmd = \"python \" + cmsdir + \"scans.py selscan_norm_xpehh\"\n\t\telse:\n\t\t\tcmd = \"\"\n\t\tfullcmd = cmd + \" \" + argstring\n\t\n\t\talreadyExists = False\n\t\tif args.checkOverwrite:\n\t\t\tif not os.path.isfile(binfilename): #check for overwrite\n\t\t\t\talreadyExists = False\n\t\t\telse:\n\t\t\t\talreadyExists = True\t\t\t\t\n\t\tif alreadyExists == False:\n\t\t\tprint(fullcmd)\n\t\t\t#execute(fullcmd)\n\t\t\twith open(binfilename, 'w') as outfile:\n\t\t\t\tsubprocess.check_output( fullcmd.split(), stderr=outfile)\n\t\t\toutfile.close()\n\t\t\tprint('wrote to: ' + binfilename)\n\treturn\ndef execute_norm_from_neut_params(args): \n\t''' using parameters from neutral simulates, normalizes component scores '''\n\tpop = args.simpop\n\tnumReps = args.nrep\n\tbasedir = args.modeldir\n\tif basedir[-1] != \"/\":\n\t\tbasedir += \"/\"\n\tcmsdir = args.cmsdir\n\tscore = args.score\n\taltpop = args.altpop\n\tscenario_dir = args.scenario_dir\n\t#if args.selbin is None:\n\t#\tscenario_dir = \"neut/\"\n\t#else:\n\t#\tscenario_dir = \"sel\" + str(pop) + \"/sel_\" + str(args.selbin) + \"/\"\n\tconcatfilename, binfilename = get_concat_files(pop, score, altpop, basedir=basedir) #I NEED TO MAKE THIS HANDLE SEL SITUATION\n\tprint('loading normalization parameters from ' + binfilename + \"...\")\n\t###############\n\t## NORMALIZE ##\n\t###############\n\tfor irep in range(1, numReps+1):\n\t\tif score in ['ihs']:\n\t\t\tunnormedfile = basedir + scenario_dir + \"ihs/rep\" + str(irep) + \"_\" + str(pop)  + \".ihs.out\"\n\t\t\tnorm_sel_ihs(unnormedfile, binfilename)\n\t\telif score in ['delihh']:\n\t\t\tunnormedfile = basedir + scenario_dir + \"delihh/rep\" + str(irep) + \"_\" + str(pop) + \".txt\"\n\t\t\tnorm_sel_ihs(unnormedfile, binfilename)\n\t\telif score in ['nsl']:\n\t\t\tunnormedfile = basedir + scenario_dir + \"nsl/rep\" + str(irep) + \"_\" + str(pop)+ \".nsl.out\"\n\t\t\tnorm_sel_ihs(unnormedfile, binfilename)\n\t\telif score in ['xpehh']:\n\t\t\tunnormedfile = basedir + scenario_dir + \"xpehh/rep\" + str(irep) + \"_\" + str(pop) + \"_\" + str(altpop) + \".xpehh.out\"\n\t\t\tnorm_sel_xpehh(unnormedfile, binfilename)\n\t\telse: #if score in ['fst']:\n\t\t\tprint('currently handling this manually: rewrite_fst_bins.py')\n\t\t\tpass\n\t\tif irep%100 == 0:\n\t\t\tprint(\"currently rep: \" + str(irep))\n\treturn\t\n\n### Define component score likelihood \n### functions as histograms of simulated scores\ndef execute_likes_from_scores(args): \n\t''' define likelihood function for component score based on histograms of score values from simulated data.\n\teach run is per-score, per-scenario. does all pops / poppairs  '''\n\tmodeldir, pops = args.modeldir, [1, 2, 3, 4]\n\tif modeldir[-1] != \"/\":\n\t\tmodeldir += \"/\"\n\tmodeldir_entries = modeldir.split('/')\n\tmodel = modeldir_entries[-2]\n\tnPerBin_Neut, nPerBin_Sel = args.nrep_neut, args.nrep_sel\n\tfreqRange, nBins = args.freqRange, args.nBins #define selscenario bins\n\tfullrange, bin_starts, bin_ends, bin_medians, bin_medians_str = get_bins(freqRange, nBins)\n\tchrlen, edge = args.chromlen, args.edge #define replicate interior (conservative strategy to avoid edge effects)\n\tstartbound, endbound = int(edge), chrlen - int(edge) \n\t#print(str([args.ihs, args.delihh, args.nsl, args.xpehh, args.deldaf, args.fst]))\n\tif [args.ihs, args.delihh, args.nsl, args.xpehh, args.deldaf, args.fst].count(True) != 1:\n\t\tprint('must call one score at a time')\n\t\tsys.exit(0)\n\t#####################\n\t## LOAD NEUT FILES ##\n\t#####################\n\tneutdir = modeldir + \"neut/\"\n\tall_completed_neut = []\n\tfor pop in pops:\n\t\tcompleted_neut = []\n\t\tfor irep in range(1, nPerBin_Neut+1):\n\t\t\tloaded_neut_files = get_sim_compscore_files(pop, irep, neutdir) \n\t\t\tall_present = [os.path.isfile(item) for item in loaded_neut_files]\n\t\t\tif (all_present.count(True)) == 9: #replicate done\n\t\t\t\tcompleted_neut.append(loaded_neut_files)\n\t\tall_completed_neut.append(completed_neut)\n\tprint(\"loaded \" + str(sum([len(item) for item in all_completed_neut])) + \" neutral replicates with complete component scores from \" + neutdir)\n\t####################\n\t## LOAD SEL FILES ## \n\t####################\n\tbinlabels = bin_medians_str \n\tall_completed_sel, selcounter = [], 0\n\tfor pop in pops:\n\t\tseldir = modeldir + \"sel\" + str(pop) + \"/\"\n\t\tcompleted_sel = []\n\t\t## generate likelihood distributions for selection simulates \n\t\t## from multiple frequency bins\n\t\tif args.binMerge:  \n\t\t\t#need: input bins and name of cluster\n\t\t\tselbin_clusters = [[\"0.10\", \"0.20\", \"0.30\", \"0.40\", \"0.50\", \"0.60\", \"0.70\", \"0.80\", \"0.90\"],[\"0.70\", \"0.80\", \"0.90\",], [\"0.40\", \"0.50\", \"0.60\",], [\"0.10\", \"0.20\", \"0.30\"],] \n\t\t\tcluster_names = [\"allfreq\", \"hi\", \"mid\", \"low\"] \n\t\t\tfor icluster in range(len(selbin_clusters)):\n\t\t\t\tcluster, clustername = selbin_clusters[icluster], cluster_names[icluster]\n\t\t\t\tcompleted_cluster = []\n\t\t\t\tfor selbin in cluster:\n\t\t\t\t\tbindir = seldir + \"sel_\" + str(selbin) + \"/\"\t\t\t\t\n\t\t\t\t\tfor irep in range(1, nPerBin_Sel+1):\n\t\t\t\t\t\tloaded_sel_files = get_sim_compscore_files(pop, irep, bindir)\n\t\t\t\t\t\tall_present = [os.path.isfile(item) for item in loaded_sel_files]\n\t\t\t\t\t\tif (all_present.count(True)) == 9: #replicate done\n\t\t\t\t\t\t\tcompleted_cluster.append(loaded_sel_files)\n\t\t\t\t\t\t\tselcounter +=1\n\t\t\t\tcompleted_sel.append(completed_cluster)\n\t\t\tall_completed_sel.append(completed_sel) #[ipop][iCLUSTER][irep][iscore]\n\t\t\tnChunks, chunk_labels = len(cluster_names), cluster_names\n\t\t\n\t\t## fine-grained (ie per-sel-bin) generation of \n\t\t## score probability density functions\n\t\telse:\n\t\t\tfor selbin in binlabels:\n\t\t\t\tbindir = seldir + \"sel_\" + str(selbin) + \"/\"\n\t\t\t\tcompleted_bin = []\n\t\t\t\tfor irep in range(1, nPerBin_Sel+1):\n\t\t\t\t\tloaded_sel_files = get_sim_compscore_files(pop, irep, bindir)\n\t\t\t\t\tall_present = [os.path.isfile(item) for item in loaded_sel_files]\n\t\t\t\t\tif (all_present.count(True)) == 9: #replicate done\n\t\t\t\t\t\tcompleted_bin.append(loaded_sel_files)\n\t\t\t\t\t\tselcounter +=1\n\t\t\t\tcompleted_sel.append(completed_bin)\n\t\t\tall_completed_sel.append(completed_sel) #[ipop][ibin][irep][iscore]\n\t\t\tnChunks, chunk_labels = len(binlabels), bin_medians_str\n\tprint(\"loaded \" + str(selcounter) + \" selection replicates with complete component scores\")\n\t#################################\n\t## SORT SCORES INTO HISTOGRAMS ## \n\t################################# \n\tfor ichunk in range(nChunks): #iterate over selfreqs\n\t\tchunkstring = chunk_labels[ichunk]\n\t\t####################\n\t\t## PER POP SCORES ##\n\t\t####################\n\t\tif (args.ihs or args.delihh or args.nsl): #per pop\n\t\t\t###########\n\t\t\t### SORT ## \n\t\t\t###########\n\t\t\tif args.ihs:\n\t\t\t\tscore = \"ihs\"\n\t\t\t\tprint('binning iHS scores...')\n\t\t\t\tvalues = get_scores_from_files(all_completed_neut, all_completed_sel, 0, ichunk, startbound, endbound, foldDists = args.foldDist)\n\t\t\tif args.delihh:\n\t\t\t\tscore = \"delihh\"\n\t\t\t\tprint('binning delIHH scores...')\n\t\t\t\tvalues = get_scores_from_files(all_completed_neut, all_completed_sel, 1, ichunk, startbound, endbound, foldDists = args.foldDist)\t\n\t\t\tif args.nsl:\n\t\t\t\tscore = \"nsl\"\n\t\t\t\tprint('binning nSL scores...')\n\t\t\t\tvalues = get_scores_from_files(all_completed_neut, all_completed_sel, 2, ichunk, startbound, endbound, foldDists = args.foldDist)\n\t\t\tif True:\n\t\t\t\tpop1vals, pop2vals, pop3vals, pop4vals = values\n\t\t\t\tneut_1, causal_1, linked_1 = pop1vals\n\t\t\t\tneut_2, causal_2, linked_2 = pop2vals\n\t\t\t\tneut_3, causal_3, linked_3 = pop3vals\n\t\t\t\tneut_4, causal_4, linked_4 = pop4vals\n\t\t\t##########\n\t\t\t## PLOT ##\n\t\t\t##########\n\t\t\tminVal, maxVal, nProbBins, annotate = get_plot_pdf_params(score, args.foldDist)\n\t\t\tplot_title = \"PDF for \" + score + \", sel_\" + str(chunkstring)\n\t\t\toutput_dir = \"\"\n\t\t\tif args.save_dir is not None:\n\t\t\t\toutput_dir = args.save_dir + model + \"_\"\n\t\t\telse:\n\t\t\t\toutput_dir = modeldir + \"likes/\"\n\n\t\t\tsavefilebase = output_dir + score + \"_sel_\" + chunkstring \n\t\t\tif args.save_suffix is not None:\n\t\t\t\tsavefilebase += \"_\" + args.save_suffix\n\n\t\t\tsavefilename = savefilebase + \".png\"\n\t\t\t#savefilebase = modeldir + \"likes/\" + score + \"_sel_\" + chunkstring #ensure consistency with get_likes_filenames\n\t\t\tlikes_savebase_1 = output_dir + score + \"_sel1_\" + chunkstring + \"_\" \n\t\t\tlikes_savebase_2 = output_dir + score + \"_sel2_\" + chunkstring + \"_\" #+ args.save_suffix + \"_\"\n\t\t\tlikes_savebase_3 = output_dir + score + \"_sel3_\" + chunkstring + \"_\" #+ args.save_suffix + \"_\"\n\t\t\tlikes_savebase_4 = output_dir + score + \"_sel4_\" + chunkstring + \"_\" #+ args.save_suffix + \"_\"\n\t\t\tif args.save_suffix is not None:\n\t\t\t\tlikes_savebase_1 += args.save_suffix + \"_\"\n\t\t\t\tlikes_savebase_2 += args.save_suffix + \"_\"\n\t\t\t\tlikes_savebase_3 += args.save_suffix + \"_\"\n\t\t\t\tlikes_savebase_4 += args.save_suffix + \"_\"\n\n\t\t\tf1, (ax1, ax2, ax3, ax4)  = plt.subplots(4, sharex=True, sharey=True)\n\t\t\tplt.suptitle(plot_title)\n\t\t\tplot_pdf_comparison_from_scores(ax1, neut_1, causal_1, linked_1, minVal, maxVal, nProbBins, \"1 (AFR)\", likes_savebase_1, saveFiles = args.save_likelihoods, annotate = annotate)\n\t\t\tplot_pdf_comparison_from_scores(ax2, neut_2, causal_2, linked_2, minVal, maxVal, nProbBins, \"2 (EUR)\", likes_savebase_2, saveFiles = args.save_likelihoods, annotate = annotate)\n\t\t\tplot_pdf_comparison_from_scores(ax3, neut_3, causal_3, linked_3, minVal, maxVal, nProbBins, \"3 (EAS)\", likes_savebase_3, annotate = annotate, saveFiles = args.save_likelihoods)\n\t\t\tplot_pdf_comparison_from_scores(ax4, neut_4, causal_4, linked_4, minVal, maxVal, nProbBins, \"4 (SAS)\", likes_savebase_4, annotate = annotate, saveFiles = args.save_likelihoods)\n\t\t\tax4.set_xlabel('score value')\n\t\t\t#f1.subplots_adjust(hspace=0)\n\t\t\t#f1.ylabel(\"p(score)\")\n\t\t\tplt.savefig(savefilename)\n\t\t\tplt.close()\n\t\t\tprint('saved to ' + savefilename)\n\n\t\t##################\n\t\t## PER POP COMP ##\n\t\t##################\n\t\tif (args.xpehh or args.deldaf or args.fst): #per pop-comp\n\t\t\t###########\n\t\t\t### SORT ##\n\t\t\t###########\n\t\t\tif args.xpehh:\n\t\t\t\tscore = \"xpehh\"\n\t\t\t\tprint('binning XP-EHH scores...')\n\t\t\t\tvalues = get_compscores_from_files_flatten(all_completed_neut, all_completed_sel, \"xpehh\", ichunk, startbound, endbound, foldDists = args.foldDist)\n\t\t\tif args.deldaf:\n\t\t\t\tscore = \"deldaf\"\n\t\t\t\tprint('binning delDAF scores...')\n\t\t\t\tvalues = get_compscores_from_files_flatten(all_completed_neut, all_completed_sel, \"deldaf\", ichunk, startbound, endbound, foldDists = args.foldDist)\t\n\t\t\tif args.fst:\n\t\t\t\tscore = \"fst\"\n\t\t\t\tprint('binning Fst scores...')\n\t\t\t\tvalues = get_compscores_from_files_flatten(all_completed_neut, all_completed_sel, \"fst\", ichunk, startbound, endbound, foldDists = args.foldDist)\n\t\t\tif True:\n\t\t\t\tpop1vals, pop2vals, pop3vals, pop4vals = values\n\t\t\t\tneutvals1, causalvals1, linkedvals1 = pop1vals\n\t\t\t\tneutvals2, causalvals2, linkedvals2 = pop2vals\n\t\t\t\tneutvals3, causalvals3, linkedvals3 = pop3vals\n\t\t\t\tneutvals4, causalvals4, linkedvals4 = pop4vals\n\n\t\t\t##########\n\t\t\t## PLOT ##\n\t\t\t##########\n\t\t\tminVal, maxVal, nProbBins, annotate = get_plot_pdf_params(score, args.foldDist)\n\t\t\toutput_dir = \"\"\n\t\t\tif args.save_dir is not None:\n\t\t\t\toutput_dir = args.save_dir + model + \"_\"\n\t\t\telse:\n\t\t\t\toutput_dir = modeldir + \"likes/\"\n\n\t\t\tsavefilebase = output_dir + score + \"_sel_\" + str(chunkstring)\n\t\t\tif args.save_suffix is not None:\n\t\t\t\tsavefilebase += \"_\" + args.save_suffix\n\t\t\tsavefilename = savefilebase + \".png\"\n\t\n\t\t\tplot_title = \"PDF for \" + score + \", \" + str(chunkstring)\n\n\t\t\tlikes_savebase_1 = output_dir + score + \"_sel1_\" + chunkstring + \"_\" \n\t\t\tlikes_savebase_2 = output_dir + score + \"_sel2_\" + chunkstring + \"_\" #+ args.save_suffix + \"_\"\n\t\t\tlikes_savebase_3 = output_dir + score + \"_sel3_\" + chunkstring + \"_\" #+ args.save_suffix + \"_\"\n\t\t\tlikes_savebase_4 = output_dir + score + \"_sel4_\" + chunkstring + \"_\" #+ args.save_suffix + \"_\"\n\t\t\tif args.save_suffix is not None:\n\t\t\t\tlikes_savebase_1 += args.save_suffix + \"_\"\n\t\t\t\tlikes_savebase_2 += args.save_suffix + \"_\"\n\t\t\t\tlikes_savebase_3 += args.save_suffix + \"_\"\n\t\t\t\tlikes_savebase_4 += args.save_suffix + \"_\"\n\t\t\tf1, (ax1, ax2, ax3, ax4)  = plt.subplots(4, sharex=True, sharey=True)\n\t\t\tplt.suptitle(plot_title)\n\t\t\tplot_pdf_comparison_from_scores(ax1, neutvals1, causalvals1, linkedvals1, minVal, maxVal, nProbBins, \"1 (AFR)\", likes_savebase_1, saveFiles = args.save_likelihoods, annotate = annotate)\n\t\t\tplot_pdf_comparison_from_scores(ax2, neutvals2, causalvals2, linkedvals2, minVal, maxVal, nProbBins, \"2 (EUR)\", likes_savebase_2, saveFiles = args.save_likelihoods, annotate = annotate)\n\t\t\tplot_pdf_comparison_from_scores(ax3, neutvals3, causalvals3, linkedvals3, minVal, maxVal, nProbBins, \"3 (EAS)\", likes_savebase_3, annotate = annotate, saveFiles = args.save_likelihoods)\n\t\t\tplot_pdf_comparison_from_scores(ax4, neutvals4, causalvals4, linkedvals4, minVal, maxVal, nProbBins, \"4 (SAS)\", likes_savebase_4, annotate = annotate, saveFiles = args.save_likelihoods)\n\t\t\tax4.set_xlabel('score value')\n\t\t\t#plot_pdf_comparison_from_scores(ax1, neuta, causala, linkeda, minVal, maxVal, nProbBins, ax_ylabela, savefilename_a, annotate = annotate, saveFiles = args.save_likelihoods)\n\t\t\t#ax3.set_xlabel('score value')\n\t\t\t#f1.subplots_adjust(hspace=0)\n\t\t\tplt.savefig(savefilename)\n\t\t\tplt.close()\n\t\t\tprint('saved to ' + savefilename)\n\treturn\ndef execute_plot_likes_vs_scores(args): ##REVISIT\n\t''' useful QC step; visualize the function that converts score values into likelihood contributions towards composite scores '''\n\tprint(\"Does this still apply with the combine_amend?\") \n\tinputprefix = args.inputLikesPrefix\n\tnregionsnps = args.default_nregion_snps\n\tcausal_likes_filename, linked_likes_filename, neut_likes_filename = inputprefix + \"_causal.txt\", inputprefix + \"_linked.txt\", inputprefix + \"_neut.txt\"\n\n\tcausal_likes = quick_load_likes(causal_likes_filename)\n\tlinked_likes = quick_load_likes(linked_likes_filename)\n\tneut_likes = quick_load_likes(neut_likes_filename)\n\n\tcomp_likes = quick_cl_from_likes(causal_likes, linked_likes, nSnp = nregionsnps, takeLn = True)\n\tcomp_like_ratios = quick_clr_from_likes(causal_likes, neut_likes, takeLn = True)\n\n\tsavefilename = inputprefix + \"_clr_likes_vs_likesscores.png\"\n\tfig, ax = plt.subplots()\n\tax.scatter(np.arange(len(comp_like_ratios)), comp_like_ratios) #I want to make this use the actual score ranges.\n\tplt.savefig(savefilename)\n\tprint('saved to: ' + savefilename)\n\tplt.close()\n\n\tsavefilename = inputprefix + \"_cl_likes_vs_likesscores.png\"\n\tfig, ax = plt.subplots()\n\tax.scatter(np.arange(len(comp_likes)), comp_likes)\n\tplt.savefig(savefilename)\n\tprint('saved to: ' + savefilename)\n\tplt.close()\n\treturn\ndef execute_write_master_likes(args):\n\t\"\"\" given granular output from likes_from_scores, bundle together into groups of distributions with which to composite \"\"\" \n\tscore = args.score\n\twriteloc = args.likes_masterDir\n\tbasedir = args.likes_inDir \n\tif basedir[-1] != \"/\":\n\t\tbasedir += \"/\"\n\tif writeloc[-1] != \"/\":\n\t\twriteloc += \"/\"\n\tpop = args.simpop\n\tmodel = args.model\n\t#like_savestring = args.likes_savestring\n\tscore_gw_like_savestring, score_local_like_savestring = get_likes_savestrings(score, basedir) #includes _folded\n\n\t###############################\n\t## CMS_GW : FOLDED, VS. NEUT ##\n\t################## #############\n\t\n\tneut_filename, linked_filename, hit_hi_filename, hit_mid_filename, hit_low_filename, hit_allfreqs_filename = get_likes_filenames(basedir, model, score, pop, like_savestring = score_gw_like_savestring)\n\tlikesFreqs_master_writefilename_global = writeloc + model + \"_\" + score + \"_sel\" + str(pop) + \"_vsNeut_likesFreqs.master.txt\"\n\tallFreqs_master_writefilename_global = writeloc + model + \"_\" + score + \"_sel\" + str(pop) + \"_vsNeut_allFreqs.master.txt\"\n\twrite_master_likesfile(likesFreqs_master_writefilename_global, neut_filename, hit_hi_filename, hit_mid_filename, hit_low_filename)\n\twrite_master_likesfile(allFreqs_master_writefilename_global, neut_filename, hit_allfreqs_filename, hit_allfreqs_filename, hit_allfreqs_filename)\n\t\n\t######################################\n\t## CMS_LOCAL : UNFOLDED, VS. LINKED ##\n\t######################################\n\tneut_filename, linked_filename, hit_hi_filename, hit_mid_filename, hit_low_filename, hit_allfreqs_filename = get_likes_filenames(basedir, model, score, pop, like_savestring = score_local_like_savestring)\n\tlikesFreqs_master_writefilename_local = writeloc + model + \"_\" + score + \"_sel\" + str(pop) + \"_vsLinked_likesFreqs.master.txt\"\n\tallFreqs_master_writefilename_local = writeloc + model + \"_\" + score + \"_sel\" + str(pop) + \"_vsLinked_allFreqs.master.txt\"\n\twrite_master_likesfile(likesFreqs_master_writefilename_local, linked_filename, hit_hi_filename, hit_mid_filename, hit_low_filename)\n\twrite_master_likesfile(allFreqs_master_writefilename_local, linked_filename, hit_allfreqs_filename, hit_allfreqs_filename, hit_allfreqs_filename)\n\treturn \n\n##########\n## MAIN ##\n##########\nif __name__ == '__main__':\n\trunparser = full_parser_likes_from_model()\n\targs = runparser.parse_args()\n\n\t# if called with no arguments, print help\n\tif len(sys.argv)==1:\n\t\trunparser.parse_args(['--help'])\n\n\tsubcommand = sys.argv[1]\n\tfunction_name = 'execute_' + subcommand + \"(args)\"\n\teval(function_name) #points to functions defined above, which wrap other programs in the pipeline\n", "meta": {"hexsha": "5c9f12d70489ca166f5b9d018e380bdd0194beab", "size": 37167, "ext": "py", "lang": "Python", "max_stars_repo_path": "cms/likes_from_model.py", "max_stars_repo_name": "broadinstitute/cms", "max_stars_repo_head_hexsha": "4743ffd3feac08f02be7719c82b3371cb94a4d6b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2015-05-18T14:39:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-22T12:57:07.000Z", "max_issues_repo_path": "cms/likes_from_model.py", "max_issues_repo_name": "broadinstitute/cms", "max_issues_repo_head_hexsha": "4743ffd3feac08f02be7719c82b3371cb94a4d6b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 33, "max_issues_repo_issues_event_min_datetime": "2015-04-13T20:48:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-19T07:27:30.000Z", "max_forks_repo_path": "cms/likes_from_model.py", "max_forks_repo_name": "broadinstitute/cms", "max_forks_repo_head_hexsha": "4743ffd3feac08f02be7719c82b3371cb94a4d6b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2016-03-31T06:56:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-30T16:35:45.000Z", "avg_line_length": 53.8652173913, "max_line_length": 245, "alphanum_fraction": 0.7179756235, "include": true, "reason": "import numpy", "num_tokens": 10269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.33111975283019596, "lm_q1q2_score": 0.19373854476930163}}
{"text": "# -*- coding: utf-8 -*-\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n#\n# Copyright (C) 2013-2018 GEM Foundation\n#\n# OpenQuake is free software: you can redistribute it and/or modify it\n# under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# OpenQuake is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"\nModule exports :class:`CampbellBozorgnia2008`, and\n:class:'CampbellBozorgnia2008Arbitrary'\n\"\"\"\nimport numpy as np\nfrom math import log, exp\nfrom openquake.hazardlib.gsim.base import GMPE, CoeffsTable\nfrom openquake.hazardlib import const\nfrom openquake.hazardlib.imt import PGA, PGV, PGD, CAV, SA\n\n\nclass CampbellBozorgnia2008(GMPE):\n    \"\"\"\n    Implements GMPE developed by Kenneth W. Campbell and Yousef Bozorgnia,\n    published as \"NGA Ground Motion Model for the Geometric Mean Horizontal\n    Component of PGA, PGV, PGD and 5 % Damped Linear Elastic Response Spectra\n    for Periods Ranging from 0.01 to 10s\" (2008, Earthquake Spectra,\n    Volume 24, Number 1, pages 139 - 171).\n    This class implements the model for the Geometric Mean of the elastic\n    spectra.\n    Included in the coefficient set are the coefficients for the\n    Campbell & Bozorgnia (2010) GMPE for predicting Cumulative Absolute\n    Velocity (CAV), published as \"A Ground Motion Prediction Equation for\n    the Horizontal Component of Cumulative Absolute Velocity (CSV) Based on\n    the PEER-NGA Strong Motion Database\" (2010, Earthquake Spectra, Volume 26,\n    Number 3, 635 - 650).\n    \"\"\"\n    #: Supported tectonic region type is active shallow crust\n    DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.ACTIVE_SHALLOW_CRUST\n\n    #: Supported intensity measure types are spectral acceleration, peak\n    #: ground velocity, peak ground displacement and peak ground acceleration\n    #: Additional model for cumulative absolute velocity defined in\n    #: Campbell & Bozorgnia (2010)\n    DEFINED_FOR_INTENSITY_MEASURE_TYPES = set([\n        PGA,\n        PGV,\n        PGD,\n        CAV,\n        SA\n    ])\n\n    #: Supported intensity measure component is orientation-independent\n    #: average horizontal :attr:`~openquake.hazardlib.const.IMC.GMRotI50`\n    DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = const.IMC.GMRotI50\n\n    #: Supported standard deviation types are inter-event, intra-event\n    #: and total, see section \"Aleatory Uncertainty Model\", page 147.\n    DEFINED_FOR_STANDARD_DEVIATION_TYPES = set([\n        const.StdDev.TOTAL,\n        const.StdDev.INTER_EVENT,\n        const.StdDev.INTRA_EVENT\n    ])\n\n    #: Required site parameters are Vs30, Vs30 type (measured or inferred),\n    #: and depth (km) to the 2.5 km/s shear wave velocity layer (z2pt5)\n    REQUIRES_SITES_PARAMETERS = set(('vs30', 'z2pt5'))\n\n    #: Required rupture parameters are magnitude, rake, dip, ztor\n    REQUIRES_RUPTURE_PARAMETERS = set(('mag', 'rake', 'dip', 'ztor'))\n\n    #: Required distance measures are Rrup and Rjb.\n    REQUIRES_DISTANCES = set(('rrup', 'rjb'))\n\n    def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):\n        \"\"\"\n        See :meth:`superclass method\n        <.base.GroundShakingIntensityModel.get_mean_and_stddevs>`\n        for spec of input and result values.\n        \"\"\"\n        # extract dictionaries of coefficients specific to required\n        # intensity measure type and for PGA\n        C = self.COEFFS[imt]\n        C_PGA = self.COEFFS[PGA()]\n\n        # compute median pga on rock (vs30=1100), needed for site response\n        # term calculation\n        # For spectral accelerations at periods between 0.0 and 0.25 s, Sa (T)\n        # cannot be less than PGA on soil, therefore if the IMT is in this\n        # period range it is necessary to calculate PGA on soil\n        if isinstance(imt, SA) and (imt.period > 0.0) and (imt.period < 0.25):\n            get_pga_site = True\n        else:\n            get_pga_site = False\n        pga1100, pga_site = self._compute_imt1100(C_PGA,\n                                                  sites,\n                                                  rup,\n                                                  dists,\n                                                  get_pga_site)\n\n        # Get the median ground motion\n        mean = (self._compute_magnitude_term(C, rup.mag) +\n                self._compute_distance_term(C, rup, dists) +\n                self._compute_style_of_faulting_term(C, rup) +\n                self._compute_hanging_wall_term(C, rup, dists) +\n                self._compute_shallow_site_response(C, sites, pga1100) +\n                self._compute_basin_response_term(C, sites.z2pt5))\n\n        # If it is necessary to ensure that Sa(T) >= PGA (see previous comment)\n        if get_pga_site:\n            idx = mean < np.log(pga_site)\n            mean[idx] = np.log(pga_site[idx])\n\n        stddevs = self._get_stddevs(C,\n                                    sites,\n                                    pga1100,\n                                    C_PGA['s_lny'],\n                                    stddev_types)\n        return mean, stddevs\n\n    def _compute_imt1100(self, C, sites, rup, dists, get_pga_site=False):\n        \"\"\"\n        Computes the PGA on reference (Vs30 = 1100 m/s) rock.\n        \"\"\"\n        # Calculates simple site response term assuming all sites 1100 m/s\n        fsite = (C['c10'] + (C['k2'] * C['n'])) * log(1100. / C['k1'])\n        # Calculates the PGA on rock\n        pga1100 = np.exp(self._compute_magnitude_term(C, rup.mag) +\n                         self._compute_distance_term(C, rup, dists) +\n                         self._compute_style_of_faulting_term(C, rup) +\n                         self._compute_hanging_wall_term(C, rup, dists) +\n                         self._compute_basin_response_term(C, sites.z2pt5) +\n                         fsite)\n        # If PGA at the site is needed then remove factor for rock and\n        # re-calculate on correct site condition\n        if get_pga_site:\n            pga_site = np.exp(np.log(pga1100) - fsite)\n            fsite = self._compute_shallow_site_response(C, sites, pga1100)\n            pga_site = np.exp(np.log(pga_site) + fsite)\n        else:\n            pga_site = None\n        return pga1100, pga_site\n\n    def _compute_magnitude_term(self, C, mag):\n        \"\"\"\n        Returns the magnitude scaling factor (equation (2), page 144)\n        \"\"\"\n        fmag = C['c0'] + C['c1'] * mag\n        if mag <= 5.5:\n            return fmag\n        elif mag > 6.5:\n            return fmag + (C['c2'] * (mag - 5.5)) + (C['c3'] * (mag - 6.5))\n        else:\n            return fmag + (C['c2'] * (mag - 5.5))\n\n    def _compute_distance_term(self, C, rup, dists):\n        \"\"\"\n        Returns the distance scaling factor (equation (3), page 145)\n        \"\"\"\n        return (C['c4'] + C['c5'] * rup.mag) * \\\n            np.log(np.sqrt(dists.rrup ** 2. + C['c6'] ** 2.))\n\n    def _compute_style_of_faulting_term(self, C, rup):\n        \"\"\"\n        Returns the style of faulting factor, depending on the mechanism (rake)\n        and top of rupture depth (equations (4) and (5), pages 145 - 146)\n        \"\"\"\n        frv, fnm = self._get_fault_type_dummy_variables(rup.rake)\n\n        if frv > 0.:\n            # Top of rupture depth term only applies to reverse faults\n            if rup.ztor < 1.:\n                ffltz = rup.ztor\n            else:\n                ffltz = 1.\n        else:\n            ffltz = 0.\n        return (C['c7'] * frv * ffltz) + (C['c8'] * fnm)\n\n    def _get_fault_type_dummy_variables(self, rake):\n        \"\"\"\n        Returns the coefficients FRV and FNM, describing if the rupture is\n        reverse (FRV = 1.0, FNM = 0.0), normal (FRV = 0.0, FNM = 1.0) or\n        strike-slip/oblique-slip (FRV = 0.0, FNM = 0.0). Reverse faults are\n        classified as those with a rake in the range 30 to 150 degrees. Normal\n        faults are classified as having a rake in the range -150 to -30 degrees\n        :returns:\n            FRV, FNM\n        \"\"\"\n        if (rake > 30.0) and (rake < 150.):\n            return 1., 0.\n        elif (rake > -150.0) and (rake < -30.0):\n            return 0., 1.\n        else:\n            return 0., 0.\n\n    def _compute_hanging_wall_term(self, C, rup, dists):\n        \"\"\"\n        Returns the hanging wall scaling term, the product of the scaling\n        coefficient and four separate scaling terms for distance, magnitude,\n        rupture depth and dip (equations 6 - 10, page 146). Individual\n        scaling terms defined in separate functions\n        \"\"\"\n        return (C['c9'] *\n                self._get_hanging_wall_distance_term(dists, rup.ztor) *\n                self._get_hanging_wall_magnitude_term(rup.mag) *\n                self._get_hanging_wall_depth_term(rup.ztor) *\n                self._get_hanging_wall_dip_term(rup.dip))\n\n    def _get_hanging_wall_distance_term(self, dists, ztor):\n        \"\"\"\n        Returns the hanging wall distance scaling term (equation 7, page 146)\n        \"\"\"\n        fhngr = np.ones_like(dists.rjb, dtype=float)\n        idx = dists.rjb > 0.\n        if ztor < 1.:\n            temp_rjb = np.sqrt(dists.rjb[idx] ** 2. + 1.)\n            r_max = np.max(np.column_stack([dists.rrup[idx], temp_rjb]),\n                           axis=1)\n            fhngr[idx] = (r_max - dists.rjb[idx]) / r_max\n        else:\n            fhngr[idx] = (dists.rrup[idx] - dists.rjb[idx]) / dists.rrup[idx]\n        return fhngr\n\n    def _get_hanging_wall_magnitude_term(self, mag):\n        \"\"\"\n        Returns the hanging wall magnitude scaling term (equation 8, page 146)\n        \"\"\"\n        if mag <= 6.0:\n            return 0.\n        elif mag >= 6.5:\n            return 1.\n        else:\n            return 2. * (mag - 6.0)\n\n    def _get_hanging_wall_depth_term(self, ztor):\n        \"\"\"\n        Returns the hanging wall depth scaling term (equation 9, page 146)\n        \"\"\"\n        if ztor >= 20.0:\n            return 0.\n        else:\n            return (20. - ztor) / 20.0\n\n    def _get_hanging_wall_dip_term(self, dip):\n        \"\"\"\n        Returns the hanging wall dip scaling term (equation 10, page 146)\n        \"\"\"\n        if dip > 70.0:\n            return (90.0 - dip) / 20.0\n        else:\n            return 1.0\n\n    def _compute_shallow_site_response(self, C, sites, pga1100):\n        \"\"\"\n        Returns the shallow site response term (equation 11, page 146)\n        \"\"\"\n        stiff_factor = C['c10'] + (C['k2'] * C['n'])\n        # Initially default all sites to intermediate rock value\n        fsite = stiff_factor * np.log(sites.vs30 / C['k1'])\n        # Check for soft soil sites\n        idx = sites.vs30 < C['k1']\n        if np.any(idx):\n            pga_scale = np.log(pga1100[idx] +\n                               (C['c'] * ((sites.vs30[idx] / C['k1']) **\n                                C['n']))) - np.log(pga1100[idx] + C['c'])\n            fsite[idx] = C['c10'] * np.log(sites.vs30[idx] / C['k1']) + \\\n                (C['k2'] * pga_scale)\n        # Any very hard rock sites are rendered to the constant amplification\n        # factor\n        idx = sites.vs30 >= 1100.\n        if np.any(idx):\n            fsite[idx] = stiff_factor * log(1100. / C['k1'])\n\n        return fsite\n\n    def _compute_basin_response_term(self, C, z2pt5):\n        \"\"\"\n        Returns the basin response term (equation 12, page 146)\n        \"\"\"\n        fsed = np.zeros_like(z2pt5, dtype=float)\n        idx = z2pt5 < 1.0\n        if np.any(idx):\n            fsed[idx] = C['c11'] * (z2pt5[idx] - 1.0)\n\n        idx = z2pt5 > 3.0\n        if np.any(idx):\n            fsed[idx] = (C['c12'] * C['k3'] * exp(-0.75)) *\\\n                (1.0 - np.exp(-0.25 * (z2pt5[idx] - 3.0)))\n        return fsed\n\n    def _get_stddevs(self, C, sites, pga1100, sigma_pga, stddev_types):\n        \"\"\"\n        Returns the standard deviations as described in the \"ALEATORY\n        UNCERTAINTY MODEL\" section of the paper. Equations 13 to 19, pages 147\n        to 151\n        \"\"\"\n        std_intra = self._compute_intra_event_std(C,\n                                                  sites.vs30,\n                                                  pga1100,\n                                                  sigma_pga)\n\n        std_inter = C['t_lny'] * np.ones_like(sites.vs30)\n        stddevs = []\n        for stddev_type in stddev_types:\n            assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES\n            if stddev_type == const.StdDev.TOTAL:\n                stddevs.append(self._get_total_sigma(C, std_intra, std_inter))\n            elif stddev_type == const.StdDev.INTRA_EVENT:\n                stddevs.append(std_intra)\n            elif stddev_type == const.StdDev.INTER_EVENT:\n                stddevs.append(std_inter)\n        return stddevs\n\n    def _compute_intra_event_std(self, C, vs30, pga1100, sigma_pga):\n        \"\"\"\n        Returns the intra-event standard deviation at the site, as defined in\n        equation 15, page 147\n        \"\"\"\n        # Get intra-event standard deviation at the base of the site profile\n        sig_lnyb = np.sqrt(C['s_lny'] ** 2. - C['s_lnAF'] ** 2.)\n        sig_lnab = np.sqrt(sigma_pga ** 2. - C['s_lnAF'] ** 2.)\n        # Get linearised relationship between f_site and ln PGA\n        alpha = self._compute_intra_event_alpha(C, vs30, pga1100)\n\n        return np.sqrt(\n            (sig_lnyb ** 2.) +\n            (C['s_lnAF'] ** 2.) +\n            ((alpha ** 2.) * (sig_lnab ** 2.)) +\n            (2.0 * alpha * C['rho'] * sig_lnyb * sig_lnab))\n\n    def _compute_intra_event_alpha(self, C, vs30, pga1100):\n        \"\"\"\n        Returns the linearised functional relationship between fsite and\n        pga1100, determined from the partial derivative defined on equation 17\n        on page 148\n        \"\"\"\n        alpha = np.zeros_like(vs30, dtype=float)\n        idx = vs30 < C['k1']\n        if np.any(idx):\n            temp1 = (pga1100[idx] +\n                     C['c'] * (vs30[idx] / C['k1']) ** C['n']) ** -1.\n            temp1 = temp1 - ((pga1100[idx] + C['c']) ** -1.)\n            alpha[idx] = C['k2'] * pga1100[idx] * temp1\n\n        return alpha\n\n    def _get_total_sigma(self, C, std_intra, std_inter):\n        \"\"\"\n        Returns the total sigma term as defined by equation 16, page 147\n        This method is defined here as the Campbell & Bozorgnia (2008) model\n        can also be applied to the \"arbitrary\" horizontal component\n        definition, in which case the total sigma is modified.\n        \"\"\"\n        return np.sqrt(std_intra ** 2. + std_inter ** 2.)\n\n    COEFFS = CoeffsTable(sa_damping=5, table=\"\"\"\\\n      imt      c0     c1      c2      c3      c4    c5    c6     c7      c8     c9     c10    c11   c12    k1      k2     k3     c     n  s_lny  t_lny s_lnAF  c_lny    rho\n      cav  -4.354  0.942  -0.178  -0.346  -1.309 0.087  7.24  0.111  -0.108  0.362   2.549  0.090  1.277  400  -2.690  1.000  1.88  1.18  0.371  0.196  0.300  0.089  0.735\n      pgd  -5.270  1.600  -0.070   0.000  -2.000  0.17  4.00  0.000   0.000  0.000  -0.820  0.300  1.000  400   0.000  2.744  1.88  1.18  0.667  0.485  0.300  0.290  0.174\n      pgv   0.954  0.696  -0.309  -0.019  -2.016  0.17  4.00  0.245   0.000  0.358   1.694  0.092  1.000  400  -1.955  1.929  1.88  1.18  0.484  0.203  0.300  0.190  0.691\n      pga  -1.715  0.500  -0.530  -0.262  -2.118  0.17  5.60  0.280  -0.120  0.490   1.058  0.040  0.610  865  -1.186  1.839  1.88  1.18  0.478  0.219  0.300  0.166  1.000\n    0.010  -1.715  0.500  -0.530  -0.262  -2.118  0.17  5.60  0.280  -0.120  0.490   1.058  0.040  0.610  865  -1.186  1.839  1.88  1.18  0.478  0.219  0.300  0.166  1.000\n    0.020  -1.680  0.500  -0.530  -0.262  -2.123  0.17  5.60  0.280  -0.120  0.490   1.102  0.040  0.610  865  -1.219  1.840  1.88  1.18  0.480  0.219  0.300  0.166  0.999\n    0.030  -1.552  0.500  -0.530  -0.262  -2.145  0.17  5.60  0.280  -0.120  0.490   1.174  0.040  0.610  908  -1.273  1.841  1.88  1.18  0.489  0.235  0.300  0.165  0.989\n    0.050  -1.209  0.500  -0.530  -0.267  -2.199  0.17  5.74  0.280  -0.120  0.490   1.272  0.040  0.610 1054  -1.346  1.843  1.88  1.18  0.510  0.258  0.300  0.162  0.963\n    0.075  -0.657  0.500  -0.530  -0.302  -2.277  0.17  7.09  0.280  -0.120  0.490   1.438  0.040  0.610 1086  -1.471  1.845  1.88  1.18  0.520  0.292  0.300  0.158  0.922\n    0.100  -0.314  0.500  -0.530  -0.324  -2.318  0.17  8.05  0.280  -0.099  0.490   1.604  0.040  0.610 1032  -1.624  1.847  1.88  1.18  0.531  0.286  0.300  0.170  0.898\n    0.150  -0.133  0.500  -0.530  -0.339  -2.309  0.17  8.79  0.280  -0.048  0.490   1.928  0.040  0.610  878  -1.931  1.852  1.88  1.18  0.532  0.280  0.300  0.180  0.890\n    0.200  -0.486  0.500  -0.446  -0.398  -2.220  0.17  7.60  0.280  -0.012  0.490   2.194  0.040  0.610  748  -2.188  1.856  1.88  1.18  0.534  0.249  0.300  0.186  0.871\n    0.250  -0.890  0.500  -0.362  -0.458  -2.146  0.17  6.58  0.280   0.000  0.490   2.351  0.040  0.700  654  -2.381  1.861  1.88  1.18  0.534  0.240  0.300  0.191  0.852\n    0.300  -1.171  0.500  -0.294  -0.511  -2.095  0.17  6.04  0.280   0.000  0.490   2.460  0.040  0.750  587  -2.518  1.865  1.88  1.18  0.544  0.215  0.300  0.198  0.831\n    0.400  -1.466  0.500  -0.186  -0.592  -2.066  0.17  5.30  0.280   0.000  0.490   2.587  0.040  0.850  503  -2.657  1.874  1.88  1.18  0.541  0.217  0.300  0.206  0.785\n    0.500  -2.569  0.656  -0.304  -0.536  -2.041  0.17  4.73  0.280   0.000  0.490   2.544  0.040  0.883  457  -2.669  1.883  1.88  1.18  0.550  0.214  0.300  0.208  0.735\n    0.750  -4.844  0.972  -0.578  -0.406  -2.000  0.17  4.00  0.280   0.000  0.490   2.133  0.077  1.000  410  -2.401  1.906  1.88  1.18  0.568  0.227  0.300  0.221  0.628\n    1.000  -6.406  1.196  -0.772  -0.314  -2.000  0.17  4.00  0.255   0.000  0.490   1.571  0.150  1.000  400  -1.955  1.929  1.88  1.18  0.568  0.255  0.300  0.225  0.534\n    1.500  -8.692  1.513  -1.046  -0.185  -2.000  0.17  4.00  0.161   0.000  0.490   0.406  0.253  1.000  400  -1.025  1.974  1.88  1.18  0.564  0.296  0.300  0.222  0.411\n    2.000  -9.701  1.600  -0.978  -0.236  -2.000  0.17  4.00  0.094   0.000  0.371  -0.456  0.300  1.000  400  -0.299  2.019  1.88  1.18  0.571  0.296  0.300  0.226  0.331\n    3.000 -10.556  1.600  -0.638  -0.491  -2.000  0.17  4.00  0.000   0.000  0.154  -0.820  0.300  1.000  400   0.000  2.110  1.88  1.18  0.558  0.326  0.300  0.229  0.289\n    4.000 -11.212  1.600  -0.316  -0.770  -2.000  0.17  4.00  0.000   0.000  0.000  -0.820  0.300  1.000  400   0.000  2.200  1.88  1.18  0.576  0.297  0.300  0.237  0.261\n    5.000 -11.684  1.600  -0.070  -0.986  -2.000  0.17  4.00  0.000   0.000  0.000  -0.820  0.300  1.000  400   0.000  2.291  1.88  1.18  0.601  0.359  0.300  0.237  0.200\n    7.500 -12.505  1.600  -0.070  -0.656  -2.000  0.17  4.00  0.000   0.000  0.000  -0.820  0.300  1.000  400   0.000  2.517  1.88  1.18  0.628  0.428  0.300  0.271  0.174\n    10.00 -13.087  1.600  -0.070  -0.422  -2.000  0.17  4.00  0.000   0.000  0.000  -0.820  0.300  1.000  400   0.000  2.744  1.88  1.18  0.667  0.485  0.300  0.290  0.174\n    \"\"\")\n\n\nclass CampbellBozorgnia2008Arbitrary(CampbellBozorgnia2008):\n    \"\"\"\n    Implements the Campbell & Bozorgnia (2008) GMPE as modified to represent\n    the arbitrary horizontal component of ground motion, instead of the\n    Rotationally Independent Geometric Mean (GMRotI) originally defined in\n    the paper.\n    \"\"\"\n\n    #: Supported intensity measure component is arbitrary horizontal\n    #: :attr:`~openquake.hazardlib.const.IMC.HORIZONTAL`,\n    DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = const.IMC.HORIZONTAL\n\n    def _get_total_sigma(self, C, std_intra, std_inter):\n        \"\"\"\n        Returns the total sigma term for the arbitrary horizontal component of\n        ground motion defined by equation 18, page 150\n        \"\"\"\n        return np.sqrt(std_intra ** 2. + std_inter ** 2. + C['c_lny'] ** 2.)\n", "meta": {"hexsha": "8f45b6206bbe8aef19f6f4054b1027f530ae20d3", "size": 20174, "ext": "py", "lang": "Python", "max_stars_repo_path": "openquake/hazardlib/gsim/campbell_bozorgnia_2008.py", "max_stars_repo_name": "gfzriesgos/shakyground-lfs", "max_stars_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-01T00:28:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-01T00:28:24.000Z", "max_issues_repo_path": "openquake/hazardlib/gsim/campbell_bozorgnia_2008.py", "max_issues_repo_name": "gfzriesgos/shakyground-lfs", "max_issues_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-08-31T14:14:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-11T12:53:13.000Z", "max_forks_repo_path": "openquake/hazardlib/gsim/campbell_bozorgnia_2008.py", "max_forks_repo_name": "gfzriesgos/shakyground-lfs", "max_forks_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-08-31T14:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-17T10:06:02.000Z", "avg_line_length": 48.8474576271, "max_line_length": 171, "alphanum_fraction": 0.5711807277, "include": true, "reason": "import numpy", "num_tokens": 7207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.19373853411235645}}
{"text": "# -*- coding: utf-8 -*-\n#!/usr/bin/env python\n\n__author__ = \"Luocheng Huang\"\n__copyright__ = \"Copyright 2018\"\n__credits__ = [\"Luocheng Huang\"]\n__license__ = \"GPL\"\n__version__ = \"2.0.2\"\n__maintainer__ = \"Luocheng Huang\"\n__email__ = \"luocheng@uw.edu\"\n__status__ = \"Production\"\n\nimport pandas as pd\nimport os\nimport numpy as np\nimport math\nimport time as time\nfrom multiprocessing import Pool\nimport matplotlib.pyplot as plt\nimport S4\n\n\n\n#CWD = os.getcwd()+'/'\n\n\n    \ndef simulate_one(config, field=1):\n    \"\"\"a wrapper for pickling\n    simulates one instance\n    \"\"\"\n    global FIELD\n    FIELD = field\n    new = RCWA.Simulation()\n    new.load_input(config)\n    return new.run()\n\n\nclass RCWA:\n    \"\"\"\n    An rcwa simulation ojbect\n    \"\"\"\n    \n    \n    def __init__(self, input_list=None, cores=10, field = None):\n        self.input = input_list\n        self.cores = cores\n        self.field = field\n        global FIELD\n        \"\"\"field is the amount of field in the center measured. 1 is 100% .5 is 25%\n            returns the mean value if field==None\n            else returns the center field.\"\"\"\n        FIELD = field\n        pass\n    \n    \n    def timeit(method):\n        \"\"\"a decor for timing methods, should be used as a decorator\n        \"\"\"\n        def timed(*args, **kw):\n            ts = time.time()\n            result = method(*args, **kw)\n            te = time.time()\n            if 'log_time' in kw:\n                name = kw.get('log_name', method.__name__.upper())\n                kw['log_time'][name] = int((te - ts) * 1000)\n            else:\n                print '%r  %2.2f s' % \\\n                      (method.__name__, (te - ts) )\n            return result\n        return timed\n\n\n    @timeit\n    def simulate_and_graph(self):\n        \"\"\"\n        inputs the attribute list, \n        :return: simulate results\n        \"\"\"\n\n        p = Pool(self.cores)\n        df = pd.DataFrame()\n        FIELD = self.field\n        solution = p.map(simulate_one, self.input)  # create a pool of workers and map it onto different cores\n        p.close() # prevent memory leakage \n        p.join() # synchronization point\n\n        t_list = []\n        p_list = []\n        for s in solution:\n            t_list.append(s[0])\n            p_list.append(s[1])\n        # make phase continuous\n        # new_p = unwrap(p_list)\n        new_p = [x[0] / (2*math.pi) for x in p_list]\n\n        config = self.input[0]\n\n        # plot data\n        plt.figure(0)\n        plt.figure(figsize=(10, 5), dpi=200)\n        label1 = 'phase'\n        label2 = 'amplitude'\n        plt.plot(new_p, label=label1)\n        plt.plot(t_list, label=label2)\n        plt.xlabel('Grating post width')\n        plt.ylabel('amp & phase')\n        plt.title('Wavelength = {} nm'.format('unknown'))\n        plt.legend()\n\n\n        plt.savefig(\"{}.png\".format(('unknown')))\n        plt.show();\n        plt.clf();\n\n        # save to csv\n        a = (new_p, t_list)\n\n        np.savetxt(\"data_{}.csv\".format(('unknown')), a, delimiter=\",\")\n\n\n        pass\n\n    \n    @timeit\n    def simulate(self):\n        \"\"\"\n        inputs the attribute list, \n        :return: simulate results\n        \"\"\"\n\n        p = Pool(self.cores)\n        df = pd.DataFrame(self.input)\n        solution = p.map(simulate_one, self.input)  # create a pool of workers and map it onto different cores\n        solutions = pd.DataFrame(solution)\n        p.close() # prevent memory leakage \n        p.join() # synchronization point\n\n        result = pd.concat([df, solutions], axis=1)\n        result.columns = ['CSCS', 'e_field']\n\n        # make phase continuous\n        # new_p = unwrap(p_list)\n\n        return result\n        \n\n    \n    \n\n    class Simulation:\n        \"\"\"A simulation object\"\"\"\n        \n        def __init__(self):\n            self.layers = []\n            self.basis = ((1,0),(0,1))\n            self.NumBasis=150\n            self.layers = None\n            self.layer_material = None\n            self.layer_thickness = None\n            self.layer_pattern = None\n            self.transmission = None\n            self.wavelength = None\n            self.buffer = 0.1\n            self.Nxy = 52\n        \n        \n        def load_input(self,input_instance):\n            \"\"\"loades the canonical id into local variables\"\"\"\n            \n            \n            # the first step is to assign values to the variables from the input_instance\n            parts = input_instance.split('/')\n            first_arg = parts[0].split('-')\n            if first_arg[0] == 't':\n                self.transmission = True\n            elif first_arg[0] == 'r':\n                self.transmission = False\n            \n            self.wavelength = float(first_arg[1])\n            self.basis = eval(first_arg[2])\n            \n            self.layers = parts[1:]\n            layers_split = [layer.split('=') for layer in self.layers]\n            self.layer_material = [layer_split[0] for layer_split in layers_split]\n            split_2 = [layer_split[1] for layer_split in layers_split]\n            self.layer_thickness = []\n            self.layer_pattern = []\n            for x in split_2:\n                x_split = x.split(':')\n                if len(x_split) == 1:\n                    self.layer_thickness.append(float(x_split[0]))\n                    self.layer_pattern.append(None)\n                else:\n                    self.layer_thickness.append(float(x_split[0]))\n                    self.layer_pattern.append(x_split[1].split('-'))\n                    \n                    \n\n        \n        def run(self):\n            \"\"\"create layers and return a S4 object\n            :type attr: dict\n            return S\n            \"\"\"\n            def querry_n(material, wavelength):\n                \"\"\"\n                given the material in string, wavelength in µm\n                output (n,k)\n                \"\"\"\n                mat = pd.read_csv('../rcwa/n_data/{}_n.csv'.format(material))\n\n                w = mat['Wavelength, µm']\n                n_list = mat['n']\n                k_list = mat['k']\n\n                n = np.interp(wavelength, w, n_list) # interpolate the refractive index value\n                k = np.interp(wavelength, w, k_list) # interpolate the k value\n\n                return n + k*1j      \n\n            # define the S object\n            S = S4.New(Lattice=self.basis,\n                       NumBasis=self.NumBasis)  # orthogonal basis, numbasis scales with memory O(N^2)\n\n            # define materials\n            for material in set(self.layer_material):\n                n = querry_n(material,self.wavelength)\n                # defines permittivity in terms of refractive index\n                eps = n**2\n                S.SetMaterial(Name=material, Epsilon=eps)\n            S.SetMaterial(Name='Vacuum', Epsilon=1.0)\n\n            # define layers\n            S.AddLayer(Name='air_above', Thickness=self.buffer, Material='Vacuum')\n            index = 0\n            for layer in zip(self.layer_material, self.layer_thickness, self.layer_pattern):\n                index += 1\n                if layer[2] == None:\n                    S.AddLayer(Name=str(index), Thickness=layer[1], Material=layer[0])\n                else:\n                    S.AddLayer(Name=str(index), Thickness=layer[1], Material='Vacuum')\n                    if '+' in layer[2]:\n                        patterns = layer[2].split('+')\n                    else:\n                        patterns = layer[2]\n                    for pattern in patterns:\n                        shape = pattern[0]\n                        coor = eval(pattern[1:])\n                        if shape == 'C':\n                            # create circle features\n                            if coor[2] != 0:\n                                S.SetRegionCircle(\n                                    Layer = str(index),\n                                    Material = layer[0],\n                                    Center = (coor[0],coor[1]),\n                                    Radius = coor[2]\n                                )\n                        elif shape == 'S':\n                        # create circle features\n                            if coor[2] != 0:\n                                S.SetRegionSquare(\n                                    Layer = str(index),\n                                    Material = layer[0],\n                                    Center = (coor[0],coor[1]),\n                                    Angle = 0,\n                                    Halfwidths = (coor[2], coor[2])\n                                    \n                                )\n            \n            S.AddLayer(Name='below', Thickness=self.buffer, Material='Vacuum')\n\n\n            # simulation settings\n            S.SetExcitationPlanewave(IncidenceAngles=(0.0, 0.0), sAmplitude=0.0,\n                                     pAmplitude=1.0, Order=0)\n\n            S.SetFrequency(1/self.wavelength)\n\n            # For higher accuracy\n            S.SetOptions(SubpixelSmoothing=True)\n            \n            # e is array of dimension Nx by Ny, each element is a tuple of length 3\n            \n            if  not self.transmission:\n                z_pos = self.buffer/(2.0)\n            else:\n                z_pos = self.buffer*1.5+sum(self.layer_thickness)\n            \n            e, h = S.GetFieldsOnGrid(z=z_pos, NumSamples=(self.Nxy, self.Nxy),\n                                     Format='Array')  \n            e = np.array(e)\n            if not self.transmission:\n                e = e - np.exp(1j*2*np.pi/self.wavelength*self.buffer/2)\n                \n            if FIELD==None:\n                e_field = np.mean(e[:,:,0])  # adding 1 removes incident wave \n            else:                \n                (a,b,_) = np.shape(e)\n                edge = (1-FIELD)/2.0\n                e_field = e[int(a*edge):int(a*(1-edge)),int(b*edge):int(b*(1-edge)),0]\n                \n            e_field = np.round(e_field, 3)\n            \n            return pd.Series(str(e_field.tolist()))\n", "meta": {"hexsha": "0296e0b41c6d377cfb7f18ec7aa337fa255b82fe", "size": 9957, "ext": "py", "lang": "Python", "max_stars_repo_path": "rcwa/RCWA.py", "max_stars_repo_name": "Luochenghuang/shared_lib", "max_stars_repo_head_hexsha": "47197a271dd87fb3b6776a8996dc92019d6f439a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rcwa/RCWA.py", "max_issues_repo_name": "Luochenghuang/shared_lib", "max_issues_repo_head_hexsha": "47197a271dd87fb3b6776a8996dc92019d6f439a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-11-10T23:32:31.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-10T23:32:31.000Z", "max_forks_repo_path": "rcwa/RCWA.py", "max_forks_repo_name": "Luochenghuang/shared_lib", "max_forks_repo_head_hexsha": "47197a271dd87fb3b6776a8996dc92019d6f439a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-07T21:41:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-07T21:41:07.000Z", "avg_line_length": 32.5392156863, "max_line_length": 110, "alphanum_fraction": 0.4794616852, "include": true, "reason": "import numpy", "num_tokens": 2166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3593641588823761, "lm_q1q2_score": 0.1936912517541437}}
{"text": "\"\"\"Model of somatostatin brain extracellular release, diffusion, and loss.\r\n\"\"\"\r\n\r\nfrom neuron import h, rxd\r\nfrom neuron.units import nM, uM, cm, s, M, nm, um\r\nimport numpy as np\r\n\r\n# Avogadro's Number from scipy\r\nfrom scipy.constants import N_A\r\nfrom .basemodel import ModelBase\r\n\r\n\r\nclass Model(ModelBase):\r\n    \"\"\"A model of somatostatin release, diffusion, and loss in the brain extracellular space.\r\n\r\n    This model simulates the photorelease of the neuropeptide somatostatin from\r\n    gold coated nanovesicles and its subsequent diffusion in the brain\r\n    extracellular space. An initial cylindrical bolus of somatostatin is placed in\r\n    the center of the extracellular domain to approximate the condition after\r\n    photorelease from gold coated nanovesicles with release stimulated by a\r\n    tornado scan of radius 30 micron with a multi-photon microscope. Somatostatin\r\n    can then diffuse away from the release site and can be lost from the\r\n    extracellular space through a first order decay reaction.\r\n\r\n    Model components (accessible as model attributes):\r\n\r\n        Compartments:\r\n            ecs -> rxd.Extracellular: The extracellular space domain and its\r\n                parameters like volume fraction and tortuosity.\r\n        Species:\r\n            sst -> rxd.Species: Neuropeptide somatostatin (sst) that is\r\n                photoreleased in the brain extracellular space.\r\n        Parameters:\r\n            loss_rate -> rxd.Parameter: Defines the kinetic rate for first order\r\n                loss of sst from the extracellular space.\r\n        Reactions:\r\n            sst_loss -> rxd.Rate: The reaction corresponding to first order loss\r\n                of sst from the extracellular space.\r\n                Forward reaction: sst --loss_rate--> None\r\n\r\n    \"\"\"\r\n\r\n    def __init__(\r\n        self,\r\n        volume_fraction: float = 0.2,\r\n        tortuosity: float = 1.0,\r\n        dx: float = 5,\r\n        xlo: float = -200.0,\r\n        xhi: float = 200.0,\r\n        ylo: float = -200.0,\r\n        yhi: float = 200.0,\r\n        zlo: float = -200.0,\r\n        zhi: float = 200.0,\r\n    ):\r\n        \"\"\"Defines and constructs all the model components.\r\n\r\n        Args:\r\n            volume_fraction: The volume fraction of extracellular space\r\n                (unitless). DEFAULT: 0.2\r\n            tortuosity: The tortuosity for diffusion in the extracellular space\r\n                (unitless). DEFAULT: 1.\r\n            dx: The discrettization size for volume voxels in the extracellular\r\n                space in microns. DEFAUT: 5\r\n            xlo: The position of the lower edge of the extracellular simulation\r\n                domain along the x-direction in microns. DEFAULT: -200.\r\n            xhi: The position of the upper edge of the extracellular simulation\r\n                domain along the x-direction in microns. DEFAULT: 200.\r\n            ylo: The position of the lower edge of the extracellular simulation\r\n                domain along the y-direction in microns. DEFAULT: -200.\r\n            yhi: The position of the upper edge of the extracellular simulation\r\n                domain along the y-direction in microns. DEFAULT: 200.\r\n            zlo: The position of the lower edge of the extracellular simulation\r\n                domain along the z-direction in microns. DEFAULT: -200.\r\n            zhi: The position of the upper edge of the extracellular simulation\r\n                domain along the z-direction in microns. DEFAULT: 200.\r\n        \"\"\"\r\n        # Where? -- specify the regions\r\n        # For extracellular reaction-diffusion we just have one\r\n        # Extracellular region.\r\n        self.ecs = rxd.Extracellular(\r\n            xlo=xlo,\r\n            ylo=ylo,\r\n            zlo=zlo,\r\n            xhi=xhi,\r\n            yhi=yhi,\r\n            zhi=zhi,\r\n            dx=dx,\r\n            volume_fraction=volume_fraction,\r\n            tortuosity=tortuosity,\r\n        )\r\n        # Who? -- define all the species\r\n        # Calcein\r\n        # The effective diffusion coefficient for fluorescently labelled SST\r\n        # in acute brain slices from integrative optical imaging (IOI) is\r\n        # 8.9+-1.3 x10^-7 cm^2/s. Xiong et al. 2021 bioRxiv https://doi.org/10.1101/2021.09.10.459853\r\n        d_sst = (\r\n            8.9e-7 * cm ** 2 / s\r\n        )  # effective diffusion coefficient (factoring in tortuosity)\r\n        # Approximate SST photorelease from gold coated nanovesicles as in\r\n        # Xiong et al. 2021 bioRxiv https://doi.org/10.1101/2021.09.10.459853\r\n        # Use an initial bolus of SST with a uniform concentration corresponding\r\n        # to the estimated 1.2x10^8 released molecs inside a disc that\r\n        # approximates the two-photon tornado scan area used for nanovesicle\r\n        # release.\r\n        r_stim = 30 * um  # radius of the tornado scan area\r\n        Qsst = 1.2e8  # Number of SST molecules released during photostimulation\r\n        focal_disc_z = 12  # z-height of the 2-photon focal plane\r\n        disc_vol = (\r\n            np.pi * r_stim ** 2 * focal_disc_z\r\n        )  # volume of the tornado scan area.\r\n        # SST concentration accounting for the disc volume and volume faction.\r\n        sst_0 = ((Qsst / N_A) / disc_vol) / volume_fraction * 1e15 * M\r\n        self.sst = rxd.Species(\r\n            self.ecs,\r\n            name=\"somatostatin\",\r\n            d=d_sst,\r\n            charge=0,\r\n            initial=lambda nd: sst_0\r\n            if (nd.x3d ** 2 + nd.y3d ** 2 < r_stim ** 2)\r\n            and (np.abs(nd.z3d) < focal_disc_z / 2)\r\n            else 0,\r\n            ecs_boundary_conditions=0.0,\r\n        )\r\n        # What? -- specify all the reactions\r\n        # 1st-order loss of SST\r\n        # Loss rate of SST estimated in range 0.023-0.048 per second.\r\n        # Xiong et al. 2021 bioRxiv https://doi.org/10.1101/2021.09.10.459853\r\n        kf = 3.6e-2 / s  # the reaction rate\r\n        self.loss_rate = rxd.Parameter(self.ecs, value=kf)\r\n        self.sst_loss = rxd.Rate(self.sst, -self.loss_rate * self.sst)\r\n\r\n        # Initialize private variables -- required for all models\r\n        self._times = None  # We'll store the time points in our simulation trajectory.\r\n        self._observables = None  # We'll assign our observables to this variable.\r\n\r\n    def simulate(self, time_step: float, n_steps: int, output_frequency: int = 1):\r\n        \"\"\"Run the simulation and set the desired trajectory ouptuts.\r\n\r\n        Args:\r\n            time_step: The time interval between each step of the simulation\r\n                trajectory in milliseconds. Times not in milliseconds can\r\n                be converted using unit conversions from the neuron.units\r\n                module.\r\n            n_steps: The total number of simulation steps to run.\r\n            output_frequency: Set the frequency for computing and storing\r\n                any observables during the simulation. DEFAULT: 1\r\n\r\n        \"\"\"\r\n        # Set the time step and initialize the simulator.\r\n        h.dt = time_step\r\n        h.finitialize()\r\n        # define any observables that you want to store\r\n        times = list()\r\n        sst_zproject_mean = list()\r\n        # Run each step.\r\n        for f in range(n_steps + 1):\r\n            if (f == 0) or ((f % output_frequency) == 0):\r\n                # simulation time\r\n                times.append(f * time_step)\r\n                # Get the mean value z-projection of the Calcein concentration.\r\n                sst_zproject_mean.append(self.sst[self.ecs].states3d.mean(2))\r\n            h.fadvance()\r\n        self._times = np.array(times)\r\n        self._observables = {\"zproject_mean_sst\": sst_zproject_mean}\r\n        return\r\n\r\n\r\nmodel = Model()\r\n", "meta": {"hexsha": "9ba22e365628186e39b3b3fabdaefaecd9460490", "size": 7655, "ext": "py", "lang": "Python", "max_stars_repo_path": "extmodels/somatostatin.py", "max_stars_repo_name": "NTBEL/extracellular-models", "max_stars_repo_head_hexsha": "b69493a331aca735f419440f21809807075f596a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "extmodels/somatostatin.py", "max_issues_repo_name": "NTBEL/extracellular-models", "max_issues_repo_head_hexsha": "b69493a331aca735f419440f21809807075f596a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extmodels/somatostatin.py", "max_forks_repo_name": "NTBEL/extracellular-models", "max_forks_repo_head_hexsha": "b69493a331aca735f419440f21809807075f596a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.2958579882, "max_line_length": 102, "alphanum_fraction": 0.6094056172, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.359364131437828, "lm_q1q2_score": 0.19369123696199278}}
{"text": "import os\nimport sys\nfrom functools import lru_cache, wraps\n\nimport astropy.units as astropy_units\nimport numpy as np\nimport six\nfrom astropy.io import fits\n\nfrom astromodels.functions.function import Function1D, FunctionMeta\nfrom astromodels.utils import configuration\nfrom astromodels.utils import _get_data_file_path\nimport gc\n\ntry:\n\n    import pyatomdb\n\n    has_atomdb = True\n\nexcept:\n\n    has_atomdb = False\n\nif has_atomdb:\n    # APEC class\n    \n    class APEC(Function1D, metaclass=FunctionMeta):\n        r\"\"\"\n        description :\n            The Astrophysical Plasma Emission Code (APEC, Smith et al. 2001)\n            contributed by Dominique Eckert\n        parameters :\n            K :\n                desc : Normalization in units of 1e-14/(4*pi*(1+z)^2*dA*2)*EM\n                initial value : 1.0\n                is_normalization : True\n                transformation : log10\n                min : 1e-30\n                max : 1e3\n                delta : 0.1\n            kT :\n                desc : Plasma temperature\n                initial value : 1.0\n                min : 0.08\n                max : 64\n                delta : 0.1\n            abund :\n                desc : Metal abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            redshift :\n                desc : Source redshift\n                initial value : 0.1\n                min : 0.0\n                max : 10.0\n                delta : 1e-3\n                fix : yes\n\n        \"\"\"\n\n        def _set_units(self, x_unit, y_unit):\n            self.kT.unit = astropy_units.keV\n\n            self.abund.unit = astropy_units.dimensionless_unscaled\n\n            self.redshift.unit = astropy_units.dimensionless_unscaled\n\n            self.K.unit = y_unit\n\n        def init_session(self, abund_table=\"AG89\"):\n            # initialize PyAtomDB session\n            self.session = pyatomdb.spectrum.CIESession(abundset=abund_table)\n\n        def clean(self):\n            \"\"\"\n            Clean the current APEC session to avoid having too many open files\n            :returns: \n            \"\"\"\n            \n            self.session = None\n            del self.session\n            gc.collect()\n\n        def evaluate(self, x, K, kT, abund, redshift):\n            assert self.session is not None, \"please run init_session(abund)\"\n\n            sess = self.session\n\n            nval = len(x)\n\n            xz = x * (1.0 + redshift)\n\n            ebplus = (np.roll(xz, -1) + xz)[: nval - 1] / 2.0\n\n            ebounds = np.empty(nval + 1)\n\n            ebounds[1:nval] = ebplus\n\n            ebounds[0] = xz[0] - (ebplus[0] - xz[0])\n\n            ebounds[nval] = xz[nval - 1] + (xz[nval - 1] - ebplus[nval - 2])\n\n            binsize = (np.roll(ebounds, -1) - ebounds)[:nval]\n\n            sess.set_response(ebounds, raw=True)\n\n            sess.set_abund(\n                [\n                    6,\n                    7,\n                    8,\n                    9,\n                    10,\n                    11,\n                    12,\n                    13,\n                    14,\n                    16,\n                    17,\n                    18,\n                    19,\n                    20,\n                    21,\n                    22,\n                    23,\n                    24,\n                    25,\n                    26,\n                    27,\n                    28,\n                    29,\n                    30,\n                ],\n                abund,\n            )\n\n            spec = sess.return_spectrum(kT) / binsize / 1e-14\n\n            return K * spec\n\n    # VAPEC class\n    \n    class VAPEC(Function1D, metaclass=FunctionMeta):\n        r\"\"\"\n        description :\n            The Astrophysical Plasma Emission Code (APEC, Smith et al. 2001), variable abundances for individual elements\n            contributed by Dominique Eckert\n        parameters :\n            K :\n                desc : Normalization in units of 1e-14/(4*pi*(1+z)^2*dA*2)*EM\n                initial value : 1.0\n                is_normalization : True\n                transformation : log10\n                min : 1e-30\n                max : 1e3\n                delta : 0.1\n            kT :\n                desc : Plasma temperature\n                initial value : 1.0\n                min : 0.08\n                max : 64\n                delta : 0.1\n            Fe :\n                desc : Fe abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            C :\n                desc : C abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            N :\n                desc : N abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            O :\n                desc : O abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            Ne :\n                desc : Ne abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            Mg :\n                desc : Mg abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            Al :\n                desc : Al abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            Si :\n                desc : Si abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            S :\n                desc : S abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            Ar :\n                desc : Ar abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            Ca :\n                desc : Ca abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            Ni :\n                desc : Ni abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            redshift :\n                desc : Source redshift\n                initial value : 0.1\n                min : 0.0\n                max : 10.0\n                delta : 1e-3\n                fix : yes\n\n        \"\"\"\n\n        def _set_units(self, x_unit, y_unit):\n            self.kT.unit = astropy_units.keV\n\n            self.Fe.unit = astropy_units.dimensionless_unscaled\n\n            self.C.unit = astropy_units.dimensionless_unscaled\n\n            self.N.unit = astropy_units.dimensionless_unscaled\n\n            self.O.unit = astropy_units.dimensionless_unscaled\n\n            self.Ne.unit = astropy_units.dimensionless_unscaled\n\n            self.Mg.unit = astropy_units.dimensionless_unscaled\n\n            self.Al.unit = astropy_units.dimensionless_unscaled\n\n            self.Si.unit = astropy_units.dimensionless_unscaled\n\n            self.Ar.unit = astropy_units.dimensionless_unscaled\n\n            self.Ca.unit = astropy_units.dimensionless_unscaled\n\n            self.Ni.unit = astropy_units.dimensionless_unscaled\n\n            self.redshift.unit = astropy_units.dimensionless_unscaled\n\n            self.K.unit = y_unit\n\n        def init_session(self, abund_table=\"AG89\"):\n            # initialize PyAtomDB session\n            self.session = pyatomdb.spectrum.CIESession(abundset=abund_table)\n\n        def clean(self):\n            \"\"\"\n            Clean the current APEC session to avoid having too many open files\n            :returns: \n            \"\"\"\n            \n            self.session = None\n            del self.session\n            gc.collect()\n\n        def evaluate(\n            self, x, K, kT, Fe, C, N, O, Ne, Mg, Al, Si, S, Ar, Ca, Ni, redshift\n        ):\n            assert self.session is not None, \"please run init_session(abund)\"\n\n            sess = self.session\n\n            nval = len(x)\n\n            xz = x * (1.0 + redshift)\n\n            ebplus = (np.roll(xz, -1) + xz)[: nval - 1] / 2.0\n\n            ebounds = np.empty(nval + 1)\n\n            ebounds[1:nval] = ebplus\n\n            ebounds[0] = xz[0] - (ebplus[0] - xz[0])\n\n            ebounds[nval] = xz[nval - 1] + (xz[nval - 1] - ebplus[nval - 2])\n\n            binsize = (np.roll(ebounds, -1) - ebounds)[:nval]\n\n            sess.set_response(ebounds, raw=True)\n\n            sess.set_abund(\n                [6, ], C,\n            )\n\n            sess.set_abund(\n                [7, ], N,\n            )\n\n            sess.set_abund(\n                [8, ], O,\n            )\n\n            sess.set_abund(\n                [10, ], Ne,\n            )\n\n            sess.set_abund(\n                [12, ], Mg,\n            )\n\n            sess.set_abund(\n                [13, ], Al,\n            )\n\n            sess.set_abund(\n                [14, ], Si,\n            )\n\n            sess.set_abund(\n                [16, ], S,\n            )\n\n            sess.set_abund(\n                [18, ], Ar,\n            )\n\n            sess.set_abund(\n                [20, ], Ca,\n            )\n\n            sess.set_abund(\n                [26, ], Fe,\n            )\n\n            sess.set_abund(\n                [28, ], Ni,\n            )\n\n            sess.set_abund(\n                [9, 11, 15, 17, 19, 21, 22, 23, 24, 25, 27, 29, 30], Fe\n            )  # Remaining elements are set to Fe\n\n            spec = sess.return_spectrum(kT) / binsize / 1e-14\n\n            return K * spec\n\n\n", "meta": {"hexsha": "467579f35767c68cc6733a68b57904b3495b49e8", "size": 10065, "ext": "py", "lang": "Python", "max_stars_repo_path": "astromodels/functions/functions_1D/apec.py", "max_stars_repo_name": "rwiller/astromodels", "max_stars_repo_head_hexsha": "0d222fe88f2b72fbc23675ee5309dde649d1b4b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2019-03-07T09:45:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T14:05:07.000Z", "max_issues_repo_path": "astromodels/functions/functions_1D/apec.py", "max_issues_repo_name": "rwiller/astromodels", "max_issues_repo_head_hexsha": "0d222fe88f2b72fbc23675ee5309dde649d1b4b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 83, "max_issues_repo_issues_event_min_datetime": "2019-01-27T18:57:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T12:57:26.000Z", "max_forks_repo_path": "astromodels/functions/functions_1D/apec.py", "max_forks_repo_name": "rwiller/astromodels", "max_forks_repo_head_hexsha": "0d222fe88f2b72fbc23675ee5309dde649d1b4b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 25, "max_forks_repo_forks_event_min_datetime": "2019-01-10T09:02:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T03:52:36.000Z", "avg_line_length": 26.0751295337, "max_line_length": 121, "alphanum_fraction": 0.4101341282, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 2411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.30404168757891037, "lm_q1q2_score": 0.19368392198383358}}
{"text": "# -*- coding: utf8 -*-\nimport numpy as np\nimport pickle\nimport Tree\n\n\nclass RAE(object):\n    \"\"\"Class to use Recursive Neural Network on Tree\n\n    Usage\n    -----\n\n\n    Methods\n    -------\n\n    \"\"\"\n    def __init__(self, vocab={}, dim=30, r=0.0001, reg=1):\n        self.dim = dim\n\n        #Initiate V, the tensor operator\n        self.V = np.random.uniform(-r, r, size=(dim+1, 2*dim+2, 2*dim+2))\n        self.V = (self.V+np.transpose(self.V, axes=[0, 2, 1]))/2\n\n        #Initiate W, the linear operator\n        self.W = np.random.uniform(-r, r, size=(dim+1, 2*dim+2))\n\n        #Initiate Ws, the linear operator\n        self.Ws = np.random.uniform(-r, r, size=(2, dim+1))\n\n        #Initiate VE, the encoder tensor\n        self.Ve = np.random.uniform(-r, r, size=(2*dim+2, dim+1, dim+1))\n        self.Ve = (self.Ve+np.transpose(self.Ve, axes=[0, 2, 1]))/2\n\n        #Initiate VE, the encoder tensor\n        self.We = np.random.uniform(-r, r, size=(2*dim+2, dim+1))\n\n        #Initiate L, the Lexicon representation\n        self.L = np.random.uniform(-r, r, size=(len(vocab), dim))\n\n        #Parameter holder\n        self.params = {}\n        self.params['V'] = self.V\n        self.params['W'] = self.W\n        self.params['Ws'] = self.Ws\n        self.params['L'] = self.L\n        self.params['Ve'] = self.Ve\n        self.params['We'] = self.We\n\n        #Regularisation\n        self.reg = {'V': 0.001*reg, 'W': 0.001*reg, 'Ws': 0.0001*reg, 'L': 0.0001*reg,\n                    'We': reg*0.0001, 'Ve': reg*0.0001}\n\n        self.vocab = {}\n        self.index = {}\n        for i, w in enumerate(vocab):\n            self.vocab[w] = i\n            self.index[i] = w\n\n        self.f = lambda X: np.tanh(X.T.dot(self.V).dot(X) + self.W.dot(X))\n        self.grad = lambda f: 1-f**2\n        self.dec = lambda X: np.tanh(X.T.dot(self.Ve).dot(X) + self.We.dot(X))\n\n        self.y = lambda X: np.exp(self.Ws.dot(X).clip(-500, 700)) \\\n            / sum(np.exp(self.Ws.dot(X).clip(-500, 700)))\n\n        self.norm = lambda X: np.sum(X*X)\n\n    def save(self, saveFile):\n        with open(saveFile, 'wb') as output:\n            pickle.dump(self.dim, output, -1)\n            pickle.dump(self.vocab, output, -1)\n            for k in self.params.keys():\n                pickle.dump(self.params[k], output, -1)\n            for k in self.params.keys():\n                pickle.dump(self.reg[k], output, -1)\n\n    def load(self, loadFile):\n        with open(loadFile, 'rb') as input:\n            self.dim = pickle.load(input)\n            self.vocab = pickle.load(input)\n            for k in self.params.keys():\n                self.params[k] = pickle.load(input)\n            for k in self.params.keys():\n                self.reg[k] = pickle.load(input)\n\n    def error(self, val_set):\n        '''\n        Calcule l'erreur moyenne sur le set val_set avec les parametres actuel\n        '''\n        errorVal = 0.0\n        for X_tree in val_set:\n            errorVal += self.forward_pass(X_tree)\n        return errorVal/len(val_set)\n\n    def forward_pass(self, X_tree):\n        '''\n        Effectue la passe forward et calcule l'erreur actuelle pour l'arbre X_tree\n        '''\n        errorVal = 0.0\n        for n in X_tree.leaf:\n            # Met a jour le mot avec le Lexicon courant\n            n.X = np.append(self.L[self.vocab[n.word]], 0)\n            n.ypred = self.y(n.X)  # Mise a jour du label predit\n            n.ypred += 1e-300*(n.ypred == 0)\n            assert (n.ypred != 0).all()\n            errorVal += -np.sum(n.y*np.log(n.ypred))\n\n        for p, [a, b] in X_tree.parcours:\n            aT = X_tree.nodes[a]  #\n            bT = X_tree.nodes[b]  # Recupere pour chaque triplet parent,enfant1/2 les noeuds\n            pT = X_tree.nodes[p]\n            if aT.order < bT.order:\n                X = np.append(aT.X, bT.X)\n            else:\n                X = np.append(bT.X, aT.X)\n            pT.X = self.f(X)  # Mise a jour du decripteur du parent\n            pT.X[-1] = 1\n\n            pT.ypred = self.y(pT.X)  # Mise a jour du label predit\n            pT.ypred += 1e-300*(pT.ypred == 0)\n            errorVal += -np.sum(pT.y*np.log(pT.ypred))\n        pT.c = pT.X\n        for p, [a, b] in X_tree.parcours[::-1]:\n            aT = X_tree.nodes[a]  #\n            bT = X_tree.nodes[b]  # Recupere pour chaque triplet parent,enfant1/2 les noeuds\n            pT = X_tree.nodes[p]\n            C = self.dec(pT.c)\n            #Propagation des erreurs vers le bas\n            if aT.order < bT.order:  # Si aT est le noeud de gauche\n                aT.c = C[:self.dim+1]\n                bT.c = C[self.dim+1:]\n            else:  # aT est a droite\n                bT.c = C[:self.dim+1]\n                aT.c = C[self.dim+1:]\n\n        nn = len(X_tree.nodes)\n        for n in X_tree.nodes:\n            errorVal += np.sum((n.c-n.X)**2) / nn\n        #E = sum([(self.y(n.X) - n.y) for n in X_tree.nodes])\n        #print E\n        #return self.Ws.dot(pT.X) -> Pas besoin de retourner le lbel, il faut le maj aussi?\n        return errorVal\n\n    def backward_pass(self, X_tree, w_root=1):\n        '''\n        Retourne le gradient du a l'erreur commise sur l'arbre X_tree\n        Attention: suppose la forward_pass faite\n        '''\n        #Initialise les gradients\n        grad = {}\n        for k in self.params.keys():\n            grad[k] = np.zeros(self.params[k].shape)\n\n        #Initialise les deltas\n        for n in X_tree.nodes:\n            gX = self.grad(n.X)\n            gC = self.grad(n.c)\n            n.d = self.Ws.T.dot(n.ypred-n.y)*gX*w_root - 2*(n.c-n.X)*gX\n            n.dr = 2*(n.c-n.X)*gC\n\n        n.d += self.Ws.T.dot(n.ypred-n.y)*gX*(1-w_root)\n\n        err_rec = 0\n\n        for p, [a, b] in X_tree.parcours:\n            aT = X_tree.nodes[a]  #\n            bT = X_tree.nodes[b]  # Recupere pour chaque triplet parent,enfant1/2 les noeuds\n            pT = X_tree.nodes[p]\n            if aT.order < bT.order:\n                dR = np.append(aT.dr, bT.dr)\n            else:\n                dR = np.append(bT.dr, aT.dr)\n            pT.dr += dR.dot(self.We) + 2*dR.dot(self.Ve.dot(pT.X))\n            grad['We'] += np.outer(dR, pT.X)\n            grad['Ve'] += np.tensordot(dR, np.outer(pT.X, pT.X), axes=0)\n\n        #Descend dans l arbre\n        for p, [a, b] in X_tree.parcours[::-1]:\n            aT = X_tree.nodes[a]  #\n            bT = X_tree.nodes[b]  # Recupere pour chaque triplet parent,enfant1/2 les noeuds\n            pT = X_tree.nodes[p]\n            #Propagation des erreurs vers le bas\n            if aT.order < bT.order:  # Si aT est le noeud de gauche\n                X = np.append(aT.X, bT.X)\n                ddown = (self.W.T.dot(pT.d+pT.dr)+2*(pT.d+pT.dr).dot(self.V.dot(X)))\n                aT.d += ddown[:self.dim+1]\n                bT.d += ddown[self.dim+1:]\n            else:  # aT est a droite\n                X = np.append(bT.X, aT.X)\n                ddown = (self.W.T.dot(pT.d+pT.dr)+2*(pT.d+pT.dr).dot(self.V.dot(X)))\n                aT.d += ddown[self.dim+1:]\n                bT.d += ddown[:self.dim+1]\n            err_rec += np.sum((aT.c-aT.X)**2)\n            err_rec += np.sum((bT.c-bT.X)**2)\n            #Contribution aux gradients du pT\n            grad['Ws'] += np.outer(pT.ypred-pT.y, pT.X)\n            grad['V'] += np.tensordot(pT.d + pT.dr, np.outer(X, X), axes=0)\n            grad['W'] += np.outer(pT.d + pT.dr, X)\n\n        #Contribution des feuilles\n        for n in X_tree.leaf:\n            grad['L'][self.vocab[n.word]] += n.d[:-1] + n.dr[:-1]\n            grad['Ws'] += np.outer(n.ypred-n.y, n.X)\n\n        return grad\n\n    def train(self, X_trees, learning_rate=0.01, mini_batch_size=27,\n              warm_start=True, r=0.0001, max_iter=1000, val_set=[],\n              n_check=100, strat='AdaGrad', w_root=1,\n              bin=False, reset_freq=-1, save_tmp='tmp.pkl', n_stop=4):\n        '''\n        Training avec AdaGrad (Dutchi et al.), prends en entrée une liste d'arbres X_trees\n        '''\n        #Remise à zero du modele\n        if not warm_start:\n            dim = self.dim\n            #Initiate V, the tensor operator\n            self.params['V'] = np.random.uniform(-r, r, size=(dim+1, 2*dim+2, 2*dim+2))\n            self.params['V'] = (self.V+np.transpose(self.V, axes=[0, 2, 1]))/2\n\n            #Initiate W, the linear operator\n            self.params['W'] = np.random.uniform(-r, r, size=(dim+1, 2*dim+2))\n\n            #Initiate Ws, the linear operator\n            self.params['Ws'] = np.random.uniform(-r, r, size=(2, dim+1))\n\n            #Initiate VE, the encoder tensor\n            self.Ve = np.random.uniform(-r, r, size=(2*dim+2, dim+1, dim+1))\n            self.Ve = (self.Ve+np.transpose(self.Ve, axes=[0, 2, 1]))/2\n\n            #Initiate VE, the encoder tensor\n            self.We = np.random.uniform(-r, r, size=(2*dim+2, dim+1))\n\n            #Initiate L, the Lexicon representation\n            self.params['L'] = np.random.uniform(-r, r, size=(len(self.vocab), dim))\n\n        #Liste pour erreurs\n        self.errMB = []\n        self.errVal = []\n        errMB = self.errMB\n        errVal = self.errVal\n\n        #Condition d'arret\n        n_iter = 1\n        gradNorm = 1.0\n        if val_set != []:\n            prevError = self.error(val_set) / len(val_set)\n            for k in self.params.keys():\n                prevError += self.reg[k]*self.norm(self.params[k])/2.0\n            iniError = prevError\n            minError = prevError  # optimal error so far\n            glError = 0\n            upStop = 0\n            errVal.append(prevError)\n\n        # Normalisation pour AdaGrad/Rms-prop\n        eta = learning_rate\n        dHist = {}\n        dMask = {}\n        dPrev = {}\n        for k in self.params.keys():\n            sh = self.params[k].shape\n            dHist[k] = np.zeros(sh)\n            dMask[k] = np.ones(sh)\n            dPrev[k] = np.zeros(sh)\n\n        early_stop = False\n        while (not early_stop) and n_iter < max_iter:  # Critere moins random\n            if n_iter % reset_freq == 0 and reset_freq > 0:  # Remise a zero des rates cf Socher\n                for k in self.params.keys():\n                    dHist[k] = np.zeros(self.params[k].shape)\n\n            #Choose mini batch randomly\n            mini_batch_samples = np.random.choice(X_trees, size=mini_batch_size)\n\n            #Initialize gradients to 0\n            dCurrent = {}\n            for k in self.params.keys():\n                    dCurrent[k] = np.zeros(self.params[k].shape)\n\n            #Mini batch pour gradient\n            currentMbe = 0.0\n            for X_tree in mini_batch_samples:\n                currentMbe += self.forward_pass(X_tree)\n                grad = self.backward_pass(X_tree, w_root=w_root)\n                for k in self.params.keys():\n                    dCurrent[k] += grad[k]\n\n            currentMbe /= mini_batch_size\n            for k in self.params.keys():\n                currentMbe += self.reg[k]*self.norm(self.params[k])/2.0\n\n            #Division par le nombre de sample + regularisation\n            for k in self.params.keys():\n                dCurrent[k] = dCurrent[k]/mini_batch_size + self.reg[k]*self.params[k]\n\n            #Mise a jour des poids et calcul des pas\n            if strat == 'AdaGrad':\n                eps = 0.001  # Adagrad >0 ? cf Socher\n                for k in self.params.keys():\n                    dHist[k] += dCurrent[k]*dCurrent[k]\n                    dCurrent[k] = eta*dCurrent[k]/np.sqrt(dHist[k]+eps)\n            else:\n                eps = 0.001\n                for k in self.params.keys():\n                    dHist[k] = 0.9*dHist[k] + 0.1*dCurrent[k]*dCurrent[k]\n                    dMask[k] *= .7*(dPrev[k]*dCurrent[k] >= 0) + .5\n                    dCurrent[k] = eta*dMask[k].clip(1e-6, 50, out=dMask[k]) *\\\n                        dCurrent[k]/np.sqrt(dHist[k]+eps)\n\n            #Calcul de la norme du gradient (critere d'arret)\n            gradNorm = 0\n            for k in self.params.keys():\n                gradNorm += np.sum(np.abs(dCurrent[k]))\n\n            #Keep previous gradient\n            for k in self.params.keys():\n                dPrev[k] = dCurrent[k]\n\n            #Descente\n            for k in self.params.keys():\n                self.params[k] -= dCurrent[k]\n\n            #Maj de la condition d'arret\n            if val_set != [] and (n_iter % n_check) == 0:\n                currentError = self.error(val_set)\n                for k in self.params.keys():\n                    currentError += self.reg[k]*self.norm(self.params[k])/2.0\n\n                errVal.append(currentError)\n                errMB.append(currentMbe)\n                print('Error on validation set at iter {0} : {1} '\n                      '(previous : {2})'.format(n_iter, currentError, prevError))\n                print('Error on mini batch at iter {0} : {1} '\n                      '(Gradient norm : {2})'.format(n_iter, currentMbe, gradNorm))\n\n                with open(save_tmp, 'wb') as output:\n                    pickle.dump(errVal, output, -1)\n                    pickle.dump(errMB, output, -1)\n\n                #Early stopping\n                minError = min(minError, currentError)\n                glError = 100*((currentError/minError)-1.0)\n                if currentError > prevError:\n                    upStop += 1\n                else:\n                    upStop = 0\n                early_stop = (upStop >= n_stop) and (n_stop > 0)  # UP criterion\n                prevError = currentError\n            else:\n                print('Error on mini batch at iter {0} : {1} '\n                      '(Gradient norm : {2})'.format(n_iter, currentMbe, gradNorm))\n                errMB.append(currentMbe)\n\n            #Maj iter\n            n_iter += 1\n\n        if val_set != []:\n            print('Error on training set before and after training'\n                  '({2} iter) : {0}->{1}\\n'.format(iniError, currentError, n_iter))\n            print('Generalization error : {0}'.format(glError))\n        return errMB, errVal\n\n    def score_fine(self, X_trees):\n        '''\n        Score sur les predictions MAP avec 5 label\n        '''\n        countAll = 0\n        countRoot = 0\n        scAll = 0.0\n        scRoot = 0.0\n        for X_tree in X_trees:\n            self.forward_pass(X_tree)\n            for n in X_tree.nodes:\n                countAll += 1\n                scAll += (Tree.Tree.getSoftLabel(n.ypred[1]) == Tree.Tree.getSoftLabel(n.y[1]))\n            countRoot += 1\n            n = X_tree.nodes[-1]\n            scRoot += (Tree.Tree.getSoftLabel(n.ypred[1]) == Tree.Tree.getSoftLabel(n.y[1]))\n        return scAll/countAll, scRoot/countRoot\n\n    def score_eps(self, X_trees, eps):\n        '''\n        Score sur les predictions MAP avec 5 label\n        '''\n        countAll = 0\n        countRoot = 0\n        scAll = 0.0\n        scRoot = 0.0\n        for X_tree in X_trees:\n            self.forward_pass(X_tree)\n            for n in X_tree.nodes:\n                countAll += 1\n                scAll += (abs(n.ypred[1] - n.y[1]) <= eps)\n            countRoot += 1\n            n = X_tree.nodes[-1]\n            scRoot += (abs(n.ypred[1] - n.y[1]) <= eps)\n        return scAll/countAll, scRoot/countRoot\n\n    def score_binary(self, X_trees, inc_neut=False):\n        '''\n        Score sur les prediction MAP pos/neg\n        '''\n        countAll = 0\n        countRoot = 0\n        scAll = 0.0\n        scRoot = 0.0\n        for X_tree in X_trees:\n            self.forward_pass(X_tree)\n            for n in X_tree.nodes:\n                countAll += 1 * (inc_neut or not (0.4 < n.y[1] <= 0.6))\n                scAll += ((n.ypred[1] <= 0.5 and n.y[1] <= 0.5) or\n                          (n.ypred[1] > 0.5 and n.y[1] > 0.5)) *\\\n                         (inc_neut or not (0.4 < n.y[1] <= 0.6))\n            n = X_tree.nodes[-1]\n            countRoot += 1 * (inc_neut or not (0.4 < n.y[1] <= 0.6))\n            scRoot += ((n.ypred[1] <= 0.5 and n.y[1] <= 0.5) or\n                      (n.ypred[1] > 0.5 and n.y[1] > 0.5)) *\\\n                      (inc_neut or not (0.4 < n.y[1] <= 0.6))\n        return scAll/countAll, scRoot/countRoot\n\n    def check_derivative(self, X_tree, eps=1e-6):\n        '''\n        Fait une compaaison dérivee / differences finies\n        '''\n        error1 = self.forward_pass(X_tree)\n        dWs, dV, dW, dL = self.backward_pass(X_tree)\n        dirW = np.random.uniform(size=self.W.shape)\n        dirWs = np.random.uniform(size=self.Ws.shape)\n        dirL = np.random.uniform(size=self.L.shape)\n        dirV = np.random.uniform(size=self.V.shape)\n\n        self.Ws += eps*dirWs\n        self.W += eps*dirW\n        self.L += eps*dirL\n        self.V += eps*dirV\n\n        error2 = self.forward_pass(X_tree)\n        diff = (error2-error1)/eps\n        diff2 = np.sum(dW*dirW)+np.sum(dWs*dirWs)+np.sum(dL*dirL)+np.sum(dV*dirV)\n\n        return np.abs(diff-diff2)\n\n    def confusion_matrix(self, X_trees):\n        confAll = np.zeros((5, 5))\n        confRoot = np.zeros((5, 5))\n        for tree in X_trees:\n            for n in tree.nodes:\n                lp = Tree.Tree.getSoftLabel(n.ypred[1])\n                l = Tree.Tree.getSoftLabel(n.y[1])\n                confAll[l, lp] += 1\n            lp = Tree.Tree.getSoftLabel(tree.nodes[-1].ypred[1])\n            l = Tree.Tree.getSoftLabel(tree.nodes[-1].y[1])\n            confRoot[l, lp] += 1\n        for lp in range(5):\n            confAll[lp, :] /= np.sum(confAll[lp, :])\n            confRoot[lp, :] /= np.sum(confRoot[lp, :])\n        return confAll, confRoot\n\n    def plot_words_2D(self, labels, N=-1):\n        from sklearn.decomposition import PCA\n        import matplotlib.pyplot as plt\n        import matplotlib.cm as cm\n\n        if N == -1:\n            N = self.L.shape[0]\n\n        pca = PCA(n_components=2)\n        X = pca.fit_transform(self.L[:N])\n        revert_vocab = {i: (w, labels[w]) for (w, i) in self.vocab.iteritems()}\n        y = np.zeros(N)\n        for i in range(N):\n            _, y[i] = revert_vocab[i]\n        plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cm.jet)\n\n    def sample_w(self, p):\n        dist = ((self.L-p)**2).sum(axis=1)\n        i0 = dist.argmin()\n        return self.index[i0]\n\n    def sample(self, p):\n        queue = [p]\n        while len(queue) != 0:\n            curr = queue.pop()\n            self.dec(curr)\n            C = self.dec(curr)\n            ac = C[:self.dim+1:]\n            bc = C[self.dim+1:]\n            if ac[-1] > 0.:\n                queue.append(ac)\n            else:\n                print(self.sample_w(ac[:-1]))\n            if bc[-1] > 0.:\n                queue.append(bc)\n            else:\n                print(self.sample_w(bc[:-1]))\n\n    def plot_eps_curve(self, X, n_pts):\n        import matplotlib.pyplot as plt\n\n        eps = np.logspace(-3, 0, n_pts)\n        curve_r = []\n        curve_a = []\n        for e in eps:\n            a, r = self.score_eps(X, e)\n            curve_r.append(r)\n            curve_a.append(a)\n\n        plt.semilogx(eps, curve_a)\n        plt.semilogx(eps, curve_r)\n        plt.show()\n\n        return curve_a, curve_r\n", "meta": {"hexsha": "7a9bfd360c67df12a9786cdc166f952fd7ae75b6", "size": 18919, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/code/RAE.py", "max_stars_repo_name": "jalayrupera/Sentiment-analysis-on-amazon-product", "max_stars_repo_head_hexsha": "f04d77769f9c9b533d530ce5b217d741c09c93ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/code/RAE.py", "max_issues_repo_name": "jalayrupera/Sentiment-analysis-on-amazon-product", "max_issues_repo_head_hexsha": "f04d77769f9c9b533d530ce5b217d741c09c93ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/code/RAE.py", "max_forks_repo_name": "jalayrupera/Sentiment-analysis-on-amazon-product", "max_forks_repo_head_hexsha": "f04d77769f9c9b533d530ce5b217d741c09c93ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7359223301, "max_line_length": 96, "alphanum_fraction": 0.5020878482, "include": true, "reason": "import numpy", "num_tokens": 5338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.30404168757891037, "lm_q1q2_score": 0.1936839177935497}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\n\nfrom . import preliminary_computations as precomp\nfrom .local_conditions import sky_countrate\nfrom . import optics as opt\nfrom . import photometry as phot\nfrom . import utils\n\n\ndef etc_computation(info_dict):\n    \"\"\"\n    Compute either the SNR, the total exposure time or\n    the magnitude in function of the 2 others\n\n    Parameters\n    ----------\n    info_dict: dictionary\n        contains all relevant information\n\n    wavelength : array\n        wavelengths in angstrom\n\n    Returns\n    ---------\n    SNR: float\n        Signal to noise ratio\n\n    mag: float\n        magnitude reached\n\n    tot_exp_time: float\n        total exposure time in seconds\n\n    \"\"\"\n    # display result\n    verbose = info_dict[\"verbose\"]\n\n    etc_type = info_dict[\"etc_type\"]\n    SNR = info_dict[\"SNR\"]\n    tot_exp_time = info_dict[\"Nexp\"] * info_dict[\"exptime\"]\n    info_dict[\"total_exposure_time\"] = tot_exp_time\n    Nexp = info_dict[\"Nexp\"]\n    # Detector Integration Time in seconds\n    if etc_type == \"snr\" or etc_type == \"mag\":\n        DIT = info_dict[\"exptime\"] - info_dict[\"T_dithering\"]\n\n    # Display\n    if verbose:\n        print(\"\\nInformation about Passband:\")\n        print(\"----------------------------\")\n        print(\"Cut_on: %.f angstroms\" % info_dict[\"Passband_cuton\"])\n        print(\"Effective wavelength: %.f angstroms\" %\n              info_dict[\"effWavelength\"])\n        print(\"Cut_off: %.f angstroms\" % info_dict[\"Passband_cutoff\"])\n\n        print(\"\\nAirmass: %.2f\" % info_dict[\"airmass\"])\n        print(\"\\nSeeing: %.2f\" % info_dict[\"seeing_los_arcsec\"])\n\n    if info_dict[\"detailed_trans\"] == 1:\n        # Computes mean transmission of each components for the given passband\n        mean_trans_tel = utils.mean_efficiency_passband(\n            info_dict, opt.telescope_efficiency(info_dict)\n        )\n        mean_trans_inst = utils.mean_efficiency_passband(\n            info_dict,\n            opt.instrument_channel_efficiency(info_dict)\n            * info_dict[\"Trans_filter\"]\n            * info_dict[\"camera_efficiency\"],\n        )\n        mean_trans_filter = utils.mean_efficiency_passband(\n            info_dict, info_dict[\"Trans_filter\"]\n        )\n        mean_eta_cam = utils.mean_efficiency_passband(\n            info_dict, info_dict[\"camera_efficiency\"]\n        )\n        mean_trans_optics = mean_trans_tel * mean_trans_inst\n        mean_trans_atm = utils.mean_efficiency_passband(\n            info_dict, info_dict[\"Trans_atmosphere\"]\n        )\n        mean_trans_system = mean_trans_optics\n        info_dict[\"trans_mean_tel\"] = mean_trans_tel\n        info_dict[\"trans_mean_inst\"] = mean_trans_inst\n        info_dict[\"trans_mean_optics\"] = mean_trans_optics\n        info_dict[\"trans_mean_filter\"] = mean_trans_filter\n        info_dict[\"trans_mean_atm\"] = mean_trans_atm\n        info_dict[\"trans_mean_cam\"] = mean_eta_cam\n        info_dict[\"trans_mean_system\"] = mean_trans_system\n\n        if verbose:\n            print(\"\\nMEAN EFFICENCIES:\")\n            print(\"------------------\")\n            print(\"Obscuration: %.3f\" % (1.0 - info_dict[\"obstruction\"]))\n            print(\n                \"Telescope: %.3f (+obs: %.3f)\"\n                % (mean_trans_tel,\n                   mean_trans_tel * (1.0 - info_dict[\"obstruction\"]))\n            )\n            print(\"Instrument: %.3f\" % mean_trans_inst)\n            print(\n                \"Optics (tel+inst): %.3f  (+obs: %.3f)\"\n                % (\n                    mean_trans_optics,\n                    mean_trans_optics * (1.0 - info_dict[\"obstruction\"]),\n                )\n            )\n            print(\"Filter: %.3f\" % mean_trans_filter)\n            print(\"Atmosphere: %.3f\" % mean_trans_atm)\n            print(\"Camera: %.3f\" % mean_eta_cam)\n            print(\n                \"System: %.3f (+obs: %.3f)\\n\"\n                % (\n                    mean_trans_system,\n                    mean_trans_system * (1 - info_dict[\"obstruction\"]),\n                )\n            )\n\n    elif info_dict[\"detailed_trans\"] == 0:\n        mean_eta_cam = utils.mean_efficiency_passband(\n            info_dict, info_dict[\"camera_efficiency\"]\n        )\n        mean_eta_optics = utils.mean_efficiency_passband(\n            info_dict, phot.set_filter(info_dict)\n        )\n        mean_trans_system = mean_eta_cam * mean_eta_optics\n        info_dict[\"trans_mean_system\"] = mean_trans_system\n        if verbose:\n            print(\"\\nMEAN EFFICENCIES:\")\n            print(\"------------------\")\n            print(\"Obscuration: %.3f\" % (1.0 - info_dict[\"obstruction\"]))\n            print(\n                \"System: %.2f (+obs: %.3f)\\n\"\n                % (\n                    mean_trans_system,\n                    mean_trans_system * (1 - info_dict[\"obstruction\"]),\n                )\n            )\n\n    # Number of pixels covering 1.35*FWHM of the PSF\n    npix = info_dict[\"npix\"]\n    # Factor when estimating the Noise from other images\n    factor_ima = precomp.factor_images_averaged(info_dict)\n    # Fraction of light in the brightest pixel\n    f_pix = precomp.Normalisation_factor(info_dict, True)\n    # Fraction of light in the PSF\n    f_PSF = precomp.Normalisation_factor(info_dict, False)\n\n    info_dict[\"factor_ima\"] = factor_ima\n    info_dict[\"f_pix\"] = f_pix\n    info_dict[\"f_PSF\"] = f_PSF\n\n    # Background Noise countrate in e-/s/px\n    # ---------------------------------------\n    info_dict = sky_countrate(info_dict)  # e-/s/px\n    BN = info_dict[\"Sky_CountRate\"]\n    # print ('Sky countrate: %.2f (e-/px/s)' % BN)\n    # Thermic signal (electrons/s/pixel)  <--> Dark current\n    # ------------------------------------------------------\n    DC = info_dict[\"cameras\"][info_dict[\"channel\"]][\"DC\"]\n    # Digitization noise   (e-/pixel)\n    # ----------------------------------\n    # Converter analog to digital noise of 1/2 ADU (electrons/pixel)\n    DigN = info_dict[\"dig_noise\"]\n\n    # Readout noise (e-/pixel)\n    # --------------------------\n    RN = info_dict[\"cameras\"][info_dict[\"channel\"]][\"RN\"]\n\n    # Instrument background (e-/s/pix)\n    inst_bg = info_dict[\"Instrument_bg\"]\n\n    # Object\n    # ---------\n    # Count rate of the object in e-/s\n    if etc_type == \"snr\" or etc_type == \"time\":\n        CR, fph = info_dict[\"Object_fes\"], info_dict[\"Object_fph\"]  # e-/s\n\n    # Zeropoint\n    # -----------\n    ZP = info_dict[\"zeropoint\"]\n\n    # Add some info in info_cit\n    if verbose:\n        print(\"Zeropoint: %.2f (%s mag)\" % (ZP,\n                                            info_dict[\"photometry_system\"]))\n\n    # Compute the SNR\n    # ------------------\n    if etc_type == \"snr\":\n        # In the case of a given magnitude to reach, the fraction of flux\n        # we kept should be included so that the given mag corresponds to the\n        # measured count rate.\n        if info_dict[\"object_type\"] == \"magnitude\":\n            CR = CR  # / f_PSF\n            CR_pix = CR  # / f_pix\n        else:\n            CR_pix = CR\n\n        # Peak SNR (Object signal/noise at the brightest pixel)\n        SNR_pix = (\n            np.sqrt(Nexp)\n            * CR_pix\n            * f_pix\n            * DIT\n            / np.sqrt(\n                CR_pix * f_pix * DIT\n                + factor_ima * ((RN ** 2.0 + DigN ** 2.0)\n                                + DIT * (DC + BN + inst_bg))\n            )\n        )\n\n        # Total integrated noise over npix (electrons/area)\n        SNR = (\n            np.sqrt(Nexp)\n            * CR\n            * f_PSF\n            * DIT\n            / np.sqrt(\n                CR * f_PSF * DIT\n                + factor_ima\n                * npix\n                * ((RN ** 2.0 + DigN ** 2.0) + DIT * (DC + BN + inst_bg))\n            )\n        )\n\n        if info_dict[\"object_type\"] == \"magnitude\":\n            # mag = ZP - 2.5*np.log10(CR*f_PSF)\n            mag = info_dict[\"object_magnitude\"]\n            mag_pix = ZP - 2.5 * np.log10(CR_pix * f_pix)\n            mag_pix = info_dict[\"object_magnitude\"]\n        else:\n            mag = ZP - 2.5 * np.log10(CR)\n            mag_pix = ZP - 2.5 * np.log10(CR_pix)\n\n        Ftot_el = CR * f_PSF * DIT  # *np.sqrt(Nexp)\n        Ftot_el_pix = CR_pix * f_pix * DIT  # *np.sqrt(Nexp)\n        DIT_pix = DIT\n\n        info_dict[\"SNR\"] = SNR\n        info_dict[\"SNR_pix\"] = SNR_pix\n        info_dict[\"mag_pix\"] = mag_pix\n        info_dict[\"Ftot_el_pix\"] = Ftot_el_pix\n        info_dict[\"Ftot_el\"] = Ftot_el\n        info_dict[\"DIT_pix\"] = DIT_pix\n\n        if verbose:\n            print(\n                \"\\n\\nA magnitude (%s system) of %.2f in %s band within a total exposure time of %.2f seconds splited in %d exposure(s), implies a total SNR of :\\n\"\n                % (\n                    info_dict[\"photometry_system\"],\n                    mag,\n                    info_dict[\"filter_band\"],\n                    DIT * Nexp,\n                    Nexp,\n                )\n            )\n            # print ('\\t - Peak SNR at the brightest pixel: %.2f \\n' % SNR_pix)\n            print(\"\\t - Integrated SNR over %d pixels: %.2f\" % (npix, SNR))\n            print(\n                \"\\n\\nA magnitude (%s system) of %.2f in %s band within a total exposure time of %.2f seconds splited in %d exposure(s), implies a SNR for the central pixel of of :\\n\\n\"\n                % (\n                    info_dict[\"photometry_system\"],\n                    mag_pix,\n                    info_dict[\"filter_band\"],\n                    DIT_pix * Nexp,\n                    Nexp,\n                )\n            )\n            print(\"\\t - SNR of the central pixel: %.2f \\n\\n\" % SNR_pix)\n\n    # Compute the total exposure time\n    # --------------------------------\n    elif etc_type == \"time\":\n\n        # In the case of a given magnitude to reach, the fraction of flux\n        # we kept should be included so that the given mag corresponds to the\n        # measured count rate.\n        if info_dict[\"object_type\"] == \"magnitude\":\n            CR = CR  # / f_PSF\n\n        # Integrated over Npixels     (solve 2nd degree equation)\n        if Nexp > 1:\n            SNR_1 = SNR / np.sqrt(Nexp)\n        else:\n            SNR_1 = SNR\n        A_sys = -((CR * f_PSF) ** 2.0)\n        B_sys = SNR_1 ** 2.0 * (CR * f_PSF + factor_ima * npix\n                                * (DC + BN + inst_bg))\n        C_sys = SNR_1 ** 2.0 * factor_ima * npix * (RN ** 2.0 + DigN ** 2.0)\n\n        delta = B_sys * B_sys - 4.0 * A_sys * C_sys\n\n        DIT = (-B_sys - np.sqrt(delta)) / (2.0 * A_sys)\n        # mag = -2.5*np.log10(obj_janskys/3631)\n\n        if info_dict[\"object_type\"] == \"magnitude\":\n            mag = ZP - 2.5 * np.log10(CR)  # *f_PSF)\n        else:\n            mag = ZP - 2.5 * np.log10(CR)\n\n        Ftot_el = CR * f_PSF * DIT  # *np.sqrt(Nexp)\n\n        # Brightest pixel\n        if info_dict[\"object_type\"] == \"magnitude\":\n            CR_pix = CR  # / f_pix\n        else:\n            CR_pix = CR\n\n        A_sys = -((CR_pix * f_pix) ** 2.0)\n        B_sys = SNR_1 ** 2.0 * (CR_pix * f_pix + factor_ima\n                                * (DC + BN + inst_bg))\n        C_sys = SNR_1 ** 2.0 * factor_ima * (RN ** 2.0 + DigN ** 2.0)\n\n        delta = B_sys * B_sys - 4.0 * A_sys * C_sys\n\n        DIT_pix = (-B_sys - np.sqrt(delta)) / (2.0 * A_sys)\n\n        if info_dict[\"object_type\"] == \"magnitude\":\n            mag_pix = ZP - 2.5 * np.log10(CR_pix)  # *f_pix)\n        else:\n            mag_pix = ZP - 2.5 * np.log10(CR)\n\n        Ftot_el_pix = CR_pix * f_pix * DIT_pix  # *np.sqrt(Nexp)\n\n        info_dict[\"DIT\"] = DIT\n        info_dict[\"DIT_pix\"] = DIT_pix\n        info_dict[\"Ftot_el_pix\"] = Ftot_el_pix\n        info_dict[\"Ftot_el\"] = Ftot_el\n        info_dict[\"mag_pix\"] = mag_pix\n\n        if verbose:\n            print(\n                \"\\n\\nReaching a magnitude (%s system) of %.2f in %s band with a SNR of %.2f requires:\\n\"\n                % (info_dict[\"photometry_system\"], mag, info_dict[\"filter_band\"], SNR)\n            )\n            print(\"\\t - a Total exposure time of: %.2f s\\n\" % (DIT * Nexp))\n            print(\n                \"\\n\\nReaching a magnitude (%s system) of %.2f in %s band with a SNR of %.2f for the central pixel requires:\\n\\n\"\n                % (\n                    info_dict[\"photometry_system\"],\n                    mag_pix,\n                    info_dict[\"filter_band\"],\n                    SNR,\n                )\n            )\n            print(\"\\t - a Total exposure time of: %.2f s\\n\\n\" % (DIT_pix * Nexp))\n\n    # Compute the magnitude\n    # ------------------------\n    elif etc_type == \"mag\":\n        # f_PSF=1\n        # f_pix=1\n        # Integrated over Npixels    (solve 2nd degree equation)\n        A_sys = -((f_PSF * DIT * np.sqrt(Nexp)) ** 2.0)\n        B_sys = SNR ** 2.0 * f_PSF * DIT\n        C_sys = SNR ** 2.0 * (\n            factor_ima * npix * (RN ** 2.0 + DigN ** 2.0 + DIT\n                                 * (DC + BN + inst_bg))\n        )\n\n        delta = B_sys * B_sys - 4.0 * A_sys * C_sys\n\n        CR = (-B_sys - np.sqrt(delta)) / (2.0 * A_sys)\n        Ftot_el = CR * f_PSF * DIT  # *np.sqrt(Nexp)\n\n        mag = ZP - 2.5 * np.log10(CR)\n\n        # Central pixel\n        A_sys = -((f_pix * DIT * np.sqrt(Nexp)) ** 2.0)\n        B_sys = SNR ** 2.0 * f_pix * DIT\n        C_sys = SNR ** 2.0 * (\n            factor_ima * (RN ** 2.0 + DigN ** 2.0 + DIT * (DC + BN + inst_bg))\n        )\n\n        delta = B_sys * B_sys - 4.0 * A_sys * C_sys\n\n        CR_pix = (-B_sys - np.sqrt(delta)) / (2.0 * A_sys)\n        Ftot_el_pix = CR_pix * f_pix * DIT  # *np.sqrt(Nexp)\n        mag_pix = ZP - 2.5 * np.log10(CR_pix)\n        DIT_pix = DIT\n\n        object_mag = mag * np.ones(len(info_dict[\"wavelength_ang\"]))\n        fJy = phot.mag2Jy(info_dict, object_mag)  # Jy\n        # erg/s/cm2/A\n        flam = utils.fJy_to_flambda(info_dict[\"wavelength_ang\"], fJy)\n        # ph/s/cm2/A\n        fph = utils.flambda_to_fph(info_dict[\"wavelength_ang\"], flam)\n\n        info_dict[\"Object_mag\"] = object_mag\n        info_dict[\"object_magnitude\"] = mag\n        info_dict[\"mag_pix\"] = mag_pix\n        info_dict[\"DIT_pix\"] = DIT\n        info_dict[\"Ftot_el_pix\"] = Ftot_el_pix\n        info_dict[\"Ftot_el\"] = Ftot_el\n\n        if verbose:\n            print(\n                \"\\n\\nFor a total SNR=%.2f in a total exposure time of %.2f (sec) in %d exposure(s) we reach:\\n\"\n                % (SNR, DIT * Nexp, Nexp)\n            )\n            print(\n                \"\\t - a magnitude (%s system) of: %.2f in %s band\\n\"\n                % (info_dict[\"photometry_system\"],\n                   mag,\n                   info_dict[\"filter_band\"])\n            )\n            print(\n                \"\\n\\nFor the central pixel a SNR=%.2f in a total exposure time of %.2f (sec) in %d exposure(s) we reach:\\n\\n\"\n                % (SNR, DIT_pix * Nexp, Nexp)\n            )\n            print(\n                \"\\t - a magnitude (%s system) of: %.2f in %s band\\n\\n\"\n                % (info_dict[\"photometry_system\"], mag_pix, info_dict[\"filter_band\"])\n            )\n\n    info_dict[\"DIT\"] = DIT\n\n    # sigma_shot_noise = np.sqrt(Ftot_el * DIT)\n    # sigma_dark_current = np.sqrt(DC * npix * DIT)\n    # sigma_sky = np.sqrt(BN * npix * DIT)\n    # sigma_digitization = np.sqrt(npix * DigN ** 2.0)\n    # sigma_readout_noise = np.sqrt(npix * RN ** 2.0)\n\n    # Total number of electrons in the brightest pixel for 1 exposure\n    N_el_tot_pix1 = Ftot_el_pix + (BN + DC + inst_bg) * DIT_pix + RN + DigN\n    N_el_tot_pix2 = (Ftot_el * f_pix / f_PSF\n                     + (BN + DC + inst_bg) * DIT + RN + DigN)\n\n    info_dict[\"N_el_tot_pix1\"] = N_el_tot_pix1\n    info_dict[\"N_el_tot_pix2\"] = N_el_tot_pix2\n\n    if N_el_tot_pix1 > info_dict[\"cameras\"][info_dict[\"channel\"]][\"FWC\"]:\n        info_dict[\"saturation\"] = \"Yes\"\n    else:\n        info_dict[\"saturation\"] = \"No\"\n\n    if verbose:\n\n        print(\n            \"\\nFull well capacity of 1 pixel: %.2f (electrons)\"\n            % (info_dict[\"cameras\"][info_dict[\"channel\"]][\"FWC\"])\n        )\n        print(\"\\n\\n--------- One pixel only------------------\")\n        print(\n            \"\\nPhoto-electrons created: central pix for %d exposure(s) of %.2f sec \"\n            % (Nexp, DIT_pix)\n        )\n        print(\"\\tby:\")\n        print(\"\\t- Object:         %10.2f   (electrons)\" % Ftot_el_pix)\n        print(\"\\t- Sky:            %10.2f   (electrons)\" % (BN * DIT_pix))\n        print(\"\\t- Readout:        %10.2f   (electrons)\" % RN)\n        print(\"\\t- Dark current:   %10.2f   (electrons)\" % (DC * DIT_pix))\n        print(\"\\t- Digitization:   %10.2f   (electrons)\" % DigN)\n        print(\"\\t- Instrument bg:  %10.2f   (electrons)\" % (inst_bg * DIT_pix))\n\n        print(\n            \"\\nSNR: -central pixel: %.2f\"\n            % (\n                np.sqrt(Nexp)\n                * Ftot_el_pix\n                / np.sqrt(\n                    Ftot_el_pix\n                    + factor_ima\n                    * ((RN ** 2.0 + DigN ** 2.0) + DIT_pix\n                       * (DC + BN + inst_bg))\n                )\n            )\n        )\n\n        print(\n            \"\\nTotal of electrons collected in the central pixel during an exposure time of %d seconds: %.2f \"\n            % (DIT_pix, N_el_tot_pix1)\n        )\n        if N_el_tot_pix1 > info_dict[\"cameras\"][info_dict[\"channel\"]][\"FWC\"]:\n            print(\n                \"--> Central pixel saturated: number of electrons > Full well Capacity\"\n            )\n        elif N_el_tot_pix1 > info_dict[\"cameras\"][info_dict[\"channel\"]][\"gain\"] * (\n            2.0 ** (info_dict[\"cameras\"][info_dict[\"channel\"]][\"bits\"]) - 1\n        ):\n            print(\n                \"--> Central pixel saturated: number of electrons > number of digitizations\"\n            )\n        elif (\n            N_el_tot_pix1 > 1.0 / 2 * info_dict[\"cameras\"][info_dict[\"channel\"]][\"FWC\"]\n        ):\n            print(\n                \"--> Number of electrons in central pixel > 1/2 of Full well Capacity. Risk of non-linear response.\"\n            )\n\n        else:\n            print(\"--> No saturation\")\n\n        print(\"\\n\\n\\n--------- Integrated over %d pixels------------------\" % npix)\n        print(\n            \"\\nPhoto-electrons created: brightest pix |  total of %d pixels, %d exposure(s) of %.2f sec \"\n            % (npix, Nexp, DIT)\n        )\n        print(\"\\tby:\")\n        print(\n            \"\\t- Object:         %10.2f   |   %10.2f   (electrons)\"\n            % (Ftot_el * f_pix / f_PSF, Ftot_el)\n        )\n        print(\n            \"\\t- Sky:            %10.2f   |   %10.2f   (electrons)\"\n            % (BN * DIT, (BN * npix * DIT * Nexp))\n        )\n        print(\n            \"\\t- Readout:        %10.2f   |   %10.2f   (electrons)\"\n            % (RN, (RN * npix * Nexp))\n        )\n        print(\n            \"\\t- Dark current:   %10.2f   |   %10.2f   (electrons)\"\n            % (DC * DIT, (DC * DIT * npix * Nexp))\n        )\n        print(\n            \"\\t- Digitization:   %10.2f   |   %10.2f   (electrons)\"\n            % (DigN, (DigN * npix * Nexp))\n        )\n        print(\n            \"\\t- Instrument bg:  %10.2f   |   %10.2f   (electrons)\"\n            % (inst_bg * DIT, (inst_bg * DIT * npix * Nexp))\n        )\n\n        print(\n            \"\\nSNR: -Brightest pixel: %.2f\"\n            % (\n                np.sqrt(Nexp)\n                * Ftot_el\n                * f_pix\n                / f_PSF\n                / np.sqrt(\n                    Ftot_el * f_pix / f_PSF\n                    + factor_ima\n                    * ((RN ** 2.0 + DigN ** 2.0) + DIT * (DC + BN + inst_bg))\n                )\n            )\n        )\n        print(\n            \"     -integrated over %d pixels: %.2f\"\n            % (\n                npix,\n                np.sqrt(Nexp)\n                * Ftot_el\n                / np.sqrt(\n                    Ftot_el\n                    + factor_ima\n                    * npix\n                    * ((RN ** 2.0 + DigN ** 2.0) + DIT * (DC + BN + inst_bg))\n                ),\n            )\n        )\n        print(\n            \"\\nTotal of electrons collected in the brightest pixel during an exposure time of %d seconds: %.2f \"\n            % (DIT_pix, N_el_tot_pix2)\n        )\n        if N_el_tot_pix2 > info_dict[\"cameras\"][info_dict[\"channel\"]][\"FWC\"]:\n            print(\n                \"--> Brightest pixel saturated: number of electrons > Full well Capacity\"\n            )\n        elif N_el_tot_pix2 > info_dict[\"cameras\"][info_dict[\"channel\"]][\"gain\"] * (\n            2.0 ** (info_dict[\"cameras\"][info_dict[\"channel\"]][\"bits\"]) - 1\n        ):\n            print(\n                \"--> Brightest pixel saturated: number of electrons > number of digitizations\"\n            )\n        elif (\n            N_el_tot_pix2 > 1.0 / 2 * info_dict[\"cameras\"][info_dict[\"channel\"]][\"FWC\"]\n        ):\n            print(\n                \"--> Number of electrons in brightest pixel > 1/2 of Full well Capacity. Risk of non-linear response.\"\n            )\n\n        else:\n            print(\"--> No saturation\")\n\n        print(\n            \"\\nDead time: %.2f sec \\n(%.2f sec for dithering, the %.2f sec for the readout are not taken into account)\"\n            % (\n                info_dict[\"deadtime_tot\"],\n                info_dict[\"T_dithering\"],\n                info_dict[\"cameras\"][info_dict[\"channel\"]][\"ReadoutTime\"],\n            )\n        )\n    info_dict[\"SNR\"] = SNR\n    info_dict[\"mag\"] = mag\n    info_dict[\"total_exposure_time\"] = DIT * Nexp\n    info_dict[\"fph\"] = fph\n\n    return info_dict\n", "meta": {"hexsha": "606b64e5ca835e93c59e643bbde3605c66b1111b", "size": 21276, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyETC/solver.py", "max_stars_repo_name": "dcorre/pyETC", "max_stars_repo_head_hexsha": "88d4eb78a6a638b28d05c6798c32952956f956b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-21T14:53:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-04T21:48:03.000Z", "max_issues_repo_path": "pyETC/solver.py", "max_issues_repo_name": "dcorre/pyETC", "max_issues_repo_head_hexsha": "88d4eb78a6a638b28d05c6798c32952956f956b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-08-02T06:54:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-05T10:44:22.000Z", "max_forks_repo_path": "pyETC/solver.py", "max_forks_repo_name": "dcorre/pyETC", "max_forks_repo_head_hexsha": "88d4eb78a6a638b28d05c6798c32952956f956b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-24T21:37:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-24T21:37:11.000Z", "avg_line_length": 35.8785834739, "max_line_length": 184, "alphanum_fraction": 0.495534875, "include": true, "reason": "import numpy", "num_tokens": 5780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.30404168127272885, "lm_q1q2_score": 0.19368391377631788}}
{"text": "# This file is part of sequencing.\n#\n#    Copyright (c) 2021, The Sequencing Authors.\n#    All rights reserved.\n#\n#    This source code is licensed under the BSD-style license found in the\n#    LICENSE file in the root directory of this source tree.\n\nimport re\nimport json\nfrom collections import defaultdict\nfrom contextlib import contextmanager\n\nimport numpy as np\nimport qutip\nimport attr\n\nfrom .parameters import Parameterized, ListParameter, DictParameter\nfrom .modes import Mode, sort_modes\n\n\nclass CouplingTerm(object):\n    \"\"\"An object representing a coupling between two ``Modes``,\n    given by a Hamiltonian term of the form ``strength * op1 * op2``.\n    If the keyword argument ``add_hc`` is provided and is True,\n    then the Hamiltonian term takes the form\n    ``strength * ((op1 * op2) + (op1 * op2).dag())``.\n\n    Args:\n        mode1 (Mode): First mode to be coupled.\n        op1_expr (str): String representation of mode1's operator in the coupling term.\n        mode2 (Mode): Second mode to tbe coupled (can the same object as mode1).\n        op2_expr (str): String representation of mode2's operator in the coupling term.\n        strength (optional, float): Coefficient parameterizing the\n            strength of the coupling. Strength should be given in\n            units of 2 * pi * GHz. Default: 1.\n        add_hc (optional, bool): Whether to add the Hermitian conjugate\n            of the product of op1 and op2. Default: False.\n    \"\"\"\n\n    def __init__(self, mode1, op1_expr, mode2, op2_expr, strength=1, add_hc=False):\n        for mode in [mode1, mode2]:\n            if not isinstance(mode, Mode):\n                raise TypeError(f\"Expected instance of Mode, but got {type(mode)}.\")\n        for expr in [op1_expr, op2_expr]:\n            if not isinstance(expr, str):\n                raise TypeError(f\"Expected instance of str, but got {type(expr)}.\")\n        self.mode1 = mode1\n        self.mode2 = mode2\n        self.op1_expr = op1_expr\n        self.op2_expr = op2_expr\n        self.strength = float(strength)\n        self.add_hc = bool(add_hc)\n\n    @property\n    def op1(self):\n        \"\"\"Operator for ``mode1``.\"\"\"\n        op = self.mode1.operator_expr(self.op1_expr)\n        if not isinstance(op, qutip.Qobj):\n            raise TypeError(f\"Expected op1 to be a qutip.Qobj, not {type(op)}\")\n        if not self.add_hc and not op.isherm:\n            raise ValueError(\"Expected op1 to be Hermitian since add_hc is False.\")\n        return op\n\n    @property\n    def op2(self):\n        \"\"\"Operator for ``mode2``.\"\"\"\n        op = self.mode2.operator_expr(self.op2_expr)\n        if not isinstance(op, qutip.Qobj):\n            raise TypeError(f\"Expected op2 to be a qutip.Qobj, not {type(op)}\")\n        if not self.add_hc and not op.isherm:\n            raise ValueError(\"Expected op2 to be Hermitian since add_hc is False.\")\n        return op\n\n    def H(self, strength=None, add_hc=None):\n        \"\"\"Returns the operator representing the coupling term.\n\n        Args:\n            strength (optional, float): Coefficient parameterizing the\n                strength of the coupling. Strength should be given in units\n                of 2 * pi * GHz. Defaults to self.strength.\n            add_hc (optional, bool): Whether to add the Hermitian conjugate\n                of product of op1 and op2. Defaults to self.add_hc.\n\n        Returns:\n            ``qutip.Qobj``: Operator representing the coupling term.\n        \"\"\"\n        if strength is None:\n            strength = self.strength\n        if add_hc is None:\n            add_hc = self.add_hc\n        op = self.op1 * self.op2\n        if add_hc:\n            op = op + op.dag()\n        return strength * op\n\n    def __repr__(self):\n        return (\n            f\"{type(self).__name__}(\"\n            f\"{self.mode1.name}.{self.op1_expr}, \"\n            f\"{self.mode2.name}.{self.op2_expr}, \"\n            f\"strength={self.strength:.3e}, \"\n            f\"add_hc={self.add_hc}\"\n            \")\"\n        )\n\n\n@attr.s\nclass System(Parameterized):\n    \"\"\"A collection of ``Modes`` that can be coupled together.\n\n    Attributes:\n        modes (list[Mode]): List of all Modes in the system.\n        coupling_terms (dict[frozenset[str], list[CouplingTerm]]):\n            A dictionary of CouplingTerm objects specifying all\n            interactions in the system.\n        cross_kerrs (dict[frozenset[str], float]): A dictionary\n            of cross-Kerr values in units of GHz.\n    \"\"\"\n\n    modes = ListParameter()\n    cross_kerrs = DictParameter()\n\n    order_modes = True\n\n    def initialize(self):\n        super().initialize()\n        if self.order_modes:\n            self.modes = sort_modes(self.modes)\n        self.active_modes = self.modes\n        self.coupling_terms = defaultdict(list)\n\n    def __getattribute__(self, name):\n        # Access modes like system.qubit.\n        # System.modes can be changed at any time, so we cannot\n        # just setattr(self, name, mode) in initialize().\n        try:\n            for mode in object.__getattribute__(self, \"modes\"):\n                if mode.name == name:\n                    return mode\n        except AttributeError:\n            pass\n        return object.__getattribute__(self, name)\n\n    def get_mode(self, mode):\n        \"\"\"Fetch a mode by name.\n\n        Args:\n            mode (str or Mode): Name of Mode to fetch, or the Mode itself.\n\n        Returns:\n            Mode: The requested ``Mode``.\n        \"\"\"\n        if isinstance(mode, Mode):\n            mode = mode.name\n        if mode not in [m.name for m in self.modes]:\n            raise ValueError(f\"{mode} is not a mode of {self.name}.\")\n        return getattr(self, mode)\n\n    @property\n    def levels(self):\n        \"\"\"Dictionary of (mode_name, number_of_levels)\"\"\"\n        return {mode.name: mode.levels for mode in self.modes}\n\n    @property\n    def active_modes(self):\n        \"\"\"List of the modes currently being used.\"\"\"\n        for mode in self._active_modes:\n            if mode not in self.modes:\n                raise ValueError(\n                    f\"{mode.name} is not in {self.name}.modes. \"\n                    f\"This likely happened because {self.name}.modes \"\n                    f\"was changed after {self.name} was created.\"\n                    f\"Please set {self.name}.active_modes to be \"\n                    f\"a subset of {self.name}.modes.\"\n                )\n        return self._active_modes\n\n    @active_modes.setter\n    def active_modes(self, modes):\n        if isinstance(modes[0], str):\n            modes = [getattr(self, m) for m in modes]\n        if self.order_modes:\n            modes = sort_modes(modes)\n        if not all(mode in self.modes for mode in modes):\n            raise ValueError(\"active_modes must be a subset of the system's modes.\")\n        self._active_modes = modes\n        for mode in self._active_modes:\n            mode.space = self._active_modes\n\n    @contextmanager\n    def use_modes(self, modes):\n        \"\"\"A context manager that temporarily sets ``self.active_modes``\n        to ``modes``, then reverts ``self.active_modes``\n        to its previous value.\n\n        Args:\n            modes (list[Mode]): List of ``Modes`` to temporarily\n                assign to ``self.active_modes``.\n        \"\"\"\n        if isinstance(modes, (str, Mode)):\n            modes = [modes]\n        old_modes = self.active_modes\n        try:\n            self.active_modes = modes\n            yield\n        finally:\n            self.active_modes = old_modes\n\n    @staticmethod\n    def tensor(*args):\n        \"\"\"Calculates the tensor product of input operators.\"\"\"\n        return qutip.tensor(*args)\n\n    def I(self, modes=None):  # noqa: E741, E743\n        \"\"\"Identity operator.\n\n        Args:\n            modes (optional, list[Mode]): List of Modes to use in\n                constructing H0. If None, will use self.active_modes.\n                Default: None.\n\n        Returns:\n            ``qutip.Qobj``: Identity operator on the Hilbert space\n            defined by ``modes``.\n        \"\"\"\n        if modes is None:\n            modes = self.active_modes\n        elif not all(mode in self.modes for mode in modes):\n            raise ValueError(\"modes must be a subset of the system's modes.\")\n        return self.tensor(*[qutip.qeye(mode.levels) for mode in modes])\n\n    eye = I\n\n    def fock(self, *args, **kwargs):\n        \"\"\"Returns a product state in the Fock basis. States can be\n        specified either positionally or as keyword arguments.\n\n        Args:\n            *args (tuple): Fock states of Modes in the order of self.modes.\n            **kwargs (dict): Fock states of Modes specified as keyword\n                arguments, mode_name=n.\n\n        Returns:\n            ``qutip.Qobj``: The requested product state.\n        \"\"\"\n        if args:\n            if kwargs:\n                raise ValueError(\n                    \"If positional arguments are provided, \"\n                    \"no keyword arguments are allowed.\"\n                )\n            if len(args) != len(self.active_modes):\n                raise ValueError(\n                    \"The number of positional argument must match \"\n                    \"the number of active modes.\"\n                )\n            states = [\n                qutip.fock(mode.levels, val)\n                for mode, val in zip(self.active_modes, args)\n            ]\n        else:\n            states = [\n                qutip.fock(mode.levels, kwargs.get(mode.name, 0))\n                for mode in self.active_modes\n            ]\n        return self.tensor(*states)\n\n    def fock_dm(self, *args, **kwargs):\n        \"\"\"Returns a product state in the Fock basis, as a density matrix.\n\n        States can be specified either positionally or as keyword arguments.\n\n        Args:\n            *args (tuple): Fock states of Modes in the order of self.modes.\n            **kwargs (dict): Fock states of Modes specified as keyword\n                arguments, mode_name=n.\n\n        Returns:\n            ``qutip.Qobj``: The requested product state, as a density matrix.\n        \"\"\"\n        ket = self.fock(*args, **kwargs)\n        return qutip.ket2dm(ket)\n\n    basis = fock\n\n    def ground_state(self):\n        \"\"\"Returns the ground state of the system.\n\n        Returns:\n            ``qutip.Qobj``: The system's ground state.\n        \"\"\"\n        return self.fock()\n\n    def logical_basis(self, *args, **kwargs):\n        \"\"\"Returns a product state in the basis spanned by the logical states\n        of all modes. Logical states can be specified either positionally\n        or as keyword arguments.\n\n        Args:\n            *args (tuple): Logical states of Modes in the order of self.modes.\n            **kwargs (dict): Logical states of Modes specified as keyword\n                arguments, mode_name=n.\n\n        Returns:\n            ``qutip.Qobj``: The requested product state.\n        \"\"\"\n        if args:\n            if kwargs:\n                raise ValueError(\n                    \"If positional arguments are provided, \"\n                    \"no keyword arguments are allowed.\"\n                )\n            if len(args) != len(self.active_modes):\n                raise ValueError(\n                    \"The number of positional argument must match \"\n                    \"the number of active modes.\"\n                )\n            states = [\n                mode.logical_states(full_space=False)[val]\n                for mode, val in zip(self.active_modes, args)\n            ]\n        else:\n            states = [\n                mode.logical_states(full_space=False)[kwargs.get(mode.name, 0)]\n                for mode in self.active_modes\n            ]\n        return self.tensor(*states)\n\n    def set_cross_kerr(self, mode1, mode2, chi=0):\n        \"\"\"Set the cross-Kerr (in GHz) between two modes. Note that the order\n        of mode1 and mode2 doesn't matter.\n\n        Args:\n            mode1 (Mode or str): Instance of Mode or\n                the name of a member of ``self.modes``.\n            mode2 (Mode or str): Instance of Mode or\n                the name of a member of ``self.modes``.\n            chi (optional, float): Cross-Kerr between mode0 and mode1 in GHz.\n                Default: 0.\n        \"\"\"\n        if isinstance(mode1, str):\n            mode1 = self.get_mode(mode1)\n        if isinstance(mode2, str):\n            mode2 = self.get_mode(mode2)\n        if mode1 is mode2:\n            raise ValueError(\"If mode1 is mode2, then it's not a cross-Kerr.\")\n        key = frozenset([mode1.name, mode2.name])\n        # Replace this cross-Kerr if it already exists\n        if key in self.coupling_terms:\n            for i, term in enumerate(self.coupling_terms[key][:]):\n                if (\n                    term.mode1 is mode1\n                    and term.op1_expr == \"n\"\n                    and term.mode2 is mode2\n                    and term.op2_expr == \"n\"\n                ) or (\n                    term.mode1 is mode2\n                    and term.op1_expr == \"n\"\n                    and term.mode2 is mode1\n                    and term.op2_expr == \"n\"\n                ):\n                    _ = self.coupling_terms[key].pop(i)\n        self.coupling_terms[key].append(\n            CouplingTerm(mode1, \"n\", mode2, \"n\", strength=2 * np.pi * chi)\n        )\n        self.cross_kerrs[key] = chi\n\n    def couplings(self, modes=None, clean=True):\n        \"\"\"Returns all of the static coupling terms in the Hamiltonian.\n\n        Args:\n            modes (optional, list[Mode]): List of Modes to use in\n                constructing H0. If None, will use self.active_modes.\n                Default: None.\n            clean (optional, bool): Only keep operators with nonzero elements.\n                Default: True.\n\n        Returns:\n            list[qutip.Qobj]: List of static coupling terms.\n        \"\"\"\n        if modes is None:\n            modes = self.active_modes\n        mode_names = [mode.name for mode in modes]\n        coupling_terms = []\n        with self.use_modes(modes):\n            for (mode0, mode1), terms in self.coupling_terms.items():\n                if mode0 in mode_names and mode1 in mode_names:\n                    coupling_terms.extend([term.H() for term in terms])\n        if clean:\n            return [term for term in coupling_terms if term.data.nnz]\n        return coupling_terms\n\n    def H0(self, modes=None, clean=True):\n        \"\"\"Returns the static Hamiltonian consisting of all\n        self-Kerrs and cross-Kerrs.\n\n        Args:\n            modes (optional, list[Mode]): List of Modes to use in\n                constructing H0. If None, will use self.active_modes.\n                Default: None.\n            clean (optional, bool): Only keep operators with nonzero elements.\n                Default: True.\n\n        Returns:\n            list[qutip.Qobj]: Static Hamiltonian in list form.\n        \"\"\"\n        if modes is None:\n            modes = self.active_modes\n        detunings = [mode.detuning for mode in modes]\n        self_kerrs = [mode.self_kerr for mode in modes]\n        couplings = self.couplings(modes=modes, clean=clean)\n        H0 = detunings + self_kerrs + couplings\n        if clean:\n            return [H for H in H0 if H.data.nnz]\n        return H0\n\n    def c_ops(self, modes=None, clean=True):\n        \"\"\"Returns a list of collapse operators corresponding to\n        loss (decay/excitation) and dephasing of all modes.\n\n        Args:\n            modes (optional, list[Mode]): List of Modes to use in\n                constructing H0. If None, will use self.active_modes.\n                Default: None.\n            clean (optional, bool): Only keep operators with nonzero elements.\n                Default: True.\n\n        Returns:\n            list[qutip.Qobj]: List of all collapse operators.\n        \"\"\"\n        if modes is None:\n            modes = self.active_modes\n        decay = [mode.decay for mode in modes]\n        excitation = [mode.excitation for mode in modes]\n        dephasing = [mode.dephasing for mode in modes]\n        c_ops = decay + excitation + dephasing\n        if clean:\n            return [c for c in c_ops if c.data.nnz]\n        return c_ops\n\n    def as_dict(self, json_friendly=False):\n        \"\"\"Overrides Parameterized.as_dict() in order to deal with cross_kerrs.\n\n        Args:\n            json_friendly (optional, bool): Whether to return\n                a JSON-friendly dictionary. Default:True.\n\n        Returns:\n            dict: Dictionary representation of the System object.\n        \"\"\"\n        d = super().as_dict(json_friendly=json_friendly)\n        cross_kerrs = d.pop(\"cross_kerrs\")\n        d[\"cross_kerrs\"] = {}\n        if json_friendly:\n            # turn frozenset({mode0, mode1}) into '{mode0, mode1}' for json\n            for key, val in cross_kerrs.items():\n                new_key = \"{\" + \", \".join(key) + \"}\"\n                d[\"cross_kerrs\"][new_key] = val\n        else:\n            for key, val in cross_kerrs.items():\n                d[\"cross_kerrs\"][key] = val\n        return d\n\n    @classmethod\n    def from_json(cls, json_path=None, json_str=None):\n        \"\"\"Overrides Parameterized.from_json()\n        in order to deal with cross_kerrs.\n\n        Args:\n            json_path (optional, str): Path to JSON file from which\n                to load parameters. Required if ``json_str`` is ``None``.\n                Default: None.\n            json_str (optional, str): JSON string like that returned by\n                ``self.to_json(dumps=True)``. Required if ``json_path``\n                is ``None`` Default: None.\n\n        Returns:\n            System: Instance of ``System``\n            whose parameters have been populated from the JSON data.\n        \"\"\"\n\n        def json_decode(obj):\n            # decode CrossKerr\n            for key in list(obj):\n                if re.match(r\"\\{(.*?)\\}\", key):\n                    # turn '{mode0, mode1}' into frozenset({mode0, mode1})\n                    k = key.replace(\"{\", \"\").replace(\"}\", \"\").split(\", \")\n                    new_key = frozenset(k)\n                    obj[new_key] = obj[key]\n                    del obj[key]\n            return obj\n\n        if json_str is not None:\n            if json_path is not None:\n                raise ValueError(\n                    \"You must provide either json_path \" \"or json_str, not both.\"\n                )\n            d = json.loads(json_str, object_hook=json_decode)\n        else:\n            if json_path is None:\n                raise ValueError(\"You must provide either json_path \" \"or json_str.\")\n            if not json_path.endswith(\".json\"):\n                json_path = json_path + \".json\"\n            with open(json_path, \"r\") as f:\n                d = json.load(f, object_hook=json_decode)\n\n        return cls.from_dict(d)\n", "meta": {"hexsha": "e4c00db13b875aadb2706bb663b5badbfc20dd3b", "size": 18679, "ext": "py", "lang": "Python", "max_stars_repo_path": "sequencing/system.py", "max_stars_repo_name": "ypeels/sequencing", "max_stars_repo_head_hexsha": "3d00a60ae94164422bb891dac35d686dbc3a1210", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sequencing/system.py", "max_issues_repo_name": "ypeels/sequencing", "max_issues_repo_head_hexsha": "3d00a60ae94164422bb891dac35d686dbc3a1210", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sequencing/system.py", "max_forks_repo_name": "ypeels/sequencing", "max_forks_repo_head_hexsha": "3d00a60ae94164422bb891dac35d686dbc3a1210", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6974459725, "max_line_length": 87, "alphanum_fraction": 0.5635205311, "include": true, "reason": "import numpy", "num_tokens": 4166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792046, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19358781864024524}}
{"text": "\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport math\n\nimport oneflow as flow\nfrom oneflow.nn import init\nfrom oneflow.nn.common_types import _size_2_t\nfrom oneflow.nn.module import Module\nfrom oneflow.nn.modules.utils import _pair\n\n\ndef slice(x, begin, size):\n    ndim = len(x.shape)\n    if not isinstance(begin, (list, tuple)) or len(begin) != ndim:\n        raise ValueError(\n            \"begin must be a list/tuple with the same length as input tensor's number of dimensions\"\n        )\n    if not all((isinstance(b, int) or b is None for b in begin)):\n        raise ValueError(\"element of begin must be a int or None\")\n    if not isinstance(size, (list, tuple)) or len(size) != ndim:\n        raise ValueError(\n            \"size must be a list/tuple with the same length as input tensor's number of dimensions.\"\n        )\n    if not all((isinstance(s, int) or s is None for s in size)):\n        raise ValueError(\"element of size must be a int or None\")\n    slice_tup_list = []\n    for (b, s, dim_size) in zip(begin, size, x.shape):\n        (start, stop, step) = (None, None, 1)\n        if b is not None:\n            if b < -dim_size or b >= dim_size:\n                raise ValueError(\"element of begin is out of range\")\n            start = b\n        if s is not None:\n            if s == -1:\n                stop = dim_size\n            else:\n                if s <= 0 or s > dim_size:\n                    raise ValueError(\"element of size is invalid\")\n                if b + s < dim_size:\n                    stop = b + s\n        slice_tup_list.append((start, stop, step))\n    return flow.slice(x, slice_tup_list)\n\n\nclass ConvUtil(object):\n    @classmethod\n    def split(cls, x, axis, split_num):\n        split_len = x.shape[axis] // split_num\n        result_list = []\n        slice_begin = [0] * len(x.shape)\n        slice_size = [-1] * len(x.shape)\n        slice_size[axis] = split_len\n        for i in range(split_num):\n            slice_begin[axis] = i * split_len\n            result = slice(x, slice_begin, slice_size)\n            result_list.append(result)\n        return result_list\n\n\nclass ConvTranspose2d(Module):\n    \"\"\"\n    \n    Applies a 2D transposed convolution operator over an input image composed of several input planes.\n\n    This module can be seen as the gradient of Conv2d with respect to its input.\n    It is also known as a fractionally-strided convolution or\n    a deconvolution (although it is not an actual deconvolution operation).\n\n    Args:\n        in_channels (int): Number of channels in the input image\n        out_channels (int): Number of channels produced by the convolution\n        kernel_size (int or tuple): Size of the convolving kernel\n        stride (int or tuple, optional): Stride of the convolution. Default: 1\n        padding (int or tuple, optional): ``dilation * (kernel_size - 1) - padding`` zero-padding\n            will be added to both sides of each dimension in the input. Default: 0\n        output_padding (int or tuple, optional): Additional size added to one side\n            of each dimension in the output shape. Default: 0\n        groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1\n        bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True``\n        dilation (int or tuple, optional): Spacing between kernel elements. Default: 1\n\n    Shape:\n        - Input: :math:`(N, C_{in}, H_{in}, W_{in})`\n        - Output: :math:`(N, C_{out}, H_{out}, W_{out})` where\n\n        .. math::\n              H_{out} = (H_{in} - 1) \\\\times \\\\text{stride}[0] - 2 \\\\times \\\\text{padding}[0] + \\\\text{dilation}[0] \n\n                        \\\\times (\\\\text{kernel_size}[0] - 1) + \\\\text{output_padding}[0] + 1\n        .. math::\n              W_{out} = (W_{in} - 1) \\\\times \\\\text{stride}[1] - 2 \\\\times \\\\text{padding}[1] + \\\\text{dilation}[1]\n              \n                        \\\\times (\\\\text{kernel_size}[1] - 1) + \\\\text{output_padding}[1] + 1\n\n    Attributes:\n        ConvTranspose2d.weight (Tensor): the learnable weights of the module of shape\n                         :math:`(\\\\text{in_channels}, \\\\frac{\\\\text{out_channels}}{\\\\text{groups}},`\n                         :math:`\\\\text{kernel_size[0]}, \\\\text{kernel_size[1]})`.\n                         The values of these weights are sampled from\n                         :math:`\\\\mathcal{U}(-\\\\sqrt{k}, \\\\sqrt{k})` where\n                         :math:`k = \\\\frac{groups}{C_\\\\text{out} * \\\\prod_{i=0}^{1}\\\\text{kernel_size}[i]}`\n        ConvTranspose2d.bias (Tensor): the learnable bias of the module of shape (out_channels)\n                         If :attr:`bias` is ``True``, then the values of these weights are\n                         sampled from :math:`\\\\mathcal{U}(-\\\\sqrt{k}, \\\\sqrt{k})` where\n                         :math:`k = \\\\frac{groups}{C_\\\\text{out} * \\\\prod_{i=0}^{1}\\\\text{kernel_size}[i]}`\n\n    Examples::\n\n        >>> import numpy as np\n        >>> import oneflow as flow\n        >>> import oneflow.nn as nn\n        \n        >>> m = nn.ConvTranspose2d(16, 33, 3, stride=2)\n        >>> # non-square kernels and unequal stride and with padding\n        >>> m = nn.ConvTranspose2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))\n        >>> m = m.to(\"cuda\")\n        >>> input = flow.Tensor(np.random.randn(20, 16, 50, 100), device=flow.device(\"cuda\"))\n        >>> output = m(input)\n        >>> output.size()\n        flow.Size([20, 33, 93, 100])\n\n    .. _cross-correlation:\n        https://en.wikipedia.org/wiki/Cross-correlation\n\n    .. _link:\n        https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md\n    \"\"\"\n\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        kernel_size: _size_2_t,\n        stride: _size_2_t = 1,\n        padding: _size_2_t = 0,\n        output_padding: _size_2_t = 0,\n        groups: int = 1,\n        bias: bool = True,\n        dilation: int = 1,\n        padding_mode: str = \"zeros\",\n    ) -> None:\n        super().__init__()\n        assert padding_mode == \"zeros\"\n        kernel_size = _pair(kernel_size)\n        stride = _pair(stride)\n        padding = _pair(padding)\n        output_padding = _pair(output_padding)\n        dilation = _pair(dilation)\n        self.groups = groups\n        assert in_channels % groups == 0\n        assert out_channels % groups == 0\n        self.weight = flow.nn.Parameter(\n            flow.Tensor(in_channels, out_channels // groups, *kernel_size)\n        )\n        self.in_channel_groups = in_channels // groups\n        self.bias = None\n        self._bias_add_op = None\n        if bias:\n            self.bias = flow.nn.Parameter(flow.Tensor(out_channels))\n            self._bias_add_op = (\n                flow.builtin_op(\"bias_add\")\n                .Input(\"a\")\n                .Input(\"b\")\n                .Output(\"out\")\n                .Attr(\"axis\", 1)\n                .Build()\n            )\n        self._op = (\n            flow.builtin_op(\"deconv2d\")\n            .Input(\"in\")\n            .Input(\"weight\")\n            .Attr(\"filters\", out_channels // groups)\n            .Attr(\"padding_before\", padding)\n            .Attr(\"data_format\", \"channels_first\")\n            .Attr(\"kernel_size\", kernel_size)\n            .Attr(\"strides\", stride)\n            .Attr(\"dilation_rate\", dilation)\n            .Attr(\"output_padding\", output_padding)\n            .Attr(\"groups\", 1)\n            .Output(\"out\")\n            .Build()\n        )\n        self.reset_parameters()\n\n    def reset_parameters(self) -> None:\n        init.kaiming_uniform_(self.weight, a=math.sqrt(5))\n        if self.bias is not None:\n            (fan_in, _) = init._calculate_fan_in_and_fan_out(self.weight)\n            bound = 1 / math.sqrt(fan_in)\n            init.uniform_(self.bias, -bound, bound)\n\n    def forward(self, x):\n        if self.groups > 1:\n            in_channel_axis = 1\n            in_split_list = ConvUtil.split(\n                x, axis=in_channel_axis, split_num=self.groups\n            )\n            out_list = []\n            for i in range(len(in_split_list)):\n                out_list.append(\n                    self._op(\n                        in_split_list[i],\n                        self.weight[\n                            i\n                            * self.in_channel_groups : (i + 1)\n                            * self.in_channel_groups,\n                            :,\n                            :,\n                            :,\n                        ],\n                    )[0]\n                )\n            res = flow.cat(out_list, dim=in_channel_axis)\n        else:\n            res = self._op(x, self.weight)[0]\n        if self._bias_add_op is not None:\n            res = self._bias_add_op(res, self.bias)[0]\n        return res\n\n\nif __name__ == \"__main__\":\n    import doctest\n\n    doctest.testmod(raise_on_error=True)\n", "meta": {"hexsha": "e69794aea2a37bbb86fa10e7c0e7d7b120f9e09e", "size": 9388, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/oneflow/nn/modules/deconv.py", "max_stars_repo_name": "wangyuyue/oneflow", "max_stars_repo_head_hexsha": "0a71c22fe8355392acc8dc0e301589faee4c4832", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-13T02:34:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-13T02:34:53.000Z", "max_issues_repo_path": "python/oneflow/nn/modules/deconv.py", "max_issues_repo_name": "wangyuyue/oneflow", "max_issues_repo_head_hexsha": "0a71c22fe8355392acc8dc0e301589faee4c4832", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/oneflow/nn/modules/deconv.py", "max_forks_repo_name": "wangyuyue/oneflow", "max_forks_repo_head_hexsha": "0a71c22fe8355392acc8dc0e301589faee4c4832", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-17T03:34:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-17T03:34:39.000Z", "avg_line_length": 39.4453781513, "max_line_length": 116, "alphanum_fraction": 0.5609288453, "include": true, "reason": "import numpy", "num_tokens": 2289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1935878186402452}}
{"text": "#!/usr/bin/env python3\n\"\"\"Compute a background mask for X-ray microscopy data.\n\nFunctions\n---------\nparse_args\n    Parse command line arguments.\ninitialize_cloudvolume\n    Create a new CloudVolume archive.\nload_image\n    Load an image from CloudVolume.\ncreate_bg_mask\n    Create a mask of background regions in x-ray microscopy.\nwrite_image\n    Write an image to CloudVolume.\n\nDependencies\n------------\ncloud-volume\nmpi4py\nnumpy\nscipy\nscikit-image\n\"\"\"\n\nimport argparse\nimport logging\nimport os\nimport re\n\nfrom cloudvolume import CloudVolume\nfrom mpi4py import MPI\nimport numpy as np\nfrom scipy.signal import find_peaks, peak_prominences, peak_widths\nfrom skimage.exposure import histogram\nfrom skimage.filters import gaussian\nfrom skimage.measure import label, regionprops\nfrom skimage.morphology import remove_small_holes\n\n\nCOMM = MPI.COMM_WORLD\nRANK = COMM.Get_rank()\nSIZE = COMM.Get_size()\n\nLOGGER = logging.getLogger('create_background_mask.py')\nsyslog = logging.StreamHandler()\nformatter = logging.Formatter('%(asctime)s %(name)s Rank %(rank)s : %(message)s')\nsyslog.setFormatter(formatter)\nLOGGER.setLevel(logging.INFO)\nLOGGER.addHandler(syslog)\nLOGGER = logging.LoggerAdapter(LOGGER, {'rank': str(RANK)})\n\n\ndef parse_args():\n    \"\"\"Parse command line arguments.\"\"\"\n    p = argparse.ArgumentParser()\n\n    p.add_argument('--input', type=str,\n                   help='path to the CloudVolume archive')\n    p.add_argument('--output', type=str,\n                   help='path to the bg mask CloudVolume archive')\n    p.add_argument('--resolution', type=int, nargs='*', default=[10, 10, 10],\n                   help='resolution of the dataset')\n    p.add_argument('--mip', type=int, default=0,\n                   help='number of mip levels to create')\n    p.add_argument('--chunk-size', type=int, nargs='*', default=[64, 64, 64],\n                   help='size of each CloudVolume block file')\n    p.add_argument('--z-step', type=int, default=None)\n    p.add_argument('--factor', type=int, nargs='*', default=[2, 2, 2],\n                   help='factor to scale between mip levels')\n    p.add_argument('--flip-xy', action='store_true',\n                   help='pass to transplose the X and Y axes')\n    p.add_argument('--memory-limit', type=float, default=10000,\n                   help='max memory available to CloudVolume')\n    p.add_argument('--offset', type=int, nargs='*', default=[0, 0, 0],\n                   help='offset into the volume from the upper-left corner')\n    p.add_argument('--quiet', action='store_true',\n                   help='pass to deactivate logging')\n\n    return p.parse_args()\n\n\ndef initialize_cloudvolume(path, resolution, offset, volume_size, chunk_size,\n                           mip, factor):\n    \"\"\"Create a new CloudVolume archive.\n\n    Parameters\n    ----------\n    path : str\n        Filepath to the location to write the archive.\n    resolution : tuple of int\n        Imaging resolution of the images in each dimension.\n    offset : tuple of int\n        Offset within the volume to the start of the archive.\n    volume_size : tuple of int\n        The dimensions of the volume in pixels.\n    chunk_size : tuple of int\n        The size of each CloudVolume block in pixels.\n    mip : int\n        The number of mip levels to include.\n    factor : tuple of int\n        The factor of change in each dimension across mip levels.\n\n    Returns\n    -------\n    cv_args : dict\n        The parameters needed to re-access the CloudVolume archive.\n    \"\"\"\n    # Set the parameters of the info file.\n    info = CloudVolume.create_new_info(\n        num_channels=1,\n        layer_type='segmentation',\n        data_type='uint32',\n        encoding='compressed_segmentation',\n        resolution=resolution,\n        voxel_offset=offset,\n        volume_size=volume_size[:-1],\n        chunk_size=chunk_size,\n        max_mip=0,\n        factor=factor\n    )\n\n    # Set up and initialize the CloudVolume object\n    cv_args = dict(\n        bounded=True, fill_missing=True, autocrop=False,\n        cache=False, compress_cache=None, cdn_cache=False,\n        progress=False, info=info, provenance=None, compress=True,\n        non_aligned_writes=True, parallel=1)\n\n    # for i in range(1, mip + 1):\n    #     info['scales'][i]['compressed_segmentation_block_size'] = \\\n    #         info['scales'][0]['compressed_segmentation_block_size']\n\n    cv = CloudVolume(path, mip=0, **cv_args)\n\n    # Create the info file.\n    LOGGER.info('Initializing image layer with config {}'.format(cv_args))\n    cv.commit_info()\n    return cv_args\n\n\ndef load_subvolume(cv, z_start, z_end, flip_xy=False):\n    \"\"\"Load an image from CloudVolume.\n\n    Parameters\n    ----------\n    cv : cloudvolume.CloudVolume\n        CloudVolume image layer to mask.\n    z_start : int\n        The index of the first image in the layer.\n    z_end : int\n        The index of the last image in the layer.\n    flip_xy : bool\n        CloudVolume reorders the dimension of image volumes, and the order of\n        the x and y dimensions can vary. If True, indicates that the CloudVolume\n        layer is saved in (Y, X, Z) order; otherwise it is saved as (X, Y, Z).\n\n    Returns\n    -------\n    subvol : numpy.ndarray\n        The subvolume with the dimensions reordered as (Z, Y, X).\n    \"\"\"\n    # Each entry in the z dimension represents one image. Extract an image.\n    subvol = cv[:, :, z_start:z_end, :]\n    subvol = np.squeeze(subvol)\n\n    # Transpose the dimensions back to\n    if not flip_xy:\n        subvol = np.transpose(subvol, axes=[2, 1, 0])\n\n    LOGGER.info('Loaded subvolume with shape {}.'.format(subvol.shape))\n    return subvol\n\n\ndef find_bg_mask(img):\n    \"\"\"Create a mask of background regions in x-ray microscopy.\n\n    Parameters\n    ----------\n    img : numpy.ndarray\n        X-ray microscopy image.\n\n    Returns\n    -------\n    bgmask : numpy.ndarray\n        Binary mask of the background of ``img``.\n    \"\"\"\n    if img.ndim == 2:\n        img = np.expand_dims(img, axis=0)\n\n    bgmask = np.zeros((3,) +img.shape, dtype=np.uint8)\n\n    for d in range(img.ndim):\n        for i in range(img.shape[d]):\n            if d == 0:\n                subimg = img[i, :, :]\n            elif d == 1:\n                subimg = img[:, i, :]\n            elif d == 2:\n                subimg = img[:, :, i]\n\n            # Blur the image to smooth any background artifacts.\n            LOGGER.info('Blurring image.')\n            blur = gaussian(subimg, sigma=5, preserve_range=True)\n\n            # Compute the image histogram and find the peaks.\n            LOGGER.info('Finding histogram peaks.')\n            hist, bins = histogram(blur)\n            peaks, properties = find_peaks(hist)  # , height=(0.3 * img.size))\n            prominences = peak_prominences(hist, peaks)\n            widths = peak_widths(hist, peaks, rel_height=0.333,\n                                 prominence_data=prominences)\n\n            # Select the left-most peak (backgrounds are usually dark) and use the\n            # width of the peak to select a threshold value. Create a mask of all\n            # pixels less than or equal to the threshold.\n            ordered = np.argsort(peaks)\n            threshold = peaks[ordered[0]] + (widths[0][ordered[0]] / 2.0)\n            # threshold = peaks[0] + (widths[0][0] / 2.0)\n            LOGGER.info('Setting hard threshold {} for image.'.format(threshold))\n            mask = np.zeros(subimg.shape, dtype=np.uint8)\n            mask[np.where(subimg <= threshold)] = 1\n            # Perform some clean up and find the largest connected component.\n            LOGGER.info('Cleaning mask of image.')\n            # remove_small_holes(mask, area_threshold=30, connectivity=2,\n            #                    in_place=True)\n            labels = label(mask)\n            objs = regionprops(labels)\n            # bg = None\n            # for obj in objs:\n            #     if obj.bbox_area >= 0.85 * img.size:\n            #         coords = obj.coords\n            #         break\n\n            # Select the connected component with the largest bounding box as the\n            # background mask.\n            objs.sort(key=lambda x: x.bbox_area, reverse=True)\n            # objs = [o for o in objs\n            #         if np.any(np.asarray(o.bbox[:mask.ndim]) == np.asarray(mask.shape))\n            #         or np.any(np.asarray(o.bbox[mask.ndim:]) == 0)]\n            print(len(objs))\n            if len(objs) > 0:\n                coords = tuple([objs[0].coords[:, j] for j in range(subimg.ndim)])\n                LOGGER.info('Setting background mask of image.')\n\n                if d == 0:\n                    bgmask[d, i, coords[0], coords[1]] = 1\n                elif d == 1:\n                    bgmask[d, coords[0], i, coords[1]] = 1\n                elif d == 2:\n                    bgmask[d, coords[0], coords[1], i] = 1\n    LOGGER.info('Full background mask covers {} voxels.'.format(np.sum(bgmask)))\n\n    consensus = bgmask[0] + bgmask[1] + bgmask[2]\n    consensus[np.where(consensus == 1)] = 0\n    consensus[consensus.nonzero()] = 1\n    objs = sorted(regionprops(label(consensus)), key=lambda x: x.bbox_area, reverse=True)\n    for obj in objs[1:]:\n        coords = tuple([obj.coords[:, j] for j in range(img.ndim)])\n        consensus[coords] = 0\n\n    LOGGER.info('Full background mask covers {} voxels.'.format(np.sum(consensus)))\n    return consensus.astype(np.uint32)\n\n\ndef write_subvolume(path, subvolume, flip_xy, z_start, mip, factor):\n    \"\"\"Write an image to CloudVolume.\n\n    Parameter\n    ---------\n    path : str\n        Filepath to the location to write the archive.\n    subvolume : numpy.ndarray\n        Image data to write to the archive.\n    flip_xy : bool\n        If True, order ``layer`` as [Y, X, Z]. Otherwise, order ``layer`` as\n        [X, Y, Z].\n    z_start\n        The starting index of ``layer`` within the archive.\n    mip\n        The number of mip levels to compute.\n    factor\n        The factor by which to reduce each mip level along each dimension.\n    \"\"\"\n    # Transpose the axes to match the CloudVolume order\n    if subvolume.ndim == 2:\n        subvolume = np.expand_dims(subvolume, 0)\n\n    if flip_xy:\n        subvolume = np.transpose(subvolume, axes=[1, 2, 0])\n    else:\n        subvolume = np.transpose(subvolume, axes=[2, 1, 0])\n\n    if subvolume.ndim == 3:\n        subvolume = np.expand_dims(subvolume, -1)\n\n    cv_args = dict(\n        bounded=True, fill_missing=True, autocrop=False,\n        cache=False, compress_cache=None, cdn_cache=False,\n        progress=False, info=None, provenance=None, compress=True,\n        non_aligned_writes=True, parallel=1)\n\n    # Set the volume for each mip level\n    for m in range(1):\n        # Access the CloudVolume\n        LOGGER.info('Writing MIP level {}.'.format(mip))\n        cv = CloudVolume(path, mip=m, **cv_args)\n\n        # Compute the index of this layer in the CloudVolume archive\n        offset = cv.mip_voxel_offset(m)\n        step = np.power(np.array(factor), m)\n        cv_z_start = int(z_start // step[2] + offset[2])\n        cv_z_end = int(min(cv_z_start + subvolume.shape[-2], cv.shape[-2]))\n\n        # Set the layer\n        cv[:, :, cv_z_start:cv_z_end] = subvolume\n\n        # Reduce the size of the layer to match the next mip level\n        subvolume = subvolume[::factor[0], ::factor[1], ::factor[2]]\n\n\ndef create_background_mask(input, output, resolution=(10, 10, 10), mip=0,\n                           chunk_size=(64, 64, 64), z_step=None,\n                           factor=(2, 2, 2), flip_xy=False, memory_limit=10000,\n                           offset=(0, 0, 0), quiet=False):\n    \"\"\"Create and write data to a new CloudVolume archive.\"\"\"\n    if quiet:\n        LOGGER.logger.removeHandler(syslog)\n        noop = logging.NullHandler()\n        LOGGER.logger.addHandler(noop)\n\n    if 'image' not in os.path.basename(input):\n        inpath = input + '/image'\n    else:\n        inpath = input\n\n    if os.path.isdir(inpath) and not re.search(r'^file://', inpath):\n        inpath = 'file://' + os.path.abspath(inpath)\n\n    if RANK == 0:\n        LOGGER.info('Loading CloudVolume image layer {}.'.format(inpath))\n\n    img_cv = CloudVolume(inpath)\n    volume_shape = img_cv.shape\n\n    outpath = os.path.abspath(output)\n\n    if os.path.dirname(inpath) == outpath:\n        outpath = outpath + 'background'\n\n    if not re.search(r'^[\\w]+://.+$', outpath):\n        outpath = 'file://' + os.path.abspath(output)\n\n    # On rank 0, initialize the CloudVolume info file, and load in the list of\n    # images to insert into the archive.\n    if RANK == 0:\n        LOGGER.info('Initialized CloudVolume image layer at {}'.format(outpath))\n        cv_args = initialize_cloudvolume(\n            outpath,\n            resolution,\n            offset,\n            volume_shape,\n            chunk_size,\n            mip,\n            factor)\n\n    # Block until the background CloudVolume layer is initialized.\n    GOGOGO = COMM.bcast(1, root=0)\n\n    # Iterate over layers of the volume. Each rank will load and write one\n    # layer at a time. If there are fewer ranks than layers, increment to\n    # n_ranks + rank and load the layer at that index.\n    # offset from the volume origin.\n    layer_idx = RANK * chunk_size[-1]\n    while layer_idx < volume_shape[-2]:\n        # Compute the index of the first image in this layer, including any\n        layer_shape = int(min(layer_idx + chunk_size[-1],\n                              img_cv.shape[-2]))\n        LOGGER.info('Loading images {}-{}.'.format(layer_idx, layer_shape))\n        image = load_subvolume(img_cv, layer_idx, layer_shape,\n                               flip_xy=flip_xy)\n\n        LOGGER.info('Creating background mask.')\n        mask = find_bg_mask(image)\n\n        # Write the layer to the archive.\n        LOGGER.info('Writing mask of images {}-{}'.format(layer_idx, layer_shape))\n        write_subvolume(\n            outpath,\n            mask,\n            flip_xy,\n            layer_idx,\n            mip,\n            factor)\n\n        # Increment to the next known layer that does not overlap with any\n        # other rank.\n        layer_idx += SIZE * chunk_size[-1]\n\n    LOGGER.info('Done.')\n\n\ndef main():\n    args = parse_args()\n    create_background_mask(\n        args.input,\n        args.output,\n        resolution=args.resolution,\n        mip=args.mip,\n        chunk_size=args.chunk_size,\n        z_step=args.z_step,\n        factor=args.factor,\n        flip_xy=args.flip_xy,\n        memory_limit=args.memory_limit,\n        offset=args.offset,\n        quiet=args.quiet)\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "0d043a43e7db9289c34e26d5014e85241aadfddf", "size": 14526, "ext": "py", "lang": "Python", "max_stars_repo_path": "happyneuron/background/create_background_mask.py", "max_stars_repo_name": "jeffkinnison/HappyNeuron", "max_stars_repo_head_hexsha": "66ad1c3dc8fc89b518fe74e8318c5ba6d79b8f0a", "max_stars_repo_licenses": ["BSD-Source-Code"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-31T12:21:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T09:20:10.000Z", "max_issues_repo_path": "happyneuron/background/create_background_mask.py", "max_issues_repo_name": "jeffkinnison/HappyNeuron", "max_issues_repo_head_hexsha": "66ad1c3dc8fc89b518fe74e8318c5ba6d79b8f0a", "max_issues_repo_licenses": ["BSD-Source-Code"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "happyneuron/background/create_background_mask.py", "max_forks_repo_name": "jeffkinnison/HappyNeuron", "max_forks_repo_head_hexsha": "66ad1c3dc8fc89b518fe74e8318c5ba6d79b8f0a", "max_forks_repo_licenses": ["BSD-Source-Code"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-16T09:33:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-16T09:33:12.000Z", "avg_line_length": 34.5035629454, "max_line_length": 89, "alphanum_fraction": 0.6043645876, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1935878186402452}}
{"text": "# Copyright 2018-2021 Xanadu Quantum Technologies Inc.\r\n\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n\r\n#     http://www.apache.org/licenses/LICENSE-2.0\r\n\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\"\"\"Function wrappers for the TensorBox API\"\"\"\r\n# pylint:disable=abstract-class-instantiated,unexpected-keyword-arg\r\nfrom collections.abc import Sequence\r\nimport itertools\r\nimport warnings\r\n\r\nimport numpy as np\r\n\r\nfrom .tensorbox import TensorBox\r\n\r\n\r\ndef _get_multi_tensorbox(values):\r\n    \"\"\"Determines the correct framework to dispatch to given a\r\n    sequence of tensor-like objects.\r\n\r\n    Args:\r\n        values (Sequence[tensor_like]): a sequence of tensor like objects\r\n\r\n    Returns:\r\n        .TensorBox: A TensorBox that will dispatch to the correct framework\r\n        given the rules of precedence. This TensorBox will contain the *first*\r\n        tensor-like object in ``values`` that corresponds to the highest-priority\r\n        framework.\r\n\r\n    To determine the framework to dispatch to, the following rules\r\n    are applied:\r\n\r\n    * Tensors that are incompatible (such as Torch and TensorFlow tensors)\r\n      cannot both be present.\r\n\r\n    * Autograd tensors *may* be present alongside Torch and TensorFlow tensors,\r\n      but Torch and TensorFlow take precendence; the autograd arrays will\r\n      be treated as non-differentiable NumPy arrays. A warning will be raised\r\n      suggesting that vanilla NumPy be used instead.\r\n\r\n    * Vanilla NumPy arrays can be used alongside other tensor objects; they will\r\n      always be treated as non-differentiable constants.\r\n    \"\"\"\r\n    interfaces = [get_interface(v) for v in values]\r\n\r\n    if len(set(interfaces) - {\"numpy\", \"autograd\"}) > 1:\r\n        # contains multiple non-autograd interfaces\r\n        raise ValueError(\"Tensors contain mixed types; cannot determine dispatch library\")\r\n\r\n    non_numpy_interfaces = set(interfaces) - {\"numpy\"}\r\n\r\n    if len(non_numpy_interfaces) > 1:\r\n        # contains autograd and another interface\r\n        warnings.warn(\r\n            f\"Contains tensors of types {non_numpy_interfaces}; dispatch will prioritize \"\r\n            \"TensorFlow and PyTorch over autograd. Consider replacing Autograd with vanilla NumPy.\",\r\n            UserWarning,\r\n        )\r\n\r\n    if \"tf\" in interfaces:\r\n        return TensorBox(values[interfaces.index(\"tf\")])\r\n\r\n    if \"torch\" in interfaces:\r\n        return TensorBox(values[interfaces.index(\"torch\")])\r\n\r\n    if \"autograd\" in interfaces:\r\n        return TensorBox(values[interfaces.index(\"autograd\")])\r\n\r\n    if \"jax\" in interfaces:\r\n        return TensorBox(values[interfaces.index(\"jax\")])\r\n\r\n    return TensorBox(values[interfaces.index(\"numpy\")])\r\n\r\n\r\ndef abs_(tensor):\r\n    \"\"\"Returns the element-wise absolute value.\r\n\r\n    Args:\r\n        tensor (tensor_like): input tensor\r\n\r\n    Returns:\r\n        tensor_like:\r\n\r\n    **Example**\r\n\r\n    >>> a = torch.tensor([1., -2.], requires_grad=True)\r\n    >>> abs(a)\r\n    tensor([1., 2.], grad_fn=<AbsBackward>)\r\n    \"\"\"\r\n    return TensorBox(tensor).abs(wrap_output=False)\r\n\r\n\r\ndef allequal(tensor1, tensor2, **kwargs):\r\n    \"\"\"Returns True if two tensors are element-wise equal along a given axis.\r\n\r\n    This function is equivalent to calling ``np.all(tensor1 == tensor2, **kwargs)``,\r\n    but allows for ``tensor1`` and ``tensor2`` to differ in type.\r\n\r\n    Args:\r\n        tensor1 (tensor_like): tensor to compare\r\n        tensor2 (tensor_like): tensor to compare\r\n        **kwargs: Accepts any keyword argument that is accepted by ``np.all``,\r\n            such as ``axis``, ``out``, and ``keepdims``. See the `NumPy documentation\r\n            <https://numpy.org/doc/stable/reference/generated/numpy.all.html>`__ for\r\n            more details.\r\n\r\n    Returns:\r\n        ndarray, bool: If ``axis=None``, a logical AND reduction is applied to all elements\r\n        and a boolean will be returned, indicating if all elements evaluate to True. Otherwise,\r\n        a boolean NumPy array will be returned.\r\n\r\n    **Example**\r\n\r\n    >>> a = torch.tensor([1, 2])\r\n    >>> b = np.array([1, 2])\r\n    >>> allequal(a, b)\r\n    True\r\n    \"\"\"\r\n    t1 = toarray(tensor1)\r\n    t2 = toarray(tensor2)\r\n    return np.all(t1 == t2, **kwargs)\r\n\r\n\r\ndef allclose(a, b, rtol=1e-05, atol=1e-08, **kwargs):\r\n    \"\"\"Wrapper around np.allclose, allowing tensors ``a`` and ``b``\r\n    to differ in type\"\"\"\r\n    t1 = toarray(a)\r\n    t2 = toarray(b)\r\n    return np.allclose(t1, t2, rtol=rtol, atol=atol, **kwargs)\r\n\r\n\r\nallclose.__doc__ = np.allclose.__doc__\r\n\r\n\r\ndef angle(tensor):\r\n    \"\"\"Returns the element-wise angle of a complex tensor.\r\n\r\n    Args:\r\n        tensor (tensor_like): input tensor\r\n\r\n    Returns:\r\n        tensor_like:\r\n\r\n    **Example**\r\n\r\n    >>> a = torch.tensor([1.0, 1.0j, 1+1j], requires_grad=True)\r\n    >>> angle(a)\r\n    tensor([0.0000, 1.5708, 0.7854], grad_fn=<AngleBackward>)\r\n    \"\"\"\r\n    return TensorBox(tensor).angle(wrap_output=False)\r\n\r\n\r\ndef arcsin(tensor):\r\n    \"\"\"Returns the element-wise inverse sine of the tensor\"\"\"\r\n    return TensorBox(tensor).arcsin(wrap_output=False)\r\n\r\n\r\ndef block_diag(values):\r\n    \"\"\"Combine a sequence of 2D tensors to form a block diagonal tensor.\r\n\r\n    Args:\r\n        values (Sequence[tensor_like]): Sequence of 2D arrays/tensors to form\r\n            the block diagonal tensor.\r\n\r\n    Returns:\r\n        tensor_like: the block diagonal tensor\r\n\r\n    **Example**\r\n\r\n    >>> t = [\r\n    ...     np.array([[1, 2], [3, 4]]),\r\n    ...     torch.tensor([[1, 2, 3], [-1, -6, -3]]),\r\n    ...     torch.tensor(5)\r\n    ... ]\r\n    >>> qml.math.block_diag(t)\r\n    tensor([[ 1,  2,  0,  0,  0,  0],\r\n            [ 3,  4,  0,  0,  0,  0],\r\n            [ 0,  0,  1,  2,  3,  0],\r\n            [ 0,  0, -1, -6, -3,  0],\r\n            [ 0,  0,  0,  0,  0,  5]])\r\n    \"\"\"\r\n    return _get_multi_tensorbox(values).block_diag(values, wrap_output=False)\r\n\r\n\r\ndef cast(tensor, dtype):\r\n    \"\"\"Casts the given tensor to a new type.\r\n\r\n    Args:\r\n        tensor (tensor_like): tensor to cast\r\n        dtype (str, np.dtype): Any supported NumPy dtype representation; this can be\r\n            a string (``\"float64\"``), a ``np.dtype`` object (``np.dtype(\"float64\")``), or\r\n            a dtype class (``np.float64``). If ``tensor`` is not a NumPy array, the\r\n            **equivalent** dtype in the dispatched framework is used.\r\n\r\n    Returns:\r\n        tensor_like: a tensor with the same shape and values as ``tensor`` and the\r\n        same dtype as ``dtype``\r\n\r\n    **Example**\r\n\r\n    We can use NumPy dtype specifiers:\r\n\r\n    >>> x = torch.tensor([1, 2])\r\n    >>> cast(x, np.float64)\r\n    tensor([1., 2.], dtype=torch.float64)\r\n\r\n    We can also use strings:\r\n\r\n    >>> x = tf.Variable([1, 2])\r\n    >>> cast(x, \"complex128\")\r\n    <tf.Tensor: shape=(2,), dtype=complex128, numpy=array([1.+0.j, 2.+0.j])>\r\n    \"\"\"\r\n    return TensorBox(tensor).cast(dtype, wrap_output=False)\r\n\r\n\r\ndef cast_like(tensor1, tensor2):\r\n    \"\"\"Casts a tensor to the same dtype as another.\r\n\r\n    Args:\r\n        tensor1 (tensor_like): tensor to cast\r\n        tensor2 (tensor_like): tensor with corresponding dtype to cast to\r\n\r\n    Returns:\r\n        tensor_like: a tensor with the same shape and values as ``tensor1`` and the\r\n        same dtype as ``tensor2``\r\n\r\n    **Example**\r\n\r\n    >>> x = torch.tensor([1, 2])\r\n    >>> y = torch.tensor([3., 4.])\r\n    >>> cast(x, y)\r\n    tensor([1., 2.])\r\n    \"\"\"\r\n    dtype = toarray(tensor2).dtype.type\r\n    return cast(tensor1, dtype)\r\n\r\n\r\ndef concatenate(values, axis=0):\r\n    \"\"\"Concatenate a sequence of tensors along the specified axis.\r\n\r\n    .. warning::\r\n\r\n        Tensors that are incompatible (such as Torch and TensorFlow tensors)\r\n        cannot both be present.\r\n\r\n    Args:\r\n        values (Sequence[tensor_like]): Sequence of tensor-like objects to\r\n            concatenate. The objects must have the same shape, except in the dimension corresponding\r\n            to axis (the first, by default).\r\n        axis (int): The axis along which the input tensors are concatenated. If axis is None,\r\n            tensors are flattened before use. Default is 0.\r\n\r\n    Returns:\r\n        tensor_like: The concatenated tensor.\r\n\r\n    **Example**\r\n\r\n    >>> x = tf.constant([0.6, 0.1, 0.6])\r\n    >>> y = tf.Variable([0.1, 0.2, 0.3])\r\n    >>> z = np.array([5., 8., 101.])\r\n    >>> concatenate([x, y, z])\r\n    TensorBox: <tf.Tensor: shape=(3, 3), dtype=float32, numpy=\r\n    array([6.00e-01, 1.00e-01, 6.00e-01, 1.00e-01, 2.00e-01, 3.00e-01, 5.00e+00, 8.00e+00, 1.01e+02], dtype=float32)>\r\n    \"\"\"\r\n    return _get_multi_tensorbox(values).concatenate(values, axis=axis, wrap_output=False)\r\n\r\n\r\ndef conj(tensor):\r\n    \"\"\"Conjugate a tensor. Negate the imaginary part of a complex value.\r\n\r\n    Args:\r\n        tensor (tensor_like): A tensor-like object to conjugate.\r\n\r\n    Returns:\r\n        tensor_like: The conjugated tensor.\r\n\r\n    **Example**\r\n\r\n    >>> x = tf.constant([0.6 + 0.1j, 0.1 - 0.3j, 0.6])\r\n    >>> conj(x)\r\n    <tf.Tensor: shape=(3,), dtype=complex64, numpy=array([6.00e-01 + 1.00e-1j, 1.00e-01 + 3.00e-1j, 6.00e-01 + 0.00j], dtype=complex64)>\r\n    \"\"\"\r\n    return TensorBox(tensor).conj(wrap_output=False)\r\n\r\n\r\ndef cov_matrix(prob, obs, wires=None, diag_approx=False):\r\n    \"\"\"Calculate the covariance matrix of a list of commuting observables, given\r\n    the joint probability distribution of the system in the shared eigenbasis.\r\n\r\n    .. note::\r\n        This method only works for **commuting observables.**\r\n        If the probability distribution is the result of a quantum circuit,\r\n        the quantum state must be rotated into the shared\r\n        eigenbasis of the list of observables before measurement.\r\n\r\n    Args:\r\n        prob (tensor_like): probability distribution\r\n        obs (list[.Observable]): a list of observables for which\r\n            to compute the covariance matrix for\r\n        diag_approx (bool): if True, return the diagonal approximation\r\n        wires (.Wires): The wire register of the system. If not provided,\r\n            it is assumed that the wires are labelled with consecutive integers.\r\n\r\n    Returns:\r\n        tensor_like: the covariance matrix of size ``(len(obs), len(obs))``\r\n\r\n    **Example**\r\n\r\n    Consider the following ansatz and observable list:\r\n\r\n    >>> obs_list = [qml.PauliX(0) @ qml.PauliZ(1), qml.PauliY(2)]\r\n    >>> ansatz = qml.templates.StronglyEntanglingLayers\r\n\r\n    We can construct a QNode to output the probability distribution in the shared eigenbasis of the\r\n    observables:\r\n\r\n    .. code-block:: python\r\n\r\n        dev = qml.device(\"default.qubit\", wires=3)\r\n\r\n        @qml.qnode(dev, interface=\"autograd\")\r\n        def circuit(weights):\r\n            ansatz(weights, wires=[0, 1, 2])\r\n            # rotate into the basis of the observables\r\n            for o in obs_list:\r\n                o.diagonalizing_gates()\r\n            return qml.probs(wires=[0, 1, 2])\r\n\r\n    We can now compute the covariance matrix:\r\n\r\n    >>> weights = qml.init.strong_ent_layers_normal(n_layers=2, n_wires=3)\r\n    >>> cov = qml.math.cov_matrix(circuit(weights), obs_list)\r\n    >>> cov\r\n    array([[0.98707611, 0.03665537],\r\n         [0.03665537, 0.99998377]])\r\n\r\n    Autodifferentiation is fully supported using all interfaces.\r\n    Here we use autograd:\r\n\r\n    >>> cost_fn = lambda weights: qml.math.cov_matrix(circuit(weights), obs_list)[0, 1]\r\n    >>> qml.grad(cost_fn)(weights)[0]\r\n    array([[[ 4.94240914e-17, -2.33786398e-01, -1.54193959e-01],\r\n            [-3.05414996e-17,  8.40072236e-04,  5.57884080e-04],\r\n            [ 3.01859411e-17,  8.60411436e-03,  6.15745204e-04]],\r\n           [[ 6.80309533e-04, -1.23162742e-03,  1.08729813e-03],\r\n            [-1.53863193e-01, -1.38700657e-02, -1.36243323e-01],\r\n            [-1.54665054e-01, -1.89018172e-02, -1.56415558e-01]]])\r\n    \"\"\"\r\n    variances = []\r\n\r\n    # diagonal variances\r\n    for i, o in enumerate(obs):\r\n        l = cast(o.eigvals, dtype=np.float64)\r\n        w = o.wires.labels if wires is None else wires.indices(o.wires)\r\n        p = marginal_prob(prob, w)\r\n\r\n        res = dot(l ** 2, p) - (dot(l, p)) ** 2\r\n        variances.append(res)\r\n\r\n    cov = diag(variances)\r\n\r\n    if diag_approx:\r\n        return cov\r\n\r\n    for i, j in itertools.combinations(range(len(obs)), r=2):\r\n        o1 = obs[i]\r\n        o2 = obs[j]\r\n\r\n        o1wires = o1.wires.labels if wires is None else wires.indices(o1.wires)\r\n        o2wires = o2.wires.labels if wires is None else wires.indices(o2.wires)\r\n        shared_wires = set(o1wires + o2wires)\r\n\r\n        l1 = cast(o1.eigvals, dtype=np.float64)\r\n        l2 = cast(o2.eigvals, dtype=np.float64)\r\n        l12 = cast(np.kron(l1, l2), dtype=np.float64)\r\n\r\n        p1 = marginal_prob(prob, o1wires)\r\n        p2 = marginal_prob(prob, o2wires)\r\n        p12 = marginal_prob(prob, shared_wires)\r\n\r\n        res = dot(l12, p12) - dot(l1, p1) * dot(l2, p2)\r\n\r\n        cov = scatter_element_add(cov, [i, j], res)\r\n        cov = scatter_element_add(cov, [j, i], res)\r\n\r\n    return cov\r\n\r\n\r\ndef convert_like(tensor1, tensor2):\r\n    \"\"\"Convert a tensor to the same type as another.\r\n\r\n    Args:\r\n        tensor1 (tensor_like): tensor to convert\r\n        tensor2 (tensor_like): tensor with corresponding type to convert to\r\n\r\n    Returns:\r\n        tensor_like: a tensor with the same shape, values, and dtype as ``tensor1`` and the\r\n        same type as ``tensor2``.\r\n\r\n    **Example**\r\n\r\n    >>> x = np.array([1, 2])\r\n    >>> y = tf.Variable([3, 4])\r\n    >>> cast(x, y)\r\n    <tf.Tensor: shape=(2,), dtype=int64, numpy=array([1, 2])>\r\n    \"\"\"\r\n    return TensorBox(tensor2).astensor(tensor1)\r\n\r\n\r\ndef diag(values, k=0):\r\n    \"\"\"Construct a diagonal tensor from a list of scalars.\r\n\r\n    Args:\r\n        values (tensor_like or Sequence[scalar]): sequence of numeric values that\r\n            make up the diagonal\r\n        k (int): The diagonal in question. ``k=0`` corresponds to the main diagonal.\r\n            Use ``k>0`` for diagonals above the main diagonal, and ``k<0`` for\r\n            diagonals below the main diagonal.\r\n\r\n    Returns:\r\n        tensor_like: the 2D diagonal tensor\r\n\r\n    **Example**\r\n\r\n    >>> x = [1., 2., tf.Variable(3.)]\r\n    >>> diag(x)\r\n    <tf.Tensor: shape=(3, 3), dtype=float32, numpy=\r\n    array([[1., 0., 0.],\r\n           [0., 2., 0.],\r\n           [0., 0., 3.]], dtype=float32)>\r\n    >>> y = tf.Variable([0.65, 0.2, 0.1])\r\n    >>> diag(y, k=-1)\r\n    <tf.Tensor: shape=(4, 4), dtype=float32, numpy=\r\n    array([[0.  , 0.  , 0.  , 0.  ],\r\n           [0.65, 0.  , 0.  , 0.  ],\r\n           [0.  , 0.2 , 0.  , 0.  ],\r\n           [0.  , 0.  , 0.1 , 0.  ]], dtype=float32)>\r\n    >>> z = torch.tensor([0.1, 0.2])\r\n    >>> qml.diag(z, k=1)\r\n    >>> qml.math.diag(z, k=1)\r\n    tensor([[0.0000, 0.1000, 0.0000],\r\n            [0.0000, 0.0000, 0.2000],\r\n            [0.0000, 0.0000, 0.0000]])\r\n    \"\"\"\r\n    if isinstance(values, Sequence):\r\n        return _get_multi_tensorbox(values).diag(values, k=k, wrap_output=False)\r\n\r\n    return TensorBox(values).diag(values, k=k, wrap_output=False)\r\n\r\n\r\ndef dot(tensor1, tensor2):\r\n    \"\"\"Returns the matrix or dot product of two tensors.\r\n\r\n    * If both tensors are 0-dimensional, elementwise multiplication\r\n      is performed and a 0-dimensional scalar returned.\r\n\r\n    * If both tensors are 1-dimensional, the dot product is returned.\r\n\r\n    * If the first array is 2-dimensional and the second array 1-dimensional,\r\n      the matrix-vector product is returned.\r\n\r\n    * If both tensors are 2-dimensional, the matrix product is returned.\r\n\r\n    * Finally, if the the first array is N-dimensional and the second array\r\n      M-dimensional, a sum product over the last dimension of the first array,\r\n      and the second-to-last dimension of the second array is returned.\r\n\r\n    Args:\r\n        tensor1 (tensor_like): input tensor\r\n        tensor2 (tensor_like): input tensor\r\n    \"\"\"\r\n    return _get_multi_tensorbox([tensor1, tensor2]).dot(tensor1, tensor2, wrap_output=False)\r\n\r\n\r\ndef expand_dims(tensor, axis):\r\n    \"\"\"Expand the shape of an array by adding a new dimension of size 1\r\n    at the specified axis location.\r\n\r\n    .. warning::\r\n\r\n        This function differs from ``np.expand_dims``.\r\n\r\n    Args:\r\n        tensor (tensor_like): tensor to expand\r\n        axis (int): location in the axes to place the new dimension\r\n\r\n    Returns:\r\n        tensor_like: a tensor with the expanded shape\r\n\r\n    **Example**\r\n\r\n    >>> x = tf.Variable([3, 4])\r\n    >>> expand_dims(x, axis=1)\r\n    <tf.Tensor: shape=(2, 1), dtype=int32, numpy=\r\n    array([[3],\r\n           [4]], dtype=int32)>\r\n    \"\"\"\r\n    return TensorBox(tensor).expand_dims(axis, wrap_output=False)\r\n\r\n\r\ndef flatten(tensor):\r\n    \"\"\"Flattens an N-dimensional tensor to a 1-dimensional tensor.\r\n\r\n    Args:\r\n        tensor (tensor_like): tensor to flatten\r\n\r\n    Returns:\r\n        tensor_like: the flattened tensor\r\n\r\n    **Example**\r\n\r\n    >>> x = tf.Variable([[1, 3], [2, 4]])\r\n    >>> flatten(x)\r\n    <tf.Tensor: shape=(4,), dtype=int32, numpy=array([1, 3, 2, 4], dtype=int32)>\r\n    \"\"\"\r\n    return reshape(tensor, (-1,))\r\n\r\n\r\ndef gather(tensor, indices):\r\n    \"\"\"Gather tensor values given a tuple of indices.\r\n\r\n    This is equivalent to the following NumPy fancy indexing:\r\n\r\n    ..code-block:: python\r\n\r\n        tensor[array(indices)]\r\n\r\n    Args:\r\n        tensor (tensor_like): tensor to gather from\r\n        indices (Sequence[int]): the indices of the values to extract\r\n\r\n    Returns:\r\n\r\n        tensor_like: the gathered tensor values\r\n\r\n    .. seealso::\r\n\r\n        :func:`~.take`\r\n    \"\"\"\r\n    return TensorBox(tensor).gather(np.array(indices), wrap_output=False)\r\n\r\n\r\ndef get_interface(tensor):\r\n    \"\"\"Returns the name of the package that any array/tensor manipulations\r\n    will dispatch to. The returned strings correspond to those used for PennyLane\r\n    :doc:`interfaces </introduction/interfaces>`.\r\n\r\n    Args:\r\n        tensor (tensor_like): tensor input\r\n\r\n    Returns:\r\n        str: name of the interface\r\n\r\n    **Example**\r\n\r\n    >>> x = torch.tensor([1., 2.])\r\n    >>> get_interface(x)\r\n    'torch'\r\n    >>> from pennylane import numpy as np\r\n    >>> x = np.array([4, 5], requires_grad=True)\r\n    >>> get_interface(x)\r\n    'autograd'\r\n    \"\"\"\r\n    return TensorBox(tensor).interface\r\n\r\n\r\ndef marginal_prob(prob, axis):\r\n    \"\"\"Compute the marginal probability given a joint probability distribution expressed as a tensor.\r\n    Each random variable corresponds to a dimension.\r\n\r\n    If the distribution arises from a quantum circuit measured in computational basis, each dimension\r\n    corresponds to a wire. For example, for a 2-qubit quantum circuit `prob[0, 1]` is the probability of measuring the\r\n    first qubit in state 0 and the second in state 1.\r\n\r\n    Args:\r\n        prob (tensor_like): 1D tensor of probabilities. This tensor should of size\r\n            ``(2**N,)`` for some integer value ``N``.\r\n        axis (list[int]): the axis for which to calculate the marginal\r\n            probability distribution\r\n\r\n    Returns:\r\n        tensor_like: the marginal probabilities, of\r\n        size ``(2**len(axis),)``\r\n\r\n    **Example**\r\n\r\n    >>> x = tf.Variable([1, 0, 0, 1.], dtype=tf.float64) / np.sqrt(2)\r\n    >>> marginal_prob(x, axis=[0, 1])\r\n    <tf.Tensor: shape=(4,), dtype=float64, numpy=array([0.70710678, 0.        , 0.        , 0.70710678])>\r\n    >>> marginal_prob(x, axis=[0])\r\n    <tf.Tensor: shape=(2,), dtype=float64, numpy=array([0.70710678, 0.70710678])>\r\n    \"\"\"\r\n    prob = flatten(prob)\r\n    num_wires = int(np.log2(len(prob)))\r\n\r\n    if num_wires == len(axis):\r\n        return prob\r\n\r\n    inactive_wires = tuple(set(range(num_wires)) - set(axis))\r\n    prob = reshape(prob, [2] * num_wires)\r\n    prob = sum_(prob, axis=inactive_wires)\r\n    return flatten(prob)\r\n\r\n\r\ndef toarray(tensor):\r\n    \"\"\"Returns the tensor as a NumPy ``ndarray``. No copying\r\n    is performed; the tensor and the returned array share the\r\n    same storage.\r\n\r\n    Args:\r\n        tensor (tensor_like): input tensor\r\n\r\n    Returns:\r\n        array: a ``ndarray`` view into the same data\r\n\r\n    **Example**\r\n\r\n    >>> x = torch.tensor([1., 2.])\r\n    >>> toarray(x)\r\n    array([1, 2])\r\n    \"\"\"\r\n    return TensorBox(tensor).numpy()\r\n\r\n\r\ndef ones_like(tensor, dtype=None):\r\n    \"\"\"Returns a tensor of all ones with the same shape and dtype\r\n    as the input tensor.\r\n\r\n    Args:\r\n        tensor (tensor_like): input tensor\r\n        dtype (str, np.dtype): The desired output datatype of the array. If not provided, the dtype of\r\n\r\n            ``tensor`` is used. This argument can be any supported NumPy dtype representation, including\r\n            a string (``\"float64\"``), a ``np.dtype`` object (``np.dtype(\"float64\")``), or\r\n            a dtype class (``np.float64``). If ``tensor`` is not a NumPy array, the\r\n            **equivalent** dtype in the dispatched framework is used.\r\n\r\n    Returns:\r\n        tensor_like: an all-ones tensor with the same shape and\r\n        size as ``tensor``\r\n\r\n    **Example**\r\n\r\n    >>> x = torch.tensor([1., 2.])\r\n    >>> ones_like(x)\r\n    tensor([1, 1])\r\n    >>> y = tf.Variable([[0], [5]])\r\n    >>> ones_like(y, dtype=np.complex128)\r\n    <tf.Tensor: shape=(2, 1), dtype=complex128, numpy=\r\n    array([[1.+0.j],\r\n           [1.+0.j]])>\r\n    \"\"\"\r\n    if dtype is not None:\r\n        return TensorBox(tensor).ones_like().cast(dtype, wrap_output=False)\r\n\r\n    return TensorBox(tensor).ones_like(wrap_output=False)\r\n\r\n\r\ndef reshape(tensor, shape):  # pylint: disable=redefined-outer-name\r\n    \"\"\"Gives a new shape to a tensor without changing its data.\r\n\r\n    Args:\r\n        tensor (tensor_like): input tensor\r\n        shape (tuple[int]): The new shape. The special value of -1 indicates\r\n            that the size of that dimension is computed so that the total size\r\n            remains constant. A dimension of -1 can only be specified once.\r\n\r\n    Returns:\r\n        tensor_like: a new view into the input tensor with\r\n        shape ``shape``\r\n\r\n    **Example**\r\n\r\n    >>> a = tf.range(4.)\r\n    >>> reshape(a, (2, 2))\r\n    <tf.Tensor: shape=(2, 2), dtype=float32, numpy=\r\n    array([[0., 1.],\r\n           [2., 3.]], dtype=float32)>\r\n    >>> b = torch.tensor([[0, 1], [2, 3]])\r\n    >>> torch.reshape(b, (-1,))\r\n    tensor([0, 1, 2, 3])\r\n    \"\"\"\r\n    return TensorBox(tensor).reshape(shape, wrap_output=False)\r\n\r\n\r\ndef requires_grad(tensor):\r\n    \"\"\"Returns True if the tensor is considered trainable.\r\n\r\n    .. warning::\r\n\r\n        The implemetation depends on the contained tensor type, and\r\n        may be context dependent.\r\n\r\n        For example, Torch tensors and PennyLane tensors track trainability\r\n        as a property of the tensor itself. TensorFlow, on the other hand,\r\n\r\n        only tracks trainability if being watched by a gradient tape.\r\n\r\n    Args:\r\n        tensor (tensor_like): input tensor\r\n\r\n    **Example**\r\n\r\n    Calling this function on a PennyLane NumPy array:\r\n\r\n    >>> x = np.array([1., 5.], requires_grad=True)\r\n    >>> requires_grad(x)\r\n    True\r\n    >>> x.requires_grad = False\r\n    >>> requires_grad(x)\r\n    False\r\n\r\n    PyTorch has similar behaviour.\r\n\r\n    With TensorFlow, the output is dependent on whether the tensor\r\n    is currently being watched by a gradient tape:\r\n\r\n    >>> x = tf.Variable([0.6, 0.1])\r\n    >>> requires_grad(x)\r\n    False\r\n    >>> with tf.GradientTape() as tape:\r\n    ...     print(requires_grad(x))\r\n    True\r\n\r\n    While TensorFlow constants are by default not trainable, they can be\r\n    manually watched by the gradient tape:\r\n\r\n    >>> x = tf.constant([0.6, 0.1])\r\n    >>> with tf.GradientTape() as tape:\r\n    ...     print(requires_grad(x))\r\n    False\r\n    >>> with tf.GradientTape() as tape:\r\n    ...     tape.watch([x])\r\n    ...     print(requires_grad(x))\r\n    True\r\n    \"\"\"\r\n    return TensorBox(tensor).requires_grad\r\n\r\n\r\ndef scatter_element_add(tensor, index, value):\r\n    \"\"\"Adds a scalar value to a specific index of a tensor.\r\n\r\n    This is a pure equivalent of ``tensor[index] += value``.\r\n\r\n    Args:\r\n        tensor (tensor_like): the input tensor to be updated\r\n        index (tuple[int]): the index of the input tensor to update\r\n        value (scalar): the scalar value to add to the tensor element\r\n\r\n    Returns:\r\n        tensor_like: the output tensor\r\n\r\n    **Example**\r\n\r\n    >>> x = torch.ones((2, 3))\r\n    >>> qml.math.scatter_element_add(x, [1, 2], 3)\r\n    tensor([[1., 1., 1.],\r\n            [1., 1., 4.]])\r\n    \"\"\"\r\n    value = convert_like(value, tensor)\r\n    return TensorBox(tensor).scatter_element_add(index, value, wrap_output=False)\r\n\r\n\r\ndef shape(tensor):\r\n    \"\"\"Returns the shape of the tensor.\r\n\r\n    Args:\r\n        tensor (tensor_like): input tensor\r\n\r\n    Returns:\r\n        tuple[int]: shape of the tensor\r\n\r\n    **Example**\r\n\r\n    >>> x = tf.constant([[0.6, 0.1, 0.6], [1., 2., 3.]])\r\n    >>> shape(x)\r\n    (2, 3)\r\n    \"\"\"\r\n    return TensorBox(tensor).shape\r\n\r\n\r\ndef sqrt(tensor):\r\n    \"\"\"Returns the element-wise square root.\r\n\r\n    Args:\r\n        tensor (tensor_like): input tensor\r\n\r\n    Returns:\r\n        tensor_like:\r\n\r\n    **Example**\r\n\r\n    >>> a = torch.tensor([4., 9.], requires_grad=True)\r\n    >>> sqrt(a)\r\n    tensor([2., 3.], grad_fn=<SqrtBackward>)\r\n    \"\"\"\r\n    return TensorBox(tensor).sqrt(wrap_output=False)\r\n\r\n\r\ndef stack(values, axis=0):\r\n    \"\"\"Stack a sequence of tensors along the specified axis.\r\n\r\n    .. warning::\r\n\r\n        Tensors that are incompatible (such as Torch and TensorFlow tensors)\r\n        cannot both be present.\r\n\r\n    Args:\r\n        values (Sequence[tensor_like]): Sequence of tensor-like objects to\r\n            stack. Each object in the sequence must have the same size in the given axis.\r\n        axis (int): The axis along which the input tensors are stacked. ``axis=0`` corresponds\r\n            to vertical stacking.\r\n\r\n    Returns:\r\n        tensor_like: The stacked array. The stacked array will have one additional dimension\r\n        compared to the unstacked tensors.\r\n\r\n    **Example**\r\n\r\n    >>> x = tf.constant([0.6, 0.1, 0.6])\r\n    >>> y = tf.Variable([0.1, 0.2, 0.3])\r\n    >>> z = np.array([5., 8., 101.])\r\n    >>> stack([x, y, z])\r\n    <tf.Tensor: shape=(3, 3), dtype=float32, numpy=\r\n    array([[6.00e-01, 1.00e-01, 6.00e-01],\r\n           [1.00e-01, 2.00e-01, 3.00e-01],\r\n           [5.00e+00, 8.00e+00, 1.01e+02]], dtype=float32)>\r\n    \"\"\"\r\n    return _get_multi_tensorbox(values).stack(values, axis=axis, wrap_output=False)\r\n\r\n\r\ndef squeeze(tensor):\r\n    \"\"\"Remove single-dimensional entries from the shape of an array.\r\n\r\n    Args:\r\n        tensor (tensor_like): A tensor-like object.\r\n\r\n    Returns:\r\n        The input array, but with all or a subset of the dimensions of length 1 removed.\r\n        This is always a itself or a view into a. Note that if all axes are squeezed,\r\n        the result is a 0d array and not a scalar.\r\n\r\n    **Example**\r\n\r\n    >>> x = torch.ones((2, 1, 3, 4, 1))\r\n    >>> y = squeeze(x)\r\n    >>> y.shape\r\n    (2, 3, 4)\r\n    \"\"\"\r\n    return TensorBox(tensor).squeeze(wrap_output=False)\r\n\r\n\r\ndef sum_(tensor, axis=None, keepdims=False):\r\n    \"\"\"TensorBox: Returns the sum of the tensor elements across the specified dimensions.\r\n\r\n    Args:\r\n        tensor (tensor_like): input tensor\r\n        axis (int or tuple[int]): The axis or axes along which to perform the sum.\r\n            If not specified, all elements of the tensor across all dimensions\r\n            will be summed, returning a tensor.\r\n        keepdims (bool): If True, retains all summed dimensions.\r\n\r\n    Returns:\r\n        tensor_like: The tensor with specified dimensions summed over. Note that\r\n        if all elements are summed, then a 0-dimensional tensor is returned, rather\r\n        than a Python scalar.\r\n\r\n    **Example**\r\n\r\n    Summing over all dimensions:\r\n\r\n    >>> x = tf.Variable([[1., 2.], [3., 4.]])\r\n    >>> sum(x)\r\n    <tf.Tensor: shape=(), dtype=float32, numpy=10.0>\r\n\r\n    Summing over specified dimensions:\r\n\r\n    >>> x = np.array([[[1, 1], [5, 3]], [[1, 4], [-6, -1]]])\r\n    >>> x.shape\r\n    (2, 2, 2)\r\n    >>> sum(x, axis=(0, 2))\r\n    tensor([7, 1], requires_grad=True)\r\n    >>> sum(x, axis=(0, 2), keepdims=True)\r\n    tensor([[[7],\r\n             [1]]], requires_grad=True)\r\n    \"\"\"\r\n    return TensorBox(tensor).sum(axis=axis, keepdims=keepdims, wrap_output=False)\r\n\r\n\r\ndef T(tensor):\r\n    \"\"\"Returns the transpose of the tensor by reversing the order\r\n    of the axes. For a 2D tensor, this corresponds to the matrix transpose.\r\n\r\n    Args:\r\n        tensor (tensor_like): input tensor\r\n\r\n    Returns:\r\n        tensor_like: input tensor with axes reversed\r\n\r\n    **Example**\r\n\r\n    >>> x = tf.Variable([[1, 2], [3, 4]])\r\n    >>> T(x)\r\n    <tf.Tensor: shape=(2, 2), dtype=int32, numpy=\r\n    array([[1, 3],\r\n           [2, 4]], dtype=int32)>\r\n    \"\"\"\r\n    return TensorBox(tensor).T(wrap_output=False)\r\n\r\n\r\ndef take(tensor, indices, axis=None):\r\n    \"\"\"Gather elements from a tensor.\r\n\r\n    Note that ``take(indices, axis=3)`` is equivalent\r\n    to ``tensor[:, :, :, indices, ...]`` for frameworks that support\r\n    NumPy-like fancy indexing.\r\n\r\n    This function is roughly equivalent to ``np.take`` and ``tf.gather``.\r\n    In the case of a 1-dimensional set of indices, it is roughly equivalent\r\n    to ``torch.index_select``, but deviates for multi-dimensional indices.\r\n\r\n    Args:\r\n        tensor (tensor_like): input tensor\r\n        indices (Sequence[int]): the indices of the values to extract\r\n        axis: The axis over which to select the values. If not provided,\r\n            the tensor is flattened before value extraction.\r\n\r\n    **Example**\r\n\r\n    >>> x = torch.tensor([[1, 2], [3, 4]])\r\n    >>> take(y, indices=[[0, 0], [1, 0]], axis=1)\r\n    tensor([[[1, 1],\r\n             [2, 1]],\r\n\r\n            [[3, 3],\r\n             [4, 3]]])\r\n    \"\"\"\r\n    return TensorBox(tensor).take(indices, axis=axis, wrap_output=False)\r\n\r\n\r\ndef where(condition, x, y):\r\n    \"\"\"Returns elements chosen from x or y depending on a boolean tensor condition.\r\n\r\n    The input tensors ``condition``, ``x``, and ``y`` must all be broadcastable to the same shape.\r\n\r\n    Args:\r\n        condition (tensor_like[bool]): A boolean tensor. Where True, elements from\r\n            ``x`` will be chosen, otherwise ``y``.\r\n        x (tensor_like): values from which to choose if the condition evaluates to True\r\n        y (tensor_like): values from which to choose if the condition evaluates to False\r\n\r\n    Returns:\r\n        tensor_like: A tensor with elements from ``x`` where the condition is True, and\r\n        ``y`` otherwise. The output tensor has the same shape as the input tensors.\r\n\r\n    **Example**\r\n\r\n    >>> a = torch.tensor([0.6, 0.23, 0.7, 1.5, 1.7], requires_grad=True)\r\n    >>> b = torch.tensor([-1., -2., -3., -4., -5.], requires_grad=True)\r\n    >>> math.where(a < 1, a, b)\r\n    tensor([ 0.6000,  0.2300,  0.7000, -4.0000, -5.0000], grad_fn=<SWhereBackward>)\r\n    \"\"\"\r\n    return _get_multi_tensorbox([x, y]).where(condition, x, y, wrap_output=False)\r\n", "meta": {"hexsha": "c7b18fc736eb01bad5de85df2d3eb8e6dd0a57a2", "size": 31273, "ext": "py", "lang": "Python", "max_stars_repo_path": "pennylane/math/fn.py", "max_stars_repo_name": "nahumsa/pennylane", "max_stars_repo_head_hexsha": "f92c36ea632f450908de915fb01ebb314a68e3fa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pennylane/math/fn.py", "max_issues_repo_name": "nahumsa/pennylane", "max_issues_repo_head_hexsha": "f92c36ea632f450908de915fb01ebb314a68e3fa", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-27T05:36:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-27T05:36:41.000Z", "max_forks_repo_path": "pennylane/math/fn.py", "max_forks_repo_name": "nahumsa/pennylane", "max_forks_repo_head_hexsha": "f92c36ea632f450908de915fb01ebb314a68e3fa", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-11T11:45:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-11T11:45:14.000Z", "avg_line_length": 32.1738683128, "max_line_length": 137, "alphanum_fraction": 0.6018930067, "include": true, "reason": "import numpy", "num_tokens": 8187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1935878186402452}}
{"text": "# -*- coding: utf-8 -*-\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n#\n# LICENSE\n#\n# Copyright (C) 2010-2018 GEM Foundation, G. Weatherill, M. Pagani,\n# D. Monelli.\n#\n# The Hazard Modeller's Toolkit is free software: you can redistribute\n# it and/or modify it under the terms of the GNU Affero General Public\n# License as published by the Free Software Foundation, either version\n# 3 of the License, or (at your option) any later version.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>\n#\n# DISCLAIMER\n#\n# The software Hazard Modeller's Toolkit (openquake.hmtk) provided herein\n# is released as a prototype implementation on behalf of\n# scientists and engineers working within the GEM Foundation (Global\n# Earthquake Model).\n#\n# It is distributed for the purpose of open collaboration and in the\n# hope that it will be useful to the scientific, engineering, disaster\n# risk and software design communities.\n#\n# The software is NOT distributed as part of GEM's OpenQuake suite\n# (https://www.globalquakemodel.org/tools-products) and must be considered as a\n# separate entity. The software provided herein is designed and implemented\n# by scientific staff. It is not developed to the design standards, nor\n# subject to same level of critical review by professional software\n# developers, as GEM's OpenQuake software suite.\n#\n# Feedback and contribution to the software is welcome, and can be\n# directed to the hazard scientific staff of the GEM Model Facility\n# (hazard@globalquakemodel.org).\n#\n# The Hazard Modeller's Toolkit (openquake.hmtk) is therefore distributed\n# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n# for more details.\n#\n# The GEM Foundation, and the authors of the software, assume no\n# liability for use of the software.\n\n#!/usr/bin/env python\n\n'''\nModule openquake.hmtk.plotting.seismicity.completeness.simple_completeness is a graphical\nfunction for estimating the completeness period of magnitude intervals\nby plotting the cumulative rate of events with time in each interval\n'''\n\nimport numpy as np\nimport pylab\nimport matplotlib.pyplot as plt\nfrom openquake.hmtk.seismicity.completeness.base import (\n    BaseCatalogueCompleteness)\n\n\nclass SimpleCumulativeRate(BaseCatalogueCompleteness):\n    '''\n    Class to define the temporal variation in completess using simple\n    changes in cumulative rates in individual completeness bins\n    '''\n\n    def completeness(self, catalogue, config, saveplot=False, filetype='png',\n                     timeout=120):\n        '''\n        :param catalogue:\n            Earthquake catalogue as instance of\n            :class:`openquake.hmtk.seismicity.catalogue.Catalogue`\n        :param dict config:\n            Configuration parameters of the algorithm, containing the\n            following information:\n            'magnitude_bin' Size of magnitude bin (non-negative float)\n            'time_bin' Size (in dec. years) of the time window (non-negative\n            float)\n            'increment_lock' Boolean to indicate whether to ensure\n            completeness magnitudes always decrease with more\n            recent bins\n        :returns:\n            2-column table indicating year of completeness and corresponding\n            magnitude numpy.ndarray\n        '''\n        if saveplot and not isinstance(saveplot, str):\n            raise ValueError('To save the figures enter a filename: ')\n\n        # Get magntitude bins\n        magnitude_bins = self._get_magnitudes_from_spacing(\n            catalogue.data['magnitude'],\n            config['magnitude_bin'])\n        dec_time = catalogue.get_decimal_time()\n        completeness_table = np.zeros([len(magnitude_bins) - 1, 2],\n                                      dtype=float)\n        min_year = float(np.min(catalogue.data['year']))\n        max_year = float(np.max(catalogue.data['year'])) + 1.0\n        has_completeness = np.zeros(len(magnitude_bins) - 1, dtype=bool)\n        for iloc in range(0, len(magnitude_bins) - 1):\n            lower_mag = magnitude_bins[iloc]\n            upper_mag = magnitude_bins[iloc + 1]\n            idx = np.logical_and(catalogue.data['magnitude'] >= lower_mag,\n                                 catalogue.data['magnitude'] < upper_mag)\n            cumvals = np.cumsum(np.ones(np.sum(idx)))\n            plt.plot(dec_time[idx], cumvals, '.')\n            plt.xlim(min_year, max_year + 5)\n            title_string = 'Magnitude %5.2f to %5.2f' % (lower_mag, upper_mag)\n            plt.title(title_string)\n            pts = pylab.ginput(1, timeout=timeout)[0]\n            if pts[0] <= max_year:\n                 # Magnitude bin has no completeness!\n                has_completeness[iloc] = True\n            completeness_table[iloc, 0] = np.floor(pts[0])\n            completeness_table[iloc, 1] = magnitude_bins[iloc]\n            print(completeness_table[iloc, :], has_completeness[iloc])\n            if config['increment_lock'] and (iloc > 0) and \\\n                    (completeness_table[iloc, 0] > completeness_table[iloc - 1, 0]):\n                completeness_table[iloc, 0] = \\\n                    completeness_table[iloc - 1, 0]\n            # Add marker line to indicate completeness point\n            marker_line = np.array([\n                [0., completeness_table[iloc, 0]],\n                [cumvals[-1], completeness_table[iloc, 0]]])\n            plt.plot(marker_line[:, 0], marker_line[:, 1], 'r-')\n            if saveplot:\n                filename = saveplot + '_' + ('%5.2f' % lower_mag) + (\n                    '%5.2f' % upper_mag) + '.' + filetype\n                plt.savefig(filename, format=filetype)\n            plt.close()\n        return completeness_table[has_completeness, :]\n\n    def _get_magnitudes_from_spacing(self, magnitudes, delta_m):\n        '''If a single magnitude spacing is input then create the bins\n\n        :param numpy.ndarray magnitudes:\n            Vector of earthquake magnitudes\n\n        :param float delta_m:\n            Magnitude bin width\n\n        :returns: Vector of magnitude bin edges (numpy.ndarray)\n        '''\n        min_mag = np.min(magnitudes)\n        max_mag = np.max(magnitudes)\n        if (max_mag - min_mag) < delta_m:\n            raise ValueError('Bin width greater than magnitude range!')\n        mag_bins = np.arange(np.floor(min_mag), np.ceil(max_mag), delta_m)\n        # Check to see if there are magnitudes in lower and upper bins\n        is_mag = np.logical_and(mag_bins - max_mag < delta_m,\n                                min_mag - mag_bins < delta_m)\n        mag_bins = mag_bins[is_mag]\n        return mag_bins\n", "meta": {"hexsha": "7891d5b7e3762547f9dcb68676c2302e7a63be58", "size": 6712, "ext": "py", "lang": "Python", "max_stars_repo_path": "openquake/hmtk/plotting/seismicity/completeness/cumulative_rate_analysis.py", "max_stars_repo_name": "gfzriesgos/shakyground-lfs", "max_stars_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-01T00:28:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-01T00:28:24.000Z", "max_issues_repo_path": "openquake/hmtk/plotting/seismicity/completeness/cumulative_rate_analysis.py", "max_issues_repo_name": "gfzriesgos/shakyground-lfs", "max_issues_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-08-31T14:14:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-11T12:53:13.000Z", "max_forks_repo_path": "openquake/hmtk/plotting/seismicity/completeness/cumulative_rate_analysis.py", "max_forks_repo_name": "gfzriesgos/shakyground-lfs", "max_forks_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-08-31T14:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-17T10:06:02.000Z", "avg_line_length": 43.3032258065, "max_line_length": 89, "alphanum_fraction": 0.6561382598, "include": true, "reason": "import numpy", "num_tokens": 1504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1935878186402452}}
{"text": "\"\"\"The WaveBlocks Project\n\nThis file contains the basic interface for general wavepackets.\n\n@author: R. Bourquin\n@copyright: Copyright (C) 2011 R. Bourquin\n@license: Modified BSD License\n\"\"\"\n\nfrom numpy import vstack, vsplit, cumsum, zeros, complexfloating\n\n\nclass Wavepacket:\n    r\"\"\"\n    This class is primarily an abstract interface to wavepackets in general.\n    But it implemets some methods for both the homogeneous and inhomogeneous Hagedorn\n    wavepackets.\n    \"\"\"\n\n    def __init__(self, parameters):\n        r\"\"\"\n        Initialize the ``Wavepacket`` object that represents :math:`|\\Psi\\rangle`.\n\n        :raise NotImplementedError: Abstract interface.\n        \"\"\"\n        raise NotImplementedError(\"'Wavepacket' is an abstract interface.\")\n\n\n    def __str__(self):\n        r\"\"\"\n        :return: A string describing the wavepacket.\n        :raise NotImplementedError: Abstract interface.\n        \"\"\"\n        raise NotImplementedError(\"'Wavepacket' is an abstract interface.\")\n\n\n    def _resize_coefficient_vector(self, component):\n        r\"\"\"\n        Adapt the coefficient vector for a given component to a new size.\n        \"\"\"\n        oldsize = self.coefficients[component].shape[0]\n        newsize = self.basis_size[component]\n\n        if oldsize == newsize:\n            return\n        elif oldsize < newsize:\n            # Append some zeros\n            z = zeros((newsize - oldsize, 1), dtype=complexfloating)\n            self.coefficients[component] = vstack([self.coefficients[component], z])\n        elif oldsize > newsize:\n            # Cut off the last part\n            self.coefficients[component] = self.coefficients[component][0:newsize]\n\n\n    def clone(self):\n        raise NotImplementedError(\"'Wavepacket' is an abstract interface.\")\n\n\n    def gen_id(self):\n        r\"\"\"\n        Generate an (unique) ID per wavepacket instance.\n        \"\"\"\n        #TODO: Better id generating function!\n        self._id = id(self)\n\n\n    def get_id(self):\n        r\"\"\"\n        Return the packet ID of this wavepacket instance. The ID may be used for storing packets in associative lists.\n        \"\"\"\n        if not hasattr(self, \"_id\"):\n            self.gen_id()\n\n        return self._id\n\n\n    def set_id(self, anid):\n        r\"\"\"\n        Manually set an ID for the current wavepacket instance.\n        \"\"\"\n        assert(type(anid) is int)\n        self._id = anid\n\n\n    def get_number_components(self):\n        r\"\"\"\n        :return: The number :math:`N` of components the wavepacket :math:`\\Psi` has.\n        \"\"\"\n        return self.number_components\n\n\n    def get_basis_size(self, component=None):\n        r\"\"\"\n        :return: The size of the basis, i.e. the number :math:`K` of :math:`{\\phi_k}_{k=1}^K`.\n        \"\"\"\n        if component is not None:\n            return self.basis_size[component]\n        else:\n            return tuple(self.basis_size)\n\n\n    def set_basis_size(self, basis_size, component=None):\n        r\"\"\"\n        Set the size of the basis of a given component or all components.\n\n        :param basis_size: An single positive integer or a list of :math:`N` positive integers.\n        :param component: The component for which we want to set the basis size.\n                          Default is ``None`` which means 'all'.\n        \"\"\"\n        if component is not None:\n            # Check for valid input basis size\n            if not component in range(self.number_components):\n                raise ValueError(\"Invalid component index \" + str(component))\n\n            if basis_size < 2:\n                raise ValueError(\"Basis size has to be a positive integer >=2.\")\n\n            # Set the new basis size for the given component\n            self.basis_size[component] = basis_size\n            # And adapt the coefficient vectors\n            self._resize_coefficient_vector(component)\n\n        else:\n            # Check for valid input basis size\n            if any([bs < 2 for bs in basis_size]):\n                raise ValueError(\"Basis size has to be a positive integer >=2.\")\n\n            if not len(basis_size) == self.number_components:\n                raise ValueError(\"Number of value(s) for basis size(s) does not match.\")\n\n            # Set the new basis size for all components\n            self.basis_size = [ bs for bs in basis_size ]\n            # And adapt the coefficient vectors\n            for index in xrange(self.number_components):\n                self._resize_coefficient_vector(index)\n\n\n    def set_coefficients(self, values, component=None):\n        r\"\"\"\n        Update the coefficients :math:`c` of :math:`\\Psi`.\n\n        :param values: The new values of the coefficients :math:`c^i` of :math:`\\Phi_i`.\n        :param component: The index :math:`i` of the component we want to update with new coefficients.\n        :raise ValueError: For invalid indices :math:`i`.\n\n        .. note:: This function can either set new coefficients for a single component :math:`\\Phi_i`\n                  only if the ``component`` attribute is set or for all components simultaneously if\n                  ``values`` is a list of arrays.\n        \"\"\"\n        if component is None:\n            for index, value in enumerate(values):\n                if index > self.number_components-1:\n                    raise ValueError(\"There is no component with index \"+str(index)+\".\")\n\n                self.coefficients[index] = value.copy().reshape((self.basis_size[index],1))\n        else:\n            if component > self.number_components-1:\n                raise ValueError(\"There is no component with index \"+str(component)+\".\")\n\n            self.coefficients[component] = values.copy().reshape((self.basis_size[component],1))\n\n\n    def set_coefficient(self, component, index, value):\n        r\"\"\"\n        Set a single coefficient :math:`c^i_k` of the specified component :math:`\\Phi_i` of :math:`|\\Psi\\rangle`.\n\n        :param component: The index :math:`i` of the component :math:`\\Phi_i` we want to update.\n        :param index: The index :math:`k` of the coefficient :math:`c^i_k` we want to update.\n        :param value: The new value of the coefficient :math:`c^i_k`.\n        :raise ValueError: For invalid indices :math:`i` or :math:`k`.\n        \"\"\"\n        if component > self.number_components-1:\n            raise ValueError(\"There is no component with index \"+str(component)+\".\")\n        if index > self.basis_size[component]-1:\n            raise ValueError(\"There is no basis function with index \"+str(index)+\".\")\n\n        self.coefficients[component][index] = value\n\n\n    def get_coefficients(self, component=None):\n        r\"\"\"\n        Returns the coefficients :math:`c^i` for some components :math:`\\Phi_i` of :math:`|\\Psi\\rangle`.\n\n        :param component: The index :math:`i` of the coefficients :math:`c^i` we want to get.\n        :return: The coefficients :math:`c^i` either for all components :math:`\\Phi_i`\n                 or for a specified one.\n        \"\"\"\n        if component is None:\n            return [ item.copy() for item in self.coefficients ]\n        else:\n            return self.coefficients[component].copy()\n\n\n    def get_coefficient_vector(self):\n        r\"\"\"\n        :return: The coefficients :math:`c^i` of all components :math:`\\Phi_i` as a single long column vector.\n        \"\"\"\n        return vstack(self.coefficients)\n\n\n    def set_coefficient_vector(self, vector):\n        r\"\"\"\n        Set the coefficients for all components :math:`\\Phi_i` simultaneously.\n\n        :param vector: The coefficients of all components as a single long column vector.\n\n        .. note:: This function does *NOT* copy the input data! This is for efficiency as this\n                  routine is used in the innermost loops.\n        \"\"\"\n        # Compute the partition of the block-vector from the basis sizes\n        partition = cumsum(self.basis_size)[:-1]\n\n        # Split the block-vector with the given partition and assign\n        self.coefficients = vsplit(vector, partition)\n\n\n    def get_parameters(self, component=None, aslist=False):\n        r\"\"\"\n        Get the Hagedorn parameters :math:`{\\Pi}` of the wavepacket :math:`\\Psi`.\n\n        :raise NotImplementedError: Abstract interface.\n        \"\"\"\n        raise NotImplementedError(\"'Wavepacket' is an abstract interface.\")\n\n\n    def set_parameters(self, parameters, component=None):\n        r\"\"\"\n        Set the Hagedorn parameters :math:`{\\Pi}` of the wavepacket :math:`\\Psi`.\n\n        :raise NotImplementedError: Abstract interface.\n        \"\"\"\n        raise NotImplementedError(\"'Wavepacket' is an abstract interface.\")\n\n\n    def evaluate_basis_at(self, nodes, component, prefactor=False):\n        r\"\"\"\n        Evaluate the basis functions :math:`\\phi_k` recursively at the given nodes :math:`\\gamma`.\n\n        :raise NotImplementedError: Abstract interface.\n        \"\"\"\n        raise NotImplementedError(\"'Wavepacket' is an abstract interface.\")\n\n\n    def evaluate_at(self, nodes, component=None, prefactor=False):\n        r\"\"\"\n        Evaluete the wavepacket :math:`\\Psi` at the given nodes :math:`\\gamma`.\n\n        :raise NotImplementedError: Abstract interface.\n        \"\"\"\n        raise NotImplementedError(\"'Wavepacket' is an abstract interface.\")\n\n\n    def get_norm(self, component=None, summed=False):\n        r\"\"\"\n        Calculate the :math:`L^2` norm of the wavepacket :math:`|\\Psi\\rangle`.\n\n        :raise NotImplementedError: Abstract interface.\n        \"\"\"\n        raise NotImplementedError(\"'Wavepacket' is an abstract interface.\")\n\n\n    def potential_energy(self, potential, summed=False):\n        r\"\"\"\n        Calculate the potential energy :math:`\\langle\\Psi|V|\\Psi\\rangle ` of the wavepacket componentwise.\n\n        :raise NotImplementedError: Abstract interface.\n        \"\"\"\n        raise NotImplementedError(\"'Wavepacket' is an abstract interface.\")\n\n\n    def kinetic_energy(self, summed=False):\n        r\"\"\"\n        Calculate the kinetic energy :math:`\\langle\\Psi|T|\\Psi\\rangle ` of the wavepacket componentwise.\n\n        :raise NotImplementedError: Abstract interface.\n        \"\"\"\n        raise NotImplementedError(\"'Wavepacket' is an abstract interface.\")\n\n\n    def project_to_canonical(self, potential):\n        r\"\"\"\n        Project the wavepacket to the canonical basis.\n\n        :raise NotImplementedError: Abstract interface.\n        \"\"\"\n        raise NotImplementedError(\"'Wavepacket' is an abstract interface.\")\n\n\n    def project_to_eigen(self, potential):\n        r\"\"\"\n        Project the wavepacket to the eigenbasis of a given potential :math:`V`.\n\n        :raise NotImplementedError: Abstract interface.\n        \"\"\"\n        raise NotImplementedError(\"'Wavepacket' is an abstract interface.\")\n\n\n    def to_fourier_space(self, assign=True):\n        r\"\"\"\n        Transform the wavepacket to Fourier space.\n\n        :raise NotImplementedError: Abstract interface.\n        \"\"\"\n        raise NotImplementedError(\"'Wavepacket' is an abstract interface.\")\n\n\n    def to_real_space(self, assign=True):\n        r\"\"\"\n        Transform the wavepacket to real space.\n\n        :raise NotImplementedError: Abstract interface.\n        \"\"\"\n        raise NotImplementedError(\"'Wavepacket' is an abstract interface.\")\n", "meta": {"hexsha": "e5b61123fc5aed424d3ecf4c3be65ca3f7e0ec7f", "size": 11151, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/WaveBlocks/Wavepacket.py", "max_stars_repo_name": "WaveBlocks/WaveBlocks", "max_stars_repo_head_hexsha": "2af3730dcf27e54006ec602e696b4d4df25459d8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/WaveBlocks/Wavepacket.py", "max_issues_repo_name": "WaveBlocks/WaveBlocks", "max_issues_repo_head_hexsha": "2af3730dcf27e54006ec602e696b4d4df25459d8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/WaveBlocks/Wavepacket.py", "max_forks_repo_name": "WaveBlocks/WaveBlocks", "max_forks_repo_head_hexsha": "2af3730dcf27e54006ec602e696b4d4df25459d8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5127388535, "max_line_length": 118, "alphanum_fraction": 0.6275670343, "include": true, "reason": "from numpy", "num_tokens": 2357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.19358781864024519}}
{"text": "\"\"\"\nEverything to store electromagnetic material properties for the solver.\n\"\"\"\n# Copyright 2018-2021 The emsig community.\n#\n# This file is part of emg3d.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License.  You may obtain a copy\n# of the License at\n#\n#     https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the\n# License for the specific language governing permissions and limitations under\n# the License.\n\nfrom copy import deepcopy\n\nimport numpy as np\nfrom scipy.constants import epsilon_0\n\nfrom emg3d import maps, meshes, utils\n\n__all__ = ['Model', 'VolumeModel', 'expand_grid_model']\n\n\n# MODEL\n@utils._known_class\nclass Model:\n    r\"\"\"A model containing the electromagnetic properties of the Earth.\n\n    A model provides the required model parameters to the solver. The x-, y-,\n    and z-directed electrical properties are by default resistivities. However,\n    they can be defined as resistivities, :math:`\\rho\\ (\\Omega\\,\\mathrm{m})`,\n    or conductivities, :math:`\\sigma\\ (\\mathrm{S/m})`, either on a linear or on\n    a logarithmic scale (log or ln), by choosing the appropriate ``mapping``.\n    Relative magnetic permeability :math:`\\mu_\\mathrm{r}` is by default set to\n    one and electric permittivity :math:`\\varepsilon_\\mathrm{r}` is by default\n    set to zero, but they can also be provided (isotropically). Keep in mind\n    that the multigrid method as implemented in emg3d works for the diffusive\n    approximation. When the displacement part in Maxwell's equations becomes\n    too dominant it will start to fail (high frequencies or very high electric\n    permittivity).\n\n\n    Parameters\n    ----------\n    grid : TensorMesh\n        The grid; a :class:`emg3d.meshes.TensorMesh` instance.\n\n    property_{x;y;z} : {None, array_like}, default: 1 (x), None (y, z)\n        Electrical material property in x-, y-, and z-directions. The\n        properties are stored as Fortran-ordered arrays with the shape given by\n        ``grid.shape``. The provided value must be broadcastable to that shape.\n\n        By default, property refers to electrical resistivity. However, this\n        can be changed with an appropriate ``mapping`` (the internals of\n        emg3d work, irrelevant of the map, with electrical conductivities).\n\n        The properties have to be of finite value, bigger than zero (on linear\n        scale). The four supported anisotropy cases are:\n\n        - ``x;y=None;z=None``: isotropic (``y=z=x``);\n        - ``x;y=None;z``: vertical transverse isotropy VTI (``y=x``);\n        - ``x;y;z=None``: horizontal transverse isotropy HTI (``z=x``);\n        - ``x;y;z``: triaxial  anisotropy.\n\n        If a property is not initiated it cannot be set later on (e.g., if a\n        VTI model is created, it is not possible to set ``property_y`` later\n        on, instead, a new model has to be initiated).\n\n    mu_r, epsilon_r : {None, array_like}, default: None\n        Relative magnetic permeability (-) and relative electric permittivity\n        (-), respectively, both isotropic. The properties are stored as\n        Fortran-ordered arrays with the shape given by ``grid.shape``. The\n        provided value must be broadcastable to that shape.\n\n        The properties have to be of finite value, bigger than zero.\n\n        The relative magnetic permeability is assumed to be 1 if not provided.\n\n        The relative electric permittivity is assumed to be 0 if not provided,\n        which ignores the displacement part completely (diffusive\n        approximation)\n\n    mapping : str, default: 'Resistivity'\n        Defines what type the electrical input ``property_{x;y;z}``-values\n        correspond to. The implemented types are:\n\n        - ``'Resistivity'``; ρ (Ω m);\n        - ``'Conductivity'``; σ (S/m);\n        - ``'LgResistivity'``; log_10(ρ);\n        - ``'LgConductivity'``; log_10(σ);\n        - ``'LnResistivity'``; log_e(ρ);\n        - ``'LnConductivity'``; log_e(σ).\n\n    \"\"\"\n\n    def __init__(self, grid, property_x=1., property_y=None, property_z=None,\n                 mu_r=None, epsilon_r=None, mapping='Resistivity'):\n        \"\"\"Initiate a new model.\"\"\"\n\n        # Store grid.\n        self.grid = grid\n\n        # Alias shape_cells and n_cells to shape and size.\n        self.shape = self.grid.shape_cells\n        self.size = self.grid.n_cells\n\n        # Get and store map.\n        self.map = getattr(maps, 'Map'+mapping)()\n\n        # Initiate and store all parameters.\n        self._property_x = self._init_parameter(property_x, 'property_x')\n        self._property_y = self._init_parameter(property_y, 'property_y')\n        self._property_z = self._init_parameter(property_z, 'property_z')\n        self._mu_r = self._init_parameter(mu_r, 'mu_r',)\n        self._epsilon_r = self._init_parameter(epsilon_r, 'epsilon_r')\n        self._properties = ['property_x', 'property_y', 'property_z',\n                            'mu_r', 'epsilon_r']\n\n        # Store case.\n        if self._property_y is None and self._property_z is None:\n            self.case = 'isotropic'\n        elif self._property_z is None:\n            self.case = 'HTI'\n        elif self._property_y is None:\n            self.case = 'VTI'\n        else:\n            self.case = 'triaxial'\n\n    def __repr__(self):\n        \"\"\"Simple representation.\"\"\"\n        return (f\"{self.__class__.__name__}: {self.map.description}; \"\n                f\"{self.case}{'' if self.mu_r is None else '; mu_r'}\"\n                f\"{'' if self.epsilon_r is None else '; epsilon_r'}\"\n                f\"; {self.shape[0]} x {self.shape[1]} x {self.shape[2]} \"\n                f\"({self.size:,})\")\n\n    def __add__(self, model):\n        \"\"\"Add two models.\"\"\"\n\n        # Ensure model is a Model instance.\n        if model.__class__.__name__ != 'Model':\n            return NotImplemented\n\n        # Check input.\n        self._operator_test(model)\n\n        # Apply operator.\n        kwargs = self._apply_operator(model, np.add)\n\n        # Return new Model instance.\n        return Model(grid=self.grid, mapping=self.map.name, **kwargs)\n\n    def __sub__(self, model):\n        \"\"\"Subtract two models.\"\"\"\n\n        # Ensure model is a Model instance.\n        if model.__class__.__name__ != 'Model':\n            return NotImplemented\n\n        # Check input.\n        self._operator_test(model)\n\n        # Apply operator.\n        kwargs = self._apply_operator(model, np.subtract)\n\n        # Return new Model instance.\n        return Model(grid=self.grid, mapping=self.map.name, **kwargs)\n\n    def __eq__(self, model):\n        \"\"\"Compare two models.\"\"\"\n\n        # Check if model is a Model instance.\n        equal = model.__class__.__name__ == 'Model'\n\n        # Check input.\n        if equal:\n            try:\n                self._operator_test(model)\n            except ValueError:\n                equal = False\n\n        # Compare values if not None.\n        if equal:\n            for prop in self._properties:\n                val = getattr(self, prop)\n                if val is not None:\n                    equal *= np.allclose(val, getattr(model, prop))\n\n        return bool(equal)\n\n    def copy(self):\n        \"\"\"Return a copy of the Model.\"\"\"\n        return self.from_dict(self.to_dict(True))\n\n    def to_dict(self, copy=False):\n        \"\"\"Store the necessary information in a dict for serialization.\n\n        Parameters\n        ----------\n        copy : bool, default: False\n            If True, returns a deep copy of the dict.\n\n\n        Returns\n        -------\n        out : dict\n            Dictionary containing all information to re-create the Model.\n\n        \"\"\"\n        out = {\n            '__class__': self.__class__.__name__,  # v ensure emg3d-TensorMesh\n            'grid': meshes.TensorMesh(self.grid.h, self.grid.origin).to_dict(),\n            **{prop: getattr(self, prop) for prop in self._properties},\n            'mapping': self.map.name,\n        }\n        if copy:\n            return deepcopy(out)\n        else:\n            return out\n\n    @classmethod\n    def from_dict(cls, inp):\n        \"\"\"Convert dictionary into :class:`emg3d.models.Model` instance.\n\n        Parameters\n        ----------\n        inp : dict\n            Dictionary as obtained from :func:`emg3d.models.Model.to_dict`. The\n            dictionary needs the keys ``property_x``, ``property_y``,\n            ``property_z``, ``mu_r``, ``epsilon_r``, ``grid``, and ``mapping``;\n            ``grid`` itself is also a dict which needs the keys ``hx``, ``hy``,\n            ``hz``, and ``origin``.\n\n        Returns\n        -------\n        model : Model\n            A :class:`emg3d.models.Model` instance.\n\n        \"\"\"\n        inp = {k: v for k, v in inp.items() if k != '__class__'}\n        MeshClass = getattr(meshes, inp['grid']['__class__'])\n        return cls(grid=MeshClass.from_dict(inp.pop('grid')), **inp)\n\n    # ELECTRICAL PROPERTIES\n    @property\n    def property_x(self):\n        r\"\"\"Electrical property in x-direction.\"\"\"\n        return self._property_x\n\n    @property_x.setter\n    def property_x(self, property_x):\n        r\"\"\"Update electrical property in x-direction.\"\"\"\n        self._check_positive_finite(property_x, 'property_x')\n        self._property_x[:] = np.asfortranarray(property_x, dtype=np.float64)\n\n    @property\n    def property_y(self):\n        r\"\"\"Electrical property in y-direction.\"\"\"\n        return self._property_y\n\n    @property_y.setter\n    def property_y(self, property_y):\n        r\"\"\"Update electrical property in y-direction.\"\"\"\n        self._check_positive_finite(property_y, 'property_y')\n        self._property_y[:] = np.asfortranarray(property_y, dtype=np.float64)\n\n    @property\n    def property_z(self):\n        r\"\"\"Electrical property in z-direction.\"\"\"\n        return self._property_z\n\n    @property_z.setter\n    def property_z(self, property_z):\n        r\"\"\"Update electrical property in z-direction.\"\"\"\n        self._check_positive_finite(property_z, 'property_z')\n        self._property_z[:] = np.asfortranarray(property_z, dtype=np.float64)\n\n    @property\n    def mu_r(self):\n        r\"\"\"Relative magnetic permeability.\"\"\"\n        return self._mu_r\n\n    @mu_r.setter\n    def mu_r(self, mu_r):\n        r\"\"\"Update relative magnetic permeability.\"\"\"\n        self._check_positive_finite(mu_r, 'mu_r')\n        self._mu_r[:] = np.asfortranarray(mu_r, dtype=np.float64)\n\n    @property\n    def epsilon_r(self):\n        r\"\"\"Relative electric permittivity.\"\"\"\n        return self._epsilon_r\n\n    @epsilon_r.setter\n    def epsilon_r(self, epsilon_r):\n        r\"\"\"Update relative electric permittivity.\"\"\"\n        self._check_positive_finite(epsilon_r, 'epsilon_r')\n        self._epsilon_r[:] = np.asfortranarray(epsilon_r, dtype=np.float64)\n\n    # INTERPOLATION\n    def interpolate_to_grid(self, grid, **interpolate_opts):\n        \"\"\"Interpolate the model to a new grid.\n\n        If the provided grid is identical to the grid of the model, it returns\n        the actual model (not a copy).\n\n\n        Parameters\n        ----------\n        grid : TensorMesh\n            Grid of the new model; a :class:`emg3d.meshes.TensorMesh` instance.\n\n        interpolate_opts : dict\n            Passed through to :func:`emg3d.maps.interpolate`. Defaults are\n            ``method='volume'``, ``log=True``, and ``extrapolate=True``.\n\n\n        Returns\n        -------\n        obj : Model\n            A new :class:`emg3d.models.Model` instance on ``grid``.\n\n        \"\"\"\n        # If grids are identical, return model.\n        if grid == self.grid:\n            return self\n\n        # Get solver options, set to defaults if not provided.\n        g2g_inp = {\n            'method': 'volume',\n            'extrapolate': True,\n            'log': not self.map.name.startswith('L'),\n            **({} if interpolate_opts is None else interpolate_opts),\n            'grid': self.grid,\n            'xi': grid,\n        }\n\n        # Interpolate property_{x;y;z}; mu_r; and epsilon_r; add to dict.\n        model_inp = {}\n        for prop in self._properties:\n            var = getattr(self, prop)\n            if var is None:\n                model_inp[prop] = None\n            else:\n                model_inp[prop] = maps.interpolate(values=var, **g2g_inp)\n\n        # Assemble new model.\n        return Model(grid, mapping=self.map.name, **model_inp)\n\n    # INTERNAL UTILITIES\n    def _init_parameter(self, values, name):\n        \"\"\"Initiate parameter by casting and broadcasting.\"\"\"\n\n        # If None, exit.\n        if values is None:\n            return None\n\n        # Cast it to an array of floats, in Fortran order.\n        values = np.asfortranarray(values, dtype=np.float64)\n\n        # If 1D array of self.size, reshape it.\n        if values.size == self.size:\n            values = values.reshape(self.shape, order='F')\n\n        # If not of shape self.shape, broadcast it.\n        elif values.shape != self.shape:\n            values = np.ones(self.shape, order='F')*values\n\n        # Check >0 and finite.\n        self._check_positive_finite(values, name)\n\n        return values\n\n    def _check_positive_finite(self, values, name):\n        \"\"\"Check parameter values are positive (on linear scale) and finite.\"\"\"\n\n        # If it is None, it cannot be set.\n        if hasattr(self, '_'+name) and getattr(self, '_'+name) is None:\n            raise ValueError(\n                f\"Model was initiated without `{name}`; cannot set values.\"\n            )\n\n        # Get mapped values; checks are carried out on conductivities.\n        if 'property_' in name:\n            mapped = self.map.backward(np.asarray(values))\n        else:\n            mapped = values\n\n        # Check they are positive.\n        if not np.all(np.real(mapped) > 0.0):\n            raise ValueError(f\"`{name}` must be all bigger than zero.\")\n\n        # Check |val| < inf.\n        if not np.all(np.isfinite(mapped)):\n            raise ValueError(f\"`{name}` must be all finite.\")\n\n    def _operator_test(self, model):\n        \"\"\"Check if ``self`` and ``model`` are consistent for operations.\"\"\"\n\n        # Ensure the two instances have the same grid.\n        if self.grid != model.grid:\n            raise ValueError(\"Models have different grids.\")\n\n        # Ensure the two instances have the same case.\n        if self.case != model.case:\n            raise ValueError(\"Models have different anisotropy.\")\n\n        # Ensure both or none has mu_r:\n        if (self.mu_r is None) != (model.mu_r is None):\n            raise ValueError(\"One model has mu_r, the other not.\")\n\n        # Ensure both or none has epsilon_r:\n        if (self.epsilon_r is None) != (model.epsilon_r is None):\n            raise ValueError(\"One model has epsilon_r, the other not.\")\n\n        # Ensure the two instances have the same mapping:\n        if self.map.name != model.map.name:\n            raise ValueError(\"Models have different mappings.\")\n\n    def _apply_operator(self, model, operator):\n        \"\"\"Apply the provided operator to self and model.\"\"\"\n\n        # Apply operator to property_{x;y;z}; mu_r; and epsilon_r; add to dict.\n        kwargs = {}\n        for prop in self._properties:\n            val = getattr(self, prop)\n            if val is None:\n                kwargs[prop] = None\n            else:\n                kwargs[prop] = operator(val, getattr(model, prop))\n\n        return kwargs\n\n\nclass VolumeModel:\n    r\"\"\"Return simplified model with volume-averaged eta_{x;y;z}; zeta.\n\n    Takes a model and a source field and returns the volume-averaged eta and\n    zeta values. This is used internally by the solver.\n\n    .. math::\n\n        \\eta_{\\{x,y,z\\}} = -V\\mathrm{i}\\omega\\mu_0\n              \\left(\\sigma_{\\{x,y,z\\}} + \\mathrm{i}\\omega\\varepsilon\\right)\n\n    .. math::\n\n        \\zeta = V\\mu_\\mathrm{r}^{-1}\n\n\n    Parameters\n    ----------\n    model : Model\n        Model to transform to volume-averaged values.\n\n    sfield : Field\n       A VolumeModel is frequency-dependent. The frequency-information is taken\n       from the provided source field.\n\n    \"\"\"\n\n    def __init__(self, model, sfield):\n        \"\"\"Initiate a new model with volume-averaged properties.\"\"\"\n\n        # Store case and minimal TensorMesh.\n        self.case = model.case\n        self.grid = meshes.BaseMesh(model.grid.h, model.grid.origin)\n\n        # Get volume for volume-averaged values.\n        vol = self.grid.cell_volumes.reshape(model.shape, order='F')\n\n        # Compute and store eta.\n        for name in model._properties[:3]:\n\n            prop = getattr(model, name)\n\n            if prop is None:\n                eta = None\n\n            else:\n                # Get conductivities.\n                cond = model.map.backward(prop)\n\n                # Diffusive approximation.\n                if model.epsilon_r is None:\n                    eta = -sfield.smu0*vol*cond\n\n                # Complete version.\n                else:\n                    eta = -sfield.smu0*vol*(\n                            cond + sfield.sval*epsilon_0*model.epsilon_r)\n\n            setattr(self, '_eta_' + name[-1], eta)\n\n        # Compute and store zeta.\n        zeta = vol\n        if model.mu_r is not None:\n            zeta /= model.mu_r\n        self._zeta = zeta\n\n    @property\n    def eta_x(self):\n        r\"\"\"Volume-averaged eta in x-direction.\"\"\"\n        return self._eta_x\n\n    @property\n    def eta_y(self):\n        r\"\"\"Volume-averaged eta in y-direction.\"\"\"\n        if self.case in ['HTI', 'triaxial']:\n            return self._eta_y\n        else:\n            return self._eta_x\n\n    @property\n    def eta_z(self):\n        r\"\"\"Volume-averaged eta in z-direction.\"\"\"\n        if self.case in ['VTI', 'triaxial']:\n            return self._eta_z\n        else:\n            return self._eta_x\n\n    @property\n    def zeta(self):\n        r\"\"\"Volume-averaged, isotropic zeta.\"\"\"\n        return self._zeta\n\n\ndef expand_grid_model(model, expand, interface):\n    \"\"\"Expand model and grid according to provided parameters.\n\n    Expand the grid and corresponding model in positive z-direction from the\n    edge of the grid to the interface with property ``expand[0]``, and a 100 m\n    thick layer above the interface with property ``expand[1]``.\n\n    The provided properties are taken as isotropic (as is the case in water and\n    air); ``mu_r`` and ``epsilon_r`` are expanded with ones, if necessary.\n\n    The ``interface`` is usually the sea-surface, and ``expand`` is therefore\n    ``[property_sea, property_air]``.\n\n    Parameters\n    ----------\n    model : Model\n        The model; a :class:`emg3d.models.Model` instance.\n\n    expand : list\n        The two properties below and above the interface:\n        ``[below_interface, above_interface]``.\n\n    interface : float\n        Interface between the two properties in ``expand``.\n\n\n    Returns\n    -------\n    exp_grid : TensorMesh\n        Expanded grid; a :class:`emg3d.meshes.TensorMesh` instance.\n\n    exp_model : Model\n        The expanded model; a :class:`emg3d.models.Model` instance.\n\n    \"\"\"\n    grid = model.grid\n\n    def extend_property(prop, add_values, nadd):\n        \"\"\"Expand property `model.prop`, IF it is not None.\"\"\"\n\n        if getattr(model, prop) is None:\n            prop_ext = None\n\n        else:\n            prop_ext = np.zeros((grid.shape_cells[0], grid.shape_cells[1],\n                                 grid.shape_cells[2]+nadd))\n            prop_ext[:, :, :-nadd] = getattr(model, prop)\n            if nadd == 2:\n                prop_ext[:, :, -2] = add_values[0]\n            prop_ext[:, :, -1] = add_values[1]\n\n        return prop_ext\n\n    # Initiate.\n    nzadd = 0\n    hz_ext = grid.h[2]\n\n    # Fill-up property_below.\n    if grid.nodes_z[-1] < interface-0.05:  # At least 5 cm.\n        hz_ext = np.r_[hz_ext, interface-grid.nodes_z[-1]]\n        nzadd += 1\n\n    # Add 100 m of property_above.\n    if grid.nodes_z[-1] <= interface+0.001:  # +1mm\n        hz_ext = np.r_[hz_ext, 100]\n        nzadd += 1\n\n    if nzadd > 0:\n        # Extend properties.\n        property_x = extend_property('property_x', expand, nzadd)\n        property_y = extend_property('property_y', expand, nzadd)\n        property_z = extend_property('property_z', expand, nzadd)\n        mu_r = extend_property('mu_r', [1, 1], nzadd)\n        epsilon_r = extend_property('epsilon_r', [1, 1], nzadd)\n\n        # Create extended grid and model.\n        grid = meshes.TensorMesh(\n                [grid.h[0], grid.h[1], hz_ext], origin=grid.origin)\n        model = Model(grid, property_x, property_y, property_z, mu_r,\n                      epsilon_r, mapping=model.map.name)\n\n    return model\n", "meta": {"hexsha": "9762380fe3c5f2c525b9d4ee371d5e2b066cee0a", "size": 20703, "ext": "py", "lang": "Python", "max_stars_repo_path": "emg3d/models.py", "max_stars_repo_name": "emsig/emg3d", "max_stars_repo_head_hexsha": "5c1e132e0b0a49185b2ca3df2c4b45b7a4914fab", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-12-16T08:14:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T01:05:57.000Z", "max_issues_repo_path": "emg3d/models.py", "max_issues_repo_name": "victortocantins/emg3d", "max_issues_repo_head_hexsha": "e3aba4274424ae61094234946425240883aa2b91", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 92, "max_issues_repo_issues_event_min_datetime": "2020-12-10T09:31:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T17:44:33.000Z", "max_forks_repo_path": "emg3d/models.py", "max_forks_repo_name": "victortocantins/emg3d", "max_forks_repo_head_hexsha": "e3aba4274424ae61094234946425240883aa2b91", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-16T13:52:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-19T00:54:15.000Z", "avg_line_length": 33.6087662338, "max_line_length": 79, "alphanum_fraction": 0.6006858909, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118493816806, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1935878129610176}}
{"text": "\"\"\"\nModule of various types of time_evolution\n\"\"\"\n\nfrom copy import deepcopy\nfrom numba import float64, int64, jit, void\nfrom numpy import arange, array, cos, cross, pi, sin, sqrt, zeros\nfrom scipy.linalg import norm\n\n\nclass Integrator:\n    \"\"\"\n    Class used to assign integrator type.\n\n    Attributes\n    ----------\n    dt : float\n        Timestep.\n\n    kB : float\n        Boltzmann constant.\n\n    magnetized : bool\n        Magnetized simulation flag.\n\n    species_num : numpy.ndarray\n        Number of particles of each species.\n\n    species_plasma_frequencies : numpy.ndarray\n        Plasma frequency of each species.\n\n    box_lengths : numpy.ndarray\n        Length of each box side.\n\n    pbox_lengths : numpy.ndarray\n        Initial particle box sides' lengths.\n\n    verbose : bool\n        Verbose output flag.\n\n    type : str\n        Integrator type.\n\n    \"\"\"\n\n    dt: float = None\n    kB: float = None\n\n    # attributes\n    type: str = None\n    supported_integrators = {}\n    equilibration_type: str = \"verlet\"\n    magnetization_type: str = \"magnetic_verlet\"\n    production_type: str = \"verlet\"\n\n    species_num = None\n    species_plasma_frequencies = None\n\n    # Thermostat attributes\n    thermalization: bool = True\n    thermostat_type: str = \"berendsen\"\n    thermalization_rate: float = 2.0\n    thermalization_timestep: int = 0\n    berendsen_tau: float = None\n    thermostat_temperatures = None\n    thermostat_temperatures_eV = None\n\n    # Magnetic attributes\n    magnetized: bool = False\n    magnetic_field_uvector = None\n    magnetic_field = None\n    omega_c = None\n    species_cyclotron_frequencies = None\n    ccodt = None\n    cdt = None\n    ssodt = None\n    sdt = None\n    v_B = None\n    v_F = None\n\n    # Langevin attributes\n    c1 = None\n    c2 = None\n    sigma = None\n    box_lengths = None\n    pbox_lengths = None\n\n    boundary_conditions = None\n\n    supported_boundary_conditions = {}\n\n    verbose: bool = False\n\n    # def __repr__(self):\n    #     sortedDict = dict(sorted(self.__dict__.items(), key=lambda x: x[0].lower()))\n    #     disp = 'Integrator( \\n'\n    #     for key, value in sortedDict.items():\n    #         disp += \"\\t{} : {}\\n\".format(key, value)\n    #     disp += ')'\n    #     return disp\n\n    def __copy__(self):\n        \"\"\"Make a shallow copy of the object using copy by creating a new instance of the object and copying its __dict__.\"\"\"\n        # Create a new object\n        _copy = type(self)()\n        # copy the dictionary\n        _copy.from_dict(input_dict=self.__dict__)\n        return _copy\n\n    def __deepcopy__(self, memodict={}):\n        \"\"\"Make a deepcopy of the object.\n\n        Parameters\n        ----------\n        memodict: dict\n            Dictionary of id's to copies\n\n        Returns\n        -------\n        _copy: :class:`sarkas.time_evolution.integrators.Integrator`\n            A new Integrator class.\n        \"\"\"\n        id_self = id(self)  # memorization avoids unnecessary recursion\n        _copy = memodict.get(id_self)\n        if _copy is None:\n            _copy = type(self)()\n            # Make a deepcopy of the mutable arrays using numpy copy function\n            for k, v in self.__dict__.items():\n                if k != \"thread_ls\":\n                    _copy.__dict__[k] = deepcopy(v, memodict)\n\n        return _copy\n\n    def from_dict(self, input_dict: dict):\n        \"\"\"\n        Update attributes from input dictionary.\n\n        Parameters\n        ----------\n        input_dict: dict\n            Dictionary to be copied.\n\n        \"\"\"\n        self.__dict__.update(input_dict)\n\n    def copy_params(self, params):\n        \"\"\"\n        Copy necessary parameters.\n\n        Parameters\n        ----------\n        params: :class:`sarkas.core.Parameters`\n            Simulation's parameters.\n\n        \"\"\"\n        self.box_lengths = params.box_lengths\n        self.pbox_lengths = params.pbox_lengths\n        self.dimensions = params.dimensions\n        self.kB = params.kB\n        self.eV2K = params.eV2K\n        self.total_num_ptcls = params.total_num_ptcls\n        self.species_num = params.species_num.copy()\n        self.species_plasma_frequencies = params.species_plasma_frequencies.copy()\n        self.species_masses = params.species_masses.copy()\n        self.species_temperatures = params.species_temperatures.copy()\n        self.verbose = params.verbose\n        # Enforce consistency\n        if not self.boundary_conditions:\n            self.boundary_conditions = params.boundary_conditions.lower()\n\n        # Check whether you input temperatures in eV or K\n        if self.thermalization and self.thermostat_temperatures:\n            self.thermostat_temperatures_eV = self.thermostat_temperatures.copy() / self.eV2K\n        elif self.thermalization and self.thermostat_temperatures_eV:\n            self.thermostat_temperatures = self.thermostat_temperatures_eV.copy() * self.eV2K\n        elif self.thermalization and not self.thermostat_temperatures:\n            self.thermostate_temperatures = params.species_temperatures.copy()\n            self.thermostate_temperatures_eV = params.species_temperatures_eV.copy()\n\n        # Backwards compatibility\n        if hasattr(self, \"equilibration_steps\"):\n            params.equilibration_steps = self.equilibration_steps\n\n        if hasattr(self, \"magnetization_steps\"):\n            params.equilibration_steps = self.magnetization_steps\n\n        if hasattr(self, \"production_steps\"):\n            params.production_steps = self.production_steps\n\n        if hasattr(self, \"eq_dump_step\"):\n            params.eq_dump_step = self.eq_dump_step\n\n        if hasattr(self, \"mag_dump_step\"):\n            params.mag_dump_step = self.mag_dump_step\n\n        if hasattr(self, \"eq_dump_step\"):\n            params.prod_dump_step = self.prod_dump_step\n\n        if not self.boundary_conditions:\n            self.boundary_conditions = params.boundary_conditions\n\n        if not hasattr(params, \"boundary_conditions\"):\n            params.boundary_conditions = self.boundary_conditions\n\n        if params.magnetized:\n            self.magnetized = True\n            self.magnetic_field = params.magnetic_field.copy()\n            self.species_cyclotron_frequencies = params.species_cyclotron_frequencies.copy()\n\n    def setup(self, params, potential):\n        \"\"\"\n        Assign attributes from simulation's parameters and classes.\n\n        Parameters\n        ----------\n        params : :class:`sarkas.core.Parameters`\n            Parameters class.\n\n        potential : :class:`sarkas.potentials.core.Potential`\n            Potential class.\n\n        \"\"\"\n        if self.dt is None:\n            raise ValueError(\"integrator.dt is None. Please define Integrator.dt\")\n\n        self.copy_params(params)\n\n        if self.magnetized:\n            self.magnetic_setup()\n\n        if self.type:\n            self.type = self.type.lower()\n            self.equilibration_type = self.type\n            self.production_type = self.type\n\n        self.boundary_condition_setup()\n\n        if self.thermalization:\n            self.thermostat_setup()\n\n        self.pot_acc_setup(potential)\n\n    def pot_acc_setup(self, potential):\n        \"\"\"\n        Link the :meth:`.update_accelerations` method depending on the potential algorithm.\n\n        Parameters\n        ----------\n        potential : :class:`sarkas.potentials.core.Potential`\n            Potential class.\n\n        \"\"\"\n\n        self.potential_type = potential.type\n        if potential.method != \"fmm\":\n            if potential.pppm_on:\n                self.update_accelerations = potential.update_pppm\n            else:\n                if potential.linked_list_on:\n                    self.update_accelerations = potential.update_linked_list\n                else:\n                    self.update_accelerations = potential.update_brute\n        else:\n            self.update_accelerations = (\n                potential.update_fmm_coulomb if potential.type == \"coulomb\" else potential.update_fmm_yukawa\n            )\n\n    def boundary_condition_setup(self):\n\n        self.supported_boundary_conditions = {\n            \"periodic\": self.periodic_bc,\n            \"absorbing\": self.absorbing_bc,\n            \"reflective\": self.reflecting_bc,\n            \"open\": self.open_bc,\n        }\n        msg = (\n            f\"Unsupported boundary conditions. \"\n            f\"Choose one of the supported boundary conditions\\n{self.supported_boundary_conditions.keys()}\",\n        )\n        # Assign integrator.enforce_bc to the correct method\n        self.enforce_bc = self.supported_boundary_conditions.get(self.boundary_conditions, ValueError(msg))\n\n    def thermostat_setup(self):\n        \"\"\"\n        Assign attributes from simulation's parameters.\n\n        Raises\n        ------\n        ValueError\n            If a thermostat different than Berendsen is chosen.\n\n        \"\"\"\n\n        self.thermostat_type = self.thermostat_type.lower()\n\n        if self.thermostat_type != \"berendsen\":\n            raise ValueError(\"Only Berendsen thermostat is supported.\")\n\n        if self.berendsen_tau:\n            self.thermalization_rate = 1.0 / self.berendsen_tau\n        else:\n            self.berendsen_tau = 1.0 / self.thermalization_rate\n\n    def type_setup(self, int_type):\n        \"\"\"\n\n        Parameters\n        ----------\n        int_type: str\n            Integrator type to use.\n\n        Raises\n        ------\n        : ValueError\n            If `int_type` is not a supported integrator.\n\n        \"\"\"\n\n        # if int_type not in self.supported_integrators:\n        #     raise ValueError(\n        #         \"Integrator not supported. \" \"Please choose one of the supported integrators \\n\",\n        #         self.supported_integrators,\n        #     )\n\n        # Assign integrator.update to the correct method\n\n        if int_type == \"langevin\":\n\n            self.sigma = sqrt(2.0 * self.langevin_gamma * self.kB * self.species_temperatures / self.species_masses)\n            self.c1 = 1.0 - 0.5 * self.langevin_gamma * self.dt\n            self.c2 = 1.0 / (1.0 + 0.5 * self.langevin_gamma * self.dt)\n\n        elif int_type == \"magnetic_verlet\":\n\n            # Calculate functions for magnetic integrator\n            # This could be used when the generalization to Forest-Ruth and MacLachlan algorithms will be implemented\n            # In a magnetic Velocity-Verlet the coefficient is 1/2, see eq.~(78) in :cite:`Chin2008`\n            self.magnetic_helpers(0.5)\n\n            if self.magnetic_field_uvector @ array([0.0, 0.0, 1.0]) == 1.0:  # dot product\n                int_type = \"magnetic_verlet_zdir\"\n\n        elif int_type == \"magnetic_pos_verlet\":\n            # Calculate functions for magnetic integrator\n            # This could be used when the generalization to Forest-Ruth and MacLachlan algorithms will be implemented\n            # In a magnetic Velocity-Verlet the coefficient is 1/2, see eq.~(78) in :cite:`Chin2008`\n            self.magnetic_helpers(1.0)\n\n            if self.magnetic_field_uvector @ array([0.0, 0.0, 1.0]) == 1.0:  # dot product\n                int_type = \"magnetic_pos_verlet_zdir\"\n\n        elif int_type == \"magnetic_boris\":\n\n            # In a leapfrog-type algorithm the coefficient is different for the acceleration and magnetic rotation\n            # see eq.~(79) in :cite:`Chin2008`\n            self.magnetic_helpers(1.0)\n\n            if self.magnetic_field_uvector @ array([0.0, 0.0, 1.0]) == 1.0:  # dot product\n                int_type = \"magnetic_boris_zdir\"\n\n        elif int_type == \"cyclotronic\":\n            # Calculate functions for magnetic integrator\n            # This could be used when the generalization to Forest-Ruth and MacLachlan algorithms will be implemented\n            # In a magnetic Velocity-Verlet the coefficient is 1/2, see eq.~(78) in :cite:`Chin2008`\n            self.magnetic_helpers(0.5)\n\n            if self.magnetic_field_uvector @ array([0.0, 0.0, 1.0]) == 1.0:  # dot product\n                int_type = \"cyclotronic_zdir\"\n\n        self.supported_integrators = {\n            \"verlet\": self.verlet,\n            \"langevin\": self.langevin,\n            \"magnetic_verlet\": self.magnetic_verlet,\n            \"magnetic_verlet_zdir\": self.magnetic_verlet_zdir,\n            \"magnetic_pos_verlet\": self.magnetic_pos_verlet,\n            \"magnetic_pos_verlet_zdir\": self.magnetic_pos_verlet_zdir,\n            \"magnetic_boris\": self.magnetic_boris,\n            \"magnetic_boris_zdir\": self.magnetic_boris_zdir,\n            \"cyclotronic\": self.cyclotronic,\n            \"cyclotronic_zdir\": self.cyclotronic_zdir,\n        }\n\n        msg = f\"Integrator not supported. Please choose one of the supported integrators \\n{self.supported_integrators.keys()}\"\n\n        return self.supported_integrators.get(int_type, ValueError(msg))\n\n    def magnetic_setup(self):\n        # Create the unit vector of the magnetic field\n        self.magnetic_field_uvector = self.magnetic_field / norm(self.magnetic_field)\n        self.omega_c = zeros((self.total_num_ptcls, 3))\n\n        sp_start = 0\n        sp_end = 0\n        for ic, sp_np in enumerate(self.species_num):\n            sp_end += sp_np\n            self.omega_c[sp_start:sp_end, :] = self.species_cyclotron_frequencies[ic]\n            sp_start += sp_np\n\n        # array to temporary store velocities\n        # Luciano: I have the vague doubt that allocating memory for these arrays is faster than calculating them\n        # each time step\n        self.v_B = zeros((self.total_num_ptcls, 3))\n        self.v_F = zeros((self.total_num_ptcls, 3))\n\n    def langevin(self, ptcls):\n        \"\"\"\n        Update particles class using the velocity verlet algorithm and Langevin damping.\n\n        Parameters\n        ----------\n        ptcls: :class:`sarkas.particles.Particles`\n            Particles data.\n\n\n        \"\"\"\n\n        beta = ptcls.gaussian(0.0, 1.0, (self.total_num_ptcls, self.dimensions))\n        sp_start = 0  # start index for species loop\n        sp_end = 0\n        for ic, num in enumerate(self.species_num):\n            sp_end += num\n            ptcls.pos[sp_start:sp_end, : self.dimensions] += (\n                self.c1 * self.dt * ptcls.vel[sp_start:sp_end, : self.dimensions]\n                + 0.5 * self.dt**2 * ptcls.acc[sp_start:sp_end, : self.dimensions]\n                + 0.5 * self.sigma[ic] * self.dt**1.5 * beta\n            )\n            sp_start += num\n\n        # Enforce boundary condition\n        self.enforce_bc(ptcls)\n\n        acc_old = ptcls.acc.copy()\n        self.update_accelerations(ptcls)\n\n        sp_start = 0\n        sp_end = 0\n        for ic, num in enumerate(self.species_num):\n            sp_end += num\n\n            ptcls.vel[sp_start:sp_end, : self.dimensions] = (\n                self.c1 * self.c2 * ptcls.vel[sp_start:sp_end, : self.dimensions]\n                + 0.5\n                * self.c2\n                * self.dt\n                * (ptcls.acc[sp_start:sp_end, : self.dimensions] + acc_old[sp_start:sp_end, : self.dimensions])\n                + self.c2 * self.sigma[ic] * sqrt(self.dt) * beta\n            )\n            sp_start += num\n\n    def verlet(self, ptcls):\n        \"\"\"\n        Update particles' class based on velocity verlet algorithm.\n        More information can be found here: https://en.wikipedia.org/wiki/Verlet_integration\n        or on the Sarkas website.\n\n        Parameters\n        ----------\n        ptcls: :class:`sarkas.particles.Particles`\n            Particles data.\n\n        \"\"\"\n        # First half step velocity update\n        ptcls.vel += 0.5 * ptcls.acc * self.dt\n        # Full step position update\n        ptcls.pos += ptcls.vel * self.dt\n        # Enforce boundary condition\n        self.enforce_bc(ptcls)\n        # Compute total potential energy and acceleration for second half step velocity update\n        self.update_accelerations(ptcls)\n        # Second half step velocity update\n        ptcls.vel += 0.5 * ptcls.acc * self.dt\n\n    def magnetic_helpers(self, coefficient):\n        \"\"\"Calculate the trigonometric functions of the magnetic integrators.\n\n        Parameters\n        ----------\n        coefficient: float\n            Timestep coefficient.\n\n        Notes\n        -----\n        This is useful for the Leapfrog magnetic algorithm and future Forest-Ruth and MacLachlan algorithms.\n\n        \"\"\"\n        theta = self.omega_c * self.dt * coefficient\n        self.sdt = sin(theta)\n        self.cdt = cos(theta)\n        self.ccodt = 1.0 - self.cdt\n        self.ssodt = 1.0 - self.sdt / theta\n\n    def magnetic_verlet_zdir(self, ptcls):\n        \"\"\"\n        Update particles' class based on velocity verlet method in the case of a\n        constant magnetic field along the :math:`z` axis. For more info see eq. (78) of Ref. :cite:`Chin2008`\n\n        Parameters\n        ----------\n        ptcls: :class:`sarkas.particles.Particles`\n            Particles data.\n\n        Returns\n        -------\n        potential_energy : float\n             Total potential energy.\n\n        Notes\n        -----\n        This integrator is faster than `magnetic_verlet` but valid only for a magnetic field in the :math:`z`-direction.\n        This is the preferred choice in this case.\n        \"\"\"\n\n        # First half step of velocity update\n        # # Magnetic rotation x - velocity\n        # (B x v)_x  = -v_y, (B x B x v)_x = -v_x\n        self.v_B[:, 0] = ptcls.vel[:, 1] * self.sdt[:, 0] + ptcls.vel[:, 0] * self.cdt[:, 0]\n        # Magnetic rotation y - velocity\n        # (B x v)_y  = v_x, (B x B x v)_y = -v_y\n        self.v_B[:, 1] = -ptcls.vel[:, 0] * self.sdt[:, 0] + ptcls.vel[:, 1] * self.cdt[:, 1]\n\n        # Magnetic + Const force field x - velocity\n        # (B x a)_x  = -a_y, (B x B x a)_x = -a_x\n        self.v_F[:, 0] = (\n            self.ccodt[:, 1] / self.omega_c[:, 1] * ptcls.acc[:, 1]\n            + self.sdt[:, 0] / self.omega_c[:, 0] * ptcls.acc[:, 0]\n        )\n        # Magnetic + Const force field y - velocity\n        # (B x a)_y  = a_x, (B x B x a)_y = -a_y\n        self.v_F[:, 1] = (\n            -self.ccodt[:, 0] / self.omega_c[:, 0] * ptcls.acc[:, 0]\n            + self.sdt[:, 1] / self.omega_c[:, 1] * ptcls.acc[:, 1]\n        )\n\n        ptcls.vel[:, 0] = self.v_B[:, 0] + self.v_F[:, 0]\n        ptcls.vel[:, 1] = self.v_B[:, 1] + self.v_F[:, 1]\n        ptcls.vel[:, 2] += 0.5 * self.dt * ptcls.acc[:, 2]\n\n        # Position update\n        ptcls.pos += ptcls.vel * self.dt\n\n        # Enforce boundary condition\n        self.enforce_bc(ptcls)\n\n        # Compute total potential energy and acceleration for second half step velocity update\n        potential_energy = self.update_accelerations(ptcls)\n\n        # # Magnetic rotation x - velocity\n        # (B x v)_x  = -v_y, (B x B x v)_x = -v_x\n        self.v_B[:, 0] = ptcls.vel[:, 1] * self.sdt[:, 0] + ptcls.vel[:, 0] * self.cdt[:, 0]\n        # Magnetic rotation y - velocity\n        # (B x v)_y  = v_x, (B x B x v)_y = -v_y\n        self.v_B[:, 1] = -ptcls.vel[:, 0] * self.sdt[:, 0] + ptcls.vel[:, 1] * self.cdt[:, 1]\n\n        # Magnetic + Const force field x - velocity\n        # (B x a)_x  = -a_y, (B x B x a)_x = -a_x\n        self.v_F[:, 0] = (\n            self.ccodt[:, 1] / self.omega_c[:, 1] * ptcls.acc[:, 1]\n            + self.sdt[:, 0] / self.omega_c[:, 0] * ptcls.acc[:, 0]\n        )\n        # Magnetic + Const force field y - velocity\n        # (B x a)_y  = a_x, (B x B x a)_y = -a_y\n        self.v_F[:, 1] = (\n            -self.ccodt[:, 0] / self.omega_c[:, 0] * ptcls.acc[:, 0]\n            + self.sdt[:, 1] / self.omega_c[:, 1] * ptcls.acc[:, 1]\n        )\n\n        ptcls.vel[:, 0] = self.v_B[:, 0] + self.v_F[:, 0]\n        ptcls.vel[:, 1] = self.v_B[:, 1] + self.v_F[:, 1]\n        ptcls.vel[:, 2] += 0.5 * self.dt * ptcls.acc[:, 2]\n\n        return potential_energy\n\n    def magnetic_verlet(self, ptcls):\n        \"\"\"\n        Update particles' class based on velocity verlet method in the case of an arbitrary direction of the\n        constant magnetic field. For more info see eq. (78) of Ref. :cite:`Chin2008`\n\n        Parameters\n        ----------\n        ptcls: :class:`sarkas.particles.Particles`\n            Particles data.\n\n        Returns\n        -------\n        potential_energy : float\n             Total potential energy.\n\n        Notes\n        -----\n        :cite:`Chin2008` equations are written for a negative charge. This allows him to write\n        :math:`\\\\dot{\\\\mathbf v} = \\\\omega_c \\\\hat{B} \\\\times \\\\mathbf v`. In the case of positive charges we will have\n        :math:`\\\\dot{\\\\mathbf v} = - \\\\omega_c \\\\hat{B} \\\\times \\\\mathbf v`.\n        Hence the reason of the different signs in the formulas below compared to Chin's.\n\n        Warnings\n        --------\n        This integrator is valid for a magnetic field in an arbitrary direction. However, while the integrator works for\n        an arbitrary direction, methods in :mod:`sarkas.tools.observables` work only for a magnetic field in the\n        :math:`z` - direction. Hence, if you choose to use this integrator remember to change your physical observables.\n\n        \"\"\"\n        # Calculate the cross products\n        b_cross_v = cross(self.magnetic_field_uvector, ptcls.vel)\n        b_cross_b_cross_v = cross(self.magnetic_field_uvector, b_cross_v)\n        b_cross_a = cross(self.magnetic_field_uvector, ptcls.acc)\n        b_cross_b_cross_a = cross(self.magnetic_field_uvector, b_cross_a)\n\n        # First half step of velocity update\n        ptcls.vel += -self.sdt * b_cross_v + self.ccodt * b_cross_b_cross_v\n\n        ptcls.vel += (\n            0.5 * ptcls.acc * self.dt\n            - self.ccodt / self.omega_c * b_cross_a\n            + 0.5 * self.dt * self.ssodt * b_cross_b_cross_a\n        )\n\n        # Position update\n        ptcls.pos += ptcls.vel * self.dt\n\n        # Enforce boundary condition\n        self.enforce_bc(ptcls)\n\n        # Compute total potential energy and acceleration for second half step velocity update\n        potential_energy = self.update_accelerations(ptcls)\n\n        # Re-calculate the cross products\n        b_cross_v = cross(self.magnetic_field_uvector, ptcls.vel)\n        b_cross_b_cross_v = cross(self.magnetic_field_uvector, b_cross_v)\n        b_cross_a = cross(self.magnetic_field_uvector, ptcls.acc)\n        b_cross_b_cross_a = cross(self.magnetic_field_uvector, b_cross_a)\n\n        # Second half step velocity update\n        ptcls.vel += -self.sdt * b_cross_v + self.ccodt * b_cross_b_cross_v\n\n        ptcls.vel += (\n            0.5 * ptcls.acc * self.dt\n            - self.ccodt / self.omega_c * b_cross_a\n            + 0.5 * self.dt * self.ssodt * b_cross_b_cross_a\n        )\n\n        return potential_energy\n\n    def magnetic_boris_zdir(self, ptcls):\n        \"\"\"\n        Update particles' class using the Boris algorithm in the case of a\n        constant magnetic field along the :math:`z` axis. For more info see eqs. (80) - (81) of Ref. :cite:`Chin2008`\n\n        Parameters\n        ----------\n        ptcls: :class:`sarkas.particles.Particles`\n            Particles data.\n\n        Returns\n        -------\n        potential_energy : float\n             Total potential energy.\n\n        \"\"\"\n        # First half step of velocity update: Apply exp(dt * V_F / 2)\n        ptcls.vel += 0.5 * ptcls.acc * self.dt\n\n        # Rotate: Apply exp( dt * V)\n        # B cross v\n        self.v_B[:, 0] = -self.sdt[:, 1] * ptcls.vel[:, 1]\n        self.v_B[:, 1] = self.sdt[:, 0] * ptcls.vel[:, 0]\n\n        # B cross B cross v\n        self.v_B[:, 0] -= self.ccodt[:, 0] * ptcls.vel[:, 0]\n        self.v_B[:, 1] -= self.ccodt[:, 1] * ptcls.vel[:, 1]\n        # Update velocities\n        ptcls.vel[:, :2] += self.v_B[:, :2]\n\n        # Second Acceleration half step: Apply exp(dt * V_F / 2)\n        ptcls.vel += 0.5 * ptcls.acc * self.dt\n\n        # Full step position update\n        ptcls.pos += ptcls.vel * self.dt\n\n        # Enforce boundary condition\n        self.enforce_bc(ptcls)\n\n        # Compute total potential energy and acceleration for second half step velocity update\n        potential_energy = self.update_accelerations(ptcls)\n\n        return potential_energy\n\n    def magnetic_boris(self, ptcls):\n        \"\"\"\n        Update particles' class using the Boris algorithm in the case of a\n        constant magnetic field along the :math:`z` axis. For more info see eqs. (80) - (81) of Ref. :cite:`Chin2008`\n\n        Parameters\n        ----------\n        ptcls: :class:`sarkas.particles.Particles`\n            Particles data.\n\n        Returns\n        -------\n        potential_energy : float\n             Total potential energy.\n\n        \"\"\"\n\n        # First half step of velocity update: Apply exp(eV_F/2)\n        ptcls.vel += 0.5 * ptcls.acc * self.dt\n\n        # Rotate: Apply exp( dt * V)\n        # B cross v\n        b_cross_v = cross(self.magnetic_field_uvector, ptcls.vel)\n        # B cross B cross v\n        b_cross_b_cross_v = cross(self.magnetic_field_uvector, b_cross_v)\n        ptcls.vel += self.sdt * b_cross_v + self.ccodt * b_cross_b_cross_v\n\n        # Second Acceleration half step: Apply exp(dt * V_F / 2)\n        ptcls.vel += 0.5 * ptcls.acc * self.dt\n\n        # Full step position update\n        ptcls.pos += ptcls.vel * self.dt\n\n        # Periodic boundary condition\n        enforce_pbc(ptcls.pos, ptcls.pbc_cntr, self.box_lengths)\n\n        # Compute total potential energy and acceleration for second half step velocity update\n        potential_energy = self.update_accelerations(ptcls)\n\n        return potential_energy\n\n    def magnetic_pos_verlet_zdir(self, ptcls):\n        \"\"\"\n        Update particles' class based on position verlet method in the case of a\n        constant magnetic field along the :math:`z` axis. For more info see eq. (79) of Ref. :cite:`Chin2008`\n\n        Parameters\n        ----------\n        ptcls: :class:`sarkas.particles.Particles`\n            Particles data.\n\n        Returns\n        -------\n        potential_energy : float\n             Total potential energy.\n\n        Notes\n        -----\n        This integrator is faster than `magnetic_verlet` but valid only for a magnetic field in the :math:`z`-direction.\n        This is the preferred choice in this case.\n        \"\"\"\n\n        # Position update\n        ptcls.pos += 0.5 * ptcls.vel * self.dt\n\n        # Enforce boundary condition\n        self.enforce_bc(ptcls)\n\n        # Compute total potential energy and acceleration for second half step velocity update\n        potential_energy = self.update_accelerations(ptcls)\n\n        # First half step of velocity update\n        # # Magnetic rotation x - velocity\n        # (B x v)_x  = -v_y, (B x B x v)_x = -v_x\n        self.v_B[:, 0] = ptcls.vel[:, 1] * self.sdt[:, 0] + ptcls.vel[:, 0] * self.cdt[:, 0]\n        # Magnetic rotation y - velocity\n        # (B x v)_y  = v_x, (B x B x v)_y = -v_y\n        self.v_B[:, 1] = -ptcls.vel[:, 0] * self.sdt[:, 0] + ptcls.vel[:, 1] * self.cdt[:, 1]\n\n        # Magnetic + Const force field x - velocity\n        # (B x a)_x  = -a_y, (B x B x a)_x = -a_x\n        self.v_F[:, 0] = (\n            self.ccodt[:, 1] / self.omega_c[:, 1] * ptcls.acc[:, 1]\n            + self.sdt[:, 0] / self.omega_c[:, 0] * ptcls.acc[:, 0]\n        )\n        # Magnetic + Const force field y - velocity\n        # (B x a)_y  = a_x, (B x B x a)_y = -a_y\n        self.v_F[:, 1] = (\n            -self.ccodt[:, 0] / self.omega_c[:, 0] * ptcls.acc[:, 0]\n            + self.sdt[:, 1] / self.omega_c[:, 1] * ptcls.acc[:, 1]\n        )\n\n        ptcls.vel[:, 0] = self.v_B[:, 0] + self.v_F[:, 0]\n        ptcls.vel[:, 1] = self.v_B[:, 1] + self.v_F[:, 1]\n        ptcls.vel[:, 2] += self.dt * ptcls.acc[:, 2]\n\n        # Position update\n        ptcls.pos += 0.5 * ptcls.vel * self.dt\n\n        # Enforce boundary condition\n        self.enforce_bc(ptcls)\n\n        return potential_energy\n\n    def magnetic_pos_verlet(self, ptcls):\n        \"\"\"\n        Update particles' class based on position verlet method in the case of an arbitrary direction of the\n        constant magnetic field. For more info see eq. (79) of Ref. :cite:`Chin2008`\n\n        Parameters\n        ----------\n        ptcls: :class:`sarkas.particles.Particles`\n            Particles data.\n\n        Returns\n        -------\n        potential_energy : float\n             Total potential energy.\n\n        Notes\n        -----\n        :cite:`Chin2008` equations are written for a negative charge. This allows him to write\n        :math:`\\\\dot{\\\\mathbf v} = \\\\omega_c \\\\hat{B} \\\\times \\\\mathbf v`. In the case of positive charges we will have\n        :math:`\\\\dot{\\\\mathbf v} = - \\\\omega_c \\\\hat{B} \\\\times \\\\mathbf v`.\n        Hence the reason of the different signs in the formulas below compared to Chin's.\n\n        Warnings\n        --------\n        This integrator is valid for a magnetic field in an arbitrary direction. However, while the integrator works for\n        an arbitrary direction, methods in :mod:`sarkas.tools.observables` work only for a magnetic field in the\n        :math:`z` - direction. Hence, if you choose to use this integrator remember to change your physical observables.\n\n        \"\"\"\n        # Half position update\n        ptcls.pos += ptcls.vel * self.dt\n\n        # Enforce boundary condition\n        self.enforce_bc(ptcls)\n\n        # Compute total potential energy and acceleration for second half step velocity update\n        potential_energy = self.update_accelerations(ptcls)\n\n        # Calculate the cross products\n        b_cross_v = cross(self.magnetic_field_uvector, ptcls.vel)\n        b_cross_b_cross_v = cross(self.magnetic_field_uvector, b_cross_v)\n        b_cross_a = cross(self.magnetic_field_uvector, ptcls.acc)\n        b_cross_b_cross_a = cross(self.magnetic_field_uvector, b_cross_a)\n\n        # First half step of velocity update\n        ptcls.vel += -self.sdt * b_cross_v + self.ccodt * b_cross_b_cross_v\n\n        ptcls.vel += (\n            ptcls.acc * self.dt - self.ccodt / self.omega_c * b_cross_a + self.dt * self.ssodt * b_cross_b_cross_a\n        )\n\n        # Second half position update\n        ptcls.pos += ptcls.vel * self.dt\n\n        # Enforce boundary condition\n        self.enforce_bc(ptcls)\n\n        return potential_energy\n\n    def cyclotronic_zdir(self, ptcls):\n        \"\"\"\n        Update particles' class using the cyclotronic algorithm in the case of a\n        constant magnetic field along the :math:`z` axis.\n        For more info see eqs. (16) - (17) of Ref. :cite:`Patacchini2009`\n\n        Parameters\n        ----------\n        ptcls: :class:`sarkas.particles.Particles`\n            Particles data.\n\n        Returns\n        -------\n        potential_energy : float\n             Total potential energy.\n\n        \"\"\"\n        # Drift half step\n        # Rotate Positions\n        ptcls.pos[:, 0] += (\n            ptcls.vel[:, 0] * self.sdt[:, 0] / self.omega_c[:, 0]\n            + ptcls.vel[:, 1] * self.ccodt[:, 1] / self.omega_c[:, 1]\n        )\n        ptcls.pos[:, 1] += (\n            ptcls.vel[:, 1] * self.sdt[:, 1] / self.omega_c[:, 1]\n            - ptcls.vel[:, 0] * self.ccodt[:, 0] / self.omega_c[:, 0]\n        )\n        ptcls.pos[:, 2] += 0.5 * ptcls.vel[:, 2] * self.dt\n        # Enforce boundary condition\n        self.enforce_bc(ptcls)\n        # Create rotated velocities\n        self.v_B[:, 0] = self.cdt[:, 0] * ptcls.vel[:, 0] + self.sdt[:, 1] * ptcls.vel[:, 1]\n        self.v_B[:, 1] = self.cdt[:, 1] * ptcls.vel[:, 1] - self.sdt[:, 0] * ptcls.vel[:, 0]\n        ptcls.vel[:, :2] = self.v_B[:, :2].copy()\n        # Compute total potential energy and accelerations\n        potential_energy = self.update_accelerations(ptcls)\n\n        # Kick full step\n        ptcls.vel += ptcls.acc * self.dt\n\n        # Drift half step\n        # Rotate Positions\n        ptcls.pos[:, 0] += (\n            ptcls.vel[:, 0] * self.sdt[:, 0] / self.omega_c[:, 0]\n            + ptcls.vel[:, 1] * self.ccodt[:, 1] / self.omega_c[:, 1]\n        )\n        ptcls.pos[:, 1] += (\n            ptcls.vel[:, 1] * self.sdt[:, 1] / self.omega_c[:, 1]\n            - ptcls.vel[:, 0] * self.ccodt[:, 0] / self.omega_c[:, 0]\n        )\n        ptcls.pos[:, 2] += 0.5 * ptcls.vel[:, 2] * self.dt\n        # Enforce boundary condition\n        self.enforce_bc(ptcls)\n        # Create rotated velocities\n        self.v_B[:, 0] = self.cdt[:, 0] * ptcls.vel[:, 0] + self.sdt[:, 1] * ptcls.vel[:, 1]\n        self.v_B[:, 1] = self.cdt[:, 1] * ptcls.vel[:, 1] - self.sdt[:, 0] * ptcls.vel[:, 0]\n        # Update final velocities\n        ptcls.vel[:, :2] = self.v_B[:, :2].copy()\n\n        return potential_energy\n\n    def cyclotronic(self, ptcls):\n        \"\"\"\n        Update particles' class using the cyclotronic algorithm in the case of a\n        constant magnetic field along the :math:`z` axis.\n        For more info see eqs. (16) - (17) of Ref. :cite:`Patacchini2009`\n\n        Parameters\n        ----------\n        ptcls: :class:`sarkas.particles.Particles`\n            Particles data.\n\n        Returns\n        -------\n        potential_energy : float\n             Total potential energy.\n\n        \"\"\"\n        # Drift half step\n\n        # Calculate the cross products\n        b_cross_v = cross(self.magnetic_field_uvector, ptcls.vel)\n        b_cross_b_cross_v = cross(self.magnetic_field_uvector, b_cross_v)\n        # Rotate Positions\n        ptcls.pos += (\n            0.5 * ptcls.vel * self.dt\n            - self.ccodt * b_cross_v / self.omega_c\n            + 0.5 * self.dt * self.ssodt * b_cross_b_cross_v\n        )\n        # Enforce boundary condition\n        self.enforce_bc(ptcls)\n        # First half step of velocity update\n        ptcls.vel += -self.sdt * b_cross_v + self.ccodt * b_cross_b_cross_v\n        # Compute total potential energy and accelerations\n        potential_energy = self.update_accelerations(ptcls)\n\n        # Kick full step\n        ptcls.vel += ptcls.acc * self.dt\n\n        # Drift half step\n        # Calculate the cross products\n        b_cross_v = cross(self.magnetic_field_uvector, ptcls.vel)\n        b_cross_b_cross_v = cross(self.magnetic_field_uvector, b_cross_v)\n        # Rotate Positions\n        ptcls.pos += (\n            0.5 * ptcls.vel * self.dt\n            - self.ccodt * b_cross_v / self.omega_c\n            + 0.5 * self.dt * self.ssodt * b_cross_b_cross_v\n        )\n        # Enforce boundary condition\n        self.enforce_bc(ptcls)\n        # Second half step of velocity update\n        ptcls.vel += -self.sdt * b_cross_v + self.ccodt * b_cross_b_cross_v\n\n        return potential_energy\n\n    def thermostate(self, ptcls):\n        \"\"\"\n        Update particles' velocities according to the chosen thermostat\n\n        Parameters\n        ----------\n        ptcls : :class:`sarkas.particles.Particles`\n            Particles' data.\n\n        \"\"\"\n        _, T = ptcls.kinetic_temperature()\n        berendsen(ptcls.vel, self.species_temperatures, T, self.species_num, self.thermalization_rate)\n\n    def periodic_bc(self, ptcls):\n        \"\"\"\n        Applies periodic boundary conditions by calling enforce_pbc\n\n        Parameters\n        ----------\n        ptcls: :class:`sarkas.particles.Particles`\n            Particles data.\n\n        \"\"\"\n\n        enforce_pbc(ptcls.pos, ptcls.pbc_cntr, self.box_lengths)\n\n    def absorbing_bc(self, ptcls):\n        \"\"\"\n        Applies absorbing boundary conditions by calling enforce_abc\n\n        Parameters\n        ----------\n        ptcls: :class:`sarkas.particles.Particles`\n            Particles data.\n\n        \"\"\"\n\n        enforce_abc(ptcls.pos, ptcls.vel, ptcls.acc, ptcls.charges, self.box_lengths)\n\n    def open_bc(self, ptcls):\n        \"\"\"\n        Applies open boundary conditions. Basically it does nothing. pass\n\n        Parameters\n        ----------\n        ptcls: :class:`sarkas.particles.Particles`\n            Particles data.\n\n        \"\"\"\n\n        pass\n\n    def reflecting_bc(self, ptcls):\n        \"\"\"\n        Applies reflective boundary conditions by calling enforce_rbc\n\n        Parameters\n        ----------\n        ptcls: :class:`sarkas.particles.Particles`\n            Particles data.\n\n        \"\"\"\n\n        enforce_rbc(ptcls.pos, ptcls.vel, self.box_lengths, self.dt)\n\n    def pretty_print(self):\n        \"\"\"Print integrator and thermostat information in a user-friendly way.\"\"\"\n\n        if self.thermalization:\n            print(\"\\nTHERMOSTAT: \")\n            print(f\"Type: {self.thermostat_type}\")\n            print(f\"First thermostating timestep, i.e. thermalization_timestep = {self.thermalization_timestep}\")\n            print(f\"Berendsen parameter tau: {self.berendsen_tau:.3f} [timesteps]\")\n            print(f\"Berendsen relaxation rate: {self.thermalization_rate:.3f} [1/timesteps] \")\n            print(\"Thermostating temperatures: \")\n            for i, (t, t_ev) in enumerate(zip(self.thermostate_temperatures, self.thermostate_temperatures_eV)):\n                print(f\"Species ID {i}: T_eq = {t:.6e} [K] = {t_ev:.6e} [eV]\")\n\n        print(\"\\nINTEGRATOR: \")\n        print(f\"Equilibration Integrator Type: {self.equilibration_type}\")\n        if self.magnetized:\n            print(f\"Magnetization Integrator Type: {self.magnetization_type}\")\n        print(f\"Production Integrator Type: {self.production_type}\")\n\n        wp_tot = norm(self.species_plasma_frequencies)\n        wp_dt = wp_tot * self.dt\n\n        print(f\"Time step = {self.dt:.6e} [s]\")\n        print(f\"Total plasma frequency = {wp_tot:.6e} [rad/s]\")\n        print(f\"w_p dt = {wp_dt:.4f} ~ 1/{int(1.0 / wp_dt)}\")\n\n        if self.potential_type == \"qsp\":\n            wp_e = self.species_plasma_frequencies[0]\n            wp_ions = norm(self.species_plasma_frequencies[1:])\n            print(f\"e plasma frequency = {wp_e:.6e} [rad/s]\")\n            print(f\"total ion plasma frequency = {wp_ions:.6e} [rad/s]\")\n            print(f\"w_pe dt = {self.dt * wp_e:.4f} ~ 1/{int(1.0 / (self.dt * wp_e))}\")\n            print(f\"w_pi dt = {self.dt * wp_ions:.4f} ~ 1/{int(1.0 / (self.dt * wp_ions))}\")\n\n        elif self.potential_type == \"lj\":\n            print(f\"The plasma frequency is defined as w_p = sqrt( epsilon / (sigma^2 * mass) )\")\n\n        if self.magnetized:\n            high_wc_dt = abs(self.species_cyclotron_frequencies).max() * self.dt\n            low_wc_dt = abs(self.species_cyclotron_frequencies).min() * self.dt\n\n            if high_wc_dt > low_wc_dt:\n                print(f\"Highest w_c dt = {high_wc_dt:2.4f} = {high_wc_dt / pi:.4f} pi\")\n                print(f\"Smallest w_c dt = {low_wc_dt:2.4f} = {low_wc_dt / pi:.4f} pi\")\n            else:\n                print(f\"w_c dt = {high_wc_dt:2.4f} = {high_wc_dt / pi:.4f} pi\")\n\n        if self.equilibration_type == \"langevin\" or self.production_type == \"langevin\":\n            print(f\"langevin_gamma * dt = {self.langevin_gamma * self.dt:.4e}\")\n            print(f\"langevin_gamma / wp = {self.langevin_gamma / wp_tot:.4e}\")\n\n\n@jit(void(float64[:, :], float64[:], float64[:], int64[:], float64), nopython=True)\ndef berendsen(vel, T_desired, T, species_np, tau):\n    \"\"\"\n    Numba'd function to update particle velocity based on Berendsen thermostat :cite:`Berendsen1984`.\n\n    Parameters\n    ----------\n    vel : numpy.ndarray\n        Particles' velocities to rescale.\n\n    T_desired : numpy.ndarray\n        Target temperature of each species.\n\n    T : numpy.ndarray\n        Instantaneous temperature of each species.\n\n    species_np : numpy.ndarray\n        Number of each species.\n\n    tau : float\n        Scale factor.\n\n    \"\"\"\n\n    # if it < therm_timestep:\n    #     fact = sqrt(T_desired / T)\n    # else:\n    #     fact = sqrt(1.0 + (T_desired / T - 1.0) * tau)  # eq.(11)\n\n    # branchless programming\n    fact = sqrt(1.0 + (T_desired / T - 1.0) * tau)\n    species_start = 0\n    species_end = 0\n\n    for i, num in enumerate(species_np):\n        species_end += num\n        vel[species_start:species_end, :] *= fact[i]\n        species_start += num\n\n\n@jit(void(float64[:, :], float64[:, :], float64[:]), nopython=True)\ndef enforce_pbc(pos, cntr, box_vector) -> None:\n    \"\"\"\n    Numba'd function to enforce periodic boundary conditions.\n\n    Parameters\n    ----------\n    pos : numpy.ndarray\n        Particles' positions.\n\n    cntr : numpy.ndarray\n        Counter for the number of times each particle get folded back into the main simulation box\n\n    box_vector : numpy.ndarray\n        Box Dimensions.\n\n    \"\"\"\n\n    # Loop over all particles\n    for p in arange(pos.shape[0]):\n        for d in arange(pos.shape[1]):\n\n            # If particle is outside of box in positive direction, wrap to negative side\n            if pos[p, d] > box_vector[d]:\n                pos[p, d] -= box_vector[d]\n                cntr[p, d] += 1\n            # If particle is outside of box in negative direction, wrap to positive side\n            if pos[p, d] < 0.0:\n                pos[p, d] += box_vector[d]\n                cntr[p, d] -= 1\n\n\n@jit(void(float64[:, :], float64[:, :], float64[:, :], float64[:], float64[:]), nopython=True)\ndef enforce_abc(pos, vel, acc, charges, box_vector) -> None:\n    \"\"\"\n    Numba'd function to enforce absorbing boundary conditions.\n\n    Parameters\n    ----------\n    pos: numpy.ndarray\n        Particles' positions.\n\n    vel : numpy.ndarray\n        Particles' velocities.\n\n    acc : numpy.ndarray\n        Particles' accelerations.\n\n    charges : numpy.ndarray\n        Charge of each particle. Shape = (``total_num_ptcls``).\n\n    box_vector: numpy.ndarray\n        Box Dimensions.\n\n    \"\"\"\n\n    # Loop over all particles\n    for p in arange(pos.shape[0]):\n        for d in arange(pos.shape[1]):\n\n            # If particle is outside of box in positive direction, remove charge, velocity and acceleration\n            if pos[p, d] >= box_vector[d]:\n                pos[p, d] = box_vector[d]\n                vel[p, :] = zeros(3)\n                acc[p, :] = zeros(3)\n                charges[p] = 0.0\n            # If particle is outside of box in negative direction, remove charge, velocity and acceleration\n            if pos[p, d] <= 0.0:\n                pos[p, d] = 0.0\n                vel[p, :] = zeros(3)\n                acc[p, :] = zeros(3)\n                charges[p] = 0.0\n\n\n@jit(void(float64[:, :], float64[:, :], float64[:], float64), nopython=True)\ndef enforce_rbc(pos, vel, box_vector, dt) -> None:\n    \"\"\"\n    Numba'd function to enforce reflecting boundary conditions.\n\n    Parameters\n    ----------\n    pos: numpy.ndarray\n        Particles' positions.\n\n    vel : numpy.ndarray\n        Particles' velocities.\n\n    box_vector: numpy.ndarray\n        Box Dimensions.\n\n    dt : float\n        Timestep.\n\n    \"\"\"\n\n    # Loop over all particles\n    for p in arange(pos.shape[0]):\n        for d in arange(pos.shape[1]):\n\n            # If particle is outside of box in positive direction, wrap to negative side\n            if pos[p, d] > box_vector[d] or pos[p, d] < 0.0:\n                # Revert velocity\n                vel[p, d] *= -1.0\n                # Restore previous position assuming verlet algorithm\n                pos[p, d] += vel[p, d] * dt\n\n\n# @jit(void(float64[:, :], int64[:], float64[:]), nopython=True)\n# def remove_drift(vel, nums, masses) -> None:\n#     \"\"\"\n#     Numba'd function to enforce conservation of total linear momentum.\n#     It updates :attr:`sarkas.particles.Particles.vel`.\n#\n#     Parameters\n#     ----------\n#     vel: numpy.ndarray\n#         Particles' velocities.\n#\n#     nums: numpy.ndarray\n#         Number of particles of each species.\n#\n#     masses: numpy.ndarray\n#         Mass of each species.\n#\n#     \"\"\"\n#\n#     P = zeros((len(nums), vel.shape[1]))\n#     species_start = 0\n#     for ic in range(len(nums)):\n#         species_end = species_start + nums[ic]\n#         P[ic, :] = vel[species_start:species_end, :].sum(axis=0) * masses[ic]\n#         species_start = species_end\n#\n#     if P.sum(axis=0).any() > 1e-40:\n#         # Remove tot momentum\n#         species_start = 0\n#         for ic in range(len(nums)):\n#             species_end = species_start + nums[ic]\n#             vel[species_start:species_end, :] -= P[ic, :] / (float(nums[ic]) * masses[ic])\n#             species_start = species_end\n", "meta": {"hexsha": "d687c1e22c9d4b82ddef4f7fd203b345c215fb67", "size": 43796, "ext": "py", "lang": "Python", "max_stars_repo_path": "sarkas/time_evolution/integrators.py", "max_stars_repo_name": "lucianogsilvestri/sarkas", "max_stars_repo_head_hexsha": "f4ab00014d09976561fbd4349b9d0610e47a61e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sarkas/time_evolution/integrators.py", "max_issues_repo_name": "lucianogsilvestri/sarkas", "max_issues_repo_head_hexsha": "f4ab00014d09976561fbd4349b9d0610e47a61e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sarkas/time_evolution/integrators.py", "max_forks_repo_name": "lucianogsilvestri/sarkas", "max_forks_repo_head_hexsha": "f4ab00014d09976561fbd4349b9d0610e47a61e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6761678543, "max_line_length": 127, "alphanum_fraction": 0.585304594, "include": true, "reason": "from numpy,from scipy,from numba", "num_tokens": 11274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.3073580295544412, "lm_q1q2_score": 0.1935662781237855}}
{"text": "import numpy as np\nimport random\nfrom sub_func.get_iou import iou\n\n\n__all__ = ['calc_rpn']\n\n\ndef calc_rpn(config, img_data, width, height, resized_width, resized_height, resize_func):\n    \"\"\"(Important part!) Calculate the rpn for all anchors\n        If feature map has shape 38x50=1900, there are 1900x(3 x 3)=17100 potential anchors\n\n    Args:\n        config: Config instance\n        img_data: augmented image data\n        width: original image width (e.g. 600)\n        height: original image height (e.g. 800)\n        resized_width: resized image width according to config.im_size (e.g. 300)\n        resized_height: resized image height according to config.im_size (e.g. 400)\n        resize_func: function to calculate final layer's feature map (of base model) size according to input image size\n\n    Returns:\n        y_rpn_cls: list(num_bboxes, y_is_box_valid + y_rpn_overlap)\n            y_is_box_valid: 0 or 1 (0 means the box is invalid, 1 means the box is valid)\n            y_rpn_overlap: 0 or 1 (0 means the box is not an object, 1 means the box is an object)\n        y_rpn_regr: list(num_bboxes, 4*y_rpn_overlap + y_rpn_regr)\n            y_rpn_regr: x1,y1,x2,y2 bunding boxes coordinates\n    \"\"\"\n    downscale = float(config.rpn_stride)\n    anchor_sizes = config.anchor_box_scales  # 128, 256, 512\n    anchor_ratios = config.anchor_box_ratios  # 1:1, 1:2*sqrt(2), 2*sqrt(2):1\n    num_anchors = len(anchor_sizes) * len(anchor_ratios)  # 3x3=9\n\n    # calculate the output map size based on the network architecture\n    (output_width, output_height) = resize_func(resized_width, resized_height)\n\n    n_anchratios = len(anchor_ratios)  # 3\n\n    # initialise empty output objectives\n    y_rpn_overlap = np.zeros((output_height, output_width, num_anchors))  # box is object?\n    y_is_box_valid = np.zeros((output_height, output_width, num_anchors))  # box is valid?\n    y_rpn_regr = np.zeros((output_height, output_width, num_anchors * 4))  # bbox coordinates\n\n    num_bboxes = len(img_data['bboxes'])\n\n    num_anchors_for_bbox = np.zeros(num_bboxes).astype(int)  # 각 bbox 마다 anchor 갯수\n    best_anchor_for_bbox = -1 * np.ones((num_bboxes, 4)).astype(int)  # 각 bbox 마다 best anchor (x, y, w, h)\n    best_iou_for_bbox = np.zeros(num_bboxes).astype(np.float32)  # 각 bbox 마다 best IOU\n    best_x_for_bbox = np.zeros((num_bboxes, 4)).astype(int)  # 각 bbox 마다 (x1, x2, y1, y2)\n    best_dx_for_bbox = np.zeros((num_bboxes, 4)).astype(np.float32)  # 각 bbox 마다 (tx, ty, tw, th)\n\n    # get the GT box coordinates, and resize to account for image resizing\n    gta = np.zeros((num_bboxes, 4))\n    for bbox_num, bbox in enumerate(img_data['bboxes']):\n        # get the GT box coordinates, and resize to account for image resizing\n        gta[bbox_num, 0] = bbox['x1'] * (resized_width / float(width))\n        gta[bbox_num, 1] = bbox['x2'] * (resized_width / float(width))\n        gta[bbox_num, 2] = bbox['y1'] * (resized_height / float(height))\n        gta[bbox_num, 3] = bbox['y2'] * (resized_height / float(height))\n\n    # rpn ground truth\n\n    for anchor_size_idx in range(len(anchor_sizes)):\n        for anchor_ratio_idx in range(n_anchratios):\n            anchor_x = anchor_sizes[anchor_size_idx] * anchor_ratios[anchor_ratio_idx][0]\n            anchor_y = anchor_sizes[anchor_size_idx] * anchor_ratios[anchor_ratio_idx][1]\n            # anchor_x, anchor_y : anchor size 에 가로 세율 비율 곱한 값\n\n            for ix in range(output_width):\n                # x-coordinates of the current anchor box\n                x1_anc = downscale * (ix + 0.5) - anchor_x / 2\n                x2_anc = downscale * (ix + 0.5) + anchor_x / 2\n\n                # ignore boxes that go across image boundaries\n                if x1_anc < 0 or x2_anc > resized_width:\n                    continue\n\n                for jy in range(output_height):\n                    # y-coordinates of the current anchor box\n                    y1_anc = downscale * (jy + 0.5) - anchor_y / 2\n                    y2_anc = downscale * (jy + 0.5) + anchor_y / 2\n\n                    # ignore boxes that go across image boundaries\n                    if y1_anc < 0 or y2_anc > resized_height:\n                        continue\n\n                    # bbox_type indicates whether an anchor should be a target\n                    # Initialize with 'negative'\n                    bbox_type = 'neg'\n\n                    # this is the best IOU for the (x,y) coord and the current anchor\n                    # note that this is different from the best IOU for a GT bbox\n                    best_iou_for_loc = 0.0\n\n                    for bbox_num in range(num_bboxes):\n\n                        # get IOU of the current GT box and the current anchor box\n                        gt_coord = [\n                            gta[bbox_num, 0],\n                            gta[bbox_num, 2],\n                            gta[bbox_num, 1],\n                            gta[bbox_num, 3],\n                        ]\n                        anc_coord = [x1_anc, y1_anc, x2_anc, y2_anc]\n                        curr_iou = iou(gt_coord, anc_coord)\n                        # calculate the regression targets if they will be needed\n                        if curr_iou > best_iou_for_bbox[bbox_num] or curr_iou > config.rpn_max_overlap:\n                            # cx, cy : gt 의 중점좌표\n                            cx = (gta[bbox_num, 0] + gta[bbox_num, 1]) / 2.0\n                            cy = (gta[bbox_num, 2] + gta[bbox_num, 3]) / 2.0\n                            # 현재 anchor 의 좌표\n                            cxa = (x1_anc + x2_anc) / 2.0\n                            cya = (y1_anc + y2_anc) / 2.0\n\n                            # x,y are the center point of ground-truth bbox\n                            # xa,ya are the center point of anchor bbox (xa=downscale * (ix + 0.5); ya=downscale * (iy+0.5))\n                            # w,h are the width and height of ground-truth bbox\n                            # wa,ha are the width and height of anchor bboxe\n                            # tx = (x - xa) / wa\n                            # ty = (y - ya) / ha\n                            # tw = log(w / wa)\n                            # th = log(h / ha)\n                            wa = x2_anc - x1_anc\n                            ha = y2_anc - y1_anc\n\n                            tx = (cx - cxa) / wa\n                            ty = (cy - cya) / ha\n                            tw = np.log((gta[bbox_num, 1] - gta[bbox_num, 0]) / wa)\n                            th = np.log((gta[bbox_num, 3] - gta[bbox_num, 2]) / ha)\n\n                        if img_data['bboxes'][bbox_num]['class'] != 'bg':\n                            # all GT boxes should be mapped to an anchor box, so we keep track of which anchor box was best\n                            if curr_iou > best_iou_for_bbox[bbox_num]:\n                                best_anchor_for_bbox[bbox_num] = [jy, ix, anchor_ratio_idx, anchor_size_idx]\n                                best_iou_for_bbox[bbox_num] = curr_iou\n                                best_x_for_bbox[bbox_num,:] = [x1_anc, x2_anc, y1_anc, y2_anc]\n                                best_dx_for_bbox[bbox_num,:] = [tx, ty, tw, th]\n\n                            # we set the anchor to positive if the IOU is >0.7 (it does not matter if there was another better box, it just indicates overlap)\n                            if curr_iou > config.rpn_max_overlap:\n                                bbox_type = 'pos'\n                                num_anchors_for_bbox[bbox_num] += 1\n                                # we update the regression layer target if this IOU is the best for the current (x,y) and anchor position\n                                if curr_iou > best_iou_for_loc:\n                                    best_iou_for_loc = curr_iou\n                                    best_regr = (tx, ty, tw, th)\n\n                            # if the IOU is >0.3 and <0.7, it is ambiguous and no included in the objective\n                            if config.rpn_min_overlap < curr_iou < config.rpn_max_overlap:\n                                # gray zone between neg and pos\n                                if bbox_type != 'pos':\n                                    bbox_type = 'neutral'\n\n                    # turn on or off outputs depending on IOUs\n                    if bbox_type == 'neg':\n                        y_is_box_valid[jy, ix, anchor_ratio_idx + n_anchratios * anchor_size_idx] = 1\n                        y_rpn_overlap[jy, ix, anchor_ratio_idx + n_anchratios * anchor_size_idx] = 0\n                    elif bbox_type == 'neutral':\n                        y_is_box_valid[jy, ix, anchor_ratio_idx + n_anchratios * anchor_size_idx] = 0\n                        y_rpn_overlap[jy, ix, anchor_ratio_idx + n_anchratios * anchor_size_idx] = 0\n                    elif bbox_type == 'pos':\n                        y_is_box_valid[jy, ix, anchor_ratio_idx + n_anchratios * anchor_size_idx] = 1\n                        y_rpn_overlap[jy, ix, anchor_ratio_idx + n_anchratios * anchor_size_idx] = 1\n                        start = 4 * (anchor_ratio_idx + n_anchratios * anchor_size_idx)\n                        y_rpn_regr[jy, ix, start:start+4] = best_regr\n\n    # we ensure that every bbox has at least one positive RPN region\n    for idx in range(num_anchors_for_bbox.shape[0]):\n        if num_anchors_for_bbox[idx] == 0:\n            # no box with an IOU greater than zero ...\n            if best_anchor_for_bbox[idx, 0] == -1:\n                continue\n            y_is_box_valid[\n                best_anchor_for_bbox[idx, 0], best_anchor_for_bbox[idx, 1], best_anchor_for_bbox[idx, 2] + n_anchratios *\n                best_anchor_for_bbox[idx, 3]] = 1\n            y_rpn_overlap[\n                best_anchor_for_bbox[idx, 0], best_anchor_for_bbox[idx, 1], best_anchor_for_bbox[idx, 2] + n_anchratios *\n                best_anchor_for_bbox[idx, 3]] = 1\n            start = 4 * (best_anchor_for_bbox[idx,2] + n_anchratios * best_anchor_for_bbox[idx, 3])\n            y_rpn_regr[\n                best_anchor_for_bbox[idx, 0], best_anchor_for_bbox[idx, 1], start:start+4] = best_dx_for_bbox[idx, :]\n\n    y_rpn_overlap = np.transpose(y_rpn_overlap, (2, 0, 1))\n    y_rpn_overlap = np.expand_dims(y_rpn_overlap, axis=0)\n    # y_rpn_overlap: (1, num_anchors, output_height, output_width)\n\n    y_is_box_valid = np.transpose(y_is_box_valid, (2, 0, 1))\n    y_is_box_valid = np.expand_dims(y_is_box_valid, axis=0)\n    # y_is_box_valid: (1, num_anchors, output_height, output_width)\n\n    y_rpn_regr = np.transpose(y_rpn_regr, (2, 0, 1))\n    y_rpn_regr = np.expand_dims(y_rpn_regr, axis=0)\n    # y_rpn_regr: (1, num_anchros * 4, output_height, output_width)\n\n    pos_locs = np.where(np.logical_and(y_rpn_overlap[0, :, :, :] == 1, y_is_box_valid[0, :, :, :] == 1))\n    neg_locs = np.where(np.logical_and(y_rpn_overlap[0, :, :, :] == 0, y_is_box_valid[0, :, :, :] == 1))\n\n    num_pos = len(pos_locs[0])\n\n    # one issue is that the RPN has many more negative than positive regions,\n    # so we turn off some of the negative regions.\n    # We also limit it to 256 regions.\n    num_regions = 256\n\n    if len(pos_locs[0]) > num_regions / 2:\n        val_locs = random.sample(\n            range(len(pos_locs[0])),\n            len(pos_locs[0])-num_regions/2,\n        )\n        y_is_box_valid[0, pos_locs[0][val_locs], pos_locs[1][val_locs], pos_locs[2][val_locs]] = 0\n        num_pos = num_regions / 2\n\n    if len(neg_locs[0]) + num_pos > num_regions:\n        val_locs = random.sample(\n            range(len(neg_locs[0])),\n            len(neg_locs[0])-num_pos,\n        )\n        y_is_box_valid[0, neg_locs[0][val_locs], neg_locs[1][val_locs], neg_locs[2][val_locs]] = 0\n\n    y_rpn_cls = np.concatenate([y_is_box_valid, y_rpn_overlap], axis=1)\n    y_rpn_regr = np.concatenate([np.repeat(y_rpn_overlap, 4, axis=1), y_rpn_regr], axis=1)\n    return np.copy(y_rpn_cls), np.copy(y_rpn_regr), num_pos\n", "meta": {"hexsha": "7774193797f729dc25377cbd2486b99763ab075a", "size": 11889, "ext": "py", "lang": "Python", "max_stars_repo_path": "train/sub_func/calc_rpn.py", "max_stars_repo_name": "DevBruce/Mask_R-CNN_For_Open_Images_2019", "max_stars_repo_head_hexsha": "00574b20eaf6d228d79fba1575c74f080a4cbf44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "train/sub_func/calc_rpn.py", "max_issues_repo_name": "DevBruce/Mask_R-CNN_For_Open_Images_2019", "max_issues_repo_head_hexsha": "00574b20eaf6d228d79fba1575c74f080a4cbf44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-01-28T22:16:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-28T22:16:56.000Z", "max_forks_repo_path": "train/sub_func/calc_rpn.py", "max_forks_repo_name": "DevBruce/Mask_R-CNN_For_Open_Images_2019", "max_forks_repo_head_hexsha": "00574b20eaf6d228d79fba1575c74f080a4cbf44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.3139013453, "max_line_length": 158, "alphanum_fraction": 0.5635461351, "include": true, "reason": "import numpy", "num_tokens": 3190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.3073580295544412, "lm_q1q2_score": 0.1935662781237855}}
{"text": "\"\"\"\n15N–1HN DQ/ZQ CPMG\n==================\n\nAnalyzes 15N and 1H chemical exchange by applying CPMG pulses on 15N and 1H\nsimultaneously. The spin system is maintained as DQ or ZQ during Trelax, and\nis calculated using the (15n)×(15n), two-spin matrix, where n is the number\nof states::\n\n    {        Ix(a),   Iy(a),   Iz(a),   Sx(a), IxSx(a), IySx(a), IzSx(a),\n      Sy(a), IxSy(a), IySy(a), IzSy(a), Sz(a), IxSz(a), IySz(a), IzSz(a),\n             Ix(b),   Iy(b),   Iz(b),   Sx(b), IxSx(b), IySx(b), IzSx(b),\n      Sy(b), IxSy(b), IySy(b), IzSy(b), Sz(b), IxSz(b), IySz(b), IzSz(b), ... }\n\nThe phase cycle of CPMG pulses is chosen based on νCPMG as described in the\nreference, which is a mixture of constant-phase and XY-family phase cycles.\n\nReferences\n----------\n\nOrekhov, Korzhnev and Kay. J Am Chem Soc (2004) 126:1886-1891\n\n\nNote\n----\n\nA sample configuration file for this module is available using the command::\n\n    $ chemex config cpmg_hn_dq_zq\n\n\"\"\"\nimport functools as ft\n\nimport numpy as np\n\nimport chemex.experiments.helper as ceh\nimport chemex.helper as ch\nimport chemex.nmr.liouvillian as cnl\n\n\n_SCHEMA = {\n    \"type\": \"object\",\n    \"properties\": {\n        \"experiment\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"time_t2\": {\"type\": \"number\"},\n                \"carrier_h\": {\"type\": \"number\"},\n                \"carrier_n\": {\"type\": \"number\"},\n                \"pw90_h\": {\"type\": \"number\"},\n                \"pw90_n\": {\"type\": \"number\"},\n                \"dq_flg\": {\"type\": \"boolean\"},\n                \"observed_state\": {\n                    \"type\": \"string\",\n                    \"pattern\": \"[a-z]\",\n                    \"default\": \"a\",\n                },\n            },\n            \"required\": [\n                \"time_t2\",\n                \"carrier_h\",\n                \"carrier_n\",\n                \"pw90_h\",\n                \"pw90_n\",\n                \"dq_flg\",\n            ],\n        }\n    },\n}\n\n\ndef read(config):\n    ch.validate(config, _SCHEMA)\n    config[\"basis\"] = cnl.Basis(type=\"ixyzsxyz\", spin_system=\"nh\")\n    config[\"fit\"] = _fit_this()\n    return ceh.load_experiment(config=config, pulse_seq_cls=PulseSeq)\n\n\ndef _fit_this():\n    return {\n        \"rates\": [\"r2mq_is_{observed_state}\", \"mu_is_{observed_state}\"],\n        \"model_free\": [\"tauc_{observed_state}\", \"s2_{observed_state}\"],\n    }\n\n\nclass PulseSeq:\n    def __init__(self, config, propagator):\n        self.prop = propagator\n        settings = config[\"experiment\"]\n        self.time_t2 = settings[\"time_t2\"]\n        self.prop.carrier_i = settings[\"carrier_n\"]\n        self.prop.carrier_s = settings[\"carrier_h\"]\n        self.pw90_i = settings[\"pw90_n\"]\n        self.pw90_s = settings[\"pw90_h\"]\n        self.prop.b1_i = 1 / (4.0 * self.pw90_i)\n        self.prop.b1_s = 1 / (4.0 * self.pw90_s)\n        self.dq_flg = settings[\"dq_flg\"]\n        self.prop.detection = self._get_detection(settings[\"observed_state\"])\n\n    @ft.lru_cache(maxsize=10000)\n    def calculate(self, ncycs, params_local):\n        self.prop.update(params_local)\n\n        # Calculation of the propagators corresponding to all the delays\n        tau_cps = self._get_tau_cps(ncycs)\n        tau_cp_list = list(tau_cps.values())\n        delays = dict(zip(tau_cp_list, self.prop.delays(tau_cp_list)))\n        d_cp = {ncyc: delays[delay] for ncyc, delay in tau_cps.items()}\n\n        # Calculation of the propagators corresponding to all the pulses\n        p9024090_1 = self.prop.p9024090_is_1[[0, 1], [0, 1]]\n        p9024090_2 = self.prop.p9024090_is_2[[0, 1], [0, 1]]\n\n        # Getting the starting magnetization\n        start = self.prop.get_start_magnetization([\"2ixsx\"])\n\n        # Calculating the cpmg trains\n        intst = {0: self.prop.detect(start)}\n        for ncyc in set(ncycs) - {0}:\n            phases1, phases2 = self._get_phases(ncyc)\n            echo1 = d_cp[ncyc] @ p9024090_1 @ d_cp[ncyc]\n            echo2 = d_cp[ncyc] @ p9024090_2 @ d_cp[ncyc]\n            cpmg1 = ft.reduce(np.matmul, echo1[phases1])\n            cpmg2 = ft.reduce(np.matmul, echo2[phases2])\n            intst[ncyc] = self.prop.detect(0.5 * (cpmg1 + cpmg2) @ start)\n        return np.array([intst[ncyc] for ncyc in ncycs])\n\n    @ft.lru_cache()\n    def _get_tau_cps(self, ncycs):\n        ncycs_ = np.asarray(ncycs)\n        ncycs_ = ncycs_[ncycs_ > 0]\n        return dict(\n            zip(ncycs_, self.time_t2 / (4.0 * ncycs_) - 7.0 / 3.0 * self.pw90_i)\n        )\n\n    @ft.lru_cache()\n    def _get_phases(self, ncyc):\n        nu_cpmg = self.ncycs_to_nu_cpmgs(ncyc)\n        if nu_cpmg < 51.0:\n            cp_phases1 = [0, 1, 0, 1]\n            cp_phases2 = [1, 0, 1, 0]\n        elif nu_cpmg < 255.0:\n            cp_phases1 = [0]\n            cp_phases2 = [1]\n        else:\n            cp_phases1 = [0, 1, 0, 1, 1, 0, 1, 0]\n            cp_phases2 = [1, 0, 1, 0, 0, 1, 0, 1]\n        phases1 = np.take(cp_phases1, np.flip(np.arange(2 * ncyc)), mode=\"wrap\")\n        phases2 = np.take(cp_phases2, np.flip(np.arange(2 * ncyc)), mode=\"wrap\")\n        return phases1, phases2\n\n    def _get_detection(self, state):\n        if self.dq_flg:\n            return f\"[2ixsx_{state}] - [2iysy_{state}]\"\n        return f\"[2ixsx_{state}] + [2iysy_{state}]\"\n\n    def ncycs_to_nu_cpmgs(self, ncycs):\n        ncycs_ = np.asarray(ncycs)\n        ncycs_ = ncycs_[ncycs_ > 0]\n        return ncycs_ / self.time_t2\n", "meta": {"hexsha": "b2f92b5d97ffe2c3cc452ac45e2b80acf08a9e82", "size": 5337, "ext": "py", "lang": "Python", "max_stars_repo_path": "chemex/experiments/cpmg_hn_dq_zq.py", "max_stars_repo_name": "gbouvignies/ChemEx", "max_stars_repo_head_hexsha": "b1748f1bdc623a1d078de47dffe8cae2515d3411", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2018-09-20T00:33:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-08T10:21:27.000Z", "max_issues_repo_path": "chemex/experiments/cpmg_hn_dq_zq.py", "max_issues_repo_name": "gbouvignies/ChemEx", "max_issues_repo_head_hexsha": "b1748f1bdc623a1d078de47dffe8cae2515d3411", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2018-09-17T12:01:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T13:40:48.000Z", "max_forks_repo_path": "chemex/experiments/cpmg_hn_dq_zq.py", "max_forks_repo_name": "gbouvignies/ChemEx", "max_forks_repo_head_hexsha": "b1748f1bdc623a1d078de47dffe8cae2515d3411", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-09-17T13:50:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-23T07:39:10.000Z", "avg_line_length": 33.149068323, "max_line_length": 80, "alphanum_fraction": 0.5617388046, "include": true, "reason": "import numpy", "num_tokens": 1666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.19338473914457557}}
{"text": "# -*- coding: utf-8 -*-\n'''This module provides a user-friendly pythonic wrapper for the low-level C interface functions.'''\n\nfrom __future__ import division, print_function, absolute_import, unicode_literals\n\nimport datetime as dt\nimport calendar\nimport warnings\n\nimport numpy as np\n\nfrom aacgm2._aacgmv2 import A2G, TRACE, BADIDEA, ALLOWTRACE, GEOCENTRIC, setDateTime, aacgmConvert\nfrom aacgm2 import IGRF_12_COEFFS\n\naacgmConvert_vectorized = np.vectorize(aacgmConvert)\n\n\ndef convert(lat, lon, alt, date=None, a2g=False, trace=False, allowtrace=False, badidea=False, geocentric=False):\n    '''Converts to/from geomagnetic coordinates.\n\n    This is a user-friendly pythonic wrapper for the low-level C interface\n    functions available in :mod:`aacgm2._aacgmv2`.\n\n    Parameters\n    ==========\n    lat,lon,alt : array_like\n        Input latitude(s), longitude(s) and altitude(s). They must be\n        `broadcastable to the same shape <http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html>`_.\n    date : :class:`datetime.date`/:class:`datetime.datetime`, optional\n        The date/time to use for the magnetic field model, default ``None`` (uses\n        current time). Must be between 1900 and 2020.\n    a2g : bool, optional\n        Convert from AACGM-v2 to geographic coordinates, default ``False``\n        (converts geographic to AACGM-v2).\n    trace : bool, optional\n        Use field-line tracing, default ``False`` (uses coefficients). Tracing\n        is more precise and needed at altitudes > 2000 km, but significantly\n        slower.\n    allowtrace : bool, optional\n        Automatically use field-line tracing above 2000 km, default ``False``\n        (raises an exception for these altitudes unless ``trace=True`` or\n        ``badidea=True``).\n    badidea : bool, optional\n        Allow use of coefficients above 2000 km (bad idea!)\n    geocentric : bool, optional\n        Assume inputs are geocentric with Earth radius 6371.2 km.\n\n    Returns\n    =======\n\n    lat_out : ``numpy.ndarray``\n        Converted latitude\n    lon_out : ``numpy.ndarray``\n        Converted longitude\n    alt_out : ``numpy.ndarray``\n        Converted altitude\n\n    Raises\n    ======\n\n    ValueError\n        if max(alt) > 2000 and neither of `trace`, `allowtrace`, or `badidea` is ``True``\n    ValueError\n        if latitude is outside the range -90 to +90 degrees\n    RuntimeError\n        if there was a problem in the C extension\n\n    Notes\n    =====\n\n    This function exclusively relies on the `AACGM-v2 C library\n    <https://engineering.dartmouth.edu/superdarn/aacgm.html>`_. Specifically,\n    it calls the functions :func:`_aacgmv2.setDateTime` and\n    :func:`_aacgmv2.aacgmConvert`, which are simple interfaces to the\n    C library functions :func:`AACGM_v2_SetDateTime` and\n    :func:`AACGM_v2_Convert`. Details of the techniques used to derive the\n    AACGM-v2 coefficients are described by Shepherd, 2014 [1]_.\n\n    .. [1] Shepherd, S. G. (2014), Altitude-adjusted corrected geomagnetic\n       coordinates: Definition and functional approximations,\n       J. Geophys. Res. Space Physics, 119, 7501--7521,\n       doi:`10.1002/2014JA020264 <http://dx.doi.org/10.1002/2014JA020264>`_.\n\n   '''\n\n    # check values\n    if np.min(alt) < 0:\n        warnings.warn('Coordinate transformations are not intended for altitudes < 0 km', UserWarning)\n\n    if np.max(alt) > 2000 and not (trace or allowtrace or badidea):\n        raise ValueError('Coefficients are not valid for altitudes above 2000 km. You must either use field-line '\n                         'tracing (trace=True or allowtrace=True) or indicate you know this is a bad idea '\n                         '(badidea=True)')\n\n    # check if latitudes are > 90.1 (to allow some room for rounding errors, which will be clipped)\n    if np.max(np.abs(lat)) > 90.1:\n        raise ValueError('Latitude must be in the range -90 to +90 degrees')\n    np.clip(lat, -90, 90)\n\n    # constrain longitudes between -180 and 180\n    lon = ((np.asarray(lon) + 180) % 360) - 180\n\n    # set to current date if none is given\n    if date is None:\n        date = dt.datetime.now()\n\n    # add time info if only date is given\n    if isinstance(date, dt.date):\n        date = dt.datetime.combine(date, dt.time(0))\n\n    # set current date and time\n    setDateTime(date.year, date.month, date.day, date.hour, date.minute, date.second)\n\n    # make flag\n    flag = A2G*a2g + TRACE*trace + ALLOWTRACE*allowtrace + BADIDEA*badidea + GEOCENTRIC*geocentric\n\n    # convert\n    lat_out, lon_out, alt_out = aacgmConvert_vectorized(lat, lon, alt, flag)\n\n    return lat_out, lon_out, alt_out\n\n\ndef convert_mlt(arr, datetime, m2a=False):\n    '''Converts between magnetic local time (MLT) and AACGM-v2 longitude.\n\n    .. note:: This function is not related to the AACGM-v2 C library, but is provided as\n              a convenience in the hopes that it might be useful for some purposes.\n\n    Parameters\n    ==========\n    arr : array_like or float\n        Magnetic longitudes or MLTs to convert.\n    datetime : :class:`datetime.datetime`\n        Date and time for MLT conversion in Universal Time (UT).\n    m2a : bool\n        Convert MLT to AACGM-v2 longitude (default is ``False``, which implies\n        conversion from AACGM-v2 longitude to MLT).\n\n    Returns\n    =======\n    out : numpy.ndarray\n        Converted coordinates/MLT\n\n    Notes\n    =====\n\n    The MLT conversion is not part of the AACGM-v2 C library and is instead based\n    on Laundal et al., 2016 [1]_. A brief summary of the method is provided below.\n\n    MLT is defined as\n\n        MLT = (magnetic longitude - magnetic noon meridian longitude) / 15 + 12\n\n    where the magnetic noon meridian longitude is the centered dipole longitude\n    of the subsolar point.\n\n    There are two important reasons for using centered dipole instead of AACGM for\n    this calculation. One reason is that the AACGM longitude of the subsolar point\n    is often undefined (being at low latitudes). More importantly, if the subsolar\n    point close to ground was used, the MLT at polar latitudes would be affected\n    by non-dipole features at low latitudes, such as the South Atlantic Anomaly.\n    This is not desirable; since the Sun-Earth interaction takes place at polar\n    field lines, it is these field lines the MLT should describe.\n\n    In calculating the centered dipole longitude of the subsolar point, we use\n    the first three IGRF Gauss coefficients, using linear interpolation between\n    the model updates every five years.\n\n    Both input and output MLON are taken modulo 360 to ensure they are between\n    0 and 360 degrees. Similarly, input/output MLT are taken modulo 24.\n    For implementation of the subsolar point calculation, see :func:`subsol`.\n\n    .. [1] Laundal, K. M. and A. D. Richmond (2016), Magnetic Coordinate Systems,\n       Space Sci. Rev., doi:`10.1007/s11214-016-0275-y <http://dx.doi.org/10.1007/s11214-016-0275-y>`_.\n\n    '''\n    d2r = np.pi/180\n\n    # find subsolar point\n    yr = datetime.year\n    doy = datetime.timetuple().tm_yday\n    ssm = datetime.hour*3600 + datetime.minute*60 + datetime.second\n    subsol_lon, subsol_lat = subsol(yr, doy, ssm)\n\n    # unit vector pointing at subsolar point:\n    s = np.array([np.cos(subsol_lat * d2r) * np.cos(subsol_lon * d2r),\n                  np.cos(subsol_lat * d2r) * np.sin(subsol_lon * d2r),\n                  np.sin(subsol_lat * d2r)])\n\n    # convert subsolar coordinates to centered dipole coordinates\n    z = igrf_dipole_axis(datetime)  # Cartesian axis pointing at Northern dipole pole\n    y = np.cross(np.array([0, 0, 1]), z)\n    y = y/np.linalg.norm(y)\n    x = np.cross(y, z)\n    R = np.vstack((x, y, z))\n    s_cd = R.dot(s)\n\n    # centered dipole longitude of subsolar point:\n    mlon_subsol = np.arctan2(s_cd[1], s_cd[0])/d2r\n\n    # convert the input array\n    if m2a:  # MLT to AACGM\n        mlt = np.asarray(arr) % 24\n        mlon = (15*(mlt - 12) + mlon_subsol) % 360\n        return mlon\n    else:  # AACGM to MLT\n        mlon = np.asarray(arr) % 360\n        mlt = ((mlon - mlon_subsol)/15 + 12) % 24\n        return mlt\n\n\ndef subsol(year, doy, ut):\n    '''Finds subsolar geocentric longitude and latitude.\n\n    Helper function for :func:`convert_mlt`.\n\n    Parameters\n    ==========\n    year : int [1601, 2100]\n        Calendar year\n    doy : int [1, 365/366]\n        Day of year\n    ut : float\n        Seconds since midnight on the specified day\n\n    Returns\n    =======\n    sbsllon : float\n        Subsolar longitude for the given date/time\n    sbsllat : float\n        Subsolar latitude for the given date/time\n\n    Notes\n    =====\n\n    Based on formulas in Astronomical Almanac for the year 1996, p. C24.\n    (U.S. Government Printing Office, 1994). Usable for years 1601-2100,\n    inclusive. According to the Almanac, results are good to at least 0.01\n    degree latitude and 0.025 degrees longitude between years 1950 and 2050.\n    Accuracy for other years has not been tested. Every day is assumed to have\n    exactly 86400 seconds; thus leap seconds that sometimes occur on December\n    31 are ignored (their effect is below the accuracy threshold of the\n    algorithm).\n\n    After Fortran code by A. D. Richmond, NCAR. Translated from IDL\n    by K. Laundal.\n\n    '''\n\n    from numpy import sin, cos, pi, arctan2, arcsin\n\n    yr = year - 2000\n\n    if year >= 2101:\n        print('subsol.py: subsol invalid after 2100. Input year is:', year)\n\n    nleap = np.floor((year-1601)/4)\n    nleap = nleap - 99\n    if year <= 1900:\n        if year <= 1600:\n            print('subsol.py: subsol invalid before 1601. Input year is:', year)\n        ncent = np.floor((year-1601)/100)\n        ncent = 3 - ncent\n        nleap = nleap + ncent\n\n    l0 = -79.549 + (-0.238699*(yr-4*nleap) + 3.08514e-2*nleap)\n\n    g0 = -2.472 + (-0.2558905*(yr-4*nleap) - 3.79617e-2*nleap)\n\n    # Days (including fraction) since 12 UT on January 1 of IYR:\n    df = (ut/86400 - 1.5) + doy\n\n    # Addition to Mean longitude of Sun since January 1 of IYR:\n    lf = 0.9856474*df\n\n    # Addition to Mean anomaly since January 1 of IYR:\n    gf = 0.9856003*df\n\n    # Mean longitude of Sun:\n    l = l0 + lf\n\n    # Mean anomaly:\n    g = g0 + gf\n    grad = g*pi/180\n\n    # Ecliptic longitude:\n    lmbda = l + 1.915*sin(grad) + 0.020*sin(2*grad)\n    lmrad = lmbda*pi/180\n    sinlm = sin(lmrad)\n\n    # Days (including fraction) since 12 UT on January 1 of 2000:\n    n = df + 365*yr + nleap\n\n    # Obliquity of ecliptic:\n    epsilon = 23.439 - 4e-7*n\n    epsrad = epsilon*pi/180\n\n    # Right ascension:\n    alpha = arctan2(cos(epsrad)*sinlm, cos(lmrad)) * 180/pi\n\n    # Declination:\n    delta = arcsin(sin(epsrad)*sinlm) * 180/pi\n\n    # Subsolar latitude:\n    sbsllat = delta\n\n    # Equation of time (degrees):\n    etdeg = l - alpha\n    nrot = round(etdeg/360)\n    etdeg = etdeg - 360*nrot\n\n    # Apparent time (degrees):\n    aptime = ut/240 + etdeg    # Earth rotates one degree every 240 s.\n\n    # Subsolar longitude:\n    sbsllon = 180 - aptime\n    nrot = round(sbsllon/360)\n    sbsllon = sbsllon - 360*nrot\n\n    return sbsllon, sbsllat\n\n\ndef gc2gd_lat(gc_lat):\n    '''Convert geocentric latitude to geodetic latitude using WGS84.\n\n    Parameters\n    ==========\n    gc_lat : array_like or float\n        Geocentric latitude\n\n    Returns\n    =======\n    gd_lat : same as input\n        Geodetic latitude\n\n    '''\n    WGS84_e2 = 0.006694379990141317\n    return np.rad2deg(-np.arctan(np.tan(np.deg2rad(gc_lat))/(WGS84_e2 - 1)))\n\n\ndef igrf_dipole_axis(date):\n    '''Get Cartesian unit vector pointing at dipole pole in the north, according to IGRF\n\n    Parameters\n    ==========\n    date : :class:`datetime.datetime`\n        Date and time\n\n    Returns\n    =======\n    m: numpy.ndarray\n        Cartesian 3 element vector pointing at dipole pole in the north (geocentric coords)\n\n    Notes\n    =====\n    IGRF coefficients are read from the igrf12coeffs.txt file. It should also work after IGRF updates.\n    The dipole coefficients are interpolated to the date, or extrapolated if date > latest IGRF model\n    '''\n\n    # get time in years, as float:\n    year = date.year\n    doy = date.timetuple().tm_yday\n    year = year + doy/(365 + calendar.isleap(year))\n\n    # read the IGRF coefficients\n    with open(IGRF_12_COEFFS, 'r') as f:\n        lines = f.readlines()\n\n    years = lines[3].split()[3:][:-1]\n    years = np.array(years, dtype=float)  # time array\n\n    g10 = lines[4].split()[3:]\n    g11 = lines[5].split()[3:]\n    h11 = lines[6].split()[3:]\n\n    # secular variation coefficients (for extrapolation)\n    g10sv = np.float32(g10[-1])\n    g11sv = np.float32(g11[-1])\n    h11sv = np.float32(h11[-1])\n\n    # model coefficients:\n    g10 = np.array(g10[:-1], dtype=float)\n    g11 = np.array(g11[:-1], dtype=float)\n    h11 = np.array(h11[:-1], dtype=float)\n\n    # get the gauss coefficient at given time:\n    if year <= years[-1]:  # regular interpolation\n        g10 = np.interp(year, years, g10)\n        g11 = np.interp(year, years, g11)\n        h11 = np.interp(year, years, h11)\n    else:  # extrapolation\n        dt = year - years[-1]\n        g10 = g10[-1] + g10sv * dt\n        g11 = g11[-1] + g11sv * dt\n        h11 = h11[-1] + h11sv * dt\n\n    # calculate pole position\n    B0 = np.sqrt(g10**2 + g11**2 + h11**2)\n\n    return -np.array([g11, h11, g10])/B0\n", "meta": {"hexsha": "b48e4131babf756886763f066ea677048e7ccb3d", "size": 13272, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/aacgm2/wrapper.py", "max_stars_repo_name": "st-bender/aacgmv2", "max_stars_repo_head_hexsha": "edbdb362be04443e0faff083e8bf5bd63a044b65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/aacgm2/wrapper.py", "max_issues_repo_name": "st-bender/aacgmv2", "max_issues_repo_head_hexsha": "edbdb362be04443e0faff083e8bf5bd63a044b65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-26T17:42:27.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-26T17:42:27.000Z", "max_forks_repo_path": "src/aacgm2/wrapper.py", "max_forks_repo_name": "st-bender/aacgmv2", "max_forks_repo_head_hexsha": "edbdb362be04443e0faff083e8bf5bd63a044b65", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-05-26T17:34:42.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-26T17:34:42.000Z", "avg_line_length": 33.0972568579, "max_line_length": 114, "alphanum_fraction": 0.650994575, "include": true, "reason": "import numpy,from numpy", "num_tokens": 3803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.34158250614097546, "lm_q1q2_score": 0.19334203477576667}}
{"text": "\"\"\"\n Copyright (c) 2019 Intel Corporation\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n      http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n\nimport numpy as np\nfrom scipy.optimize import linear_sum_assignment\n\n\nclass Detection:\n    \"\"\"Class that stores detected object\"\"\"\n\n    def __init__(self, obj_id, roi, conf, waiting=0, duration=1):\n        \"\"\"Constructor\"\"\"\n\n        self.id = obj_id\n        self.roi = roi\n        self.conf = conf\n        self.waiting = waiting\n        self.duration = duration\n\n    @property\n    def roi(self):\n        \"\"\"Returns ROI of detected object\"\"\"\n\n        return self._roi\n\n    @roi.setter\n    def roi(self, roi):\n        \"\"\"Sets ROI of detected object\"\"\"\n\n        self._roi = np.copy(roi.reshape(1, -1))\n\n\nclass Tracker:  # pylint: disable=too-few-public-methods\n    \"\"\"Class that carries out tracking of persons using Hungarian algorithm\"\"\"\n\n    def __init__(self, detector, score_threshold, iou_threshold, smooth_weight=0.5, max_waiting=5):\n        \"\"\"Constructor\"\"\"\n\n        self._detector = detector\n        self._score_threshold = score_threshold\n        self._iou_threshold = iou_threshold\n        self._smooth_weight = smooth_weight\n        self._max_waiting = max_waiting\n\n        self._last_detections = []\n        self._cur_req_id, self._next_req_id = 0, 1\n        self._last_id = 0\n\n    @staticmethod\n    def _matrix_iou(set_a, set_b):\n        \"\"\"Computes IoU metric for the two sets of vectors\"\"\"\n\n        intersect_ymin = np.maximum(set_a[:, 0].reshape([-1, 1]), set_b[:, 0].reshape([1, -1]))\n        intersect_xmin = np.maximum(set_a[:, 1].reshape([-1, 1]), set_b[:, 1].reshape([1, -1]))\n        intersect_ymax = np.minimum(set_a[:, 2].reshape([-1, 1]), set_b[:, 2].reshape([1, -1]))\n        intersect_xmax = np.minimum(set_a[:, 3].reshape([-1, 1]), set_b[:, 3].reshape([1, -1]))\n\n        intersect_heights = np.maximum(0.0, intersect_ymax - intersect_ymin)\n        intersect_widths = np.maximum(0.0, intersect_xmax - intersect_xmin)\n        intersect_areas = intersect_heights * intersect_widths\n\n        areas_set_a = ((set_a[:, 2] - set_a[:, 0]) * (set_a[:, 3] - set_a[:, 1])).reshape([-1, 1])\n        areas_set_b = ((set_b[:, 2] - set_b[:, 0]) * (set_b[:, 3] - set_b[:, 1])).reshape([1, -1])\n\n        union_areas = areas_set_a + areas_set_b - intersect_areas\n\n        return intersect_areas / union_areas\n\n    @staticmethod\n    def filter_rois(new_rois, score_threshold):\n        \"\"\"Filters input ROIs by valid height/width and score threshold values\"\"\"\n\n        heights = new_rois[:, 2] - new_rois[:, 0]\n        widths = new_rois[:, 3] - new_rois[:, 1]\n        valid_sizes_mask = np.logical_and(heights > 0.0, widths > 0.0)\n        valid_conf_mask = new_rois[:, 4] > score_threshold\n\n        valid_roi_ids = np.where(np.logical_and(valid_sizes_mask, valid_conf_mask))[0]\n        filtered_rois = new_rois[valid_roi_ids, :4]\n        filtered_conf = new_rois[valid_roi_ids, 4]\n\n        return filtered_rois, filtered_conf\n\n    def _track(self, last_detections, new_rois):\n        \"\"\"Updates current tracks according new observations\"\"\"\n\n        filtered_rois, filtered_conf = self.filter_rois(new_rois, self._score_threshold)\n\n        if filtered_rois.shape[0] == 0:\n            out_detections = []\n            for det in last_detections:\n                det.waiting = 1\n                det.duration = 0\n                out_detections.append(det)\n\n            return out_detections\n\n        if last_detections is None or len(last_detections) == 0:\n            out_detections = []\n            for roi, conf in zip(filtered_rois, filtered_conf):\n                out_detections.append(Detection(self._last_id, roi.reshape(1, -1), conf))\n                self._last_id += 1\n\n            return out_detections\n\n        last_rois = np.concatenate([det.roi for det in last_detections], axis=0)\n        affinity_matrix = self._matrix_iou(last_rois, filtered_rois)\n        cost_matrix = 1.0 - affinity_matrix\n\n        row_ind, col_ind = linear_sum_assignment(cost_matrix)\n        affinity_values = 1.0 - cost_matrix[row_ind, col_ind]\n\n        valid_matches = affinity_values > self._iou_threshold\n        row_ind = row_ind[valid_matches]\n        col_ind = col_ind[valid_matches]\n\n        out_detections = []\n        for src_id, trg_id in zip(row_ind, col_ind):\n            det = last_detections[src_id]\n            det.waiting = 0\n            det.duration += 1\n            new_roi = filtered_rois[trg_id]\n            det.roi = self._smooth_roi(det.roi, new_roi.reshape(1, -1), self._smooth_weight)\n            det.conf = filtered_conf[trg_id]\n            out_detections.append(det)\n\n        unmatched_src_ind = set(range(len(last_detections))) - set(row_ind.tolist())\n        for src_id in unmatched_src_ind:\n            det = last_detections[src_id]\n            det.waiting += 1\n            det.duration = 0\n            if det.waiting < self._max_waiting:\n                out_detections.append(det)\n\n        unmatched_trg_ind = set(range(len(filtered_rois))) - set(col_ind.tolist())\n        for trg_id in unmatched_trg_ind:\n            new_roi = filtered_rois[trg_id]\n            new_roi_conf = filtered_conf[trg_id]\n            out_detections.append(Detection(self._last_id, new_roi.reshape(1, -1), new_roi_conf))\n            self._last_id += 1\n\n        return out_detections\n\n    @staticmethod\n    def _smooth_roi(prev_roi, new_roi, weight):\n        \"\"\"Smooths tracking ROI\"\"\"\n\n        if prev_roi is None:\n            return new_roi\n\n        return weight * prev_roi + (1.0 - weight) * new_roi\n\n    @staticmethod\n    def _clip_roi(roi, frame_size):\n        \"\"\"Clips ROI limits according frame sizes\"\"\"\n\n        frame_height, frame_width = frame_size\n\n        old_roi = roi.reshape(-1)\n        new_roi = [np.maximum(0, int(old_roi[0])),\n                   np.maximum(0, int(old_roi[1])),\n                   np.minimum(frame_width, int(old_roi[2])),\n                   np.minimum(frame_height, int(old_roi[3]))]\n\n        return np.array(new_roi)\n\n    def _get_last_detections(self, frame_size, max_num_detections, labels_map):\n        \"\"\"Returns active detections\"\"\"\n\n        if self._last_detections is None or len(self._last_detections) == 0:\n            return [], {}\n\n        out_detections = []\n        for det in self._last_detections:\n            if det.waiting > 0 or det.duration <= 1:\n                continue\n\n            clipped_roi = self._clip_roi(det.roi, frame_size)\n            out_det = Detection(det.id, clipped_roi, det.conf, det.waiting, det.duration)\n            out_detections.append(out_det)\n\n        if len(out_detections) > max_num_detections:\n            out_detections.sort(key=lambda x: x.conf, reverse=True)\n            out_detections = out_detections[:max_num_detections]\n\n        matched_det_ids = {det.id for det in out_detections} & labels_map.keys()\n        unused_det_ids = sorted(set(range(max_num_detections)) - matched_det_ids)\n\n        out_labels_map = {}\n        for det in out_detections:\n            if det.id in matched_det_ids:\n                out_labels_map[det.id] = labels_map[det.id]\n            else:\n                new_local_det_id = unused_det_ids[0]\n                unused_det_ids = unused_det_ids[1:]\n\n                out_labels_map[det.id] = new_local_det_id\n                det.id = new_local_det_id\n\n        return out_detections, labels_map\n\n    def add_frame(self, frame, max_num_detections, labels_map):\n        \"\"\"Adds new detections and returns active tracks\"\"\"\n\n        self._detector.async_infer(frame, self._next_req_id)\n        new_rois = self._detector.wait_request(self._cur_req_id)\n        self._cur_req_id, self._next_req_id = self._next_req_id, self._cur_req_id\n\n        if new_rois is not None:\n            self._last_detections = self._track(self._last_detections, new_rois)\n\n        frame_size = frame.shape[:2]\n        out_detections, out_labels_map = self._get_last_detections(\n            frame_size, max_num_detections, labels_map)\n\n        return out_detections, out_labels_map\n", "meta": {"hexsha": "4893e9e2c0fab212d1cff20d292cecc14ada716b", "size": 8443, "ext": "py", "lang": "Python", "max_stars_repo_path": "gesture_recognition_demo/tracker.py", "max_stars_repo_name": "JHP4911/Gesture-Triggered-Alarm-on-Pi-or-Jetson-Nano", "max_stars_repo_head_hexsha": "1e9416c2baeaf40dfc87b2f0263076f7ca79183d", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2201, "max_stars_repo_stars_event_min_datetime": "2018-10-15T14:37:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-16T02:05:51.000Z", "max_issues_repo_path": "gesture_recognition_demo/tracker.py", "max_issues_repo_name": "JHP4911/Gesture-Triggered-Alarm-on-Pi-or-Jetson-Nano", "max_issues_repo_head_hexsha": "1e9416c2baeaf40dfc87b2f0263076f7ca79183d", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 966, "max_issues_repo_issues_event_min_datetime": "2020-07-16T08:13:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T18:09:18.000Z", "max_forks_repo_path": "gesture_recognition_demo/tracker.py", "max_forks_repo_name": "JHP4911/Gesture-Triggered-Alarm-on-Pi-or-Jetson-Nano", "max_forks_repo_head_hexsha": "1e9416c2baeaf40dfc87b2f0263076f7ca79183d", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 808, "max_forks_repo_forks_event_min_datetime": "2018-10-16T14:03:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-15T11:41:45.000Z", "avg_line_length": 36.7086956522, "max_line_length": 99, "alphanum_fraction": 0.635200758, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.1933420335683572}}
{"text": "import numpy as np\nimport numpy.linalg as la\nimport scipy.sparse as SP\nimport scipy\nfrom scipy.sparse import linalg as SPla\n\ndef spdot(a, b, array_out=True):\n    \"\"\"\n    Matrix multiplication function to deal with sparse and dense objects\n\n    Parameters\n    ----------\n\n    a           : array\n                  first multiplication factor. Can either be sparse or dense.\n    b           : array\n                  second multiplication factor. Can either be sparse or dense.\n    array_out   : boolean\n                  If True (default) the output object is always a np.array\n\n    Returns\n    -------\n\n    ab : array\n         product of a times b. Sparse if a and b are sparse. Dense otherwise.\n    \"\"\"\n    if type(a).__name__ == 'ndarray' and type(b).__name__ == 'ndarray':\n        ab = np.dot(a, b)\n    elif type(a).__name__ == 'csr_matrix' or type(b).__name__ == 'csr_matrix' \\\n            or type(a).__name__ == 'csc_matrix' or type(b).__name__ == 'csc_matrix':\n        ab = a * b\n        if array_out:\n            if type(ab).__name__ == 'csc_matrix' or type(ab).__name__ == 'csr_matrix':\n                ab = ab.toarray()\n    else:\n        raise Exception, \"Invalid format for 'spdot' argument: %s and %s\" % (\n            type(a).__name__, type(b).__name__)\n    return ab\n\n\ndef spmultiply(a, b, array_out=True):\n    \"\"\"\n    Element-wise multiplication function to deal with sparse and dense\n    objects. Both objects must be of the same type.\n\n    Parameters\n    ----------\n\n    a           : array\n                  first multiplication factor. Can either be sparse or dense.\n    b           : array\n                  second multiplication factor. Can either be sparse or dense.\n                  integer.\n    array_out   : boolean\n                  If True (default) the output object is always a np.array\n\n    Returns\n    -------\n\n    ab : array\n         elementwise multiplied object. Sparse if a is sparse. Dense otherwise.\n    \"\"\"\n    if type(a).__name__ == 'ndarray' and type(b).__name__ == 'ndarray':\n        ab = a * b\n    elif (type(a).__name__ == 'csr_matrix' or type(a).__name__ == 'csc_matrix') \\\n            and (type(b).__name__ == 'csr_matrix' or type(b).__name__ == 'csc_matrix'):\n        ab = a.multiply(b)\n        if array_out:\n            if type(ab).__name__ == 'csc_matrix' or type(ab).__name__ == 'csr_matrix':\n                ab = ab.toarray()\n    else:\n        raise Exception, \"Invalid format for 'spmultiply' argument: %s and %s\" % (\n            type(a).__name__, type(b).__name__)\n    return ab\n\n\ndef sphstack(a, b, array_out=False):\n    \"\"\"\n    Horizontal stacking of vectors (or matrices) to deal with sparse and dense objects\n\n    Parameters\n    ----------\n\n    a           : array or sparse matrix\n                  First object.\n    b           : array or sparse matrix\n                  Object to be stacked next to a\n    array_out   : boolean\n                  If True the output object is a np.array; if False (default)\n                  the output object is an np.array if both inputs are\n                  arrays or CSR matrix if at least one input is a CSR matrix\n\n    Returns\n    -------\n\n    ab          : array or sparse matrix\n                  Horizontally stacked objects\n    \"\"\"\n    if type(a).__name__ == 'ndarray' and type(b).__name__ == 'ndarray':\n        ab = np.hstack((a, b))\n    elif type(a).__name__ == 'csr_matrix' or type(b).__name__ == 'csr_matrix':\n        ab = SP.hstack((a, b), format='csr')\n        if array_out:\n            if type(ab).__name__ == 'csr_matrix':\n                ab = ab.toarray()\n    else:\n        raise Exception, \"Invalid format for 'sphstack' argument: %s and %s\" % (\n            type(a).__name__, type(b).__name__)\n    return ab\n\n\ndef spbroadcast(a, b, array_out=False):\n    \"\"\"\n    Element-wise multiplication of a matrix and vector to deal with sparse \n    and dense objects\n\n    Parameters\n    ----------\n\n    a           : array or sparse matrix\n                  Object with one or more columns.\n    b           : array\n                  Object with only one column\n    array_out   : boolean\n                  If True the output object is a np.array; if False (default)\n                  the output object is an np.array if both inputs are\n                  arrays or CSR matrix if at least one input is a CSR matrix\n\n    Returns\n    -------\n\n    ab          : array or sparse matrix\n                  Element-wise multiplication of a and b\n    \"\"\"\n    if type(a).__name__ == 'ndarray' and type(b).__name__ == 'ndarray':\n        ab = a * b\n    elif type(a).__name__ == 'csr_matrix':\n        b_mod = SP.lil_matrix((b.shape[0], b.shape[0]))\n        b_mod.setdiag(b)\n        ab = (a.T * b_mod).T\n        if array_out:\n            if type(ab).__name__ == 'csr_matrix':\n                ab = ab.toarray()\n    else:\n        raise Exception, \"Invalid format for 'spbroadcast' argument: %s and %s\" % (\n            type(a).__name__, type(b).__name__)\n    return ab\n\n\ndef spmin(a):\n    \"\"\"\n    Minimum value in a matrix or vector to deal with sparse and dense objects\n\n    Parameters\n    ----------\n\n    a           : array or sparse matrix\n                  Object with one or more columns.\n\n    Returns\n    -------\n\n    min a       : int or float\n                  minimum value in a\n    \"\"\"\n    return a.min()\n\ndef spmax(a):\n    \"\"\"\n    Maximum value in a matrix or vector to deal with sparse and dense objects\n\n    Parameters\n    ----------\n\n    a           : array or sparse matrix\n                  Object with one or more columns.\n\n    Returns\n    -------\n\n    max a       : int or float\n                  maximum value in a\n    \"\"\"\n    return a.max()\n\ndef splogdet(a):\n    \"\"\"\n    Compute the log determinant of a large matrix. \n\n    Parameters\n    ----------\n\n    a       :   array or sparse matrix\n                Object with one or more columns\n\n    Returns\n    -------\n\n    log determinant of a    :   int or float\n                                logged determinant of a\n    \"\"\"\n    if SP.issparse(a):\n        LU = SPla.splu(a)\n        det = np.sum(np.log(np.abs(LU.U.diagonal())))\n    else:\n        sgn, ldet = la.slogdet(a)\n        det = sgn * ldet\n    return det\n\ndef spfill_diagonal(a, val):\n    \"\"\"\n    Fill the diagonal of a sparse or dense matrix\n\n    Parameters\n    ----------\n\n    a       :   array or sparse matrix\n                Object with one or more columns\n    val     :   int or float\n                value with which to fill the diagonal of a\n\n    Returns\n    -------\n\n    a with val on each element of the diagonal\n    \"\"\"\n    if SP.issparse(a):\n        a.setdiag(val)\n    else:\n        np.fill_diagonal(a, val)\n    return a\n\ndef spinv(a):\n    \"\"\"\n    Compute the inverse of a sparse or dense matrix\n\n    Parameters\n    ----------\n\n    a       :   array or sparse matrix\n                Object with one or more columns\n    \n    Returns\n    -------\n\n    ai, the inverse of a\n    \"\"\"\n    if SP.issparse(a):\n        ai = SPla.inv(a)\n    else:\n        ai = la.inv(a)\n    return ai\n\ndef spisfinite(a):\n    \"\"\"\n    Determine whether an array has nan or inf values\n\n    Parameters\n    ----------\n    a   :   array or sparse matrix\n            Object with one or more columns\n\n    Returns\n    -------\n    bool denoting whether or not the array contains any NaN or inf\n    \"\"\"\n    return np.isfinite(a.sum())\n\ndef _test():\n    import doctest\n    doctest.testmod()\n\nif __name__ == '__main__':\n    _test()\n\n", "meta": {"hexsha": "0fde0e9d5c27b6a5a2c52cbf8ea15430c54fa14f", "size": 7410, "ext": "py", "lang": "Python", "max_stars_repo_path": "pysal/spreg/sputils.py", "max_stars_repo_name": "cubensys/pysal", "max_stars_repo_head_hexsha": "8d50990f6e6603ba79ae1a887a20a1e3a0734e51", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pysal/spreg/sputils.py", "max_issues_repo_name": "cubensys/pysal", "max_issues_repo_head_hexsha": "8d50990f6e6603ba79ae1a887a20a1e3a0734e51", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pysal/spreg/sputils.py", "max_forks_repo_name": "cubensys/pysal", "max_forks_repo_head_hexsha": "8d50990f6e6603ba79ae1a887a20a1e3a0734e51", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-19T01:46:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-19T01:46:17.000Z", "avg_line_length": 26.847826087, "max_line_length": 87, "alphanum_fraction": 0.5457489879, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 1759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961016, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.19334202598069936}}
{"text": "import sys\nimport os\nimport os.path\nimport copy\nimport collections\nimport ast\n\n\n\nimport numpy\nimport numpy as np\nimport pandas as pd\n\nfrom limatix.lm_units import parseunits,multiplyunits,printunits\n\nfrom matplotlib import pyplot as pl\n#import pyximport\n#pyximport.install()\nfrom . import convolution\nfrom .convolution import impulse_response,convolution_evaluation\n\n\n#\n#\n# Inputs:\n# Welder model: Vector A of complex amplitude\n#               Vector alpha of complex exponents\n#               time delay (syn_time_delay)\n#               initial_displacement (should be -rho*c_A) because motion positive toward vibrometer\n# Welder model predicts response to an impulse force away from the vibrometer\n# with amplitude 1 N*s\n\n# Also need a model for the pneumatic cylinder behaviour\n# That provides the restoring force\n# and the long-time behavior where the 1 N-s impulse\n# accelerate the entire welder. \n\n\n#\n#\n# Welder & Specimen model\n# Represent as impulse response, possibly followed by continued ringing\n# of one or more decaying sinusoids (i.e. exp(-alpha*t)\n\n\nclass dummy(object):\n    pass\n\npkgpath = sys.modules[dummy.__module__].__file__\npkgdir=os.path.split(pkgpath)[0]\n\n# All welder responses now loaded from welder_modeling_out.py\nwelder_model_output_dir = pkgdir\n\n# Welder model provides globals welder_tip_tip_resp, welder_tip_elec_resp, welder_elec_tip_resp,\n# and welder_elec_elec_resp\nexec(open(os.path.join(welder_model_output_dir,\"welder_modeling_out.py\")).read(),globals())\n\n\n## Temporarily zero out welder_tip_tip_resp for convergence testing\n#welder_tip_tip_resp.h[:]=0.0\n#welder_tip_tip_resp.h[:10]=-1e-28\n#welder_tip_tip_resp.h[1]=-1e-28\n#welder_tip_tip_resp.A[:]=0.0\n\ndefault_welder_spring_constant=5000 # N/m -- bounciness of seals in welder pneumatic cylinder\ndefault_R_contact=25.4e-3 # Hertzian contact parameter: 1 inch radius                  \ndefault_welder_elec_freq=19890.0 # Frequency, Hz\ndefault_dt=1e-6 # Time step, seconds\n\ndefault_gpu_precision=\"single\" # gpu_precision must be \"single\" or \"double\"\n\ncontact_F_nominal = 100.0 # N -- nominal contact force used to decide to neglect imaginary parts order of magnitude smaller\nG_nominal = contact_F_nominal**(1.0/3.0)\n\n\n#specimen_model_output_dir = '.'\n#specimen_model_fname = \"specimen_modeling_out.py\"\n#specimen_model_fname = \"cantilever_modeling_out.py\"\n#specimen_model_fname = \"cantilever_modeling_out_moredamping.py\"\n#specimen_model_fname = \"cantilever_modeling_out_2019_10_01.py\"\n#specimen_model_fname = \"cantilever_modeling_out_2019-11-09-finerseg.py.xz\"\n\n## response of specimen, evaluated at welder contact point\n#specimen_dataframe = pd.read_csv(specimen_model_fname)\n#specimen_resp =\n\n#specimen_model_fpath=os.path.join(specimen_model_output_dir,specimen_model_fname)\n\n\ndef select_gpu_device(priority_list_str):\n    \"\"\"Based on a priority list string of the form:\n     [\n       ('NVIDIA CUDA','Quadro GP100'), \n       ('Intel(R) OpenCL HD Graphics','Intel(R) Gen9 HD Graphics NEO'), \n       ('Portable Computing Language','pthread-AMD EPYC 7351P 16-Core Processor')\n     ]\n    select the first of these devices found and return (context,device,queue).\n    If priority_list_str==\"\" then None will be returned. \n    Otherwise a ValueError or other error will be raised if the \n    string is not parseable or if the device is not found. \n    \n    Each entry in the list is (Platform Name, Device Name)\n    The available platforms and devices can be found by looking\n    at the output of the \"clinfo\" command. \n    \"\"\"\n    \n    if priority_list_str != \"\":\n        import pyopencl as cl\n        gpu_device_priority_list = ast.literal_eval(priority_list_str)\n        platforms=cl.get_platforms()\n        platforms_byname = { platform.name: platform for platform in platforms }\n\n        device = None\n        \n        for (gpu_platform_name,gpu_device_name) in gpu_device_priority_list:\n            \n            if gpu_platform_name in platforms_byname:\n                platform = platforms_byname[gpu_platform_name]\n\n                devices=platform.get_devices()\n                devices_byname = { device.name: device for device in devices }\n\n                if gpu_device_name in devices_byname:\n                    device=devices_byname[gpu_device_name]\n                    break\n                pass\n            pass\n        \n        if device is None:\n            raise ValueError(\"No OpenCL devices found matching any entry in priority list %s. Use clinfo command to find platform name and device name. Priority list must be entered using list notation: \\\"[ ('platform1_name','device1_name'), ('platform2_name','device2_name') ]\\\"\")\n        context = cl.Context(devices=[device])\n        queue = cl.CommandQueue(context)\n        gpu_context_device_queue = (context,device,queue)\n        pass\n    else:\n        gpu_context_device_queue=None\n        pass\n    return gpu_context_device_queue\n\ndef load_specimen_model(specimen_model_filepath):\n    import pandas as pd\n    specimen_dataframe = pd.read_csv(specimen_model_filepath,index_col=\"Time(s)\")\n    \n    #dt=specimen_dataframe[\"Time(s)\"][1]-specimen_dataframe[\"Time(s)\"][0]\n    dt=specimen_dataframe.index[1]-specimen_dataframe.index[0]\n\n    assert(specimen_dataframe.index[0]==0.0)\n    \n    specimen_dict=collections.OrderedDict()    \n    specimen_units_dict=collections.OrderedDict()    \n    for column in specimen_dataframe.columns:\n        if column==\"Time(s)\":\n            continue\n        unitstartidx = column.find(\"(\")\n        if unitstartidx < 0: \n            raise ValueError(\"Dynamic model column name \\\"%s\\\" does not include units\" % (column))\n        fieldname=column[:unitstartidx]\n        fieldunits_with_close_paren=column[(unitstartidx+1):].strip()\n        if not fieldunits_with_close_paren.endswith(\")\"):\n            raise ValueError(\"Dynamic model column \\\"%s\\\" units do not end with close parentheses\" % (column))\n        fieldunits = fieldunits_with_close_paren[:-1]\n        \n        \n        specimen_dict[fieldname]=convolution.impulse_response(\n            h=np.array(specimen_dataframe[column]),\n            dt=dt,\n            t0=0.0,\n            A=np.array((0,),dtype='d'),\n            D=0.0,\n            alpha=np.array((1.0,),dtype='d'))\n        \n        \n        specimen_units_dict[fieldname]=fieldunits\n        pass\n\n    return (specimen_dict,specimen_units_dict) # keys are \"specimen_resp\", etc.; values are impulse_response instances\n\n\ndef contact_model(specimen_dict,\n                  specimen_units_dict,\n                  t0_t1, # Excitation start time (seconds)\n                  t2_t3, # Excitation end time (seconds)\n                  t4, # Time to calculate out to (seconds)\n                  mass_of_welder_and_slider, # mass, kg\n                  pneumatic_force, # Force, N\n                  welder_elec_ampl, # Amplitude (au...? should be volts)\n                  specimen_E, specimen_nu, # Specimen elastic params\n                  welder_spring_constant=default_welder_spring_constant, # N/m -- bounciness of seals in welder pneumatic cylinder\n                  R_contact=default_R_contact, # Hertzian contact parameter: 1 inch radius                  \n                  welder_elec_freq=default_welder_elec_freq, # Frequency, Hz\n                  dt=default_dt, # Time step, seconds\n                  gpu_context_device_queue=None,                  \n                  gpu_precision=default_gpu_precision):\n\n    # specimen_model defines specimen_resp, specimen_mobility, specimen_laser,\n    # specimen_crackcenternormalstrain, and specimen_crackcentershearstrain\n    \n    ## temporarily hardwire gpu_precision to double\n    #gpu_precision=\"double\"\n    #gpu_context_device_queue=None # Temporarily disable GPU\n\n    #s(pecimen_dict,specimen_units_dict)=load_specimen_model(specimen_model_fpath)\n\n    # IDEA: Add small uniform real part to specimen_resp in frequency domain\n    # To keep the phase away from the edge.... FAILED\n\n    # IDEA: Add damping to Hertzian contact spring\n\n    # Resample specimen data to desired dt value\n    for key in specimen_dict:\n        \n        specimen_dict[key].resample(dt)\n        pass\n    \n    specimen_resp=specimen_dict[\"specimen_resp\"]\n    del specimen_dict[\"specimen_resp\"] # Remove specimen_resp from specimen_dict so convolutions with entries in specimen_dict will not be redundant\n    if \"specimen_mobility\" in specimen_dict:\n        del specimen_dict[\"specimen_mobility\"] # Don't care about predicting specimen contact velocity\n        pass \n    \n    ## Temporarily zero out specimen_resp\n    #specimen_resp.h[:]=0.0\n\n    assert(welder_elec_tip_resp.h[0]==0.0) # response of tip to electrical excitation MUST be delayed\n    assert(welder_elec_elec_resp.h[0]==0.0) # electrical response to electrical excitation MUST be delayed\n    assert(welder_tip_elec_resp.h[0]==0.0) # electrical response to tip impulse MUST be delayed\n    \n    \n    welder_tip_tip_resp_local=copy.deepcopy(welder_tip_tip_resp)\n    welder_tip_elec_resp_local=copy.deepcopy(welder_tip_elec_resp)\n    welder_elec_tip_resp_local=copy.deepcopy(welder_elec_tip_resp)\n    welder_elec_elec_resp_local=copy.deepcopy(welder_elec_elec_resp)\n    \n    # resample all responses to desired timestep\n    welder_tip_tip_resp_local.resample(dt)\n    welder_tip_elec_resp_local.resample(dt)\n    welder_tip_elec_resp_local.h[0]=0.0 # resampling can mess this up\n    welder_elec_tip_resp_local.resample(dt)\n    welder_elec_tip_resp_local.h[0]=0.0 # resampling can mess tihs up\n    welder_elec_elec_resp_local.resample(dt)\n    welder_elec_elec_resp_local.h[0]=0.0 # resampling can mess this up\n    \n\n    # welder_tip_tip_resp_local.h[0] is negative... specimen_resp.h[0] is positive,\n    # (criteria for solving for contact force, below)\n    assert(welder_tip_tip_resp_local.h[1] < 0.0)\n    #assert(specimen_resp.h[0] > 0.0)\n    \n\n    # Connect specimen and welder models at contact\n    #  * Sum of forces at contact = 0 (contact massless)\n    #  * No overlap between specimen and welder.\n    \n    # z positive towards specimen\n    welder_tip_z = 0\n    specimen_z = 0\n    \n    #max_t = 0.1\n    #max_t = 0.3\n    #max_t=0.2\n    trange = np.arange(t4/dt)*dt\n    \n    #mass_of_welder_and_slider=2.0   # mass, kg !!!*** Need to properly measure\n    #pneumatic_force = 300 # Force, N  ***!!! Not necessarily representative\n    # NOTE: If welder_spring_constant is nonzero, the pneumatic force ( in\n    # equilbrium) be split between contact load and spring!!!\n    \n\n    # NOTE: with welder_overall_dashpot = 0\n    # get resonance (~170Hz as of this writing), which\n    # matches (1/(2pi))*sqrt(k/m) for\n    # m = mass_of_welder_and_slider = 2 and\n    # k = 1.0/(np.sum(specimen_resp.eval(np.arange(trange.shape[0])).real)*dt) = 2.5e6 N/m\n    # represents the effective DC stiffness of the specimen\n    #  (we should consider the welder and contact stiffnesses as well probably,\n    #  but they are much stiffer!) \n    # For critically damped, set damping ratio = c/(2sqrt(m*k)) = 1\n    # so c = 2*sqrt(m*k) = 4472 for critically damped.\n    # Probably want significantly underdamped, so set c=400 N/(m/s)\n    welder_overall_dashpot = 1000 # dashpot coefficient simulating absorption of pneumatic cylinder\n    \n    # ... at welder 50% amplitude setting , expect open circuit velocity of roughly 80 um p-p at 20 kHz. this corresponds to a welder_elec_ampl of ~1.8e7 (UNITS?)\n    #welder_elec_ampl= 1.8e7*1.0\n    \n    #... double it!\n    #welder_elec_ampl= 1.8e7*5.0\n    \n    #welder_elec_freq=19890.0\n    \n    # Plot welder open-circuit behavior with:\n    #\n    #welder_elec_input = welder_elec_ampl*np.cos(2*np.pi*welder_elec_freq*trange)\n    #welder_elec_tip_conv = convolution_evaluation.blank_from_imp_resp(welder_elec_tip_resp)\n    #welder_tip_z = np.zeros(trange.shape,dtype='d')\n    #for tcnt in range(trange.shape[0]):\n    #    welder_tip_z[tcnt]=welder_elec_tip_conv.step(welder_elec_input[tcnt])\n    #    pass\n    #pl.plot(trange,welder_tip_z)\n    \n    \n    # NOTE: This spring represents the limited contact zone,\n    # and helps to prevent system resonances involving\n    # high Q, high-mobility resonances like the 20 kHz welder motion\n    #kspring = 120e9*(np.pi*12e-3**2/4.0)/(1e-3)*.1 # *100)  # contact stiffness, N/m\n    # NOTE: kspring replaced by Hertzian contact model\n    # Hertzian contact parameters\n    #R_contact=25.4e-3 # 1 inch radius\n    # Welder material (Ti)\n    nu1=.342\n    E1=113.8e9\n    \n    ## Al\n    #nu2=.33\n    #E2=68.9e9\n    \n\n    Estar = 1.0/( (1.0-nu1**2.0)/E1 + (1.0-specimen_nu**2.0)/specimen_E)\n\n\n    # This spring represents the bounciness of the seals in the pneumatic cylinder... based on 20 ms resonant period, and assuming 2kg mass,\n    # f=sqrt(k/m) = 1/.02\n    # f*sqrt(m) = sqrt(k)\n    # k = f^2*m = (1/.02)^2 * 2.0 = 5000 N/m \n    # ... if you set this to 0, then you get instead pure\n    # pneumatic cylinder behavior\n    #welder_spring_constant = 5000\n    \n\n    welder_overall_velocity=0.0 # positive towards specimen\n    #welder_overall_pos=-.5e-3 # half-mm distance initially # positive towards specimen\n    #welder_overall_pos=0e-3 # no distance initially # positive towards specimen\n    \n    # This code is for starting from equilibrium displacement\n    # Next line is correct for pneumatic cylinder but no spring\n    #welder_overall_pos = convolution_evaluation.quiescent_value(pneumatic_force,specimen_resp.A,specimen_resp.alpha,specimen_resp.dt,specimen_resp.h).real - convolution_evaluation.quiescent_value(pneumatic_force,welder_tip_tip_resp_local.A,welder_tip_tip_resp_local.alpha,welder_tip_tip_resp_local.dt,welder_tip_tip_resp_local.h).real\n\n    # overall_pos = specimen_quiescent_coeff*(pneumatic-welder_spring_constant*overall_pos) - welder_quiescent_coeff*(pneumatic-welder_spring_constant*overall_pos)\n    # overall_pos = specimen_quiescent_coeff*pneumatic-specimen_quescent_coeff * welder_spring_constant*overall_pos - welder_quiescent_coeff*pneumatic + welder_quiescent_coeff*welder_spring_constant*overall_pos\n    # overall_pos*(1.0 + specimen_quiescent_coeff*welder_spring_constant - welder_quiescent_coeff*welder_spring_constant) = (specimen_quiescent_coeff - welder_quiescent_coeff)*pneumatic\n    # overall_pos = (specimen_quiescent_coeff - welder_quiescent_coeff)*pneumatic/(1.0 + specimen_quiescent_coeff*welder_spring_constant - welder_quiescent_coeff*welder_spring_constant)\n\n    # Hertzian equilibrium displacement:\n    # Displacement = (9/(16Estar^2R))^(1/3) * contact_F^(2/3)\n    initial_contact_displacement = (9.0/(16.0*R_contact*Estar**2.0))**(1.0/3.0) * pneumatic_force**(2.0/3.0)\n    \n\n    welder_overall_pos = (convolution_evaluation.quiescent_value(1.0,specimen_resp.A,specimen_resp.alpha,specimen_resp.dt,specimen_resp.h).real - convolution_evaluation.quiescent_value(1.0,welder_tip_tip_resp_local.A,welder_tip_tip_resp_local.alpha,welder_tip_tip_resp_local.dt,welder_tip_tip_resp_local.h).real)*pneumatic_force/(1.0 + convolution_evaluation.quiescent_value(1.0,specimen_resp.A,specimen_resp.alpha,specimen_resp.dt,specimen_resp.h).real*welder_spring_constant - convolution_evaluation.quiescent_value(1.0,welder_tip_tip_resp_local.A,welder_tip_tip_resp_local.alpha,welder_tip_tip_resp_local.dt,welder_tip_tip_resp_local.h).real*welder_spring_constant) + initial_contact_displacement\n\n\n    \n\n\n    # Define convolutions of the various responses\n    # This is for zero initial displacement\n    #specimen_conv = convolution_evaluation.blank_from_imp_resp(specimen_resp)\n    # This is for equilbrium initial displacement\n\n    specimen_conv = convolution_evaluation.quiescent_from_imp_resp(specimen_resp,pneumatic_force-welder_overall_pos*welder_spring_constant,gpu_context_device_queue=gpu_context_device_queue,gpu_precision=gpu_precision)\n\n\n    # specimen_dict_conv gets convolution evaluations setup just like\n    # specimen_conv for all the other characteristics of interest\n    # (laser point velocity, crack normal stress, etc.)\n    specimen_dict_conv=collections.OrderedDict()\n    specimen_dict_history=collections.OrderedDict()\n    for specimen_motion_name in specimen_dict:\n        original_unit_str = specimen_units_dict[specimen_motion_name]\n        original_units = parseunits(original_unit_str)\n        \n        # Convolving with force as a function multiplies by Newton seconds\n        convolve_units = parseunits(\"N*s\")\n        convolution_units = multiplyunits(original_units,convolve_units)\n\n        specimen_motion_characteristic=\"%s(%s)\" % (specimen_motion_name,printunits(convolution_units))\n        \n        specimen_dict_conv[specimen_motion_characteristic] = convolution_evaluation.quiescent_from_imp_resp(specimen_dict[specimen_motion_name],pneumatic_force-welder_overall_pos*welder_spring_constant,gpu_context_device_queue=gpu_context_device_queue,gpu_precision=gpu_precision)\n\n        specimen_dict_history[specimen_motion_characteristic]=np.zeros(trange.shape[0],dtype='d')\n\n        \n        pass\n    \n    \n\n    assert(dt==specimen_resp.dt)\n    \n    \n    # This is for zero initial displacement\n    #welder_tip_tip_conv = convolution_evaluation.blank_from_imp_resp(welder_tip_tip_resp_local)\n    # This is for equilbrium initial displacement\n    welder_tip_tip_conv = convolution_evaluation.quiescent_from_imp_resp(welder_tip_tip_resp_local,pneumatic_force)\n    assert(dt==welder_tip_tip_resp_local.dt)\n\n\n    welder_tip_elec_conv = convolution_evaluation.blank_from_imp_resp(welder_tip_elec_resp_local)\n    assert(dt==welder_tip_elec_resp_local.dt)\n    \n    welder_elec_tip_conv = convolution_evaluation.blank_from_imp_resp(welder_elec_tip_resp_local)\n    assert(dt==welder_elec_tip_resp_local.dt)\n    assert(welder_elec_tip_resp_local.h[0]==0.0) # response of tip to electrical excitation MUST be delayed\n    \n    welder_elec_elec_conv = convolution_evaluation.blank_from_imp_resp(welder_elec_elec_resp_local)\n    assert(dt==welder_elec_elec_resp_local.dt)\n    assert(welder_elec_elec_resp_local.h[0]==0.0) # electrical response to electrical excitation MUST be delayed\n    \n\n\n    specimen_z_history=np.zeros(trange.shape[0],dtype='d')\n    welder_tip_z_history=np.zeros(trange.shape[0],dtype='d')\n    contact_F_history=np.zeros(trange.shape[0],dtype='d')\n    welder_overall_velocity_history=np.zeros(trange.shape[0],dtype='d')\n\n    welder_tip_z=welder_tip_tip_conv.evaluate() + welder_elec_tip_conv.evaluate() + welder_overall_pos\n\n    specimen_z=specimen_conv.evaluate()\n    \n    \n    last_overlap = welder_tip_z - specimen_z\n\n    for tcnt in range(trange.shape[0]):\n        if tcnt % 10000 == 0:\n            print(\"tcnt=%d/%d\" % (tcnt,trange.shape[0]))\n\n            # memory leak debugging\n            #import tracemalloc\n            #snapshot=tracemalloc.take_snapshot()\n            #top_stats=snapshot.statistics('lineno')\n            #print(\"Top 25:\")\n            #print(\"\\n\".join([str(stat) for stat in top_stats[:25]]))\n            #print(\" \")\n            pass\n    \n\n\n        #if tcnt==42890:\n        #    raise ValueError(\"Debug!\")\n        \n        #if tcnt==3953: \n        #    import pdb\n        #    pdb.set_trace()\n        #    pass\n\n        specimen_z=specimen_conv.step_without_instantaneous()\n        \n        welder_overall_pos += welder_overall_velocity*dt\n        welder_tip_z=welder_tip_tip_conv.step_without_instantaneous() + welder_elec_tip_conv.step_without_instantaneous() + welder_overall_pos\n        \n    \n        \n        welder_elec_resp_voltage = welder_tip_elec_conv.step_without_instantaneous() + welder_elec_elec_conv.step_without_instantaneous()\n        \n        # Determine electrical control input\n        \n        # Welder elec input  --- Could include welder controller behavior here (based on welder_elec_resp_voltage and its history)\n        \n        if trange[tcnt] >= t0_t1 and trange[tcnt] <= t2_t3:\n            welder_elec_input = welder_elec_ampl*np.cos(2*np.pi*welder_elec_freq*(trange[tcnt]-t0_t1))\n            pass\n        else:\n            welder_elec_input = 0.0\n            pass\n\n        # Determine contact force from overlap\n    \n        # evaluate overlap\n        overlap = welder_tip_z - specimen_z  # overlap represents amount of overalp between welder and specimen if no force is applied in this step\n\n\n        if overlap > 0:\n            # Conditions\n            # Define Fwelder positive compression into welder\n            # Define Fspecimen positive compression into specimen\n            # Fwelder = Fspecimen\n            # zshift_welder = instantaneous_welder_displacement*Fwelder*dt    # instantaneous_welder_displacement from welder model corresponds to displacement resulting from a 1 N*s impulse. Therefore it can be interpreted as have units of meters/(N*s) It is negative because the positive contact_F pulse pushes the welder away from the vibrometer\n            # zshift_specimen = specimen_response[0]*Fspecimen*dt # Due to 1 N*s impulse... Should be positive\n            # Add in contact springiness in series with\n            # surface springiness:\n            #  zspring=contact_F/kspring\n            # zshift_welder - zshift_specimen - zspring = -overlap (known)\n            \n            # Solve this sytem....\n            # let contact_F = Fwelder = Fspecimen = Fspring\n            # instantaneous_welder_displacement*contact_F*dt  - specimen_response[0]*contact_F*dt - contact_F/kspring = -overlap\n            # F = -overlap/(dt*(instantaneous_welder_displacement-specimen_resp[0]) - (1/kspring))\n            \n            # New Hertzian contact model\n            # instantaneous_welder_displacement*contact_F*dt  - specimen_response[0]*contact_F*dt - (9/(16Estar^2R))^(1/3) * contact_F^(2/3) = -nocontactforce_overlap\n            \n            # This is a cubic equation for contact_F\n            # for a*F - b*F^(2/3) + c = 0\n            # G = F^(1/3)\n            # a*G^3 - b*G^2 + c = 0\n            G = np.roots([np.real(welder_tip_tip_resp_local.h[0]*dt-specimen_resp.h[0]*dt),-(9.0/(16.0*R_contact*Estar**2.0))**(1.0/3.0),0.0,overlap])\n            use_G = G[(G.real > 0) & (abs(G.imag) <= G_nominal*1e-8)].real\n            if use_G.shape[0] != 1:\n                raise ValueError(\"Bad Hertzian contact solution: %s\" % (str(G)))\n            \n            contact_F=use_G[0]**3.0\n        \n\n            # Old simple spring contact model here:\n            #contact_F = -overlap/(dt*(np.real(welder_tip_tip_resp_local.h[0]-specimen_resp.h[0])) - 1.0/kspring)  # welder_tip_tip_resp_local.h[0] is negative... specimen_resp.h[0] is positive, overlap is positive, so contact_F is positive for compressive force between\n            # Welder and specimen\n            # Accumulate immediate response to this force\n            pass\n        else:\n            contact_F=0.0\n            pass\n        \n        contact_F_history[tcnt]=contact_F\n    \n        \n        # Need to convolve force history\n        # displacement = integral( F(t-tau) * response(tau)) dtau\n        # store force history Fhist(t)\n        # At a particular time t, \n        # displacement = integral( F(t-tau) * response(tau)) dtau where tau >= 0\n        \n        #welder_tip_z = welder_tip_z + contact_F*welder_tip_tip_resp_local.h[0]*dt\n        #specimen_z = specimen_z + contact_F*specimen_resp.h[0]*dt\n        \n        # Positive (compressive) contact_F gives positive instantaneous\n        # contribution... specimen_z moves in +z direction (away from welder)\n        specimen_z += specimen_conv.step_instantaneous_contribution(contact_F)\n\n        for specimen_motion_characteristic in specimen_dict_conv:\n            specimen_dict_history[specimen_motion_characteristic][tcnt] = specimen_dict_conv[specimen_motion_characteristic].step(contact_F)\n            pass\n        \n        \n        # Positive (compressive) contact_F gives negative instantaneous\n        # contribution... welder tip moves in -z direction (away from specimen)\n        # Also need to apply contribution of welder electric input (but\n        # the instantaneous effect of this is zero\n        welder_tip_z += welder_tip_tip_conv.step_instantaneous_contribution(contact_F) + welder_elec_tip_conv.step_instantaneous_contribution(welder_elec_input)\n        \n        # Apply the contribution to the electric response...\n        # instantaneous effect is zero. \n        welder_elec_resp_voltage = welder_tip_elec_conv.step_instantaneous_contribution(contact_F) + welder_elec_elec_conv.step_instantaneous_contribution(welder_elec_input)\n        assert(welder_elec_resp_voltage==0.0) # These should not have instantaneous responses!\n        \n    \n        # Should verify that overlap has been reduced to approximately 0\n        new_overlap = welder_tip_z - specimen_z\n        #assert(new_overlap < 1e-12)  (new overlap is no longer small now that we have added contact stiffness) \n        \n        specimen_z_history[tcnt]=specimen_z\n        welder_tip_z_history[tcnt]=welder_tip_z\n        \n        # determine change in welder_overall_velocity\n        # ***!!!! Should this have a lag ?\n        # F = ma  -> a = F/m\n        # v = vprior + a*dt\n        # v = vprior + (F/m)*dt\n        # Where F = pneumatic_force - contact_F - welder_overall_dashpot*welder_overall_velocity\n        welder_spring_force = -welder_tip_z*welder_spring_constant + pneumatic_force    # use \"pneumatic_force\" parameter as spring preload\n        welder_overall_velocity += ((welder_spring_force-contact_F - welder_overall_dashpot*welder_overall_velocity)/mass_of_welder_and_slider) * dt\n        assert(np.imag(welder_overall_velocity)==0.0)\n        \n        welder_overall_velocity_history[tcnt]=welder_overall_velocity\n        \n        #if tcnt >= 80890 and contact_F > 0:\n        #raise ValueError(\"Debug!\")\n        #    break\n        last_overlap = new_overlap\n        pass\n    # !!! Need conservation of energy constraint !!!***\n    # Would it help to make contact more compliant (don't require\n    #  exactly zero overlap)? \n    \n    \n    motiontable = pd.DataFrame(index=pd.Float64Index(data=np.arange(trange.shape[0],dtype='d')*dt,dtype='d',name=\"Time(s)\"))\n    \n    motiontable.insert(len(motiontable.columns),\"specimen_z_history(m)\",specimen_z_history)\n    motiontable.insert(len(motiontable.columns),\"welder_tip_z_history(m)\",welder_tip_z_history)\n    motiontable.insert(len(motiontable.columns),\"contact_F_history(N)\",contact_F_history)\n    motiontable.insert(len(motiontable.columns),\"welder_overall_velocity_history(m/s)\",welder_overall_velocity_history)\n\n    motiontable.insert(len(motiontable.columns),\"welder_tip_tip_resp(m/(N*s))\",welder_tip_tip_resp_local.eval(np.arange(trange.shape[0])).real)\n    motiontable.insert(len(motiontable.columns),\"specimen_resp(m/(N*s))\",specimen_resp.eval(np.arange(trange.shape[0])).real)\n    \n    for specimen_motion_characteristic in specimen_dict_history:\n        motiontable.insert(len(motiontable.columns),specimen_motion_characteristic,specimen_dict_history[specimen_motion_characteristic])\n        pass\n    \n    return motiontable\n\ndef write_motiontable(motiontable,output_filename):\n    if output_filename.endswith(\".bz2\"):\n        motiontable.to_csv(output_filename,compression='bz2')\n        pass\n    else:\n        motiontable.to_csv(output_filename)\n        pass\n\n    pass\n\n\n\ndef plot_contact(motiontable,exc_t0):\n\n    trange = np.array(motiontable.index) # [\"Time(s)\"]\n    dt=trange[1]-trange[0]\n\n    difft = (trange[:-1]+trange[1:])/2.0\n\n    max_t_plot = np.max(trange)\n    \n    # round length up to next power-of-two size \n    # so we don't get bogged down if trange.shape[0] is prime\n    fft_len = 1 << int(np.ceil(np.log(trange.shape[0])/np.log(2)))\n    \n    frange = np.arange(fft_len,dtype='d')/(fft_len*dt)\n    frange[fft_len//2:] -= 1.0/dt\n    frange[fft_len//2]=np.nan\n\n    welder_tip_z_history = motiontable[\"welder_tip_z_history(m)\"]\n    specimen_z_history = motiontable[\"specimen_z_history(m)\"]\n    contact_F_history = motiontable[\"contact_F_history(N)\"]\n    specimen_laser_vel_history = motiontable[\"specimen_laser(m/s)\"]\n    \n    impresp_plot=pl.figure()\n    pl.clf()\n    pl.title(\"Welder and specimen impulse response\")\n    pl.plot(trange*1e6,\n            motiontable[\"welder_tip_tip_resp(m/(N*s))\"],'-',\n            trange*1e6,\n            motiontable[\"specimen_resp(m/(N*s))\"],'--')    \n    pl.xlabel('time (us)')\n    pl.legend(('Welder','Specimen'))\n    pl.grid()\n        \n    velspec_plot=pl.figure()\n    pl.clf()\n    pl.title(\"Welder and specimen velocity spectrum\")\n    pl.plot(frange/1e3,\n            np.abs(np.fft.fft(motiontable[\"welder_tip_tip_resp(m/(N*s))\"],n=fft_len)*dt*(2.0*np.pi*np.abs(frange))),'-',\n            frange/1e3,\n            np.abs(np.fft.fft(motiontable[\"specimen_resp(m/(N*s))\"],n=fft_len)*dt*(2.0*np.pi*np.abs(frange))),'--')\n    pl.xlabel('Frequency (kHz)')\n    pl.ylabel('Velocity spectrum (m/s/Hz)')\n    pl.legend(('Welder','Specimen'))\n    pl.axis((0,250,0,.012))\n    pl.grid()\n        \n    phasespec_plot = pl.figure()\n    # NOTE: Because welder velocity is negated\n    # relative to force direction, we undo that by negating before\n    # evaluating the angle, so it is clear whether the phase is in the\n    # required (-pi/2,pi/2) range\n    pl.clf()\n    pl.title(\"Welder and specimen velocity phase spectrum\")\n    pl.plot(frange/1e3,\n            np.angle(-np.fft.fft(motiontable[\"welder_tip_tip_resp(m/(N*s))\"],n=fft_len)*dt*((0+1j)*2.0*np.pi*np.abs(frange))),'-',\n            frange/1e3,\n            np.angle(np.fft.fft(motiontable[\"specimen_resp(m/(N*s))\"],n=fft_len)*dt*((0+1j)*2.0*np.pi*np.abs(frange))),'--')\n    pl.xlabel('Frequency (kHz)')\n    pl.ylabel('Phase angle (rad)')\n    pl.legend(('Welder','Specimen'))\n    pl.axis((0,250,-np.pi,np.pi))\n    pl.grid()\n    \n    \n    disp_plot = pl.figure()\n    pl.clf()\n    pl.plot(trange*1e3,specimen_z_history*1e6,'-',\n            trange*1.e3,welder_tip_z_history*1e6,'-')\n    pl.axis((0,max_t_plot*1.e3,min(np.min(specimen_z_history*1e6),np.min(welder_tip_z_history*1e6)),max(np.max(specimen_z_history*1e6),np.max(welder_tip_z_history*1e6))))\n    pl.xlabel('Time (ms)')\n    pl.ylabel('Displacement (um)')\n    pl.title('Specimen and welder displacement')\n    pl.legend(('Specimen','Welder'))\n    pl.grid()\n    \n\n    \n    dispzoom_plot = pl.figure()\n    pl.clf()\n    fig5_tstart = exc_t0 - 0.1e-3 #5e-3\n    fig5_tend = exc_t0 + 0.9e-3 # 6e-3\n    pl.plot(trange*1e3,specimen_z_history*1e6,'-',\n            trange*1.e3,welder_tip_z_history*1e6,'-')\n    pl.axis((fig5_tstart*1e3,fig5_tend*1e3,min(np.min(specimen_z_history[(trange >= fig5_tstart) & (trange <= fig5_tend)]*1e6),np.min(welder_tip_z_history[(trange >= fig5_tstart) & (trange <= fig5_tend)]*1e6)),max(np.max(specimen_z_history[(trange >= fig5_tstart) & (trange <= fig5_tend)]*1e6),np.max(welder_tip_z_history[(trange >= fig5_tstart) & (trange <= fig5_tend)]*1e6))))\n    pl.xlabel('Time (ms)')\n    pl.ylabel('Displacement (um)')\n    pl.title('Specimen and welder displacement')\n    pl.legend(('Specimen','Welder'))\n    pl.grid()\n\n        \n    contactforce_plot = pl.figure()\n    pl.clf()\n    # Impulse between .28*.33\n    Impulse=contact_F_history[(trange >.28e-3) & (trange < .33e-3)].sum()*dt\n    pl.plot(trange*1e3,contact_F_history)\n    pl.axis((0,max_t_plot*1.e3,0,20000))\n    pl.xlabel('Time (ms)')\n    pl.ylabel('Force (N)')\n    pl.title('Contact force (time domain')\n    pl.grid()\n        \n        \n    #pl.figure(5)\n    #pl.clf()\n    #pl.plot(trange,welder_overall_velocity_history)\n        \n    contactspectrum_plot = pl.figure()\n    pl.clf()\n    # Impulse between .28*.33\n    pl.plot(frange/1e3,np.abs(np.fft.fft(contact_F_history,n=fft_len)*dt))\n    #pl.axis((0,max_t_plot*1.e3,0,20000))\n    pl.xlabel('Frequency (kHz)')\n    pl.ylabel('Force spectrum (N/Hz)')\n    pl.title('Contact force (frequency domain')\n    pl.grid()\n        \n        \n    overlap_plot = pl.figure()\n    pl.clf()\n    pl.plot(trange*1.e3,(welder_tip_z_history-specimen_z_history)*1e6,'-')\n    #pl.axis((0,55,-1000,500))\n    pl.xlabel('Time (ms)')\n    pl.ylabel('Displacement (um)')\n    pl.title('Welder/specimen overlap')\n    #pl.axis((0,1,-3,1))\n    pl.grid()\n        \n    #pl.figure(7)\n    #pl.clf()\n    #difft = (trange[:-1]+trange[1:])/2.0\n    #pl.plot(difft*1.e3,np.diff(welder_tip_z_history-specimen_z_history)/dt,'-')\n    #pl.xlabel('Time (ms)')\n    #pl.ylabel('Velocity (m/s)')\n    #pl.grid()\n    \n    contactvel_plot = pl.figure()\n    pl.clf()\n    pl.plot(difft*1.e3,np.diff(specimen_z_history)/dt,'-')\n    #pl.axis((0,55,-1000,500))\n    pl.xlabel('Time (ms)')\n    pl.ylabel('Velocity (m/s)')\n    pl.title('Specimen contact surface velocity (synthetic vibrometer)')\n    #pl.axis((0,1,-3,1))\n    pl.grid()\n    \n    contactvelspec_plot = pl.figure()\n    pl.clf()\n    pl.plot(frange/1.e3,np.abs(np.fft.fft(specimen_z_history,n=fft_len)*dt*(2.0*np.pi*frange)),'-')\n    #pl.axis((0,55,-1000,500))\n    pl.xlabel('Frequency (kHz)')\n    pl.ylabel('Velocity spectrum (m/s)/Hz')\n    pl.title('Specimen contact velocity spectrum (synthetic vibrometer)')\n    #pl.axis((0,1,-3,1))\n    pl.grid()\n    \n\n\n    laservel_plot = pl.figure()\n    pl.clf()\n    pl.plot(trange*1e3,specimen_laser_vel_history,'-')\n    pl.xlabel('Time (ms)')\n    pl.ylabel('Velocity (m/s)')\n    pl.title('Laser spot surface velocity (synthetic vibrometer)')\n    #pl.axis((0,1,-3,1))\n    pl.grid()\n    \n    laservelspec_plot = pl.figure()\n    pl.clf()\n    pl.plot(frange/1.e3,np.abs(np.fft.fft(specimen_laser_vel_history,n=fft_len)*dt),'-')\n    #pl.axis((0,55,-1000,500))\n    pl.xlabel('Frequency (kHz)')\n    pl.ylabel('Velocity spectrum (m/s)/Hz')\n    pl.title('Laser spot surface velocity spectrum (synthetic vibrometer)')\n    #pl.axis((0,1,-3,1))\n    pl.grid()\n    \n\n\n\n    plotdict = {\n        \"impulse_response\": impresp_plot,\n        \"velocity_spectrum\": velspec_plot,\n        \"phase_spectrum\": phasespec_plot,\n        \"displacement\": disp_plot,\n        \"displacement_zoom\": dispzoom_plot,\n        \"contact_force\": contactforce_plot,\n        \"contact_spectrum\": contactspectrum_plot,\n        \"overlap\": overlap_plot,\n        \"contact_velocity\": contactvel_plot,\n        \"contact_velocity_spectrum\": contactvelspec_plot,\n        \"laser_velocity\": laservel_plot,\n        \"laser_velocity_spectrum\": laservelspec_plot,\n    }\n    return plotdict\n", "meta": {"hexsha": "4710d9ba881e6dd7c0937b628bdff0ca612a473f", "size": 34086, "ext": "py", "lang": "Python", "max_stars_repo_path": "VibroSim_WelderModel/contact_model.py", "max_stars_repo_name": "VibroSim/VibroSim_WelderModel", "max_stars_repo_head_hexsha": "54acab2dc4c7ec8c0fb58f64333eba99b94064aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "VibroSim_WelderModel/contact_model.py", "max_issues_repo_name": "VibroSim/VibroSim_WelderModel", "max_issues_repo_head_hexsha": "54acab2dc4c7ec8c0fb58f64333eba99b94064aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VibroSim_WelderModel/contact_model.py", "max_forks_repo_name": "VibroSim/VibroSim_WelderModel", "max_forks_repo_head_hexsha": "54acab2dc4c7ec8c0fb58f64333eba99b94064aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.8216080402, "max_line_length": 699, "alphanum_fraction": 0.6892565863, "include": true, "reason": "import numpy", "num_tokens": 8925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.19334202598069933}}
{"text": "import abc\nfrom typing import Callable, Optional, Tuple, TypeVar\n\nimport equinox as eqx\nimport jax\nimport jax.numpy as jnp\n\nfrom ..custom_types import Bool, DenseInfo, PyTree, PyTreeDef, Scalar\nfrom ..heuristics import is_sde\nfrom ..local_interpolation import AbstractLocalInterpolation\nfrom ..nonlinear_solver import AbstractNonlinearSolver, NewtonNonlinearSolver\nfrom ..solution import RESULTS\nfrom ..term import AbstractTerm\n\n\n_SolverState = TypeVar(\"SolverState\", bound=Optional[PyTree])\n\n\ndef vector_tree_dot(a, b):\n    return jax.tree_map(lambda bi: jnp.tensordot(a, bi, axes=1), b)\n\n\nclass _MetaAbstractSolver(type(eqx.Module)):\n    def __instancecheck__(cls, obj):\n        if super(_MetaAbstractSolver, AbstractWrappedSolver).__instancecheck__(obj):\n            obj = obj.solver\n        return super().__instancecheck__(obj)\n\n\nclass AbstractSolver(eqx.Module, metaclass=_MetaAbstractSolver):\n    \"\"\"Abstract base class for all differential equation solvers.\"\"\"\n\n    @property\n    @abc.abstractmethod\n    def term_structure(self) -> PyTreeDef:\n        \"\"\"What PyTree structure `terms` should have when used with this solver.\"\"\"\n\n    # On the type: frequently just Type[AbstractLocalInterpolation]\n    @property\n    @abc.abstractmethod\n    def interpolation_cls(self) -> Callable[..., AbstractLocalInterpolation]:\n        \"\"\"How to interpolate the solution in between steps.\"\"\"\n\n    def order(self, terms: PyTree[AbstractTerm]) -> Optional[int]:\n        \"\"\"Order of the solver for solving ODEs.\"\"\"\n        return None\n\n    def strong_order(self, terms: PyTree[AbstractTerm]) -> Optional[Scalar]:\n        \"\"\"Strong order of the solver for solving SDEs.\"\"\"\n        return None\n\n    def error_order(self, terms: PyTree[AbstractTerm]) -> Optional[Scalar]:\n        \"\"\"Order of the error estimate used for adaptive stepping.\n\n        The default (slightly heuristic) implementation is as follows.\n\n        The error estimate is assumed to come from the difference of two methods. If\n        these two methods have orders `p` and `q` then the local order of the error\n        estimate is `min(p, q) + 1` for an ODE and `min(p, q) + 0.5` for an SDE.\n\n        - In the SDE case then we assume `p == q == solver.strong_order()`.\n        - In the ODE case then we assume `p == q + 1 == solver.order()`.\n        - We assume that non-SDE/ODE cases do not arise.\n\n        This is imperfect as these assumptions may not be true. In addition in the SDE\n        case, then solvers will sometimes exhibit higher orders of convergence for\n        specific noise types (see issue #47).\n        \"\"\"\n        if is_sde(terms):\n            order = self.strong_order(terms)\n            if order is not None:\n                order = order + 0.5\n            return order\n        else:\n            return self.order(terms)\n\n    def init(\n        self,\n        terms: PyTree[AbstractTerm],\n        t0: Scalar,\n        t1: Scalar,\n        y0: PyTree,\n        args: PyTree,\n    ) -> _SolverState:\n        \"\"\"Initialises any hidden state for the solver.\n\n        **Arguments** as [`diffrax.diffeqsolve`][].\n\n        **Returns:**\n\n        The initial solver state, which should be used the first time `step` is called.\n        \"\"\"\n        return None\n\n    @abc.abstractmethod\n    def step(\n        self,\n        terms: PyTree[AbstractTerm],\n        t0: Scalar,\n        t1: Scalar,\n        y0: PyTree,\n        args: PyTree,\n        solver_state: _SolverState,\n        made_jump: Bool,\n    ) -> Tuple[PyTree, Optional[PyTree], DenseInfo, _SolverState, RESULTS]:\n        \"\"\"Make a single step of the solver.\n\n        Each step is made over the specified interval $[t_0, t_1]$.\n\n        **Arguments:**\n\n        - `terms`: The PyTree of terms representing the vector fields and controls.\n        - `t0`: The start of the interval that the step is made over.\n        - `t1`: The end of the interval that the step is made over.\n        - `y0`: The current value of the solution at `t0`.\n        - `args`: Any extra arguments passed to the vector field.\n        - `solver_state`: Any evolving state for the solver itself, at `t0`.\n        - `made_jump`: Whether there was a discontinuity in the vector field at `t0`.\n            Some solvers (notably FSAL Runge--Kutta solvers) usually assume that there\n            are no jumps and for efficiency re-use information between steps; this\n            indicates that a jump has just occurred and this assumption is not true.\n\n        **Returns:**\n\n        A tuple of several objects:\n\n        - The value of the solution at `t1`.\n        - A local error estimate made during the step. (Used by adaptive step size\n            controllers to change the step size.) May be `None` if no estimate was\n            made.\n        - Some dictionary of information that is passed to the solver's interpolation\n            routine to calculate dense output. (Used with `SaveAt(ts=...)` or\n            `SaveAt(dense=...)`.)\n        - The value of the solver state at `t1`.\n        - An integer (corresponding to `diffrax.RESULTS`) indicating whether the step\n            happened successfully, or if (unusually) it failed for some reason.\n        \"\"\"\n\n    def func_for_init(\n        self, terms: PyTree[AbstractTerm], t0: Scalar, y0: PyTree, args: PyTree\n    ) -> PyTree:\n        \"\"\"Provides vector field evaluations to select the initial step size.\n\n        This is used to make a point evaluation. This is unlike\n        [`diffrax.AbstractSolver.step`][], which operates over an interval.\n\n        In general differential equation solvers are interval-based. There is precisely\n        one place where point evaluations are needed: selecting the initial step size\n        automatically in an ODE solve. And that is what this function is for.\n\n        **Arguments:** As [`diffrax.diffeqsolve`][]\n\n        **Returns:**\n\n        The evaluation of the vector field at `t0`.\n        \"\"\"\n\n        raise ValueError(\n            \"An initial step size cannot be selected automatically. The most common \"\n            \"scenario for this error to occur is when trying to use adaptive step \"\n            \"size solvers with SDEs. Please specify an initial `dt0` instead.\"\n        )\n\n\nclass AbstractImplicitSolver(AbstractSolver):\n    nonlinear_solver: AbstractNonlinearSolver = NewtonNonlinearSolver()\n\n\nclass AbstractItoSolver(AbstractSolver):\n    pass\n\n\nclass AbstractStratonovichSolver(AbstractSolver):\n    pass\n\n\nclass AbstractAdaptiveSolver(AbstractSolver):\n    pass\n\n\nclass AbstractAdaptiveSDESolver(AbstractAdaptiveSolver):\n    pass\n\n\nclass AbstractWrappedSolver(AbstractSolver):\n    solver: AbstractSolver\n\n\nclass HalfSolver(AbstractWrappedSolver, AbstractAdaptiveSDESolver):\n    \"\"\"Wraps another solver, trading cost in order to provide error estimates. (These\n    error estimates mean that the solver can be used with an adaptive step size\n    controller, like [`diffrax.PIDController`][].)\n\n    For every step of the wrapped solver, it does this by also making two half-steps,\n    and comparing the results. (Hence the name \"HalfSolver\".)\n\n    As such each step costs 3 times the computational cost of the wrapped solver.\n\n    !!! tip\n\n        Many solvers already provided error estimates, making `HalfSolver` primarily\n        useful when using a solver that doesn't provide error estimates -- e.g.\n        [`diffrax.Euler`][] -- in particular this is common when solving SDEs.\n    \"\"\"\n\n    @property\n    def term_structure(self):\n        return self.solver.term_structure\n\n    @property\n    def interpolation_cls(self):\n        return self.solver.interpolation_cls\n\n    def order(self, terms: PyTree[AbstractTerm]) -> Optional[int]:\n        return self.solver.order(terms)\n\n    def strong_order(self, terms: PyTree[AbstractTerm]) -> Optional[Scalar]:\n        return self.solver.strong_order(terms)\n\n    def error_order(self, terms: PyTree[AbstractTerm]) -> Optional[Scalar]:\n        if is_sde(terms):\n            order = self.strong_order(terms)\n            if order is not None:\n                order = order + 0.5\n        else:\n            order = self.order(terms)\n            if order is not None:\n                order = order + 1\n        return order\n\n    def init(\n        self,\n        terms: PyTree[AbstractTerm],\n        t0: Scalar,\n        t1: Scalar,\n        y0: PyTree,\n        args: PyTree,\n    ):\n        return self.solver.init(terms, t0, t1, y0, args)\n\n    def step(\n        self,\n        terms: PyTree[AbstractTerm],\n        t0: Scalar,\n        t1: Scalar,\n        y0: PyTree,\n        args: PyTree,\n        solver_state: _SolverState,\n        made_jump: Bool,\n    ) -> Tuple[PyTree, Optional[PyTree], DenseInfo, _SolverState, RESULTS]:\n\n        original_solver_state = solver_state\n        thalf = t0 + 0.5 * (t1 - t0)\n\n        yhalf, _, _, solver_state, result1 = self.solver.step(\n            terms, t0, thalf, y0, args, solver_state, made_jump\n        )\n        y1, _, _, solver_state, result2 = self.solver.step(\n            terms, thalf, t1, yhalf, args, solver_state, made_jump=False\n        )\n\n        # TODO: use dense_info from the pair of half-steps instead\n        y1_alt, _, dense_info, _, result3 = self.solver.step(\n            terms, t0, t1, y0, args, original_solver_state, made_jump\n        )\n\n        y_error = jnp.abs(y1 - y1_alt)\n        result = jnp.maximum(result1, jnp.maximum(result2, result3))\n\n        return y1, y_error, dense_info, solver_state, result\n\n    def func_for_init(\n        self, terms: PyTree[AbstractTerm], t0: Scalar, y0: PyTree, args: PyTree\n    ):\n        return self.solver.func_for_init(terms, t0, y0, args)\n\n\nHalfSolver.__init__.__doc__ = \"\"\"**Arguments:**\n\n- `solver`: The solver to wrap.\n\"\"\"\n", "meta": {"hexsha": "8073c600b8bc4ad686babb67130ef316ce95aea7", "size": 9661, "ext": "py", "lang": "Python", "max_stars_repo_path": "diffrax/solver/base.py", "max_stars_repo_name": "FedericoV/diffrax", "max_stars_repo_head_hexsha": "98b010242394491fea832e77dc94f456b48495fa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "diffrax/solver/base.py", "max_issues_repo_name": "FedericoV/diffrax", "max_issues_repo_head_hexsha": "98b010242394491fea832e77dc94f456b48495fa", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "diffrax/solver/base.py", "max_forks_repo_name": "FedericoV/diffrax", "max_forks_repo_head_hexsha": "98b010242394491fea832e77dc94f456b48495fa", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2588652482, "max_line_length": 87, "alphanum_fraction": 0.6484835938, "include": true, "reason": "import jax", "num_tokens": 2302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.3415824860330003, "lm_q1q2_score": 0.19334201339180346}}
{"text": "\"\"\"Calculates the Frechet Inception Distance (FID) to evalulate GANs\n\nThe FID metric calculates the distance between two distributions of images.\nTypically, we have summary statistics (mean & covariance matrix) of one\nof these distributions, while the 2nd distribution is given by a GAN.\n\nWhen run as a stand-alone program, it compares the distribution of\nimages that are stored as PNG/JPEG at a specified location with a\ndistribution given by summary statistics (in pickle format).\n\nThe FID is calculated by assuming that X_1 and X_2 are the activations of\nthe pool_3 layer of the inception net for generated samples and real world\nsamples respectively.\n\nSee --help to see further details.\n\nCode apapted from https://github.com/bioinf-jku/TTUR to use PyTorch instead\nof Tensorflow\n\nCopyright 2018 Institute of Bioinformatics, JKU Linz\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n   http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport numpy as np\nimport torch\nfrom scipy import linalg\nfrom torch.nn.functional import adaptive_avg_pool2d\n\nfrom models.inception import InceptionV3\n\n\nclass FIDScoreCumulative:\n    def __init__(self, dims=2048, device='cpu'):\n        \"\"\"Init FIDScore\n\n        Params:\n        -- dims        : Dimensionality of features returned by Inception\n        -- device      : Device to run calculations\n        \"\"\"\n        self.dims = dims\n        self.device = device\n\n        block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[self.dims]\n        self.model = InceptionV3([block_idx]).to(self.device)\n        self.model.eval()\n\n        self.sessions = {}\n\n    class Session:\n        def __init__(self, data_len, dims):\n            self.data_len = data_len\n            self.dims = dims\n            self.reset_activations()\n\n        def reset_activations(self):\n            self.pred_arr = np.empty((self.data_len, self.dims))\n            self.start_idx = 0\n\n        def add_activation(self, pred):\n            self.pred_arr[self.start_idx:self.start_idx + pred.shape[0]] = pred\n            self.start_idx = self.start_idx + pred.shape[0]\n\n    def add_session(self, id, data_len):\n        self.sessions[id] = self.Session(data_len, self.dims)\n\n    def remove_session(self, id):\n        del self.sessions[id]\n\n    def reset_activations(self, id):\n        self.sessions[id].reset_activations()\n\n    def add_activation(self, id, batch, inf_model=None):\n        \"\"\"Calculates the activations of the pool_3 layer for all images.\n\n        Params:\n        -- dataloader  : Dataloader containing images or inputs to inf_model\n        -- inf_model   : Model in which to input the dataset. Use dataset directly\n                         if inf_model is None.\n\n        Returns:\n        -- A numpy array of dimension (num images, dims) that contains the\n           activations of the given tensor when feeding inception with the\n           query tensor.\n        \"\"\"\n\n        batch = batch.to(self.device)\n        pred = self.calculate_activation(batch, inf_model)\n        self.sessions[id].add_activation(pred)\n\n    def calculate_activation(self, batch, inf_model=None):\n        # Use output of inf_model instead of batch if an inf_model is given.\n        with torch.no_grad():\n            if inf_model is not None:\n                batch = inf_model(batch)\n            pred = self.model(batch)[0]\n\n        # If model output is not scalar, apply global spatial average pooling.\n        # This happens if you choose a dimensionality not equal 2048.\n        if pred.size(2) != 1 or pred.size(3) != 1:\n            pred = adaptive_avg_pool2d(pred, output_size=(1, 1))\n\n        pred = pred.squeeze(3).squeeze(2).cpu().numpy()\n\n        return pred\n\n    def calculate_activation_statistics(self, id):\n        \"\"\"Calculation of the statistics used by the FID.\n        Params:\n        -- dataloader  : Dataloader containing images or inputs to inf_model\n        -- inf_model   : Model in which to input the dataset. Use dataset directly\n                         if inf_model is None.\n\n        Returns:\n        -- mu    : The mean over samples of the activations of the pool_3 layer of\n                   the inception model.\n        -- sigma : The covariance matrix of the activations of the pool_3 layer of\n                   the inception model.\n        \"\"\"\n        mu = np.mean(self.sessions[id].pred_arr, axis=0)\n        sigma = np.cov(self.sessions[id].pred_arr, rowvar=False)\n        return mu, sigma\n\n    def calculate_frechet_distance(self, mu1, sigma1, mu2, sigma2, eps=1e-6):\n        \"\"\"Numpy implementation of the Frechet Distance.\n        The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)\n        and X_2 ~ N(mu_2, C_2) is\n                d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).\n\n        Stable version by Dougal J. Sutherland.\n\n        Params:\n        -- mu1   : Numpy array containing the activations of a layer of the\n                   inception net (like returned by the function 'get_predictions')\n                   for generated samples.\n        -- mu2   : The sample mean over activations, precalculated on an\n                   representative data set.\n        -- sigma1: The covariance matrix over activations for generated samples.\n        -- sigma2: The covariance matrix over activations, precalculated on an\n                   representative data set.\n\n        Returns:\n        --   : The Frechet Distance.\n        \"\"\"\n\n        mu1 = np.atleast_1d(mu1)\n        mu2 = np.atleast_1d(mu2)\n\n        sigma1 = np.atleast_2d(sigma1)\n        sigma2 = np.atleast_2d(sigma2)\n\n        assert mu1.shape == mu2.shape, \\\n            'Training and test mean vectors have different lengths'\n        assert sigma1.shape == sigma2.shape, \\\n            'Training and test covariances have different dimensions'\n\n        diff = mu1 - mu2\n\n        # Product might be almost singular\n        covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)\n        if not np.isfinite(covmean).all():\n            msg = ('fid calculation produces singular product; '\n                   'adding %s to diagonal of cov estimates') % eps\n            print(msg)\n            offset = np.eye(sigma1.shape[0]) * eps\n            covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))\n\n        # Numerical error might give slight imaginary component\n        if np.iscomplexobj(covmean):\n            if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):\n                m = np.max(np.abs(covmean.imag))\n                raise ValueError('Imaginary component {}'.format(m))\n            covmean = covmean.real\n\n        tr_covmean = np.trace(covmean)\n\n        return (diff.dot(diff) + np.trace(sigma1) +\n                np.trace(sigma2) - 2 * tr_covmean)\n\n\n", "meta": {"hexsha": "6d007afaacab801ae5a21415ce6fcb3dc7257f90", "size": 7123, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/metrics/fid_score_cumulative.py", "max_stars_repo_name": "johnpeterflynn/surface-texture-inpainting-net", "max_stars_repo_head_hexsha": "b2de05eaa47c9bcca53b9aee12b6012ac2c05156", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/metrics/fid_score_cumulative.py", "max_issues_repo_name": "johnpeterflynn/surface-texture-inpainting-net", "max_issues_repo_head_hexsha": "b2de05eaa47c9bcca53b9aee12b6012ac2c05156", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/metrics/fid_score_cumulative.py", "max_forks_repo_name": "johnpeterflynn/surface-texture-inpainting-net", "max_forks_repo_head_hexsha": "b2de05eaa47c9bcca53b9aee12b6012ac2c05156", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2931937173, "max_line_length": 82, "alphanum_fraction": 0.644812579, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.34864514886966624, "lm_q1q2_score": 0.19331343779996124}}
{"text": "# -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.\n#\n#  File Name : to_tardis_mapper.py\n#\n#  Purpose : Generate Tardis input from generic explosion models\n#\n#  Creation Date : 29-02-2016\n#\n#  Last Modified : Fri 04 Mar 2016 15:23:22 CET\n#\n#  Created By : unoebauer\n#\n# _._._._._._._._._._._._._._._._._._._._._.\n\"\"\"A simple tool to map the output of SN explosion calculations or any ejecta\nmodel into Tardis, using its capability to work with specific density and\nabundance files.\n\"\"\"\nimport numpy as np\nimport logging\nimport astropy.units as units\nfrom pyne import nucname, material\n\nlogger = logging.getLogger(__name__)\n\ntry:\n    material.Material().decay\nexcept AttributeError:\n    logger.critical(\"PyNe module outdated: version >= 0.5 is required\")\n    raise ImportError(\"No recent PyNe module found\")\n\n# maximum atomic number\nzmax = 30\n\n\nclass original_model(object):\n    \"\"\"Simple model interface. It and its derived classes should provide a\n    common interface for all possible explosion model formats.\n\n    This class only requires a minimal set of information, from which all the\n    remaining quantities are constructed (under the assumption of homologous\n    expansion). For each radial shell, the inner and the outer shell radius\n    have to be provided, in addition with the shell density, the mass fractions\n    of all stable elements and of all radioactive elements. The final\n    information to be passed is the time since explosion.\n\n    Velocity and shell masses are generated from these input data, by assuming\n    perfect homologous expansion, (i.e. $u = r/t$) and spherical symmetry.\n\n    Notes\n    -----\n\n    The to_tardis_mapper tool expects that stable_abundances + radio_abundance\n    = 1. In other words, the radioactive isotopes should not be contained in\n    the mass fractions stores in stable_abundances.\n\n    Parameters\n    ----------\n    \"\"\"\n    def __init__(self):\n\n        self._ro = None\n        self._ri = None\n        self._t = None\n        self._rho = None\n\n        self._nzones = None\n        self._vo = None\n        self._vi = None\n        self._dm = None\n        self._mr = None\n\n        self._stable_abundances = None\n        self._radio_abundances = None\n\n    def _reset_cached_variables(self):\n        \"\"\"Resets the cached derived quantities. This routine should be called\n        every time one of the principle inputs (such as density) is reset.\n        \"\"\"\n\n        self._nzones = None\n        self._vo = None\n        self._vi = None\n        self._dm = None\n        self._mr = None\n\n    @property\n    def ro(self):\n        \"\"\"outer shell edge for each radial cell\"\"\"\n        if self._ro is None:\n            raise ValueError(\n                \"You have to read-in or assign the outer cell radii first\")\n        return self._ro\n\n    @ro.setter\n    def ro(self, val):\n        try:\n            val.to(\"cm\")\n        except (AttributeError, units.UnitConversionError):\n            raise ValueError(\n                \"ro must be a valid length astropy.units.Quantity\")\n        self._ro = val\n        self._reset_cached_variables()\n\n    @property\n    def ri(self):\n        \"\"\"inner shell edge for each radial cell\"\"\"\n        if self._ri is None:\n            raise ValueError(\n                \"You have to read-in or assign the inner cell radii first\")\n        return self._ri\n\n    @ri.setter\n    def ri(self, val):\n        try:\n            val.to(\"cm\")\n        except (AttributeError, units.UnitConversionError):\n            raise ValueError(\n                \"ri must be a valid length astropy.units.Quantity\")\n        self._ri = val\n        self._reset_cached_variables()\n\n    @property\n    def rho(self):\n        \"\"\"cell density\"\"\"\n        if self._rho is None:\n            raise ValueError(\n                \"You have to read-in or assign the cell density first\")\n        return self._rho\n\n    @rho.setter\n    def rho(self, val):\n        try:\n            val.to(\"g/cm^3\")\n        except (AttributeError, units.UnitConversionError):\n            raise ValueError(\n                \"rho must be a valid mass density astropy.units.Quantity\")\n        self._rho = val\n        self._reset_cached_variables()\n\n    @property\n    def t(self):\n        \"\"\"time since explosion\"\"\"\n        if self._t is None:\n            raise ValueError(\n                \"You have to read-in or assign the time since explosion first\")\n        return self._t\n\n    @t.setter\n    def t(self, val):\n        try:\n            val.to(\"s\")\n        except (AttributeError, units.UnitConversionError):\n            raise ValueError(\n                \"t must be a valid time astropy.units.Quantity\")\n        self._t = val\n        self._reset_cached_variables()\n\n    @property\n    def nzones(self):\n        \"\"\"number of shells in the model\"\"\"\n        if self._nzones is None:\n            self._nzones = len(self.ro)\n\n        return self._nzones\n\n    @property\n    def vo(self):\n        \"\"\"fluid velocity at outer cell edge\"\"\"\n        if self._vo is None:\n            self._vo = self.ro / self.t\n        return self._vo\n\n    @property\n    def vi(self):\n        \"\"\"fluid velocity at inner cell edge\"\"\"\n        if self._vi is None:\n            self._vi = self.ri / self.t\n        return self._vi\n\n    @property\n    def dm(self):\n        \"\"\"mass contained within a cell\"\"\"\n        if self._dm is None:\n            self._dm = 4. * np.pi / 3. * (self.ro**3 - self.ri**3) * self.rho\n        return self._dm\n\n    @property\n    def mr(self):\n        \"\"\"mass enclosed by shells outer radius\"\"\"\n        if self._mr is None:\n            _mr = np.zeros(self.nzones) * self.dm.unit\n            _mr[0] = self.dm[0]\n            for i in xrange(1, self.nzones):\n                _mr[i] = _mr[i-1] + self.dm[i]\n            self._mr = _mr\n        return self._mr\n\n    @property\n    def stable_abundances(self):\n        \"\"\"a dictionary holding the mass fractions of all stable elements up to\n        Z = zmax. The proton number serves as dictionary key\n        \"\"\"\n        if self._stable_abundances is None:\n            tmp = {}\n\n            for i in xrange(zmax):\n                z = i+1\n                tmp[z] = np.zeros(self.nzones)\n            self._stable_abundances = tmp\n\n        return self._stable_abundances\n\n    @property\n    def radio_abundances(self):\n        \"\"\"a dictionary holding the mass fractions of all radioactive isotopes\n        at time = t. Strings such as 'Ni56', i.e. containing the Element symbol\n        and the mass number, serve as dictionary keys\n        \"\"\"\n        if self._radio_abundances is None:\n            self._radio_abundances = {}\n        return self._radio_abundances\n\n    @property\n    def complete(self):\n        \"\"\"A simple flag determining whether all quantities necessary for the\n        mapping process have been set/read-in\"\"\"\n\n        _complete = False\n        try:\n            self.t\n            self.rho\n            self.ro\n            self.ri\n            _complete = True\n        except ValueError:\n            pass\n\n        try:\n            X = np.array(\n                [self.stable_abundances[z] for z in xrange(1, zmax+1)])\n            _complete = _complete * (X > 0).any()\n        except ValueError:\n            _complete = False\n\n        return _complete\n\n    def read_density(self, fname):\n        \"\"\"A prototype for reading the radius and density information from\n        file\"\"\"\n\n        pass\n\n    def read_abundances(self, fname):\n        \"\"\"A prototype for reading the stable and radioactive elemental\n        abundances from file\"\"\"\n\n        pass\n\n\nclass w7_model(original_model):\n    \"\"\"A simple interface class for the W7 model.\n\n    Notes\n    -----\n    The original W7 model has been presented by [1]_. This reader is designed\n    particular version calculated by [2]_.\n\n    References\n    ----------\n\n    .. [1] Nomoto et al. \"Accreting white dwarf models of Type I supernovae.\n       III - Carbon deflagration supernovae\" ApJ, 1984, 286, 644-658\n    .. [2] Iwamoto et al. \"Nucleosynthesis in Chandrasekhar Mass Models for\n       Type IA Supernovae and Constraints on Progenitor Systems and\n       Burning-Front Propagation\" ApJS, 1999, 125, 439-462\n    \"\"\"\n    def __init__(self):\n        super(w7_model, self).__init__()\n\n    def read_density(self, fname):\n        \"\"\"Read the radius and density of the W7 model from file.\n\n        Parameters\n        ----------\n        fname : str\n            Name of the hydrodynamics file of the W7 model\n        \"\"\"\n\n        f = open(fname, \"r\")\n\n        # read header\n        buffer = f.readline().rsplit()\n        self.t = float(buffer[2]) * units.s\n        buffer = f.readline()\n\n        # read main data block\n        data = np.loadtxt(f)\n        f.close()\n\n        self.ro = data[:, 2] * units.cm\n        self.ri = np.insert(self.ro, 0, 0 * units.cm)[:-1]\n        self.rho = data[:, 3] * units.g / units.cm**3\n\n    def read_abundances(self, fname):\n        \"\"\"Read elemental abundances of the W7 model from file.\n\n        Parameters\n        ----------\n        fname : str\n            Name of the nucleosynthesis file of the W7 model\n        \"\"\"\n\n        f = open(fname, \"r\")\n        data = np.loadtxt(f, skiprows=1)\n        f.close()\n\n        # the file contains abundances for elements from Z=1 to Z=32 (Ge).\n        for i in xrange(np.max([zmax, 32])):\n            self.stable_abundances[i+1] = data[:, i]\n\n        # the last three columns contain the mass fractions of the radioactive\n        # isotopes nickel-56, cobalt-56, nickel-57\n        self.radio_abundances[\"ni56\"] = data[:, 32]\n        self.radio_abundances[\"co56\"] = data[:, 33]\n        self.radio_abundances[\"ni57\"] = data[:, 34]\n\n\nclass to_tardis_mapper(object):\n    \"\"\"A simple mapper object, transforming explosion models, stored in the\n    original_model interface classes, into Tardis specific structure input\n    files\n\n    Parameters\n    ----------\n    orig_model : original_model or derived classes\n        interface object holding the essential data of the original explosion\n        model\n    \"\"\"\n    def __init__(self, orig_model):\n\n        if not orig_model.complete:\n            logger.critical(\"Not all necessary information have been\"\n                            \" set/read-in in the original model\")\n            raise ValueError(\"Check original_model for completeness\")\n        self.orig = orig_model\n\n    def remap(self, v, t, decay=True, write_density=True,\n              density_fname=\"tardis_densities.dat\", write_abundances=True,\n              abundance_fname=\"tardis_abundances.dat\", be_fix=True, be_to_z=6):\n        \"\"\"Perform the remapping of the original model onto a specified Tardis\n        velocity grid. A homologous expansion from the time of the model to the\n        time since explosion used in the Tardis calculation is automatically\n        performed. Optionally, the decay of the radioactive isotopes can also\n        be performed. The remapped model can then be written to Tardis files.\n\n        Notes\n        -----\n        When supplying specific structure files to Tardis, it expects to find\n        also the density and composition of the photosphere. Thus, if the\n        ejecta above the photosphere is supposed to be described by 20 shells,\n        the data files have to contain 21 rows. The specific density and\n        composition of the photosphere is not important since this information\n        is not used within Tardis - the photospheric velocity (i.e. the\n        velocity of the first row) is used!\n\n        Parameters\n        ----------\n        v : array-like astropy.units.Quantity\n            Tardis velocity grid, interpreted as the velocity at the outer\n            shell edges. Mind the photospheric shell!\n        t : scalar astropy.units.Quantity\n            start time (time since explosion) of the Tardis calculation\n        decay : bool\n            perform decay of the radioactive isotopes (default True)\n        write_density : bool\n            write remapped density to a Tardis specific structure file (default\n            True)\n        density_fname : str\n            name of the Tardis specific structure file (default\n            'tardis_densities.dat')\n        write_abundances : bool\n            write remapped abundances to a Tardis specific abundance file\n            (default True)\n        abundance_fname : str\n            name of the Tardis specific structure file (default\n            'tardis_abundances.dat')\n        be_fix : bool\n            perform the Beryllium fix (see #438), i.e. set Be to zero and add\n            its abundance to a different element (default True)\n        be_to_z : int\n            proton number of the destination element for the Be fix (default 6,\n            i.e. carbon)\n        \"\"\"\n\n        self._remap_density(v, t)\n        self._remap_abundances()\n\n        if decay:\n            self._decay_abundances()\n        else:\n            self._copy_radio_abundances()\n        if be_fix:\n            self._be_fix(to_z=be_to_z)\n        if write_density:\n            self._write_tardis_density_file(fname=density_fname)\n        if write_abundances:\n            self._write_tardis_abundance_file(fname=abundance_fname)\n\n    def _remap_density(self, v, t):\n        \"\"\"Remap density of the original_model onto the provided velocity\n        grid and perform a homologous expansion of the density until the\n        defined start time of Tardis\n\n        Notes\n        -----\n\n        For the remapping, we interpolate mr in the v**3 space (corresponds to\n        volume space).\n\n        Parameters\n        ----------\n        v : array-like astropy.units.Quantity\n            Tardis velocity grid, interpreted as the velocity at the outer\n            shell edges. Mind the photospheric shell!\n        t : scalar astropy.units.Quantity\n            start time (time since explosion) of the Tardis calculation\n        \"\"\"\n\n        self.t = t\n        self.N_interp = len(v) - 1\n        self.v_interp_r = v[1:].to(\"cm/s\")\n        self.v_interp_l = v[:-1].to(\"cm/s\")\n\n        V_interp = 4. / 3. * np.pi * ((self.v_interp_r * t).to(\"cm\")**3 -\n                                      (self.v_interp_l * t).to(\"cm\")**3)\n\n        vrorig = self.orig.vo.to(\"cm/s\")\n        mrorig = self.orig.mr.to(\"solMass\")\n\n        mr_interp = np.interp(\n            np.insert(self.v_interp_r, 0, self.v_interp_l[0])**3,\n            np.append(0 * vrorig.unit, vrorig)**3,\n            np.append(0 * mrorig.unit, mrorig)) * mrorig.unit\n\n        self.dm_interp = (mr_interp[1:] - mr_interp[:-1])\n        self.rho_interp = (self.dm_interp / V_interp).to(\"g/cm^3\")\n\n    def _remap_abundances(self):\n        \"\"\"Remap abundances for the original model onto the grid defined in\n        _remap_density. This routine has be called after _remap_density is\n        performed.\n\n        Notes\n        -----\n        Must be called after _remap_density.\n\n        Raises\n        ------\n        AttributeError if called before _remap_density\n        \"\"\"\n        try:\n            self.v_interp_l\n            self.v_interp_r\n        except AttributeError:\n            logger.critical(\"Density must be remapped before abundances are\"\n                            \" addressed\")\n            raise AttributeError(\"no v_interp_r; call _remap_density first\")\n\n        self.abundances_interp = {}\n        self.radio_abundances_interp = {}\n\n        def remap_species(Xorig):\n            \"\"\"helper routine to remap one specific elemental species onto the\n            new velocity grid\n\n            Parameters\n            ----------\n            Xorig : numpy.ndarray\n                original mass fraction of the original model\n\n            Returns\n            -------\n            X_interp : numpy.ndarray\n                remapped mass fractions, corresponding to the Tardis model\n            \"\"\"\n\n            vrorig = self.orig.vo.to(\"cm/s\")\n            Xrorig = np.zeros(len(Xorig)) * self.orig.dm.unit\n\n            Xrorig[0] = self.orig.dm[0] * Xorig[0]\n            for i in xrange(1, self.orig.nzones):\n                Xrorig[i] += Xrorig[i-1] + self.orig.dm[i] * Xorig[i]\n\n            X_interp = np.interp(\n                np.insert(self.v_interp_r, 0, self.v_interp_l[0])**3,\n                np.append(0 * vrorig.unit, vrorig)**3,\n                np.append(0 * Xrorig.unit, Xrorig)) * Xrorig.unit\n\n            X_interp = X_interp[1:] - X_interp[:-1]\n\n            return (X_interp / self.dm_interp).to(\"\").value\n\n        # remap stable elements\n        for z in xrange(1, zmax+1):\n\n            Xorig = self.orig.stable_abundances[z]\n            X_interp = remap_species(Xorig)\n\n            self.abundances_interp[z] = X_interp\n\n        # remap radioactive isotopes\n        for ident in self.orig.radio_abundances.keys():\n\n            Xorig = self.orig.radio_abundances[ident]\n\n            X_interp = remap_species(Xorig)\n\n            self.radio_abundances_interp[ident] = X_interp\n\n    def _copy_radio_abundances(self):\n        \"\"\"Copies the radioactive isotopes onto the corresponding stable\n        elements. This routine is intended for uses of the mapper during which\n        the decay is neglected\n\n        Notes\n        -----\n        Must be called after _remap_abundances.\n\n        Raises\n        ------\n        AttributeError if called before _remap_abundances\n        \"\"\"\n        try:\n            self.radio_abundances_interp\n        except AttributeError:\n            logger.critical(\"Abundances must be remapped before radioactive:\"\n                            \" isotopes are copied onto the stable elements\")\n            raise AttributeError(\"no radio_abundances_interp; call\"\n                                 \" _remap_abundances first\")\n\n        for ident in self.radio_abundances_interp.keys():\n            elemid = nucname.id(ident)\n            z = nucname.znum(elemid)\n            self.abundances_interp[z] = \\\n                self.abundances_interp[z] + self.radio_abundances_interp[ident]\n\n    def _decay_abundances(self):\n        \"\"\"Determines the decay of all radioactive isotopes. Afterwards their\n        mass fractions are added to the stable elements.\n\n        Notes\n        -----\n        Must be called after _remap_abundances.\n\n        Raises\n        ------\n        AttributeError if called before _remap_abundances\n        \"\"\"\n        try:\n            self.radio_abundances_interp\n        except AttributeError:\n            logger.critical(\"Abundances must be remapped before decay is\"\n                            \" handled\")\n            raise AttributeError(\"no radio_abundances_interp; call \"\n                                 \"_remap_abundances first\")\n\n        for i in xrange(self.N_interp):\n            comp = {}\n            mass = 0\n            for ident in self.radio_abundances_interp.keys():\n                Xi = self.radio_abundances_interp[ident][i]\n                mass += Xi\n                comp[nucname.id(ident)] = Xi\n            inp = material.Material(comp, mass=mass)\n            res = inp.decay(\n                (self.t - self.orig.t).to(\"s\").value).mult_by_mass()\n\n            for item in res.items():\n                z = nucname.znum(item[0])\n                self.abundances_interp[z][i] = \\\n                    self.abundances_interp[z][i] + item[1]\n\n    def _be_fix(self, to_z=6):\n        \"\"\"Set Beryllium abundance to zero and add its mass fraction to another\n        (specified) element. This is done to avoid issue #438.\n\n        Notes\n        -----\n        Must be called after _remap_abundances.\n\n        Parameters\n        ---------\n        to_z : int\n            proton number of the destination element for the Be fix (default 6,\n            i.e. carbon)\n\n        Raises\n        ------\n        AttributeError if called before _remap_abundances\n        \"\"\"\n        try:\n            self.abundances_interp\n        except AttributeError:\n            logger.critical(\"Abundances must be remapped before the Be fix can\"\n                            \" be applied\")\n            raise AttributeError(\"no abundances_interp; call\"\n                                 \" _remap_abundances first\")\n\n        logger.info(\"Total relative Be mass in model: {:e}\\n\".format(\n            (self.abundances_interp[4] * self.dm_interp).sum() /\n            self.dm_interp.sum()))\n\n        self.abundances_interp[to_z] = (\n            self.abundances_interp[to_z] + self.abundances_interp[4])\n        self.abundances_interp[4] = np.zeros(self.N_interp)\n\n    def _write_tardis_abundance_file(self, fname=\"tardis_abundances.dat\"):\n        \"\"\"Write specific density file for Tardis\n\n        Parameters\n        ----------\n        fname : str\n            name of the Tardis specific structure file (default\n            'tardis_abundances.dat')\n        \"\"\"\n        f = open(fname, \"w\")\n        f.write(\"# index Z=1 - Z={:d}\\n\".format(zmax))\n        X = np.zeros((zmax+1, self.N_interp+1))\n\n        X[0, :] = np.arange(self.N_interp+1)\n        X[1:, 1:] = np.array(\n            [self.abundances_interp[z] for z in xrange(1, zmax+1)])\n        X[1:, 0] = X[1:, 1]\n\n        np.savetxt(f, X.T, fmt=[\"% 4d\"] + [\"%.7e\" for i in xrange(1, zmax+1)])\n        f.close()\n\n    def _write_tardis_density_file(self, fname=\"tardis_densities.dat\"):\n        \"\"\"Write specific abundance file for Tardis\n\n        Parameters\n        ----------\n        fname : str\n            name of the Tardis specific structure file (default\n            'tardis_densities.dat')\n        \"\"\"\n        f = open(fname, \"w\")\n\n        f.write(\"{:f} {:s}\\n\".format(self.t.to(\"day\").value, \"day\"))\n        f.write(\"# index velocity (km/s) density (g/cm^3)\\n\")\n        X = np.array([np.arange(self.N_interp+1),\n                     np.insert(self.v_interp_r.to(\"km/s\"), 0,\n                               self.v_interp_l.to(\"km/s\")[0]).value,\n                     np.insert(self.rho_interp.to(\"g/cm^3\"), 0,\n                               self.rho_interp.to(\"g/cm^3\")[0]).value]).T\n        np.savetxt(f, X, fmt=[\"% 4d\", \"% 9.3f\", \"%.7e\"])\n\n        f.close()\n", "meta": {"hexsha": "c8ca58111e1d4ce6862cccfc62784c39238dd897", "size": 21822, "ext": "py", "lang": "Python", "max_stars_repo_path": "to_tardis_mapper.py", "max_stars_repo_name": "jamesgillanders/tardisanalysis", "max_stars_repo_head_hexsha": "b5c27784d3d1db224c629a9d8418a0d126d2f1c8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-08-25T15:00:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T16:53:30.000Z", "max_issues_repo_path": "to_tardis_mapper.py", "max_issues_repo_name": "jamesgillanders/tardisanalysis", "max_issues_repo_head_hexsha": "b5c27784d3d1db224c629a9d8418a0d126d2f1c8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2015-08-25T10:32:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-26T10:59:11.000Z", "max_forks_repo_path": "to_tardis_mapper.py", "max_forks_repo_name": "jamesgillanders/tardisanalysis", "max_forks_repo_head_hexsha": "b5c27784d3d1db224c629a9d8418a0d126d2f1c8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2015-08-25T10:19:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T12:10:42.000Z", "avg_line_length": 33.1138088012, "max_line_length": 79, "alphanum_fraction": 0.5831271194, "include": true, "reason": "import numpy,import astropy", "num_tokens": 5122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.3486451353339458, "lm_q1q2_score": 0.1933134354283639}}
{"text": "\"\"\"\nComputes the Heat of Formation at 0 K for a given species\n\"\"\"\n\nimport os\nimport csv\nimport numpy as np\nfrom qcelemental import constants as qcc\nimport autoparse.pattern as app\nimport autoparse.find as apf\nimport automol.inchi\nimport automol.graph\nfrom . import util\n\n# Conversion factors\nKJ2KCAL = qcc.conversion_factor('kJ/mol', 'kcal/mol')\nEH2KCAL = qcc.conversion_factor('hartree', 'kcal/mol')\n\n# Path  the database files (stored in the thermo src directory)\nSRC_PATH = os.path.dirname(os.path.realpath(__file__))\n\n\ndef get_hform_298k_thermp(output_string):\n    \"\"\"\n    Obtains deltaHf from thermp output\n    \"\"\"\n\n    # Line pattern containing the DeltaHf value at 298 K\n    dhf298_pattern = ('h298 final' +\n                      app.one_or_more(app.SPACE) +\n                      app.capturing(app.FLOAT))\n    dhf298 = float(apf.last_capture(dhf298_pattern, output_string))\n\n    return dhf298\n\n\ndef calc_hform_0k(hzero_mol, hzero_basis, basis, coeff, ref_set):\n    \"\"\" calculates the heat-of-formation at 0 K\n    \"\"\"\n\n    # Calculate the heat of formation\n    dhzero = hzero_mol * EH2KCAL\n    for i, spc in enumerate(basis):\n        h_basis = get_ref_h(spc, ref_set, 0)\n        if h_basis is None:\n            h_basis = 0.0\n        dhzero += coeff[i] * h_basis * KJ2KCAL\n        dhzero -= coeff[i] * hzero_basis[i] * EH2KCAL\n\n    return dhzero\n\n\ndef get_ref_h(species, ref, temp):\n    \"\"\" gets a reference value\n    \"\"\"\n\n    # Set path and name to thermo database file\n    thermodb_name = 'thermodb_{}K.csv'.format(str(int(temp)))\n    thermodb_file = os.path.join(SRC_PATH, thermodb_name)\n\n    # Find the energy value for the given species and enery type\n    h_species = None\n    with open(thermodb_file, 'r') as db_file:\n        reader = csv.DictReader(db_file)\n        for row in reader:\n            if row['inchi'] == species:\n                val = row[ref]\n                if val == '':\n                    val = None\n                h_species = float(val)\n\n    return h_species\n\n\ndef select_basis(atom_dct, att=0):\n    \"\"\"\n    Given a list of atoms, generates a list of molecules\n    that is best suited to serve as a basis for those atoms\n\n    :param atomlist: list of atoms\n    :type atomlist: list\n    :param att: ???\n    :type att: ???\n\n    OUPUT:\n    basis    - recommended basis as a list of stoichiometries\n    \"\"\"\n\n    # Determine number of basis species required\n    nbasis = len(atom_dct)\n\n    # Get a list of all the atom types in the molecule\n    atoms = list(atom_dct.keys())\n\n    # Create list of inchi keys corresponding to basis species\n    basis = []\n    # H2\n    basis.append('InChI=1S/H2/h1H')\n    # NH3\n    if 'N' in atoms:\n        basis.append('InChI=1S/H3N/h1H3')\n    # CH4\n    if 'C' in atoms:\n        basis.append('InChI=1S/CH4/h1H4')\n    # H2O\n    if 'O' in atoms:\n        basis.append('InChI=1S/H2O/h1H2')\n    # SO2\n    if 'S' in atoms:\n        basis.append('InChI=1S/O2S/c1-3-2')\n        if not 'O' in atoms:\n            basis.append('InChI=1S/H2O/h1H2')\n\n    return basis\n\n\ndef get_reduced_basis(basis_ich, species_formula):\n    \"\"\"\n    Form a matrix for a given basis and atomlist\n    INPUT:\n    input_basis     - ich strings for set of reference molecules\n    atomlist  - list of atoms (all atoms that appear\n                in basis should be in atomlist)\n    OUTPUT:\n    mat       - matrix (length of basis by length of atomlist)\n                (square if done right)\n    \"\"\"\n\n    # Get the basis formulae list\n    basis_formulae = [util.inchi_formula(spc) for spc in basis_ich]\n\n    reduced_basis = []\n    for i, basis_formula in enumerate(basis_formulae):\n        basis_atom_dict = util.get_atom_counts_dict(basis_formula)\n        flag = True\n        for key, _ in basis_atom_dict.items():\n            if key not in species_formula:\n                flag = False\n\n        if flag:\n            reduced_basis.append(basis_ich[i])\n\n    return reduced_basis\n\n\ndef calc_coefficients(basis, mol_atom_dict):\n    \"\"\"\n    Form a matrix for a given basis and atomlist\n    INPUT:\n    basis     - basis of molecules\n    atomlist  - list of atoms (all atoms that appear\n                in basis should be in atomlist)\n    OUTPUT:\n    mat       - matrix (length of basis by length of atomlist)\n                (square if done right)\n    \"\"\"\n\n        \n    # Initialize an natoms x natoms matrix\n    nbasis = len(basis)\n    basis_mat = np.zeros((nbasis, nbasis))\n\n    # Get the basis formulae list\n    basis_formulae = [util.inchi_formula(spc) for spc in basis]\n    #basis_atom_dict = [automol.geom.formula(automol.inchi.geom(spc) for spc in basis]\n    for spc in basis_formulae:\n        basis_atom_dict = util.get_atom_counts_dict(spc)\n        for atom in basis_atom_dict:\n            if not atom in mol_atom_dict:\n                mol_atom_dict[atom] = 0\n    # Set the elements of the matrix\n    for i, spc in enumerate(basis_formulae):\n        basis_atom_dict = util.get_atom_counts_dict(spc)\n        basis_vals = []\n        for key in mol_atom_dict.keys():\n            if key in basis_atom_dict:\n                basis_vals.append(basis_atom_dict[key])\n            else:\n                basis_vals.append(0)\n        basis_mat[i] = basis_vals\n\n    #  Transpose\n    basis_mat = basis_mat.T\n\n    # Form stoich vector\n    stoich_vec = np.zeros(len(mol_atom_dict))\n    for i, key in enumerate(mol_atom_dict.keys()):\n        stoich_vec[i] = mol_atom_dict[key]\n\n    # Solve C = M^-1 S\n    basis_mat = np.linalg.inv(basis_mat)\n    coeff = np.dot(basis_mat, stoich_vec)\n\n    return coeff\n\n\ndef stoich(ich):\n    \"\"\"\n    Finds the stoichiometry of a molecule\n    INPUT:\n    ich  -- STR inchii\n    OUTPUT:\n    stoich -- dictionary with key = STR atomsymbol,\n                val = INT number of atomsymbol in molecule\n    \"\"\"\n\n    stoich = {'H': 0}\n    gra = automol.inchi.graph(ich)\n    atms = automol.graph.atoms(gra)\n    for atm in atms:\n        stoich['H'] += atms[atm][1]\n        if atms[atm][0] in stoich:\n            stoich[atms[atm][0]] += 1\n        else:\n            stoich[atms[atm][0]] = 1\n    return stoich\n\n\ndef cbhzed(ich):\n    \"\"\"\n    Fragments molecule so that each heavy-atom is a seperate fragment\n    INPUT:\n    ich --  STR inchii name for molecule\n    OUTPUT\n    frags -- DIC dictionary with keys as STR inchii name for fragments\n    and value as INT their coefficient\n    \"\"\"\n\n    # Graphical info about molecule\n    gra = automol.inchi.graph(ich)\n    rad_atms = list(automol.graph.sing_res_dom_radical_atom_keys(gra))\n    atm_vals = automol.graph.atom_element_valences(gra)\n    atms = automol.graph.atoms(gra)\n\n    # Determine CBHzed fragments\n    frags = {}\n    for atm in atm_vals:\n        if atm in rad_atms:\n            atm_vals[atm] -= 1\n        atm_dic = {0: (atms[atm][0], int(atm_vals[atm]), None)}\n        gra = (atm_dic, {})\n        frag = automol.graph.inchi(gra)\n        _add2dic(frags, frag)\n\n    return _balance_frags(ich, frags)\n\n\ndef cbhone(ich):\n    \"\"\"\n    Fragments molecule in a way that conserves each heavy-atom/heavy-atom bond\n    INPUT:\n    ich --  STR inchii name for molecule\n    OUTPUT\n    frags -- DIC dictionary with keys as STR inchii name for fragments\n    and value as INT their coefficient\n    \"\"\"\n\n    # Graphical info about molecule\n    gra = automol.inchi.graph(ich)\n    atms = automol.graph.atoms(gra)\n    bnd_ords = automol.graph.one_resonance_dominant_bond_orders(gra)\n    rad_atms = list(automol.graph.sing_res_dom_radical_atom_keys(gra))\n    atm_vals = automol.graph.atom_element_valences(gra)\n    adj_atms = automol.graph.atom_neighbor_keys(gra)\n\n    # Determine CBHone fragments\n    frags = {}\n    for atm in atm_vals:\n        for adj in list(adj_atms[atm]):\n            if atm > adj:\n                vali = atm_vals[atm]\n                valj = atm_vals[adj]\n                if atm in rad_atms:\n                    vali -= 1\n                if adj in rad_atms:\n                    valj -= 1\n                key = frozenset({atm, adj})\n                bnd_ord = list(bnd_ords[key])[0]\n                vali -= bnd_ord\n                valj -= bnd_ord\n                atm_dic = {0: (atms[atm][0], int(vali), None),\n                           1: (atms[adj][0], int(valj), None)}\n                bnd_dic = {frozenset({0, 1}): (1, None)}\n                gra = (atm_dic, bnd_dic)\n                frag = automol.graph.inchi(gra)\n                _add2dic(frags, frag)\n    frags = {k: v for k, v in frags.items() if v}\n\n    # Balance\n    balance_ = _balance(ich, frags)\n    balance_ = {k: v for k, v in balance_.items() if v}\n\n    if balance_:\n        newfrags = {}\n        zedfrags = cbhzed(ich)\n        new = {}\n        for frag in frags:\n            newfrags[frag] = frags[frag]\n            new = cbhzed(frag)\n            for n in new:\n                _add2dic(newfrags, n, - new[n] * frags[frag])\n        if not frags:\n            frags = cbhzed(ich)\n        for frag in zedfrags:\n            if frag in newfrags:\n                _add2dic(newfrags, frag, zedfrags[frag])\n        frags = newfrags\n        frags = {k: v for k, v in frags.items() if v}\n        balance_ = _balance(ich, frags)\n        balance_ = {k: v for k, v in balance_.items() if v}\n\n    if balance_:\n        frags = _balance_frags(ich, frags)\n\n    return frags\n\n\ndef cbhtwo(ich):\n    \"\"\"\n    Fragments molecule for each heavy-atom to stay bonded to its adjacent atoms\n    INPUT:\n    ich --  STR inchii name for molecule\n    OUTPUT\n    frags -- DIC dictionary with keys as STR inchii name for fragments and\n    value as INT their coefficient\n    \"\"\"\n\n    # Graphical info about molecule\n    gra = automol.inchi.graph(ich)\n    atms = automol.graph.atoms(gra)\n    bnd_ords = automol.graph.one_resonance_dominant_bond_orders(gra)\n    rad_atms = list(automol.graph.sing_res_dom_radical_atom_keys(gra))\n    atm_vals = automol.graph.atom_element_valences(gra)\n    adj_atms = automol.graph.atom_neighbor_keys(gra)\n\n    # Determine CBHtwo fragments\n    frags = {}\n    for atm in atms:\n        vali = atm_vals[atm]\n        if atm in rad_atms:\n            vali -= 1\n        # First loop over all atoms of this frag to get saturation of atomi\n        for adj in list(adj_atms[atm]):\n            key = frozenset({atm, adj})\n            bnd_ord = list(bnd_ords[key])[0]\n            vali -= bnd_ord\n        atm_dic = {0: (atms[atm][0], int(vali), None)}\n        bnd_dic = {}\n        # Then start adding bonds to the bnddic and atomdic\n        j = 0\n        for adj in list(adj_atms[atm]):\n            j += 1\n            valj = atm_vals[adj]\n            if adj in rad_atms:\n                valj -= 1\n            key = frozenset({atm, adj})\n            bnd_ord = list(bnd_ords[key])[0]\n            valj -= bnd_ord\n            atm_dic[j] = (atms[adj][0], int(valj), None)\n            bnd_dic[frozenset({0, j})] = (1, None)\n        gra = (atm_dic, bnd_dic)\n        frag = automol.graph.inchi(gra)\n        _add2dic(frags, frag)\n\n    frags = {k: v for k, v in frags.items() if v}\n\n    # Balance\n    balance_ = _balance(ich, frags)\n    balance_ = {k: v for k, v in balance_.items() if v}\n    if balance_:\n        newfrags = {}\n        onefrags = cbhone(ich)\n        new = {}\n        for frag in frags:\n            newfrags[frag] = frags[frag]\n            new = cbhone(frag)\n            for n in new:\n                _add2dic(newfrags, n, - new[n] * frags[frag])\n        if not frags:\n            frags = cbhone(ich)\n        for frag in onefrags:\n            if frag in newfrags:\n                _add2dic(newfrags, frag, onefrags[frag])\n        frags = newfrags\n        frags = {k: v for k, v in frags.items() if v}\n\n        balance_ = _balance(ich, frags)\n        balance_ = {k: v for k, v in balance_.items() if v}\n        if balance_:\n            newfrags = {}\n            zedfrags = cbhzed(ich)\n            new = {}\n            for frag in frags:\n                newfrags[frag] = frags[frag]\n                new = cbhzed(frag)\n                for n in new:\n                    _add2dic(newfrags, n, - new[n] * frags[frag])\n            if not frags:\n                frags = cbhzed(ich)\n            for frag in zedfrags:\n                if frag in newfrags:\n                    _add2dic(newfrags, frag, zedfrags[frag])\n            frags = newfrags\n            frags = {k: v for k, v in frags.items() if v}\n\n            balance_ = _balance(ich, frags)\n            balance_ = {k: v for k, v in balance_.items() if v}\n            if balance_:\n                frags = _balance_frags(ich, frags)\n\n    return frags\n\n\ndef get_basis(ich):\n    formula  = util.inchi_formula(ich)\n    atm_dict = util.get_atom_counts_dict(formula)\n    return select_basis(atm_dict)\n\n\ndef get_cbhzed(ich):\n    return list(cbhzed(ich).keys())\n\n\ndef get_cbhone(ich):\n    return list(cbhone(ich).keys())\n\n\ndef get_cbhtwo(ich):\n    return list(cbhtwo(ich).keys())\n\n\ndef _add2dic(dic, key, val=1):\n    if key in dic:\n        dic[key] += val\n    else:\n        dic[key] = val\n\n\ndef _lhs_rhs(frags):\n    rhs = {}\n    lhs = {}\n    for frag in frags:\n        if frags[frag] > 0:\n            rhs[frag] = frags[frag]\n        elif frags[frag] < 0:\n            lhs[frag] = - frags[frag]\n    return lhs, rhs\n\n\ndef _print_lhs_rhs(ich, frags):\n    lhs, rhs = _lhs_rhs(frags)\n    lhsprint = automol.inchi.smiles(ich)\n    rhsprint = ''\n    for frag in rhs:\n        if rhsprint:\n            rhsprint += ' +  {:.1f} {} '.format(\n                rhs[frag], automol.inchi.smiles(frag))\n        else:\n            rhsprint = ' {:.1f} {} '.format(\n                rhs[frag], automol.inchi.smiles(frag))\n    for frag in lhs:\n        lhsprint += ' +  {:.1f} {} '.format(\n            lhs[frag], automol.inchi.smiles(frag))\n    return '{} --> {}'.format(lhsprint, rhsprint)\n\n\ndef _balance(ich, frags):\n    stoichs = {}\n    for frag in frags:\n        _stoich = stoich(frag)\n        for atm in _stoich:\n            if atm in stoichs:\n                stoichs[atm] += _stoich[atm] * frags[frag]\n            else:\n                stoichs[atm] = _stoich[atm] * frags[frag]\n    balance_ = {}\n    _stoich = stoich(ich)\n    for atom in _stoich:\n        if atom in stoichs:\n            balance_[atom] = _stoich[atom] - stoichs[atom]\n        else:\n            balance_[atom] = _stoich[atom]\n    balance_ = {x: y for x, y in balance_.items() if y != 0}\n    return balance_\n\n\ndef _balance_frags(ich, frags):\n    balance_ = _balance(ich, frags)\n    methane = automol.smiles.inchi('C')\n    water = automol.smiles.inchi('O')\n    ammonm = automol.smiles.inchi('N')\n    hydrgn = automol.smiles.inchi('[H][H]')\n    if 'C' in balance_:\n        _add2dic(frags, methane, balance_['C'])\n    if 'N' in balance_:\n        _add2dic(frags, ammonm, balance_['N'])\n    if 'O' in balance_:\n        _add2dic(frags, water, balance_['O'])\n    balance_ = _balance(ich, frags)\n    if 'H' in balance_:\n        _add2dic(frags, hydrgn, balance_['H']/2)\n    return frags\n", "meta": {"hexsha": "43cb70baef2fb008df7ee8cc6fe0a701fd6c997e", "size": 14797, "ext": "py", "lang": "Python", "max_stars_repo_path": "thermo/heatform.py", "max_stars_repo_name": "mobergd/interfaces", "max_stars_repo_head_hexsha": "82705d2173b9d213684da80913ec0593d30cdbe1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thermo/heatform.py", "max_issues_repo_name": "mobergd/interfaces", "max_issues_repo_head_hexsha": "82705d2173b9d213684da80913ec0593d30cdbe1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thermo/heatform.py", "max_forks_repo_name": "mobergd/interfaces", "max_forks_repo_head_hexsha": "82705d2173b9d213684da80913ec0593d30cdbe1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4174950298, "max_line_length": 86, "alphanum_fraction": 0.5817395418, "include": true, "reason": "import numpy", "num_tokens": 4162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.193313430294804}}
{"text": "## Observation correction model\n\nimport numpy as np\n\nimport astropy.time\nimport astropy.coordinates\nimport astropy.units as u\nimport astropy.units.imperial\nimport astropy.units.cds\n\nimport bossdata\nimport specsim\n\nimport tpcorr.pointing\nimport tpcorr.guider\nimport tpcorr.acceptance_model\n\nclass Observation(object):\n    def __init__(self, plate, mjd, guide_wlen=5400 * u.Angstrom, offset_wlen=4000 * u.Angstrom,\n        std_wlen=5400 * u.Angstrom, wlen_grid_steps=15, steps_per_exposure=5,\n        pressure0=None, temperature0=None):\n        print 'Calculating corrections for {} observed on MJD {}'.format(plate, mjd)\n\n        self.plate = plate\n        self.mjd = mjd\n        self.guide_wlen = guide_wlen\n        self.std_wlen = std_wlen\n        self.offset_wlen = offset_wlen\n        self.steps_per_exposure = steps_per_exposure\n        self.wlen_grid_steps = wlen_grid_steps\n        \n        self.finder = bossdata.path.Finder()\n        self.mirror = bossdata.remote.Manager()\n\n        # Get the list of exposures used in this observation's coadd from a spec lite file.\n        spec_name = self.finder.get_spec_path(plate, mjd, fiber=1, lite=True)\n        self.spec_file = bossdata.spec.SpecFile(self.mirror.get(spec_name))\n\n        # Read the first b1 raw science exposure to find this plate's plug map.\n        raw = self.spec_file.get_raw_image(0, 'blue', finder=self.finder, mirror=self.mirror)\n        plug_map = raw.read_plug_map()\n\n        # Look up the plate design pointing from the raw header and convert to\n        # an index A,B,C,... -> 0,1,2,...\n        pointing_label = raw.header['POINTING'].strip()\n        pointing_index = ord(pointing_label) - ord('A')\n        \n        # Initialize a pointing object for this plate's sky location.\n        ra_center = float(plug_map['raCen']) * u.deg\n        self.ra_center = ra_center\n        dec_center = float(plug_map['decCen']) * u.deg\n        print 'Plate center is RA={:.3f}, DEC={:.3f} for {}-{}'.format(ra_center, dec_center, plate, pointing_label)\n        self.pointing = tpcorr.pointing.Pointing(ra_center, dec_center)\n        \n        # Find the nominal observing temperature and time that this plate's holes are drilled for.\n        self.design_temp = float(plug_map['temp'])*u.deg_C\n        self.design_pressure = None # Calculate based on elevation and temperature\n        self.design_ha = float(plug_map['ha'].split()[pointing_index]) * u.deg\n        midnight = astropy.time.Time(mjd, format='mjd', scale='tai', location=self.pointing.where)\n        design_time = specsim.transform.adjust_time_to_hour_angle(midnight, ra_center, self.design_ha, max_iterations=100)\n        self.design_tai = design_time.mjd * 86400.\n        print 'Holes drilled for T={:.1f} and HA={:.1f} (TAI={:.1f})'.format(self.design_temp, self.design_ha, self.design_tai)\n        \n        # design_time.mjd\n        # when = astropy.time.Time(tai/86400., format='mjd', scale='tai', location=self.where)\n        self.design_alt = self.pointing.plate_center.transform_to(astropy.coordinates.AltAz(\n            obstime=design_time, location=self.pointing.where)).alt.to(u.deg)\n\n        # Find this plate's guide stars.\n        plugging = plug_map['PLUGMAPOBJ']\n        guide_fibers = plugging['holeType'] == 'GUIDE'\n\n        guide_ra, guide_dec = plugging['ra'][guide_fibers], plugging['dec'][guide_fibers]\n        self.guide_targets = astropy.coordinates.ICRS(guide_ra * u.deg, guide_dec * u.deg)\n        \n        # Calculate the nominal guide fiber positions.\n        self.guide_x0, self.guide_y0, _, _ = self.pointing.transform(\n            self.guide_targets, self.design_tai, guide_wlen, self.design_temp, self.design_pressure)\n        \n        # Find this plate's offset fibers. We have to use spAll for this since the plug map does\n        # not record the design wavelengths.\n        self.plugmap = self.get_plugmap_from_spframes()\n\n        offset_fibers_mask = self.plugmap['LAMBDA_EFF'] == offset_wlen.to(u.Angstrom).value\n        offset_fibers = self.plugmap[offset_fibers_mask]\n\n        offset_xfocal = offset_fibers['XFOCAL'] * u.mm\n        offset_yfocal = offset_fibers['YFOCAL'] * u.mm\n        self.fiber_ids = offset_fibers['FIBERID']\n        self.offset_targets = astropy.coordinates.ICRS(ra=offset_fibers['RA'] * u.deg, dec=offset_fibers['DEC'] * u.deg)\n        self.num_offset_targets = np.count_nonzero(self.offset_targets)\n        print 'Plate has {:d} guide fibers and {:d} offset targets.'.format(len(self.guide_targets), self.num_offset_targets)\n\n        if self.num_offset_targets > 0:\n            # Calculate the nominal science fiber positions. These will not match XFOCAL, YFOCAL\n            # exactly since we do not exactly replicate the IDL transforms, but they should be\n            # close (within ~0.2 arcsec) and we only use offsets calculated consistently with\n            # transform() in the following.\n            self.offset_x0, self.offset_y0, offset_alt, offset_az = self.pointing.transform(\n                self.offset_targets, self.design_tai, offset_wlen, self.design_temp, self.design_pressure)\n        \n            # Calculate where the offset target fibers would have been positioned if they were\n            # designed for the same wavelength as the standard stars.\n            self.offset_x0_std, self.offset_y0_std, _, _ = self.pointing.transform(\n                self.offset_targets, self.design_tai, std_wlen, self.design_temp, self.design_pressure)\n        \n        # Initialize the wavelength grid to use for calculating corrections.\n        self.wlen_grid = np.linspace(3500., 10500., wlen_grid_steps)[:, np.newaxis] * u.Angstrom\n        \n        # Initialize guided target centroid list\n        self.guided_centroids = []\n\n        # Initialize exposure meta data lists\n        self.seeing = np.empty((self.spec_file.num_exposures)) * u.arcsec\n        self.ha = np.empty((self.spec_file.num_exposures)) * u.degree\n        self.pressure = np.empty((self.spec_file.num_exposures)) * u.kPa\n        self.temperature = np.empty((self.spec_file.num_exposures)) * u.deg_C\n        self.tai_beg = np.empty((self.spec_file.num_exposures)) # seconds\n        self.tai_end = np.empty((self.spec_file.num_exposures)) # seconds\n        self.alt = np.empty((self.spec_file.num_exposures)) * u.degree\n\n        self.init_exposure_meta(pressure=pressure0, temperature=temperature0)\n\n\n    def init_exposure_meta(self, seeing=None, pressure=None, temperature=None):\n        # Precompute the conversion from inches of Hg to kPa.\n        pconv = (1 * u.cds.mmHg * u.imperial.inch / u.mm).to(u.kPa).value\n\n        # Loop over exposures\n        for exp_index in range(self.spec_file.num_exposures):\n\n            # Open the b1 frame for this exposure, to access its metadata.\n            b1_frame_name = self.finder.get_plate_path(\n                self.plate, self.spec_file.get_exposure_name(exp_index, 'blue', 'spFrame'))\n            b1_frame = bossdata.plate.FrameFile(self.mirror.get(b1_frame_name))\n            exp_id = b1_frame.exposure_id\n\n            # Lookup this exposure's observing time, seeing, and temperature.\n            self.tai_beg[exp_index] = b1_frame.header['TAI-BEG']\n            self.tai_end[exp_index] = b1_frame.header['TAI-END']\n            tai_mid = 0.5 * (self.tai_beg[exp_index] + self.tai_end[exp_index])\n            \n            # Convert tai to hour angle\n            self.ha[exp_index] = tpcorr.pointing.normalize_angle(\n                self.pointing.hour_angle(tai_mid).to(u.deg).value)*u.deg\n            \n            if seeing is not None:\n                self.seeing[exp_index] = seeing\n            else:\n                if b1_frame.header['SEEING50'] == 0:\n                    self.seeing[exp_index] = 1.49 * u.arcsec\n                    print 'Warning: SEEING50=0. Using nominal value: ', self.seeing[exp_index]\n                else:\n                    self.seeing[exp_index] = b1_frame.header['SEEING50'] * u.arcsec\n\n            if temperature is not None:\n                self.temperature[exp_index] = temperature\n            else:\n                try:\n                    self.temperature[exp_index] = b1_frame.header['AIRTEMP'] * u.deg_C\n                except ValueError, e:\n                    self.temperature[exp_index] = 5 * u.deg_C\n                    print 'Warning: AIRTEMP not available in exp header. Using nominal value: ', self.temperature[exp_index]\n\n            if pressure is not None:\n                self.pressure[exp_index] = pressure\n            else:\n                try:\n                    self.pressure[exp_index] = b1_frame.header['PRESSURE'] * pconv * u.kPa\n                except ValueError, e:\n                    self.pressure[exp_index] = 71.890 * u.kPa\n                    print 'Warning: PRESSURE not available in exp header. Using nominal value: ', self.pressure[exp_index]\n\n            obstime = astropy.time.Time(tai_mid/86400., format='mjd', scale='tai', location=self.pointing.where)\n            self.alt[exp_index] = self.pointing.plate_center.transform_to(astropy.coordinates.AltAz(\n                obstime=obstime, location=self.pointing.where)).alt.to(u.deg)\n\n            print 'Exp[{:02d}] #{:08d} seeing {:.3f}, T={:+5.1f}, P={:.1f}, TAI {:.1f} ({:+7.3f} days, HA {:+.1f})'.format(\n                exp_index, exp_id, self.seeing[exp_index], self.temperature[exp_index], self.pressure[exp_index], \n                tai_mid, (tai_mid - self.design_tai)/86400., self.ha[exp_index])\n\n    def get_plugmap_from_spframes(self):\n        # Read frame files for both spectrographs\n        frames = []\n        for fiber in (1,501):\n            spec_name = self.finder.get_spec_path(self.plate, self.mjd, fiber=fiber, lite=True)\n            spec_file = bossdata.spec.SpecFile(self.mirror.get(spec_name))\n            frame_name = self.finder.get_plate_path(self.plate, spec_file.get_exposure_name(0, 'blue', 'spFrame'))\n            frames.append(bossdata.plate.FrameFile(self.mirror.get(frame_name)))\n        # Stack frame plugmaps\n        return astropy.table.vstack([frame.plug_map for frame in frames])\n\n    def get_exp_centroids(self, exp_index, guide_plot_name=None):\n        # Create time steps covering this exposure.\n        tai_steps = np.linspace(self.tai_beg[exp_index], self.tai_end[exp_index], self.steps_per_exposure)\n\n        # Calculate the actual guide target positions on the focal plane without any guiding.\n        guide_x, guide_y, _, _ = self.pointing.transform(\n            self.guide_targets[:, np.newaxis], tai_steps, self.guide_wlen, self.temperature[exp_index], self.pressure[exp_index])\n        \n        # Solve for the optimal guider corrections.\n        guider = tpcorr.guider.Guider(self.guide_x0, self.guide_y0, guide_x, guide_y)\n        if guide_plot_name:\n            guider.plot(tai_steps, field_radius=340 * u.mm, zoom=5000., \n                fiber_radius=0.1 * u.arcsec * self.pointing.platescale, save=guide_plot_name)\n\n        # Calculate the offset target paths on the focal plane without any guiding, for the actual observing conditions.\n        offset_x, offset_y, _, _ = self.pointing.transform(\n            self.offset_targets[:, np.newaxis, np.newaxis], tai_steps, self.wlen_grid, self.temperature[exp_index], self.pressure[exp_index])\n        \n        # Apply guiding corrections to estimate the actual offset target paths during the exposure.\n        return guider.correct(offset_x, offset_y)\n\n    def get_mean_exp_centroids(self, extrap_wlen=False):\n        # Create time steps covering this exposure.\n        midnight = astropy.time.Time(self.mjd, format='mjd', scale='tai', location=self.pointing.where)\n        ha = np.mean(self.ha)\n        time = specsim.transform.adjust_time_to_hour_angle(midnight, self.ra_center, ha, max_iterations=100)\n        tai = time.mjd * 86400.\n\n        temperature = np.mean(self.temperature)\n        pressure = np.mean(self.pressure)\n\n        print 'Mean Exposure: seeing {:.3f}, T={:+5.1f}, P={:.1f}, TAI {:.1f} ({:+7.3f} days, HA {:+.1f})'.format(\n                np.mean(self.seeing), temperature, pressure, tai, (tai - self.design_tai)/86400., ha)\n\n        # Calculate the actual guide target positions on the focal plane without any guiding.\n        guide_x, guide_y, _, _ = self.pointing.transform(\n            self.guide_targets[:, np.newaxis], tai, self.guide_wlen, self.design_temp, self.design_pressure)\n\n        # Solve for the optimal guider corrections.\n        guider = tpcorr.guider.Guider(self.guide_x0, self.guide_y0, guide_x, guide_y)\n\n        # Calculate the offset target paths on the focal plane without any guiding, for the actual observing conditions.\n        offset_x, offset_y, _, _ = self.pointing.transform(\n            self.offset_targets[:, np.newaxis, np.newaxis], tai, self.wlen_grid, self.design_temp, self.design_pressure, extrap_wlen=extrap_wlen)\n\n        return guider.correct(offset_x, offset_y)\n\n    def get_mean_correction(self, extrap_wlen=False):\n\n        corrections = np.empty((self.num_offset_targets, self.wlen_grid_steps, 1))\n\n        # Estimate the actual offset target paths during the exposure\n        # (offset_x0, offset_y0), (offset_x0_std, offset_y0_std), (guided_x, guided_y) = self.get_mean_exp_centroids()\n        guided_x, guided_y = self.get_mean_exp_centroids(extrap_wlen=extrap_wlen)\n\n        # Calculate centroid offsets for each offset target, relative to its nominal fiber center.\n        offset = np.sqrt(\n            (guided_x - self.offset_x0[:, np.newaxis, np.newaxis])**2 +\n            (guided_y - self.offset_y0[:, np.newaxis, np.newaxis])**2)\n\n        # Calculate centroid offsets for each offset target, relative to where its fiber center would\n        # be if it were designed for the same wavelength as the standard stars.\n        offset_std = np.sqrt(\n            (guided_x - self.offset_x0_std[:, np.newaxis, np.newaxis])**2 +\n            (guided_y - self.offset_y0_std[:, np.newaxis, np.newaxis])**2)\n\n        seeing = np.mean(self.seeing)\n\n        max_offset = 1.1/2.0*max(np.max((offset / self.pointing.platescale).to(u.arcsec)).value,\n                                 np.max((offset_std / self.pointing.platescale).to(u.arcsec)).value)\n\n        acceptance_model = tpcorr.acceptance_model.AcceptanceModel(seeing, max_offset=max_offset)\n\n        # Calculate the acceptance fractions for both sets of centroid offsets.\n        acceptance = acceptance_model((offset / self.pointing.platescale).to(u.arcsec))\n        acceptance_std = acceptance_model((offset_std / self.pointing.platescale).to(u.arcsec))\n        \n        # Calculate the acceptance fraction ratios, tabulated for each offset target, wavelength and time.\n        # The ratio calculated this way gives the correction of eqn (13).\n        corrections = acceptance_std / acceptance\n\n        mean_correction = np.mean(corrections, axis=-1)\n\n        return mean_correction, guided_x, guided_y\n\n    def get_corrections(self, seeing_wlen=5400.*u.Angstrom):\n\n        # Precompute wlen ratio for wavelength dependent seeing adjustment\n        wlen_ratio = (self.wlen_grid / seeing_wlen).si\n\n        # Initialize acceptance ratio grid\n        corrections = np.empty(\n            (self.spec_file.num_exposures, self.num_offset_targets, self.wlen_grid_steps, self.steps_per_exposure),\n            dtype=float)\n\n        guided_centroids = []\n\n        # Loop over exposures\n        for exp_index in range(self.spec_file.num_exposures):\n\n            # Estimate the actual offset target paths during the exposure\n            guided_x, guided_y = self.get_exp_centroids(exp_index)\n            guided_centroids.append((guided_x, guided_y))\n\n            # Calculate centroid offsets for each offset target, relative to its nominal fiber center.\n            offset = np.sqrt(\n                (guided_x - self.offset_x0[:, np.newaxis, np.newaxis])**2 +\n                (guided_y - self.offset_y0[:, np.newaxis, np.newaxis])**2)\n            \n            # Calculate centroid offsets for each offset target, relative to where its fiber center would\n            # be if it were designed for the same wavelength as the standard stars.\n            offset_std = np.sqrt(\n                (guided_x - self.offset_x0_std[:, np.newaxis, np.newaxis])**2 +\n                (guided_y - self.offset_y0_std[:, np.newaxis, np.newaxis])**2)\n\n            seeing = self.seeing[exp_index]\n            # psf = sdss_25m.get_atmospheric_psf(seeing_wlen, seeing, gauss=False)\n            # acceptance_model = sdss_25m.calculate_fiber_acceptance(psf)\n\n            seeing_wlen_adjusted = seeing*wlen_ratio**(-0.2)\n            # acceptance_model_grid = map(tpcorr.acceptance_model.AcceptanceModel, seeing_wlen_adjusted)\n            max_offset = 1.1/2.0*max(np.max((offset / self.pointing.platescale).to(u.arcsec)).value,\n                    np.max((offset_std / self.pointing.platescale).to(u.arcsec)).value)\n\n            for wlen_index in range(self.wlen_grid_steps):\n                # Build acceptance model for this wavelength\n                acceptance_model = tpcorr.acceptance_model.AcceptanceModel(seeing_wlen_adjusted[wlen_index], max_offset=max_offset)\n\n                # Calculate the acceptance fractions for both sets of centroid offsets.\n                acceptance = acceptance_model((offset[:,wlen_index,:] / self.pointing.platescale).to(u.arcsec))\n                acceptance_std = acceptance_model((offset_std[:,wlen_index,:] / self.pointing.platescale).to(u.arcsec))\n                \n                # Calculate the acceptance fraction ratios, tabulated for each offset target, wavelength and time.\n                # The ratio calculated this way gives the correction of eqn (13).\n                corrections[exp_index,:,wlen_index,:] = acceptance_std / acceptance\n\n        # Average the correction over each exposure time slice.\n        avg_corrections = np.mean(np.mean(corrections, axis=-1), axis=0)\n\n        return corrections, avg_corrections, guided_centroids\n\nif __name__ == '__main__':\n    pass\n", "meta": {"hexsha": "0163bffced5d8b9e70953d2dd27940a45e13b7f8", "size": 17935, "ext": "py", "lang": "Python", "max_stars_repo_path": "tpcorr/observation.py", "max_stars_repo_name": "dmargala/tpcorr", "max_stars_repo_head_hexsha": "64544a4ca51f622e5847407d191fc9a52e0e7e5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tpcorr/observation.py", "max_issues_repo_name": "dmargala/tpcorr", "max_issues_repo_head_hexsha": "64544a4ca51f622e5847407d191fc9a52e0e7e5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tpcorr/observation.py", "max_forks_repo_name": "dmargala/tpcorr", "max_forks_repo_head_hexsha": "64544a4ca51f622e5847407d191fc9a52e0e7e5c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.3779761905, "max_line_length": 145, "alphanum_fraction": 0.6594368553, "include": true, "reason": "import numpy,import astropy", "num_tokens": 4287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.193313430294804}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb  2 16:06:09 2019\n\n@author:\nMaximilian N. Günther\nMIT Kavli Institute for Astrophysics and Space Research, \nMassachusetts Institute of Technology,\n77 Massachusetts Avenue,\nCambridge, MA 02109, \nUSA\nEmail: maxgue@mit.edu\nWeb: www.mnguenther.com\n\"\"\"\n\nfrom __future__ import print_function, division, absolute_import\n\n#::: plotting settings\nimport seaborn as sns\nsns.set(context='paper', style='ticks', palette='deep', font='sans-serif', font_scale=1.5, color_codes=True)\nsns.set_style({\"xtick.direction\": \"in\",\"ytick.direction\": \"in\"})\nsns.set_context(rc={'lines.markeredgewidth': 1})\n\n#::: modules\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import gridspec\nfrom matplotlib.patches import Circle\nimport matplotlib.ticker as plticker\nfrom matplotlib.collections import LineCollection\nfrom matplotlib.colors import LinearSegmentedColormap\nimport random\nimport warnings\ntry:\n    import rebound\n    from rebound.particle import Particle\nexcept:\n    warnings.warn('Module \"rebound\" could not be imported. Orbital plots are not available.')\nfrom itertools import cycle\n\n#::: allesfitter codes\nfrom allesfitter import config\nfrom allesfitter.exoworlds_rdx.lightcurves.index_transits import get_first_epoch\nfrom allesfitter.exoworlds_rdx.lightcurves.lightcurve_tools import calc_phase\n\n\n\n\ndef OrbitPlot(sim, figsize=None, lim=None, limz=None, Narc=100, xlabel='x', ylabel='y', zlabel='z', color=False, periastron=False, trails=True, show_orbit=True, lw=1., glow=False, slices=False, plotparticles=[], primary=None, fancy=False, ax=None):\n    \"\"\"\n    Convenience function for plotting instantaneous orbits.\n\n    Parameters\n    ----------\n    slices          : bool, optional\n        Plot all three slices if set to True. Default is False and plots orbits only in the xy plane.\n    figsize         : tuple of float, optional\n        Tuple defining the figure size (default: (5,5))\n    lim             : float, optional           \n        Limit for axes (default: None = automatically determined)\n    limz            : float, optional           \n        Limit for z axis, only used if slices=True (default: None = automatically determined)\n    unitlabel       : str, optional          \n        String describing the units, shown on axis labels (default: None)\n    color           : bool, str or list, optional            \n        By default plots in black. If set to True, plots using REBOUND color cycle. If a string or list of strings, e.g. ['red', 'cyan'], will cycle between passed colors.\n    periastron  : bool, optional            \n        Draw a marker at periastron (default: False)\n    trails          : bool, optional            \n        Draw trails instead of solid lines (default: False)\n    show_orbit      : bool, optional\n        Draw orbit trails/lines (default: True)\n    lw              : float, optional           \n        Linewidth (default: 1.)\n    glow            : bool (default: False)\n        Make lines glow\n    fancy           : bool (default: False)\n        Changes various settings to create a fancy looking plot\n    plotparticles   : list, optional\n        List of particles to plot. Can be a list of any valid keys for accessing sim.particles, i.e., integer indices or hashes (default: plot all particles)\n    primary         : rebound.Particle, optional\n        Pimrary to use for the osculating orbit (default: Jacobi center of mass)\n\n    Returns\n    -------\n    fig\n        A matplotlib figure\n\n    Examples\n    --------\n    The following example illustrates a typical use case.\n\n    >>> sim = rebound.Simulation()\n    >>> sim.add(m=1)\n    >>> sim.add(a=1)\n    >>> fig = rebound.OrbitPlot(sim)\n    >>> fig.savefig(\"image.png\") # save figure to file\n    >>> fig.show() # show figure on screen\n\n    \"\"\"\n    if slices:\n        if figsize is None:\n            figsize = (8,8)\n        if ax is None:\n            fig, ax = plt.subplots(2, 2, figsize=figsize)\n        gs = gridspec.GridSpec(2, 2, width_ratios=[3., 2.], height_ratios=[2.,3.],wspace=0., hspace=0.) \n        OrbitPlotOneSlice(sim, plt.subplot(gs[2]), lim=lim, Narc=Narc, color=color, periastron=periastron, trails=trails, show_orbit=show_orbit, lw=lw, axes=\"xy\",fancy=fancy, plotparticles=plotparticles, primary=primary, glow=glow)\n        OrbitPlotOneSlice(sim, plt.subplot(gs[3]), lim=lim, limz=limz, Narc=Narc, color=color, periastron=periastron, trails=trails, show_orbit=show_orbit, lw=lw,fancy=fancy, axes=\"zy\", plotparticles=plotparticles, primary=primary, glow=glow)\n        OrbitPlotOneSlice(sim, plt.subplot(gs[0]), lim=lim, limz=limz, Narc=Narc, color=color, periastron=periastron, trails=trails, show_orbit=show_orbit, lw=lw,fancy=fancy, axes=\"xz\", plotparticles=plotparticles, primary=primary, glow=glow)\n        plt.subplot(gs[2]).set_xlabel(xlabel)\n        plt.subplot(gs[2]).set_ylabel(ylabel)\n      \n        plt.setp(plt.subplot(gs[0]).get_xticklabels(), visible=False)\n        plt.subplot(gs[0]).set_ylabel(zlabel)\n        \n        plt.subplot(gs[3]).set_xlabel(zlabel)\n        plt.setp(plt.subplot(gs[3]).get_yticklabels(), visible=False)\n    else:\n        if figsize is None:\n            figsize = (5,5)\n        if ax is None:\n            fig, ax = plt.subplots(1, 1, figsize=figsize)\n        ax.set_xlabel(xlabel)\n        ax.set_ylabel(ylabel)\n        OrbitPlotOneSlice(sim, ax, lim=lim, Narc=Narc, color=color, periastron=periastron, trails=trails, show_orbit=show_orbit, lw=lw,fancy=fancy, plotparticles=plotparticles, primary=primary, glow=glow)\n    return plt.gcf(), ax\n\n\n\n\ndef get_color(color):\n    \"\"\"\n    Takes a string for a color name defined in matplotlib and returns of a 3-tuple of RGB values.\n    Will simply return passed value if it's a tuple of length three.\n\n    Parameters\n    ----------\n    color   : str\n        Name of matplotlib color to calculate RGB values for.\n    \"\"\"\n\n    if isinstance(color, tuple) and len(color) == 3: # already a tuple of RGB values\n        return color\n\n    hexcolor = sns.colors.xkcd_rgb[color]\n\n    hexcolor = hexcolor.lstrip('#')\n    lv = len(hexcolor)\n    return tuple(int(hexcolor[i:i + lv // 3], 16)/255. for i in range(0, lv, lv // 3)) # tuple of rgb values\n\n\n\n\ndef fading_line(x, y, color='black', alpha_initial=1., alpha_final=0., glow=False, **kwargs):\n    \"\"\"\n    Returns a matplotlib LineCollection connecting the points in the x and y lists, with a single color and alpha varying from alpha_initial to alpha_final along the line.\n    Can pass any kwargs you can pass to LineCollection, like linewidgth.\n\n    Parameters\n    ----------\n    x       : list or array of floats for the positions on the (plot's) x axis\n    y       : list or array of floats for the positions on the (plot's) y axis\n    color   : matplotlib color for the line. Can also pass a 3-tuple of RGB values (default: 'black')\n    alpha_initial:  Limiting value of alpha to use at the beginning of the arrays.\n    alpha_final:    Limiting value of alpha to use at the end of the arrays.\n    \"\"\"\n    if glow:\n        glow = False\n        kwargs[\"lw\"] = 1\n        fl1 = fading_line(x, y, color, alpha_initial, alpha_final, glow=False, **kwargs)\n        kwargs[\"lw\"] = 2\n        alpha_initial *= 0.5\n        alpha_final *= 0.5\n        fl2 = fading_line(x, y, color, alpha_initial, alpha_final, glow=False, **kwargs)\n        kwargs[\"lw\"] = 6\n        alpha_initial *= 0.5\n        alpha_final *= 0.5\n        fl3 = fading_line(x, y, color, alpha_initial, alpha_final, glow=False, **kwargs)\n        return [fl3,fl2,fl1]\n\n    color = get_color(color)\n    cdict = {'red': ((0.,color[0],color[0]),(1.,color[0],color[0])),\n             'green': ((0.,color[1],color[1]),(1.,color[1],color[1])),\n             'blue': ((0.,color[2],color[2]),(1.,color[2],color[2])),\n             'alpha': ((0.,alpha_initial, alpha_initial), (1., alpha_final, alpha_final))}\n    \n    Npts = len(x)\n    if len(y) != Npts:\n        raise AttributeError(\"x and y must have same dimension.\")\n   \n    segments = np.zeros((Npts-1,2,2))\n    segments[0][0] = [x[0], y[0]]\n    for i in range(1,Npts-1):\n        pt = [x[i], y[i]]\n        segments[i-1][1] = pt\n        segments[i][0] = pt \n    segments[-1][1] = [x[-1], y[-1]]\n\n    individual_cm = LinearSegmentedColormap('indv1', cdict)\n    lc = LineCollection(segments, cmap=individual_cm, **kwargs)\n    lc.set_array(np.linspace(0.,1.,len(segments)))\n    return lc\n\n\n\n\ndef OrbitPlotOneSlice(sim, ax, lim=None, limz=None, Narc=100, color=False, periastron=False, trails=False, show_orbit=True, lw=1., axes=\"xy\", plotparticles=[], primary=None, glow=False, fancy=False):\n    p_orb_pairs = []\n    if not plotparticles:\n        plotparticles = range(1, sim.N_real)\n    for i in plotparticles:\n        p = sim.particles[i]\n        p_orb_pairs.append((p, p.calculate_orbit(primary=primary)))\n\n    if lim is None:\n        lim = 0.\n        for p, o in p_orb_pairs: \n            if o.a>0.:\n                r = (1.+o.e)*o.a\n            else:\n                r = o.d\n            if r>lim:\n                lim = r\n        lim *= 1.15\n    if limz is None:\n        z = [p.z for p,o in p_orb_pairs]\n        limz = 2.0*max(z)\n        if limz > lim:\n            limz = lim\n        if limz <= 0.:\n            limz = lim\n\n    if axes[0]==\"z\":\n        ax.set_xlim([-limz,limz])\n    else:\n        ax.set_xlim([-lim,lim])\n    if axes[1]==\"z\":\n        ax.set_ylim([-limz,limz])\n    else:\n        ax.set_ylim([-lim,lim])\n        \n    if fancy:\n        ax.set_facecolor((0.,0.,0.))\n        for pos in ['top', 'bottom', 'right', 'left']:\n            ax.spines[pos].set_edgecolor((0.3,0.3,0.3))\n\n    if color is not False:\n        if isinstance(color, list):\n            colors = []\n            for c in color:\n                colors.append(get_color(c))\n        elif isinstance(color, str):\n            colors = [get_color(color)]\n        elif color == True:\n            colors = [(1.,0.,0.),(0.,0.75,0.75),(0.75,0.,0.75),(0.75, 0.75, 0,),(0., 0., 0.),(0., 0., 1.),(0., 0.5, 0.)]\n    else:\n        if fancy:\n            colors = [(181./206.,66./206.,191./206.)]\n            glow = True\n        else:\n            colors = [\"black\"]\n    coloriterator = cycle(colors)\n\n#    coords = {'x':0, 'y':1, 'z':2}\n#    axis0 = coords[axes[0]]\n#    axis1 = coords[axes[1]]\n   \n    prim = sim.particles[0] if primary is None else primary \n    if fancy:\n        sun = (256./256.,256./256.,190./256.)\n        opa = 0.020\n        size = 6000.\n        for i in range(256):\n            ax.scatter(getattr(prim,axes[0]),getattr(prim,axes[1]), alpha=opa, s=size*lw, facecolor=sun, edgecolor=None, zorder=3)\n            size *= 0.95\n        \n        starcolor = (1.,1.,1.)\n        mi, ma = ax.get_xlim()\n        prestate = random.getstate()\n        random.seed(1) #always same stars\n        x, y = [], []\n        #small stars\n        for i in range(64):\n            x.append(random.uniform(mi,ma))\n            y.append(random.uniform(mi,ma))\n        ax.scatter(x,y, alpha=0.05, s=8*lw, facecolor=starcolor, edgecolor=None, zorder=3)\n        ax.scatter(x,y, alpha=0.1, s=4*lw, facecolor=starcolor, edgecolor=None, zorder=3)\n        ax.scatter(x,y, alpha=0.2, s=0.5*lw, facecolor=starcolor, edgecolor=None, zorder=3)\n        #medium stars\n        x, y = [], []\n        for i in range(16):\n            x.append(random.uniform(mi,ma))\n            y.append(random.uniform(mi,ma))\n        ax.scatter(x,y, alpha=0.1, s=15*lw, facecolor=starcolor, edgecolor=None, zorder=3)\n        ax.scatter(x,y, alpha=0.1, s=5*lw, facecolor=starcolor, edgecolor=None, zorder=3)\n        ax.scatter(x,y, alpha=0.5, s=2*lw, facecolor=starcolor, edgecolor=None, zorder=3)\n        random.setstate(prestate)\n\n    else:\n        ax.scatter(getattr(prim,axes[0]),getattr(prim,axes[1]), marker=\"*\", s=35*lw, facecolor=\"black\", edgecolor=None, zorder=3)\n    \n    proj = {}\n    for p, o in p_orb_pairs:\n        colori = next(coloriterator)\n        \n        prim = p.jacobi_com if primary is None else primary \n        if fancy:\n            ax.scatter(getattr(p,axes[0]), getattr(p,axes[1]), s=25*lw, facecolor=colors, edgecolor=None, zorder=3)\n        else:\n            pass\n            #::: !!!\n            #::: !!!\n            #::: plot the planet symbols\n            #::: !!!\n            #::: !!!\n#            ax.scatter(getattr(p,axes[0]), getattr(p,axes[1]), s=p.r*lw, facecolor=colori, edgecolor=None, zorder=3)\n\n       \n        if show_orbit is True:\n            alpha_final = 0. if trails is True else 1. # fade to 0 with trails\n\n            hyperbolic = o.a < 0. # Boolean for whether orbit is hyperbolic\n            if hyperbolic is False:\n                pts = np.array(p.sample_orbit(Npts=Narc+1, primary=prim))\n                proj['x'],proj['y'],proj['z'] = [pts[:,i] for i in range(3)]\n                lc = fading_line(proj[axes[0]], proj[axes[1]], colori, alpha_final=alpha_final, lw=lw, glow=glow)\n                if type(lc) is list:\n                    for l in lc:\n                        ax.add_collection(l)\n                else:\n                    ax.add_collection(lc)\n\n            else:\n                pts = np.array(p.sample_orbit(Npts=Narc+1, primary=prim, useTrueAnomaly=False))\n                # true anomaly stays close to limiting value and switches quickly at pericenter for hyperbolic orbit, so use mean anomaly\n                proj['x'],proj['y'],proj['z'] = [pts[:,i] for i in range(3)]\n                lc = fading_line(proj[axes[0]], proj[axes[1]], colori, alpha_final=alpha_final, lw=lw, glow=glow)\n                if type(lc) is list:\n                    for l in lc:\n                        ax.add_collection(l)\n                else:\n                    ax.add_collection(lc)\n          \n                alpha = 0.2 if trails is True else 1.\n                pts = np.array(p.sample_orbit(Npts=Narc+1, primary=prim, trailing=False, useTrueAnomaly=False))\n                proj['x'],proj['y'],proj['z'] = [pts[:,i] for i in range(3)]\n                lc = fading_line(proj[axes[0]], proj[axes[1]], colori, alpha_initial=alpha, alpha_final=alpha, lw=lw, glow=glow)\n                if type(lc) is list:\n                    for l in lc:\n                        ax.add_collection(l)\n                else:\n                    ax.add_collection(lc)\n\n        if periastron:\n            newp = Particle(a=o.a, f=0., inc=o.inc, omega=o.omega, Omega=o.Omega, e=o.e, m=p.m, primary=prim, simulation=sim)\n            ax.plot([getattr(prim,axes[0]), getattr(newp,axes[0])], [getattr(prim,axes[1]), getattr(newp,axes[1])], linestyle=\"dotted\", c=colori, zorder=1, lw=lw)\n            ax.scatter([getattr(newp,axes[0])],[getattr(newp,axes[1])], marker=\"o\", s=5.*lw, facecolor=\"none\", edgecolor=colori, zorder=1)\n\n\n\n\ndef plot_top_down_view(params_median, params_star, a=None, timestep=None, scaling=5., colors=sns.color_palette('deep'), linewidth=2, plot_arrow=False, ax=None):\n    \n    sim = rebound.Simulation()\n    sim.add(m=1)\n    \n    for i, companion in enumerate(config.BASEMENT.settings['companions_all']):\n        if (i==0) and (timestep is None): \n            timestep = params_median[companion+'_epoch'] #calculate it for the timestep where the first companion is in transit\n        first_epoch = get_first_epoch(timestep, params_median[companion+'_epoch'], params_median[companion+'_period'])\n        phase = calc_phase(timestep, params_median[companion+'_period'], first_epoch)\n        ecc = params_median[companion+'_f_s']**2 + params_median[companion+'_f_c']**2\n        w = np.arccos( params_median[companion+'_f_c'] / np.sqrt(ecc) ) #in rad\n        inc = params_median[companion+'_incl']/180.*np.pi\n        if a is None:\n            a1 = params_star['R_star'] / params_median[companion+'_radius_1'] #in Rsun \n            a1 *= 0.004650467260962157 #in AU\n        else:\n            a1 = a[i]\n#        print(a, inc, ecc, w, phase*2*np.pi)\n        if ecc>0:\n            sim.add(a=a1, inc=inc-np.pi/2., e=ecc, omega=w, f=phase*2*np.pi)\n        else:\n            sim.add(a=a1, inc=inc--np.pi/2., f=phase*2*np.pi)\n#    print(len(sim.particles))\n    \n#    print('Epoch, Period and mean anomaly, b:', sim.particles[0].M )\n#    print('Mean anomaly, c:', sim.particles[0].M )\n#    print('Mean anomaly, c:', sim.particles[0].M )\n#    err\n    \n    fig, ax = OrbitPlot(sim, xlabel='AU', ylabel='AU', color=colors, lw=linewidth, ax=ax) #color=[sns.color_palette('deep')[i] for i in [0,1,3]],\n    \n    for i, companion in enumerate(config.BASEMENT.settings['companions_all']):\n        \n        R_companion = params_star['R_star'] * params_median[companion+'_rr'] # in Rsun\n        R_companion *= 0.004650467260962157 #in AU\n        R_companion *= scaling\n    \n        \n        x = sim.particles.get(i+1).x\n        y = sim.particles.get(i+1).y\n        p = Circle((x,y), R_companion, color=colors[i])\n        ax.add_artist(p)\n        \n    if plot_arrow:\n        x0, x1 = ax.get_xlim()\n        plt.arrow( 0.1*x1, 0, 0.7*x1, 0, color='silver', zorder=1 ) \n              \n    plt.axis('equal')\n#    ax.set(xlim=[-0.12,0.12], ylim=[-0.12,0.12])\n#    loc = plticker.MultipleLocator(base=0.05) # this locator puts ticks at regular intervals\n#    ax.xaxis.set_major_locator(loc)\n#    ax.yaxis.set_major_locator(loc)\n\n    return fig, ax\n\n\n", "meta": {"hexsha": "9da667dc0833ef79438c28f29e38de6828226382", "size": 17196, "ext": "py", "lang": "Python", "max_stars_repo_path": "allesfitter/plot_top_down_view.py", "max_stars_repo_name": "pierfra-ro/allesfitter", "max_stars_repo_head_hexsha": "a6a885aaeb3253fec0d924ef3b45e8b7c473b181", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "allesfitter/plot_top_down_view.py", "max_issues_repo_name": "pierfra-ro/allesfitter", "max_issues_repo_head_hexsha": "a6a885aaeb3253fec0d924ef3b45e8b7c473b181", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "allesfitter/plot_top_down_view.py", "max_forks_repo_name": "pierfra-ro/allesfitter", "max_forks_repo_head_hexsha": "a6a885aaeb3253fec0d924ef3b45e8b7c473b181", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9428571429, "max_line_length": 248, "alphanum_fraction": 0.5982786695, "include": true, "reason": "import numpy", "num_tokens": 4789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.36658974324230986, "lm_q1q2_score": 0.193308828913143}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf8 -*-\n\"\"\"\n    SAMI XJoin\n\n    This script simply joins the four existing extensions inside a FITS file\n    created during observations with SAMI (SAM Imager). During the reduce,\n    it also fits a 2nd degree polynomium to the OVERSCAN region that is\n    subtracted from the corresponding image.\n\n    The user also may want to add flags in order to reduce the images\n    according to the following options (in order):\n\n    - BIAS subtraction;\n    - DARK subtraction;\n    - Remove hot pixels and cosmic rays;\n    - Remove overglow using a long exposure DARK image;\n    - Divide by the FLAT;\n    - Divide by the exposure time;\n\n    The documentation for each reduce is shown in the corresponding function.\n\n    Todo\n    ----\n    - Use multithread or multiprocessing to run this script faster.\n    - Use astropy.ccdproc to reduce the data.\n\n    Bruno Quint (bquint at ctio.noao.edu)\n    May 2016\n\n    Thanks to Andrei Tokovinin and Claudia M. de Oliveira for the ideas that\n    were implemented here.\n\"\"\"\n\nimport numpy as _np\n\nfrom ccdproc import cosmicray_lacosmic as _cosmicray_lacosmic\nfrom scipy import stats\n\nfrom astropy import wcs\nfrom astropy.coordinates import SkyCoord\nfrom astropy import units as u\n\nfrom soar_simager.io import pyfits as _pyfits\nfrom soar_simager.io.logging import get_logger\nfrom soar_simager.tools import slices\n\nlogger = get_logger(__name__)\n\n\n# Piece of code from cosmics.py\n# We define the laplacian kernel to be used\n_laplkernel = _np.array([[0.0, -1.0, 0.0], [-1.0, 4.0, -1.0], [0.0, -1.0, 0.0]])\n\n# Other kernels :\n_growkernel = _np.ones((3, 3))\n\n# dilation structure for some morphological operations\n_dilstruct = _np.ones((5, 5))\n_dilstruct[0, 0] = 0\n_dilstruct[0, 4] = 0\n_dilstruct[4, 0] = 0\n_dilstruct[4, 4] = 0\n\n\nclass Reducer:\n    \"\"\"\n    This class holds all the methods used to join the extensions within a\n    FITS file obtained with SAMI.\n\n    Parameters\n    ----------\n        zero_file : str\n            The filename of the master zero that will be used in subtraction.\n\n        clean : bool\n            Clean bad collumns by taking the _median value of the pixels around\n            them.\n\n        cosmic_rays : bool\n            Clean cosmic rays using LACosmic package. See noted bellow for\n            reference.\n\n        dark_file : str\n            Master Dark's filename to be used for dark subtraction.\n\n        debug : bool\n            Turn on debug mode with lots of printing.\n\n        flat_file : str\n            Master Flat filename to be used for normalization.\n\n        glow_file : str\n            Master file that contains the lateral glowings sometimes present in\n            SAMI's data.\n\n        time : bool\n            Divide each pixel's values by the exposure time and update header.\n\n        verbose : bool\n            Turn on verbose mode (not so talktive as debug mode).\n\n    Attributes\n    ----------\n        gain : list\n            A list containing the gain that converts ADU values to eletrons for \n            each simager amplifier.\n            \n        read_noise : list\n            A list containing the read noise on each simager amplifier.\n\n    See also\n    --------\n        LACosmic - http://www.astro.yale.edu/dokkum/lacosmic/\n    \"\"\"\n\n    gain = [2.6, 2.6, 2.6, 2.6]\n    read_noise = [10., 10., 10., 10.]\n\n    def __init__(self, clean=False, cosmic_rays=False, dark_file=None,\n                 debug=False, flat_file=None, glow_file=None, merge=False,\n                 overscan=False, norm_flat=False, time=False, verbose=False,\n                 zero_file=None):\n\n        logger.setLevel(\"ERROR\")\n\n        if verbose:\n            logger.setLevel(\"INFO\")\n\n        if debug:\n            logger.setLevel(\"DEBUG\")\n\n        self.clean = clean\n        self.cosmic_rays = cosmic_rays\n        self.dark_file = dark_file\n        self.flat_file = flat_file\n        self.glow_file = glow_file\n        self._merge = merge\n        self.norm_flat = norm_flat\n        self.overscan = overscan\n        self.time = time\n        self.zero_file = zero_file\n\n        return\n\n    def reduce(self, hdu_list, prefix=\"\"):\n\n        # If the number of extensions is just 1, then the file is already\n        # processed.\n        if len(hdu_list) == 1:\n            return hdu_list, ''\n\n        # Merge file\n        data, header, prefix = self.merge(hdu_list)\n\n        # Correct ZERO\n        data, header, prefix = self.correct_zero(\n            data, header, prefix, self.zero_file\n        )\n\n        # Correct DARK\n        data, header, prefix = self.correct_dark(\n            data, header, prefix, self.dark_file\n        )\n\n        # Remove cosmic rays and hot pixels\n        data, header, prefix = self.remove_cosmic_rays(\n            data, header, prefix, self.cosmic_rays\n        )\n\n        # Remove lateral glows\n        data, header, prefix = self.correct_lateral_glow(\n            data, header, prefix, self.glow_file\n        )\n\n        # Correct FLAT\n        data, header, prefix = self.correct_flat(\n            data, header, prefix, self.flat_file\n        )\n\n        # Normalize by the EXPOSURE TIME\n        data, header, prefix = self.divide_by_exposuretime(\n            data, header, prefix, self.time\n        )\n\n        # Clean known bad columns and lines\n        data, header, prefix = self.clean_hot_columns_and_lines(\n            data, header, prefix, self.clean\n        )\n\n        # Add WCS\n        data, header = self.create_wcs(\n            data, header\n        )\n\n        return data, header, prefix\n\n    @staticmethod\n    def create_wcs(data, header):\n        \"\"\"\n        Creates a first guess of the WCS using the telescope coordinates, the\n        CCDSUM (binning), position angle and plate scale.\n\n        Parameters\n        ----------\n            data : numpy.ndarray\n                2D array with the data.\n\n            header : astropy.io.fits.Header\n                Primary Header to be updated.\n\n        Returns\n        -------\n            header : astropy.io.fits.Header\n                Primary Header with updated WCS information.\n        \"\"\"\n        h = header\n\n        if 'EQUINOX' not in h:\n            h['EQUINOX'] = 2000.\n\n        if 'EPOCH' not in h:\n            h['EPOCH'] = 2000.\n\n        if h['PIXSCAL1'] != h['PIXSCAL2']:\n            logger.warning('Pixel scales for X and Y do not mach.')\n\n        if h['OBSTYPE'] != 'OBJECT':\n            return data, header\n\n        binning = _np.array([int(b) for b in h['CCDSUM'].split(' ')])\n        plate_scale = h['PIXSCAL1'] * u.arcsec\n        p = plate_scale.to('degree').value\n        w = wcs.WCS(naxis=2)\n\n        try:\n            coordinates = SkyCoord(ra=h['RA'], dec=h['DEC'],\n                                   unit=(u.hourangle, u.deg))\n\n        except ValueError:\n\n            logger.error(\n                '\"RA\" and \"DEC\" missing. Using \"TELRA\" and \"TELDEC\" instead.')\n\n            coordinates = SkyCoord(ra=h['TELRA'], dec=h['TELDEC'],\n                                   unit=(u.hourangle, u.deg))\n\n        ra = coordinates.ra.to('degree').value\n        dec = coordinates.dec.to('degree').value\n\n        w.wcs.crpix = [data.shape[1] / 2, data.shape[0] / 2]\n        w.wcs.cdelt = p * binning\n        w.wcs.crval = [ra, dec]\n        w.wcs.ctype = [\"RA---TAN\", \"DEC--TAN\"]\n\n        wcs_header = w.to_header()\n\n        theta = _np.deg2rad(h['DECPANGL'])\n        wcs_header['cd1_1'] = p * binning[0] * _np.cos(theta)\n        wcs_header['cd2_2'] = p * binning[0] * _np.cos(theta)\n        wcs_header['cd1_2'] = p * binning[0] * _np.sin(theta)\n        wcs_header['cd2_1'] = - p * binning[0] * _np.sin(theta)\n\n        for key in wcs_header.keys():\n            header[key] = wcs_header[key]\n\n        return data, header\n\n    @staticmethod\n    def check_header(hdu_list, prefix):\n\n        for i in range(5):\n\n            h = hdu_list[i].header\n\n            try:\n                h['RADESYSa'] = h['RADECSYS']\n                del h['RADECSYS']\n            except KeyError:\n                pass\n\n            if 'EQUINOX' in h and 'unavail' in h['EQUINOX']:\n                h['EQUINOX'] = 2000.\n\n            if 'EPOCH' not in h:\n                h['EPOCH'] = 2000.\n\n        return hdu_list, prefix\n\n    @staticmethod\n    def clean_column(_data, x0, y0, yf, n=5):\n        \"\"\"\n        Substitutes a single column by the _median of the neighbours columns.\n\n        Args:\n\n            _data (numpy.ndarray) : A 2D numpy array that contains the data.\n\n            x0 (int) : X position of the pixel to be cleaned.\n\n            y0 (int) : Start position of the column.\n\n            yf (int) : Final position of the column.\n\n            n (int, optional) : Number of neighbour columns (Default=5).\n\n        Returns:\n\n            _data (numpy.ndarray) : Processed 2D numpy array.\n\n        See also:\n\n            Reducer.clean_columns\n            Reducer.clean_line\n            Reducer.clean_lines\n        \"\"\"\n\n        if not isinstance(_data, _np.ndarray):\n            raise (TypeError, 'Please, use a np.array as input')\n\n        if _data.ndim is not 2:\n            raise (TypeError, 'Data contains %d dimensions while it was '\n                              'expected 2 dimensions.')\n\n        t1 = _data[y0:yf, x0 - n:x0]\n        t2 = _data[y0:yf, x0 + 1:x0 + n]\n        t = _np.hstack((t1, t2))\n        _data[y0:yf, x0] = _np.median(t, axis=1)\n\n        return _data\n\n    def clean_columns(self, data, header):\n        \"\"\"\n        Clean the known bad columns that exists in most of SAMI's, SOI's or\n        SIFS's data. This method is meant to be overwritten via inheritance.\n\n        Args:\n\n            data (numpy.ndarray) : A 2D numpy array that contains the data.\n\n            header (astropy.io.fits.Header) : A header that will be updated.\n\n        See also:\n\n            Reducer.clean_column\n            Reducer.clean_line\n            Reducer.clean_lines\n        \"\"\"\n        return data, header\n\n    @staticmethod\n    def clean_line(_data, x0, xf, y, n=5):\n        \"\"\"\n        Substitutes a single column by the _median of the neighbours columns.\n\n        Args:\n\n            _data (numpy.ndarray) : A 2D numpy array that contains the data.\n\n            x0 (int) : Start position of the line.\n\n            xf (int) : Final position of the line.\n\n            y (int) : Y position of the pixel to be cleaned.\n\n            n (int) : Number of neighbour columns. (Default=5)\n\n        See also:\n\n            Reducer.clean_column\n            Reducer.clean_columns\n            Reducer.clean_lines\n        \"\"\"\n        if not isinstance(_data, _np.ndarray):\n            raise (TypeError, 'Please, use a np.array as input')\n\n        if _data.ndim is not 2:\n            raise (TypeError, 'Data contains %d dimensions while it was '\n                              'expected 2 dimensions.')\n\n        t1 = _data[y - n:y, x0:xf]\n        t2 = _data[y + 1:y + n, x0:xf]\n        t = _np.vstack((t1, t2))\n        _data[y, x0:xf] = _np.median(t, axis=0)\n\n        return _data\n\n    def clean_lines(self, data, header):\n        \"\"\"\n        Clean the known bad lines that exists in most of SAMI's, SOI's or\n        SIFS's data. This method is meant to be overwritten via inheritance.\n\n        Args:\n\n            data (numpy.ndarray) : A 2D numpy array that contains the data.\n\n            header (astropy.io.fits.Header) : A header that will be updated.\n\n        See also:\n\n            Reducer.clean_column\n            Reducer.clean_line\n            Reducer.clean_lines\n        \"\"\"\n        return data, header\n\n    def clean_hot_columns_and_lines(self, data, header, prefix, clean):\n        \"\"\"\n        Clean known hot columns and lines from SAMI's images.\n\n        Args:\n\n            data (numpy.ndarray) : A 2D numpy array that contains the data.\n\n            header (astropy.io.fits.Header) : A header that will be updated.\n\n            prefix (str) : File prefix that is added after each reduce.\n\n            clean (bool) : Should I perform the clean?\n\n        See also:\n\n            Reducer.clean_column\n            Reducer.clean_columns\n            Reducer.clean_line\n            Reducer.clean_lines\n        \"\"\"\n        if clean is True:\n\n            data = self.clean_columns(data, header)\n            data = self.clean_lines(data, header)\n            header.add_history('Cleaned bad columns and lines.')\n            prefix = 'c' + prefix\n\n        return data, header, prefix\n\n    @staticmethod\n    def correct_dark(data, header, prefix, dark_file=None):\n        \"\"\"\n        Subtract the dark file from data and add HISTORY to header.\n\n        Args:\n\n            data (numpy.ndarray) : A 2D numpy array that contains the data.\n\n            header (astropy.io.fits.Header) : A header that will be updated.\n\n            prefix : str\n                File prefix that is added after each reduce.\n\n            dark_file: str | None\n                Master Dark filename. If None is given, nothing is done.\n        \"\"\"\n\n        if not isinstance(prefix, str):\n            raise (TypeError, 'Expected string but found %s instead.' %\n                   prefix.__class__)\n\n        if dark_file is not None:\n\n            dark = _pyfits.open(dark_file)[0]\n            dark.data = dark.data / float(dark.header['EXPTIME'])\n\n            data = data - dark.data * header['EXPTIME']\n            header['DARKFILE'] = dark_file\n            prefix = 'd' + prefix\n\n        return data, header, prefix\n\n    @staticmethod\n    def correct_flat(data, header, prefix, flat_file):\n        \"\"\"\n        Divide the image by the master flat file and add HISTORY to header.\n\n        Args:\n\n            data (numpy.ndarray) : A 2D numpy array that contains the data.\n\n            header (astropy.io.fits.Header) : A header that will be updated.\n\n            prefix (str) : File prefix that is added after each reduce.\n\n            flat_file (str or None) : Master flat filename. If None is given,\n            nothing is done.\n        \"\"\"\n        if not isinstance(prefix, str):\n            raise (TypeError, 'Expected string but found %s instead.' %\n                   prefix.__class__)\n\n        if flat_file is not None:\n            flat = _pyfits.open(flat_file)[0]\n\n            data /= flat.data\n            header['FLATFILE'] = flat_file\n            prefix = 'f' + prefix\n\n        return data, header, prefix\n\n    def correct_lateral_glow(self, data, header, prefix, glow_file):\n        \"\"\"\n        Remove lateral glows by scaling the glows in the `glow_file` based\n         on `data` and subtracting it.\n\n        Args:\n\n            data (numpy.ndarray) : A 2D numpy array that contains the data.\n\n            header (astropy.io.fits.Header) : A header that will be updated.\n\n            prefix : str\n                Filename prefix to flag images that were clean.\n\n            glow_file : str\n                Path to a long dark file that contains the lateral glow.\n        \"\"\"\n\n        if glow_file is not None:\n\n            # Create four different regions.\n            regions = [\n                [_np.median(data[539:589, 6:56]),  # Top Left\n                 _np.median(data[539:589, 975:1019])],  # Top Right\n                [_np.median(data[449:506, 6:56]),  # Bottom Left\n                 _np.median(data[449:506, 975:1019])]  # Bottom Right\n            ]\n\n            min_std_region = _np.argmin(regions) % 2\n\n            # The upper reg has background lower or equal to the lower reg\n            midpt1 = regions[0][min_std_region]\n            midpt2 = regions[1][min_std_region]\n            diff = midpt2 - midpt1\n\n            dark = _pyfits.getdata(glow_file)\n            dark = self.clean_columns(dark)\n            dark = self.clean_lines(dark)\n\n            dark_regions = [\n                [_np.median(dark[539:589, 6:56]),  # Top Left\n                 _np.median(dark[539:589, 975:1019])],  # Top Right\n                [_np.median(dark[449:506, 6:56]),  # Bottom Left\n                 _np.median(dark[449:506, 975:1019])]  # Bottom Right\n            ]\n\n            dark_midpt1 = dark_regions[0][min_std_region]\n            dark_midpt2 = dark_regions[1][min_std_region]\n\n            dark_diff = dark_midpt2 - dark_midpt1\n            dark -= dark_midpt1\n\n            k = diff / dark_diff\n            temp_dark = dark * k\n            data -= midpt1\n            data -= temp_dark\n\n            header.add_history('Lateral glow removed using %s file' % glow_file)\n            prefix = 'g' + prefix\n\n        return data, header, prefix\n\n    @staticmethod\n    def correct_zero(data, header, prefix, zero_file):\n        \"\"\"\n        Subtract zero from data.\n\n        Args:\n\n            data (numpy.ndarray) : A 2D numpy array that contains the data.\n\n            header (astropy.io.fits.Header) : A header that will be updated.\n\n            prefix (str) : File prefix that is added after each reduce.\n\n            zero_file (str | None) : Master Bias filename. If None is given,\n            nothing is done.\n\n        \"\"\"\n        from os.path import abspath\n\n        if zero_file is not None:\n\n            zero = _pyfits.open(abspath(zero_file))[0]\n            data = data - zero.data\n            header['BIASFILE'] = zero_file\n            prefix = 'z' + prefix\n\n        return data, header, prefix\n\n    @staticmethod\n    def divide_by_exposuretime(data, header, prefix, time):\n        \"\"\"\n            Divide the image by the exposure time and add HISTORY to header.\n\n            Args:\n\n                data (numpy.ndarray) : A 2D numpy array that contains the data.\n\n                header (astropy.io.fits.Header) : A header that will be updated.\n\n                prefix : str\n                    File prefix that is added after each reduce.\n\n                time: bool\n                    Divide image by exposure time?\n        \"\"\"\n        if time is True:\n\n            h = header\n\n            try:\n\n                h['UNITS'] = 'adu / s'\n                t = float(h['EXPTIME'])\n                d = data / t\n\n                header = h\n                data = d\n\n            except AttributeError:\n                header = h\n\n            except KeyError:\n                pass\n\n            prefix = 't' + prefix\n\n        return data, header, prefix\n\n    def get_header(self, hdu_source):\n        \"\"\"\n        Return the header of the primary HDU extension of a FITS file.\n\n        Args:\n\n            hdu_source (str or astropy.io.fits.HDUList) : HDUList or name of the\n            file which contains a HDUList.\n        \"\"\"\n        from os.path import exists\n\n        if isinstance(hdu_source, str):\n\n            if not exists(hdu_source):\n                raise (IOError, '%s file not found.' % hdu_source)\n\n            hdu_source = _pyfits.open(hdu_source)\n\n        h0 = hdu_source[0].header\n        h1 = hdu_source[1].header\n\n        h0.append('UNITS')\n        h0.set('UNITS', value='ADU', comment='Pixel intensity units.')\n\n        # Save the CCD binning in the main header\n        h0['CCDSUM'] = h1['CCDSUM']\n        h0['DETSEC'] = h1['DETSEC']\n\n        # Save the area that corresponds to each amplifier\n        bin_size = _np.array(h0['CCDSUM'].split(' '), dtype=int)\n\n        dx, dy = slices.iraf2python(h0['DETSEC'])\n        dx, dy = dx // bin_size[0], dy // bin_size[1]\n\n        h0['AMP_SEC1'] = slices.python2iraf(\n            dx[0], dx[1], dy[0], dy[1])\n\n        h0['AMP_SEC2'] = slices.python2iraf(\n            dx[0] + dx[1], dx[1] + dx[1], dy[0], dy[1])\n\n        h0['AMP_SEC3'] = slices.python2iraf(\n            dx[0], dx[1], dy[0] + dy[1], dy[1] + dy[1])\n\n        h0['AMP_SEC4'] = slices.python2iraf(\n            dx[0] + dx[1], dx[1] + dx[1], dy[0] + dy[1], dy[1] + dy[1])\n\n        return h0\n\n    def get_prefix(self):\n        \"\"\"\n        Return a prefix to be added to the file deppending on the data\n        reduction steps.\n\n        Returns\n        -------\n            prefix : (str)\n                The prefix that can be used.\n                    m = merged amplifiers.\n                    z = zero subtracted.\n                    f = flat corrected.\n        \"\"\"\n\n        prefix = 'm_'\n\n        if self.zero_file:\n            prefix = 'z' + prefix\n\n        if self.dark_file:\n            prefix = 'd' + prefix\n\n        if self.flat_file:\n            prefix = 'f' + prefix\n\n        return prefix\n\n    def merge(self,  hdul):\n        \"\"\"\n        Open a FITS image and try to join its extensions in a single array.\n\n        Args:\n\n            hdul (astropy.io.fits.HDUList) : an HDUList that contains one\n            PrimaryHDU and four ImageHDU\n\n        \"\"\"\n        w, h = slices.iraf2python(hdul[1].header['DETSIZE'])\n\n        if len(hdul) is 1:\n            logger.warning('%s file contains a single extension. ' % hdul +\n                           'Not doing anything')\n            return hdul[0].data\n\n        # Correct for binning\n        bin_size = _np.array(hdul[1].header['CCDSUM'].split(' '),\n                             dtype=int)\n        bw, bh = w[1] // bin_size[0], h[1] // bin_size[1]\n\n        # Create empty full frame\n        new_data = _np.empty((bh, bw), dtype=float)\n\n        # Process each extension\n        for i in range(1, 5):\n            tx, ty = slices.iraf2python(hdul[i].header['TRIMSEC'])\n            bx, by = slices.iraf2python(hdul[i].header['BIASSEC'])\n\n            data = hdul[i].data\n            trim = data[ty[0]:ty[1], tx[0]:tx[1]]\n            bias = data[by[0]:by[1], bx[0]:bx[1]]\n\n            # Collapse the bias columns to a single column.\n            bias = _np.median(bias, axis=1)\n\n            # Fit and remove OVERSCAN\n            x = _np.arange(bias.size) + 1\n            bias_fit_pars = _np.polyfit(x, bias, 2)  # Last par = inf\n            bias_fit = _np.polyval(bias_fit_pars, x)\n            bias_fit = bias_fit.reshape((bias_fit.size, 1))\n            bias_fit = _np.repeat(bias_fit, trim.shape[1], axis=1)\n\n            trim = trim - bias_fit\n            dx, dy = slices.iraf2python(hdul[i].header['DETSEC'])\n            dx, dy = dx // bin_size[0], dy // bin_size[1]\n            new_data[dy[0]:dy[1], dx[0]:dx[1]] = trim\n\n        header = self.get_header(hdul)\n\n        return new_data, header, \"m_\"\n\n    @staticmethod\n    def remove_cosmic_rays(data, header, prefix, cosmic_rays):\n        \"\"\"\n        Use LACosmic to remove cosmic rays.\n\n        Args:\n\n            data (numpy.ndarray) : A 2D numpy array that contains the data.\n\n            header (astropy.io.fits.Header) : A header that will be updated.\n\n            prefix : str\n                Filename prefix to flag images that were clean.\n\n            cosmic_rays : bool\n                Flag to indicate if cosmic rays removal should be performed.\n        \"\"\"\n        if cosmic_rays:\n\n            d = data\n            d, _ = _cosmicray_lacosmic(\n                d, gain=2.6, readnoise=10.0, sigclip=2.5, sigfrac=0.3,\n                objlim=5.0)\n            d /= 2.6\n\n            h = header\n            h.add_history(\n                'Cosmic rays and hot pixels removed using LACosmic')\n\n            data = d\n            header = h\n\n        return data, header, prefix\n\n    @staticmethod\n    def remove_wcs(header):\n\n        return header\n\n\nclass SamiReducer(Reducer):\n\n    gain = [2.1, 2.0537, 2.1, 2.0823]\n    read_noise = [10., 10., 10., 10.]\n    \n    def reduce(self, hdu_list, prefix=\"\"):\n\n        # If the number of extensions is just 1, then the file is already\n        # processed.\n        if len(hdu_list) == 1:\n            return hdu_list, ''\n\n        # Merge file\n        data, header, prefix = self.merge(hdu_list)\n\n        # Removing bad column and line\n        data, header, prefix = self.remove_central_bad_columns(\n            data, header, prefix,\n        )\n\n        # Correct ZERO\n        data, header, prefix = self.correct_zero(\n            data, header, prefix, self.zero_file\n        )\n\n        # Correct DARK\n        data, header, prefix = self.correct_dark(\n            data, header, prefix, self.dark_file\n        )\n\n        # Remove cosmic rays and hot pixels\n        data, header, prefix = self.remove_cosmic_rays(\n            data, header, prefix, self.cosmic_rays\n        )\n\n        # Remove lateral glows\n        data, header, prefix = self.correct_lateral_glow(\n            data, header, prefix, self.glow_file\n        )\n\n        # Correct FLAT\n        data, header, prefix = self.correct_flat(\n            data, header, prefix, self.flat_file\n        )\n\n        # Normalize by the EXPOSURE TIME\n        data, header, prefix = self.divide_by_exposuretime(\n            data, header, prefix, self.time\n        )\n\n        # Clean known bad columns and lines\n        data, header, prefix = self.clean_hot_columns_and_lines(\n            data, header, prefix, self.clean\n        )\n\n        # Add WCS\n        data, header = self.create_wcs(\n            data, header\n        )\n\n        return data, header, prefix\n\n    def clean_columns(self, data, header):\n        \"\"\"\n        Clean the known bad columns that exists in most of SAMI's, SOI's or\n        SIFS's data. This method is meant to be overwritten via inheritance.\n\n        Args:\n\n            data (numpy.ndarray) : A 2D numpy array that contains the data.\n\n            header (astropy.io.fits.Header) : A header that will be updated.\n\n        See also:\n\n            Reducer.clean_column\n            Reducer.clean_line\n            Reducer.clean_lines\n        \"\"\"\n        binning = header['CCDSUM'].split(' ')[0]\n        binning = int(binning.strip())\n\n        if binning == 4:\n            bad_columns = [\n                [167, 0, 513],\n                [213, 513, 1023],\n                [304, 0, 513],\n                [309, 1, 512],\n                [386, 0, 513],\n                [476, 0, 513],\n                [602, 0, 513],\n                [671, 0, 513],\n                [673, 475, 513],\n                [678, 0, 513],\n                [741, 0, 513],\n                [810, 0, 513],\n                [919, 0, 513],\n                [212, 513, 1023],\n                [680, 513, 1023],\n                [725, 513, 1023],\n                [848, 513, 1023],\n                [948, 0, 512],\n                [949, 0, 512]\n                ]\n        else:\n            []\n\n        for column in bad_columns:\n            x0 = column[0]\n            y0 = column[1]\n            yf = column[2]\n            data = self.clean_column(data, x0, y0, yf)\n\n        return data\n\n    def clean_lines(self, data, header):\n        \"\"\"\n        Clean the known bad lines that exists in most of SAMI's, SOI's or\n        SIFS's data. This method is meant to be overwritten via inheritance.\n\n        Args:\n\n            data (numpy.ndarray) : A 2D numpy array that contains the data.\n\n            header (astropy.io.fits.Header) : A header that will be updated.\n\n        See also:\n\n            Reducer.clean_column\n            Reducer.clean_line\n            Reducer.clean_lines\n        \"\"\"\n        binning = header['CCDSUM'].split(' ')[0]\n        binning = int(binning.strip())\n\n        if binning == 4:\n            bad_lines = [\n                [166, 206, 282],\n                [212, 258, 689],\n                [214, 239, 688],\n                [304, 345, 291],\n                [386, 422, 454],\n                [398, 422, 38],\n                [477, 516, 490],\n                [387, 429, 455],\n                [574, 603, 494],\n                [574, 603, 493],\n                [640, 672, 388],\n                [604, 671, 388],\n                [698, 746, 198],\n                [706, 634, 634],\n                [772, 812, 354],\n                [900, 938, 426],\n                [904, 920, 396]\n            ]\n\n        else:\n            bad_lines = []\n\n        for line in bad_lines:\n            x0 = line[0]\n            xf = line[1]\n            y = line[2]\n            data = self.clean_line(data, x0, xf, y)\n\n        return data\n\n    @staticmethod\n    def remove_central_bad_columns(data, header, prefix):\n        \"\"\"\n        Remove central bad columns at the interface of the four extensions.\n\n        Parameter\n        ---------\n            data : numpy.ndarray\n                2D Array containing the data.\n        \"\"\"\n        n_rows, n_columns = data.shape\n\n        # Copy the central bad columns to a temp array\n        temp_column = data[:, n_columns // 2 - 1:n_columns // 2 + 1]\n\n        # Shift the whole image by two columns\n        data[:, n_columns // 2 - 1:-2] = data[:, n_columns // 2 + 1:]\n\n        # Copy the bad array in the end (right) of the image).\n        data[:, -2:] = temp_column\n\n        return data, header, prefix\n\n\nclass SifsReducer(SamiReducer):\n    pass\n\n\nclass SoiReducer(Reducer):\n    \"\"\"\n    SoiReducer\n\n    This class holds all the methods used to join the extensions within a\n    FITS file obtained with SOI.\n\n    Parameters\n    ----------\n        zero_file : str\n            The filename of the master zero that will be used in subtraction.\n\n        clean : bool\n            Clean bad collumns by taking the _median value of the pixels around\n            them.\n\n        cosmic_rays : bool\n            Clean cosmic rays using LACosmic package. See noted bellow for\n            reference.\n\n        dark_file : str\n            Master Dark's filename to be used for dark subtraction.\n\n        debug : bool\n            Turn on debug mode with lots of printing.\n\n        flat_file : str\n            Master Flat filename to be used for normalization.\n\n        glow_file : str\n            Master file that contains the lateral glowings sometimes present in\n            SAMI's data.\n\n        time : bool\n            Divide each pixel's values by the exposure time and update header.\n\n        verbose : bool\n            Turn on verbose mode (not so talktive as debug mode).\n\n    See also\n    --------\n        LACosmic - http://www.astro.yale.edu/dokkum/lacosmic/\n    \"\"\"\n\n    @staticmethod\n    def add_gap(data, header, interpolation_factor=10):\n        \"\"\"\n        SOI has two detectors which are separated by 7.8 arcsec (or 102\n        unbinned pixels). This method reads an merged array and adds the gap\n        based on the detector's binning.\n\n        Parameters\n        ----------\n            data : numpy.ndarray\n                2D array with the data merged.\n\n            header : astropy.io.fits.Header\n                a header that contains the binning information on the 'CCDSUM'\n                key.\n        \"\"\"\n        if header['OBSTYPE'] == 'OBJECT':\n\n            binning = header['CCDSUM']\n            binning = int(binning.split()[0])\n\n            gap_size = 7.8  # arcseconds\n            pixel_scale = 0.0767  # arcsecond / pixel\n            gap_pixel = int(round(gap_size / pixel_scale / binning, 0))\n\n            nrow, ncol = data.shape\n\n            data = _np.append(data, _np.zeros((nrow, gap_pixel)), axis=1)\n            data[:, ncol // 2 + gap_pixel:] = data[:, ncol // 2:- gap_pixel]\n            data[:, ncol // 2:ncol // 2 + gap_pixel] = 0\n\n        return data, header\n\n    def clean_columns(self, _data, _header):\n        \"\"\"\n        Clean the known bad columns that exists in most of SAMI's data.\n\n        Parameters\n        ----------\n            _data : numpy.ndarray\n                A 2D numpy array that contains the data.\n\n            _header : astropy.io.fits.Header\n                a header that contains the binning information on the 'CCDSUM'\n                key.\n\n        See also\n        --------\n            SoiMerger.clean_column\n            SoiMerger.clean_line\n            SoiMerger.clean_lines\n        \"\"\"\n        if not isinstance(_data, _np.ndarray):\n            raise (TypeError, 'Please, use a np.array as input')\n        if _data.ndim is not 2:\n            raise (TypeError, 'Data contains %d dimensions while it was '\n                              'expected 2 dimensions.')\n\n        b = int(_header['CCDSUM'].strip().split(' ')[0])\n\n        if b == 1:\n            bad_columns = []\n        elif b == 2:\n            bad_columns = [\n                [855, 0, 2047],\n            ]\n        elif b == 4:\n            bad_columns = [\n                [427, 0, 1023]\n            ]\n        else:\n            logger.warning(\n                'Skipping clean_columns for binning {} x {}'.format(b, b))\n            bad_columns = []\n\n        for column in bad_columns:\n            x0 = column[0]\n            y0 = column[1]\n            yf = column[2]\n            _data = self.clean_column(_data, x0, y0, yf)\n\n        return _data\n\n    def clean_lines(self, hdu_list):\n        \"\"\"\n        Clean the known bad lines that exists in most of SAMI's, SOI's or\n        SIFS's data. This method is meant to be overwritten via inheritance.\n\n        Args:\n\n            hdu_list (astropy.io.fits.HDUList)\n\n        See also:\n\n            Reducer.clean_column\n            Reducer.clean_line\n            Reducer.clean_lines\n        \"\"\"\n        if not isinstance(hdu_list, _pyfits.HDUList):\n            raise TypeError('Please, use a HDUList as input')\n\n        if len(hdu_list) != 5:\n            raise ValueError(\n                \"HDUList is expected to have 1 + 4 elements. Found {}\".format(\n                    len(hdu_list)))\n\n        for i in range(1, len(hdu_list)):\n\n            _data = hdu_list[i].data\n            _hdr = hdu_list[i].header\n\n            bad_lines = [\n                # [166, 206, 282],\n                # [212, 258, 689],\n                # [214, 239, 688],\n                # [304, 345, 291],\n                # [386, 422, 454],\n                # [398, 422, 38],\n                # [477, 516, 490],\n                # [387, 429, 455],\n                # [574, 603, 494],\n                # [574, 603, 493],\n                # [640, 672, 388],\n                # [604, 671, 388],\n                # [698, 746, 198],\n                # [706, 634, 634],\n                # [772, 812, 354],\n                # [900, 938, 426],\n                # [904, 920, 396]\n            ]\n\n            for line in bad_lines:\n                x0 = line[0]\n                xf = line[1]\n                y = line[2]\n                _data = self.clean_line(_data, x0, xf, y)\n\n            hdu_list[i].data = _data\n\n        return hdu_list\n\n\ndef _normalize_data(data):\n    \"\"\"\n    This method is intended to normalize flat data before it is applied to the\n    images that are being reduced. A total of 1000 random points are used to\n    estimate the _median level that will be used for normalization.\n\n    Args:\n\n        data (numpy.ndarray) : Data that will be normalized\n\n    Returns:\n        norm_data (numpy.ndarray) : Normalized data.\n    \"\"\"\n    sample = _np.random.randint(0, high=data.size - 1, size=1000)\n    mode = stats.mode(data.ravel()[sample])[0]\n\n    return data / mode\n", "meta": {"hexsha": "f789661476f6d1271cee57789463a040f2c9b594", "size": 34399, "ext": "py", "lang": "Python", "max_stars_repo_path": "soar_simager/data_reduction/reduce.py", "max_stars_repo_name": "soar-telescope/sami", "max_stars_repo_head_hexsha": "8a9e2b28e3e7d753d05220abd0bac6912fa36ad1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-09T21:57:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-09T21:57:27.000Z", "max_issues_repo_path": "soar_simager/data_reduction/reduce.py", "max_issues_repo_name": "soar-telescope/sami", "max_issues_repo_head_hexsha": "8a9e2b28e3e7d753d05220abd0bac6912fa36ad1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2018-06-21T22:19:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-22T20:35:55.000Z", "max_forks_repo_path": "soar_simager/data_reduction/reduce.py", "max_forks_repo_name": "soar-telescope/sami", "max_forks_repo_head_hexsha": "8a9e2b28e3e7d753d05220abd0bac6912fa36ad1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7857740586, "max_line_length": 80, "alphanum_fraction": 0.5343469287, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 8515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3665897432423098, "lm_q1q2_score": 0.19330882891314297}}
{"text": "# SVMs for Food Experiment Data\nimport matplotlib \nimport numpy as np\nimport matplotlib.pyplot as pp\nimport optparse\nimport unittest\nimport random\nimport itertools\nfrom sklearn import decomposition\nfrom sklearn import svm\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import LeaveOneOut\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom scipy.interpolate import InterpolatedUnivariateSpline\nfrom scipy.ndimage.filters import gaussian_filter1d\nimport sys\nimport lib_get_subset as lib_get_subset\nimport matplotlib.pyplot as plt\n\n\nTRIAL_ORDER = [[1, 4, 6, 2, 3, 7, 0, 5, 8],\n               [0, 3, 6, 2, 5, 7, 1, 4, 8],\n               [2, 3, 7, 1, 4, 6, 0, 5, 8],\n               [2, 4, 6, 0, 5, 8, 1, 3, 7],\n               [0, 5, 6, 1, 4, 7, 2, 3, 8],\n               [1, 3, 8, 0, 4, 6, 2, 5, 7],\n               [0, 4, 7, 1, 3, 8, 2, 5, 6],\n               [2, 3, 8, 0, 4, 6, 1, 5, 7],\n               [0, 3, 8, 2, 4, 6, 1, 5, 7],\n               [1, 3, 6, 0, 5, 7, 2, 4, 8],\n               [0, 5, 7, 1, 3, 8, 2, 4, 6],\n               [1, 3, 8, 0, 4, 7, 2, 5, 6],\n               [1, 5, 6, 0, 4, 7, 2, 3, 8],\n               [1, 5, 8, 2, 4, 6, 0, 3, 7],\n               [1, 5, 8, 2, 4, 6, 0, 3, 7],\n               [1, 4, 6, 2, 5, 7, 0, 3, 8],\n               [0, 4, 6, 2, 5, 8, 1, 3, 7],\n               [2, 4, 7, 0, 5, 6, 1, 3, 8],\n               [1, 5, 7, 0, 3, 6, 2, 4, 8],\n               [2, 5, 7, 0, 4, 8, 1, 3, 6],\n               [2, 5, 7, 1, 4, 6, 0, 3, 8],\n               [0, 5, 7, 2, 3, 6, 1, 4, 8],\n               [2, 4, 8, 0, 5, 6, 1, 3, 7],\n               [2, 5, 7, 0, 4, 8, 1, 3, 6],\n               [1, 3, 7, 2, 5, 8, 0, 4, 6],\n               [2, 3, 8, 1, 5, 7, 0, 4, 6],\n               [2, 3, 7, 0, 5, 8, 1, 4, 6],\n               [1, 4, 7, 0, 5, 6, 2, 3, 8],\n               [2, 5, 8, 1, 3, 6, 0, 4, 7],\n               [1, 4, 8, 0, 5, 7, 2, 3, 6]]\n\nNUM_TRIAL_SETS = len(TRIAL_ORDER)\n\n\n\ndef get_most_overlapping(x_full, data_dict, num_pairs):\n\n    matching_criteria = []\n\n    for trial_set in range(len(TRIAL_ORDER)):\n        optim_set = data_dict['trial_set_' + str(trial_set + 1) + '_X']\n        print(\"trial set 1 shape\", optim_set.shape)\n\n        for block in [0, 1, 2]:\n            present_set = optim_set[block, :]\n            for other_trial_set in range(len(TRIAL_ORDER)):\n                if other_trial_set != trial_set:\n                    for CW_block in [6, 7, 8]:\n                        check_set = data_dict['trial_set_' + str(other_trial_set + 1) + '_X'][CW_block, :]\n                        #print(present_set)\n                        #print(check_set)\n                        matching_criteria.append([trial_set, block, other_trial_set, CW_block, np.sum(np.square(present_set - check_set))])\n\n            #break\n\n\n        #break\n\n    matching_criteria = np.array(matching_criteria)\n\n    matching_criteria = matching_criteria[matching_criteria[:,4].argsort()]\n    #matching_criteria = np.flipud(matching_criteria)\n\n    #for criteria in matching_criteria:\n    #    print(criteria)\n\n\n\n    #matching_criteria = matching_criteria[0:num_pairs, :]\n\n    #here make sure there arne't any duplicates in the list\n    reduced_matching_criteria = []\n    iterator = 0\n    while len(reduced_matching_criteria) < num_pairs:\n        next_criteria = matching_criteria[iterator, :]\n        should_append = True\n        print(next_criteria)\n        for item in reduced_matching_criteria:\n            if item[0] == next_criteria[0] and item[1] == next_criteria[1]:\n                should_append = False\n            if item[2] == next_criteria[2] and item[3] == next_criteria[3]:\n                should_append = False\n        if should_append == True:\n            reduced_matching_criteria.append(next_criteria)\n        iterator += 1\n\n    matching_criteria = np.array(reduced_matching_criteria).astype(int)\n\n\n\n\n\n    print(matching_criteria.astype(int))\n\n    X_data = []\n    y_data = []\n    #Use matching criteria indexing to create data subsets that we can use for LOOCV\n    for ct in range(num_pairs):\n        trial_set = int(matching_criteria[ct, 0])\n        block = int(matching_criteria[ct, 1])\n        X_data.append(data_dict['trial_set_' + str(trial_set + 1) + '_X'][block, :])\n        y_data.append(0)\n    for ct in range(num_pairs):\n        trial_set = int(matching_criteria[ct, 2])\n        block = int(matching_criteria[ct, 3])\n        X_data.append(data_dict['trial_set_' + str(trial_set + 1) + '_X'][block, :])\n        y_data.append(1)\n    X_data = np.array(X_data)\n    y_data = np.array(y_data)\n\n    # print(len(skf))\n    # for train_index, test_index in skf:\n\n\n\n\n\n    cm_total = np.zeros((2,2))\n\n    #loo = LeaveOneOut(num_pairs)\n    #for train_index, test_index in loo:\n\n    for i in range(1000):\n        kfold = KFold(n_splits=3, shuffle = True)\n        kfold.get_n_splits(np.arange(num_pairs))\n        for train_index, test_index in kfold.split(np.arange(num_pairs)):\n            print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n            train_index_second = list(np.array(train_index) + num_pairs)\n            train_index = np.array(list(train_index) + train_index_second)\n            test_index_second = list(np.array(test_index) + num_pairs)\n            test_index = np.array(list(test_index) + test_index_second)\n            print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n\n            print(np.shape(X_data))\n\n            X_train, X_test = X_data[train_index], X_data[test_index]\n            print(np.shape(X_train))\n\n            y_train, y_test = y_data[train_index], y_data[test_index]\n            # print(X_test)\n            # print(y_test)\n\n            svc = svm.SVC(kernel='linear')\n            # svc = svm.SVC(kernel='rbf')\n            # svc = svm.SVC(kernel='poly', degree=3)\n            clf = svc.fit(X_train, y_train)\n            preds = svc.predict(X_test)\n\n            print(y_test, preds)\n\n            cm = confusion_matrix(y_test, preds, labels=[0, 1])\n\n            scores = clf.score(X_test, y_test)\n\n            #print(test_index, y_test, np.array(preds))\n            cm_total += cm\n            print(cm)\n            print(cm_total)\n    print(cm_total / 1000)\n\n    '''\n    ax=[]\n    fig = plt.figure()\n    print(np.shape(X_data))\n    for trial_set in range(num_pairs):\n        ax.append(trial_set)\n        print(\"trial set num: \", trial_set)\n\n        ax[-1] = fig.add_subplot(4, 5, trial_set+1)\n\n\n        ax[-1].plot(np.arange(1000)/200., X_data[trial_set+num_pairs, :], 'r-', linewidth=0.5)\n        ax[-1].plot(np.arange(1000)/200., X_data[trial_set, :], 'b-', linewidth=0.5)\n\n        ax[-1].set_ylim(26.0, 30.0)\n        ax[-1].set_xlim(0, 5)\n        ax[-1].grid()\n\n    plt.tight_layout()\n    fig = plt.gcf()\n    plt.show()\n    '''\n\n\n\ndef get_meanstd_overlapping2(data_dict):\n\n\n    print(\"GOT TO OVERLAPPING2\")\n\n    X_data_all_M = []\n    y_data_all_M = []\n    X_data_all_CW = []\n    y_data_all_CW = []\n    X_data_all_W = []\n    y_data_all_W = []\n\n    for trial_set in range(len(TRIAL_ORDER)):\n        optim_set = data_dict['trial_set_' + str(trial_set + 1) + '_X']\n        print(\"trial set 1 shape\", optim_set.shape)\n\n        for block in [0, 1, 2]:\n            X_data_all_M.append(optim_set[block, :])\n            y_data_all_M.append(0)\n\n        for block in [3, 4, 5]:\n            X_data_all_W.append(optim_set[block, :])\n            y_data_all_W.append(1)\n\n\n        for block in [6, 7, 8]:\n            X_data_all_CW.append(optim_set[block, :])\n            y_data_all_CW.append(1)\n\n\n\n\n    X_data_all_M = np.array(X_data_all_M)\n    X_data_all_CW = np.array(X_data_all_CW)\n    X_data_all_W = np.array(X_data_all_W)\n    print(X_data_all_M.shape)\n    X_data_all_M_mean = np.mean(X_data_all_M, axis = 0)\n    X_data_all_M_std = np.std(X_data_all_M, axis = 0)\n    X_data_all_CW_mean = np.mean(X_data_all_CW, axis = 0)\n    X_data_all_CW_std = np.std(X_data_all_CW, axis = 0)\n    X_data_all_W_mean = np.mean(X_data_all_W, axis = 0)\n    X_data_all_W_std = np.std(X_data_all_W, axis = 0)\n    #print(X_data_all_M_mean.shape)\n    #print(X_data_all_M_mean)\n    #print(X_data_all_M_std)\n\n    #print(X_data_all_M_mean - X_data_all_M_std)\n\n\n    X_upper_bound = np.amin([X_data_all_CW_mean + X_data_all_CW_std, X_data_all_M_mean + X_data_all_M_std], axis = 0)\n    X_lower_bound = np.amax([X_data_all_CW_mean - X_data_all_CW_std, X_data_all_M_mean - X_data_all_M_std], axis = 0)\n    #print(\"BLAH\")\n    #print(X_upper_bound)\n    #print(X_lower_bound)\n    #print(\"BLAH2\")\n\n\n    fig, ax = plt.subplots()\n\n    #ax.plot(np.arange(0, 1000)/200., X_data_all_M_mean[0:1000], color = '#d95f02', label=\"mean M, active\")\n    #ax.plot(np.arange(0, 1000)/200., X_data_all_CW_mean[0:1000], '--', color = '#1b9e77', label=\"mean CW, active\")\n    #ax.plot(np.arange(0, 1000)/200., X_data_all_W_mean[0:1000],  '-.', color = '#7570b3', label=\"mean W, active\")\n    #ax.fill_between(np.arange(0, 1000)/200.,\n    #                X_data_all_M_mean[0:1000] - X_data_all_M_std[0:1000],\n    #                X_data_all_M_mean[0:1000] + X_data_all_M_std[0:1000], facecolor='#d95f02', alpha = 0.3)\n    #ax.fill_between(np.arange(0, 1000)/200.,\n    #                X_data_all_CW_mean[0:1000] - X_data_all_CW_std[0:1000],\n    #                X_data_all_CW_mean[0:1000] + X_data_all_CW_std[0:1000], facecolor='#1b9e77', alpha = 0.3)\n    #ax.fill_between(np.arange(0, 1000)/200.,\n    #                X_data_all_W_mean[0:1000] - X_data_all_W_std[0:1000],\n    #                X_data_all_W_mean[0:1000] + X_data_all_W_std[0:1000], facecolor='#7570b3', alpha = 0.3)\n    #ax.plot(np.arange(0, 1000)/200., X_lower_bound, 'c-')\n    #ax.plot(np.arange(0, 1000)/200., X_upper_bound, 'c-')\n\n    ax.plot(np.arange(0, 1000)/200., X_data_all_M_mean[1000:2000], color = '#d95f02', label=\"mean M, passive\")\n    ax.plot(np.arange(0, 1000)/200., X_data_all_CW_mean[1000:2000], '--', color = '#1b9e77', label=\"mean CW, passive\")\n    ax.plot(np.arange(0, 1000)/200., X_data_all_W_mean[1000:2000],  '-.', color = '#7570b3', label=\"mean W, passive\")\n\n    ax.fill_between(np.arange(0, 1000)/200.,\n                    X_data_all_M_mean[1000:2000] - X_data_all_M_std[1000:2000],\n                    X_data_all_M_mean[1000:2000] + X_data_all_M_std[1000:2000], facecolor='#d95f02', alpha = 0.3)\n    ax.fill_between(np.arange(0, 1000)/200.,\n                    X_data_all_CW_mean[1000:2000] - X_data_all_CW_std[1000:2000],\n                    X_data_all_CW_mean[1000:2000] + X_data_all_CW_std[1000:2000], facecolor='#1b9e77', alpha = 0.3)\n    ax.fill_between(np.arange(0, 1000)/200.,\n                    X_data_all_W_mean[1000:2000] - X_data_all_W_std[1000:2000],\n                    X_data_all_W_mean[1000:2000] + X_data_all_W_std[1000:2000], facecolor='#7570b3', alpha = 0.3)\n    #ax.plot(np.arange(0, 1000)/200., X_lower_bound, 'c-')\n    #ax.plot(np.arange(0, 1000)/200., X_upper_bound, 'c-')\n\n\n\n    ax.legend(loc=3, fontsize=10)\n    ax.set_title(\"Mean Temperature and \\n Standard Deviation Bounds\", fontsize=16)\n    ax.set_xlabel(\"Time Elapsed (seconds)\", fontsize=14)\n    ax.set_ylabel(\"Temperature, Celsius\", fontsize=14)\n    plt.tight_layout()\n    fig = plt.gcf()\n    plt.show()\n\n\n    X_data_all_M = list(X_data_all_M)\n    X_data_all_CW = list(X_data_all_CW)\n\n    X_data = []\n    y_data = []\n\n    #ax.plot(np.arange(0, 1000) / 200., X_data_all_mean + X_data_all_std, 'k-', label=\"mean\")\n    for ct in range(len(X_data_all_M)):\n\n        if np.min(X_upper_bound - X_data_all_M[ct]) > 0 and\\\n                np.min(X_data_all_M[ct] - X_lower_bound) > 0:\n            #ax.plot(np.arange(0, 1000) / 200., X_data_all[ct], 'r-', linewidth = 0.5)\n            X_data.append(X_data_all_M[ct])\n            y_data.append(y_data_all_M[ct])\n\n    for ct in range(len(X_data_all_CW)):\n\n        if np.min(X_upper_bound - X_data_all_CW[ct]) > 0 and\\\n                np.min(X_data_all_CW[ct] - X_lower_bound) > 0:\n            #ax.plot(np.arange(0, 1000) / 200., X_data_all[ct], 'r-', linewidth = 0.5)\n            X_data.append(X_data_all_CW[ct])\n            y_data.append(y_data_all_CW[ct])\n\n    print(np.shape(X_data))\n    print(np.shape(y_data))\n    print(np.sum(y_data))\n\n    #ax.legend()\n    #plt.tight_layout()\n    #fig = plt.gcf()\n    #plt.show()\n\n    X_data = np.array(X_data)\n    y_data = np.array(y_data)\n\n    from time import sleep\n    sleep(4)\n\n    cm_total = np.zeros((2,2))\n\n    for i in range(1000):\n\n        skf = StratifiedKFold(y_data, n_folds=3, shuffle=True)\n        for train_index, test_index in skf:\n            print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n\n            print(np.shape(X_data))\n\n            X_train = X_data[train_index]\n            X_test = X_data[test_index]\n            print(np.shape(X_train))\n\n            y_train, y_test = y_data[train_index], y_data[test_index]\n            # print(X_test)\n            # print(y_test)\n\n            svc = svm.SVC(kernel='linear')\n            # svc = svm.SVC(kernel='rbf')\n            # svc = svm.SVC(kernel='poly', degree=3)\n            clf = svc.fit(X_train, y_train)\n            preds = svc.predict(X_test)\n\n            print(y_test, preds)\n\n            cm = confusion_matrix(y_test, preds, labels=[0, 1])\n\n            scores = clf.score(X_test, y_test)\n\n            #print(test_index, y_test, np.array(preds))\n            cm_total += cm\n            print(cm)\n            print(cm_total)\n    print(cm_total/1000)\n\n    '''\n    ax=[]\n    fig = plt.figure()\n    print(np.shape(X_data))\n    for trial_set in range(num_pairs):\n        ax.append(trial_set)\n        print(\"trial set num: \", trial_set)\n\n        ax[-1] = fig.add_subplot(4, 5, trial_set+1)\n\n\n        ax[-1].plot(np.arange(1000)/200., X_data[trial_set+num_pairs, :], 'r-', linewidth=0.5)\n        ax[-1].plot(np.arange(1000)/200., X_data[trial_set, :], 'b-', linewidth=0.5)\n\n        ax[-1].set_ylim(26.0, 30.0)\n        ax[-1].set_xlim(0, 5)\n        ax[-1].grid()\n\n    plt.tight_layout()\n    fig = plt.gcf()\n    plt.show()\n    '''\ndef get_meanstd_overlapping(x_full, data_dict):\n\n    X_data_all = []\n    y_data_all = []\n\n    for trial_set in range(len(TRIAL_ORDER)):\n        optim_set = data_dict['trial_set_' + str(trial_set + 1) + '_X']\n        print(\"trial set 1 shape\", optim_set.shape)\n\n        for block in [0, 1, 2, 6, 7, 8]:\n            X_data_all.append(optim_set[block, :])\n            if block in [0, 1, 2]:\n                y_data_all.append(0)\n            else:\n                y_data_all.append(1)\n\n    X_data_all = np.array(X_data_all)\n    print(X_data_all.shape)\n    X_data_all_mean = np.mean(X_data_all, axis = 0)\n    X_data_all_std = np.std(X_data_all, axis = 0)\n    print(X_data_all_mean.shape)\n    print(X_data_all_mean)\n    print(X_data_all_std)\n\n    print(X_data_all_mean - X_data_all_std)\n\n    fig, ax = plt.subplots()\n\n    ax.plot(np.arange(0, 1000)/200., X_data_all_mean, 'k-', label=\"mean\")\n    ax.fill_between(np.arange(0, 1000)/200.,\n                    X_data_all_mean - X_data_all_std,\n                    X_data_all_mean + X_data_all_std)\n    ax.legend()\n    plt.tight_layout()\n    fig = plt.gcf()\n    plt.show()\n\n    X_data_all = list(X_data_all)\n\n    X_data = []\n    y_data = []\n\n    ax.plot(np.arange(0, 1000) / 200., X_data_all_mean + X_data_all_std, 'k-', label=\"mean\")\n    for ct in range(len(X_data_all)):\n\n        print(ct, np.shape(X_data_all_mean + X_data_all_std - X_data_all[ct]),\n              np.min(X_data_all_mean + X_data_all_std - X_data_all[ct]),\n              np.min(X_data_all[ct] + X_data_all_std - X_data_all_mean))\n\n        if np.min(X_data_all_mean + X_data_all_std - X_data_all[ct]) > 0 and\\\n                np.min(X_data_all[ct] - X_data_all_mean + X_data_all_std) > 0:\n            #ax.plot(np.arange(0, 1000) / 200., X_data_all[ct], 'r-', linewidth = 0.5)\n            X_data.append(X_data_all[ct])\n            y_data.append(y_data_all[ct])\n\n    print(np.shape(X_data))\n    print(np.shape(y_data))\n    print(np.sum(y_data))\n\n    #ax.legend()\n    #plt.tight_layout()\n    #fig = plt.gcf()\n    #plt.show()\n\n    X_data = np.array(X_data)\n    y_data = np.array(y_data)\n\n\n\n    cm_total = np.zeros((2,2))\n\n    for i in range(1000):\n\n        skf = StratifiedKFold(y_data, n_folds=3, shuffle=True)\n        for train_index, test_index in skf:\n            print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n\n            print(np.shape(X_data))\n\n            X_train = X_data[train_index]\n            X_test = X_data[test_index]\n            print(np.shape(X_train))\n\n            y_train, y_test = y_data[train_index], y_data[test_index]\n            # print(X_test)\n            # print(y_test)\n\n            svc = svm.SVC(kernel='linear')\n            # svc = svm.SVC(kernel='rbf')\n            # svc = svm.SVC(kernel='poly', degree=3)\n            clf = svc.fit(X_train, y_train)\n            preds = svc.predict(X_test)\n\n            print(y_test, preds)\n\n            cm = confusion_matrix(y_test, preds, labels=[0, 1])\n\n            scores = clf.score(X_test, y_test)\n\n            #print(test_index, y_test, np.array(preds))\n            cm_total += cm\n            print(cm)\n            print(cm_total)\n    print(cm_total/1000)\n\n    '''\n    ax=[]\n    fig = plt.figure()\n    print(np.shape(X_data))\n    for trial_set in range(num_pairs):\n        ax.append(trial_set)\n        print(\"trial set num: \", trial_set)\n\n        ax[-1] = fig.add_subplot(4, 5, trial_set+1)\n\n\n        ax[-1].plot(np.arange(1000)/200., X_data[trial_set+num_pairs, :], 'r-', linewidth=0.5)\n        ax[-1].plot(np.arange(1000)/200., X_data[trial_set, :], 'b-', linewidth=0.5)\n\n        ax[-1].set_ylim(26.0, 30.0)\n        ax[-1].set_xlim(0, 5)\n        ax[-1].grid()\n\n    plt.tight_layout()\n    fig = plt.gcf()\n    plt.show()\n    '''\n\n\ndef get_overlapping_reference(x_full, data_dict, num_referenced):\n\n    matching_criteria = []\n\n    #get set of all possible pairs of RMSE scores\n    for trial_set in range(len(TRIAL_ORDER)):\n        optim_set = data_dict['trial_set_' + str(trial_set + 1) + '_X']\n        print(\"trial set 1 shape\", optim_set.shape)\n        for block in [0, 1, 2]:\n            present_set = optim_set[block, :]\n            for other_trial_set in range(len(TRIAL_ORDER)):\n                if other_trial_set != trial_set:\n                    for CW_block in [6, 7, 8]:\n                        check_set = data_dict['trial_set_' + str(other_trial_set + 1) + '_X'][CW_block, :]\n                        #print(present_set)\n                        #print(check_set)\n                        matching_criteria.append([trial_set, block, other_trial_set, CW_block, np.sum(np.square(present_set - check_set))])\n\n\n\n    matching_criteria = np.array(matching_criteria)\n    matching_criteria = matching_criteria[matching_criteria[:,4].argsort()]\n    #matching_criteria = np.flipud(matching_criteria)\n\n\n    referenced_pair = matching_criteria[0, :]\n    print(referenced_pair)\n\n\n    #get set of nearest metals to the metal\n    matching_M_criteria = []\n    M_trial_set = int(referenced_pair[0])\n    M_block = int(referenced_pair[1])\n    present_set = data_dict['trial_set_' + str(M_trial_set + 1) + '_X'][M_block, :]\n    for other_trial_set in range(len(TRIAL_ORDER)):\n        for other_block in [0, 1, 2]:\n            if other_trial_set == M_trial_set and other_block == M_block: pass\n            else:\n                check_set = data_dict['trial_set_' + str(other_trial_set + 1) + '_X'][other_block, :]\n                matching_M_criteria.append([other_trial_set, other_block, np.sum(np.square(present_set - check_set))])\n    matching_M_criteria = np.array(matching_M_criteria)\n    matching_M_criteria = matching_M_criteria[matching_M_criteria[:,2].argsort()]\n\n    print(matching_M_criteria[0:num_referenced-1, :])\n\n\n    #get set of nearest cold woods to the cold wood\n    matching_CW_criteria = []\n    CW_trial_set = int(referenced_pair[2])\n    CW_block = int(referenced_pair[3])\n    present_set = data_dict['trial_set_' + str(CW_trial_set + 1) + '_X'][CW_block, :]\n    for other_trial_set in range(len(TRIAL_ORDER)):\n        for other_block in [6, 7, 8]:\n            if other_trial_set == CW_trial_set and other_block == CW_block: pass\n            else:\n                check_set = data_dict['trial_set_' + str(other_trial_set + 1) + '_X'][other_block, :]\n                matching_CW_criteria.append([other_trial_set, other_block, np.sum(np.square(present_set - check_set))])\n    matching_CW_criteria = np.array(matching_CW_criteria)\n    matching_CW_criteria = matching_CW_criteria[matching_CW_criteria[:,2].argsort()]\n\n    print(matching_CW_criteria[0:num_referenced-1, :])\n\n\n\n\n    print(matching_criteria.astype(int))\n\n\n    #Use matching criteria indexing to create data subsets that we can use for LOOCV\n    X_data = []\n    y_data = []\n    trial_set = int(referenced_pair[0])\n    block = int(referenced_pair[1])\n    X_data.append(data_dict['trial_set_' + str(trial_set + 1) + '_X'][block, :])\n    y_data.append(0)\n    for ct in range(num_referenced-1):\n        trial_set = int(matching_M_criteria[ct, 0])\n        block = int(matching_M_criteria[ct, 1])\n        X_data.append(data_dict['trial_set_' + str(trial_set + 1) + '_X'][block, :])\n        y_data.append(0)\n\n\n    trial_set = int(referenced_pair[2])\n    block = int(referenced_pair[3])\n    X_data.append(data_dict['trial_set_' + str(trial_set + 1) + '_X'][block, :])\n    y_data.append(1)\n    for ct in range(num_referenced-1):\n        trial_set = int(matching_CW_criteria[ct, 0])\n        block = int(matching_CW_criteria[ct, 1])\n        X_data.append(data_dict['trial_set_' + str(trial_set + 1) + '_X'][block, :])\n        y_data.append(1)\n\n    X_data = np.array(X_data)\n    y_data = np.array(y_data)\n\n    print(y_data)\n\n    # print(len(skf)\n    # for train_index, test_index in skf:\n\n\n    cm_total = np.zeros((2,2))\n\n    #loo = LeaveOneOut(num_pairs)\n    #for train_index, test_index in loo:\n\n\n    for i in range(1000):\n\n        skf = StratifiedKFold(y_data, n_folds=3, shuffle=True)\n        for train_index, test_index in skf:\n            print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n\n            print(np.shape(X_data))\n\n            X_train, X_test = X_data[train_index], X_data[test_index]\n            print(np.shape(X_train))\n\n            y_train, y_test = y_data[train_index], y_data[test_index]\n            # print(X_test)\n            # print(y_test)\n\n            svc = svm.SVC(kernel='linear')\n            # svc = svm.SVC(kernel='rbf')\n            # svc = svm.SVC(kernel='poly', degree=3)\n            clf = svc.fit(X_train, y_train)\n            preds = svc.predict(X_test)\n\n            print(y_test, preds)\n\n            cm = confusion_matrix(y_test, preds, labels=[0, 1])\n\n            scores = clf.score(X_test, y_test)\n\n            #print(test_index, y_test, np.array(preds))\n            cm_total += cm\n            print(cm)\n            print(cm_total)\n    print(cm_total/1000)\n    #[[6.234 3.766]\n    # [3.221 6.779]]\n\n\n\n    '''\n    ax=[]\n    fig = plt.figure()\n    print(np.shape(X_data))\n    for trial_set in range(num_pairs):\n        ax.append(trial_set)\n        print(\"trial set num: \", trial_set)\n\n        ax[-1] = fig.add_subplot(4, 5, trial_set+1)\n\n\n        ax[-1].plot(np.arange(1000)/200., X_data[trial_set+num_pairs, :], 'r-', linewidth=0.5)\n        ax[-1].plot(np.arange(1000)/200., X_data[trial_set, :], 'b-', linewidth=0.5)\n\n        ax[-1].set_ylim(26.0, 30.0)\n        ax[-1].set_xlim(0, 5)\n        ax[-1].grid()\n\n    plt.tight_layout()\n    fig = plt.gcf()\n    plt.show()\n    '''", "meta": {"hexsha": "e85a52506cfa37f37762356fe91944432938664d", "size": 23496, "ext": "py", "lang": "Python", "max_stars_repo_path": "robot_study/lib_overlapping.py", "max_stars_repo_name": "Healthcare-Robotics/thermal-ambiguity-ToH", "max_stars_repo_head_hexsha": "70dbe35c6096b3793ed0565656d6ff2a30fdcf5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "robot_study/lib_overlapping.py", "max_issues_repo_name": "Healthcare-Robotics/thermal-ambiguity-ToH", "max_issues_repo_head_hexsha": "70dbe35c6096b3793ed0565656d6ff2a30fdcf5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "robot_study/lib_overlapping.py", "max_forks_repo_name": "Healthcare-Robotics/thermal-ambiguity-ToH", "max_forks_repo_head_hexsha": "70dbe35c6096b3793ed0565656d6ff2a30fdcf5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.517831669, "max_line_length": 139, "alphanum_fraction": 0.5896748383, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3665897363221599, "lm_q1q2_score": 0.1933088252640336}}
{"text": "#!/urs/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"/stations.py\nAuthor: Hunter Mellema\nSummary: Defines measuring stations for simulation for CR3BP navigation simulations\nProject: Advanced State Estimation Final Project\nAuthor: Hunter Mellema\nDate: April 2020\n\"\"\"\n# === Begin Imports ===\n# third party\nimport numpy as np\nfrom numpy.linalg import norm\n\n# local imports\nfrom .constants import (\n    THETA_0,\n    R_E,\n    W_E_ND,\n    R_E_ND,\n    EARTH_ANG_VEL_ND,\n    NON_DIM_DIST_TO_DIM,\n    MU_EARTH_MOON,\n    E_M_OFFSET_ANGLE, \n    OMEGA_CR3BP, \n    CR3BP_ANG_VEL\n)\nfrom .measurements import R3Msr, Range\n\n# std library\nimport json\n\n# === End Imports ===\n\n# Measurement Generation Functions\nclass CR3BPEarthStn(object):\n    \"\"\" Represents a ground station at some point on the earth's surface that is taking measurements\n    of a spacecraft.\n    Args:\n        stn_id (str, int): a unique string or integer id for the given station\n        longitude (float): longitude of the station position in degrees\n        latitude (float): latitude of the station in degrees\n        el_mask (float): elevation below which the station will not take measurements (in degrees)\n        covariance (np.ndarray): covariance for measurements take by this station. Will be added to\n            every measurement taken by this station\n\n    \"\"\"\n\n    def __init__(\n        self,\n        stn_name,\n        stn_id,\n        pos_ecef_nd,\n        el_mask,\n        cov,\n        msrs,\n        mu,\n        lat=None,\n        longitude=None,\n        el=None,\n    ):\n        self.stn_name = stn_name\n        self.stn_id = stn_id\n        self.pos = pos_ecef_nd\n        self.el_mask = el_mask\n        self.cov = cov\n        self.allowed_msrs = msrs\n        self.lat = lat\n        self.long = longitude\n        self.el = el\n        self.mu = mu\n\n    @classmethod\n    def from_db_object(cls, station_data):\n        \"\"\" Constructs a stn from a row in the database\n        \n        Args: \n            station_data (dict): dicitonary representing a row in the stations table\n\n        Return: \n            cls\n\n        \"\"\"\n        pos_nd = lat_long_to_ecef(\n            station_data[\"latitude_deg\"],\n            station_data[\"longitude_deg\"],\n            station_data[\"elevation_km\"],\n        ) * (1 / NON_DIM_DIST_TO_DIM)\n\n        return cls(\n            station_data[\"stn_name\"],\n            station_data[\"stn_id\"],\n            pos_nd,\n            station_data[\"elevation_mask_deg\"],\n            json.loads(station_data[\"covariance\"]),\n            json.loads(station_data[\"measurement_types\"]),\n            station_data[\"mu\"],\n            station_data[\"latitude_deg\"],\n            station_data[\"longitude_deg\"],\n            station_data[\"elevation_km\"],\n        )\n\n    def __repr__(self):\n        string = \"\"\"\n        ==================================================\n        ++++++++++++++++++++++++++++++++++++++++++++++++++\n        STN: {}     | STN ID: {}\n        ++++++++++++++++++++++++++++++++++++++++++++++++++\n        Position: \n            {} (Nondimensional CR3BP)\n        Location (lat, long, el): \n            {} deg N, {} deg E, {} Km,\n        Elevation Mask: {} deg\n        Measurement Covariance: {}\n        ==================================================\n        \"\"\".format(\n            self.stn_name,\n            self.stn_id,\n            self.pos,\n            self.lat,\n            self.long,\n            self.el,\n            self.el_mask,\n            self.cov,\n        )\n\n        return string\n\n    def gen_msr(self, sc_state, time, msr_type=\"R3Msr\"):\n        \"\"\"Generates a measurement if the spacecraft is visible\n\n        Args:\n            sc_state (np.ndarray): spacecraft state vector, pos, vel must be first 6 terms\n            time (float): time since reference epoch\n            msr_type (str): name of measurement to use (default = R3 (range and range rate))\n\n        Returns:\n            tuple(bool, float, np.ndarray)\n\n        \"\"\"\n        valid, el, stn_state = self._check_elevation(sc_state, time)\n        if valid:\n            return globals()[msr_type].from_stn(\n                time, sc_state, stn_state, self.stn_id, self.cov\n            )\n        else:\n            return None\n\n    def _check_elevation(self, sc_state, time):\n        \"\"\"Checks to see if the spacecraft is visible\n\n        Args:\n            sc_state (np.ndarray): spacecraft state vector, pos, vel must be first 6 terms\n            time (float): time since reference epoch\n\n        Returns:\n            tuple(bool, float, np.ndarray)\n\n        \"\"\"\n        stn_state_ns = self.state(time, include_shift=False)\n        stn_state_shift = stn_state_ns + np.array([self.mu, 0.0, 0.0, 0.0, 0.0, 0.0])\n        line_o_sight = sc_state[0:3] - stn_state_shift[0:3]\n        num = np.dot(stn_state_ns[0:3], line_o_sight)\n        denom = np.linalg.norm(stn_state_ns[0:3]) * np.linalg.norm(line_o_sight)\n        zenel = np.arccos(num / denom)\n        el = np.pi / 2 - zenel\n\n        if el > np.deg2rad(self.el_mask):\n            flag = True\n        else:\n            flag = False\n\n        return (flag, el, stn_state_shift)\n\n    def state(self, time_nd, include_shift=True):\n        \"\"\"Finds the station state in ECI at a given nondimensional CR3BP time\n\n        Args:\n            time_nd (float): non-dimensional CR3BP time past reference epoch\n\n        Returns:\n            np.ndarray([1x6])\n\n        \"\"\"\n        rot_mat_ecef_eci = ecef_to_eci_nd(time_nd)\n        rot_mat_eci_cr3bp = eci_to_cr3bp(time_nd)\n        pos_eci = rot_mat_ecef_eci @ self.pos\n        pos_cr3bp = rot_mat_eci_cr3bp @ pos_eci\n        \n        if include_shift:\n            pos_cr3bp = pos_cr3bp + np.array([self.mu, 0.0, 0.0])\n\n        vel_ecef = np.cross(EARTH_ANG_VEL_ND.T, self.pos.T).T\n        vel_eci = rot_mat_ecef_eci @ vel_ecef\n        vel_cr3bp_no_cr3bp_and_vel = rot_mat_eci_cr3bp @ vel_eci\n        coriolis = np.cross(CR3BP_ANG_VEL.T, pos_cr3bp.T).T\n        vel_cr3bp = vel_cr3bp_no_cr3bp_and_vel + coriolis\n\n        state = np.concatenate((pos_cr3bp.T[0], vel_cr3bp.T[0]))\n\n        return state\n\n\ndef lat_long_to_ecef(latitude, longitude, elevation):\n    \"\"\"Converts from latituted-longitude to cartesian position in ECEF\n    Note: Assumes location is on the surface of the earth and uses a spherical\n        earth model\n\n    Args:\n        latitude (float): latitude to convert (in degrees)\n        longitude (float): longitude to convert (in degrees)\n        elevation (float): elevation above spherical model (in km)\n\n    Returns:\n       np.ndarray([3x3])\n\n    \"\"\"\n    phi = np.deg2rad(latitude)\n    lam = np.deg2rad(longitude)\n\n    pos_ecef = (R_E + elevation) * np.array(\n        [[np.cos(phi) * np.cos(lam)], [np.cos(phi) * np.sin(lam)], [np.sin(phi)]]\n    )\n\n    return pos_ecef\n\n\ndef ecef_to_eci_nd(time_nd, theta_0=THETA_0):\n    \"\"\"Calculates rotation matrix to ECI at a given time\n    Args:\n       time_nd (float): nondimensional time since reference epoch\n       theta_0 (float): initial rotation of the earth at the reference epoch\n            [default=filtering.THETA_0]\n    Returns:\n       np.ndarray([3x3])\n    \"\"\"\n    alpha = theta_0 + time_nd * W_E_ND\n    rot_mat = np.array(\n        [\n            [np.cos(alpha), -np.sin(alpha), 0],\n            [np.sin(alpha), np.cos(alpha), 0],\n            [0, 0, 1],\n        ]\n    )\n\n    return rot_mat\n\n\ndef eci_to_cr3bp(time_nd):\n    \"\"\"Calculates rotation matrix from ECI to CR3BP at a given nondimensional time\n\n    Args:\n       time_nd (float): nondimensional time since reference epoch\n\n    Returns:\n       np.ndarray([3x3])\n\n    \"\"\"\n    axis_north_pole = np.array([\n        np.sin(-E_M_OFFSET_ANGLE) * np.cos(time_nd * OMEGA_CR3BP), \n        np.sin(-E_M_OFFSET_ANGLE) * np.sin(time_nd * OMEGA_CR3BP), \n        np.cos(-E_M_OFFSET_ANGLE)\n    ])\n    z_axis = np.array([0.0, 0.0, 0.1])\n    rot = rotate_plane(z_axis, axis_north_pole)\n\n    return rot\n\n\ndef unitcross(a, b): \n    c = np.cross(a, b)\n    return c / norm(c)\n\ndef costheta(a, b): \n    return np.dot(a, b) / (norm(a) * norm(b))\n\ndef rotate_plane(M, N): \n    (x, y, z) = unitcross(M, N)\n    c = costheta(M, N)\n    s = np.sqrt(1-c*c)\n    C = 1-c\n    rmat = np.array(\n        [\n            [ x * x * C + c, x * y * C - z * s, x * z * C + y * s],\n            [ y * x * C + z * s, y * y * C + c, y * z * C - x * s],\n            [ z * x * C - y * s, z * y * C + x * s, z * z * C + c]\n        ]\n    )\n\n    return rmat", "meta": {"hexsha": "82e2871d52273b0825919c79d36677422e7324fd", "size": 8365, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/simulation/stations.py", "max_stars_repo_name": "mellemahp/cr3bp_nav", "max_stars_repo_head_hexsha": "9321cfbcc57b20171777897951822edd9d543bd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simulation/stations.py", "max_issues_repo_name": "mellemahp/cr3bp_nav", "max_issues_repo_head_hexsha": "9321cfbcc57b20171777897951822edd9d543bd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simulation/stations.py", "max_forks_repo_name": "mellemahp/cr3bp_nav", "max_forks_repo_head_hexsha": "9321cfbcc57b20171777897951822edd9d543bd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8448275862, "max_line_length": 100, "alphanum_fraction": 0.5655708308, "include": true, "reason": "import numpy,from numpy", "num_tokens": 2202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.36658972248186006, "lm_q1q2_score": 0.19330881796581478}}
{"text": "#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n\r\n\r\n################################################## ##############################\r\n#########################  List of implemented limits  #########################\r\n######################### ######################### #############################\r\n\r\n### Define a class to store all the relevant data about the external limits \r\n### as well as the way of recasting them to the fermion portal case. Then loads all the implemented exeternal limits\r\n\r\n\r\n### L. Darme, S. Ellis, T. You, 29/12/2019\r\n\r\n\r\n\r\n\r\n############################ Messy library import part #########################\r\nimport numpy as np\r\n\r\n# Importing the other sub-Modules\r\n\r\nimport UsefulFunctions as uf\r\nimport Production as br\r\nimport Detection as de\r\n\r\nverbose=True\r\n\r\n\r\nclass Limit:\r\n    \"\"\"\r\n    Contain the informations to recast a given experimental limit\r\n    \r\n    exp:     The experiment associated to the limit\r\n    \r\n    channel: The type of limit (e.g MissingE, Decay ...)\r\n    \r\n    descr:   Any relevant additional details on the limit \r\n    \r\n    ref:     The Inspire reference for the limit\r\n    \r\n    mx_ini:  The range of Mx value on which the limit is relevant (by convention \r\n             this is typically the mass of the lower state X1 in case there is\r\n             two dark sector states, such as for decay limits)\r\n             \r\n    lim_ini: The actual limit (typically from a dark photon model)\r\n    \r\n    lim_inilist: Dictionnary with the initial limits stored in (mx, lim) list for different operator in case they exist ( \"V\" and \"AV\")\r\n    \"\"\"\r\n\r\n    def __init__(self, name, exp, channel, Delini,interptype=\"log\"):\r\n        self.exp = exp\r\n        self.channel = channel\r\n        self.delini = Delini\r\n        self.descr = \"No description for this limit\"\r\n        self.ref = \"No reference for this limit\"\r\n        self.combthr=1.1 # Standard value used when relevant to combine the upper and lower limit      \r\n        try: \r\n            self.name = name\r\n            self.mx_ini, self.lim_ini = uf.LoadData('LimData/'+name+'.dat',interptype)   \r\n#             if verbose: print(\"Loading: \",  self.name,self.lim_ini   )             \r\n        except: \r\n            self.name = \"NotDefined\"\r\n            self.mx_ini = np.logspace(-3., 1., 30.)\r\n            self.lim_ini = np.zeros(np.shape(self.mx_ini ))    \r\n\r\n        try: \r\n            self.model = model\r\n        except: \r\n            self.model = \"No model for this limit\"\r\n  \r\n        self.lim_inifull = {\"V\":(self.mx_ini,self.lim_ini),\"AV\":(self.mx_ini,self.lim_ini)}\r\n    \r\n    def UpdateLimIni(self,mx,lim,optype=\"V\"): \r\n#         print(optype,(mx,lim)) \r\n        self.lim_inifull.update({optype:(mx,lim)})\r\n        if optype==\"V\":\r\n            self.lim_ini = lim\r\n            self.mx_ini = mx\r\n            \r\n        \r\n    def recast(self,delrec, geff, optype,useHeavyMeson=False):\r\n        # we define the recast based on the expected signal\r\n        \r\n        if self.channel == \"decay\":\r\n            if self.model == \"EFT\": # For naive NoE based limits\r\n                xi,EffLimtmp = de.GetNaiveDecayLimits( delrec,  self.exp ,10,geff,optype)\r\n                xi,EffLim,EffLim_low = de.RecastDecayLimit(xi, EffLimtmp, delrec,delrec,self.exp,geff,optype)\r\n                xi_full, Lim_full=uf.CombineUpDown(xi,EffLim_low,EffLim,self.combthr)        \r\n            else: # Standard recasting case\r\n                xi_full, Lim_full=de.FastDecayLimit(self.exp,self.mx_ini, self.lim_ini , self.delini, delrec, geff, optype,self.combthr,useHeavyMeson)\r\n        elif self.channel == \"heavymesondecay\": \r\n            if self.model == \"EFT\":\r\n                xi,EffLimtmp = de.GetNaiveDecayLimits( delrec, self.exp ,10,geff,optype,True)\r\n                xi_heavy,EffLim_heavy,EffLim_heavy_low = de.RecastDecayLimit(xi,EffLimtmp , delrec,delrec,self.exp,geff,optype,True)\r\n                xi_full, Lim_full=uf.CombineUpDown(xi_heavy,EffLim_heavy_low,EffLim_heavy,self.combthr)\r\n            else:\r\n                xi_full, Lim_full=de.FastDecayLimit(self.exp,self.mx_ini, self.lim_ini , self.delini, delrec, geff, optype,self.combthr,useHeavyMeson)\r\n        elif self.channel==\"scattering\":\r\n            xi_full, Lim_full=de.FastScatLimit(self.exp,self.mx_ini, self.lim_ini , self.delini,delrec, geff, optype)\r\n        elif self.channel==\"monogam\":\r\n            xi_full, Lim_full=de.FastMonoPhoton(self.exp,self.mx_ini, self.lim_ini , self.delini,delrec, geff, optype)\r\n        elif self.channel==\"invisibledecayBmtoKm\":\r\n            if self.exp == \"babar\":\r\n                xi_full, Lim_full=  de.FastInvMesDecay(\"babar_BmtoKmnunu\",delrec, geff, optype)\r\n            elif self.exp == \"belle2\":\r\n                xi_full, Lim_full=  de.FastInvMesDecay(\"belle2_BmtoKmnunu\",delrec, geff, optype)\r\n        elif self.channel==\"invisibledecayBmtoPim\":\r\n            xi_full, Lim_full=  de.FastInvMesDecay(\"babar_BmtoPimnunu\",delrec, geff, optype)\r\n        elif self.channel == \"invisibledecayB0toPi0\":\r\n            xi_full, Lim_full=  de.FastInvMesDecay(\"belle_B0toPi0nunu\",delrec, geff, optype)\r\n        elif self.channel == \"invisibledecayB0toK0\":\r\n            xi_full, Lim_full=  de.FastInvMesDecay(\"belle_B0toK0nunu\",delrec, geff, optype)\r\n        elif self.channel==\"monojet_down\":\r\n            xi_full, Lim_full = de.FastMonoJet(self.exp,self.mx_ini, self.lim_ini , self.delini,delrec, geff, optype)\r\n        elif self.channel==\"monojet_up\":\r\n            xi_full, Lim_full = de.FastMonoJet(self.exp,self.mx_ini, self.lim_ini , self.delini,delrec, geff, optype)\r\n        elif self.channel == \"invisibledecayKL0toPi0\":\r\n            if self.exp == \"e391a\":\r\n                xi_full, Lim_full=  de.FastInvMesDecay(\"e391a_KL0toPi0nunu\",delrec, geff, optype)\r\n            if self.exp == \"na62\":\r\n                xi_full, Lim_full=  de.FastInvMesDecay(\"na62_KL0toPi0nunu\",delrec, geff, optype)\r\n        elif self.channel == \"invisibledecayPi0\":\r\n            xi_full, Lim_full=  de.FastInvMesDecay(\"na62_pi0toinvisible\",delrec, geff, optype)\r\n        elif self.channel == \"invisibledecayJPsi\":\r\n            xi_full, Lim_full=  de.FastInvMesDecay(\"bes_JPsitoinvisible\",delrec, geff, optype)\r\n        elif self.channel == \"invisibledecayUpsilon\":\r\n            xi_full, Lim_full=  de.FastInvMesDecay(\"babar_Upsilontoinvisible\",delrec, geff, optype)   \r\n        elif self.channel == \"invisibledecayKptoPip\":\r\n            if self.exp == \"na62\":\r\n                xi_full, Lim_full=  de.FastInvMesDecay(\"na62_KptoPipa\",delrec, geff, optype)  \r\n            elif self.exp == \"e949\":\r\n                xi_full, Lim_full=  de.FastInvMesDecay(\"e949_KptoPipa\",delrec, geff, optype)  \r\n        elif self.channel == \"cosmicrays\":\r\n            xi_full, Lim_low_full, Lim_high_full = de.FastCRLimit(\"t2k\", delrec, geff,optype)\r\n            xi_full, Lim_full = uf.CombineUpDown(xi_full, Lim_low_full, Lim_high_full)\r\n        elif self.channel == \"low_cooling\":  \r\n            xi_full, Lim_full= de.FastSN1987Limit(self.lim_inifull ,delrec, geff, optype,False)\r\n        elif self.channel == \"high_cooling\": \r\n            xi_full, Lim_full= de.FastSN1987Limit( self.lim_inifull ,delrec, geff, optype,True)\r\n        else:\r\n            print(\"Channel selected: \", self.channel, \" is not currently implemented. Possible choices: \\n\",\r\n            \"'decay' : faser, mathusla, ship, charm, seaquest, seaquest_Phase2, lsnd \\n\",\r\n            \"heavymesondecay : ship\"\r\n            \"'scattering' :  nova, miniboone, sbnd \\n\",\r\n            \"'missingE' : babar, belleII, atlas, lep \\n\",\r\n             \"'cosmicrays' : t2k (decay from cosmic ray showers into t2k), \",\r\n             \"cooling : for sn1987_low (pessimistic limit from SN1987 cooling), sn1987_high (optimistic limit from SN1987 cooling) \",\r\n             \"Invisible light meson decays: na62 (pi0decay and invisibledecayKptoPip) e949 (pi0decay and invisibledecayKptoPip), e391a (invisibledecayKL0toPi0)\",\r\n             \"Invisible heavy meson decay: belle (invisibledecayB0toPi0 ,invisibledecayB0toK0) and belleII (invisibledecayBmtoKm)\")\r\n            xi_full= np.logspace(-3., 1., 30.);\r\n            Lim_full =np.zeros(np.shape(xi_full))   \r\n        return xi_full,Lim_full  \r\n\r\nAllLimits={} # Dictionnary for all the limits\r\n \r\ndef UpdateLimitList(limit,name=\"noname\"):\r\n    \r\n    if name==\"noname\":\r\n        name=limit.exp+ \"_\"+limit.channel # We fill up the name automatically if not given\r\n\r\n    if name in AllLimits: # Making a new limits if one already existing for the same \r\n#         print(\"Test:\", name, AllLimits)\r\n        i = 1\r\n        name_new=name+\"_\"+str(i)\r\n        while (name_new in AllLimits):\r\n            i += 1\r\n            name_new=name+\"_\"+str(i)\r\n        name=name_new\r\n    AllLimits.update({name:limit})\r\n\r\n\r\n## This function runs over a list of experiments and search channels,\r\n## compute the recasted bound, print it to file and return everything in a dictionnary with a list of label\r\n## Note that it can also just read an external file and use it directly as the limit\r\n\r\ndef GetLimits(LimList,Del,geff,optype=\"V\",PrintToFile = False, ReadFromFile=False, filename=''):\r\n    \r\n    Res = {}\r\n    LabelLimit = []\r\n\r\n    # Making sure the  input for the effective couplings is okay\r\n    if type(geff) is dict:\r\n        ge=geff\r\n    else:\r\n        if np.ndim(geff[0]) >0:\r\n            geffdiag=(geff[0][0][0],geff[1][0][0],geff[2][0][0])  \r\n            gMesDecay=(geff[1][2][1],geff[1][2][1],geff[1][2][0],geff[1][2][0],geff[1][1][0],geff[1][1][0]) # gd32, gd32,gd31,gd31,gd21,gd21\r\n        else:\r\n            geffdiag=  geff\r\n            gMesDecay=(0,0,0,0,0,0)\r\n        ge={\"gu11\":geffdiag[0],\"gd11\":geffdiag[1],\"gl11\":geffdiag[2],\"gl22\":geffdiag[2] \\\r\n        ,\"gd32\":gMesDecay[0],\"gd31\":gMesDecay[2],\"gd21\":gMesDecay[4]}#We make the couping a dictionnary to have more freedom\r\n\r\n    resultsDict = {} #e.g. {\"exp1_channel1\":(mxlist, limlist), \"exp2_channel2\":{mxlist, limlist}, ... }\r\n    expchannelList = [] #e.g. [\"exp1_channel1\", \"exp2_channel2\", etc.]\r\n\r\n    for expchannel in LimList: \r\n        if not expchannel in AllLimits:\r\n            print( \"Selected limit \" + expchannel +\" not available, choose from: \", AllLimits.keys())\r\n#             raise Exception()\r\n        else:\r\n            if ReadFromFile: \r\n                if filename == '': \r\n                    filestr = 'Output/Lim_'+expchannel+\".dat\"\r\n                else:\r\n                    filestr = filename\r\n                filedat = np.loadtxt(filestr)\r\n                Mx, LamLim = np.transpose(filedat)\r\n            else: \r\n                #print(exp, channel)\r\n    \r\n                Mx, LamLim = AllLimits[expchannel].recast(Del,ge,optype)\r\n                \r\n    \r\n            expchannelList.append(expchannel)\r\n            resultsDict[expchannel] = (Mx,LamLim)\r\n    \r\n            if PrintToFile:\r\n                if filename == '':\r\n                    filestr = 'Output/Lim_'+expchannel+\".dat\"\r\n                else: \r\n                    filestr = filename\r\n                np.savetxt(filestr, np.transpose(resultsDict[expchannel]))\r\n\r\n    return resultsDict, expchannelList  \r\n        \r\n\r\n\r\n################################################## #########################\r\n#########################                           #########################\r\n#########################  Loading external limits  #########################\r\n#########################                           #########################\r\n######################### ######################### #########################\r\n\r\ngeffem={\"gu11\":2/3.,\"gd11\":-1/3.,\"gl11\":-1.}\r\n\r\nprint(\"Loading limits:\")\r\n\r\n#########################  Scattering #########################\r\nif verbose: print(\"Scattering ...\")\r\n\r\nminiboone_scattering=Limit(\"miniboone_1807.06137\",\"miniboone\",\"scattering\",0.)\r\nminiboone_scattering.descr=\"\"\"\r\nLimits from MiniBooNE collaboration for light dark matter scattering, produced at the beam dump. \r\n\r\nExtracted from Figure 24.a, the data is given as epsilon^2, for alpha_D = 0.5, \r\nwe rescale it by 5 ^1/4. since the scattering limit scale as eps^4 alpha_D\r\n\"\"\"\r\nminiboone_scattering.ref=\"inspirehep.net/record/1682906\"\r\nminiboone_scattering.UpdateLimIni(miniboone_scattering.mx_ini,np.sqrt(miniboone_scattering.lim_ini)*np.power(5,1/4.) )\r\nUpdateLimitList(miniboone_scattering)\r\n\r\n############\r\n\r\nsbnd_scattering=Limit(\"sbnd_1609.01770\",\"sbnd\",\"scattering\",0.)\r\nsbnd_scattering.descr=\"\"\"\r\nProjective Limits from SBND collaboration for light dark matter scattering\r\nproduced by 1609.01770, for 2. * 10^20  PoT, based on 10 events reach\r\n\r\nExtracted from Figure 9.b, the data is given as epsilon^2, for alpha_D = 0.5\r\n\"\"\"\r\nsbnd_scattering.ref=\"inspirehep.net/record/1485563\"\r\nsbnd_scattering.UpdateLimIni(sbnd_scattering.mx_ini,np.sqrt(sbnd_scattering.lim_ini)*np.power(5,1/4.) )\r\nUpdateLimitList(sbnd_scattering)\r\n\r\n############\r\n\r\nship_scattering=Limit(\"ship_1609.01770\",\"ship\",\"scattering\",0.)\r\nship_scattering.descr=\"\"\"\r\nProjective limits from SHIP collaboration for light dark matter scattering,\r\nproduced by  1609.01770, for 2. * 10^20  PoT, based on 10 events reach\r\n\r\nExtracted from Figure 24.a, the data is given as epsilon^2, for alpha_D = 0.5\r\n\"\"\"\r\nship_scattering.ref=\"inspirehep.net/record/1485563\"\r\nship_scattering.UpdateLimIni(ship_scattering.mx_ini,np.sqrt(ship_scattering.lim_ini)*np.power(5,1/4.) )\r\nUpdateLimitList(ship_scattering)\r\n\r\n\r\n############\r\n\r\nnova_scattering=Limit(\"nova_1807.06501\",\"nova\",\"scattering\",0.)\r\nnova_scattering.descr=\"\"\"\r\nLimit produced by 1807.06501 based on NOvA collaboration neutrino-electron scattering \r\nin 1710.03428, recasted for light dark matter scattering for 2.97 * 10^20  PoT.\r\nThis is not a projection, limit for 58 events, although the authors of 1807.06501 merely\r\ncall for a full analysis by the collaboration\r\n\r\nExtracted from Figure 2, with alpha_D = 0.05, the data is given as y = eps^2 * alpha_D *(mx/ mv)^4= 0.00062 eps^2\r\n\"\"\"\r\nnova_scattering.ref=\"inspirehep.net/record/1682772\"\r\n# print(\"nova\",nova_scattering.mx_ini,nova_scattering.lim_ini)\r\nnova_scattering.UpdateLimIni(nova_scattering.mx_ini,np.sqrt(nova_scattering.lim_ini)/np.sqrt(0.00062)/np.power(2,1/4.) )\r\nUpdateLimitList(nova_scattering)\r\n# print(\"nova2\",nova_scattering.mx_ini,nova_scattering.lim_ini)\r\n\r\n#########################  Long-lived particles #########################\r\nif verbose: print(\"Long-lived dark sector ...\")\r\n\r\n############ Based on: Kling, 2018 MATHUSLA\r\n\r\nmathusla_decay=Limit(\"mathusla_1810.01879\",\"mathusla\",\"decay\",0.1)\r\nmathusla_decay.descr=\"\"\"\r\nProjective limits for MATHUSLA from 1810.01879, with 3 ab-1 of luminosity from HL-LHC\r\n\r\nEnergy cut > 0.6 GeV\r\n\"\"\"\r\nmathusla_decay.ref=\"inspirehep.net/record/1696950\"\r\nmathusla_decay.combthr=1.2\r\nUpdateLimitList(mathusla_decay)\r\n\r\n############ Based on: Kling, 2018 FASER\r\n\r\nfaser_decay=Limit(\"faser_1810.01879\",\"faser\",\"decay\",0.1)\r\nfaser_decay.descr=\"\"\"\r\nProjective limits for FASER from 1810.01879,  with 3 ab-1 of luminosity from HL-LHC\r\n\r\nEnergy cut > 100 GeV\r\n\"\"\"\r\nfaser_decay.ref=\"inspirehep.net/record/1696950\"\r\nfaser_decay.combthr=1.1\r\nUpdateLimitList(faser_decay)\r\n\r\n\r\n############ Based on: 2018 SeaQuest phase 1 and 2\r\n\r\nseaquest_phase2_decay=Limit(\"seaquest_phase2_1804.00661\",\"seaquest_phase2\",\"decay\",0.1)\r\nseaquest_phase2_decay.descr=\"\"\"\r\nProjective limits 1804.00661 Figure 12, 10 events limits with 5m−6m fiducial decay region Phase 2 with 10^20 PoT\r\n\r\n\"\"\"\r\nseaquest_phase2_decay.ref=\"inspirehep.net/record/1665691\"\r\nUpdateLimitList(seaquest_phase2_decay)\r\n\r\n\r\nseaquest_phase1_decay=Limit(\"\",\"seaquest_phase1\",\"decay\",0.1)\r\nseaquest_phase1_decay.descr=\"\"\"\r\nProjective limit, 1804.00661, rescaled from Figure 12 given the reduced number of PoT: 1.44×10^18 PoT \r\n, 10 events limits with 5m−6m fiducial decay regions \r\n\"\"\"\r\nseaquest_phase1_decay.ref=\"inspirehep.net/record/1665691\"\r\nseaquest_phase1_decay.UpdateLimIni(seaquest_phase1_decay.mx_ini,np.sqrt(seaquest_phase1_decay.lim_ini)/np.power(0.014,1/4.))\r\nUpdateLimitList(seaquest_phase1_decay)\r\n\r\n############ Based on: Izaguiire, 2017 LSND (on-shell pi0 only?)\r\n\r\nlsnd_decay_2=Limit(\"lsnd_1703.06881\",\"lsnd\",\"decay\",0.1)\r\nlsnd_decay_2.descr=\"\"\"\r\nLimits for LSND collaboration, based on  original neutrino scattering search from hep-ex/0104049, \r\nrecasted for iDM in 1703.06881 Fig 6, with splitting 10%\r\n\"\"\"\r\nlsnd_decay_2.ref=\"inspirehep.net/record/1682906\"\r\nUpdateLimitList(lsnd_decay_2,\"lsnd_decay_2\")\r\n\r\n\r\n############  LSND ---- based Darme 2018\r\n \r\nlsnd_decay=Limit(\"lsnd_1807.10314\",\"lsnd\",\"decay\",0.15)\r\nlsnd_decay.descr=\"\"\"\r\nLimits for LSND collaboration, based on  original neutrino scattering search from hep-ex/0104049, \r\nrecasted for iDM in 1807.10314 Fig5a, with splitting 15%\r\n\"\"\"\r\nlsnd_decay.ref=\"inspirehep.net/record/1684267\"\r\nUpdateLimitList(lsnd_decay)\r\n\r\n############  CHARM ---- based Tsai 2019\r\n \r\ncharm_decay=Limit(\"charm_1908.07525\",\"charm\",\"decay\",0.1)\r\ncharm_decay.descr=\"\"\"\r\nLimits for CHARM collaboration, based on  original neutrino scattering search from Phys.Lett. 128B (1983) 361,\r\n recasted for iDM in 1908.07525 Fig1.c\r\n\r\nEcut > 3 GeV\r\n\"\"\"\r\ncharm_decay.ref=\"inspirehep.net/record/1682906\"\r\nUpdateLimitList(charm_decay)\r\n\r\n############  SHIP decay prediction\r\n \r\nship_decay=Limit(\"\",\"ship\",\"decay\",0.1)\r\nship_decay.descr=\"\"\"\r\nNaive limit prediction for SHIP, based on the routine for production and decay implemented in this code.\r\nDoes not include the experimental efficiency. The output is the 10 events line.\r\n\"\"\"\r\nship_decay.ref=\"\"\r\nship_decay.model=\"EFT\"\r\nUpdateLimitList(ship_decay)\r\n\r\nship_heavymesondecay=Limit(\"\",\"ship\",\"heavymesondecay\",0.1)\r\nship_heavymesondecay.descr=\"\"\"\r\nNaive limit prediction for SHIP, based on the routine for production and decay implemented in this code.\r\nDoes not include the experimental efficiency. The output is the 10 events line.\r\nProduction is generated by heavy meson decay\r\n\"\"\"\r\nship_heavymesondecay.ref=\"\"\r\nship_heavymesondecay.model=\"EFT\" # The generated limits are already in the EFT\r\nUpdateLimitList(ship_heavymesondecay)\r\n\r\n#########################  Missing energy searches  #########################\r\nif verbose: print(\"Mono-X searches ...\")\r\n\r\n############  BaBAr  # Based on Essig 2013\r\n\r\nbabar_monogam=Limit(\"babar_1309.5084\",\"babar\",\"monogam\",0.0)\r\nbabar_monogam.descr=\"\"\"\r\nLimits for BaBar collaboration, based on the recasting from 1309.5084 of the upsilon decay \r\nmono-photon search from 0808.0017.\r\n\r\nNotice that the absence of \"bump\" in the reconstructed dark sector invariant mass distribution\r\nsignificantly weakens the reach. Better control of the background could lead to improvement\r\n\"\"\"\r\nbabar_monogam.ref=\"inspirehep.net/record/1254859,inspirehep.net/record/792059\"\r\nUpdateLimitList(babar_monogam)\r\n\r\n############  Belle II  # Based on Essig 2013\r\n\r\nbelle2_monogam=Limit(\"belle2_1309.5084\",\"belle2\",\"monogam\",0.0)\r\nbelle2_monogam.descr=\"\"\"\r\nLimits for Belle II collaboration, based on the proejction from 1309.5084\r\n\r\nNotice that the absence of \"bump\" in the reconstructed dark sector invariant mass distribution\r\nsignificantly weakens the reach. Better control of the background could lead to improvement\r\n\"\"\"\r\nbelle2_monogam.ref=\"inspirehep.net/record/1254859\"\r\nUpdateLimitList(belle2_monogam)\r\n\r\n\r\n#########################  MonoJet searches at ATLAS 35.9 fb-1  #########################\r\ndata =  np.loadtxt('Data/LimData/atlas_1711.03301.dat')\r\nxi_ATLAS = np.abs(data[:,0])\r\nLim_ATLAS_Down = data[:,1]\r\nLim_ATLAS_Up= data[:,2]\r\n\r\natlas_monoXlow=Limit(\"\",\"atlas\",\"monojet_down\",0.0)\r\natlas_monoXlow.descr=\"\"\"\r\nLimits for ATLAS collaboration, 1711.03301 based on the upper recasted limit from 1807.03817 \r\nand our own recast.\r\n\"\"\"\r\natlas_monoXlow.ref=\"inspirehep.net/record/1635274\"\r\natlas_monoXlow.UpdateLimIni(xi_ATLAS,Lim_ATLAS_Down)\r\nUpdateLimitList(atlas_monoXlow)\r\n\r\n\r\natlas_monoXhigh=Limit(\"\",\"atlas\",\"monojet_up\",0.0)\r\natlas_monoXhigh.descr=\"\"\"\r\nLimits for ATLAS collaboration, 1711.03301 based on the upper recasted limit from 1807.03817 \r\nand our own recast.\r\n\"\"\"\r\natlas_monoXhigh.ref=\"inspirehep.net/record/1635274\"\r\natlas_monoXhigh.UpdateLimIni(xi_ATLAS,Lim_ATLAS_Up)\r\nUpdateLimitList(atlas_monoXhigh)\r\n\r\n\r\n#########################  MonoPhoton searches at DELPHI from 1103.0240  #########################\r\n\r\nxi_LimLEP_V,LimLEP_V  = uf.LoadData('LimData/lep_1103.0240_V.dat',\"lin\")\r\nxi_LimLEP_AV,LimLEP_AV  = uf.LoadData('LimData/lep_1103.0240_AV.dat',\"lin\")\r\n\r\nlep_monoX=Limit(\"lep_1103.0240\",\"lep\",\"monogam\",0.0)\r\nlep_monoX.descr=\"\"\"\r\nLimits for LEP collaboration, based on the recasting from 1103.0240 for the upper limit. \r\nThe lower limit is given by the breakdown of the EFT at the LEP CoM energy.\r\n\"\"\"\r\nlep_monoX.ref=\"inspirehep.net/record/890992\"\r\nlep_monoX.UpdateLimIni(xi_LimLEP_V,LimLEP_V)\r\nlep_monoX.UpdateLimIni(xi_LimLEP_AV,LimLEP_AV,\"AV\")\r\nUpdateLimitList(lep_monoX)\r\n\r\n######################### SN1987 cooling rate constraints #####\r\nif verbose: print(\"SN1987 cooling ...\")\r\n\r\nsn1987low_cooling=Limit(\"sn1987low\",\"sn1987\",\"low_cooling\",0.0,\"lin\")\r\nsn1987low_cooling.descr=\"\"\"\r\nLower limit from SN1987 cooling constraints, recasted from ***\r\n\"\"\"\r\nsn1987low_cooling.ref=\"inspirehep.net/record/1682906\"\r\nnewmx=np.power(10.,sn1987low_cooling.mx_ini/1.)\r\nnewlim=np.power(10.,sn1987low_cooling.lim_ini/1.)\r\nsn1987low_cooling.UpdateLimIni(newmx,newlim,\"V\")\r\nsn1987low_cooling.UpdateLimIni(newmx,newlim,\"AV\")\r\nUpdateLimitList(sn1987low_cooling)\r\n# print(sn1987low_cooling.mx_ini,sn1987low_cooling.lim_ini)\r\n\r\n\r\nsn1987high_cooling=Limit(\"sn1987high\",\"sn1987\",\"high_cooling\",0.0,\"lin\")\r\nsn1987high_cooling.descr=\"\"\"\r\nUpper limit from SN1987 cooling constraints, recasted from ***\r\n\r\nIn the case of AV coupling, we use instead the lower limit on the pi0->invisible BR\r\nderived in *** from sn1987 cooling\r\n\"\"\"\r\nsn1987high_cooling.ref=\"inspirehep.net/record/1682906\"\r\nxi_LimSN_AV_up,LamlimSN_AV_up= uf.LoadData('LimData/sn1987_pi0decay.dat',\"log\")\r\nsn1987high_cooling.UpdateLimIni(np.power(10.,sn1987high_cooling.mx_ini/1.),np.power(10.,sn1987high_cooling.lim_ini/1.))\r\nsn1987high_cooling.UpdateLimIni(xi_LimSN_AV_up,LamlimSN_AV_up,\"AV\")\r\nUpdateLimitList(sn1987high_cooling)\r\n\r\n# print(sn1987high_cooling.mx_ini,sn1987high_cooling.lim_ini)\r\n\r\n#########################  Invisible decay of pi0  #################\r\n\r\nif verbose: print(\"Invisible meson decay ...\")\r\n\r\nna62_invisibledecayPi0=Limit(\"na62_talkKaon2019\",\"na62\",\"invisibledecayPi0\",0.0)\r\nna62_invisibledecayPi0.descr=\"\"\"\r\nLimits for invisible decay branching ratio of pi0 meson as constrained by the NA62 collaboration\r\n\r\nCurrently value only from https://indico.cern.ch/event/769729/sessions/318725/ Ruggiero's talk\r\nBR < 4.4 10^-9 at 90% CL\r\n\"\"\"\r\nna62_invisibledecayPi0.ref=\"indico.cern.ch/event/769729/contributions/3510938/attachments/1905346/3146619/kaon2019_ruggiero_final.pdf\"\r\nUpdateLimitList(na62_invisibledecayPi0)\r\n\r\n#########################  Invisible decay of heavy mesons  #################\r\nif verbose: print(\"Invisible heavy meson decay ...\")\r\n\r\nbabar_invisibledecayBmtoKm=Limit(\"babar_invisibledecayBmtoKm\",\"babar\",\"invisibledecayBmtoKm\",0.0)\r\nbelle2_invisibledecayBmtoKm=Limit(\"belle2_invisibledecayBmtoKm\",\"belle2\",\"invisibledecayBmtoKm\",0.0)\r\nbelle_invisibledecayB0toPi0=Limit(\"belle_invisibledecayB0toPi0\",\"belle\",\"invisibledecayB0toPi0\",0.0)\r\nbelle_invisibledecayB0toK0=Limit(\"belle_invisibledecayB0toK0\",\"belle\",\"invisibledecayB0toK0\",0.0)\r\nbabar_invisibledecayBmtoPim=Limit(\"babar_invisibledecayBmtoPim\",\"babar\",\"invisibledecayBmtoPim\",0.0)\r\ne391a_invisibledecayKL0toPi0=Limit(\"e391a_invisibledecayKL0toPi0\",\"e391a\",\"invisibledecayKL0toPi0\",0.0)\r\nna62_invisibledecayKL0toPi0=Limit(\"na62_invisibledecayKL0toPi0\",\"na62\",\"invisibledecayKL0toPi0\",0.0)\r\ne949_invisibledecayKptoPip=Limit(\"e949_invisibledecayKptoPip\",\"e949\",\"invisibledecayKptoPip\",0.0)\r\nna62_invisibledecayKptoPip=Limit(\"na62_invisibledecayKptoPip\",\"na62\",\"invisibledecayKptoPip\",0.0)\r\n\r\n\r\nbes_invisibledecayJPsi=Limit(\"bes_invisibledecayJPsi\",\"bes\",\"invisibledecayJPsi\",0.0)\r\nbes_invisibledecayJPsi.descr=\"Limit BR JPSi-> inv < 7.2 * 10^-4 from BES collaboration  0710.0039\"\r\n\r\nbabar_invisibledecayUpsilon=Limit(\"babar_invisibledecayUpsilon\",\"babar\",\"invisibledecayUpsilon\",0.0)\r\nbabar_invisibledecayUpsilon.descr=\"Limit BR Upsilon-> inv < 3.0 * 10^-4 from BABAR collaboration  0908.2840\"\r\n\r\n\r\nUpdateLimitList(babar_invisibledecayBmtoKm);UpdateLimitList(belle2_invisibledecayBmtoKm);UpdateLimitList(belle_invisibledecayB0toPi0);\r\nUpdateLimitList(belle_invisibledecayB0toK0);UpdateLimitList(babar_invisibledecayBmtoPim);\r\nUpdateLimitList(e391a_invisibledecayKL0toPi0);UpdateLimitList(na62_invisibledecayKL0toPi0);\r\nUpdateLimitList(e949_invisibledecayKptoPip);UpdateLimitList(na62_invisibledecayKptoPip)\r\nUpdateLimitList(bes_invisibledecayJPsi);UpdateLimitList(babar_invisibledecayUpsilon)\r\n\r\n\r\n\r\n######################### CR limits at T2K ################# Currently not used\r\n# if verbose: print(\"Decay from CR production limits ...\")\r\n# \r\n# t2k_cosmicrays=Limit(\"t2k_cosmicrays\",\"t2k\",\"cosmicrays\",0.0)\r\n# t2k_cosmicrays.descr=\"\"\"\r\n# Projections from T2K limits based on cosmic ray production of dark sector states\r\n# limits for 500 number of signal events per year, neutrino background for superK is ~150\r\n# \r\n# \"\"\"\r\n# UpdateLimitList(t2k_cosmicrays)\r\n\r\n", "meta": {"hexsha": "10afc91154443609bb743af325d484164c1dafad", "size": 25197, "ext": "py", "lang": "Python", "max_stars_repo_path": "LimitsList.py", "max_stars_repo_name": "Luc-Darme/DarkEFT", "max_stars_repo_head_hexsha": "f4be14742ced9a1447dbcab40a6c7b18e61cb001", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LimitsList.py", "max_issues_repo_name": "Luc-Darme/DarkEFT", "max_issues_repo_head_hexsha": "f4be14742ced9a1447dbcab40a6c7b18e61cb001", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LimitsList.py", "max_forks_repo_name": "Luc-Darme/DarkEFT", "max_forks_repo_head_hexsha": "f4be14742ced9a1447dbcab40a6c7b18e61cb001", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-09T06:43:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-09T06:43:46.000Z", "avg_line_length": 45.3183453237, "max_line_length": 162, "alphanum_fraction": 0.6680160337, "include": true, "reason": "import numpy", "num_tokens": 7205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.19322385642982773}}
{"text": "import numpy as np\nfrom astropy.cosmology import FlatwCDM\nfrom astropy.cosmology import w0waCDM\nfrom astropy.cosmology import FlatLambdaCDM\nfrom astropy.cosmology import LambdaCDM\nimport matplotlib.pyplot as plt\nfrom astropy import cosmology as cosmo\nimport wmom as wmom\nimport matplotlib\nimport linef\nimport matplotlib\nimport plotsetup\nfrom matplotlib import gridspec\nimport matplotlib.ticker as ticker\nplotsetup.halfpaperfig()\n\ngs1 = gridspec.GridSpec(1,4)\ngs1.update(bottom=0.6, top=0.95, hspace=0.0)\nax1= plt.subplot(gs1[0])\nax2= plt.subplot(gs1[1])\nax3= plt.subplot(gs1[2])                                                                                 \nax4= plt.subplot(gs1[3])\n\ngs1 = gridspec.GridSpec(1,4)\ngs1.update(bottom=0.34, top=0.57, hspace=0.0)\nax5= plt.subplot(gs1[0])\nax6= plt.subplot(gs1[1])\nax7= plt.subplot(gs1[2])\nax8= plt.subplot(gs1[3])\n\ngs1 = gridspec.GridSpec(1,4)\ngs1.update(bottom=0.1, top=0.31, hspace=0.0)\nax9= plt.subplot(gs1[0])\nax10= plt.subplot(gs1[1])\nax11= plt.subplot(gs1[2])\nax12= plt.subplot(gs1[3])\n\n#ax13= plt.subplot(gs1[1,0])\n#ax14= plt.subplot(gs1[1,1])\n#ax15= plt.subplot(gs1[1,2])\n#ax16= plt.subplot(gs1[1,3])\n\nax=[ax1,ax2,ax3,ax4,ax5,ax6,ax7,ax8,ax9,ax10,ax11,ax12]\nran=[0.04,0.04,0.04,0.04,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02]\nheadn=linef.linef('../DATA/SALT2mu_SNLS+SDSS+LOWZ+PS1_Scolnic2+HST/DS17/SALT2mu_FITOPT'+str('000')+'_MUOPT'+str('000')+'.M0DIF','VARN')\nz1,mures, murese = np.loadtxt('../DATA/SALT2mu_SNLS+SDSS+LOWZ+PS1_Scolnic2+HST/DS17/SALT2mu_FITOPT'+str('000')+'_MUOPT'+str('000')+'.M0DIF', usecols=(4,5,6), unpack=True, dtype='string', skiprows=headn+1)\nz1 = z1.astype(float)\nmures1 = mures.astype(float)\nmurese1 = murese.astype(float)\n\n\n#FITOPT: color #GLOBAL GROUP 1\n#FITOPT: massstep #GLOBAL GROUP 1\n#FITOPT: massevol #GLOBAL GROUP 1\n#FITOPT: colorevol #GLOBAL GROUP 1\n\n\n#p1=plt.errorbar(z1, mures, yerr=murese, fmt='ko', ecolor='black', color='black',label='D15 Data')\n#xp=[0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3]\n#yp=[0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3]\n#syslabel=['SALT2 Cal','Beta Evol.','Intr Scat.','Selection',\n# 'MW Ext.','Mass Split','Mass Evol.','Pec. Vel.',\n#          'HST Cal', 'SDSS g','PS1 r','SNLS i','Supercal', 'SDSS r','PS1 i','SNLS z']\n#r'$\\beta$'+' Evol. & '\n#$\\gamma$'+' Evol. & '\n#$m_{\\rm step}$'+'Shift\n\nsyslabel=['SALT2 Cal',r'$\\mathbf{\\beta}$'+' Evol. ','Intr Scat.','Selection',\n 'MW Ext.',r'$\\mathbf{ m_{\\rm step}}$'+' Shift',r'$\\mathbf{\\gamma}$'+' Evol. ','Pec. Vel.',\n          'HST Cal', 'Supercal','PS1 r','SNLS i'];#,'Supercal', 'SDSS r','PS1 i','SNLS z']\n\n#sysnum1=['001','012','000','000','011','000','000','013','012','015','037','046','084','016','038','047']\n#sysnum2=['000','000','001','002','000','006','011','000','000','000','000','000','000','000','000','000']\n#weights=[1,1,0.5,1,\n#         1,1,1,1,\n#         1,.5,.3,.5,.5,.5,.5,.5]\nsysnum1=['001','012','000','000','011','000','000','013','012','084','037','046']\nsysnum2=['000','000','001','002','000','006','011','000','000','000','000','000']\nweights=[1,0.5,0.5,1,\n                  1,1,1,1,\n                  1,.5,.3,.5]\n\n#sysnum=[1,84,85,86,\n# 11,83,13,11,\n#        28,15,37,50,29,16,38,51]\n#sysnum=[1,11,12,86,83,84,85,15,28,37,51]\n#syslabel=['SALT2 Cal','MW Ext','HST Cal','Int. Scat','Mass Split','Mass Evol','Color Evol','SDSS g','CSP B','PS1 r', 'SNLS z']\nprint len(sysnum1)\n#stop\nfor x in range(0,len(sysnum1)):\n    z2,mures2, murese2 = np.loadtxt('../DATA/SALT2mu_SNLS+SDSS+LOWZ+PS1_Scolnic2+HST/DS17/SALT2mu_FITOPT'+str(sysnum1[x])+'_MUOPT'+str(sysnum2[x])+'.M0DIF', usecols=(4,5,6), unpack=True, dtype='string', skiprows=headn+1)\n    z2 = z2.astype(float)\n    mures2 = mures2.astype(float)\n    murese2 = murese2.astype(float)\n\n    ax[x].errorbar(z1, (mures1-mures2)*weights[x], yerr=murese2*0, fmt='go', ecolor='g', alpha=.95)\n    ax[x].set_ylim(-ran[x]*.99,ran[x]*.99)\n    ax[x].set_xlim(0.005,1.7)\n    ax[x].set_xscale('log')\n    line, = ax[x].plot(np.arange(0,2,.1), np.arange(0,2,.1)*0.0, lw=2)\n    if (x<8): ax[x].text(.01,-.88*ran[x], syslabel[x],fontdict={'fontsize':10}, color='black')\n    if (x>7): ax[x].text(.01,-.88*ran[x], syslabel[x],fontdict={'fontsize':10}, color='black')\n        \n    ax[x].set_xticks([0.01,0.1,1.0])\n    if (x<4): ax[x].yaxis.set_major_locator(ticker.MultipleLocator(0.02))\n    if (x>3): ax[x].yaxis.set_major_locator(ticker.MultipleLocator(0.01))\n    if (x>7): ax[x].yaxis.set_major_locator(ticker.MultipleLocator(0.01))\n        \n    if ((x!=0)&(x!=4)&(x!=8)&(x!=12)):\n                     ax[x].set_yticklabels(['','','','','','',''])\n    if (x<9):\n         ax[x].set_xticklabels(['','','','',''])\n    if (x>7):\n        ax[x].set_xlabel('z',labelpad=-1)\n        ax[x].set_xticklabels([' 0.01','0.1','1.0  ',''])\n        #ax[x].set_xticklabels(['0.0','','0.5','','1.0'])\n    #if ((x==8)|(x==12)):\n    #    ax[x].set_yticklabels(['','-0.01','0.0','0.01',''])\n    ax[x].tick_params('both', length=2, width=2, which='major')\n    ax[x].tick_params('both', length=0, width=2, which='minor')\n        \n#plt.text(.2,-.13,r'$Omega_M=0.30,\\Omega_{\\Lambda}=.70,w=-1.0$',fontdict={'fontsize':20}, color='black')\n#plt.text(.2,.1,r'$\\Omega_M=0.25,\\Omega_{\\Lambda}=.75,w=-1.0$',fontdict={'fontsize':20}, color='orange')\n#plt.text(.2,.13,r'$\\Omega_M=0.30,\\Omega_{\\Lambda}=.70,w=-1.1$',fontdict={'fontsize':20}, color='red')\n#plt.text(.2,.16,r'$\\Omega_M=0.30,\\Omega_{\\Lambda}=.70,w=-1.0, w_a=-0.1$',fontdict={'fontsize':20}, color='blue')\n\n#ax[1,0].text(-0.3,0.05, 'd(m-M) [Mag]',fontdict={'fontsize':18}, color='black',rotation=90)\n\nax[4].set_ylabel(r'$\\Delta \\mu_{\\rm Sys}  - \\Delta \\mu_{\\rm Baseline} $'+' [mag]',labelpad=-1)\n\n#plt.ylabel('d(m-M) [Mag]', size=24)\n\nplt.show()\nplt.savefig('sysgrid.png')\n#line, = plt.plot(range(1,150)/100.0,5.0*np.log(c1/c2), lw=2,color='red')\n#plt.show()\n#plt.savefig('wdemo1.png')\n", "meta": {"hexsha": "e5ff9b5fdbe50a9d8bcd15f7985c01cc90d02760", "size": 5807, "ext": "py", "lang": "Python", "max_stars_repo_path": "SCRIPTS/sysgrid.py", "max_stars_repo_name": "LBJ-Wade/Pantheon", "max_stars_repo_head_hexsha": "7eb29dc87ba223b4ec8457cd3cccba1216c36fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2018-06-08T01:38:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T14:44:46.000Z", "max_issues_repo_path": "SCRIPTS/sysgrid.py", "max_issues_repo_name": "LBJ-Wade/Pantheon", "max_issues_repo_head_hexsha": "7eb29dc87ba223b4ec8457cd3cccba1216c36fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-03-31T08:26:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-25T11:08:13.000Z", "max_forks_repo_path": "SCRIPTS/sysgrid.py", "max_forks_repo_name": "LBJ-Wade/Pantheon", "max_forks_repo_head_hexsha": "7eb29dc87ba223b4ec8457cd3cccba1216c36fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2018-04-09T12:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T15:51:13.000Z", "avg_line_length": 42.0797101449, "max_line_length": 220, "alphanum_fraction": 0.6063371793, "include": true, "reason": "import numpy,from astropy", "num_tokens": 2293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.33458942798284697, "lm_q1q2_score": 0.19322384876626825}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nr\"\"\"Provide the wrench limits constraint.\n\nThis provides bounds/limits on the wrenches:\n\n.. math::  F_{lb} \\leq F \\leq F_{ub}\n\nwhere :math:`(F_{lb}, F_{ub})` are the lower and upper bound on the wrenches, and\n:math:`F` is the wrench vector being optimized.\n\nThis formulation can be rewritten as the inequality constraint math:`lb \\leq x \\leq ub` in QP, with\n:math:`lb = F_{lb}`, :math:`ub = F_{ub}`, and :math:`x = F`. This can also be rewritten as :math:`Gx \\leq h`,\nwith :math:`G = [-I, I]^\\top` and :math:`h = [-F_{lb}^\\top, F_{ub}^\\top]^\\top` where :math:`I` is the square\nidentity matrix.\n\nThe implementation of this class is inspired by [1] (which is licensed under the LGPLv2).\n\nReferences:\n    - [1] \"OpenSoT: A whole-body control library for the compliant humanoid robot COMAN\", Rocchi et al., 2015\n\"\"\"\n\nimport numpy as np\n\nfrom pyrobolearn.priorities.constraints.constraint import BoundConstraint, ForceConstraint\n\n\n__author__ = \"Brian Delhaisse\"\n__copyright__ = \"Copyright 2019, PyRoboLearn\"\n__credits__ = [\"Enrico Mingo Hoffman (C++)\", \"Brian Delhaisse (Python + doc)\"]\n__license__ = \"GNU GPLv3\"\n__version__ = \"1.0.0\"\n__maintainer__ = \"Brian Delhaisse\"\n__email__ = \"briandelhaisse@gmail.com\"\n__status__ = \"Development\"\n\n\nclass WrenchLimitsConstraint(BoundConstraint, ForceConstraint):\n    r\"\"\"Wrench Limits constraint.\n\n     This provides bounds/limits on the wrenches:\n\n    .. math::  F_{lb} \\leq F \\leq F_{ub}\n\n    where :math:`(F_{lb}, F_{ub})` are the lower and upper bound on the wrenches, and\n    :math:`F` is the wrench vector being optimized.\n\n    This formulation can be rewritten as the inequality constraint math:`lb \\leq x \\leq ub` in QP, with\n    :math:`lb = F_{lb}`, :math:`ub = F_{ub}`, and :math:`x = F`. This can also be rewritten as :math:`Gx \\leq h`,\n    with :math:`G = [-I, I]^\\top` and :math:`h = [-F_{lb}^\\top, F_{ub}^\\top]^\\top` where :math:`I` is the square\n    identity matrix.\n\n    The implementation of this class is inspired by [1] (which is licensed under the LGPLv2).\n\n    References:\n        - [1] \"OpenSoT: A whole-body control library for the compliant humanoid robot COMAN\", Rocchi et al., 2015\n    \"\"\"\n\n    def __init__(self, model, bounds):\n        r\"\"\"\n        Initialize the constraint.\n\n        Args:\n            model (ModelInterface): model interface.\n            bounds (tuple[2 * np.array[float[M]]], np.array[float[M]]): wrench limits, where `M` is 3 (vector of\n              forces) or 6 (vector of forces and torques). If tuple, it is the lower and upper bounds on the wrenches.\n              If np.array, then the lower and upper bound will be set to (-bounds, bounds).\n        \"\"\"\n        super(WrenchLimitsConstraint, self).__init__(model)\n\n        # set variables\n        self.bounds = bounds\n\n        # first update\n        self.update()\n\n    ##############\n    # Properties #\n    ##############\n\n    @property\n    def bounds(self):\n        \"\"\"Get the wrench bounds.\"\"\"\n        return self._bounds\n\n    @bounds.setter\n    def bounds(self, bounds):\n        \"\"\"Set the wrench bounds.\"\"\"\n        if bounds is not None:\n            if isinstance(bounds, tuple):\n                if len(bounds) != 2:\n                    raise ValueError(\"Expecting the bounds to be a tuple of length 2, but got a length of \"\n                                     \"{}\".format(len(bounds)))\n                for i, bound in enumerate(bounds):\n                    if isinstance(bound, (int, float)):\n                        bound = np.ones(3) * bound\n                        bounds[i] = bound\n                    elif isinstance(bound, np.ndarray) and len(bound) != 3:\n                        raise ValueError(\"Expecting the given bound to be of length 3, but instead got a length of \"\n                                         \"{}\".format(len(bound)))\n                    else:\n                        raise TypeError(\"Expecting the given bound to be a np.array, but got instead: \"\n                                        \"{}\".format(type(bound)))\n            elif isinstance(bounds, np.ndarray):\n                bounds = bounds.reshape(-1)\n                if len(bounds) == 3:\n                    bounds = (-bounds, bounds)\n                elif len(bounds) == 6:\n                    bounds = (bounds[:3], bounds[3:])\n                elif len(bounds) == 12:\n                    bounds = (bounds[:6], bounds[6:])\n                else:\n                    raise ValueError(\"Expecting the given bounds to be of length 3 or 6 but got instead a length of: \"\n                                     \"{}\".format(len(bounds)))\n            elif isinstance(bounds, (int, float)):\n                bounds = (-np.ones(3) * bounds, np.ones(3) * bounds)\n            else:\n                raise TypeError(\"Expecting the given bounds to be a tuple of np.array, a np.array, or None, but \"\n                                \"instead got: {}\".format(type(bounds)))\n        self._bounds = bounds\n\n    ###########\n    # Methods #\n    ###########\n\n    def _update(self):\n        \"\"\"Update the lower and upper bounds.\"\"\"\n        self._b_lower_bound, self._b_upper_bound = self._bounds\n", "meta": {"hexsha": "92851818caac92f75c2e4611543c8dabf9286879", "size": 5139, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyrobolearn/priorities/constraints/force/wrench_limits.py", "max_stars_repo_name": "Pandinosaurus/pyrobolearn", "max_stars_repo_head_hexsha": "9cd7c060723fda7d2779fa255ac998c2c82b8436", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-21T21:08:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:45:49.000Z", "max_issues_repo_path": "pyrobolearn/priorities/constraints/force/wrench_limits.py", "max_issues_repo_name": "Pandinosaurus/pyrobolearn", "max_issues_repo_head_hexsha": "9cd7c060723fda7d2779fa255ac998c2c82b8436", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyrobolearn/priorities/constraints/force/wrench_limits.py", "max_forks_repo_name": "Pandinosaurus/pyrobolearn", "max_forks_repo_head_hexsha": "9cd7c060723fda7d2779fa255ac998c2c82b8436", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-29T21:25:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-29T21:25:39.000Z", "avg_line_length": 39.8372093023, "max_line_length": 118, "alphanum_fraction": 0.5726795096, "include": true, "reason": "import numpy", "num_tokens": 1267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.37754068280545827, "lm_q1q2_score": 0.19319383634290138}}
{"text": "__docformat__='reStructuredText'\n__author__ = 'Anand Patil, anand.prabhakar.patil@gmail.com'\n__all__ = ['extend_children', 'extend_parents', 'ParentDict', 'Stochastic', 'Deterministic', 'Potential']\n\n\nfrom copy import copy\nfrom numpy import array, ndarray, reshape, Inf, asarray, dot, sum, float, isnan, size, NaN, asanyarray\nimport numpy as np\nfrom Node import Node, ZeroProbability, Variable, PotentialBase, StochasticBase, DeterministicBase\nimport Container\nfrom Container import DictContainer, ContainerBase, file_items, ArrayContainer\nimport sys\nimport pdb\n\nd_neg_inf = float(-1.7976931348623157e+308)\n\n# from PyrexLazyFunction import LazyFunction\nfrom LazyFunction import LazyFunction, Counter\n\ndef extend_children(children):\n    \"\"\"\n    extend_children(children)\n\n    Returns a set containing\n    nearest conditionally stochastic (Stochastic, not Deterministic) descendants.\n    \"\"\"\n    new_children = copy(children)\n    need_recursion = False\n    dtrm_children = set()\n\n    for child in children:\n        if isinstance(child,Deterministic):\n            new_children |= child.children\n            dtrm_children.add(child)\n            need_recursion = True\n\n    new_children -= dtrm_children\n\n    if need_recursion:\n        new_children = extend_children(new_children)\n\n    return new_children\n\ndef extend_parents(parents):\n    \"\"\"\n    extend_parents(parents)\n\n    Returns a set containing\n    nearest conditionally stochastic (Stochastic, not Deterministic) ancestors.\n    \"\"\"\n    new_parents = set()\n\n    for parent in parents:\n\n        new_parents.add(parent)\n\n        if isinstance(parent, DeterministicBase):\n            new_parents.remove(parent)\n            new_parents |= parent.extended_parents\n\n        elif isinstance(parent, ContainerBase):\n            for contained_parent in parent.stochastics:\n                new_parents.add(contained_parent)\n            for contained_parent in parent.deterministics:\n                new_parents |= contained_parent.extended_parents\n\n\n    return new_parents\n\n\nclass ParentDict(DictContainer):\n    \"\"\"\n    A special subclass of DictContainer which makes it safe to change\n    varibales' parents. When __setitem__ is called, a ParentDict instance\n    removes its owner from the old parent's children set (if appropriate)\n    and adds its owner to the new parent's children set. It then asks\n    its owner to generate a new LazyFunction instance using its new\n    parents.\n\n    Also manages the extended_parents attribute of owner.\n\n    NB: StepMethod and Model are expecting variables'\n    children to be static. If you want to change indedependence structure\n    over the course of an MCMC loop, please do so with indicator variables.\n\n    :SeeAlso: DictContainer\n    \"\"\"\n    def __init__(self, regular_dict, owner):\n        DictContainer.__init__(self, dict(regular_dict))\n        self.owner = owner\n        self.owner.extended_parents = extend_parents(self.variables)\n        if isinstance(self.owner, StochasticBase) or isinstance(self.owner, PotentialBase):\n            self.has_logp = True\n        else:\n            self.has_logp = False\n\n    def detach_parents(self):\n        for parent in self.itervalues():\n            if isinstance(parent, Variable):\n                parent.children.discard(self.owner)\n            elif isinstance(parent, ContainerBase):\n                for variable in parent.variables:\n                    variable.chidren.discard(self.owner)\n\n        if self.has_logp:\n            self.detach_extended_parents()\n\n\n    def detach_extended_parents(self):\n        for e_parent in self.owner.extended_parents:\n            if isinstance(e_parent, StochasticBase):\n                e_parent.extended_children.discard(self.owner)\n\n\n    def attach_parents(self):\n        for parent in self.itervalues():\n            if isinstance(parent, Variable):\n                parent.children.add(self.owner)\n            elif isinstance(parent, ContainerBase):\n                for variable in parent.variables:\n                    variable.children.add(self.owner)\n\n        if self.has_logp:\n            self.attach_extended_parents()\n\n    def attach_extended_parents(self):\n        for e_parent in self.owner.extended_parents:\n            if isinstance(e_parent, StochasticBase):\n                e_parent.extended_children.add(self.owner)\n\n\n    def __setitem__(self, key, new_parent):\n        old_parent = self[key]\n\n        # Possibly remove owner from old parent's children set.\n        if isinstance(old_parent, Variable) or isinstance(old_parent, ContainerBase):\n\n            # Tell all extended parents to forget about owner\n            if self.has_logp:\n                self.detach_extended_parents()\n\n            self.val_keys.remove(key)\n            self.nonval_keys.append(key)\n\n            if isinstance(old_parent, Variable):\n                # See if owner only claims the old parent via this key.\n                if sum([parent is old_parent for parent in self.itervalues()]) == 1:\n                    old_parent.children.remove(self.owner)\n\n\n            if isinstance(old_parent, ContainerBase):\n                for variable in old_parent.variables:\n                    if sum([parent is variable for parent in self.itervalues()]) == 1:\n                        variable.children.remove(self.owner)\n\n\n\n        # If the new parent is a variable, add owner to its children set.\n        if isinstance(new_parent, Variable) or isinstance(new_parent, ContainerBase):\n\n            self.val_keys.append(key)\n            self.nonval_keys.remove(key)\n\n            if isinstance(new_parent, Variable):\n                new_parent.children.add(self.owner)\n\n            elif isinstance(new_parent, ContainerBase):\n                for variable in new_parent.variables:\n                    new_parent.children.add(self.owner)\n\n        # Totally recompute extended parents\n        self.owner.extended_parents = extend_parents(self.variables)\n        if self.has_logp:\n            self.attach_extended_parents()\n\n        dict.__setitem__(self, key, new_parent)\n\n        file_items(self, self)\n\n        # Tell my owner it needs a new lazy function.\n        self.owner.gen_lazy_function()\n\nclass Potential(PotentialBase):\n    \"\"\"\n    Not a variable; just an arbitrary log-probability term to multiply into the\n    joint distribution. Useful for expressing models that aren't directed, such as\n    Markov random fields.\n\n    Decorator instantiation:\n\n    @potential(trace = True)\n    def A(x = B, y = C):\n        return -.5 * (x-y)**2 / 3.\n\n    Direct instantiation:\n\n    :Parameters:\n\n        -logp: function\n              The function that computes the potential's value from the values\n              of its parents.\n\n        -doc: string\n              The docstring for this potential.\n\n        -name: string\n              The name of this potential.\n\n        -parents: dictionary\n              A dictionary containing the parents of this potential.\n\n        -cache_depth (optional): integer\n              An integer indicating how many of this potential's value computations\n              should be 'memoized'.\n\n        - plot (optional) : boolean\n            A flag indicating whether this variable is to be plotted.\n\n        - verbose (optional) : integer\n              Level of output verbosity: 0=none, 1=low, 2=medium, 3=high\n\n\n    Externally-accessible attribute:\n\n        -logp: float\n              Returns the potential's log-probability given its parents' values. Skips\n              computation if possible.\n\n    No methods.\n\n    :SeeAlso: Stochastic, Node, LazyFunction, stoch, dtrm, data, Model, Container\n    \"\"\"\n    def __init__(self, logp,  doc, name, parents, cache_depth=2, plot=None, verbose=None):\n\n        self.ParentDict = ParentDict\n\n        # This function gets used to evaluate self's value.\n        self._logp_fun = logp\n\n        self.errmsg = \"Potential %s forbids its parents' current values\"%name\n\n        Node.__init__(  self,\n                        doc=doc,\n                        name=name,\n                        parents=parents,\n                        cache_depth = cache_depth,\n                        verbose=verbose)\n\n        self._plot = plot\n\n        # self._logp.force_compute()\n\n        # Check initial value\n        if not isinstance(self.logp, float):\n            raise ValueError, \"Potential \" + self.__name__ + \"'s initial log-probability is %s, should be a float.\" %self.logp.__repr__()\n\n    def gen_lazy_function(self):\n\n        self._logp = LazyFunction(fun = self._logp_fun,\n                                    arguments = self.parents,\n                                    ultimate_args = self.extended_parents,\n                                    cache_depth = self._cache_depth)\n        self._logp.force_compute()\n\n    def get_logp(self):\n        if self.verbose > 1:\n            print '\\t' + self.__name__ + ': log-probability accessed.'\n        logp = self._logp.get()\n        if self.verbose > 1:\n            print '\\t' + self.__name__ + ': Returning log-probability ', logp\n\n        try:\n            logp = float(logp)\n        except:\n            raise TypeError, self.__name__ + ': computed log-probability ' + str(logp) + ' cannot be cast to float'\n\n        if logp != logp:\n            raise ValueError, self.__name__ + ': computed log-probability is NaN'\n\n        # Check if the value is smaller than a double precision infinity:\n        if logp <= d_neg_inf:\n            if self.verbose > 0:\n                raise ZeroProbability, self.errmsg + \": %s\" %self._parents.value\n            else:\n                raise ZeroProbability, self.errmsg\n\n        return logp\n\n    def set_logp(self,value):\n        raise AttributeError, 'Potential '+self.__name__+'\\'s log-probability cannot be set.'\n\n    logp = property(fget = get_logp, fset=set_logp, doc=\"Self's log-probability value conditional on parents.\")\n\n\nclass Deterministic(DeterministicBase):\n    \"\"\"\n    A variable whose value is determined by the values of its parents.\n\n    Decorator instantiation:\n\n    @dtrm(trace=True)\n    def A(x = B, y = C):\n        return sqrt(x ** 2 + y ** 2)\n\n    :Parameters:\n      eval : function\n        The function that computes the variable's value from the values\n        of its parents.\n      doc : string\n        The docstring for this variable.\n      name: string\n        The name of this variable.\n      parents: dictionary\n        A dictionary containing the parents of this variable.\n      trace (optional): boolean\n        A boolean indicating whether this variable's value\n        should be traced (in MCMC).\n      cache_depth (optional): integer\n        An integer indicating how many of this variable's\n        value computations should be 'memoized'.\n      plot (optional) : boolean\n        A flag indicating whether this variable is to be plotted.\n      verbose (optional) : integer\n        Level of output verbosity: 0=none, 1=low, 2=medium, 3=high\n\n    :Attributes:\n      value : any object\n        Returns the variable's value given its parents' values. Skips\n        computation if possible.\n\n    :SeeAlso:\n      Stochastic, Potential, deterministic, MCMC, Lambda,\n      LinearCombination, Index\n    \"\"\"\n    def __init__(self, eval,  doc, name, parents, dtype=None, trace=True, cache_depth=2, plot=None, verbose=None):\n        self.ParentDict = ParentDict\n\n        # This function gets used to evaluate self's value.\n        self._eval_fun = eval\n\n        Variable.__init__(  self,\n                        doc=doc,\n                        name=name,\n                        parents=parents,\n                        cache_depth = cache_depth,\n                        dtype=dtype,\n                        trace=trace,\n                        plot=plot,\n                        verbose=verbose)\n\n        # self._value.force_compute()\n\n    def gen_lazy_function(self):\n\n        self._value = LazyFunction(fun = self._eval_fun,\n                                    arguments = self.parents,\n                                    ultimate_args = self.extended_parents,\n                                    cache_depth = self._cache_depth)\n\n        self._value.force_compute()\n\n    def get_value(self):\n        if self.verbose > 1:\n            print '\\t' + self.__name__ + ': value accessed.'\n        _value = self._value.get()\n        if isinstance(_value, ndarray):\n            _value.flags['W'] = False\n        if self.verbose > 1:\n            print '\\t' + self.__name__ + ': Returning value ',_value\n        return _value\n\n    def set_value(self,value):\n        raise AttributeError, 'Deterministic '+self.__name__+'\\'s value cannot be set.'\n\n    value = property(fget = get_value, fset=set_value, doc=\"Self's value computed from current values of parents.\")\n\nclass Stochastic(StochasticBase):\n\n    \"\"\"\n    A variable whose value is not determined by the values of its parents.\n\n\n    Decorator instantiation:\n\n    @stoch(trace=True)\n    def X(value = 0., mu = B, tau = C):\n        return Normal_like(value, mu, tau)\n\n    @stoch(trace=True)\n    def X(value=0., mu=B, tau=C):\n\n        def logp(value, mu, tau):\n            return Normal_like(value, mu, tau)\n\n        def random(mu, tau):\n            return Normal_r(mu, tau)\n\n        rseed = 1.\n\n\n    Direct instantiation:\n\n\n\n    - logp : function\n            The function that computes the variable's log-probability from\n            its value and the values of its parents.\n\n    - doc : string\n            The docstring for this variable.\n\n    - name : string\n            The name of this variable.\n\n    - parents: dict\n            A dictionary containing the parents of this variable.\n\n    - random (optional) : function\n            A function that draws a new value for this\n            variable given its parents' values.\n\n    - trace (optional) : boolean\n            A boolean indicating whether this variable's value\n            should be traced (in MCMC).\n\n    - value (optional) : number or array\n            An initial value for this variable\n\n    - dtype (optional) : type\n            A type for this variable.\n\n    - rseed (optional) : integer or rseed\n            A seed for this variable's rng. Either value or rseed must\n            be given.\n\n    - observed (optional) :  boolean\n            A flag indicating whether this variable is data; whether\n            its value is known.\n\n    - cache_depth (optional) : integer\n            An integer indicating how many of this variable's\n            log-probability computations should be 'memoized'.\n\n    - plot (optional) : boolean\n            A flag indicating whether this variable is to be plotted.\n\n    - verbose (optional) : integer\n            Level of output verbosity: 0=none, 1=low, 2=medium, 3=high\n\n\n    Externally-accessible attribute:\n\n    - value: any class\n          Returns this variable's current value.\n\n    - logp: float\n          Returns the variable's log-probability given its value and its\n          parents' values. Skips computation if possible.\n\n    last_value: any class\n          Returns this variable's last value. Useful for rejecting\n          Metropolis-Hastings jumps. See touch() and the warning below.\n\n    Externally-accessible methods:\n\n    random():   Draws a new value for this variable from its distribution and\n                returns it.\n\n    :SeeAlso: Deterministic, Node, LazyFunction, stoch, dtrm, data, Model, Container\n    \"\"\"\n\n    def __init__(   self,\n                    logp,\n                    doc,\n                    name,\n                    parents,\n                    random = None,\n                    trace=True,\n                    value=None,\n                    dtype=None,\n                    rseed=False,\n                    observed=False,\n                    cache_depth=2,\n                    plot=None,\n                    verbose = None,\n                    isdata=None, \n                    check_logp=True):\n\n        self.counter = Counter()\n        self.ParentDict = ParentDict\n\n        # Support legacy 'isdata' for a while\n        if isdata is not None:\n            print \"Deprecation Warning: the 'isdata' flag has been replaced by 'observed'. Please update your model accordingly.\"\n            self.observed = isdata\n\n        # A flag indicating whether self's value has been observed.\n        self._observed = observed\n        if observed and value is None:\n            raise ValueError, 'Stochastic %s must be given an initial value if observed=True.'%name\n\n        # This function will be used to evaluate self's log probability.\n        self._logp_fun = logp\n\n        # This function will be used to draw values for self conditional on self's parents.\n        self._random = random\n\n        # A seed for self's rng. If provided, the initial value will be drawn. Otherwise it's\n        # taken from the constructor.\n        self.rseed = rseed\n\n        self.errmsg = \"Stochastic %s's value is outside its support,\\n or it forbids its parents' current values.\"%name\n\n        dtype = np.dtype(dtype)\n\n        # Initialize value, either from value provided or from random function.\n        try:\n            if dtype.kind != 'O' and value is not None:\n                self._value = asanyarray(value, dtype=dtype)\n                self._value.flags['W']=False\n            else:\n                self._value = value\n        except:\n            cls, inst, tb = sys.exc_info()\n            new_inst = cls('Stochastic %s: Failed to cast initial value to required dtype.\\n\\nOriginal error message:\\n'%name + inst.message)\n            raise cls, new_inst, tb\n\n        # Store the shape of the stochastic value\n        self._shape = np.shape(self._value)\n\n        Variable.__init__(  self,\n                        doc=doc,\n                        name=name,\n                        parents=parents,\n                        cache_depth=cache_depth,\n                        trace=trace,\n                        dtype=dtype,\n                        plot=plot,\n                        verbose=verbose)\n\n        # self._logp.force_compute()\n\n        # Store the shape of the stochastic value\n        self._shape = np.shape(self._value)\n\n        if isinstance(self._value, ndarray):\n            self._value.flags['W'] = False\n\n        if check_logp:\n            # Check initial value\n            if not isinstance(self.logp, float):\n                raise ValueError, \"Stochastic \" + self.__name__ + \"'s initial log-probability is %s, should be a float.\" %self.logp.__repr__()\n\n\n    def gen_lazy_function(self):\n        \"\"\"\n        Will be called by Node at instantiation.\n        \"\"\"\n\n        # If value argument to __init__ was None, draw value from random method.\n        if self._value is None:\n\n            # Use random function if provided\n            if self._random is not None:\n                self.value = self._random(**self._parents.value)\n\n            # Otherwise leave initial value at None and warn.\n            else:\n                raise ValueError, 'Stochastic ' + self.__name__ + \"'s value initialized to None; no initial value or random method provided.\"\n\n        arguments = {}\n        arguments.update(self.parents)\n        arguments['value'] = self\n        arguments = DictContainer(arguments)\n\n        self._logp = LazyFunction(fun = self._logp_fun,\n                                    arguments = arguments,\n                                    ultimate_args = self.extended_parents | set([self]),\n                                    cache_depth = self._cache_depth)\n        self._logp.force_compute()\n\n    def get_value(self):\n        # Define value attribute\n        if self.verbose > 1:\n            print '\\t' + self.__name__ + ': value accessed.'\n        return self._value\n\n\n    def set_value(self, value, force=False):\n        # Record new value and increment counter\n\n        # Value can't be updated if observed=True\n        if self.observed and not force:\n            raise AttributeError, 'Stochastic '+self.__name__+'\\'s value cannot be updated if observed flag is set'\n\n        if self.verbose > 0:\n            print '\\t' + self.__name__ + ': value set to ', value\n\n        # Save current value as last_value\n        # Don't copy because caching depends on the object's reference.\n        self.last_value = self._value\n\n        if self.dtype.kind != 'O':\n            self._value = asanyarray(value, dtype=self.dtype)\n            self._value.flags['W']=False\n        else:\n            self._value = value\n\n        self.counter.click()\n\n    value = property(fget=get_value, fset=set_value, doc=\"Self's current value.\")\n\n    def shape():\n        doc = \"The shape of the value of self.\"\n        def fget(self):\n            if self.verbose > 1:\n                print '\\t' + self.__name__ + ': shape accessed.'\n            return self._shape\n        return locals()\n    shape = property(**shape())\n\n    def revert(self):\n        \"\"\"\n        Sets self's value to self's last value. Bypasses the data cleaning in\n        the set_value method.\n        \"\"\"\n        self.counter.unclick()\n        self._value = self.last_value\n\n\n    def get_logp(self):\n\n        if self.verbose > 0:\n            print '\\t' + self.__name__ + ': logp accessed.'\n        logp = self._logp.get()\n\n        try:\n            logp = float(logp)\n        except:\n            raise TypeError, self.__name__ + ': computed log-probability ' + str(logp) + ' cannot be cast to float'\n\n        if logp != logp:\n            raise ValueError, self.__name__ + ': computed log-probability is NaN'\n\n        if self.verbose > 0:\n            print '\\t' + self.__name__ + ': Returning log-probability ', logp\n\n        # Check if the value is smaller than a double precision infinity:\n        if logp <= d_neg_inf:\n            if self.verbose > 0:\n                raise ZeroProbability, self.errmsg + \"\\nValue: %s\\nParents' values:%s\" % (self._value, self._parents.value)\n            else:\n                raise ZeroProbability, self.errmsg\n\n        return logp\n\n    def set_logp(self, new_logp):\n        raise AttributeError, 'Stochastic '+self.__name__+'\\'s logp attribute cannot be set'\n\n    logp = property(fget = get_logp, fset=set_logp, doc=\"Log-probability or log-density of self's current value\\n given values of parents.\")\n\n\n    # Sample self's value conditional on parents.\n    def random(self):\n        \"\"\"\n        Draws a new value for a stoch conditional on its parents\n        and returns it.\n\n        Raises an error if no 'random' argument was passed to __init__.\n        \"\"\"\n\n        if self._random:\n            # Get current values of parents for use as arguments for _random()\n            r = self._random(**self.parents.value)\n        else:\n            raise AttributeError, 'Stochastic '+self.__name__+' does not know how to draw its value, see documentation'\n\n        if self.shape:\n            r = np.reshape(r, self.shape)\n\n        # Set Stochastic's value to drawn value\n        if not self.observed:\n            self.value = r\n\n        return r\n\n    # Shortcut alias to random\n    rand = random\n\n    def _get_isdata(self):\n        import warnings\n        warnings.warn('\"isdata\" is deprecated, please use \"observed\" instead.')\n        return self._observed\n    def _set_isdata(self, isdata):\n        raise ValueError, 'Stochastic %s: \"observed\" flag cannot be changed.'%self.__name__\n    isdata = property(_get_isdata, _set_isdata)\n\n    def _get_observed(self):\n        return self._observed\n    def _set_observed(self, observed):\n        raise ValueError, 'Stochastic %s: \"observed\" flag cannot be changed.'%self.__name__\n    observed = property(_get_observed, _set_observed)\n\n\n    def _get_coparents(self):\n        coparents = set()\n        for child in self.extended_children:\n            coparents |= child.extended_parents\n        coparents.add(self)\n        return coparents\n    coparents = property(_get_coparents, doc=\"All the variables whose extended children intersect with self's.\")\n\n    def _get_moral_neighbors(self):\n        moral_neighbors = self.coparents | self.extended_parents | self.extended_children\n        for neighbor in copy(moral_neighbors):\n            if isinstance(neighbor, PotentialBase):\n                moral_neighbors.remove(neighbor)\n        return moral_neighbors\n    moral_neighbors = property(_get_moral_neighbors, doc=\"Self's neighbors in the moral graph: self's Markov blanket with self removed.\")\n\n    def _get_markov_blanket(self):\n        return self.moral_neighbors | set([self])\n    markov_blanket = property(_get_markov_blanket, doc=\"Self's coparents, self's extended parents, self's children and self.\")\n", "meta": {"hexsha": "60b9589437664931b7a2fcb345442567e38bdd33", "size": 24447, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymc/PyMCObjects.py", "max_stars_repo_name": "matthew-brett/pymc", "max_stars_repo_head_hexsha": "3a31613f056e7993a449d89bafef5fdaa40d47e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-12-03T09:42:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T19:23:29.000Z", "max_issues_repo_path": "pymc/PyMCObjects.py", "max_issues_repo_name": "matthew-brett/pymc", "max_issues_repo_head_hexsha": "3a31613f056e7993a449d89bafef5fdaa40d47e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-09-27T02:00:41.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-27T02:15:32.000Z", "max_forks_repo_path": "pymc/PyMCObjects.py", "max_forks_repo_name": "matthew-brett/pymc", "max_forks_repo_head_hexsha": "3a31613f056e7993a449d89bafef5fdaa40d47e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-10-27T13:27:32.000Z", "max_forks_repo_forks_event_max_datetime": "2017-10-27T13:27:32.000Z", "avg_line_length": 33.7665745856, "max_line_length": 142, "alphanum_fraction": 0.6085818301, "include": true, "reason": "import numpy,from numpy", "num_tokens": 5232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.1931938291751268}}
{"text": "# Copyright 2016 Raytheon BBN Technologies\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n\ntry:\n    from QGL import *\n    from QGL import config as QGLconfig\n    from QGL.BasicSequences.helpers import create_cal_seqs, delay_descriptor, cal_descriptor\nexcept:\n    print(\"Could not find QGL\")\n\nimport auspex.config as config\nfrom auspex.log import logger\nfrom copy import copy, deepcopy\nfrom adapt.refine import refine_1D\nimport os\nimport uuid\nimport pandas as pd\nimport networkx as nx\nimport scipy as sp\nimport subprocess\nimport zmq\nimport json\nimport datetime\n\nimport time\nimport bbndb\nfrom auspex.filters import DataBuffer\nfrom .qubit_exp import QubitExperiment\nfrom . import pipeline\nfrom auspex.parameter import FloatParameter\nfrom auspex.filters.plot import ManualPlotter\nfrom auspex.analysis.fits import *\nfrom auspex.analysis.qubit_fits import *\nfrom auspex.analysis.helpers import normalize_data\nfrom matplotlib import cm\nfrom scipy.optimize import curve_fit\nimport numpy as np\nfrom itertools import product\n\nimport bbndb\n\nclass Calibration(object):\n\n    def __init__(self):\n        self.do_plotting = True\n        self.uuid = str(uuid.uuid4())\n\n    def init_plots(self):\n        \"\"\"Return a ManualPlotter object so we can plot calibrations. All\n        plot lines, glyphs, etc. must be declared up front!\"\"\"\n        return None\n\n    def start_plots(self):\n        # Create the descriptor and set uuids for each plot process\n        plot_desc = {p.filter_name: p.desc() for p in self.plotters}\n\n        for p in self.plotters:\n            p.uuid = self.uuid\n        try:\n            time.sleep(1.0)\n            context = zmq.Context()\n            socket = context.socket(zmq.DEALER)\n            socket.setsockopt(zmq.LINGER, 0)\n            socket.identity = \"Auspex_Experiment\".encode()\n            socket.connect(\"tcp://localhost:7761\")\n            socket.send_multipart([self.uuid.encode(), json.dumps(plot_desc).encode('utf8')])\n\n            poller = zmq.Poller()\n            poller.register(socket, zmq.POLLIN)\n\n            evts = dict(poller.poll(5000))\n            if socket in evts:\n                try:\n                    if socket.recv_multipart()[0] == b'ACK':\n                        logger.info(\"Connection established to plot server.\")\n                        self.do_plotting = True\n                    else:\n                        raise Exception(\"Server returned invalid message, expected ACK.\")\n                except:\n                    logger.info(\"Could not connect to server.\")\n                    for p in self.plotters:\n                        p.do_plotting = False\n            else:\n                logger.info(\"Server did not respond.\")\n                for p in self.plotters:\n                    p.do_plotting = False\n\n        except Exception as e:\n            logger.warning(f\"Exception {e} occured while contacting the plot server. Is it running?\")\n            for p in self.plotters:\n                p.do_plotting = False\n\n        for p in self.plotters:\n            p.start()\n\n    def stop_plots(self):\n        for p in self.plotters:\n            p.start()\n\n    def calibrate(self):\n        if self.do_plotting:\n            self.plotters = self.init_plots()\n            self.start_plots()\n\n        self._calibrate()\n\n        if self.succeeded:\n            self.update_settings()\n\n        if self.do_plotting:\n            self.stop_plots()\n\n    def update_settings(self):\n        # Must be overriden in child class\n        pass\n\n    def descriptor(self):\n        return None\n\n    def _calibrate(self):\n        \"\"\"Runs the actual calibration routine, must be overridden to provide any useful functionality.\n        This function is responsible for calling self.update_plot()\"\"\"\n        pass\n\n    def exp_config(self, exp):\n        \"\"\"Any final experiment configuration before it gets run.\"\"\"\n        pass\n\nclass QubitCalibration(Calibration):\n    calibration_experiment = None\n    def __init__(self, qubits, sample_name=None, output_nodes=None, stream_selectors=None, quad=\"real\", auto_rollback=True, do_plotting=True, **kwargs):\n        self.qubits           = qubits if isinstance(qubits, list) else [qubits]\n        self.qubit            = None if isinstance(qubits, list) else qubits\n        self.output_nodes     = output_nodes if isinstance(output_nodes, list) else [output_nodes]\n        self.stream_selectors = stream_selectors if isinstance(stream_selectors, list) else [stream_selectors]\n        self.filename         = 'None'\n        self.axis_descriptor  = None\n        self.leave_plots_open = True\n        self.cw_mode          = False\n        self.quad             = quad\n        self.succeeded        = False\n        self.norm_points      = None\n        self.auto_rollback    = True # Rollback any db changes upon calibration failure\n        self.kwargs           = kwargs\n        self.plotters         = []\n        self.do_plotting      = do_plotting\n        self.fake_data        = None\n        self.sample           = None\n        try:\n            self.quad_fun = {\"real\": np.real, \"imag\": np.imag, \"amp\": np.abs, \"phase\": np.angle}[quad]\n        except:\n            raise ValueError('Quadrature to calibrate must be one of (\"real\", \"imag\", \"amp\", \"phase\").')\n        super(QubitCalibration, self).__init__()\n\n        if sample_name:\n            if not bbndb.session:\n                raise Exception(\"Attempting to load Calibrations database, \\\n                    but no database session is open! Have the ChannelLibrary and PipelineManager been created?\")\n            existing_samples = list(bbndb.session.query(bbndb.calibration.Sample).filter_by(name=sample_name).all())\n            if len(existing_samples) == 0:\n                logger.info(\"Creating a new sample in the calibration database.\")\n                self.sample = bbndb.calibration.Sample(name=sample_name)\n                bbndb.session.add(self.sample)\n            elif len(existing_samples) == 1:\n                self.sample = existing_samples[0]\n            else:\n                raise Exception(\"Multiple samples found in calibration database with the same name! How?\")\n\n    def sequence(self):\n        \"\"\"Returns the sequence for the given calibration, must be overridden\"\"\"\n        raise NotImplementedError(\"Must run a specific qubit calibration.\")\n\n    def set_fake_data(self, *args, **kwargs):\n        self.fake_data = (args, kwargs)\n\n    def run_sweeps(self):\n        meta_file = compile_to_hardware(self.sequence(), fileName=self.filename, axis_descriptor=self.descriptor())\n        exp       = CalibrationExperiment(self.qubits, self.output_nodes, self.stream_selectors, meta_file, **self.kwargs)\n        if self.fake_data:\n            exp.set_fake_data(*self.fake_data[0], **self.fake_data[1])\n        self.exp_config(exp)\n        exp.run_sweeps()\n\n        data = {}\n        var = {}\n\n        for qubit, output_buff, var_buff in zip(exp.qubits,\n                                [exp.proxy_to_filter[on] for on in exp.output_nodes],\n                                [exp.proxy_to_filter[on] for on in exp.var_buffers]):\n            if not isinstance(output_buff, DataBuffer):\n                raise ValueError(\"Could not find data buffer for calibration.\")\n\n            dataset, descriptor = output_buff.get_data()\n            if self.norm_points:\n                buff_data = normalize_data(dataset, zero_id=self.norm_points[qubit.label][0],\n                                           one_id=self.norm_points[self.qubit.label][1])\n            else:\n                buff_data = dataset\n\n            data[qubit.label] = self.quad_fun(buff_data)\n\n            var_dataset, var_descriptor = var_buff.get_data()\n            # if 'Variance' in dataset.dtype.names:\n            realvar = np.real(var_dataset)\n            imagvar = np.imag(var_dataset)\n            N = descriptor.metadata[\"num_averages\"]\n            if self.quad in ['real', 'imag']:\n                var[qubit.label] = self.quad_fun(var_dataset)/N\n            elif self.quad == 'amp':\n                var[qubit.label] = (realvar + imagvar)/N\n            elif self.quad == 'phase':\n                # take the approach from Qlab assuming the noise is\n                # Gaussian in both quadratures i.e. 'circular' in the IQ plane.\n                stddata = np.sqrt(realvar + imagvar)\n                stdtheta = 180/np.pi * 2 * np.arctan(stddata/abs(data[qubit.label]))\n                var[qubit.label] = (stdtheta**2)/N\n            else:\n                raise Exception('Variance of {} not available. Choose amp, phase, real or imag'.format(self.quad))\n\n        # Return data and variance of the mean\n        if len(data) == 1:\n            # if single qubit, get rid of dictionary\n            data = list(data.values())[0]\n            var = list(var.values())[0]\n        return data, var\n\nclass CalibrationExperiment(QubitExperiment):\n\n    def __init__(self, qubits, output_nodes, stream_selectors, *args, **kwargs):\n        self.qubits = qubits\n        self.output_nodes = output_nodes\n        self.input_selectors = stream_selectors # name collision otherwise\n        self.var_buffers = []\n        super(CalibrationExperiment, self).__init__(*args, **kwargs)\n\n    def guess_output_nodes(self, graph):\n        output_nodes = []\n        qubit_labels = [q.label for q in self.qubits]\n        for qubit in self.qubits:\n            stream_sels = [ss for ss in self.stream_selectors if ss.qubit_name == qubit.label]\n            if len(stream_sels) > 1:\n                raise Exception(f\"More than one stream selector found for {qubit}, please explicitly define output node using output_nodes argument.\")\n            ds = nx.descendants(graph, stream_sels[0].hash_val)\n            outputs = [graph.nodes[d]['node_obj'] for d in ds if isinstance(graph.nodes[d]['node_obj'], (bbndb.auspex.Write, bbndb.auspex.Buffer))]\n            if len(outputs) > 1:\n                raise Exception(f\"More than one output node found for {qubit}, please explicitly define output node using output_nodes argument.\")\n            output_nodes.append(outputs[0])\n\n        return output_nodes\n\n    def modify_graph(self, graph):\n        \"\"\"Change the graph as needed. By default we changes all writers to buffers\"\"\"\n        if None in self.output_nodes:\n            self.output_nodes = self.guess_output_nodes(graph)\n\n        for output_node in self.output_nodes:\n            if output_node.hash_val not in graph:\n                raise ValueError(f\"Could not find specified output node {output_node} in graph.\")\n\n        for qubit in self.qubits:\n            stream_sels = [ss for ss in self.stream_selectors if ss.qubit_name == qubit.label]\n            if not any([ss.hash_val in graph for ss in stream_sels]):\n                raise ValueError(f\"Could not find specified qubit {qubit} in graph.\")\n\n        mapping = {}\n        for i in range(len(self.output_nodes)):\n            output_node = self.output_nodes[i]\n            if isinstance(output_node, bbndb.auspex.Write):\n                # Change the output node to a buffer\n                mapping[output_node] = bbndb.auspex.Buffer(label=output_node.label, qubit_name=output_node.qubit_name)\n\n        # Disable any paths not involving the buffer\n        new_graph = nx.DiGraph()\n        new_output_nodes = []\n        for output_node, qubit in zip(self.output_nodes, self.qubits):\n            new_output = mapping[output_node]\n            new_output_nodes.append(new_output)\n\n            ancestors   = [graph.nodes[n]['node_obj'] for n in nx.ancestors(graph, output_node.hash_val)]\n            stream_sels = [a for a in ancestors if isinstance(a, bbndb.auspex.StreamSelect)]\n            if len(stream_sels) != 1:\n                raise Exception(f\"Expected to find one stream selector for {qubit}. Instead found {len(stream_sels)}\")\n            stream_sel = stream_sels[0]\n\n            old_path  = nx.shortest_path(graph, stream_sel.hash_val, output_node.hash_val)\n            path      = old_path[:-1] + [new_output.hash_val]\n            nx.add_path(new_graph, path)\n            for n in old_path[:-1]:\n                new_graph.nodes[n]['node_obj'] = graph.nodes[n]['node_obj']\n            new_graph.nodes[new_output.hash_val]['node_obj'] = mapping[output_node]\n\n            # Fix connectors\n            for i in range(len(path)-1):\n                new_graph[path[i]][path[i+1]]['connector_in']  = graph[old_path[i]][old_path[i+1]]['connector_in']\n                new_graph[path[i]][path[i+1]]['connector_out'] = graph[old_path[i]][old_path[i+1]]['connector_out']\n\n            if not isinstance(new_graph.nodes(data=True)[path[-2]]['node_obj'], bbndb.auspex.Average):\n                raise Exception(\"There is no averager in line.\")\n            else:\n                vb = bbndb.auspex.Buffer(label=f\"{output_node.label}-VarBuffer\", qubit_name=output_node.qubit_name)\n                self.var_buffers.append(vb)\n                new_graph.add_node(vb.hash_val, node_obj=vb)\n                new_graph.add_edge(path[-2], vb.hash_val, node_obj=vb, connector_in=\"sink\", connector_out=\"final_variance\")\n            # maintain standard plots\n            plot_nodes = [output_node for output_node in nx.descendants(graph, path[-2]) if isinstance(graph.nodes[output_node]['node_obj'], bbndb.auspex.Display)]\n            for plot_node in plot_nodes:\n                plot_path = nx.shortest_path(graph, path[-2], plot_node)\n                new_graph = nx.compose(new_graph, graph.subgraph(plot_path))\n\n        self.output_nodes = new_output_nodes\n        return new_graph\n\n    def add_cal_sweep(self, method, values):\n        par = FloatParameter()\n        par.assign_method(method)\n        self.add_sweep(par, values)\n\n\nclass CavityTuneup(QubitCalibration):\n    def __init__(self, qubit, frequencies, averages=750, **kwargs):\n        self.start_frequencies = frequencies\n        kwargs['averages'] = averages\n        super(CavityTuneup, self).__init__(qubit, **kwargs)\n        self.cw_mode = True\n\n    def sequence(self):\n        return [[Id(self.qubit), MEAS(self.qubit)]]\n\n    def exp_config(self, exp):\n        exp.add_qubit_sweep(self.qubit, \"measure\", \"frequency\", self.new_frequencies)\n        self.quad_fun = lambda x: x\n\n    def _calibrate(self):\n        # all_data = np.empty(dtype=np.complex128)\n        self.new_frequencies = self.start_frequencies\n        self.frequencies = np.empty(0, dtype=np.complex128)\n        self.group_delays = np.empty(0, dtype=np.complex128)\n        self.datas = np.empty(0, dtype=np.complex128)\n        # orig_avg = self.kwargs['averages']\n        # Adaptive refinement to find cavity feature\n        # for i in range(self.iterations + 1):\n        self.data, _      = self.run_sweeps()\n        self.datas        = np.append(self.datas, self.data)\n        self.frequencies  = np.append(self.frequencies, self.new_frequencies[:-1])\n\n        ord = np.argsort(self.frequencies)\n        self.datas = self.datas[ord]\n        self.frequencies = self.frequencies[ord]\n\n        self.phases = np.unwrap(np.angle(self.datas))\n        self.group_delays = -np.diff(self.phases)/np.diff(self.frequencies)\n        phase_poly = np.poly1d(np.polyfit(self.frequencies, self.phases, 6))\n        # group_delay_poly = phase_poly.deriv()\n        # fine_freqs = np.linspace(self.frequencies[0], self.frequencies[-1], self.iterations*len(self.frequencies))\n        subtracted = self.phases - phase_poly(self.frequencies)\n        group_delay = np.diff(subtracted)/np.diff(self.frequencies)\n\n        # ordering = np.argsort(self.frequencies[:-1])\n        self.plot1[\"Phase\"] = (self.frequencies, self.phases)\n        self.plot1[\"Phase Fit\"] = (self.frequencies,phase_poly(self.frequencies))\n        self.plot1B[\"Group Delay\"] = (self.frequencies[:-1],group_delay)\n        self.plot2[\"Amplitude\"] = (self.frequencies,np.abs(self.datas))\n\n        guess = np.abs(self.frequencies[np.argmax(np.abs(group_delay))])\n        self.new_frequencies = np.arange(guess-15e6, guess+15e6, 1e6)\n        self.frequencies = np.empty(0, dtype=np.complex128)\n        self.group_delays = np.empty(0, dtype=np.complex128)\n        self.datas = np.empty(0, dtype=np.complex128)\n\n        self.data, _      = self.run_sweeps()\n        self.datas        = np.append(self.datas, self.data)\n        self.frequencies  = np.append(self.frequencies, self.new_frequencies[:-1])\n\n        ord = np.argsort(self.frequencies)\n        self.datas = self.datas[ord]\n        self.frequencies = self.frequencies[ord]\n\n        self.phases = np.unwrap(np.angle(self.datas))\n        self.group_delays = -np.diff(self.phases)/np.diff(self.frequencies)\n        phase_poly = np.poly1d(np.polyfit(self.frequencies, self.phases, 6))\n        # group_delay_poly = phase_poly.deriv()\n        # fine_freqs = np.linspace(self.frequencies[0], self.frequencies[-1], self.iterations*len(self.frequencies))\n        subtracted = self.phases - phase_poly(self.frequencies)\n        group_delay = np.diff(subtracted)/np.diff(self.frequencies)\n\n        # ordering = np.argsort(self.frequencies[:-1])\n        self.plot1[\"Phase\"] = (self.frequencies, self.phases)\n        self.plot1[\"Phase Fit\"] = (self.frequencies,phase_poly(self.frequencies))\n        self.plot1B[\"Group Delay\"] = (self.frequencies[:-1],group_delay)\n        self.plot2[\"Amplitude\"] = (self.frequencies,np.abs(self.datas))\n\n        guess = np.abs(self.frequencies[np.argmax(np.abs(group_delay))])\n        self.new_frequencies = np.arange(guess-4e6, guess+4e6, 0.2e6)\n        self.frequencies = np.empty(0, dtype=np.complex128)\n        self.group_delays = np.empty(0, dtype=np.complex128)\n        self.datas = np.empty(0, dtype=np.complex128)\n\n        self.data, _      = self.run_sweeps()\n        self.datas        = np.append(self.datas, self.data)\n        self.frequencies  = np.append(self.frequencies, self.new_frequencies[:-1])\n\n        ord = np.argsort(self.frequencies)\n        self.datas = self.datas[ord]\n        self.frequencies = self.frequencies[ord]\n\n        self.phases = np.unwrap(np.angle(self.datas))\n        self.group_delays = -np.diff(self.phases)/np.diff(self.frequencies)\n        phase_poly = np.poly1d(np.polyfit(self.frequencies, self.phases, 6))\n        # group_delay_poly = phase_poly.deriv()\n        # fine_freqs = np.linspace(self.frequencies[0], self.frequencies[-1], self.iterations*len(self.frequencies))\n        subtracted = self.phases - phase_poly(self.frequencies)\n        group_delay = np.diff(subtracted)/np.diff(self.frequencies)\n\n        # ordering = np.argsort(self.frequencies[:-1])\n        self.plot1[\"Phase\"] = (self.frequencies, self.phases)\n        self.plot1[\"Phase Fit\"] = (self.frequencies,phase_poly(self.frequencies))\n        self.plot1B[\"Group Delay\"] = (self.frequencies[:-1],group_delay)\n\n        self.plot2[\"Amplitude\"] = (self.frequencies,np.abs(self.datas))\n\n        shifted_cav = np.real(self.datas) - np.mean(np.real(self.datas))\n        guess = np.abs(self.frequencies[np.argmax(np.abs(shifted_cav))])\n            # self.kwargs['averages'] = 2000\n\n            # import pdb; pdb.set_trace()\n            #\n            # self.new_frequencies = refine_1D(self.frequencies, subtracted, all_points=False,\n            #                             criterion=\"difference\", threshold = \"one_sigma\")\n            # logger.info(f\"new_frequencies {self.new_frequencies}\")\n\n        # n, bins = sp.histogram(np.abs(self.frequencies), bins=\"auto\")\n        # f_start = bins[np.argmax(n)]\n        # f_stop  = bins[np.argmax(n)+1]\n        # logger.info(f\"Looking in bin from {f_start} to {f_stop}\")\n\n        # # self.kwargs['averages'] = orig_avg\n        # self.new_frequencies = np.arange(f_start, f_stop, 2e6)\n        # self.frequencies = np.empty(0, dtype=np.complex128)\n        # self.group_delays = np.empty(0, dtype=np.complex128)\n        # self.datas = np.empty(0, dtype=np.complex128)\n        #\n        # for i in range(self.iterations + 3):\n        #     self.data, _      = self.run_sweeps()\n        #     self.datas        = np.append(self.datas, self.data)\n        #     self.frequencies  = np.append(self.frequencies, self.new_frequencies[:-1])\n        #\n        #     ord = np.argsort(self.frequencies)\n        #     self.datas = self.datas[ord]\n        #     self.frequencies = self.frequencies[ord]\n        #\n        #     self.group_delays = -np.diff(np.unwrap(np.angle(self.datas)))/np.diff(self.frequencies)\n        #     # self.group_delays = group_del\n        #\n        #     # ordering = np.argsort(self.frequencies[:-1])\n        #     self.plot3[\"Group Delay\"] = (self.frequencies[1:],self.group_delays)\n        #     # self.plot2[\"Amplitude\"] = (self.frequencies,np.abs(self.datas))\n        #     # self.kwargs['averages'] = 2000\n        #\n        #     self.new_frequencies = refine_1D(self.frequencies[:-1], self.group_delays, all_points=False,\n        #                                 criterion=\"integral\", threshold = \"one_sigma\")\n        #     logger.info(f\"new_frequencies {self.new_frequencies}\")\n        # #\n\n        # # self.data, _ = self.run_sweeps()\n        # # group_delay = -np.diff(np.unwrap(np.angle(self.data)))/np.diff(self.new_frequencies)\n        # # self.plot3[\"Group Delay\"] = (self.new_frequencies[1:],group_delay)\n        #\n        # def lor_der(x, a, x0, width, offset):\n        #     return offset-(x-x0)*a/((4.0*((x-x0)/width)**2 + a**2)**2)\n        # f0 = np.abs(self.frequencies[np.argmax(np.abs(self.group_delays))])\n        # p0 = [np.max(np.abs(self.group_delays))*1e-18, np.abs(f0), 200e6, np.abs(self.group_delays)[0]]\n        # popt, pcov = curve_fit(lor_der, np.abs(self.frequencies[1:]), np.abs(self.group_delays), p0=p0)\n        # self.plot3[\"Group Delay Fit\"] = ( np.abs(self.frequencies[1:]),  lor_der( np.abs(self.frequencies[1:]), *popt))\n\n\n    def init_plots(self):\n        plot1 = ManualPlotter(\"Phase\", x_label='Frequency (GHz)', y_label='Group Delay')\n        plot1.add_data_trace(\"Phase\", {'color': 'C1'})\n        plot1.add_fit_trace(\"Phase Fit\", {'color': 'C2'})\n\n        plot1B = ManualPlotter(\"Group Delay\", x_label='Frequency (GHz)', y_label='Group Delay')\n        plot1B.add_data_trace(\"Group Delay\", {'color': 'C1'})\n        # plot1B.add_fit_trace(\"Phase Fit\", {'color': 'C2'})\n\n        plot2 = ManualPlotter(\"Amplitude\", x_label='Frequency (GHz)', y_label='Amplitude (Arb. Units)')\n        plot2.add_data_trace(\"Amplitude\", {'color': 'C2'})\n\n        # plot3 = ManualPlotter(\"First refined sweep\", x_label='Frequency (GHz)', y_label='Group Delay')\n        # plot3.add_data_trace(\"Group Delay\", {'color': 'C3'})\n        # plot3.add_fit_trace(\"Group Delay Fit\", {'color': 'C4'})\n        self.plot1 = plot1\n        self.plot1B = plot1B\n        self.plot2 = plot2\n        # self.plot3 = plot3\n        return [plot1, plot1B, plot2] #, plot3]\n\nclass QubitTuneup(QubitCalibration):\n    def __init__(self, qubit, f_start=5e9, f_stop=6e9, coarse_step=0.1e9, fine_step=1.0e6, averages=500, amp=1.0, **kwargs):\n        self.coarse_frequencies = np.arange(f_start, f_stop, coarse_step) - 10.0e6 # Don't stray too close to the carrier tone\n        self.fine_frequencies   = np.arange(10.0e6, coarse_step+10.0e6, fine_step)\n        self.f_start = f_start\n        self.f_stop = f_stop\n        self.coarse_step = coarse_step\n        self.fine_step = fine_step\n        self.amp = amp\n        kwargs['averages'] = averages\n        super(QubitTuneup, self).__init__(qubit, **kwargs)\n\n    def sequence(self):\n        return [[X(self.qubit, frequency=f, amp=self.amp), MEAS(self.qubit)] for f in self.fine_frequencies]\n\n    def exp_config(self, exp):\n        exp.add_qubit_sweep(self.qubit, \"control\", \"frequency\", self.coarse_frequencies)\n        self.quad_fun = lambda x: x\n\n    def _calibrate(self):\n        self.data, _ = self.run_sweeps()\n        freqs = np.arange(self.f_start, self.f_stop, self.fine_step)\n        self.plot[\"Data\"] = (freqs, self.data)\n\n    def init_plots(self):\n        plot = ManualPlotter(\"Qubit Search\", x_label='Frequency (Hz)', y_label='Amplitude (Arb. Units)')\n        plot.add_data_trace(\"Data\", {'color': 'C1'})\n        plot.add_fit_trace(\"Fit\", {'color': 'C1'})\n        self.plot = plot\n        return [plot]\n\nclass RabiAmpCalibration(QubitCalibration):\n\n    amp2offset = 0.5\n\n    def __init__(self, qubit, num_steps=40, **kwargs):\n        if num_steps % 2 != 0:\n            raise ValueError(\"Number of steps for RabiAmp calibration must be even!\")\n        #for now, only do one qubit at a time\n        self.num_steps = num_steps\n        self.amps = np.hstack((np.arange(-1, 0, 2./num_steps),\n                               np.arange(2./num_steps, 1+2./num_steps, 2./num_steps)))\n        super(RabiAmpCalibration, self).__init__(qubit, **kwargs)\n        self.filename = 'Rabi/Rabi'\n\n    def sequence(self):\n        return ([[Xtheta(self.qubit, amp=a), MEAS(self.qubit)] for a in self.amps] +\n                [[Ytheta(self.qubit, amp=a), MEAS(self.qubit)] for a in self.amps])\n\n    def _calibrate(self):\n        data, _ = self.run_sweeps()\n        N = len(data)\n        I_fit = RabiAmpFit(self.amps, data[N//2:])\n        Q_fit = RabiAmpFit(self.amps, data[:N//2])\n        #Arbitary extra division by two so that it doesn't push the offset too far.\n        self.pi_amp = I_fit.pi_amp\n        self.pi2_amp = I_fit.pi_amp/2.0\n        self.i_offset = I_fit.fit_params[\"phi\"]*self.amp2offset\n        self.q_offset = Q_fit.fit_params[\"phi\"]*self.amp2offset\n        logger.info(\"Found X180 amplitude: {}\".format(self.pi_amp))\n        logger.info(\"Shifting I offset by: {}\".format(self.i_offset))\n        logger.info(\"Shifting Q offset by: {}\".format(self.q_offset))\n        finer_amps = np.linspace(np.min(self.amps), np.max(self.amps), 4*len(self.amps))\n        self.plot[\"I Data\"] = (self.amps, data[:N//2])\n        self.plot[\"Q Data\"] = (self.amps, data[N//2:])\n        self.plot[\"I Fit\"] = (finer_amps, I_fit.model(finer_amps))\n        self.plot[\"Q Fit\"] = (finer_amps, Q_fit.model(finer_amps))\n\n        if self.pi_amp <= 1.0 and self.pi2_amp <= 1.0:\n            self.succeeded = True\n\n    def init_plots(self):\n        plot = ManualPlotter(\"Rabi Amplitude Cal\", x_label=\"I/Q Amplitude\", y_label=\"{} (Arb. Units)\".format(self.quad))\n        plot.add_data_trace(\"I Data\", {'color': 'C1'})\n        plot.add_data_trace(\"Q Data\", {'color': 'C2'})\n        plot.add_fit_trace(\"I Fit\", {'color': 'C1'})\n        plot.add_fit_trace(\"Q Fit\", {'color': 'C2'})\n        self.plot = plot\n        return [plot]\n\n    def update_settings(self):\n        s = round(self.pi_amp, 5)\n        self.qubit.pulse_params['pi2Amp'] = round(self.pi2_amp, 5)\n        self.qubit.pulse_params['piAmp'] = round(self.pi_amp, 5)\n        awg_chan   = self.qubit.phys_chan\n        amp_factor = self.qubit.phys_chan.amp_factor\n        awg_chan.I_channel_offset += round(amp_factor*self.amp2offset*self.i_offset, 5)\n        awg_chan.Q_channel_offset += round(amp_factor*self.amp2offset*self.i_offset, 5)\n\n        if self.sample:\n            c1 = bbndb.calibration.Calibration(value=self.pi2_amp, sample=self.sample, name=\"Pi2Amp\", category=\"Rabi\")\n            c2 = bbndb.calibration.Calibration(value=self.pi_amp, sample=self.sample, name=\"PiAmp\", category=\"Rabi\")\n            c1.date = c2.date = datetime.datetime.now()\n            bbndb.session.add_all([c1, c2])\n            bbndb.session.commit()\n\nclass RamseyCalibration(QubitCalibration):\n    def __init__(self, qubit, delays=np.linspace(0.0, 20.0, 41)*1e-6,\n                two_freqs=False, added_detuning=150e3, set_source=True, AIC=True, **kwargs):\n        self.delays         = delays\n        self.two_freqs      = two_freqs\n        self.added_detuning = added_detuning\n        self.set_source     = set_source\n        self.AIC            = AIC #Akaike information criterion for model choice\n\n        super(RamseyCalibration, self).__init__(qubit, **kwargs)\n        self.filename = 'Ramsey/Ramsey'\n\n    def descriptor(self):\n        return [delay_descriptor(self.delays)]\n\n    def sequence(self):\n        return [[X90(self.qubit), Id(self.qubit, delay), X90(self.qubit), MEAS(self.qubit)] for delay in self.delays]\n\n    def init_plots(self):\n        plot = ManualPlotter(\"Ramsey Fits\", x_label='Time (us)', y_label='Amplitude (Arb. Units)')\n        plot.add_data_trace(\"Data 1\", {'color': 'black'})\n        plot.add_fit_trace(\"Fit 1\", {'color': 'red'})\n        plot.add_data_trace(\"Data 2\", {'color': 'green'})\n        plot.add_fit_trace(\"Fit 2\", {'color': 'blue'})\n        self.plot = plot\n        return [plot]\n\n    def exp_config(self, exp):\n        rcvr = self.qubit.measure_chan.receiver_chan.receiver\n        if self.first_ramsey:\n            self.source_proxy = self.qubit.phys_chan.generator # DB object\n            self.qubit_source = exp._instruments[self.source_proxy.label] # auspex instrument\n            self.orig_freq    = self.source_proxy.frequency\n            if self.set_source:\n                self.source_proxy.frequency = round(self.orig_freq + self.added_detuning, 10)\n                self.qubit_source.frequency = self.source_proxy.frequency\n            exp._instruments[rcvr.label].exp_step = 0\n        else:\n            exp._instruments[rcvr.label].exp_step = 1\n\n    def _calibrate(self):\n        self.first_ramsey = True\n\n        if not self.set_source:\n            self.qubit.frequency += float(self.added_detuning)\n        data, _ = self.run_sweeps()\n        try:\n            ramsey_fit = RamseyFit(self.delays, data, two_freqs=self.two_freqs, AIC=self.AIC)\n            fit_freqs = ramsey_fit.fit_params[\"f\"]\n        except Exception as e:\n            raise Exception(f\"Exception {e} while fitting in {self}\")\n\n        # Plot the results\n        self.plot[\"Data 1\"] = (self.delays, data)\n        finer_delays = np.linspace(np.min(self.delays), np.max(self.delays), 4*len(self.delays))\n        self.plot[\"Fit 1\"] = (finer_delays, ramsey_fit.model(finer_delays))\n\n        #TODO: set conditions for success\n        fit_freq_A = np.mean(fit_freqs) #the fit result can be one or two frequencies\n        if self.set_source:\n            self.source_proxy.frequency = round(self.orig_freq + self.added_detuning + fit_freq_A/2, 10)\n            self.qubit_source.frequency = self.source_proxy.frequency\n        else:\n            self.qubit.frequency += float(fit_freq_A/2)\n\n        self.first_ramsey = False\n\n        # if self.plot:\n        #     [self.add_manual_plotter(p) for p in self.plot] if isinstance(self.plot, list) else self.add_manual_plotter(self.plot)\n        # self.start_manual_plotters()\n        data, _ = self.run_sweeps()\n\n        try:\n            ramsey_fit = RamseyFit(self.delays, data, two_freqs=self.two_freqs, AIC=self.AIC)\n            fit_freqs = ramsey_fit.fit_params[\"f\"]\n        except Exception as e:\n            raise Exception(f\"Exception {e} while fitting in {self}\")\n\n        # Plot the results\n        self.plot[\"Data 2\"] = (self.delays, data)\n        self.plot[\"Fit 2\"]  = (finer_delays, ramsey_fit.model(finer_delays))\n\n        fit_freq_B = np.mean(fit_freqs)\n        if fit_freq_B < fit_freq_A:\n            self.fit_freq = round(self.orig_freq + self.added_detuning + 0.5*(fit_freq_A + 0.5*fit_freq_A + fit_freq_B), 10)\n        else:\n            self.fit_freq = round(self.orig_freq + self.added_detuning - 0.5*(fit_freq_A - 0.5*fit_freq_A + fit_freq_B), 10)\n\n    def update_settings(self):\n        if self.set_source:\n            self.source_proxy.frequency = float(round(self.fit_freq))\n            self.qubit_source.frequency = self.source_proxy.frequency\n        else:\n            self.qubit.frequency += float(round(self.fit_freq - self.orig_freq))\n        # update edges where this is the target qubit\n        for edge in self.qubit.edge_target:\n            edge_source = edge.phys_chan.generator\n            edge.frequency = self.source_proxy.frequency + self.qubit_source.frequency - edge_source.frequency\n        #         # TODO: fix this for db backend\n\n        # qubit_set_freq = self.saved_settings['instruments'][qubit_source]['frequency'] + self.saved_settings['qubits'][self.qubit.label]['control']['frequency']\n        # logger.info(\"Qubit set frequency = {} GHz\".format(round(float(qubit_set_freq/1e9),5)))\n        # return ('frequency', qubit_set_freq)\n\nclass PhaseEstimation(QubitCalibration):\n\n    amp2offset = 0.5\n\n    def __init__(self, qubit, num_pulses= 1, amplitude= 0.1, direction = 'X',\n                    target=np.pi/2, epsilon=1e-2, max_iter=5, **kwargs):\n        #for now, only do one qubit at a time\n        self.num_pulses = num_pulses\n        self.amplitude = amplitude\n        self.direction = direction\n\n        self.target = target\n        self.epsilon = epsilon\n        self.max_iter = max_iter\n\n        super(PhaseEstimation, self).__init__(qubit, **kwargs)\n\n        self.filename = 'PhaseCal/PhaseCal'\n\n    def sequence(self):\n        # Determine whether it is a single- or a two-qubit pulse calibration\n        if isinstance(self.qubit, list):\n            qubit = self.qubit[1]\n            cal_pulse = [ZX90_CR(*self.qubit, amp=self.amplitude)]\n        else:\n            qubit = self.qubit\n            cal_pulse = [Xtheta(self.qubit, amp=self.amplitude)]\n\n        # Exponentially growing repetitions of the target pulse, e.g.\n        # (1, 2, 4, 8, 16, 32, 64, 128, ...) x X90\n        seqs = [cal_pulse*n for n in 2**np.arange(self.num_pulses+1)]\n        # measure each along Z or Y\n        seqs = [s + m for s in seqs for m in [ [MEAS(qubit)], [X90m(qubit), MEAS(qubit)] ]]\n        # tack on calibrations to the beginning\n        seqs = [[Id(qubit), MEAS(qubit)], [X(qubit), MEAS(qubit)]] + seqs\n        # repeat each\n        return [copy(s) for s in seqs for _ in range(2)]\n\n    def _calibrate(self):\n\n        ct = 0\n        done = 0\n\n        start_amp = self.amplitude\n\n        phase_error = []\n\n        while not done and ct < self.max_iter:\n            ct += 1\n            data, var = self.run_sweeps()\n            phase, sigma = phase_estimation(data, var)\n            self.amplitude, done, error = phase_to_amplitude(phase, sigma, self.amplitude,\n                                                self.target, epsilon=self.epsilon)\n            phase_error.append(error)\n\n            self.data_plot['data'] = (np.array(range(1, len(data)+1)), data)\n            self.plot[\"angle_estimate\"] = (np.array(range(1, len(phase_error)+1)), np.array(phase_error))\n\n        if done == -1:\n            self.succeeded = False\n        elif done == 1:\n            self.succeeded = True\n        else:\n            raise Exception()\n\n    def init_plots(self):\n        data_plot = ManualPlotter(\"Phase Cal\", x_label=\"Sequence Number\", y_label=\"{} (Arb. Units)\".format(self.quad))\n        data_plot.add_data_trace(\"data\", {'color': 'C1'})\n        plot = ManualPlotter(\"Phase Angle Error\", x_label=\"Iteration\", y_label=\"Angle (rad.)\")\n        plot.add_data_trace(\"angle_estimate\", {'color': 'C1'})\n        self.plot = plot\n        self.data_plot = data_plot\n        return [data_plot, plot]\n\n    def update_settings(self):\n        logger.warning(\"Nothing to update.\")\n\n\nclass Pi2Calibration(PhaseEstimation):\n\n    def __init__(self, qubit, num_pulses= 1, direction = 'X',\n                    epsilon=1e-2, max_iter=5, **kwargs):\n        super(Pi2Calibration, self).__init__(qubit, num_pulses=num_pulses,\n                        amplitude=qubit.pulse_params['pi2Amp'], direction =direction,\n                        target=np.pi/2, epsilon=epsilon, max_iter=max_iter, **kwargs)\n\n    def update_settings(self):\n        self.qubit.pulse_params['pi2Amp'] = round(self.amplitude, 5)\n\n        if self.sample:\n            c = bbndb.calibration.Calibration(value=self.amplitude, sample=self.sample, name=\"Pi2Amp\", category=\"PhaseEstimation\")\n            c.date = datetime.datetime.now()\n            bbndb.session.add(c)\n            bbndb.session.commit()\n\nclass PiCalibration(PhaseEstimation):\n\n    def __init__(self, qubit, num_pulses= 1, direction = 'X',\n                    epsilon=1e-2, max_iter=5, **kwargs):\n        super(PiCalibration, self).__init__(qubit, num_pulses=num_pulses,\n                        amplitude=qubit.pulse_params['piAmp'], direction =direction,\n                        target=np.pi, epsilon=epsilon, max_iter=max_iter, **kwargs)\n\n    def update_settings(self):\n        self.qubit.pulse_params['piAmp'] = round(self.amplitude, 5)\n\n        if self.sample:\n            c = bbndb.calibration.Calibration(value=self.amplitude, sample=self.sample, name=\"PiAmp\", category=\"PhaseEstimation\")\n            c.date = datetime.datetime.now()\n            bbndb.session.add(c)\n            bbndb.session.commit()\n\n# class CRAmpCalibration_PhEst(PhaseEstimation):\n#     def __init__(self, qubit_names, num_pulses= 9):\n#         super(CRAmpCalibration_PhEst, self).__init__(qubit_names, num_pulses = num_pulses)\n#         self.CRchan = ChannelLibraries.EdgeFactory(*self.qubit)\n#         self.amplitude = self.CRchan.pulse_params['amp']\n#         self.target    = np.pi/2\n#         self.edge_name = self.CRchan.label\n\nclass DRAGCalibration(QubitCalibration):\n    def __init__(self, qubit, deltas = np.linspace(-1,1,21), num_pulses = np.arange(8, 48, 4), **kwargs):\n        self.filename = 'DRAG/DRAG'\n        self.deltas = deltas\n        self.num_pulses = num_pulses\n        super(DRAGCalibration, self).__init__(qubit, **kwargs)\n\n    def sequence(self):\n        seqs = []\n        for n in self.num_pulses:\n            seqs += [[X90(self.qubit, drag_scaling = d), X90m(self.qubit, drag_scaling = d)]*n + [X90(self.qubit, drag_scaling = d), MEAS(self.qubit)] for d in self.deltas]\n        seqs += create_cal_seqs((self.qubit,),2)\n        return seqs\n\n    def init_plots(self):\n        plot = ManualPlotter(\"DRAG Cal\", x_label=['DRAG parameter', 'Number of pulses'], y_label=['Amplitude (Arb. Units)', 'Fit DRAG parameter'], numplots = 2)\n        cmap = cm.viridis(np.linspace(0, 1, len(self.num_pulses)))\n        for n in range(len(self.num_pulses)):\n            plot.add_data_trace('Data_{}'.format(n), {'color': list(cmap[n]), 'linestyle': 'None'})\n            plot.add_fit_trace('Fit_{}'.format(n), {'color': list(cmap[n])})\n        plot.add_data_trace('Data_opt', subplot_num = 1) #TODO: error bars\n        self.plot = plot\n        return [plot]\n\n    def exp_config(self, exp):\n        rcvr = self.qubit.measure_chan.receiver_chan.receiver\n        exp._instruments[rcvr.label].exp_step = self.step #where from?\n\n    def _calibrate(self):\n        # run twice for different DRAG parameter ranges\n        for k in range(2):\n            self.step = k\n            data, _ = self.run_sweeps()\n            finer_deltas = np.linspace(np.min(self.deltas), np.max(self.deltas), 4*len(self.deltas))\n            #normalize data with cals\n            data = quick_norm_data(data)\n            try:\n                opt_drag, error_drag, popt_mat = fit_drag(data, self.deltas, self.num_pulses)\n                if k==1:\n                    self.succeeded = True\n            except Exception as e:\n                raise Exception(f\"Exception {e} while fitting in {self}\")\n\n            norm_data = data.reshape((len(self.num_pulses), len(self.deltas)))\n            for n in range(len(self.num_pulses)):\n                self.plot['Data_{}'.format(n)] = (self.deltas, norm_data[n, :])\n                finer_deltas = np.linspace(np.min(self.deltas), np.max(self.deltas), 4*len(self.deltas))\n                self.plot['Fit_{}'.format(n)] = (finer_deltas, quadf(finer_deltas, *popt_mat[:, n]))\n            self.plot[\"Data_opt\"] = (self.num_pulses, opt_drag) #TODO: add error bars\n\n            if k==0:\n                #generate sequence with new pulses and drag parameters\n                new_drag_step = 0.25*(max(self.deltas) - min(self.deltas))\n                self.deltas = np.linspace(opt_drag[-1] - new_drag_step, opt_drag[-1] + new_drag_step, len(self.deltas))\n                new_pulse_step = int(np.floor(2*(max(self.num_pulses)-min(self.num_pulses))/len(self.num_pulses)))\n                self.num_pulses = np.arange(max(self.num_pulses) - new_pulse_step, max(self.num_pulses) + new_pulse_step*(len(self.num_pulses)-1), new_pulse_step)\n\n            if not self.leave_plots_open:\n                self.plot.set_quit()\n        self.opt_drag = round(float(opt_drag[-1]), 5)\n\n    def update_settings(self):\n        logger.info(f'{self.qubit.label} DRAG parameter set to {self.opt_drag}')\n        self.qubit.pulse_params['drag_scaling'] = self.opt_drag\n\n        if self.sample:\n            c = bbndb.calibration.Calibration(value=self.opt_drag, sample=self.sample, name=\"drag_scaling\")\n            c.date = datetime.datetime.now()\n            bbndb.session.add(c)\n            bbndb.session.commit()\n\n# class MeasCalibration(Calibration):\n#     def __init__(self, qubit_name):\n#         super(MeasCalibration, self).__init__(qubit, **kwargs)\n#         self.meas_name = \"M-\" + qubit_name\n\n# class CLEARCalibration(MeasCalibration):\n#     '''\n#     Calibration of cavity reset pulse\n#     aux_qubit: auxiliary qubit used for CLEAR pulse\n#     kappa: cavity linewidth (angular frequency: 1/s)\n#     chi: half of the dispershive shift (angular frequency: 1/s)\n#     tau: duration of each of the 2 depletion steps (s)\n#     alpha: scaling factor\n#     T1factor: decay due to T1 between end of msm't and start of Ramsey\n#     T2: measured T2*\n#     nsteps: calibration steps/sweep\n#     cal_steps: choose ranges for calibration steps. 1: +-100%; 0: skip step\n#     '''\n#     def __init__(self, qubit, aux_qubit, kappa = 2e6, chi = 1e6, t_empty = 200e-9, ramsey_delays=np.linspace(0.0, 50.0, 51)*1e-6, ramsey_freq = 100e3, meas_delay = 0, tau = 200e-9, \\\n#     alpha = 1, T1factor = 1, T2 = 30e-6, nsteps = 11, eps1 = None, eps2 = None, cal_steps = (1,1,1)):\n#         super(CLEARCalibration, self).__init__(qubit, **kwargs)\n#         self.filename = 'CLEAR/CLEAR'\n#         self.aux_qubit = aux_qubit\n#         self.kappa = kappa\n#         self.chi = chi\n#         self.ramsey_delays = ramsey_delays\n#         self.ramsey_freq = ramsey_freq\n#         self.meas_delay = meas_delay\n#         self.tau = tau\n#         self.alpha = alpha\n#         self.T1factor = T1factor\n#         self.T2 = T2\n#         self.nsteps = nsteps\n#         if not eps1:\n#             # theoretical values as default\n#             self.eps1 = (1 - 2*np.exp(kappa*t_empty/4)*np.cos(chi*t_empty/2))/(1+np.exp(kappa*t_empty/2)-2*np.exp(kappa*t_empty/4)*np.cos(chi*t_empty/2))\n#             self.eps2 = 1/(1+np.exp(kappa*t_empty/2)-2*np.exp(kappa*t_empty/4)*np.cos(chi*t_empty/2))\n#         self.cal_steps = cal_steps\n\n#     def sequence(self, **params):\n#         qM = QubitFactory(self.aux_qubit) #TODO: replace with MEAS(q) devoid of digitizer trigger\n#         prep = X(self.qubit) if params['state'] else Id(self.qubit)\n#         seqs = [[prep, MEAS(qM, amp1 = params['eps1'], amp2 =  params['eps2'], step_length = self.tau), X90(self.qubit), Id(self.qubit,d), U90(self.qubit,phase = self.ramsey_freq*d),\n#         Id(self.qubit, self.meas_delay), MEAS(self.qubit)] for d in self.ramsey_delays]\n#         seqs += create_cal_seqs((self.qubit,), 2, delay = self.meas_delay)\n#         return seqs\n\n#     def init_plots(self): #keep in a single plot?\n#         plot_raw = ManualPlotter(\"CLEAR Ramsey\", x_label='Time (us)', y_label='<Z>')\n#         plot_res = ManualPlotter(\"CLEAR Cal\", x_label= ['eps1, eps2', 'eps1', 'eps2'], y_label=['Residual photons n0', '', ''], numplots=3)\n\n#         plot_raw.add_data_trace('Data')\n#         plot_raw.add_fit_trace('Fit')\n#         for sweep_num, state in product([0,1,2], [0,1]):\n#             plot_res.add_data_trace('sweep {}, state {}'.format(sweep_num, state), {'color': 'C{}'.format(state+1)}, sweep_num) #TODO: error bar\n#             plot_res.add_fit_trace('Fit sweep {}, state {}'.format(sweep_num, state), {'color' : 'C{}'.format(state+1)}, sweep_num) #TODO\n#         return [plot_raw, plot_res]\n\n\n#     def calibrate(self):\n#         cal_step = 0\n#         for ct in range(3):\n#             if not self.cal_steps[ct]:\n#                 continue\n#             #generate sequence\n#             xpoints = np.linspace(1-self.cal_steps[ct], 1+self.cal_steps[ct], self.nsteps)\n#             n0vec = np.zeros(self.nsteps)\n#             err0vec = np.zeros(self.nsteps)\n#             n1vec = np.zeros(self.nsteps)\n#             err1vec = np.zeros(self.nsteps)\n#             for k in range(self.nsteps):\n#                 eps1 = self.eps1 if k==1 else xpoints[k]*self.eps1\n#                 eps2 = self.eps2 if k==2 else xpoints[k]*self.eps2\n#                 #run for qubit in 0/1\n#                 for state in [0,1]:\n#                     self.set(eps1 = eps1, eps2 = eps2, state = state, exp_step = cal_step)\n#                     #analyze\n#                     data, _ = self.run()\n#                     norm_data = quick_norm_data(data)\n#                     eval('n{}vec'.format(state))[k], eval('err{}vec'.format(state))[k], fit_curve = fit_photon_number(self.ramsey_delays, norm_data, [self.kappa, self.ramsey_freq, 2*self.chi, self.T2, self.T1factor, 0])\n#                     #plot\n#                     self.plot[0]['Data'] = (self.ramsey_delays, norm_data)\n#                     self.plot[0]['Fit'] = fit_curve\n#                     self.plot[1]['sweep {}, state 0'.format(ct)] = (xpoints, n0vec)\n#                     self.plot[1]['sweep {}, state 1'.format(ct)] = (xpoints, n1vec)\n#                     cal_step+=1\n\n#             #fit for minimum photon number\n#             popt_0,_ = fit_quad(xpoints, n0vec)\n#             popt_1,_ = fit_quad(xpoints, n1vec)\n#             finer_xpoints = np.linspace(np.min(xpoints), np.max(xpoints), 4*len(xpoints))\n#             opt_scaling = np.mean(popt_0[0], popt_1[0])\n#             logger.info(\"Optimal scaling factor for step {} = {}\".format(ct+1, opt_scaling))\n\n#             if ct<2:\n#                 self.eps1*=opt_scaling\n#             if ct!=1:\n#                 self.eps2*=opt_scaling\n#             self.plot[1]['Fit sweep {}, state 0'.format(ct)] = (finer_xpoints, quadf(finer_xpoints, popt_0))\n#             self.plot[1]['Fit sweep {}, state 1'.format(ct)] = (finer_xpoints, quadf(finer_xpoints, popt_1))\n\n#         def update_settings(self):\n#             #update library (default amp1, amp2 for MEAS)\n#             self.saved_settings['qubits'][self.qubit.label]['measure']['pulse_params']['amp1'] = round(float(self.eps1), 5)\n#             self.saved_settings['qubits'][self.qubit.label]['measure']['pulse_params']['amp2'] = round(float(self.eps2), 5)\n#             self.saved_settings['qubits'][self.qubit.label]['measure']['pulse_params']['step_length'] = round(float(self.tau), 5)\n#             super(CLEARCalibration, self).update_settings()\n\n# '''Two-qubit gate calibrations'''\n# class CRCalibration(Calibration):\n#     def __init__(self, qubit_names, lengths=np.linspace(20, 1020, 21)*1e-9, phase = 0, amp = 0.8, rise_fall = 40e-9):\n#         super(CRCalibration, self).__init__(qubit_names, factory)\n#         self.lengths = lengths\n#         self.phases = phase\n#         self.amps = amp\n#         self.rise_fall = rise_fall\n#         self.filename = 'CR/CR'\n#         self.edge_name = ChannelLibraries.EdgeFactory(*self.qubit).label\n\n#     def init_plots(self):\n#         plot = ManualPlotter(\"CR\"+str.lower(self.cal_type.name)+\"Fit\", x_label=str.lower(self.cal_type.name), y_label='$<Z_{'+self.qubit_names[1]+'}>$', y_lim=(-1.02,1.02))\n#         plot.add_data_trace(\"Data 0\", {'color': 'C1'})\n#         plot.add_fit_trace(\"Fit 0\", {'color': 'C1'})\n#         plot.add_data_trace(\"Data 1\", {'color': 'C2'})\n#         plot.add_fit_trace(\"Fit 1\", {'color': 'C2'})\n#         return plot\n\n#     def calibrate(self):\n#         # generate sequence\n#         self.set()\n#         # run and load normalized data\n#         data, _ = self.run(norm_points = {self.qubit_names[0]: (0, 1), self.qubit_names[1]: (0, 2)})\n#         # select target qubit\n#         data_t = data[self.qubit_names[1]]\n#         # fit\n#         self.opt_par, all_params_0, all_params_1 = fit_CR([self.lengths, self.phases, self.amps], data_t, self.cal_type)\n#         # plot the result\n#         xaxis = self.lengths if self.cal_type==CR_cal_type.LENGTH else self.phases if self.cal_type==CR_cal_type.PHASE else self.amps\n#         finer_xaxis = np.linspace(np.min(xaxis), np.max(xaxis), 4*len(xaxis))\n#         self.plot[\"Data 0\"] = (xaxis,       data_t[:len(data_t)//2])\n#         self.plot[\"Fit 0\"] =  (finer_xaxis, np.polyval(all_params_0, finer_xaxis) if self.cal_type == CR_cal_type.AMP else sinf(finer_xaxis, *all_params_0))\n#         self.plot[\"Data 1\"] = (xaxis,       data_t[len(data_t)//2:])\n#         self.plot[\"Fit 1\"] =  (finer_xaxis, np.polyval(all_params_1, finer_xaxis) if self.cal_type == CR_cal_type.AMP else sinf(finer_xaxis, *all_params_1))\n#         return (str.lower(self.cal_type.name), self.opt_par)\n\n#     def update_settings(self):\n#         self.saved_settings['edges'][self.edge_name]['pulse_params'][str.lower(self.cal_type.name)] = float(self.opt_par)\n#         super(CRCalibration, self).update_settings()\n\n# class CRLenCalibration(CRCalibration):\n#     def __init__(self, qubit_names, factory, lengths=np.linspace(20, 1020, 21)*1e-9, phase = 0, amp = 0.8, rise_fall = 40e-9, cal_type = CR_cal_type.LENGTH):\n#         self.cal_type = cal_type\n#         super(CRLenCalibration, self).__init__(qubit_names, factory, lengths, phase, amp, rise_fall)\n\n#     def sequence(self):\n#         qc, qt = self.qubit\n#         seqs = [[Id(qc)] + echoCR(qc, qt, length=l, phase = self.phases, amp=self.amps, riseFall=self.rise_fall).seq + [Id(qc), MEAS(qt)*MEAS(qc)]\n#         for l in self.lengths]+ [[X(qc)] + echoCR(qc, qt, length=l, phase= self.phases, amp=self.amps, riseFall=self.rise_fall).seq + [X(qc), MEAS(qt)*MEAS(qc)]\n#         for l in self.lengths] + create_cal_seqs((qt,qc), 2, measChans=(qt,qc))\n\n#         self.axis_descriptor=[\n#             delay_descriptor(np.concatenate((self.lengths, self.lengths))),\n#             cal_descriptor(tuple(self.qubit), 2)\n#         ]\n\n#         return seqs\n\n# class CRPhaseCalibration(CRCalibration):\n#     def __init__(self, qubit_names, factory, phases = np.linspace(0,2*np.pi,21), amp = 0.8, rise_fall = 40e-9, cal_type = CR_cal_type.PHASE):\n#         self.cal_type = cal_type\n#         super(CRPhaseCalibration, self).__init__(qubit_names, factory, 0, phases, amp, rise_fall)\n#         CRchan = ChannelLibraries.EdgeFactory(*self.qubit)\n#         self.lengths = CRchan.pulse_params['length']\n\n\n#     def sequence(self):\n#         qc, qt = self.qubit\n#         seqs = [[Id(qc)] + echoCR(qc, qt, length=self.lengths, phase=ph, amp=self.amps, riseFall=self.rise_fall).seq + [X90(qt)*Id(qc), MEAS(qt)*MEAS(qc)]\n#         for ph in self.phases]+ [[X(qc)] + echoCR(qc, qt, length=self.lengths, phase= ph, amp=self.amps, riseFall=self.rise_fall).seq + [X90(qt)*X(qc), MEAS(qt)*MEAS(qc)]\n#         for ph in self.phases] + create_cal_seqs((qt,qc), 2, measChans=(qt,qc))\n\n#         self.axis_descriptor = [\n#             {\n#                 'name': 'phase',\n#                 'unit': 'radians',\n#                 'points': list(self.phases)+list(self.phases),\n#                 'partition': 1\n#             },\n#             cal_descriptor(tuple(self.qubit), 2)\n#         ]\n\n#         return seqs\n\n# class CRAmpCalibration(CRCalibration):\n#     def __init__(self, qubit_names, factory, amp_range = 0.4, amp = 0.8, rise_fall = 40e-9, num_CR = 1, cal_type = CR_cal_type.AMP):\n#         self.num_CR = num_CR\n#         if num_CR % 2 == 0:\n#             logger.error('The number of ZX90 must be odd')\n#         self.cal_type = cal_type\n#         amps = np.linspace((1-amp_range/2)*amp, (1+amp_range/2)*amp, 21)\n#         super(CRAmpCalibration, self).__init__(qubit_names, factory, 0, 0, amps, rise_fall)\n#         CRchan = ChannelLibraries.EdgeFactory(*self.qubit)\n#         self.lengths = CRchan.pulse_params['length']\n#         self.phases = CRchan.pulse_params['phase']\n\n#     def sequence(self):\n#         qc, qt = self.qubit\n#         seqs = [[Id(qc)] + self.num_CR*echoCR(qc, qt, length=self.lengths, phase=self.phases, amp=a, riseFall=self.rise_fall).seq + [Id(qc), MEAS(qt)*MEAS(qc)]\n#         for a in self.amps]+ [[X(qc)] + self.num_CR*echoCR(qc, qt, length=self.lengths, phase= self.phases, amp=a, riseFall=self.rise_fall).seq + [X(qc), MEAS(qt)*MEAS(qc)]\n#         for a in self.amps] + create_cal_seqs((qt,qc), 2, measChans=(qt,qc))\n\n#         self.axis_descriptor = [\n#             {\n#                 'name': 'amplitude',\n#                 'unit': None,\n#                 'points': list(self.amps)+list(self.amps),\n#                 'partition': 1\n#             },\n#             cal_descriptor(tuple(self.qubit), 2)\n#         ]\n\n#         return seqs\n\ndef restrict(phase):\n    out = np.mod( phase + np.pi, 2*np.pi, ) - np.pi\n    return out\n\ndef phase_estimation( data_in, vardata_in, verbose=False):\n    \"\"\"Estimates pulse rotation angle from a sequence of P^k experiments, where\n    k is of the form 2^n. Uses the modified phase estimation algorithm from\n    Kimmel et al, quant-ph/1502.02677 (2015). Every experiment i doubled.\n    vardata should be the variance of the mean\"\"\"\n\n    #average together pairs of data points\n    avgdata = (data_in[0::2] + data_in[1::2])/2\n\n    # normalize data using the first two pulses to calibrate the \"meter\"\n    data = 1 + 2*(avgdata[2:] - avgdata[0]) / (avgdata[0] - avgdata[1])\n    zdata = data[0::2]\n    xdata = data[1::2]\n\n    # similar scaling with variances\n    vardata = (vardata_in[0::2] + vardata_in[1::2])/2\n    vardata = vardata[2:] * 2 / abs(avgdata[0] - avgdata[1])**2\n    zvar = vardata[0::2]\n    xvar = vardata[1::2]\n\n    phases = np.arctan2(xdata, zdata)\n    distances = np.sqrt(xdata**2 + zdata**2)\n\n    curGuess = phases[0]\n    phase = curGuess\n    sigma = np.pi\n\n    if verbose == True:\n        print('Current Guess: %f'%(curGuess))\n\n    for k in range(1,len(phases)):\n\n        if verbose == True:\n            print('k: %d'%(k))\n\n        # Each step of phase estimation needs to assign the measured phase to\n        # the correct half circle. We will conservatively require that the\n        # (x,z) tuple is long enough that we can assign it to the correct\n        # quadrant of the circle with 2σ confidence\n\n        if distances[k] < 2*np.sqrt(xvar[k] + zvar[k]):\n            logger.info('Phase estimation terminated at %dth pulse because the (x,z) vector is too short'%(k))\n            break\n\n        lowerBound = restrict(curGuess - np.pi/2**(k))\n        upperBound = restrict(curGuess + np.pi/2**(k))\n        possiblesTest = [ restrict((phases[k] + 2*n*np.pi)/2**(k)) for n in range(0,2**(k)+1)]\n\n        if verbose == True:\n            logger.info('Lower Bound: %f'%lowerBound)\n            logger.info('Upper Bound: %f'%upperBound)\n\n        possibles=[]\n        for p in possiblesTest:\n            # NOTE: previous code did not handle upperbound == lowerBound\n            if lowerBound >= upperBound:\n                satisfiesLB = p > lowerBound or p < 0.\n                satisfiesUP = p < upperBound or p > 0.\n            else:\n                satisfiesLB = p > lowerBound\n                satisfiesUP = p < upperBound\n\n            if satisfiesLB == True and satisfiesUP == True:\n                possibles.append(p)\n\n        curGuess = possibles[0]\n        if verbose == True:\n            logger.info('Current Guess: %f'%(curGuess))\n\n        phase = curGuess\n        sigma = np.maximum(np.abs(restrict(curGuess - lowerBound)), np.abs(restrict(curGuess - upperBound)))\n\n    return phase, sigma\n\ndef phase_to_amplitude(phase, sigma, amp, target, epsilon=1e-2):\n    # correct for some errors related to 2pi uncertainties\n    if np.sign(phase) != np.sign(amp):\n        phase += np.sign(amp)*2*np.pi\n    angle_error = phase - target;\n    logger.info('Angle error: %.4f'%angle_error);\n\n    amp_target = target/phase * amp\n    amp_error = amp - amp_target\n    logger.info('Set amplitude: %.4f\\n'%amp)\n    logger.info('Amplitude error: %.4f\\n'%amp_error)\n\n    amp = amp_target\n    done_flag = 0\n\n    # check for stopping condition\n    phase_error = phase - target\n    if np.abs(phase_error) < epsilon or np.abs(phase_error/sigma) < 1:\n        if np.abs(phase_error) < epsilon:\n            logger.info('Reached target rotation angle accuracy');\n        elif abs(phase_error/sigma) < 1:\n            logger.info('Reached phase uncertainty limit');\n        done_flag = 1\n\n    if amp > 1.0 or amp < epsilon:\n        logger.warning(f\"Phase estimation returned an unreasonable amplitude setting {amp}. Aborting.\")\n        done_flag = -1\n\n    return amp, done_flag, phase_error\n\ndef quick_norm_data(data): #TODO: generalize as in Qlab.jl\n    \"\"\"Rescale data assuming 2 calibrations / single qubit state at the end of the sequence\"\"\"\n    data = 2*(data-np.mean(data[-4:-2]))/(np.mean(data[-4:-2])-np.mean(data[-2:])) + 1\n    data = data[:-4]\n    return data\n", "meta": {"hexsha": "16e0d56b5758e241b07338b750f42970488ba51f", "size": 56946, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/auspex/qubit/pulse_calibration.py", "max_stars_repo_name": "minhhaiphys/Auspex", "max_stars_repo_head_hexsha": "3b9480120f0cdaf8a1e890a59e0e45e0fab5f1dd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/auspex/qubit/pulse_calibration.py", "max_issues_repo_name": "minhhaiphys/Auspex", "max_issues_repo_head_hexsha": "3b9480120f0cdaf8a1e890a59e0e45e0fab5f1dd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/auspex/qubit/pulse_calibration.py", "max_forks_repo_name": "minhhaiphys/Auspex", "max_forks_repo_head_hexsha": "3b9480120f0cdaf8a1e890a59e0e45e0fab5f1dd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.3352318959, "max_line_length": 221, "alphanum_fraction": 0.6131773961, "include": true, "reason": "import numpy,import scipy,from scipy,import networkx", "num_tokens": 14805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19319382917512679}}
{"text": "\n\n#def write_fits(path,array):\n#    from astropy.io import fits\n#    hdul = fits.PrimaryHDU(array)\n#    hdul.writeto(path,overwrite=True)\n#    return\n\ndef write_fits(path,array):\n    from astropy.io import fits\n    opd = '/Users/mygouf/Python/webbpsf/webbpsf-data4/NIRCam/OPD/OPD_RevW_ote_for_NIRCam_requirements.fits.gz'\n    hdul = fits.open(opd)\n    hdul[0].header['BUNIT']    \n    hdu2 = fits.PrimaryHDU(array)\n    hdu2.header['BUNIT'] = 'micron'\n    fits.writeto(path, np.nan_to_num(hdu2.data*1e6),hdu2.header,overwrite=True)\n    return\n\ndef display_ote_and_psf(inst,ote, opd_vmax=500, psf_vmax=0.1, title=\"OPD and PSF\", **kwargs):\n    import matplotlib.pyplot as plt\n    import webbpsf\n    psf = inst.calc_psf(monochromatic=2e-6,)\n    plt.figure(figsize=(12,8))\n    ax1=plt.subplot(121)\n    ote.display_opd(ax=ax1, vmax=opd_vmax, \n                    colorbar_orientation='horizontal',\n                   title='OPD modified for mirror moves') #, cbpad=0.05)\n    ax2=plt.subplot(122)\n    webbpsf.display_psf(psf, ext=1, vmax=psf_vmax, vmin=psf_vmax/1e4,\n                        colorbar_orientation='horizontal',\n                       title=\"PSF sim, 2 microns\") #, cbpad=0.05)\n    plt.suptitle(title, fontsize=16)\n    \ndef show_telescope_wfe(instr, ax=None, title=None, ticks=True, **kwargs):\n    if ax is None:\n        ax=plt.gca()\n    osys = instr._getOpticalSystem()\n    tel_wfe = osys.planes[0]\n    tel_wfe.display(what='opd', ax=ax,\n                    colorbar_orientation='vertical',\n                   **kwargs)\n    if title is None:\n        title=tel_wfe.name+\" for\\n\"+instr.name\n    ax.set_title(title)\n    if not ticks:\n        ax.set_xticks([])\n        ax.set_yticks([])\n        \ndef show_inst_wfe(instr, ax=None, **kwargs):\n    if ax is None:\n        plt.gca()\n    osys = instr._getOpticalSystem()\n    pupils = [p for p in osys.planes if p.planetype==poppy.poppy_core.PlaneType.pupil]\n    inst_wfe = pupils[-1]\n    inst_wfe.display(what='opd', ax=ax, \n                     colorbar_orientation='vertical', **kwargs)\n    plt.title(inst_wfe.name.replace(',','\\n')+ \"field point\")\n    \ndef show_tel_inst_wfes(instr):\n    plt.figure(figsize=(12,4))\n    ax1 = plt.subplot(121)\n    show_telescope_wfe(instr, ax=ax1)\n    ax2 = plt.subplot(122)\n    show_inst_wfe(instr, ax=ax2)\n    return\n  \ndef dist(yc,xc,y1,x1):\n    \"\"\" Returns the Euclidean distance between two points.\n    \"\"\"\n    return np.sqrt((yc-y1)**2+(xc-x1)**2)\n\ndef find_coords(rad, sep, init_angle, fin_angle):\n    angular_range = fin_angle-init_angle\n    npoints = (np.deg2rad(angular_range)*rad)/sep   #(2*np.pi*rad)/sep\n    ang_step = angular_range/npoints   #360/npoints\n    x = []\n    y = []\n    for i in range(int(npoints)): \n        newx = rad * np.cos(np.deg2rad(ang_step * i + init_angle))\n        newy = rad * np.sin(np.deg2rad(ang_step * i + init_angle))\n        x.append(newx)\n        y.append(newy)\n    return np.array(y), np.array(x)\n\ndef contrast_curve(data):\n\n    import matplotlib.pyplot as plt\n    import photutils\n    \n    data_crop = data\n\n    fwhm = 4\n    wedge=(0,360)\n    init_angle, fin_angle = wedge\n    init_rad=fwhm\n\n    NP = data_crop.shape[0]\n    print(NP)\n    array = data_crop\n    centery, centerx = np.array([NP/2,NP/2])\n\n    separation = 1.1\n    separation = 0.5\n    n_annuli = int(np.floor((centery)/separation))\n\n    x = centerx\n    y = centery\n    total = []\n    mean = []\n    noise = []\n    vector_radd = []\n\n    #plt.figure(figsize=(5,5)) \n    #vmin,vmax=np.min(data_crop),np.max(data_crop)\n    #plt.imshow(data_crop, cmap='CMRmap', origin = 'lower', vmin = vmin , vmax = vmax)\n\n    for i in range(n_annuli-1):\n        y = centery + init_rad + separation*(i)\n        rad = dist(centery, centerx, y, x)\n        yy, xx = find_coords(rad, fwhm, init_angle, fin_angle)\n        yy += centery\n        xx += centerx\n\n        apertures = photutils.CircularAperture((xx, yy), fwhm/2.)\n        #fluxes = photutils.aperture_photometry(array, apertures,mask = stis_mask)\n        fluxes = photutils.aperture_photometry(array, apertures)\n        fluxes = np.array(fluxes['aperture_sum'])\n\n        noise_ann = np.std(fluxes)\n        noise.append(noise_ann)\n        vector_radd.append(rad)\n\n        mean_ann = np.mean(fluxes)\n        mean.append(mean_ann)\n\n        nb_apertures = apertures.positions.shape[0]\n        total_ann = np.sum(fluxes)/nb_apertures\n        total.append(total_ann)\n        #print(total_ann)\n        if i <= 9:\n            apertures.plot(color='blue', lw=1.5, alpha=0.5)\n    #plt.show()\n\n    total0 = np.array(total)    \n    mean0 = np.array(mean)\n    noise0 = np.array(noise)\n    vector_rad0 = np.array(vector_radd)   \n    total0_stis = np.array(total)\n    mean0_stis = np.array(mean)\n    noise0_stis = np.array(noise)\n    vector_rad0_stis = np.array(vector_radd)  \n    \n    return noise0_stis, vector_rad0_stis\n\ndef generate_wavefront_errors(nb_of_maps,errors,nb_zernikes,path):\n\n    import poppy,webbpsf\n    import random\n    import matplotlib.pyplot as plt\n\n    # intial wavefront map\n    nc = webbpsf.NIRCam()\n    nc, ote = webbpsf.enable_adjustable_ote(nc)\n    osys = nc._get_aberrations()\n\n    # perturbed wavefront map\n    nc_perturb = webbpsf.NIRCam()\n    nc_perturb, ote_perturb = webbpsf.enable_adjustable_ote(nc_perturb)\n    osys_perturb = nc_perturb._get_aberrations()\n\n    # final wavefront map\n    nc_final = webbpsf.NIRCam()\n    nc_final, ote_final = webbpsf.enable_adjustable_ote(nc_final)\n    osys_final = nc_final._get_aberrations()\n\n    tab_opd_final = []\n    for n, error in zip(range(nb_of_maps), errors):\n        print(n, error)\n        \n        # change aberrations in wavefront map: example with random zernikes\n        # this map will be our perturbation map and we will add it to the initial map with a certain weight\n\n        # creating the perturbation map\n        #weight = 0.2\n        weight = error/100\n        for i in range(nb_zernikes):\n            #tmp = random.randint(-10,10)\n            tmp = random.randint(-1,1)\n            osys_perturb.zernike_coeffs[i] = weight*tmp*osys.zernike_coeffs[i]\n            osys_final.zernike_coeffs[i] = osys.zernike_coeffs[i] + weight*tmp*osys.zernike_coeffs[i]\n\n        # implementing and displaying the wavefront maps    \n        #display_ote_and_psf(nc, ote, title=\"Initial OPD and PSF\")\n\n        ote_perturb.reset()\n        ote_perturb.move_global_zernikes(osys_perturb.zernike_coeffs[0:10])\n        #display_ote_and_psf(nc_perturb, ote_perturb, title=\"Perturbed OPD and PSF\")\n\n        ote_final.reset()\n        ote_final.move_global_zernikes(osys_final.zernike_coeffs[0:10])\n        #display_ote_and_psf(nc_final, ote_final, title=\"Final OPD and PSF\")\n\n        rms = ote.rms()\n        rms_perturb = ote_perturb.rms()\n        rms_final = ote_final.rms()\n        print(rms,rms_perturb,rms_final)\n        print('')\n\n        #print(osys.zernike_coeffs)\n        #print('')\n        #print(osys_perturb.zernike_coeffs)\n        #print('')\n        #print(osys_final.zernike_coeffs)\n        #print('')\n\n        opd = poppy.zernike.opd_from_zernikes(osys.zernike_coeffs[0:10],\n                                                       npix=1024, basis=poppy.zernike.zernike_basis_faster)\n\n        opd_perturb = poppy.zernike.opd_from_zernikes(osys_perturb.zernike_coeffs[0:10],\n                                                       npix=1024, basis=poppy.zernike.zernike_basis_faster)\n\n        opd_final = poppy.zernike.opd_from_zernikes(osys_final.zernike_coeffs[0:10],\n                                                       npix=1024, basis=poppy.zernike.zernike_basis_faster)\n        \n        #tab_opd_final.append(opd_final)\n        \n        write_fits(path+'_opd'+str(n)+'.fits',opd)\n        write_fits(path+'_opd_perturb'+str(n)+'.fits',opd_perturb)\n        write_fits(path+'_opd_final'+str(n)+'.fits',opd_final)\n        \n        #plt.figure(figsize=(12,4))\n        #ax1 = plt.subplot(131)\n        #ax1.imshow(opd)\n        #ax1.set_title('initial wavefront map')\n        #ax2 = plt.subplot(132)\n        #ax2.imshow(opd_perturb)\n        #ax2.set_title('perturbed wavefront map')\n        #ax3 = plt.subplot(133)\n        #ax3.imshow(opd_final)\n        #ax3.set_title('sum of maps')\n        #plt.show()\n\n        wavefront_error = mse(np.nan_to_num(opd), np.nan_to_num(opd_final))\n        print('mse',error,wavefront_error)\n        print(\"MSE: %.2f\" % (wavefront_error*100))\n        \n    return tab_opd_final\n\ndef mse(image, reference):\n    # the 'Mean Squared Error' between the two images is the\n    # sum of the squared difference between the two images;\n    # NOTE: the two images must have the same dimension\n    import numpy as np\n    n_points = float(image.shape[0] * image.shape[1])\n    err = np.sum((image.astype(\"float\") - reference.astype(\"float\")) ** 2)\n    err /= n_points\n    err = np.sqrt(err)\n    #norm = 1\n    #norm = np.sum(reference) / n_points\n    norm = np.sqrt(np.sum((np.abs(reference))**2)/n_points)\n    print('erreur:',err/norm)\n    \n    # return the MSE, the lower the error, the more \"similar\"\n    # the two images are\n    return err/norm\n\ndef compare_images(imageA, imageB, title):\n    # compute the mean squared error and structural similarity\n    # index for the images\n    m = mse(imageA, imageB)\n    #s = ssim(imageA, imageB)\n    # setup the figure\n    fig = plt.figure(title)\n    plt.suptitle(\"MSE: %.2f\" % (m))\n    # show first image\n    ax = fig.add_subplot(1, 2, 1)\n    plt.imshow(imageA, cmap = plt.cm.gray)\n    plt.axis(\"off\")\n    # show the second image\n    ax = fig.add_subplot(1, 2, 2)\n    plt.imshow(imageB, cmap = plt.cm.gray)\n    plt.axis(\"off\")\n    # show the images\n    plt.show()\n    return m\n\ndef generate_wavefront_errors_correction(nb_of_maps,errors,nb_zernikes):\n    import poppy, webbpsf\n    import matplotlib.pyplot as plt\n    \n    # intial wavefront map\n    nc = webbpsf.NIRCam()\n    nc, ote = webbpsf.enable_adjustable_ote(nc)\n    osys = nc._get_aberrations()\n\n    # final wavefront map\n    nc_final = webbpsf.NIRCam()\n    nc_final, ote_final = webbpsf.enable_adjustable_ote(nc_final)\n    osys_final = nc_final._get_aberrations()\n\n    tab_wavefront_error = np.zeros(nb_of_maps)\n    tab_error = np.zeros(nb_of_maps)\n    for n, error in zip(range(nb_of_maps), errors):\n        print(n, error)\n        #print(zip(range(nb_of_maps)))\n        #print(errors)      \n        # change aberrations in wavefront map: example with random zernikes\n        # this map will be our perturbation map and we will add it to the initial map with a certain weight\n\n        # creating the perturbation map\n        #weight = 0.2\n        #weight = error/100\n        osys_corrected = osys.zernike_coeffs.copy()\n\n        for i in range(nb_zernikes):\n            if i<error+1:\n                osys_corrected[i] = 0\n            \n        print(osys.zernike_coeffs)\n        print(osys_corrected)\n        \n        opd = poppy.zernike.opd_from_zernikes(osys.zernike_coeffs,\n                                                       npix=1024, basis=poppy.zernike.zernike_basis_faster)\n\n        opd_corrected = poppy.zernike.opd_from_zernikes(osys_corrected,\n                                                       npix=1024, basis=poppy.zernike.zernike_basis_faster)\n        \n        wavefront_error = mse(np.nan_to_num(opd), np.nan_to_num(opd_corrected))\n        print('mse',error,wavefront_error)\n        \n        #tab_opd_final.append(opd_final)\n        \n        #write_fits('_opd'+str(n)+'.fits',opd)\n        #write_fits('_opd_corrected'+str(n)+'.fits',opd_corrected)\n        \n        plt.figure(figsize=(12,4))\n        ax1 = plt.subplot(131)\n        #ax1.imshow(opd,vmin=np.min(opd),vmax=np.max(opd))\n        ax1.imshow(opd)\n        ax1.set_title('initial wavefront map')\n        ax2 = plt.subplot(132)\n        #ax2.imshow(opd_corrected,vmin=np.min(opd),vmax=np.max(opd))\n        ax2.imshow(opd_corrected)\n        ax2.set_title('corrected wavefront map')\n        ax3 = plt.subplot(133)\n        ax3.imshow(opd - opd_corrected)\n        ax3.set_title('sum of maps')\n        plt.show()\n    \n        tab_wavefront_error[n] = wavefront_error\n        tab_error[n] = error\n        \n    return tab_wavefront_error, tab_error\n\n\ndef test_wavefront_errors():\n\n    # Import packages\n    #################\n    \n    import os\n    import numpy as np\n    import matplotlib.pyplot as plt\n    from matplotlib.colors import LogNorm\n    from datetime import date\n    from datetime import datetime\n    from astropy.io import fits\n\n    import random\n    import photutils\n\n    from Simulator import Simulation\n    #from Estimation import Estimation\n\n    os.environ['WEBBPSF_PATH'] = \"/Users/mygouf/Python/webbpsf/my_webbpsf-data3\"\n    os.environ['PYSYN_CDBS'] = \"/Users/mygouf/git/pynrc/cdbs/\"\n\n    import poppy\n    import webbpsf\n\n    # Set up directories\n    ####################\n    \n    today = date.today()\n    test_date = date = today.strftime(\"%Y%m%d\")\n    print(test_date)\n    \n    tests_directory = './Tests/'+test_date+'/'\n\n    if not os.path.exists(tests_directory):\n        os.makedirs(tests_directory)\n\n    directory = tests_directory+test_date+'_wavefront_errors/'\n    directory1 = directory\n    if not os.path.exists(directory):\n        os.makedirs(directory)\n\n    path = directory+date\n\n    # Parameters simulation images\n    ##############################\n\n    #transmission = '/Users/mygouf/Python/webbpsf/webbpsf-data4/jwst_pupil_RevW_npix1024.fits.gz'\n    #opd = '/Users/mygouf/Python/webbpsf/webbpsf-data4/NIRCam/OPD/OPD_RevW_ote_for_NIRCam_requirements.fits.gz'\n\n    # poppy paramaters\n    \n    pixelscale = 0.063\n    fov_arcsec = 10\n    #oversample = 4\n    #wavelength = 4.441e-6\n    \n    # webbPSF parameters\n\n    #filt = 'F444W'\n\n    \n    # Generate wavefront errors\n    ###########################\n\n    nb_of_maps = 10\n    errors = [1,2,3,4,5,10,20,30,40,50]\n    #nb_of_maps = 2\n    #errors = [1,2]\n    nb_zernikes = 35\n\n    tab_opd_final = generate_wavefront_errors(nb_of_maps,errors,nb_zernikes,path)\n\n\n    # Generating images with those wavefronts\n    #########################################\n\n    dict_simulation_parameters = {'fov_arcsec': fov_arcsec}\n    simulation = Simulation(dict_simulation_parameters)\n    \n    tab_images_initial = np.zeros((nb_of_maps,636,636))\n    tab_images_final = np.zeros((nb_of_maps,636,636))\n    for i in range(nb_of_maps):\n        dict_initial = simulation.create_image_from_opd_file(opd=path+'_opd'+str(i)+'.fits', input_noise=None)\n        dict_final = simulation.create_image_from_opd_file(opd=path+'_opd_final'+str(i)+'.fits', input_noise=None)\n\n        image_initial0 = dict_initial['image']\n        image_final0 = dict_final['image']\n\n        tab_images_initial[i] = image_initial0\n        tab_images_final[i] = image_final0\n    \n\n    # Compute contrast curves\n    #########################\n\n    contrast_initial_image1, vector_rad_initial_image1 = contrast_curve(tab_images_initial[0])\n    contrast_final_image1, vector_rad_final_image1 = contrast_curve(tab_images_initial[0]-tab_images_final[0])\n    contrast_initial_image2, vector_rad_initial_image2 = contrast_curve(tab_images_initial[1])\n    contrast_final_image2, vector_rad_final_image2 = contrast_curve(tab_images_initial[1]-tab_images_final[1])\n    contrast_initial_image3, vector_rad_initial_image3 = contrast_curve(tab_images_initial[2])\n    contrast_final_image3, vector_rad_final_image3 = contrast_curve(tab_images_initial[2]-tab_images_final[2])\n    contrast_initial_image4, vector_rad_initial_image4 = contrast_curve(tab_images_initial[3])\n    contrast_final_image4, vector_rad_final_image4 = contrast_curve(tab_images_initial[3]-tab_images_final[3])\n    contrast_initial_image5, vector_rad_initial_image5 = contrast_curve(tab_images_initial[4])\n    contrast_final_image5, vector_rad_final_image5 = contrast_curve(tab_images_initial[4]-tab_images_final[4])\n    contrast_initial_image6, vector_rad_initial_image6 = contrast_curve(tab_images_initial[5])\n    contrast_final_image6, vector_rad_final_image6 = contrast_curve(tab_images_initial[5]-tab_images_final[5])\n    contrast_initial_image7, vector_rad_initial_image7 = contrast_curve(tab_images_initial[6])\n    contrast_final_image7, vector_rad_final_image7 = contrast_curve(tab_images_initial[6]-tab_images_final[6])\n    contrast_initial_image8, vector_rad_initial_image8 = contrast_curve(tab_images_initial[7])\n    contrast_final_image8, vector_rad_final_image8 = contrast_curve(tab_images_initial[7]-tab_images_final[7])\n    contrast_initial_image9, vector_rad_initial_image9 = contrast_curve(tab_images_initial[8])\n    contrast_final_image9, vector_rad_final_image9 = contrast_curve(tab_images_initial[8]-tab_images_final[8])\n    contrast_initial_image10, vector_rad_initial_image10 = contrast_curve(tab_images_initial[9])\n    contrast_final_image10, vector_rad_final_image10 = contrast_curve(tab_images_initial[9]-tab_images_final[9])\n\n\n    # Create and saving figures\n    ###########################\n\n    pxscale = pixelscale\n\n    fig = plt.figure(figsize=(8,4))\n    ax1 = fig.add_subplot(111)\n    plt.plot(vector_rad_initial_image1*pxscale, contrast_initial_image1/np.max(tab_images_initial[0]), label='Raw')\n    plt.plot(vector_rad_final_image1*pxscale, contrast_final_image1/np.max(tab_images_initial[0]), label='1% error',linestyle='--')\n    plt.plot(vector_rad_final_image5*pxscale, contrast_final_image5/np.max(tab_images_initial[4]), label='5% error',linestyle='--')\n    plt.plot(vector_rad_final_image6*pxscale, contrast_final_image6/np.max(tab_images_initial[5]), label='10% error',linestyle='--')\n    plt.plot(vector_rad_final_image10*pxscale, contrast_final_image10/np.max(tab_images_initial[9]), label='50% error',linestyle='--')\n\n    plt.xlabel('Angular separation [arcsec]')\n    plt.ylabel('Contrast')\n    plt.grid('on', which='both', alpha=0.2, linestyle='solid')\n    ax1.set_yscale('log')\n    ax1.set_xlim(0, 4)\n    plt.legend()\n    plt.show()\n\n    fname = path+'_contrast_curves.pdf'       \n    fig.savefig(fname, dpi=None, facecolor='w', edgecolor='w',\n                orientation='portrait', papertype=None, format=None,\n                transparent=False, pad_inches=0.1,\n                frameon=None, metadata=None,bbox_inches = 'tight')\n    print('Saving file:',fname)\n\n\n    # Create and saving figures\n    ###########################\n\n    contrast_raw = contrast_initial_image1/np.max(tab_images_initial[0])\n    contrast1 = contrast_final_image1/np.max(tab_images_initial[0])\n    contrast5 = contrast_final_image5/np.max(tab_images_initial[4])\n    contrast6 = contrast_final_image6/np.max(tab_images_initial[5])\n    contrast10 = contrast_final_image10/np.max(tab_images_initial[9])\n                                              \n    fig = plt.figure(figsize=(8,4))\n    ax1 = fig.add_subplot(111)\n    plt.plot(vector_rad_initial_image1*pxscale, contrast_raw/contrast_initial_image1/np.max(tab_images_initial[0]), label='Raw')\n    plt.plot(vector_rad_final_image1*pxscale, contrast_raw/contrast1, label='1% error',linestyle='--')\n    plt.plot(vector_rad_final_image5*pxscale, contrast_raw/contrast5, label='5% error',linestyle='--')\n    plt.plot(vector_rad_final_image6*pxscale, contrast_raw/contrast6, label='10% error',linestyle='--')\n    plt.plot(vector_rad_final_image10*pxscale, contrast_raw/contrast10, label='50% error',linestyle='--')\n    \n    plt.xlabel('Angular separation [arcsec]')\n    plt.ylabel('Contrast Gain')\n    plt.grid('on', which='both', alpha=0.2, linestyle='solid')\n    ax1.set_xlim(0, 4)\n    ax1.set_ylim(0, 50)\n    ax1.hlines([0,10], 0, 10, colors='k', linestyles='solid', label='', data=None)\n    \n    plt.legend()\n    plt.show()\n\n    fname = path+'_contrast_gain_curves.pdf'       \n    fig.savefig(fname, dpi=None, facecolor='w', edgecolor='w',\n                orientation='portrait', papertype=None, format=None,\n                transparent=False, pad_inches=0.1,\n                frameon=None, metadata=None,bbox_inches = 'tight')\n    print('Saving file:',fname)\n\n\n    # How many Zernike coeff. does that correspond to?\n    ##################################################\n\n    nb_zernikes = 36\n    errors = np.linspace(0,nb_zernikes,nb_zernikes+1) # actually number of corrected zernike coefficients\n    nb_of_maps = len(errors)\n    print(nb_of_maps)\n    print(errors)\n    # nb_of_maps = 2\n    # errors = [1,36]\n\n    # nb_of_maps = 1\n    # errors = [1]\n\n    tab_wavefront_error, tab_error = generate_wavefront_errors_correction(nb_of_maps,errors,nb_zernikes)\n\n    print('Number of corrected Zernike coefficients:',tab_error)\n    print('Error in percent:',tab_wavefront_error)\n\n    \n    # Save fits files\n    #################\n\n    #\n\n    \nif __name__ == \"__main__\":\n    \n    from datetime import date\n    from astropy.io import fits\n    import os\n    import numpy as np\n    \n    test_wavefront_errors()\n\n    today = date.today()\n    date = test_date = today.strftime(\"%Y%m%d\")\n\n    date_ref = '20200308'\n    \n    tests_directory = './Tests/'+test_date+'/'\n\n    if not os.path.exists(tests_directory):\n        os.makedirs(tests_directory)\n        \n    directory = tests_directory+test_date+'_wavefront_errors/'\n    if not os.path.exists(directory):\n        os.makedirs(directory)\n\n    #filename = directory+date+test+'_Zernike_coefficients_estimation.fits'\n    #filename_ref = '../Reference_Tests/'+date_ref+'_wavefront_errors/'+date_ref+'_wavefront_errors.fits'\n    #hdul = fits.open(filename)\n    #hdul_ref = fits.open(filename)\n    #image = hdul[0].data\n    #image_ref = hdul[0].data\n\n    #diff1 = np.sum(image-image_ref)\n\n    #filename = directory+date+test+'_Zernike_coefficients_estimation.fits'\n    #filename_ref = '../Reference_Tests/'+date_ref+'_wavefront_errors/'+date_ref+'_psf_webbpsf.fits'\n    #hdul = fits.open(filename)\n    #hdul_ref = fits.open(filename)\n    #image = hdul[0].data\n    #image_ref = hdul[0].data\n\n    #diff1 = np.sum(image-image_ref)\n    \n    #print(diff1)\n\n    #if np.sum([diff1,diff2]) == 0:\n    #    print(\"Test 'Wavefront errors' passed\")\n    #else:\n    #    print(\"Test 'Wavefront errors' not passed\")\n    \n", "meta": {"hexsha": "43a9fc66f4cd32ff532305b05fe6681c732e9ccc", "size": 21971, "ext": "py", "lang": "Python", "max_stars_repo_path": "dev_utils/20200617_Shared_Package_shared/Wavefront Errors Tests/20200308_test_wavefront_errors.py", "max_stars_repo_name": "JarronL/pyNRC", "max_stars_repo_head_hexsha": "0354f0635dd4c5391ca3a769fa9e5ead83661c30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-01-09T05:11:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T18:30:41.000Z", "max_issues_repo_path": "dev_utils/20200617_Shared_Package_shared/Wavefront Errors Tests/20200308_test_wavefront_errors.py", "max_issues_repo_name": "JarronL/pyNRC", "max_issues_repo_head_hexsha": "0354f0635dd4c5391ca3a769fa9e5ead83661c30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2017-05-25T04:45:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T18:31:48.000Z", "max_forks_repo_path": "dev_utils/20200617_Shared_Package_shared/Wavefront Errors Tests/20200308_test_wavefront_errors.py", "max_forks_repo_name": "JarronL/pyNRC", "max_forks_repo_head_hexsha": "0354f0635dd4c5391ca3a769fa9e5ead83661c30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2017-01-27T22:40:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T18:41:46.000Z", "avg_line_length": 35.9003267974, "max_line_length": 134, "alphanum_fraction": 0.6553183742, "include": true, "reason": "import numpy,from astropy", "num_tokens": 5933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19319382917512679}}
{"text": "# Copyright 2019-present NAVER Corp.\n# CC BY-NC-SA 3.0\n# Available only for non-commercial use\n\nimport pdb\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n\"\"\" Different samplers, each specifying how to sample pixels for the AP loss.\n\"\"\"\n\n\nclass FullSampler(nn.Module):\n    \"\"\" all pixels are selected\n        - feats: keypoint descriptors\n        - confs: reliability values\n    \"\"\"\n    def __init__(self):\n        nn.Module.__init__(self)\n        self.mode = 'bilinear'\n        self.padding = 'zeros'\n\n    @staticmethod\n    def _aflow_to_grid(aflow):\n        H, W = aflow.shape[2:]\n        grid = aflow.permute(0,2,3,1).clone()\n        grid[:,:,:,0] *= 2/(W-1)\n        grid[:,:,:,1] *= 2/(H-1)\n        grid -= 1\n        grid[torch.isnan(grid)] = 9e9 # invalids\n        return grid\n    \n    def _warp(self, feats, confs, aflow):\n        if isinstance(aflow, tuple): return aflow # result was precomputed\n        feat1, feat2 = feats\n        conf1, conf2 = confs if confs else (None,None)\n    \n        B, two, H, W = aflow.shape\n        D = feat1.shape[1]\n        assert feat1.shape == feat2.shape == (B, D, H, W) # D = 128, B = batch\n        assert conf1.shape == conf2.shape == (B, 1, H, W) if confs else True\n\n        # warp img2 to img1\n        grid = self._aflow_to_grid(aflow)\n        ones2 = feat2.new_ones(feat2[:,0:1].shape)\n        feat2to1 = F.grid_sample(feat2, grid, mode=self.mode, padding_mode=self.padding)\n        mask2to1 = F.grid_sample(ones2, grid, mode='nearest', padding_mode='zeros')\n        conf2to1 = F.grid_sample(conf2, grid, mode=self.mode, padding_mode=self.padding) \\\n                   if confs else None\n        return feat2to1, mask2to1.byte(), conf2to1\n\n    def _warp_positions(self, aflow):\n        B, two, H, W = aflow.shape\n        assert two == 2\n        \n        Y = torch.arange(H, device=aflow.device)\n        X = torch.arange(W, device=aflow.device)\n        XY = torch.stack(torch.meshgrid(Y,X)[::-1], dim=0)\n        XY = XY[None].expand(B, 2, H, W).float()\n        \n        grid = self._aflow_to_grid(aflow)\n        XY2 = F.grid_sample(XY, grid, mode='bilinear', padding_mode='zeros')\n        return XY, XY2\n\n\n\nclass SubSampler (FullSampler):\n    \"\"\" pixels are selected in an uniformly spaced grid\n    \"\"\"\n    def __init__(self, border, subq, subd, perimage=False):\n        FullSampler.__init__(self)\n        assert subq % subd == 0, 'subq must be multiple of subd'\n        self.sub_q = subq\n        self.sub_d = subd\n        self.border = border\n        self.perimage = perimage\n\n    def __repr__(self):\n        return \"SubSampler(border=%d, subq=%d, subd=%d, perimage=%d)\" % (\n            self.border, self.sub_q, self.sub_d, self.perimage)\n\n    def __call__(self, feats, confs, aflow):\n        feat1, conf1 = feats[0], (confs[0] if confs else None)\n        # warp with optical flow in img1 coords\n        feat2, mask2, conf2 = self._warp(feats, confs, aflow)\n        \n        # subsample img1\n        slq = slice(self.border, -self.border or None, self.sub_q)\n        feat1 = feat1[:, :, slq, slq]\n        conf1 = conf1[:, :, slq, slq] if confs else None\n        # subsample img2\n        sld = slice(self.border, -self.border or None, self.sub_d)\n        feat2 = feat2[:, :, sld, sld]\n        mask2 = mask2[:, :, sld, sld]\n        conf2 = conf2[:, :, sld, sld] if confs else None\n        \n        B, D, Hq, Wq = feat1.shape\n        B, D, Hd, Wd = feat2.shape\n        \n        # compute gt\n        if self.perimage or self.sub_q != self.sub_d:\n            # compute ground-truth by comparing pixel indices\n            f = feats[0][0:1,0] if self.perimage else feats[0][:,0]\n            idxs = torch.arange(f.numel(), dtype=torch.int64, device=feat1.device).view(f.shape)\n            idxs1 = idxs[:, slq, slq].reshape(-1,Hq*Wq)\n            idxs2 = idxs[:, sld, sld].reshape(-1,Hd*Wd)\n            if self.perimage:\n                gt = (idxs1[0].view(-1,1) == idxs2[0].view(1,-1))\n                gt = gt[None,:,:].expand(B, Hq*Wq, Hd*Wd)\n            else :\n                gt = (idxs1.view(-1,1) == idxs2.view(1,-1)) \n        else:\n            gt = torch.eye(feat1[:,0].numel(), dtype=torch.uint8, device=feat1.device) # always binary for AP loss\n        \n        # compute all images together\n        queries  =  feat1.reshape(B,D,-1) # B x D x (Hq x Wq)\n        database =  feat2.reshape(B,D,-1) # B x D x (Hd x Wd)\n        if self.perimage:\n            queries  =  queries.transpose(1,2) # B x (Hd x Wd) x D\n            scores = torch.bmm(queries, database) # B x (Hq x Wq) x (Hd x Wd)\n        else:\n            queries  =  queries .transpose(1,2).reshape(-1,D) # (B x Hq x Wq) x D\n            database =  database.transpose(1,0).reshape(D,-1) # D x (B x Hd x Wd)\n            scores = torch.matmul(queries, database) # (B x Hq x Wq) x (B x Hd x Wd)\n\n        # compute reliability\n        qconf = (conf1 + conf2)/2 if confs else None\n\n        assert gt.shape == scores.shape\n        return scores, gt, mask2, qconf\n\n\n\nclass NghSampler (FullSampler):\n    \"\"\" all pixels in a small neighborhood\n    \"\"\"\n    def __init__(self, ngh, subq=1, subd=1, ignore=1, border=None):\n        FullSampler.__init__(self)\n        assert 0 <= ignore < ngh\n        self.ngh = ngh\n        self.ignore = ignore\n        assert subd <= ngh\n        self.sub_q = subq\n        self.sub_d = subd\n        if border is None: border = ngh\n        assert border >= ngh, 'border has to be larger than ngh'\n        self.border = border\n\n    def __repr__(self):\n        return \"NghSampler(ngh=%d, subq=%d, subd=%d, ignore=%d, border=%d)\" % (\n            self.ngh, self.sub_q, self.sub_d, self.ignore, self.border)\n\n    def trans(self, arr, i, j):\n        s = lambda i: slice(self.border+i, i-self.border or None, self.sub_q)\n        return arr[:,:,s(j),s(i)]\n\n    def __call__(self, feats, confs, aflow):\n        feat1, conf1 = feats[0], (confs[0] if confs else None)\n        # warp with optical flow in img1 coords\n        feat2, mask2, conf2 = self._warp(feats, confs, aflow)\n        \n        qfeat = self.trans(feat1,0,0)\n        qconf = (self.trans(conf1,0,0) + self.trans(conf2,0,0)) / 2 if confs else None\n        mask2 = self.trans(mask2,0,0)\n        scores_at = lambda i,j: (qfeat * self.trans(feat2,i,j)).sum(dim=1)\n        \n        # compute scores for all neighbors\n        B, D = feat1.shape[:2]\n        min_d = self.ignore**2\n        max_d = self.ngh**2\n        rad = (self.ngh//self.sub_d) * self.ngh # make an integer multiple\n        negs = []\n        offsets = []\n        for j in range(-rad, rad+1, self.sub_d):\n          for i in range(-rad, rad+1, self.sub_d):\n            if not(min_d < i*i + j*j <= max_d): \n                continue # out of scope\n            offsets.append((i,j)) # Note: this list is just for debug\n            negs.append( scores_at(i,j) )\n        \n        scores = torch.stack([scores_at(0,0)] + negs, dim=-1)\n        gt = scores.new_zeros(scores.shape, dtype=torch.uint8)\n        gt[..., 0] = 1 # only the center point is positive\n\n        return scores, gt, mask2, qconf\n\n\n\nclass FarNearSampler (FullSampler):\n    \"\"\" Sample pixels from *both* a small neighborhood *and* far-away pixels.\n        \n    How it works?\n        1) Queries are sampled from img1,\n            - at least `border` pixels from borders and \n            - on a grid with step = `subq`\n            \n        2) Close database pixels \n            - from the corresponding image (img2),\n            - within a `ngh` distance radius \n            - on a grid with step = `subd_ngh`\n            - ignored if distance to query is >0 and <=`ignore`\n            \n        3) Far-away database pixels from ,\n            - from all batch images in `img2`\n            - at least `border` pixels from borders\n            - on a grid with step = `subd_far`\n    \"\"\"\n    def __init__(self, subq, ngh, subd_ngh, subd_far, border=None, ignore=1, \n                       maxpool_ngh=False ):\n        FullSampler.__init__(self)\n        border = border or ngh\n        assert ignore < ngh < subd_far, 'neighborhood needs to be smaller than far step'\n        self.close_sampler = NghSampler(ngh=ngh, subq=subq, subd=subd_ngh, \n                ignore=not(maxpool_ngh), border=border)\n        self.faraway_sampler = SubSampler(border=border, subq=subq, subd=subd_far)\n        self.maxpool_ngh = maxpool_ngh\n\n    def __repr__(self):\n        c,f = self.close_sampler, self.faraway_sampler\n        res = \"FarNearSampler(subq=%d, ngh=%d\" % (c.sub_q, c.ngh)\n        res += \", subd_ngh=%d, subd_far=%d\" % (c.sub_d, f.sub_d)\n        res += \", border=%d, ign=%d\" % (f.border, c.ignore)\n        res += \", maxpool_ngh=%d\" % self.maxpool_ngh\n        return res+')'\n\n    def __call__(self, feats, confs, aflow):\n        # warp with optical flow in img1 coords\n        aflow = self._warp(feats, confs, aflow)\n\n        # sample ngh pixels\n        scores1, gt1, msk1, conf1 = self.close_sampler(feats, confs, aflow)\n        scores1, gt1 = scores1.view(-1,scores1.shape[-1]), gt1.view(-1,gt1.shape[-1])\n        if self.maxpool_ngh:\n            # we consider all scores from ngh as potential positives\n            scores1, self._cached_maxpool_ngh = scores1.max(dim=1,keepdim=True)\n            gt1 = gt1[:, 0:1]\n\n        # sample far pixels\n        scores2, gt2, msk2, conf2 = self.faraway_sampler(feats, confs, aflow)\n        # assert (msk1 == msk2).all()\n        # assert (conf1 == conf2).all()\n\n        return (torch.cat((scores1,scores2),dim=1), \n                torch.cat((gt1,    gt2),    dim=1), \n                msk1, conf1 if confs else None)\n\n\nclass NghSampler2 (nn.Module):\n    \"\"\" Similar to NghSampler, but doesnt warp the 2nd image.\n    Distance to GT =>  0 ... pos_d ... neg_d ... ngh\n    Pixel label    =>  + + + + + + 0 0 - - - - - - -\n    \n    Subsample on query side: if > 0, regular grid\n                                < 0, random points \n    In both cases, the number of query points is = W*H/subq**2\n    \"\"\"\n    def __init__(self, ngh, subq=1, subd=1, pos_d=0, neg_d=2, border=None,\n                       maxpool_pos=True, subd_neg=0):\n        nn.Module.__init__(self)\n        assert 0 <= pos_d < neg_d <= (ngh if ngh else 99)\n        self.ngh = ngh\n        self.pos_d = pos_d\n        self.neg_d = neg_d\n        assert subd <= ngh or ngh == 0\n        assert subq != 0\n        self.sub_q = subq\n        self.sub_d = subd\n        self.sub_d_neg = subd_neg\n        if border is None: border = ngh\n        assert border >= ngh, 'border has to be larger than ngh'\n        self.border = border\n        self.maxpool_pos = maxpool_pos\n        self.precompute_offsets()\n\n    def precompute_offsets(self):\n        pos_d2 = self.pos_d**2\n        neg_d2 = self.neg_d**2\n        rad2 = self.ngh**2\n        rad = (self.ngh//self.sub_d) * self.ngh # make an integer multiple\n        pos = []\n        neg = []\n        for j in range(-rad, rad+1, self.sub_d):\n          for i in range(-rad, rad+1, self.sub_d):\n            d2 = i*i + j*j\n            if d2 <= pos_d2:\n                pos.append( (i,j) )\n            elif neg_d2 <= d2 <= rad2: \n                neg.append( (i,j) )\n\n        self.register_buffer('pos_offsets', torch.LongTensor(pos).view(-1,2).t())\n        self.register_buffer('neg_offsets', torch.LongTensor(neg).view(-1,2).t())\n\n    def gen_grid(self, step, aflow):\n        B, two, H, W = aflow.shape\n        dev = aflow.device\n        b1 = torch.arange(B, device=dev)\n        if step > 0:\n            # regular grid\n            x1 = torch.arange(self.border, W-self.border, step, device=dev)\n            y1 = torch.arange(self.border, H-self.border, step, device=dev)\n            H1, W1 = len(y1), len(x1)\n            x1 = x1[None,None,:].expand(B,H1,W1).reshape(-1)\n            y1 = y1[None,:,None].expand(B,H1,W1).reshape(-1)\n            b1 = b1[:,None,None].expand(B,H1,W1).reshape(-1)\n            shape = (B, H1, W1)\n        else:\n            # randomly spread\n            n = (H - 2*self.border) * (W - 2*self.border) // step**2\n            x1 = torch.randint(self.border, W-self.border, (n,), device=dev)\n            y1 = torch.randint(self.border, H-self.border, (n,), device=dev)\n            x1 = x1[None,:].expand(B,n).reshape(-1)\n            y1 = y1[None,:].expand(B,n).reshape(-1)\n            b1 = b1[:,None].expand(B,n).reshape(-1)\n            shape = (B, n)\n        return b1, y1, x1, shape\n\n    def forward(self, feats, confs, aflow, **kw):\n        B, two, H, W = aflow.shape\n        assert two == 2\n        feat1, conf1 = feats[0], (confs[0] if confs else None)\n        feat2, conf2 = feats[1], (confs[1] if confs else None)\n        \n        # positions in the first image\n        b1, y1, x1, shape = self.gen_grid(self.sub_q, aflow)\n\n        # sample features from first image\n        feat1 = feat1[b1, :, y1, x1]\n        qconf = conf1[b1, :, y1, x1].view(shape) if confs else None\n        \n        #sample GT from second image\n        b2 = b1\n        xy2 = (aflow[b1, :, y1, x1] + 0.5).long().t()\n        mask = (0 <= xy2[0]) * (0 <= xy2[1]) * (xy2[0] < W) * (xy2[1] < H)\n        mask = mask.view(shape)\n        \n        def clamp(xy):\n            torch.clamp(xy[0], 0, W-1, out=xy[0])\n            torch.clamp(xy[1], 0, H-1, out=xy[1])\n            return xy\n        \n        # compute positive scores\n        xy2p = clamp(xy2[:,None,:] + self.pos_offsets[:,:,None])\n        pscores = (feat1[None,:,:] * feat2[b2, :, xy2p[1], xy2p[0]]).sum(dim=-1).t()\n#        xy1p = clamp(torch.stack((x1,y1))[:,None,:] + self.pos_offsets[:,:,None])\n#        grid = FullSampler._aflow_to_grid(aflow)\n#        feat2p = F.grid_sample(feat2, grid, mode='bilinear', padding_mode='border')\n#        pscores = (feat1[None,:,:] * feat2p[b1,:,xy1p[1], xy1p[0]]).sum(dim=-1).t()\n        if self.maxpool_pos:\n            pscores, pos = pscores.max(dim=1, keepdim=True)\n            if confs: \n                sel = clamp(xy2 + self.pos_offsets[:,pos.view(-1)])\n                qconf = (qconf + conf2[b2, :, sel[1], sel[0]].view(shape))/2\n        \n        # compute negative scores\n        xy2n = clamp(xy2[:,None,:] + self.neg_offsets[:,:,None])\n        nscores = (feat1[None,:,:] * feat2[b2, :, xy2n[1], xy2n[0]]).sum(dim=-1).t()\n\n        if self.sub_d_neg:\n            # add distractors from a grid\n            b3, y3, x3, _ = self.gen_grid(self.sub_d_neg, aflow)\n            distractors = feat2[b3, :, y3, x3]\n            dscores = torch.matmul(feat1, distractors.t())\n            del distractors\n            \n            # remove scores that corresponds to positives or nulls\n            dis2 = (x3 - xy2[0][:,None])**2 + (y3 - xy2[1][:,None])**2\n            dis2 += (b3 != b2[:,None]).long() * self.neg_d**2\n            dscores[dis2 < self.neg_d**2] = 0\n            \n            scores = torch.cat((pscores, nscores, dscores), dim=1)\n        else:\n            # concat everything\n            scores = torch.cat((pscores, nscores), dim=1)\n\n        gt = scores.new_zeros(scores.shape, dtype=torch.uint8)\n        gt[:, :pscores.shape[1]] = 1\n\n        return scores, gt, mask, qconf\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "9fede70d3a04d7f31a1d414eace0aaf3729e8235", "size": 15031, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyslam/thirdparty/r2d2/nets/sampler.py", "max_stars_repo_name": "dysdsyd/VO_benchmark", "max_stars_repo_head_hexsha": "a7602edab934419c1ec73618ee655e18026f834f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-11T09:13:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T01:39:56.000Z", "max_issues_repo_path": "pyslam/thirdparty/r2d2/nets/sampler.py", "max_issues_repo_name": "dysdsyd/VO_benchmark", "max_issues_repo_head_hexsha": "a7602edab934419c1ec73618ee655e18026f834f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyslam/thirdparty/r2d2/nets/sampler.py", "max_forks_repo_name": "dysdsyd/VO_benchmark", "max_forks_repo_head_hexsha": "a7602edab934419c1ec73618ee655e18026f834f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.442455243, "max_line_length": 114, "alphanum_fraction": 0.5495309693, "include": true, "reason": "import numpy", "num_tokens": 4510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.37754065479083276, "lm_q1q2_score": 0.19319382200735233}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 28 09:28:15 2017\n\n@author: tkoller\n\"\"\"\nimport warnings\nimport casadi as cas\nimport numpy as np\nfrom casadi import MX, mtimes, vertcat, sum2, sqrt\nfrom casadi import reshape as cas_reshape\nfrom .gp_reachability_casadi import lin_ellipsoid_safety_distance\nfrom .gp_reachability_casadi import multi_step_reachability as cas_multistep\nfrom .uncertainty_propagation_casadi import mean_equivalent_multistep, \\\n    multi_step_taylor_symbolic\nfrom .utils import dlqr, feedback_ctrl, array_of_vec_to_array_of_mat\n\nATTR_NAMES_PERF = ['type_perf_traj', 'n_perf', 'r', 'perf_has_fb']\nDEFAULT_OPT_PERF = {'type_perf_traj': 'mean_equivalent', 'n_perf': 5, 'r': 1,\n                    'perf_has_fb': True}\n\nATTR_NAMES_ENV = ['l_mu', 'l_sigma', 'h_mat_safe', 'h_safe', 'lin_model', 'ctrl_bounds',\n                  'safe_policy', 'h_mat_obs', 'h_obs']\nDEFAULT_OPT_ENV = {'ctrl_bounds': None, 'safe_policy': None, 'lin_model': None,\n                   'h_mat_obs': None, 'h_obs': None}\n\n\nclass SimpleSafeMPC:\n    \"\"\" Simplified implementation of the SafeMPC algorithm in Casadi\n\n    \"\"\"\n\n    def __init__(self, n_safe, ssm, opt_env, wx_cost, wu_cost, beta_safety=2.5,\n                 rhc=True,\n                 safe_policy=None, opt_perf_trajectory={}, lin_trafo_gp_input=None, opts_solver=None, verbosity=0):\n        \"\"\" Initialize the SafeMPC object with dynamic model information\n\n        Parameters\n        ----------\n        n_safe: int\n            Length of the safety trajectory (number of safe controls)\n        ssm: StateSpaceModel\n            The underlying statistical model\n        opt_env: dict\n            Dictionary of environment options. List of accepted attributes are given in ATTR_NAMES_ENV.\n            All values that are NOT specified in DEFAULT_OPT_ENV are mandatory.\n        wx_cost: n_x x n_x np.ndarray[float]\n            State cost matrix for the LQR\n        wu_cost: n_u x n_u np.ndarray[float]\n            Control cost matrix for the LQR\n        beta_safety: float, optional\n            The safety coefficient for the confidence intervals (Denoted by \\beta in paper)\n        rhc: boolean, optional\n            True, if we want to reinitialize the SafeMPC problem in a receding horizon fashion\n        lin_model: Tuple, optional\n            The linear prior model. Consists of tuple (a,b) that defines the linear system.\n            Default is: x_{t+1} = x_t, i.e. (I,0)\n        ctrl_bounds: n_u x 2 np.ndarray[float], optional\n            Upper and lower bound per control input\n        safe_policy: function, optional\n            Custom safe policy u_t^safe = safe_policy(x_t)\n            Default: LQR based on prior model and wx_cost,wu_cost\n        opt_perf_trajectory: dict, optional\n            Dictionary of environment options. List of accepted attributes are given in ATTR_NAMES_PERF.\n            All values that are NOT specified in DEFAULT_OPT_PERF are mandatory.\n        lin_trafo_gp_input: n_x_gp_in x n_x np.ndarray[float], optional\n            Allows for a linear transformation of the gp input (e.g. removing an input)\n\n\n        \"\"\"\n        self.rhc = rhc\n        self.ssm = ssm\n        self.ssm_forward = ssm.get_forward_model_casadi(True)\n        self.n_safe = n_safe\n        self.n_fail = self.n_safe  # initialize s.t. there is no backup strategy\n        self.n_s = self.ssm.num_states\n        self.n_u = self.ssm.num_actions\n        self.has_openloop = False\n        self.opts_solver = opts_solver\n\n        self.safe_policy = safe_policy\n\n        self.cost_func = None  # This is updated wheenver the solver is newly initialized (possibly again with None)\n\n        self._set_attributes_from_dict(ATTR_NAMES_ENV, DEFAULT_OPT_ENV, opt_env)\n\n        self.lin_trafo_gp_input = lin_trafo_gp_input\n        if self.lin_trafo_gp_input is None:\n            self.lin_trafo_gp_input = np.eye(self.n_s)\n\n        if self.h_mat_obs is None:\n            m_obs_mat = 0\n        else:\n            m_obs_mat, n_s_obs = np.shape(self.h_mat_obs)\n            assert n_s_obs == self.n_s, \" Wrong shape of obstacle matrix\"\n            assert np.shape(self.h_obs) == (m_obs_mat,\n                                            1), \" Shapes of obstacle linear inequality matrix/vector must match \"\n        self.m_obs = m_obs_mat\n\n        m_safe_mat, n_s_safe = np.shape(self.h_mat_safe)\n        assert n_s_safe == self.n_s, \" Wrong shape of safety matrix\"\n        assert np.shape(self.h_safe) == (\n            m_safe_mat,\n            1), \" Shapes of safety linear inequality matrix/vector must match \"\n        self.m_safe = m_safe_mat\n\n        # init safety constraints evaluator\n        p_cas = MX.sym('p', (self.n_s, self.n_u))\n        q_cas = MX.sym('q', (self.n_s, self.n_s))\n        g_val_term_cas = lin_ellipsoid_safety_distance(p_cas, q_cas, self.h_mat_safe,\n                                                       self.h_safe)\n        self.g_term_cas = cas.Function(\"g_term\", [p_cas, q_cas], [g_val_term_cas])\n\n        if not self.h_mat_obs is None:\n            g_val_interm_cas = lin_ellipsoid_safety_distance(p_cas, q_cas,\n                                                             self.h_mat_obs, self.h_obs)\n            self.g_interm_cas = cas.Function(\"g_interm\", [p_cas, q_cas],\n                                             [g_val_term_cas])\n\n        self.has_ctrl_bounds = False\n\n        if not self.ctrl_bounds is None:\n            self.has_ctrl_bounds = True\n            assert np.shape(self.ctrl_bounds) == (self.n_u, 2), \"\"\"control bounds need\n            to be of shape n_u x 2 with i,0 lower bound and i,1 upper bound per dimension\"\"\"\n\n        self.wx_cost = wx_cost\n        self.wu_cost = wu_cost\n        self.wx_feedback = wx_cost\n        self.wu_feedback = 1 * wu_cost\n\n        self.do_shift_solution = True\n        self.solver_initialized = False\n\n        self.beta_safety = beta_safety\n        self.verbosity = verbosity\n\n        # SET ALL ATTRIBUTES FOR THE ENVIRONMENT\n\n        self.lin_prior = False\n        self.a = np.eye(self.n_s)\n        self.b = np.zeros((self.n_s, self.n_u))\n        if not self.lin_model is None:\n            self.a, self.b = self.lin_model\n            self.lin_prior = True\n            if self.safe_policy is None:\n                # no safe policy specified? Use lqr as safe policy\n                K = self.get_lqr_feedback()\n                self.safe_policy = lambda x: np.dot(K, x)\n\n        # if self.performance_trajectory is None:\n        #    self.performance_trajectory = mean_equivalent\n        self._set_attributes_from_dict(ATTR_NAMES_PERF, DEFAULT_OPT_PERF,\n                                       opt_perf_trajectory)\n        self._set_perf_trajectory(self.type_perf_traj)\n\n        self.k_fb_all = None\n        if self.safe_policy is None:\n            warnings.warn(\"No SafePolicy!\")\n\n        # init safe\n\n    def init_solver(self, cost_func=None, opt_x0=False, init_uncertainty=False):\n        \"\"\" Initialize a casadi solver object corresponding to the SafeMPC optimization problem\n\n\n\n        Parameters:\n        -----------\n        cost_func: Function\n            A function which admits casadi.SX type inputs\n            and returns a scalar function\n            If performance controls exist function has to be of the form:\n                cost_func(p_all,k_ff_all,x_perf,u_perf)\n            otherwise:\n                cost_func(p_all,k_ff_all)\n\n\n        \"\"\"\n        self.cost_func = cost_func\n        self.opt_x0 = opt_x0\n        self.init_uncertainty = init_uncertainty\n\n        u_0 = MX.sym(\"init_control\", (self.n_u, 1))\n        k_ff_all = MX.sym(\"feed-forward control\", (self.n_safe - 1, self.n_u))\n        g = []\n        lbg = []\n        ubg = []\n        g_name = []\n\n        p_0 = MX.sym(\"initial state\", (self.n_s, 1))\n        q_0 = None\n        k_fb_0 = None\n        if init_uncertainty:\n            q_0 = MX.sym(\"init uncertainty\", (self.n_s, self.n_s))\n            k_fb_0 = MX.sym(\"init feddback control matrix\", (self.n_u, self.n_s))\n\n        k_fb_safe = MX.sym(\"feedback matrices\",\n                        (self.n_safe - 1, self.n_s * self.n_u))\n\n        p_all, q_all, gp_sigma_pred_safe_all = cas_multistep(p_0, u_0, k_fb_safe, k_ff_all,\n                                                             self.ssm_forward, self.l_mu,\n                                                             self.l_sigma,\n                                                             self.beta_safety, self.a,\n                                                             self.b,\n                                                             self.lin_trafo_gp_input, q_0, k_fb_0)\n\n        # generate open_loop trajectory function [vertcat(x_0,u_0)],[f_x])\n\n        if init_uncertainty:\n            self._f_multistep_eval = cas.Function(\"safe_multistep\",\n                                                  [p_0, u_0, k_fb_safe, k_ff_all, q_0, k_fb_0],\n                                                  [p_all, q_all, gp_sigma_pred_safe_all])\n        else:\n            self._f_multistep_eval = cas.Function(\"safe_multistep\",\n                                                  [p_0, u_0, k_fb_safe, k_ff_all],\n                                                  [p_all, q_all, gp_sigma_pred_safe_all])\n\n        g_safe, lbg_safe, ubg_safe, g_names_safe = self.generate_safety_constraints(\n            p_all, q_all, u_0, k_fb_safe, k_ff_all, q_0, k_fb_0)\n        g = vertcat(g, g_safe)\n        lbg += lbg_safe\n        ubg += ubg_safe\n        g_name += g_names_safe\n\n        # Generate performance trajectory\n        if self.n_perf > 1:\n            k_ff_perf, k_fb_perf, k_ff_perf_traj, k_fb_perf_traj, mu_perf, sigma_perf, gp_sigma_pred_perf_all, g_perf, lbg_perf, ubg_perf, g_names_perf = self._generate_perf_trajectory_casadi(\n                p_0, u_0, k_ff_all, k_fb_safe, self.a, self.b, self.lin_trafo_gp_input)\n            g = vertcat(g, g_perf)\n            lbg += lbg_perf\n            ubg += ubg_perf\n            g_name += g_names_perf\n        else:\n            k_ff_perf = np.array([])\n            k_fb_perf = np.array([])\n            k_fb_perf_traj = np.array([])\n            k_ff_perf_traj = np.array([])\n            mu_perf = np.array([])\n            sigma_perf = np.array([])\n            gp_sigma_pred_perf_all = None\n\n        cost = self.generate_cost_function(p_0, u_0, p_all, q_all, mu_perf, sigma_perf,\n                                           k_ff_all, k_fb_safe, gp_sigma_pred_safe_all,\n                                           k_fb_perf=k_fb_perf_traj,\n                                           k_ff_perf=k_ff_perf_traj,\n                                           gp_pred_sigma_perf=gp_sigma_pred_perf_all,\n                                           custom_cost_func=cost_func)\n\n        if self.opt_x0:\n            opt_vars = vertcat(p_0, u_0, k_ff_perf, k_ff_all.reshape((-1, 1)))\n            opt_params = vertcat(k_fb_safe.reshape((-1, 1)), k_fb_perf.reshape((-1, 1)))\n        else:\n            opt_vars = vertcat(u_0, k_ff_perf, k_ff_all.reshape((-1, 1)))\n            opt_params = vertcat(p_0, k_fb_safe.reshape((-1, 1)), k_fb_perf.reshape((-1, 1)))\n\n        if self.init_uncertainty:\n            opt_params = vertcat(opt_params, q_0.reshape((-1, 1)), k_fb_0.reshape((-1, 1)))\n\n        prob = {'f': cost, 'x': opt_vars, 'p': opt_params, 'g': g}\n\n        opt = self.opts_solver\n        if opt is None:\n            opt = {'error_on_fail': False,\n                   'ipopt': {'hessian_approximation': 'limited-memory', \"max_iter\": 100,\n                             \"expect_infeasible_problem\": \"no\", \\\n                             'acceptable_tol': 1e-4, \"acceptable_constr_viol_tol\": 1e-5,\n                             \"bound_frac\": 0.5, \"start_with_resto\": \"no\",\n                             \"required_infeasibility_reduction\": 0.85,\n                             \"acceptable_iter\": 8}}  # ipopt\n\n            # opt = {'max_iter':120,'hessian_approximation':'limited-memory'}#,\"c1\":5e-4} #sqpmethod #,\n        # opt = {'max_iter':120,'qpsol':'qpoases'}\n\n        solver = cas.nlpsol('solver', 'ipopt', prob, opt)\n        # solver = cas.nlpsol('solver','sqpmethod',prob,opt)\n        # solver = cas.nlpsol('solver','blocksqp',prob,opt)\n\n        self.solver = solver\n        self.lbg = lbg\n        self.ubg = ubg\n        self.solver_initialized = True\n        self.g = g\n        self.g_name = g_name\n\n    def generate_cost_function(self, p_0, u_0, p_all, q_all, mu_perf, sigma_perf,\n                               k_ff_safe, k_fb_safe, sigma_safe, k_fb_perf=None,\n                               k_ff_perf=None, gp_pred_sigma_perf=None,\n                               custom_cost_func=None, eps_noise=0.0):\n        # Generate cost function\n        if custom_cost_func is None:\n            cost = 0\n            if self.n_perf > 1:\n\n                n_cost_deviation = np.minimum(self.n_perf, self.n_safe)\n                for i in range(1, n_cost_deviation):\n                    cost += mtimes(mu_perf[i, :] - p_all[i, :],\n                                   mtimes(.1 * self.wx_cost,\n                                          (mu_perf[i, :] - p_all[i, :]).T))\n\n                for i in range(self.n_perf):\n                    cost -= sqrt(sum2(gp_pred_sigma_perf[i, :] + eps_noise))\n            else:\n                for i in range(self.n_safe):\n                    cost -= sqrt(sum2(sigma_safe[i, :] + eps_noise))\n        else:\n            if self.n_perf > 1:\n                cost = custom_cost_func(p_0, u_0, p_all, q_all, k_ff_safe, k_fb_safe,\n                                        sigma_safe, mu_perf, sigma_perf,\n                                        gp_pred_sigma_perf, k_fb_perf, k_ff_perf)\n            else:\n                cost = custom_cost_func(p_0, u_0, p_all, q_all, k_ff_safe, k_fb_safe,\n                                        sigma_safe)\n\n        return cost\n\n    def generate_safety_constraints(self, p_all, q_all, u_0, k_fb, k_ff_all, q_0=None, k_fb_0=None):\n        \"\"\" Generate all safety constraints\n\n        Parameters\n        ----------\n        p_all: n_safe x n_s casadi.SX\n            The centers of the safe trajctory ellipsoids\n        q_all: n_safe x n_s x n_s ndarray[float]\n\n        u_0 The initial\n            The shape matrices of the safe trajectory ellipsoids\n        k_fb: (n_safe-1) x (n_x * n_u) casadi.SX\n            Feedback control matrices\n        k_ff_all: (n_safe-1) x n_u casadi.SX\n            Feed-forward controls\n\n        Returns\n        -------\n        g: list[casadi.SX]\n            The constraint functions\n        lbg: list[casadi.SX]\n            Lower bounds for the constraints\n        ubg: list[casadi.SX]\n            Upper bounds for the constraints\n        \"\"\"\n        g = []\n        lbg = []\n        ubg = []\n        g_name = []\n\n        H = np.shape(p_all)[0]\n        # control constraints\n        if self.has_ctrl_bounds:\n            g_u_0, lbg_u_0, ubg_u_0 = self._generate_control_constraint(u_0, q_0, k_fb_0)\n            g = vertcat(g, g_u_0)\n            lbg += lbg_u_0\n            ubg += ubg_u_0\n            g_name += [\"u_0_ctrl_constraint\"]\n\n            for i in range(H - 1):\n                p_i = p_all[i, :].T\n                q_i = q_all[i, :].reshape((self.n_s, self.n_s))\n                k_ff_i = k_ff_all[i, :].reshape((self.n_u, 1))\n                k_fb_i = k_fb[i, :].reshape((self.n_u, self.n_s))\n\n                g_u_i, lbg_u_i, ubg_u_i = self._generate_control_constraint(k_ff_i, q_i,\n                                                                            k_fb_i)\n                g = vertcat(g, g_u_i)\n                lbg += lbg_u_i\n                ubg += ubg_u_i\n                g_name += [\"ellipsoid_ctrl_constraint_{}\".format(i)] * len(lbg_u_i)\n\n        # intermediate state constraints\n        if not self.h_mat_obs is None:\n            for i in range(H - 1):\n                p_i = p_all[i, :].T\n                q_i = q_all[i, :].reshape((self.n_s, self.n_s))\n                g_state = lin_ellipsoid_safety_distance(p_i, q_i, self.h_mat_obs,\n                                                        self.h_obs)\n                g = vertcat(g, g_state)\n                lbg += [-cas.inf] * self.m_obs\n                ubg += [0] * self.m_obs\n                g_name += [\"obstacle_avoidance_constraint{}\".format(i)] * self.m_obs\n\n        # terminal state constraint\n        p_T = p_all[-1, :].T\n        q_T = q_all[-1, :].reshape((self.n_s, self.n_s))\n\n        g_terminal = lin_ellipsoid_safety_distance(p_T, q_T, self.h_mat_safe,\n                                                   self.h_safe)\n        g = vertcat(g, g_terminal)\n        g_name += [\"terminal constraint\"] * self.m_safe\n        lbg += [-cas.inf] * self.m_safe\n        ubg += [0] * self.m_safe\n\n        return g, lbg, ubg, g_name\n\n    def _generate_perf_trajectory_casadi(self, mu_0, u_0, k_ff_ctrl, k_fb_safe, a=None,\n                                         b=None, lin_trafo_gp_input=None,\n                                         safety_constr=False):\n        \"\"\" Generate the performance trajectory variables for the casadi solver\n\n        Parameters:\n        mu_0: n_x x 1 casadi.SX\n            Initial state\n        u_0: n_u x 1 casadi.SX\n            Initial control\n        k_ff_ctrl: (n_safe-1) x n_u casadi.SX\n            Safe feed-forward controls\n        k_fb_safe: (n_safe-1) x (n_x * n_u) casadi.SX\n            Safe feedback control matrices\n        a: n_x x n_x np.ndarray[float], optional\n            The A-matrix of the prior linear model\n        b: n_x x n_u np.ndarray[float], optional\n            The B-matrix of the prior linear model\n        lin_trafo_gp_input: n_x_gp_in x n_x np.ndarray[float], optional\n            Allows for a linear transformation of the gp input (e.g. removing an input)\n        safety_constr: boolean, optional\n            True, if we want to put a constraint after (n_safe+1)th performance trajectory state to\n            be inside the terminal safe set. Can potentially help with (recursive) feasibility\n        \"\"\"\n        if self.r > 1:\n            warnings.warn(\n                \"Coupling performance and safety trajectory for more than one step is UNTESTED\")\n\n        # we don't have a performance trajectory, so nothing to do here. Might wanna catch this even before\n        if self.n_perf <= 1:\n            return np.array([]), np.array([]), np.array([]), np.array(\n                []), None, np.array([]), [], [], [], [], []\n        else:\n            k_ff_perf = MX.sym(\"k_ff_perf\", (self.n_perf - self.r, self.n_u))\n            k_ff_perf_traj = vertcat(k_ff_ctrl[:self.r - 1, :], k_ff_perf)\n\n            k_fb_perf_traj = np.array([])\n            for i in range(self.r - 1):\n                k_fb_perf_traj = np.append(k_fb_perf_traj,\n                                           [k_fb_safe[i, :].reshape((self.n_u, self.n_s))])\n            if self.perf_has_fb and self.n_perf - self.r > 0:\n                k_fb_perf = MX.sym(\"k_fb_perf\", (self.n_u, self.n_s))\n                for i in range(self.n_perf - self.r):\n                    k_fb_perf_traj = np.append(k_fb_perf_traj, [k_fb_perf])\n\n            mu_perf_all, sigma_perf_all, gp_sigma_pred_perf_all = self.perf_trajectory(\n                mu_0, self.ssm_forward, vertcat(u_0, k_ff_perf_traj), k_fb_perf_traj, None, a, b,\n                lin_trafo_gp_input)\n\n            # evaluation trajectory (mainly for verbosity)\n            mu_0_eval = MX.sym(\"mu_0\", (self.n_s, 1))\n            u_0_eval = MX.sym(\"u_0\", (self.n_u, 1))\n            k_fb_perf_all_eval = MX.sym(\"k_fb_perf\",\n                                        (self.n_perf - 1, self.n_u * self.n_s))\n            k_ff_perf_all_eval = MX.sym(\"k_ff_perf\", (self.n_perf - 1, self.n_u))\n\n            list_kfb_perf = [cas_reshape(k_fb_perf_all_eval[i, :], (self.n_u, self.n_s))\n                             for i in range(self.n_perf - 1)]\n            mu_perf_eval_all, sigma_perf_eval_all, gp_sigma_pred_perf_all_eval = self.perf_trajectory(\n                mu_0_eval, self.ssm_forward, vertcat(u_0_eval, k_ff_perf_all_eval),\n                list_kfb_perf, None, a, b, lin_trafo_gp_input)\n            self._f_multistep_perf_eval = cas.Function(\"f_multistep_perf_eval\",\n                                                       [mu_0_eval, u_0_eval,\n                                                        k_fb_perf_all_eval,\n                                                        k_ff_perf_all_eval],\n                                                       [mu_perf_eval_all,\n                                                        gp_sigma_pred_perf_all_eval])\n\n        # generate (approxiamte) constraints for the performance trajectory\n        g_name = []\n        g = []\n        lbg = []\n        ubg = []\n        if safety_constr and self.n_perf > self.n_safe:\n            g_name += [\"Terminal safety performance\"]\n            g_term = lin_ellipsoid_safety_distance(\n                cas_reshape(mu_perf_all[self.n_safe + 1, :], (self.n_s, 1)),\n                cas_reshape(sigma_perf_all[self.n_safe + 1, :], (self.n_s, self.n_s)),\n                self.h_mat_safe, self.h_safe)\n            g = vertcat(g, g_term)\n            lbg += [-np.inf] * self.m_safe\n            ubg += [0.] * self.m_safe\n\n        if self.has_ctrl_bounds:\n            for i in range(self.n_perf - self.r):\n                g_u_i, lbu_i, ubu_i = self._generate_control_constraint(\n                    k_ff_perf[i, :].T)\n                g = vertcat(g, g_u_i)\n                lbg += lbu_i\n                ubg += ubu_i\n                g_name += [\"ctrl_constr_performance_{}\".format(i)]\n\n        return k_ff_perf, k_fb_perf, k_ff_perf_traj, k_fb_perf_traj, mu_perf_all, sigma_perf_all, gp_sigma_pred_perf_all, g, lbg, ubg, g_name\n\n    def _generate_control_constraint(self, k_ff, q=None, k_fb=None, ctrl_bounds=None):\n        \"\"\" Build control constraints from state ellipsoids and linear feedback controls\n\n        k_ff: n_u x 1 ndarray[casadi.SX]\n            The feed-forward control gain\n        q: n_s x n_s ndarray[casadi.SX]\n            The shape matrix of the state ellipsoid\n        k_fb: n_u x n_s ndarray[casadi.SX]\n            The feedback gain\n        ctrl_bounds: n_u x 2 ndarray[float], optional\n\n        Returns\n        -------\n        g: 2*n_u x 1 ndarray[casadi.SX]\n            The control constraints (symbollicaly) evaluated at the current\n            state/controls\n        lbg: 2*n_u x 0 list[float]\n            Lower bounds for the control constraints\n        ubg: 2*n_u x 0 list[float]\n            Upper bounds for the control constraints\n        \"\"\"\n        if ctrl_bounds is None:\n            if not self.has_ctrl_bounds:\n                raise ValueError(\"\"\"Either ctrl_bounds has to be specified or\n                the objects' ctrl_bounds has to be specified \"\"\")\n            ctrl_bounds = self.ctrl_bounds\n\n        # no feedback term. Reduces to simple feed-forward control bounds\n\n        n_u, _ = np.shape(ctrl_bounds)\n        u_min = ctrl_bounds[:, 0]\n        u_max = ctrl_bounds[:, 1]\n\n        if k_fb is None:\n            return k_ff, u_min.tolist(), u_max.tolist()\n\n        h_vec = np.vstack((u_max[:, None], -u_min[:, None]))\n        h_mat = np.vstack((np.eye(n_u), -np.eye(n_u)))\n\n        p_u = k_ff\n        q_u = mtimes(k_fb, mtimes(q, k_fb.T))\n\n        g = lin_ellipsoid_safety_distance(p_u, q_u, h_mat, h_vec)\n\n        return g, [-cas.inf] * 2 * n_u, [0] * 2 * n_u\n\n    def _eval_prior_casadi(self, state, action):\n        \"\"\" symbolically evaluate the prior\n\n        Parameters\n        ----------\n        state: n x n_s array[casadi.SX]\n            Symbolic array of states\n        action: n x 1 array[casadi.SX]\n            Symbolic array of actions\n\n        Returns\n        -------\n        x_prior: n x n_s array[casadi.SX]\n            The (state,action) pairs evaluated at the prior\n        \"\"\"\n\n        return mtimes(self.a, state.T) + mtimes(self.b, action.T)\n\n    def eval_prior(self, state, action):\n        \"\"\" Evaluate the prior numerically\n\n        Parameters\n        ----------\n        state: n x n_s array[float]\n            Array of states\n        action: n x n_u array[float]\n\n        Returns\n        -------\n        x_prior: n x n_s array[float]\n            The (state,action) pairs evaluated at the prior\n        \"\"\"\n\n        return np.dot(state, self.a.T) + np.dot(action, self.b.T)\n\n    def get_lqr_feedback(self, x_0=None, u_0=None):\n        \"\"\" Get the initial feedback controller k_fb\n\n        x_0: n_s x 1 ndarray[float], optional\n            Current state of the system\n        u_0: n_u x 1 ndarray[float], optional\n            Initialization of the control input\n\n        \"\"\"\n        q = self.wx_feedback\n        r = self.wu_feedback\n\n        if x_0 is None:\n            x_0 = np.zeros((self.n_s, 1))\n        if u_0 is None:\n            u_0 = np.zeros((self.n_u, 1))\n\n        if self.lin_prior:\n            a = self.a\n            b = self.b\n\n            k_lqr, _, _ = dlqr(a, b, q, r)\n            k_fb = -k_lqr\n        else:\n\n            raise NotImplementedError(\n                \"Cannot compute feed-back matrices without prior model\")\n\n        return k_fb.reshape((1, self.n_s * self.n_u))\n\n    def get_safety_trajectory_openloop(self, x_0, u_0, k_fb=None, k_ff=None, q_0=None, k_fb_0=None):\n        \"\"\" Compute a trajectory of ellipsoids based on an initial state and a set of controls\n\n        Parameters\n        ----------\n        x_0: n_s x 1 2darray[float]\n            The initial state\n        u_0: n_u x 1 2darray[float]\n            The initial action\n        k_fb: (n_safe-1) x n_u x n_s  or n_u x n_s ndarray[float], optional\n            The feedback controls. Uses the most recent solution to the\n            MPC Problem (when calling solve()) if this parameter is not set\n        k_ff: (n_safe-1) x n_u, optional\n            The feed-forward controls. Uses the most recent solution to the\n            MPC Problem (when calling solve()) if this parameter is not set\n        get_controls: bool, optional\n            Additionally returns the applied controls if this flag is set to TRUE\n        Returns\n        -------\n        p_all: T x n_s ndarray[float]\n            The centers of the trajctory ellipsoids\n        q_all: T x n_s x n_s ndarray[float]\n            The shape matrices of the trajectory ellipsoids\n        \"\"\"\n        if not self.has_openloop:\n            return None, None\n\n        if k_fb is None:\n            k_fb = np.array(self.k_fb_all)\n\n        if k_ff is None:\n            k_ff = np.array(self.k_ff_all)\n\n        if self.init_uncertainty:\n            p_all, q_all, gp_sigma_pred_safe_all = self._f_multistep_eval(x_0, u_0, k_fb, k_ff, q_0, k_fb_0)\n        else:\n            p_all, q_all, gp_sigma_pred_safe_all = self._f_multistep_eval(x_0, u_0, k_fb, k_ff)\n\n        return p_all, q_all, gp_sigma_pred_safe_all\n\n    def get_action(self, x0_mu, lqr_only=False, sol_verbose=False):\n        \"\"\" Wrapper around the solve function\n\n        Parameters\n        ----------\n        x0_mu: n_s x 0 1darray[float]\n            The current state of the system\n\n        Returns\n        -------\n        u_apply: n_u x 0 1darray[float]\n            The action to be applied to the system\n        success: bool\n            The control was not successful if we are outside the safezone\n            AND we have to revert to the safe controller.\n        \"\"\"\n        safety_failure = False\n        if lqr_only:\n            u_apply = self.safe_policy(x0_mu)\n\n            return u_apply, safety_failure\n\n        if sol_verbose:\n            _, u_apply, feasible, success, k_fb_apply, k_ff_all, p_all, q_all = self.solve(\n                x0_mu[:, None], sol_verbose=True)\n            return u_apply.reshape(\n                self.n_u, ), feasible, success, k_fb_apply, k_ff_all, p_all, q_all\n\n        else:\n            _, u_apply, success = self.solve(x0_mu[:, None])\n\n            return u_apply.reshape(self.n_u, ), success\n\n    def solve(self, p_0, u_0=None, k_ff_all_0=None, k_fb_safe=None, u_perf_0=None,\n              k_fb_perf_0=None, sol_verbose=False, q_0=None, k_fb_0=None):\n        \"\"\" Solve the MPC problem for a given set of input parameters\n\n\n        Parameters\n        ----------\n        p_0: n_s x 1 array[float]\n            The initial (current) state\n        k_ff_all_0: n_safe x n_u  array[float], optional\n            The initialization of the feed-forward controls\n        k_fb_all_0: n_safe x (n_s * n_u) array[float], optional\n            The initialization of the feedback controls\n\n        Returns\n        -------\n        k_fb_apply: n_u x n_s array[float]\n            The feedback control term to be applied to the system\n        k_ff_apply: n_u x 1 array[float]\n            The feed-forward control term to be applied to the system\n        k_fb_all: n_safe x n_u x n_s\n            The feedback control terms for all time steps\n        k_ff_all: n_safe x n_u x 1\n        \"\"\"\n        assert self.solver_initialized, \"Need to initialize the solver first!\"\n\n        u_0_init, k_ff_all_0_init, k_fb_safe_init, u_perf_0_init, k_fb_perf_0_init = self._get_init_controls()\n\n        if u_0 is None:\n            u_0 = u_0_init\n        if k_ff_all_0 is None:\n            k_ff_all_0 = k_ff_all_0_init\n        if k_fb_safe is None:\n            k_fb_safe = k_fb_safe_init\n        if u_perf_0 is None:\n            u_perf_0 = u_perf_0_init\n        if k_fb_perf_0 is None:\n            k_fb_perf_0 = k_fb_perf_0_init\n        if q_0 is not None:\n            if k_fb_0 is None:\n                k_fb_0 = self.get_lqr_feedback()\n\n        if self.opt_x0:\n            params = np.vstack(\n                (cas_reshape(k_fb_safe, (-1, 1)), cas_reshape(k_fb_perf_0, (-1, 1))))\n\n            opt_vars_init = vertcat(cas_reshape(p_0, (-1, 1)), cas_reshape(u_0, (-1, 1)), u_perf_0, \\\n                               cas_reshape(k_ff_all_0, (-1, 1)))\n        else:\n            params = np.vstack(\n                (p_0, cas_reshape(k_fb_safe, (-1, 1)), cas_reshape(k_fb_perf_0, (-1, 1))))\n\n            opt_vars_init = vertcat(cas_reshape(u_0, (-1, 1)), u_perf_0, \\\n                             cas_reshape(k_ff_all_0, (-1, 1)))\n\n        if self.init_uncertainty:\n            params = vertcat(params, cas_reshape(q_0, (-1, 1)), cas_reshape(k_fb_0, (-1, 1)))\n\n        crash = False \n        sol = self.solver(x0=opt_vars_init, lbg=self.lbg, ubg=self.ubg, p=params)\n        try:\n            # pass\n            sol = self.solver(x0=opt_vars_init, lbg=self.lbg, ubg=self.ubg, p=params)\n        except:\n            crash = True\n            warnings.warn(\"NLP solver crashed, solution infeasible\")\n            sol = None\n\n        return self._get_solution(p_0, sol, k_fb_safe, k_fb_perf_0, sol_verbose, crash, q_0=q_0, k_fb_0=k_fb_0)\n\n    def _get_solution(self, x_0, sol, k_fb, k_fb_perf_0, sol_verbose=False,\n                      crashed=False, feas_tol=1e-6, q_0=None, k_fb_0=None):\n        \"\"\" Process the solution dict of the casadi solver\n\n        Processes the solution dictionary of the casadi solver and\n        (depending on the chosen mode) saves the solution for reuse in the next\n        time step. Depending on the chosen verbosity level, it also prints\n        some statistics.\n\n        Parameters\n        ----------\n        sol: dict\n            The solution dictionary returned by the casadi solver\n        sol_verbose: boolean, optional\n            Return additional solver results such as the constraint values\n\n        Returns\n        -------\n        k_fb_apply: n_u x n_s array[float]\n            The feedback control term to be applied to the system\n        k_ff_apply: n_u x 1 array[float]\n            The feed-forward control term to be applied to the system\n        k_fb_all: n_safe x n_u x n_s\n            The feedback control terms for all time steps\n        k_ff_all: n_safe x n_u x 1\n\n        h_values: (m_obs*n_safe + m_safe) x 0 array[float], optional\n            The values of the constraint evaluation (distance to obstacle)\n        \"\"\"\n\n        success = True\n        feasible = True\n        if crashed:\n            feasible = False\n\n            if self.verbosity > 1:\n                print(\"Optimization crashed, infeasible soluion!\")\n        else:\n            g_res = np.array(sol[\"g\"]).squeeze()\n\n            # This is not sufficient, since casadi gives out wrong feasibility values\n            if np.any(np.array(self.lbg) - feas_tol > g_res) or np.any(\n                    np.array(self.ubg) + feas_tol < g_res):\n                feasible = False\n\n            x_opt = sol[\"x\"]\n            self.has_openloop = True\n\n            if self.opt_x0:\n                x_0 = x_opt[:self.n_s]\n                x_opt = x_opt[self.n_s:, :]\n\n            # get indices of the respective variables\n            n_u_0 = self.n_u\n            n_u_perf = 0\n            if self.n_perf > 1:\n                n_u_perf = (self.n_perf - self.r) * self.n_u\n            n_k_ff = (self.n_safe - 1) * self.n_u\n\n            c = 0\n            idx_u_0 = np.arange(n_u_0)\n            c += n_u_0\n            idx_u_perf = np.arange(c, c + n_u_perf)\n            c += n_u_perf\n            idx_k_ff = np.arange(c, c + n_k_ff)\n            c += n_k_ff\n\n            u_apply = np.array(cas_reshape(x_opt[idx_u_0], (1, self.n_u)))\n            k_ff_perf = np.array(\n                cas_reshape(x_opt[idx_u_perf], (self.n_perf - self.r, self.n_u)))\n\n            k_ff_safe = np.array(\n                cas_reshape(x_opt[idx_k_ff], (self.n_safe - 1, self.n_u)))\n            k_ff_safe_all = np.vstack((u_apply, k_ff_safe))\n\n            k_fb_safe_output = array_of_vec_to_array_of_mat(np.copy(k_fb), self.n_u,\n                                                            self.n_s)\n\n            p_safe, q_safe, gp_sigma_pred_safe_all = self.get_safety_trajectory_openloop(x_0, u_apply,\n                                                                 np.copy(k_fb),\n                                                                 k_ff_safe, q_0, k_fb_0)\n\n            p_safe = np.array(p_safe)\n            q_safe = np.array(q_safe)\n\n            if self.verbosity > 1:\n                print(\"=== Safe Trajectory: ===\")\n                print(\"Centers:\")\n                print(p_safe)\n                print(\"Shape matrices:\")\n                print(q_safe)\n                print(\"Safety controls:\")\n                print(u_apply)\n                print(k_ff_safe)\n\n            k_fb_perf_traj_eval = np.empty((0, self.n_s * self.n_u))\n            k_ff_perf_traj_eval = np.empty((0, self.n_u))\n            if self.n_safe > 1:\n                k_fb_perf_traj_eval = np.vstack(\n                    (k_fb_perf_traj_eval, k_fb[:self.r - 1, :]))\n                k_ff_perf_traj_eval = np.vstack(\n                    (k_ff_perf_traj_eval, k_ff_safe[:self.r - 1, :]))\n            if self.n_perf > self.r:\n                k_fb_perf_traj_eval = np.vstack((k_fb_perf_traj_eval,\n                                                 np.matlib.repmat(k_fb_perf_0,\n                                                                  self.n_perf - self.r,\n                                                                  1)))\n            k_ff_perf_traj_eval = np.vstack((k_ff_perf_traj_eval, k_ff_perf))\n\n            if self.n_perf > 1:\n                mu_perf, sigma_perf = self._f_multistep_perf_eval(x_0.squeeze(),\n                                                                  u_apply,\n                                                                  k_fb_perf_traj_eval,\n                                                                  k_ff_perf_traj_eval)\n\n                if self.verbosity > 1:\n                    print(\"=== Performance Trajectory: ===\")\n                    print(\"Mu perf:\")\n                    print(mu_perf)\n                    print(\"Peformance controls:\")\n                    print(k_ff_perf_traj_eval)\n\n            feasible, _ = self.eval_safety_constraints(p_safe, q_safe)\n\n            if self.rhc and feasible:\n                self.k_ff_safe = k_ff_safe\n                self.k_ff_perf = k_ff_perf\n                self.p_safe = p_safe\n                self.k_fb_safe_all = np.copy(k_fb)\n                self.u_apply = u_apply\n                self.k_fb_perf_0 = k_fb_perf_0\n\n        if feasible:\n            self.n_fail = 0\n\n        if not feasible:\n            self.n_fail += 1\n            q_all = None\n            k_fb_safe_output = None\n            k_ff_all = None\n            p_safe = None\n            q_safe = None\n            g_res = None\n\n            if self.n_fail >= self.n_safe:\n                # Too many infeasible solutions -> switch to safe controller\n                if self.verbosity > 1:\n                    print(\n                        \"Infeasible solution. Too many infeasible solutions, switching to safe controller\")\n                u_apply = self.safe_policy(x_0)\n                k_ff_safe_all = u_apply\n            else:\n                # can apply previous solution\n                if self.verbosity > 1:\n                    print((\n                        \"Infeasible solution. Switching to previous solution, n_fail = {}, n_safe = {}\".format(\n                            self.n_fail, self.n_safe)))\n                if sol_verbose:\n                    u_apply, k_fb_safe_output, k_ff_safe_all, p_safe = self.get_old_solution(\n                        x_0, get_ctrl_traj=True)\n                else:\n                    u_apply = self.get_old_solution(x_0)\n                    k_ff_safe_all = u_apply\n\n        if sol_verbose:\n            return x_0, u_apply, feasible, success, k_fb_safe_output, k_ff_safe_all, p_safe, q_safe, sol, gp_sigma_pred_safe_all\n\n        return x_0, u_apply, success\n\n    def eval_safety_constraints(self, p_all, q_all, ubg_term=0., lbg_term=-np.inf,\n                                ubg_interm=0., lbg_interm=-np.inf, terminal_only=False,\n                                eps_constraints=1e-5):\n        \"\"\" Evaluate the safety constraints \"\"\"\n        g_term_val = self.g_term_cas(p_all[-1, :, None],\n                                     cas_reshape(q_all[-1, :], (self.n_s, self.n_s)))\n\n        feasible_term = np.all(lbg_term - eps_constraints < g_term_val) and np.all(\n            g_term_val < ubg_term + eps_constraints)\n\n        feasible = feasible_term\n        if terminal_only or self.h_mat_obs is None:\n\n            if self.verbosity > 1:\n                print((\n                    \"\\n===== Evaluated terminal constraint values: FEASIBLE = {} =====\".format(\n                        feasible)))\n                print(g_term_val)\n                print(\"\\n===== ===== ===== ===== ===== ===== ===== =====\")\n\n            return feasible, g_term_val\n\n        g_interm_val = self.g_interm_cas(p_all[-1, :, None], cas_reshape(q_all[-1, :], (\n            self.n_s, self.n_s)))\n\n        feasible_interm = np.all(\n            lbg_interm - eps_constraints < g_interm_val) and np.all(\n            g_interm_val < ubg_interm + eps_constraints)\n\n        feasible = feasible_term and feasible_interm\n\n        return feasible, np.vstack((g_term_val, g_interm_val))\n\n    def get_old_solution(self, x, k=None, get_ctrl_traj=False):\n        \"\"\" Shift previously obtained solutions in time and return solution to be applied\n\n        Prameters\n        ---------\n        k: int, optional\n            The number of steps to shift back in time. This is number is\n            already tracked by the algorithm, so a custom value should be used with caution\n        get_ctrl_traj: bool, optional\n            Return the safety trajectory state feedback ctrl laws in terms of k_fb,k_ff,p_ctrl\n\n        Returns\n        -------\n        u_apply: n_s x 0 1darray[float]\n            The controls to be applied at the current time step\n\n        if get_ctrl_traj:\n            k_fb_safe_traj:\n                The feedback ctrls of the remaining safety trajectory\n            k_ff_safe_traj:\n                The current ff ctrl and the remaining ff ctrls of the safety trajectory\n            p_ctrl_safe_traj:\n                The\n\n\n\n        \"\"\"\n        if self.n_fail > self.n_safe:\n            warnings.warn(\n                \"There are no previous solution to be applied. Returning None\")\n            return None\n        if k is None:\n            k = self.n_fail\n\n        if k < 1:\n            warnings.warn(\"Have to shift at least one timestep back\")\n            return None\n\n        k_fb_old = self.k_fb_safe_all[k - 1]\n        k_ff = self.k_ff_safe[k - 1, :, None]\n        p_safe = self.p_safe[k - 1, :, None]\n\n        u_apply = feedback_ctrl(x, k_ff, k_fb_old, p_safe)\n        if get_ctrl_traj:\n            k_fb_safe_traj = None\n            k_ff_safe_traj = u_apply\n            p_ctrl_safe_traj = None\n\n            if k < self.n_safe:\n                k_fb_safe_traj = self.k_fb_safe_all[k:, :]\n                # in accordance to the structure current ctrl u_apply is part of the k_ff ctrl trajectory\n                k_ff_safe_traj = np.vstack((u_apply, self.k_ff_safe[k + 1:, :]))\n                p_ctrl_safe_traj = self.p_safe[k:, :]\n\n            return u_apply, k_fb_safe_traj, \\\n                   k_ff_safe_traj, p_ctrl_safe_traj\n\n        return u_apply\n\n    def _set_attributes_from_dict(self, attrib_names, default_attribs={},\n                                  custom_attrib={}):\n        \"\"\" Set class attributes from a list of keys,values \"\"\"\n        for attr_name in attrib_names:\n            if attr_name in custom_attrib:\n                attr_val = custom_attrib[attr_name]\n            elif attr_name in default_attribs:\n                attr_val = default_attribs[attr_name]\n            else:\n                raise ValueError(\n                    \"Neither a custom nor a default value is given for the requried attribute {}\".format(\n                        attr_name))\n\n            setattr(self, attr_name, attr_val)\n\n    def _set_perf_trajectory(self, name):\n        \"\"\" Get the peformance trajectory function from identifier\"\"\"\n        if name == 'mean_equivalent':\n            self.perf_trajectory = mean_equivalent_multistep\n        elif name == 'taylor':\n            self.perf_trajectory = multi_step_taylor_symbolic\n        else:\n            raise NotImplementedError(\"Unknown uncertainty propagation method\")\n\n    def _get_init_controls(self):\n        \"\"\" Initialize the controls for the MPC step\n\n\n        Returns\n        -------\n        u_0: n_u x 0 np.array[float]\n            Initialization of the first (shared) input\n        k_ff_safe_new:  (n_safe-1) x n_u np.ndarray[float]\n            Initialization of the safety feed-forward control inputs\n        k_fb_new: n_u x n_x np.ndarray[float]\n            Initialization of the safety feed-back control inputs\n        k_ff_perf_new: (n_perf - r_1) x n_u np.ndarray[float]\n            Initialization of the performance feed-forward control inputs.\n            Not including the shared controls (if r > 1)\n        k_fb_perf_0: n_u x n_x np.ndarray[float]\n            Initialization of the safety feed-back control inputs\n\n        \"\"\"\n\n        u_perf_0 = None\n        k_fb_perf_0 = None\n        k_fb_lqr = self.get_lqr_feedback()\n\n        if self.do_shift_solution and self.n_fail == 0:\n            if self.n_safe > 1:\n                k_fb_safe = np.copy(self.k_fb_safe_all)\n\n                # Shift the safe controls\n                k_ff_safe = np.copy(self.k_ff_safe)\n\n                u_0 = k_ff_safe[0, :]\n\n                if self.n_safe > self.r and self.n_perf > self.n_safe:  # the first control after the shared controls\n                    k_ff_perf = np.copy(self.k_ff_perf)\n                    k_ff_r_last = (k_ff_perf[0, :] + k_ff_safe[self.r - 1,\n                                                     :]) / 2  # mean of first perf ctrl and safe ctrl after shared\n                else:\n                    k_ff_r_last = k_ff_safe[-1, :]  # just the last safe control\n\n                k_ff_safe_new = np.vstack((k_ff_safe[1:self.r, :], k_ff_r_last))\n\n                if self.n_safe > self.r + 1:\n                    k_ff_safe_new = np.vstack((k_ff_safe_new, k_ff_safe[self.r:, :]))\n            else:\n                u_0 = self.u_apply\n                k_ff_safe_new = np.array([])\n\n            if self.n_perf - self.r > 0:\n                k_ff_perf = np.copy(self.k_ff_perf)\n                k_ff_perf_new = np.vstack((k_ff_perf[1:, :], k_ff_perf[-1, :]))\n\n                if self.perf_has_fb:\n                    k_fb_perf_0 = np.copy(self.k_fb_perf_0)\n                else:\n                    k_fb_perf_0 = np.array([])\n            else:\n                k_ff_perf_new = np.array([])\n                k_fb_perf_0 = np.array([])\n        else:\n            k_fb_safe = np.empty((self.n_safe - 1, self.n_s * self.n_u))\n            for i in range(self.n_safe - 1):\n                k_fb_safe[i] = cas_reshape(k_fb_lqr, (1, -1))\n\n            k_ff_safe_new = np.zeros((self.n_safe - 1, self.n_u))\n            u_0 = np.zeros((self.n_u, 1))\n\n            k_ff_perf_new = np.array([])\n            if self.n_perf > 1:\n                k_ff_perf_new = np.zeros((self.n_perf - self.r, self.n_u))\n\n                if self.perf_has_fb:\n                    k_fb_perf_0 = k_fb_lqr\n            else:\n                k_fb_perf_0 = np.array([])\n\n        if self.n_safe > 1:\n            k_fb_safe_new = np.vstack((k_fb_safe[1:, :], k_fb_safe[-1, :]))\n\n        else:\n            k_fb_safe_new = np.array([])\n\n        return u_0, k_ff_safe_new, k_fb_safe, k_ff_perf_new, k_fb_perf_0\n\n    def update_model(self, x, y, opt_hyp=False, replace_old=True,\n                     reinitialize_solver=True):\n        \"\"\" Update the model of the dynamics\n\n        Parameters\n        ----------\n        x: n x (n_s+n_u) array[float]\n            The raw training input (state,action) pairs\n        y: n x (n_s) array[float]\n            The raw training targets (observations of next state)\n        opt_hyp: bool\n            True, if we want to re-optimize the GP hyperparameters\n        replace_old: bool\n            True, if we replace the current training set of the GP with x,y\n        reinitialize_solver:\n            True, if we re-initialize the solver (otherwise the MPC will not be updated with the new GP)\n\n        \"\"\"\n        n_train = np.shape(x)[0]\n        x_s = x[:, :self.n_s].reshape((n_train, self.n_s))\n        x_u = x[:, self.n_s:].reshape((n_train, self.n_u))\n        y_prior = self.eval_prior(x_s, x_u)\n        x_trafo = mtimes(x_s, self.lin_trafo_gp_input.T)\n\n        x = np.hstack((x_trafo, x_u))\n\n        self.ssm.update_model(x, y - y_prior, opt_hyp, replace_old)\n        self.ssm_forward = self.ssm.get_forward_model_casadi(True)\n\n        if reinitialize_solver:\n            self.init_solver(self.cost_func)\n        else:\n            warnings.warn(\"\"\"Updating gp without reinitializing the solver! \\n\n                This is potentially dangerous, since the new GP is not incorporated in the MPC\"\"\")\n", "meta": {"hexsha": "b22868be6c54439b37d2d417aad996319a154261", "size": 46618, "ext": "py", "lang": "Python", "max_stars_repo_path": "safe_exploration/safempc_simple.py", "max_stars_repo_name": "befelix/safe-exploration", "max_stars_repo_head_hexsha": "e6c0bc57b7b51fe3e3c97d51721893fe297b2b11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 55, "max_stars_repo_stars_event_min_datetime": "2019-05-13T07:17:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T16:39:20.000Z", "max_issues_repo_path": "safe_exploration/safempc_simple.py", "max_issues_repo_name": "befelix/safe-exploration", "max_issues_repo_head_hexsha": "e6c0bc57b7b51fe3e3c97d51721893fe297b2b11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-05-13T06:56:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-12T22:19:28.000Z", "max_forks_repo_path": "safe_exploration/safempc_simple.py", "max_forks_repo_name": "befelix/safe-exploration", "max_forks_repo_head_hexsha": "e6c0bc57b7b51fe3e3c97d51721893fe297b2b11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2019-05-13T11:08:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T12:51:36.000Z", "avg_line_length": 40.7144104803, "max_line_length": 192, "alphanum_fraction": 0.5506671243, "include": true, "reason": "import numpy", "num_tokens": 11217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878696277512, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.19316868462337058}}
{"text": "#!/home/jue/.conda/envs/ampere/bin/python                                                 \n\nimport os\nimport mock\nimport numpy as np\nimport sys\nimport datetime\n\nfrom typing import Any, Mapping, Optional, Sequence, Tuple\nimport collections\nfrom collections import OrderedDict\n\nfrom timeit import default_timer as timer\nimport argparse\n\nimport io\nfrom Bio import PDB\nfrom Bio.PDB.Polypeptide import PPBuilder\nfrom Bio.PDB import PDBParser\nfrom Bio.PDB.mmcifio import MMCIFIO\n\nsys.path.insert( 0, '/home/nrbennet/software/dl/af2/alphafold' )\n\nimport scipy\n\nimport jax\nimport jax.numpy as jnp\n\nfrom alphafold.common import residue_constants\nfrom alphafold.common import protein\nfrom alphafold.common import confidence\nfrom alphafold.data import pipeline\nfrom alphafold.data import templates\nfrom alphafold.data import mmcif_parsing\nfrom alphafold.model import data\nfrom alphafold.model import config\nfrom alphafold.model import model\nfrom alphafold.data.tools import hhsearch\n\nsys.path.append( '/home/nrbennet/software/silent_tools' )\nimport silent_tools\n\n# Run with Nate's ampere environment\nfrom pyrosetta import *\nfrom rosetta import *\ninit( '-in:file:silent_struct_type binary' )\n\ndef get_args():\n    parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)\n    parser.add_argument(\"-silent\", dest=\"silent\", required=True,\n                        help=\"silent file to predict\")\n    parser.add_argument(\"-batch\", dest=\"batch_size\", type=int, default=1,\n                        help=\"Number of structures to batch together\")\n    parser.add_argument(\"-recycle\", dest=\"recycle\", type=int, default=3,\n                        help=\"Number of recycle iterations to perform\")\n\n    args = parser.parse_args()\n    return args\n\nargs = get_args()\n\nmodel_name = \"model_1_ptm\"\n\nmodel_config = config.model_config(model_name)\nmodel_config.data.eval.num_ensemble = 1\n\nmodel_config.data.common.num_recycle = args.recycle\nmodel_config.model.num_recycle = args.recycle\n\nmodel_config.model.embeddings_and_evoformer.initial_guess = True\n\nmodel_config.model.global_config.mixed_precision = False\n\nmodel_config.data.common.max_extra_msa = 5\nmodel_config.data.eval.max_msa_clusters = 5\n\nmodel_params = data.get_model_haiku_params(model_name=model_name, data_dir=\"/projects/ml/alphafold\") # CHANGE THIS (directory where \"params/ folder is\")\nmodel_runner = model.RunModel(model_config, model_params)\n\ndef get_seq_from_pdb( pdb_fn ):\n  to1letter = {\n    \"ALA\":'A', \"ARG\":'R', \"ASN\":'N', \"ASP\":'D', \"CYS\":'C',\n    \"GLN\":'Q', \"GLU\":'E', \"GLY\":'G', \"HIS\":'H', \"ILE\":'I',\n    \"LEU\":'L', \"LYS\":'K', \"MET\":'M', \"PHE\":'F', \"PRO\":'P',\n    \"SER\":'S', \"THR\":'T', \"TRP\":'W', \"TYR\":'Y', \"VAL\":'V' }\n\n  seq = []\n  seqstr = ''\n  with open(pdb_fn) as fp:\n    for line in fp:\n      if line.startswith(\"TER\"):\n          seq.append(seqstr)\n          seqstr = ''\n      if not line.startswith(\"ATOM\"):\n        continue\n      if line[12:16].strip() != \"CA\":\n        continue\n      resName = line[17:20]\n      #\n      seqstr += to1letter[resName]\n  return seq\n\ndef af2_get_atom_positions( pdbfilename ) -> Tuple[np.ndarray, np.ndarray]:\n  \"\"\"Gets atom positions and mask from a list of Biopython Residues.\"\"\"\n\n  with open(pdbfilename, 'r') as pdb_file:\n    lines = pdb_file.readlines()\n\n  # indices of residues observed in the structure\n  idx_s = [int(l[22:26]) for l in lines if l[:4]==\"ATOM\" and l[12:16].strip()==\"CA\"]\n  num_res = len(idx_s)\n\n  all_positions = np.zeros([num_res, residue_constants.atom_type_num, 3])\n  all_positions_mask = np.zeros([num_res, residue_constants.atom_type_num],\n                                dtype=np.int64)\n\n  residues = collections.defaultdict(list)\n  # 4 BB + up to 10 SC atoms\n  xyz = np.full((len(idx_s), 14, 3), np.nan, dtype=np.float32)\n  for l in lines:\n    if l[:4] != \"ATOM\":\n        continue\n    resNo, atom, aa = int(l[22:26]), l[12:16], l[17:20]\n\n    residues[ resNo ].append( ( atom.strip(), aa, [float(l[30:38]), float(l[38:46]), float(l[46:54])] ) )\n\n  for resNo in residues:\n\n    pos = np.zeros([residue_constants.atom_type_num, 3], dtype=np.float32)\n    mask = np.zeros([residue_constants.atom_type_num], dtype=np.float32)\n\n    for atom in residues[ resNo ]:\n      atom_name = atom[0]\n      x, y, z = atom[2]\n      if atom_name in residue_constants.atom_order.keys():\n        pos[residue_constants.atom_order[atom_name]] = [x, y, z]\n        mask[residue_constants.atom_order[atom_name]] = 1.0\n      elif atom_name.upper() == 'SE' and res.get_resname() == 'MSE':\n        # Put the coordinates of the selenium atom in the sulphur column.\n        pos[residue_constants.atom_order['SD']] = [x, y, z]\n        mask[residue_constants.atom_order['SD']] = 1.0\n\n    idx = idx_s.index(resNo) # This is the order they show up in the pdb\n    all_positions[idx] = pos\n    all_positions_mask[idx] = mask\n  # _check_residue_distances(\n  #     all_positions, all_positions_mask, max_ca_ca_distance) # AF2 checks this but if we want to allow massive truncations we don't want to check this\n\n  return all_positions, all_positions_mask\n\ndef af2_all_atom_from_struct( pdbfilename, seq_list, just_target=False ):\n  template_seq = ''.join( seq_list )\n\n  # Parse a residue mask from the chainbreak sequence\n  binder_len = len( seq_list[0] )\n  residue_mask = [ int( i ) > binder_len for i in range( 1, len( template_seq ) + 1 ) ]\n\n  all_atom_positions, all_atom_mask = af2_get_atom_positions( pdbfilename )\n\n  all_atom_positions = np.split(all_atom_positions, all_atom_positions.shape[0])\n\n  templates_all_atom_positions = []\n\n  # Initially fill will all zero values\n  for _ in template_seq:\n    templates_all_atom_positions.append(\n        jnp.zeros((residue_constants.atom_type_num, 3)))\n\n  for idx, i in enumerate( template_seq ):\n    if just_target and not residue_mask[ idx ]: continue\n\n    templates_all_atom_positions[ idx ] = all_atom_positions[ idx ][0] # assign target indices to template coordinates\n\n  return jnp.array(templates_all_atom_positions)\n\ndef template_from_struct( pdbfilename, seq_list ):\n\n  template_seq = ''.join(seq_list)\n\n  # Parse a residue mask from the chainbreak sequence\n  binder_len = len( seq_list[0] )\n  residue_mask = [ int( i ) > binder_len for i in range( 1, len( template_seq ) + 1 ) ]\n\n  ret_all_atom_positions, ret_all_atom_mask = af2_get_atom_positions( pdbfilename )\n\n  all_atom_positions = np.split(ret_all_atom_positions, ret_all_atom_positions.shape[0])\n  all_atom_masks = np.split(ret_all_atom_mask, ret_all_atom_mask.shape[0])\n  \n  output_templates_sequence = []\n  output_confidence_scores = []\n  templates_all_atom_positions = []\n  templates_all_atom_masks = []\n\n  # Initially fill will all zero values\n  for _ in template_seq:\n    templates_all_atom_positions.append(\n        np.zeros((residue_constants.atom_type_num, 3)))\n    templates_all_atom_masks.append(np.zeros(residue_constants.atom_type_num))\n    output_templates_sequence.append('-')\n    output_confidence_scores.append(-1)\n  \n  confidence_scores = []\n  for _ in template_seq: confidence_scores.append( 9 )\n\n  for idx, i in enumerate( template_seq ):\n\n    if not residue_mask[ idx ]: continue\n\n    templates_all_atom_positions[ idx ] = all_atom_positions[ idx ][0] # assign target indices to template coordinates\n    templates_all_atom_masks[ idx ] = all_atom_masks[ idx ][0]\n    output_templates_sequence[ idx ] = template_seq[ idx ]\n    output_confidence_scores[ idx ] = confidence_scores[ idx ] # 0-9 where higher is more confident\n\n  output_templates_sequence = ''.join(output_templates_sequence)\n\n  templates_aatype = residue_constants.sequence_to_onehot(\n      output_templates_sequence, residue_constants.HHBLITS_AA_TO_ID)\n\n  template_feat_dict = {'template_all_atom_positions': np.array(templates_all_atom_positions)[None],\n       'template_all_atom_masks': np.array(templates_all_atom_masks)[None],\n       'template_sequence': [output_templates_sequence.encode()],\n       'template_aatype': np.array(templates_aatype)[None],\n       'template_confidence_scores': np.array(output_confidence_scores)[None],\n       'template_domain_names': ['none'.encode()],\n       'template_release_date': [\"none\".encode()]}\n\n  return template_feat_dict, ret_all_atom_positions, ret_all_atom_mask\n\ndef insert_chainbreaks( pose, binderlen ):\n\n    conf = pose.conformation()\n    conf.insert_chain_ending( binderlen )\n    pose.set_new_conformation( conf )\n\n    splits = pose.split_by_chain()\n \n    newpose = splits[1]\n    for i in range( 2, len( splits )+1 ):\n        newpose.append_pose_by_jump( splits[i], newpose.size() )\n \n    info = core.pose.PDBInfo( newpose, True )\n    newpose.pdb_info( info )\n\n    return newpose\n\n    return final_dict\n\ndef get_final_dict(score_dict, string_dict):\n    print(score_dict)\n    final_dict = OrderedDict()\n    keys_score = [] if score_dict is None else list(score_dict)\n    keys_string = [] if string_dict is None else list(string_dict)\n\n    all_keys = keys_score + keys_string\n\n    argsort = sorted(range(len(all_keys)), key=lambda x: all_keys[x])\n\n    for idx in argsort:\n        key = all_keys[idx]\n\n        if ( idx < len(keys_score) ):\n            final_dict[key] = \"%8.3f\"%(score_dict[key])\n        else:\n            final_dict[key] = string_dict[key]\n\n    return final_dict\n\ndef add2scorefile(tag, scorefilename, write_header=False, score_dict=None):\n    with open(scorefilename, \"a\") as f:\n        add_to_score_file_open(tag, f, write_header, score_dict)\n\ndef add_to_score_file_open(tag, f, write_header=False, score_dict=None, string_dict=None):\n    final_dict = get_final_dict( score_dict, string_dict )\n    if ( write_header ):\n        f.write(\"SCORE:     %s description\\n\"%(\" \".join(final_dict.keys())))\n    scores_string = \" \".join(final_dict.values())\n    f.write(\"SCORE:     %s        %s\\n\"%(scores_string, tag))\n\ndef generate_scoredict( outtag, start_time, binderlen, prediction_result, scorefilename ):\n\n  plddt_array = prediction_result['plddt']\n  plddt = np.mean( plddt_array )\n  plddt_binder = np.mean( plddt_array[:binderlen] )\n  plddt_target = np.mean( plddt_array[binderlen:] )\n\n  pae = prediction_result['predicted_aligned_error']\n  pae_interaction1 = np.mean( pae[:binderlen,binderlen:] )\n  pae_interaction2 = np.mean( pae[binderlen:,:binderlen] )\n  pae_binder = np.mean( pae[:binderlen,:binderlen] )\n  pae_target = np.mean( pae[binderlen:,binderlen:] )\n\n  pae_interaction_total = ( pae_interaction1 + pae_interaction2 ) / 2\n\n  # Calculate pae_interface which is pae_interaction of only residues within 10A of the binder\n  # This is all derived from some AF2 code to calculate pAE from logits\n  # This turns logits to probabilites and then gets the expected value at each position\n\n  edges = prediction_result['distogram']['bin_edges']\n  edges = np.squeeze(edges)\n  probs = scipy.special.softmax(\n          prediction_result['distogram']['logits'],\n          axis=-1)\n  probs = np.squeeze(probs)\n\n  step = (edges[1] - edges[0])\n  bin_centers = edges + step / 2\n\n  bin_centers = np.concatenate([bin_centers, [bin_centers[-1] + step]], axis=-1)\n\n  dgram = np.sum(probs * bin_centers, axis=-1)\n\n  # End AF2-derived\n\n  interface_cutoff = 15 # This can be made into a commandline argument eventually\n  distance_mask = np.where(dgram < interface_cutoff, 1, 0) # mask all positions that are not within the interface cutoff\n  pae_masked = np.squeeze(pae) * distance_mask\n  pae_interface = ( np.mean( pae_masked[:binderlen,binderlen:] ) + np.mean( pae_masked[binderlen:,:binderlen] ) ) / 2\n\n  if np.isnan(pae_interface): pae_interface = 25\n  if pae_interface == 0: pae_interface = 25 # If there are no residues within the interface we want to set this as a high number, not 0\n\n  time = timer() - start_time\n\n  score_dict = {\n          \"plddt_total\" : plddt,\n          \"plddt_binder\" : plddt_binder,\n          \"plddt_target\" : plddt_target,\n          \"pae_interaction1\" : pae_interaction1,\n          \"pae_interaction2\" : pae_interaction2,\n          \"pae_binder\" : pae_binder,\n          \"pae_target\" : pae_target,\n          \"pae_interaction\" : pae_interaction_total,\n          # \"pae_interface\" : pae_interface, # Benchmarking with this metric suggests that it's not a very good predictor of binder success\n          \"time\" : time\n  }\n\n  write_header=False\n  if not os.path.isfile(scorefilename): write_header=True\n  add2scorefile(outtag, scorefilename, write_header=write_header, score_dict=score_dict)\n  \n  print(score_dict)\n  print( f\"Tag: {outtag} reported success in {time} seconds\" )\n\n  return score_dict\n\ndef combine_batches(tags, feature_dict_dict, initial_guess_dict):\n    print( tags )\n    allkeys = feature_dict_dict[tags[0]].keys()\n    processed_feature_dict = {}\n    for key in allkeys:\n        processed_feature_dict[key] = jnp.stack([feature_dict_dict[tag][key] for tag in tags], axis=0)\n    processed_initial_guess_dict = jnp.stack([initial_guess_dict[tag] for tag in tags], axis=0)\n    return processed_feature_dict, processed_initial_guess_dict\n\ndef unpack_batches( tags, binderlen_dict, start, feature_dict_dict, prediction_result, sfd_out, scorefilename ):\n\n    # First unpack the structures\n    all_struct_module = prediction_result['structure_module']\n    proteins = {} \n    for i in range(all_struct_module['final_atom_positions'].shape[0]):\n        key = tags[i]\n\n        proteins[key] = protein.Protein(\n           aatype=feature_dict_dict[key]['aatype'][0],\n           atom_positions=all_struct_module['final_atom_positions'][i,...],\n           atom_mask=all_struct_module['final_atom_mask'][i,...],\n           residue_index=feature_dict_dict[key]['residue_index'][0] + 1,\n           b_factors=np.zeros_like(all_struct_module['final_atom_mask'][i,...]) )\n\n    # Then unpack and compute confidence metrics\n    confidence_metrics = {}\n    for i in range(prediction_result['predicted_lddt']['logits'].shape[0]):\n        key = tags[i]\n\n        curr_metrics = {}\n        curr_metrics['distogram'] = prediction_result['distogram']\n        curr_metrics['plddt'] = confidence.compute_plddt(\n                prediction_result['predicted_lddt']['logits'][i,...])\n        if 'predicted_aligned_error' in prediction_result:\n            curr_metrics.update(confidence.compute_predicted_aligned_error(\n                prediction_result['predicted_aligned_error']['logits'][i,...],\n                prediction_result['predicted_aligned_error']['breaks'][i,...]))\n\n        confidence_metrics[key] = curr_metrics\n\n    for tag in tags:\n\n        unrelaxed_pdb_lines = protein.to_pdb(proteins[tag])\n        \n        outtag = f'{tag}_af2pred'\n        unrelaxed_pdb_path = f'temp_af2output.pdb'\n        with open(unrelaxed_pdb_path, 'w') as f: f.write(unrelaxed_pdb_lines)\n        \n        score_dict = generate_scoredict( outtag, start, binderlen_dict[tag], confidence_metrics[tag], scorefilename )\n\n        add2silent( outtag, unrelaxed_pdb_path, score_dict, binderlen_dict[tag], sfd_out ) \n        os.remove( unrelaxed_pdb_path )\n\ndef insert_truncations(residue_index, Ls):\n    # Minkyung's chainbreak wizardry\n    idx_res = residue_index\n    for break_i in Ls:\n        idx_res[break_i:] += 200\n    residue_index = idx_res\n\n    return residue_index\n\ndef add2silent( tag, pdb, score_dict, binderlen, sfd_out ):\n    pose = pose_from_file( pdb )\n\n    pose = insert_chainbreaks( pose, binderlen )\n\n    struct = sfd_out.create_SilentStructOP()\n    struct.fill_struct( pose, tag )\n\n    for scorename, value in score_dict.items():\n        struct.add_energy(scorename, value, 1)\n\n    sfd_out.add_structure( struct )\n    sfd_out.write_silent_struct( struct, \"out.silent\" )\n\ndef predict_structure(tags, feature_dict_dict, binderlen_dict, initial_guess_dict, sfd_out, scorefilename, random_seed=0):  \n  \"\"\"Predicts structure using AlphaFold for the given sequence.\"\"\"\n\n  start = timer()\n  print(f\"running {model_name}\")\n  model_runner.params = model_params\n  \n  processed_feature_dict, processed_initial_guess_dict = combine_batches(tags, feature_dict_dict, initial_guess_dict)\n\n  prediction_result = jax.vmap(model_runner.apply, in_axes=(None,None,0,0))(model_runner.params,\n          jax.random.PRNGKey(0), processed_feature_dict, processed_initial_guess_dict)\n\n  unpack_batches( tags, binderlen_dict, start, feature_dict_dict, prediction_result, sfd_out, scorefilename ) \n\n  print( f\"{args.batch_size} predictions made in {timer() - start} seconds\" )\n\n# Mostly taken from af2 source\n# Going to use to detect truncation points\ndef check_residue_distances(all_positions,\n                             all_positions_mask,\n                             max_amide_distance):\n  \"\"\"Checks if the distance between unmasked neighbor residues is ok.\"\"\"\n  breaks = []\n\n  c_position = residue_constants.atom_order['C']\n  n_position = residue_constants.atom_order['N']\n  prev_is_unmasked = False\n  this_c = None\n  for i, (coords, mask) in enumerate(zip(all_positions, all_positions_mask)):\n    this_is_unmasked = bool(mask[c_position]) and bool(mask[n_position])\n    if this_is_unmasked:\n      this_n = coords[n_position]\n      if prev_is_unmasked:\n        distance = np.linalg.norm(this_n - prev_c)\n        if distance > max_amide_distance:\n          breaks.append(i)\n          print( f'The distance between residues {i} and {i+1} is {distance:.2f} A' +\n                     f' > limit {max_amide_distance} A.' )\n          print( f\"I'm going to insert a chainbreak after residue {i}\" )\n      prev_c = coords[c_position]\n    prev_is_unmasked = this_is_unmasked\n\n  return breaks\n\ndef generate_feature_dict( pdbfile ):\n  seq_list = get_seq_from_pdb(pdbfile)\n  query_sequence = ''.join(seq_list)\n\n  initial_guess = af2_all_atom_from_struct(pdbfile, seq_list, just_target=False)\n\n  template_dict, all_atom_positions, all_atom_masks = template_from_struct(pdbfile, seq_list)\n  \n  # Gather features\n  feature_dict = {\n      **pipeline.make_sequence_features(sequence=query_sequence,\n                                        description=\"none\",\n                                        num_res=len(query_sequence)),\n      **pipeline.make_msa_features(msas=[[query_sequence]],\n                                   deletion_matrices=[[[0]*len(query_sequence)]]),\n      **template_dict\n  }\n  \n  max_amide_distance = 3\n  breaks = check_residue_distances(all_atom_positions, all_atom_masks, max_amide_distance)\n\n  feature_dict['residue_index'] = insert_truncations(feature_dict['residue_index'], breaks)\n\n  return feature_dict, initial_guess, len(seq_list[0]) \n\ndef input_check( pdbfile, tag ):\n    with open(pdbfile,'r') as f: lines = f.readlines()\n\n    seen_indices = set()\n    chain1 = True\n\n    for line in lines:\n        line = line.strip()\n        \n        if len(line) == 0: continue\n\n        splits = line.split()\n\n        if splits[0] == \"TER\":\n            chain1 = False\n            continue\n\n        if not splits[0] == \"ATOM\": continue\n\n        if splits[2] == 'CA':\n            # Only checking residue index at CA atom\n            residx = splits[5]\n            if residx in seen_indices:\n                sys.exit( f\"\\nNon-unique residue indices detected for tag: {tag}. \" +\n                \"This will cause AF2 to yield garbage outputs. Exiting.\" )\n\n            seen_indices.add(residx)\n\n        if ( not splits[4] == \"A\" ) and chain1:\n            sys.exit( f\"\\nThe first chain in the pose must be the binder and it must be chain A. \" +\n                    f\"Tag: {tag} does not satisfy this requirement. Exiting.\" )\n\ndef tag_buffer2features(tag_buffer, sfd_in):\n  \n  feature_dict_dict = {}\n  initial_guess_dict = {}\n  binderlen_dict = {}\n\n  for tag in tag_buffer:\n    # dump pdb\n    pose = Pose()\n    sfd_in.get_structure(tag).fill_pose(pose)\n    pose.dump_pdb(tmppdb)\n\n    # Input Checking\n    # Must ensure that:\n    # - All residue indices are unique\n    # - The first chain is \"A\"\n\n    input_check(tmppdb, tag)\n    \n    feature_dict, initial_guess, binderlen = generate_feature_dict(tmppdb)\n    feature_dict_dict[tag] = model_runner.process_features(feature_dict, random_seed=0)\n    initial_guess_dict[tag] = initial_guess\n    binderlen_dict[tag] = binderlen\n\n    os.remove( tmppdb )\n\n  return feature_dict_dict, initial_guess_dict, binderlen_dict\n\n# Checkpointing Functions\n\ndef record_checkpoint( tag_buffer, checkpoint_filename ):\n    with open( checkpoint_filename, 'a' ) as f:\n        for tag in tag_buffer:\n            f.write( tag )\n            f.write( '\\n' )\n\ndef determine_finished_structs( checkpoint_filename ):\n    done_set = set()\n    if not os.path.isfile( checkpoint_filename ): return done_set\n\n    with open( checkpoint_filename, 'r' ) as f:\n        for line in f:\n            done_set.add( line.strip() )\n\n    return done_set\n\n# End Checkpointing Functions\n\n################## Begin Main Function ##################\n\nsfd_out = core.io.silent.SilentFileData( \"out.silent\", False, False, \"binary\", core.io.silent.SilentFileOptions())\n\nsfd_in = rosetta.core.io.silent.SilentFileData(rosetta.core.io.silent.SilentFileOptions())\nsfd_in.read_file(args.silent)\n\nalltags = silent_tools.get_silent_index(args.silent)[\"tags\"]\ntmppdb = 'tmp.pdb'\n\ncheckpoint_filename = \"check.point\"\nscorefilename = \"out.sc\"\ntag_buffer = []\n\nfinished_structs = determine_finished_structs( checkpoint_filename )\n\nfor idx,tag in enumerate(alltags):\n  \n  if tag in finished_structs:\n    print( f\"SKIPPING {tag}, since it was already run\" )\n    continue\n  \n  tag_buffer.append(tag)\n  if (len(tag_buffer) < args.batch_size) and not idx>=(len(alltags)-1) : continue\n  \n  feature_dict_dict, initial_guess_dict, binderlen_dict = tag_buffer2features(tag_buffer, sfd_in)\n  predict_structure(tag_buffer, feature_dict_dict, binderlen_dict, initial_guess_dict, sfd_out, scorefilename)\n\n  record_checkpoint( tag_buffer, checkpoint_filename )\n  tag_buffer = []\n\nprint('done predicting')\n", "meta": {"hexsha": "09438b534682db1a2a82c8acca2f601073605d70", "size": 21703, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/af2_interface_metrics.py", "max_stars_repo_name": "RosettaCommons/RFDesign", "max_stars_repo_head_hexsha": "b404b8b2c57f89c047529c30259aeeb8f6012b61", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45, "max_stars_repo_stars_event_min_datetime": "2022-01-12T04:39:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T12:33:36.000Z", "max_issues_repo_path": "scripts/af2_interface_metrics.py", "max_issues_repo_name": "RosettaCommons/RFDesign", "max_issues_repo_head_hexsha": "b404b8b2c57f89c047529c30259aeeb8f6012b61", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2022-01-15T16:48:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T16:20:34.000Z", "max_forks_repo_path": "scripts/af2_interface_metrics.py", "max_forks_repo_name": "RosettaCommons/RFDesign", "max_forks_repo_head_hexsha": "b404b8b2c57f89c047529c30259aeeb8f6012b61", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2022-01-12T11:28:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:36:41.000Z", "avg_line_length": 35.991708126, "max_line_length": 152, "alphanum_fraction": 0.6959406534, "include": true, "reason": "import numpy,import scipy,import jax", "num_tokens": 5445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.1931686801915882}}
{"text": "# Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\n此模块包含构造 MBQC 模型的常用类和配套的运算模拟工具。\n\"\"\"\n\nfrom numpy import random, pi\nfrom networkx import Graph, spring_layout, draw_networkx\nimport matplotlib.pyplot as plt\nfrom paddle import t, to_tensor, matmul, conj, real, reshape, multiply\nfrom paddle_quantum.mbqc.utils import plus_state, cz_gate, pauli_gate\nfrom paddle_quantum.mbqc.utils import basis, kron, div_str_to_float\nfrom paddle_quantum.mbqc.utils import permute_to_front, permute_systems, print_progress, plot_results\nfrom paddle_quantum.mbqc.qobject import State, Pattern\nfrom paddle_quantum.mbqc.transpiler import transpile\n\n__all__ = [\n    \"MBQC\",\n    \"simulate_by_mbqc\"\n]\n\n\nclass MBQC:\n    r\"\"\"定义基于测量的量子计算模型 ``MBQC`` 类。\n\n    用户可以通过实例化该类来定义自己的 MBQC 模型。\n    \"\"\"\n\n    def __init__(self):\n        r\"\"\"MBQC 类的构造函数，用于实例化一个 ``MBQC`` 对象。\n        \"\"\"\n        self.__graph = None  # Graph in a MBQC model\n        self.__pattern = None  # Measurement pattern in a MBQC model\n\n        self.__bg_state = State()  # Background state of computation\n        self.__history = [self.__bg_state]  # History of background states\n        self.__status = self.__history[-1] if self.__history != [] else None  # latest history item\n\n        self.vertex = None  # Vertex class to maintain all the vertices\n        self.__outcome = {}  # Dictionary to store all measurement outcomes\n        self.max_active = 0  # Maximum number of active vertices so far\n\n        self.__draw = False  # Switch to draw the dynamical running process\n        self.__track = False  # Switch to track the running progress\n        self.__pause_time = None  # Pause time for drawing\n        self.__pos = None  # Position for drawing\n\n    class Vertex:\n        r\"\"\"定义维护点列表，用于实例化一个 ``Vertex`` 对象。\n\n        将 MBQC 算法中图的节点分为三类，并进行动态维护。\n\n        Note:\n            这是内部类，用户不需要直接调用到该类。\n\n        Attributes:\n            total (list): MBQC 算法中图上的全部节点，不随运算而改变\n            pending (list): 待激活的节点，随着运算的执行而逐渐减少\n            active (list): 激活的节点，与当前测量步骤直接相关的节点\n            measured (list): 已被测量过的节点，随着运算的执行而逐渐增加\n        \"\"\"\n\n        def __init__(self, total=None, pending=None, active=None, measured=None):\n            r\"\"\"``Vertex`` 类的构造函数，用于实例化一个 ``Vertex`` 对象。\n\n            Args:\n                total (list): MBQC 算法中图上的全部节点，不随运算而改变\n                pending (list): 待激活的节点，随着运算的执行而逐渐减少\n                active (list): 激活的节点，与当前测量步骤直接相关的节点\n                measured (list): 已被测量过的节点，随着运算的执行而逐渐增加\n            \"\"\"\n            self.total = [] if total is None else total\n            self.pending = [] if pending is None else pending\n            self.active = [] if active is None else active\n            self.measured = [] if measured is None else measured\n\n    def set_graph(self, graph):\n        r\"\"\"设置 MBQC 模型中的图。\n\n        该函数用于将用户自己构造的图传递给 ``MBQC`` 实例。\n        \n        Args:\n            graph (list): MBQC 模型中的图，由列表 ``[V, E]`` 给出， 其中 ``V`` 为节点列表，``E`` 为边列表\n        \"\"\"\n        vertices, edges = graph\n\n        vertices_of_edges = set([vertex for edge in edges for vertex in list(edge)])\n        assert vertices_of_edges.issubset(vertices), \"edge must be between the graph vertices.\"\n\n        self.__graph = Graph()\n        self.__graph.add_nodes_from(vertices)\n        self.__graph.add_edges_from(edges)\n\n        self.vertex = self.Vertex(total=vertices, pending=vertices, active=[], measured=[])\n\n    def get_graph(self):\n        r\"\"\"获取图的信息。\n\n        Returns:\n            nx.Graph: 图\n        \"\"\"\n        return self.__graph\n\n    def set_pattern(self, pattern):\n        r\"\"\"设置 MBQC 模型的测量模式。\n\n        该函数用于将用户由电路图翻译得到或自己构造的测量模式传递给 ``MBQC`` 实例。\n\n        Warning:\n            输入的 pattern 参数是 ``Pattern`` 类型，其中命令列表为标准 ``EMC`` 命令。\n\n        Args:\n            pattern (Pattern): MBQC 算法对应的测量模式\n        \"\"\"\n        assert isinstance(pattern, Pattern), \"please input a pattern of type 'Pattern'.\"\n\n        self.__pattern = pattern\n        cmds = self.__pattern.commands[:]\n\n        # Check if the pattern is a standard EMC form\n        cmd_map = {\"E\": 1, \"M\": 2, \"X\": 3, \"Z\": 4, \"S\": 5}\n        cmd_num_wild = [cmd_map[cmd.name] for cmd in cmds]\n        cmd_num_standard = cmd_num_wild[:]\n        cmd_num_standard.sort(reverse=False)\n        assert cmd_num_wild == cmd_num_standard, \"input pattern is not a standard EMC form.\"\n\n        # Set graph by entanglement commands\n        edges = [tuple(cmd.which_qubits) for cmd in cmds if cmd.name == \"E\"]\n        vertices = list(set([vertex for edge in edges for vertex in list(edge)]))\n        graph = [vertices, edges]\n        self.set_graph(graph)\n\n    def get_pattern(self):\n        r\"\"\"获取测量模式的信息。\n\n        Returns:\n            Pattern: 测量模式\n        \"\"\"\n        return self.__pattern\n\n    def set_input_state(self, state=None):\n        r\"\"\"设置需要替换的输入量子态。\n\n        Warning:\n            与电路模型不同，MBQC 模型通常默认初始态为加态。如果用户不调用此方法设置初始量子态，则默认为加态。\n            如果用户以测量模式运行 MBQC，则此处输入量子态的系统标签会被限制为从零开始的自然数，类型为整型。\n\n        Args:\n            state (State): 需要替换的量子态，默认为加态\n        \"\"\"\n        assert self.__graph is not None, \"please set 'graph' or 'pattern' before calling 'set_input_state'.\"\n        assert isinstance(state, State) or state is None, \"please input a state of type 'State'.\"\n        vertices = list(self.__graph.nodes)\n\n        if state is None:\n            vector = plus_state()\n            system = [vertices[0]]  # Activate the first vertex, system should be a list\n        else:\n            vector = state.vector\n            # If a pattern is set, map the input state system to the pattern's input\n            if self.__pattern is not None:\n                assert all(isinstance(label, int) for label in state.system), \"please input system labels of type 'int'\"\n                assert all(label >= 0 for label in state.system), \"please input system labels with non-negative values\"\n\n                system = [label for label in self.__pattern.input_ if int(div_str_to_float(label[0])) in state.system]\n            else:\n                system = state.system\n        assert set(system).issubset(vertices), \"input system labels must be a subset of graph vertices.\"\n\n        self.__bg_state = State(vector, system)\n        self.__history = [self.__bg_state]\n        self.__status = self.__history[-1]\n        self.vertex = self.Vertex(total=vertices,\n                                  pending=list(set(vertices).difference(system)),\n                                  active=system,\n                                  measured=[])\n        self.max_active = len(self.vertex.active)\n\n    def __set_position(self, pos):\n        r\"\"\"设置动态过程图绘制时节点的位置坐标。\n\n        Note:\n            这是内部方法，用户并不需要直接调用到该方法。\n\n        Args:\n            pos (dict or bool, optional): 节点坐标的字典数据或者内置的坐标选择，\n                                          内置的坐标选择有：``True`` 为测量模式自带的坐标，``False`` 为 ``spring_layout`` 坐标\n        \"\"\"\n        assert isinstance(pos, bool) or isinstance(pos, dict), \"'pos' should be either bool or dict.\"\n        if isinstance(pos, dict):\n            self.__pos = pos\n        elif pos:\n            assert self.__pattern is not None, \"'pos=True' must be chosen after a pattern is set.\"\n            self.__pos = {v: [div_str_to_float(v[1]), - div_str_to_float(v[0])] for v in list(self.__graph.nodes)}\n        else:\n            self.__pos = spring_layout(self.__graph)  # Use 'spring_layout' otherwise\n\n    def __draw_process(self, which_process, which_qubit):\n        r\"\"\"根据当前节点状态绘图，用以实时展示 MBQC 模型的模拟计算过程。\n\n        Note:\n            这是内部方法，用户并不需要直接调用到该方法。\n\n        Args:\n            which_process (str): MBQC 执行的阶段，\"measuring\", \"active\" 或者 \"measured\"\n            which_qubit (any): 当前关注的节点，可以是 ``str``, ``tuple`` 等任意数据类型，但需要和图的标签类型匹配\n        \"\"\"\n        if self.__draw:\n            assert which_process in [\"measuring\", \"active\", \"measured\"]\n            assert which_qubit in self.vertex.total, \"'which_qubit' must be in the graph.\"\n\n            vertex_sets = []\n            # Find where the 'which_qubit' is\n            if which_qubit in self.vertex.pending:\n                pending = self.vertex.pending[:]\n                pending.remove(which_qubit)\n                vertex_sets = [pending, self.vertex.active, [which_qubit], self.vertex.measured]\n            elif which_qubit in self.vertex.active:\n                active = self.vertex.active[:]\n                active.remove(which_qubit)\n                vertex_sets = [self.vertex.pending, active, [which_qubit], self.vertex.measured]\n            elif which_qubit in self.vertex.measured:\n                vertex_sets = [self.vertex.pending, self.vertex.active, [], self.vertex.measured]\n\n            # Indentify ancilla vertices\n            ancilla_qubits = []\n            if self.__pattern is not None:\n                for vertex in list(self.__graph.nodes):\n                    row_coordinate = div_str_to_float(vertex[0])\n                    col_coordinate = div_str_to_float(vertex[1])\n                    # Ancilla vertices do not have integer coordinates\n                    if abs(col_coordinate - int(col_coordinate)) >= 1e-15 \\\n                            or abs(row_coordinate - int(row_coordinate)) >= 1e-15:\n                        ancilla_qubits.append(vertex)\n\n            plt.cla()\n            plt.title(\"MBQC Running Process\", fontsize=15)\n            plt.xlabel(\"Measuring (RED)  Active (GREEN)  Pending (BLUE)  Measured (GRAY)\", fontsize=12)\n            plt.grid()\n            mngr = plt.get_current_fig_manager()\n            mngr.window.setGeometry(500, 100, 800, 600)\n            colors = ['tab:blue', 'tab:green', 'tab:red', 'tab:gray']\n            for j in range(4):\n                for vertex in vertex_sets[j]:\n                    options = {\n                        \"nodelist\": [vertex],\n                        \"node_color\": colors[j],\n                        \"node_shape\": '8' if vertex in ancilla_qubits else 'o',\n                        \"with_labels\": False,\n                        \"width\": 3,\n                    }\n                    draw_networkx(self.__graph, self.__pos, **options)\n                    ax = plt.gca()\n                    ax.margins(0.20)\n                    plt.axis(\"on\")\n                    ax.set_axisbelow(True)\n            plt.pause(self.__pause_time)\n\n    def draw_process(self, draw=True, pos=False, pause_time=0.5):\n        r\"\"\"动态过程图绘制，用以实时展示 MBQC 模型的模拟计算过程。\n\n        Args:\n            draw (bool, optional): 是否绘制动态过程图的布尔开关\n            pos (bool or dict, optional): 节点坐标的字典数据或者内置的坐标选择，内置的坐标选择有：\n                                            ``True`` 为测量模式自带的坐标，``False`` 为 `spring_layout` 坐标\n            pause_time (float, optional): 绘制动态过程图时每次更新的停顿时间\n        \"\"\"\n        assert self.__graph is not None, \"please set 'graph' or 'pattern' before calling 'draw_process'.\"\n        assert isinstance(draw, bool), \"'draw' must be bool.\"\n        assert isinstance(pos, bool) or isinstance(pos, dict), \"'pos' should be either bool or dict.\"\n        assert pause_time > 0, \"'pause_time' must be strictly larger than 0.\"\n\n        self.__draw = draw\n        self.__pause_time = pause_time\n\n        if self.__draw:\n            plt.figure()\n            plt.ion()\n            self.__set_position(pos)\n\n    def track_progress(self, track=True):\n        r\"\"\" 显示 MBQC 模型运行进度的开关。\n\n        Args:\n            track (bool, optional): ``True`` 打开进度条显示功能， ``False`` 关闭进度条显示功能\n        \"\"\"\n        assert isinstance(track, bool), \"the parameter 'track' must be bool.\"\n        self.__track = track\n\n    def __apply_cz(self, which_qubits_list):\n        r\"\"\"对给定的两个比特作用控制 Z 门。\n\n        Note:\n            这是内部方法，用户并不需要直接调用到该方法。\n\n        Warning:\n            作用控制 Z 门的两个比特一定是被激活的。\n\n        Args:\n            which_qubits_list (list): 作用控制 Z 门的比特对标签列表，例如 ``[(1, 2), (3, 4),...]``\n        \"\"\"\n        for which_qubits in which_qubits_list:\n            assert set(which_qubits).issubset(self.vertex.active), \\\n                \"vertices in 'which_qubits_list' must be activated first.\"\n            assert which_qubits[0] != which_qubits[1], \\\n                'the control and target qubits must not be the same.'\n\n            # Find the control and target qubits and permute them to the front\n            self.__bg_state = permute_to_front(self.__bg_state, which_qubits[0])\n            self.__bg_state = permute_to_front(self.__bg_state, which_qubits[1])\n\n            new_state = self.__bg_state\n            new_state_len = new_state.length\n            qua_length = int(new_state_len / 4)\n            cz = cz_gate()\n            # Reshape the state, apply CZ and reshape it back\n            new_state.vector = reshape(matmul(cz, reshape(new_state.vector, [4, qua_length])), [new_state_len, 1])\n\n            # Update the order of active vertices and the background state\n            self.vertex.active = new_state.system\n            self.__bg_state = State(new_state.vector, new_state.system)\n\n    def __apply_pauli_gate(self, gate, which_qubit):\n        r\"\"\"对给定的单比特作用 Pauli 门。\n\n        Note:\n            这是内部方法，用户并不需要直接调用到该方法。\n\n        Args:\n            gate (str): Pauli 门的索引字符，\"I\", \"X\", \"Y\", \"Z\" 分别表示对应的门，在副产品处理时用 \"X\" 和 \"Z\" 门\n            which_qubit (any): 作用 Pauli 门的系统标签，\n                               可以是 ``str``, ``tuple`` 等任意数据类型，但需要和 MBQC 模型中节点的标签类型匹配\n        \"\"\"\n        new_state = permute_to_front(self.__bg_state, which_qubit)\n        new_state_len = new_state.length\n        half_length = int(new_state_len / 2)\n        gate_mat = pauli_gate(gate)\n        # Reshape the state, apply X and reshape it back\n        new_state.vector = reshape(matmul(gate_mat, reshape(new_state.vector, [2, half_length])), [new_state_len, 1])\n        # Update the order of active vertices and the background state\n        self.vertex.active = new_state.system\n        self.__bg_state = State(new_state.vector, new_state.system)\n\n    def __create_graph_state(self, which_qubit):\n        r\"\"\"以待测量的比特为输入参数，生成测量当前节点所需要的最小的量子图态。\n\n        Note:\n            这是内部方法，用户并不需要直接调用到该方法。\n\n        Args:\n            which_qubit (any): 待测量比特的系统标签。\n                                可以是 ``str``, ``tuple`` 等任意数据类型，但需要和 MBQC 模型中节点的标签类型匹配\n        \"\"\"\n        # Find the neighbors of 'which_qubit'\n        which_qubit_neighbors = set(self.__graph.neighbors(which_qubit))\n        # Exclude the qubits already measured\n        neighbors_not_measured = which_qubit_neighbors.difference(set(self.vertex.measured))\n        # Create a list of system labels that will be applied to cz gates\n        cz_list = [(which_qubit, qubit) for qubit in neighbors_not_measured]\n        # Get the qubits to be activated\n        append_qubits = {which_qubit}.union(neighbors_not_measured).difference(set(self.vertex.active))\n        # Update active and pending lists\n        self.vertex.active += list(append_qubits)\n        self.vertex.pending = list(set(self.vertex.pending).difference(self.vertex.active))\n\n        # Compute the new background state vector\n        new_bg_state_vector = kron([self.__bg_state.vector] + [plus_state() for _ in append_qubits])\n\n        # Update the background state and apply cz\n        self.__bg_state = State(new_bg_state_vector, self.vertex.active)\n        self.__apply_cz(cz_list)\n        self.__draw_process(\"active\", which_qubit)\n\n    def __update(self):\n        r\"\"\"更新历史列表和量子态信息。\n        \"\"\"\n        self.__history.append(self.__bg_state)\n        self.__status = self.__history[-1]\n\n    def measure(self, which_qubit, basis_list):\n        r\"\"\"以待测量的比特和测量基为输入参数，对该比特进行测量。\n\n        Note:\n            这是用户在实例化 MBQC 类之后最常调用的方法之一，此处我们对单比特测量模拟进行了最大程度的优化，\n            随着用户对该函数的调用，MBQC 类将自动完成激活相关节点、生成所需的图态以及对特定比特进行测量的全过程，\n            并记录测量结果和对应测量后的量子态。用户每调用一次该函数，就完成一次对单比特的测量操作。\n\n        Warning:\n            当且仅当用户调用 ``measure`` 类方法时，MBQC 模型才真正进行运算。\n\n        Args:\n            which_qubit (any): 待测量量子比特的系统标签，\n                                可以是 ``str``, ``tuple`` 等任意数据类型，但需要和 MBQC 模型的图上标签匹配\n            basis_list (list): 测量基向量构成的列表，列表元素为 ``Tensor`` 类型的列向量\n\n        代码示例：\n\n        .. code-block:: python\n\n            from paddle_quantum.mbqc.simulator import MBQC\n            from paddle_quantum.mbqc.qobject import State\n            from paddle_quantum.mbqc.utils import zero_state, basis\n\n            G = [['1', '2', '3'], [('1', '2'), ('2', '3')]]\n            mbqc = MBQC()\n            mbqc.set_graph(G)\n            state = State(zero_state(), ['1'])\n            mbqc.set_input_state(state)\n            mbqc.measure('1', basis('X'))\n            mbqc.measure('2', basis('X'))\n            print(\"Measurement outcomes: \", mbqc.get_classical_output())\n\n        ::\n\n            Measurement outcomes:  {'1': 0, '2': 1}\n        \"\"\"\n        self.__draw_process(\"measuring\", which_qubit)\n        self.__create_graph_state(which_qubit)\n        assert which_qubit in self.vertex.active, 'the qubit to be measured must be activated first.'\n\n        new_bg_state = permute_to_front(self.__bg_state, which_qubit)\n        self.vertex.active = new_bg_state.system\n        half_length = int(new_bg_state.length / 2)\n\n        eps = 10 ** (-10)\n        prob = [0, 0]\n        state_unnorm = [0, 0]\n\n        # Calculate the probability and post-measurement states\n        for result in [0, 1]:\n            basis_dagger = t(conj(basis_list[result]))\n            # Reshape the state, multiply the basis and reshape it back\n            state_unnorm[result] = reshape(matmul(basis_dagger,\n                                                  reshape(new_bg_state.vector, [2, half_length])), [half_length, 1])\n            probability = matmul(t(conj(state_unnorm[result])), state_unnorm[result])\n            is_complex128 = probability.dtype == to_tensor([], dtype='complex128').dtype\n            prob[result] = real(probability) if is_complex128 else probability\n\n        # Randomly choose a result and its corresponding post-measurement state\n        if prob[0].numpy().item() < eps:\n            result = 1\n            post_state_vector = state_unnorm[1]\n        elif prob[1].numpy().item() < eps:\n            result = 0\n            post_state_vector = state_unnorm[0]\n        else:  # Take a random choice of outcome\n            result = random.choice(2, 1, p=[prob[0].numpy().item(), prob[1].numpy().item()]).item()\n            # Normalize the post-measurement state\n            post_state_vector = state_unnorm[result] / prob[result].sqrt()\n\n        # Write the measurement result into the dict\n        self.__outcome.update({which_qubit: int(result)})\n        # Update measured, active lists\n        self.vertex.measured.append(which_qubit)\n        self.max_active = max(len(self.vertex.active), self.max_active)\n        self.vertex.active.remove(which_qubit)\n\n        # Update the background state and history list\n        self.__bg_state = State(post_state_vector, self.vertex.active)\n        self.__update()\n\n        self.__draw_process(\"measured\", which_qubit)\n\n    def sum_outcomes(self, which_qubits, start=0):\n        r\"\"\"根据输入的量子系统标签，在存储测量结果的字典中找到对应的测量结果，并进行求和。\n\n        Note:\n            在进行副产品纠正操作和定义适应性测量角度时，用户可以调用该方法对特定比特的测量结果求和。\n\n        Args:\n            which_qubits (list): 需要查找测量结果并求和的比特的系统标签列表\n            start (int): 对结果进行求和后需要额外相加的整数\n\n        Returns:\n            int: 指定比特的测量结果的和\n\n        代码示例：\n\n        .. code-block:: python\n\n            from paddle_quantum.mbqc.simulator import MBQC\n            from paddle_quantum.mbqc.qobject import State\n            from paddle_quantum.mbqc.utils import zero_state, basis\n\n            G = [['1', '2', '3'], [('1', '2'), ('2', '3')]]\n            mbqc = MBQC()\n            mbqc.set_graph(G)\n            input_state = State(zero_state(), ['1'])\n            mbqc.set_input_state(input_state)\n            mbqc.measure('1', basis('X'))\n            mbqc.measure('2', basis('X'))\n            mbqc.measure('3', basis('X'))\n            print(\"All measurement outcomes: \", mbqc.get_classical_output())\n            print(\"Sum of outcomes of qubits '1' and '2': \", mbqc.sum_outcomes(['1', '2']))\n            print(\"Sum of outcomes of qubits '1', '2' and '3' with an extra 1: \", mbqc.sum_outcomes(['1', '2', '3'], 1))\n\n        ::\n\n            All measurement outcomes:  {'1': 0, '2': 0, '3': 1}\n            Sum of outcomes of qubits '1' and '2':  0\n            Sum of outcomes of qubits '1', '2' and '3' with an extra 1:  2\n        \"\"\"\n        assert isinstance(start, int), \"'start' must be of type int.\"\n\n        return sum([self.__outcome[label] for label in which_qubits], start)\n\n    def correct_byproduct(self, gate, which_qubit, power):\n        r\"\"\"对测量后的量子态进行副产品纠正。\n\n        Note:\n            这是用户在实例化 MBQC 类并完成测量后，经常需要调用的一个方法。\n\n        Args:\n            gate (str): ``'X'`` 或者 ``'Z'``，分别表示 Pauli X 或 Z 门修正\n            which_qubit (any): 待操作的量子比特的系统标签，可以是 ``str``, ``tuple`` 等任意数据类型，但需要和 MBQC 中图的标签类型匹配\n            power (int): 副产品纠正算符的指数\n\n        代码示例：\n\n            此处展示的是 MBQC 模型下实现隐形传态的一个例子。\n\n        .. code-block:: python\n\n            from paddle_quantum.mbqc.simulator import MBQC\n            from paddle_quantum.mbqc.qobject import State\n            from paddle_quantum.mbqc.utils import random_state_vector, basis, compare_by_vector\n\n            G = [['1', '2', '3'], [('1', '2'), ('2', '3')]]\n            state = State(random_state_vector(1), ['1'])\n            mbqc = MBQC()\n            mbqc.set_graph(G)\n            mbqc.set_input_state(state)\n            mbqc.measure('1', basis('X'))\n            mbqc.measure('2', basis('X'))\n            outcome = mbqc.get_classical_output()\n            mbqc.correct_byproduct('Z', '3', outcome['1'])\n            mbqc.correct_byproduct('X', '3', outcome['2'])\n            state_out = mbqc.get_quantum_output()\n            state_std = State(state.vector, ['3'])\n            compare_by_vector(state_out, state_std)\n\n        ::\n\n            Norm difference of the given states is:\n             0.0\n            They are exactly the same states.\n        \"\"\"\n        assert gate in ['X', 'Z'], \"'gate' must be 'X' or 'Z'.\"\n        assert isinstance(power, int), \"'power' must be of type 'int'.\"\n\n        if power % 2 == 1:\n            self.__apply_pauli_gate(gate, which_qubit)\n        self.__update()\n\n    def __run_cmd(self, cmd):\n        r\"\"\"执行测量或副产品处理命令。\n\n        Args:\n            cmd (Pattern.CommandM / Pattern.CommandX / Pattern.CommandZ): 测量或副产品处理命令\n        \"\"\"\n        assert cmd.name in [\"M\", \"X\", \"Z\"], \"the input 'cmd' must be CommandM, CommandX or CommandZ.\"\n        if cmd.name == \"M\":  # Execute measurement commands\n            signal_s = self.sum_outcomes(cmd.domain_s)\n            signal_t = self.sum_outcomes(cmd.domain_t)\n            # The adaptive angle is (-1)^{signal_s} * angle + {signal_t} * pi\n            adaptive_angle = multiply(to_tensor([(-1) ** signal_s], dtype=\"float64\"), cmd.angle) \\\n                             + to_tensor([signal_t * pi], dtype=\"float64\")\n            self.measure(cmd.which_qubit, basis(cmd.plane, adaptive_angle))\n        else:  # Execute byproduct correction commands\n            power = self.sum_outcomes(cmd.domain)\n            self.correct_byproduct(cmd.name, cmd.which_qubit, power)\n\n    def __run_cmd_lst(self, cmd_lst, bar_start, bar_end):\n        r\"\"\"对列表执行测量或副产品处理命令。\n\n        Args:\n            cmd_lst (list): 命令列表，包含测量或副产品处理命令\n            bar_start (int): 进度条的开始点\n            bar_end (int): 进度条的结束点\n        \"\"\"\n        for i in range(len(cmd_lst)):\n            cmd = cmd_lst[i]\n            self.__run_cmd(cmd)\n            print_progress((bar_start + i + 1) / bar_end, \"Pattern Running Progress\", self.__track)\n\n    def __kron_unmeasured_qubits(self):\n        r\"\"\"该方法将没有被作用 CZ 纠缠的节点初始化为 |+> 态，并与当前的量子态做张量积。\n\n        Warning:\n            该方法仅在用户输入测量模式时调用，当用户输入图时，如果节点没有被激活，我们默认用户没有对该节点进行任何操作。\n        \"\"\"\n        # Turn off the plot switch\n        self.__draw = False\n        # As the create_graph_state function would change the measured qubits list, we need to record it\n        measured_qubits = self.vertex.measured[:]\n\n        for qubit in list(self.__graph.nodes):\n            if qubit not in self.vertex.measured:\n                self.__create_graph_state(qubit)\n                # Update vertices and backgrounds\n                self.vertex.measured.append(qubit)\n                self.max_active = max(len(self.vertex.active), self.max_active)\n                self.__bg_state = State(self.__bg_state.vector, self.vertex.active)\n\n        # Restore the measured qubits\n        self.vertex.measured = measured_qubits\n\n    def run_pattern(self):\n        r\"\"\"按照设置的测量模式对 MBQC 模型进行模拟。\n\n        Warning:\n            该方法必须在 ``set_pattern`` 调用后调用。\n        \"\"\"\n        assert self.__pattern is not None, \"please use this method after calling 'set_pattern'!\"\n\n        # Execute measurement commands and correction commands\n        cmd_m_lst = [cmd for cmd in self.__pattern.commands if cmd.name == \"M\"]\n        cmd_c_lst = [cmd for cmd in self.__pattern.commands if cmd.name in [\"X\", \"Z\"]]\n        bar_end = len(cmd_m_lst + cmd_c_lst)\n\n        self.__run_cmd_lst(cmd_m_lst, 0, bar_end)\n        # Activate unmeasured qubits before byproduct corrections\n        self.__kron_unmeasured_qubits()\n        self.__run_cmd_lst(cmd_c_lst, len(cmd_m_lst), bar_end)\n\n        # The output state's label is messy (e.g. [(2, 0), (0, 1), (1, 3)...]),\n        # so we permute the systems in order\n        q_output = self.__pattern.output_[1]\n        self.__bg_state = permute_systems(self.__status, q_output)\n        self.__update()\n\n    @staticmethod\n    def __map_qubit_to_row(out_lst):\n        r\"\"\"将输出比特的标签与行数对应起来，便于查找其对应关系。\n\n        Returns:\n            dict: 返回字典，代表行数与标签的对应关系\n        \"\"\"\n        return {int(div_str_to_float(qubit[0])): qubit for qubit in out_lst}\n\n    def get_classical_output(self):\n        r\"\"\"获取 MBQC 模型运行后的经典输出结果。\n\n        Returns:\n            str or dict: 如果用户输入是测量模式，则返回测量输出节点得到的比特串，与原电路的测量结果相一致，没有被测量的比特位填充 \"？\"，如果用户输入是图，则返回所有节点的测量结果\n        \"\"\"\n        # If the input is pattern, return the equivalent result as the circuit model\n        if self.__pattern is not None:\n            width = len(self.__pattern.input_)\n            c_output = self.__pattern.output_[0]\n            q_output = self.__pattern.output_[1]\n            # Acquire the relationship between row number and corresponding output qubit label\n            output_lst = c_output + q_output\n            row_and_qubit = self.__map_qubit_to_row(output_lst)\n\n            # Obtain the string, with classical outputs denoted as their measurement outcomes\n            # and quantum outputs denoted as \"?\"\n            bit_str = [str(self.__outcome[row_and_qubit[i]])\n                       if row_and_qubit[i] in c_output else '?'\n                       for i in range(width)]\n            string = \"\".join(bit_str)\n            return string\n\n        # If the input is graph, return the outcome dictionary\n        else:\n            return self.__outcome\n\n    def get_history(self):\n        r\"\"\"获取 MBQC 计算模拟时的中间步骤信息。\n\n        Returns:\n            list: 生成图态、进行测量、纠正副产品后运算结果构成的列表\n        \"\"\"\n        return self.__history\n\n    def get_quantum_output(self):\n        r\"\"\"获取 MBQC 模型运行后的量子态输出结果。\n\n        Returns:\n            State: MBQC 模型运行后的量子态\n        \"\"\"\n        return self.__status\n\n\ndef simulate_by_mbqc(circuit, input_state=None):\n    r\"\"\"使用等价的 MBQC 模型模拟量子电路。\n\n    该函数通过将量子电路转化为等价的 MBQC 模型并运行，从而获得等价于原始量子电路的输出结果。\n\n    Warning:\n        与 ``UAnsatz`` 不同，此处输入的 ``circuit`` 参数包含了测量操作。\n        另，MBQC 模型默认初始态为加态，因此，如果用户不输入参数 ``input_state`` 设置初始量子态，则默认为加态。\n\n    Args:\n        circuit (Circuit): 量子电路图\n        input_state (State, optional): 量子电路的初始量子态，默认为 :math:`|+\\rangle` 态\n\n    Returns:\n        tuple: 包含如下两个元素:\n\n            - str: 经典输出\n            - State: 量子输出\n    \"\"\"\n    if input_state is not None:\n        assert isinstance(input_state, State), \"the 'input_state' must be of type 'State'.\"\n\n    pattern = transpile(circuit)\n    mbqc = MBQC()\n    mbqc.set_pattern(pattern)\n    mbqc.set_input_state(input_state)\n    mbqc.run_pattern()\n    c_output = mbqc.get_classical_output()\n    q_output = mbqc.get_quantum_output()\n\n    # Return the classical and quantum outputs\n    return c_output, q_output\n\n\ndef __get_sample_dict(bit_num, mea_bits, samples):\n    r\"\"\"根据比特数和测量比特索引的列表，统计采样结果。\n\n    Args:\n        bit_num (int): 比特数\n        mea_bits (list): 测量的比特列表\n        samples (list): 采样结果\n\n    Returns:\n        dict: 统计得到的采样结果\n    \"\"\"\n    sample_dict = {}\n    for i in range(2 ** len(mea_bits)):\n        str_of_order = bin(i)[2:].zfill(len(mea_bits))\n        bit_str = []\n        idx = 0\n        for j in range(bit_num):\n            if j in mea_bits:\n                bit_str.append(str_of_order[idx])\n                idx += 1\n            else:\n                bit_str.append('?')\n        string = \"\".join(bit_str)\n        sample_dict[string] = 0\n\n    # Count sampling results\n    for string in list(set(samples)):\n        sample_dict[string] += samples.count(string)\n    return sample_dict\n\n\ndef sample_by_mbqc(circuit, input_state=None, plot=False, shots=1024, print_or_not=True):\n    r\"\"\"将 MBQC 模型重复运行多次，获得经典结果的统计分布。\n   \n    Warning:\n        与 ``UAnsatz`` 不同，此处输入的 circuit 参数包含了测量操作。\n        另，MBQC 模型默认初始态为加态，因此，如果用户不输入参数 `input_state` 设置初始量子态，则默认为加态。\n\n    Args:\n        circuit (Circuit): 量子电路图\n        input_state (State, optional): 量子电路的初始量子态，默认为加态\n        plot (bool, optional): 绘制经典采样结果的柱状图开关，默认为关闭状态\n        shots (int, optional): 采样次数，默认为 1024 次\n        print_or_not (bool, optional): 是否打印采样结果和绘制采样进度，默认为开启状态\n\n    Returns:\n        dict: 经典结果构成的频率字典\n        list: 经典测量结果和所有采样结果（包括经典输出和量子输出）的列表\n    \"\"\"\n    # Initialize\n    if shots == 1:\n        print_or_not = False\n    if print_or_not:\n        print(\"Sampling \" + str(shots) + \" times.\" + \"\\nWill return the sampling results.\\r\\n\")\n    width = circuit.get_width()\n    mea_bits = circuit.get_measured_qubits()\n\n    # Sampling for \"shots\" times\n    samples = []\n    all_outputs = []\n    for shot in range(shots):\n        if print_or_not:\n            print_progress((shot + 1) / shots, \"Current Sampling Progress\")\n        c_output, q_output = simulate_by_mbqc(circuit, input_state)\n        samples.append(c_output)\n        all_outputs.append([c_output, q_output])\n\n    sample_dict = __get_sample_dict(width, mea_bits, samples)\n    if print_or_not:\n        print(\"Sample count \" + \"(\" + str(shots) + \" shots)\" + \" : \" + str(sample_dict))\n    if plot:\n        dict_lst = [sample_dict]\n        bar_labels = [\"MBQC sample outcomes\"]\n        title = 'Sampling results (MBQC)'\n        xlabel = \"Measurement outcomes\"\n        ylabel = \"Distribution\"\n        plot_results(dict_lst, bar_labels, title, xlabel, ylabel)\n\n    return sample_dict, all_outputs\n", "meta": {"hexsha": "1e6d859304913033979a2008147b061e6e640c87", "size": 30925, "ext": "py", "lang": "Python", "max_stars_repo_path": "paddle_quantum/mbqc/simulator.py", "max_stars_repo_name": "gsq7474741/Quantum", "max_stars_repo_head_hexsha": "16e7d3bf2dba7e94e6faf5c853faf0e913e1f268", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-14T14:10:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-14T14:10:23.000Z", "max_issues_repo_path": "paddle_quantum/mbqc/simulator.py", "max_issues_repo_name": "gsq7474741/Quantum", "max_issues_repo_head_hexsha": "16e7d3bf2dba7e94e6faf5c853faf0e913e1f268", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paddle_quantum/mbqc/simulator.py", "max_forks_repo_name": "gsq7474741/Quantum", "max_forks_repo_head_hexsha": "16e7d3bf2dba7e94e6faf5c853faf0e913e1f268", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1790123457, "max_line_length": 120, "alphanum_fraction": 0.5990622474, "include": true, "reason": "from numpy,from networkx", "num_tokens": 8977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.19316866786195516}}
{"text": "'''\nDescription: 查看生成的矩形\nAuthor: Lirenjie\nDate: 2021-12-21 21:22:08\nLastEditors: Lirenjie\nLastEditTime: 2021-12-22 15:55:23\n'''\nimport cv2\nimport numpy as np\nfrom numpy.linalg import norm\nimport sys\nimport os\nimport json\n\nimport turtle as t\nimport time\n\nimg = cv2.imread(\"C:\\\\Users\\\\lirenjie\\\\Desktop\\\\cAA662F.jpg\")\noldimg = cv2.GaussianBlur(img, (3, 3), 0)  # 图片分辨率调整\npic_hight, pic_width = (576, 704)\n\n\nbox = [[114, 295], [115, 259], [208, 262], [207, 298]]\n\nt.penup()\nt.goto(box[0])\n\nt.pendown()\nt.goto(box[1])\nt.goto(box[2])\nt.goto(box[3])\nt.goto(box[0])\n\nt.down()\n# time.sleep(3)\n\n\nheigth_point = right_point = [0, 0]\nleft_point = low_point = [1000, 1000]\nfor point in box:\n    if left_point[0] > point[0]:\n        left_point = point\n    if low_point[1] > point[1]:\n        low_point = point\n    if heigth_point[1] < point[1]:\n        heigth_point = point\n    if right_point[0] < point[0]:\n        right_point = point\n\n# 比较得到长边的斜率\nlength1 = (left_point[0] - low_point[0]) ** 2 + (left_point[1] - low_point[1]) ** 2\nlength2 = (right_point[0] - low_point[0]) ** 2 + (right_point[1] - low_point[1]) ** 2\nif length1 > length2:\n    k = (left_point[1] - low_point[1]) / (left_point[0] - low_point[0])\nelse:\n    k = (right_point[1] - low_point[1]) / (right_point[0] - low_point[0])\nprint('k', k)\n\nif k < 0:  # 正角度\n    new_right_point = [right_point[0], heigth_point[1]]\n    pts2 = np.float32([left_point, heigth_point, new_right_point])  # 字符只是高度需要改变\n    pts1 = np.float32([left_point, heigth_point, right_point])\n    M = cv2.getAffineTransform(pts1, pts2)  # 仿射变换\n    dst = cv2.warpAffine(oldimg, M, (pic_width, pic_hight))\n    cv2.imshow(\"card\", dst)\n    cv2.waitKey(0)\n    cv2.destroyAllWindows()\n    # dst = cv2.warpAffine(oldimg, M, (pic_width, pic_hight))\n    # cv2.imshow(\"card\", dst)\n    # cv2.waitKey(0)\n    # cv2.destroyAllWindows()\n\n    # point_limit(new_right_point)\n    # point_limit(heigth_point)\n    # point_limit(left_point)\n    # card_img = dst[\n    #     int(left_point[1]) : int(heigth_point[1]),\n    #     int(left_point[0]) : int(new_right_point[0]),\n    # ]\n\n    # print(card_img)\n\n    # card_imgs.append(card_img)\n    # cv2.imshow(\"card\", card_img)\n    # cv2.waitKey(0)\n    # cv2.destroyAllWindows()\nelif k > 0:  # 负角度\n    new_left_point = [left_point[0], heigth_point[1]]\n    pts2 = np.float32([new_left_point, heigth_point, right_point])  # 字符只是高度需要改变\n    pts1 = np.float32([left_point, heigth_point, right_point])\n    M = cv2.getAffineTransform(pts1, pts2)\n    dst = cv2.warpAffine(oldimg, M, (pic_width, pic_hight))\n    cv2.imshow(\"card\", dst)\n    cv2.waitKey(0)\n    cv2.destroyAllWindows()\n    # dst = cv2.warpAffine(oldimg, M, (pic_width, pic_hight))\n    # cv2.imshow(\"card\", dst)\n    # cv2.waitKey(0)\n    # cv2.destroyAllWindows()\n\n    # point_limit(right_point)\n    # point_limit(heigth_point)\n    # point_limit(new_left_point)\n    # card_img = dst[\n    #     int(right_point[1]) : int(heigth_point[1]),\n    #     int(new_left_point[0]) : int(right_point[0]),\n    # ]\n\n    # print(card_img)\n\n    # card_imgs.append(card_img)\n    # cv2.imshow(\"card\", card_img)\n    # cv2.waitKey(0)\n    # cv2.destroyAllWindows()\n\nprint(M)\n", "meta": {"hexsha": "a0dff3229ab0c14cc030d2377dcf91295b07478b", "size": 3150, "ext": "py", "lang": "Python", "max_stars_repo_path": "vehicle-license-plate-recognition/test1.py", "max_stars_repo_name": "xin9421/vehicle-license-plate-recognition", "max_stars_repo_head_hexsha": "e8d7312c65f3e9d6bd4f571a116ee659d4651d58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vehicle-license-plate-recognition/test1.py", "max_issues_repo_name": "xin9421/vehicle-license-plate-recognition", "max_issues_repo_head_hexsha": "e8d7312c65f3e9d6bd4f571a116ee659d4651d58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vehicle-license-plate-recognition/test1.py", "max_forks_repo_name": "xin9421/vehicle-license-plate-recognition", "max_forks_repo_head_hexsha": "e8d7312c65f3e9d6bd4f571a116ee659d4651d58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9230769231, "max_line_length": 85, "alphanum_fraction": 0.6425396825, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.35577490717496246, "lm_q1q2_score": 0.1931371341793934}}
{"text": "from typing import Callable, NamedTuple, Tuple\n\nimport jax\nimport jax.numpy as jnp\n\nfrom blackjax.types import PyTree\n\n\nclass SMCInfo(NamedTuple):\n    \"\"\"Additional information on the tempered SMC step.\n\n    weights: jnp.ndarray\n        The weights after the MCMC pass.\n    proposals: PyTree\n        The particles that were proposed by the MCMC pass.\n    ancestors: jnp.ndarray\n        The index of the particles proposed by the MCMC pass that were selected\n        by the resampling step.\n    log_likelihood_increment: float\n        The log-likelihood increment due to the current step of the SMC algorithm.\n    \"\"\"\n\n    weights: jnp.ndarray\n    proposals: PyTree\n    ancestors: jnp.ndarray\n    log_likelihood_increment: float\n\n\ndef kernel(\n    mcmc_kernel_factory: Callable,\n    mcmc_state_generator: Callable,\n    resampling_fn: Callable,\n    num_mcmc_iterations: int,\n):\n    \"\"\"Build a generic SMC kernel.\n\n    In Feynman-Kac equivalent terms, the algo goes roughly as follows:\n\n    ```\n        M_t = mcmc_kernel_factory(potential_fn)\n        for i in range(num_mcmc_iterations):\n            x_t^i = M_t(..., x_t^i)\n        G_t = log_weights_fn\n        log_weights = G_t(x_t)\n        idx = resample(log_weights)\n        x_t = x_t[idx]\n    ```\n\n\n    Parameters\n    ----------\n    mcmc_kernel_factory: Callable\n        A function of the Markov potential that returns a mcmc_kernel.\n    mcmc_state_generator: Callable\n        A function that creates a new mcmc state from a position and a potential.\n    resampling_fn: Callable\n        A function that resamples the particles generated by the MCMC kernel,\n        based of previously computed weights.\n    num_mcmc_iterations: int\n        Number of iterations of the MCMC kernel\n\n    Returns\n    -------\n    A kernel that takes a PRNGKey, a set of particles, the log-likehood of the\n    distribution and the Feynman-Kac potential at time `t`. The kernel returns\n    a new set of particles.\n\n    \"\"\"\n\n    def one_step(\n        rng_key: jnp.ndarray,\n        particles: PyTree,\n        logprob_fn: Callable,\n        log_weight_fn: Callable,\n    ) -> Tuple[PyTree, SMCInfo]:\n        \"\"\"\n\n        Parameters\n        ----------\n        rng_key: DeviceArray[int],\n            JAX PRNGKey for randomness.\n        particles: PyTree\n            Current particles sample of the SMC algorithm.\n        logprob_fn: Callable\n            Log probability function we wish to sample from.\n        log_weight_fn: Callable\n            A function that represents the Feynman-Kac log potential at time t.\n\n        Returns\n        -------\n        particles: PyTree,\n            The updated set of particles.\n        info: SMCInfo,\n            Additional information on the SMC step\n        \"\"\"\n\n        num_particles = jax.tree_flatten(particles)[0][0].shape[0]\n        scan_key, resampling_key = jax.random.split(rng_key, 2)\n\n        # First advance the particles using the MCMC kernel\n        mcmc_kernel = mcmc_kernel_factory(logprob_fn)\n\n        def mcmc_body_fn(curr_particles, curr_key):\n            keys = jax.random.split(curr_key, num_particles)\n            new_particles, _ = jax.vmap(mcmc_kernel, in_axes=(0, 0))(\n                keys, curr_particles\n            )\n            return new_particles, None\n\n        mcmc_state = jax.vmap(mcmc_state_generator, in_axes=(0, None))(\n            particles, logprob_fn\n        )\n        keys = jax.random.split(scan_key, num_mcmc_iterations)\n        proposed_states, _ = jax.lax.scan(mcmc_body_fn, mcmc_state, keys)\n        proposed_particles = proposed_states.position\n\n        # Resample the particles depending on their respective weights\n        log_weights = jax.vmap(log_weight_fn, in_axes=(0,))(proposed_particles)\n        weights, log_likelihood_increment = _normalize(log_weights)\n        resampling_index = resampling_fn(weights, resampling_key)\n        particles = jax.tree_map(lambda x: x[resampling_index], proposed_particles)\n\n        info = SMCInfo(\n            weights, proposed_particles, resampling_index, log_likelihood_increment\n        )\n        return particles, info\n\n    return one_step\n\n\ndef _normalize(log_weights):\n    \"\"\"Normalize log-weights into weights and return resulting weights and log-likelihood increment.\"\"\"\n    n = log_weights.shape[0]\n    max_logw = jnp.max(log_weights)\n    w = jnp.exp(log_weights - max_logw)\n    w_mean = w.mean()\n\n    log_likelihood_increment = jnp.log(w_mean) + max_logw\n\n    w = w / (n * w_mean)\n    return w, log_likelihood_increment\n", "meta": {"hexsha": "9db15809ca73423244d8d4e36419d330fa3fffd2", "size": 4479, "ext": "py", "lang": "Python", "max_stars_repo_path": "blackjax/smc/base.py", "max_stars_repo_name": "rlouf/blackjax", "max_stars_repo_head_hexsha": "07c345a2977ef81fc0f6d2231464bc14e0815b2f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-23T20:32:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T20:32:31.000Z", "max_issues_repo_path": "blackjax/smc/base.py", "max_issues_repo_name": "rlouf/blackjax", "max_issues_repo_head_hexsha": "07c345a2977ef81fc0f6d2231464bc14e0815b2f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "blackjax/smc/base.py", "max_forks_repo_name": "rlouf/blackjax", "max_forks_repo_head_hexsha": "07c345a2977ef81fc0f6d2231464bc14e0815b2f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5422535211, "max_line_length": 103, "alphanum_fraction": 0.6588524224, "include": true, "reason": "import jax", "num_tokens": 1039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.542863297964157, "lm_q2_score": 0.3557748935136303, "lm_q1q2_score": 0.1931371320256561}}
{"text": "\"\"\"\nNotes\n-----\n\nImportant attributes of continuous (order > 0) :class:`Field` and\n:class:`SurfaceField` instances:\n\n- `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]`\n- `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]`\n\nwhere `conn` is the mesh vertex connectivity, `econn` is the\nregion-local field connectivity.\n\"\"\"\nimport numpy as nm\n\nfrom sfepy.base.base import output, get_default, assert_\nfrom sfepy.base.base import Struct\nimport fea\nfrom sfepy.discrete.common.fields import parse_shape, Field\nfrom sfepy.discrete.fem.mesh import Mesh\nfrom sfepy.discrete.fem.meshio import convert_complex_output\nfrom sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap,\n                                      invert_remap, get_min_value)\nfrom sfepy.discrete.fem.fe_surface import FESurface\nfrom sfepy.discrete.integrals import Integral\nfrom sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors,\n                                           create_output)\n\ndef get_eval_expression(expression, ig,\n                        fields, materials, variables,\n                        functions=None, mode='eval', term_mode=None,\n                        extra_args=None, verbose=True, kwargs=None):\n    \"\"\"\n    Get the function for evaluating an expression given a list of elements,\n    and reference element coordinates.\n    \"\"\"\n    from sfepy.discrete.evaluate import eval_in_els_and_qp\n\n    def _eval(iels, coors):\n        val = eval_in_els_and_qp(expression, ig, iels, coors,\n                                 fields, materials, variables,\n                                 functions=functions, mode=mode,\n                                 term_mode=term_mode,\n                                 extra_args=extra_args, verbose=verbose,\n                                 kwargs=kwargs)\n        return val[..., 0]\n\n    return _eval\n\ndef create_expression_output(expression, name, primary_field_name,\n                             fields, materials, variables,\n                             functions=None, mode='eval', term_mode=None,\n                             extra_args=None, verbose=True, kwargs=None,\n                             min_level=0, max_level=1, eps=1e-4):\n    \"\"\"\n    Create output mesh and data for the expression using the adaptive\n    linearizer.\n\n    Parameters\n    ----------\n    expression : str\n        The expression to evaluate.\n    name : str\n        The name of the data.\n    primary_field_name : str\n        The name of field that defines the element groups and polynomial\n        spaces.\n    fields : dict\n        The dictionary of fields used in `variables`.\n    materials : Materials instance\n        The materials used in the expression.\n    variables : Variables instance\n        The variables used in the expression.\n    functions : Functions instance, optional\n        The user functions for materials etc.\n    mode : one of 'eval', 'el_avg', 'qp'\n        The evaluation mode - 'qp' requests the values in quadrature points,\n        'el_avg' element averages and 'eval' means integration over\n        each term region.\n    term_mode : str\n        The term call mode - some terms support different call modes\n        and depending on the call mode different values are\n        returned.\n    extra_args : dict, optional\n        Extra arguments to be passed to terms in the expression.\n    verbose : bool\n        If False, reduce verbosity.\n    kwargs : dict, optional\n        The variables (dictionary of (variable name) : (Variable\n        instance)) to be used in the expression.\n    min_level : int\n        The minimum required level of mesh refinement.\n    max_level : int\n        The maximum level of mesh refinement.\n    eps : float\n        The relative tolerance parameter of mesh adaptivity.\n\n    Returns\n    -------\n    out : dict\n        The output dictionary.\n    \"\"\"\n    field = fields[primary_field_name]\n    vertex_coors = field.coors[:field.n_vertex_dof, :]\n\n    coors = []\n    vdofs = []\n    conns = []\n    mat_ids = []\n    levels = []\n    offset = 0\n    for ig, ap in field.aps.iteritems():\n        ps = ap.interp.poly_spaces['v']\n        gps = ap.interp.gel.interp.poly_spaces['v']\n        group = field.domain.groups[ig]\n        vertex_conn = ap.econn[:, :group.shape.n_ep]\n\n        eval_dofs = get_eval_expression(expression, ig,\n                                        fields, materials, variables,\n                                        functions=functions,\n                                        mode=mode, extra_args=extra_args,\n                                        verbose=verbose, kwargs=kwargs)\n        eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps)\n\n        (level, _coors, conn,\n         _vdofs, _mat_ids) = create_output(eval_dofs, eval_coors,\n                                           group.shape.n_el, ps,\n                                           min_level=min_level,\n                                           max_level=max_level, eps=eps)\n\n        _mat_ids[:] = field.domain.mesh.mat_ids[ig][0]\n\n        coors.append(_coors)\n        vdofs.append(_vdofs)\n        conns.append(conn + offset)\n        mat_ids.append(_mat_ids)\n        levels.append(level)\n\n        offset += _coors.shape[0]\n\n    coors = nm.concatenate(coors, axis=0)\n    vdofs = nm.concatenate(vdofs, axis=0)\n    mesh = Mesh.from_data('linearized_mesh', coors, None, conns, mat_ids,\n                          field.domain.mesh.descs)\n\n    out = {}\n    out[name] = Struct(name='output_data', mode='vertex',\n                       data=vdofs, var_name=name, dofs=None,\n                       mesh=mesh, levels=levels)\n\n    out = convert_complex_output(out)\n\n    return out\n\nclass FEField(Field):\n    \"\"\"\n    Base class for finite element fields.\n\n    Notes\n    -----\n    - Region can span over several groups -> different Aproximation\n      instances\n    - interps and hence node_descs are per region (must have single\n      geometry!)\n    - no two interps can be in a same group -> no two aps (with\n      different regions) can be in a same group -> aps can be uniquely\n      indexed with ig\n\n    Field shape information:\n\n    - ``shape`` - the shape of the base functions in a point\n    - ``n_components`` - the number of DOFs per FE node\n    - ``val_shape`` - the shape of field value (the product of DOFs and\n      base functions) in a point\n    \"\"\"\n\n    def __init__(self, name, dtype, shape, region, approx_order=1):\n        \"\"\"\n        Create a finite element field.\n\n        Parameters\n        ----------\n        name : str\n            The field name.\n        dtype : numpy.dtype\n            The field data type: float64 or complex128.\n        shape : int/tuple/str\n            The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,)\n            or 3 or (3,)) or 'vector', or a tuple. The field shape determines\n            the shape of the FE base functions and is related to the number of\n            components of variables and to the DOF per node count, depending\n            on the field kind.\n        region : Region\n            The region where the field is defined.\n        approx_order : int or tuple\n            The FE approximation order. The tuple form is (order, has_bubble),\n            e.g. (1, True) means order 1 with a bubble function.\n\n        Notes\n        -----\n        Assumes one cell type for the whole region!\n        \"\"\"\n        shape = parse_shape(shape, region.domain.shape.dim)\n        if not self._check_region(region):\n            raise ValueError('unsuitable region for field %s! (%s)' %\n                             (name, region.name))\n\n        Struct.__init__(self, name=name, dtype=dtype, shape=shape,\n                        region=region)\n        self.domain = self.region.domain\n        self.igs = self.region.igs\n\n        self._set_approx_order(approx_order)\n        self._setup_geometry()\n        self._setup_kind()\n        self._setup_shape()\n\n        self._create_interpolant()\n        self._setup_approximations()\n        self._setup_global_base()\n        self.setup_coors()\n        self.clear_mappings(clear_all=True)\n\n    def _set_approx_order(self, approx_order):\n        \"\"\"\n        Set a uniform approximation order.\n        \"\"\"\n        if isinstance(approx_order, tuple):\n            self.approx_order = approx_order[0]\n            self.force_bubble = approx_order[1]\n\n        else:\n            self.approx_order = approx_order\n            self.force_bubble = False\n\n    def _create_interpolant(self):\n        name = '%s_%s_%s_%d%s' % (self.gel.name, self.space,\n                                  self.poly_space_base, self.approx_order,\n                                  'B' * self.force_bubble)\n        self.interp = fea.Interpolant(name, self.gel, self.space,\n                                      self.poly_space_base, self.approx_order,\n                                      self.force_bubble)\n\n    def _setup_approximations(self):\n        self.aps = {}\n        self.aps_by_name = {}\n        for ig in self.igs:\n            name = self.interp.name + '_%s_ig%d' % (self.region.name, ig)\n            ap = fea.Approximation(name, self.interp, self.region, ig)\n            self.aps[ig] = ap\n            self.aps_by_name[ap.name] = ap\n\n    def get_true_order(self):\n        \"\"\"\n        Get the true approximation order depending on the reference\n        element geometry.\n\n        For example, for P1 (linear) approximation the true order is 1,\n        while for Q1 (bilinear) approximation in 2D the true order is 2.\n        \"\"\"\n        gel = self.gel\n        if (gel.dim + 1) == gel.n_vertex:\n            order = self.approx_order\n\n        else:\n            order = gel.dim * self.approx_order\n\n        if self.force_bubble:\n            bubble_order = gel.dim + 1\n            order = max(order, bubble_order)\n\n        return order\n\n    def is_higher_order(self):\n        \"\"\"\n        Return True, if the field's approximation order is greater than one.\n        \"\"\"\n        return self.force_bubble or (self.approx_order > 1)\n\n    def _setup_global_base(self):\n        \"\"\"\n        Setup global DOF/base functions, their indices and connectivity of the\n        field. Called methods implemented in subclasses.\n        \"\"\"\n        self._setup_facet_orientations()\n\n        self._init_econn()\n\n        self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs()\n        self.vertex_remap_i = invert_remap(self.vertex_remap)\n\n        aux = self._setup_edge_dofs()\n        self.n_edge_dof, self.edge_dofs, self.edge_remap = aux\n\n        aux = self._setup_face_dofs()\n        self.n_face_dof, self.face_dofs, self.face_remap = aux\n\n        aux = self._setup_bubble_dofs()\n        self.n_bubble_dof, self.bubble_dofs, self.bubble_remaps = aux\n\n        self.n_nod = self.n_vertex_dof + self.n_edge_dof \\\n                     + self.n_face_dof + self.n_bubble_dof\n\n        self._setup_esurface()\n\n    def _setup_esurface(self):\n        \"\"\"\n        Setup extended surface entities (edges in 2D, faces in 3D),\n        i.e. indices of surface entities into the extended connectivity.\n        \"\"\"\n        node_desc = self.node_desc\n\n        for ig, ap in self.aps.iteritems():\n            gel = ap.interp.gel\n            ap.efaces = gel.get_surface_entities().copy()\n\n            nd = node_desc.edge\n            if nd is not None:\n                efs = []\n                for eof in gel.get_edges_per_face():\n                    efs.append(nm.concatenate([nd[ie] for ie in eof]))\n                efs = nm.array(efs).squeeze()\n\n                if efs.ndim < 2:\n                    efs = efs[:,nm.newaxis]\n                ap.efaces = nm.hstack((ap.efaces, efs))\n\n            efs = node_desc.face\n            if efs is not None:\n                efs = nm.array(efs).squeeze()\n\n                if efs.ndim < 2:\n                    efs = efs[:,nm.newaxis]\n                ap.efaces = nm.hstack((ap.efaces, efs))\n\n    def setup_coors(self, coors=None):\n        \"\"\"\n        Setup coordinates of field nodes.\n        \"\"\"\n        mesh = self.domain.mesh\n        self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64)\n\n        if coors is None:\n            coors = mesh.coors\n\n        # Mesh vertex nodes.\n        if self.n_vertex_dof:\n            indx = self.vertex_remap_i\n            self.coors[:self.n_vertex_dof] = nm.take(coors,\n                                                     indx.astype(nm.int32),\n                                                     axis=0)\n\n        for ig, ap in self.aps.iteritems():\n            ap.eval_extra_coor(self.coors, coors)\n\n    def get_vertices(self):\n        \"\"\"\n        Return indices of vertices belonging to the field region.\n        \"\"\"\n        return self.vertex_remap_i\n\n    def _get_facet_dofs(self, get_facets, remap, dofs, ig):\n        gfacets = get_facets(ig)\n        facets = remap[gfacets]\n\n        return dofs[facets[facets >= 0]].ravel()\n\n    def get_data_shape(self, ig, integral,\n                       integration='volume', region_name=None):\n        \"\"\"\n        Get element data dimensions.\n\n        Parameters\n        ----------\n        ig : int\n            The element group index.\n        integral : Integral instance\n            The integral describing used numerical quadrature.\n        integration : 'volume', 'plate', 'surface', 'surface_extra' or 'point'\n            The term integration type.\n        region_name : str\n            The name of surface region, required when `shape_kind` is\n            'surface'.\n\n        Returns\n        -------\n        data_shape : 4 ints\n            The `(n_el, n_qp, dim, n_en)` for volume shape kind,\n            `(n_fa, n_qp, dim, n_fn)` for surface shape kind and\n            `(n_nod, 0, 0, 1)` for point shape kind.\n\n        Notes\n        -----\n        - `n_el`, `n_fa` = number of elements/facets\n        - `n_qp` = number of quadrature points per element/facet\n        - `dim` = spatial dimension\n        - `n_en`, `n_fn` = number of element/facet nodes\n        - `n_nod` = number of element nodes\n        \"\"\"\n        ap = self.aps[ig]\n\n        region = self.domain.regions[region_name]\n        shape = region.shape[ig]\n        dim = region.dim\n\n        if integration in ('surface', 'surface_extra'):\n            sd = ap.surface_data[region_name]\n\n            # This works also for surface fields.\n            key = sd.face_type\n            weights = ap.get_qp(key, integral).weights\n            n_qp = weights.shape[0]\n\n            if integration == 'surface':\n                data_shape = (sd.n_fa, n_qp, dim, ap.n_ep[key])\n\n            else:\n                data_shape = (sd.n_fa, n_qp, dim, ap.n_ep['v'])\n\n        elif integration in ('volume', 'plate'):\n            _, weights = integral.get_qp(self.gel.name)\n            n_qp = weights.shape[0]\n\n            data_shape = (shape.n_cell, n_qp, dim, ap.n_ep['v'])\n\n        elif integration == 'point':\n            dofs = self.get_dofs_in_region(region, merge=True)\n            data_shape = (dofs.shape[0], 0, 0, 1)\n\n        else:\n            raise NotImplementedError('unsupported integration! (%s)'\n                                      % integration)\n\n        return data_shape\n\n    def get_dofs_in_region_group(self, region, ig, merge=True):\n        \"\"\"\n        Return indices of DOFs that belong to the given region and group.\n        \"\"\"\n        node_desc = self.node_desc\n\n        dofs = []\n\n        vdofs = nm.empty((0,), dtype=nm.int32)\n        if node_desc.vertex is not None:\n            ii = region.get_vertices(ig)\n            vdofs = self.vertex_remap[ii]\n            vdofs = vdofs[vdofs >= 0]\n        dofs.append(vdofs)\n\n        edofs = nm.empty((0,), dtype=nm.int32)\n        if node_desc.edge is not None:\n            edofs = self._get_facet_dofs(region.get_edges,\n                                         self.edge_remap,\n                                         self.edge_dofs, ig)\n        dofs.append(edofs)\n\n        fdofs = nm.empty((0,), dtype=nm.int32)\n        if node_desc.face is not None:\n            fdofs = self._get_facet_dofs(region.get_faces,\n                                         self.face_remap,\n                                         self.face_dofs, ig)\n        dofs.append(fdofs)\n\n        bdofs = nm.empty((0,), dtype=nm.int32)\n        if (node_desc.bubble is not None) and region.has_cells():\n            ii = region.get_cells(ig)\n            group_els = self.bubble_remaps[ig][ii]\n            bdofs = self.bubble_dofs[ig][group_els[group_els >= 0]].ravel()\n        dofs.append(bdofs)\n\n        if merge:\n            dofs = nm.concatenate(dofs)\n\n        return dofs\n\n    def extend_dofs(self, dofs, fill_value=None):\n        \"\"\"\n        Extend DOFs to the whole domain using the `fill_value`, or the\n        smallest value in `dofs` if `fill_value` is None.\n        \"\"\"\n        if fill_value is None:\n            if nm.isrealobj(dofs):\n                fill_value = get_min_value(dofs)\n\n            else:\n                # Complex values - treat real and imaginary parts separately.\n                fill_value = get_min_value(dofs.real)\n                fill_value += 1j * get_min_value(dofs.imag)\n\n        if self.approx_order != 0:\n            indx = self.get_vertices()\n\n            n_nod = self.domain.shape.n_nod\n            new_dofs = nm.empty((n_nod, dofs.shape[1]), dtype=self.dtype)\n            new_dofs.fill(fill_value)\n            new_dofs[indx] = dofs[:indx.size]\n\n        else:\n            new_dofs = extend_cell_data(dofs, self.domain, self.region,\n                                        val=fill_value)\n\n        return new_dofs\n\n    def remove_extra_dofs(self, dofs):\n        \"\"\"\n        Remove DOFs defined in higher order nodes (order > 1).\n        \"\"\"\n        if self.approx_order != 0:\n            new_dofs = dofs[:self.n_vertex_dof]\n\n        else:\n            new_dofs = dofs\n\n        return new_dofs\n\n    def linearize(self, dofs, min_level=0, max_level=1, eps=1e-4):\n        \"\"\"\n        Linearize the solution for post-processing.\n\n        Parameters\n        ----------\n        dofs : array, shape (n_nod, n_component)\n            The array of DOFs reshaped so that each column corresponds\n            to one component.\n        min_level : int\n            The minimum required level of mesh refinement.\n        max_level : int\n            The maximum level of mesh refinement.\n        eps : float\n            The relative tolerance parameter of mesh adaptivity.\n\n        Returns\n        -------\n        mesh : Mesh instance\n            The adapted, nonconforming, mesh.\n        vdofs : array\n            The DOFs defined in vertices of `mesh`.\n        levels : array of ints\n            The refinement level used for each element group.\n        \"\"\"\n        assert_(dofs.ndim == 2)\n\n        n_nod, dpn = dofs.shape\n\n        assert_(n_nod == self.n_nod)\n        assert_(dpn == self.shape[0])\n\n        vertex_coors = self.coors[:self.n_vertex_dof, :]\n\n        coors = []\n        vdofs = []\n        conns = []\n        mat_ids = []\n        levels = []\n        offset = 0\n        for ig, ap in self.aps.iteritems():\n            ps = ap.interp.poly_spaces['v']\n            gps = ap.interp.gel.interp.poly_spaces['v']\n            group = self.domain.groups[ig]\n            vertex_conn = ap.econn[:, :group.shape.n_ep]\n\n            eval_dofs = get_eval_dofs(dofs, ap.econn, ps, ori=ap.ori)\n            eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps)\n\n            (level, _coors, conn,\n             _vdofs, _mat_ids) = create_output(eval_dofs, eval_coors,\n                                               group.shape.n_el, ps,\n                                               min_level=min_level,\n                                               max_level=max_level, eps=eps)\n\n            _mat_ids[:] = self.domain.mesh.mat_ids[ig][0]\n\n            coors.append(_coors)\n            vdofs.append(_vdofs)\n            conns.append(conn + offset)\n            mat_ids.append(_mat_ids)\n            levels.append(level)\n\n            offset += _coors.shape[0]\n\n        coors = nm.concatenate(coors, axis=0)\n        vdofs = nm.concatenate(vdofs, axis=0)\n        mesh = Mesh.from_data('linearized_mesh', coors, None, conns, mat_ids,\n                              self.domain.mesh.descs)\n\n        return mesh, vdofs, levels\n\n    def get_output_approx_order(self):\n        \"\"\"\n        Get the approximation order used in the output file.\n        \"\"\"\n        return min(self.approx_order, 1)\n\n    def create_output(self, dofs, var_name, dof_names=None,\n                      key=None, extend=True, fill_value=None,\n                      linearization=None):\n        \"\"\"\n        Convert the DOFs corresponding to the field to a dictionary of\n        output data usable by Mesh.write().\n\n        Parameters\n        ----------\n        dofs : array, shape (n_nod, n_component)\n            The array of DOFs reshaped so that each column corresponds\n            to one component.\n        var_name : str\n            The variable name corresponding to `dofs`.\n        dof_names : tuple of str\n            The names of DOF components.\n        key : str, optional\n            The key to be used in the output dictionary instead of the\n            variable name.\n        extend : bool\n            Extend the DOF values to cover the whole domain.\n        fill_value : float or complex\n           The value used to fill the missing DOF values if `extend` is True.\n        linearization : Struct or None\n            The linearization configuration for higher order approximations.\n\n        Returns\n        -------\n        out : dict\n            The output dictionary.\n        \"\"\"\n        linearization = get_default(linearization, Struct(kind='strip'))\n\n        out = {}\n        if linearization.kind is None:\n            out[key] = Struct(name='output_data', mode='full',\n                              data=dofs, var_name=var_name,\n                              dofs=dof_names, field_name=self.name)\n\n        elif ((not self.is_higher_order())\n            or (linearization.kind == 'strip')):\n            if extend:\n                ext = self.extend_dofs(dofs, fill_value)\n\n            else:\n                ext = self.remove_extra_dofs(dofs)\n\n            if ext is not None:\n                approx_order = self.get_output_approx_order()\n\n                if approx_order != 0:\n                    # Has vertex data.\n                    out[key] = Struct(name='output_data', mode='vertex',\n                                      data=ext, var_name=var_name,\n                                      dofs=dof_names)\n\n                else:\n                    ext.shape = (ext.shape[0], 1, ext.shape[1], 1)\n                    out[key] = Struct(name='output_data', mode='cell',\n                                      data=ext, var_name=var_name,\n                                      dofs=dof_names)\n\n        else:\n            mesh, vdofs, levels = self.linearize(dofs,\n                                                 linearization.min_level,\n                                                 linearization.max_level,\n                                                 linearization.eps)\n            out[key] = Struct(name='output_data', mode='vertex',\n                              data=vdofs, var_name=var_name, dofs=dof_names,\n                              mesh=mesh, levels=levels)\n\n        out = convert_complex_output(out)\n\n        return out\n\n    def create_mesh(self, extra_nodes=True):\n        \"\"\"\n        Create a mesh from the field region, optionally including the field\n        extra nodes.\n        \"\"\"\n        mesh = self.domain.mesh\n\n        if self.approx_order != 0:\n            conns, mat_ids, descs = [], [], []\n            for ig, ap in self.aps.iteritems():\n                group = self.domain.groups[ig]\n                if extra_nodes:\n                    conn = ap.econn\n                else:\n                    offset = group.shape.n_ep\n                    conn = ap.econn[:,:offset]\n                conns.append(conn)\n                mat_ids.append(mesh.mat_ids[ig])\n                descs.append(mesh.descs[ig])\n\n            if extra_nodes:\n                coors = self.coors\n\n            else:\n                coors = self.coors[:self.n_vertex_dof]\n\n            mesh = Mesh.from_data(self.name, coors, None, conns,\n                                  mat_ids, descs)\n\n        return mesh\n\n    def interp_to_qp(self, dofs):\n        \"\"\"\n        Interpolate DOFs into quadrature points.\n\n        The quadrature order is given by the field approximation order.\n\n        Parameters\n        ----------\n        dofs : array\n            The array of DOF values of shape `(n_nod, n_component)`.\n\n        Returns\n        -------\n        data_qp : array\n            The values interpolated into the quadrature points.\n        integral : Integral\n            The corresponding integral defining the quadrature points.\n        \"\"\"\n        integral = Integral('i', order=self.approx_order)\n\n        data_qp = []\n        for ig, ap in self.aps.iteritems():\n            bf = ap.get_base('v', False, integral)\n            bf = bf[:,0,:].copy()\n\n            vals = nm.dot(bf, dofs[ap.econn])\n            vals = nm.swapaxes(vals, 0, 1)\n            vals.shape = vals.shape + (1,)\n\n            data_qp.append(vals)\n\n        data_qp = nm.concatenate(data_qp, axis=0)\n\n        return data_qp, integral\n\n    def get_coor(self, nods=None):\n        \"\"\"\n        Get coordinates of the field nodes.\n\n        Parameters\n        ----------\n        nods : array, optional\n           The indices of the required nodes. If not given, the\n           coordinates of all the nodes are returned.\n        \"\"\"\n        if nods is None:\n            return self.coors\n        else:\n            return self.coors[nods]\n\n    def create_mapping(self, ig, region, integral, integration):\n        \"\"\"\n        Create a new reference mapping.\n        \"\"\"\n        ap = self.aps[ig]\n\n        out = ap.describe_geometry(self, integration, region, integral,\n                                   return_mapping=True)\n        return out\n\nclass VolumeField(FEField):\n    \"\"\"\n    Finite element field base class over volume elements (element dimension\n    equals space dimension).\n    \"\"\"\n\n    def _check_region(self, region):\n        \"\"\"\n        Check whether the `region` can be used for the\n        field. Non-surface fields require the region to span whole\n        element groups.\n\n        Returns\n        -------\n        ok : bool\n            True if the region is usable for the field.\n        \"\"\"\n        ok = True\n        domain = region.domain\n        for ig in region.igs:\n            if domain.groups[ig].gel.dim != domain.shape.tdim:\n                output('cells with a bad topological dimension! (%d == %d)'\n                       % (domain.groups[ig].gel.dim, domain.shape.tdim))\n                ok = False\n                break\n            shape = domain.groups[ig].shape\n            if region.shape[ig].n_vertex < shape.n_vertex:\n                output('region does not span a whole element group!')\n                ok = False\n                break\n\n        return ok\n\n    def _setup_geometry(self):\n        \"\"\"\n        Setup the field region geometry.\n        \"\"\"\n        ig = self.region.domain.cmesh.cell_groups[self.region.cells[0]]\n        self.gel = self.domain.groups[ig].gel\n\n        self.is_surface = False\n\n    def _create_interpolant(self):\n        name = '%s_%s_%s_%d%s' % (self.gel.name, self.space,\n                                  self.poly_space_base, self.approx_order,\n                                  'B' * self.force_bubble)\n        self.interp = fea.Interpolant(name, self.gel, self.space,\n                                      self.poly_space_base, self.approx_order,\n                                      self.force_bubble)\n\n    def _setup_approximations(self):\n        self.aps = {}\n        self.aps_by_name = {}\n        for ig in self.igs:\n            name = self.interp.name + '_%s_ig%d' % (self.region.name, ig)\n            ap = fea.Approximation(name, self.interp, self.region, ig)\n            self.aps[ig] = ap\n            self.aps_by_name[ap.name] = ap\n\n    def _init_econn(self):\n        \"\"\"\n        Initialize the extended DOF connectivity.\n        \"\"\"\n        for ig, ap in self.aps.iteritems():\n            n_ep = ap.n_ep['v']\n            n_cell = self.region.get_n_cells(ig)\n            ap.econn = nm.zeros((n_cell, n_ep), nm.int32)\n\n    def _setup_vertex_dofs(self):\n        \"\"\"\n        Setup vertex DOF connectivity.\n        \"\"\"\n        if self.node_desc.vertex is None:\n            return 0, None\n\n        region = self.region\n\n        vertices = region.get_vertices_of_cells()\n        remap = prepare_remap(vertices, region.n_v_max)\n        n_dof = vertices.shape[0]\n\n        ##\n        # Remap vertex node connectivity to field-local numbering.\n        for ig, ap in self.aps.iteritems():\n            group = self.domain.groups[ig]\n            offset = group.shape.n_ep\n            cells = region.get_cells(ig)\n            ap.econn[:,:offset] = nm.take(remap,\n                                          nm.take(group.conn,\n                                                  cells.astype(nm.int32),\n                                                  axis=0))\n\n        return n_dof, remap\n\n    def setup_extra_data(self, geometry, info, is_trace):\n        dct = info.dc_type.type\n\n        if geometry != None:\n            geometry_flag = 'surface' in geometry\n        else:\n            geometry_flag = False\n\n        if (dct == 'surface') or (geometry_flag):\n            reg = info.get_region()\n            self.domain.create_surface_group(reg)\n            self._setup_surface_data(reg, is_trace)\n\n        elif dct == 'edge':\n            raise NotImplementedError('dof connectivity type %s' % dct)\n\n        elif dct == 'point':\n            self._setup_point_data(self, info.region)\n\n        elif dct not in ('volume', 'scalar', 'plate'):\n            raise ValueError('unknown dof connectivity type! (%s)' % dct)\n\n    def _setup_surface_data(self, region, is_trace=False):\n        for ig, ap in self.aps.iteritems():\n            if ig not in region.igs: continue\n            if region.name not in ap.surface_data:\n                ap.setup_surface_data(region)\n\n        for ig, ap in self.aps.iteritems():\n            if region.name in ap.surface_data and is_trace:\n                sd = ap.surface_data[region.name]\n                sd.setup_mirror_connectivity(region)\n\n    def _setup_point_data(self, field, region):\n        # Point data only in the first group to avoid multiple\n        # assembling of nodes on group boundaries.\n        ap = self.aps[self.igs[0]]\n        if region.name not in ap.point_data:\n            ap.setup_point_data(field, region)\n\n    def get_econn(self, conn_type, region, ig, is_trace=False,\n                  integration=None):\n        \"\"\"\n        Get extended connectivity of the given type in the given region.\n        \"\"\"\n        ct = conn_type.type if isinstance(conn_type, Struct) else conn_type\n\n        if ((ig not in self.igs) or (ig not in region.igs)\n            or (ct == 'point' and (ig > self.igs[0]))):\n            # Point data only in the first group to avoid multiple\n            # assembling of nodes on group boundaries.\n            return None\n\n        ap = self.aps[ig]\n\n        if ct in ('volume', 'plate'):\n            if region.name == self.region.name:\n                conn = ap.econn\n\n            else:\n                aux = integration in ('volume', 'plate')\n                cells = region.get_cells(ig, true_cells_only=aux)\n                conn = nm.take(ap.econn, cells.astype(nm.int32), axis=0)\n\n        elif ct == 'surface':\n            sd = ap.surface_data[region.name]\n            conn = sd.get_connectivity(is_trace=is_trace)\n\n        elif ct == 'edge':\n            raise NotImplementedError('connectivity type %s' % ct)\n\n        elif ct == 'point':\n            conn = ap.point_data[region.name]\n\n        else:\n            raise ValueError('unknown connectivity type! (%s)' % ct)\n\n        return conn\n\n    def get_full_econn(self, ig=None):\n        if ig not in self.igs:\n            msg = \"The required index (%s) of element group is not available\" \\\n                % (str(ig),)\n            raise ValueError(msg)\n\n        econn = self.aps[ig].econn\n        n_econn = econn.shape[1]\n        if self.n_basis == n_econn:\n            full_econn = econn\n\n        elif self.n_basis==self.n_components*n_econn:\n            full_econn = nm.zeros([econn.shape[0], self.n_basis],\n                                  dtype=nm.int32)\n            for ii in nm.arange(self.n_components):\n                slc = slice(n_econn*ii, n_econn*(ii+1))\n                full_econn[:, slc] = econn*self.n_components + ii\n\n        return full_econn\n\n    def average_qp_to_vertices(self, data_qp, integral):\n        \"\"\"\n        Average data given in quadrature points in region elements into\n        region vertices.\n\n        .. math::\n           u_n = \\sum_e (u_{e,avg} * volume_e) / \\sum_e volume_e\n               = \\sum_e \\int_{volume_e} u / \\sum volume_e\n        \"\"\"\n        region = self.region\n\n        n_cells = region.get_n_cells()\n        if n_cells != data_qp.shape[0]:\n            msg = 'incomatible shape! (%d == %d)' % (n_cells,\n                                                     data_qp.shape[0])\n            raise ValueError(msg)\n\n        n_vertex = self.n_vertex_dof\n        nc = data_qp.shape[2]\n\n        nod_vol = nm.zeros((n_vertex,), dtype=nm.float64)\n        data_vertex = nm.zeros((n_vertex, nc), dtype=nm.float64)\n        for ig, ap in self.aps.iteritems():\n            vg = ap.describe_geometry(self, 'volume', ap.region, integral)\n\n            volume = nm.squeeze(vg.volume)\n            iels = ap.region.get_cells(ig)\n\n            data_e = nm.zeros((volume.shape[0], 1, nc, 1), dtype=nm.float64)\n            vg.integrate(data_e, data_qp[iels])\n\n            ir = nm.arange(nc, dtype=nm.int32)\n\n            conn = ap.econn[:, :self.gel.n_vertex]\n            for ii, cc in enumerate(conn):\n                # Assumes unique nodes in cc!\n                ind2, ind1 = nm.meshgrid(ir, cc)\n                data_vertex[ind1,ind2] += data_e[iels[ii],0,:,0]\n                nod_vol[cc] += volume[ii]\n        data_vertex /= nod_vol[:,nm.newaxis]\n\n        return data_vertex\n\nclass SurfaceField(FEField):\n    \"\"\"\n    Finite element field base class over surface (element dimension is one\n    less than space dimension).\n    \"\"\"\n\n    def _check_region(self, region):\n        \"\"\"\n        Check whether the `region` can be used for the\n        field.\n\n        Returns\n        -------\n        ok : bool\n            True if the region is usable for the field.\n        \"\"\"\n        ok = True\n        for ig in region.igs:\n            n_cell = region.get_n_cells(ig, True)\n            if n_cell == 0:\n                ok = False\n                break\n\n        return ok\n\n    def _setup_geometry(self):\n        \"\"\"\n        Setup the field region geometry.\n        \"\"\"\n        self.gel = self.domain.groups[self.region.igs[0]].gel.surface_facet\n        if self.gel is None:\n            raise ValueError('element group has no surface!')\n\n        self.is_surface = True\n\n    def _create_interpolant(self):\n        name = '%s_%s_%s_%d%s' % (self.gel.name, self.space,\n                                  self.poly_space_base, self.approx_order,\n                                  'B' * self.force_bubble)\n        self.interp = fea.SurfaceInterpolant(name, self.gel, self.space,\n                                             self.poly_space_base,\n                                             self.approx_order,\n                                             self.force_bubble)\n\n    def _setup_approximations(self):\n        self.aps = {}\n        self.aps_by_name = {}\n        for ig in self.igs:\n            name = self.interp.name + '_%s_ig%d' % (self.region.name, ig)\n            ap = fea.SurfaceApproximation(name, self.interp, self.region, ig)\n            self.aps[ig] = ap\n            self.aps_by_name[ap.name] = ap\n\n    def setup_extra_data(self, geometry, info, is_trace):\n        dct = info.dc_type.type\n\n        if dct != 'surface':\n            msg = \"dof connectivity type must be 'surface'! (%s)\" % dct\n            raise ValueError(msg)\n\n        reg = info.get_region()\n\n        for ig, ap in self.aps.iteritems():\n            if ig not in reg.igs: continue\n\n            if reg.name not in ap.surface_data:\n                # Defined in setup_vertex_dofs()\n                msg = 'no surface data of surface field! (%s)' % reg.name\n                raise ValueError(msg)\n\n        for ig, ap in self.aps.iteritems():\n            if reg.name in ap.surface_data and is_trace:\n                sd = ap.surface_data[reg.name]\n                sd.setup_mirror_connectivity(reg)\n\n    def _init_econn(self):\n        \"\"\"\n        Initialize the extended DOF connectivity.\n        \"\"\"\n        for ig, ap in self.aps.iteritems():\n            n_ep = ap.n_ep['v']\n            n_cell = self.region.get_n_cells(ig, True)\n            ap.econn = nm.zeros((n_cell, n_ep), nm.int32)\n\n    def _setup_vertex_dofs(self):\n        \"\"\"\n        Setup vertex DOF connectivity.\n        \"\"\"\n        if self.node_desc.vertex is None:\n            return 0, None\n\n        region = self.region\n\n        remap = prepare_remap(region.vertices, region.n_v_max)\n        n_dof = region.vertices.shape[0]\n\n        ##\n        # Remap vertex node connectivity to field-local numbering.\n        for ig, ap in self.aps.iteritems():\n            group = self.domain.groups[ig]\n            faces = group.gel.get_surface_entities()\n            aux = FESurface('aux', region, faces, group.conn, ig)\n            ap.econn[:,:aux.n_fp] = aux.leconn\n            ap.surface_data[region.name] = aux\n\n        return n_dof, remap\n\n    def _setup_bubble_dofs(self):\n        \"\"\"\n        Setup bubble DOF connectivity.\n        \"\"\"\n        return 0, None, None\n\n    def get_econn(self, conn_type, region, ig, is_trace=False,\n                  integration=None):\n        \"\"\"\n        Get extended connectivity of the given type in the given region.\n        \"\"\"\n        ct = conn_type.type if isinstance(conn_type, Struct) else conn_type\n\n        if ct != 'surface':\n            msg = 'connectivity type must be \"surface\"! (%s)' % ct\n            raise ValueError(msg)\n\n        ap = self.aps[ig]\n\n        sd = ap.surface_data[region.name]\n        conn = sd.get_connectivity(local=True, is_trace=is_trace)\n\n        return conn\n\n    def average_qp_to_vertices(self, data_qp, integral):\n        \"\"\"\n        Average data given in quadrature points in region elements into\n        region vertices.\n\n        .. math::\n           u_n = \\sum_e (u_{e,avg} * area_e) / \\sum_e area_e\n               = \\sum_e \\int_{area_e} u / \\sum area_e\n        \"\"\"\n        region = self.region\n\n        n_cells = region.get_n_cells(None, True)\n        if n_cells != data_qp.shape[0]:\n            msg = 'incomatible shape! (%d == %d)' % (n_cells,\n                                                     data_qp.shape[0])\n            raise ValueError(msg)\n\n        n_vertex = len(region.vertices)\n        nc = data_qp.shape[2]\n\n        nod_vol = nm.zeros((n_vertex,), dtype=nm.float64)\n        data_vertex = nm.zeros((n_vertex, nc), dtype=nm.float64)\n        offset = 0\n        for ig, ap in self.aps.iteritems():\n            sg = ap.describe_geometry(self, 'surface', ap.region, integral)\n\n            area = nm.squeeze(sg.volume)\n            n_cells = region.get_n_cells(ig, True)\n            iels = offset + nm.arange(n_cells, dtype=nm.int32)\n            offset += n_cells\n\n            data_e = nm.zeros((area.shape[0], 1, nc, 1), dtype=nm.float64)\n            sg.integrate(data_e, data_qp[iels])\n\n            ir = nm.arange(nc, dtype=nm.int32)\n\n            sd = self.domain.surface_groups[ig][region.name]\n            # Should be vertex connectivity!\n            conn = sd.get_connectivity(local=True)\n            for ii, cc in enumerate(conn):\n                # Assumes unique nodes in cc!\n                ind2, ind1 = nm.meshgrid(ir, cc)\n                data_vertex[ind1,ind2] += data_e[iels[ii],0,:,0]\n                nod_vol[cc] += area[ii]\n        data_vertex /= nod_vol[:,nm.newaxis]\n\n        return data_vertex\n\nclass H1Mixin(Struct):\n    \"\"\"\n    Methods of fields specific to H1 space.\n    \"\"\"\n\n    def _setup_shape(self):\n        \"\"\"\n        Setup the field's shape-related attributes, see :class:`Field`.\n        \"\"\"\n        self.n_components = nm.prod(self.shape)\n        self.val_shape = self.shape\n", "meta": {"hexsha": "a52f8d321b4cf51f320ca8575393153db6e531ff", "size": 40389, "ext": "py", "lang": "Python", "max_stars_repo_path": "sfepy/discrete/fem/fields_base.py", "max_stars_repo_name": "vondrejc/sfepy", "max_stars_repo_head_hexsha": "8e427af699c4b2858eb096510057abb3ae7e28e8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sfepy/discrete/fem/fields_base.py", "max_issues_repo_name": "vondrejc/sfepy", "max_issues_repo_head_hexsha": "8e427af699c4b2858eb096510057abb3ae7e28e8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sfepy/discrete/fem/fields_base.py", "max_forks_repo_name": "vondrejc/sfepy", "max_forks_repo_head_hexsha": "8e427af699c4b2858eb096510057abb3ae7e28e8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-14T03:12:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-25T11:44:50.000Z", "avg_line_length": 34.0261162595, "max_line_length": 79, "alphanum_fraction": 0.5450741539, "include": true, "reason": "import numpy", "num_tokens": 9006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3557749003442964, "lm_q1q2_score": 0.1931371304712756}}
{"text": "import os\nimport numpy\n\nimport _mypath\nimport chroma\n\ndata_dir = '../../../data/'\n\ndef load_LSST_filters():\n    \"\"\" Read the LSST filter definitions from disk.  Also add a normalization filter that is\n    only non-zero at 500nm, which is used to define the CatSim/PhoSim normalization.\n    \"\"\"\n    filter_dir = data_dir+'filters/'\n    filter_names = 'ugrizy'\n    # establish wavelength array\n    filters = {}\n    for filter_name in filter_names:\n        ffile = filter_dir+'LSST_{}.dat'.format(filter_name)\n        wave, throughput = numpy.genfromtxt(ffile).T\n        filters['LSST_'+filter_name] = {'wave':wave,\n                                        'throughput':throughput}\n    norm_throughput = numpy.zeros_like(wave)\n    norm_throughput[wave==500] = 1.0\n    filters['norm'] = {'wave':wave,\n                       'throughput':norm_throughput}\n    return filters\n\ndef load_Euclid_filters():\n    \"\"\" Load Euclid filters as defined by Voigt+12, centered at 775nm with widths of 150, 250, 350,\n    and 450 nm.  These are stored in the data directory.\"\"\"\n\n    filter_dir = data_dir+'filters/'\n    filter_names = ['Euclid_{}'.format(width) for width in [150,250,350,450]]\n\n    filters = {}\n    for filter_name in filter_names:\n        ffile = filter_dir+'{}.dat'.format(filter_name)\n        wave, throughput = numpy.genfromtxt(ffile).T\n        filters[filter_name] = {'wave':wave,\n                                'throughput':throughput}\n    norm_throughput = numpy.zeros_like(wave)\n    norm_throughput[wave==500] = 1.0\n    filters['norm'] = {'wave':wave,\n                       'throughput':norm_throughput}\n    return filters\n\ndef match_filter_wavelengths(filters, wave_match):\n    for fname, f in filters.iteritems():\n        new_throughput = numpy.interp(wave_match, f['wave'], f['throughput'])\n        filters[fname] = {'wave':wave_match,\n                          'throughput':new_throughput}\n    return filters\n\ndef AB_zeropoints(filters):\n    \"\"\"Compute AB zeropoints for given filters.\n    \"\"\"\n    # define AB source in flambda\n    ABsource = 3631e-23 # 3631 Jy -> erg/s/Hz/cm^2\n    c = 29979245800.0 # cm/s\n    nm_to_cm = 1.0e-7\n\n    zps = {}\n    for filter_name, filter_ in filters.iteritems():\n        fwave = filter_['wave']\n        throughput = filter_['throughput']\n        ABflambda = ABsource * c / fwave**2 / nm_to_cm # erg/s/Hz/cm^2*cm/s/nm^2 -> erg/s/cm^2/nm\n        AB_photons = ABflambda * fwave * throughput\n        dlambda = fwave[1] - fwave[0] # assuming linear wavelength bins!\n        AB_sumphotons = (AB_photons * dlambda).sum()\n        zps[filter_name] = -2.5 * numpy.log10(AB_sumphotons)\n    return zps\n\ndef read_spec(specfile):\n    wave, flambda = numpy.genfromtxt(specfile).T\n    return {'wave':wave, 'flambda':flambda}\n\ndef match_wavelengths(spec, wave_match):\n    \"\"\" Interpolate spectrum onto given wavelength array.\n    \"\"\"\n    flux_i = numpy.interp(wave_match, spec['wave'], spec['flambda'])\n    return {'wave':wave_match, 'flambda':flux_i}\n\ndef apply_redshift(spec, redshift):\n    flux_i = numpy.interp(spec['wave'], spec['wave'] * (1.0 + redshift), spec['flambda'])\n    return {'wave':spec['wave'], 'flambda':flux_i / (1.0 + redshift)}\n\ndef scale_spec(spec, target_mag, normfilter, normzp):\n    \"\"\" Multiply spectrum flux such that the normalization magnitude matches the given target\n    magnitude.\n    \"\"\"\n    fwave = normfilter['wave']\n    throughput = normfilter['throughput']\n    flambda_i = numpy.interp(fwave, spec['wave'], spec['flambda'])\n    photons = flambda_i * fwave * throughput\n    dlambda = fwave[1] - fwave[0]\n    sumphotons = (photons * dlambda).sum()\n    current_mag = -2.5 * numpy.log10(sumphotons) - normzp\n    multiplier = 10**(-0.4 * (target_mag - current_mag))\n    spec['flambda'] *= multiplier\n    return spec\n\ndef apply_extinction(spec, A_v, R_v=3.1):\n    wave = spec['wave']\n    valid = (wave > 92) & (wave < 1200)\n    wave = wave[valid]\n    ext = chroma.extinction.reddening(wave*10, a_v=A_v, r_v=R_v, model='f99')\n    flambda = spec['flambda']\n    flambda[valid] /= ext\n    spec = {'wave':spec['wave'], 'flambda':flambda}\n    return spec\n\ndef compute_mags(spec, filters, zps):\n    \"\"\" Compute magnitudes from spectrum.  Assume that spectrum wavelengths are already matched to\n    filter wavelengths.\n    \"\"\"\n    mags = {}\n    for filter_name, filter_ in filters.iteritems():\n        fwave = filter_['wave']\n        throughput = filter_['throughput']\n        photons = spec['flambda'] * fwave * throughput\n        dlambda = fwave[1] - fwave[0] # assuming linear wavelength bins!\n        sumphotons = (photons * dlambda).sum()\n        mags[filter_name] = -2.5 * numpy.log10(sumphotons) - zps[filter_name]\n    return mags\n\ndef make_composite_spec(gal, filters, zps, wave_match):\n    SED_dir = os.environ['CAT_SHARE_DATA']+'data/'\n\n    if gal['sedPathBulge'] != 'None':\n        bulge_spec = read_spec(SED_dir+gal['sedPathBulge'])\n        bulge_spec = scale_spec(bulge_spec, gal['magNormBulge'],\n                                filters['norm'], zps['norm'])\n        bulge_spec = apply_extinction(bulge_spec,\n                                      A_v=gal['internalAVBulge'],\n                                      R_v=gal['internalRVBulge'])\n        bulge_spec = apply_redshift(bulge_spec, gal['redshift'])\n        bulge_spec = match_wavelengths(bulge_spec, wave_match)\n    else:\n        bulge_spec = {'wave':wave_match, 'flambda':numpy.zeros_like(wave_match)}\n    if gal['sedPathDisk'] != 'None':\n        disk_spec = read_spec(SED_dir+gal['sedPathDisk'])\n        disk_spec = scale_spec(disk_spec, gal['magNormDisk'],\n                                filters['norm'], zps['norm'])\n        disk_spec = apply_extinction(disk_spec,\n                                      A_v=gal['internalAVDisk'],\n                                      R_v=gal['internalRVDisk'])\n        disk_spec = apply_redshift(disk_spec, gal['redshift'])\n        disk_spec = match_wavelengths(disk_spec, wave_match)\n    else:\n        disk_spec = {'wave':wave_match, 'flambda':numpy.zeros_like(wave_match)}\n    if gal['sedPathAGN'] != 'None':\n        AGN_spec = read_spec(SED_dir+gal['sedPathAGN'])\n        AGN_spec = scale_spec(AGN_spec, gal['magNormAGN'],\n                              filters['norm'], zps['norm'])\n        AGN_spec = apply_redshift(AGN_spec, gal['redshift'])\n        AGN_spec = match_wavelengths(AGN_spec, wave_match)\n    else:\n        AGN_spec = {'wave':wave_match, 'flambda':numpy.zeros_like(wave_match)}\n    return {'wave':wave_match, 'flambda':(bulge_spec['flambda'] +\n                                          disk_spec['flambda'] +\n                                          AGN_spec['flambda'])}\n\ndef get_UV_flux(spec):\n    # flambda in erg/s/cm^2/nm\n    UV_flambda = numpy.interp(230.0, spec['wave'], spec['flambda'])\n    # convert to erg/s/Hz\n    c = 29979245800.0 # cm/s\n    nm_to_cm = 1.0e-7\n    UV_fnu = UV_flambda * (230.0)**2 / c * nm_to_cm\n    return UV_fnu\n\ndef add_emission_lines(spec):\n    wave = spec['wave'][:]\n    flambda = spec['flambda'][:]\n    UV_fnu = get_UV_flux(spec)\n    lines = ['OII','OIII','Hbeta','Halpha','Lya']\n    multipliers = numpy.array([1.0, 0.36, 0.61, 1.77, 2.0])*1.e13\n    waves = [372.7, 500.7, 486.1, 656.3, 121.5]\n    velocity = 200.0 # km/s\n    for line, m, w in zip(lines, multipliers, waves):\n        flux = UV_fnu * m\n        sigma = velocity / 299792.458 * w # sigma in Angstroms\n        amplitude = flux / sigma / numpy.sqrt(2.0 * numpy.pi)\n        flambda += amplitude * numpy.exp(-(w-spec['wave'])**2/(2*sigma**2))\n    return {'wave':wave, 'flambda':flambda}\n\ndef make_composite_spec_with_emission_lines(gal, filters, zps, wave_match):\n    SED_dir = os.environ['CAT_SHARE_DATA']+'data/'\n\n    if gal['sedPathBulge'] != 'None':\n        bulge_spec = read_spec(SED_dir+gal['sedPathBulge'])\n        bulge_spec = scale_spec(bulge_spec, gal['magNormBulge'],\n                                filters['norm'], zps['norm'])\n        bulge_spec = add_emission_lines(bulge_spec)\n        bulge_spec = apply_extinction(bulge_spec,\n                                      A_v=gal['internalAVBulge'],\n                                      R_v=gal['internalRVBulge'])\n        bulge_spec = apply_redshift(bulge_spec, gal['redshift'])\n        bulge_spec = match_wavelengths(bulge_spec, wave_match)\n    else:\n        bulge_spec = {'wave':wave_match, 'flambda':numpy.zeros_like(wave_match)}\n    if gal['sedPathDisk'] != 'None':\n        disk_spec = read_spec(SED_dir+gal['sedPathDisk'])\n        disk_spec = scale_spec(disk_spec, gal['magNormDisk'],\n                                filters['norm'], zps['norm'])\n        disk_spec = add_emission_lines(disk_spec)\n        disk_spec = apply_extinction(disk_spec,\n                                      A_v=gal['internalAVDisk'],\n                                      R_v=gal['internalRVDisk'])\n        disk_spec = apply_redshift(disk_spec, gal['redshift'])\n        disk_spec = match_wavelengths(disk_spec, wave_match)\n    else:\n        disk_spec = {'wave':wave_match, 'flambda':numpy.zeros_like(wave_match)}\n    if gal['sedPathAGN'] != 'None':\n        AGN_spec = read_spec(SED_dir+gal['sedPathAGN'])\n        AGN_spec = scale_spec(AGN_spec, gal['magNormAGN'],\n                              filters['norm'], zps['norm'])\n        AGN_spec = apply_redshift(AGN_spec, gal['redshift'])\n        AGN_spec = match_wavelengths(AGN_spec, wave_match)\n    else:\n        AGN_spec = {'wave':wave_match, 'flambda':numpy.zeros_like(wave_match)}\n    return {'wave':wave_match, 'flambda':(bulge_spec['flambda'] +\n                                          disk_spec['flambda'] +\n                                          AGN_spec['flambda'])}\n\ndef make_bulge_spec(gal, filters, zps, wave_match):\n    SED_dir = os.environ['CAT_SHARE_DATA']+'data/'\n\n    if gal['sedPathBulge'] != 'None':\n        bulge_spec = read_spec(SED_dir+gal['sedPathBulge'])\n        bulge_spec = scale_spec(bulge_spec, gal['magNormBulge'],\n                                filters['norm'], zps['norm'])\n        bulge_spec = apply_extinction(bulge_spec,\n                                      A_v=gal['internalAVBulge'],\n                                      R_v=gal['internalRVBulge'])\n        bulge_spec = apply_redshift(bulge_spec, gal['redshift'])\n        bulge_spec = match_wavelengths(bulge_spec, wave_match)\n    else:\n        return None\n    return {'wave':wave_match, 'flambda':bulge_spec['flambda']}\n\ndef make_disk_spec(gal, filters, zps, wave_match):\n    SED_dir = os.environ['CAT_SHARE_DATA']+'data/'\n\n    if gal['sedPathDisk'] != 'None':\n        disk_spec = read_spec(SED_dir+gal['sedPathDisk'])\n        disk_spec = scale_spec(disk_spec, gal['magNormDisk'],\n                                filters['norm'], zps['norm'])\n        disk_spec = apply_extinction(disk_spec,\n                                      A_v=gal['internalAVDisk'],\n                                      R_v=gal['internalRVDisk'])\n        disk_spec = apply_redshift(disk_spec, gal['redshift'])\n        disk_spec = match_wavelengths(disk_spec, wave_match)\n    else:\n        return None\n    return {'wave':wave_match, 'flambda':disk_spec['flambda']}\n", "meta": {"hexsha": "26302fad0c80cb03eb2da6aaa6bfb227eca102b6", "size": 11092, "ext": "py", "lang": "Python", "max_stars_repo_path": "bin/analytic/catalog/phot.py", "max_stars_repo_name": "DarkEnergyScienceCollaboration/chroma", "max_stars_repo_head_hexsha": "64fc123a065334b307654f29b3bea52885b46ec8", "max_stars_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-10-22T14:57:27.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-25T08:16:02.000Z", "max_issues_repo_path": "bin/analytic/catalog/phot.py", "max_issues_repo_name": "DarkEnergyScienceCollaboration/chroma", "max_issues_repo_head_hexsha": "64fc123a065334b307654f29b3bea52885b46ec8", "max_issues_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-08-28T14:42:46.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-28T16:08:37.000Z", "max_forks_repo_path": "bin/analytic/catalog/phot.py", "max_forks_repo_name": "DarkEnergyScienceCollaboration/chroma", "max_forks_repo_head_hexsha": "64fc123a065334b307654f29b3bea52885b46ec8", "max_forks_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.1595330739, "max_line_length": 99, "alphanum_fraction": 0.6017850703, "include": true, "reason": "import numpy", "num_tokens": 3005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.1931371267631578}}
{"text": "\"\"\" Minimum working example of an SME script\n\"\"\"\n\nimport logging\nimport sys\nfrom os.path import dirname, join, realpath\n\nimport numpy as np\n\nfrom pysme import sme as SME\nfrom pysme import util\nfrom pysme.linelist.vald import ValdFile\nfrom pysme.nso import load_solar_spectrum\nfrom pysme.solve import solve\n\nlogger = logging.getLogger(\"pysme\")\n# logger.setLevel(logging.CRITICAL)\n\nif __name__ == \"__main__\":\n    # Define the location of all your files\n    # this will put everything into the example dir\n    target = \"sun\"\n    examples_dir = dirname(realpath(__file__))\n    # in_file = join(examples_dir, \"../sun_6440_test.inp\")\n    # in_file = join(examples_dir, \"gr8_HARPS_HD148816.inp\")\n    vald_file = join(examples_dir, \"data/harps.lin\")\n    out_file = join(examples_dir, f\"{target}.sme\")\n    plot_file = join(examples_dir, f\"{target}.html\")\n    log_file = join(examples_dir, f\"{target}.log\")\n\n    # Use HARPS spectral range\n    wave, flux = load_solar_spectrum()\n    wmin, wmax = 3780, 6910\n    idx = (wave > wmin) & (wave < wmax)\n    wave, flux = wave[idx], flux[idx]\n    flux[flux < 0] = 0\n\n    sme = SME.SME_Structure(wave=wave, sob=flux)\n    sme.uncs = np.sqrt(flux)\n    sme.mask = sme.mask_values[\"line\"]\n\n    sme.linelist = ValdFile(vald_file)\n\n    sme.nmu = 7\n    sme.vrad = 0\n    sme.cscale = None\n    sme.vrad_flag = \"each\"\n    sme.cscale_flag = \"linear\"\n    sme.cscale_type = \"match\"\n    sme.atmo.source = \"marcs2014.sav\"\n    sme.abund = \"asplund2009\"\n\n    # elems = [\n    #     \"Al\",\n    #     \"Ba\",\n    #     \"Ca\",\n    #     \"C\",\n    #     \"H\",\n    #     \"K\",\n    #     \"Li\",\n    #     \"Mg\",\n    #     \"Mn\",\n    #     \"Na\",\n    #     \"N\",\n    #     \"O\",\n    #     \"Si\",\n    # ]\n    # for elem in elems:\n    #     sme.nlte.set_nlte(elem, f\"nlte_{elem}_ama51_pysme.grd\")\n    # sme.nlte.set_nlte(\"Fe\", \"marcs2012_Fe2016.grd\")\n\n    # Load the parameters from the command line\n    if len(sys.argv) > 1:\n        param = sys.argv[1:]\n    else:\n        param = [5000, 4.0, 0]  # 5000.00, 4.00, 0.00\n    sme.teff = float(param[0])\n    sme.logg = float(param[1])\n    sme.monh = float(param[2])\n\n    # try:\n    sme = solve(sme, [\"teff\", \"logg\", \"monh\"])\n    print(f\"{param[0]}, {param[1]}, {param[2]}, {sme.teff}, {sme.logg}, {sme.monh}\")\n    # except Exception as ex:\n    #     print(f\"{param[0]}, {param[1]}, {param[2]}, nan, nan, nan\")\n", "meta": {"hexsha": "9026686291bb4d67b075087aa08733a7234e2dbc", "size": 2345, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/paper/convergence_part1.py", "max_stars_repo_name": "AWehrhahn/SME", "max_stars_repo_head_hexsha": "542e880ed779381f7cbbaaacb59475fa6a6d3537", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-06-26T18:43:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T00:53:42.000Z", "max_issues_repo_path": "examples/paper/convergence_part1.py", "max_issues_repo_name": "AWehrhahn/SME", "max_issues_repo_head_hexsha": "542e880ed779381f7cbbaaacb59475fa6a6d3537", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-03-01T15:21:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-01T15:28:37.000Z", "max_forks_repo_path": "examples/paper/convergence_part1.py", "max_forks_repo_name": "AWehrhahn/SME", "max_forks_repo_head_hexsha": "542e880ed779381f7cbbaaacb59475fa6a6d3537", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-03-01T15:25:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T10:26:33.000Z", "avg_line_length": 27.2674418605, "max_line_length": 84, "alphanum_fraction": 0.5918976546, "include": true, "reason": "import numpy", "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3557748866829644, "lm_q1q2_score": 0.19313712305504008}}
{"text": "'''\nContains routines to read and manipulate particle size distribution data from the\n2D-S and HVPS optical array probes during the IMPACTS experiment. Creation of 1 Hz\nPSD data requires use of UIOOPS package (doi: 10.5281/zenodo.3976291).\nSome of the arguments in the routines require radar data matched to the P-3\nlocation to determine the optional degree of riming following Leinonen & Szyrmer (2015).\n\nCopyright Joe Finlon, Univ. of Washington, 2022.\n'''\n\nimport xarray as xr\nimport numpy as np\nnp.warnings.filterwarnings('ignore', category=np.VisibleDeprecationWarning)\nnp.warnings.filterwarnings('ignore', message='Mean of empty slice')\nnp.seterr(invalid='ignore')\nfrom datetime import datetime, timedelta\nfrom scipy.optimize import least_squares\ntry: # try importing the pytmatrix package\n    from forward import *\nexcept ImportError:\n    print(\n        'WARNING: The pytmatrix package cannot be installed for the psdread() function.'\n    )\n\n    \ndef psdread(\n        twodsfile, hvpsfile, datestr, size_cutoff=1., minD=0.15, maxD=30.,\n        qc=False, deadtime_thresh=0.6, verbose=True,\n        start_time=None, end_time=None, tres=5.,\n        compute_bulk=False, compute_fits=False, Z_interp=False,\n        matchedZ_W=None, matchedZ_Ka=None, matchedZ_Ku=None, matchedZ_X=None):\n    '''\n    Load the 2DS and HVPS PSDs processed by UIOOPS and create n-second combined PSDs with optional bulk properties.\n    Inputs:\n        twodsfile: Path to the 2DS data\n        hvpsfile: Path to the HVPS data\n        datestr: YYYYMMDD [str]\n        size_cutoff: Size [mm] for the 2DS-HVPS crossover\n        minD: Minimum size [mm] to consider in the combined PSD\n        maxD: Maximum size [mm] to consider in the combined PSD\n        qc: Boolean to optionally ignore 1-Hz data from averaging when probe dead time > deadtime_thresh\n        deadtime_thresh: Deadtime hreshold [0–1] to ignore 1-Hz data when qc is True\n        verbose: Boolean to optionally print all data-related warnings (e.g., high probe dead time)\n        start_time: Start time [YYYY-MM-DDTHH:MM:SS as str] to consider for the PSDs (optional)\n        end_time: End time [YYYY-MM-DDTHH:MM:SS as str] to consider for the PSDs (optional)\n        tres: Averaging interval [s]; tres=1. skips averaging routine\n        compute_bulk: Boolean to optionally compute bulk statistics such as N, IWC, Dmm, rho_e\n        compute_fits: Boolean to optionally compute gamma fit parameters N0, mu, lambda\n        Z_interp: Boolean to optionally simulate Z for additional degrees of riming from Leinonen & Szyrmer (2015; LS15)\n        matchedZ_Ka, ...: None (skips minimization) or masked array of matched Z values to perform LS15 m-D minimization\n    '''\n    p3psd = {}\n\n    if (twodsfile is None) and (hvpsfile is not None):\n        print('Only using the HVPS data for {}'.format(datestr))\n        size_cutoff = 0.4 # start HVPS PSD at 0.4 mm\n    elif (hvpsfile is None) and (twodsfile is not None):\n        print('Only using the 2DS data for {}'.format(datestr))\n        size_cutoff = 3.2 # end 2DS PSD at 3.2 mm\n    elif (twodsfile is None) and (hvpsfile is None):\n        print('No input files given...exiting')\n        exit()\n\n    # 2DS information\n    if twodsfile is not None:\n        ds1 = xr.open_dataset(twodsfile)\n        time_raw = ds1['time'].values # HHMMSS from flight start date or numpy.datetime64\n        if np.issubdtype(time_raw.dtype, np.datetime64): # numpy.datetime64\n            time = np.array(time_raw, dtype='datetime64[s]')\n        else: # native HHMMSS format (from UIOOPS SD file)\n            time_dt = [\n                datetime(int(datestr[0:4]), int(datestr[4:6]), int(datestr[6:]))\n                + timedelta(\n                    hours=int(str(int(time_raw[i])).zfill(6)[0:2]),\n                    minutes=int(str(int(time_raw[i])).zfill(6)[2:4]),\n                    seconds=int(str(int(time_raw[i])).zfill(6)[4:]))\n                for i in range(len(time_hhmmss))\n            ]\n            time_str = [\n                datetime.strftime(time_dt[i], '%Y-%m-%dT%H:%M:%S')\n                for i in range(len(time_dt))\n            ]\n            time = np.array(time_str, dtype='datetime64[s]')\n        bin_min_2ds = ds1['bin_min'].values # mm\n        bin_max_2ds = ds1['bin_max'].values\n        bin_inds = np.where((bin_min_2ds>=minD) & (bin_max_2ds<=size_cutoff))[0] # find bins within user-specified range\n        bin_min_2ds = bin_min_2ds[bin_inds]; bin_max_2ds = bin_max_2ds[bin_inds]\n        bin_width_2ds = ds1['bin_dD'].values[bin_inds] / 10. # cm\n        bin_mid_2ds = bin_min_2ds + (bin_width_2ds * 10.) / 2.\n        count_2ds = ds1['count'].values[:, bin_inds]\n        sv_2ds = ds1['sample_vol'].values[:, bin_inds] # cm^3\n        count_hab_2ds = ds1['habitsd'].values[:, bin_inds, :] * np.tile(np.reshape(sv_2ds, (sv_2ds.shape[0], sv_2ds.shape[1], 1)), (1, 1, 10)) * np.tile(\n            np.reshape(bin_width_2ds, (1, len(bin_width_2ds), 1)), (sv_2ds.shape[0], 1, 10))\n        ar_2ds = ds1['mean_area_ratio'].values[:, bin_inds] # mean area ratio (circular fit) per bin\n        asr_2ds = ds1['mean_aspect_ratio_ellipse'].values[:, bin_inds] # mean aspect ratio (elliptical fit) per bin\n        activetime_2ds = ds1['sum_IntArr'].values # s\n\n        if hvpsfile is None:\n            count = count_2ds; count_hab = count_hab_2ds; sv = sv_2ds; ar = ar_2ds; asr = asr_2ds; activetime_hvps = np.ones(count.shape[0])\n            bin_min = bin_min_2ds; bin_mid = bin_mid_2ds; bin_max = bin_max_2ds; bin_width = bin_width_2ds\n\n    # HVPS information\n    if hvpsfile is not None:\n        ds2 = xr.open_dataset(hvpsfile)\n        bin_min_hvps = ds2['bin_min'].values # mm\n        bin_max_hvps = ds2['bin_max'].values\n        bin_inds = np.where((bin_min_hvps>=size_cutoff) & (bin_max_hvps<=maxD))[0] # find bins within user-specified range\n        bin_min_hvps = bin_min_hvps[bin_inds]; bin_max_hvps = bin_max_hvps[bin_inds]\n        bin_width_hvps = ds2['bin_dD'].values[bin_inds] / 10. # cm\n        if size_cutoff==2.:\n            bin_min_hvps = np.insert(bin_min_hvps, 0, 2.); bin_max_hvps = np.insert(bin_max_hvps, 0, 2.2); bin_width_hvps = np.insert(bin_width_hvps, 0, 0.02)\n            bin_inds = np.insert(bin_inds, 0, bin_inds[0]-1)\n        bin_mid_hvps = bin_min_hvps + (bin_width_hvps * 10.) / 2.\n        count_hvps = ds2['count'].values[:, bin_inds]\n        sv_hvps = ds2['sample_vol'].values[:, bin_inds] # cm^3\n        count_hab_hvps = (ds2['habitsd'].values[:, bin_inds, :]) * np.tile(np.reshape(sv_hvps, (sv_hvps.shape[0], sv_hvps.shape[1], 1)), (1, 1, 10)) * np.tile(\n            np.reshape(bin_width_hvps, (1, len(bin_width_hvps), 1)), (sv_hvps.shape[0], 1, 10))\n        ar_hvps = ds2['mean_area_ratio'].values[:, bin_inds] # mean area ratio (circular fit) per bin\n        asr_hvps = ds2['mean_aspect_ratio_ellipse'].values[:, bin_inds] # mean aspect ratio (elliptical fit) per bin\n        activetime_hvps = ds2['sum_IntArr'].values # s\n        if size_cutoff==2.: # normalize counts in first bin (1.8-2.2 mm, now only for 2-2.2 mm)\n            count_hvps[:, 0] = count_hvps[:, 0] / 2.\n            count_hab_hvps[:, 0, :] = count_hab_hvps[:, 0, :] / 2.\n\n        if twodsfile is None:\n            time_hhmmss = ds2['time'].values # HHMMSS from flight start date\n            time_dt = [datetime(int(datestr[0:4]), int(datestr[4:6]), int(datestr[6:])) + timedelta(\n                hours=int(str(int(time_hhmmss[i])).zfill(6)[0:2]), minutes=int(str(int(time_hhmmss[i])).zfill(6)[2:4]),\n                seconds=int(str(int(time_hhmmss[i])).zfill(6)[4:])) for i in range(len(time_hhmmss))]\n            time_str = [datetime.strftime(time_dt[i], '%Y-%m-%dT%H:%M:%S') for i in range(len(time_dt))]\n            time = np.array(time_str, dtype='datetime64[s]')\n            count = count_hvps; count_hab = count_hab_hvps; sv = sv_hvps; ar = ar_hvps; asr = asr_hvps; activetime_2ds = np.ones(count.shape[0])\n            bin_min = bin_min_hvps; bin_mid = bin_mid_hvps; bin_max = bin_max_hvps; bin_width = bin_width_hvps\n\n    # Combine the datasets\n    if (twodsfile is not None) and (hvpsfile is not None):\n        count = np.concatenate((count_2ds, count_hvps), axis=1)\n        count_hab = np.concatenate((count_hab_2ds, count_hab_hvps), axis=1)\n        sv = np.concatenate((sv_2ds, sv_hvps), axis=1)\n        ar = np.concatenate((ar_2ds, ar_hvps), axis=1)\n        asr = np.concatenate((asr_2ds, asr_hvps), axis=1)\n        bin_min = np.concatenate((bin_min_2ds, bin_min_hvps))\n        bin_mid = np.concatenate((bin_mid_2ds, bin_mid_hvps))\n        bin_max = np.concatenate((bin_max_2ds, bin_max_hvps))\n        bin_width = np.concatenate((bin_width_2ds, bin_width_hvps))\n\n    # Average the data\n    if start_time is None:\n        start_dt64 = time[0]\n    else:\n        start_dt64 = np.datetime64(start_time)\n    if end_time is None:\n        end_dt64 = time[-1] if int(tres)>1 else time[-1]+np.timedelta64(1, 's')\n    else:\n        end_dt64 = np.datetime64(end_time) if int(tres)>1 else np.datetime64(end_time)+np.timedelta64(1, 's')\n    dur = (end_dt64 - start_dt64) / np.timedelta64(1, 's') # dataset duration to consider [s]\n\n    # Allocate arrays\n    count_aver = np.zeros((int(dur/tres), len(bin_mid)))\n    count_hab_aver = np.zeros((int(dur/tres), len(bin_mid), 8))\n    sv_aver = np.zeros((int(dur/tres), len(bin_mid)))\n    at_2ds_aver = np.ma.array(np.ones(int(dur/tres)), mask=False)\n    at_hvps_aver = np.ma.array(np.ones(int(dur/tres)), mask=False)\n    ND = np.zeros((int(dur/tres), len(bin_mid)))\n    ar_aver = np.zeros((int(dur/tres), len(bin_mid)))\n    asr_aver = np.zeros((int(dur/tres), len(bin_mid)))\n\n    time_subset = start_dt64 # allocate time array of N-sec interval obs\n    curr_time = start_dt64\n    i = 0\n\n    while curr_time+np.timedelta64(int(tres),'s')<=end_dt64:\n        if curr_time>start_dt64:\n            time_subset = np.append(time_subset, curr_time)\n        time_inds = np.where((time>=curr_time) & (time<curr_time+np.timedelta64(int(tres), 's')))[0]\n        if qc is True:\n            activetime_thresh = 1. - deadtime_thresh\n            time_inds = time_inds[(activetime_2ds[time_inds]>=activetime_thresh) & (activetime_hvps[time_inds]>=activetime_thresh)]\n        if len(time_inds)>0:\n            count_aver[i, :] = np.nansum(count[time_inds, :], axis=0)\n            count_hab_aver[i, :, 0] = np.nansum(count_hab[time_inds, :, 3], axis=0) # tiny\n            count_hab_aver[i, :, 1] = np.nansum(count_hab[time_inds, :, 0], axis=0) # spherical\n            count_hab_aver[i, :, 2] = np.nansum(count_hab[time_inds, :, 1:3], axis=(0, 2)) # oriented + linear\n            count_hab_aver[i, :, 3] = np.nansum(count_hab[time_inds, :, 4], axis=0) # hexagonal\n            count_hab_aver[i, :, 4] = np.nansum(count_hab[time_inds, :, 5], axis=0) # irregular\n            count_hab_aver[i, :, 5] = np.nansum(count_hab[time_inds, :, 6], axis=0) # graupel\n            count_hab_aver[i, :, 6] = np.nansum(count_hab[time_inds, :, 7], axis=0) # dendrite\n            count_hab_aver[i, :, 7] = np.nansum(count_hab[time_inds, :, 8], axis=0) # aggregate\n            ar_aver[i, :] = np.nanmean(ar[time_inds, :], axis=0) # binned mean of area ratio\n            asr_aver[i, :] = np.nanmean(asr[time_inds, :], axis=0) # binned mean of aspect ratio\n            sv_aver[i, :] = np.nansum(sv[time_inds, :], axis=0)\n            at_2ds_aver[i] = np.nansum(activetime_2ds[time_inds]) / len(time_inds)\n            at_hvps_aver[i] = np.nansum(activetime_hvps[time_inds]) / len(time_inds)\n            ND[i, :] = np.nanmean(count[time_inds, :]/sv[time_inds, :], axis=0) / bin_width # take N(D) for each sec, then average [cm**-4]\n        else: # Mask data for current period if dead (active) time from either probe > 0.8*tres (< 0.2*tres) for all 1-Hz times\n            if verbose is True:\n                print('All 1-Hz data for the {}-s period beginning {} has high dead time. Masking data.'.format(str(tres), np.datetime_as_string(curr_time)))\n            at_2ds_aver[i] = np.nansum(activetime_2ds[np.where((time>=curr_time) & (time<curr_time+np.timedelta64(int(tres), 's')))[0]]) / tres; at_2ds_aver.mask[i] = True\n            at_hvps_aver[i] = np.nansum(activetime_hvps[np.where((time>=curr_time) & (time<curr_time+np.timedelta64(int(tres), 's')))[0]]) / tres; at_hvps_aver.mask[i] = True\n            count_aver[i, :] = np.nan; count_hab_aver[i, :] = np.nan; sv_aver[i, :] = np.nan; ND[i, :] = np.nan; asr_aver[i, :] = np.nan\n        i += 1\n        curr_time += np.timedelta64(int(tres), 's')\n\n    #ND = np.ma.masked_invalid(count_aver / sv_aver / np.tile(bin_width[np.newaxis, :], (int(dur/tres), 1))) # cm^-4\n\n    # Mask arrays\n    count_aver = np.ma.masked_where(np.isnan(count_aver), count_aver)\n    count_hab_aver = np.ma.masked_where(np.isnan(count_hab_aver), count_hab_aver)\n    sv_aver = np.ma.masked_where(np.isnan(sv_aver), sv_aver)\n    ar_aver = np.ma.masked_invalid(ar_aver)\n    asr_aver = np.ma.masked_invalid(asr_aver)\n    ND[~np.isfinite(ND)] = 0.; ND = np.ma.masked_where(ND==0., ND)\n\n    # Create dictionary\n    p3psd['time'] = time_subset\n    p3psd['count'] = count_aver\n    p3psd['count_habit'] = count_hab_aver\n    p3psd['sv'] = sv_aver\n    p3psd['area_ratio'] = ar_aver\n    p3psd['aspect_ratio'] = asr_aver\n    p3psd['ND'] = ND\n    p3psd['bin_min'] = bin_min\n    p3psd['bin_mid'] = bin_mid\n    p3psd['bin_max'] = bin_max\n    p3psd['bin_width'] = bin_width\n    p3psd['active_time_2ds'] = at_2ds_aver\n    p3psd['active_time_hvps'] = at_hvps_aver\n\n    if compute_bulk is True:\n        # Compute Z for various degrees of riming and radar wavelengths\n        # Based on work from Leionen and Szyrmer 2015 (LS15)\n        # (https://agupubs.onlinelibrary.wiley.com/doi/pdf/10.1002/2015EA000102)\n        # Follows https://github.com/dopplerchase/Leinonen_Python_Forward_Model\n        # and uses forward.py and ess238-sup-0002-supinfo.tex in repo\n        Z = forward_Z() #initialize class\n        # get the PSD in the format to use in the routine (mks units)\n        Z.set_PSD(PSD=ND*10.**8, D=bin_mid/1000., dD=bin_width/100., Z_interp=Z_interp)\n        Z.load_split_L15() # Load the leinonen output\n        Z.fit_sigmas(Z_interp) # Fit the backscatter cross-sections\n        Z.fit_rimefrac(Z_interp) # Fit the riming fractions\n        Z.calc_Z() # Calculate Z...outputs are Z.Z_x, Z.Z_ku, Z.Z_ka, Z.Z_w for the four radar wavelengths\n\n        # Compute IWC and Dmm following Brown and Francis (1995), modified for a Dmax definition following Hogan et al.\n        [\n            N0_bf, N0_hy, mu_bf, mu_hy, lam_bf, lam_hy, iwc_bf, iwc_hy, iwc_hab,\n            asr_nw, asr_bf, asr_hy, asr_hab, dmm_bf, dmm_hy, dmm_hab, dm_bf, dm_hy,\n            dm_hab, rho_bf, rho_hy, rho_hab, rhoe_bf, rhoe_hy, rhoe_hab] = calc_bulk(\n            count_aver, count_hab_aver, sv_aver, asr_aver, bin_mid, bin_width)\n\n        # Add bulk variables to the dictionary\n        if Z_interp is True: # consider additional degrees of riming from LS15\n            p3psd['riming_mass_array'] = [\n                0., 0.05, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 0.75, 1., 2.]\n        else:\n            p3psd['riming_mass_array'] = [0., 0.1, 0.2, 0.5, 1., 2.]\n        p3psd['a_coeff_array'] = Z.a_coeff\n        p3psd['b_coeff_array'] = Z.b_coeff\n        p3psd['dbz_W'] = Z.Z_w\n        p3psd['dbz_Ka'] = Z.Z_ka\n        p3psd['dbz_Ku'] = Z.Z_ku\n        p3psd['dbz_X'] = Z.Z_x\n        p3psd['N0_bf'] = N0_bf\n        p3psd['N0_hy'] = N0_hy\n        p3psd['mu_bf'] = mu_bf\n        p3psd['mu_hy'] = mu_hy\n        p3psd['lambda_bf'] = lam_bf\n        p3psd['lambda_hy'] = lam_hy\n        p3psd['iwc_bf'] = iwc_bf\n        p3psd['iwc_hy'] = iwc_hy\n        p3psd['iwc_hab'] = iwc_hab\n        p3psd['mean_aspect_ratio'] = asr_nw\n        p3psd['mean_aspect_ratio_bf'] = asr_bf\n        p3psd['mean_aspect_ratio_hy'] = asr_hy\n        p3psd['mean_aspect_ratio_habit'] = asr_hab\n        p3psd['dmm_bf'] = dmm_bf\n        p3psd['dmm_hy'] = dmm_hy\n        p3psd['dmm_hab'] = dmm_hab\n        p3psd['dm_bf'] = dm_bf\n        p3psd['dm_hy'] = dm_hy\n        p3psd['dm_hab'] = dm_hab\n        p3psd['eff_density_bf'] = rhoe_bf\n        p3psd['eff_density_hy'] = rhoe_hy\n        p3psd['eff_density_hab'] = rhoe_hab\n        p3psd['density_bf'] = rho_bf\n        p3psd['density_hy'] = rho_hy\n        p3psd['density_hab'] = rho_hab\n\n        # Optionally constrain the matched Z at Ku- and Ka-band against PSDS to estimate bulk properties\n        if (\n                matchedZ_W is not None) or (matchedZ_Ka is not None) or (\n                matchedZ_Ku is not None) or (matchedZ_X is not None):\n            p3psd = calc_riming(\n                p3psd, Z, matchedZ_W, matchedZ_Ka, matchedZ_Ku, matchedZ_X,\n                compute_fits=compute_fits)\n\n    return p3psd\n\ndef calc_bulk(particle_count, habit_count, sample_vol, aspect_ratio, bin_mid, bin_width):\n    x0 = [1.e-1, -1., 5.] # initial guess for N0 [cm**-4], mu, lambda [cm**-1]\n\n    # allocate arrays\n    N0_bf = np.zeros(particle_count.shape[0])\n    N0_hy = np.zeros(particle_count.shape[0])\n    mu_bf = np.zeros(particle_count.shape[0])\n    mu_hy = np.zeros(particle_count.shape[0])\n    lam_bf = np.zeros(particle_count.shape[0])\n    lam_hy = np.zeros(particle_count.shape[0])\n    iwc_bf = np.zeros(particle_count.shape[0])\n    iwc_hy = np.zeros(particle_count.shape[0])\n    iwc_hab = np.zeros(particle_count.shape[0])\n    asr_nw = np.zeros(particle_count.shape[0])\n    asr_bf = np.zeros(particle_count.shape[0])\n    asr_hy = np.zeros(particle_count.shape[0])\n    asr_hab = np.zeros(particle_count.shape[0])\n    dmm_bf = np.zeros(particle_count.shape[0])\n    dmm_hy = np.zeros(particle_count.shape[0])\n    dmm_hab = np.zeros(particle_count.shape[0])\n    dm_bf = np.zeros(particle_count.shape[0])\n    dm_hy = np.zeros(particle_count.shape[0])\n    dm_hab = np.zeros(particle_count.shape[0])\n    rhoe_bf = np.zeros(particle_count.shape[0])\n    rhoe_hy = np.zeros(particle_count.shape[0])\n    rhoe_hab = np.zeros(particle_count.shape[0])\n    rho_bf = np.zeros((particle_count.shape[0], particle_count.shape[1]))\n    rho_hy = np.zeros((particle_count.shape[0], particle_count.shape[1]))\n    rho_hab = np.zeros((particle_count.shape[0], particle_count.shape[1]))\n\n    # compute particle habit mass outside loop for speed\n    a_coeff = np.array([1.96e-3, 1.96e-3, 1.666e-3, 7.39e-3, 1.96e-3, 4.9e-2, 5.16e-4, 1.96e-3])\n    a_tile = np.tile(np.reshape(a_coeff, (1, len(a_coeff))), (habit_count.shape[1], 1))\n    b_coeff = np.array([1.9, 1.9, 1.91, 2.45, 1.9, 2.8, 1.8, 1.9])\n    b_tile = np.tile(np.reshape(b_coeff, (1, len(b_coeff))), (habit_count.shape[1], 1))\n    D_tile = np.tile(np.reshape(bin_mid, (len(bin_mid), 1)), (1, habit_count.shape[2]))\n    mass_tile = a_tile * (D_tile/10.) ** b_tile\n\n    for time_ind in range(particle_count.shape[0]):\n        if particle_count[time_ind, :].count()==particle_count.shape[1]: # time period is not masked...continue on\n            Nt = 1000.*np.nansum(particle_count[time_ind, :]/sample_vol[time_ind, :]) # number concentratino [L**-1]\n\n            # spherical volume from Chase et al. (2018) [cm**3 / cm**3]\n            vol = (np.pi / 6.) * np.sum(0.6 * ((bin_mid/10.)**3.) * particle_count[time_ind, :] / sample_vol[time_ind, :])\n\n            # number-weighted mean aspect rato\n            asr_nw[time_ind] = np.nansum(aspect_ratio[time_ind, :] * particle_count[time_ind, :]) / np.nansum(particle_count[time_ind, :])\n\n            # Brown & Francis products\n            mass_particle = (0.00294/1.5) * (bin_mid/10.)**1.9 # particle mass [g]\n            mass_bf = mass_particle * particle_count[time_ind, :] # g (binned)\n            cumMass_bf = np.nancumsum(mass_bf)\n            if cumMass_bf[-1]>0.:\n                iwc_bf[time_ind] = 10.**6 * np.nansum(mass_bf / sample_vol[time_ind, :]) # g m^-3\n                z_bf = 1.e12 * (0.174/0.93) * (6./np.pi/0.934)**2 * np.nansum(mass_particle**2*particle_count[time_ind, :]/sample_vol[time_ind, :]) # mm^6 m^-3\n                sol = least_squares(calc_chisquare, x0, method='lm',ftol=1e-9,xtol=1e-9, max_nfev=int(1e6),\\\n                                    args=(Nt,iwc_bf[time_ind],z_bf,bin_mid,bin_width,0.00294/1.5,1.9)) # sove the gamma params using least squares minimziation\n                N0_bf[time_ind] = sol.x[0]; mu_bf[time_ind] = sol.x[1]; lam_bf[time_ind] = sol.x[2]\n                asr_bf[time_ind] = np.sum(aspect_ratio[time_ind, :] * mass_bf / sample_vol[time_ind, :]) / np.sum(mass_bf / sample_vol[time_ind, :]) # mass-weighted aspect ratio\n                rhoe_bf[time_ind] = (iwc_bf[time_ind] / 10.**6) / vol # effective density from Chase et al. (2018) [g cm**-3]\n                rho_bf[time_ind, :] = (mass_bf / particle_count[time_ind, :]) / (np.pi / 6.) / (bin_mid/10.)**3. # rho(D) following Heymsfield et al. (2003) [g cm**-3]\n                dm_bf[time_ind] = 10. * np.sum((bin_mid/10.) * mass_bf / sample_vol[time_ind, :]) / np.sum(mass_bf / sample_vol[time_ind, :]) # mass-weighted mean D from Chase et al. (2020) [mm]\n                if cumMass_bf[0]>=0.5*cumMass_bf[-1]:\n                    dmm_bf[time_ind] = bin_mid[0]\n                else:\n                    dmm_bf[time_ind] = bin_mid[np.where(cumMass_bf>0.5*cumMass_bf[-1])[0][0]-1]\n\n            # Heymsfield (2010) products [https://doi.org/10.1175/2010JAS3507.1]\n            #mass_hy = (0.0061*(bin_mid/10.)**2.05) * particle_count[time_ind, :] # g (binned) H04 definition used in GPM NCAR files\n            mass_particle = 0.00528 * (bin_mid/10.)**2.1 # particle mass [g]\n            mass_hy = mass_particle * particle_count[time_ind, :] # g (binned)\n            cumMass_hy = np.nancumsum(mass_hy)\n            if cumMass_hy[-1]>0.:\n                iwc_hy[time_ind] = 10.**6 * np.nansum(mass_hy / sample_vol[time_ind, :]) # g m^-3\n                z_hy = 1.e12 * (0.174/0.93) * (6./np.pi/0.934)**2 * np.nansum(mass_particle**2*particle_count[time_ind, :]/sample_vol[time_ind, :]) # mm^6 m^-3\n                sol = least_squares(calc_chisquare, x0, method='lm',ftol=1e-9,xtol=1e-9, max_nfev=int(1e6),\\\n                                    args=(Nt,iwc_hy[time_ind],z_hy,bin_mid,bin_width,0.00528,2.1)) # sove the gamma params using least squares minimziation\n                N0_hy[time_ind] = sol.x[0]; mu_hy[time_ind] = sol.x[1]; lam_hy[time_ind] = sol.x[2]\n                asr_hy[time_ind] = np.sum(aspect_ratio[time_ind, :] * mass_hy / sample_vol[time_ind, :]) / np.sum(mass_hy / sample_vol[time_ind, :]) # mass-weighted aspect ratio\n                rhoe_hy[time_ind] = (iwc_hy[time_ind] / 10.**6) / vol # effective density from Chase et al. (2018) [g cm**-3]\n                rho_hy[time_ind, :] = (mass_hy / particle_count[time_ind, :]) / (np.pi / 6.) / (bin_mid/10.)**3. # rho(D) following Heymsfield et al. (2003) [g cm**-3]\n                dm_hy[time_ind] = 10. * np.sum((bin_mid/10.) * mass_hy / sample_vol[time_ind, :]) / np.sum(mass_hy / sample_vol[time_ind, :]) # mass-weighted mean D from Chase et al. (2020) [mm]\n                if cumMass_hy[0]>=0.5*cumMass_hy[-1]:\n                    dmm_hy[time_ind] = bin_mid[0]\n                else:\n                    dmm_hy[time_ind] = bin_mid[np.where(cumMass_hy>0.5*cumMass_hy[-1])[0][0]-1]\n\n\n            # Habit-specific products\n            mass_hab = np.sum(mass_tile * habit_count[time_ind, :, :], axis=1) # g (binned)\n            cumMass_hab = np.nancumsum(mass_hab)\n            if cumMass_hab[-1]>0.:\n                if cumMass_hab[0]>=0.5*cumMass_hab[-1]:\n                    dmm_hab[time_ind] = bin_mid[0]\n                else:\n                    dmm_hab[time_ind] = bin_mid[np.where(cumMass_hab>0.5*cumMass_hab[-1])[0][0]-1]\n            iwc_hab[time_ind] = 10.**6 * np.nansum(mass_hab / sample_vol[time_ind, :]) # g m^-3\n            asr_hab[time_ind] = np.sum(aspect_ratio[time_ind, :] * mass_hab / sample_vol[time_ind, :]) / np.sum(mass_hab / sample_vol[time_ind, :]) # mass-weighted aspect ratio\n            rhoe_hab[time_ind] = (iwc_hab[time_ind] / 10.**6) / vol # effective density from Chase et al. (2018) [g cm**-3]\n            rho_hab[time_ind, :] = (mass_hab / particle_count[time_ind, :]) / (np.pi / 6.) / (bin_mid/10.)**3. # rho(D) following Heymsfield et al. (2003) [g cm**-3]\n            dm_hab[time_ind] = 10. * np.sum((bin_mid/10.) * mass_hab / sample_vol[time_ind, :]) / np.sum(mass_hab / sample_vol[time_ind, :]) # mass-weighted mean D from Chase et al. (2020) [mm]\n\n    mu_bf = np.ma.masked_where(N0_bf==0., mu_bf)\n    mu_hy = np.ma.masked_where(N0_hy==0., mu_hy)\n    lam_bf = np.ma.masked_where(N0_bf==0., lam_bf)\n    lam_hy = np.ma.masked_where(N0_hy==0., lam_hy)\n    N0_bf = np.ma.masked_where(N0_bf==0., N0_bf)\n    N0_hy = np.ma.masked_where(N0_hy==0., N0_hy)\n    dmm_bf = np.ma.masked_where(dmm_bf==0., dmm_bf)\n    dmm_hy = np.ma.masked_where(dmm_hy==0., dmm_hy)\n    dmm_hab = np.ma.masked_where(dmm_hab==0., dmm_hab)\n    dm_bf = np.ma.masked_where(dm_bf==0., dm_bf)\n    dm_hy = np.ma.masked_where(dm_hy==0., dm_hy)\n    dm_hab = np.ma.masked_where(dm_hab==0., dm_hab)\n    asr_nw = np.ma.masked_where(np.ma.getmask(dmm_bf), asr_nw)\n    asr_bf = np.ma.masked_where(np.ma.getmask(dmm_bf), asr_bf)\n    asr_hy = np.ma.masked_where(np.ma.getmask(dmm_hy), asr_hy)\n    asr_hab = np.ma.masked_where(np.ma.getmask(asr_hab), iwc_hab)\n    rhoe_bf = np.ma.masked_where(np.ma.getmask(dmm_bf), rhoe_bf)\n    rhoe_hy = np.ma.masked_where(np.ma.getmask(dmm_hy), rhoe_hy)\n    rhoe_hab = np.ma.masked_where(np.ma.getmask(dmm_hab), rhoe_hab)\n    iwc_bf = np.ma.masked_where(np.ma.getmask(dmm_bf), iwc_bf)\n    iwc_hy = np.ma.masked_where(np.ma.getmask(dmm_hy), iwc_hy)\n    iwc_hab = np.ma.masked_where(np.ma.getmask(dmm_hab), iwc_hab)\n    rho_bf = np.ma.masked_where(rho_bf==0., rho_bf)\n    rho_hy = np.ma.masked_where(rho_hy==0., rho_hy)\n    rho_hab = np.ma.masked_where(rho_hab==0., rho_hab)\n\n    return (N0_bf, N0_hy, mu_bf, mu_hy, lam_bf, lam_hy, iwc_bf, iwc_hy, iwc_hab, asr_nw, asr_bf, asr_hy, asr_hab, dmm_bf, dmm_hy, dmm_hab,\\\n            dm_bf, dm_hy, dm_hab, rho_bf, rho_hy, rho_hab, rhoe_bf, rhoe_hy, rhoe_hab)\n\ndef calc_riming(p3psd, Z, matchedZ_W, matchedZ_Ka, matchedZ_Ku, matchedZ_X, compute_fits=False):\n    x0 = [1.e-1, -1., 5.] # initial guess for N0 [cm**-4], mu, lambda [cm**-1]\n\n    rmass = np.zeros(len(p3psd['time']))\n    rfrac = np.zeros(len(p3psd['time']))\n    a_coeff = np.zeros(len(p3psd['time']))\n    b_coeff = np.zeros(len(p3psd['time']))\n    Nw = np.zeros(len(p3psd['time']))\n    N0 = np.zeros(len(p3psd['time']))\n    mu = np.zeros(len(p3psd['time']))\n    lam = np.zeros(len(p3psd['time']))\n    iwc = np.zeros(len(p3psd['time']))\n    asr = np.zeros(len(p3psd['time']))\n    dm = np.zeros(len(p3psd['time']))\n    dmm = np.zeros(len(p3psd['time']))\n    rho_eff = np.zeros(len(p3psd['time']))\n    dfr_KuKa = np.zeros(len(p3psd['time']))\n    error = np.zeros((len(p3psd['time']), len(p3psd['riming_mass_array'])))\n\n    for i in range(len(p3psd['time'])):\n        # loop through the different possible riming masses\n        for j in range(len(p3psd['riming_mass_array'])):\n            if (matchedZ_W is not None) and (np.ma.is_masked(matchedZ_W[i]) is False) and (np.ma.is_masked(p3psd['dbz_W'][i, :]) is False):\n                error[i, j] = error[i, j] + np.abs(matchedZ_W[i] - p3psd['dbz_W'][i, j])\n            if (matchedZ_Ka is not None) and (np.ma.is_masked(matchedZ_Ka[i]) is False) and (np.ma.is_masked(p3psd['dbz_Ka'][i, :]) is False):\n                error[i, j] = error[i, j] + np.abs(matchedZ_Ka[i] - p3psd['dbz_Ka'][i, j])\n            if (matchedZ_Ku is not None) and (np.ma.is_masked(matchedZ_Ku[i]) is False) and (np.ma.is_masked(p3psd['dbz_Ku'][i, :]) is False):\n                error[i, j] = error[i, j] + np.abs(matchedZ_Ku[i] - p3psd['dbz_Ku'][i, j])\n            if (matchedZ_X is not None) and (np.ma.is_masked(matchedZ_X[i]) is False) and (np.ma.is_masked(p3psd['dbz_X'][i, :]) is False):\n                error[i, j] = error[i, j] + np.abs(matchedZ_X[i] - p3psd['dbz_X'][i, j])\n\n        if np.sum(error[i, :])>0.:\n            rmass[i] = p3psd['riming_mass_array'][np.argmin(error[i, :])]\n            a_coeff[i] = p3psd['a_coeff_array'][np.argmin(error[i, :])]\n            b_coeff[i] = p3psd['b_coeff_array'][np.argmin(error[i, :])]\n\n            if p3psd['count'][i, :].count()==p3psd['count'].shape[1]: # time period is not masked...continue on\n                Nt = 1000.*np.nansum(p3psd['count'][i, :]/p3psd['sv'][i, :]) # concentration [L**-1]\n                mass_particle = a_coeff[i] * (p3psd['bin_mid']/10.)**b_coeff[i] # particle mass [g]\n                mass = mass_particle * p3psd['count'][i, :] # g (binned)\n                cumMass = np.nancumsum(mass)\n                if cumMass[-1]>0.:\n                    # Nw (follows Chase et al. 2021)\n                    # [log10(m**-3 mm**-1)]\n                    D_melt = ((6. * mass_particle) / (np.pi * 0.997))**(1./3.)\n                    Nw[i] = np.log10((1e5) * (4.**4 / 6) * np.nansum(\n                        D_melt**3 * p3psd['ND'][i, :] * p3psd['bin_width'])**5 / np.nansum(\n                        D_melt**4 * p3psd['ND'][i, :] * p3psd['bin_width'])**4)\n\n                    # IWC\n                    iwc[i] = 10.**6 * np.nansum(mass / p3psd['sv'][i, :]) # g m^-3\n\n                    # DFR\n                    dfr_KuKa[i] = p3psd[\n                        'dbz_Ku'][i, np.argmin(error[i, :])] - p3psd[\n                        'dbz_Ka'][i, np.argmin(error[i, :])] # dB\n\n                    # Optionally compute N0, mu, lambda\n                    if compute_fits:\n                        z = 10.**(p3psd['dbz_X'][i,np.argmin(error[i, :])]/10.) # mm^6 m^-3\n\n                        # solve gamma params using least squares minimziation\n                        sol = least_squares(\n                            calc_chisquare, x0, method='lm', ftol=1e-9, xtol=1e-9,\n                            max_nfev=int(1e6), args=(\n                                Nt, iwc[i], z, p3psd['bin_mid'], p3psd['bin_width'],\n                                a_coeff[i], b_coeff[i], np.argmin(error[i, :])))\n                        N0[i] = sol.x[0]; mu[i] = sol.x[1]; lam[i] = sol.x[2]\n\n                    # Mass-weighted mean aspect ratio\n                    asr[i] = np.sum(\n                        p3psd['aspect_ratio'][i, :] * mass / p3psd['sv'][i, :]) / np.sum(\n                        mass / p3psd['sv'][i, :])\n\n                    # Bulk riming fraction (see Eqn 1 of Morrison and Grabowski\n                    # [2010, https://doi.org/10.1175/2010JAS3250.1] for binned version)\n                    rfrac[i] = np.sum(\n                        np.squeeze(Z.rimefrac[0, :, np.argmin(error[i, :])])\n                        * mass / p3psd['sv'][i, :]) / np.nansum(\n                        mass / p3psd['sv'][i, :]) # SUM(rimed mass conc)/iwc\n\n                    # Effective density (follows Chase et al. 2018)\n                    vol = (np.pi / 6.) * np.sum(\n                        0.6 * ((p3psd['bin_mid']/10.)**3.) * p3psd['count'][i, :]\n                        / p3psd['sv'][i, :]) # [cm**3 / cm**3]\n                    rho_eff[i] = (iwc[i] / 10.**6) / vol # [g cm**-3]\n\n                    # Mass-weighted mean diameter (follows Chase et al. 2020)\n                    # M3/M2 if b==2, more generally M(b+1)/Mb\n                    dm[i] = 10. * np.sum(\n                        (p3psd['bin_mid']/10.) * mass / p3psd['sv'][i, :]) / np.sum(\n                        mass / p3psd['sv'][i, :]) # [mm]\n\n                    # Mass-weighted median diameter [mm]\n                    if cumMass[0]>=0.5*cumMass[-1]:\n                        dmm[i] = p3psd['bin_mid'][0]\n                    else:\n                        dmm[i] = p3psd[\n                            'bin_mid'][np.where(cumMass>0.5*cumMass[-1])[0][0]-1]\n\n    p3psd['sclwp'] = np.ma.masked_where(np.sum(error, axis=1)==0., rmass)\n    p3psd['riming_frac'] = np.ma.masked_where(np.sum(error, axis=1)==0., rfrac)\n    p3psd['a_coeff'] = np.ma.masked_where(np.sum(error, axis=1)==0., a_coeff)\n    p3psd['b_coeff'] = np.ma.masked_where(np.sum(error, axis=1)==0., b_coeff)\n    if compute_fits:\n        p3psd['mu_ls'] = np.ma.masked_where(N0==0., mu)\n        p3psd['lambda_ls'] = np.ma.masked_where(N0==0., lam)\n        p3psd['N0_ls'] = np.ma.masked_where(N0==0., N0)\n    p3psd['Nw_ls'] = np.ma.masked_where(np.sum(error, axis=1)==0., Nw)\n    p3psd['iwc_ls'] = np.ma.masked_where(np.sum(error, axis=1)==0., iwc)\n    p3psd['mean_aspect_ratio_ls'] = np.ma.masked_where(np.sum(error, axis=1)==0., asr)\n    p3psd['dm_ls'] = np.ma.masked_where(np.sum(error, axis=1)==0., dm)\n    p3psd['dmm_ls'] = np.ma.masked_where(np.sum(error, axis=1)==0., dmm)\n    p3psd['eff_density_ls'] = np.ma.masked_where(np.sum(error, axis=1)==0., rho_eff)\n    p3psd['dfr_KuKa_ls'] = np.ma.masked_where(np.sum(error, axis=1)==0., dfr_KuKa)\n\n    return p3psd\n\ndef calc_chisquare(\n    x, Nt_obs, iwc_obs, z_obs, bin_mid, bin_width, a_coefficient, b_coefficient,\n    rime_ind=None, exponential=False):\n    '''\n    Compute gamma fit parameters for the PSD.\n    Follows McFarquhar et al. (2015) by finding N0-mu-lambda minimizing first\n    (Nt), third (mass), sixth (reflectivity) moments.\n    Inputs:\n        x: N0, mu, lambda to test on the minimization procedure\n        Nt_obs: Observed number concentration [L^-1]\n        iwc_obs: Observed IWC using an assumed m-D relation [g m**-3]\n        z_obs: Observed Z (following Hogan et al. 2012 definition) using assumed m-D relation [mm**6 m**-3]\n        bin_mid: Midpoints for the binned particle size [mm]\n        bin_width: Bin width for the binned particle size [cm]\n        a_coefficient: Prefactor component to the assumed m-D reltation [cm**-b]\n        b_coefficient: Exponent component to the assumed m-D reltation\n        rime_ind (optional, for LS products only): Riming category index to use for the reflectivity moment\n        exponential: Boolean, True if setting mu=0 for the fit (exponential form)\n    Outputs:\n        chi_square: Chi-square value for the provided N0-mu-lambda configuration\n    '''\n    Dmax = bin_mid / 10. # midpoint in cm\n    dD = bin_width # bin width in cm\n    mass_particle = a_coefficient * Dmax**b_coefficient # binned particle mass [g]\n\n    if exponential: # exponential form with mu=0\n        ND_fit = x[0] * np.exp(-x[2]*Dmax)\n    else: # traditional gamma function with variable mu\n        ND_fit = x[0] * Dmax**x[1] * np.exp(-x[2]*Dmax)\n        \n    Nt_fit = 1000.*np.nansum(ND_fit*dD) # L**-1\n    iwc_fit = 10.**6  * np.nansum(mass_particle*ND_fit*dD) # g m**-3\n    if rime_ind is not None:\n        Z_fit = forward_Z() #initialize class\n        Z_fit.set_PSD(PSD=ND_fit[np.newaxis,:]*10.**8, D=Dmax/100., dD=dD/100., Z_interp=True) # get the PSD in the format to use in the routine (mks units)\n        Z_fit.load_split_L15() # Load the leinonen output\n        Z_fit.fit_sigmas(Z_interp=True) # Fit the backscatter cross-sections\n        Z_fit.calc_Z() # Calculate Z...outputs are Z.Z_x, Z.Z_ku, Z.Z_ka, Z.Z_w for the four radar wavelengths\n        z_fit = 10.**(Z_fit.Z_x[0, rime_ind] / 10.) # mm**6 m**-3\n    else:\n        z_fit = 1.e12 * (0.174/0.93) * (6./np.pi/0.934)**2 * np.nansum(mass_particle**2*ND_fit*dD) # mm**6 m**-3\n\n    csq_Nt = ((Nt_obs-Nt_fit) / np.sqrt(Nt_obs*Nt_fit))**2\n    csq_iwc = ((iwc_obs-iwc_fit) / np.sqrt(iwc_obs*iwc_fit))**2\n    csq_z = ((z_obs-z_fit) / np.sqrt(z_obs*z_fit))**2\n    chi_square = [csq_Nt, csq_iwc, csq_z]\n\n    return chi_square", "meta": {"hexsha": "090b631c56a8b8007055f2f54b77d15bee53fe77", "size": 35286, "ext": "py", "lang": "Python", "max_stars_repo_path": "p3.py", "max_stars_repo_name": "joefinlon/Finlon_et_al_2021_DFR", "max_stars_repo_head_hexsha": "1529df191687a12c8c6e4e1346ee0836260bc56f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "p3.py", "max_issues_repo_name": "joefinlon/Finlon_et_al_2021_DFR", "max_issues_repo_head_hexsha": "1529df191687a12c8c6e4e1346ee0836260bc56f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "p3.py", "max_forks_repo_name": "joefinlon/Finlon_et_al_2021_DFR", "max_forks_repo_head_hexsha": "1529df191687a12c8c6e4e1346ee0836260bc56f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.404040404, "max_line_length": 194, "alphanum_fraction": 0.6079748342, "include": true, "reason": "import numpy,from scipy", "num_tokens": 11794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.19313712305504002}}
{"text": "#!/usr/bin/env python\n# -*-coding:utf8 -*\n\n\"\"\"\nModule for the definition of FunctionalData types.\n\nThis modules is used to defined different types of functional data. The\ndifferent types are: Univariate Functional Data, Irregular Functional data and\nMultivariate Functional Data.\n\"\"\"\nimport numpy as np\nimport pygam\n\nfrom abc import ABC, abstractmethod\nfrom collections import UserList\n\nfrom sklearn.metrics import pairwise_distances\n\nfrom ..preprocessing.smoothing.bandwidth import Bandwidth\nfrom ..preprocessing.smoothing.local_polynomial import LocalPolynomial\nfrom ..preprocessing.smoothing.smoothing_splines import SmoothingSpline\nfrom ..misc.utils import get_dict_dimension_, get_obs_shape_\nfrom ..misc.utils import integration_weights_, outer_\nfrom ..misc.utils import range_standardization_\n\n\n###############################################################################\n# Checkers for parameters\n\ndef _check_dict_array(argv_dict, argv_array):\n    \"\"\"Raise an error in case of dimension conflicts between the arguments.\n\n    An error is raised when `argv_dict` (a dictionary) and `argv_array`\n    (a np.ndarray) do not have coherent common dimensions. The first dimension\n    of `arg_array` is assumed to represented the number of observation.\n    \"\"\"\n    dim_dict = get_dict_dimension_(argv_dict)\n    dim_array = argv_array.shape[1:]\n    if dim_dict != dim_array:\n        raise ValueError(f\"{argv_dict} and {argv_array} do not have coherent\"\n                         \" dimension.\")\n\n\ndef _check_dict_dict(argv1, argv2):\n    \"\"\"Raise an error in case of dimension conflicts between the arguments.\n\n    An error is raised when `argv1` (a nested dictonary) and `argv2` (a\n    dictionary) do not have coherent common dimensions.\n    \"\"\"\n    has_obs_shape = [obs.shape == get_obs_shape_(argv1, idx)\n                     for idx, obs in argv2.items()]\n    if not np.all(has_obs_shape):\n        raise ValueError(f\"{argv1} and {argv2} do not\"\n                         \" have coherent dimension.\")\n\n\ndef _check_type(argv, category):\n    \"\"\"Raise an error if `argv` is not of type category.\"\"\"\n    if not isinstance(argv, category):\n        raise TypeError(f\"Argument must be FunctionalData, not\"\n                        f\" {type(argv).__name__}\")\n\n\ndef _check_dict_type(argv, category):\n    \"\"\"Raise an error if all elements of `argv` are not of type `category`.\"\"\"\n    is_cat = [isinstance(obj, category) for obj in argv.values()]\n    if not np.all(is_cat):\n        raise TypeError(f\"Argument values must be {category.__name__}\")\n\n\ndef _check_dict_len(argv):\n    \"\"\"Raise an error if all elements of `argv` do not have equal length.\"\"\"\n    lengths = [len(obj) for obj in argv.values()]\n    if len(set(lengths)) > 1:\n        raise ValueError(\"The number of observations is different across the\"\n                         \" dimensions.\"\"\")\n\n\ndef _check_same_type(argv1, argv2):\n    \"\"\"Raise an error if `argv1` and `argv2` have different type.\"\"\"\n    if not isinstance(argv2, type(argv1)):\n        raise TypeError(f\"{argv1} and {argv2} do not have the same type.\")\n\n\ndef _check_same_nobs(*argv):\n    \"\"\"Raise an arror if elements in argv have different number of obs.\"\"\"\n    n_obs = set(obj.n_obs for obj in argv)\n    if len(n_obs) > 1:\n        raise ValueError(\"Elements do not have the same number\"\n                         \" of observations.\")\n\n\ndef _check_same_ndim(argv1, argv2):\n    \"\"\"Raise an error if `argv1` and `argv2` have different number of dim.\"\"\"\n    if argv1.n_dim != argv2.n_dim:\n        raise ValueError(f\"{argv1} and {argv2} do not have the same number\"\n                         \" of dimensions.\")\n\n\ndef _check_argvals_equality_dense(argv1, argv2):\n    \"\"\"Raise an error if `argv1` and `argv2` are not equal.\"\"\"\n    argvs_equal = all(np.array_equal(argv1[key], argv2[key]) for key in argv1)\n    if not argvs_equal:\n        raise ValueError(f\"{argv1} and {argv2} do not have the same sampling\"\n                         \" points.\")\n\n\ndef _check_argvals_equality_irregular(argv1, argv2):\n    \"\"\"Raise an error if `argv1` and `argv2` are not equal.\"\"\"\n    temp = []\n    for points1, points2 in zip(argv1.values(), argv2.values()):\n        temp.append(all(np.array_equal(points1[key], points2[key])\n                        for key in points1))\n\n    argvs_equal = all(temp)\n    if not argvs_equal:\n        raise ValueError(f\"{argv1} and {argv2} do not have the same sampling\"\n                         \" points.\")\n\n\n###############################################################################\n# Class FunctionalData\n\n\nclass FunctionalData(ABC):\n    \"\"\"Metaclass for the definition of diverse functional data objects.\n\n    Parameters\n    ----------\n    argvals: list\n    values: list\n    category: str, {'univariate', 'irregular', 'multivariate'}\n\n    \"\"\"\n\n    @staticmethod\n    @abstractmethod\n    def _check_argvals(argvals):\n        _check_type(argvals, dict)\n\n    @staticmethod\n    @abstractmethod\n    def _check_values(values):\n        pass\n\n    @staticmethod\n    @abstractmethod\n    def _check_argvals_values(argvals, values):\n        pass\n\n    @staticmethod\n    @abstractmethod\n    def _perform_computation(fdata1, fdata2, func):\n        pass\n\n    def __init__(self, argvals, values, category):\n        \"\"\"Initialize FunctionalData object.\"\"\"\n        super().__init__()\n        self.argvals = argvals\n        self.values = values\n        self.category = category\n\n    def __repr__(self):\n        \"\"\"Override print function.\"\"\"\n        return (f\"{self.category.capitalize()} functional data object with\"\n                f\" {self.n_obs} observations on a {self.n_dim}-dimensional\"\n                \" support.\")\n\n    @abstractmethod\n    def __getitem__(self, index):\n        \"\"\"Override getitem function, called when self[index].\"\"\"\n        pass\n\n    def __add__(self, obj):\n        \"\"\"Override add function.\"\"\"\n        return self._perform_computation(self, obj, np.add)\n\n    def __sub__(self, obj):\n        \"\"\"Override sub function.\"\"\"\n        return self._perform_computation(self, obj, np.subtract)\n\n    def __mul__(self, obj):\n        \"\"\"Overrude mul function.\"\"\"\n        return self._perform_computation(self, obj, np.multiply)\n\n    def __rmul__(self, obj):\n        \"\"\"Override rmul function.\"\"\"\n        return self * obj\n\n    def __truediv__(self, obj):\n        \"\"\"Override truediv function.\"\"\"\n        return self._perform_computation(self, obj, np.divide)\n\n    def __floordiv__(self, obj):\n        \"\"\"Override floordiv function.\"\"\"\n        return self / obj\n\n    @property\n    def argvals(self):\n        \"\"\"Getter for argvals.\"\"\"\n        return self._argvals\n\n    @argvals.setter\n    def argvals(self, new_argvals):\n        self._check_argvals(new_argvals)\n        if hasattr(self, 'values'):\n            self._check_argvals_values(new_argvals, self.values)\n        self._argvals = new_argvals\n\n    @property\n    def argvals_stand(self):\n        \"\"\"Getter for argvals_stand.\"\"\"\n        return self._argvals_stand\n\n    @argvals_stand.setter\n    def argvals_stand(self, new_argvals_stand):\n        self._argvals_stand = new_argvals_stand\n\n    @property\n    def values(self):\n        \"\"\"Getter for values.\"\"\"\n        return self._values\n\n    @values.setter\n    def values(self, new_values):\n        self._check_values(new_values)\n        if hasattr(self, 'argvals'):\n            self._check_argvals_values(self.argvals, new_values)\n        self._values = new_values\n\n    @property\n    def category(self):\n        \"\"\"Getter for category.\"\"\"\n        return self._category\n\n    @category.setter\n    def category(self, new_category):\n        self._category = new_category\n\n    @property\n    def n_obs(self):\n        \"\"\"Get the number of observations of the functional data.\n\n        Returns\n        -------\n        n_obs: int\n            Number of observations within the functional data.\n\n        \"\"\"\n        return len(self.values)\n\n    @property\n    @abstractmethod\n    def range_obs(self):\n        \"\"\"Get the range of the observations of the object.\"\"\"\n        pass\n\n    @property\n    def n_dim(self):\n        \"\"\"Get the number of input dimension of the functional data.\n\n        Returns\n        -------\n        n_dim: int\n            Number of input dimension with the functional data.\n\n        \"\"\"\n        return len(self.argvals)\n\n    @property\n    @abstractmethod\n    def n_points(self):\n        \"\"\"Get the mean number of sampling points.\"\"\"\n        pass\n\n    @property\n    @abstractmethod\n    def range_dim(self):\n        \"\"\"Range of the `argvals` for each of the dimension.\"\"\"\n        pass\n\n    @property\n    @abstractmethod\n    def shape(self):\n        \"\"\"Shape of the data for each dimension.\"\"\"\n        pass\n\n    @abstractmethod\n    def is_compatible(self, fdata):\n        \"\"\"Check if `fdata` is compatible with `self`.\"\"\"\n        _check_same_type(self, fdata)\n        _check_same_nobs(self, fdata)\n        _check_same_ndim(self, fdata)\n\n    @abstractmethod\n    def mean(self, smooth=None, **kwargs):\n        \"\"\"Compute an estimate of the mean.\"\"\"\n        pass\n\n    @abstractmethod\n    def covariance(self, mean=None, smooth=None, **kwargs):\n        \"\"\"Compute an estimate of the covariance.\"\"\"\n        pass\n\n    @abstractmethod\n    def smooth(self, points, neighborhood, points_estim=None, degree=0,\n               kernel=\"epanechnikov\", bandwidth=None):\n        \"\"\"Smooth the data.\"\"\"\n        pass\n\n\n###############################################################################\n# Class DenseFunctionalData\n\nclass DenseFunctionalData(FunctionalData):\n    r\"\"\"A class for defining Dense Functional Data.\n\n    A class used to define dense functional data. We denote by :math:`n`, the\n    number of observations and by :math:`p`, the number of input dimensions.\n    Here, we are in the case of univariate functional data, and so the output\n    dimension will be :math:`\\mathbb{R}`.\n\n    Parameters\n    ----------\n    argvals: dict\n        The sampling points of the functional data. Each entry of the\n        dictionary represents an input dimension. The shape of the :math:`j`th\n        dimension is :math:`(m_j,)` for :math:`0 \\leq j \\leq p`.\n    values: np.ndarray\n        The values of the functional data. The shape of the array is\n        :math:`(n, m_1, \\dots, m_p)`.\n\n    Examples\n    --------\n    >>> argvals = {'input_dim_0': np.array([1, 2, 3, 4]),\n                   'input_dim_1': np.array([5, 6, 7])}\n\n    >>> values = np.array([[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]],\n                   [[5, 6, 7], [5, 6, 7], [5, 6, 7], [5, 6, 7]],\n                   [[3, 4, 5], [3, 4, 5], [3, 4, 5], [3, 4, 5]],\n                   [[3, 4, 5], [3, 4, 5], [3, 4, 5], [3, 4, 5]],\n                   [[3, 4, 5], [3, 4, 5], [3, 4, 5], [3, 4, 5]]])\n\n    >>> DenseFunctionalData(argvals, values)\n\n    \"\"\"\n\n    @staticmethod\n    def _check_argvals(argvals):\n        \"\"\"Check the user provided `argvals`.\"\"\"\n        FunctionalData._check_argvals(argvals)\n        _check_dict_type(argvals, np.ndarray)\n\n    @staticmethod\n    def _check_values(values):\n        \"\"\"Check the use provided `values`.\"\"\"\n        _check_type(values, np.ndarray)\n\n    @staticmethod\n    def _check_argvals_values(argvals, values):\n        \"\"\"Check the compatibility of argvals and values.\"\"\"\n        _check_dict_array(argvals, values)\n\n    @staticmethod\n    def _perform_computation(fdata1, fdata2, func):\n        \"\"\"Perform computation defined by `func`.\"\"\"\n        if fdata1.is_compatible(fdata2):\n            new_values = func(fdata1.values, fdata2.values)\n        return DenseFunctionalData(fdata1.argvals, new_values)\n\n    def __init__(self, argvals, values):\n        \"\"\"Initialize UnivariateFunctionalData object.\"\"\"\n        super().__init__(argvals, values, 'univariate')\n\n    def __getitem__(self, index):\n        \"\"\"Overrride getitem function, called when self[index].\n\n        Parameters\n        ----------\n        index: int\n            The observation(s) of the object to retrive.\n\n        Returns\n        -------\n        data: DenseFunctionalData object\n            The selected observation(s) as DenseFunctionalData object.\n\n        \"\"\"\n        argvals = self.argvals\n        values = self.values[index]\n\n        if len(argvals) == len(values.shape):\n            values = values[np.newaxis]\n        return DenseFunctionalData(argvals, values)\n\n    @property\n    def argvals(self):\n        \"\"\"Getter for argvals.\"\"\"\n        return super().argvals\n\n    @argvals.setter\n    def argvals(self, new_argvals):\n        super(DenseFunctionalData, self.__class__).\\\n            argvals.fset(self, new_argvals)\n\n        argvals_stand = {}\n        for dim, points in new_argvals.items():\n            argvals_stand[dim] = range_standardization_(points)\n        self.argvals_stand = argvals_stand\n\n    @property\n    def range_obs(self):\n        \"\"\"Get the range of the observations of the object.\n\n        Returns\n        -------\n        min, max: tuple\n            Tuple containing the mimimum and maximum values taken by all the\n            observations for the object.\n\n        \"\"\"\n        return np.min(self.values), np.max(self.values)\n\n    @property\n    def n_points(self):\n        \"\"\"Get the mean number of sampling points.\n\n        Returns\n        -------\n        n_points: dict\n            A dictionary with the same shape than argavls with the number of\n            sampling points along each axis.\n\n        \"\"\"\n        return {i: len(points) for i, points in self.argvals.items()}\n\n    @property\n    def range_dim(self):\n        \"\"\"Get the range of the `argvals` for each of the dimension.\n\n        Returns\n        -------\n        ranges: dict\n            Dictionary containing the range of the argvals for each of the\n            input dimension.\n\n        \"\"\"\n        return {idx: (min(argval), max(argval))\n                for idx, argval in self.argvals.items()}\n\n    @property\n    def shape(self):\n        r\"\"\"Get the shape of the data for each dimension.\n\n        Returns\n        -------\n        shape: dict\n            Dictionary containing the number of points for each of the\n            dimension. It corresponds to :math:`m_j` for\n            :math:`0 \\leq j \\leq p`.\n\n        \"\"\"\n        return {idx: len(dim) for idx, dim in self.argvals.items()}\n\n    def as_irregular(self):\n        \"\"\"Convert `self` from Dense to Irregular functional data.\n\n        Coerce a DenseFunctionalData object into an IrregularFunctionalData\n        object.\n\n        Returns\n        -------\n        obj: IrregularFunctionalData\n            An object of the class IrregularFunctionalData\n\n        \"\"\"\n        new_argvals = dict.fromkeys(self.argvals.keys(), {})\n        for dim in new_argvals.keys():\n            temp = {}\n            for idx in range(self.n_obs):\n                temp[idx] = self.argvals[dim]\n            new_argvals[dim] = temp\n\n        new_values = {}\n        for idx in range(self.n_obs):\n            new_values[idx] = self.values[idx]\n\n        return IrregularFunctionalData(new_argvals, new_values)\n\n    def is_compatible(self, fdata):\n        \"\"\"Check if `fdata` is compatible with `self`.\n\n        Two DenseFunctionalData object are said to be compatible if they\n        have the same number of observations and dimensions. Moreover, they\n        must have (strictly) the same sampling points.\n\n        Parameters\n        ----------\n        fdata: DenseFunctionalData object\n            The object to compare with `self`.\n\n        Returns\n        -------\n        True\n            If the objects are compatible.\n\n        \"\"\"\n        super().is_compatible(fdata)\n        _check_argvals_equality_dense(self.argvals, fdata.argvals)\n        return True\n\n    def mean(self, smooth=None, **kwargs):\n        \"\"\"Compute an estimate of the mean.\n\n        Parameters\n        ----------\n        smooth: str, default=None\n            Name of the smoothing method to use. Currently, not implemented.\n\n        Keyword Args\n        ------------\n        kernel_name: str, default='epanechnikov'\n            Name of the kernel used for local polynomial smoothing.\n        degree: int, default=1\n            Degree used for local polynomial smoothing.\n        bandwidth: float, default=1\n            Bandwidth used for local polynomial smoothing.\n        n_basis: int, default=10\n            Number of splines basis used for GAM smoothing.\n\n        Returns\n        -------\n        obj: DenseFunctionalData object\n            An estimate of the mean as a DenseFunctionalData object with the\n            same argvals as `self` and one observation.\n\n        \"\"\"\n        mean_estim = self.values.mean(axis=0)\n\n        if smooth is not None:\n            argvals = self.argvals['input_dim_0']\n            if self.n_dim > 1:\n                raise ValueError('Only one dimensional data can be smoothed.')\n            if smooth == 'LocalLinear':\n                p = self.n_points['input_dim_0']\n                points = kwargs.get('points', 0.5)\n                neigh = kwargs.get('neighborhood',\n                                   np.int(p * np.exp(-(np.log(np.log(p)))**2)))\n                data_smooth = self.smooth(points=points,\n                                          neighborhood=neigh)\n                mean_estim = data_smooth.values.mean(axis=0)\n            elif smooth == 'GAM':\n                n_basis = kwargs.get('n_basis', 10)\n                argvals = self.argvals['input_dim_0']\n                mean_estim = pygam.LinearGAM(pygam.s(0, n_splines=n_basis)).\\\n                    fit(argvals, mean_estim).\\\n                    predict(argvals)\n            elif smooth == 'SmoothingSpline':\n                ss = SmoothingSpline()\n                mean_estim = ss.fit_predict(argvals, mean_estim)\n            else:\n                raise NotImplementedError('Smoothing method not implemented.')\n        return DenseFunctionalData(self.argvals, mean_estim[np.newaxis])\n\n    def covariance(self, mean=None, smooth=None, **kwargs):\n        \"\"\"Compute an estimate of the covariance.\n\n        Parameters\n        ----------\n        smooth: str, default=None\n            Name of the smoothing method to use. Currently, not implemented.\n        mean: DenseFunctionalData, default=None\n            An estimate of the mean of self. If None, an estimate is computed.\n\n        Returns\n        -------\n        obj: DenseFunctionalData object\n            An estimate of the covariance as a two-dimensional\n            DenseFunctionalData object with same argvals as `self`.\n\n        Keyword Args\n        ------------\n        kernel_name: str, default='epanechnikov'\n            Name of the kernel used for local polynomial smoothing.\n        degree: int, default=1\n            Degree used for local polynomial smoothing.\n        bandwidth: float, default=1\n            Bandwidth used for local polynomial smoothing.\n        n_basis: int, default=10\n            Number of splines basis used for GAM smoothing.\n\n        References\n        ----------\n        * Yao, Müller and Wang (2005), Functional Data Analysis for Sparse\n        Longitudinal Data,\n        Journal of the American Statistical Association, Vol. 100, No. 470\n        * Staniswalis, J. G., and Lee, J. J. (1998), “Nonparametric Regression\n        Analysis of Longitudinal Data,” Journal of the American Statistical\n        Association, 93, 1403–1418.\n\n        \"\"\"\n        if self.n_dim > 1:\n            raise ValueError('Only one dimensional functional data are'\n                             ' supported')\n\n        p = self.n_points['input_dim_0']\n        argvals = self.argvals['input_dim_0']\n        if mean is None:\n            mean = self.mean(smooth)\n        data = self.values - mean.values\n        cov = np.dot(data.T, data) / (self.n_obs - 1)\n        cov_diag = np.copy(np.diag(cov))\n\n        if smooth is not None:\n            # Remove covariance diagonale because of measurement errors.\n            np.fill_diagonal(cov, None)\n            cov = cov[~np.isnan(cov)]\n\n            # Define train vector\n            train_ = np.vstack((\n                np.repeat(argvals, repeats=len(argvals)),\n                np.tile(argvals, reps=len(argvals)))\n            )\n\n            train = train_[:, train_[0, :] != train_[1, :]]\n\n            if smooth == 'LocalLinear':\n                points = kwargs.get('points', 0.5)\n                neigh = kwargs.get('neighborhood',\n                                   np.int(p * np.exp(-(np.log(np.log(p)))**2)))\n                data_smooth = self.smooth(points=points,\n                                          neighborhood=neigh)\n                data = data_smooth.values - mean.values\n                cov = np.dot(data.T, data) / (self.n_obs - 1)\n            elif smooth == 'GAM':\n                n_basis = kwargs.get('n_basis', 10)\n\n                cov = pygam.LinearGAM(pygam.te(0, 1, n_splines=n_basis)).\\\n                    fit(np.transpose(train), cov).\\\n                    predict(np.transpose(train_)).\\\n                    reshape((len(argvals), len(argvals)))\n            else:\n                raise NotImplementedError('Smoothing method not implemented.')\n\n        # Ensure the covariance is symmetric.\n        cov = (cov + cov.T) / 2\n\n        # Smoothing the diagonal of the covariance (Yao, Müller and Wang, 2005)\n        lp = LocalPolynomial(kernel_name=kwargs.get('kernel_name', 'gaussian'),\n                             bandwidth=kwargs.get('bandwidth', 1),\n                             degree=kwargs.get('degree', 1))\n        var_hat = lp.fit_predict(argvals, cov_diag, argvals)\n        # Estimate noise variance (Staniswalis and Lee, 1998)\n        ll = argvals[len(argvals) - 1] - argvals[0]\n        lower = np.sum(~(argvals >= (argvals[0] + 0.25 * ll)))\n        upper = np.sum((argvals <= (argvals[len(argvals) - 1] - 0.25 * ll)))\n        weights = integration_weights_(argvals[lower:upper], method='trapz')\n        nume = np.dot(weights, (var_hat - cov_diag)[lower:upper])\n        self.var_noise = np.maximum(nume / argvals[upper] - argvals[lower], 0)\n\n        new_argvals = {'input_dim_0': argvals, 'input_dim_1': argvals}\n        return DenseFunctionalData(new_argvals, cov[np.newaxis])\n\n    def smooth(self, points, neighborhood, points_estim=None, degree=0,\n               kernel=\"epanechnikov\", bandwidth=None):\n        \"\"\"Smooth the data.\n\n        Notes\n        -----\n        Only, one dimensional IrregularFunctionalData can be smoothed.\n\n        Parameters\n        ----------\n        points: np.array\n            Points at which the Bandwidth is estimated.\n        neighborhood: np.array\n            Neighborhood considered for each each points. Should have the same\n            shape than points.\n        points_estim: np.array, default=None\n            Points at which the curves are estimated. The default is None,\n            meaning we use the argvals as estimation points.\n        degree: int, default=2\n            Degree for the local polynomial smoothing.\n        kernel: str, default='epanechnikov'\n            The name of the kernel to use.\n        bandwidth: Bandwidth, default=None\n            An instance of Bandwidth for the smoothing.\n\n        Returns\n        -------\n        obj: IrregularFunctionalData\n            A smoothed version of the data.\n\n        \"\"\"\n        if self.n_dim != 1:\n            raise NotImplementedError('Only one dimensional data can be'\n                                      ' smoothed.')\n\n        data = self.as_irregular()\n        data_smooth = data.smooth(points, neighborhood,\n                                  points_estim=points_estim,\n                                  degree=degree,\n                                  kernel=kernel,\n                                  bandwidth=bandwidth)\n        return data_smooth.as_dense()\n\n    def pairwise_distance(self, metric='euclidean'):\n        \"\"\"Compute the pairwise distance between the data.\n\n        Parameters\n        ----------\n        metric: str, default='euclidean'\n            The metric to use when calculating distance between instances in a\n            functional data object.\n\n        Returns\n        -------\n        D: np.ndarray, shape=(n_obs, n_obs)\n            A distance matrix D such that D_{i, j} is the distance between the\n            ith and jth observations of the functional data object,\n\n        \"\"\"\n        if self.n_dim > 1:\n            raise NotImplementedError('The distance computation is not'\n                                      ' implemented for data with dimension'\n                                      ' greater than 1.')\n        return pairwise_distances(self.values, metric=metric)\n\n    def concatenate(self, data):\n        \"\"\"Concatenate two DenseFunctionalData.\n\n        Parameters\n        ----------\n        data: DenseFunctionalData\n            The data to concatenate with self.\n\n        Returns\n        -------\n        res: DenseFunctionalData\n            The concatenation of self and data.\n\n        \"\"\"\n        return concatenate_(self, data)\n\n\n###############################################################################\n# Class IrregularFunctionalData\n\nclass IrregularFunctionalData(FunctionalData):\n    r\"\"\"A class for defining Irregular Functional Data.\n\n    Parameters\n    ----------\n    argvals: dict\n        The sampling points of the functional data. Each entry of the\n        dictionary represents an input dimension. Then, each dimension is a\n        dictionary where entries are the different observations. So, the\n        observation :math:`i` for the dimension :math:`j` is a `np.ndarray`\n        with shape :math:`(m^i_j,)` for :math:`0 \\leq i \\leq n` and\n        :math:`0 \\leq j \\leq p`.\n    values: dict\n        The values of the functional data. Each entry of the dictionary is an\n        observation of the process. And, an observation is represented by a\n        `np.ndarray` of shape :math:`(n, m_1, \\dots, m_p)`. It should not\n        contain any missing values.\n\n    Examples\n    --------\n    >>> argvals = {'input_dim_0': {\n                        0: np.array([1, 2, 3, 4]),\n                        1: np.array([2, 4])},\n                   'input_dim_1': {\n                        0: np.array([5, 6, 7]),\n                        1: np.array([1, 2, 3])}\n                  }\n\n    >>> values = {0: np.array([[1, 2, 3], [4, 1, 2], [3, 4, 1], [2, 3, 4]]),\n                  1: np.array([[1, 2, 3], [1, 2, 3]])}\n\n    >>> IrregularFunctionalData(argvals, values)\n\n    \"\"\"\n\n    @staticmethod\n    def _check_argvals(argvals):\n        \"\"\"Check the user provided `argvals`.\"\"\"\n        FunctionalData._check_argvals(argvals)\n        for obj in argvals.values():\n            _check_type(obj, dict)\n            _check_dict_type(obj, np.ndarray)\n        _check_dict_len(argvals)\n\n    @staticmethod\n    def _check_values(values):\n        \"\"\"Check the user provided `values`.\"\"\"\n        _check_type(values, dict)\n        for obj in values.values():\n            _check_type(obj, np.ndarray)\n\n    @staticmethod\n    def _check_argvals_values(argvals, values):\n        \"\"\"Check the compatibility of argvals and values.\"\"\"\n        _check_dict_dict(argvals, values)\n\n    @staticmethod\n    def _perform_computation(fdata1, fdata2, func):\n        \"\"\"Perform computation defined by `func`.\"\"\"\n        if fdata1.is_compatible(fdata2):\n            new_values = {}\n            for (idx, obs1), (_, obs2) in zip(fdata1.values.items(),\n                                              fdata2.values.items()):\n                new_values[idx] = func(obs1, obs2)\n        return IrregularFunctionalData(fdata1.argvals, new_values)\n\n    def __init__(self, argvals, values):\n        \"\"\"Initialize IrregularFunctionalData object.\"\"\"\n        super().__init__(argvals, values, 'irregular')\n\n    def __getitem__(self, index):\n        \"\"\"Overrride getitem function, called when self[index].\n\n        Parameters\n        ----------\n        index: int\n            The observation(s) of the object to retrive.\n\n        Returns\n        -------\n        data: IrregularFunctionalData object\n            The selected observation(s) as IrregularFunctionalData object.\n\n        \"\"\"\n        if isinstance(index, slice):\n            indices = index.indices(self.n_obs)\n\n            argvals = {}\n            for idx, dim in self.argvals.items():\n                argvals[idx] = {i: dim.get(i) for i in range(*indices)}\n            values = {i: self.values.get(i) for i in range(*indices)}\n        else:\n            argvals = {idx: {index: points.get(index)}\n                       for idx, points in self.argvals.items()}\n            values = {index: self.values.get(index)}\n        return IrregularFunctionalData(argvals, values)\n\n    @property\n    def argvals(self):\n        \"\"\"Getter for argvals.\"\"\"\n        return super().argvals\n\n    @argvals.setter\n    def argvals(self, new_argvals):\n        super(IrregularFunctionalData, self.__class__).\\\n            argvals.fset(self, new_argvals)\n\n        points = self.gather_points()\n        argvals_stand = {}\n        for dim, obss in new_argvals.items():\n            max_x, min_x = np.max(points[dim]), np.min(points[dim])\n\n            argvals_stand[dim] = {}\n            for obs, point in obss.items():\n                argvals_stand[dim][obs] = range_standardization_(point,\n                                                                 max_x, min_x)\n        self.argvals_stand = argvals_stand\n\n    @property\n    def range_obs(self):\n        \"\"\"Get the range of the observations of the object.\n\n        Returns\n        -------\n        min, max: tuple\n            Tuple containing the mimimum and maximum values taken by all the\n            observations for the object.\n\n        \"\"\"\n        ranges = [(np.min(obs), np.max(obs)) for obs in self.values.values()]\n        return min(min(ranges)), max(max(ranges))\n\n    @property\n    def n_points(self):\n        \"\"\"Get the mean number of sampling points.\n\n        Returns\n        -------\n        n_points: dict\n            A dictionary with the same shape than argavls with the number of\n            sampling points along each axis.\n\n        \"\"\"\n        n_points = {}\n        for i, points in self.argvals.items():\n            n_points[i] = np.mean([len(p) for p in points.values()])\n        return n_points\n\n    @property\n    def range_dim(self):\n        \"\"\"Get the range of the `argvals` for each of the dimension.\n\n        Returns\n        -------\n        ranges: dict\n            Dictionary containing the range of the argvals for each of the\n            input dimension.\n\n        \"\"\"\n        ranges = {idx: list(argval.values())\n                  for idx, argval in self.argvals.items()}\n        return {idx: (min(map(min, dim)), max(map(max, dim)))\n                for idx, dim in ranges.items()}\n\n    @property\n    def shape(self):\n        r\"\"\"Get the shape of the data for each dimension.\n\n        Returns\n        -------\n        shape: dict\n            Dictionary containing the number of points for each of the\n            dimension. It corresponds to :math:`m_j` for\n            :math:`0 \\leq j \\leq p`.\n\n        \"\"\"\n        return {idx: len(dim) for idx, dim in self.gather_points().items()}\n\n    def gather_points(self):\n        \"\"\"Gather all the `argvals` for each of the dimensions separetely.\n\n        Returns\n        -------\n        argvals: dict\n            Dictionary containing all the unique observations points for each\n            of the input dimension.\n\n        \"\"\"\n        return {idx: np.unique(np.hstack(list(dim.values())))\n                for idx, dim in self.argvals.items()}\n\n    def as_dense(self):\n        \"\"\"Convert `self` from Irregular to Dense functional data.\n\n        Coerce an IrregularFunctionalData object into a DenseFunctionalData\n        object.\n\n        Note\n        ----\n        We coerce an IrregularFunctionalData object into a DenseFunctionalData\n        object by gathering all the sampling points from the different\n        dimension into one, and set the value to `np.nan` for the not observed\n        points.\n\n        Returns\n        -------\n        obj: DenseFunctionalData\n            An object of the class DenseFunctionalData\n\n        \"\"\"\n        new_argvals = self.gather_points()\n        new_values = np.full((self.n_obs,) + tuple(self.shape.values()),\n                             np.nan)\n\n        # Create the index definition domain for each of the observation\n        index_obs = {}\n        for obs in self.values.keys():\n            index_obs_dim = []\n            for dim in new_argvals.keys():\n                _, idx, _ = np.intersect1d(new_argvals[dim],\n                                           self.argvals[dim][obs],\n                                           return_indices=True)\n                index_obs_dim.append(idx)\n            index_obs[obs] = index_obs_dim\n\n        # Create mask arrays\n        mask_obs = {obs: np.full(tuple(self.shape.values()), False)\n                    for obs in self.values.keys()}\n        for obs in self.values.keys():\n            mask_obs[obs][tuple(np.meshgrid(*index_obs[obs]))] = True\n\n        # Assign values\n        for obs in self.values.keys():\n            new_values[obs][mask_obs[obs]] = self.values[obs].flatten()\n\n        return DenseFunctionalData(new_argvals, new_values)\n\n    def is_compatible(self, fdata):\n        \"\"\"Check if `fdata` is compatible with `self`.\n\n        Two IrregularFunctionalData object are said to be compatible if they\n        have the same number of observations and dimensions. Moreover, they\n        must have (strictly) the same sampling points.\n\n        Parameters\n        ----------\n        fdata : IrregularFunctionalData object\n            The object to compare with `self`.\n\n        Returns\n        -------\n        True\n            If the objects are compatible.\n\n        \"\"\"\n        super().is_compatible(fdata)\n        _check_argvals_equality_irregular(self.argvals, fdata.argvals)\n        return True\n\n    def mean(self, smooth=None, **kwargs):\n        \"\"\"Compute an estimate of the mean.\n\n        Parameters\n        ----------\n        smooth: str, default=None\n            Name of the smoothing method. Currently, not implemented.\n\n        Returns\n        -------\n        obj: DenseFunctionalData object\n            An estimate of the mean as a DenseFunctionalData object with a\n            concatenation of the self.argvals as argvals and one observation.\n\n        \"\"\"\n        dense_self = self.as_dense()\n        mean_estim = np.nanmean(dense_self.values, axis=0, keepdims=True)\n        return DenseFunctionalData(dense_self.argvals, mean_estim)\n\n    def covariance(self, mean=None, smooth=None, **kwargs):\n        \"\"\"Compute an estimate of the covariance.\"\"\"\n        pass\n\n    def smooth(self, points, neighborhood, points_estim=None, degree=0,\n               kernel=\"epanechnikov\", bandwidth=None):\n        \"\"\"Smooth the data.\n\n        Notes\n        -----\n        Only, one dimensional IrregularFunctionalData can be smoothed.\n\n        Parameters\n        ----------\n        points: np.array\n            Points at which the Bandwidth is estimated.\n        neighborhood: np.array\n            Neighborhood considered for each each points. Should have the same\n            shape than points.\n        points_estim: np.array, default=None\n            Points at which the curves are estimated. The default is None,\n            meaning we use the argvals as estimation points.\n        degree: int, default=0\n            Degree for the local polynomial smoothing.\n        kernel: str, default='epanechnikov'\n            The name of the kernel to use.\n        bandwidth: Bandwidth, default=None\n            An instance of Bandwidth for the smoothing.\n\n        Returns\n        -------\n        obj: IrregularFunctionalData\n            A smoothed version of the data.\n\n        \"\"\"\n        if self.n_dim > 1:\n            raise NotImplementedError('Currently, only one dimensional data'\n                                      ' can be smoothed.')\n\n        if bandwidth is None:\n            band_obj = Bandwidth(points=points, neighborhood=neighborhood)\n            bandwidth = band_obj(self).bandwidths\n\n        argvals = self.argvals['input_dim_0'].values()\n        values = self.values.values()\n        smooth_argvals, smooth_values = {}, {}\n        for i, (arg, val, b) in enumerate(zip(argvals, values, bandwidth)):\n            if points_estim is None:\n                points_estim = arg\n\n            lp = LocalPolynomial(kernel_name=kernel,\n                                 bandwidth=b,\n                                 degree=degree)\n            pred = lp.fit_predict(arg, val, points_estim)\n            smooth_argvals[i] = points_estim\n            smooth_values[i] = pred\n        return IrregularFunctionalData({'input_dim_0': smooth_argvals},\n                                       smooth_values)\n\n\n###############################################################################\n# Class MultivariateFunctionalData\n\nclass MultivariateFunctionalData(UserList):\n    r\"\"\"A class for defining Multivariate Functional Data.\n\n    An instance of MultivariateFunctionalData is a list containing objects of\n    the class DenseFunctionalData or IrregularFunctionalData.\n\n    Notes\n    -----\n    Be careful that we will not check if all the elements have the same type.\n    It is possible to create MultivariateFunctionalData containing both\n    Dense and Iregular functional data. However, only this two types are\n    allowed to be in the list.\n\n    Parameters\n    ----------\n    data: list\n        The list containing the elements of the MultivariateFunctionalData.\n\n    \"\"\"\n\n    @staticmethod\n    def _check_data(new_data):\n        \"\"\"Check the user provided `data`.\"\"\"\n        for obj in new_data:\n            _check_type(obj, (DenseFunctionalData, IrregularFunctionalData))\n        _check_same_nobs(*new_data)\n\n    def __init__(self, initlist=None):\n        \"\"\"Initialize MultivariateFunctionalData object.\"\"\"\n        self.data = initlist\n\n    def __repr__(self):\n        \"\"\"Override print function.\"\"\"\n        return (f\"Multivariate functional data object with {self.n_functional}\"\n                f\" functions of {self.n_obs} observations.\")\n\n    @property\n    def data(self):\n        \"\"\"Getter for data.\"\"\"\n        return self._data\n\n    @data.setter\n    def data(self, new_data):\n        if new_data is not None:\n            self._check_data(new_data)\n            self._data = new_data\n        else:\n            self._data = []\n\n    @property\n    def n_obs(self):\n        \"\"\"Get the number of observations of the functional data.\n\n        Returns\n        -------\n        n_obs: int\n            Number of observations within the functional data.\n\n        \"\"\"\n        return self.data[0].n_obs if len(self) > 0 else 0\n\n    @property\n    def n_functional(self):\n        \"\"\"Get the number of functional data with `self`.\n\n        Returns\n        -------\n        n_functional: int\n            Number of functions in the list.\n\n        \"\"\"\n        return len(self)\n\n    @property\n    def n_dim(self):\n        \"\"\"Get the dimension of the functional data.\n\n        Returns\n        -------\n        dim: list\n            List containing the dimension of each component in the functional\n            data.\n\n        \"\"\"\n        return [i.n_dim for i in self]\n\n    @property\n    def range_obs(self):\n        \"\"\"Get the range of the observations of the object.\n\n        Returns\n        -------\n        (min, max): list of tuples\n            List of tuples containing the mimimum and maximum values taken by\n            all the observations for the object for each function.\n\n        \"\"\"\n        return [i.range_obs for i in self]\n\n    @property\n    def n_points(self):\n        \"\"\"Get the mean number of sampling points.\n\n        Returns\n        -------\n        n_points: list of dict\n            A list of dictionary with the same shape than argvals with the\n            number of sampling points along each axis for each function.\n\n        \"\"\"\n        return [i.n_points for i in self]\n\n    @property\n    def range_points(self):\n        \"\"\"Get the range of the `argvals` for each of the dimension.\n\n        Returns\n        -------\n        ranges: list of dict\n            List of dictionary containing the range of the argvals for each of\n            the input dimension for each function.\n\n        \"\"\"\n        return [i.range_dim for i in self]\n\n    @property\n    def shape(self):\n        r\"\"\"Get the shape of the data for each dimension.\n\n        Returns\n        -------\n        shape: list of dict\n            List of dictionary containing the number of points for each of the\n            dimension for each function. It corresponds to :math:`m_j` for\n            :math:`0 \\leq j \\leq p`.\n\n        \"\"\"\n        return [i.shape for i in self]\n\n    def append(self, item):\n        \"\"\"Add an item to `self`.\n\n        Parameters\n        ----------\n        item: DenseFunctionalData or IrregularFunctionalData\n            Item to add.\n\n        \"\"\"\n        if len(self.data) == 0:\n            self.data = [item]\n        else:\n            _check_same_nobs(self, item)\n            self.data.append(item)\n\n    def extend(self, other):\n        \"\"\"Extend the list of FunctionalData by appending from iterable.\"\"\"\n        super().extend(other)\n\n    def insert(self, i, item):\n        \"\"\"Insert an item `item` at a given position `i`.\"\"\"\n        _check_same_nobs(self, item)\n        self.data.insert(i, item)\n\n    def remove(self, item):\n        \"\"\"Remove the first item from `self` where value is `item`.\"\"\"\n        raise NotImplementedError\n\n    def pop(self, i=-1):\n        \"\"\"Remove the item at the given position in the list, and return it.\"\"\"\n        return super().pop(i)\n\n    def clear(self):\n        \"\"\"Remove all items from the list.\"\"\"\n        super().clear()\n\n    def index(self, item, *args):\n        \"\"\"Return first item of the list equald to x.\"\"\"\n        raise NotImplementedError\n\n    def count(self, item):\n        \"\"\"Return the number of times `item` appears in the list.\"\"\"\n        raise NotImplementedError\n\n    def sort(self, *args, **kwds):\n        \"\"\"Sort the items of the list in place.\"\"\"\n        raise NotImplementedError\n\n    def reverse(self):\n        \"\"\"Reserve the elements of the list in place.\"\"\"\n        super().reverse()\n\n    def copy(self):\n        \"\"\"Return a shallow copy of the list.\"\"\"\n        return super().copy()\n\n    def get_obs(self):\n        \"\"\"Return a generator over the observation.\"\"\"\n        for idx in range(self.n_obs):\n            yield MultivariateFunctionalData([obs[idx] for obs in self])\n\n    def mean(self, smooth=None, **kwargs):\n        \"\"\"Compute an estimate of the mean.\n\n        Parameters\n        ----------\n        smooth: str, default=None\n            Name of the smoothing method. Currently, not implemented.\n\n        Returns\n        -------\n        obj: MultivariateFunctionalData object\n            An estimate of the mean as a MultivariateFunctionalData object\n            with a concatenation of the self.argvals as argvals and one\n            observation.\n\n        \"\"\"\n        return MultivariateFunctionalData([i.mean(smooth, **kwargs)\n                                           for i in self])\n\n    def covariance(self, mean=None, smooth=None, **kwargs):\n        \"\"\"Compute an estimate of the covariance.\n\n        Parameters\n        ----------\n        smooth: str, default=None\n            Name of the smoothing method to use. Currently, not implemented.\n        mean: MultivariateFunctionalData, default=None\n            An estimate of the mean of self. If None, an estimate is computed.\n\n        Returns\n        -------\n        obj: MultivariateFunctionalData object\n            An estimate of the covariance as a two-dimensional\n            MultivariateFunctionalData object with same argvals as `self`.\n\n        \"\"\"\n        if mean is not None:\n            return MultivariateFunctionalData(\n                [i.covariance(m, smooth, **kwargs)\n                    for i, m in zip(self, mean)])\n        else:\n            return MultivariateFunctionalData(\n                [i.covariance(None, smooth, **kwargs) for i in self])\n\n    def concatenate(self, data):\n        \"\"\"Concatenate two MultivariateFunctionalData.\n\n        Parameters\n        ----------\n        data: MultivariateFunctionalData\n            The data to concatenate with self.\n\n        Returns\n        -------\n        res: MultivariateFunctionalData\n            The concatenation of self and data.\n\n        \"\"\"\n        new = [data1.concatenate(data2) for data1, data2 in zip(self, data)]\n        return MultivariateFunctionalData(new)\n\n\n##############################################################################\n# Functional data manipulation\n\ndef concatenate_(*data):\n    \"\"\"Concatenate functional data.\n\n    Compute multiple DenseFunctionalData into one. It works with higher\n    dimension for the input data.\n\n    Parameters\n    ----------\n    *data: DenseFunctionalData\n        DenseFunctionalData to concatenate.\n\n    Returns\n    -------\n    data: DenseFunctionalData\n        The concatenation of the input data.\n\n    Notes\n    -----\n    TODO :\n    * Add tests, in particular check that the data are compatible.\n\n    \"\"\"\n    new_argvals = data[0].argvals\n    new_values = np.vstack([d.values for d in data])\n    return DenseFunctionalData(new_argvals, new_values)\n\n\ndef tensor_product_(data1, data2):\n    \"\"\"Compute the tensor product between functional data.\n\n    Compute the tensor product between all the observation of data1 with all\n    the observation of data2.\n\n    Parameters\n    ----------\n    data1: DenseFunctionalData\n        First functional data.\n    data2: DenseFunctionalData\n        Second functional data.\n\n    Returns\n    -------\n    data: DenseFunctionalData\n        The tensor product between data1 and data2. It contains data1.n_obs *\n        data2.n_obs observations.\n\n    Notes\n    -----\n    TODO:\n    * Add tests.\n\n    \"\"\"\n    arg = {'input_dim_0': data1.argvals['input_dim_0'],\n           'input_dim_1': data2.argvals['input_dim_0']}\n    val = [outer_(i, j) for i in data1.values for j in data2.values]\n    return DenseFunctionalData(arg, np.array(val))\n", "meta": {"hexsha": "6a81b83b7fa09db65fe85a6f593548c90add0d8f", "size": 45898, "ext": "py", "lang": "Python", "max_stars_repo_path": "FDApy/representation/functional_data.py", "max_stars_repo_name": "vishalbelsare/FDApy", "max_stars_repo_head_hexsha": "50feb99e34f265b1c17a6f234a9d2f942ceb8f6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-02-11T08:35:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T16:51:10.000Z", "max_issues_repo_path": "FDApy/representation/functional_data.py", "max_issues_repo_name": "vishalbelsare/FDApy", "max_issues_repo_head_hexsha": "50feb99e34f265b1c17a6f234a9d2f942ceb8f6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-04-07T07:10:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T16:33:19.000Z", "max_forks_repo_path": "FDApy/representation/functional_data.py", "max_forks_repo_name": "vishalbelsare/FDApy", "max_forks_repo_head_hexsha": "50feb99e34f265b1c17a6f234a9d2f942ceb8f6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-04-24T13:24:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T17:28:30.000Z", "avg_line_length": 32.5287030475, "max_line_length": 79, "alphanum_fraction": 0.580548172, "include": true, "reason": "import numpy", "num_tokens": 10008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.19313711934692232}}
{"text": "# -*- coding:utf-8 -*-\r\nimport numpy as np\r\nfrom random import choice\r\n\r\ndef strategy(state):\r\n    \"\"\" Information provided to you:\r\n    state = (board, last_move, playing, board_size)\r\n    board = (x_stones, o_stones)\r\n    stones is a set contains positions of one player's stones. e.g.\r\n        x_stones = {(8,8), (8,9), (8,10), (8,11)}\r\n    playing = 0|1, the current player's index\r\n\r\n    Your strategy will return a position code for the next stone, e.g. (8,7)\r\n    \"\"\"\r\n    board, last_move, playing, board_size = state\r\n    row = board_size\r\n    col = board_size\r\n    # create a table to record the board state\r\n    # 1: occupied by self\r\n    # 2: occupied by opponent\r\n    # 0: available\r\n    table = np.zeros([row, col])\r\n    for i in range(row):\r\n        for j in range(col):\r\n            if playing == 1:\r\n                if (i+1, j+1) in board[0]:\r\n                    table[i, j] = 2\r\n                elif (i+1, j+1) in board[1]:\r\n                    table[i, j] = 1\r\n            else:\r\n                if (i+1, j+1) in board[0]:\r\n                    table[i, j] = 1\r\n                elif (i+1, j+1) in board[1]:\r\n                    table[i, j] = 2\r\n    # 获取该点4个方向的棋型\r\n    def getstring(point):\r\n        x = point[0]\r\n        y = point[1]\r\n        # vertical\r\n        getLine1 = ''\r\n        for k in range(max(x - 4, 0), min(x + 5, 15)):\r\n            getLine1 += str(int(table[k, y]))\r\n        if x-4<0: getLine1 = '*'+getLine1\r\n        if x+4>14: getLine1 = getLine1+'*'\r\n        # horizonal\r\n        getLine2 = ''\r\n        for k in range(max(y - 4, 0), min(y + 5, 15)):\r\n            getLine2 += str(int(table[x, k]))\r\n        if y-4<0: getLine2 = '*'+getLine2\r\n        if y+4>14: getLine2 = getLine2+'*'\r\n        # Oblique 45\r\n        getLine3 = ''\r\n        bx = max(0, x - 4)\r\n        by = max(0, y - 4)\r\n        ux = min(14, x + 4)\r\n        uy = min(14, y + 4)\r\n        for k in range(max(bx - x, by - y), min(ux - x, uy - y)+1):\r\n            getLine3 += str(int(table[x + k, y + k]))\r\n        if x-4<0 or y-4<0: getLine3 = '*'+getLine3\r\n        if x+4>14 or y+4>14: getLine3 = getLine3+'*'\r\n        # Oblique 135\r\n        getLine4 = ''\r\n        for k in range(max(bx - x, y - uy), min(ux - x, y - by)+1):\r\n            getLine4 += str(int(table[x + k, y - k]))\r\n        if x-4<0 or y+4>14: getLine4 = '*'+getLine4\r\n        if x+4>14 or y-4<0: getLine4 = getLine4+'*'\r\n\r\n        return [getLine1, getLine2, getLine3, getLine4]\r\n\r\n    # 判断我方棋型\r\n    def judgeType1(getline):\r\n        if '11111' in getline:\r\n            return 'win5'\r\n        if '011110' in getline:\r\n            return 'alive4'\r\n        if '211110' in getline or '011112' in getline\\\r\n                or '*11110' in getline or '01111*' in getline:\r\n            return 'lian-rush4'\r\n        if '11101' in getline or '10111' in getline\\\r\n                or '11011' in getline:\r\n            return 'tiao-rush4'\r\n        if '001110' in getline or '011100' in getline:\r\n            return 'lian-alive3'\r\n        if '011010' in getline or '010110' in getline:\r\n            return 'tiao-alive3'\r\n        if '211100' in getline or '001112' in getline\\\r\n                or '*11100' in getline or '00111*' in getline:\r\n            return 'lian-sleep3'\r\n        if '211010' in getline or '010112' in getline\\\r\n                or '*11010' in getline or '01011*' in getline\\\r\n                or '210110' in getline or '011012' in getline\\\r\n                or '*10110' in getline or '01101*' in getline:\r\n            return 'tiao-sleep3'\r\n        if '11001' in getline or '10011' in getline\\\r\n                or '10101' in getline:\r\n            return 'te-sleep3'\r\n        if '2011102' in getline or '*011102' in getline\\\r\n                or '201110*' in getline or '*01110*' in getline:\r\n            return 'jia-alive3'\r\n        if '001100' in getline or '011000' in getline\\\r\n                or '000110' in getline or '001010' in getline\\\r\n                or '010100' in getline or '010010' in getline:\r\n            return 'alive2'\r\n        if '211000' in getline or '000112' in getline\\\r\n                or '*11000' in getline or '00011*' in getline\\\r\n                or '210100' in getline or '001012' in getline\\\r\n                or '*10100' in getline or '00101*' in getline\\\r\n                or '210010' in getline or '010012' in getline\\\r\n                or '*10010' in getline or '01001*' in getline\\\r\n                or '10001' in getline or '2010102' in getline\\\r\n                or '*01010*' in getline or '201010*' in getline\\\r\n                or '*010102' in getline or '2011002' in getline\\\r\n                or '2001102' in getline or '*011002' in getline\\\r\n                or '200110*' in getline or '201100*' in getline\\\r\n                or '*001102' in getline:\r\n            return 'sleep2'\r\n        if '010' in getline:\r\n            return 'alive1'\r\n        else:\r\n            return 'nothreat'\r\n\r\n    # 判断对方棋型\r\n    def judgeType2(getline):\r\n        if '22222' in getline:\r\n            return 'win5'\r\n        if '022220' in getline:\r\n            return 'alive4'\r\n        if '122220' in getline or '022221' in getline\\\r\n                or '*22220' in getline or '02222*' in getline:\r\n            return 'lian-rush4'\r\n        if '22202' in getline or '20222' in getline\\\r\n                or '22022' in getline:\r\n            return 'tiao-rush4'\r\n        if '002220' in getline or '022200' in getline:\r\n            return 'lian-alive3'\r\n        if '022020' in getline or '020220' in getline:\r\n            return 'tiao-alive3'\r\n        if '122200' in getline or '002221' in getline\\\r\n                or '*22200' in getline or '00222*' in getline:\r\n            return 'lian-sleep3'\r\n        if '122020' in getline or '020221' in getline\\\r\n                or '*22020' in getline or '02022*' in getline\\\r\n                or '120220' in getline or '022021' in getline\\\r\n                or '*20220' in getline or '02202*' in getline:\r\n            return 'tiao-sleep3'\r\n        if '22002' in getline or '20022' in getline\\\r\n                or '20202' in getline:\r\n            return 'te-sleep3'\r\n        if '1022201' in getline or '*022201' in getline\\\r\n                or '102220*' in getline or '*02220*' in getline:\r\n            return 'jia-alive3'\r\n        if '002200' in getline or '022000' in getline\\\r\n                or '000220' in getline or '002020' in getline\\\r\n                or '020200' in getline or '020020' in getline:\r\n            return 'alive2'\r\n        if '122000' in getline or '000221' in getline\\\r\n                or '*22000' in getline or '00022*' in getline\\\r\n                or '120200' in getline or '002021' in getline\\\r\n                or '*20200' in getline or '00202*' in getline\\\r\n                or '120020' in getline or '020021' in getline\\\r\n                or '*20020' in getline or '02002*' in getline\\\r\n                or '20002' in getline or '1020201' in getline\\\r\n                or '*02020*' in getline or '102020*' in getline\\\r\n                or '*020201' in getline or '1022001' in getline\\\r\n                or '1002201' in getline or '*022001' in getline\\\r\n                or '100220*' in getline or '102200*' in getline\\\r\n                or '*002201' in getline:\r\n            return 'sleep2'\r\n        if '020' in getline:\r\n            return 'alive1'\r\n        else:\r\n            return 'nothreat'\r\n\r\n    # 计算我方形势分数\r\n    def evaluate_self(table):\r\n        row, col = table.shape\r\n        myscore = 0\r\n        for i in range(row):\r\n            for j in range(col):\r\n                if table[i, j] == 1:\r\n                    point = (i, j)\r\n                    myType={'win5':0, 'alive4':0, 'lian-rush4':0, 'tiao-rush4':0, 'lian-alive3':0, 'tiao-alive3':0,\\\r\n                            'lian-sleep3':0, 'tiao-sleep3':0, 'te-sleep3':0, 'jia-alive3':0,\\\r\n                            'alive2':0, 'sleep2':0, 'alive1':0, 'nothreat':0}\r\n                    lines = getstring(point)\r\n                    for item0 in lines:\r\n                        tmp1 = judgeType1(item0)\r\n                        myType[tmp1] += 1\r\n                    # my score\r\n                    myscore += 1000000*myType['win5']+20000*myType['alive4']+ \\\r\n                               6100*myType['lian-rush4']+6000*myType['tiao-rush4']+ \\\r\n                               1100*myType['lian-alive3']+1000*myType['tiao-alive3']+ \\\r\n                               300*myType['lian-sleep3']+290*myType['tiao-sleep3']+\\\r\n                               290*myType['te-sleep3']+290*myType['jia-alive3']+\\\r\n                               100*myType['alive2']+10*myType['sleep2']+\\\r\n                               3*myType['alive1']+1*myType['nothreat']\r\n        return myscore\r\n\r\n    # 计算敌方的形势分数\r\n    def evaluate_op(table):\r\n        row, col = table.shape\r\n        opscore = 0\r\n        for i in range(row):\r\n            for j in range(col):\r\n                if table[i, j] == 2:\r\n                    point = (i, j)\r\n                    opType = {'win5':0, 'alive4':0, 'lian-rush4':0, 'tiao-rush4':0, 'lian-alive3':0, 'tiao-alive3':0,\\\r\n                            'lian-sleep3':0, 'tiao-sleep3':0, 'te-sleep3':0, 'jia-alive3':0,\\\r\n                            'alive2':0, 'sleep2':0, 'alive1':0, 'nothreat':0}\r\n                    lines = getstring(point)\r\n                    for item0 in lines:\r\n                        tmp2 = judgeType2(item0)\r\n                        opType[tmp2] += 1\r\n                    # opponent score\r\n                    opscore += 1000000*opType['win5']+100000*opType['alive4']+ \\\r\n                               65000*opType['lian-rush4']+65000*opType['tiao-rush4']+ \\\r\n                               5500*opType['lian-alive3']+5000*opType['tiao-alive3']+ \\\r\n                               200*opType['lian-sleep3']+200*opType['tiao-sleep3']+\\\r\n                               200*opType['te-sleep3']+200*opType['jia-alive3']+\\\r\n                               90*opType['alive2']+9*opType['sleep2']+\\\r\n                               4*opType['alive1']+1*opType['nothreat']\r\n        return opscore\r\n    \r\n    \r\n    #随机返回一个score最大的位置\r\n    def randomChoose(scoretable):\r\n        maxValue = max(scoretable.items(), key=lambda x: x[1])[1]\r\n        positions=[]\r\n        for item in scoretable.items():\r\n            if item[1]==maxValue:\r\n                positions.append(item[0])\r\n        return choice(positions)\r\n    \r\n\r\n    if len(board[0]) == 0 and len(board[1]) == 0:\r\n        return (board_size/2 + 1, board_size/2 + 1)\r\n    else:\r\n        # 获得局部搜索区域的下标\r\n        sumBoard = board[0] | board[1]\r\n        xmax = min(max(sumBoard, key=lambda x: x[0])[0] + 2, 15)\r\n        ymax = min(max(sumBoard, key=lambda x: x[1])[1] + 2, 15)\r\n        xmin = max(min(sumBoard, key=lambda x: x[0])[0] - 3, 0)\r\n        ymin = max(min(sumBoard, key=lambda x: x[1])[1] - 3, 0)\r\n\r\n        scoretable={}\r\n        for i in range(xmin, xmax):\r\n            for j in range(ymin, ymax):\r\n                if table[i, j] == 0:\r\n                    #old = evaluate_self(table)-defend*evaluate_op(table)\r\n                    table[i, j] = 1\r\n                    scoretable[(i, j)] = evaluate_self(table)-evaluate_op(table)\r\n                    table[i, j] = 0\r\n        self_position = randomChoose(scoretable)\r\n        return (self_position[0]+1, self_position[1]+1)\r\n\r\n\r\ndef finish():\r\n    pass\r\n", "meta": {"hexsha": "8da52add28d251ada90d53d673a9d9608e352446", "size": 11281, "ext": "py", "lang": "Python", "max_stars_repo_path": "AI5.py", "max_stars_repo_name": "TianxiaoHu/GomokuAgent", "max_stars_repo_head_hexsha": "8cb05025059945692846cbb0541a834e9f985ce2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2017-06-29T07:47:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T05:33:59.000Z", "max_issues_repo_path": "AI5.py", "max_issues_repo_name": "TianxiaoHu/GomokuAgent", "max_issues_repo_head_hexsha": "8cb05025059945692846cbb0541a834e9f985ce2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AI5.py", "max_forks_repo_name": "TianxiaoHu/GomokuAgent", "max_forks_repo_head_hexsha": "8cb05025059945692846cbb0541a834e9f985ce2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-01T07:53:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-01T07:53:48.000Z", "avg_line_length": 43.555984556, "max_line_length": 119, "alphanum_fraction": 0.4823153976, "include": true, "reason": "import numpy", "num_tokens": 3197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.19313711934692226}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\nimport matplotlib.cm as cm\nimport pandas as pd\nimport re\nimport io\nimport os\nimport astropy.constants as cst\nimport astropy.units as units\nimport scipy.interpolate as interp\n\nfrom collections import deque\nfrom pathlib import Path \n\n\n#######################################\n# model loading functions\n#\ndef _read_model_BHAC2015(path, fname, instrument):\n    '''\n    (Private) Read the BHAC2015 models\n\n    Parameters\n    ----------\n    path : str\n        Full path to the directory containing the model files\n\n    fname : str\n        Full model file name\n\n    instrument : str\n        Name of the instrument (or observatory) for the file\n\n    Returns\n    -------\n    masses : vector\n        Numpy vector with unique masses, in MJup\n\n    ages : vector\n        Numpy vector with unique ages, in Myr\n\n    values : array\n        Array with names of parameters\n\n    data : array\n        Numpy data array\n    '''\n    \n    # read general data\n    data = pd.read_csv(path / fname, sep='\\s+', header=None, comment='!')\n\n    # add ages\n    data.insert(0, 'age', 0)\n\n    # read column headers and age values\n    p_cols = re.compile('!\\s+(mass)\\s+(Teff)')\n    p_ages = re.compile('!\\s+t\\s+\\(Gyr\\)\\s+=\\s+([0-9]+\\.[0-9]+)')\n    p_vals = re.compile('\\s+([0-9]+\\.[0-9]+)\\s+([0-9]+\\.[0-9]+)')\n\n    cols = ['age']\n    ages = []\n    cage = 0\n\n    file = open(path / fname, 'r')\n    for line in file:\n        # skip non-comment lines\n        if (line[0] != '!'):\n            m = p_vals.match(line)\n            if (m is not None):\n                ages.append(cage)\n            continue\n\n        # column names\n        if (len(cols) == 1):\n            m = p_cols.match(line)\n            if (m is not None):\n                cols.extend(line[1:].split())\n\n        # age value\n        m = p_ages.match(line)\n        if (m is not None):\n            cage = float(m.group(1))\n\n    file.close()\n\n    # rename columns and add age values\n    data.columns = cols    \n    data.age = ages\n\n    # unit conversion\n    data.age    *= 1000\n    data.mass   *= cst.M_sun / cst.M_jup\n    data.radius *= cst.R_sun / cst.R_jup\n    \n    # reshape in final format\n    masses, ages, values, dat = _reshape_data(data)\n\n    return masses, ages, values, dat\n\n\ndef _read_model_PHOENIX_websim(path, fname, instrument):\n    '''\n    (Private) Read models from the PHOENIX web simulator\n\n    Parameters\n    ----------\n    path : str\n        Full path to the directory containing the model files\n\n    fname : str\n        Full model file name\n\n    instrument : str\n        Name of the instrument (or observatory) for the file\n\n    Returns\n    -------\n    masses : vector\n        Numpy vector with unique masses, in MJup\n\n    ages : vector\n        Numpy vector with unique ages, in Myr\n\n    values : array\n        Array with names of parameters\n\n    data : array\n        Numpy data array\n    '''\n\n    # read column headers and number of values\n    p_cols = re.compile('\\s+M/Ms\\s*Teff.K.\\s+L/Ls\\s+lg\\(g\\)\\s+R.(\\w+).\\s+D\\s+Li\\s+([A-Za-z0-9\\\\s_.\\']+)')\n    p_ages = re.compile('\\s+t\\s+\\(Gyr\\)\\s+=\\s+([0-9]+\\.[0-9]+)')\n    p_vals = re.compile('(\\s+[+-]*[0-9]+\\.[0-9]*){3}')\n\n    cols  = ['age', 'mass', 'Teff', 'logL', 'logg', 'radius', 'D', 'Li']\n    cage  = 0\n    ages  = []\n    unit  = None\n    lines = []\n    \n    # get column names\n    file = open(path / fname, 'r')\n    for line in file:\n        # age value\n        m = p_ages.match(line)\n        if (m is not None):            \n            cage = float(m.group(1))\n            continue\n        \n        # column names\n        if (len(cols) == 8):\n            m = p_cols.match(line)\n            if (m is not None):\n                unit = m.group(1)\n\n                names = m.group(2)\n                names = names.replace(\"'\", \"p\")\n                \n                cols.extend(names.split())\n                \n                continue\n            \n        # model values\n        m = p_vals.match(line)\n        if (m is not None):\n            lines.append(line)\n            ages.append(cage)\n            \n    file.close()\n                \n    # create data frame\n    lines = ''.join(lines)\n    data = pd.read_csv(io.StringIO(lines), sep='\\s+', header=None)\n\n    # add ages\n    data.insert(0, 'age', 0)\n    data.age = ages\n\n    # rename columns\n    data.columns = cols    \n    \n    # unit conversion\n    data.age  *= 1000\n    data.mass *= cst.M_sun / cst.M_jup\n    if unit == 'Gm':\n        # data.radius /= cst.R_jup.to(units.Gm)\n        pass\n    elif unit == 'Gcm':\n        #data.radius /= cst.R_jup.to(units.Gm*100)\n        pass\n    else:\n        pass\n        \n    # reshape in final format\n    masses, ages, values, dat = _reshape_data(data)\n        \n    return masses, ages, values, dat\n\n\ndef _read_model_sonora(path, fname, instrument):\n    '''\n    (Private) Read the SONORA models\n\n    Parameters\n    ----------\n    path : str\n        Full path to the directory containing the model files\n\n    fname : str\n        Full model file name\n\n    instrument : str\n        Name of the instrument (or observatory) for the file\n\n    Returns\n    -------\n    masses : vector\n        Numpy vector with unique masses, in MJup\n\n    ages : vector\n        Numpy vector with unique ages, in Myr\n\n    values : array\n        Array with names of parameters\n\n    data : array\n        Numpy data array\n    '''\n\n    df = pd.read_csv(path / fname, index_col=(0, 1))\n\n    masses  = np.sort(np.unique(df.index.get_level_values(0)))  # MJup\n    ages    = np.sort(np.unique(df.index.get_level_values(1)))  # yr\n    values  = df.columns\n\n    data = np.zeros((len(masses), len(ages), len(values)))\n    for iv, val in enumerate(values):\n        for im, mass in enumerate(masses):\n            tmp = df.loc[(mass, slice(None)), val]\n            data[im, :, iv] = tmp\n            \n    # converts ages in Myr\n    ages = ages / 1e6\n    \n    return masses, ages, values, data\n\n\ndef _read_model_bex(path, fname, instrument):\n    '''\n    (Private) Read the BEX models\n\n    Parameters\n    ----------\n    path : str\n        Full path to the directory containing the model files\n\n    fname : str\n        Full model file name\n\n    instrument : str\n        Name of the instrument (or observatory) for the file\n\n    Returns\n    -------\n    masses : vector\n        Numpy vector with unique masses, in MJup\n\n    ages : vector\n        Numpy vector with unique ages, in Myr\n\n    values : array\n        Array with names of parameters\n\n    data : array\n        Numpy data array\n    '''\n\n    df = pd.read_csv(path / fname, index_col=(0, 1))\n\n    masses  = np.sort(np.unique(df.index.get_level_values(0)))  # MJup\n    ages    = np.sort(np.unique(df.index.get_level_values(1)))  # yr\n    values  = df.columns\n\n    data = np.zeros((len(masses), len(ages), len(values)))\n    for iv, val in enumerate(values):\n        for im, mass in enumerate(masses):\n            tmp = df.loc[(mass, slice(None)), val]\n            data[im, :, iv] = tmp\n            \n    # converts ages in Myr\n    ages = ages / 1e6\n    \n    return masses, ages, values, data\n\n    \ndef _read_model_atmo(path, fname, instrument):\n    '''\n    (Private) Read the ATMO models\n\n    Parameters\n    ----------\n    path : str\n        Full path to the directory containing the model files\n\n    fname : str\n        Full model file name\n\n    instrument : str\n        Name of the instrument (or observatory) for the file\n\n    Returns\n    -------\n    masses : vector\n        Numpy vector with unique masses, in MJup\n\n    ages : vector\n        Numpy vector with unique ages, in Myr\n\n    values : array\n        Array with names of parameters\n\n    data : array\n        Numpy data array\n    '''\n\n    df = pd.read_csv(path / fname, index_col=(0, 1))\n\n    masses  = np.sort(np.unique(df.index.get_level_values(0)))  # MJup\n    ages    = np.sort(np.unique(df.index.get_level_values(1)))  # yr\n    values  = df.columns\n\n    data = np.zeros((len(masses), len(ages), len(values)))\n    for iv, val in enumerate(values):\n        for im, mass in enumerate(masses):\n            tmp = df.loc[(mass, slice(None)), val]\n            data[im, :, iv] = tmp\n            \n    # converts ages in Myr\n    ages = ages / 1e6\n    \n    return masses, ages, values, data\n\n    \ndef _reshape_data(dataframe):\n    '''\n    Reshape the data frame in a regular grid that can be used as input in scipy functions.\n\n    Parameters\n    ----------\n    dataframe : pandas DataFrame\n        Data frame with all the data\n\n    Returns\n    -------\n    masses : vector\n        Numpy vector with unique masses, in MJup\n\n    ages : vector\n        Numpy vector with unique ages, in Myr\n\n    values : array\n        Array with names of parameters\n\n    data : array\n        Numpy data array\n    '''\n\n    # unique ages and masses\n    masses = dataframe.mass.unique()\n    ages = dataframe.age.unique()\n\n    # values\n    values = dataframe.columns.values[2:]\n\n    # fill array\n    data = np.full((masses.size, ages.size, values.size), np.nan)\n    for m, mass in enumerate(masses):\n        for a, age in enumerate(ages):\n            mask = (dataframe.mass == mass) & (dataframe.age == age)\n            \n            if mask.any():\n                data[m, a, :] = dataframe.loc[mask, 'Teff':].values.squeeze()\n\n    return masses, ages, values, data\n\n\n#######################################\n# utility functions\n#\ndef _monotonic_sublists(lst):\n    '''\n    (Private) Extract monotonic sublists from a list of values\n    \n    Given a list of values that is not sorted (such that for some valid\n    indices i,j, i<j, sometimes lst[i] > lst[j]), produce a new\n    list-of-lists, such that in the new list, each sublist *is*\n    sorted: for all sublist \\elem returnval: assert_is_sorted(sublist)\n    and furthermore this is the minimal set of sublists required to\n    achieve the condition.\n\n    Thus, if the input list lst is actually sorted, this returns\n    [list(lst)].\n\n    Parameters\n    ----------\n    lst : list or array\n        List of values\n\n    Returns\n    -------\n    ret_i : list\n        List of indices of monotonic sublists\n    \n    ret_v : list\n        List of values of monotonic sublists\n    '''\n\n    # Make a copy of lst before modifying it; use a deque so that\n    # we can pull entries off it cheaply.\n    idx = deque(range(len(lst)))\n    deq = deque(lst)\n    ret_i = []\n    ret_v = []\n    while deq:\n        sub_i = [idx.popleft()]\n        sub_v = [deq.popleft()]\n\n        if len(deq) > 1:\n            if deq[0] <= sub_v[-1]:\n                while deq and deq[0] <= sub_v[-1]:\n                    sub_i.append(idx.popleft())\n                    sub_v.append(deq.popleft())\n            else:\n                while deq and deq[0] >= sub_v[-1]:\n                    sub_i.append(idx.popleft())\n                    sub_v.append(deq.popleft())\n                    \n        ret_i.append(sub_i)\n        ret_v.append(sub_v)\n        \n    return ret_i, ret_v\n\n\ndef _interpolate_model(masses, ages, values, data, age, filt, param, Mabs, fill):\n    '''\n    (Private) Interpolate model grid\n\n    Parameters\n    ----------\n    masses : array\n        Mass values in the model grid\n\n    ages : array\n        Age values in the model grid\n    \n    values : array\n        Name of filters (and other parameters) in the model grid\n\n    data : array\n        Data of the model grid\n\n    age : float\n        Age at which interpolation is needed\n\n    filt : str\n        Filter in which the magnitude is provided\n\n    param : str\n        Parameter to be interpolated\n\n    Mabs : array\n        Absolute magnitude\n\n    fill : bool\n        Fill interpolated values with min/max values in the models when\n        trying to interpolate outside the values in the models\n    \n    Returns\n    -------\n    values : array\n        Interpolated values\n    '''\n\n    # age indices\n    ii = np.abs(ages-age).argmin()\n    if age <= ages[ii]:\n        imin = ii-1\n        imax = ii\n    elif age > ages[ii]:\n        imin = ii\n        imax = ii+1\n\n    agemin = ages[imin]\n    agemax = ages[imax]\n        \n    # parameter value\n    if param == 'Mass':\n        ifilt = np.where(values == filt)[0]\n\n        Zmin = data[:, imin, ifilt].squeeze()\n        Zmax = data[:, imax, ifilt].squeeze()\n\n        Znew = (Zmin - Zmax) / (agemin - agemax) * (age - agemin) + Zmin\n\n        # remove missing values\n        masses = masses[np.isfinite(Znew)]\n        Znew   = Znew[np.isfinite(Znew)]\n        \n        # find monotonic parts of the signal\n        mono_i, mono_v = _monotonic_sublists(Znew)\n        \n        nsub = len(mono_i)\n        sub_idx = np.zeros((2*nsub-1, 2), dtype=np.int)\n        for s in range(nsub):\n            sub_idx[s, 0] = mono_i[s][0]\n            sub_idx[s, 1] = mono_i[s][-1]\n        for s in range(nsub-1):\n            sub_idx[s+nsub, 0] = mono_i[s][-1]\n            sub_idx[s+nsub, 1] = mono_i[s+1][0]\n\n        sub_idx = np.sort(sub_idx, axis=0)\n\n        # interpolate over each part\n        values = np.zeros((2*nsub-1, Mabs.size))\n        for i, s in enumerate(sub_idx):\n            sub_Znew   = Znew[s[0]:s[1]+1]\n            sub_masses = masses[s[0]:s[1]+1]\n\n            if len(sub_Znew) < 2:\n                continue\n            \n            interp_func = interp.interp1d(sub_Znew, sub_masses, bounds_error=False, fill_value=np.nan)\n            values[i] = interp_func(Mabs)\n\n            # fill if outside of available values\n            if fill:\n                values[i, Mabs < sub_Znew.min()] = masses.max()\n                values[i, Mabs > sub_Znew.max()] = masses.min()\n        \n        # combine\n        values = np.nanmax(values, axis=0)\n    else:\n        raise ValueError('Interpolation for parameter {0} is not implemented yet.'.format(param))\n\n    return values\n\n\ndef _read_model_data(paths, models, instrument, model):\n    '''\n    Return the data from a model and instrument\n\n    Parameters\n    ----------\n    paths : list\n        List of paths where to find the models\n\n    models : dict\n        Dictionary containing all the models information and data\n\n    instrument : str\n        Instrument name\n\n    model : str\n        Model name\n\n    Returns\n    -------\n    path : str\n        The complete path to the model file\n    '''\n\n    # lower case\n    model = model.lower()\n    instrument = instrument.lower()\n    \n    # model key\n    key = instrument.lower()+'_'+model.lower()\n\n    # find proper model\n    data = None\n    for mod in models['properties']:\n        if (mod['name'] == model) and (mod['instrument'] == instrument):\n            fname = mod['file']\n            \n            # search for path\n            found = False\n            for path in paths:\n                if (path / fname).exists():\n                    mod['path'] = path\n                    found = True\n                    break\n\n            if not found:\n                raise ValueError('File {0} for model {1} and instrument {2} does not exists. Are you sure it is in your search path?'.format(path, model, instrument))\n            \n            # get data in format (masses, ages, values, data)\n            data = mod['function'](path, fname, instrument)\n\n    # not found\n    if data is None:\n        raise ValueError('Could not find model {0} for instrument {1}'.format(model, instrument))\n\n    # save data\n    models['data'][key] = data\n\n    \n#######################################\n# models definitions\n#\nsearch_path = [(Path(__file__) / '../../data/evolution/').resolve()]\nmodels = {\n    'properties': [\n        {'instrument': 'nicmos', 'name': 'dusty2000',           'file': 'model.AMES-dusty-2000.M-0.0.HST',           'function': _read_model_PHOENIX_websim},\n        {'instrument': 'naco',   'name': 'dusty2000',           'file': 'model.AMES-dusty-2000.M-0.0.NaCo',          'function': _read_model_PHOENIX_websim},\n        {'instrument': 'irdis',  'name': 'dusty2000',           'file': 'model.AMES-dusty-2000.M-0.0.SPHERE.Vega',   'function': _read_model_PHOENIX_websim},\n        {'instrument': 'nicmos', 'name': 'cond2003',            'file': 'model.AMES-Cond-2003.M-0.0.HST',            'function': _read_model_PHOENIX_websim},\n        {'instrument': 'naco',   'name': 'cond2003',            'file': 'model.AMES-Cond-2003.M-0.0.NaCo',           'function': _read_model_PHOENIX_websim},\n        {'instrument': 'irdis',  'name': 'cond2003',            'file': 'model.AMES-Cond-2003.M-0.0.SPHERE.Vega',    'function': _read_model_PHOENIX_websim},    \n        {'instrument': 'irdis',  'name': 'bhac2015+dusty2000',  'file': 'BHAC15_DUSTY00_iso_t10_10.SPHERE',          'function': _read_model_BHAC2015},\n        {'instrument': 'irdis',  'name': 'bhac2015+cond2003',   'file': 'BHAC15_COND03_iso_t10_10.SPHERE',           'function': _read_model_BHAC2015},\n        \n        {'instrument': 'mko',    'name': 'sonora',              'file': 'sonora_mko.csv.gz',                         'function': _read_model_sonora},\n        {'instrument': '2mass',  'name': 'sonora',              'file': 'sonora_2mass.csv.gz',                       'function': _read_model_sonora},\n        {'instrument': 'keck',   'name': 'sonora',              'file': 'sonora_keck.csv.gz',                        'function': _read_model_sonora},\n        {'instrument': 'sdss',   'name': 'sonora',              'file': 'sonora_sdss.csv.gz',                        'function': _read_model_sonora},\n        {'instrument': 'irac',   'name': 'sonora',              'file': 'sonora_irac.csv.gz',                        'function': _read_model_sonora},\n        {'instrument': 'wise',   'name': 'sonora',              'file': 'sonora_wise.csv.gz',                        'function': _read_model_sonora},        \n        \n        {'instrument': 'irdis',  'name': 'bex_cond_coldest',    'file': 'bex_ames-cond_coldest.csv.gz',              'function': _read_model_bex},\n        {'instrument': 'irdis',  'name': 'bex_cond_warm',       'file': 'bex_ames-cond_warm.csv.gz',                 'function': _read_model_bex},\n        {'instrument': 'irdis',  'name': 'bex_cond_hot',        'file': 'bex_ames-cond_hot.csv.gz',                  'function': _read_model_bex},\n        {'instrument': 'irdis',  'name': 'bex_cond_hottest',    'file': 'bex_ames-cond_hottest.csv.gz',              'function': _read_model_bex},\n        {'instrument': 'irdis',  'name': 'bex_dusty_coldest',   'file': 'bex_ames-dusty_coldest.csv.gz',             'function': _read_model_bex},\n        {'instrument': 'irdis',  'name': 'bex_dusty_warm',      'file': 'bex_ames-dusty_warm.csv.gz',                'function': _read_model_bex},\n        {'instrument': 'irdis',  'name': 'bex_dusty_hot',       'file': 'bex_ames-dusty_hot.csv.gz',                 'function': _read_model_bex},\n        {'instrument': 'irdis',  'name': 'bex_dusty_hottest',   'file': 'bex_ames-dusty_hottest.csv.gz',             'function': _read_model_bex},\n\n        {'instrument': 'mko',    'name': 'atmo_ceq',            'file': 'ATMO_CEQ_MKO.csv.gz',                       'function': _read_model_atmo},\n        {'instrument': 'mko',    'name': 'atmo_neq_strong',     'file': 'ATMO_NEQ_strong_MKO.csv.gz',                'function': _read_model_atmo},\n        {'instrument': 'mko',    'name': 'atmo_neq_weak',       'file': 'ATMO_NEQ_weak_MKO.csv.gz',                  'function': _read_model_atmo},\n        {'instrument': 'irac',   'name': 'atmo_ceq',            'file': 'ATMO_CEQ_MKO.csv.gz',                       'function': _read_model_atmo},\n        {'instrument': 'irac',   'name': 'atmo_neq_strong',     'file': 'ATMO_NEQ_strong_MKO.csv.gz',                'function': _read_model_atmo},\n        {'instrument': 'irac',   'name': 'atmo_neq_weak',       'file': 'ATMO_NEQ_weak_MKO.csv.gz',                  'function': _read_model_atmo},\n        {'instrument': 'wise',   'name': 'atmo_ceq',            'file': 'ATMO_CEQ_MKO.csv.gz',                       'function': _read_model_atmo},\n        {'instrument': 'wise',   'name': 'atmo_neq_strong',     'file': 'ATMO_NEQ_strong_MKO.csv.gz',                'function': _read_model_atmo},\n        {'instrument': 'wise',   'name': 'atmo_neq_weak',       'file': 'ATMO_NEQ_weak_MKO.csv.gz',                  'function': _read_model_atmo},\n    ],\n    'data': {}\n}\n\n\n#######################################\n# public functions\n#\ndef mag_to_mass(age, distance, mag, Dmag, filt,\n                instrument='IRDIS', model='bhac2015+cond2003', fill=False,\n                age_range=None, distance_range=None, mag_err=None, Dmag_range=None):\n    '''\n    Convert a contrast value into mass\n\n    Parameters\n    ----------\n    age : float\n        Age of the target in Myr\n\n    distance : float\n        Distance of the target in pc\n\n    mag : float\n        Magnitude of the target in the filter\n\n    Dmag : array\n        Contrast value(s) in the filter\n\n    filt : str\n        Name of the filter\n\n    instrument : str\n        Name of the instrument. The default is IRDIS\n\n    model : str\n        Name of the evolutionary model. The default is bhac2015+cond2003\n\n    fill : bool\n        Fill interpolated values with min/max values in the models when\n        trying to interpolate outside the values in the models\n    \n    age_range : list\n        [min, max] age estimations for the target\n\n    distance_range : list\n        [min, max] distance estimations for the target\n\n    mag_err : float\n        Error on the target magnitude\n\n    Dmag_range : array\n        [min, max] contrast estimations\n\n    Returns\n    -------\n    mass, mass_min, mass_max : array\n        Values of the mass interpolated into the model\n    '''    \n    \n    # -------------------------------\n    # get model data\n    # -------------------------------\n    masses, ages, values, data = model_data(instrument, model)\n\n    # check ages\n    if (age < ages.min()) or (age > ages.max()):\n        raise ValueError('Age {0} Myr outside of model range [{1}, {2}]'.format(age, ages.min(), ages.max()))\n\n    # check filter\n    if filt not in values:\n        raise ValueError('Filter {0} not available in list: {1}'.format(filt, values))\n    \n    # -------------------------------\n    # explicit variable names\n    # -------------------------------\n    \n    # age range\n    if age_range is not None:\n        if not isinstance(age_range, list):\n            raise ValueError('Age range must be a 2-elements array')\n\n        age_min = np.min(age_range)\n        age_max = np.max(age_range)\n    else:\n        age_min = age\n        age_max = age\n                \n    # dist range\n    if distance_range is not None:\n        if not isinstance(distance_range, list):\n            raise ValueError('Dist range must be a 2-elements array')\n\n        dist_min = np.min(distance_range)\n        dist_max = np.max(distance_range)\n    else:\n        dist_min = distance\n        dist_max = distance\n\n    # Stellar mag range\n    if mag_err is not None:\n        if not isinstance(mag_err, (int, float)):\n            raise ValueError('Stellar mag error must be a float')\n\n        mag_min = mag - mag_err\n        mag_max = mag + mag_err\n    else:\n        mag_min = mag\n        mag_max = mag\n\n    # delta mag range\n    if Dmag_range is not None:\n        raise ValueError('Dmag error not implemented')\n    else:\n        Dmag_faint  = Dmag\n        Dmag_bright = Dmag\n\n    # -------------------------------\n    # absolute magnitude conversion\n    # -------------------------------\n\n    # nominal values\n    Mabs_nom = mag - 5*np.log10(distance) + 5 + Dmag\n\n    # taking errors into account\n    Mabs_faint  = mag_min - 5*np.log10(dist_min) + 5 + Dmag_faint\n    Mabs_bright = mag_max - 5*np.log10(dist_max) + 5 + Dmag_bright\n\n    # -------------------------------\n    # interpolate models\n    # -------------------------------\n    param = 'Mass'   # only parameter currently available\n    values_nom = _interpolate_model(masses, ages, values, data, age, filt, param, Mabs_nom, fill)\n    values_min = _interpolate_model(masses, ages, values, data, age_min, filt, param, Mabs_faint, fill)\n    values_max = _interpolate_model(masses, ages, values, data, age_max, filt, param, Mabs_bright, fill)\n    \n    values_all = np.vstack((values_min, values_nom, values_max))\n    values_min = np.nanmin(values_all, axis=0)\n    values_max = np.nanmax(values_all, axis=0)\n        \n    return values_nom, values_min, values_max\n\n\ndef list_models():\n    '''\n    Print the list of available models\n    '''\n    print()\n    print('Search paths:')\n    for p in search_path:\n        print(' * {}'.format(p))\n    print()\n\n    for i in range(len(models['properties'])):\n        prop = models['properties'][i]\n        \n        print(prop['file'])\n        print(' * instrument: {0}'.format(prop['instrument']))\n        print(' * name:       {0}'.format(prop['name']))\n        print(' * function:   {0}'.format(prop['function'].__name__))\n        try:\n            print(' * path:       {0}'.format(prop['path']))\n        except KeyError:\n            pass\n        print()\n\n\ndef model_data(instrument, model):\n    '''\n    Return the model data for a given instrument\n\n    Directly returns the data if it has been read and stored\n    already. Otherwise read and store it before returning.\n    \n    Parameters\n    ----------\n    instrument : str\n        Instrument name\n\n    model : str\n        Model name\n\n    Returns\n    -------\n    data : tuple \n        Tuple (masses, ages, values, data)\n    '''\n    \n    # model key\n    key = instrument.lower()+'_'+model.lower()\n\n    if key not in models['data'].keys():\n        print('Loading model {0} for {1}'.format(model, instrument))\n        \n        _read_model_data(search_path, models, instrument, model)\n\n    return models['data'][key]\n\n\ndef add_search_path(path):\n    '''\n    Add a new location in the search path\n\n    Useful to easily handle \"private\" models that are not provided\n    with the public distribution of the package.\n\n    Parameters\n    ----------\n    path : str\n        Path to the additional directory\n    '''\n    \n    path = Path(path).expanduser().resolve()\n    \n    # add only if necessary\n    if path not in search_path:\n        search_path.append(path)\n\n\ndef plot_model(instrument, model, param, age_list=None, mass_list=None):\n    '''\n    Plot parameter evolution as a function of age for a model and instrument\n\n    Parameters\n    ----------\n    instrument : str\n        Instrument name\n\n    model : str\n        Model name\n\n    param : str\n        Parameter of the model to be plotted\n    \n    age_list : array\n        List of ages to use for the plots. Default is None, so it will \n        use all available ages\n\n    mass_list : array\n        List of masses to use for the plots. Default is None, so it will \n        use all available masses\n\n    Returns\n    -------\n    path : str\n        The complete path to the model file\n    '''\n    \n    masses, ages, values, data = model_data(instrument, model)\n\n    if not mass_list:\n        mass_list = masses\n        \n    if not age_list:\n        age_list = ages\n\n    cmap = cm.plasma\n    norm = colors.LogNorm(vmin=ages.min(), vmax=ages.max())\n    \n    #\n    # param vs. age\n    #\n    fig = plt.figure(0, figsize=(12, 9))\n    plt.clf()\n    ax = fig.add_subplot(111)\n    \n    for mass in mass_list:\n        if (mass <= 75):\n            ax.plot(ages, data[masses == mass, :, values == param].squeeze(), \n                    label=r'{0:.1f} MJup'.format(mass), color=cmap(mass/75.))\n\n    ax.set_xscale('log')\n    ax.set_yscale('linear')\n    \n    ax.set_xlabel('Age [Myr]')\n    ax.set_ylabel(param)\n\n    ax.set_title('{0}, {1}'.format(model, instrument))\n    \n    ax.legend(loc='upper right')\n    \n    plt.tight_layout()\n\n    #\n    # param vs. mass\n    #\n    fig = plt.figure(1, figsize=(12, 9))\n    plt.clf()\n    ax = fig.add_subplot(111)\n    \n    for age in age_list:\n        ax.plot(masses, data[:, ages == age, values == param].squeeze(), \n                label=r'{0:.4f} Myr'.format(age), color=cmap(norm(age)))\n\n    ax.set_xlim(0, 75)\n        \n    ax.set_xscale('linear')\n    ax.set_yscale('linear')\n    \n    ax.set_xlabel(r'Mass [$M_{Jup}$]')\n    ax.set_ylabel(param)\n\n    ax.set_title('{0}, {1}'.format(model, instrument))\n    \n    # ax.legend(loc='upper right')\n    \n    plt.tight_layout()\n", "meta": {"hexsha": "659ac05c64390ed70684639ba43dc8691977bf51", "size": 28057, "ext": "py", "lang": "Python", "max_stars_repo_path": "vigan/astro/evolution.py", "max_stars_repo_name": "avigan/Python-utils", "max_stars_repo_head_hexsha": "360d6326e8336c624ab35755ae1827ebcdc71b33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vigan/astro/evolution.py", "max_issues_repo_name": "avigan/Python-utils", "max_issues_repo_head_hexsha": "360d6326e8336c624ab35755ae1827ebcdc71b33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2017-08-23T13:40:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-25T10:11:23.000Z", "max_forks_repo_path": "vigan/astro/evolution.py", "max_forks_repo_name": "avigan/Python-utils", "max_forks_repo_head_hexsha": "360d6326e8336c624ab35755ae1827ebcdc71b33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-10-26T08:06:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-25T09:09:18.000Z", "avg_line_length": 29.3790575916, "max_line_length": 166, "alphanum_fraction": 0.554514025, "include": true, "reason": "import numpy,import scipy,import astropy", "num_tokens": 7258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.19296030471683717}}
{"text": "import numpy as np\nimport os\nimport copy\nimport galsim\nfrom galsim import DeVaucouleurs\nfrom galsim import Exponential\nimport descwl\n\nfrom .shifts import get_shifts, get_pair_shifts\nfrom .constants import SCALE\nfrom .cache_tools import cached_catalog_read\n\n\nDEFAULT_FIXED_GAL_CONFIG = {\n    \"mag\": 17.0,\n    \"hlr\": 0.5,\n    \"morph\": \"exp\",\n}\n\n\ndef make_galaxy_catalog(\n    *,\n    rng,\n    gal_type,\n    coadd_dim=None,\n    buff=0,\n    layout=None,\n    gal_config=None,\n    sep=None,\n):\n    \"\"\"\n    rng: numpy.random.RandomState\n        Numpy random state\n    gal_type: string\n        'fixed', 'varying' or 'wldeblend'\n    coadd_dim: int\n        Dimensions of coadd\n    buff: int, optional\n        Buffer around the edge where no objects are drawn.  Ignored for\n        layout 'grid'.  Default 0.\n    layout: string, optional\n        'grid' or 'random'.  Ignored for gal_type \"wldeblend\", otherwise\n        required.\n    gal_config: dict or None\n        Can be sent for fixed galaxy catalog.  See DEFAULT_FIXED_GAL_CONFIG\n        for defaults mag, hlr and morph\n    sep: float, optional\n        Separation of pair in arcsec for layout='pair'\n    \"\"\"\n    if layout == 'pair':\n        if sep is None:\n            raise ValueError(\n                f'send sep= for gal_type {gal_type} and layout {layout}'\n            )\n        gal_config = get_fixed_gal_config(config=gal_config)\n\n        if gal_type in ['fixed', 'exp']:  # TODO remove exp\n            cls = FixedPairGalaxyCatalog\n        else:\n            cls = PairGalaxyCatalog\n\n        galaxy_catalog = cls(\n            rng=rng,\n            mag=gal_config['mag'],\n            hlr=gal_config['hlr'],\n            morph=gal_config['morph'],\n            sep=sep,\n        )\n\n    else:\n        if coadd_dim is None:\n            raise ValueError(\n                f'send coadd_dim= for gal_type {gal_type} and layout {layout}'\n            )\n\n        if gal_type == 'wldeblend':\n            galaxy_catalog = WLDeblendGalaxyCatalog(\n                rng=rng,\n                coadd_dim=coadd_dim,\n                buff=buff,\n            )\n        elif gal_type in ['fixed', 'varying', 'exp']:  # TODO remove exp\n            if layout is None:\n                raise ValueError(\"send layout= for gal_type '%s'\" % gal_type)\n\n            gal_config = get_fixed_gal_config(config=gal_config)\n\n            if gal_type == 'fixed':\n                cls = FixedGalaxyCatalog\n            else:\n                cls = GalaxyCatalog\n\n            galaxy_catalog = cls(\n                rng=rng,\n                coadd_dim=coadd_dim,\n                buff=buff,\n                layout=layout,\n                mag=gal_config['mag'],\n                hlr=gal_config['hlr'],\n                morph=gal_config['morph'],\n            )\n\n        else:\n            raise ValueError(f'bad gal_type \"{gal_type}\"')\n\n    return galaxy_catalog\n\n\ndef get_fixed_gal_config(config=None):\n    \"\"\"\n    get the configuration for fixed galaxies, with defaults in place\n\n    Parameters\n    ----------\n    config: dict, optional\n        The input config. Over-rides defaults\n\n    Returns\n    -------\n    the config dict\n    \"\"\"\n    out_config = copy.deepcopy(DEFAULT_FIXED_GAL_CONFIG)\n\n    if config is not None:\n        for key in config:\n            if key not in out_config:\n                raise ValueError(\"bad key for fixed gals: '%s'\" % key)\n        out_config.update(config)\n    return out_config\n\n\nclass FixedGalaxyCatalog(object):\n    \"\"\"\n    Galaxies of fixed galsim type, flux, and size and shape.\n\n    Same for all bands\n\n    Parameters\n    ----------\n    rng: np.random.RandomState\n        The random number generator\n    coadd_dim: int\n        dimensions of the coadd\n    layout: string\n        The layout of objects, either 'grid' or 'random'\n    mag: float\n        Magnitude of all objects. Objects brighter than magntiude 17 (e.g., 14\n        since mags are opposite) tend to cause the Rubin Observatory science\n        pipeline detection algorithm to misdetect isolted objects in unphysical\n        ways. This effect causes the shear response to be non-linear and so\n        metadetect will fail. For this reason, you should use the default\n        magnitude of 17 or fainter for this kind of galaxy.\n    hlr: float\n        Half light radius of all objects\n    buff: int, optional\n        Buffer region with no objects, on all sides of image.  Ingored\n        for layout 'grid'.  Default 0.\n    morph: str\n        Galaxy morphology, 'exp', 'dev' or 'bd', 'bdk'.  Default 'exp'\n    \"\"\"\n    def __init__(self, *, rng, coadd_dim, layout, mag, hlr, buff=0, morph='exp'):\n        self.gal_type = 'fixed'\n        self.morph = morph\n        self.mag = mag\n        self.hlr = hlr\n\n        self.shifts_array = get_shifts(\n            rng=rng,\n            coadd_dim=coadd_dim,\n            buff=buff,\n            layout=layout,\n        )\n\n    def __len__(self):\n        return len(self.shifts_array)\n\n    def get_objlist(self, *, survey):\n        \"\"\"\n        get a list of galsim objects\n\n        Parameters\n        ----------\n        band: string\n            Get objects for this band.  For the fixed\n            catalog, the objects are the same for every band\n\n        Returns\n        -------\n        [galsim objects], [shifts]\n        \"\"\"\n\n        flux = survey.get_flux(self.mag)\n\n        sarray = self.shifts_array\n        objlist = []\n        shifts = []\n        for i in range(len(self)):\n            objlist.append(self._get_galaxy(flux))\n            shifts.append(galsim.PositionD(sarray['dx'][i], sarray['dy'][i]))\n\n        return objlist, shifts\n\n    def _get_galaxy(self, flux):\n        \"\"\"\n        get a galaxy object\n\n        Parameters\n        ----------\n        flux: float\n            Flux of object\n\n        Returns\n        --------\n        galsim.GSObject\n        \"\"\"\n\n        if self.morph == 'exp':\n            gal = _generate_exp(hlr=self.hlr, flux=flux)\n        elif self.morph == 'dev':\n            gal = _generate_dev(hlr=self.hlr, flux=flux)\n        elif self.morph == 'bd':\n            gal = _generate_bd(hlr=self.hlr, flux=flux)\n        elif self.morph == 'bdk':\n            gal = _generate_bdk(hlr=self.hlr, flux=flux)\n        else:\n            raise ValueError(f\"bad gal type '{self.morph}'\")\n\n        return gal\n\n\nclass GalaxyCatalog(FixedGalaxyCatalog):\n    \"\"\"\n    Galaxies of fixed galsim type, but varying properties.\n\n    Same for all bands\n\n    Parameters\n    ----------\n    rng: np.random.RandomState\n        The random number generator\n    coadd_dim: int\n        dimensions of the coadd\n    layout: string\n        The layout of objects, either 'grid' or 'random'\n    mag: float\n        Magnitude of all objects. Objects brighter than magntiude 17 (e.g., 14\n        since mags are opposite) tend to cause the Rubin Observatory science\n        pipeline detection algorithm to misdetect isolted objects in unphysical\n        ways. This effect causes the shear response to be non-linear and so\n        metadetect will fail. For this reason, you should use the default\n        magnitude of 17 or fainter for this kind of galaxy.\n    hlr: float\n        Half light radius of all objects\n    buff: int, optional\n        Buffer region with no objects, on all sides of image.  Ingored\n        for layout 'grid'.  Default 0.\n    morph: str\n        Galaxy morphology, 'exp', 'dev' or 'bd', 'bdk'.  Default 'exp'\n    \"\"\"\n    def __init__(self, *, rng, coadd_dim, layout, mag, hlr, buff=0, morph='exp'):\n        super().__init__(\n            rng=rng, coadd_dim=coadd_dim, buff=buff, layout=layout,\n            mag=mag, hlr=hlr, morph=morph,\n        )\n        self.gal_type = 'varying'\n\n        # we use this to ensure the same galaxies are generated in different\n        # bands\n        self.morph_seed = rng.randint(0, 2**31)\n        self.gs_morph_seed = rng.randint(0, 2**31)\n\n    def get_objlist(self, *, survey):\n        \"\"\"\n        get a list of galsim objects\n\n        Parameters\n        ----------\n        band: string\n            Get objects for this band.  For the fixed\n            catalog, the objects are the same for every band\n\n        Returns\n        -------\n        [galsim objects], [shifts]\n        \"\"\"\n\n        self._morph_rng = np.random.RandomState(self.morph_seed)\n        self._gs_morph_rng = galsim.BaseDeviate(seed=self.gs_morph_seed)\n        return super().get_objlist(survey=survey)\n\n    def _get_galaxy(self, flux):\n        \"\"\"\n        get a galaxy object\n\n        Parameters\n        ----------\n        flux: float\n            Flux of object\n\n        Returns\n        --------\n        galsim.GSObject\n        \"\"\"\n\n        if self.morph == 'exp':\n            gal = _generate_exp(\n                hlr=self.hlr, flux=flux, vary=True, rng=self._morph_rng,\n            )\n        elif self.morph == 'dev':\n            gal = _generate_dev(\n                hlr=self.hlr, flux=flux, vary=True, rng=self._morph_rng,\n            )\n        elif self.morph == 'bd':\n            gal = _generate_bd(\n                hlr=self.hlr, flux=flux,\n                vary=True, rng=self._morph_rng,\n            )\n        elif self.morph == 'bdk':\n            gal = _generate_bdk(\n                hlr=self.hlr, flux=flux,\n                vary=True,\n                rng=self._morph_rng, gsrng=self._gs_morph_rng,\n            )\n        else:\n            raise ValueError(f\"bad morph '{self.morph}'\")\n\n        return gal\n\n\ndef _generate_exp(hlr, flux, vary=False, rng=None):\n    gal = Exponential(half_light_radius=hlr, flux=flux)\n\n    if vary:\n        g1, g2 = _generate_g1g2(rng)\n        gal = gal.shear(g1=g1, g2=g2)\n\n    return gal\n\n\ndef _generate_dev(hlr, flux, vary=False, rng=None):\n    gal = DeVaucouleurs(half_light_radius=hlr, flux=flux)\n    if vary:\n        g1, g2 = _generate_g1g2(rng)\n        gal = gal.shear(g1=g1, g2=g2)\n\n    return gal\n\n\ndef _generate_bd(\n    hlr, flux,\n    vary=False,\n    rng=None,\n    max_bulge_shift_frac=0.1,  # fraction of hlr\n    max_bulge_rot=np.pi/4,\n):\n\n    if vary:\n        bulge_frac = _generate_bulge_frac(rng)\n    else:\n        bulge_frac = 0.5\n\n    disk_frac = (1.0 - bulge_frac)\n\n    bulge = DeVaucouleurs(half_light_radius=hlr, flux=flux * bulge_frac)\n    disk = Exponential(half_light_radius=hlr, flux=flux * disk_frac)\n\n    if vary:\n        bulge = _shift_bulge(rng, bulge, hlr, max_bulge_shift_frac)\n\n    if vary:\n        g1disk, g2disk = _generate_g1g2(rng)\n\n        g1bulge, g2bulge = g1disk, g2disk\n        if vary:\n            g1bulge, g2bulge = _rotate_bulge(rng, max_bulge_rot, g1bulge, g2bulge)\n\n        bulge = bulge.shear(g1=g1bulge, g2=g2bulge)\n        disk = disk.shear(g1=g1disk, g2=g2disk)\n\n    return galsim.Add(bulge, disk)\n\n\ndef _generate_bdk(\n    hlr, flux,\n    vary=False,\n    rng=None,\n    gsrng=None,\n    knots_hlr_frac=0.25,\n    max_knots_disk_frac=0.1,  # fraction of disk light\n    max_bulge_shift_frac=0.1,  # fraction of hlr\n    max_bulge_rot=np.pi/4,\n):\n\n    if vary:\n        bulge_frac = _generate_bulge_frac(rng)\n    else:\n        bulge_frac = 0.5\n\n    all_disk_frac = (1.0 - bulge_frac)\n\n    knots_hlr = knots_hlr_frac * hlr\n    if vary:\n        knots_sub_frac = _generate_knots_sub_frac(rng, max_knots_disk_frac)\n    else:\n        knots_sub_frac = max_knots_disk_frac\n\n    disk_frac = (1 - knots_sub_frac) * all_disk_frac\n    knots_frac = knots_sub_frac * all_disk_frac\n\n    bulge = DeVaucouleurs(half_light_radius=hlr, flux=flux * bulge_frac)\n    disk = Exponential(half_light_radius=hlr, flux=flux * disk_frac)\n\n    if gsrng is None:\n        # fixed galaxy, so fix the rng\n        gsrng = galsim.BaseDeviate(123)\n\n    knots = galsim.RandomKnots(\n        npoints=10,\n        half_light_radius=knots_hlr,\n        flux=flux * knots_frac,\n        rng=gsrng,\n    )\n\n    if vary:\n        bulge = _shift_bulge(rng, bulge, hlr, max_bulge_shift_frac)\n\n    if vary:\n        g1disk, g2disk = _generate_g1g2(rng)\n\n        g1bulge, g2bulge = g1disk, g2disk\n        if vary:\n            g1bulge, g2bulge = _rotate_bulge(rng, max_bulge_rot, g1bulge, g2bulge)\n\n        bulge = bulge.shear(g1=g1bulge, g2=g2bulge)\n        disk = disk.shear(g1=g1disk, g2=g2disk)\n        knots = knots.shear(g1=g1disk, g2=g2disk)\n\n    return galsim.Add(bulge, disk, knots)\n\n\ndef _generate_bulge_frac(rng):\n    assert rng is not None, 'send rng to generate bulge fraction'\n    return rng.uniform(low=0.0, high=1.0)\n\n\ndef _generate_g1g2(rng, std=0.2):\n    assert rng is not None, 'send rng to vary shape'\n    while True:\n        g1, g2 = rng.normal(scale=std, size=2)\n        g = np.sqrt(g1**2 + g2**2)\n        if abs(g) < 0.9999:\n            break\n\n    return g1, g2\n\n\ndef _generate_bulge_shift(rng, hlr, max_bulge_shift_frac):\n    bulge_shift = rng.uniform(low=0.0, high=max_bulge_shift_frac*hlr)\n    bulge_shift_angle = rng.uniform(low=0, high=2*np.pi)\n    bulge_shiftx = bulge_shift * np.cos(bulge_shift_angle)\n    bulge_shifty = bulge_shift * np.sin(bulge_shift_angle)\n\n    return bulge_shiftx, bulge_shifty\n\n\ndef _shift_bulge(rng, bulge, hlr, max_bulge_shift_frac):\n    bulge_shiftx, bulge_shifty = _generate_bulge_shift(\n        rng, hlr, max_bulge_shift_frac,\n    )\n    return bulge.shift(bulge_shiftx, bulge_shifty)\n\n\ndef _rotate_bulge(rng, max_bulge_rot, g1, g2):\n    assert rng is not None, 'send rng to rotate bulge'\n    bulge_rot = rng.uniform(low=-max_bulge_rot, high=max_bulge_rot/4)\n    return _rotate_shape(g1, g2, bulge_rot)\n\n\ndef _rotate_shape(g1, g2, theta_radians):\n    twotheta = 2.0 * theta_radians\n\n    cos2angle = np.cos(twotheta)\n    sin2angle = np.sin(twotheta)\n    g1rot = g1 * cos2angle + g2 * sin2angle\n    g2rot = -g1 * sin2angle + g2 * cos2angle\n\n    return g1rot, g2rot\n\n\ndef _generate_knots_sub_frac(rng, max_knots_disk_frac):\n    assert rng is not None, 'send rng to generate knots sub frac'\n    return rng.uniform(low=0.0, high=max_knots_disk_frac)\n\n\nclass FixedPairGalaxyCatalog(FixedGalaxyCatalog):\n    \"\"\"\n    A pair of galaxies of fixed galsim type, flux, and size\n\n    Same for all bands\n\n    Parameters\n    ----------\n    rng: np.random.RandomState\n        The random number generator\n    mag: float\n        Magnitude of all objects. Objects brighter than magntiude 17 (e.g., 14\n        since mags are opposite) tend to cause the Rubin Observatory science\n        pipeline detection algorithm to misdetect isolted objects in unphysical\n        ways. This effect causes the shear response to be non-linear and so\n        metadetect will fail. For this reason, you should use the default\n        magnitude of 17 or fainter for this kind of galaxy.\n    hlr: float\n        Half light radius of all objects\n    sep: float\n        Separation of pair in arcsec\n    morph: str\n        Galaxy morphology, 'exp', 'dev' or 'bd', 'bdk'.  Default 'exp'\n    \"\"\"\n    def __init__(self, *, rng, mag, hlr, sep, morph='exp'):\n        self.gal_type = 'fixed'\n        self.morph = morph\n        self.mag = mag\n        self.hlr = hlr\n        self.rng = rng\n\n        self.shifts_array = get_pair_shifts(\n            rng=rng,\n            sep=sep,\n        )\n\n\nclass PairGalaxyCatalog(GalaxyCatalog):\n    \"\"\"\n    A pair of galaxies of fixed galsim type, flux, and size\n\n    Same for all bands\n\n    Parameters\n    ----------\n    rng: np.random.RandomState\n        The random number generator\n    mag: float\n        Magnitude of all objects. Objects brighter than magntiude 17 (e.g., 14\n        since mags are opposite) tend to cause the Rubin Observatory science\n        pipeline detection algorithm to misdetect isolted objects in unphysical\n        ways. This effect causes the shear response to be non-linear and so\n        metadetect will fail. For this reason, you should use the default\n        magnitude of 17 or fainter for this kind of galaxy.\n    hlr: float\n        Half light radius of all objects\n    sep: float\n        Separation of pair in arcsec\n    morph: str\n        Galaxy morphology, 'exp', 'dev' or 'bd', 'bdk'.  Default 'exp'\n    \"\"\"\n    def __init__(self, *, rng, mag, hlr, sep, morph='exp'):\n        self.gal_type = 'varying'\n        self.morph = morph\n        self.mag = mag\n        self.hlr = hlr\n        self.rng = rng\n\n        self.morph_seed = rng.randint(0, 2**31)\n        self.gs_morph_seed = rng.randint(0, 2**31)\n\n        self.shifts_array = get_pair_shifts(\n            rng=rng,\n            sep=sep,\n        )\n\n\nclass WLDeblendGalaxyCatalog(object):\n    \"\"\"\n    Catalog of galaxies from wldeblend\n\n    Parameters\n    ----------\n    rng: np.random.RandomState\n        The random number generator\n    coadd_dim: int\n        Dimensions of the coadd\n    buff: int, optional\n        Buffer region with no objects, on all sides of image.  Ingored\n        for layout 'grid'.  Default 0.\n    \"\"\"\n    def __init__(self, *, rng, coadd_dim, buff=0):\n        self.gal_type = 'wldeblend'\n        self.rng = rng\n\n        self._wldeblend_cat = read_wldeblend_cat(rng)\n\n        # one square degree catalog, convert to arcmin\n        gal_dens = self._wldeblend_cat.size / (60 * 60)\n        area = ((coadd_dim - 2*buff)*SCALE/60)**2\n        nobj_mean = area * gal_dens\n        nobj = rng.poisson(nobj_mean)\n\n        self.shifts_array = get_shifts(\n            rng=rng,\n            coadd_dim=coadd_dim,\n            buff=buff,\n            layout=\"random\",\n            nobj=nobj,\n        )\n\n        num = len(self)\n        self.indices = self.rng.randint(\n            0,\n            self._wldeblend_cat.size,\n            size=num,\n        )\n\n        self.angles = self.rng.uniform(low=0, high=360, size=num)\n\n    def __len__(self):\n        return len(self.shifts_array)\n\n    def get_objlist(self, *, survey):\n        \"\"\"\n        get a list of galsim objects\n\n        Parameters\n        ----------\n        survey: WLDeblendSurvey\n            The survey object\n\n        Returns\n        -------\n        [galsim objects], [shifts]\n        \"\"\"\n\n        builder = descwl.model.GalaxyBuilder(\n            survey=survey.descwl_survey,\n            no_disk=False,\n            no_bulge=False,\n            no_agn=False,\n            verbose_model=False,\n        )\n\n        band = survey.filter_band\n\n        sarray = self.shifts_array\n        objlist = []\n        shifts = []\n        for i in range(len(self)):\n            objlist.append(self._get_galaxy(builder, band, i))\n            shifts.append(galsim.PositionD(sarray['dx'][i], sarray['dy'][i]))\n\n        return objlist, shifts\n\n    def _get_galaxy(self, builder, band, i):\n        \"\"\"\n        Get a galaxy\n\n        Parameters\n        ----------\n        builder: descwl.model.GalaxyBuilder\n            Builder for this object\n        band: string\n            Band string, e.g. 'r'\n        i: int\n            Index of object\n\n        Returns\n        -------\n        galsim.GSObject\n        \"\"\"\n        index = self.indices[i]\n\n        angle = self.angles[i]\n\n        galaxy = builder.from_catalog(\n            self._wldeblend_cat[index],\n            0,\n            0,\n            band,\n        ).model.rotate(\n            angle * galsim.degrees,\n        )\n\n        return galaxy\n\n\ndef read_wldeblend_cat(rng):\n    \"\"\"\n    Read the catalog from the cache, but update the position angles each time\n\n    Parameters\n    ----------\n    rng: np.random.RandomState\n        The random number generator\n\n    Returns\n    -------\n    array with fields\n    \"\"\"\n    fname = os.path.join(\n        os.environ.get('CATSIM_DIR', '.'),\n        'OneDegSq.fits',\n    )\n\n    # not thread safe\n    cat = cached_catalog_read(fname)\n    return cat\n", "meta": {"hexsha": "bbc34ac66274c1b5320626d4b853ff69b664d796", "size": 19369, "ext": "py", "lang": "Python", "max_stars_repo_path": "descwl_shear_sims/galaxies.py", "max_stars_repo_name": "LSSTDESC/descwl_shear_sims", "max_stars_repo_head_hexsha": "1c696518104b7f301dd6c69571239431c6232110", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "descwl_shear_sims/galaxies.py", "max_issues_repo_name": "LSSTDESC/descwl_shear_sims", "max_issues_repo_head_hexsha": "1c696518104b7f301dd6c69571239431c6232110", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2019-12-10T23:30:27.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-24T13:59:32.000Z", "max_forks_repo_path": "descwl_shear_sims/galaxies.py", "max_forks_repo_name": "LSSTDESC/wl-shear-testing-sims", "max_forks_repo_head_hexsha": "6e4a0baa6f664b5bc52b08b55614eaa58c8b0748", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4737588652, "max_line_length": 82, "alphanum_fraction": 0.5898084568, "include": true, "reason": "import numpy", "num_tokens": 5129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.3174262720448507, "lm_q1q2_score": 0.19288825465901174}}
{"text": "from typing import List\n\nimport numpy\n\nimport torch\n\n\ndef intersect(box_a, box_b):\n    \"\"\" We resize both tensors to [A,B,2] without new malloc:\n    [A,2] -> [A,1,2] -> [A,B,2]\n    [B,2] -> [1,B,2] -> [A,B,2]\n    Then we compute the area of intersect between box_a and box_b.\n    Args:\n      box_a: (tensor) bounding boxes, Shape: [A,4].\n      box_b: (tensor) bounding boxes, Shape: [B,4].\n    Return:\n      (tensor) intersection area, Shape: [A,B].\n    \"\"\"\n    A = box_a.size(0)\n    B = box_b.size(0)\n    max_xy = torch.min(box_a[:, 2:].unsqueeze(1).expand(A, B, 2),\n                       box_b[:, 2:].unsqueeze(0).expand(A, B, 2))\n    min_xy = torch.max(box_a[:, :2].unsqueeze(1).expand(A, B, 2),\n                       box_b[:, :2].unsqueeze(0).expand(A, B, 2))\n    inter = torch.clamp((max_xy - min_xy), min=0)\n    return inter[:, :, 0] * inter[:, :, 1]\n    # inter[:, :, 0] is the width of intersection and inter[:, :, 1] is height\n\n\ndef jaccard_tensor(box_a: torch.Tensor, box_b: torch.Tensor) -> torch.Tensor:\n    \"\"\"Compute the jaccard overlap of two sets of boxes.  The jaccard overlap\n    is simply the intersection over union of two boxes.  Here we operate on\n    ground truth boxes and default boxes.\n    E.g.:\n        A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B)\n    Args:\n        box_a: (tensor) Ground truth bounding boxes, Shape: [A,4]\n        box_b: (tensor) Prior boxes from priorbox layers, Shape: [B,4]\n    Return:\n        jaccard overlap: (tensor) Shape: [A, B]\n    \"\"\"\n    inter = intersect(box_a, box_b)\n    area_a = ((box_a[:, 2] - box_a[:, 0]) *\n              (box_a[:, 3] - box_a[:, 1])).unsqueeze(1).expand_as(inter)  # [A,B]\n    area_b = ((box_b[:, 2] - box_b[:, 0]) *\n              (box_b[:, 3] - box_b[:, 1])).unsqueeze(0).expand_as(inter)  # [A,B]\n    union = area_a + area_b - inter\n    return inter / union  # [A,B]\n\n\nclass YoloV3Loss(torch.nn.Module):\n    \"\"\"\n    YoloV3 损失函数\n    \"\"\"\n\n    def __init__(self, config: dict) -> None:\n        super().__init__()\n\n        self.lambda_xy = 1.0  # 预测框中心误差权重\n        self.lambda_wh = 1.0  # 预测框大小误差权重\n        self.lambda_noobj = 1.0  # 预测框置信度误差权重\n        self.lambda_obj = 1.0  # 预测框置信度误差权重\n        self.lambda_class = 1.0  # 预测框类别误差权重\n        self.lambda_conf = 1.0  # 预测框类别误差权重\n\n        self.normd_anchors = numpy.asarray(config[\"anchors\"]).astype(numpy.float)\n        self.normd_anchors[:, :, 0] /= config[\"image_width\"]\n        self.normd_anchors[:, :, 1] /= config[\"image_height\"]\n        self.normd_anchors = self.normd_anchors.reshape((9, 2))\n        self.normd_anchors_box = torch.cat(\n            (\n                torch.zeros((self.normd_anchors.shape[0], 2)),\n                torch.from_numpy(self.normd_anchors)\n            ), 1)\n\n        self.classes = config[\"classes\"]\n        self.bbox_attrs = 4 + 1 + self.classes\n\n        self.ignore_threshold = 0.5  # iou 忽略的阈值\n\n        self.cuda = config[\"cuda\"]\n\n    def pyramid_target(self, tensord_target_list: List[torch.Tensor]):\n        pyramid_target_list_13 = []\n        pyramid_target_list_26 = []\n        pyramid_target_list_52 = []\n\n        for tensord_target in tensord_target_list:\n            tensord_target_13 = []\n            tensord_target_26 = []\n            tensord_target_52 = []\n\n            target_box = tensord_target[:, :4].clone().detach()\n            target_box[:, 0] = 0\n            target_box[:, 1] = 0\n            normd_anch_ious = jaccard_tensor(target_box, self.normd_anchors_box)\n            max_anch_ious_index = torch.argmax(normd_anch_ious, dim=-1)\n\n            for box_index, anch_index in enumerate(max_anch_ious_index):\n                if anch_index in [0, 1, 2]:\n                    tensord_target_13.append(tensord_target[box_index].numpy())\n                elif anch_index in [3, 4, 5]:\n                    tensord_target_26.append(tensord_target[box_index].numpy())\n                elif anch_index in [6, 7, 8]:\n                    tensord_target_52.append(tensord_target[box_index].numpy())\n                else:\n                    raise Exception(\"unexpected error\")\n\n            pyramid_target_list_13.append(torch.as_tensor(tensord_target_13))\n            pyramid_target_list_26.append(torch.as_tensor(tensord_target_26))\n            pyramid_target_list_52.append(torch.as_tensor(tensord_target_52))\n\n        return pyramid_target_list_13, pyramid_target_list_26, pyramid_target_list_52\n\n    def decode_pyramid_target(self,\n                              pyramid_target_list: List[torch.Tensor],\n                              pyramid_normd_anchors: numpy.ndarray,\n                              pyramid_features: int\n                              ) -> (\n            torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor,\n            torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor,\n            torch.Tensor, torch.Tensor\n    ):\n        assert pyramid_features in [13, 26, 52]\n\n        if pyramid_features == 13:\n            pyramid_anch_index_list = [0, 1, 2]\n        elif pyramid_features == 26:\n            pyramid_anch_index_list = [3, 4, 5]\n        elif pyramid_features == 52:\n            pyramid_anch_index_list = [6, 7, 8]\n        else:\n            raise Exception(\"unexpected error\")\n\n        batch_size = len(pyramid_target_list)\n\n        target_x = torch.zeros(batch_size, 3, pyramid_features, pyramid_features)\n        target_y = torch.zeros(batch_size, 3, pyramid_features, pyramid_features)\n        target_w = torch.zeros(batch_size, 3, pyramid_features, pyramid_features)\n        target_h = torch.zeros(batch_size, 3, pyramid_features, pyramid_features)\n\n        target_loss_weight_xw = torch.zeros(batch_size, 3, pyramid_features, pyramid_features)\n        target_loss_weight_yh = torch.zeros(batch_size, 3, pyramid_features, pyramid_features)\n\n        target_obj_conf = torch.zeros(batch_size, 3, pyramid_features, pyramid_features)\n        target_class_conf_list = torch.zeros(batch_size, 3, pyramid_features, pyramid_features,\n                                             self.classes)\n\n        target_obj_mask = torch.zeros(batch_size, 3, pyramid_features, pyramid_features)\n        target_noobj_mask = torch.ones(batch_size, 3, pyramid_features, pyramid_features)\n\n        # 遍历这一个批次所有的图片\n        for bs_i, pyramid_target in enumerate(pyramid_target_list):\n            if pyramid_target.shape[0] == 0:\n                continue\n\n            truth_feature_box = pyramid_target[:, 0:4] * pyramid_features\n\n            truth_grid_x = torch.floor(truth_feature_box[:, 0]).int()\n            truth_grid_y = torch.floor(truth_feature_box[:, 1]).int()\n\n            truth_x = truth_feature_box[:, 0] - truth_grid_x\n            truth_y = truth_feature_box[:, 1] - truth_grid_y\n\n            target_box = pyramid_target[:, :4].clone().detach()\n            target_box[:, 0] = 0\n            target_box[:, 1] = 0\n            normd_anch_ious = jaccard_tensor(target_box, self.normd_anchors_box)\n            max_anch_ious_index = torch.argmax(normd_anch_ious, dim=-1)\n\n            for box_i, anch_i in enumerate(max_anch_ious_index):\n                if anch_i not in pyramid_anch_index_list:\n                    continue\n                pyramid_anch_i = anch_i % 3\n\n                truth_w_box = torch.log(pyramid_target[box_i][2] / self.normd_anchors[anch_i][0])\n                truth_h_box = torch.log(pyramid_target[box_i][3] / self.normd_anchors[anch_i][1])\n\n                target_x[bs_i, pyramid_anch_i, truth_grid_y[box_i], truth_grid_x[box_i]] = truth_x[box_i]\n                target_y[bs_i, pyramid_anch_i, truth_grid_y[box_i], truth_grid_x[box_i]] = truth_y[box_i]\n\n                target_w[bs_i, pyramid_anch_i, truth_grid_y[box_i], truth_grid_x[box_i]] = truth_w_box\n                target_h[bs_i, pyramid_anch_i, truth_grid_y[box_i], truth_grid_x[box_i]] = truth_h_box\n\n                target_loss_weight_xw[bs_i, pyramid_anch_i, truth_grid_y[box_i], truth_grid_x[box_i]] = \\\n                    pyramid_target[box_i][2]\n                target_loss_weight_yh[bs_i, pyramid_anch_i, truth_grid_y[box_i], truth_grid_x[box_i]] = \\\n                    pyramid_target[box_i][3]\n\n                target_obj_conf[bs_i, pyramid_anch_i, truth_grid_y[box_i], truth_grid_x[box_i]] = 1\n                target_class_conf_list[\n                    bs_i, pyramid_anch_i, truth_grid_y[box_i], truth_grid_x[box_i], pyramid_target[box_i][4].int()] = 1\n\n                target_obj_mask[bs_i, pyramid_anch_i, truth_grid_y[box_i], truth_grid_x[box_i]] = 1\n                target_noobj_mask[bs_i, pyramid_anch_i, truth_grid_y[box_i], truth_grid_x[box_i]] = 0\n\n        # print(\"loss in cuda\") if self.cuda else print(\"loss not in cuda\")\n\n        if self.cuda:\n            return target_x.cuda(), \\\n                   target_y.cuda(), \\\n                   target_w.cuda(), \\\n                   target_h.cuda(), \\\n                   target_loss_weight_xw.cuda(), \\\n                   target_loss_weight_yh.cuda(), \\\n                   target_obj_conf.cuda(), \\\n                   target_class_conf_list.cuda(), \\\n                   target_obj_mask.cuda(), \\\n                   target_noobj_mask.cuda()\n\n        return target_x, \\\n               target_y, \\\n               target_w, \\\n               target_h, \\\n               target_loss_weight_xw, \\\n               target_loss_weight_yh, \\\n               target_obj_conf, \\\n               target_class_conf_list, \\\n               target_obj_mask, \\\n               target_noobj_mask\n\n    def compute_loss(self, predict_feature: torch.Tensor, decoded_target) -> (\n            torch.Tensor, torch.Tensor):\n        (target_x, target_y, target_w, target_h, target_loss_weight_xw, target_loss_weight_yh, target_obj_conf,\n         target_class_conf_list, target_obj_mask, target_noobj_mask) = decoded_target\n\n        predict_feature = predict_feature.view(\n            predict_feature.shape[0],\n            3,\n            self.bbox_attrs,\n            predict_feature.shape[2],\n            predict_feature.shape[3],\n        ).permute(0, 1, 3, 4, 2).contiguous()\n\n        predict_x = torch.sigmoid(predict_feature[..., 0])\n        predict_y = torch.sigmoid(predict_feature[..., 1])\n        predict_w = predict_feature[..., 2]\n        predict_h = predict_feature[..., 3]\n        predict_obj_conf = torch.sigmoid(predict_feature[..., 4])\n        predict_class_conf_list = torch.sigmoid(predict_feature[..., 5:])\n\n        target_loss_scale = 2 - target_loss_weight_xw * target_loss_weight_yh\n\n        loss_x = torch.sum(torch.nn.BCELoss()(predict_x, target_x) * target_loss_scale * target_obj_mask)\n        loss_y = torch.sum(torch.nn.BCELoss()(predict_y, target_y) * target_loss_scale * target_obj_mask)\n\n        loss_w = torch.sum(torch.nn.MSELoss()(predict_w, target_w) * 0.5 * target_loss_scale * target_obj_mask)\n        loss_h = torch.sum(torch.nn.MSELoss()(predict_h, target_h) * 0.5 * target_loss_scale * target_obj_mask)\n\n        loss_conf = self.lambda_obj * torch.sum(\n            torch.nn.BCELoss()(predict_obj_conf, target_obj_mask) * target_obj_mask) + \\\n                    self.lambda_noobj * torch.sum(\n            torch.nn.BCELoss()(predict_obj_conf, target_obj_mask) * target_noobj_mask)\n\n        loss_class = torch.sum(torch.nn.BCELoss()(predict_class_conf_list[target_obj_mask == 1],\n                                                  target_class_conf_list[target_obj_mask == 1]))\n\n        print(\"\\n---------------------------------------\")\n        print(loss_x, loss_y)\n        print(loss_w, loss_h)\n        print(loss_conf, loss_class)\n        print(\"---------------------------------------\\n\")\n\n        loss = loss_x * self.lambda_xy + loss_y * self.lambda_xy + \\\n               loss_w * self.lambda_wh + loss_h * self.lambda_wh + \\\n               loss_conf * self.lambda_conf + loss_class * self.lambda_class\n\n        return loss, torch.sum(target_obj_mask)\n\n    def forward(self, predict_feature_list,\n                tensord_target_list: List[torch.Tensor]) -> torch.Tensor:\n        # pyramid_target_list_13, pyramid_target_list_26, pyramid_target_list_52 = \\\n        #     self.pyramid_target(tensord_target_list)\n        # pyramid_normd_anchors_13, pyramid_normd_anchors_26, pyramid_normd_anchors_52 = \\\n        #     self.normd_anchors[0:3], self.normd_anchors[3, 6], self.normd_anchors[6, 9]\n\n        target_13 = self.decode_pyramid_target(tensord_target_list, None, 13)\n        target_26 = self.decode_pyramid_target(tensord_target_list, None, 26)\n        target_52 = self.decode_pyramid_target(tensord_target_list, None, 52)\n\n        loss_13, loss_13_num = self.compute_loss(predict_feature_list[0], target_13)\n        loss_26, loss_26_num = self.compute_loss(predict_feature_list[1], target_26)\n        loss_52, loss_52_num = self.compute_loss(predict_feature_list[2], target_52)\n\n        loss_list = []\n\n        if not torch.isnan(loss_13):\n            loss_list.append(loss_13)\n        if not torch.isnan(loss_26):\n            loss_list.append(loss_26)\n        if not torch.isnan(loss_52):\n            loss_list.append(loss_52)\n\n        assert len(loss_list) != 0\n\n        loss = sum(loss_list)\n\n        loss_num = loss_13_num + loss_26_num + loss_52_num\n\n        return loss / loss_num\n", "meta": {"hexsha": "0777a5b1c34021c897db562a1a7ae2583828d44c", "size": 13141, "ext": "py", "lang": "Python", "max_stars_repo_path": "model/yolov3loss.py", "max_stars_repo_name": "lilinxi/210318_SimpleYoloV3", "max_stars_repo_head_hexsha": "0fb40075cc3681a0dc46f303afd6b82f910dff52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "model/yolov3loss.py", "max_issues_repo_name": "lilinxi/210318_SimpleYoloV3", "max_issues_repo_head_hexsha": "0fb40075cc3681a0dc46f303afd6b82f910dff52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model/yolov3loss.py", "max_forks_repo_name": "lilinxi/210318_SimpleYoloV3", "max_forks_repo_head_hexsha": "0fb40075cc3681a0dc46f303afd6b82f910dff52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.657807309, "max_line_length": 119, "alphanum_fraction": 0.6077163077, "include": true, "reason": "import numpy", "num_tokens": 3387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.19288825132214757}}
{"text": "import numpy as np\nimport scipy.signal as signal\nfrom scipy.interpolate import interp1d\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nfrom astropy.io import fits\nimport emcee\nimport corner\nimport copy\nimport time\nimport os\nimport sys\nimport smart\n\ndef makeModel(teff, logg=5, metal=0, vsini=1, rv=0, tell_alpha=1.0, airmass=1.0, pwv=0.5, wave_offset=0, flux_offset=0,**kwargs):\n\t\"\"\"\n\tReturn a forward model.\n\n\tParameters\n\t----------\n\tteff   : effective temperature\n\t\n\tdata   : an input science data used for continuum correction\n\n\tOptional Parameters\n\t-------------------\n\t\n\n\tReturns\n\t-------\n\tmodel: a synthesized model\n\t\"\"\"\n\n\t# read in the parameters\n\torder        = kwargs.get('order', '33')\n\tmodelset     = kwargs.get('modelset', 'btsettl08')\n\tinstrument   = kwargs.get('instrument', 'nirspec')\n\tveiling      = kwargs.get('veiling', 0)    # flux veiling parameter\n\tlsf          = kwargs.get('lsf', 4.5)   # instrumental LSF\n\tinclude_fringe_model = kwargs.get('include_fringe_model', False)\n\n\tif instrument == 'apogee':\n\t\ttry:\n\t\t\timport apogee_tools as ap\n\t\texcept ImportError:\n\t\t\tprint('Need to install the package \"apogee_tools\" (https://github.com/jbirky/apogee_tools) \\n')\n\t\txlsf       = kwargs.get('xlsf', np.linspace(-7.,7.,43))   # APOGEE instrumental LSF sampling\n\t\twave_off1  = kwargs.get('wave_off1') # wavelength offset for chip a\n\t\twave_off2  = kwargs.get('wave_off2') # wavelength offset for chip b\n\t\twave_off3  = kwargs.get('wave_off3') # wavelength offset for chip c\n\t\tc0_1       = kwargs.get('c0_1')      # constant flux offset for chip a\n\t\tc0_2       = kwargs.get('c0_2')      # linear flux offset for chip a\n\t\tc1_1       = kwargs.get('c1_1')      # constant flux offset for chip b\n\t\tc1_2       = kwargs.get('c1_2')      # linear flux offset for chip b\n\t\tc2_1       = kwargs.get('c2_1')      # constant flux offset for chip c\n\t\tc2_2       = kwargs.get('c2_2')      # linear flux offset for chip c\n\n\ttell       = kwargs.get('tell', True) # apply telluric\n\t#tell_alpha = kwargs.get('tell_alpha', 1.0) # Telluric alpha power\n\tbinary     = kwargs.get('binary', False) # make a binary model\n\n\t# assume the secondary has the same metallicity\n\tif binary:\n\t\tteff2       = kwargs.get('teff2')\n\t\tlogg2       = kwargs.get('logg2')\n\t\trv2         = kwargs.get('rv2')\n\t\tvsini2      = kwargs.get('vsini2')\n\t\tflux_scale = kwargs.get('flux_scale', 0.8)\n\n\tdata       = kwargs.get('data', None) # for continuum correction and resampling\n\n\toutput_stellar_model = kwargs.get('output_stellar_model', False)\n\t\n\tif data is not None and instrument == 'nirspec':\n\t\torder = data.order\n\t\t# read in a model\n\t\t#print('teff ',teff,'logg ',logg, 'z', z, 'order', order, 'modelset', modelset)\n\t\t#print('teff ',type(teff),'logg ',type(logg), 'z', type(z), 'order', type(order), 'modelset', type(modelset))\n\t\tmodel    = smart.Model(teff=teff, logg=logg, metal=metal, order=str(order), modelset=modelset, instrument=instrument)\n\n\t#elif data is not None and instrument == 'apogee':\n\telif instrument == 'apogee':\n\t\tmodel    = smart.Model(teff=teff, logg=logg, metal=metal, modelset=modelset, instrument=instrument)\n\t\t# Dirty fix here\n\t\tmodel.wave = model.wave[np.where(model.flux != 0)]\n\t\tmodel.flux = model.flux[np.where(model.flux != 0)]\n\n\t\t# apply vmicro\n\t\tvmicro = 2.478 - 0.325*logg\n\t\tmodel.flux = smart.broaden(wave=model.wave, flux=model.flux, vbroad=vmicro, rotate=False, gaussian=True)\n\t\n\telif data is None and instrument == 'nirspec':\n\t\tmodel    = smart.Model(teff=teff, logg=logg, metal=metal, order=str(order), modelset=modelset, instrument=instrument)\n\t\n\t# wavelength offset\n\t#model.wave += wave_offset\n\n\t# apply vsini\n\tmodel.flux = smart.broaden(wave=model.wave, flux=model.flux, vbroad=vsini, rotate=True, gaussian=False)\n\t\n\t# apply rv (including the barycentric correction)\n\tmodel.wave = rvShift(model.wave, rv=rv)\n\t\n\t# flux veiling\n\tmodel.flux += veiling\n\n\t## if binary is True: make a binary model\n\tif binary:\n\t\tmodel2      = smart.Model(teff=teff2, logg=logg2, metal=metal, order=str(order), modelset=modelset, instrument=instrument)\n\t\t# apply vsini\n\t\tmodel2.flux = smart.broaden(wave=model2.wave, flux=model2.flux, vbroad=vsini2, rotate=True, gaussian=False)\n\t\t# apply rv (including the barycentric correction)\n\t\tmodel2.wave = rvShift(model2.wave, rv=rv2)\n\t\t# linearly interpolate the model2 onto the model1 grid\n\t\tfit = interp1d(model2.wave, model2.flux)\n\n\t\tselect_wavelength = np.where( (model.wave < model2.wave[-1]) & (model.wave > model2.wave[0]) )\n\t\tmodel.flux = model.flux[select_wavelength]\n\t\tmodel.wave = model.wave[select_wavelength]\n\n\t\t# combine the models together and scale the secondary flux\n\t\tmodel.flux += flux_scale * fit(model.wave)\n\n\tif output_stellar_model:\n\t\tstellar_model = copy.deepcopy(model)\n\t\tif binary:\n\t\t\tmodel2.flux = flux_scale * fit(model.wave)\n\n\t# apply telluric\n\tif tell is True:\n\t\tmodel = smart.applyTelluric(model=model, tell_alpha=tell_alpha, airmass=airmass, pwv=pwv)\n\n\t# fringe \n\tif include_fringe_model is True:\n\t\t#print('adding the fringe model')\n\t\ts1, s2, s3, s4, s5 = 0, 150, 400, 600, -1\n\t\tpiecewise_fringe_model = [s1, s2, s3, s4, s5]\n\t\tmodel.flux *= smart.double_sine_fringe(model, data, piecewise_fringe_model, teff, logg, vsini, rv, airmass, pwv, wave_offset, flux_offset, lsf, modelset)\n\n\t# instrumental LSF\n\tif instrument == 'nirspec':\n\t\tmodel.flux = smart.broaden(wave=model.wave, flux=model.flux, vbroad=lsf, rotate=False, gaussian=True)\n\telif instrument == 'apogee':\n\t\tmodel.flux = ap.apogee_hack.spec.lsf.convolve(model.wave, model.flux, lsf=lsf, xlsf=xlsf).flatten()\n\t\tmodel.wave = ap.apogee_hack.spec.lsf.apStarWavegrid()\n\t\t# Remove the NANs\n\t\tmodel.wave = model.wave[~np.isnan(model.flux)]\n\t\tmodel.flux = model.flux[~np.isnan(model.flux)]\n\n\tif output_stellar_model:\n\t\tstellar_model.flux = smart.broaden(wave=stellar_model.wave, flux=stellar_model.flux, vbroad=lsf, rotate=False, gaussian=True)\n\t\tif binary:\n\t\t\tmodel2.flux = smart.broaden(wave=model2.wave, flux=model2.flux, vbroad=lsf, rotate=False, gaussian=True)\n\n\t# wavelength offset\n\tmodel.wave += wave_offset\n\n\tif output_stellar_model: \n\t\tstellar_model.wave += wave_offset\n\t\tif binary:\n\t\t\tmodel2.wave = stellar_model.wave\n\n\t# integral resampling\n\tif data is not None:\n\t\tif instrument == 'nirspec':\n\t\t\tmodel.flux = np.array(smart.integralResample(xh=model.wave, yh=model.flux, xl=data.wave))\n\t\t\tmodel.wave = data.wave\n\n\t\t\tif output_stellar_model:\n\t\t\t\tstellar_model.flux = np.array(smart.integralResample(xh=stellar_model.wave, yh=stellar_model.flux, xl=data.wave))\n\t\t\t\tstellar_model.wave = data.wave\n\t\t\t\tif binary:\n\t\t\t\t\tmodel2.flux = np.array(smart.integralResample(xh=model2.wave, yh=model2.flux, xl=data.wave))\n\t\t\t\t\tmodel2.wave = data.wave\n\n\t\t# contunuum correction\n\t\tif data.instrument == 'nirspec':\n\t\t\tniter = 5 # continuum iteration\n\t\t\tif output_stellar_model:\n\t\t\t\tmodel, cont_factor = smart.continuum(data=data, mdl=model, prop=True)\n\t\t\t\tfor i in range(niter):\n\t\t\t\t\tmodel, cont_factor2 = smart.continuum(data=data, mdl=model, prop=True)\n\t\t\t\t\tcont_factor *= cont_factor2\n\t\t\t\tstellar_model.flux *= cont_factor\n\t\t\t\tif binary:\n\t\t\t\t\tmodel2.flux *= cont_factor\n\t\t\telse:\n\t\t\t\tmodel = smart.continuum(data=data, mdl=model)\n\t\t\t\tfor i in range(niter):\n\t\t\t\t\tmodel = smart.continuum(data=data, mdl=model)\n\t\telif data.instrument == 'apogee':\n\t\t\t## set the order in the continuum fit\n\t\t\tdeg         = 5\n\t\t\t## because of the APOGEE bands, continuum is corrected from three pieces of the spectra\n\t\t\tdata0       = copy.deepcopy(data)\n\t\t\tmodel0      = copy.deepcopy(model)\n\n\t\t\t# wavelength offset\n\t\t\tmodel0.wave += wave_off1\n\n\t\t\trange0      = np.where((data0.wave >= data.oriWave0[0][-1]) & (data0.wave <= data.oriWave0[0][0]))\n\t\t\tdata0.wave  = data0.wave[range0]\n\t\t\tdata0.flux  = data0.flux[range0]\n\t\t\tif data0.wave[0] > data0.wave[-1]:\n\t\t\t\tdata0.wave = data0.wave[::-1]\n\t\t\t\tdata0.flux = data0.flux[::-1]\n\t\t\tmodel0.flux = np.array(smart.integralResample(xh=model0.wave, yh=model0.flux, xl=data0.wave))\n\t\t\tmodel0.wave = data0.wave\n\t\t\tmodel0      = smart.continuum(data=data0, mdl=model0, deg=deg)\n\t\t\t# flux corrections\n\t\t\tmodel0.flux = (model0.flux + c0_1) * np.e**(-c0_2)\n\n\t\t\tdata1       = copy.deepcopy(data)\n\t\t\tmodel1      = copy.deepcopy(model)\n\n\t\t\t# wavelength offset\n\t\t\tmodel1.wave += wave_off2\n\n\t\t\trange1      = np.where((data1.wave >= data.oriWave0[1][-1]) & (data1.wave <= data.oriWave0[1][0]))\n\t\t\tdata1.wave  = data1.wave[range1]\n\t\t\tdata1.flux  = data1.flux[range1]\n\t\t\tif data1.wave[0] > data1.wave[-1]:\n\t\t\t\tdata1.wave = data1.wave[::-1]\n\t\t\t\tdata1.flux = data1.flux[::-1]\n\t\t\tmodel1.flux = np.array(smart.integralResample(xh=model1.wave, yh=model1.flux, xl=data1.wave))\n\t\t\tmodel1.wave = data1.wave\n\t\t\tmodel1      = smart.continuum(data=data1, mdl=model1, deg=deg)\n\n\t\t\t# flux corrections\n\t\t\tmodel1.flux = (model1.flux + c1_1) * np.e**(-c1_2)\n\n\t\t\tdata2       = copy.deepcopy(data)\n\t\t\tmodel2      = copy.deepcopy(model)\n\n\t\t\t# wavelength offset\n\t\t\tmodel2.wave += wave_off3\n\n\t\t\trange2      = np.where((data2.wave >= data.oriWave0[2][-1]) & (data2.wave <= data.oriWave0[2][0]))\n\t\t\tdata2.wave  = data2.wave[range2]\n\t\t\tdata2.flux  = data2.flux[range2]\n\t\t\tif data2.wave[0] > data2.wave[-1]:\n\t\t\t\tdata2.wave = data2.wave[::-1]\n\t\t\t\tdata2.flux = data2.flux[::-1]\n\n\t\t\tmodel2.flux = np.array(smart.integralResample(xh=model2.wave, yh=model2.flux, xl=data2.wave))\n\t\t\tmodel2.wave = data2.wave\n\t\t\tmodel2      = smart.continuum(data=data2, mdl=model2, deg=deg)\n\t\t\t# flux corrections\n\t\t\tmodel2.flux = (model2.flux + c2_1) * np.e**(-c2_2)\n\n\t\t\t## scale the flux to be the same as the data\n\t\t\t#model0.flux *= (np.std(data0.flux)/np.std(model0.flux))\n\t\t\t#model0.flux -= np.median(model0.flux) - np.median(data0.flux)\n\n\t\t\t#model1.flux *= (np.std(data1.flux)/np.std(model1.flux))\n\t\t\t#model1.flux -= np.median(model1.flux) - np.median(data1.flux)\n\n\t\t\t#model2.flux *= (np.std(data2.flux)/np.std(model2.flux))\n\t\t\t#model2.flux -= np.median(model2.flux) - np.median(data2.flux)\n\n\t\t\tmodel.flux  = np.array( list(model2.flux) + list(model1.flux) + list(model0.flux) )\n\t\t\tmodel.wave  = np.array( list(model2.wave) + list(model1.wave) + list(model0.wave) )\n\n\tif instrument == 'nirspec':\n\t\t# flux offset\n\t\tmodel.flux += flux_offset\n\t\tif output_stellar_model: \n\t\t\tstellar_model.flux += flux_offset\n\t\t\tif binary:\n\t\t\t\tmodel2.flux += flux_offset\n\t#model.flux **= (1 + flux_exponent_offset)\n\n\tif output_stellar_model:\n\t\tif not binary:\n\t\t\treturn model, stellar_model\n\t\telse:\n\t\t\treturn model, stellar_model, model2\n\telse:\n\t\treturn model\n\n\n# Fringe Model; testing\n\ndef doub_sine(wave, a1, k1, a2, k2):\n    # the initial guess is determined from the best frequency\n    # wave (i.e. kx) multiplicative effects\n    return (1 + a1**2 + 2 * a1*np.sin( k1 * wave )) * ( 1 + a2**2 + 2 * a2 * np.sin( k2*wave ))\n\ndef makeModelFringe(teff, logg=5, metal=0, vsini=1, rv=0, tell_alpha=1.0, airmass=1.0, pwv=0.5, wave_offset=0, flux_offset=0, \n\ta1_1=0.01, k1_1=2.10, a2_1=0.01, k2_1=0.85, a1_2=0.01, k1_2=2.10, a2_2=0.01, k2_2=0.85, \n\ta1_3=0.01, k1_3=2.10, a2_3=0.01, k2_3=0.85, a1_4=0.01, k1_4=2.10, a2_4=0.01, k2_4=0.85, **kwargs):\n\t\"\"\"\n\tReturn a forward model.\n\n\tParameters\n\t----------\n\tteff   : effective temperature\n\t\n\tdata   : an input science data used for continuum correction\n\n\tOptional Parameters\n\t-------------------\n\t\n\n\tReturns\n\t-------\n\tmodel: a synthesized model\n\t\"\"\"\n\n\t# read in the parameters\n\torder        = kwargs.get('order', '33')\n\tmodelset     = kwargs.get('modelset', 'btsettl08')\n\tinstrument   = kwargs.get('instrument', 'nirspec')\n\tveiling      = kwargs.get('veiling', 0)    # flux veiling parameter\n\tlsf          = kwargs.get('lsf', 4.5)   # instrumental LSF\n\n\tif instrument == 'apogee':\n\t\ttry:\n\t\t\timport apogee_tools as ap\n\t\texcept ImportError:\n\t\t\tprint('Need to install the package \"apogee_tools\" (https://github.com/jbirky/apogee_tools) \\n')\n\t\txlsf       = kwargs.get('xlsf', np.linspace(-7.,7.,43))   # APOGEE instrumental LSF sampling\n\t\twave_off1  = kwargs.get('wave_off1') # wavelength offset for chip a\n\t\twave_off2  = kwargs.get('wave_off2') # wavelength offset for chip b\n\t\twave_off3  = kwargs.get('wave_off3') # wavelength offset for chip c\n\t\tc0_1       = kwargs.get('c0_1')      # constant flux offset for chip a\n\t\tc0_2       = kwargs.get('c0_2')      # linear flux offset for chip a\n\t\tc1_1       = kwargs.get('c1_1')      # constant flux offset for chip b\n\t\tc1_2       = kwargs.get('c1_2')      # linear flux offset for chip b\n\t\tc2_1       = kwargs.get('c2_1')      # constant flux offset for chip c\n\t\tc2_2       = kwargs.get('c2_2')      # linear flux offset for chip c\n\n\ttell       = kwargs.get('tell', True) # apply telluric\n\t#tell_alpha = kwargs.get('tell_alpha', 1.0) # Telluric alpha power\n\tbinary     = kwargs.get('binary', False) # make a binary model\n\n\t# assume the secondary has the same metallicity\n\tif binary:\n\t\tteff2       = kwargs.get('teff2')\n\t\tlogg2       = kwargs.get('logg2')\n\t\trv2         = kwargs.get('rv2')\n\t\tvsini2      = kwargs.get('vsini2')\n\t\tflux_scale = kwargs.get('flux_scale', 0.8)\n\n\tdata       = kwargs.get('data', None) # for continuum correction and resampling\n\n\toutput_stellar_model = kwargs.get('output_stellar_model', False)\n\t\n\tif data is not None and instrument == 'nirspec':\n\t\torder = data.order\n\t\t# read in a model\n\t\t#print('teff ',teff,'logg ',logg, 'z', z, 'order', order, 'modelset', modelset)\n\t\t#print('teff ',type(teff),'logg ',type(logg), 'z', type(z), 'order', type(order), 'modelset', type(modelset))\n\t\tmodel    = smart.Model(teff=teff, logg=logg, metal=metal, order=str(order), modelset=modelset, instrument=instrument)\n\n\t#elif data is not None and instrument == 'apogee':\n\telif instrument == 'apogee':\n\t\tmodel    = smart.Model(teff=teff, logg=logg, metal=metal, modelset=modelset, instrument=instrument)\n\t\t# Dirty fix here\n\t\tmodel.wave = model.wave[np.where(model.flux != 0)]\n\t\tmodel.flux = model.flux[np.where(model.flux != 0)]\n\n\t\t# apply vmicro\n\t\tvmicro = 2.478 - 0.325*logg\n\t\tmodel.flux = smart.broaden(wave=model.wave, flux=model.flux, vbroad=vmicro, rotate=False, gaussian=True)\n\t\n\telif data is None and instrument == 'nirspec':\n\t\tmodel    = smart.Model(teff=teff, logg=logg, metal=metal, order=str(order), modelset=modelset, instrument=instrument)\n\t\n\t# wavelength offset\n\t#model.wave += wave_offset\n\n\t# apply vsini\n\tmodel.flux = smart.broaden(wave=model.wave, flux=model.flux, vbroad=vsini, rotate=True, gaussian=False)\n\t\n\t# apply rv (including the barycentric correction)\n\tmodel.wave = rvShift(model.wave, rv=rv)\n\t\n\t# flux veiling\n\tmodel.flux += veiling\n\n\t## if binary is True: make a binary model\n\tif binary:\n\t\tmodel2      = smart.Model(teff=teff2, logg=logg2, metal=metal, order=str(order), modelset=modelset, instrument=instrument)\n\t\t# apply vsini\n\t\tmodel2.flux = smart.broaden(wave=model2.wave, flux=model2.flux, vbroad=vsini2, rotate=True, gaussian=False)\n\t\t# apply rv (including the barycentric correction)\n\t\tmodel2.wave = rvShift(model2.wave, rv=rv2)\n\t\t# linearly interpolate the model2 onto the model1 grid\n\t\tfit = interp1d(model2.wave, model2.flux)\n\n\t\tselect_wavelength = np.where( (model.wave < model2.wave[-1]) & (model.wave > model2.wave[0]) )\n\t\tmodel.flux = model.flux[select_wavelength]\n\t\tmodel.wave = model.wave[select_wavelength]\n\n\t\t# combine the models together and scale the secondary flux\n\t\tmodel.flux += flux_scale * fit(model.wave)\n\n\tif output_stellar_model:\n\t\tstellar_model = copy.deepcopy(model)\n\t\tif binary:\n\t\t\tmodel2.flux = flux_scale * fit(model.wave)\n\n\t# apply telluric\n\tif tell is True:\n\t\tmodel = smart.applyTelluric(model=model, tell_alpha=tell_alpha, airmass=airmass, pwv=pwv)\n\n\t# instrumental LSF\n\tif instrument == 'nirspec':\n\t\tmodel.flux = smart.broaden(wave=model.wave, flux=model.flux, vbroad=lsf, rotate=False, gaussian=True)\n\telif instrument == 'apogee':\n\t\tmodel.flux = ap.apogee_hack.spec.lsf.convolve(model.wave, model.flux, lsf=lsf, xlsf=xlsf).flatten()\n\t\tmodel.wave = ap.apogee_hack.spec.lsf.apStarWavegrid()\n\t\t# Remove the NANs\n\t\tmodel.wave = model.wave[~np.isnan(model.flux)]\n\t\tmodel.flux = model.flux[~np.isnan(model.flux)]\n\n\tif output_stellar_model:\n\t\tstellar_model.flux = smart.broaden(wave=stellar_model.wave, flux=stellar_model.flux, vbroad=lsf, rotate=False, gaussian=True)\n\t\tif binary:\n\t\t\tmodel2.flux = smart.broaden(wave=model2.wave, flux=model2.flux, vbroad=lsf, rotate=False, gaussian=True)\n\n\t# wavelength offset\n\tmodel.wave += wave_offset\n\n\tif output_stellar_model: \n\t\tstellar_model.wave += wave_offset\n\t\tif binary:\n\t\t\tmodel2.wave = stellar_model.wave\n\n\t# integral resampling\n\tif data is not None:\n\t\tif instrument == 'nirspec':\n\t\t\tmodel.flux = np.array(smart.integralResample(xh=model.wave, yh=model.flux, xl=data.wave))\n\t\t\tmodel.wave = data.wave\n\n\t\t\tif output_stellar_model:\n\t\t\t\tstellar_model.flux = np.array(smart.integralResample(xh=stellar_model.wave, yh=stellar_model.flux, xl=data.wave))\n\t\t\t\tstellar_model.wave = data.wave\n\t\t\t\tif binary:\n\t\t\t\t\tmodel2.flux = np.array(smart.integralResample(xh=model2.wave, yh=model2.flux, xl=data.wave))\n\t\t\t\t\tmodel2.wave = data.wave\n\n\t\t# fringe modeling\n\t\tif instrument == 'nirspec':\n\t\t\t# Define the four piece-wise fringe model to include the k(wavelength) variation.\n\t\t\ts1, s2, s3, s4, s5 = 0, 200, 400, 600, -1\n\t\n\t\t\tmodel.flux[s1:s2] = model.flux[s1:s2] * doub_sine(wave=model.wave[s1:s2], a1=a1_1, k1=k1_1, a2=a2_1, k2=k2_1)\n\t\t\tmodel.flux[s2:s3] = model.flux[s2:s3] * doub_sine(wave=model.wave[s2:s3], a1=a1_2, k1=k1_2, a2=a2_2, k2=k2_2)\n\t\t\tmodel.flux[s3:s4] = model.flux[s3:s4] * doub_sine(wave=model.wave[s3:s4], a1=a1_3, k1=k1_3, a2=a2_3, k2=k2_3)\n\t\t\tmodel.flux[s4:s5] = model.flux[s4:s5] * doub_sine(wave=model.wave[s4:s5], a1=a1_4, k1=k1_4, a2=a2_4, k2=k2_4)\n\t\n\t\t\tif output_stellar_model:\n\t\t\t\tstellar_model.flux[s1:s2] = stellar_model.flux[s1:s2] * doub_sine(wave=model.wave[s1:s2], a1=a1_1, k1=k1_1, a2=a2_1, k2=k2_1)\n\t\t\t\tstellar_model.flux[s2:s3] = stellar_model.flux[s2:s3] * doub_sine(wave=model.wave[s2:s3], a1=a1_2, k1=k1_2, a2=a2_2, k2=k2_2)\n\t\t\t\tstellar_model.flux[s3:s4] = stellar_model.flux[s3:s4] * doub_sine(wave=model.wave[s3:s4], a1=a1_3, k1=k1_3, a2=a2_3, k2=k2_3)\n\t\t\t\tstellar_model.flux[s4:s5] = stellar_model.flux[s4:s5] * doub_sine(wave=model.wave[s4:s5], a1=a1_4, k1=k1_4, a2=a2_4, k2=k2_4)\n\n\t\t# contunuum correction\n\t\tif data.instrument == 'nirspec':\n\t\t\tniter = 5 # continuum iteration\n\t\t\tif output_stellar_model:\n\t\t\t\tmodel, cont_factor = smart.continuum(data=data, mdl=model, prop=True)\n\t\t\t\tfor i in range(niter):\n\t\t\t\t\tmodel, cont_factor2 = smart.continuum(data=data, mdl=model, prop=True)\n\t\t\t\t\tcont_factor *= cont_factor2\n\t\t\t\tstellar_model.flux *= cont_factor\n\t\t\t\tif binary:\n\t\t\t\t\tmodel2.flux *= cont_factor\n\t\t\telse:\n\t\t\t\tmodel = smart.continuum(data=data, mdl=model)\n\t\t\t\tfor i in range(niter):\n\t\t\t\t\tmodel = smart.continuum(data=data, mdl=model)\n\n\t\telif data.instrument == 'apogee':\n\t\t\t## set the order in the continuum fit\n\t\t\tdeg         = 5\n\t\t\t## because of the APOGEE bands, continuum is corrected from three pieces of the spectra\n\t\t\tdata0       = copy.deepcopy(data)\n\t\t\tmodel0      = copy.deepcopy(model)\n\n\t\t\t# wavelength offset\n\t\t\tmodel0.wave += wave_off1\n\n\t\t\trange0      = np.where((data0.wave >= data.oriWave0[0][-1]) & (data0.wave <= data.oriWave0[0][0]))\n\t\t\tdata0.wave  = data0.wave[range0]\n\t\t\tdata0.flux  = data0.flux[range0]\n\t\t\tif data0.wave[0] > data0.wave[-1]:\n\t\t\t\tdata0.wave = data0.wave[::-1]\n\t\t\t\tdata0.flux = data0.flux[::-1]\n\t\t\tmodel0.flux = np.array(smart.integralResample(xh=model0.wave, yh=model0.flux, xl=data0.wave))\n\t\t\tmodel0.wave = data0.wave\n\t\t\tmodel0      = smart.continuum(data=data0, mdl=model0, deg=deg)\n\t\t\t# flux corrections\n\t\t\tmodel0.flux = (model0.flux + c0_1) * np.e**(-c0_2)\n\n\t\t\tdata1       = copy.deepcopy(data)\n\t\t\tmodel1      = copy.deepcopy(model)\n\n\t\t\t# wavelength offset\n\t\t\tmodel1.wave += wave_off2\n\n\t\t\trange1      = np.where((data1.wave >= data.oriWave0[1][-1]) & (data1.wave <= data.oriWave0[1][0]))\n\t\t\tdata1.wave  = data1.wave[range1]\n\t\t\tdata1.flux  = data1.flux[range1]\n\t\t\tif data1.wave[0] > data1.wave[-1]:\n\t\t\t\tdata1.wave = data1.wave[::-1]\n\t\t\t\tdata1.flux = data1.flux[::-1]\n\t\t\tmodel1.flux = np.array(smart.integralResample(xh=model1.wave, yh=model1.flux, xl=data1.wave))\n\t\t\tmodel1.wave = data1.wave\n\t\t\tmodel1      = smart.continuum(data=data1, mdl=model1, deg=deg)\n\n\t\t\t# flux corrections\n\t\t\tmodel1.flux = (model1.flux + c1_1) * np.e**(-c1_2)\n\n\t\t\tdata2       = copy.deepcopy(data)\n\t\t\tmodel2      = copy.deepcopy(model)\n\n\t\t\t# wavelength offset\n\t\t\tmodel2.wave += wave_off3\n\n\t\t\trange2      = np.where((data2.wave >= data.oriWave0[2][-1]) & (data2.wave <= data.oriWave0[2][0]))\n\t\t\tdata2.wave  = data2.wave[range2]\n\t\t\tdata2.flux  = data2.flux[range2]\n\t\t\tif data2.wave[0] > data2.wave[-1]:\n\t\t\t\tdata2.wave = data2.wave[::-1]\n\t\t\t\tdata2.flux = data2.flux[::-1]\n\n\t\t\tmodel2.flux = np.array(smart.integralResample(xh=model2.wave, yh=model2.flux, xl=data2.wave))\n\t\t\tmodel2.wave = data2.wave\n\t\t\tmodel2      = smart.continuum(data=data2, mdl=model2, deg=deg)\n\t\t\t# flux corrections\n\t\t\tmodel2.flux = (model2.flux + c2_1) * np.e**(-c2_2)\n\n\t\t\t## scale the flux to be the same as the data\n\t\t\t#model0.flux *= (np.std(data0.flux)/np.std(model0.flux))\n\t\t\t#model0.flux -= np.median(model0.flux) - np.median(data0.flux)\n\n\t\t\t#model1.flux *= (np.std(data1.flux)/np.std(model1.flux))\n\t\t\t#model1.flux -= np.median(model1.flux) - np.median(data1.flux)\n\n\t\t\t#model2.flux *= (np.std(data2.flux)/np.std(model2.flux))\n\t\t\t#model2.flux -= np.median(model2.flux) - np.median(data2.flux)\n\n\t\t\tmodel.flux  = np.array( list(model2.flux) + list(model1.flux) + list(model0.flux) )\n\t\t\tmodel.wave  = np.array( list(model2.wave) + list(model1.wave) + list(model0.wave) )\n\n\tif instrument == 'nirspec':\n\t\t# flux offset\n\t\tmodel.flux += flux_offset\n\t\tif output_stellar_model: \n\t\t\tstellar_model.flux += flux_offset\n\t\t\tif binary:\n\t\t\t\tmodel2.flux += flux_offset\n\t#model.flux **= (1 + flux_exponent_offset)\n\n\tif output_stellar_model:\n\t\tif not binary:\n\t\t\treturn model, stellar_model\n\t\telse:\n\t\t\treturn model, stellar_model, model2\n\telse:\n\t\treturn model \n\n# Fringe Model; testing\n\ndef rvShift(wavelength, rv):\n\t\"\"\"\n\tPerform the radial velocity correction.\n\n\tParameters\n\t----------\n\twavelength \t: \tnumpy array \n\t\t\t\t\tmodel wavelength (in Angstroms)\n\n\trv \t\t\t: \tfloat\n\t\t\t\t\tradial velocity shift (in km/s)\n\n\tReturns\n\t-------\n\twavelength \t: \tnumpy array \n\t\t\t\t\tshifted model wavelength (in Angstroms)\n\t\"\"\"\n\treturn wavelength * ( 1 + rv / 299792.458)\n\ndef applyTelluric(model, tell_alpha=1.0, airmass=1.5, pwv=0.5):\n\t\"\"\"\n\tApply the telluric model on the science model.\n\n\tParameters\n\t----------\n\tmodel \t:\tmodel object\n\t\t\t\tBT Settl model\n\talpha \t: \tfloat\n\t\t\t\ttelluric scaling factor (the power on the flux)\n\n\tReturns\n\t-------\n\tmodel \t: \tmodel object\n\t\t\t\tBT Settl model times the corresponding model\n\n\t\"\"\"\n\t# read in a telluric model\n\twavelow  = model.wave[0] - 10\n\twavehigh = model.wave[-1] + 10\n\t#telluric_model = smart.getTelluric(wavelow=wavelow, wavehigh=wavehigh, alpha=alpha, airmass=airmass)\n\n\ttelluric_model = smart.Model()\n\ttelluric_model.wave, telluric_model.flux = \tsmart.InterpTelluricModel(wavelow=wavelow, wavehigh=wavehigh, airmass=airmass, pwv=pwv)\n\n\t# apply the telluric alpha parameter\n\ttelluric_model.flux = telluric_model.flux**(tell_alpha)\n\n\t#if len(model.wave) > len(telluric_model.wave):\n\t#\tprint(\"The model has a higher resolution ({}) than the telluric model ({}).\"\\\n\t#\t\t.format(len(model.wave),len(telluric_model.wave)))\n\t#\tmodel.flux = np.array(smart.integralResample(xh=model.wave, \n\t#\t\tyh=model.flux, xl=telluric_model.wave))\n\t#\tmodel.wave = telluric_model.wave\n\t#\tmodel.flux *= telluric_model.flux\n\n\t#elif len(model.wave) < len(telluric_model.wave):\n\t## This should be always true\n\ttelluric_model.flux = np.array(smart.integralResample(xh=telluric_model.wave, yh=telluric_model.flux, xl=model.wave))\n\ttelluric_model.wave = model.wave\n\tmodel.flux *= telluric_model.flux\n\n\t#elif len(model.wave) == len(telluric_model.wave):\n\t#\tmodel.flux *= telluric_model.flux\n\t\t\n\treturn model\n\ndef convolveTelluric(lsf, telluric_data, alpha=1.0, airmass='1.0', pwv='1.5'):\n\t\"\"\"\n\tReturn a convolved telluric transmission model given a telluric data and lsf.\n\t\"\"\"\n\t# get a telluric standard model\n\twavelow               = telluric_data.wave[0]  - 50\n\twavehigh              = telluric_data.wave[-1] + 50\n\ttelluric_model        = smart.getTelluric(wavelow=wavelow,wavehigh=wavehigh, airmass=airmass, pwv=pwv)\n\ttelluric_model.flux **= alpha\n\t# lsf\n\ttelluric_model.flux = smart.broaden(wave=telluric_model.wave, flux=telluric_model.flux, \n\t\tvbroad=lsf, rotate=False, gaussian=True)\n\t# resample\n\ttelluric_model.flux = np.array(smart.integralResample(xh=telluric_model.wave, \n\t\tyh=telluric_model.flux, xl=telluric_data.wave))\n\ttelluric_model.wave = telluric_data.wave\n\treturn telluric_model\n\ndef getLSF2(telluric_data, continuum=True, test=False, save_path=None):\n\t\"\"\"\n\tReturn a best LSF value from a telluric data.\n\t\"\"\"\n\t\n\tdata = copy.deepcopy(telluric_data)\n\n\tdef bestParams(data, i, alpha, c2, c0):\n\n\t\tdata2          = copy.deepcopy(data)\n\t\tdata2.wave     = data2.wave + c0\n\t\ttelluric_model = smart.convolveTelluric(i, data2, alpha=alpha)\n\t\tmodel          = smart.continuum(data=data2, mdl=telluric_model)\n\t\t#plt.figure(2)\n\t\t#plt.plot(model.wave, model.flux+c2, 'r-', alpha=0.5)\n\t\t#plt.plot(data.wave*c1+c0, data.flux, 'b-', alpha=0.5)\n\t\t#plt.close()\n\t\t#plt.show()\n\t\t#sys.exit()\n\t\treturn model.flux + c2\n\n\tdef bestParams2(theta, data):\n\n\t\ti, alpha, c2, c0, c1 = theta \n\t\tdata2                = copy.deepcopy(data)\n\t\tdata2.wave           = data2.wave*c1 + c0\n\t\ttelluric_model       = smart.convolveTelluric(i, data2, alpha=alpha)\n\t\tmodel                = smart.continuum(data=data2, mdl=telluric_model)\n\t\treturn np.sum(data.flux - (model.flux + c2))**2\n\n\tfrom scipy.optimize import curve_fit, minimize\n\n\tpopt, pcov = curve_fit(bestParams, data, data.flux, p0=[4.01, 1.01, 0.01, 1.01], maxfev=1000000, epsfcn=0.1)\n\n\t#nll = lambda *args: bestParams2(*args)\n\t#results = minimize(nll, [3., 1., 0.1, -10., 1.], args=(data))\n\t#popt = results['x']\n\n\tdata.wave      = data.wave+popt[3]\n\n\ttelluric_model = smart.convolveTelluric(popt[0], data, alpha=popt[1])\n\tmodel          = smart.continuum(data=data, mdl=telluric_model)\n\n\t#model.flux * np.e**(-popt[2]) + popt[3]\n\tmodel.flux + popt[2]\n\n\treturn popt[0]\n\ndef getLSF(telluric_data, alpha=1.0, continuum=True,test=False,save_path=None):\n\t\"\"\"\n\tReturn a best LSF value from a telluric data.\n\t\"\"\"\n\tlsf_list = []\n\ttest_lsf = np.arange(3.0,13.0,0.1)\n\t\n\tdata = copy.deepcopy(telluric_data)\n\tif continuum is True:\n\t\tdata = smart.continuumTelluric(data=data)\n\n\tdata.flux **= alpha\n\tfor i in test_lsf:\n\t\ttelluric_model = smart.convolveTelluric(i,data)\n\t\tif telluric_data.order == 59:\n\t\t\ttelluric_model.flux **= 3\n\t\t\t# mask hydrogen absorption feature\n\t\t\tdata2          = copy.deepcopy(data)\n\t\t\ttell_mdl       = copy.deepcopy(telluric_model)\n\t\t\tmask_pixel     = 450\n\t\t\tdata2.wave     = data2.wave[mask_pixel:]\n\t\t\tdata2.flux     = data2.flux[mask_pixel:]\n\t\t\tdata2.noise    = data2.noise[mask_pixel:]\n\t\t\ttell_mdl.wave  = tell_mdl.wave[mask_pixel:]\n\t\t\ttell_mdl.flux  = tell_mdl.flux[mask_pixel:]\n\n\t\t\tchisquare = smart.chisquare(data2,tell_mdl)\n\n\t\telse:\n\t\t\tchisquare = smart.chisquare(data,telluric_model)\n\t\tlsf_list.append([chisquare,i])\n\n\t\tif test is True:\n\t\t\tplt.plot(telluric_model.wave,telluric_model.flux+(i-3)*10+1,\n\t\t\t\t'r-',alpha=0.5)\n\n\tif test is True:\n\t\tplt.plot(data.wave,data.flux,\n\t\t\t'k-',label='telluric data',alpha=0.5)\n\t\tplt.title(\"Test LSF\",fontsize=15)\n\t\tplt.xlabel(\"Wavelength ($\\AA$)\",fontsize=12)\n\t\tplt.ylabel(\"Transmission + Offset\",fontsize=12)\n\t\tplt.minorticks_on()\n\t\tif save_path is not None:\n\t\t\tplt.savefig(save_path+\\\n\t\t\t\t\"/{}_O{}_lsf_data_mdl.png\"\\\n\t\t\t\t.format(data.name, data.order))\n\t\t#plt.show()\n\t\tplt.close()\n\n\t\tfig, ax = plt.subplots()\n\t\tfor i in range(len(lsf_list)):\n\t\t\tax.plot(lsf_list[i][1],lsf_list[i][0],'k.',alpha=0.5)\n\t\tax.plot(min(lsf_list)[1],min(lsf_list)[0],'r.',\n\t\t\tlabel=\"best LSF {} km/s\".format(min(lsf_list)[1]))\n\t\tax.set_xlabel(\"LSF (km/s)\",fontsize=12)\n\t\tax.set_ylabel(\"$\\chi^2$\",fontsize=11)\n\t\tplt.minorticks_on()\n\t\tplt.legend(fontsize=10)\n\t\tif save_path is not None:\n\t\t\tplt.savefig(save_path+\\\n\t\t\t\t\"/{}_O{}_lsf_chi2.png\"\\\n\t\t\t\t.format(data.name, data.order))\n\t\t#plt.show()\n\t\tplt.close()\n\n\tlsf = min(lsf_list)[1]\n\n\tif telluric_data.order == 61 or telluric_data.order == 62 \\\n\tor telluric_data.order == 63: #or telluric_data.order == 64:\n\t\tlsf = 5.5\n\t\tprint(\"The LSF is obtained from orders 60 and 65 (5.5 km/s).\")\n\n\treturn lsf\n\ndef getAlpha(telluric_data,lsf,continuum=True,test=False,save_path=None):\n\t\"\"\"\n\tReturn a best alpha value from a telluric data.\n\t\"\"\"\n\talpha_list = []\n\ttest_alpha = np.arange(0.1,7,0.1)\n\n\tdata = copy.deepcopy(telluric_data)\n\tif continuum is True:\n\t\tdata = smart.continuumTelluric(data=data)\n\n\tfor i in test_alpha:\n\t\ttelluric_model = smart.convolveTelluric(lsf,data,\n\t\t\talpha=i)\n\t\t#telluric_model.flux **= i \n\t\tif data.order == 59:\n\t\t\t# mask hydrogen absorption feature\n\t\t\tdata2          = copy.deepcopy(data)\n\t\t\ttell_mdl       = copy.deepcopy(telluric_model)\n\t\t\tmask_pixel     = 450\n\t\t\tdata2.wave     = data2.wave[mask_pixel:]\n\t\t\tdata2.flux     = data2.flux[mask_pixel:]\n\t\t\tdata2.noise    = data2.noise[mask_pixel:]\n\t\t\ttell_mdl.wave  = tell_mdl.wave[mask_pixel:]\n\t\t\ttell_mdl.flux  = tell_mdl.flux[mask_pixel:]\n\n\t\t\tchisquare = smart.chisquare(data2,tell_mdl)\n\n\t\telse:\n\t\t\tchisquare = smart.chisquare(data,telluric_model)\n\t\talpha_list.append([chisquare,i])\n\n\t\tif test is True:\n\t\t\tplt.plot(telluric_model.wave,telluric_model.flux+i*10,\n\t\t\t\t'k-',alpha=0.5)\n\n\tif test is True:\n\t\tplt.plot(telluric_data.wave,telluric_data.flux,\n\t\t\t'r-',alpha=0.5)\n\t\tplt.rc('font', family='sans-serif')\n\t\tplt.title(\"Test Alpha\",fontsize=15)\n\t\tplt.xlabel(\"Wavelength ($\\AA$)\",fontsize=12)\n\t\tplt.ylabel(\"Transmission + Offset\",fontsize=12)\n\t\tplt.minorticks_on()\n\t\tif save_path is not None:\n\t\t\tplt.savefig(save_path+\\\n\t\t\t\t\"/{}_O{}_alpha_data_mdl.png\"\\\n\t\t\t\t.format(telluric_data.name,\n\t\t\t\t\ttelluric_data.order))\n\t\tplt.show()\n\t\tplt.close()\n\n\t\tfig, ax = plt.subplots()\n\t\tplt.rc('font', family='sans-serif')\n\t\tfor i in range(len(alpha_list)):\n\t\t\tax.plot(alpha_list[i][1],alpha_list[i][0],'k.',alpha=0.5)\n\t\tax.plot(min(alpha_list)[1],min(alpha_list)[0],'r.',\n\t\t\tlabel=\"best alpha {}\".format(min(alpha_list)[1]))\n\t\tax.set_xlabel(r\"$\\alpha$\",fontsize=12)\n\t\tax.set_ylabel(\"$\\chi^2$\",fontsize=12)\n\t\tplt.minorticks_on()\n\t\tplt.legend(fontsize=10)\n\t\tif save_path is not None:\n\t\t\tplt.savefig(save_path+\\\n\t\t\t\t\"/{}_O{}_alpha_chi2.png\"\\\n\t\t\t\t.format(telluric_data.name,\n\t\t\t\t\ttelluric_data.order))\n\t\tplt.show()\n\t\tplt.close()\n\n\talpha = min(alpha_list)[1]\n\n\treturn alpha\n\ndef getFringeFrequecy(tell_data, test=False):\n\t\"\"\"\n\tUse the Lomb-Scargle Periodogram to identify \n\tthe fringe pattern.\n\t\"\"\"\n\ttell_sp  = copy.deepcopy(tell_data)\n\n\t## continuum correction\n\ttell_sp  = smart.continuumTelluric(data=tell_sp, order=tell_sp.order)\n\n\t## get a telluric model\n\tlsf      = smart.getLSF(tell_sp)\n\talpha    = smart.getAlpha(tell_sp,lsf)\n\ttell_mdl = smart.convolveTelluric(lsf=lsf,\n\t\ttelluric_data=tell_sp,alpha=alpha)\n\n\t## fit the fringe pattern in the residual\n\tpgram_x = np.array(tell_sp.wave,float)[10:-10]\n\tpgram_y = np.array(tell_sp.flux - tell_mdl.flux,float)[10:-10]\n\toffset  = np.mean(pgram_y)\n\tpgram_y -= offset\n\tmask    = np.where(pgram_y - 1.5 * np.absolute(np.std(pgram_y)) > 0)\n\tpgram_x = np.delete(pgram_x, mask)\n\tpgram_y = np.delete(pgram_y, mask)\n\tpgram_x = np.array(pgram_x, float)\n\tpgram_y = np.array(pgram_y, float)\n\n\t#f = np.lismartace(0.01,10,100000)\n\tf = np.lismartace(1.0,10,100000)\n\n\t## Lomb Scargle Periodogram\n\tpgram = signal.lombscargle(pgram_x, pgram_y, f)\n\n\tif test:\n\t\tfig, ax = plt.subplots(figsize=(16,6))\n\t\tax.plot(f,pgram, 'k-', label='residual',alpha=0.5)\n\t\tax.set_xlabel('frequency')\n\t\tplt.legend()\n\t\tplt.show()\n\t\tplt.close()\n\n\treturn f[np.argmax(pgram)]\n\ndef initModelFit(sci_data, lsf, modelset='btsettl08'):\n\t\"\"\"\n\tConduct simple chisquare fit to obtain the initial parameters\n\tfor the forward modeling MCMC.\n\n\tThe function would calculate the chisquare for teff, logg, vini, rv, and alpha.\n\n\tParameters\n\t----------\n\tdata \t\t\t\t:\tspectrum object\n\t\t\t\t\t\t\tinput science data\n\n\tlsf \t\t\t\t:\tfloat\n\t\t\t\t\t\t\tline spread function for the NIRSPEC\n\n\tReturns\n\t-------\n\tbest_params_dic \t:\tdic\n\t\t\t\t\t\t\ta dictionary that stores the best parameters for \n\t\t\t\t\t\t\tteff, logg, vsini, rv, and alpha\n\n\tchisquare \t\t\t:\tint\n\t\t\t\t\t\t\tminimum chisquare\n\n\t\"\"\"\n\tdata            = copy.deepcopy(sci_data)\n\n\t## set up the parameter grid for chisquare computation\n\tteff_array      = np.arange(1200,3001,100)\n\tlogg_array      = np.arange(3.5,5.51,0.5)\n\tvsini_array     = np.arange(10,101,10)\n\trv_array        = np.arange(-200,201,50)\n\talpha_array     = np.arange(0.5,2.01,0.5)\n\tchisquare_array = np.empty(len(teff_array)*len(logg_array)*len(vsini_array)*len(rv_array)*len(alpha_array))\\\n\t.reshape(len(teff_array),len(logg_array),len(vsini_array),len(rv_array),len(alpha_array))\n\n\ttime1 = time.time()\n\tfor i, teff in enumerate(teff_array):\n\t\tfor j, logg in enumerate(logg_array):\n\t\t\tfor k, vsini in enumerate(vsini_array):\n\t\t\t\tfor l, rv in enumerate(rv_array):\n\t\t\t\t\tfor m, alpha in enumerate(alpha_array):\n\t\t\t\t\t\tmodel = smart.makeModel(teff, logg, 0.0, vsini, rv, alpha, 0, 0,\n\t\t\t\t\t\t\tlsf=lsf, order=str(data.order), data=data, modelset=modelset)\n\t\t\t\t\t\tchisquare_array[i,j,k,l,m] = smart.chisquare(data, model)\n\ttime2 = time.time()\n\tprint(\"total time:\",time2-time1)\n\n\tind = np.unravel_index(np.argmin(chisquare_array, axis=None), chisquare_array.shape)\n\tprint(\"ind \",ind)\n\tchisquare       = chisquare_array[ind]\n\n\tbest_params_dic = {'teff':teff_array[ind[0]], 'logg':logg_array[ind[1]], \n\t'vsini':vsini_array[ind[2]], 'rv':rv_array[ind[3]], 'alpha':alpha_array[ind[4]]}\n\n\tprint(best_params_dic, chisquare)\n\n\treturn best_params_dic , chisquare\n\n", "meta": {"hexsha": "4a31a8e19d55d7ec282b17b451fbae2ca9a602b3", "size": 33577, "ext": "py", "lang": "Python", "max_stars_repo_path": "smart/forward_model/model_fit.py", "max_stars_repo_name": "chihchunhsu/smart", "max_stars_repo_head_hexsha": "c4d5668a0c44e9780290f7f7eba24726f5262b97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-01-21T09:09:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T18:24:02.000Z", "max_issues_repo_path": "smart/forward_model/model_fit.py", "max_issues_repo_name": "chihchunhsu/smart", "max_issues_repo_head_hexsha": "c4d5668a0c44e9780290f7f7eba24726f5262b97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-02-07T19:03:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T01:21:56.000Z", "max_forks_repo_path": "smart/forward_model/model_fit.py", "max_forks_repo_name": "chihchunhsu/smart", "max_forks_repo_head_hexsha": "c4d5668a0c44e9780290f7f7eba24726f5262b97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-22T21:54:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-11T05:16:53.000Z", "avg_line_length": 35.2699579832, "max_line_length": 155, "alphanum_fraction": 0.683116419, "include": true, "reason": "import numpy,import scipy,from scipy,from astropy", "num_tokens": 11036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.19288825132214757}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"\ndust --- Models for dust\n========================\n\n.. autosummary::\n   :toctree: generated/\n\n   Activity\n   --------\n   acrit\n\n   Dust Models\n   -----------\n   AfrhoRadiation\n   AfrhoScattered\n   AfrhoThermal\n\n   Phase functions\n   ---------------\n   phaseK\n   phaseH\n   phaseHM\n\n\"\"\"\n\nimport numpy as np\nimport astropy.units as u\nfrom astropy.units import Quantity\n\n__all__ = [\n    'acrit',\n\n    'AfrhoRadiation',\n    'AfrhoScattered',\n    'AfrhoThermal',\n\n    'phaseK',\n    'phaseH',\n    'phaseHM'\n]\n\ndef acrit(Q, vth, R, rho_g=Quantity(1, u.g / u.cm**3),\n          rho_n=Quantity(0.3, u.g / u.cm**3), f_active=1.0):\n    \"\"\"Maximum liftable grain radius from a spherical nucleus.\n\n    See Meech and Svoren 2004, Comets II.\n\n    Parameters\n    ----------\n    Q : Quantity\n      Mass production rate of the driving gas.\n    vth : Quantity\n      Gas expansion speed.\n    R : Quantity\n      Nucleus radius.\n    rho_g : Quantity, optional\n      Grain density.\n    rho_n : Quantity, optional\n      Nucleus mean density.\n    f_active : float, optional\n      Active fraction of the nucleus.\n    \n    Returns\n    -------\n    a : Quantity\n      Maximum liftable grain radius.\n\n    \"\"\"\n\n    from numpy import pi\n    import astropy.constants as c\n\n    a = 9 * Q * vth / (64 * pi**2 * rho_g * rho_n * R**3 * c.G)\n    return a.to(u.um)\n\nclass AfrhoRadiation(object):\n    \"\"\"Light from a comet coma parameterized by Afrho, or similar.\n\n    Methods\n    -------\n    fluxd : Total flux density from the object.\n\n    Notes\n    -----\n    Afrho should refer to the value at zero phase angle.\n\n    Inheriting classes should override `fluxd`, and `__init__`\n    functions.  `__init__` should take a single argument, `Afrho` (or\n    equivalent) as a Quantity.\n\n    As much as possible, keyword arguments must have the same meaning\n    in all derived models.\n\n    \"\"\"\n\n    def __init__(self, Afrho, **kwargs):\n        pass\n\n    def __call__(self, *args, **kwargs):\n        return self.fluxd(*args, **kwargs)\n\n    def fluxd(self, geom, wave, unit=None):\n        pass\n\nclass AfrhoScattered(AfrhoRadiation):\n    \"\"\"Scattered light from a comet coma parameterized by Afrho.\n\n    If you use this model, please reference A'Hearn et al. (1984, AJ\n    89, 579-591) as the source of the Afrho parameter.\n\n    Parameters\n    ----------\n    Afrho : Quantity\n      The product of albedo at zero phase, A, dust filling factor, f,\n      and observer's aperture radius, rho.\n    phasef : function, optional\n      The phase function of the coma.  Set to `None` to use `phaseK`.\n\n    Methods\n    -------\n    fluxd : Total flux density from the coma.\n\n    \"\"\"\n\n    def __init__(self, Afrho, phasef=None, **kwargs):\n        self.Afrho = Afrho\n        if phasef is None:\n            self.phasef = phaseK\n        else:\n            self.phasef = phasef\n\n    def fluxd(self, geom, wave, rap, unit=u.Unit('W / (m2 um)')):\n        \"\"\"Flux density.\n\n        Parameters\n        ----------\n        geom : dict of Quantities\n          A dictionary-like object with the keys 'rh' (heliocentric\n          distance), 'delta' (observer-target distance), and 'phase'\n          (phase angle).\n        wave : Quantity\n          The wavelengths at which to compute the emission.\n        rap : Quantity\n          The aperture radius, angular or projected distance at the\n          comet.\n        unit : astropy Units, optional\n          The return units.  Must be spectral flux density.\n\n        Returns\n        -------\n        fluxd : Quantityu\n          The flux density from the coma.\n\n        Raises\n        ------\n        ValueError : If `rap` has incorrect units.\n\n        \"\"\"\n\n        from ..calib import solar_flux\n\n        if rap.unit.is_equivalent(u.cm):\n            rho = rap.to(self.Afrho.unit)\n        elif rap.unit.is_equivalent(u.arcsec):\n            rho = geom['delta'].to(self.Afrho.unit) * rap.to(u.rad).value\n        else:\n            raise ValueError(\"rap must have angular or length units.\")\n\n        fsun = solar_flux(wave, unit=unit) / geom['rh'].to(u.au).value**2\n        fluxd = (self.Afrho\n                 * self.phasef(np.abs(geom['phase'].to(u.deg).value))\n                 * rho * fsun / 4.0 / geom['delta'].to(self.Afrho.unit)**2)\n\n        return fluxd\n\nclass AfrhoThermal(AfrhoRadiation):\n    \"\"\"Thermal emisson from a coma parameterized by efrho.\n\n    If you use this model, please cite and reference Kelley et\n    al. (2013, Icarus 225, 475-494).  They define `epsilon-f-rho` as\n    the product of IR emissivity (`epsilon`), dust filling factor\n    (`f`), and observer's aperture radius (`rho`).\n\n    The default `ef2af` is 3.5, which assumes `epsilion` is\n    approximately 0.9, `A` is approximately 0.25, and the scattering\n    and emission filling factors are the same.  This value can roughly\n    reproduce the spectral shape of 73P-C/Schwassmann-Wachmann in\n    Fig. 16 of Sitko et al. (2011, AJ 142, 80) for `Tscale = 1.12`.\n\n    The default long-wavelength slope, `beta = 0.89+/-0.10`, is from\n    an analysis of Hyakutake JCMT data by Jewitt and Matthews (1997,\n    AJ 113, 1145).  The break-point, `wave0` = 70 um, is based on my\n    own analysis, combining the Jewitt and Matthews fluxes with mid-IR\n    fluxes from Mason et al. (1998, ApJ 507, 398).\n\n    Parameters\n    ----------\n    Afrho : Quantity\n      The product of albedo at zero phase, A, dust filling factor, f,\n      and observer's aperture radius, rho.\n    ef2af : float, optional\n      The ratio of epsilon-f_therm to A-f_sca, where f_therm and f_sca\n      are the effective thermal and scattered light filling factors,\n      (they are not necessarily the same).\n    Tscale : float, optional\n      The isothermal blackbody sphere temperature scale factor that\n      characterizes the spectral shape of the thermal emission.\n    beta : float, optional\n    wave0 : Quantity, optional\n      Scale wavelengths longer than `wave0` by `(wave / wave0)**-beta`.\n\n    Methods\n    -------\n    fluxd : Total flux density from the coma.\n\n    \"\"\"\n\n    def __init__(self, Afrho, ef2af=3.5, Tscale=1.1, beta=0.89,\n                 wave0=70 * u.um, **kwargs):\n        assert isinstance(Afrho, u.Quantity)\n        self.Afrho = Afrho\n        self.ef2af = ef2af\n        self.Tscale = Tscale\n        self.beta = beta\n        self.wave0 = wave0\n\n    def fluxd(self, geom, wave, rap, unit=u.Unit('W / (m2 um)')):\n        \"\"\"Flux density.\n\n        Parameters\n        ----------\n        geom : dict of Quantities\n          A dictionary-like object with the keys 'rh' (heliocentric\n          distance), 'delta' (observer-target distance), and 'phase'\n          (phase angle).\n        wave : Quantity\n          The wavelengths at which to compute the emission.\n        rap : Quantity\n          The aperture radius, angular or projected distance at the\n          comet.\n        unit : astropy Units, optional\n          The return units.  Must be spectral flux density.\n\n        Returns\n        -------\n        fluxd : Quantity\n          The flux density from the coma.\n\n        Raises\n        ------\n        ValueError : If `rap` has incorrect units.\n\n        \"\"\"\n\n        from ..util import planck\n\n        if rap.unit.is_equivalent(u.cm):\n            rho = rap.to(self.Afrho.unit)\n        elif rap.unit.is_equivalent(u.arcsec):\n            rho = geom['delta'].to(self.Afrho.unit) * rap.to(u.rad).value\n        else:\n            raise ValueError(\"rap must have angular or length units.\")\n\n        T = self.Tscale * 278 / np.sqrt(geom['rh'].to(u.au).value)\n        B = planck(wave, T, unit=unit / u.sr).value\n        efrho = self.Afrho * self.ef2af\n        d = geom['delta'].to(self.Afrho.unit).value\n        fluxd = efrho.value * np.pi * B * rho.value / d**2\n\n        if any(wave > self.wave0):\n            eps = np.ones(len(wave))\n            i = wave > self.wave0\n            eps[i] *= (wave[i] / self.wave0)**-self.beta\n            fluxd *= eps\n\n        return fluxd * unit\n\ndef phaseK(phase):\n    \"\"\"Phase function derived from Kolokolova et al. (2004, Comets II).\n\n    The phase function of K04 is scaled to phasef(0) = 1.0.\n\n    Parameters\n    ----------\n    phase : float or array\n        Phase angle. [degrees]\n\n    Returns\n    -------\n    phi : float or ndarray\n        The phase function.\n\n    Notes\n    -----\n    To estimate the phase function, I fit a polynomial function to the\n    solid line of Kolokolova et al. (2004, Comets II):\n\n      a = array([0.27, 0.21, 0.17, 0.15, 0.14, 0.135, 0.135, 0.135, 0.15,\n           0.175, 0.225, 0.3, 0.43, 0.62, 0.775])\n      b = array([0.0,  10,   20,   30,   40,   60,    70,   80,   100,\n           110,   120,   130, 140,  150,  156])\n      fit = poly1d(polyfit(b, a / 0.27, 4))\n      plot(b, a, 'o')\n      plot(b, fit(b) * min(a), 'r-')\n\n    \"\"\"\n\n    phasef = np.poly1d([  3.14105489e-08,  -7.84714255e-06,   7.34255521e-04,\n                         -3.09608957e-02,   1.00920684e+00])\n    return phasef(np.abs(phase))\n\ndef phaseH(phase):\n    \"\"\"Halley phase function from Schleicher et al. (1998).\n\n    The Halley phase function is from Schleicher et al. (1998, Icarus\n    132, 397-417).  The Comet Halley observations were at phases less\n    than 70 degrees.\n\n    Parameters\n    ----------\n    phase : float or array\n        Phase angle. [degrees]\n\n    Returns\n    -------\n    phi : float or ndarray\n        The phase function.\n\n    \"\"\"\n\n    phasef = np.poly1d([0.000177, -0.01807, 1])\n    return phasef(np.abs(phase))\n\ndef phaseHM(phase):\n    \"\"\"Halley-Marcus phase function from Schleicher et al. (2011).\n\n    The Halley phase function is first published in Schleicher and\n    Bair (2011, AJ 141, 117), but only described in detail by\n    Schleicher and Marcus (May 2010) at:\n\n      http://asteroid.lowell.edu/comet/dustphase.html\n\n      \"To distinguish this curve from others, we designate this as the\n      HM phase function, for the sources of the two components: Halley\n      and Marcus, where the Halley curve for smaller phase angles\n      comes from our previous work (Schleicher et al. 1998) while Joe\n      Marcus has fit a Henyey-Greenstein function to a variety of mid-\n      and large-phase angle data sets (Marcus 2007); see here for\n      details. Note that we do not consider our composite curve to be\n      a definitive result, but rather appropriate for performing\n      first-order adjustments to dust measurements for changing phase\n      angle.\"\n\n    Parameters\n    ----------\n    phase : float or array\n        Phase angle. [degrees]\n\n    Returns\n    -------\n    phi : float or ndarray\n        The phase function.\n\n    \"\"\"\n\n    from scipy.interpolate import splrep, splev\n\n    th = np.arange(181)\n    ph = np.array(\n        [  1.0000e+00,   9.5960e-01,   9.2170e-01,   8.8590e-01,\n           8.5220e-01,   8.2050e-01,   7.9060e-01,   7.6240e-01,\n           7.3580e-01,   7.1070e-01,   6.8710e-01,   6.6470e-01,\n           6.4360e-01,   6.2370e-01,   6.0490e-01,   5.8720e-01,\n           5.7040e-01,   5.5460e-01,   5.3960e-01,   5.2550e-01,\n           5.1220e-01,   4.9960e-01,   4.8770e-01,   4.7650e-01,\n           4.6590e-01,   4.5590e-01,   4.4650e-01,   4.3770e-01,\n           4.2930e-01,   4.2150e-01,   4.1420e-01,   4.0730e-01,\n           4.0090e-01,   3.9490e-01,   3.8930e-01,   3.8400e-01,\n           3.7920e-01,   3.7470e-01,   3.7060e-01,   3.6680e-01,\n           3.6340e-01,   3.6030e-01,   3.5750e-01,   3.5400e-01,\n           3.5090e-01,   3.4820e-01,   3.4580e-01,   3.4380e-01,\n           3.4210e-01,   3.4070e-01,   3.3970e-01,   3.3890e-01,\n           3.3850e-01,   3.3830e-01,   3.3850e-01,   3.3890e-01,\n           3.3960e-01,   3.4050e-01,   3.4180e-01,   3.4320e-01,\n           3.4500e-01,   3.4700e-01,   3.4930e-01,   3.5180e-01,\n           3.5460e-01,   3.5760e-01,   3.6090e-01,   3.6450e-01,\n           3.6830e-01,   3.7240e-01,   3.7680e-01,   3.8150e-01,\n           3.8650e-01,   3.9170e-01,   3.9730e-01,   4.0320e-01,\n           4.0940e-01,   4.1590e-01,   4.2280e-01,   4.3000e-01,\n           4.3760e-01,   4.4560e-01,   4.5400e-01,   4.6270e-01,\n           4.7200e-01,   4.8160e-01,   4.9180e-01,   5.0240e-01,\n           5.1360e-01,   5.2530e-01,   5.3750e-01,   5.5040e-01,\n           5.6380e-01,   5.7800e-01,   5.9280e-01,   6.0840e-01,\n           6.2470e-01,   6.4190e-01,   6.5990e-01,   6.7880e-01,\n           6.9870e-01,   7.1960e-01,   7.4160e-01,   7.6480e-01,\n           7.8920e-01,   8.1490e-01,   8.4200e-01,   8.7060e-01,\n           9.0080e-01,   9.3270e-01,   9.6640e-01,   1.0021e+00,\n           1.0399e+00,   1.0799e+00,   1.1223e+00,   1.1673e+00,\n           1.2151e+00,   1.2659e+00,   1.3200e+00,   1.3776e+00,\n           1.4389e+00,   1.5045e+00,   1.5744e+00,   1.6493e+00,\n           1.7294e+00,   1.8153e+00,   1.9075e+00,   2.0066e+00,\n           2.1132e+00,   2.2281e+00,   2.3521e+00,   2.4861e+00,\n           2.6312e+00,   2.7884e+00,   2.9592e+00,   3.1450e+00,\n           3.3474e+00,   3.5685e+00,   3.8104e+00,   4.0755e+00,\n           4.3669e+00,   4.6877e+00,   5.0418e+00,   5.4336e+00,\n           5.8682e+00,   6.3518e+00,   6.8912e+00,   7.4948e+00,\n           8.1724e+00,   8.9355e+00,   9.7981e+00,   1.0777e+01,\n           1.1891e+01,   1.3166e+01,   1.4631e+01,   1.6322e+01,\n           1.8283e+01,   2.0570e+01,   2.3252e+01,   2.6418e+01,\n           3.0177e+01,   3.4672e+01,   4.0086e+01,   4.6659e+01,\n           5.4704e+01,   6.4637e+01,   7.7015e+01,   9.2587e+01,\n           1.1237e+02,   1.3775e+02,   1.7060e+02,   2.1348e+02,\n           2.6973e+02,   3.4359e+02,   4.3989e+02,   5.6292e+02,\n           7.1363e+02,   8.8448e+02,   1.0533e+03,   1.1822e+03,\n           1.2312e+03])\n\n    C = splrep(th, ph)\n    return splev(np.abs(phase), C)\n\n\n# update module docstring\nfrom ..util import autodoc\nautodoc(globals())\ndel autodoc\n\n", "meta": {"hexsha": "bf011816b83edabf025aca46680b91cd2b7375ed", "size": 13780, "ext": "py", "lang": "Python", "max_stars_repo_path": "mskpy/models/dust.py", "max_stars_repo_name": "mkelley/mskpy", "max_stars_repo_head_hexsha": "41f41fd69bae71853abdfd2afbd535cd0b79c530", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-03-27T09:52:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-07T22:29:51.000Z", "max_issues_repo_path": "mskpy/models/dust.py", "max_issues_repo_name": "mkelley/mskpy", "max_issues_repo_head_hexsha": "41f41fd69bae71853abdfd2afbd535cd0b79c530", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2015-11-29T22:20:57.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-01T21:15:07.000Z", "max_forks_repo_path": "mskpy/models/dust.py", "max_forks_repo_name": "mkelley/mskpy", "max_forks_repo_head_hexsha": "41f41fd69bae71853abdfd2afbd535cd0b79c530", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-11-29T21:26:09.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-24T08:53:43.000Z", "avg_line_length": 32.2716627635, "max_line_length": 77, "alphanum_fraction": 0.576777939, "include": true, "reason": "import numpy,from numpy,from scipy,import astropy,from astropy", "num_tokens": 4784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.1928882462245139}}
{"text": "from __future__ import annotations\nfrom typing import Optional, Tuple, Union, List, Dict\nimport torch\nimport numpy as np\nimport scipy.special\nfrom dqc.hamilton.base_hamilton import BaseHamilton\nfrom dqc.hamilton.hcgto_pbc import HamiltonCGTO_PBC\nfrom dqc.system.base_system import BaseSystem\nfrom dqc.grid.base_grid import BaseGrid\nfrom dqc.grid.factory import get_predefined_grid\nfrom dqc.system.mol import _parse_basis, _get_nelecs_spin, \\\n                           _get_orb_weights, AtomZsType, AtomPosType\nfrom dqc.utils.datastruct import CGTOBasis, AtomCGTOBasis, ZType, BasisInpType, \\\n                                 SpinParam, DensityFitInfo\nfrom dqc.utils.safeops import safe_cdist\nfrom dqc.utils.periodictable import get_atom_mass\nfrom dqc.api.parser import parse_moldesc\nfrom dqc.hamilton.intor.lattice import Lattice\nfrom dqc.hamilton.intor.pbcintor import PBCIntOption\nfrom dqc.utils.cache import Cache\n\n__all__ = [\"Sol\"]\n\nclass Sol(BaseSystem):\n    \"\"\"\n    Describe the system of a solid (i.e. periodic boundary condition system).\n\n    Arguments\n    ---------\n    * soldesc: str or 2-elements tuple\n        Description of the molecule system.\n        If string, it can be described like ``\"H 1 0 0; H -1 0 0\"``.\n        If tuple, the first element of the tuple is the Z number of the atoms while\n        the second element is the position of the atoms: ``(atomzs, atomposs)``.\n    * basis: str, CGTOBasis, list of str, or CGTOBasis\n        The string describing the gto basis. If it is a list, then it must have\n        the same length as the number of atoms.\n    * grid: int\n        Describe the grid.\n        If it is an integer, then it uses the default grid with specified level\n        of accuracy.\n    * spin: int, float, torch.Tensor, or None\n        The difference between spin-up and spin-down electrons.\n        It must be an integer or ``None``.\n        If ``None``, then it is ``num_electrons % 2``.\n        For floating point atomzs and/or charge, the ``spin`` must be specified.\n    * charge: int, float, or torch.Tensor\n        The charge of the molecule.\n    * orb_weights: SpinParam[torch.Tensor] or None\n        Specifiying the orbital occupancy (or weights) directly. If specified,\n        ``spin`` and ``charge`` arguments are ignored.\n    * dtype: torch.dtype\n        The data type of tensors in this class.\n    * device: torch.device\n        The device on which the tensors in this class are stored.\n    \"\"\"\n\n    def __init__(self,\n                 soldesc: Union[str, Tuple[AtomZsType, AtomPosType]],\n                 alattice: torch.Tensor,\n                 basis: Union[str, List[CGTOBasis], List[str], List[List[CGTOBasis]]],\n                 *,\n                 grid: Union[int, str] = \"sg3\",\n                 spin: Optional[ZType] = None,\n                 lattsum_opt: Optional[Union[PBCIntOption, Dict]] = None,\n                 dtype: torch.dtype = torch.float64,\n                 device: torch.device = torch.device('cpu'),\n                 ):\n        self._dtype = dtype\n        self._device = device\n        self._grid_inp = grid\n        self._basis_inp = basis\n        self._grid: Optional[BaseGrid] = None\n        charge = 0  # we can't have charged solids for now\n\n        # get the AtomCGTOBasis & the hamiltonian\n        # atomzs: (natoms,) dtype: torch.int or dtype for floating point\n        # atompos: (natoms, ndim)\n        atomzs, atompos = parse_moldesc(soldesc, dtype, device)\n        allbases = _parse_basis(atomzs, basis)  # list of list of CGTOBasis\n        atombases = [AtomCGTOBasis(atomz=atz, bases=bas, pos=atpos)\n                     for (atz, bas, atpos) in zip(atomzs, allbases, atompos)]\n        self._atombases = atombases\n        self._atompos = atompos  # (natoms, ndim)\n        self._atomzs = atomzs  # (natoms,) int-type\n        nelecs_tot: torch.Tensor = torch.sum(atomzs)\n\n        # get the number of electrons and spin and orbital weights\n        nelecs, spin, frac_mode = _get_nelecs_spin(nelecs_tot, spin, charge)\n        assert not frac_mode, \"Fractional Z mode for pbc is not supported\"\n        _orb_weights, _orb_weights_u, _orb_weights_d = _get_orb_weights(\n            nelecs, spin, frac_mode, dtype, device)\n\n        # initialize cache\n        self._cache = Cache()\n\n        # save the system's properties\n        self._spin = spin\n        self._charge = charge\n        self._numel = nelecs\n        self._orb_weights = _orb_weights\n        self._orb_weights_u = _orb_weights_u\n        self._orb_weights_d = _orb_weights_d\n        self._alattice_inp = alattice\n        self._lattice = Lattice(self._alattice_inp)\n        self._lattsum_opt = PBCIntOption.get_default(lattsum_opt)\n\n    def densityfit(self, method: Optional[str] = None,\n                   auxbasis: Optional[BasisInpType] = None) -> BaseSystem:\n        \"\"\"\n        Indicate that the system's Hamiltonian uses density fit for its integral.\n\n        Arguments\n        ---------\n        method: Optional[str]\n            Density fitting method. Available methods in this class are:\n\n            * ``\"gdf\"``: Density fit with gdf compensating charge to perform\n                the lattice sum. Ref https://doi.org/10.1063/1.4998644 (default)\n\n        auxbasis: Optional[BasisInpType]\n            Auxiliary basis for the density fit. If not specified, then it uses\n            ``\"cc-pvtz-jkfit\"``.\n        \"\"\"\n        if method is None:\n            method = \"gdf\"\n        if auxbasis is None:\n            # TODO: choose the auxbasis properly\n            auxbasis = \"cc-pvtz-jkfit\"\n\n        # get the auxiliary basis\n        assert auxbasis is not None\n        auxbasis_lst = _parse_basis(self._atomzs, auxbasis)\n        atomauxbases = [AtomCGTOBasis(atomz=atz, bases=bas, pos=atpos)\n                        for (atz, bas, atpos) in zip(self._atomzs, auxbasis_lst, self._atompos)]\n\n        # change the hamiltonian to have density fit\n        df = DensityFitInfo(method=method, auxbases=atomauxbases)\n        self._hamilton = HamiltonCGTO_PBC(self._atombases, df=df, latt=self._lattice,\n                                          lattsum_opt=self._lattsum_opt,\n                                          cache=self._cache.add_prefix(\"hamilton\"))\n        return self\n\n    def get_hamiltonian(self) -> BaseHamilton:\n        \"\"\"\n        Returns the Hamiltonian that corresponds to the system, i.e.\n        :class:`~dqc.hamilton.HamiltonCGTO_PBC`\n        \"\"\"\n        return self._hamilton\n\n    def set_cache(self, fname: str, paramnames: Optional[List[str]] = None) -> BaseSystem:\n        \"\"\"\n        Setup the cache of some parameters specified by `paramnames` to be read/written\n        on a file.\n        If the file exists, then the parameters will not be recomputed, but just\n        loaded from the cache instead.\n        Cache is usually used for repeated calculations where the cached parameters\n        are not changed (e.g. running multiple systems with slightly different environment.)\n\n        Arguments\n        ---------\n        fname: str\n            The file to store the cache.\n        paramnames: list of str or None\n            List of parameter names to be read/write from the cache.\n        \"\"\"\n        self._cache.set(fname, paramnames)\n        return self\n\n    def get_orbweight(self, polarized: bool = False) -> Union[torch.Tensor, SpinParam[torch.Tensor]]:\n        if not polarized:\n            return self._orb_weights\n        else:\n            return SpinParam(u=self._orb_weights_u, d=self._orb_weights_d)\n\n    def get_nuclei_energy(self) -> torch.Tensor:\n        # self._atomzs: (natoms,)\n        # self._atompos: (natoms, ndim)\n\n        # r12: (natoms, natoms)\n        r12_inf = safe_cdist(self._atompos, self._atompos, add_diag_eps=True, diag_inf=True)\n        r12 = safe_cdist(self._atompos, self._atompos, add_diag_eps=True)\n        z12 = self._atomzs.unsqueeze(-2) * self._atomzs.unsqueeze(-1)  # (natoms, natoms)\n\n        precision = self._lattsum_opt.precision\n        eta = self._lattice.estimate_ewald_eta(precision) * 2\n        vol = self._lattice.volume()\n        rcut = scipy.special.erfcinv(float(vol.detach()) * eta * eta / (2 * np.pi) * precision) / eta\n        gcut = scipy.special.erfcinv(precision * np.sqrt(np.pi) / 2 / eta) * 2 * eta\n\n        # get the shift vector in real space and in reciprocal space\n        ls = self._lattice.get_lattice_ls(rcut=rcut, exclude_zeros=True)  # (nls, ndim)\n        # gv: (ngv, ndim), gvweights: (ngv,)\n        gv, gvweights = self._lattice.get_gvgrids(gcut=gcut, exclude_zeros=True)\n        gv_norm2 = torch.einsum(\"gd,gd->g\", gv, gv)  # (ngv)\n\n        # get the shift in position\n        atpos_shift = self._atompos - ls.unsqueeze(-2)  # (nls, natoms, ndim)\n        r12_ls = safe_cdist(atpos_shift, self._atompos)  # (nls, natoms, natoms)\n\n        # calculate the short range\n        short_range_comp1 = torch.erfc(eta * r12_ls) / r12_ls  # (nls, natoms, natoms)\n        short_range_comp2 = torch.erfc(eta * r12) / r12_inf  # (natoms, natoms)\n        short_range1 = torch.sum(z12 * short_range_comp1)  # scalar\n        short_range2 = torch.sum(z12 * short_range_comp2)  # scalar\n        short_range = short_range1 + short_range2\n\n        # calculate the long range sum\n        coul_g = 4 * np.pi / gv_norm2 * gvweights  # (ngv,)\n        # this part below is quicker, but raises warning from pytorch\n        si = torch.exp(1j * torch.matmul(self._atompos, gv.transpose(-2, -1)))  # (natoms, ngv)\n        zsi = torch.einsum(\"a,ag->g\", self._atomzs.to(si.dtype), si)  # (ngv,)\n        zexpg2 = zsi * torch.exp(-gv_norm2 / (4 * eta * eta))\n        long_range = torch.einsum(\"a,a,a->\", zsi.conj(), zexpg2, coul_g.to(zsi.dtype)).real  # (scalar)\n\n        # # alternative way to compute the long-range part\n        # r12_pair = self._atompos.unsqueeze(-2) - self._atompos  # (natoms, natoms, ndim)\n        # long_range_exp = torch.exp(-gv_norm2 / (4 * eta * eta)) * coul_g  # (ngv,)\n        # long_range_cos = torch.cos(torch.einsum(\"gd,abd->gab\", gv, -r12_pair))  # (ngv, natoms, natoms)\n        # long_range = torch.sum(long_range_exp[:, None, None] * long_range_cos * z12)  # scalar\n\n        # background interaction\n        vbar1 = -torch.sum(self._atomzs ** 2) * (2 * eta / np.sqrt(np.pi))\n        vbar2 = -torch.sum(self._atomzs) ** 2 * np.pi / (eta * eta * vol)\n        vbar = vbar1 + vbar2  # (scalar)\n\n        eii = short_range + long_range + vbar\n        return eii * 0.5\n\n    def setup_grid(self) -> None:\n        self._grid = get_predefined_grid(self._grid_inp, self._atomzs, self._atompos,\n                                         lattice=self._lattice,\n                                         dtype=self._dtype, device=self._device)\n\n    def get_grid(self) -> BaseGrid:\n        if self._grid is None:\n            raise RuntimeError(\"Please run mol.setup_grid() first before calling get_grid()\")\n        return self._grid\n\n    def requires_grid(self) -> bool:\n        return False\n\n    def getparamnames(self, methodname: str, prefix: str = \"\") -> List[str]:\n        pass\n\n    def make_copy(self, **kwargs) -> Sol:\n        \"\"\"\n        Returns a copy of the system identical to the orginal except for new\n        parameters set in the kwargs.\n\n        Arguments\n        ---------\n        **kwargs\n            Must be the same kwargs as Sol.\n        \"\"\"\n        # create dictionary of all parameters\n        parameters = {\n            'soldesc': (self.atomzs, self.atompos),\n            'alattice': self._alattice_inp,\n            'basis': self._basis_inp,\n            'grid': self._grid_inp,\n            'spin': self._spin,\n            'lattsum_opt': self._lattsum_opt,\n            'dtype': self._dtype,\n            'device': self._device\n        }\n        # update dictionary with provided kwargs \n        parameters.update(kwargs)\n        # create new system\n        return Sol(**parameters)\n\n    ################### properties ###################\n    @property\n    def atompos(self) -> torch.Tensor:\n        return self._atompos\n\n    @property\n    def atomzs(self) -> torch.Tensor:\n        return self._atomzs\n\n    @property\n    def atommasses(self) -> torch.Tensor:\n        # returns the atomic mass (only for non-isotope for now)\n        return torch.tensor([get_atom_mass(int(atomz)) for atomz in self._atomzs],\n                            dtype=self._dtype, device=self._device)\n\n    @property\n    def spin(self) -> ZType:\n        return self._spin\n\n    @property\n    def charge(self) -> ZType:\n        return self._charge\n\n    @property\n    def numel(self) -> ZType:\n        return self._numel\n\n    @property\n    def efield(self) -> Optional[Tuple[torch.Tensor, ...]]:\n        # solid with external efield has not been implemented\n        return None\n", "meta": {"hexsha": "a12bc0539f92767c6af6649384f18b1e9e0731b5", "size": 12689, "ext": "py", "lang": "Python", "max_stars_repo_path": "dqc/system/sol.py", "max_stars_repo_name": "sofroniewn/dqc", "max_stars_repo_head_hexsha": "0fe821fc92cb3457fb14f6dff0c223641c514ddb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dqc/system/sol.py", "max_issues_repo_name": "sofroniewn/dqc", "max_issues_repo_head_hexsha": "0fe821fc92cb3457fb14f6dff0c223641c514ddb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dqc/system/sol.py", "max_forks_repo_name": "sofroniewn/dqc", "max_forks_repo_head_hexsha": "0fe821fc92cb3457fb14f6dff0c223641c514ddb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.8778877888, "max_line_length": 105, "alphanum_fraction": 0.6170699031, "include": true, "reason": "import numpy,import scipy", "num_tokens": 3287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.19281265153914087}}
{"text": "##########################################################################################\n# Copyright (c) MemSQL. All rights reserved.\n# Licensed under the MIT License. See LICENSE in the project root for license information.\n##########################################################################################\n\n\"\"\"\ncycle.py\n\nDetect cyclical anomalies from a history\n\nA cyclical anomaly is a cycle in a Direct Serialization Graph (DGS) of the history,\nwhich encodes dependencies between txns.\n\nThere are three types of item dependencies:\n    Write-depends (ww): T0 writes x_i and T_1 writes x_{i + 1}. There is a dependency from T0 to T1\n    Read-depends  (wr): T0 writes x_i and T_1 reads x_i. There is a dependency from T0 to T1\n    Anti-depends  (rw): T0 reads x_i and T_1 writes x_{i + 1}. There is a dependency from T0 to T1\n\nThere are also predicate dependencies. However, these are more difficult to inspect.\n\nFor instance, write predicate queries require visibility to what values were\nwritten and, more importantly, which values were *considered* when trying to match.\n\nPredicate write-read dependencies are also difficult, for the same reason: the\nonly advantage compared to regular item WR dependencies is to the values that\ndidn't match the predicate, to which we have no visibility; and the ones that\ndid match already appear in the history as regular item reads. The interesting\ncase is predicate anti-dependencies (which interestingly are the separation\nbetween REPEATABLE READ and SERIALIZABLE isolation). There is an anti dependency\nfrom the predicate read to the future writes which update objects to values\nwhich *would have matched* the predicate.\n\nThese dependencies represent edges on the DSG. One could think of a dependency\nfrom TA to TB as `TA needs to happen before TB`. As such, a topological order\nwould give a (possibly) valid ordering of the txns. However, cycles make it\nimpossible for such ordering to exist.\n\nThere are several of cyclical anomalies, whose description can be found\nin Atul Adya's PhD thesis. Some examples:\n    G0 - cycle of ww dependencies\n      eg:   T1 writes w(0, 0) (0 -> [0])       |\n            T2 writes w(0, 1) (0 -> [0,1])     | ww T1 -> T2\n            T1 writes w(0, 2) (0->[0,1,2])     | ww T2 -> T1\n            T1 commits, T2 commits.            |\n\n    G1b - cycle of ww and wr dependencies\n      eg:   T1 writes w(0, 0) (0 -> [0])       |\n            T2 writes w(0, 1) (0 -> [0,1])     | ww T1 -> T2\n            T1 reads  r(0) -> [0,1]            | wr T2 -> T1\n            T1 commits, T2 commits.            |\n\n    G2 - cycle with at least one anti dependency\n      eg:   T1 writes w(0, 0) (0 -> [0])       |\n            T2 writes w(0, 1) (0 -> [0,1])     | ww T1 -> T2\n            T3 writes w(0, 2) (0 -> [0,1,2])   | ww T2 -> T3\n            T3 reads  r(0) -> [0,1,2]          |\n            T1 writes w(0, 3) (0 -> [0,1,2,3]) | rw T3 -> T1\n\n    Gsingle - G2 where the cycle has exactly one anti dependency\n\"\"\"\n\nfrom frodo.domain import DBObject, Operation, Result\nfrom frodo.history import Anomaly, History, HistoryElem, ObservedTransaction\nfrom typing import Any, Dict, Iterable, List, Optional, Set, Tuple\n\nfrom abc import abstractmethod\n\nimport coloredlogs  # type: ignore\nimport enum\nimport logging\nimport networkx as nx  # type: ignore\n\n# setup logger\nlogger: logging.Logger = logging.getLogger(__name__)\ncoloredlogs.install(level=\"INFO\")\nlogger.setLevel(logging.INFO)\n\n\nclass DSG:\n    \"\"\"\n    Direct Serialization Graph of a history\n\n    The direct serialization graph includes as nodes the transactions and\n    as edges the dependencies. It is constructed directly from a recorded\n    history of transactions.\n\n    This representation allows for 3 high-level APIs:\n        - find_cycles(): returns the list of *node* cycles\n        - find_anomalies(anomaly_list): returns an iterable to the anomalies\n                found in the graph which belong to the list\n        - dump_dot() and dump_dots(): return DOT representation of the graph and\n                the cycles, respectively. Accept a list of anomalies to match against\n    \"\"\"\n\n    class Edge:\n        \"\"\"\n        Edge in the DSG\n\n        Note: all edges are directional\n        \"\"\"\n\n        class Type(enum.Enum):\n            WW = enum.auto()\n            WR = enum.auto()\n            RW = enum.auto()\n            PRW = enum.auto()\n\n            def __repr__(self) -> str:\n                if self.value == DSG.Edge.Type.WW.value:\n                    return \"ww\"\n                elif self.value == DSG.Edge.Type.WR.value:\n                    return \"wr\"\n                elif self.value == DSG.Edge.Type.RW.value:\n                    return \"rw\"\n                else:  # self.value == DSG.Edge.Type.PRW.value:\n                    return \"prw\"\n\n        def __init__(self, etype: Type, target: Any):  # cannot forward reference Node\n            self._type: DSG.Edge.Type = etype\n            self._target: Any = target  # cannot forward reference Node\n\n        def __repr__(self) -> str:\n            return \"-> {}\".format(self.target)\n\n        @property\n        def type(self) -> Type:\n            return self._type\n\n        @property\n        def target(self) -> Any:  # cannot forward reference Node\n            return self._target\n\n    class Node:\n        \"\"\"\n        Node in the DSG\n        \"\"\"\n\n        def __init__(self, txn: ObservedTransaction):\n            self._txn = txn\n            self._edges: List[DSG.Edge] = list()\n\n        def add_edge(self, etype: Any, target: Any) -> None:  # surprisingly, neither Edge nor Node are in context here\n            if (\n                len(\n                    tuple(\n                        filter(\n                            lambda e: e.type == etype and e.target.txn.id == target.txn.id,\n                            self._edges,\n                        )\n                    )\n                )\n                == 0\n                and self.txn.id != target.txn.id\n            ):  # prevent loops\n                self._edges.append(DSG.Edge(etype, target))\n\n        def __repr__(self) -> str:\n            return \"T{}\".format(self.txn.id)\n\n        @property\n        def txn(self) -> ObservedTransaction:\n            return self._txn\n\n        @property\n        def edges(self) -> List[Any]:  # Edge not in context\n            return self._edges\n\n        def neighbours(self, edge_types: Set[Any]) -> List[Any]:  # Edge and Node not in context\n            \"\"\"\n            Node neighbours reachable by one of the edge types in <edge_types>\n            \"\"\"\n            return list(\n                set(\n                    map(\n                        lambda edge: edge.target,\n                        filter(lambda x: x.type in edge_types, self._edges),\n                    )\n                )\n            )  # remove duplicates\n\n    class CyclicalAnomaly(Anomaly):\n        \"\"\"\n        An anomaly comprised of a cycle.\n        It receives and identifies a cycle.\n        \"\"\"\n\n        # Anomaly Types\n        #\n        class CyclicalAnomalyType(Anomaly.Type):\n            \"\"\"\n            Abstract class for representing a cyclical anomaly\n\n            The type needs:\n                - provide a short description\n                - be able to identify a cycle as matching its type\n                - give the type of edges which can exist in its cycles\n                    (this is useful for limiting the cycles in the DSG)\n            \"\"\"\n\n            @abstractmethod\n            def description(cls) -> str:\n                pass\n\n            @abstractmethod\n            def identify_cycle(cls, node_cycle: List[Any], edge_cycle: List[Any]) -> bool:\n                pass\n\n            @abstractmethod\n            def edge_types(cls) -> List[Any]:\n                pass\n\n        class G0(CyclicalAnomalyType):\n            @classmethod\n            def description(cls) -> str:\n                return \"G0: write cycles\"\n\n            @staticmethod\n            def identify_cycle(node_cycle: List[Any], edge_cycle: List[Any]) -> bool:\n                return all(e.type in DSG.CyclicalAnomaly.G0.edge_types() for e in edge_cycle)\n\n            @classmethod\n            def edge_types(cls) -> List[Any]:\n                return [DSG.Edge.Type.WW]\n\n        class G1C(CyclicalAnomalyType):\n            @classmethod\n            def description(cls) -> str:\n                return \"G1c: circular information flow\"\n\n            @staticmethod\n            def identify_cycle(node_cycle: List[Any], edge_cycle: List[Any]) -> bool:\n                return all(e.type in DSG.CyclicalAnomaly.G1C.edge_types() for e in edge_cycle)\n\n            @classmethod\n            def edge_types(cls) -> List[Any]:\n                return [DSG.Edge.Type.WW, DSG.Edge.Type.WR]\n\n        class G2item(CyclicalAnomalyType):\n            @classmethod\n            def description(cls) -> str:\n                return \"G2-item: item anti dependency cycle\"\n\n            @staticmethod\n            def identify_cycle(node_cycle: List[Any], edge_cycle: List[Any]) -> bool:\n                return all(e.type in DSG.CyclicalAnomaly.G2item.edge_types() for e in edge_cycle) and any(\n                    e.type == DSG.Edge.Type.RW for e in edge_cycle\n                )\n\n            @classmethod\n            def edge_types(cls) -> List[Any]:\n                return [DSG.Edge.Type.WW, DSG.Edge.Type.WR, DSG.Edge.Type.RW]\n\n        class Gsingle(CyclicalAnomalyType):\n            @classmethod\n            def description(cls) -> str:\n                return \"G-single: single anti dependency cycle\"\n\n            @staticmethod\n            def identify_cycle(node_cycle: List[Any], edge_cycle: List[Any]) -> bool:\n                return (\n                    all(e.type in DSG.CyclicalAnomaly.Gsingle.edge_types() for e in edge_cycle)\n                    and sum(\n                        map(\n                            lambda e: 1 if e.type in [DSG.Edge.Type.RW, DSG.Edge.Type.PRW] else 0,\n                            edge_cycle,\n                        )\n                    )\n                    == 1\n                )\n\n            @classmethod\n            def edge_types(cls) -> List[Any]:\n                return [\n                    DSG.Edge.Type.WW,\n                    DSG.Edge.Type.WR,\n                    DSG.Edge.Type.RW,\n                    DSG.Edge.Type.PRW,\n                ]\n\n        class Gsingleitem(CyclicalAnomalyType):\n            @classmethod\n            def description(cls) -> str:\n                return \"G-single-item: single item anti dependency cycle\"\n\n            @staticmethod\n            def identify_cycle(node_cycle: List[Any], edge_cycle: List[Any]) -> bool:\n                return (\n                    all(e.type in DSG.CyclicalAnomaly.Gsingleitem.edge_types() for e in edge_cycle)\n                    and sum(map(lambda e: 1 if e.type == DSG.Edge.Type.RW else 0, edge_cycle)) == 1\n                )\n\n            @classmethod\n            def edge_types(cls) -> List[Any]:\n                return [DSG.Edge.Type.WW, DSG.Edge.Type.WR, DSG.Edge.Type.RW]\n\n        class G2(CyclicalAnomalyType):\n            @classmethod\n            def description(cls) -> str:\n                return \"G2: anti dependency cycle\"\n\n            @staticmethod\n            def identify_cycle(node_cycle: List[Any], edge_cycle: List[Any]) -> bool:\n                return all(e.type in DSG.CyclicalAnomaly.G2.edge_types() for e in edge_cycle) and any(\n                    e.type in [DSG.Edge.Type.RW, DSG.Edge.Type.PRW] for e in edge_cycle\n                )\n\n            @classmethod\n            def edge_types(cls) -> List[Any]:\n                return [\n                    DSG.Edge.Type.WW,\n                    DSG.Edge.Type.WR,\n                    DSG.Edge.Type.RW,\n                    DSG.Edge.Type.PRW,\n                ]\n\n        class Gcursor(CyclicalAnomalyType):\n            @classmethod\n            def description(cls) -> str:\n                return \"G-cursor: labeled single anti dependency cycle\"\n\n            @staticmethod\n            def identify_cycle(node_cycle: List[Any], edge_cycle: List[Any]) -> bool:\n                return False  # TODO: unimplemented\n\n            @classmethod\n            def edge_types(cls) -> List[Any]:\n                return []  # TODO: unimplemented\n\n        class GMSRA(CyclicalAnomalyType):\n            @classmethod\n            def description(cls) -> str:\n                return \"G-MSRa: action interference\"\n\n            @staticmethod\n            def identify_cycle(node_cycle: List[Any], edge_cycle: List[Any]) -> bool:\n                return False  # TODO: unimplemented\n\n            @classmethod\n            def edge_types(cls) -> List[Any]:\n                return []  # TODO: unimplemented\n\n        class GMSRB(CyclicalAnomalyType):\n            @classmethod\n            def description(cls) -> str:\n                return \"G-MSRb: action missed\"\n\n            @staticmethod\n            def identify_cycle(node_cycle: List[Any], edge_cycle: List[Any]) -> bool:\n                return False  # TODO: unimplemented\n\n            @classmethod\n            def edge_types(cls) -> List[Any]:\n                return []  # TODO: unimplemented\n\n        class GMSR(CyclicalAnomalyType):\n            @classmethod\n            def description(cls) -> str:\n                return \"G-MSRb: action missed\"\n\n            @staticmethod\n            def identify_cycle(node_cycle: List[Any], edge_cycle: List[Any]) -> bool:\n                return DSG.CyclicalAnomaly.GMSRA.identify_cycle(\n                    node_cycle, edge_cycle\n                ) or DSG.CyclicalAnomaly.GMSRB.identify_cycle(node_cycle, edge_cycle)\n\n            @classmethod\n            def edge_types(cls) -> List[Any]:\n                return []  # TODO: unimplemented\n\n        class Gmonotonic(CyclicalAnomalyType):\n            @classmethod\n            def description(cls) -> str:\n                return \"G-monotonic: monotonic reads\"\n\n            @staticmethod\n            def identify_cycle(node_cycle: List[Any], edge_cycle: List[Any]) -> bool:\n                return False  # TODO: unimplemented\n\n            @classmethod\n            def edge_types(cls) -> List[Any]:\n                return []  # TODO: unimplemented\n\n        class GSIA(CyclicalAnomalyType):\n            @classmethod\n            def description(cls) -> str:\n                return \"G-SIa: interference\"\n\n            @staticmethod\n            def identify_cycle(node_cycle: List[Any], edge_cycle: List[Any]) -> bool:\n                return False  # TODO: unimplemented\n\n            @classmethod\n            def edge_types(cls) -> List[Any]:\n                return []  # TODO: unimplemented\n\n        class GSIB(CyclicalAnomalyType):\n            @classmethod\n            def description(cls) -> str:\n                return \"G-SIb: missed effects\"\n\n            @staticmethod\n            def identify_cycle(node_cycle: List[Any], edge_cycle: List[Any]) -> bool:\n                return False  # TODO: unimplemented\n\n            @classmethod\n            def edge_types(cls) -> List[Any]:\n                return []  # TODO: unimplemented\n\n        class GSI(CyclicalAnomalyType):\n            @classmethod\n            def description(cls) -> str:\n                return \"G-SI: snapshot isolation violation\"\n\n            @staticmethod\n            def identify_cycle(node_cycle: List[Any], edge_cycle: List[Any]) -> bool:\n                return DSG.CyclicalAnomaly.GSIA.identify_cycle(\n                    node_cycle, edge_cycle\n                ) or DSG.CyclicalAnomaly.GSIB.identify_cycle(node_cycle, edge_cycle)\n\n            @classmethod\n            def edge_types(cls) -> List[Any]:\n                return []  # TODO: unimplemented\n\n        class Gupdate(CyclicalAnomalyType):\n            @classmethod\n            def description(cls) -> str:\n                return \"G-update: single anti dependency cycle with update transmission\"\n\n            @staticmethod\n            def identify_cycle(node_cycle: List[Any], edge_cycle: List[Any]) -> bool:\n                return False  # TODO: unimplemented\n\n            @classmethod\n            def edge_types(cls) -> List[Any]:\n                return []  # TODO: unimplemented\n\n        @staticmethod\n        def safe_implies(anomaly_type: Any) -> Optional[List[Any]]:\n            \"\"\"\n            Implication between cyclical dependencies without throwing exceptions\n            \"\"\"\n            if anomaly_type == DSG.CyclicalAnomaly.G0:\n                return [DSG.CyclicalAnomaly.G1C]\n            if anomaly_type == DSG.CyclicalAnomaly.G1C:\n                return [DSG.CyclicalAnomaly.G1]\n            if anomaly_type == DSG.CyclicalAnomaly.Gmonotonic:\n                return [DSG.CyclicalAnomaly.G2item]\n            if anomaly_type == DSG.CyclicalAnomaly.Gcursor:\n                return [DSG.CyclicalAnomaly.G2item, DSG.CyclicalAnomaly.Gsingle]\n            if anomaly_type == DSG.CyclicalAnomaly.GMSRA:\n                return [DSG.CyclicalAnomaly.GMSR]\n            if anomaly_type == DSG.CyclicalAnomaly.GMSRB:\n                return [DSG.CyclicalAnomaly.GMSR]\n            if anomaly_type == DSG.CyclicalAnomaly.GSIA:\n                return [DSG.CyclicalAnomaly.GSI]\n            if anomaly_type == DSG.CyclicalAnomaly.GSIB:\n                return [DSG.CyclicalAnomaly.GSI]\n            if anomaly_type == DSG.CyclicalAnomaly.Gupdate:\n                return [DSG.CyclicalAnomaly.G2]\n            if anomaly_type == DSG.CyclicalAnomaly.GMSR:\n                return [DSG.CyclicalAnomaly.G2]\n            if anomaly_type == DSG.CyclicalAnomaly.GSI:\n                return [DSG.CyclicalAnomaly.G2]\n            if anomaly_type == DSG.CyclicalAnomaly.Gsingleitem:\n                return [DSG.CyclicalAnomaly.Gsingle, DSG.CyclicalAnomaly.G2item]\n            if anomaly_type == DSG.CyclicalAnomaly.Gsingle:\n                return [DSG.CyclicalAnomaly.G2]\n            if anomaly_type == DSG.CyclicalAnomaly.G2item:\n                return [DSG.CyclicalAnomaly.G2]\n            if anomaly_type == DSG.CyclicalAnomaly.G2:\n                return []\n            return None\n\n        @staticmethod\n        def cyclical_implies(cls: Any) -> List[Any]:\n            \"\"\"\n            Implication between cyclical dependencies\n            \"\"\"\n            implies: List[Any] = DSG.CyclicalAnomaly.safe_implies(cls)\n            if implies is None:\n                raise ValueError(\"Unknown anomaly type: {}\".format(cls))\n            return implies\n\n        @staticmethod\n        def cyclical_closure(a: Any) -> List[Any]:\n            \"\"\"\n            Compute transitive closure of a cyclical anomaly type\n            \"\"\"\n\n            def aux(l: List[Any], additions: List[Any]) -> List[Any]:\n                if len(additions) == 0:\n                    return l\n                return aux(\n                    l + additions,\n                    list(\n                        sum(\n                            filter(\n                                lambda x: x is not None,\n                                map(\n                                    lambda y: DSG.CyclicalAnomaly.safe_implies(y),\n                                    additions,\n                                ),\n                            ),\n                            [],\n                        )\n                    ),\n                )\n\n            return aux(list(), [a])\n\n        def __init__(\n            self,\n            dsg: Any,\n            node_cycle: List[Any],\n            edge_cycle: List[Any],\n            final_txn: ObservedTransaction,\n        ):\n            if len(node_cycle) != len(edge_cycle):\n                raise ValueError(\n                    \"Node cycle and edge cycles need to have the same size: {} vs {}\".format(node_cycle, edge_cycle)\n                )\n            elif len(node_cycle) < 2:\n                raise ValueError(\"Need at least two nodes in the cycle: {}\".format(node_cycle))\n            elif edge_cycle[-1].target != node_cycle[0]:\n                raise ValueError(\n                    \"If the target of the last edge is not the first node, this isn't a cycle: {} vs {}\".format(\n                        edge_cycle[-1].target, node_cycle[0]\n                    )\n                )\n\n            self._node_cycle: List[DSG.Node] = node_cycle\n            self._edge_cycle: List[DSG.Edge] = edge_cycle\n            self._final_txn: ObservedTransaction = final_txn\n            self._dsg: DSG = dsg\n\n        def type(self) -> CyclicalAnomalyType:\n            \"\"\"\n            To identify the cycle, it gives it to each anomaly type\n            After getting the matches, it finds the one which isn't implied by any\n\n            This assumes that there are no cycles the implication graph of anomalies.\n            Moreover, one cycle should have one (and only one) fundamental anomaly\n            (ie: it shouldn't match unrelated anomalies)\n            \"\"\"\n            possible_types: List[Any] = [\n                DSG.CyclicalAnomaly.G0,\n                DSG.CyclicalAnomaly.G1C,\n                DSG.CyclicalAnomaly.Gmonotonic,\n                DSG.CyclicalAnomaly.Gcursor,\n                DSG.CyclicalAnomaly.GMSRA,\n                DSG.CyclicalAnomaly.GMSRB,\n                DSG.CyclicalAnomaly.GSIA,\n                DSG.CyclicalAnomaly.GSIB,\n                DSG.CyclicalAnomaly.Gupdate,\n                DSG.CyclicalAnomaly.GMSR,\n                DSG.CyclicalAnomaly.GSI,\n                DSG.CyclicalAnomaly.Gsingleitem,\n                DSG.CyclicalAnomaly.Gsingle,\n                DSG.CyclicalAnomaly.G2item,\n                DSG.CyclicalAnomaly.G2,\n            ]\n\n            matched_types: List[Any] = list(\n                filter(\n                    lambda x: x.identify_cycle(self._node_cycle, self._edge_cycle),\n                    possible_types,\n                )\n            )\n            if len(matched_types) == 0:\n                raise ValueError(\"Unknown anomaly: {}, {}\".format(self._node_cycle, self._edge_cycle))\n\n            minimal_types: List[Any] = list()\n            for idx, t in enumerate(matched_types):\n                if all(\n                    t not in DSG.CyclicalAnomaly.cyclical_closure(s)\n                    for s in matched_types[:idx] + matched_types[idx + 1 :]\n                ):\n                    minimal_types.append(t)\n\n            if len(minimal_types) != 1:\n                raise ValueError(\n                    \"It should be impossible for there to be more than one minimal type: {}\".format(minimal_types)\n                )\n\n            return minimal_types[0]\n\n        def txns(self) -> List[ObservedTransaction]:\n            if any(node.txn.id == self._final_txn.id for node in self._node_cycle):\n                return [node.txn for node in self._node_cycle]\n            else:\n                return [node.txn for node in self._node_cycle] + [self._final_txn]\n\n        def explanation(self) -> List[str]:\n            def explain_dependency(dsg: DSG, orig: DSG.Node, edge: DSG.Edge) -> str:\n                \"\"\"\n                Explain a dependency\n                \"\"\"\n                obj_id: Optional[int]\n                ver: Optional[List[int]]\n                _, _, obj_id, ver = next(\n                    filter(\n                        lambda x: x[0] == edge.type and x[1] == edge.target.txn.id,\n                        dsg.find_dependencies(orig),\n                    ),\n                    (None, None, None, None),\n                )\n\n                if obj_id is None:\n                    raise RuntimeError(\n                        \"The {} dependency from T{} to T{} could not be recovered\".format(\n                            edge.type, orig.txn.id, edge.target.txn.id\n                        )\n                    )\n\n                dep_msg: str\n                if edge.type == DSG.Edge.Type.WW:\n                    dep_msg = \"T{} wrote version {} and T{} wrote version {} [object {}] (Write dependency)\".format(\n                        orig.txn.id, ver[:-1], edge.target.txn.id, ver, obj_id\n                    )\n                elif edge.type == DSG.Edge.Type.WR:\n                    dep_msg = \"T{} wrote version {} and T{} read version {} [object {}] (Read dependency)\".format(\n                        orig.txn.id, ver, edge.target.txn.id, ver, obj_id\n                    )\n                elif edge.type == DSG.Edge.Type.RW:\n                    dep_msg = \"T{} read version {} and T{} wrote version {} [object {}] (Item Anti dependency)\".format(\n                        orig.txn.id, ver[:-1], edge.target.txn.id, ver, obj_id\n                    )\n                elif edge.type == DSG.Edge.Type.PRW:\n                    dep_msg = \"T{} didn't read the object because it was two small (required len > {}), and T{} wrote the first version which matched: {} [object {}] (Predicate Anti dependency)\".format(\n                        orig.txn.id, len(ver) - 1, edge.target.txn.id, ver, obj_id\n                    )\n\n                return \"T{} < T{}, because {}\".format(orig.txn.id, edge.target.txn.id, dep_msg)\n\n            msgs: List[str] = [\n                explain_dependency(self._dsg, orig, edge) for orig, edge in zip(self._node_cycle, self._edge_cycle)\n            ]\n            msgs[-1] = \"But {}\".format(msgs[-1])\n            msgs.append(\"This means we have a cycle (and an anomaly)\")\n            return msgs\n\n    def __init__(self, hist: History):\n        \"\"\"\n        Initialize the DSG:\n            - uncommitted transactions are filtered out\n            -\n        \"\"\"\n        self._hist: History = hist\n        self._nodes: List[DSG.Node] = list()\n        for txn_id in range(self._hist.txn_range()[0], self._hist.txn_range()[1] + 1):\n            txn: ObservedTransaction = self._hist.get_observed_txn(txn_id)\n            if self._hist.txn_state(txn_id) == History.TransactionState.COMMITTED:\n                self._nodes.append(DSG.Node(txn))\n\n        self._nodes = sorted(self._nodes, key=lambda n: n.txn.id)\n        self._cycles: Dict[Tuple[Any, ...], List[List[DSG.Node]]] = dict()  # memoization\n        self._dependencies: Dict[DSG.Node, List[Tuple[DSG.Edge.Type, int, int, List[int]]]] = dict()  # memoization\n\n        logger.info(\"finding dependencies between {} transactions\".format(len(self._nodes)))\n        for node in self._nodes:\n            for etype, txn_id, _, _ in self.find_dependencies(node):\n                node.add_edge(etype, self.get_node(txn_id))\n        logger.info(\"constructed the Direct Serialization Graph\")\n\n    def find_dependencies(self, node: Node) -> List[Tuple[Edge.Type, int, int, List[int]]]:\n        \"\"\"\n        Finds the dependencies originating from the node\n        Returns the edge type, target txn id, obj_id, version\n        \"\"\"\n\n        def longest_ver(vers: List[List[int]], val: int) -> List[int]:\n            \"\"\"\n            find the longest version containing <val>\n            \"\"\"\n\n            longest_ver: List[int] = list()\n            for ver in filter(lambda v: val in v, vers):\n                if len(ver) > len(longest_ver):\n                    longest_ver = ver\n\n            if len(longest_ver) == 0:\n                raise ValueError(\"Could not find any version containing {}: {}\".format(val, vers))\n\n            return longest_ver\n\n        def is_prefix(a: List[Any], b: List[Any]) -> bool:\n            if len(a) > len(b):\n                return False\n            return all(a_el == b_el for a_el, b_el in zip(a, b))\n\n        if node in self._dependencies:\n            return self._dependencies[node]\n\n        deps: List[Tuple[DSG.Edge.Type, int, int, List[int]]] = list()\n        for el in filter(\n            lambda e: e.op.type\n            in [\n                Operation.Type.WRITE,\n                Operation.Type.READ,\n                Operation.Type.PREDICATE_READ,\n            ],\n            node.txn.hist,\n        ):\n            if el.op.type in [Operation.Type.WRITE, Operation.Type.READ]:\n                committed_vers: List[List[int]] = self._hist.committed_versions(el.op.obj.id)\n                idx: int\n                ver: List[int]\n                if el.op.type == Operation.Type.WRITE:\n                    ver = longest_ver(committed_vers, el.op.value)\n                    idx = ver.index(el.op.value)\n                    if idx + 1 < len(ver):\n                        deps.append(\n                            (\n                                DSG.Edge.Type.WW,\n                                self._hist.who_wrote(el.op.obj.id, ver[idx + 1]).txn_id,\n                                el.op.obj.id,\n                                ver[: idx + 2],\n                            )\n                        )\n\n                    for next_el in self._hist.who_read(el.op.obj.id, el.op.value):\n                        deps.append(\n                            (\n                                DSG.Edge.Type.WR,\n                                next_el.txn_id,\n                                el.op.obj.id,\n                                ver[: idx + 1],\n                            )\n                        )\n                elif el.op.type == Operation.Type.READ:\n                    ver = longest_ver(committed_vers, el.res.value()[-1])\n                    idx = ver.index(el.res.value()[-1])\n                    if idx + 1 < len(ver):\n                        deps.append(\n                            (\n                                DSG.Edge.Type.RW,\n                                self._hist.who_wrote(el.op.obj.id, ver[idx + 1]).txn_id,\n                                el.op.obj.id,\n                                ver[: idx + 2],\n                            )\n                        )\n            elif el.op.type == Operation.Type.PREDICATE_READ:\n                boundary_len = el.op.value\n                # We have a predicate anti-dependency to operations\n                # which write the first version of an object which would be inserted\n                # but wasn't seen by the predicate read\n                #\n                # We ignore predicate read-dependencies because they are invisible\n                # (ie: Tj pred-read-depends on Ti if Ti writes xi and Tj accesses\n                #      xi but doens't match the predicate).\n                #\n                # The values which *are* matched, have direct item-read-dependencies\n                #\n                for dep in filter(\n                    lambda x: x.op.type == Operation.Type.WRITE\n                    and len(x.op.value_written) == boundary_len + 1\n                    and not any(is_prefix(x.op.value_written, v[1]) for v in el.res.values()),\n                    self._hist,\n                ):\n                    deps.append(\n                        (\n                            DSG.Edge.Type.PRW,\n                            dep.txn_id,\n                            dep.op.obj.id,\n                            dep.op.value_written,\n                        )\n                    )\n\n        result: List[Tuple[DSG.Edge.Type, int, int, List[int]]] = list(\n            filter(\n                lambda x: self._hist.txn_state(x[1]) == History.TransactionState.COMMITTED,\n                deps,\n            )\n        )\n        self._dependencies[node] = result\n        return result\n\n    def get_node(self, txn_id: int) -> Node:\n        node: Optional[DSG.Node] = next(filter(lambda n: n.txn.id == txn_id, self._nodes), None)\n        if node is None:\n            raise KeyError(\"Transaction T{} does not exist in the graph\".format(txn_id))\n        return node\n\n    def find_cycles(self, anom_types: List[Any]) -> Iterable[List[Node]]:\n        \"\"\"\n        Find cycles in the DSG\n        \"\"\"\n\n        def convert_cycle(node_map: Dict[int, DSG.Node], cycle: List[int]) -> List[DSG.Node]:\n            \"\"\"\n            Convert a cycle as a list of ints (txn ids) to nodes\n            \"\"\"\n            return [node_map[txn_id] for txn_id in cycle]\n\n        anom_types = sorted(anom_types, key=lambda x: repr(x))\n        if tuple(anom_types) in self._cycles:\n            for c in self._cycles[tuple(anom_types)]:\n                yield c\n            return None\n\n        edge_types: Set[DSG.Edge.Type] = set(sum((anomaly.edge_types() for anomaly in anom_types), []))\n\n        graph: nx.DiGraph = nx.DiGraph()\n        for node in self._nodes:\n            graph.add_node(node.txn.id)\n            for neigh in node.neighbours(edge_types):\n                graph.add_edge(node.txn.id, neigh.txn.id)\n\n        logger.info(\"finding cyclic anomalies (this might take a while)\")\n        cycles: List[List[DSG.Node]] = list()\n        node_map: Dict[int, DSG.Node] = {n.txn.id: n for n in self._nodes}\n        for cycle in nx.simple_cycles(graph):\n            converted: List[DSG.Node] = convert_cycle(node_map, cycle)\n            cycles.append(converted)\n            yield converted\n\n        self._cycles[tuple(anom_types)] = cycles\n        logger.info(\"found {} node cycles in the DSG\".format(len(self._cycles[tuple(anom_types)])))\n\n    def find_anomalies(self, anomalies: List[Any]) -> Iterable[Anomaly]:\n        def classify_cycle(node_cycle: List[DSG.Node], final_txn: ObservedTransaction) -> Iterable[Anomaly]:\n            \"\"\"\n            classify a cycle, turning it into a list of anomalies\n\n            return the list of anomalies from the cycle\n            note that since to transactions can be connected by more than one\n            edge (of different types), it needs to be possible to return more\n            than one anomaly from that cycle\n            \"\"\"\n\n            edge_cycles: List[List[DSG.Edge]] = [[]]\n            for u, v in zip(node_cycle, node_cycle[1:] + node_cycle[0:]):\n                edges: List[DSG.Edge] = list(filter(lambda e: e.target == v, u.edges))\n                for edge_cycle in edge_cycles:\n                    # necessary because we add to edge_cycles in this loop\n                    #\n                    if len(edge_cycle) > 0 and edge_cycle[-1].target == v:\n                        continue\n\n                    edge_cycle.append(edges[0])\n                    for e in edges[1:]:\n                        edge_cycles.append(edge_cycle[:-1] + [e])\n\n            for edge_cycle in edge_cycles:\n                yield DSG.CyclicalAnomaly(self, node_cycle, edge_cycle, final_txn)\n\n        for node_cycle in self.find_cycles(anomalies):\n            for a in classify_cycle(node_cycle, self._hist.get_observed_txn(self._hist.txn_range()[1])):\n                if any(anom in anomalies for anom in DSG.CyclicalAnomaly.cyclical_closure(a.type())):\n                    yield a\n\n    @staticmethod\n    def list_to_dot(stmts: List[Tuple[Node, Edge]]) -> str:\n        \"\"\"\n        Convert a list of (node, edge) pairs into a DOT representation\n        WW and WR conflicts have solid arrows\n        RW and PRW have dashed arrows (similar to how Adya represents them)\n        \"\"\"\n\n        return \"\"\"\ndigraph DSG {{\n{}\nedge [style=dashed]\n{}\n}}\n\"\"\".format(\n            \"\\t\"\n            + \"\\n\\t\".join(\n                \"{} -> {} [label={}];\".format(n, edge.target, repr(edge.type))\n                for n, edge in filter(\n                    lambda x: x[1].type not in [DSG.Edge.Type.RW, DSG.Edge.Type.PRW],\n                    stmts,\n                )\n            ),\n            \"\\t\"\n            + \"\\n\\t\".join(\n                \"{} -> {} [label={}];\".format(n, edge.target, repr(edge.type))\n                for n, edge in filter(lambda x: x[1].type in [DSG.Edge.Type.RW, DSG.Edge.Type.PRW], stmts)\n            ),\n        )\n\n    def dump_dot(self, anomalies: List[Any], full: bool = False) -> str:\n        \"\"\"\n        Dump a DOT file with the DSG\n        If <full> include all *committed* transactions. Otherwise, only the cycles.\n        \"\"\"\n\n        stmts: List[Tuple[DSG.Node, DSG.Edge]] = list()\n        if full:\n            for node in self._nodes:\n                for edge in node.edges:\n                    stmts.append((node, edge))\n        else:\n            cycle_nodes: Set[DSG.Node] = set(sum((c for c in self.find_cycles(anomalies)), []))\n            for node in cycle_nodes:\n                for edge in filter(lambda e: e.target in cycle_nodes, node.edges):\n                    stmts.append((node, edge))\n\n        return DSG.list_to_dot(stmts)\n\n    def dump_dots(self, anomalies: List[Any]) -> List[str]:\n        \"\"\"\n        Dump a DOT file for each cycle\n        \"\"\"\n        dot_list: List[str] = list()\n        for cycle in self.find_cycles(anomalies):\n            stmts: List[Tuple[DSG.Node, DSG.Edge]] = list()\n            for node in cycle:\n                for edge in filter(lambda e: e.target in cycle, node.edges):\n                    stmts.append((node, edge))\n\n            dot_list.append(DSG.list_to_dot(stmts))\n\n        return dot_list\n", "meta": {"hexsha": "0b318afd4206edf52c7396e4a03b531e835af5f0", "size": 36479, "ext": "py", "lang": "Python", "max_stars_repo_path": "frodo/cycle.py", "max_stars_repo_name": "memsql/frodo", "max_stars_repo_head_hexsha": "d7fb7f055399eb5873ea4a5a7b6780608faf2402", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-09-11T20:04:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T23:59:20.000Z", "max_issues_repo_path": "frodo/cycle.py", "max_issues_repo_name": "memsql/frodo", "max_issues_repo_head_hexsha": "d7fb7f055399eb5873ea4a5a7b6780608faf2402", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "frodo/cycle.py", "max_forks_repo_name": "memsql/frodo", "max_forks_repo_head_hexsha": "d7fb7f055399eb5873ea4a5a7b6780608faf2402", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8677595628, "max_line_length": 202, "alphanum_fraction": 0.5238356315, "include": true, "reason": "import networkx", "num_tokens": 8016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.36296920551961676, "lm_q1q2_score": 0.19281264421804578}}
{"text": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Union\nfrom warnings import filterwarnings\n\nimport pyopencl as cl\nimport pyopencl.array as cla\n\nimport numpy as np\nfrom gpyfft.fft import FFT\n\nfrom ._util import get_context\n\nfilterwarnings(\"ignore\", module=\"pyopencl\")\n\n\nif TYPE_CHECKING:\n    from reikna.cluda.cuda import Array as cudaArray\n    from reikna.cluda.ocl import Array as oclArray\n\n    Array = Union[cudaArray, oclArray]\n\ncontext = get_context()\nqueue = cl.CommandQueue(context)\n\n#  plan cache\n_PLAN_CACHE = {}\n\n\ndef _normalize_axes(dshape, axes):\n    \"\"\"Convert possibly negative axes to positive axes.\"\"\"\n    if axes is None:\n        return None\n    _axes = [axes] if np.isscalar(axes) else list(axes)\n    try:\n        return tuple(np.arange(len(dshape))[_axes])\n    except Exception as e:\n        raise TypeError(f\"Cannot normalize axes {axes}: {e}\")\n\n\ndef _get_fft_plan(arr, axes=None, fast_math=False):\n    \"\"\"Cache and return a reikna FFT plan suitable for `arr` type and shape.\"\"\"\n    axes = _normalize_axes(arr.shape, axes)\n    plan_key = (arr.shape, arr.dtype, axes, fast_math)\n\n    if plan_key not in _PLAN_CACHE:\n        _PLAN_CACHE[plan_key] = FFT(context, queue, arr, axes=axes, fast_math=fast_math)\n\n    return _PLAN_CACHE[plan_key]\n\n\ndef _fftn(\n    input_arr: np.ndarray | Array,\n    output_arr: np.ndarray | Array = None,\n    axes: tuple[int, ...] | None = None,\n    inplace: bool = False,\n    fast_math: bool = True,\n    *,\n    _inverse: bool = False,\n) -> Array:\n    \"\"\"Perform fast Fourier transformation on `input_array`.\n\n    Parameters\n    ----------\n    input_arr : numpy or OCL array\n        A numpy or OCL array to transform.  If an OCL array is provided, it must already\n        be of type `complex64`.  If a numpy array is provided, it will be converted\n        to `float32` before the transformation is performed.\n    output_arr : numpy or OCL array, optional\n        An optional array/buffer to use for output, by default None\n    axes : tuple of int, optional\n        T tuple with axes over which to perform the transform.\n        If not given, the transform is performed over all the axes., by default None\n    inplace : bool, optional\n        Whether to place output data in the `input_arr` buffer, by default False\n    fast_math : bool, optional\n        Whether to enable fast (less precise) mathematical operations during\n        compilation, by default True\n    _inverse : bool, optional\n        Perform inverse FFT, by default False.  (prefer using `ifftn`)\n\n    Returns\n    -------\n    OCLArray\n        result of transformation (still on GPU). Use `.get()` or `cle.pull`\n        to retrieve from GPU.\n        If `inplace` or  `output_arr` where used, data will also be placed in\n        the corresponding buffer as a side effect.\n\n    Raises\n    ------\n    TypeError\n        If OCL array is provided that is not of type complex64.  Or if an unrecognized\n        array is provided.\n    ValueError\n        If inplace is used for numpy array, or both `output_arr` and `inplace` are used.\n    \"\"\"\n    if output_arr is not None and inplace:\n        raise ValueError(\"`output_arr` cannot be provided if `inplace` is True\")\n    assert input_arr.dtype in (np.float32, np.float64, np.complex64, np.complex128)\n\n    if not np.iscomplexobj(input_arr):\n        input_arr = input_arr.astype(np.complex64)  # TODO\n\n    _input_array = (\n        cla.to_device(queue, input_arr)\n        if isinstance(input_arr, np.ndarray)\n        else input_arr\n    )\n    transform = _get_fft_plan(_input_array, axes=axes, fast_math=fast_math)\n\n    if not inplace:\n        if output_arr is None:\n            output_arr = cla.empty_like(_input_array)\n        transform.result = output_arr\n\n    (event,) = transform.enqueue(forward=not _inverse)\n    event.wait()\n\n    if not inplace:\n        return output_arr\n    return _input_array\n\n\ndef fft(\n    input_arr: np.ndarray | Array,\n    output_arr: np.ndarray | Array = None,\n    axes: int = -1,\n    inplace: bool = False,\n    fast_math: bool = True,\n) -> Array:\n    return fftn(input_arr, output_arr, (axes,), inplace, fast_math)\n\n\ndef ifft(\n    input_arr: np.ndarray | Array,\n    output_arr: np.ndarray | Array = None,\n    axes: int = -1,\n    inplace: bool = False,\n    fast_math: bool = True,\n) -> Array:\n    return ifftn(input_arr, output_arr, (axes,), inplace, fast_math)\n\n\ndef fft2(\n    input_arr: np.ndarray | Array,\n    output_arr: np.ndarray | Array = None,\n    axes: tuple[int, int] = (-2, -1),\n    inplace: bool = False,\n    fast_math: bool = True,\n) -> Array:\n    return fftn(input_arr, output_arr, axes, inplace, fast_math)\n\n\ndef ifft2(\n    input_arr: np.ndarray | Array,\n    output_arr: np.ndarray | Array = None,\n    axes: tuple[int, int] = (-2, -1),\n    inplace: bool = False,\n    fast_math: bool = True,\n) -> Array:\n    return ifftn(input_arr, output_arr, axes, inplace, fast_math)\n\n\ndef fftn(\n    input_arr: np.ndarray | Array,\n    output_arr: np.ndarray | Array = None,\n    axes: tuple[int, ...] | None = None,\n    inplace: bool = False,\n    fast_math: bool = True,\n) -> Array:\n    return _fftn(input_arr, output_arr, axes, inplace, fast_math)\n\n\ndef ifftn(\n    input_arr,\n    output_arr=None,\n    axes=None,\n    inplace=False,\n    fast_math=True,\n):\n    return _fftn(input_arr, output_arr, axes, inplace, fast_math, _inverse=True)\n\n\ndef rfft(\n    input_arr: np.ndarray | Array,\n    output_arr: np.ndarray | Array = None,\n    axes: int = -1,\n    inplace: bool = False,\n    fast_math: bool = True,\n) -> Array:\n    x = _fftn(input_arr, output_arr, (axes,), inplace, fast_math)\n    return x[:, : input_arr.shape[-1] // 2 + 1]\n\n\n# FIXME\n# def irfft(\n#     input_arr: np.ndarray | Array,\n#     output_arr: np.ndarray | Array = None,\n#     axes: int = -1,\n#     inplace: bool = False,\n#     fast_math: bool = True,\n# ) -> Array:\n#     x = _fftn(input_arr, output_arr, axes, inplace, fast_math, _inverse=True)\n#     shp = list(input_arr.shape)\n#     n = shp[axes]\n#     shp[axes] = 2 * n - 2\n#     result = empty(shp, np.float32)\n#     result[..., :n] = x.real\n#     result[..., n - 1 :] = x.real[..., 1:][::-1]\n#     return result.astype(np.float64)\n\n\ndef rfft2(\n    input_arr: np.ndarray | Array,\n    output_arr: np.ndarray | Array = None,\n    axes: tuple[int, int] = (-2, -1),\n    inplace: bool = False,\n    fast_math: bool = True,\n) -> Array:\n    x = _fftn(input_arr, output_arr, axes, inplace, fast_math)\n    return x[:, : input_arr.shape[1] // 2 + 1]\n\n\n# FIXME\n# def irfft2(\n#     input_arr: np.ndarray | Array,\n#     output_arr: np.ndarray | Array = None,\n#     axes: Tuple[int, int] = (-2, -1),\n#     inplace: bool = False,\n#     fast_math: bool = True,\n# ) -> Array:\n#     x = _fftn(input_arr, output_arr, axes, inplace, fast_math)\n#     return x[:, : input_arr.shape[1] // 2 + 1]\n\n\ndef rfftn(\n    input_arr: np.ndarray | Array,\n    output_arr: np.ndarray | Array = None,\n    axes: tuple[int, ...] | None = None,\n    inplace: bool = False,\n    fast_math: bool = True,\n) -> Array:\n    x = _fftn(input_arr, output_arr, axes, inplace, fast_math)\n    return x[:, : input_arr.shape[1] // 2 + 1]\n\n\n# FIXME\n# def irfftn(\n#     input_arr: np.ndarray | Array,\n#     output_arr: np.ndarray | Array = None,\n#     axes: tuple[int, ...] | None = None,\n#     inplace: bool = False,\n#     fast_math: bool = True,\n# ) -> Array:\n#     x = _fftn(input_arr, output_arr, axes, inplace, fast_math)\n#     return x[..., : input_arr.shape[1] // 2 + 1]\n", "meta": {"hexsha": "81071cd36ae3927f25941d70868ac2b0c4d17661", "size": 7429, "ext": "py", "lang": "Python", "max_stars_repo_path": "anyfft/gpyfft/_fft.py", "max_stars_repo_name": "tlambert03/anyfft", "max_stars_repo_head_hexsha": "2b5fb526fa96d7ed607765383adb8c198f505232", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "anyfft/gpyfft/_fft.py", "max_issues_repo_name": "tlambert03/anyfft", "max_issues_repo_head_hexsha": "2b5fb526fa96d7ed607765383adb8c198f505232", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "anyfft/gpyfft/_fft.py", "max_forks_repo_name": "tlambert03/anyfft", "max_forks_repo_head_hexsha": "2b5fb526fa96d7ed607765383adb8c198f505232", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7945736434, "max_line_length": 88, "alphanum_fraction": 0.6393861893, "include": true, "reason": "import numpy", "num_tokens": 2024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.36296920551961676, "lm_q1q2_score": 0.1928126388304558}}
{"text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n'''\n * Copyright (c) 2017, Matthias Julius Kannwischer\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n#./simulation/simulate 500 HW_BYTE 33c0364151e93bbda2896900f18c987737593ff2abc2f8a2220f54c58aa71968\n##### SIMULATING POWER TRACE #####\n#seed=0x33c0364151e93bbda2896900f18c987737593ff2abc2f8a2220f54c58aa71968\n#leakage_type=3\n#Creating 500 traces\n#iv[0]=0x6a09e667bb67ae853c6ef372a54ff53a510e527f9b05688c1f83d9ab5be0cd19\n#iv[1]=0x13e087020936aab9a2ecc5396601faf1a919aa0e8f4074c1e21173981cce9431\n#a_0=0x13e08702\n#b_0=0x0936aab9\n#c_0=0xa2ecc539\n#d_0=0x6601faf1\n#e_0=0xa919aa0e\n#f_0=0x8f4074c1\n#g_0=0xe2117398\n#h_0=0x1cce9431\n#delta=0x21fd7822\n#T2=0x42d93dc4\n#leakage_500.bin\n\n#./analysis/analyze_8bit.py leakage_500.bin secret_data.txt\n\nR = np.load(\"../data/correlation_values.npy\")\nR[np.isnan(R)] = 0\nR = np.absolute(R)\nprint R.shape\n\ncorrect_hyp = R[:, 0x22]\nwrong_hyp   = R[:, 0x42]\nprint correct_hyp[0:10];\n\n\ndef plot_overtime(d, fname):\n\n    plt.plot(d)\n\n\n# correlation over time\nf, axarr = plt.subplots(2, sharex=True, figsize=(11,5))\naxarr[0].plot(correct_hyp)\naxarr[0].set_title(\"correct hypothesis (34)\")\naxarr[1].plot(wrong_hyp)\naxarr[1].set_title(\"wrong hypothesis (66)\")\nplt.xlim(xmin=17000)\nplt.xlim(xmax=32000)\nplt.ylim(ymax=1.0)\n# dummy subplot for the axis\nax = f.add_subplot(111, frameon=False)\nax.set_yticklabels([])\nax.set_xticklabels([])\nax.set_ylabel(\"Pearson correlation coefficient\",labelpad=25)\nplt.xlabel(\"index of sample\",labelpad=20)\nplt.tight_layout()\nf.savefig(\"correlation_over_time.pdf\")\n\n\n# correlation of different hyptohesis\nf = plt.figure(figsize=(11,3.5))\nprint np.where(R == 1.0)\nd = R[20980, :]\nplt.bar(range(0,256), d, edgecolor=\"none\")\nplt.xlabel(\"key hypothesis\")\nplt.ylabel(\"Pearon correlation coefficient\")\nplt.xlim(xmax=255)\nplt.tight_layout()\n\nf.savefig(\"max_correlation.pdf\");\n", "meta": {"hexsha": "bab831e6059de091f64aa0e4f4ac07e818c39574", "size": 3206, "ext": "py", "lang": "Python", "max_stars_repo_path": "plots/corr_over_time.py", "max_stars_repo_name": "mkannwischer/xmss-prng-dpa", "max_stars_repo_head_hexsha": "440ce76cda6f084e2e74c61e6fad10193bc7943f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-08-23T14:45:22.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-01T23:57:27.000Z", "max_issues_repo_path": "plots/corr_over_time.py", "max_issues_repo_name": "mkannwischer/xmss-prng-dpa", "max_issues_repo_head_hexsha": "440ce76cda6f084e2e74c61e6fad10193bc7943f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plots/corr_over_time.py", "max_forks_repo_name": "mkannwischer/xmss-prng-dpa", "max_forks_repo_head_hexsha": "440ce76cda6f084e2e74c61e6fad10193bc7943f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.06, "max_line_length": 99, "alphanum_fraction": 0.7679351216, "include": true, "reason": "import numpy", "num_tokens": 969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.19277782742286617}}
{"text": "__VERSION__=\"ete2-2.2rev1056\" \n# -*- coding: utf-8 -*-\n# #START_LICENSE###########################################################\n#\n#\n# This file is part of the Environment for Tree Exploration program\n# (ETE).  http://ete.cgenomics.org\n#  \n# ETE is free software: you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#  \n# ETE is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public\n# License for more details.\n#  \n# You should have received a copy of the GNU General Public License\n# along with ETE.  If not, see <http://www.gnu.org/licenses/>.\n#\n# \n#                     ABOUT THE ETE PACKAGE\n#                     =====================\n# \n# ETE is distributed under the GPL copyleft license (2008-2011).  \n#\n# If you make use of ETE in published work, please cite:\n#\n# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon.\n# ETE: a python Environment for Tree Exploration. Jaime BMC\n# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24\n#\n# Note that extra references to the specific methods implemented in \n# the toolkit are available in the documentation. \n# \n# More info at http://ete.cgenomics.org\n#\n# \n# #END_LICENSE#############################################################\n\nimport numpy\nfrom math import sqrt \n\ndef safe_mean(values):\n    \"\"\" Returns mean value discarding non finite values \"\"\"\n    valid_values = []\n    for v in values:\n        if numpy.isfinite(v):\n            valid_values.append(v)\n    return numpy.mean(valid_values), numpy.std(valid_values)\n\ndef safe_mean_vector(vectors):\n    \"\"\" Returns mean profile discarding non finite values.\n    \"\"\"\n    # if only one vector, avg = itself\n    if len(vectors)==1:\n        return vectors[0], numpy.zeros(len(vectors[0]))\n    # Takes the vector length form the first item\n    length = len(vectors[0])\n\n    safe_mean = []\n    safe_std  = []\n\n    for pos in xrange(length):\n        pos_mean = []\n        for v in vectors:\n            if numpy.isfinite(v[pos]):\n                pos_mean.append(v[pos])\n        safe_mean.append(numpy.mean(pos_mean))\n        safe_std.append(numpy.std(pos_mean))\n    return numpy.array(safe_mean), numpy.array(safe_std)\n\ndef get_silhouette_width(fdist, cluster):\n    sisters = cluster.get_sisters()\n\n    # Calculates silhouette\n    silhouette = []\n    intra_dist = []\n    inter_dist = []\n    for st in sisters:\n        if st.profile is None:\n            continue\n        for i in cluster.iter_leaves():\n            # Skip nodes without profile\n            if i._profile is not None:\n                # item intraclsuterdist -> Centroid Diameter\n                a = fdist(i.profile, cluster.profile)*2\n                # intracluster dist -> Centroid Linkage\n                b = fdist(i.profile, st.profile)\n\n                if (b-a) == 0.0:\n                    s = 0.0\n                else:\n                    s =  (b-a) / max(a,b)\n\n                intra_dist.append(a)\n                inter_dist.append(b)\n                silhouette.append(s)\n\n    silhouette, std = safe_mean(silhouette)\n    intracluster_dist, std = safe_mean(intra_dist)\n    intercluster_dist, std = safe_mean(inter_dist)\n    return silhouette, intracluster_dist, intercluster_dist\n\ndef get_avg_profile(node):\n    \"\"\" This internal function updates the mean profile\n    associated to an internal node. \"\"\"\n\n    if not node.is_leaf():\n        leaf_vectors = [n._profile for n in  node.get_leaves() \\\n                            if n._profile is not None]\n        if len(leaf_vectors)>0:\n            node._profile, node._std_profile = safe_mean_vector(leaf_vectors)\n        else:\n            node._profile, node._std_profile = None, None\n        return node._profile, node._std_profile\n    else:\n        node._std_profile = [0.0]*len(node._profile)\n        return node._profile, [0.0]*len(node._profile)\n\n\ndef get_dunn_index(fdist, *clusters):\n    \"\"\"\n    Returns the Dunn index for the given selection of nodes.\n\n    J.C. Dunn. Well separated clusters and optimal fuzzy\n    partitions. 1974. J.Cybern. 4. 95-104.\n\n    \"\"\"\n\n    if len(clusters)<2:\n        raise ValueError, \"At least 2 clusters are required\"\n\n    intra_dist = []\n    for c in clusters:\n        for i in c.get_leaves():\n            if i is not None:\n                # item intraclsuterdist -> Centroid Diameter\n                a = fdist(i.profile, c.profile)*2\n                intra_dist.append(a)\n    max_a = numpy.max(intra_dist)\n    inter_dist = []\n    for i, ci in enumerate(clusters):\n        for cj in clusters[i+1:]:\n            # intracluster dist -> Centroid Linkage\n            b = fdist(ci.profile, cj.profile)\n            inter_dist.append(b)\n    min_b = numpy.min(inter_dist)\n\n    if max_a == 0.0:\n        D = 0.0\n    else:\n        D = min_b / max_a\n    return D\n\n\n\n# ####################\n# distance functions\n# ####################\n\ndef pearson_dist(v1, v2):\n    if (v1 == v2).all():\n        return 0.0\n    else:\n        return 1.0 - stats.pearsonr(list(v1),list(v2))[0]\n \ndef spearman_dist(v1, v2):\n    if (v1 == v2).all():\n        return 0.0\n    else:\n        return 1.0 - stats.spearmanr(list(v1),list(v2))[0]\n\ndef euclidean_dist(v1,v2):\n    if (v1 == v2).all():\n        return 0.0\n    else:\n        return sqrt( square_euclidean_dist(v1,v2) )\n\ndef square_euclidean_dist(v1,v2):\n    if (v1 == v2).all():\n        return 0.0\n    valids  = 0\n    distance= 0.0\n    for i in xrange(len(v1)):\n        if numpy.isfinite(v1[i]) and numpy.isfinite(v2[i]):\n            valids += 1\n            d = v1[i]-v2[i]\n            distance += d*d\n    if valids==0:\n        raise ValueError, \"Cannot calculate values\"\n    return  distance/valids\n\ntry: \n   from scipy import stats\nexcept ImportError: \n    try:\n        import stats\n        default_dist = spearman_dist\n    except ImportError:\n        default_dist = euclidean_dist\nelse:\n    default_dist = spearman_dist\n", "meta": {"hexsha": "3afacdfa2c982a44715bd2e1b0b48fa73f8a3027", "size": 6103, "ext": "py", "lang": "Python", "max_stars_repo_path": "ete2/clustering/clustvalidation.py", "max_stars_repo_name": "csc8630Spring2014/Clusterizer", "max_stars_repo_head_hexsha": "f64b0cabfbf4fa117b73a2af9355f67cc9207fe5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-05-10T02:51:51.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-10T02:51:51.000Z", "max_issues_repo_path": "ete2/clustering/clustvalidation.py", "max_issues_repo_name": "csc8630Spring2014/Clusterizer", "max_issues_repo_head_hexsha": "f64b0cabfbf4fa117b73a2af9355f67cc9207fe5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ete2/clustering/clustvalidation.py", "max_forks_repo_name": "csc8630Spring2014/Clusterizer", "max_forks_repo_head_hexsha": "f64b0cabfbf4fa117b73a2af9355f67cc9207fe5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7707317073, "max_line_length": 77, "alphanum_fraction": 0.5962641324, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19277782022841536}}
{"text": "\"\"\"Atmospheric soundings.\n\n--- NOTATION ---\n\nThe following letters will be used throughout this module.\n\nT = number of lead times\nn = number of storm objects\np = number of pressure levels, not including surface\nP = number of pressure levels, including surface\nF = number of sounding fields\n\nN = number of soundings = T*n\n\"\"\"\n\nimport os.path\nimport numpy\nimport pandas\nimport netCDF4\nfrom scipy.interpolate import interp1d as scipy_interp1d\nfrom gewittergefahr.gg_io import grib_io\nfrom gewittergefahr.gg_io import netcdf_io\nfrom gewittergefahr.gg_utils import geodetic_utils\nfrom gewittergefahr.gg_utils import nwp_model_utils\nfrom gewittergefahr.gg_utils import storm_tracking_utils as tracking_utils\nfrom gewittergefahr.gg_utils import interp\nfrom gewittergefahr.gg_utils import moisture_conversions\nfrom gewittergefahr.gg_utils import temperature_conversions\nfrom gewittergefahr.gg_utils import time_conversion\nfrom gewittergefahr.gg_utils import file_system_utils\nfrom gewittergefahr.gg_utils import error_checking\n\nSEPARATOR_STRING = '\\n\\n' + '*' * 50 + '\\n\\n'\nTIME_FORMAT_IN_FILE_NAMES = '%Y-%m-%d-%H%M%S'\n\nMB_TO_PASCALS = 100\nPASCALS_TO_MB = 0.01\nPERCENT_TO_UNITLESS = 0.01\n\nPRESSURE_LEVEL_KEY = 'pressure_level_mb'\nLEAD_TIME_KEY = 'lead_time_seconds'\nLAG_TIME_KEY = 'lag_time_for_convective_contamination_sec'\nINITIAL_TIME_COLUMN = 'init_time_unix_sec'\nFORECAST_TIME_COLUMN = 'forecast_time_unix_sec'\n\nFULL_IDS_KEY = 'full_storm_id_strings'\nINITIAL_TIMES_KEY = 'init_times_unix_sec'\nLEAD_TIMES_KEY = 'lead_times_seconds'\nSTORM_ELEVATIONS_KEY = 'storm_elevations_m_asl'\nSOUNDING_MATRIX_KEY = 'sounding_matrix'\nSURFACE_PRESSURES_KEY = 'surface_pressures_mb'\nPRESSURE_LEVELS_WITH_SFC_KEY = 'pressure_levels_with_surface_mb'\nHEIGHT_LEVELS_KEY = 'height_levels_m_agl'\nFIELD_NAMES_KEY = 'field_names'\n\nGEOPOTENTIAL_HEIGHT_NAME = nwp_model_utils.HEIGHT_COLUMN_FOR_SOUNDINGS\nRELATIVE_HUMIDITY_NAME = 'relative_humidity_unitless'\nTEMPERATURE_NAME = nwp_model_utils.TEMPERATURE_COLUMN_FOR_SOUNDINGS\nU_WIND_NAME = nwp_model_utils.U_WIND_COLUMN_FOR_SOUNDINGS\nV_WIND_NAME = nwp_model_utils.V_WIND_COLUMN_FOR_SOUNDINGS\nSPECIFIC_HUMIDITY_NAME = nwp_model_utils.SPFH_COLUMN_FOR_SOUNDINGS\nVIRTUAL_POTENTIAL_TEMPERATURE_NAME = 'virtual_potential_temperature_kelvins'\nPRESSURE_NAME = 'pressure_pascals'\n\nVALID_FIELD_NAMES = [\n    GEOPOTENTIAL_HEIGHT_NAME, RELATIVE_HUMIDITY_NAME, TEMPERATURE_NAME,\n    U_WIND_NAME, V_WIND_NAME, SPECIFIC_HUMIDITY_NAME,\n    VIRTUAL_POTENTIAL_TEMPERATURE_NAME, PRESSURE_NAME\n]\n\nFIELD_NAME_TO_VERBOSE_DICT = {\n    GEOPOTENTIAL_HEIGHT_NAME: 'Geopotential height (m)',\n    RELATIVE_HUMIDITY_NAME: 'Relative humidity',\n    TEMPERATURE_NAME: 'Temperature (K)',\n    U_WIND_NAME: r'$u$-wind (m s$^{-1}$)',\n    V_WIND_NAME: r'$v$-wind (m s$^{-1}$)',\n    SPECIFIC_HUMIDITY_NAME: r'Specific humidity (kg kg$^{-1}$)',\n    VIRTUAL_POTENTIAL_TEMPERATURE_NAME: 'Virtual potential temperature (K)',\n    PRESSURE_NAME: 'Pressure (Pa)'\n}\n\nFIELD_NAME_TO_VERBOSE_UNITLESS_DICT = {\n    GEOPOTENTIAL_HEIGHT_NAME: 'Geopotential height',\n    RELATIVE_HUMIDITY_NAME: 'Relative humidity',\n    TEMPERATURE_NAME: 'Temperature',\n    U_WIND_NAME: r'$u$-wind',\n    V_WIND_NAME: r'$v$-wind',\n    SPECIFIC_HUMIDITY_NAME: 'Specific humidity',\n    VIRTUAL_POTENTIAL_TEMPERATURE_NAME: 'Virtual potential temperature',\n    PRESSURE_NAME: 'Pressure'\n}\n\nSTORM_OBJECT_DIMENSION_KEY = 'storm_object'\nFIELD_DIMENSION_KEY = 'field'\nHEIGHT_DIMENSION_KEY = 'height_level'\nSTORM_ID_CHAR_DIMENSION_KEY = 'storm_id_character'\nFIELD_NAME_CHAR_DIMENSION_KEY = 'field_name_character'\n\n# Field names for MetPy.\nPRESSURE_COLUMN_METPY = 'pressures_mb'\nTEMPERATURE_COLUMN_METPY = 'temperatures_deg_c'\nDEWPOINT_COLUMN_METPY = 'dewpoints_deg_c'\nU_WIND_COLUMN_METPY = 'u_winds_kt'\nV_WIND_COLUMN_METPY = 'v_winds_kt'\n\nDEFAULT_LEAD_TIMES_SEC = numpy.array([0], dtype=int)\nDEFAULT_LAG_TIME_FOR_CONVECTIVE_CONTAMINATION_SEC = 1800\nDEFAULT_HEIGHT_LEVELS_M_AGL = numpy.linspace(0, 12000, num=49, dtype=int)\n\n\ndef _get_nwp_fields_for_sounding(\n        model_name, return_table, include_surface=False,\n        minimum_pressure_mb=0.):\n    \"\"\"Returns list of NWP fields needed to create sounding.\n\n    :param model_name: Model name (must be accepted by\n        `nwp_model_utils.check_model_name`).\n    :param return_table: Boolean flag.  See below for how this affects output.\n    :param include_surface: Boolean flag.  If True, this method will return the\n        \"surface\" (2-metre or 10-metre) level for each field.\n    :param minimum_pressure_mb: Leave this alone.\n\n    :return: sounding_field_names: [None if return_table = True]\n        length-F list with names of sounding fields (GewitterGefahr format).\n    :return: sounding_field_names_grib1: [None if return_table = True]\n        length-F list with names of sounding fields (grib1 format).\n    :return: sounding_field_name_table: [None if return_table = False]\n        pandas DataFrame with the following columns.  Each row is one pressure\n        level.  Only one of \"relative_humidity_percent\" and \"specific_humidity\"\n        (depending on the NWP model) will be present.\n    sounding_field_name_table.geopotential_height_metres: Name of geopotential-\n        height field.\n    sounding_field_name_table.temperature_kelvins: Name of temperature field.\n    sounding_field_name_table.relative_humidity_percent: Name of humidity field.\n    sounding_field_name_table.specific_humidity: Name of humidity field.\n    sounding_field_name_table.u_wind_m_s01: Name of u-wind field.\n    sounding_field_name_table.v_wind_m_s01: Name of v-wind field.\n    sounding_field_name_table.pressure_level_mb: Pressure level (millibars).\n        The surface is denoted by NaN.\n    \"\"\"\n\n    nwp_model_utils.check_model_name(model_name)\n    error_checking.assert_is_boolean(return_table)\n    error_checking.assert_is_geq(minimum_pressure_mb, 0.)\n    error_checking.assert_is_boolean(include_surface)\n\n    pressure_levels_no_surface_mb = nwp_model_utils.get_pressure_levels(\n        model_name=model_name, grid_name=nwp_model_utils.NAME_OF_130GRID\n    ).astype(float)\n\n    pressure_levels_no_surface_mb = pressure_levels_no_surface_mb[\n        pressure_levels_no_surface_mb >= minimum_pressure_mb\n    ]\n\n    if include_surface:\n        pressure_levels_with_surface_mb = numpy.concatenate((\n            pressure_levels_no_surface_mb, numpy.array([numpy.nan])\n        ))\n    else:\n        pressure_levels_with_surface_mb = pressure_levels_no_surface_mb + 0.\n\n    num_pressure_levels_no_surface = len(pressure_levels_no_surface_mb)\n    num_pressure_levels_with_surface = len(pressure_levels_with_surface_mb)\n\n    field_names, field_names_grib1 = (\n        nwp_model_utils.get_columns_in_sounding_table(model_name)\n    )\n\n    num_fields = len(field_names)\n    sounding_field_name_table = None\n    sounding_field_names = []\n    sounding_field_names_grib1 = []\n\n    if return_table:\n        sounding_field_name_dict = {\n            PRESSURE_LEVEL_KEY: pressure_levels_with_surface_mb\n        }\n\n        list_of_empty_strings = [''] * num_pressure_levels_with_surface\n        for j in range(num_fields):\n            sounding_field_name_dict.update({\n                field_names[j]: list_of_empty_strings\n            })\n\n        sounding_field_name_table = pandas.DataFrame.from_dict(\n            sounding_field_name_dict)\n\n    for j in range(num_fields):\n        for k in range(num_pressure_levels_no_surface):\n            this_field_name = '{0:s}_{1:d}mb'.format(\n                field_names[j],\n                int(numpy.round(pressure_levels_no_surface_mb[k]))\n            )\n\n            if return_table:\n                sounding_field_name_table[field_names[j]].values[k] = (\n                    this_field_name\n                )\n            else:\n                this_field_name_grib1 = '{0:s}:{1:d} mb'.format(\n                    field_names_grib1[j],\n                    int(numpy.round(pressure_levels_no_surface_mb[k]))\n                )\n\n                sounding_field_names.append(this_field_name)\n                sounding_field_names_grib1.append(this_field_name_grib1)\n\n        if not include_surface:\n            continue\n\n        if field_names[j] == GEOPOTENTIAL_HEIGHT_NAME:\n            this_field_name, this_field_name_grib1 = (\n                nwp_model_utils.get_lowest_height_name(model_name)\n            )\n\n        if field_names[j] == TEMPERATURE_NAME:\n            this_field_name, this_field_name_grib1 = (\n                nwp_model_utils.get_lowest_temperature_name(model_name)\n            )\n\n        if field_names[j] in [nwp_model_utils.RH_COLUMN_FOR_SOUNDINGS,\n                              SPECIFIC_HUMIDITY_NAME]:\n            this_field_name, this_field_name_grib1 = (\n                nwp_model_utils.get_lowest_humidity_name(model_name)\n            )\n\n        if field_names[j] == U_WIND_NAME:\n            this_field_name, this_field_name_grib1 = (\n                nwp_model_utils.get_lowest_u_wind_name(model_name)\n            )\n\n        if field_names[j] == V_WIND_NAME:\n            this_field_name, this_field_name_grib1 = (\n                nwp_model_utils.get_lowest_v_wind_name(model_name)\n            )\n\n        if return_table:\n            sounding_field_name_table[field_names[j]].values[\n                num_pressure_levels_with_surface - 1\n            ] = this_field_name\n        else:\n            sounding_field_names.append(this_field_name)\n            sounding_field_names_grib1.append(this_field_name_grib1)\n\n    if return_table or not include_surface:\n        return (sounding_field_names, sounding_field_names_grib1,\n                sounding_field_name_table)\n\n    this_field_name, this_field_name_grib1 = (\n        nwp_model_utils.get_lowest_pressure_name(model_name)\n    )\n\n    sounding_field_names.append(this_field_name)\n    sounding_field_names_grib1.append(this_field_name_grib1)\n\n    return (sounding_field_names, sounding_field_names_grib1,\n            sounding_field_name_table)\n\n\ndef _create_target_points_for_interp(storm_object_table, lead_times_seconds):\n    \"\"\"Creates target points for interpolation.\n\n    Each target point consists of (latitude, longitude, time).\n\n    :param storm_object_table: pandas DataFrame with columns documented in\n        `storm_tracking_io.write_file`.\n    :param lead_times_seconds: 1-D numpy array of lead times (non-negative\n        integers).  For each lead time t, each storm object will be extrapolated\n        t seconds into the future, along its estimated motion vector.\n    :return: target_point_table: pandas DataFrame with the following columns.\n    target_point_table.full_id_string: Full storm ID.\n    target_point_table.init_time_unix_sec: Initial time (storm time).  Valid\n        time = initial time + lead time.\n    target_point_table.centroid_lat_deg: Latitude (deg N) of extrapolated storm\n        object's centroid.\n    target_point_table.centroid_lng_deg: Longitude (deg E) of extrapolated storm\n        object's centroid.\n    target_point_table.valid_time_unix_sec: Time of extrapolated storm object.\n    target_point_table.lead_time_seconds: Lead time used for extrapolation.\n    target_point_table.east_velocity_m_s01: Eastward component (metres per\n        second) of estimated storm-motion vector.\n    target_point_table.north_velocity_m_s01: Northward component.\n    \"\"\"\n\n    if numpy.any(lead_times_seconds > 0):\n        storm_speeds_m_s01, storm_bearings_deg = (\n            geodetic_utils.xy_to_scalar_displacements_and_bearings(\n                x_displacements_metres=\n                storm_object_table[tracking_utils.EAST_VELOCITY_COLUMN].values,\n                y_displacements_metres=\n                storm_object_table[tracking_utils.NORTH_VELOCITY_COLUMN].values)\n        )\n\n    num_storm_objects = len(storm_object_table.index)\n    num_lead_times = len(lead_times_seconds)\n    list_of_target_point_tables = [None] * num_lead_times\n\n    for i in range(num_lead_times):\n        if lead_times_seconds[i] == 0:\n            list_of_target_point_tables[i] = storm_object_table[[\n                tracking_utils.FULL_ID_COLUMN, tracking_utils.VALID_TIME_COLUMN,\n                tracking_utils.CENTROID_LATITUDE_COLUMN,\n                tracking_utils.CENTROID_LONGITUDE_COLUMN,\n                tracking_utils.EAST_VELOCITY_COLUMN,\n                tracking_utils.NORTH_VELOCITY_COLUMN\n            ]]\n\n            argument_dict = {\n                LEAD_TIME_KEY: numpy.full(num_storm_objects, 0, dtype=int),\n                FORECAST_TIME_COLUMN: list_of_target_point_tables[i][\n                    tracking_utils.VALID_TIME_COLUMN].values\n            }\n\n            list_of_target_point_tables[i] = (\n                list_of_target_point_tables[i].assign(**argument_dict)\n            )\n\n            if i == 0:\n                continue\n\n            list_of_target_point_tables[i] = (\n                list_of_target_point_tables[i].align(\n                    list_of_target_point_tables[0], axis=1\n                )[0]\n            )\n\n            continue\n\n        these_extrap_latitudes_deg, these_extrap_longitudes_deg = (\n            geodetic_utils.start_points_and_displacements_to_endpoints(\n                start_latitudes_deg=storm_object_table[\n                    tracking_utils.CENTROID_LATITUDE_COLUMN].values,\n                start_longitudes_deg=storm_object_table[\n                    tracking_utils.CENTROID_LONGITUDE_COLUMN].values,\n                scalar_displacements_metres=\n                storm_speeds_m_s01 * lead_times_seconds[i],\n                geodetic_bearings_deg=storm_bearings_deg)\n        )\n\n        these_times_unix_sec = (\n            storm_object_table[tracking_utils.VALID_TIME_COLUMN].values +\n            lead_times_seconds[i]\n        )\n\n        this_dict = {\n            tracking_utils.FULL_ID_COLUMN:\n                storm_object_table[tracking_utils.FULL_ID_COLUMN].values,\n            tracking_utils.VALID_TIME_COLUMN:\n                storm_object_table[tracking_utils.VALID_TIME_COLUMN].values,\n            tracking_utils.CENTROID_LATITUDE_COLUMN: these_extrap_latitudes_deg,\n            tracking_utils.CENTROID_LONGITUDE_COLUMN:\n                these_extrap_longitudes_deg,\n            FORECAST_TIME_COLUMN: these_times_unix_sec,\n            tracking_utils.EAST_VELOCITY_COLUMN:\n                storm_object_table[tracking_utils.EAST_VELOCITY_COLUMN].values,\n            tracking_utils.NORTH_VELOCITY_COLUMN:\n                storm_object_table[tracking_utils.NORTH_VELOCITY_COLUMN].values,\n            LEAD_TIME_KEY: numpy.full(\n                num_storm_objects, lead_times_seconds[i], dtype=int)\n        }\n\n        list_of_target_point_tables[i] = pandas.DataFrame.from_dict(this_dict)\n        if i == 0:\n            continue\n\n        list_of_target_point_tables[i] = list_of_target_point_tables[i].align(\n            list_of_target_point_tables[0], axis=1\n        )[0]\n\n    target_point_table = pandas.concat(\n        list_of_target_point_tables, axis=0, ignore_index=True)\n\n    column_dict_old_to_new = {\n        tracking_utils.VALID_TIME_COLUMN: INITIAL_TIME_COLUMN\n    }\n\n    return target_point_table.rename(\n        columns=column_dict_old_to_new, inplace=False)\n\n\ndef _interp_soundings_from_nwp(\n        target_point_table, top_grib_directory_name, include_surface,\n        model_name, use_all_grids, grid_id, wgrib_exe_name, wgrib2_exe_name,\n        raise_error_if_missing):\n    \"\"\"Interpolates soundings from NWP model to target points.\n\n    Each target point consists of (latitude, longitude, time).\n\n    :param target_point_table: pandas DataFrame created by\n        `_create_target_points_for_interp`.\n    :param top_grib_directory_name: See doc for\n        `interp.interp_nwp_from_xy_grid`.\n    :param include_surface: See doc for `_get_nwp_fields_for_sounding`.\n    :param model_name: See doc for `interp.interp_nwp_from_xy_grid`.\n    :param use_all_grids: Same.\n    :param grid_id: Same.\n    :param wgrib_exe_name: Same.\n    :param wgrib2_exe_name: Same.\n    :param raise_error_if_missing: Same.\n    :return: interp_table: pandas DataFrame, where each column is one field and\n        each row is one target point.  Column names are from the list\n    \"\"\"\n\n    sounding_field_names, sounding_field_names_grib1 = (\n        _get_nwp_fields_for_sounding(\n            model_name=model_name, return_table=False,\n            include_surface=include_surface\n        )[:2]\n    )\n    \n    return interp.interp_nwp_from_xy_grid(\n        query_point_table=target_point_table, field_names=sounding_field_names,\n        field_names_grib1=sounding_field_names_grib1, model_name=model_name,\n        top_grib_directory_name=top_grib_directory_name,\n        use_all_grids=use_all_grids, grid_id=grid_id,\n        temporal_interp_method_string=interp.PREV_NEIGHBOUR_METHOD_STRING,\n        spatial_interp_method_string=interp.NEAREST_NEIGHBOUR_METHOD_STRING,\n        wgrib_exe_name=wgrib_exe_name, wgrib2_exe_name=wgrib2_exe_name,\n        raise_error_if_missing=raise_error_if_missing)\n\n\ndef _convert_interp_table_to_soundings(\n        interp_table, target_point_table, model_name, include_surface=False,\n        minimum_pressure_mb=0.):\n    \"\"\"Converts table of interpolated values to list of soundings.\n\n    :param interp_table: N-row pandas DataFrame created by\n        `_interp_soundings_from_nwp`.\n    :param target_point_table: N-row pandas DataFrame created by\n        `_create_target_points_for_interp`.\n    :param model_name: Model name (must be accepted by\n        `nwp_model_utils.check_model_name`).\n    :param include_surface: See doc for `_get_nwp_fields_for_sounding`.\n    :param minimum_pressure_mb: Same.\n    :return: sounding_dict_pressure_coords: Dictionary with the following keys.\n    sounding_dict_pressure_coords['full_storm_id_strings']: length-N list of\n        full IDs.\n    sounding_dict_pressure_coords['init_times_unix_sec']: length-N numpy array\n        of initial times (storm times).  Valid time = initial time + lead time.\n    sounding_dict_pressure_coords['lead_times_seconds']: length-N numpy array of\n        lead times.\n    sounding_dict_pressure_coords['sounding_matrix']: N-by-P-by-F numpy array of\n        sounding values.\n    sounding_dict_pressure_coords['surface_pressures_mb']: length-N numpy array\n        with surface pressure (millibars) for each storm object.  If\n        `include_surface = False`, this is `None`.\n    sounding_dict_pressure_coords['pressure_levels_mb']: length-P numpy array of\n        pressure levels (millibars).  The surface is denoted by NaN.\n    sounding_dict_pressure_coords['field_names']: length-F list of field names.\n    \"\"\"\n\n    sounding_field_name_table = _get_nwp_fields_for_sounding(\n        model_name=model_name, return_table=True,\n        include_surface=include_surface,\n        minimum_pressure_mb=minimum_pressure_mb\n    )[-1]\n\n    if include_surface:\n        surface_pressure_name = nwp_model_utils.get_lowest_pressure_name(\n            model_name\n        )[0]\n\n        surface_pressures_mb = (\n            PASCALS_TO_MB * interp_table[surface_pressure_name].values\n        )\n    else:\n        surface_pressures_mb = None\n\n    field_names = list(sounding_field_name_table)\n    field_names.remove(PRESSURE_LEVEL_KEY)\n\n    pressure_levels_with_surface_mb = sounding_field_name_table[\n        PRESSURE_LEVEL_KEY\n    ].values\n\n    num_fields = len(field_names)\n    num_pressure_levels = len(sounding_field_name_table.index)\n    num_storm_objects = len(interp_table.index)\n\n    sounding_matrix = numpy.full(\n        (num_storm_objects, num_pressure_levels, num_fields), numpy.nan\n    )\n\n    for j in range(num_pressure_levels):\n        for k in range(num_fields):\n            this_field_name = (\n                sounding_field_name_table[field_names[k]].values[j]\n            )\n            sounding_matrix[:, j, k] = interp_table[this_field_name].values\n\n    return {\n        FULL_IDS_KEY:\n            target_point_table[tracking_utils.FULL_ID_COLUMN].values.tolist(),\n        INITIAL_TIMES_KEY: target_point_table[INITIAL_TIME_COLUMN].values,\n        LEAD_TIMES_KEY: target_point_table[LEAD_TIME_KEY].values,\n        SOUNDING_MATRIX_KEY: sounding_matrix,\n        SURFACE_PRESSURES_KEY: surface_pressures_mb,\n        PRESSURE_LEVELS_WITH_SFC_KEY: pressure_levels_with_surface_mb,\n        FIELD_NAMES_KEY: field_names\n    }\n\n\ndef _get_pressures(sounding_dict):\n    \"\"\"Returns pressure levels in soundings.\n\n    :param sounding_dict: Dictionary created by\n        `_convert_interp_table_to_soundings` or `_pressure_to_height_coords`.\n    :return: pressure_matrix_pascals: N-by-P numpy array of pressures.\n    \"\"\"\n\n    if PRESSURE_LEVELS_WITH_SFC_KEY not in sounding_dict:\n        pressure_index = sounding_dict[FIELD_NAMES_KEY].index(PRESSURE_NAME)\n        return sounding_dict[SOUNDING_MATRIX_KEY][..., pressure_index]\n\n    num_storm_objects = sounding_dict[SOUNDING_MATRIX_KEY].shape[0]\n    num_pressure_levels = sounding_dict[SOUNDING_MATRIX_KEY].shape[1]\n    pressure_matrix_pascals = numpy.full(\n        (num_storm_objects, num_pressure_levels), numpy.nan)\n\n    for i in range(num_storm_objects):\n        pressure_matrix_pascals[i, :] = sounding_dict[\n            PRESSURE_LEVELS_WITH_SFC_KEY]\n\n    if sounding_dict[SURFACE_PRESSURES_KEY] is not None:\n        surface_index = numpy.where(\n            numpy.isnan(sounding_dict[PRESSURE_LEVELS_WITH_SFC_KEY]))[0][0]\n        pressure_matrix_pascals[:, surface_index] = sounding_dict[\n            SURFACE_PRESSURES_KEY]\n\n    return MB_TO_PASCALS * pressure_matrix_pascals\n\n\ndef _relative_to_specific_humidity(sounding_dict, pressure_matrix_pascals):\n    \"\"\"Converts relative to specific humidity in each sounding.\n\n    :param sounding_dict: Dictionary created by\n        `_convert_interp_table_to_soundings` or `_pressure_to_height_coords`.\n    :param pressure_matrix_pascals: N-by-P numpy array of pressures.\n    :return: sounding_dict: Same as input, with the following exceptions.\n    [1] contains specific humidity\n    [2] relative humidity is in 0...1, rather than a percentage\n\n    :return: dewpoint_matrix_kelvins: N-by-P numpy array of dewpoints.\n    \"\"\"\n\n    field_names = sounding_dict[FIELD_NAMES_KEY]\n    sounding_matrix = sounding_dict[SOUNDING_MATRIX_KEY]\n    temperature_index = field_names.index(TEMPERATURE_NAME)\n\n    if nwp_model_utils.RH_COLUMN_FOR_SOUNDINGS in field_names:\n        relative_humidity_index = field_names.index(\n            nwp_model_utils.RH_COLUMN_FOR_SOUNDINGS)\n\n        sounding_matrix[..., relative_humidity_index] = (\n            PERCENT_TO_UNITLESS * sounding_matrix[..., relative_humidity_index]\n        )\n\n        field_names[relative_humidity_index] = RELATIVE_HUMIDITY_NAME\n    else:\n        relative_humidity_index = field_names.index(RELATIVE_HUMIDITY_NAME)\n\n    dewpoint_matrix_kelvins = (\n        moisture_conversions.relative_humidity_to_dewpoint(\n            relative_humidities=sounding_matrix[..., relative_humidity_index],\n            temperatures_kelvins=sounding_matrix[..., temperature_index],\n            total_pressures_pascals=pressure_matrix_pascals\n        )\n    )\n\n    spec_humidity_matrix_kg_kg01 = (\n        moisture_conversions.dewpoint_to_specific_humidity(\n            dewpoints_kelvins=dewpoint_matrix_kelvins,\n            temperatures_kelvins=sounding_matrix[..., temperature_index],\n            total_pressures_pascals=pressure_matrix_pascals\n        )\n    )\n\n    if SPECIFIC_HUMIDITY_NAME in field_names:\n        sounding_matrix[\n            ..., field_names.index(SPECIFIC_HUMIDITY_NAME)\n        ] = spec_humidity_matrix_kg_kg01\n    else:\n        field_names.append(SPECIFIC_HUMIDITY_NAME)\n\n        spec_humidity_matrix_kg_kg01 = numpy.reshape(\n            spec_humidity_matrix_kg_kg01,\n            spec_humidity_matrix_kg_kg01.shape + (1,)\n        )\n\n        sounding_matrix = numpy.concatenate(\n            (sounding_matrix, spec_humidity_matrix_kg_kg01), axis=-1\n        )\n\n    sounding_dict[FIELD_NAMES_KEY] = field_names\n    sounding_dict[SOUNDING_MATRIX_KEY] = sounding_matrix\n    return sounding_dict, dewpoint_matrix_kelvins\n\n\ndef _specific_to_relative_humidity(sounding_dict, pressure_matrix_pascals):\n    \"\"\"Converts specific to relative humidity in each sounding.\n\n    :param sounding_dict: Dictionary created by\n        `_convert_interp_table_to_soundings` or `_pressure_to_height_coords`.\n    :param pressure_matrix_pascals: N-by-P numpy array of pressures.\n    :return: sounding_dict: Same as input, but including relative humidity.\n    :return: dewpoint_matrix_kelvins: N-by-P numpy array of dewpoints.\n    \"\"\"\n\n    field_names = sounding_dict[FIELD_NAMES_KEY]\n    sounding_matrix = sounding_dict[SOUNDING_MATRIX_KEY]\n    temperature_index = field_names.index(TEMPERATURE_NAME)\n    specific_humidity_index = field_names.index(SPECIFIC_HUMIDITY_NAME)\n\n    dewpoint_matrix_kelvins = (\n        moisture_conversions.specific_humidity_to_dewpoint(\n            specific_humidities_kg_kg01=\n            sounding_matrix[..., specific_humidity_index],\n            temperatures_kelvins=sounding_matrix[..., temperature_index],\n            total_pressures_pascals=pressure_matrix_pascals\n        )\n    )\n\n    relative_humidity_matrix = (\n        moisture_conversions.dewpoint_to_relative_humidity(\n            dewpoints_kelvins=dewpoint_matrix_kelvins,\n            temperatures_kelvins=sounding_matrix[..., temperature_index],\n            total_pressures_pascals=pressure_matrix_pascals\n        )\n    )\n\n    if RELATIVE_HUMIDITY_NAME in field_names:\n        sounding_matrix[\n            ..., field_names.index(RELATIVE_HUMIDITY_NAME)\n        ] = relative_humidity_matrix\n    else:\n        field_names.append(RELATIVE_HUMIDITY_NAME)\n\n        relative_humidity_matrix = numpy.reshape(\n            relative_humidity_matrix, relative_humidity_matrix.shape + (1,)\n        )\n\n        sounding_matrix = numpy.concatenate(\n            (sounding_matrix, relative_humidity_matrix), axis=-1\n        )\n\n    sounding_dict[FIELD_NAMES_KEY] = field_names\n    sounding_dict[SOUNDING_MATRIX_KEY] = sounding_matrix\n    return sounding_dict, dewpoint_matrix_kelvins\n\n\ndef _get_virtual_potential_temperatures(\n        sounding_dict, pressure_matrix_pascals, dewpoint_matrix_kelvins):\n    \"\"\"Adds virtual potential temperature to each sounding.\n\n    :param sounding_dict: Dictionary created by\n        `_convert_interp_table_to_soundings` or `_pressure_to_height_coords`.\n    :param pressure_matrix_pascals: N-by-P numpy array of pressures.\n    :param dewpoint_matrix_kelvins: N-by-P numpy array of dewpoints.\n    :return: sounding_dict: Same as input, but including virtual potential\n        temperature.\n    \"\"\"\n\n    field_names = sounding_dict[FIELD_NAMES_KEY]\n    sounding_matrix = sounding_dict[SOUNDING_MATRIX_KEY]\n    temperature_index = field_names.index(TEMPERATURE_NAME)\n\n    vapour_pressure_matrix_pascals = (\n        moisture_conversions.dewpoint_to_vapour_pressure(\n            dewpoints_kelvins=dewpoint_matrix_kelvins,\n            temperatures_kelvins=sounding_matrix[..., temperature_index],\n            total_pressures_pascals=pressure_matrix_pascals\n        )\n    )\n\n    virtual_temperature_matrix_kelvins = (\n        moisture_conversions.temperature_to_virtual_temperature(\n            temperatures_kelvins=sounding_matrix[..., temperature_index],\n            total_pressures_pascals=pressure_matrix_pascals,\n            vapour_pressures_pascals=vapour_pressure_matrix_pascals\n        )\n    )\n\n    theta_v_matrix_kelvins = (\n        temperature_conversions.temperatures_to_potential_temperatures(\n            temperatures_kelvins=virtual_temperature_matrix_kelvins,\n            total_pressures_pascals=pressure_matrix_pascals)\n    )\n\n    if VIRTUAL_POTENTIAL_TEMPERATURE_NAME in field_names:\n        sounding_matrix[\n            ..., field_names.index(VIRTUAL_POTENTIAL_TEMPERATURE_NAME)\n        ] = theta_v_matrix_kelvins\n    else:\n        field_names.append(VIRTUAL_POTENTIAL_TEMPERATURE_NAME)\n\n        theta_v_matrix_kelvins = numpy.reshape(\n            theta_v_matrix_kelvins, theta_v_matrix_kelvins.shape + (1,)\n        )\n\n        sounding_matrix = numpy.concatenate(\n            (sounding_matrix, theta_v_matrix_kelvins), axis=-1\n        )\n\n    sounding_dict[FIELD_NAMES_KEY] = field_names\n    sounding_dict[SOUNDING_MATRIX_KEY] = sounding_matrix\n    return sounding_dict\n\n\ndef _fill_nans_in_soundings(\n        sounding_dict_pressure_coords, pressure_matrix_pascals,\n        min_num_pressure_levels_without_nan=15):\n    \"\"\"Interpolates to fill NaN's in each sounding.\n\n    :param sounding_dict_pressure_coords: See doc for\n        `_convert_interp_table_to_soundings`.\n    :param pressure_matrix_pascals: N-by-P numpy array of pressures.\n    :param min_num_pressure_levels_without_nan: Minimum number of pressure\n        levels without NaN.  For a given sounding S, if any field has fewer\n        pressure levels without NaN, S will be thrown out.\n    :return: sounding_dict_pressure_coords: Same as input, with the following\n        exceptions.\n    [1] maybe fewer soundings\n    [2] NaN's have been replaced\n    \"\"\"\n\n    # TODO(thunderhoser): Remove surface pressure of NaN.\n\n    field_names = sounding_dict_pressure_coords[FIELD_NAMES_KEY]\n    sounding_matrix = sounding_dict_pressure_coords[SOUNDING_MATRIX_KEY]\n    height_index = field_names.index(GEOPOTENTIAL_HEIGHT_NAME)\n\n    num_soundings = sounding_matrix.shape[0]\n    keep_sounding_flags = numpy.full(num_soundings, True, dtype=bool)\n\n    field_names_to_interp = [\n        GEOPOTENTIAL_HEIGHT_NAME, U_WIND_NAME, V_WIND_NAME, TEMPERATURE_NAME,\n        SPECIFIC_HUMIDITY_NAME\n    ]\n\n    for i in range(num_soundings):\n        for this_field_name in field_names_to_interp:\n            this_field_index = field_names.index(this_field_name)\n            these_real_flags = numpy.invert(numpy.isnan(\n                sounding_matrix[i, :, this_field_index]\n            ))\n\n            if numpy.all(these_real_flags):\n                continue\n\n            if (numpy.sum(these_real_flags) <\n                    min_num_pressure_levels_without_nan):\n                keep_sounding_flags[i] = False\n                break\n\n            these_nan_indices = numpy.where(numpy.invert(these_real_flags))[0]\n            these_real_indices = numpy.where(these_real_flags)[0]\n\n            if this_field_name == GEOPOTENTIAL_HEIGHT_NAME:\n                interp_object = scipy_interp1d(\n                    x=numpy.log(pressure_matrix_pascals[i, these_real_indices]),\n                    y=sounding_matrix[i, these_real_indices, this_field_index],\n                    kind='linear', bounds_error=False, fill_value='extrapolate',\n                    assume_sorted=False)\n\n                sounding_matrix[i, these_nan_indices, this_field_index] = (\n                    interp_object(\n                        numpy.log(pressure_matrix_pascals[i, these_nan_indices])\n                    )\n                )\n            else:\n                interp_object = scipy_interp1d(\n                    x=sounding_matrix[i, these_real_indices, height_index],\n                    y=sounding_matrix[i, these_real_indices, this_field_index],\n                    kind='linear', bounds_error=False, fill_value='extrapolate',\n                    assume_sorted=False)\n\n                sounding_matrix[i, these_nan_indices, this_field_index] = (\n                    interp_object(\n                        sounding_matrix[i, these_nan_indices, height_index]\n                    )\n                )\n\n    keep_sounding_indices = numpy.where(keep_sounding_flags)[0]\n    sounding_dict_pressure_coords[SOUNDING_MATRIX_KEY] = (\n        sounding_matrix[keep_sounding_indices, ...]\n    )\n    sounding_dict_pressure_coords[FULL_IDS_KEY] = [\n        sounding_dict_pressure_coords[FULL_IDS_KEY][i]\n        for i in keep_sounding_indices\n    ]\n\n    sounding_dict_pressure_coords[INITIAL_TIMES_KEY] = (\n        sounding_dict_pressure_coords[INITIAL_TIMES_KEY][keep_sounding_indices]\n    )\n    sounding_dict_pressure_coords[LEAD_TIMES_KEY] = (\n        sounding_dict_pressure_coords[LEAD_TIMES_KEY][keep_sounding_indices]\n    )\n\n    if sounding_dict_pressure_coords[SURFACE_PRESSURES_KEY] is not None:\n        sounding_dict_pressure_coords[SURFACE_PRESSURES_KEY] = (\n            sounding_dict_pressure_coords[SURFACE_PRESSURES_KEY][\n                keep_sounding_indices]\n        )\n\n    return sounding_dict_pressure_coords\n\n\ndef _convert_fields_and_units(sounding_dict_pressure_coords):\n    \"\"\"Converts fields and units in each sounding.\n\n    :param sounding_dict_pressure_coords: See doc for\n        `_convert_interp_table_to_soundings`.\n    :return: sounding_dict_pressure_coords: Same as input, but with different\n        fields and units.\n    \"\"\"\n\n    pressure_matrix_pascals = _get_pressures(sounding_dict_pressure_coords)\n    found_rh = (\n        nwp_model_utils.RH_COLUMN_FOR_SOUNDINGS in\n        sounding_dict_pressure_coords[FIELD_NAMES_KEY]\n    )\n\n    if found_rh:\n        sounding_dict_pressure_coords, dewpoint_matrix_kelvins = (\n            _relative_to_specific_humidity(\n                sounding_dict=sounding_dict_pressure_coords,\n                pressure_matrix_pascals=pressure_matrix_pascals)\n        )\n\n    sounding_dict_pressure_coords = _fill_nans_in_soundings(\n        sounding_dict_pressure_coords=sounding_dict_pressure_coords,\n        pressure_matrix_pascals=pressure_matrix_pascals)\n\n    pressure_matrix_pascals = _get_pressures(sounding_dict_pressure_coords)\n\n    if found_rh:\n        field_names = sounding_dict_pressure_coords[FIELD_NAMES_KEY]\n        sounding_matrix = sounding_dict_pressure_coords[SOUNDING_MATRIX_KEY]\n\n        specific_humidity_index = field_names.index(SPECIFIC_HUMIDITY_NAME)\n        temperature_index = field_names.index(TEMPERATURE_NAME)\n\n        dewpoint_matrix_kelvins = (\n            moisture_conversions.specific_humidity_to_dewpoint(\n                specific_humidities_kg_kg01=\n                sounding_matrix[..., specific_humidity_index],\n                temperatures_kelvins=sounding_matrix[..., temperature_index],\n                total_pressures_pascals=pressure_matrix_pascals\n            )\n        )\n    else:\n        sounding_dict_pressure_coords, dewpoint_matrix_kelvins = (\n            _specific_to_relative_humidity(\n                sounding_dict=sounding_dict_pressure_coords,\n                pressure_matrix_pascals=pressure_matrix_pascals\n            )\n        )\n\n    return _get_virtual_potential_temperatures(\n        sounding_dict=sounding_dict_pressure_coords,\n        pressure_matrix_pascals=pressure_matrix_pascals,\n        dewpoint_matrix_kelvins=dewpoint_matrix_kelvins\n    )\n\n\ndef _pressure_to_height_coords(\n        sounding_dict_pressure_coords, height_levels_m_agl):\n    \"\"\"Converts soundings from pressure coords to ground-relative height coords.\n\n    :param sounding_dict_pressure_coords: Dictionary created by\n        `_convert_fields_and_units`, but with additional keys listed below.\n    sounding_dict_pressure_coords['storm_elevations_m_asl']: length-N numpy\n        array of storm elevations (metres above sea level).\n\n    :param height_levels_m_agl: length-H numpy array of height levels (integer\n        metres above ground level).  This method will interpolate each sounding\n        to said heights, and the output soundings will be in ground-relative\n        height coords rather than pressure coords.\n    :return: sounding_dict_height_coords: Dictionary with the following keys.\n    sounding_dict_height_coords['full_storm_id_strings']: length-N list of full\n        IDs.\n    sounding_dict_height_coords['init_times_unix_sec']: length-N numpy array of\n        initial times (storm times).  Valid time = initial time + lead time.\n    sounding_dict_height_coords['lead_times_seconds']: length-N numpy array of\n        lead times.\n    sounding_dict_height_coords['storm_elevations_m_asl']: length-N numpy array\n        of storm elevations (metres above sea level).\n    sounding_dict_height_coords['sounding_matrix']: N-by-P-by-F numpy array of\n        sounding values.\n    sounding_dict_height_coords['height_levels_m_agl']: length-H numpy array of\n        height levels (metres above ground level).\n    sounding_dict_height_coords['field_names']: length-F list of field names.\n    \"\"\"\n\n    error_checking.assert_is_numpy_array(height_levels_m_agl, num_dimensions=1)\n    error_checking.assert_is_geq_numpy_array(height_levels_m_agl, 0)\n    height_levels_m_agl = numpy.round(height_levels_m_agl).astype(int)\n\n    sounding_dict_height_coords = {\n        FULL_IDS_KEY: sounding_dict_pressure_coords[FULL_IDS_KEY],\n        INITIAL_TIMES_KEY: sounding_dict_pressure_coords[INITIAL_TIMES_KEY],\n        LEAD_TIMES_KEY: sounding_dict_pressure_coords[LEAD_TIMES_KEY],\n        STORM_ELEVATIONS_KEY:\n            sounding_dict_pressure_coords[STORM_ELEVATIONS_KEY],\n        SOUNDING_MATRIX_KEY: sounding_dict_pressure_coords[SOUNDING_MATRIX_KEY],\n        HEIGHT_LEVELS_KEY: height_levels_m_agl,\n        FIELD_NAMES_KEY: sounding_dict_pressure_coords[FIELD_NAMES_KEY]\n    }\n\n    field_names = sounding_dict_pressure_coords[FIELD_NAMES_KEY]\n    orig_sounding_matrix = sounding_dict_pressure_coords[SOUNDING_MATRIX_KEY]\n    storm_elevations_m_asl = sounding_dict_pressure_coords[STORM_ELEVATIONS_KEY]\n\n    height_index = field_names.index(GEOPOTENTIAL_HEIGHT_NAME)\n    orig_height_matrix_m_asl = orig_sounding_matrix[..., height_index] + 0.\n\n    pressure_matrix_pascals = _get_pressures(sounding_dict_pressure_coords)\n    field_names[height_index] = PRESSURE_NAME\n    orig_sounding_matrix[..., height_index] = pressure_matrix_pascals + 0.\n\n    field_names_to_interp = [\n        PRESSURE_NAME, TEMPERATURE_NAME, U_WIND_NAME, V_WIND_NAME\n    ]\n\n    if RELATIVE_HUMIDITY_NAME in field_names:\n        field_names_to_interp.append(RELATIVE_HUMIDITY_NAME)\n    else:\n        field_names_to_interp.append(SPECIFIC_HUMIDITY_NAME)\n\n    num_soundings = orig_sounding_matrix.shape[0]\n    num_fields = orig_sounding_matrix.shape[-1]\n    num_height_levels = len(height_levels_m_agl)\n\n    new_sounding_matrix = numpy.full(\n        (num_soundings, num_height_levels, num_fields), numpy.nan\n    )\n\n    pressure_index = field_names.index(PRESSURE_NAME)\n\n    for j in range(len(field_names_to_interp)):\n        this_field_index = field_names.index(field_names_to_interp[j])\n\n        for i in range(num_soundings):\n            if field_names_to_interp[j] == PRESSURE_NAME:\n                this_interp_object = scipy_interp1d(\n                    x=orig_height_matrix_m_asl[i, ...],\n                    y=numpy.log(orig_sounding_matrix[i, ..., this_field_index]),\n                    kind='linear', bounds_error=False, fill_value='extrapolate',\n                    assume_sorted=False)\n\n                new_sounding_matrix[i, ..., this_field_index] = numpy.exp(\n                    this_interp_object(\n                        storm_elevations_m_asl[i] + height_levels_m_agl)\n                )\n            else:\n                this_interp_object = scipy_interp1d(\n                    x=orig_sounding_matrix[i, ..., pressure_index],\n                    y=orig_sounding_matrix[i, ..., this_field_index],\n                    kind='linear', bounds_error=False, fill_value='extrapolate',\n                    assume_sorted=False)\n\n                new_sounding_matrix[i, ..., this_field_index] = (\n                    this_interp_object(\n                        new_sounding_matrix[i, ..., pressure_index]\n                    )\n                )\n\n    sounding_dict_height_coords[FIELD_NAMES_KEY] = field_names\n    sounding_dict_height_coords[SOUNDING_MATRIX_KEY] = new_sounding_matrix\n\n    pressure_matrix_pascals = _get_pressures(sounding_dict_height_coords)\n\n    if RELATIVE_HUMIDITY_NAME in field_names:\n        sounding_dict_height_coords, dewpoint_matrix_kelvins = (\n            _relative_to_specific_humidity(\n                sounding_dict=sounding_dict_height_coords,\n                pressure_matrix_pascals=pressure_matrix_pascals)\n        )\n    else:\n        sounding_dict_height_coords, dewpoint_matrix_kelvins = (\n            _specific_to_relative_humidity(\n                sounding_dict=sounding_dict_height_coords,\n                pressure_matrix_pascals=pressure_matrix_pascals)\n        )\n\n    rh_index = field_names.index(RELATIVE_HUMIDITY_NAME)\n    sounding_matrix = sounding_dict_height_coords[SOUNDING_MATRIX_KEY]\n\n    sounding_matrix[..., rh_index] = numpy.maximum(\n        sounding_matrix[..., rh_index], 0.\n    )\n    sounding_matrix[..., rh_index] = numpy.minimum(\n        sounding_matrix[..., rh_index], 1.\n    )\n\n    sounding_dict_height_coords[SOUNDING_MATRIX_KEY] = sounding_matrix\n\n    return _get_virtual_potential_temperatures(\n        sounding_dict=sounding_dict_height_coords,\n        pressure_matrix_pascals=pressure_matrix_pascals,\n        dewpoint_matrix_kelvins=dewpoint_matrix_kelvins)\n\n\ndef check_field_name(field_name):\n    \"\"\"Error-checks name of sounding field.\n\n    :param field_name: Name of sounding field.\n    :raises: ValueError: if `field_name not in VALID_FIELD_NAMES`.\n    \"\"\"\n\n    error_checking.assert_is_string(field_name)\n\n    if field_name not in VALID_FIELD_NAMES:\n        error_string = (\n            '\\n{0:s}\\nValid field names (listed above) do not include \"{1:s}\".'\n        ).format(str(VALID_FIELD_NAMES), field_name)\n\n        raise ValueError(error_string)\n\n\ndef field_name_to_verbose(field_name, include_units=True):\n    \"\"\"Converts field name from underscore-separated format to verbose.\n\n    :param field_name: Field name in default (underscore-separated) format.\n    :param include_units: Boolean flag.  If True, verbose name will include\n        units.\n    :return: field_name_verbose: Verbose field name.\n    \"\"\"\n\n    error_checking.assert_is_boolean(include_units)\n\n    if include_units:\n        return FIELD_NAME_TO_VERBOSE_DICT[field_name]\n\n    return FIELD_NAME_TO_VERBOSE_UNITLESS_DICT[field_name]\n\n\ndef interp_soundings_to_storm_objects(\n        storm_object_table, top_grib_directory_name, model_name,\n        elevation_dir_name, use_all_grids=True, grid_id=None,\n        height_levels_m_agl=DEFAULT_HEIGHT_LEVELS_M_AGL,\n        lead_times_seconds=DEFAULT_LEAD_TIMES_SEC,\n        lag_time_for_convective_contamination_sec=\n        DEFAULT_LAG_TIME_FOR_CONVECTIVE_CONTAMINATION_SEC,\n        wgrib_exe_name=grib_io.WGRIB_EXE_NAME_DEFAULT,\n        wgrib2_exe_name=grib_io.WGRIB2_EXE_NAME_DEFAULT,\n        raise_error_if_missing=False):\n    \"\"\"Interpolates NWP sounding to each storm object at each lead time.\n\n    :param storm_object_table: pandas DataFrame with columns listed in\n        `storm_tracking_io.write_file`.\n    :param top_grib_directory_name: Name of top-level directory with grib files\n        for the given NWP model.\n    :param model_name: Model name (must be accepted by\n        `nwp_model_utils.check_grid_name`).\n    :param elevation_dir_name: Name of directory with elevation data (used by\n        the Python package \"srtm\").\n    :param use_all_grids: Boolean flag.  If True, this method will interp from\n        the highest-resolution grid available at each model-initialization time.\n        If False, will use only `grid_id`.\n    :param grid_id: [used only if `use_all_grids = False`]\n        Grid ID (must be accepted by `nwp_model_utils.check_grid_name`).\n    :param height_levels_m_agl: 1-D numpy array of height levels (metres above\n        ground level).  These will be the height levels in each sounding.\n    :param lead_times_seconds: length-T numpy array of lead times.\n    :param lag_time_for_convective_contamination_sec: Lag time (used to avoid\n        convective contamination of soundings, where the sounding for storm S is\n        heavily influenced by storm S).  This will be subtracted from each lead\n        time.\n    :param wgrib_exe_name: Path to wgrib executable.\n    :param wgrib2_exe_name: Path to wgrib2 executable.\n    :param raise_error_if_missing: Boolean flag.  If any grib file is missing\n        and `raise_error_if_missing = True`, this method will error out.  If any\n        grib file is missing and `raise_error_if_missing = False`, this method\n        will carry on, leaving the affected values as NaN.\n    :return: sounding_dict_by_lead_time: length-T list of dictionaries, each\n        containing the keys listed in `_pressure_to_height_coords`.\n    \"\"\"\n\n    error_checking.assert_is_integer_numpy_array(lead_times_seconds)\n    error_checking.assert_is_numpy_array(lead_times_seconds, num_dimensions=1)\n    error_checking.assert_is_geq_numpy_array(lead_times_seconds, 0)\n    error_checking.assert_is_integer(lag_time_for_convective_contamination_sec)\n    error_checking.assert_is_geq(lag_time_for_convective_contamination_sec, 0)\n\n    print((\n        'Creating target point for each storm object and lead time ({0:s} '\n        'seconds)...'\n    ).format(\n        str(lead_times_seconds)\n    ))\n\n    target_point_table = _create_target_points_for_interp(\n        storm_object_table=storm_object_table,\n        lead_times_seconds=lead_times_seconds)\n\n    print((\n        'Subtracting lag time ({0:d} seconds) from each target point, to '\n        'account for convective contamination...'\n    ).format(lag_time_for_convective_contamination_sec))\n\n    target_point_table[\n        FORECAST_TIME_COLUMN\n    ] -= lag_time_for_convective_contamination_sec\n\n    column_dict_old_to_new = {\n        tracking_utils.CENTROID_LATITUDE_COLUMN: interp.QUERY_LAT_COLUMN,\n        tracking_utils.CENTROID_LONGITUDE_COLUMN: interp.QUERY_LNG_COLUMN,\n        FORECAST_TIME_COLUMN: interp.QUERY_TIME_COLUMN\n    }\n\n    target_point_table.rename(columns=column_dict_old_to_new, inplace=True)\n    \n    print(SEPARATOR_STRING)\n    interp_table = _interp_soundings_from_nwp(\n        target_point_table=target_point_table,\n        top_grib_directory_name=top_grib_directory_name, include_surface=False,\n        model_name=model_name, use_all_grids=use_all_grids, grid_id=grid_id,\n        wgrib_exe_name=wgrib_exe_name, wgrib2_exe_name=wgrib2_exe_name,\n        raise_error_if_missing=raise_error_if_missing)\n    print(SEPARATOR_STRING)\n    \n    print(SEPARATOR_STRING)\n    print('this is the interp_table')\n    print(interp_table)\n    print(SEPARATOR_STRING)\n\n    print('Converting interpolated values to soundings...')\n    sounding_dict_pressure_coords = _convert_interp_table_to_soundings(\n        interp_table=interp_table, target_point_table=target_point_table,\n        model_name=model_name, include_surface=False)\n\n    print('Converting fields and units in each sounding...')\n    orig_num_soundings = len(sounding_dict_pressure_coords[FULL_IDS_KEY])\n    sounding_dict_pressure_coords = _convert_fields_and_units(\n        sounding_dict_pressure_coords)\n    num_soundings = len(sounding_dict_pressure_coords[FULL_IDS_KEY])\n\n    print('Removed {0:d} of {1:d} soundings (too many NaN''s).'.format(\n        orig_num_soundings - num_soundings, orig_num_soundings))\n\n    print('Finding elevation of each storm object...')\n    storm_elevations_m_asl = geodetic_utils.get_elevations(\n        latitudes_deg=storm_object_table[\n            tracking_utils.CENTROID_LATITUDE_COLUMN].values,\n        longitudes_deg=storm_object_table[\n            tracking_utils.CENTROID_LONGITUDE_COLUMN].values,\n        working_dir_name=elevation_dir_name\n    )\n\n    these_indices = tracking_utils.find_storm_objects(\n        all_id_strings=storm_object_table[\n            tracking_utils.FULL_ID_COLUMN].values.tolist(),\n        all_times_unix_sec=storm_object_table[\n            tracking_utils.VALID_TIME_COLUMN].values,\n        id_strings_to_keep=sounding_dict_pressure_coords[FULL_IDS_KEY],\n        times_to_keep_unix_sec=sounding_dict_pressure_coords[INITIAL_TIMES_KEY]\n    )\n\n    storm_elevations_m_asl = storm_elevations_m_asl[these_indices]\n    sounding_dict_pressure_coords.update({\n        STORM_ELEVATIONS_KEY: storm_elevations_m_asl\n    })\n\n    print('Converting soundings from pressure coords to metres AGL...\\n')\n    sounding_dict_height_coords = _pressure_to_height_coords(\n        sounding_dict_pressure_coords=sounding_dict_pressure_coords,\n        height_levels_m_agl=height_levels_m_agl)\n\n    num_lead_times = len(lead_times_seconds)\n    sounding_dict_by_lead_time = [None] * num_lead_times\n\n    for k in range(num_lead_times):\n        print((\n            'Creating separate sounding dictionary for {0:d}-second lead '\n            'time...'\n        ).format(lead_times_seconds[k]))\n\n        these_indices = numpy.where(\n            sounding_dict_height_coords[LEAD_TIMES_KEY] ==\n            lead_times_seconds[k]\n        )[0]\n\n        sounding_dict_by_lead_time[k] = {\n            FULL_IDS_KEY: [\n                sounding_dict_height_coords[FULL_IDS_KEY][i]\n                for i in these_indices\n            ],\n            INITIAL_TIMES_KEY:\n                sounding_dict_height_coords[INITIAL_TIMES_KEY][these_indices],\n            LEAD_TIMES_KEY:\n                sounding_dict_height_coords[LEAD_TIMES_KEY][these_indices],\n            STORM_ELEVATIONS_KEY:\n                sounding_dict_height_coords[STORM_ELEVATIONS_KEY][\n                    these_indices],\n            SOUNDING_MATRIX_KEY:\n                sounding_dict_height_coords[SOUNDING_MATRIX_KEY][\n                    these_indices, ...],\n            HEIGHT_LEVELS_KEY: sounding_dict_height_coords[HEIGHT_LEVELS_KEY],\n            FIELD_NAMES_KEY: sounding_dict_height_coords[FIELD_NAMES_KEY]\n        }\n\n        print((\n            'Dictionary for {0:d}-second lead time contains {1:d} of {2:d} '\n            'soundings.'\n        ).format(lead_times_seconds[k], len(these_indices), num_soundings))\n\n    return sounding_dict_by_lead_time\n\n\ndef write_soundings(\n        netcdf_file_name, sounding_dict_height_coords, lead_time_seconds,\n        lag_time_for_convective_contamination_sec):\n    \"\"\"Writes soundings to NetCDF file.\n\n    This file may contain soundings with one lead time only.\n\n    :param netcdf_file_name: Path to output file.\n    :param sounding_dict_height_coords: Dictionary created by\n        `interp_soundings_to_storm_objects`.\n    :param lead_time_seconds: Lead time for all soundings.\n    :param lag_time_for_convective_contamination_sec: Lag time for all soundings\n        (see doc for `interp_soundings_to_storm_objects`).\n    :raises: ValueError: if `sounding_dict_height_coords` contains more than one\n        unique lead time.\n    :raises: ValueError: if lead time in `sounding_dict_height_coords` does not\n        match the input arg `lead_time_seconds`.\n    \"\"\"\n\n    error_checking.assert_is_integer(lead_time_seconds)\n    error_checking.assert_is_geq(lead_time_seconds, 0)\n    error_checking.assert_is_integer(lag_time_for_convective_contamination_sec)\n    error_checking.assert_is_geq(lag_time_for_convective_contamination_sec, 0)\n\n    unique_lead_times_seconds = numpy.unique(\n        sounding_dict_height_coords[LEAD_TIMES_KEY]\n    )\n\n    if not numpy.all(unique_lead_times_seconds == lead_time_seconds):\n        error_string = (\n            'All lead times in sounding dictionary should be {0:d} seconds.  '\n            'Instead, got lead times listed below.\\n{1:s}'\n        ).format(lead_time_seconds, str(unique_lead_times_seconds))\n\n        raise ValueError(error_string)\n\n    # Create file and set global attributes.\n    file_system_utils.mkdir_recursive_if_necessary(file_name=netcdf_file_name)\n    netcdf_dataset = netCDF4.Dataset(\n        netcdf_file_name, 'w', format='NETCDF3_64BIT_OFFSET')\n\n    netcdf_dataset.setncattr(LEAD_TIME_KEY, lead_time_seconds)\n    netcdf_dataset.setncattr(\n        LAG_TIME_KEY, lag_time_for_convective_contamination_sec)\n\n    num_storm_objects = len(sounding_dict_height_coords[FULL_IDS_KEY])\n    num_height_levels = len(sounding_dict_height_coords[HEIGHT_LEVELS_KEY])\n    num_fields = len(sounding_dict_height_coords[FIELD_NAMES_KEY])\n\n    netcdf_dataset.createDimension(\n        STORM_OBJECT_DIMENSION_KEY, num_storm_objects)\n    netcdf_dataset.createDimension(HEIGHT_DIMENSION_KEY, num_height_levels)\n    netcdf_dataset.createDimension(FIELD_DIMENSION_KEY, num_fields)\n\n    id_lengths = [len(f) for f in sounding_dict_height_coords[FULL_IDS_KEY]]\n    num_id_characters = max(id_lengths + [1])\n    netcdf_dataset.createDimension(\n        STORM_ID_CHAR_DIMENSION_KEY, num_id_characters)\n\n    num_field_name_chars = max([\n        len(f) for f in sounding_dict_height_coords[FIELD_NAMES_KEY]\n    ])\n    netcdf_dataset.createDimension(\n        FIELD_NAME_CHAR_DIMENSION_KEY, num_field_name_chars)\n\n    # Add storm IDs to file.\n    netcdf_dataset.createVariable(\n        FULL_IDS_KEY, datatype='S1',\n        dimensions=(STORM_OBJECT_DIMENSION_KEY, STORM_ID_CHAR_DIMENSION_KEY)\n    )\n\n    string_type = 'S{0:d}'.format(num_id_characters)\n    full_ids_char_array = netCDF4.stringtochar(numpy.array(\n        sounding_dict_height_coords[FULL_IDS_KEY], dtype=string_type\n    ))\n    netcdf_dataset.variables[FULL_IDS_KEY][:] = numpy.array(full_ids_char_array)\n\n    # Add initial times (storm times) to file.\n    netcdf_dataset.createVariable(\n        INITIAL_TIMES_KEY, datatype=numpy.int32,\n        dimensions=STORM_OBJECT_DIMENSION_KEY)\n    netcdf_dataset.variables[INITIAL_TIMES_KEY][:] = (\n        sounding_dict_height_coords[INITIAL_TIMES_KEY]\n    )\n\n    # Add storm elevations to file.\n    netcdf_dataset.createVariable(\n        STORM_ELEVATIONS_KEY, datatype=numpy.float32,\n        dimensions=STORM_OBJECT_DIMENSION_KEY)\n    netcdf_dataset.variables[STORM_ELEVATIONS_KEY][:] = (\n        sounding_dict_height_coords[STORM_ELEVATIONS_KEY]\n    )\n\n    # Add height levels to file.\n    netcdf_dataset.createVariable(\n        HEIGHT_LEVELS_KEY, datatype=numpy.int32,\n        dimensions=HEIGHT_DIMENSION_KEY)\n    netcdf_dataset.variables[HEIGHT_LEVELS_KEY][:] = (\n        sounding_dict_height_coords[HEIGHT_LEVELS_KEY]\n    )\n\n    # Add field names to file.\n    netcdf_dataset.createVariable(\n        FIELD_NAMES_KEY, datatype='S1',\n        dimensions=(FIELD_DIMENSION_KEY, FIELD_NAME_CHAR_DIMENSION_KEY)\n    )\n\n    string_type = 'S{0:d}'.format(num_field_name_chars)\n    field_names_as_char_array = netCDF4.stringtochar(numpy.array(\n        sounding_dict_height_coords[FIELD_NAMES_KEY], dtype=string_type\n    ))\n    netcdf_dataset.variables[FIELD_NAMES_KEY][:] = numpy.array(\n        field_names_as_char_array)\n\n    # Add soundings to file.\n    netcdf_dataset.createVariable(\n        SOUNDING_MATRIX_KEY, datatype=numpy.float32,\n        dimensions=(STORM_OBJECT_DIMENSION_KEY, HEIGHT_DIMENSION_KEY,\n                    FIELD_DIMENSION_KEY)\n    )\n\n    netcdf_dataset.variables[SOUNDING_MATRIX_KEY][:] = (\n        sounding_dict_height_coords[SOUNDING_MATRIX_KEY]\n    )\n    netcdf_dataset.close()\n\n\ndef read_soundings(\n        netcdf_file_name, field_names_to_keep=None,\n        full_id_strings_to_keep=None, init_times_to_keep_unix_sec=None):\n    \"\"\"Reads soundings from NetCDF file.\n\n    K = number of storm objects to keep\n\n    If `full_id_strings_to_keep is None or init_times_to_keep_unix_sec is None`,\n    this method will return soundings for all storm objects.  Otherwise, will\n    return only a subset of storm objects.\n\n    If `field_names_to_keep is None`, this method will return all sounding\n    fields.  Otherwise, will return only a subset of fields.\n\n    :param netcdf_file_name: Path to input file.\n    :param field_names_to_keep: 1-D list with names of sounding fields.\n    :param full_id_strings_to_keep: length-K list of full IDs.\n    :param init_times_to_keep_unix_sec: length-K numpy array of initial times\n        (storm times).\n    :return: sounding_dict_height_coords: Dictionary with keys listed in\n        `_pressure_to_height_coords`.\n    :return: lag_time_for_convective_contamination_sec: See doc for\n        `interp_soundings_to_storm_objects`.\n    \"\"\"\n\n    netcdf_dataset = netcdf_io.open_netcdf(\n        netcdf_file_name=netcdf_file_name, raise_error_if_fails=True)\n\n    lead_time_seconds = getattr(netcdf_dataset, LEAD_TIME_KEY)\n    lag_time_for_convective_contamination_sec = int(getattr(\n        netcdf_dataset, LAG_TIME_KEY\n    ))\n\n    height_levels_m_agl = numpy.array(\n        netcdf_dataset.variables[HEIGHT_LEVELS_KEY][:], dtype=int\n    )\n    field_names = netCDF4.chartostring(\n        netcdf_dataset.variables[FIELD_NAMES_KEY][:]\n    )\n    field_names = [str(f) for f in field_names]\n\n    if field_names_to_keep is None:\n        field_indices_to_keep = numpy.linspace(\n            0, len(field_names) - 1, num=len(field_names), dtype=int\n        )\n    else:\n        error_checking.assert_is_numpy_array(\n            numpy.array(field_names_to_keep), num_dimensions=1\n        )\n        for this_field_name in field_names_to_keep:\n            check_field_name(this_field_name)\n\n        field_indices_to_keep = numpy.array(\n            [field_names.index(f) for f in field_names_to_keep], dtype=int\n        )\n        field_names = field_names_to_keep + []\n\n    num_storm_objects = netcdf_dataset.variables[FULL_IDS_KEY].shape[0]\n    num_height_levels = len(height_levels_m_agl)\n    num_fields = len(field_names)\n\n    if num_storm_objects == 0:\n        full_id_strings = []\n        init_times_unix_sec = numpy.array([], dtype=int)\n        storm_elevations_m_asl = numpy.array([], dtype=float)\n        sounding_matrix = numpy.full(\n            (num_storm_objects, num_height_levels, num_fields), numpy.nan\n        )\n    else:\n        full_id_strings = netCDF4.chartostring(\n            netcdf_dataset.variables[FULL_IDS_KEY][:]\n        )\n        full_id_strings = [str(this_id) for this_id in full_id_strings]\n\n        init_times_unix_sec = numpy.array(\n            netcdf_dataset.variables[INITIAL_TIMES_KEY][:], dtype=int\n        )\n        storm_elevations_m_asl = numpy.array(\n            netcdf_dataset.variables[STORM_ELEVATIONS_KEY][:]\n        )\n        sounding_matrix = numpy.array(\n            netcdf_dataset.variables[SOUNDING_MATRIX_KEY][\n                ..., field_indices_to_keep]\n        )\n\n    netcdf_dataset.close()\n\n    filter_storm_objects = (\n        full_id_strings_to_keep is not None and\n        init_times_to_keep_unix_sec is not None and\n        num_storm_objects != 0\n    )\n\n    if filter_storm_objects:\n        these_indices = tracking_utils.find_storm_objects(\n            all_id_strings=full_id_strings,\n            all_times_unix_sec=init_times_unix_sec,\n            id_strings_to_keep=full_id_strings_to_keep,\n            times_to_keep_unix_sec=init_times_to_keep_unix_sec,\n            allow_missing=True)\n\n        these_indices = these_indices[these_indices != -1]\n\n        full_id_strings = [full_id_strings[i] for i in these_indices]\n        init_times_unix_sec = init_times_unix_sec[these_indices]\n        storm_elevations_m_asl = storm_elevations_m_asl[these_indices]\n        sounding_matrix = sounding_matrix[these_indices, ...]\n\n    num_storm_objects = len(full_id_strings)\n    lead_times_seconds = numpy.full(\n        num_storm_objects, lead_time_seconds, dtype=int)\n\n    sounding_dict_height_coords = {\n        FULL_IDS_KEY: full_id_strings,\n        INITIAL_TIMES_KEY: init_times_unix_sec,\n        LEAD_TIMES_KEY: lead_times_seconds,\n        STORM_ELEVATIONS_KEY: storm_elevations_m_asl,\n        SOUNDING_MATRIX_KEY: sounding_matrix,\n        HEIGHT_LEVELS_KEY: height_levels_m_agl,\n        FIELD_NAMES_KEY: field_names\n    }\n\n    return (sounding_dict_height_coords,\n            lag_time_for_convective_contamination_sec)\n\n\ndef find_sounding_file(\n        top_directory_name, spc_date_string, lead_time_seconds,\n        lag_time_for_convective_contamination_sec, init_time_unix_sec=None,\n        raise_error_if_missing=True):\n    \"\"\"Finds NetCDF file created by `write_soundings`.\n\n    If `init_time_unix_sec is None`, this method will seek a file with all\n    soundings for one SPC date.  Otherwise, will seek a file with soundings for\n    one time step.\n\n    :param top_directory_name: Name of top-level directory with sounding files.\n    :param spc_date_string: SPC date (format \"yyyymmdd\").\n    :param lead_time_seconds: Lead time.\n    :param lag_time_for_convective_contamination_sec: See doc for\n        `interp_soundings_to_storm_objects`.\n    :param init_time_unix_sec: Initial time (storm time).\n    :param raise_error_if_missing: Boolean flag.  If file is missing and\n        `raise_error_if_missing = True`, this method will error out.\n    :return: sounding_file_name: Path to sounding file.  If file is missing and\n        `raise_error_if_missing = False`, this is the *expected* path.\n    :raises: ValueError: if file is missing and `raise_error_if_missing = True`.\n    \"\"\"\n\n    error_checking.assert_is_string(top_directory_name)\n    time_conversion.spc_date_string_to_unix_sec(spc_date_string)\n    error_checking.assert_is_boolean(raise_error_if_missing)\n\n    if init_time_unix_sec is None:\n        sounding_file_name = (\n            '{0:s}/{1:s}/storm_soundings_{2:s}_lead-time-{3:05d}sec'\n            '_lag-time-{4:04d}sec.nc'\n        ).format(\n            top_directory_name, spc_date_string[:4], spc_date_string,\n            lead_time_seconds, lag_time_for_convective_contamination_sec\n        )\n    else:\n        sounding_file_name = (\n            '{0:s}/{1:s}/{2:s}/storm_soundings_{3:s}_lead-time-{4:05d}sec'\n            '_lag-time-{5:04d}sec.nc'\n        ).format(\n            top_directory_name, spc_date_string[:4], spc_date_string,\n            time_conversion.unix_sec_to_string(\n                init_time_unix_sec, TIME_FORMAT_IN_FILE_NAMES),\n            lead_time_seconds, lag_time_for_convective_contamination_sec\n        )\n\n    if raise_error_if_missing and not os.path.isfile(sounding_file_name):\n        error_string = (\n            'Cannot find file with soundings interpolated to storm objects.  '\n            'Expected at: {0:s}'\n        ).format(sounding_file_name)\n\n        raise ValueError(error_string)\n\n    return sounding_file_name\n", "meta": {"hexsha": "4acdc093040a3684f7a9c2cde8eabc08f7092d53", "size": 61665, "ext": "py", "lang": "Python", "max_stars_repo_path": "gewittergefahr/gg_utils/soundings.py", "max_stars_repo_name": "dopplerchase/GewitterGefahr", "max_stars_repo_head_hexsha": "4415b08dd64f37eba5b1b9e8cc5aa9af24f96593", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gewittergefahr/gg_utils/soundings.py", "max_issues_repo_name": "dopplerchase/GewitterGefahr", "max_issues_repo_head_hexsha": "4415b08dd64f37eba5b1b9e8cc5aa9af24f96593", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-23T21:14:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T21:14:00.000Z", "max_forks_repo_path": "gewittergefahr/gg_utils/soundings.py", "max_forks_repo_name": "dopplerchase/GewitterGefahr", "max_forks_repo_head_hexsha": "4415b08dd64f37eba5b1b9e8cc5aa9af24f96593", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5957867018, "max_line_length": 80, "alphanum_fraction": 0.7200356766, "include": true, "reason": "import numpy,from scipy", "num_tokens": 13748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19277782022841536}}
{"text": "import os\nfrom pprint import pprint\nfrom pyomo.environ import *\nimport switch_model.utilities as utilities\nfrom util import get\n\ndef define_arguments(argparser):\n    argparser.add_argument('--biofuel-limit', type=float, default=1.0,\n        help=\"Maximum fraction of power that can be obtained from biofuel in any period (default=1.0)\")\n    argparser.add_argument('--biofuel-switch-threshold', type=float, default=1.0,\n        help=\"RPS level at which all thermal plants switch to biofuels (0.0-1.0, default=1.0); use with --rps-allocation fuel_switch_at_high_rps\")\n    argparser.add_argument('--rps-activate', default='activate',\n        dest='rps_level', action='store_const', const='activate',\n        help=\"Activate RPS (on by default).\")\n    argparser.add_argument('--rps-deactivate',\n        dest='rps_level', action='store_const', const='deactivate',\n        help=\"Deactivate RPS.\")\n    argparser.add_argument('--rps-no-new-renewables',\n        dest='rps_level', action='store_const', const='no_new_renewables',\n        help=\"Deactivate RPS and don't allow any new renewables except to replace existing capacity.\")\n    argparser.add_argument('--rps-no-new-wind', action='store_true', default=False,\n        help=\"Don't allow any new wind capacity except to replace existing capacity.\")\n    argparser.add_argument('--rps-no-wind', action='store_true', default=False,\n        help=\"Don't allow any new wind capacity or replacement of existing capacity.\")\n    argparser.add_argument('--rps-prefer-dist-pv', action='store_true', default=False,\n        help=\"Don't allow any new large solar capacity unless 90% of distributed PV ('*DistPV') capacity has been developed.\")\n    argparser.add_argument(\n        '--rps-allocation', default=None,\n        choices=[\n            'quadratic',\n            'fuel_switch_by_period', 'fuel_switch_by_timeseries',\n            'full_load_heat_rate',\n            'split_commit',\n            'relaxed_split_commit',\n            'fuel_switch_at_high_rps',\n        ],\n        help=\"Method to use to allocate power output among fuels. Default is fuel_switch_by_period for models \"\n            + \"with unit commitment, full_load_heat_rate for models without.\"\n    )\n    argparser.add_argument('--rps-targets', nargs='*', default=None,\n        help=\"Targets to use for RPS, specified as --rps-targets year1 level1 year2 level2 ..., \"\n        \"where years are transition years and levels are fractions between 0 and 1. \"\n        \"If not specified, values from rps_targets.tab will be used.\"\n    )\n\n# TODO: make this work with progressive hedging as follows:\n# add a variable indexed over all weather scenarios and all cost scenarios,\n# which shows how much of the RPS will be allocated to each scenario.\n# Problem: we multiply the RPS target by total generation, so this will become quadratic?\n# May instead need to treat the RPS more like a limit on non-renewable production (as a fraction of loads)?\n# Designate the allocations as a first-stage variable.\n# Require each subproblem to work within its part of the allocation. Also require in each subproblem\n# that the allocations across all weather scenarios (within each cost scenario) average out to match the\n# actual target (when applying the scenario weights).\n# Then PHA will force all the scenarios to agree on how the target is allocated among them.\n# Could do the same with hydrogen storage: require average hydrogen stored across all scenarios\n# to be less than the size of the storage built.\n\ndef define_components(m):\n    \"\"\"\n\n    \"\"\"\n    ###################\n    # RPS calculation\n    ##################\n\n    m.f_rps_eligible = Param(m.FUELS, within=Binary)\n\n    m.RPS_ENERGY_SOURCES = Set(initialize=lambda m:\n        [s for s in m.NON_FUEL_ENERGY_SOURCES if s != 'Battery'] + [f for f in m.FUELS if m.f_rps_eligible[f]]\n    )\n\n    m.RPS_YEARS = Set(ordered=True)\n    m.rps_target = Param(m.RPS_YEARS)\n\n    def rps_target_for_period_rule(m, p):\n        \"\"\"find the last target that is in effect before the _end_ of the period\"\"\"\n        latest_target = max(y for y in m.RPS_YEARS if y < m.period_start[p] + m.period_length_years[p])\n        return m.rps_target[latest_target]\n    m.rps_target_for_period = Param(m.PERIODS, initialize=rps_target_for_period_rule)\n\n    # maximum share of (bio)fuels in rps\n    # note: using Infinity as the upper limit causes the solution to take forever\n    # m.rps_fuel_limit = Param(default=float(\"inf\"), mutable=True)\n    m.rps_fuel_limit = Param(initialize=m.options.biofuel_limit, mutable=True)\n\n    # calculate amount of pre-existing capacity in each generation project;\n    # used when we want to restrict expansion\n    m.gen_pre_existing_capacity = Expression(\n        m.GENERATION_PROJECTS,\n        rule=lambda m, g: (\n            m.GenCapacity[g, m.PERIODS.first()]\n            - get(m.BuildGen, (g, m.PERIODS.first()), 0)\n        )\n    )\n\n    # Define DispatchGenRenewableMW, which shows the amount of power produced\n    # by each project from each fuel during each time step.\n    define_DispatchGenRenewableMW(m)\n\n    # calculate amount of power produced from renewable fuels during each period\n    m.RPSFuelPower = Expression(m.PERIODS, rule=lambda m, per:\n        sum(\n            m.DispatchGenRenewableMW[g, tp] * m.tp_weight[tp]\n            for g in m.FUEL_BASED_GENS\n            for tp in m.TPS_FOR_GEN_IN_PERIOD[g, per]\n        )\n    )\n\n    # Note: this rule ignores pumped hydro and batteries, so it could be gamed by producing extra\n    # RPS-eligible power and burning it off in storage losses; on the other hand,\n    # it also neglects the (small) contribution from net flow of pumped hydro projects.\n    # TODO: incorporate pumped hydro into this rule, maybe change the target to refer to\n    # sum(getattr(m, component)[z, t] for z in m.LOAD_ZONES) for component in m.Zone_Power_Injections)\n\n    # power production that can be counted toward the RPS each period\n    m.RPSEligiblePower = Expression(m.PERIODS, rule=lambda m, per:\n        m.RPSFuelPower[per]\n        +\n        sum(\n            m.DispatchGen[g, tp] * m.tp_weight[tp]\n            for f in m.NON_FUEL_ENERGY_SOURCES if f in m.RPS_ENERGY_SOURCES\n            for g in m.GENS_BY_NON_FUEL_ENERGY_SOURCE[f]\n            for tp in m.TPS_FOR_GEN_IN_PERIOD[g, per]\n        )\n    )\n\n    # total power production each period (against which RPS is measured)\n    # note: we exclude production from storage\n    m.RPSTotalPower = Expression(m.PERIODS, rule=lambda m, per:\n        sum(\n            m.DispatchGen[g, tp] * m.tp_weight[tp]\n            for g in m.GENERATION_PROJECTS if g not in getattr(m, 'STORAGE_GENS', [])\n            for tp in m.TPS_FOR_GEN_IN_PERIOD[g, per]\n        )\n    )\n\n    if m.options.rps_level == 'activate':\n        # we completely skip creating the constraint if the RPS is not activated.\n        # this makes it easy for other modules to check whether there's an RPS in effect\n        # (if we deactivated the RPS after it is constructed, then other modules would\n        # have to postpone checking until then)\n        m.RPS_Enforce = Constraint(m.PERIODS, rule=lambda m, per:\n            m.RPSEligiblePower[per] >= m.rps_target_for_period[per] * m.RPSTotalPower[per]\n        )\n    elif m.options.rps_level == 'no_new_renewables':\n        # prevent construction of any new exclusively-renewable projects, but allow\n        # replacement of existing ones\n        # (doesn't ban use of biofuels in existing or multi-fuel projects, but that could\n        # be done with --biofuel-limit 0)\n        m.No_New_Renewables = Constraint(m.NEW_GEN_BLD_YRS, rule=lambda m, g, bld_yr:\n            (m.GenCapacity[g, bld_yr] <= m.gen_pre_existing_capacity[g])\n            if m.gen_energy_source[g] in m.RPS_ENERGY_SOURCES\n            else Constraint.Skip\n        )\n\n    wind_energy_sources = {'WND'}\n    if m.options.rps_no_new_wind:\n        # limit wind to existing capacity\n        m.No_New_Wind = Constraint(m.NEW_GEN_BLD_YRS, rule=lambda m, g, bld_yr:\n            (m.GenCapacity[g, bld_yr] <= m.gen_pre_existing_capacity[g])\n            if m.gen_energy_source[g] in wind_energy_sources\n            else Constraint.Skip\n        )\n    if m.options.rps_no_wind:\n        # don't build any new capacity or replace existing\n        m.No_Wind = Constraint(m.NEW_GEN_BLD_YRS, rule=lambda m, g, bld_yr:\n            (m.BuildGen[g, bld_yr] == 0.0)\n            if m.gen_energy_source[g] in wind_energy_sources\n            else Constraint.Skip\n        )\n\n    if m.options.rps_prefer_dist_pv:\n        m.DIST_PV_GENS = Set(initialize=lambda m: [\n            g for g in m.GENS_BY_NON_FUEL_ENERGY_SOURCE['SUN']\n            if 'DistPV' in m.gen_tech[g]\n        ])\n        m.LARGE_PV_GENS = Set(initialize=lambda m: [\n            g for g in m.GENS_BY_NON_FUEL_ENERGY_SOURCE['SUN']\n            if g not in m.DIST_PV_GENS\n        ])\n        # LargePVAllowed must be 1 to allow large PV to be built\n        m.LargePVAllowed = Var(m.PERIODS, within=Binary) #\n        # LargePVAllowed can only be 1 if 90% of the available rooftop PV has been built\n        m.Set_LargePVAllowed = Constraint(\n            m.PERIODS,\n            rule=lambda m, p:\n                sum(m.GenCapacity[g, p] for g in m.DIST_PV_GENS)\n                >=\n                m.LargePVAllowed[p]\n                * 0.9\n                * sum(m.gen_capacity_limit_mw[g] for g in m.DIST_PV_GENS)\n        )\n        m.Apply_LargePVAllowed = Constraint(\n            m.LARGE_PV_GENS, m.PERIODS,\n            rule=lambda m, g, p:\n                m.GenCapacity[g, p]\n                <=\n                m.LargePVAllowed[p] * m.gen_capacity_limit_mw[g]\n                + m.gen_pre_existing_capacity[g]\n        )\n\n    # Don't allow (bio)fuels to provide more than a certain percentage of the system's energy\n    # Note: when the system really wants to use more biofuel, it is possible to \"game\" this limit by\n    # cycling power through batteries, pumped storage, transmission lines or the hydrogen system to\n    # burn off some\n    # extra non-fuel energy, allowing more biofuel into the system. (This doesn't typically happen\n    # with batteries due to high variable costs -- e.g., it has to cycle 4 kWh through a battery to\n    # consume 1 kWh of non-biofuel power, to allow 0.05 kWh of additional biofuel into the system.\n    # Even if this can save $0.5/kWh, if battery cycling costs $0.15/kWh, that means $0.60 extra to\n    # save $0.025. It also doesn't happen in the hydrogen scenario, since storing intermittent power\n    # directly as hydrogen can directly displace biofuel consumption. But it could happen if batteries\n    # have low efficiency or low cycling cost, or if transmission losses are significant.)\n    # One solution would be to only apply the RPS to the predefined load (not generation), but then\n    # transmission and battery losses could be served by fossil fuels.\n    # Alternatively: limit fossil fuels to (1-rps) * standard loads\n    # and limit biofuels to (1-bio)*standard loads. This would force renewables to be used for\n    # all losses, which is slightly inaccurate.\n    # TODO: fix the problem noted above; for now we don't worry too much because there are no\n    # transmission losses, the cycling costs for batteries are too high and pumped storage is only\n    # adopted on a small scale.\n\n    m.RPS_Fuel_Cap = Constraint(m.PERIODS, rule = lambda m, per:\n        m.RPSFuelPower[per] <= m.rps_fuel_limit * m.RPSTotalPower[per]\n    )\n\ndef define_DispatchGenRenewableMW(m):\n    # Define DispatchGenRenewableMW, which shows the amount of power produced\n    # by each project from each fuel during each time step.\n    # This must be linear, because it may be used in RPS calculations.\n    # This can get complex when a project uses multiple fuels and incremental\n    # heat rate curves.\n    if m.options.rps_allocation is None:\n        if hasattr(m, 'FUEL_USE_SEGMENTS_FOR_GEN'):\n            # using heat rate curves and possibly startup fuel;\n            # have to do more advanced allocation of power to fuels\n            m.options.rps_allocation = 'fuel_switch_by_period'\n        else:\n            # only using full load heat rate; use simpler allocation strategy\n            m.options.rps_allocation = 'full_load_heat_rate'\n        if m.options.verbose:\n            print \"Using {} method to allocate DispatchGenRenewableMW\".format(m.options.rps_allocation)\n\n    if m.options.rps_allocation == 'full_load_heat_rate':\n        simple_DispatchGenRenewableMW(m)\n    elif m.options.rps_allocation == 'quadratic':\n        quadratic_DispatchGenRenewableMW(m)\n    elif m.options.rps_allocation == 'fuel_switch_by_period':\n        binary_by_period_DispatchGenRenewableMW(m)\n    elif m.options.rps_allocation == 'fuel_switch_by_timeseries':\n        binary_by_timeseries_DispatchGenRenewableMW(m)\n    elif m.options.rps_allocation == 'split_commit':\n        split_commit_DispatchGenRenewableMW(m)\n    elif m.options.rps_allocation == 'relaxed_split_commit':\n        relaxed_split_commit_DispatchGenRenewableMW(m)\n    elif m.options.rps_allocation == 'fuel_switch_at_high_rps':\n        fuel_switch_at_high_rps_DispatchGenRenewableMW(m)\n\ndef simple_DispatchGenRenewableMW(m):\n    # Allocate the power produced during each timepoint among the fuels.\n    # When not using heat rate curves, this can be calculated directly from\n    # fuel usage and the full load heat rate. This also allows use of\n    # multiple fuels in the same project at the same time.\n    m.DispatchGenRenewableMW = Expression(\n        m.FUEL_BASED_GEN_TPS,\n        rule=lambda m, g, t:\n            sum(\n                m.GenFuelUseRate[g, t, f]\n                    for f in m.FUELS_FOR_GEN[g]\n                        if m.f_rps_eligible[f]\n            )\n            / m.gen_full_load_heat_rate[g]\n    )\n\n\ndef split_commit_DispatchGenRenewableMW(m):\n    # This approach requires the utility to designate part of their capacity for\n    # renewable production and part for non-renewable, and show how they commit\n    # and dispatch each part. The current version allows fractional commitment to\n    # each mode, but we could use integer commitment variables to force full units\n    # into each mode (more physically meaningful, but unnecessarily restrictive and\n    # harder to calculate; the current version may serve as a reasonable accounting\n    # method for multi-fuel projects in a partial-RPS environment).\n\n    # TODO: limit this to projects that can use both renewable and non-renewable fuel\n    # TODO: force CommitGenRenewable == CommitGen when there's 100% RPS\n    # TODO: force DispatchGenRenewableMW == DispatchGen when there's 100% RPS\n    # TODO: force CommitGenRenewable == 0 when there's 0% RPS\n    # (these may not be needed: single-category projects will get dispatch forced to zero\n    # in one category and forced up to total dispatch in another; non-renewable capacity\n    # can't get committed in the 100% RPS due to non-zero min loads)\n\n    # count amount of renewable power produced from project\n    m.DispatchGenRenewableMW = Var(m.FUEL_BASED_GEN_TPS, within=NonNegativeReals)\n    m.DispatchGenRenewableMW_Cap = Constraint(m.FUEL_BASED_GEN_TPS,\n        rule = lambda m, g, tp:\n            m.DispatchGenRenewableMW[g, tp] <= m.DispatchGen[g, tp]\n    )\n    # a portion of every startup and shutdown must be designated as renewable\n    m.CommitGenRenewable = Var(m.FUEL_BASED_GEN_TPS, within=NonNegativeReals)\n    m.CommitGenRenewable_Cap = Constraint(m.FUEL_BASED_GEN_TPS,\n        rule = lambda m, g, tp:\n            m.CommitGenRenewable[g, tp] <= m.CommitGen[g, tp]\n    )\n    m.StartupGenCapacityRenewable = Var(m.FUEL_BASED_GEN_TPS, within=NonNegativeReals)\n    m.StartupGenCapacityRenewable_Cap = Constraint(m.FUEL_BASED_GEN_TPS,\n        rule = lambda m, g, tp:\n            m.StartupGenCapacityRenewable[g, tp] <= m.StartupGenCapacity[g, tp]\n    )\n    m.ShutdownGenCapacityRenewable = Var(m.FUEL_BASED_GEN_TPS, within=NonNegativeReals)\n    m.ShutdownGenCapacityRenewable_Cap = Constraint(m.FUEL_BASED_GEN_TPS,\n        rule = lambda m, g, tp:\n            m.ShutdownGenCapacityRenewable[g, tp] <= m.ShutdownGenCapacity[g, tp]\n    )\n    # chain commitments, startup and shutdown for renewables\n    m.Commit_StartupGenCapacity_ShutdownGenCapacity_Consistency_Renewable = Constraint(\n        m.FUEL_BASED_GEN_TPS,\n        rule=lambda m, g, tp:\n            m.CommitGenRenewable[g, m.tp_previous[tp]]\n            + m.StartupGenCapacityRenewable[g, tp]\n            - m.ShutdownGenCapacityRenewable[g, tp]\n            == m.CommitGenRenewable[g, tp]\n    )\n    # must use committed capacity for renewable production\n    m.Enforce_Dispatch_Upper_Limit_Renewable = Constraint(\n        m.FUEL_BASED_GEN_TPS,\n        rule=lambda m, g, tp:\n            m.DispatchGenRenewableMW[g, tp] <= m.CommitGenRenewable[g, tp]\n    )\n    # can't dispatch non-renewable capacity below its lower limit\n    m.Enforce_Dispatch_Lower_Limit_Non_Renewable = Constraint(\n        m.FUEL_BASED_GEN_TPS,\n        rule=lambda m, g, tp:\n            (m.DispatchGen[g, tp] - m.DispatchGenRenewableMW[g, tp])\n            >=\n            (m.CommitGen[g, tp] - m.CommitGenRenewable[g, tp])\n            * m.gen_min_load_fraction_TP[g, tp]\n    )\n    # use standard heat rate calculations for renewable and non-renewable parts\n    m.ProjRenewableFuelUseRate_Calculate = Constraint(\n        m.GEN_TPS_FUEL_PIECEWISE_CONS_SET,\n        rule=lambda m, g, tp, intercept, incremental_heat_rate:\n            sum(\n                m.GenFuelUseRate[g, tp, f]\n                    for f in m.FUELS_FOR_GEN[g]\n                        if f in m.RPS_ENERGY_SOURCES\n            )\n            >=\n            m.StartupGenCapacityRenewable[g, tp] * m.gen_startup_fuel[g] / m.tp_duration_hrs[tp]\n            + intercept * m.CommitGenRenewable[g, tp]\n            + incremental_heat_rate * m.DispatchGenRenewableMW[g, tp]\n    )\n    m.ProjNonRenewableFuelUseRate_Calculate = Constraint(\n        m.GEN_TPS_FUEL_PIECEWISE_CONS_SET,\n        rule=lambda m, g, tp, intercept, incremental_heat_rate:\n            sum(\n                m.GenFuelUseRate[g, tp, f]\n                    for f in m.FUELS_FOR_GEN[g]\n                        if f not in m.RPS_ENERGY_SOURCES\n            )\n            >=\n            (m.StartupGenCapacity[g, tp] - m.StartupGenCapacityRenewable[g, tp]) * m.gen_startup_fuel[g] / m.tp_duration_hrs[tp]\n            + intercept * (m.CommitGen[g, tp] - m.CommitGenRenewable[g, tp])\n            + incremental_heat_rate * (m.DispatchGen[g, tp] - m.DispatchGenRenewableMW[g, tp])\n    )\n\ndef relaxed_split_commit_DispatchGenRenewableMW(m):\n    # This is similar to the split_commit approach, but allows startup fuel\n    # to be freely allocated between renewable and non-renewable fuels.\n    # This eliminates the need for m.CommitGenRenewable variables, which are\n    # then replaced by m.DispatchGenRenewableMW.\n    # This means all startup fuel can be non-renewable, except when the RPS\n    # is 100%.\n\n    # count amount of renewable power produced from project\n    m.DispatchGenRenewableMW = Var(m.FUEL_BASED_GEN_TPS, within=NonNegativeReals)\n    m.DispatchGenRenewableMW_Cap = Constraint(m.FUEL_BASED_GEN_TPS,\n        rule = lambda m, g, tp:\n            m.DispatchGenRenewableMW[g, tp] <= m.DispatchGen[g, tp]\n    )\n    m.StartupGenCapacityRenewable = Var(m.FUEL_BASED_GEN_TPS, within=NonNegativeReals)\n    m.StartupGenCapacityRenewable_Cap = Constraint(m.FUEL_BASED_GEN_TPS,\n        rule = lambda m, g, tp:\n            m.StartupGenCapacityRenewable[g, tp] <= m.StartupGenCapacity[g, tp]\n    )\n\n    # can't dispatch non-renewable capacity below its lower limit\n    m.Enforce_Dispatch_Lower_Limit_Non_Renewable = Constraint(\n        m.FUEL_BASED_GEN_TPS,\n        rule=lambda m, g, tp:\n            (m.DispatchGen[g, tp] - m.DispatchGenRenewableMW[g, tp])\n            >=\n            (m.CommitGen[g, tp] - m.DispatchGenRenewableMW[g, tp])\n            * m.gen_min_load_fraction_TP[g, tp]\n    )\n\n    # rule=lambda m, g, t, intercept, incremental_heat_rate: (\n    #     sum(m.GenFuelUseRate[g, t, f] for f in m.FUELS_FOR_GEN[g]) >=\n    #     # Do the startup\n    #     m.StartupGenCapacity[g, t] * m.gen_startup_fuel[g] / m.tp_duration_hrs[t] +\n    #     intercept * m.CommitGen[g, t] +\n    #     incremental_heat_rate * m.DispatchGen[g, t]))\n\n    # TODO: fix bug in this code that forces renewable dispatch=total committed when\n    # using 100% RPS (this makes it hard to get reserves and makes it impossible to\n    # use the AES plant when using discrete commitment, because the PSIP module limits\n    # output to 180 MW but the plant is rated 185 MW.)\n\n    # use standard heat rate calculations for renewable and non-renewable parts\n    # These set a lower bound for each type of fuel, as if we committed one slice of capacity\n    # for renewables and one slice for non-renewable, equal to the amount of power from each.\n    m.ProjRenewableFuelUseRate_Calculate = Constraint(\n        m.GEN_TPS_FUEL_PIECEWISE_CONS_SET,\n        rule=lambda m, g, tp, intercept, incremental_heat_rate:\n            sum(\n                m.GenFuelUseRate[g, tp, f]\n                    for f in m.FUELS_FOR_GEN[g]\n                        if f in m.RPS_ENERGY_SOURCES\n            )\n            >=\n            m.StartupGenCapacityRenewable[g, tp] * m.gen_startup_fuel[g] / m.tp_duration_hrs[tp]\n            + intercept * m.DispatchGenRenewableMW[g, tp]\n            + incremental_heat_rate * m.DispatchGenRenewableMW[g, tp]\n    )\n    m.ProjNonRenewableFuelUseRate_Calculate = Constraint(\n        m.GEN_TPS_FUEL_PIECEWISE_CONS_SET,\n        rule=lambda m, g, tp, intercept, incremental_heat_rate:\n            sum(\n                m.GenFuelUseRate[g, tp, f]\n                    for f in m.FUELS_FOR_GEN[g]\n                        if f not in m.RPS_ENERGY_SOURCES\n            )\n            >=\n            (m.StartupGenCapacity[g, tp] - m.StartupGenCapacityRenewable[g, tp]) * m.gen_startup_fuel[g] / m.tp_duration_hrs[tp]\n            + intercept * (m.DispatchGen[g, tp] - m.DispatchGenRenewableMW[g, tp])\n            + incremental_heat_rate * (m.DispatchGen[g, tp] - m.DispatchGenRenewableMW[g, tp])\n    )\n\n    # don't allow any non-renewable fuel if RPS is 100%\n    if m.options.rps_level == 'activate':\n        # find all dispatch points for non-renewable fuels during periods with 100% RPS\n        m.FULL_RPS_GEN_FOSSIL_FUEL_DISPATCH_POINTS = Set(\n            dimen=3,\n            initialize=lambda m: [\n                (g, tp, f)\n                for per in m.PERIODS if m.rps_target_for_period[per] == 1.0\n                for g in m.FUEL_BASED_GENS if (g, per) in m.GEN_PERIODS\n                for f in m.FUELS_FOR_GEN[g] if not m.f_rps_eligible[f]\n                for tp in m.TPS_IN_PERIOD[per]\n            ]\n        )\n        m.No_Fossil_Fuel_With_Full_RPS = Constraint(\n            m.FULL_RPS_GEN_FOSSIL_FUEL_DISPATCH_POINTS,\n            rule=lambda m, g, tp, f: m.GenFuelUseRate[g, tp, f] == 0.0\n        )\n\n\ndef fuel_switch_at_high_rps_DispatchGenRenewableMW(m):\n    \"\"\" switch all plants to biofuel (and count toward RPS) if and only if rps is above threshold \"\"\"\n\n    if m.options.rps_level == 'activate':\n        # find all dispatch points for non-renewable fuels during periods with 100% RPS\n        m.HIGH_RPS_GEN_FOSSIL_FUEL_DISPATCH_POINTS = Set(\n            dimen=3,\n            initialize=lambda m: [\n                (g, tp, f)\n                    for p in m.PERIODS if m.rps_target_for_period[p] >= m.options.biofuel_switch_threshold\n                        for g in m.FUEL_BASED_GENS if (g, p) in m.GEN_PERIODS\n                            for f in m.FUELS_FOR_GEN[g] if not m.f_rps_eligible[f]\n                                for tp in m.TPS_IN_PERIOD[p]\n            ]\n        )\n        m.No_Fossil_Fuel_With_High_RPS = Constraint(\n            m.HIGH_RPS_GEN_FOSSIL_FUEL_DISPATCH_POINTS,\n            rule=lambda m, g, tp, f: m.GenFuelUseRate[g, tp, f] == 0.0\n        )\n        # count full dispatch toward RPS during non-fossil periods, otherwise give no credit\n        def rule(m, g, tp):\n            if m.rps_target_for_period[m.tp_period[tp]] >=  m.options.biofuel_switch_threshold:\n                return m.DispatchGen[g, tp]\n            else:\n                return 0.0\n        m.DispatchGenRenewableMW = Expression(m.FUEL_BASED_GEN_TPS, rule=rule)\n    else:\n        m.DispatchGenRenewableMW = Expression(\n            m.FUEL_BASED_GEN_TPS, within=NonNegativeReals,\n            rule=lambda m, g, tp: 0.0\n        )\n\ndef binary_by_period_DispatchGenRenewableMW(m):\n    # NOTE: this could be extended to handle fuel blends (e.g., 50% biomass/50% coal)\n    # by assigning an RPS eligibility level to each fuel (e.g., 50%), then\n    # setting binary variables for whether to use each fuel during each period\n    # (possibly treated as an SOS; or might be able to have an SOS for total\n    # amount to produce from each fuel during the period, and require that total\n    # consumption of each fuel <= production from that fuel * max((consumption+startup)/output across operating points)\n    # This could be further simplified by creating a set of eligibility levels,\n    # and choosing the amount to produce from each eligibility level (similar to the\n    # renewable/non-renewable distinction here, but with a 50% renewable category)\n\n    m.GEN_WITH_FUEL_ACTIVE_PERIODS = Set(dimen=2, initialize=lambda m: {\n        (g, pe)\n            for g in m.FUEL_BASED_GENS for pe in m.PERIODS\n                if (g, m.TPS_IN_PERIOD[pe].first()) in m.FUEL_BASED_GEN_TPS\n    })\n\n    # choose whether to run (only) on renewable fuels during each period\n    m.DispatchRenewableFlag = Var(m.GEN_WITH_FUEL_ACTIVE_PERIODS, within=Binary)\n\n    # force flag on or off when the RPS is simple (to speed computation)\n    def rule(m, g, p):\n        if m.rps_target_for_period[pe]==1.0:\n            # 100% RPS; use only renewable fuels\n            return (m.DispatchRenewableFlag[g, pe] == 1)\n        elif m.rps_target_for_period[pe]==0.0 or m.options.rps_level != 'activate':\n            # no RPS, don't bother counting renewable fuels\n            return (m.DispatchRenewableFlag[g, pe] == 0)\n        else:\n            return Constraint.Skip\n    m.Force_DispatchRenewableFlag = Constraint(\n        m.GEN_WITH_FUEL_ACTIVE_PERIODS,\n        rule=lambda m, g, pe:\n            (m.DispatchRenewableFlag[g, pe] == 0)\n            if (m.rps_target_for_period[pe]==0.0 or m.options.rps_level != 'activate')\n            else (\n                (m.DispatchRenewableFlag[g, pe] == 1)\n                if m.rps_target_for_period[pe]==1.0\n                else Constraint.Skip\n            )\n    )\n\n    # count amount of renewable power produced from project\n    m.DispatchGenRenewableMW = Var(m.FUEL_BASED_GEN_TPS, within=NonNegativeReals)\n\n    # don't overcount renewable power production\n    m.Limit_DispatchGenRenewableMW = Constraint(\n        m.FUEL_BASED_GEN_TPS,\n            rule=lambda m, g, tp:\n                m.DispatchGenRenewableMW[g, tp] <= m.DispatchGen[g, tp]\n    )\n    # force the flag to be set during renewable timepoints\n    m.Set_DispatchRenewableFlag = Constraint(\n            m.FUEL_BASED_GEN_TPS,\n            rule=lambda m, g, tp:\n                 m.DispatchGenRenewableMW[g, tp]\n                 <=\n                 m.DispatchRenewableFlag[g, m.tp_period[tp]] * m.gen_capacity_limit_mw[g]\n    )\n\n    # prevent use of non-renewable fuels during renewable timepoints\n    def Enforce_DispatchRenewableFlag_rule(m, g, tp, f):\n        if m.f_rps_eligible[f]:\n            return Constraint.Skip\n        else:\n            # harder to read like this, but having all numerical values on the right hand side\n            # facilitates analysis of duals and reduced costs\n            # note: we also add a little slack to avoid having this be the main constraint\n            # on total output from any power plant (that also clarifies dual analysis)\n            big_fuel = 1.01 * m.gen_capacity_limit_mw[g] * m.gen_full_load_heat_rate[g]\n            return (\n                m.GenFuelUseRate[g, tp, f]\n                + m.DispatchRenewableFlag[g, m.tp_period[tp]] * big_fuel\n                <=\n                big_fuel\n            )\n    m.Enforce_DispatchRenewableFlag = Constraint(\n        m.GEN_TP_FUELS, rule=Enforce_DispatchRenewableFlag_rule\n    )\n\ndef binary_by_timeseries_DispatchGenRenewableMW(m):\n    m.GEN_WITH_FUEL_ACTIVE_TIMESERIES = Set(dimen=2, initialize=lambda m: {\n        (g, ts)\n            for g in m.FUEL_BASED_GENS for ts in m.TIMESERIES\n                if (g, m.TPS_IN_TS[ts].first()) in m.FUEL_BASED_GEN_TPS\n    })\n\n    # choose whether to run (only) on renewable fuels during each period\n    m.DispatchRenewableFlag = Var(m.GEN_WITH_FUEL_ACTIVE_TIMESERIES, within=Binary)\n\n    # force flag on or off depending on RPS status (to speed computation)\n    m.Force_DispatchRenewableFlag = Constraint(\n        m.GEN_WITH_FUEL_ACTIVE_TIMESERIES,\n        rule=lambda m, g, ts:\n            (m.DispatchRenewableFlag[g, ts] == 0) if m.rps_target_for_period[m.ts_period[ts]]==0.0\n            else (\n                (m.DispatchRenewableFlag[g, ts] == 1) if m.rps_target_for_period[m.ts_period[ts]]==1.0\n                else Constraint.Skip\n            )\n    )\n\n    # count amount of renewable power produced from project\n    m.DispatchGenRenewableMW = Var(m.FUEL_BASED_GEN_TPS, within=NonNegativeReals)\n\n    # don't overcount renewable power production\n    m.Limit_DispatchGenRenewableMW = Constraint(\n        m.FUEL_BASED_GEN_TPS,\n            rule=lambda m, g, tp:\n                m.DispatchGenRenewableMW[g, tp] <= m.DispatchGen[g, tp]\n    )\n    # force the flag to be set during renewable timepoints\n    m.Set_DispatchRenewableFlag = Constraint(\n            m.FUEL_BASED_GEN_TPS,\n            rule=lambda m, g, tp:\n                 m.DispatchGenRenewableMW[g, tp]\n                 <=\n                 m.DispatchRenewableFlag[g, m.tp_ts[tp]] * m.gen_capacity_limit_mw[g]\n    )\n\n    # prevent use of non-renewable fuels during renewable timepoints\n    m.Enforce_DispatchRenewableFlag = Constraint(\n        m.GEN_TP_FUELS,\n        rule=lambda m, g, tp, f:\n            Constraint.Skip if m.f_rps_eligible[f]\n            else (\n                # original code, rewritten to get numerical parts on rhs\n                # m.GenFuelUseRate[g, tp, f]\n                # <=\n                # (1-m.DispatchRenewableFlag[g, m.tp_ts[tp]]) * m.gen_capacity_limit_mw[g] * m.gen_full_load_heat_rate[g]\n                m.GenFuelUseRate[g, tp, f]\n                + m.DispatchRenewableFlag[g, m.tp_ts[tp]] * m.gen_capacity_limit_mw[g] * m.gen_full_load_heat_rate[g]\n                <=\n                m.gen_capacity_limit_mw[g] * m.gen_full_load_heat_rate[g]\n            )\n    )\n\n\n\ndef advanced2_DispatchGenRenewableMW(m):\n    # choose whether to run (only) on renewable fuels during each timepoint\n    m.DispatchRenewableFlag = Var(m.FUEL_BASED_GEN_TPS, within=Binary)\n\n    # count amount of renewable power produced from project\n    m.DispatchGenRenewableMW = Var(m.FUEL_BASED_GEN_TPS, within=NonNegativeReals)\n\n    # don't overcount renewable power production\n    m.Limit_DispatchGenRenewableMW = Constraint(\n        m.FUEL_BASED_GEN_TPS,\n            rule=lambda m, g, tp: m.DispatchGenRenewableMW[g, tp] <= m.DispatchGen[g, tp]\n    )\n    # force the flag to be set during renewable timepoints\n    m.Set_DispatchRenewableFlag = Constraint(\n            m.FUEL_BASED_GEN_TPS,\n            rule=lambda m, g, tp:\n                 m.DispatchGenRenewableMW[g, tp]\n                 <=\n                 m.DispatchRenewableFlag[g, tp] * m.gen_capacity_limit_mw[g]\n    )\n\n    # prevent use of non-renewable fuels during renewable timepoints\n    m.Enforce_DispatchRenewableFlag = Constraint(\n        m.GEN_TP_FUELS,\n        rule=lambda m, g, tp, f:\n            Constraint.Skip if m.f_rps_eligible[f]\n            else (\n                m.GenFuelUseRate[g, tp, f]\n                <=\n                (1-m.DispatchRenewableFlag[g, tp]) * m.gen_capacity_limit_mw[g] * m.gen_full_load_heat_rate[g]\n            )\n    )\n\n\ndef advanced1_DispatchGenRenewableMW(m):\n    # Allocate the power produced during each timepoint among the fuels.\n\n    m.DispatchGenRenewableMW = Var(m.GEN_TP_FUELS, within=NonNegativeReals)\n    # make sure this matches total production\n    m.DispatchGenRenewableMW_Total = Constraint(\n        m.FUEL_BASED_GEN_TPS,\n        rule=lambda m, g, tp:\n            sum(m.DispatchGenRenewableMW[g, tp, f] for f in m.FUELS_FOR_GEN[g])\n            ==\n            m.DispatchGen[g, tp]\n    )\n\n    # choose a single fuel to use during each timestep\n    m.DispatchFuelFlag = Var(m.GEN_TP_FUELS, within=Binary)\n    m.DispatchFuelFlag_Total = Constraint(\n        m.FUEL_BASED_GEN_TPS,\n        rule=lambda m, g, tp:\n            sum(m.DispatchFuelFlag[g, tp, f] for f in m.FUELS_FOR_GEN[g])\n            ==\n            1\n    )\n\n    # consume only the selected fuel and allocate all production to that fuel (big-M constraints)\n    m.Allocate_Dispatch_Output = Constraint(\n        m.GEN_TP_FUELS,\n        rule=lambda m, g, tp, f:\n            m.DispatchGenRenewableMW[g, tp, f]\n            <=\n            m.DispatchFuelFlag[g, tp, f] * m.gen_capacity_limit_mw[g]\n    )\n    m.Allocate_Dispatch_Fuel = Constraint(\n        m.GEN_TP_FUELS,\n        rule=lambda m, g, tp, f:\n            m.GenFuelUseRate[g, tp, f]\n            <=\n            m.DispatchFuelFlag[g, tp, f] * m.gen_capacity_limit_mw[g] * m.gen_full_load_heat_rate[g]\n    )\n\n    # note: in cases where a project has a single fuel, the presolver should force\n    # DispatchGenRenewableMW for that fuel to match DispatchGen, and possibly\n    # eliminate the allocation constraints\n\n    # possible simplifications:\n    # omit binary variables and big-m constraints if len(m.FUELS_FOR_GEN[p]) == 1\n    #   (assign all production to the single fuel)\n    # use m.GenFuelUseRate[g, t, f] / m.gen_full_load_heat_rate[g]\n    #    for projects with no heat rate curve and no startup fuel\n\n    # note: a continuous, quadratic version of this function can be created as follows:\n    # - make DispatchFuelFlag a PercentFraction instead of Binary\n    # - replace gen_capacity_limit_mw with GenCapacity in Allocate_Dispatch_Output\n    # - replace m.gen_capacity_limit_mw * m.gen_full_load_heat_rate with\n    #   sum(m.GenFuelUseRate[g, t, f] for f in m.FUELS_FOR_GEN[g])\n    #   in Allocate_Dispatch_Fuel (define this as an Expression in dispatch.py)\n    # - replace <= with == in the allocation constraints\n    # - drop the DispatchGenRenewableMW_Total constraint\n\n    # or this would also work:\n    # m.DispatchGenRenewableMW = Var(m.GEN_TP_FUELS)\n    # m.DispatchGenRenewableMW_Allocate = Constraint(\n    #     m.GEN_TP_FUELS,\n    #     rule = lambda m, g, t, f:\n    #         m.DispatchGenRenewableMW[g, t, f]\n    #         * sum(m.GenFuelUseRate[g, t, _f] for _f in m.FUELS_FOR_GEN[g])\n    #         ==\n    #         DispatchGen[g, t]\n    #         * m.GenFuelUseRate[g, t, f]\n    # )\n\ndef quadratic_DispatchGenRenewableMW(m):\n    # choose how much power to obtain from renewables during each timepoint\n    m.DispatchRenewableFraction = Var(m.FUEL_BASED_GEN_TPS, within=PercentFraction)\n\n    # count amount of renewable power produced from project\n    m.DispatchGenRenewableMW = Var(m.FUEL_BASED_GEN_TPS, within=NonNegativeReals)\n\n    # don't overcount renewable power production\n    m.Set_DispatchRenewableFraction = Constraint(\n            m.FUEL_BASED_GEN_TPS,\n            rule=lambda m, g, tp:\n                 m.DispatchGenRenewableMW[g, tp]\n                 <=\n                 m.DispatchRenewableFraction[g, tp] * m.DispatchGen[g, tp]\n    )\n    m.Enforce_DispatchRenewableFraction = Constraint(\n        m.FUEL_BASED_GEN_TPS,\n        rule=lambda m, g, tp:\n            sum(\n                m.GenFuelUseRate[g, tp, f]\n                    for f in m.FUELS_FOR_GEN[g]\n                        if m.f_rps_eligible[f]\n            )\n            >=\n            m.DispatchRenewableFraction[g, tp] *\n            sum(\n                m.GenFuelUseRate[g, tp, f]\n                    for f in m.FUELS_FOR_GEN[g]\n            )\n    )\n\ndef quadratic1_DispatchGenRenewableMW(m):\n    # Allocate the power produced during each timepoint among the fuels.\n    m.DispatchGenRenewableMW = Var(m.GEN_TP_FUELS, within=NonNegativeReals)\n\n    # make sure this matches total production\n    m.DispatchGenRenewableMW_Total = Constraint(\n        m.FUEL_BASED_GEN_TPS,\n        rule=lambda m, g, tp:\n            sum(m.DispatchGenRenewableMW[g, tp, f] for f in m.FUELS_FOR_GEN[g])\n            ==\n            m.DispatchGen[g, tp]\n    )\n\n    m.DispatchGenRenewableMW_Allocate = Constraint(\n        m.GEN_TP_FUELS,\n        rule = lambda m, g, t, f:\n            m.DispatchGenRenewableMW[g, t, f]\n            * sum(m.GenFuelUseRate[g, t, _f] for _f in m.FUELS_FOR_GEN[g])\n            <=\n            m.DispatchGen[g, t]\n            * m.GenFuelUseRate[g, t, f]\n    )\n\ndef load_inputs(m, switch_data, inputs_dir):\n    switch_data.load_aug(\n        optional=True,\n        filename=os.path.join(inputs_dir, 'fuels.tab'),\n        select=('fuel', 'rps_eligible'),\n        param=(m.f_rps_eligible,))\n    if m.options.rps_targets is None:\n        switch_data.load_aug(\n            optional=True,\n            filename=os.path.join(inputs_dir, 'rps_targets.tab'),\n            autoselect=True,\n            index=m.RPS_YEARS,\n            param=(m.rps_target,))\n    else:\n        # construct data from a target specified as 'year1 level1 year2 level2 ...'\n        iterator = iter(m.options.rps_targets)\n        rps_targets = {int(year): float(target) for year, target in zip(iterator, iterator)}\n        switch_data.data()['RPS_YEARS'] = {None: sorted(rps_targets.keys())}\n        switch_data.data()['rps_target'] = rps_targets\n", "meta": {"hexsha": "292043e748fc258a809ec823c4c46299f38b58d3", "size": 37662, "ext": "py", "lang": "Python", "max_stars_repo_path": "switch_model/hawaii/rps.py", "max_stars_repo_name": "ashutosh-pande/switch3", "max_stars_repo_head_hexsha": "769d25a42c8323f24740567aa15c980f905a03e2", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "switch_model/hawaii/rps.py", "max_issues_repo_name": "ashutosh-pande/switch3", "max_issues_repo_head_hexsha": "769d25a42c8323f24740567aa15c980f905a03e2", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "switch_model/hawaii/rps.py", "max_forks_repo_name": "ashutosh-pande/switch3", "max_forks_repo_head_hexsha": "769d25a42c8323f24740567aa15c980f905a03e2", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.7850931677, "max_line_length": 146, "alphanum_fraction": 0.6547979396, "include": true, "reason": "from pyomo", "num_tokens": 9690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19277782022841536}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# coding: utf-8\n\n\n\"\"\"\nAuthor: Arnaud Ferré\nMail: arnaud.ferre.pro@gmail.com\nDescription: Training module for C-Norm method\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\n\n\n\n#######################################################################################################\n# Import modules & set up logging\n#######################################################################################################\n\nfrom optparse import OptionParser\nimport json\nimport gzip\nfrom os.path import dirname, exists\nfrom os import makedirs\n\nimport numpy\nimport gensim\nfrom tensorflow.keras import layers, models, Model, Input, regularizers, optimizers, metrics, losses, initializers, backend\n\nfrom word2term import getSizeOfVST\nfrom onto import loadOnto, ontoToVec\n\n#######################################################################################################\n# Utils\n#######################################################################################################\n\n# Normalization of token embeddings:\ndef normalizeEmbedding(vst_onlyTokens):\n    for token in vst_onlyTokens.keys():\n        vst_onlyTokens[token] = vst_onlyTokens[token] / numpy.linalg.norm(vst_onlyTokens[token])\n    return vst_onlyTokens\n\n\n# CHoose with getMatricForCNN...?\ndef prepare2D_data(vst_onlyTokens, dl_terms, dl_associations, vso, phraseMaxSize):\n\n    #ToDo: Keep a constant size of the input matrix between train and prediction\n    nbTerms = len(dl_terms.keys())\n    sizeVST = getSizeOfVST(vst_onlyTokens)\n    sizeVSO = getSizeOfVST(vso)\n\n    X_train = numpy.zeros((nbTerms, phraseMaxSize, sizeVST))\n    Y_train = numpy.zeros((nbTerms, 1, sizeVSO))\n\n    l_unkownTokens = list()\n    l_uncompleteExpressions = list()\n\n    for i, id_term in enumerate(dl_associations.keys()):\n        # stderr.write('id_term = %s\\n' % str(id_term))\n        # stderr.write('len(dl_associations[id_term]) = %d\\n' % len(dl_associations[id_term]))\n\n        for id_concept in dl_associations[id_term]:\n            Y_train[i][0] = vso[id_concept]\n            for j, token in enumerate(dl_terms[id_term]):\n                if j < phraseMaxSize:\n                    if token in vst_onlyTokens.keys():\n                        X_train[i][j] = vst_onlyTokens[token]\n                    else:\n                        l_unkownTokens.append(token)\n                else:\n                    l_uncompleteExpressions.append(id_term)\n            break # Because it' easier to keep only one concept per mention (mainly to calculate size of matrix).\n            # ToDo: switch to object to include directly size with these structures.\n\n    return X_train, Y_train, l_unkownTokens, l_uncompleteExpressions\n\n\n#\ndef loadJSON(filename):\n    if filename.endswith('.gz'):\n        f = gzip.open(filename)\n    else:\n        # f = open(filename, encoding='utf-8')\n        f = open(filename, \"r\", encoding=\"utf-8\")\n    result = json.load(f)\n    f.close()\n    return result;\n\n\n\n\n#######################################################################################################\n# Concept-Normalization (C-Norm)\n#######################################################################################################\n\ndef CNorm(vst_onlyTokens, dl_terms, dl_associations, vso,\n          nbEpochs=30, batchSize=64,\n          l_numberOfFilters=[4000], l_filterSizes=[1],\n          phraseMaxSize=15):\n\n    # Preparing data for SLFNN and S-CNN components:\n    dataSCNN, labels, l_unkownTokens, l_uncompleteExpressions = prepare2D_data(vst_onlyTokens, dl_terms, dl_associations, vso, phraseMaxSize)\n    dataSLFNN = numpy.zeros((dataSCNN.shape[0], dataSCNN.shape[2]))\n    for i in range( dataSCNN.shape[0]):\n        numberOfToken = 0\n        for embedding in dataSCNN[i]:\n            if not numpy.any(embedding):\n                pass\n            else:\n                numberOfToken += 1\n                dataSLFNN[i] += embedding\n\n        if numberOfToken > 0:\n            dataSLFNN[i] = dataSLFNN[i] / numberOfToken\n\n\n    # Input layers:\n    inputLP = Input(shape=dataSLFNN.shape[1])\n    inputCNN = Input(shape=[dataSCNN.shape[1],dataSCNN.shape[2]])\n\n\n    # SLFNN component:\n    ontoSpaceSize = labels.shape[2]\n    denseLP = layers.Dense(units=ontoSpaceSize, use_bias=True, kernel_initializer=initializers.GlorotUniform())(inputLP)\n    modelLP = Model(inputs=inputLP, outputs=denseLP)\n\n\n    # Shallow-CNN component:\n    l_subLayers = list()\n    for i, filterSize in enumerate(l_filterSizes):\n\n        convLayer = (layers.Conv1D(l_numberOfFilters[i], filterSize, strides=1, kernel_initializer=initializers.GlorotUniform()))(inputCNN)\n\n        outputSize = phraseMaxSize - filterSize + 1\n        pool = (layers.MaxPool1D(pool_size=outputSize))(convLayer)\n\n        activationLayer = (layers.LeakyReLU(alpha=0.3))(pool)\n\n        l_subLayers.append(activationLayer)\n\n    if len(l_filterSizes) > 1:\n        concatenateLayer = (layers.Concatenate(axis=-1))(l_subLayers)  # axis=-1 // concatenating on the last dimension\n    else:\n        concatenateLayer = l_subLayers[0]\n\n    denseLayer = layers.Dense(ontoSpaceSize, kernel_initializer=initializers.GlorotUniform())(concatenateLayer)\n    modelCNN = Model(inputs=inputCNN, outputs=denseLayer)\n\n    convModel = Model(inputs=inputCNN, outputs=concatenateLayer)\n    fullmodel = models.Sequential()\n    fullmodel.add(convModel)\n\n\n    # Combination of the two components:\n    combinedLayer = layers.average([modelLP.output, modelCNN.output])\n    fullModel = Model(inputs=[inputLP, inputCNN], outputs=combinedLayer)\n    fullModel.summary()\n\n\n    # Compile and train:\n    fullModel.compile(optimizer=optimizers.Nadam(), loss=losses.LogCosh(), metrics=[metrics.CosineSimilarity(), metrics.MeanSquaredError()])\n    fullModel.fit([dataSLFNN, dataSCNN], labels, epochs=nbEpochs, batch_size=batchSize)\n\n\n    return fullModel, vso, l_unkownTokens\n\n\n\n\n\n#######################################################################################################\n# Run class:\n#######################################################################################################\nclass Train(OptionParser):\n\n    def __init__(self):\n\n        OptionParser.__init__(self, usage='usage: %prog [options]')\n\n        self.add_option('--word-vectors', action='store', type='string', dest='word_vectors',\n                        help='path to word vectors JSON file as produced by word2vec')\n        self.add_option('--word-vectors-bin', action='store', type='string', dest='word_vectors_bin',\n                        help='path to word vectors binary file as produced by word2vec')\n        self.add_option('--terms', action='store', type='string', dest='terms',\n                        help='path to terms file in JSON format (map: id -> array of tokens)')\n        self.add_option('--attributions', action='store', type='string', dest='attributions',\n                        help='path to attributions file in JSON format (map: id -> array of concept ids)')\n        self.add_option('--ontology', action='store', type='string', dest='ontology',\n                        help='path to ontology file in OBO format')\n\n        self.add_option('--outputModel', action='store', type='string', dest='model', help='path to save the NN model directory')\n\n        # Methods hyperparameters:\n        self.add_option('--factor', action='store', type='float', dest='factors', default=0.65, help='parent concept weight factor (default=0.6).')\n        self.add_option('--epochs', action='store', type='int', dest='epochs', default=150, help='number of epochs (default=150).')\n        self.add_option('--batch', action='store', type='int', dest='batch', default=64, help='number of samples in batch (default=64).')\n        self.add_option('--filtersSize', action='append', type='int', dest='filtersSize', help='list of the different size of filters (default=1)')\n        self.add_option('--filtersNb', action='append', type='int', dest='filtersNb', help='list of the number of filters from filtersSize (default=100)')\n        self.add_option('--phraseMaxSize', action='store', type='int', dest='phrase_max_size', default=15, help='max considered size of phrases in inputs (default=15).')\n        self.add_option('--normalizedInputs', action='store', type='string', dest='normalizedInputs', default=\"True\", help='unit normalize embeddings if \"True\" (default: True).')\n\n\n\n    def run(self):\n\n        options, args = self.parse_args()\n        if len(args) > 0:\n            raise Exception('stray arguments: ' + ' '.join(args))\n\n        if options.word_vectors is None and options.word_vectors_bin is None:\n            raise Exception('missing either --word-vectors or --word-vectors-bin')\n        if options.word_vectors is not None and options.word_vectors_bin is not None:\n            raise Exception('incompatible --word-vectors or --word-vectors-bin')\n        if options.ontology is None:\n            raise Exception('missing --ontology')\n        if not options.terms:\n            raise Exception('missing --terms')\n        if not options.attributions:\n            raise Exception('missing --attributions')\n        if not options.model:\n            raise Exception('missing --outputModel')\n\n        if options.filtersSize is None:\n            options.filtersSize = [1]\n        if options.filtersNb is None:\n            options.filtersNb = [100]\n        if options.filtersSize is not None and options.filtersNb is not None:\n            if len(options.filtersSize) != len(options.filtersNb):\n                raise Exception('ERROR: number of elements in --filtersSize different from number of elements in --filtersNb')\n\n\n        # Selected hyperparameters (can have an important influence...):\n        print(\"\\nRuning C-Norm with next hyperparameters:\")\n        print(\"factor=\", options.factors)\n        print(\"epochs=\", options.epochs)\n        print(\"batch=\", options.batch)\n        print(\"filtersSize=\", options.filtersSize)\n        print(\"filtersNb=\", options.filtersNb)\n        print(\"phraseMaxSize=\", options.phrase_max_size)\n        print(\"normalizedInputs=\", options.normalizedInputs)\n\n\n        # Loading ontology:\n        print(\"\\nloading ontology:\", options.ontology)\n        ontology = loadOnto(options.ontology)\n\n        # Loading word embeddings:\n        if options.word_vectors is not None:\n            print(\"loading word embeddings:\", options.word_vectors)\n            word_vectors = loadJSON(options.word_vectors)\n        elif options.word_vectors_bin is not None:\n            print(\"loading word embeddings:\", options.word_vectors_bin)\n            EmbModel = gensim.models.Word2Vec.load(options.word_vectors_bin)\n            word_vectors = dict((k, list(numpy.float_(npf32) for npf32 in EmbModel.wv[k])) for k in EmbModel.wv.vocab.keys())\n\n        # Loading all mentions:\n        print(\"Loading terms:\", options.terms)\n        dl_terms = loadJSON(options.terms)\n\n        # Loading training examples:\n        print(\"Loading attributions:\", options.attributions)\n        attributions = loadJSON(options.attributions)\n\n\n        # Scaling of all embeddings:\n        if options.normalizedInputs is not None:\n            if options.normalizedInputs == \"True\":\n                print(\"\\nScaling: Unit normalization of input embeddings (recommended)...\")\n                word_vectors = normalizeEmbedding(word_vectors)\n                print(\"Scaling done.\\n\")\n        else:\n            print(\"No scaling of input embeddings (not recommended, see normalizedInputs option).\")\n\n        # Building ontological space\n        print(\"Building ontological space (with factor applied)...\")\n        vso = ontoToVec(ontology, options.factors)\n        print(\"Ontological space built.\\n\")\n\n\n\n        print(\"C-Norm training...\")\n        model, ontology_vector, _ = CNorm(word_vectors, dl_terms, attributions, vso,\n                                nbEpochs=options.epochs, batchSize=options.batch,\n                                l_numberOfFilters=options.filtersNb, l_filterSizes=options.filtersSize,\n                                phraseMaxSize=options.phrase_max_size)\n        print(\"C-Norm training done.\\n\")\n\n\n\n        # Saving model:\n        if options.model is not None:\n            print(\"Saving trained Tensorflow model...\")\n            d = dirname(options.model)\n            if not exists(d) and d != '':\n                makedirs(d)\n            model.save(options.model)\n            print(\"Model saved.\")\n\n\n\n#######################################################################################################\n# Test section\n#######################################################################################################\n\nif __name__ == '__main__':\n\n    Train().run()\n", "meta": {"hexsha": "804df5e345a19fbd0e940f19119eaec2491a4aeb", "size": 13136, "ext": "py", "lang": "Python", "max_stars_repo_path": "train.py", "max_stars_repo_name": "ArnaudFerre/C-Norm_PostLab", "max_stars_repo_head_hexsha": "edb9462a32b3e47b38bfd62836427d3a90f510ab", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "train.py", "max_issues_repo_name": "ArnaudFerre/C-Norm_PostLab", "max_issues_repo_head_hexsha": "edb9462a32b3e47b38bfd62836427d3a90f510ab", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "train.py", "max_forks_repo_name": "ArnaudFerre/C-Norm_PostLab", "max_forks_repo_head_hexsha": "edb9462a32b3e47b38bfd62836427d3a90f510ab", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5696202532, "max_line_length": 178, "alphanum_fraction": 0.6079476248, "include": true, "reason": "import numpy", "num_tokens": 2792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19277782022841536}}
{"text": "# -*- coding: utf-8 -*-\n# After execution of the main pipeline, files are organized in a variety of\n# locations, and some information is spread across multiple files. This\n# gathers various charts and creates tables using provided data, storing it\n# all in folders organized by paper section.\nimport utils\nimport graphUtils\nimport numpy as np\nimport scipy.stats as stats\nimport os\nimport re\nimport subprocess\n\nimport mainParams as mp\nfrom groupWords import getWordGroupsRangeTest\n\n\n# ==============================================================================\n# ==============================================================================\n\n# Color constants for heat-map tables\nCOLOR_BLUE = (66, 134, 244)\nCOLOR_ORANGE = (244, 179, 66)\nCOLOR_GRAY = (239, 239, 239)\n\n# given a start color, an end color, and a current value within a min-max\n# range, find a linear interpolation between start and end color\ndef colorConvert(min, max, current, startColor, endColor):\n    sr, sg, sb = startColor\n    er, eg, eb = endColor\n    scale = (current - min) / (max - min)\n    red = sr + scale*(er-sr)\n    green = sg + scale*(eg-sg)\n    blue = sb + scale*(eb-sb)\n    return (red/255, green/255, blue/255)\n\n\n# create tables with information evaluating given metrics\ndef makeMetricEvalTables(suffix, topStr, comparableTopStr, topNum, poetryNum, comparableNum, simMetrics, baseFolder):\n    baseScoreInfo = [\n        (\"Cosine\", 0),\n        (\"Burrows' Delta\", 0),\n    ]\n\n    bestMetricName = \"Jensen-Shannon (250)\" #Jensen-Shannon+p\n    bestMetricSigWork = []\n    bestMetricSigAuthor = []\n\n    evalTableOutput = []\n    evalTableOutput.append(\"\"\"\\\\begin{table}[!bt]\n  \\\\centering\n  \\\\def\\\\arraystretch{1}\n  \\\\begin{tabular}{| l | r | r |}\n\\\\hline\n & \\\\multicolumn{2}{c|}{\\\\textbf{Percentage of segments most similar to a segment...}} \\\\\\\\\n\n\\\\textbf{Metric}& \\\\textbf{from the same work} & \\\\textbf{by the same author} \\\\\\\\\\\\hline\n\"\"\")\n\n\n    sameWorkTableOutput = []\n    sameAuthorTableOutput = []\n    temp = \"\"\"\\\\begin{table}[!bt]\n  \\\\centering\n  \\\\def\\\\arraystretch{1}\n  \\\\begin{tabular}{| l | c | c | c |}\n\\\\hline\n    \"\"\"\n    sameWorkTableOutput.append(temp)\n    sameAuthorTableOutput.append(temp)\n\n    temp = \"& & \\\\textbf{Top %d +} & \\\\\\\\\" % (topNum)\n    sameWorkTableOutput.append(temp)\n    sameAuthorTableOutput.append(temp)\n\n    temp = \"\\\\textbf{Metric}& \\\\textbf{Top %d} & \\\\textbf{Top %d in Poetry} & \\\\textbf{Top %d} \\\\\\\\\\\\hline\" % (topNum, poetryNum, comparableNum)\n    sameWorkTableOutput.append(temp)\n    sameAuthorTableOutput.append(temp)\n\n    workSigReport = []\n    authorSigReport = []\n\n\n    # & \\\\textbf{Sim to another work} & \\\\textbf{Closest to diff author} & \\\\textbf{Median}\n\n    # Get the list of authors and works the metric got correct\n    scoreLists = {}\n    for simMetric in simMetrics:\n        dir, metricName = simMetric\n        scoreLists[metricName] = {}\n        for i, params in enumerate([(False, False), (True, False), (False, True), ]):\n            name = metricName\n            addP, comparable = params\n            metricTopStr = topStr\n            if addP:\n                metricTopStr += \"+p\"\n                name += \"+p\"\n            # look at comparable number of non-poetry words\n            elif comparable:\n                metricTopStr = comparableTopStr\n                name += \" (%d)\" % comparableNum\n            else:\n                name += \" (%d)\" % topNum\n\n            fname = \"output/greek/no_split/%s/%s/metric/Books/scores.json\" % (metricTopStr, dir)\n            scores = utils.getContent(fname, True)\n            scoreLists[metricName][i] = scores\n            scoreLists[metricName][i][\"name\"] = name\n\n    baseScores = []\n    for bsi in baseScoreInfo:\n        baseScoreMetric, baseScoreIndex = bsi\n        baseScores.append(scoreLists[baseScoreMetric][baseScoreIndex])\n\n    # Create a table of the information using the provided scores\n    for metricName in scoreLists:\n        cell2 = \"\\\\textbf{%s}\" % (metricName)\n        cell3 = \"\\\\textbf{%s}\" % (metricName)\n        for i in scoreLists[metricName]:\n            currentScores = scoreLists[metricName][i]\n            authorScores = currentScores[\"author\"]\n            workScores = currentScores[\"work\"]\n            name = currentScores[\"name\"]\n            sameWork = \"%.2f%%\" % (100*np.mean(workScores))\n            sameAuth = \"%.2f%%\" % (100*np.mean(authorScores))\n            # sameWork = \"%.2f%%, (%d/%d)\" % (100*np.mean(workScores), np.sum(workScores), len(workScores))\n            # sameAuth = \"%.2f%%, (%d/%d)\" % (100*np.mean(authorScores), np.sum(authorScores), len(authorScores))\n\n            # cell = \"%s & %s & %s & %s & %s & %s\" % (name, sameAuth, sameWork, otherWork, diffAuthClosest, median)\n            cell = \"%s & %s & %s\" % (name, sameWork, sameAuth)\n            cell = cell.replace(\"%\", \"\\\\%\")\n            evalTableOutput.append(\"%s\\\\\\\\\\\\hline\" % cell)\n\n            cell2 += \" & %s\" % (sameWork) # work_p\n            cell3 += \" & %s\" % (sameAuth) # , author_p)\n\n            for j, baseScore in enumerate(baseScores):\n                a = baseScore[\"work\"]\n                b = currentScores[\"work\"]\n                work_t, work_p = stats.ttest_rel(a, b)\n                workSigReport.append(name)\n                # Degrees of freedom\n                df = len(b) - 1\n                workSig = \"  (M=%.3f, SD=%.3f) t(%d)=%.3f, p=%.3e\" % (np.mean(b), np.std(b), df, work_t, work_p)\n                workSigReport.append(workSig)\n\n\n                a = baseScore[\"author\"]\n                b = currentScores[\"author\"]\n                author_t, author_p = stats.ttest_rel(a, b)\n                authorSigReport.append(name)\n                # Degrees of freedom\n                df = len(b) - 1\n                authorSig = \"  (M=%.3f, SD=%.3f) t(%d)=%.3f, p=%.3e\" % (np.mean(b), np.std(b), df, author_t, author_p)\n                authorSigReport.append(authorSig)\n\n                if (name == bestMetricName or name == baseScore[\"name\"]):\n                    bestMetricSigWork.append(\"%s vs %s\" % (name, baseScore[\"name\"]))\n                    bestMetricSigWork.append(workSig)\n\n                    bestMetricSigAuthor.append(\"%s vs %s\" % (name, baseScore[\"name\"]))\n                    bestMetricSigAuthor.append(authorSig)\n\n                #print(\"  Author: t-statistic = %6.3f pvalue = %f\" %  stats.ttest_rel(a, b))\n\n                # Significance notes\n                if (j == 0):\n                    if (work_p < 0.01):\n                        cell2 += \"\\\\textbf{†}\"\n                    elif (work_p < 0.05):\n                        cell2 += \"\\\\textbf{*}\"\n                    if (author_p < 0.01):\n                        cell3 += \"\\\\textbf{†}\"\n                    elif (author_p < 0.05):\n                        cell3 += \"\\\\textbf{*}\"\n                else:\n                    if (work_p < 0.01):\n                        cell2 += \"\\\\textbf{‡}\"\n                    if (author_p < 0.01):\n                        cell3 += \"\\\\textbf{‡}\"\n\n\n\n        cell2 = cell2.replace(\"%\", \"\\\\%\")\n        sameWorkTableOutput.append(\"%s\\\\\\\\\\\\hline\" % cell2)\n\n        cell3 = cell3.replace(\"%\", \"\\\\%\")\n        sameAuthorTableOutput.append(\"%s\\\\\\\\\\\\hline\" % cell3)\n\n    evalTableOutput.append(\"\"\"\n      \\\\end{tabular}\n      \\\\caption{How well similarity metrics identify whether two segments come from the same work or the same author.}\n      \\\\label{table:metric_eval}\n    \\\\end{table}\n    \"\"\")\n\n    utils.safeWrite(\"%smetric/extraInfo/metricEvalTable%s.tex\" % (baseFolder, suffix), \"\\n\".join(evalTableOutput))\n\n    sameWorkTableOutput.append(\"\\\\end{tabular}\")\n    sameWorkTableOutput.append(\"\\\\caption[How well similarity metrics based on a given set of words identify whether two segments come from the same work.]{\")\n    sameWorkTableOutput.append(\"How well similarity metrics based on a given set of words identify whether two segments come from the same work. \\\\newline\")\n    sameWorkTableOutput.append(\"†: Results very significant (p < 0.01) when compared to %s. \\\\newline\" % baseScores[0][\"name\"])\n    sameWorkTableOutput.append(\"*: Results significant (p < 0.05) when compared to %s. \\\\newline\" % baseScores[0][\"name\"])\n    sameWorkTableOutput.append(\"‡: Results very significant (p < 0.01) when compared to %s. \" % baseScores[1][\"name\"])\n    sameWorkTableOutput.append(\"}\")\n    sameWorkTableOutput.append(\"\\\\label{table:metric_eval_work}\")\n    sameWorkTableOutput.append(\"\\\\end{table}\")\n\n    utils.safeWrite(\"%smetric/sameWorkEvalTable%s.tex\" % (baseFolder, suffix), \"\\n\".join(sameWorkTableOutput))\n\n\n    sameAuthorTableOutput.append(\"\\\\end{tabular}\")\n    sameAuthorTableOutput.append(\"\\\\caption[How well similarity metrics based on a given set of words identify whether two segments come from the same author.]{\")\n    sameAuthorTableOutput.append(\"How well similarity metrics based on a given set of words identify whether two segments come from the same author. \\\\newline\")\n    sameAuthorTableOutput.append(\"†: Results very significant (p < 0.01) when compared to %s. \\\\newline\" % baseScores[0][\"name\"])\n    sameAuthorTableOutput.append(\"*: Results significant (p < 0.05) when compared to %s. \\\\newline\" % baseScores[0][\"name\"])\n    sameAuthorTableOutput.append(\"‡: Results very significant (p < 0.01) when compared to %s. \" % baseScores[1][\"name\"])\n    sameAuthorTableOutput.append(\"}\")\n    sameAuthorTableOutput.append(\"\\\\label{table:metric_eval_author}\")\n    sameAuthorTableOutput.append(\"\\\\end{table}\")\n\n    utils.safeWrite(\"%smetric/sameAuthorEvalTable%s.tex\" % (baseFolder, suffix), \"\\n\".join(sameAuthorTableOutput))\n\n\n    sigReport = \"Work:\\n\" + (\"\\n\".join(bestMetricSigWork)) + \"\\n\\n-------------\\n\\nAuthor:\\n\" + (\"\\n\".join(bestMetricSigAuthor))\n    utils.safeWrite(\"%smetric/bestMetricSignificance%s.txt\" % (baseFolder, suffix), sigReport)\n    # utils.safeWrite(\"%smetric/bestMetricSignificanceWork%s.txt\" % (baseFolder, suffix), \"\\n\".join(bestMetricSigWork))\n    # utils.safeWrite(\"%smetric/bestMetricSignificanceAuthor%s.txt\" % (baseFolder, suffix), \"\\n\".join(bestMetricSigAuthor))\n\n\n    utils.safeWrite(\"%smetric/extraInfo/metricSignificanceReportWork%s.txt\" % (baseFolder, suffix), \"\\n\".join(workSigReport))\n    utils.safeWrite(\"%smetric/extraInfo/metricSignificanceReportAuthor%s.txt\" % (baseFolder, suffix), \"\\n\".join(authorSigReport))\n\n\n\n\n# create tables with information evaluating performance of each metric with/without\n# smoothing and remainder words\ndef makeMetricInternalTables(suffix, topStr, simMetrics, baseFolder):\n    metricInternalTables = []\n    for simMetric in simMetrics:\n        dir, metricName = simMetric\n\n        # skip Jensen-Shannon\n        if metricName == \"Jensen-Shannon\":\n            continue\n\n        tableOutput = []\n        temp = \"\"\"\n\\\\begin{table}[!bt]\n  \\\\centering\n  \\\\def\\\\arraystretch{1}\n  \\\\begin{tabular}{| l | c | c | c |}\n\\\\hline\n        \"\"\"\n        tableOutput.append(temp)\n\n        temp = \"\\\\textbf{Metric Options} & \\\\textbf{Author} & \\\\textbf{Work} & \\\\textbf{Total} \\\\\\\\\\\\hline\"\n        tableOutput.append(temp)\n\n        workSigReport = []\n        authorSigReport = []\n        totalSigReport = []\n\n        # & \\\\textbf{Sim to another work} & \\\\textbf{Closest to diff author} & \\\\textbf{Median}\n\n        metricOptions = [\n            (\"Baseline\", \"-remainder-smoothed\"),\n            (\"+1 Smoothing\", \"-remainder+smoothed\"),\n            (\"Remainder\", \"+remainder-smoothed\"),\n            (\"Both\", \"+remainder+smoothed\")\n        ]\n\n        # Get the list of authors and works the metric got correct\n        scoreLists = {}\n        for _, opt in metricOptions:\n            scoreLists[opt] = {}\n            name = opt\n            # Use Poetry Words\n            metricTopStr = topStr\n\n            fname = \"output/greek/no_split/%s/%s/metric%s/Books/scores.json\" % (metricTopStr, dir, opt)\n            scores = utils.getContent(fname, True)\n            scoreLists[opt] = scores\n            scoreLists[opt][\"name\"] = name\n\n        baseScore = scoreLists[\"-remainder-smoothed\"]\n        # baseScores = []\n        # for bsi in baseScoreInfo:\n        #     baseScoreMetric, baseScoreIndex = bsi\n        #     baseScores.append(scoreLists[baseScoreMetric][baseScoreIndex])\n\n        # Create a table of the information using the provided scores\n        for optName, opt in metricOptions:\n            cell = \"\\\\textbf{%s}\" % (optName)\n\n            currentScores = scoreLists[opt]\n            authorScores = currentScores[\"author\"]\n            workScores = currentScores[\"work\"]\n            name = currentScores[\"name\"]\n            sameWork = \"%.2f%%, (%d/%d)\" % (100*np.mean(workScores), np.sum(workScores), len(workScores))\n            sameAuth = \"%.2f%%, (%d/%d)\" % (100*np.mean(authorScores), np.sum(authorScores), len(authorScores))\n            all = np.concatenate((workScores, authorScores))\n            total = \"%.2f%%, (%d/%d)\" % (100*np.mean(all), np.sum(all), len(all))\n\n            wrk = \" & %s\" % (sameWork)\n            auth = \" & %s\" % (sameAuth)\n            tot = \" & %s\" % (total)\n\n\n            # Calculate significance\n            a = baseScore[\"work\"]\n            b = currentScores[\"work\"]\n            work_t, work_p = stats.ttest_rel(a, b)\n            workSigReport.append(name)\n            # Degrees of freedom\n            df = len(b) - 1\n            workSig = \"  (M=%.3f, SD=%.3f) t(%d)=%.3f, p=%.3e\" % (np.mean(b), np.std(b), df, work_t, work_p)\n            workSigReport.append(workSig)\n\n\n            a = baseScore[\"author\"]\n            b = currentScores[\"author\"]\n            author_t, author_p = stats.ttest_rel(a, b)\n            authorSigReport.append(name)\n            # Degrees of freedom\n            df = len(b) - 1\n            authorSig = \"  (M=%.3f, SD=%.3f) t(%d)=%.3f, p=%.3e\" % (np.mean(b), np.std(b), df, author_t, author_p)\n            authorSigReport.append(authorSig)\n\n\n            a = np.concatenate((baseScore[\"work\"], baseScore[\"author\"]))\n            b = np.concatenate((currentScores[\"work\"], currentScores[\"author\"]))\n            all_t, all_p = stats.ttest_rel(a, b)\n            totalSigReport.append(name)\n            # Degrees of freedom\n            df = len(b) - 1\n            totalSig = \"  (M=%.3f, SD=%.3f) t(%d)=%.3f, p=%.3e\" % (np.mean(b), np.std(b), df, all_t, all_p)\n            totalSigReport.append(totalSig)\n\n\n            # if (name == bestMetricName or name == baseScore[\"name\"]):\n            #     bestMetricSigWork.append(\"%s vs %s\" % (name, baseScore[\"name\"]))\n            #     bestMetricSigWork.append(workSig)\n            #\n            #     bestMetricSigAuthor.append(\"%s vs %s\" % (name, baseScore[\"name\"]))\n            #     bestMetricSigAuthor.append(authorSig)\n\n            #print(\"  Author: t-statistic = %6.3f pvalue = %f\" %  stats.ttest_rel(a, b))\n\n            # Significance notes\n            if (work_p < 0.01):\n                wrk += \"\\\\textbf{†}\"\n            elif (work_p < 0.05):\n                wrk += \"\\\\textbf{*}\"\n            if (author_p < 0.01):\n                auth += \"\\\\textbf{†}\"\n            elif (author_p < 0.05):\n                auth += \"\\\\textbf{*}\"\n            if (all_p < 0.01):\n                tot += \"\\\\textbf{†}\"\n            elif (all_p < 0.05):\n                tot += \"\\\\textbf{*}\"\n\n            # wrk += \" %.4f\" % work_p\n            # auth += \" %.4f\" % author_p\n            # tot += \" %.4f\" % all_p\n\n            cell += \"%s%s%s\" % (wrk, auth, tot)\n\n            cell = cell.replace(\"%\", \"\\\\%\")\n            tableOutput.append(\"%s\\\\\\\\\\\\hline\" % cell)\n\n        tableOutput.append(\"\\\\end{tabular}\")\n        tableOutput.append(\"\\\\caption{\")\n        tableOutput.append(\"How well %s performs with the remainder words and smoothing included. \" % metricName)\n        tableOutput.append(\"†: Results very significant (p < 0.01) when compared to baseline. \")\n        tableOutput.append(\"*: Results significant (p < 0.05) when compared to baseline. \")\n        tableOutput.append(\"}\")\n        tableOutput.append(\"\\\\label{table:metric_options_eval_%s}\" % dir)\n        tableOutput.append(\"\\\\end{table}\")\n\n        tableOutput.append(\"\")\n        tableOutput.append(\"\")\n        metricInternalTables.append(\"\\n\".join(tableOutput))\n        utils.safeWrite(\"%smetric/%s_optionsEvalTable%s.tex\" % (baseFolder, metricName, suffix), \"\\n\".join(tableOutput))\n\n        # sigReport = \"Work:\\n\" + (\"\\n\".join(bestMetricSigWork)) + \"\\n\\n-------------\\n\\nAuthor:\\n\" + (\"\\n\".join(bestMetricSigAuthor))\n        # utils.safeWrite(\"%smetric/bestMetricSignificance%s_2.txt\" % (baseFolder, suffix), sigReport)\n\n        # utils.safeWrite(\"%smetric/extraInfo/metricSignificanceReportWork%s_2.txt\" % (baseFolder, suffix), \"\\n\".join(workSigReport))\n        # utils.safeWrite(\"%smetric/extraInfo/metricSignificanceReportAuthor%s_2.txt\" % (baseFolder, suffix), \"\\n\".join(authorSigReport))\n    utils.safeWrite(\"%smetric/extraInfo/optionsEvalTables%s.tex\" % (baseFolder, suffix), \"\\n\".join(metricInternalTables))\n\n\n# Get author pairs for authors 4 centuries apart with high similarity.\ndef fourCenturiesTables(topStr, simMetrics, baseFolder):\n    comparisonOutput = []\n    topSimsToExamine = 100\n\n    # Grab this from the best metric\n    authorSims = utils.getContent(\"output/greek/no_split/%s/jensen-shannon/metric/Authors/sims.txt\" % (topStr), False).split(\"\\n\")\n    topDistantSims = []\n    topDistantAuthors = {}\n    for i, sim in enumerate(authorSims):\n        centuries_apart = int(sim.split(\"(\")[-1].split(\" \")[0])\n        if (centuries_apart >= 4 and i < topSimsToExamine):\n            topDistantSims.append(sim)\n            topDistantAuthors[sim[11:]] = {}\n\n        authors = \" (\".join(sim.split(\" - \")[1].split(\" (\")[:-1])\n        if authors == \"Isocrates, Lysias\" or authors == \"Plato, Xenophon\" or authors == \"AratusSolensis, Callimachus\" or authors == \"Herodotus, Thucydides\":\n            comparisonOutput.append(\"Rank %d: %s\" % (i+1, sim))\n\n    fourCenturiesApartOutput = []\n    fourCenturiesApartOutput.append(\"%d of the top %d are at least 4 centuries apart.\" % (len(topDistantSims), topSimsToExamine))\n    fourCenturiesApartOutput.append(\"---\")\n    fourCenturiesApartOutput.extend(topDistantSims)\n\n    utils.safeWrite(\"%swordUse/fourCenturiesApart.txt\" % baseFolder, \"\\n\".join(fourCenturiesApartOutput))\n\n    # Comparison to English and Icelandic\n    numGreek = len(authorSims)\n    fracGreek = topSimsToExamine/numGreek\n    numDistantGreek = len(topDistantSims)\n\n    englishSims = utils.getContent(\"output/english/no_split/%s/jensen-shannon/metric/Authors/sims.txt\" % (topStr), False).split(\"\\n\")\n    numEnglish = len(englishSims)\n    topSimsEnglish = int(np.ceil(numEnglish*fracGreek))\n    fracEnglish = topSimsEnglish/numEnglish\n    numDistantEnglish = 0\n    num2English = 0\n    for sim in englishSims[:topSimsEnglish]:\n        centuries_apart = int(sim.split(\"(\")[-1].split(\" \")[0])\n        if (centuries_apart >= 2):\n            num2English += 1\n        if (centuries_apart >= 4):\n            numDistantEnglish += 1\n\n    iceSims = utils.getContent(\"output/icelandic/no_split/%s/jensen-shannon/metric/Authors/sims.txt\" % (topStr), False).split(\"\\n\")\n    numIcelandic = len(iceSims)\n    topSimsIcelandic = int(np.ceil(numIcelandic*fracGreek))\n    fracIcelandic = topSimsIcelandic/numIcelandic\n    numDistantIcelandic = 0\n    for sim in iceSims[:topSimsIcelandic]:\n        centuries_apart = int(sim.split(\"(\")[-1].split(\" \")[0])\n        if (centuries_apart >= 4):\n            numDistantIcelandic += 1\n\n    comparisonOutput.append(\"\\n=========\\n\")\n    comparisonOutput.append(\"Top similar pairs\")\n    comparisonOutput.append(\"Greek:\")\n    comparisonOutput.append(\"  examining top %d of %d pairs (%.2f%%)\" % (topSimsToExamine, numGreek, 100*fracGreek))\n    comparisonOutput.append(\"  %d (%.2f%%) are at least 4 centuries apart\" % (numDistantGreek, 100*numDistantGreek/topSimsToExamine))\n    comparisonOutput.append(\"English:\")\n    comparisonOutput.append(\"  examining top %d of %d pairs (%.2f%%)\" % (topSimsEnglish, numEnglish, 100*fracEnglish))\n    comparisonOutput.append(\"  %d (%.2f%%) are at least 4 centuries apart\" % (numDistantEnglish, 100*numDistantEnglish/topSimsEnglish))\n    comparisonOutput.append(\"  %d (%.2f%%) are at least 2 centuries apart\" % (num2English, 100*num2English/topSimsEnglish))\n    comparisonOutput.append(\"Icelandic:\")\n    comparisonOutput.append(\"  examining top %d of %d pairs (%.2f%%)\" % (topSimsIcelandic, numIcelandic, 100*fracIcelandic))\n    comparisonOutput.append(\"  %d (%.2f%%) are at least 4 centuries apart\" % (numDistantIcelandic, 100*numDistantIcelandic/topSimsIcelandic))\n\n    utils.safeWrite(\"%swordUse/fourApartComparisonInfo.txt\" % baseFolder, \"\\n\".join(comparisonOutput))\n\n    # Table\n    for simMetric in simMetrics:\n        dir, name = simMetric\n        # \"\" or \"+p\" depending on which is better\n        metricSims = utils.getContent(\"output/greek/no_split/%s/%s/metric/Authors/sims.txt\" % (topStr, dir), False).split(\"\\n\")\n        for i, sim in enumerate(metricSims):\n            pairName = sim[11:]\n            if pairName in topDistantAuthors:\n                topDistantAuthors[pairName][dir] = i + 1\n\n    # prepare values for coloring table cells\n    maxVal = 0\n    minVal = 1000000\n\n    for authorPair in topDistantAuthors:\n        for simDir, _ in simMetrics:\n            val = topDistantAuthors[authorPair][simDir]\n            minVal = min(minVal, val)\n            maxVal = max(maxVal, val)\n\n    pairRankOutput = []\n    pairRankOutputSimple = []\n    pairRankOutput.append(\"\"\"\n    \\\\begin{table}[!bt]\n      \\\\centering\n      \\\\def\\\\arraystretch{1}\n      \\\\begin{tabular}{| l | c | c | c | c | c | c |}\n    \\\\hline\n    & \\\\multicolumn{5}{c|}{\\\\textbf{Rank according to}} \\\\\\\\\n    & \\\\textbf{Jensen-} & \\\\textbf{Burrows'} & & & & \\\\\\\\\n    \\\\textbf{Authors} & \\\\textbf{Shannon} & \\\\textbf{Delta} & \\\\textbf{Min-Max} & \\\\textbf{Manhattan} & \\\\textbf{Canberra} & \\\\textbf{Cosine} \\\\\\\\\\\\hline\n    \"\"\")\n    pairRankOutputSimple.append(\"%s,%s,%s,%s,%s,%s,%s\" % (\"Authors\", \"Jensen-Shannon\", \"Burrow's Delta\", \"Min-Max\", \"Manhattan\", \"Canberra\", \"Cosine\"))\n    authorConvert = {\n        \"ApolloniusRhodius\": \"Apollonius\",\n        \"DionysiusOfHalicarnassus\": \"Dionysius\",\n        \"EusebiusOfCaesarea\": \"Eusebius\",\n        \"ClementOfAlexandria\": \"Clement\",\n        \"BasilBishopOfCaesarea\": \"Basil\",\n        \"Anonymous(Hymns_Aphrodite)\": \"Hymns Aphrodite\",\n        \"Anonymous(Hymns_Apollo)\": \"Hymns Apollo\",\n        \"Anonymous(Hymns_Demeter)\": \"Hymns Demeter\",\n        \"Anonymous(Hymns_Hermes)\": \"Hymns Hermes\",\n        \"Anonymous(Hymns_Rest)\": \"Hymns Rest\",\n    }\n    for authorPair in topDistantAuthors:\n        pair = \"(\".join(authorPair.split(\" (\")[:-1])\n        pairSplit = pair.split(\", \")\n        author1 = pairSplit[0]\n        author2 = pairSplit[1]\n\n        if author1 in authorConvert:\n            author1 = authorConvert[author1]\n        if author2 in authorConvert:\n            author2 = authorConvert[author2]\n\n        pairName = author1 + \", \" + author2\n        cell = \"%s &\" % pairName\n        cellSimple = \"%s,\" % re.sub(\", \", \"/\", pairName)\n        firstVal = None\n        for simDir, _ in simMetrics:\n            val = topDistantAuthors[authorPair][simDir]\n\n            cutoff = 100\n            if (val < cutoff):\n                r, g, b = colorConvert(minVal, cutoff, val, COLOR_ORANGE, COLOR_GRAY)\n            else:\n                r, g, b = colorConvert(cutoff, maxVal, val, COLOR_GRAY, COLOR_BLUE)\n            cell += \"\\\\cellcolor[rgb]{%.3f,%.3f,%.3f} \" % (r, g, b)\n\n            if (firstVal == None):\n                firstVal = val\n                cell += \"%d & \" % (val)\n                cellSimple += \"%d,\" % (val)\n            else:\n                cell += \"%d (%+d) & \" % (val, firstVal - val)\n                rel = \"(%d)\" % (firstVal - val)\n                cellSimple += \"%d %s,\" % (val, rel)\n        cell = cell[:-2]\n        pairRankOutput.append(\"%s\\\\\\\\\\\\hline\" % cell)\n        pairRankOutputSimple.append(cellSimple)\n    pairRankOutput.append(\"\"\"\n      \\\\end{tabular}\n      \\\\caption{Rank of these pair's similarity by different metrics.}\n      \\\\label{table:pair_rank}\n    \\\\end{table}\n    \"\"\")\n\n    utils.safeWrite(\"%swordUse/pairRankTable.tex\" % baseFolder, \"\\n\".join(pairRankOutput))\n    utils.safeWrite(\"%swordUse/pairRankTableSimple.csv\" % baseFolder, \"\\n\".join(pairRankOutputSimple))\n\n\n# Get info on number of words used and create the table of top words\ndef getWordUseInfo(topStr, baseFolder):\n    # total +p words\n    tops = utils.getContent(\"output/greek/no_split/%s/wordInfo_%s.txt\" % (topStr, topStr), False).split(\"\\n\")[1:]\n    poetrys = utils.getContent(\"output/greek/no_split/top_p/wordInfo_top_p.txt\", False).split(\"\\n\")[1:]\n    # Top plus poetry\n    totals = utils.getContent(\"output/greek/no_split/%s+p/wordInfo_%s+p.txt\" % (topStr, topStr), False).split(\"\\n\")[1:]\n\n    numWordsOutput = []\n    numWordsOutput.append(\"Number of Top Words: %d\" % len(tops))\n    numWordsOutput.append(\"Number of Poetry Words: %d\" % len(poetrys))\n    numWordsOutput.append(\"Total Number of Words: %d\" % len(totals))\n    utils.safeWrite(\"%s/wordUse/totalWords.txt\" % baseFolder, \"\\n\".join(numWordsOutput))\n\n\n    # Create Table of words\n    topRanks = {}\n    poetryRanks = {}\n\n    for i, line in enumerate(tops):\n        w = line.split(\":\")[0]\n        topRanks[w] = i + 1\n\n    for i, line in enumerate(poetrys):\n        w = line.split(\":\")[0]\n        poetryRanks[w] = i + 1\n\n    rankInfo = []\n    for line in totals:\n        w = line.split(\":\")[0]\n        topRank = \"\"\n        if w in topRanks:\n            topRank = \"%d\" % topRanks[w]\n        poetryRank = \"\"\n        if w in poetryRanks:\n            poetryRank = \"%d\" % poetryRanks[w]\n\n        rankInfo.append((w, topRank, poetryRank))\n\n\n    rankTableOutput = []\n    rankTableOutput.append(\"\"\"\n    \\\\begin{table}[!hbt]\n      \\\\centering\n      \\\\def\\\\arraystretch{1}\n      \\\\begin{tabular}{| l | l | l ||| l | l | l ||| l | l | l ||| l | l | l |}\n    \\\\hline\n\n    \\\\textbf{Token} & \\\\textbf{A} & \\\\textbf{P} & \\\\textbf{Token} & \\\\textbf{A} & \\\\textbf{P} & \\\\textbf{Token} & \\\\textbf{A} & \\\\textbf{P} & \\\\textbf{Token} & \\\\textbf{A} & \\\\textbf{P}\\\\\\\\\\\\hline\n    \"\"\")\n\n\n    columnHeight = 43;\n    for i in range(columnHeight):\n        cells =  []\n        for j in range(4):\n            index = i + j*columnHeight\n            cell = \"\"\n            if (index < len(rankInfo)):\n                cell = \"%s & %s & %s\" % rankInfo[index]\n\n            cells.append(cell)\n        rankTableOutput.append(\"%s \\\\\\\\\\\\hline\" % (\" & \".join(cells)))\n\n    rankTableOutput.append(\"\"\"\n      \\\\end{tabular}\n      \\\\caption{List of tokens used, along with their rank in the top 150 tokens found in all texts (\\\\textbf{A}) and rank in the top 100 tokens found in poetry texts (\\\\textbf{P}).}\n      \\\\label{table:top_words}\n    \\\\end{table}\n    \"\"\")\n\n    utils.safeWrite(\"%swordUse/topWordsTable.tex\" % baseFolder, \"\\n\".join(rankTableOutput))\n\n\n# Get author and book counts for our languages for the data section\ndef getAuthorBookCounts(baseFolder):\n    ab_counts_output = []\n    splitter = \"\\n------\\n\"\n\n    ab_counts_output.append(\"Greek:\\n\")\n    ab_counts_output.append(utils.getContent(\"output/greek/numberOfAuthors_Books.txt\", False))\n    ab_counts_output.append(utils.getContent(\"output/greek/numberOfTypes_Tokens.txt\", False))\n    ab_counts_output.append(splitter)\n    ab_counts_output.append(\"English:\\n\")\n    ab_counts_output.append(utils.getContent(\"output/english/numberOfAuthors_Books.txt\", False))\n    ab_counts_output.append(utils.getContent(\"output/english/numberOfTypes_Tokens.txt\", False))\n    ab_counts_output.append(splitter)\n    ab_counts_output.append(\"Icelandic:\\n\")\n    ab_counts_output.append(utils.getContent(\"output/icelandic/numberOfAuthors_Books.txt\", False))\n    ab_counts_output.append(utils.getContent(\"output/icelandic/numberOfTypes_Tokens.txt\", False))\n    ab_counts_output.append(splitter)\n\n    utils.safeWrite(\"%s/AuthorBookNumbers.txt\" % baseFolder, \"\\n\".join(ab_counts_output))\n\n# Get word overlap info\ndef getOverlapInfo(baseFolder):\n    output = []\n    splitter = \"\\n------\\n\"\n\n    output.append(\"Greek:\\n\")\n    output.append(utils.getContent(\"output/greek/topWordOverlapOverTime.txt\", False))\n    output.append(splitter)\n    output.append(\"English:\\n\")\n    output.append(utils.getContent(\"output/english/topWordOverlapOverTime.txt\", False))\n    output.append(splitter)\n    output.append(\"Icelandic:\\n\")\n    output.append(utils.getContent(\"output/icelandic/topWordOverlapOverTime.txt\", False))\n    output.append(splitter)\n\n    utils.safeWrite(\"%s/topWordOverlapOverTime.txt\" % baseFolder, \"\\n\".join(output))\n\n# Get information about words that were skipped\ndef getSkippedWordInfo(baseFolder):\n    output = []\n    splitter = \"\\n------\\n\"\n\n    output.append(\"Greek:\\n\")\n    output.append(utils.getContent(\"output/greek/no_split/top250/chosenWordInfo.txt\", False))\n    output.append(\"\\nPoetry:\")\n    output.append(utils.getContent(\"output/greek/no_split/top250+p/chosenWordInfoPoetry.txt\", False))\n    output.append(splitter)\n    output.append(\"English:\\n\")\n    output.append(utils.getContent(\"output/english/no_split/top250/chosenWordInfo.txt\", False))\n    output.append(\"\\nPoetry:\")\n    output.append(utils.getContent(\"output/english/no_split/top250+p/chosenWordInfoPoetry.txt\", False))\n    output.append(splitter)\n    output.append(\"Icelandic:\\n\")\n    output.append(utils.getContent(\"output/icelandic/no_split/top250/chosenWordInfo.txt\", False))\n    output.append(splitter)\n\n    utils.safeWrite(\"%s/skippedWords.txt\" % baseFolder, \"\\n\".join(output))\n\ndef getDataInfo(topStr, baseFolder):\n    baseFolder = baseFolder + \"/data\"\n\n    getAuthorBookCounts(baseFolder)\n\n    getOverlapInfo(baseFolder)\n\n    getSkippedWordInfo(baseFolder)\n\n    subprocess.run(\"cp output/greek/no_split/%s/wordsTable.csv %s/wordsTableGreek_%s.csv\" % (topStr, baseFolder, topStr), shell=True)\n    subprocess.run(\"cp output/english/no_split/%s/wordsTable.csv %s/wordsTableEnglish_%s.csv\" % (topStr, baseFolder, topStr), shell=True)\n    subprocess.run(\"cp output/icelandic/no_split/%s/wordsTable.csv %s/wordsTableIcelandic_%s.csv\" % (topStr, baseFolder, topStr), shell=True)\n\n# Get information on the top authors\ndef makeTopAuthorTable(topStr, baseFolder):\n    # Grab this from the best metric\n    fname = \"output/greek/no_split/%s/jensen-shannon/metric/Authors/sims.txt\" % (topStr)\n    allAuthorSims = utils.getContent(fname, False).split(\"\\n\")\n\n    topAuthorPairs = []\n\n    topAuthorPairs.append(\"\"\"\\\\begin{table}[!bt]\n  \\\\centering\n  \\\\def\\\\arraystretch{1.2}\n  \\\\begin{tabular}{| r | l | l | l | l |} \\\\hline\n  & \\\\textbf{Author 1} & \\\\textbf{Author 2} & \\\\textbf{Score} & \\\\textbf{Notes}  \\\\\\\\\\\\hline\n\"\"\")\n\n\n    for i, pair in enumerate(allAuthorSims[:10]):\n        splt1 = pair.split(\" - \")\n        sim = splt1[0]\n        auths = splt1[1].split(\" (\")[0].split(\", \")\n        topAuthorPairs.append(\"  %.2d & %s & %s & %s & TODO \\\\\\\\\\\\hline\" % (i+1, auths[0], auths[1], sim))\n\n    topAuthorPairs.append(\"\"\"\n  \\\\end{tabular}\n  \\\\caption{Top author pairs by similarity score according to Jensen-Shannon Similarity.}\n  \\\\label{table:top_author_pairs}\n\\\\end{table}\n    \"\"\")\n\n    utils.safeWrite(\"%smetric/topAuthorPairs.tex\" % baseFolder, \"\\n\".join(topAuthorPairs))\n\n\n\n# create tables showing performance of light machine learning algorithms on predicting various categories\ndef makeMLTable(source, norm, filename):\n    output = []\n\n    output.append(\"\"\"\\\\begin{table}[!bt]\n  \\\\centering\n  \\\\def\\\\arraystretch{1.2}\n\"\"\")\n\n    # No naive bayes if normed due to negative data\n    if norm:\n        output.append(\"  \\\\begin{tabular}{| r | l | l |} \\\\hline\")\n        output.append(\"  \\\\textbf{Prediction Task} & \\\\textbf{Majority Class} & \\\\textbf{KNN}  \\\\\\\\\\\\hline\")\n    else:\n        output.append(\"  \\\\begin{tabular}{| r | l | l | l |} \\\\hline\")\n        output.append(\"  \\\\textbf{Prediction Task} & \\\\textbf{Majority Class} & \\\\textbf{KNN} & \\\\textbf{Naive Bayes}  \\\\\\\\\\\\hline\")\n\n\n    for t in [\"Authors\", \"Books\", \"Books_2\"]:\n        cats = [\"genre\", \"dialect\", \"timeframe\"]\n        if (t == \"Books\"):\n            cats.append(\"author\")\n        if (t == \"Books_2\"):\n            cats = [\"work\", \"genre\", \"dialect\", \"timeframe\", \"author\"]\n\n        for cat in cats:\n            fname = source + \"res_%s_%s.txt\" % (cat, t)\n            lines = utils.getContent(fname, False).split(\"\\n\")\n            maj_class = lines[1].split(\" - \")[0].strip()\n            knn = lines[2].split(\" - \")[0].strip()\n            naive_bayes = lines[3].split(\" - \")[0].strip()\n\n            t_name = t\n            if t_name == \"Books\":\n                t_name = \"Segments\"\n            if t_name == \"Books_2\":\n                t_name = \"Segments*\"\n            if norm:\n                output.append(\" %s of %s & %s & %s \\\\\\\\\\\\hline\" % (cat, t_name, maj_class, knn))\n            else:\n                output.append(\" %s of %s & %s & %s & %s \\\\\\\\\\\\hline\" % (cat, t_name, maj_class, knn, naive_bayes))\n\n    output.append(\"\"\"\n  \\\\end{tabular}\n  \\\\caption{Results of running simple machine learning on the frequency data.}\n  \\\\label{table:ml+p}\n\\\\end{table}\n    \"\"\")\n\n    utils.safeWrite(filename, \"\\n\".join(output))\n\n# =============================================================================\n# =============================================================================\n\n# Get information on genre\ndef getGenreInfo(topStr, baseFolder):\n    # 2-dimensional tSNE projection\n    subprocess.run(\"cp output/greek/no_split/%s/authors/tSNE/genre_tSNE_2D_no_labels.pdf %sgenre/tSNE_topWords_nolabels.pdf\" % (topStr, baseFolder), shell=True)\n    subprocess.run(\"cp output/greek/no_split/%s/authors/tSNE/genre_tSNE_2D_labels.pdf %sgenre/tSNE_topWords_labels.pdf\" % (topStr, baseFolder), shell=True)\n\n\n# Get information on the metrics\ndef getMetricInfo(topStr, comparableTopStr, topNum, poetryNum, comparableNum, simMetrics, baseFolder):\n    # Copy full eval files for jensen-shannon\n    subprocess.run(\"cp output/greek/no_split/%s/jensen-shannon/metric/Books/comparisonInfo.txt %smetric/extraInfo/metricEvaluation_tops.txt\" % (topStr, baseFolder), shell=True)\n    subprocess.run(\"cp output/greek/no_split/%s+p/jensen-shannon/metric/Books/comparisonInfo.txt %smetric/extraInfo/metricEvaluation_+p.txt\" % (topStr, baseFolder), shell=True)\n\n    # Grab median distance\n    fname = \"output/greek/no_split/%s/jensen-shannon/metric/Books/comparisonInfo.txt\" % (topStr)\n    metricEvalInfo = utils.getContent(fname, False).split(\"=========\")[-2].split(\"\\n\")[2:-1]\n    sameAuthorRanks = []\n    for i, line in enumerate(metricEvalInfo):\n        sameAuthorRank = line.split(\"with same author: \")[1].split(\".\")[0]\n        sameAuthorRanks.append(int(sameAuthorRank))\n\n    median = np.median(sameAuthorRanks)\n\n    utils.safeWrite(\"%smetric/extraInfo/medianForDifferentAuthor.txt\" % (baseFolder), \"Median distance for closest author: %f\" % median)\n\n    # get info on the indica\n    subprocess.run(\"cp output/greek/no_split/%s/jensen-shannon/metric/Books/sims/Arrian.Indica.1.txt %smetric/extraInfo/arrianIndica.txt\" % (topStr, baseFolder), shell=True)\n\n\n    # Info on book distance\n    # Grab this from the best metric\n    fname = \"output/greek/no_split/%s/jensen-shannon/metric/Books/sims.txt\" % (topStr)\n    allBookSims = utils.getContent(fname, False).split(\"\\n\")\n\n    utils.safeWrite(\"%smetric/lowestSimilarity.txt\" % (baseFolder), \"Lowest similarity between segments: %s\" % allBookSims[-1])\n\n    # Info on top similar authors\n    makeTopAuthorTable(topStr, baseFolder)\n\n    # ===============================\n\n\n    makeMetricEvalTables(\"\", topStr, comparableTopStr, topNum, poetryNum, comparableNum, simMetrics, baseFolder)\n\n    # baseScoreMetric = \"Burrows' Delta\"\n    # baseScoreIndex = 1\n    # makeMetricEvalTables(\"_cmp_burrows\", topStr, comparableTopStr, topNum, poetryNum, comparableNum, simMetrics, baseScoreMetric, baseScoreIndex)\n\n# Get information comparing various texts across centuries\ndef getCenturyInfo(topStr, baseFolder):\n    subprocess.run(\"cp output/greek/no_split/%s/jensen-shannon/metric/Authors/century_sims_overall_no_labels.pdf %scentury/centuriesGreek.pdf\" % (topStr, baseFolder), shell=True)\n    subprocess.run(\"cp output/greek/no_split/%s/jensen-shannon/metric/Authors/century_sims_overall_labels.pdf %scentury/extraInfo/Greek_CenturyOverall_Label.pdf\" % (topStr, baseFolder), shell=True)\n\n    subprocess.run(\"cp output/greek/no_split/%s/jensen-shannon/metric/Authors/simRange.txt %scentury/extraInfo/Greek_SimRange.txt\" % (topStr, baseFolder), shell=True)\n\n\n    # -------------------------\n    # Century similarity data\n    subprocess.run(\"cp output/greek/no_split/%s/jensen-shannon/metric/Authors/century_sims_genre_no_labels.pdf %scentury/extraInfo/Greek_Century_No_Label.pdf\" % (topStr, baseFolder), shell=True)\n    subprocess.run(\"cp output/greek/no_split/%s/jensen-shannon/metric/Authors/century_sims_genre_labels.pdf %scentury/extraInfo/Greek_Century_Label.pdf\" % (topStr, baseFolder), shell=True)\n    subprocess.run(\"cp output/greek/no_split/%s+p/jensen-shannon/metric/Authors/century_sims_genre_no_labels.pdf %scentury/extraInfo/Greek+p_Century_No_Label.pdf\" % (topStr, baseFolder), shell=True)\n    subprocess.run(\"cp output/greek/no_split/%s+p/jensen-shannon/metric/Authors/century_sims_genre_labels.pdf %scentury/extraInfo/Greek+p_Century_Label.pdf\" % (topStr, baseFolder), shell=True)\n\n    subprocess.run(\"cp output/greek/no_split/%s/jensen-shannon/metric/Authors/century_sims_genre_under_9_no_labels.pdf %scentury/extraInfo/Greek_Century_Cutoff_No_Label.pdf\" % (topStr, baseFolder), shell=True)\n    subprocess.run(\"cp output/greek/no_split/%s/jensen-shannon/metric/Authors/century_sims_genre_under_9_labels.pdf %scentury/extraInfo/Greek_Century_Cutoff_Label.pdf\" % (topStr, baseFolder), shell=True)\n    subprocess.run(\"cp output/greek/no_split/%s+p/jensen-shannon/metric/Authors/century_sims_genre_under_9_no_labels.pdf %scentury/extraInfo/Greek+p_Century_Cutoff_No_Label.pdf\" % (topStr, baseFolder), shell=True)\n    subprocess.run(\"cp output/greek/no_split/%s+p/jensen-shannon/metric/Authors/century_sims_genre_under_9_labels.pdf %scentury/extraInfo/Greek+p_Century_Cutoff_Label.pdf\" % (topStr, baseFolder), shell=True)\n\n\n\n    subprocess.run(\"cp output/greek/no_split/%s/jensen-shannon/metric/Authors/century_sims_genre_under_9_no_labels.pdf %scentury/centuriesGreek2.pdf\" % (topStr, baseFolder), shell=True)\n    subprocess.run(\"cp output/greek/no_split/%s/jensen-shannon/metric/Authors/century_sims_genre_under_9_no_labels_violin.pdf %scentury/centuriesGreekViolin.pdf\" % (topStr, baseFolder), shell=True)\n\n\n    subprocess.run(\"cp output/english/no_split/%s/jensen-shannon/metric/Authors/simRange.txt %scentury/extraInfo/English_SimRange.txt\" % (topStr, baseFolder), shell=True)\n    subprocess.run(\"cp output/english/no_split/%s/jensen-shannon/metric/Authors/century_sims_genre_no_labels.pdf %scentury/centuriesEnglish.pdf\" % (topStr, baseFolder), shell=True)\n    subprocess.run(\"cp output/english/no_split/%s/jensen-shannon/metric/Authors/century_sims_genre_no_labels_violin.pdf %scentury/centuriesEnglishViolin.pdf\" % (topStr, baseFolder), shell=True)\n    subprocess.run(\"cp output/english/no_split/%s/jensen-shannon/metric/Authors/century_sims_genre_labels.pdf %scentury/extraInfo/English_Century_Label.pdf\" % (topStr, baseFolder), shell=True)\n\n    subprocess.run(\"cp output/icelandic/no_split/%s/jensen-shannon/metric/Authors/simRange.txt %scentury/extraInfo/Icelandic_SimRange.txt\" % (topStr, baseFolder), shell=True)\n    subprocess.run(\"cp output/icelandic/no_split/%s/jensen-shannon/metric/Authors/century_sims_genre_no_labels.pdf %scentury/centuriesIcelandic.pdf\" % (topStr, baseFolder), shell=True)\n    subprocess.run(\"cp output/icelandic/no_split/%s/jensen-shannon/metric/Authors/century_sims_genre_no_labels_violin.pdf %scentury/centuriesIcelandicViolin.pdf\" % (topStr, baseFolder), shell=True)\n    subprocess.run(\"cp output/icelandic/no_split/%s/jensen-shannon/metric/Authors/century_sims_genre_labels.pdf %scentury/extraInfo/Icelandic_Century_Label.pdf\" % (topStr, baseFolder), shell=True)\n\n\n    # Get pvalue + other regression information for charts\n    greekPval = utils.getContent(\"output/greek/no_split/%s/jensen-shannon/metric/Authors/century_sims_genre_under_9_pslope.txt\" % (topStr), False)\n    englishPval = utils.getContent(\"output/english/no_split/%s/jensen-shannon/metric/Authors/century_sims_genre_pslope.txt\" % (topStr), False)\n    icelandicPval = utils.getContent(\"output/icelandic/no_split/%s/jensen-shannon/metric/Authors/century_sims_genre_pslope.txt\" % (topStr), False)\n\n    pvalOutput = []\n    pvalOutput.append(\"Greek:\")\n    pvalOutput.append(greekPval)\n    pvalOutput.append(\"English:\")\n    pvalOutput.append(englishPval)\n    pvalOutput.append(\"Icelandic:\")\n    pvalOutput.append(icelandicPval)\n\n    utils.safeWrite(\"%scentury/century_pvals.txt\" % baseFolder, \"\\n\".join(pvalOutput))\n\n# Get charts on word usage across authors and by specific author pairs\ndef getWordUsageInfo(topStr, baseFolder):\n    # Word usage charts\n    # Grab these from the best metric\n    subprocess.run(\"cp output/greek/no_split/%s/wordImportance/Jensen-shannon-sorted/ignoreBestWords.pdf %swordUse/ignoreBestWords.pdf\" % (topStr, baseFolder), shell=True)\n    subprocess.run(\"cp output/greek/no_split/%s/wordImportance/Jensen-shannon-sorted/all-diffs-cumul-cloud.pdf %swordUse/extraInfo/broadWordUsage.pdf\" % (topStr, baseFolder), shell=True)\n    subprocess.run(\"cp output/greek/no_split/%s/wordImportance/Jensen-shannon-sorted/all-diffs-cumul.pdf %swordUse/extraInfo/all-diffs-cumul.pdf\" % (topStr, baseFolder), shell=True)\n\n\n    # Word organization charts\n    subprocess.run(\"cp output/greek/no_split/%s/textsOnlyTopWords/9_group/tSNE/Word_Groupings_tSNE_2D_labels.pdf %swordUse/wordGroups.pdf\" % (topStr, baseFolder), shell=True)\n\n    subprocess.run(\"cp output/greek/no_split/%s/textsOnlyTopWords/9_group/images/dhct.pdf %swordUse/eightUp_9Group.pdf\" % (topStr, baseFolder), shell=True)\n    subprocess.run(\"cp output/greek/no_split/%s/textsOnlyTopWords/pos_group/images/dhct.pdf %swordUse/eightUp_posGroup.pdf\" % (topStr, baseFolder), shell=True)\n\n# create each of the folders in a list if they do not exist yet\ndef createFolders(folders, baseFolder):\n    for folder in folders:\n        if not(os.path.exists(baseFolder + folder)):\n            subprocess.run(\"mkdir \" + baseFolder + folder, shell=True)\n\n# =============================================================================\n# =============================================================================\n# =============================================================================\n\n# List of similarity metrics\nSIM_METRICS = [\n    (\"jensen-shannon\", \"Jensen-Shannon\"),\n    (\"burrowsdelta\", \"Burrows' Delta\"),\n    (\"minmax\", \"Min-Max\"),\n    (\"cityblock\", \"Manhattan\"),\n    (\"canberra\", \"Canberra\"),\n    (\"cosine\", \"Cosine\"),\n]\n\n\n# Gather full set of files\ndef gatherFilesFull(topStr, topNum, comparableTopStr, comparableNum, poetryNum):\n    baseFolder = \"output/full/\"\n\n\n    folders = [\n        \"\",\n        \"data\",\n        \"genre\",\n        \"metric\",\n        \"metric/extraInfo\",\n        \"century\",\n        \"century/extraInfo\",\n        \"wordUse\",\n        \"wordUse/extraInfo\",\n        \"wordUse/grouping\",\n    ]\n    createFolders(folders, baseFolder)\n\n    # Get info for the data section\n    getDataInfo(topStr, baseFolder)\n\n    # Get info for approach section\n    getWordUseInfo(topStr, baseFolder)\n\n    # Get genre info\n    getGenreInfo(topStr, baseFolder)\n    # Gather 4up tsne charts for standard data and data normalized by genre\n    # Grab this from the best metric\n    subprocess.run(\"cp output/greek/no_split/%s/Authors/tSNE/info_no_labels_4Up.pdf %sgenre/groupings.pdf\" % (topStr, baseFolder), shell=True)\n    subprocess.run(\"cp output/greek/no_split/%s/Books/tSNE/outliers4up.pdf %sgenre/bookOutliers.pdf\" % (topStr, baseFolder), shell=True)\n\n    # Get book tsne charts\n    # Grab this from the best metric\n    subprocess.run(\"cp output/greek/no_split/%s/Books/tSNE/tSNE_2D_no_labels.pdf %sgenre/books_tSNE_no_labels.pdf\" % (topStr, baseFolder), shell=True)\n    subprocess.run(\"cp output/greek/no_split/%s/Books/tSNE/tSNE_2D_labels.pdf %sgenre/books_tSNE_labels.pdf\" % (topStr, baseFolder), shell=True)\n    # To get a look at these, run python3 visualizeBooks\n\n\n    # Get info for standard and normalized by poetry\n    makeMLTable(\"output/greek/no_split/%s/dataPreds/\" % (topStr), False, \"%sgenre/ml_table.tex\" % baseFolder)\n    # makeMLTable(\"output/greek/no_split/%s+p/dataPreds/\" % (topStr), False, \"%sgenre/ml_table+p.tex\" % baseFolder)\n\n    # =========================\n\n    # Get info for results section\n\n    # -----------\n    # Metric\n    getMetricInfo(topStr, comparableTopStr, topNum, poetryNum, comparableNum, SIM_METRICS, baseFolder)\n\n    makeMetricInternalTables(\"\", topStr, SIM_METRICS, baseFolder)\n    makeMetricInternalTables(\"\", topStr + \"+p\", SIM_METRICS, baseFolder)\n\n    # -----------\n    # Century\n    # Get information on century comparison\n    getCenturyInfo(topStr, baseFolder)\n    # Get pvalue + other regression information for charts that are + p\n    greekPval = utils.getContent(\"output/greek/no_split/%s+p/jensen-shannon/metric/Authors/century_sims_genre_under_9_pslope.txt\" % (topStr), False)\n    englishPval = utils.getContent(\"output/english/no_split/%s+p/jensen-shannon/metric/Authors/century_sims_genre_pslope.txt\" % (topStr), False)\n\n    pvalOutput = []\n    pvalOutput.append(\"Greek:\")\n    pvalOutput.append(greekPval)\n    pvalOutput.append(\"English:\")\n    pvalOutput.append(englishPval)\n\n    utils.safeWrite(\"%scentury/century_pvals+p.txt\" % baseFolder, \"\\n\".join(pvalOutput))\n\n    # -------------------------\n    # Grab this from the best metric\n    subprocess.run(\"cp output/greek/no_split/%s/jensen-shannon/metric/Authors/sims.txt %swordUse/authorSims.txt\" % (topStr, baseFolder), shell=True)\n\n    fourCenturiesTables(topStr, SIM_METRICS, baseFolder)\n\n    # get word usage charts and info\n    getWordUsageInfo(topStr, baseFolder)\n\n    # We didn't end up using grouping charts\n    # groups = getWordGroupsRangeTest(topNum)\n    # for g in groups:\n    #     subprocess.run(\"cp output/greek/no_split/%s+p/textsOnlyTopWords/%d_group/images/groupingCompare.png %swordUse/grouping/%.2d.png\" % (topStr, g, baseFolder, g), shell=True)\n\nif __name__ == \"__main__\":\n    #gatherFiles(mp.topStr, mp.topNum, mp.comparableTopStr, mp.comparableTopNum, mp.poetryNum)\n    gatherFilesFull(mp.topStr, mp.topNum, mp.comparableTopStr, mp.comparableTopNum, mp.poetryNum)\n", "meta": {"hexsha": "04fd8e7527a72c7f92a3463375a4e45a93e5f6a0", "size": 46348, "ext": "py", "lang": "Python", "max_stars_repo_path": "gatherFiles.py", "max_stars_repo_name": "twopis/twopis", "max_stars_repo_head_hexsha": "1f89d44c3e8481bb2da8e20187b5eeb63b96092e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-11T00:08:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-11T00:08:11.000Z", "max_issues_repo_path": "gatherFiles.py", "max_issues_repo_name": "twopis/twopis", "max_issues_repo_head_hexsha": "1f89d44c3e8481bb2da8e20187b5eeb63b96092e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gatherFiles.py", "max_forks_repo_name": "twopis/twopis", "max_forks_repo_head_hexsha": "1f89d44c3e8481bb2da8e20187b5eeb63b96092e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.7984189723, "max_line_length": 213, "alphanum_fraction": 0.6381073617, "include": true, "reason": "import numpy,import scipy", "num_tokens": 12516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19277782022841533}}
{"text": "from scipy.interpolate import interp1d\nimport os\nfrom astropy.io import fits\nimport astropy.units as u\nimport h5py\nimport numpy as np\nfrom astropy.constants import h, c\n\n__all__ = ['Spectrum1D', 'ObservationArchive', 'nirspec_pixel_wavelengths',\n           'Simulation']\n\nbg_path = os.path.join(os.path.dirname(__file__), os.pardir, 'data', 'etc',\n                       'image_detector.fits')\n\nwl_path = os.path.join(os.path.dirname(__file__), os.pardir, 'data', 'etc',\n                       'lineplot_wave_pix.fits')\n\noutputs_dir_path = os.path.join(os.path.dirname(__file__), os.pardir, 'data',\n                                'outputs')\n\nJWST_aperture_area = 25 * u.m**2\n\n\ndef nirspec_pixel_wavelengths():\n    return fits.getdata(wl_path)['WAVELENGTH'] * u.um\n\n\nclass Spectrum1D(object):\n    def __init__(self, wavelength, flux, error=None, header=None, t_eff=None):\n        self.wavelength = wavelength\n        self.flux = flux\n        self.error = error\n        self.header = header\n        self.t_eff = t_eff\n\n    def plot(self, ax=None, **kwargs):\n        import matplotlib.pyplot as plt\n        if ax is None:\n            ax = plt.gca()\n\n        ax.plot(self.wavelength, self.flux, **kwargs)\n\n        return ax\n\n    @u.quantity_input(new_wavelengths=u.m)\n    def interp_flux(self, new_wavelengths):\n        f = interp1d(self.wavelength.value, self.flux, kind='linear',\n                     bounds_error=False, fill_value=0)\n        interped_fluxes = f(new_wavelengths)\n\n        if hasattr(self.flux, 'unit') and self.flux.unit is not None:\n            return interped_fluxes * self.flux.unit\n        return interped_fluxes\n\n    def __add__(self, other_spectrum):\n\n        if not hasattr(other_spectrum, 'wavelength'):\n            raise NotImplementedError()\n\n        interp_flux = (np.interp(other_spectrum.wavelength.value,\n                                 self.wavelength.value, self.flux.value) *\n                       self.flux.unit)\n\n        return Spectrum1D(other_spectrum.wavelength,\n                          interp_flux + other_spectrum.flux,\n                          header=self.header)\n\n    def __rmul__(self, multiplier):\n        if not np.isscalar(multiplier):\n            raise NotImplementedError()\n\n        return Spectrum1D(self.wavelength, multiplier * self.flux,\n                          header=self.header)\n\n    def n_photons(self, wavelengths, exp_time, J):\n        \"\"\"\n        Estimate the number of photons received from a target with J magnitude\n        ``J`` over exposure time ``exp_time``.\n\n        Parameters\n        ----------\n        wavelengths : `~astropy.units.Quantity`\n            Wavelengths to test\n        exp_time : `~astropy.units.Quantity`\n            Exposure time\n        J : float\n            J-band magnitude of the target\n\n        Returns\n        -------\n        fluxes : `~numpy.ndarray`\n            Counts that reach the telescope at each wavelength\n        \"\"\"\n        if not hasattr(self.flux, 'unit'):\n            raise NotImplementedError(\"Flux must have units\")\n\n        interped_fluxes = self.interp_flux(wavelengths)\n\n        delta_lambda = np.nanmedian(np.diff(wavelengths))\n        n_photons_template = (interped_fluxes * wavelengths / h / c *\n                              JWST_aperture_area * delta_lambda *\n                              exp_time).decompose().value\n\n        relative_target_flux = 10**(0.4 * (float(self.header['J']) - J))\n\n        return relative_target_flux * n_photons_template\n\n\nclass ObservationArchive(object):\n    def __init__(self, fname, mode='r', outputs_dir=None):\n\n        if outputs_dir is None:\n            outputs_dir = outputs_dir_path\n\n        self.path = os.path.join(outputs_dir, fname + '.hdf5')\n        self.target_name = fname\n        self.archive = None\n        self.mode = mode\n\n    def __enter__(self):\n        self.archive = h5py.File(self.path, self.mode)\n\n        planets = [i for i in list('bcdefgh') if i in self.archive]\n\n        for planet in planets:\n            simulations = []\n            for iteration in self.archive[planet]:\n                attrs = dict(self.archive[planet][iteration].attrs)\n                simulations.append(Simulation(self.archive[planet][iteration],\n                                              attrs=attrs,\n                                              path=\"/{0}/{1}/\".format(planet,\n                                                                      iteration)))\n            setattr(self, planet, simulations)\n\n        return self\n\n    def __exit__(self, *args):\n        self.archive.close()\n\n\nclass Simulation(object):\n    def __init__(self, observation, attrs=None, path=None):\n        self.observation = observation\n        self.attrs = attrs\n        self.path = path\n\n    @property\n    def times(self):\n        return self.observation['times'][:]\n\n    @property\n    def areas(self):\n        return self.observation['spotted_area'][:]\n\n    @property\n    def spitzer_var(self):\n        return self.observation['spitzer_var'][:]\n\n    @property\n    def flares(self):\n        return self.observation['flares'][:]\n\n    @property\n    def fluxes(self):\n        return self.observation['fluxes'][:]\n\n    @property\n    def spectra(self):\n        return self.observation['spectra'][:]\n\n    @property\n    def samples_depth(self):\n        return self.observation['samples/depth'][:]\n\n    @property\n    def samples_t0(self):\n        return self.observation['samples/t0'][:]\n\n    @property\n    def samples_amp(self):\n        return self.observation['samples/amp'][:]\n\n    @property\n    def samples_log_S0(self):\n        return self.observation['samples/log_S0'][:]\n\n    @property\n    def samples_log_omega0(self):\n        return self.observation['samples/log_omega0'][:]\n\n\n    @property\n    def samples_median(self):\n        samples = (self.samples_log_S0, self.samples_log_omega0,\n                   self.samples_amp, self.samples_depth, self.samples_t0)\n        return np.array([np.median(s) for s in samples])\n\n    def plot(self):\n        wl = nirspec_pixel_wavelengths()\n\n        fig, ax = plt.subplots(2, 5, figsize=(14, 6))\n        ax[0, 0].plot(self.times, self.areas)\n        ax[0, 0].set(xlabel='Time', ylabel='Spotted area')\n\n        ax[0, 1].plot(self.times, self.fluxes)\n        ax[0, 1].set(xlabel='Time', ylabel='Stellar flux')\n\n        monochromatic_flares = np.sum(self.flares, axis=1)\n        monochromatic_flares /= np.median(monochromatic_flares)\n        ax[0, 2].plot(self.times, monochromatic_flares)\n        ax[0, 2].set(xlabel='Time', ylabel='Flare flux')\n\n        ax[0, 3].plot(self.times, self.spitzer_var)\n        ax[0, 3].set(xlabel='Time', ylabel='Spitzer var.')\n\n        ax[0, 4].plot(self.times, self.transit)\n        ax[0, 4].set(xlabel='Time', ylabel='Transit')\n\n        ax[1, 0].imshow(self.spectra, extent=[0.6, 5.3, 0, self.times.ptp()])\n        ax[1, 0].set(title='Spectrophotometry', aspect=3/(self.times.ptp()),\n                     xlabel='Wavelength [$\\mu$m]', ylabel='Time [d]')\n\n        short_bin = np.sum(self.spectra[:, :100], axis=1)\n        mid_bin = np.sum(self.spectra[:, 100:200], axis=1)\n        long_bin = np.sum(self.spectra[:, 200:], axis=1)\n        ax[1, 1].plot(self.times, long_bin/long_bin.max(), ',', color='C0',\n                      label=r'{0:.2f}-{1:.2f} $\\mu$m'\n                      .format(wl[0].value, wl[100].value))\n        ax[1, 2].plot(self.times, mid_bin/mid_bin.max(), ',', color='C2',\n                      label=r'{0:.2f}-{1:.2f} $\\mu$m'\n                      .format(wl[100].value, wl[200].value))\n        ax[1, 3].plot(self.times, short_bin/short_bin.max(), ',', color='r',\n                      label=r'{0:.2f}-{1:.2f} $\\mu$m'\n                      .format(wl[200].value, wl[-1].value))\n\n        ax[1, 4].plot(self.times, np.sum(self.spectra, axis=1), ',')\n        ax[1, 4].set(xlabel='Time', ylabel='NIRSpec counts',\n                     title='Band-integrated')\n\n        for axis in [ax[1, 1], ax[1, 2], ax[1, 3]]:\n            axis.get_shared_y_axes().join(axis, ax[1, 1])\n            axis.legend()\n            axis.set_xlabel('Time')\n            axis.set_ylabel('Flux')\n\n        fig.tight_layout()\n\n        return fig, ax", "meta": {"hexsha": "6adbbd1f41e4f1f1c82268f5a25e9262b22dc991", "size": 8148, "ext": "py", "lang": "Python", "max_stars_repo_path": "libra/spectra/spectrum.py", "max_stars_repo_name": "jlustigy/libra", "max_stars_repo_head_hexsha": "ed260e95394f79f9b2aba3287689addc886f6972", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libra/spectra/spectrum.py", "max_issues_repo_name": "jlustigy/libra", "max_issues_repo_head_hexsha": "ed260e95394f79f9b2aba3287689addc886f6972", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libra/spectra/spectrum.py", "max_forks_repo_name": "jlustigy/libra", "max_forks_repo_head_hexsha": "ed260e95394f79f9b2aba3287689addc886f6972", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8548387097, "max_line_length": 82, "alphanum_fraction": 0.5751104566, "include": true, "reason": "import numpy,from scipy,import astropy,from astropy", "num_tokens": 2004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.29746994883293104, "lm_q1q2_score": 0.19270050274827819}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nAdobe Wide Gamut RGB Colourspace\n================================\n\nDefines the *Adobe Wide Gamut RGB* colourspace:\n\n-   :attr:`colour.models.RGB_COLOURSPACE_ADOBE_WIDE_GAMUT_RGB`.\n\nReferences\n----------\n-   :cite:`Wikipedia2004c` : Wikipedia. (2004). Wide-gamut RGB color space.\n    Retrieved April 13, 2014, from\n    http://en.wikipedia.org/wiki/Wide-gamut_RGB_color_space\n\"\"\"\n\nimport numpy as np\nfrom functools import partial\n\nfrom colour.colorimetry import CCS_ILLUMINANTS\nfrom colour.models.rgb import (\n    RGB_Colourspace,\n    gamma_function,\n    normalised_primary_matrix,\n)\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2021 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-developers@colour-science.org'\n__status__ = 'Production'\n\n__all__ = [\n    'PRIMARIES_ADOBE_WIDE_GAMUT_RGB',\n    'WHITEPOINT_NAME_ADOBE_WIDE_GAMUT_RGB',\n    'CCS_WHITEPOINT_ADOBE_WIDE_GAMUT_RGB',\n    'MATRIX_ADOBE_WIDE_GAMUT_RGB_TO_XYZ',\n    'MATRIX_XYZ_TO_ADOBE_WIDE_GAMUT_RGB',\n    'RGB_COLOURSPACE_ADOBE_WIDE_GAMUT_RGB',\n]\n\nPRIMARIES_ADOBE_WIDE_GAMUT_RGB = np.array([\n    [0.7347, 0.2653],\n    [0.1152, 0.8264],\n    [0.1566, 0.0177],\n])\n\"\"\"\n*Adobe Wide Gamut RGB* colourspace primaries.\n\nPRIMARIES_ADOBE_WIDE_GAMUT_RGB : ndarray, (3, 2)\n\"\"\"\n\nWHITEPOINT_NAME_ADOBE_WIDE_GAMUT_RGB = 'D50'\n\"\"\"\n*Adobe Wide Gamut RGB* colourspace whitepoint name.\n\nWHITEPOINT_NAME_ADOBE_WIDE_GAMUT_RGB : str\n\"\"\"\n\nCCS_WHITEPOINT_ADOBE_WIDE_GAMUT_RGB = (\n    CCS_ILLUMINANTS['CIE 1931 2 Degree Standard Observer'][\n        WHITEPOINT_NAME_ADOBE_WIDE_GAMUT_RGB])\n\"\"\"\n*Adobe Wide Gamut RGB* colourspace whitepoint chromaticity coordinates.\n\nCCS_WHITEPOINT_ADOBE_WIDE_GAMUT_RGB : ndarray\n\"\"\"\n\nMATRIX_ADOBE_WIDE_GAMUT_RGB_TO_XYZ = normalised_primary_matrix(\n    PRIMARIES_ADOBE_WIDE_GAMUT_RGB, CCS_WHITEPOINT_ADOBE_WIDE_GAMUT_RGB)\n\"\"\"\n*Adobe Wide Gamut RGB* colourspace to *CIE XYZ* tristimulus values matrix.\n\nMATRIX_ADOBE_WIDE_GAMUT_RGB_TO_XYZ : array_like, (3, 3)\n\"\"\"\n\nMATRIX_XYZ_TO_ADOBE_WIDE_GAMUT_RGB = np.linalg.inv(\n    MATRIX_ADOBE_WIDE_GAMUT_RGB_TO_XYZ)\n\"\"\"\n*CIE XYZ* tristimulus values to *Adobe Wide Gamut RGB* colourspace matrix.\n\nMATRIX_XYZ_TO_ADOBE_WIDE_GAMUT_RGB : array_like, (3, 3)\n\"\"\"\n\nRGB_COLOURSPACE_ADOBE_WIDE_GAMUT_RGB = RGB_Colourspace(\n    'Adobe Wide Gamut RGB',\n    PRIMARIES_ADOBE_WIDE_GAMUT_RGB,\n    CCS_WHITEPOINT_ADOBE_WIDE_GAMUT_RGB,\n    WHITEPOINT_NAME_ADOBE_WIDE_GAMUT_RGB,\n    MATRIX_ADOBE_WIDE_GAMUT_RGB_TO_XYZ,\n    MATRIX_XYZ_TO_ADOBE_WIDE_GAMUT_RGB,\n    partial(gamma_function, exponent=1 / (563 / 256)),\n    partial(gamma_function, exponent=563 / 256),\n)\nRGB_COLOURSPACE_ADOBE_WIDE_GAMUT_RGB.__doc__ = \"\"\"\n*Adobe Wide Gamut RGB* colourspace.\n\nReferences\n----------\n:cite:`Wikipedia2004c`\n\nRGB_COLOURSPACE_ADOBE_WIDE_GAMUT_RGB : RGB_Colourspace\n\"\"\"\n", "meta": {"hexsha": "7304ccdb71326949e74b5810383605443565c183", "size": 2904, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/models/rgb/datasets/adobe_wide_gamut_rgb.py", "max_stars_repo_name": "JGoldstone/colour", "max_stars_repo_head_hexsha": "6829b363d5f0682bff0f4826995e7ceac189ff28", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "colour/models/rgb/datasets/adobe_wide_gamut_rgb.py", "max_issues_repo_name": "JGoldstone/colour", "max_issues_repo_head_hexsha": "6829b363d5f0682bff0f4826995e7ceac189ff28", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/models/rgb/datasets/adobe_wide_gamut_rgb.py", "max_forks_repo_name": "JGoldstone/colour", "max_forks_repo_head_hexsha": "6829b363d5f0682bff0f4826995e7ceac189ff28", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6571428571, "max_line_length": 78, "alphanum_fraction": 0.7620523416, "include": true, "reason": "import numpy", "num_tokens": 923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.2974699363766585, "lm_q1q2_score": 0.192700494679127}}
{"text": "# -*- coding: utf-8 -*-\n\nfrom __future__ import division, print_function\n\n__all__ = [\"Vetter\"]\n\nimport os\nimport h5py\nimport transit\nimport numpy as np\nfrom scipy.optimize import minimize\nfrom scipy.signal import lombscargle\n\nfrom .pipeline import Pipeline\n\n\ndef _nll_transit(p, system, lcs):\n    system.set_vector(p)\n\n    ll = 0.0\n    for lc in lcs:\n        mod = 1e3*(system.light_curve(lc.time, texp=lc.texp)-1.0)\n        r = mod - lc.flux\n        ll += lc.lnlike_eval(r)\n    return -ll\n\n\ndef _nll_and_grad_transit(p, system, lcs):\n    system.set_vector(p)\n\n    ll = 0.0\n    ll_grad = np.zeros_like(p)\n    for lc in lcs:\n        mod, grad = system.light_curve_gradient(lc.time, texp=lc.texp)\n        r = 1e3 * (mod - 1.0) - lc.flux\n        if np.any(~np.isfinite(r)):\n            assert 0\n        grad *= 1e3\n        a, b = lc.grad_lnlike_eval(r, grad)\n        ll += a\n        ll_grad += b\n    return -ll, ll_grad\n\n\ndef _ln_evidence_basic(lcs):\n    ll = sum(lc.lnlike_eval(lc.flux) for lc in lcs)\n    return ll, ll\n\n\ndef _ln_evidence_outlier(lcs, period, duration, t0):\n    hp = 0.5 * period\n    hd = 0.5 * duration\n\n    lnlike = 0.0\n    norm = 0.0\n    depths = np.empty(len(lcs))\n    ivars = np.empty(len(lcs))\n    for i, lc in enumerate(lcs):\n        r = lc.flux - lc.predict()\n        m = np.fabs((lc.time - t0 + hp) % period - hp) < hd\n        if not np.any(m):\n            lnlike += lc.ll0\n            continue\n        tloc = lc.time[m][np.argmin(r[m])]\n\n        def model(t):\n            mod = np.zeros_like(t)\n            mod[t == tloc] = -1.0\n            return mod\n\n        l0, depths[i], ivars[i] = lc.lnlike(model)\n        lnlike += lc.ll0\n        if ivars[i] > 0.0:\n            lnlike += l0\n            norm += 0.5 * (np.log(2*np.pi) - np.log(ivars[i]))\n\n    return lnlike, lnlike + norm\n\n\ndef _ln_evidence_box0(lcs, period, duration, t0):\n    def model(t, hp=0.5*period, hd=0.5*duration):\n        mod = np.zeros_like(t)\n        mod[np.fabs((t - t0 + hp) % period - hp) < hd] = -1.0\n        return mod\n\n    # Compute the evidence.\n    lnlike = 0.0\n    depths = np.empty(len(lcs))\n    ivars = np.empty(len(lcs))\n    for i, lc in enumerate(lcs):\n        l0, depths[i], ivars[i] = lc.lnlike(model)\n        lnlike += lc.ll0\n        if ivars[i] > 0.0:\n            lnlike += l0\n\n    m = ivars > 0.0\n    depths = depths[m]\n    ivars = ivars[m]\n\n    depth = np.sum(ivars * depths) / np.sum(ivars)\n    ivar = np.sum(ivars)\n\n    lnlike -= 0.5 * np.sum(depths**2 * ivars)\n    lnlike += 0.5 * depth**2 * ivar\n    lnlike += 0.5 * np.sum(np.log(ivars)) - 0.5*len(depths)*np.log(2*np.pi)\n\n    return lnlike, lnlike - 0.5 * np.log(ivar) + 0.5 * np.log(2*np.pi)\n\n\ndef _ln_evidence_box(lcs, period, duration, t0, eps=1.123e-2):\n    lnlike, f0 = _ln_evidence_box0(lcs, period, duration, t0)\n    lnd2fdx2 = 0.0\n\n    _, fp = _ln_evidence_box0(lcs, period + eps, duration, t0)\n    _, fm = _ln_evidence_box0(lcs, period - eps, duration, t0)\n    lnd2fdx2 += np.log(2*f0 - fp - fm) - 2 * np.log(eps) - np.log(2*np.pi)\n\n    _, fp = _ln_evidence_box0(lcs, period, duration + eps, t0)\n    _, fm = _ln_evidence_box0(lcs, period, duration - eps, t0)\n    lnd2fdx2 += np.log(2*f0 - fp - fm) - 2 * np.log(eps) - np.log(2*np.pi)\n\n    _, fp = _ln_evidence_box0(lcs, period, duration, t0 + eps)\n    _, fm = _ln_evidence_box0(lcs, period, duration, t0 - eps)\n    lnd2fdx2 += np.log(2*f0 - fp - fm) - 2 * np.log(eps) - np.log(2*np.pi)\n\n    if not np.isfinite(lnd2fdx2):\n        return lnlike, f0\n\n    return lnlike, f0 - 0.5 * lnd2fdx2\n\n\ndef _ln_evidence_vee0(lcs, period, duration, t0):\n    def model(t, hp=0.5*period, hd=0.5*duration):\n        mod = np.zeros_like(t)\n        dt = (t - t0 + hp) % period - hp\n        m = np.fabs(dt) < hd\n        mod[m] = np.abs(dt[m]) / hd - 1.0\n        return mod\n\n    # Compute the evidence.\n    lnlike = 0.0\n    depths = np.empty(len(lcs))\n    ivars = np.empty(len(lcs))\n    for i, lc in enumerate(lcs):\n        l0, depths[i], ivars[i] = lc.lnlike(model)\n        lnlike += lc.ll0\n        if ivars[i] > 0.0:\n            lnlike += l0\n\n    m = ivars > 0.0\n    depths = depths[m]\n    ivars = ivars[m]\n\n    depth = np.sum(ivars * depths) / np.sum(ivars)\n    ivar = np.sum(ivars)\n\n    lnlike -= 0.5 * np.sum(depths**2 * ivars)\n    lnlike += 0.5 * depth**2 * ivar\n    lnlike += 0.5 * np.sum(np.log(ivars)) - 0.5*len(depths)*np.log(2*np.pi)\n\n    return lnlike, lnlike - 0.5 * np.log(ivar) + 0.5 * np.log(2*np.pi)\n\n\ndef _ln_evidence_vee(lcs, period, duration, t0, eps=1.123e-2):\n    lnlike, f0 = _ln_evidence_vee0(lcs, period, duration, t0)\n    lnd2fdx2 = 0.0\n\n    _, fp = _ln_evidence_vee0(lcs, period + eps, duration, t0)\n    _, fm = _ln_evidence_vee0(lcs, period - eps, duration, t0)\n    lnd2fdx2 += np.log(2*f0 - fp - fm) - 2 * np.log(eps) - np.log(2*np.pi)\n\n    _, fp = _ln_evidence_vee0(lcs, period, duration + eps, t0)\n    _, fm = _ln_evidence_vee0(lcs, period, duration - eps, t0)\n    lnd2fdx2 += np.log(2*f0 - fp - fm) - 2 * np.log(eps) - np.log(2*np.pi)\n\n    _, fp = _ln_evidence_vee0(lcs, period, duration, t0 + eps)\n    _, fm = _ln_evidence_vee0(lcs, period, duration, t0 - eps)\n    lnd2fdx2 += np.log(2*f0 - fp - fm) - 2 * np.log(eps) - np.log(2*np.pi)\n\n    if not np.isfinite(lnd2fdx2):\n        return lnlike, f0\n\n    return lnlike, f0 - 0.5 * lnd2fdx2\n\n\ndef _ln_evidence_transit(p, *args):\n    h = 1.1234e-3\n    x0 = np.array(p)\n    lnd2fdx2 = np.empty_like(x0)\n    f0 = _nll_transit(x0, *args)\n    for i in range(len(x0)):\n        x0[i] += h\n        fp = _nll_transit(x0, *args)\n        x0[i] -= 2*h\n        fm = _nll_transit(x0, *args)\n        x0[i] += h\n        d = fp - 2*f0 + fm\n        if d <= 0.0:\n            lnd2fdx2[i] = np.inf\n        else:\n            lnd2fdx2[i] = np.log(fp - 2*f0 + fm)\n    lnd2fdx2 -= 2*np.log(h)\n    lnZ = -f0 - 0.5 * np.sum(lnd2fdx2) + 0.5 * len(x0) * np.log(2*np.pi)\n    return -f0, lnZ\n\n\ndef _ln_evidence_period(lcs):\n    if not hasattr(lcs[0], \"detrend_flux\"):\n        return -np.inf, -np.inf\n    x = np.concatenate([lc.time for lc in lcs])\n    y = np.concatenate([lc.detrend_flux for lc in lcs])\n    ivar = np.concatenate([1./lc.detrend_ferr**2 for lc in lcs])\n    delta = np.max(x) - np.min(x)\n    f = 2*np.pi*np.arange(max(2./24., 10./delta), 1.0 / 0.025, 0.1 / delta)\n    p = lombscargle(x, y, f)\n    omega = f[np.argmax(p)]\n    AT = np.vstack([np.sin(omega*x), np.cos(omega*x), np.ones(len(x))])\n    A = AT.T\n    cov = np.dot(AT, A * ivar[:, None])\n    w = np.linalg.solve(cov, np.dot(AT, y * ivar))\n\n    def model(t):\n        A = np.vstack([np.sin(omega*t), np.cos(omega*t)]).T\n        return np.dot(A, w[:2])\n\n    # Compute the evidence.\n    lnlike = 0.0\n    depths = np.empty(len(lcs))\n    ivars = np.empty(len(lcs))\n    for i, lc in enumerate(lcs):\n        l0, depths[i], ivars[i] = lc.lnlike(model)\n        lnlike += lc.ll0\n        if ivars[i] > 0.0:\n            lnlike += l0\n\n    m = ivars > 0.0\n    depths = depths[m]\n    ivars = ivars[m]\n\n    depth = np.sum(ivars * depths) / np.sum(ivars)\n    ivar = np.sum(ivars)\n\n    lnlike -= 0.5 * np.sum(depths**2 * ivars)\n    lnlike += 0.5 * depth**2 * ivar\n    lnlike += 0.5 * np.sum(np.log(ivars)) - 0.5*len(depths)*np.log(2*np.pi)\n\n    return (lnlike, lnlike - 0.5 * np.log(ivar) + 0.5 * np.log(2*np.pi),\n            2*np.pi/omega)\n\n\nclass Vetter(Pipeline):\n\n    cache_ext = \".h5\"\n    query_parameters = dict(\n        t0_rng=(0.2, False),\n        period_rng=(0.1, False),\n    )\n\n    def get_result(self, query, parent_response):\n        # Get the results from the pipeline so far.\n        peaks = parent_response.peaks\n        lcs = parent_response.model_light_curves\n\n        # Save the initial flux values.\n        flux0 = [np.array(lc.flux) for lc in lcs]\n\n        # Loop over the peaks and compute the evidence for each one.\n        for peak in peaks:\n            # Set up the Keplerian fit.\n            system = transit.SimpleSystem(\n                period=peak[\"period\"], t0=peak[\"t0\"],\n                ror=np.sqrt(1e-3*peak[\"depth\"]),\n                duration=peak[\"duration\"],\n                impact=0.5,\n            )\n\n            # Fit the transit model.\n            p0 = system.get_vector()\n            ln_period_rng = np.log((\n                peak[\"period\"] - query[\"period_rng\"],\n                peak[\"period\"] + query[\"period_rng\"],\n            ))\n            t0_rng = (\n                peak[\"t0\"] - query[\"t0_rng\"],\n                peak[\"t0\"] + query[\"t0_rng\"],\n            )\n            bounds = [(None, None), ln_period_rng, t0_rng,\n                      (None, None), (None, None),\n                      (-10.0, 10.0), (-10.0, 10.0)]\n            result = minimize(_nll_and_grad_transit, p0, method=\"L-BFGS-B\",\n                              jac=True,\n                              args=(system, lcs),\n                              bounds=bounds)\n            system.set_vector(result.x)\n\n            # Compute the transit evidence.\n            x = result.x\n            peak[\"transit_q1\"] = system.q1\n            peak[\"transit_q2\"] = system.q2\n            peak[\"transit_period\"] = system.period\n            peak[\"transit_ror\"] = system.ror\n            peak[\"transit_duration\"] = system.duration\n            peak[\"transit_t0\"] = system.t0\n            peak[\"transit_b\"] = system.impact\n            peak[\"lnlike_transit\"], peak[\"lnZ_transit\"] = \\\n                _ln_evidence_transit(x, system, lcs)\n\n            # Compute the evidence for the competing models.\n            peak[\"lnlike_none\"], peak[\"lnZ_none\"] = _ln_evidence_basic(lcs)\n            peak[\"lnlike_box\"], peak[\"lnZ_box\"] = _ln_evidence_box(\n                lcs, peak[\"transit_period\"], peak[\"transit_duration\"],\n                peak[\"transit_t0\"])\n            peak[\"lnlike_vee\"], peak[\"lnZ_vee\"] = _ln_evidence_vee(\n                lcs, peak[\"transit_period\"], peak[\"transit_duration\"],\n                peak[\"transit_t0\"])\n            peak[\"lnlike_outlier\"], peak[\"lnZ_outlier\"] = _ln_evidence_outlier(\n                lcs, peak[\"transit_period\"], peak[\"transit_duration\"],\n                peak[\"transit_t0\"])\n\n            peak[\"lnlike_period\"], peak[\"lnZ_period\"], peak[\"osc_period\"] = \\\n                _ln_evidence_period(lcs)\n\n            # Subtract the best fit transit model.\n            for lc in lcs:\n                mod = 1e3*(system.light_curve(lc.time, texp=lc.texp)-1.0)\n                lc.flux -= mod\n\n        # Return the fluxes to their original values.\n        for lc, f in zip(lcs, flux0):\n            lc.flux[:] = f[:]\n\n        return dict(\n            peaks=peaks,\n        )\n\n    def save_to_cache(self, fn, response):\n        try:\n            os.makedirs(os.path.dirname(fn))\n        except os.error:\n            pass\n\n        # Parse the peaks into a structured array.\n        peaks = response[\"peaks\"]\n        if len(peaks):\n            dtype = [(k, np.float64) for k in sorted(peaks[0].keys())]\n            peaks = [tuple(peak[k] for k, _ in dtype) for peak in peaks]\n            peaks = np.array(peaks, dtype=dtype)\n\n        with h5py.File(fn, \"w\") as f:\n            f.create_dataset(\"peaks\", data=peaks, compression=\"gzip\")\n\n    def load_from_cache(self, fn):\n        if os.path.exists(fn):\n            with h5py.File(fn, \"r\") as f:\n                try:\n                    peaks = [dict((k, peak[k]) for k in peak.dtype.names)\n                             for peak in f[\"peaks\"]]\n                    return dict(\n                        peaks=peaks,\n                    )\n                except KeyError:\n                    pass\n        return None\n", "meta": {"hexsha": "3744a500d9052c107388c75e05a95e1eebab0634", "size": 11467, "ext": "py", "lang": "Python", "max_stars_repo_path": "ketu/vetter.py", "max_stars_repo_name": "dfm/turnstile", "max_stars_repo_head_hexsha": "13a9a3b489b458396a6ad1e8a2d1e89a0dd6312d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-02-19T09:13:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-25T10:50:38.000Z", "max_issues_repo_path": "ketu/vetter.py", "max_issues_repo_name": "dfm/turnstile", "max_issues_repo_head_hexsha": "13a9a3b489b458396a6ad1e8a2d1e89a0dd6312d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-07-10T19:50:31.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-11T03:51:15.000Z", "max_forks_repo_path": "ketu/vetter.py", "max_forks_repo_name": "dfm/turnstile", "max_forks_repo_head_hexsha": "13a9a3b489b458396a6ad1e8a2d1e89a0dd6312d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2015-04-20T06:42:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-25T03:04:45.000Z", "avg_line_length": 31.5027472527, "max_line_length": 79, "alphanum_fraction": 0.5386762013, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.19268159618448505}}
{"text": "\"\"\"A 1D simple velocity gradient model to calculate lines with the LVG method\n\nOriginal IDL model by Kees Dullemond, Python translation by Attila Juhasz\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nimport traceback\ntry:\n    import numpy as np\nexcept ImportError:\n    np = None\n    print(' Numpy cannot be imported ')\n    print(' To use the python module of RADMC-3D you need to install Numpy')\n    print(traceback.format_exc())\n\nfrom .. natconst import *\n\n\ndef getModelDesc():\n    \"\"\"Provides a brief description of the model\n    \"\"\"\n\n    return \"Example model: A 1D simple velocity gradient model to calculate lines with the LVG method\"\n           \n\ndef getDefaultParams():\n    \"\"\"Provides default parameter values \n\n    Returns a list whose elements are also lists with three elements:\n    1) parameter name, 2) parameter value, 3) parameter description\n    All three elements should be strings. The string of the parameter\n    value will be directly written out to the parameter file if requested,\n    and the value of the string expression will be evaluated and be put\n    to radmc3dData.ppar. The third element contains the description of the\n    parameter which will be written in the comment field of the line when\n    a parameter file is written. \n    \"\"\"\n\n    defpar = [['mstar', '1.0*ms', 'Mass of the star(s)'],\n              ['pstar', '[0., 0., 0.]', 'Position of the star(s) (cartesian coordinates)'],\n              ['rstar', '1.0*rs', 'Radius of the star(s)'],\n              ['tstar', '1.0*ts', 'Effective temperature of the star(s)'],\n              ['crd_sys', \"'car'\", 'Coordinate system used (car/sph)'],\n              ['nx', '10', 'Number of grid points in the first dimension'],\n              ['ny', '1', 'Number of grid points in the second dimension'],\n              ['nz', '1', 'Number of grid points in the third dimension'],\n              ['xbound', '[-1000.0*au, 1000.0*au]', 'Boundaries for the x-grid'],\n              ['ybound', '[-1000.0*au/nx, 1000.0*au/nx]', 'Boundaries for the y-grid'],\n              ['zbound', '[-1000.0*au/nx, 1000.0*au/nx]', 'Boundaries for the z-grid'],\n              ['nw', '[20,100,30]', 'Number of points in the wavelength grid'],\n              ['wbound', '[0.1, 7., 25., 1e4]', 'Boundaries for the wavelength grid'],\n              ['dustkappa_ext', \"['silicate']\", 'Dust opacity file name extension'],\n              ['nphot', '1000000', 'Number of photons in the thermal Monte Carlo simulation'],\n              ['lines_mode', '3', ''],\n              ['scattering_mode_max', '1', '0 - no scattering, 1 - isotropic scattering, 2 - anizotropic scattering'],\n              ['gasspec_mol_name', \"['co']\", ''],\n              ['gasspec_mol_abun', '[1e-4]', ''],\n              ['gasspec_mol_dbase_type', \"['leiden']\", ''],\n              ['gasspec_colpart_name', \"['h2']\", ''],\n              ['gasspec_colpart_abun', '[1e0]', ''],\n              ['gasspec_vturb', '1e5', 'Microturbulent linewidth'],\n              ['abun_h2', '0.5', ''],\n              ['abun_he', '0.1', ''],\n              ['nh2', '1e5', ''],\n              ['temp0', '30.', ''],\n              ['tdust0', '30.', ''],\n              ['dusttogas', '1e-2', ''],\n              ['dvdau', '1e-2*1e5', '']]\n\n    return defpar\n\n\ndef getGasTemperature(grid=None, ppar=None):\n    \"\"\"Calculates the gas temperature\n    \n    Parameters\n    ----------\n    grid : radmc3dGrid\n            An instance of the radmc3dGrid class containing the spatial and wavelength grid\n    \n    ppar : dictionary\n            Dictionary containing all parameters of the model \n    \n    Returns\n    -------\n    Returns the gas temperature in K\n    \"\"\"\n\n    tgas = np.zeros([grid.nx, grid.ny, grid.nz], dtype=np.float64) + ppar['temp0']\n    return tgas\n\n\ndef getDustTemperature(grid=None, ppar=None):\n    \"\"\"Calculates/sets the dust temperature\n    \n    Parameters\n    ----------\n    grid : radmc3dGrid\n            An instance of the radmc3dGrid class containing the spatial and wavelength grid\n    \n    ppar : dictionary\n            Dictionary containing all parameters of the model \n    \n    Returns\n    -------\n    Returns the dust temperature in K\n    \n    \"\"\"\n\n    tdust = np.zeros([grid.nx, grid.ny, grid.nz, 1], dtype=np.float64) + ppar['tdust0']\n    return tdust\n\n\ndef getGasAbundance(grid=None, ppar=None, ispec=''):\n    \"\"\"Calculates/sets the molecular abundance of species ispec \n    The number density of a molecule is rhogas * abun \n   \n    Parameters\n    ----------\n    grid  : radmc3dGrid\n            An instance of the radmc3dGrid class containing the spatial and wavelength grid\n\n    ppar  : dictionary\n            Dictionary containing all parameters of the model \n\n    ispec : str\n            The name of the gas species whose abundance should be calculated\n\n    Returns\n    -------\n    Returns the abundance as an ndarray\n    \"\"\"\n    # Mass of gas per H2-molecule\n    # mgas    = mp*(2.0*ppar['abun_h2']+4*ppar['abun_he'])/ppar['abun_h2']\n\n    if ispec in ppar['gasspec_mol_name']:\n        gasabun = np.zeros([grid.nx, grid.ny, grid.nz], dtype=np.float64) \n        ind = ppar['gasspec_mol_name'].index(ispec)\n        gasabun[:, :, :] = ppar['gasspec_mol_abun'][ind]  # /mgas\n \n    elif ispec in ppar['gasspec_colpart_name']:\n        gasabun = np.zeros([grid.nx, grid.ny, grid.nz], dtype=np.float64) \n        ind = ppar['gasspec_colpart_name'].index(ispec)\n        gasabun[:, :, :] = ppar['gasspec_colpart_abun'][ind]  # /mgas\n    else:\n        raise ValueError(' The abundance of \"'+ispec+'\" is not specified in the parameter file')\n   \n    return gasabun\n\n\ndef getGasDensity(grid=None, ppar=None):\n    \"\"\"Calculates the total gas density distribution \n    \n    Parameters\n    ----------\n    grid : radmc3dGrid\n            An instance of the radmc3dGrid class containing the spatial and wavelength grid\n    \n    ppar : dictionary\n            Dictionary containing all parameters of the model \n    \n    Returns\n    -------\n    Returns the gas volume density in g/cm^3\n    \"\"\"\n    # Mass of gas per H2-molecule\n    mgas = mp*(2.0*ppar['abun_h2']+4*ppar['abun_he'])/ppar['abun_h2']\n    rhogas = np.zeros([grid.nx, grid.ny, grid.nz], dtype=np.float64) + ppar['nh2'] * mgas\n    return rhogas\n\n\ndef getDustDensity(grid=None, ppar=None):\n    \"\"\"Calculates the dust density distribution \n    \n    Parameters\n    ----------\n    grid : radmc3dGrid\n            An instance of the radmc3dGrid class containing the spatial and wavelength grid\n    \n    ppar : dictionary\n            Dictionary containing all parameters of the model \n    \n    Returns\n    -------\n    Returns the dust volume density in g/cm^3\n    \"\"\"\n    rhogas = getGasDensity(grid=grid, ppar=ppar)\n    rhodust = np.zeros([grid.nx, grid.ny, grid.nz, 1], dtype=np.float64) \n    rhodust[:, :, :, 0] = rhogas * ppar['dusttogas']\n    return rhodust\n\n\ndef getVTurb(grid=None, ppar=None):\n    \"\"\"Calculates/sets the turbulent velocity field\n    \n    Parameters\n    ----------\n    grid : radmc3dGrid\n            An instance of the radmc3dGrid class containing the spatial and wavelength grid\n    \n    ppar : dictionary\n            Dictionary containing all parameters of the model \n    \n    Returns\n    -------\n    Returns the turbulent velocity in cm/s\n    \"\"\"\n    vturb = np.zeros([grid.nx, grid.ny, grid.nz], dtype=np.float64) + ppar['gasspec_vturb']\n    return vturb\n\n\ndef getVelocity(grid=None, ppar=None):\n    \"\"\"Calculates/sets the gas velocity field\n    \n    Parameters\n    ----------\n    grid : radmc3dGrid\n            An instance of the radmc3dGrid class containing the spatial and wavelength grid\n    \n    ppar : dictionary\n            Dictionary containing all parameters of the model \n    \n    Returns\n    -------\n    Returns the turbulent velocity in cm/s\n    \"\"\"\n    vel = np.zeros([grid.nx, grid.ny, grid.nz, 3], dtype=np.float64)\n    for ix in range(grid.nx):\n        vel[ix, :, :, 0] = ppar['dvdau']*grid.x[ix]/au\n    \n    return vel\n", "meta": {"hexsha": "3551fbb82c6c6cdf6b9dde1e75e61ed443d6b119", "size": 7931, "ext": "py", "lang": "Python", "max_stars_repo_path": "radmc-3d/version_0.41/python/radmc3dPy/models/lines_nlte_lvg_1d_1.py", "max_stars_repo_name": "dlmatra/miao", "max_stars_repo_head_hexsha": "71799811b21a4249754390a8ec00972723edab99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-23T00:03:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-23T00:03:40.000Z", "max_issues_repo_path": "radmc-3d/version_0.41/python/radmc3dPy/models/lines_nlte_lvg_1d_1.py", "max_issues_repo_name": "dlmatra/miao", "max_issues_repo_head_hexsha": "71799811b21a4249754390a8ec00972723edab99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-05-26T12:54:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-27T10:58:48.000Z", "max_forks_repo_path": "radmc-3d/version_0.41/python/radmc3dPy/models/lines_nlte_lvg_1d_1.py", "max_forks_repo_name": "dlmatra/miao", "max_forks_repo_head_hexsha": "71799811b21a4249754390a8ec00972723edab99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-23T14:09:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T14:09:52.000Z", "avg_line_length": 34.1853448276, "max_line_length": 118, "alphanum_fraction": 0.6038330601, "include": true, "reason": "import numpy", "num_tokens": 2092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.19268159618448505}}
{"text": "#! /usr/bin/env python\n\nimport numpy as np\n\ndef framewiseEval(resTracks, groundTruthTracks):\n    GTTracks = groundTruthTracks\n    # aligning the tracks:\n    Tref = GTTracks.shape[0]\n    refTimes = GTTracks[:,0]\n    estTimes = resTracks[:,0]\n    reference = np.zeros([Tref, GTTracks.shape[1]-1])\n    reference[:,:] = GTTracks[:,1:]\n    print reference.shape\n    \n    nTracks = resTracks.shape[1] - 1\n    newResTracks = np.zeros([Tref, nTracks])\n    for i in range(Tref):\n        indexMin = np.argmin(np.abs(refTimes[i] - estTimes))\n        newResTracks[i,:] = resTracks[indexMin,1:]\n    \n    resTracks0 = np.copy(newResTracks)\n    GTTracks0 = np.copy(reference)\n    \n    # Consider negative frequency values as 0:\n    newResTracks[newResTracks < 0] = 0\n    # Setting same number of tracks:\n    ## nTracks = np.maximum(nTracks, reference.shape[1])\n\n    print newResTracks.shape\n    \n    # setting the boundaries for tolerance of error:\n    reference_low = 0.97 * reference\n    reference_hig = 1.03 * reference\n    \n    # values for score computation\n    TP = np.zeros(Tref) # True Positives\n    FN = np.zeros(Tref) # False Negatives\n    TN = np.zeros(Tref) # True Negatives\n    \n    for n in range(Tref):\n        for track in range(nTracks):\n            for track2 in range(reference.shape[1]):\n                if reference_low[n, track2] < newResTracks[n, track] and \\\n                       newResTracks[n, track] < reference_hig[n, track2] and \\\n                       reference[n, track2] > 0:\n                    TP[n] += 1\n                    # inhibiting the TP match\n                    newResTracks[n, track] = -1\n                    reference_low[n, track2] = -1\n                    reference_hig[n, track2] = -1\n                    reference[n, track2] = -1\n    \n    FP = np.sum(newResTracks>0) # True Negatives\n    # True Negatives - not sure if this quantity is right\n    TN = np.minimum(np.sum(reference<=0,\n                           axis=1),\n                    np.sum(np.array(newResTracks==0) + \\\n                           np.array(newResTracks<-1),\n                           axis=1))\n    Ncorr = np.copy(TP) # number of correctly estimated pitches for each frames (MIREX 2007 criteria)\n    TP = np.sum(TP) # total TP\n    FN = np.maximum(0, np.sum(np.array(newResTracks==0) + \\\n                              np.array(newResTracks<-1),\n                              axis=1) -\\\n                    np.sum(reference<=0,\n                           axis=1)) # False Negatives, per frame\n    TN = np.sum(TN) # total TN\n    FN = np.sum(FN) # total FN\n\n    # dictionary containing all of the desired values\n    resStruct = {}\n    resStruct['TP'] = TP\n    resStruct['TN'] = TN\n    resStruct['FP'] = FP\n    resStruct['FN'] = FN\n    resStruct['Precision'] = 100.0 * TP / np.double(TP+FP)\n    resStruct['Recall'] = 100.0 * TP / np.double(np.sum(GTTracks0>0))# np.sum(reference!=0, dtype=np.double)\n    resStruct['FMeasure'] = 2.0 * resStruct['Precision'] * resStruct['Recall'] / (resStruct['Precision'] + resStruct['Recall'])\n    resStruct['Accuracy'] = 100.0 * (TP + TN) / np.double(TP + TN + FN) # recall, including silence in the classes to retrieve. \n    \n    # Additional MIREX 2007 evaluation criteria:\n    Nref = np.sum(GTTracks0>0, axis=1, dtype=np.double)\n    Nsys = np.sum(resTracks0>0, axis=1, dtype=np.double)\n    \n    resStruct['AccuracyMirex07'] = 100.0 * TP / np.double(TP+FN+FP)\n    \n    NrefTotal = np.sum(Nref, dtype=np.double)\n    resStruct['Mirex07Etot'] = 100.0 * \\\n                               np.sum(np.maximum(Nref,Nsys) - \\\n                                      Ncorr) / \\\n                                      NrefTotal\n    resStruct['Mirex07Esub'] = 100.0 * \\\n                               np.sum(np.minimum(Nref,Nsys) - \\\n                                      Ncorr) / \\\n                                      NrefTotal\n    resStruct['Mirex07Emis'] = 100.0 * \\\n                               np.sum(np.maximum(0, Nref-Nsys)) / \\\n                                      NrefTotal\n    resStruct['Mirex07Efal'] = 100.0 * \\\n                               np.sum(np.maximum(0, Nsys-Nref)) / \\\n                                      NrefTotal\n    \n    return resStruct, GTTracks0, resTracks0\n\ndef framewiseMono(resTracks, groundTruthTracks):\n    GTTracks = groundTruthTracks\n    # aligning the tracks:\n    Tref = GTTracks.shape[0]\n    refTimes = GTTracks[:,0]\n    estTimes = resTracks[:,0]\n    reference = GTTracks[:,1]\n    \n    newResTracks = np.zeros(Tref)\n    for i in range(Tref):\n        indexMin = np.argmin(np.abs(refTimes[i] - estTimes))\n        newResTracks[i] = resTracks[indexMin,1]\n    \n    resTracks0 = np.copy(newResTracks)\n    GTTracks0 = np.copy(reference)\n    \n    # Consider negative frequency values as 0:\n    newResTracks[newResTracks < 0] = 0\n    \n    errorInSemitone = np.zeros(Tref)\n    for n in range(Tref):\n        if reference[n] > 0 and newResTracks[n] != 0:\n            errorInSemitone[n] = 12.0 * np.log2(np.abs(newResTracks[n])/np.double(reference[n]))\n        \n    return errorInSemitone\n\ndef compareFilesByName(fileGT, fileRes):\n    GTTracks = np.loadtxt(fileGT)\n    resTracks = np.loadtxt(fileRes)\n    \n    errorInSemitone = framewiseMono(resTracks, GTTracks)\n    resStruct, GTTracks0, resTracks0 = framewiseEval(resTracks, GTTracks)\n    \n    return errorInSemitone, resStruct, GTTracks0, resTracks0\n", "meta": {"hexsha": "ddbb9de3b552aa18e7fd85bb2c38789761547cf6", "size": 5360, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/separateLeadStereo/pitchEval.py", "max_stars_repo_name": "dkdfirefly/speaker_project", "max_stars_repo_head_hexsha": "1c129f3f4d664e6526ab5be35932c27e8b90b07d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-01-16T11:27:28.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-16T11:27:28.000Z", "max_issues_repo_path": "code/separateLeadStereo/pitchEval.py", "max_issues_repo_name": "dkdfirefly/speaker_project", "max_issues_repo_head_hexsha": "1c129f3f4d664e6526ab5be35932c27e8b90b07d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/separateLeadStereo/pitchEval.py", "max_forks_repo_name": "dkdfirefly/speaker_project", "max_forks_repo_head_hexsha": "1c129f3f4d664e6526ab5be35932c27e8b90b07d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5611510791, "max_line_length": 128, "alphanum_fraction": 0.5619402985, "include": true, "reason": "import numpy", "num_tokens": 1428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.1926815886632039}}
{"text": "\"\"\"\nCopyright (c) 2021, Electric Power Research Institute\n\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification,\n are permitted provided that the following conditions are met:\n\n     * Redistributions of source code must retain the above copyright notice,\n       this list of conditions and the following disclaimer.\n     * Redistributions in binary form must reproduce the above copyright notice,\n       this list of conditions and the following disclaimer in the documentation\n       and/or other materials provided with the distribution.\n     * Neither the name of DER-VET nor the names of its contributors\n       may be used to endorse or promote products derived from this software\n       without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\"\"\"\nStorage\n\nThis Python class contains methods and attributes specific for technology analysis within StorageVet.\n\"\"\"\nimport logging\nimport cvxpy as cvx\nimport numpy as np\nimport pandas as pd\nfrom storagevet.Technology.DistributedEnergyResource import DER\nfrom dervet.MicrogridDER.DERExtension import DERExtension\nfrom dervet.MicrogridDER.ContinuousSizing import ContinuousSizing\nfrom storagevet.ErrorHandling import *\n\n\nclass ElectricVehicle1(DER, ContinuousSizing, DERExtension):\n    \"\"\" A general template for storage object\n\n    We define \"storage\" as anything that can affect the quantity of load/power being delivered or used. Specific\n    types of storage are subclasses. The storage subclass should be called. The storage class should never\n    be called directly.\n\n    \"\"\"\n\n    def __init__(self, params):\n        \"\"\" Initialize all technology with the following attributes.\n\n        Args:\n            params (dict): Dict of parameters\n        \"\"\"\n        TellUser.debug(f\"Initializing ElectricVehicle1\")\n        # create generic technology object\n        DER.__init__(self, params)\n        ContinuousSizing.__init__(self, params)\n        DERExtension.__init__(self, params)\n\n        self.technology_type = 'Electric Vehicle'\n        self.tag = 'ElectricVehicle1'\n\n        self.ene_target = params['ene_target']\n        self.ch_max_rated = params['ch_max_rated']\n        self.ch_min_rated = params['ch_min_rated']\n\n        self.plugin_time = params['plugin_time']\n        self.plugout_time = params['plugout_time']\n\n        self.capital_cost_function = params['ccost']\n\n        self.fixed_om = params['fixed_om']\n        self.incl_binary = False  # params['binary'] #TODO\n\n        self.variable_names = {'ene', 'ch', 'uene', 'uch', 'on_c'}\n\n        # initialize any attributes you want to set and use later\n        self.plugin_times_index = None\n        self.plugout_times_index = None\n        self.unplugged_index = None\n\n    # def charge_capacity(self):\n    #     \"\"\"\n\n    #     Returns: the maximum charge that can be attained\n\n    #     \"\"\"\n    #     return self.ch_max_rated\n\n    def initialize_variables(self, size):\n        \"\"\" Adds optimization variables to dictionary\n\n        Variables added: (with self.unique_ess_id as a prefix to these)\n            ene (Variable): A cvxpy variable for Energy collected at the end of the time step (kWh)\n            ch (Variable): A cvxpy variable for Charge Power, kW during the previous time step (kW)\n            on_c (Variable/Parameter): A cvxpy variable/parameter to flag for charging in previous interval (bool)\n\n        Notes:\n            CVX Parameters turn into Variable when the condition to include them is active\n\n        Args:\n            size (Int): Length of optimization variables to create\n\n        \"\"\"\n        self.variables_dict = {\n            'ene': cvx.Variable(shape=size, name=self.name + '-ene'),\n            'ch': cvx.Variable(shape=size, name=self.name + '-ch'),\n            'uene': cvx.Variable(shape=size, name=self.name + '-uene'),  # TODO you can switch to parameter, where value == np.zeros(size)  -HN\n            'uch': cvx.Variable(shape=size, name=self.name + '-uch'),  # TODO you can switch to parameter, where value == np.zeros(size)  -HN\n            'on_c': cvx.Parameter(shape=size, name=self.name + '-on_c', value=np.ones(size)),\n\n        }\n\n        if self.incl_binary:\n            self.variable_names.update(['on_c'])\n            self.variables_dict.update({'on_c': cvx.Variable(shape=size, boolean=True, name=self.name + '-on_c')})\n\n    def get_state_of_energy(self, mask):\n        \"\"\"\n        Args:\n            mask (DataFrame): A boolean array that is true for indices corresponding to time_series data included\n                in the subs data set\n\n        Returns: the state of energy as a function of time for the\n\n        \"\"\"\n        return self.variables_dict['ene']\n\n    def get_charge(self, mask):\n        \"\"\"\n        Args:\n            mask (DataFrame): A boolean array that is true for indices corresponding to time_series data included\n                in the subs data set\n\n        Returns: the charge as a function of time for the\n\n        \"\"\"\n        return self.variables_dict['ch']\n\n    def get_capex(self, **kwargs):\n        \"\"\" Returns the capex of a given technology\n        \"\"\"\n        return self.capital_cost_function\n\n    def get_charge_up_schedule(self, mask):\n        \"\"\" the amount of charging power in the up direction (supplying power up into the grid) that\n        this DER can schedule to reserve\n\n        Args:\n            mask (DataFrame): A boolean array that is true for indices corresponding to time_series data included\n                    in the subs data set\n\n        Returns: CVXPY parameter/variable\n\n        \"\"\"\n        return self.variables_dict['ch'] - self.ch_min_rated\n\n    def get_charge_down_schedule(self, mask):\n        \"\"\" the amount of charging power in the up direction (pulling power down from the grid) that\n        this DER can schedule to reserve\n\n        Args:\n            mask (DataFrame): A boolean array that is true for indices corresponding to time_series data included\n                    in the subs data set\n\n        Returns: CVXPY parameter/variable\n\n        \"\"\"\n        return self.ch_max_rated - self.variables_dict['ch']\n\n    def get_delta_uenegy(self, mask):\n        \"\"\" the amount of energy, from the current SOE level the DER's state of energy changes\n        from subtimestep energy shifting\n\n        Returns: the energy throughput in kWh for this technology\n\n        \"\"\"\n        return self.variables_dict['uene']\n\n    def get_uenergy_increase(self, mask):\n        \"\"\" the amount of energy in a timestep that is provided to the distribution grid\n\n        Returns: the energy throughput in kWh for this technology\n\n        \"\"\"\n        return self.variables_dict['uch'] * self.dt\n\n    def get_active_times(self, mask):\n        \"\"\"\n\n        Args:\n            mask:\n\n        Returns:\n\n        \"\"\"\n        compute_plugin_index = pd.DataFrame(index=mask.index)\n        compute_plugin_index['plugin'] = compute_plugin_index.index.hour == self.plugin_time\n        compute_plugin_index['plugout'] = compute_plugin_index.index.hour == self.plugout_time\n        compute_plugin_index['unplugged'] = False\n\n        if self.plugin_time < self.plugout_time:  # plugin time and plugout time must be different\n            compute_plugin_index.loc[\n                (compute_plugin_index.index.hour >= self.plugin_time) * (compute_plugin_index.index.hour < self.plugout_time), 'unplugged'] = True\n        elif self.plugin_time > self.plugout_time:\n            compute_plugin_index.loc[\n                (compute_plugin_index.index.hour >= self.plugin_time) | (compute_plugin_index.index.hour < self.plugout_time), 'unplugged'] = True\n\n        self.plugout_times_index = compute_plugin_index['plugout']\n        self.plugin_times_index = compute_plugin_index['plugin']\n        self.unplugged_index = compute_plugin_index['unplugged']\n\n    def constraints(self, mask):\n        \"\"\"Default build constraint list method. Used by services that do not have constraints.\n\n        Args:\n            mask (DataFrame): A boolean array that is true for indices corresponding to time_series data included\n                    in the subs data set\n\n        Returns:\n            A list of constraints that corresponds the EV requirement to collect the required energy to operate. It also allows\n            flexibility to provide other grid services\n        \"\"\"\n\n        constraint_list = []\n        self.get_active_times(mask.loc[mask])  # constructing the array that indicates whether the ev is plugged or not\n\n        # print(self.plugin_times_index.iloc[0:24])\n        # print(self.plugout_times_index.iloc[0:24])\n        # print(self.unplugged_index.iloc[0:24])\n        # print('Ene target :' + str(self.ene_target))\n        # print('Charging max :' + str(self.ch_max_rated))\n        # print('Charging min :' + str(self.ch_min_rated))\n\n        # optimization variables\n        ene = self.variables_dict['ene']\n        ch = self.variables_dict['ch']\n        uene = self.variables_dict['uene']\n        uch = self.variables_dict['uch']\n        on_c = self.variables_dict['on_c']\n\n        # collected energy at start time is zero for all start times\n        constraint_list += [cvx.Zero(ene[self.plugin_times_index])]\n\n        # energy evolution generally for every time step\n\n        numeric_unplugged_index = pd.Series(range(len(self.unplugged_index)), index=self.unplugged_index.index).loc[self.unplugged_index]\n        ene_ini_window = 0\n\n        if numeric_unplugged_index.iloc[0] == 0:  # energy evolution for the EV, only during plugged times\n            constraint_list += [cvx.Zero(ene[numeric_unplugged_index.iloc[0]] - ene_ini_window)]\n            constraint_list += [cvx.Zero(ene[list(numeric_unplugged_index.iloc[1:])] - ene[list(numeric_unplugged_index.iloc[1:] - 1)] - (\n                        self.dt * ch[list(numeric_unplugged_index.iloc[1:] - 1)]))]  # - uene[list(numeric_unplugged_index.iloc[1:]-1)])]\n        else:\n            constraint_list += [cvx.Zero(ene[list(numeric_unplugged_index)] - ene[list(numeric_unplugged_index - 1)] - (\n                        self.dt * ch[list(numeric_unplugged_index - 1)]))]  # - uene[list(numeric_unplugged_index-1)])]\n        # constraint_list += [cvx.Zero(ene[1:] - ene[:-1]  - ( self.dt * ch[:-1]) - uene[:-1])]\n\n        # energy at plugout times must be greater or equal to energy target\n\n        numeric_plugout_time_index = pd.Series(range(len(self.plugout_times_index)), index=self.plugout_times_index.index).loc[\n            self.plugout_times_index]\n\n        # the next few lines make sure that the state of energy at the end of the chargign period is equal to the target\n        if numeric_plugout_time_index[0] == 0:\n            constraint_list += [cvx.Zero(self.ene_target - ene[list(numeric_plugout_time_index.iloc[1:] - 1)] - (\n                        self.dt * ch[list(numeric_plugout_time_index.iloc[1:] - 1)]))]  # - uene[list(numeric_plugout_time_index.iloc[1:]-1)])]\n        else:\n            constraint_list += [cvx.Zero(self.ene_target - ene[list(numeric_plugout_time_index - 1)] - (\n                        self.dt * ch[list(numeric_plugout_time_index - 1)]))]  # - uene[list(numeric_plugout_time_index-1)])]\n\n        constraint_list += [cvx.Zero(ene[list(numeric_plugout_time_index)] - self.ene_target)]\n\n        # constraints on the ch/dis power\n\n        # make it MILP or not depending on user selection\n        if self.incl_binary:\n            constraint_list += [cvx.NonPos(ch - (on_c * self.ch_max_rated))]\n            constraint_list += [cvx.NonPos((on_c * self.ch_min_rated) - ch)]\n        else:\n            constraint_list += [cvx.NonPos(ch - self.ch_max_rated)]\n            constraint_list += [cvx.NonPos(- ch)]\n\n        # constraints to make sure that the ev does nothing when it is unplugged\n        constraint_list += [cvx.NonPos(ch[~self.unplugged_index])]\n\n        # account for -/+ sub-dt energy -- this is the change in energy that the battery experiences as a result of energy option\n        # constraint_list += [cvx.Zero(uene - (uch * self.dt))]\n        constraint_list += [cvx.Zero(uch)]  # TODO: you can set the variable to be parameters instead  -HN\n        constraint_list += [cvx.Zero(uene)]  # TODO: you can set the variable to be parameters instead  -HN\n        return constraint_list\n\n    def timeseries_report(self):\n        \"\"\" Summaries the optimization results for this DER.\n\n        Returns: A timeseries dataframe with user-friendly column headers that\n            summarize the results pertaining to this instance\n\n        \"\"\"\n        tech_id = self.unique_tech_id()\n        results = pd.DataFrame(index=self.variables_df.index)\n        solve_dispatch_opt = self.variables_df.get('ch')\n        if solve_dispatch_opt is not None:\n            results[tech_id + ' Charge (kW)'] = self.variables_df['ch']\n            results[tech_id + ' Power (kW)'] = -self.variables_df['ch']\n            results[tech_id + ' State of Energy (kWh)'] = \\\n                self.variables_df['ene']\n\n            results[tech_id + ' Energy Option (kWh)'] = \\\n                self.variables_df['uene']\n            results[tech_id + ' Charge Option (kW)'] = self.variables_df['uch']\n\n        return results\n\n    def proforma_report(self, apply_inflation_rate_func, fill_forward_func, results):\n        \"\"\" Calculates the proforma that corresponds to participation in this value stream\n\n        Args:\n            apply_inflation_rate_func:\n            fill_forward_func:\n            results (pd.DataFrame):\n\n        Returns: A DateFrame of with each year in opt_year as the index and\n            the corresponding value this stream provided.\n\n        \"\"\"\n        pro_forma = super().proforma_report(apply_inflation_rate_func, fill_forward_func, results)\n        if self.variables_df.empty:\n            return pro_forma\n        analysis_years = self.variables_df.index.year.unique()\n        om_costs = pd.DataFrame()\n        for year in analysis_years:\n            # add fixed o&m costs\n            index_yr = pd.Period(year=year, freq='y')\n            om_costs.loc[index_yr, self.fixed_column_name()] = -self.fixed_om\n        # fill forward\n        om_costs = fill_forward_func(om_costs, None)\n        # apply inflation rates\n        om_costs = apply_inflation_rate_func(om_costs, None, min(analysis_years))\n        # append will super class's proforma\n        pro_forma = pd.concat([pro_forma, om_costs], axis=1)\n        return pro_forma\n\n    def sizing_summary(self):\n        \"\"\" Creates the template for sizing df that each DER must fill to report their size.\n\n        Returns: A dictionary describe this DER's size and captial costs.\n\n        \"\"\"\n        # template = pd.DataFrame(columns=)\n        sizing_dict = {\n            'DER': np.nan,\n            'Energy Rating (kWh)': np.nan,\n            'Charge Rating (kW)': np.nan,\n            'Discharge Rating (kW)': np.nan,\n            'Round Trip Efficiency (%)': np.nan,\n            'Lower Limit on SOC (%)': np.nan,\n            'Upper Limit on SOC (%)': np.nan,\n            'Duration (hours)': np.nan,\n            'Capital Cost ($)': np.nan,\n            'Capital Cost ($/kW)': np.nan,\n            'Capital Cost ($/kWh)': np.nan,\n            'Power Capacity (kW)': np.nan,\n            'Quantity': 1,\n        }\n        return sizing_dict\n\n\nclass ElectricVehicle2(DER, ContinuousSizing, DERExtension):\n    \"\"\" A general template for storage object\n\n    We define \"storage\" as anything that can affect the quantity of load/power being delivered or used. Specific\n    types of storage are subclasses. The storage subclass should be called. The storage class should never\n    be called directly.\n\n    \"\"\"\n\n    def __init__(self, params):\n        \"\"\" Initialize all technology with the following attributes.\n\n        Args:\n            params (dict): Dict of parameters\n        \"\"\"\n        TellUser.debug(f\"Initializing ElectricVehicle2\")\n        # create generic technology object\n        DER.__init__(self, params)\n        ContinuousSizing.__init__(self, params)\n        DERExtension.__init__(self, params)\n\n        self.technology_type = 'Electric Vehicle'\n        self.tag = 'ElectricVehicle2'\n\n        # input params\n        # note: these should never be changed in simulation (i.e from degradation)\n\n        self.max_load_ctrl = params[\n                                 'max_load_ctrl'] / 100.0  # maximum amount of baseline EV load that can be shed as a percentage of the original load\n        # self.qualifying_cap = params['qualifying_cap'] #capacity that can be used for 'capacity' services (DR, RA) as a percentage of the baseline load\n        self.lost_load_cost = params['lost_load_cost']\n        self.incl_binary = params['binary']\n        self.EV_load_TS = params['EV_baseline']\n\n        self.capital_cost_function = params['ccost']\n\n        self.fixed_om = params['fixed_om']\n\n        self.variable_names = {'ch'}\n\n    def qualifying_capacity(self, event_length):\n        \"\"\" Describes how much power the DER can discharge to qualify for RA or DR. Used to determine\n        the system's qualifying commitment.\n\n        Args:\n            event_length (int): the length of the RA or DR event, this is the\n                total hours that a DER is expected to discharge for\n\n        Returns: int/float\n\n        \"\"\"\n        return 0\n\n    def initialize_variables(self, size):\n        \"\"\" Adds optimization variables to dictionary\n\n        Variables added: (with self.unique_ess_id as a prefix to these)\n            ene (Variable): A cvxpy variable for Energy collected at the end of the time step (kWh)\n            ch (Variable): A cvxpy variable for Charge Power, kW during the previous time step (kW)\n            on_c (Variable/Parameter): A cvxpy variable/parameter to flag for charging in previous interval (bool)\n\n        Notes:\n            CVX Parameters turn into Variable when the condition to include them is active\n\n        Args:\n            size (Int): Length of optimization variables to create\n\n        \"\"\"\n        self.variables_dict = {\n            'ch': cvx.Variable(shape=size, name=self.name + '-ch')\n        }\n\n        if self.incl_binary:\n            self.variable_names.update(['on_c'])\n            self.variables_dict.update({'on_c': cvx.Variable(shape=size, boolean=True, name=self.name + '-on_c')})\n\n    def get_charge(self, mask):\n        \"\"\"\n        Args:\n            mask (DataFrame): A boolean array that is true for indices corresponding to time_series data included\n                in the subs data set\n\n        Returns: the charge as a function of time for the\n\n        \"\"\"\n        return self.variables_dict['ch']\n\n    def get_capex(self, **kwargs):\n        \"\"\" Returns the capex of a given technology\n        \"\"\"\n        return self.capital_cost_function\n\n    def get_charge_up_schedule(self, mask):\n        \"\"\" the amount of charging power in the up direction (supplying power up into the grid) that\n        this DER can schedule to reserve\n\n        Args:\n            mask (DataFrame): A boolean array that is true for indices corresponding to time_series data included\n                    in the subs data set\n\n        Returns: CVXPY parameter/variable\n\n\n\n        \"\"\"\n        return self.variables_dict['ch'] - (1 - self.max_load_ctrl) * self.EV_load_TS[mask]\n\n    def get_charge_down_schedule(self, mask):\n        \"\"\" the amount of charging power in the up direction (pulling power down from the grid) that\n        this DER can schedule to reserve\n\n        Args:\n            mask (DataFrame): A boolean array that is true for indices corresponding to time_series data included\n                    in the subs data set\n\n        Returns: CVXPY parameter/variable\n\n        \"\"\"\n        return -self.variables_dict['ch'] + self.EV_load_TS[mask]\n\n    def objective_function(self, mask, annuity_scalar=1):\n        \"\"\" Generates the objective function related to a technology. Default includes O&M which can be 0\n\n        Args:\n            mask (Series): Series of booleans used, the same length as case.power_kw\n            annuity_scalar (float): a scalar value to be multiplied by any yearly cost or benefit that helps capture the cost/benefit over\n                    the entire project lifetime (only to be set iff sizing, else annuity_scalar should not affect the aobject function)\n\n        Returns:\n            self.costs (Dict): Dict of objective costs\n        \"\"\"\n\n        # create objective expression for variable om based on discharge activity\n        ch = self.variables_dict['ch']\n        costs = {\n            self.name + ' fixed_om': self.fixed_om * annuity_scalar,\n            self.name + ' lost_load_cost': cvx.sum(self.EV_load_TS[mask].values - ch) * self.lost_load_cost  # added to account for lost load\n\n        }\n        # add startup objective costs\n\n        return costs\n\n    def constraints(self, mask):\n        \"\"\"Default build constraint list method. Used by services that do not have constraints.\n\n        Args:\n            mask (DataFrame): A boolean array that is true for indices corresponding to time_series data included\n                    in the subs data set\n\n        Returns:\n            A list of constraints that corresponds the EV requirement to collect the required energy to operate. It also allows\n            flexibility to provide other grid services\n        \"\"\"\n        constraint_list = []\n\n        # optimization variables\n\n        ch = self.variables_dict['ch']\n        # uch = self.variables_dict['uch']\n\n        # constraints on the ch/dis power\n        constraint_list += [cvx.NonPos(ch - self.EV_load_TS[mask].values)]\n        constraint_list += [cvx.NonPos((1 - self.max_load_ctrl) * self.EV_load_TS[mask].values - ch)]\n\n        # the constraint below limits energy throughput and total discharge to less than or equal to\n        # (number of cycles * energy capacity) per day, for technology warranty purposes\n        # this constraint only applies when optimization window is equal to or greater than 24 hours\n\n        return constraint_list\n\n    def timeseries_report(self):\n        \"\"\" Summaries the optimization results for this DER.\n\n        Returns: A timeseries dataframe with user-friendly column headers that\n            summarize the results pertaining to this instance\n\n        \"\"\"\n        tech_id = self.unique_tech_id()\n        results = pd.DataFrame(index=self.variables_df.index)\n        solve_dispatch_opt = self.variables_df.get('ch')\n        if solve_dispatch_opt is not None:\n            results[tech_id + ' EV Fleet Baseline Load'] = self.EV_load_TS\n            results[tech_id + ' Charge (kW)'] = self.variables_df['ch']\n            results[tech_id + ' Power (kW)'] = -self.variables_df['ch']\n\n        return results\n\n    def proforma_report(self, apply_inflation_rate_func, fill_forward_func, results):\n        \"\"\" Calculates the proforma that corresponds to participation in this value stream\n\n        Args:\n            apply_inflation_rate_func:\n            fill_forward_func:\n            results (pd.DataFrame):\n\n        Returns: A DateFrame of with each year in opt_year as the index and\n            the corresponding value this stream provided.\n\n        \"\"\"\n        pro_forma = super().proforma_report(apply_inflation_rate_func, fill_forward_func, results)\n        if self.variables_df.empty:\n            return pro_forma\n        analysis_years = self.variables_df.index.year.unique()\n        om_costs = pd.DataFrame()\n        for year in analysis_years:\n            # add fixed o&m costs\n            index_yr = pd.Period(year=year, freq='y')\n            om_costs.loc[index_yr, self.fixed_column_name()] = -self.fixed_om\n        # fill forward\n        om_costs = fill_forward_func(om_costs, None)\n        # apply inflation rates\n        om_costs = apply_inflation_rate_func(om_costs, None, min(analysis_years))\n        # append will super class's proforma\n        pro_forma = pd.concat([pro_forma, om_costs], axis=1)\n        return pro_forma\n\n    def sizing_summary(self):\n        \"\"\" Creates the template for sizing df that each DER must fill to report their size.\n\n        Returns: A dictionary describe this DER's size and captial costs.\n\n        \"\"\"\n        # template = pd.DataFrame(columns=)\n        sizing_dict = {\n            'DER': np.nan,\n            'Energy Rating (kWh)': np.nan,\n            'Charge Rating (kW)': np.nan,\n            'Discharge Rating (kW)': np.nan,\n            'Round Trip Efficiency (%)': np.nan,\n            'Lower Limit on SOC (%)': np.nan,\n            'Upper Limit on SOC (%)': np.nan,\n            'Duration (hours)': np.nan,\n            'Capital Cost ($)': np.nan,\n            'Capital Cost ($/kW)': np.nan,\n            'Capital Cost ($/kWh)': np.nan,\n            'Power Capacity (kW)': np.nan,\n            'Quantity': 1,\n        }\n        return sizing_dict\n", "meta": {"hexsha": "77952c43c72e19c901f03da6d081012a86f70d85", "size": 25446, "ext": "py", "lang": "Python", "max_stars_repo_path": "dervet/MicrogridDER/ElectricVehicles.py", "max_stars_repo_name": "epri-dev/dervet", "max_stars_repo_head_hexsha": "2d74d8b3f00fd0ebcf562900c0cb2bff0e995b42", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-04-27T18:14:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T18:56:59.000Z", "max_issues_repo_path": "dervet/MicrogridDER/ElectricVehicles.py", "max_issues_repo_name": "epri-dev/dervet", "max_issues_repo_head_hexsha": "2d74d8b3f00fd0ebcf562900c0cb2bff0e995b42", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-21T13:47:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-21T13:47:41.000Z", "max_forks_repo_path": "dervet/MicrogridDER/ElectricVehicles.py", "max_forks_repo_name": "epri-dev/dervet", "max_forks_repo_head_hexsha": "2d74d8b3f00fd0ebcf562900c0cb2bff0e995b42", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-24T14:14:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-23T19:17:58.000Z", "avg_line_length": 41.3756097561, "max_line_length": 153, "alphanum_fraction": 0.6467421206, "include": true, "reason": "import numpy,import cvxpy", "num_tokens": 5565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.19268157606943334}}
{"text": "\"\"\" \nTensorflow SMPL implementation as batch.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport pickle as pickle\n\nimport tensorflow as tf\nfrom .batch_lbs import batch_rodrigues, batch_global_rigid_transformation\n\n\n# There are chumpy variables so convert them to numpy.\ndef undo_chumpy(x):\n    return x if isinstance(x, np.ndarray) else x.r\n\n\nclass SMPL(object):\n    def __init__(self, pkl_path, joint_type='cocoplus', dtype=tf.float64):\n        \"\"\"\n        pkl_path is the path to a SMPL model\n        \"\"\"\n        # -- Load SMPL params --\n        with open(pkl_path, 'rb') as f:\n            dd = pickle.load(f, encoding=\"latin1\")\n        self.dtype = dtype\n        # Mean template vertices\n        self.v_template = tf.Variable(undo_chumpy(dd['v_template']),\n                                      name='v_template',\n                                      dtype=self.dtype,\n                                      trainable=False)\n        self.f = dd['f']\n\n        # Size of mesh [Number of vertices, 3]\n        self.size = [self.v_template.shape[0].value, 3]\n        self.num_betas = dd['shapedirs'].shape[-1]\n        self.num_verts = dd['shapedirs']\n        self.num_joints = dd['J'].shape[0]\n\n        # Shape blend shape basis: num_verts x 3 x num_betas\n        # reshaped to 3*num_verts x num_betas, transposed to num_betas x 3*num_verts\n        shapedir = np.reshape(undo_chumpy(dd['shapedirs']), [-1, self.num_betas]).T\n        self.shapedirs = tf.Variable(shapedir, name='shapedirs', dtype=self.dtype, trainable=False)\n\n        # Regressor for joint locations given shape - num_verts x num_joints\n        self.J_regressor = tf.Variable(dd['J_regressor'].T.todense(),\n                                       name=\"J_regressor\",\n                                       dtype=self.dtype,\n                                       trainable=False)\n\n        # Pose blend shape basis: num_verts x 3 x 9*num_joints, reshaped to 3*num_verts x 9*num_joints\n        num_pose_basis = dd['posedirs'].shape[-1]\n        posedirs = np.reshape(undo_chumpy(dd['posedirs']), [-1, num_pose_basis]).T\n        self.posedirs = tf.Variable(posedirs, name='posedirs', dtype=self.dtype, trainable=False)\n\n        # indices of parents for each joints\n        self.parents = dd['kintree_table'][0].astype(np.int32)\n\n        # LBS weights\n        self.weights = tf.Variable(undo_chumpy(dd['weights']),\n                                   name='lbs_weights',\n                                   dtype=self.dtype,\n                                   trainable=False)\n\n\n    def __call__(self, trans, beta, theta, name=''):\n        \"\"\"\n        Obtain SMPL with shape (beta) & pose (theta) inputs.\n        Theta includes the global rotation.\n        Args:\n          beta: N x num_betas\n          theta: N x 3*num_joints (with 3-D axis-angle rep)\n\n        Updates:\n        self.J_transformed: N x num_joints x 3 joint location after shaping\n                 & posing with beta and theta\n\n        Returns:\n          - Verts: N x num_verts x 3\n        \"\"\"\n\n        with tf.name_scope(name, \"smpl_main\", [beta, theta]):\n            num_batch = beta.shape[0].value\n\n            # 1. Add shape blend shapes\n            # (N x num_betas) x (num_betas x 3*num_verts) = N x num_verts x 3\n            v_shaped = tf.reshape(tf.matmul(beta, self.shapedirs, name='shape_bs'),\n                                  [-1, self.size[0], self.size[1]]) + self.v_template\n\n            # 2. Infer shape-dependent joint locations.\n            Jx = tf.matmul(v_shaped[:, :, 0], self.J_regressor)\n            Jy = tf.matmul(v_shaped[:, :, 1], self.J_regressor)\n            Jz = tf.matmul(v_shaped[:, :, 2], self.J_regressor)\n            J = tf.stack([Jx, Jy, Jz], axis=2)\n\n            # 3. Add pose blend shapes\n            # N x num_joints x 3 x 3\n            Rs = tf.reshape(batch_rodrigues(tf.reshape(theta, [-1, 3])), [-1, self.num_joints, 3, 3])\n            with tf.name_scope(\"lrotmin\"):\n                # Ignore global rotation.\n                pose_feature = tf.reshape(Rs[:, 1:, :, :] - tf.eye(3, dtype=self.dtype), [-1, 9*(self.num_joints-1)])\n\n            # (N x 9*(num_joints-1))) x (9*(num_joints-1), 3*num_verts) -> N x num_verts x 3\n            v_posed = tf.reshape(tf.matmul(pose_feature, self.posedirs),\n                                 [-1, self.size[0], self.size[1]]) + v_shaped\n\n            #4. Get the global joint location\n            self.J_transformed, A = batch_global_rigid_transformation(Rs, J, self.parents)\n\n            # 5. Do skinning:\n            # W is N x num_verts x num_joints\n            W = tf.reshape(tf.tile(self.weights, [num_batch, 1]), [num_batch, -1, self.num_joints])\n\n            # (N x num_verts x num_joints) x (N x num_joints x 16)\n            T = tf.reshape(\n                tf.matmul(W, tf.reshape(A, [num_batch, self.num_joints, 16])),\n                [num_batch, -1, 4, 4])\n            v_posed_homo = tf.concat([v_posed, tf.ones([num_batch, v_posed.shape[1], 1], dtype=self.dtype)], 2)\n            v_homo = tf.matmul(T, tf.expand_dims(v_posed_homo, -1))\n\n            return tf.add(v_homo[:, :, :3, 0], trans)\n", "meta": {"hexsha": "16c02cdd511bb9be499cfff3afcf56a804170218", "size": 5189, "ext": "py", "lang": "Python", "max_stars_repo_path": "tf_smpl/batch_smpl.py", "max_stars_repo_name": "samiurprapon/TF_FLAME", "max_stars_repo_head_hexsha": "23dddfd97d1ecd957495d7ab66f82a32dd980161", "max_stars_repo_licenses": ["AAL"], "max_stars_count": 300, "max_stars_repo_stars_event_min_datetime": "2019-05-25T01:12:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T13:29:02.000Z", "max_issues_repo_path": "tf_smpl/batch_smpl.py", "max_issues_repo_name": "samiurprapon/TF_FLAME", "max_issues_repo_head_hexsha": "23dddfd97d1ecd957495d7ab66f82a32dd980161", "max_issues_repo_licenses": ["AAL"], "max_issues_count": 56, "max_issues_repo_issues_event_min_datetime": "2019-06-17T05:06:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T23:30:09.000Z", "max_forks_repo_path": "tf_smpl/batch_smpl.py", "max_forks_repo_name": "samiurprapon/TF_FLAME", "max_forks_repo_head_hexsha": "23dddfd97d1ecd957495d7ab66f82a32dd980161", "max_forks_repo_licenses": ["AAL"], "max_forks_count": 66, "max_forks_repo_forks_event_min_datetime": "2019-06-12T19:52:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T11:36:30.000Z", "avg_line_length": 41.512, "max_line_length": 117, "alphanum_fraction": 0.5642705724, "include": true, "reason": "import numpy", "num_tokens": 1324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.19265415051877124}}
{"text": "import os\nfrom typing import List, Dict\nimport numpy as np\nimport h5py as h5\nfrom scipy.sparse import csr_matrix\nfrom mpi4py import MPI\n\nfrom .__init__ import (\n\tpprint,\n\tcomm,\n\trank,\n\tnproc,\n)\nfrom .conversion import (\n\tcomoving_density,\n\tcomoving_length,\n\tcomoving_velocity,\n\tcomoving_mass,\n\tcomoving_kinetic_energy,\n\tcomoving_momentum,\n\tcomoving_ang_momentum,\n\tdensity_units,\n\tvelocity_units,\n\tlength_units,\n\tmass_units,\n\tmomentum_units,\n\tenergy_units,\n)\n\ndef split(nfiles):\n    nfiles=int(nfiles)\n    nf=int(nfiles/nproc)\n    rmd=nfiles % nproc\n    st=rank*nf\n    fh=(rank+1)*nf\n    if rank < rmd:\n        st+=rank\n        fh+=(rank+1)\n    else:\n        st+=rmd\n        fh+=rmd\n    return st,fh\n\ndef commune(data):\n    tmp=np.zeros(nproc,dtype=np.int)\n    tmp[rank]=len(data)\n    cnts=np.zeros(nproc,dtype=np.int)\n    comm.Allreduce([tmp,MPI.INT],[cnts,MPI.INT],op=MPI.SUM)\n    del tmp\n    dspl=np.zeros(nproc,dtype=np.int)\n    i=0\n    for j in range(nproc):\n        dspl[j]=i\n        i+=cnts[j]\n    rslt=np.zeros(i,dtype=data.dtype)\n    comm.Allgatherv([data,cnts[rank]],[rslt,cnts,dspl,MPI._typedict[data.dtype.char]])\n    del data,cnts,dspl\n    return rslt\n\ndef compute_M(data):\n    cols = np.arange(data.size)\n    return csr_matrix((cols, (data.ravel(), cols)), shape=(data.max() + 1, data.size))\n\ndef get_indices_sparse(data):\n    M = compute_M(data)\n    return [np.unravel_index(row.data, data.shape) for row in M]\n\ndef find_files(redshift: str) -> list:\n    z_value = ['z004p688', 'z004p061', 'z003p053', 'z003p078', 'z002p688', 'z002p349',\n            'z002p053', 'z001p792', 'z001p561', 'z001p354', 'z001p168', 'z001p000', 'z000p846', 'z000p706',\n            'z000p577', 'z000p457', 'z000p345', 'z000p240', 'z000p140', 'z000p046', 'z000p000']\n    z_IDNumber = ['002', '003', '004', '005', '006', '007', '008', '009', '010', '011', '012', '013',\n            '014', '015', '016', '017', '018', '019', '020', '021', '022']\n    sn = dict(zip(z_value, z_IDNumber))[redshift]\n    path='/cosma5/data/dp004/dc-hens1/macsis/macsis_gas'\n    pprint(f\"[+] Find simulation files {redshift:s}...\")\n\n    halos = [x for x in os.listdir(path) if x.startswith('halo_')]\n\tmaster_files = []\n\tfor halo in halos:\n\t\tgroups = []\n\t\tfor x in os.listdir(os.path.join(path, halo, f'data/groups_{sn}')):\n\t\t\tif x.startswith('eagle_subfind_tab'):\n\t\t\t\tcomplete_path = os.path.join(path, halo, f'data/groups_{sn}/{x}')\n\t\t\t\tgroups.append(complete_path)\n\n\t\tparticle = []\n\t\tfor x in os.listdir(os.path.join(path, halo, f'data/particledata_{sn}')):\n\t\t\tif x.startswith('eagle_subfind_particles'):\n\t\t\t\tcomplete_path = os.path.join(path, halo, f'data/particledata_{sn}/{x}')\n\t\t\t\tparticle.append(complete_path)\n\n\t\tmaster_files.append([groups[0], particle[0]])\n\n\treturn master_files\n\n\n\ndef fof_header(files: list):\n\tpprint(f\"[+] Find header information...\")\n\theader = {}\n\twith h5.File(files[0][1], 'r') as f:\n\t\theader['Hub']  = f['Header'].attrs['HubbleParam']\n\t\theader['aexp'] = f['Header'].attrs['ExpansionFactor']\n\t\theader['zred'] = f['Header'].attrs['Redshift']\n\t\theader['OmgL'] = f['Header'].attrs['OmegaLambda']\n\t\theader['OmgM'] = f['Header'].attrs['Omega0']\n\t\theader['OmgB'] = f['Header'].attrs['OmegaBaryon']\n\treturn header\n\n\n\ndef fof_groups(files: list):\n\tpprint(f\"[+] Find groups information...\")\n\tgroup_files = [pair[0] for pair in files]\n\tst, fh = split(len(group_files))\n\tMfof = np.empty(0, dtype=np.float32)\n\tM2500 = np.empty(0, dtype=np.float32)\n\tM500 = np.empty(0, dtype=np.float32)\n\tM200 = np.empty(0, dtype=np.float32)\n\tR2500 = np.empty(0, dtype=np.float32)\n\tR500 = np.empty(0, dtype=np.float32)\n\tR200 = np.empty(0, dtype=np.float32)\n\tCOP = np.empty(0, dtype=np.float32)\n\tNSUB = np.empty(0, dtype=np.int)\n\tFSID = np.empty(0, dtype=np.int)\n\tSCOP = np.empty(0, dtype=np.float32)\n\tfor x in range(st, fh, 1):\n\t\twith h5.File(group_files[x], 'r') as f:\n\t\t\tMfof = np.append(Mfof, f['FOF/GroupMass'][:])\n\t\t\tM2500 = np.append(M2500, f['FOF/Group_M_Crit2500'][:])\n\t\t\tR2500 = np.append(R2500, f['FOF/Group_R_Crit2500'][:])\n\t\t\tM500 = np.append(M500, f['FOF/Group_M_Crit500'][:])\n\t\t\tR500 = np.append(R500, f['FOF/Group_R_Crit500'][:])\n\t\t\tM200 = np.append(M200, f['FOF/Group_M_Crit200'][:])\n\t\t\tR200 = np.append(R200, f['FOF/Group_R_Crit200'][:])\n\t\t\tCOP = np.append(COP, f['FOF/GroupCentreOfPotential'][:])\n\t\t\tNSUB = np.append(NSUB, f['FOF/NumOfSubhalos'][:])\n\t\t\tFSID = np.append(FSID, f['FOF/FirstSubhaloID'][:])\n\t\t\tSCOP = np.append(SCOP, f['Subhalo/CentreOfPotential'][:])\n\n\theader = {}\n\twith h5.File(group_files[0], 'r') as f:\n\t\theader['Hub'] =  f['Header'].attrs['HubbleParam']\n\t\theader['aexp'] = f['Header'].attrs['ExpansionFactor']\n\t\theader['zred'] = f['Header'].attrs['Redshift']\n\n\t# Conversion\n\tMfof = comoving_mass(header, Mfof * 1.0e10)\n\tM2500 = comoving_mass(header, M2500 * 1.0e10)\n\tM500 = comoving_mass(header, M500 * 1.0e10)\n\tM200 = comoving_mass(header, M200 * 1.0e10)\n\tR2500 = comoving_length(header, R2500)\n\tR500 = comoving_length(header, R500)\n\tR200 = comoving_length(header, R200)\n\tCOP = comoving_length(header, COP)\n\tSCOP = comoving_length(header, SCOP)\n\n\tdata = {}\n\tdata['groupfiles'] = np.asarray(group_files)\n\tdata['particlefiles'] = np.asarray([pair[1] for pair in files])\n\tdata['Mfof'] = commune(Mfof)\n\tdata['M2500'] = commune(M2500)\n\tdata['R2500'] = commune(R2500)\n\tdata['M500'] = commune(M500)\n\tdata['R500'] = commune(R500)\n\tdata['M200'] = commune(M200)\n\tdata['R200'] = commune(R200)\n\tdata['COP']  = commune(COP.reshape(-1, 1)).reshape(-1, 3)\n\tdata['NSUB'] = commune(NSUB)\n\tdata['FSID'] = commune(FSID)\n\tdata['SCOP'] = commune(SCOP.reshape(-1, 1)).reshape(-1, 3)\n\n\treturn data\n\ndef fof_group(clusterID: int, fofgroups: Dict[str, np.ndarray] = None):\n\tpprint(f\"[+] Find group information for cluster {clusterID}\")\n\tnew_data = {}\n\tnew_data['clusterID'] = clusterID\n\tnew_data['Mfof']  = fofgroups['Mfof'][clusterID]\n\tnew_data['M2500'] = fofgroups['M2500'][clusterID]\n\tnew_data['R2500'] = fofgroups['R2500'][clusterID]\n\tnew_data['M500']  = fofgroups['M500'][clusterID]\n\tnew_data['R500']  = fofgroups['R500'][clusterID]\n\tnew_data['M200']  = fofgroups['M200'][clusterID]\n\tnew_data['R200']  = fofgroups['R200'][clusterID]\n\tnew_data['COP']   = fofgroups['COP'][clusterID]\n\tnew_data['NSUB']  = fofgroups['NSUB'][clusterID]\n\tnew_data['FSID']  = fofgroups['FSID'][clusterID]\n\tnew_data['SCOP']  = fofgroups['SCOP'][clusterID]\n\tnew_data['groupfiles']  = fofgroups['groupfiles'][clusterID]\n\tnew_data['particlefiles'] = fofgroups['particlefiles'][clusterID]\n\treturn new_data\n\n\ndef cluster_partgroupnumbers(fofgroup: Dict[str, np.ndarray] = None):\n\t\"\"\"\n\n\t:param fofgroups:\n\t:return:\n\t\"\"\"\n\tpgn = []\n\twith h5.File(fofgroup['particlefiles'], 'r') as h5file:\n\n\t\tfor pt in ['0', '1', '4']:\n\t\t\tNparticles = h5file['Header'].attrs['NumPart_ThisFile'][int(pt)]\n\t\t\tst, fh = split(Nparticles)\n\t\t\tpprint(f\"[+] Collecting particleType {pt} GroupNumber...\")\n\t\t\tgroupnumber = h5file[f'/PartType{pt}/GroupNumber'][st:fh]\n\n\t\t\t# Clip out negative values and exceeding values\n\t\t\tgroupnumber = np.clip(groupnumber, 0, 6)\n\t\t\tpprint(f\"\\t Computing CSR indexing matrix...\")\n\t\t\tgroupnumber_csrm = get_indices_sparse(groupnumber)\n\t\t\tdel groupnumber_csrm[0], groupnumber_csrm[-1]\n\t\t\tpgn.append(groupnumber_csrm)\n\t\t\tdel groupnumber\n\n\treturn pgn\n\ndef cluster_particles(fofgroup: Dict[str, np.ndarray] = None, groupNumbers: List[np.ndarray] = None):\n\t\"\"\"\n\n\t:param fofgroup:\n\t:param groupNumbers:\n\t:return:\n\t\"\"\"\n\tpprint(f\"[+] Find particle information for cluster {fofgroup['clusterID']}\")\n\tdata_out = {}\n\theader = {}\n\tpartTypes = ['0', '1', '4']\n\twith h5.File(fofgroup['particlefiles'], 'r') as h5file:\n\n\t\theader['Hub']  = h5file['Header'].attrs['HubbleParam']\n\t\theader['aexp'] = h5file['Header'].attrs['ExpansionFactor']\n\t\theader['zred'] = h5file['Header'].attrs['Redshift']\n\n\t\tfor pt in partTypes:\n\n\t\t\t# Initialise particledata arrays\n\t\t\tpgn_core = np.empty(0, dtype=np.int)\n\t\t\tsubgroup_number = np.empty(0, dtype=np.int)\n\t\t\tvelocity = np.empty(0, dtype=np.float32)\n\t\t\tcoordinates = np.empty(0, dtype=np.float32)\n\t\t\tmass = np.empty(0, dtype=np.float32)\n\t\t\ttemperature = np.empty(0, dtype=np.float32)\n\t\t\tsphdensity = np.empty(0, dtype=np.float32)\n\t\t\tsphlength = np.empty(0, dtype=np.float32)\n\n\t\t\t# Let each CPU core import a portion of the pgn data\n\t\t\tpgn = groupNumbers[partTypes.index(pt)]\n\t\t\tst, fh = split(len(pgn))\n\t\t\tpgn_core = np.append(pgn_core, pgn[st:fh])\n\t\t\tdel pgn\n\n\t\t\t# Filter particle data with collected groupNumber indexing\n\t\t\tsubgroup_number = np.append(subgroup_number, h5file[f'/PartType{pt}/SubGroupNumber'][pgn_core])\n\t\t\tvelocity        = np.append(velocity, h5file[f'/PartType{pt}/Velocity'][pgn_core])\n\t\t\tcoordinates     = np.append(coordinates, h5file[f'/PartType{pt}/Coordinates'][pgn_core])\n\t\t\tif pt == '1':\n\t\t\t\tparticle_mass_DM = h5file['Header'].attrs['MassTable'][1]\n\t\t\t\tmass = np.append(mass, np.ones(len(pgn_core), dtype=np.float32) * particle_mass_DM)\n\t\t\telse:\n\t\t\t\tmass = np.append(mass, h5file[f'/PartType{pt}/Mass'][pgn_core])\n\t\t\tif pt == '0':\n\t\t\t\ttemperature = np.append(temperature, h5file[f'/PartType{pt}/Temperature'][pgn_core])\n\t\t\t\tsphdensity  = np.append(sphdensity, h5file[f'/PartType{pt}/Density'][pgn_core])\n\t\t\t\tsphlength   = np.append(sphlength, h5file[f'/PartType{pt}/SmoothingLength'][pgn_core])\n\n\t\t\tdel pgn_core\n\n\t\t\t# Conversion from comoving units to physical units\n\t\t\tvelocity = comoving_velocity(header, velocity)\n\t\t\tcoordinates = comoving_length(header, coordinates)\n\t\t\tmass = comoving_mass(header, mass * 1.0e10)\n\t\t\tif pt == '0':\n\t\t\t\tden_conv = h5file[f'/PartType{pt}/Density'].attrs['CGSConversionFactor']\n\t\t\t\tsphdensity = comoving_density(header, sphdensity * den_conv)\n\t\t\t\tsphlength = comoving_length(header, sphlength)\n\n\t\t\t# Gather the imports across cores\n\t\t\tdata_out[f'partType{pt}'] = {}\n\t\t\tdata_out[f'partType{pt}']['subgroupnumber'] = commune(subgroup_number)\n\t\t\tdata_out[f'partType{pt}']['velocity']        = commune(velocity.reshape(-1, 1)).reshape(-1, 3)\n\t\t\tdata_out[f'partType{pt}']['coordinates']     = commune(coordinates.reshape(-1, 1)).reshape(-1, 3)\n\t\t\tdata_out[f'partType{pt}']['mass']            = commune(mass)\n\t\t\tif pt == '0':\n\t\t\t\tdata_out[f'partType{pt}']['temperature'] = commune(temperature)\n\t\t\t\tdata_out[f'partType{pt}']['sphdensity']  = commune(sphdensity)\n\t\t\t\tdata_out[f'partType{pt}']['sphlength']   = commune(sphlength)\n\n\t\t\tdel subgroup_number, velocity, mass, coordinates, temperature, sphdensity, sphlength\n\n\treturn data_out\n\ndef cluster_data(clusterID: int,\n                 header: Dict[str, float] = None,\n                 fofgroups: Dict[str, np.ndarray] = None):\n\t\"\"\"\n\n\t:param clusterID:\n\t:param header:\n\t:param fofgroups:\n\t:param groupNumbers:\n\t:return:\n\t\"\"\"\n\n\tgroup_data  = fof_group(clusterID, fofgroups = fofgroups)\n\thalo_partgn = cluster_partgroupnumbers(fofgroup=group_data)\n\tpart_data   = cluster_particles(fofgroup=group_data, groupNumbers= halo_partgn)\n\n\tout = {}\n\tout['Header'] = {**header}\n\tout['FOF'] = {**group_data}\n\tfor pt in ['0', '1', '4']:\n\t\tout[f'partType{pt}'] = {**part_data[f'partType{pt}']}\n\treturn out\n\n\ndef glance_cluster(cluster_dict: dict, verbose: bool = False, indent: int = 1) -> None:\n\t\"\"\"\n\n\t:param cluster_dict:\n\t:param verbose:\n\t:param indent:\n\t:return:\n\t\"\"\"\n\tif not verbose:\n\t\tfor key, value in cluster_dict.items():\n\t\t\tif isinstance(value, dict):\n\t\t\t\tpprint('\\t'*indent + str(key))\n\t\t\t\tglance_cluster(value, indent=indent+1)\n\t\t\telif (isinstance(value, np.ndarray) or isinstance(value, list)) and len(value) > 10:\n\t\t\t\tpprint('\\t' * indent + str(key) + ' : ' + f\"len({len(value):d})\\t val({value[0]} ... {value[-1]})\")\n\t\t\telse:\n\t\t\t\tpprint('\\t' * indent + str(key) + ' : ' + str(value))\n\n\tif verbose:\n\t\tfor key, value in cluster_dict.items():\n\t\t\tif isinstance(value, dict):\n\t\t\t\tpprint('\\t'*indent + str(key))\n\t\t\t\tglance_cluster(value, indent=indent+1)\n\t\t\telse:\n\t\t\t\tpprint('\\t'*indent + str(key) +' : '+ str(value))", "meta": {"hexsha": "f05671659d6ac7d122ac9954be24330eb0966a21", "size": 11793, "ext": "py", "lang": "Python", "max_stars_repo_path": "macsis/read.py", "max_stars_repo_name": "LBJ-Wade/C-Eagle-analysis", "max_stars_repo_head_hexsha": "d13ffb219834e11baeb5b9d863c6a6eb965ba6ad", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "macsis/read.py", "max_issues_repo_name": "LBJ-Wade/C-Eagle-analysis", "max_issues_repo_head_hexsha": "d13ffb219834e11baeb5b9d863c6a6eb965ba6ad", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "macsis/read.py", "max_forks_repo_name": "LBJ-Wade/C-Eagle-analysis", "max_forks_repo_head_hexsha": "d13ffb219834e11baeb5b9d863c6a6eb965ba6ad", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2819767442, "max_line_length": 107, "alphanum_fraction": 0.6662426863, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.19265414291785646}}
{"text": "'''\nMichel Lam 2015\nLoads a parameter file\n'''\nimport decimal\nimport re\nimport numpy as np\nfrom astropy.coordinates import SkyCoord\nimport astropy.units as unit\n\nnumre = re.compile('(\\d+[.]\\d+D[+]\\d+)|(-?\\d+[.]\\d+)')\nflagre = re.compile('-[a-zA-Z]')\n\nc = 2.9979e8\nPC_TO_M = 3.086e16\nMAS_TO_RAD = np.pi/(180*60*60*1000)\nYR_TO_S = 3.154e7\n\nDECIMAL = decimal.Decimal\n\n\nclass Parameter(object):\n    def __init__(self, name, value=None, fit=None, error=None, flag=None,\n                 flagvalue=None, numwrap=float, usedecimal=False):\n        if usedecimal:\n            self.numwrap = DECIMAL\n        else:\n            self.numwrap = numwrap\n        # Initialize all values just in case\n        self.name = name\n        self.value = value\n        self.fit = fit\n        self.error = error\n        self.flag = flag\n        self.flagvalue = flagvalue\n        if value is None: #parse all arguments\n            self.parstring = name\n            if name[0] == \"#\":# this is a comment\n                self.name = \"#\"\n                self.value = name[1:]\n                return\n            splitstring = self.parstring.strip().split()\n            if len(splitstring) == 0:\n                return None #?\n            self.name = splitstring[0]\n            if self.name == \"C\": #this is also a comment:\n                self.value = self.parstring[2:]\n                return\n\n            if len(splitstring) == 1: # sometimes true in PSRFITS PSREPHEM table\n                return\n            elif flagre.match(splitstring[1][:2]) and len(splitstring) >= 4: #flag present\n                self.flag = splitstring[1]\n                self.flagvalue = splitstring[2]\n                self.value = self.numwrap(splitstring[3])\n                if len(splitstring) >= 5:\n                    self.error = self.numwrap(splitstring[-1])\n                    if len(splitstring) == 6:\n                        self.fit = int(splitstring[4])\n            else: #no flag present\n                if numre.match(splitstring[1]):\n                    self.value = self.numwrap(splitstring[1].replace('D', 'e'))\n                elif splitstring[1].isdigit():\n                    self.value = int(splitstring[1])\n                elif splitstring[1][1:].isdigit() and (splitstring[1][0] == \"+\" or splitstring[1][0] == \"-\"):\n                    self.value = int(splitstring[1])\n                else:\n                    self.value = splitstring[1]\n\n                if len(splitstring) == 3 or len(splitstring) == 4:\n                    if numre.match(splitstring[-1]):\n                        self.error = self.numwrap(splitstring[-1].replace('D', 'e'))\n                    elif splitstring[1].isdigit():\n                        if splitstring[-1] == \"NaN\":\n                            self.error = np.nan\n                        else:\n                            self.error = int(splitstring[-1])\n                    elif splitstring[1][1:].isdigit() and (splitstring[1][0] == \"+\" or splitstring[1][0] == \"-\"):\n                        self.error = int(splitstring[-1])\n                    else:\n                        self.error = splitstring[-1]\n                    # Fit flag\n                    if len(splitstring) == 3 and not numre.match(splitstring[2]) and splitstring[2] != \"NaN\":\n                        if splitstring[2].isdigit():\n                            self.fit = int(splitstring[2])\n                        else: #this is actually NAME VAL ERROR rather than NAME VAL FLAG\n                            self.fit = 0\n                            self.error = float(splitstring[2])\n                    elif len(splitstring) == 4:\n                        self.fit = int(splitstring[2])\n\n    def getName(self):\n        return self.name\n\n    def getValue(self):\n        return self.value\n\n    def getFit(self):\n        return self.fit\n\n    def getError(self):\n        return self.error\n\n    def getFlag(self):\n        return self.flag\n\n    def getFlagValue(self):\n        return self.flagvalue\n\n    def hasFlag(self):\n        if self.flagvalue is not None:\n            return True\n        return False\n\n\nclass Par(object):\n    def __init__(self, filename, numwrap=float, usedecimal=False):\n        self.filename = filename\n        if isinstance(filename, (list, np.ndarray)):\n            lines = filename\n        elif isinstance(filename, (str, np.str_)):\n            FILE = open(filename, 'r')\n            lines = FILE.readlines()\n        else:\n            return None\n\n        self.usedecimal = usedecimal\n        if self.usedecimal:\n            self.numwrap = DECIMAL\n        else:\n            self.numwrap = numwrap\n        self.paramlist = list() #each unique parameter\n        self.paramnames = list() #the names of each parameter\n        for line in lines:\n            if len(line) == 0:\n                continue\n            p = Parameter(line, numwrap=self.numwrap)\n            self.paramlist.append(p)\n            self.paramnames.append(p.getName())\n        self.paramnames = np.array(self.paramnames, dtype=np.str_)\n        if isinstance(filename, str):\n            FILE.close()\n\n    def __repr__(self):\n        numwrapstr = repr(self.numwrap).split(\"'\")[1]\n        return \"Par(%r, numwrap=%s, usedecimal=%r)\" % (self.filename, numwrapstr, self.usedecimal)\n\n    def __str__(self):\n        if isinstance(self.filename, (list, np.ndarray)):\n            return \"\\n\".join(self.filename)\n        return self.filename\n\n    def save(self, filename):\n        # Crude saving attempt\n        output = \"\"\n        for param in self.paramlist:\n            output += param.parstring\n        with open(filename, 'w') as FILE:\n            FILE.write(output)\n\n    def getInd(self, tag):\n        return np.where(self.paramnames == tag)[0]#[0]\n\n    def get(self, tag, flag=False, error=False):\n        if tag in self.paramnames:\n            ind = self.getInd(tag)\n            retval = []\n            for i in ind:\n                if error:\n                    val = self.paramlist[i].getError()\n                elif flag:\n                    val = self.paramlist[i].getFlagValue()\n                else:\n                    val = self.paramlist[i].getValue()\n                try:\n                    retval.append(self.numwrap(val))\n                except (ValueError, TypeError, decimal.InvalidOperation):\n                    retval.append(val)\n            if len(retval) == 1:\n                return retval[0]\n            return np.array(retval)\n        return None\n\n    \"\"\"\n    def getParameterFlags(self, tag):\n        #If a parameter has flags, return all of the possible values as a list\n        if tag in self.paramnames:\n            ind = self.getInd(tag)\n            retval = []\n            for i in ind:\n                retval.append(self.paramlist[i].getFlagValue())\n            if len(retval) == 1:\n                return retval[0]\n            return np.array(retval)\n        return None\n    \"\"\"\n\n    def getPeriod(self):\n        if 'P0' in self.paramnames:\n            return self.get('P0')\n        if 'F0' in self.paramnames:\n            F0 = self.get('F0')\n        elif 'F' in self.paramnames:\n            F0 = self.get('F')\n        elif 'IF0' in self.paramnames:\n            F0 = (self.get('IF0') + self.get('FF0'))/self.numwrap(1000.0)\n        return self.numwrap(1.0)/F0\n\n    def getPeriodDot(self, shklovskii=False):\n        if 'P1' in self.paramnames:\n            Pdot = self.get('P1')\n        elif 'F1' in self.paramnames:\n            Pdot = self.numwrap(-1.0)*self.get('F1') / (self.get('F0')**2)\n        else:\n            return None\n\n        if shklovskii: #Correct for the shklovskii effect\n            PM = self.getPM()\n            if PM is None or \"PX\" not in self.paramnames:\n                return Pdot\n\n            P = self.getPeriod() #s\n            PX = self.get(\"PX\") #mas\n            PXerr = self.get(\"PX\", error=True)\n            if PX <= 0 or (PXerr is not None and PXerr >= np.abs(PX)):\n                return Pdot\n\n            PM = PM * self.numwrap(MAS_TO_RAD/YR_TO_S) #mas/yr -> rad/s\n            D = self.numwrap(1000*PC_TO_M)/PX #kpc -> m\n            Pdot_pm = P*PM**2 *D/self.numwrap(c) #s/s\n            return Pdot-Pdot_pm\n        else:\n            return Pdot\n\n    def getFrequency(self):\n        return self.numwrap(1.0)/self.getPeriod()\n\n    def getFrequencyDot(self, shklovskii=False):\n        return self.numwrap(-1.0) * self.getPeriodDot(shklovskii=shklovskii) / self.getPeriod()**2\n\n    def getPM(self, error=False):\n        keys = self.paramnames\n        retval = None\n        if \"PMRA\" in keys and \"PMDEC\" in keys:\n            PMRA = self.get(\"PMRA\")\n            PMDEC = self.get(\"PMDEC\")\n            PM = np.sqrt(PMRA**2 + PMDEC**2) #mas/yr\n            if error:\n                PMRAerr = self.get(\"PMRA\", error=True)\n                PMDECerr = self.get(\"PMDEC\", error=True)\n                retval = np.sqrt((PMRAerr*PMRA/PM)**2 + (PMDECerr*PMDEC/PM)**2)\n            else:\n                retval = PM\n        elif \"PMRA\" in keys:\n            retval = abs(self.get(\"PMRA\", error=error))\n        elif \"PMDEC\" in keys:\n            retval = abs(self.get(\"PMDEC\", error=error))\n        elif \"PMLAMBDA\" in keys and \"PMBETA\" in keys:\n            PMLAMBDA = self.get(\"PMLAMBDA\")\n            PMBETA = self.get(\"PMBETA\")\n            PM = np.sqrt(PMLAMBDA**2 + PMBETA**2) #mas/yr\n            if error:\n                PMLAMBDAerr = self.get(\"PMLAMBDA\", error=True)\n                PMBETAerr = self.get(\"PMBETA\", error=True)\n                retval = np.sqrt((PMLAMBDAerr*PMLAMBDA/PM)**2 + (PMBETAerr*PMBETA/PM)**2)\n            else:\n                retval = PM\n        elif \"PMLAMBDA\" in keys:\n            retval = abs(self.get(\"PMLAMBDA\", error=error))\n        elif \"PMBETA\" in keys:\n            retval = abs(self.get(\"PMBETA\", error=error))\n        return retval\n\n    def getPX(self, error=False):\n        return self.get('PX', error=error)\n\n    def getDIST(self, error=False):\n        PX = self.getPX()\n        if error:\n            PXerr = self.getPX(error=True)\n            return PXerr/PX**2\n        else:\n            return self.numwrap(1.0)/PX\n\n    def getVpperp(self, error=False):\n        '''\n        Get transverse velocity\n        v = 4.74 km/s (D/kpc) (mu/ mas yr^-1)\n\n        for errors: assuming PM and PX are\n        '''\n        PM = self.getPM() #mas yr^-1\n        DIST = self.getDIST() #kpc\n        retval = self.numwrap(4.74) * PM * DIST\n\n        if error:\n            PMerr = self.getPM(error=True)\n            DISTerr = self.getDIST(error=True)\n            return retval * np.sqrt((PMerr/PM)**2 + (DISTerr/DIST)**2)\n        else:\n            return retval\n\n\n    def getCoord(self):\n        '''\n        Return an Astropy SkyCoord object based on the coordinates\n        '''\n        keys = self.paramnames\n        if \"RAJ\" in keys: #return Equatorial coordinates\n            RAJ = self.get(\"RAJ\")\n            DECJ = self.get(\"DECJ\")\n            if DECJ[0].isdigit(): #is positive\n                DECJ = \"+\" + DECJ\n            coord = SkyCoord(ra=RAJ, dec=DECJ, frame=\"icrs\", unit=(unit.hourangle, unit.deg))\n        elif \"LAMBDA\" in keys: #return Ecliptic coordinates\n            LAMBDA = self.get(\"LAMBDA\")\n            BETA = self.get(\"BETA\")\n            coord = SkyCoord(lon=LAMBDA, lat=BETA, frame=\"barycentrictrueecliptic\", unit=unit.deg)\n        elif \"ELAT\" in keys: #return Ecliptic coordinates\n            LAMBDA = self.get(\"ELONG\")\n            BETA = self.get(\"ELAT\")\n            coord = SkyCoord(lon=LAMBDA, lat=BETA, frame=\"barycentrictrueecliptic\", unit=unit.deg)\n        return coord\n    getCoords = getCoord\n\n\n    def getDM(self):\n        return self.get('DM')\n\n    def getDMX(self, full_output=False):\n        keys = self.paramnames\n        Ncomponents = 0\n        for key in keys:\n            if key[0:4] == 'DMX_':\n                Ncomponents += 1\n        if Ncomponents == 0:\n            return None\n        #DM = self.getDM()\n        ts = np.zeros(Ncomponents)\n        dmxs = np.zeros(Ncomponents)\n        errs = np.zeros(Ncomponents)\n        if full_output:\n            R1s = np.zeros(Ncomponents)\n            R2s = np.zeros(Ncomponents)\n            F1s = np.zeros(Ncomponents)\n            F2s = np.zeros(Ncomponents)\n        for i in range(Ncomponents):\n            ts[i] = self.get('DMXEP_%04i'%(i+1))\n            if np.isnan(ts[i]):\n                ts[i] = self.numwrap(0.5)*(self.get('DMXR1_%04i'%(i+1))+self.get('DMXR2_%04i'%(i+1)))\n            dmxs[i] = self.get('DMX_%04i'%(i+1))\n            errs[i] = self.get('DMX_%04i'%(i+1), error=True) #check to make sure this exists?\n            if full_output:\n                R1s[i] = self.get('DMXR1_%04i'%(i+1))\n                R2s[i] = self.get('DMXR2_%04i'%(i+1))\n                F1s[i] = self.get('DMXF1_%04i'%(i+1))\n                F2s[i] = self.get('DMXF2_%04i'%(i+1))\n                if np.isnan(ts[i]):\n                    ts[i] = (R1s[i]+R2s[i])/2.0\n        if full_output:\n            return ts, dmxs, errs, R1s, R2s, F1s, F2s\n        return ts, dmxs, errs\n\n    def getXMX(self):#, full_output=False):\n        keys = self.paramnames\n        Ncomponents = 0\n        for key in keys:\n            if key[0:4] == 'XMX_':\n                Ncomponents += 1\n        if Ncomponents == 0:\n            return None\n        #DM = self.getDM()\n        xmxs = np.zeros(Ncomponents)\n        errs = np.zeros(Ncomponents)\n        R1s = np.zeros(Ncomponents)\n        R2s = np.zeros(Ncomponents)\n        EXPs = np.zeros(Ncomponents)\n        for i in range(Ncomponents):\n            xmxs[i] = self.get('XMX_%04i'%(i+1))\n            errs[i] = self.get('XMX_%04i'%(i+1), error=True) #check to make sure this exists?\n            R1s[i] = self.get('XMXR1_%04i'%(i+1))\n            R2s[i] = self.get('XMXR2_%04i'%(i+1))\n            EXPs[i] = self.get('XMXEXP_%04i'%(i+1))\n        return xmxs, errs, R1s, R2s, EXPs\n\n    def getDMseries(self):\n        ts, dmxs, errs = self.getDMX()\n        DM = self.getDM()\n        return ts, dmxs + float(DM), errs #float from possible decimal!\n\n    def getFD(self):\n        coeffs = []\n        for param in self.paramnames:\n            if \"FD\" in param:\n                coeffs.append(self.get(param))\n        if len(coeffs) == 0:\n            return None\n        return np.array(coeffs)\n\n    def getFDfunc(self):\n        \"\"\"\n        Returns a function that provides the timing delays as a function of observing frequency\n        \"\"\"\n        FD = self.getFD()\n        if FD is None:\n            return None\n        FD = FD[::-1]\n        FD = np.concatenate((FD, [0]))\n        f = lambda nu: 1e6*np.polyval(FD, np.log(nu)) #nu in GHz, returns values in microseconds\n        return f\n\n    def getName(self):\n        \"\"\" Returns the pulsar name \"\"\"\n        if \"PSR\" in self.paramnames:\n            return self.get(\"PSR\")\n        elif \"PSRJ\" in self.paramnames:\n            return self.get(\"PSRJ\")\n        return None\n\n    def getTspan(self, years=False):\n        \"\"\" Returns the total time span the par file covers \"\"\"\n        start = self.get(\"START\")\n        finish = self.get(\"FINISH\")\n        if years:\n            return (finish-start)/365.25\n        return finish-start\n", "meta": {"hexsha": "4508d82cbb89a69e837b7b5e1bbb213d11ed0bde", "size": 15082, "ext": "py", "lang": "Python", "max_stars_repo_path": "pypulse/par.py", "max_stars_repo_name": "mtlam/PyPulse", "max_stars_repo_head_hexsha": "87cad878408ee5021c1092eda7d271a712f52198", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2015-10-20T14:29:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-19T17:17:16.000Z", "max_issues_repo_path": "pypulse/par.py", "max_issues_repo_name": "mtlam/PyPulse", "max_issues_repo_head_hexsha": "87cad878408ee5021c1092eda7d271a712f52198", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2017-08-03T19:37:42.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-17T23:58:17.000Z", "max_forks_repo_path": "pypulse/par.py", "max_forks_repo_name": "mtlam/PyPulse", "max_forks_repo_head_hexsha": "87cad878408ee5021c1092eda7d271a712f52198", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2015-10-20T14:34:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T18:28:23.000Z", "avg_line_length": 35.3208430913, "max_line_length": 113, "alphanum_fraction": 0.5170401803, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 3872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.19265414177889673}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom builtins import object\n\nimport numpy as np\nimport pkg_resources\nimport fsps\nimport os\nimport linecache\n#grid: 2 files: line, cont\n#columns: wavelengths\n#rows: models\n#header\n#wavelength grid\n#age, Z, logU\n#flux1\n#flux2\n#flux3\n\n###\n# reads from ZAU***.out_lines, ZAU***.out_cont\n# produces ZAU_**.lines, ZAU_**.cont\n###\nclass writeFormattedOutput(object):\n    #sp = fsps.StellarPopulation()\n    #fsps_lam = sp.wavelengths\n    def __init__(self, dir_, mod_prefix, mod_suffix,\n                 use_extended_lines=False, more_info=False,**kwargs):\n        '''\n        writeFormattedOutput(mod_dir, 'ZAU', 'BPASS')\n        '''\n        self.dir_, self.mod_prefix = dir_, mod_prefix\n        self.file_pr = dir_ + mod_prefix\n        if mod_suffix is None:\n            self.out_pr = dir_ + mod_prefix\n        else:\n            self.out_pr = dir_ + mod_prefix + mod_suffix\n        # each model's final info will be in prefix00.lines, prefix00.cont\n        self.line_out = self.out_pr + \".lines\"\n        self.cont_out = self.out_pr + \".cont\"\n        # load each model's parameters from prefix.pars\n        self.loadModInfo()\n        # print ordered emission line wavelengths + fluxes\n        self.doLineOut(use_extended_lines=use_extended_lines,\n                       more_info=more_info)\n        # interp and print neb cont onto FSPS wavelenth arr\n        self.doContOut()\n        return\n    def loadModInfo(self, **kwargs):\n        '''\n        reads model parameters from \"ZAU.pars\"\n        '''\n        name_keys = [\"mod_num\", \"logZ\", \"Age\", \"logU\", \"logR\", \"logQ\", \"nH\", \"efrac\"]\n        data = np.genfromtxt(self.file_pr+\".pars\", unpack=True)\n        ddata = {}\n        for i,key in enumerate(name_keys):\n            ddata[key] = data[i]\n            self.__setattr__(key, data[i])\n        self.__setattr__(\"modpars\", ddata)\n        self.NZ = len(np.unique(self.logZ))\n        self.NA = len(np.unique(self.Age))\n        self.NU = len(np.unique(self.logU))\n        return\n    def doLineOut(self, more_info=False, **kwargs):\n        '''\n        prints line fluxes to prefix00.lines file\n        '''\n        f = open(self.line_out, \"w\")\n        self.printLineLam(f, **kwargs)\n        for n in self.mod_num:\n            self.printLineFlu(f, n.astype(int), more_info=more_info)\n        f.close()\n        print(\"lines: {0:.0f} models to file {1}\".format(self.mod_num[-1], self.line_out))\n        return\n    def printLineLam(self, f, use_extended_lines=False):\n        '''\n        prints the wavelength array for the emission lines as the second\n        line in the output file. converts all wavelengths to vacuum.\n        '''\n        #read in file containing wavelength info\n        if use_extended_lines:\n            linefile = pkg_resources.resource_filename(__name__, \"data/orderedLinesEXT.dat\")\n        else:\n            linefile = pkg_resources.resource_filename(__name__, \"data/orderedLines.dat\")\n        data_vac = np.genfromtxt(linefile)\n        #data_vac = air_to_vac(data) # new file is already in vac\n        nlines = len(data_vac)\n        nmods = np.max(self.mod_num)\n        #print header to file\n        head_str = \"#{0} cols {1:.0f} rows {2} logZ {3} Age {4} logU\".format(nlines, nmods, self.NZ, self.NA, self.NU)\n        f.write(head_str+\"\\n\")\n        #print lambda array\n        p_str = \" \".join([\"{0:1.6e}\".format(dat) for dat in data_vac])\n        f.write(p_str+\"\\n\")\n        return\n    def printLineFlu(self, f, n, more_info=False):\n        #write model parameters\n        if more_info:\n            tstr = linecache.getline(self.file_pr+'.pars', n)\n        else:\n            tstr = \"{0:2.4e} {1:2.4e} {2:2.4e}\\n\".format(self.logZ[n-1], self.Age[n-1], self.logU[n-1])\n        f.write(tstr)\n        #read in and print emission line intensities (Lsun/Q)\n        nst = \"{0}\".format(n)\n        filename = self.file_pr+nst+\".out_lines\"\n        lam, flu = np.genfromtxt(filename, unpack=True)\n        I_str = [\"{0:1.4e}\".format(s) for s in flu]\n        tstr = \" \".join(I_str)\n        f.write(tstr+\"\\n\")\n        return\n    def doContOut(self, **kwargs):\n        f = open(self.cont_out, \"w\")\n        self.printContLam(f)\n        for num in self.modpars['mod_num']:\n            iind = num.astype(int)\n            pars = dict(logZ=self.logZ[iind-1],\n                        Age=self.Age[iind-1],\n                        nH=self.nH[iind-1],\n                        logQ=self.logQ[iind-1],\n                        logU=self.logU[iind-1],\n                        logR=self.logR[iind-1],\n                        mod_num=iind,\n                        efrac=self.efrac[iind-1])\n            self.printContFlu(f, pars)\n        f.close()\n        print(\"cont: {0:.0f} models to file {1}\".format(self.modpars['mod_num'][-1], self.cont_out))\n        return\n    def printContFlu(self, f, pars):\n        #write model parameters\n        tstr = \"{0:2.4e} {1:2.4e} {2:2.4e}\".format(pars[\"logZ\"],\n                                                   pars[\"Age\"],\n                                                   pars[\"logU\"])\n        f.write(tstr+\"\\n\")\n        #read in and print emission line intensities\n        nst = \"{0}\".format(pars[\"mod_num\"])\n        filename = self.file_pr+nst+\".out_cont\"\n        # read lambda, diffuse cont\n        mdata = np.genfromtxt(filename)\n        lam = mdata[:,0]\n        flu = mdata[:,1]\n        y_str = \" \".join([\"{0:1.4}\".format(y) for y in flu])\n        f.write(y_str+\"\\n\")\n        return\n    def printContLam(self, f):\n        '''\n        prints header in first line of file, and the FSPS wavelength array\n        (for the nebular continuum) as the second line in the output file.\n        # nlam cols nmod rows logZ Age logU\n        # fsps_lam_1 fsps_lam_2 .... fsps_lam_n\n        '''\n        #grab fsps wavelength info\n        lamfile = pkg_resources.resource_filename(__name__, \"data/FSPSlam.dat\")\n        fsps_lam = np.genfromtxt(lamfile)\n        self.__setattr__(\"fsps_lam\", fsps_lam)\n        nlam = len(fsps_lam)\n        nmods = np.max(self.mod_num).astype(int)\n        #print header to file\n        head_str = \"#{0} cols {1} rows {2} logZ {3} Age {4} logU\".format(nlam, nmods, self.NZ, self.NA, self.NU)\n        f.write(head_str+\"\\n\")\n        #print lambda array\n        p_str = \" \".join([\"{0:1.6e}\".format(lam) for lam in fsps_lam])\n        f.write(p_str+\"\\n\")\n        return\n\n\n\n#------------------------------------------------\ndef zmet_to_nuZ(zmet):\n    '''\n    zmet = 1,2,3,4,5,6,7,8\n        ...corresponding to...\n    m1.00, m1.02, m1.04, m1.06, p0.00, p0.02, p0.04, p0.06\n    '''\n    zmets = np.array([1,2,3,4,5,6,7,8])\n    zs = np.array([-1.00, -1.02, -1.04, -1.06, 0.00, 0.02, 0.04, 0.06])\n    if type(zmet) is float:\n        ii, = np.where(zmets == zmet)[0]\n        out_val = zs[ii]\n    else:\n        out_val = np.zeros_like(zmet, dtype='float')\n        for i in range(len(zmet)):\n            ii, = np.where(zmets == zmet[i])[0]\n            out_val[i] = zs[ii]\n    return out_val\n\nclass writeAltFormattedOutput(object):\n    #sp = fsps.StellarPopulation()\n    #fsps_lam = sp.wavelengths\n    def __init__(self, dir_, mod_prefix, mod_suffix,\n                 use_extended_lines=False, more_info=False,**kwargs):\n        '''\n        writeFormattedOutput(mod_dir, 'ZAU', 'BPASS')\n        '''\n        self.dir_, self.mod_prefix = dir_, mod_prefix\n        self.file_pr = dir_ + mod_prefix\n        if mod_suffix is None:\n            self.out_pr = dir_ + mod_prefix\n        else:\n            self.out_pr = dir_ + mod_prefix + mod_suffix\n        # each model's final info will be in prefix00.lines, prefix00.cont\n        self.line_out = self.out_pr + \".lines\"\n        self.cont_out = self.out_pr + \".cont\"\n        self.loadModInfo() # load each model's parameters from prefix.pars\n        # print ordered emission line wavelengths + fluxes\n        self.doLineOut(use_extended_lines=use_extended_lines,\n                       more_info=more_info)\n        self.doContOut() # interp and print neb cont onto FSPS wavelenth arr\n        return\n    def loadModInfo(self, **kwargs):\n        '''\n        reads model parameters from \"ZAU.pars\"\n        '''\n        name_keys = [\"mod_num\", \"logZ\", \"Age\", \"logU\", \"logR\", \"logQ\", \"nH\", \"efrac\", \"zmet\"]\n        data = np.genfromtxt(self.file_pr+\".pars\", unpack=True)\n        ddata = {}\n        for i,key in enumerate(name_keys):\n            if key == 'zmet':\n                temp_arr = zmet_to_nuZ(data[i])\n                ddata[key] = temp_arr\n                self.__setattr__(key, temp_arr)\n            else:\n                ddata[key] = data[i]\n                self.__setattr__(key, data[i])\n        self.__setattr__(\"modpars\", ddata)\n        self.NZ = len(np.unique(self.zmet))\n        self.NA = len(np.unique(self.Age))\n        self.NU = len(np.unique(self.logU))\n        return\n    def doLineOut(self, more_info=False, **kwargs):\n        '''\n        prints line fluxes to prefix00.lines file\n        '''\n        f = open(self.line_out, \"w\")\n        self.printLineLam(f, **kwargs)\n        for n in self.mod_num:\n            self.printLineFlu(f, n.astype(int), more_info=more_info)\n        f.close()\n        print(\"lines: {0:.0f} models to file {1}\".format(self.mod_num[-1], self.line_out))\n        return\n    def printLineLam(self, f, use_extended_lines=False):\n        '''\n        prints the wavelength array for the emission lines as the second\n        line in the output file. converts all wavelengths to vacuum.\n        '''\n        #read in file containing wavelength info\n        if use_extended_lines:\n            linefile = pkg_resources.resource_filename(__name__, \"data/orderedLinesEXT.dat\")\n        else:\n            linefile = pkg_resources.resource_filename(__name__, \"data/orderedLines.dat\")\n        data_vac = np.genfromtxt(linefile)\n        #data_vac = air_to_vac(data) # new file is already in vac\n        nlines = len(data_vac)\n        nmods = np.max(self.mod_num)\n        #print header to file\n        head_str = \"#{0} cols {1:.0f} rows {2} logZ {3} Age {4} logU\".format(nlines, nmods, self.NZ, self.NA, self.NU)\n        f.write(head_str+\"\\n\")\n        #print lambda array\n        p_str = \" \".join([\"{0:1.6e}\".format(dat) for dat in data_vac])\n        f.write(p_str+\"\\n\")\n        return\n    def printLineFlu(self, f, n, more_info=False):\n        #write model parameters\n        if more_info:\n            tstr = linecache.getline(self.file_pr+'.pars', n)\n            f.write(tstr)\n        else:\n            tstr = \"{0:2.4e} {1:2.4e} {2:2.4e}\".format(self.zmet[n-1], self.Age[n-1], self.logU[n-1])\n            f.write(tstr+\"\\n\")\n        #read in and print emission line intensities (Lsun/Q)\n        nst = \"{0}\".format(n)\n        filename = self.file_pr+nst+\".out_lines\"\n        lam, flu = np.genfromtxt(filename, unpack=True)\n        I_str = [\"{0:1.4e}\".format(s) for s in flu]\n        tstr = \" \".join(I_str)\n        f.write(tstr+\"\\n\")\n        return\n    def doContOut(self, **kwargs):\n        f = open(self.cont_out, \"w\")\n        self.printContLam(f)\n        for num in self.modpars['mod_num']:\n            iind = num.astype(int)\n            pars = dict(logZ=self.logZ[iind-1],\n                        Age=self.Age[iind-1],\n                        nH=self.nH[iind-1],\n                        logQ=self.logQ[iind-1],\n                        logU=self.logU[iind-1],\n                        logR=self.logR[iind-1],\n                        mod_num=iind,\n                        zmet=self.zmet[iind-1])\n            self.printContFlu(f, pars)\n        f.close()\n        print(\"cont: {0:.0f} models to file {1}\".format(self.modpars['mod_num'][-1], self.cont_out))\n        return\n    def printContFlu(self, f, pars):\n        #write model parameters\n        tstr = \"{0:2.4e} {1:2.4e} {2:2.4e}\".format(pars[\"zmet\"],\n                                                   pars[\"Age\"],\n                                                   pars[\"logU\"])\n        f.write(tstr+\"\\n\")\n        #read in and print emission line intensities\n        nst = \"{0}\".format(pars[\"mod_num\"])\n        filename = self.file_pr+nst+\".out_cont\"\n        # read lambda, diffuse cont\n        mdata = np.genfromtxt(filename)\n        lam = mdata[:,0]\n        flu = mdata[:,1]\n        y_str = \" \".join([\"{0:1.4}\".format(y) for y in flu])\n        f.write(y_str+\"\\n\")\n        return\n    def printContLam(self, f):\n        '''\n        prints header in first line of file, and the FSPS wavelength array\n        (for the nebular continuum) as the second line in the output file.\n        # nlam cols nmod rows logZ Age logU\n        # fsps_lam_1 fsps_lam_2 .... fsps_lam_n\n        '''\n        #grab fsps wavelength info\n        lamfile = pkg_resources.resource_filename(__name__, \"data/FSPSlam.dat\")\n        fsps_lam = np.genfromtxt(lamfile)\n        self.__setattr__(\"fsps_lam\", fsps_lam)\n        nlam = len(fsps_lam)\n        nmods = np.max(self.mod_num).astype(int)\n        #print header to file\n        head_str = \"#{0} cols {1} rows {2} logZ {3} Age {4} logU\".format(nlam, nmods, self.NZ, self.NA, self.NU)\n        f.write(head_str+\"\\n\")\n        #print lambda array\n        p_str = \" \".join([\"{0:1.6e}\".format(lam) for lam in fsps_lam])\n        f.write(p_str+\"\\n\")\n        return\n", "meta": {"hexsha": "714959e02b80dc95fe381b90d41cf3c5667d7ce3", "size": 13313, "ext": "py", "lang": "Python", "max_stars_repo_path": "cloudyfsps/outputFormatting.py", "max_stars_repo_name": "prerakgarg07/cloudyfsps", "max_stars_repo_head_hexsha": "4a6a185343ed1e09b9f201a465c37e377ef42101", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-12-07T01:00:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T17:50:51.000Z", "max_issues_repo_path": "cloudyfsps/outputFormatting.py", "max_issues_repo_name": "prerakgarg07/cloudyfsps", "max_issues_repo_head_hexsha": "4a6a185343ed1e09b9f201a465c37e377ef42101", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cloudyfsps/outputFormatting.py", "max_forks_repo_name": "prerakgarg07/cloudyfsps", "max_forks_repo_head_hexsha": "4a6a185343ed1e09b9f201a465c37e377ef42101", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-12-08T22:57:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-30T15:04:33.000Z", "avg_line_length": 39.7402985075, "max_line_length": 118, "alphanum_fraction": 0.5590024788, "include": true, "reason": "import numpy", "num_tokens": 3645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.33807711081162, "lm_q1q2_score": 0.19265413797843944}}
{"text": "\"\"\"\n.. module:: mcmc\n   :synopsis: Monte Carlo procedure\n.. moduleauthor:: Benjamin Audren <benjamin.audren@epfl.ch>\n\nThis module defines one key function, :func:`chain`, that handles the Markov\nchain. So far, the code uses only one chain, as no parallelization is done.\n\nThe following routine is also defined in this module, which is called at\nevery step:\n\n* :func:`get_new_position` returns a new point in the parameter space,\n  depending on the proposal density.\n\nThe :func:`chain` in turn calls several helper routines, defined in\n:mod:`sampler`. These are called just once:\n\n* :func:`compute_lkl() <sampler.compute_lkl>` is called at every step in the Markov chain, returning\n  the likelihood at the current point in the parameter space.\n* :func:`get_covariance_matrix() <sampler.get_covariance_matrix>`\n* :func:`read_args_from_chain() <sampler.read_args_from_chain>`\n* :func:`read_args_from_bestfit() <sampler.read_args_from_bestfit>`\n* :func:`accept_step() <sampler.accept_step>`\n\nTheir usage is described in :mod:`sampler`. On the contrary, the following\nroutines are called at every step:\n\nThe arguments of these functions will often contain **data** and/or **cosmo**.\nThey are both initialized instances of respectively :class:`data` and the\ncosmological class. They will thus not be described for every function.\n\"\"\"\n\nimport os\nimport sys\nimport math\nimport random as rd\nimport numpy as np\nimport warnings\nimport scipy.linalg as la\nfrom pprint import pprint\n\nimport io_mp\nimport sampler\n\n\ndef get_new_position(data, eigv, U, k, Cholesky, Rotation):\n    \"\"\"\n    Obtain a new position in the parameter space from the eigen values of the\n    inverse covariance matrix, or from the Cholesky decomposition (original\n    idea by Anthony Lewis, in `Efficient sampling of fast and slow\n    cosmological parameters <http://arxiv.org/abs/1304.4473>`_ )\n\n    The three different jumping options, decided when starting a run with the\n    flag **-j**  are **global**, **sequential** and **fast** (by default) (see\n    :mod:`parser_mp` for reference).\n\n    .. warning::\n\n        For running Planck data, the option **fast** is highly recommended, as\n        it speeds up the convergence. Note that when using this option, the\n        list of your likelihoods in your parameter file **must match** the\n        ordering of your nuisance parameters (as always, they must come after\n        the cosmological parameters, but they also must be ordered between\n        likelihood, with, preferentially, the slowest likelihood to compute\n        coming first).\n\n\n    - **global**: varies all the parameters at the same time. Depending on the\n      input covariance matrix, some degeneracy direction will be followed,\n      otherwise every parameter will jump independently of each other.\n    - **sequential**: varies every parameter sequentially. Works best when\n      having no clue about the covariance matrix, or to understand which\n      estimated sigma is wrong and slowing down the whole process.\n    - **fast**: privileged method when running the Planck likelihood. Described\n      in the aforementioned article, it separates slow (cosmological) and fast\n      (nuisance) parameters.\n\n    Parameters\n    ----------\n    eigv : numpy array\n        Eigenvalues previously computed\n    U : numpy_array\n        Covariance matrix.\n    k : int\n        Number of points so far in the chain, is used to rotate through\n        parameters\n    Cholesky : numpy array\n        Cholesky decomposition of the covariance matrix, and its inverse\n    Rotation : numpy_array\n        Not used yet\n\n    \"\"\"\n\n    parameter_names = data.get_mcmc_parameters(['varying'])\n    vector_new = np.zeros(len(parameter_names), 'float64')\n    sigmas = np.zeros(len(parameter_names), 'float64')\n\n    # Write the vector of last accepted points, or if it does not exist\n    # (initialization routine), take the mean value\n    vector = np.zeros(len(parameter_names), 'float64')\n    try:\n        for elem in parameter_names:\n            vector[parameter_names.index(elem)] = \\\n                data.mcmc_parameters[elem]['last_accepted']\n    except KeyError:\n        for elem in parameter_names:\n            vector[parameter_names.index(elem)] = \\\n                data.mcmc_parameters[elem]['initial'][0]\n\n    # Initialize random seed\n    rd.seed()\n\n    # Choice here between sequential and global change of direction\n    if data.jumping == 'global':\n        for i in range(len(vector)):\n            sigmas[i] = (math.sqrt(1/eigv[i]/len(vector))) * \\\n                rd.gauss(0, 1)*data.jumping_factor\n    elif data.jumping == 'sequential':\n        i = k % len(vector)\n        sigmas[i] = (math.sqrt(1/eigv[i]))*rd.gauss(0, 1)*data.jumping_factor\n    elif data.jumping == 'fast':\n        #i = k % len(vector)\n        j = k % len(data.over_sampling_indices)\n        i = data.over_sampling_indices[j]\n        ###############\n        # method fast+global\n        for index, elem in enumerate(data.block_parameters):\n            # When the running index is below the maximum index of a block of\n            # parameters, this block is varied, and **only this one** (note the\n            # break at the end of the if clause, it is not a continue)\n            if i < elem:\n                if index == 0:\n                    Range = elem\n                    Previous = 0\n                else:\n                    Range = elem-data.block_parameters[index-1]\n                    Previous = data.block_parameters[index-1]\n                # All the varied parameters are given a random variation with a\n                # sigma of 1. This will translate in a jump for all the\n                # parameters (as long as the Cholesky matrix is non diagonal)\n                for j in range(Range):\n                    sigmas[j+Previous] = (math.sqrt(1./Range)) * \\\n                        rd.gauss(0, 1)*data.jumping_factor\n                break\n            else:\n                continue\n    else:\n        print('\\n\\n Jumping method unknown (accepted : ')\n        print('global, sequential, fast (default))')\n\n    # Fill in the new vector\n    if data.jumping in ['global', 'sequential']:\n        vector_new = vector + np.dot(U, sigmas)\n    else:\n        vector_new = vector + np.dot(Cholesky, sigmas)\n\n    # Check for boundaries problems\n    flag = 0\n    for i, elem in enumerate(parameter_names):\n        value = data.mcmc_parameters[elem]['initial']\n        if((str(value[1]) != str(-1) and value[1] is not None) and\n                (vector_new[i] < value[1])):\n            flag += 1  # if a boundary value is reached, increment\n        elif((str(value[2]) != str(-1) and value[2] is not None) and\n                vector_new[i] > value[2]):\n            flag += 1  # same\n\n    # At this point, if a boundary condition is not fullfilled, ie, if flag is\n    # different from zero, return False\n    if flag != 0:\n        return False\n\n    # Check for a slow step (only after the first time, so we put the test in a\n    # try: statement: the first time, the exception KeyError will be raised)\n    try:\n        data.check_for_slow_step(vector_new)\n    except KeyError:\n        pass\n\n    # If it is not the case, proceed with normal computation. The value of\n    # new_vector is then put into the 'current' point in parameter space.\n    for index, elem in enumerate(parameter_names):\n        data.mcmc_parameters[elem]['current'] = vector_new[index]\n\n    # Propagate the information towards the cosmo arguments\n    data.update_cosmo_arguments()\n\n    return True\n\n\n######################\n# MCMC CHAIN\n######################\ndef chain(cosmo, data, command_line):\n    \"\"\"\n    Run a Markov chain of fixed length with a Metropolis Hastings algorithm.\n\n    Main function of this module, this is the actual Markov chain procedure.\n    After having selected a starting point in parameter space defining the\n    first **last accepted** one, it will, for a given amount of steps :\n\n    + choose randomly a new point following the *proposal density*,\n    + compute the cosmological *observables* through the cosmological module,\n    + compute the value of the *likelihoods* of the desired experiments at this\n      point,\n    + *accept/reject* this point given its likelihood compared to the one of\n      the last accepted one.\n\n    Every time the code accepts :code:`data.write_step` number of points\n    (quantity defined in the input parameter file), it will write the result to\n    disk (flushing the buffer by forcing to exit the output file, and reopen it\n    again.\n\n    .. note::\n\n        to use the code to set a fiducial file for certain fixed parameters,\n        you can use two solutions. The first one is to put all input 1-sigma\n        proposal density to zero (this method still works, but is not\n        recommended anymore). The second one consist in using the flag \"-f 0\",\n        to force a step of zero amplitude.\n\n    \"\"\"\n\n    ## Initialisation\n    loglike = 0\n\n    # In case command_line.silent has been asked, outputs should only contain\n    # data.out. Otherwise, it will also contain sys.stdout\n    outputs = [data.out]\n    if not command_line.silent:\n        outputs.append(sys.stdout)\n\n    use_mpi = False\n    # check for MPI\n    try:\n        from mpi4py import MPI\n        comm = MPI.COMM_WORLD\n        rank = comm.Get_rank()\n        # suppress duplicate output from slaves\n        if rank:\n            command_line.quiet = True\n        use_mpi = True\n    except ImportError:\n        # set all chains to master if no MPI\n        rank = 0\n\n    # Initialise master and slave chains for superupdate.\n    # Workaround in order to have one master chain and several slave chains even when\n    # communication fails between MPI chains. It could malfunction on some hardware.\n    # TODO: Would like to merge with MPI initialization above and make robust and logical\n    # TODO: Or if keeping current scheme, store value and delete jumping_factor.txt\n    # TODO: automatically if --parallel-chains is enabled\n    if command_line.superupdate and data.jumping_factor:\n        try:\n            jump_file = open(command_line.folder + '/jumping_factor.txt','r')\n            #if command_line.restart is None:\n            if not use_mpi and command_line.parallel_chains:\n                rank = 1\n                warnings.warn('MPI not in use, flag --parallel-chains enabled, '\n                              'superupdate enabled, and a jumping_factor.txt file detected. '\n                              'If relaunching in the same folder or restarting a run this '\n                              'will cause all chains to be assigned as slaves. In this case '\n                              'instead note the value in jumping_factor.txt, delete the '\n                              'file, and pass the value with flag -f <value>. This warning '\n                              'may then appear again, but you can safely disregard it.')\n            else:\n                # For restart runs we want to save the input jumping factor\n                # as starting jumping factor, but continue from the jumping\n                # factor stored in the file.\n                starting_jumping_factor = data.jumping_factor\n                # This will load the value irrespective of whether it starts\n                # with # (i.e. the jumping factor adaptation was started) or not.\n                jump_value = jump_file.read().replace('# ','')\n                data.jumping_factor = float(jump_value)\n            jump_file.close()\n            print('rank = ',rank)\n        except:\n            jump_file = open(command_line.folder + '/jumping_factor.txt','w')\n            jump_file.write(str(data.jumping_factor))\n            jump_file.close()\n            rank = 0\n            print('rank = ',rank)\n            starting_jumping_factor = data.jumping_factor\n\n    # Recover the covariance matrix according to the input, if the varying set\n    # of parameters is non-zero\n    if (data.get_mcmc_parameters(['varying']) != []):\n\n        # Read input covariance matrix\n        sigma_eig, U, C = sampler.get_covariance_matrix(cosmo, data, command_line)\n\n        # if we want to compute the starting point by minimising lnL (instead of taking it from input file or bestfit file)\n        minimum = 0\n        if command_line.minimize:\n            minimum, min_chi2 = sampler.get_minimum(cosmo, data, command_line, C)\n\n            parameter_names = data.get_mcmc_parameters(['last_accepted'])\n            for index,elem in parameter_names:\n                data.mcmc_parameters[elem]['last_accepted'] = minimum[index]\n\n            #FK: write out the results of the minimzer:\n            labels = data.get_mcmc_parameters(['varying'])\n            fname = os.path.join(command_line.folder, 'results.minimized')\n            with open(fname, 'w') as f:\n                f.write('# minimized \\chi^2 = {:} \\n'.format(min_chi2))\n                f.write('# %s\\n' % ', '.join(['%16s' % label for label in labels]))\n                for idx in range(len(labels)):\n                    bf_value = minimum[idx]\n                    if bf_value > 0:\n                        f.write(' %.6e\\t' % bf_value)\n                    else:\n                        f.write('%.6e\\t' % bf_value)\n                f.write('\\n')\n            print('Results of minimizer saved to: \\n', fname)\n\n        # if we want to compute Fisher matrix and then stop\n        if command_line.fisher:\n            sampler.get_fisher_matrix(cosmo, data, command_line, C, minimum)\n            return\n\n        # warning if no jumps are requested\n        if data.jumping_factor == 0:\n            warnings.warn(\n                \"The jumping factor has been set to 0. The above covariance \" +\n                \"matrix will not be used.\")\n\n    # In case of a fiducial run (all parameters fixed), simply run once and\n    # print out the likelihood. This should not be used any more (one has to\n    # modify the log.param, which is never a good idea. Instead, force the code\n    # to use a jumping factor of 0 with the option \"-f 0\".\n    else:\n        warnings.warn(\n            \"You are running with no varying parameters... I will compute \" +\n            \"only one point and exit\")\n        data.update_cosmo_arguments()  # this fills in the fixed parameters\n        loglike = sampler.compute_lkl(cosmo, data)\n        io_mp.print_vector(outputs, 1, loglike, data)\n        return 1, loglike\n\n    # In the fast-slow method, one need the Cholesky decomposition of the\n    # covariance matrix. Return the Cholesky decomposition as a lower\n    # triangular matrix\n    Cholesky = None\n    Rotation = None\n    if command_line.jumping == 'fast':\n        Cholesky = la.cholesky(C).T\n        Rotation = np.identity(len(sigma_eig))\n\n    # define path and covmat\n    input_covmat = command_line.cov\n    base = os.path.basename(command_line.folder)\n    # the previous line fails when \"folder\" is a string ending with a slash. This issue is cured by the next lines:\n    if base == '':\n        base = os.path.basename(command_line.folder[:-1])\n    command_line.cov = os.path.join(\n        command_line.folder, base+'.covmat')\n\n    # Fast Parameter Multiplier (fpm) for adjusting update and superupdate numbers.\n    # This is equal to N_slow + f_fast N_fast, where N_slow is the number of slow\n    # parameters, f_fast is the over sampling number for each fast block and f_fast\n    # is the number of parameters in each fast block.\n    for i in range(len(data.block_parameters)):\n        if i == 0:\n            fpm = data.over_sampling[i]*data.block_parameters[i]\n        else:\n            fpm += data.over_sampling[i]*(data.block_parameters[i] - data.block_parameters[i-1])\n\n    # If the update mode was selected, the previous (or original) matrix should be stored\n    if command_line.update:\n        if not rank and not command_line.silent:\n            print('Update routine is enabled with value %d (recommended: 50)' % command_line.update)\n            print('This number is rescaled by cycle length %d (N_slow + f_fast * N_fast) to %d' % (fpm,fpm*command_line.update))\n        # Rescale update number by cycle length N_slow + f_fast * N_fast to account for fast parameters\n        command_line.update *= fpm\n        previous = (sigma_eig, U, C, Cholesky)\n\n    # Initialise adaptive\n    if command_line.adaptive:\n        if not command_line.silent:\n            print('Adaptive routine is enabled with value %d (recommended: 10*dimension)' % command_line.adaptive)\n            print('and adaptive_ts = %d (recommended: 100*dimension)' % command_line.adaptive_ts)\n            print('Please note: current implementation not suitable for multiple chains')\n        if rank > 0:\n            raise io_mp.ConfigurationError('Adaptive routine not compatible with MPI')\n        if command_line.update:\n            warnings.warn('Adaptive routine not compatible with update, overwriting input update value')\n        if command_line.superupdate:\n            warnings.warn('Adaptive routine not compatible with superupdate, deactivating superupdate')\n            command_line.superupdate = 0\n        # Define needed parameters\n        parameter_names = data.get_mcmc_parameters(['varying'])\n        mean = np.zeros(len(parameter_names))\n        last_accepted = np.zeros(len(parameter_names),'float64')\n        ar = np.zeros(100)\n        if command_line.cov == None:\n            # If no input covmat was given, the starting jumping factor\n            # should be very small until a covmat is obtained and the\n            # original start jumping factor should be saved\n            start_jumping_factor = command_line.jumping_factor\n            data.jumping_factor = command_line.jumping_factor/100.\n            # Analyze module will be forced to compute one covmat,\n            # after which update flag will be set to False.\n            command_line.update = command_line.adaptive\n        else:\n            # If an input covmat was provided, take mean values from param file\n            # Question: is it better to always do this, rather than setting mean\n            # to last accepted after the initial update run?\n            for elem in parameter_names:\n                mean[parameter_names.index(elem)] = data.mcmc_parameters[elem]['initial'][0]\n\n    # Initialize superupdate\n    if command_line.superupdate:\n        if not rank and not command_line.silent:\n            print('Superupdate routine is enabled with value %d (recommended: 20)' % command_line.superupdate)\n            if command_line.superupdate < 20:\n                warnings.warn('Superupdate value lower than the recommended value. This '\n                              'may increase the risk of poorly converged acceptance rate')\n            print('This number is rescaled by cycle length %d (N_slow + f_fast * N_fast) to %d' % (fpm,fpm*command_line.superupdate))\n        # Rescale superupdate number by cycle length N_slow + f_fast * N_fast to account for fast parameters\n        command_line.superupdate *= fpm\n        # Define needed parameters\n        parameter_names = data.get_mcmc_parameters(['varying'])\n        updated_steps = 0\n        stop_c = False\n        jumping_factor_rescale = 0\n        if command_line.restart:\n            try:\n                jump_file = open(command_line.cov,'r')\n                jumping_factor_rescale = 1\n            except:\n                jumping_factor_rescale = 0\n        c_array = np.zeros(command_line.superupdate) # Allows computation of mean of jumping factor\n        R_minus_one = np.array([100.,100.]) # 100 to make sure max(R-1) value is high if computation failed\n        # Local acceptance rate of last SU*(N_slow + f_fast * N_fast) steps\n        ar = np.zeros(command_line.superupdate)\n        # Store acceptance rate of last 5*SU*(N_slow + f_fast * N_fast) steps\n        backup_ar = np.zeros(5*command_line.superupdate)\n        # Make sure update is enabled\n        if command_line.update == 0:\n            if not rank and not command_line.silent:\n                print('Update routine required by superupdate. Setting --update 50')\n                print('This number is then rescaled by cycle length: %d (N_slow + f_fast * N_fast)' % fpm)\n            command_line.update = 50 * fpm\n            previous = (sigma_eig, U, C, Cholesky)\n\n    # If restart wanted, pick initial value for arguments\n    if command_line.restart is not None:\n        sampler.read_args_from_chain(data, command_line.restart)\n\n    # If restart from best fit file, read first point (overwrite settings of\n    # read_args_from_chain)\n    if command_line.bf is not None and not command_line.minimize:\n        sampler.read_args_from_bestfit(data, command_line.bf)\n\n    # Pick a position (from last accepted point if restart, from the mean value\n    # else), with a 100 tries.\n    for i in range(100):\n        if get_new_position(data, sigma_eig, U, i,\n                            Cholesky, Rotation) is True:\n            break\n        if i == 99:\n            raise io_mp.ConfigurationError(\n                \"You should probably check your prior boundaries... because \" +\n                \"no valid starting position was found after 100 tries\")\n\n    # Compute the starting Likelihood\n    loglike = sampler.compute_lkl(cosmo, data)\n\n    # Choose this step as the last accepted value\n    # (accept_step), and modify accordingly the max_loglike\n    sampler.accept_step(data)\n    max_loglike = loglike\n\n    # If the jumping factor is 0, the likelihood associated with this point is\n    # displayed, and the code exits.\n    if data.jumping_factor == 0:\n        io_mp.print_vector(outputs, 1, loglike, data)\n        return 1, loglike\n\n    acc, rej = 0.0, 0.0  # acceptance and rejection number count\n    N = 1   # number of time the system stayed in the current position\n\n    # Print on screen the computed parameters\n    if not command_line.silent and not command_line.quiet:\n        io_mp.print_parameters(sys.stdout, data)\n\n    # Suppress non-informative output after initializing\n    command_line.quiet = True\n\n    k = 1\n    # Main loop, that goes on while the maximum number of failure is not\n    # reached, and while the expected amount of steps (N) is not taken.\n    while k <= command_line.N:\n        # If the number of steps reaches the number set in the adaptive method plus one,\n        # then the proposal distribution should be gradually adapted.\n        # If the number of steps also exceeds the number set in adaptive_ts,\n        # the jumping factor should be gradually adapted.\n        if command_line.adaptive and k>command_line.adaptive+1:\n            # Start of adaptive routine\n            # By B. Schroer and T. Brinckmann\n            # Modified version of the method outlined in the PhD thesis of Marta Spinelli\n\n            # Store last accepted step\n            for elem in parameter_names:\n                last_accepted[parameter_names.index(elem)] = data.mcmc_parameters[elem]['last_accepted']\n            # Recursion formula for mean and covmat (and jumping factor after ts steps)\n            # mean(k) = mean(k-1) + (last_accepted - mean(k-1))/k\n            mean += 1./k*(last_accepted-mean)\n            # C(k) = C(k-1) + [(last_accepted - mean(k))^T * (last_accepted - mean(k)) - C(k-1)]/k\n            C +=1./k*(np.dot(np.transpose(np.asmatrix(last_accepted-mean)),np.asmatrix(last_accepted-mean))-C)\n            sigma_eig, U = np.linalg.eig(np.linalg.inv(C))\n            if command_line.jumping == 'fast':\n                Cholesky = la.cholesky(C).T\n            if k>command_line.adaptive_ts:\n                # c = j^2/d\n                c = data.jumping_factor**2/len(parameter_names)\n                # c(k) = c(k-1) + [acceptance_rate(last 100 steps) - 0.25]/k\n                c +=(np.mean(ar)-0.25)/k\n                data.jumping_factor = np.sqrt(len(parameter_names)*c)\n\n            # Save the covariance matrix and the jumping factor in a file\n            # For a possible MPI implementation\n            #if not (k-command_line.adaptive) % 5:\n            #    io_mp.write_covariance_matrix(C,parameter_names,str(command_line.cov))\n            #    jump_file = open(command_line.folder + '/jumping_factor.txt','w')\n            #    jump_file.write(str(data.jumping_factor))\n            #    jump_file.close()\n            # End of adaptive routine\n\n        # If the number of steps reaches the number set in the update method,\n        # then the proposal distribution should be adapted.\n        if command_line.update:\n            # Start of update routine\n            # By M. Ballardini and T. Brinckmann\n            # Also used by superupdate and adaptive\n\n            # master chain behavior\n            if not rank:\n                # Add the folder to the list of files to analyze, and switch on the\n                # options for computing only the covmat\n                from parser_mp import parse\n                info_command_line = parse(\n                    'info %s --minimal --noplot --keep-fraction 0.5 --keep-non-markovian --want-covmat' % command_line.folder)\n                info_command_line.update = command_line.update\n\n                if command_line.adaptive:\n                    # Keep all points for covmat guess in adaptive\n                    info_command_line = parse('info %s --minimal --noplot --keep-non-markovian --want-covmat' % command_line.folder)\n                    # Tell the analysis to update the covmat after t0 steps if it is adaptive\n                    info_command_line.adaptive = command_line.adaptive\n                    # Only compute covmat if no input covmat was provided\n                    if input_covmat != None:\n                        info_command_line.want_covmat = False\n\n                # This is in order to allow for more frequent R-1 computation with superupdate\n                compute_R_minus_one = False\n                if command_line.superupdate:\n                    if not (k+10) % command_line.superupdate:\n                        compute_R_minus_one = True\n                # the +10 below is here to ensure that the first master update will take place before the first slave updates,\n                # but this is a detail, the code is robust against situations where updating is not possible, so +10 could be omitted\n                if (not (k+10) % command_line.update or compute_R_minus_one) and k > 10:\n                    # Try to launch an analyze (computing a new covmat if successful)\n                    try:\n                        if not (k+10) % command_line.update:\n                            from .analyze import analyze\n                            R_minus_one = analyze(info_command_line)\n                        elif command_line.superupdate:\n                            # Compute (only, i.e. no covmat) R-1 more often when using superupdate\n                            info_command_line = parse(\n                                'info %s --minimal --noplot --keep-fraction 0.5 --keep-non-markovian' % command_line.folder)\n                            info_command_line.update = command_line.update\n                            R_minus_one = analyze(info_command_line)\n                    except:\n                        if not command_line.silent:\n                            print('Step ',k,' chain ', rank,': Failed to calculate covariance matrix')\n\n                if command_line.superupdate:\n                    # Start of superupdate routine\n                    # By B. Schroer and T. Brinckmann\n\n                    c_array[(k-1)%(command_line.superupdate)] = data.jumping_factor\n\n                    # If acceptance rate deviates too much from the target acceptance\n                    # rate we want to resume adapting the jumping factor\n                    # T. Brinckmann 02/2019: use mean a.r. over the last 5*len(ar) steps\n                    # instead or the over last len(ar), which is more stable\n                    if abs(np.mean(backup_ar) - command_line.superupdate_ar) > 5.*command_line.superupdate_ar_tol:\n                        stop_c = False\n\n                    # Start adapting the jumping factor after command_line.superupdate steps if R-1 < 10\n                    # The lower R-1 criterium is an arbitrary choice to keep from updating when the R-1\n                    # calculation fails (i.e. returns only zeros).\n                    if (k > updated_steps + command_line.superupdate) and 0.01 < (max(R_minus_one) < 10.) and not stop_c:\n                        c = data.jumping_factor**2/len(parameter_names)\n                        # To avoid getting trapped in local minima, the jumping factor should\n                        # not go below 0.1 (arbitrary) times the starting jumping factor.\n                        if (c + (np.mean(ar) - command_line.superupdate_ar)/(k - updated_steps)) > (0.1*starting_jumping_factor)**2./len(parameter_names) or ((np.mean(ar) - command_line.superupdate_ar)/(k - updated_steps) > 0):\n                            c += (np.mean(ar) - command_line.superupdate_ar)/(k - updated_steps)\n                            data.jumping_factor = np.sqrt(len(parameter_names) * c)\n\n                        if not (k-1) % 5:\n                            # Check if the jumping factor adaptation should stop.\n                            # An acceptance rate of 25% balances the wish for more accepted\n                            # points, while ensuring the parameter space is properly sampled.\n                            # The convergence criterium is by default (26+/-1)%, so the adaptation\n                            # will stop when the code reaches an acceptance rate of at least 25%.\n                            # T. Brinckmann 02/2019: use mean a.r. over the last 5*len(ar) steps\n                            # instead or the over last len(ar), which is more stable\n                            if (max(R_minus_one) < 0.4) and (abs(np.mean(backup_ar) - command_line.superupdate_ar) < command_line.superupdate_ar_tol) and (abs(np.mean(c_array)/c_array[(k-1) % (command_line.superupdate)] - 1) < 0.01):\n                                stop_c = True\n                                data.out.write('# After %d accepted steps: stop adapting the jumping factor at a value of %f with a local acceptance rate %f \\n' % (int(acc),data.jumping_factor,np.mean(backup_ar)))\n                                if not command_line.silent:\n                                    print('After %d accepted steps: stop adapting the jumping factor at a value of %f with a local acceptance rate of %f \\n' % (int(acc), data.jumping_factor,np.mean(backup_ar)))\n                                jump_file = open(command_line.folder + '/jumping_factor.txt','w')\n                                jump_file.write('# '+str(data.jumping_factor))\n                                jump_file.close()\n                            else:\n                                jump_file = open(command_line.folder + '/jumping_factor.txt','w')\n                                jump_file.write(str(data.jumping_factor))\n                                jump_file.close()\n\n                    # Write the evolution of the jumping factor to a file\n                    if not k % (command_line.superupdate):\n                        jump_file = open(command_line.folder + '/jumping_factors.txt','a')\n                        for i in range(command_line.superupdate):\n                            jump_file.write(str(c_array[i])+'\\n')\n                        jump_file.close()\n                    # End of main part of superupdate routine\n\n                if not (k-1) % (command_line.update/3):\n                    try:\n                        # Read the covmat\n                        sigma_eig, U, C = sampler.get_covariance_matrix(\n                            cosmo, data, command_line)\n                        if command_line.jumping == 'fast':\n                            Cholesky = la.cholesky(C).T\n                        # Test here whether the covariance matrix has really changed\n                        # We should in principle test all terms, but testing the first one should suffice\n                        if not C[0,0] == previous[2][0,0]:\n                            if k == 1:\n                                if not command_line.silent:\n                                    if not input_covmat == None:\n                                        warnings.warn(\n                                            'Appending to an existing folder: using %s instead of %s. '\n                                            'If new input covmat is desired, please delete previous covmat.'\n                                            % (command_line.cov, input_covmat))\n                                    else:\n                                        warnings.warn(\n                                            'Appending to an existing folder: using %s. '\n                                            'If no starting covmat is desired, please delete previous covmat.'\n                                            % command_line.cov)\n                            else:\n                                # Start of second part of superupdate routine\n                                if command_line.superupdate:\n                                    # Adaptation of jumping factor should start again after the covmat is updated\n                                    # Save the step number after it updated for superupdate and start adaption of c again\n                                    updated_steps = k\n                                    stop_c = False\n                                    cov_det = np.linalg.det(C)\n                                    prev_cov_det = np.linalg.det(previous[2])\n                                    # Rescale jumping factor in order to keep the magnitude of the jumps the same.\n                                    # Skip this update the first time the covmat is updated in order to prevent\n                                    # problems due to a poor initial covmat. Rescale the jumping factor after the\n                                    # first calculated covmat to the expected optimal one of 2.4.\n                                    if jumping_factor_rescale:\n                                        new_jumping_factor = data.jumping_factor * (prev_cov_det/cov_det)**(1./(2 * len(parameter_names)))\n                                        data.out.write('# After %d accepted steps: rescaled jumping factor from %f to %f, due to updated covariance matrix \\n' % (int(acc), data.jumping_factor, new_jumping_factor))\n                                        if not command_line.silent:\n                                            print('After %d accepted steps: rescaled jumping factor from %f to %f, due to updated covariance matrix \\n' % (int(acc), data.jumping_factor, new_jumping_factor))\n                                        data.jumping_factor = new_jumping_factor\n                                    else:\n                                        data.jumping_factor = starting_jumping_factor\n                                    jumping_factor_rescale += 1\n                                # End of second part of superupdate routine\n\n                                # Write to chains file when the covmat was updated\n                                data.out.write('# After %d accepted steps: update proposal with max(R-1) = %f and jumping factor = %f \\n' % (int(acc), max(R_minus_one), data.jumping_factor))\n                                if not command_line.silent:\n                                    print('After %d accepted steps: update proposal with max(R-1) = %f and jumping factor = %f \\n' % (int(acc), max(R_minus_one), data.jumping_factor))\n                                try:\n                                    if stop_after_update:\n                                        k = command_line.N\n                                        print('Covariance matrix updated - stopping run')\n                                except:\n                                    pass\n\n                            previous = (sigma_eig, U, C, Cholesky)\n                    except:\n                        pass\n\n                    command_line.quiet = True\n\n                    # Start of second part of adaptive routine\n                    # Stop updating the covmat after t0 steps in adaptive\n                    if command_line.adaptive and k > 1:\n                        command_line.update = 0\n                        data.jumping_factor = start_jumping_factor\n                        # Test if there are still enough steps left before the adaption of the jumping factor starts\n                        if k > 0.5*command_line.adaptive_ts:\n                            command_line.adaptive_ts += k\n                        # Set the mean for the recursion formula to the last accepted point\n                        for elem in parameter_names:\n                            mean[parameter_names.index(elem)] = data.mcmc_parameters[elem]['last_accepted']\n                    # End of second part of adaptive routine\n\n            # slave chain behavior\n            else:\n                # Start of slave superupdate routine\n                if command_line.superupdate:\n                    # If acceptance rate deviates too much from the target acceptance\n                    # rate we want to resume adapting the jumping factor. This line\n                    # will force the slave chains to check if the jumping factor\n                    # has been updated\n                    if abs(np.mean(backup_ar) - command_line.superupdate_ar) > 5.*command_line.superupdate_ar_tol:\n                        stop_c = False\n\n                    # Update the jumping factor every 5 steps in superupdate\n                    if not k % 5 and k > command_line.superupdate and command_line.superupdate and (not stop_c or (stop_c and k % command_line.update)):\n                        try:\n                            jump_file = open(command_line.folder + '/jumping_factor.txt','r')\n                            # If there is a # in the file, the master has stopped adapting c\n                            for line in jump_file:\n                                if line.find('#') == -1:\n                                    jump_file.seek(0)\n                                    jump_value = jump_file.read()\n                                    data.jumping_factor = float(jump_value)\n                                else:\n                                    jump_file.seek(0)\n                                    jump_value = jump_file.read().replace('# ','')\n                                    #if not stop_c or (stop_c and not float(jump_value) == data.jumping_factor):\n                                    if not float(jump_value) == data.jumping_factor:\n                                        data.jumping_factor = float(jump_value)\n                                        stop_c = True\n                                        data.out.write('# After %d accepted steps: stop adapting the jumping factor at a value of %f with a local acceptance rate %f \\n' % (int(acc),data.jumping_factor,np.mean(backup_ar)))\n                                        if not command_line.silent:\n                                            print('After %d accepted steps: stop adapting the jumping factor at a value of %f with a local acceptance rate of %f \\n' % (int(acc), data.jumping_factor,np.mean(backup_ar)))\n                            jump_file.close()\n                        except:\n                            if not command_line.silent:\n                                print('Reading jumping_factor file failed')\n                            pass\n                # End of slave superupdate routine\n\n                # Start of slave update routine\n                if not (k-1) % (command_line.update/10):\n                    try:\n                        sigma_eig, U, C = sampler.get_covariance_matrix(\n                            cosmo, data, command_line)\n                        if command_line.jumping == 'fast':\n                            Cholesky = la.cholesky(C).T\n                        # Test here whether the covariance matrix has really changed\n                        # We should in principle test all terms, but testing the first one should suffice\n                        if not C[0,0] == previous[2][0,0] and not k == 1:\n                            if command_line.superupdate:\n                                # If the covmat was updated, the master has resumed adapting c\n                                stop_c = False\n                            data.out.write('# After %d accepted steps: update proposal \\n' % int(acc))\n                            if not command_line.silent:\n                                print('After %d accepted steps: update proposal \\n' % int(acc))\n                            try:\n                                if stop_after_update:\n                                    k = command_line.N\n                                    print('Covariance matrix updated - stopping run')\n                            except:\n                                pass\n                        previous = (sigma_eig, U, C, Cholesky)\n\n                    except:\n                        pass\n                # End of slave update routine\n            # End of update routine\n\n        # Pick a new position ('current' flag in mcmc_parameters), and compute\n        # its likelihood. If get_new_position returns True, it means it did not\n        # encounter any boundary problem. Otherwise, just increase the\n        # multiplicity of the point and start the loop again\n        if get_new_position(\n                data, sigma_eig, U, k, Cholesky, Rotation) is True:\n            newloglike = sampler.compute_lkl(cosmo, data)\n        else:  # reject step\n            rej += 1\n            if command_line.superupdate:\n                        ar[k%len(ar)] = 0 # Local acceptance rate of last SU*(N_slow + f_fast * N_fast) steps\n            elif command_line.adaptive:\n                ar[k%len(ar)] = 0 # Local acceptance rate of last 100 steps\n            N += 1\n            k += 1\n            continue\n\n        # Harmless trick to avoid exponentiating large numbers. This decides\n        # whether or not the system should move.\n        if (newloglike != data.boundary_loglike):\n            if (newloglike >= loglike):\n                alpha = 1.\n            else:\n                alpha = np.exp(newloglike-loglike)\n        else:\n            alpha = -1\n\n        if ((alpha == 1.) or (rd.uniform(0, 1) < alpha)):  # accept step\n\n            # Print out the last accepted step (WARNING: this is NOT the one we\n            # just computed ('current' flag), but really the previous one.)\n            # with its proper multiplicity (number of times the system stayed\n            # there).\n            io_mp.print_vector(outputs, N, loglike, data)\n\n            # Report the 'current' point to the 'last_accepted'\n            sampler.accept_step(data)\n            loglike = newloglike\n            if loglike > max_loglike:\n                max_loglike = loglike\n            acc += 1.0\n            N = 1  # Reset the multiplicity\n            if command_line.superupdate:\n                ar[k%len(ar)] = 1 # Local acceptance rate of last SU*(N_slow + f_fast * N_fast) steps\n            elif command_line.adaptive:\n                ar[k%len(ar)] = 1 # Local acceptance rate of last 100 steps\n        else:  # reject step\n            rej += 1.0\n            N += 1  # Increase multiplicity of last accepted point\n            if command_line.superupdate:\n                ar[k%len(ar)] = 0 # Local acceptance rate of last SU*(N_slow + f_fast * N_fast) steps\n            elif command_line.adaptive:\n                ar[k%len(ar)] = 0 # Local acceptance rate of last 100 steps\n\n        # Store a.r. for last 5 x SU*(N_slow + f_fast * N_fast) steps\n        if command_line.superupdate:\n            backup_ar[k%len(backup_ar)] = ar[k%len(ar)]\n\n        # Regularly (option to set in parameter file), close and reopen the\n        # buffer to force to write on file.\n        if acc % data.write_step == 0:\n            io_mp.refresh_file(data)\n            # Update the outputs list\n            outputs[0] = data.out\n        k += 1  # One iteration done\n    # END OF WHILE LOOP\n\n    # If at this moment, the multiplicity is higher than 1, it means the\n    # current point is not yet accepted, but it also mean that we did not print\n    # out the last_accepted one yet. So we do.\n    if N > 1:\n        io_mp.print_vector(outputs, N-1, loglike, data)\n\n    # Print out some information on the finished chain\n    rate = acc / (acc + rej)\n    sys.stdout.write('\\n#  {0} steps done, acceptance rate: {1}\\n'.\n                     format(command_line.N, rate))\n\n    # In case the acceptance rate is too low, or too high, print a warning\n    if rate < 0.05:\n        warnings.warn(\"The acceptance rate is below 0.05. You might want to \"\n                      \"set the jumping factor to a lower value than the \"\n                      \"default (2.4), with the option `-f 1.5` for instance.\")\n    elif rate > 0.6:\n        warnings.warn(\"The acceptance rate is above 0.6, which means you might\"\n                      \" have difficulties exploring the entire parameter space\"\n                      \". Try analysing these chains, and use the output \"\n                      \"covariance matrix to decrease the acceptance rate to a \"\n                      \"value between 0.2 and 0.4 (roughly).\")\n    # For a restart, erase the starting point to keep only the new, longer\n    # chain.\n    if command_line.restart is not None:\n        os.remove(command_line.restart)\n        sys.stdout.write('    deleting starting point of the chain {0}\\n'.\n                         format(command_line.restart))\n\n    return\n", "meta": {"hexsha": "72ef4e3192cfd2028e0952ae6cd345b119947cf0", "size": 45588, "ext": "py", "lang": "Python", "max_stars_repo_path": "montepython/mcmc.py", "max_stars_repo_name": "ivandebono/montepython_public_3.2dev_Python3", "max_stars_repo_head_hexsha": "16771c3d37faaa3f80b171c01d78da56a75aa3d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "montepython/mcmc.py", "max_issues_repo_name": "ivandebono/montepython_public_3.2dev_Python3", "max_issues_repo_head_hexsha": "16771c3d37faaa3f80b171c01d78da56a75aa3d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "montepython/mcmc.py", "max_forks_repo_name": "ivandebono/montepython_public_3.2dev_Python3", "max_forks_repo_head_hexsha": "16771c3d37faaa3f80b171c01d78da56a75aa3d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.3398392652, "max_line_length": 233, "alphanum_fraction": 0.5793849259, "include": true, "reason": "import numpy,import scipy", "num_tokens": 9573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.19260688771242962}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport astropy.units as u\nimport math\nfrom eventio.simtel.simtelfile import SimTelFile\nfrom .plot_utils import sens_plot, sens_minimization_plot, plot_positions_survived_events\nfrom .mc import rate, weight, power_law_integrated_distribution\nfrom lstchain.spectra.crab import crab_hegra, crab_magic\nfrom lstchain.spectra.proton import proton_bess\nfrom gammapy.stats.poisson import excess_matching_significance_on_off\nfrom lstchain.reco.utils import reco_source_position_sky\nfrom  astropy.coordinates.angle_utilities import angular_separation\nfrom astropy.coordinates import SkyCoord\nfrom lstchain.io import read_simu_info_merged_hdf5\nfrom lstchain.reco import dl1_to_dl2\n\nfrom lstchain.reco import dl1_to_dl2\n\n__all__ = ['read_sim_par',\n           'process_mc',\n           'calculate_sensitivity',\n           'calculate_sensitivity_lima',\n           'calculate_sensitivity_lima_1d',\n           'bin_definition',\n           'ring_containment',\n           'find_best_cuts_sens',\n           'sens',\n           ]\n\ndef read_sim_par(dl1_file):\n    \"\"\"\n    Read MC simulated parameters\n\n    Parameters\n    ---------\n    source: simtelarray file\n\n    Returns\n    ---------\n    par: `dict` with simulated parameters\n\n    \"\"\"\n    simu_info = read_simu_info_merged_hdf5(dl1_file)\n    emin = simu_info.energy_range_min\n    emax = simu_info.energy_range_max\n    sp_idx = simu_info.spectral_index\n    sim_ev = simu_info.num_showers * simu_info.shower_reuse\n    area_sim = (simu_info.max_scatter_range - simu_info.min_scatter_range)**2 * np.pi\n    cone = simu_info.max_viewcone_radius\n\n    par_var = [emin, emax, sp_idx, sim_ev, area_sim, cone]\n    par_dic = ['emin', 'emax', 'sp_idx', 'sim_ev', 'area_sim', 'cone']\n    par = dict(zip(par_dic, par_var))\n\n    return par\n\ndef process_mc(dl1_file, dl2_file, mc_type):\n    \"\"\"\n    Process the MC simulated and reconstructed to extract the relevant\n    parameters to compute the sensitivity\n\n    Paramenters\n    ---------\n    simtel: simtelarray file\n    dl2_file: `pandas.DataFrame` dl2 parameters\n    mc_type: 'string' type of particle\n\n    Returns\n    ---------\n    gammaness: `numpy.ndarray`\n    angdist2:  `numpy.ndarray` angular distance squared\n    e_reco:    `numpy.ndarray` reconstructed energies\n    n_reco:    `int` number of reconstructed events\n    mc_par:    `dict` with simulated parameters\n\n    \"\"\"\n    sim_par = read_sim_par(dl1_file)\n    events = pd.read_hdf(dl2_file)\n\n    #Filters:\n\n    filter_good_events =  (events.leakage < 0.2) & \\\n                          (events.intensity > np.log10(200)) & \\\n                          (events.wl > 0.1) & \\\n                          (events.tel_id==1)\n\n    events = events[filter_good_events]\n\n    e_reco = 10**events.mc_energy.to_numpy() * u.GeV\n    e_true = 10**events.mc_energy.to_numpy() * u.GeV\n\n    gammaness = events.gammaness\n\n    #Get source position in radians\n\n    #focal_length = source.telescope_descriptions[1]['camera_settings']['focal_length'] * u.m\n    focal_length = 28 * u.m\n\n    # If the particle is a gamma ray, it returns the squared angular distance\n    # from the reconstructed gamma-ray position and the simulated incoming position\n    if mc_type=='gamma':\n        events = events[events.mc_type==0]\n        alt2 = events.mc_alt\n        az2 = np.arctan(np.tan(events.mc_az))\n\n    # If the particle is not a gamma-ray (diffuse protons/electrons), it returns\n    # the squared angular distance of the reconstructed position w.r.t. the\n    # center of the camera\n    else:\n        events = events[events.mc_type!=0]\n        alt2 = events.mc_alt_tel\n        az2 = np.arctan(np.tan(events.mc_az_tel))\n\n    src_pos_reco = reco_source_position_sky(events.x.values * u.m,\n                                            events.y.values * u.m,\n                                            events.reco_disp_dx.values * u.m,\n                                            events.reco_disp_dy.values * u.m,\n                                            focal_length,\n                                            events.mc_alt_tel.values * u.rad,\n                                            events.mc_az_tel.values * u.rad)\n\n    alt1 = src_pos_reco.alt.rad\n    az1 = np.arctan(np.tan(src_pos_reco.az.rad))\n\n    angdist2 = (angular_separation(az1, alt1, az2, alt2).to_numpy() * u.rad)**2\n    events['theta2'] = angdist2\n\n    return gammaness, angdist2.to(u.deg**2), e_reco, e_true, sim_par, events\n\n\ndef calculate_sensitivity(nex, nbg, alpha):\n    \"\"\"\n    Sensitivity calculation using nex/sqrt(nbg)\n\n    Parameters\n    ---------\n    nex:   `float` number of excess events in the signal region\n    nbg:   `float` number of events in the background region\n    alpha: `float` inverse of the number of off positions\n\n    Returns\n    ---------\n    sens: `float` in percentage of Crab units\n    \"\"\"\n    significance = nex / np.sqrt(nbg * alpha)\n    sens = 5 / significance * 100  # percentage of Crab\n\n    return sens\n\ndef calculate_sensitivity_lima(nex, nbg, alpha, eb, gb, tb):\n    \"\"\"\n    Sensitivity calculation using the Li & Ma formula\n    eq. 17 of Li & Ma (1983).\n    https://ui.adsabs.harvard.edu/abs/1983ApJ...272..317L/abstract\n\n    Parameters\n    ---------\n    nex:   `float` number of excess events in the signal region\n    nbg:   `float` number of events in the background region\n    alpha: `float` inverse of the number of off positions\n\n    Returns\n    ---------\n    sens: `float` in percentage of Crab units\n    \"\"\"\n    nex_5sigma = excess_matching_significance_on_off(\\\n        n_off=nbg,alpha=alpha,significance=5,method='lima')\n\n    for i in range(0, eb):\n        for j in range(0, gb):\n            for k in range(0, tb):\n                if nex_5sigma[i][j][k] < 10:\n                    nex_5sigma[i][j][k] = 10\n                if nex_5sigma[i,j,k] < 0.05 * nbg[i][j][k]/5:\n                    nex_5sigma[i,j,k] = 0.05 * nbg[i][j][k]/5\n\n    sens = nex_5sigma / nex * 100  # percentage of Crab\n\n    return nex_5sigma, sens\n\ndef calculate_sensitivity_lima_1d(nex, nbg, alpha, eb):\n    \"\"\"\n    Sensitivity calculation using the Li & Ma formula\n    eq. 17 of Li & Ma (1983).\n    https://ui.adsabs.harvard.edu/abs/1983ApJ...272..317L/abstract\n\n    Parameters\n    ---------\n    nex:   `float` number of excess events in the signal region\n    nbg:   `float` number of events in the background region\n    alpha: `float` inverse of the number of off positions\n\n    Returns\n    ---------\n    sens: `float` in percentage of Crab units\n    \"\"\"\n    nex_5sigma = excess_matching_significance_on_off(\\\n        n_off=nbg,alpha=alpha,significance=5,method='lima')\n\n    for i in range(0, eb):\n                if nex_5sigma[i] < 10:\n                    nex_5sigma[i] = 10\n                if nex_5sigma[i] < 0.05 * nbg[i]/5:\n                    nex_5sigma[i] = 0.05 * nbg[i]/5\n\n    sens = nex_5sigma / nex * 100  # percentage of Crab\n\n    return nex_5sigma, sens\n\ndef bin_definition(gb, tb):\n    \"\"\"\n    Define binning in gammaness and theta2 for the\n    optimization of the sensitivity\n\n    Parameters\n    ---------\n    gb:   `int` number of bins in gammaness\n    tb:   `int` number of bins in theta2\n\n    Returns\n    ---------\n    g, t: `numpy.ndarray` binning of gammaness and theta2\n    \"\"\"\n    max_gam = 1\n    max_th2 = 0.05 * u.deg * u.deg\n    min_th2 = 0.005 * u.deg * u.deg\n\n    g = np.linspace(0, max_gam, gb)\n    t = np.linspace(min_th2, max_th2, tb)\n\n    ####TEST####\n    #g = np.full(gb, 0.0)\n    #t = np.linspace(10*u.deg*u.deg, 10*u.deg*u.deg, tb)\n    ###########\n    \n    return g, t\n\ndef ring_containment(angdist2, ring_radius, ring_halfwidth):\n    \"\"\"\n    Calculate containment of cosmic ray particles with reconstructed positions\n    within a ring of radius=ring_radius and half width=ring_halfwidth\n    Parameters\n    ---------\n    angdist2:       `numpy.ndarray` angular distance squared w.r.t.\n                    the center of the camera\n    ring_radius:    `float` ring radius\n    ring_halfwidth: `float` halfwidth of the ring\n\n    Returns\n    ---------\n    contained: `numpy.ndarray` bool array\n    area: angular area of the ring\n    \"\"\"\n    ring_lower_limit = ring_radius - ring_halfwidth\n    ring_upper_limit = np.sqrt(2 * (ring_radius**2) - (ring_lower_limit)**2)\n\n    area = np.pi * (ring_upper_limit**2 - ring_lower_limit**2)\n    # For the two halfwidths to cover the same area, compute the area of\n    # the internal and external rings:\n    # A_internal = pi * ((ring_radius**2) - (ring_lower_limit)**2)\n    # A_external = pi * ((ring_upper_limit**2) - (ring_radius)**2)\n    # The areas should be equal, so we can extract the ring_upper_limit\n    # ring_upper_limit = math.sqrt(2 * (ring_radius**2) - (ring_lower_limit)**2)\n\n    contained = np.where((np.sqrt(angdist2) < ring_upper_limit) & (np.sqrt(angdist2) > ring_lower_limit), True, False)\n\n    return contained, area\n\ndef find_best_cuts_sens(simtelfile_gammas, simtelfile_protons,\n         dl2_file_g, dl2_file_p,\n         nfiles_gammas, nfiles_protons,\n         eb, gb, tb, noff,\n         obstime = 50 * 3600 * u.s):\n    \"\"\"\n    Main function to calculate the sensitivity given a MC dataset\n\n    Parameters\n    ---------\n    simtelfile_gammas: `string` path to simtelfile of gammas with mc info\n    simtelfile_protons: `string` path to simtelfile of protons with mc info\n    dl2_file_g: `string` path to h5 file of reconstructed gammas\n    dl2_file_p: `string' path to h5 file of reconstructed protons\n    nfiles_gammas: `int` number of simtel gamma files reconstructed\n    nfiles_protons: `int` number of simtel proton files reconstructed\n    eb: `int` number of bins in energy\n    gb: `int` number of bins in gammaness\n    tb: `int` number of bins in theta2\n    noff: `float` ratio between the background and the signal region\n    obstime: `Quantity` Observation time in seconds\n\n    TODO: Give files as input in a configuration file!\n    Returns\n    E: `array` center of energy bins\n    sensitivity: `array` sensitivity per energy bin\n    ---------\n    \"\"\"\n\n    # Read simulated and reconstructed values\n    gammaness_g, theta2_g, e_reco_g, e_true_g, mc_par_g, events_g = process_mc(simtelfile_gammas,\n                                                           dl2_file_g, 'gamma')\n    gammaness_p, angdist2_p, e_reco_p, e_true_p, mc_par_p, events_p = process_mc(simtelfile_protons,\n                                                             dl2_file_p, 'proton')\n\n    mc_par_g['sim_ev'] = mc_par_g['sim_ev']*nfiles_gammas\n    mc_par_p['sim_ev'] = mc_par_p['sim_ev']*nfiles_protons\n\n    #Pass units to GeV and cm2\n    mc_par_g['emin'] = mc_par_g['emin'].to(u.GeV)\n    mc_par_g['emax'] = mc_par_g['emax'].to(u.GeV)\n\n    mc_par_p['emin'] = mc_par_p['emin'].to(u.GeV)\n    mc_par_p['emax'] = mc_par_p['emax'].to(u.GeV)\n\n    mc_par_g['area_sim'] = mc_par_g['area_sim'].to(u.cm**2)\n    mc_par_p['area_sim'] = mc_par_p['area_sim'].to(u.cm**2)\n\n    #Set binning for sensitivity calculation\n    emin_sens = 10**1 * u.GeV #mc_par_g['emin']\n    emax_sens = 10**5 * u.GeV #mc_par_g['emax']\n\n    E = np.logspace(np.log10(emin_sens.to_value()),\n                np.log10(emax_sens.to_value()), eb + 1) * u.GeV\n\n    g, t = bin_definition(gb, tb)\n\n    #Number of simulated events per energy bin\n    \"\"\"\n    bins, n_sim_bin = power_law_integrated_distribution(emin_sens.to_value(),\n                                                        emax_sens.to_value(),\n                                                        mc_par_g['sim_ev'],\n                                                        mc_par_g['sp_idx'], eb+1)\n\n\n    \"\"\"\n    # Extract spectral parameters\n    dFdE, crab_par = crab_hegra(E)\n    dFdEd0, proton_par = proton_bess(E)\n\n    bins = np.logspace(np.log10(emin_sens.to_value()), np.log10(emax_sens.to_value()), eb+1)\n    y0 = mc_par_g['sim_ev'] / (mc_par_g['emax'].to_value()**(mc_par_g['sp_idx'] + 1) \\\n                               - mc_par_g['emin'].to_value()**(mc_par_g['sp_idx'] + 1)) \\\n        * (mc_par_g['sp_idx'] + 1)\n    y = y0 * (bins[1:]**(crab_par['alpha'] + 1) - bins[:-1]**(crab_par['alpha'] + 1)) / (crab_par['alpha'] + 1)\n\n    n_sim_bin = y\n\n\n    # Rates and weights\n    rate_g = rate(mc_par_g['emin'], mc_par_g['emax'], crab_par['alpha'],\n                     mc_par_g['cone'], mc_par_g['area_sim'],\n                     crab_par['f0'], crab_par['e0'])\n\n    rate_p = rate(mc_par_p['emin'], mc_par_p['emax'], proton_par['alpha'],\n                     mc_par_p['cone'], mc_par_p['area_sim'],\n                     proton_par['f0'], proton_par['e0'])\n\n    w_g = weight(mc_par_g['emin'], mc_par_g['emax'], mc_par_g['sp_idx'],\n                    crab_par['alpha'], rate_g,\n                    mc_par_g['sim_ev'], crab_par['e0'])\n\n    w_p = weight(mc_par_p['emin'], mc_par_p['emax'], mc_par_p['sp_idx'],\n                    proton_par['alpha'], rate_p,\n                    mc_par_p['sim_ev'], proton_par['e0'])\n\n\n    e_reco_gw = ((e_reco_g / crab_par['e0'])**(crab_par['alpha'] - mc_par_g['sp_idx'])) \\\n                * w_g\n    e_reco_pw = ((e_reco_p / proton_par['e0'])**(proton_par['alpha'] - mc_par_p['sp_idx'])) \\\n                * w_p\n\n    p_contained, ang_area_p = ring_containment(angdist2_p, 0.4 * u.deg, 0.2 * u.deg)\n    # FIX: ring_radius and ring_halfwidth should have units of deg\n    # FIX: hardcoded at the moment, but ring_radius should be read from\n    # the gamma file (point-like) or given as input (diffuse).\n    # FIX: ring_halfwidth should be given as input\n    area_ratio_p = np.pi * t / ang_area_p\n    # ratio between the area where we search for protons ang_area_p\n    # and the area where we search for gammas math.pi * t\n\n    # Arrays to contain the number of gammas and hadrons for different cuts\n    final_gamma = np.ndarray(shape=(eb, gb, tb))\n    final_hadrons = np.ndarray(shape=(eb, gb, tb))\n    pre_gamma = np.ndarray(shape=(eb, gb, tb))\n    pre_hadrons = np.ndarray(shape=(eb, gb, tb))\n\n    ngamma_per_ebin = np.ndarray(eb)\n    nhadron_per_ebin = np.ndarray(eb)\n\n    # Weight events and count number of events per bin:\n    for i in range(0,eb):  # binning in energy\n        for j in range(0,gb):  # cut in gammaness\n            for k in range(0,tb):  # cut in theta2\n                eg_w_sum = np.sum(e_reco_gw[(e_reco_g < E[i+1]) & (e_reco_g > E[i]) \\\n                                            & (gammaness_g > g[j]) & (theta2_g < t[k])])\n\n                ep_w_sum = np.sum(e_reco_pw[(e_reco_p < E[i+1]) & (e_reco_p > E[i]) \\\n                                            & (gammaness_p > g[j]) & p_contained])\n                final_gamma[i][j][k] = eg_w_sum * obstime\n                final_hadrons[i][j][k] = ep_w_sum * obstime * area_ratio_p[k]\n\n                pre_gamma[i][j][k] = e_reco_g[(e_reco_g < E[i+1]) & (e_reco_g > E[i]) \\\n                                            & (gammaness_g > g[j]) & (theta2_g < t[k])].shape[0]\n                pre_hadrons[i][j][k] = e_reco_p[(e_reco_p < E[i+1]) & (e_reco_p > E[i]) \\\n                                            & (gammaness_p > g[j]) & p_contained].shape[0]\n\n                ngamma_per_ebin[i] = np.sum(e_reco_gw[(e_reco_g < E[i+1]) & (e_reco_g > E[i])]) * obstime\n                nhadron_per_ebin[i] = np.sum(e_reco_pw[(e_reco_p < E[i+1]) & (e_reco_p > E[i])]) * obstime\n\n    nex_5sigma, sens = calculate_sensitivity_lima(final_gamma, final_hadrons * noff, 1/noff,\n                                                  eb, gb, tb)\n    # Avoid bins which are empty or have too few events:\n    min_num_events = 10\n    min_pre_events = 10\n    # Minimum number of gamma and proton events in a bin to be taken into account for minimization\n    for i in range(0, eb):\n        for j in range(0, gb):\n            for k in range(0, tb):\n                conditions = (not np.isfinite(sens[i,j,k])) or (sens[i,j,k]<=0) \\\n                             or (final_hadrons[i,j,k] < min_num_events) \\\n                             or (pre_gamma[i,j,k] < min_pre_events) \\\n                             or (pre_hadrons[i,j,k] < min_pre_events)\n                if conditions:\n                    sens[i][j][k] = np.inf\n\n    #Quantities to show in the results\n    sensitivity = np.ndarray(shape=eb)\n    nex_min = np.ndarray(shape=eb)\n    eff_g = np.ndarray(shape=eb)\n    eff_p = np.ndarray(shape=eb)\n    gcut = np.ndarray(shape=eb)\n    tcut = np.ndarray(shape=eb)\n    ngammas = np.ndarray(shape=eb)\n    nhadrons = np.ndarray(shape=eb)\n    gammarate = np.ndarray(shape=eb)\n    hadronrate = np.ndarray(shape=eb)\n    eff_area = np.ndarray(shape=eb)\n    nevents_gamma = np.ndarray(shape=eb)\n    nevents_proton = np.ndarray(shape=eb)\n\n    # Calculate the minimum sensitivity per energy bin\n    for i in range(0,eb):\n        ind = np.unravel_index(np.nanargmin(sens[i], axis=None), sens[i].shape)\n        gcut[i] = g[ind[0]]\n        tcut[i] = t[ind[1]].to_value()\n        ngammas[i] = final_gamma[i][ind]\n        nhadrons[i] = final_hadrons[i][ind]\n        gammarate[i] = final_gamma[i][ind]/(obstime.to(u.min)).to_value()\n        hadronrate[i] = final_hadrons[i][ind]/(obstime.to(u.min)).to_value()\n        nex_min[i] =  nex_5sigma[i][ind]\n        sensitivity[i] = sens[i][ind]\n        eff_g[i] = final_gamma[i][ind]/ngamma_per_ebin[i]\n        eff_p[i] = final_hadrons[i][ind]/nhadron_per_ebin[i]\n\n        e_aftercuts = e_true_g[(e_true_g < E[i+1]) & (e_true_g > E[i]) \\\n                               & (gammaness_g > g[ind[0]]) & (theta2_g < t[ind[1]])]\n\n        e_aftercuts_p = e_true_p[(e_true_p < E[i+1]) & (e_true_p > E[i]) \\\n                                 & (gammaness_p > g[ind[0]]) & p_contained]\n\n        e_aftercuts_w = np.sum(np.power(e_aftercuts, crab_par['alpha']-mc_par_g['sp_idx']))\n\n        e_w = np.sum(np.power(e_true_g[(e_true_g < E[i+1]) & (e_true_g > E[i])],\n                              crab_par['alpha']-mc_par_g['sp_idx']))\n\n        #eff_area[i] = e_true_g[(e_true_g < E[i+1]) & (e_true_g > E[i]) & (gammaness_g > g[ind[0]]) & (theta2_g < t[ind[1]])].shape[0] / n_sim_bin[i] * mc_par_g['area_sim'].to(u.m**2).to_value()\n\n        eff_area[i] = e_aftercuts_w.to_value() / n_sim_bin[i] * mc_par_g['area_sim'].to(u.m**2).to_value()\n\n        nevents_gamma[i] = e_aftercuts.shape[0]\n        nevents_proton[i] = e_aftercuts_p.shape[0]\n\n    #Compute sensitivity  in flux units\n\n    emed = np.sqrt(E[1:] * E[:-1])\n    dFdE, par = crab_magic(emed)\n    sens_flux = sensitivity / 100 * (dFdE * emed * emed).to(u.erg / (u.cm**2 * u.s))\n\n    list_of_tuples = list(zip(E[:E.shape[0]-2].to_value(), E[1:].to_value(), gcut, tcut,\n                            ngammas, nhadrons,\n                            gammarate, hadronrate,\n                            nex_min, sens_flux.to_value(), eff_area,\n                              eff_g, eff_p, nevents_gamma, nevents_proton))\n    result = pd.DataFrame(list_of_tuples,\n                           columns=['ebin_low', 'ebin_up', 'gammaness_cut', 'theta2_cut',\n                                    'n_gammas', 'n_hadrons',\n                                    'gamma_rate', 'hadron_rate',\n                                    'nex_min', 'sensitivity','eff_area',\n                                    'eff_gamma', 'eff_hadron',\n                                    'nevents_g', 'nevents_p'])\n\n    units = [E.unit, E.unit,\"\", t.unit,\"\", \"\",\n             u.min**-1, u.min**-1, \"\",\n             sens_flux.unit, mc_par_g['area_sim'].to(u.m**2).unit, \"\", \"\", \"\", \"\"]\n    \"\"\"\n    sens_minimization_plot(eb, gb, tb, E, sens)\n    \n    plot_positions_survived_events(events_g,\n                                   events_p,\n                                   gammaness_g, gammaness_p,\n                                   theta2_g, p_contained, sens, E, eb, g, t)\n    \n    \"\"\"\n    return E, sensitivity, result, units, gcut, tcut\n\n\ndef sens(simtelfile_gammas, simtelfile_protons,\n         dl2_file_g, dl2_file_p,\n         nfiles_gammas, nfiles_protons,\n         eb, gcut, tcut, noff,\n         obstime = 50 * 3600 * u.s):\n    \"\"\"\n    Main function to calculate the sensitivity given a MC dataset\n\n    Parameters\n    ---------\n    simtelfile_gammas: `string` path to simtelfile of gammas with mc info\n    simtelfile_protons: `string` path to simtelfile of protons with mc info\n    dl2_file_g: `string` path to h5 file of reconstructed gammas\n    dl2_file_p: `string' path to h5 file of reconstructed protons\n    nfiles_gammas: `int` number of simtel gamma files reconstructed\n    nfiles_protons: `int` number of simtel proton files reconstructed\n    eb: `int` number of bins in energy\n    gb: `int` number of bins in gammaness\n    tb: `int` number of bins in theta2\n    noff: `float` ratio between the background and the signal region\n    obstime: `Quantity` Observation time in seconds\n\n    TODO: Give files as input in a configuration file!\n    Returns\n    E: `array` center of energy bins\n    sensitivity: `array` sensitivity per energy bin\n    ---------\n    \"\"\"\n\n    # Read simulated and reconstructed values\n    gammaness_g, theta2_g, e_reco_g, e_true_g, mc_par_g, events_g = process_mc(simtelfile_gammas,\n                                                           dl2_file_g, 'gamma')\n    gammaness_p, angdist2_p, e_reco_p, e_true_p, mc_par_p, events_p = process_mc(simtelfile_protons,\n                                                             dl2_file_p, 'proton')\n\n    mc_par_g['sim_ev'] = mc_par_g['sim_ev']*nfiles_gammas\n    mc_par_p['sim_ev'] = mc_par_p['sim_ev']*nfiles_protons\n\n    #Pass units to GeV and cm2\n    mc_par_g['emin'] = mc_par_g['emin'].to(u.GeV)\n    mc_par_g['emax'] = mc_par_g['emax'].to(u.GeV)\n\n    mc_par_p['emin'] = mc_par_p['emin'].to(u.GeV)\n    mc_par_p['emax'] = mc_par_p['emax'].to(u.GeV)\n\n    mc_par_g['area_sim'] = mc_par_g['area_sim'].to(u.cm**2)\n    mc_par_p['area_sim'] = mc_par_p['area_sim'].to(u.cm**2)\n\n    #Set binning for sensitivity calculation\n    emin_sens = 10**1 * u.GeV #mc_par_g['emin']\n    emax_sens = 10**5 * u.GeV #mc_par_g['emax']\n\n    E = np.logspace(np.log10(emin_sens.to_value()),\n                np.log10(emax_sens.to_value()), eb + 1) * u.GeV\n\n    #Number of simulated events per energy bin\n    \"\"\"\n    bins, n_sim_bin = power_law_integrated_distribution(emin_sens.to_value(),\n                                                        emax_sens.to_value(),\n                                                        mc_par_g['sim_ev'],\n                                                        mc_par_g['sp_idx'], eb+1)\n\n\n    \"\"\"\n    # Extract spectral parameters\n    dFdE, crab_par = crab_hegra(E)\n    dFdEd0, proton_par = proton_bess(E)\n\n    bins = np.logspace(np.log10(emin_sens.to_value()), np.log10(emax_sens.to_value()), eb+1)\n    y0 = mc_par_g['sim_ev'] / (mc_par_g['emax'].to_value()**(mc_par_g['sp_idx'] + 1) \\\n                               - mc_par_g['emin'].to_value()**(mc_par_g['sp_idx'] + 1)) \\\n        * (mc_par_g['sp_idx'] + 1)\n    y = y0 * (bins[1:]**(crab_par['alpha'] + 1) - bins[:-1]**(crab_par['alpha'] + 1)) / (crab_par['alpha'] + 1)\n\n    n_sim_bin = y\n\n\n    # Rates and weights\n    rate_g = rate(mc_par_g['emin'], mc_par_g['emax'], crab_par['alpha'],\n                     mc_par_g['cone'], mc_par_g['area_sim'],\n                     crab_par['f0'], crab_par['e0'])\n\n    rate_p = rate(mc_par_p['emin'], mc_par_p['emax'], proton_par['alpha'],\n                     mc_par_p['cone'], mc_par_p['area_sim'],\n                     proton_par['f0'], proton_par['e0'])\n\n    w_g = weight(mc_par_g['emin'], mc_par_g['emax'], mc_par_g['sp_idx'],\n                    crab_par['alpha'], rate_g,\n                    mc_par_g['sim_ev'], crab_par['e0'])\n\n    w_p = weight(mc_par_p['emin'], mc_par_p['emax'], mc_par_p['sp_idx'],\n                    proton_par['alpha'], rate_p,\n                    mc_par_p['sim_ev'], proton_par['e0'])\n\n\n    e_reco_gw = ((e_reco_g / crab_par['e0'])**(crab_par['alpha'] - mc_par_g['sp_idx'])) \\\n                * w_g\n    e_reco_pw = ((e_reco_p / proton_par['e0'])**(proton_par['alpha'] - mc_par_p['sp_idx'])) \\\n                * w_p\n\n    p_contained, ang_area_p = ring_containment(angdist2_p, 0.4 * u.deg, 0.2 * u.deg)\n    # FIX: ring_radius and ring_halfwidth should have units of deg\n    # FIX: hardcoded at the moment, but ring_radius should be read from\n    # the gamma file (point-like) or given as input (diffuse).\n    # FIX: ring_halfwidth should be given as input\n    area_ratio_p = np.pi * tcut / ang_area_p\n    # ratio between the area where we search for protons ang_area_p\n    # and the area where we search for gammas math.pi * t\n\n    # Arrays to contain the number of gammas and hadrons for different cuts\n    final_gamma = np.ndarray(shape=(eb))\n    final_hadrons = np.ndarray(shape=(eb))\n    pre_gamma = np.ndarray(shape=(eb))\n    pre_hadrons = np.ndarray(shape=(eb))\n\n    ngamma_per_ebin = np.ndarray(eb)\n    nhadron_per_ebin = np.ndarray(eb)\n\n    # Weight events and count number of events per bin:\n    for i in range(0,eb):  # binning in energy\n        eg_w_sum = np.sum(e_reco_gw[(e_reco_g < E[i+1]) & (e_reco_g > E[i]) \\\n                                    & (gammaness_g > gcut[i]) & (theta2_g < tcut[i])])\n\n        ep_w_sum = np.sum(e_reco_pw[(e_reco_p < E[i+1]) & (e_reco_p > E[i]) \\\n                                    & (gammaness_p > gcut[i]) & p_contained])\n        final_gamma[i] = eg_w_sum * obstime\n        final_hadrons[i] = ep_w_sum * obstime * area_ratio_p[i]\n\n        pre_gamma[i] = e_reco_g[(e_reco_g < E[i+1]) & (e_reco_g > E[i]) \\\n                                & (gammaness_g > gcut[i]) & (theta2_g < tcut[i])].shape[0]\n        pre_hadrons[i] = e_reco_p[(e_reco_p < E[i+1]) & (e_reco_p > E[i]) \\\n                                  & (gammaness_p > gcut[i]) & p_contained].shape[0]\n\n        ngamma_per_ebin[i] = np.sum(e_reco_gw[(e_reco_g < E[i+1]) & (e_reco_g > E[i])]) * obstime\n        nhadron_per_ebin[i] = np.sum(e_reco_pw[(e_reco_p < E[i+1]) & (e_reco_p > E[i])]) * obstime\n\n    nex_5sigma, sens = calculate_sensitivity_lima_1d(final_gamma, final_hadrons * noff, 1/noff,\n                                                  eb)\n    # Avoid bins which are empty or have too few events:\n    min_num_events = 10\n    min_pre_events = 10\n    # Minimum number of gamma and proton events in a bin to be taken into account for minimization\n    for i in range(0, eb):\n        conditions = (not np.isfinite(sens[i])) or (sens[i]<=0) \\\n                     or (final_hadrons[i] < min_num_events) \\\n                     or (pre_gamma[i] < min_pre_events) \\\n                     or (pre_hadrons[i] < min_pre_events)\n        if conditions:\n            sens[i] = np.inf\n\n    #Quantities to show in the results\n    sensitivity = np.ndarray(shape=eb)\n    nex_min = np.ndarray(shape=eb)\n    eff_g = np.ndarray(shape=eb)\n    eff_p = np.ndarray(shape=eb)\n    ngammas = np.ndarray(shape=eb)\n    nhadrons = np.ndarray(shape=eb)\n    gammarate = np.ndarray(shape=eb)\n    hadronrate = np.ndarray(shape=eb)\n    eff_area = np.ndarray(shape=eb)\n    nevents_gamma = np.ndarray(shape=eb)\n    nevents_proton = np.ndarray(shape=eb)\n\n    # Calculate the minimum sensitivity per energy bin\n    for i in range(0,eb):\n        ngammas[i] = final_gamma[i]\n        nhadrons[i] = final_hadrons[i]\n        gammarate[i] = final_gamma[i]/(obstime.to(u.min)).to_value()\n        hadronrate[i] = final_hadrons[i]/(obstime.to(u.min)).to_value()\n        nex_min[i] =  nex_5sigma[i]\n        sensitivity[i] = sens[i]\n        eff_g[i] = final_gamma[i]/ngamma_per_ebin[i]\n        eff_p[i] = final_hadrons[i]/nhadron_per_ebin[i]\n\n        e_aftercuts = e_true_g[(e_true_g < E[i+1]) & (e_true_g > E[i]) \\\n                               & (gammaness_g > gcut[i]) & (theta2_g < tcut[i])]\n\n        e_aftercuts_p = e_true_p[(e_true_p < E[i+1]) & (e_true_p > E[i]) \\\n                                 & (gammaness_p > gcut[i]) & p_contained]\n\n        e_aftercuts_w = np.sum(np.power(e_aftercuts, crab_par['alpha']-mc_par_g['sp_idx']))\n\n        e_w = np.sum(np.power(e_true_g[(e_true_g < E[i+1]) & (e_true_g > E[i])],\n                              crab_par['alpha']-mc_par_g['sp_idx']))\n\n        eff_area[i] = e_aftercuts_w.to_value() / n_sim_bin[i] * mc_par_g['area_sim'].to(u.m**2).to_value()\n\n        nevents_gamma[i] = e_aftercuts.shape[0]\n        nevents_proton[i] = e_aftercuts_p.shape[0]\n\n    #Compute sensitivity  in flux units\n\n    emed = np.sqrt(E[1:] * E[:-1])\n    dFdE, par = crab_magic(emed)\n    sens_flux = sensitivity / 100 * (dFdE * emed * emed).to(u.erg / (u.cm**2 * u.s))\n\n    list_of_tuples = list(zip(E[:E.shape[0]-2].to_value(), E[1:].to_value(), gcut, tcut,\n                            ngammas, nhadrons,\n                            gammarate, hadronrate,\n                            nex_min, sens_flux.to_value(), eff_area,\n                              eff_g, eff_p, nevents_gamma, nevents_proton))\n    result = pd.DataFrame(list_of_tuples,\n                           columns=['ebin_low', 'ebin_up', 'gammaness_cut', 'theta2_cut',\n                                    'n_gammas', 'n_hadrons',\n                                    'gamma_rate', 'hadron_rate',\n                                    'nex_min', 'sensitivity','eff_area',\n                                    'eff_gamma', 'eff_hadron',\n                                    'nevents_g', 'nevents_p'])\n\n    units = [E.unit, E.unit,\"\", tcut.unit,\"\", \"\",\n             u.min**-1, u.min**-1, \"\",\n             sens_flux.unit, mc_par_g['area_sim'].to(u.m**2).unit, \"\", \"\", \"\", \"\"]\n\n    \"\"\"\n    sens_minimization_plot(eb, gb, tb, E, sens)\n    \n    plot_positions_survived_events(events_g,\n                                   events_p,\n                                   gammaness_g, gammaness_p,\n                                   theta2_g, p_contained, sens, E, eb, gcut, tcut)\n    \"\"\"\n    # Build dataframe of events that survive the cuts:\n    events = pd.concat((events_g, events_p))\n    dl2 = pd.DataFrame(columns=events.keys())\n    for i in range(0,eb):\n        df_bin = events[(10**events.mc_energy < E[i+1]) & (10**events.mc_energy > E[i]) \\\n                               & (events.gammaness > gcut[i]) & (events.theta2 < tcut[i])]\n\n        dl2 = pd.concat((dl2, df_bin))\n\n    return E, sensitivity, result, units, dl2\n\n", "meta": {"hexsha": "6fa7e3589e02905bb6d40a11a5cc8f25d63d5cdb", "size": 30026, "ext": "py", "lang": "Python", "max_stars_repo_path": "lstchain/mc/sensitivity.py", "max_stars_repo_name": "thomasgas/cta-lstchain", "max_stars_repo_head_hexsha": "59dbc58f7dd7fb35aebce22489082ac885fac18b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lstchain/mc/sensitivity.py", "max_issues_repo_name": "thomasgas/cta-lstchain", "max_issues_repo_head_hexsha": "59dbc58f7dd7fb35aebce22489082ac885fac18b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lstchain/mc/sensitivity.py", "max_forks_repo_name": "thomasgas/cta-lstchain", "max_forks_repo_head_hexsha": "59dbc58f7dd7fb35aebce22489082ac885fac18b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6305818674, "max_line_length": 194, "alphanum_fraction": 0.581229601, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 8483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.19258312171764091}}
{"text": "# isochrones.py\n# Ben Cook (bcook@cfa.harvard.edu)\n\n\"\"\"Define the Isocrhone_Model class\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport os\nimport glob\nimport sys\nfrom warnings import warn\nfrom pkg_resources import resource_filename\n\n##########################\n# Useful Utilities\n\n\ndef load_MIST_dir(dir_path, iso_append='.iso.cmd'):\n    df = pd.DataFrame()\n    for MIST_doc in glob.glob(os.path.join(dir_path, '*'+iso_append)):\n        try:\n            with open(MIST_doc, 'r') as f:\n                lines = [f.readline() for _ in range(13)]\n                colnames = lines[-1].strip('#\\n').split()\n                assert ('EEP' in colnames)\n            dtypes = {c: float for c in colnames}\n            dtypes['EEP'] = int\n            new_df = pd.read_table(MIST_doc, names=colnames,\n                                   comment='#', delim_whitespace=True,\n                                   dtype=dtypes, na_values=['Infinity'])\n            new_df[new_df.isna()] = 100.\n            df = df.append([new_df], ignore_index=True)\n        except Exception:\n            warn('File not properly formatted: %s' % (MIST_doc))\n            sys.exit(1)\n    return df\n\n\ndef _interp_arrays(arr1, arr2, f):\n    \"\"\"Linearly interpolate between two (potentially unequal length) arrays\n    \n    Arguments:\n    arr1 -- first (lower) array (len N1 or N1xD)\n    arr2 -- second (upper) array (len N2 or N2xD, N2 doesn't have to equal N1)\n    f -- linear interpolation fraction (float between 0 and 1)\n    Output: interpolated array (len max(N1,N2) or max(N1,N2)xD)\n    \"\"\"\n    assert (arr1.ndim == arr2.ndim), (\n        \"The two interpolated arrays must have same dimensions\")\n\n    l1, l2 = len(arr1), len(arr2)\n    # If arrays are unequal length, extrapolate shorter using trend of longer\n    if (l1 < l2):\n        delta = arr2[l1:] - arr2[l1-1]\n        added = arr1[-1] + delta\n        arr1 = np.append(arr1, added, axis=0)\n    elif (l1 > l2):\n        delta = arr1[l2:] - arr1[l2-1]\n        added = arr2[-1] + delta\n        arr2 = np.append(arr2, added, axis=0)\n    return (1-f)*arr1 + f*arr2\n\n\ndef _feh_from_str(feh_str):\n    \"\"\"Converts a metallicity value to MIST string\n    Example Usage:\n    _feh_from_str(\"m0.53\") -> -0.53\n    _feh_from_str(\"p1.326\")   -> 1.326\n    \n    Arguments:\n    feh_str -- metallicity (as a string)\n    Output: float value of metallicity\n    \"\"\"\n    value = float(feh_str[1:])\n    if feh_str[0] == 'm':\n        value *= -1\n    elif feh_str[0] != 'p':\n        raise ValueError('feh string not of valid format')\n    return value\n\n\ndef _feh_to_str(feh):\n    \"\"\"Converts a metallicity value to MIST string\n    Example Usage:\n    _feh_to_str(-0.5313) -> \"m0.53\"\n    _feh_to_str(1.326)   -> \"p1.33\"\n    \n    Arguments:\n    feh -- metallicity (float)\n    Output: string representing metallicity\n    \"\"\"\n    result = ''\n    if (feh < 0):\n        result += 'm'\n    else:\n        result += 'p'\n    result += '%1.2f' % (np.abs(feh))\n    return result\n\n\ndef _interp_df_by_mass(df, dm_min):\n    ages = np.unique(df.age.values)\n    fehs = np.unique(df['[Fe/H]_init'].values)\n    new_rows = []\n    for age in ages:\n        for feh in fehs:\n            iso_df = df[np.isclose(df.age, age) & np.isclose(df['[Fe/H]_init'], feh)]\n            # add more points until reached desired spacing\n            mass = iso_df.initial_mass.values\n            frac_dm = np.diff(mass) / mass[:-1]\n            id_too_large = np.where(frac_dm > dm_min)[0]\n            for i_max in id_too_large:\n                # add additional 5 points spacing by interpolating 0.1 between points\n                row_low = iso_df.iloc[i_max]\n                row_high = iso_df.iloc[i_max + 1]\n                for f in np.linspace(0.1, 0.9, 5):\n                    new_rows.append(f*row_low + (1-f)*row_high)\n    df = df.append(pd.DataFrame(new_rows))\n    return df\n\n\nclass Isochrone_Model:\n    \"\"\"Models Isochrones (IMF, and magnitudes in particular Filters) using\n       linear interpolation of MIST models\n\n    An Isocrhone_Model incorporates a collection of MIST models, and\n       allows for interpolating the IMF and magnitudes (for given Filter\n       objects) at any arbitrary metallicity and mass\n\n    Attributes:\n       MIST_df-- A pandas Dataframe containing all pre-computed MIST datapoints\n       ages -- An array of ages (in log years) which are valid for the model\n    Methods:\n       get_magnitudes -- Pass a Galaxy_Model object, return IMF and magnitudes\n                         for each mass, age, metallicity bin\n    Constructors:\n       __init__ -- Pass a list of Filter objects, path to MIST model files,\n                   and array of metallicities.\n    \"\"\"\n    def __init__(self, filters, MIST_path=None, iso_append=\".iso.cmd\",\n                 rotating=False,\n                 mag_system='vega', dm_interp=-1):\n        \"\"\"Creates a new Isochrone_Model, given a list of Filter objects\n        \n        Arguments:\n           filters -- list of Filter objects\n        Keyword Arguments:\n           MIST_path -- directory containing MIST model files\n           feh_arr -- array of MIST metallicity values to use\n           dm_interp -- \n        \"\"\"\n\n        # Locate MIST files\n        if MIST_path is None:\n            if rotating:\n                MIST_path = resource_filename('pcmdpy', 'isochrones/MIST_v1.2_rot/')\n            else:\n                MIST_path = resource_filename('pcmdpy', 'isochrones/MIST_v1.2/')\n        \n        # Import all MIST model files into Pandas dataframe\n        self.num_filters = len(filters)\n\n        # Use optional conversions from VEGA to AB or ST, etc\n        self.conversions = {}\n        self.conversions['vega'] = np.zeros(len(filters), dtype=float)\n        self.conversions['ab'] = np.array([f._zpts['ab'] - f._zpts['vega']\n                                           for f in filters])\n        self.conversions['st'] = np.array([f._zpts['ab'] - f._zpts['vega']\n                                           for f in filters])\n        self.default_system = mag_system.lower()\n        assert self.default_system in self.conversions.keys(), (\n            \"the given mag_system is not valid. Please choose one of: \"\n            \"['vega', 'ab', 'st']\")\n        \n        self.filters = filters\n        self.filter_names = [f.tex_name for f in self.filters]\n        # load all MIST files found in directory\n        if isinstance(MIST_path, str):\n            self.MIST_df = load_MIST_dir(MIST_path, iso_append=iso_append)\n        elif isinstance(MIST_path, list):\n            merge_cols = ['[Fe/H]_init', 'EEP', 'log10_isochrone_age_yr']\n            self.MIST_df = pd.DataFrame(columns=merge_cols)\n            # Merge multiple filter sets\n            for pth in MIST_path:\n                df_temp = load_MIST_dir(pth, iso_append=iso_append)\n                self.MIST_df = self.MIST_df.merge(df_temp,\n                                                  how='outer', on=merge_cols,\n                                                  suffixes=['', '_repeat'])\n                self.MIST_df.drop(\n                    [c for c in self.MIST_df.columns if c.endswith('_repeat')],\n                    axis=1, inplace=True)\n\n        self._feh_arr = self.MIST_df['[Fe/H]_init'].unique()\n        self.MIST_df.rename(columns={'log10_isochrone_age_yr': 'age',\n                                     '[Fe/H]_init': 'feh'},\n                            inplace=True)\n        # This is deprecated\n        if dm_interp > 0.:\n            print('starting manual interpolation')\n            self.MIST_df = _interp_df_by_mass(self.MIST_df, dm_interp)\n            print('done with interpolation')\n\n        self.MIST_df = self.MIST_df.sort_values(by=['feh', 'age',\n                                                    'initial_mass'])\n        self.MIST_df = self.MIST_df.reset_index(drop=True)\n        self.ages = self.MIST_df.age.unique()\n        # The MIST columns that will be interpolated (initial, currentmass, EEP,\n        # and all input filters)\n        self._interp_cols = ['initial_mass', 'star_mass', 'EEP']\n        for f in self.filters:\n            c = f.MIST_column\n            c_alt = f.MIST_column_alt\n            if c in self.MIST_df.columns:\n                self._interp_cols.append(c)\n            elif c_alt in self.MIST_df.columns:\n                self._interp_cols.append(c_alt)\n            else:\n                print((c, c_alt))\n                raise ValueError('Filter does not have a valid MIST_column')\n        self.MIST_gb = self.MIST_df.groupby(['age', 'feh'])[self._interp_cols]\n    \n    def get_isochrone(self, age, feh, downsample=5, mag_system=None):\n        \"\"\"Interpolate MIST isochrones for given age and metallicity\n        \n        Arguments:\n           age ---\n           feh ---\n           downsample ---\n           mag_system ---\n        Output:\n           mags -- 2D array of magnitudes (DxN, where D is number of filters\n                   the model was initialized with)\n           imass -- array of initial masses (N)\n           cmass -- array of current masses (N)\n        \"\"\"\n\n        mag_system = mag_system or self.default_system\n        mag_system = mag_system.lower()\n        if mag_system not in self.conversions.keys():\n            warn(('mag_system {0:s} not in list of magnitude '\n                  'conversions. Reverting to Vega'.format(mag_system)))\n            conversions = self.conversions['vega']\n        else:\n            conversions = self.conversions[mag_system]\n        \n        # Find closest age in MIST database\n        age = self.ages[np.abs(self.ages - age).argmin()]\n        nearest_feh = self._feh_arr[np.abs(self._feh_arr - feh).argmin()]\n        if np.isclose(nearest_feh, feh, atol=0.05):\n            feh = nearest_feh\n            inter = self.MIST_gb.get_group((age, feh)).values\n        # Interpolate/extrapolate for other metallicities\n        else:\n            this_age = self.MIST_df[np.isclose(self.MIST_df.age.values, age)]\n            i = self._feh_arr.searchsorted(feh)\n            if (i == 0):\n                i = 1  # will extrapolate low\n            elif (i == len(self._feh_arr)):\n                i = -1  # will extrapolate high\n            fehlow, fehhigh = self._feh_arr[i-1:i+1]  # bounding metallicities\n            frac_between = (feh - fehlow) / (fehhigh - fehlow)\n            if (frac_between >= 2) or (frac_between <= -1):\n                raise ValueError('Extrapolating metallicity more than one '\n                                 'entire metallicity bin')\n            dflow = this_age[np.isclose(this_age.feh.values, fehlow)][self._interp_cols]\n            dfhigh = this_age[np.isclose(this_age.feh.values, fehhigh)][self._interp_cols]\n            inter = _interp_arrays(dflow.values, dfhigh.values, frac_between)\n            \n        initial_mass = inter[::downsample, 0]\n        current_mass = inter[::downsample, 1]\n        eep = inter[::downsample, 2]\n\n        mags = (inter[::downsample, 3:] + conversions).T\n        \n        return mags, initial_mass, current_mass, eep\n\n    def model_galaxy(self, galaxy, lum_cut=np.inf, mag_system=None,\n                     downsample=5, return_mass=False):\n        weights = np.empty((1, 0), dtype=float)\n        magnitudes = np.empty((self.num_filters, 0), dtype=float)\n        initial_mass = np.empty((1, 0), dtype=float)\n        current_mass = np.empty((1, 0), dtype=float)\n        eeps = np.empty((1, 0), dtype=float)\n        # Collect the isochrones from each bin\n        for age, feh, sfh, d_mod in galaxy.iter_SSPs():\n            mags, i_mass, c_mass, eep = self.get_isochrone(\n                age, feh, mag_system=mag_system, downsample=downsample)\n            imf = galaxy.imf_func(i_mass, **galaxy.imf_kwargs)\n            weights = np.append(weights, imf*sfh)\n            mags += d_mod\n            magnitudes = np.append(magnitudes, mags, axis=-1)\n            initial_mass = np.append(initial_mass, i_mass)\n            current_mass = np.append(current_mass, c_mass)\n            eeps = np.append(eeps, eep)\n        if not np.isinf(lum_cut):\n            lum = np.power(10., -0.4*magnitudes)\n            mean_lum = np.average(lum, weights=weights, axis=1)\n            to_keep = (lum.T / mean_lum >= lum_cut).sum(axis=1) == 0\n            weights = weights[to_keep]\n            magnitudes = magnitudes[:, to_keep]\n            initial_mass = initial_mass[to_keep]\n            current_mass = current_mass[to_keep]\n            eeps = eeps[to_keep]\n        if return_mass:\n            return weights, magnitudes, initial_mass, current_mass, eeps\n        else:\n            return weights, magnitudes\n\n    def get_stellar_mass(self, galaxy, downsample=5):\n        imf, _, _, c_mass, _ = self.model_galaxy(galaxy,\n                                                 downsample=downsample,\n                                                 return_mass=True)\n        return (imf * c_mass).sum()\n", "meta": {"hexsha": "ae0223ae17a5a5a24669bb5426de098ac60d48f7", "size": 12810, "ext": "py", "lang": "Python", "max_stars_repo_path": "pcmdpy/isochrones/isochrones.py", "max_stars_repo_name": "johnnygreco/pcmdpy", "max_stars_repo_head_hexsha": "fe38db999f4445c98bde168867274654b2be4dbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcmdpy/isochrones/isochrones.py", "max_issues_repo_name": "johnnygreco/pcmdpy", "max_issues_repo_head_hexsha": "fe38db999f4445c98bde168867274654b2be4dbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcmdpy/isochrones/isochrones.py", "max_forks_repo_name": "johnnygreco/pcmdpy", "max_forks_repo_head_hexsha": "fe38db999f4445c98bde168867274654b2be4dbe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.7961783439, "max_line_length": 90, "alphanum_fraction": 0.5711163154, "include": true, "reason": "import numpy", "num_tokens": 3191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.35220179564702847, "lm_q1q2_score": 0.19256215887771896}}
{"text": "# Copyright 2016 Valentine Svensson, James Hensman, alexggmatthews, Alexis Boukouvalas\n# Copyright 2017 Artem Artemev @awav\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nLikelihoods are another core component of GPflow. This describes how likely the\ndata is under the assumptions made about the underlying latent functions\np(Y|F). Different likelihoods make different\nassumptions about the distribution of the data, as such different data-types\n(continuous, binary, ordinal, count) are better modelled with different\nlikelihood assumptions.\n\nUse of any likelihood other than Gaussian typically introduces the need to use\nan approximation to perform inference, if one isn't already needed. A\nvariational inference and MCMC models are included in GPflow and allow\napproximate inference with non-Gaussian likelihoods. An introduction to these\nmodels can be found :ref:`here <implemented_models>`. Specific notebooks\nillustrating non-Gaussian likelihood regressions are available for\n`classification <notebooks/classification.html>`_ (binary data), `ordinal\n<notebooks/ordinal.html>`_ and `multiclass <notebooks/multiclass.html>`_.\n\nCreating new likelihoods\n----------\nLikelihoods are defined by their\nlog-likelihood. When creating new likelihoods, the\n:func:`logp <gpflow.likelihoods.Likelihood.logp>` method (log p(Y|F)), the\n:func:`conditional_mean <gpflow.likelihoods.Likelihood.conditional_mean>`,\n:func:`conditional_variance\n<gpflow.likelihoods.Likelihood.conditional_variance>`.\n\nIn order to perform variational inference with non-Gaussian likelihoods a term\ncalled ``variational expectations``, ∫ q(F) log p(Y|F) dF, needs to\nbe computed under a Gaussian distribution q(F) ~ N(μ, Σ).\n\nThe :func:`variational_expectations <gpflow.likelihoods.Likelihood.variational_expectations>`\nmethod can be overriden if this can be computed in closed form, otherwise; if\nthe new likelihood inherits\n:class:`Likelihood <gpflow.likelihoods.Likelihood>` the default will use\nGauss-Hermite numerical integration (works well when F is 1D\nor 2D), if the new likelihood inherits from\n:class:`MonteCarloLikelihood <gpflow.likelihoods.MonteCarloLikelihood>` the\nintegration is done by sampling (can be more suitable when F is higher dimensional).\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\nimport abc\nimport warnings\n\nfrom .. import logdensities\nfrom ..base import Module, Parameter\nfrom ..config import default_float\nfrom ..quadrature import hermgauss, ndiag_mc, ndiagquad\nfrom ..utilities import positive, to_default_int\nfrom .robustmax import RobustMax\n\n\ndef inv_probit(x):\n    jitter = 1e-3  # ensures output is strictly between 0 and 1\n    return 0.5 * (1.0 + tf.math.erf(x / np.sqrt(2.0))) * (1 - 2 * jitter) + jitter\n\n\nclass Likelihood(Module, metaclass=abc.ABCMeta):\n    def __init__(self, latent_dim: int, observation_dim: int):\n        \"\"\"\n        A base class for likelihoods, which specifies an observation model \n        connecting the latent functions ('F') to the data ('Y').\n\n        All of the members of this class are expected to obey some shape conventions, as specified\n        by latent_dim and observation_dim.\n\n        If we're operating on an array of function values 'F', then the last dimension represents\n        multiple functions (preceding dimensions could represent different data points, or\n        different random samples, for example). Similarly, the last dimension of Y represents a\n        single data point. We check that the dimensions are as this object expects.\n\n        The return shapes of all functions in this class is the broadcasted shape of the arguments,\n        excluding the last dimension of each argument.\n\n        :param latent_dim: the dimension of the vector F of latent functions for a single data point\n        :param observation_dim: the dimension of the observation vector Y for a single data point\n        \"\"\"\n        super().__init__()\n        self.latent_dim = latent_dim\n        self.observation_dim = observation_dim\n\n    def _check_last_dims_valid(self, F, Y):\n        \"\"\"\n        Assert that the dimensions of the latent functions F and the data Y are compatible.\n\n        :param F: function evaluation Tensor, with shape [..., latent_dim]\n        :param Y: observation Tensor, with shape [..., observation_dim]\n        \"\"\"\n        self._check_latent_dims(F)\n        self._check_data_dims(Y)\n\n    def _check_return_shape(self, result, F, Y):\n        \"\"\"\n        Check that the shape of a computed statistic of the data\n        is the broadcasted shape from F and Y.\n\n        :param result: result Tensor, with shape [...]\n        :param F: function evaluation Tensor, with shape [..., latent_dim]\n        :param Y: observation Tensor, with shape [..., observation_dim]\n        \"\"\"\n        expected_shape = tf.broadcast_dynamic_shape(tf.shape(F)[:-1], tf.shape(Y)[:-1])\n        tf.debugging.assert_equal(tf.shape(result), expected_shape)\n\n    def _check_latent_dims(self, F):\n        \"\"\"\n        Ensure that a tensor of latent functions F has latent_dim as right-most dimension.\n\n        :param F: function evaluation Tensor, with shape [..., latent_dim]\n        \"\"\"\n        tf.debugging.assert_shapes([(F, (..., self.latent_dim))])\n\n    def _check_data_dims(self, Y):\n        \"\"\"\n        Ensure that a tensor of data Y has observation_dim as right-most dimension.\n\n        :param Y: observation Tensor, with shape [..., observation_dim]\n        \"\"\"\n        tf.debugging.assert_shapes([(Y, (..., self.observation_dim))])\n\n    def log_prob(self, F, Y):\n        \"\"\"\n        The log probability density log p(Y|F)\n\n        :param F: function evaluation Tensor, with shape [..., latent_dim]\n        :param Y: observation Tensor, with shape [..., observation_dim]:\n        :returns: log pdf, with shape [...]\n        \"\"\"\n        self._check_last_dims_valid(F, Y)\n        res = self._log_prob(F, Y)\n        self._check_return_shape(res, F, Y)\n        return res\n\n    @abc.abstractmethod\n    def _log_prob(self, F, Y):\n        raise NotImplementedError\n\n    def conditional_mean(self, F):\n        \"\"\"\n        The conditional mean of Y|F: [E[Y₁|F], ..., E[Yₖ|F]]\n        where K = observation_dim\n\n        :param F: function evaluation Tensor, with shape [..., latent_dim]\n        :returns: mean [..., observation_dim]\n        \"\"\"\n        self._check_latent_dims(F)\n        expected_Y = self._conditional_mean(F)\n        self._check_data_dims(expected_Y)\n        return expected_Y\n\n    def _conditional_mean(self, F):\n        raise NotImplementedError\n\n    def conditional_variance(self, F):\n        \"\"\"\n        The conditional marginal variance of Y|F: [var(Y₁|F), ..., var(Yₖ|F)]\n        where K = observation_dim\n\n        :param F: function evaluation Tensor, with shape [..., latent_dim]\n        :returns: variance [..., observation_dim]\n        \"\"\"\n        self._check_latent_dims(F)\n        var_Y = self._conditional_variance(F)\n        self._check_data_dims(var_Y)\n        return var_Y\n\n    def _conditional_variance(self, F):\n        raise NotImplementedError\n\n    def predict_mean_and_var(self, Fmu, Fvar):\n        \"\"\"\n        Given a Normal distribution for the latent function,\n        return the mean and marginal variance of Y,\n\n        i.e. if\n            q(f) = N(Fmu, Fvar)\n\n        and this object represents\n\n            p(y|f)\n\n        then this method computes the predictive mean\n\n           ∫∫ y p(y|f)q(f) df dy\n\n        and the predictive variance\n\n           ∫∫ y² p(y|f)q(f) df dy  - [ ∫∫ y p(y|f)q(f) df dy ]²\n\n\n        :param Fmu: mean function evaluation Tensor, with shape [..., latent_dim]\n        :param Fvar: variance of function evaluation Tensor, with shape [..., latent_dim]\n        :returns: mean and variance, both with shape [..., observation_dim]\n        \"\"\"\n        self._check_latent_dims(Fmu)\n        self._check_latent_dims(Fvar)\n        mu, var = self._predict_mean_and_var(Fmu, Fvar)\n        self._check_data_dims(mu)\n        self._check_data_dims(var)\n        return mu, var\n\n    @abc.abstractmethod\n    def _predict_mean_and_var(self, Fmu, Fvar):\n        raise NotImplementedError\n\n    def predict_log_density(self, Fmu, Fvar, Y):\n        r\"\"\"\n        Given a Normal distribution for the latent function, and a datum Y,\n        compute the log predictive density of Y,\n\n        i.e. if\n            q(F) = N(Fmu, Fvar)\n\n        and this object represents\n\n            p(y|F)\n\n        then this method computes the predictive density\n\n            log ∫ p(y=Y|F)q(F) df\n\n        :param Fmu: mean function evaluation Tensor, with shape [..., latent_dim]\n        :param Fvar: variance of function evaluation Tensor, with shape [..., latent_dim]\n        :param Y: observation Tensor, with shape [..., observation_dim]:\n        :returns: log predictive density, with shape [...]\n        \"\"\"\n        tf.debugging.assert_equal(tf.shape(Fmu), tf.shape(Fvar))\n        self._check_last_dims_valid(Fmu, Y)\n        res = self._predict_log_density(Fmu, Fvar, Y)\n        self._check_return_shape(res, Fmu, Y)\n        return res\n\n    @abc.abstractmethod\n    def _predict_log_density(self, Fmu, Fvar, Y):\n        raise NotImplementedError\n\n    def predict_density(self, Fmu, Fvar, Y):\n        \"\"\"\n        Deprecated: see `predict_log_density`\n        \"\"\"\n        warnings.warn(\n            \"predict_density is deprecated and will be removed in GPflow 2.1, use predict_log_density instead\",\n            DeprecationWarning,\n        )\n        return self.predict_log_density(Fmu, Fvar, Y)\n\n    def variational_expectations(self, Fmu, Fvar, Y):\n        r\"\"\"\n        Compute the expected log density of the data, given a Gaussian\n        distribution for the function values,\n\n        i.e. if\n            q(f) = N(Fmu, Fvar)\n\n        and this object represents\n\n            p(y|f)\n\n        then this method computes\n\n           ∫ log(p(y=Y|f)) q(f) df.\n\n        This only works if the broadcasting dimension of the statistics of q(f) (mean and variance)\n        are broadcastable with that of the data Y.\n\n        :param Fmu: mean function evaluation Tensor, with shape [..., latent_dim]\n        :param Fvar: variance of function evaluation Tensor, with shape [..., latent_dim]\n        :param Y: observation Tensor, with shape [..., observation_dim]:\n        :returns: expected log density of the data given q(F), with shape [...]\n        \"\"\"\n        tf.debugging.assert_equal(tf.shape(Fmu), tf.shape(Fvar))\n        # returns an error if Y[:-1] and Fmu[:-1] do not broadcast together\n        _ = tf.broadcast_dynamic_shape(tf.shape(Fmu)[:-1], tf.shape(Y)[:-1])\n        self._check_last_dims_valid(Fmu, Y)\n        ret = self._variational_expectations(Fmu, Fvar, Y)\n        self._check_return_shape(ret, Fmu, Y)\n        return ret\n\n    @abc.abstractmethod\n    def _variational_expectations(self, Fmu, Fvar, Y):\n        raise NotImplementedError\n\n\nclass ScalarLikelihood(Likelihood):\n    \"\"\"\n    A likelihood class that helps with scalar likelihood functions: likelihoods where\n    each scalar latent function is associated with a single scalar observation variable.\n\n    If there are multiple latent functions, then there must be a corresponding number of data: we\n    check for this.\n\n    The `Likelihood` class contains methods to compute marginal statistics of functions\n    of the latents and the data ϕ(y,f):\n     * variational_expectations:  ϕ(y,f) = log p(y|f)\n     * predict_log_density: ϕ(y,f) = p(y|f)\n    Those statistics are computed after having first marginalized the latent processes f\n    under a multivariate normal distribution q(f) that is fully factorized.\n\n    Some univariate integrals can be done by quadrature: we implement quadrature routines for 1D\n    integrals in this class, though they may be overwritten by inheriting classes where those\n    integrals are available in closed form.\n    \"\"\"\n\n    def __init__(self, **kwargs):\n        super().__init__(latent_dim=None, observation_dim=None, **kwargs)\n        self.num_gauss_hermite_points = 20\n\n    def _check_last_dims_valid(self, F, Y):\n        \"\"\"\n        Assert that the dimensions of the latent functions and the data are compatible\n        :param F: function evaluation Tensor, with shape [..., latent_dim]\n        :param Y: observation Tensor, with shape [..., latent_dim]\n        \"\"\"\n        tf.debugging.assert_shapes([(F, (..., \"num_latent\")), (Y, (..., \"num_latent\"))])\n\n    def _log_prob(self, F, Y):\n        r\"\"\"\n        Compute log p(Y|F), where by convention we sum out the last axis as it represented\n        independent latent functions and observations.\n        :param F: function evaluation Tensor, with shape [..., latent_dim]\n        :param Y: observation Tensor, with shape [..., latent_dim]\n        \"\"\"\n        return tf.reduce_sum(self._scalar_log_density(F, Y), axis=-1)\n\n    def _scalar_log_density(self, F, Y):\n        raise NotImplementedError\n\n    def _variational_expectations(self, Fmu, Fvar, Y):\n        r\"\"\"\n        Here, we implement a default Gauss-Hermite quadrature routine, but some\n        likelihoods (Gaussian, Poisson) will implement specific cases.\n        :param Fmu: mean function evaluation Tensor, with shape [..., latent_dim]\n        :param Fvar: variance of function evaluation Tensor, with shape [..., latent_dim]\n        :param Y: observation Tensor, with shape [..., latent_dim]:\n        :returns: variational expectations, with shape [...]\n        \"\"\"\n        return tf.reduce_sum(\n            ndiagquad(self._scalar_log_density, self.num_gauss_hermite_points, Fmu, Fvar, Y=Y),\n            axis=-1,\n        )\n\n    def _predict_log_density(self, Fmu, Fvar, Y):\n        r\"\"\"\n        Here, we implement a default Gauss-Hermite quadrature routine, but some\n        likelihoods (Gaussian, Poisson) will implement specific cases.\n        :param Fmu: mean function evaluation Tensor, with shape [..., latent_dim]\n        :param Fvar: variance of function evaluation Tensor, with shape [..., latent_dim]\n        :param Y: observation Tensor, with shape [..., latent_dim]:\n        :returns: log predictive density, with shape [...]\n        \"\"\"\n        return tf.reduce_sum(\n            ndiagquad(\n                self._scalar_log_density,\n                self.num_gauss_hermite_points,\n                Fmu,\n                Fvar,\n                logspace=True,\n                Y=Y,\n            ),\n            axis=-1,\n        )\n\n    def _predict_mean_and_var(self, Fmu, Fvar):\n        r\"\"\"\n        Here, we implement a default Gauss-Hermite quadrature routine, but some\n        likelihoods (e.g. Gaussian) will implement specific cases.\n\n        :param Fmu: mean function evaluation Tensor, with shape [..., latent_dim]\n        :param Fvar: variance of function evaluation Tensor, with shape [..., latent_dim]\n        :returns: mean and variance, both with shape [..., observation_dim]\n        \"\"\"\n\n        def integrand(*X):\n            return self.conditional_variance(*X) + self.conditional_mean(*X) ** 2\n\n        integrands = [self.conditional_mean, integrand]\n        E_y, E_y2 = ndiagquad(integrands, self.num_gauss_hermite_points, Fmu, Fvar)\n        V_y = E_y2 - E_y ** 2\n        return E_y, V_y\n\n\nclass Gaussian(ScalarLikelihood):\n    r\"\"\"\n    The Gaussian likelihood is appropriate where uncertainties associated with the data are\n    believed to follow a normal distribution, with constant variance.\n\n    Very small uncertainties can lead to numerical instability during the\n    optimization process. A lower bound of 1e-6 is therefore imposed on the likelihood variance\n    by default.\n    \"\"\"\n\n    def __init__(self, variance=1.0, variance_lower_bound=1e-6, **kwargs):\n        super().__init__(**kwargs)\n        self.variance = Parameter(variance, transform=positive(lower=variance_lower_bound))\n\n    def _scalar_log_density(self, F, Y):\n        return logdensities.gaussian(Y, F, self.variance)\n\n    def _conditional_mean(self, F):  # pylint: disable=R0201\n        return tf.identity(F)\n\n    def _conditional_variance(self, F):\n        return tf.fill(tf.shape(F), tf.squeeze(self.variance))\n\n    def _predict_mean_and_var(self, Fmu, Fvar):\n        return tf.identity(Fmu), Fvar + self.variance\n\n    def _predict_log_density(self, Fmu, Fvar, Y):\n        return tf.reduce_sum(logdensities.gaussian(Y, Fmu, Fvar + self.variance), axis=-1)\n\n    def _variational_expectations(self, Fmu, Fvar, Y):\n        return tf.reduce_sum(\n            -0.5 * np.log(2 * np.pi)\n            - 0.5 * tf.math.log(self.variance)\n            - 0.5 * ((Y - Fmu) ** 2 + Fvar) / self.variance,\n            axis=-1,\n        )\n\n\nclass Poisson(ScalarLikelihood):\n    r\"\"\"\n    Poisson likelihood for use with count data, where the rate is given by the (transformed) GP.\n\n    let g(.) be the inverse-link function, then this likelihood represents\n\n    p(yᵢ | fᵢ) = Poisson(yᵢ | g(fᵢ) * binsize)\n\n    Note:binsize\n    For use in a Log Gaussian Cox process (doubly stochastic model) where the\n    rate function of an inhomogeneous Poisson process is given by a GP.  The\n    intractable likelihood can be approximated via a Riemann sum (with bins\n    of size 'binsize') and using this Poisson likelihood.\n    \"\"\"\n\n    def __init__(self, invlink=tf.exp, binsize=1.0, **kwargs):\n        super().__init__(**kwargs)\n        self.invlink = invlink\n        self.binsize = np.array(binsize, dtype=default_float())\n\n    def _scalar_log_density(self, F, Y):\n        return logdensities.poisson(Y, self.invlink(F) * self.binsize)\n\n    def _conditional_variance(self, F):\n        return self.invlink(F) * self.binsize\n\n    def _conditional_mean(self, F):\n        return self.invlink(F) * self.binsize\n\n    def _variational_expectations(self, Fmu, Fvar, Y):\n        if self.invlink is tf.exp:\n            return tf.reduce_sum(\n                Y * Fmu\n                - tf.exp(Fmu + Fvar / 2) * self.binsize\n                - tf.math.lgamma(Y + 1)\n                + Y * tf.math.log(self.binsize),\n                axis=-1,\n            )\n        return super()._variational_expectations(Fmu, Fvar, Y)\n\n\nclass Exponential(ScalarLikelihood):\n    def __init__(self, invlink=tf.exp, **kwargs):\n        super().__init__(**kwargs)\n        self.invlink = invlink\n\n    def _scalar_log_density(self, F, Y):\n        return logdensities.exponential(Y, self.invlink(F))\n\n    def _conditional_mean(self, F):\n        return self.invlink(F)\n\n    def _conditional_variance(self, F):\n        return tf.square(self.invlink(F))\n\n    def _variational_expectations(self, Fmu, Fvar, Y):\n        if self.invlink is tf.exp:\n            return tf.reduce_sum(-tf.exp(-Fmu + Fvar / 2) * Y - Fmu, axis=-1)\n        return super()._variational_expectations(Fmu, Fvar, Y)\n\n\nclass StudentT(ScalarLikelihood):\n    def __init__(self, scale=1.0, df=3.0, **kwargs):\n        \"\"\"\n        :param scale float: scale parameter\n        :param df float: degrees of freedom\n        \"\"\"\n        super().__init__(**kwargs)\n        self.df = df\n        self.scale = Parameter(scale, transform=positive())\n\n    def _scalar_log_density(self, F, Y):\n        return logdensities.student_t(Y, F, self.scale, self.df)\n\n    def _conditional_mean(self, F):\n        return F\n\n    def _conditional_variance(self, F):\n        var = (self.scale ** 2) * (self.df / (self.df - 2.0))\n        return tf.fill(tf.shape(F), tf.squeeze(var))\n\n\nclass Bernoulli(ScalarLikelihood):\n    def __init__(self, invlink=inv_probit, **kwargs):\n        super().__init__(**kwargs)\n        self.invlink = invlink\n\n    def _scalar_log_density(self, F, Y):\n        return logdensities.bernoulli(Y, self.invlink(F))\n\n    def _predict_mean_and_var(self, Fmu, Fvar):\n        if self.invlink is inv_probit:\n            p = inv_probit(Fmu / tf.sqrt(1 + Fvar))\n            return p, p - tf.square(p)\n        else:\n            # for other invlink, use quadrature\n            return super()._predict_mean_and_var(Fmu, Fvar)\n\n    def _predict_log_density(self, Fmu, Fvar, Y):\n        p = self.predict_mean_and_var(Fmu, Fvar)[0]\n        return logdensities.bernoulli(Y, p)\n\n    def _conditional_mean(self, F):\n        return self.invlink(F)\n\n    def _conditional_variance(self, F):\n        p = self.conditional_mean(F)\n        return p - (p ** 2)\n\n\nclass Gamma(ScalarLikelihood):\n    \"\"\"\n    Use the transformed GP to give the *scale* (inverse rate) of the Gamma\n    \"\"\"\n\n    def __init__(self, invlink=tf.exp, **kwargs):\n        super().__init__(**kwargs)\n        self.invlink = invlink\n        self.shape = Parameter(1.0, transform=positive())\n\n    def _scalar_log_density(self, F, Y):\n        return logdensities.gamma(Y, self.shape, self.invlink(F))\n\n    def _conditional_mean(self, F):\n        return self.shape * self.invlink(F)\n\n    def _conditional_variance(self, F):\n        scale = self.invlink(F)\n        return self.shape * (scale ** 2)\n\n    def _variational_expectations(self, Fmu, Fvar, Y):\n        if self.invlink is tf.exp:\n            return tf.reduce_sum(\n                -self.shape * Fmu\n                - tf.math.lgamma(self.shape)\n                + (self.shape - 1.0) * tf.math.log(Y)\n                - Y * tf.exp(-Fmu + Fvar / 2.0),\n                axis=-1,\n            )\n        else:\n            return super()._variational_expectations(Fmu, Fvar, Y)\n\n\nclass Beta(ScalarLikelihood):\n    \"\"\"\n    This uses a reparameterisation of the Beta density. We have the mean of the\n    Beta distribution given by the transformed process:\n\n        m = invlink(f)\n\n    and a scale parameter. The familiar α, β parameters are given by\n\n        m     = α / (α + β)\n        scale = α + β\n\n    so:\n        α = scale * m\n        β  = scale * (1-m)\n    \"\"\"\n\n    def __init__(self, invlink=inv_probit, scale=1.0, **kwargs):\n        super().__init__(**kwargs)\n        self.scale = Parameter(scale, transform=positive())\n        self.invlink = invlink\n\n    def _scalar_log_density(self, F, Y):\n        mean = self.invlink(F)\n        alpha = mean * self.scale\n        beta = self.scale - alpha\n        return logdensities.beta(Y, alpha, beta)\n\n    def _conditional_mean(self, F):\n        return self.invlink(F)\n\n    def _conditional_variance(self, F):\n        mean = self.invlink(F)\n        return (mean - tf.square(mean)) / (self.scale + 1.0)\n\n\nclass MultiClass(Likelihood):\n    def __init__(self, num_classes, invlink=None, **kwargs):\n        \"\"\"\n        A likelihood for multi-way classification.  Currently the only valid\n        choice of inverse-link function (invlink) is an instance of RobustMax.\n\n        For most problems, the stochastic `Softmax` likelihood may be more\n        appropriate (note that you then cannot use Scipy optimizer).\n        \"\"\"\n        super().__init__(latent_dim=num_classes, observation_dim=None, **kwargs)\n        self.num_classes = num_classes\n        self.num_gauss_hermite_points = 20\n\n        if invlink is None:\n            invlink = RobustMax(self.num_classes)\n\n        if not isinstance(invlink, RobustMax):\n            raise NotImplementedError\n\n        self.invlink = invlink\n\n    def _log_prob(self, F, Y):\n        hits = tf.equal(tf.expand_dims(tf.argmax(F, 1), 1), tf.cast(Y, tf.int64))\n        yes = tf.ones(tf.shape(Y), dtype=default_float()) - self.invlink.epsilon\n        no = tf.zeros(tf.shape(Y), dtype=default_float()) + self.invlink.eps_k1\n        p = tf.where(hits, yes, no)\n        return tf.reduce_sum(tf.math.log(p), axis=-1)\n\n    def _variational_expectations(self, Fmu, Fvar, Y):\n        gh_x, gh_w = hermgauss(self.num_gauss_hermite_points)\n        p = self.invlink.prob_is_largest(Y, Fmu, Fvar, gh_x, gh_w)\n        ve = p * tf.math.log(1.0 - self.invlink.epsilon) + (1.0 - p) * tf.math.log(\n            self.invlink.eps_k1\n        )\n        return tf.reduce_sum(ve, axis=-1)\n\n    def _predict_mean_and_var(self, Fmu, Fvar):\n        possible_outputs = [\n            tf.fill(tf.stack([tf.shape(Fmu)[0], 1]), np.array(i, dtype=np.int64))\n            for i in range(self.num_classes)\n        ]\n        ps = [self._predict_non_logged_density(Fmu, Fvar, po) for po in possible_outputs]\n        ps = tf.transpose(tf.stack([tf.reshape(p, (-1,)) for p in ps]))\n        return ps, ps - tf.square(ps)\n\n    def _predict_log_density(self, Fmu, Fvar, Y):\n        return tf.reduce_sum(tf.math.log(self._predict_non_logged_density(Fmu, Fvar, Y)), axis=-1)\n\n    def _predict_non_logged_density(self, Fmu, Fvar, Y):\n        gh_x, gh_w = hermgauss(self.num_gauss_hermite_points)\n        p = self.invlink.prob_is_largest(Y, Fmu, Fvar, gh_x, gh_w)\n        den = p * (1.0 - self.invlink.epsilon) + (1.0 - p) * (self.invlink.eps_k1)\n        return den\n\n    def _conditional_mean(self, F):\n        return self.invlink(F)\n\n    def _conditional_variance(self, F):\n        p = self.conditional_mean(F)\n        return p - tf.square(p)\n\n\nclass SwitchedLikelihood(ScalarLikelihood):\n    def __init__(self, likelihood_list, **kwargs):\n        \"\"\"\n        In this likelihood, we assume at extra column of Y, which contains\n        integers that specify a likelihood from the list of likelihoods.\n        \"\"\"\n        super().__init__(**kwargs)\n        for l in likelihood_list:\n            assert isinstance(l, ScalarLikelihood)\n        self.likelihoods = likelihood_list\n\n    def _partition_and_stitch(self, args, func_name):\n        \"\"\"\n        args is a list of tensors, to be passed to self.likelihoods.<func_name>\n\n        args[-1] is the 'Y' argument, which contains the indexes to self.likelihoods.\n\n        This function splits up the args using dynamic_partition, calls the\n        relevant function on the likelihoods, and re-combines the result.\n        \"\"\"\n        # get the index from Y\n        Y = args[-1]\n        ind = Y[..., -1]\n        ind = tf.cast(ind, tf.int32)\n        Y = Y[..., :-1]\n        args[-1] = Y\n\n        # split up the arguments into chunks corresponding to the relevant likelihoods\n        args = zip(*[tf.dynamic_partition(X, ind, len(self.likelihoods)) for X in args])\n\n        # apply the likelihood-function to each section of the data\n        funcs = [getattr(lik, func_name) for lik in self.likelihoods]\n        results = [f(*args_i) for f, args_i in zip(funcs, args)]\n\n        # stitch the results back together\n        partitions = tf.dynamic_partition(tf.range(0, tf.size(ind)), ind, len(self.likelihoods))\n        results = tf.dynamic_stitch(partitions, results)\n\n        return results\n\n    def _check_last_dims_valid(self, F, Y):\n        tf.assert_equal(tf.shape(F)[-1], tf.shape(Y)[-1] - 1)\n\n    def _scalar_log_density(self, F, Y):\n        return self._partition_and_stitch([F, Y], \"_scalar_log_density\")\n\n    def _predict_log_density(self, Fmu, Fvar, Y):\n        return self._partition_and_stitch([Fmu, Fvar, Y], \"predict_log_density\")\n\n    def _variational_expectations(self, Fmu, Fvar, Y):\n        return self._partition_and_stitch([Fmu, Fvar, Y], \"variational_expectations\")\n\n    def _predict_mean_and_var(self, Fmu, Fvar):\n        mvs = [lik.predict_mean_and_var(Fmu, Fvar) for lik in self.likelihoods]\n        mu_list, var_list = zip(*mvs)\n        mu = tf.concat(mu_list, 1)\n        var = tf.concat(var_list, 1)\n        return mu, var\n\n    def _conditional_mean(self, F):\n        raise NotImplementedError\n\n    def _conditional_variance(self, F):\n        raise NotImplementedError\n\n\nclass Ordinal(ScalarLikelihood):\n    \"\"\"\n    A likelihood for doing ordinal regression.\n\n    The data are integer values from 0 to k, and the user must specify (k-1)\n    'bin edges' which define the points at which the labels switch. Let the bin\n    edges be [a₀, a₁, ... aₖ₋₁], then the likelihood is\n\n    p(Y=0|F) = ɸ((a₀ - F) / σ)\n    p(Y=1|F) = ɸ((a₁ - F) / σ) - ɸ((a₀ - F) / σ)\n    p(Y=2|F) = ɸ((a₂ - F) / σ) - ɸ((a₁ - F) / σ)\n    ...\n    p(Y=K|F) = 1 - ɸ((aₖ₋₁ - F) / σ)\n\n    where ɸ is the cumulative density function of a Gaussian (the inverse probit\n    function) and σ is a parameter to be learned. A reference is:\n\n    @article{chu2005gaussian,\n      title={Gaussian processes for ordinal regression},\n      author={Chu, Wei and Ghahramani, Zoubin},\n      journal={Journal of Machine Learning Research},\n      volume={6},\n      number={Jul},\n      pages={1019--1041},\n      year={2005}\n    }\n    \"\"\"\n\n    def __init__(self, bin_edges, **kwargs):\n        \"\"\"\n        bin_edges is a numpy array specifying at which function value the\n        output label should switch. If the possible Y values are 0...K, then\n        the size of bin_edges should be (K-1).\n        \"\"\"\n        super().__init__(**kwargs)\n        self.bin_edges = bin_edges\n        self.num_bins = bin_edges.size + 1\n        self.sigma = Parameter(1.0, transform=positive())\n\n    def _scalar_log_density(self, F, Y):\n        Y = to_default_int(Y)\n        scaled_bins_left = tf.concat([self.bin_edges / self.sigma, np.array([np.inf])], 0)\n        scaled_bins_right = tf.concat([np.array([-np.inf]), self.bin_edges / self.sigma], 0)\n        selected_bins_left = tf.gather(scaled_bins_left, Y)\n        selected_bins_right = tf.gather(scaled_bins_right, Y)\n\n        return tf.math.log(\n            inv_probit(selected_bins_left - F / self.sigma)\n            - inv_probit(selected_bins_right - F / self.sigma)\n            + 1e-6\n        )\n\n    def _make_phi(self, F):\n        \"\"\"\n        A helper function for making predictions. Constructs a probability\n        matrix where each row output the probability of the corresponding\n        label, and the rows match the entries of F.\n\n        Note that a matrix of F values is flattened.\n        \"\"\"\n        scaled_bins_left = tf.concat([self.bin_edges / self.sigma, np.array([np.inf])], 0)\n        scaled_bins_right = tf.concat([np.array([-np.inf]), self.bin_edges / self.sigma], 0)\n        return inv_probit(scaled_bins_left - tf.reshape(F, (-1, 1)) / self.sigma) - inv_probit(\n            scaled_bins_right - tf.reshape(F, (-1, 1)) / self.sigma\n        )\n\n    def _conditional_mean(self, F):\n        phi = self._make_phi(F)\n        Ys = tf.reshape(np.arange(self.num_bins, dtype=default_float()), (-1, 1))\n        return tf.reshape(tf.linalg.matmul(phi, Ys), tf.shape(F))\n\n    def _conditional_variance(self, F):\n        phi = self._make_phi(F)\n        Ys = tf.reshape(np.arange(self.num_bins, dtype=default_float()), (-1, 1))\n        E_y = phi @ Ys\n        E_y2 = phi @ (Ys ** 2)\n        return tf.reshape(E_y2 - E_y ** 2, tf.shape(F))\n\n\nclass MonteCarloLikelihood(Likelihood):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.num_monte_carlo_points = 100\n\n    def _mc_quadrature(self, funcs, Fmu, Fvar, logspace: bool = False, epsilon=None, **Ys):\n        return ndiag_mc(funcs, self.num_monte_carlo_points, Fmu, Fvar, logspace, epsilon, **Ys)\n\n    def _predict_mean_and_var(self, Fmu, Fvar, epsilon=None):\n        r\"\"\"\n        Given a Normal distribution for the latent function,\n        return the mean of Y\n\n        if\n            q(f) = N(Fmu, Fvar)\n\n        and this object represents\n\n            p(y|f)\n\n        then this method computes the predictive mean\n\n           ∫∫ y p(y|f)q(f) df dy\n\n        and the predictive variance\n\n           ∫∫ y² p(y|f)q(f) df dy  - [ ∫∫ y p(y|f)q(f) df dy ]²\n\n        Here, we implement a default Monte Carlo routine.\n        \"\"\"\n        integrand2 = lambda *X: self.conditional_variance(*X) + tf.square(self.conditional_mean(*X))\n        E_y, E_y2 = self._mc_quadrature(\n            [self.conditional_mean, integrand2], Fmu, Fvar, epsilon=epsilon\n        )\n        V_y = E_y2 - tf.square(E_y)\n        return E_y, V_y  # [N, D]\n\n    def _predict_log_density(self, Fmu, Fvar, Y, epsilon=None):\n        r\"\"\"\n        Given a Normal distribution for the latent function, and a datum Y,\n        compute the log predictive density of Y.\n\n        i.e. if\n            q(f) = N(Fmu, Fvar)\n\n        and this object represents\n\n            p(y|f)\n\n        then this method computes the predictive density\n\n            log ∫ p(y=Y|f)q(f) df\n\n        Here, we implement a default Monte Carlo routine.\n        \"\"\"\n        return tf.reduce_sum(\n            self._mc_quadrature(self.log_prob, Fmu, Fvar, Y=Y, logspace=True, epsilon=epsilon),\n            axis=-1,\n        )\n\n    def _variational_expectations(self, Fmu, Fvar, Y, epsilon=None):\n        r\"\"\"\n        Compute the expected log density of the data, given a Gaussian\n        distribution for the function values.\n\n        if\n            q(f) = N(Fmu, Fvar)  - Fmu: [N, D]  Fvar: [N, D]\n\n        and this object represents\n\n            p(y|f)  - Y: [N, 1]\n\n        then this method computes\n\n           ∫ (log p(y|f)) q(f) df.\n\n\n        Here, we implement a default Monte Carlo quadrature routine.\n        \"\"\"\n        return tf.reduce_sum(\n            self._mc_quadrature(self.log_prob, Fmu, Fvar, Y=Y, epsilon=epsilon), axis=-1\n        )\n\n\nclass GaussianMC(MonteCarloLikelihood, Gaussian):\n    \"\"\"\n    Stochastic version of Gaussian likelihood for comparison.\n    \"\"\"\n\n    pass\n\n\nclass Softmax(MonteCarloLikelihood):\n    \"\"\"\n    The soft-max multi-class likelihood.  It can only provide a stochastic\n    Monte-Carlo estimate of the variational expectations term, but this\n    added variance tends to be small compared to that due to mini-batching\n    (when using the SVGP model).\n    \"\"\"\n\n    def __init__(self, num_classes, **kwargs):\n        super().__init__(latent_dim=num_classes, observation_dim=None, **kwargs)\n        self.num_classes = self.latent_dim\n\n    def _log_prob(self, F, Y):\n        return -tf.nn.sparse_softmax_cross_entropy_with_logits(logits=F, labels=Y[:, 0])\n\n    def _conditional_mean(self, F):\n        return tf.nn.softmax(F)\n\n    def _conditional_variance(self, F):\n        p = self.conditional_mean(F)\n        return p - p ** 2\n", "meta": {"hexsha": "8a80ab116acd3e5ad6215d6ddf35d929839173e4", "size": 34040, "ext": "py", "lang": "Python", "max_stars_repo_path": "gpflow/likelihoods/likelihoods.py", "max_stars_repo_name": "christabella/GPflow", "max_stars_repo_head_hexsha": "30824d289f8ee3f58d4249238c8b7267e6a0b2fc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gpflow/likelihoods/likelihoods.py", "max_issues_repo_name": "christabella/GPflow", "max_issues_repo_head_hexsha": "30824d289f8ee3f58d4249238c8b7267e6a0b2fc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gpflow/likelihoods/likelihoods.py", "max_forks_repo_name": "christabella/GPflow", "max_forks_repo_head_hexsha": "30824d289f8ee3f58d4249238c8b7267e6a0b2fc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4844587353, "max_line_length": 111, "alphanum_fraction": 0.6415393655, "include": true, "reason": "import numpy", "num_tokens": 8496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.19256215144255093}}
{"text": "\"\"\" hat_model.py models the environment and components for heliotropic hat \n    in 3D. \n\n    Author: Jonathon Sather\n    Last updated: 4/15/2017\n\"\"\"\n\nimport numpy as np\nimport pdb\n\nclass DirectionalSource:\n    \"\"\" Directional light source w/ direction and intensity. \"\"\"\n\n    def __init__(self, (dirX, dirY, dirZ)):\n        self.direction = np.array([dirX, dirY, dirZ])\n        self.intensity = np.linalg.norm(self.direction)\n\nclass PointSource:\n    \"\"\" Point light source w/ position and intensity. \"\"\"\n\n    def __init__(self, (x, y, z), intensity):\n        self.position = np.array([x, y, z])\n        self.intensity = intensity\n\nclass LightSensor:\n    \"\"\" Light sensor w/ value proportional to light intensity. \"\"\"\n\n    def __init__(self, (x, y, z), (dirX, dirY, dirZ)):\n        self.position = np.array([x, y, z])\n        self.orientation = (np.array([dirX, dirY, dirZ]) /\n         np.linalg.norm(np.array([dirX, dirY, dirZ]))) # Ensure unit magnitude\n        self.value = 0\n        self.color = np.array([255, 255, 0])\n\nclass Hat:\n    \"\"\" A standard baseball hat with spacial orientation and bill position.\n        Bill is represented as circular w/ offset from center. Hat class also\n        stores light sensors attached to hat as a list of light sensor objects.\n    \"\"\"\n\n    def __init__(self, (x, y, z), theta, scale, restricted=True):\n        self.billDiam = 1.5 * scale\n        self.billOffset = 0.9 * scale\n        self.color = np.array([0, 0, 255]) \n        self.diam = 2 * scale\n        self.lightSensors = []\n        self.position = np.array([x, y, z])\n        self.restricted = restricted    # Restricted bill rotation\n        self.theta = theta\n        self.thetaDot = 2 * np.pi / 100 # Constant rotational speed\n\n    def getBillCenter(self):\n        \"\"\" Method to find the center of the bill based on angular position\n            and hat geometry.\n        \"\"\"\n\n        center = self.position + np.array([np.cos(self.theta) *\n                 self.billOffset, np.sin(self.theta) * self.billOffset, 0])\n        return center\n\n\n    def getLSValues(self, mode='no_noise'):\n        \"\"\" Fetches values of light sensors currently attached to hat. \"\"\"\n\n        num_ls = len(self.lightSensors)\n        ls_vals = np.empty((1, num_ls))\n\n        for ls in range(num_ls):\n            ls_vals[0,ls] = self.lightSensors[ls].value\n\n        if mode == 'add_noise':\n            ls_vals += np.random.normal(scale=0.00001,size=(1,num_ls))\n\n        return ls_vals\n\n    def get_state(self, pot=True, actions=None):\n        \"\"\" Returns current state of hat (light sensor values + bill angle in\n            numpy array).\n        \"\"\"\n        \n        if pot: # State w/ potentiometer\n            state = np.transpose(np.hstack((self.getLSValues(),\n                                 np.array([[self.theta]]))))\n        else:   # State w/ last actions\n            state = np.transpose(np.hstack((self.getLSValues(),\n                                 np.array([actions]))))\n        return state\n\n    def includeLightSensors(self, quantity):\n        \"\"\" Adds <quantity> light sensors evenly spaced around hat base. \n            Note that this method gets rid of any previously included \n            light sensors.\n        \"\"\"\n\n        self.lightSensors = []\n        sectorAngle = 2 * np.pi / quantity\n\n        for i in range(quantity):\n            (dx, dy, dz) = (np.cos(sectorAngle * i), np.sin(sectorAngle *\n             i), 0)\n            (x, y, z) = (self.position[0] + dx, self.position[1] + dy,\n                         self.position[2] + dz)\n\n            self.lightSensors.append(LightSensor((x, y, z), (dx, dy, dz)))\n\n    def rotateBill(self, direction):\n        \"\"\" Rotates bill based on input direction and angular velocity. \"\"\"\n        \n        update = self.theta + direction * self.thetaDot\n        if self.restricted:\n            if update < 0 or update > (2 * np.pi):  # Boundary at 0/2*pi\n                pass\n            else:                                   # No boundary issues\n                self.theta = update\n        else:\n            self.theta = update % (2 * np.pi)\n\n    def rotateBillCCW(self):\n        \"\"\" Rotates bill counter-clockwise. Includes stop at 0 radians by\n            default. Return 1 if non-restricted rotation. 0 if restricted.\n        \"\"\"\n\n        update = self.theta - self.thetaDot\n        rotation = 1\n\n        if self.restricted:\n            if update < 0:\n                rotation = 0\n            else:\n                self.theta = update\n        else:\n            self.theta = self.theta % (2 * np.pi)\n\n        return rotation\n\n    def rotateBillCW(self):\n        \"\"\" Rotates bill clockwise. Includes stop at 0 radians by default.\n            Return 1 if non-restricted rotation. 0 if restricted.\n        \"\"\"\n\n        update = self.theta + self.thetaDot\n        rotation = 1\n\n        if self.restricted:\n            if update > (2 * np.pi):   # Overflow pi to -pi\n                rotation = 0\n            else:                                          \n                self.theta = update\n        else:\n            self.theta = update % (2 * np.pi)\n\n        return rotation\n\n\n    def updateSpeed(self, thetaDot):\n        \"\"\" Method to update self.thetadot. \"\"\"\n\n        self.thetaDot = thetaDot\n\nclass Environment: \n    \"\"\" Environment contains data and regarding the hat environment. \"\"\"\n\n    def __init__(self, (width, height)):\n        self.boundary = np.array([width, height])\n        self.color = np.array([255, 255, 255])\n\n        self.hat = None\n        self.directionalSources = []\n        self.pointSources = []\n        self.ambient = 0\n\n    def addHat(self, hat):\n        \"\"\" Method for adding or replacing hat. \"\"\"\n\n        self.hat = hat\n\n    def updateColor(self, (r, g, b)):\n        \"\"\" Updates the color of the environment. \"\"\"\n\n        self.color = np.array([r, g, b])\n\n    def updateAmbient(self, ambient):\n        \"\"\" Updates the ambient light value of the environment. \"\"\"\n\n        self.ambient = ambient\n\n    def addDirectionalSource(self, (dirX, dirY, dirZ)):\n        \"\"\" Adds a directional source to the environment. \"\"\"\n\n        self.directionalSources.append(DirectionalSource((dirX, dirY, dirZ)))\n\n    def addPointSource(self, (x, y, z), intensity):\n        \"\"\" Adds a point light source to the environment. \"\"\"\n\n        self.pointSources.append(PointSource((x, y, z), intensity))\n\n    def clearSources(self):\n        \"\"\" Clears the ambient, point and directional light sources from \n            the environment.\n        \"\"\"\n\n        self.directionalSources = []\n        self.pointSources = []\n        self.ambient = 0\n\n    def notObstructedDirectional(self, hat, lightSensor, directionalSource):\n        \"\"\" Returns 0 if light sensor obstructed from directional source by\n            hat bill or base.\n        \"\"\"\n        distance = np.linalg.norm(lightSensor.position - hat.getBillCenter())\n\n        # Only account for bill if light directed downwards.\n        if np.dot(directionalSource.direction, np.array([0,0,1])) < 0:\n            direction_down = 1\n        else:\n            direction_down = 0\n\n        if (((distance < hat.billDiam / 2) and direction_down) or\n         (np.dot(lightSensor.orientation, directionalSource.direction) > 0)):\n            return 0\n        \n        return 1\n\n    def notObstructedPoint(self, hat, lightSensor, pointSource):\n        \"\"\" Returns 0 if light sensor obstructed from point source by hat\n            bill or base.\n        \"\"\"\n\n        distance = np.linalg.norm(lightSensor.position - hat.getBillCenter())\n\n        dir = lightSensor.position - pointSource.position\n\n        # Only account for bill if light directed downwards.\n        if np.dot(dir, np.array([0, 0, 1])) < 0:\n            direction_down = 1\n        else:\n            direction_down = 0\n  \n        if (((distance < hat.billDiam / 2) and direction_down) or\n         (np.dot(lightSensor.orientation, dir) > 0)):\n            return 0\n\n        return 1\n\n    def updateLightSensor(self, lightSensor):\n        \"\"\" Updates a single light sensor's value, considering ambient, point,\n            and directional components.\n        \"\"\"\n\n        # Ambient\n        lightSensor.value = self.ambient\n\n        # Point\n        for p in self.pointSources:\n            #pdb.set_trace()\n            inv_square = (1 / \n             (np.linalg.norm(p.position - lightSensor.position) ** 2))\n\n            lightSensor.value +=  (\n             inv_square * (self.notObstructedPoint(self.hat, \n             lightSensor, p) * np.dot(lightSensor.orientation, - \n             (lightSensor.position - p.position) * p.intensity / \n             np.linalg.norm(lightSensor.position - p.position))))\n\n        # Directional\n        for d in self.directionalSources:\n            lightSensor.value += (self.notObstructedDirectional(self.hat, \n             lightSensor, d) * np.dot(lightSensor.orientation, - d.direction))\n\n    def update(self):\n        \"\"\" Updates all light sensors on the hat. \"\"\"\n\n        for lightSensor in self.hat.lightSensors:\n            self.updateLightSensor(lightSensor)\n\nif __name__ == '__main__':\n    pass\n\n\n", "meta": {"hexsha": "26423ab68c1e90cad8acf3aee71b398cea9c6080", "size": 9076, "ext": "py", "lang": "Python", "max_stars_repo_path": "simulation_no_pot/hat_model.py", "max_stars_repo_name": "jsather/heliotropic-hat", "max_stars_repo_head_hexsha": "9e17dfb45e6d0d5852ef331e4dbb2511e4282dc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulation_no_pot/hat_model.py", "max_issues_repo_name": "jsather/heliotropic-hat", "max_issues_repo_head_hexsha": "9e17dfb45e6d0d5852ef331e4dbb2511e4282dc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulation_no_pot/hat_model.py", "max_forks_repo_name": "jsather/heliotropic-hat", "max_forks_repo_head_hexsha": "9e17dfb45e6d0d5852ef331e4dbb2511e4282dc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4142857143, "max_line_length": 79, "alphanum_fraction": 0.572939621, "include": true, "reason": "import numpy", "num_tokens": 2108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.19256215144255093}}
{"text": "#! /usr/bin/env python\nimport os\nimport numpy as np\nfrom PythonPhot import getpsf, aper\nfrom astropy.io import fits as pyfits\n\n\ndef getcamera(imfile):\n    \"\"\" Determine the camera name (e.g. ACS-WFC or WFC3-IR)\n    from the header of the given image.  The input imfile\n    may be a string giving a fits filename, a pyfits hdu object,\n    or a pyfits header.\n    :param imfile:\n    :return:\n    \"\"\"\n    import hstphot\n    hdr = hstphot.getheader(imfile)\n    instrument, detector = '', ''\n    if 'CAMERA' in hdr:\n        instrument = hdr['CAMERA']\n        detector = ''\n    elif 'INSTRUME' in hdr:\n        instrument = hdr['INSTRUME']\n    if 'DETECTOR' in hdr:\n        detector = hdr['DETECTOR']\n    camera = '-'.join([instrument, detector]).rstrip('-')\n    return camera\n\n\ndef mkpsfmodel_stdstar(psfimdir=\"./\", psfrad=0.3, fitrad=0.15,\n                       starname='g191b2b',\n                       pixscale=0.03,\n                       bandlist=['f435w', 'f606w', 'f814w'],\n                       verbose=True):\n    \"\"\" Construct a set of psf models from drizzled HST images of a\n    standard star, with the star in the center of the image.\n\n    :param psfimdir: psf image directory (where the input std star images are\n       and also where the output psf model images will be put)\n    :param psfrad: the scalar radius, in arcsec, of the circular area within\n                which the PSF will be defined.  This should be slightly larger\n                than the radius of the brightest star that one will be\n                interested in.\n    :param fitrad: the scalar radius, in arcsec, of the circular area used in\n               the least-square star fits.  Stetson suggest that fitrad should\n               approximately equal to the FWHM, slightly less for crowded\n               fields.  (fitrad must be smaller than psfrad.)\n\n    :return : None\n    \"\"\"\n    # radius of aperture and sky annulus for first-pass aperture photometry,\n    # used to scale the psf\n    aparcsec = 2.5\n    skyradarcsec = np.array([2.5, 3.5])\n\n    for band in bandlist:\n\n        # convert user-supplied radii from arcsec to pixels\n        appix = aparcsec / pixscale\n        skyradpix = skyradarcsec / pixscale\n        psfradpix = psfrad / pixscale\n        fitradpix = fitrad / pixscale\n\n        inputfile = os.path.join(\n            psfimdir, '%s.e00/%s_%s_e00_reg_drz_sci.fits' % (\n                starname, starname, band))\n        outputfile = os.path.join(\n            psfimdir, '%s_%s_%2imas_psf_model.fits' % (\n                starname, band, int(pixscale * 1000)))\n\n        hdulist = pyfits.open(inputfile)\n        hdr = hdulist[0].header\n        imdat = hdulist[0].data\n        if 'FILTER1' in hdr:\n            if 'CLEAR' in hdr['FILTER1']:\n                filtname = hdr['FILTER2']\n            else:\n                filtname = hdr['FILTER1']\n        else:\n            filtname = hdr['FILTER']\n        camera = getcamera(hdr)\n\n        # Define the conversion factor from the values in this image\n        # to photons : photons per ADU.\n        if 'BUNIT' not in hdr:\n            if camera == 'WFC3-IR' and 'EXPTIME' in hdr:\n                phpadu = hdr['EXPTIME']\n            else:\n                phpadu = 1\n        elif hdr['BUNIT'].lower() in ['cps', 'electrons/s']:\n            phpadu = hdr['EXPTIME']\n        elif hdr['BUNIT'].lower() in ['counts', 'electrons']:\n            phpadu = 1\n        assert (phpadu is not None), \\\n            \"Can't determine units from the image header.\"\n\n        rdnoise = 0\n        if 'READNSEA' in hdr:\n            rdnoise = np.mean([hdr[key] for key in hdr.keys()\n                               if key.startswith('READNSE')])\n\n        xmid = np.array([hdr['NAXIS1'] / 2.]) - 1\n        ymid = np.array([hdr['NAXIS2'] / 2.]) - 1\n        xpos, ypos = hstphot.getxycenter(\n            inputfile, xmid, ymid, ext=0, radec=False,\n            fitsconvention=False, verbose=True)\n        if verbose:\n            print(\"PSF recentering : (%.2f,%.2f) ==> (%.2f,%.2f)\" % (\n                xmid, ymid, xpos, ypos))\n        xpos = np.array([xpos])\n        ypos = np.array([ypos])\n\n        idpsf = np.arange(len(xpos))\n        image = pyfits.getdata(inputfile)\n\n        # run aper to get mags and sky values for specified coords\n        mag, magerr, flux, fluxerr, sky, skyerr, badflag, outstr = \\\n            aper.aper(image, xpos, ypos, phpadu=phpadu, apr=appix,\n                      zeropoint=25,\n                      skyrad=skyradpix, badpix=[-12000, 60000], exact=True)\n\n        # use the star at those coords to generate a PSF model\n        gauss, psf, psfmag = getpsf.getpsf(image, xpos, ypos, mag,\n                                           np.asfarray([sky]), rdnoise,\n                                           phpadu,\n                                           idpsf, psfradpix, fitradpix,\n                                           outputfile, zeropoint=25,\n                                           debug=False)\n        if verbose:\n            print(\"PSF image written to %s\" % outputfile)\n    return\n\n\ndef bin_image_data(arr, binfactor):\n    # bin an array by reshaping it into a higher-order array and taking\n    # the sum over the new dimension\n    old_shape = arr.shape\n    new_shape = np.array(old_shape) / binfactor\n    shape = (new_shape[0], arr.shape[0] // new_shape[0],\n             new_shape[1], arr.shape[1] // new_shape[1])\n    return arr.reshape(shape).sum(-1).sum(1)\n\n\ndef mkpsfmodel(psfimage, psfrad=0.6, fitrad=0.3, pixscale=0.03, binning=None,\n               phpadu=1, rdnoise=0, mag=25, zeropoint=25, sky=0,\n               verbose=True):\n    \"\"\" Construct a psf model from drizzled HST images of a\n    standard star or composite star, with the star in the center of the image.\n\n    :param psfimage: filename of the .fits file with the star at the center in\n               image array 0.\n    :param psfrad: the scalar radius, in arcsec, of the circular area within\n                which the PSF will be defined.  This should be slightly larger\n                than the radius of the brightest star that one will be\n                interested in measuring photometry for.\n    :param fitrad: the scalar radius, in arcsec, of the circular area used in\n               the least-square star fits.  Stetson suggest that fitrad should\n               approximately equal to the FWHM, slightly less for crowded\n               fields.  (fitrad must be smaller than psfrad.)\n    :param pixscale: the pixel scale of the input image [arcseconds per pixel]\n    :param phpadu:  the \"gain\" of the input image in photons per ADU  [?]\n    :param rdnoise: the readnoise of the input image, in ADU [?]\n    :param mag: the magnitude of the star in the input image\n    :param zeropoint: the zero point of the input image (magnitude that\n             produces a flux of 1 [ADU per second?]\n    :param sky: the sky brightness of the input image, in ADU per second [?]\n    :return : None\n    \"\"\"\n    # TODO : currently the units in the __doc__ text are guesses. Need to\n    # review the code  in the PythonPhot source and check\n    import hstphot\n\n    # convert user-supplied radii from arcsec to pixels\n    psfradpix = psfrad / pixscale\n    fitradpix = fitrad / pixscale\n\n    outputfile = psfimage.replace('.fits', '_model.fits')\n    hdulist = pyfits.open(psfimage)\n    hdr = hdulist[0].header\n    imdat = hdulist[0].data\n\n    xmid = np.array([hdr['NAXIS1'] / 2.]) - 1\n    ymid = np.array([hdr['NAXIS2'] / 2.]) - 1\n    xpos, ypos = hstphot.getxycenter(\n        psfimage, xmid, ymid, ext=0, radec=False,\n        fitsconvention=False, verbose=True)\n    if verbose:\n        print(\"PSF recentering : (%.2f,%.2f) ==> (%.2f,%.2f)\" % (\n            xmid, ymid, xpos, ypos))\n    xpos = np.array([xpos])\n    ypos = np.array([ypos])\n    mag = np.array([mag])\n    idpsf = np.arange(len(xpos))\n\n    if binning is not None:\n        assert isinstance(binning, int)\n        assert not (imdat.shape[0] % binning)\n        assert not (imdat.shape[1] % binning)\n        imdat = bin_image_data(imdat, binning)\n        xpos /= binning\n        ypos /= binning\n        psfradpix /= binning\n        fitradpix /= binning\n        print(\"Binning input image %i x %i\" % (binning, binning))\n\n\n    # use the star at those coords to generate a PSF model\n    gauss, psf, psfmag = getpsf.getpsf(\n        imdat, xpos, ypos, mag,  np.asfarray([sky]), rdnoise,\n        phpadu, idpsf, psfradpix, fitradpix,  outputfile, zeropoint=zeropoint,\n        debug=False)\n    if verbose:\n        print(\"PSF image written to %s\" % outputfile)\n    return outputfile, gauss, psf, psfmag\n\n\ndef main():\n    import argparse\n\n    parser = argparse.ArgumentParser(\n        description=\"Make a PythonPhot psf model from the a single-star image\")\n\n    # Required positional argument\n    parser.add_argument('inputimage',\n                        help='FITS file with a single star at the center.')\n\n    # optional keyword arguments\n    parser.add_argument('--pixscale', type=float,\n                        default=0.03,\n                        help=\"arcseconds per pixel.\")\n\n    argv = parser.parse_args()\n\n    mkpsfmodel(argv.inputimage, pixscale=argv.pixscale)\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "9837af3530cefabfe59c432a2668298602004b3e", "size": 9172, "ext": "py", "lang": "Python", "max_stars_repo_path": "mkpsfmodel.py", "max_stars_repo_name": "koconnor4/hstphot", "max_stars_repo_head_hexsha": "04ec83fc6dce056bd6153e407446e1be4dff3923", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mkpsfmodel.py", "max_issues_repo_name": "koconnor4/hstphot", "max_issues_repo_head_hexsha": "04ec83fc6dce056bd6153e407446e1be4dff3923", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mkpsfmodel.py", "max_forks_repo_name": "koconnor4/hstphot", "max_forks_repo_head_hexsha": "04ec83fc6dce056bd6153e407446e1be4dff3923", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3765690377, "max_line_length": 79, "alphanum_fraction": 0.5872219799, "include": true, "reason": "import numpy,from astropy", "num_tokens": 2480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.19256214995777723}}
{"text": "# /mpcutilities/mpcutilities/leapsec.py\n\"\"\"\n    \n--------------------------------------------------------------\n\nNov 2018\n\nPayne\n\nOriginal code by Sonia Keys \n\nProvides leap second information by year.  It requires a file\nof leap second data in the format prepared by Judah Levine at NIST.\nSee https://www.ietf.org/timezones/data/leap-seconds.list for example.\n\n*** Payne: I believe this code to be unnecessary / unused ***\n\n*** Payne: I am keeping it for archival purposes ***\n\n--------------------------------------------------------------\n\n\"\"\"\n\n# Import third-party packages\n# --------------------------------------------------------------\nimport numpy as np\nfrom pkg_resources import resource_filename\n\n__all__ = [\"LeapSeconds\"]\n\n\nclass LeapSeconds:\n    \"\"\"loads leap second data from a file.\n\n    Parameters\n    ----------\n    fn : string\n        File name of leap second data, by default leap-seconds.list.\n    jd_ref_utc : float\n        Reference date, JD at which to start counting leap seconds.\n        The default value of 2415020.5 is year 1900.0.\n    \"\"\"\n\n    def __init__(self, fn=resource_filename('mpcutilities','data/leap-seconds.list'), jd_ref_utc=2415020.5):\n        # Create two numpy arrays, secSinceArray and leapSecArray,\n        # that I can use to make a look-up table.\n        # This is just reading Judah Levine's file.\n        self.jd_ref_utc = jd_ref_utc\n        secSinceList = []\n        leapSecList = []\n        with open(fn) as f:\n            for line in f:\n                if not line.startswith('#'):\n                    secondsSince, leapSeconds = line.rsplit('#')[0].split()\n                    secSinceList.append(int(secondsSince))\n                    leapSecList.append(int(leapSeconds))\n        self.secSinceArray = np.array(secSinceList)\n        self.leapSecArray = np.array(leapSecList)\n\n    def getLeapSeconds(self, jd_utc):\n        \"\"\"\n        gets number of leap seconds since the reference Julian date.\n\n        Parameters\n        ----------\n        jd_utc : float\n            JD of end of period since reference date.\n\n        Returns\n        -------\n        int\n            number of leap seconds since reference date.\n        \"\"\"\n        # Given a Julian Date in UTC, determine the number of seconds\n        # that have elapsed since the reference time.  Then find the\n        # correspoding number of leap seconds.\n        max_idx = self.secSinceArray.shape[0] - 1\n        secsSince = self.secondsSinceRef(jd_utc)\n        idx = np.searchsorted(self.secSinceArray, int(secsSince),\n            side='right') - 1\n        if idx < 0:\n            return 0\n        if idx > max_idx:\n            return self.leapSecArray[max_idx]\n        else:\n            return self.leapSecArray[idx]\n\n    def secondsSinceRef(self, jd_utc):\n        \"\"\"Determines the seconds (not just leap seconds) that have elapsed\n        since the reference Julian date.\n\n        Parameters\n        ----------\n        jd_utc : float\n            JD of end of period since reference date.\n\n        Returns\n        -------\n        float\n            number of seconds since reference date.\n        \"\"\"\n        secondsSince = (jd_utc - self.jd_ref_utc) * 24.0 * 60 * 60\n        return secondsSince\n", "meta": {"hexsha": "382d87ae0b3dfc37dd6f7c6922ef89d9d2b7776c", "size": 3207, "ext": "py", "lang": "Python", "max_stars_repo_path": "mpcutilities/leapsec.py", "max_stars_repo_name": "matthewjohnpayne/MPCUtilities", "max_stars_repo_head_hexsha": "3132ad43b69e9271635a20fb07f33abd1d11b7d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-03T16:24:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T16:24:24.000Z", "max_issues_repo_path": "mpcutilities/leapsec.py", "max_issues_repo_name": "matthewjohnpayne/MPCUtilities", "max_issues_repo_head_hexsha": "3132ad43b69e9271635a20fb07f33abd1d11b7d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-15T17:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-15T17:47:56.000Z", "max_forks_repo_path": "mpcutilities/leapsec.py", "max_forks_repo_name": "matthewjohnpayne/MPCUtilities", "max_forks_repo_head_hexsha": "3132ad43b69e9271635a20fb07f33abd1d11b7d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8365384615, "max_line_length": 108, "alphanum_fraction": 0.5734331151, "include": true, "reason": "import numpy", "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.3522017752483203, "lm_q1q2_score": 0.192562147724967}}
{"text": "#!/usr/bin/env python3\nimport configparser\nimport os, h5py, sys \nimport numpy as np\nfrom matplotlib import pyplot as plt\nthisDir = os.path.dirname(os.path.abspath(__file__))\nparentDir = os.path.dirname(thisDir)\nsys.path.insert(0,parentDir)\nfrom pyCRTM import pyCRTM, profilesCreate\n \ndef main(coefficientPath, sensor_id):\n    thisDir = os.path.dirname(os.path.abspath(__file__))\n    cases = os.listdir( os.path.join(thisDir,'data') )\n    cases.sort()\n    # create 4 profiles for each of the 4 cases\n    profiles = profilesCreate( 4, 92 )\n    storedTb = []\n    storedEmis = []\n    # populate the cases, and previously calculated Tb from crtm test program.    \n    for i,c in enumerate(cases):\n        h5 = h5py.File(os.path.join(thisDir,'data',c) , 'r')\n        profiles.Angles[i,0] = h5['zenithAngle'][()]\n        profiles.Angles[i,1] = 999.9 \n        profiles.Angles[i,2] = 100.0  # 100 degrees zenith below horizon.\n        profiles.Angles[i,3] = 0.0 # zero solar azimuth \n        profiles.Angles[i,4] = h5['scanAngle'][()]\n        profiles.DateTimes[i,0] = 2001\n        profiles.DateTimes[i,1] = 1\n        profiles.DateTimes[i,2] = 1\n        profiles.Pi[i,:] = np.asarray(h5['pressureLevels'] )\n        profiles.P[i,:] = np.asarray(h5['pressureLayers'][()])\n        profiles.T[i,:] = np.asarray(h5['temperatureLayers'])\n        profiles.Q[i,:] = np.asarray(h5['humidityLayers'])\n        profiles.O3[i,:] = np.asarray(h5['ozoneConcLayers'])\n        profiles.clouds[i,:,0,0] = np.asarray(h5['cloudConcentration'])\n        profiles.clouds[i,:,0,1] = np.asarray(h5['cloudEffectiveRadius'])\n        profiles.aerosols[i,:,0,0] = np.asarray(h5['aerosolConcentration'])\n        profiles.aerosols[i,:,0,1] = np.asarray(h5['aerosolEffectiveRadius'])\n        profiles.aerosolType[i] = h5['aerosolType'][()]\n        profiles.cloudType[i] = h5['cloudType'][()]\n        profiles.cloudFraction[i,:] = h5['cloudFraction'][()]\n        profiles.climatology[i] = h5['climatology'][()]\n        profiles.surfaceFractions[i,:] = h5['surfaceFractions']\n        profiles.surfaceTemperatures[i,:] = h5['surfaceTemperatures']\n        profiles.S2m[i,1] = 33.0 # just use salinity out of S2m for the moment.\n        profiles.windSpeed10m[i] = 5.0\n        profiles.LAI[i] = h5['LAI'][()]\n        profiles.windDirection10m[i] = h5['windDirection10m'][()]\n        # land, soil, veg, water, snow, ice\n        profiles.surfaceTypes[i,0] = h5['landType'][()]\n        profiles.surfaceTypes[i,1] = h5['soilType'][()]\n        profiles.surfaceTypes[i,2] = h5['vegType'][()]\n        profiles.surfaceTypes[i,3] = h5['waterType'][()]\n        profiles.surfaceTypes[i,4] = h5['snowType'][()]\n        profiles.surfaceTypes[i,5] = h5['iceType'][()]\n        storedTb.append(np.asarray(h5['Tb']))\n        storedEmis.append(np.asarray(h5['emissivity_atms']))\n        h5.close()\n\n    crtmOb = pyCRTM()\n    crtmOb.profiles = profiles\n    crtmOb.coefficientPath = pathInfo['CRTM']['coeffs_dir']\n    crtmOb.sensor_id = sensor_id\n    crtmOb.nThreads = 4\n\n    crtmOb.loadInst()\n\n    crtmOb.runDirect()\n    forwardTb = crtmOb.Bt\n    forwardEmissivity = crtmOb.surfEmisRefl[0,:]\n    crtmOb.surfEmisRefl = []\n\n    crtmOb.runK()\n    kTb = crtmOb.Bt\n    kEmissivity = crtmOb.surfEmisRefl[0,:]\n\n    if ( all( np.abs( forwardTb.flatten() - np.asarray(storedTb).flatten() ) <= 1e-5)  and all( np.abs( kTb.flatten() - np.asarray(storedTb).flatten() ) <= 1e-5) ):\n        print(\"Yay! all values are close enough to what CRTM test program produced!\")\n    else: \n        print(\"Boo! something failed. Look at cris plots\")\n        wavenumbers = np.zeros([4,1305])\n        wavenumbers[0:4,:] = np.linspace(1,1306,1305)\n        plt.figure()\n        plt.plot(wavenumbers.T,forwardTb.T-np.asarray(storedTb).T ) \n        plt.legend(['1','2','3','4'])\n        plt.savefig(os.path.join(thisDir,'cris'+'_spectrum_forward.png'))\n        plt.figure()\n        plt.plot(wavenumbers.T,forwardEmissivity.T-np.asarray(storedEmis).T)\n        plt.savefig(os.path.join(thisDir,'cris'+'_emissivity_forward.png')) \n    \n        plt.figure()\n        plt.plot(wavenumbers.T,kTb.T-np.asarray(storedTb).T)\n        plt.savefig(os.path.join(thisDir,'cris'+'_spectrum_k.png'))\n        plt.figure()\n        plt.plot(wavenumbers.T,kEmissivity.T-np.asarray(storedEmis).T)\n        plt.savefig(os.path.join(thisDir,'cris'+'_emissivity_k.png')) \n        sys.exit(\"Boo! didn't pass tolerance with CRTM test program.\")\n\n\nif __name__ == \"__main__\":\n    pathInfo = configparser.ConfigParser()\n    pathInfo.read( os.path.join(parentDir,'crtm.cfg') ) \n    coefficientPath = pathInfo['CRTM']['coeffs_dir']\n    sensor_id = 'cris_npp'\n    main(coefficientPath, sensor_id)\n \n", "meta": {"hexsha": "868f4befd3ff09e2f675160294422d8976c44a8a", "size": 4668, "ext": "py", "lang": "Python", "max_stars_repo_path": "testCases/test_cris.py", "max_stars_repo_name": "karpob/pycrtm", "max_stars_repo_head_hexsha": "3f32c105e4dfa087d3bc9d94934470b09005e20a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-06-29T07:12:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T15:55:16.000Z", "max_issues_repo_path": "testCases/test_cris.py", "max_issues_repo_name": "karpob/pycrtm", "max_issues_repo_head_hexsha": "3f32c105e4dfa087d3bc9d94934470b09005e20a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 50, "max_issues_repo_issues_event_min_datetime": "2019-07-29T14:33:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-01T09:34:25.000Z", "max_forks_repo_path": "testCases/test_cris.py", "max_forks_repo_name": "karpob/pycrtm", "max_forks_repo_head_hexsha": "3f32c105e4dfa087d3bc9d94934470b09005e20a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-10-21T16:07:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T01:29:53.000Z", "avg_line_length": 43.6261682243, "max_line_length": 164, "alphanum_fraction": 0.6338903171, "include": true, "reason": "import numpy", "num_tokens": 1372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.19256214400738306}}
{"text": "import ctypes\nimport os\nimport numpy as np\nimport time\n\nif os.name == 'nt':\n    import msvcrt\n    def getch():\n        return msvcrt.getch().decode()\nelse:\n    import sys, tty, termios\n    fd = sys.stdin.fileno()\n    old_settings = termios.tcgetattr(fd)\n    def getch():\n        try:\n            tty.setraw(sys.stdin.fileno())\n            ch = sys.stdin.read(1)\n        finally:\n            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n        return ch\n\nfrom dynamixel_sdk import *                    # Uses Dynamixel SDK library\n\n# Length of the arms\na0 \t\t\t\t= 10   \na1 \t\t\t\t= 5\na2 \t\t\t\t= 20\n# Angles of the joints\nt0 \t\t\t\t= 0\nt1\t\t\t\t= 0 \nt2\t\t\t\t= 0\n\n# Angles in radians\nt0 \t\t= t0/180*np.pi\nt1 \t\t= t1/180*np.pi\nt2 \t\t= t2/180*np.pi\n\n# Control Table address\nADDR_TORQUE_ENABLE                 = 64\nADDR_PROFILE_VELOCITY              = 112\nADDR_PROFILE_ACCELERATION          = 108\nADDR_GOAL_POSITION                 = 116\nADDR_PRESENT_POSITION              = 132\nADDR_DRIVE_MODE                    = 10\nADDR_MOVING_STATUS                 = 123\n\n# Data Byte Length\nLEN_GOAL_POSITION       = 4\nLEN_PRESENT_POSITION    = 4\n\n# Protocol version\nPROTOCOL_VERSION            = 2.0               # See which protocol version is used in the Dynamixel\n\n# Default setting\nDXL1_ID                     = 71                 # Dynamixel#1 ID : 1\nDXL2_ID                     = 72                 # Dynamixel#1 ID : 2\nBAUDRATE                    = 1000000             # Dynamixel default baudrate : 57600\nDEVICENAME                  = '/dev/ttyUSB0'    # Check which port is being used on your controller\n                                                # ex) Windows: \"COM1\"   Linux: \"/dev/ttyUSB0\" Mac: \"/dev/tty.usbserial-*\"\n\nTORQUE_ENABLE               = 1                 # Value for enabling the torque\nTORQUE_DISABLE              = 0                 # Value for disabling the torque\n#DXL1_MIN_POSITION_VALUE     = -1000\t\t\t# Dynamixel 1 will rotate between this value\n#DXL1_MAX_POSITION_VALUE     = 1000\t\t# and this value \n#DXL2_MIN_POSITION_VALUE     = -2000 \t\t# Dynamixel 2 will rotate between this value\n#DXL2_MAX_POSITION_VALUE     = 2000\t\t# and this value\nDXL_MOVING_STATUS_THRESHOLD = 20 \t\t# Dynamixel moving status threshold\n\nindex = 0\ndxl1_goal_position = [DXL1_MIN_POSITION_VALUE, DXL1_MAX_POSITION_VALUE]         # Goal position of dynamixel 1\ndxl2_goal_position = [DXL2_MIN_POSITION_VALUE, DXL2_MAX_POSITION_VALUE]         # Goal position of dynamixel 2\n\n# Initialize PortHandler instance\n# Set the port path\n# Get methods and members of PortHandlerLinux or PortHandlerWindows\nportHandler = PortHandler(DEVICENAME)\n\n# Initialize PacketHandler instance\n# Set the protocol version\n# Get methods and members of Protocol1PacketHandler or Protocol2PacketHandler\npacketHandler = PacketHandler(PROTOCOL_VERSION)\n\n# Initialize GroupBulkWrite instance\ngroupBulkWrite = GroupBulkWrite(portHandler, packetHandler)\n\n# Initialize GroupBulkRead instace for Present Position\ngroupBulkRead = GroupBulkRead(portHandler, packetHandler)\n\n# Open port\nif portHandler.openPort():\n    print(\"Succeeded to open the port\")\nelse:\n    print(\"Failed to open the port\")\n    print(\"Press any key to terminate...\")\n    getch()\n    quit()\n\n# Set port baudrate\nif portHandler.setBaudRate(BAUDRATE):\n    print(\"Succeeded to change the baudrate\")\nelse:\n    print(\"Failed to change the baudrate\")\n    print(\"Press any key to terminate...\")\n    getch()\n    quit()\n\n# Enable Dynamixel Torque DXL1\ndxl_comm_result, dxl_error = packetHandler.write1ByteTxRx(portHandler, DXL1_ID, ADDR_TORQUE_ENABLE, TORQUE_ENABLE)\nif dxl_comm_result != COMM_SUCCESS:\n    print(\"%s\" % packetHandler.getTxRxResult(dxl_comm_result))\nelif dxl_error != 0:\n    print(\"%s\" % packetHandler.getRxPacketError(dxl_error))\nelse:\n    print(\"Dynamixel 1 has been successfully connected\")\n\n# Enable Dynamixel Torque DXL2\ndxl_comm_result, dxl_error = packetHandler.write1ByteTxRx(portHandler, DXL2_ID, ADDR_TORQUE_ENABLE, TORQUE_ENABLE)\nif dxl_comm_result != COMM_SUCCESS:\n    print(\"%s\" % packetHandler.getTxRxResult(dxl_comm_result))\nelif dxl_error != 0:\n    print(\"%s\" % packetHandler.getRxPacketError(dxl_error))\nelse:\n    print(\"Dynamixel 2 has been successfully connected\")\n\n# Add parameter storage for Dynamixel#1 present position\ndxl_addparam_result = groupBulkRead.addParam(DXL1_ID, ADDR_PRESENT_POSITION, LEN_PRESENT_POSITION)\nif dxl_addparam_result != True:\n    print(\"[ID:%03d] groupBulkRead addparam failed\" % DXL1_ID)\n    quit()\n\n# Add parameter storage for Dynamixel#2 present position\ndxl_addparam_result = groupBulkRead.addParam(DXL2_ID, ADDR_PRESENT_POSITION, LEN_PRESENT_POSITION)\nif dxl_addparam_result != True:\n    print(\"[ID:%03d] groupBulkRead addparam failed\" % DXL2_ID)\n    quit()\n\n\ndef end_eff_pos(t0,t1,te):\n    # Parameter table with columns \" theta, alpha, r or a, d \n    \n    param_tab = [[t0 ,      0         ,  a0   ,  0  ],\n                 [t1 ,      0         ,  a1   ,  0  ],\n                 [t2 ,      0         ,  a2   ,  0  ]]\n    \n    # Transformation matrix\n\n    i=0\n    T0_1 = [[np.cos(param_tab[i][0]) , -np.cos(param_tab[i][1])*np.sin(param_tab[i][0]), np.sin(param_tab[i][1])*np.sin(param_tab[i][0])  , param_tab[i][2]*np.cos(param_tab[i][0])],\n            [np.sin(param_tab[i][0]) , np.cos(param_tab[i][1])*np.cos(param_tab[i][0]) , -np.sin(param_tab[i][1])*np.cos(param_tab[i][0]) , param_tab[i][2]*np.sin(param_tab[i][0])],\n            [           0            ,            np.sin(param_tab[i][1])              ,       np.cos(param_tab[i][1])                    ,     param_tab[i][3]                    ],\n            [0  ,  0  ,  0  ,  1 ]]\n\n    i=1\n    T1_2 = [[np.cos(param_tab[i][0]) , -np.cos(param_tab[i][1])*np.sin(param_tab[i][0]), np.sin(param_tab[i][1])*np.sin(param_tab[i][0])  , param_tab[i][2]*np.cos(param_tab[i][0])],\n            [np.sin(param_tab[i][0]) , np.cos(param_tab[i][1])*np.cos(param_tab[i][0]) , -np.sin(param_tab[i][1])*np.cos(param_tab[i][0]) , param_tab[i][2]*np.sin(param_tab[i][0])],\n            [           0            ,            np.sin(param_tab[i][1])              ,       np.cos(param_tab[i][1])                    ,     param_tab[i][3]                    ],\n            [0  ,  0  ,  0  ,  1 ]]\n\n    i=2\n    T2_3 = [[np.cos(param_tab[i][0]) , -np.cos(param_tab[i][1])*np.sin(param_tab[i][0]), np.sin(param_tab[i][1])*np.sin(param_tab[i][0])  , param_tab[i][2]*np.cos(param_tab[i][0])],\n            [np.sin(param_tab[i][0]) , np.cos(param_tab[i][1])*np.cos(param_tab[i][0]) , -np.sin(param_tab[i][1])*np.cos(param_tab[i][0]) , param_tab[i][2]*np.sin(param_tab[i][0])],\n            [           0            ,            np.sin(param_tab[i][1])              ,       np.cos(param_tab[i][1])                    ,     param_tab[i][3]                    ],\n            [0  ,  0  ,  0  ,  1 ]]\n    \n   \n    \n\n\n\n\nwhile 1:\n    print(\"Press any key to continue! (or press ESC to quit!)\")\n    if getch() == chr(0x1b):\n        break\n\n    # Allocate goal position value into byte array\n    param_goal_position_dxl1 = [DXL_LOBYTE(DXL_LOWORD(dxl1_goal_position[index])), DXL_HIBYTE(DXL_LOWORD(dxl1_goal_position[index])), DXL_LOBYTE(DXL_HIWORD(dxl1_goal_position[index])), DXL_HIBYTE(DXL_HIWORD(dxl1_goal_position[index]))]\n    param_goal_position_dxl2 = [DXL_LOBYTE(DXL_LOWORD(dxl2_goal_position[index])), DXL_HIBYTE(DXL_LOWORD(dxl2_goal_position[index])), DXL_LOBYTE(DXL_HIWORD(dxl2_goal_position[index])), DXL_HIBYTE(DXL_HIWORD(dxl2_goal_position[index]))]\n   \n    # Add Dynamixel#1 goal position value to the Bulkwrite parameter storage\n    dxl_addparam_result = groupBulkWrite.addParam(DXL1_ID, ADDR_GOAL_POSITION, LEN_GOAL_POSITION, param_goal_position_dxl1)\n    if dxl_addparam_result != True:\n        print(\"[ID:%03d] groupBulkWrite addparam failed\" % DXL1_ID)\n        quit()\n    # Add Dynamixel#2 goal position value to the Bulkwrite parameter storage\n    dxl_addparam_result = groupBulkWrite.addParam(DXL2_ID, ADDR_GOAL_POSITION, LEN_GOAL_POSITION, param_goal_position_dxl2)\n    if dxl_addparam_result != True:\n        print(\"[ID:%03d] groupBulkWrite addparam failed\" % DXL2_ID)\n        quit()\n\n\n    # Bulkwrite goal position values for both the dynamixels\n    dxl_comm_result = groupBulkWrite.txPacket()\n    if dxl_comm_result != COMM_SUCCESS:\n        print(\"%s\" % packetHandler.getTxRxResult(dxl_comm_result))\n\n    # Clear bulkwrite parameter storage\n    groupBulkWrite.clearParam()\n\n\n    while 1:\n        # Bulkread present positions of both dynamixels\n        dxl_comm_result = groupBulkRead.txRxPacket()\n        if dxl_comm_result != COMM_SUCCESS:\n            print(\"%s\" % packetHandler.getTxRxResult(dxl_comm_result))\n\n        # Check if groupbulkread data of Dynamixel#1 is available\n        dxl_getdata_result = groupBulkRead.isAvailable(DXL1_ID, ADDR_PRESENT_POSITION, LEN_PRESENT_POSITION)\n        if dxl_getdata_result != True:\n            print(\"[ID:%03d] groupBulkRead getdata failed\" % DXL1_ID)\n            quit()\n\n        # Check if groupbulkread data of Dynamixel#2 is available\n        dxl_getdata_result = groupBulkRead.isAvailable(DXL2_ID, ADDR_PRESENT_POSITION, LEN_PRESENT_POSITION)\n        if dxl_getdata_result != True:\n            print(\"[ID:%03d] groupBulkRead getdata failed\" % DXL2_ID)\n            quit()\n\n\t# Get present position value\n        dxl1_present_position = groupBulkRead.getData(DXL1_ID, ADDR_PRESENT_POSITION, LEN_PRESENT_POSITION)\n        dxl2_present_position = groupBulkRead.getData(DXL2_ID, ADDR_PRESENT_POSITION, LEN_PRESENT_POSITION)\n\n\tnumber = dxl1_present_position & 0xFFFFFFFF\n        dxl1_present_position = ctypes.c_long(number).value\n\n\tnumber = dxl2_present_position & 0xFFFFFFFF\n        dxl2_present_position = ctypes.c_long(number).value\n\n\tprint(\"[ID:%03d] Present Position : %d \\t [ID:%03d] LED Value: %d\" % (DXL1_ID, dxl1_present_position, DXL2_ID, dxl2_present_position))\n\n\tif ((abs(dxl1_goal_position[index] - dxl1_present_position) > DXL_MOVING_STATUS_THRESHOLD) and (abs(dx2_goal_position[index] - dxl2_present_position) > DXL_MOVING_STATUS_THRESHOLD)):\n\t    break\n\n    # Change goal position\n    if index == 0:\n        index = 1\n    else:\n        index = 0\n\n\n# Clear bulkread parameter storage\ngroupBulkRead.clearParam()\n\n\n# Disable Dynamixel Torque DXL1\ndxl_comm_result, dxl_error = packetHandler.write1ByteTxRx(portHandler, DXL1_ID, ADDR_TORQUE_ENABLE, TORQUE_DISABLE)\nif dxl_comm_result != COMM_SUCCESS:\n    print(\"%s\" % packetHandler.getTxRxResult(dxl_comm_result))\nelif dxl_error != 0:\n    print(\"%s\" % packetHandler.getRxPacketError(dxl_error))\n\n# Disable Dynamixel Torque DXL2\ndxl_comm_result, dxl_error = packetHandler.write1ByteTxRx(portHandler, DXL2_ID, ADDR_TORQUE_ENABLE, TORQUE_DISABLE)\nif dxl_comm_result != COMM_SUCCESS:\n    print(\"%s\" % packetHandler.getTxRxResult(dxl_comm_result))\nelif dxl_error != 0:\n    print(\"%s\" % packetHandler.getRxPacketError(dxl_error))\n\n# Close port\nportHandler.closePort()\n\n", "meta": {"hexsha": "cb268d8717283622f1cf67e3ec33732380a514de", "size": 10889, "ext": "py", "lang": "Python", "max_stars_repo_path": "DynamixelWorkingMotionControl/forward_kinematics.py", "max_stars_repo_name": "tummalag/Controlled-Flight-of-High-DOF-Humanoid-Robot", "max_stars_repo_head_hexsha": "383f41c504b5a08ffd6d0b4c8f6013e4070d8458", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DynamixelWorkingMotionControl/forward_kinematics.py", "max_issues_repo_name": "tummalag/Controlled-Flight-of-High-DOF-Humanoid-Robot", "max_issues_repo_head_hexsha": "383f41c504b5a08ffd6d0b4c8f6013e4070d8458", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DynamixelWorkingMotionControl/forward_kinematics.py", "max_forks_repo_name": "tummalag/Controlled-Flight-of-High-DOF-Humanoid-Robot", "max_forks_repo_head_hexsha": "383f41c504b5a08ffd6d0b4c8f6013e4070d8458", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5610687023, "max_line_length": 235, "alphanum_fraction": 0.6591055193, "include": true, "reason": "import numpy", "num_tokens": 2995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.19256214400738306}}
{"text": "import os\n\nimport numpy as np\n\nfrom astropy import units as u\nfrom astropy import wcs\nfrom astropy.coordinates import EarthLocation\nfrom astropy.coordinates import FK5\nfrom astropy.coordinates import SkyCoord\nfrom astropy.io import fits\nfrom astropy.time import Time\nfrom ccdproc import CCDData\nfrom collections import namedtuple\nfrom skimage.feature import register_translation\nfrom skimage.util import view_as_blocks\n\nfrom pocs import PanBase\nfrom pocs.utils import images as img_utils\n\nPointingError = namedtuple('PointingError', ['delta_ra', 'delta_dec', 'magnitude'])\n\n\nclass Image(PanBase):\n\n    def __init__(self, fits_file, wcs_file=None):\n        \"\"\"Object to represent a single image from a PANOPTES camera.\n\n        Instantiate the object by providing a .cr2 (or .dng) file.\n\n        Args:\n            fits_file (str): Name of FITS file to be read (can be .fz)\n            wcs_file (str, optional): Name of FITS file to use for WCS\n        \"\"\"\n        super().__init__()\n        assert os.path.exists(fits_file), self.logger.warning('File does not exist: {}'.format(fits_file))\n\n        if fits_file.endswith('.fz'):\n            fits_file = img_utils.fpack(fits_file, unpack=True)\n\n        assert fits_file.lower().endswith(('.fits')), self.logger.warning('File must end with .fits')\n\n        self.wcs = None\n        self._wcs_file = None\n        self.fits_file = fits_file\n\n        if wcs_file is not None:\n            self.wcs_file = wcs_file\n        else:\n            self.wcs_file = fits_file\n\n        with fits.open(self.fits_file, 'readonly') as hdu:\n            self.header = hdu[0].header\n            self.data = hdu[0].data\n\n        assert 'DATE-OBS' in self.header, self.logger.warning('FITS file must contain the DATE-OBS keyword')\n        assert 'EXPTIME' in self.header, self.logger.warning('FITS file must contain the EXPTIME keyword')\n\n        self.RGGB = CCDData(data=self.data, unit='adu',\n                            meta=self.header,\n                            mask=np.zeros(self.data.shape))\n\n        # Location Information\n        cfg_loc = self.config['location']\n        self.loc = EarthLocation(lat=cfg_loc['latitude'],\n                                 lon=cfg_loc['longitude'],\n                                 height=cfg_loc['elevation'],\n                                 )\n        # Time Information\n        self.starttime = Time(self.header['DATE-OBS'], location=self.loc)\n        self.exptime = float(self.header['EXPTIME']) * u.second\n        self.midtime = self.starttime + (self.exptime / 2.0)\n        self.sidereal = self.midtime.sidereal_time('apparent')\n        self.FK5_Jnow = FK5(equinox=self.midtime)\n\n        # Coordinates from header keywords\n        self.header_pointing = None\n        self.header_RA = None\n        self.header_Dec = None\n        self.header_HA = None\n\n        # Coordinates from WCS\n        self.pointing = None\n        self.RA = None\n        self.Dec = None\n        self.HA = None\n\n        self.get_header_pointing()\n        self.get_wcs_pointing()\n\n        self._luminance = None\n        self._pointing = None\n        self._pointing_error = None\n\n    @property\n    def wcs_file(self):\n        \"\"\"WCS file name\n\n        When setting the WCS file name, the WCS information will be read,\n        setting the `wcs` property.\n        \"\"\"\n        return self._wcs_file\n\n    @wcs_file.setter\n    def wcs_file(self, filename):\n        if filename is not None:\n            try:\n                w = wcs.WCS(filename)\n                assert w.is_celestial\n\n                self.wcs = w\n                self._wcs_file = filename\n            except Exception:\n                self.logger.warn(\"Can't get WCS from FITS file (try solve_field)\")\n\n    @property\n    def luminance(self):\n        \"\"\"Luminance for the image\n\n        Bin the image 2x2 combining each RGGB set of pixels in to a single\n        luminance value.\n        \"\"\"\n        if self._luminance is None:\n            block_size = (2, 2)\n            image_out = view_as_blocks(self.RGGB.data, block_size)\n\n            for i in range(len(image_out.shape) // 2):\n                image_out = np.average(image_out, axis=-1)\n\n            self._luminance = image_out\n\n        return self._luminance\n\n    @property\n    def pointing_error(self):\n        \"\"\"Pointing error namedtuple (delta_ra, delta_dec, magnitude)\n\n        Returns pointing error information. The first time this is accessed\n        this will solve the field if not previously solved.\n\n        Returns:\n            namedtuple: Pointing error information\n        \"\"\"\n        if self._pointing_error is None:\n            assert self.pointing is not None, self.logger.warn(\"No WCS, can't get pointing_error\")\n            assert self.header_pointing is not None\n\n            if self.wcs is None:\n                self.solve_field()\n\n            mag = self.pointing.separation(self.header_pointing)\n            dDec = self.pointing.dec - self.header_pointing.dec\n            dRA = self.pointing.ra - self.header_pointing.ra\n\n            self._pointing_error = PointingError(dRA.to(u.degree), dDec.to(u.degree), mag)\n\n        return self._pointing_error\n\n    def get_header_pointing(self):\n        \"\"\"Get the pointing information from the header\n\n        The header should contain the `RA-MNT` and `DEC-MNT` keywords, from which\n        the header pointing coordinates are built.\n        \"\"\"\n        try:\n            self.header_pointing = SkyCoord(ra=float(self.header['RA-MNT']) * u.degree,\n                                            dec=float(self.header['DEC-MNT']) * u.degree)\n\n            self.header_RA = self.header_pointing.ra.to(u.hourangle)\n            self.header_Dec = self.header_pointing.dec.to(u.degree)\n\n            # Precess to the current equinox otherwise the RA - LST method will be off.\n            self.header_HA = self.header_pointing.transform_to(self.FK5_Jnow).ra.to(u.hourangle) - self.sidereal\n        except Exception as e:\n            self.logger.warning('Cannot get header pointing information: {}'.format(e))\n\n    def get_wcs_pointing(self):\n        \"\"\"Get the pointing information from the WCS\n\n        Builds the pointing coordinates from the plate-solved WCS. These will be\n        compared with the coordinates stored in the header.\n        \"\"\"\n        if self.wcs is not None:\n            ny, nx = self.RGGB.data.shape\n            decimals = self.wcs.all_pix2world(nx // 2, ny // 2, 1)\n\n            self.pointing = SkyCoord(ra=decimals[0] * u.degree,\n                                     dec=decimals[1] * u.degree)\n\n            self.RA = self.pointing.ra.to(u.hourangle)\n            self.Dec = self.pointing.dec.to(u.degree)\n\n            # Precess to the current equinox otherwise the RA - LST method will be off.\n            self.HA = self.pointing.transform_to(self.FK5_Jnow).ra.to(u.hourangle) - self.sidereal\n\n    def solve_field(self, **kwargs):\n        \"\"\" Solve field and populate WCS information\n\n        Args:\n            **kwargs (dict): Options to be passed to `get_solve_field`\n        \"\"\"\n        solve_info = img_utils.get_solve_field(self.fits_file,\n                                               ra=self.header_pointing.ra.value,\n                                               dec=self.header_pointing.dec.value,\n                                               **kwargs)\n\n        self.wcs_file = solve_info['solved_fits_file']\n        self.get_wcs_pointing()\n\n        return solve_info\n\n    def compute_offset(self, ref, units='arcsec', rotation=True):\n        \"\"\"Offset information between this image and a reference\n\n        Args:\n            ref (str): Refernce image, either another `Image` instance or a\n                filename that will be read\n            units (str, optional): Can be either `arcsec` or `pixel`\n            rotation (bool, optional): If rotation information should be included,\n                defaults to True\n\n        Returns:\n            dict: Offset information in key/value pairs\n        \"\"\"\n        if isinstance(units, (u.Unit, u.Quantity, u.IrreducibleUnit)):\n            units = units.name\n        assert units in ['pix', 'pixel', 'arcsec']\n\n        if isinstance(ref, str):\n            assert os.path.exists(ref)\n            ref = Image(ref)\n        assert isinstance(ref, Image)\n\n        offset_pix = compute_offset_rotation(ref.luminance, self.luminance)\n        offset_pix['X'] *= 2\n        offset_pix['Y'] *= 2\n\n        if self.HA:\n            selfHA = self.HA\n        else:\n            selfHA = self.header_HA\n        if self.Dec:\n            selfDec = self.Dec\n        else:\n            selfDec = self.header_Dec\n        if ref.HA:\n            refHA = ref.HA\n        else:\n            stime_diff = (self.midtime.sidereal_time('apparent') - ref.midtime.sidereal_time('apparent'))\n            refHA = selfHA - stime_diff.to(u.hourangle)\n\n        time_diff = (self.midtime - ref.midtime)\n\n        info = {'image': self.fits_file,\n                'time': self.midtime.to_datetime().isoformat(),\n                'HA': selfHA.to(u.hourangle).value,\n                'HA unit': 'hours',\n                'Dec': selfDec.to(u.degree).value,\n                'Dec unit': 'deg',\n\n                'refimage': ref.fits_file,\n                'reftime': ref.midtime.to_datetime().isoformat(),\n                'refHA': refHA.to(u.hourangle).value,\n\n                'dt': time_diff.to(u.second).value,\n                'dt unit': 'seconds',\n                'angle': offset_pix['angle'].to(u.degree).value,\n                'angle unit': 'deg',\n                'offset units': units,\n                }\n\n        if units in ['pix', 'pixel']:\n            info['offsetX'] = offset_pix['X'].to(u.pixel).value\n            info['offsetY'] = offset_pix['Y'].to(u.pixel).value\n        elif units == 'arcsec':\n            deltapix = [offset_pix['X'].to(u.pixel).value,\n                        offset_pix['Y'].to(u.pixel).value]\n            offset_deg = self.wcs.pixel_scale_matrix.dot(deltapix)\n            info['offsetX'] = (offset_deg[0] * u.degree).to(u.arcsecond).value\n            info['offsetY'] = (offset_deg[1] * u.degree).to(u.arcsecond).value\n        return info\n\n\n##################################################################################################\n# Private Methods\n##################################################################################################\n\n    def __str__(self):\n        return \"{}: {}\".format(self.fits_file, self.header_pointing)\n\n\ndef compute_offset_rotation(im, imref, upsample_factor=20, subframe_size=200, corners=True):\n    \"\"\"Determine rotation information between two images\n\n    Detremine the rotation information for the center and, if `corner`, the\n    four corner boxes, each of `subframe_size` pixels.\n\n    Args:\n        im (numpy.array): Image data\n        imref (numpy.array): Comparison image data\n        upsample_factor (int, optional): Subpixel fraction to compute\n        subframe_size (int, optional): Box size\n        corners (bool, optional): If corner boxes should be included, defaults\n            to True\n\n    Returns:\n        dict: Rotation offset in `X`, `Y`, and `angle`\n    \"\"\"\n    assert im.shape == imref.shape\n    ny, nx = im.shape\n\n    subframe_half = int(subframe_size / 2)\n\n    # Create the center point for each of our regions\n    regions = {'center': (int(nx / 2), int(ny / 2)), }\n    offsets = {'center': None, }\n\n    if corners:\n        regions.update({\n            'upper_right': (int(nx - subframe_half), int(ny - subframe_half)),\n            'upper_left': (int(subframe_half), int(ny - subframe_half)),\n            'lower_right': (int(nx - subframe_half), int(subframe_half)),\n            'lower_left': (int(subframe_half), int(subframe_half)),\n        })\n\n        offsets.update({\n            'upper_right': None,\n            'upper_left': None,\n            'lower_right': None,\n            'lower_left': None,\n        })\n\n    # Get im/imref offsets for each region\n    for region, midpoint in regions.items():\n        imarr = img_utils.crop_data(im, center=midpoint, box_width=subframe_size)\n        imrefarr = img_utils.crop_data(imref, center=midpoint, box_width=subframe_size)\n\n        shifts, err, h = register_translation(imrefarr, imarr, upsample_factor=upsample_factor)\n        offsets[region] = shifts\n\n    # Rotate the offsets according to region\n    angles = []\n    for region in regions.keys():\n        if region != 'center':\n            offsets[region] -= offsets['center']\n\n            relpos = (regions[region][0] - regions['center'][0],\n                      regions[region][1] - regions['center'][1])\n\n            theta1 = np.arctan(relpos[1] / relpos[0])\n            theta2 = np.arctan((relpos[1] + offsets[region][1]) / (relpos[0] + offsets[region][0]))\n            angles.append(theta2 - theta1)\n\n    angle = np.mean(angles)\n\n    result = {'X': offsets['center'][0] * u.pix,\n              'Y': offsets['center'][1] * u.pix,\n              'angle': (angle * u.radian).to(u.degree)}\n\n    return result\n", "meta": {"hexsha": "3f5dc527e0b6f6b6897ea63fdafc69750c3b47d7", "size": 12954, "ext": "py", "lang": "Python", "max_stars_repo_path": "pocs/images.py", "max_stars_repo_name": "brendan-o/POCS", "max_stars_repo_head_hexsha": "243d0acf1ade7a96f71d83ad13fb141ee1ea9781", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pocs/images.py", "max_issues_repo_name": "brendan-o/POCS", "max_issues_repo_head_hexsha": "243d0acf1ade7a96f71d83ad13fb141ee1ea9781", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pocs/images.py", "max_forks_repo_name": "brendan-o/POCS", "max_forks_repo_head_hexsha": "243d0acf1ade7a96f71d83ad13fb141ee1ea9781", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9833333333, "max_line_length": 112, "alphanum_fraction": 0.5790489424, "include": true, "reason": "import numpy,from astropy", "num_tokens": 2946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.32082131381216084, "lm_q1q2_score": 0.19255321795262414}}
{"text": "#!/usr/bin/env python\n\n# A library of stuff used for getting Balrog data from the databse,\n# HEALPixifying it, and general munging.\n\n\nimport desdb\nimport numpy as np\nimport esutil\nimport sys\nimport healpy as hp\nimport os\nimport numpy.lib.recfunctions as rf\n\n\ndef GetDepthMap(depth_file):\n    map = hp.read_map(depth_file, nest=True)\n    nside = hp.npix2nside(map.size)\n    return map, nside\n\ndef GetPhi(ra):\n    return ra * np.pi / 180.0\n\ndef GetRa(phi):\n    return phi*180.0/np.pi\n\ndef GetTheta(dec):\n    return (90.0 - dec) * np.pi / 180.0\n\ndef GetDec(theta):\n    return 90.0 - theta*180.0/np.pi\n\ndef GetRaDec(theta, phi):\n    return [GetRa(phi), GetDec(theta)]\n\ndef GetPix(nside, ra, dec, nest=True):\n    phi = GetPhi(ra)\n    theta = GetTheta(dec)\n    pix = hp.ang2pix(nside, theta, phi, nest=nest)\n    return pix\n\ndef GetDepthCut(map, nside, ra, dec, depth = 0.0):\n    pix = GetPix(nside, ra, dec)\n    depths = map[pix]\n    ok_depths =  (depths > depth)\n    return ok_depths\n\ndef ValidDepth(map, nside, arr, rakey='ra', deckey='dec', depth = 0.0):\n    ok_depths = GetDepthCut(map, nside, arr[rakey], arr[deckey], depth = depth)\n    arr = arr[ok_depths]\n    return arr\n\ndef InTile(data, ura, udec, rakey='ra', deckey='dec'):\n    inside = (data[rakey] > ura[0]) & (data[rakey] < ura[1]) & (data[deckey] > udec[0]) & (data[deckey] < udec[1])\n    return inside\n\ndef RemoveTileOverlap(tilestuff, data, col='tilename', rakey='ra', deckey='dec'):\n    datatile = data[col]\n    tiles = np.unique(datatile)\n    keep = np.zeros( len(data), dtype=np.bool_)\n    for tile in tiles:\n        cut = (datatile==tile)\n        entry = tilestuff[tile]\n        ura = (entry['urall'], entry['uraur'])\n        udec = (entry['udecll'], entry['udecur'])\n        u = InTile(data[cut], ura, udec, rakey=rakey, deckey=deckey)\n        keep[cut] =  u\n    return data[keep]\n\ndef NoSimFields(band='i'):\n    q = \"\"\"\n    SELECT\n        balrog_index,\n        mag_auto,\n        flags\n    FROM\n        SUCHYTA1.balrog_sva1v2_nosim_%s\n    \"\"\" %(band)\n    return q\n\n\n\ndef SimFields(band='i',table='sva1v2'):\n    q = \"\"\"\n    SELECT\n        t.tilename as tilename,\n        m.xwin_image as xwin_image,\n        m.ywin_image as ywin_image,\n        m.xmin_image as xmin_image,\n        m.ymin_image as ymin_image,\n        m.xmax_image as xmax_image,\n        m.ymax_image as ymax_image,\n        m.balrog_index as balrog_index,\n        m.alphawin_j2000 as ra,\n        m.deltawin_j2000 as dec,\n        m.mag_auto as mag_auto,\n        m.spread_model as spread_model,\n        m.spreaderr_model as spreaderr_model,\n        m.class_star as class_star,\n        m.mu_max as mu_max,\n        t.sersicindex_0 as sersic_index,\n        m.disk_scale_image as disk_scale,\n        m.flux_radius as flux_radius,\n        m.mag_disk as mag_disk,\n        m.mag_psf as mag_psf,\n        t.mag as truth_mag_auto,\n        m.flags as flags\n    FROM\n        SUCHYTA1.balrog_%s_sim_%s m\n        JOIN SUCHYTA1.balrog_%s_truth_%s t ON t.balrog_index = m.balrog_index\n    \"\"\" %(table, band, table, band)\n    return q\n\n\n\n\n\ndef DESFields(tilestuff, band='i'):\n    q = \"\"\"\n        SELECT\n           tilename,\n           coadd_objects_id,\n           mag_auto_%s as mag_auto,\n           alphawin_j2000_%s as ra,\n           deltawin_j2000_%s as dec,\n           spread_model_%s as spread_model,\n           spreaderr_model_%s as spreaderr_model,\n           class_star_%s as class_star,\n           mag_psf_%s as mag_psf,\n           flux_radius_%s as flux_radius,\n           flags_%s as flags\n        FROM\n           sva1_coadd_objects\n        WHERE\n           tilename in %s\n        \"\"\" % (band,band,band,band,band,band,band,band,band,str(tuple(np.unique(tilestuff['tilename']))))\n    return q\n\n\ndef TruthFields(band='i', table = 'sva1v2'):\n    q = \"\"\"\n    SELECT\n        balrog_index,\n        tilename,\n        ra,\n        dec,\n        objtype,\n        HALFLIGHTRADIUS_0 as radius,\n        mag,\n        z,\n        sersicindex_0\n    FROM\n        SUCHYTA1.balrog_%s_truth_%s        \n    \"\"\"%(table,band)\n    return q\n    \n\ndef GetDESCat( depthmap, nside, tilestuff, tileinfo, band='i',depth = 0.0):\n    cur = desdb.connect()\n    q = DESFields(tileinfo, band=band)\n    detcat = cur.quick(q, array=True)\n    detcat = ValidDepth(depthmap, nside, detcat, rakey='ra', deckey='dec',depth = depth)\n    detcat = RemoveTileOverlap(tilestuff, detcat, col='tilename', rakey='ra', deckey='dec')\n    return detcat\n\n\n\ndef getTileInfo(catalog, HealConfig=None):\n    if HealConfig is None:\n        HealConfig = getHealConfig()\n        \n    tiles = np.unique(catalog['tilename'])\n    cur = desdb.connect()\n    q = \"SELECT tilename, udecll, udecur, urall, uraur FROM coaddtile\"\n    tileinfo = cur.quick(q, array=True)\n    tilestuff = {}\n    for i in range(len(tileinfo)):\n        tilestuff[ tileinfo[i]['tilename'] ] = tileinfo[i]\n    max = np.power(map_nside/float(HealConfig['out_nside']), 2.0)\n    depthmap, nside = GetDepthMap(HealConfig['depthfile'])\n    return depthmap, nside\n\n\ndef cleanCatalog(catalog, tag='mag_auto'):\n    # We should get rid of obviously wrong things.\n    keep = np.where( (catalog[tag] > 15. ) & (catalog[tag] < 30.) & (catalog['flags'] < 2) )\n    return catalog[keep]\n\ndef removeBadTilesFromTruthCatalog(truth, tag='mag_auto', goodfrac = 0.8):\n    tileList = np.unique(truth['tilename'])\n    number = np.zeros(tileList.size)\n    for tile, i in zip(tileList,xrange(number.size)):\n        number[i] = np.sum(truth['tilename'] == tile)\n    tileList = tileList[number > goodfrac*np.max(number)]\n    keep = np.in1d( truth['tilename'], tileList )\n    return truth[keep]\n\n\n\ndef mergeCatalogsUsingPandas(sim=None, truth=None, key='balrog_index', suffixes = ['_sim','']):\n    import pandas as pd\n    simData = pd.DataFrame(sim)\n    truthData = pd.DataFrame(truth)\n    matched = pd.merge(simData, truthData, on=key, suffixes = suffixes)\n    matched_arr = matched.to_records(index=False)\n    # This last step is necessary because Pandas converts strings to Objects when eating structured arrays.\n    # And np.recfunctions flips out when it has one.\n    oldDtype = matched_arr.dtype.descr\n    newDtype = oldDtype\n    for thisOldType,i in zip(oldDtype, xrange(len(oldDtype) )):\n        if 'O' in thisOldType[1]:\n            newDtype[i] = (thisOldType[0], 'S12')\n    matched_arr = np.array(matched_arr,dtype=newDtype)\n    return matched_arr\n\n\n\ndef GetFromDB( band='i', depth = 0.0,tables =['sva1v2','sva1v3','sva1v3_2','sva1v3_3']): \n    depthfile = '../../Data/sva1_gold_1.0.2-4_nside4096_nest_i_auto_weights.fits'\n\n    cur = desdb.connect()\n    q = \"SELECT tilename, udecll, udecur, urall, uraur FROM coaddtile\"\n    tileinfo = cur.quick(q, array=True)\n    tilestuff = {}\n    for i in range(len(tileinfo)):\n        tilestuff[ tileinfo[i]['tilename'] ] = tileinfo[i]\n    depthmap, nside = GetDepthMap(depthfile)\n    truths = []\n    sims = []\n    truthMatcheds = []\n    \n    for tableName in tables:\n        q = TruthFields(band=band,table=tableName)\n        truth = cur.quick(q, array=True)\n\n        truth = removeBadTilesFromTruthCatalog(truth)\n        truth = ValidDepth(depthmap, nside, truth, depth = depth)\n        truth = RemoveTileOverlap(tilestuff, truth)\n        #truth = cleanCatalog(truth,tag='mag')\n        unique_binds, unique_inds = np.unique(truth['balrog_index'],return_index=True)\n        truth = truth[unique_inds]\n\n        q = SimFields(band=band, table=tableName)\n        sim = cur.quick(q, array=True)\n        sim = cleanCatalog(sim,tag='mag_auto')\n        unique_binds, unique_inds = np.unique(sim['balrog_index'],return_index=True)\n        sim = sim[unique_inds]\n        \n        \n        truthMatched = mergeCatalogsUsingPandas(sim=sim,truth=truth)\n        \n        sim = sim[np.in1d(sim['balrog_index'],truthMatched['balrog_index'])]\n        sim.sort(order='balrog_index')\n        truthMatched.sort(order='balrog_index')\n        \n        truthMatcheds.append(truthMatched)\n        truths.append(truth)\n        sims.append(sim)\n\n    sim = np.hstack(sims)\n    truth = np.hstack(truths)\n    truthMatched = np.hstack(truthMatcheds)\n    \n    des = GetDESCat(depthmap, nside, tilestuff, sim, band=band,depth = depth)\n    des = cleanCatalog(des, tag='mag_auto')\n    \n    return des, sim, truthMatched, truth, tileinfo\n\n\ndef hpRaDecToHEALPixel(ra, dec, nside=  4096, nest= True):\n    phi = ra * np.pi / 180.0\n    theta = (90.0 - dec) * np.pi / 180.0\n    hpInd = hp.ang2pix(nside, theta, phi, nest= nest)\n    return hpInd\n\ndef convertThetaPhiToRaDec(theta, phi):\n    ra = phi*180.0/np.pi\n    dec = 90.0 - theta*180.0/np.pi\n    return ra,dec\n\ndef convertRaDecToThetaPhi(ra, dec):\n    theta = (90.0 - dec) * np.pi / 180.0\n    phi =  ra * np.pi / 180.0\n    return theta, phi\n\ndef HealPixifyCatalogs(catalog=None, healConfig=None, ratag='ra', dectag = 'dec'):\n    HealInds = hpRaDecToHEALPixel( catalog[ratag],catalog[dectag], nside= healConfig['out_nside'], nest= healConfig['nest'])\n    if 'HEALIndex' in catalog.dtype.fields:\n        healCat = catalog.copy()\n        healCat['HEALIndex'] = HealInds\n    else:\n        healCat = rf.append_fields(catalog,'HEALIndex',HealInds,dtypes=HealInds.dtype)\n    return healCat\n\n\ndef getHealConfig(map_nside = 4096, out_nside = 128, depthfile = '../../Data/sva1_gold_1.0.2-4_nside4096_nest_i_auto_weights.fits'):\n    HealConfig = {}\n    HealConfig['map_nside'] = map_nside\n    HealConfig['out_nside'] = out_nside\n    HealConfig['finer_nside'] = map_nside\n    HealConfig['depthfile'] = depthfile\n    HealConfig['nest'] = True\n    return HealConfig\n\n\ndef getGoodRegionIndices(catalog=None, badHPInds=None, nside=4096,band=None, raTag = 'ra', decTag = 'dec'):\n    hpInd = hpRaDecToHEALPixel(catalog[raTag], catalog[decTag], nside=nside, nest= True)\n    keep = ~np.in1d(hpInd, badHPInds)\n    return keep\n\n\ndef excludeBadRegions(des,balrogObs, balrogTruthMatched, balrogTruth, band=None):\n    eliMap = hp.read_map(\"sva1_gold_1.0.4_goodregions_04_equ_nest_4096.fits\", nest=True)\n    nside = hp.npix2nside(eliMap.size)\n    maskIndices = np.arange(eliMap.size)\n    badIndices = maskIndices[eliMap == 1]\n    if band is not None:\n        raTag = 'ra_'+band\n        decTag = 'dec_'+band\n    else:\n        raTag = 'ra'\n        decTag = 'dec'\n    obsKeepIndices = getGoodRegionIndices(catalog=balrogObs, badHPInds=badIndices, nside=nside, raTag = raTag, decTag = decTag)\n    truthKeepIndices = getGoodRegionIndices(catalog=balrogTruth, badHPInds=badIndices, nside=nside, raTag = raTag, decTag = decTag)\n    desKeepIndices = getGoodRegionIndices(catalog=des, badHPInds=badIndices, nside=nside, raTag = raTag, decTag = decTag)\n\n    balrogObs = balrogObs[obsKeepIndices]\n    balrogTruthMatched = balrogTruthMatched[obsKeepIndices]\n    balrogTruth = balrogTruth[truthKeepIndices]\n    des = des[desKeepIndices]\n\n    return des,balrogObs, balrogTruthMatched, balrogTruth\n\n\ndef removeNeighbors(thing1, thing2, radius= 2./3600,\n                    raTag1 = 'ra', decTag1 = 'dec', raTag2 = 'ra', decTag2 = 'dec'):\n    # Returns the elements of thing 1 that are outside of the matching radius from thing 2\n    \n    depth=10\n    h = esutil.htm.HTM(depth)\n    m1, m2, d12 = h.match(thing1[raTag1],thing1[decTag1],thing2[raTag2],thing2[decTag2],radius,maxmatch=0)\n    keep = ~np.in1d(thing1['balrog_index'],thing1['balrog_index'][m1])\n    return keep\n\n\ndef getCatalogs(reload=False,band='i', path = '../../Data/'):\n    # Check to see whether the catalog files exist.  If they do, then\n    # use the files. If at least one does not, then get what we need\n    # from the database\n\n    fileNames = ['desCatalogFile-'+band+'.fits','BalrogObsFile-'+band+'.fits',\n                 'BalrogTruthFile-'+band+'.fits', 'BalrogTruthMatchedFile-'+band+'.fits',\n                 'BalrogTileInfo.fits']\n    exists = True\n    for thisFile in fileNames:\n        print \"Checking for existence of: \"+path+thisFile\n        if not os.path.isfile(path+thisFile): exists = False\n    if exists and not reload:\n\n        desCat = esutil.io.read(path+fileNames[0])\n        BalrogObs = esutil.io.read(path+fileNames[1])\n        BalrogTruth = esutil.io.read(path+fileNames[2])\n        BalrogTruthMatched = esutil.io.read(path+fileNames[3])\n        BalrogTileInfo = esutil.io.read(path+fileNames[4])\n    else:\n        print \"Cannot find files, or have been asked to reload. Getting data from DESDB.\"\n        desCat, BalrogObs, BalrogTruthMatched, BalrogTruth, BalrogTileInfo = GetFromDB(band=band)\n        esutil.io.write( path+fileNames[0], desCat , clobber=True)\n        esutil.io.write( path+fileNames[1], BalrogObs , clobber=True)\n        esutil.io.write( path+fileNames[2], BalrogTruth , clobber=True)\n        esutil.io.write( path+fileNames[3], BalrogTruthMatched , clobber=True)\n        esutil.io.write( path+fileNames[4], BalrogTileInfo, clobber=True)\n        \n    return desCat, BalrogObs, BalrogTruthMatched, BalrogTruth, BalrogTileInfo\n\n\ndef modestify(data):\n    modest = np.zeros(len(data), dtype=np.int32)\n\n    galcut = (data['flags'] <=3) & -( ((data['class_star'] > 0.3) & (data['mag_auto'] < 18.0)) | ((data['spread_model'] + 3*data['spreaderr_model']) < 0.003) | ((data['mag_psf'] > 30.0) & (data['mag_auto'] < 21.0)))\n    modest[galcut] = 1\n\n    starcut = (data['flags'] <=3) & ((data['class_star'] > 0.3) & (data['mag_auto'] < 18.0) & (data['mag_psf'] < 30.0) | (((data['spread_model'] + 3*data['spreaderr_model']) < 0.003) & ((data['spread_model'] +3*data['spreaderr_model']) > -0.003)))\n    modest[starcut] = 3\n\n    neither = -(galcut | starcut)\n    modest[neither] = 5\n\n    data = rf.append_fields(data, 'modtype', modest)\n    print len(data), np.sum(galcut), np.sum(starcut), np.sum(neither)\n    return data\n\n\ndef getCleanCatalogs( reload = False, band=None, isolated=False, nside=None):\n    \n    if band is None:\n        print \"Please specify a filter using the 'band' keyword argument.\"\n        print \"Choose one of [grizY].\"\n        \n        \n    des, balrogObs, balrogTruthMatched, balrogTruth, balrogTileInfo = getCatalogs(reload=reload, band=band)\n\n    # Remove things in regions that are officially masked.\n    des, balrogObs, balrogTruthMatched, balrogTruth = excludeBadRegions(des,balrogObs, balrogTruthMatched, balrogTruth)\n    \n    # if the isolated keyword is set, exclude things within some\n    # separation from a pre-existing DES detection.\n    if isolated is not False:\n        print \"isolated keyword should be set to a number, in arcseconds.\"\n        keep = removeNeighbors(balrogTruthMatched, des, radius= float(isolated)/3600)\n        balrogTruthMatched = balrogTruthMatched[keep]\n        balrogObs = balrogObs[keep]\n    \n    # nside is set, then create a HEALPixel configuration and\n    # assign pixel indices to each object.\n    if nside is not None:\n        HEALConfig = getHealConfig(map_nside = 4096, out_nside = nside )\n        des = HealPixifyCatalogs(catalog=des, healConfig=HEALConfig)\n        balrogObs = HealPixifyCatalogs(catalog=balrogObs, healConfig=HEALConfig)\n        balrogTruth = HealPixifyCatalogs(catalog=balrogTruth, healConfig=HEALConfig)\n        balrogTruthMatched = HealPixifyCatalogs(catalog=balrogTruthMatched, healConfig=HEALConfig)\n        return des, balrogObs, balrogTruthMatched, balrogTruth,HEALConfig\n    else:\n        return des, balrogObs, balrogTruthMatched, balrogTruth\n\ndef matchCatalogs(cat1, cat2 ,tag = 'balrog_index'):\n    ind1, ind2 = esutil.numpy_util.match(cat1[tag], cat2[tag])\n    return cat1[ind1], cat2[ind2]\n    \ndef getStellarityCatalogs( reload = False, band = None, nside = None):\n    \n    des, balrogObs, balrogTruthMatched, balrogTruth = getCleanCatalogs(reload=reload,band=band)\n    des = modestify(des)\n    balrogObs = modestify(balrogObs)\n\n    return des, balrogObs, balrogTruthMatched, balrogTruth\n", "meta": {"hexsha": "53a924acbe096dc12753bdc91e179d2aa9b132a3", "size": 15709, "ext": "py", "lang": "Python", "max_stars_repo_path": "cfunc.py", "max_stars_repo_name": "emhuff/regularizedInversion", "max_stars_repo_head_hexsha": "bb6ef71c041ee9a91a8ef625e0d228458cc8e0e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cfunc.py", "max_issues_repo_name": "emhuff/regularizedInversion", "max_issues_repo_head_hexsha": "bb6ef71c041ee9a91a8ef625e0d228458cc8e0e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cfunc.py", "max_forks_repo_name": "emhuff/regularizedInversion", "max_forks_repo_head_hexsha": "bb6ef71c041ee9a91a8ef625e0d228458cc8e0e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9473684211, "max_line_length": 247, "alphanum_fraction": 0.6563753262, "include": true, "reason": "import numpy", "num_tokens": 4697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188373563072, "lm_q2_score": 0.3208213008246071, "lm_q1q2_score": 0.19255321474630996}}
{"text": "\"\"\"\nInference with different ADC precisions\n\"\"\"\nimport math\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import Tensor\nfrom .utee import wage_quantizer\nfrom .quant_modules import WQ, AQ, stats_quant\n\ndef decimal2binary(weight_q, bitWeight, cellBit):\n    cellRange = 2**cellBit\n    remainder_list = torch.Tensor([]).type_as(weight_q)\n    \n    for k in range(int(bitWeight/cellBit)):\n        remainder = torch.fmod(weight_q, cellRange)\n        remainder = remainder.unsqueeze(0)\n        remainder_list = torch.cat((remainder_list, remainder), dim=0)\n        weight_q = torch.round((weight_q-remainder.squeeze(0))/cellRange)\n    return remainder_list\n\ndef bit2cond(bitWeight, hrs, lrs):\n    \"\"\"\n    Draft: replace the binary values to conductance measurement\n    \"\"\"\n    level0 = torch.ones(bitWeight[bitWeight==0].size()).mul(hrs)\n    level1 = torch.ones(bitWeight[bitWeight==1].size()).mul(lrs)\n\n    bitWeight[bitWeight==0] = level0.cuda()\n    bitWeight[bitWeight==1] = level1.cuda()\n\n    bitWeight = bitWeight.clamp(0)\n    return bitWeight\n\ndef program_noise_cond(weight_q, weight_b, hrs, lrs, sensitive_lv):\n    wb = torch.zeros_like(weight_b)\n    weight_cond = bit2cond(weight_b, hrs, lrs)  # typical values\n\n    for ii in range(len(weight_q.unique())):\n        \n        if len(weight_q.unique()) == 1:\n            ii = int(weight_q.unique().item())\n\n        idx_4b = weight_q.eq(ii)\n        wb_ii = weight_cond[:, idx_4b]\n        wbin_ii = weight_b[:, idx_4b]\n        \n        # noises\n        noise = np.load(f\"/home/mengjian/Desktop/ASU_research/SWIPE_analysis/prob/SWIPE/noSWIPE_25Times_raw/level{ii}_raw.npy\") # 1.66\n        # swipe = np.load(f\"/home/mengjian/Desktop/ASU_research/SWIPE_analysis/prob/SWIPE/Level_4x16_SWIPE_250nPW_chip14_raw_in_16lvl/level{ii}_raw.npy\")\n        \n        # rescale the programming noise with new lrs （1.66 to 1.11)\n        # noise = noise * (1.11e-4/1.66e-4)\n        # swipe = swipe * (1.11e-4/1.66e-4)\n        \n        # noise = np.load(f\"/home/mengjian/Desktop/ASU_research/SWIPE_analysis/prob/SWIPE/DNN_SWIPE_101021/Level_4x16_noSWIPE_250nPW_chip14_raw_in_16lvl_10080928/level{ii}_raw.npy\")\n        # swipe = np.load(f\"/home/mengjian/Desktop/ASU_research/SWIPE_analysis/prob/SWIPE/DNN_SWIPE_102021/Level_4x16_SWIPE_250nPW_chip14_raw_in_16lvl_10201845/level{ii}_raw.npy\")\n        # swipe = np.load(f\"/home/mengjian/Desktop/ASU_research/SWIPE_analysis/prob/SWIPE/DNN_SWIPE_102021/09191845/level{ii}_raw.npy\")   # 1.11\n        swipe = np.load(f\"/home/mengjian/Desktop/ASU_research/SWIPE_analysis/prob/SWIPE/DNN_SWIPE_102021/Level_4x16_SWIPE_250nPW_chip14_raw_in_16lvl_10201845/level{ii}_raw.npy\")   # 1.11\n        swipe = swipe * (1.66e-4/1.11e-4)\n        \n        \n        # sizes\n        _, numel = wb_ii.size()\n        \n        bit_idx = np.arange(noise.shape[0])\n        random_idx = np.random.choice(bit_idx, size=(numel))\n        \n        bit_random_noise = noise[random_idx, :].T\n        swipe_random_noise = swipe[random_idx, :].T\n\n        wb_cond = torch.from_numpy(bit_random_noise).float()\n        swipe_cond = torch.from_numpy(swipe_random_noise).float()\n\n        wb_cond = torch.flip(wb_cond, dims=[0])\n        swipe_cond = torch.flip(swipe_cond, dims=[0])\n\n        if not ii in sensitive_lv:\n            wb[:, idx_4b] = swipe_cond.cuda()   # SWIPE scheme\n        else:\n            wb[:, idx_4b] = wb_cond.cuda()      # Non SWIPE scheme\n        \n        # # statistics\n        # hrs = wb_cond[wb_ii == 0]\n        # lrs = wb_cond[wb_ii == 1]\n        # print(\"\\nLevel {}; Average HRS={}; Average LRS={}; dummy={}\".format(ii, hrs.mean(), lrs.mean(), dummy))\n    return wb\n\nclass RRAMConv2d(nn.Conv2d):\n    r\"\"\"\n    NeuroSim-based RRAM inference with low precision weights and activations\n    \"\"\"\n    def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, \n                wl_input=8, wl_weight=8, subArray=128, inference=0, cellBit=1, ADCprecision=5, sensitive_lv=0):\n        super(RRAMConv2d, self).__init__(in_channels, out_channels, kernel_size,\n                                      stride, padding, dilation, groups, bias)\n        self.wl_input = wl_input\n        self.inference = inference\n        self.wl_weight = wl_weight\n        self.cellBit = cellBit\n        self.ADCprecision = ADCprecision\n        self.layer_idx = 0\n        self.iter = 0\n        self.init = True\n        self.subArray = subArray\n        \n        # quantization\n        self.wbit = wl_weight\n        self.abit = wl_input \n        self.weight_quant = WQ(wbit=wl_weight)\n        self.act_quant = AQ(abit=wl_input, act_alpha=torch.tensor(10.0))\n\n        # conductance\n        self.hrs = 1e-6\n        # self.lrs = 1.11e-04\n        self.lrs = 1.66e-04\n        self.nonideal_unit = self.lrs - self.hrs\n        self.sensitive_lv = sensitive_lv\n    \n    def _act_quant(self, input):\n        act_alpha = self.act_quant.act_alpha \n        input = torch.where(input < act_alpha, input, act_alpha)\n\n        with torch.no_grad():\n            scale = (2**self.abit - 1) / act_alpha\n        \n        input_div = input.mul(scale)\n        input_q = input_div.round()\n        return input_q, scale\n\n    def forward(self, input: Tensor) -> Tensor:        \n        # quantization\n        wq, w_scale = stats_quant(self.weight.data, nbit=self.wbit, dequantize=False)\n        wq = wq.add(2 ** (self.wbit - 1) - 1)\n        wd = torch.ones_like(wq).mul(2 ** (self.wbit - 1) - 1)\n        \n        # decomposition\n        wqb_list = decimal2binary(wq, bitWeight=self.wbit, cellBit=self.cellBit)\n        wdb_list = decimal2binary(wd, bitWeight=self.wbit, cellBit=self.cellBit)\n\n        wqb_list = program_noise_cond(wq, wqb_list, hrs=self.hrs, lrs=self.lrs, sensitive_lv=self.sensitive_lv)\n        wdb_list = program_noise_cond(wd, wdb_list, hrs=self.hrs, lrs=self.lrs, sensitive_lv=self.sensitive_lv)\n\n        # input quantization\n        xq, x_scale = self._act_quant(input)\n        cellRange = 2**self.cellBit\n\n        # targeted output size\n        odim = math.floor((xq.size(2) + 2*self.padding[0] - self.dilation[0] * (wq.size(2)-1)-1)/self.stride[0] + 1)\n        output = torch.zeros((xq.size(0), wq.size(0), odim, odim)).cuda()\n        for i in range(wq.size(2)):\n            for j in range(wq.size(3)):\n                numSubArray = wq.shape[1] // self.subArray\n                \n                if numSubArray == 0:\n                    mask = torch.zeros_like(wq)\n                    mask[:,:,i,j] = 1\n                    xq, x_scale = self._act_quant(input)\n                    outputIN = torch.zeros_like(output)\n                    xb_list = []\n                    for z in range(int(self.abit)):\n                        xb = torch.fmod(xq, 2)\n                        xq = torch.round((xq-xb)/2)\n                        macs = torch.zeros_like(output).cuda()\n\n                        xb_list.append(xb)\n                        for k in range(int(self.wbit/self.cellBit)):\n                            wqb = wqb_list[k]\n                            wdb = wdb_list[k]\n\n                            outputPartial = F.conv2d(xb, wqb*mask, self.bias, self.stride, self.padding, self.dilation, self.groups)\n                            outputOffset = F.conv2d(xb, wdb*mask, self.bias, self.stride, self.padding, self.dilation, self.groups)\n                            scaler = cellRange**k\n\n                            maci = outputPartial - outputOffset\n                            maci = maci.div(self.nonideal_unit)\n\n                            macs = macs + maci * scaler\n                        \n                        scalerIN = 2**z\n                        outputIN = outputIN + macs * scalerIN\n                    output = output + outputIN / x_scale \n                else:\n                    xq, x_scale = self._act_quant(input)\n                    outputIN = torch.zeros_like(output)\n                    for z in range(int(self.abit)):\n                        xb = torch.fmod(xq, 2)\n                        xq = torch.round((xq-xb)/2)\n                        total_macs = torch.zeros_like(output)\n\n                        for s in range(numSubArray):\n                            mask = torch.zeros_like(wq)\n                            mask[:,(s*self.subArray):(s+1)*self.subArray, i, j] = 1\n                            macs = torch.zeros_like(output).cuda()\n\n                            for k in range(int(self.wbit/self.cellBit)):\n                                wqb = wqb_list[k]\n                                wdb = wdb_list[k]\n\n                                outputPartial = F.conv2d(xb, wqb*mask, self.bias, self.stride, self.padding, self.dilation, self.groups)\n                                outputOffset = F.conv2d(xb, wdb*mask, self.bias, self.stride, self.padding, self.dilation, self.groups)\n                                scaler = cellRange**k\n\n                                maci = outputPartial - outputOffset\n                                # ADC\n                                maci = wage_quantizer.LinearQuantizeOut(maci, bit=self.ADCprecision, lb=maci.min(), ub=maci.max())\n                                maci = maci.div(self.nonideal_unit)\n                                macs = macs + maci * scaler\n                                \n                            total_macs = total_macs.add(macs)\n                        scalerIN = 2**z\n                        outputIN = outputIN + total_macs * scalerIN\n                    output = output + outputIN / x_scale \n        output = output / w_scale\n        return output", "meta": {"hexsha": "01288ed66a2c91a45d61ce7a98e6d01db39e8c2c", "size": 9569, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/quant/neurosim_modules.py", "max_stars_repo_name": "mengjian0502/TorchInference_RRAM", "max_stars_repo_head_hexsha": "3fb556dcfb6d9284012613d9c46a595ea3c93f5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/quant/neurosim_modules.py", "max_issues_repo_name": "mengjian0502/TorchInference_RRAM", "max_issues_repo_head_hexsha": "3fb556dcfb6d9284012613d9c46a595ea3c93f5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/quant/neurosim_modules.py", "max_forks_repo_name": "mengjian0502/TorchInference_RRAM", "max_forks_repo_head_hexsha": "3fb556dcfb6d9284012613d9c46a595ea3c93f5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-06T05:47:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T23:30:34.000Z", "avg_line_length": 44.0967741935, "max_line_length": 186, "alphanum_fraction": 0.5667258857, "include": true, "reason": "import numpy", "num_tokens": 2495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.19255321405513484}}
{"text": "import logging\nimport multiprocessing\nimport sys\nimport traceback\nfrom multiprocessing import Pool\n\nimport numpy as np\nimport ellc\nimport matplotlib.pyplot as plt\nfrom lcbuilder.lcbuilder_class import LcBuilder\nfrom lcbuilder.objectinfo.InputObjectInfo import InputObjectInfo\nfrom lcbuilder.objectinfo.MissionInputObjectInfo import MissionInputObjectInfo\nfrom lcbuilder.objectinfo.preparer.MissionLightcurveBuilder import MissionLightcurveBuilder\nfrom lcbuilder.objectinfo.MissionObjectInfo import MissionObjectInfo\nimport wotan\nfrom matplotlib.ticker import FormatStrFormatter\nfrom foldedleastsquares import transitleastsquares, DefaultTransitTemplateGenerator\nfrom foldedleastsquares import transit_mask, cleaned_array\nimport astropy.constants as ac\nimport astropy.units as u\nimport lightkurve as lk\nimport os\nimport re\nimport pandas as pd\n\nfrom tkmatrix.inject_model import InjectModel\n\n\nclass MATRIX:\n    \"\"\"\n    MATRIX: Multi-phAse Transits Recovery from Injected eXoplanets\n    \"\"\"\n    object_info = None\n    SDE_ROCHE = 2000\n    lcbuilder = LcBuilder()\n    MIN_SEARCH_PERIOD = 0.5\n\n    def __init__(self, target, sectors, dir, preserve=False, star_info=None, file=None, exposure_time=None,\n                 initial_mask=None, initial_transit_mask=None,\n                 eleanor_corr_flux='pca_flux', outliers_sigma=None, high_rms_enabled=True, high_rms_threshold=2.5,\n                 high_rms_bin_hours=4, smooth_enabled=False,\n                 auto_detrend_enabled=False, auto_detrend_method=\"cosine\", auto_detrend_ratio=0.25,\n                 auto_detrend_period=None, prepare_algorithm=None, cache_dir=os.path.expanduser('~') + \"/\",\n                 oscillation_reduction=False, oscillation_min_snr=4, oscillation_amplitude_threshold=0.001,\n                 oscillation_ws_percent=0.01, oscillation_min_period=0.002, oscillation_max_period=0.2,\n                 cores=multiprocessing.cpu_count() - 1\n                 ):\n        assert target is not None and isinstance(target, str)\n        assert sectors is not None and (sectors == 'all' or isinstance(sectors, list))\n        assert exposure_time is not None and isinstance(exposure_time, (int, float))\n        assert initial_transit_mask is None or isinstance(initial_transit_mask, list)\n        self.id = target\n        self.dir = dir\n        self.sectors = sectors\n        self.star_info = star_info\n        self.exposure_time = exposure_time\n        self.preserve = preserve\n        self.file = file\n        self.eleanor_corr_flux = eleanor_corr_flux\n        self.initial_mask = initial_mask\n        self.initial_transit_mask = initial_transit_mask\n        self.star_info = star_info\n        self.outliers_sigma = outliers_sigma\n        self.high_rms_enabled = high_rms_enabled\n        self.high_rms_threshold = high_rms_threshold\n        self.high_rms_bin_hours = high_rms_bin_hours\n        self.smooth_enabled = smooth_enabled\n        self.auto_detrend_enabled = auto_detrend_enabled\n        self.auto_detrend_method = auto_detrend_method\n        self.auto_detrend_ratio = auto_detrend_ratio\n        self.auto_detrend_period = auto_detrend_period\n        self.oscillation_reduction = oscillation_reduction\n        self.oscillation_min_snr = oscillation_min_snr\n        self.oscillation_amplitude_threshold = oscillation_amplitude_threshold\n        self.oscillation_ws_percent = oscillation_ws_percent\n        self.oscillation_min_period = oscillation_min_period\n        self.oscillation_max_period = oscillation_max_period\n        self.prepare_algorithm = prepare_algorithm\n        self.cache_dir = cache_dir\n        self.cores = cores\n\n    def retrieve_object_data(self, inject_dir=None):\n        self.object_info = self.lcbuilder.build_object_info(self.id, None, self.sectors, self.file, self.exposure_time,\n                                                       None, None,\n                                                       self.star_info, None,\n                                                       self.eleanor_corr_flux, self.outliers_sigma,\n                                                       False, self.high_rms_threshold,\n                                                       self.high_rms_bin_hours, False,\n                                                       False, self.auto_detrend_method,\n                                                       self.auto_detrend_ratio, self.auto_detrend_period,\n                                                       self.prepare_algorithm, False,\n                                                       self.oscillation_min_snr, self.oscillation_amplitude_threshold,\n                                                       self.oscillation_ws_percent, self.oscillation_min_period,\n                                                       self.oscillation_max_period)\n        if inject_dir is None:\n            inject_dir = self.build_inject_dir()\n        self.lc_build = self.lcbuilder.build(self.object_info, inject_dir, self.cache_dir)\n        if self.star_info is None:\n            self.star_info = self.lc_build.star_info\n        self.ab = self.star_info.ld_coefficients\n        self.mass = self.star_info.mass\n        self.massmin = self.star_info.mass_min\n        self.massmax = self.star_info.mass_max\n        self.radius = self.star_info.radius\n        self.radiusmin = self.star_info.radius_min\n        self.radiusmax = self.star_info.radius_max\n        # units for ellc\n        self.rstar = self.star_info.radius * u.R_sun\n        self.mstar = self.star_info.mass * u.M_sun\n        self.mstar_min = self.star_info.mass_min * u.M_sun\n        self.mstar_max = self.star_info.mass_max * u.M_sun\n        self.rstar_min = self.star_info.radius_min * u.R_sun\n        self.rstar_max = self.star_info.radius_max * u.R_sun\n        return inject_dir\n\n    def retrieve_object_data_for_recovery(self, inject_dir, recovery_file):\n        self.__setup_logging(inject_dir)\n        self.object_info = self.lcbuilder.build_object_info(\"\", None, None, recovery_file, self.exposure_time,\n                                                       self.initial_mask, self.initial_transit_mask,\n                                                       self.star_info, None,\n                                                       self.eleanor_corr_flux, self.outliers_sigma,\n                                                       self.high_rms_enabled, self.high_rms_threshold,\n                                                       self.high_rms_bin_hours, self.smooth_enabled,\n                                                       self.auto_detrend_enabled, self.auto_detrend_method,\n                                                       self.auto_detrend_ratio, self.auto_detrend_period,\n                                                       self.prepare_algorithm, self.oscillation_reduction,\n                                                       self.oscillation_min_snr, self.oscillation_amplitude_threshold,\n                                                       self.oscillation_ws_percent, self.oscillation_min_period,\n                                                       self.oscillation_max_period)\n\n        if self.object_info.reduce_simple_oscillations and \\\n                self.object_info.oscillation_max_period < self.object_info.oscillation_min_period:\n            logging.info(\"Stellar oscillation period has been set to empty. Defaulting to 1/3 the minimum search period\")\n            self.object_info.oscillation_max_period = self.MIN_SEARCH_PERIOD / 3\n        self.lc_build = self.lcbuilder.build(self.object_info, inject_dir, self.cache_dir)\n\n    def build_inject_dir(self):\n        inject_dir = self.dir + \"/\" + self.object_info.mission_id().replace(\" \", \"\") + \"_ir/\"\n        index = 0\n        while os.path.exists(inject_dir) or os.path.isdir(inject_dir):\n            inject_dir = self.dir + \"/\" + self.object_info.mission_id().replace(\" \", \"\") + \"_ir_\" + str(index) + \"/\"\n            index = index + 1\n        os.mkdir(inject_dir)\n        self.__setup_logging(inject_dir)\n        return inject_dir\n\n    def __setup_logging(self, inject_dir):\n        file_dir = inject_dir + \"matrix.log\"\n        formatter = logging.Formatter('%(message)s')\n        logger = logging.getLogger()\n        while len(logger.handlers) > 0:\n            logger.handlers.pop()\n        logger.setLevel(logging.INFO)\n        handler = logging.StreamHandler(sys.stdout)\n        handler.setLevel(logging.INFO)\n        handler.setFormatter(formatter)\n        logger.addHandler(handler)\n        handler = logging.FileHandler(file_dir)\n        handler.setLevel(logging.INFO)\n        handler.setFormatter(formatter)\n        logger.addHandler(handler)\n        logging.info(\"Setup injection directory\")\n\n    def inject(self, phases, min_period, max_period, steps_period, min_radius, max_radius, steps_radius,\n               period_grid_geom=\"lin\", radius_grid_geom=\"lin\"):\n        assert phases is not None and isinstance(phases, int) and phases > 0\n        assert min_period is not None and isinstance(min_period, (int, float)) and min_period > 0\n        assert max_period is not None and isinstance(max_period, (int, float)) and max_period > 0\n        assert steps_period is not None and isinstance(steps_period, (int)) and steps_period > 0\n        assert min_radius is not None and isinstance(min_radius, (int, float)) and min_radius > 0\n        assert max_radius is not None and isinstance(max_radius, (int, float)) and max_radius > 0\n        assert steps_radius is not None and isinstance(steps_radius, (int)) and steps_radius > 0\n        assert max_period >= min_period\n        assert max_radius >= min_radius\n        inject_dir = self.retrieve_object_data()\n        flux0 = self.lc_build.lc.flux.value\n        time = self.lc_build.lc.time.value\n        flux_err = self.lc_build.lc.flux_err.value\n        period_grid = np.linspace(min_period, max_period, steps_period) if period_grid_geom == \"lin\" \\\n            else np.logspace(np.log10(min_period), np.log10(max_period), steps_period)\n        radius_grid = np.linspace(min_radius, max_radius, steps_radius) if radius_grid_geom == \"lin\" \\\n            else np.logspace(np.log10(min_radius), np.log10(max_radius), steps_period)\n        inject_models = []\n        for period in period_grid:\n            for t0 in np.arange(time[60], time[60] + period - 0.1, period / phases):\n                for rplanet in radius_grid:\n                    rplanet = np.around(rplanet, decimals=2) * u.R_earth\n                    inject_models.append(InjectModel(inject_dir, time, flux0, flux_err, self.rstar, self.mstar, t0,\n                                                     period, rplanet, self.exposure_time, self.ab))\n        with Pool(processes=self.cores) as pool:\n            pool.map(InjectModel.make_model, inject_models)\n        return inject_dir\n\n\n    def recovery(self, inject_dir, snr_threshold=5, sherlock_samples=0, detrend_ws=0,\n                 transit_template='tls', run_limit=5, custom_search_algorithm=None, max_period_search=25):\n        assert detrend_ws is not None and isinstance(detrend_ws, (int, float))\n        assert transit_template in ('tls', 'bls')\n        assert inject_dir is not None and isinstance(inject_dir, str)\n        if transit_template == 'tls':\n            transit_template = 'default'\n        elif transit_template == 'bls':\n            transit_template = 'box'\n        reports_df = pd.DataFrame(columns=['period', 'radius', 'epoch', 'duration_found', 'period_found', 'epoch_found',\n                                           'found', 'snr', 'sde', 'run'])\n        for file in sorted(os.listdir(inject_dir)):\n            file_name_matches = re.search(\"P([0-9]+\\\\.[0-9]+)+_R([0-9]+\\\\.[0-9]+)_([0-9]+\\\\.[0-9]+)\\\\.csv\", file)\n            if file_name_matches is not None:\n                try:\n                    period = float(file_name_matches[1])\n                    r_planet = float(file_name_matches[2])\n                    epoch = float(file_name_matches[3])\n                    df = pd.read_csv(inject_dir + file, float_precision='round_trip', sep=',',\n                                     usecols=['#time', 'flux', 'flux_err'])\n                    if len(df) == 0:\n                        found = True\n                        snr = 20\n                        sde = self.SDE_ROCHE\n                        run = 1\n                        duration_found = 20\n                        epoch_found = 0\n                        period_found = 0\n                    else:\n                        self.retrieve_object_data_for_recovery(inject_dir + \"/\", inject_dir + file)\n                        found, snr, sde, run, duration_found, period_found, epoch_found = \\\n                            self.__search(self.lc_build.lc.time.value, self.lc_build.lc.flux.value, self.radius, self.radiusmin,\n                                          self.radiusmax, self.mass, self.massmin,\n                                          self.massmax, self.ab, epoch, period, self.MIN_SEARCH_PERIOD,\n                                          max_period_search, snr_threshold,\n                                          transit_template, detrend_ws, self.lc_build.transits_min_count,\n                                          run_limit, custom_search_algorithm)\n                    new_report = {\"period\": period, \"radius\": r_planet, \"epoch\": epoch, \"found\": found, \"snr\": snr,\n                                  \"sde\": sde, \"run\": run, \"duration_found\": duration_found,\n                                  \"period_found\": period_found, \"epoch_found\": epoch_found}\n                    reports_df = reports_df.append(new_report, ignore_index=True)\n                    print(\"P=\" + str(period) + \", R=\" + str(r_planet) + \", T0=\" + str(epoch) + \", FOUND WAS \" + str(\n                        found) +\n                          \" WITH SNR \" + str(snr) + \" AND SDE \" + str(sde))\n                    reports_df = reports_df.sort_values(['period', 'radius', 'epoch'], ascending=[True, True, True])\n                    reports_df.to_csv(inject_dir + \"a_tls_report.csv\", index=False)\n                except Exception as e:\n                    traceback.print_exc()\n                    print(\"File not valid: \" + file)\n        # tls_report_df = pd.read_csv(inject_dir + \"a_tls_report.csv\", float_precision='round_trip', sep=',',\n        #                             usecols=['period', 'radius', 'epoch', 'found', 'duration', 'snr', 'sde', 'run'])\n        if sherlock_samples > 0:\n            from sherlockpipe import sherlock\n            from sherlockpipe.scoring.QuorumSnrBorderCorrectedSignalSelector import QuorumSnrBorderCorrectedSignalSelector\n\n            class QuorumSnrBorderCorrectedStopWhenMatchSignalSelector(QuorumSnrBorderCorrectedSignalSelector):\n                def __init__(self, strength=1, min_quorum=0, per=None, t0=None):\n                    super().__init__()\n                    self.strength = strength\n                    self.min_quorum = min_quorum\n                    self.per = per\n                    self.t0 = t0\n\n                def select(self, transit_results, snr_min, detrend_method, wl):\n                    signal_selection = super(QuorumSnrBorderCorrectedStopWhenMatchSignalSelector, self) \\\n                        .select(transit_results, snr_min, detrend_method, wl)\n                    if signal_selection.score == 0 or (\n                            self.is_harmonic(signal_selection.transit_result.period, self.per) and\n                            self.isRightEpoch(signal_selection.transit_result.t0, self.t0, self.per)):\n                        signal_selection.score = 0\n                    return signal_selection\n\n                def is_harmonic(self, a, b, tolerance=0.05):\n                    a = np.float(a)\n                    b = np.float(b)\n                    mod_ab = a % b\n                    mod_ba = b % a\n                    return (a > b and a < b * 3 + tolerance * 3 and (\n                            abs(mod_ab % 1) <= tolerance or abs((b - mod_ab) % 1) <= tolerance)) or \\\n                           (b > a and a > b / 3 - tolerance / 3 and (\n                                   abs(mod_ba % 1) <= tolerance or abs((a - mod_ba) % 1) <= tolerance))\n\n                def isRightEpoch(self, t0, known_epoch, known_period):\n                    right_epoch = False\n                    for i in range(-5, 5):\n                        right_epoch = right_epoch or (np.abs(t0 - known_epoch + i * known_period) < (\n                                1. / 24.))\n                    return right_epoch\n            report = {}\n            reports_df = pd.DataFrame(columns=['period', 'radius', 'epoch', 'found', 'snr', 'sde', 'run'])\n            a = False\n            samples_analysed = sherlock_samples\n            for index, row in tls_report_df[::-1].iterrows():\n                file = os.path.join(\n                    'P' + str(row['period']) + '_R' + str(row['radius']) + '_' + str(row['epoch']) + '.csv')\n                first_false = index > 0 and tls_report_df.iloc[index - 1]['found'] and \\\n                            not tls_report_df.iloc[index]['found']\n                if first_false:\n                    samples_analysed = 0\n                elif tls_report_df.iloc[index]['found']:\n                    samples_analysed = sherlock_samples\n                if samples_analysed < sherlock_samples:\n                    try:\n                        samples_analysed = samples_analysed + 1\n                        period = float(re.search(\"P([0-9]+\\\\.[0-9]+)\", file)[1])\n                        r_planet = float(re.search(\"R([0-9]+\\\\.[0-9]+)\", file)[1])\n                        epoch = float(re.search(\"_([0-9]+\\\\.[0-9]+)\\\\.csv\", file)[1])\n                        signal_selection_algorithm = QuorumSnrBorderCorrectedStopWhenMatchSignalSelector(1, 0, period,\n                                                                                                         epoch)\n                        df = pd.read_csv(inject_dir + file, float_precision='round_trip', sep=',',\n                                         usecols=['#time', 'flux', 'flux_err'])\n                        if len(df) == 0:\n                            found = True\n                            snr = 20\n                            sde = 20\n                            run = 1\n                        else:\n                            sherlock.Sherlock(False, object_infos=[MissionInputObjectInfo(self.id, inject_dir + file)]) \\\n                                .setup_detrend(True, True, 1.5, 4, 12, \"biweight\", 0.2, 1.0, 20, False,\n                                               0.25, \"cosine\", None) \\\n                                .setup_transit_adjust_params(5, None, None, 10, None, None, 0.4, 14, 10,\n                                                             20, 5, 5.5, 0.05, \"mask\", \"quorum\", 1, 0,\n                                                             signal_selection_algorithm) \\\n                                .run()\n                            df = pd.read_csv(self.id.replace(\" \", \"\") + \"_INP/candidates.csv\", float_precision='round_trip', sep=',',\n                                             usecols=['curve', 'period', 't0', 'run', 'snr', 'sde', 'rad_p',\n                                                      'transits'])\n                            snr = df[\"snr\"].iloc[len(df) - 1]\n                            run = df[\"run\"].iloc[len(df) - 1]\n                            sde = df[\"sde\"].iloc[len(df) - 1]\n                            per_run = 0\n                            found_period = False\n                            j = 0\n                            for per in df[\"period\"]:\n                                if signal_selection_algorithm.is_harmonic(per, period / 2.):\n                                    found_period = True\n                                    t0 = df[\"t0\"].iloc[j]\n                                    break\n                                j = j + 1\n                            right_epoch = False\n                            if found_period:\n                                for i in range(-5, 5):\n                                    right_epoch = right_epoch or (np.abs(t0 - epoch + i * period) < (\n                                            1. / 24.))\n                                    if right_epoch:\n                                        snr = df[\"snr\"].iloc[j]\n                                        run = df[\"run\"].iloc[j]\n                                        sde = df[\"sde\"].iloc[j]\n                                        break\n                            found = right_epoch\n                        new_report = {\"period\": period, \"radius\": r_planet, \"epoch\": epoch, \"found\": found, \"sde\": sde,\n                                      \"snr\": snr,\n                                      \"run\": int(run)}\n                        reports_df = reports_df.append(new_report, ignore_index=True)\n                        reports_df.to_csv(inject_dir + \"a_sherlock_report.csv\", index=False)\n                        print(\"P=\" + str(period) + \", R=\" + str(r_planet) + \", T0=\" + str(epoch) + \", FOUND WAS \" + str(\n                            found) +\n                              \" WITH SNR \" + str(snr) + \"and SDE \" + str(sde))\n                    except Exception as e:\n                        print(e)\n                        print(\"File not valid: \" + file)\n\n        # If preserve parameter is not True, we remove inject files:\n        if not self.preserve:\n            for file in os.listdir(inject_dir):\n                if file.endswith(\".csv\") and file.startswith(\"P\"):\n                    os.remove(inject_dir + file)\n\n    def transit_masks(self, transit_masks, time):\n        if transit_masks is None:\n            transit_masks = []\n        result = np.full(len(time), False)\n        for mask in transit_masks:\n            intransit = transit_mask(time, mask[\"P\"], 2 * mask[\"D\"], mask[\"T0\"])\n            result[intransit] = True\n\n        return result\n\n    def __clean(self, lc, detrend_period, detrend_period_method, custom_clean_algorithm):\n        clean_flux = lc.flux.value\n        time = lc.time.value\n        if custom_clean_algorithm is not None:\n            clean_flux = custom_clean_algorithm.clean(time, clean_flux)\n        elif detrend_period:\n            periodogram = lc.to_periodogram(minimum_period=0.05, maximum_period=15, oversample_factor=10)\n            ws = self.__calculate_max_significant_period(lc, periodogram)\n            clean_flux = wotan.flatten(time, clean_flux, window_length=ws, return_trend=False,\n                                       method=detrend_period_method, break_tolerance=0.5)\n        return clean_flux\n\n    def __calculate_max_significant_period(self, lc, periodogram):\n        #max_accepted_period = (lc.time[len(lc.time) - 1] - lc.time[0]) / 4\n        max_accepted_period = np.float64(10)\n        # TODO related to https://github.com/franpoz/SHERLOCK/issues/29 check whether this fits better\n        max_power_index = np.argmax(periodogram.power)\n        period = periodogram.period[max_power_index]\n        if max_power_index > 0.0008:\n            period = period.value\n            logging.info(\"Auto-Detrend found the strong period: \" + str(period) + \".\")\n        else:\n            logging.info(\"Auto-Detrend did not find relevant periods.\")\n            period = None\n        return period\n\n    @staticmethod\n    def plot_results(object_id, inject_dir, binning=1, xticks=None, yticks=None, period_grid_geom=\"lin\",\n                     radius_grid_geom=\"lin\"):\n        df = pd.read_csv(inject_dir + '/a_tls_report.csv', float_precision='round_trip', sep=',',\n                         usecols=['period', 'radius', 'found', 'sde'])\n        min_period = df[\"period\"].min()\n        max_period = df[\"period\"].max()\n        min_rad = df[\"radius\"].min()\n        max_rad = df[\"radius\"].max()\n        phases = len(df[df[\"period\"] == df[\"period\"].min()][df[\"radius\"] == df[\"radius\"].min()])\n        phases_str = \"phase\" if phases == 1 else \"phases\"\n        bin_nums = int(np.ceil(len(df[\"period\"].unique()) / binning))\n        if period_grid_geom == 'lin':\n            step_period = (max_period - min_period) / (len(df[\"period\"].unique()) - 1)\n            step_period = step_period * binning\n            if step_period <= 0:\n                step_period = 0.1\n            period_grid = np.linspace(min_period, max_period, bin_nums)\\\n                if max_period - min_period > 0 else np.full((1), min_period)\n        else:\n            period_grid = np.logspace(np.log10(min_period), np.log10(max_period), bin_nums)\n        bin_nums = int(np.ceil(len(df[\"radius\"].unique()) / binning))\n        if radius_grid_geom == 'lin':\n            step_radius = (max_rad - min_rad) / (len(df[\"radius\"].unique()) - 1)\n            step_radius = step_radius * binning\n            if step_radius <= 0:\n                step_radius = 0.1\n            radius_grid = np.round(np.linspace(min_rad, max_rad, bin_nums), 2)\\\n                if max_rad - min_rad > 0 else np.full((1), min_rad)\n        else:\n            radius_grid = np.round(np.logspace(np.log10(min_rad), np.log10(max_rad), 2), bin_nums)\n        f = len(period_grid) / len(radius_grid)\n        bins = [period_grid, radius_grid]\n        h1, x, y = np.histogram2d(df['period'][df['found'] == 1], df['radius'][df['found'] == 1], bins=bins)\n        h2, x, y = np.histogram2d(df['period'][df['found'] == 0], df['radius'][df['found'] == 0], bins=bins)\n        normed_hist = (100. * h1 / (h1 + h2))\n        fig, ax = plt.subplots(figsize=(2.7 * 5, 5))\n        im = plt.imshow(normed_hist.T, origin='lower', extent=(x[0], x[-1], y[0], y[-1]), interpolation='none',\n                        aspect='auto', cmap='viridis', vmin=0, vmax=100, rasterized=True)\n        plt.colorbar(im, label='Recovery rate (%)')\n        plt.xlabel('Injected period (days)')\n        plt.ylabel(r'Injected radius (R$_\\oplus$)')\n        ax.set_title(object_id + \" - P/R recovery (\" + str(phases) + \" \" + phases_str + \")\")\n        if xticks is not None:\n            plt.xticks(xticks)\n        else:\n            period_ticks_decimals = MATRIX.num_of_zeros(max_period - min_period) + 1\n            plot_bins = 10 if 10 < len(period_grid) else len(period_grid)\n            plt.locator_params(axis=\"x\", nbins=plot_bins)\n            ax.xaxis.set_major_formatter(FormatStrFormatter('%.' + str(period_ticks_decimals) + 'f'))\n        if yticks is not None:\n            plt.xticks(yticks)\n        plt.savefig(inject_dir + '/inj-rec.png', bbox_inches='tight', dpi=200)\n        plt.close()\n\n    @staticmethod\n    def plot_diff(object_id, inject_dir1, inject_dir2, output_dir, binning=1, xticks=None, yticks=None,\n                  period_grid_geom=\"lin\", radius_grid_geom=\"lin\"):\n        df1 = pd.read_csv(inject_dir1 + '/a_tls_report.csv', float_precision='round_trip', sep=',',\n                         usecols=['period', 'radius', 'found', 'sde'])\n        df2 = pd.read_csv(inject_dir2 + '/a_tls_report.csv', float_precision='round_trip', sep=',',\n                         usecols=['period', 'radius', 'found', 'sde'])\n        min_period = df1[\"period\"].min()\n        max_period = df1[\"period\"].max()\n        min_rad = df1[\"radius\"].min()\n        max_rad = df1[\"radius\"].max()\n        phases = len(df1[df1[\"period\"] == df1[\"period\"].min()][df1[\"radius\"] == df1[\"radius\"].min()])\n        phases_str = \"phase\" if phases == 1 else \"phases\"\n        bin_nums = int(np.ceil(len(df1[\"period\"].unique()) / binning))\n        if period_grid_geom == 'lin':\n            step_period = (max_period - min_period) / (len(df1[\"period\"].unique()) - 1)\n            step_period = step_period * binning\n            if step_period <= 0:\n                step_period = 0.1\n            period_grid = np.linspace(min_period, max_period, bin_nums)\\\n                if max_period - min_period > 0 else np.full((1), min_period)\n        else:\n            period_grid = np.logspace(np.log10(min_period), np.log10(max_period), bin_nums)\n        bin_nums = int(np.ceil(len(df1[\"radius\"].unique()) / binning))\n        if radius_grid_geom == 'lin':\n            step_radius = (max_rad - min_rad) / (len(df1[\"radius\"].unique()) - 1)\n            step_radius = step_radius * binning\n            if step_radius <= 0:\n                step_radius = 0.1\n            radius_grid = np.round(np.linspace(min_rad, max_rad, bin_nums), 2)\\\n                if max_rad - min_rad > 0 else np.full((1), min_rad)\n        else:\n            radius_grid = np.round(np.logspace(np.log10(min_rad), np.log10(max_rad), 2), bin_nums)\n        f = len(period_grid) / len(radius_grid)\n        bins = [period_grid, radius_grid]\n        h11, x1, y1 = np.histogram2d(df1['period'][df1['found'] == 1], df1['radius'][df1['found'] == 1], bins=bins)\n        h12, x1, y1 = np.histogram2d(df1['period'][df1['found'] == 0], df1['radius'][df1['found'] == 0], bins=bins)\n        h21, x2, y2 = np.histogram2d(df2['period'][df2['found'] == 1], df2['radius'][df2['found'] == 1], bins=bins)\n        h22, x2, y2 = np.histogram2d(df2['period'][df2['found'] == 0], df2['radius'][df2['found'] == 0], bins=bins)\n        h1 = h11 - h12\n        h2 = h21 - h22\n        normed_hist1 = phases * h11 / (h11 + h12)\n        normed_hist2 = phases * h21 / (h21 + h22)\n        normed_hist = normed_hist1 - normed_hist2\n        fig, ax = plt.subplots(figsize=(2.7 * 5, 5))\n        im = plt.imshow(normed_hist.T, origin='lower', extent=(x1[0], x1[-1], y1[0], y1[-1]), interpolation='none',\n                        aspect='auto', cmap='viridis', vmin=-phases, vmax=phases, rasterized=True)\n        plt.colorbar(im, label='# Found samples diff.')\n        plt.xlabel('Injected period (days)')\n        plt.ylabel(r'Injected radius (R$_\\oplus$)')\n        ax.set_title(object_id + \" - P/R recovery diff(\" + str(phases) + \" \" + phases_str + \")\")\n        if xticks is not None:\n            plt.xticks(xticks)\n        else:\n            period_ticks_decimals = MATRIX.num_of_zeros(max_period - min_period) + 1\n            plot_bins = 10 if 10 < len(period_grid) else len(period_grid)\n            plt.locator_params(axis=\"x\", nbins=plot_bins)\n            ax.xaxis.set_major_formatter(FormatStrFormatter('%.' + str(period_ticks_decimals) + 'f'))\n        if yticks is not None:\n            plt.xticks(yticks)\n        plt.savefig(output_dir + '/inj-rec-diff.png', bbox_inches='tight', dpi=200)\n        plt.close()\n\n    def __search(self, time, flux, rstar, rstar_min, rstar_max, mass, mstar_min, mstar_max, ab, epoch,\n                 period, min_period, max_period, min_snr, transit_template, ws, transits_min_count,\n                 run_limit, custom_search_algorithm):\n        tls_period_grid = self.__calculate_period_grid(time, min_period, max_period, 3, self.star_info,\n                                                   transits_min_count)\n        if custom_search_algorithm is not None:\n            return custom_search_algorithm.search(time, flux, rstar, rstar_min, rstar_max, mass, mstar_min, mstar_max,\n                                                ab, epoch, period, min_period, max_period, min_snr, self.cores,\n                                                transit_template, ws, transits_min_count, run_limit)\n        else:\n            return self.__tls_search(time, flux, rstar, rstar_min, rstar_max, mass, mstar_min, mstar_max, ab, epoch,\n                     period, min_period, max_period, min_snr, self.cores, transit_template, ws, transits_min_count,\n                     run_limit, tls_period_grid)\n\n    def __tls_search(self, time, flux, rstar, rstar_min, rstar_max, mass, mstar_min, mstar_max, ab, epoch,\n                     period, min_period, max_period, min_snr, cores, transit_template, ws, transits_min_count,\n                     run_limit, tls_period_grid):\n        snr = 1e12\n        found_signal = False\n        time, flux = cleaned_array(time, flux)\n        run = 0\n        if ws > 0:\n            flux = wotan.flatten(time, flux, window_length=ws, return_trend=False, method='biweight', break_tolerance=0.5)\n        while snr >= min_snr and not found_signal and (run_limit > 0 and run < run_limit):\n            model = transitleastsquares(time, flux)\n            # R_starx = rstar / u.R_sun\n            results = model.power(u=ab,\n                                  R_star=rstar,  # rstar/u.R_sun,\n                                  R_star_min=rstar_min,  # rstar_min/u.R_sun,\n                                  R_star_max=rstar_max,  # rstar_max/u.R_sun,\n                                  M_star=mass,  # mstar/u.M_sun,\n                                  M_star_min=mstar_min,  # mstar_min/u.M_sun,\n                                  M_star_max=mstar_max,  # mstar_max/u.M_sun,\n                                  period_min=min_period,\n                                  period_max=max_period,\n                                  n_transits_min=transits_min_count,\n                                  show_progress_bar=False,\n                                  use_threads=cores,\n                                  transit_template=transit_template,\n                                  period_grid=tls_period_grid\n                                  )\n            snr = results.snr\n            if results.snr >= min_snr:\n                intransit_result = transit_mask(time, results.period, 2 * results.duration, results.T0)\n                time = time[~intransit_result]\n                flux = flux[~intransit_result]\n                time, flux = cleaned_array(time, flux)\n                right_period = self.__is_multiple_of(results.period, period / 2.)\n                right_epoch = False\n                for tt in results.transit_times:\n                    for i in range(-5, 5):\n                        right_epoch = right_epoch or (np.abs(tt - epoch + i * period) < (1. / 24.))\n                #            right_depth   = (np.abs(np.sqrt(1.-results.depth)*rstar - rplanet)/rplanet < 0.05) #check if the depth matches\n                if right_period and right_epoch:\n                    found_signal = True\n                    break\n            run = run + 1\n        return found_signal, results.snr, results.SDE, run, results.duration, results.period, results.T0\n\n    def __equal(self, a, b, tolerance=0.01):\n        return np.abs(a - b) < tolerance\n\n    def __calculate_period_grid(self, time, min_period, max_period, oversampling, star_info, transits_min_count):\n        dif = time[1:] - time[:-1]\n        jumps = np.where(dif > 1)[0]\n        jumps = np.append(jumps, len(time))\n        previous_jump_index = 0\n        time_span_all_sectors = 0\n        for jumpIndex in jumps:\n            time_chunk = time[previous_jump_index + 1:jumpIndex]  # ignoring first measurement as could be the last from the previous chunk\n            time_span_all_sectors = time_span_all_sectors + (time_chunk[-1] - time_chunk[0])\n            previous_jump_index = jumpIndex\n        return DefaultTransitTemplateGenerator() \\\n            .period_grid(star_info.radius, star_info.mass, time[-1] - time[0], min_period, max_period, oversampling,\n                         transits_min_count, time_span_all_sectors)\n\n    @staticmethod\n    def num_of_zeros(n):\n        if n.is_integer():\n            return 0\n        s = '{:.16f}'.format(n).split('.')[1]\n        return len(s) - len(s.lstrip('0'))\n\n    def __is_multiple_of(self, a, b, tolerance=0.05):\n        a = np.float(a)\n        b = np.float(b)\n        mod_ab = a % b\n        mod_ba = b % a\n        return (a > b and a < b * 3 + tolerance * 3 and (\n                    abs(mod_ab % 1) <= tolerance or abs((b - mod_ab) % 1) <= tolerance)) or \\\n               (b > a and a > b / 3 - tolerance / 3 and (\n                           abs(mod_ba % 1) <= tolerance or abs((a - mod_ba) % 1) <= tolerance))\n", "meta": {"hexsha": "6fbd522ea90b7c4e944b212685ac9c71f3598c87", "size": 35620, "ext": "py", "lang": "Python", "max_stars_repo_path": "tkmatrix/tkmatrix_class.py", "max_stars_repo_name": "PlanetHunters/tkmatrix", "max_stars_repo_head_hexsha": "7c112e2cbcd1e75753828a334720ddf7972c8551", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-09T18:50:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T18:50:23.000Z", "max_issues_repo_path": "tkmatrix/tkmatrix_class.py", "max_issues_repo_name": "PlanetHunters/tkmatrix", "max_issues_repo_head_hexsha": "7c112e2cbcd1e75753828a334720ddf7972c8551", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2021-03-24T14:13:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T06:37:45.000Z", "max_forks_repo_path": "tkmatrix/tkmatrix_class.py", "max_forks_repo_name": "martindevora/tkmatrix", "max_forks_repo_head_hexsha": "7c112e2cbcd1e75753828a334720ddf7972c8551", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-09T18:50:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-09T18:50:26.000Z", "avg_line_length": 58.4893267652, "max_line_length": 139, "alphanum_fraction": 0.5521617069, "include": true, "reason": "import numpy,import astropy", "num_tokens": 8024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.19255321405513484}}
{"text": "import torch\nimport numpy as np\nimport os\nfrom skimage import draw\nfrom geotnf.transformation import GeometricTnf\nfrom geotnf.flow import th_sampling_grid_to_np_flow, write_flo_file\nimport torch.nn.functional as F\nfrom data.pf_dataset import PFDataset, PFPascalDataset\nfrom data.caltech_dataset import CaltechDataset\nfrom torch.autograd import Variable\nfrom geotnf.point_tnf import PointTnf, PointsToUnitCoords, PointsToPixelCoords\nfrom util.py_util import create_file_path\nfrom model.loss import WeakInlierCount, TwoStageWeakInlierCount\n\n\ndef compute_metric(metric,model,dataset,dataloader,batch_tnf,batch_size,two_stage=True,do_aff=False,do_tps=False,args=None):\n    # Initialize stats\n    N=len(dataset)\n    stats={}\n    # decide which results should be computed aff/tps/aff+tps\n    if two_stage or do_aff:\n        stats['aff']={}\n    if not two_stage and do_tps:\n        stats['tps']={}\n    if two_stage:\n        stats['aff_tps']={}\n    # choose metric function and metrics to compute\n    if metric=='pck':  \n        metrics = ['pck']\n        metric_fun = pck_metric\n    if metric=='dist':\n        metrics = ['dist']\n        metric_fun = point_dist_metric\n    elif metric=='area':\n        metrics = ['intersection_over_union',\n                   'label_transfer_accuracy',\n                   'localization_error']\n        metric_fun = area_metrics\n    elif metric=='pascal_parts':\n        metrics = ['intersection_over_union','pck']\n        metric_fun = pascal_parts_metrics\n    elif metric=='flow':\n        metrics = ['flow']\n        metric_fun = flow_metrics\n    elif metric=='inlier_count':\n        metrics = ['inlier_count']\n        metric_fun = inlier_count\n        model.return_correlation = True\n    # initialize vector for storing results for each metric\n    for key in stats.keys():\n        for metric in metrics:\n            stats[key][metric] = np.zeros((N,1))\n\n    # Compute\n    for i, batch in enumerate(dataloader):\n        batch = batch_tnf(batch)        \n        batch_start_idx=batch_size*i\n        batch_end_idx=np.minimum(batch_start_idx+batch_size,N)\n\n        model.eval()\n        theta_aff=None\n        theta_tps=None\n        theta_aff_tps=None\n        \n        if two_stage:\n            if model.return_correlation==False:\n                theta_aff,theta_aff_tps=model(batch)\n            else:\n                theta_aff,theta_aff_tps,corr_aff,corr_aff_tps=model(batch)\n        elif do_aff:\n            theta_aff=model(batch)\n            if isinstance(theta_aff,tuple):\n                theta_aff=theta_aff[0]\n        elif do_tps:\n            theta_tps=model(batch)   \n            if isinstance(theta_tps,tuple):\n                theta_tps=theta_tps[0]\n        \n        if metric=='inlier_count':\n            stats = inlier_count(batch,batch_start_idx,theta_aff,theta_tps,theta_aff_tps,corr_aff,corr_aff_tps,stats,args)\n        elif metric_fun is not None:\n            stats = metric_fun(batch,batch_start_idx,theta_aff,theta_tps,theta_aff_tps,stats,args)\n            \n        print('Batch: [{}/{} ({:.0f}%)]'.format(i, len(dataloader), 100. * i / len(dataloader)))\n\n    # Print results\n    if metric == 'flow':\n        print('Flow files have been saved to '+args.flow_output_dir)\n        return stats\n\n    for key in stats.keys():\n        print('=== Results '+key+' ===')\n        for metric in metrics:\n            # print per-class brakedown for PFPascal, or caltech\n            if isinstance(dataset,PFPascalDataset):\n                N_cat = int(np.max(dataset.category))\n                for c in range(N_cat):\n                    cat_idx = np.nonzero(dataset.category==c+1)[0]\n                    print(dataset.category_names[c].ljust(15)+': ','{:.2%}'.format(np.mean(stats[key][metric][cat_idx])))\n\n            # print mean value\n            results=stats[key][metric]\n            good_idx = np.flatnonzero((results!=-1) * ~np.isnan(results))\n            print('Total: '+str(results.size))\n            print('Valid: '+str(good_idx.size)) \n            filtered_results = results[good_idx]\n            print(metric+':','{:.2%}'.format(np.mean(filtered_results)))\n\n        print('\\n')\n        \n    return stats\n\ndef pck(source_points,warped_points,L_pck,alpha=0.1):\n    # compute precentage of correct keypoints\n    batch_size=source_points.size(0)\n    pck=torch.zeros((batch_size))\n    for i in range(batch_size):\n        p_src = source_points[i,:]\n        p_wrp = warped_points[i,:]\n        N_pts = torch.sum(torch.ne(p_src[0,:],-1)*torch.ne(p_src[1,:],-1))\n        point_distance = torch.pow(torch.sum(torch.pow(p_src[:,:N_pts]-p_wrp[:,:N_pts],2),0),0.5)\n        L_pck_mat = L_pck[i].expand_as(point_distance)\n        correct_points = torch.le(point_distance,L_pck_mat*alpha)\n        pck[i]=torch.mean(correct_points.float())\n    return pck\n\ndef mean_dist(source_points,warped_points,L_pck):\n    # compute precentage of correct keypoints\n    batch_size=source_points.size(0)\n    dist=torch.zeros((batch_size))\n    for i in range(batch_size):\n        p_src = source_points[i,:]\n        p_wrp = warped_points[i,:]\n        N_pts = torch.sum(torch.ne(p_src[0,:],-1)*torch.ne(p_src[1,:],-1))\n        point_distance = torch.pow(torch.sum(torch.pow(p_src[:,:N_pts]-p_wrp[:,:N_pts],2),0),0.5)\n        L_pck_mat = L_pck[i].expand_as(point_distance)\n        dist[i]=torch.mean(torch.div(point_distance,L_pck_mat))\n    return dist\n\ndef point_dist_metric(batch,batch_start_idx,theta_aff,theta_tps,theta_aff_tps,stats,args,use_cuda=True):\n    do_aff = theta_aff is not None\n    do_tps = theta_tps is not None\n    do_aff_tps = theta_aff_tps is not None\n    \n    source_im_size = batch['source_im_size']\n    target_im_size = batch['target_im_size']\n\n    source_points = batch['source_points']\n    target_points = batch['target_points']\n    \n    # Instantiate point transformer\n    pt = PointTnf(use_cuda=use_cuda,\n                  tps_reg_factor=args.tps_reg_factor)\n\n    # warp points with estimated transformations\n    target_points_norm = PointsToUnitCoords(target_points,target_im_size)\n\n    if do_aff:\n        # do affine only\n        warped_points_aff_norm = pt.affPointTnf(theta_aff,target_points_norm)\n        warped_points_aff = PointsToPixelCoords(warped_points_aff_norm,source_im_size)\n\n    if do_tps:\n        # do tps only\n        warped_points_tps_norm = pt.tpsPointTnf(theta_tps,target_points_norm)\n        warped_points_tps = PointsToPixelCoords(warped_points_tps_norm,source_im_size)\n        \n    if do_aff_tps:\n        # do tps+affine\n        warped_points_aff_tps_norm = pt.tpsPointTnf(theta_aff_tps,target_points_norm)\n        warped_points_aff_tps_norm = pt.affPointTnf(theta_aff,warped_points_aff_tps_norm)\n        warped_points_aff_tps = PointsToPixelCoords(warped_points_aff_tps_norm,source_im_size)\n    \n    L_pck = batch['L_pck'].data\n    \n    current_batch_size=batch['source_im_size'].size(0)\n    indices = range(batch_start_idx,batch_start_idx+current_batch_size)\n\n#    import pdb; pdb.set_trace()\n\n    if do_aff:\n        dist_aff = mean_dist(source_points.data, warped_points_aff.data, L_pck)\n        \n    if do_tps:\n        dist_tps = mean_dist(source_points.data, warped_points_tps.data, L_pck)\n        \n    if do_aff_tps:\n        dist_aff_tps = mean_dist(source_points.data, warped_points_aff_tps.data, L_pck)\n        \n    if do_aff:\n        stats['aff']['dist'][indices] = dist_aff.unsqueeze(1).cpu().numpy()\n    if do_tps:\n        stats['tps']['dist'][indices] = dist_tps.unsqueeze(1).cpu().numpy()\n    if do_aff_tps:\n        stats['aff_tps']['dist'][indices] = dist_aff_tps.unsqueeze(1).cpu().numpy() \n        \n    return stats\n\ndef inlier_count(batch,batch_start_idx,theta_aff,theta_tps,theta_aff_tps,corr_aff,corr_aff_tps,stats,args,use_cuda=True):\n    inliersComposed = TwoStageWeakInlierCount(use_cuda=torch.cuda.is_available(),dilation_filter=0,normalize_inlier_count=True)\n    inliers_comp = inliersComposed(matches=corr_aff,theta_aff=theta_aff,theta_aff_tps=theta_aff_tps)\n    current_batch_size=batch['source_im_size'].size(0)\n    indices = range(batch_start_idx,batch_start_idx+current_batch_size)\n    \n    stats['aff_tps']['inlier_count'][indices] = inliers_comp.unsqueeze(1).cpu().data.numpy()\n\n    return stats\n\n\ndef pck_metric(batch,batch_start_idx,theta_aff,theta_tps,theta_aff_tps,stats,args,use_cuda=True):\n    alpha = args.pck_alpha\n    do_aff = theta_aff is not None\n    do_tps = theta_tps is not None\n    do_aff_tps = theta_aff_tps is not None\n    \n    source_im_size = batch['source_im_size']\n    target_im_size = batch['target_im_size']\n\n    source_points = batch['source_points']\n    target_points = batch['target_points']\n    \n    # Instantiate point transformer\n    pt = PointTnf(use_cuda=use_cuda,\n                  tps_reg_factor=args.tps_reg_factor)\n\n    # warp points with estimated transformations\n    target_points_norm = PointsToUnitCoords(target_points,target_im_size)\n\n    if do_aff:\n        # do affine only\n        warped_points_aff_norm = pt.affPointTnf(theta_aff,target_points_norm)\n        warped_points_aff = PointsToPixelCoords(warped_points_aff_norm,source_im_size)\n\n    if do_tps:\n        # do tps only\n        warped_points_tps_norm = pt.tpsPointTnf(theta_tps,target_points_norm)\n        warped_points_tps = PointsToPixelCoords(warped_points_tps_norm,source_im_size)\n        \n    if do_aff_tps:\n        # do tps+affine\n        warped_points_aff_tps_norm = pt.tpsPointTnf(theta_aff_tps,target_points_norm)\n        warped_points_aff_tps_norm = pt.affPointTnf(theta_aff,warped_points_aff_tps_norm)\n        warped_points_aff_tps = PointsToPixelCoords(warped_points_aff_tps_norm,source_im_size)\n    \n    L_pck = batch['L_pck'].data\n    \n    current_batch_size=batch['source_im_size'].size(0)\n    indices = range(batch_start_idx,batch_start_idx+current_batch_size)\n\n    # import pdb; pdb.set_trace()\n\n    if do_aff:\n        pck_aff = pck(source_points.data, warped_points_aff.data, L_pck, alpha)\n        \n    if do_tps:\n        pck_tps = pck(source_points.data, warped_points_tps.data, L_pck, alpha)\n        \n    if do_aff_tps:\n        pck_aff_tps = pck(source_points.data, warped_points_aff_tps.data, L_pck, alpha)\n        \n    if do_aff:\n        stats['aff']['pck'][indices] = pck_aff.unsqueeze(1).cpu().numpy()\n    if do_tps:\n        stats['tps']['pck'][indices] = pck_tps.unsqueeze(1).cpu().numpy()\n    if do_aff_tps:\n        stats['aff_tps']['pck'][indices] = pck_aff_tps.unsqueeze(1).cpu().numpy() \n        \n    return stats\n\ndef pascal_parts_metrics(batch,batch_start_idx,theta_aff,theta_tps,theta_aff_tps,stats,args,use_cuda=True):\n    do_aff = theta_aff is not None\n    do_tps = theta_tps is not None\n    do_aff_tps = theta_aff_tps is not None\n\n    batch_size=batch['source_im_size'].size(0)\n    for b in range(batch_size):\n        idx = batch_start_idx+b\n        h_src = int(batch['source_im_size'][b,0].data.cpu().numpy())\n        w_src = int(batch['source_im_size'][b,1].data.cpu().numpy())\n        h_tgt = int(batch['target_im_size'][b,0].data.cpu().numpy())\n        w_tgt = int(batch['target_im_size'][b,1].data.cpu().numpy())\n        \n        # do pck\n        if batch['keypoint_A'][b].size!=0:\n            src_points = Variable(torch.FloatTensor(batch['keypoint_A'][b])).unsqueeze(0)\n            tgt_points = Variable(torch.FloatTensor(batch['keypoint_B'][b])).unsqueeze(0)\n            L_pck = Variable(torch.FloatTensor([batch['L_pck'][b]])).unsqueeze(1)\n            if use_cuda:\n                src_points=src_points.cuda()\n                tgt_points=tgt_points.cuda()\n                L_pck = L_pck.cuda()\n\n            batch_b = {'source_im_size': batch['source_im_size'][b,:].unsqueeze(0),\n                       'target_im_size': batch['target_im_size'][b,:].unsqueeze(0),\n                       'source_points':  src_points,\n                       'target_points': tgt_points,\n                       'L_pck': L_pck}\n            args.pck_alpha = 0.05\n            stats = pck_metric(batch_b,\n                               idx,\n                               theta_aff[b,:].unsqueeze(0) if do_aff else None,\n                               theta_tps[b,:].unsqueeze(0) if do_tps else None,\n                               theta_aff_tps[b,:].unsqueeze(0) if do_aff_tps else None,\n                               stats,args,use_cuda)\n        else:\n            if do_aff:\n                stats['aff']['pck'][idx] = -1\n            if do_tps:\n                stats['tps']['pck'][idx] = -1\n            if do_aff_tps:\n                stats['aff_tps']['pck'][idx] = -1\n                \n        # do area\n        source_mask = Variable(torch.FloatTensor(batch['part_A'][b].astype(np.float32)).unsqueeze(0).transpose(2,3).transpose(1,2))\n        target_mask = Variable(torch.FloatTensor(batch['part_B'][b].astype(np.float32)).unsqueeze(0).transpose(2,3).transpose(1,2))\n        \n        if use_cuda:\n            source_mask = source_mask.cuda()\n            target_mask = target_mask.cuda()\n            \n        grid_aff,grid_tps,grid_aff_tps=theta_to_sampling_grid(h_tgt,w_tgt,\n                                                              theta_aff[b,:] if do_aff else None,\n                                                              theta_tps[b,:] if do_tps else None,\n                                                              theta_aff_tps[b,:] if do_aff_tps else None,\n                                                              use_cuda=use_cuda,\n                                                              tps_reg_factor=args.tps_reg_factor)\n\n          \n        if do_aff:\n            warped_mask_aff = F.grid_sample(source_mask, grid_aff)            \n            stats['aff']['intersection_over_union'][idx] = intersection_over_union(warped_mask_aff,target_mask)   \n        if do_tps:\n            warped_mask_tps = F.grid_sample(source_mask, grid_tps)            \n            stats['tps']['intersection_over_union'][idx] = intersection_over_union(warped_mask_tps,target_mask)\n        if do_aff_tps:\n            warped_mask_aff_tps = F.grid_sample(source_mask, grid_aff_tps)           \n            stats['aff_tps']['intersection_over_union'][idx] = intersection_over_union(warped_mask_aff_tps,target_mask)\n\n    return stats\n\ndef area_metrics(batch,batch_start_idx,theta_aff,theta_tps,theta_aff_tps,stats,args,use_cuda=True):\n    do_aff = theta_aff is not None\n    do_tps = theta_tps is not None\n    do_aff_tps = theta_aff_tps is not None\n    \n    batch_size=batch['source_im_size'].size(0)\n\n    pt=PointTnf(use_cuda=use_cuda)\n\n    for b in range(batch_size):\n        h_src = int(batch['source_im_size'][b,0].data.cpu().numpy())\n        w_src = int(batch['source_im_size'][b,1].data.cpu().numpy())\n        h_tgt = int(batch['target_im_size'][b,0].data.cpu().numpy())\n        w_tgt = int(batch['target_im_size'][b,1].data.cpu().numpy())\n\n        target_mask_np,target_mask = poly_str_to_mask(batch['target_polygon'][0][b],\n                                                      batch['target_polygon'][1][b],\n                                                      h_tgt,w_tgt,use_cuda=use_cuda)\n\n        source_mask_np,source_mask = poly_str_to_mask(batch['source_polygon'][0][b],\n                                                      batch['source_polygon'][1][b],\n                                                      h_src,w_src,use_cuda=use_cuda)\n\n        grid_X,grid_Y = np.meshgrid(np.linspace(-1,1,w_tgt),np.linspace(-1,1,h_tgt))\n        grid_X = torch.FloatTensor(grid_X).unsqueeze(0).unsqueeze(3)\n        grid_Y = torch.FloatTensor(grid_Y).unsqueeze(0).unsqueeze(3)\n        grid_X = Variable(grid_X,requires_grad=False)\n        grid_Y = Variable(grid_Y,requires_grad=False)\n\n        if use_cuda:\n            grid_X = grid_X.cuda()\n            grid_Y = grid_Y.cuda()\n\n        grid_X_vec = grid_X.view(1,1,-1)\n        grid_Y_vec = grid_Y.view(1,1,-1)\n\n        grid_XY_vec = torch.cat((grid_X_vec,grid_Y_vec),1)        \n\n        def pointsToGrid (x,h_tgt=h_tgt,w_tgt=w_tgt): return x.contiguous().view(1,2,h_tgt,w_tgt).transpose(1,2).transpose(2,3)\n\n        idx = batch_start_idx+b\n        \n        if do_aff:\n            grid_aff = pointsToGrid(pt.affPointTnf(theta_aff[b,:].unsqueeze(0),grid_XY_vec))\n            warped_mask_aff = F.grid_sample(source_mask, grid_aff)            \n            flow_aff = th_sampling_grid_to_np_flow(source_grid=grid_aff,h_src=h_src,w_src=w_src)\n            \n            stats['aff']['intersection_over_union'][idx] = intersection_over_union(warped_mask_aff,target_mask)\n            stats['aff']['label_transfer_accuracy'][idx] = label_transfer_accuracy(warped_mask_aff,target_mask)\n            stats['aff']['localization_error'][idx] = localization_error(source_mask_np, target_mask_np, flow_aff)\n        if do_tps:\n            grid_tps = pointsToGrid(pt.tpsPointTnf(theta_tps[b,:].unsqueeze(0),grid_XY_vec))\n            warped_mask_tps = F.grid_sample(source_mask, grid_tps)\n            flow_tps = th_sampling_grid_to_np_flow(source_grid=grid_tps,h_src=h_src,w_src=w_src)\n            \n            stats['tps']['intersection_over_union'][idx] = intersection_over_union(warped_mask_tps,target_mask)\n            stats['tps']['label_transfer_accuracy'][idx] = label_transfer_accuracy(warped_mask_tps,target_mask)\n            stats['tps']['localization_error'][idx] = localization_error(source_mask_np, target_mask_np, flow_tps)\n        if do_aff_tps:\n            grid_aff_tps = pointsToGrid(pt.affPointTnf(theta_aff[b,:].unsqueeze(0),pt.tpsPointTnf(theta_aff_tps[b,:].unsqueeze(0),grid_XY_vec)))\n            warped_mask_aff_tps = F.grid_sample(source_mask, grid_aff_tps)\n            flow_aff_tps = th_sampling_grid_to_np_flow(source_grid=grid_aff_tps,h_src=h_src,w_src=w_src)\n            \n            stats['aff_tps']['intersection_over_union'][idx] = intersection_over_union(warped_mask_aff_tps,target_mask)\n            stats['aff_tps']['label_transfer_accuracy'][idx] = label_transfer_accuracy(warped_mask_aff_tps,target_mask)\n            stats['aff_tps']['localization_error'][idx] = localization_error(source_mask_np, target_mask_np, flow_aff_tps)\n        \n    return stats\n\n\ndef flow_metrics(batch,batch_start_idx,theta_aff,theta_tps,theta_aff_tps,stats,args,use_cuda=True):\n    result_path=args.flow_output_dir\n    \n    do_aff = theta_aff is not None\n    do_tps = theta_tps is not None\n    do_aff_tps = theta_aff_tps is not None\n\n    pt=PointTnf(use_cuda=use_cuda)\n    \n    batch_size=batch['source_im_size'].size(0)\n    for b in range(batch_size):\n        h_src = int(batch['source_im_size'][b,0].data.cpu().numpy())\n        w_src = int(batch['source_im_size'][b,1].data.cpu().numpy())\n        h_tgt = int(batch['target_im_size'][b,0].data.cpu().numpy())\n        w_tgt = int(batch['target_im_size'][b,1].data.cpu().numpy())\n\n        grid_X,grid_Y = np.meshgrid(np.linspace(-1,1,w_tgt),np.linspace(-1,1,h_tgt))\n        grid_X = torch.FloatTensor(grid_X).unsqueeze(0).unsqueeze(3)\n        grid_Y = torch.FloatTensor(grid_Y).unsqueeze(0).unsqueeze(3)\n        grid_X = Variable(grid_X,requires_grad=False)\n        grid_Y = Variable(grid_Y,requires_grad=False)\n        if use_cuda:\n            grid_X = grid_X.cuda()\n            grid_Y = grid_Y.cuda()\n\n        grid_X_vec = grid_X.view(1,1,-1)\n        grid_Y_vec = grid_Y.view(1,1,-1)\n\n        grid_XY_vec = torch.cat((grid_X_vec,grid_Y_vec),1)        \n\n        def pointsToGrid (x,h_tgt=h_tgt,w_tgt=w_tgt): return x.contiguous().view(1,2,h_tgt,w_tgt).transpose(1,2).transpose(2,3)\n\n        idx = batch_start_idx+b\n                \n        if do_aff:\n            grid_aff = pointsToGrid(pt.affPointTnf(theta_aff[b,:].unsqueeze(0),grid_XY_vec))\n            flow_aff = th_sampling_grid_to_np_flow(source_grid=grid_aff,h_src=h_src,w_src=w_src)\n            flow_aff_path = os.path.join(result_path,'aff',batch['flow_path'][b])\n            create_file_path(flow_aff_path)\n            write_flo_file(flow_aff,flow_aff_path)\n        if do_tps:\n            grid_tps = pointsToGrid(pt.tpsPointTnf(theta_tps[b,:].unsqueeze(0),grid_XY_vec))\n            flow_tps = th_sampling_grid_to_np_flow(source_grid=grid_tps,h_src=h_src,w_src=w_src)\n            flow_tps_path = os.path.join(result_path,'tps',batch['flow_path'][b])\n            create_file_path(flow_tps_path)\n            write_flo_file(flow_tps,flow_tps_path)\n        if do_aff_tps:\n            grid_aff_tps = pointsToGrid(pt.affPointTnf(theta_aff[b,:].unsqueeze(0),pt.tpsPointTnf(theta_aff_tps[b,:].unsqueeze(0),grid_XY_vec)))\n            flow_aff_tps = th_sampling_grid_to_np_flow(source_grid=grid_aff_tps,h_src=h_src,w_src=w_src)\n            flow_aff_tps_path = os.path.join(result_path,'aff_tps',batch['flow_path'][b])\n            create_file_path(flow_aff_tps_path)\n            write_flo_file(flow_aff_tps,flow_aff_tps_path)\n\n        idx = batch_start_idx+b\n    return stats\n\ndef poly_to_mask(vertex_row_coords, vertex_col_coords, shape):\n    fill_row_coords, fill_col_coords = draw.polygon(vertex_row_coords, vertex_col_coords, shape)\n    mask = np.zeros(shape, dtype=np.bool)\n    mask[fill_row_coords, fill_col_coords] = True\n    return mask\n\ndef poly_str_to_mask(poly_x_str,poly_y_str,out_h,out_w,use_cuda=True):\n    polygon_x = np.fromstring(poly_x_str,sep=',')\n    polygon_y = np.fromstring(poly_y_str,sep=',')\n    mask_np = poly_to_mask(vertex_col_coords=polygon_x,\n                               vertex_row_coords=polygon_y,shape=[out_h,out_w])\n    mask = Variable(torch.FloatTensor(mask_np.astype(np.float32)).unsqueeze(0).unsqueeze(0))\n    if use_cuda:\n        mask = mask.cuda()\n    return (mask_np,mask)\n\n#def intersection_over_union(warped_mask,target_mask): \n#    return torch.sum(warped_mask.data.gt(0.5) & target_mask.data.gt(0.5))/torch.sum(warped_mask.data.gt(0.5) | target_mask.data.gt(0.5))\ndef intersection_over_union(warped_mask,target_mask): \n    relative_part_weight = torch.sum(torch.sum(target_mask.data.gt(0.5).float(),2,True),3,True)/torch.sum(target_mask.data.gt(0.5).float())\n    part_iou = torch.sum(torch.sum((warped_mask.data.gt(0.5) & target_mask.data.gt(0.5)).float(),2,True),3,True)/torch.sum(torch.sum((warped_mask.data.gt(0.5) | target_mask.data.gt(0.5)).float(),2,True),3,True)\n    weighted_iou = torch.sum(torch.mul(relative_part_weight,part_iou))\n    return weighted_iou\n\ndef label_transfer_accuracy(warped_mask,target_mask): \n    return torch.mean((warped_mask.data.gt(0.5) == target_mask.data.gt(0.5)).double())\n\ndef localization_error(source_mask_np, target_mask_np, flow_np):\n    h_tgt, w_tgt = target_mask_np.shape[0],target_mask_np.shape[1]\n    h_src, w_src = source_mask_np.shape[0],source_mask_np.shape[1]\n\n    # initial pixel positions x1,y1 in target image\n    x1, y1 = np.meshgrid(range(1,w_tgt+1), range(1,h_tgt+1))\n    # sampling pixel positions x2,y2\n    x2 = x1 + flow_np[:,:,0]\n    y2 = y1 + flow_np[:,:,1]\n\n    # compute in-bound coords for each image\n    in_bound = (x2 >= 1) & (x2 <= w_src) & (y2 >= 1) & (y2 <= h_src)\n    row,col = np.where(in_bound)\n    row_1=y1[row,col].flatten().astype(np.int)-1\n    col_1=x1[row,col].flatten().astype(np.int)-1\n    row_2=y2[row,col].flatten().astype(np.int)-1\n    col_2=x2[row,col].flatten().astype(np.int)-1\n\n    # compute relative positions\n    target_loc_x,target_loc_y = obj_ptr(target_mask_np)\n    source_loc_x,source_loc_y = obj_ptr(source_mask_np)\n    x1_rel=target_loc_x[row_1,col_1]\n    y1_rel=target_loc_y[row_1,col_1]\n    x2_rel=source_loc_x[row_2,col_2]\n    y2_rel=source_loc_y[row_2,col_2]\n\n    # compute localization error\n    loc_err = np.mean(np.abs(x1_rel-x2_rel)+np.abs(y1_rel-y2_rel))\n    \n    return loc_err\n\ndef obj_ptr(mask):\n    # computes images of normalized coordinates around bounding box\n    # kept function name from DSP code\n    h,w = mask.shape[0],mask.shape[1]\n    y, x = np.where(mask>0.5)\n    left = np.min(x);\n    right = np.max(x);\n    top = np.min(y);\n    bottom = np.max(y);\n    fg_width = right-left + 1;\n    fg_height = bottom-top + 1;\n    x_image,y_image = np.meshgrid(range(1,w+1), range(1,h+1));\n    x_image = (x_image - left)/fg_width;\n    y_image = (y_image - top)/fg_height;\n    return (x_image,y_image)\n\n", "meta": {"hexsha": "2d0da244246766918bc64e38fef3ac72c9c9dea7", "size": 23991, "ext": "py", "lang": "Python", "max_stars_repo_path": "util/eval_util.py", "max_stars_repo_name": "hukim1112/weakalign", "max_stars_repo_head_hexsha": "4d2c5a275fd50f34418734198b32de3c8ce749a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "util/eval_util.py", "max_issues_repo_name": "hukim1112/weakalign", "max_issues_repo_head_hexsha": "4d2c5a275fd50f34418734198b32de3c8ce749a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util/eval_util.py", "max_forks_repo_name": "hukim1112/weakalign", "max_forks_repo_head_hexsha": "4d2c5a275fd50f34418734198b32de3c8ce749a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.3456561922, "max_line_length": 210, "alphanum_fraction": 0.6504105706, "include": true, "reason": "import numpy", "num_tokens": 6121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.19248093185662354}}
{"text": "# Copyright 2020 Makani Technologies LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Python dynamics helpers.\n\nProvides a simplified control-oriented model of the wing and tether.\n\"\"\"\nimport collections\nimport copy\n\nfrom makani.analysis.control import actuator_util\nfrom makani.analysis.control import catenary\nfrom makani.analysis.control import geometry\nfrom makani.analysis.control import type_util\nfrom makani.control import control_types\nfrom makani.control import system_types\nfrom makani.sim.physics import physics\nimport numpy as np\n\n# Structure storing a force, moment, and position at which that force\n# is applied.\nForceMomentPos = collections.namedtuple('ForceMomentPos',\n                                        ['force', 'moment', 'pos'])\n\n# Structure for storing forces and moment.\nForceMoment = collections.namedtuple('ForceMoment', ['force', 'moment'])\n\n# Structure representing the inputs to the wing.\n#   thrust: Motor thrust [N] (1-by-1 np.matrix).\n#   motor_moment: Motor moments [N-m] (3-by-1 np.matrix).\n#   flaps: Flaps [rad] (kNumFlaps-by-1 np.matrix).\n#   wind_g: Wind speed [m/s] in ground coordinates (3-by-1 np.matrix).\nWingInputs = type_util.MakeNamedVectorClass(  # pylint: disable=invalid-name\n    'WingInputs', [('thrust', range(0, 1)),\n                   ('motor_moment', range(1, 4)),\n                   ('flaps', range(4, 4 + system_types.kNumFlaps)),\n                   ('wind_g', range(4 + system_types.kNumFlaps,\n                                    7 + system_types.kNumFlaps))])\n\n\nclass WingState(type_util.MakeStateClass(\n    'WingState', [('omega_b', range(0, 3)),\n                  ('dcm_g2b', range(3, 6)),\n                  ('wing_vel_g', range(6, 9)),\n                  ('wing_pos_g', range(9, 12))])):\n  \"\"\"Class representing the state of the wing.\n\n  Attributes:\n    omega_b: Body angular rates.\n    dcm_g2b: Ground to body rotation DCM.  Increments in the DCM are represented\n        by an Euler vector.\n    wing_vel_g: Velocity of the wing in ground coordinates.\n    wing_pos_g: Position of the wing in ground coordinates.\n  \"\"\"\n\n  def Increment(self, tangent, step=1.0):\n    \"\"\"Return a state evolved from this state along a tangent direction.\n\n    Args:\n      tangent: A WingState.Tangent along which to move.\n      step: A scaling of how far to move.\n\n    Returns:\n      A new WingState.\n    \"\"\"\n    return WingState(omega_b=self.omega_b + step * tangent.domega_b,\n                     dcm_g2b=(geometry.AxisToDcm(step * tangent.ddcm_g2b)\n                              * self.dcm_g2b),\n                     wing_vel_g=self.wing_vel_g + step * tangent.dwing_vel_g,\n                     wing_pos_g=self.wing_pos_g + step * tangent.dwing_pos_g)\n\n  def Difference(self, other_state):\n    \"\"\"Inverse operation of Increment with a step size of 1.0.\"\"\"\n    return WingState.Tangent(\n        domega_b=other_state.omega_b - self.omega_b,\n        ddcm_g2b=geometry.DcmToAxis(other_state.dcm_g2b * self.dcm_g2b.T),\n        dwing_vel_g=other_state.wing_vel_g - self.wing_vel_g,\n        dwing_pos_g=other_state.wing_pos_g - self.wing_pos_g)\n\n  @type_util.RequireMatrixArguments(None, (3, 1))\n  def CalcAerodynamicAngles(self, wind_g):\n    \"\"\"Calculates (v_rel, alpha, beta) from the current wing state.\n\n    Args:\n      wind_g: A 3-by-1 matrix storing the wind in g coordinates.\n\n    Returns:\n      A tuple (v_rel, alpha, beta).\n    \"\"\"\n    return geometry.VelocitiesToAerodynamicAngles(\n        self.dcm_g2b, self.wing_vel_g, wind_g)\n\n\n@type_util.RequireMatrixArguments((3, 1), (3, 2), None, None)\ndef _CalcBridleKnotPos(tether_force_b, bridle_pos, bridle_y_offset,\n                       bridle_radius):\n  \"\"\"Calculate the bridle knot position in body coordinates.\"\"\"\n  if np.linalg.norm(tether_force_b) == 0.0:\n    tether_force_b = np.matrix([[0.0], [0.0], [1.0]])\n\n  # Calculate the knot point location.  Here we use a bridle\n  # coordinate system with its origin at the bridle pivot, its\n  # y-axis pointing toward the starboard bridle point and its z-axis\n  # pointed at the knot.\n  bridle_coord_y = bridle_pos[:, 1] - bridle_pos[:, 0]\n  bridle_coord_y /= np.linalg.norm(bridle_coord_y)\n\n  bridle_coord_z = copy.copy(tether_force_b)\n  bridle_coord_z -= bridle_coord_y * (np.transpose(bridle_coord_y)\n                                      * tether_force_b)\n  bridle_coord_z /= np.linalg.norm(bridle_coord_z)\n\n  bridle_coord_origin = (bridle_pos[:, 1] + bridle_pos[:, 0]) * 0.5\n  bridle_coord_origin[1] += bridle_y_offset\n\n  return bridle_coord_origin + bridle_coord_z * bridle_radius\n\n\nclass MotorModel(object):\n\n  # pylint: disable=unused-argument\n  def CalcMotorForceMomentPos(self, v_rel, alpha, beta, omega_b,\n                              thrust, motor_moment_r):\n    raise NotImplementedError()\n\n\nclass PureForceMomentMotorModel(MotorModel):\n\n  def __init__(self, rotor_params, pos_com_b):\n    self._dcm_r2b = geometry.AngleToDcm(\n        0.0, np.arctan2(rotor_params[0]['axis'][2],\n                        rotor_params[0]['axis'][0]), 0.0)\n    self._pos_com_b = np.matrix(pos_com_b).T\n\n  # pylint: disable=unused-argument\n  @type_util.RequireMatrixArguments(None, None, None, None, (3, 1), (1, 1),\n                                    (3, 1))\n  def CalcMotorForceMomentPos(self, v_rel, alpha, beta, omega_b,\n                              thrust, motor_moment_r):\n    # NOTE: This neglects motor reaction torques, and assumes that\n    # MixRotors cancels the non-zero torque about the center-of-mass\n    # that results from pure thrusting.\n    motor_force_r = np.matrix([[thrust[0, 0]], [0.0], [0.0]])\n    return ForceMomentPos(\n        self._dcm_r2b * motor_force_r, self._dcm_r2b * motor_moment_r,\n        self._pos_com_b)\n\n\nclass MotorMixerMotorModel(MotorModel):\n  \"\"\"Model the commanded thrust and moment by calling MixRotors.\"\"\"\n\n  def __init__(self, rotor_databases, air_density, weights, rotor_params,\n               rotor_control_params, hover_flight_mode=False):\n    self._dcm_r2b = geometry.AngleToDcm(\n        0.0, np.arctan2(rotor_params[0]['axis'][2],\n                        rotor_params[0]['axis'][0]), 0.0)\n    self._rotor_databases = rotor_databases\n    self._air_density = air_density\n    self._weights = weights\n    self._rotor_params = rotor_params\n    self._rotor_control_params = rotor_control_params\n    self._hover_flight_mode = hover_flight_mode\n\n  @type_util.RequireMatrixArguments(None, None, (3, 1), (1, 1), (3, 1))\n  def CalcRotorSpeeds(self, v_rel, omega_b, thrust, motor_moment_r):\n    thrust_moment = {\n        'thrust': thrust[0, 0],\n        'moment': [motor_moment_r[i, 0] for i in range(3)]\n    }\n\n    return actuator_util.MixRotors(\n        thrust_moment, self._weights, v_rel, [omega_b[i, 0] for i in range(3)],\n        control_types.kStackingStateNormal, self._hover_flight_mode,\n        self._air_density, self._rotor_params, self._rotor_control_params)\n\n  @type_util.RequireMatrixArguments(None, None, None, None, (3, 1), (1, 1),\n                                    (3, 1))\n  def CalcMotorForceMomentPos(self, v_rel, alpha, beta, omega_b,\n                              thrust, motor_moment_r):\n    rotor_speeds = self.CalcRotorSpeeds(v_rel, omega_b, thrust, motor_moment_r)\n    total_force = np.matrix(np.zeros((3, 1)))\n    total_moment = np.matrix(np.zeros((3, 1)))\n\n    v_rel_b = geometry.AerodynamicAnglesToRelativeVelocity(v_rel, alpha, beta)\n    for i in range(rotor_speeds.shape[0]):\n      rotor_speed = rotor_speeds[i, 0]\n      if self._rotor_params[i]['dir'] == system_types.kPositiveX:\n        direction = 1.0\n      else:\n        direction = -1.0\n      rotor_velocity = direction * rotor_speed\n\n      rotor_pos_b = np.matrix(self._rotor_params[i]['pos']).T\n      v_freestream = np.dot(\n          self._dcm_r2b[:, 0].T, v_rel_b + np.cross(omega_b.T, rotor_pos_b.T).T)\n      v_freestream *= (1.0 - self._rotor_params[i]['local_pressure_coeff'])**0.5\n\n      rotor_thrust = self._rotor_databases[i].CalcThrust(\n          rotor_speed, v_freestream[0, 0], self._air_density)\n      rotor_torque = direction * self._rotor_databases[i].CalcTorque(\n          rotor_speed, v_freestream[0, 0], self._air_density)\n\n      motor_force_b = self._dcm_r2b * np.matrix([[rotor_thrust], [0.0], [0.0]])\n\n      lever_arm_moment_b = np.cross(\n          rotor_pos_b.T, motor_force_b.T).T\n      aero_moment_b = self._dcm_r2b * np.matrix([[rotor_torque], [0.0], [0.0]])\n      gyro_moment_b = np.cross(\n          self._rotor_params[i]['I'] * rotor_velocity * self._dcm_r2b[:, 0].T,\n          omega_b.T).T\n\n      total_force += motor_force_b\n      total_moment += lever_arm_moment_b + aero_moment_b + gyro_moment_b\n\n    return ForceMomentPos(\n        total_force, total_moment, np.matrix(np.zeros((3, 1))))\n\n\nclass TetherForceModel(object):\n\n  # pylint: disable=unused-argument\n  def CalcBodyForce(self, dcm_g2b, wing_pos_g, wing_vel_g, wind_g):\n    raise NotImplementedError()\n\n\nclass ConstantTetherForceModel(TetherForceModel):\n  \"\"\"Simple model of tether force as constant in ground coordinates.\"\"\"\n\n  def __init__(self, force_g):\n    self.SetForce(force_g)\n\n  # pylint: disable=unused-argument\n  @type_util.RequireMatrixArguments(None, (3, 3), (3, 1), (3, 1), (3, 1))\n  def CalcBodyForce(self, dcm_g2b, wing_pos_g, wing_vel_g, wind_g):\n    \"\"\"Calculate the tether force in body coordinates.\n\n    Args:\n      dcm_g2b: DCM rotating ground to body coordinates (3-by-3 np.matrix).\n      wing_pos_g: Wing positon [m] in ground coordinates (unused\n          3-by-1 np.matrix).\n      wing_vel_g: Wing velocity [m/s] in ground coordinates (unused\n          3-by-1 np.matrix).\n      wind_g: Wind velocity [m/s] in ground coordinates (unused 3-by-1\n          np.matrix).\n\n    Returns:\n      A 3-by-1 np.matrix storing the tether force in body coordinates.\n    \"\"\"\n    return dcm_g2b * self._force_g\n\n  @type_util.RequireMatrixArguments(None, (3, 1))\n  def SetForce(self, force_g):\n    \"\"\"Update the force vector.\n\n    Args:\n      force_g: New tether force in ground coordinates.\n    \"\"\"\n    self._force_g = copy.copy(force_g)\n\n\nclass SimpleSpringTetherForceModel(TetherForceModel):\n  \"\"\"Model of tether force as a simple spring, including bridle interactions.\"\"\"\n\n  def __init__(self, spring_const, system_params):\n    tether_params = system_params['tether']\n    wing_params = system_params['wing']\n\n    self._spring_const = spring_const\n    self._tether_length = tether_params['length']\n    self._tether_drag_area = (0.25 * tether_params['section_drag_coeff']\n                              * tether_params['length']\n                              * tether_params['outer_diameter'])\n    self._air_density = system_params['phys']['rho']\n    self._bridle_pos = np.matrix(wing_params['bridle_pos']).T\n    self._bridle_y_offset = wing_params['bridle_y_offset']\n    self._bridle_radius = wing_params['bridle_rad']\n\n  # pylint: disable=unused-argument\n  @type_util.RequireMatrixArguments(None, (3, 3), (3, 1), (3, 1), (3, 1))\n  def CalcBodyForce(self, dcm_g2b, wing_pos_g, wing_vel_g, wind_g):\n    \"\"\"Calculate the tether force in body coordinates.\n\n    Args:\n      dcm_g2b: DCM rotating ground to body coordinates (3-by-3 np.matrix).\n      wing_pos_g: Wing positon [m] in ground coordinates (3-by-1 np.matrix).\n      wing_vel_g: Wing velocity [m/s] in ground coordinates (3-by-1 np.matrix).\n      wind_g: Wind velocity [m/s] in ground coordinates (3-by-1 np.matrix).\n\n    Returns:\n      A 3-by-1 np.matrix storing the tether force in body coordinates.\n    \"\"\"\n    # This intentionally ignores the small offset from the GSG\n    # position for simplicity.\n    bridle_knot_b = _CalcBridleKnotPos(dcm_g2b * -wing_pos_g,\n                                       self._bridle_pos,\n                                       self._bridle_y_offset,\n                                       self._bridle_radius)\n    bridle_knot_g = wing_pos_g + dcm_g2b.T * bridle_knot_b\n    tension = self._spring_const * (np.linalg.norm(bridle_knot_g)\n                                    - self._tether_length)\n    spring_force_g = -tension * bridle_knot_g / np.linalg.norm(bridle_knot_g)\n\n    airspeed = np.linalg.norm(wing_vel_g - wind_g)\n    drag = 0.5 * self._air_density * airspeed**2.0 * self._tether_drag_area\n    drag_force_g = drag * (wind_g - wing_vel_g) / max(airspeed, 0.1)\n    return dcm_g2b * (spring_force_g + drag_force_g)\n\n\nclass CatenaryTetherForceModel(TetherForceModel):\n  \"\"\"Model of tether force using catenary tension and rigid-rod drag.\"\"\"\n\n  def __init__(self, tether_params, gsg_pos_g, bridle_radius, g, air_density):\n    \"\"\"Create a catenary tether force model.\n\n    Args:\n      tether_params: TetherParams dictionary.\n      gsg_pos_g: Position [m] of the GSG in the g-frame.\n      bridle_radius: Bridle radius [m] of the kite.\n      g: Gravitational acceleration [m/s^2].\n      air_density: Air density [kg/m^3].\n    \"\"\"\n    self._gsg_pos_g = np.matrix(np.reshape(gsg_pos_g, (3, 1)))\n    self._length = tether_params['length'] + bridle_radius\n    self._weight = tether_params['length'] * tether_params['linear_density'] * g\n    self._section_drag_coeff = tether_params['section_drag_coeff']\n    self._outer_diameter = tether_params['outer_diameter']\n    self._air_density = air_density\n\n  # pylint: disable=unused-argument\n  @type_util.RequireMatrixArguments(None, (3, 3), (3, 1), (3, 1), (3, 1))\n  def CalcBodyForce(self, dcm_g2b, wing_pos_g, wing_vel_g, wind_g):\n    \"\"\"Calculate the tether force in body coordinates.\n\n    Args:\n      dcm_g2b: DCM rotating ground to body coordinates (3-by-3 np.matrix).\n      wing_pos_g: Wing positon [m] in ground coordinates (3-by-1 np.matrix).\n      wing_vel_g: Wing velocity [m/s] in ground coordinates (3-by-1 np.matrix).\n      wind_g: Wind velocity [m/s] in ground coordinates (unused 3-by-1\n          np.matrix).\n\n    Returns:\n      A 3-by-1 np.matrix storing the tether force in body coordinates.\n    \"\"\"\n    # Calculate catenary tension.\n    horizontal_distance = (wing_pos_g[0, 0]**2.0 + wing_pos_g[1, 0]**2.0)**0.5\n    vertical_distance = self._gsg_pos_g[2, 0] - wing_pos_g[2, 0]\n    (h, v) = catenary.DimensionlessTensionsFromPoint(\n        horizontal_distance / self._length,\n        vertical_distance / self._length)\n    azi = np.arctan2(wing_pos_g[1, 0], wing_pos_g[0, 0])\n    tension_g = self._weight * np.matrix(\n        [[-h * np.cos(azi)], [-h * np.sin(azi)], [v]])\n\n    # Calculate drag reaction force on the wing. This is calculated by modeling\n    # the tether as a rigid rod that is pinned at the GSG and rotating at fixed\n    # angular velocity.\n    #\n    # Let\n    #     CD  = cross-sectional drag coefficient\n    #     s   = diameter of the rod\n    #     L   = length of rod\n    #     V   = velocity of the free end of the rod\n    #     rho = air density\n    # The drag dD along a segment of the rod with length dx at distance x from\n    # the fixed end is\n    #     dD(x) = 1/2 * rho * v(x)^2 * CD * s * dx.\n    # Therefore,\n    #     dD/dx = 1/2 * rho * v(x)^2 * CD * s.\n    # The velocity of the segment is v(x) = x/L * V, so\n    #     dD/dx = 1/2 * rho * x^2 / L^2 * V^2 * CD * s\n    # From this, we obtain the differential moment about the fixed end:\n    #     dM/dx = x * dD/dx = 1/2 * rho * x^3 / L^2 * V^2 * CD * s.\n    # Integrating from x=0 to x=L yields the total moment due to drag,\n    #     M = 1/8 * rho * L^2 * V^2 * CD * s.\n    # Force at the fixed end induces no moment, so the drag moment must be\n    # entirely balanced by a reaction force at the free end (i.e. the kite).\n    # The magnitude of this force, R, is\n    #     R = M / L = 1/8 * rho * L * V^2 * CD * s.\n    #\n    # Here, we treat the rod as extending from the GSG to the body frame origin,\n    # and we use the wing velocity normal to the rod to determine V.\n    gsg_to_wing_g = wing_pos_g - self._gsg_pos_g\n    gsg_to_wing_dir_g = gsg_to_wing_g / np.linalg.norm(gsg_to_wing_g)\n\n    normal_vel_g = (wing_vel_g\n                    - float(wing_vel_g.T * gsg_to_wing_dir_g)\n                    * gsg_to_wing_dir_g)\n    normal_vel_mag = np.linalg.norm(normal_vel_g)\n    drag_direction_g = -normal_vel_g / normal_vel_mag\n    drag_g = (1.0 / 8.0 * self._air_density * np.linalg.norm(gsg_to_wing_g)\n              * normal_vel_mag**2.0 * self._section_drag_coeff\n              * self._outer_diameter * drag_direction_g)\n\n    return dcm_g2b * (tension_g + drag_g)\n\n\nclass SwigAeroModel(object):\n  \"\"\"Swig import of the simulator aerodynamics model.\"\"\"\n\n  def __init__(self):\n    self._aero = physics.Aero(physics.GetAeroSimParams())\n\n  @type_util.RequireMatrixArguments(None, None, None, None,\n                                    (system_types.kNumFlaps, 1), (3, 1),\n                                    None)\n  def CalcFMCoeff(self, alpha, beta, reynolds_number, flaps, omega_hat,\n                  thrust_coeff):\n    \"\"\"Calculates force and moment coefficients from the Swig database.\"\"\"\n    omega_hat_vec3 = physics.Vec3()\n    omega_hat_vec3.x = omega_hat[0, 0]\n    omega_hat_vec3.y = omega_hat[1, 0]\n    omega_hat_vec3.z = omega_hat[2, 0]\n    flaps_vec = physics.VecWrapper(system_types.kNumFlaps)\n    for i in range(system_types.kNumFlaps):\n      flaps_vec.SetValue(i, flaps[i, 0])\n    force_moment = physics.ForceMoment()\n    self._aero.CalcForceMomentCoeff(alpha, beta, omega_hat_vec3.this,\n                                    flaps_vec.GetVec(), reynolds_number,\n                                    force_moment.this, thrust_coeff)\n    force_moment_coeff = (np.matrix([[force_moment.force.x],\n                                     [force_moment.force.y],\n                                     [force_moment.force.z]]),\n                          np.matrix([[force_moment.moment.x],\n                                     [force_moment.moment.y],\n                                     [force_moment.moment.z]]))\n    return force_moment_coeff\n\n\nclass Wing(object):\n  \"\"\"Simplified model of the wing for control design.\n\n  The Wing class stores parameters defined by the environment (air\n  density, gravitational constant), a stateless tether force model,\n  a stateless aerodynamic model, and a nominal orientation.\n\n  It provides functions for calculating the ODEs that govern a 6-DOF\n  rigid body model.\n  \"\"\"\n\n  def __init__(self, system_params, sim_params, aero_model, motor_model,\n               tether_force_model):\n    \"\"\"Constructs a Wing model.\n\n    Args:\n      system_params: A system parameters structure from mconfig.\n      sim_params: A simulator parameters structure from mconfig.\n      aero_model: A Python class implementing a function CalcFMCoeff.  See\n          SwigAeroModel in this module as an example.\n      motor_model: A MotorModel.\n      tether_force_model: A TetherForceModel.\n    \"\"\"\n    self._wing_area = system_params['wing']['A']\n    self._wing_span = system_params['wing']['b']\n    self._wing_chord = system_params['wing']['c']\n    self._wing_mass = system_params['wing']['m']\n    self._wing_inertia_matrix = np.matrix(system_params['wing']['I']['d'])\n    self._pos_com_b = np.matrix(system_params['wing']['center_of_mass_pos']).T\n\n    # Bridle parameters.\n    self._bridle_pos = np.matrix(system_params['wing']['bridle_pos']).T\n    self._bridle_y_offset = system_params['wing']['bridle_y_offset']\n    self._bridle_radius = system_params['wing']['bridle_rad']\n\n    # Physics parameters.\n    self._g_g = np.matrix([[0.0], [0.0], [system_params['phys']['g']]])\n    self._air_density = system_params['phys']['rho']\n    self._dynamic_viscosity = sim_params['phys_sim']['dynamic_viscosity']\n\n    self._aero_model = aero_model\n    self._motor_model = motor_model\n    self._tether_force_model = tether_force_model\n\n  @type_util.RequireMatrixArguments(None, (3, 3))\n  def _CalcGravityForceMomentPos(self, dcm_g2b):\n    return ForceMomentPos(dcm_g2b * (self._wing_mass * self._g_g),\n                          np.matrix(np.zeros((3, 1))), self._pos_com_b)\n\n  @type_util.RequireMatrixArguments(None, None, None, None, (3, 1), (1, 1),\n                                    (3, 1))\n  def _CalcMotorForceMomentPos(self, v_rel, alpha, beta, omega_b,\n                               thrust, motor_moment):\n    \"\"\"Calculates the motor forces and moments.\"\"\"\n    return self._motor_model.CalcMotorForceMomentPos(\n        v_rel, alpha, beta, omega_b, thrust, motor_moment)\n\n  @type_util.RequireMatrixArguments(None, (3, 3), (3, 1), (3, 1), (3, 1))\n  def _CalcTetherForceMomentPos(self, dcm_g2b, wing_pos_g, wing_vel_g, wind_g):\n    tether_force_b = self._tether_force_model.CalcBodyForce(dcm_g2b, wing_pos_g,\n                                                            wing_vel_g, wind_g)\n    return ForceMomentPos(tether_force_b, np.matrix(np.zeros((3, 1))),\n                          _CalcBridleKnotPos(tether_force_b, self._bridle_pos,\n                                             self._bridle_y_offset,\n                                             self._bridle_radius))\n\n  def CalcTetherForceG(self, state, inputs):\n    return state.dcm_g2b.T * self._tether_force_model.CalcBodyForce(\n        state.dcm_g2b, state.wing_pos_g, state.wing_vel_g, inputs.wind_g)\n\n  def CalcTetherTensionRollPitch(self, state, inputs):\n    tether_force_b = self._tether_force_model.CalcBodyForce(\n        state.dcm_g2b, state.wing_pos_g, state.wing_vel_g, inputs.wind_g)\n    return geometry.TetherForceCartToSph(tether_force_b)\n\n  @type_util.RequireMatrixArguments(None, None, None, None, (3, 1),\n                                    (system_types.kNumFlaps, 1), None)\n  def CalcAeroForceMomentPos(self, v_rel, alpha, beta, omega_b, flaps,\n                             thrust_coeff):\n    \"\"\"Calculate the aerodynamic force and moments on the wing.\n\n    Args:\n      v_rel: Airspeed [m/s].\n      alpha: Angle-of-attack [rad].\n      beta: Angle-of-sideslip [rad].\n      omega_b: Wing body-rates [rad/s] (3-by-1 np.matrix).\n      flaps: Flap deflections (kNumFlaps-by-1 np.matrix).\n      thrust_coeff: Thrust coefficient [#] using wind turbine convention.\n\n    Returns:\n      (ForceMomentPos in body coordinates, force coeffs., moment coeffs.)\n    \"\"\"\n    reynolds_number = ((v_rel * self._wing_chord * self._air_density)\n                       / self._dynamic_viscosity)\n    dynamic_pressure = 0.5 * self._air_density * v_rel**2.0\n\n    length_scale = np.matrix([[self._wing_span],\n                              [self._wing_chord],\n                              [self._wing_span]])\n    omega_hat = np.multiply(omega_b, length_scale) / (2.0 * v_rel)\n    (cf, cm) = self._aero_model.CalcFMCoeff(alpha, beta, reynolds_number,\n                                            flaps, omega_hat, thrust_coeff)\n\n    return (ForceMomentPos(dynamic_pressure * self._wing_area * cf,\n                           (dynamic_pressure * self._wing_area\n                            * np.multiply(length_scale, cm)),\n                           np.matrix(np.zeros((3, 1)))),\n            cf, cm)\n\n  def _BodyForceMomentPosToComForceMoment(self, force_moment_pos_list):\n    force = np.matrix(np.zeros((3, 1)))\n    moment = np.matrix(np.zeros((3, 1)))\n    for force_moment_pos in force_moment_pos_list:\n      force += force_moment_pos.force\n      moment += force_moment_pos.moment\n      moment += np.cross(force_moment_pos.pos - self._pos_com_b,\n                         force_moment_pos.force, axis=0)\n    return ForceMoment(force, moment)\n\n  def CalcDeriv(self, state, inputs):\n    \"\"\"Calculates the derivative of the wing state vector.\n\n    Args:\n      state: A WingState.\n      inputs: A WingInputs.\n\n    Returns:\n      A WingState.Tangent containing the derivative of the state.\n    \"\"\"\n    euler_moment = np.cross(self._wing_inertia_matrix * state.omega_b,\n                            state.omega_b, axis=0)\n\n    v_rel, alpha, beta = state.CalcAerodynamicAngles(inputs.wind_g)\n\n    # Fixing total thrust coefficient to 0.0 for this application.\n    # NOTE: By accounting for the rotor wake effect on the tail,\n    # we found that the synthesized gains yield worse flight quality than when\n    # the effect is ignored (see b/110491871 for details).\n    thrust_coeff = 0.0\n    aero_force_moment_pos, _, _ = self.CalcAeroForceMomentPos(\n        v_rel, alpha, beta, state.omega_b, inputs.flaps, thrust_coeff)\n\n    force_moment_com = self._BodyForceMomentPosToComForceMoment([\n        self._CalcGravityForceMomentPos(state.dcm_g2b),\n        self._CalcMotorForceMomentPos(\n            v_rel, alpha, beta, state.omega_b, inputs.thrust,\n            inputs.motor_moment),\n        self._CalcTetherForceMomentPos(state.dcm_g2b, state.wing_pos_g,\n                                       state.wing_vel_g, inputs.wind_g),\n        aero_force_moment_pos,\n        ForceMomentPos(np.matrix(np.zeros((3, 1))), euler_moment,\n                       np.matrix(np.zeros((3, 1))))\n    ])\n\n    # Calculate center-of-mass acceleration.\n    accel_com_g = (state.dcm_g2b.T * force_moment_com.force) / self._wing_mass\n\n    # Calculate body angular acceleration.\n    omega_b_dot = np.matrix(np.linalg.solve(self._wing_inertia_matrix,\n                                            force_moment_com.moment))\n\n    wing_accel_g = accel_com_g - state.dcm_g2b.T * (\n        np.cross(state.omega_b,\n                 np.cross(state.omega_b, self._pos_com_b, axis=0), axis=0)\n        + np.cross(omega_b_dot, self._pos_com_b, axis=0))\n\n    return WingState.Tangent(domega_b=omega_b_dot, ddcm_g2b=state.omega_b,\n                             dwing_vel_g=wing_accel_g,\n                             dwing_pos_g=state.wing_vel_g)\n\n  def CalcDVbCom(self, state, state_dot):\n    \"\"\"Calculates the rate of change of Vb for unit tests.\"\"\"\n    return (state.dcm_g2b * state_dot.dwing_vel_g\n            - np.cross(state.omega_b, state.dcm_g2b * state.wing_vel_g, axis=0)\n            + np.cross(state_dot.domega_b, self._pos_com_b, axis=0))\n\n  def CalcEnergy(self, state):\n    \"\"\"Calculates energy of the rigid body model for unit tests.\"\"\"\n    wing_com_pos_g = state.wing_pos_g + state.dcm_g2b.T * self._pos_com_b\n    wing_com_vel_g = (state.wing_vel_g\n                      + (state.dcm_g2b.T\n                         * np.cross(state.omega_b, self._pos_com_b, axis=0)))\n    return ((0.5 * np.transpose(state.omega_b)\n             * self._wing_inertia_matrix * state.omega_b)\n            + (0.5 * self._wing_mass * np.transpose(wing_com_vel_g)\n               * wing_com_vel_g)\n            - self._wing_mass * np.transpose(self._g_g) * wing_com_pos_g)[0, 0]\n\n\ndef CalcLinearization(f, state, inputs, state_step_sizes, input_step_sizes):\n  \"\"\"Calculate the system matrices for the Wing model.\n\n  Produces a linearized model:\n\n    f(x + dx, u + du) ~ f(x) + A * dx + B * du\n\n  where f is an arbitrary function, x is the wing state and u are\n  the wing inputs.\n\n  Args:\n    f: A function mapping an n-by-1 np.matrix and an m-by-1 np.matrix to\n        a n-by-1 np.matrix.\n    state: An instance of a state class from type_util.\n    inputs: An instance of a named vector from type_util.\n    state_step_sizes: A vector of step sizes for the state.\n    input_step_sizes: A vector of step sizes for the inputs.\n\n  Returns:\n    A tuple (A, B) where A and B are both of type np.matrix.\n  \"\"\"\n  num_states = state.Tangent.GetDim()\n  num_inputs = inputs.GetDim()\n  num_outputs = f(state, inputs).shape[0]\n\n  dfdx = np.matrix(np.zeros((num_outputs, num_states)))\n  dfdu = np.matrix(np.zeros((num_outputs, num_inputs)))\n  for i in range(num_states):\n    h = state_step_sizes[i, 0]\n    e = state.Tangent.FromVector(np.matrix([\n        [1.0 if j == i else 0.0] for j in range(num_states)]))\n\n    dfdx[:, i] = (f(state.Increment(e, step=h), inputs)\n                  - f(state.Increment(e, step=-h), inputs)) / (2.0 * h)\n\n  for i in range(num_inputs):\n    h = input_step_sizes[i, 0]\n    e = np.matrix([[1.0 if j == i else 0.0] for j in range(num_inputs)])\n    dfdu[:, i] = (\n        f(state, inputs.FromVector(inputs.ToVector() + h * e))\n        - f(state, inputs.FromVector(inputs.ToVector() - h * e))) / (2.0 * h)\n\n  return (dfdx, dfdu)\n", "meta": {"hexsha": "5286751a8b9c851a5bcf3823508a7b079e480f30", "size": 28331, "ext": "py", "lang": "Python", "max_stars_repo_path": "analysis/control/dynamics.py", "max_stars_repo_name": "leozz37/makani", "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1178, "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_issues_repo_path": "analysis/control/dynamics.py", "max_issues_repo_name": "leozz37/makani", "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_forks_repo_path": "analysis/control/dynamics.py", "max_forks_repo_name": "leozz37/makani", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 107, "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "avg_line_length": 42.1592261905, "max_line_length": 80, "alphanum_fraction": 0.6498182203, "include": true, "reason": "import numpy", "num_tokens": 7610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.19248092514938}}
{"text": "\"\"\"\nadaptive.py\n\nfunctions relating to simulating an AO system with Proper\nmostly code copied from the original MEDIS from Rupert\n\nGenerally, the optical prescription will call the deformable_mirror function, which will compile all information and\nrun sequentially all functions related to creating the adaptive optic correction (main AO functionality, relating to\natmospheric and common-path aberrations) as well as using or not CDI probes, DM corrections or errors, etc\n\nTODO\n    Add astrogrid pattern functionality from MEDIS0\n\n\"\"\"\n\nimport numpy as np\nfrom scipy import interpolate, ndimage\nfrom inspect import getframeinfo, stack\nfrom skimage.restoration import unwrap_phase\nimport matplotlib.pylab as plt\nimport proper\nimport datetime\n\nfrom medis.params import sp, tp, ap\nfrom medis.CDI import cdi, config_probe\nfrom medis.optics import check_sampling\nfrom medis.utils import dprint\nfrom medis.plot_tools import quick2D\n\n\n################################################################################\n# Deformable Mirror\n################################################################################\ndef deformable_mirror(wf, WFS_map, iter, previous_output=None, apodize=False, plane_name='', debug=False):\n    \"\"\"\n    combine different DM actuator commands into single map to send to prop_dm\n\n    prop_dm needs an input map of n_actuators x n_actuators in units of actuator command height. quick_ao will handle\n    the conversion to actuator command height, and the CDI probe must be scaled in cdi.probe_amp in params in\n    units of m. Each subroutine is also responsible for creating a map of n_actuators x n_actuators spacing. prop_dm\n    handles the resampling of this map onto the wavefront, including the influence function. Its some wizardry that\n    happens in c, and presumably it is taken care of so you don't have to worry about it.\n\n    In the call to proper.prop_dm, we apply the flag tp.fit_dm, which switches between two 'modes' of proper's DM\n    surface fitting. If FALSE, the DM is driven to the heights specified by dm_map, and the influence function will\n    act on these heights to define the final surface shape applied to the DM, which may differ substantially from\n    the initial heights specified by dm_map. If TRUE, proper will iterate applying the influence function to the\n    input heights, and adjust the heights until the difference between the influenced-map and input map meets some\n    proper-defined convergence criterea. Setting tp.fit_dm=TRUE will obviously slow down the code, but will (likely)\n    more accurately represent a well-calibrated DM response function.\n\n    much of this code copied over from example from Proper manual on pg 94\n\n    :param wf: single wavefront\n    :param WFS_map: wavefront sensor map, should be in units of phase delay\n    :param previous_output:\n    :param iter: the current index of iteration (which timestep this is)\n    :param plane_name: name of plane (should be 'woofer' or 'tweeter' for best functionality)\n    :return: nothing is returned, but the probe map has been applied to the DM via proper.prop_dm. DM plane post DM\n        application can be saved via the sp.save_list functionality\n    \"\"\"\n    assert np.logical_xor(WFS_map is None, previous_output is None)\n\n    # AO Actuator Count from DM Type\n    if plane_name == 'tweeter' and hasattr(tp,'act_tweeter'):\n        nact = tp.act_tweeter\n    elif plane_name == 'woofer' and hasattr(tp,'act_woofer'):\n        nact = tp.act_woofer\n    else:\n        nact = tp.ao_act\n\n    # DM Coordinates\n    nact_across_pupil = nact - 2  # number of full DM actuators across pupil (oversizing DM extent)\n    dm_xc = (nact / 2)   # The location of the optical axis (center of the wavefront) on the DM in\n    dm_yc = (nact / 2)   # actuator units. First actuator is centered on (0.0, 0.0). The 0.5 is a\n    #  parameter introduced/tuned by Rupert to remove weird errors (address this).\n    # KD verified this needs to be here or else suffer weird errors 9/19\n    # TODO address/remove the 0.5 in DM x,y coordinates\n\n    ############################\n    # Creating DM Surface Map\n    ############################\n    d_beam = 2 * proper.prop_get_beamradius(wf)  # beam diameter\n    act_spacing = d_beam / nact_across_pupil  # actuator spacing [m]\n\n    #######\n    # AO\n    #######\n    if previous_output is not None and WFS_map is None:\n        dm_map = update_dm(previous_output)\n    else:\n        dm_map = quick_ao(wf, nact, WFS_map[wf.iw])\n\n    #########\n    # Waffle\n    #########\n    if tp.satelite_speck['apply'] and plane_name is not 'woofer':\n        waffle = make_speckle_kxy(tp.satelite_speck['xloc'], tp.satelite_speck['yloc'],\n                                  tp.satelite_speck['amp'], tp.satelite_speck['phase'])\n        waffle += make_speckle_kxy(tp.satelite_speck['xloc'], -tp.satelite_speck['yloc'],\n                                   tp.satelite_speck['amp'], tp.satelite_speck['phase'])\n        dm_map += waffle\n\n    #######\n    # CDI\n    ######\n    if cdi.use_cdi and plane_name == cdi.which_DM:\n        theta = cdi.phase_series[iter]\n        if not np.isnan(theta):\n            # dprint(f\"Applying CDI probe, lambda = {wfo.wsamples[iw]*1e9:.2f} nm\")\n            cdi.save_tseries(iter, datetime.datetime.now())\n            probe = config_probe(theta, nact, iw=wf.iw, ib=wf.ib, tstep=iter)\n            dm_map = dm_map + probe  # Add Probe to DM map\n\n    #########################\n    # Applying Piston Error\n    #########################\n    if tp.piston_error:\n        mean_dm_map = np.mean(np.abs(dm_map))\n        var = 1e-4  # 1e-11\n        dm_map = dm_map + np.random.normal(0, var, (dm_map.shape[0], dm_map.shape[1]))\n\n    #########################\n    # proper.prop_dm\n    #########################\n    dmap = proper.prop_dm(wf, dm_map, dm_xc, dm_yc, act_spacing, FIT=tp.fit_dm)  #\n\n    if debug and wf.iw == 0 and wf.ib == 0 and iter==0:\n        dprint(plane_name)\n        check_sampling(wf, iter, plane_name+' DM pupil plane', getframeinfo(stack()[0][0]), units='mm')\n\n        quick2D(WFS_map[wf.iw], title=f\"WFS map after masking\",\n                zlabel='unwrapped phase (rad)',\n                vlim=[-3 * np.pi, 3 * np.pi])\n\n        fig, ax = plt.subplots(1,1)\n        cax = ax.imshow(dm_map*1e9, interpolation='none', origin='lower')\n        plt.title(f'{plane_name} dm_map (actuator coordinates)')\n        cb = plt.colorbar(cax)\n        cb.set_label('nm')\n\n        plt.show()\n\n        post_ao = unwrap_phase(proper.prop_get_phase(wf)) * wf.lamda / (2 * np.pi)\n        # quick2D(pre_ao_dist*1e9, title='unwrapped wavefront before DM', zlabel='nm', show=False)  # , vlim=(-0.5e-7,0.5e-7))\n        # quick2D(np.abs(pre_ao_amp)**2, title='Pre-AO Intensity', show=False)#, vlim=(-0.5e-7,0.5e-7))\n        # quick2D(dmap, title='the phase map prop_dm is applying', zlabel='distance (m)', show=False)#, vlim=(-0.5e-7,0.5e-7))\n        # plt.figure()\n        # plt.plot(pre_ao_dist[len(pre_ao_dist)//2], label=f'pre_ao 1D cut, row {len(pre_ao_dist)//2}')\n        # plt.plot(2*dmap[len(dmap)//2], label=f'dmap 1D cut (x2), row {len(dmap)//2}')\n        # plt.plot((pre_ao_dist + (2*dmap))[len(dmap)//2], label='difference')\n        # plt.legend()\n        # plt.xlim(sp.grid_size//2*np.array([1-sp.beam_ratio*1.1, 1+sp.beam_ratio*1.1]))\n        # quick2D(pre_ao + (2*dmap), title='diff', zlabel='m', show=False, vlim=(-0.5e-7,0.5e-7))\n        # quick2D(post_ao, title='unwrapped wavefront after DM', zlabel='m', show=True, vlim=(-0.5e-7,0.5e-7))\n        # quick2D(np.abs(proper.prop_get_amplitude(wf))**2, title='wavefront after DM intensity', show=False)\n        # quick2D(proper.prop_get_phase(wf), title='wavefront after DM in phase units', zlabel='Phase',\n        #          show=True)  # colormap='sunlight',\n\n    if apodize:\n        hardmask_pupil(wf)\n\n    return dmap\n\n\n################################################################################\n# Ideal AO\n################################################################################\ndef quick_ao(wf, nact, WFS_map):\n    \"\"\"\n    calculate the offset map to send to the DM from the WFS map\n\n    The main idea is to apply the DM only to the region of the wavefront that contains the beam. The phase map from\n    the wfs saved the whole wavefront, so that must be cropped. During the wavefront initialization in\n    wavefront.initialize_proper, the beam ratio set in sp.beam_ratio is scaled per wavelength (to achieve constant\n    sampling sto create white light images), so the cropped value must also be scaled by wavelength. Note, beam ratio\n    is scaled differently depending on if sp.focused_sys is True or not. See params-->sp.focused_sys and Proper\n    manual pg 36 for more info.\n\n    Then, we interpolate the cropped beam onto a grid of (n_actuators,n_actuators), such that the DM can apply a\n    actuator height to each represented actuator, not a over or sub-sampled form. If the number of actuators is low\n    compared to the number of samples on the beam, you should anti-alias the WFS map via a lowpass filter before\n    interpolating. There is a discrepancy between the sampling of the wavefront at this location (the size you cropped)\n    vs the size of the DM. proper.prop_dm handles this, so just plug in the n_actuator sized DM map with specified\n    parameters, and assume that prop_dm handles the resampling correctly via the spacing or n_act_across_pupil flag.\n    FYI the resampling is done via a c library you installed/compiled when installing proper.\n\n    The WFS map is a map of real values in units of phase delay in radians. However, the AO map that gets passed to\n    proper.prop_dm wants input in nm height of each actuator. Therefore, you need to convert the phase delay to\n    a DM height. For the ideal AO, you would do this individually for each wavelength. However, for a 'real' AO system\n    you do this for the median wavelength. You also need to account for a factor of 2, since the DM is modeled as\n    a mirror so it travels the length of the phase delay twice.\n\n    much of this code copied over from example from Proper manual on pg 94\n\n    :param wfo: wavefront object created by optics.Wavefronts() [n_wavelengths, n_objects] of tp.gridsize x tp.gridsize\n    :param WFS_map: returned from quick_wfs (as of Aug 2019, its an idealized image)\n    :return: ao_map: map of DM actuator command heights in units of m\n    \"\"\"\n\n    nact_across_pupil = nact-2          # number of full DM actuators across pupil (oversizing DM extent)\n                                        # Note: oversample by 2 actuators hardcoded here, check if this is appropriate \n    \n    ############################\n    # Creating AO Surface Map\n    ############################\n    d_beam = 2 * proper.prop_get_beamradius(wf)  # beam diameter\n    act_spacing = d_beam / nact_across_pupil  # actuator spacing [m]\n\n    ###################################\n    # Cropping the Beam from WFS map\n    ###################################\n    # cropping here by beam_ratio rather than d_beam is valid since the beam size was initialized\n    #  using the scaled beam_ratios when the wfo was created\n    # crop should be -1,+1 on either side of the center because for an even sp.grid_size\n    ao_map = WFS_map[\n             sp.grid_size//2 - np.int_(wf.beam_ratio*sp.grid_size//2)-1:\n             sp.grid_size//2 + np.int_(wf.beam_ratio*sp.grid_size//2)+2,\n             sp.grid_size//2 - np.int_(wf.beam_ratio*sp.grid_size//2)-1:\n             sp.grid_size//2 + np.int_(wf.beam_ratio*sp.grid_size//2)+2]\n    # dprint(f\"WFS map coordinates are {sp.grid_size//2 - np.int_(wf.beam_ratio*sp.grid_size//2)-1},\"\n    #        f\"{sp.grid_size//2 + np.int_(wf.beam_ratio*sp.grid_size//2)+1}\")\n\n    ########################################################\n    # Interpolating the WFS map onto the actuator spacing\n    # (tp.nact,tp.nact)\n    ########################################################\n    # Lowpass Filter- prevents aliasing; uses Gaussian filter\n    nyquist_dm = nact/2 * act_spacing  # [m]\n    sigma = [nyquist_dm/2.355, nyquist_dm/2.355]  # assume we want sigma to be twice the HWHM\n    ao_map = ndimage.gaussian_filter(ao_map, sigma=sigma, mode='nearest')\n\n    f = interpolate.interp2d(range(ao_map.shape[0]), range(ao_map.shape[0]), ao_map, kind='cubic')\n    ao_map = f(np.linspace(0,ao_map.shape[0],nact), np.linspace(0,ao_map.shape[0], nact))\n    # map_spacing = proper.prop_get_sampling(wf)\n    # ao_map = proper.prop_magnify(ao_map, map_spacing / act_spacing, nact, QUICK=True)\n\n    ################################################\n    # Converting phase delay to DM actuator height\n    ################################################\n    # Apply the inverse of the WFS image to the DM, so use -dm_map (dm_map is in phase units, divide by k=2pi/lambda)\n    surf_height = proper.prop_get_wavelength(wf) / (4 * np.pi)  # [m/rad]\n    ao_map = -ao_map * surf_height  # Converts DM map to units of [m] of actuator heights\n\n    return ao_map\n\n\ndef retro_wfs(star_fields, wfo, plane_name='wfs'):\n    \"\"\"\n    Retrospective wfs (measure an old field)\n\n    :param star_fields:\n    :param wfo:\n    :param plane_name:\n    :return:\n    \"\"\"\n    WFS_map = np.zeros((len(star_fields), sp.grid_size, sp.grid_size))\n    from skimage.restoration import unwrap_phase\n    for iw in range(len(star_fields)):\n        quick2D(np.angle(star_fields), title='before mask', colormap='sunlight')\n        phasemap = np.angle(star_fields[iw])\n        masked_phase = np.ma.masked_equal(phasemap, 0)\n        quick2D(masked_phase, title='before unwrap', colormap='sunlight')\n        WFS_map[iw] = unwrap_phase(masked_phase, wrap_around=[False, False])\n        WFS_map[iw][phasemap == 0] = 0\n        quick2D(WFS_map[iw], title='after')\n    if 'retro_closed_wfs' in sp.save_list:\n        wfo.save_plane(location='WFS_map')\n\n    return WFS_map\n\n\ndef open_loop_wfs(wfo, plane_name='wfs'):\n    \"\"\"\n    saves the unwrapped phase [arctan2(imag/real)] of the wfo.wf_collection at each wavelength\n\n    It is an idealized image (exact copy) of the wavefront phase per wavelength. Only the map for the first object\n    (the star) is saved. We have initialized\n\n    Here we hardmask on the WFS map to be a circle around the beam in the pupil plane. This hard masking prevents the\n     DM from acting on non-beam signal, since the DM modelled by proper is a nxn square array, but the beam is nominally\n     circular for circular apertures.\n\n    #TODO the way this is saved for naming the WFS_map is going to break if you want to do closed loop WFS on a\n    #TODO woofer-tweeter system\n\n    :param wfo: wavefront object\n    :param plane_name: name of the plane to enable or disable saving the WFS map\n    :return: array containing only the unwrapped phase delay of the wavefront; shape=[n_wavelengths], units=radians\n    \"\"\"\n    star_wf = wfo.wf_collection[:, 0]\n    WFS_map = np.zeros((len(star_wf), sp.grid_size, sp.grid_size))\n\n    for iw in range(len(star_wf)):  # for each wavelength\n        hardmask_pupil(star_wf[iw])\n        phasemap = proper.prop_get_phase(star_wf[iw])\n        WFS_map[iw] = unwrap_phase(phasemap, wrap_around=[False, False])\n        WFS_map[iw][phasemap==0] = 0 #TODO is this still necessary?\n\n        # if sp.verbose:\n        #     quick2D(WFS_map[iw], title=f\"WFS map after masking, lambda={wfo.wsamples[iw]*1e9:.2f}\",\n        #             zlabel='unwrapped phase (rad)',\n        #             vlim=[-3*np.pi, 3*np.pi])\n        #\n\n    if 'WFS' in sp.save_list or sp.closed_loop:\n        wfo.save_plane(location='WFS')\n\n    return WFS_map\n\n\ndef hardmask_pupil(wf):\n    \"\"\"\n    hard-edged circular mask of the pupil plane.\n\n    Masks out the WFS map outside of the beam since the DM modeled by proper can only be a square nxn grid of actuators,\n    and thus the influence function surrounding each DM actuator could  be affecting on-beam pixels, even if the\n    actuator is acting on off-beam signal. In other words, even if a cornerDM actuator doesn't actuate on the beam,\n    if there was non-zero signal in the WFS map, it will try to act on it, and it could 'influence' nearby DM actuators\n    that are acting on the beam.\n\n    This hard-edged mask is different from prop_circular_aperture in that it does not anti-alias the edges of the mask\n    based on the 'fill factor' of the edge pixels. Instead, it has a boolean mask to zero everything > a fixed radius,\n    in this case determined by the grid size and beam ratio of each wavefront passed into it.\n\n    :param wf: a single wavefront\n    :return: nothing is returned but the wf passed into it has been masked\n\n    \"\"\"\n    phase_map = proper.prop_get_phase(wf)\n    amp_map = proper.prop_get_amplitude(wf)\n\n    # Sizing the Mask\n    h, w = wf.wfarr.shape[:2]\n    center = (int(w / 2), int(h / 2))\n    radius = np.floor(sp.grid_size * wf.beam_ratio / 2)  # Should scale with wavelength if sp.focused_system=False,\n                                                        # np.ceil used to oversize map so don't clip the beam\n    # Making the Circular Boolean Mask\n    Y, X = np.mgrid[:h, :w]\n    dist_from_center = np.sqrt((X - center[0]) ** 2 + (Y - center[1]) ** 2)\n    inds = dist_from_center <= radius\n\n    # Applying the Mask to the Complex Array\n    mask = np.zeros_like(phase_map)\n    mask[inds] = 1\n    masked = phase_map * mask\n    wf.wfarr = proper.prop_shift_center(amp_map * np.cos(masked) + 1j * amp_map * np.sin(masked))\n\n    # if sp.verbose:\n    #     dprint(f\"Radius of hard-edge pupil mask is {radius} pixels\")\n    #     quick2D(masked, title=f\"Masked phase map in hardmask_pupil, lambda={wf.lamda*1e9} nm\", zlabel='phase (rad)')\n    #     plt.show()\n\n\ndef make_speckle_kxy(kx, ky, amp, dm_phase):\n    \"\"\"given an kx and ky wavevector,\n    generates a NxN flatmap that has\n    a speckle at that position\"\"\"\n    N = tp.ao_act\n    dmx, dmy   = np.meshgrid(\n                    np.linspace(-0.5, 0.5, N),\n                    np.linspace(-0.5, 0.5, N))\n\n    xm=dmx*kx*2.0*np.pi\n    ym=dmy*ky*2.0*np.pi\n    # print 'DM phase', dm_phase\n    ret = amp*np.cos(xm + ym +  dm_phase)\n    return ret\n\n\n# def ao(wf, WFS_map, theta):\n#     if sp.closed_loop:\n#         deformable_mirror(wf, WFS_map, theta)\n#     else:\n#         WFS_map = open_loop_wfs(wf)  # overwrite WFS_map\n#         # dprint(f\"WFS_ma.shape = {WFS_map.shape}\")\n#         deformable_mirror(wf, WFS_map, theta)\n#\n################################################################################\n# Full AO\n################################################################################\n# not implemented. Full AO implies a time delay, and maybe non-ideal WFS\n", "meta": {"hexsha": "c410b2ae01f468257a5ebd205edceea3603f59f4", "size": 18590, "ext": "py", "lang": "Python", "max_stars_repo_path": "medis/adaptive.py", "max_stars_repo_name": "jessmos/MEDIS", "max_stars_repo_head_hexsha": "eeea1904d31878fb3ad6444af144ee6f1d3ab705", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "medis/adaptive.py", "max_issues_repo_name": "jessmos/MEDIS", "max_issues_repo_head_hexsha": "eeea1904d31878fb3ad6444af144ee6f1d3ab705", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "medis/adaptive.py", "max_forks_repo_name": "jessmos/MEDIS", "max_forks_repo_head_hexsha": "eeea1904d31878fb3ad6444af144ee6f1d3ab705", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.5378590078, "max_line_length": 126, "alphanum_fraction": 0.6445938677, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.19233999260145246}}
{"text": "#! /usr/bin/env python\n\n# Eureka! Stage 3 reduction pipeline\n\n# Proposed Steps\n# --------------\n# 1.  Read in all data frames and header info from Stage 2 data products DONE\n# 2.  Record JD and other relevant header information DONE\n# 3.  Apply light-time correction (if necessary) DONE\n# 4.  Calculate trace and 1D+2D wavelength solutions (if necessary)\n# 5.  Make flats, apply flat field correction (Stage 2)\n# 6.  Manually mask regions DONE\n# 7.  Compute difference frames OR slopes (Stage 1)\n# 8.  Perform outlier rejection of BG region DONE\n# 9.  Background subtraction DONE\n# 10. Compute 2D drift, apply rough (integer-pixel) correction\n# 11. Full-frame outlier rejection for time-series stack of NDRs\n# 12. Apply sub-pixel 2D drift correction\n# 13. Extract spectrum through summation DONE\n# 14. Compute median frame DONE\n# 15. Optimal spectral extraction DONE\n# 16. Save Stage 3 data products\n# 17. Produce plots DONE\n\n\nimport os, time, glob\nimport numpy as np\nfrom astropy.io import fits\nfrom tqdm import tqdm\nfrom . import optspex\nfrom . import plots_s3, source_pos\nfrom . import background as bg\nfrom . import bright2flux as b2f\nfrom ..lib import sort_nicely as sn\nfrom ..lib import logedit\nfrom ..lib import readECF as rd\nfrom ..lib import manageevent as me\nfrom ..lib import astropytable\nfrom ..lib import util\n\n\nclass MetaClass:\n    '''A class to hold Eureka! metadata.\n    '''\n\n    def __init__(self):\n        return\n\n\nclass DataClass:\n    '''A class to hold Eureka! image data.\n    '''\n\n    def __init__(self):\n        return\n\n\ndef reduceJWST(eventlabel, s2_meta=None):\n    '''Reduces data images and calculates optimal spectra.\n\n    Parameters\n    ----------\n    eventlabel: str\n        The unique identifier for these data.\n    s2_meta:    MetaClass\n        The metadata object from Eureka!'s S2 step (if running S2 and S3 sequentially).\n\n    Returns\n    -------\n    meta:   MetaClass\n        The metadata object with attributes added by S3.\n\n    Notes\n    -------\n    History:\n\n    - May 2021 Kevin Stevenson\n        Initial version\n    - October 2021 Taylor Bell\n        Updated to allow for inputs from S2\n    '''\n\n    # Initialize data object\n    data = DataClass()\n\n    # Initialize a new metadata object\n    meta = MetaClass()\n    meta.eventlabel = eventlabel\n\n    # Load Eureka! control file and store values in Event object\n    ecffile = 'S3_' + eventlabel + '.ecf'\n    ecf = rd.read_ecf(ecffile)\n    rd.store_ecf(meta, ecf)\n    meta.eventlabel=eventlabel\n    \n    # S3 is not being called right after S2 - try to load a metadata in case S2 was previously run\n    if s2_meta == None:\n        # Search for the S2 output metadata in the inputdir provided in\n        rootdir = os.path.join(meta.topdir, *meta.inputdir.split(os.sep))\n        if rootdir[-1]!='/':\n            rootdir += '/'\n        fnames = glob.glob(rootdir+'**/S2_'+meta.eventlabel+'_Meta_Save.dat', recursive=True)\n        fnames = sn.sort_nicely(fnames)\n\n        if len(fnames)==0:\n            # There may be no metafiles in the inputdir - raise an error and give a helpful message\n            print('WARNING: Unable to find an output metadata file from Eureka!\\'s S2 step '\n                 +'in the inputdir: \\n\"{}\"!\\n'.format(meta.inputdir)\n                 +'Assuming this S2 data was produced by the JWST pipeline instead.')\n        else:\n            if len(fnames)>1:\n                # There may be multiple runs - use the most recent but warn the user\n                print('WARNING: There are multiple metadata save files in your inputdir: \\n\"{}\"\\n'.format(meta.inputdir)\n                     +'Using the metadata file: \\n\"{}\"'.format(fnames[-1]))\n\n            fname = fnames[-1] # Pick the last file name\n            fname = fname[:-4] # Strip off the .dat ending\n\n            s2_meta = me.loadevent(fname)\n\n    # Locate the exact output folder from the previous S2 run (since there is a procedurally generated subdirectory for each run)\n    if s2_meta != None:\n        # Need to remove the topdir from the outputdir\n        if os.path.isdir(s2_meta.outputdir):\n            s2_outputdir = s2_meta.outputdir[len(s2_meta.topdir):]\n            if s2_outputdir[0]=='/':\n                s2_outputdir = s2_outputdir[1:]\n\n            meta = s2_meta\n\n            # Load Eureka! control file and store values in the S2 metadata object\n            ecffile = 'S3_' + eventlabel + '.ecf'\n            ecf = rd.read_ecf(ecffile)\n            rd.store_ecf(meta, ecf)\n\n            # Overwrite the inputdir with the exact output directory from S2\n            meta.inputdir = s2_outputdir\n        else:\n            raise AssertionError(\"Unable to find output data files from Eureka!'s S2 step! \"\n                                 + \"Looked in the folder: \\n{}\".format(s2_meta.outputdir))\n\n    meta.inputdir_raw = meta.inputdir\n    meta.outputdir_raw = meta.outputdir\n\n    # check for range of spectral apertures\n    if isinstance(meta.spec_hw, list):\n        meta.spec_hw_range = range(meta.spec_hw[0], meta.spec_hw[1]+meta.spec_hw[2], meta.spec_hw[2])\n    else:\n        meta.spec_hw_range = [meta.spec_hw]\n\n    #check for range of background apertures\n    if isinstance(meta.bg_hw, list):\n        meta.bg_hw_range = range(meta.bg_hw[0], meta.bg_hw[1]+meta.spec_hw[2], meta.bg_hw[2])\n    else:\n        meta.bg_hw_range = [meta.bg_hw]\n\n    # create directories to store data\n    meta.runs = [] # Used to make sure we're always looking at the right run for each aperture/annulus pair\n    for spec_hw_val in meta.spec_hw_range:\n\n        for bg_hw_val in meta.bg_hw_range:\n\n            meta.eventlabel = eventlabel\n\n            meta.runs.append(util.makedirectory(meta, 'S3', ap=spec_hw_val, bg=bg_hw_val))\n\n    # begin process\n    run_i = 0\n    for spec_hw_val in meta.spec_hw_range:\n\n        for bg_hw_val in meta.bg_hw_range:\n\n            t0 = time.time()\n\n            meta.spec_hw = spec_hw_val\n\n            meta.bg_hw = bg_hw_val\n\n            meta.outputdir = util.pathdirectory(meta, 'S3', meta.runs[run_i], ap=spec_hw_val, bg=bg_hw_val)\n            run_i += 1\n\n            event_ap_bg = meta.eventlabel + \"_ap\" + str(spec_hw_val) + '_bg' + str(bg_hw_val)\n\n            # Open new log file\n            meta.logname = meta.outputdir + 'S3_' + event_ap_bg + \".log\"\n            log = logedit.Logedit(meta.logname)\n            log.writelog(\"\\nStarting Stage 3 Reduction\\n\")\n            log.writelog(f\"Input directory: {meta.inputdir}\")\n            log.writelog(f\"Output directory: {meta.outputdir}\")\n            log.writelog(\"Using ap=\" + str(spec_hw_val) + \", bg=\" + str(bg_hw_val))\n\n            # Copy ecf (and update inputdir in case S3 is being called sequentially with S2)\n            log.writelog('Copying S3 control file')\n            new_ecfname = meta.outputdir + ecffile.split('/')[-1]\n            with open(new_ecfname, 'w') as new_file:\n                with open(ecffile, 'r') as file:\n                    for line in file.readlines():\n                        if len(line.strip())==0 or line.strip()[0]=='#':\n                            new_file.write(line)\n                        else:\n                            line_segs = line.strip().split()\n                            if line_segs[0]=='inputdir':\n                                new_file.write(line_segs[0]+'\\t\\t/'+meta.inputdir+'\\t'+' '.join(line_segs[2:])+'\\n')\n                            else:\n                                new_file.write(line)\n\n            # Create list of file segments\n            meta = util.readfiles(meta)\n            num_data_files = len(meta.segment_list)\n            if num_data_files==0:\n                rootdir = os.path.join(meta.topdir, *meta.inputdir.split(os.sep))\n                if rootdir[-1]!='/':\n                    rootdir += '/'\n                raise AssertionError(f'Unable to find any \"{meta.suffix}.fits\" files in the inputdir: \\n\"{rootdir}\"!')\n            else:\n                log.writelog(f'\\nFound {num_data_files} data file(s) ending in {meta.suffix}.fits')\n\n            with fits.open(meta.segment_list[-1]) as hdulist:\n                # Figure out which instrument we are using\n                meta.inst = hdulist[0].header['INSTRUME'].lower()\n            # Load instrument module\n            if meta.inst == 'miri':\n                from . import miri as inst\n            elif meta.inst == 'nircam':\n                from . import nircam as inst\n            elif meta.inst == 'nirspec':\n                from . import nirspec as inst\n            elif meta.inst == 'niriss':\n                raise ValueError('NIRISS observations are currently unsupported!')\n            else:\n                raise ValueError('Unknown instrument {}'.format(meta.inst))\n\n            stdspec = np.array([])\n            # Loop over each segment\n            # Only reduce the last segment/file if testing_S3 is set to True in ecf\n            if meta.testing_S3:\n                istart = num_data_files - 1\n            else:\n                istart = 0\n            for m in range(istart, num_data_files):\n                # Keep track if this is the first file - otherwise MIRI will keep swapping x and y windows\n                if m==istart:\n                    meta.firstFile = True\n                else:\n                    meta.firstFile = False\n                # Report progress\n                log.writelog(f'Reading file {m + 1} of {num_data_files}')\n                # Read in data frame and header\n                data, meta = inst.read(meta.segment_list[m], data, meta)\n                # Get number of integrations and frame dimensions\n                meta.n_int, meta.ny, meta.nx = data.data.shape\n                if meta.testing_S3:\n                    # Only process the last 5 integrations when testing\n                    meta.int_start = np.max((0,meta.n_int-5))\n                else:\n                    meta.int_start = 0\n                # Locate source postion\n                meta.src_ypos = source_pos.source_pos(data, meta, m, header=('SRCYPOS' in data.shdr))\n                log.writelog(f'  Source position on detector is row {meta.src_ypos}.')\n                # Trim data to subarray region of interest\n                data, meta = util.trim(data, meta)\n                # Create bad pixel mask (1 = good, 0 = bad)\n                # FINDME: Will want to use DQ array in the future to flag certain pixels\n                data.submask = np.ones(data.subdata.shape)\n\n                # Convert flux units to electrons (eg. MJy/sr -> DN -> Electrons)\n                data, meta = b2f.convert_to_e(data, meta, log)\n\n                # Check if arrays have NaNs\n                data.submask = util.check_nans(data.subdata, data.submask, log, name='SUBDATA')\n                data.submask = util.check_nans(data.suberr, data.submask, log, name='SUBERR')\n                data.submask = util.check_nans(data.subv0, data.submask, log, name='SUBV0')\n\n                # Manually mask regions [colstart, colend, rowstart, rowend]\n                if hasattr(meta, 'manmask'):\n                    log.writelog(\"  Masking manually identified bad pixels\")\n                    for i in range(len(meta.manmask)):\n                        ind, colstart, colend, rowstart, rowend = meta.manmask[i]\n                        data.submask[rowstart:rowend, colstart:colend] = 0\n\n                # Perform outlier rejection of sky background along time axis\n                log.writelog('  Performing background outlier rejection')\n                meta.bg_y2 = int(meta.src_ypos + bg_hw_val)\n                meta.bg_y1 = int(meta.src_ypos - bg_hw_val)\n                data = inst.flag_bg(data, meta)\n\n                data = bg.BGsubtraction(data, meta, log, meta.isplots_S3)\n\n                # Calulate drift2D\n                # print(\"Calculating 2D drift...\")\n\n                # print(\"Performing rough, pixel-scale drift correction...\")\n\n                # Outlier rejection of full frame along time axis\n                # print(\"Performing full-frame outlier rejection...\")\n\n                if meta.isplots_S3 >= 3:\n                    log.writelog('  Creating figures for background subtraction')\n                    for n in tqdm(range(meta.int_start,meta.n_int)):\n                        # make image+background plots\n                        plots_s3.image_and_background(data, meta, n)\n\n                # print(\"Performing sub-pixel drift correction...\")\n\n                # Select only aperture region\n                ap_y1 = int(meta.src_ypos - spec_hw_val)\n                ap_y2 = int(meta.src_ypos + spec_hw_val)\n                data.apdata  = data.subdata[:, ap_y1:ap_y2]\n                data.aperr   = data.suberr[:, ap_y1:ap_y2]\n                data.apmask  = data.submask[:, ap_y1:ap_y2]\n                data.apbg    = data.subbg[:, ap_y1:ap_y2]\n                data.apv0    = data.subv0[:, ap_y1:ap_y2]\n                # Extract standard spectrum and its variance\n                data.stdspec = np.sum(data.apdata, axis=1)\n                data.stdvar  = np.sum(data.aperr ** 2, axis=1)  # FINDME: stdvar >> stdspec, which is a problem\n                # Compute fraction of masked pixels within regular spectral extraction window\n                # numpixels   = 2.*meta.spec_width*subnx\n                # fracMaskReg = (numpixels - np.sum(apmask,axis=(2,3)))/numpixels\n\n                # Compute median frame\n                data.medsubdata = np.median(data.subdata, axis=0)\n                data.medapdata  = np.median(data.apdata, axis=0)\n\n                # Extract optimal spectrum with uncertainties\n                log.writelog(\"  Performing optimal spectral extraction\")\n                data.optspec = np.zeros(data.stdspec.shape)\n                data.opterr  = np.zeros(data.stdspec.shape)\n                gain = 1  # Already converted DN to electrons, so gain = 1 for optspex\n                for n in tqdm(range(meta.int_start,meta.n_int)):\n                    data.optspec[n], data.opterr[n], mask = optspex.optimize(data.apdata[n], data.apmask[n], data.apbg[n],\n                                                                             data.stdspec[n], gain, data.apv0[n],\n                                                                             p5thresh=meta.p5thresh, p7thresh=meta.p7thresh,\n                                                                             fittype=meta.fittype, window_len=meta.window_len,\n                                                                             deg=meta.prof_deg, n=data.intstart + n,\n                                                                             isplots=meta.isplots_S3, eventdir=meta.outputdir,\n                                                                             meddata=data.medapdata, hide_plots=meta.hide_plots)\n\n                # Plot results\n                if meta.isplots_S3 >= 3:\n                    log.writelog('  Creating figures for optimal spectral extraction')\n                    for n in tqdm(range(meta.int_start,meta.n_int)):\n                        # make optimal spectrum plot\n                        plots_s3.optimal_spectrum(data, meta, n)\n\n                # Append results\n                if len(stdspec) == 0:\n                    wave_2d = data.subwave\n                    wave_1d = data.subwave[meta.src_ypos]\n                    stdspec = data.stdspec\n                    stdvar  = data.stdvar\n                    optspec = data.optspec\n                    opterr  = data.opterr\n                    bjdtdb  = data.bjdtdb\n                else:\n                    stdspec = np.append(stdspec, data.stdspec, axis=0)\n                    stdvar  = np.append(stdvar, data.stdvar, axis=0)\n                    optspec = np.append(optspec, data.optspec, axis=0)\n                    opterr  = np.append(opterr, data.opterr, axis=0)\n                    bjdtdb  = np.append(bjdtdb, data.bjdtdb, axis=0)\n\n            # Calculate total time\n            total = (time.time() - t0) / 60.\n            log.writelog('\\nTotal time (min): ' + str(np.round(total, 2)))\n\n            if meta.testing_S3 == False:\n                log.writelog('Saving results as astropy table')\n                meta.tab_filename = meta.outputdir + 'S3_' + event_ap_bg + \"_Table_Save.txt\"\n                astropytable.savetable_S3(meta.tab_filename, bjdtdb, wave_1d, stdspec, stdvar, optspec, opterr)\n\n            if meta.isplots_S3 >= 1:\n                log.writelog('Generating figure')\n                # 2D light curve without drift correction\n                plots_s3.lc_nodriftcorr(meta, wave_1d, optspec)\n\n            # Save results\n            if meta.testing_S3 == False:\n                log.writelog('Saving Metadata')\n                me.saveevent(meta, meta.outputdir + 'S3_' + event_ap_bg + \"_Meta_Save\", save=[])\n\n            log.closelog()\n\n    return meta\n", "meta": {"hexsha": "b971415f54fe2aa56d79034d9abc4995f9208026", "size": 16732, "ext": "py", "lang": "Python", "max_stars_repo_path": "eureka/S3_data_reduction/s3_reduce.py", "max_stars_repo_name": "evamariaa/Eureka", "max_stars_repo_head_hexsha": "a3e739a528fbe85ec588bca996188765649b7778", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2020-08-07T12:12:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T10:20:38.000Z", "max_issues_repo_path": "eureka/S3_data_reduction/s3_reduce.py", "max_issues_repo_name": "evamariaa/Eureka", "max_issues_repo_head_hexsha": "a3e739a528fbe85ec588bca996188765649b7778", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 159, "max_issues_repo_issues_event_min_datetime": "2020-08-05T14:34:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:02:10.000Z", "max_forks_repo_path": "eureka/S3_data_reduction/s3_reduce.py", "max_forks_repo_name": "evamariaa/Eureka", "max_forks_repo_head_hexsha": "a3e739a528fbe85ec588bca996188765649b7778", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2021-06-16T09:40:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T18:28:07.000Z", "avg_line_length": 43.6866840731, "max_line_length": 129, "alphanum_fraction": 0.5622161128, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 3892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.19233998538149175}}
{"text": "\"\"\"The Mine class.\"\"\"\n\n__docformat__ = \"reStructuredText\"\n\nfrom functools import reduce\nfrom typing import List, Dict, Optional, Union, Callable, Tuple\nfrom abc import ABC, abstractmethod\nfrom collections import defaultdict\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport networkx as nx\nfrom prettytable import PrettyTable\nfrom qiskit.opflow import PauliOp, I, Z, Plus, MatrixOp\nfrom qiskit.algorithms import (\n    MinimumEigensolver,\n    AlgorithmResult,\n    NumPyMinimumEigensolver,\n)\n\nfrom ..algorithms import Pseudoflow, PEPSITE\nfrom ..benchmark import Benchmark\nfrom ..utils import null_operator, z_projector, single_qubit_pauli, int_to_bitstr\n\n\nclass BaseMine(ABC):\n    \"\"\"\n    Abstract Mine class\n    \"\"\"\n\n    def __init__(self) -> None:\n        pass\n\n    @abstractmethod\n    def solve(self) -> \"MiningProblemResult\":\n        raise NotImplementedError()\n\n\nclass Mine(BaseMine):\n    \"\"\"This class stores the mine configurations.\"\"\"\n\n    def __init__(self, mine_config: Union[str, np.ndarray]) -> None:\n        \"\"\"Initialize the Mine class.\n\n        Parameters\n        ----------\n        mine_config : str\n            Path to the mine configuration file.\n\n        Raises\n        ------\n        IOError\n            Invalid path to the mine configuration file.\n\n        \"\"\"\n        if isinstance(mine_config, str):\n            try:\n                self.dat = np.loadtxt(mine_config, dtype=float)\n            except:\n                raise IOError(\"Invalid Mine Configuration File\")\n        elif isinstance(mine_config, np.ndarray):\n            if len(mine_config.shape) != 2:\n                raise ValueError(\"`mine_config` must be two-demensional\")\n            self.dat = np.array(mine_config, dtype=float)\n        else:\n            raise ValueError(\"Unrecognized `mine_config` type\")\n\n        self.rows, self.cols = self.dat.shape\n        self.graph = defaultdict(list)  # p:c\n        self.graph_r = defaultdict(list)  # c:p\n        self.idx2cord = []\n        self.cord2idx = {}\n        self._init_mapping()\n        self.nqubits: int = len(self.idx2cord)\n        self.valid_configs = None\n        self._Hs = None\n        self._Hp = None\n\n    @property\n    def Hs(self) -> float:\n        if self._Hs is None:\n            self._Hs = self.gen_Hs()\n        return self._Hs\n\n    @property\n    def Hp(self) -> float:\n        if self._Hp is None:\n            self._Hp = self.gen_Hp()\n        return self._Hp\n\n    @staticmethod\n    def gen_random_mine(\n        size: Tuple[int, int], distribution: Optional[str] = \"normal\", seed: Optional[int] = None, **kwargs\n    ) -> \"Mine\":\n        distribution = distribution.lower()\n        rng = np.random.default_rng(seed)\n        if distribution == \"gaussian\" or distribution == \"normal\":\n            return Mine(rng.normal(size=size, **kwargs))\n        if distribution == \"uniform\":\n            return Mine(rng.uniform(size=size, **kwargs))\n        raise ValueError(\"Distribution not supported.\")\n\n    def _init_mapping(self) -> None:\n        \"\"\"Assign a unique id to each valid node and store the graph structure with ``self.graph``.\"\"\"\n        for r in range(self.rows):\n            for c in range(self.cols):\n                if c < r or c > self.cols - r - 1:\n                    self.dat[r, c] = float(\"inf\")\n                if self.dat[r, c] < float(\"inf\"):\n                    self.idx2cord.append((r, c))\n                    self.cord2idx[(r, c)] = len(self.idx2cord) - 1\n                    idx = self.cord2idx[(r, c)]\n                    for pr, pc in [(r - 1, c - 1), (r - 1, c), (r - 1, c + 1)]:\n                        if (\n                            0 <= pr < self.rows\n                            and 0 <= pc < self.cols\n                            and self.dat[pr, pc] < float(\"inf\")\n                        ):\n                            self.graph[idx].append(self.cord2idx[(pr, pc)])\n                            self.graph_r[self.cord2idx[(pr, pc)]].append(idx)\n\n    def plot_mine(self) -> None:\n        \"\"\"Plot the mine configuration.\"\"\"\n        x = PrettyTable([\" \"] + [str(ic) for ic in range(self.cols)])\n        for ir in range(self.rows):\n            x.add_row([ir] + [\"%.3f\" % self.dat[ir, ic] for ic in range(self.cols)])\n        print(str(x))\n\n    def plot_mine_graph(\n        self, color: str = \"r\", pos_func: Callable = nx.spring_layout\n    ) -> None:\n        \"\"\"Plot a graph representing the mine configuration.\n\n        Parameters\n        ----------\n        color : str\n            Color of the nodes.\n        pos_func : Callable\n            A Callable that returns positions of nodes.\n\n        \"\"\"\n        G = nx.Graph()\n        G.add_nodes_from(np.arange(self.nqubits))\n        elist = [[i, j] for i, jl in self.graph.items() for j in jl]\n        # tuple is (i,j,weight) where (i,j) is the edge\n        G.add_edges_from(elist)\n\n        colors = [color for node in G.nodes()]\n        pos = pos_func(G)\n\n        default_axes = plt.axes(frameon=True)\n        nx.draw_networkx(\n            G, node_color=colors, node_size=600, alpha=0.8, ax=default_axes, pos=pos\n        )\n\n    def gen_Hs(self) -> PauliOp:\n        \"\"\"Generate the smoothess Hamiltonian\n        :math:`H_{s}=\\sum_{i}\\sum_{j:Parent(i)} (1-Z_{i})/2*(1+Z_{j})/2`\n\n        Returns\n        ----------\n        qiskit.opflow.PauliOp\n            Smoothness Hamiltonian.\n\n        \"\"\"\n        Hs = 0 * I ^ self.nqubits\n        for i in range(self.nqubits):\n            for j in self.graph[i]:\n                Hs += (\n                    (I ^ self.nqubits) - ((I ^ self.nqubits - i - 1) ^ Z ^ (I ^ i))\n                ) @ ((I ^ self.nqubits) + ((I ^ self.nqubits - j - 1) ^ Z ^ (I ^ j)))\n        return 0.25 * Hs\n\n    def gen_Hp(self) -> PauliOp:\n        \"\"\"Generate the profit Hamiltonian\n        :math:`H_{p}=\\sum_{i}w(i)(1-Z_{i})/2`\n\n        Returns\n        ----------\n        qiskit.opflow.PauliOp\n            Profit Hamiltonian.\n\n        \"\"\"\n        Hp = 0 * I ^ self.nqubits\n        for i in range(self.nqubits):\n            # Qiskit opflow doesn't support multiplying types other than python built-in ones (e.g. np.float64)\n            Hp += float(self.dat[self.idx2cord[i]]) * (\n                (I ^ self.nqubits) - ((I ^ self.nqubits - i - 1) ^ Z ^ (I ^ i))\n            )\n        return 0.5 * Hp\n\n    def gen_Hamiltonian(self, penalty: Union[float, bool, None]) -> PauliOp:\n        \"\"\"Generate the Hamiltonian with penalty weight :math:`\\gamma`.\n\n        :math:`H=-H_{p}+\\gamma H_{s}`\n\n        Parameter   s\n        ----------\n        penalty : float\n            Penalty for the smoothness term in the Hamiltonian.\n\n        Returns\n        ----------\n        qiskit.opflow.PauliOp\n            Hamiltonian with penalty weight :math:`\\gamma`.\n\n        \"\"\"\n        if penalty is True:\n            penalty = self.heuristic_penalty()\n        if penalty:\n            return (-self.Hp + penalty * self.Hs).reduce()\n        return self.gen_projected_Hamiltonian()\n\n    def gen_projected_Hamiltonian(self) -> PauliOp:\n        \"\"\"Generate the profit Hamiltonian projected onto valid states.\n\n        Returns\n        ----------\n        qiskit.opflow.PauliOp\n            :math:`H=-PH_{p}P`\n\n        \"\"\"\n        state_fn = (-self.Hs @ (Plus ^ self.nqubits)).reduce().eval().to_dict_fn()\n        self.valid_configs = [\n            int(k, 2) for k, v in state_fn.primitive.items() if abs(v) < 1e-8\n        ]\n        p_op = np.zeros((2 ** self.nqubits))\n        p_op[np.array(self.valid_configs, dtype=int)] = 1\n        p_op = MatrixOp(np.diag(p_op))\n\n        return (p_op @ -self.Hp @ p_op).reduce().to_matrix_op()\n\n    def gen_pseudoflow_graph(self, MAX_FLOW: int) -> Tuple[nx.DiGraph, int, int]:\n        G = nx.DiGraph()\n        G.add_nodes_from(np.arange(self.nqubits))\n        source = -1\n        sink = self.nqubits\n\n        for p in self.graph:\n            for c in self.graph[p]:\n                G.add_edge(p, c, const=MAX_FLOW)\n\n            if self.dat[self.idx2cord[p]] >= 0:\n                G.add_edge(source, p, const=self.dat[self.idx2cord[p]])\n            else:\n                G.add_edge(p, sink, const=-self.dat[self.idx2cord[p]])\n\n        return G, source, sink\n\n    def plot_mine_state(\n        self, bitstring: str, bit_ordering: Optional[str] = \"R\"\n    ) -> None:\n        \"\"\"Plot the mining state represented by the bitstring.\n\n        Parameters\n        ----------\n        bitstring : str\n            A 0/1 string represents the state. Length of the string is the same as the number of qubits.\n        bit_ordering : str\n            Available options ``[\\'L\\', \\'R\\']``. ``\\'L\\'`` means the least significant bit (LSB) is on the left, and ``\\'R\\'`` means LSB is on the right. LSB represents the qubit with index 0.\n        \"\"\"\n        assert (\n            len(bitstring) == self.nqubits\n        ), \"Length of the bitstring should be the same as the number of qubits.\"\n        assert bit_ordering in [\"L\", \"R\"], \"bit_ordering options: 'L', 'R'.\"\n        if bit_ordering == \"R\":\n            bitstring = \"\".join(list(bitstring)[::-1])\n\n        x = PrettyTable([\" \"] + [str(ic) for ic in range(self.cols)])\n        for ir in range(self.rows):\n            x.add_row(\n                [ir]\n                + [\n                    bitstring[self.cord2idx[(ir, ic)]]\n                    if (ir, ic) in self.cord2idx\n                    else \"x\"\n                    for ic in range(self.cols)\n                ]\n            )\n        print(str(x))\n\n    def get_profit(self, bitstring: str, bit_ordering: Optional[str] = \"R\") -> int:\n        \"\"\"Return profit for a vector state.\n\n        Parameters\n        ----------\n        bitstring : str\n            A 0/1 string represents the state. Length of the string is the same as the number of qubits.\n        bit_ordering : str\n            Available options ``[\\'L\\', \\'R\\']``. ``\\'L\\'`` means the least significant bit (LSB) is on the left, and ``\\'R\\'`` means LSB is on the right. LSB represents the qubit with index 0.\n        \"\"\"\n        assert (\n            len(bitstring) == self.nqubits\n        ), \"Length of the bitstring should be the same as the number of qubits.\"\n        assert bit_ordering in [\"L\", \"R\"], \"bit_ordering options: 'L', 'R'.\"\n        if bit_ordering == \"R\":\n            bitstring = \"\".join(list(bitstring)[::-1])\n\n        return sum(\n            [\n                self.dat[self.idx2cord[i]]\n                for i in range(self.nqubits)\n                if bitstring[i] == \"1\"\n            ]\n        )\n\n    def get_violation(self, bitstring: str, bit_ordering: Optional[str] = \"R\") -> int:\n        \"\"\"Return violation for a vector state.\n\n        Parameters\n        ----------\n        bitstring : str\n            A 0/1 string represents the state. Length of the string is the same as the number of qubits.\n        bit_ordering : str\n            Available options ``[\\'L\\', \\'R\\']``. ``\\'L\\'`` means the least significant bit (LSB) is on the left, and ``\\'R\\'`` means LSB is on the right. LSB represents the qubit with index 0.\n        \"\"\"\n        assert (\n            len(bitstring) == self.nqubits\n        ), \"Length of the bitstring should be the same as the number of qubits.\"\n        assert bit_ordering in [\"L\", \"R\"], \"bit_ordering options: 'L', 'R'.\"\n        if bit_ordering == \"R\":\n            bitstring = \"\".join(list(bitstring)[::-1])\n\n        dig = list(map(lambda x: -1 if x == \"1\" else 1, list(bitstring)))\n        res = 0\n        for i in range(self.nqubits):\n            for j in self.graph[i]:\n                res += 0.25 * (1.0 - dig[i]) * (1.0 + dig[j])\n        return int(res)\n\n    def heuristic_penalty(self, coeff: float = 3.8) -> float:\n        return (\n            float(\n                np.linalg.norm(np.where(self.dat.flat != np.inf), ord=2) / self.nqubits\n            )\n            * coeff\n        )\n\n    def solve(\n        self,\n        algorithm: Union[MinimumEigensolver, Pseudoflow],\n        penalty: Union[float, bool, None] = None,\n        benchmark: Union[Benchmark, bool, None] = None,\n    ) -> \"MiningProblemResult\":\n        if benchmark is True:\n            benchmark = Benchmark()\n        elif benchmark is False or benchmark is None:\n            benchmark = Benchmark(activate=False)\n\n        with benchmark:\n            self._ret = MiningProblemResult()\n\n            if isinstance(algorithm, MinimumEigensolver):\n                res = algorithm.compute_minimum_eigenvalue(\n                    self.gen_Hamiltonian(penalty), [self.Hp, self.Hs]\n                )\n\n                if isinstance(algorithm, NumPyMinimumEigensolver):\n                    self._ret.optimal_config = format(\n                        np.argwhere(res.eigenstate.primitive.data.real == 1.0).item(),\n                        f\"0{self.nqubits + 2}b\",\n                    )[2:]\n                    self._ret.optimal_config_prob = 1.0\n\n                else:\n                    if isinstance(res.eigenstate, dict):\n                        self._ret.optimal_config, self._ret.optimal_config_prob = max(\n                            (\n                                item\n                                for item in res.eigenstate.items()\n                                if self.valid_configs is None\n                                or int(item[0], 2) in self.valid_configs\n                            ),\n                            key=lambda item: item[1],\n                        )\n                    elif isinstance(res.eigenstate, np.ndarray):\n                        idx = np.argmax(res.eigenstate * res.eigenstate.conj())\n                        self._ret.optimal_config = int_to_bitstr(idx, self.nqubits)\n                        self._ret.optimal_config_prob = res.eigenstate[idx]\n\n                    if isinstance(self._ret.optimal_config_prob, complex):\n                        self._ret.optimal_config_prob = (\n                            self._ret.optimal_config_prob.real ** 2\n                            - self._ret.optimal_config_prob.imag ** 2\n                        )\n                    else:\n                        self._ret.optimal_config_prob **= 2\n\n                self._ret.ground_state = res.eigenstate\n                if (\n                    res.aux_operator_eigenvalues is not None\n                ):  # Remove after implemented ASP expectation value\n                    (\n                        self._ret._expected_profit,\n                        self._ret._expected_violation,\n                    ) = res.aux_operator_eigenvalues\n\n            elif isinstance(algorithm, Pseudoflow):\n                self._ret.optimal_config = algorithm.run(\n                    *self.gen_pseudoflow_graph(algorithm.MAX_FLOW)\n                )\n                self._ret.optimal_config_prob = 1.0\n\n            elif isinstance(algorithm, PEPSITE):\n                self._ret.optimal_config = algorithm.run(self)\n                self._ret.optimal_config_prob = 1.0\n                \n            else:\n                raise ValueError(f\"{type(algorithm)} is not a valid algorithm.\")\n\n            print(\n                \"The most probable configuration and the corresponding probability:\"\n                f\" {self._ret.optimal_config, self._ret.optimal_config_prob}\"\n            )\n            self.plot_mine_state(self._ret.optimal_config)\n            return self._ret\n\n\nclass SubMine(BaseMine):\n    def __init__(self, mine: Mine, node_list: List) -> None:\n        self.node_list = node_list\n        self.nqubits = len(self.node_list)\n        self.node_c = {}  # key: a node in this frag, value: child node in another frag\n        self.node_p = {}  # key: a node in this frag, value: parent node in another frag\n        self.node_bd = []  # submine idx of bd nodes\n        self.zb = []  # pauli z op of bd nodes\n\n        self._init_nodes(mine)\n        self.Hp = self.gen_Hp(mine)  # profit\n        self.Hs = self.gen_Hs(mine)  # smoothness, inner nodes\n        self.Hb = null_operator(self.nqubits)  # boundary\n\n    def _init_nodes(self, mine: Mine) -> None:\n        for idx, i in enumerate(self.node_list):\n            self.node_c[i] = [j for j in mine.graph[i] if j not in self.node_list]\n            self.node_p[i] = [j for j in mine.graph_r[i] if j not in self.node_list]\n            if len(self.node_c[i]) + len(self.node_p[i]) > 0:\n                self.node_bd.append(idx)\n                self.zb.append(single_qubit_pauli(\"z\", idx, self.nqubits))\n\n    def gen_Hs(self, mine: Mine) -> PauliOp:\n        Hs = null_operator(self.nqubits)\n        for sub_i, i in enumerate(self.node_list):\n            for j in mine.graph[i]:\n                try:\n                    sub_j = self.node_list.index(j)\n                    Hs += z_projector(1, sub_i, self.nqubits) @ z_projector(\n                        0, sub_j, self.nqubits\n                    )\n                except:\n                    continue\n        return Hs\n\n    def gen_Hp(self, mine: Mine) -> PauliOp:\n        Hp = null_operator(self.nqubits)\n        for sub_idx, idx in enumerate(self.node_list):\n            Hp += float(mine.dat[mine.idx2cord[idx]]) * z_projector(\n                1, sub_idx, self.nqubits\n            )\n        return Hp\n\n    def _update_Hb(self, z_val: Dict) -> None:\n        self.Hb = null_operator(self.nqubits)\n        for sub_idx in self.node_bd:\n            mine_idx = self.node_list[sub_idx]\n            for j in self.node_c[mine_idx]:\n                self.Hb += float(0.5 * (1 + z_val[j])) * z_projector(\n                    1, sub_idx, self.nqubits\n                )\n            for j in self.node_p[mine_idx]:\n                self.Hb += float(0.5 * (1 - z_val[j])) * z_projector(\n                    0, sub_idx, self.nqubits\n                )\n\n    def gen_Hamiltonian(self, penalty: float, z_val: Dict) -> PauliOp:\n        self._update_Hb(z_val)\n        H_res = -self.Hp + penalty * (self.Hs + self.Hb)\n        return H_res\n\n    def solve(\n        self, algorithm: MinimumEigensolver, penalty: Union[float, None], z_val: Dict\n    ) -> \"MiningProblemResult\":\n        if isinstance(algorithm, MinimumEigensolver):\n            res = algorithm.compute_minimum_eigenvalue(\n                self.gen_Hamiltonian(penalty, z_val), self.zb + [self.Hp, self.Hs]\n            )\n            self._ret = MiningProblemResult()\n            self._ret.optimal_config, self._ret.optimal_config_prob = max(\n                res.eigenstate.items(), key=lambda item: item[1]\n            )\n            # self._ret.ground_state = res.eigenstate\n            for sub_idx, zi in zip(self.node_bd, res.aux_operator_eigenvalues[:-2]):\n                z_val[self.node_list[sub_idx]] = zi\n            self._ret.expected_profit = res.aux_operator_eigenvalues[-2]\n            self._ret.expected_violation = res.aux_operator_eigenvalues[-1]\n            return self._ret\n        else:\n            raise ValueError()\n\n\nclass SubMine(BaseMine):\n    def __init__(self, mine: Mine, node_list: List) -> None:\n        super.__init__()\n        self.node_list = node_list\n        self.nqubits = len(self.node_list)\n        self.node_c = {}  # key: a node in this frag, value: child node in another frag\n        self.node_p = {}  # key: a node in this frag, value: parent node in another frag\n        self.node_bd = []  # submine idx of bd nodes\n        self.zb = []  # pauli z op of bd nodes\n\n        self._init_nodes(mine)\n        self.Hp = self.gen_Hp(mine)  # profit\n        self.Hs = self.gen_Hs(mine)  # smoothness, inner nodes\n        self.Hb = null_operator(self.nqubits)  # boundary\n\n    def _init_nodes(self, mine: Mine) -> None:\n        for idx, i in enumerate(self.node_list):\n            self.node_c[i] = [j for j in mine.graph[i] if j not in self.node_list]\n            self.node_p[i] = [j for j in mine.graph_r[i] if j not in self.node_list]\n            if len(self.node_c[i]) + len(self.node_p[i]) > 0:\n                self.node_bd.append(idx)\n                self.zb.append(single_qubit_pauli(\"z\", idx, self.nqubits))\n\n    def gen_Hs(self, mine: Mine) -> PauliOp:\n        Hs = null_operator(self.nqubits)\n        for sub_i, i in enumerate(self.node_list):\n            for j in mine.graph[i]:\n                try:\n                    sub_j = self.node_list.index(j)\n                    Hs += z_projector(1, sub_i, self.nqubits) @ z_projector(\n                        0, sub_j, self.nqubits\n                    )\n                except:\n                    continue\n        return Hs\n\n    def gen_Hp(self, mine: Mine) -> PauliOp:\n        Hp = null_operator(self.nqubits)\n        for sub_idx, idx in enumerate(self.node_list):\n            Hp += float(mine.dat[mine.idx2cord[idx]]) * z_projector(\n                1, sub_idx, self.nqubits\n            )\n        return Hp\n\n    def _update_Hb(self, z_val: Dict) -> None:\n        self.Hb = null_operator(self.nqubits)\n        for sub_idx in self.node_bd:\n            mine_idx = self.node_list[sub_idx]\n            for j in self.node_c[mine_idx]:\n                self.Hb += float(0.5 * (1 + z_val[j])) * z_projector(\n                    1, sub_idx, self.nqubits\n                )\n            for j in self.node_p[mine_idx]:\n                self.Hb += float(0.5 * (1 - z_val[j])) * z_projector(\n                    0, sub_idx, self.nqubits\n                )\n\n    def gen_Hamiltonian(self, penalty: float, z_val: Dict) -> PauliOp:\n        self._update_Hb(z_val)\n        H_res = -self.Hp + penalty * (self.Hs + self.Hb)\n        return H_res\n\n    def solve(\n        self, algorithm: MinimumEigensolver, penalty: Union[float, None], z_val: Dict\n    ) -> \"MiningProblemResult\":\n        if isinstance(algorithm, MinimumEigensolver):\n            res = algorithm.compute_minimum_eigenvalue(\n                self.gen_Hamiltonian(penalty, z_val), self.zb + [self.Hp, self.Hs]\n            )\n            self._ret = MiningProblemResult()\n            self._ret.optimal_config, self._ret.optimal_config_prob = max(\n                res.eigenstate.items(), key=lambda item: item[1]\n            )\n            # self._ret.ground_state = res.eigenstate\n            for sub_idx, zi in zip(self.node_bd, res.aux_operator_eigenvalues[:-2]):\n                z_val[self.node_list[sub_idx]] = zi\n            self._ret.expected_profit = res.aux_operator_eigenvalues[-2]\n            self._ret.expected_violation = res.aux_operator_eigenvalues[-1]\n            return self._ret\n        else:\n            raise ValueError()\n\n\nclass MiningProblemResult(AlgorithmResult):\n    def __init__(self) -> None:\n        super().__init__()\n        self._optimal_config = None\n        self._optimal_config_prob = None\n        self._ground_state = None\n        self._expected_profit = None\n        self._expected_violation = None\n\n    @property\n    def optimal_config(self) -> Optional[str]:\n        return self._optimal_config\n\n    @optimal_config.setter\n    def optimal_config(self, optimal_config: str) -> None:\n        self._optimal_config = optimal_config\n\n    @property\n    def optimal_config_prob(self) -> Optional[float]:\n        return self._optimal_config_prob\n\n    @optimal_config_prob.setter\n    def optimal_config_prob(self, optimal_config_prob: float) -> None:\n        self._optimal_config_prob = optimal_config_prob\n\n    @property\n    def ground_state(self) -> Optional[np.ndarray]:\n        return self._ground_state\n\n    @ground_state.setter\n    def ground_state(self, ground_state: np.ndarray) -> None:\n        self._ground_state = ground_state\n\n    @property\n    def expected_profit(self) -> Optional[float]:\n        return self._expected_profit\n\n    @expected_profit.setter\n    def expected_profit(self, expected_profit: float) -> None:\n        self._expected_profit = expected_profit\n\n    @property\n    def expected_violation(self) -> Optional[float]:\n        return self._expected_violation\n\n    @expected_violation.setter\n    def expected_violation(self, expected_violation: float) -> None:\n        self._expected_violation = expected_violation\n", "meta": {"hexsha": "e4637f9cc14f460a2a4899e57a788eed1d34a349", "size": 23744, "ext": "py", "lang": "Python", "max_stars_repo_path": "qore/model/mine.py", "max_stars_repo_name": "HaoTy/qore", "max_stars_repo_head_hexsha": "2d866615bb05c5b8a5d6f6c7a2c1ca1008e7851b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "qore/model/mine.py", "max_issues_repo_name": "HaoTy/qore", "max_issues_repo_head_hexsha": "2d866615bb05c5b8a5d6f6c7a2c1ca1008e7851b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qore/model/mine.py", "max_forks_repo_name": "HaoTy/qore", "max_forks_repo_head_hexsha": "2d866615bb05c5b8a5d6f6c7a2c1ca1008e7851b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5696202532, "max_line_length": 193, "alphanum_fraction": 0.5496546496, "include": true, "reason": "import numpy,import networkx", "num_tokens": 5802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.1923399781615312}}
{"text": "\"\"\"\npretrain using qt, to get neural representation, then run kmeans on various\ncombinations of the resulting representations\n\nthis was forked initially from train.py, then modified\n\"\"\"\nimport argparse\nimport datetime\nimport copy\nimport time\nimport numpy as np\nimport sklearn.cluster\nimport warnings\nimport torch\nfrom torch import autograd\n\nfrom proc_data import Dataset\nfrom model.multiview_encoders import MultiviewEncoders\nfrom metrics import cluster_metrics\nimport pretrain\n\n\nwarnings.filterwarnings(action='ignore', category=RuntimeWarning)\n\ntorch.manual_seed(0)\nnp.random.seed(0)\n\nLSTM_LAYER = 1\nLSTM_HIDDEN = 300\nWORD_DROPOUT_RATE = 0.\nDROPOUT_RATE = 0.\nBATCH_SIZE = 32\nLEARNING_RATE = 0.001\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\ndef transform(data, model):\n    model.eval()\n    latent_zs = []\n    n_batch = (len(data) + BATCH_SIZE - 1) // BATCH_SIZE\n    for i in range(n_batch):\n        data_batch = data[i*BATCH_SIZE:(i+1)*BATCH_SIZE]\n        with autograd.no_grad():\n            latent_z = model(data_batch, encoder='v1')\n        latent_zs.append(latent_z.cpu().data.numpy())\n    latent_zs = np.concatenate(latent_zs)\n    return latent_zs\n\n\ndef calc_prec_rec_f1_acc(preds, golds):\n    lgolds, lpreds = [], []\n    for g, p in zip(golds, list(preds)):\n        if g > 0:\n            lgolds.append(g)\n            lpreds.append(p)\n    prec, rec, f1 = cluster_metrics.calc_prec_rec_f1(\n        gnd_assignments=torch.LongTensor(lgolds).to(device),\n        pred_assignments=torch.LongTensor(lpreds).to(device))\n    acc = cluster_metrics.calc_ACC(\n        torch.LongTensor(lpreds).to(device), torch.LongTensor(lgolds).to(device))\n    return prec, rec, f1, acc\n\n\ndef main():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--data-path', type=str, default='./data/airlines_processed.csv')\n    parser.add_argument('--glove-path', type=str, default='./data/glove.840B.300d.txt')\n    parser.add_argument('--pre-epoch', type=int, default=5)\n    parser.add_argument('--pt-batch', type=int, default=100)\n    parser.add_argument('--scenarios', type=str, default='view1,view2,concatviews,wholeconv',\n                        help='comma-separated, from [view1|view2|concatviews|wholeconv|mvsc]')\n    parser.add_argument('--mvsc-no-unk', action='store_true',\n                        help='only feed non-unk data to MVSC (to avoid oom)')\n\n    parser.add_argument('--view1-col', type=str, default='view1')\n    parser.add_argument('--view2-col', type=str, default='view2')\n    parser.add_argument('--label-col', type=str, default='tag')\n    args = parser.parse_args()\n\n    print('loading dataset')\n    dataset = Dataset(args.data_path, view1_col=args.view1_col, view2_col=args.view2_col,\n                      label_col=args.label_col)\n    n_cluster = len(dataset.id_to_label) - 1\n    print(\"num of class = %d\" % n_cluster)\n\n    id_to_token, token_to_id = dataset.id_to_token, dataset.token_to_id\n    vocab_size = len(dataset.token_to_id)\n    print('vocab_size', vocab_size)\n\n    # Load pre-trained GloVe vectors\n    pretrained = {}\n    word_emb_size = 0\n    print('loading glove')\n    for line in open(args.glove_path):\n        parts = line.strip().split()\n        if len(parts) % 100 != 1:\n            continue\n        word = parts[0]\n        if word not in token_to_id:\n            continue\n        vector = [float(v) for v in parts[1:]]\n        pretrained[word] = vector\n        word_emb_size = len(vector)\n    pretrained_list = []\n    scale = np.sqrt(3.0 / word_emb_size)\n    print('loading oov')\n    for word in id_to_token:\n        # apply lower() because all GloVe vectors are for lowercase words\n        if word.lower() in pretrained:\n            pretrained_list.append(np.array(pretrained[word.lower()]))\n        else:\n            random_vector = np.random.uniform(-scale, scale, [word_emb_size])\n            pretrained_list.append(random_vector)\n\n    model = MultiviewEncoders.from_embeddings(\n        embeddings=torch.FloatTensor(pretrained_list),\n        num_layers=LSTM_LAYER,\n        embedding_size=word_emb_size,\n        lstm_hidden_size=LSTM_HIDDEN,\n        word_dropout=WORD_DROPOUT_RATE,\n        dropout=DROPOUT_RATE,\n        vocab_size=vocab_size\n    )\n    model.to(device)\n    optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE)\n\n    expressions = (model, optimizer)\n    pre_acc, pre_state = 0., None\n    pretrain_method = pretrain.pretrain_qt\n    for epoch in range(1, args.pre_epoch + 1):\n        model.train()\n        perm_idx = np.random.permutation(dataset.trn_idx)\n        trn_loss, _ = pretrain_method(dataset, perm_idx, expressions, train=True)\n        model.eval()\n        _, tst_acc = pretrain_method(dataset, dataset.tst_idx, expressions, train=False)\n        if tst_acc > pre_acc:\n            pre_state = copy.deepcopy(model.state_dict())\n            pre_acc = tst_acc\n        print(f'{datetime.datetime.now()} epoch {epoch}, train_loss={trn_loss:.4f} '\n              f'test_acc={tst_acc:.4f}')\n\n    if args.pre_epoch > 0:\n        # load best state\n        model.load_state_dict(pre_state)\n\n        # deepcopy pretrained views into v1 and/or view2\n        pretrain.after_pretrain_qt(model)\n\n    kmeans = sklearn.cluster.KMeans(n_clusters=n_cluster, max_iter=300, verbose=0, random_state=0)\n\n    golds = [dataset[idx][1] for idx in dataset.trn_idx]\n    for rep in args.scenarios.split(','):\n        if rep == 'view1':\n            data = [dataset[idx][0][0] for idx in dataset.trn_idx]\n            encoded = transform(data=data, model=model)\n            preds = kmeans.fit_predict(encoded)\n        elif rep == 'view2':\n            data = [dataset[idx][0][1] for idx in dataset.trn_idx]\n            encoded = []\n            for conv in data:\n                encoded_conv = transform(data=conv, model=model)\n                encoded_conv = torch.from_numpy(encoded_conv)\n                encoded_conv = encoded_conv.mean(dim=0)\n                encoded.append(encoded_conv)\n            encoded = torch.stack(encoded, dim=0)\n            # print('encoded.size()', encoded.size())\n            encoded = encoded.numpy()\n            preds = kmeans.fit_predict(encoded)\n        elif rep == 'concatviews':\n            v1_data = [dataset[idx][0][0] for idx in dataset.trn_idx]\n            v1_encoded = torch.from_numpy(transform(data=v1_data, model=model))\n\n            v2_data = [dataset[idx][0][1] for idx in dataset.trn_idx]\n            v2_encoded = []\n            for conv in v2_data:\n                encoded_conv = transform(data=conv, model=model)\n                encoded_conv = torch.from_numpy(encoded_conv)\n                encoded_conv = encoded_conv.mean(dim=0)\n                v2_encoded.append(encoded_conv)\n            v2_encoded = torch.stack(v2_encoded, dim=0)\n            concatview = torch.cat([v1_encoded, v2_encoded], dim=-1)\n            print('concatview.size()', concatview.size())\n            encoded = concatview.numpy()\n            preds = kmeans.fit_predict(encoded)\n        elif rep == 'wholeconv':\n            encoded = []\n            for idx in dataset.trn_idx:\n                v1 = dataset[idx][0][0]\n                v2 = dataset[idx][0][1]\n                conv = [v1] + v2\n                encoded_conv = transform(data=conv, model=model)\n                encoded_conv = torch.from_numpy(encoded_conv)\n                encoded_conv = encoded_conv.mean(dim=0)\n                encoded.append(encoded_conv)\n            encoded = torch.stack(encoded, dim=0)\n            print('encoded.size()', encoded.size())\n            encoded = encoded.numpy()\n            preds = kmeans.fit_predict(encoded)\n        elif rep == 'mvsc':\n            try:\n                import multiview\n            except Exception:\n                print('please install https://github.com/mariceli3/multiview')\n                return\n            print('imported multiview ok')\n\n            idx = dataset.trn_idx_no_unk if args.mvsc_no_unk else dataset.trn_idx\n            v1_data = [dataset[idx][0][0] for idx in idx]\n            v1_encoded = torch.from_numpy(transform(data=v1_data, model=model))\n\n            v2_data = [dataset[idx][0][1] for idx in idx]\n            v2_encoded = []\n            for conv in v2_data:\n                encoded_conv = transform(data=conv, model=model)\n                encoded_conv = torch.from_numpy(encoded_conv)\n                encoded_conv = encoded_conv.mean(dim=0)\n                v2_encoded.append(encoded_conv)\n            v2_encoded = torch.stack(v2_encoded, dim=0)\n\n            mvsc = multiview.mvsc.MVSC(\n                k=n_cluster\n            )\n            print('running mvsc', end='', flush=True)\n            start = time.time()\n            preds, eivalues, eivectors, sigmas = mvsc.fit_transform(\n                [v1_encoded, v2_encoded], [False] * 2\n            )\n            print('...done')\n            mvsc_time = time.time() - start\n            print('time taken %.3f' % mvsc_time)\n        else:\n            raise Exception('unimplemented rep', rep)\n\n        prec, rec, f1, acc = calc_prec_rec_f1_acc(preds, golds)\n        print(f'{datetime.datetime.now()} {rep}: eval prec={prec:.4f} rec={rec:.4f} f1={f1:.4f} '\n              f'acc={acc:.4f}')\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "01d18f8e1f4e9d666911006a8ec6c5d3a742d89d", "size": 9201, "ext": "py", "lang": "Python", "max_stars_repo_path": "train_qt.py", "max_stars_repo_name": "asappresearch/dialog-intent-induction", "max_stars_repo_head_hexsha": "6396f3153b0fda7e170b1df6b68e969b5e4eb16e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 60, "max_stars_repo_stars_event_min_datetime": "2019-09-11T12:05:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T13:19:53.000Z", "max_issues_repo_path": "train_qt.py", "max_issues_repo_name": "asappresearch/dialog-intent-induction", "max_issues_repo_head_hexsha": "6396f3153b0fda7e170b1df6b68e969b5e4eb16e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-01-17T19:34:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-08T04:10:27.000Z", "max_forks_repo_path": "train_qt.py", "max_forks_repo_name": "asappresearch/dialog-intent-induction", "max_forks_repo_head_hexsha": "6396f3153b0fda7e170b1df6b68e969b5e4eb16e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2019-09-06T08:44:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-23T10:36:58.000Z", "avg_line_length": 38.020661157, "max_line_length": 98, "alphanum_fraction": 0.6188457776, "include": true, "reason": "import numpy", "num_tokens": 2205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.19233997816153117}}
{"text": "# -*- coding: utf-8 -*-\nimport os\nimport fnmatch\nimport copy\nimport datetime\nimport pickle\nimport pathlib\n\nimport numpy as np\nfrom numpy.lib.format import open_memmap\nimport mpmath\nimport PIL\nimport PIL.PngImagePlugin\nimport numba\n\nimport fractalshades as fs\nimport fractalshades.numpy_utils.xrange as fsx\nimport fractalshades.settings as fssettings\nimport fractalshades.utils as fsutils\n\nfrom fractalshades.mprocessing import Multiprocess_filler\n\n\n\nclass _Pillow_figure:\n    def __init__(self, img, pnginfo):\n        \"\"\"\n        This class is a wrapper that can be used to redirect a Fractal_plotter\n        output, for instance when generating the documentation.\n        \"\"\"\n        self.img = img\n        self.pnginfo = pnginfo\n\n    def save_png(self, im_path):\n        \"\"\"\n        Saves as a png with Lanczos antialiasing if exceeds the max width\n        \"\"\"\n        im = self.img\n        width, height = im.size\n        max_width = fs.settings.output_context[\"doc_max_width\"]\n        \n        if width > max_width:\n            ratio = float(width) / float(max_width)\n            new_height = int(height / ratio)\n            im = im.resize((max_width, new_height), PIL.Image.LANCZOS)\n        im.save(im_path, format=\"png\", pnginfo=self.pnginfo)\n\n\nclass Fractal_plotter:\n    def  __init__(self, postproc_batch):\n        \"\"\"\n        The base plotting class.\n        \n        A Fractal plotter :\n\n        - points to a single Fractal\n        - can hold several `fractalshades.postproc.Postproc_batch` each one\n          point to a single\n          (`Fracal`, ``calculation``) couple\n        - can hold several post-processing layers\n         \n        Parameters\n        ----------\n        postproc_batch\n            A single `fractalshades.postproc.Postproc_batch` or a list of \n            these\n\n        Notes\n        -----\n\n        .. warning::\n            When passed a list of `fractalshades.postproc.Postproc_batch`\n            objects, each one shall point to\n            the same `Fractal`.\n        \"\"\"\n        # postproc_batchescan be single or an enumeration\n        postproc_batches = postproc_batch\n        if isinstance(postproc_batch, fs.postproc.Postproc_batch):\n            postproc_batches = [postproc_batch]\n        for i, postproc_batch in enumerate(postproc_batches):\n            if i == 0:\n                self.postproc_batches = [postproc_batch]\n                self.posts = copy.copy(postproc_batch.posts)\n                self.postnames_2d = postproc_batch.postnames_2d\n                # iterator :\n                self.fractal = postproc_batch.fractal\n            else:\n                self.add_postproc_batch(postproc_batch)\n\n        self.chunk_slices = self.fractal.chunk_slices\n        # layer data\n        self.layers = []\n        self.scalings = None # to be computed !\n        # Plotting directory\n        self.plot_dir = self.fractal.directory\n    \n    @property\n    def postnames(self):\n        return self.posts.keys()\n    \n    @property\n    def size(self):\n        f = self.fractal\n        return (f.nx, f.ny)\n\n    def add_postproc_batch(self, postproc_batch):\n        \"\"\"\n        Adds another post-processing batch & register the associated postproc\n        names. `postproc_batch` shall map to the same fractal.\n        Note : several postproc_batches are needed whenever different \n        calculations need to be combined in an output plot, as a postproc\n        batch can only map to a unique calc_name.\n        :meta private:\n        \"\"\"\n        if postproc_batch.fractal != self.fractal:\n            raise ValueError(\"Attempt to add a postproc_batch from a different\"\n                             \"fractal: {} from {}\".format(\n                postproc_batch.fractal, postproc_batch.calc_name))\n        self.postproc_batches += [postproc_batch]\n        self.posts.update(postproc_batch.posts)\n        self.postnames_2d += postproc_batch.postnames_2d\n\n    def add_layer(self, layer):\n        \"\"\"\n        Adds a layer field to allow subsequent graphical operations or outputs.\n        \n        Parameters\n        ----------\n        layer : `fractalshades.colors.layers.Virtual_layer` or a derived class\n            The layer to add\n        \n        Notes\n        -----\n\n        .. warning::\n            Layer `postname` shall have been already registered in one of the\n            plotter batches.\n\n        .. warning::\n            When a layer is added, a link layer -> Fractal_plotter is \n            created ; a layer can only point to a single `Fractal_plotter`.\n        \"\"\"\n        postname = layer.postname\n        if postname not in (list(self.postnames) + self.postnames_2d):\n            raise ValueError(\"Layer `{}` shall be registered in \"\n                             \"Fractal_plotter postproc_batches: {}\".format(\n            postname, list(self.postnames) + self.postnames_2d))\n        self.layers += [layer]\n        layer.link_plotter(self)\n\n    def __getitem__(self, layer_name):\n        \"\"\" Get the layer by its postname\n        \"\"\"\n        for layer in self.layers:\n            if layer.postname == layer_name:\n                return layer\n        raise KeyError(\"Layer {} not in available layers: {}\".format(\n                layer_name, list(l.postname for l in self.layers)))\n\n    def plot(self):\n        \"\"\"\n        The base method to produce images.\n        \n        When called, it will got through all the instance-registered layers\n        and plot each layer for which the `output` attribute is set to `True`.\n        \"\"\"\n        self.store_postprocs()\n        self.compute_scalings()\n        self.write_postproc_report()\n        self.open_images()\n        self.push_layers_to_images()\n        self.save_images()\n        self.clean_up()\n\n    def store_postprocs(self):\n        \"\"\" Computes and stores posprocessed data in a temporary mmap\n        :meta private:\n        \"\"\"\n        if fs.settings.optimize_RAM:\n            self.has_memmap = True\n            self.open_temporary_mmap()\n        else:\n            self.has_memmap = False\n            self.open_RAM_data()\n\n        inc_posproc_rank = 0\n        self.postname_rank = dict()\n        \n        for batch in self.postproc_batches:\n            if self.has_memmap:\n                self.store_temporary_mmap(\n                        chunk_slice=None,\n                        batch=batch,\n                        inc_posproc_rank=inc_posproc_rank\n                )\n            else:\n                self.store_data(\n                        chunk_slice=None,\n                        batch=batch,\n                        inc_posproc_rank=inc_posproc_rank\n                )\n            for i, postname in enumerate(batch.postnames):\n                self.postname_rank[postname] = inc_posproc_rank + i\n            inc_posproc_rank += len(batch.posts)\n\n    def temporary_mmap_path(self):\n        \"\"\" Path to the temporary memmap used to stored plotting arrays\"\"\"\n        # from tempfile import mkdtemp\n        return os.path.join(\n            self.fractal.directory, \"data\", \"_plotter.tpm\")\n\n    def open_temporary_mmap(self):\n        \"\"\"\n        Creates the memory mappings for postprocessed arrays\n        Note: We expand to 2d format\n        \"\"\"\n        f = self.fractal\n        nx, ny = (f.nx, f.ny)\n        n_pp = len(self.posts)\n        mmap = open_memmap(\n            filename=self.temporary_mmap_path(), \n            mode='w+',\n            dtype=f.float_postproc_type,\n            shape=(n_pp, nx, ny),\n            fortran_order=False,\n            version=None)\n        del mmap\n\n    def open_RAM_data(self):\n        \"\"\"\n        Same as open_temporary_mmap but in RAM\n        \"\"\"\n        f = self.fractal\n        nx, ny = (f.nx, f.ny)\n        n_pp = len(self.posts)\n        self._RAM_data = np.zeros(\n            shape=(n_pp, nx, ny),\n            dtype=f.float_postproc_type\n        )\n\n\n    @Multiprocess_filler(iterable_attr=\"chunk_slices\",\n        iter_kwargs=\"chunk_slice\", veto_multiprocess=False)\n    def store_temporary_mmap(self, chunk_slice, batch, inc_posproc_rank):\n        \"\"\" Compute & store temporary arrays for this postproc batch\n            Note : inc_posproc_rank rank shift to take into account potential\n            other batches for this plotter.\n            (memory mapping version)\n        \"\"\"\n        f = self.fractal\n        inc = inc_posproc_rank\n        post_array, chunk_mask = self.fractal.postproc(batch, chunk_slice)\n        arr_2d = f.reshape2d(post_array, chunk_mask, chunk_slice)\n        n_posts, cx, cy = arr_2d.shape\n        (ix, ixx, iy, iyy) = chunk_slice\n        mmap = open_memmap(filename=self.temporary_mmap_path(), mode='r+')\n        mmap[inc:inc+n_posts, ix:ixx, iy:iyy] = arr_2d\n\n\n    @Multiprocess_filler(iterable_attr=\"chunk_slices\",\n        iter_kwargs=\"chunk_slice\", veto_multiprocess=True)\n    def store_data(self, chunk_slice, batch, inc_posproc_rank):\n        \"\"\" Compute & store temporary arrays for this postproc batch\n            (in-RAM version -> shall not use multiprocessing)\n        \"\"\"\n        f = self.fractal\n        inc = inc_posproc_rank\n        post_array, chunk_mask = self.fractal.postproc(batch, chunk_slice)\n        arr_2d = f.reshape2d(post_array, chunk_mask, chunk_slice)\n        n_posts, cx, cy = arr_2d.shape\n        (ix, ixx, iy, iyy) = chunk_slice\n        self._RAM_data[inc:inc+n_posts, ix:ixx, iy:iyy] = arr_2d\n\n    # All methods needed for plotting\n    def compute_scalings(self):\n        \"\"\" Compute the scaling for all layer field\n        (needed for mapping to color) \"\"\"\n        for layer in self.layers:\n            self.compute_layer_scaling(chunk_slice=None, layer=layer)\n    \n    def write_postproc_report(self):\n        report_path = os.path.join(\n            self.fractal.directory, type(self).__name__ + \".txt\")\n\n        def write_layer_report(i, layer, report):\n            report.write(\" - Layer #{} :\\n\".format(i))\n            postname = layer.postname\n            report.write(\"post-processing: `{}`\\n\".format(postname))\n            report.write(\"kind: {}\\n\".format(type(layer).__name__))\n            report.write(\"func: {}\\n\".format(layer._func_arg))\n\n            mask = layer.mask\n            if mask is None:\n                mask_str = \"None\"\n            else:\n                mask_str = \"{} `{}` with mask color: {}\".format(\n                    type(mask[0]).__name__,\n                    mask[0].postname,\n                    mask[1])\n            report.write(\"mask: {}\\n\".format(mask_str))\n\n            report.write(\"output: {}\\n\".format(layer.output))\n            report.write(\"min: {}\\n\".format(layer.min))\n            report.write(\"max: {}\\n\\n\".format(layer.max))\n            \n        with open(report_path, 'w', encoding='utf-8') as report:\n            for i, layer in enumerate(self.layers):\n                write_layer_report(i, layer, report)\n\n\n    @Multiprocess_filler(iterable_attr=\"chunk_slices\",\n        iter_kwargs=\"chunk_slice\", veto_multiprocess=True)\n    def compute_layer_scaling(self, chunk_slice, layer):\n        \"\"\" Compute the scaling for this layer \"\"\"\n        layer.update_scaling(chunk_slice)\n\n    def open_images(self):\n        self._im = []\n        for layer in self.layers:\n            if layer.output:\n                self._im += [PIL.Image.new(mode=layer.mode, size=self.size)]\n            else:\n                self._im += [None]\n\n    def save_images(self):\n        for i, layer in enumerate(self.layers):\n            if not(layer.output):\n                continue\n            file_name = \"{}_{}\".format(type(layer).__name__, layer.postname)\n            base_img_path = os.path.join(self.plot_dir, file_name + \".png\")\n            self.save_tagged(self._im[i], base_img_path, self.fractal.params)\n\n    def save_tagged(self, img, img_path, tag_dict):\n        \"\"\"\n        Saves *img* to png format at *path*, tagging with *tag_dict*.\n        https://dev.exiv2.org/projects/exiv2/wiki/The_Metadata_in_PNG_files\n        \"\"\"\n        pnginfo = PIL.PngImagePlugin.PngInfo()\n        for k, v in tag_dict.items():\n            pnginfo.add_text(k, str(v))\n        if (fssettings.output_context[\"doc\"]\n            and not(fssettings.output_context[\"gui_iter\"] > 0)):\n            fssettings.add_figure(_Pillow_figure(img, pnginfo))\n        else:\n            img.save(img_path, pnginfo=pnginfo)\n\n    def push_layers_to_images(self):\n        for i, layer in enumerate(self.layers):\n            if not(layer.output):\n                continue\n            self.push_cropped(chunk_slice=None, layer=layer, im=self._im[i])\n\n    @Multiprocess_filler(iterable_attr=\"chunk_slices\",\n        iter_kwargs=\"chunk_slice\", veto_multiprocess=True)\n    def push_cropped(self, chunk_slice, layer, im):\n        \"\"\" push \"cropped image\" from layer for this chunk to the image\"\"\"\n        (ix, ixx, iy, iyy) = chunk_slice\n        ny = self.fractal.ny\n        crop_slice = (ix, ny-iyy, ixx, ny-iy)\n        paste_crop = layer.crop(chunk_slice)\n        im.paste(paste_crop, box=crop_slice)\n        \n    def clean_up(self):\n        if self.has_memmap:\n            os.unlink(self.temporary_mmap_path())\n        else:\n            del self._RAM_data\n\n\n\nclass Fractal:\n    \n    REPORT_ITEMS = [\n        \"chunk1d_begin\",\n        \"chunk1d_end\",\n        \"iref\",\n        \"glitch_max_attempt\",\n        \"chunk_pts\",\n        \"total-glitched\",\n        \"dyn-glitched\"]\n\n    # Note : chunk_mask is pre-computed and saved also but not at the same \n    # stage (at begining of calculation)\n    SAVE_ARRS = [\n        \"Z\",\n        \"U\",\n        \"stop_reason\",\n        \"stop_iter\"]\n\n    def __init__(self, directory):\n        \"\"\"\nThe base class for all escape-time fractals calculations.\n\nDerived class should implement the actual calculation methods used in the\ninnner loop. This class provides the outer looping (calculation is run on \nsuccessive tiles), enables multiprocessing, and manage raw-result storing \nand retrieving.\n\nParameters\n----------\ndirectory : str\n    Path for the working base directory\n\nAttributes\n----------\ndirectory : str\n    the working directory\niref : int\n    the reference point index, when using perturbation technique (if\n    not, shall be None)\nglitch_max_attempt : int\n    The maximal number of glitch correction loops\nsubset\n    A boolean array-like of the size of the image, when False the\n    calculation is skipped for this point. It is usually the result\n    of a previous calculation that can be passed via a Fractal_array\n    wrapper.\n    If None (default) all points will be calculated.\nglitch_stop_index : int\n    A calculation can exit for several reasons which are tracked in \n    `stop_reason` int-array (see below the description of the raw data\n    arrays). Values of `stop_reason` above `glitch_stop_index` indicate\n    glitched pixels, for which the calculation is deemed invalid.\ncomplex_type :\n    the datatype used for Z output arrays\ncodes :\n    the string identifier codes for the saved arrays:\n    (`complex_codes`, `int_codes`, `termination_codes`)\n\nNotes\n-----\n\nThese notes describe implementation details and should be useful mostly to\nadvanced users when subclassing.\n\n.. note::\n\n    **Special methods**\n    \n    this class and its subclasses may define several methods decorated with\n    specific tags:\n    \n    `fractalshades.zoom_options`\n        decorates the methods used to define the zoom\n    `fractalshades.calc_options`\n        decorates the methods defining the calculation inner-loop\n    `fractalshades.interactive_options` \n        decorates the methods that can be called\n        interactively from the GUI (right-click then context menu selection).\n        The coordinates of the click are passed to the called method.\n\n.. note::\n    \n    **Calculation parameters**\n\n    To lanch a calculation, call `~fractalshades.Fractal.run`. The parameters\n    from the last \n    @ `fractalshades.zoom_options` call and last \n    @ `fractalshades.calc_options` call will be used. \n    They are stored as class attributes, above a list of such attributes and\n    their  meaning (non-exhaustive as derived class cmay define their own).\n    Note that they should normally not be directly accessed but defined in\n    derived class through zoom and calc methods.\n\n.. note::\n\n    **Saved data**\n    \n        The calculation results (raw output of the inner loop at exit) are\n        saved to disk and internally accessed during plotting phase through\n        memory-mapping. These are:\n\n        chunk_mask    \n            boolean - alias for `subset`\n            Saved to disk as ``calc_name``\\_Z.arr in ``data`` folder\n        Z\n            Complex fields, several fields can be defined and accessed through\n            a field string identifier.\n            Saved to disk as ``calc_name``\\_Z.arr in ``data`` folder\n        U\n            Integer fields, several fields can be defined and accessed through\n            a field string identifier.\n            Saved to disk as ``calc_name``\\_U.arr in ``data`` folder\n        stop_reason\n            Byte codes: the reasons for loop exit (max iteration reached ?\n            overflow ? other ?) A string identifier\n            Saved to disk as ``calc_name``\\_stop_reason.arr in ``data`` folder\n        stop_iter\n            Integer: iterations count at loop exit\n            Saved to disk as ``calc_name``\\_stop_iter.arr in ``data`` folder\n\n        The string identifiers are stored in ``codes`` attributes.\n\"\"\"\n        self.directory = directory\n        self.iref = None # None when no reference point used / needed\n        self.glitch_max_attempt = 0\n        self.subset = None\n        self.glitch_stop_index = None\n\n    def init_data_types(self, complex_type):\n        if type(complex_type) is tuple:\n            type_modifier, _ = complex_type\n            if type_modifier != \"Xrange\":\n                raise ValueError(type_modifier)\n        self.complex_type = complex_type\n        self.float_postproc_type = np.float32\n        self.termination_type = np.int8\n        self.int_type = np.int32\n\n    @fsutils.zoom_options\n    def zoom(self, *,\n             x: float,\n             y: float,\n             dx: float,\n             nx: int,\n             xy_ratio: float,\n             theta_deg: float,\n             projection: str=\"cartesian\",\n             antialiasing: bool=False):\n        \"\"\"\n        Define and stores as class-attributes the zoom parameters for the next\n        calculation.\n        \n        Parameters\n        ----------\n        x : float\n            x-coordinate of the central point\n        y : float \n            y-coordinate of the central point\n        dx : float\n            span of the view rectangle along the x-axis\n        nx : int\n            number of pixels of the image along the x-axis\n        xy_ratio: float\n            ratio of dx / dy and nx / ny\n        theta_deg : float\n            Pre-rotation of the calculation domain, in degree\n        projection : \"cartesian\" | \"spherical\" | \"exp_map\"\n            Kind of projection used (default to cartesian)\n        antialiasing : bool\n            If True, some degree of randomization is applied\n        \"\"\"\n        # We're all set, the job is done by `zoom_options` wrapper...\n\n    def run(self):\n        \"\"\"\n        Lauch a full calculation.\n                \n        The parameters from the last \n        @ `fractalshades.zoom_options`\\-tagged method call and last\n        @ `fractalshades.calc_options`\\-tagged method call will be used.\n\n        If calculation results are already there, the parameters will be\n        compared and if identical, the calculation will be skipped. This is\n        done for each tile and each glitch correction iteration, so i enables\n        calculation to restart from an unfinished status.\n        \"\"\"\n        if not(self.res_available()):\n            # We write the param file and initialize the\n            # memmaps for progress reports and calc arrays\n            # It is not process safe so we dot it before entering multi-processing\n            # loop\n            fsutils.mkdir_p(os.path.join(self.directory, \"data\"))\n            self.open_report_mmap()\n            self.open_data_mmaps()\n            self.save_params()\n        \n        # Lazzy compilation of subset boolean array chunk-span\n        self._mask_beg_end = None\n\n        # JIT-compiled function\n        # self.jitted_numba_cycles = numba.njit(numba_cycles)\n        self._iterate = self.iterate()\n        self.cycles()\n        \n        # Export to human-readable format\n        if fs.settings.inspect_calc:\n            self.inspect_calc()\n\n\n    @property\n    def interrupt_path(self):\n        return os.path.join(self.directory, \"data\", \"_interrupt.lck\")\n\n    def raise_interruption(self):\n        pathlib.Path(self.interrupt_path).touch()\n        \n    def lower_interruption(self):\n        if os.path.isfile(self.interrupt_path):\n            os.unlink(self.interrupt_path)\n    \n    def is_interrupted(self):\n        \"\"\" Either programmatically 'interrupted' (from the GUI) or by the user \n        in batch mode through fs.settings.skip_calc \"\"\"\n        return (os.path.isfile(self.interrupt_path)\n                or fs.settings.skip_calc)\n\n    @property\n    def ny(self):\n        return int(self.nx / self.xy_ratio + 0.5)\n\n    @property\n    def dy(self):\n        return self.dx / self.xy_ratio\n\n    @property\n    def px(self):\n        if not(hasattr(self, \"_px\")): # is None:\n            self._px = self.dx / self.nx\n        return self._px\n\n    @property\n    def multiprocess_dir(self):\n        \"\"\" Directory used for multiprocess stdout stderr streams redirection\n        :meta private:\n        \"\"\"\n        return os.path.join(self.directory, \"multiproc_calc\")\n\n    @property\n    def Xrange_complex_type(self):\n        \"\"\" Return True if the data type is a xrange array\n        :meta private:\n        \"\"\"\n        if type(self.complex_type) is tuple:\n            type_modifier, _ = self.complex_type\n            return type_modifier == \"Xrange\"\n        return False\n\n    @property\n    def base_complex_type(self):\n        complex_type = self.complex_type\n        if type(complex_type) is tuple:\n            _, complex_type = complex_type\n        return complex_type\n\n    @property\n    def base_float_type(self):\n        select = {np.dtype(np.complex64): np.float32,\n                  np.dtype(np.complex128): np.float64}\n        return select[np.dtype(self.base_complex_type)]\n\n    @property    \n    def params(self):\n        \"\"\" Used to tag an output image or check if data is already computed\n        and stored\n        :meta private:\n        \"\"\"\n        software_params = {\n                \"Software\": \"fractalshades \" + fs.__version__,\n                \"fractal_type\": type(self).__name__,\n                # \"debug\": (\"1234567890\" * 10), # tested 10000 chars ok\n                \"datetime\": datetime.datetime.today().strftime(\n                        '%Y-%m-%d_%H:%M:%S')}\n        zoom_params = self.zoom_options\n        calc_function = self.calc_options_lastcall # TODO rename to calc_callable\n        calc_params = self.calc_options\n\n        res = dict(software_params)\n        res.update(zoom_params)\n        res[\"calc-function\"] = calc_function\n        res.update({\"calc-param_\" + k: v for (k, v) in calc_params.items()})\n\n        return res\n\n\n    def clean_up(self, calc_name):\n        \"\"\"\n        Deletes all saved data files associated with a given ``calc_name``.\n        \n        Parameters\n        ----------\n        calc_name : str\n            The string identifying the calculation run for which we want to\n            delete the files. \n        \"\"\"\n        for pattern in [\n                calc_name + \"_*.arr\",\n                calc_name + \".params\",\n                calc_name + \".report\",\n                calc_name + \"_pt*.ref\",\n                calc_name + \"_pt*.sa\"\n        ]:\n            data_dir = os.path.join(self.directory, \"data\")\n            if not os.path.isdir(data_dir):\n                return\n            with os.scandir(data_dir) as it:\n                for entry in it:\n                    if (fnmatch.fnmatch(entry.name, pattern)):\n                        os.unlink(entry.path)\n            \n    @property\n    def pts_count(self):\n        \"\"\" Return the total number of points for the current calculation \n        taking into account the `subset` parameter\n        :meta private:\n        \"\"\"\n        if self.subset is not None:\n#            print(\"in pts_count\", self.subset)\n#            print(\"in pts_count\", np.sum(self.subset[None]),\n#                  np.count_nonzero(self.subset[None]))\n            return np.count_nonzero(self.subset[None])\n        else:\n            return self.nx * self.ny\n\n\n    # The various method associated with chunk mgmt ===========================\n    def chunk_slices(self): #, chunk_size=None):\n        \"\"\"\n        Generator function\n        Yields the chunks spans (ix, ixx, iy, iyy)\n        with each chunk of size chunk_size x chunk_size\n        \"\"\"\n        # if chunk_size is None:\n        chunk_size = fssettings.chunk_size\n\n        for ix in range(0, self.nx, chunk_size):\n            ixx = min(ix + chunk_size, self.nx)\n            for iy in range(0, self.ny, chunk_size):\n                iyy = min(iy + chunk_size, self.ny)\n                yield  (ix, ixx, iy, iyy)\n\n    @property\n    def chunks_count(self):\n        \"\"\"\n        Return the total number of chunks (tiles) for the current image\n        \"\"\"\n        chunk_size = fssettings.chunk_size\n        (cx, r) = divmod(self.nx, chunk_size)\n        if r != 0:\n            cx += 1\n        (cy, r) = divmod(self.ny, chunk_size)\n        if r != 0: cy += 1\n        return cx * cy\n\n    def chunk_rank(self, chunk_slice):\n        \"\"\"\n        Return the generator yield index for chunk_slice\n        \"\"\"\n        chunk_size = fssettings.chunk_size\n        (ix, _, iy, _) = chunk_slice\n        chunk_item_x = ix // chunk_size\n        chunk_item_y = iy // chunk_size\n        (cy, r) = divmod(self.ny, chunk_size)\n        if r != 0: cy += 1\n        return chunk_item_x * cy + chunk_item_y\n\n    def chunk_from_rank(self, rank):\n        \"\"\"\n        Return the chunk_slice from the generator yield index\n        \"\"\"\n        chunk_size = fssettings.chunk_size\n        (cy, r) = divmod(self.ny, chunk_size)\n        if r != 0: cy += 1\n        chunk_item_x, chunk_item_y = divmod(rank, cy)\n        ix = chunk_item_x * chunk_size\n        iy = chunk_item_y * chunk_size\n        ixx = min(ix + chunk_size, self.nx)\n        iyy = min(iy + chunk_size, self.ny)\n        return (ix, ixx, iy, iyy)\n\n    def mask_beg_end(self, rank):\n        \"\"\" Return the span for the boolean mask index for the chunk index\n        `rank` \"\"\"\n        if self._mask_beg_end is None:\n            arr = np.empty((self.chunks_count + 1,), dtype=np.int32)\n            arr[0] = 0\n            for i, chunk_slice in enumerate(self.chunk_slices()):\n                (ix, ixx, iy, iyy) = chunk_slice\n                arr[i + 1] = arr[i] + (ixx - ix) * (iyy - iy)\n            self._mask_beg_end = arr\n        return self._mask_beg_end[rank: rank + 2]\n\n    def chunk_pts(self, chunk_slice):\n        \"\"\"\n        Return the number of compressed 1d points for this chunk_slice\n        (taking into account 2d subset bool if available)\n        \"\"\"\n        subset = self.subset\n        (ix, ixx, iy, iyy) = chunk_slice\n        if subset is not None:\n            subset_pts = np.count_nonzero(subset[chunk_slice]) # TODO : test this\n            return subset_pts\n        else:\n            return (ixx - ix) * (iyy - iy)\n\n    @property\n    def chunk_mask(self):#, chunk_slice):\n        \"\"\" Legacy - simple alias \"\"\"\n        return self.subset\n#        subset = self.subset\n#        if subset is not None:\n#            return ~subset # np.ravel(subset[chunk_slice])\n#        else:\n#            return None\n\n    def c_chunk(self, chunk_slice):\n        \"\"\"\n        Returns a chunk of c_vec for the calculation\n        Parameters\n         - chunk_span\n         - data_type: expected one of np.float64, np.longdouble\n        \n        Returns: \n        c_vec : [chunk_size x chunk_size] 2d-vec of type datatype\n\n        Projection availables cases :\n            - cartesian : standard cartesisan\n            - spherical : uses a spherical projection\n            - exp_map : uses an exponential map projection\n            - mixed_exp_map :  a mix of cartesian, exponential\n\n        Note : return type is always standard prec - standard range\n        \"\"\"\n        \n        (x, y)  = (self.x, self.y)\n\n        offset = self.chunk_offset(chunk_slice)\n        return (x + offset[0]) + (y + offset[1]) * 1j # TODO test this\n\n\n    def chunk_offset(self, chunk_slice, ensure_Xr=False):\n        \"\"\"\n        Only computes the delta around ref central point for different projections\n        Note : return type is always standard prec - standard or extended range\n        \n        ensure_Xr : enforce extended range if True\n        \"\"\"\n#        select = {np.complex256: np.float128,\n#                  np.complex128: np.float64}\n        data_type = self.base_float_type # select[self.base_complex_type]\n\n        (xy_ratio, theta_deg)  = (self.xy_ratio, self.theta_deg)\n        (nx, ny, dx, dy) = (self.nx, self.ny, self.dx, self.dy)\n\n        if self.Xrange_complex_type or ensure_Xr:\n            dx_m, dx_exp = mpmath.frexp(dx)\n            dx_m = np.array(dx_m, data_type)\n            dx = fsx.Xrange_array(dx_m, dx_exp)\n            dy_m, dy_exp = mpmath.frexp(dy)\n            dy_m = np.array(dy_m, data_type)\n            dy = fsx.Xrange_array(dy_m, dy_exp)\n        else:\n            dx = float(dx)\n            dy = float(dy)\n        \n        (ix, ixx, iy, iyy) = chunk_slice\n        theta = theta_deg / 180. * np.pi\n\n        dx_grid = np.linspace(-0.5, 0.5, num=nx, dtype=data_type)\n        dy_grid = np.linspace(-0.5, 0.5, num=ny, dtype=data_type)\n        dy_vec, dx_vec  = np.meshgrid(dy_grid[iy:iyy], dx_grid[ix:ixx])\n\n        if self.antialiasing:\n            rg = np.random.default_rng(0)\n            dx_vec += (0.5 - rg.random(dx_vec.shape, dtype=data_type)) * 0.5 / nx\n            dy_vec += (0.5 - rg.random(dy_vec.shape, dtype=data_type)) * 0.5 / ny\n\n        dx_vec = dx * dx_vec\n        dy_vec = dy * dy_vec\n\n        if self.projection == \"cartesian\":\n            offset = [(dx_vec * np.cos(theta)) - (dy_vec * np.sin(theta)),\n                      (dx_vec * np.sin(theta)) + (dy_vec * np.cos(theta))]\n\n        elif self.projection == \"spherical\":\n            dr_sc = np.sqrt(dx_vec**2 + dy_vec**2) / max(dx, dy) * np.pi\n            k = np.where(dr_sc >= np.pi * 0.5, np.nan,  # outside circle\n                         np.where(dr_sc < 1.e-12, 1., np.tan(dr_sc) / dr_sc))\n            dx_vec *= k\n            dy_vec *= k\n            offset = [(dx_vec * np.cos(theta)) - (dy_vec * np.sin(theta)),\n                      (dx_vec * np.sin(theta)) + (dy_vec * np.cos(theta))]\n\n        elif self.projection == \"mixed_exp_map\":\n            # square + exp. map\n            h_max = 2. * np.pi * xy_ratio # max h reached on the picture\n            xbar = (dx_vec + 0.5 * dx - dy) / dx * h_max # 0 .. hmax\n            ybar = dy_vec / dy * 2. * np.pi              # -pi .. +pi\n            rho = dx * 0.5 * np.where(xbar > 0., np.exp(xbar), 0.)\n            phi = ybar + theta\n            dx_vec = (dx_vec + 0.5 * dx - 0.5 * dy) * xy_ratio\n            dy_vec = dy_vec * xy_ratio\n            offset = [np.where(xbar <= 0.,\n                          (dx_vec * np.cos(theta)) - (dy_vec * np.sin(theta)),\n                          rho * np.cos(phi)),\n                      np.where(xbar <= 0.,\n                          (dx_vec * np.sin(theta)) + (dy_vec * np.cos(theta)),\n                          rho * np.sin(phi))]\n\n        elif self.projection == \"exp_map\":\n            # only exp. map\n            h_max = 2. * np.pi * xy_ratio # max h reached on the picture\n            xbar = (dx_vec + 0.5 * dx - dy) / dx * h_max # 0 .. hmax\n            ybar = dy_vec / dy * 2. * np.pi              # -pi .. +pi\n            rho = dx * 0.5 * np.exp(xbar)\n            phi = ybar + theta\n            offset = [rho * np.cos(phi), rho * np.sin(phi)]\n\n        else:\n            raise ValueError(\"Projection not implemented: {}\".format(\n                              self.projection))\n        return offset\n\n    def px_chunk(self, chunk_slice):\n        \"\"\"\n        Local size of pixel for different projections\n        \"\"\"\n        data_type = self.base_float_type\n\n        xy_ratio  = self.xy_ratio\n        (nx, ny, dx, dy) = (self.nx, self.ny, self.dx, self.dy)\n        (ix, ixx, iy, iyy) = chunk_slice\n        \n        if not(self.Xrange_complex_type):\n            dx = float(dx)\n            dy = float(dy)\n        else:\n            dx_m, dx_exp = mpmath.frexp(dx)\n            dx_m = np.array(dx_m, data_type)\n            dx = fsx.Xrange_array(dx_m, dx_exp)\n            dy_m, dy_exp = mpmath.frexp(dy)\n            dy_m = np.array(dy_m, data_type)\n            dy = fsx.Xrange_array(dy_m, dy_exp)\n\n        dx_grid = dx * np.linspace(-0.5, 0.5, num=nx, dtype=data_type)\n        dy_grid = dy * np.linspace(-0.5, 0.5, num=ny, dtype=data_type)\n        dy_vec, dx_vec  = np.meshgrid(dy_grid[iy:iyy], dx_grid[ix:ixx])\n\n        if self.projection == \"cartesian\":\n            px = (dx / (nx - 1.)) #* np.ones_like(dx_vec)\n\n        elif self.projection == \"spherical\":\n            raise NotImplementedError()\n\n        elif self.projection == \"mixed_exp_map\":\n            raise NotImplementedError()\n\n        elif self.projection == \"exp_map\":\n            h_max = 2. * np.pi * xy_ratio\n            xbar = (dx_vec + 0.5 * dx - dy) / dx * h_max\n            px = (dx / (nx - 1.)) * 0.5 * h_max * np.exp(xbar)\n\n        else:\n            raise ValueError(\"Projection not implemented: {}\".format(\n                              self.projection))\n        return px\n\n\n\n    def param_matching(self, dparams):\n        \"\"\"\n        Test if the stored parameters match those of new calculation\n        /!\\ modified in subclass\n        \"\"\"\n        print(\"**CALLING param_matching +++\", self.params)\n        # TODO : note: when comparing iref should be disregarded ? \n        # or subclass specific implementation\n        UNTRACKED = [\"datetime\", \"debug\"] \n        for key, val in self.params.items():\n            if not(key in UNTRACKED) and dparams[key] != val:\n                print(\"Unmatching\", key, val, \"-->\", dparams[key])\n                return False\n#            print(\"its a match\", key, val, dparams[key] )\n        print(\"** all good\")\n        return True\n\n    def res_available(self, chunk_slice=None):\n        \"\"\"  \n        If chunk_slice is None, check that stored calculation parameters\n        matches.\n        If chunk_slice is provided, checks that calculation results are\n        available up to current self.iref\n        \"\"\"\n        try:\n            params, codes = self.reload_params()\n        except IOError:\n            return False\n        matching = self.param_matching(params)\n        if not(matching):\n            return False\n        if chunk_slice is None:\n            return matching # True\n\n        try:\n            report = self.reload_report(chunk_slice)\n        except IOError:\n            return False\n\n        if self.iref is None:\n            return report[\"iref\"] >= -1 # -2 means not yet calculated\n        else:\n            completed = (report[\"iref\"] >= self.iref)\n            not_needed = (report[\"total-glitched\"] == 0)\n            return (not_needed or completed)\n\n\n    @Multiprocess_filler(iterable_attr=\"chunk_slices\",\n                         redirect_path_attr=\"multiprocess_dir\",\n                         iter_kwargs=\"chunk_slice\")\n    def cycles(self, chunk_slice=None, SA_params=None):\n        \"\"\"\n        Fast-looping for Julia and Mandelbrot sets computation.\n\n        Parameters\n        *initialize*  function(Z, U, c) modify in place Z, U (return None)\n        *iterate*   function(Z, U, c, n) modify place Z, U (return None)\n\n        *subset*   bool arrays, iteration is restricted to the subset of current\n                   chunk defined by this array. In the returned arrays the size\n                    of axis \":\" is np.sum(subset[ix:ixx, iy:iyy]) - see below\n        *codes*  = complex_codes, int_codes, termination_codes\n        *calc_name* prefix identifig the data files\n        *chunk_slice_c* None - provided by the looping wrapper\n        \n        *iref* *ref_path* : defining the reference path, for iterations with\n            perturbation method. if iref > 0 : means glitch correction loop.\n        \n\n        \n        *gliched* boolean Fractal_Data_array of pixels that should be updated\n                  with a new ref point\n        *irefs*   integer Fractal_Data_array of pixels current ref points\n        \n        \n        Returns \n        None - save to a file. \n        *raw_data* = (chunk_mask, Z, U, stop_reason, stop_iter) where\n            *chunk_mask*    1d mask\n            *Z*             Final values of iterated complex fields shape [ncomplex, :]\n            *U*             Final values of int fields [nint, :]       np.int32\n            *stop_reason*   Byte codes -> reasons for termination [:]  np.int8\n            *stop_iter*     Numbers of iterations when stopped [:]     np.int32\n        \"\"\"\n        if self.is_interrupted():\n            return\n        if self.res_available(chunk_slice):\n            return\n\n        if self.iref is None:\n            (c, Z, U, stop_reason, stop_iter, n_stop, bool_active,\n             index_active, n_iter) = self.init_cycling_arrays(chunk_slice)\n            SA_iter = 0\n        else:\n            (c, Z, U, stop_reason, stop_iter, n_stop, bool_active,\n             index_active, n_iter, SA_iter, ref_div_iter, ref_path\n             ) = self.init_cycling_arrays(chunk_slice, SA_params)\n            # print(\"n_iter, SA_iter, ref_div_iter\", n_iter, SA_iter, ref_div_iter)\n        modified_in_cycle = np.copy(bool_active)\n\n        iterate = self._iterate\n        iref = self.iref\n\n        print(\"**/CALLING cycles looping,  n_stop\", n_stop)\n\n        if iref is None:\n            # Standard iterations\n            numba_cycles(Z, U, c, stop_reason, stop_iter, bool_active,\n                         n_iter, iterate)\n        else:\n            # Perturbation iterations\n            last_iref = (iref == self.glitch_max_attempt) \n            numba_cycles_perturb(Z, U, c, stop_reason, stop_iter, bool_active,\n                iref, n_iter, SA_iter, ref_div_iter, ref_path, iterate,\n                last_iref)\n\n        # Saving the results after cycling\n        self.update_report_mmap(chunk_slice, stop_reason)\n        print(\"#### saving\", Z.dtype)\n        print(\"#### stop_reason\", stop_reason)\n        self.update_data_mmaps(chunk_slice, Z, U, stop_reason, stop_iter,\n                               modified_in_cycle)\n\n\n\n    def init_cycling_arrays(self, chunk_slice):\n        \"\"\"\n        Prepared the chunk arrays for subsequent looping\n        \"\"\"\n        c = np.ravel(self.c_chunk(chunk_slice))\n        if self.subset is not None:\n            c = c[self.chunk_mask[chunk_slice]]\n#        c = self._2d_to_1d(self.c_chunk(chunk_slice), chunk_slice)\n\n        (n_pts,) = c.shape\n        n_Z, n_U, n_stop = (len(code) for code in self.codes)\n\n        if self.Xrange_complex_type:\n            Z = fsx.Xrange_array.zeros([n_Z, n_pts], # [n_Z, n_pts],\n                                       dtype=self.base_complex_type)\n        else:\n            Z = np.zeros([n_Z, n_pts], dtype=self.complex_type)\n        U = np.zeros([n_U, n_pts], dtype=self.int_type)\n        stop_reason = -np.ones([1, n_pts], dtype=self.termination_type)\n        stop_iter = np.zeros([1, n_pts], dtype=self.int_type)\n\n        self.initialize()(Z, U, c, chunk_slice)\n\n        # We start at 0 with all index active\n        n_iter = 0\n        index_active = np.arange(c.size, dtype=self.int_type)\n        bool_active = np.ones(c.size, dtype=np.bool)\n\n        return (c, Z, U, stop_reason, stop_iter, n_stop, bool_active,\n                index_active, n_iter)\n\n\n    # ======== The various storing files for a calculation ====================\n    @staticmethod\n    def filter_stored_codes(codes):\n        \"\"\" Don't store temporary codes - i.e. those which starts with \"_\" \"\"\"\n        return list(filter(lambda x: not(x.startswith(\"_\")), codes))\n\n    def params_path(self, calc_name=None):\n        if calc_name is None:\n            calc_name = self.calc_name\n        return os.path.join(\n            self.directory, \"data\", calc_name + \".params\")\n    \n    def serializable_params(self, params):\n        \"\"\" Some params we do not want to save as-is but only keep partial\n        information. Saving them would duplicate information + require coding\n        ad-hoc __getstate__, __setstate__ methods.\n        \"\"\"\n        unserializable = (\"calc-param_subset\",)\n        ret = {}\n        for k, v in params.items():\n            if k in unserializable:\n                if v is None:\n                    ret[k] = v\n                else:\n                    ret[k] = repr(v)\n            else:\n                ret[k] = v\n        # print(\"modified params ready to save\", ret)\n        return ret\n\n    def save_params(self):\n        \"\"\"\n        Save (pickle) current calculation parameters in data file,\n        Don't save temporary codes - i.e. those which startwith \"_\"\n        This should only be used to tag images and not to re-run a calculation.\n        \"\"\"\n        (complex_codes, int_codes, stop_codes) = self.codes\n        f_complex_codes = self.filter_stored_codes(complex_codes)\n        f_int_codes = self.filter_stored_codes(int_codes)\n        saved_codes = (f_complex_codes, f_int_codes, stop_codes)\n\n        save_path = self.params_path()\n        fsutils.mkdir_p(os.path.dirname(save_path))\n        with open(save_path, 'wb+') as tmpfile:\n            s_params = self.serializable_params(self.params)\n            pickle.dump(s_params, tmpfile, pickle.HIGHEST_PROTOCOL)\n            pickle.dump(saved_codes, tmpfile, pickle.HIGHEST_PROTOCOL)\n#        print(\"Saved calc params\", save_path)\n\n    def reload_params(self, calc_name=None): # public\n        save_path = self.params_path(calc_name)\n        with open(save_path, 'rb') as tmpfile:\n            params = pickle.load(tmpfile)\n            codes = pickle.load(tmpfile)\n            return (params, codes)\n\n    def report_path(self, calc_name=None): # public\n        if calc_name is None:\n            calc_name = self.calc_name\n        return os.path.join(\n            self.directory, \"data\", calc_name + \".report\")\n\n    def open_report_mmap(self): # private\n        \"\"\"\n        Create the memory mapping for calculation reports by chunks\n        [chunk1d_begin, chunk1d_end,\n                    iref, glitch_max_attempt, chunk_pts, chunk_glitched]\n\n        Initialized as:\n        [chunk1d_begin, chunk1d_end,\n        -2, self.glitch_max_attempt, pts_total, -2]\n        \"\"\"\n        items = self.REPORT_ITEMS\n        chunks_count = self.chunks_count\n        report_cols_count = len(items)\n\n        mmap = open_memmap(\n            filename=self.report_path(), \n            mode='w+',\n            dtype=np.int32,\n            shape=(chunks_count, report_cols_count),\n            fortran_order=False,\n            version=None)\n\n        mmap[:, items.index(\"iref\")] = -2 # -1 used if calculated\n        mmap[:, items.index(\"total-glitched\")] = -1\n        mmap[:, items.index(\"dyn-glitched\")] = -1\n        mmap[:, items.index(\"glitch_max_attempt\")] = self.glitch_max_attempt\n\n        # Number of points per chunk\n        chunk_pts = np.empty((chunks_count,), dtype=np.int32)\n        for i, chunk_slice in enumerate(self.chunk_slices()):\n            chunk_pts[i] = self.chunk_pts(chunk_slice)\n        mmap[:, items.index(\"chunk_pts\")] = chunk_pts\n\n        # full_cumsum is np.cumsum(chunk_pts) with inserted 0\n        full_cumsum = np.empty((chunks_count + 1,), dtype=np.int32)\n        np.cumsum(chunk_pts, out=full_cumsum[1:])\n        full_cumsum[0] = 0\n        mmap[:, items.index(\"chunk1d_begin\")] = full_cumsum[:-1]\n        mmap[:, items.index(\"chunk1d_end\")] = full_cumsum[1:]\n\n        del mmap\n\n    def update_report_mmap(self, chunk_slice, stop_reason): # private\n        \"\"\"\n        \"\"\"\n        items = self.REPORT_ITEMS\n        chunk_rank = self.chunk_rank(chunk_slice)\n        glitch_stop_index = self.glitch_stop_index\n        mmap = open_memmap(filename=self.report_path(), mode='r+')\n        total_glitched = dyn_glitched = 0 # Default if no glitch correction \n        if glitch_stop_index is not None:\n            total_glitched = np.count_nonzero(stop_reason >= glitch_stop_index)\n            dyn_glitched = np.count_nonzero(stop_reason == glitch_stop_index)\n        mmap[chunk_rank, items.index(\"total-glitched\")] = total_glitched\n        mmap[chunk_rank, items.index(\"dyn-glitched\")] = dyn_glitched\n        mmap[chunk_rank, items.index(\"iref\")] = (\n                self.iref if (self.iref is not None) else -1)\n#        print(\"report updated\", chunk_slice, \"iref:\", self.iref, \"chunk_glitched:\",  total_glitched)\n        \n        del mmap\n\n    def reload_report(self, chunk_slice, calc_name=None): # public\n        \"\"\" Return a report extract for the given chunk, as a dict\n             If no chunk provided, return the full report (header, report)\n#        \"\"\"\n        items = self.REPORT_ITEMS\n        mmap = open_memmap(filename=self.report_path(calc_name), mode='r')\n        if chunk_slice is None:\n            report = np.empty(mmap.shape, mmap.dtype)\n            #  print(mmap.shape, mmap.dtype)\n            report[:, :] = mmap[:, :]\n            return  self.REPORT_ITEMS, report\n        rank = self.chunk_rank(chunk_slice)\n        report = dict(zip(\n            items,\n            (mmap[rank, items.index(it)] for it in items)\n        ))\n        return report\n\n\n    def inspect_calc(self):\n        \"\"\"\n        Outputs a report for the current calculation\n        \"\"\"\n        REPORT_ITEMS, report = self.reload_report(None)\n        report_header = (\"chnk_beg|chnk_end|iref|atmt|chnk_pts|\"\n                         \"glitched|dyn glit|\")\n\n        # There are other interesting items to inspect\n        chunks_count = self.chunks_count\n\n        stop_ITEMS = [\"min_stop_iter\", \"max_stop_iter\", \"mean_stop_iter\"]\n        stop_report = np.zeros([chunks_count, 3], dtype = np.int32)\n        stop_header = \"min_stop|max_stop|mean_stp|\"\n\n        reason_ITEMS = []\n        reason_reports = []\n        reason_header = \"\"\n        reason_template = np.zeros([chunks_count, 1], dtype = np.int32)\n\n        for i, chunk_slice in enumerate(self.chunk_slices()):\n            chunk_mask, Z, U, stop_reason, stop_iter = self.reload_data(\n                chunk_slice)\n            # Outputs a summary of the stop iter\n            has_item = (stop_iter.size != 0)\n            \n#            print(\"len(stop_iter)\" , len(stop_iter),  stop_iter.shape, \"\\n\" , stop_iter)\n            for j, it in enumerate(stop_ITEMS):\n                if it == \"min_stop_iter\" and has_item:\n                    stop_report[i, j] = np.min(stop_iter)\n                elif it == \"max_stop_iter\" and has_item:\n                    stop_report[i, j] = np.max(stop_iter)\n                elif it == \"mean_stop_iter\" and has_item:\n                    stop_report[i, j] = int(np.mean(stop_iter))\n                else:\n                    stop_report[i, j] = -1\n\n            # Outputs a summary of the stop reason\n            if (stop_reason.size == 0): # Nothing to report\n                continue\n            max_chunk_reason = np.max(stop_reason)\n            for r in range(len(reason_ITEMS), max_chunk_reason + 1):\n                reason_ITEMS += [\"reason_\" + str(r)]\n                reason_reports += [reason_template.copy()]\n                reason_header += (\"reason_\" + str(r) + \"|\")\n            bc = np.bincount(np.ravel(stop_reason))\n            for r, bc_r in enumerate(bc): #range(len(reason_ITEMS)):\n#                print(\"r\", r, \"i\", i, \"len\", len(reason_ITEMS), len(reason_reports), max_chunk_reason)\n                reason_reports[r][i, 0] = bc_r\n\n        # Stack the results\n        header = REPORT_ITEMS + stop_ITEMS + reason_ITEMS\n        n_header = len(header)\n#        print(\"header\", header, n_header)\n#        print(\"report\", report)\n#        print(\"stop_report\", stop_report)\n#        print(\"reason_reports\", reason_reports)\n        full_report = np.empty((chunks_count, n_header), dtype = np.int32)\n        l1 = len(REPORT_ITEMS)\n        l2 = l1 + len(stop_ITEMS)\n        full_report[:, :l1] = report\n        full_report[:, l1:l2] = stop_report\n        for i in range(l2, n_header):\n            r = i - l2\n            full_report[:, i] = reason_reports[r][:, 0]\n#        print(\"full_report\", full_report)\n\n        # https://numpy.org/doc/stable/reference/generated/numpy.savetxt.html\n        outpath = os.path.join(self.directory, self.calc_name + \".inspect\")\n        np.savetxt(\n            outpath,\n            full_report,\n            fmt=('%8i|%8i|%4i|%4i|%8i|%8i|%8i|%8i|%8i|%8i|'\n                 + '%8i|' * len(reason_ITEMS)),\n            header=(report_header + stop_header + reason_header),\n            comments=''\n        )\n\n\n    def data_path(self, calc_name=None):\n        if calc_name is None:\n            calc_name = self.calc_name\n        keys = [\"chunk_mask\"] + self.SAVE_ARRS \n        def file_map(key):\n            return os.path.join(self.directory, \"data\",\n                                calc_name + \"_\" + key + \".arr\")\n        return dict(zip(keys, map(file_map, keys)))\n\n    def open_data_mmaps(self):\n        \"\"\"\n        Creates the memory mappings for calculated arrays\n        [chunk_mask, Z, U, stop_reason, stop_iter]\n        \n        Note : chunk_mask can be initialized here\n        \"\"\"\n#        items = self.REPORT_ITEMS\n        keys = self.SAVE_ARRS #[\"\"Z\", \"U\", \"stop_reason\", \"stop_iter\"]\n        data_type = {\n            # \"chunk_mask\": np.bool,\n            \"Z\": self.complex_type, # TODO Xrange array\n            \"U\": self.int_type,\n            \"stop_reason\": self.termination_type,\n            \"stop_iter\": self.int_type,\n        }\n        if self.Xrange_complex_type:\n            data_type[\"Z\"] = np.dtype([\n                    ('mantissa', self.base_complex_type),\n                    ('exp', np.int32)\n            ], align=False)\n        data_path = self.data_path()\n\n        pts_count = self.pts_count # the memmap 1st dim\n        (complex_codes, int_codes, stop_codes) = self.codes\n        # keep only the one which do not sart with \"_\"\n        f_complex_codes = self.filter_stored_codes(complex_codes)\n        f_int_codes = self.filter_stored_codes(int_codes)\n        n_Z, n_U, n_stop = (len(codes) for codes in \n                            (f_complex_codes, f_int_codes, stop_codes))\n        # Followin C row-major order --> arr[x, :] shall be fast\n        data_dim = {\n            # \"chunk_mask\": (pts_count,),\n            \"Z\": (n_Z, pts_count),\n            \"U\": (n_U, pts_count),\n            \"stop_reason\": (1, pts_count),\n            \"stop_iter\": (1, pts_count),\n        }\n\n        for key in keys:\n            mmap = open_memmap(\n                filename=data_path[key], \n                mode='w+',\n                dtype=data_type[key],\n                shape=data_dim[key],\n                fortran_order=False,\n                version=None)\n            del mmap\n\n        # Store the chunk_mask (if there is one) at this stage : it is already\n        # known\n        # /!\\ the size of the chunk_mask is always the same, irrespective of\n        # the number of items masked\n        if self.subset is not None:\n            \n            mmap = open_memmap(\n                filename=data_path[\"chunk_mask\"], \n                mode='w+',\n                dtype=np.bool,\n                shape=(self.nx * self.ny,),\n                fortran_order=False,\n                version=None)\n            for i, chunk_slice in enumerate(self.chunk_slices()):\n                beg_end = self.mask_beg_end(i)\n                mmap[beg_end[0]: beg_end[1]] = self.chunk_mask[chunk_slice]\n\n\n    def update_data_mmaps(self, chunk_slice, Z, U, stop_reason, stop_iter,\n                          modified_in_cycle):\n        keys = self.SAVE_ARRS\n        items = self.REPORT_ITEMS\n        data_path = self.data_path()\n        arr_map = {\n            \"Z\": Z,\n            \"U\": U,\n            \"stop_reason\": stop_reason,\n            \"stop_iter\": stop_iter,\n        }\n        report_mmap = open_memmap(filename=self.report_path(), mode='r')\n        rank = self.chunk_rank(chunk_slice)\n        beg = report_mmap[rank, items.index(\"chunk1d_begin\")]\n        end = report_mmap[rank, items.index(\"chunk1d_end\")]\n\n        # codes mapping - taking into account suppressed fields (starting with\n        # \"_\")\n        (complex_codes, int_codes, stop_codes) = self.codes\n        # keep only the one which do not sart with \"_\"\n        f_complex_codes = self.filter_stored_codes(complex_codes)\n        f_int_codes = self.filter_stored_codes(int_codes)\n        n_Z, n_U, n_stop = (len(codes) for codes in \n                            (f_complex_codes, f_int_codes, stop_codes))\n        codes_index_map = {\n            \"Z\": (range(n_Z), list(complex_codes.index(f_complex_codes[i]) \n                                   for i in range(n_Z))),\n            \"U\": (range(n_U), list(int_codes.index(f_int_codes[i])\n                                     for i in range(n_U))),\n            \"stop_reason\": (range(1), range(1)),\n            \"stop_iter\": (range(1), range(1))\n        }\n\n        for key in keys:\n            mmap = open_memmap(filename=data_path[key], mode='r+')\n            arr = arr_map[key]\n\n            fancy_indexing = np.arange(beg, end, dtype=np.int32)\n            fancy_indexing = fancy_indexing[modified_in_cycle]\n\n            for (field, f_field) in zip(*codes_index_map[key]):\n                mmap[field, fancy_indexing] = arr[f_field, modified_in_cycle]\n\n    def reload_data(self, chunk_slice, calc_name=None): # public\n        \"\"\" Reload all strored raw arrays for this chunk : \n        raw_data = chunk_mask, Z, U, stop_reason, stop_iter\n        \"\"\"\n        keys = self.SAVE_ARRS\n        items = self.REPORT_ITEMS\n        # Retrieve 1d-coordinates for this chunck\n        report_mmap = open_memmap(filename=self.report_path(calc_name),\n                                  mode='r')\n        rank = self.chunk_rank(chunk_slice)\n        beg = report_mmap[rank, items.index(\"chunk1d_begin\")]\n        end = report_mmap[rank, items.index(\"chunk1d_end\")]\n\n        arr = dict()\n        data_path = self.data_path(calc_name)\n        for key in keys:\n            mmap = open_memmap(filename=data_path[key], mode='r')\n            arr[key] = mmap[:, beg:end]\n\n        # Here we can t always rely on self.subset, it has to be consistent\n        # with calc_name ie loaded from params options\n        subset = self.subset\n        if calc_name is not None:\n            params, _ = self.reload_params(calc_name)\n            subset = params[\"calc-param_subset\"]\n            \n        if subset is not None:\n            # /!\\ fixed-size irrespective of the mask\n            mmap = open_memmap(filename=data_path[\"chunk_mask\"], mode='r')\n            beg_end = self.mask_beg_end(rank)\n            arr[\"chunk_mask\"] = mmap[beg_end[0]: beg_end[1]]\n        else:\n            arr[\"chunk_mask\"] = None\n        \n        return (arr[\"chunk_mask\"], arr[\"Z\"], arr[\"U\"], arr[\"stop_reason\"],\n                arr[\"stop_iter\"])\n\n\n    @staticmethod\n    def kind_from_code(code, codes):\n        \"\"\"\n        codes as returned by \n        (params, codes) = self.reload_data_chunk(chunk_slice, calc_name)\n        Used for \"raw\" post-processing\n        \"\"\"\n        complex_codes, int_codes, _ = codes\n        if code in complex_codes:\n            kind = \"complex\"\n        elif code in int_codes:\n            kind = \"int\"\n        elif code == \"stop_reason\":\n            kind = code\n        elif code == \"stop_iter\":\n            kind = code\n        else:\n            raise KeyError(\"raw data code unknow: \" + code, complex_codes,\n                           int_codes, \"stop_reason\", \"stop_iter\")\n        return kind\n\n    @staticmethod\n    def reshape2d(chunk_array, chunk_mask, chunk_slice):\n        \"\"\"\n        Returns 2d versions of the 1d stored vecs\n               chunk_array of size (n_post, n_pts)\n        \n        # note : to get a 2-dimensionnal vec do:\n                 if bool_mask is not None:\n                 we need to inverse\n                     chunk_mask = np.ravel(subset[chunk_size])\n                     c = c[chunk_mask]\n        \"\"\"\n        (ix, ixx, iy, iyy) = chunk_slice\n        nx, ny = ixx - ix, iyy - iy\n\n        n_post, n_pts = chunk_array.shape\n        if chunk_mask is None:\n            chunk_2d = np.copy(chunk_array)\n        else:\n            indices = np.arange(nx * ny)[chunk_mask]\n            chunk_2d = np.empty([n_post, nx * ny], dtype=chunk_array.dtype)\n            chunk_2d[:] = np.nan\n            chunk_2d[:, indices] = chunk_array\n\n        return np.reshape(chunk_2d, [n_post, nx, ny])\n    \n    @staticmethod\n    def index2d(index_1d, chunk_mask, chunk_slice):\n        \"\"\" Return the 2d-indexing from 1d + mask \n        chunk_mask = None | self.subset[chunk_slice]\n        \"\"\"\n        # chunk_size = fssettings.chunk_size\n        (ix, ixx, iy, iyy) = chunk_slice\n        nx, ny = ixx - ix, iyy - iy\n        ix, iy = np.indices((nx, ny))\n        ix = np.ravel(ix)\n        iy = np.ravel(iy)\n        if chunk_mask is not None:\n            ix = ix[chunk_mask]\n            iy = iy[chunk_mask]\n        return ix[index_1d], iy[index_1d]\n\n    @staticmethod\n    def codes_mapping(complex_codes, int_codes, termination_codes):\n        \"\"\"\n        Utility function, returns the inverse mapping code -> int\n        \"\"\"\n        complex_dic, int_dic, termination_dic = [dict(\n            zip(tab, range(len(tab)))) for tab in [\n            complex_codes, int_codes, termination_codes]]\n        return complex_dic, int_dic, termination_dic\n\n    @staticmethod\n    def subsubset(bool_set, bool_subset_of_set):\n        \"\"\"\n        Returns boolean array for a subset\n        Parameters    \n         - *bool_set* bool array of shape N, defines a set \n         - *bool_subset_of_set* bool array of shape Card(set)\n        Returns\n         - *bool_subset* bool array of shape N\n        \"\"\"\n        set_count = np.sum(bool_set)\n        Card_set, = np.shape(bool_subset_of_set)\n        if Card_set != set_count:\n            raise ValueError(\"Expected bool_subset_of_set of shape\"\n                             \" [Card(set)]\")\n        bool_subset = np.copy(bool_set)\n        bool_subset[bool_set] = bool_subset_of_set\n        return bool_subset\n\n    def postproc(self, postproc_batch, chunk_slice):\n        \"\"\" Computes the output of ``postproc_batch`` for chunk_slice\n        Return\n          post_array of shape(nposts, chunk_n_pts)\n          chunk_mask\n        \"\"\"\n        if postproc_batch.fractal is not self:\n            raise ValueError(\"Postproc batch from a different factal provided\")\n\n        # Input data\n        calc_name = postproc_batch.calc_name\n        chunk_mask, Z, U, stop_reason, stop_iter = self.reload_data(\n                chunk_slice, calc_name)\n        # View casting Z as extended-range if needed\n        if self.Xrange_complex_type:\n            Z = Z.view(fsx.Xrange_array)\n\n        params, codes = self.reload_params(calc_name)\n        complex_dic, int_dic, termination_dic = self.codes_mapping(*codes)\n        postproc_batch.set_chunk_data(chunk_slice, chunk_mask, Z, U,\n            stop_reason, stop_iter, complex_dic, int_dic, termination_dic)\n\n        # Output data\n        n_pts = Z.shape[1]  # Z of shape [n_Z, n_pts]\n        post_array = np.empty((len(postproc_batch.posts), n_pts),\n                               dtype=self.float_postproc_type)\n\n        for i, postproc in enumerate(postproc_batch.posts.values()):\n\n            val, context_update = postproc[chunk_slice]\n            # Debug\n#            if np.iscomplexobj(val):\n#                raise ValueError(val, \"i\", i, postproc.key)\n            post_array[i, :]  = val\n            postproc_batch.update_context(chunk_slice, context_update)\n\n        postproc_batch.clear_chunk_data()\n\n        return post_array, chunk_mask\n\n\n# Numba JIT functions =========================================================\n@numba.njit\ndef numba_cycles_perturb(Z, U, c, stop_reason, stop_iter, bool_active, iref,\n                n_iter, SA_iter, ref_div_iter, ref_path, iterate,\n                last_iref):\n    \"\"\" Run the perturbation cycles\n    \"\"\"\n    npts = c.size\n    n_iter_init = n_iter\n    for ipt in range(npts):\n        # skip this ipt if pixel not active\n        if not(bool_active[ipt]):\n            continue\n        Zpt = Z[:, ipt]\n        Upt = U[:, ipt]\n        cpt = c[ipt]\n        stop_pt = stop_reason[:, ipt]\n        n_iter = n_iter_init\n        cycling = True\n        while cycling:\n            n_iter += 1 \n            iterate(Zpt, Upt, cpt, stop_pt, n_iter, SA_iter,\n                    ref_div_iter, ref_path[n_iter - 1 , :],\n                    ref_path[n_iter, :], last_iref)\n            cycling = (stop_pt[0] == -1)\n            if not(cycling):\n                stop_iter[0, ipt] = n_iter\n                stop_reason[0, ipt] = stop_pt[0]\n\n@numba.njit\ndef numba_cycles(Z, U, c, stop_reason, stop_iter, bool_active,\n                 n_iter, iterate):\n    \"\"\" Run the standard cycles\n    \"\"\"\n    npts = c.size\n    n_iter_init = n_iter\n    for ipt in range(npts):\n        # skip this ipt if pixel not active\n        if not(bool_active[ipt]):\n            continue\n        Zpt = Z[:, ipt]\n        Upt = U[:, ipt]\n        cpt = c[ipt]\n        stop_pt = stop_reason[:, ipt]\n        n_iter = n_iter_init\n        cycling = True\n        while cycling:\n            n_iter += 1 \n            iterate(Zpt, Upt, cpt, stop_pt, n_iter)\n            cycling = (stop_pt[0] == -1)\n            if not(cycling):\n                stop_iter[0, ipt] = n_iter\n                stop_reason[0, ipt] = stop_pt[0]\n", "meta": {"hexsha": "7a025344944be81853088bb33d1b0b5131c9a63b", "size": 61759, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/fractalshades/core.py", "max_stars_repo_name": "GBillotey/Fractal-shades", "max_stars_repo_head_hexsha": "99c690cb1114ab7edcbfd9836af585fed2b133e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-03-06T18:32:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T01:35:21.000Z", "max_issues_repo_path": "src/fractalshades/core.py", "max_issues_repo_name": "GBillotey/Fractal-shades", "max_issues_repo_head_hexsha": "99c690cb1114ab7edcbfd9836af585fed2b133e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fractalshades/core.py", "max_forks_repo_name": "GBillotey/Fractal-shades", "max_forks_repo_head_hexsha": "99c690cb1114ab7edcbfd9836af585fed2b133e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9593058049, "max_line_length": 103, "alphanum_fraction": 0.57525219, "include": true, "reason": "import numpy,from numpy,import numba,import mpmath", "num_tokens": 14361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3593641588823761, "lm_q1q2_score": 0.19229519672268341}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# TODO\n\"\"\"\n\n\"\"\"\n\nimport argparse\nimport json\n\nimport numpy as np\n\nimport apbs as apbs\nimport MDAnalysis as mda\n\n\ndef main(argdict):\n    \"\"\" Main function for entry point checking.\n\n    Expects a dictionary of command line arguments.\n    \"\"\"\n\n    # make sure ionic strength arrays have same length:\n    if len(argdict[\"ionic_radii\"]) is not len(argdict[\"ionic_charges\"]):\n        raise ValueError(\"need as many ionic_radii as ionic_charges\")\n    if (\n        len(argdict[\"ionic_concentrations\"])\n        is not len(argdict[\"ionic_charges\"])\n    ):\n        raise ValueError(\"need as many ionic_concentrations as ionic_charges\")\n\n    # make ionic parameters a list of tuples:\n    ionic_params = zip(\n        argdict[\"ionic_charges\"],\n        argdict[\"ionic_concentrations\"],\n        argdict[\"ionic_radii\"]\n    )\n\n    # make sure there are no signs in filename that apbs dislikes:\n    if \"=\" in argdict[\"out_basename\"]:\n        raise RuntimeError(\"out_basename may not contain '=' character\")\n\n    # write log of the parameters used to call this script:\n    logfile = argdict[\"out_basename\"] + \"_gromacs2apbs_logfile_.json\"\n    with open(logfile, \"w\") as f:\n        print(json.dumps(argdict, sort_keys=True, indent=4),\n              file=f)\n\n    # load input PQR file:\n    u = mda.Universe(argdict[\"in_pqr\"])\n\n    # select atoms for coarse and fine regions:\n    sel_coarse = u.select_atoms(argdict[\"sel_coarse\"])\n    sel_fine = u.select_atoms(argdict[\"sel_fine\"])\n\n    # determine center of coarse and fine grid:\n    cog_coarse = sel_coarse.center_of_geometry()\n    cog_fine = sel_fine.center_of_geometry()\n\n    # determine length of coarse and fine grid:\n    # (scaling factor is used to ensure the boundary is far from the atoms)\n    bb_coarse = sel_coarse.bbox()\n    bb_fine = sel_fine.bbox()\n    len_coarse = (bb_coarse[1] - bb_coarse[0]) * argdict[\"scale_coarse\"]\n    len_fine = (bb_fine[1] - bb_fine[0]) * argdict[\"scale_fine\"]\n\n    # estimate minimal integer constant that will ensure specified grid spacing:\n    nlev = 4    # for mg-auto this is always 4!\n    c = np.ceil((len_fine/argdict[\"grid_spacing\"] - 1)/(pow(2, nlev + 1)))\n\n    # calculate number of grid points according to this:\n    dime = c*pow(2, nlev + 1) + 1\n\n    # write coarse selection to a PQR file:\n    out_pqr_name = argdict[\"out_basename\"] + \"_.pqr\"\n    sel_coarse.write(out_pqr_name)\n\n    # will read data from the modified PQR file set up above:\n    read_block = apbs.ApbsInputReadBlock()\n    read_block.add_mol_input(\"pqr\", argdict[\"out_basename\"] + \"_.pqr\")\n\n    # set up focusing finite difference calculation:\n    elec_block = apbs.ApbsInputElecBlock()\n\n    # which outputs to calculate and write out:\n    elec_block.set_calcenergy(argdict[\"calc_energy\"])\n    elec_block.set_calcforce(argdict[\"calc_force\"])  # requires spline surfaces\n    elec_block.add_output(\n        \"charge\", \"dx\", (argdict[\"out_basename\"] + \"_gridval-charge_\")\n    )\n    elec_block.add_output(\n        \"pot\", \"dx\", (argdict[\"out_basename\"] + \"_gridval-potential_\")\n    )\n    elec_block.add_output(\n        \"lap\", \"dx\", (argdict[\"out_basename\"] + \"_gridval-laplacian_\")\n    )\n\n    # grid size:\n    elec_block.set_cgcent(list(cog_coarse))\n    elec_block.set_cglen(list(len_coarse))\n    elec_block.set_fgcent(list(cog_fine))\n    elec_block.set_fglen(list(len_fine))\n    elec_block.set_dime(dime[0], dime[1], dime[2])\n\n    # methods to use and algorithmic parameters:\n    elec_block.set_chgm(argdict[\"chgm\"])\n    elec_block.set_pbetype(argdict[\"pbetype\"])\n    elec_block.set_sdens(argdict[\"sdens\"])\n\n    # physical parameters:\n    elec_block.set_pdie(argdict[\"pdie\"])\n    elec_block.set_sdie(argdict[\"sdie\"])\n    elec_block.set_srad(argdict[\"srad\"])\n    elec_block.set_temp(argdict[\"temp\"])\n\n    # ionic strength:\n    for charge, conc, radius in ionic_params:\n        elec_block.add_ionic_species(charge, conc, radius)\n\n    # molecules to consider:\n    elec_block.set_mol(1)\n\n    # will print energy to screen if it is calculated:\n    if argdict[\"calc_energy\"] is \"total\":\n        print_block = apbs.ApbsInputPrintBlock(\"elecEnergy\", 1)\n\n    # write APBS input file:\n    apbs_input = apbs.ApbsInput()\n    apbs_input.add_block(read_block)\n    apbs_input.add_block(elec_block)\n    apbs_input.add_block(print_block)\n    apbs_input.write(argdict[\"out_basename\"] + \"_.in\")\n\n\nif __name__ == \"__main__\":\n\n    # parse command line arguments:\n    parser = argparse.ArgumentParser(\n        description=__doc__,\n        formatter_class=argparse.ArgumentDefaultsHelpFormatter\n    )\n\n    parser.add_argument(\n        \"-sel_coarse\",\n        type=str,\n        nargs=None,\n        default=\"all and not resname SOL WAT HOH NA CL\",\n        help=\"Selection of the system defining the coarse grid.\"\n    )\n    parser.add_argument(\n        \"-sel_fine\",\n        type=str,\n        nargs=None,\n        default=\"protein\",\n        help=\"Selection of system defining the fine grid.\"\n    )\n    parser.add_argument(\n        \"-scale_coarse\",\n        type=float,\n        nargs=None,\n        default=1.75,\n        help=\"Length coarse of grid will be this parameter times the bounding \"\n        \"box of the coarse selection.\"\n    )\n    parser.add_argument(\n        \"-scale_fine\",\n        type=float,\n        nargs=None,\n        default=1.30,\n        help=\"Length of fine grid will be this parameter times the bounding box\"\n        \" of the fine selection.\"\n    )\n    parser.add_argument(\n        \"-in_pqr\",\n        type=str,\n        nargs=None,\n        default=\"production.pqr\",\n        help=\"Input PQR file generated from a TPR file via editconf.\"\n    )\n    parser.add_argument(\n        \"-out_basename\",\n        type=str,\n        nargs=None,\n        default=\"apbs\",\n        help=\"Base name for output files, to with .pqr or .in will be added as\"\n        \" appropriate.\"\n    )\n    parser.add_argument(\n        \"-calc_energy\",\n        type=str,\n        choices=[\"no\", \"total\", \"comps\"],\n        nargs=1,\n        default=\"total\",\n        help=\"This optional keyword controls energy output from an apolar \"\n        \"solvation calculation.\"\n    )\n    parser.add_argument(\n        \"-calc_force\",\n        type=str,\n        choices=[\"no\", \"total\", \"comps\"],\n        nargs=1,\n        default=\"no\",\n        help=\"This optional keyword controls force output from an apolar \"\n        \"solvation calculation.\"\n    )\n    parser.add_argument(\n        \"-pdie\",\n        type=float,\n        nargs=None,\n        default=2.0,\n        help=\"Specify the dielectric constant of the solute molecule. This is\"\n        \" usually a value between 2 to 20, where lower values consider only\"\n        \" electronic polarization and higher values consider additional\"\n        \" polarization due to intramolecular motion.\"\n    )\n    parser.add_argument(\n        \"-sdie\",\n        type=float,\n        nargs=None,\n        default=78.5,\n        help=\"Specify the dielectric constant of the solvent. Bulk water at\"\n        \" biologically-relevant temperatures is usually modeled with a\"\n        \" dielectric constant of 78-80.\"\n    )\n    parser.add_argument(\n        \"-srad\",\n        type=float,\n        nargs=None,\n        default=1.4,\n        help=\"This keyword specifies the radius (in Å) of the solvent\"\n        \" molecules; this parameter is used to define various solvent-related\"\n        \" surfaces and volumes (see srfm (elec)). This value is usually set to\"\n        \" 1.4 Å for a water-like molecular surface and set to 0 Å for a van der\"\n        \" Waals surface.\"\n    )\n    parser.add_argument(\n        \"-temp\",\n        type=float,\n        nargs=None,\n        default=310,\n        help=\"This keyword specifies the temperature (in K) for the\"\n        \" calculation.\"\n    )\n    parser.add_argument(\n        \"-ionic_charges\",\n        type=float,\n        nargs=\"+\",\n        default=[+1, -1],\n        help=\"Array of ionic species charges (in elementary charge). Must have\"\n        \" same length as -ionic_concentrations and -ionic_radii. Default\"\n        \" parameters are for physiological NaCl.\"\n    )\n    parser.add_argument(\n        \"-ionic_concentrations\",\n        type=float,\n        nargs=\"+\",\n        default=[0.150, 0.150],\n        help=\"Array of ionic species concentrations (in M). Must have same\"\n        \"length as -ionic_charges and -ionic_radii. Default parameters are for\"\n        \"physiological NaCl.\"\n    )\n    parser.add_argument(\n        \"-ionic_radii\",\n        type=float,\n        nargs=\"+\",\n        default=[1.680, 1.937],\n        help=\"Array of ionic species radii (in Å). Must have same length as\"\n        \" -ionic_concentrations and -ionic_charges. Default parameters are for\"\n        \" physiological NaCl.\"\n    )\n    parser.add_argument(\n        \"-grid_spacing\",\n        type=float,\n        nargs=None,\n        default=1.0,\n        help=\"Desired spacing of points on the fine grid (in Å). The actual\"\n        \" grid spacing is determined internally by APBS, which for numerical\"\n        \" reasons needs a magical number of grid points in each dimension. This\"\n        \" parameter will be used to ensure that there are at least as many grid\"\n        \" points as is necessary for the grid spacing to be at least this fine\"\n        \" (but it may be finer). The grid spacing is determined individually\"\n        \" for each grid dimension. The coarse grid will use the same number of\"\n        \" grid points, but with different edge lengths.\"\n    )\n    parser.add_argument(\n        \"-chgm\",\n        type=str,\n        choices=[\"spl0\", \"spl2\", \"spl4\"],\n        nargs=None,\n        default=\"spl2\",\n        help=\"Specify the method by which the biomolecular point charges (i.e.,\"\n        \" Dirac delta functions) by which charges are mapped to the grid for a\"\n        \" multigrid (mg-manual, mg-auto, mg-para) Poisson-Boltzmann\"\n        \" calculation. As we are attempting to model delta functions, the\"\n        \" support (domain) of these discretized charge distributions is always\"\n        \" strongly dependent on the grid spacing.\"\n    )\n    parser.add_argument(\n        \"-pbetype\",\n        type=str,\n        choices=[\"lpbe\", \"npbe\", \"lrpbe\", \"nrpbe\"],\n        nargs=None,\n        default=\"lpbe\",  # TODO: default sensible?\n        help=\"Which equation to solve: linearised Poisson-Boltzmann (lpbe),\"\n        \" full (non-linear) Poisson-Boltzmann (npbe), or the respective\"\n        \" regularised variants (lrpbe, nrpbe).\"\n    )\n    parser.add_argument(\n        \"-sdens\",\n        type=float,\n        nargs=None,\n        default=10.0,\n        help=\"This keyword specifies the number of quadrature points per Å2 to\"\n        \" use in calculation surface terms (e.g., molecular surface, solvent\"\n        \" accessible surface). This keyword is ignored when srad is 0.0 (e.g.,\"\n        \" for van der Waals surfaces) or when srfm (elec) is spl2 (e.g., for\"\n        \" spline surfaces).  A typical value is 10.0.\"\n    )\n\n    # parse arguments:\n    args = parser.parse_args()\n    argdict = vars(args)\n\n    main(argdict)\n", "meta": {"hexsha": "b4691c46d8de64c0ac2bcedd1c345f04d4cf2e84", "size": 10957, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/poisson-boltzmann/gromacs2apbs.py", "max_stars_repo_name": "Inniag/nanopore-electrowetting-scripts", "max_stars_repo_head_hexsha": "5539a2b6f7b06ae8b386cf3cb1d9b9bce2c5828f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-24T17:09:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T17:09:36.000Z", "max_issues_repo_path": "scripts/poisson-boltzmann/gromacs2apbs.py", "max_issues_repo_name": "Inniag/nanopore-electrowetting-scripts", "max_issues_repo_head_hexsha": "5539a2b6f7b06ae8b386cf3cb1d9b9bce2c5828f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/poisson-boltzmann/gromacs2apbs.py", "max_forks_repo_name": "Inniag/nanopore-electrowetting-scripts", "max_forks_repo_head_hexsha": "5539a2b6f7b06ae8b386cf3cb1d9b9bce2c5828f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-28T13:52:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-28T13:52:33.000Z", "avg_line_length": 33.6104294479, "max_line_length": 80, "alphanum_fraction": 0.6327461897, "include": true, "reason": "import numpy", "num_tokens": 2714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988773, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.19229519139412724}}
{"text": "# -*- coding: UTF-8 -*-\nimport os\nimport time\nimport numpy as np\nimport tensorflow as tf\nfrom scipy.optimize import fmin_ncg\n\nfrom my_utils import load_data_for_HGNN\nfrom hessians import hessian_vector_product\n\n\ndef add_layer(input_data, in_size, out_size, act_func=None, name=None):\n    weights = tf.Variable(tf.random.normal([in_size, out_size]), name=name + '_weight')\n    biases = tf.Variable(tf.random.normal([1, out_size]) + 0.001, name=name + '_biases')\n    result = tf.matmul(input_data, weights) + biases\n    if act_func is None:\n        outputs = result\n    else:\n        outputs = act_func(result)\n    return outputs\n\n\n# def geo_eval(y_pred, U_ture, classLatMedian, classLonMedian, userLocation):\n#\n#     assert len(y_pred) == len(U_ture), \"#preds: %d, #users: %d\" % (len(y_pred), len(U_ture))\n#\n#     distances = []\n#     latlon_pred = []\n#     latlon_true = []\n#     for i in range(0, len(y_pred)):\n#         user = U_ture[i]\n#         location = userLocation[user].split(',')\n#         lat, lon = float(location[0]), float(location[1])\n#         latlon_true.append([lat, lon])\n#         prediction = str(y_pred[i])\n#         lat_pred, lon_pred = classLatMedian[prediction], classLonMedian[prediction]\n#         latlon_pred.append([lat_pred, lon_pred, y_pred[i]])\n#         distance = haversine((lat, lon), (lat_pred, lon_pred))\n#         distances.append(distance)\n#\n#     acc_at_161 = 100 * len([d for d in distances if d < 161]) / float(len(distances))\n#     # return np.mean(distances), np.median(distances), acc_at_161, distances, latlon_true, latlon_pred\n#     return np.mean(distances), np.median(distances), acc_at_161, distances, latlon_true, latlon_pred\n\n\n\"\"\" load data for HGNN model \"\"\"\ndump_file = \"../data/cmu/dump_doc_dim_128_for_hgnn.pkl\"\ndata = load_data_for_HGNN(dump_file, feature_norm='None')\n(adj, features, labels, idx_train, idx_val, idx_test, U_train, U_dev, U_test,\n classLatMedian, classLonMedian, userLocation, cluster_nodes, cluster_adj, node2cluster_arr) = data\n\n\"\"\" HGNN + influence by using tensorflow.  \"\"\"\nlearning_rate = 0.01\ngraph_emb_size = 128\ncontent_emb_size = 512\nclass_num = 129\ntraining_epochs = 100\ndisplay_epoch = 10\npatience = 10\n\nx_input = tf.compat.v1.placeholder(tf.float32, [None, content_emb_size], name='contentEmbedding')\ny_label = tf.compat.v1.placeholder(tf.int64, [None, class_num], name='LabelData')\n\nhidden_1 = add_layer(x_input, content_emb_size, 512, act_func=tf.nn.relu, name='MLP_1')\noutput_x = add_layer(hidden_1, 512, class_num, act_func=None, name='MLP_2')\n\nloss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_label, logits=output_x))\n\noptimizer = tf.compat.v1.train.AdamOptimizer(learning_rate).minimize(loss)\n\npred = tf.argmax(output_x, axis=1)\nacc = tf.equal(tf.argmax(output_x, 1), tf.argmax(y_label, 1))\nacc = tf.reduce_mean(tf.cast(acc, tf.float32))\n\n'''calculate influence '''\nall_params = tf.compat.v1.trainable_variables()\nparams = [tf.compat.v1.trainable_variables()[2]]  # only last layer's params\ngradients = tf.gradients(loss, params)\nv_placeholder = params\nhessian_vector = hessian_vector_product(loss, params, v_placeholder)\n'''calculate influence '''\n\n# Initialize the variables (i.e. assign their default value)\ninit = tf.compat.v1.global_variables_initializer()\n\n# 'Saver' op to save and restore all the variables\nsaver = tf.compat.v1.train.Saver()\n\n\ndef get_influence(test_x, test_y):\n    # Done --> predicted_loss_diffs == First step：S test(for test point which interested)、\n    # Done --> Second step：I up,loss(calculate the effect of each training point)\n    inverse_hvp = get_inverse_hvp_cg(get_test_grad_loss(test_x, test_y)[0])\n\n    num_to_remove = len(idx_train)\n    predicted_loss_diffs = list()\n    for idx_to_remove in range(0, num_to_remove):\n        single_train_feed_dict = fill_feed_dict_with_one_ex(idx_to_remove)\n        train_grad_loss_val = sess.run(gradients, feed_dict=single_train_feed_dict)\n        predicted_loss_diffs.append(np.dot(inverse_hvp, train_grad_loss_val[0].flatten()) / num_to_remove)\n    return np.array(predicted_loss_diffs)\n\n\ndef get_test_grad_loss(test_x, test_y):\n    return sess.run(gradients, {x_input: test_x, y_label: test_y})\n\n\ndef get_inverse_hvp_cg(v):\n    fmin_loss_fn = get_fmin_loss_fn(v)\n    fmin_grad_fn = get_fmin_grad_fn(v)\n\n    fmin_results = fmin_ncg(\n        f=fmin_loss_fn,\n        x0=np.concatenate(v),\n        fprime=fmin_grad_fn,  # gradient\n        fhess_p=get_fmin_hvp,\n        callback=None,\n        avextol=1e-8,\n        maxiter=20)\n\n    return get_vec_to_list_fn()(fmin_results)\n\n\ndef get_fmin_loss_fn(v):\n    def get_fmin_loss(x):\n        hessian_vector_val = minibatch_hessian_vector_val(get_vec_to_list_fn()(x))\n\n        return 0.5 * np.dot(np.concatenate(hessian_vector_val), x) - np.dot(np.concatenate(v), x)\n\n    return get_fmin_loss\n\n\ndef get_fmin_grad_fn(v):\n    def get_fmin_grad(x):\n        hessian_vector_val = minibatch_hessian_vector_val(get_vec_to_list_fn()(x))\n\n        return np.concatenate(hessian_vector_val) - np.concatenate(v)\n\n    return get_fmin_grad\n\n\ndef minibatch_hessian_vector_val(v):\n    feed_dict = fill_feed_dict_with_all_ex()\n    # Can optimize this\n    feed_dict = update_feed_dict_with_v_placeholder(feed_dict, v)\n    hessian_vector_val = sess.run(hessian_vector, feed_dict=feed_dict)\n    hessian_vector_val = np.reshape(hessian_vector_val,\n                                    np.shape(hessian_vector_val[0])[0] * np.shape(hessian_vector_val[0])[1])\n    return [hessian_vector_val]\n\n\ndef get_fmin_hvp(x, p):\n    hessian_vector_val = minibatch_hessian_vector_val(get_vec_to_list_fn()(p))\n\n    return np.concatenate(hessian_vector_val)\n\n\ndef fill_feed_dict_with_all_ex():\n    feed_dict = {\n        x_input: features[idx_train],\n        y_label: get_one_hot(labels[idx_train])\n    }\n    return feed_dict\n\n\ndef fill_feed_dict_with_one_ex(target_idx):\n    feed_dict = {\n        x_input: [features[target_idx]],\n        y_label: get_one_hot([labels[target_idx]])\n    }\n    return feed_dict\n\n\ndef update_feed_dict_with_v_placeholder(feed_dict, vec):\n    for pl_block, vec_block in zip(v_placeholder, [np.reshape(vec, v_placeholder[0].get_shape())]):\n        feed_dict[pl_block] = vec_block\n    return feed_dict\n\n\ndef get_vec_to_list_fn():\n    def vec_to_list(v):\n        return v\n\n    return vec_to_list\n\n\ndef get_one_hot(y_label):\n    one_hot_index = np.arange(len(y_label)) * class_num + y_label\n    one_hot = np.zeros((len(y_label), class_num))\n    one_hot.flat[one_hot_index] = 1\n    return one_hot\n\n\n\"\"\" start running the framework ...\"\"\"\ntf_config = tf.compat.v1.ConfigProto()\ntf_config.gpu_options.per_process_gpu_memory_fraction = 0.5  # 分配50%\ntf_config.gpu_options.allow_growth = True  # 自适应\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\n\"\"\"\"for each test sample, calculate it's influence on each training sample, i.e. inf_of_a_test_point\"\"\"\nfeatures_test, labels_test = features[idx_test], labels[idx_test]\nerror_index = list()  # !!! store the error index which should rerun after.\nfor i in range(0, len(idx_test)):\n    with tf.compat.v1.Session(config=tf_config) as sess:\n        sess.run(init)\n        try:\n            inf_of_a_test_point = get_influence([features_test[i]], get_one_hot([labels_test[i]]))\n        except Exception:\n            error_index.append(i)\n            print(\"-----------------------------------------There is a RuntimeWarning at index:\", i)\n            with open(\"./error_index.txt\", 'a') as f:\n                f.write(\"\\nTime:\" + str(time.asctime(time.localtime(time.time()))) + \"\\t\\tError_at_index:\" + str(i))\n            continue\n        else:\n            np.savetxt(\"./Res_inf_HGNN/inf_of_a_test_point{}.txt\".format(i), inf_of_a_test_point)\n            print(\"Time:\", time.asctime(time.localtime(time.time())),\n                  \"has done ---------------------------- {}\".format(i))\n\n# show and save the whole error_index\nerror_index_str = \"\\n\\nTime:\" + str(time.asctime(time.localtime(time.time()))) + \\\n                  \" \\t\\tModel:HGNN \\nAll_Error_index:\" + str(error_index)\nprint(error_index_str)\nwith open(\"./error_index.txt\", 'a') as f:\n    f.write(error_index_str)\n", "meta": {"hexsha": "a6d4b47428f8ccc6fc36e58c71bc900d54ca2f78", "size": 8122, "ext": "py", "lang": "Python", "max_stars_repo_path": "influence/main_HGNN_inf.py", "max_stars_repo_name": "duzhizhai/HGNN", "max_stars_repo_head_hexsha": "1d219f9eb773e0d2f585295d6fc13c2eb093d908", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "influence/main_HGNN_inf.py", "max_issues_repo_name": "duzhizhai/HGNN", "max_issues_repo_head_hexsha": "1d219f9eb773e0d2f585295d6fc13c2eb093d908", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "influence/main_HGNN_inf.py", "max_forks_repo_name": "duzhizhai/HGNN", "max_forks_repo_head_hexsha": "1d219f9eb773e0d2f585295d6fc13c2eb093d908", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0977777778, "max_line_length": 116, "alphanum_fraction": 0.6972420586, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.1922951893799161}}
{"text": "class class_FibersData:\n    def __init__(self, endo_fiber_angle,epi_fiber_angle,endo_beta_angle,epi_beta_angle,gamma_angle):\n        self.endo_fiber_angle = endo_fiber_angle\n        self.epi_fiber_angle  = epi_fiber_angle\n        self.endo_beta_angle  = endo_beta_angle\n        self.epi_beta_angle   = epi_beta_angle\n        self.gamma_angle      = gamma_angle\n\nclass matParameters:\n    def __init__(self, a_iso, b_iso, a_f, b_f, a_s, b_s, a_fs, b_fs, k):\n        self.a_iso = a_iso\n        self.b_iso = b_iso\n        self.a_f   = a_f\n        self.b_f   = b_f\n        self.a_s   = a_s\n        self.b_s   = b_s\n        self.a_fs  = a_fs\n        self.b_fs  = b_fs\n        self.k     = k\n\ndef LoadModelAnatomy(vtk_mean):\n\n    import numpy as np\n    import vtk\n    from vtk.util.numpy_support import vtk_to_numpy\n\n    reader = vtk.vtkUnstructuredGridReader()\n    reader.SetFileName(vtk_mean)\n    reader.ReadAllScalarsOn()\n    reader.ReadAllVectorsOn()\n    reader.Update()\n    data = reader.GetOutput()\n\n    n_points = data.GetNumberOfPoints()\n    n_el     = data.GetNumberOfCells()\n    Coords   =  vtk_to_numpy(data.GetPoints().GetData())\n    Els      = np.zeros((n_el,4),dtype=int)\n    for i in range(n_el):\n        cell_type = data.GetCellType(i)\n        n_nodes_el   = data.GetCell(i).GetPointIds().GetNumberOfIds()\n        for n_sel in range(n_nodes_el):\n            Els[i,n_sel] = int(data.GetCell(i).GetPointId(n_sel))\n\n    labels  = vtk_to_numpy(data.GetPointData().GetArray('labels'))\n    x_c  = vtk_to_numpy(data.GetPointData().GetArray('x_c'))\n    x_l  = vtk_to_numpy(data.GetPointData().GetArray('x_l'))\n    x_t  = vtk_to_numpy(data.GetPointData().GetArray('x_t'))\n    e_c  = vtk_to_numpy(data.GetPointData().GetVectors('e_c'))\n    e_l  = vtk_to_numpy(data.GetPointData().GetVectors('e_l'))\n    e_t  = vtk_to_numpy(data.GetPointData().GetVectors('e_t'))\n\n    Node_par_coords = np.zeros((n_points,4))\n    Node_par_coords[:,0] = labels\n    Node_par_coords[:,1] = x_c\n    Node_par_coords[:,2] = x_l\n    Node_par_coords[:,3] = x_t\n\n    faces_connectivity = np.array([[0,2,1],[0,1,3],[1,2,3],[2,0,3]])\n    Faces_Endo = []\n    start_faces = True\n    for kk in range(n_el):\n        el_points = Els[kk,:]\n        for jj in range(4):\n            if all(labels[int(v)] == 2 for v in el_points[faces_connectivity[jj]]):\n                if start_faces:\n                    Faces_Endo  = np.array(el_points[faces_connectivity[jj]],dtype=int).reshape(1,-1)\n                    start_faces = False\n                else:\n                    Faces_Endo = np.concatenate((Faces_Endo,np.array(el_points[faces_connectivity[jj]],dtype=int).reshape(1,-1)),0)\n\n    return Coords, Els, n_points, n_el, Node_par_coords, e_t, e_l, e_c, Faces_Endo\n\ndef GenerateNodalAreas(Faces_Endo,Coords):\n\n    import numpy as np\n    \n    Nodal_area  = np.zeros((Coords.shape[0],3))\n    for jj in range(Faces_Endo.shape[0]):\n        area_vector = 0.5*(np.cross(Coords[Faces_Endo[jj][1],:]-Coords[Faces_Endo[jj][0],:],Coords[Faces_Endo[jj][2],:]-Coords[Faces_Endo[jj][0],:]))\n        for ll in range(3):\n            Nodal_area[Faces_Endo[jj][ll],:] += area_vector/3.0\n    return Nodal_area\n\ndef GradientOperator_AvgBased(Coords,Els,Node_par_coords):\n    # Claudio Mancinellia , Marco Livesub  and Enrico Puppoa (2019),  \n    #     A Comparison of Methods for Gradient Field Estimation on Simplicial Meshes\n    #     in Computers & Graphics (80), 37-50, doi.org/10.1016/j.cag.2019.03.005 \n\n    import numpy as np\n\n    n_el     = Els.shape[0]\n    n_points = Coords.shape[0]\n\n    Vol_el       = np.zeros((n_el,1))\n    Nodal_volume = np.zeros((n_points,1))\n\n    dFcdx = np.zeros((n_el,n_points))\n    dFcdy = np.zeros((n_el,n_points))\n    dFcdz = np.zeros((n_el,n_points))\n\n    dFdx = np.zeros((n_points,n_points))\n    dFdy = np.zeros((n_points,n_points))\n    dFdz = np.zeros((n_points,n_points))\n\n    W = np.zeros((n_points,n_el))\n\n    for sel_el in range(n_el):\n        AA = np.zeros((3,3))\n        AA[0,0] = Coords[Els[sel_el,1],0] - Coords[Els[sel_el,0],0]\n        AA[0,1] = Coords[Els[sel_el,1],1] - Coords[Els[sel_el,0],1]\n        AA[0,2] = Coords[Els[sel_el,1],2] - Coords[Els[sel_el,0],2]\n        AA[1,0] = Coords[Els[sel_el,2],0] - Coords[Els[sel_el,0],0]\n        AA[1,1] = Coords[Els[sel_el,2],1] - Coords[Els[sel_el,0],1]\n        AA[1,2] = Coords[Els[sel_el,2],2] - Coords[Els[sel_el,0],2]\n        AA[2,0] = Coords[Els[sel_el,3],0] - Coords[Els[sel_el,0],0]\n        AA[2,1] = Coords[Els[sel_el,3],1] - Coords[Els[sel_el,0],1]\n        AA[2,2] = Coords[Els[sel_el,3],2] - Coords[Els[sel_el,0],2]\n\n        invA = np.linalg.inv(AA)\n\n        dFcdx[sel_el,Els[sel_el,0]] = - np.sum(invA[0,:])\n        dFcdx[sel_el,Els[sel_el,1]] = invA[0,0]\n        dFcdx[sel_el,Els[sel_el,2]] = invA[0,1]\n        dFcdx[sel_el,Els[sel_el,3]] = invA[0,2]\n\n        dFcdy[sel_el,Els[sel_el,0]] = -np.sum(invA[1,:])\n        dFcdy[sel_el,Els[sel_el,1]] = invA[1,0]\n        dFcdy[sel_el,Els[sel_el,2]] = invA[1,1]\n        dFcdy[sel_el,Els[sel_el,3]] = invA[1,2]\n\n        dFcdz[sel_el,Els[sel_el,0]] = -np.sum(invA[2,:])\n        dFcdz[sel_el,Els[sel_el,1]] = invA[2,0]\n        dFcdz[sel_el,Els[sel_el,2]] = invA[2,1]\n        dFcdz[sel_el,Els[sel_el,3]] = invA[2,2]\n\n    # dFcdx, dFcdy,dFcdz are correct, validated with FEniCs and relative errors are around 10-5\n    # only at apex they are around 1% (mesh distortion)\n\n    # Volume weighted projection\n    for i in range(n_el):\n        Vol_el[i] = 1.0/6.0*abs((Coords[Els[i,3],:]-Coords[Els[i,0],:]).dot( np.cross(Coords[Els[i,2],:]-Coords[Els[i,0],:],Coords[Els[i,1],:]-Coords[Els[i,0],:])))\n        for n_sel in Els[i]:\n            Nodal_volume[n_sel] += Vol_el[i]/4.0\n\n    for i in range(n_points):\n        Els_per_node = np.where(Els == i)[0]\n\n        for sel_el in Els_per_node: \n            dFdx[i,:] += dFcdx[sel_el,:].copy()*Vol_el[sel_el]/4.0/Nodal_volume[i]\n            dFdy[i,:] += dFcdy[sel_el,:].copy()*Vol_el[sel_el]/4.0/Nodal_volume[i]\n            dFdz[i,:] += dFcdz[sel_el,:].copy()*Vol_el[sel_el]/4.0/Nodal_volume[i]\n\n    return dFcdx, dFcdy, dFcdz,dFdx, dFdy, dFdz, Nodal_volume,Vol_el\n\ndef LoadPODmodes_FunctionalModel(POD_folder,n_modes):\n\n    import sys,os\n    import numpy as np\n\n    snapshots      = np.sort(next(os.walk(POD_folder))[2])\n    n_snapshots    = len(snapshots)-1\n    n_modes        = np.min([n_modes,n_snapshots])\n\n    for m_sel in range(n_modes):\n        Phi_matrix = np.load(POD_folder+'/Phi'+str(m_sel)+'_points.npy')\n        if m_sel == 0:\n            PHI = np.concatenate((Phi_matrix[:,0].reshape(-1,1),Phi_matrix[:,1].reshape(-1,1),Phi_matrix[:,2].reshape(-1,1)),0)\n        else:\n            pp_sel = np.concatenate((Phi_matrix[:,0].reshape(-1,1),Phi_matrix[:,1].reshape(-1,1),Phi_matrix[:,2].reshape(-1,1)),0)\n            PHI    = np.concatenate((PHI,pp_sel),1)\n\n    if os.path.isfile(POD_folder+'/Amplitudes_min_max.txt'):\n        amplitudes = np.loadtxt(POD_folder+'/Amplitudes_min_max.txt')\n        return PHI,n_modes, amplitudes[:n_modes,:]\n    elif os.path.isfile(POD_folder+'/Amplitude_range.txt'):\n        amplitudes = np.loadtxt(POD_folder+'/Amplitude_range.txt')\n        return PHI,n_modes, amplitudes[:n_modes,:]\n    else:\n        return PHI,n_modes, 0.0\n\ndef GenerateFibers(e_t_vector,e_l_vector,e_c_vector,Node_par_coords,FiberData):\n\n    import numpy as np\n\n    n_points = Node_par_coords.shape[0]\n\n    fx =  np.zeros((n_points,1))\n    fy =  np.zeros((n_points,1))\n    fz =  np.zeros((n_points,1))\n\n    sx =  np.zeros((n_points,1))\n    sy =  np.zeros((n_points,1))\n    sz =  np.zeros((n_points,1))\n\n    # Normalize fibers\n    for i in range(n_points):\n        x_c = Node_par_coords[i,1]\n        x_l = Node_par_coords[i,2]\n        x_t = Node_par_coords[i,3]\n        e_c = e_c_vector[i,:]\n        e_l = e_l_vector[i,:]\n        e_t = e_t_vector[i,:]\n\n        e_c = e_c/np.linalg.norm(e_c)\n        e_t = np.cross(e_c,e_l)\n        e_t = e_t/np.linalg.norm(e_t)\n        e_l = e_l - np.dot(e_c,e_l)*e_c\n        e_l = e_l/np.linalg.norm(e_l)\n\n        alfa_angle  = np.pi/180.0*(FiberData.epi_fiber_angle*x_t + FiberData.endo_fiber_angle*(1.0 - x_t))\n        gamma_angle = FiberData.gamma_angle*np.pi/180.0\n\n        vf_dir   = np.cos(alfa_angle)*e_c + np.sin(alfa_angle)*e_l\n        vf_dir   = vf_dir/np.linalg.norm(vf_dir)\n        vs0_dir  = - np.cos(gamma_angle)*e_t + np.sin(gamma_angle)*e_l\n        if np.linalg.norm(vs0_dir) > 0:\n            vs_dir  = vs0_dir/np.linalg.norm(vs0_dir)\n        else:\n            vs_dir = vs_0_dir\n        vs_dir = vs_dir - np.dot(vf_dir,vs_dir)*vf_dir\n        vs_dir = vs_dir / np.linalg.norm(vs_dir)\n\n        fx[i] = vf_dir[0]\n        fy[i] = vf_dir[1]\n        fz[i] = vf_dir[2]\n        sx[i] = vs_dir[0]\n        sy[i] = vs_dir[1]\n        sz[i] = vs_dir[2]\n\n    return fx[:,0],fy[:,0],fz[:,0],sx[:,0],sy[:,0],sz[:,0]\n\ndef WriteFibers2VTK(Coords,Els,fx,fy,fz,sx,sy,sz,out_file):\n    import numpy as np\n\n    outFile = open(out_file,'w')\n    outFile.write('# vtk DataFile Version 4.0\\n')\n    outFile.write('vtk output\\n')\n    outFile.write('ASCII\\n')\n    outFile.write('DATASET UNSTRUCTURED_GRID \\n')\n    outFile.write('POINTS '+str(Coords.shape[0])+' float\\n')\n    for j in range(Coords.shape[0]):\n        outFile.write(str(Coords[j,0])+' ')\n        outFile.write(str(Coords[j,1])+' ')\n        outFile.write(str(Coords[j,2])+' ')\n        outFile.write('\\n')\n    outFile.write( 'CELLS ' + str( Els.shape[0] ) + ' ' + str( (Els.shape[0]) * 5 ) )\n    outFile.write('\\n')\n    for k in range( Els.shape[0] ):\n        outFile.write( '4 ' )\n        for j in range( 4 ):\n            outFile.write( str( Els[k,j]) + ' ' )\n        outFile.write('\\n')\n    # write cell types\n    outFile.write( '\\n\\nCELL_TYPES ' + str( Els.shape[0] ) )\n    for k in range( Els.shape[0] ):\n        outFile.write( '\\n10' )\n    outFile.write('\\nPOINT_DATA '+str(Coords.shape[0])+'\\n')\n    outFile.write('VECTORS f float \\n')\n    for k in range(Coords.shape[0]):\n        outFile.write(str(fx[k])+' '+str(fy[k])+' '+str(fz[k])+' '+'\\n')\n    outFile.write('VECTORS s float \\n')\n    for k in range(Coords.shape[0]):\n        outFile.write(str(sx[k])+' '+str(sy[k])+' '+str(sz[k])+' '+'\\n')\n    outFile.close()\n    return 0", "meta": {"hexsha": "fcbbdb9d47182c62ef6e1d4bac0261b1eb39d26d", "size": 10159, "ext": "py", "lang": "Python", "max_stars_repo_path": "DeepCardioFunctions.py", "max_stars_repo_name": "sbuoso/Cardio-PINN", "max_stars_repo_head_hexsha": "c3215d91e0a637aaf6f3faf63c780dcb24141468", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-04-24T17:23:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T17:12:09.000Z", "max_issues_repo_path": "DeepCardioFunctions.py", "max_issues_repo_name": "sbuoso/Cardio-PINN", "max_issues_repo_head_hexsha": "c3215d91e0a637aaf6f3faf63c780dcb24141468", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DeepCardioFunctions.py", "max_forks_repo_name": "sbuoso/Cardio-PINN", "max_forks_repo_head_hexsha": "c3215d91e0a637aaf6f3faf63c780dcb24141468", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-28T08:52:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T17:34:50.000Z", "avg_line_length": 38.3358490566, "max_line_length": 164, "alphanum_fraction": 0.6044886308, "include": true, "reason": "import numpy", "num_tokens": 3391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.35936415202123906, "lm_q1q2_score": 0.1922951877227436}}
{"text": "# -*- coding: utf-8 -*-\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n#\n# Copyright (C) 2012-2018 GEM Foundation\n#\n# OpenQuake is free software: you can redistribute it and/or modify it\n# under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# OpenQuake is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"\nModule exports :class:`ChiouYoungs2014`.\n\"\"\"\nimport numpy as np\nimport math\n\nfrom openquake.hazardlib.gsim.base import GMPE, CoeffsTable\nfrom openquake.hazardlib import const\nfrom openquake.hazardlib.imt import PGA, PGV, SA\n\n\nclass ChiouYoungs2014(GMPE):\n    \"\"\"\n    Implements GMPE developed by Brian S.-J. Chiou and Robert R. Youngs\n    and published as \"Updated of the Chiou and Youngs NGA Model for the\n    Average Horizontal Component of Peak Ground Motion and Response Spectra\"\n    (2014, Earthquake Spectra).\n    \"\"\"\n    #: Supported tectonic region type is active shallow crust\n    DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.ACTIVE_SHALLOW_CRUST\n\n    #: Supported intensity measure types are spectral acceleration,\n    #: peak ground velocity and peak ground acceleration\n    DEFINED_FOR_INTENSITY_MEASURE_TYPES = set([\n        PGA,\n        PGV,\n        SA\n    ])\n\n    #: Supported intensity measure component is orientation-independent\n    #: measure :attr:`~openquake.hazardlib.const.IMC.RotD50`,\n    DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = const.IMC.RotD50\n\n    #: Supported standard deviation types are inter-event, intra-event\n    #: and total, see chapter \"Variance model\".\n    DEFINED_FOR_STANDARD_DEVIATION_TYPES = set([\n        const.StdDev.TOTAL,\n        const.StdDev.INTER_EVENT,\n        const.StdDev.INTRA_EVENT\n    ])\n\n    #: Required site parameters are Vs30, Vs30 measured flag\n    #: and Z1.0.\n    REQUIRES_SITES_PARAMETERS = set(('vs30', 'vs30measured', 'z1pt0'))\n\n    #: Required rupture parameters are magnitude, rake,\n    #: dip and ztor.\n    REQUIRES_RUPTURE_PARAMETERS = set(('dip', 'rake', 'mag', 'ztor'))\n\n    #: Required distance measures are RRup, Rjb and Rx.\n    REQUIRES_DISTANCES = set(('rrup', 'rjb', 'rx'))\n\n    def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):\n        \"\"\"\n        See :meth:`superclass method\n        <.base.GroundShakingIntensityModel.get_mean_and_stddevs>`\n        for spec of input and result values.\n        \"\"\"\n        # extracting dictionary of coefficients specific to required\n        # intensity measure type.\n        C = self.COEFFS[imt]\n        # intensity on a reference soil is used for both mean\n        # and stddev calculations.\n        ln_y_ref = self._get_ln_y_ref(rup, dists, C)\n        # exp1 and exp2 are parts of eq. 12 and eq. 13,\n        # calculate it once for both.\n        exp1 = np.exp(C['phi3'] * (sites.vs30.clip(-np.inf, 1130) - 360))\n        exp2 = np.exp(C['phi3'] * (1130 - 360))\n        mean = self._get_mean(sites, C, ln_y_ref, exp1, exp2)\n        stddevs = self._get_stddevs(sites, rup, C, stddev_types,\n                                    ln_y_ref, exp1, exp2)\n\n        return mean, stddevs\n\n    def _get_mean(self, sites, C, ln_y_ref, exp1, exp2):\n        \"\"\"\n        Add site effects to an intensity.\n\n        Implements eq. 13b.\n        \"\"\"\n        # we do not support estimating of basin depth and instead\n        # rely on it being available (since we require it).\n        # centered_z1pt0\n        centered_z1pt0 = self._get_centered_z1pt0(sites)\n        # we consider random variables being zero since we want\n        # to find the exact mean value.\n        eta = epsilon = 0.\n\n        ln_y = (\n            # first line of eq. 12\n            ln_y_ref + eta\n            # second line\n            + C['phi1'] * np.log(sites.vs30 / 1130).clip(-np.inf, 0)\n            # third line\n            + C['phi2'] * (exp1 - exp2)\n            * np.log((np.exp(ln_y_ref) * np.exp(eta) + C['phi4']) / C['phi4'])\n            # fourth line\n            + C['phi5']\n            * (1.0 - np.exp(-1. * centered_z1pt0 / C['phi6']))\n            # fifth line\n            + epsilon\n        )\n\n        return ln_y\n\n    def _get_stddevs(self, sites, rup, C, stddev_types, ln_y_ref, exp1, exp2):\n        \"\"\"\n        Get standard deviation for a given intensity on reference soil.\n\n        Implements equations 13 for inter-event, intra-event\n        and total standard deviations.\n        \"\"\"\n        Fmeasured = sites.vs30measured\n        Finferred = 1 - sites.vs30measured\n\n        # eq. 13 to calculate inter-event standard error\n        mag_test = min(max(rup.mag, 5.0), 6.5) - 5.0\n        tau = C['tau1'] + (C['tau2'] - C['tau1']) / 1.5 * mag_test\n\n        # b and c coeffs from eq. 10\n        b = C['phi2'] * (exp1 - exp2)\n        c = C['phi4']\n\n        y_ref = np.exp(ln_y_ref)\n        # eq. 13\n        NL = b * y_ref / (y_ref + c)\n        sigma = ((C['sig1'] + (C['sig2'] - C['sig1']) * mag_test / 1.5)\n                 * np.sqrt((C['sig3'] * Finferred + 0.7 * Fmeasured) +\n                           (1. + NL) ** 2.))\n\n        ret = []\n        for stddev_type in stddev_types:\n            assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES\n            if stddev_type == const.StdDev.TOTAL:\n                # eq. 13\n                ret += [np.sqrt(((1 + NL) ** 2) * (tau ** 2) + (sigma ** 2))]\n            elif stddev_type == const.StdDev.INTRA_EVENT:\n                ret.append(sigma)\n            elif stddev_type == const.StdDev.INTER_EVENT:\n                # this is implied in eq. 21\n                ret.append(np.abs((1 + NL) * tau))\n        return ret\n\n    def _get_ln_y_ref(self, rup, dists, C):\n        \"\"\"\n        Get an intensity on a reference soil.\n\n        Implements eq. 13a.\n        \"\"\"\n        # reverse faulting flag\n        Frv = 1. if 30 <= rup.rake <= 150 else 0.\n        # normal faulting flag\n        Fnm = 1. if -120 <= rup.rake <= -60 else 0.\n        # hanging wall flag\n\n        Fhw = np.zeros_like(dists.rx)\n        idx = np.nonzero(dists.rx >= 0.)\n        Fhw[idx] = 1.\n\n        # a part in eq. 11\n        mag_test1 = np.cosh(2. * max(rup.mag - 4.5, 0))\n\n        # centered DPP\n        centered_dpp = self._get_centered_cdpp(dists)\n        # centered_ztor\n        centered_ztor = self._get_centered_ztor(rup, Frv)\n        #\n        dist_taper = np.fmax(1 - (np.fmax(dists.rrup - 40,\n                                  np.zeros_like(dists)) / 30.),\n                             np.zeros_like(dists))\n        dist_taper = dist_taper.astype(np.float64)\n        ln_y_ref = (\n            # first part of eq. 11\n            C['c1']\n            + (C['c1a'] + C['c1c'] / mag_test1) * Frv\n            + (C['c1b'] + C['c1d'] / mag_test1) * Fnm\n            + (C['c7'] + C['c7b'] / mag_test1) * centered_ztor\n            + (C['c11'] + C['c11b'] / mag_test1) *\n            np.cos(math.radians(rup.dip)) ** 2\n            # second part\n            + C['c2'] * (rup.mag - 6)\n            + ((C['c2'] - C['c3']) / C['cn'])\n            * np.log(1 + np.exp(C['cn'] * (C['cm'] - rup.mag)))\n            # third part\n            + C['c4']\n            * np.log(dists.rrup + C['c5']\n                     * np.cosh(C['c6'] * max(rup.mag - C['chm'], 0)))\n            + (C['c4a'] - C['c4'])\n            * np.log(np.sqrt(dists.rrup ** 2 + C['crb'] ** 2))\n            # forth part\n            + (C['cg1'] + C['cg2'] / (np.cosh(max(rup.mag - C['cg3'], 0))))\n            * dists.rrup\n            # fifth part\n            + C['c8'] * dist_taper\n            * min(max(rup.mag - 5.5, 0) / 0.8, 1.0)\n            * np.exp(-1 * C['c8a'] * (rup.mag - C['c8b']) ** 2) * centered_dpp\n            # sixth part\n            + C['c9'] * Fhw * np.cos(math.radians(rup.dip)) *\n            (C['c9a'] + (1 - C['c9a']) * np.tanh(dists.rx / C['c9b']))\n            * (1 - np.sqrt(dists.rjb ** 2 + rup.ztor ** 2)\n               / (dists.rrup + 1.0))\n        )\n\n        return ln_y_ref\n\n    def _get_centered_z1pt0(self, sites):\n        \"\"\"\n        Get z1pt0 centered on the Vs30- dependent avarage z1pt0(m)\n        California and non-Japan regions\n\n        \"\"\"\n        #: California and non-Japan regions\n\n        mean_z1pt0 = (-7.15 / 4.) * np.log(((sites.vs30) ** 4. + 570.94 ** 4.)\n                                           / (1360 ** 4. + 570.94 ** 4.))\n        centered_z1pt0 = sites.z1pt0 - np.exp(mean_z1pt0)\n\n        return centered_z1pt0\n\n    def _get_centered_ztor(self, rup, Frv):\n        \"\"\"\n        Get ztor centered on the M- dependent avarage ztor(km)\n        by different fault types.\n        \"\"\"\n        if Frv == 1:\n\n            mean_ztor = max(2.704 - 1.226 * max(rup.mag - 5.849, 0.0), 0.) ** 2\n            centered_ztor = rup.ztor - mean_ztor\n        else:\n\n            mean_ztor = max(2.673 - 1.136 * max(rup.mag - 4.970, 0.0), 0.) ** 2\n            centered_ztor = rup.ztor - mean_ztor\n\n        return centered_ztor\n\n    def _get_centered_cdpp(self, dists):\n        \"\"\"\n        Get directivity prediction parameter centered on the avgerage\n        directivity prediction parameter. Here we set the centered_dpp\n        equals to zero, since the near fault directivity effect prediction is\n        off in our calculation.\n\n        \"\"\"\n        centered_dpp = 0.\n\n        return centered_dpp\n\n    #: Coefficient tables are constructed from values in tables 1 - 5\n\n    COEFFS = CoeffsTable(sa_damping=5, table=\"\"\"\\\nIMT     c1      c1a     c1b     c1c     c1d     cn      cm    c2      c3    c4     c4a  crb   c5      chm     c6      c7      c7b     c8     c8a    c8b       c9     c9a    c9b     c11      c11b        cg1        cg2       cg3     phi1       phi2      phi3     phi4     phi5   phi6  gjpit  gwn      phi1jp  phi5jp   phi6jp     tau1    tau2    sig1    sig2    sig3    sig2jp\npga   -1.5065  0.165  -0.255  -0.165  0.255  16.0875  4.9993  1.06  1.9636  -2.1  -0.5  50  6.4551  3.0956  0.4908  0.0352   0.0462  0.     0.2695  0.4833  0.9228  0.1202  6.8607  0.      -0.4536    -0.007146  -0.006758  4.2542  -0.521   -0.1417   -0.00701   0.102151  0.     300  1.5817  0.7594  -0.6846  0.459    800.        0.4     0.26    0.4912  0.3762  0.8     0.4528\npgv    2.3549  0.165  -0.0626 -0.165  0.0626  3.3024  5.423   1.06  2.3152  -2.1  -0.5  50  5.8096  3.0514  0.4407  0.0324   0.0097  0.2154 0.2695  5.      0.3079  0.1     6.5     0       -0.3834    -0.001852  -0.007403  4.3439  -0.7936  -0.0699   -0.008444  5.41      0.0202 300. 2.2306  0.335   -0.7966  0.9488   800.        0.3894  0.2578  0.4785  0.3629  0.7504  0.3918\n0.01  -1.5065  0.165  -0.255  -0.165  0.255  16.0875  4.9993  1.06  1.9636  -2.1  -0.5  50  6.4551  3.0956  0.4908  0.0352   0.0462  0.     0.2695  0.4833  0.9228  0.1202  6.8607  0.      -0.4536    -0.007146  -0.006758  4.2542  -0.521   -0.1417   -0.00701   0.102151  0.     300  1.5817  0.7594  -0.6846  0.459    800.        0.4     0.26    0.4912  0.3762  0.8     0.4528\n0.02  -1.4798  0.165  -0.255  -0.165  0.255  15.7118  4.9993  1.06  1.9636  -2.1  -0.5  50  6.4551  3.0963  0.4925  0.0352   0.0472  0.     0.2695  1.2144  0.9296  0.1217  6.8697  0.      -0.4536    -0.007249  -0.006758  4.2386  -0.5055  -0.1364   -0.007279  0.10836   0.     300  1.574   0.7606  -0.6681  0.458    800.        0.4026  0.2637  0.4904  0.3762  0.8     0.4551\n0.03  -1.2972  0.165  -0.255  -0.165  0.255  15.8819  4.9993  1.06  1.9636  -2.1  -0.5  50  6.4551  3.0974  0.4992  0.0352   0.0533  0.     0.2695  1.6421  0.9396  0.1194  6.9113  0.      -0.4536    -0.007869  -0.006758  4.2519  -0.4368  -0.1403   -0.007354  0.119888  0.     300  1.5544  0.7642  -0.6314  0.462    800.        0.4063  0.2689  0.4988  0.3849  0.8     0.4571\n0.04  -1.1007  0.165  -0.255  -0.165  0.255  16.4556  4.9993  1.06  1.9636  -2.1  -0.5  50  6.4551  3.0988  0.5037  0.0352   0.0596  0.     0.2695  1.9456  0.9661  0.1166  7.0271  0.      -0.4536    -0.008316  -0.006758  4.296   -0.3752  -0.1591   -0.006977  0.133641  0.     300  1.5502  0.7676  -0.5855  0.453    800.        0.4095  0.2736  0.5049  0.391   0.8     0.4642\n0.05  -0.9292  0.165  -0.255  -0.165  0.255  17.6453  4.9993  1.06  1.9636  -2.1  -0.5  50  6.4551  3.1011  0.5048  0.0352   0.0639  0.     0.2695  2.181   0.9794  0.1176  7.0959  0.      -0.4536    -0.008743  -0.006758  4.3578  -0.3469  -0.1862   -0.006467  0.148927  0.     300  1.5391  0.7739  -0.5457  0.436    800.        0.4124  0.2777  0.5096  0.3957  0.8     0.4716\n0.075 -0.658   0.165  -0.254  -0.165  0.254  20.1772  5.0031  1.06  1.9636  -2.1  -0.5  50  6.4551  3.1094  0.5048  0.0352   0.063   0.     0.2695  2.6087  1.026   0.1171  7.3298  0.      -0.4536    -0.009537  -0.00619   4.5455  -0.3747  -0.2538   -0.005734  0.190596  0.     300  1.4804  0.7956  -0.4685  0.383    800.        0.4179  0.2855  0.5179  0.4043  0.8     0.5022\n0.1   -0.5613  0.165  -0.253  -0.165  0.253  19.9992  5.0172  1.06  1.9636  -2.1  -0.5  50  6.8305  3.2381  0.5048  0.0352   0.0532  0.     0.2695  2.9122  1.0177  0.1146  7.2588  0.      -0.4536    -0.00983   -0.005332  4.7603  -0.444   -0.2943   -0.005604  0.230662  0.     300  1.4094  0.7932  -0.4985  0.375    800.        0.4219  0.2913  0.5236  0.4104  0.8     0.523\n0.12  -0.5342  0.165  -0.252  -0.165  0.252  18.7106  5.0315  1.06  1.9795  -2.1  -0.5  50  7.1333  3.3407  0.5048  0.0352   0.0452  0.     0.2695  3.1045  1.0008  0.1128  7.2372  0.      -0.4536    -0.009913  -0.004732  4.8963  -0.4895  -0.3077   -0.005696  0.253169  0.     300  1.3682  0.7768  -0.5603  0.377    800.        0.4244  0.2949  0.527   0.4143  0.8     0.5278\n0.15  -0.5462  0.165  -0.25   -0.165  0.25   16.6246  5.0547  1.06  2.0362  -2.1  -0.5  50  7.3621  3.43    0.5045  0.0352   0.0345  0.     0.2695  3.3399  0.9801  0.1106  7.2109  0.      -0.4536    -0.009896  -0.003806  5.0644  -0.5477  -0.3113   -0.005845  0.266468  0.     300  1.3241  0.7437  -0.6451  0.379    800.        0.4275  0.2993  0.5308  0.4191  0.8     0.5304\n0.17  -0.5858  0.165  -0.248  -0.165  0.248  15.3709  5.0704  1.06  2.0823  -2.1  -0.5  50  7.4365  3.4688  0.5036  0.0352   0.0283  0.     0.2695  3.4719  0.9652  0.115   7.2491  0.      -0.4536    -0.009787  -0.00328   5.1371  -0.5922  -0.3062   -0.005959  0.26506   0.     300  1.3071  0.7219  -0.6981  0.38     800.        0.4292  0.3017  0.5328  0.4217  0.8     0.531\n0.2   -0.6798  0.165  -0.2449 -0.165  0.2449 13.7012  5.0939  1.06  2.1521  -2.1  -0.5  50  7.4972  3.5146  0.5016  0.0352   0.0202  0.     0.2695  3.6434  0.9459  0.1208  7.2988  0.      -0.444     -0.009505  -0.00269   5.188   -0.6693  -0.2927   -0.006141  0.255253  0.     300  1.2931  0.6922  -0.7653  0.384    800.        0.4313  0.3047  0.5351  0.4252  0.8     0.5312\n0.25  -0.8663  0.165  -0.2382 -0.165  0.2382 11.2667  5.1315  1.06  2.2574  -2.1  -0.5  50  7.5416  3.5746  0.4971  0.0352   0.009   0.     0.2695  3.8787  0.9196  0.1208  7.3691  0.      -0.3539    -0.008918  -0.002128  5.2164  -0.7766  -0.2662   -0.006439  0.231541  0.     300  1.315   0.6579  -0.8469  0.393    800.        0.4341  0.3087  0.5377  0.4299  0.7999  0.5309\n0.3   -1.0514  0.165  -0.2313 -0.165  0.2313  9.1908  5.167   1.06  2.344   -2.1  -0.5  50  7.56    3.6232  0.4919  0.0352  -0.0004  0.     0.2695  4.0711  0.8829  0.1175  6.8789  0.      -0.2688    -0.008251  -0.001812  5.1954  -0.8501  -0.2405   -0.006704  0.207277  0.001  300  1.3514  0.6362  -0.8999  0.408    800.        0.4363  0.3119  0.5395  0.4338  0.7997  0.5307\n0.4   -1.3794  0.165  -0.2146 -0.165  0.2146  6.5459  5.2317  1.06  2.4709  -2.1  -0.5  50  7.5735  3.6945  0.4807  0.0352  -0.0155  0.     0.2695  4.3745  0.8302  0.106   6.5334  0.      -0.1793    -0.007267  -0.001274  5.0899  -0.9431  -0.1975   -0.007125  0.165464  0.004  300  1.4051  0.6049  -0.9618  0.462    800.        0.4396  0.3165  0.5422  0.4399  0.7988  0.531\n0.5   -1.6508  0.165  -0.1972 -0.165  0.1972  5.2305  5.2893  1.06  2.5567  -2.1  -0.5  50  7.5778  3.7401  0.4707  0.0352  -0.0278  0.0991 0.2695  4.6099  0.7884  0.1061  6.526   0.      -0.1428    -0.006492  -0.001074  4.7854  -1.0044  -0.1633   -0.007435  0.133828  0.01   300  1.4402  0.5507  -0.9945  0.524    800.        0.4419  0.3199  0.5433  0.4446  0.7966  0.5313\n0.75  -2.1511  0.165  -0.162  -0.165  0.162   3.7896  5.4109  1.06  2.6812  -2.1  -0.5  50  7.5808  3.7941  0.4575  0.0352  -0.0477  0.1982 0.2695  5.0376  0.6754  0.1     6.5     0.      -0.1138    -0.005147  -0.001115  4.3304  -1.0602  -0.1028   -0.00812   0.085153  0.034  300  1.528   0.3582  -1.0225  0.658    800.        0.4459  0.3255  0.5294  0.4533  0.7792  0.5309\n1     -2.5365  0.165  -0.14   -0.165  0.14    3.3024  5.5106  1.06  2.7474  -2.1  -0.5  50  7.5814  3.8144  0.4522  0.0352  -0.0559  0.2154 0.2695  5.3411  0.6196  0.1     6.5     0.      -0.1062    -0.004277  -0.001197  4.1667  -1.0941  -0.0699   -0.008444  0.058595  0.067  300  1.6523  0.2003  -1.0002  0.78     800.        0.4484  0.3291  0.5105  0.4594  0.7504  0.5302\n1.5   -3.0686  0.165  -0.1184 -0.165  0.1184  2.8498  5.6705  1.06  2.8161  -2.1  -0.5  50  7.5817  3.8284  0.4501  0.0352  -0.063   0.2154 0.2695  5.7688  0.5101  0.1     6.5     0.      -0.102     -0.002979  -0.001675  4.0029  -1.1142  -0.0425   -0.007707  0.031787  0.143  300  1.8872  0.0356  -0.9245  0.96     800.        0.4515  0.3335  0.4783  0.468   0.7136  0.5276\n2     -3.4148  0.1645 -0.11   -0.1645 0.11    2.5417  5.7981  1.06  2.8514  -2.1  -0.5  50  7.5818  3.833   0.45    0.0352  -0.0665  0.2154 0.2695  6.0723  0.3917  0.1     6.5     0.      -0.1009    -0.002301  -0.002349  3.8949  -1.1154  -0.0302   -0.004792  0.019716  0.203  300  2.1348  0.      -0.8626  1.11     800.        0.4534  0.3363  0.4681  0.4681  0.7035  0.5167\n3     -3.9013  0.1168 -0.104  -0.1168 0.104   2.1488  5.9983  1.06  2.8875  -2.1  -0.5  50  7.5818  3.8361  0.45    0.016   -0.0516  0.2154 0.2695  6.5     0.1244  0.1     6.5     0.      -0.1003    -0.001344  -0.003306  3.7928  -1.1081  -0.0129   -0.001828  0.009643  0.277  300  3.5752  0.      -0.7882  1.291    800.        0.4558  0.3398  0.4617  0.4617  0.7006  0.4917\n4     -4.2466  0.0732 -0.102  -0.0732 0.102  1.8957   6.1552  1.06  2.9058  -2.1  -0.5  50  7.5818  3.8369  0.45    0.0062  -0.0448  0.2154 0.2695  6.8035  0.0086  0.1     6.5     0.      -0.1001    -0.001084  -0.003566  3.7443  -1.0603  -0.0016   -0.001523  0.005379  0.309  300  3.8646  0.      -0.7195  1.387    800.        0.4574  0.3419  0.4571  0.4571  0.7001  0.4682\n5     -4.5143  0.0484 -0.101  -0.0484 0.101  1.7228   6.2856  1.06  2.9169  -2.1  -0.5  50  7.5818  3.8376  0.45    0.0029  -0.0424  0.2154 0.2695  7.0389  0.      0.1     6.5     0.      -0.1001    -0.00101   -0.00364   3.709   -0.9872   0.       -0.00144   0.003223  0.321  300  3.7292  0.      -0.656   1.433    800.        0.4584  0.3435  0.4535  0.4535  0.7     0.4517\n7.5   -5.0009  0.022  -0.101  -0.022  0.101  1.5737   6.5428  1.06  2.932   -2.1  -0.5  50  7.5818  3.838   0.45    0.0007  -0.0348  0.2154 0.2695  7.4666  0.      0.1     6.5     0.      -0.1       -0.000964  -0.003686  3.6632  -0.8274   0.       -0.001369  0.001134  0.329  300  2.3763  0.      -0.5202  1.46     800.        0.4601  0.3459  0.4471  0.4471  0.7     0.4167\n10    -5.3461  0.0124 -0.1    -0.0124 0.1    1.5265   6.7415  1.06  2.9396  -2.1  -0.5  50  7.5818  3.838   0.45    0.0003  -0.0253  0.2154 0.2695  7.77    0.      0.1     6.5     0.      -0.1       -0.00095   -0.0037    3.623   -0.7053   0.       -0.001361  0.000515  0.33   300  1.7679  0.      -0.4068  1.464    800.        0.4612  0.3474  0.4426  0.4426  0.7     0.3755\n\"\"\")\n\n\nclass ChiouYoungs2014PEER(ChiouYoungs2014):\n    \"\"\"\n    This implements the Chiou & Youngs (2014) GMPE for use with the PEER\n    tests. In this version the total standard deviation is fixed at 0.65\n    \"\"\"\n    #: Only the total standars deviation is defined\n    DEFINED_FOR_STANDARD_DEVIATION_TYPES = set([\n        const.StdDev.TOTAL,\n    ])\n    #: The PEER tests requires only PGA\n    DEFINED_FOR_INTENSITY_MEASURE_TYPES = set([\n        PGA,\n    ])\n\n    def _get_stddevs(self, sites, rup, C, stddev_types, ln_y_ref, exp1, exp2):\n        \"\"\"\n        Returns the standard deviation, which is fixed at 0.65 for every site\n        \"\"\"\n        ret = []\n        for stddev_type in stddev_types:\n            assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES\n            if stddev_type == const.StdDev.TOTAL:\n                # eq. 13\n                ret.append(0.65 * np.ones_like(sites.vs30))\n        return ret\n\n\nclass ChiouYoungs2014NearFaultEffect(ChiouYoungs2014):\n    \"\"\"\n    This implements the Chiou & Youngs (2014) GMPE include the near fault\n    effect prediction. In this version, we add the distance measure, rcdpp\n    for directivity prediction.\n\n    \"\"\"\n    #: Required distance measures are RRup, Rjb, Rx, and Rcdpp\n    REQUIRES_DISTANCES = set(('rrup', 'rjb', 'rx', 'rcdpp'))\n\n    def _get_centered_cdpp(self, dists):\n        \"\"\"\n        Get directivity prediction parameter centered on the avgerage\n        directivity prediction parameter.\n\n        \"\"\"\n        centered_dpp = dists.rcdpp\n\n        return centered_dpp\n", "meta": {"hexsha": "0d94052ccb25ebdfea12d9aec56ef610fe609fd4", "size": 21330, "ext": "py", "lang": "Python", "max_stars_repo_path": "openquake/hazardlib/gsim/chiou_youngs_2014.py", "max_stars_repo_name": "gfzriesgos/shakyground-lfs", "max_stars_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-01T00:28:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-01T00:28:24.000Z", "max_issues_repo_path": "openquake/hazardlib/gsim/chiou_youngs_2014.py", "max_issues_repo_name": "gfzriesgos/shakyground-lfs", "max_issues_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-08-31T14:14:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-11T12:53:13.000Z", "max_forks_repo_path": "openquake/hazardlib/gsim/chiou_youngs_2014.py", "max_forks_repo_name": "gfzriesgos/shakyground-lfs", "max_forks_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-08-31T14:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-17T10:06:02.000Z", "avg_line_length": 61.8260869565, "max_line_length": 373, "alphanum_fraction": 0.5499765588, "include": true, "reason": "import numpy", "num_tokens": 9804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.19229518736570467}}
{"text": "# -----------------------------------------------------------------------------\n#   @author:\n#       Tingwu Wang\n#   @brief:\n# -----------------------------------------------------------------------------\nimport numpy as np\n\nfrom .base_reward import base_reward_network\nfrom mbbl.config import init_path\nfrom mbbl.util.common import tf_networks\nfrom mbbl.util.common import tf_utils\nfrom mbbl.util.common import logger\nfrom mbbl.util.il import expert_data_util\nimport tensorflow as tf\n\n\nclass reward_network(base_reward_network):\n    '''\n        @brief:\n    '''\n\n    def __init__(self, args, session, name_scope,\n                 observation_size, action_size):\n        '''\n            @input:\n                @ob_placeholder:\n                    if this placeholder is not given, we will make one in this\n                    class.\n\n                @trainable:\n                    If it is set to true, then the policy weights will be\n                    trained. It is useful when the class is a subnet which\n                    is not trainable\n        '''\n        super(reward_network, self).__init__(\n            args, session, name_scope, observation_size, action_size\n        )\n        self._base_dir = init_path.get_abs_base_dir()\n        # load the expert data\n        self._expert_trajectory_obs = expert_data_util.load_expert_trajectory(\n            self.args.expert_data_name, self.args.traj_episode_num\n        )\n\n    def build_network(self):\n        self._build_ph()\n        self._tensor = {}\n\n        self._tensor['normalized_start_state'] = (\n            self._input_ph['start_state'] -\n            self._whitening_operator['state_mean']\n        ) / self._whitening_operator['state_std']\n        self._tensor['net_input'] = self._tensor['normalized_start_state']\n\n        # the mlp for policy\n        network_shape = [self._observation_size] + \\\n            self.args.reward_network_shape + [1]\n        num_layer = len(network_shape) - 1\n        act_type = \\\n            [self.args.reward_activation_type] * (num_layer - 1) + [None]\n        norm_type = \\\n            [self.args.reward_normalizer_type] * (num_layer - 1) + [None]\n        init_data = []\n        for _ in range(num_layer):\n            init_data.append(\n                {'w_init_method': 'normc', 'w_init_para': {'stddev': 1.0},\n                 'b_init_method': 'constant', 'b_init_para': {'val': 0.0}}\n            )\n        # init_data[-1]['w_init_para']['stddev'] = 0.01  # the output layer std\n        self._MLP = tf_networks.MLP(\n            dims=network_shape, scope='discriminator_mlp', train=True,\n            activation_type=act_type, normalizer_type=norm_type,\n            init_data=init_data\n        )\n\n        self._tensor['logits'] = self._MLP(self._tensor['net_input'])\n        self._tensor['discriminator_output'] = \\\n            tf.nn.sigmoid(self._tensor['logits'])\n        # the self.discriminator_output is the sigmoid(logit)\n        self._tensor['logOfD'] = \\\n            tf.log(self._tensor['discriminator_output'] + 1e-8)\n        self._tensor['logOf1minusD'] = \\\n            tf.log(1 - self._tensor['discriminator_output'] + 1e-8)\n\n        self._tensor['reward_output'] = tf.minimum(\n            -self._tensor['logOf1minusD'], self.args.GAN_reward_clip_value\n        )\n\n    def build_loss(self):\n        self._update_operator = {}\n        self._input_ph['if_expert_data'] = tf.placeholder(tf.float32, [None, 1],\n                                                          name='observation_gt')\n        self._tensor['if_fake_data'] = 1 - self._input_ph['if_expert_data']\n\n        # calculate the entropy\n        self._update_operator['entropy'] = tf.reduce_mean(\n            tf_utils.logit_bernoulli_entropy(self._tensor['logits'])\n        )\n        self._update_operator['entropy_loss'] = \\\n            -self.args.GAN_ent_coeff * self._update_operator['entropy']\n\n        self._update_operator['loss'] = \\\n            -tf.reduce_mean(self._tensor['if_fake_data'] *\n                            self._tensor['logOf1minusD']) + \\\n            -tf.reduce_mean(self._input_ph['if_expert_data'] *\n                            self._tensor['logOfD']) + \\\n            self._update_operator['entropy_loss']\n\n        # logging stats, real traj should be 1\n        self._tensor['expert_traj_accuracy'] = tf.reduce_sum(\n            tf.to_float(self._tensor['discriminator_output'] > 0.5)\n            * self._input_ph['if_expert_data']\n        ) / tf.reduce_sum(self._input_ph['if_expert_data'])\n\n        self._tensor['expert_average_reward'] = tf.reduce_sum(\n            self._tensor['reward_output'] * self._input_ph['if_expert_data']\n        ) / tf.reduce_sum(self._input_ph['if_expert_data'])\n\n        self._tensor['agent_traj_accuracy'] = tf.reduce_sum(\n            tf.to_float(self._tensor['discriminator_output'] < 0.5) *\n            self._tensor['if_fake_data']\n        ) / tf.reduce_sum(self._tensor['if_fake_data'])  # fake traj should be 0\n\n        self._tensor['agent_average_reward'] = tf.reduce_sum(\n            self._tensor['reward_output'] * self._tensor['if_fake_data']\n        ) / tf.reduce_sum(self._tensor['if_fake_data'])\n\n        self._update_operator['update_gan_op'] = tf.train.AdamOptimizer(\n            learning_rate=self.args.reward_lr\n        ).minimize(self._update_operator['loss'])\n\n    def train(self, data_dict, replay_buffer, training_info={}):\n        \"\"\" @brief:\n            The GAN training of the reward function\n        \"\"\"\n\n        agent_obs = data_dict['start_state']\n        training_stats = []\n\n        for i_epoch in range(self.args.reward_epochs):\n            # we start from 1 since the first state will be fixed to be 0 reward\n            agent_sample_id = self._npr.randint(\n                1, agent_obs.shape[0], self.args.gan_timesteps_per_epoch\n            )\n            # sample and process the positive data-samples\n            expert_sample_id = self._npr.randint(\n                0, self._expert_trajectory_obs.shape[0],\n                self.args.positive_negative_ratio *\n                self.args.gan_timesteps_per_epoch\n            )\n\n            feed_dict = {\n                self._input_ph['if_expert_data']: np.reshape(\n                    np.concatenate(\n                        [np.zeros(len(agent_sample_id)),\n                         np.ones(len(expert_sample_id))],\n                    ),\n                    [-1, 1]\n                ),\n                self._input_ph['start_state']: np.concatenate(\n                    [agent_obs[agent_sample_id],\n                     self._expert_trajectory_obs[expert_sample_id]]\n                )\n            }\n\n            # train the network\n            fetch_dict = {\n                'update_op': self._update_operator['update_gan_op'],\n                'reward_gan_loss': self._update_operator['loss'],\n                'expert_traj_accuracy': self._tensor['expert_traj_accuracy'],\n                'agent_traj_accuracy': self._tensor['agent_traj_accuracy'],\n                'expert_average_reward': self._tensor['expert_average_reward'],\n                'agent_average_reward': self._tensor['agent_average_reward'],\n                'entropy': self._update_operator['entropy']\n            }\n            i_training_stats = self._session.run(fetch_dict, feed_dict=feed_dict)\n            training_stats.append(i_training_stats)\n\n        training_stats = {\n            key: np.mean([training_stats[i_epoch][key]\n                          for i_epoch in range(len(training_stats))])\n            for key in training_stats[-1] if key != 'update_op'\n        }\n        self._set_whitening_var(data_dict['whitening_stats'])\n        return training_stats\n\n    def eval(self, data_dict):\n        pass\n\n    def pred(self, data_dict):\n        logger.info('This function should not be used!')\n        reward = []\n        for i_data in range(len(data_dict['action'])):\n            i_reward = self._env.reward(\n                {key: data_dict[key][i_data]\n                 for key in ['start_state', 'action']}\n            )\n            reward.append(i_reward)\n        return np.stack(reward), -1, -1\n\n    def use_groundtruth_network(self):\n        return False\n\n    def generate_rewards(self, rollout_data):\n        \"\"\"@brief:\n            This function should be called before _preprocess_data\n        \"\"\"\n        for path in rollout_data:\n            # the predicted value function (baseline function)\n            path[\"raw_rewards\"] = path['rewards']  # preserve the raw reward\n            # from mbbl.util.common.fpdb import fpdb; fpdb().set_trace()\n\n            # generate the observation pairs\n            ob_pairs = path['obs'][1: len(path['obs'])]\n\n            path[\"rewards\"] = self._session.run(\n                self._tensor['reward_output'],\n                feed_dict={self._input_ph['start_state']: ob_pairs}\n            ).flatten()\n            assert len(path[\"rewards\"]) == len(path['raw_rewards'])\n        return rollout_data\n", "meta": {"hexsha": "4dffc103c2f16423c5db61b13f9b1b68454169a8", "size": 8913, "ext": "py", "lang": "Python", "max_stars_repo_path": "mbbl_envs/mbbl/network/reward/GAN_reward.py", "max_stars_repo_name": "hbutsuak95/iv_rl", "max_stars_repo_head_hexsha": "0f72a8f077a238237027ea96b7d1160c35ac9959", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2022-01-16T11:27:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T14:04:48.000Z", "max_issues_repo_path": "mbbl_envs/mbbl/network/reward/GAN_reward.py", "max_issues_repo_name": "hbutsuak95/iv_rl", "max_issues_repo_head_hexsha": "0f72a8f077a238237027ea96b7d1160c35ac9959", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mbbl_envs/mbbl/network/reward/GAN_reward.py", "max_forks_repo_name": "hbutsuak95/iv_rl", "max_forks_repo_head_hexsha": "0f72a8f077a238237027ea96b7d1160c35ac9959", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3303167421, "max_line_length": 81, "alphanum_fraction": 0.5738808482, "include": true, "reason": "import numpy", "num_tokens": 1941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.31069439597968646, "lm_q1q2_score": 0.1922516131060939}}
{"text": "\"\"\" Module for mean-flux regulation\nPort of K-G Lee IDL code\n\"\"\"\nimport pdb\n\nimport numpy as np\n\nfrom astropy.table import Table\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\nfrom astropy.modeling import FittableModel, Parameter\n\nfrom pyigm.fN import tau_eff as pyteff\n\ntry:\n    basestring\nexcept NameError:  # For Python 3\n    basestring = str\n\n\ndef fit_forest(wave, flux, sigma, zqso, wavemin=3200., normfac=None,\n               user_mask=None, mask_dlas=None, coord=None,\n               for_lohi=(1041.,1185)):\n    \"\"\"  Perform mean-flux regulation on an input spectrum\n\n    Parameters\n    ----------\n    wave : ndarray\n      Observed wavelength values in Ang\n    flux : ndarray\n      flux array\n    sigma : ndarray\n      sigma array.  0 values are masked\n    zqso : float\n      Quasar emission redshift\n    wavemin : float, optional\n      Minimum wavelength to include in analysis\n    normfac : float, optional\n      optional scaling factor\n    user_mask : list (of lists)\n      User can mask out regions in the anaylsis `by-hand'\n    mask_dlas : Table or str, optional\n      Table of DLAs to mask based on coordinates and redshift\n        Required columns are RA, DEC, z\n      Can be the filename of the table to input\n    coord : SkyCoord, optional\n      Coordinate of the sightline.  Used to match against DLAs\n    for_lohi : tuple\n      wavemin, wavemax that define the forest for analysis\n\n    Returns\n    -------\n    new_ff : ndarray\n      Mean-flux regulated flux\n    parm : FittableModel\n      astropy model of the continuum\n    \"\"\"\n    from astropy.modeling import fitting\n\n    # invvar\n    ivar = (sigma != 0.) / (sigma**2 + (sigma == 0))\n\n    # Scale?\n    if normfac is not None:\n        ivar = ivar * normfac**2\n        flux = flux / normfac\n\n    # User Mask?\n    if user_mask is not None:\n        for imask in user_mask:\n            msk = (wave >= imask[0]) & (wave <= imask[1])\n            ivar[msk] = 0.\n\n    # DLA mask?\n    if mask_dlas is not None:\n        if coord is None:\n            raise IOError(\"Must input coord to mask DLAs\")\n        # Load DLAs, as needed\n        if isinstance(mask_dlas, basestring):\n            dlas = Table.read(mask_dlas)\n        elif isinstance(mask_dlas, Table):\n            dlas = mask_dlas\n            # Check for coord column\n            if 'coord' not in dlas.keys():\n                dla_coord = SkyCoord(ra=dlas['RA'], dec=dlas['DEC'], unit='deg')\n            else:\n                dla_coord = dlas['coord']\n        else:\n            raise IOError(\"Not ready for this type of DLA input\")\n\n        # Search\n        sep = coord.separation(dla_coord)\n        match = np.where(sep < 2*u.arcsec)[0]\n        for imatch in match:\n            zdla = dlas['z'][imatch]\n            skip_fg = np.abs(wave-1215.6701*(1+zdla)) < 100.\n            ivar[skip_fg] = 0.\n            #print, 'Removed a DLA'\n\n    # Isolate forest for analysis\n    lambda_r = wave / (1+zqso)\n    forestrange = (lambda_r >= for_lohi[0]) & (lambda_r <= for_lohi[1]) & (\n                    wave > wavemin)\n    lamb_forest = lambda_r[forestrange]\n    z_for = (lamb_forest/1215.67)*(1.+zqso) -1.  # Redshift at each pixel\n    fforest = flux[forestrange]\n    ivarforest = ivar[forestrange]\n\n    # Estimate weights for each pixel\n    var_F = forestvar(z_for) * (np.exp(-pyteff.lyman_alpha_obs(z_for)))**2\n    #var_F = forestvar(z_for) * (np.exp(-old_taueff_evo(z_for)))**2\n    var_noise = (ivarforest != 0) / (ivarforest + (ivarforest == 0))\n    var_total = var_F + var_noise\n    weights_forest = (var_total != 0) / (var_total + (var_total == 0))\n\n    # But need to make sure that masked pixels remain masked...\n    maskedpix = ivarforest == 0\n    weights_forest[maskedpix] = 0\n\n    # Astropy modeling\n    model = mflux_tauevo(p0=0., p1=0., zqso=zqso, lamb_piv=1113.)\n    fitter = fitting.LevMarLSQFitter()\n    parm = fitter(model, lamb_forest, fforest, weights=weights_forest)\n\n    # Apply\n    full_forest = lambda_r < 1220.\n    new_ff = flux\n    new_ff[full_forest] = flux[full_forest] / mfluxcorr(lambda_r[full_forest],\n                                                        parm.p0.value, parm.p1.value,\n                                                        lamb_piv=parm.lamb_piv.value)\n    # Return\n    return new_ff, parm\n\n\ndef forestvar(z_in):\n    \"\"\"  Return intrinsic variance of LyaF variance for weighting. This\n    estimate is roughly from McDonald et al 2006\n\n    Parameters\n    ----------\n    z_in : float or ndarray\n\n    Returns\n    -------\n    fvar : float or ndarray\n      Variance\n    \"\"\"\n    fvar = 0.065 * ((1.+z_in)/(1.+2.25))**3.8\n    # Return\n    return fvar\n\n\ndef mfluxcorr(lambda_r, p0, p1, lamb_piv=1113.):\n    \"\"\" Correction factor to power-law fit\n    Parameters\n    ----------\n    lambda_r\n    p\n    lamb_piv\n\n    Returns\n    -------\n\n    \"\"\"\n    lamb_piv = 1113. # This is the pivot point in the restframe spectrum\n    return p0 + p1*(lambda_r/lamb_piv - 1.)\n\n\nclass mflux_tauevo(FittableModel):\n    \"\"\" Mean flux evolution * exp(delta*(lambda/1280-1)),\n    Meant for use with astropy.modeling to correct the fitted Lya forest continuum\n    Abscissa parameter x is the restframe wavelength, and free parameters p0, p1\n    set the power law.\n    This function NEEDS the quasar redshift zqso to be set\n\n    input: lambda_r :: Rest wavelength Assumed in Angstroms\n    output: absorbed, normalized flux\n    Parameters: logN,b,z,wrest,f,gamma,fwhm\n    \"\"\"\n    inputs = ('lambda_r',)\n    outputs = ('flux',)\n\n    # Free parameters (generally)\n    p0 = Parameter()\n    p1 = Parameter()\n\n    # Fixed parameters\n    zqso = Parameter(fixed=True)\n    lamb_piv = Parameter(fixed=True)\n\n    @staticmethod\n    def evaluate(lambda_r, p0, p1, zqso, lamb_piv): #logN,b,z,wrest,f,gamma,fwhm):\n        zfor = (lambda_r/1216.) * (1. + zqso) - 1.\n        tau = pyteff.lyman_alpha_obs(zfor)\n        #tau = old_taueff_evo(zfor)\n        fmean = np.exp(-1*tau)\n\n        mfluxtauevo = fmean * mfluxcorr(lambda_r, p0, p1, lamb_piv=lamb_piv)\n        return mfluxtauevo\n\n\ndef old_taueff_evo(z):\n    \"\"\" F-G taueff.\n    Mainly for testing\n\n    Parameters\n    ----------\n    z\n\n    Returns\n    -------\n\n    \"\"\"\n    tauevo  = 0.001845 * (1+z)**3.924\n    return tauevo", "meta": {"hexsha": "78a5e769cee19c48af7721e7278a94c99c20bc30", "size": 6209, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyigm/igm/mfr.py", "max_stars_repo_name": "pyigm/pyigm", "max_stars_repo_head_hexsha": "8b4bc7f7f1c9f1c280720a4cc0693cd7cb79e9cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2016-02-12T19:03:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-11T15:16:25.000Z", "max_issues_repo_path": "pyigm/igm/mfr.py", "max_issues_repo_name": "pyigm/pyigm", "max_issues_repo_head_hexsha": "8b4bc7f7f1c9f1c280720a4cc0693cd7cb79e9cb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 204, "max_issues_repo_issues_event_min_datetime": "2015-12-06T13:40:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-11T21:48:39.000Z", "max_forks_repo_path": "pyigm/igm/mfr.py", "max_forks_repo_name": "pyigm/pyigm", "max_forks_repo_head_hexsha": "8b4bc7f7f1c9f1c280720a4cc0693cd7cb79e9cb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2015-12-06T23:27:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T10:08:24.000Z", "avg_line_length": 28.8790697674, "max_line_length": 85, "alphanum_fraction": 0.6075052343, "include": true, "reason": "import numpy,from astropy", "num_tokens": 1770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040617, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.19225160957570844}}
{"text": "import numpy as np\nfrom scipy import interpolate\nimport matplotlib\nfrom datetime import datetime\nfrom scipy.stats.mstats import mquantiles\nimport os\nfrom astropy.io import fits\nimport glob\nfrom parameters import *\nimport sys\nimport argparse\nfrom astropy.table import Table\n##sys.path.insert(0, 'python')\n# matplotlib.rc('text', usetex=True)\n# matplotlib.rcParams['text.latex.preamble'] = [r\"\\usepackage{amsmath}\",\n#                                    r\"\\usepackage{color}\"]\n# matplotlib.use('Agg')\nfrom ptemcee import Sampler as PTSampler\nimport matplotlib.pyplot as plt\n##import corner\nstartTime = datetime.now()\n\n\nparser = argparse.ArgumentParser(description=\"Calculate radial velocities and stellar parameters of WEAVE target spectra.\")\n\nparser.add_argument(\"--infile\", type=str, required=True, help=\"input file\", nargs=1)\nparser.add_argument(\"--outdir\", type=str, required=True, help=\"output directory\", nargs=1)\nparser.add_argument(\"--targlist\", type=str, required=True, help=\"path to list of FIBREIDs or TARGIDs to be analysed. To analyse all BA stars, enter 'all'.\", nargs=1)\nparser.add_argument(\"--params\", type=str, required=False, default='parameters.py', help=\"path to parameter file\", nargs=1)\n\n#parser.add_argument(\"--setups\", type=str, default=None, required=True, help=\"input setups\", nargs='*')\n\nargs = parser.parse_args()\nwrite_directory = args.outdir[0]\ntarget_list = args.targlist[0]\ndata_file = args.infile[0]\n\n\n# processing (cropping, smoothing, rebinning, rotational broadening) templates if required \n\nif process_templates==True:\n\tprint('Beginning processing of templates')\n\tfrom PyAstronomy import pyasl\n\timport scipy.stats\n\ttemplatelist = np.genfromtxt(template_list_file, dtype=None, encoding=None)\n\n\t# Ensuring the number of templates to be processed matches the number of points on the grid. \n\tnotemps = len(templatelist)\n\td_size = len(Teff) * len(logg) * len(vsini)\n\tif notemps < d_size:\n\t\tprint('ERROR: The amount of templates to be processed is less than the amount of points in the grid. Add more templates to the list or reduce the grid as necessary (see PARAMETER BOUNDARIES in parameters file).')\n\t\tsys.exit()\n\tif notemps > d_size: \n\t\tprint('ERROR: The amount of templates to be processed is greater than the amount of points in the grid. Remove templates from the list or expand the grid as necessary (see PARAMETER BOUNDARIES in parameters file).')\n\t\tsys.exit()\n\n\tdef restrict_range(w, f):\t\t# to crop the templates\n\t\tour_range = (w > template_crop_min_wav) & (w < template_crop_max_wav)\n\t\tw, f = w[our_range], f[our_range]\n\t\treturn w, f\n\n\tdef smooth(w, f, sig):\t\t# to smooth/broaden templates to match resolution of observed spectrum\n\t\tf = pyasl.broadGaussFast(w, f, sig)\n\t\treturn f\n\n\tdef rotbroad(w, f, vsini):\t\t# to rotationally broaden the templates\n\t\tf = pyasl.rotBroad(w, f, 0.6, float(vsini))\n\t\treturn f\n\n\tdef rebin(w, f, samp):\t\t# to rebin the templates to match the sampling of the observed spectrum\n\t\tf, bin_edges, binnumber = scipy.stats.binned_statistic(w, f, statistic = 'mean', bins = (w[-1] - w[0]) / samp)\n\t\tbin_width = bin_edges[1] - bin_edges[0]\n\t\tw = bin_edges[1:] - bin_width/2\n\t\treturn w, f\n\n\tdef process_template(w, f, sig=sigma, samp=sampling):\n\t\tif sigma != None:\n\t\t\tf = smooth(w, f, sig)\n\t\tif sampling != None:\n\t\t\tw, f = rebin(w, f, samp)\n\t\tfile = open(template_write_directory + '/'+ os.path.splitext(os.path.basename(i))[0] + '_processed', \"w\")\n\t\tfor index in range(len(w)):\n\t\t\tfile.write(str(w[index]) + \" \" + str(f[index]) + \"\\n\")\n\t\tfile.close()\n\t\treturn w, f\n\n\tdef process_template_vsini(w, f, vsini, sig=sigma, samp=sampling):\n\t\tf = rotbroad(w, f, vsini)\n\t\tif sigma != None:\n\t\t\tf = smooth(w, f, sig)\n\t\tif sampling != None:\n\t\t\tw, f = rebin(w, f, samp)\n\t\tfile = open(template_write_directory + '/' + os.path.splitext(os.path.basename(i))[0] + '_processed_vsini' + str(int(vsini)), \"w\")\n\t\tfor index in range(len(w)):\n\t\t\tfile.write(str(w[index]) + \" \" + str(f[index]) + \"\\n\")\n\t\tfile.close()\n\t\treturn w, f\n\n\tdef write_to_grid(templatename, f, t_ind=temp_ind, l_ind=logg_ind, v_ind=vsini_ind, vsini0=None):\n\t\t# finding the teff and logg information from the template name, to write to corresponding grid point\n\t\tt1 = float(templatename[temp_ind[0]:temp_ind[1]])\n\t\tl1 = float(templatename[logg_ind[0]:logg_ind[1]])\n\t\tif vsini0==None:\n\t\t\tv1 = float(templatename[vsini_ind[0]:vsini_ind[1]])\n\t\telse: \n\t\t\tv1 = float(vsini0)\n\n\t\tprint('Teff: ' + str(t1) + ', logg: ' + str(l1) + ', vsini: ' + str(v1))\n\n\t\td[np.where(Teff == t1)[0][0], np.where(logg == l1)[0][0], np.where(vsini == v1)[0][0]] = f\n\n\tt_wavelength_0, t_flux_0 = np.genfromtxt(templatelist[0], unpack=True, usecols=(wav_ind, flux_ind), dtype=None, encoding=None)\n\tt_wavelength_0, t_flux_0 = restrict_range(t_wavelength_0, t_flux_0)\n\tif sampling != None:\n\t\tt_wavelength_0, t_flux_0 = rebin(t_wavelength_0, t_flux_0, sampling)\n\n\td = np.zeros((len(Teff), len(logg), len(vsini), len(t_wavelength_0)))\n\td_filled = 0\n\n\tfor i in templatelist:\n\t\tprint('Processing: ' + i)\n\t\tt_wavelength, t_flux = np.genfromtxt(i, unpack=True, usecols=(wav_ind, flux_ind), dtype=None, encoding=None)\n\t\tt_wavelength, t_flux = restrict_range(t_wavelength, t_flux)\n\t\tif rotbroads == None:\n\t\t\t_, t_flux = process_template(t_wavelength, t_flux, sigma, sampling)\n\t\t\tprint('template processed, writing to grid at:')\n\t\t\twrite_to_grid(i, t_flux)\n\t\t\td_filled += 1\n\t\t\tprint('grid is ' + str(\"{0:.1f}\".format(float(d_filled)/float(d_size) * 100.)) + ' percent full')\n\n\n\n\t\telse:\n\t\t\tprint('processing for vsini: 0')\n\t\t\t_, t_flux_v0 = process_template(t_wavelength, t_flux, sig=sigma, samp=sampling)\n\t\t\tprint('template processed, writing to grid at:')\n\t\t\twrite_to_grid(i, t_flux_v0, vsini0=0.)\n\t\t\td_filled += 1\n\t\t\tprint('grid is ' + str(\"{0:.1f}\".format(float(d_filled)/float(d_size) * 100.)) + ' percent full')\n\n\t\t\tfor j in rotbroads:\n\t\t\t\tif j == 0:\n\t\t\t\t\tcontinue\n\t\t\t\tprint('processing for vsini: ' + str(j))\n\t\t\t\t_, t_flux_vj = process_template_vsini(t_wavelength, t_flux, j, sig=sigma, samp=sampling)\n\t\t\t\tprint('template processed, writing to grid at:')\n\t\t\t\twrite_to_grid(i, t_flux_vj, vsini0=j)\n\t\t\t\td_filled += 1\n\t\t\t\tprint('grid is ' + str(\"{0:.1f}\".format(float(d_filled)/float(d_size) * 100.)) + ' percent full')\n\n\n\tnp.save(template_write_directory + 'template_grid.npy', d)\n\n\n# creating /plots and /results folders in write_directory if they dont already exist \nif not os.path.exists(write_directory + '/plots'):\n    os.mkdir(write_directory + '/plots')\n    print(write_directory + 'plots folder created')\nif not os.path.exists(write_directory + '/results'):\n    os.mkdir(write_directory + '/results')\n    print(write_directory + 'results folder created')\n\nif process_templates==False:\n\t# location of folder containing this script\n\ttemplatedirectory = os.path.dirname(os.path.abspath(__file__)) + '/templates/'\n\t# loading the template flux grid\n\tflux_data_all = np.load(templatedirectory + 'template_grid.npy')\n\t#loading the wavelength data\n\ttemplatewavelength = np.loadtxt(templatedirectory + 'wavelength_data.dat')\nelse:\n\t# the first template for the template wavelength data\n\tflux_data_all = np.load(template_write_directory + 'template_grid.npy')\n\ttemplatewavelength = t_wavelength_0\n\ntemplate_min_wav = min_wav*(1.0 + (min(drv)/299792.458)) - 10.\ntemplate_max_wav = max_wav*(1.0 + (max(drv)/299792.458)) + 10.\n\ntemplatemask = (templatewavelength > template_min_wav) & (templatewavelength < template_max_wav)\nflux_data = np.zeros((len(Teff), len(logg), len(vsini), len(templatewavelength[templatemask])))\ntemplatewavelength = templatewavelength[templatemask]\n\nfor ii in range(len(Teff)):\n\tfor jj in range(len(logg)):\n\t\tfor kk in range(len(vsini)):\n\t\t\tflux_data[ii,jj,kk] = flux_data_all[ii,jj,kk][templatemask]\n\n\nipo = interpolate.RegularGridInterpolator((Teff, logg, vsini), flux_data, method='linear')\n\n# grid of parameters for walker initial positions\nini_grid = [Teff, logg, vsini, drv, slopes, intercepts]\nndim=6\n\n# define edges of parameter space\nteffmin, teffmax, loggmin, loggmax, vsinimin, vsinimax, rvmin, rvmax, slopemin, slopemax, interceptmin, interceptmax = min(Teff), max(Teff), min(logg), max(logg), min(vsini), max(vsini), min(drv), max(drv), min(slopes), max(slopes), min(intercepts), max(intercepts)\n\ndef model(X, wavelength):\n\ti, j, k, l, m, n = X \n\t# interpolating template grid with teff (i), logg (j), vsini (k) trial parameter\n\ttemplateflux = ipo([i, j, k])[0]\n\t# interpolating on wavelength axis for trial RV (l)\n\tfi = interpolate.interp1d(templatewavelength*(1.0 + l/299792.458), templateflux)\n\treturn fi(wavelength)\n\ndef lnprior(X):\n\ti, j, k, l, m, n = X\n\t# flat prior, edges should corespond to template grid\n\tif (teffmin <= i <= teffmax) & (loggmin <= j <= loggmax) & (vsinimin <= k <= vsinimax) & (rvmin <= l <= rvmax) & (slopemin <= m <= slopemax) & (interceptmin <= n <= interceptmax):\n\t\treturn 0.0\n\telse:\n\t\treturn -np.inf\n\ndef lnlike(X, wavelength, flux, noisespec, mask):\n\ti, j, k, l, m, n = X\n\tz = m, n \n\tf = np.poly1d(z)\n\tif exclude_region == False:\n\t\treturn -(np.sum((flux - (model(X, wavelength)*f(wavelength)))**2/(2*PPRE*noisespec**2)))\n\telse:\n\t\treturn -(np.sum((flux[mask] - (model(X, wavelength)*f(wavelength))[mask])**2/(2*PPRE*noisespec[mask]**2)))\n\ndef mcmc_one(t):\n\n\tprint(\"Processing: \" + t)  \n\ttarg_start = datetime.now()\n\n\t# checking if spectrum file exists, and if result already written\n\tif os.path.exists(write_directory + '/results/' + os.path.splitext(os.path.basename(t))[0] + '_results'):\n\t\tprint('WARNING: result for '+t+' already exists, skipping')\n\t\treturn\n\n\t# specify unnormalised calibrated flux\n\twith fits.open(data_file) as ALLDATA:\n\t\tfinal_spectra = ALLDATA[1].data[info['TARGID'] == t][0]\n\t\tspectra_before_sky_subtraction = ALLDATA[3].data[info['TARGID'] == t][0]\n\t\tCalibration_function = ALLDATA[5].data[info['TARGID'] == t][0]\n\t\ttry: \n\t\t\tidx=list(ALLDATA[6].data['FIBREID']).index(t)\n\t\texcept:\n\t\t\tidx=list(ALLDATA[6].data['TARGID']).index(t)\n\t\tNSPEC = ALLDATA[6].data['Nspec'][idx]\n\t\tFIBREID = ALLDATA[6].data['FIBREID'][idx]\n\t\tCNAME = ALLDATA[6].data['CNAME'][idx]\n\tflux = final_spectra * Calibration_function * 1.0e18\n\n\t# restrict to desired wavelength range\n\tflux = flux[targetmask]\n\n\t# create corresponsing noise spectrum\n\tnoisespec = np.sqrt((2.*spectra_before_sky_subtraction - final_spectra)*Calibration_function*1.0e18)\n\tnoisespec = noisespec[targetmask]\n\n\t# mask for excluding a wavelength region\n\tif exclude_region == True:\n\t\tmask = np.zeros(len(wavelength), dtype=bool)\n\t\tfor line in lines:\n\t\t\tmask |= (wavelength >= line[0]) & (wavelength <= line[1])\n\telse:\n\t\tmask = np.ones(len(wavelength), dtype=bool)\n\n\t# choose initial walker positions\n\tpos = [[[np.random.choice(i) for i in ini_grid] for i in range(nwalkers)] for i in range(ntemps)]\n\n\t# initialise MCMC sampler\n\tsampler = PTSampler(ntemps=ntemps, nwalkers=nwalkers, dim=ndim, logl=lnlike, logp=lnprior, Tmax=np.inf, loglargs=[wavelength, flux, noisespec, mask])\n\n\t# run MCMC sampler for burn period\n\tif progress_bar==True:\n\t\tprint(\"running burn\")\n\tpos, prob, state = sampler.run_mcmc(pos, burn, adapt=True, progress_bar=progress_bar)\n\t# reset sampler, run MCMC sampler for run period with walkers starting at their positions at the end of burn\n\tsampler.reset()\n\tif progress_bar==True:\n\t\tprint(\"running runs\")\n\tsampler.run_mcmc(pos, runs, adapt=True, progress_bar=progress_bar)\n\tsamples=sampler.chain[0, :, :, :].reshape((-1, ndim))\n\n\t# plot walker paths\n\tylabels = ['Teff', 'logg', 'vsini', 'RV', 'slope', 'intercept']\n\tfor m in range(ndim):\n\t\tplt.subplot(ndim,1,m+1)\n\t\tplt.plot(sampler.chain[0,:,:,m].transpose(), alpha=0.2)\n\t\tplt.ylabel(ylabels[m])\n\tplt.xlabel('Step')\n\tplt.savefig(write_directory + '/plots/' + t + '_walkers.png', bbox_inches='tight')\n\tplt.close()\n\n\t# calculate 16th, 50th, 84th quantiles of the parameter samples\n\tquantiles = mquantiles(samples, prob=[0.16, 0.50, 0.84], axis=0)\n\n\ttargetname = os.path.splitext(os.path.basename(t))[0]\n\tacceptance_r = np.mean(sampler.acceptance_fraction)\n\n\t# print acceptance fraction, should be between 0.2-0.5 for efficient sampling\n\tprint(\"Mean acceptance fraction: {0:.3f}\"\n                .format(acceptance_r))\n\n\t# The parameter results\n\tTeff_r = quantiles[1][0]\n\tTeffminus_r = quantiles[1][0] - quantiles[0][0]\n\tTeffplus_r = quantiles[2][0] - quantiles[1][0]\n\tlogg_r = quantiles[1][1]\n\tloggminus_r = quantiles[1][1] - quantiles[0][1]\n\tloggplus_r = quantiles[2][1] - quantiles[1][1]\n\tvsini_r = quantiles[1][2]\n\tvsiniminus_r = quantiles[1][2] - quantiles[0][2]\n\tvsiniplus_r = quantiles[2][2] - quantiles[1][2]\n\tRV_r = quantiles[1][3]\n\tRVminus_r = quantiles[1][3] - quantiles[0][3]\n\tRVplus_r = quantiles[2][3] - quantiles[1][3]\n\tslope_r = quantiles[1][4]\n\tslopeminus_r = quantiles[1][4] - quantiles[0][4]\n\tslopeplus_r = quantiles[2][4] - quantiles[1][4]\n\tintercept_r = quantiles[1][5]\n\tinterceptminus_r = quantiles[1][5] - quantiles[0][5]\n\tinterceptplus_r = quantiles[2][5] - quantiles[1][5]\n\n\t#fig = corner.corner(samples, quantiles=[0.16, 0.50, 0.84], labels=['Teff', 'log(g)', 'vsini', 'RV', 'slope', 'intercept'], show_titles=True, title_kwargs={\"fontsize\": 10}, plot_datapoints=True, plot_contours=True, auto_bars=True, data_kwargs={\"alpha\": 0.005})\n\t# fig.savefig(write_directory + t + '_cornerplot.png', bbox_inches='tight')\n\t# plt.close()\n\n\t# parameters of best fit (for plotting)\n\tXp = Teff_r, logg_r, vsini_r, RV_r, slope_r, intercept_r\n\tfp = np.poly1d(Xp[-2:])\n\tfitp = fp(wavelength)\n\n\t# plot spectrum and best-fit\n\tplt.plot(wavelength, flux, wavelength, model(Xp, wavelength) * fitp)\n\tif exclude_region == True:\n\t\tfor n,line in enumerate(lines):\n\t\t\tif n == 0:\n\t\t\t\tplt.vlines([line[1]], flux.min()*0.8, flux.max()*1.2, colors='r', linestyles='dashed')\n\t\t\telif n == (len(lines)-1):\n\t\t\t\tplt.vlines([line[0]], flux.min()*0.8, flux.max()*1.2, colors='r', linestyles='dashed')\n\t\t\telse:\n\t\t\t\tplt.vlines([line[0], line[1]], flux.min()*0.8, flux.max()*1.2, colors='r', linestyles='dashed')\n\n\tplt.xlim(min_wav, max_wav)\n\tplt.ylim(flux.min()*0.8, flux.max()*1.2)\n\tplt.xlabel(r'Wavelength ($\\AA$)')\n\tplt.ylabel('Calibrated counts')\n\tplt.savefig(write_directory + '/plots/' + t + '_spectrum.png', bbox_inches='tight')\n\tplt.close()\n\n\t# plot mapping function\n\tplt.plot(wavelength, fitp, wavelength, flux / model(Xp, wavelength))\n\tplt.xlim(min_wav, max_wav)\n\tplt.xlabel(r'Wavelength ($\\AA$)')\n\tplt.ylabel('Calibrated counts')\n\tplt.savefig(write_directory + '/plots/' + t + '_mapping_function.png', bbox_inches='tight')\n\tplt.close()\n\n\t# write results\n\ttab = open(write_directory + '/results/' + t +  '_results', \"w\")\n\ttab.write(np.str(NSPEC) + \" \" + np.str(FIBREID) + \" \" + np.str(CNAME) + \" \" + t + \" \" + np.str(acceptance_r) + \" \" + np.str(Teff_r) + \" \" + np.str(Teffminus_r) + \" \" + np.str(Teffplus_r) + \" \" + np.str(logg_r) + \" \" + np.str(loggminus_r) + \" \" + np.str(loggplus_r) + \" \" + np.str(vsini_r) + \" \" + np.str(vsiniminus_r) + \" \" + np.str(vsiniplus_r) + \" \" + np.str(RV_r) + \" \" + np.str(RVminus_r) + \" \" + np.str(RVplus_r) + \" \" + np.str(slope_r) + \" \" + np.str(slopeminus_r) + \" \" + np.str(slopeplus_r) + \" \" + np.str(intercept_r) + \" \" + np.str(interceptminus_r) + \" \" + np.str(interceptplus_r) + \"\\n\")\n\ttab.close()\n\n\ttarg_end = datetime.now() - targ_start\n\tprint(targ_end)\n\ndef make_output_fits():\n\toutput_files = glob.glob(write_directory + 'results/*_results')\n\tall_res = []\n\tfor i in output_files:\n\t\twith open(i) as outf:\n\t\t\tall_res.append(outf.read().split())\n\tt = Table(rows=all_res, names=('NSPEC', 'FIBREID', 'CNAME', 'TARGID', 'Acceptance', 'Teff', 'Teff_minus', 'Teff_plus', 'logg', 'logg_minus', 'logg_plus', 'vsini', 'vsini_minus', 'vsini_plus', 'RV', 'RV_minus', 'RV_plus', 'slope', 'slope_minus', 'slope_plus', 'intercept', 'intercept_minus', 'intercept_plus'))\n\tt.write(write_directory+'results/'+os.path.splitext(os.path.basename(args.infile[0]))[0]+'_ptmcmc.fits', format='fits', overwrite=False)\n\n\n\n\nif __name__ ==  '__main__':\n\t# checking if results table already exists\n\tif os.path.exists(write_directory+'results/'+os.path.splitext(os.path.basename(args.infile[0]))[0]+'_ptmcmc.fits'):\n\t\tprint('WARNING: result table already exists, ending process.')\n\t\tsys.exit()\n\tif target_list == 'all':\n\t\tprint(\"Processing all BA stars in fits file\")\n\t\tBA = []\n\t\twith fits.open(data_file) as ALLDATA:\n\t\t\tfor n,i in enumerate(ALLDATA[6].data['TARGID']):\n\t\t\t\tif 'LR-BA' in i:\n\t\t\t\t\tBA.append(i)\n\telse:\n\t\tprint(\"Processing BA stars specified in target list\")\n\t\ttarglist = np.genfromtxt(target_list, dtype=None, encoding=None)\n\t\tBA = []\n\t\twith fits.open(data_file) as ALLDATA:\n\t\t\tfor targ in targlist:\n\t\t\t\ttry: \n\t\t\t\t\tidx=list(ALLDATA[6].data['FIBREID']).index(targ)\n\t\t\t\t\tBA.append(ALLDATA[6].data['TARGID'][idx])\n\t\t\t\texcept:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tidx=list(ALLDATA[6].data['TARGID']).index(targ)\n\t\t\t\t\t\tBA.append(ALLDATA[6].data['TARGID'][idx])\n\t\t\t\t\texcept:\t\n\t\t\t\t\t\tprint(str(targ)+\": Cant find either FIBREID or TARGID in input table.\")\n\nALLDATA = None\ninfo = None\nwavelength = None\ntargetmask = None\n\ndef set_globals():\n    global ALLDATA\n    global info \n    global wavelength\n    global targetmask\n\n    with fits.open(data_file) as ALLDATA:\n\t    head0 = ALLDATA[0].header\n\t    info = ALLDATA[6].data\n\t    data1 = ALLDATA[1].data\n\t    head1 = ALLDATA[1].header\n\t    wave0 = head1['CRVAL1']  \n\t    increm = head1['CD1_1']\n\t    wavelength = np.array([wave0+increm*a for a in range(len(data1[1]))])\n\t    targetmask = (wavelength > min_wav) & (wavelength < max_wav)\n\t    wavelength = wavelength[targetmask]\n\nif multiprocess==True:\n\tfrom multiprocessing import Pool\n\tif __name__ ==  '__main__':\n\t\tpool = Pool(processes=process_no, initializer=set_globals)\n\t\tit = pool.imap_unordered(mcmc_one, BA)\n\t\tfor nn,i in enumerate(range(len(BA))):\n\t\t\tit.next()\n\t\tmake_output_fits()\n\t\tprint(datetime.now() - startTime)\n\nelse:\n\tset_globals()\n\tfor nn,i in enumerate(BA):\n\t\tmcmc_one(i)\n\tmake_output_fits()\n\tprint(datetime.now() - startTime)", "meta": {"hexsha": "8e9be3bc96550dcc8fffac2fcc143ef9bf445575", "size": 17806, "ext": "py", "lang": "Python", "max_stars_repo_path": "ptmcmc.py", "max_stars_repo_name": "amyharris2/ptmcmc", "max_stars_repo_head_hexsha": "f19c60faa3c60ec5899f210e3d7345cc9a66b568", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ptmcmc.py", "max_issues_repo_name": "amyharris2/ptmcmc", "max_issues_repo_head_hexsha": "f19c60faa3c60ec5899f210e3d7345cc9a66b568", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ptmcmc.py", "max_forks_repo_name": "amyharris2/ptmcmc", "max_forks_repo_head_hexsha": "f19c60faa3c60ec5899f210e3d7345cc9a66b568", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6529680365, "max_line_length": 600, "alphanum_fraction": 0.6926316972, "include": true, "reason": "import numpy,import scipy,from scipy,from astropy", "num_tokens": 5379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.1922516012578726}}
{"text": "from __future__ import division\nimport numpy as np\nfrom functools import partial\nfrom builtins import zip\n\nfrom pybasicbayes.distributions import DiagonalRegression, Gaussian, Regression\n\nimport pyhsmm\nfrom pyhsmm.util.general import list_split\n\nfrom pyslds.states import HMMSLDSStatesPython, HMMSLDSStatesEigen, HSMMSLDSStatesPython, HSMMSLDSStatesEigen\nfrom pyslds.states import HMMCountSLDSStatesPython, HMMCountSLDSStatesEigen, HSMMCountSLDSStatesPython, \\\n    HSMMCountSLDSStatesEigen\nfrom pyslds.util import gaussian_map_estimation, regression_map_estimation, gaussian_logprior, regression_logprior\n\n\nclass _SLDSMixin(object):\n    def __init__(self,dynamics_distns,emission_distns,init_dynamics_distns,**kwargs):\n        self.init_dynamics_distns = init_dynamics_distns\n        self.dynamics_distns = dynamics_distns\n\n        # Allow for a single, shared emission distribution\n        if not isinstance(emission_distns, list):\n            self._single_emission = True\n            self._emission_distn = emission_distns\n            self.emission_distns = [emission_distns] * len(self.dynamics_distns)\n        else:\n            assert isinstance(emission_distns, list) and \\\n                   len(emission_distns) == len(dynamics_distns)\n            self._single_emission = False\n            self.emission_distns = emission_distns\n\n        super(_SLDSMixin,self).__init__(\n            obs_distns=self.dynamics_distns,**kwargs)\n\n    def generate(self, T=100, keep=True, with_noise=True, initial_condition=None, stateseq=None, **kwargs):\n        s = self._states_class(model=self, T=T, initialize_from_prior=True, **kwargs)\n        s.generate_states(with_noise=with_noise, initial_condition=initial_condition, stateseq=stateseq)\n        data = self._generate_obs(s)\n        if keep:\n            self.states_list.append(s)\n        return data + (s.stateseq,)\n\n    def _generate_obs(self,s):\n        if s.data is None:\n            s.data = s.generate_obs()\n        else:\n            # TODO: Handle missing data\n            raise NotImplementedError\n\n        return s.data, s.gaussian_states\n\n    def smooth(self, data, inputs=None, mask=None):\n        self.add_data(data, inputs=inputs, mask=mask)\n        s = self.states_list.pop()\n        return s.smooth()\n\n    @property\n    def diagonal_noise(self):\n        return all([isinstance(ed, DiagonalRegression) for ed in self.emission_distns])\n\n    @property\n    def has_missing_data(self):\n        return any([s.mask is not None for s in self.states_list])\n\n    def heldout_log_likelihood(self, test_masks=None):\n        test_masks = [None] * len(self.states_list) if test_masks is None else test_masks\n        assert len(test_masks) == len(self.states_list)\n\n        hll = 0\n        for mask, states in zip(test_masks, self.states_list):\n            hll += states.heldout_log_likelihood(test_mask=mask)\n        return hll\n\n\nclass _SLDSGibbsMixin(_SLDSMixin):\n    def resample_parameters(self):\n        self.resample_lds_parameters()\n        self.resample_hmm_parameters()\n\n    def resample_lds_parameters(self):\n        self.resample_init_dynamics_distns()\n        self.resample_dynamics_distns()\n        self.resample_emission_distns()\n\n    def resample_hmm_parameters(self):\n        super(_SLDSGibbsMixin,self).resample_parameters()\n\n    def resample_init_dynamics_distns(self):\n        for state, d in enumerate(self.init_dynamics_distns):\n            d.resample(\n                [s.gaussian_states[0] for s in self.states_list\n                    if s.stateseq[0] == state])\n        self._clear_caches()\n\n    def resample_dynamics_distns(self):\n        zs = [s.stateseq[:-1] for s in self.states_list]\n        xs = [np.hstack((s.gaussian_states[:-1], s.inputs[:-1]))\n              for s in self.states_list]\n        ys = [s.gaussian_states[1:] for s in self.states_list]\n\n        for state, d in enumerate(self.dynamics_distns):\n            d.resample(\n                [(x[z == state], y[z == state])\n                 for x, y, z in zip(xs, ys, zs)])\n        self._clear_caches()\n\n    def resample_emission_distns(self):\n        if self._single_emission:\n            data = [(np.hstack((s.gaussian_states, s.inputs)), s.data)\n                    for s in self.states_list]\n            mask = [s.mask for s in self.states_list] if self.has_missing_data else None\n\n            if self.has_missing_data:\n                self._emission_distn.resample(data=data, mask=mask)\n            else:\n                self._emission_distn.resample(data=data)\n        else:\n            for state, d in enumerate(self.emission_distns):\n                data = [(np.hstack((s.gaussian_states[s.stateseq == state],\n                                    s.inputs[s.stateseq == state])),\n                         s.data[s.stateseq == state])\n                        for s in self.states_list]\n\n                mask = [s.mask[s.stateseq == state] for s in self.states_list] \\\n                    if self.has_missing_data else None\n\n                if self.has_missing_data:\n                    d.resample(data=data, mask=mask)\n                else:\n                    d.resample(data=data)\n\n\n        self._clear_caches()\n\n    def resample_obs_distns(self):\n        pass  # handled in resample_parameters\n\n    ### joblib parallel\n\n    def _joblib_resample_states(self,states_list,num_procs):\n        from joblib import Parallel, delayed\n        import pyslds.parallel as parallel\n\n        if len(states_list) > 0:\n            joblib_args = list(map(self._get_joblib_pair, states_list))\n\n            parallel.model = self\n            parallel.args = list_split(joblib_args, num_procs)\n\n            idxs = range(len(parallel.args))\n            raw_stateseqs = Parallel(n_jobs=num_procs,backend='multiprocessing')\\\n                    (list(map(delayed(parallel._get_sampled_stateseq), idxs)))\n\n            flatten = lambda lst: [x for y in lst for x in y]\n            raw_stateseqs = flatten(raw_stateseqs)\n\n            # since list_split might reorder things, do the same to states_list\n            states_list = flatten(list_split(states_list, num_procs))\n\n            for s, tup in zip(states_list, raw_stateseqs):\n                s.stateseq, s.gaussian_states, s._normalizer = tup\n\n\nclass _SLDSVBEMMixin(_SLDSMixin):\n\n    def _vb_E_step(self):\n        # update the variational approximation for the states\n        for state in self.states_list:\n            state.vb_E_step()\n\n    def _vb_M_step(self):\n        # Update the HMM parameters\n        self._M_step_init_state_distn()\n        self._M_step_trans_distn()\n\n        # Update the LDS parameters\n        self._M_step_init_dynamics_distn()\n        self._M_step_dynamics_distn()\n        self._M_step_emission_distn()\n\n    def _M_step_init_dynamics_distn(self):\n        sum_tuples = lambda lst: list(map(sum, zip(*lst)))\n        E_init_stats = lambda i, s: \\\n            tuple(s.expected_states[0, i] * stat for stat in s.E_init_stats)\n\n        for state, d in enumerate(self.init_dynamics_distns):\n            gaussian_map_estimation(sum_tuples(E_init_stats(state, s) for s in self.states_list), d)\n\n    def _M_step_dynamics_distn(self):\n        contract = partial(np.tensordot, axes=1)\n        sum_tuples = lambda lst: list(map(sum, zip(*lst)))\n\n        E_dyn_stats = lambda i, s: \\\n            tuple(contract(s.expected_states[:-1, i], stat) for stat in s.E_dynamics_stats)\n\n        for state, d in enumerate(self.dynamics_distns):\n            regression_map_estimation(sum_tuples(E_dyn_stats(state, s) for s in self.states_list), d)\n\n    def _M_step_emission_distn(self):\n        contract = partial(np.tensordot, axes=1)\n        sum_tuples = lambda lst: list(map(sum, zip(*lst)))\n\n        if self._single_emission:\n            E_emi_stats = lambda s: \\\n                tuple(np.sum(stat, axis=0) for stat in s.E_emission_stats)\n            stats = sum_tuples(E_emi_stats(s) for s in self.states_list)\n            regression_map_estimation(stats, self._emission_distn)\n        else:\n            E_emi_stats = lambda i, s: \\\n                tuple(contract(s.expected_states[:, i], stat) for stat in s.E_emission_stats)\n            for state, d in enumerate(self.emission_distns):\n                regression_map_estimation(sum_tuples(E_emi_stats(state, s) for s in self.states_list), d)\n\n    def VBEM_step(self, n_iter=1):\n        for _ in range(n_iter):\n            self._vb_E_step()\n        self._vb_M_step()\n\n    def VBEM_ELBO(self):\n        # log p(theta)\n        # todo: include transition distribution and init state distribution!\n        elbo = np.sum([gaussian_logprior(id) for id in self.init_dynamics_distns])\n        elbo += np.sum([regression_logprior(dd) for dd in self.dynamics_distns])\n\n        if self._single_emission:\n            elbo += regression_logprior(self.emission_distns[0])\n        else:\n            elbo += np.sum([regression_logprior(ed) for ed in self.emission_distns])\n\n        # E_q [log p(z, x, y, theta)]\n        elbo += sum(s.vb_elbo() for s in self.states_list)\n        return elbo\n\n\nclass _SLDSMeanFieldMixin(_SLDSMixin):\n    def meanfield_update_parameters(self):\n        self.meanfield_update_init_dynamics_distns()\n        self.meanfield_update_dynamics_distns()\n        self.meanfield_update_emission_distns()\n        super(_SLDSMeanFieldMixin, self).meanfield_update_parameters()\n\n    def meanfield_update_init_dynamics_distns(self):\n        sum_tuples = lambda lst: list(map(sum, zip(*lst)))\n        E_stats = lambda i, s: \\\n            tuple(s.expected_states[0,i] * stat for stat in s.E_init_stats)\n\n        for state, d in enumerate(self.init_dynamics_distns):\n            d.meanfieldupdate(\n                stats=sum_tuples(E_stats(state, s) for s in self.states_list))\n\n    def meanfield_update_dynamics_distns(self):\n        contract = partial(np.tensordot, axes=1)\n        sum_tuples = lambda lst: list(map(sum, zip(*lst)))\n        E_stats = lambda i, s: \\\n            tuple(contract(s.expected_states[1:,i], stat) for stat in s.E_dynamics_stats)\n\n        for state, d in enumerate(self.dynamics_distns):\n            d.meanfieldupdate(\n                stats=sum_tuples(E_stats(state, s) for s in self.states_list))\n\n    def meanfield_update_emission_distns(self):\n        sum_tuples = lambda lst: list(map(sum, zip(*lst)))\n\n        if self._single_emission:\n            E_stats = lambda s: \\\n                tuple(np.sum(stat, axis=0) for stat in s.E_emission_stats)\n\n            self._emission_distn.meanfieldupdate(\n                stats=sum_tuples(E_stats(s) for s in self.states_list))\n        else:\n            contract = partial(np.tensordot, axes=1)\n            E_stats = lambda i, s: \\\n                tuple(contract(s.expected_states[:, i], stat) for stat in s.E_emission_stats)\n\n            for state, d in enumerate(self.emission_distns):\n                d.meanfieldupdate(\n                    stats=sum_tuples(E_stats(state, s) for s in self.states_list))\n\n    def meanfield_update_obs_distns(self):\n        pass  # handled in meanfield_update_parameters\n\n    ### init\n    def _init_mf_from_gibbs(self):\n        # Now also update the emission and dynamics params\n        for ed in self.emission_distns:\n            if hasattr(ed, \"_initialize_mean_field\"):\n                ed._initialize_mean_field()\n        for dd in self.dynamics_distns:\n            if hasattr(dd, \"_initialize_mean_field\"):\n                dd._initialize_mean_field()\n\n        for s in self.states_list:\n            s._init_mf_from_gibbs()\n\n    ### vlb\n\n    def vlb(self, states_last_updated=False):\n        vlb = 0.\n        vlb += sum(s.get_vlb(states_last_updated) for s in self.states_list)\n        vlb += self.trans_distn.get_vlb()\n        vlb += self.init_state_distn.get_vlb()\n        vlb += sum(d.get_vlb() for d in self.init_dynamics_distns)\n        vlb += sum(d.get_vlb() for d in self.dynamics_distns)\n        if self._single_emission:\n            vlb += self._emission_distn.get_vlb()\n        else:\n            vlb += sum(d.get_vlb() for d in self.emission_distns)\n        return vlb\n\n\nclass HMMSLDSPython(_SLDSGibbsMixin, _SLDSVBEMMixin, _SLDSMeanFieldMixin, pyhsmm.models.HMMPython):\n    _states_class = HMMSLDSStatesPython\n\n\nclass HMMSLDS(_SLDSGibbsMixin, _SLDSVBEMMixin, _SLDSMeanFieldMixin, pyhsmm.models.HMM):\n    _states_class = HMMSLDSStatesEigen\n\n\nclass HSMMSLDSPython(_SLDSGibbsMixin, _SLDSVBEMMixin, _SLDSMeanFieldMixin, pyhsmm.models.HSMMPython):\n    _states_class = HSMMSLDSStatesPython\n\n\nclass HSMMSLDS(_SLDSGibbsMixin, _SLDSVBEMMixin, _SLDSMeanFieldMixin, pyhsmm.models.HSMM):\n    _states_class = HSMMSLDSStatesEigen\n\n\nclass WeakLimitHDPHMMSLDS(_SLDSGibbsMixin, _SLDSVBEMMixin, _SLDSMeanFieldMixin,\n                          pyhsmm.models.WeakLimitHDPHMM):\n    _states_class = HMMSLDSStatesEigen\n\n\nclass WeakLimitStickyHDPHMMSLDS(\n        _SLDSGibbsMixin, _SLDSVBEMMixin, _SLDSMeanFieldMixin,\n        pyhsmm.models.WeakLimitStickyHDPHMM):\n    _states_class = HMMSLDSStatesEigen\n\n\nclass WeakLimitHDPHSMMSLDS(_SLDSGibbsMixin, _SLDSVBEMMixin, _SLDSMeanFieldMixin,\n                           pyhsmm.models.WeakLimitHDPHSMM):\n    _states_class = HSMMSLDSStatesEigen\n\n\n## Default constructors\n\ndef _default_model(model_class, K, D_obs, D_latent, D_input=0,\n                   mu_inits=None, sigma_inits=None,\n                   As=None, Bs=None, sigma_statess=None,\n                   Cs=None, Ds=None, sigma_obss=None,\n                   alpha=3.0, init_state_distn='uniform',\n                   **kwargs):\n\n    # Initialize init_dynamics_distns\n    init_dynamics_distns = \\\n        [Gaussian(nu_0=D_latent+3,\n                  sigma_0=3.*np.eye(D_latent),\n                  mu_0=np.zeros(D_latent),\n                  kappa_0=0.01)\n         for _ in range(K)]\n\n    if mu_inits is not None:\n        assert isinstance(mu_inits, list) and len(mu_inits) == K\n        for id, mu in zip(init_dynamics_distns, mu_inits):\n            id.mu = mu\n\n    if sigma_inits is not None:\n        assert isinstance(sigma_inits, list) and len(sigma_inits) == K\n        for id, sigma in zip(init_dynamics_distns, sigma_inits):\n            id.sigma = sigma\n\n    # Initialize dynamics distributions\n    dynamics_distns = [Regression(\n        nu_0=D_latent + 1,\n        S_0=D_latent * np.eye(D_latent),\n        M_0=np.hstack((.99 * np.eye(D_latent), np.zeros((D_latent, D_input)))),\n        K_0=D_latent * np.eye(D_latent + D_input))\n        for _ in range(K)]\n    if As is not None:\n        assert isinstance(As, list) and len(As) == K\n        if D_input > 0:\n            assert isinstance(Bs, list) and len(Bs) == K\n            As = [np.hstack((A, B)) for A,B in zip(As, Bs)]\n    else:\n        # As = [random_rotation(D_latent) for _ in range(K)]\n        As = [np.eye(D_latent) for _ in range(K)]\n        if D_input > 0:\n            As = [np.hstack((A, np.zeros((D_latent, D_input))))\n                  for A in As]\n    for dd, A in zip(dynamics_distns, As):\n        dd.A = A\n\n    if sigma_statess is not None:\n        assert isinstance(sigma_statess, list) and len(sigma_statess) == K\n    else:\n        sigma_statess = [np.eye(D_latent) for _ in range(K)]\n\n    for dd, sigma in zip(dynamics_distns, sigma_statess):\n        dd.sigma = sigma\n\n    # Initialize emission distributions\n    _single_emission = (Cs is not None) and (not isinstance(Cs, list))\n\n    if _single_emission:\n        if D_input > 0:\n            assert Ds is not None and not isinstance(Ds, list)\n            Cs = np.hstack((Cs, Ds))\n\n        if sigma_obss is None:\n            sigma_obss = np.eye(D_obs)\n\n        emission_distns = Regression(\n            nu_0=D_obs + 3,\n            S_0=D_obs * np.eye(D_obs),\n            M_0=np.zeros((D_obs, D_latent + D_input)),\n            K_0=D_obs * np.eye(D_latent + D_input),\n            A=Cs, sigma=sigma_obss)\n\n    else:\n        emission_distns = [Regression(\n            nu_0=D_obs + 1,\n            S_0=D_obs * np.eye(D_obs),\n            M_0=np.zeros((D_obs, D_latent + D_input)),\n            K_0=D_obs * np.eye(D_latent + D_input))\n            for _ in range(K)]\n\n        if Cs is not None and sigma_obss is not None:\n            assert isinstance(Cs, list) and len(Cs) == K\n            assert isinstance(sigma_obss, list) and len(sigma_obss) == K\n            if D_input > 0:\n                assert isinstance(Ds, list) and len(Ds) == K\n                Cs = [np.hstack((C, D)) for C,D in zip(Cs, Ds)]\n        else:\n            Cs = [np.zeros((D_obs, D_latent + D_input)) for _ in range(K)]\n            sigma_obss = [0.05 * np.eye(D_obs) for _ in range(K)]\n\n        for ed, C, sigma in zip(emission_distns, Cs, sigma_obss):\n            ed.A = C\n            ed.sigma = sigma\n\n    model = model_class(\n        init_dynamics_distns=init_dynamics_distns,\n        dynamics_distns=dynamics_distns,\n        emission_distns=emission_distns,\n        init_state_distn=init_state_distn,\n        alpha=alpha,\n        **kwargs)\n\n    return model\n\ndef DefaultSLDS(K, D_obs, D_latent, D_input=0,\n                mu_inits=None, sigma_inits=None,\n                As=None, Bs=None, sigma_statess=None,\n                Cs=None, Ds=None, sigma_obss=None,\n                alpha=3.,\n                **kwargs):\n    return _default_model(HMMSLDS, K, D_obs, D_latent, D_input=D_input,\n                          mu_inits=mu_inits, sigma_inits=sigma_inits,\n                          As=As, Bs=Bs, sigma_statess=sigma_statess,\n                          Cs=Cs, Ds=Ds, sigma_obss=sigma_obss,\n                          alpha=alpha,\n                          **kwargs)\n\n\ndef DefaultWeakLimitHDPSLDS(K, D_obs, D_latent, D_input=0,\n                mu_inits=None, sigma_inits=None,\n                As=None, Bs=None, sigma_statess=None,\n                Cs=None, Ds=None, sigma_obss=None,\n                alpha=3., gamma=3.,\n                **kwargs):\n    return _default_model(WeakLimitHDPHMMSLDS, K, D_obs, D_latent, D_input=D_input,\n                          mu_inits=mu_inits, sigma_inits=sigma_inits,\n                          As=As, Bs=Bs, sigma_statess=sigma_statess,\n                          Cs=Cs, Ds=Ds, sigma_obss=sigma_obss,\n                          alpha=alpha, gamma=gamma,\n                          **kwargs)\n\ndef DefaultWeakLimitStickyHDPSLDS(K, D_obs, D_latent, D_input=0,\n                mu_inits=None, sigma_inits=None,\n                As=None, Bs=None, sigma_statess=None,\n                Cs=None, Ds=None, sigma_obss=None,\n                alpha=3., gamma=3., kappa=10.,\n                **kwargs):\n    return _default_model(WeakLimitStickyHDPHMMSLDS, K, D_obs, D_latent, D_input=D_input,\n                          mu_inits=mu_inits, sigma_inits=sigma_inits,\n                          As=As, Bs=Bs, sigma_statess=sigma_statess,\n                          Cs=Cs, Ds=Ds, sigma_obss=sigma_obss,\n                          kappa=kappa, alpha=alpha, gamma=gamma,\n                          **kwargs)\n\n\nclass _CountSLDSMixin(_SLDSGibbsMixin):\n\n    def resample_emission_distns(self):\n        if self._single_emission:\n            data = [(np.hstack((s.gaussian_states, s.inputs)), s.data)\n                    for s in self.states_list]\n            mask = [s.mask for s in self.states_list] if self.has_missing_data else None\n            omega = [s.omega for s in self.states_list]\n            self._emission_distn.resample(data=data, mask=mask, omega=omega)\n\n        else:\n            for state, d in enumerate(self.emission_distns):\n                data = [(np.hstack((s.gaussian_states[s.stateseq == state],\n                                    s.inputs[s.stateseq == state])),\n                         s.data[s.stateseq == state])\n                        for s in self.states_list]\n                mask = [s.mask[s.stateseq == state] for s in self.states_list] \\\n                    if self.has_missing_data else None\n                omega = [s.omega[s.stateseq == state] for s in self.states_list]\n                d.resample(data=data, mask=mask, omega=omega)\n\n        self._clear_caches()\n\n\nclass HMMCountSLDSPython(_CountSLDSMixin, pyhsmm.models.HMMPython):\n    _states_class = HMMCountSLDSStatesPython\n\n\nclass HMMCountSLDS(_CountSLDSMixin, pyhsmm.models.HMM):\n    _states_class = HMMCountSLDSStatesEigen\n\n\nclass HSMMCountSLDSPython(_CountSLDSMixin, pyhsmm.models.HSMMPython):\n    _states_class = HSMMCountSLDSStatesPython\n\n\nclass HSMMCountSLDS(_CountSLDSMixin, pyhsmm.models.HSMM):\n    _states_class = HSMMCountSLDSStatesEigen\n\n\nclass WeakLimitHDPHMMCountSLDS(_CountSLDSMixin, pyhsmm.models.WeakLimitHDPHMM):\n    _states_class = HMMCountSLDSStatesEigen\n\n\nclass WeakLimitStickyHDPHMMCountSLDS(\n    _CountSLDSMixin, pyhsmm.models.WeakLimitStickyHDPHMM):\n    _states_class = HMMCountSLDSStatesEigen\n\n\nclass WeakLimitHDPHSMMCountSLDS(\n    _CountSLDSMixin, pyhsmm.models.WeakLimitHDPHSMM):\n    _states_class = HSMMCountSLDSStatesEigen\n", "meta": {"hexsha": "f558be22a0b1ae00e56382c2073d87634c8f4764", "size": 20741, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyslds/models.py", "max_stars_repo_name": "nitinshyamk/pyslds", "max_stars_repo_head_hexsha": "a90ce829e807a5ae0bacda806a8c516e4ff3cba7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 77, "max_stars_repo_stars_event_min_datetime": "2016-12-14T18:35:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T23:27:43.000Z", "max_issues_repo_path": "pyslds/models.py", "max_issues_repo_name": "nitinshyamk/pyslds", "max_issues_repo_head_hexsha": "a90ce829e807a5ae0bacda806a8c516e4ff3cba7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2016-11-18T14:02:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T22:02:41.000Z", "max_forks_repo_path": "pyslds/models.py", "max_forks_repo_name": "nitinshyamk/pyslds", "max_forks_repo_head_hexsha": "a90ce829e807a5ae0bacda806a8c516e4ff3cba7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2017-02-21T10:43:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T17:00:33.000Z", "avg_line_length": 38.197053407, "max_line_length": 114, "alphanum_fraction": 0.6278385806, "include": true, "reason": "import numpy", "num_tokens": 5252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.192163495368841}}
{"text": "from __future__ import annotations\n\nfrom collections import defaultdict\nfrom dataclasses import dataclass\nfrom functools import cache\nfrom itertools import permutations\nfrom itertools import product\nfrom typing import Literal\n\nimport numpy as np\n\nfrom chemex.model import model\n\n_BASES = {\n    \"ixy\": [\"ix\", \"iy\"],\n    \"iz\": [\"iz\"],\n    \"izsz\": [\"iz\", \"2izsz\"],\n    \"iz_eq\": [\"ie\", \"iz\"],\n    \"ixyz\": [\"ix\", \"iy\", \"iz\"],\n    \"ixyz_eq\": [\"ie\", \"ix\", \"iy\", \"iz\"],\n    \"ixysxy\": [\"2ixsx\", \"2ixsy\", \"2iysx\", \"2iysy\"],\n    \"ixy_ixysxy\": [\"ix\", \"iy\", \"2ixsx\", \"2ixsy\", \"2iysx\", \"2iysy\"],\n    \"ixyzsz\": [\"ix\", \"iy\", \"iz\", \"2ixsz\", \"2iysz\", \"2izsz\"],\n    \"ixyzsz_diff\": [\"ix\", \"iy\", \"iz\", \"2ixsz\", \"2iysz\", \"2izsz\"],\n    \"ixyzsz_eq\": [\"ie\", \"ix\", \"iy\", \"iz\", \"2ixsz\", \"2iysz\", \"2izsz\"],\n    \"ixyzsxyz\": [\n        \"ix\",\n        \"iy\",\n        \"iz\",\n        \"sx\",\n        \"sy\",\n        \"sz\",\n        \"2ixsz\",\n        \"2iysz\",\n        \"2izsx\",\n        \"2izsy\",\n        \"2ixsx\",\n        \"2ixsy\",\n        \"2iysx\",\n        \"2iysy\",\n        \"2izsz\",\n    ],\n    \"ixyzsxyz_eq\": [\n        \"ie\",\n        \"se\",\n        \"ix\",\n        \"iy\",\n        \"iz\",\n        \"sx\",\n        \"sy\",\n        \"sz\",\n        \"2ixsz\",\n        \"2iysz\",\n        \"2izsx\",\n        \"2izsy\",\n        \"2ixsx\",\n        \"2ixsy\",\n        \"2iysx\",\n        \"2iysy\",\n        \"2izsz\",\n    ],\n}\n_TRANSITIONS: dict[str, tuple[tuple[str, str, float], ...]] = {\n    \"r2_i_{state}\": ((\"ix\", \"ix\", -1.0), (\"iy\", \"iy\", -1.0)),\n    \"r2_s_{state}\": ((\"sx\", \"sx\", -1.0), (\"sy\", \"sy\", -1.0)),\n    \"r1_i_{state}\": ((\"iz\", \"iz\", -1.0), (\"iz\", \"ie\", +1.0)),\n    \"r1_s_{state}\": ((\"sz\", \"sz\", -1.0), (\"sz\", \"se\", +1.0)),\n    \"r2a_i_{state}\": ((\"2ixsz\", \"2ixsz\", -1.0), (\"2iysz\", \"2iysz\", -1.0)),\n    \"r2a_s_{state}\": ((\"2izsx\", \"2izsx\", -1.0), (\"2izsy\", \"2izsy\", -1.0)),\n    \"r2mq_is_{state}\": (\n        (\"2ixsx\", \"2ixsx\", -1.0),\n        (\"2ixsy\", \"2ixsy\", -1.0),\n        (\"2iysx\", \"2iysx\", -1.0),\n        (\"2iysy\", \"2iysy\", -1.0),\n    ),\n    \"r1a_is_{state}\": ((\"2izsz\", \"2izsz\", -1.0),),\n    \"etaxy_i_{state}\": (\n        (\"ix\", \"2ixsz\", -1.0),\n        (\"iy\", \"2iysz\", -1.0),\n        (\"2ixsz\", \"ix\", -1.0),\n        (\"2iysz\", \"iy\", -1.0),\n    ),\n    \"etaxy_s_{state}\": (\n        (\"sx\", \"2izsx\", -1.0),\n        (\"sy\", \"2izsy\", -1.0),\n        (\"2izsx\", \"sx\", -1.0),\n        (\"2izsy\", \"sy\", -1.0),\n    ),\n    \"etaz_i_{state}\": (\n        (\"iz\", \"2izsz\", -1.0),\n        (\"2izsz\", \"iz\", -1.0),\n        (\"2izsz\", \"ie\", +1.0),\n    ),\n    \"etaz_s_{state}\": (\n        (\"sz\", \"2izsz\", -1.0),\n        (\"2izsz\", \"sz\", -1.0),\n        (\"2izsz\", \"se\", +1.0),\n    ),\n    \"sigma_is_{state}\": (\n        (\"iz\", \"sz\", -1.0),\n        (\"sz\", \"iz\", -1.0),\n        (\"sz\", \"ie\", +1.0),\n        (\"iz\", \"se\", +1.0),\n    ),\n    \"mu_is_{state}\": (\n        (\"2ixsx\", \"2iysy\", +1.0),\n        (\"2ixsy\", \"2iysx\", -1.0),\n        (\"2iysx\", \"2ixsy\", -1.0),\n        (\"2iysy\", \"2ixsx\", +1.0),\n    ),\n    \"rotz_i\": (\n        (\"ix\", \"iy\", -1.0),\n        (\"iy\", \"ix\", +1.0),\n        (\"2ixsx\", \"2iysx\", -1.0),\n        (\"2iysx\", \"2ixsx\", +1.0),\n        (\"2ixsy\", \"2iysy\", -1.0),\n        (\"2iysy\", \"2ixsy\", +1.0),\n        (\"2ixsz\", \"2iysz\", -1.0),\n        (\"2iysz\", \"2ixsz\", +1.0),\n    ),\n    \"rotz_s\": (\n        (\"sx\", \"sy\", -1.0),\n        (\"sy\", \"sx\", +1.0),\n        (\"2ixsx\", \"2ixsy\", -1.0),\n        (\"2ixsy\", \"2ixsx\", +1.0),\n        (\"2iysx\", \"2iysy\", -1.0),\n        (\"2iysy\", \"2iysx\", +1.0),\n        (\"2izsx\", \"2izsy\", -1.0),\n        (\"2izsy\", \"2izsx\", +1.0),\n    ),\n    \"cs_i_{state}\": (\n        (\"ix\", \"iy\", -1.0),\n        (\"iy\", \"ix\", +1.0),\n        (\"2ixsx\", \"2iysx\", -1.0),\n        (\"2iysx\", \"2ixsx\", +1.0),\n        (\"2ixsy\", \"2iysy\", -1.0),\n        (\"2iysy\", \"2ixsy\", +1.0),\n        (\"2ixsz\", \"2iysz\", -1.0),\n        (\"2iysz\", \"2ixsz\", +1.0),\n    ),\n    \"cs_s_{state}\": (\n        (\"sx\", \"sy\", -1.0),\n        (\"sy\", \"sx\", +1.0),\n        (\"2ixsx\", \"2ixsy\", -1.0),\n        (\"2ixsy\", \"2ixsx\", +1.0),\n        (\"2iysx\", \"2iysy\", -1.0),\n        (\"2iysy\", \"2iysx\", +1.0),\n        (\"2izsx\", \"2izsy\", -1.0),\n        (\"2izsy\", \"2izsx\", +1.0),\n    ),\n    \"carrier_i\": (\n        (\"ix\", \"iy\", +1.0),\n        (\"iy\", \"ix\", -1.0),\n        (\"2ixsx\", \"2iysx\", +1.0),\n        (\"2iysx\", \"2ixsx\", -1.0),\n        (\"2ixsy\", \"2iysy\", +1.0),\n        (\"2iysy\", \"2ixsy\", -1.0),\n        (\"2ixsz\", \"2iysz\", +1.0),\n        (\"2iysz\", \"2ixsz\", -1.0),\n    ),\n    \"carrier_s\": (\n        (\"sx\", \"sy\", +1.0),\n        (\"sy\", \"sx\", -1.0),\n        (\"2ixsx\", \"2ixsy\", +1.0),\n        (\"2ixsy\", \"2ixsx\", -1.0),\n        (\"2iysx\", \"2iysy\", +1.0),\n        (\"2iysy\", \"2iysx\", -1.0),\n        (\"2izsx\", \"2izsy\", +1.0),\n        (\"2izsy\", \"2izsx\", -1.0),\n    ),\n    \"offset_i\": (\n        (\"ix\", \"iy\", +2.0 * np.pi),\n        (\"iy\", \"ix\", -2.0 * np.pi),\n        (\"2ixsx\", \"2iysx\", +2.0 * np.pi),\n        (\"2iysx\", \"2ixsx\", -2.0 * np.pi),\n        (\"2ixsy\", \"2iysy\", +2.0 * np.pi),\n        (\"2iysy\", \"2ixsy\", -2.0 * np.pi),\n        (\"2ixsz\", \"2iysz\", +2.0 * np.pi),\n        (\"2iysz\", \"2ixsz\", -2.0 * np.pi),\n    ),\n    \"offset_s\": (\n        (\"sx\", \"sy\", +2.0 * np.pi),\n        (\"sy\", \"sx\", -2.0 * np.pi),\n        (\"2ixsx\", \"2ixsy\", +2.0 * np.pi),\n        (\"2ixsy\", \"2ixsx\", -2.0 * np.pi),\n        (\"2iysx\", \"2iysy\", +2.0 * np.pi),\n        (\"2iysy\", \"2iysx\", -2.0 * np.pi),\n        (\"2izsx\", \"2izsy\", +2.0 * np.pi),\n        (\"2izsy\", \"2izsx\", -2.0 * np.pi),\n    ),\n    \"jeff_i\": (\n        (\"ix\", \"iy\", -2.0 * np.pi),\n        (\"iy\", \"ix\", +2.0 * np.pi),\n        (\"2ixsx\", \"2iysx\", -2.0 * np.pi),\n        (\"2iysx\", \"2ixsx\", +2.0 * np.pi),\n        (\"2ixsy\", \"2iysy\", -2.0 * np.pi),\n        (\"2iysy\", \"2ixsy\", +2.0 * np.pi),\n        (\"2ixsz\", \"2iysz\", -2.0 * np.pi),\n        (\"2iysz\", \"2ixsz\", +2.0 * np.pi),\n    ),\n    \"j_is_{state}\": (\n        (\"ix\", \"2iysz\", -np.pi),\n        (\"2iysz\", \"ix\", +np.pi),\n        (\"2ixsz\", \"iy\", -np.pi),\n        (\"iy\", \"2ixsz\", +np.pi),\n        (\"sx\", \"2izsy\", -np.pi),\n        (\"2izsy\", \"sx\", +np.pi),\n        (\"2izsx\", \"sy\", -np.pi),\n        (\"sy\", \"2izsx\", +np.pi),\n    ),\n    \"d_{state}\": (\n        (\"ix\", \"ix\", -1.0),\n        (\"iy\", \"iy\", -1.0),\n        (\"iz\", \"iz\", -1.0),\n        (\"sx\", \"sx\", -1.0),\n        (\"sy\", \"sy\", -1.0),\n        (\"sz\", \"sz\", -1.0),\n        (\"2ixsz\", \"2ixsz\", -1.0),\n        (\"2iysz\", \"2iysz\", -1.0),\n        (\"2izsx\", \"2izsx\", -1.0),\n        (\"2izsy\", \"2izsy\", -1.0),\n        (\"2ixsx\", \"2ixsx\", -1.0),\n        (\"2ixsy\", \"2ixsy\", -1.0),\n        (\"2iysx\", \"2iysx\", -1.0),\n        (\"2iysy\", \"2iysy\", -1.0),\n        (\"2izsz\", \"2izsz\", -1.0),\n    ),\n    \"b1x_i\": (\n        (\"iy\", \"iz\", -2.0 * np.pi),\n        (\"iz\", \"iy\", +2.0 * np.pi),\n        (\"2iysx\", \"2izsx\", -2.0 * np.pi),\n        (\"2izsx\", \"2iysx\", +2.0 * np.pi),\n        (\"2iysy\", \"2izsy\", -2.0 * np.pi),\n        (\"2izsy\", \"2iysy\", +2.0 * np.pi),\n        (\"2iysz\", \"2izsz\", -2.0 * np.pi),\n        (\"2izsz\", \"2iysz\", +2.0 * np.pi),\n    ),\n    \"b1y_i\": (\n        (\"iz\", \"ix\", -2.0 * np.pi),\n        (\"ix\", \"iz\", +2.0 * np.pi),\n        (\"2izsx\", \"2ixsx\", -2.0 * np.pi),\n        (\"2ixsx\", \"2izsx\", +2.0 * np.pi),\n        (\"2izsy\", \"2ixsy\", -2.0 * np.pi),\n        (\"2ixsy\", \"2izsy\", +2.0 * np.pi),\n        (\"2izsz\", \"2ixsz\", -2.0 * np.pi),\n        (\"2ixsz\", \"2izsz\", +2.0 * np.pi),\n    ),\n    \"b1x_s\": (\n        (\"sy\", \"sz\", -2.0 * np.pi),\n        (\"sz\", \"sy\", +2.0 * np.pi),\n        (\"2ixsy\", \"2ixsz\", -2.0 * np.pi),\n        (\"2ixsz\", \"2ixsy\", +2.0 * np.pi),\n        (\"2iysy\", \"2iysz\", -2.0 * np.pi),\n        (\"2iysz\", \"2iysy\", +2.0 * np.pi),\n        (\"2izsy\", \"2izsz\", -2.0 * np.pi),\n        (\"2izsz\", \"2izsy\", +2.0 * np.pi),\n    ),\n    \"b1y_s\": (\n        (\"sz\", \"sx\", -2.0 * np.pi),\n        (\"sx\", \"sz\", +2.0 * np.pi),\n        (\"2ixsz\", \"2ixsx\", -2.0 * np.pi),\n        (\"2ixsx\", \"2ixsz\", +2.0 * np.pi),\n        (\"2iysz\", \"2iysx\", -2.0 * np.pi),\n        (\"2iysx\", \"2iysz\", +2.0 * np.pi),\n        (\"2izsz\", \"2izsx\", -2.0 * np.pi),\n        (\"2izsx\", \"2izsz\", +2.0 * np.pi),\n    ),\n}\n_ATOMS = {\n    atoms: {\"i\": atoms[0], \"s\": atoms[1]} for atoms in (\"hn\", \"hc\", \"nh\", \"ch\", \"cn\")\n}\n\n\n@cache\ndef _build_vectors(basis: Basis) -> dict[str, np.ndarray]:\n    size = len(basis) * len(model.states)\n    vectors: defaultdict[str, np.ndarray] = defaultdict(lambda: np.zeros((size, 1)))\n    for index, (state, name) in enumerate(product(model.states, basis.components)):\n        vectors[f\"{name}_{state}\"][index] = 1.0\n        vectors[name][index] = 1.0\n    return dict(vectors)\n\n\ndef _get_indices(\n    basis: Basis, transition_name: str, state: str\n) -> tuple[tuple[list[int], list[int]], list[float]]:\n    rows: list[int] = []\n    cols: list[int] = []\n    vals: list[float] = []\n    offset = model.states.index(state) * len(basis)\n    for start, end, value in _TRANSITIONS[transition_name]:\n        if {start, end}.issubset(basis.components):\n            rows.append(basis.components.index(start) + offset)\n            cols.append(basis.components.index(end) + offset)\n            vals.append(value)\n    return (rows, cols), vals\n\n\ndef _build_spin_matrices(basis: Basis) -> dict[str, np.ndarray]:\n    size = len(basis) * len(model.states)\n    matrices: dict[str, np.ndarray] = defaultdict(lambda: np.zeros((size, size)))\n    for transition_name, state in product(_TRANSITIONS, model.states):\n        if not basis.type.endswith(\"_diff\") and transition_name.startswith(\"d_\"):\n            continue\n        name = transition_name.format(state=state)\n        indices, values = _get_indices(basis, transition_name, state)\n        if values:\n            matrices[name][indices] = values\n    return matrices\n\n\ndef _build_exchange_matrices(basis: Basis) -> dict[str, np.ndarray]:\n    matrices: dict[str, np.ndarray] = {}\n    for (i1, s1), (i2, s2) in permutations(enumerate(model.states), r=2):\n        name = f\"k{s1}{s2}\"\n        matrix = np.zeros((len(model.states), len(model.states)))\n        matrix[((i1, i2), i1)] = -1.0, 1.0\n        matrices[name] = np.kron(matrix, np.eye(len(basis)))\n    return matrices\n\n\n@cache\ndef _build_matrices(basis: Basis) -> dict[str, np.ndarray]:\n    return _build_exchange_matrices(basis) | _build_spin_matrices(basis)\n\n\n@dataclass(frozen=True)\nclass Basis:\n    type: str\n    extension: Literal[\"\", \"dq\", \"tq\"] = \"\"\n    spin_system: str = \"\"\n\n    @property\n    def name(self):\n        return \".\".join([self.type, self.extension, self.spin_system])\n\n    @property\n    def components(self):\n        return _BASES[self.type]\n\n    @property\n    def atoms(self):\n        return {\n            letter: atom\n            for letter, atom in _ATOMS.get(self.spin_system, {}).items()\n            if letter in self.type\n        }\n\n    @property\n    def vectors(self) -> dict[str, np.ndarray]:\n        return dict(_build_vectors(self))\n\n    @property\n    def matrices(self) -> dict[str, np.ndarray]:\n        return _build_matrices(self)\n\n    @property\n    def required_names(self) -> set[str]:\n        required_names = set(self.matrices)\n        required_names |= {f\"p{state}\" for state in model.states}\n        return required_names\n\n    def __len__(self):\n        return len(self.components)\n", "meta": {"hexsha": "6871d242a87563196769668b49bf737e1f7830fb", "size": 10945, "ext": "py", "lang": "Python", "max_stars_repo_path": "chemex/nmr/basis.py", "max_stars_repo_name": "gbouvignies/chemex", "max_stars_repo_head_hexsha": "b021650928b6db930281957222529bc6bcab8aa2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2015-03-16T16:45:42.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-17T08:43:58.000Z", "max_issues_repo_path": "chemex/nmr/basis.py", "max_issues_repo_name": "gbouvignies/chemex", "max_issues_repo_head_hexsha": "b021650928b6db930281957222529bc6bcab8aa2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 33, "max_issues_repo_issues_event_min_datetime": "2015-01-12T16:46:48.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-29T15:01:15.000Z", "max_forks_repo_path": "chemex/nmr/basis.py", "max_forks_repo_name": "gbouvignies/chemex", "max_forks_repo_head_hexsha": "b021650928b6db930281957222529bc6bcab8aa2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2015-01-15T21:53:16.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-04T15:33:52.000Z", "avg_line_length": 29.9863013699, "max_line_length": 85, "alphanum_fraction": 0.4339881224, "include": true, "reason": "import numpy", "num_tokens": 4224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.1921634922942738}}
{"text": "from collections import OrderedDict\n\nimport torch\nimport torchvision\n\nimport torch.nn.functional as F\nfrom torch import nn, Tensor\n\nfrom torchvision.ops import boxes as box_ops\n\nfrom torchvision.ops import roi_align\n\nfrom torchvision.models.detection import _utils as det_utils\n\nfrom torch.jit.annotations import Optional, List, Dict, Tuple\nimport numpy as np\n\nfrom TorchUtils import tensor_isin\nfrom nucls_model.torchvision_detection_utils.transforms import \\\n    remove_degenerate_bboxes\n\n\n@torch.jit._script_if_tracing\ndef global_nms(boxes, scores, iou_threshold):\n    # type: (Tensor, Tensor, float) -> Tensor\n    \"\"\"\n    Performs non-maximum suppression globally (regardless of category).\n\n    Parameters\n    ----------\n    boxes : Tensor[N, 4]\n        boxes where NMS will be performed. They\n        are expected to be in (x1, y1, x2, y2) format\n    scores : Tensor[N]\n        scores for each one of the boxes\n    iou_threshold : float\n        discards all overlapping boxes\n        with IoU > iou_threshold\n\n    Returns\n    -------\n    keep : Tensor\n        int64 tensor with the indices of\n        the elements that have been kept by NMS, sorted\n        in decreasing order of scores\n    \"\"\"\n    if boxes.numel() == 0:\n        return torch.empty((0,), dtype=torch.int64, device=boxes.device)\n    else:\n        keep = box_ops.nms(boxes, scores, iou_threshold)\n        return keep\n\n\n# noinspection LongLine,PyTypeHints\ndef fastrcnn_loss(\n        class_logits, box_regression, labels, regression_targets,\n        ignore_label=None, batched_nms=True):\n    # type: (Tensor, Tensor, List[Tensor], List[Tensor]) -> Tuple[Tensor, Tensor]\n    \"\"\"\n    Computes the loss for Faster R-CNN.\n\n    Arguments:\n        class_logits (Tensor)\n        box_regression (Tensor)\n        labels (list[BoxList])\n        regression_targets (Tensor)\n        ignore_label (int)\n        batched_nms (bool)\n\n    Returns:\n        classification_loss (Tensor)\n        box_loss (Tensor)\n    \"\"\"\n\n    labels = torch.cat(labels, dim=0)\n    regression_targets = torch.cat(regression_targets, dim=0)\n\n    # Mohamed: Ignore certain nuclei from classification loss.\n    # Do not to modify in-place since labels are used later here!!\n    clkeep = labels != ignore_label\n    classification_loss = F.cross_entropy(class_logits[clkeep], labels[clkeep])\n\n    # get indices that correspond to the regression targets for\n    # the corresponding ground truth labels, to be used with\n    # advanced indexing\n    sampled_pos_inds_subset = torch.nonzero(labels > 0).squeeze(1)\n    if batched_nms:\n        labels_pos = labels[sampled_pos_inds_subset]\n    else:\n        # Mohamed: only two classes (bckgrnd, frgrnd) for box regression\n        labs = 0 + labels\n        labs[labs > 1] = 1\n        labels_pos = labs[sampled_pos_inds_subset]\n    N, num_classes = class_logits.shape\n    box_regression = box_regression.reshape(N, -1, 4)\n\n    box_loss = det_utils.smooth_l1_loss(\n        box_regression[sampled_pos_inds_subset, labels_pos],\n        regression_targets[sampled_pos_inds_subset],\n        beta=1 / 9,\n        size_average=False,\n    )\n    box_loss = box_loss / labels.numel()\n\n    return classification_loss, box_loss\n\n\ndef maskrcnn_inference(x, labels):\n    # type: (Tensor, List[Tensor]) -> List[Tensor]\n    \"\"\"\n    From the results of the CNN, post process the masks\n    by taking the mask corresponding to the class with max\n    probability (which are of fixed size and directly output\n    by the CNN) and return the masks in the mask field of the BoxList.\n\n    Arguments:\n        x (Tensor): the mask logits\n        labels (list[BoxList]): bounding boxes that are used as\n            reference, one for ech image\n\n    Returns:\n        results (list[BoxList]): one BoxList for each image, containing\n            the extra field mask\n    \"\"\"\n    mask_prob = x.sigmoid()\n\n    # select masks corresponding to the predicted classes\n    num_masks = x.shape[0]\n    boxes_per_image = [label.shape[0] for label in labels]\n    labels = torch.cat(labels)\n    index = torch.arange(num_masks, device=labels.device)\n    mask_prob = mask_prob[index, labels][:, None]\n    mask_prob = mask_prob.split(boxes_per_image, dim=0)\n\n    return mask_prob\n\n\ndef project_masks_on_boxes(gt_masks, boxes, matched_idxs, M):\n    # type: (Tensor, Tensor, Tensor, int) -> Tensor\n    \"\"\"\n    Given segmentation masks and the bounding boxes corresponding\n    to the location of the masks in the image, this function\n    crops and resizes the masks in the position defined by the\n    boxes. This prepares the masks for them to be fed to the\n    loss computation as the targets.\n    \"\"\"\n    matched_idxs = matched_idxs.to(boxes)\n    rois = torch.cat([matched_idxs[:, None], boxes], dim=1)\n    gt_masks = gt_masks[:, None].to(rois)\n    return roi_align(gt_masks, rois, (M, M), 1.)[:, 0]\n\n\n# noinspection LongLine,PyTypeHints\ndef maskrcnn_loss(\n        mask_logits, proposals, gt_masks, gt_labels, mask_matched_idxs,\n        gt_ismask=None):\n    # type: (Tensor, List[Tensor], List[Tensor], List[Tensor], List[Tensor]) -> Tensor\n    \"\"\"\n    Arguments:\n        mask_logits (Tensor)\n        proposals (list[BoxList])\n\n    Return:\n        mask_loss (Tensor): scalar tensor containing the loss\n\n    Parameters\n    ----------\n    gt_ismask\n    mask_matched_idxs\n    gt_labels\n    proposals\n    mask_logits\n    gt_masks\n    \"\"\"\n\n    discretization_size = mask_logits.shape[-1]\n    labels = [gt_label[idxs] for gt_label, idxs in zip(gt_labels, mask_matched_idxs)]\n    mask_targets = [\n        project_masks_on_boxes(m, p, i, discretization_size)\n        for m, p, i in zip(gt_masks, proposals, mask_matched_idxs)\n    ]\n\n    labels = torch.cat(labels, dim=0)\n    mask_targets = torch.cat(mask_targets, dim=0)\n\n    # Mohamed: added this to disregard nuclei without masks (bboxes)\n    if gt_ismask is not None:\n        keep_idxs = [torch.where(t > 0)[0] for t in gt_ismask]\n        keep_list = [\n            tensor_isin(idxs, keep_idx)\n            for idxs, keep_idx in zip(mask_matched_idxs, keep_idxs)\n        ]\n        keep_array = torch.cat(keep_list).type(torch.bool)\n        mask_logits = mask_logits[keep_array, ...]\n        mask_targets = mask_targets[keep_array, ...]\n        labels = labels[keep_array]\n\n    # torch.mean (in binary_cross_entropy_with_logits) doesn't\n    # accept empty tensors, so handle it separately\n    if mask_targets.numel() == 0:\n        return mask_logits.sum() * 0\n\n    mask_loss = F.binary_cross_entropy_with_logits(\n        mask_logits[torch.arange(labels.shape[0], device=labels.device), labels], mask_targets\n    )\n    return mask_loss\n\n\ndef keypoints_to_heatmap(keypoints, rois, heatmap_size):\n    # type: (Tensor, Tensor, int) -> Tuple[Tensor, Tensor]\n    offset_x = rois[:, 0]\n    offset_y = rois[:, 1]\n    scale_x = heatmap_size / (rois[:, 2] - rois[:, 0])\n    scale_y = heatmap_size / (rois[:, 3] - rois[:, 1])\n\n    offset_x = offset_x[:, None]\n    offset_y = offset_y[:, None]\n    scale_x = scale_x[:, None]\n    scale_y = scale_y[:, None]\n\n    x = keypoints[..., 0]\n    y = keypoints[..., 1]\n\n    x_boundary_inds = x == rois[:, 2][:, None]\n    y_boundary_inds = y == rois[:, 3][:, None]\n\n    x = (x - offset_x) * scale_x\n    x = x.floor().long()\n    y = (y - offset_y) * scale_y\n    y = y.floor().long()\n\n    x[x_boundary_inds] = heatmap_size - 1\n    y[y_boundary_inds] = heatmap_size - 1\n\n    valid_loc = (x >= 0) & (y >= 0) & (x < heatmap_size) & (y < heatmap_size)\n    vis = keypoints[..., 2] > 0\n    valid = (valid_loc & vis).long()\n\n    lin_ind = y * heatmap_size + x\n    heatmaps = lin_ind * valid\n\n    return heatmaps, valid\n\n\n# noinspection LongLine\ndef _onnx_heatmaps_to_keypoints(maps, maps_i, roi_map_width, roi_map_height,\n                                widths_i, heights_i, offset_x_i, offset_y_i):\n    num_keypoints = torch.scalar_tensor(maps.size(1), dtype=torch.int64)\n\n    width_correction = widths_i / roi_map_width\n    height_correction = heights_i / roi_map_height\n\n    roi_map = F.interpolate(\n        maps_i[:, None], size=(int(roi_map_height), int(roi_map_width)), mode='bicubic', align_corners=False)[:, 0]\n\n    w = torch.scalar_tensor(roi_map.size(2), dtype=torch.int64)\n    pos = roi_map.reshape(num_keypoints, -1).argmax(dim=1)\n\n    x_int = (pos % w)\n    y_int = ((pos - x_int) // w)\n\n    x = (torch.tensor(0.5, dtype=torch.float32) + x_int.to(dtype=torch.float32)) * \\\n        width_correction.to(dtype=torch.float32)\n    y = (torch.tensor(0.5, dtype=torch.float32) + y_int.to(dtype=torch.float32)) * \\\n        height_correction.to(dtype=torch.float32)\n\n    xy_preds_i_0 = x + offset_x_i.to(dtype=torch.float32)\n    xy_preds_i_1 = y + offset_y_i.to(dtype=torch.float32)\n    xy_preds_i_2 = torch.ones((xy_preds_i_1.shape), dtype=torch.float32)  # noqa\n    xy_preds_i = torch.stack([xy_preds_i_0.to(dtype=torch.float32),\n                              xy_preds_i_1.to(dtype=torch.float32),\n                              xy_preds_i_2.to(dtype=torch.float32)], 0)\n\n    # mTODO: simplify when indexing without rank will be supported by ONNX\n    base = num_keypoints * num_keypoints + num_keypoints + 1\n    ind = torch.arange(num_keypoints)\n    ind = ind.to(dtype=torch.int64) * base\n    end_scores_i = roi_map.index_select(1, y_int.to(dtype=torch.int64)) \\\n        .index_select(2, x_int.to(dtype=torch.int64)).view(-1).index_select(0, ind.to(dtype=torch.int64))\n\n    return xy_preds_i, end_scores_i\n\n\n# noinspection LongLine\n@torch.jit._script_if_tracing\ndef _onnx_heatmaps_to_keypoints_loop(maps, rois, widths_ceil, heights_ceil,\n                                     widths, heights, offset_x, offset_y, num_keypoints):\n    xy_preds = torch.zeros((0, 3, int(num_keypoints)), dtype=torch.float32, device=maps.device)\n    end_scores = torch.zeros((0, int(num_keypoints)), dtype=torch.float32, device=maps.device)\n\n    for i in range(int(rois.size(0))):\n        xy_preds_i, end_scores_i = _onnx_heatmaps_to_keypoints(maps, maps[i],\n                                                               widths_ceil[i], heights_ceil[i],\n                                                               widths[i], heights[i],\n                                                               offset_x[i], offset_y[i])\n        xy_preds = torch.cat((xy_preds.to(dtype=torch.float32),\n                              xy_preds_i.unsqueeze(0).to(dtype=torch.float32)), 0)\n        end_scores = torch.cat((end_scores.to(dtype=torch.float32),\n                                end_scores_i.to(dtype=torch.float32).unsqueeze(0)), 0)\n    return xy_preds, end_scores\n\n\n# noinspection LongLine\ndef heatmaps_to_keypoints(maps, rois):\n    \"\"\"Extract predicted keypoint locations from heatmaps. Output has shape\n    (#rois, 4, #keypoints) with the 4 rows corresponding to (x, y, logit, prob)\n    for each keypoint.\n    \"\"\"\n    # This function converts a discrete image coordinate in a HEATMAP_SIZE x\n    # HEATMAP_SIZE image to a continuous keypoint coordinate. We maintain\n    # consistency with keypoints_to_heatmap_labels by using the conversion from\n    # Heckbert 1990: c = d + 0.5, where d is a discrete coordinate and c is a\n    # continuous coordinate.\n    offset_x = rois[:, 0]\n    offset_y = rois[:, 1]\n\n    widths = rois[:, 2] - rois[:, 0]\n    heights = rois[:, 3] - rois[:, 1]\n    widths = widths.clamp(min=1)\n    heights = heights.clamp(min=1)\n    widths_ceil = widths.ceil()\n    heights_ceil = heights.ceil()\n\n    num_keypoints = maps.shape[1]\n\n    if torchvision._is_tracing():\n        xy_preds, end_scores = _onnx_heatmaps_to_keypoints_loop(maps, rois,\n                                                                widths_ceil, heights_ceil, widths, heights,\n                                                                offset_x, offset_y,\n                                                                torch.scalar_tensor(num_keypoints, dtype=torch.int64))\n        return xy_preds.permute(0, 2, 1), end_scores\n\n    xy_preds = torch.zeros((len(rois), 3, num_keypoints), dtype=torch.float32, device=maps.device)\n    end_scores = torch.zeros((len(rois), num_keypoints), dtype=torch.float32, device=maps.device)\n    for i in range(len(rois)):\n        roi_map_width = int(widths_ceil[i].item())\n        roi_map_height = int(heights_ceil[i].item())\n        width_correction = widths[i] / roi_map_width\n        height_correction = heights[i] / roi_map_height\n        roi_map = F.interpolate(\n            maps[i][:, None], size=(roi_map_height, roi_map_width), mode='bicubic', align_corners=False)[:, 0]\n        # roi_map_probs = scores_to_probs(roi_map.copy())\n        w = roi_map.shape[2]\n        pos = roi_map.reshape(num_keypoints, -1).argmax(dim=1)\n\n        x_int = pos % w\n        y_int = (pos - x_int) // w\n        # assert (roi_map_probs[k, y_int, x_int] ==\n        #         roi_map_probs[k, :, :].max())\n        x = (x_int.float() + 0.5) * width_correction\n        y = (y_int.float() + 0.5) * height_correction\n        xy_preds[i, 0, :] = x + offset_x[i]\n        xy_preds[i, 1, :] = y + offset_y[i]\n        xy_preds[i, 2, :] = 1\n        end_scores[i, :] = roi_map[torch.arange(num_keypoints), y_int, x_int]\n\n    return xy_preds.permute(0, 2, 1), end_scores\n\n\n# noinspection LongLine\ndef keypointrcnn_loss(keypoint_logits, proposals, gt_keypoints, keypoint_matched_idxs):\n    # type: (Tensor, List[Tensor], List[Tensor], List[Tensor]) -> Tensor\n    N, K, H, W = keypoint_logits.shape\n    assert H == W\n    discretization_size = H\n    heatmaps = []\n    valid = []\n    for proposals_per_image, gt_kp_in_image, midx in zip(proposals, gt_keypoints, keypoint_matched_idxs):\n        kp = gt_kp_in_image[midx]\n        heatmaps_per_image, valid_per_image = keypoints_to_heatmap(\n            kp, proposals_per_image, discretization_size\n        )\n        heatmaps.append(heatmaps_per_image.view(-1))\n        valid.append(valid_per_image.view(-1))\n\n    keypoint_targets = torch.cat(heatmaps, dim=0)\n    valid = torch.cat(valid, dim=0).to(dtype=torch.uint8)\n    valid = torch.nonzero(valid).squeeze(1)\n\n    # torch.mean (in binary_cross_entropy_with_logits) does'nt\n    # accept empty tensors, so handle it sepaartely\n    if keypoint_targets.numel() == 0 or len(valid) == 0:\n        return keypoint_logits.sum() * 0\n\n    keypoint_logits = keypoint_logits.view(N * K, H * W)\n\n    keypoint_loss = F.cross_entropy(keypoint_logits[valid], keypoint_targets[valid])\n    return keypoint_loss\n\n\n# noinspection LongLine\ndef keypointrcnn_inference(x, boxes):\n    # type: (Tensor, List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]\n    kp_probs = []\n    kp_scores = []\n\n    boxes_per_image = [box.size(0) for box in boxes]  # noqa\n    x2 = x.split(boxes_per_image, dim=0)\n\n    for xx, bb in zip(x2, boxes):\n        kp_prob, scores = heatmaps_to_keypoints(xx, bb)\n        kp_probs.append(kp_prob)\n        kp_scores.append(scores)\n\n    return kp_probs, kp_scores\n\n\n# noinspection LongLine,DuplicatedCode\ndef _onnx_expand_boxes(boxes, scale):\n    # type: (Tensor, float) -> Tensor\n    w_half = (boxes[:, 2] - boxes[:, 0]) * .5\n    h_half = (boxes[:, 3] - boxes[:, 1]) * .5\n    x_c = (boxes[:, 2] + boxes[:, 0]) * .5\n    y_c = (boxes[:, 3] + boxes[:, 1]) * .5\n\n    w_half = w_half.to(dtype=torch.float32) * scale\n    h_half = h_half.to(dtype=torch.float32) * scale\n\n    boxes_exp0 = x_c - w_half\n    boxes_exp1 = y_c - h_half\n    boxes_exp2 = x_c + w_half\n    boxes_exp3 = y_c + h_half\n    boxes_exp = torch.stack((boxes_exp0, boxes_exp1, boxes_exp2, boxes_exp3), 1)\n    return boxes_exp\n\n\n# the next two functions should be merged inside Masker\n# but are kept here for the moment while we need them\n# temporarily for paste_mask_in_image\n# noinspection DuplicatedCode\ndef expand_boxes(boxes, scale):\n    # type: (Tensor, float) -> Tensor\n    if torchvision._is_tracing():\n        return _onnx_expand_boxes(boxes, scale)\n    w_half = (boxes[:, 2] - boxes[:, 0]) * .5\n    h_half = (boxes[:, 3] - boxes[:, 1]) * .5\n    x_c = (boxes[:, 2] + boxes[:, 0]) * .5\n    y_c = (boxes[:, 3] + boxes[:, 1]) * .5\n\n    w_half *= scale\n    h_half *= scale\n\n    boxes_exp = torch.zeros_like(boxes)\n    boxes_exp[:, 0] = x_c - w_half\n    boxes_exp[:, 2] = x_c + w_half\n    boxes_exp[:, 1] = y_c - h_half\n    boxes_exp[:, 3] = y_c + h_half\n    return boxes_exp\n\n\n# noinspection LongLine\n@torch.jit.unused\ndef expand_masks_tracing_scale(M, padding):\n    # type: (int, int) -> float\n    return torch.tensor(M + 2 * padding).to(torch.float32) / torch.tensor(M).to(torch.float32)\n\n\n# noinspection LongLine\ndef expand_masks(mask, padding):\n    # type: (Tensor, int) -> Tuple[Tensor, float]\n    M = mask.shape[-1]\n    if torch._C._get_tracing_state():  # could not import is_tracing(), not sure why\n        scale = expand_masks_tracing_scale(M, padding)\n    else:\n        scale = float(M + 2 * padding) / M\n    padded_mask = torch.nn.functional.pad(mask, (padding,) * 4)\n    return padded_mask, scale\n\n\n# noinspection LongLine\ndef paste_mask_in_image(mask, box, im_h, im_w, im_mask=None, ocode=None):\n    # type: (Tensor, Tensor, int, int) -> Tensor\n    TO_REMOVE = 1\n    w = int(box[2] - box[0] + TO_REMOVE)\n    h = int(box[3] - box[1] + TO_REMOVE)\n    w = max(w, 1)\n    h = max(h, 1)\n\n    # Set shape to [batchxCxHxW]\n    mask = mask.expand((1, 1, -1, -1))\n\n    # Resize mask\n    mask = F.interpolate(mask, size=(h, w), mode='bilinear', align_corners=False)\n    mask = mask[0][0]\n\n    x_0 = max(box[0], 0)\n    x_1 = min(box[2] + 1, im_w)\n    y_0 = max(box[1], 0)\n    y_1 = min(box[3] + 1, im_h)\n\n    if im_mask is None:\n        # sparse mask (only one object per channel)\n        im_mask = torch.zeros((im_h, im_w), dtype=mask.dtype, device=mask.device)\n        im_mask[y_0:y_1, x_0:x_1] = mask[\n            (y_0 - box[1]):(y_1 - box[1]), (x_0 - box[0]):(x_1 - box[0])\n        ]\n    else:\n        # Mohamed: dense mask (just one channel, where code represents object)\n        # IMPORTANT NOTE: this means we threshold probabilities.\n        patch = im_mask[y_0:y_1, x_0:x_1]\n        omask = mask[\n            (y_0 - box[1]):(y_1 - box[1]), (x_0 - box[0]):(x_1 - box[0])\n        ]\n        patch[omask > 0.5] = ocode\n\n    return im_mask\n\n\n# noinspection LongLine\ndef _onnx_paste_mask_in_image(mask, box, im_h, im_w):\n    one = torch.ones(1, dtype=torch.int64)\n    zero = torch.zeros(1, dtype=torch.int64)\n\n    w = (box[2] - box[0] + one)\n    h = (box[3] - box[1] + one)\n    w = torch.max(torch.cat((w, one)))\n    h = torch.max(torch.cat((h, one)))\n\n    # Set shape to [batchxCxHxW]\n    mask = mask.expand((1, 1, mask.size(0), mask.size(1)))\n\n    # Resize mask\n    mask = F.interpolate(mask, size=(int(h), int(w)), mode='bilinear', align_corners=False)\n    mask = mask[0][0]\n\n    x_0 = torch.max(torch.cat((box[0].unsqueeze(0), zero)))\n    x_1 = torch.min(torch.cat((box[2].unsqueeze(0) + one, im_w.unsqueeze(0))))\n    y_0 = torch.max(torch.cat((box[1].unsqueeze(0), zero)))\n    y_1 = torch.min(torch.cat((box[3].unsqueeze(0) + one, im_h.unsqueeze(0))))\n\n    unpaded_im_mask = mask[(y_0 - box[1]):(y_1 - box[1]),\n                           (x_0 - box[0]):(x_1 - box[0])]\n\n    # mTODO : replace below with a dynamic padding when support is added in ONNX\n\n    # pad y\n    zeros_y0 = torch.zeros(y_0, unpaded_im_mask.size(1))\n    zeros_y1 = torch.zeros(im_h - y_1, unpaded_im_mask.size(1))\n    concat_0 = torch.cat((zeros_y0,\n                          unpaded_im_mask.to(dtype=torch.float32),\n                          zeros_y1), 0)[0:im_h, :]\n    # pad x\n    zeros_x0 = torch.zeros(concat_0.size(0), x_0)\n    zeros_x1 = torch.zeros(concat_0.size(0), im_w - x_1)\n    im_mask = torch.cat((zeros_x0,\n                         concat_0,\n                         zeros_x1), 1)[:, :im_w]\n    return im_mask\n\n\n@torch.jit._script_if_tracing\ndef _onnx_paste_masks_in_image_loop(masks, boxes, im_h, im_w):\n    res_append = torch.zeros(0, im_h, im_w)\n    for i in range(masks.size(0)):\n        mask_res = _onnx_paste_mask_in_image(masks[i][0], boxes[i], im_h, im_w)\n        mask_res = mask_res.unsqueeze(0)\n        res_append = torch.cat((res_append, mask_res))\n    return res_append\n\n\n# noinspection LongLine\ndef paste_masks_in_image(masks, boxes, img_shape, padding=1):\n    # type: (Tensor, Tensor, Tuple[int, int], int) -> Tensor\n    masks, scale = expand_masks(masks, padding=padding)\n    boxes = expand_boxes(boxes, scale).to(dtype=torch.int64)\n    im_h, im_w = img_shape\n\n    if torchvision._is_tracing():\n        return _onnx_paste_masks_in_image_loop(masks, boxes,\n                                               torch.scalar_tensor(im_h, dtype=torch.int64),\n                                               torch.scalar_tensor(im_w, dtype=torch.int64))[:, None]\n    res = [\n        paste_mask_in_image(m[0], b, im_h, im_w)\n        for m, b in zip(masks, boxes)\n    ]\n    if len(res) > 0:\n        ret = torch.stack(res, dim=0)[:, None]\n    else:\n        ret = masks.new_empty((0, 1, im_h, im_w))\n    return ret\n\n# Mohamed: dense mask (code represents object)\ndef paste_and_densify_masks_in_image(masks, boxes, img_shape, padding=1):\n    # type: (Tensor, Tensor, Tuple[int, int], int) -> Tensor\n\n    masks, scale = expand_masks(masks, padding=padding)\n    boxes = expand_boxes(boxes, scale).to(dtype=torch.int64)\n    im_h, im_w = img_shape\n\n    if torchvision._is_tracing():\n        raise NotImplementedError(\n            \"I didn't support tracing yet. See paste_masks_in_image().\"\n        )\n\n    # IMPORTANT NOTE: in the dense mask, each object id encoded by a code\n    # that corresponds to (1 + idx), where idx is the index of the object\n    # in the labels/bbox tensors. For example, where im_mask == 5 corresponds\n    # to the nucleus whose label is in the 4th index in the labels tensor\n\n    # Find the order in which to overlay objects in the mask, from big to small\n    # This prevents a big object from covering a small one. Noe, however, that\n    # 1. This is still a \"lossy\" process, but it saves up on speed and makes\n    #    the memory requirement less dependent on the no of objects\n    # 2. We maintain the object codes' correspondence to (1 + idx)\n    areas = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])\n    idxs = torch.argsort(areas, descending=True)\n\n    im_mask = torch.zeros((im_h, im_w), dtype=torch.int64, device=masks.device)\n    for idx in idxs:\n        im_mask = paste_mask_in_image(\n            mask=masks[idx][0], box=boxes[idx], im_h=im_h, im_w=im_w,\n            im_mask=im_mask, ocode=idx + 1)\n\n    return im_mask\n\n# noinspection LongLine\nclass RoIHeads(torch.nn.Module):\n    __annotations__ = {\n        'box_coder': det_utils.BoxCoder,\n        'proposal_matcher': det_utils.Matcher,\n        'fg_bg_sampler': det_utils.BalancedPositiveNegativeSampler,\n    }\n\n    def __init__(self,\n                 box_roi_pool,\n                 box_head,\n                 box_predictor,\n                 # Faster R-CNN training\n                 fg_iou_thresh, bg_iou_thresh,\n                 batch_size_per_image, positive_fraction,\n                 bbox_reg_weights,\n                 # Faster R-CNN inference\n                 score_thresh,\n                 nms_thresh,\n                 detections_per_img,\n                 # Mask\n                 mask_roi_pool=None,\n                 mask_head=None,\n                 mask_predictor=None,\n                 keypoint_roi_pool=None,\n                 keypoint_head=None,\n                 keypoint_predictor=None,\n                 # added by Mohamed\n                 batched_nms=True,  # inference nms independently per class?\n                 indep_classif_boxes=False,\n                 classification_bbox_size=None,  # float\n                 cconvhead=None,  # extra conv layers for classification\n                 sattention_head=None,  # nuclei are aware of each other\n                 ignore_label: int = None,  # label to ignore in classif. loss\n                 ):\n        super(RoIHeads, self).__init__()\n\n        if indep_classif_boxes:\n            assert classification_bbox_size is not None\n\n        self.box_similarity = box_ops.box_iou\n        # assign ground-truth boxes for each proposal\n        self.proposal_matcher = det_utils.Matcher(\n            fg_iou_thresh,\n            bg_iou_thresh,\n            allow_low_quality_matches=False)\n\n        self.fg_bg_sampler = det_utils.BalancedPositiveNegativeSampler(\n            batch_size_per_image,\n            positive_fraction)\n\n        if bbox_reg_weights is None:\n            bbox_reg_weights = (10., 10., 5., 5.)\n        self.box_coder = det_utils.BoxCoder(bbox_reg_weights)\n\n        self.box_roi_pool = box_roi_pool\n        self.box_head = box_head\n        self.box_predictor = box_predictor\n\n        self.score_thresh = score_thresh\n        self.nms_thresh = nms_thresh\n        self.detections_per_img = detections_per_img\n\n        self.mask_roi_pool = mask_roi_pool\n        self.mask_head = mask_head\n        self.mask_predictor = mask_predictor\n\n        self.keypoint_roi_pool = keypoint_roi_pool\n        self.keypoint_head = keypoint_head\n        self.keypoint_predictor = keypoint_predictor\n\n        # added by Mohamed\n        self.batched_nms = batched_nms\n        self.indep_classif_boxes = indep_classif_boxes\n        self.classification_bbox_size = classification_bbox_size\n        self.halfclbox = self.classification_bbox_size / 2 if \\\n            classification_bbox_size is not None else None\n        self.cconvhead = cconvhead\n        self.sattention_head = sattention_head\n        self.ignore_label = ignore_label\n\n    def has_mask(self):\n        if self.mask_roi_pool is None:\n            return False\n        if self.mask_head is None:\n            return False\n        if self.mask_predictor is None:\n            return False\n        return True\n\n    def has_keypoint(self):\n        if self.keypoint_roi_pool is None:\n            return False\n        if self.keypoint_head is None:\n            return False\n        if self.keypoint_predictor is None:\n            return False\n        return True\n\n    def assign_targets_to_proposals(self, proposals, gt_boxes, gt_labels):\n        # type: (List[Tensor], List[Tensor], List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]\n        matched_idxs = []\n        labels = []\n        for proposals_in_image, gt_boxes_in_image, gt_labels_in_image in zip(proposals, gt_boxes, gt_labels):\n\n            if gt_boxes_in_image.numel() == 0:\n                # Background image\n                device = proposals_in_image.device\n                clamped_matched_idxs_in_image = torch.zeros(\n                    (proposals_in_image.shape[0],), dtype=torch.int64, device=device\n                )\n                labels_in_image = torch.zeros(\n                    (proposals_in_image.shape[0],), dtype=torch.int64, device=device\n                )\n            else:\n                #  set to self.box_similarity when https://github.com/pytorch/pytorch/issues/27495 lands\n                match_quality_matrix = box_ops.box_iou(gt_boxes_in_image, proposals_in_image)\n                matched_idxs_in_image = self.proposal_matcher(match_quality_matrix)\n\n                clamped_matched_idxs_in_image = matched_idxs_in_image.clamp(min=0)\n\n                labels_in_image = gt_labels_in_image[clamped_matched_idxs_in_image]\n                labels_in_image = labels_in_image.to(dtype=torch.int64)\n\n                # Label background (below the low threshold)\n                bg_inds = matched_idxs_in_image == self.proposal_matcher.BELOW_LOW_THRESHOLD\n                labels_in_image[bg_inds] = 0\n\n                # Label ignore proposals (between low and high thresholds)\n                ignore_inds = matched_idxs_in_image == self.proposal_matcher.BETWEEN_THRESHOLDS\n                labels_in_image[ignore_inds] = -1  # -1 is ignored by sampler\n\n            matched_idxs.append(clamped_matched_idxs_in_image)\n            labels.append(labels_in_image)\n        return matched_idxs, labels\n\n    def subsample(self, labels):\n        # type: (List[Tensor]) -> List[Tensor]\n        sampled_pos_inds, sampled_neg_inds = self.fg_bg_sampler(labels)\n        sampled_inds = []\n        for img_idx, (pos_inds_img, neg_inds_img) in enumerate(\n            zip(sampled_pos_inds, sampled_neg_inds)\n        ):\n            img_sampled_inds = torch.nonzero(pos_inds_img | neg_inds_img).squeeze(1)\n            sampled_inds.append(img_sampled_inds)\n        return sampled_inds\n\n    # noinspection PyMethodMayBeStatic\n    def add_gt_proposals(self, proposals, gt_boxes):\n        # type: (List[Tensor], List[Tensor]) -> List[Tensor]\n        proposals = [\n            torch.cat((proposal, gt_box))\n            for proposal, gt_box in zip(proposals, gt_boxes)\n        ]\n\n        return proposals\n\n    def check_targets(self, targets):\n        # type: (Optional[List[Dict[str, Tensor]]]) -> None\n        assert targets is not None\n        assert all([\"boxes\" in t for t in targets])\n        assert all([\"labels\" in t for t in targets])\n        if self.has_mask():\n            assert all([\"masks\" in t for t in targets])\n\n    def select_training_samples(self,\n                                proposals,  # type: List[Tensor]\n                                targets     # type: Optional[List[Dict[str, Tensor]]]\n                                ):\n        # type: (...) -> Tuple[List[Tensor], List[Tensor], List[Tensor], List[Tensor]]\n        self.check_targets(targets)\n        assert targets is not None\n        dtype = proposals[0].dtype\n        device = proposals[0].device\n\n        gt_boxes = [t[\"boxes\"].to(dtype) for t in targets]\n        gt_labels = [t[\"labels\"] for t in targets]\n\n        # append ground-truth bboxes to propos\n        proposals = self.add_gt_proposals(proposals, gt_boxes)\n\n        # get matching gt indices for each proposal\n        matched_idxs, labels = self.assign_targets_to_proposals(proposals, gt_boxes, gt_labels)\n        # sample a fixed proportion of positive-negative proposals\n        sampled_inds = self.subsample(labels)\n        matched_gt_boxes = []\n        num_images = len(proposals)\n        for img_id in range(num_images):\n            img_sampled_inds = sampled_inds[img_id]\n            proposals[img_id] = proposals[img_id][img_sampled_inds]\n            labels[img_id] = labels[img_id][img_sampled_inds]\n            matched_idxs[img_id] = matched_idxs[img_id][img_sampled_inds]\n\n            gt_boxes_in_image = gt_boxes[img_id]\n            if gt_boxes_in_image.numel() == 0:\n                gt_boxes_in_image = torch.zeros((1, 4), dtype=dtype, device=device)\n            matched_gt_boxes.append(gt_boxes_in_image[matched_idxs[img_id]])\n\n        regression_targets = self.box_coder.encode(matched_gt_boxes, proposals)\n        return proposals, matched_idxs, labels, regression_targets\n\n    def postprocess_detections_globalnms(self,\n                               class_logits,    # type: Tensor\n                               box_regression,  # type: Tensor\n                               proposals,       # type: List[Tensor]\n                               image_shapes     # type: List[Tuple[int, int]]\n                               ):\n        # type: (...) -> Tuple[List[Tensor], List[Tensor], List[Tensor]]\n        device = class_logits.device\n        hdim = class_logits.shape[0]\n        num_classes = class_logits.shape[-1]\n\n        boxes_per_image = [boxes_in_image.shape[0] for boxes_in_image in proposals]\n        pred_boxes = self.box_coder.decode(box_regression, proposals)\n\n        pred_scores = F.softmax(class_logits, -1)\n\n        pred_boxes_list = pred_boxes.split(boxes_per_image, 0)\n        pred_scores_list = pred_scores.split(boxes_per_image, 0)\n\n        all_boxes = []\n        all_objectness = []  # probability this is an object\n        all_labels = []\n        all_probabs = []  # probabilities for each class\n        all_keptidxs = []\n        for boxes, scores, image_shape in zip(pred_boxes_list, pred_scores_list, image_shapes):\n\n            boxes = box_ops.clip_boxes_to_image(boxes, image_shape)\n\n            # remove predictions with the background label\n            boxes = boxes[:, 1, :]\n            scores = scores[:, 1:]\n\n            # we define the \"objectness\" as the sum of non-background scores\n            objectness = scores.sum(1)\n\n            # indices of detections that are kept nms and postprocessing\n            keptidxs = torch.arange(hdim, device=device)\n\n            # Mohamed: prevent (set as zero prob.) ignore_label prediction\n            if self.ignore_label is not None:\n                ignore = [j == self.ignore_label for j in range(1, num_classes)]\n                scores[:, ignore] = 0.\n\n            # remove low scoring boxes (i.e. low \"objectness\").\n            inds = torch.nonzero(objectness > self.score_thresh).squeeze(1)\n            boxes, scores, objectness, keptidxs = boxes[inds], scores[inds], objectness[inds], keptidxs[inds]\n\n            # remove empty boxes\n            keep = box_ops.remove_small_boxes(boxes, min_size=1e-2)\n            boxes, scores, objectness, keptidxs = boxes[keep], scores[keep], objectness[keep], keptidxs[keep]\n\n            # global nms, regardless of class\n            keep = global_nms(boxes=boxes, scores=objectness, iou_threshold=self.nms_thresh)\n\n            # keep only topk scoring predictions\n            keep = keep[:self.detections_per_img]\n            boxes, scores, objectness, keptidxs = boxes[keep], scores[keep], objectness[keep], keptidxs[keep]\n\n            if boxes.shape[0] > 0:\n                # make sure probabilities add to 1, while preserving the\n                # ignore_label columns as zero, so we divide by total instead\n                # of using softmax\n                scores = scores / scores.sum(1)[:, None]\n\n                # label is argmax, just like ordinary classification tasks. Keep\n                # in mind that we got rid of the background channel, so add 1\n                labels = torch.argmax(scores, dim=1) + 1\n            else:\n                # empty tensor; nothing was left after filtering out junk\n                labels = scores[:, 0].type(torch.int64)\n\n            all_boxes.append(boxes)\n            all_objectness.append(objectness)\n            all_labels.append(labels)\n            all_probabs.append(scores)\n            all_keptidxs.append(keptidxs)\n\n        return all_boxes, all_objectness, all_labels, all_probabs, all_keptidxs\n\n\n    def postprocess_detections(self,\n                               class_logits,    # type: Tensor\n                               box_regression,  # type: Tensor\n                               proposals,       # type: List[Tensor]\n                               image_shapes     # type: List[Tuple[int, int]]\n                               ):\n        # type: (...) -> Tuple[List[Tensor], List[Tensor], List[Tensor]]\n        device = class_logits.device\n        num_classes = class_logits.shape[-1]\n\n        boxes_per_image = [boxes_in_image.shape[0] for boxes_in_image in proposals]\n        pred_boxes = self.box_coder.decode(box_regression, proposals)\n\n        pred_scores = F.softmax(class_logits, -1)\n\n        pred_boxes_list = pred_boxes.split(boxes_per_image, 0)\n        pred_scores_list = pred_scores.split(boxes_per_image, 0)\n\n        all_boxes = []\n        all_scores = []\n        all_labels = []\n        for boxes, scores, image_shape in zip(pred_boxes_list, pred_scores_list, image_shapes):\n            boxes = box_ops.clip_boxes_to_image(boxes, image_shape)\n\n            # create labels for each prediction\n            labels = torch.arange(num_classes, device=device)\n            labels = labels.view(1, -1).expand_as(scores)\n\n            # remove predictions with the background label\n            boxes = boxes[:, 1:]\n            scores = scores[:, 1:]\n            labels = labels[:, 1:]\n\n            # Mohamed: remove self.ignore_label predictions\n            if self.ignore_label is not None:\n                keep = [j != self.ignore_label for j in range(1, num_classes)]\n                boxes = boxes[:, keep]\n                scores = scores[:, keep]\n                labels = labels[:, keep]\n\n            # batch everything, by making every class prediction be a separate instance\n            boxes = boxes.reshape(-1, 4)\n            scores = scores.reshape(-1)\n            labels = labels.reshape(-1)\n\n            # remove low scoring boxes\n            inds = torch.nonzero(scores > self.score_thresh).squeeze(1)\n            boxes, scores, labels = boxes[inds], scores[inds], labels[inds]\n\n            # remove empty boxes\n            keep = box_ops.remove_small_boxes(boxes, min_size=1e-2)\n            boxes, scores, labels = boxes[keep], scores[keep], labels[keep]\n\n            # independent nms per class\n            keep = box_ops.batched_nms(\n                boxes=boxes, scores=scores, idxs=labels,\n                iou_threshold=self.nms_thresh)\n\n            # keep only topk scoring predictions\n            keep = keep[:self.detections_per_img]\n            boxes, scores, labels = boxes[keep], scores[keep], labels[keep]\n\n            all_boxes.append(boxes)\n            all_scores.append(scores)\n            all_labels.append(labels)\n\n        return all_boxes, all_scores, all_labels\n\n    def get_classification_proposals(self, proposals, image_shapes):\n\n        classification_proposals = []\n        for pno, prop in enumerate(proposals):\n            xmins, ymins, xmaxs, ymaxs = torch.chunk(prop, 4, dim=1)\n            xs = xmins + (xmaxs - xmins) / 2\n            ys = ymins + (ymaxs - ymins) / 2\n            boxes = torch.cat(\n                [xs - self.halfclbox, ys - self.halfclbox,\n                 xs + self.halfclbox, ys + self.halfclbox],\n                dim=1)\n\n            # adjust boxes\n            dim0, dim1 = image_shapes[pno]\n            boxes, _ = remove_degenerate_bboxes(\n                boxes=boxes, dim0=dim0, dim1=dim1, min_boxside=0)\n\n            classification_proposals.append(boxes)\n\n        return classification_proposals\n\n    def forward(self,\n                features,  # type: Dict[str, Tensor]\n                proposals,  # type: List[Tensor]\n                image_shapes,  # type: List[Tuple[int, int]]\n                targets=None,  # type: Optional[List[Dict[str, Tensor]]]\n                _just_return_probabs=False,  # type: bool\n                _cprobabs=None,  # type: List[Tensor]\n                _return_prepr=False,  # type: bool\n                ):\n        # type: (...) -> Tuple[List[Dict[str, Tensor]], Dict[str, Tensor]]\n        \"\"\"\n        Arguments:\n            features (List[Tensor])\n            proposals (List[Tensor[N, 4]])\n            image_shapes (List[Tuple[H, W]])\n            targets (List[Dict])\n            _just_return_probabs (bool): If true, just returns logits for each\n                of the proposals without postprocessing. This is only applies\n                if not self.training.\n            _cprobabs (List[Tensor]): If given, these \"past logits\" (obtained\n                from variations of the proposals) would be aggregated to\n                the class_logits as a form of test-time augmentation. This\n                obviously only applies if not self.training\n            _return_prepr (bool): also return intermediate representations?\n        \"\"\"\n        if targets is not None:\n            for t in targets:\n                # mTODO: https://github.com/pytorch/pytorch/issues/26731\n                floating_point_types = (torch.float, torch.double, torch.half)\n                assert t[\"boxes\"].dtype in floating_point_types, 'target boxes must of float type'\n                assert t[\"labels\"].dtype == torch.int64, 'target labels must of int64 type'\n                if self.has_keypoint():\n                    assert t[\"keypoints\"].dtype == torch.float32, 'target keypoints must of float type'\n\n        if self.training:\n            proposals, matched_idxs, labels, regression_targets = self.select_training_samples(proposals, targets)\n        else:\n            labels = None\n            regression_targets = None\n            matched_idxs = None\n\n        # Added by Mohamed: Classification proposals use an\n        # independent (possibly wider) region beyond object boundary\n        cproposals = None if not self.indep_classif_boxes else \\\n            self.get_classification_proposals(proposals=proposals, image_shapes=image_shapes)\n\n        # Mohamed: Independent, extra convolutions for classification\n        cfeatures = None if self.cconvhead is None else OrderedDict(\n            {k: self.cconvhead(v) for k, v in features.items()}\n        )\n\n        # roi pooling for the object bbox\n        box_features = self.box_roi_pool(features, proposals, image_shapes)\n        if (cproposals is not None) or (cfeatures is not None):\n            cbox_features = self.box_roi_pool(\n                cfeatures or features, cproposals or proposals, image_shapes)\n        else:\n            cbox_features = None\n\n        # flatten\n        box_features = self.box_head(box_features)\n        cbox_features = self.box_head(cbox_features) \\\n            if cbox_features is not None else None\n\n        # Mohamed: per-fov nuclei attentive to each other\n        if self.sattention_head is not None:\n\n            # this only applies for classification\n            if cbox_features is None:\n                cbox_features = 0. + box_features\n\n            # get the start index for each group of proposals from one FOV\n            fov_start_idxs = np.cumsum(\n                [0] + [j.shape[0] for j in proposals[:-1]]).tolist()\n\n            # pass through self-attention head\n            cbox_features = self.sattention_head(\n                cbox_features, fov_start_idxs=fov_start_idxs)\n\n        # pass through fully-connected layers\n        if cbox_features is None:\n            class_logits, box_regression = self.box_predictor(box_features)\n        else:\n            _, box_regression = self.box_predictor(box_features, get_scores=False)\n            class_logits, _ = self.box_predictor(cbox_features, get_deltas=False)\n\n        result = torch.jit.annotate(List[Dict[str, torch.Tensor]], [])\n        losses = {}\n        if self.training:\n            assert labels is not None and regression_targets is not None\n            loss_classifier, loss_box_reg = fastrcnn_loss(\n                class_logits=class_logits,\n                box_regression=box_regression,\n                labels=labels,\n                regression_targets=regression_targets,\n                ignore_label=self.ignore_label,\n                batched_nms=self.batched_nms,\n            )\n            losses = {\n                \"loss_classifier\": loss_classifier,\n                \"loss_box_reg\": loss_box_reg\n            }\n        else:\n            # Mohamed: maybe just return class probabs without postprocessing\n            # Note that this INCLUDES the background class\n            if _just_return_probabs:\n                return F.softmax(class_logits, -1)\n\n            # Mohamed: \"past logits\" (obtained from variations of proposals)\n            # would be aggregated to the class_logits as a form of test-time\n            # augmentation. This obviously only applies if not self.training\n            if _cprobabs is not None:\n                class_logits = F.softmax(class_logits, -1)\n                class_logits += _cprobabs\n\n            if self.batched_nms:\n                boxes, scores, labels = self.postprocess_detections(class_logits, box_regression, proposals, image_shapes)\n                probabs = [None] * len(boxes)\n                keptidxs = [None] * len(boxes)\n            else:\n                boxes, scores, labels, probabs, keptidxs = self.postprocess_detections_globalnms(class_logits, box_regression, proposals, image_shapes)\n            num_images = len(boxes)\n\n            if _return_prepr:\n                bperim = [boxes_in_image.shape[0] for boxes_in_image in proposals]\n                bfeats = box_features.split(bperim, 0)\n                cbfeats = None if cbox_features is None else cbox_features.split(bperim, 0)\n                clogits = class_logits.split(bperim, 0)\n\n            for i in range(num_images):\n                out = {\n                    \"boxes\": boxes[i],\n                    \"labels\": labels[i],\n                    \"scores\": scores[i],\n                    \"probabs\": probabs[i],\n                }\n                if _return_prepr:\n                    out.update({\n                        \"box_features\": bfeats[i][keptidxs[i], :],\n                        \"cbox_features\": None if cbfeats is None else cbfeats[i][keptidxs[i], :],\n                        \"clogits\": clogits[i][keptidxs[i], :],\n                    })\n                result.append(out)\n\n        if self.has_mask():\n            mask_proposals = [p[\"boxes\"] for p in result]\n            if self.training:\n                assert matched_idxs is not None\n                # during training, only focus on positive boxes\n                num_images = len(proposals)\n                mask_proposals = []\n                pos_matched_idxs = []\n                for img_id in range(num_images):\n                    pos = torch.nonzero(labels[img_id] > 0).squeeze(1)\n                    mask_proposals.append(proposals[img_id][pos])\n                    pos_matched_idxs.append(matched_idxs[img_id][pos])\n            else:\n                pos_matched_idxs = None\n\n            if self.mask_roi_pool is not None:\n                mask_features = self.mask_roi_pool(features, mask_proposals, image_shapes)\n                mask_features = self.mask_head(mask_features)\n                mask_logits = self.mask_predictor(mask_features)\n            else:\n                # noinspection PyUnusedLocal\n                mask_logits = torch.tensor(0)\n                raise Exception(\"Expected mask_roi_pool to be not None\")\n\n            loss_mask = {}\n            if self.training:\n                assert targets is not None\n                assert pos_matched_idxs is not None\n                assert mask_logits is not None\n\n                # Mohamed: if not self.batched_nms, just one mask per object\n                gt_labels = [0 + t[\"labels\"] for t in targets]\n                if not self.batched_nms:\n                    for labs in gt_labels:\n                        labs[labs > 1] = 1\n\n                gt_masks = [t[\"masks\"] for t in targets]\n                # Mohamed: added to ignore bboxes (false masks)\n                #  so that they don't contribute to the mask loss\n                if 'ismask' in targets[0]:\n                    gt_ismask = [t['ismask'] for t in targets]\n                else:\n                    gt_ismask = None\n                rcnn_loss_mask = maskrcnn_loss(\n                    mask_logits=mask_logits, proposals=mask_proposals,\n                    gt_masks=gt_masks, gt_labels=gt_labels,\n                    mask_matched_idxs=pos_matched_idxs,\n                    gt_ismask=gt_ismask)\n                loss_mask = {\n                    \"loss_mask\": rcnn_loss_mask\n                }\n            else:\n                # Mohamed: if not self.batched_nms, just one mask per object\n                mask_labels = [0 + r[\"labels\"] for r in result]\n                if not self.batched_nms:\n                    for labs in mask_labels:\n                        labs[labs > 1] = 1\n                masks_probs = maskrcnn_inference(mask_logits, mask_labels)\n                for mask_prob, r in zip(masks_probs, result):\n                    r[\"masks\"] = mask_prob\n\n            losses.update(loss_mask)\n\n        # keep none checks in if conditional so torchscript will conditionally\n        # compile each branch\n        if self.keypoint_roi_pool is not None and self.keypoint_head is not None \\\n                and self.keypoint_predictor is not None:\n            keypoint_proposals = [p[\"boxes\"] for p in result]\n            if self.training:\n                # during training, only focus on positive boxes\n                num_images = len(proposals)\n                keypoint_proposals = []\n                pos_matched_idxs = []\n                assert matched_idxs is not None\n                for img_id in range(num_images):\n                    pos = torch.nonzero(labels[img_id] > 0).squeeze(1)\n                    keypoint_proposals.append(proposals[img_id][pos])\n                    pos_matched_idxs.append(matched_idxs[img_id][pos])\n            else:\n                pos_matched_idxs = None\n\n            keypoint_features = self.keypoint_roi_pool(features, keypoint_proposals, image_shapes)\n            keypoint_features = self.keypoint_head(keypoint_features)\n            keypoint_logits = self.keypoint_predictor(keypoint_features)\n\n            loss_keypoint = {}\n            if self.training:\n                assert targets is not None\n                assert pos_matched_idxs is not None\n\n                gt_keypoints = [t[\"keypoints\"] for t in targets]\n                rcnn_loss_keypoint = keypointrcnn_loss(\n                    keypoint_logits, keypoint_proposals,\n                    gt_keypoints, pos_matched_idxs)\n                loss_keypoint = {\n                    \"loss_keypoint\": rcnn_loss_keypoint\n                }\n            else:\n                assert keypoint_logits is not None\n                assert keypoint_proposals is not None\n\n                keypoints_probs, kp_scores = keypointrcnn_inference(keypoint_logits, keypoint_proposals)\n                for keypoint_prob, kps, r in zip(keypoints_probs, kp_scores, result):\n                    r[\"keypoints\"] = keypoint_prob\n                    r[\"keypoints_scores\"] = kps\n\n            losses.update(loss_keypoint)\n\n        return result, losses\n", "meta": {"hexsha": "f0dbbadf1bcb335c606491f6ccb3c001a8c57b5b", "size": 49387, "ext": "py", "lang": "Python", "max_stars_repo_path": "nucls_model/ROIHeads.py", "max_stars_repo_name": "CancerDataScience/NuCLS", "max_stars_repo_head_hexsha": "c172b55b18d4ea78c3f51a8fd28ee6c2595c8360", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-02-18T18:24:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T07:37:27.000Z", "max_issues_repo_path": "nucls_model/ROIHeads.py", "max_issues_repo_name": "CancerDataScience/NuCLS", "max_issues_repo_head_hexsha": "c172b55b18d4ea78c3f51a8fd28ee6c2595c8360", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-03-06T03:26:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-27T07:45:29.000Z", "max_forks_repo_path": "nucls_model/ROIHeads.py", "max_forks_repo_name": "CancerDataScience/NuCLS", "max_forks_repo_head_hexsha": "c172b55b18d4ea78c3f51a8fd28ee6c2595c8360", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-02-24T14:06:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T09:26:58.000Z", "avg_line_length": 39.8603712672, "max_line_length": 151, "alphanum_fraction": 0.6081357442, "include": true, "reason": "import numpy", "num_tokens": 11874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.19216348296321353}}
{"text": "\"\"\"A module containing the core message-passing functions for belief propagation\"\"\"\n\nimport functools\nimport inspect\nfrom dataclasses import dataclass\nfrom typing import Any, Callable, Dict, Hashable, Mapping, Optional, Tuple\n\nimport jax\nimport jax.numpy as jnp\nimport numpy as np\nfrom jax.scipy.special import logsumexp\n\nfrom pgmax.factor import FAC_TO_VAR_UPDATES\n\nfrom . import bp_state as bpstate\nfrom . import bp_utils\nfrom .bp_state import BPArrays, BPState, Evidence, FToVMessages, LogPotentials\n\n\n@dataclass(frozen=True, eq=False)\nclass BeliefPropagation:\n    \"\"\"Belief propagation functions.\n\n    Arguments:\n        init: Function to create log_potentials, ftov_msgs and evidence.\n            Args:\n                log_potentials_updates: Optional dictionary containing log_potentials updates.\n                ftov_msgs_updates: Optional dictionary containing ftov_msgs updates.\n                evidence_updates: Optional dictionary containing evidence updates.\n            Returns:\n                A BPArrays with the log_potentials, ftov_msgs and evidence.\n\n        update: Function to update log_potentials, ftov_msgs and evidence.\n            Args:\n                bp_arrays: Optional arrays of log_potentials, ftov_msgs, evidence.\n                log_potentials_updates: Optional dictionary containing log_potentials updates.\n                ftov_msgs_updates: Optional dictionary containing ftov_msgs updates.\n                evidence_updates: Optional dictionary containing evidence updates.\n            Returns:\n                A BPArrays with the updated log_potentials, ftov_msgs and evidence.\n\n        run_bp: Function to run belief propagation for num_iters with a damping_factor.\n            Args:\n                bp_arrays: Initial arrays of log_potentials, ftov_msgs, evidence.\n                num_iters: Number of belief propagation iterations.\n                damping: The damping factor to use for message updates between one timestep and the next.\n            Returns:\n                A BPArrays containing the updated ftov_msgs.\n\n        get_bp_state: Function to reconstruct the BPState from a BPArrays.\n            Args:\n                bp_arrays: A BPArrays containing log_potentials, ftov_msgs, evidence.\n            Returns:\n                The reconstructed BPState\n\n        get_beliefs: Function to calculate beliefs from a BPArrays.\n            Args:\n                bp_arrays: A BPArrays containing log_potentials, ftov_msgs, evidence.\n            Returns:\n                beliefs: Beliefs returned by belief propagation.\n    \"\"\"\n\n    init: Callable\n    update: Callable\n    run_bp: Callable\n    to_bp_state: Callable\n    get_beliefs: Callable\n\n\ndef BP(bp_state: BPState, temperature: float = 0.0) -> BeliefPropagation:\n    \"\"\"Function for generating belief propagation functions.\n\n    Args:\n        bp_state: Belief propagation state.\n        temperature: Temperature for loopy belief propagation.\n            1.0 corresponds to sum-product, 0.0 corresponds to max-product.\n\n    Returns:\n        Belief propagation functions.\n    \"\"\"\n    wiring = bp_state.fg_state.wiring\n    edges_num_states = np.concatenate(\n        [wiring[factor_type].edges_num_states for factor_type in FAC_TO_VAR_UPDATES]\n    )\n    max_msg_size = int(np.max(edges_num_states))\n\n    var_states_for_edges = np.concatenate(\n        [wiring[factor_type].var_states_for_edges for factor_type in FAC_TO_VAR_UPDATES]\n    )\n\n    # Inference argumnets per factor type\n    inference_arguments: Dict[type, Mapping] = {}\n    for factor_type in FAC_TO_VAR_UPDATES:\n        this_inference_arguments = inspect.getfullargspec(\n            FAC_TO_VAR_UPDATES[factor_type]\n        ).args\n        this_inference_arguments.remove(\"vtof_msgs\")\n        this_inference_arguments.remove(\"log_potentials\")\n        this_inference_arguments.remove(\"temperature\")\n        this_inference_arguments = {\n            key: getattr(wiring[factor_type], key) for key in this_inference_arguments\n        }\n        inference_arguments[factor_type] = this_inference_arguments\n\n    factor_type_to_msgs_range = bp_state.fg_state.factor_type_to_msgs_range\n    factor_type_to_potentials_range = bp_state.fg_state.factor_type_to_potentials_range\n\n    def update(\n        bp_arrays: Optional[BPArrays] = None,\n        log_potentials_updates: Optional[Dict[Any, jnp.ndarray]] = None,\n        ftov_msgs_updates: Optional[Dict[Any, jnp.ndarray]] = None,\n        evidence_updates: Optional[Dict[Any, jnp.ndarray]] = None,\n    ) -> BPArrays:\n        \"\"\"Function to update belief propagation log_potentials, ftov_msgs, evidence.\n\n        Args:\n            bp_arrays: Optional arrays of log_potentials, ftov_msgs, evidence.\n            log_potentials_updates: Optional dictionary containing log_potentials updates.\n            ftov_msgs_updates: Optional dictionary containing ftov_msgs updates.\n            evidence_updates: Optional dictionary containing evidence updates.\n\n        Returns:\n            A BPArrays with the updated log_potentials, ftov_msgs and evidence.\n        \"\"\"\n        if bp_arrays is not None:\n            log_potentials = bp_arrays.log_potentials\n            evidence = bp_arrays.evidence\n            ftov_msgs = bp_arrays.ftov_msgs\n        else:\n            log_potentials = jax.device_put(bp_state.log_potentials.value)\n            ftov_msgs = bp_state.ftov_msgs.value\n            evidence = bp_state.evidence.value\n\n        if log_potentials_updates is not None:\n            log_potentials = bpstate.update_log_potentials(\n                log_potentials, log_potentials_updates, bp_state.fg_state\n            )\n\n        if ftov_msgs_updates is not None:\n            ftov_msgs = bpstate.update_ftov_msgs(\n                ftov_msgs, ftov_msgs_updates, bp_state.fg_state\n            )\n\n        if evidence_updates is not None:\n            evidence = bpstate.update_evidence(\n                evidence, evidence_updates, bp_state.fg_state\n            )\n\n        return BPArrays(\n            log_potentials=log_potentials, ftov_msgs=ftov_msgs, evidence=evidence\n        )\n\n    def run_bp(\n        bp_arrays: BPArrays,\n        num_iters: int,\n        damping: float = 0.5,\n    ) -> BPArrays:\n        \"\"\"Function to run belief propagation for num_iters with a damping_factor.\n\n        Args:\n            bp_arrays: Initial arrays of log_potentials, ftov_msgs, evidence.\n            num_iters: Number of belief propagation iterations.\n            damping: The damping factor to use for message updates between one timestep and the next.\n\n        Returns:\n            A BPArrays containing the updated ftov_msgs.\n        \"\"\"\n        log_potentials = bp_arrays.log_potentials\n        evidence = bp_arrays.evidence\n        ftov_msgs = bp_arrays.ftov_msgs\n\n        # Normalize the messages to ensure the maximum value is 0.\n        ftov_msgs = normalize_and_clip_msgs(ftov_msgs, edges_num_states, max_msg_size)\n\n        @jax.checkpoint\n        def update(msgs: jnp.ndarray, _) -> Tuple[jnp.ndarray, None]:\n            # Compute new variable to factor messages by message passing\n            vtof_msgs = pass_var_to_fac_messages(\n                msgs,\n                evidence,\n                var_states_for_edges,\n            )\n            ftov_msgs = jnp.zeros_like(vtof_msgs)\n            for factor_type in FAC_TO_VAR_UPDATES:\n                msgs_start, msgs_end = factor_type_to_msgs_range[factor_type]\n                potentials_start, potentials_end = factor_type_to_potentials_range[\n                    factor_type\n                ]\n                ftov_msgs_type = FAC_TO_VAR_UPDATES[factor_type](\n                    vtof_msgs=vtof_msgs[msgs_start:msgs_end],\n                    log_potentials=log_potentials[potentials_start:potentials_end],\n                    temperature=temperature,\n                    **inference_arguments[factor_type],\n                )\n                ftov_msgs = ftov_msgs.at[msgs_start:msgs_end].set(ftov_msgs_type)\n\n            # Use the results of message passing to perform damping and\n            # update the factor to variable messages\n            delta_msgs = ftov_msgs - msgs\n            msgs = msgs + (1 - damping) * delta_msgs\n            # Normalize and clip these damped, updated messages before returning them.\n            msgs = normalize_and_clip_msgs(msgs, edges_num_states, max_msg_size)\n            return msgs, None\n\n        ftov_msgs, _ = jax.lax.scan(update, ftov_msgs, None, num_iters)\n\n        return BPArrays(\n            log_potentials=log_potentials, ftov_msgs=ftov_msgs, evidence=evidence\n        )\n\n    def to_bp_state(bp_arrays: BPArrays) -> BPState:\n        \"\"\"Function to reconstruct the BPState from a BPArrays\n\n        Args:\n            bp_arrays: A BPArrays containing log_potentials, ftov_msgs, evidence.\n\n        Returns:\n            The reconstructed BPState\n        \"\"\"\n        return BPState(\n            log_potentials=LogPotentials(\n                fg_state=bp_state.fg_state, value=bp_arrays.log_potentials\n            ),\n            ftov_msgs=FToVMessages(\n                fg_state=bp_state.fg_state,\n                value=bp_arrays.ftov_msgs,\n            ),\n            evidence=Evidence(fg_state=bp_state.fg_state, value=bp_arrays.evidence),\n        )\n\n    def unflatten_beliefs(flat_beliefs, variable_groups) -> Dict[Hashable, Any]:\n        \"\"\"Function that returns unflattened beliefs from the flat beliefs\n\n        Args:\n            flat_beliefs: Flattened array of beliefs\n            variable_groups: All the variable groups in the FactorGraph.\n        \"\"\"\n        beliefs = {}\n        start = 0\n        for variable_group in variable_groups:\n            num_states = variable_group.num_states\n            assert isinstance(num_states, np.ndarray)\n            length = num_states.sum()\n\n            beliefs[variable_group] = variable_group.unflatten(\n                flat_beliefs[start : start + length]\n            )\n            start += length\n        return beliefs\n\n    @jax.jit\n    def get_beliefs(bp_arrays: BPArrays) -> Dict[Hashable, Any]:\n        \"\"\"Function to calculate beliefs from a BPArrays\n\n        Args:\n            bp_arrays: A BPArrays containing log_potentials, ftov_msgs, evidence.\n\n        Returns:\n            beliefs: Beliefs returned by belief propagation.\n        \"\"\"\n\n        flat_beliefs = (\n            jax.device_put(bp_arrays.evidence)\n            .at[jax.device_put(var_states_for_edges)]\n            .add(bp_arrays.ftov_msgs)\n        )\n        return unflatten_beliefs(flat_beliefs, bp_state.fg_state.variable_groups)\n\n    bp = BeliefPropagation(\n        init=functools.partial(update, None),\n        update=update,\n        run_bp=run_bp,\n        to_bp_state=to_bp_state,\n        get_beliefs=get_beliefs,\n    )\n    return bp\n\n\n@jax.jit\ndef pass_var_to_fac_messages(\n    ftov_msgs: jnp.array,\n    evidence: jnp.array,\n    var_states_for_edges: jnp.array,\n) -> jnp.array:\n    \"\"\"Passes messages from Variables to Factors.\n\n    The update works by first summing the evidence and neighboring factor to variable messages for\n    each variable. Next, it subtracts messages from the correct elements of this sum to yield the\n    correct updated messages.\n\n    Args:\n        ftov_msgs: Array of shape (num_edge_state,). This holds all the flattened factor to variable\n            messages.\n        evidence: Array of shape (num_var_states,) representing the flattened evidence for each variable\n        var_states_for_edges: Array of shape (num_edge_states,)\n            Global variable state indices for each edge state\n    Returns:\n        Array of shape (num_edge_state,). This holds all the flattened variable to factor messages.\n    \"\"\"\n    var_sums_arr = evidence.at[var_states_for_edges].add(ftov_msgs)\n    vtof_msgs = var_sums_arr[var_states_for_edges] - ftov_msgs\n    return vtof_msgs\n\n\n@functools.partial(jax.jit, static_argnames=(\"max_msg_size\"))\ndef normalize_and_clip_msgs(\n    msgs: jnp.ndarray,\n    edges_num_states: jnp.ndarray,\n    max_msg_size: int,\n) -> jnp.ndarray:\n    \"\"\"Performs normalization and clipping of flattened messages\n\n    Normalization is done by subtracting the maximum value of every message from every element of every message,\n    clipping is done to keep every message value in the range [-1000, 0].\n\n    Args:\n        msgs: Array of shape (num_edge_state,). This holds all the flattened factor to variable messages.\n        edges_num_states: Array of shape (num_edges,). Number of states for the variables connected to each edge\n        max_msg_size: the max of edges_num_states\n\n    Returns:\n        Array of shape (num_edge_state,). This holds all the flattened factor to variable messages\n            after normalization and clipping\n    \"\"\"\n    msgs = msgs - jnp.repeat(\n        bp_utils.segment_max_opt(msgs, edges_num_states, max_msg_size),\n        edges_num_states,\n        total_repeat_length=msgs.shape[0],\n    )\n    # Clip message values to be always greater than -1000\n    msgs = jnp.clip(msgs, -1000, None)\n    return msgs\n\n\n@jax.jit\ndef decode_map_states(beliefs: Dict[Hashable, Any]) -> Any:\n    \"\"\"Function to decode MAP states given the calculated beliefs.\n\n    Args:\n        beliefs: An array or a PyTree container containing beliefs for different variables.\n\n    Returns:\n        An array or a PyTree container containing the MAP states for different variables.\n    \"\"\"\n    return jax.tree_util.tree_map(lambda x: jnp.argmax(x, axis=-1), beliefs)\n\n\n@jax.jit\ndef get_marginals(beliefs: Dict[Hashable, Any]) -> Any:\n    \"\"\"Function to get marginal probabilities given the calculated beliefs.\n\n    Args:\n        beliefs: An array or a PyTree container containing beliefs for different variables.\n\n    Returns:\n        An array or a PyTree container containing the marginal probabilities different variables.\n    \"\"\"\n    return jax.tree_util.tree_map(\n        lambda x: jnp.exp(x - logsumexp(x, axis=-1, keepdims=True)), beliefs\n    )\n", "meta": {"hexsha": "67aceb3ac01316416999efe445cd1dae380b8a10", "size": 13879, "ext": "py", "lang": "Python", "max_stars_repo_path": "pgmax/infer/bp.py", "max_stars_repo_name": "NishanthJKumar/PGMax", "max_stars_repo_head_hexsha": "7c71b1456cd84e40b4974649adbf6eecaf0276a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45, "max_stars_repo_stars_event_min_datetime": "2021-11-18T15:54:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:28:06.000Z", "max_issues_repo_path": "pgmax/infer/bp.py", "max_issues_repo_name": "NishanthJKumar/PGMax", "max_issues_repo_head_hexsha": "7c71b1456cd84e40b4974649adbf6eecaf0276a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 54, "max_issues_repo_issues_event_min_datetime": "2021-11-07T03:49:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:19:22.000Z", "max_forks_repo_path": "pgmax/infer/bp.py", "max_forks_repo_name": "NishanthJKumar/PGMax", "max_forks_repo_head_hexsha": "7c71b1456cd84e40b4974649adbf6eecaf0276a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2021-11-03T18:25:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T02:55:12.000Z", "avg_line_length": 38.4459833795, "max_line_length": 112, "alphanum_fraction": 0.6685640176, "include": true, "reason": "import numpy,import jax,from jax", "num_tokens": 2963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3812195803163618, "lm_q1q2_score": 0.19209889884792114}}
{"text": "# coding: utf-8\n# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\n\"\"\"\nThis module provides core classes needed by all define electronic structure,\nsuch as the Spin, Orbital, etc.\n\"\"\"\n\nfrom monty.json import MSONable\nfrom enum import Enum, unique\nimport numpy as np\n\n__author__ = \"Shyue Ping Ong\"\n__copyright__ = \"Copyright 2011, The Materials Project\"\n__version__ = \"1.0\"\n__maintainer__ = \"Shyue Ping Ong\"\n__email__ = \"shyuep@gmail.com\"\n__status__ = \"Production\"\n__date__ = \"Sep 23, 2011\"\n\n\n@unique\nclass Spin(Enum):\n    \"\"\"\n    Enum type for Spin.  Only up and down.\n    Usage: Spin.up, Spin.down.\n    \"\"\"\n    up, down = (1, -1)\n\n    def __int__(self):\n        return self.value\n\n    def __float__(self):\n        return float(self.value)\n\n    def __str__(self):\n        return str(self.value)\n\n\n@unique\nclass OrbitalType(Enum):\n    \"\"\"\n    Enum type for orbital type. Indices are basically the azimuthal quantum\n    number, l.\n    \"\"\"\n\n    s = 0\n    p = 1\n    d = 2\n    f = 3\n\n    def __str__(self):\n        return self.name\n\n\n@unique\nclass Orbital(Enum):\n    \"\"\"\n    Enum type for specific orbitals. The indices are basically the order in\n    which the orbitals are reported in VASP and has no special meaning.\n    \"\"\"\n\n    s = 0\n    py = 1\n    pz = 2\n    px = 3\n    dxy = 4\n    dyz = 5\n    dz2 = 6\n    dxz = 7\n    dx2 = 8\n    f_3 = 9\n    f_2 = 10\n    f_1 = 11\n    f0 = 12\n    f1 = 13\n    f2 = 14\n    f3 = 15\n\n    def __int__(self):\n        return self.value\n\n    def __str__(self):\n        return self.name\n\n    @property\n    def orbital_type(self):\n        \"\"\"\n        Returns OrbitalType of an orbital.\n        \"\"\"\n        return OrbitalType[self.name[0]]\n\n\nclass Magmom(MSONable):\n    \"\"\"\n    New class in active development. Use with caution, feedback is\n    appreciated.\n\n    Class to handle magnetic moments. Defines the magnetic moment of a\n    site or species relative to a spin quantization axis. Designed for\n    use in electronic structure calculations.\n\n    * For the general case, Magmom can be specified by a vector,\n      e.g. m = Magmom([1.0, 1.0, 2.0]), and subscripts will work as\n      expected, e.g. m[0] gives 1.0\n\n    * For collinear calculations, Magmom can assumed to be scalar-like,\n      e.g. m = Magmom(5.0) will work as expected, e.g. float(m) gives 5.0\n\n    Both of these cases should be safe and shouldn't give any surprises,\n    but more advanced functionality is available if required.\n\n    There also exist useful static methods for lists of magmoms:\n\n    * Magmom.are_collinear(magmoms) - if true, a collinear electronic\n      structure calculation can be safely initialized, with float(Magmom)\n      giving the expected scalar magnetic moment value\n\n    * Magmom.get_consistent_set_and_saxis(magmoms) - for non-collinear\n      electronic structure calculations, a global, consistent spin axis\n      has to be used. This method returns a list of Magmoms which all\n      share a common spin axis, along with the global spin axis.\n\n    All methods that take lists of magmoms will accept magmoms either as\n    Magmom objects or as scalars/lists and will automatically convert to\n    a Magmom representation internally.\n\n    The following methods are also particularly useful in the context of\n    VASP calculations:\n\n    * Magmom.get_xyz_magmom_with_001_saxis()\n    * Magmom.get_00t_magmom_with_xyz_saxis()\n\n    See VASP documentation for more information:\n\n    https://cms.mpi.univie.ac.at/wiki/index.php/SAXIS\n    \"\"\"\n\n    def __init__(self, moment, saxis=(0, 0, 1)):\n        \"\"\"\n        :param moment: magnetic moment, supplied as float or list/np.ndarray\n        :param saxis: spin axis, supplied as list/np.ndarray, parameter will\n            be converted to unit vector (default is [0, 0, 1])\n        :return: Magmom object\n        \"\"\"\n        # to init from another Magmom instance\n        if isinstance(moment, Magmom):\n            saxis = moment.saxis\n            moment = moment.moment\n\n        moment = np.array(moment, dtype='d')\n        if moment.ndim == 0:\n            moment = moment * [0, 0, 1]\n\n        self.moment = moment\n\n        saxis = np.array(saxis, dtype='d')\n\n        self.saxis = saxis / np.linalg.norm(saxis)\n\n    @classmethod\n    def from_global_moment_and_saxis(cls, global_moment, saxis):\n        \"\"\"\n        Convenience method to initialize Magmom from a given global\n        magnetic moment, i.e. magnetic moment with saxis=(0,0,1), and\n        provided saxis.\n\n        Method is useful if you do not know the components of your\n        magnetic moment in frame of your desired saxis.\n\n        :param global_moment:\n        :param saxis: desired saxis\n        :return:\n        \"\"\"\n        magmom = Magmom(global_moment)\n        return cls(magmom.get_moment(saxis=saxis), saxis=saxis)\n\n    def _get_transformation_matrix(self, saxis):\n\n        saxis = saxis / np.linalg.norm(saxis)\n\n        alpha = np.arctan2(saxis[1], saxis[0])\n        beta = np.arctan2(np.sqrt(saxis[0] ** 2 + saxis[1] ** 2), saxis[2])\n\n        cos_a = np.cos(alpha)\n        cos_b = np.cos(beta)\n        sin_a = np.sin(alpha)\n        sin_b = np.sin(beta)\n\n        m = [[cos_b * cos_a, -sin_a, sin_b * cos_a],\n             [cos_b * sin_a, cos_a, sin_b * sin_a],\n             [-sin_b, 0, cos_b]]\n\n        return m\n\n    def _get_transformation_matrix_inv(self, saxis):\n\n        saxis = saxis / np.linalg.norm(saxis)\n\n        alpha = np.arctan2(saxis[1], saxis[0])\n        beta = np.arctan2(np.sqrt(saxis[0] ** 2 + saxis[1] ** 2), saxis[2])\n\n        cos_a = np.cos(alpha)\n        cos_b = np.cos(beta)\n        sin_a = np.sin(alpha)\n        sin_b = np.sin(beta)\n\n        m = [[cos_b * cos_a, cos_b * sin_a, -sin_b],\n             [-sin_a, cos_a, 0],\n             [sin_b * cos_a, sin_b * sin_a, cos_b]]\n\n        return m\n\n    def get_moment(self, saxis=(0, 0, 1)):\n        \"\"\"\n        Get magnetic moment relative to a given spin quantization axis.\n        If no axis is provided, moment will be given relative to the\n        Magmom's internal spin quantization axis, i.e. equivalent to\n        Magmom.moment\n\n        :param axis: (list/numpy array) spin quantization axis\n        :return: np.ndarray of length 3\n        \"\"\"\n\n        # transform back to moment with spin axis [0, 0, 1]\n        m_inv = self._get_transformation_matrix_inv(self.saxis)\n        moment = np.matmul(self.moment, m_inv)\n\n        # transform to new saxis\n        m = self._get_transformation_matrix(saxis)\n        moment = np.matmul(moment, m)\n\n        # round small values to zero\n        moment[np.abs(moment) < 1e-8] = 0\n\n        return moment\n\n    @property\n    def global_moment(self):\n        \"\"\"\n        Get the magnetic moment defined in an arbitrary global reference frame.\n\n        :return: np.ndarray of length 3\n        \"\"\"\n        return self.get_moment()\n\n    @property\n    def projection(self):\n        \"\"\"\n        Projects moment along spin quantisation axis. Useful for obtaining\n        collinear approximation for slightly non-collinear magmoms.\n\n        :return: float\n        \"\"\"\n        return np.dot(self.moment, self.saxis)\n\n    def get_xyz_magmom_with_001_saxis(self):\n        \"\"\"\n        Returns a Magmom in the default setting of saxis = [0, 0, 1] and\n        the magnetic moment rotated as required.\n\n        :return: Magmom\n        \"\"\"\n        return Magmom(self.get_moment())\n\n    def get_00t_magmom_with_xyz_saxis(self):\n        \"\"\"\n        For internal implementation reasons, in non-collinear calculations\n        VASP prefers:\n\n        MAGMOM = 0 0 total_magnetic_moment\n        SAXIS = x y z\n\n        to an equivalent:\n\n        MAGMOM = x y z\n        SAXIS = 0 0 1\n\n        This method returns a Magmom object with magnetic moment [0, 0, t],\n        where t is the total magnetic moment, and saxis rotated as required.\n\n        A consistent direction of saxis is applied such that t might be positive\n        or negative depending on the direction of the initial moment. This is useful\n        in the case of collinear structures, rather than constraining assuming\n        t is always positive.\n\n        :return: Magmom\n        \"\"\"\n        # reference direction gives sign of moment\n        # entirely arbitrary, there will always be a pathological case\n        # where a consistent sign is not possible if the magnetic moments\n        # are aligned along the reference direction, but in practice this\n        # is unlikely to happen\n        ref_direction = np.array([1.01, 1.02, 1.03])\n        t = abs(self)\n        if t != 0:\n            new_saxis = self.moment / np.linalg.norm(self.moment)\n            if np.dot(ref_direction, new_saxis) < 0:\n                t = -t\n                new_saxis = -new_saxis\n            return Magmom([0, 0, t], saxis=new_saxis)\n        else:\n            return Magmom(self)\n\n    @staticmethod\n    def have_consistent_saxis(magmoms):\n        \"\"\"\n        This method checks that all Magmom objects in a list have a\n        consistent spin quantization axis. To write MAGMOM tags to a\n        VASP INCAR, a global SAXIS value for all magmoms has to be used.\n        If saxis are inconsistent, can create consistent set with:\n        Magmom.get_consistent_set(magmoms)\n\n        :param magmoms: list of magmoms (Magmoms, scalars or vectors)\n        :return: bool\n        \"\"\"\n        magmoms = [Magmom(magmom) for magmom in magmoms]\n        ref_saxis = magmoms[0].saxis\n        match_ref = [magmom.saxis == ref_saxis for magmom in magmoms]\n        if np.all(match_ref):\n            return True\n        else:\n            return False\n\n    @staticmethod\n    def get_consistent_set_and_saxis(magmoms, saxis=None):\n        \"\"\"\n        Method to ensure a list of magmoms use the same spin axis.\n        Returns a tuple of a list of Magmoms and their global spin axis.\n\n        :param magmoms: list of magmoms (Magmoms, scalars or vectors)\n        :param saxis: can provide a specific global spin axis\n        :return: (list of Magmoms, global spin axis) tuple\n        \"\"\"\n        magmoms = [Magmom(magmom) for magmom in magmoms]\n        if saxis is None:\n            saxis = Magmom.get_suggested_saxis(magmoms)\n        else:\n            saxis = saxis / np.linalg.norm(saxis)\n        magmoms = [magmom.get_moment(saxis=saxis) for magmom in magmoms]\n        return (magmoms, saxis)\n\n    @staticmethod\n    def get_suggested_saxis(magmoms):\n        \"\"\"\n        This method returns a suggested spin axis for a set of magmoms,\n        taking the largest magnetic moment as the reference. For calculations\n        with collinear spins, this would give a sensible saxis for a ncl\n        calculation.\n\n        :param magmoms: list of magmoms (Magmoms, scalars or vectors)\n        :return: np.ndarray of length 3\n        \"\"\"\n        # heuristic, will pick largest magmom as reference\n        # useful for creating collinear approximations of\n        # e.g. slightly canted magnetic structures\n        # for fully collinear structures, will return expected\n        # result\n\n        magmoms = [Magmom(magmom) for magmom in magmoms]\n        # filter only non-zero magmoms\n        magmoms = [magmom for magmom in magmoms if abs(magmom)]\n        magmoms.sort(reverse=True)\n        if len(magmoms) > 0:\n            return magmoms[0].get_00t_magmom_with_xyz_saxis().saxis\n        else:\n            return np.array([0, 0, 1], dtype=\"d\")\n\n    @staticmethod\n    def are_collinear(magmoms):\n        \"\"\"\n        Method checks to see if a set of magnetic moments are collinear\n        with each other.\n        :param magmoms: list of magmoms (Magmoms, scalars or vectors)\n        :return: bool\n        \"\"\"\n        magmoms = [Magmom(magmom) for magmom in magmoms]\n        if not Magmom.have_consistent_saxis(magmoms):\n            magmoms = Magmom.get_consistent_set(magmoms)\n\n        # convert to numpy array for convenience\n        magmoms = np.array([list(magmom) for magmom in magmoms])\n        magmoms = magmoms[np.any(magmoms, axis=1)]  # remove zero magmoms\n        if len(magmoms) == 0:\n            return True\n\n        # use first moment as reference to compare against\n        ref_magmom = magmoms[0]\n        # magnitude of cross products != 0 if non-collinear with reference\n        num_ncl = np.count_nonzero(np.linalg.norm(np.cross(ref_magmom, magmoms), axis=1))\n        if num_ncl > 0:\n            return False\n        else:\n            return True\n\n    @classmethod\n    def from_moment_relative_to_crystal_axes(cls, moment, lattice):\n        \"\"\"\n        Obtaining a Magmom object from a magnetic moment provided\n        relative to crystal axes.\n\n        Used for obtaining moments from magCIF file.\n        :param magmom: list of floats specifying vector magmom\n        :param lattice: Lattice\n        :return: Magmom\n        \"\"\"\n        # get matrix representing unit lattice vectors\n        unit_m = lattice.matrix / np.linalg.norm(lattice.matrix, axis=1)[:, None]\n        moment = np.matmul(list(moment), unit_m)\n        # round small values to zero\n        moment[np.abs(moment) < 1e-8] = 0\n        return cls(moment)\n\n    def get_moment_relative_to_crystal_axes(self, lattice):\n        \"\"\"\n        If scalar magmoms, moments will be given arbitrarily along z.\n        Used for writing moments to magCIF file.\n\n        :param magmom: Magmom\n        :param lattice: Lattice\n        :return: vector as list of floats\n        \"\"\"\n        # get matrix representing unit lattice vectors\n        unit_m = lattice.matrix / np.linalg.norm(lattice.matrix, axis=1)[:, None]\n        # note np.matmul() requires numpy version >= 1.10\n        moment = np.matmul(self.global_moment, np.linalg.inv(unit_m))\n        # round small values to zero\n        moment[np.abs(moment) < 1e-8] = 0\n        return moment\n\n    def __getitem__(self, key):\n        return self.moment[key]\n\n    def __iter__(self):\n        return iter(self.moment)\n\n    def __abs__(self):\n        return np.linalg.norm(self.moment)\n\n    def __eq__(self, other):\n        \"\"\"\n        Equal if 'global' magnetic moments are the same, saxis can differ.\n        \"\"\"\n        other = Magmom(other)\n        return np.allclose(self.global_moment, other.global_moment)\n\n    def __ne__(self, other):\n        return not self.__eq__(other)\n\n    def __lt__(self, other):\n        return abs(self) < abs(other)\n\n    def __neg__(self):\n        return Magmom(-self.moment, saxis=self.saxis)\n\n    def __hash__(self):\n        return (tuple(self.moment) + tuple(self.saxis)).__hash__()\n\n    def __float__(self):\n        \"\"\"\n        Returns magnitude of magnetic moment with a sign with respect to\n        an arbitrary direction.\n\n        Should give unsurprising output if Magmom is treated like a\n        scalar or if a set of Magmoms describes a collinear structure.\n\n        Implemented this way rather than simpler abs(self) so that\n        moments will have a consistent sign in case of e.g.\n        antiferromagnetic collinear structures without additional\n        user intervention.\n\n        However, should be used with caution for non-collinear\n        structures and might give non-sensical results except in the case\n        of only slightly non-collinear structures (e.g. small canting).\n\n        This approach is also used to obtain \"diff\" VolumetricDensity\n        in pymatgen.io.vasp.outputs.VolumetricDensity when processing\n        Chgcars from SOC calculations.\n        \"\"\"\n        return float(self.get_00t_magmom_with_xyz_saxis()[2])\n\n    def __str__(self):\n        return str(float(self))\n\n    def __repr__(self):\n        if np.allclose(self.saxis, (0, 0, 1)):\n            return 'Magnetic moment {0}'.format(self.moment)\n        else:\n            return 'Magnetic moment {0} (spin axis = {1})'.format(self.moment,\n                                                                  self.saxis)\n", "meta": {"hexsha": "43fd11e90aedf70d0585348a5525036ada39e121", "size": 15748, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymatgen/electronic_structure/core.py", "max_stars_repo_name": "cajfisher/pymatgen", "max_stars_repo_head_hexsha": "286c304e38102d567723a71f733e0c304b72035d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-02-06T08:27:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-28T14:42:52.000Z", "max_issues_repo_path": "pymatgen/electronic_structure/core.py", "max_issues_repo_name": "cajfisher/pymatgen", "max_issues_repo_head_hexsha": "286c304e38102d567723a71f733e0c304b72035d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pymatgen/electronic_structure/core.py", "max_forks_repo_name": "cajfisher/pymatgen", "max_forks_repo_head_hexsha": "286c304e38102d567723a71f733e0c304b72035d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-10-17T19:08:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T20:26:58.000Z", "avg_line_length": 32.0081300813, "max_line_length": 89, "alphanum_fraction": 0.625984252, "include": true, "reason": "import numpy", "num_tokens": 4038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3812195803163617, "lm_q1q2_score": 0.1920988988479211}}
{"text": "\"\"\"\nNAME:\n\tplotting_functions.py\n\nAUTHOR:\n\tBronwyn Reichardt Chu\n\tSwinburne\n\t2021\n\nEMAIL:\n\t<breichardtchu@swin.edu.au>\n\nPURPOSE:\n\tTo hold useful plotting functions\n\tWritten on MacOS Mojave 10.14.5, with Python 3.7\n\nFUNCTIONS INLCUDED:\n    get_rc_params\n    chen_et_al_2010\n    murray_et_al_2011\n    davies_et_al_2019\n    kim_et_al_2020\n    fitting_function\n    running_mean\n    lower_quantile\n    upper_quantile\n    binned_median_quantile_log\n    binned_median_quantile_lin\n    pearson_correlation\n    read_in_create_wcs\n    plot_continuum_contours\n\nMODIFICATION HISTORY:\n\t\tv.1.0 - first created January 2021\n\n\"\"\"\nimport numpy as np\nimport scipy.stats as stats\n\nfrom astropy.io import fits\nfrom astropy.wcs import WCS\n\n\n#===============================================================================\n# DEFINE PLOTTING PARAMETERS\n#===============================================================================\n\n\ndef get_rc_params():\n    \"\"\"\n    Define the rcParams that will be used in all the plots.\n\n    Returns\n    -------\n    rc_params dictionary object\n    \"\"\"\n\n    rc_params = {\n        \"text.usetex\": False,\n        \"axes.facecolor\": 'white',\n\n        #\"figure.dpi\": 125,\n        #\"legend.fontsize\": 12,\n        \"legend.frameon\": False,\n        #\"legend.markerscale\": 1.0,\n\n        \"axes.labelsize\": 'large',\n\n        \"xtick.direction\": 'in',\n        \"xtick.labelsize\": 'medium',\n        \"xtick.minor.visible\": True,\n        \"xtick.top\": True,\n        \"xtick.major.width\": 1,\n\n        \"ytick.direction\": 'in',\n        \"ytick.labelsize\": 'medium',\n        \"ytick.minor.visible\": True,\n        \"ytick.right\": True,\n        \"ytick.major.width\": 1,\n    }\n\n    return rc_params\n\n\n#===============================================================================\n# RELATIONS FROM OTHER PAPERS\n#===============================================================================\n\n\ndef chen_et_al_2010(sfr_surface_density_min, sfr_surface_density_max, scale_factor=1):\n    \"\"\"\n    The trendline from Chen et al. (2010) where v_out is proportional to (SFR surface density)^0.1\n    (Energy driven winds - SNe feedback)\n\n    Parameters\n    ----------\n    sfr_surface_density_min : float\n        The minimum value of the SFR surface density\n\n    sfr_surface_density_max : float\n        The maximum value of the SFR surface density\n\n    scale_factor : float\n        The number by which to scale the trend, can be used to bring the trend\n        into the range of the data on the plot (Default = 1)\n\n    Returns\n    -------\n    sfr_surface_density : :obj:'~numpy.ndarray'\n        vector of SFR surface densities\n\n    v_out : :obj:'~numpy.ndarray'\n        vector of outflow velocities following the trend\n    \"\"\"\n    #create a vector for sfr surface density\n    sfr_surface_density = np.linspace(sfr_surface_density_min, sfr_surface_density_max+4, num=1000)\n\n    #use the relationship to predict the v_out\n    v_out = scale_factor*sfr_surface_density**0.1\n\n    return sfr_surface_density, v_out\n\n\ndef murray_et_al_2011(sfr_surface_density_min, sfr_surface_density_max, scale_factor=1):\n    \"\"\"\n    The trendline from Murray et al. (2011) where v_out is proportional to (SFR surface density)^2\n    (Momentum driven winds - radiative feedback from young stars)\n\n    Parameters\n    ----------\n    sfr_surface_density_min : float\n        The minimum value of the SFR surface density\n\n    sfr_surface_density_max : float\n        The maximum value of the SFR surface density\n\n    scale_factor : float\n        The number by which to scale the trend, can be used to bring the trend\n        into the range of the data on the plot (Default = 1)\n\n    Returns\n    -------\n    sfr_surface_density : :obj:'~numpy.ndarray'\n        vector of SFR surface densities\n\n    v_out : :obj:'~numpy.ndarray'\n        vector of outflow velocities following the trend\n    \"\"\"\n    #create a vector for sfr surface density\n    sfr_surface_density = np.linspace(sfr_surface_density_min, sfr_surface_density_max+4, num=1000)\n\n    #use the relationship to predict the v_out\n    v_out = scale_factor*sfr_surface_density**2\n\n    return sfr_surface_density, v_out\n\ndef davies_et_al_2019(sfr_surface_density_min, sfr_surface_density_max):\n    \"\"\"\n    The trendline from Davies et al. (2019) where the flow velocity dispersion\n    is proportional to SFR surface density.\n\n    Parameters\n    ----------\n    sfr_surface_density_min : float\n        The minimum value of the SFR surface density\n\n    sfr_surface_density_max : float\n        The maximum value of the SFR surface density\n\n    Returns\n    -------\n    sfr_surface_density : :obj:'~numpy.ndarray'\n        vector of SFR surface densities\n\n    vel_disp : :obj:'~numpy.ndarray'\n        vector of outflow velocity dispersions following the trend\n    \"\"\"\n    #create a vector for sfr surface density\n    sfr_surface_density = np.linspace(sfr_surface_density_min, sfr_surface_density_max+4, num=1000)\n\n    #use the relationship to predict the v_out\n    vel_disp = 241*sfr_surface_density**0.3\n\n    return sfr_surface_density, vel_disp\n\ndef kim_et_al_2020(sfr_surface_density_min, sfr_surface_density_max, scale_factor=1):\n    \"\"\"\n    The trendline from Kim et al. (2020) where mass the loading factor is proportional\n    to (SFR surface density)^-0.44\n\n    Parameters\n    ----------\n    sfr_surface_density_min : float\n        The minimum value of the SFR surface density\n\n    sfr_surface_density_max : float\n        The maximum value of the SFR surface density\n\n    scale_factor : float\n        The number by which to scale the trend, can be used to bring the trend\n        into the range of the data on the plot (Default = 1)\n\n    Returns\n    -------\n    sfr_surface_density : :obj:'~numpy.ndarray'\n        vector of SFR surface densities\n\n    mlf : :obj:'~numpy.ndarray'\n        vector of mass loading factors following the trend\n    \"\"\"\n    #create a vector for sfr surface density\n    sfr_surface_density = np.linspace(sfr_surface_density_min, sfr_surface_density_max+4, num=1000)\n\n    #use the relationship to predict the v_out\n    mlf = scale_factor*sfr_surface_density**-0.44\n\n    return sfr_surface_density, mlf\n\n\n#===============================================================================\n# USEFUL LITTLE FUNCTIONS\n#===============================================================================\n\ndef fitting_function(x, a, b):\n    \"\"\"\n    My fitting function to be fit to the v_out to sfr surface density data\n\n    Parameters\n    ----------\n    x : (vector)\n        the SFR surface density\n\n    a, b : (int)\n        constants to be fit\n\n    Returns\n    -------\n    y : (vector)\n        the outflow velocity\n    \"\"\"\n    return a*(x**b)\n\ndef running_mean(x, N):\n    \"\"\"\n    Calculates the running mean\n\n    Parameters\n    ----------\n    x : :obj:'~numpy.ndarray'\n        data\n    N : integer\n        bin size\n    \"\"\"\n\n    cumsum = np.cumsum(np.insert(x, 0, 0))\n    return (cumsum[N:] - cumsum[:-N]) / float(N)\n\ndef lower_quantile(x):\n    \"\"\"\n    Calculate the lower quantile of x (data :obj:'~numpy.nd:obj:'~numpy.ndarray'')\n    \"\"\"\n    return np.nanquantile(x, 0.33)\n\ndef upper_quantile(x):\n    \"\"\"\n    Calculate the upper quantile of x (data :obj:'~numpy.ndarray')\n    \"\"\"\n    return np.nanquantile(x, 0.66)\n\n\ndef binned_median_quantile_log(x, y, num_bins, weights=None, min_bin=None, max_bin=None):\n    \"\"\"\n    Calculate the median, upper and lower quantile for an array of data in\n    logarithmically increasing bins\n\n    Parameters\n    ----------\n    x : :obj:'~numpy.ndarray'\n        x-axis logarithmic data\n\n    y : :obj:'~numpy.ndarray'\n        y-axis data\n\n    num_bins : integer\n        the number of bins to divide the data into\n\n    weights : :obj:'~numpy.ndarray'\n        array to multiply x by, usually the error (Default = None)\n\n    min_bin : float\n        starting value of the first bin (Default = None)\n\n    max_bin : float\n        ending value of the last bin (Default = None)\n\n    Returns\n    -------\n    logspace : :obj:'~numpy.ndarray'\n        the logarithmic array of bin edges in x\n\n    bin_center : :obj:'~numpy.ndarray'\n        values indicating the centres of the bins in x\n\n    bin_avg : :obj:'~numpy.ndarray'\n        values of the median of the bins in y\n\n    lower_quantile : :obj:'~numpy.ndarray'\n        values for the lower quantile of each bin in y\n\n    upper_quantile : :obj:'~numpy.ndarray'\n        values for the upper quantile of each bin in y\n\n    bin_stdev : :obj:'~numpy.ndarray'\n        values for the standard deviation of each bin in y\n    \"\"\"\n    if min_bin == None:\n        min_bin = np.nanmin(x)\n\n    if max_bin == None:\n        max_bin = np.nanmax(x)\n\n    #create the logspace - these are the bin edges\n    logspace = np.logspace(np.log10(min_bin), np.log10(max_bin), num=num_bins+1)\n\n    #calculate the average\n    bin_avg = np.zeros(len(logspace)-1)\n    upper_quantile = np.zeros(len(logspace)-1)\n    lower_quantile = np.zeros(len(logspace)-1)\n    bin_stdev = np.zeros(len(logspace)-1)\n\n    for i in range(0, len(logspace)-1):\n        left_bound = logspace[i]\n        right_bound = logspace[i+1]\n        items_in_bin = y[(x>left_bound)&(x<=right_bound)]\n        print('Number of items in bin '+str(i)+': '+str(items_in_bin.shape))\n        #calculate the median of the bin\n        if weights == None:\n            bin_avg[i] = np.nanmedian(items_in_bin)\n        else:\n            weights_in_bin = weights[0][(x>left_bound)&(x<=right_bound)]\n            weights_in_bin = 1.0 - weights_in_bin/items_in_bin\n            bin_avg[i] = np.average(items_in_bin, weights=weights_in_bin)\n\n        #calculate the quartiles of the bin\n        if items_in_bin.shape[0] < 10:\n            upper_quantile[i] = np.nanquantile(items_in_bin, 0.80)\n            lower_quantile[i] = np.nanquantile(items_in_bin, 0.20)\n        else:\n            upper_quantile[i] = np.nanquantile(items_in_bin, 0.66)\n            lower_quantile[i] = np.nanquantile(items_in_bin, 0.33)\n\n        #calculate the standard deviation of the bin\n        bin_stdev[i] = np.nanstd(items_in_bin)\n\n    #calculate the bin center for plotting\n    bin_center = np.zeros(len(logspace)-1)\n    for i in range(0, len(logspace)-1):\n        bin_center[i] = np.nanmean([logspace[i],logspace[i+1]])\n\n    return logspace, bin_center, bin_avg, lower_quantile, upper_quantile, bin_stdev\n\n\ndef binned_median_quantile_lin(x, y, num_bins, weights=None, min_bin=None, max_bin=None):\n    \"\"\"\n    Calculate the median, upper and lower quantile for an array of data in\n    linearly increasing bins\n\n    Parameters\n    ----------\n    x : :obj:'~numpy.ndarray'\n        x-axis linear data\n\n    y : :obj:'~numpy.ndarray'\n        y-axis data\n\n    num_bins : integer\n        the number of bins to divide the data into\n\n    weights : :obj:'~numpy.ndarray'\n        array to multiply x by, usually the error (Default = None)\n\n    min_bin : float\n        starting value of the first bin (Default = None)\n\n    max_bin : float\n        ending value of the last bin (Default = None)\n\n    Returns\n    -------\n    linspace : :obj:'~numpy.ndarray'\n        the array of linear bin edges in x\n\n    bin_center : :obj:'~numpy.ndarray'\n        values indicating the centres of the bins in x\n\n    bin_avg : :obj:'~numpy.ndarray'\n        values of the median of the bins in y\n\n    lower_quantile : :obj:'~numpy.ndarray'\n        values for the lower quantile of each bin in y\n\n    upper_quantile : :obj:'~numpy.ndarray'\n        values for the upper quantile of each bin in y\n\n    bin_stdev : :obj:'~numpy.ndarray'\n        values for the standard deviation of each bin in y\n    \"\"\"\n    if min_bin == None:\n        min_bin = np.nanmin(x)\n    if max_bin == None:\n        max_bin = np.nanmax(x)\n\n    #create the logspace - these are the bin edges\n    linspace = np.linspace(min_bin, max_bin, num=num_bins+1)\n\n    #calculate the average\n    bin_avg = np.zeros(len(linspace)-1)\n    upper_quantile = np.zeros(len(linspace)-1)\n    lower_quantile = np.zeros(len(linspace)-1)\n    bin_stdev = np.zeros(len(linspace)-1)\n\n    for i in range(0, len(linspace)-1):\n        left_bound = linspace[i]\n        right_bound = linspace[i+1]\n        items_in_bin = y[(x>left_bound)&(x<=right_bound)]\n        print('Number of items in bin '+str(i)+': '+str(items_in_bin.shape))\n        if weights == None:\n            bin_avg[i] = np.nanmedian(items_in_bin)\n        else:\n            weights_in_bin = weights[0][(x>left_bound)&(x<=right_bound)]\n            weights_in_bin = 1.0 - weights_in_bin/items_in_bin\n            bin_avg[i] = np.average(items_in_bin, weights=weights_in_bin)\n\n        if items_in_bin.shape[0] < 10:\n            upper_quantile[i] = np.nanquantile(items_in_bin, 0.80)\n            lower_quantile[i] = np.nanquantile(items_in_bin, 0.20)\n        else:\n            upper_quantile[i] = np.nanquantile(items_in_bin, 0.66)\n            lower_quantile[i] = np.nanquantile(items_in_bin, 0.33)\n\n        #calculate the standard deviation of the bin\n        bin_stdev[i] = np.nanstd(items_in_bin)\n\n    #calculate the bin center for plotting\n    bin_center = np.zeros(len(linspace)-1)\n    for i in range(0, len(linspace)-1):\n        bin_center[i] = np.nanmean([linspace[i],linspace[i+1]])\n\n    return linspace, bin_center, bin_avg, lower_quantile, upper_quantile, bin_stdev\n\n\ndef pearson_correlation(x, y):\n    \"\"\"\n    Calculate the Pearson correlation coefficient and p-value\n\n    Parameters\n    ----------\n    x : :obj:'~numpy.ndarray'\n        Input array - x values\n\n    y : :obj:'~numpy.ndarray'\n        Input array - y values\n\n    Returns\n    -------\n    r : float\n        Pearson's correlation coefficient\n\n    p_value : float\n        Two-tailed p-value\n    \"\"\"\n    r, p_value = stats.pearsonr(x, y)\n\n    return r, p_value\n\n\ndef read_in_create_wcs(fits_file, index=0, shift=None):\n    \"\"\"\n    Reads in the fits file and creates the wcs\n\n    Parameters\n    ----------\n    fits_file : string\n        the filepath for the fits file to read in\n\n    index : int\n        the index of the extension to be loaded (default is 0)\n\n    shift : list or None\n        how to alter the header if the wcs is going to be wrong.\n        e.g. ['CRPIX2', 32.0] will change the header value of CRPIX2 to 32.0\n\n    Returns\n    -------\n    fits_data : :obj:'~numpy.ndarray'\n        the fits data as a numpy array\n\n    fits_wcs : astropy WCS object\n        the world coordinate system for the fits file\n    \"\"\"\n    #read the data in from fits\n    with fits.open(fits_file) as hdu:\n        hdu.info()\n        fits_data = hdu[index].data\n        fits_header = hdu[index].header\n    hdu.close()\n\n    #shift the header\n    if shift:\n        fits_header[shift[0]] = shift[1]\n\n    #create the WCS\n    fits_wcs = WCS(fits_header)\n\n    return fits_data, fits_header, fits_wcs\n\n\ndef plot_continuum_contours(lamdas, xx, yy, data, z, ax):\n    \"\"\"\n    Plots the continuum contours, using the rest wavelengths between 4600 and 4800 to define the continuum.\n\n    Parameters\n    ----------\n    lamdas : :obj:'~numpy.ndarray'\n        wavelength vector (1D)\n\n    xx : :obj:'~numpy.ndarray'\n        x coordinate array (2D)\n\n    yy : :obj:'~numpy.ndarray'\n        y coordinate array (2D)\n\n    data : :obj:'~numpy.ndarray'\n        data array (3D)\n\n    z : float\n        redshift of the galaxy\n\n    ax : matplotlib axis instance\n        axis for matplotlib to draw on\n\n    Returns\n    -------\n    cont_contours : matplotlib.contour.QuadContourSet instance\n\n    \"\"\"\n    #create a mask for the continuum\n    cont_mask = (lamdas>4600*(1+z))&(lamdas<4800*(1+z))\n\n    #find the median of the continuum\n    cont_median = np.median(data[cont_mask,:,:], axis=0)\n\n    #create the contours\n    cont_contours = ax.contour(xx, yy, cont_median, colors='black', linewidths=0.7, alpha=0.7, levels=(0.2,0.3,0.4,0.7,1.0,2.0,4.0))\n\n    return cont_contours\n", "meta": {"hexsha": "9b3b5fcaf89e9020a1ea408f8556f481a8a2cd49", "size": 15748, "ext": "py", "lang": "Python", "max_stars_repo_path": "plotting_functions.py", "max_stars_repo_name": "bronreichardtchu/koffee", "max_stars_repo_head_hexsha": "7fc9ee53b940aecf716c23ec8003aa138d60aabc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "plotting_functions.py", "max_issues_repo_name": "bronreichardtchu/koffee", "max_issues_repo_head_hexsha": "7fc9ee53b940aecf716c23ec8003aa138d60aabc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plotting_functions.py", "max_forks_repo_name": "bronreichardtchu/koffee", "max_forks_repo_head_hexsha": "7fc9ee53b940aecf716c23ec8003aa138d60aabc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-21T22:55:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-21T22:55:28.000Z", "avg_line_length": 28.2728904847, "max_line_length": 132, "alphanum_fraction": 0.6268732537, "include": true, "reason": "import numpy,import scipy,from astropy", "num_tokens": 4015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.38121956625615, "lm_q1q2_score": 0.19209889176289366}}
{"text": "import os\nfrom pyscf import lib,pbc\nfrom pyscf.lib import param\nfrom pyscf.pbc.lib.kpts_helper import gamma_point\nimport numpy as np\nimport ctypes\nimport math\nfrom multiprocessing import Pool\nimport time,gc\nfrom pydmfet import tools\n\nlib_wannier90 = np.ctypeslib.load_library('libwannier90',  os.path.dirname(__file__))\nlibmisc = np.ctypeslib.load_library('libmisc', os.path.dirname(__file__))\nnum_nnmax = 12\n\nsqrt = math.sqrt\n\n\ndef assign_wf2atm(wf,filename=None,num_wf=None,natom=None):\n\n    if filename is None: filename = wf.seedname+'_centres.xyz'\n    if num_wf is None: num_wf = wf.num_wann\n    if natom is None: natom = wf.num_atoms\n\n    wf_c = np.zeros((num_wf,3))\n    atm_cart = np.zeros((natom,3))\n    with open( filename, 'r' ) as f:\n        tmp = next(f)\n        tmp = next(f)\n        for i in range(num_wf):\n            a,x,y,z = [tmp for tmp in next(f).split()]\n            wf_c[i,0] = float(x)\n            wf_c[i,1] = float(y)\n            wf_c[i,2] = float(z)\n        for i in range(natom):\n            a,x,y,z = [tmp for tmp in next(f).split()]\n            atm_cart[i,0] = float(x)\n            atm_cart[i,1] = float(y)\n            atm_cart[i,2] = float(z)\n\n    dist_table = np.zeros((natom,num_wf))\n    for i in range(natom):\n        for j in range(num_wf):\n            dist_table[i,j] = np.linalg.norm(atm_cart[i] - wf_c[j])\n\n    #print dist_table\n    aoslice = wf.cell.aoslice_by_atom()\n    assign_table = []\n    assign_list = []\n    for i in range(natom):\n        seq = dist_table[i].argsort()\n        nao = aoslice[i,3] - aoslice[i,2]\n        assign_table.append(seq[:nao])\n        for j in range(nao):\n            assign_list.append(seq[j])\n\n    print (assign_table)\n    print (assign_list)\n\n    for i in range(num_wf):\n        exist = False\n        for j in range(num_wf):\n            if(assign_list[j] == i):\n                exist = True\n\n        assert(exist == True)\n\n    return assign_list\n\n\ndef read_umat(wannier,filename):\n\n    nk = 0\n    nw = 0\n    nw1 = 0\n    kpts = None\n    umat = None\n    with open( filename, 'r' ) as f:\n        tmp = next(f)\n        nk,nw,nw1 = [int(x) for x in next(f).split()]\n        tmp = next(f)\n        kpts = np.zeros((nk,3))\n        umat = np.zeros((nk,nw,nw), dtype = np.complex128)\n        for k in range(nk):\n            kpts[k] = [float(x) for x in next(f).split()]\n            for j in range(nw):\n                for i in range(nw):\n                    u_r, u_i = [float(x) for x in next(f).split()]\n                    umat[k,i,j] = u_r + 1j*u_i\n            if(k<nk-1):\n                tmp = next(f)\n\n    return umat\n\ndef write_eig(wannier, filename, nband=None):\n\n    if nband is None: nband = wannier.nband\n    mf = wannier.mf\n    cell = wannier.cell\n    ene = mf.mo_energy\n\n    nk = 1\n    cof_hartree2ev = param.HARTREE2EV\n    with open( filename, 'w' ) as fout:\n        for k in range(nk):\n            for i in range(nband):\n                fout.write('%d  %d  %16.10f\\n' % (i+1, k+1, ene[i]*cof_hartree2ev) )\n\n\ndef write_bloch_u_r(wannier, bands = None, nband=None, kpts = np.zeros((1,3))):\n\n    if bands is None: bands = wannier.bands\n    if nband is None: nband = wannier.nband\n    cell = wannier.cell\n    gs = cell.gs\n    ngx, ngy, ngz = 2*np.asarray(gs)+1\n\n    coords_zyx = cell.gen_uniform_grids(gs)\n    ngs = len(coords_zyx)\n\n    assert(ngs == ngx*ngy*ngz)\n\n    coords = np.zeros((ngs,3))\n    index = 0\n    for ix in range(ngx):\n        for iy in range(ngy):\n            for iz in range(ngz):\n                coords[ix+iy*ngx+iz*ngx*ngy] = coords_zyx[index]\n                index += 1\n\n\n    mf = wannier.mf\n    mo_coeff = mf.mo_coeff\n    nk = len(kpts)\n    #nao = cell.nao_nr()\n    #mo_coeff = mf.mo_coeff.reshape((nk,nao,nao))\n\n    mydf = mf.with_df\n    ni = mydf._numint\n    aoR = ni.eval_ao(cell, coords, kpts, non0tab=None)\n\n    phase_k = np.zeros((nk,ngs), dtype = np.complex128)\n    for i in range(nk):\n        for j in range(ngs):\n            kr = np.dot(kpts[i], coords[j])\n            phase_k[i,j] = np.exp(-1j*kr)\n\n    u_r = np.zeros((nk,nband,ngs), dtype = np.complex128)\n    for k, aoR_k in enumerate(aoR):\n        u_r[k] = lib.dot(mo_coeff[:,bands].T,aoR_k.T*phase_k[k])\n\n    #bohr2ang = math.pow(param.BOHR, -1.5)\n    #u_r *= bohr2ang\n\n    for k in range(nk):\n        filename = 'UNK'+'{:05}'.format(k+1)+'.1'\n        with open( filename, 'w' ) as fout:\n            fout.write('%d %d %d %d %d\\n' % (ngx,ngy,ngz,k+1,nband) )\n            for i in range(nband):\n                for j in range(ngs):\n                    fout.write('%16.10f   %16.10f\\n' % (u_r[k,i,j].real, u_r[k,i,j].imag) )\n\ndef calc_iso_cutoff(wannier, umat=None, bands = None, nband=None, kpts=np.zeros((1,3))):\n\n    if bands is None: bands = wannier.bands\n    if nband is None: nband = wannier.nband\n    if umat  is None: umat = wannier.u_mat\n    cell = wannier.cell\n    gs = cell.gs\n    ngx, ngy, ngz = 2*np.asarray(gs)+1\n\n    coords_zyx = cell.gen_uniform_grids(gs)\n    ngs = len(coords_zyx)\n\n    assert(ngs == ngx*ngy*ngz)\n\n    coords = coords_zyx\n\n    mf = wannier.mf\n    mo_coeff = mf.mo_coeff\n    nk = len(kpts)\n    #nao = cell.nao_nr()\n    #mo_coeff = mf.mo_coeff.reshape((nk,nao,nao))\n\n    mydf = mf.with_df\n    ni = mydf._numint\n\n    aoR = ni.eval_ao(cell, coords, kpts, non0tab=None)\n\n    u_r = np.zeros((nband,ngs), dtype = np.complex128)\n    wf_coeff = np.dot(mf.mo_coeff,umat[0].real)\n    #gamma point k = 0\n    for k, aoR_k in enumerate(aoR):\n        u_r = lib.dot(wf_coeff[:,bands].T,aoR_k.T)\n\n    weight = cell.vol / ngs\n\n    thresh = 0.8\n    c =  np.zeros((nband))\n    for i in range(nband):\n            u2_r = u_r[i] * u_r[i].conj()\n            u2_r = u2_r.real\n            nelec = weight * u2_r.sum()\n            if abs(nelec - 1.0)>0.0001:\n                print ('k=',k,'  iband=',i, '  nelec=',nelec)\n\n            u2_r *= -1.0\n            u2_r.sort()\n            u2_r *= -1.0\n            rho = 0.0\n            index  = -1\n            for j in range(ngs):\n                rho += weight * u2_r[j]\n                if(rho > thresh):\n                    index = j\n                    break\n\n            c[i] = sqrt(0.5*(u2_r[j] + u2_r[j-1]))\n            print (c[i])\n\n\n    \ndef get_nnkpts(nntot, nnlist, nncell):\n\n    nk = nnlist.shape[0]\n    nnkpts = np.zeros((nk,nntot,5), dtype=np.int32)   \n\n    for k in range(nk):\n        for i in range(nntot):\n            nnkpts[k,i,0] = k+1\n            nnkpts[k,i,1] = nnlist[k,i]\n            nnkpts[k,i,2:5] = nncell[0:3,k,i] \n\n    return nnkpts\n\ndef get_bpts(wannier, nnkpts=None,  kpts = np.zeros((1,3)) ):\n\n    if nnkpts is None: nnkpts = wannier.nnkpts\n    nk = len(kpts)\n    nb = nnkpts.shape[1]\n\n    cell = wannier.cell\n    b = cell.reciprocal_vectors()\n\n    bpts = np.zeros((nk,nb,3))\n    for k in range(nk):\n        for i in range(nb):\n            kk = nnkpts[k,i,0]-1\n            k2 = nnkpts[k,i,1]-1\n            kb = kpts[k2] + np.dot(nnkpts[k,i,2:5], b) \n            bpts[k,i,:] = kb - kpts[kk]\n\n    return bpts\n\n\ndef write_Amn(wannier, filename, nk, nband = None, Amn = None):\n\n    if Amn is None: Amn = wannier.Amn\n    if nband is None: nband = wannier.nband\n\n    with open( filename, 'w' ) as fout:\n        fout.write('Amn file\\n')\n        fout.write('%d   %d   %d\\n' % (nband, nk, nband))\n\n        for k in range(nk):\n            for n in range(nband):\n                for m in range(nband):\n                    fout.write('%d  %d  %d  %16.10f   %16.10f\\n' % (m+1, n+1, k+1, Amn[k,m,n].real, Amn[k,m,n].imag) )\n\n\n\ndef write_Mmn(wannier, filename, nk, nband = None, Mmn = None, nnkpts=None):\n\n    if Mmn is None: Mmn = wannier.Mmn\n    if nnkpts is None: nnkpts = wannier.nnkpts\n    if nband is None: nband = wannier.nband\n\n    nntot = nnkpts.shape[1]\n\n    with open( filename, 'w' ) as fout:\n\n        fout.write('Mmn file\\n')\n        fout.write('%d   %d   %d\\n' % (nband, nk, nntot))\n\n        for k in range(nk):\n          for i in range(nntot):\n            fout.write('%d %d %d %d %d\\n' % tuple(nnkpts[k,i]) )\n            for n in range(nband):\n                for m in range(nband):\n                    fout.write('%16.10f   %16.10f\\n' % (Mmn[k,i,m,n].real, Mmn[k,i,m,n].imag) ) \n\n\ndef comput_Mmn(wannier, bands = None, nband = None, bpts=None, kpts = np.zeros((1,3)) ):\n\n    #only works for Gamma point\n\n    if bands is None: bands = wannier.bands\n    if nband is None: nband = wannier.nband\n    if bpts is None: bpts = wannier.bpts\n    mf = wannier.mf\n    mo_coeff = mf.mo_coeff\n\n    cell = wannier.cell\n    mydf = mf.with_df\n    gs = mydf.gs\n\n    coords = cell.gen_uniform_grids(gs)\n    ngs = len(coords)\n\n    ni = mydf._numint\n\n    weight = cell.vol / ngs\n\n    aoR = ni.eval_ao(cell, coords, kpts, non0tab=None)\n\n    \n    nk = len(kpts) \n    nntot = bpts.shape[1]\n    phase_b = np.zeros((nk,nntot,ngs), dtype = np.complex128)\n    for k in range(nk):\n        for i in range(nntot):\n            for j in range(ngs):\n                br = np.dot(bpts[k,i], coords[j])\n                phase_b[k,i,j] = np.exp(-1j*br)\n\n    nbas = cell.nao_nr()\n    Mmunu = np.zeros((nk,nntot,nbas,nbas), dtype = np.complex128)\n    Mmn = np.zeros((nk,nntot,nband,nband), dtype = np.complex128)\n    for k, aoR_k in enumerate(aoR):\n        for i in range(nntot):\n            Mmunu[k,i] = weight * lib.dot(aoR_k.T.conj()*phase_b[k,i], aoR_k)\n\n    for k in range(nk):\n        for i in range(nntot):\n            Mmn[k,i] = lib.dot(lib.dot(mo_coeff[:,bands].T.conj(), Mmunu[k,i]), mo_coeff[:,bands])\n\n    return Mmn\n\ndef read_proj_data(filename):\n\n    nband = 0\n    with open( filename, 'r' ) as f:\n        tmp = next(f)\n        nband = int(next(f))\n        R = np.zeros((nband,3))\n        lmr = np.zeros((nband,3),dtype=np.int32)\n        zaxis = np.zeros((nband,3))\n        xaxis = np.zeros((nband,3))\n        zona = np.zeros(nband)\n        for i in range(nband):\n            tmp = [float(x) for x in next(f).split()]\n            R[i,0:3] = tmp[0:3]\n            lmr[i,0:3] = [int(x) for x in tmp[3:6]]\n            tmp =  [float(x) for x in next(f).split()]\n            zaxis[i,0:3] = tmp[0:3]\n            xaxis[i,0:3] = tmp[3:6]\n            zona[i] = tmp[6]\n            zona[i] *= param.BOHR\n\n        return (R,lmr,zaxis,xaxis,zona) \n\n\ndef comput_g_r_para(i, R,lmr,zaxis,xaxis,zona,coords):\n\n        ngs = len(coords)\n        g_r = np.zeros((ngs))\n\n        l=lmr[i,0]\n        m=lmr[i,1]\n        r=lmr[i,2]\n        zax = zaxis[i]\n        xax = xaxis[i]  \n\n        r_rel = coords - R[i]\n        radial = g_r_radial(r,zona[i],r_rel)\n        ang = None\n        if(l<0):\n            if(l == -1):\n                s = g_r_ang(0,1,r_rel,zax,xax)\n                px = g_r_ang(1,2,r_rel,zax,xax)\n                fac = 1.0/sqrt(2.0)\n                if(m == 1):\n                    ang = fac*(s+px)\n                elif(m == 2):\n                    ang = fac*(s-px)\n\n            elif(l == -2):\n                s = g_r_ang(0,1,r_rel,zax,xax)\n                px = g_r_ang(1,2,r_rel,zax,xax)\n                if(m == 1):\n                    py = g_r_ang(1,3,r_rel,zax,xax)\n                    ang = 1.0/sqrt(3.0)*s - 1.0/sqrt(6.0)*px + 1.0/sqrt(2.0)*py\n                elif(m == 2):\n                    py = g_r_ang(1,3,r_rel,zax,xax)\n                    ang = 1.0/sqrt(3.0)*s - 1.0/sqrt(6.0)*px - 1.0/sqrt(2.0)*py\n                elif(m == 3):\n                    ang = 1.0/sqrt(3.0)*s + 2.0/sqrt(6.0)*px\n\n            elif(l == -3):\n                s = g_r_ang(0,1,r_rel,zax,xax)\n                px = g_r_ang(1,2,r_rel,zax,xax)\n                py = g_r_ang(1,3,r_rel,zax,xax)\n                pz = g_r_ang(1,1,r_rel,zax,xax)\n                \n                if(m == 1):\n                    ang = 0.5*(s+px+py+pz)\n                elif(m == 2):\n                    ang = 0.5*(s+px-py-pz)\n                elif(m == 3):\n                    ang = 0.5*(s-px+py-pz)\n                elif(m == 4):\n                    ang = 0.5*(s-px-py+pz)\n\n            else:\n                raise Exception(\"NYI\")\n        else:\n            ang = g_r_ang(l,m,r_rel,zax,xax)\n\n        g_r = radial * ang\n\n        del radial, ang, r_rel\n        return g_r\n\n\n\ndef comput_g_r(R,lmr,zaxis,xaxis,zona,nband,coords):\n\n    ngs = len(coords)\n    g_r = np.zeros((nband,ngs))\n   \n    for i in range(nband):\n        l=lmr[i,0]\n        m=lmr[i,1]\n        r=lmr[i,2]\n        zax = zaxis[i]\n        xax = xaxis[i]  \n\n        r_rel = coords - R[i]\n        radial = g_r_radial(r,zona[i],r_rel)\n        ang = None\n        if(l<0):\n            if(l == -1):\n                s = g_r_ang(0,1,r_rel,zax,xax)\n                px = g_r_ang(1,2,r_rel,zax,xax)\n                fac = 1.0/sqrt(2.0)\n                if(m == 1):\n                    ang = fac*(s+px)\n                elif(m == 2):\n                    ang = fac*(s-px)\n\n            elif(l == -2):\n                s = g_r_ang(0,1,r_rel,zax,xax)\n                px = g_r_ang(1,2,r_rel,zax,xax)\n                if(m == 1):\n                    py = g_r_ang(1,3,r_rel,zax,xax)\n                    ang = 1.0/sqrt(3.0)*s - 1.0/sqrt(6.0)*px + 1.0/sqrt(2.0)*py\n                elif(m == 2):\n                    py = g_r_ang(1,3,r_rel,zax,xax)\n                    ang = 1.0/sqrt(3.0)*s - 1.0/sqrt(6.0)*px - 1.0/sqrt(2.0)*py\n                elif(m == 3):\n                    ang = 1.0/sqrt(3.0)*s + 2.0/sqrt(6.0)*px\n\n            elif(l == -3):\n                s = g_r_ang(0,1,r_rel,zax,xax)\n                px = g_r_ang(1,2,r_rel,zax,xax)\n                py = g_r_ang(1,3,r_rel,zax,xax)\n                pz = g_r_ang(1,1,r_rel,zax,xax)\n                \n                if(m == 1):\n                    ang = 0.5*(s+px+py+pz)\n                elif(m == 2):\n                    ang = 0.5*(s+px-py-pz)\n                elif(m == 3):\n                    ang = 0.5*(s-px+py-pz)\n                elif(m == 4):\n                    ang = 0.5*(s-px-py+pz)\n\n            else:\n                raise Exception(\"NYI\")\n        else:\n            ang = g_r_ang(l,m,r_rel,zax,xax)\n\n        g_r[i] = radial * ang\n\n    return g_r\n\ndef g_r_ang(l,m,r_rel,zaxis,xaxis):\n\n    ngs = len(r_rel)\n    ang = np.zeros(ngs)\n    if(l==0):\n        ang[:] = 1.0/sqrt(4.0*np.pi)\n        return ang\n\n    yaxis = np.cross(zaxis,xaxis)\n    yaxis = yaxis*(1.0/np.linalg.norm(yaxis))\n    xy_perp = np.cross(xaxis,yaxis)\n\n    if(l==1):\n        fac = sqrt(0.75*np.pi)\n        if(m==1):\n            ang = fac*cos_theta(r_rel,zaxis)\n        elif(m==2):\n            ang = fac*sin_theta(r_rel,zaxis)*cos_phi(r_rel,xy_perp,xaxis,yaxis)\n        elif(m==3):\n            ang = fac*sin_theta(r_rel,zaxis)*sin_phi(r_rel,xy_perp,xaxis,yaxis)\n    else:\n        raise Exception(\"NYI\")\n\n    return ang\n\ndef sin_phi(r_rel,xy_perp,xaxis,yaxis):\n\n    return sin_cos_phi(r_rel,xy_perp,xaxis,yaxis)[0]\n\ndef cos_phi(r_rel,xy_perp,xaxis,yaxis):\n\n    return sin_cos_phi(r_rel,xy_perp,xaxis,yaxis)[1]\n\ndef sin_cos_phi(r_rel,xy_perp,xaxis,yaxis):\n\n    ngs = len(r_rel)\n    sin_phi = np.zeros(ngs)\n    cos_phi = np.zeros(ngs)\n    x_norm = np.linalg.norm(xaxis)\n\n    for i in range(ngs):\n        r_proj_xy = np.cross(np.cross(xy_perp, r_rel[i]), xy_perp)\n        dot = np.dot(r_proj_xy, xaxis)\n        ab = np.linalg.norm(r_proj_xy) * x_norm\n        if(ab == 0.0):\n            cos_phi[i] = 0.0\n        else:\n            cos_phi[i] = dot/ab\n\n        sin_phi[i] = sqrt(1.0-cos_phi[i]**2)\n        dot = np.dot(r_proj_xy, yaxis)\n        if(dot < 0.0):\n            sin_phi[i] *= -1.0\n\n    return(sin_phi, cos_phi)\n\n\ndef sin_theta(r_rel,zaxis):\n\n    cos = cos_theta(r_rel,zaxis)\n    sin_theta = np.sqrt(1.0-np.square(cos))\n    del cos\n    return sin_theta\n\ndef cos_theta(r_rel,zaxis):\n\n    ngs = len(r_rel)\n    cos_theta = np.zeros(ngs)\n    z_norm = np.linalg.norm(zaxis)\n\n    for i in range(ngs):\n        dot = np.dot(r_rel[i],zaxis)\n        ab = np.linalg.norm(r_rel[i]) * z_norm\n        if(ab == 0.0):\n            cos_theta[i] = 0.0\n        else:\n            cos_theta[i] = dot/ab\n\n    return cos_theta\n\n\ndef g_r_radial(r,zona,r_rel):\n\n    ngs = len(r_rel)\n    radial = np.zeros(ngs)\n\n    r_norm = np.zeros(ngs)\n    for i in range(ngs):\n        r_norm[i] = np.linalg.norm(r_rel[i])\n\n    if(r==1):\n        fac = 2.0*math.pow(zona, 1.5)\n        radial = fac*np.exp(-1.0*zona*r_norm)\n    elif(r==2):\n        fac = 0.5/sqrt(2.0)*math.pow(zona, 1.5)\n        radial = fac*(2.0-zona*r_norm)*np.exp(-0.5*zona*r_norm)\n    elif(r==3):\n        fac = sqrt(4.0/27.0)*math.pow(zona, 1.5)\n        radial = fac*(1.0-2.0/3.0*zona*r_norm+2.0/27.0*zona**2*np.square(r_norm))*np.exp(-1.0/3.0*zona*r_norm)\n    else:\n        raise Exception(\"NYI\")\n\n    del r_norm\n    return radial\n\ndef comput_Amn(wf, Rc=None,lmr=None,zaxis=None,xaxis=None,zona=None, bands = None, nband = None, kpts = np.zeros((1,3)),max_memory=None):\n\n    if Rc is None: Rc = wf.Rc\n    if lmr is None: lmr = wf.lmr\n    if zaxis is None: zaxis = wf.zaxis\n    if xaxis is None: xaxis = wf.xaxis\n    if zona is None: zona = wf.zona\n    if bands is None: bands = wf.bands\n    if nband is None: nband = wf.nband\n    if max_memory is None: max_memory = wf.max_memory\n\n    nk = len(kpts)\n    mf = wf.mf\n    mo_coeff = mf.mo_coeff\n\n    cell = wf.cell\n    mydf = mf.with_df\n    gs = mydf.gs\n\n    coords = cell.gen_uniform_grids(gs)\n    ngs = len(coords)\n\n    ni = mydf._numint\n\n    weight = cell.vol / ngs\n\n    aoR = ni.eval_ao(cell, coords, kpts, non0tab=None)\n\n    a = cell.lattice_vectors()\n    R = np.dot(Rc,a)\n    #g_r = comput_g_r(R,lmr,zaxis,xaxis,zona,nband,coords)\n    \n    #parallel block \n    g_r = np.ndarray((nband*ngs))\n\n    from pyscf import lib\n    max_mem = wf.max_memory - lib.current_memory()[0]\n    print ('available mem (Mb) = ', max_mem)\n\n    blk_size = min(ngs,(max_mem*1e6/8-nband*ngs*3)/12/16)\n    nblks = ngs//blk_size\n    if(nblks <= 1):\n        nblks = lib.num_threads()\n    blk_size = ngs//nblks\n    #g_r_blks = np.concatenate(tuple[g_r_split[i] for i in range(nblks)],axis=0)\n\n\n    libmisc.comput_g_r(ctypes.c_int(blk_size), ctypes.c_int(nblks), \\\n                       g_r.ctypes.data_as(ctypes.c_void_p), coords.ctypes.data_as(ctypes.c_void_p),ctypes.c_int(ngs), ctypes.c_int(nband), \\\n                       R.ctypes.data_as(ctypes.c_void_p),lmr.ctypes.data_as(ctypes.c_void_p), zaxis.ctypes.data_as(ctypes.c_void_p), \\\n                       xaxis.ctypes.data_as(ctypes.c_void_p),zona.ctypes.data_as(ctypes.c_void_p))\n\n\n    g_r_split = np.split(g_r,[i*nband*blk_size for i in range(1,nblks)])\n    for i in range(nblks):\n        g_r_split[i] = np.reshape(g_r_split[i],(nband,-1))\n\n    g_r = np.concatenate([g_r_split[i] for i in range(nblks)],axis=1)\n\n\n    \n    '''\n    pool = Pool()\n    results = [pool.apply_async(comput_g_r_para, (i, R,lmr,zaxis,xaxis,zona,coords,)) for i in range(nband) ]\n    pool.close()\n    pool.join()\n    for i in range(nband):\n        g_r[i] = results[i].get()\n    '''\n    '''\n    #assume 8 proc\n    blk_size = ngs//8\n    tmp = np.split(coords,[blk_size,blk_size*2,blk_size*3,blk_size*4,blk_size*5,blk_size*6,blk_size*7])\n    for i in range(nband):\n        pool = Pool(8,maxtasksperchild=1)\n        results = [pool.apply_async(comput_g_r_para, (i, R,lmr,zaxis,xaxis,zona,coords_blk,)) for blk,coords_blk in enumerate(tmp) ]\n        pool.close()\n        pool.join()\n        for blk in range(8):\n            index1 = blk*blk_size\n            index2 = index1+blk_size\n            if(blk == 7):\n                index2 = ngs\n            g_r[i][index1:index2] = results[blk].get()\n\n    del tmp\n    #end parallel block\n    '''   \n\n    print ('available mem (Mb) = ', wf.max_memory - lib.current_memory()[0])\n \n    nao = cell.nao_nr()\n    Amun = np.zeros((nk,nao,nband), dtype = np.complex128)\n    Amn = np.zeros((nk,nband,nband), dtype = np.complex128)\n    for k, aoR_k in enumerate(aoR):\n        Amun[k] = weight * lib.dot(aoR_k.T.conj(), g_r.T)\n\n    for k in range(nk):\n        Amn[k] = lib.dot(mo_coeff[:,bands].T.conj(), Amun[k])\n\n    return Amn\n\n\ndef wannier90_setup(wf, seedname=None, mp_grid_dim=None, num_kpts=None, real_lattice=None, recip_lattice=None, \\\n                    kpt_latt=None, num_bands_tot=None, num_atoms=None, atom_symbols=None, atoms_cart=None, \\\n                    gamma_only=None, spinors=False):\n\n    if seedname is None: seedname = wf.seedname\n    if mp_grid_dim is None: mp_grid_dim = wf.mp_grid_dim\n    if num_kpts is None: num_kpts = wf.num_kpts\n    if real_lattice is None: real_lattice = wf.real_lattice\n    if recip_lattice is None: recip_lattice = wf.recip_lattice\n    if kpt_latt is None: kpt_latt = wf.kpt_latt\n    if num_bands_tot is None: num_bands_tot = wf.num_bands_tot\n    if num_atoms is None: num_atoms = wf.num_atoms\n    if atom_symbols is None: atom_symbols = wf.atom_symbols\n    if atoms_cart is None: atoms_cart = wf.atoms_cart\n    if gamma_only is None: gamma_only = wf.gamma_only\n\n    real_lattice = real_lattice * param.BOHR  #unit: Angstrom\n    recip_lattice = recip_lattice / param.BOHR #unit: 1/Angstrom\n    real_lattice_T = real_lattice.T\n    recip_lattice_T = recip_lattice.T\n\n    atoms_cart = atoms_cart * param.BOHR #unit: Angstrom\n\n    #output\n    nnlist = np.ndarray((num_kpts,num_nnmax), dtype = np.int32, order='F')\n    nncell = np.ndarray((3,num_kpts,num_nnmax), dtype = np.int32, order='F')\n    nntot = np.ndarray((1), dtype = np.int32)\n    num_bands = np.ndarray((1), dtype = np.int32)\n    num_wann = np.ndarray((1), dtype = np.int32)\n    proj_site = np.ndarray((num_bands_tot,3))\n    proj_l = np.ndarray((num_bands_tot), dtype = np.int32)\n    proj_m = np.ndarray((num_bands_tot), dtype = np.int32)\n    proj_radial = np.ndarray((num_bands_tot), dtype = np.int32)\n    proj_z = np.ndarray((num_bands_tot,3))\n    proj_x = np.ndarray((num_bands_tot,3))\n    proj_zona = np.ndarray((num_bands_tot))\n    exclude_bands = np.ndarray((num_bands_tot), dtype = np.int32)\n    proj_s = np.ndarray((num_bands_tot), dtype = np.int32)\n    proj_s_qaxis = np.ndarray((num_bands_tot,3))\n\n    arr = (ctypes.c_char_p * num_atoms)()\n    arr[:] = atom_symbols\n    #fn_setup = getattr(lib_wannier90, 'wannier90_setup')\n    lib_wannier90.wannier90_setup(ctypes.c_char_p(seedname), mp_grid_dim.ctypes.data_as(ctypes.c_void_p),ctypes.c_int(num_kpts), \\\n             real_lattice_T.ctypes.data_as(ctypes.c_void_p),recip_lattice_T.ctypes.data_as(ctypes.c_void_p), \\\n             kpt_latt.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(num_bands_tot), \\\n             ctypes.c_int(num_atoms), arr, atoms_cart.ctypes.data_as(ctypes.c_void_p), \\\n             ctypes.c_int(gamma_only), ctypes.c_int(spinors), \\\n             nntot.ctypes.data_as(ctypes.c_void_p),nnlist.ctypes.data_as(ctypes.c_void_p),\\\n             nncell.ctypes.data_as(ctypes.c_void_p),num_bands.ctypes.data_as(ctypes.c_void_p),num_wann.ctypes.data_as(ctypes.c_void_p), \\\n             proj_site.ctypes.data_as(ctypes.c_void_p),proj_l.ctypes.data_as(ctypes.c_void_p),proj_m.ctypes.data_as(ctypes.c_void_p), \\\n             proj_radial.ctypes.data_as(ctypes.c_void_p), proj_z.ctypes.data_as(ctypes.c_void_p), \\\n             proj_x.ctypes.data_as(ctypes.c_void_p),proj_zona.ctypes.data_as(ctypes.c_void_p), \\\n             exclude_bands.ctypes.data_as(ctypes.c_void_p),proj_s.ctypes.data_as(ctypes.c_void_p), \\\n             proj_s_qaxis.ctypes.data_as(ctypes.c_void_p))\n\n    nntot = nntot[0]\n    num_bands = num_bands[0]\n    num_wann = num_wann[0]\n\n    proj_zona *= param.BOHR\n\n    return (nnlist,nncell,nntot,num_bands,num_wann,\\\n            proj_site,proj_l,proj_m,proj_radial,\\\n            proj_z,proj_x,proj_zona,exclude_bands,\\\n            proj_s,proj_s_qaxis)\n\n\ndef wannier90_run(wf, Mmn=None, Amn=None, eigenvalues=None, \\\n                  seedname=None, mp_grid_dim=None, num_kpts=None, real_lattice=None, recip_lattice=None, \\\n                  kpt_latt=None, num_bands=None,num_wann=None,nntot=None,num_atoms=None, atom_symbols=None, atoms_cart=None, \\\n                  gamma_only=None):\n\n    if Mmn is None: Mmn = wf.Mmn\n    if Amn is None: Amn = wf.Amn\n    if eigenvalues is None: eigenvalues = wf.eig\n\n    if seedname is None: seedname = wf.seedname\n    if mp_grid_dim is None: mp_grid_dim = wf.mp_grid_dim\n    if num_kpts is None: num_kpts = wf.num_kpts\n    if real_lattice is None: real_lattice = wf.real_lattice\n    if recip_lattice is None: recip_lattice = wf.recip_lattice\n    if kpt_latt is None: kpt_latt = wf.kpt_latt\n    if num_bands is None: num_bands = wf.num_bands\n    if num_wann is None: num_wann = wf.num_wann\n    if nntot is None: nntot = wf.nntot\n    if num_atoms is None: num_atoms = wf.num_atoms\n    if atom_symbols is None: atom_symbols = wf.atom_symbols\n    if atoms_cart is None: atoms_cart = wf.atoms_cart\n    if gamma_only is None: gamma_only = wf.gamma_only\n\n    real_lattice = real_lattice * param.BOHR  #unit: Angstrom\n    recip_lattice = recip_lattice / param.BOHR #unit: 1/Angstrom\n    real_lattice_T = real_lattice.T\n    recip_lattice_T = recip_lattice.T\n\n    atoms_cart = atoms_cart * param.BOHR #unit: Angstrom\n\n    arr = (ctypes.c_char_p * num_atoms)()\n    arr[:] = atom_symbols\n\n    M_matrix = np.zeros((num_kpts, nntot, num_bands, num_bands), dtype=np.complex128)\n    for k in range(num_kpts):\n        for i in range(nntot):\n            M_matrix[k,i] = Mmn[k,i].T\n\n    A_matrix = np.zeros((num_kpts,num_wann,num_bands),dtype=np.complex128)\n    for k in range(num_kpts):\n        A_matrix[k] = Amn[k].T\n\n\n    #output\n    U_matrix = np.ndarray((num_kpts,num_wann,num_wann), dtype = np.complex128)\n    U_matrix_opt = np.ndarray((num_kpts,num_wann,num_bands), dtype = np.complex128)\n    lwindow = np.ndarray((num_kpts,num_bands), dtype=np.int32)\n    wann_centres = np.ndarray((num_wann,3))\n    wann_spreads = np.ndarray((num_wann))\n    spread = np.ndarray((3))\n\n    lib_wannier90.wannier90_run(ctypes.c_char_p(seedname),mp_grid_dim.ctypes.data_as(ctypes.c_void_p),ctypes.c_int(num_kpts), \\\n                                real_lattice_T.ctypes.data_as(ctypes.c_void_p),recip_lattice_T.ctypes.data_as(ctypes.c_void_p), \\\n                                kpt_latt.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(num_bands), ctypes.c_int(num_wann), \\\n                                ctypes.c_int(nntot),ctypes.c_int(num_atoms), \\\n                                arr,atoms_cart.ctypes.data_as(ctypes.c_void_p),\\\n                                ctypes.c_int(gamma_only),\\\n                                M_matrix.ctypes.data_as(ctypes.c_void_p),A_matrix.ctypes.data_as(ctypes.c_void_p),\\\n                                eigenvalues.ctypes.data_as(ctypes.c_void_p),\\\n                                U_matrix.ctypes.data_as(ctypes.c_void_p),U_matrix_opt.ctypes.data_as(ctypes.c_void_p),\\\n                                lwindow.ctypes.data_as(ctypes.c_void_p),wann_centres.ctypes.data_as(ctypes.c_void_p),\\\n                                wann_spreads.ctypes.data_as(ctypes.c_void_p),spread.ctypes.data_as(ctypes.c_void_p))\n    for k in range(num_kpts):\n        U_matrix[k] = U_matrix[k].T\n\n    #print U_matrix\n\n    return U_matrix\n\nclass wannier2:\n\n    def __init__(self, the_mf, mp_grid_dim, seedname, bands=None, plot=False, reorder=False, max_memory=None):\n\n        self.mp_grid_dim = np.asarray(mp_grid_dim, dtype=np.int32)\n        self.num_kpts = mp_grid_dim[0]*mp_grid_dim[1]*mp_grid_dim[2]\n\n        self.seedname = seedname\n        self.plot = plot\n        self.reorder = reorder\n\n        self.mf = the_mf\n        self.cell = self.mf.cell\n        self.real_lattice = self.cell.lattice_vectors()\n        self.recip_lattice = self.cell.reciprocal_vectors()\n        \n        self.max_memory = max_memory\n        if self.max_memory is None: self.max_memory = self.cell.max_memory\n\n        self.num_bands_tot = self.cell.nao_nr() \n        self.bands = bands\n        if self.bands is None: self.bands = np.arange(self.num_bands_tot)\n\n        self.num_atoms = self.cell.natm\n        self.atom_symbols = [x[0] for x in self.cell._atom]\n        self.atoms_cart = np.asarray([x[1] for x in self.cell._atom])\n\n        self.kpts = None\n        if isinstance(self.mf, pbc.scf.khf.KSCF) : self.kpts = self.mf.kpts\n        elif isinstance(self.mf, pbc.scf.hf.SCF) : self.kpts = self.mf.kpt\n        self.kpts = self.kpts.reshape((-1,3))\n        self.kpt_latt = self.cell.get_scaled_kpts(self.kpts)\n\n        assert(len(self.kpt_latt) == self.num_kpts)\n\n        self.gamma_only = False\n        if gamma_point(self.kpts) : self.gamma_only = True\n\n        eig = self.mf.mo_energy\n        eig *= param.HARTREE2EV #in eV\n        self.eig = eig.reshape((-1,self.num_bands_tot))\n\n        self.nnlist,self.nncell,self.nntot,self.num_bands,self.num_wann,\\\n        self.proj_site,self.proj_l,self.proj_m,self.proj_radial,\\\n        self.proj_z,self.proj_x,self.proj_zona,self.exclude_bands,\\\n        self.proj_s,self.proj_s_qaxis = self.wannier90_setup()\n\n        #print self.proj_site\n        #print self.proj_l\n        #print self.proj_m\n        #print self.proj_radial\n\n    def kernel(self):\n\n        nnkpts = get_nnkpts(self.nntot, self.nnlist, self.nncell)\n        self.bpts = get_bpts(self, nnkpts, self.kpts)\n\n        if(self.plot):\n            write_bloch_u_r(self, self.bands, self.num_bands_tot, self.kpts)\n\n        t0 = (time.clock(),time.time())\n        self.Mmn = comput_Mmn(self, self.bands, self.num_bands, self.bpts, self.kpts)\n        #write_Mmn(self, self.seedname+'.mmn', self.num_kpts, self.num_bands, self.Mmn, nnkpts)\n        t1 = tools.timer(\"Mmn\",t0)\n\n        self.lmr = np.column_stack((self.proj_l,self.proj_m,self.proj_radial))\n\n        t0 = (time.clock(),time.time()) \n        self.Amn = comput_Amn(self, self.proj_site, self.lmr, self.proj_z, self.proj_x, self.proj_zona, self.bands, self.num_bands, self.kpts)\n        t1 = tools.timer(\"Amn\",t0)\n\n        u_mat = self.wannier90_run()\n        self.u_mat = u_mat\n        if (self.reorder):\n            seq = self.assign_wf2atm()\n            self.u_mat = u_mat[:,:,seq]\n\n        #calc_iso_cutoff(self, self.u_mat, self.bands, self.num_bands, self.kpts)\n\n    wannier90_setup = wannier90_setup\n    wannier90_run = wannier90_run\n    assign_wf2atm = assign_wf2atm\n\nclass wannier:\n\n    def __init__(self, the_mf, nnkpts, seedname,bands, has_proj_data=False, kpts = np.zeros((1,3))):\n\n        self.mf = the_mf\n        self.cell = self.mf.cell\n        self.nnkpts = nnkpts\n        self.bands = bands\n        self.nband = len(self.bands)\n        self.kpts = kpts\n        self.file_mmn = seedname+'.mmn'\n        self.file_amn = seedname+'.amn'\n        self.file_ene = seedname+'.eig'\n\n        self.bpts = self.get_bpts()\n        self.Mmn = self.comput_Mmn()\n        self.write_Mmn(self.file_mmn, len(self.kpts))\n        self.write_bloch_u_r()\n        self.write_eig(self.file_ene)\n\n        self.Rc = None \n        self.lmr = None\n        self.zaxis = None\n        self.xaxis = None\n        self.zona = None\n        self.Amn = None\n        if(has_proj_data):\n            self.file_proj_data = seedname+'.proj'\n            self.Rc,self.lmr,self.zaxis,self.xaxis,self.zona = read_proj_data(self.file_proj_data)\n            self.Amn = self.comput_Amn()\n            self.write_Amn(self.file_amn, len(self.kpts))\n\n    get_bpts = get_bpts\n    comput_Mmn = comput_Mmn\n    write_Mmn = write_Mmn\n    comput_Amn = comput_Amn\n    write_Amn = write_Amn\n    write_bloch_u_r = write_bloch_u_r\n    write_eig = write_eig\n", "meta": {"hexsha": "a7ef25932b00902eb92ced439df3b4a1ac627178", "size": 31087, "ext": "py", "lang": "Python", "max_stars_repo_path": "pydmfet/locints/mmn_wannier90.py", "max_stars_repo_name": "fishjojo/pydmfe", "max_stars_repo_head_hexsha": "93cfc655314933d3531b5733521a1f95a044f6cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-02-26T06:26:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T08:58:20.000Z", "max_issues_repo_path": "pydmfet/locints/mmn_wannier90.py", "max_issues_repo_name": "fishjojo/pydmfet", "max_issues_repo_head_hexsha": "93cfc655314933d3531b5733521a1f95a044f6cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pydmfet/locints/mmn_wannier90.py", "max_forks_repo_name": "fishjojo/pydmfet", "max_forks_repo_head_hexsha": "93cfc655314933d3531b5733521a1f95a044f6cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5859538784, "max_line_length": 142, "alphanum_fraction": 0.5735516454, "include": true, "reason": "import numpy", "num_tokens": 9788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19209889176289363}}
{"text": "# SPDX-License-Identifier: Apache-2.0\n# SPDX-FileCopyrightText: © 2019- d3p Developers and their Assignees\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n#     http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\" Stochastic Variational Inference implementation with per-example gradient\n    manipulation capability.\n\"\"\"\nimport functools\nfrom typing import Any, NamedTuple, Sequence, Tuple\n\nimport jax\nimport jax.numpy as jnp\nimport numpy as np\n\nfrom numpyro.infer.svi import SVI, SVIState\nfrom numpyro.infer.elbo import ELBO\nfrom numpyro.handlers import seed, trace, substitute, block\n\nfrom d3p.util import example_count\nimport d3p.random as strong_rng\n\nfrom fourier_accountant.compute_eps import get_epsilon_R\nfrom fourier_accountant.compute_delta import get_delta_R\n\nPRNGState = Any\n\n\nclass DPSVIState(NamedTuple):\n    optim_state: Any\n    rng_key: PRNGState\n    observation_scale: float\n\n\ndef get_observations_scale(model, model_args, model_kwargs, params):\n    \"\"\"\n    Traces through a model to extract the scale applied to observation log-likelihood.\n    \"\"\"\n\n    # todo(lumip): is there a way to avoid tracing through the entire model?\n    #       need to experiment with effect handlers and what exactly blocking achieves\n    model = substitute(seed(model, 0), data=params)\n    model = block(model, lambda msg: msg['type'] != 'sample' or not msg['is_observed'])\n    model_trace = trace(model).get_trace(*model_args, **model_kwargs)\n    scales = np.unique(\n        [msg['scale'] if msg['scale'] is not None else 1 for msg in model_trace.values()]\n    )\n\n    if len(scales) > 1:\n        raise ValueError(\n            \"The model received several observation sites with different example counts.\"\n            \" This is not supported in DPSVI.\"\n        )\n    elif len(scales) == 0:\n        return 1.\n\n    return scales[0]\n\n\nclass CombinedLoss(object):\n\n    def __init__(self, per_example_loss: ELBO, combiner_fn=jnp.mean):\n        self.px_loss = per_example_loss\n        self.combiner_fn = combiner_fn\n\n    def loss(self, rng_key, param_map, model, guide, *args, **kwargs):\n        return self.combiner_fn(self.px_loss.loss(\n            rng_key, param_map, model, guide, *args, **kwargs\n        ))\n\n\ndef full_norm(list_of_parts_or_tree, ord=2):\n    \"\"\"Computes the total norm over a list of values (of any shape) or a jax\n    tree by treating them as a single large vector.\n\n    :param list_of_parts_or_tree: The list or jax tree of values that make up\n        the vector to compute the norm over.\n    :param ord: Order of the norm. May take any value possible for\n    `numpy.linalg.norm`.\n    :return: The indicated norm over the full vector.\n    \"\"\"\n    if isinstance(list_of_parts_or_tree, list):\n        list_of_parts = list_of_parts_or_tree\n    else:\n        list_of_parts = jax.tree_leaves(list_of_parts_or_tree)\n\n    if list_of_parts is None or len(list_of_parts) == 0:\n        return 0.\n\n    ravelled = [g.ravel() for g in list_of_parts]\n    gradients = jnp.concatenate(ravelled)\n    assert(len(gradients.shape) == 1)\n    norm = jnp.linalg.norm(gradients, ord=ord)\n    return norm\n\n\ndef normalize_gradient(list_of_gradient_parts, ord=2):\n    \"\"\"Normalizes a gradient by its total norm.\n\n    The norm is computed by interpreting the given list of parts as a single\n    vector (see `full_norm`).\n\n    :param list_of_gradient_parts: A list of values (of any shape) that make up\n        the overall gradient vector.\n    :return: Normalized gradients given in the same format/layout/shape as\n        list_of_gradient_parts.\n    \"\"\"\n    norm_inv = 1./full_norm(list_of_gradient_parts, ord=ord)\n    normalized = [norm_inv * g for g in list_of_gradient_parts]\n    return normalized\n\n\ndef clip_gradient(list_of_gradient_parts, c, rescale_factor=1.):\n    \"\"\"Clips the total norm of a gradient by a given value C.\n\n    The norm is computed by interpreting the given list of parts as a single\n    vector (see `full_norm`). Each entry is then scaled by the factor\n    (1/max(1, norm/C)) which effectively clips the norm to C. Additionally,\n    the gradient can be scaled by a given factor before clipping.\n\n    :param list_of_gradient_parts: A list of values (of any shape) that make up\n        the overall gradient vector.\n    :param c: The clipping threshold C.\n    :param rescale_factor: Factor to scale the gradient by before clipping.\n    :return: Clipped gradients given in the same format/layout/shape as\n        list_of_gradient_parts.\n    \"\"\"\n    if c == 0.:\n        raise ValueError(\"The clipping threshold must be greater than 0.\")\n    norm = full_norm(list_of_gradient_parts) * rescale_factor  # norm of rescale_factor * grad\n    normalization_constant = 1./jnp.maximum(1., norm/c)\n    f = rescale_factor * normalization_constant  # to scale grad to max(rescale_factor * grad, C)\n    clipped_grads = [f * g for g in list_of_gradient_parts]\n    return clipped_grads\n\n\ndef get_gradients_clipping_function(c, rescale_factor):\n    \"\"\"Factory function to obtain a gradient clipping function for a fixed\n    clipping threshold C.\n\n    :param c: The clipping threshold C.\n    :param rescale_factor: Factor to scale the gradient by before clipping.\n    :return: `clip_gradient` function with fixed threshold C. Only takes a\n        list_of_gradient_parts as argument.\n    \"\"\"\n    @functools.wraps(clip_gradient)\n    def gradient_clipping_fn_inner(list_of_gradient_parts):\n        return clip_gradient(list_of_gradient_parts, c, rescale_factor)\n    return gradient_clipping_fn_inner\n\n\nclass DPSVI(SVI):\n    \"\"\"\n    Differentially-Private Stochastic Variational Inference given a per-example\n    loss objective and a gradient clipping threshold.\n\n    This is identical to numpyro's `SVI` but adds differential privacy by\n    clipping gradients per example to the given clipping_threshold and\n    perturbing the batch gradient with noise determined by sigma*clipping_threshold.\n\n    To obtain the per-example gradients, the `per_example_loss_fn` is evaluated\n    for (and the gradient take wrt) each example in a vectorized manner (using\n    `jax.vmap`).\n\n    For this to work `per_example_loss_fn` must be able to deal with batches\n    of single examples. The leading batch dimension WILL NOT be stripped away,\n    however, so a `per_example_loss_fn` that can deal with arbitrarily sized batches\n    suffices. Take special care that the loss function scales the likelihood\n    contribution of the data properly wrt to batch size and total example count\n    (use e.g. the `numpyro.scale` or the convenience `minibatch` context managers\n    in the `model` and `guide` functions where appropriate).\n\n    :param model: Python callable with Pyro primitives for the model.\n    :param guide: Python callable with Pyro primitives for the guide\n        (recognition network).\n    :param per_example_loss_fn: ELBo loss, i.e. negative Evidence Lower Bound,\n        to minimize, per example.\n    :param optim: an instance of :class:`~numpyro.optim._NumPyroOptim`.\n    :param clipping_threshold: The clipping threshold C to which the norm\n        of each per-example gradient is clipped.\n    :param dp_scale: Scale parameter for the Gaussian mechanism applied to\n        each dimension of the batch gradients.\n    :param static_kwargs: static arguments for the model / guide, i.e. arguments\n        that remain constant during fitting.\n    \"\"\"\n\n    def __init__(\n            self,\n            model,\n            guide,\n            optim,\n            per_example_loss,\n            clipping_threshold,\n            dp_scale,\n            rng_suite=strong_rng,\n            **static_kwargs\n        ):  # noqa: E121, E125\n\n        self._clipping_threshold = clipping_threshold\n        self._dp_scale = dp_scale\n        self._rng_suite = rng_suite\n\n        if (not np.isfinite(clipping_threshold)):\n            raise ValueError(\"clipping_threshold must be finite!\")\n\n        total_loss = CombinedLoss(per_example_loss, combiner_fn=jnp.mean)\n        super().__init__(model, guide, optim, total_loss, **static_kwargs)\n\n    @staticmethod\n    def _update_state_rng(dp_svi_state: DPSVIState, rng_key: PRNGState) -> DPSVIState:\n        return DPSVIState(\n            dp_svi_state.optim_state,\n            rng_key,\n            dp_svi_state.observation_scale\n        )\n\n    @staticmethod\n    def _update_state_optim_state(dp_svi_state: DPSVIState, optim_state: Any) -> DPSVIState:\n        return DPSVIState(\n            optim_state,\n            dp_svi_state.rng_key,\n            dp_svi_state.observation_scale\n        )\n\n    def _split_rng_key(self, dp_svi_state: DPSVIState) -> Tuple[DPSVIState, PRNGState]:\n        rng_key = dp_svi_state.rng_key\n        rng_key, split_key = self._rng_suite.split(rng_key)\n        return DPSVI._update_state_rng(dp_svi_state, rng_key), split_key\n\n    def init(self, rng_key, *args, **kwargs):\n        jax_rng_key = self._rng_suite.convert_to_jax_rng_key(rng_key)\n        svi_state = super().init(jax_rng_key, *args, **kwargs)\n\n        if svi_state.mutable_state is not None:\n            raise RuntimeError(\"Mutable state is not supported.\")\n\n        model_kwargs = dict(kwargs)\n        model_kwargs.update(self.static_kwargs)\n\n        one_element_batch = [\n            jnp.expand_dims(a[0], 0) for a in args\n        ]\n\n        # note: DO use super().get_params here to get constrained/transformed params\n        #  for use in get_observations_scale (svi_state.optim_state holds unconstrained params)\n        params = super().get_params(svi_state)\n        observation_scale = get_observations_scale(\n            self.model, one_element_batch, model_kwargs, params\n        )\n\n        return DPSVIState(svi_state.optim_state, rng_key, observation_scale)\n\n    def _compute_per_example_gradients(self, dp_svi_state, *args, **kwargs):\n        \"\"\" Computes the raw per-example gradients of the model.\n\n        This is the first step in a full update iteration.\n\n        :param dp_svi_state: The current state of the DPSVI algorithm.\n        :param args: Arguments to the loss function.\n        :param kwargs: All keyword arguments to model or guide.\n        :returns: tuple consisting of the updated DPSVI state, an array of loss\n            values per example, and a jax tuple tree of per-example gradients\n            per parameter site (each site's gradients have shape (batch_size, *parameter_shape))\n        \"\"\"\n        dp_svi_state, rng_key_step = self._split_rng_key(dp_svi_state)\n        jax_rng_key = self._rng_suite.convert_to_jax_rng_key(rng_key_step)\n\n        # note: do NOT use self.get_params here; that applies constraint transforms for end-consumers of the parameters\n        # but internally we maintain and optimize on unconstrained params\n        # (they are constrained in the loss function so that we get the correct\n        # effect of the constraint transformation in the gradient)\n        params = self.optim.get_params(dp_svi_state.optim_state)\n\n        # we wrap the per-example loss (ELBO) to make it easier \"digestable\"\n        # for jax.vmap(jax.value_and_grad()): slighly reordering parameters; fixing kwargs, model and guide\n        def wrapped_px_loss(prms, rng_key, loss_args):\n            # vmap removes leading dimensions, we re-add those in a wrapper for fun so\n            # that fun can be oblivious of this\n            new_args = (jnp.expand_dims(arg, 0) for arg in loss_args)\n            return self.loss.px_loss.loss(\n                rng_key, self.constrain_fn(prms), self.model, self.guide,\n                *new_args, **kwargs, **self.static_kwargs\n            )\n\n        batch_size = jnp.shape(args[0])[0]  # todo: need checks to ensure this indexing is okay\n        px_rng_keys = jax.random.split(jax_rng_key, batch_size)\n\n        px_value_and_grad = jax.vmap(jax.value_and_grad(wrapped_px_loss), in_axes=(None, 0, 0))\n        per_example_loss, per_example_grads = px_value_and_grad(params, px_rng_keys, args)\n\n        return dp_svi_state, per_example_loss, per_example_grads\n\n    def _clip_gradients(self, dp_svi_state, px_gradients):\n        \"\"\" Clips each per-example gradient.\n\n        This is the second step in a full update iteration.\n\n        :param dp_svi_state: The current state of the DPSVI algorithm.\n        :param px_gradients: Jax tuple tree of per-example gradients as returned\n            by `_compute_per_example_gradients`\n        :returns: tuple consisting of the updated svi state, a list of\n            transformed per-example gradients per site and the jax tree structure\n            definition. The list is a flattened representation of the jax tree,\n            the shape of per-example gradients per parameter is unaffected.\n        \"\"\"\n        obs_scale = dp_svi_state.observation_scale\n\n        # px_gradients is a jax tree of jax jnp.arrays of shape\n        #   [batch_size, (param_shape)] for each parameter. flatten it out!\n        px_grads_list, px_grads_tree_def = jax.tree_flatten(\n            px_gradients\n        )\n\n        # scale the gradients by 1/obs_scale then clip them:\n        #  in the loss, every single examples loss contribution is scaled by obs_scale\n        #  but the clipping threshold assumes no scaling.\n        #  we scale by the reciprocal to ensure that clipping is correct.\n        clip_fn = get_gradients_clipping_function(self._clipping_threshold, 1./obs_scale)\n        px_grads_list = jax.vmap(clip_fn, in_axes=0)(px_grads_list)\n\n        return dp_svi_state, px_grads_list, px_grads_tree_def\n\n    def _combine_gradients(self, px_grads_list, px_loss):\n        \"\"\" Combines the per-example gradients into the batch gradient and\n            applies the batch gradient transformation given as\n            `batch_grad_manipulation_fn`.\n\n        This is the third step of a full update iteration.\n\n        :param px_grads_list: List of transformed per-example gradients as returned\n            by `_apply_per_example_gradient_transformations`\n        :param px_loss: Array of per-example loss values as output by\n            `_compute_per_example_gradients`.\n        :returns: tuple consisting of the updated svi state, the loss value for\n            the batch and a jax tree of batch gradients per parameter site.\n        \"\"\"\n\n        assert(self.loss.combiner_fn == jnp.mean)\n\n        loss_val = jnp.mean(px_loss, axis=0)\n        grads_list = tuple(map(lambda px_grad_site: jnp.mean(px_grad_site, axis=0), px_grads_list))\n\n        return loss_val, grads_list\n\n    def _perturb_and_reassemble_gradients(self, dp_svi_state, gradient_list, batch_size, px_grads_tree_def):\n        \"\"\" Perturbs the gradients using Gaussian noise and reassembles the gradient tree.\n\n        This is the fourth step of a full update iteration.\n\n        :param dp_svi_state: The current state of the DPSVI algorithm.\n        :param gradient_list: List of batch gradients for each parameter site\n        :param batch_size: Size of the training batch.\n        :param px_grads_tree_def: Jax tree definition for the gradient tree as\n            returned by `_apply_per_example_gradient_transformations`.\n        \"\"\"\n        dp_svi_state, perturbation_rng = self._split_rng_key(dp_svi_state)\n\n        perturbation_scale = self._dp_scale * self._clipping_threshold / batch_size\n        perturbed_grads_list = self.perturbation_function(\n            self._rng_suite, perturbation_rng, gradient_list, perturbation_scale\n        )\n\n        # we multiply each parameter site by obs_scale to revert the downscaling\n        # performed before clipping, so that the final gradient is scaled as\n        # expected without DP\n        obs_scale = dp_svi_state.observation_scale\n        perturbed_grads_list = tuple(\n            grad * obs_scale\n            for grad in perturbed_grads_list\n        )\n\n        # reassemble the jax tree used by optimizer for the final gradients\n        perturbed_grads = jax.tree_unflatten(\n            px_grads_tree_def, perturbed_grads_list\n        )\n\n        return dp_svi_state, perturbed_grads\n\n    def _apply_gradient(self, dp_svi_state, batch_gradient):\n        \"\"\" Takes a (batch) gradient step in parameter space using the specified\n            optimizer.\n\n        This is the fifth and last step of a full update iteration.\n        :param dp_svi_state: The current state of the DPSVI algorithm.\n        :param batch_gradient: Jax tree of batch gradients per parameter site,\n            as returned by `_combine_and_transform_gradient`.\n        :returns: tuple consisting of the updated svi state.\n        \"\"\"\n        optim_state = dp_svi_state.optim_state\n        new_optim_state = self.optim.update(batch_gradient, optim_state)\n\n        dp_svi_state = self._update_state_optim_state(dp_svi_state, new_optim_state)\n        return dp_svi_state\n\n    def update(self, svi_state, *args, **kwargs):\n        svi_state, per_example_loss, per_example_grads = \\\n            self._compute_per_example_gradients(svi_state, *args, **kwargs)\n\n        batch_size = example_count(per_example_loss)\n\n        svi_state, per_example_grads, tree_def = \\\n            self._clip_gradients(\n                svi_state, per_example_grads\n            )\n\n        loss, gradient = self._combine_gradients(\n            per_example_grads, per_example_loss\n        )\n\n        svi_state, gradient = self._perturb_and_reassemble_gradients(\n            svi_state, gradient, batch_size, tree_def\n        )\n\n        svi_state = self._apply_gradient(svi_state, gradient)\n\n        return svi_state, loss\n\n    def evaluate(self, svi_state: DPSVIState, *args, **kwargs):\n        \"\"\"\n        Take a single step of SVI (possibly on a batch / minibatch of data).\n\n        :param svi_state: current state of DPSVI.\n        :param args: arguments to the model / guide (these can possibly vary during\n            the course of fitting).\n        :param kwargs: keyword arguments to the model / guide.\n        :return: evaluate ELBO loss given the current parameter values\n            (held within `svi_state.optim_state`).\n        \"\"\"\n        # we split to have the same seed as `update_fn` given an svi_state\n        jax_rng_key = self._rng_suite.convert_to_jax_rng_key(self._rng_suite.split(svi_state.rng_key, 1)[0])\n        numpyro_svi_state = SVIState(svi_state.optim_state, None, jax_rng_key)\n        return super().evaluate(numpyro_svi_state, *args, **kwargs)\n\n    def _validate_epochs_and_iter(self, num_epochs, num_iter, q):\n        if num_epochs is not None:\n            num_iter = num_epochs / q\n        if num_iter is None:\n            raise ValueError(\"A value must be supplied for either num_iter or num_epochs\")\n        return num_iter\n\n    def get_epsilon(self, target_delta, q, num_epochs=None, num_iter=None):\n        num_iter = self._validate_epochs_and_iter(num_epochs, num_iter, q)\n\n        eps = get_epsilon_R(target_delta, self._dp_scale, q, ncomp=num_iter)\n        return eps\n\n    def get_delta(self, target_epsilon, q, num_epochs=None, num_iter=None):\n        num_iter = self._validate_epochs_and_iter(num_epochs, num_iter, q)\n\n        eps = get_delta_R(target_epsilon, self._dp_scale, q, ncomp=num_iter)\n        return eps\n\n    @staticmethod\n    def perturbation_function(\n            rng_suite, rng: PRNGState, values: Sequence[jnp.ndarray], perturbation_scale: float\n        ) -> Sequence[jnp.ndarray]:  # noqa: E121, E125\n        \"\"\" Perturbs given values using Gaussian noise.\n\n        `values` can be a list of array-like objects. Each value is independently\n        perturbed by adding noise sampled from a Gaussian distribution with a\n        standard deviation of `perturbation_scale`.\n\n        :param rng: Jax PRNGKey for perturbation randomness.\n        :param values: Iterable of array-like where each value will be perturbed.\n        :param perturbation_scale: The scale/standard deviation of the noise\n            distribution.\n        \"\"\"\n        def perturb_one(a: jnp.ndarray, site_rng: PRNGState) -> jnp.ndarray:\n            \"\"\" perturbs a single gradient site \"\"\"\n            noise = rng_suite.normal(site_rng, a.shape) * perturbation_scale\n            return a + noise\n\n        per_site_rngs = rng_suite.split(rng, len(values))\n        values = tuple(\n            perturb_one(grad, site_rng)\n            for grad, site_rng in zip(values, per_site_rngs)\n        )\n        return values\n", "meta": {"hexsha": "2cb9b8c9c90236d57c3fe649c3da497bf3ab66a2", "size": 20627, "ext": "py", "lang": "Python", "max_stars_repo_path": "d3p/svi.py", "max_stars_repo_name": "DPBayes/d3p", "max_stars_repo_head_hexsha": "af3ba4eb5243494bd5e223c60e81f32a8dca1eab", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-07T06:42:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T13:19:54.000Z", "max_issues_repo_path": "d3p/svi.py", "max_issues_repo_name": "DPBayes/d3p", "max_issues_repo_head_hexsha": "af3ba4eb5243494bd5e223c60e81f32a8dca1eab", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "d3p/svi.py", "max_forks_repo_name": "DPBayes/d3p", "max_forks_repo_head_hexsha": "af3ba4eb5243494bd5e223c60e81f32a8dca1eab", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-26T04:32:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T16:30:05.000Z", "avg_line_length": 42.18200409, "max_line_length": 119, "alphanum_fraction": 0.6955446745, "include": true, "reason": "import numpy,from numpy,import jax", "num_tokens": 4745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38121955219593834, "lm_q1q2_score": 0.1920988846778662}}
{"text": "##############################################\n# This code is based on samples from pytorch #\n##############################################\n# Writer: Kimin Lee \n\nfrom __future__ import print_function\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport data_loader\nimport numpy as np\nimport torchvision.utils as vutils\nimport models\nfrom torchvision import datasets, transforms\nfrom torch.autograd import Variable\n\nimport os\n\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"  # see issue #152\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"5\"\n\n# Training settings\nparser = argparse.ArgumentParser(description='Training code - joint confidence')\nparser.add_argument('--batch-size', type=int, default=128, help='input batch size for training')\nparser.add_argument('--epochs', type=int, default=100, help='number of epochs to train')\nparser.add_argument('--lr', type=float, default=0.0002, help='learning rate')\nparser.add_argument('--no-cuda', action='store_true', default=False, help='disables CUDA training')\nparser.add_argument('--seed', type=int, default=1, help='random seed')\nparser.add_argument('--log-interval', type=int, default=100,\n                    help='how many batches to wait before logging training status')\nparser.add_argument('--nz', type=int, default=100, help='size of the latent z vector')\nparser.add_argument('--ngf', type=int, default=180)\nparser.add_argument('--ndf', type=int, default=80)\nparser.add_argument('--beta1', type=float, default=0.5, help='beta1 for adam. default=0.5')\nparser.add_argument('--netG', default='', help=\"path to netG (to continue training)\")\nparser.add_argument('--netD', default='', help=\"path to netD (to continue training)\")\n\nparser.add_argument('--dataset', default='svhn', help='cifar10 | svhn')\nparser.add_argument('--dataroot', required=True, help='path to dataset')\nparser.add_argument('--imageSize', type=int, default=32, help='the height / width of the input image to network')\nparser.add_argument('--outf', default='.', help='folder to output images and model checkpoints')\nparser.add_argument('--wd', type=float, default=0.0, help='weight decay')\nparser.add_argument('--droprate', type=float, default=0.1, help='learning rate decay')\nparser.add_argument('--decreasing_lr', default='60', help='decreasing strategy')\nparser.add_argument('--num_classes', type=int, default=10, help='the # of classes')\nparser.add_argument('--beta', type=float, default=1, help='penalty parameter for KL term')\n\nargs = parser.parse_args()\n\nif args.dataset == 'cifar10':\n    args.beta = 0.1\n    args.batch_size = 64\n\nprint(args)\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\nprint(\"Random Seed: \", args.seed)\ntorch.manual_seed(args.seed)\n\nif args.cuda:\n    torch.cuda.manual_seed(args.seed)\n\nkwargs = {'num_workers': 1, 'pin_memory': True} if args.cuda else {}\n\nprint('load data: ', args.dataset)\nif args.dataset=='mnist':\n    transform = transforms.Compose([\n        transforms.Scale(32),\n        transforms.ToTensor(),\n        transforms.Lambda(lambda x: x.repeat(3, 1, 1)),\n        transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))\n    ])\n    train_loader = torch.utils.data.DataLoader(\n        datasets.MNIST('data', train=True, download=True, transform=transform),\n        batch_size=128, shuffle=True)\n    test_loader = None\nelse:\n    train_loader, test_loader = data_loader.getTargetDataSet(args.dataset, args.batch_size, args.imageSize, args.dataroot)\n\n\n\nprint('Load model')\nmodel = models.vgg13()\nprint(model)\n\nprint('load GAN')\n\n\nnz = int(args.nz)\nngf = int(args.ngf)\nndf = int(args.ndf)\nif args.dataset == 'mnist':\n    #nc = 1\n    nc=3\n    nb_label = 10\nelse:\n    nc = 3\n    nb_label = 10\n\nnetG = models.acnetG(nz, ngf, nc)\n\nif args.netG != '':\n    netG.load_state_dict(torch.load(args.netG))\nprint(netG)\n\nnetD = models.acnetD(ndf, nc, nb_label)\n\nif args.netD != '':\n    netD.load_state_dict(torch.load(args.netD))\nprint(netD)\n\n\nprint('Setup optimizer')\noptimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.wd)\n\ndecreasing_lr = list(map(int, args.decreasing_lr.split(',')))\n\nnum_labels = 10\n# os.environ[\"CUDA_LAUNCH_BLOCKING\"]=\"1\"\nbatchSize = 128\nimageSize = 32\ninput = torch.FloatTensor(batchSize, 3, imageSize, imageSize)\nnoise = torch.FloatTensor(batchSize, nz, 1, 1)\nfixed_noise = torch.FloatTensor(batchSize, nz, 1, 1).normal_(0, 1)\ns_label = torch.FloatTensor(batchSize)\nc_label = torch.LongTensor(batchSize)\n\nreal_label = 1\nfake_label = 0\n\n\ns_criterion = nn.BCELoss()\nc_criterion = nn.NLLLoss()\n\nif args.cuda:\n    netD.cuda()\n    netG.cuda()\n    s_criterion.cuda()\n    c_criterion.cuda()\n    input, s_label = input.cuda(), s_label.cuda()\n    c_label = c_label.cuda()\n    noise, fixed_noise = noise.cuda(), fixed_noise.cuda()\n\ninput = Variable(input)\ns_label = Variable(s_label)\nc_label = Variable(c_label)\nnoise = Variable(noise)\nfixed_noise = Variable(fixed_noise)\nfixed_noise_ = np.random.normal(0, 1, (batchSize, nz))\nrandom_label = np.random.randint(0, nb_label, batchSize)\nprint('fixed label:{}'.format(random_label))\nrandom_onehot = np.zeros((batchSize, nb_label))\nrandom_onehot[np.arange(batchSize), random_label] = 1\nfixed_noise_[np.arange(batchSize), :nb_label] = random_onehot[np.arange(batchSize)]\n\n\nfixed_noise_ = (torch.from_numpy(fixed_noise_))\nfixed_noise_ = fixed_noise_.resize_(batchSize, nz, 1, 1)\nfixed_noise.data.copy_(fixed_noise_)\n\n# setup optimizer\noptimizerD = optim.Adam(netD.parameters(), lr=args.lr, betas=(args.beta1, 0.999))\noptimizerG = optim.Adam(netG.parameters(), lr=args.lr, betas=(args.beta1, 0.999))\n\n\ndef train(epoch):\n    model.train()\n    # D_train_loss = 0\n    # G_train_loss = 3\n    trg = 0\n    trd = 0\n\n    global first\n    global fixed_noise\n    global fixed_label\n    global fixed_label_base\n    global one_hot_zero\n    for batch_idx, (img, label) in enumerate(train_loader):\n        ###########################\n        # (1) Update D network\n        ###########################\n        # train with real\n        if img.shape[0] != batchSize:\n            print('shape problem')\n            break\n        netD.zero_grad()\n        batch_size = img.size(0)\n        input.data.resize_(img.size()).copy_(img)\n        s_label.data.resize_(batch_size).fill_(real_label)\n        c_label.data.resize_(batch_size).copy_(label.squeeze())\n        s_output, c_output = netD(input)\n        s_errD_real = s_criterion(s_output, s_label)\n        c_errD_real = c_criterion(c_output, c_label)\n        errD_real = s_errD_real + 2.0*c_errD_real\n        errD_real.backward()\n        D_x = s_output.data.mean()\n\n        #correct, length = test(c_output, c_label)\n\n        # train with fake\n        noise.data.resize_(batch_size, nz, 1, 1)\n        noise.data.normal_(0, 1)\n\n        label = np.random.randint(0, nb_label, batch_size)\n        noise_ = np.random.normal(0, 1, (batch_size, nz))\n        label_onehot = np.zeros((batch_size, nb_label))\n        label_onehot[np.arange(batch_size), label] = 1\n        noise_[np.arange(batch_size), :nb_label] = label_onehot[np.arange(batch_size)]\n\n        noise_ = (torch.from_numpy(noise_))\n        noise_ = noise_.resize_(batch_size, nz, 1, 1)\n        noise.data.copy_(noise_)\n\n        c_label.data.resize_(batch_size).copy_(torch.from_numpy(label))\n\n        fake = netG(noise)\n        s_label.data.fill_(fake_label)\n        s_output, c_output = netD(fake.detach())\n        s_errD_fake = s_criterion(s_output, s_label)\n        c_errD_fake = c_criterion(c_output, c_label)\n        errD_fake = s_errD_fake + 2.0*c_errD_fake\n\n        errD_fake.backward()\n        D_G_z1 = s_output.data.mean()\n        errD = s_errD_real + s_errD_fake\n        optimizerD.step()\n        trd += 1\n        ###########################\n        # (2) Update G network\n        ###########################\n        netG.zero_grad()\n        s_label.data.fill_(real_label)  # fake labels are real for generator cost\n        s_output, c_output = netD(fake)\n        s_errG = s_criterion(s_output, s_label)\n        c_errG = c_criterion(c_output, c_label)\n\n        errG = s_errG + 2.0*c_errG\n        errG.backward()\n        D_G_z2 = s_output.data.mean()\n\n        if errG > 0:\n            optimizerG.step()\n            trg+=1\n        # minimize the true distribution\n        # KL_fake_output = F.log_softmax(model(G_result))\n        # errG_KL = F.kl_div(KL_fake_output, uniform_dist)*args.num_classes\n        # generator_loss = G_train_loss + args.beta*errG_KL # 12.0, .65, 0e-8\n        # generator_loss.backward()\n        #G_train_loss.backward()\n        #G_optimizer.step()\n        # G_losses.append(G_train_loss.item())\n        ###########################\n        # (3) Update classifier   #\n        ###########################\n        # cross entropy loss\n        \"\"\"    \n        optimizer.zero_grad()\n        x_ = Variable(x_)\n\n        output = F.log_softmax(model(x_))\n        loss = F.nll_loss(output.cuda(), label.type(torch.cuda.LongTensor).squeeze())\n\n        # KL divergence\n\n        ####\n        z_ = torch.randn((img.shape[0], 100)).view(-1, 100, 1, 1).cuda()\n        y_ = (torch.rand(img.shape[0], 1) * num_labels).type(torch.LongTensor).squeeze().cuda()\n        y_label_ = onehot[y_]\n        y_fill_ = fill[y_]\n\n        assert y_label_[0, y_[0]] == 1\n        assert y_label_.shape == (data.shape[0], 10, 1, 1)\n\n        assert y_fill_[0, y_[0], :, :].sum() == (img_size ) ** 2\n        assert y_fill_.sum() == (img_size ) ** 2 * data.shape[0]\n\n        G_result = G(z_, y_label_)\n        # !!!#D_result = D(G_result, y_fill_).squeeze()\n\n        ####\n        KL_fake_output = F.log_softmax(model(G_result))\n        KL_loss_fake = F.kl_div(KL_fake_output, uniform_dist) * args.num_classes\n\n        total_loss = loss + args.beta * KL_loss_fake\n        # total_loss = loss\n        total_loss.backward()\n        optimizer.step()\n        \"\"\"\n        if batch_idx % args.log_interval == 0:\n            print(\n                \"Epoch {} , Descriminator loss {:.6f} Generator loss {:.6f} traingenerator {:.6f} traindiscriminator {:.6f}\".format(\n                    epoch, errD, errG, trg, trd))\n            #print('Classification Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}, KL fake Loss: {:.6f}'.format(\n            #    epoch, batch_idx * len(data), len(train_loader.dataset),\n            #           100. * batch_idx / len(train_loader), loss.data.item(), KL_loss_fake.data.item()))\n\n            # print('Classification Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}, KL fake Loss: {:.6f}'.format(\n            #   epoch, batch_idx * len(data), len(train_loader.dataset),\n            #   100. * batch_idx / len(train_loader), loss.data.item(), KL_loss_fake.data.item()))\n            fake = netG(fixed_noise)\n            vutils.save_image(fake.data, '%s/SVHNcDCgan_samples_epoch_%03d.png' % (args.outf, epoch), normalize=True)\n\n\n\ndef test(epoch):\n    model.eval()\n    test_loss = 0\n    correct = 0\n    total = 0\n    for data, target in test_loader:\n        total += data.size(0)\n        if args.cuda:\n            data, target = data.cuda(), target.cuda()\n        # data, target = Variable(data, volatile=True), Variable(target)\n        output = F.log_softmax(model(data))\n        target = target.type(\n            torch.LongTensor)  # https://discuss.pytorch.org/t/runtimeerror-multi-target-not-supported-newbie/10216/4\n        if args.cuda:\n            output = output.cuda()\n            target = target.cuda()\n        target = torch.squeeze(target)\n\n        test_loss += F.nll_loss(output, target).data.item()\n        pred = output.data.max(1)[1]  # get the index of the max log-probability\n        correct += pred.eq(target.data).cpu().sum()\n\n    test_loss = test_loss\n    test_loss /= len(test_loader)  # loss function already averages over batch size\n    print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n        test_loss, correct, total,\n        100. * correct / total))\n\n\nfor epoch in range(1, args.epochs + 1):\n    train(epoch)\n#    test(epoch)\n    if epoch in decreasing_lr:\n        optimizerG.param_groups[0]['lr'] *= args.droprate\n        optimizerD.param_groups[0]['lr'] *= args.droprate\n        optimizer.param_groups[0]['lr'] *= args.droprate\n    if epoch % 20 == 0:\n        # do checkpointing\n        torch.save(netG.state_dict(), '%s/netG_epoch_%d.pth' % (args.outf, epoch))\n        torch.save(netD.state_dict(), '%s/netD_epoch_%d.pth' % (args.outf, epoch))\n        torch.save(model.state_dict(), '%s/model_epoch_%d.pth' % (args.outf, epoch))\n", "meta": {"hexsha": "087ffbfe4e98f6ce8d8765809011f570cb3929e5", "size": 12485, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/run_joint_confidence_condgan.py", "max_stars_repo_name": "williamsashbee/Confident_classifier", "max_stars_repo_head_hexsha": "cba3ef862b310afc3af6c4a62b524f032f45549e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/run_joint_confidence_condgan.py", "max_issues_repo_name": "williamsashbee/Confident_classifier", "max_issues_repo_head_hexsha": "cba3ef862b310afc3af6c4a62b524f032f45549e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/run_joint_confidence_condgan.py", "max_forks_repo_name": "williamsashbee/Confident_classifier", "max_forks_repo_head_hexsha": "cba3ef862b310afc3af6c4a62b524f032f45549e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9798270893, "max_line_length": 132, "alphanum_fraction": 0.6358029636, "include": true, "reason": "import numpy", "num_tokens": 3250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.19202966684547867}}
{"text": "import numpy as np\nimport math\nimport torch\nfrom typing import Any\nimport jax\nfrom jax import numpy as jnp\n\nfrom torch.utils import dlpack as tdlpack\nfrom jax import dlpack as jdlpack\n\nfrom flax import struct\n\nimport uuid\nimport pykeops\ntry:\n    pykeops.set_bin_folder(f'/scratch/wwhitney/pykeops_bin/{uuid.uuid4()}')\nexcept:\n    pykeops.set_bin_folder(f'/scratch/ww1114/pykeops_bin/{uuid.uuid4()}')\nfrom pykeops.torch import LazyTensor\n\nfrom environments import jax_specs\nimport utils\n\n\nJ_DTYPE = jnp.float32\nT_DTYPE = torch.float32\n\n\n@struct.dataclass\nclass DensityState:\n    observations: Any\n    weights: Any\n    device: Any\n    state_rescale: jnp.ndarray\n    action_rescale: jnp.ndarray\n    state_shift: jnp.ndarray\n    action_shift: jnp.ndarray\n    max_obs: int = 100000\n    tolerance: float = 0.95\n    reweight_dropped: bool = False\n    conserve_weight: bool = False\n    total: int = 0\n    next_slot: int = 0\n\n\n\ndef new(observation_spec, action_spec, max_obs=100000,\n        state_scale=1, action_scale=1, tolerance=0.95,\n        reweight_dropped=False, conserve_weight=False,\n        **kwargs):\n    flat_ospec = utils.flatten_observation_spec(observation_spec)\n    j_flat_ospec = jax_specs.convert_dm_spec(flat_ospec)\n    j_aspec = jax_specs.convert_dm_spec(action_spec)\n\n    state_rescale = state_scale * (j_flat_ospec.maximum - j_flat_ospec.minimum)\n    action_rescale = action_scale * (j_aspec.maximum - j_aspec.minimum)\n    state_shift = j_flat_ospec.minimum\n    action_shift = j_aspec.minimum\n\n    state_rescale = jax.device_put(state_rescale,\n                                   jax.local_devices(backend='cpu')[0])\n    action_rescale = jax.device_put(action_rescale,\n                                    jax.local_devices(backend='cpu')[0])\n    state_shift = jax.device_put(state_shift,\n                                 jax.local_devices(backend='cpu')[0])\n    action_shift = jax.device_put(action_shift,\n                                  jax.local_devices(backend='cpu')[0])\n\n    key_dim = j_flat_ospec.shape[0] + j_aspec.shape[0]\n\n    if torch.cuda.is_available():\n        device = torch.device('cuda')\n    else:\n        device = torch.device('cpu')\n\n    # pykeops.clean_pykeops()  # just in case old build files are still present\n\n    # initialize this to some reasonable size\n    # starting_size = 65536\n    starting_size = 4096\n    observations = torch.zeros((starting_size, key_dim))\n    observations = observations.type(T_DTYPE).to(device)\n    weights = torch.zeros((starting_size,))\n    weights = weights.type(T_DTYPE).to(device)\n\n    return DensityState(observations, weights, device,\n                        state_rescale, action_rescale,\n                        state_shift, action_shift,\n                        max_obs=max_obs, tolerance=tolerance,\n                        reweight_dropped=reweight_dropped,\n                        conserve_weight=conserve_weight)\n\n\n@jax.profiler.trace_function\ndef update_batch(density_state: DensityState, states, actions):\n    # increase the size of weights vector if needed\n    observations = density_state.observations\n    weights = density_state.weights\n    needed_size = density_state.next_slot + states.shape[0]\n    while ((needed_size >= observations.shape[0]) and\n           (observations.shape[0] < density_state.max_obs)):\n        observations, weights = _grow_observations(observations, weights,\n                                                   density_state.max_obs)\n    density_state = density_state.replace(observations=observations,\n                                          weights=weights)\n\n    # compute which states are new and which weights to update\n    keys = _make_key_batch(density_state, states, actions)\n    new_keys, weight_updates = _compute_updates(density_state, keys)\n\n    # update weights\n    if weight_updates.sum() > 0:\n        weights = density_state.weights + weight_updates.to(density_state.device)\n        density_state = density_state.replace(weights=weights)\n\n    # add all the new observations to the index\n    if len(new_keys) > 0:\n        density_state = _add_observations(density_state, new_keys)\n\n    return density_state\n\n\n@jax.profiler.trace_function\ndef _compute_updates(density_state: DensityState, keys):\n    if density_state.total <= 0:\n    # if True:\n        weight_update = torch.zeros_like(density_state.weights)\n        return keys, weight_update\n\n    obs = density_state.observations\n\n    x_o = LazyTensor( obs[:, None, :] )  # obs_size x 1 x dim\n    x_q = LazyTensor( keys[None, :, :] )  # 1 x batch_size x dim\n\n    D_oq = ((x_o - x_q)**2).sum(dim=2)  # obs_size x batch_size\n    K_oq = (-0.5 * D_oq).exp()\n\n    # want:\n    #   (1) the keys that have no close neighbors,\n    #   (2) the close neighbors & distances of the others\n\n    mins, inds = (-K_oq).Kmin_argKmin(16, dim=1)\n    sims_per_neighbor = -mins.cpu().numpy()\n    new_keys = []\n    weight_updates = torch.zeros((obs.shape[0],))\n\n    for (key, sims, ind) in zip(keys, sims_per_neighbor, inds):\n        similar_mask = sims > density_state.tolerance\n        n_similar_obs = similar_mask.sum()\n\n        if n_similar_obs >= 1:\n            similar_meta_indices = np.flatnonzero(similar_mask)\n            similar_indices = ind[similar_meta_indices]\n            weight_updates[similar_indices] += 1 / n_similar_obs\n        else:\n            new_keys.append(key)\n\n    if len(new_keys) > 0:\n        new_keys = torch.stack(new_keys)\n    return new_keys, weight_updates\n\n\n@jax.profiler.trace_function\ndef _add_observations(density_state: DensityState, keys):\n    bsize = keys.shape[0]\n    next_slot = density_state.next_slot\n    observations = density_state.observations\n    weights = density_state.weights\n\n    if density_state.total >= density_state.max_obs:\n        indices = torch.randint(low=0, high=int(density_state.max_obs - 1),\n                                size=(bsize,))\n    else:\n        indices = torch.arange(next_slot, next_slot + bsize)\n        indices = indices % density_state.max_obs\n    indices = indices.long()\n\n    if density_state.conserve_weight:\n        removed_weight = weights[indices].sum()\n        max_key = min(density_state.total, density_state.max_obs)\n        weights[:int(max_key)] += removed_weight / max_key\n\n    # update the observations\n    observations[indices] = keys\n    weights[indices] = 1\n    total = density_state.total + bsize\n    next_slot = (next_slot + bsize) % observations.shape[0]\n    return density_state.replace(observations=observations, weights=weights,\n                                 total=total, next_slot=next_slot)\n\n\n@jax.profiler.trace_function\ndef _grow_observations(observations, weights, max_size):\n    current_size = observations.shape[0]\n    print(f\"Growing KDE observations from {current_size}.\")\n\n    observations = torch.cat([observations, torch.zeros_like(observations)],\n                             dim=0)\n    weights = torch.cat([weights, torch.zeros_like(weights)],\n                        dim=0)\n    return observations, weights\n\n\n@jax.profiler.trace_function\ndef get_count(density_state: DensityState, state, action):\n    states = np.expand_dims(state, axis=0)\n    actions = np.expand_dims(action, axis=0)\n    return get_count_batch(density_state, states, actions)[0]\n\n\n@jax.profiler.trace_function\ndef get_count_batch(density_state: DensityState, states, actions):\n\n    with jax.profiler.TraceContext(\"check density size\"):\n        # prevent the index from segfaulting if queried when empty\n        if density_state.total <= 0:\n            return np.zeros((states.shape[0],))\n\n\n    with jax.profiler.TraceContext(\"access density obs + weights\"):\n        obs = density_state.observations\n        weights = density_state.weights\n\n\n    with jax.profiler.TraceContext(\"make keys\"):\n        keys = _make_key_batch(density_state, states, actions)\n\n\n    with jax.profiler.TraceContext(\"construct keops computation\"):\n        x_o = LazyTensor( obs[:, None, :] )  # obs_size x 1 x dim\n        x_q = LazyTensor( keys[None, :, :] )  # 1 x batch_size x dim\n        x_w = LazyTensor( weights[:, None], axis=0 )  # obs_size x 1\n\n        D_oq = ((x_o - x_q)**2).sum(dim=2)  # obs_size x batch_size\n        K_oq = (-0.5 * D_oq).exp()\n        C_oq = x_w * K_oq  # multiply the row for each obs by its weight\n\n\n    with jax.profiler.TraceContext(\"do keops computation\"):\n        counts = C_oq.sum(dim=0)  # batch_size\n\n    # reweight counts to account for dropped entries\n    if density_state.reweight_dropped:\n        counts = counts * (density_state.total / weights.sum())\n\n    with jax.profiler.TraceContext(\"convert types\"):\n        counts = utils.t_to_j(counts.reshape(-1))\n    return counts\n\n\n@jax.profiler.trace_function\n@jax.partial(jax.jit, backend='cpu')\ndef _make_key_jax(state_rescale, action_rescale, state_shift, action_shift,\n                  s, a):\n    flat_s = utils.flatten_observation(s)\n    flat_a = jnp.array(a).reshape((-1,))\n    normalized_s = (flat_s - state_shift) / state_rescale\n    normalized_a = (flat_a - action_shift) / action_rescale\n    return jnp.concatenate([normalized_s, normalized_a], axis=0).astype(J_DTYPE)\n_make_key_jax_batch = jax.vmap(_make_key_jax, in_axes=(None, None, None, None,\n                                                       0, 0))\n_make_key_jax_batch = jax.profiler.trace_function(_make_key_jax_batch,\n                                                  \"_make_key_jax_batch\")\n\n\n@jax.profiler.trace_function\ndef _make_key_batch(density_state: DensityState, s, a):\n    j_key = _make_key_jax_batch(density_state.state_rescale,\n                                density_state.action_rescale,\n                                density_state.state_shift,\n                                density_state.action_shift,\n                                s, a)\n    return utils.j_to_t(j_key).to(density_state.device)\n\n\nif __name__ == \"__main__\":\n    from dm_control import suite\n    from observation_domains import DOMAINS\n    import jax_specs\n    import point\n\n    env_name = 'point'\n    task_name = 'velocity'\n    env = suite.load(env_name, task_name)\n    ospec = DOMAINS[env_name][task_name]\n\n    aspec = env.action_spec()\n    j_aspec = jax_specs.convert_dm_spec(aspec)\n    j_ospec = jax_specs.convert_dm_spec(ospec)\n    density_state = new(ospec, aspec, state_scale=0.01, action_scale=1)\n\n    timestep = env.reset()\n    state = utils.flatten_observation(timestep.observation)\n    actions = utils.sample_uniform_actions(j_aspec, jax.random.PRNGKey(0), 1)\n    action = actions[0]\n\n\n    # ---------- sanity checking counts --------------------\n    timestep2 = env.step(jnp.ones(aspec.shape))\n    state2 = utils.flatten_observation(timestep2.observation)\n\n    print(\"S1 count:\", get_count(density_state, state, action))\n\n    print(\"S2 count:\", get_count(density_state, state2, action))\n    density_state_updated = update_batch(density_state,\n                                         jnp.expand_dims(state2, axis=0),\n                                         jnp.expand_dims(action, axis=0))\n    print(\"S2 count after self update:\", get_count(density_state_updated,\n                                                state2, action))\n\n    print(\"Batch of counts:\", get_count_batch(density_state_updated,\n                                              jnp.stack([state, state2]),\n                                              jnp.stack([action, action])))\n", "meta": {"hexsha": "d2c6f1affde73a9cb0067b3f73df6917b8829dd3", "size": 11323, "ext": "py", "lang": "Python", "max_stars_repo_path": "densities/keops_kernel_count.py", "max_stars_repo_name": "willwhitney/exploration-reimplementation", "max_stars_repo_head_hexsha": "5e2ca54119529b8bf9235bfbad92e38a6781fbd5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-24T15:59:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-24T17:03:30.000Z", "max_issues_repo_path": "densities/keops_kernel_count.py", "max_issues_repo_name": "willwhitney/exploration-reimplementation", "max_issues_repo_head_hexsha": "5e2ca54119529b8bf9235bfbad92e38a6781fbd5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "densities/keops_kernel_count.py", "max_forks_repo_name": "willwhitney/exploration-reimplementation", "max_forks_repo_head_hexsha": "5e2ca54119529b8bf9235bfbad92e38a6781fbd5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0605095541, "max_line_length": 81, "alphanum_fraction": 0.6550384174, "include": true, "reason": "import numpy,import jax,from jax", "num_tokens": 2678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.1920296618342123}}
{"text": "\"\"\"\nThe POVMEffect class and supporting functionality.\n\"\"\"\n#***************************************************************************************************\n# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).\n# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights\n# in this software.\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n# in compliance with the License.  You may obtain a copy of the License at\n# http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory.\n#***************************************************************************************************\n\nimport numpy as _np\n\nfrom pygsti.modelmembers import modelmember as _modelmember\nfrom pygsti.tools import optools as _ot\nfrom pygsti.baseobjs.opcalc import bulk_eval_compact_polynomials_complex as _bulk_eval_compact_polynomials_complex\n\n\nclass POVMEffect(_modelmember.ModelMember):\n    \"\"\"\n    TODO: update docstring\n    A parameterized state preparation OR POVM effect vector (operator).\n\n    This class is the  common base class for all specific\n    parameterizations of a POVM effect vector.\n\n    Parameters\n    ----------\n    rep : object\n        A representation object containing the core data for this spam vector.\n\n    evotype : Evotype\n        The evolution type of this operator, for matching with forward simulators.\n\n    Attributes\n    ----------\n    size : int\n        The number of independent elements in this POVM effect vector (when viewed as a dense array).\n    \"\"\"\n\n    def __init__(self, rep, evotype):\n        \"\"\" Initialize a new POVM effect Vector \"\"\"\n        super(POVMEffect, self).__init__(rep.state_space, evotype)\n        self._rep = rep\n\n    @property\n    def outcomes(self):\n        \"\"\"\n        The z-value outcomes corresponding to this effect POVM effect vector.\n\n        (Used in the context of a stabilizer-state simulation.)\n\n        Returns\n        -------\n        numpy.ndarray\n        \"\"\"\n        raise NotImplementedError(\"'outcomes' property is not implemented for %s objects\" % self.__class__.__name__)\n\n    @property\n    def dim(self):\n        \"\"\"\n        Return the dimension of this effect (when viewed as a dense array)\n\n        Returns\n        -------\n        int\n        \"\"\"\n        return self.state_space.dim\n\n    @property\n    def hilbert_schmidt_size(self):\n        \"\"\"\n        Return the number of independent elements in this effect as a dense Hilbert-Schmidt super-bra.\n\n        Returns\n        -------\n        int\n        \"\"\"\n        return self.state_space.dim\n\n    def set_dense(self, vec):\n        \"\"\"\n        Set the dense-vector value of this POVM effect vector.\n\n        Attempts to modify this POVM effect vector's parameters so that the raw\n        POVM effect vector becomes `vec`.  Will raise ValueError if this operation\n        is not possible.\n\n        Parameters\n        ----------\n        vec : array_like or POVMEffect\n            A numpy array representing a POVM effect vector, or a POVMEffect object.\n\n        Returns\n        -------\n        None\n        \"\"\"\n        raise ValueError(\"Cannot set the value of a %s directly!\" % self.__class__.__name__)\n\n    def set_time(self, t):\n        \"\"\"\n        Sets the current time for a time-dependent operator.\n\n        For time-independent operators (the default), this function does absolutely nothing.\n\n        Parameters\n        ----------\n        t : float\n            The current time.\n\n        Returns\n        -------\n        None\n        \"\"\"\n        pass\n\n    ## PUT term calc methods here if appropriate...\n\n    def frobeniusdist_squared(self, other_spam_vec, transform=None,\n                              inv_transform=None):\n        \"\"\"\n        Return the squared frobenius difference between this operation and `other_spam_vec`.\n\n        Optionally transforms this vector first using `transform` and\n        `inv_transform`.\n\n        Parameters\n        ----------\n        other_spam_vec : POVMEffect\n            The other spam vector\n\n        transform : numpy.ndarray, optional\n            Transformation matrix.\n\n        inv_transform : numpy.ndarray, optional\n            Inverse of `tranform`.\n\n        Returns\n        -------\n        float\n        \"\"\"\n        vec = self.to_dense()\n        if transform is None:\n            return _ot.frobeniusdist_squared(vec, other_spam_vec.to_dense())\n        else:\n            return _ot.frobeniusdist_squared(_np.dot(_np.transpose(transform),\n                                                     vec), other_spam_vec.to_dense())\n\n    def residuals(self, other_spam_vec, transform=None, inv_transform=None):\n        \"\"\"\n        Return a vector of residuals between this spam vector and `other_spam_vec`.\n\n        Optionally transforms this vector first using `transform` and\n        `inv_transform`.\n\n        Parameters\n        ----------\n        other_spam_vec : POVMEffect\n            The other spam vector\n\n        transform : numpy.ndarray, optional\n            Transformation matrix.\n\n        inv_transform : numpy.ndarray, optional\n            Inverse of `tranform`.\n\n        Returns\n        -------\n        float\n        \"\"\"\n        vec = self.to_dense()\n        if transform is None:\n            return _ot.residuals(vec, other_spam_vec.to_dense())\n        else:\n            return _ot.residuals(_np.dot(_np.transpose(transform),\n                                         vec), other_spam_vec.to_dense())\n\n    def transform_inplace(self, s):\n        \"\"\"\n        Update POVM effect (column) vector V => s^T * V\n\n        Note that this is equivalent to the *transpose* of effect vectors\n        being mapped as `E^T -> E^T * s`.\n\n        Generally, the transform function updates the *parameters* of\n        the POVM effect vector such that the resulting vector is altered as\n        described above.  If such an update cannot be done (because\n        the gate parameters do not allow for it), ValueError is raised.\n\n        Parameters\n        ----------\n        s : GaugeGroupElement\n            A gauge group element which specifies the \"s\" matrix\n            (and it's inverse) used in the above similarity transform.\n\n        typ : { 'prep', 'effect' }\n            Which type of POVM effect vector is being transformed (see above).\n\n        Returns\n        -------\n        None\n        \"\"\"\n        #Evec^T --> ( Evec^T * s )^T\n        Smx = s.transform_matrix\n        self.set_dense(_np.dot(_np.transpose(Smx), self.to_dense()))\n\n    @property\n    def num_params(self):\n        \"\"\"\n        Get the number of independent parameters which specify this POVM effect vector.\n\n        Returns\n        -------\n        int\n            the number of independent parameters.\n        \"\"\"\n        return 0  # no parameters\n\n    def to_vector(self):\n        \"\"\"\n        Get the POVM effect vector parameters as an array of values.\n\n        Returns\n        -------\n        numpy array\n            The parameters as a 1D array with length num_params().\n        \"\"\"\n        return _np.array([], 'd')  # no parameters\n\n    def from_vector(self, v, close=False, dirty_value=True):\n        \"\"\"\n        Initialize the POVM effect vector using a 1D array of parameters.\n\n        Parameters\n        ----------\n        v : numpy array\n            The 1D vector of POVM effect vector parameters.  Length\n            must == num_params()\n\n        close : bool, optional\n            Whether `v` is close to this POVM effect vector's current\n            set of parameters.  Under some circumstances, when this\n            is true this call can be completed more quickly.\n\n        dirty_value : bool, optional\n            The value to set this object's \"dirty flag\" to before exiting this\n            call.  This is passed as an argument so it can be updated *recursively*.\n            Leave this set to `True` unless you know what you're doing.\n\n        Returns\n        -------\n        None\n        \"\"\"\n        assert(len(v) == 0)  # should be no parameters, and nothing to do\n\n    def deriv_wrt_params(self, wrt_filter=None):\n        \"\"\"\n        The element-wise derivative this POVM effect vector.\n\n        Construct a matrix whose columns are the derivatives of the POVM effect vector\n        with respect to a single param.  Thus, each column is of length\n        dimension and there is one column per POVM effect vector parameter.\n\n        Parameters\n        ----------\n        wrt_filter : list or numpy.ndarray\n            List of parameter indices to take derivative with respect to.\n            (None means to use all the this operation's parameters.)\n\n        Returns\n        -------\n        numpy array\n            Array of derivatives, shape == (dimension, num_params)\n        \"\"\"\n        dtype = complex if self._evotype == 'statevec' else 'd'\n        derivMx = _np.zeros((self.dim, 0), dtype)\n        if wrt_filter is None:\n            return derivMx\n        else:\n            return _np.take(derivMx, wrt_filter, axis=1)\n\n    def has_nonzero_hessian(self):\n        \"\"\"\n        Whether this POVM effect vector has a non-zero Hessian with respect to its parameters.\n\n        Returns\n        -------\n        bool\n        \"\"\"\n        #Default: assume Hessian can be nonzero if there are any parameters\n        return self.num_params > 0\n\n    def hessian_wrt_params(self, wrt_filter1=None, wrt_filter2=None):\n        \"\"\"\n        Construct the Hessian of this POVM effect vector with respect to its parameters.\n\n        This function returns a tensor whose first axis corresponds to the\n        flattened operation matrix and whose 2nd and 3rd axes correspond to the\n        parameters that are differentiated with respect to.\n\n        Parameters\n        ----------\n        wrt_filter1 : list or numpy.ndarray\n            List of parameter indices to take 1st derivatives with respect to.\n            (None means to use all the this operation's parameters.)\n\n        wrt_filter2 : list or numpy.ndarray\n            List of parameter indices to take 2nd derivatives with respect to.\n            (None means to use all the this operation's parameters.)\n\n        Returns\n        -------\n        numpy array\n            Hessian with shape (dimension, num_params1, num_params2)\n        \"\"\"\n        if not self.has_nonzero_hessian():\n            return _np.zeros(self.size, self.num_params, self.num_params)\n\n        # FUTURE: create a finite differencing hessian method?\n        raise NotImplementedError(\"hessian_wrt_params(...) is not implemented for %s objects\" % self.__class__.__name__)\n\n    def taylor_order_terms(self, order, max_polynomial_vars=100, return_coeff_polys=False):\n        \"\"\"\n        Get the `order`-th order Taylor-expansion terms of this effect vector.\n\n        This function either constructs or returns a cached list of the terms at\n        the given order.  Each term is \"rank-1\", meaning that it is a state\n        preparation followed by or POVM effect preceded by actions on a\n        density matrix `rho` of the form:\n\n        `rho -> A rho B`\n\n        The coefficients of these terms are typically polynomials of the\n        State's parameters, where the polynomial's variable indices index the\n        *global* parameters of the State's parent (usually a :class:`Model`)\n        , not the State's local parameter array (i.e. that returned from\n        `to_vector`).\n\n        Parameters\n        ----------\n        order : int\n            The order of terms to get.\n\n        max_polynomial_vars : int, optional\n            maximum number of variables the created polynomials can have.\n\n        return_coeff_polys : bool\n            Whether a parallel list of locally-indexed (using variable indices\n            corresponding to *this* object's parameters rather than its parent's)\n            polynomial coefficients should be returned as well.\n\n        Returns\n        -------\n        terms : list\n            A list of :class:`RankOneTerm` objects.\n\n        coefficients : list\n            Only present when `return_coeff_polys == True`.\n            A list of *compact* polynomial objects, meaning that each element\n            is a `(vtape,ctape)` 2-tuple formed by concatenating together the\n            output of :method:`Polynomial.compact`.\n        \"\"\"\n        #NOTE: exact copy of State method - consolidate in FUTURE?\n        raise NotImplementedError(\"taylor_order_terms(...) not implemented for %s objects!\" %\n                                  self.__class__.__name__)\n\n    def highmagnitude_terms(self, min_term_mag, force_firstorder=True, max_taylor_order=3, max_polynomial_vars=100):\n        \"\"\"\n        Get terms with magnitude above `min_term_mag`.\n\n        Get the terms (from a Taylor expansion of this state vector) that have\n        magnitude above `min_term_mag` (the magnitude of a term is taken to\n        be the absolute value of its coefficient), considering only those\n        terms up to some maximum Taylor expansion order, `max_taylor_order`.\n\n        Note that this function also *sets* the magnitudes of the returned\n        terms (by calling `term.set_magnitude(...)`) based on the current\n        values of this state vector's parameters.  This is an essential step\n        to using these terms in pruned-path-integral calculations later on.\n\n        Parameters\n        ----------\n        min_term_mag : float\n            the threshold for term magnitudes: only terms with magnitudes above\n            this value are returned.\n\n        force_firstorder : bool, optional\n            if True, then always return all the first-order Taylor-series terms,\n            even if they have magnitudes smaller than `min_term_mag`.  This\n            behavior is needed for using GST with pruned-term calculations, as\n            we may begin with a guess model that has no error (all terms have\n            zero magnitude!) and still need to compute a meaningful jacobian at\n            this point.\n\n        max_taylor_order : int, optional\n            the maximum Taylor-order to consider when checking whether term-\n            magnitudes exceed `min_term_mag`.\n\n        max_polynomial_vars : int, optional\n            maximum number of variables the created polynomials can have.\n\n        Returns\n        -------\n        highmag_terms : list\n            A list of the high-magnitude terms that were found.  These\n            terms are *sorted* in descending order by term-magnitude.\n\n        first_order_indices : list\n            A list of the indices into `highmag_terms` that mark which\n            of these terms are first-order Taylor terms (useful when\n            we're forcing these terms to always be present).\n        \"\"\"\n        #NOTE: SAME as for LinearOperator class and State class -- TODO consolidate in FUTURE\n        #print(\"DB: state get_high_magnitude_terms\")\n        v = self.to_vector()\n        taylor_order = 0\n        terms = []; last_len = -1; first_order_magmax = 1.0\n        while len(terms) > last_len:  # while we keep adding something\n            if taylor_order > 1 and first_order_magmax**taylor_order < min_term_mag:\n                break  # there's no way any terms at this order reach min_term_mag - exit now!\n\n            MAX_CACHED_TERM_ORDER = 1\n            if taylor_order <= MAX_CACHED_TERM_ORDER:\n                #print(\"order \",taylor_order,\" : \",len(terms), \"terms\")\n                terms_at_order, cpolys = self.taylor_order_terms(taylor_order, max_polynomial_vars, True)\n                coeffs = _bulk_eval_compact_polynomials_complex(\n                    cpolys[0], cpolys[1], v, (len(terms_at_order),))  # an array of coeffs\n                mags = _np.abs(coeffs)\n                last_len = len(terms)\n                #OLD: terms_at_order = [ t.copy_with_magnitude(abs(coeff)) for coeff, t in zip(coeffs, terms_at_order) ]\n\n                if taylor_order == 1:\n                    #OLD: first_order_magmax = max([t.magnitude for t in terms_at_order])\n                    first_order_magmax = max(mags)\n\n                    if force_firstorder:\n                        terms.extend([(taylor_order, t.copy_with_magnitude(mag))\n                                      for coeff, mag, t in zip(coeffs, mags, terms_at_order)])\n                    else:\n                        for mag, t in zip(mags, terms_at_order):\n                            if mag >= min_term_mag:\n                                terms.append((taylor_order, t.copy_with_magnitude(mag)))\n                else:\n                    for mag, t in zip(mags, terms_at_order):\n                        if mag >= min_term_mag:\n                            terms.append((taylor_order, t.copy_with_magnitude(mag)))\n\n            else:\n                eff_min_term_mag = 0.0 if (taylor_order == 1 and force_firstorder) else min_term_mag\n                terms.extend([(taylor_order, t) for t in\n                              self.taylor_order_terms_above_mag(taylor_order,\n                                                                max_polynomial_vars, eff_min_term_mag)])\n\n            taylor_order += 1\n            if taylor_order > max_taylor_order: break\n\n        #Sort terms based on magnitude\n        sorted_terms = sorted(terms, key=lambda t: t[1].magnitude, reverse=True)\n        first_order_indices = [i for i, t in enumerate(sorted_terms) if t[0] == 1]\n        return [t[1] for t in sorted_terms], first_order_indices\n\n    def taylor_order_terms_above_mag(self, order, max_polynomial_vars, min_term_mag):\n        \"\"\"\n        Get the `order`-th order Taylor-expansion terms of this state vector that have magnitude above `min_term_mag`.\n\n        This function constructs the terms at the given order which have a magnitude (given by\n        the absolute value of their coefficient) that is greater than or equal to `min_term_mag`.\n        It calls :method:`taylor_order_terms` internally, so that all the terms at order `order`\n        are typically cached for future calls.\n\n        Parameters\n        ----------\n        order : int\n            The order of terms to get.\n\n        max_polynomial_vars : int, optional\n            maximum number of variables the created polynomials can have.\n\n        min_term_mag : float\n            the minimum term magnitude.\n\n        Returns\n        -------\n        list\n        \"\"\"\n        #NOTE: exact copy of State method - consolidate in FUTURE?\n        v = self.to_vector()\n        terms_at_order, cpolys = self.taylor_order_terms(order, max_polynomial_vars, True)\n        coeffs = _bulk_eval_compact_polynomials_complex(\n            cpolys[0], cpolys[1], v, (len(terms_at_order),))  # an array of coeffs\n        terms_at_order = [t.copy_with_magnitude(abs(coeff)) for coeff, t in zip(coeffs, terms_at_order)]\n        return [t for t in terms_at_order if t.magnitude >= min_term_mag]\n", "meta": {"hexsha": "3d09103d5ff0bfa05134ac261f2327c12ccc92a5", "size": 18791, "ext": "py", "lang": "Python", "max_stars_repo_path": "pygsti/modelmembers/povms/effect.py", "max_stars_repo_name": "pyGSTi-Developers/pyGSTi", "max_stars_repo_head_hexsha": "bfedc1de4d604f14b0f958615776fb80ddb59e33", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pygsti/modelmembers/povms/effect.py", "max_issues_repo_name": "pyGSTi-Developers/pyGSTi", "max_issues_repo_head_hexsha": "bfedc1de4d604f14b0f958615776fb80ddb59e33", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pygsti/modelmembers/povms/effect.py", "max_forks_repo_name": "pyGSTi-Developers/pyGSTi", "max_forks_repo_head_hexsha": "bfedc1de4d604f14b0f958615776fb80ddb59e33", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0384615385, "max_line_length": 120, "alphanum_fraction": 0.6068330584, "include": true, "reason": "import numpy", "num_tokens": 3932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.34158250614097546, "lm_q1q2_score": 0.19202965806613523}}
{"text": "# ======================================================================\n#         Imports\n# ======================================================================\nimport copy\nfrom collections import OrderedDict\nimport numpy as np\nfrom scipy import sparse\nfrom mpi4py import MPI\nfrom pyspline import Curve\nfrom pyspline.utils import openTecplot, closeTecplot, writeTecplot1D, writeTecplot3D\nfrom . import pyNetwork, pyBlock, geo_utils\nimport os\nimport warnings\n\n\nclass Error(Exception):\n    \"\"\"\n    Format the error message in a box to make it clear this\n    was a explicitly raised exception.\n    \"\"\"\n\n    def __init__(self, message):\n        msg = \"\\n+\" + \"-\" * 78 + \"+\" + \"\\n\" + \"| DVGeometry Error: \"\n        i = 19\n        for word in message.split():\n            if len(word) + i + 1 > 78:  # Finish line and start new one\n                msg += \" \" * (78 - i) + \"|\\n| \" + word + \" \"\n                i = 1 + len(word) + 1\n            else:\n                msg += word + \" \"\n                i += len(word) + 1\n        msg += \" \" * (78 - i) + \"|\\n\" + \"+\" + \"-\" * 78 + \"+\" + \"\\n\"\n        print(msg)\n        Exception.__init__(self)\n\n\nclass DVGeometry(object):\n    \"\"\"\n    A class for manipulating geometry.\n\n    The purpose of the DVGeometry class is to provide a mapping from\n    user-supplied design variables to an arbitrary set of discrete,\n    three-dimensional coordinates. These three-dimensional coordinates\n    can in general represent anything, but will typically be the\n    surface of an aerodynamic mesh, the nodes of a FE mesh or the\n    nodes of another geometric construct.\n\n    In a very general sense, DVGeometry performs two primary\n    functions:\n\n    1. Given a new set of design variables, update the\n       three-dimensional coordinates: :math:`X_{DV}\\\\rightarrow\n       X_{pt}` where :math:`X_{pt}` are the coordinates and :math:`X_{DV}`\n       are the user variables.\n\n    2. Determine the derivative of the coordinates with respect to the\n       design variables. That is the derivative :math:`\\\\frac{dX_{pt}}{dX_{DV}}`\n\n    DVGeometry uses the *Free-Form Deformation* approach for goemetry\n    manipulation. The basic idea is the coordinates are *embedded* in\n    a clear-flexible jelly-like block. Then by stretching moving and\n    'poking' the volume, the coordinates that are embedded inside move\n    along with overall deformation of the volume.\n\n    Parameters\n    ----------\n    fileName : str\n       filename of FFD file. This must be a ascii formatted plot3D file\n       in fortran ordering.\n\n    complex : bool\n        Make the entire object complex. This should **only** be used when\n        debugging the entire tool-chain with the complex step method.\n\n    child : bool\n        Flag to indicate that this object is a child of parent DVGeo object\n\n\n    Examples\n    --------\n    The general sequence of operations for using DVGeometry is as follows::\n      >>> from pygeo import *\n      >>> DVGeo = DVGeometry('FFD_file.fmt')\n      >>> # Embed a set of coordinates Xpt into the object\n      >>> DVGeo.addPointSet(Xpt, 'myPoints')\n      >>> # Associate a 'reference axis' for large-scale manipulation\n      >>> DVGeo.addRefAxis('wing_axis', axis_curve)\n      >>> # Define a global design variable function:\n      >>> def twist(val, geo):\n      >>>    geo.rot_z['wing_axis'].coef[:] = val[:]\n      >>> # Now add this as a global variable:\n      >>> DVGeo.addGlobalDV('wing_twist', 0.0, twist, lower=-10, upper=10)\n      >>> # Now add local (shape) variables\n      >>> DVGeo.addLocalDV('shape', lower=-0.5, upper=0.5, axis='y')\n      >>>\n    \"\"\"\n\n    def __init__(self, fileName, complex=False, child=False, faceFreeze=None, name=None, *args, **kwargs):\n\n        self.DV_listGlobal = OrderedDict()  # Global Design Variable List\n        self.DV_listLocal = OrderedDict()  # Local Design Variable List\n        self.DV_listSectionLocal = OrderedDict()  # Local Normal Design Variable List\n        self.DV_listSpanwiseLocal = OrderedDict()  # Local Normal Design Variable List\n\n        # Coefficient rotation matrix dict for Section Local variables\n        self.coefRotM = {}\n\n        # Name (used for ensuring design variables names are unique to pyoptsparse)\n        self.name = name\n\n        # Flags to determine if this DVGeometry is a parent or child\n        self.isChild = child\n        self.children = []\n        self.iChild = None\n        self.points = OrderedDict()\n        self.updated = {}\n        self.masks = None\n        self.finalized = False\n        self.complex = complex\n        if self.complex:\n            self.dtype = \"D\"\n        else:\n            self.dtype = \"d\"\n\n        # Load the FFD file in FFD mode. Also note that args and\n        # kwargs are passed through in case additional pyBlock options\n        # need to be set.\n        self.FFD = pyBlock(\"plot3d\", fileName=fileName, FFD=True, *args, **kwargs)\n        self.origFFDCoef = self.FFD.coef.copy()\n\n        # Jacobians:\n        self.ptSetNames = []\n        self.JT = {}\n        self.nPts = {}\n\n        # Derivatives of Xref and Coef provided by the parent to the\n        # children\n        self.dXrefdXdvg = None\n        self.dCoefdXdvg = None\n\n        self.dXrefdXdvl = None\n        self.dCoefdXdvl = None\n\n        # derivative counters for offsets\n        self.nDV_T = None  # total number of design variables\n        self.nDVG_T = None\n        self.nDVL_T = None\n        self.nDVSL_T = None\n        self.nDVSW_T = None\n        self.nDVG_count = 0  # number of global   (G)  variables\n        self.nDVL_count = 0  # number of local    (L)  variables\n        self.nDVSL_count = 0  # number of section  (SL) local variables\n        self.nDVSW_count = 0  # number of spanwise (SW) local variables\n\n        # The set of user supplied axis.\n        self.axis = OrderedDict()\n\n        # Generate coefMask regardless\n        coefMask = []\n        for iVol in range(self.FFD.nVol):\n            coefMask.append(\n                np.zeros((self.FFD.vols[iVol].nCtlu, self.FFD.vols[iVol].nCtlv, self.FFD.vols[iVol].nCtlw), dtype=bool)\n            )\n        # Now do the faceFreeze\n        if faceFreeze is not None:\n            for iVol in range(self.FFD.nVol):\n                key = \"%d\" % iVol\n                if key in faceFreeze.keys():\n                    if \"iLow\" in faceFreeze[key]:\n                        coefMask[iVol][0, :, :] = True\n                        coefMask[iVol][1, :, :] = True\n                    if \"iHigh\" in faceFreeze[key]:\n                        coefMask[iVol][-1, :, :] = True\n                        coefMask[iVol][-2, :, :] = True\n                    if \"jLow\" in faceFreeze[key]:\n                        coefMask[iVol][:, 0, :] = True\n                        coefMask[iVol][:, 1, :] = True\n                    if \"jHigh\" in faceFreeze[key]:\n                        coefMask[iVol][:, -1, :] = True\n                        coefMask[iVol][:, -2, :] = True\n                    if \"kLow\" in faceFreeze[key]:\n                        coefMask[iVol][:, :, 0] = True\n                        coefMask[iVol][:, :, 1] = True\n                    if \"kHigh\" in faceFreeze[key]:\n                        coefMask[iVol][:, :, -1] = True\n                        coefMask[iVol][:, :, -2] = True\n\n        # Finally we need to convert coefMask to the flattened global\n        # coef type:\n        tmp = np.zeros(len(self.FFD.coef), dtype=bool)\n        for iVol in range(self.FFD.nVol):\n            for i in range(coefMask[iVol].shape[0]):\n                for j in range(coefMask[iVol].shape[1]):\n                    for k in range(coefMask[iVol].shape[2]):\n                        ind = self.FFD.topo.lIndex[iVol][i, j, k]\n                        if coefMask[iVol][i, j, k]:\n                            tmp[ind] = True\n        self.masks = tmp\n\n    def addRefAxis(\n        self,\n        name,\n        curve=None,\n        xFraction=None,\n        yFraction=None,\n        zFraction=None,\n        volumes=None,\n        rotType=5,\n        axis=\"x\",\n        alignIndex=None,\n        rotAxisVar=None,\n        rot0ang=None,\n        rot0axis=[1, 0, 0],\n        xFractionOrder=2,\n        includeVols=[],\n        ignoreInd=[],\n        raySize=1.5,\n    ):\n        \"\"\"\n        This function is used to add a 'reference' axis to the\n        DVGeometry object.  Adding a reference axis is only required\n        when 'global' design variables are to be used, i.e. variables\n        like span, sweep, chord etc --- variables that affect many FFD\n        control points.\n\n        There are two different ways that a reference can be\n        specified:\n\n        #. The first is explicitly a pySpline curve object using the\n           keyword argument curve=<curve>.\n\n        #. The second is to specify the xFraction variable. There are a\n           few caveats with the use of this method. First, DVGeometry\n           will try to determine automatically the orientation of the FFD\n           volume. Then, a reference axis will consist of the same number of\n           control points as the number of span-wise sections in the FFD volume\n           and will be oriented in the streamwise (x-direction) according to the\n           xPercent keyword argument.\n\n        Parameters\n        ----------\n        name : str\n            Name of the reference axis. This name is used in the\n            user-supplied design variable functions to determine what\n            axis operations occur on.\n\n        curve : pySpline curve object\n            Supply exactly the desired reference axis\n\n        xFraction : float\n            Specify the stream-wise extent\n\n        volumes : list or array or integers\n            List of the volume indices, in 0-based ordering that this\n            reference axis should manipulate. If xFraction is\n            specified, the volumes argument must contain at most 1\n            volume. If the volumes is not given, then all volumes are\n            taken.\n\n        rotType : int\n            Integer in range 0->6 (inclusive) to determine the order\n            that the rotations are made.\n\n            0. Intrinsic rotation, rot_theta is rotation about axis\n            1. x-y-z\n            2. x-z-y\n            3. y-z-x\n            4. y-x-z\n            5. z-x-y  Default (x-streamwise y-up z-out wing)\n            6. z-y-x\n            7. z-x-y + rot_theta\n            8. z-x-y + rotation about section axis (to allow for winglet rotation)\n\n        axis: str\n            Axis along which to project points/control points onto the\n            ref axis. Default is `x` which will project rays.\n\n        alignIndex: str\n            FFD axis along which the reference axis will lie. Can be `i`, `j`,\n            or `k`. Only necessary when using xFraction.\n\n        rotAxisVar: str\n            If rotType == 8, then you must specify the name of the section local\n            variable which should be used to compute the orientation of the theta\n            rotation.\n\n        rot0ang: float\n            If rotType == 0, defines the offset angle of the (child) FFD with respect\n            to the main system of reference. This is necessary to use the scaling functions\n            `scale_x`, `scale_y`, and `scale_z` with rotType == 0. The axis of rotation is\n            defined by `rot0axis`.\n\n        rot0axis: list\n            If rotType == 0, defines the rotation axis for the rotation offset of the\n            FFD grid given by `rot0ang`. The variable has to be a list of 3 floats\n            defining the [x,y,z] components of the axis direction.\n            This is necessary to use the scaling functions `scale_x`, `scale_y`,\n            and `scale_z` with rotType == 0.\n\n        xFractionOrder : int  (NOT USED?)\n            Order of spline used for refaxis curve.\n\n        includeVols : list\n            List of additional volumes to add to reference axis after the\n            automatic generation of the ref axis based on the volumes list using\n            xFraction.\n\n        ignoreInd : list\n            List of indices that should be ignored from the volumes that were\n            added to this reference axis. This can be handy if you have a single\n            volume but you want to link different sets of indices to different\n            reference axes.\n\n        raySize : float\n            Used in projection to find attachment point on reference axis.\n            See full description in pyNetwork.projectRays function doc string.\n            In most cases the default value is sufficient. In the case of highly\n            swept wings its sometimes necessary to increase this value.\n\n        Notes\n        -----\n        One of curve or xFraction must be specified.\n\n        Examples\n        --------\n        >>> # Simple wing with single volume FFD, reference axis at 1/4 chord:\n        >>> DVGeo.addRefAxis('wing', xFraction=0.25)\n        >>> # Multiblock FFD, wing is volume 6.\n        >>> DVGeo.addRefAxis('wing', xFraction=0.25, volumes=[6])\n        >>> # Multiblock FFD, multiple volumes attached refAxis\n        >>> DVGeo.addRefAxis('wing', myCurve, volumes=[2,3,4])\n\n        Returns\n        -------\n        nAxis : int\n            The number of control points on the reference axis.\n        \"\"\"\n\n        # We don't do any of the final processing here; we simply\n        # record the information the user has supplied into a\n        # dictionary structure.\n        if axis is None:\n            pass\n        elif axis.lower() == \"x\":\n            axis = np.array([1, 0, 0], \"d\")\n        elif axis.lower() == \"y\":\n            axis = np.array([0, 1, 0], \"d\")\n        elif axis.lower() == \"z\":\n            axis = np.array([0, 0, 1], \"d\")\n\n        if curve is not None:\n            # Explicit curve has been supplied:\n            if self.FFD.symmPlane is None:\n                if volumes is None:\n                    volumes = np.arange(self.FFD.nVol)\n                self.axis[name] = {\n                    \"curve\": curve,\n                    \"volumes\": volumes,\n                    \"rotType\": rotType,\n                    \"axis\": axis,\n                    \"rot0ang\": rot0ang,\n                    \"rot0axis\": rot0axis,\n                }\n\n            else:\n                # get the direction of the symmetry plane\n                if self.FFD.symmPlane.lower() == \"x\":\n                    index = 0\n                elif self.FFD.symmPlane.lower() == \"y\":\n                    index = 1\n                elif self.FFD.symmPlane.lower() == \"z\":\n                    index = 2\n\n                # mirror the axis and attach the mirrored vols\n                if volumes is None:\n                    volumes = np.arange(self.FFD.nVol / 2)\n\n                volumesSymm = []\n                for volume in volumes:\n                    volumesSymm.append(volume + self.FFD.nVol / 2)\n\n                curveSymm = copy.deepcopy(curve)\n                curveSymm.reverse()\n                for coef in curveSymm.coef:\n                    curveSymm.coef[:, index] = -curveSymm.coef[:, index]\n                self.axis[name] = {\n                    \"curve\": curve,\n                    \"volumes\": volumes,\n                    \"rotType\": rotType,\n                    \"axis\": axis,\n                    \"rot0ang\": rot0ang,\n                    \"rot0axis\": rot0axis,\n                }\n                self.axis[name + \"Symm\"] = {\n                    \"curve\": curveSymm,\n                    \"volumes\": volumesSymm,\n                    \"rotType\": rotType,\n                    \"axis\": axis,\n                    \"rot0ang\": rot0ang,\n                    \"rot0axis\": rot0axis,\n                }\n            nAxis = len(curve.coef)\n        elif xFraction or yFraction or zFraction:\n            # Some assumptions\n            #   - FFD should be a close approximation of geometry surface so that\n            #       xFraction roughly corresponds to airfoil LE, TE, or 1/4 chord\n            #   - User provides 'i', 'j' or 'k' to specify which block direction\n            #       the reference axis should project\n            #   - if no volumes are listed, it is assumed that all volumes are\n            #       included\n            #   - 'x' is streamwise direction\n\n            # Default to \"mean\" ref axis location along non-user specified direction\n\n            # This is the block direction along which the reference axis will lie\n            # alignIndex = 'k'\n            if alignIndex is None:\n                raise Error(\"Must specify alignIndex to use xFraction.\")\n\n            # Get index direction along which refaxis will be aligned\n            if alignIndex.lower() == \"i\":\n                alignIndex = 0\n                faceCol = 2\n            elif alignIndex.lower() == \"j\":\n                alignIndex = 1\n                faceCol = 4\n            elif alignIndex.lower() == \"k\":\n                alignIndex = 2\n                faceCol = 0\n\n            if volumes is None:\n                volumes = range(self.FFD.nVol)\n\n            # Reorder the volumes in sequential order and check if orientation is correct\n            v = list(volumes)\n            nVol = len(v)\n            volOrd = [v.pop(0)]\n            faceLink = self.FFD.topo.faceLink\n            for iter in range(nVol):\n                for vInd, i in enumerate(v):\n                    for pInd, j in enumerate(volOrd):\n                        if faceLink[i, faceCol] == faceLink[j, faceCol + 1]:\n                            volOrd.insert(pInd + 1, v.pop(vInd))\n                            break\n                        elif faceLink[i, faceCol + 1] == faceLink[j, faceCol]:\n                            volOrd.insert(pInd, v.pop(vInd))\n                            break\n\n            if len(volOrd) < nVol:\n                raise Error(\n                    \"The volumes are not ordered with matching faces\" \" in the direction of the reference axis.\"\n                )\n\n            # Count total number of sections and check if volumes are aligned\n            # face to face along refaxis direction\n            lIndex = self.FFD.topo.lIndex\n            nSections = []\n            for i in range(len(volOrd)):\n                if i == 0:\n                    nSections.append(lIndex[volOrd[i]].shape[alignIndex])\n                else:\n                    nSections.append(lIndex[volOrd[i]].shape[alignIndex] - 1)\n\n            refaxisNodes = np.zeros((sum(nSections), 3))\n\n            # Loop through sections and compute node location\n            place = 0\n            for j, vol in enumerate(volOrd):\n                # sectionArr: indices of FFD points grouped by section\n                sectionArr = np.rollaxis(lIndex[vol], alignIndex, 0)\n                skip = 0\n                if j > 0:\n                    skip = 1\n                for i in range(nSections[j]):\n                    # getting all the section control points coordinates\n                    pts_tens = self.FFD.coef[sectionArr[i + skip, :, :], :]  # shape=(xAxisNodes,yAxisnodes,3)\n\n                    # reshaping into vector to allow rotation (if needed) - leveraging on pts_tens.shape[2]=3 (FFD cp coordinates)\n                    pts_vec = np.copy(pts_tens.reshape(-1, 3))  # new shape=(xAxisNodes*yAxisnodes,3)\n\n                    if rot0ang:\n                        # rotating the FFD to be aligned with main axes\n                        for ct_ in range(np.shape(pts_vec)[0]):\n                            # here we loop over the pts_vec, rotate them and insert them inplace in pts_vec again\n                            p_ = np.copy(pts_vec[ct_, :])\n                            p_rot = geo_utils.rotVbyW(p_, rot0axis, np.pi / 180 * (rot0ang))\n                            pts_vec[ct_, :] = p_rot\n\n                    # Temporary ref axis node coordinates - aligned with main system of reference\n                    if xFraction:\n                        # getting the bounds of the FFD section\n                        x_min = np.min(pts_vec[:, 0])\n                        x_max = np.max(pts_vec[:, 0])\n                        x_node = xFraction * (x_max - x_min) + x_min  # chordwise\n                    else:\n                        x_node = np.mean(pts_vec[:, 0])\n\n                    if yFraction:\n                        y_min = np.min(pts_vec[:, 1])\n                        y_max = np.max(pts_vec[:, 1])\n                        y_node = y_max - yFraction * (y_max - y_min)  # top-bottom\n                    else:\n                        y_node = np.mean(pts_vec[:, 1])\n\n                    if zFraction:\n                        z_min = np.min(pts_vec[:, 2])\n                        z_max = np.max(pts_vec[:, 2])\n                        z_node = z_max - zFraction * (z_max - z_min)  # top-bottom\n                    else:\n                        z_node = np.mean(pts_vec[:, 2])\n\n                    # This is the FFD ref axis node - if the block has not been rotated\n                    nd = [x_node, y_node, z_node]\n                    nd_final = np.copy(nd)\n\n                    if rot0ang:\n                        # rotating the non-aligned FFDs back in position\n                        nd_final[:] = geo_utils.rotVbyW(nd, rot0axis, np.pi / 180 * (-rot0ang))\n\n                    # insert the final coordinates in the var to be passed to pySpline:\n                    refaxisNodes[place + i, 0] = nd_final[0]\n                    refaxisNodes[place + i, 1] = nd_final[1]\n                    refaxisNodes[place + i, 2] = nd_final[2]\n\n                place += i + 1\n\n            # Add additional volumes\n            for iVol in includeVols:\n                if iVol not in volumes:\n                    volumes.append(iVol)\n\n            # Generate reference axis pySpline curve\n            curve = Curve(X=refaxisNodes, k=2)\n            nAxis = len(curve.coef)\n            self.axis[name] = {\n                \"curve\": curve,\n                \"volumes\": volumes,\n                \"rotType\": rotType,\n                \"axis\": axis,\n                \"rot0ang\": rot0ang,\n                \"rot0axis\": rot0axis,\n                \"rotAxisVar\": rotAxisVar,\n            }\n        else:\n            raise Error(\"One of 'curve' or 'xFraction' must be \" \"specified for a call to addRefAxis\")\n\n        # Specify indices to be ignored\n        self.axis[name][\"ignoreInd\"] = ignoreInd\n\n        # Add the raySize multiplication factor for this axis\n        self.axis[name][\"raySize\"] = raySize\n\n        return nAxis\n\n    def addPointSet(self, points, ptName, origConfig=True, **kwargs):\n        \"\"\"\n        Add a set of coordinates to DVGeometry\n\n        The is the main way that geometry, in the form of a coordinate\n        list is given to DVGeoemtry to be manipulated.\n\n        Parameters\n        ----------\n        points : array, size (N,3)\n            The coordinates to embed. These cordinates *should* all\n            project into the interior of the FFD volume.\n        ptName : str\n            A user supplied name to associate with the set of\n            coordinates. This name will need to be provided when\n            updating the coordinates or when getting the derivatives\n            of the coordinates.\n        origConfig : bool\n            Flag determine if the coordinates are projected into the\n            undeformed or deformed configuration. This should almost\n            always be True except in circumstances when the user knows\n            exactly what they are doing.\"\"\"\n\n        # save this name so that we can zero out the jacobians properly\n        self.ptSetNames.append(ptName)\n        self.zeroJacobians([ptName])\n        self.nPts[ptName] = None\n\n        points = np.array(points).real.astype(\"d\")\n        self.points[ptName] = points\n\n        # Ensure we project into the undeformed geometry\n        if origConfig:\n            tmpCoef = self.FFD.coef.copy()\n            self.FFD.coef = self.origFFDCoef\n            self.FFD._updateVolumeCoef()\n\n        # Project the last set of points into the volume\n        if self.isChild:\n            self.FFD.attachPoints(self.points[ptName], ptName, interiorOnly=True, **kwargs)\n        else:\n            self.FFD.attachPoints(self.points[ptName], ptName, interiorOnly=False)\n\n        if origConfig:\n            self.FFD.coef = tmpCoef\n            self.FFD._updateVolumeCoef()\n\n        # Now embed into the children:\n        for child in self.children:\n            child.addPointSet(points, ptName, origConfig, **kwargs)\n\n        self.FFD.calcdPtdCoef(ptName)\n        self.updated[ptName] = False\n\n    def addChild(self, childDVGeo):\n        \"\"\"Embed a child FFD into this object.\n\n        An FFD child is a 'sub' FFD that is fully contained within\n        another, parent FFD. A child FFD is also an instance of\n        DVGeometry which may have its own global and/or local design\n        variables. Coordinates do **not** need to be added to the\n        children. The parent object will take care of that in a call\n        to addPointSet().\n\n        See https://github.com/mdolab/pygeo/issues/7 for a description of an\n        issue with Child FFDs that you should be aware of if you are combining\n        shape changes of a parent FFD with rotation or shape changes of a child FFD.\n\n        Parameters\n        ----------\n        childDVGeo : instance of DVGeometry\n            DVGeo object to use as a sub-FFD\n        \"\"\"\n\n        # Make sure the DVGeo being added is flaged as a child:\n        if childDVGeo.isChild is False:\n            raise Error(\"Trying to add a child FFD that has NOT been \" \"created as a child. This operation is illegal.\")\n\n        # Extract the coef from the child FFD and ref axis and embed\n        # them into the parent and compute their derivatives\n        iChild = len(self.children)\n        childDVGeo.iChild = iChild\n\n        self.FFD.attachPoints(childDVGeo.FFD.coef, \"child%d_coef\" % (iChild))\n        self.FFD.calcdPtdCoef(\"child%d_coef\" % (iChild))\n\n        # We must finalize the Child here since we need the ref axis\n        # coefficients\n        childDVGeo._finalizeAxis()\n        self.FFD.attachPoints(childDVGeo.refAxis.coef, \"child%d_axis\" % (iChild))\n        self.FFD.calcdPtdCoef(\"child%d_axis\" % (iChild))\n\n        # Add the child to the parent and return\n        self.children.append(childDVGeo)\n\n    def addGlobalDV(self, dvName, value, func, lower=None, upper=None, scale=1.0, config=None):\n        \"\"\"\n        Add a global design variable to the DVGeometry object. This\n        type of design variable acts on one or more reference axis.\n\n        Parameters\n        ----------\n        dvName : str\n            A unique name to be given to this design variable group\n\n        value : float, or iterable list of floats\n            The starting value(s) for the design variable. This\n            parameter may be a single variable or a numpy array\n            (or list) if the function requires more than one\n            variable. The number of variables is determined by the\n            rank (and if rank ==1, the length) of this parameter.\n\n        lower : float, or iterable list of floats\n            The lower bound(s) for the variable(s). A single variable\n            is permissable even if an array is given for value. However,\n            if an array is given for 'lower', it must be the same length\n            as 'value'\n\n        func : python function\n            The python function handle that will be used to apply the\n            design variable\n\n        upper : float, or iterable list of floats\n            The upper bound(s) for the variable(s). Same restrictions as\n            'lower'\n\n        scale : float, or iterable list of floats\n            The scaling of the variables. A good approximate scale to\n            start with is approximately 1.0/(upper-lower). This gives\n            variables that are of order ~1.0.\n\n        config : str or list\n            Define what configurations this design variable will be applied to\n            Use a string for a single configuration or a list for multiple\n            configurations. The default value of None implies that the design\n            variable appies to *ALL* configurations.\n        \"\"\"\n        # if the parent DVGeometry object has a name attribute, prepend it\n        if self.name is not None:\n            dvName = self.name + \"_\" + dvName\n\n        if type(config) == str:\n            config = [config]\n        self.DV_listGlobal[dvName] = geoDVGlobal(dvName, value, lower, upper, scale, func, config)\n\n    def addGeoDVGlobal(self, *args, **kwargs):\n        warnings.warn(\"addGeoDVGlobal will be deprecated, use addGlobalDV instead\")\n        self.addGlobalDV(*args, **kwargs)\n\n    def addLocalDV(\n        self, dvName, lower=None, upper=None, scale=1.0, axis=\"y\", volList=None, pointSelect=None, config=None\n    ):\n        \"\"\"\n        Add one or more local design variables ot the DVGeometry\n        object. Local variables are used for small shape modifications.\n\n        Parameters\n        ----------\n        dvName : str\n            A unique name to be given to this design variable group\n\n        lower : float\n            The lower bound for the variable(s). This will be applied to\n            all shape variables\n\n        upper : float\n            The upper bound for the variable(s). This will be applied to\n            all shape variables\n\n        scale : flot\n            The scaling of the variables. A good approximate scale to\n            start with is approximately 1.0/(upper-lower). This gives\n            variables that are of order ~1.0.\n\n        axis : str. Default is `y`\n            The coordinate directions to move. Permissible values are `x`,\n            `y` and `z`. If more than one direction is required, use multiple\n            calls to addLocalDV with different axis values.\n\n        volList : list\n            Use the control points on the volume indicies given in volList.\n            You should use pointSelect = None, otherwise this will not work.\n\n        pointSelect : pointSelect object. Default is None Use a\n            pointSelect object to select a subset of the total number\n            of control points. See the documentation for the\n            pointSelect class in geo_utils. Using pointSelect discards everything in\n            volList.\n\n        config : str or list\n            Define what configurations this design variable will be applied to\n            Use a string for a single configuration or a list for multiple\n            configurations. The default value of None implies that the design\n            variable appies to *ALL* configurations.\n\n        Returns\n        -------\n        N : int\n            The number of design variables added.\n\n        Examples\n        --------\n        >>> # Add all variables in FFD as local shape variables\n        >>> # moving in the y direction, within +/- 1.0 units\n        >>> DVGeo.addLocalDV('shape_vars', lower=-1.0, upper= 1.0, axis='y')\n        >>> # As above, but moving in the x and y directions.\n        >>> nVar = DVGeo.addLocalDV('shape_vars_x', lower=-1.0, upper= 1.0, axis='x')\n        >>> nVar = DVGeo.addLocalDV('shape_vars_y', lower=-1.0, upper= 1.0, axis='y')\n        >>> # Create a point select to use: (box from (0,0,0) to (10,0,10) with\n        >>> # any point projecting into the point along 'y' axis will be selected.\n        >>> PS = geo_utils.PointSelect(type = 'y', pt1=[0,0,0], pt2=[10, 0, 10])\n        >>> nVar = DVGeo.addLocalDV('shape_vars', lower=-1.0, upper=1.0, pointSelect=PS)\n        \"\"\"\n        if self.name is not None:\n            dvName = self.name + \"_\" + dvName\n\n        if type(config) == str:\n            config = [config]\n\n        if pointSelect is not None:\n            if pointSelect.type != \"ijkBounds\":\n                pts, ind = pointSelect.getPoints(self.FFD.coef)\n            else:\n                pts, ind = pointSelect.getPoints_ijk(self)\n        elif volList is not None:\n            if self.FFD.symmPlane is not None:\n                volListTmp = []\n                for vol in volList:\n                    volListTmp.append(vol)\n                for vol in volList:\n                    volListTmp.append(vol + self.FFD.nVol / 2)\n                volList = volListTmp\n\n            volList = np.atleast_1d(volList).astype(\"int\")\n            ind = []\n            for iVol in volList:\n                ind.extend(self.FFD.topo.lIndex[iVol].flatten())\n            ind = geo_utils.unique(ind)\n        else:\n            # Just take'em all\n            ind = np.arange(len(self.FFD.coef))\n\n        self.DV_listLocal[dvName] = geoDVLocal(dvName, lower, upper, scale, axis, ind, self.masks, config)\n\n        return self.DV_listLocal[dvName].nVal\n\n    def addGeoDVLocal(self, *args, **kwargs):\n        warnings.warn(\"addGeoDVLocal will be deprecated, use addLocalDV instead\")\n        self.addLocalDV(*args, **kwargs)\n\n    def addSpanwiseLocalDV(\n        self,\n        dvName,\n        spanIndex,\n        axis=\"y\",\n        lower=None,\n        upper=None,\n        scale=1.0,\n        pointSelect=None,\n        volList=None,\n        config=None,\n    ):\n        \"\"\"\n        Add one or more spanwise local design variables to the DVGeometry\n        object. Spanwise local variables are alternative form of local shape\n        variables used to apply equal DV changes in a chosen direction.\n        Some scenarios were this could be useful are:\n\n        1.  2D airfoil shape optimization. Because adflow works with 3D meshes,\n            2D problems are represented my a mesh a single cell wide. Therefor,\n            to change the 2D representation of the airfoil both sides of the\n            mesh must be moved equally. This can be done with the addition of\n            linear constraints on a set of local shape variables, however this\n            approach requires more DVs than necessary (which complicates DV\n            sweeps) and the constaints are only enforced to a tolerance. Using\n            spanwise local design variables insures the airfoil is always\n            correctly represented in the 3D mesh using the correct amount of\n            design variables.\n\n        2.  3D wing optimization with constant airfoil shape. If the initial\n            wing geometry has a constant airfoil shape  and constant chord, then\n            spanwise local dvs can be used to change the airfoil shape of the\n            wing while still keeping it constant along the span of the wing.\n\n        Parameters\n        ----------\n        dvName : str\n            A unique name to be given to this design variable group\n\n        spanIndex : str, ('i', 'j', 'k')\n            the axis of the FFD along which the DVs are constant\n            all shape variables\n\n        axis : str. Default is `y`\n            The coordinate directions to move. Permissible values are `x`,\n            `y` and `z`. If more than one direction is required, use multiple\n            calls to addLocalDV with different axis values.\n\n        lower : float\n            The lower bound for the variable(s). This will be applied to\n            all shape variables\n\n        upper : float\n            The upper bound for the variable(s). This will be applied to\n            all shape variables\n\n        scale : flot\n            The scaling of the variables. A good approximate scale to\n            start with is approximately 1.0/(upper-lower). This gives\n            variables that are of order ~1.0.\n\n        pointSelect : pointSelect object. Default is None Use a\n            pointSelect object to select a subset of the total number\n            of control points. See the documentation for the\n            pointSelect class in geo_utils. Using pointSelect discards everything in\n            volList.\n\n        volList : list\n            Use the control points on the volume indicies given in volList.\n            You should use pointSelect = None, otherwise this will not work.\n\n        config : str or list\n            Define what configurations this design variable will be applied to\n            Use a string for a single configuration or a list for multiple\n            configurations. The default value of None implies that the design\n            variable applies to *ALL* configurations.\n\n        Returns\n        -------\n        N : int\n            The number of design variables added.\n\n        Examples\n        --------\n        >>> # Add all spanwise local variables\n        >>> # moving in the y direction, within +/- 0.5 units\n        >>> DVGeo.addSpanwiseLocalDV(\"shape\", 'k', lower=-0.5, upper=0.5, axis=\"z\", scale=1.0)\n        \"\"\"\n        if type(config) == str:\n            config = [config]\n\n        if pointSelect is not None:\n            if pointSelect.type != \"ijkBounds\":\n                pts, ind = pointSelect.getPoints(self.FFD.coef)\n            else:\n                pts, ind = pointSelect.getPoints_ijk(self)\n        elif volList is not None:\n            if self.FFD.symmPlane is not None:\n                volListTmp = []\n                for vol in volList:\n                    volListTmp.append(vol)\n                for vol in volList:\n                    volListTmp.append(vol + self.FFD.nVol / 2)\n                volList = volListTmp\n\n            volList = np.atleast_1d(volList).astype(\"int\")\n            ind = []\n            for iVol in volList:\n                ind.extend(self.FFD.topo.lIndex[iVol].flatten())\n            ind = geo_utils.unique(ind)\n        else:\n            # Just take'em all\n            volList = np.arange(self.FFD.nVol)\n            ind = np.arange(len(self.FFD.coef))\n\n        # secLink = np.zeros(self.FFD.coef.shape[0], dtype=int)\n        # secTransform = [np.eye(3)]\n\n        if type(spanIndex) is str:\n            spanIndex = [spanIndex] * len(volList)\n        elif type(spanIndex) is list:\n            if len(spanIndex) != len(volList):\n                raise Error(\"If a list is given for spanIndex, the length must be\" \" equal to the length of volList.\")\n\n        ijk_2_idx = {\"i\": 0, \"j\": 1, \"k\": 2}\n\n        volDVMap = []\n        for ivol in volList:\n\n            spanIdx = ijk_2_idx[spanIndex[ivol]]\n            lIndex = self.FFD.topo.lIndex[ivol]\n\n            topo_shape = lIndex.shape\n\n            # remove the span axis since all dv in that axis are linked\n            n_linked_coef = topo_shape[spanIdx]\n            dvs_shape = np.delete(topo_shape, spanIdx)\n\n            # get total number of dvs\n            n_dvs = np.product(dvs_shape)\n\n            # make a map from dvs to the ind that are controlled by that dv.\n            # (phrased another way) map from dv to all ind in the same span size position\n            dv_to_coef_ind = np.zeros((n_dvs, n_linked_coef), dtype=\"intc\")\n\n            # slice lIndex to get the indices of the coeffs that are in the same\n            # spanwise position\n            dv_idx = 0\n            for i in range(dvs_shape[0]):\n                for j in range(dvs_shape[1]):\n                    # no need to use fancy axis manipulation, since it doesn't need\n                    # to be fast and if statements are expressive\n                    if spanIndex[ivol] == \"i\":\n                        coef_ind = lIndex[:, i, j]\n                    elif spanIndex[ivol] == \"j\":\n                        coef_ind = lIndex[i, :, j]\n                    elif spanIndex[ivol] == \"k\":\n                        coef_ind = lIndex[i, j, :]\n\n                    dv_to_coef_ind[dv_idx] = coef_ind\n                    dv_idx += 1\n\n            # the for this volume is complete and can be added to the list of maps\n            volDVMap.append(dv_to_coef_ind)\n\n        self.DV_listSpanwiseLocal[dvName] = geoDVSpanwiseLocal(\n            dvName, lower, upper, scale, axis, volDVMap, self.masks, config\n        )\n\n        return self.DV_listSpanwiseLocal[dvName].nVal\n\n    def addGeoDVSpanwiseLocal(self, *args, **kwargs):\n        warnings.warn(\"addGeoDVSpanwiseLocal will be deprecated, use addSpanwiseLocalDV instead\")\n        self.addSpanwiseLocalDV(*args, **kwargs)\n\n    def addLocalSectionDV(\n        self,\n        dvName,\n        secIndex,\n        lower=None,\n        upper=None,\n        scale=1.0,\n        axis=1,\n        pointSelect=None,\n        volList=None,\n        orient0=None,\n        orient2=\"svd\",\n        config=None,\n    ):\n        \"\"\"\n        Add one or more section local design variables to the DVGeometry\n        object. Section local variables are used as an alternative to local\n        variables when it is desirable to deform a cross-section shape within a\n        plane that is consistent with the original cross-section orientation.\n        This is helpful in at least two common scenarios:\n\n        1. The original geometry has cross-sections that are not aligned with\n            the global coordinate axes. For instance, with a winglet, we want\n            the shape variables to deform normal to the winglet surface\n            instead of in the x, y, or z directions.\n        2. The global design variables cause changes in the geometry that\n            rotate the orientation of the original cross-section planes. In\n            this case, we want the shape variables to deform in directions\n            aligned with the rotated cross-section plane, which may not be\n            the x, y, or z directions.\n\n        ** Warnings **\n            - Rotations in an upper level (parent) FFD will not propagate down\n                to the lower level FFDs due to limitations of the current\n                implementation.\n            - Section local design variables should not be specified at the same\n                time as local design variables. This will most likely not result\n                in the desired behavior.\n\n        Parameters\n        ----------\n        dvName : str\n            A unique name to be given to this design variable group\n\n        lower : float\n            The lower bound for the variable(s). This will be applied to\n            all shape variables\n\n        upper : float\n            The upper bound for the variable(s). This will be applied to\n            all shape variables\n\n        scale : flot\n            The scaling of the variables. A good approximate scale to\n            start with is approximately 1.0/(upper-lower). This gives\n            variables that are of order ~1.0.\n\n        axis : int\n            The coordinate directions to move. Permissible values are\n                0: longitudinal direction (in section plane)\n                1: latitudinal direction (in section plane)\n                2: transverse direction (out of section plane)\n\n            If more than one direction is required, use multiple calls to\n            `addLocalSectionDV` with different axis values.\n            ::\n\n                                    1\n                                    ^\n                                    |\n                o-----o--------o----|----o--------o--------o-----o\n                |                   |                            |  j\n                |                   x---------> 0                |  ^\n                |                  /                             |  |\n                o-----o--------o--/------o--------o--------o-----o\n                                 /      ----> i\n                                /\n                               2\n\n        pointSelect : pointSelect object. Default is None\n            Use a pointSelect object to select a subset of the total number\n            of control points. See the documentation for the pointSelect\n            class in geo_utils. Using pointSelect discards everything in volList.\n            You can create a PointSelect object by using, for instance:\n            >>> PS = geo_utils.PointSelect(type = `y`, pt1=[0,0,0], pt2=[10, 0, 10])\n            Check the other PointSelect options in geo_utils.py\n\n        volList : list\n            Use the control points on the volume indicies given in volList. If\n            None, all volumes will be included.\n            PointSelect has priority over volList. So if you use PointSelect, the values\n            defined in volList will have no effect.\n\n        secIndex : char or list of chars\n            For each volume, we need to specify along which index we would like\n            to subdivide the volume into sections. Entries in list can be `i`,\n            `j`, or `k`. This index will be designated as the transverse (2)\n            direction in terms of the direction of perturbation for the 'axis'\n            parameter.\n\n        orient0 : None, `i`, `j`, `k`, or numpy vector. Default is None.\n            Although secIndex defines the `2` axis, the `0` and `1` axes are still\n            free to rotate within the section plane. We will choose the orientation\n            of the `0` axis and let `1` be orthogonal. We have three options:\n\n            1. <None> (default) If nothing is prescribed, the `0` direction will\n                be the best fit line through the section points. In the case\n                of an airfoil, this would roughly align with the chord.\n            2. <`i`,`j` or `k`> In this case, the `0` axis will be aligned\n                with the mean vector between the FFD edges corresponding to\n                this index. In the ascii art above, if `j` were given for this\n                option, we would average the vectors between the points on the\n                top and bottom surfaces and project this vector on to the\n                section plane as the `0` axis. If a list is given, each index\n                will be applied to its corresponding volume in volList.\n            3. <[`x`, `y`, `z`]> If a numpy vector is given, the `0` axis\n                will be aligned with a projection of this vector onto the\n                section plane. If a numpy array of len(volList) x 3 is given,\n                each vector will apply to its corresponding volume.\n\n        orient2 : `svd` or `ffd`. Default is `svd`\n            How to compute the orientation `2` axis. SVD is the\n            default bevaviour and is taken from the svd of the plane\n            points. `ffd` Uses the vector along the FFD direction of\n            secIndex. This is requied to get consistent normals if you\n            have a circular-type FFD when the SVD will swap the\n            normals.\n\n        config : str or list\n            Define what configurations this design variable will be applied to\n            Use a string for a single configuration or a list for multiple\n            configurations. The default value of None implies that the design\n            variable appies to *ALL* configurations.\n\n        Returns\n        -------\n        N : int\n            The number of design variables added.\n\n        Examples\n        --------\n        >>> # Add all control points in FFD as local shape variables\n        >>> # moving in the 1 direction, within +/- 1.0 units\n        >>> DVGeo.addLocalSectionDV('shape_vars', secIndex='k', lower=-1, upper=1, axis=1)\n        \"\"\"\n        if self.name is not None:\n            dvName = self.name + \"_\" + dvName\n\n        if type(config) == str:\n            config = [config]\n\n        # Pick out control points\n        if pointSelect is not None:\n            if pointSelect.type != \"ijkBounds\":\n                pts, ind = pointSelect.getPoints(self.FFD.coef)\n                volList = np.arange(self.FFD.nVol)  # Select all volumes\n            else:\n                pts, ind = pointSelect.getPoints_ijk(self)\n                volList = pointSelect.ijkBounds.keys()  # Select only volumes used by pointSelect\n        elif volList is not None:\n            if self.FFD.symmPlane is not None:\n                volListTmp = []\n                for vol in volList:\n                    volListTmp.append(vol)\n                for vol in volList:\n                    volListTmp.append(vol + self.FFD.nVol / 2)\n                volList = volListTmp\n\n            volList = np.atleast_1d(volList).astype(\"int\")\n            ind = []\n            for iVol in volList:\n                ind.extend(self.FFD.topo.lIndex[iVol].flatten())  # Get all indices from this block\n            ind = geo_utils.unique(ind)\n        else:\n            # Just take'em all\n            volList = np.arange(self.FFD.nVol)\n            ind = np.arange(len(self.FFD.coef))\n\n        secLink = np.zeros(self.FFD.coef.shape[0], dtype=int)\n        secTransform = [np.eye(3)]\n\n        if type(secIndex) is str:\n            secIndex = [secIndex] * len(volList)\n        elif type(secIndex) is list:\n            if len(secIndex) != len(volList):\n                raise Error(\"If a list is given for secIndex, the length must be\" \" equal to the length of volList.\")\n\n        if orient0 is not None:\n            # 'i', 'j', or 'k'\n            if type(orient0) is str:\n                orient0 = [orient0] * len(volList)\n            # ['k', 'k', 'i', etc.]\n            elif type(orient0) is list:\n                if len(orient0) != len(volList):\n                    raise Error(\"If a list is given for orient0, the length must\" \" be equal to the length of volList.\")\n            # np.array([1.0, 0.0, 0.0])\n            elif type(orient0) is np.ndarray:\n                # vector\n                if len(orient0.shape) == 1:\n                    orient0 = np.reshape(orient0, (1, 3))\n                    orient0 = np.repeat(orient0, len(volList), 0)\n                elif orient0.shape[0] == 1:\n                    orient0 = np.repeat(orient0, len(volList), 0)\n                elif orient0.shape[0] != len(volList):\n                    raise Error(\n                        \"If an array is given for orient0, the row dimension\" \" must be equal to the length of volList.\"\n                    )\n            for i, iVol in enumerate(volList):\n                self.sectionFrame(secIndex[i], secTransform, secLink, iVol, orient0[i], orient2=orient2)\n        else:\n            for i, iVol in enumerate(volList):\n                self.sectionFrame(secIndex[i], secTransform, secLink, iVol, orient2=orient2)\n\n        self.DV_listSectionLocal[dvName] = geoDVSectionLocal(\n            dvName, lower, upper, scale, axis, ind, self.masks, config, secTransform, secLink\n        )\n\n        return self.DV_listSectionLocal[dvName].nVal\n\n    def addGeoDVSectionLocal(self, *args, **kwargs):\n        warnings.warn(\"addGeoDVSectionLocal will be deprecated, use addLocalSectionDV instead\")\n        self.addLocalSectionDV(*args, **kwargs)\n\n    def getSymmetricCoefList(self, volList=None, pointSelect=None, tol=1e-8):\n        \"\"\"\n        Determine the pairs of coefs that need to be constrained for symmetry.\n\n        Parameters\n        ----------\n        volList : list\n            Use the control points on the volume indicies given in volList\n\n        pointSelect : pointSelect object. Default is None Use a\n            pointSelect object to select a subset of the total number\n            of control points. See the documentation for the\n            pointSelect class in geo_utils.\n        tol : float\n              Tolerance for ignoring nodes around the symmetry plane. These should be\n              merged by the network/connectivity anyway\n\n        Returns\n        -------\n        indSetA : list of ints\n                  One half of the coefs to be constrained\n\n        indSetB : list of ints\n                  Other half of the coefs to be constrained\n\n        Examples\n        --------\n\n        \"\"\"\n\n        if self.FFD.symmPlane is None:\n            # nothing to be done\n            indSetA = []\n            indSetB = []\n        else:\n            # get the direction of the symmetry plane\n            if self.FFD.symmPlane.lower() == \"x\":\n                index = 0\n            elif self.FFD.symmPlane.lower() == \"y\":\n                index = 1\n            elif self.FFD.symmPlane.lower() == \"z\":\n                index = 2\n\n            # get the points to be matched up\n            if pointSelect is not None:\n                pts, ind = pointSelect.getPoints(self.FFD.coef)\n            elif volList is not None:\n                volListTmp = []\n                for vol in volList:\n                    volListTmp.append(vol)\n                for vol in volList:\n                    volListTmp.append(vol + self.FFD.nVol / 2)\n                volList = volListTmp\n\n                volList = np.atleast_1d(volList).astype(\"int\")\n                ind = []\n                for iVol in volList:\n                    ind.extend(self.FFD.topo.lIndex[iVol].flatten())\n                ind = geo_utils.unique(ind)\n                pts = self.FFD.coef[ind]\n            else:\n                # Just take'em all\n                ind = np.arange(len(self.FFD.coef))\n                pts = self.FFD.coef\n\n            # Create the base points for the KD tree search. We will take the abs\n            # value of the symmetry direction, that way when we search we will get\n            # back index pairs which is what we want.\n            baseCoords = copy.copy(pts)\n            baseCoords[:, index] = abs(baseCoords[:, index])\n\n            # now use the baseCoords to create a KD tree\n            try:\n                from scipy.spatial import cKDTree\n            except ImportError:\n                raise Error(\"scipy.spatial \" \"must be available to use detect symmetry\")\n\n            # Now make a KD-tree so we can use it to find the unique nodes\n            tree = cKDTree(baseCoords)\n\n            # Now search through the +ve half of the points, ignoring anything within\n            # tol of the symmetry plane to find pairs\n            indSetA = []\n            indSetB = []\n            for pt in pts:\n                if pt[index] > tol:\n                    # Now find any matching nodes within tol. there should be 2 and\n                    # only 2 if the mesh is symmtric\n                    Ind = tree.query_ball_point(pt, tol)  # should this be a separate tol\n                    if not (len(Ind) == 2):\n                        raise Error(\"more than 2 coefs found that match pt\")\n                    else:\n                        indSetA.append(Ind[0])\n                        indSetB.append(Ind[1])\n\n        return indSetA, indSetB\n\n    def setDesignVars(self, dvDict):\n        \"\"\"\n        Standard routine for setting design variables from a design\n        variable dictionary.\n\n        Parameters\n        ----------\n        dvDict : dict\n            Dictionary of design variables. The keys of the dictionary\n            must correspond to the design variable names. Any\n            additional keys in the dfvdictionary are simply ignored.\n        \"\"\"\n\n        # Coefficients must be complexifed from here on if complex\n        if self.complex:\n            self._finalize()\n            self._complexifyCoef()\n\n        for key in dvDict:\n            if key in self.DV_listGlobal:\n                vals_to_set = np.atleast_1d(dvDict[key]).astype(\"D\")\n                if len(vals_to_set) != self.DV_listGlobal[key].nVal:\n                    raise Error(\n                        \"Incorrect number of design variables \"\n                        \"for DV: %s.\\nExpecting %d variables and \"\n                        \"received %d variabes\" % (key, self.DV_listGlobal[key].nVal, len(vals_to_set))\n                    )\n\n                self.DV_listGlobal[key].value = vals_to_set\n\n            if key in self.DV_listLocal:\n                vals_to_set = np.atleast_1d(dvDict[key]).astype(\"D\")\n                if len(vals_to_set) != self.DV_listLocal[key].nVal:\n                    raise Error(\n                        \"Incorrect number of design variables \\\n                    for DV: %s.\\nExpecting %d variables and received \\\n                    %d variabes\"\n                        % (key, self.DV_listLocal[key].nVal, len(vals_to_set))\n                    )\n                self.DV_listLocal[key].value = vals_to_set\n\n            if key in self.DV_listSectionLocal:\n                vals_to_set = np.atleast_1d(dvDict[key]).astype(\"D\")\n                if len(vals_to_set) != self.DV_listSectionLocal[key].nVal:\n                    raise Error(\n                        \"Incorrect number of design variables \\\n                    for DV: %s.\\nExpecting %d variables and received \\\n                    %d variabes\"\n                        % (key, self.DV_listSectionLocal[key].nVal, len(vals_to_set))\n                    )\n                self.DV_listSectionLocal[key].value = vals_to_set\n\n            if key in self.DV_listSpanwiseLocal:\n                vals_to_set = np.atleast_1d(dvDict[key]).astype(\"D\")\n                if len(vals_to_set) != self.DV_listSpanwiseLocal[key].nVal:\n                    raise Error(\n                        \"Incorrect number of design variables \\\n                    for DV: %s.\\nExpecting %d variables and received \\\n                    %d variabes\"\n                        % (key, self.DV_listSpanwiseLocal[key].nVal, len(vals_to_set))\n                    )\n                self.DV_listSpanwiseLocal[key].value = vals_to_set\n\n            # Jacobians are, in general, no longer up to date\n            self.zeroJacobians(self.ptSetNames)\n\n        # Flag all the pointSets as not being up to date:\n        for pointSet in self.updated:\n            self.updated[pointSet] = False\n\n        # Now call setValues on the children. This way the\n        # variables will be set on the children\n        for child in self.children:\n            child.setDesignVars(dvDict)\n\n    def zeroJacobians(self, ptSetNames):\n        \"\"\"\n        set stored jacobians to None for ptSetNames\n\n        Parameters\n        ----------\n        ptSetNames : list\n            list of ptSetNames to zero the jacobians.\n        \"\"\"\n        for name in ptSetNames:\n            self.JT[name] = None  # J is no longer up to date\n\n    def getValues(self):\n        \"\"\"\n        Generic routine to return the current set of design\n        variables. Values are returned in a dictionary format\n        that would be suitable for a subsequent call to setValues()\n\n        Returns\n        -------\n        dvDict : dict\n            Dictionary of design variables\n        \"\"\"\n\n        dvDict = {}\n        for key in self.DV_listGlobal:\n            dvDict[key] = self.DV_listGlobal[key].value\n\n        # and now the local DVs\n        for key in self.DV_listLocal:\n            dvDict[key] = self.DV_listLocal[key].value\n\n        # and now the section local DVs\n        for key in self.DV_listSectionLocal:\n            dvDict[key] = self.DV_listSectionLocal[key].value\n\n        # and now the Spanwise local DVs\n        for key in self.DV_listSpanwiseLocal:\n            dvDict[key] = self.DV_listSpanwiseLocal[key].value\n\n        # Now call getValues on the children. This way the\n        # returned dictionary will include the variables from\n        # the children\n        for child in self.children:\n            childdvDict = child.getValues()\n            dvDict.update(childdvDict)\n\n        return dvDict\n\n    def extractCoef(self, axisID):\n        \"\"\"Extract the coefficients for the selected reference\n        axis. This should be used only inside design variable functions\"\"\"\n\n        axisNumber = self._getAxisNumber(axisID)\n        C = np.zeros((len(self.refAxis.topo.lIndex[axisNumber]), 3), self.coef.dtype)\n\n        C[:, 0] = np.take(self.coef[:, 0], self.refAxis.topo.lIndex[axisNumber])\n        C[:, 1] = np.take(self.coef[:, 1], self.refAxis.topo.lIndex[axisNumber])\n        C[:, 2] = np.take(self.coef[:, 2], self.refAxis.topo.lIndex[axisNumber])\n\n        return C\n\n    def restoreCoef(self, coef, axisID):\n        \"\"\"Restore the coefficients for the selected reference\n        axis. This should be used inside design variable functions\"\"\"\n\n        # Reset\n        axisNumber = self._getAxisNumber(axisID)\n        np.put(self.coef[:, 0], self.refAxis.topo.lIndex[axisNumber], coef[:, 0])\n        np.put(self.coef[:, 1], self.refAxis.topo.lIndex[axisNumber], coef[:, 1])\n        np.put(self.coef[:, 2], self.refAxis.topo.lIndex[axisNumber], coef[:, 2])\n\n    def extractS(self, axisID):\n        \"\"\"Extract the parametric positions of the control\n        points. This is usually used in conjunction with extractCoef()\"\"\"\n        axisNumber = self._getAxisNumber(axisID)\n        return self.refAxis.curves[axisNumber].s.copy()\n\n    def _getAxisNumber(self, axisID):\n        \"\"\"Get the sequential axis number from the name tag axisID\"\"\"\n        try:\n            return list(self.axis.keys()).index(axisID)\n        except IndexError:\n            raise Error(\"'The 'axisID' was invalid!\")\n\n    def updateCalculations(self, new_pts, isComplex, config):\n        \"\"\"\n        The core update rountine. pulled out here to eliminate duplication between update and\n        update_deriv.\n        \"\"\"\n\n        if self.isChild:\n            # If this is a child, update the links between the ref axis and the\n            # coefficients on the nested FFD now that the nested FFD has been\n            # moved.\n            # **Important**: this expects the FFD coef to be clean on this level,\n            # meaning that the only changes to FFD.coef can be coming from\n            # higher levels.\n\n            # just use complex dtype here. we will convert to real in the end\n            self.links_x = self.links_x.astype(\"D\")\n\n            for ipt in range(self.nPtAttach):\n                base_pt = self.refAxis.curves[self.curveIDs[ipt]](self.links_s[ipt])\n                self.links_x[ipt] = self.FFD.coef[self.ptAttachInd[ipt], :] - base_pt\n\n        # Run Global Design Vars\n        for key in self.DV_listGlobal:\n            self.DV_listGlobal[key](self, config)\n\n        # update the reference axis now that the new global vars have been run\n        self.refAxis.coef = self.coef.copy()\n        self.refAxis._updateCurveCoef()\n\n        for ipt in range(self.nPtAttach):\n            base_pt = self.refAxis.curves[self.curveIDs[ipt]](self.links_s[ipt])\n            # Variables for rotType = 0 rotation + scaling\n            ang = self.axis[self.curveIDNames[ipt]][\"rot0ang\"]\n            ax_dir = self.axis[self.curveIDNames[ipt]][\"rot0axis\"]\n\n            scale = self.scale[self.curveIDNames[ipt]](self.links_s[ipt])\n            scale_x = self.scale_x[self.curveIDNames[ipt]](self.links_s[ipt])\n            scale_y = self.scale_y[self.curveIDNames[ipt]](self.links_s[ipt])\n            scale_z = self.scale_z[self.curveIDNames[ipt]](self.links_s[ipt])\n\n            rotType = self.axis[self.curveIDNames[ipt]][\"rotType\"]\n            if rotType == 0:\n                bp_ = np.copy(base_pt)  # copy of original pointset - will not be rotated\n                if isinstance(ang, (float, int)):  # rotation active only if a non-default value is provided\n                    ang *= np.pi / 180  # conv to [rad]\n                    # Rotating the FFD according to inputs\n                    # The FFD points should now be aligned with the main system of reference\n                    base_pt = geo_utils.rotVbyW(bp_, ax_dir, ang)\n                deriv = self.refAxis.curves[self.curveIDs[ipt]].getDerivative(self.links_s[ipt])\n                deriv /= geo_utils.euclideanNorm(deriv)  # Normalize\n                new_vec = -np.cross(deriv, self.links_n[ipt])\n                if isComplex:\n                    new_pts[ipt] = bp_ + new_vec * scale  # using \"unrotated\" bp_ vector\n                else:\n                    new_pts[ipt] = np.real(bp_ + new_vec * scale)\n\n                if isinstance(ang, (float, int)):\n                    # Rotating to be aligned with main sys ref\n                    nv_ = np.copy(new_vec)\n                    new_vec = geo_utils.rotVbyW(nv_, ax_dir, ang)\n\n                # Apply scaling\n                new_vec[0] *= scale_x\n                new_vec[1] *= scale_y\n                new_vec[2] *= scale_z\n\n                if isinstance(ang, (float, int)):\n                    # Rotating back the scaled pointset to its original position\n                    nv_rot = np.copy(new_vec)  # nv_rot is scaled and rotated\n                    new_vec = geo_utils.rotVbyW(nv_rot, ax_dir, -ang)\n\n                new_vec = geo_utils.rotVbyW(\n                    new_vec, deriv, self.rot_theta[self.curveIDNames[ipt]](self.links_s[ipt]) * np.pi / 180\n                )\n\n                if isComplex:\n                    new_pts[ipt] = bp_ + new_vec\n                else:\n                    new_pts[ipt] = np.real(bp_ + new_vec)\n\n            else:\n                rotX = geo_utils.rotxM(self.rot_x[self.curveIDNames[ipt]](self.links_s[ipt]))\n                rotY = geo_utils.rotyM(self.rot_y[self.curveIDNames[ipt]](self.links_s[ipt]))\n                rotZ = geo_utils.rotzM(self.rot_z[self.curveIDNames[ipt]](self.links_s[ipt]))\n\n                D = self.links_x[ipt]\n\n                rotM = self._getRotMatrix(rotX, rotY, rotZ, rotType)\n\n                # if necessary, assign rotation matrix for each ffd coef\n                if self.coefRotM is not None:\n                    attachedPoint = self.ptAttachInd[ipt]\n                    if isComplex:\n                        self.coefRotM[attachedPoint] = rotM\n                    else:\n                        self.coefRotM[attachedPoint] = np.real(rotM)\n\n                D = np.dot(rotM, D)\n                if rotType == 7:\n                    # only apply the theta rotations in certain cases\n                    deriv = self.refAxis.curves[self.curveIDs[ipt]].getDerivative(self.links_s[ipt])\n                    deriv /= geo_utils.euclideanNorm(deriv)  # Normalize\n                    D = geo_utils.rotVbyW(\n                        D, deriv, np.pi / 180 * self.rot_theta[self.curveIDNames[ipt]](self.links_s[ipt])\n                    )\n\n                elif rotType == 8:\n                    varname = self.axis[self.curveIDNames[ipt]][\"rotAxisVar\"]\n                    slVar = self.DV_listSectionLocal[varname]\n                    attachedPoint = self.ptAttachInd[ipt]\n                    W = slVar.sectionTransform[slVar.sectionLink[attachedPoint]][:, 2]\n                    D = geo_utils.rotVbyW(D, W, np.pi / 180 * self.rot_theta[self.curveIDNames[ipt]](self.links_s[ipt]))\n\n                D[0] *= scale_x\n                D[1] *= scale_y\n                D[2] *= scale_z\n\n                if isComplex:\n                    new_pts[ipt] = base_pt + D * scale\n                else:\n                    new_pts[ipt] = np.real(base_pt + D * scale)\n\n    def update(self, ptSetName, childDelta=True, config=None):\n        \"\"\"\n        This is the main routine for returning coordinates that have\n        been updated by design variables.\n\n        Parameters\n        ----------\n        ptSetName : str\n            Name of point-set to return. This must match ones of the\n            given in an :func:`addPointSet()` call.\n\n        childDelta : bool\n            Return updates on child as a delta. The user should not\n            need to ever change this parameter.\n\n        config : str or list\n            Define what configurations this design variable will be applied to\n            Use a string for a single configuration or a list for multiple\n            configurations. The default value of None implies that the design\n            variable appies to *ALL* configurations.\n\n        \"\"\"\n        self.curPtSet = ptSetName\n        # We've postponed things as long as we can...do the finialization.\n        self._finalize()\n\n        # Make sure coefficients are complex\n        self._complexifyCoef()\n\n        # Set all coef Values back to initial values\n        if not self.isChild:\n            self.FFD.coef = self.origFFDCoef.copy()\n            self._setInitialValues()\n        else:\n            # Update all coef\n            self.FFD._updateVolumeCoef()\n\n            # Evaluate starting pointset\n            Xstart = self.FFD.getAttachedPoints(ptSetName)\n\n            if self.complex:\n                # Now we have to propagate the complex part through Xstart\n                tempCoef = self.FFD.coef.copy().astype(\"D\")\n                Xstart = Xstart.astype(\"D\")\n                imag_part = np.imag(tempCoef)\n                imag_j = 1j\n\n                dPtdCoef = self.FFD.embededVolumes[ptSetName].dPtdCoef\n                if dPtdCoef is not None:\n                    for ii in range(3):\n                        Xstart[:, ii] += imag_j * dPtdCoef.dot(imag_part[:, ii])\n\n        # Step 1: Call all the design variables IFF we have ref axis:\n        if len(self.axis) > 0:\n            if self.complex:\n                new_pts = np.zeros((self.nPtAttach, 3), \"D\")\n            else:\n                new_pts = np.zeros((self.nPtAttach, 3), \"d\")\n\n            # Apply the global design variables\n            self.updateCalculations(new_pts, isComplex=self.complex, config=config)\n\n            # Put the update FFD points in their proper place\n            temp = np.real(new_pts)\n            np.put(self.FFD.coef[:, 0], self.ptAttachInd, temp[:, 0])\n            np.put(self.FFD.coef[:, 1], self.ptAttachInd, temp[:, 1])\n            np.put(self.FFD.coef[:, 2], self.ptAttachInd, temp[:, 2])\n\n        # Now add in the spanwise local DVs\n        for key in self.DV_listSpanwiseLocal:\n            self.DV_listSpanwiseLocal[key](self.FFD.coef, config)\n\n        # Now add in the section local DVs\n        for key in self.DV_listSectionLocal:\n            self.DV_listSectionLocal[key](self.FFD.coef, self.coefRotM, config)\n\n        # Now add in the local DVs\n        for key in self.DV_listLocal:\n            self.DV_listLocal[key](self.FFD.coef, config)\n\n        # Update all coef\n        self.FFD._updateVolumeCoef()\n\n        # Evaluate coordinates from the parent\n        Xfinal = self.FFD.getAttachedPoints(ptSetName)\n\n        # Propagate the complex part through the volume artificially\n        if self.complex:\n            # Above, we only took the real part of the coef because\n            # _updateVolumeCoef gets rid of it anyway. Here, we need to include\n            # the complex part because we want to propagate it through\n            tempCoef = self.FFD.coef.copy().astype(\"D\")\n            if len(self.axis) > 0:\n                np.put(tempCoef[:, 0], self.ptAttachInd, new_pts[:, 0])\n                np.put(tempCoef[:, 1], self.ptAttachInd, new_pts[:, 1])\n                np.put(tempCoef[:, 2], self.ptAttachInd, new_pts[:, 2])\n\n            # Apply just the complex part of the local varibales\n            for key in self.DV_listSpanwiseLocal:\n                self.DV_listSpanwiseLocal[key].updateComplex(tempCoef, config)\n            for key in self.DV_listSectionLocal:\n                self.DV_listSectionLocal[key].updateComplex(tempCoef, self.coefRotM, config)\n            for key in self.DV_listLocal:\n                self.DV_listLocal[key].updateComplex(tempCoef, config)\n\n            Xfinal = Xfinal.astype(\"D\")\n            imag_part = np.imag(tempCoef)\n            imag_j = 1j\n\n            dPtdCoef = self.FFD.embededVolumes[ptSetName].dPtdCoef\n            if dPtdCoef is not None:\n                for ii in range(3):\n                    Xfinal[:, ii] += imag_j * dPtdCoef.dot(imag_part[:, ii])\n\n        # Now loop over the children set the FFD and refAxis control\n        # points as evaluated from the parent\n        for iChild in range(len(self.children)):\n            child = self.children[iChild]\n            child._finalize()\n            self.applyToChild(iChild)\n\n            if self.complex:\n                # need to propagate the sensitivity to the children Xfinal here to do this\n                # correctly\n                child._complexifyCoef()\n                child.FFD.coef = child.FFD.coef.astype(\"D\")\n\n                dXrefdCoef = self.FFD.embededVolumes[\"child%d_axis\" % (iChild)].dPtdCoef\n                dCcdCoef = self.FFD.embededVolumes[\"child%d_coef\" % (iChild)].dPtdCoef\n\n                if dXrefdCoef is not None:\n                    for ii in range(3):\n                        child.coef[:, ii] += imag_j * dXrefdCoef.dot(imag_part[:, ii])\n\n                if dCcdCoef is not None:\n                    for ii in range(3):\n                        child.FFD.coef[:, ii] += imag_j * dCcdCoef.dot(imag_part[:, ii])\n                child.refAxis.coef = child.coef.copy()\n                child.refAxis._updateCurveCoef()\n\n            Xfinal += child.update(ptSetName, childDelta=True, config=config)\n\n        self._unComplexifyCoef()\n\n        # Finally flag this pointSet as being up to date:\n        self.updated[ptSetName] = True\n\n        if self.isChild and childDelta:\n            return Xfinal - Xstart\n        else:\n            return Xfinal\n\n    def applyToChild(self, iChild):\n        \"\"\"\n        This function is used to apply the changes in the parent FFD to the\n        child FFD points and child reference axis points.\n        \"\"\"\n        child = self.children[iChild]\n\n        # Set FFD points and reference axis points from parent\n        child.FFD.coef = self.FFD.getAttachedPoints(\"child%d_coef\" % (iChild))\n        child.coef = self.FFD.getAttachedPoints(\"child%d_axis\" % (iChild))\n\n        # Update the reference axes on the child\n        child.refAxis.coef = child.coef.copy()\n        child.refAxis._updateCurveCoef()\n\n    def pointSetUpToDate(self, ptSetName):\n        \"\"\"\n        This is used externally to query if the object needs to update\n        its pointset or not. Essentially what happens, is when\n        update() is called with a point set, it the self.updated dict\n        entry for pointSet is flagged as true. Here we just return\n        that flag. When design variables are set, we then reset all\n        the flags to False since, when DVs are set, nothing (in\n        general) will up to date anymore.\n\n        Parameters\n        ----------\n        ptSetName : str\n            The name of the pointset to check.\n        \"\"\"\n        if ptSetName in self.updated:\n            return self.updated[ptSetName]\n        else:\n            return True\n\n    def convertSensitivityToDict(self, dIdx, out1D=False):\n        \"\"\"\n        This function takes the result of totalSensitivity and\n        converts it to a dict for use in pyOptSparse\n\n        Parameters\n        ----------\n        dIdx : array\n           Flattened array of length getNDV(). Generally it comes from\n           a call to totalSensitivity()\n\n        out1D : boolean\n            If true, creates a 1D array in the dictionary instead of 2D.\n            This function is used in the matrix-vector product calculation.\n\n        Returns\n        -------\n        dIdxDict : dictionary\n           Dictionary of the same information keyed by this object's\n           design variables\n        \"\"\"\n\n        # compute the various DV offsets\n        DVCountGlobal, DVCountLocal, DVCountSecLoc, DVCountSpanLoc = self._getDVOffsets()\n\n        i = DVCountGlobal\n        dIdxDict = {}\n        for key in self.DV_listGlobal:\n            dv = self.DV_listGlobal[key]\n            if out1D:\n                dIdxDict[dv.name] = np.ravel(dIdx[:, i : i + dv.nVal])\n            else:\n                dIdxDict[dv.name] = dIdx[:, i : i + dv.nVal]\n            i += dv.nVal\n\n        i = DVCountSpanLoc\n        for key in self.DV_listSpanwiseLocal:\n            dv = self.DV_listSpanwiseLocal[key]\n            if out1D:\n                dIdxDict[dv.name] = np.ravel(dIdx[:, i : i + dv.nVal])\n            else:\n                dIdxDict[dv.name] = dIdx[:, i : i + dv.nVal]\n            i += dv.nVal\n\n        i = DVCountSecLoc\n        for key in self.DV_listSectionLocal:\n            dv = self.DV_listSectionLocal[key]\n            if out1D:\n                dIdxDict[dv.name] = np.ravel(dIdx[:, i : i + dv.nVal])\n            else:\n                dIdxDict[dv.name] = dIdx[:, i : i + dv.nVal]\n            i += dv.nVal\n\n        i = DVCountLocal\n        for key in self.DV_listLocal:\n            dv = self.DV_listLocal[key]\n            if out1D:\n                dIdxDict[dv.name] = np.ravel(dIdx[:, i : i + dv.nVal])\n            else:\n                dIdxDict[dv.name] = dIdx[:, i : i + dv.nVal]\n\n            i += dv.nVal\n\n        # Add in child portion\n        for iChild in range(len(self.children)):\n            childdIdx = self.children[iChild].convertSensitivityToDict(dIdx, out1D=out1D)\n            # update the total sensitivities with the derivatives from the child\n            for key in childdIdx:\n                if key in dIdxDict.keys():\n                    dIdxDict[key] += childdIdx[key]\n                else:\n                    dIdxDict[key] = childdIdx[key]\n\n        return dIdxDict\n\n    def convertDictToSensitivity(self, dIdxDict):\n        \"\"\"\n        This function performs the reverse operation of\n        convertSensitivityToDict(); it transforms the dictionary back\n        into an array. This function is important for the matrix-free\n        interface.\n\n        Parameters\n        ----------\n        dIdxDict : dictionary\n           Dictionary of information keyed by this object's\n           design variables\n\n        Returns\n        -------\n        dIdx : array\n           Flattened array of length getNDV().\n        \"\"\"\n        DVCountGlobal, DVCountLocal, DVCountSecLoc, DVCountSpanLoc = self._getDVOffsets()\n        dIdx = np.zeros(self.nDV_T, self.dtype)\n        i = DVCountGlobal\n        for key in self.DV_listGlobal:\n            dv = self.DV_listGlobal[key]\n            dIdx[i : i + dv.nVal] = dIdxDict[dv.name]\n            i += dv.nVal\n\n        i = DVCountLocal\n        for key in self.DV_listLocal:\n            dv = self.DV_listLocal[key]\n            dIdx[i : i + dv.nVal] = dIdxDict[dv.name]\n            i += dv.nVal\n\n        i = DVCountSecLoc\n        for key in self.DV_listSectionLocal:\n            dv = self.DV_listSectionLocal[key]\n            dIdx[i : i + dv.nVal] = dIdxDict[dv.name]\n            i += dv.nVal\n\n        i = DVCountSpanLoc\n        for key in self.DV_listSpanwiseLocal:\n            dv = self.DV_listSpanwiseLocal[key]\n            dIdx[i : i + dv.nVal] = dIdxDict[dv.name]\n            i += dv.nVal\n\n        # Note: not sure if this works with (multiple) sibling child FFDs\n        for iChild in range(len(self.children)):\n            childdIdx = self.children[iChild].convertDictToSensitivity(dIdxDict)\n            # update the total sensitivities with the derivatives from the child\n            dIdx += childdIdx\n        return dIdx\n\n    def getVarNames(self):\n        \"\"\"\n        Return a list of the design variable names. This is typically\n        used when specifying a wrt= argument for pyOptSparse.\n\n        Examples\n        --------\n        optProb.addCon(.....wrt=DVGeo.getVarNames())\n        \"\"\"\n        names = list(self.DV_listGlobal.keys())\n        names.extend(list(self.DV_listLocal.keys()))\n        names.extend(list(self.DV_listSectionLocal.keys()))\n        names.extend(list(self.DV_listSpanwiseLocal.keys()))\n\n        # Call the children recursively\n        for iChild in range(len(self.children)):\n            names.extend(self.children[iChild].getVarNames())\n\n        return names\n\n    def totalSensitivity(self, dIdpt, ptSetName, comm=None, config=None):\n        \"\"\"\n        This function computes sensitivty information.\n\n        Specificly, it computes the following:\n        :math:`\\\\frac{dX_{pt}}{dX_{DV}}^T \\\\frac{dI}{d_{pt}}`\n\n        Parameters\n        ----------\n        dIdpt : array of size (Npt, 3) or (N, Npt, 3)\n\n            This is the total derivative of the objective or function\n            of interest with respect to the coordinates in\n            'ptSetName'. This can be a single array of size (Npt, 3)\n            **or** a group of N vectors of size (Npt, 3, N). If you\n            have many to do, it is faster to do many at once.\n\n        ptSetName : str\n            The name of set of points we are dealing with\n\n        comm : MPI.IntraComm\n            The communicator to use to reduce the final derivative. If\n            comm is None, no reduction takes place.\n\n        config : str or list\n            Define what configurations this design variable will be applied to\n            Use a string for a single configuration or a list for multiple\n            configurations. The default value of None implies that the design\n            variable appies to *ALL* configurations.\n\n\n        Returns\n        -------\n        dIdxDict : dic\n            The dictionary containing the derivatives, suitable for\n            pyOptSparse\n\n        Notes\n        -----\n        The ``child`` and ``nDVStore`` options are only used\n        internally and should not be changed by the user.\n        \"\"\"\n\n        # Make dIdpt at least 3D\n        if len(dIdpt.shape) == 2:\n            dIdpt = np.array([dIdpt])\n        N = dIdpt.shape[0]\n\n        # generate the total Jacobian self.JT\n        self.computeTotalJacobian(ptSetName, config=config)\n\n        # now that we have self.JT compute the Mat-Mat multiplication\n        nDV = self._getNDV()\n        dIdx_local = np.zeros((N, nDV), \"d\")\n        for i in range(N):\n            if self.JT[ptSetName] is not None:\n                dIdx_local[i, :] = self.JT[ptSetName].dot(dIdpt[i, :, :].flatten())\n\n        if comm:  # If we have a comm, globaly reduce with sum\n            dIdx = comm.allreduce(dIdx_local, op=MPI.SUM)\n        else:\n            dIdx = dIdx_local\n\n        # Now convert to dict:\n        dIdx = self.convertSensitivityToDict(dIdx)\n\n        return dIdx\n\n    def totalSensitivityProd(self, vec, ptSetName, comm=None, child=False, nDVStore=0, config=None):\n        \"\"\"\n        This function computes sensitivty information.\n\n        Specifically, it computes the following:\n        :math:`\\\\frac{dX_{pt}}{dX_{DV}} \\\\ vec`\n\n        This is useful for forward AD mode.\n\n        Parameters\n        ----------\n        vec : dictionary whose keys are the design variable names, and whose\n              values are the derivative seeds of the corresponding design variable.\n\n        ptSetName : str\n            The name of set of points we are dealing with\n\n        comm : MPI.IntraComm\n            The communicator to use to reduce the final derivative. If\n            comm is None, no reduction takes place.\n\n        config : str or list\n            Define what configurations this design variable will be applied to\n            Use a string for a single configuration or a list for multiple\n            configurations. The default value of None implies that the design\n            variable appies to *ALL* configurations.\n\n        Returns\n        -------\n        xsdot : array (Nx3) -> Array with derivative seeds of the surface nodes.\n\n        Notes\n        -----\n        The ``child`` and ``nDVStore`` options are only used\n        internally and should not be changed by the user.\n        \"\"\"\n\n        self.computeTotalJacobian(ptSetName, config=config)\n\n        names = self.getVarNames()\n        newvec = np.zeros(self.getNDV(), self.dtype)\n        i = 0\n        for key in names:\n            if key in self.DV_listGlobal:\n                dv = self.DV_listGlobal[key]\n            elif key in self.DV_listSpanwiseLocal:\n                dv = self.DV_listSpanwiseLocal[key]\n            elif key in self.DV_listSectionLocal:\n                dv = self.DV_listSectionLocal[key]\n            else:\n                dv = self.DV_listLocal[key]\n\n            if key in vec:\n                newvec[i : i + dv.nVal] = vec[key]\n\n            i += dv.nVal\n\n        # perform the product\n        if self.JT[ptSetName] is None:\n            xsdot = np.zeros((0, 3))\n        else:\n            xsdot = self.JT[ptSetName].T.dot(newvec)\n            xsdot.reshape(len(xsdot) // 3, 3)\n            # Maybe this should be:\n            # xsdot = xsdot.reshape(len(xsdot)//3, 3)\n\n        return xsdot\n\n    def totalSensitivityTransProd(self, vec, ptSetName, comm=None, child=False, nDVStore=0, config=None):\n        \"\"\"\n        This function computes sensitivty information.\n\n        Specifically, it computes the following:\n        :math:`\\\\frac{dX_{pt}}{dX_{DV}}^T \\\\ vec`\n\n        This is useful for reverse AD mode.\n\n        Parameters\n        ----------\n        dIdpt : array of size (Npt, 3) or (N, Npt, 3)\n\n            This is the total derivative of the objective or function\n            of interest with respect to the coordinates in\n            'ptSetName'. This can be a single array of size (Npt, 3)\n            **or** a group of N vectors of size (Npt, 3, N). If you\n            have many to do, it is faster to do many at once.\n\n        ptSetName : str\n            The name of set of points we are dealing with\n\n        comm : MPI.IntraComm\n            The communicator to use to reduce the final derivative. If\n            comm is None, no reduction takes place.\n\n        config : str or list\n            Define what configurations this design variable will be applied to\n            Use a string for a single configuration or a list for multiple\n            configurations. The default value of None implies that the design\n            variable appies to *ALL* configurations.\n\n        Returns\n        -------\n        dIdxDict : dic\n            The dictionary containing the derivatives, suitable for\n            pyOptSparse\n\n        Notes\n        -----\n        The ``child`` and ``nDVStore`` options are only used\n        internally and should not be changed by the user.\n        \"\"\"\n\n        self.computeTotalJacobian(ptSetName, config=config)\n\n        # perform the product\n        if self.JT[ptSetName] is None:\n            xsdot = np.zeros((0, 3))\n        else:\n            xsdot = self.JT[ptSetName].dot(np.ravel(vec))\n\n        # Pack result into dictionary\n        xsdict = {}\n        names = self.getVarNames()\n        i = 0\n        for key in names:\n            if key in self.DV_listGlobal:\n                dv = self.DV_listGlobal[key]\n            elif key in self.DV_listSpanwiseLocal:\n                dv = self.DV_listSpanwiseLocal[key]\n            elif key in self.DV_listSectionLocal:\n                dv = self.DV_listSectionLocal[key]\n            else:\n                dv = self.DV_listLocal[key]\n            xsdict[key] = xsdot[i : i + dv.nVal]\n            i += dv.nVal\n\n        return xsdict\n\n    def computeDVJacobian(self, config=None):\n        \"\"\"\n        return J_temp for a given config\n        \"\"\"\n        # These routines are not recursive. They compute the derivatives at this level and\n        # pass information down one level for the next pass call from the routine above\n\n        # This is going to be DENSE in general\n        J_attach = self._attachedPtJacobian(config=config)\n\n        # Compute local normal jacobian\n        J_spanwiselocal = self._spanwiselocalDVJacobian(config=config)\n\n        # Compute local normal jacobian\n        J_sectionlocal = self._sectionlocalDVJacobian(config=config)\n\n        # This is the sparse jacobian for the local DVs that affect\n        # Control points directly.\n        J_local = self._localDVJacobian(config=config)\n\n        # this is the jacobian from accumulated derivative dependence from parent to child\n        J_casc = self._cascadedDVJacobian(config=config)\n\n        J_temp = None\n\n        # add them together\n        if J_attach is not None:\n            J_temp = sparse.lil_matrix(J_attach)\n\n        if J_spanwiselocal is not None:\n            if J_temp is None:\n                J_temp = sparse.lil_matrix(J_spanwiselocal)\n            else:\n                J_temp += J_spanwiselocal\n\n        if J_sectionlocal is not None:\n            if J_temp is None:\n                J_temp = sparse.lil_matrix(J_sectionlocal)\n            else:\n                J_temp += J_sectionlocal\n\n        if J_local is not None:\n            if J_temp is None:\n                J_temp = sparse.lil_matrix(J_local)\n            else:\n                J_temp += J_local\n\n        if J_casc is not None:\n            if J_temp is None:\n                J_temp = sparse.lil_matrix(J_casc)\n            else:\n                J_temp += J_casc\n\n        return J_temp\n\n    def computeTotalJacobian(self, ptSetName, config=None):\n        \"\"\"Return the total point jacobian in CSR format since we\n        need this for TACS\"\"\"\n\n        # Finalize the object, if not done yet\n        self._finalize()\n        self.curPtSet = ptSetName\n\n        if not (self.JT[ptSetName] is None):\n            return\n\n        # compute the derivatives of the coeficients of this level wrt all of the design\n        # variables at this level and all levels above\n        J_temp = self.computeDVJacobian(config=config)\n\n        # now get the derivative of the points for this level wrt the coefficients(dPtdCoef)\n        if self.FFD.embededVolumes[ptSetName].dPtdCoef is not None:\n            dPtdCoef = self.FFD.embededVolumes[ptSetName].dPtdCoef.tocoo()\n            # We have a slight problem...dPtdCoef only has the shape\n            # functions, so it size Npt x Coef. We need a matrix of\n            # size 3*Npt x 3*nCoef, where each non-zero entry of\n            # dPtdCoef is replaced by value * 3x3 Identity matrix.\n\n            # Extract IJV Triplet from dPtdCoef\n            row = dPtdCoef.row\n            col = dPtdCoef.col\n            data = dPtdCoef.data\n\n            new_row = np.zeros(3 * len(row), \"int\")\n            new_col = np.zeros(3 * len(row), \"int\")\n            new_data = np.zeros(3 * len(row))\n\n            # Loop over each entry and expand:\n            for j in range(3):\n                new_data[j::3] = data\n                new_row[j::3] = row * 3 + j\n                new_col[j::3] = col * 3 + j\n\n            # Size of New Matrix:\n            Nrow = dPtdCoef.shape[0] * 3\n            Ncol = dPtdCoef.shape[1] * 3\n\n            # Create new matrix in coo-dinate format and convert to csr\n            new_dPtdCoef = sparse.coo_matrix((new_data, (new_row, new_col)), shape=(Nrow, Ncol)).tocsr()\n\n            # Do Sparse Mat-Mat multiplication and resort indices\n            if J_temp is not None:\n                self.JT[ptSetName] = (J_temp.T * new_dPtdCoef.T).tocsr()\n                self.JT[ptSetName].sort_indices()\n\n            # Add in child portion\n            for iChild in range(len(self.children)):\n\n                # Reset control points on child for child link derivatives\n                self.applyToChild(iChild)\n                self.children[iChild].computeTotalJacobian(ptSetName, config=config)\n\n                if self.JT[ptSetName] is not None:\n                    self.JT[ptSetName] = self.JT[ptSetName] + self.children[iChild].JT[ptSetName]\n                else:\n                    self.JT[ptSetName] = self.children[iChild].JT[ptSetName]\n        else:\n            self.JT[ptSetName] = None\n\n    def computeTotalJacobianCS(self, ptSetName, config=None):\n        \"\"\"Return the total point jacobian in CSR format since we\n        need this for TACS\"\"\"\n\n        self._finalize()\n        self.curPtSet = ptSetName\n\n        if not (self.JT[ptSetName] is None):\n            return\n\n        if self.isChild:\n            refFFDCoef = copy.copy(self.FFD.coef)\n            refCoef = copy.copy(self.coef)\n\n        if self.nPts[ptSetName] is None:\n            self.nPts[ptSetName] = len(self.update(ptSetName).flatten())\n        for child in self.children:\n            child.nPts[ptSetName] = self.nPts[ptSetName]\n\n        DVGlobalCount, DVLocalCount, DVSecLocCount, DVSpanLocCount = self._getDVOffsets()\n\n        h = 1e-40j\n\n        self.JT[ptSetName] = np.zeros([self.nDV_T, self.nPts[ptSetName]])\n        self._complexifyCoef()\n        for key in self.DV_listGlobal:\n            for j in range(self.DV_listGlobal[key].nVal):\n                if self.isChild:\n                    self.FFD.coef = refFFDCoef.copy()\n                    self.coef = refCoef.copy()\n                    self.refAxis.coef = refCoef.copy()\n                    self.refAxis._updateCurveCoef()\n\n                refVal = self.DV_listGlobal[key].value[j]\n\n                self.DV_listGlobal[key].value[j] += h\n\n                deriv = np.imag(self._update_deriv_cs(ptSetName, config=config).flatten()) / np.imag(h)\n\n                self.JT[ptSetName][DVGlobalCount, :] = deriv\n\n                DVGlobalCount += 1\n                self.DV_listGlobal[key].value[j] = refVal\n\n        self._unComplexifyCoef()\n        for key in self.DV_listSpanwiseLocal:\n            for j in range(self.DV_listSpanwiseLocal[key].nVal):\n                if self.isChild:\n                    self.FFD.coef = refFFDCoef.copy()\n                    self.coef = refCoef.copy()\n                    self.refAxis.coef = refCoef.copy()\n                    self.refAxis._updateCurveCoef()\n\n                refVal = self.DV_listSpanwiseLocal[key].value[j]\n\n                self.DV_listSpanwiseLocal[key].value[j] += h\n                deriv = np.imag(self._update_deriv_cs(ptSetName, config=config).flatten()) / np.imag(h)\n\n                self.JT[ptSetName][DVSpanLocCount, :] = deriv\n\n                DVSpanLocCount += 1\n                self.DV_listSpanwiseLocal[key].value[j] = refVal\n\n        for key in self.DV_listSectionLocal:\n            for j in range(self.DV_listSectionLocal[key].nVal):\n                if self.isChild:\n                    self.FFD.coef = refFFDCoef.copy()\n                    self.coef = refCoef.copy()\n                    self.refAxis.coef = refCoef.copy()\n                    self.refAxis._updateCurveCoef()\n\n                refVal = self.DV_listSectionLocal[key].value[j]\n\n                self.DV_listSectionLocal[key].value[j] += h\n                deriv = np.imag(self._update_deriv_cs(ptSetName, config=config).flatten()) / np.imag(h)\n\n                self.JT[ptSetName][DVSecLocCount, :] = deriv\n\n                DVSecLocCount += 1\n                self.DV_listSectionLocal[key].value[j] = refVal\n\n        for key in self.DV_listLocal:\n            for j in range(self.DV_listLocal[key].nVal):\n                if self.isChild:\n                    self.FFD.coef = refFFDCoef.copy()\n                    self.coef = refCoef.copy()\n                    self.refAxis.coef = refCoef.copy()\n                    self.refAxis._updateCurveCoef()\n\n                refVal = self.DV_listLocal[key].value[j]\n\n                self.DV_listLocal[key].value[j] += h\n                deriv = np.imag(self._update_deriv_cs(ptSetName, config=config).flatten()) / np.imag(h)\n\n                self.JT[ptSetName][DVLocalCount, :] = deriv\n\n                DVLocalCount += 1\n                self.DV_listLocal[key].value[j] = refVal\n\n        for iChild in range(len(self.children)):\n            child = self.children[iChild]\n            child._finalize()\n\n            # In the updates applied previously, the FFD points on the children\n            # will have been set as deltas. We need to set them as absolute\n            # coordinates based on the changes in the parent before moving down\n            # to the next level\n            self.applyToChild(iChild)\n\n            # Now get jacobian from child and add to parent jacobian\n            child.computeTotalJacobianCS(ptSetName, config=config)\n            self.JT[ptSetName] = self.JT[ptSetName] + child.JT[ptSetName]\n\n        return\n\n    def addVariablesPyOpt(\n        self,\n        optProb,\n        globalVars=True,\n        localVars=True,\n        sectionlocalVars=True,\n        spanwiselocalVars=True,\n        ignoreVars=None,\n        freezeVars=None,\n    ):\n        \"\"\"\n        Add the current set of variables to the optProb object.\n\n        Parameters\n        ----------\n        optProb : pyOpt_optimization class\n            Optimization problem definition to which variables are added\n\n        globalVars : bool\n            Flag specifying whether global variables are to be added\n\n        localVars : bool\n            Flag specifying whether local variables are to be added\n\n        sectionlocalVars : bool\n            Flag specifying whether section local variables are to be added\n\n        spanwiselocalVars : bool\n            Flag specifying whether spanwiselocal variables are to be added\n\n        ignoreVars : list of strings\n            List of design variables the user DOESN'T want to use\n            as optimization variables.\n\n        freezeVars : list of string\n            List of design variables the user WANTS to add as optimization\n            variables, but to have the lower and upper bounds set at the current\n            variable. This effectively eliminates the variable, but it the variable\n            is still part of the optimization.\n        \"\"\"\n        if ignoreVars is None:\n            ignoreVars = set()\n        if freezeVars is None:\n            freezeVars = set()\n\n        # Add design variables from the master:\n        varLists = OrderedDict(\n            [\n                (\"globalVars\", self.DV_listGlobal),\n                (\"localVars\", self.DV_listLocal),\n                (\"sectionlocalVars\", self.DV_listSectionLocal),\n                (\"spanwiselocalVars\", self.DV_listSpanwiseLocal),\n            ]\n        )\n        for lst in varLists:\n            if (\n                lst == \"globalVars\"\n                and globalVars\n                or lst == \"localVars\"\n                and localVars\n                or lst == \"sectionlocalVars\"\n                and sectionlocalVars\n                or lst == \"spanwiselocalVars\"\n                and spanwiselocalVars\n            ):\n                for key in varLists[lst]:\n                    if key not in ignoreVars:\n                        dv = varLists[lst][key]\n                        if key not in freezeVars:\n                            optProb.addVarGroup(\n                                dv.name, dv.nVal, \"c\", value=dv.value, lower=dv.lower, upper=dv.upper, scale=dv.scale\n                            )\n                        else:\n                            optProb.addVarGroup(\n                                dv.name, dv.nVal, \"c\", value=dv.value, lower=dv.value, upper=dv.value, scale=dv.scale\n                            )\n\n        # Add variables from the children\n        for child in self.children:\n            child.addVariablesPyOpt(\n                optProb, globalVars, localVars, sectionlocalVars, spanwiselocalVars, ignoreVars, freezeVars\n            )\n\n    def writeTecplot(self, fileName):\n        \"\"\"Write the (deformed) current state of the FFD's to a tecplot file,\n        including the children\n\n        Parameters\n        ----------\n        fileName : str\n           Filename for tecplot file. Should have a .dat extension\n        \"\"\"\n\n        # Name here doesn't matter, just take the first one\n        if len(self.points) > 0:\n            keyToUpdate = list(self.points.keys())[0]\n            self.update(keyToUpdate, childDelta=False)\n\n        f = openTecplot(fileName, 3)\n        vol_counter = 0\n\n        # Write master volumes:\n        vol_counter += self._writeVols(f, vol_counter)\n\n        closeTecplot(f)\n        if len(self.points) > 0:\n            self.update(keyToUpdate, childDelta=True)\n\n    def writeRefAxes(self, fileName):\n        \"\"\"Write the (deformed) current state of the RefAxes to a tecplot file,\n        including the children\n\n        Parameters\n        ----------\n        fileName : str\n           Filename for tecplot file. Should have a no extension,an\n           extension will be added.\n        \"\"\"\n        # Name here doesnt matter, just take the first one\n        self.update(self.points.keys()[0], childDelta=False)\n\n        gFileName = fileName + \"_parent.dat\"\n        if not len(self.axis) == 0:\n            self.refAxis.writeTecplot(gFileName, orig=True, curves=True, coef=True)\n        # Write children axes:\n        for iChild in range(len(self.children)):\n            cFileName = fileName + \"_child{:03d}.dat\".format(iChild)\n            self.children[iChild].refAxis.writeTecplot(cFileName, orig=True, curves=True, coef=True)\n\n    def writeLinks(self, fileName):\n        \"\"\"Write the links attaching the control points to the reference axes\n\n        Parameters\n        ----------\n        fileName : str\n            Filename for tecplot file. Should have .dat extension\n        \"\"\"\n        self._finalize()\n        f = openTecplot(fileName, 3)\n        f.write(\"ZONE NODES=%d ELEMENTS=%d ZONETYPE=FELINESEG\\n\" % (self.nPtAttach * 2, self.nPtAttach))\n        f.write(\"DATAPACKING=POINT\\n\")\n        for ipt in range(self.nPtAttach):\n            pt1 = self.refAxis.curves[self.curveIDs[ipt]](self.links_s[ipt])\n            pt2 = self.links_x[ipt] + pt1\n\n            f.write(\"%.12g %.12g %.12g\\n\" % (pt1[0], pt1[1], pt1[2]))\n            f.write(\"%.12g %.12g %.12g\\n\" % (pt2[0], pt2[1], pt2[2]))\n        for i in range(self.nPtAttach):\n            f.write(\"%d %d\\n\" % (2 * i + 1, 2 * i + 2))\n\n        closeTecplot(f)\n\n    def writePointSet(self, name, fileName):\n        \"\"\"\n        Write a given point set to a tecplot file\n\n        Parameters\n        ----------\n        name : str\n             The name of the point set to write to a file\n\n        fileName : str\n           Filename for tecplot file. Should have no extension, an\n           extension will be added\n        \"\"\"\n        if self.isChild:\n            raise Error('Must call \"writePointSet\" from parent DVGeo.')\n        else:\n            coords = self.update(name, childDelta=True)\n            fileName = fileName + \"_%s.dat\" % name\n            f = openTecplot(fileName, 3)\n            writeTecplot1D(f, name, coords)\n            closeTecplot(f)\n\n    def writePlot3d(self, fileName):\n        \"\"\"Write the (deformed) current state of the FFD object into a\n        plot3D file. This file could then be used as the base-line FFD\n        for a subsequent optimization. This function is not typically\n        used in a regular basis, but may be useful in certain\n        situaions, i.e. a sequence of optimizations\n\n        Parameters\n        ----------\n        fileName : str\n            Filename of the plot3D file to write. Should have a .fmt\n            file extension.\n        \"\"\"\n        self.FFD.writePlot3dCoef(fileName)\n\n    def updatePyGeo(self, geo, outputType, fileName, nRefU=0, nRefV=0):\n        \"\"\"Deform a pyGeo object and write to a file of specified type\n        given the (deformed) current state of the FFD object.\n\n        Parameters\n        ----------\n        geo : pyGeo object\n            A pyGeo object containing an initialized object\n        outputType: str\n            Type of output file to be written. Can be `iges` or `tecplot`\n        fileName: str\n            Filename for the output file. Should have no extension, an\n            extension will be added\n        nRefU: int or list of ints\n            Number of spline refinement points to add in the surface B-Spline u-direction.\n            If scalar, it is applied across each surface. If list, the length must match the\n            number of surfaces in the object and corresponding entries are matched with surfaces.\n        nRefV: int or list of ints\n            Number of spline refinement points to add in the surface B-Spline v-direction.\n            If scalar, it is applied across each surface. If list, the length must match the\n            number of surfaces in the object and corresponding entries are matched with surfaces\n        \"\"\"\n        # Function to check if value matches a knot point\n        # (set to 1e-12 to match pySpline mult. tolerance)\n        def check_mult(val, knots):\n            for iKnot in range(len(knots)):\n                if np.isclose(val, knots[iKnot], atol=1e-12):\n                    return True\n            return False\n\n        # Refine Surface -- U-Direction\n        if isinstance(nRefU, int):\n            # Refine BSplines by adding knot points\n            Refine_U = np.linspace(0.0, 1.0, nRefU + 2)\n            for iSurf in range(geo.nSurf):\n                for iX in Refine_U:\n                    if not check_mult(iX, geo.surfs[iSurf].tu):\n                        geo.surfs[iSurf].insertKnot(\"u\", iX, 1)\n        elif isinstance(nRefU, list):\n            if len(nRefU) != geo.nSurf:\n                raise RuntimeError(\"Length of nRefU does not match number of surfaces in object\")\n            # Refine BSplines by adding knot points\n            for iSurf in range(geo.nSurf):\n                Refine_U = np.linspace(0.0, 1.0, nRefU[iSurf] + 2)\n                for iX in Refine_U:\n                    if not check_mult(iX, geo.surfs[iSurf].tu):\n                        geo.surfs[iSurf].insertKnot(\"u\", iX, 1)\n        else:\n            raise TypeError(\"nRefU type not recognized, must be: integer or list of integers\")\n\n        # Refine Surface -- V-Direction\n        if isinstance(nRefV, int):\n            # Refine BSplines by adding knot points\n            Refine_V = np.linspace(0.0, 1.0, nRefV + 2)\n            for iSurf in range(geo.nSurf):\n                for iY in Refine_V:\n                    if not check_mult(iY, geo.surfs[iSurf].tv):\n                        geo.surfs[iSurf].insertKnot(\"v\", iY, 1)\n        elif isinstance(nRefV, list):\n            if len(nRefU) != geo.nSurf:\n                raise RuntimeError(\"Length of nRefV does not match number of surfaces in object\")\n            # Refine BSplines by adding knot points\n            for iSurf in range(geo.nSurf):\n                Refine_V = np.linspace(0.0, 1.0, nRefV[iSurf] + 2)\n                for iY in Refine_V:\n                    if not check_mult(iY, geo.surfs[iSurf].tv):\n                        geo.surfs[iSurf].insertKnot(\"v\", iY, 1)\n        else:\n            raise TypeError(\"nRefV type not recognized, must be: integer or list of integers\")\n\n        # Update Coefficients\n        for iSurf in range(geo.nSurf):\n            # Add Point Sets\n            npt = geo.surfs[iSurf].nCtlu * geo.surfs[iSurf].nCtlv\n            self.addPointSet(geo.surfs[iSurf].coef.reshape((npt, 3)), \"coef%d\" % iSurf)\n\n            # Update and Overwrite Old Values\n            geo.surfs[iSurf].coef = self.update(\"coef%d\" % iSurf).reshape(geo.surfs[iSurf].coef.shape)\n\n        # Write File\n        if outputType == \"iges\":\n            geo.writeIGES(fileName + \".igs\")\n        elif outputType == \"tecplot\":\n            geo.writeTecplot(fileName + \".plt\")\n        else:\n            raise ValueError(\"Type {} not recognized. Must be either 'iges' or 'tecplot'\".format(outputType))\n\n    def getLocalIndex(self, iVol):\n        \"\"\"Return the local index mapping that points to the global\n        coefficient list for a given volume\"\"\"\n        return self.FFD.topo.lIndex[iVol].copy()\n\n    def getFlattenedChildren(self):\n        \"\"\"\n        Return a flattened list of all DVGeo objects in the family heirarchy.\n        \"\"\"\n        flatChildren = [self]\n        for child in self.children:\n            flatChildren += child.getFlattenedChildren()\n\n        return flatChildren\n\n    def demoDesignVars(self, directory, includeLocal=True, includeGlobal=True, pointSet=None, callBack=None, freq=2):\n        \"\"\"\n        This function can be used to \"test\" the design variable parametrization\n        for a given optimization problem. It should be called in the script\n        after DVGeo has been set up. The function will loop through all the\n        design variables and write out a deformed FFD volume for the upper\n        and lower bound of every design variable. It will also write out the\n        deformed pointset of choice.\n\n        Parameters\n        ----------\n        directory : str\n            The directory where the FFD files should be written.\n        includeLocal : boolean\n            False if you don't want to include the shape variables.\n        pointSet : str\n            Name of the pointset to write out. If this is not specified, it will\n            take the first one in the list.\n        callBack : function\n            This allows the user to perform an additional task at each new design\n            variable iteration (e.g. write out a deformed mesh). The callback\n            function must take two inputs: 1) the output directory name (str) and\n            2) the iteration count (int).\n        freq : int\n            Number of snapshots to take between the upper and lower bounds of\n            a given variable. If greater than 2, will do a sinusoidal sweep.\n        \"\"\"\n        # Generate directories\n        os.system(\"mkdir -p {:s}/ffd\".format(directory))\n        os.system(\"mkdir -p {:s}/pointset\".format(directory))\n\n        # Get design variables\n        dvDict = self.getValues()\n\n        # Get pointSet\n        if pointSet is None:\n            writePointSet = False\n            if self.ptSetNames:\n                pointSet = self.ptSetNames[0]\n            else:\n                raise Error(\"DVGeo must have a point set to update for \" \"demoDesignVars to work.\")\n        else:\n            writePointSet = True\n\n        # Loop through design variables on self and children\n        geoList = self.getFlattenedChildren()\n        count = 0\n        for geo in geoList:\n            for key in dvDict:\n                lower = []\n                if key in geo.DV_listLocal:\n                    if not includeLocal:\n                        continue\n                    lower = geo.DV_listLocal[key].lower\n                    upper = geo.DV_listLocal[key].upper\n\n                elif key in geo.DV_listSpanwiseLocal:\n                    if not includeLocal:\n                        continue\n                    lower = geo.DV_listSpanwiseLocal[key].lower\n                    upper = geo.DV_listSpanwiseLocal[key].upper\n\n                elif key in geo.DV_listSectionLocal:\n                    if not includeLocal:\n                        continue\n                    lower = geo.DV_listSectionLocal[key].lower\n                    upper = geo.DV_listSectionLocal[key].upper\n\n                elif key in geo.DV_listGlobal:\n                    if not includeGlobal:\n                        continue\n                    lower = geo.DV_listGlobal[key].lower\n                    upper = geo.DV_listGlobal[key].upper\n\n                if lower is None or upper is None:\n                    raise Error(\"demoDesignVars requires upper and lower bounds\" \"on all design variables.\")\n\n                x = dvDict[key].flatten()\n                nDV = len(lower)\n                for j in range(nDV):\n                    if freq == 2:\n                        stops = [lower[j], upper[j]]\n                    elif freq > 2:\n                        sinusoid = np.sin(np.linspace(0, np.pi, freq))\n                        down_swing = x[j] + (lower[j] - x[j]) * sinusoid\n                        up_swing = x[j] + (upper[j] - x[j]) * sinusoid\n                        stops = np.concatenate((down_swing[:-1], up_swing[:-1]))\n\n                    for val in stops:\n                        # Add perturbation to the design variable and update\n                        old_val = x[j]\n                        x[j] = val\n                        dvDict.update({key: x})\n                        self.setDesignVars(dvDict)\n                        self.update(pointSet)\n\n                        # Write FFD\n                        self.writeTecplot(\"{}/ffd/dv_{}_{:03d}_iter_{:03d}.dat\".format(directory, key, j, count))\n\n                        # Write pointset\n                        if writePointSet:\n                            self.writePointSet(pointSet, \"{}/pointset/iter_{:03d}\".format(directory, count))\n\n                        # Call user function\n                        if callBack is not None:\n                            callBack(directory, count)\n\n                        # Reset variable\n                        x[j] = old_val\n                        dvDict.update({key: x})\n\n                        # Iterate counter\n                        count += 1\n\n    # ----------------------------------------------------------------------\n    #        THE REMAINDER OF THE FUNCTIONS NEED NOT BE CALLED BY THE USER\n    # ----------------------------------------------------------------------\n\n    def _finalizeAxis(self):\n        \"\"\"\n        Internal function that sets up the collection of curve that\n        the user has added one at a time. This will create the\n        internal pyNetwork object\n        \"\"\"\n        if len(self.axis) == 0:\n            return\n\n        curves = []\n        for axis in self.axis:\n            curves.append(self.axis[axis][\"curve\"])\n\n        # Setup the network of reference axis curves\n        self.refAxis = pyNetwork(curves)\n        # These are the rotations\n        self.rot_x = OrderedDict()\n        self.rot_y = OrderedDict()\n        self.rot_z = OrderedDict()\n        self.rot_theta = OrderedDict()\n        self.scale = OrderedDict()\n        self.scale_x = OrderedDict()\n        self.scale_y = OrderedDict()\n        self.scale_z = OrderedDict()\n        self.coef = self.refAxis.coef  # pointer\n        self.coef0 = self.coef.copy().astype(self.dtype)\n\n        i = 0\n        for key in self.axis:\n            # curves in ref axis are indexed sequentially...this is ok\n            # since self.axis is an ORDERED dict\n            t = self.refAxis.curves[i].t\n            k = self.refAxis.curves[i].k\n            N = len(self.refAxis.curves[i].coef)\n            z = np.zeros((N, 1), self.dtype)\n            o = np.ones((N, 1), self.dtype)\n            self.rot_x[key] = Curve(t=t, k=k, coef=z.copy())\n            self.rot_y[key] = Curve(t=t, k=k, coef=z.copy())\n            self.rot_z[key] = Curve(t=t, k=k, coef=z.copy())\n            self.rot_theta[key] = Curve(t=t, k=k, coef=z.copy())\n            self.scale[key] = Curve(t=t, k=k, coef=o.copy())\n            self.scale_x[key] = Curve(t=t, k=k, coef=o.copy())\n            self.scale_y[key] = Curve(t=t, k=k, coef=o.copy())\n            self.scale_z[key] = Curve(t=t, k=k, coef=o.copy())\n            i += 1\n\n        # Need to keep track of initail scale values\n        self.scale0 = self.scale.copy()\n        self.scale_x0 = self.scale_x.copy()\n        self.scale_y0 = self.scale_y.copy()\n        self.scale_z0 = self.scale_z.copy()\n        self.rot_x0 = self.rot_x.copy()\n        self.rot_y0 = self.rot_y.copy()\n        self.rot_z0 = self.rot_z.copy()\n        self.rot_theta0 = self.rot_theta.copy()\n\n    def _finalize(self):\n        if self.finalized:\n            return\n        self._finalizeAxis()\n        if len(self.axis) == 0:\n            self.finalized = True\n            self.nPtAttachFull = len(self.FFD.coef)\n            return\n        # What we need to figure out is which of the control points\n        # are connected to an axis, and which ones are not connected\n        # to an axis.\n\n        # Retrieve all the pointset masks\n        coefMask = self.masks\n\n        self.ptAttachInd = []\n        self.ptAttach = []\n        curveIDs = []\n        s = []\n        curveID = 0\n        # Loop over the axis we have:\n        for key in self.axis:\n            vol_list = np.atleast_1d(self.axis[key][\"volumes\"]).astype(\"intc\")\n            temp = []\n            for iVol in vol_list:\n                for i in range(self.FFD.vols[iVol].nCtlu):\n                    for j in range(self.FFD.vols[iVol].nCtlv):\n                        for k in range(self.FFD.vols[iVol].nCtlw):\n                            ind = self.FFD.topo.lIndex[iVol][i, j, k]\n                            if (not coefMask[ind]) and (ind not in self.axis[key][\"ignoreInd\"]):\n                                temp.append(ind)\n\n            # Unique the values and append to the master list\n            curPtAttach = geo_utils.unique(temp)\n            self.ptAttachInd.extend(curPtAttach)\n\n            curPts = self.FFD.coef.take(curPtAttach, axis=0).real\n            self.ptAttach.extend(curPts)\n\n            # Now do the projections for *just* the axis defined by my\n            # key.\n            if self.axis[key][\"axis\"] is None:\n                tmpIDs, tmpS0 = self.refAxis.projectPoints(curPts, curves=[curveID])\n            else:\n                tmpIDs, tmpS0 = self.refAxis.projectRays(\n                    curPts, self.axis[key][\"axis\"], curves=[curveID], raySize=self.axis[key][\"raySize\"]\n                )\n\n            curveIDs.extend(tmpIDs)\n            s.extend(tmpS0)\n            curveID += 1\n\n        self.ptAttachFull = self.FFD.coef.copy().real\n        self.nPtAttach = len(self.ptAttach)\n        self.nPtAttachFull = len(self.ptAttachFull)\n\n        self.curveIDs = curveIDs\n        self.curveIDNames = []\n        axisKeys = list(self.axis.keys())\n        for i in range(len(curveIDs)):\n            self.curveIDNames.append(axisKeys[self.curveIDs[i]])\n\n        self.links_s = np.array(s)\n        self.links_x = []\n        self.links_n = []\n\n        for i in range(self.nPtAttach):\n            self.links_x.append(self.ptAttach[i] - self.refAxis.curves[self.curveIDs[i]](s[i]))\n            deriv = self.refAxis.curves[self.curveIDs[i]].getDerivative(self.links_s[i])\n            deriv /= geo_utils.euclideanNorm(deriv)  # Normalize\n            self.links_n.append(np.cross(deriv, self.links_x[-1]))\n\n        self.links_x = np.array(self.links_x)\n        self.links_s = np.array(self.links_s)\n        self.finalized = True\n\n    def _setInitialValues(self):\n        if len(self.axis) > 0:\n            self.coef[:, :] = copy.deepcopy(self.coef0)\n            for key in self.axis:\n                self.scale[key].coef[:] = copy.deepcopy(self.scale0[key].coef)\n                self.scale_x[key].coef[:] = copy.deepcopy(self.scale_x0[key].coef)\n                self.scale_y[key].coef[:] = copy.deepcopy(self.scale_y0[key].coef)\n                self.scale_z[key].coef[:] = copy.deepcopy(self.scale_z0[key].coef)\n                self.rot_x[key].coef[:] = copy.deepcopy(self.rot_x0[key].coef)\n                self.rot_y[key].coef[:] = copy.deepcopy(self.rot_y0[key].coef)\n                self.rot_z[key].coef[:] = copy.deepcopy(self.rot_z0[key].coef)\n                self.rot_theta[key].coef[:] = copy.deepcopy(self.rot_theta0[key].coef)\n\n    def _getRotMatrix(self, rotX, rotY, rotZ, rotType):\n        if rotType == 1:\n            D = np.dot(rotZ, np.dot(rotY, rotX))\n        elif rotType == 2:\n            D = np.dot(rotY, np.dot(rotZ, rotX))\n        elif rotType == 3:\n            D = np.dot(rotX, np.dot(rotZ, rotY))\n        elif rotType == 4:\n            D = np.dot(rotZ, np.dot(rotX, rotY))\n        elif rotType == 5:\n            D = np.dot(rotY, np.dot(rotX, rotZ))\n        elif rotType == 6:\n            D = np.dot(rotX, np.dot(rotY, rotZ))\n        elif rotType == 7:\n            D = np.dot(rotY, np.dot(rotX, rotZ))\n        elif rotType == 8:\n            D = np.dot(rotY, np.dot(rotX, rotZ))\n        return D\n\n    def _getNDV(self):\n        \"\"\"Return the actual number of design variables, global + local\n        + section local + spanwise local\n        \"\"\"\n        return self._getNDVGlobal() + self._getNDVLocal() + self._getNDVSectionLocal() + self._getNDVSpanwiseLocal()\n\n    def getNDV(self):\n        \"\"\"\n        Return the total number of design variables this object has.\n\n        Returns\n        -------\n        nDV : int\n            Total number of design variables\n        \"\"\"\n        return self._getNDV()\n\n    def _getNDVGlobal(self):\n        \"\"\"\n        Get total number of global variables, inclding any children\n        \"\"\"\n        nDV = 0\n        for key in self.DV_listGlobal:\n            nDV += self.DV_listGlobal[key].nVal\n\n        for child in self.children:\n            nDV += child._getNDVGlobal()\n\n        return nDV\n\n    def _getNDVLocal(self):\n        \"\"\"\n        Get total number of local variables, inclding any children\n        \"\"\"\n        nDV = 0\n        for key in self.DV_listLocal:\n            nDV += self.DV_listLocal[key].nVal\n\n        for child in self.children:\n            nDV += child._getNDVLocal()\n\n        return nDV\n\n    def _getNDVSectionLocal(self):\n        \"\"\"\n        Get total number of local variables, inclding any children\n        \"\"\"\n        nDV = 0\n        for key in self.DV_listSectionLocal:\n            nDV += self.DV_listSectionLocal[key].nVal\n\n        for child in self.children:\n            nDV += child._getNDVSectionLocal()\n\n        return nDV\n\n    def _getNDVSpanwiseLocal(self):\n        \"\"\"\n        Get total number of local variables, inclding any children\n        \"\"\"\n        nDV = 0\n        for key in self.DV_listSpanwiseLocal:\n            nDV += self.DV_listSpanwiseLocal[key].nVal\n\n        for child in self.children:\n            nDV += child._getNDVSpanwiseLocal()\n\n        return nDV\n\n    def _getNDVSelf(self):\n        \"\"\"\n        Get total number of local and global variables, not including\n        children\n        \"\"\"\n        return self._getNDVGlobalSelf() + self._getNDVLocalSelf()\n\n    def _getNDVGlobalSelf(self):\n        \"\"\"\n        Get total number of global variables, not including\n        children\n        \"\"\"\n        nDV = 0\n        for key in self.DV_listGlobal:\n            nDV += self.DV_listGlobal[key].nVal\n\n        return nDV\n\n    def _getNDVLocalSelf(self):\n        \"\"\"\n        Get total number of local variables, not including\n        children\n        \"\"\"\n        nDV = 0\n        for key in self.DV_listLocal:\n            nDV += self.DV_listLocal[key].nVal\n\n        return nDV\n\n    def _getNDVSectionLocalSelf(self):\n        \"\"\"\n        Get total number of local variables, not including\n        children\n        \"\"\"\n        nDV = 0\n        for key in self.DV_listSectionLocal:\n            nDV += self.DV_listSectionLocal[key].nVal\n\n        return nDV\n\n    def _getNDVSpanwiseLocalSelf(self):\n        \"\"\"\n        Get total number of local variables, not including\n        children\n        \"\"\"\n        nDV = 0\n        for key in self.DV_listSpanwiseLocal:\n            nDV += self.DV_listSpanwiseLocal[key].nVal\n\n        return nDV\n\n    def _getDVOffsets(self):\n        \"\"\"\n        return the global and local DV offsets for this FFD\n        \"\"\"\n\n        # figure out the split between local and global Variables\n        # All global vars at all levels come first\n        # then spanwise, then section local vars and then local vars.\n        # Parent Vars come before child Vars\n\n        # get the global and local DV numbers on the parents if we don't have them\n        if (\n            self.nDV_T is None\n            or self.nDVG_T is None\n            or self.nDVL_T is None\n            or self.nDVSL_T is None\n            or self.nDVSW_T is None\n        ):\n            self.nDV_T = self._getNDV()\n            self.nDVG_T = self._getNDVGlobal()\n            self.nDVL_T = self._getNDVLocal()\n            self.nDVSL_T = self._getNDVSectionLocal()\n            self.nDVSW_T = self._getNDVSpanwiseLocal()\n            self.nDVG_count = 0\n            self.nDVSL_count = self.nDVG_T\n            self.nDVL_count = self.nDVG_T + self.nDVSL_T\n\n        nDVG = self._getNDVGlobalSelf()\n        nDVL = self._getNDVLocalSelf()\n        nDVSL = self._getNDVSectionLocalSelf()\n        nDVSW = self._getNDVSpanwiseLocalSelf()\n\n        # Set the total number of global and local DVs into any children of this parent\n        for child in self.children:\n            # now get the numbers for the current parent child\n\n            child.nDV_T = self.nDV_T\n            child.nDVG_T = self.nDVG_T\n            child.nDVL_T = self.nDVL_T\n            child.nDVSL_T = self.nDVSL_T\n            child.nDVSW_T = self.nDVSW_T\n            child.nDVG_count = self.nDVG_count + nDVG\n            child.nDVL_count = self.nDVL_count + nDVL\n            child.nDVSL_count = self.nDVSL_count + nDVSL\n            child.nDVSW_count = self.nDVSW_count + nDVSL\n\n            # Increment the counters for the children\n            nDVG += child._getNDVGlobalSelf()\n            nDVL += child._getNDVLocalSelf()\n            nDVSL += child._getNDVSectionLocalSelf()\n            nDVSW += child._getNDVSpanwiseLocalSelf()\n\n        return self.nDVG_count, self.nDVL_count, self.nDVSL_count, self.nDVSW_count\n\n    def _update_deriv(self, iDV=0, h=1.0e-40j, oneoverh=1.0 / 1e-40, config=None, localDV=False):\n\n        \"\"\"Copy of update function for derivative calc\"\"\"\n        new_pts = np.zeros((self.nPtAttach, 3), \"D\")\n\n        # Step 1: Call all the design variables IFF we have ref axis:\n        if len(self.axis) > 0:\n\n            # Recompute changes due to global dvs at current point + h\n            self.updateCalculations(new_pts, isComplex=True, config=config)\n\n            # create a vector of the size of the full FFD\n            np.put(self.FFD.coef[:, 0], self.ptAttachInd, new_pts[:, 0])\n            np.put(self.FFD.coef[:, 1], self.ptAttachInd, new_pts[:, 1])\n            np.put(self.FFD.coef[:, 2], self.ptAttachInd, new_pts[:, 2])\n\n            # Add dependence of section variables on the global dv rotations\n            for key in self.DV_listSectionLocal:\n                self.DV_listSectionLocal[key].updateComplex(self.FFD.coef, self.coefRotM, config)\n\n            # Send values back to new_pts\n            new_pts[:, 0] = self.FFD.coef[self.ptAttachInd, 0]\n            new_pts[:, 1] = self.FFD.coef[self.ptAttachInd, 1]\n            new_pts[:, 2] = self.FFD.coef[self.ptAttachInd, 2]\n\n            # set the forward effect of the global design vars in each child\n            for iChild in range(len(self.children)):\n\n                # get the derivative of the child axis and control points wrt the parent\n                # control points\n                dXrefdCoef = self.FFD.embededVolumes[\"child%d_axis\" % (iChild)].dPtdCoef\n                dCcdCoef = self.FFD.embededVolumes[\"child%d_coef\" % (iChild)].dPtdCoef\n\n                # create a vector with the derivative of the parent control points wrt the\n                # parent global variables\n                tmp = np.zeros(self.FFD.coef.shape, dtype=\"d\")\n                np.put(tmp[:, 0], self.ptAttachInd, np.imag(new_pts[:, 0]) * oneoverh)\n                np.put(tmp[:, 1], self.ptAttachInd, np.imag(new_pts[:, 1]) * oneoverh)\n                np.put(tmp[:, 2], self.ptAttachInd, np.imag(new_pts[:, 2]) * oneoverh)\n\n                # create variables for the total derivative of the child axis and control\n                # points wrt the parent global variables\n                dXrefdXdv = np.zeros((dXrefdCoef.shape[0] * 3), \"d\")\n                dCcdXdv = np.zeros((dCcdCoef.shape[0] * 3), \"d\")\n\n                # multiply the derivative of the child axis wrt the parent control points\n                # by the derivative of the parent control points wrt the parent global vars.\n                # this is just chain rule\n                dXrefdXdv[0::3] = dXrefdCoef.dot(tmp[:, 0])\n                dXrefdXdv[1::3] = dXrefdCoef.dot(tmp[:, 1])\n                dXrefdXdv[2::3] = dXrefdCoef.dot(tmp[:, 2])\n\n                # do the same for the child control points\n                dCcdXdv[0::3] = dCcdCoef.dot(tmp[:, 0])\n                dCcdXdv[1::3] = dCcdCoef.dot(tmp[:, 1])\n                dCcdXdv[2::3] = dCcdCoef.dot(tmp[:, 2])\n                if localDV and self._getNDVLocalSelf():\n                    self.children[iChild].dXrefdXdvl[:, iDV] += dXrefdXdv\n                    self.children[iChild].dCcdXdvl[:, iDV] += dCcdXdv\n                elif self._getNDVGlobalSelf():\n                    self.children[iChild].dXrefdXdvg[:, iDV] += dXrefdXdv.real\n                    self.children[iChild].dCcdXdvg[:, iDV] += dCcdXdv.real\n        return new_pts\n\n    def _update_deriv_cs(self, ptSetName, config=None):\n\n        \"\"\"\n        A version of the update_deriv function specifically for use\n        in the computeTotalJacobianCS function.\"\"\"\n        new_pts = np.zeros((self.nPtAttachFull, 3), \"D\")\n\n        # Make sure coefficients are complex\n        self._complexifyCoef()\n\n        # Set all coef Values back to initial values\n        if not self.isChild:\n            self.FFD.coef = self.FFD.coef.astype(\"D\")\n            self._setInitialValues()\n        else:\n            # Update all coef\n            self.FFD.coef = self.FFD.coef.astype(\"D\")\n            self.FFD._updateVolumeCoef()\n\n            # Evaluate starting pointset\n            Xstart = self.FFD.getAttachedPoints(ptSetName)\n\n            # Now we have to propagate the complex part through Xstart\n            tempCoef = self.FFD.coef.copy().astype(\"D\")\n            Xstart = Xstart.astype(\"D\")\n            imag_part = np.imag(tempCoef)\n            imag_j = 1j\n\n            dPtdCoef = self.FFD.embededVolumes[ptSetName].dPtdCoef\n            if dPtdCoef is not None:\n                for ii in range(3):\n                    Xstart[:, ii] += imag_j * dPtdCoef.dot(imag_part[:, ii])\n\n        # Step 1: Call all the design variables IFF we have ref axis:\n        if len(self.axis) > 0:\n\n            # Compute changes due to global design vars\n            self.updateCalculations(new_pts, isComplex=True, config=config)\n\n            # Put the update FFD points in their proper place\n            np.put(self.FFD.coef[:, 0], self.ptAttachInd, new_pts[:, 0])\n            np.put(self.FFD.coef[:, 1], self.ptAttachInd, new_pts[:, 1])\n            np.put(self.FFD.coef[:, 2], self.ptAttachInd, new_pts[:, 2])\n\n        # Apply the real and complex parts separately\n        for key in self.DV_listSpanwiseLocal:\n            self.DV_listSpanwiseLocal[key](self.FFD.coef, self.coefRotM, config)\n            self.DV_listSpanwiseLocal[key].updateComplex(self.FFD.coef, self.coefRotM, config)\n\n        for key in self.DV_listSectionLocal:\n            self.DV_listSectionLocal[key](self.FFD.coef, self.coefRotM, config)\n            self.DV_listSectionLocal[key].updateComplex(self.FFD.coef, self.coefRotM, config)\n\n        for key in self.DV_listLocal:\n            self.DV_listLocal[key](self.FFD.coef, config)\n            self.DV_listLocal[key].updateComplex(self.FFD.coef, config)\n\n        # Update all coef\n        self.FFD._updateVolumeCoef()\n\n        # Evaluate coordinates from the parent\n        Xfinal = self.FFD.getAttachedPoints(ptSetName)\n\n        # now project derivs through from the coef to the pts\n        Xfinal = Xfinal.astype(\"D\")\n        imag_part = np.imag(self.FFD.coef)\n        imag_j = 1j\n\n        dPtdCoef = self.FFD.embededVolumes[ptSetName].dPtdCoef\n        if dPtdCoef is not None:\n            for ii in range(3):\n                Xfinal[:, ii] += imag_j * dPtdCoef.dot(imag_part[:, ii])\n\n        # now do the same for the children\n        for iChild in range(len(self.children)):\n            # first, update the coef. to their new locations\n            child = self.children[iChild]\n            child._finalize()\n            self.applyToChild(iChild)\n\n            # now cast forward the complex part of the derivative\n            child._complexifyCoef()\n            child.FFD.coef = child.FFD.coef.astype(\"D\")\n\n            dXrefdCoef = self.FFD.embededVolumes[\"child%d_axis\" % (iChild)].dPtdCoef\n            dCcdCoef = self.FFD.embededVolumes[\"child%d_coef\" % (iChild)].dPtdCoef\n\n            if dXrefdCoef is not None:\n                for ii in range(3):\n                    child.coef[:, ii] += imag_j * dXrefdCoef.dot(imag_part[:, ii])\n\n            if dCcdCoef is not None:\n                for ii in range(3):\n                    child.FFD.coef[:, ii] += imag_j * dCcdCoef.dot(imag_part[:, ii])\n            child.refAxis.coef = child.coef.copy()\n            child.refAxis._updateCurveCoef()\n            Xfinal += child._update_deriv_cs(ptSetName, config=config)\n            child._unComplexifyCoef()\n\n        self.FFD.coef = self.FFD.coef.real.astype(\"d\")\n\n        if self.isChild:\n            return Xfinal - Xstart\n        else:\n            return Xfinal\n\n    def _complexifyCoef(self):\n        \"\"\"Convert coef to complex temporarily\"\"\"\n        if len(self.axis) > 0:\n            for key in self.axis:\n                self.rot_x[key].coef = self.rot_x[key].coef.astype(\"D\")\n                self.rot_y[key].coef = self.rot_y[key].coef.astype(\"D\")\n                self.rot_z[key].coef = self.rot_z[key].coef.astype(\"D\")\n                self.rot_theta[key].coef = self.rot_theta[key].coef.astype(\"D\")\n\n                self.scale[key].coef = self.scale[key].coef.astype(\"D\")\n                self.scale_x[key].coef = self.scale_x[key].coef.astype(\"D\")\n                self.scale_y[key].coef = self.scale_y[key].coef.astype(\"D\")\n                self.scale_z[key].coef = self.scale_z[key].coef.astype(\"D\")\n\n            for i in range(self.refAxis.nCurve):\n                self.refAxis.curves[i].coef = self.refAxis.curves[i].coef.astype(\"D\")\n            self.coef = self.coef.astype(\"D\")\n\n    def _unComplexifyCoef(self):\n        \"\"\"Convert coef back to reals\"\"\"\n        if len(self.axis) > 0 and not self.complex:\n            for key in self.axis:\n                self.rot_x[key].coef = self.rot_x[key].coef.real.astype(\"d\")\n                self.rot_y[key].coef = self.rot_y[key].coef.real.astype(\"d\")\n                self.rot_z[key].coef = self.rot_z[key].coef.real.astype(\"d\")\n                self.rot_theta[key].coef = self.rot_theta[key].coef.real.astype(\"d\")\n\n                self.scale[key].coef = self.scale[key].coef.real.astype(\"d\")\n                self.scale_x[key].coef = self.scale_x[key].coef.real.astype(\"d\")\n                self.scale_y[key].coef = self.scale_y[key].coef.real.astype(\"d\")\n                self.scale_z[key].coef = self.scale_z[key].coef.real.astype(\"d\")\n\n            for i in range(self.refAxis.nCurve):\n                self.refAxis.curves[i].coef = self.refAxis.curves[i].coef.real.astype(\"d\")\n\n            self.coef = self.coef.real.astype(\"d\")\n\n    def computeTotalJacobianFD(self, ptSetName, config=None):\n        \"\"\"This function takes the total derivative of an objective,\n        I, with respect the points controlled on this processor using FD.\n        We take the transpose prodducts and mpi_allreduce them to get the\n        resulting value on each processor. Note that this function is slow\n        and should eventually be replaced by an analytic version.\n        \"\"\"\n\n        self._finalize()\n        self.curPtSet = ptSetName\n\n        if not (self.JT[ptSetName] is None):\n            return\n\n        if self.isChild:\n            refFFDCoef = copy.copy(self.FFD.coef)\n            refCoef = copy.copy(self.coef)\n\n        # Here we set childDelta as False, but it really doesn't matter\n        # whether it is True or False because we take a difference\n        # between coordsph and coords0, so the Xstart would be cancelled\n        # out in the end.\n        coords0 = self.update(ptSetName, childDelta=False, config=config).flatten()\n\n        if self.nPts[ptSetName] is None:\n            self.nPts[ptSetName] = len(coords0.flatten())\n        for child in self.children:\n            child.nPts[ptSetName] = self.nPts[ptSetName]\n\n        DVGlobalCount, DVLocalCount, DVSecLocCount, DVSpanLocCount = self._getDVOffsets()\n\n        h = 1e-6\n\n        self.JT[ptSetName] = np.zeros([self.nDV_T, self.nPts[ptSetName]])\n\n        for key in self.DV_listGlobal:\n            for j in range(self.DV_listGlobal[key].nVal):\n                if self.isChild:\n                    self.FFD.coef = refFFDCoef.copy()\n                    self.coef = refCoef.copy()\n                    self.refAxis.coef = refCoef.copy()\n                    self.refAxis._updateCurveCoef()\n\n                refVal = self.DV_listGlobal[key].value[j]\n\n                self.DV_listGlobal[key].value[j] += h\n\n                coordsph = self.update(ptSetName, childDelta=False, config=config).flatten()\n\n                deriv = (coordsph - coords0) / h\n                self.JT[ptSetName][DVGlobalCount, :] = deriv\n\n                DVGlobalCount += 1\n                self.DV_listGlobal[key].value[j] = refVal\n\n        for key in self.DV_listSpanwiseLocal:\n            for j in range(self.DV_listSpanwiseLocal[key].nVal):\n                if self.isChild:\n                    self.FFD.coef = refFFDCoef.copy()\n                    self.coef = refCoef.copy()\n                    self.refAxis.coef = refCoef.copy()\n                    self.refAxis._updateCurveCoef()\n\n                refVal = self.DV_listSpanwiseLocal[key].value[j]\n\n                self.DV_listSpanwiseLocal[key].value[j] += h\n                coordsph = self.update(ptSetName, childDelta=False, config=config).flatten()\n\n                deriv = (coordsph - coords0) / h\n                self.JT[ptSetName][DVSpanLocCount, :] = deriv\n\n                DVSpanLocCount += 1\n                self.DV_listSpanwiseLocal[key].value[j] = refVal\n\n        for key in self.DV_listSectionLocal:\n            for j in range(self.DV_listSectionLocal[key].nVal):\n                if self.isChild:\n                    self.FFD.coef = refFFDCoef.copy()\n                    self.coef = refCoef.copy()\n                    self.refAxis.coef = refCoef.copy()\n                    self.refAxis._updateCurveCoef()\n\n                refVal = self.DV_listSectionLocal[key].value[j]\n\n                self.DV_listSectionLocal[key].value[j] += h\n                coordsph = self.update(ptSetName, childDelta=False, config=config).flatten()\n\n                deriv = (coordsph - coords0) / h\n                self.JT[ptSetName][DVSecLocCount, :] = deriv\n\n                DVSecLocCount += 1\n                self.DV_listSectionLocal[key].value[j] = refVal\n\n        for key in self.DV_listLocal:\n            for j in range(self.DV_listLocal[key].nVal):\n                if self.isChild:\n                    self.FFD.coef = refFFDCoef.copy()\n                    self.coef = refCoef.copy()\n                    self.refAxis.coef = refCoef.copy()\n                    self.refAxis._updateCurveCoef()\n\n                refVal = self.DV_listLocal[key].value[j]\n\n                self.DV_listLocal[key].value[j] += h\n                coordsph = self.update(ptSetName, childDelta=False, config=config).flatten()\n\n                deriv = (coordsph - coords0) / h\n                self.JT[ptSetName][DVLocalCount, :] = deriv\n\n                DVLocalCount += 1\n                self.DV_listLocal[key].value[j] = refVal\n\n        for iChild in range(len(self.children)):\n            child = self.children[iChild]\n            child._finalize()\n\n            # In the updates applied previously, the FFD points on the children\n            # will have been set as deltas. We need to set them as absolute\n            # coordinates based on the changes in the parent before moving down\n            # to the next level\n            self.applyToChild(iChild)\n\n            # Now get jacobian from child and add to parent jacobian\n            child.computeTotalJacobianFD(ptSetName, config=config)\n            self.JT[ptSetName] = self.JT[ptSetName] + child.JT[ptSetName]\n\n        return\n\n    def _attachedPtJacobian(self, config):\n        \"\"\"\n        Compute the derivative of the the attached points\n        \"\"\"\n        nDV = self._getNDVGlobalSelf()\n\n        self._getDVOffsets()\n\n        h = 1.0e-40j\n        oneoverh = 1.0 / 1e-40\n        # Just do a CS loop over the coef\n        # First sum the actual number of globalDVs\n        if nDV != 0:  # check this\n            # create a jacobian the size of nPtAttached full by self.nDV_T, the total number of\n            # dvs\n            Jacobian = np.zeros((self.nPtAttachFull * 3, self.nDV_T))\n\n            # Create the storage arrays for the information that must be\n            # passed to the children\n            for iChild in range(len(self.children)):\n                N = self.FFD.embededVolumes[\"child%d_axis\" % (iChild)].N\n                # Derivative of reference axis points wrt global DVs at this level\n                self.children[iChild].dXrefdXdvg = np.zeros((N * 3, self.nDV_T))\n\n                N = self.FFD.embededVolumes[\"child%d_coef\" % (iChild)].N\n                # derivative of the control points wrt the global DVs at this level\n                self.children[iChild].dCcdXdvg = np.zeros((N * 3, self.nDV_T))\n\n            # We need to save the reference state so that we can always start\n            # from the same place when calling _update_deriv\n            refFFDCoef = copy.copy(self.FFD.coef)\n            refCoef = copy.copy(self.coef)\n\n            iDV = self.nDVG_count\n            for key in self.DV_listGlobal:\n                if (\n                    self.DV_listGlobal[key].config is None\n                    or config is None\n                    or any(c0 == config for c0 in self.DV_listGlobal[key].config)\n                ):\n                    nVal = self.DV_listGlobal[key].nVal\n                    for j in range(nVal):\n\n                        refVal = self.DV_listGlobal[key].value[j]\n\n                        self.DV_listGlobal[key].value[j] += h\n\n                        # Reset coefficients\n                        self.FFD.coef = refFFDCoef.astype(\"D\")  # ffd coefficients\n                        self.coef = refCoef.astype(\"D\")\n                        self.refAxis.coef = refCoef.astype(\"D\")\n                        self._complexifyCoef()  # Make sure coefficients are complex\n                        self.refAxis._updateCurveCoef()\n\n                        deriv = oneoverh * np.imag(self._update_deriv(iDV, h, oneoverh, config=config)).flatten()\n                        # reset the FFD and axis\n                        self._unComplexifyCoef()\n                        self.FFD.coef = self.FFD.coef.real.astype(\"d\")\n\n                        np.put(Jacobian[0::3, iDV], self.ptAttachInd, deriv[0::3])\n                        np.put(Jacobian[1::3, iDV], self.ptAttachInd, deriv[1::3])\n                        np.put(Jacobian[2::3, iDV], self.ptAttachInd, deriv[2::3])\n\n                        iDV += 1\n\n                        self.DV_listGlobal[key].value[j] = refVal\n                else:\n                    iDV += self.DV_listGlobal[key].nVal\n        else:\n            Jacobian = None\n\n        return Jacobian\n\n    def _spanwiselocalDVJacobian(self, config=None):\n        \"\"\"\n        Return the derivative of the coefficients wrt the local normal design\n        variables\n        \"\"\"\n        # This is relatively straight forward, since the matrix is\n        # entirely one's or zeros\n        nDV = self._getNDVSpanwiseLocalSelf()\n        self._getDVOffsets()\n\n        if nDV != 0:\n            Jacobian = sparse.lil_matrix((self.nPtAttachFull * 3, self.nDV_T))\n\n            # Create the storage arrays for the information that must be\n            # passed to the children\n\n            for iChild in range(len(self.children)):\n                N = self.FFD.embededVolumes[\"child%d_axis\" % (iChild)].N\n                self.children[iChild].dXrefdXdvl = np.zeros((N * 3, self.nDV_T))\n\n                N = self.FFD.embededVolumes[\"child%d_coef\" % (iChild)].N\n                self.children[iChild].dCcdXdvl = np.zeros((N * 3, self.nDV_T))\n\n            iDVSpanwiseLocal = self.nDVSW_count\n            for key in self.DV_listSpanwiseLocal:\n                dv = self.DV_listSpanwiseLocal[key]\n\n                # check that the dv is active for this config\n                if dv.config is None or config is None or any(c0 == config for c0 in dv.config):\n                    nVal = dv.nVal\n\n                    # apply this dv to FFD\n                    self.DV_listSpanwiseLocal[key](self.FFD.coef, config)\n\n                    # loop over value of the dv\n                    # (for example a single shape dv may have 20 values that\n                    # control the shape of the FFD at 20 points)\n                    for j in range(nVal):\n                        coefs = dv.dv_to_coefs[j]  # affected control points of FFD\n\n                        # this is map from dvs to coef\n                        for coef in coefs:\n                            irow = coef * 3 + dv.axis\n                            # *3 because the jacobian has a row for each x,y,z of the FFD\n                            # It is basically\n                            # row number = coef index * n dimensions + dimension index\n\n                            # value of FFD node location = x0 + dv_SWLocal[j]\n                            # so partial(FFD node location)/partial(dv_SWLocal) = 1\n                            # for each node effected by the dv_SWLocal[j]\n                            Jacobian[irow, iDVSpanwiseLocal] = 1.0\n\n                        for iChild in range(len(self.children)):\n                            # Get derivatives of child ref axis and FFD control\n                            # points w.r.t. parent's FFD control points\n                            dXrefdCoef = self.FFD.embededVolumes[\"child%d_axis\" % (iChild)].dPtdCoef\n                            dCcdCoef = self.FFD.embededVolumes[\"child%d_coef\" % (iChild)].dPtdCoef\n\n                            # derivative of Change in the FFD coef due to DVs\n                            # same as Jacobian above, but differnt ordering\n                            dCoefdXdvl = np.zeros(self.FFD.coef.shape, dtype=\"d\")\n\n                            for coef in coefs:\n                                dCoefdXdvl[coef, dv.axis] = 1.0\n\n                            dXrefdXdvl = np.zeros((dXrefdCoef.shape[0] * 3), \"d\")\n                            dCcdXdvl = np.zeros((dCcdCoef.shape[0] * 3), \"d\")\n\n                            dXrefdXdvl[0::3] = dXrefdCoef.dot(dCoefdXdvl[:, 0])\n                            dXrefdXdvl[1::3] = dXrefdCoef.dot(dCoefdXdvl[:, 1])\n                            dXrefdXdvl[2::3] = dXrefdCoef.dot(dCoefdXdvl[:, 2])\n\n                            dCcdXdvl[0::3] = dCcdCoef.dot(dCoefdXdvl[:, 0])\n                            dCcdXdvl[1::3] = dCcdCoef.dot(dCoefdXdvl[:, 1])\n                            dCcdXdvl[2::3] = dCcdCoef.dot(dCoefdXdvl[:, 2])\n\n                            # TODO: the += here is to allow recursion check this with multiple nesting\n                            # levels\n                            self.children[iChild].dXrefdXdvl[:, iDVSpanwiseLocal] += dXrefdXdvl\n                            self.children[iChild].dCcdXdvl[:, iDVSpanwiseLocal] += dCcdXdvl\n\n                        iDVSpanwiseLocal += 1\n                else:\n                    iDVSpanwiseLocal += self.DV_listSectionLocal[key].nVal\n\n                # end if config check\n            # end for\n        else:\n            Jacobian = None\n\n        return Jacobian\n\n    def _sectionlocalDVJacobian(self, config=None):\n        \"\"\"\n        Return the derivative of the coefficients wrt the local normal design\n        variables\n        \"\"\"\n        # This is relatively straight forward, since the matrix is\n        # entirely one's or zeros\n        nDV = self._getNDVSectionLocalSelf()\n        self._getDVOffsets()\n\n        if nDV != 0:\n            Jacobian = sparse.lil_matrix((self.nPtAttachFull * 3, self.nDV_T))\n\n            # Create the storage arrays for the information that must be\n            # passed to the children\n\n            for iChild in range(len(self.children)):\n                N = self.FFD.embededVolumes[\"child%d_axis\" % (iChild)].N\n                self.children[iChild].dXrefdXdvl = np.zeros((N * 3, self.nDV_T))\n\n                N = self.FFD.embededVolumes[\"child%d_coef\" % (iChild)].N\n                self.children[iChild].dCcdXdvl = np.zeros((N * 3, self.nDV_T))\n\n            iDVSectionLocal = self.nDVSL_count\n            for key in self.DV_listSectionLocal:\n                dv = self.DV_listSectionLocal[key]\n                if dv.config is None or config is None or any(c0 == config for c0 in dv.config):\n                    nVal = dv.nVal\n\n                    self.DV_listSectionLocal[key](self.FFD.coef, self.coefRotM, config)\n\n                    for j in range(nVal):\n                        coef = dv.coefList[j]  # affected control point\n                        T = dv.sectionTransform[dv.sectionLink[coef]]\n                        inFrame = np.zeros((3, 1))\n                        # Set axis that is being perturbed to 1.0\n                        inFrame[dv.axis] = 1.0\n\n                        R = np.real(self.coefRotM[coef])\n                        # this is a bug fix for scipy 1.3+ related to fancy indexing\n                        # the original was:\n                        # rows = range(coef*3,(coef+1)*3)\n                        # Jacobian[rows, iDVSectionLocal] += R.dot(T.dot(inFrame))\n                        Jacobian[coef * 3 : (coef + 1) * 3, iDVSectionLocal] += R.dot(T.dot(inFrame))\n                        for iChild in range(len(self.children)):\n\n                            dXrefdCoef = self.FFD.embededVolumes[\"child%d_axis\" % (iChild)].dPtdCoef\n                            dCcdCoef = self.FFD.embededVolumes[\"child%d_coef\" % (iChild)].dPtdCoef\n\n                            tmp = np.zeros(self.FFD.coef.shape, dtype=\"d\")\n\n                            tmp[coef, :] = R.dot(T.dot(inFrame)).flatten()\n\n                            dXrefdXdvl = np.zeros((dXrefdCoef.shape[0] * 3), \"d\")\n                            dCcdXdvl = np.zeros((dCcdCoef.shape[0] * 3), \"d\")\n\n                            dXrefdXdvl[0::3] = dXrefdCoef.dot(tmp[:, 0])\n                            dXrefdXdvl[1::3] = dXrefdCoef.dot(tmp[:, 1])\n                            dXrefdXdvl[2::3] = dXrefdCoef.dot(tmp[:, 2])\n\n                            dCcdXdvl[0::3] = dCcdCoef.dot(tmp[:, 0])\n                            dCcdXdvl[1::3] = dCcdCoef.dot(tmp[:, 1])\n                            dCcdXdvl[2::3] = dCcdCoef.dot(tmp[:, 2])\n\n                            # TODO: the += here is to allow recursion check this with multiple nesting\n                            # levels\n                            self.children[iChild].dXrefdXdvl[:, iDVSectionLocal] += dXrefdXdvl\n                            self.children[iChild].dCcdXdvl[:, iDVSectionLocal] += dCcdXdvl\n                        iDVSectionLocal += 1\n                else:\n                    iDVSectionLocal += self.DV_listSectionLocal[key].nVal\n\n                # end if config check\n            # end for\n        else:\n            Jacobian = None\n\n        return Jacobian\n\n    def _localDVJacobian(self, config=None):\n        \"\"\"\n        Return the derivative of the coefficients wrt the local design\n        variables\n        \"\"\"\n\n        # This is relatively straight forward, since the matrix is\n        # entirely one's or zeros\n        nDV = self._getNDVLocalSelf()\n        self._getDVOffsets()\n\n        if nDV != 0:\n            Jacobian = sparse.lil_matrix((self.nPtAttachFull * 3, self.nDV_T))\n\n            # Create the storage arrays for the information that must be\n            # passed to the children\n            for iChild in range(len(self.children)):\n                N = self.FFD.embededVolumes[\"child%d_axis\" % (iChild)].N\n                self.children[iChild].dXrefdXdvl = np.zeros((N * 3, self.nDV_T))\n\n                N = self.FFD.embededVolumes[\"child%d_coef\" % (iChild)].N\n                self.children[iChild].dCcdXdvl = np.zeros((N * 3, self.nDV_T))\n\n            iDVLocal = self.nDVL_count\n            for key in self.DV_listLocal:\n                if (\n                    self.DV_listLocal[key].config is None\n                    or config is None\n                    or any(c0 == config for c0 in self.DV_listLocal[key].config)\n                ):\n\n                    self.DV_listLocal[key](self.FFD.coef, config)\n\n                    nVal = self.DV_listLocal[key].nVal\n                    for j in range(nVal):\n                        pt_dv = self.DV_listLocal[key].coefList[j]\n                        irow = pt_dv[0] * 3 + pt_dv[1]\n                        Jacobian[irow, iDVLocal] = 1.0\n\n                        for iChild in range(len(self.children)):\n                            # Get derivatives of child ref axis and FFD control\n                            # points w.r.t. parent's FFD control points\n                            dXrefdCoef = self.FFD.embededVolumes[\"child%d_axis\" % (iChild)].dPtdCoef\n                            dCcdCoef = self.FFD.embededVolumes[\"child%d_coef\" % (iChild)].dPtdCoef\n\n                            tmp = np.zeros(self.FFD.coef.shape, dtype=\"d\")\n\n                            tmp[pt_dv[0], pt_dv[1]] = 1.0\n\n                            dXrefdXdvl = np.zeros((dXrefdCoef.shape[0] * 3), \"d\")\n                            dCcdXdvl = np.zeros((dCcdCoef.shape[0] * 3), \"d\")\n\n                            dXrefdXdvl[0::3] = dXrefdCoef.dot(tmp[:, 0])\n                            dXrefdXdvl[1::3] = dXrefdCoef.dot(tmp[:, 1])\n                            dXrefdXdvl[2::3] = dXrefdCoef.dot(tmp[:, 2])\n\n                            dCcdXdvl[0::3] = dCcdCoef.dot(tmp[:, 0])\n                            dCcdXdvl[1::3] = dCcdCoef.dot(tmp[:, 1])\n                            dCcdXdvl[2::3] = dCcdCoef.dot(tmp[:, 2])\n\n                            # TODO: the += here is to allow recursion check this with multiple nesting\n                            # levels\n                            self.children[iChild].dXrefdXdvl[:, iDVLocal] += dXrefdXdvl\n                            self.children[iChild].dCcdXdvl[:, iDVLocal] += dCcdXdvl\n                        iDVLocal += 1\n                else:\n                    iDVLocal += self.DV_listLocal[key].nVal\n\n                # end if config check\n            # end for\n        else:\n            Jacobian = None\n\n        return Jacobian\n\n    def _cascadedDVJacobian(self, config=None):\n        \"\"\"\n        Compute the cascading derivatives from the parent to the child\n        \"\"\"\n\n        if not self.isChild:\n            return None\n\n        # we are now on a child. Add in dependence passed from parent\n        Jacobian = sparse.lil_matrix((self.nPtAttachFull * 3, self.nDV_T))\n\n        # Save reference values (these are necessary so that we always start\n        # from the base state on the current DVGeo, and then apply the design\n        # variables from there).\n        refFFDCoef = copy.copy(self.FFD.coef)\n        refCoef = copy.copy(self.coef)\n\n        h = 1.0e-40j\n        oneoverh = 1.0 / 1e-40\n        if self.dXrefdXdvg is not None:\n            for iDV in range(self.dXrefdXdvg.shape[1]):\n                nz1 = np.count_nonzero(self.dXrefdXdvg[:, iDV])\n                nz2 = np.count_nonzero(self.dCcdXdvg[:, iDV])\n                if nz1 + nz2 == 0:\n                    continue\n\n                # Complexify all of the coefficients\n                self.FFD.coef = refFFDCoef.astype(\"D\")\n                self.coef = refCoef.astype(\"D\")\n                self._complexifyCoef()\n\n                # Add a complex pertubation representing the change in the child\n                # reference axis wrt the parent global DVs\n                self.coef[:, 0] += self.dXrefdXdvg[0::3, iDV] * h\n                self.coef[:, 1] += self.dXrefdXdvg[1::3, iDV] * h\n                self.coef[:, 2] += self.dXrefdXdvg[2::3, iDV] * h\n\n                # insert the new coef into the refAxis\n                self.refAxis.coef = self.coef.copy()\n                self.refAxis._updateCurveCoef()\n\n                # Complexify the child FFD coords\n                tmp1 = np.zeros_like(self.FFD.coef, dtype=\"D\")\n\n                # add the effect of the global coordinates on the actual control points\n                tmp1[:, 0] = self.dCcdXdvg[0::3, iDV] * h\n                tmp1[:, 1] = self.dCcdXdvg[1::3, iDV] * h\n                tmp1[:, 2] = self.dCcdXdvg[2::3, iDV] * h\n\n                self.FFD.coef += tmp1\n\n                # Store the original FFD coordinates so that we can get the delta\n                oldCoefLocations = self.FFD.coef.copy()\n\n                # compute the deriv of the child FFD coords wrt the parent by processing\n                # the above CS perturbation\n                new_pts = self._update_deriv(iDV, h, oneoverh, config=config)\n\n                # insert this result in the the correct locations of a vector the correct\n                # size\n                np.put(self.FFD.coef[:, 0], self.ptAttachInd, new_pts[:, 0])\n                np.put(self.FFD.coef[:, 1], self.ptAttachInd, new_pts[:, 1])\n                np.put(self.FFD.coef[:, 2], self.ptAttachInd, new_pts[:, 2])\n\n                # We have to subtract off the oldCoefLocations because we only\n                # want the cascading effect on the current design variables. The\n                # complex part on oldCoefLocations was already accounted for on\n                # the parent.\n                self.FFD.coef -= oldCoefLocations\n\n                # sum up all of the various influences\n                Jacobian[0::3, iDV] += oneoverh * np.imag(self.FFD.coef[:, 0:1])\n                Jacobian[1::3, iDV] += oneoverh * np.imag(self.FFD.coef[:, 1:2])\n                Jacobian[2::3, iDV] += oneoverh * np.imag(self.FFD.coef[:, 2:3])\n\n                # decomplexify the coefficients\n                self.coef = self.coef.real.astype(\"d\")\n                self.FFD.coef = self.FFD.coef.real.astype(\"d\")\n                self._unComplexifyCoef()\n\n        if self.dXrefdXdvl is not None:\n            # Now repeat for the local variables\n            for iDV in range(self.dXrefdXdvl.shape[1]):\n                # check if there is any dependence on this DV\n                nz1 = np.count_nonzero(self.dXrefdXdvl[:, iDV])\n                nz2 = np.count_nonzero(self.dCcdXdvl[:, iDV])\n                if nz1 + nz2 == 0:\n                    continue\n\n                # Complexify all of the coefficients\n                self.FFD.coef = refFFDCoef.astype(\"D\")\n                self.coef = refCoef.astype(\"D\")\n                self._complexifyCoef()\n\n                # Add a complex pertubation representing the change in the child\n                # reference axis wrt the parent local DVs\n                self.coef[:, 0] += self.dXrefdXdvl[0::3, iDV] * h\n                self.coef[:, 1] += self.dXrefdXdvl[1::3, iDV] * h\n                self.coef[:, 2] += self.dXrefdXdvl[2::3, iDV] * h\n\n                # insert the new coef into the refAxis\n                self.refAxis.coef = self.coef.copy()\n                self.refAxis._updateCurveCoef()\n\n                # Complexify the child FFD coords\n                tmp1 = np.zeros_like(self.FFD.coef, dtype=\"D\")\n\n                # add the effect of the global coordinates on the actual control points\n                tmp1[:, 0] = self.dCcdXdvl[0::3, iDV] * h\n                tmp1[:, 1] = self.dCcdXdvl[1::3, iDV] * h\n                tmp1[:, 2] = self.dCcdXdvl[2::3, iDV] * h\n\n                self.FFD.coef += tmp1\n\n                # Store the original FFD coordinates so that we can get the delta\n                oldCoefLocations = self.FFD.coef.copy()\n\n                # compute the deriv of the child FFD coords wrt the parent by processing\n                # the above CS perturbation\n                new_pts = self._update_deriv(iDV, h, oneoverh, config=config, localDV=True)\n                np.put(self.FFD.coef[:, 0], self.ptAttachInd, new_pts[:, 0])\n                np.put(self.FFD.coef[:, 1], self.ptAttachInd, new_pts[:, 1])\n                np.put(self.FFD.coef[:, 2], self.ptAttachInd, new_pts[:, 2])\n\n                # We have to subtract off the oldCoefLocations because we only\n                # want the cascading effect on the current design variables. The\n                # complex part on oldCoefLocations was already accounted for on\n                # the parent.\n                self.FFD.coef -= oldCoefLocations\n\n                # sum up all of the various influences\n                Jacobian[0::3, iDV] += oneoverh * np.imag(self.FFD.coef[:, 0:1])\n                Jacobian[1::3, iDV] += oneoverh * np.imag(self.FFD.coef[:, 1:2])\n                Jacobian[2::3, iDV] += oneoverh * np.imag(self.FFD.coef[:, 2:3])\n\n                # decomplexify the coefficients\n                self.coef = self.coef.real.astype(\"d\")\n                self.FFD.coef = self.FFD.coef.real.astype(\"d\")\n                self._unComplexifyCoef()\n\n        return Jacobian\n\n    def _writeVols(self, handle, vol_counter):\n        for i in range(len(self.FFD.vols)):\n            writeTecplot3D(handle, \"vol%d\" % i, self.FFD.vols[i].coef)\n            vol_counter += 1\n\n        # Write children volumes:\n        for iChild in range(len(self.children)):\n            vol_counter += self.children[iChild]._writeVols(handle, vol_counter)\n\n        return vol_counter\n\n    def checkDerivatives(self, ptSetName):\n        \"\"\"\n        Run a brute force FD check on ALL design variables\n\n        Parameters\n        ----------\n        ptSetName : str\n            name of the point set to check\n        \"\"\"\n\n        print(\"Computing Analytic Jacobian...\")\n        self.zeroJacobians(ptSetName)\n        for child in self.children:\n            child.zeroJacobians(ptSetName)\n\n        self.computeTotalJacobian(ptSetName)\n        # self.computeTotalJacobian_fast(ptSetName)\n\n        Jac = copy.deepcopy(self.JT[ptSetName])\n\n        # Global Variables\n        print(\"========================================\")\n        print(\"             Global Variables           \")\n        print(\"========================================\")\n\n        if self.isChild:\n            refFFDCoef = copy.copy(self.FFD.coef)\n            refCoef = copy.copy(self.coef)\n\n        coords0 = self.update(ptSetName).flatten()\n\n        h = 1e-6\n\n        # figure out the split between local and global Variables\n        DVCountGlob, DVCountLoc, DVCountSecLoc, DVCountSpanLoc = self._getDVOffsets()\n\n        for key in self.DV_listGlobal:\n            for j in range(self.DV_listGlobal[key].nVal):\n\n                print(\"========================================\")\n                print(\"      GlobalVar(%s), Value(%d)\" % (key, j))\n                print(\"========================================\")\n\n                if self.isChild:\n                    self.FFD.coef = refFFDCoef.copy()\n                    self.coef = refCoef.copy()\n                    self.refAxis.coef = self.coef.copy()\n                    self.refAxis._updateCurveCoef()\n\n                refVal = self.DV_listGlobal[key].value[j]\n\n                self.DV_listGlobal[key].value[j] += h\n\n                coordsph = self.update(ptSetName).flatten()\n\n                deriv = (coordsph - coords0) / h\n\n                for ii in range(len(deriv)):\n\n                    relErr = (deriv[ii] - Jac[DVCountGlob, ii]) / (1e-16 + Jac[DVCountGlob, ii])\n                    absErr = deriv[ii] - Jac[DVCountGlob, ii]\n\n                    if abs(relErr) > h * 10 and abs(absErr) > h * 10:\n                        print(ii, deriv[ii], Jac[DVCountGlob, ii], relErr, absErr)\n\n                DVCountGlob += 1\n                self.DV_listGlobal[key].value[j] = refVal\n\n        for key in self.DV_listLocal:\n            for j in range(self.DV_listLocal[key].nVal):\n\n                print(\"========================================\")\n                print(\"      LocalVar(%s), Value(%d)           \" % (key, j))\n                print(\"========================================\")\n\n                if self.isChild:\n                    self.FFD.coef = refFFDCoef.copy()\n                    self.coef = refCoef.copy()\n                    self.refAxis.coef = self.coef.copy()\n                    self.refAxis._updateCurveCoef()\n\n                refVal = self.DV_listLocal[key].value[j]\n\n                self.DV_listLocal[key].value[j] += h\n                coordsph = self.update(ptSetName).flatten()\n\n                deriv = (coordsph - coords0) / h\n\n                for ii in range(len(deriv)):\n                    relErr = (deriv[ii] - Jac[DVCountLoc, ii]) / (1e-16 + Jac[DVCountLoc, ii])\n                    absErr = deriv[ii] - Jac[DVCountLoc, ii]\n\n                    if abs(relErr) > h and abs(absErr) > h:\n                        print(ii, deriv[ii], Jac[DVCountLoc, ii], relErr, absErr)\n\n                DVCountLoc += 1\n                self.DV_listLocal[key].value[j] = refVal\n\n        for key in self.DV_listSectionLocal:\n            for j in range(self.DV_listSectionLocal[key].nVal):\n\n                print(\"========================================\")\n                print(\"   SectionLocalVar(%s), Value(%d)       \" % (key, j))\n                print(\"========================================\")\n\n                if self.isChild:\n                    self.FFD.coef = refFFDCoef.copy()\n                    self.coef = refCoef.copy()\n                    self.refAxis.coef = self.coef.copy()\n                    self.refAxis._updateCurveCoef()\n\n                refVal = self.DV_listSectionLocal[key].value[j]\n\n                self.DV_listSectionLocal[key].value[j] += h\n                coordsph = self.update(ptSetName).flatten()\n\n                deriv = (coordsph - coords0) / h\n\n                for ii in range(len(deriv)):\n                    relErr = (deriv[ii] - Jac[DVCountSecLoc, ii]) / (1e-16 + Jac[DVCountSecLoc, ii])\n                    absErr = deriv[ii] - Jac[DVCountSecLoc, ii]\n\n                    if abs(relErr) > h and abs(absErr) > h:\n                        print(ii, deriv[ii], Jac[DVCountSecLoc, ii], relErr, absErr)\n\n                DVCountSecLoc += 1\n                self.DV_listSectionLocal[key].value[j] = refVal\n\n        for key in self.DV_listSpanwiseLocal:\n            for j in range(self.DV_listSpanwiseLocal[key].nVal):\n\n                print(\"========================================\")\n                print(\"   SpanwiseLocalVar(%s), Value(%d)       \" % (key, j))\n                print(\"========================================\")\n\n                if self.isChild:\n                    self.FFD.coef = refFFDCoef.copy()\n                    self.coef = refCoef.copy()\n                    self.refAxis.coef = self.coef.copy()\n                    self.refAxis._updateCurveCoef()\n\n                refVal = self.DV_listSpanwiseLocal[key].value[j]\n\n                self.DV_listSpanwiseLocal[key].value[j] += h\n                coordsph = self.update(ptSetName).flatten()\n\n                deriv = (coordsph - coords0) / h\n\n                for ii in range(len(deriv)):\n                    relErr = (deriv[ii] - Jac[DVCountSpanLoc, ii]) / (1e-16 + Jac[DVCountSpanLoc, ii])\n                    absErr = deriv[ii] - Jac[DVCountSpanLoc, ii]\n\n                    if abs(relErr) > h and abs(absErr) > h:\n                        print(ii, deriv[ii], Jac[DVCountSpanLoc, ii], relErr, absErr)\n                    # print(ii, deriv[ii], Jac[DVCountSpanLoc, ii], relErr, absErr)\n\n                DVCountSpanLoc += 1\n                self.DV_listSpanwiseLocal[key].value[j] = refVal\n\n        for child in self.children:\n            child.checkDerivatives(ptSetName)\n\n    def printDesignVariables(self):\n        \"\"\"\n        Print a formatted list of design variables to the screen\n        \"\"\"\n        for dg in self.DV_listGlobal:\n            print(\"%s\" % (self.DV_listGlobal[dg].name))\n            for i in range(self.DV_listGlobal[dg].nVal):\n                print(\"%20.15f\" % (self.DV_listGlobal[dg].value[i]))\n\n        for dl in self.DV_listLocal:\n            print(\"%s\" % (self.DV_listLocal[dl].name))\n            for i in range(self.DV_listLocal[dl].nVal):\n                print(\"%20.15f\" % (self.DV_listLocal[dl].value[i]))\n\n        for dsl in self.DV_listSectionLocal:\n            print(\"%s\" % (self.DV_listSectionLocal[dsl].name))\n            for i in range(self.DV_listSectionLocal[dsl].nVal):\n                print(\"%20.15f\" % (self.DV_listSectionLocal[dsl].value[i]))\n\n        for child in self.children:\n            child.printDesignVariables()\n\n    def sectionFrame(self, sectionIndex, sectionTransform, sectionLink, ivol=0, orient0=None, orient2=\"svd\"):\n        \"\"\"\n        This function computes a unique reference coordinate frame for each\n        section of an FFD volume. You can choose which axis of the FFD you would\n        like these sections to be defined by. For example, if we have a wing\n        with a winglet, the airfoil sections which make up the wing will not all\n        lie in parallel planes. We want to find a reference frame for each of\n        these airfoil sections so that we can constrain local control points to\n        deform within the sectional plane. Let's say the wing FFD is oriented\n        with indices:\n\n        `i`\n            along chord\n        `j`\n            normal to wing surface\n        `k`\n            along span\n\n        If we choose `sectionIndex='k'`, this function will compute a frame which\n        has two axes aligned with the k-planes of the FFD volume. This is useful\n        because in some cases (as with a winglet), we want to perturb sectional\n        control points within the section plane instead of in the global\n        coordinate directions.\n\n        Assumptions:\n\n        * the normal direction is computed along the block index with size 2\n        * all point for a given sectionIndex lie within a plane\n\n        Parameters\n        ----------\n        sectionIndex : `i`, `j`, or `k`\n            This the index of the FFD which defines a section plane.\n\n        orient0 : None, `i`, `j`, `k`, or numpy vector. Default is None.\n            Although secIndex defines the '2' axis, the '0' and '1' axes are still\n            free to rotate within the section plane. We will choose the orientation\n            of the '0' axis and let '1' be orthogonal. See `addLocalSectionDV`\n            for a more detailed description.\n\n        ivol : integer\n            Volume ID for the volume in which section normals will be computed.\n\n        alignStreamwise : `x`, `y`, or `z` (optional)\n            If given, section frames are rotated about the k-plane normal\n            so that the longitudinal axis is parallel with the given streamwise\n            direction.\n\n        rootGlobal : list\n            List of sections along specified axis that will be fixed to the\n            global coordinate frame.\n\n        Returns\n        -------\n        sectionTransform : list of 3x3 arrays\n            List of transformation matrices for the sections of a given volume.\n            Transformations are set up from local section frame to global frame.\n        \"\"\"\n        # xyz_2_idx = {\"x\": 0, \"y\": 1, \"z\": 2}\n        ijk_2_idx = {\"i\": 0, \"j\": 1, \"k\": 2}\n        lIndex = self.FFD.topo.lIndex[ivol]\n\n        # Get normal index\n        orient0idx = False\n        orient0vec = False\n        if orient0 is not None:\n            if type(orient0) is str:\n                orient0 = ijk_2_idx[orient0.lower()]\n                orient0idx = True\n            elif type(orient0) is np.ndarray:\n                orient0vec = True\n            else:\n                raise Error(\"orient0 must be an index (i, j, or k) or a \" \"vector.\")\n        # Get section index and number of sections\n        sectionIndex = ijk_2_idx[sectionIndex.lower()]\n        nSections = lIndex.shape[sectionIndex]\n\n        # Roll lIndex so that 0th index is sectionIndex and 1st index is orient0\n        rolledlIndex = np.rollaxis(lIndex, sectionIndex, 0)\n        if orient0idx:\n            if orient0 != 2:\n                orient0 += 1\n            rolledlIndex = np.rollaxis(rolledlIndex, orient0, 1)\n\n        # Length of sectionTransform\n        Tcount = len(sectionTransform)\n\n        for i in range(nSections):\n            # Compute singular value decomposition of points in section (the\n            # U matrix should provide us with a pretty good approximation\n            # of the transformation matrix)\n            pts = self.FFD.coef[rolledlIndex[i, :, :]]\n            nJ, nI = pts.shape[:-1]\n            X = np.reshape(pts, (nI * nJ, 3))\n            c = np.mean(X, 0)\n            A = X - c\n            U, S, V = np.linalg.svd(A.T)\n\n            # Choose section plane normal axis\n            if orient2 == \"svd\":\n                ax2 = U[:, 2]\n            elif orient2 == \"ffd\":\n                # Use a centered FD approximation (first order at the boundaries)\n                if i == 0:\n                    pt = np.mean(self.FFD.coef[rolledlIndex[i, :, :]].reshape(nI * nJ, 3), 0)\n                    ptp = np.mean(self.FFD.coef[rolledlIndex[i + 1, :, :]].reshape(nI * nJ, 3), 0)\n                    ax2 = ptp - pt\n                elif i == nSections - 1:\n                    pt = np.mean(self.FFD.coef[rolledlIndex[i, :, :]].reshape(nI * nJ, 3), 0)\n                    ptm = np.mean(self.FFD.coef[rolledlIndex[i - 1, :, :]].reshape(nI * nJ, 3), 0)\n                    ax2 = pt - ptm\n                else:\n                    ptp = np.mean(self.FFD.coef[rolledlIndex[i + 1, :, :]].reshape(nI * nJ, 3), 0)\n                    ptm = np.mean(self.FFD.coef[rolledlIndex[i - 1, :, :]].reshape(nI * nJ, 3), 0)\n                    ax2 = ptp - ptm\n                ax2 /= np.linalg.norm(ax2)\n            else:\n                raise Error(\"orient2 must be 'svd' or 'ffd'\")\n\n            # Options for choosing in-plane axes\n            # 1. Align axis '0' with projection of the given vector on section\n            #       plane.\n            # 2. Align axis '0' with the projection of an average\n            #       difference vector between opposing edges of FFD block\n            #       section plane\n            # 3. Use the default SVD decomposition (in general this will work).\n            #       It will choose the chordwise direction as the best fit line\n            #       through the section points.\n            if orient0vec or orient0idx:\n                if orient0vec:\n                    u = orient0 / np.linalg.norm(orient0)\n                else:\n                    u = np.mean((pts[-1, :] - pts[0, :]), axis=0)\n                    u = u / np.linalg.norm(u)\n                ax0 = u - u.dot(ax2) * ax2\n                ax1 = np.cross(ax2, ax0)\n            else:\n                ax0 = U[:, 0]\n                ax1 = U[:, 1]\n\n            T = np.vstack((ax0, ax1, ax2)).T\n            sectionTransform.append(T)\n            # Designate section transformation matrix for each control point in\n            # section\n            sectionLink[rolledlIndex[i, :, :]] = Tcount\n            Tcount += 1\n\n            # Need to initialize coefRotM to identity matrix for case with no\n            # global design variables\n            for slice in rolledlIndex[i, :, :]:\n                for coef in slice:\n                    self.coefRotM[coef] = np.eye(3)\n\n        return nSections\n\n\nclass geoDVGlobal(object):\n    def __init__(self, dv_name, value, lower, upper, scale, function, config):\n        \"\"\"Create a geometric design variable (or design variable group)\n        See addGlobalDV in DVGeometry class for more information\n        \"\"\"\n        self.name = dv_name\n        self.value = np.atleast_1d(np.array(value)).astype(\"D\")\n        self.nVal = len(self.value)\n        self.lower = None\n        self.upper = None\n        self.config = config\n        self.function = function\n        if lower is not None:\n            self.lower = _convertTo1D(lower, self.nVal)\n        if upper is not None:\n            self.upper = _convertTo1D(upper, self.nVal)\n        if scale is not None:\n            self.scale = _convertTo1D(scale, self.nVal)\n\n    def __call__(self, geo, config):\n        \"\"\"When the object is called, actually apply the function\"\"\"\n        # Run the user-supplied function\n        d = np.dtype(complex)\n\n        if self.config is None or config is None or any(c0 == config for c0 in self.config):\n            # If the geo object is complex, which is indicated by .coef\n            # being complex, run with complex numbers. Otherwise, convert\n            # to real before calling. This eliminates casting warnings.\n            if geo.coef.dtype == d or geo.complex:\n                return self.function(self.value, geo)\n            else:\n                return self.function(np.real(self.value), geo)\n\n\nclass geoDVLocal(object):\n    def __init__(self, dvName, lower, upper, scale, axis, coefListIn, mask, config):\n\n        \"\"\"Create a set of geometric design variables which change the shape\n        of a surface surface_id. Local design variables change the surface\n        in all three axis.\n        See addLocalDV for more information\n        \"\"\"\n\n        coefList = []\n        # create a new coefficent list that excludes any values that are masked\n        for i in range(len(coefListIn)):\n            if not mask[coefListIn[i]]:\n                coefList.append(coefListIn[i])\n\n        N = len(axis)\n        self.nVal = len(coefList) * N\n        self.value = np.zeros(self.nVal, \"D\")\n        self.name = dvName\n        self.lower = None\n        self.upper = None\n        self.config = config\n        if lower is not None:\n            self.lower = _convertTo1D(lower, self.nVal)\n        if upper is not None:\n            self.upper = _convertTo1D(upper, self.nVal)\n        if scale is not None:\n            self.scale = _convertTo1D(scale, self.nVal)\n\n        self.coefList = np.zeros((self.nVal, 2), \"intc\")\n        j = 0\n\n        for i in range(len(coefList)):\n            if \"x\" in axis.lower():\n                self.coefList[j] = [coefList[i], 0]\n                j += 1\n            elif \"y\" in axis.lower():\n                self.coefList[j] = [coefList[i], 1]\n                j += 1\n            elif \"z\" in axis.lower():\n                self.coefList[j] = [coefList[i], 2]\n                j += 1\n\n    def __call__(self, coef, config):\n        \"\"\"When the object is called, apply the design variable values to\n        coefficients\"\"\"\n        if self.config is None or config is None or any(c0 == config for c0 in self.config):\n            for i in range(self.nVal):\n                coef[self.coefList[i, 0], self.coefList[i, 1]] += self.value[i].real\n\n        return coef\n\n    def updateComplex(self, coef, config):\n        if self.config is None or config is None or any(c0 == config for c0 in self.config):\n            for i in range(self.nVal):\n                coef[self.coefList[i, 0], self.coefList[i, 1]] += self.value[i].imag * 1j\n\n        return coef\n\n    def mapIndexSets(self, indSetA, indSetB):\n        \"\"\"\n        Map the index sets from the full coefficient indices to the local set.\n        \"\"\"\n        # Temp is the list of FFD coefficients that are included\n        # as shape variables in this localDV \"key\"\n        temp = self.coefList\n        cons = []\n        for j in range(len(indSetA)):\n            # Try to find this index # in the coefList (temp)\n            up = None\n            down = None\n\n            # Note: We are doing inefficient double looping here\n            for k in range(len(temp)):\n                if temp[k][0] == indSetA[j]:\n                    up = k\n                if temp[k][0] == indSetB[j]:\n                    down = k\n\n            # If we haven't found up AND down do nothing\n            if up is not None and down is not None:\n                cons.append([up, down])\n\n        return cons\n\n\ndef _convertTo1D(value, dim1):\n    \"\"\"\n    Generic function to process 'value'. In the end, it must be\n    array of size dim1. value is already that shape, excellent,\n    otherwise, a scalar will be 'upcast' to that size\n    \"\"\"\n\n    if np.isscalar:\n        return value * np.ones(dim1)\n    else:\n        temp = np.atleast_1d(value)\n        if temp.shape[0] == dim1:\n            return value\n        else:\n            raise Error(\"The size of the 1D array was the incorret shape\")\n\n\nclass geoDVSpanwiseLocal(geoDVLocal):\n    def __init__(self, dvName, lower, upper, scale, axis, vol_dv_to_coefs, mask, config):\n\n        \"\"\"Create a set of geometric design variables which change the shape\n        of a surface surface_id. Local design variables change the surface\n        in all three axis.\n        See addLocalDV for more information\n        \"\"\"\n\n        self.dv_to_coefs = []\n\n        # add all the coefs to a flat array, but check that it isn't masked first\n        for ivol in range(len(vol_dv_to_coefs)):\n            for loc_dv in range(len(vol_dv_to_coefs[ivol])):\n                coefs = vol_dv_to_coefs[ivol][loc_dv]\n\n                loc_dv_to_coefs = []\n\n                # loop through each of coefs to see if it is masked\n                for coef in coefs:\n                    if not mask[coef]:\n                        loc_dv_to_coefs.append(coef)\n\n                self.dv_to_coefs.append(loc_dv_to_coefs)\n\n        if \"x\" == axis.lower():\n            self.axis = 0\n        elif \"y\" == axis.lower():\n            self.axis = 1\n        elif \"z\" == axis.lower():\n            self.axis = 2\n        else:\n            raise NotImplementedError\n\n        self.nVal = len(self.dv_to_coefs)\n        self.value = np.zeros(self.nVal, \"D\")\n\n        self.name = dvName\n        self.lower = None\n        self.upper = None\n        self.config = config\n\n        if lower is not None:\n            self.lower = _convertTo1D(lower, self.nVal)\n        if upper is not None:\n            self.upper = _convertTo1D(upper, self.nVal)\n        if scale is not None:\n            self.scale = _convertTo1D(scale, self.nVal)\n\n    def __call__(self, coef, config):\n        \"\"\"When the object is called, apply the design variable values to\n        coefficients\"\"\"\n        if self.config is None or config is None or any(c0 == config for c0 in self.config):\n            for i in range(self.nVal):\n                coef[self.dv_to_coefs[i], self.axis] += self.value[i].real\n\n        return coef\n\n    def updateComplex(self, coef, config):\n        if self.config is None or config is None or any(c0 == config for c0 in self.config):\n            for i in range(self.nVal):\n                coef[self.dv_to_coefs[i], self.axis] += self.value[i].imag * 1j\n\n        return coef\n\n    def mapIndexSets(self, indSetA, indSetB):\n        \"\"\"\n        Map the index sets from the full coefficient indices to the local set.\n        \"\"\"\n\n        cons = []\n        for j in range(len(indSetA)):\n            # Try to find this index # in the coefList (temp)\n            up = None\n            down = None\n\n            # Note: We are doing inefficient double looping here\n            for idx_dv, coefs in enumerate(self.dv_to_coefs):\n\n                for coef in coefs:\n\n                    if coef == indSetA[j]:\n                        up = idx_dv\n                    if coef == indSetB[j]:\n                        down = idx_dv\n\n            # If we haven't found up AND down do nothing\n            if up is not None and down is not None:\n                cons.append([up, down])\n\n        return cons\n\n\nclass geoDVSectionLocal(object):\n    def __init__(self, dvName, lower, upper, scale, axis, coefListIn, mask, config, sectionTransform, sectionLink):\n        \"\"\"\n        Create a set of geometric design variables which change the shape\n        of a surface.\n        See `addLocalSectionDV` for more information\n        \"\"\"\n\n        self.coefList = []\n        # create a new coefficent list that excludes any values that are masked\n        for i in range(len(coefListIn)):\n            if not mask[coefListIn[i]]:\n                self.coefList.append(coefListIn[i])\n\n        self.nVal = len(self.coefList)\n        self.value = np.zeros(self.nVal, \"D\")\n        self.name = dvName\n        self.lower = None\n        self.upper = None\n        self.config = config\n        if lower is not None:\n            self.lower = _convertTo1D(lower, self.nVal)\n        if upper is not None:\n            self.upper = _convertTo1D(upper, self.nVal)\n        if scale is not None:\n            self.scale = _convertTo1D(scale, self.nVal)\n\n        self.sectionTransform = sectionTransform\n        self.sectionLink = sectionLink\n\n        self.axis = axis\n\n    def __call__(self, coef, coefRotM, config):\n        \"\"\"When the object is called, apply the design variable values to\n        coefficients\"\"\"\n        if self.config is None or config is None or any(c0 == config for c0 in self.config):\n            for i in range(len(self.coefList)):\n                T = self.sectionTransform[self.sectionLink[self.coefList[i]]]\n                inFrame = np.zeros(3)\n                inFrame[self.axis] = self.value[i].real\n\n                R = coefRotM[self.coefList[i]].real\n                coef[self.coefList[i]] += R.dot(T.dot(inFrame))\n        return coef\n\n    def updateComplex(self, coef, coefRotM, config):\n        if self.config is None or config is None or any(c0 == config for c0 in self.config):\n            for i in range(len(self.coefList)):\n                T = self.sectionTransform[self.sectionLink[self.coefList[i]]]\n                inFrame = np.zeros(3, \"D\")\n                inFrame[self.axis] = self.value[i]\n\n                R = coefRotM[self.coefList[i]]\n                coef[self.coefList[i]] += R.dot(T.dot(inFrame)).imag * 1j\n        return coef\n\n    def mapIndexSets(self, indSetA, indSetB):\n        \"\"\"\n        Map the index sets from the full coefficient indices to the local set.\n        \"\"\"\n        # Temp is the list of FFD coefficients that are included\n        # as shape variables in this localDV \"key\"\n        temp = self.coefList\n        cons = []\n        for j in range(len(indSetA)):\n            # Try to find this index # in the coefList (temp)\n            up = None\n            down = None\n\n            # Note: We are doing inefficient double looping here\n            for k in range(len(temp)):\n                if temp[k] == indSetA[j]:\n                    up = k\n                if temp[k] == indSetB[j]:\n                    down = k\n\n            # If we haven't found up AND down do nothing\n            if up is not None and down is not None:\n                cons.append([up, down])\n\n        return cons\n", "meta": {"hexsha": "718933829080484959d2188a9d94db8f2ce3df1b", "size": 183778, "ext": "py", "lang": "Python", "max_stars_repo_path": "pygeo/DVGeometry.py", "max_stars_repo_name": "kanekosh/pygeo", "max_stars_repo_head_hexsha": "5bd69ee47d9483d851bd2bfdc2a6135c94ad0343", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pygeo/DVGeometry.py", "max_issues_repo_name": "kanekosh/pygeo", "max_issues_repo_head_hexsha": "5bd69ee47d9483d851bd2bfdc2a6135c94ad0343", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pygeo/DVGeometry.py", "max_forks_repo_name": "kanekosh/pygeo", "max_forks_repo_head_hexsha": "5bd69ee47d9483d851bd2bfdc2a6135c94ad0343", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3021929825, "max_line_length": 130, "alphanum_fraction": 0.552596067, "include": true, "reason": "import numpy,from scipy", "num_tokens": 43412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.19202965806613517}}
{"text": "import sys\nimport csv\nimport collections\nimport math\nimport numpy as np\nimport pandas as pd\n\ndef delete_false_co(codict,mdict):\n    '''Remove false positive crossover events\n    based on nTypedBetween and return filtered\n    dict.\n    '''\n    print(\"Crossovers before filtering: \" + str(len(codict)))\n    # Use set as there can be quadruple crossovers\n    # This leads to duplicate bad keys\n    bad_keys = set()\n    for key, value in codict.items():\n        #nTypedBetween \n        ntb = value[9]\n        ind = value[1]\n        genpos = value[2]\n        # Skip last CO for individual\n        # These can't be used for filtering\n        if ntb != \"NA\":\n            chr_pos1 = value[0] + \"_\" + value[3]\n            co_index1 = codict.keys().index(key)\n            # Get following crossover entry\n            co_index2 = co_index1 + 1\n            co_key2 = list(codict)[co_index2]\n            chr_pos2 = codict[co_key2][0] + \"_\" + codict[co_key2][3]\n\n            #Physical marker positions\n            phypos1 = mdict[chr_pos1].split(\"_\")[1]\n            phypos2 = mdict[chr_pos2].split(\"_\")[1]\n            phychr1 = mdict[chr_pos1].split(\"_\")[0]\n            phychr2 = mdict[chr_pos2].split(\"_\")[0]\n            if phychr1 == phychr2:\n                phydist = int(phypos2) - int(phypos1)\n                # Use absolute numbers\n                phydist = abs(phydist)\n            else:\n                # If adjacent marker is from different chromosome\n                # Set arbitrary high physical distance\n                phydist = 1000000\n            # Genetic distance between breakpoints           \n            gendist = float(codict[co_key2][2]) - float(genpos)\n           # Recombinations separated by less than 5 markers are false\n           # Recombinations <10kb are considered gene conversions\n            if int(ntb) < 5 or phydist < 10000 or gendist < 0.02:\n                co_index1 = codict.keys().index(key)\n                # Get following crossover entry\n                co_index2 = co_index1 + 1\n                co_key2 = list(codict)[co_index2]\n                bad_keys.add(key)\n                if ind == codict[co_key2][1]:\n                    bad_keys.add(co_key2)\n                else:\n                    print(\"Aborted. Expected paired false positives.\")\n                    break\n    # delete all the bad entries\n    for bkey in bad_keys:\n        codict.pop(bkey, None) \n    print(\"Crossovers after filtering: \" + str(len(codict)))\n    return codict\n\n# Read marker positions and crossover into dicts\n# These tables are generated with r/qtl locateXO and a custom script\n\ncrossovers = sys.argv[1] \n# Example of head -2 of input file:\n#chr,IND,location,left,right,ileft,iright,gleft,gright,nTypedBetween\n#A01,1,111.50960844248,109.290254466964,113.728962417996,402,403,3,2,323\n\nmarkers = sys.argv[2]\n# Example of head -3 of input file:\n#chr,name,value\n#A01,A01_3072290,0\n#A01,A01_3071845,1.35449890934482\n\n# Values in the markers file are genetic map positions in cM\n\nwith open(crossovers, mode='r') as co:\n    reader1 = csv.reader(co)\n    next(reader1, None)\n    # Use chr_ind_pos as unique key and all row as values\n    codict = collections.OrderedDict((row[0] + \"_\" + row[1] + \"_\" + row[2], row[0:]) for row in reader1)\nwith open(markers, mode='r') as mark:\n    reader2 = csv.reader(mark)\n    next(reader2, None)\n    mdict = collections.OrderedDict((row[0] + \"_\" + row[2], row[1]) for row in reader2)\n\n# Filter false positive CO\nfiltdict = delete_false_co(codict,mdict)\n# Physical distances between CO\nind_list = []\nco = {}\nfor key, value in filtdict.items():\n    ind = value[1]\n    chrom = value[0]\n    lchrpos = value[0] + \"_\" + value[3]\n    lphypos = mdict[lchrpos].split(\"_\")[1]\n    lphychr = mdict[lchrpos].split(\"_\")[0]\n    rchrpos = value[0] + \"_\" + value[4]\n    rphypos = mdict[rchrpos].split(\"_\")[1]\n    rphychr = mdict[rchrpos].split(\"_\")[0]\n    \n    if rphychr == chrom and lphychr == chrom:\n        breakpoint = int((int(lphypos) + int(rphypos)) / 2)\n        if chrom in co:\n            # append CO to list\n            breaklist = co[chrom]\n            breaklist.append(breakpoint)\n            co[chrom] = breaklist\n        else:\n            co[chrom] = [breakpoint]\n\n    ind_list.append(ind)\n\n# CO counts per individual\ncounter=collections.Counter(ind_list)\nind_list = []\nfrq = []\nfor ind in counter.most_common():\n    ind_list.append(ind[0])\n    frq.append(ind[1])\ninddf = pd.DataFrame({'Ind' : ind_list, 'CO' : frq})\ninddf.sort_values(['Ind'], ascending=True, axis=0,inplace=True)\ninddf.to_csv('Individual_CO_Frequency.csv', index=False, encoding='utf-8', columns=['Ind','CO'])\n\n# Histogram of CO across chromsomes\nchromlist = []\nhistlist = []\nbinlist = []\n\nfor key, value in co.items():\n    chrom = key\n    breakpoints = np.array(value)\n    # Round highest position up to nearest 500kb\n    toprange = math.ceil(breakpoints.max() / 500000.0) * 500000.0\n    # Number of bins\n    binnum = int(toprange / 500000.0)\n    # Calculate histogram\n    hist,bins = np.histogram(breakpoints,bins=binnum,range=(0, toprange))\n    histlist.extend(np.ndarray.tolist(hist))\n    bins_tidy = np.ndarray.tolist(bins)[:-1]\n    binlist.extend(bins_tidy)\n    for bin in bins_tidy:\n        chromlist.append(chrom)\ncodf = pd.DataFrame({'Chr' : chromlist, 'Bin' : binlist, 'Histogram' : histlist})\ncodf.sort_values(['Chr', 'Bin'], ascending=True, axis=0,inplace=True)\ncodf.to_csv('CO_hist.csv', index=False, encoding='utf-8', columns=['Chr','Bin','Histogram'])\n", "meta": {"hexsha": "aef2f5cde06004b3e833a00508ee952e4e774738", "size": 5468, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/crossover.py", "max_stars_repo_name": "ascheben/bn_gbs", "max_stars_repo_head_hexsha": "cb70234e81874392f041ac51f7cb695ce183e252", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/crossover.py", "max_issues_repo_name": "ascheben/bn_gbs", "max_issues_repo_head_hexsha": "cb70234e81874392f041ac51f7cb695ce183e252", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/crossover.py", "max_forks_repo_name": "ascheben/bn_gbs", "max_forks_repo_head_hexsha": "cb70234e81874392f041ac51f7cb695ce183e252", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9736842105, "max_line_length": 104, "alphanum_fraction": 0.6181419166, "include": true, "reason": "import numpy", "num_tokens": 1535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.19202965429805816}}
{"text": "#!/usr/bin/python3\n\n\"\"\"Projection class\nImplements a class for 2D phantoms. The Golosio phantom is coded in terms of\ngeometry and composition data, with class methods supplied to instantiate it.\nAlternatively, phantoms can be defined as a pair of files, one containing\ngeometry data as a greyscale bitmap and the other containing the composition\ndata structure defined in a yaml file.\n\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\nfrom . import config\nimport logging\nimport os\nimport glob\nimport fnmatch\nfrom progressbar import ProgressBar\n\nimport numpy as np\nfrom numpy import exp, pi\nimport scipy.constants as sc\nfrom scipy.special import expm1\nimport matplotlib.pyplot as plt\nimport xraylib as xrl\n\nfrom . import helpers\nfrom .helpers import write_tiff32, zero_outside_circle, rotate, imshow\nfrom .data_helpers import MatrixProperties\n\nlogger = logging.getLogger(__name__)\n\n\nUM_PER_CM = 1e4\nJ_PER_KEV = 1e3 * sc.eV\ndeg_to_rad = lambda x: x / 180. * pi\nrad_to_deg = lambda x: x * 180. / pi\n\n# maia_d = Maia()  # Maia detector object (should be a singleton)\n\n\ndef absorption_sinogram(p, anglelist):\n    \"\"\"Generates the absorption sinogram for absorption by the full\n    elemental content of the Phantom2d object.\n\n    Parameters\n    ----------\n    p : Phantom2d object\n    anglelist : list of float\n        Ordered list of sinogram projection angles in degrees.\n\n    Returns\n    -------\n    array of float\n        Sinogram of requested scattering or fluorescence.\n        This is a 2d x-theta map of dimensionless values.\n\n    \"\"\"\n    sinogram = np.empty((p.cols, len(anglelist)))\n    if config.show_progress:\n        pbar = ProgressBar(maxval=max(1, len(anglelist)-1), term_width=80).start()\n    for i, angle in enumerate(anglelist):\n        if config.show_progress:\n            pbar.update(i)\n\n        increasing_ix = True   # Set True to accumulate cmam along increasing y\n        n_map = irradiance_map(p, angle, n0=1.0, increasing_ix=increasing_ix)\n        if increasing_ix:\n            sinogram[:, i] = np.log(n_map[0] / n_map[-1])\n        else:\n            sinogram[:, i] = np.log(n_map[-1] / n_map[0])\n    return sinogram\n\n\ndef outgoing_cmam(p, q, maia_d, angle, energy, increasing_ix=True):\n    \"\"\"Compute and return the outgoing cumulative multiplicative absorption map\n    (cmam), aka xi'.\n\n    Parameters\n    ----------\n    p : Phantom2d object\n        p.energy - incident beam photon energy (keV).\n        p.um_per_px - length of one pixel of the map (um).\n    q : int\n        Maia detector channel id\n    maia_d : Maia() instance\n    angle : float\n        Tomography projection angle (degree)\n    energy : float\n        outgoing radiation energy (keV)\n    increasing_ix : bool, optional\n        If False, performs cumulative sum in opposite direction (in direction of\n        decreasing y-index). Note, for the standard Radon transform,\n        this direction is unimportant, but for the Radon transform with\n        attenuation, we should project in the beam propagation direction.\n        (default True).\n\n    Returns\n    -------\n    2d ndarray of float\n        cumulative multiplicative absorption map.\n\n    \"\"\"\n    # The linear absorption map mu = ma_M * mu_M + sum_k ( ma_k * mu_k )\n    mu = p.matrix.ma(energy) * p.el_maps['matrix']\n    for el in p.el_maps:\n        if el == 'matrix':\n            continue\n        Z = xrl.SymbolToAtomicNumber(el)\n        mu += xrl.CS_Total(Z, energy) * p.el_maps[el]\n\n    # project at angle theta by rotating the phantom by angle -theta and\n    # projecting along the z-axis (along columns)\n\n    # rotate by the sum of the projection angle and local detector angle\n    # Get angle to rotate maps so that propagation toward detector plane\n    # corresponds with direction to maia detector element\n    phi_x = maia_d.pads[q].angle_X_rad\n    phix_deg = rad_to_deg(phi_x)\n\n    # Apply local rotation, accumulation and rotation operators\n\n    # Apply R_{-theta} operator to mu\n    # Apply R_{-phi} operator\n    mu = rotate(mu, angle + 180 - phix_deg)\n\n    saveflag = np.isclose(angle, config.cmam_angle_save) and config.save_projection_images\n    if saveflag:\n        path = os.path.join(config.mlem_im_path, 'project_cmam1_%03d.tif' % config.i)\n        helpers.write_tiff32(path, mu)\n\n    # Apply C_z operator\n    if increasing_ix:\n        mu = np.cumsum(mu, axis=0)\n    else:\n        mu = np.cumsum(mu[::-1], axis=0)[::-1]\n\n    if saveflag:\n        path = os.path.join(config.mlem_im_path, 'project_cmam2_%03d.tif' % config.i)\n        helpers.write_tiff32(path, mu)\n\n    # Apply R_{phi} operator\n    mu = rotate(mu, 180 + phix_deg)\n    t = p.um_per_px / UM_PER_CM\n\n    if saveflag:\n        path = os.path.join(config.mlem_im_path, 'project_cmam3_%03d.tif' % config.i)\n        helpers.write_tiff32(path, mu)\n\n    phi = maia_d.pads[q].out_of_xz_plane_angle\n    cmam = mu * t / np.cos(phi)\n    return cmam\n\n\ndef project_sinogram(event_type, p, q, maia_d, anglelist, el=None):\n    \"\"\"Generates the sinogram of the requested element accounting for\n    absorption by the Phantom2d composition and the geometry.\n\n    Parameters\n    ----------\n    event_type : string\n        One of ['rayleigh', 'compton', 'fluoro'].\n    p : Phantom2d object\n        p.energy - incident beam photon energy (keV).\n        p.um_per_px - length of one pixel of the map (um).\n    q : int\n        Maia detector channel id\n    maia_d : Maia() instance\n    anglelist : list of float\n        Ordered list of sinogram projection angles in degrees.\n    el : string, optional\n        Name of element (e.g. 'Fe') used if projecting that element's\n        fluorescence.\n\n    Returns\n    -------\n    array of float\n        Sinogram of requested scattering or fluorescence.\n\n    \"\"\"\n    assert event_type in ['rayleigh', 'compton', 'fluoro']\n\n    sinogram = np.empty((p.cols, len(anglelist)))\n    if config.show_progress:\n        if len(anglelist) > 1:\n            pbar = ProgressBar(maxval=len(anglelist)-1).start()\n        else:\n            pbar = ProgressBar(maxval=1).start()\n    for i, angle in enumerate(anglelist):\n        if config.show_progress:\n            pbar.update(i)\n\n        increasing_ix = True   # Set True to accumulate cmam along increasing y\n        n_map = irradiance_map(p, angle, n0=1.0, increasing_ix=increasing_ix)\n        e_map = channel_fluoro_map(p, q, maia_d, n_map, angle, el)\n        energy = outgoing_photon_energy(event_type, p, q, maia_d, el)\n        c = outgoing_cmam(p, q, maia_d, angle, energy, increasing_ix=increasing_ix)\n        if config.no_out_absorption:\n            sinogram[:, i] = e_map.sum(axis=0)\n        else:\n            sinogram[:, i] = (e_map * np.exp(-c)).sum(axis=0)\n\n        if i == config.angle_save_index and config.save_projection_images:\n            path = os.path.join(config.mlem_im_path, 'project_%s_map_%03d.tif' % (el, config.i))\n            helpers.write_tiff32(path, p.el_maps[el])\n            path = os.path.join(config.mlem_im_path, 'project_n_map_%03d.tif' % config.i)\n            helpers.write_tiff32(path, n_map)\n            path = os.path.join(config.mlem_im_path, 'project_e_map_%03d.tif' % config.i)\n            helpers.write_tiff32(path, e_map)\n            path = os.path.join(config.mlem_im_path, 'project_c_map_%03d.tif' % config.i)\n            helpers.write_tiff32(path, c)\n\n    return sinogram\n\n\ndef irradiance_map(p, angle, n0=1.0, increasing_ix=True, matrix_only=False):\n    \"\"\"Generates the image-sized map of irradiance [1/(cm2 s)] at each 2d pixel\n    for a given angle accounting for absorption at the incident energy by the\n    full elemental distribution.\n    Note: In the full biological approximation, where we only need to consider absorption by\n    the matrix and not by the full elemental composition, we could cache this result,\n    possibly by adding the memoization decorator I use in Sakura here:\n    https://github.com/AustralianSynchrotron/Sakura/blob/master/utils.py\n    https://github.com/AustralianSynchrotron/Sakura/blob/master/memoize_core.py\n\n    Parameters\n    ----------\n    p : phantom object\n        p.energy - incident beam energy (keV)\n        p.um_per_px - length of one pixel of the map (um)\n    angle : float\n        tomography angle in degrees. The rotation axis is the y-axis in a conventional xyz\n        right-handed coordinate system, so positive rotation in the xz-plane is ccw. i.e.\n        with y(out-of-page) o--> x\n                            |\n                            v\n                            z\n        therefore, using our rotate function, which assumes 2d rotation\n    n0 : float\n        incident irradiance (default 1.0).\n    increasing_ix : bool, optional\n        If False, performs cumulative sum in opposite direction (in direction of\n        decreasing y-index). Note, for the standard Radon transform,\n        this direction is unimportant, but for the Radon transform with\n        attenuation, we should project in the beam propagation direction.\n        (default True).\n    matrix_only : bool, optional\n        If True, the map only considers the matrix and doesn't consider the\n        other elements in the model.\n        (default False).\n\n    Returns\n    -------\n    2d ndarray of float\n        The irradiance map.\n\n    \"\"\"\n    # matrix_map = zero_outside_circle(p.el_maps['matrix'])\n\n    # The linear absorption map mu0 = ma_M * mu_M + sum_k ( ma_k * mu_k )\n    mu0 = p.matrix.ma(p.energy) * p.el_maps['matrix']\n    if not config.absorb_with_matrix_only:\n        for el in p.el_maps:\n            if el == 'matrix':\n                continue\n            Z = xrl.SymbolToAtomicNumber(el)\n            mu0 += xrl.CS_Total(Z, p.energy) * p.el_maps[el]\n\n    # project at angle theta by rotating the phantom by angle -theta and\n    # projecting along the z-axis (along columns)\n    im = rotate(mu0, angle)     # rotate by angle degrees ccw\n    t = p.um_per_px / UM_PER_CM\n    # accumulate along z-axis (image defined in xz-coordinates, so accumulate\n    # along image rows), consistent with matlab sinogram convention.\n    # See http://www.mathworks.com/help/images/radon-transform.html\n    if increasing_ix:\n        cmam = t * np.cumsum(im, axis=0)\n    else:\n        cmam = t * np.cumsum(im[::-1], axis=0)[::-1]\n    if config.no_in_absorption:\n        n_map = n0 + np.zeros_like(cmam)\n    else:\n        n_map = n0 * exp(-cmam)\n    return n_map\n\n'''\ndef scattering_ma(event_type, p, maia_d, row, col):\n    \"\"\"Return the Rayleigh or Compton differential mass attenuation coefficients\n    (cm2/g/sr) for icru44 brain tissue with density described by the 'matrix'\n    map of phantom p into the Maia detector element indexed by row, col. This\n    needs to be multiplied later by the Maia-channel-dependent solid angle.\n\n    Arguments:\n    event_type - string, one of ['rayleigh', 'compton']\n    p - phantom instance (matrix plus elements)\n    maia_d - Maia instance\n\n    row, col - maia detector element indices\n\n    Returns:\n    The (rayleigh, compton) differential mass attenuation coefficient\n\n    \"\"\"\n    assert event_type in ['rayleigh', 'compton']\n\n    # Get spherical angles (polar theta & azimuthal phi) to detector element\n    theta = maia_d.pads[q].theta\n    phi = maia_d.pads[q].phi\n\n    compound = p.matrix.cp  # elemental data for matrix compound\n\n    # Get the contribution to Rayleigh and Compton scattering from each\n    # element in the matrix compound and sum these.\n    ma = 0.0\n    for el in compound:\n        # Assuming propagation along z, coordinate system used by the DCSP_Rayl\n        # and DCSP_Compt methods is shown here:\n        # http://upload.wikimedia.org/wikipedia/commons/thumb/4/4f/\n        # 3D_Spherical.svg/200px-3D_Spherical.svg.png\n        # i.e. spherical coordinates with polar angle theta, azimuthal angle phi\n        z = xrl.SymbolToAtomicNumber(compound[el])\n\n        # Mass attenuation coefficients from cross-sections. See\n        # http://physics.nist.gov/PhysRefData/XrayMassCoef/chap2.html\n        # Units of the following expression:\n        # elemental fraction by weight * differential mass attenuation coefft\n        # unitless * cm2/g/sr\n        if event_type == 'rayleigh':\n            f = xrl.DCSP_Rayl\n        else:\n            f = xrl.DCSP_Compt\n        ma += compound[el] * f(z, p.energy, theta, phi)\n    return ma\n\n\ndef compton_scattered_energy(energy_in, q, maia_d):\n    \"\"\"Energy of the Compton photons scattered into the direction of the Maia\n    detector element.\n\n    Parameters\n    ----------\n    energy_in : float\n        Incident beam photon energy (keV).\n    q : int\n        Maia detector channel id\n    maia_d : Maia instance\n\n    Returns\n    -------\n    float\n        Energy of scattered photons (keV)\n\n    \"\"\"\n    # Get polar scattering angle (theta) to detector element\n    # Get spherical angles (polar theta & azimuthal phi) to detector element\n    theta = maia_d.pads[q].theta\n\n    # energy_out = 1.0 / (1.0/energy_in +\n    # (1 - np.cos(theta))*J_PER_KEV/sc.m_e/sc.c/sc.c)\n    return xrl.ComptonEnergy(energy_in, theta)\n'''\n\n'''\ndef old_emission_map(event_type, p, n_map, angle, el=None):\n    \"\"\"Compute the maia-detector-shaped map of Rayleigh, Compton or K-edge\n    fluorescence from the element map for an incident irradiance map n_map.\n\n    Parameters\n    ----------\n    event_type : string\n        One of ['rayleigh', 'compton', 'fluoro'].\n    p : Phantom2d object\n        p.energy - incident beam photon energy (keV).\n        p.um_per_px - length of one pixel of the map (um).\n    n_map : 2d ndarray of float\n        Map of incident irradiance.\n    angle : float\n        Stage rotation angle (degrees).\n    el : string, optional\n        Name of element (e.g. 'Fe') used if projecting that element's\n        fluorescence.\n\n    Returns\n    -------\n    1d ndarray of float\n        The accumulated flux in Maia detector row 7 for the requested edge.\n\n    \"\"\"\n    assert event_type in ['rayleigh', 'compton', 'fluoro']\n\n    # Get matrix map and, for fluorescence, the map for the requested element,\n    # and rotate them to the same angle as the intensity map since these all\n    # need to be in registration.\n    matrix_map = zero_outside_circle(p.el_maps['matrix'])\n    matrix_map_r = rotate(matrix_map, -angle)\n    del matrix_map\n\n    k_alpha_energy = -1\n    if event_type == 'fluoro':\n        edge_map = zero_outside_circle(p.el_maps[el])\n        edge_map_r = rotate(edge_map, -angle)\n        del edge_map\n\n        # Do this here because we're outside the detector channel loop.\n        # Get Z for the fluorescing element and check that its K_alpha is\n        # below the incident energy.\n        el_z = xrl.SymbolToAtomicNumber(el)\n        line = xrl.KA_LINE\n        k_alpha_energy = xrl.LineEnergy(el_z, line)\n        assert k_alpha_energy < p.energy\n\n    # 2d accumulator for results\n    accumulator = np.empty((maia_d.shape[1], n_map.shape[0]))\n\n    # Iterate over maia detector elements in theta, i.e. maia columns\n    # This should be parallelizable\n    row = 7\n    # Get multiplication factor for additional distance that an outgoing photon\n    # must travel as it passes out-of-plane to the detector.\n    delta_theta_yx_radian = maia_d.yx_angles_radian(row, col=0)\n    delta_theta_y_radian = delta_theta_yx_radian[0]\n    y_distance_factor = 1.0 / np.cos(delta_theta_y_radian)\n\n    for channel_id in maia_d.channel_selection(row=row):\n        col = maia_d.maia_data_column_from_id(channel_id, 'Column')\n        # Get angle to rotate maps so that propagation toward detector plane\n        # corresponds with direction to maia detector element\n        delta_theta_yx_radian = maia_d.yx_angles_radian(row, col)\n        delta_theta_x = rad_to_deg(delta_theta_yx_radian[1])\n\n        # For every maia detector element, get the solid angle (parallelize?)\n        # Orient the maps toward the maia element\n        # TODO: check sign of delta: +ve or -ve?\n        imap_rm = rotate(n_map, -delta_theta_x)\n        matrix_map_rm = rotate(matrix_map_r, -delta_theta_x)\n\n        # Rotate the geometry so that the detector is on the bottom, so we can\n        # integrate by stepping through the row indices.\n        imap_rm = np.rot90(imap_rm)\n        matrix_map_rm = np.rot90(matrix_map_rm)\n\n        # Solid angle of Maia channel\n        omega = maia_d.solid_angle(row, col)\n\n        # mass attenuation coefft. (cm2/g)\n        if event_type == 'fluoro':\n            edge_map_rm = rotate(edge_map_r, -delta_theta_x)\n            edge_map_rm = np.rot90(edge_map_rm)\n\n            # Simulate fluorescence event:\n            # Generate the initial fluorescence intensity\n            # Start with the highest-energy edge or a mean factor accounting for\n            # all edges first (move to other edges later?)\n            mac = fluoro_ma(p, el_z)\n\n            # Scale for propagation over one voxel\n            # *_mac_t = *_mac * p.um_per_px/UM_PER_CM\n            # (cm3/g/sr) =   (cm2/g/sr) * cm\n            mac_t = mac * p.um_per_px / UM_PER_CM * y_distance_factor\n            # Generate outgoing radiation.\n            # This is the fluorescence intensity map.\n            imap_rm *= -expm1(-edge_map_rm * omega * mac_t)\n            del edge_map_rm\n        else:\n            mac = scattering_ma(event_type, p, row, col)\n            mac_t = mac * p.um_per_px / UM_PER_CM * y_distance_factor\n            # Generate outgoing radiation.\n            # This is the scattering radiation intensity map.\n            imap_rm *= -expm1(-matrix_map_rm * omega * mac_t)\n\n        # Now we've \"evented,\" we use the mass attenuation coefficients of the\n        # matrix for propagation with absorption out to the detector, but this\n        # is at a new energy depending on the event type.\n        energy = {\n            'rayleigh': p.energy,\n            'compton': compton_scattered_energy(p.energy, row, col),\n            'fluoro': k_alpha_energy,\n        }[event_type]\n        mac_t = brain.ma(energy) * p.um_per_px / UM_PER_CM * y_distance_factor\n\n        # Propagate all intensity to the detector, accumulating (+) and\n        # absorbing [exp(-mu/rho rho t)] as we go.\n        cmam_matrix = np.cumsum(matrix_map_rm, axis=0) * mac_t\n        i_out = (imap_rm * exp(-cmam_matrix * omega)).sum(axis=0)\n\n        # Store the result for this detector element.\n        accumulator[col] = i_out\n\n    return accumulator\n'''\n\n\ndef outgoing_photon_energy(event_type, p, q=None, maia_d=None, el=None):\n    \"\"\"Return the interaction-type-dependent outgoing photon energy in keV.\n\n    Parameters\n    ----------\n    event_type : string\n        One of ['rayleigh', 'compton', 'fluoro'].\n    p : Phantom2d object\n        p.energy - incident beam photon energy (keV).\n        p.um_per_px - length of one pixel of the map (um).\n    q : int (optional, required for compton interaction)\n        Maia detector channel id\n    maia_d : Maia() instance (optional, required for compton interaction)\n    el : string (optional, required for fluoro interaction)\n        Name of fluorescing element (e.g. 'Fe').\n\n    Returns\n    -------\n    float\n        Outgoing photon energy (keV)\n\n    \"\"\"\n    assert event_type in ['rayleigh', 'compton', 'fluoro']\n\n    def k_alpha_energy(el):\n        el_z = xrl.SymbolToAtomicNumber(el)\n        line = xrl.KA_LINE\n        energy = xrl.LineEnergy(el_z, line)\n        # assert energy < p.energy\n        return energy\n\n    '''\n    if event_type == 'rayleigh':\n        energy = p.energy\n    elif event_type == 'compton':\n        energy = compton_scattered_energy(p.energy, q, maia_d)\n    else:           # 'fluoro'\n    '''\n    if True:        # Just support 'fluoro' for now\n        energy = k_alpha_energy(el)\n\n    return energy\n\n\ndef fluoro_emission_map(p, n_map, angle, el):\n    \"\"\"Compute the maia-detector-shaped map of K-edge\n    fluorescence from the element map for an incident irradiance map n_map.\n\n    Parameters\n    ----------\n    p : Phantom2d object\n        p.energy - incident beam photon energy (keV).\n        p.um_per_px - length of one pixel of the map (um).\n    n_map : 2d ndarray of float\n        Map of incident irradiance.\n    angle : float\n        Stage rotation angle (degrees).\n    el : string\n        Name of fluorescing element (e.g. 'Fe').\n\n    Returns\n    -------\n    2d ndarray of float\n        The fluorescence emission map for the requested edge.\n\n    \"\"\"\n    # edge_map = zero_outside_circle(p.el_maps[el])\n    edge_map = p.el_maps[el]\n    edge_map_r = rotate(edge_map, angle)\n    del edge_map\n\n    # Get Z for the fluorescing element\n    el_z = xrl.SymbolToAtomicNumber(el)\n    line = xrl.KA_LINE\n\n    # Sanity check that el K_alpha is below the incident energy.\n    k_alpha_energy = xrl.LineEnergy(el_z, line)\n    # assert k_alpha_energy < p.energy\n    if k_alpha_energy >= p.energy:\n        Q = 0.0\n    else:\n        # Simulate fluorescence event:\n        # CS_FluorLine_Kissel_Cascade is the XRF cross section Q_{i,YX} in Eq. (12)\n        # of Schoonjans et al.\n        Q = xrl.CS_FluorLine_Kissel_Cascade(el_z, line, p.energy)\n        # print(el, end=' ')\n\n    # 2d array for results\n    emission_map = n_map * Q * edge_map_r * p.um_per_px / UM_PER_CM\n\n    return emission_map\n\n\ndef channel_emission_map(event_type, p, q, maia_d, n_map, angle, el):\n    \"\"\"Select and defer to the interaction-type-specific emission map\n    computation.\n\n    Parameters\n    ----------\n    event_type : string\n        One of ['rayleigh', 'compton', 'fluoro'].\n    p : Phantom2d object\n        p.energy - incident beam photon energy (keV).\n        p.um_per_px - length of one pixel of the map (um).\n    q : int\n        Maia detector channel id\n    maia_d : Maia() instance\n    n_map : 2d ndarray of float\n        Map of incident irradiance.\n    angle : float\n        Stage rotation angle (degrees).\n    el : string\n        Name of fluorescing element (e.g. 'Fe').\n\n    Returns\n    -------\n    2d ndarray of float\n        The fluorescence emission map for the requested edge.\n\n    \"\"\"\n    assert event_type in ['rayleigh', 'compton', 'fluoro']\n\n    if event_type == 'fluoro':\n        e_map = channel_fluoro_map(p, q, maia_d, n_map, angle, el)\n    elif event_type == 'rayleigh':\n        e_map = channel_rayleigh_map(p, q, maia_d, n_map, angle)\n    elif event_type == 'compton':\n        e_map = channel_compton_map(p, q, maia_d, n_map, angle)\n    else:\n        raise RuntimeError('Brain explodes')\n\n    return e_map\n\n\ndef channel_fluoro_map(p, q, maia_d, n_map, angle, el):\n    \"\"\"Compute the maia-detector-shaped map of K-edge\n    fluorescence from the element map for an incident irradiance map n_map.\n\n    Parameters\n    ----------\n    p : Phantom2d object\n        p.energy - incident beam photon energy (keV).\n        p.um_per_px - length of one pixel of the map (um).\n    q : int\n        Maia detector channel id\n    maia_d : Maia instance\n    n_map : 2d ndarray of float\n        Map of incident irradiance.\n    angle : float\n        Stage rotation angle (degrees).\n    el : string\n        Name of fluorescing element (e.g. 'Fe').\n\n    Returns\n    -------\n    2d ndarray of float\n        The fluorescence emission map for the requested edge.\n\n    \"\"\"\n    solid_angle = maia_d.pads[q].omega\n    return (solid_angle / 4 / np.pi *\n            fluoro_emission_map(p, n_map, angle, el))\n\n\ndef channel_rayleigh_map(p, q, maia_d, n_map, angle):\n    \"\"\"Compute the maia-detector-shaped map of Rayleigh scattering\n    from the element map for an incident irradiance map n_map.\n\n    Parameters\n    ----------\n    p : Phantom2d object\n        p.energy - incident beam photon energy (keV).\n        p.um_per_px - length of one pixel of the map (um).\n    q : int\n        Maia detector channel id\n    maia_d : Maia() instance\n    n_map : 2d ndarray of float\n        Map of incident irradiance.\n    angle : float\n        Stage rotation angle (degrees).\n\n    Returns\n    -------\n    2d ndarray of float\n        The fluorescence emission map for the requested edge.\n\n    \"\"\"\n    solid_angle = maia_d.pads[q].omega\n\n    # Get spherical angles (polar theta & azimuthal phi) to detector element\n    theta = maia_d.pads[q].theta\n    phi = maia_d.pads[q].phi\n\n    energy = outgoing_photon_energy('rayleigh', p)\n\n    # get a list of all elements el and their weights w_el\n\n    # The absorption map mu = ma_M * mu_M + sum_k ( ma_k * mu_k )\n    mu = p.matrix.ma(energy) * p.el_maps['matrix']\n    for el in p.el_maps:\n        if el == 'matrix':\n            continue\n        Z = xrl.SymbolToAtomicNumber(el)\n        mu += p.matrix.cp[el] * xrl.DCSP_Rayl(Z, energy, theta, phi) * \\\n              p.el_maps[el]\n\n    ma += xrl.DCSP_Rayl(Z, energy, theta, phi)\n\n    # edge_map = zero_outside_circle(p.el_maps[el])\n    edge_map_r = rotate(edge_map, angle)\n    del edge_map\n\n    # Get Z for the fluorescing element\n    el_z = xrl.SymbolToAtomicNumber(el)\n    line = xrl.KA_LINE\n\n    # Sanity check that el K_alpha is below the incident energy.\n    k_alpha_energy = xrl.LineEnergy(el_z, line)\n    assert k_alpha_energy < p.energy\n\n    # Simulate fluorescence event:\n    # CS_FluorLine_Kissel_Cascade is the XRF cross section Q_{i,YX} in Eq. (12)\n    # of Schoonjans et al.\n    Q = xrl.CS_FluorLine_Kissel_Cascade(el_z, line, p.energy)\n\n    # 2d array for results\n    emission_map = n_map * Q * edge_map_r * p.um_per_px / UM_PER_CM\n\n    return emission_map\n\n\ndef write_sinogram(im, p, event_type, el='matrix'):\n    \"\"\"Project and write sinogram for element map el\n    Creates a filename by prepending s_ to the filename and appending r or c\n    if writing the rayleigh or compton sinogram, respectively.\n\n    Parameters\n    ----------\n    im : 2d ndarray of float\n        sinogram.\n    p : Phantom2d object\n    event_type : string\n        One of ['absorption', 'rayleigh', 'compton', 'fluoro'].\n    el : string\n        name of current element, e.g. 'Fe'. (default 'matrix').\n\n    \"\"\"\n    # Get the filename that matches the glob pattern for this element\n    # and prepend s_ to it\n    pattern = p.filename\n\n    matches = helpers.match_pattern(pattern, glob.glob(pattern))\n    if matches:\n        # Just get the filename that's a match for the element el\n        match_base = [m[0] for m in matches if el==m[1]][0]\n    else:\n        raise Exception('Element {} not found in {}'.format(el, matches))\n    path = os.path.dirname(pattern)\n    base = os.path.basename(match_base)\n    s_filename = os.path.join(path, 's_'+base)\n\n    # Write sinogram (absorption map)\n\n    # append r, c, f, a to -matrix suffix so sinograms read in as unique images\n    if '-matrix' in s_filename:\n        s_filename = s_filename.replace('-matrix', '-matrix-' + event_type[0])\n    write_tiff32(s_filename, im)\n\n    return im\n", "meta": {"hexsha": "d9b81de1e77471884e4ff743f07af4f6788506a6", "size": 26528, "ext": "py", "lang": "Python", "max_stars_repo_path": "acsemble/projection.py", "max_stars_repo_name": "gazzar/tmm_model", "max_stars_repo_head_hexsha": "b50a8cb2d58e70333015c0ecf5759d887f785047", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-11-14T02:30:24.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-14T02:30:24.000Z", "max_issues_repo_path": "acsemble/projection.py", "max_issues_repo_name": "gazzar/tmm_model", "max_issues_repo_head_hexsha": "b50a8cb2d58e70333015c0ecf5759d887f785047", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "acsemble/projection.py", "max_forks_repo_name": "gazzar/tmm_model", "max_forks_repo_head_hexsha": "b50a8cb2d58e70333015c0ecf5759d887f785047", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.813648294, "max_line_length": 96, "alphanum_fraction": 0.6491254524, "include": true, "reason": "import numpy,from numpy,import scipy,from scipy", "num_tokens": 6765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.19202964676190412}}
{"text": "# hst.py\n\nimport os\nimport numpy as np\nimport pandas as pd\n\nfrom ..io.read_hst import read_hst\nfrom ..load_sim import LoadSim\n\nclass Hst:\n\n    @LoadSim.Decorators.check_pickle_hst\n    def read_hst(self, savdir=None, merge_mhd=True, force_override=False):\n        \"\"\"Function to read hst and convert quantities to convenient units\n        \"\"\"\n        \n        hst = read_hst(self.files['hst'], force_override=force_override)\n    \n        # delete the first row (post-processing)\n        hst.drop(hst.index[:1], inplace=True)\n\n        u = self.u\n        domain = self.domain\n\n        # volume of resolution element (code unit)\n        dvol = domain['dx'].prod()\n        # total volume of domain (code unit)\n        vol = domain['Lx'].prod()\n        # Area of domain (code unit)\n        LxLy = domain['Lx'][0]*domain['Lx'][1]\n\n        # Time in code unit\n        hst['time_code'] = hst['time']\n        # Time in Myr\n        hst['time'] *= u.Myr\n        # Total gas mass in Msun\n        hst['mass'] *= vol*u.Msun\n        # Gas surface density in Msun/pc^2\n        hst['Sigma_gas'] = hst['mass']/(LxLy*u.pc**2)\n        # H mass/surface density in Msun\n        hst['MH'] = hst['mass']/u.muH\n        hst['Sigma_H'] = hst['MH']/(LxLy*u.pc**2)\n        \n        # H2 mass in Msun\n        try:\n            hst['MH2'] = hst['MH2']*vol*u.Msun/u.muH\n            hst['Sigma_H2'] = hst['MH2']/(LxLy*u.pc**2)\n            hst['MH2_noLW'] = hst['MH2_noLW']*vol*u.Msun/u.muH\n            hst['Sigma_H2_noLW'] = hst['MH2_noLW']/(LxLy*u.pc**2)\n        except KeyError:\n            pass\n\n        # Neutral gas mass in Msun \n        try:\n            hst['Mneu'] = hst['scalar{:d}'.format(domain['IHI'])]*vol*u.Msun\n        except KeyError:\n            pass\n\n        # Star formation rate per area [Msun/kpc^2/yr]\n        hst['sfr10'] = hst['sfr10']/(LxLy*u.pc**2)\n        hst['sfr40'] = hst['sfr40']/(LxLy*u.pc**2)\n        hst['sfr100'] = hst['sfr100']/(LxLy*u.pc**2)\n        \n        # Cosmic ray ionization rate without attenuation\n        hst['xi_CR0'] = 2e-16*self.par['problem']['xi_CR_amp']*(hst['sfr40']/3e-3)\n        \n        hst.index = hst['time_code']\n        #hst.index.name = 'index'\n        \n        # Merge with mhd history dump\n        if merge_mhd:\n            try:\n                hst_mhd = self.read_hst_mhd()\n                hst = hst_mhd.reindex(hst.index, method='nearest',\n                                      tolerance=0.1).combine_first(hst)\n            except FileNotFoundError:\n                pass\n                \n        self.hst = hst\n        \n        return hst\n        \n        # # Ionized gas mass in Msun\n        # hst['Mion'] *= vol*u.Msun\n        # # Collisionally ionized gas (before ray tracing) in Msun\n        # hst['Mion_coll'] *= vol*u.Msun\n        # # Total photoionization rate [#/sec]\n        # hst['Qiphot'] *= vol*(u.length**3).cgs\n        # # Total collisional ionization rate [#/sec]\n        # hst['Qicoll'] *= vol*(u.length**3).cgs\n        # # Total dust absorption rate [#/sec]\n        # hst['Qidust'] *= vol*(u.length**3).cgs\n\n    #     # Mass fraction ionized gas\n    #     hst['mf_ion'] = hst['Mion']/hst['mass']\n    #     hst['mf_ion_coll'] = hst['Mion_coll']/hst['mass']\n\n        # for f in range(self.par['radps']['nfreq']):\n        #     # Total luminosity [Lsun]\n        #     hst['Ltot_cl{:d}'.format(f)] *= vol*u.Lsun\n        #     hst['Ltot_ru{:d}'.format(f)] *= vol*u.Lsun\n        #     hst['Ltot{:d}'.format(f)] = \\\n        #         hst['Ltot_cl{:d}'.format(f)] + hst['Ltot_ru{:d}'.format(f)]\n        #     # Total luminosity included in simulation\n        #     hst['L_cl{:d}'.format(f)] *= vol*u.Lsun\n        #     hst['L_ru{:d}'.format(f)] *= vol*u.Lsun\n        #     hst['L{:d}'.format(f)] = \\\n        #         hst['L_cl{:d}'.format(f)] + hst['L_ru{:d}'.format(f)]\n        #     # Luminosity that escaped boundary\n        #     hst['Lesc{:d}'.format(f)] *= vol*u.Lsun\n        #     # Luminosity lost due to dmax\n        #     hst['Llost{:d}'.format(f)] *= vol*u.Lsun\n        #     # Escape fraction, lost fraction\n        #     # Estimation of true escape fraction estimation (upper bound)\n        #     hst['fesc{:d}'.format(f)] = hst['Lesc{:d}'.format(f)] / \\\n        #                                 hst['L{:d}'.format(f)]\n        #     hst['flost{:d}'.format(f)] = hst['Llost{:d}'.format(f)] / \\\n        #                                  hst['L{:d}'.format(f)]\n        #     hst['fesc{:d}_est'.format(f)] = hst['fesc{:d}'.format(f)] + \\\n        #                                     hst['flost{:d}'.format(f)]\n        #     hst['fesc{:d}_cum_est'.format(f)] = \\\n        #         (hst['Lesc{:d}'.format(f)] + hst['Llost{:d}'.format(f)]).cumsum() / \\\n        #          hst['L{:d}'.format(f)].cumsum()\n\n        # return hst\n\n    #     # Scale heights of [warm] ionized gas, nesq\n    #     # Check if columns exist\n\n    #     # nesq\n    #     if 'H2nesq' in hst.columns and 'nesq' in hst.columns:\n    #         hst['H_nesq'] = np.sqrt(hst['H2nesq'] / hst['nesq'])\n    #         hst.drop(columns=['H2nesq', 'nesq'], inplace=True)\n\n    #     # Warm nesq\n    #     if 'H2wnesq' in hst.columns and 'wnesq' in hst.columns:\n    #         hst['H_wnesq'] = np.sqrt(hst['H2wnesq'] / hst['wnesq'])\n    #         hst.drop(columns=['H2wnesq', 'wnesq'], inplace=True)\n\n    #     # For warm medium, \n    #     # append _ to distinguish from mhd history variable\n    #     if 'H2w' in hst.columns and 'massw' in hst.columns:\n    #         hst['H_w_'] = np.sqrt(hst['H2w'] / hst['massw'])\n    #         hst['Mw_'] = hst['massw']*vol*u.Msun\n    #         hst['mf_w_'] = hst['Mw_']/hst['mass']\n    #         hst.drop(columns=['H2w', 'massw'], inplace=True)\n\n    #     # Warm ionized\n    #     if 'H2wi' in hst.columns and 'masswi' in hst.columns:\n    #         hst['H_wi'] = np.sqrt(hst['H2wi'] / hst['masswi'])\n    #         hst['Mwion'] = hst['masswi']*vol*u.Msun\n    #         hst['mf_wion'] = hst['Mwion']/hst['mass']\n    #         hst.drop(columns=['H2wi', 'masswi'], inplace=True)\n            \n    #     ##########################\n    #     # With ionizing radiation\n    #     ##########################\n    #     if self.par['radps']['nfreq'] == 2 and \\\n    #        self.par['radps']['nfreq_ion'] == 1:\n    #         hnu0 = self.par['radps']['hnu[0]']/u.eV\n    #         hnu1 = self.par['radps']['hnu[1]']/u.eV\n    #         # Total luminosity\n    #         hst['Qitot_cl'] = hst['Ltot_cl0']/u.Lsun/hnu0/u.s\n    #         hst['Qitot_ru'] = hst['Ltot_ru0']/u.Lsun/hnu0/u.s\n    #         hst['Qitot'] = hst['Qitot_ru'] + hst['Qitot_cl']\n    #         # Total Q included as source\n    #         hst['Qi_cl'] = hst['L_cl0']/u.Lsun/hnu0/u.s\n    #         hst['Qi_ru'] = hst['L_ru0']/u.Lsun/hnu0/u.s\n    #         hst['Qi'] = hst['Qi_ru'] + hst['Qi_cl']\n    #         hst['Qiesc'] = hst['Lesc0']/u.Lsun/hnu0/u.s\n    #         hst['Qilost'] = hst['Llost0']/u.Lsun/hnu0/u.s\n    #         hst['Qiesc_est'] = hst['Qilost'] + hst['Qiesc']\n\n    #     else:\n    #         self.logger.error('Unrecognized option nfreq={0:d}, nfreq_ion={1:d}'.\\\n    #                           format(self.par['radps']['nfreq'],\n    #                                  self.par['radps']['nfreq_ion']))\n\n    #     # midplane radiation energy density in cgs units\n    #     hst['Erad0_mid'] *= u.energy_density\n    #     hst['Erad1_mid'] *= u.energy_density\n\n\n    #     try:\n    #         hst.to_pickle(fpkl)\n    #     except IOError:\n    #         self.logger.warning('[read_hst]: Could not pickle hst to {0:s}.'.format(fpkl))\n\n    #     self.hst = hst\n    #     return self.hst\n\n    def read_hst_mhd(self):\n\n        # Read original mhd history dump from /tigress/changgoo\n        hst = read_hst('/tigress/changgoo/{0:s}/hst/{0:s}.hst'.\\\n                       format(self.problem_id), force_override=True)\n\n        u = self.u\n        domain = self.par['domain1']\n        Lx = domain['x1max'] - domain['x1min']\n        Ly = domain['x2max'] - domain['x2min']\n        Lz = domain['x3max'] - domain['x3min']\n        Nx = domain['Nx1']\n        Ny = domain['Nx2']\n        Nz = domain['Nx3']\n        Ntot = Nx*Ny*Nz\n        vol = Lx*Ly*Lz\n        LxLy = Lx*Ly\n        dz = Lz/Nz\n        Omega = self.par['problem']['Omega']\n        time_orb = 2*np.pi/Omega*u.Myr # Orbital time in Myr\n\n        if 'x1Me' in hst:\n            mhd = True\n        else:\n            mhd = False\n\n        h = pd.DataFrame()\n        h['time_code'] = hst['time']\n        h['time'] = h['time_code']*u.Myr # time in Myr\n        h['time_orb'] = h['time']/time_orb\n\n        h['mass'] = hst['mass']*u.Msun*vol\n        h['Sigma'] = h['mass']/LxLy\n        h['mass_sp'] = hst['msp']*u.Msun*vol\n        h['Sigma_sp'] = h['mass_sp']/LxLy\n\n        # Mass, volume fraction, scale height\n        h['H'] = np.sqrt(hst['H2'] / hst['mass'])\n        for ph in ['c','u','w','h1','h2']:\n            h['mf_{}'.format(ph)] = hst['M{}'.format(ph)]/hst['mass']\n            h['vf_{}'.format(ph)] = hst['V{}'.format(ph)]\n            h['H_{}'.format(ph)] = \\\n                np.sqrt(hst['H2{}'.format(ph)] / hst['M{}'.format(ph)])\n\n        # mf, vf, H of thermally bistable (cold + unstable + warm) medium\n        h['mf_2p'] = h['mf_c'] + h['mf_u'] + h['mf_w']\n        h['vf_2p'] = h['vf_c'] + h['vf_u'] + h['vf_w']\n        h['H_2p'] = np.sqrt((hst['H2c'] + hst['H2u'] + hst['H2w']) / \\\n                            (hst['Mc'] + hst['Mu'] + hst['Mw']))\n\n        # Kinetic and magnetic energy\n        h['KE'] = hst['x1KE'] + hst['x2KE'] + hst['x3KE']\n        if mhd:\n            h['ME'] = hst['x1ME'] + hst['x2ME'] + hst['x3ME']\n\n        hst['x2KE'] = hst['x2dke']\n        for ax in ('1','2','3'):\n            Ekf = 'x{}KE'.format(ax)\n            if ax == '2':\n                Ekf = 'x2dke'\n            # Mass weighted velocity dispersion??\n            h['v{}'.format(ax)] = np.sqrt(2*hst[Ekf]/hst['mass'])\n            if mhd:\n                h['vA{}'.format(ax)] = \\\n                    np.sqrt(2*hst['x{}ME'.format(ax)]/hst['mass'])\n            h['v{}_2p'.format(ax)] = \\\n                np.sqrt(2*hst['x{}KE_2p'.format(ax)]/hst['mass']/h['mf_2p'])\n            \n        h['cs'] = np.sqrt(hst['P']/hst['mass'])\n        h['Pth_mid'] = hst['Pth']*u.pok\n        h['Pth_mid_2p'] = hst['Pth_2p']*u.pok/hst['Vmid_2p']\n        h['Pturb_mid'] = hst['Pturb']*u.pok\n        h['Pturb_mid_2p'] = hst['Pturb_2p']*u.pok/hst['Vmid_2p']\n\n        # Midplane number density\n        h['nmid'] = hst['nmid']\n        h['nmid_2p'] = hst['nmid_2p']/hst['Vmid_2p']\n\n        # Star formation rate per unit area [Msun/kpc^2/yr]\n        h['sfr10']=hst['sfr10']\n        h['sfr40']=hst['sfr40']\n        h['sfr100']=hst['sfr100']\n\n        h.index = h['time_code']\n        #h.index.name = 'index'\n        \n        self.hst_mhd = h\n\n        return self.hst_mhd\n    \n        # return pd.read_pickle(\n        #     '/tigress/changgoo/{0:s}/hst/{0:s}.hst_cal.p'.format(self.problem_id))\n", "meta": {"hexsha": "04b561832ee1eff6fb842475314e5f4a81ebbee5", "size": 10901, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyathena/tigress_xco/hst.py", "max_stars_repo_name": "changgoo/pyathena-1", "max_stars_repo_head_hexsha": "c461ac3390d773537ce52393e3ebf68a3282aa46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-03T13:59:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-03T13:59:14.000Z", "max_issues_repo_path": "pyathena/tigress_xco/hst.py", "max_issues_repo_name": "changgoo/pyathena-1", "max_issues_repo_head_hexsha": "c461ac3390d773537ce52393e3ebf68a3282aa46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-09-23T23:36:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T06:16:56.000Z", "max_forks_repo_path": "pyathena/tigress_xco/hst.py", "max_forks_repo_name": "changgoo/pyathena-1", "max_forks_repo_head_hexsha": "c461ac3390d773537ce52393e3ebf68a3282aa46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-06-10T04:26:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-04T22:27:02.000Z", "avg_line_length": 38.3838028169, "max_line_length": 92, "alphanum_fraction": 0.4801394367, "include": true, "reason": "import numpy", "num_tokens": 3617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.19200484243355398}}
{"text": "#!/usr/bin/env python\n\n\"\"\"\n    Does some simple calculations to test trace gas  PACE calculations\n\n    Adapted from benchmark4Amir.py\n    Patricia Castellanos, April 2020\n\n\"\"\"\n\nimport os\nimport sys\nfrom   netCDF4 import Dataset\nfrom   netCDF4 import Dataset as ncread\nimport numpy   as np\nfrom MAPL.constants import *\nfrom py_leo_vlidort import VLIDORT_POLAR_\nfrom scipy.interpolate import interp1d\nimport scipy.integrate as integrate\nfrom pyhdf.SD import SD, SDC\nfrom multiprocessing import Pool\n\nformat   = 'NETCDF4_CLASSIC'\nplane_parallel = True\nMISSING = -1.e+20\n\n\nWrapperFuncs = {'MODIS_BRDF'                : VLIDORT_POLAR_.vector_brdf_modis,\n                'MODIS_BRDF_BPDF'           : VLIDORT_POLAR_.vector_brdf_modis_bpdf,\n                'BPDF'                      : VLIDORT_POLAR_.vector_bpdf,\n                'LAMBERTIAN'                : VLIDORT_POLAR_.vector_lambert,\n                'LAMBERTIAN_BPDF'           : VLIDORT_POLAR_.vector_lambert_bpdf,\n                'GissCX'                    : VLIDORT_POLAR_.vector_gisscx,\n                'CX'                        : VLIDORT_POLAR_.vector_cx,\n                'OCICX'                     : VLIDORT_POLAR_.vector_ocicx,\n                'OCIGissCX'                 : VLIDORT_POLAR_.vector_ocigisscx,\n                'OCIGissCX_NOBM_CLOUD'      : VLIDORT_POLAR_.vector_ocigisscx_nobm_cloud,\n                'ROT_CALC'                  : VLIDORT_POLAR_.rot_calc}\n\n\n\ndef get_geom(Iscan,Icross):\n    inFile = '/nobackup/PACE/L1B/Y2020/M03/D24/OCI2020084005000.L1B_PACE.nc'\n    nc = Dataset(inFile)\n    grp = nc.groups['geolocation_data']\n    sza = grp.variables['solar_zenith'][:]\n    saa = grp.variables['solar_azimuth'][:]\n    vza = grp.variables['sensor_zenith'][:]\n    vaa = grp.variables['sensor_azimuth'][:]\n\n    # make azimuths clockwise from north\n    I = saa < 0\n    saa[I] = 360. + saa[I]\n\n    I = vaa < 0\n    vaa[I] = 360. + vaa[I]\n\n    # define SAA according to photon travel direction\n    saa = saa + 180.0\n    I = saa >= 360.\n    saa[I] = saa[I] - 360.\n\n    raa = vaa - saa   \n\n    I = raa < 0\n    raa[I] = raa[I] + 360.0\n\n    saa = grp.variables['solar_azimuth'][:]\n    vaa = grp.variables['sensor_azimuth'][:]\n\n\n    sza = np.array([sza[Iscan,Icross]])\n    vza = np.array([vza[Iscan,Icross]])\n    raa = np.array([raa[Iscan,Icross]])\n    saa = np.array([saa[Iscan,Icross]])\n    vaa = np.array([vaa[Iscan,Icross]])\n\n    return sza,vza,raa,saa,vaa\n\ndef get_ROT(ch,pe,te,ze,verbose=True):\n    \"\"\"\n    calculate ROT and depol ratio\n    \"\"\"\n\n    args = [ch, pe, ze, te, MISSING, verbose]\n    ROT, depol_ratio, rc = VLIDORT_POLAR_.rot_calc(*args)\n\n\n    return ROT,depol_ratio\n\ndef get_TOA_unpack(args):\n    return get_TOA(*args)\n\ndef get_TOA(channel,\n            F0,\n            ROT,depol_ratio,\n            tau,ssa,pmom,\n            alpha,\n            SZA,VZA,RAA,            \n            km,pe,te,ze,\n            nstreams,            \n            albedoType,\n            sleave,\n            U10m,V10m,mr,\n            verbose):\n    \"\"\"\n    Do RT calculation to get TOA\n    \"\"\"\n\n    # wrapper function based on albedo\n    vlidortWrapper = WrapperFuncs[albedoType]\n    \n    if albedoType == 'OCIGissCX':\n        args = [channel, nstreams, plane_parallel, ROT, depol_ratio, alpha, tau, ssa, pmom,\n                pe, ze, te,\n                U10m, V10m, mr,\n                SZA, RAA, VZA,\n                F0,\n                MISSING,\n                verbose]\n        I, reflectance, surf_reflectance, Q, U, BR_Q, BR_U, rc = vlidortWrapper(*args)\n    else:\n        args = [channel, nstreams, plane_parallel, ROT, depol_ratio, alpha, tau, ssa, pmom,\n                tau, ssa, pmom,\n                tau, ssa, pmom,\n                pe, ze, te,\n                U10m, V10m, mr,\n                sleave, False,\n                SZA, RAA, VZA,\n                F0,\n                MISSING,\n                verbose]\n        I, reflectance, surf_reflectance, Q, U, BR_Q, BR_U, rc, adjusted_sleave = vlidortWrapper(*args)\n\n\n    return I,reflectance,surf_reflectance\n\n\ndef writenc(outFile,channels,\n            F0,\n            SZA,SAA,VZA,VAA,\n            I,BR,reflectance,\n            ROD,depol_ratio,\n            alphaD,\n            pe,te,ze,\n            U10m,V10m,mr):\n\n\n\n    nch = len(channels)\n    km  = len(pe)\n\n    # Write data to netcdf file\n    nc = Dataset(outFile,'w',format='NETCDF4_CLASSIC')\n    nc.title = 'Line-by-Line TOA radiance calculation for one OCI pixel. Model 5 - US Standard 1962'\n\n    dc = nc.createDimension('channels',nch)\n    dn = nc.createDimension('npixel',1)\n    dk = nc.createDimension('leve',km)\n\n    ch = nc.createVariable('channels','f4',('channels',))\n    ch.long_name = \"Wavelength in nm\"\n    ch[:] = channels\n\n    f  = nc.createVariable('solar_irradiance','f4',('channels',))\n    f.long_name = 'Thuillier solar irradiance spectrum'\n    f.units = 'uW/cm^2/nm'\n    f[:] = F0\n\n    rad = nc.createVariable('I','f4',('channels',))\n    rad.long_name = \"sun normalized TOA radiance\"\n    rad[:] = I\n\n    ref = nc.createVariable('R','f4',('channels',))\n    ref.long_name = \"TOA reflectance\"\n    ref[:] = reflectance\n\n    sr = nc.createVariable('surface_reflectance','f4',('channels',))\n    sr.long_name = \"surface bidirectional reflectance\"\n    sr[:] = BR  \n\n    a = nc.createVariable('sza','f4',('npixel',))\n    a.long_name = \"solar zenith angle\"\n    a.units = 'degrees'\n    a[:] = SZA    \n\n    a = nc.createVariable('saa','f4',('npixel',))\n    a.long_name = \"solar azimiuth angle\"\n    a.units = 'degrees 0-360 clockwise from north'\n    a[:] = SAA\n\n    a = nc.createVariable('vza','f4',('npixel',))\n    a.long_name = \"sensor zenith angle\"\n    a.units = 'degrees'\n    a[:] = VZA\n\n    a = nc.createVariable('vaa','f4',('npixel',))\n    a.long_name = \"sensor azimiuth angle\"\n    a.units = 'degrees 0-360 clockwise from north'\n    a[:] = SAA \n\n    rod = nc.createVariable('ROD','f4',('channels',))\n    rod.long_name = \"Rayleigh Optical Depth\"\n    rod[:] = ROD\n\n    depol = nc.createVariable('depol_ratio','f4',('channels',))\n    depol.long_name = 'Rayleigh depolarization ratio'\n    depol[:] = depol_ratio\n\n    alpha = nc.createVariable('ALPHA','f4',('channels',))\n    alpha.long_name = \"Trace Gas Absorption Optical Depth\"\n    alpha[:] = alphaD\n\n    ke = nc.createVariable('PE','f4',('leve',))\n    ke.long_name = 'Pressure at layer edge'\n    ke.units     = 'Pa'\n    ke[:] = pe\n\n    ke = nc.createVariable('TE','f4',('leve',))\n    ke.long_name = 'Temperature at layer edge'\n    ke.units     = 'K'\n    ke[:] = te\n\n    ke = nc.createVariable('ZE','f4',('leve',))\n    ke.long_name = 'height above surface'\n    ke.units = 'm'\n    ke[:] = ze\n\n    wi = nc.createVariable('U10M','f4',('npixel',))\n    wi.long_name = 'U10M wind speed'\n    wi.units = 'm/s'\n    wi[:] = U10m\n\n    wi = nc.createVariable('V10M','f4',('npixel',))\n    wi.long_name = 'V10M wind speed'\n    wi.units = 'm/s'\n    wi[:] = V10m\n\n    wi = nc.createVariable('mr','f4',('npixel',))\n    wi.long_name = 'ocean water refractive index'\n    wi[:] = mr\n\n    nc.close()    \n\ndef get_PTWV_profile(inFile,model=5):\n    \"\"\"\n    Read in height [km],pressure [mb], temperature [K], water vapor vmr profile [ppm]\n    for selected model:\n    0:Tropical\n    1:Mid Latitude Summer\n    2:Mid Latitude Winter\n    3:Subarctic Summer\n    4:Subarctic Winter\n    5:US Standard 1962\n    6:User Defined Model\n    \"\"\"\n    nc = Dataset(inFile)\n    # make array because interp doesn't take masked arrays\n    pe = np.array(nc.variables['p'][model,:])  \n    te = np.array(nc.variables['t'][model,:])\n    ze = np.array(nc.variables['h'][model,:])    \n    vmre =np.array( nc.variables['vmr'][model,:])\n\n    km   = len(ze) - 1\n\n    # get DP, from Amir's code\n    DP= np.empty([km])\n    for i in range(km):\n        DP[i] = (pe[i] - pe[i+1])/1013\n\n    # convert mb to Pascal\n    pe = pe *100\n    DELP = pe[:-1] - pe[1:]\n\n    # get T middles\n    DELP = pe[:-1] - pe[1:]\n    pm = pe[:-1] - 0.5*DELP\n    f = interp1d(pe,te)\n    tm = f(pm)\n\n\n    # convert km to m\n    ze = ze*1000.\n    dz = ze[1:] - ze[:-1]\n\n    # calculate air number density [molecules/m3]\n    g = 9.80616 # gravity m/s2\n    Na = 6.022e23 # avogadro's number\n    MW_AIR =  28.964*1e-3 # kg/mole\n\n    AIRDENS = DELP/(dz*g) # kg/m3\n    rho = AIRDENS/MW_AIR      # moles/m3\n    rho = rho*Na  #[molecules/m3]\n\n    return km, pe, te, tm, ze, dz, rho, vmre, DP, AIRDENS \n\n\ndef get_abs(inFile):\n    \"\"\"\n    Read aborption coefficients from Amir's HITRAN calculations\n    \"\"\"\n    nc = Dataset(inFile)\n    # wavenumber [cm-1]\n    waveno = np.array(nc.variables['waveno'][:])\n    # abosrption coefficients [not sure about units]\n    abs_o2  = nc.variables['abscf_o2'][:]\n    abs_h2o = nc.variables['abscf_h2o'][:]\n    abs_co  = nc.variables['abscf_co'][:]\n    abs_co2 = nc.variables['abscf_co2'][:]\n    abs_ch4 = nc.variables['abscf_ch4'][:]\n    abs_n2o = nc.variables['abscf_n2o'][:]\n\n    nc.close()\n\n    return abs_o2, abs_h2o, abs_co, abs_co2, abs_ch4, abs_n2o, waveno\n\n\ndef get_rsr(inFile):\n    \"\"\"\n    Read in OCI RSR File\n    \"\"\"\n    hdf = SD(inFile, SDC.READ)\n    rsr = hdf.select('RSR')[:]\n    wav_rsr = hdf.select('rsrwave')[:]\n    wav_oci = hdf.select('wave')[:]\n    hdf.end()\n\n    return rsr, wav_rsr, wav_oci\n\ndef get_alpha(A,VMR,rho,dz):\n    \"\"\"\n    Calculate Absorption optical depth profile\n    A - absorption coefficient [m2/molecule]\n    VMR - trace gas mixing ratio [vol/vol, dimensionless]\n    rho - air number density [molecules/m3]\n    ze  - profile layer thickness [m]\n    \"\"\"\n\n    # convert vmr to molecules/m3\n    nxe = VMR*rho\n\n    # get the optical depth subcolumns\n    km, nch = A.shape\n    alpha = np.zeros([km,nch])\n    for i in range(km):\n        alpha[i,:] = nxe[i]*dz[i]*A[i,:]\n\n    return alpha\n\n\n# ---\ndef read_o3(inFile,te):\n    f = open(inFile)\n    nhead = 10\n    for i in range(nhead):\n        hh = f.readline()\n\n    wav_o3, c0, c1, c2 = [],[],[],[]\n    for l in f:\n        a = np.array(l.split()).astype(float)\n        wav_o3.append(a[0])\n        c0.append(a[1])\n        c1.append(a[2])\n        c2.append(a[3])\n    f.close()\n\n    wav_o3 = np.array(wav_o3)\n    c0     = np.array(c0)\n    c1     = np.array(c1)\n    c2     = np.array(c2)\n    T0     = 273.15\n\n    # calculate xsec for te\n    nwav = len(wav_o3)\n    km   = len(te)\n    xsec_o3 = np.zeros([km,nwav])\n\n    for i,t in enumerate(te):\n        xsec_o3[i,:] = c0 + c1*(t-T0) + c2*(t-T0)**2\n\n    xsec_o3 = xsec_o3*1e-20\n\n    # convert from cm2/molecule to m2/molecule\n    xsec_o3 = xsec_o3*1e-4\n\n    return wav_o3, xsec_o3\n\n# --\ndef read_ROD_table(inFile):\n    f = open(inFile)\n\n    for i in range(16):\n        f.readline() #header\n\n    wav = []\n    rod = []\n    depol = []\n    for l in f:\n        w, r, d = l.split()\n        wav.append(w)\n        rod.append(r)\n        depol.append(d)\n\n    f.close()\n\n    wav = np.array(wav).astype('float')\n    rod = np.array(rod).astype('float')\n    depol = np.array(depol).astype('float')\n\n    return wav, rod, depol\n\n#------------------------------------ M A I N ------------------------------------\n\nif __name__ == \"__main__\":\n\n    outRoot = 'hyperTest/'\n    outFile   = '{}/outputs/hyperTest_CK_Thuillier_g5nr.nc4'.format(outRoot)\n\n\n    # Pressure [Pa], temperature [K], height [m], water vapor [ppm]  profile - standard atmosphere\n    # used to make OCI look up tables\n    # rhoe = air number density [molecules/m3]\n    inFile    = '{}/atrem_tpvmr.nc'.format(outRoot)\n    km, pe, te, tm, ze, dz, rho, h2oe, DP, AIRDENS =  get_PTWV_profile(inFile)\n\n    # Read in G5NR CO, CO2, O3, RH\n    Iscan  = 600\n    Icross = 1000\n    LevelB = '/nobackup/PACE/LevelB/Y2006/M03/D24'\n    inFile = '{}/pace-g5nr-std.lb.chm_Nv.20060324_005000.nc4'.format(LevelB)\n    nc = Dataset(inFile)\n    co = nc.variables['CO'][0,:,Iscan,Icross]    # VMR\n    co2 = nc.variables['CO2'][0,:,Iscan,Icross]  # VMR\n    o3 = nc.variables['O3'][0,:,Iscan,Icross]  #kg/kg\n    nc.close()\n    inFile = '{}/pace-g5nr-std.lb.aer_Nv.20060324_005000.nc4'.format(LevelB)\n    nc = Dataset(inFile)\n    h2o = nc.variables['WV_VMR'][0,:,Iscan,Icross]  #ppm\n    nc.close()\n    \n    # flip from bottom to top\n    co  = co[::-1]\n    co2 = co2[::-1]\n    o3  = o3[::-1]\n    h2o = h2o[::-1]\n\n    # Read in alpha_table\n    inFile = 'alphaTable_v0/alpha_CK_Thuillier_o3.nc4'\n    nc = Dataset(inFile)\n    all_wl = np.array(nc.variables['channels'][:])\n    g_bins   = nc.variables['g_bins'][:]\n    alpha_o2 = nc.variables['alpha_o2'][:]\n    ROD      = nc.variables['ROD'][:]\n    depol    = nc.variables['depol_ratio'][:]\n    F0_int   = nc.variables['solar_irradiance'][:]\n\n    nc.close()\n\n    alpha = alpha_o2\n\n#    # integrate air density in each layer\n#    rhoint = rho*dz\n\n\n    # get absorption optical depth with new aborption coefficient\n#    co_vmr = 0.1*1e-6\n#    co_vmr = co\n#    alpha_co = get_alpha(abs_co_z,co_vmr,rho,dz)\n    \n#    o2_vmr = 0.21\n#    alpha_o2 = get_alpha(abs_o2_z,o2_vmr,rho,dz)\n    \n#    co2_vmr = 400.*1.0E-06\n#    co2_vmr = co2\n#    alpha_co2 = get_alpha(abs_co2_z,co2_vmr,rho,dz)\n\n#    ch4_vmr = 1.8*1.0E-06\n#    alpha_ch4 = get_alpha(abs_ch4_z,ch4_vmr,rho,dz)\n\n#    n2o_vmr = 0.3*1.0E-06\n#    alpha_n2o = get_alpha(abs_n2o_z,n2o_vmr,rho,dz)\n\n#    h2o_vmr = h2o*1.0e-6\n#    alpha_h2o = get_alpha(abs_h2o_z,h2o_vmr,rho,dz)\n\n    # add up all the alphas\n#    alpha = alpha_h2o + alpha_n2o + alpha_ch4 + alpha_co2 + alpha_o2 + alpha_co\n\n#    # ----\n#    # OZONE Stuff\n#    # ---\n#    # read xsec\n#    inFile = 'hyperTest/o3_bremen/Ozone_abs_x_wTemperatureFit.dat'\n#    # wav [nm], C0, C1(T), C2(T^2)\n#    # xsec is in m2/molecule\n#    wav_o3,abs_o3 = read_o3(inFile,tm)\n#    # reverse so going from max to min wavelength\n#    wav_o3 = wav_o3[::-1]\n#    abs_o3 = abs_o3[:,::-1]\n\n#    # interpolate to LBL wavelengths\n#    # append zeros to max lbl wavelength\n#    wav_new = np.arange(wav_o3.max()+0.1,wav_abs.max()+0.1,0.1)\n#    # reverse\n#    wav_new = wav_new[::-1]\n#    wav_o3  = np.append(wav_new,wav_o3)\n#    nnew = len(wav_new)\n#    abs_o3 = np.append(np.zeros([km,nnew]),abs_o3,axis=1)\n\n#    abs_o3_lbl = np.zeros(abs_h2o_z.shape)\n#    for k in range(km):\n#       # xsec_f = interp1d(wav_o3,abs_o3[k,:],kind='linear')\n#        abs_o3_lbl[k,:] = xsec_f(wav_abs)\n    \n#    # append UV-Vis to LBL that stops at 555\n#    i = wav_o3 < wav_abs.min()\n#    all_wl = np.append(wav_abs,wav_o3[i])\n#    abs_o3_lbl = np.append(abs_o3_lbl,abs_o3[:,i],axis=1)\n    \n#    # convert mass mixing ratio to molecules/m3\n#    Na = 6.022e23 # avogadro's number\n#    O3_MW  = 48.0*1e-3     # kg/mole\n\n#    o3_conc = o3*AIRDENS   # kg/m3\n#    o3_conc = o3_conc*Na/O3_MW   # molecules/m3\n\n#    # get the optical depth subcolumns\n#    alpha_o3 = np.zeros(abs_o3_lbl.shape)\n#    for i in range(km):\n#        alpha_o3[i,:] = o3_conc[i]*dz[i]*abs_o3_lbl[i,:]\n\n    nwav = len(all_wl)\n    \n#    # add ozone to total alpha\n#    # extend array down to uv\n#    nnew = nwav - len(wav_abs)\n#    alpha = np.append(alpha,np.zeros([km,nnew]),axis=1)\n#    alpha = alpha + alpha_o3\n    \n#    # limit to wavelengths covered by RSR\n#    I = all_wl <= wav_rsr.max()+1.0\n#    all_wl = all_wl[I]\n#    alpha   = alpha[:,I]\n#    alpha[:] = 0.0\n\n\n#    # get ROD from oci_tables\n#    inFile = 'oci_tables/rayleigh_bodhaine.txt'\n#    wav,rod,depol = read_ROD_table(inFile)\n\n#    # interpolate to lbl wavelengths\n#    rod_f = interp1d(wav,rod,kind='linear')\n#    rod_lbl = rod_f(all_wl)\n#    depol_f = interp1d(wav,depol,kind='linear')\n#    depol_lbl = depol_f(all_wl)\n    \n    # flip everything vertically so going from top of atmosphere to surface\n    pe = pe[-1::-1]\n    te = te[-1::-1]\n    ze = ze[-1::-1]\n#    alpha = alpha[-1::-1,:]\n\n    # add dimension to be in km+1,nobs\n    pe.shape = (km+1,1)\n    te.shape = (km+1,1)\n    ze.shape = (km+1,1)\n\n\n    # read in granule geometry\n    SZA,VZA,RAA,SAA,VAA = get_geom(Iscan,Icross)\n    csza = np.cos(np.radians(SZA))\n\n#    # Read in solar irradiance spectrum\n#    # second dim = wavelength, irradiance\n#    # units=nm, uW/cm^2/nm\n#    inFile = '{}/Thuillier_F0.npy'.format(outRoot)\n#    F0 = np.load(inFile)\n#    # interpolate to wavelengths \n#    F0_f = interp1d(F0[:,0],F0[:,1],kind='linear',fill_value=\"extrapolate\")\n#    F0_int = F0_f(all_wl)\n\n    # --------------\n    # surface stuff\n    # --------------\n\n    # SLEAVE\n    LevelB = '/nobackup/PACE/LevelB/surface/SLEAVE/NOBM/Y2006/M03/D24'\n    inFile = '{}/pace-g5nr.lb.sleave.20060324_005000.nc4'.format(LevelB)\n    nc     = Dataset(inFile)\n    nobm_wav = nc.variables['wavelength'][:]\n    rrs      = nc.variables['rrs'][0,:,Iscan,Icross]\n    nc.close()\n    rrs_f    = interp1d(nobm_wav,rrs,kind='linear',fill_value=0.0,bounds_error=False)\n    sleave   = rrs_f(all_wl)*csza\n    \n    # wind speed\n    LevelB = '/nobackup/PACE/LevelB/Y2006/M03/D24'\n    inFile = '{}/pace-g5nr-std.lb.met_Nv.20060324_005000.nc4'.format(LevelB)\n    nc     = Dataset(inFile)\n    U10m   = np.array([nc.variables['U10M'][0,Iscan,Icross]])\n    V10m   = np.array([nc.variables['V10M'][0,Iscan,Icross]])\n\n    # water refractive index\n    mr   = 1.334\n\n    # RT stuff\n    nstreams = 12\n    albedoType = 'OCIGissCX_NOBM_CLOUD'\n    albedoType = 'OCIGissCX'\n\n    # loop through channels\n    nproc = 50\n    nwl   = len(all_wl)\n#    nwl   = 100\n#    wlstep = int(nwl/nproc)\n    wlstep  = 10\n    sys.exit()\n    args = []\n    ROD  = []\n    depol = []\n    sys.exit()\n    for ich in np.arange(0,nwl,wlstep):\n        endch = ich + wlstep\n        if endch > nwl:\n            endch = nwl\n        nch = endch - ich\n        ch = all_wl[ich:endch]\n\n        # Get Rayleigh\n        # ROT shape is nlev,1,nch\n        ROT, depol_ratio = get_ROT(ch,pe,te,ze,verbose=False)    \n       \n        ROT = ROT*rod_lbl[ich:endch]/np.squeeze(ROT.sum(axis=0))\n        ROD.append(np.squeeze(ROT.sum(axis=0)))\n\n        depol_ratio = depol_lbl[ich:endch]\n        depol.append(depol_ratio)\n\n        # trace gas\n        alpha_ch = alpha[:,ich:endch]\n        alpha_ch.shape = (km,1,nch)\n\n        # AOP vectors [km,nch,nobs]\n        tau = np.zeros([km,nch,1])\n        ssa = np.zeros([km,nch,1])\n        pmom = np.zeros([km,nch,1,30,6])\n \n        # water refractive index\n        mr_in = np.ones(nch)\n        mr_in = mr_in*mr\n\n        # solar irradiance\n        F0_in = F0_int[ich:endch]\n        F0_in.shape = (nch,1)\n\n        # sleave\n        sleave_ch = sleave[ich:endch]\n\n        args.append([ch,\n                     F0_in,\n                     ROT,depol_ratio,\n                     tau,ssa,pmom,\n                     alpha_ch,\n                     SZA,VZA,RAA,\n                     km,pe,te,ze,\n                     nstreams,\n                     albedoType,\n                     sleave_ch,\n                     U10m,V10m,mr_in,\n                     False])\n\n#       I,reflectance,BR =  get_TOA(ch,\n#                                    ROT,depol_ratio,\n#                                    tau,ssa,pmom,\n#                                    alpha_ch,\n#                                    SZA,VZA,RAA,\n#                                    km,pe,te,ze,\n#                                    nstreams,\n#                                    albedoType,\n#                                    U10m=U10m,V10m=V10m,mr=np.array([1.334]),\n#                                    verbose=False)\n\n\n    \n    # use multiprocessing\n    p = Pool(nproc)\n    result = p.map(get_TOA_unpack,args)\n    I = []\n    reflectance = []\n    BR = []\n    for r in result:    \n        I_r,reflectance_r,BR_r = r\n        I.append(np.squeeze(I_r))\n        reflectance.append(np.squeeze(reflectance_r))\n        BR.append(np.squeeze(BR_r))\n\n    p.close()\n    p.join()\n    \n    # concatenate arrays\n    ROD = np.concatenate(ROD)\n    depol_ratio = np.concatenate(depol)\n\n    I  = np.concatenate(I)\n    reflectance = np.concatenate(reflectance)\n    BR = np.concatenate(BR)\n                \n    alphaD = alpha.sum(axis=0)            \n    # write to outFile\n    writenc(outFile,all_wl,\n            F0_int,\n            SZA,SAA,VZA,VAA,\n            I,BR,reflectance,\n            ROD,depol_ratio,\n            alphaD,\n            pe,te,ze,\n            U10m,V10m,mr)    \n\n", "meta": {"hexsha": "9592620b57c68258aa14e6dbe02f79360dcc64cf", "size": 19986, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Components/missions/PACE/hyperTest_ck_g5nr.py", "max_stars_repo_name": "GEOS-ESM/AeroApps", "max_stars_repo_head_hexsha": "874dad6f34420c014d98eccbe81a061bdc0110cf", "max_stars_repo_licenses": ["NASA-1.3", "ECL-2.0", "Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-02T14:23:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T15:39:30.000Z", "max_issues_repo_path": "src/Components/missions/PACE/hyperTest_ck_g5nr.py", "max_issues_repo_name": "GEOS-ESM/AeroApps", "max_issues_repo_head_hexsha": "874dad6f34420c014d98eccbe81a061bdc0110cf", "max_issues_repo_licenses": ["NASA-1.3", "ECL-2.0", "Apache-2.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-04-15T16:22:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T13:59:25.000Z", "max_forks_repo_path": "src/Components/missions/PACE/hyperTest_ck_g5nr.py", "max_forks_repo_name": "GEOS-ESM/AeroApps", "max_forks_repo_head_hexsha": "874dad6f34420c014d98eccbe81a061bdc0110cf", "max_forks_repo_licenses": ["NASA-1.3", "ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7969401947, "max_line_length": 103, "alphanum_fraction": 0.5610427299, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 6425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.19200483798606158}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n################################################################################\n#\n#   CanTherm\n#    \n#   Copyright (c) 2010 by Joshua W. Allen (jwallen@mit.edu)\n#\n#   Permission is hereby granted, free of charge, to any person obtaining a\n#   copy of this software and associated documentation files (the 'Software'),\n#   to deal in the Software without restriction, including without limitation\n#   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n#   and/or sell copies of the Software, and to permit persons to whom the\n#   Software is furnished to do so, subject to the following conditions:\n#\n#   The above copyright notice and this permission notice shall be included in\n#   all copies or substantial portions of the Software.\n#\n#   THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n#   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n#   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n#   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n#   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n#   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n#   DEALINGS IN THE SOFTWARE.\n#\n################################################################################\n\nimport math\nimport numpy\nimport logging\n\nfrom rmgpy.quantity import constants\nfrom rmgpy.statmech import *\n\n################################################################################\n\ndef applyEnergyCorrections(E0, modelChemistry, atoms, bonds):\n    \"\"\"\n    Given an energy `E0` in J/mol as read from the output of a quantum chemistry\n    calculation at a given `modelChemistry`, adjust the energy such that it\n    is consistent with the normal gas-phase reference states. `atoms` is a\n    dictionary associating element symbols with the number of that element in\n    the molecule. `bonds` is a dictionary associating bond types with the number\n    of that bond in the molecule.\n    \"\"\"\n    \n    # Spin orbit correction (SOC) in Hartrees\n    # Values taken from note 22 of http://jcp.aip.org/resource/1/jcpsa6/v109/i24/p10570_s1 and converted to hartrees\n    # Values in millihartree are also available (with fewer significant figures) from http://jcp.aip.org/resource/1/jcpsa6/v106/i3/p1063_s1\n    SOC = {'H':0.0, 'N':0.0, 'O': -0.000355, 'C': -0.000135, 'P': 0.0, 'S': -0.000893} \n    \n    # Step 1: Reference all energies to a model chemistry-independent basis\n    # by subtracting out that model chemistry's atomic energies\n    # Note: If your model chemistry does not include spin orbit coupling, you should add the corrections to the energies here\n    if modelChemistry == 'CBS-QB3':\n        atomEnergies = {'H':-0.499818 , 'N':-54.520543, 'O':-74.987624, 'C':-37.785385, 'P':-340.817186, 'S': -397.657360}\n    elif modelChemistry == 'G3':\n        atomEnergies = {'H':-0.5010030, 'N':-54.564343, 'O':-75.030991, 'C':-37.827717, 'P':-341.116432}\n    elif modelChemistry == 'Klip_1':\n        atomEnergies = {'H':-0.50003976 + SOC['H'], 'O':-75.00915718 + SOC['O'], 'C':-37.79249556 + SOC['C']}\n    elif modelChemistry == 'Klip_2':\n        #Klip QCI(tz,qz)\n        atomEnergies = {'H':-0.50003976 + SOC['H'], 'O':-75.00692746 + SOC['O'], 'C':-37.79044863 + SOC['C']}\n    elif modelChemistry == 'Klip_2_cc':\n        #Klip CCSD(T)(tz,qz)\n        atomEnergies = {'H':-0.50003976 + SOC['H'], 'O':-75.00681155 + SOC['O'], 'C':-37.79029443 + SOC['C']}\n    else:\n        logging.warning('Unknown model chemistry \"{0}\"; not applying energy corrections.'.format(modelChemistry))\n        return E0\n    for symbol, count in atoms.iteritems():\n        if symbol in atomEnergies: E0 -= count * atomEnergies[symbol] * 4.35974394e-18 * constants.Na\n        else:\n            logging.warning('Ignored unknown atom type \"{0}\".'.format(symbol))\n    \n    # Step 2: Atom energy corrections to reach gas-phase reference state\n    # Experimental enthalpy of formation at 0 K \n    # See Gaussian thermo whitepaper at http://www.gaussian.com/g_whitepap/thermo.htm)\n    # Note: these values are relatively old and some improvement may be possible by using newer values, particularly for carbon\n    # However, care should be taken to ensure that they are compatible with the BAC values (if BACs are used)\n    atomHf = {'H': 51.63 , 'N': 112.53 ,'O': 58.99 ,'C': 169.98, 'S': 65.66 }\n    # Thermal contribution to enthalpy Hss(298 K) - Hss(0 K) reported by Gaussian thermo whitepaper\n    # This will be subtracted from the corresponding value in atomHf to produce an enthalpy used in calculating the enthalpy of formation at 298 K\n    atomThermal = {'H': 1.01 , 'N': 1.04, 'O': 1.04 ,'C': 0.25, 'S': 1.05 }\n    # Total energy correction used to reach gas-phase reference state\n    # Note: Spin orbit coupling no longer included in these energies, since some model chemistries include it automatically\n    atomEnergies = {}\n    for element in atomHf:\n        atomEnergies[element] = atomHf[element] - atomThermal[element]\n    for symbol, count in atoms.iteritems():\n        if symbol in atomEnergies: E0 += count * atomEnergies[symbol] * 4184\n    \n    # Step 3: Bond energy corrections\n    bondEnergies = { 'C-H': -0.11, 'C-C': -0.3, 'C=C': -0.08, 'C#C': -0.64,\n        'O-H': 0.02, 'C-O': 0.33, 'C=O': 0.55, 'N#N': -2.0, 'O=O': -0.2, \n        'H-H': 1.1, 'C#N': -0.89, 'S-H': 0.0, 'C-S': 0.43, 'S=O': -0.78 }\n    for symbol, count in bonds.iteritems():\n        if symbol in bondEnergies: E0 += count * bondEnergies[symbol] * 4184\n        else:\n            logging.warning('Ignored unknown bond type \"{0}\".'.format(symbol))\n    \n    return E0\n\n################################################################################\n\ndef projectRotors(geom, F, rotors, linear, TS):\n    \"\"\"\n    For a given geometry `geom` with associated force constant matrix `F`,\n    lists of rotor information `rotors`, `pivots`, and `top1`, and the linearity\n    of the molecule `linear`, project out the nonvibrational modes from the\n    force constant matrix and use this to determine the vibrational frequencies.\n    The list of vibrational frequencies is returned in cm^-1.\n    \"\"\"\n    \n    Nrotors = len(rotors)\n    Natoms = len(geom.mass)\n    Nvib = 3 * Natoms - (5 if linear else 6) - Nrotors - (1 if (TS) else 0)\n    \n    if linear:\n        D = numpy.zeros((Natoms*3,5+Nrotors), numpy.float64)\n    else:\n        D = numpy.zeros((Natoms*3,6+Nrotors), numpy.float64)\n\n    for i in range(Natoms):\n        # Projection vectors for translation\n        D[3*i+0,0] = 1.0\n        D[3*i+1,1] = 1.0\n        D[3*i+2,2] = 1.0\n        # Projection vectors for [external] rotation\n        D[3*i:3*i+3,3] = numpy.array([0, -geom.coordinates[i,2], geom.coordinates[i,1]], numpy.float64)\n        D[3*i:3*i+3,4] = numpy.array([geom.coordinates[i,2], 0, -geom.coordinates[i,0]], numpy.float64)\n        if not linear:\n            D[3*i:3*i+3,5] = numpy.array([-geom.coordinates[i,1], geom.coordinates[i,0], 0], numpy.float64)\n    for i, rotor in enumerate(rotors):\n        scanLog, pivots, top, symmetry = rotor\n        # Determine pivot atom\n        if pivots[0] in top: pivot = pivots[0]\n        elif pivots[1] in top: pivot = pivots[1]\n        else: raise Exception('Could not determine pivot atom.')\n        # Projection vectors for internal rotation\n        e12 = geom.coordinates[pivots[0],:] - geom.coordinates[pivots[1],:]\n        e12 /= numpy.linalg.norm(e12)\n        for atom in top:\n            e31 = geom.coordinates[atom,:] - geom.coordinates[pivot,:]\n            D[3*atom:3*atom+3,-Nrotors+i] = numpy.cross(e31, e12)\n\n    # Make sure projection matrix is orthonormal\n    import scipy.linalg\n    D = scipy.linalg.orth(D)\n\n    # Project out the non-vibrational modes from the force constant matrix\n    P = numpy.dot(D, D.transpose())\n    I = numpy.identity(Natoms*3, numpy.float64)\n    F = numpy.dot(I - P, numpy.dot(F, I - P))\n\n    # Generate mass-weighted force constant matrix\n    # This converts the axes to mass-weighted Cartesian axes\n    # Units of Fm are J/m^2*kg = 1/s^2\n    Fm = F.copy()\n    for i in range(Natoms):\n        for j in range(Natoms):\n            for u in range(3):\n                for v in range(3):\n                    Fm[3*i+u,3*j+v] /= math.sqrt(geom.mass[i] * geom.mass[j]) / constants.Na\n\n    # Get eigenvalues of mass-weighted force constant matrix\n    eig, V = numpy.linalg.eigh(Fm)\n    eig.sort()\n\n    # Convert eigenvalues to vibrational frequencies in cm^-1\n    # Only keep the modes that don't correspond to translation, rotation, or internal rotation\n    return numpy.sqrt(eig[-Nvib:]) / (2 * math.pi * constants.c * 100)\n\n################################################################################   \n\ndef saveStates(species, geometry, label, path):\n    \"\"\"\n    Append the molecular degrees of freedom for `species` with associated\n    string `label` to the file located at `path` on disk.\n    \"\"\"\n    \n    f = open(path, 'a')\n\n    coordinates = geometry.coordinates * 1e10\n    number = geometry.number\n    numbers = {1: 'H', 6: 'C', 7: 'N', 8: 'O', 14: 'Si', 15: 'P', 16: 'S'}\n\n    f = open(path, 'a')\n    f.write('# Coordinates for {0} (angstroms):\\n'.format(label))\n    for i in range(coordinates.shape[0]):\n        x = coordinates[i,0] - coordinates[0,0]\n        y = coordinates[i,1] - coordinates[0,1]\n        z = coordinates[i,2] - coordinates[0,2]\n        f.write('#   {0} {1:9.4f} {2:9.4f} {3:9.4f}\\n'.format(numbers[number[i]], x, y, z))\n    \n    f.write('states(\\n')\n    f.write('    label = \"{0}\",\\n'.format(label))\n    f.write('    E0 = {0!r},\\n'.format(species.E0))\n    f.write('    modes = [\\n')\n    for mode in species.states.modes:\n        f.write('        {0!r},\\n'.format(mode))\n    f.write('    ],\\n')\n    f.write('    spinMultiplicity = {0:d},\\n'.format(species.states.spinMultiplicity))\n    try:\n        f.write('    frequency={0!r},\\n'.format(species.frequency))\n    except AttributeError: pass\n    f.write('    short_comment = \"\",\\n')\n    f.write('    long_comment = \\n')\n    f.write('\"\"\"\\n')\n    f.write('\\n')\n    f.write('\"\"\",\\n')\n    f.write(')\\n\\n')\n    \n    f.close()\n", "meta": {"hexsha": "828a0e36e5672d9dc0847b58586a308bf5398adf", "size": 10178, "ext": "py", "lang": "Python", "max_stars_repo_path": "rmgpy/cantherm/states.py", "max_stars_repo_name": "sean-v8/RMG-Py", "max_stars_repo_head_hexsha": "7cc7c3bfb330786526c56113d98c785bcaaa161a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rmgpy/cantherm/states.py", "max_issues_repo_name": "sean-v8/RMG-Py", "max_issues_repo_head_hexsha": "7cc7c3bfb330786526c56113d98c785bcaaa161a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rmgpy/cantherm/states.py", "max_forks_repo_name": "sean-v8/RMG-Py", "max_forks_repo_head_hexsha": "7cc7c3bfb330786526c56113d98c785bcaaa161a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1203703704, "max_line_length": 146, "alphanum_fraction": 0.6123992926, "include": true, "reason": "import numpy,import scipy", "num_tokens": 2919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.1919665920677642}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\n\r\nMachine Learning applied to defeat a 30 years old DOS game... \r\n\r\nGame mechanics \r\n\"Imbiss\" v. 5.4 by T. Bauer for IBM PC, Public Domain\r\n\r\nCustom Environments in OpenAI’s Gym\r\n\r\nPocs (2020), Beginner’s Guide to Custom Environments in OpenAI’s Gym\r\nHow to set up, verify, and use a custom environment in reinforcement learning training with Python\r\nhttps://towardsdatascience.com/beginners-guide-to-custom-environments-in-openai-s-gym-989371673952\r\nhttps://github.com/MatePocs/gym-basic/blob/main/gym_basic/envs/basic_env_2.py\r\n\r\n@author: Seinheilig, 2021\r\n\"\"\"\r\n\r\n\r\nimport gym\r\nimport numpy as np \r\n\r\nclass ImbissEnv(gym.Env):\r\n    \r\n        def __init__(self):\r\n            self.action_space = gym.spaces.Box(np.array([0,0,0,0,0,0,0]),np.array([300,300,300,300,1300,1300,1300]),dtype=np.int16)  # price tags of all 7 elements\r\n            self.observation_space = gym.spaces.Box(np.array([1,-9]),np.array([7,40])) # day of week / temperature\r\n            \r\n            #### ToDo: Observations better MultiDiscrete?  // requre different logic for TE... \r\n            ### self.observation_space = gym.spaces.MultiDiscrete([ 1, 49 ]) # day of week / temperature\r\n            \r\n        def rnd_state(self):\r\n            #self.state = np.array([np.random.randint(1,7),np.random.randint(0,49)-9],dtype=np.int16) # full state (all days)\r\n            self.state = np.array([1,np.random.randint(0,49)-9],dtype=np.int16) # only weekday...\r\n            \r\n        def step(self, action):\r\n            '''\r\n            single step\r\n            return \r\n            '''\r\n            V = action  # price tags (actions)\r\n            T = self.state[0] # day of the week \r\n            TE = self.state[1] # temperatur\r\n            K = 0 # money before selling \r\n            reward =  self.Customer_Simulation(V,T,TE,K,Version=3)                     \r\n            self.rnd_state()\r\n            done = True        \r\n            info = {}       \r\n            return self.state, reward, done, info\r\n    \r\n        def reset(self):\r\n            self.rnd_state()\r\n            return self.state\r\n        \r\n        def render(self, mode='human'):\r\n            pass\r\n\r\n        def Kaufen(self,WS,V,S,K):  \r\n            \"\"\" reduced game mechanics for buying (DE: \"kaufen\")\r\n            \"\"\"\r\n            debug_ = False \r\n            H = [10,10,10,20,200,35,55]  # lowest price possible \r\n            H = [10,10,10,20,200,50,70]  # good price..\r\n            if debug_:\r\n              Waren = ['Schokoeis','Vanilleeis','Erdbeereis','Cola','Zigaretten','Bratwurst','Pommes']\r\n              print('Kunde: Könnten Sie mir bitte',S,Waren[WS],'geben')\r\n              \r\n            return K + S*V[WS] - S*H[WS]  # return new net balance after selling (income-expense)\r\n        \r\n        def Customer_Simulation(self,V,T,TE,K,Version=3):\r\n            \"\"\" Spielmechanik - Kunden Simulation\r\n        \r\n            Args:\r\n              V: Verkaufspreise\r\n              T: Wochentag in [1:7]\r\n              TE: Temperatur              \r\n              K: Kontostand vor der Simulation\r\n              Version: 1) \"Imbiss-Bude\" von F. Brall 1983 für Apple II\r\n                       2) \"Imbiss\" von O. Schwald 1984 für Commodore C64\r\n                       3) \"Imbiss\" von T. Bauer 1991 für PC\r\n        \r\n            Returns:\r\n              K: Kontostand nach der Simulation\r\n              \r\n            \"\"\"            \r\n            debug_ = False\r\n            if Version <3:\r\n                EK = 10  # Eis Kunden\r\n                ZK = 10  # Zigaretten Kunden \r\n                BK = 30  # Bratwurst Kunden \r\n                if T == 6:  # Samstag\r\n                   EK = 15\r\n                   ZK = 13\r\n                   BK = 40\r\n                if T == 7:  # Sonntag\r\n                   EK = 20\r\n                   ZK = 18\r\n                   BK = 40\r\n                \r\n                # Korrektur der Kunden als Funktion des Preise \r\n                EK -= int(np.min(V[0:3])/10) # bugfix!!\r\n                ZK -= int(V[4]/100)\r\n                BK -= int(np.min(V[5:7])/20) # bugfix!!\r\n                \r\n                # Temperatur Korrektur\r\n                EK += int(TE/2)\r\n                BK -= int(TE/2)\r\n            else:\r\n                ##### \"Imbiss\" PC 1991 \r\n                # 5 Änderungen zum Orginal:\r\n                # 1) nutze max V der Warengruppe für Korrektur\r\n                # 2) ZK = [10,12,15], ZK Basis Wochentag/Sa/So\r\n                # 3) EK += 10 / andere Temperaturabhängigkeit\r\n                # 4) BK andere Temperaturabhängigkeit        \r\n                # 5) if ZK/EK/BK < 0 --> ZK/EK/BK = 0 bevor AK berechnet wird \r\n                EK = 20  # Eis Kunden \r\n                ZK = 10  # Zigaretten Kunden \r\n                BK = 30  # Bratwurst Kunden \r\n                if T == 6:  # Samstag\r\n                   EK = 25\r\n                   ZK = 12\r\n                   BK = 40\r\n                if T == 7:  # Sonntag\r\n                   EK = 30\r\n                   ZK = 15\r\n                   BK = 40\r\n                \r\n                # Korrektur der Kunden als Funktion des Preise \r\n                EK -= int(np.max(V[0:4])/10)  # bugfix!!\r\n                ZK -= int(V[4]/100)\r\n                BK -= int(np.max(V[5:7])/20)  # bugfix!!\r\n                \r\n                # Temperatur Korrektur\r\n                EK += int(TE/4)\r\n                BK -= int(TE/3)\r\n                \r\n            # zu hoher Preis in einer Warengruppe (neg Kundenwert) führt nicht(!) zu einer Reduktion der Gesamtzahl der Kunden\r\n            if BK < 0:\r\n                BK = 0\r\n            if ZK < 0:\r\n                ZK = 0\r\n            if EK < 0:\r\n                EK = 0        \r\n                \r\n            AK = ZK+BK+EK  \r\n            if debug_:\r\n              print(\"Customer_Simulation:\",V,T,TE,K)\r\n              print('Kunden gesamt:\\t\\t',AK)\r\n              print('Eis Kunden:\\t\\t',EK)\r\n              print('Zigaret. Kunden:\\t',ZK)\r\n              print('Bratwurst Kunden:\\t',BK)\r\n            if AK < 0:\r\n                AK = 0 \r\n                \r\n            if AK < 2:\r\n                return K\r\n            \r\n            for Kunde in range(AK):\r\n                #print('Kunde',Kunde)\r\n                kauf = False\r\n                E = np.random.randint(0,9)    # eine Zufallsvariabe für Anzahl Einheiten zu kaufen und Preise ignorieren \r\n                if E == 2:\r\n                    S = 2\r\n                else: \r\n                    S = 1 \r\n                    \r\n                while not(kauf):\r\n                    # eine zufällige Ware wählen \r\n                    Z = np.random.randint(0,7)\r\n                    \r\n                    if Z < 4 and  EK == 0:  # keine Eiskunden mehr  \r\n                        #print('keine Eiskunden mehr')\r\n                        kauf = False  \r\n                        continue\r\n                    \r\n                    if Z == 4 and  ZK == 0:  # keine Zigarettenkunden mehr  \r\n                        continue\r\n        \r\n                    if Z > 4 and  BK == 0:  # keine Bratwurstkunden mehr  \r\n                        continue\r\n        \r\n                    if Z == 0: # Schokoeis\r\n                        if E != 3:  # Preisprüfung überspringen? (in 10% der Fälle)\r\n                           if V[0]-V[1] > 20:\r\n                               K = self.Kaufen(1,V,S,K)\r\n                               EK -= 1; kauf = True  \r\n                               break\r\n                           if V[0]-V[2] > 20:\r\n                               K = self.Kaufen(2,V,S,K)\r\n                               EK -= 1; kauf = True  \r\n                               break \r\n                        K = self.Kaufen(0,V,S,K)  \r\n                        EK -= 1; kauf = True  \r\n                           \r\n                    if Z == 1: # Vanilleeis\r\n                        if E != 3:  # Preisprüfung überspringen? (in 10% der Fälle)\r\n                           if V[1]-V[0] > 20:\r\n                               K = self.Kaufen(0,V,S,K)\r\n                               EK -= 1; kauf = True  \r\n                               break \r\n                           if V[1]-V[2] > 20:\r\n                               K = self.Kaufen(2,V,S,K)\r\n                               EK -= 1; kauf = True  \r\n                               break\r\n                        K = self.Kaufen(1,V,S,K)  \r\n                        EK -= 1; kauf = True  \r\n                \r\n                    if Z == 2: # Erdbeereis\r\n                        if E != 3:  # Preisprüfung überspringen? (in 10% der Fälle)\r\n                           if V[2]-V[0] > 20:\r\n                               K = K = self.Kaufen(0,V,S,K)\r\n                               EK -= 1; kauf = True  \r\n                               break \r\n                           if V[2]-V[1] > 20:\r\n                               K = self.Kaufen(1,V,S,K)\r\n                               EK -= 1; kauf = True  \r\n                               break \r\n                        K = self.Kaufen(2,V,S,K)  \r\n                        EK -= 1; kauf = True     \r\n                        \r\n                    if Z == 3: # Cola    ## KEINE PREISPRÜFUNG COLA!!!\r\n                        K = self.Kaufen(3,V,S,K)  \r\n                        EK -= 1; kauf = True             \r\n                    \r\n                    if Z == 4: # Zigarette   ## PREISPRÜFUNG indirekt über ZK \r\n                        K = self.Kaufen(4,V,S,K)  \r\n                        ZK -= 1; kauf = True                            \r\n                        \r\n                    if Z == 5: # Bratwurst\r\n                        if E != 3:  # Preisprüfung überspringen? (in 10% der Fälle)\r\n                           if V[5]-V[6] > 30:\r\n                               K = self.Kaufen(6,V,S,K)\r\n                               BK -= 1; kauf = True  \r\n                               break\r\n                        K = self.Kaufen(5,V,S,K)  \r\n                        BK -= 1; kauf = True  \r\n                \r\n                    if Z == 6: # Pommes\r\n                        if E != 3:  # Preisprüfung überspringen? (in 10% der Fälle)\r\n                           if V[6]-V[5] > 30:\r\n                               K = self.Kaufen(5,V,S,K)\r\n                               BK -= 1; kauf = True  \r\n                               break\r\n                        K = self.Kaufen(6,V,S,K)  \r\n                        BK -= 1; kauf = True      \r\n                    \r\n            return K\r\n", "meta": {"hexsha": "3c12a5c1e32ff1b2cef47a8d73023d7b3d94fd65", "size": 10397, "ext": "py", "lang": "Python", "max_stars_repo_path": "imbiss_env.py", "max_stars_repo_name": "Steinheilig/Imbiss", "max_stars_repo_head_hexsha": "49f6ae865cef05b4999569cecaf5931db0fb2113", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "imbiss_env.py", "max_issues_repo_name": "Steinheilig/Imbiss", "max_issues_repo_head_hexsha": "49f6ae865cef05b4999569cecaf5931db0fb2113", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "imbiss_env.py", "max_forks_repo_name": "Steinheilig/Imbiss", "max_forks_repo_head_hexsha": "49f6ae865cef05b4999569cecaf5931db0fb2113", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9233870968, "max_line_length": 164, "alphanum_fraction": 0.3776089257, "include": true, "reason": "import numpy", "num_tokens": 2574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3486451353339458, "lm_q1q2_score": 0.19196657947290124}}
{"text": "#!/usr/bin/env python\n#\n# See top-level LICENSE file for Copyright information\n#\n# -*- coding: utf-8 -*-\n\"\"\"\nThis script enables the user to convert spec2D FITS files\nfrom IFU instruments into a 3D cube with a defined WCS.\n\"\"\"\n\nimport argparse\n\nfrom astropy import units\nfrom astropy.io import fits\nfrom astropy.coordinates import SkyCoord\nfrom astropy.wcs import WCS\nimport numpy as np\nimport copy, os\n\nfrom pypeit import msgs, par, io, spec2dobj\nfrom pypeit.spectrographs.util import load_spectrograph\nfrom pypeit.core import datacube as dc_utils\nfrom pypeit.core.flux_calib import load_extinction_data, extinction_correction\nfrom pypeit.core.flexure import calculate_image_offset\nfrom pypeit.core import parse\n\nfrom IPython import embed\n\n\ndef parse_args(options=None, return_parser=False):\n\n    parser = argparse.ArgumentParser(description='Read in an array of spec2D files and convert them into a datacube',\n                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n    parser.add_argument('file', type = str, default=None, help='filename.coadd3d file')\n    parser.add_argument('--det', default=1, type=int, help=\"Detector\")\n    parser.add_argument('-o', '--overwrite', default=False, action='store_true',\n                        help='Overwrite any existing files/directories')\n\n    if return_parser:\n        return parser\n\n    return parser.parse_args() if options is None else parser.parse_args(options)\n\n\ndef coadd_cube(files, parset, overwrite=False):\n    \"\"\" Main routine to coadd spec2D files into a 3D datacube\n\n    Args:\n        files (list):\n            List of all spec2D files\n        parset (:class:`pypeit.par.core.PypeItPar`):\n            An instance of the parameter set.\n        overwrite (bool):\n            Overwrite the output file, if it exists?\n    \"\"\"\n    # Get the detector number\n    det = 1 if parset is None else parset['rdx']['detnum']\n\n    # Load the spectrograph\n    spec2DObj = spec2dobj.Spec2DObj.from_file(files[0], det)\n    specname = spec2DObj.head0['PYP_SPEC']\n    spec = load_spectrograph(specname)\n\n    # Grab the parset, if not provided\n    if parset is None: parset = spec.default_pypeit_par()\n    cubepar = parset['reduce']['cube']\n\n    # Check the output file\n    outfile = cubepar['output_filename'] if \".fits\" in cubepar['output_filename'] else cubepar['output_filename']+\".fits\"\n    out_whitelight = outfile.replace(\".fits\", \"_whitelight.fits\")\n    if os.path.exists(outfile) and not overwrite:\n        msgs.error(\"Output filename already exists:\"+msgs.newline()+outfile)\n    elif os.path.exists(out_whitelight) and cubepar['save_whitelight'] and not overwrite:\n        msgs.error(\"Output filename already exists:\"+msgs.newline()+out_whitelight)\n    # Check the reference cube and image exist, if requested\n    ref_scale = None  # This will be used to correct relative scaling among the various input frames\n    if cubepar['standard_cube'] is not None:\n        if not os.path.exists(cubepar['standard_cube']):\n            msgs.error(\"Standard cube does not exist:\" + msgs.newline() + cubepar['reference_cube'])\n        cube = fits.open(cubepar['standard_cube'])\n        ref_scale = cube['REFSCALE'].data\n    if cubepar['reference_image'] is not None:\n        if not os.path.exists(cubepar['reference_image']):\n            msgs.error(\"Reference cube does not exist:\" + msgs.newline() + cubepar['reference_image'])\n    if cubepar['flux_calibrate']:\n        msgs.error(\"Flux calibration is not currently implemented\" + msgs.newline() +\n                   \"Please set 'flux_calibrate = False'\")\n\n    # prep\n    numfiles = len(files)\n    combine = cubepar['combine']\n\n    all_ra, all_dec, all_wave = np.array([]), np.array([]), np.array([])\n    all_sci, all_ivar, all_idx, all_wghts = np.array([]), np.array([]), np.array([]), np.array([])\n    all_wcs = []\n    dspat = None if cubepar['spatial_delta'] is None else  cubepar['spatial_delta']/3600.0  # binning size on the sky (/3600 to convert to degrees)\n    dwv = cubepar['wave_delta']       # binning size in wavelength direction (in Angstroms)\n    wave_ref = None\n    whitelight_img = None  # This is the whitelight image based on all input spec2d frames\n    weights = np.ones(numfiles)  # Weights to use when combining cubes\n    for ff, fil in enumerate(files):\n        # Load it up\n        spec2DObj = spec2dobj.Spec2DObj.from_file(fil, det)\n        detector = spec2DObj.detector\n\n        # Setup for PypeIt imports\n        msgs.reset(verbosity=2)\n\n        if ref_scale is None:\n            ref_scale = spec2DObj.scaleimg.copy()\n        # Extract the information\n        sciimg = (spec2DObj.sciimg-spec2DObj.skymodel) * (ref_scale/spec2DObj.scaleimg)  # Subtract sky and apply relative sky\n        ivar = spec2DObj.ivarraw / (ref_scale/spec2DObj.scaleimg)**2\n        waveimg = spec2DObj.waveimg\n        bpmmask = spec2DObj.bpmmask\n\n        # Grab the slit edges\n        slits = spec2DObj.slits\n\n        wave0 = waveimg[waveimg != 0.0].min()\n        diff = waveimg[1:, :] - waveimg[:-1, :]\n        dwv = float(np.median(diff[diff != 0.0]))\n        msgs.info(\"Using wavelength solution: wave0={0:.3f}, dispersion={1:.3f} Angstrom/pixel\".format(wave0, dwv))\n\n        msgs.info(\"Constructing slit image\")\n        slitid_img_init = slits.slit_img(pad=0, initial=True, flexure=spec2DObj.sci_spat_flexure)\n        onslit_gpm = (slitid_img_init > 0) & (bpmmask == 0)\n\n        # Grab the WCS of this frame\n        wcs = spec.get_wcs(spec2DObj.head0, slits, detector.platescale, wave0, dwv)\n        all_wcs.append(copy.deepcopy(wcs))\n\n        # Find the largest spatial scale of all images being combined\n        # TODO :: probably need to put this in the DetectorContainer\n        pxscl = detector.platescale * parse.parse_binning(detector.binning)[1] / 3600.0  # This should be degrees/pixel\n        slscl = spec.get_meta_value([spec2DObj.head0], 'slitwid')\n        if dspat is None:\n            dspat = max(pxscl, slscl)\n        elif max(pxscl, slscl) > dspat:\n            dspat = max(pxscl, slscl)\n\n        # Generate an RA/DEC image\n        msgs.info(\"Generating RA/DEC image\")\n        raimg, decimg, minmax = slits.get_radec_image(wcs, initial=True, flexure=spec2DObj.sci_spat_flexure)\n\n        # Perform the DAR correction\n        if wave_ref is None:\n            wave_ref = 0.5*(np.min(waveimg[onslit_gpm]) + np.max(waveimg[onslit_gpm]))\n        # Get DAR parameters\n        raval = spec.get_meta_value([spec2DObj.head0], 'ra')\n        decval = spec.get_meta_value([spec2DObj.head0], 'dec')\n        obstime = spec.get_meta_value([spec2DObj.head0], 'obstime')\n        pressure = spec.get_meta_value([spec2DObj.head0], 'pressure')\n        temperature = spec.get_meta_value([spec2DObj.head0], 'temperature')\n        rel_humidity = spec.get_meta_value([spec2DObj.head0], 'humidity')\n        coord = SkyCoord(raval, decval, unit=(units.deg, units.deg))\n        location = spec.location  # TODO :: spec.location should probably end up in the TelescopePar (spec.telescope.location)\n        ra_corr, dec_corr = dc_utils.dar_correction(waveimg[onslit_gpm], coord, obstime, location,\n                                                    pressure, temperature, rel_humidity, wave_ref=wave_ref)\n        raimg[onslit_gpm] += ra_corr\n        decimg[onslit_gpm] += dec_corr\n\n        # Get copies of arrays to be saved\n        wave_ext = waveimg[onslit_gpm].copy()\n        flux_ext = sciimg[onslit_gpm].copy()\n        ivar_ext = ivar[onslit_gpm].copy()\n\n        # Perform extinction correction\n        msgs.info(\"Applying extinction correction\")\n        longitude = spec.telescope['longitude']\n        latitude = spec.telescope['latitude']\n        airmass = spec2DObj.head0[spec.meta['airmass']['card']]\n        extinct = load_extinction_data(longitude, latitude)\n        # extinction_correction requires the wavelength is sorted\n        wvsrt = np.argsort(wave_ext)\n        ext_corr = extinction_correction(wave_ext[wvsrt] * units.AA, airmass, extinct)\n        # Correct for extinction\n        flux_sav = flux_ext[wvsrt] * ext_corr\n        ivar_sav = ivar_ext[wvsrt] / ext_corr ** 2\n        # sort back to the original ordering\n        resrt = np.argsort(wvsrt)\n\n        # Calculate the weights relative to the zeroth cube\n        if ff != 0:\n            weights[ff] = np.median(flux_sav[resrt]*np.sqrt(ivar_sav[resrt]))**2\n\n        # Store the information\n        numpix = raimg[onslit_gpm].size\n        all_ra = np.append(all_ra, raimg[onslit_gpm].copy())\n        all_dec = np.append(all_dec, decimg[onslit_gpm].copy())\n        all_wave = np.append(all_wave, wave_ext.copy())\n        all_sci = np.append(all_sci, flux_sav[resrt].copy())\n        all_ivar = np.append(all_ivar, ivar_sav[resrt].copy())\n        all_idx = np.append(all_idx, ff*np.ones(numpix))\n        all_wghts = np.append(all_wghts, weights[ff]*np.ones(numpix))\n\n    # Grab cos(dec) for convenience\n    cosdec = np.cos(np.mean(all_dec) * np.pi / 180.0)\n\n    # Register spatial offsets between all frames if several frames are being combined\n    if combine:\n\n        # Check if a reference whitelight image should be used to register the offsets\n        if cubepar[\"reference_image\"] is None:\n            # Generate white light images\n            whitelight_imgs, _, _ = dc_utils.make_whitelight(all_ra, all_dec, all_wave, all_sci, all_wghts, all_idx,\n                                                             dspat)\n            # ref_idx will be the index of the cube with the highest S/N\n            ref_idx = np.argmax(weights)\n            reference_image = whitelight_imgs[:, :, ref_idx].copy()\n            msgs.info(\"Calculating spatial translation of each cube relative to cube #{0:d})\".format(ref_idx+1))\n        else:\n            ref_idx = -1  # Don't use an index\n            # Load reference information\n            reference_image, whitelight_imgs, wlwcs = \\\n                dc_utils.make_whitelight_fromref(all_ra, all_dec, all_wave, all_sci, all_wghts, all_idx, dspat,\n                                                 cubepar['reference_image'])\n            msgs.info(\"Calculating the spatial translation of each cube relative to user-defined 'reference_image'\")\n        # Calculate the image offsets - check the reference is a zero shift\n        ra_shift_ref, dec_shift_ref = calculate_image_offset(reference_image.copy(), reference_image.copy())\n        for ff in range(numfiles):\n            # Don't correlate the reference image with itself\n            if ff == ref_idx:\n                continue\n            # Calculate the shift\n            ra_shift, dec_shift = calculate_image_offset(whitelight_imgs[:, :, ff], reference_image.copy())\n            # Convert to reference\n            ra_shift -= ra_shift_ref\n            dec_shift -= dec_shift_ref\n            # Convert pixel shift to degress shift\n            ra_shift *= dspat/cosdec\n            dec_shift *= dspat\n            msgs.info(\"Spatial shift of cube #{0:d}: RA, DEC (arcsec) = {1:+0.3f}, {2:+0.3f}\".format(ff+1, ra_shift*3600.0, dec_shift*3600.0))\n            # Apply the shift\n            all_ra[all_idx == ff] += ra_shift\n            all_dec[all_idx == ff] += dec_shift\n\n        # Generate a white light image of *all* data\n        msgs.info(\"Generating global white light image\")\n        if cubepar[\"reference_image\"] is None:\n            whitelight_img, _, wlwcs = dc_utils.make_whitelight(all_ra, all_dec, all_wave, all_sci, all_wghts,\n                                                                np.zeros(all_ra.size), dspat)\n        else:\n            _, whitelight_img, wlwcs = \\\n                dc_utils.make_whitelight_fromref(all_ra, all_dec, all_wave, all_sci, all_wghts, np.zeros(all_ra.size),\n                                                 dspat, cubepar['reference_image'])\n\n        # Calculate the relative spectral weights of all pixels\n        all_wghts = dc_utils.compute_weights(all_ra, all_dec, all_wave, all_sci, all_ivar, all_idx,\n                                             whitelight_img[:, :, 0], dspat, dwv,\n                                             relative_weights=cubepar['relative_weights'])\n    # Check if a whitelight image should be saved\n    if cubepar['save_whitelight']:\n        # Check if the white light image still needs to be generated - if so, generate it now\n        if whitelight_img is None:\n            msgs.info(\"Generating global white light image\")\n            if cubepar[\"reference_image\"] is None:\n                whitelight_img, _, wlwcs = dc_utils.make_whitelight(all_ra, all_dec, all_wave, all_sci, all_wghts,\n                                                                    np.zeros(all_ra.size), dspat)\n            else:\n                _, whitelight_img, wlwcs = \\\n                    dc_utils.make_whitelight_fromref(all_ra, all_dec, all_wave, all_sci, all_wghts,\n                                                     np.zeros(all_ra.size),\n                                                     dspat, cubepar['reference_image'])\n        # Prepare and save the fits file\n        msgs.info(\"Saving white light image as: {0:s}\".format(out_whitelight))\n        img_hdu = fits.PrimaryHDU(whitelight_img.T, header=wlwcs.to_header())\n        img_hdu.writeto(out_whitelight, overwrite=overwrite)\n\n    # Setup the cube ranges\n    ra_min = cubepar['ra_min'] if cubepar['ra_min'] is not None else np.min(all_ra)\n    ra_max = cubepar['ra_max'] if cubepar['ra_max'] is not None else np.max(all_ra)\n    dec_min = cubepar['dec_min'] if cubepar['dec_min'] is not None else np.min(all_dec)\n    dec_max = cubepar['dec_max'] if cubepar['dec_max'] is not None else np.max(all_dec)\n    wav_min = cubepar['wave_min'] if cubepar['wave_min'] is not None else np.min(all_wave)\n    wav_max = cubepar['wave_max'] if cubepar['wave_max'] is not None else np.max(all_wave)\n    if cubepar['wave_delta'] is not None: dwv = cubepar['wave_delta']\n    # Generate a master WCS to register all frames\n    coord_min = [ra_min, dec_min, wav_min]\n    coord_dlt = [dspat, dspat, dwv]\n    masterwcs = dc_utils.generate_masterWCS(coord_min, coord_dlt, name=specname)\n    msgs.info(msgs.newline()+\"-\"*40 +\n              msgs.newline() + \"Parameters of the WCS:\" +\n              msgs.newline() + \"RA   min, max = {0:f}, {1:f}\".format(ra_min, ra_max) +\n              msgs.newline() + \"DEC  min, max = {0:f}, {1:f}\".format(dec_min, dec_max) +\n              msgs.newline() + \"WAVE min, max = {0:f}, {1:f}\".format(wav_min, wav_max) +\n              msgs.newline() + \"Spaxel size = {0:f}''\".format(3600.0*dspat) +\n              msgs.newline() + \"Wavelength step = {0:f} A\".format(dwv) +\n              msgs.newline() + \"-\" * 40)\n\n    # Generate the output binning\n    if combine:\n        numra = int((ra_max-ra_min) * cosdec / dspat)\n        numdec = int((dec_max-dec_min)/dspat)\n        numwav = int((wav_max-wav_min)/dwv)\n        xbins = np.arange(1+numra)-0.5\n        ybins = np.arange(1+numdec)-0.5\n        spec_bins = np.arange(1+numwav)-0.5\n    else:\n        slitlength = int(np.round(np.median(slits.get_slitlengths(initial=True, median=True))))\n        numwav = int((np.max(waveimg) - wave0) / dwv)\n        xbins, ybins, spec_bins = spec.get_datacube_bins(slitlength, minmax, numwav)\n\n    # Make the cube\n    msgs.info(\"Generating pixel coordinates\")\n    if combine:\n        pix_coord = masterwcs.wcs_world2pix(all_ra, all_dec, all_wave * 1.0E-10, 0)\n        hdr = masterwcs.to_header()\n    else:\n        pix_coord = wcs.wcs_world2pix(np.vstack((all_ra, all_dec, all_wave*1.0E-10)).T, 0)\n        hdr = wcs.to_header()\n\n    # Find the NGP coordinates for all input pixels\n    msgs.info(\"Generating data cube\")\n    bins = (xbins, ybins, spec_bins)\n    datacube, edges = np.histogramdd(pix_coord, bins=bins, weights=all_sci*all_wghts)\n    norm, edges = np.histogramdd(pix_coord, bins=bins, weights=all_wghts)\n    norm_cube = (norm > 0) / (norm + (norm == 0))\n    datacube *= norm_cube\n    # Create the variance cube, including weights\n    msgs.info(\"Generating variance cube\")\n    all_var = (all_ivar > 0) / (all_ivar + (all_ivar == 0))\n    var_cube, edges = np.histogramdd(pix_coord, bins=bins, weights=all_var * all_wghts**2)\n    var_cube *= norm_cube**2\n\n    # Save the datacube\n    debug = False\n    if debug:\n        datacube_resid, edges = np.histogramdd(pix_coord, bins=(xbins, ybins, spec_bins), weights=all_sci*np.sqrt(all_ivar))\n        norm, edges = np.histogramdd(pix_coord, bins=(xbins, ybins, spec_bins))\n        norm_cube = (norm > 0) / (norm + (norm == 0))\n        outfile = \"datacube_resid.fits\"\n        msgs.info(\"Saving datacube as: {0:s}\".format(outfile))\n        hdu = fits.PrimaryHDU((datacube_resid*norm_cube).T, header=masterwcs.to_header())\n        hdu.writeto(outfile, overwrite=overwrite)\n\n    msgs.info(\"Saving datacube as: {0:s}\".format(outfile))\n    final_cube = dc_utils.DataCube(datacube.T, var_cube.T, specname,\n                                   refscale=ref_scale, fluxed=cubepar['flux_calibrate'])\n    final_cube.to_file(outfile, hdr=hdr, overwrite=overwrite)\n\n\ndef main(args):\n    if args.file is None:\n        msgs.error('You must input a coadd3d file')\n    else:\n        spectrograph_name, config_lines, spec2d_files = io.read_spec2d_file(args.file, filetype=\"coadd3d\")\n        spectrograph = load_spectrograph(spectrograph_name)\n\n        # Parameters\n        spectrograph_def_par = spectrograph.default_pypeit_par()\n        parset = par.PypeItPar.from_cfg_lines(cfg_lines=spectrograph_def_par.to_config(),\n                                              merge_with=config_lines)\n        # If detector was passed as an argument override whatever was in the coadd3d file\n        if args.det is not None:\n            msgs.info(\"Restricting to detector={}\".format(args.det))\n            parset['rdx']['detnum'] = int(args.det)\n\n    # Coadd the files\n    coadd_cube(spec2d_files, parset, overwrite=args.overwrite)\n", "meta": {"hexsha": "fc160bcea27c34433d77fd970a778e1b9415f68d", "size": 17834, "ext": "py", "lang": "Python", "max_stars_repo_path": "pypeit/scripts/coadd_datacube.py", "max_stars_repo_name": "NathanSandford/PypeIt", "max_stars_repo_head_hexsha": "89470d27422b7f8662642060b5687a5b2fda27ed", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pypeit/scripts/coadd_datacube.py", "max_issues_repo_name": "NathanSandford/PypeIt", "max_issues_repo_head_hexsha": "89470d27422b7f8662642060b5687a5b2fda27ed", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pypeit/scripts/coadd_datacube.py", "max_forks_repo_name": "NathanSandford/PypeIt", "max_forks_repo_head_hexsha": "89470d27422b7f8662642060b5687a5b2fda27ed", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.2651933702, "max_line_length": 147, "alphanum_fraction": 0.6391723674, "include": true, "reason": "import numpy,from astropy", "num_tokens": 4591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.19196657202003395}}
{"text": "# Lint as: python2, python3\n# Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Implementation for distributed Shampoo optimizer.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\nimport lingvo.compat as tf\nfrom lingvo.core import matrix_functions\nfrom lingvo.core import ops as x_ops\nimport numpy as np\n\n# pylint: disable=g-direct-tensorflow-import\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.training import optimizer\n# pylint: enable=g-direct-tensorflow-import\n\n\nclass PartitionConfig(object):\n  \"\"\"Config for tensor partitioning.\"\"\"\n\n  def __init__(self, max_dim_size, partition_size):\n    \"\"\"Initialize the `PartitionConfig`.\n\n    Args:\n      max_dim_size: Partitions dimensions with size greater than this value.\n      partition_size: Size of each partition\n    \"\"\"\n    self.max_dim_size = max_dim_size\n    self.partition_size = partition_size\n\n\nclass PartitionMetadata(object):\n  \"\"\"Metadata for partitioning.\"\"\"\n\n  def __init__(self, split_sizes_per_dim, num_splits_per_dim):\n    \"\"\"Initialize the `PartitionMetadata`.\n\n    Args:\n      split_sizes_per_dim: Split sizes per dimemsion.\n      num_splits_per_dim: Number of splits per dimension ( inferred from\n        split_sizes_per_dim).\n    \"\"\"\n    self.split_sizes_per_dim = split_sizes_per_dim\n    self.num_splits_per_dim = num_splits_per_dim\n\n\nclass TensorPartitioner(object):\n  \"\"\"Shards Tensor's across its axis.\n\n  In cases of TPUs, these partitions are zero cost, and does not involve data\n  movement.\n  \"\"\"\n\n  @classmethod\n  def partition_metadata(cls, tensor, partition_info):\n    \"\"\"Returns metadata required for partitioning and reforming tensors.\n\n    Args:\n      tensor: Tensor to partition.\n      partition_info: Partitioning info.\n\n    Returns:\n      split_sizes_per_dim and num_splits_per_dim.\n    \"\"\"\n    shape = tensor.get_shape()\n    # Split if dim is greater than max_dim.\n    axis_to_shard = [s > partition_info.max_dim_size for s in shape]\n    split_sizes_per_dim = []\n    # Compute the number of splits, and the sizes of the splits for\n    # each dimension\n    for sharded, dim in zip(axis_to_shard, shape):\n      dim = int(dim)\n      split_sizes_per_dim.append([dim])\n      if sharded:\n        split_sizes = []\n        num_shards = dim // partition_info.partition_size\n        if num_shards > 0:\n          split_sizes = [partition_info.partition_size] * num_shards\n          last_shard_size = dim % partition_info.partition_size\n          if last_shard_size > 0:\n            split_sizes.append(last_shard_size)\n        else:\n          split_sizes.append(dim)\n        split_sizes_per_dim[-1] = split_sizes\n    num_splits_per_dim = [len(v) for v in split_sizes_per_dim]\n    return PartitionMetadata(split_sizes_per_dim, num_splits_per_dim)\n\n  @classmethod\n  def partition_tensor(cls, tensor, partition_info):\n    \"\"\"Returns partitioned tensors.\"\"\"\n    metadata = (TensorPartitioner.partition_metadata(tensor, partition_info))\n    # Split from last to first axis.\n    partitioned_tensors = [tensor]\n    rank = len(metadata.num_splits_per_dim)\n    for raxis, (num_splits, sizes) in enumerate(\n        zip(\n            reversed(metadata.num_splits_per_dim),\n            reversed(metadata.split_sizes_per_dim))):\n      if num_splits > 1:\n        tmp_partitioned_tensors = []\n        for item in partitioned_tensors:\n          tmp_partitioned_tensors += tf.split(\n              item, sizes, axis=rank - raxis - 1)\n        partitioned_tensors = tmp_partitioned_tensors\n    return partitioned_tensors\n\n  @classmethod\n  def reform_tensor(cls, partitioned_tensors, num_splits_per_dim):\n    \"\"\"Returns a tensor concatenated from the given partitions.\"\"\"\n    # Concatenates tensors across all dimension. Assumes the `partitions` tensor\n    # was created by partition_tensor.\n    for axis, num_splits in enumerate(num_splits_per_dim):\n      if num_splits > 1:\n        tmp_partitioned_tensors = []\n        num_concat = len(partitioned_tensors) // num_splits\n        for i in range(num_concat):\n          tensors_to_concat = (\n              partitioned_tensors[i * num_splits:(i + 1) * num_splits])\n          tmp_partitioned_tensors.append(\n              tf.concat(tensors_to_concat, axis=axis))\n        partitioned_tensors = tmp_partitioned_tensors\n    return partitioned_tensors[0]\n\n\nclass DistributedShampoo(optimizer.Optimizer):\n  \"\"\"Approximates full-matrix AdaGrad per layer.\n\n  Approximates full-matrix AdaGrad with kronecker-products of two statistics\n  matrices based on only the first-order gradients of the layer.\n\n  \"Second-order optimization made practical.\", 2019\n  Rohan Anil, Vineet Gupta, Tomer Koren, Kevin Regan, Yoram Singer.\n  \"\"\"\n\n  def __init__(self,\n               learning_rate,\n               momentum=0.0,\n               initial_accumulator_value=0.0,\n               start_preconditioning_steps=1000,\n               statistics_computation_frequency=1,\n               matrix_epsilon=1e-6,\n               synchronous_preconditioning=False,\n               second_moment_averaging=1.0,\n               fallback_to_diagonal_dim=4096,\n               max_any_dim=6656,\n               block_size=4096,\n               block_partition_threshold_size=1000000,\n               global_step=None,\n               exponent_multiplier=1.0,\n               name=\"DistributedShampoo\"):\n    \"\"\"Construct a DistributedShampoo optimizer.\n\n    Args:\n      learning_rate: A `Tensor` or a floating point value.  The learning rate.\n      momentum: A `Tensor` or a floating point value. Momentum is not applied to\n        sparse updates.\n      initial_accumulator_value: A floating point value.\n      start_preconditioning_steps: A int32 value which indicates when to start\n        preconditioning.\n      statistics_computation_frequency: A int32 step value which indicates how\n        often to compute statistics for preconditioning.\n      matrix_epsilon: An epsilon regularizer to make the matrices positive\n        definite.\n      synchronous_preconditioning: Whether to run preconditioning synchronously.\n      second_moment_averaging: 1.0 means sum of gradients squares, while less\n        than 1.0 switches to RMSProp style exponential moving averages of the\n        second moments.\n      fallback_to_diagonal_dim: Fallback to diagonal version of AFMA if the any\n        of the dimension is larger than fallback_to_diagonal_dim.\n      max_any_dim: If maximum value for any dimension is greater than this value\n        we skip preconditioning and fall back to the diagonal.\n      block_size: Dimension of the partitioned tensors.\n      block_partition_threshold_size: Partitions diemnsions beyond this size.\n      global_step: Global step for training.\n      exponent_multiplier: A multiplier 'e` for the exponent for the inverse\n        calculation. e * -1/(2*rank). Only applies when calculating inverses\n        through svd.\n      name: Optional name prefix for the operations created when applying\n        gradients.\n    \"\"\"\n    super(DistributedShampoo, self).__init__(False, name)\n    self._learning_rate = learning_rate\n    self._momentum = momentum\n    self._initial_accumulator_value = initial_accumulator_value\n    self._start_preconditioning_steps = start_preconditioning_steps\n    self._matrix_epsilon = matrix_epsilon\n    self._synchronous_preconditioning = synchronous_preconditioning\n    self._second_moment_averaging = second_moment_averaging\n    self._fallback_to_diagonal_dim = fallback_to_diagonal_dim\n    self._max_any_dim = max_any_dim\n    self._block_size = block_size\n    # NOTE: On XLA - int64 is not handled properly.\n    if global_step is not None:\n      self._global_step = tf.cast(tf.identity(global_step), tf.int32)\n    else:\n      self._global_step = tf.cast(\n          tf.identity(tf.train.get_or_create_global_step()), tf.int32)\n    self._run_nondiagonal_update = tf.greater_equal(\n        self._global_step, self._start_preconditioning_steps)\n    start_steps_f = tf.cast(self._start_preconditioning_steps, tf.float32)\n    global_step_f = tf.cast(self._global_step, tf.float32)\n    self._run_nondiagonal_update_warmup = tf.minimum(\n        1.0, tf.maximum((global_step_f - start_steps_f) / start_steps_f, 0.0))\n    # Computes statistics every K steps.\n    self._statistics_computation_frequency = statistics_computation_frequency\n    self._run_statistics_computation = tf.equal(\n        tf.math.floormod(self._global_step,\n                         self._statistics_computation_frequency), 0)\n    # All vars that are preconditioned.\n    self._all_vars_for_preconditioning = []\n    self._exponent_multiplier = exponent_multiplier\n    self._partition_info = PartitionConfig(block_partition_threshold_size,\n                                           block_size)\n    self._partitioner_metadata = {}\n\n  def _fallback_to_diagonal_for_shape(self, shape):\n    \"\"\"Returns whether we should fallback to the diagonal update given shape.\"\"\"\n    # We fallback to diagonal for the following usecases:\n    #\n    # (a) Rank <= 1 tensors\n    # (b) if any dim of Tensor is > max_any_dim.\n    # (c) if all dims are 1 or are greater than fallback_to_diagonal_dim\n    #\n    if len(shape) <= 1:\n      return True\n    if any([d > self._max_any_dim for d in shape]):\n      return True\n    if all([d == 1 for d in shape]):\n      return True\n    return False\n\n  def _preconditioner_available_for_dims(self, shape):\n    \"\"\"Returns indicator vector if preconditioner exists for each axis.\"\"\"\n    # If any of the dims < fallback_to_diagonal_dim and not 1, we run a\n    # a preconditioner for that particular dimension.\n    return [d <= self._fallback_to_diagonal_dim and d != 1 for d in shape]\n\n  def _preconditioner_indices(self, shape):\n    \"\"\"Returns indices of the available preconditioner.\"\"\"\n    preconditioners_available_for_dims = (\n        self._preconditioner_available_for_dims(shape))\n    indices = []\n    index = 0\n    for is_avail_for_dim_i in preconditioners_available_for_dims:\n      indices.append(index)\n      if is_avail_for_dim_i:\n        index += 1\n    return indices\n\n  def _make_named_slot(self, var, val, slot_name):\n    _ = self._get_or_make_slot(var, val, slot_name,\n                               self._name + \"_\" + slot_name)\n\n  def make_named_zeros_slot(self, var, slot_name):\n    self._zeros_slot(var, slot_name, self._name + \"_\" + slot_name)\n\n  def _generalized_inverse_pth_root(self, input_t, exponent, epsilon=1e-12):\n    input_t_f64 = tf.cast(input_t, tf.float64)\n    s, u, v = tf.linalg.svd(\n        input_t_f64 +\n        tf.eye(tf.shape(input_t_f64)[0], dtype=tf.float64) * epsilon,\n        full_matrices=True)\n    inv_s = tf.reshape(\n        tf.pow(tf.maximum(s, epsilon), tf.cast(exponent, tf.float64)), [1, -1])\n    val = tf.matmul(u * inv_s, v, adjoint_b=True)\n    return tf.cast(val, tf.float32), tf.reduce_max(tf.abs(u - v))\n\n  def _specialized_inverse_pth_root(self, input_t, exponent, epsilon=1e-12):\n    input_t_f64 = tf.cast(input_t, tf.float64)\n    val, error = matrix_functions.inlined_matrix_inverse_pth_root(\n        input_t_f64,\n        tf.shape(input_t_f64)[0],\n        exponent,\n        iter_count=40,\n        ridge_epsilon=epsilon)\n    return tf.cast(val, tf.float32), error\n\n  def _inverse_pth_root_graph(self, epsilon):\n    graph = tf.Graph()\n    with graph.as_default():\n      exponent_t = tf.reshape(\n          tf.placeholder(dtype=tf.float32, name=\"exponent\", shape=None), [])\n      # Apply exponent multiplier.\n      exponent_t = exponent_t * self._exponent_multiplier\n      input_t = tf.placeholder(dtype=tf.float32, name=\"input\", shape=None)\n      # For p = 2, 4 or 8, we use the iterative Newton-Schur method for\n      # computing the inverse-pth root.\n      either_p_2_4_8 = tf.math.logical_or(\n          tf.math.logical_or(\n              tf.equal(-1.0 / exponent_t, 2), tf.equal(-1.0 / exponent_t, 4)),\n          tf.equal(-1.0 / exponent_t, 8))\n      # 4096 is the larger dimension SVD is tractable for.\n      greater_than_4096 = tf.greater(tf.shape(input_t)[0], 4096)\n      run_specialized_iterative_method = tf.math.logical_and(\n          greater_than_4096, either_p_2_4_8)\n      specialized_fn = functools.partial(self._specialized_inverse_pth_root,\n                                         input_t, exponent_t, epsilon)\n      generalized_fn = functools.partial(self._generalized_inverse_pth_root,\n                                         input_t, exponent_t, epsilon)\n      output, diff = tf.cond(run_specialized_iterative_method, specialized_fn,\n                             generalized_fn)\n\n      tf.identity(output, \"output\")\n      tf.identity(tf.cast(diff, tf.float32), \"diff\")\n    return graph.as_graph_def().SerializeToString()\n\n  def _create_slots(self, var_list):\n    self._preconditioner_compute_graphdef = self._inverse_pth_root_graph(\n        epsilon=self._matrix_epsilon)\n    for v in var_list:\n      self._make_named_slot(v,\n                            tf.ones_like(v) * self._initial_accumulator_value,\n                            \"accumulator\")\n\n      if self._momentum > 0.0:\n        self.make_named_zeros_slot(v, \"momentum\")\n      shape = np.array(v.get_shape())\n      self._partitioner_metadata[v] = TensorPartitioner.partition_metadata(\n          v, self._partition_info)\n      partitioned_v = TensorPartitioner.partition_tensor(\n          v, self._partition_info)\n      if not self._fallback_to_diagonal_for_shape(shape):\n        self._all_vars_for_preconditioning.append(v)\n        if self._momentum > 0.0:\n          self.make_named_zeros_slot(v, \"precond_grad_momentum\")\n        num_partitions = len(partitioned_v)\n        for pt_idx, pt_v in enumerate(partitioned_v):\n          pt_v_shape = pt_v.get_shape()\n          preconditioner_exists_for_dim = (\n              self._preconditioner_available_for_dims(pt_v_shape))\n          for i, d in enumerate(pt_v_shape):\n            if preconditioner_exists_for_dim[i]:\n              mat_stat_init = array_ops.zeros([d, d], dtype=pt_v.dtype)\n              self._make_named_slot(\n                  v, mat_stat_init,\n                  self._statistics_key_for_partition_and_dim(\n                      i, pt_idx, num_partitions))\n              self._make_named_slot(\n                  v, mat_stat_init,\n                  self._preconditioner_key_for_partition_and_dim(\n                      i, pt_idx, num_partitions))\n\n  def _prepare(self):\n    learning_rate = self._call_if_callable(self._learning_rate)\n    self._learning_rate_tensor = ops.convert_to_tensor(\n        learning_rate, name=\"learning_rate\")\n    momentum = self._call_if_callable(self._momentum)\n    self._momentum_tensor = ops.convert_to_tensor(momentum, name=\"momentum\")\n\n  def invoke_async_preconditioner_computation(self, global_step_int32):\n    \"\"\"Invokes SVD preconditioner and graph runs on the CPU.\"\"\"\n    keys_stats_and_rank = []\n    for var in self._all_vars_for_preconditioning:\n      shape = var.get_shape()\n      if not self._fallback_to_diagonal_for_shape(shape):\n        partitioned_v = TensorPartitioner.partition_tensor(\n            var, self._partition_info)\n        num_partitions = len(partitioned_v)\n        for pt_idx, pt_v in enumerate(partitioned_v):\n          pt_v_shape = pt_v.get_shape()\n          preconditioner_exists_for_dim = (\n              self._preconditioner_available_for_dims(pt_v_shape))\n          for i in range(len(pt_v_shape)):\n            if preconditioner_exists_for_dim[i]:\n              rank = sum(preconditioner_exists_for_dim)\n              key = self._key_for_var(var, i, pt_idx)\n              stat = self.get_slot(\n                  var,\n                  self._statistics_key_for_partition_and_dim(\n                      i, pt_idx, num_partitions))\n              keys_stats_and_rank.append((key, stat, rank))\n\n    if not keys_stats_and_rank:\n      return tf.no_op()\n    keys, stats, ranks = zip(*keys_stats_and_rank)\n\n    return x_ops.compute_preconditioners(\n        stats, [-1.0 / (2.0 * r) for r in ranks],\n        global_step_int32,\n        keys=keys,\n        sync=self._synchronous_preconditioning,\n        preconditioner_compute_graphdef=self._preconditioner_compute_graphdef)\n\n  def assign_preconditioner_to_host_vars(self):\n    \"\"\"Assign/Grab latest copy of preconditioners.\"\"\"\n    keys_shapes_and_preconditioner_vars = []\n    assign_ops = []\n    for var in self._all_vars_for_preconditioning:\n      shape = var.get_shape()\n      if not self._fallback_to_diagonal_for_shape(shape):\n        partitioned_v = TensorPartitioner.partition_tensor(\n            var, self._partition_info)\n        num_partitions = len(partitioned_v)\n        for pt_idx, pt in enumerate(partitioned_v):\n          pt_shape = pt.get_shape()\n          preconditioner_exists_for_dim = (\n              self._preconditioner_available_for_dims(pt_shape))\n          var_rank = len(pt_shape)\n          for i in range(var_rank):\n            if preconditioner_exists_for_dim[i]:\n              key = self._key_for_var(var, i, pt_idx)\n              preconditioner = self.get_slot(\n                  var,\n                  self._preconditioner_key_for_partition_and_dim(\n                      i, pt_idx, num_partitions))\n              keys_shapes_and_preconditioner_vars.append(\n                  (key, tf.shape(preconditioner), preconditioner))\n\n      if not keys_shapes_and_preconditioner_vars:\n        return tf.no_op()\n\n      keys, shapes, preconditioner_vars = zip(\n          *keys_shapes_and_preconditioner_vars)\n\n      preconditioner_vals, successes = x_ops.get_preconditioners(\n          shapes,\n          keys=keys,\n          preconditioner_compute_graphdef=(\n              self._preconditioner_compute_graphdef))\n\n      for preconditioner_var, preconditioner_val, success in zip(\n          preconditioner_vars, preconditioner_vals, successes):\n        success_mult = tf.cast(success, preconditioner.dtype)\n        assign_ops.append(\n            state_ops.assign(preconditioner_var,\n                             (1.0 - success_mult) * preconditioner_var +\n                             success_mult * preconditioner_val))\n    return tf.group(*assign_ops)\n\n  def _statistics_key_for_partition_and_dim(self, dim_index, partition_index,\n                                            num_partitions):\n    if num_partitions == 1:\n      return \"mat_statistics_\" + str(dim_index)\n    else:\n      return str(partition_index) + \"_mat_statistics_\" + str(dim_index)\n\n  def _preconditioner_key_for_partition_and_dim(self, dim_index,\n                                                partition_index,\n                                                num_partitions):\n    if num_partitions == 1:\n      return \"mat_preconditioner_\" + str(dim_index)\n    else:\n      return str(partition_index) + \"_mat_preconditioner_\" + str(dim_index)\n\n  def _key_for_var(self, var, dim_index, partition_index):\n    return \"P_\" + str(partition_index) + \"_D_\" + str(dim_index) + \"_\" + var.name\n\n  def _updated_statistics(self, var, partitioned_grads):\n    \"\"\"Returns updated Shampoo statistics L_t, R_t, etc.\n\n    Args:\n      var: tf.Variable associated with the gradient.\n      partitioned_grads: Partitioned gradient tensor.\n\n    Returns:\n      A list of updated statistics matrices.\n    \"\"\"\n    precond_statistics_update = []\n    num_partitions = len(partitioned_grads)\n    mat_stats = []\n    mat_grads = []\n    mat_dims = []\n    for pt_idx, pt_grad in enumerate(partitioned_grads):\n      pt_shape = pt_grad.get_shape()\n      preconditioner_exists_for_dim = (\n          self._preconditioner_available_for_dims(pt_shape))\n      rank = len(pt_shape)\n      # Calculates the preconditioner statistics for each tensor.\n      for i in range(rank):\n        if preconditioner_exists_for_dim[i]:\n          mat_stats.append(\n              self.get_slot(\n                  var,\n                  self._statistics_key_for_partition_and_dim(\n                      i, pt_idx, num_partitions)))\n          mat_grads.append(pt_grad)\n          mat_dims.append(i)\n\n    # axes is the list of indices to reduce - everything but\n    # the current i.\n    def _update_statistics(dim, stat_var, grad):\n      \"\"\"Update preconditioner statistics.\"\"\"\n      with tf.variable_scope(\"GradientStatistics\"):\n        var_rank = len(grad.get_shape())\n        axes = list(range(dim)) + list(range(dim + 1, var_rank))\n        new_stat = math_ops.tensordot(grad, grad, axes=(axes, axes))\n        if self._second_moment_averaging == 1.0:\n          updated_stat = state_ops.assign_add(stat_var, new_stat)\n        else:\n          updated_stat = state_ops.assign_add(\n              stat_var, (self._second_moment_averaging - 1.0) * stat_var +\n              (1.0 - self._second_moment_averaging) * new_stat)\n        return updated_stat\n\n    if self._statistics_computation_frequency <= 1:\n      for mat_stat, mat_grad, dim in zip(mat_stats, mat_grads, mat_dims):\n        precond_statistics_update.append(\n            _update_statistics(dim, mat_stat, mat_grad))\n    else:\n\n      # NOTE: We rewrite tf.cond() as a while loop to avoid certain overheads\n      # in XLA from buffer allocation.\n      def _loop_body(mat_stats, mat_grads, mat_dims, unused_perform_step):\n        precond_statistics_update_ops = []\n        for mat_stat, mat_grad, dim in zip(mat_stats, mat_grads, mat_dims):\n          precond_statistics_update_ops.append(\n              _update_statistics(dim, mat_stat, mat_grad))\n        with tf.control_dependencies(precond_statistics_update_ops):\n          return tf.constant(False)\n\n      loop_body_fn = functools.partial(_loop_body, mat_stats, mat_grads,\n                                       mat_dims)\n      precond_statistics_update.append(\n          tf.while_loop(lambda perform_step: perform_step, loop_body_fn,\n                        [self._run_statistics_computation]))\n\n    return precond_statistics_update\n\n  def _compute_preconditioned_raw_grad(self, var, partitioned_grads):\n    \"\"\"Returns preconditioned gradient.\n\n    Args:\n      var: tf.Variable associated with the gradient.\n      partitioned_grads: Partitioned gradient tensor.\n\n    Returns:\n      A preconditioned gradient tensor.\n    \"\"\"\n\n    partitioned_preconditioned_grads = []\n    num_partitions = len(partitioned_grads)\n    for pt_idx, pt_grad in enumerate(partitioned_grads):\n      pt_shape = pt_grad.get_shape()\n      rank = len(pt_shape)\n      preconditioner_exists_for_dim = (\n          self._preconditioner_available_for_dims(pt_shape))\n      preconditioner_indices = self._preconditioner_indices(pt_shape)\n      mat_preconditioner_list = []\n      for i in range(rank):\n        if preconditioner_exists_for_dim[i]:\n          mat_preconditioner_list.append(\n              self.get_slot(\n                  var,\n                  self._preconditioner_key_for_partition_and_dim(\n                      i, pt_idx, num_partitions)))\n      precond_grad = pt_grad\n      if rank == 2 and all(preconditioner_exists_for_dim):\n        # Fast path for speedup.\n        precond_grad = tf.matmul(\n            tf.matmul(mat_preconditioner_list[0], precond_grad),\n            mat_preconditioner_list[1])\n      else:\n        for i in range(rank):\n          if preconditioner_exists_for_dim[i]:\n            precond_grad = tf.tensordot(\n                precond_grad,\n                mat_preconditioner_list[preconditioner_indices[i]],\n                axes=([0], [0]))\n          else:\n            # if preconditioner is not available we transpose it to\n            # permute the axis for the next preconditioner.\n            precond_grad = tf.transpose(\n                precond_grad, perm=list(range(1, rank)) + [0])\n      partitioned_preconditioned_grads.append(precond_grad)\n    return TensorPartitioner.reform_tensor(\n        partitioned_preconditioned_grads,\n        self._partitioner_metadata[var].num_splits_per_dim)\n\n  def _preconditioned_update(self, var, partitioned_grads,\n                             diagonal_grad_update):\n    \"\"\"Computes the matrix preconditioned update.\n\n    Args:\n      var: Variable for which we are computing the preconditioned gradient.\n      partitioned_grads: Partitioned gradients.\n      diagonal_grad_update: Update as given by diagonal adagrad.\n\n    Returns:\n      scaled preconditioned gradient.\n    \"\"\"\n\n    def _l2_norm(v):\n      return tf.sqrt(tf.reduce_sum(tf.square(v)))\n\n    precond_grad = self._compute_preconditioned_raw_grad(var, partitioned_grads)\n    if self._momentum > 0.0:\n      gbar = self.get_slot(var, \"precond_grad_momentum\")\n      matrix_preconditioned_grad = state_ops.assign(\n          gbar, gbar * self._momentum_tensor + precond_grad *\n          (1.0 - self._momentum_tensor))\n    else:\n      matrix_preconditioned_grad = precond_grad\n\n    # We use the direction from Shampoo while using the step size scale from\n    # diagonal AdaGrad.\n    precond_l2_norm = _l2_norm(matrix_preconditioned_grad)\n    diagonal_l2_norm = _l2_norm(diagonal_grad_update)\n    multiplier = tf.where(\n        tf.greater(precond_l2_norm, 0.0),\n        tf.maximum(diagonal_l2_norm, 1e-30) /\n        (tf.maximum(precond_l2_norm, 1e-30)), 1.0)\n    return matrix_preconditioned_grad * multiplier\n\n  def _apply_dense(self, grad, var):\n    # Calculates the preconditioner statistics for each tensor.\n    partitioned_grads = TensorPartitioner.partition_tensor(\n        grad, self._partition_info)\n    shape = var.get_shape()\n    fallback_to_diagonal = self._fallback_to_diagonal_for_shape(shape)\n\n    precond_statistics_update = []\n    if not fallback_to_diagonal:\n      precond_statistics_update = self._updated_statistics(\n          var, partitioned_grads)\n\n    accumulator = self.get_slot(var, \"accumulator\")\n    accumulator_updated = state_ops.assign_add(accumulator, grad * grad)\n    accumulator_inv_sqrt = math_ops.rsqrt(accumulator_updated + 1e-30)\n    if self._momentum > 0.0:\n      scaled_g = (1.0 - self._momentum_tensor) * (grad * accumulator_inv_sqrt)\n      gbar = self.get_slot(var, \"momentum\")\n      gbar_updated = state_ops.assign_add(\n          gbar,\n          gbar * (self._momentum_tensor - 1.0) + scaled_g)\n    else:\n      gbar_updated = (grad * accumulator_inv_sqrt)\n\n    if not fallback_to_diagonal:\n      # Update the preconditioner statistics followed by computing the\n      # preconditioned gradient.\n      with ops.control_dependencies(precond_statistics_update):\n        s = tf.cast(self._run_nondiagonal_update, tf.float32)\n        preconditioned_grad = self._preconditioned_update(\n            var, partitioned_grads, gbar_updated)\n        # slowly adapt from diagonal to preconditioned gradient.\n        w = self._run_nondiagonal_update_warmup\n        warmup_update = s * self._learning_rate_tensor * (\n            w * preconditioned_grad + (1.0 - w) * gbar_updated)\n        fallback_update = (1 - s) * (self._learning_rate_tensor * gbar_updated)\n        return state_ops.assign_sub(var, warmup_update + fallback_update)\n    else:\n      return state_ops.assign_sub(var,\n                                  self._learning_rate_tensor * gbar_updated)\n\n  def _resource_apply_dense(self, grad, var):\n    return self._apply_dense(grad, var)\n\n  # Sparse gradients are not handled currently and is part of future work.\n  def _resource_apply_sparse(self, grad_values, var, grad_indices):\n    return tf.no_op()\n\n  def _apply_sparse(self, grad, var):\n    return tf.no_op()\n", "meta": {"hexsha": "ed6b64ff4a0c506ac18bdad5dabb28205bc754ec", "size": 27983, "ext": "py", "lang": "Python", "max_stars_repo_path": "lingvo/core/distributed_shampoo.py", "max_stars_repo_name": "Singed-jj/lingvo", "max_stars_repo_head_hexsha": "a2a4ac8bd835ffc2f95fc38ee3e9bc17c30fcc56", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lingvo/core/distributed_shampoo.py", "max_issues_repo_name": "Singed-jj/lingvo", "max_issues_repo_head_hexsha": "a2a4ac8bd835ffc2f95fc38ee3e9bc17c30fcc56", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lingvo/core/distributed_shampoo.py", "max_forks_repo_name": "Singed-jj/lingvo", "max_forks_repo_head_hexsha": "a2a4ac8bd835ffc2f95fc38ee3e9bc17c30fcc56", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6413690476, "max_line_length": 80, "alphanum_fraction": 0.6791266126, "include": true, "reason": "import numpy", "num_tokens": 6278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.1919467426860628}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nThis provides the basis for torque computation via two additional\nclasses: TorqueMap which has data for a torque derivation and \nGalacticTorque which derives from GalacticDisc and contains the torque\nmaps.\n\"\"\"\nimport numpy as np\n\n__author__ = \"Eric Emsellem\"\n__copyright__ = \"Eric Emsellem\"\n__license__ = \"mit\"\n\nfrom .disc import GalacticDisc\nfrom .misc_io import add_suffix, AttrDict, guess_stepx\nfrom .transform import extract_radial_profile_fromXY\nfrom .maps_grammar import remap_suffix, _is_flag_density\nfrom .local_units import km_pc\nfrom . import fit_functions as ff\nfrom . import gravpot_functions as gpot\n\nclass TorqueMap(object):\n    \"\"\"Main map class for the torques\n    \"\"\"\n    def __init__(self, massmap, mass_dname, comp_dname,\n                 velprof, vel_dname, pc_per_xyunit=1.0, PAnodes=0.0,\n                 factor_hz=12.0):\n        \"\"\"\n        \"\"\"\n        self.massmap = massmap\n        self.mass_dname = mass_dname\n        self.comp_dname = comp_dname\n        self.velprof = velprof\n        self.vel_dname = vel_dname\n        self.factor_hz = factor_hz\n\n        self.dmass = self.massmap.dmaps[self.mass_dname]\n        self.dcomp = self.massmap.dmaps[self.comp_dname]\n        self.dvel = self.velprof.dprofiles[self.vel_dname]\n        self.pc_per_xyunit = pc_per_xyunit\n\n        # Check the coordinates\n        self.Xdep = self.massmap.X_londep\n        self.Ydep = self.massmap.Y_londep\n        self.Rdep = np.sqrt(self.Xdep**2 + self.Ydep**2)\n        self.Xdep_pc = self.Xdep * self.pc_per_xyunit\n        self.Ydep_pc = self.Ydep * self.pc_per_xyunit\n        self.Rdep_pc = self.Rdep * self.pc_per_xyunit\n        self.pc_per_x = guess_stepx(self.Xdep_pc)\n        self.pc_per_y = guess_stepx(self.Ydep_pc)\n\n        # We also need a maximised X and Y grid to help with the kernel\n        self.Xdep_pcexp, self.Ydep_pcexp = self.get_XYpcexp()\n        self.Rdep_pcexp = np.sqrt(self.Xdep_pcexp**2 + self.Ydep_pcexp**2)\n\n        # Using the average between the x and y step in parsec\n        self.pc_per_pixel = (self.pc_per_x + self.pc_per_y) / 2.\n        self.PAnodes = PAnodes\n\n    @property\n    def XY_extent(self):\n        \"\"\"Provide the extent - a la matplotlib - for\n        the given map grid\n        \"\"\"\n        return [np.min(self.Xdep), np.max(self.Xdep),\n                np.min(self.Ydep), np.max(self.Ydep)]\n\n    @property\n    def XYpc_extent(self):\n        \"\"\"Provide the extent in parsec - a la matplotlib - for\n        the given map grid\n        \"\"\"\n        return [np.min(self.Xdep_pc), np.max(self.Xdep_pc),\n                np.min(self.Ydep_pc), np.max(self.Ydep_pc)]\n\n    def get_XYpcexp(self):\n        \"\"\"Provided an expanded grid for X and Y\n        which will be used later for the kernel convolution\n        \"\"\"\n        maxXpc = np.max(np.abs(self.Xdep_pc))\n        maxYpc = np.max(np.abs(self.Ydep_pc))\n        maxX = np.max(np.abs(self.Xdep_pc))\n        stepX = self.Xdep_pc[0,1] - self.Xdep_pc[0,0]\n        stepY = self.Ydep_pc[1,0] - self.Ydep_pc[0,0]\n        npixX = np.int(maxXpc // stepX) + 1\n        npixY = np.int(maxYpc // stepY) + 1\n        nmaxXpc = npixX * stepX\n        nmaxYpc = npixY * stepY\n        xlin = np.linspace(-nmaxXpc, nmaxXpc, npixX * 2 + 1)\n        ylin = np.linspace(-nmaxYpc, nmaxYpc, npixY * 2 + 1)\n        eX, eY = np.meshgrid(xlin, ylin)\n        return eX, eY\n\n    def get_mass_profile(self, wedge_size=0.0, wedge_angle=0):\n        \"\"\"Compute the 1d mass profile using the dmass.data\n        and a number of bins. A wedge-angle and size can be used to indicate\n        where to extract the data. Uses the extract_radial_profile_fromXY\n        function.\n\n        Input\n        -----\n        wedge_size (float): size of the wedge in degrees [0]\n        wedge_angle (float): angle of the central wedge (in degrees) [0]\n\n        Creates\n        -------\n        self.Rmass1d and self.mass1d following the deprojected grid Xdep, Ydep\n        and the dmass.data map.\n        \"\"\"\n        self.Rmass1d, self.mass1d = extract_radial_profile_fromXY(self.Xdep, self.Ydep,\n                                                                  self.dmass.data,\n                                                                  nbins=None, verbose=True,\n                                                                  wedge_size=wedge_size, \n                                                                  wedge_angle=wedge_angle)\n\n    def fit_mass_profile(self):\n        \"\"\"Fit the 1d mass profile\n        \"\"\"\n        self.opt_mass, self.fsphe1d, self.fdisc1d, self.fmass1d = ff.fit_disc_sphe(self.Rmass1d, self.mass1d)\n        self.bfit_mass1d = self.fmass1d(self.Rmass1d, self.opt_mass[0])\n        self.bfit_mass1d_sphe = self.fsphe1d(self.Rmass1d, self.opt_mass[0])\n        self.bfit_mass1d_disc = self.fdisc1d(self.Rmass1d, self.opt_mass[0])\n        self.bfit_sphe1d = self.fsphe1d(self.massmap._R, self.opt_mass[0])\n        self.bfit_sphe1d_dep = self.fsphe1d(self.Rdep, self.opt_mass[0])\n        self.massmap.faceon = self.dmass.data - self.bfit_sphe1d_dep + self.bfit_sphe1d\n        self.Rl_disc = self.opt_mass[0][3]\n\n    def get_kernel(self, softening=0.0, function=\"sech2\"):\n        \"\"\"Get the kernel array\n        \"\"\"\n        hz_pc = self.Rl_disc * self.pc_per_xyunit / self.factor_hz\n        self.kernel = gpot.get_gravpot_kernel(self.Rdep_pcexp, hz_pc,\n                                              pc_per_pixel=self.pc_per_pixel,\n                                              softening=softening,\n                                              function=function)\n\n    def get_gravpot(self):\n        \"\"\"Calculate the gravitational potential\n        \"\"\"\n        self.gravpot = gpot.get_potential(self.massmap.faceon \n                                          * self.pc_per_x * self.pc_per_y, \n                                          self.kernel)\n\n    def get_forces(self):\n        \"\"\"Calculate the forces from the potential\n        Units should be in km^2.s^-2.pc^-2\n        \"\"\"\n        self.Fgrad, self.Fx, self.Fy, self.Frad, self.Ftan = \\\n            gpot.get_forces(self.Xdep_pc, self.Ydep_pc,\n                            self.gravpot, self.PAnodes)\n\n    def get_vrot_from_forces(self):\n        \"\"\"Calculate the velocities from forces\n        \"\"\"\n        self.VcU = gpot.get_vrot_from_force(self.Rdep_pc, self.Frad)\n\n    def get_torque_map(self):\n        \"\"\"Compute the torque map\n\n        Units back are units of X * F (hence pc * F)\n        Since F is in (km/s)^2 pc-1 -> torque in (km/s)^2\n        \"\"\"\n        self.torque_map = gpot.get_torque(self.Xdep_pc, self.Ydep_pc,\n                                          self.Fx, self.Fy)\n\n    def get_weighted_torque_map(self):\n        \"\"\"Compute the torque map\n        \"\"\"\n        self.torque_w_map = gpot.get_weighted_torque(self.Xdep_pc, self.Ydep_pc,\n                                          self.Fx, self.Fy, self.dcomp.data)\n\n    def get_torque_profiles(self, n_rbins=300):\n        \"\"\"Get the profiles from the torque\n        \"\"\"\n        self.r_mean, self.v_mean, self.torque_mean, self.torque_mean_w, \\\n            self.ang_mom_mean, self.dm, self.dm_sum = \\\n            gpot.get_torque_profiles(self.Xdep_pc, self.Ydep_pc, self.VcU,\n                                     self.Fx, self.Fy, self.dcomp.data,\n                                     n_rbins=n_rbins, pc_per_pixel=self.pc_per_pixel)\n        # T in s\n        self.Trot = 2. * np.pi * self.r_mean * km_pc / self.v_mean\n        # dloL adimensional\n        self.dloL = self.torque_mean_w * self.Trot / self.ang_mom_mean\n\n    def get_torques(self, n_rbins=300):\n        \"\"\"Calculate the torques from existing forces\n\n        Args:\n            n_rbins:\n        \"\"\"\n        self.get_torque_map()\n        self.get_weighted_torque_map()\n        self.get_torque_profiles(n_rbins=n_rbins)\n\n    def run_torques(self, softening=0.0, func_kernel=\"sech2\", n_rbins=200):\n        \"\"\"Running the torque calculation from start to end\n\n        Args:\n            softening:\n            func_kernel:\n            n_rbins:\n\n        \"\"\"\n        # Step 1 - extract the radial profile and fit it with bulge and disc\n        self.get_mass_profile()\n\n        # Step 2 - Now doing the fit of the spheroid (and disc)\n        self.fit_mass_profile()\n\n        # Step 3 - calculate the kernel\n        self.get_kernel(softening=softening, function=func_kernel)\n\n        # Step 4 - calculate the potential\n        self.get_gravpot()\n\n        # Step 5 - Calculate the forces\n        self.get_forces()\n\n        # Step 6 - Get the rotation velocities\n        self.get_vrot_from_forces()\n\n        # Step 7 - Normalise the fields with M/L\n        # For the moment = passed\n\n        # Step 8 - Calculate the torques\n        self.get_torques(n_rbins=n_rbins)\n\n\nclass GalacticTorque(GalacticDisc):\n    \"\"\"Class for functionalities associated with Torques\n    \"\"\"\n\n    def __init__(self, vcfile_name=None, vcfile_type=\"ROTCUR\",\n                 Rfinestep=0, vprof_name=\"Velocity\", **kwargs):\n        \"\"\"\n\n        Args:\n            vcfile_name:\n            vcfile_type:\n            **kwargs:\n        \"\"\"\n        self.verbose = kwargs.pop(\"verbose\", False)\n\n        # Using GalacticDisc class attributes\n        super().__init__(**kwargs)\n\n        # Now the velocity file\n        if vcfile_name is not None:\n            print(\"INFO: Adding the provided Vc file\")\n            velname = self.add_vprofile(filename=vcfile_name, filetype=vcfile_type,\n                              Rfinestep=Rfinestep, vprof_name=vprof_name)\n        else:\n            velname = kwargs.pop(\"velname\", \"vel_vel01\")\n\n        # And checking the maps\n        compname = kwargs.pop(\"compname\", \"comp_comp01\")\n        massname = kwargs.pop(\"massname\", \"mass_mass01\")\n        self.init_torque_components(velname=velname, compname=compname,\n                                    massname=massname)\n\n        # Make sure we start with a clean set of torque maps\n        self._reset_torquemaps()\n\n\n    @property\n    def velname(self):\n        return self.profiles[self.vel_pname]._fullname(self.vel_dname)\n\n    @property\n    def massname(self):\n        return self.maps[self.mass_mname]._fullname(self.mass_dname)\n\n    @property\n    def compname(self):\n        return self.maps[self.comp_mname]._fullname(self.comp_dname)\n\n    def init_torque_components(self, **kwargs):\n        \"\"\"Initialise the torque maps components\n\n        Args:\n            **kwargs: velname, compname, massname\n\n        \"\"\"\n        self._decode_torque_names(**kwargs)\n        self.check_torque_components()\n        if self._check_all:\n            self.match_comp_mass()\n\n    def _decode_torque_names(self, velname=None, compname=None, massname=None):\n        \"\"\"\n\n        Args:\n            velname (str): composite name for the velocity profile\n            compname (str): composite name for the component map\n            massname (str): composite name for the mass map\n\n        \"\"\"\n        # Decoding the names\n        self.vel_pname, self.vel_dname = self._decode_prof_name(velname)\n        self.comp_mname, self.comp_dname = self._decode_map_name(compname)\n        self.mass_mname, self.mass_dname = self._decode_map_name(massname)\n\n    def check_torque_components(self):\n        \"\"\"Find the components for the torque calculations using the composite\n        names for the velocities, component (e.g., gas flux) and mass.\n\n        \"\"\"\n        # Checking the maps and profiles\n        # And making sure they are density maps\n        if self._check_mass():\n            thismap = self.massmap\n            if not _is_flag_density(self.massdmap.flag):\n                self.mass_dname = thismap.intmap_to_densitymap(self.mass_dname, self)\n\n        if self._check_comp():\n            thismap = self.compmap\n            if not _is_flag_density(self.compdmap.flag):\n                self.comp_dname = thismap.intmap_to_densitymap(self.comp_dname, self)\n\n    @property\n    def veldprof(self):\n        return self.profiles[self.vel_pname].dprofiles[self.vel_dname]\n\n    @property\n    def velprof(self):\n        return self.profiles[self.vel_pname]\n\n    @property\n    def compdmap(self):\n        return self.maps[self.comp_mname].dmaps[self.comp_dname]\n\n    @property\n    def compmap(self):\n        return self.maps[self.comp_mname]\n\n    @property\n    def massdmap(self):\n        return self.maps[self.mass_mname].dmaps[self.mass_dname]\n\n    @property\n    def massmap(self):\n        return self.maps[self.mass_mname]\n\n    @property\n    def _matched(self):\n        return (self.mass_mname == self.comp_mname)\n\n    @property\n    def _check_all(self):\n        return all((self._check_comp(), self._check_mass(), self._check_vel()))\n\n    def _check_vel(self):\n        return self._has_profile_data(self.vel_pname, self.vel_dname,\n                                      order=1)\n\n    def _check_comp(self):\n        return self._has_map_data(self.comp_mname, self.comp_dname,\n                                  order=0)\n\n    def _check_mass(self):\n        return self._has_map_data(self.mass_mname, self.mass_dname,\n                                  order=0)\n\n    def _reset_torquemaps(self):\n        \"\"\"Initalise the torquemap Profiles by setting an empty\n        'torquemaps' dictionary\n        \"\"\"\n        # set up the torquemaps\n        self.tmaps = AttrDict()\n\n    @property\n    def ntorquemaps(self):\n        \"\"\"Number of existing torquemap profiles\n        \"\"\"\n        if hasattr(self, 'tmaps'):\n            return len(self.tmaps)\n        else:\n            return -1\n\n    def match_comp_mass(self, odname1=\"dmass\", odname2=\"dcomp\", **kwargs):\n        \"\"\"Aligning the gas onto the mass map\n        \"\"\"\n        if not self._check_all:\n            print(\"WARNING[match_comp_mass]: cannot proceed with match \"\n                  \"as all maps are not yet set up. Please check\")\n            return\n\n        if not self._matched:\n            match_name = self.match_datamaps(self.mass_mname, self.comp_mname,\n                                             self.mass_dname, self.comp_dname,\n                                             odname1, odname2)\n            print(\"INFO[match_comp_mass]: new map is {}\".format(match_name))\n            self.mass_mname = match_name\n            self.comp_mname = match_name\n            self.mass_dname = odname1\n            self.comp_dname = odname2\n            self.deproject_nodes(match_name)\n        else:\n            print(\"WARNING[match_comp_mass]: nothing to match as the data are \"\n                  \"associated with the same map {}\".format(self.mass_mname))\n\n    def run_torques(self, torquemap_name=None, softening=0, func_kernel=\"sech2\",\n                    n_rbins=200, **kwargs):\n        \"\"\"Running the torques recipes\n\n        Args:\n            gas_name:\n            mass_name:\n            vel_name:\n            torquemap_name:\n\n        Returns:\n\n        \"\"\"\n        if torquemap_name is None:\n            torquemap_name = \"Torq{0:02d}\".format(self.ntorquemaps+1)\n\n        # Step 0 - finding the gas, mass and vel if not defined\n        # and match the maps\n        if not self._check_all:\n            # Try to read the maps\n            velname = kwargs.pop(\"velname\", self.velname)\n            compname = kwargs.pop(\"compname\", self.compname)\n            massname = kwargs.pop(\"massname\", self.massname)\n            self.init_torque_components(velname=velname, compname=compname,\n                                        massname=massname)\n\n        pc_per_xy = self.pc_per_xyunit(self.massmap.XYunit)\n\n        # Defining the structure in which the torques will be calculated\n        # Note that PAnodes is now -90 as we put the nodes along the X axis - horizontal\n        # During the matching\n        newT = TorqueMap(self.massmap, self.mass_dname, self.comp_dname,\n                         self.velprof, self.vel_dname, pc_per_xyunit=pc_per_xy,\n                         PAnodes=-90.0)\n\n        # Running the torque calculation\n        newT.run_torques(softening=softening, n_rbins=n_rbins,\n                         func_kernel=func_kernel)\n\n        # Now allocating it to the torquemaps\n        self.tmaps[torquemap_name] = newT\n", "meta": {"hexsha": "ec63d45214321b570248a40f79fa588c5aa3a0c6", "size": 16071, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/pydisc/torques.py", "max_stars_repo_name": "emsellem/pydisc", "max_stars_repo_head_hexsha": "a8737b6c84d150774612f50e6607fd0dcfe6e677", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pydisc/torques.py", "max_issues_repo_name": "emsellem/pydisc", "max_issues_repo_head_hexsha": "a8737b6c84d150774612f50e6607fd0dcfe6e677", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pydisc/torques.py", "max_forks_repo_name": "emsellem/pydisc", "max_forks_repo_head_hexsha": "a8737b6c84d150774612f50e6607fd0dcfe6e677", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2776523702, "max_line_length": 109, "alphanum_fraction": 0.5943002925, "include": true, "reason": "import numpy", "num_tokens": 3963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.1919467378085528}}
{"text": "# -*- coding: UTF-8 -*-\n# !/usr/bin/python\n# @time     :2019/8/31 21:33\n# @author   :Mo\n# @function :topic model of LDA\n# @paper    :Latent Dirichlet Allocation\n\n\nfrom nlg_yongzhuo.data_preprocess.text_preprocess import extract_chinese\nfrom nlg_yongzhuo.data_preprocess.text_preprocess import cut_sentence\nfrom nlg_yongzhuo.data_preprocess.text_preprocess import jieba_cut\nfrom nlg_yongzhuo.data.stop_words.stop_words import stop_words\n# sklearn\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.decomposition import LatentDirichletAllocation\nimport numpy as np\n\nclass LDASum:\n    def __init__(self):\n        self.stop_words = stop_words.values()\n        self.algorithm = 'lda'\n\n    def summarize(self, text, num=8, topic_min=6, judge_topic=None):\n        \"\"\"\n\n        :param text: str\n        :param num: int\n        :return: list\n        \"\"\"\n        # 切句\n        if type(text) == str:\n            self.sentences = cut_sentence(text)\n        elif type(text) == list:\n            self.sentences = text\n        else:\n            raise RuntimeError(\"text type must be list or str\")\n        len_sentences_cut = len(self.sentences)\n        # 切词\n        sentences_cut = [[word for word in jieba_cut(extract_chinese(sentence))\n                          if word.strip()] for sentence in self.sentences]\n        # 去除停用词等\n        self.sentences_cut = [list(filter(lambda x: x not in self.stop_words, sc)) for sc in sentences_cut]\n        self.sentences_cut = [\" \".join(sc) for sc in self.sentences_cut]\n        # 计算每个句子的tf\n        vector_c = CountVectorizer(ngram_range=(1, 2), stop_words=self.stop_words)\n        tf_ngram = vector_c.fit_transform(self.sentences_cut)\n        # 主题数, 经验判断\n        topic_num = min(topic_min, int(len(sentences_cut) / 2))  # 设定最小主题数为3\n        lda = LatentDirichletAllocation(n_components=topic_num, max_iter=32,\n                                        learning_method='online',\n                                        learning_offset=50.,\n                                        random_state=2019)\n        res_lda_u = lda.fit_transform(tf_ngram.T)\n        res_lda_v = lda.components_\n\n        if judge_topic:\n            ### 方案一, 获取最大那个主题的k个句子\n            ##################################################################################\n            topic_t_score = np.sum(res_lda_v, axis=-1)\n            # 对每列(一个句子topic_num个主题),得分进行排序,0为最大\n            res_nmf_h_soft = res_lda_v.argsort(axis=0)[-topic_num:][::-1]\n            # 统计为最大每个主题的句子个数\n            exist = (res_nmf_h_soft <= 0) * 1.0\n            factor = np.ones(res_nmf_h_soft.shape[1])\n            topic_t_count = np.dot(exist, factor)\n            # 标准化\n            topic_t_count /= np.sum(topic_t_count, axis=-1)\n            topic_t_score /= np.sum(topic_t_score, axis=-1)\n            # 主题最大个数占比, 与主题总得分占比选择最大的主题\n            topic_t_tc = topic_t_count + topic_t_score\n            topic_t_tc_argmax = np.argmax(topic_t_tc)\n            # 最后得分选择该最大主题的\n            res_nmf_h_soft_argmax = res_lda_v[topic_t_tc_argmax].tolist()\n            res_combine = {}\n            for l in range(len_sentences_cut):\n                res_combine[self.sentences[l]] = res_nmf_h_soft_argmax[l]\n            score_sen = [(rc[1], rc[0]) for rc in sorted(res_combine.items(), key=lambda d: d[1], reverse=True)]\n            #####################################################################################\n        else:\n            ### 方案二, 获取最大主题概率的句子, 不分主题\n            res_combine = {}\n            for i in range(len_sentences_cut):\n                res_row_i = res_lda_v[:, i]\n                res_row_i_argmax = np.argmax(res_row_i)\n                res_combine[self.sentences[i]] = res_row_i[res_row_i_argmax]\n            score_sen = [(rc[1], rc[0]) for rc in sorted(res_combine.items(), key=lambda d: d[1], reverse=True)]\n        num_min = min(num, len(self.sentences))\n        return score_sen[0:num_min]\n\n\nif __name__ == '__main__':\n    lda = LDASum()\n    doc = \"多知网5月26日消息，今日，方直科技发公告，拟用自有资金人民币1.2亿元，\" \\\n          \"与深圳嘉道谷投资管理有限公司、深圳嘉道功程股权投资基金（有限合伙）共同发起设立嘉道方直教育产业投资基金（暂定名）。\" \\\n          \"该基金认缴出资总规模为人民币3.01亿元。\" \\\n          \"基金的出资方式具体如下：出资进度方面，基金合伙人的出资应于基金成立之日起四年内分四期缴足，每期缴付7525万元；\" \\\n          \"各基金合伙人每期按其出资比例缴付。合伙期限为11年，投资目标为教育领域初创期或成长期企业。\" \\\n          \"截止公告披露日，深圳嘉道谷投资管理有限公司股权结构如下:截止公告披露日，深圳嘉道功程股权投资基金产权结构如下:\" \\\n          \"公告还披露，方直科技将探索在中小学教育、在线教育、非学历教育、学前教育、留学咨询等教育行业其他分支领域的投资。\" \\\n          \"方直科技2016年营业收入9691万元，营业利润1432万元，归属于普通股股东的净利润1847万元。（多知网 黎珊）}}\"\n\n    doc = \"PageRank算法简介。\" \\\n           \"是上世纪90年代末提出的一种计算网页权重的算法! \" \\\n           \"当时，互联网技术突飞猛进，各种网页网站爆炸式增长。 \" \\\n           \"业界急需一种相对比较准确的网页重要性计算方法。 \" \\\n           \"是人们能够从海量互联网世界中找出自己需要的信息。 \" \\\n           \"百度百科如是介绍他的思想:PageRank通过网络浩瀚的超链接关系来确定一个页面的等级。 \" \\\n           \"Google把从A页面到B页面的链接解释为A页面给B页面投票。 \" \\\n           \"Google根据投票来源甚至来源的来源，即链接到A页面的页面。 \" \\\n           \"和投票目标的等级来决定新的等级。简单的说， \" \\\n           \"一个高等级的页面可以使其他低等级页面的等级提升。 \" \\\n           \"具体说来就是，PageRank有两个基本思想，也可以说是假设。 \" \\\n           \"即数量假设：一个网页被越多的其他页面链接，就越重）。 \" \\\n           \"质量假设：一个网页越是被高质量的网页链接，就越重要。 \" \\\n           \"总的来说就是一句话，从全局角度考虑，获取重要的信。 \"\n\n    sum = lda.summarize(doc)\n    for i in sum:\n        print(i)\n", "meta": {"hexsha": "ab3509c399d9f09cfd02965f7461914b66c81208", "size": 5113, "ext": "py", "lang": "Python", "max_stars_repo_path": "nlg_yongzhuo/text_summarization/extractive_sum/topic_base/topic_lda.py", "max_stars_repo_name": "yongzhuo/nlg-yongzhuo", "max_stars_repo_head_hexsha": "937bfa750486294b333e685da6c34914948590b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 280, "max_stars_repo_stars_event_min_datetime": "2019-08-31T16:48:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T08:08:21.000Z", "max_issues_repo_path": "nlg_yongzhuo/text_summarization/extractive_sum/topic_base/topic_lda.py", "max_issues_repo_name": "Mindyu/nlg-yongzhuo", "max_issues_repo_head_hexsha": "937bfa750486294b333e685da6c34914948590b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2019-09-11T01:51:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-21T07:58:11.000Z", "max_forks_repo_path": "nlg_yongzhuo/text_summarization/extractive_sum/topic_base/topic_lda.py", "max_forks_repo_name": "Mindyu/nlg-yongzhuo", "max_forks_repo_head_hexsha": "937bfa750486294b333e685da6c34914948590b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 43, "max_forks_repo_forks_event_min_datetime": "2019-10-21T11:58:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T09:39:34.000Z", "avg_line_length": 42.6083333333, "max_line_length": 112, "alphanum_fraction": 0.5883043223, "include": true, "reason": "import numpy", "num_tokens": 1952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.19194673293104275}}
{"text": "import numpy as np\nimport time\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import datasets\n\nfrom Py_FS.wrapper.nature_inspired._utilities import Solution, Data, initialize, sort_agents, display, compute_fitness, Conv_plot\nfrom Py_FS.wrapper.nature_inspired._transfer_functions import get_trans_function\n\ndef MA(num_agents, max_iter, train_data, train_label, obj_function=compute_fitness, trans_function_shape='s',  prob_mut=0.2,  save_conv_graph=False):\n    \n    # Mayfly Algorithm\n    ############################### Parameters ####################################\n    #                                                                             #\n    #   num_agents: number of mayflies                                            #\n    #   max_iter: maximum number of generations                                   #\n    #   train_data: training samples of data                                      #\n    #   train_label: class labels for the training samples                        #                \n    #   obj_function: the function to maximize while doing feature selection      #\n    #   prob_mut: probability of mutation                                         #\n    #   trans_function_shape: shape of the transfer function used                 #\n    #   save_conv_graph: boolean value for saving convergence graph               #\n    #                                                                             #\n    ###############################################################################\n\n    short_name = 'MA'\n    agent_name = 'Mayfly'\n    train_data, train_label = np.array(train_data), np.array(train_label)\n    num_features = train_data.shape[1]\n    trans_function = get_trans_function(trans_function_shape)\n\n    # setting up the objectives\n    weight_acc = None\n    if(obj_function==compute_fitness):\n        weight_acc = float(input('Weight for the classification accuracy [0-1]: '))\n    obj = (obj_function, weight_acc)\n    compute_accuracy = (compute_fitness, 1) # compute_accuracy is just compute_fitness with accuracy weight as 1\n    \n    # control parameters\n    a1 = 1\n    a2 = 1.5\n    d = 0.1\n    fl = 0.1\n    g = 0.8\n    beta = 2\n    delta = 0.9\n    \n    # initialize position and velocities of male and female mayflies' and Leader (the agent with the max fitness)\n    male_pos = initialize(num_agents, num_features)\n    female_pos = initialize(num_agents, num_features)\n    male_vel = np.random.uniform(low = -1, high = 1, size = (num_agents, num_features))\n    female_vel = np.random.uniform(low = -1, high = 1, size = (num_agents, num_features))\n    male_fitness = np.zeros((num_agents))\n    male_accuracy = np.zeros(num_agents)\n    female_fitness = np.zeros((num_agents))\n    Leader_agent = np.zeros((num_features))\n    Leader_fitness = float(\"-inf\")\n    Leader_accuracy = float(\"-inf\")\n    male_personal_best = np.zeros((num_agents, num_features))\n    male_offspring = np.zeros((num_agents, num_features))\n    female_offspring = np.zeros((num_agents, num_features))\n    vmax_male = np.zeros((num_features))\n    vmax_female = np.zeros((num_features))\n    \n    # initialize convergence curves\n    convergence_curve = {}\n    convergence_curve['fitness'] = np.zeros(max_iter)\n    \n    # initialize data class\n    data = Data()\n    val_size = float(input('Enter the percentage of data wanted for valdiation [0, 100]: '))/100\n    data.train_X, data.val_X, data.train_Y, data.val_Y = train_test_split(train_data, train_label, stratify=train_label, test_size=val_size)\n    \n    # create a solution object\n    solution = Solution()\n    solution.num_agents = num_agents\n    solution.max_iter = max_iter\n    solution.num_features = num_features\n    solution.obj_function = obj_function\n    \n    # rank initial population\n    male_pos, male_fitness = sort_agents(male_pos, obj, data)\n    female_pos, female_fitness = sort_agents(female_pos, obj, data)\n    \n    # start timer\n    start_time = time.time()\n    \n    # main loop\n    for iter_no in range(max_iter):\n        print('\\n================================================================================')\n        print('                          Iteration - {}'.format(iter_no+1))\n        print('================================================================================\\n')\n        \n        #updating velocity limits\n        vmax_male, vmax_female = update_max_velocity(male_pos, female_pos)\n        \n        for agent in range(num_agents):\n            \n            #updating Leader fitness and personal best fitnesses\n            if male_fitness[agent] > Leader_fitness:\n                Leader_fitness = male_fitness[agent]\n                Leader_agent = male_pos[agent]\n            \n            if male_fitness[agent] > obj_function(male_personal_best[agent], data.train_X, data.val_X, data.train_Y, data.val_Y):\n                male_personal_best[agent] = male_pos[agent]\n\n            #update velocities of male and female mayflies\n            male_vel[agent], female_vel[agent] = update_velocity(male_pos[agent], female_pos[agent], male_vel[agent], female_vel[agent], Leader_agent, male_personal_best[agent], a1, a2, d, fl, g, beta, agent, data, obj_function)\n            \n            #check boundary condition of velocities of male and female mayflies\n            male_vel[agent], female_vel[agent] = check_velocity_limits(male_vel[agent], female_vel[agent], vmax_male, vmax_female)\n            \n            #applying transfer functions to update positions of male and female mayflies\n            #the updation is done based on their respective velocity values\n            for j in range(num_features):\n                trans_value = trans_function(male_vel[agent][j])\n                if trans_value > np.random.normal(0,1):\n                    male_pos[agent][j]=1\n                else:\n                    male_pos[agent][j]=0\n\n                trans_value = trans_function(female_vel[agent][j])\n                if trans_value > np.random.random():\n                    female_pos[agent][j]=1\n                else:\n                    female_pos[agent][j]=0\n        \n        #sorting \n        male_pos, male_fitness = sort_agents(male_pos, obj, data)\n        female_pos, female_fitness = sort_agents(female_pos, obj, data)\n        \n        for agent in range(num_agents):\n            \n            #generation of offsprings by crossover and mutation between male and female parent mayflies\n            male_offspring[agent], female_offspring[agent] = cross_mut(male_pos[agent], female_pos[agent],prob_mut)\n            \n        #comparing parents and offsprings and replacing parents wherever necessary\n        male_pos = compare_and_replace(male_pos, male_offspring, male_fitness, data, obj)\n        female_pos = compare_and_replace(female_pos, female_offspring, female_fitness, data, obj)\n        \n        #updating fitness values\n        male_pos, male_fitness = sort_agents(male_pos, obj, data)\n        female_pos, female_fitness = sort_agents(female_pos, obj, data)\n        \n        #updating values of nuptial dance\n        d = d * delta\n        fl = fl * delta\n        \n        #update final information\n        display(male_pos, male_fitness, agent_name)\n        if(male_fitness[0] > Leader_fitness):\n            Leader_agent = male_pos[0].copy()\n            Leader_fitness = male_fitness[0].copy()\n\n        convergence_curve['fitness'][iter_no] = np.mean(male_fitness)\n    \n    # compute final accuracy\n    Leader_agent, Leader_accuracy = sort_agents(Leader_agent, compute_accuracy, data)\n    male_pos, male_accuracy = sort_agents(male_pos, compute_accuracy, data)\n\n    print('\\n================================================================================')\n    print('                                    Final Result                                  ')\n    print('================================================================================\\n')\n    print('Leader ' + agent_name + ' Dimension : {}'.format(int(np.sum(Leader_agent))))\n    print('Leader ' + agent_name + ' Fitness : {}'.format(Leader_fitness))\n    print('Leader ' + agent_name + ' Classification Accuracy : {}'.format(Leader_accuracy))\n    print('\\n================================================================================\\n')\n\n    # stop timer\n    end_time = time.time()\n    exec_time = end_time - start_time\n    \n    # plot convergence graph\n    fig, axes = Conv_plot(convergence_curve)\n    if(save_conv_graph):\n        plt.savefig('convergence_graph_'+ short_name + '.jpg')\n    plt.show()\n    \n    # update attributes of solution\n    solution.best_agent = Leader_agent\n    solution.best_fitness = Leader_fitness\n    solution.best_accuracy = Leader_accuracy\n    solution.convergence_curve = convergence_curve\n    solution.final_population = male_pos\n    solution.final_fitness = male_fitness\n    solution.final_accuracy = male_accuracy\n    solution.execution_time = exec_time\n\n    return solution\n\n\ndef update_max_velocity(male, female):\n    size, length = male.shape\n    agent1 = []\n    agent2 = []\n    r = np.random.normal(0,1 , size=(length))\n    for j in range(length):\n        r[j] *= 2\n        agent1.append((male[0][j]-male[size-1][j])*r[j])\n        agent2.append((female[0][j]-female[size-1][j])*r[j])\n    \n    return (agent1, agent2)\n\ndef update_velocity(m_pos, f_pos, m_vel, f_vel, Leader_agent, pbest, a1, a2, d, fl, g, b, i, data, obj_function):\n    tot_features = m_pos.shape[0]\n    agent1 = np.zeros((tot_features))\n    agent2 = np.zeros((tot_features))\n    tot_features = len(m_pos)\n    if i==0:\n        for j in range(tot_features):\n            agent1[j] = m_vel[j]+d*np.random.uniform(-1,1)\n    else:\n        sum = 0    \n        for j in range(tot_features):\n            sum = sum+(m_pos[j]-Leader_agent[j])*(m_pos[j]-Leader_agent[j])\n        rg = np.sqrt(sum)\n        sum = 0\n        for j in range(tot_features):\n            sum = sum+(m_pos[j]-pbest[j])*(m_pos[j]-pbest[j])\n        rp = np.sqrt(sum)\n        for j in range(tot_features):\n            agent1[j] = g*m_vel[j]+a1*np.exp(-b*rp*rp)*(pbest[j]-m_pos[j])+a2*np.exp(-b*rg*rg)*(Leader_agent[j]-m_pos[j])\n    if obj_function(m_pos, data.train_X, data.val_X, data.train_Y, data.val_Y) >= obj_function(f_pos, data.train_X, data.val_X, data.train_Y, data.val_Y):\n        sum = 0\n        for j in range(tot_features):\n            sum = sum+(m_pos[j]-f_pos[j])*(m_pos[j]-f_pos[j])\n        rmf = np.sqrt(sum)\n        agent2[j] = g*f_vel[j]+a2*np.exp(-b*rmf*rmf)*(m_pos[j]-f_pos[j])\n    else:\n        for j in range(tot_features):\n            agent2[j] = g*f_vel[j]+fl*np.random.uniform(-1,1)\n            \n    return (agent1, agent2)\n\ndef check_velocity_limits(m_vel, f_vel, vmax_m, vmax_f):\n    tot_features = len(m_vel)\n    for j in range(tot_features):\n        m_vel[j] = np.minimum(m_vel[j], vmax_m[j])\n        m_vel[j] = np.maximum(m_vel[j], -vmax_m[j])\n        f_vel[j] = np.minimum(f_vel[j], vmax_f[j])\n        f_vel[j] = np.maximum(f_vel[j], -vmax_f[j])\n    \n    return (m_vel, f_vel)\n\ndef cross_mut(m_pos, f_pos,prob_mut):\n    tot_features = len(m_pos)\n    offspring1 = np.zeros((tot_features))\n    offspring2 = np.zeros((tot_features))\n    # partition defines the midpoint of the crossover\n    partition = np.random.randint(tot_features//4, np.floor((3*tot_features//4)+1))\n\n    # starting crossover\n    for i in range(partition):\n        offspring1[i] = m_pos[i]\n        offspring2[i] = f_pos[i]\n\n    for i in  range(partition, tot_features):\n        offspring1[i] = f_pos[i]\n        offspring2[i] = m_pos[i]\n    # crossover ended\n\n\n    # starting mutation\n    if np.random.random() <= prob_mut:\n        percent = 0.2\n        numChange = int(tot_features*percent)\n        pos = np.random.randint(0,tot_features-1,numChange)\n        \n        for j in pos:\n            offspring1[j] = 1-offspring1[j]\n        pos=np.random.randint(0,tot_features-1,numChange)\n        for j in pos:\n            offspring2[j] = 1-offspring2[j]\n\n    # mutation ended\n    \n    if np.random.random() >= 0.5:\n        return (offspring1, offspring2)\n    else:\n        return (offspring2, offspring1)\n\n\ndef compare_and_replace(pos, off, fit, data, obj):\n    agents, features = pos.shape\n    newfit = np.zeros((agents))\n    temp_pos = np.zeros((agents, features))\n    pos, fit = sort_agents(pos, obj, data)\n    # finding fitnesses of offsprings\n    off, newfit = sort_agents(off, obj, data)\n    i=0\n    j=0\n    cnt=0\n    # merging offsprings and parents and finding the next generation of mayflies\n    while(cnt < agents):\n        if fit[i] > newfit[j]:\n            temp_pos[cnt] = pos[i].copy()\n            i+=1\n        else:\n            temp_pos[cnt] = off[i].copy()\n            j+=1\n        cnt+=1\n    return temp_pos\n\n\nif __name__ == '__main__':\n    data = datasets.load_digits()\n    MA(20, 30, data.data, data.target, save_conv_graph=True)\n", "meta": {"hexsha": "2294d45063ef101f67cac2a09e6826215e25e083", "size": 12832, "ext": "py", "lang": "Python", "max_stars_repo_path": "Other Optimization Algorithms/MA.py", "max_stars_repo_name": "stochasticmaterialism/Dendritic-Non-Dendritic-Classification", "max_stars_repo_head_hexsha": "cb0f68377b0d7cfdbb091bb2df898ecbcb0e44e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-04T14:48:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T14:48:49.000Z", "max_issues_repo_path": "Other Optimization Algorithms/MA.py", "max_issues_repo_name": "stochasticmaterialism/Dendritic-Non-Dendritic-Classification", "max_issues_repo_head_hexsha": "cb0f68377b0d7cfdbb091bb2df898ecbcb0e44e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-03-26T16:06:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T16:07:14.000Z", "max_forks_repo_path": "Other Optimization Algorithms/MA.py", "max_forks_repo_name": "stochasticmaterialism/Dendritic-Non-Dendritic-Classification", "max_forks_repo_head_hexsha": "cb0f68377b0d7cfdbb091bb2df898ecbcb0e44e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-28T15:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-28T15:18:26.000Z", "avg_line_length": 41.5275080906, "max_line_length": 228, "alphanum_fraction": 0.5931265586, "include": true, "reason": "import numpy", "num_tokens": 2967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.19188052770221994}}
{"text": "import random\nimport copy\nimport numpy as np\nimport pandas as pd\nimport os\n\nfrom models.MultiGMPmodel import MultiCopyGMPmodel\nfrom models.MultiGGHPmodel import MultiCopyGGHPmodel\nfrom models.GGHPmodel import GGHPmodel\nfrom util.calculateFissionsAndFusions import calculateFissionAndFussions\n\ndef readSequence(file):\n    chr = []\n    with open(file,'r') as rf:\n        while True:\n            line = rf.readline()[:-2]\n            if not line:\n                break\n            itemset = line.split(' ')\n            header = itemset[0]\n            new_itemset = [header]\n            for i in itemset[1:]:\n                item = i.split('_')\n                new_itemset.append(item[0])\n            chr.append(new_itemset)\n    return chr\n\ndef outSequence(sequence,outfile):\n    outfile = open(outfile,'w')\n    for i in sequence:\n        for j in i:\n            outfile.write(j+' ')\n        outfile.write('\\n')\n    outfile.close()\n\ndef sequence2adjacency(sequence):\n    adjacency = []\n    for i in sequence:\n        block = i[0]\n        if block.startswith('-'):\n            adjacency.append(['$',block[1:] + 'b'])\n            start = block[1:] + 'a'\n        else:\n            adjacency.append(['$', block + 'a'])\n            start = block + 'b'\n        for j in range(len(i)-1):\n            block = i[j+1]\n            if block.startswith('-'):\n                adjacency.append([start, block[1:] + 'b'])\n                start = block[1:] + 'a'\n            else:\n                adjacency.append([start, block + 'a'])\n                start = block + 'b'\n        adjacency.append([start,'$'])\n    return adjacency\n\ndef reverse(item):\n    if item[-1] == 'a':\n        return item[:-1] + 'b'\n    else:\n        return item[:-1] + 'a'\n\ndef assemble(adjacency_list):\n    # build adj M\n    matrix_items = []\n    for i in adjacency_list:\n        for j in i:\n            if j not in matrix_items:\n                matrix_items.append(j)\n    matrix_items = sorted(matrix_items)\n    adjacency_matrix = {}  # 创建初始邻接矩阵\n    for i in matrix_items:\n        adjacency_matrix[i] = {}\n        for j in matrix_items:\n            adjacency_matrix[i][j] = 0\n    for i in adjacency_list:\n        adjacency_matrix[i[0]][i[1]] = 1\n        adjacency_matrix[i[1]][i[0]] = 1\n    adjacency_matrix = pd.DataFrame(adjacency_matrix)\n    index = adjacency_matrix.index.tolist()\n    columns = adjacency_matrix.columns.tolist()\n    np_adjacency_matrix = np.asarray(adjacency_matrix)\n    adjacencies = {}\n    for i in range(len(index)):\n        for j in range(len(index)):\n            if int(np_adjacency_matrix[i][j]) == 1:\n                if '$' == index[i] or '$' == index[j]:\n                    continue\n                pair = sorted([index[i], index[j]])\n                key = pair[0] + '@' + pair[1]\n                if key not in adjacencies.keys():\n                    adjacencies[key] = 1\n                else:\n                    adjacencies[key] += 1\n    adjs = {}\n    for i in adjacencies.keys():\n        itemset = i.split('@')\n        if itemset[0] not in adjs.keys():\n            adjs[itemset[0]] = itemset[1]\n        if itemset[1] not in adjs.keys():\n            adjs[itemset[1]] = itemset[0]\n    startpoint = []\n    # 遍历矩阵第一行，不是0的加入start:\n    for j in range(len(columns)):\n        if np_adjacency_matrix[0][j] == 1:\n            startpoint.append(columns[j])\n    markerstartpoint = []\n    chr = []\n    for i in startpoint:\n        if i not in markerstartpoint:\n            path = []\n            if i[-1] == 'a':\n                path.append(i[:-1])\n            else:\n                path.append('-' + i[:-1])\n            start = reverse(i)\n            if start in startpoint:\n                markerstartpoint.append(start)\n                chr.append(path)\n            else:\n                while True:\n                    next = adjs[start]\n                    if next[-1] == 'a':\n                       path.append(next[:-1])\n                    else:\n                        path.append('-' + next[:-1])\n                    start = reverse(next)\n                    if start in startpoint:\n                        markerstartpoint.append(start)\n                        break\n                chr.append(path)\n    vector = []\n    for i in chr:\n        for j in i:\n            if j.startswith('-'):\n                vector.append(j[1:])\n            else:\n                vector.append(j)\n    cyclepoint = []\n    for i in adjs.keys():\n        if i[:-1] not in vector:\n            cyclepoint.append(i)\n    cyclechr = []\n    markercycle = []\n    for i in cyclepoint:\n        if i not in markercycle:\n            startpoint = i\n            cycle = []\n            markercycle.append(i)\n            start = i\n            while True:\n                next = adjs[start]\n                if next[-1] == 'a':\n                    cycle.append(next[:-1])\n                else:\n                    cycle.append('-' + next[:-1])\n                markercycle.append(start)\n                markercycle.append(next)\n                start = reverse(next)\n                if start == startpoint:\n                    break\n            cyclechr.append(cycle)\n    return chr,cyclechr\n\ndef changeAdj(adj_list):\n    change = copy.deepcopy(adj_list)\n    endpoints = []\n    for j in change:\n        for k in j:\n            endpoints.append(k)\n    random.shuffle(endpoints)\n    change_part = []\n    for j in range(int(len(endpoints) / 2)):\n        change_part.append([endpoints[j * 2], endpoints[2 * j + 1]])\n    return change_part\n\n\n\ndef buildNoCRBSimulations(prefix_adjacencies,\n                          suffix_adjacencies, save_final_species_adjacencies, change_adjacency_number,\n                          divergence_level, current_level):\n    split_adjacency = []\n    divergence_change_adjacencies_group_number = len(suffix_adjacencies) * 2\n    for i in suffix_adjacencies:\n        one_change_adjacencies = []\n        for j in range(divergence_change_adjacencies_group_number):\n            one_change_adjacencies.append(copy.deepcopy(i[j * change_adjacency_number:(j + 1) * change_adjacency_number]))\n        one_change_adjacencies.append(copy.deepcopy(i[divergence_change_adjacencies_group_number * change_adjacency_number:]))\n        split_adjacency.append(one_change_adjacencies)\n\n    sub_species_1 = []\n    sub_species_2 = []\n    copy_number = 0\n\n    for i in split_adjacency:\n        sp1_copy = []\n        sp2_copy = []\n        sp1_change = copy_number\n        sp2_change = copy_number+len(split_adjacency)\n        for j in range(len(i)):\n            # change different part, no CRBs\n            if j == sp1_change:\n                change = copy.deepcopy(i[j])\n                change_part = changeAdj(change)\n                sp1_copy.append(change_part)\n            else:\n                sp1_copy.append(copy.deepcopy(i[j]))\n            if j == sp2_change:\n                change = copy.deepcopy(i[j])\n                change_part = changeAdj(change)\n                sp2_copy.append(change_part)\n            else:\n                sp2_copy.append(copy.deepcopy(i[j]))\n\n        sub_species_1.append(sp1_copy)\n        sub_species_2.append(sp2_copy)\n        copy_number += 1\n\n    species_1 = []\n    for i in range(len(sub_species_1)):\n        one_copy = []\n        one_copy += copy.deepcopy(prefix_adjacencies[i])\n        for j in copy.deepcopy(sub_species_1[i]):\n            one_copy += j\n        species_1.append(one_copy)\n    # save first species\n    save_final_species_adjacencies.append(species_1)\n    species_2 = []\n    for i in range(len(sub_species_2)):\n        one_copy = []\n        one_copy += copy.deepcopy(prefix_adjacencies[i])\n        for j in copy.deepcopy(sub_species_2[i]):\n            one_copy += j\n        species_2.append(one_copy)\n    # save second species\n    save_final_species_adjacencies.append(species_2)\n\n    # duplication\n    dup_flag = 1\n    species_2_dup = []\n    if dup_flag == 1:\n        for i in range(len(sub_species_2)):\n            change_list = copy.deepcopy(sub_species_2[i][:-1])\n            unchange = copy.deepcopy(sub_species_2[i][-1])\n\n            split_unchange = []\n            for j in range(len(sub_species_2)*2):\n                split_unchange.append(copy.deepcopy(unchange[j * change_adjacency_number:(j + 1) * change_adjacency_number]))\n            split_unchange.append(unchange[len(sub_species_2) * 2 * change_adjacency_number:])\n            # change adjacencies\n            change_1 = i*len(sub_species_2)\n            change_2 = i*len(sub_species_2) + 1\n            new_change_list_copy1 = []\n            new_change_list_copy2 = []\n            for j in range(len(split_unchange)):\n                if j == change_1:\n                    change = copy.deepcopy(split_unchange[j])\n                    change_part = changeAdj(change)\n                    new_change_list_copy1.append(change_part)\n                else:\n                    new_change_list_copy1.append(copy.deepcopy(split_unchange[j]))\n                if j == change_2:\n                    change = copy.deepcopy(split_unchange[j])\n                    change_part = changeAdj(change)\n                    new_change_list_copy2.append(change_part)\n                else:\n                    new_change_list_copy2.append(copy.deepcopy(split_unchange[j]))\n            final_change_list_1 = copy.deepcopy(change_list) + new_change_list_copy1\n            final_change_list_2 = copy.deepcopy(change_list) + new_change_list_copy2\n            species_2_dup.append(final_change_list_1)\n            species_2_dup.append(final_change_list_2)\n\n    if current_level == divergence_level:\n        species_2_dup_sequence = []\n        for i in range(len(species_2_dup)):\n            one_copy = []\n            one_copy += copy.deepcopy(prefix_adjacencies[int(i / 2)])\n            for j in copy.deepcopy(species_2_dup[i]):\n                one_copy += j\n            species_2_dup_sequence.append(one_copy)\n        save_final_species_adjacencies.append(species_2_dup_sequence)\n\n    else:\n        species_2_dup_sequence = []\n        for i in range(len(species_2_dup)):\n            one_copy = []\n            one_copy += copy.deepcopy(prefix_adjacencies[int(i / 2)])\n            for j in copy.deepcopy(species_2_dup[i]):\n                one_copy += j\n            species_2_dup_sequence.append(one_copy)\n        # save duplicated species\n        save_final_species_adjacencies.append(species_2_dup_sequence)\n        new_prefix_adjacency = []\n        new_suffix_adjacency = []\n        for i in range(len(species_2_dup)):\n            one_copy = copy.deepcopy(prefix_adjacencies[int(i / 2)])\n            change_part = species_2_dup[i][:-1]\n            unchange_part = species_2_dup[i][-1]\n            for j in change_part:\n                one_copy += copy.deepcopy(j)\n            new_prefix_adjacency.append(one_copy)\n            new_suffix_adjacency.append(copy.deepcopy(unchange_part))\n        # recursion build next level species, level += 1\n        buildNoCRBSimulations(new_prefix_adjacency, new_suffix_adjacency,\n                              save_final_species_adjacencies, change_adjacency_number,\n                              divergence_level, current_level + 1)\n\n\ndef simulateNoCRB(workdir):\n    chromosome_number = 5\n    block_number = 100\n    ancestor_sequence = []\n    one_chromosome = int(block_number / chromosome_number)\n    block = 100\n    for i in range(chromosome_number):\n        sequence = []\n        for j in range(one_chromosome):\n            if block % 2 == 0:\n                sequence.append('-' + str(block))\n            else:\n                sequence.append(str(block))\n            block += 1\n        ancestor_sequence.append(sequence)\n    ancestor_adjacency = sequence2adjacency(ancestor_sequence)\n    random.shuffle(ancestor_adjacency)\n    print('ancestor adjacency number:')\n    print(len(ancestor_adjacency))\n    divergence_level = 2\n    change_adjacency_number = 5\n    save_final_species_adjacencies = []\n    buildNoCRBSimulations([[]], [ancestor_adjacency],\n                          save_final_species_adjacencies, change_adjacency_number, divergence_level, current_level=0)\n    species_count = 1\n    # output species\n    for i in save_final_species_adjacencies:\n        copy_count = 1\n        outfile = workdir + 'species.sequence.' + str(species_count)\n\n        outfile = open(outfile,'w')\n        for j in i:\n            filter_tel2tel = []\n            for k in j:\n                # filter ($,$)\n                if k[0] == '$' and k[1] == '$':\n                    continue\n                else:\n                    if k[0] != '$':\n                        newendpoint1 = k[0][:-1]+'_'+str(copy_count)+k[0][-1]\n                    else:\n                        newendpoint1 = '$'\n                    if k[1] != '$':\n                        newendpoint2 = k[1][:-1]+'_'+str(copy_count)+k[1][-1]\n                    else:\n                        newendpoint2 = '$'\n                    filter_tel2tel.append([newendpoint1,newendpoint2])\n            chrs,cycles = assemble(filter_tel2tel)\n            for k in chrs:\n                outfile.write('s ')\n                for l in k:\n                    outfile.write(l+' ')\n                outfile.write('\\n')\n            for k in cycles:\n                outfile.write('c ')\n                min_index = -1\n                min_value = 1000000\n                for l in range(len(k)):\n                    if k[l].startswith('-'):\n                        item = k[l][1:].split('_')\n                        block = int(item[0])\n                    else:\n                        item = k[l].split('_')\n                        block = int(item[0])\n                    if block < min_value:\n                        min_index = l\n                        min_value = block\n                if k[min_index].startswith('-'):\n                    half1 = k[min_index + 1:]\n                    half2 = k[:min_index + 1]\n                    new_string = half1 + half2\n                else:\n                    half1 = k[min_index:]\n                    half2 = k[:min_index]\n                    new_string = half1 + half2\n                for l in new_string:\n                    outfile.write(l+' ')\n                outfile.write('\\n')\n            copy_count += 1\n        outfile.close()\n        species_count += 1\n\n\ndef doubled(infile,outfile):\n    outfile = open(outfile,'w')\n    sequence = []\n    with open(infile,'r') as f:\n        while True:\n            line = f.readline()\n            if not line:\n                break\n            sequence.append(line)\n    for i in sequence:\n        outfile.write(i)\n    for i in sequence:\n        outfile.write(i)\n\n\nworkdir = 'D:/InferAncestorGenome/realData/IAGS_version1.0/simulations/NonCRBs/inferring/repeat/'\n# simulate No CRB species\nif not os.path.exists(workdir):\n    os.makedirs(workdir)\nresultfile = open(workdir + 'result.xls', 'w')\nresultfile.write('Repeat\\tAncestor\\tFissions\\tFusions\\n')\nfor i in range(200):\n    repeatdir = workdir + str(i+1) + '/'\n    if not os.path.exists(repeatdir):\n        os.makedirs(repeatdir)\n    simulateNoCRB(repeatdir)\n    filelist = ['species.sequence.1', 'species.sequence.2', 'species.sequence.3',\n                'species.sequence.4', 'species.sequence.5', 'species.sequence.6',\n                'species.sequence.7', 'species.sequence.8', 'species.sequence.9']\n    for j in filelist:\n        sequence = readSequence(repeatdir + j)\n        outSequence(sequence, repeatdir + j + '.noBar')\n    \"\"\"\n    Ancestor 8: Multi-copy GGHP model\n    \"\"\"\n    dup_child_file = repeatdir + 'species.sequence.9.noBar'\n    outgroup_file = repeatdir + 'species.sequence.7.noBar'\n    outAncestor8dir = repeatdir + 'Ancestor8/'\n    if not os.path.exists(outAncestor8dir):\n        os.makedirs(outAncestor8dir)\n\n    dup_copy_number = 8\n    out_copy_number = 4\n    ancestor_target_copy_number = 4\n    ancestor_name = 'Ancestor8'\n    MultiCopyGGHPmodel(dup_child_file, outgroup_file, outAncestor8dir,\n                       ancestor_name, dup_copy_number, out_copy_number,\n                       ancestor_target_copy_number)\n\n    ancestor_file = outAncestor8dir + ancestor_name + '.block'\n\n    fissions, fusions = calculateFissionAndFussions(ancestor_file,\n                                                    repeatdir + 'species.sequence.8.noBar',\n                                                    ancestor_target_copy_number, ancestor_target_copy_number,\n                                                    outAncestor8dir)\n    resultfile.write(str(i+1)+'\\tAncestor8\\t' + str(fissions) + '\\t' + str(fusions) + '\\n')\n\n    \"\"\"\n    Ancestor 5: Multi-copy GGHP model\n    \"\"\"\n    dup_child_file = repeatdir + 'species.sequence.7.noBar'\n    outgroup_file = repeatdir + 'species.sequence.4.noBar'\n    outAncestor5dir = repeatdir + 'Ancestor5/'\n    if not os.path.exists(outAncestor5dir):\n        os.makedirs(outAncestor5dir)\n    dup_copy_number = 4\n    out_copy_number = 2\n    ancestor_target_copy_number = 2\n    ancestor_name = 'Ancestor5'\n    MultiCopyGGHPmodel(dup_child_file, outgroup_file, outAncestor5dir,\n                       ancestor_name, dup_copy_number, out_copy_number,\n                       ancestor_target_copy_number)\n\n    ancestor_file = outAncestor5dir + ancestor_name + '.block'\n\n    fissions, fusions = calculateFissionAndFussions(ancestor_file,\n                                                    repeatdir + 'species.sequence.5.noBar',\n                                                    ancestor_target_copy_number, ancestor_target_copy_number,\n                                                    outAncestor5dir)\n    resultfile.write(str(i+1)+'\\tAncestor5\\t' + str(fissions) + '\\t' + str(fusions) + '\\n')\n\n    \"\"\"\n    Ancestor 6: Multi-copy GMP model\n    \"\"\"\n    outAncestor6dir = repeatdir + 'Ancestor6/'\n    if not os.path.exists(outAncestor6dir):\n        os.makedirs(outAncestor6dir)\n    doubled(outAncestor5dir + 'Ancestor5.block', outAncestor6dir + 'Ancestor5.doubled.block')\n    species_file_list = [repeatdir + 'species.sequence.7.noBar',\n                         outAncestor8dir + 'Ancestor8.block',\n                         outAncestor6dir + 'Ancestor5.doubled.block']\n    guided_species_for_matching = repeatdir + 'species.sequence.7.noBar'\n    ancestor_target_copy_number = 4\n    ancestor_name = 'Ancestor6'\n    MultiCopyGMPmodel(species_file_list, outAncestor6dir, guided_species_for_matching,\n                      ancestor_name, ancestor_target_copy_number)\n\n    ancestor_file = outAncestor6dir + ancestor_name + '.block'\n\n    fissions, fusions = calculateFissionAndFussions(ancestor_file,\n                                                    repeatdir + 'species.sequence.6.noBar',\n                                                    ancestor_target_copy_number, ancestor_target_copy_number,\n                                                    outAncestor6dir)\n    resultfile.write(str(i+1)+'\\tAncestor6\\t' + str(fissions) + '\\t' + str(fusions) + '\\n')\n\n    \"\"\"\n    Ancestor 2: GGHP model\n    \"\"\"\n    dup_child_file = repeatdir + 'species.sequence.4.noBar'\n    outgroup_file = repeatdir + 'species.sequence.1.noBar'\n    outAncestor2dir = repeatdir + 'Ancestor2/'\n    if not os.path.exists(outAncestor2dir):\n        os.makedirs(outAncestor2dir)\n    dup_copy_number = 2\n    out_copy_number = 1\n    ancestor_target_copy_number = 1\n    ancestor_name = 'Ancestor2'\n    GGHPmodel(dup_child_file=dup_child_file,\n              outgroup_file=outgroup_file,\n              outdir=outAncestor2dir,\n              ancestor_name=ancestor_name,\n              dup_copy_number=dup_copy_number,\n              out_copy_number=out_copy_number)\n\n    ancestor_file = outAncestor2dir + ancestor_name + '.block'\n\n    fissions, fusions = calculateFissionAndFussions(ancestor_file,\n                                                    repeatdir + 'species.sequence.2.noBar',\n                                                    ancestor_target_copy_number, ancestor_target_copy_number,\n                                                    outAncestor2dir)\n    resultfile.write(str(i+1)+'\\tAncestor2\\t' + str(fissions) + '\\t' + str(fusions) + '\\n')\n\n    \"\"\"\n    Ancestor 3: Multi-copy GMP model\n    \"\"\"\n    outAncestor3dir = repeatdir + 'Ancestor3/'\n    outAncestor2dir = repeatdir + 'Ancestor2/'\n    if not os.path.exists(outAncestor3dir):\n        os.makedirs(outAncestor3dir)\n    doubled(outAncestor2dir + 'Ancestor2.block', outAncestor3dir + 'Ancestor2.doubled.block')\n    species_file_list = [repeatdir + 'species.sequence.4.noBar',\n                         outAncestor5dir + 'Ancestor5.block',\n                         outAncestor3dir + 'Ancestor2.doubled.block']\n    guided_species_for_matching = repeatdir + 'species.sequence.4.noBar'\n    ancestor_target_copy_number = 2\n    ancestor_name = 'Ancestor3'\n    MultiCopyGMPmodel(species_file_list, outAncestor3dir, guided_species_for_matching,\n                      ancestor_name, ancestor_target_copy_number)\n\n    ancestor_file = outAncestor3dir + ancestor_name + '.block'\n\n    fissions, fusions = calculateFissionAndFussions(ancestor_file,\n                                                    repeatdir + 'species.sequence.3.noBar',\n                                                    ancestor_target_copy_number, ancestor_target_copy_number,\n                                                    outAncestor3dir)\n    resultfile.write(str(i+1)+'\\tAncestor3\\t' + str(fissions) + '\\t' + str(fusions) + '\\n')\n    resultfile.flush()\n\nresultfile.close()\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "9c5cbd4a8f5c56245deac9bf789100ec49349459", "size": 21373, "ext": "py", "lang": "Python", "max_stars_repo_path": "simulations/NonCRBs/NonCRBSimulateion.py", "max_stars_repo_name": "865699871/IAGS_version1.0", "max_stars_repo_head_hexsha": "f5b2f30cef9b809a9ece91abf5b1d56367512f58", "max_stars_repo_licenses": ["AFL-1.1"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-08-04T07:38:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T16:56:57.000Z", "max_issues_repo_path": "simulations/NonCRBs/NonCRBSimulateion.py", "max_issues_repo_name": "xjtu-omics/IAGS", "max_issues_repo_head_hexsha": "1e9de501e1f7875e0cea6da5954aa034445eae77", "max_issues_repo_licenses": ["AFL-1.1"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulations/NonCRBs/NonCRBSimulateion.py", "max_forks_repo_name": "xjtu-omics/IAGS", "max_forks_repo_head_hexsha": "1e9de501e1f7875e0cea6da5954aa034445eae77", "max_forks_repo_licenses": ["AFL-1.1"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-03-03T03:10:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T01:49:19.000Z", "avg_line_length": 38.0302491103, "max_line_length": 126, "alphanum_fraction": 0.5603799186, "include": true, "reason": "import numpy", "num_tokens": 4849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.19188052225159238}}
{"text": "#!/usr/bin/env python\n# TODO: how do we choose the simulation box?\n\nimport numpy as np\nimport numpy.linalg as la\nimport sys\nimport os\nfrom libs import topology as top\nfrom libs import base\nfrom libs import utils\n\n\t\nclass Options(object):\n\n\tdef __init__(self):\n\t\tobject.__init__(self)\n\t\t\n\t\tself.closed = True\n\t\tself.double = True\n\t\tself.nicked = False\n\t\tself.supercoiling = 0.\n\t\tself.writhe = 0.\n\t\tself.seed = None\n\t\tself.sequence_file = None\n\t\t\n\tdef check(self):\n\t\tif self.nicked and not self.double:\n\t\t\tprint >> sys.stderr, \"The --nicked and --ssDNA options are incompatible\"\n\t\t\texit(1)\n\t\t\n\t\t\ndef print_usage():\n\tprint >> sys.stderr, \"USAGE:\"\n\tprint >> sys.stderr, \"\\t%s centerline_file\" % sys.argv[0]\n\tprint >> sys.stderr, \"\\t[-c\\--closed] [-o\\--open] [-h\\--help] [-d\\--dsDNA] [-s\\--ssDNA] [-n\\--nicked] [-p\\--supercoiling VALUE] [-w\\--writhe VALUE] [-e\\--seed VALUE] [-q\\--sequence FILE]\"\n\texit(1)\n\t\t\n\t\t\ndef parse_options():\n\tshortArgs = 'cohdsnp:w:e:q:'\n\tlongArgs = ['closed', 'open', 'help', 'dsDNA', 'ssDNA', 'nicked', 'supercoiling=', 'writhe=', 'seed=', 'sequence=']\n\t\n\topts = Options()\n\t\n\ttry:\n\t\timport getopt\n\t\targs, files = getopt.gnu_getopt(sys.argv[1:], shortArgs, longArgs)\n\t\tfor k in args:\n\t\t\tif k[0] == '-c' or k[0] == '--closed': opts.closed = True\n\t\t\tif k[0] == '-o' or k[0] == '--open': opts.closed = False\n\t\t\tif k[0] == '-h' or k[0] == '--help': print_usage()\n\t\t\tif k[0] == '-d' or k[0] == '--dsDNA': opts.double = True\n\t\t\tif k[0] == '-s' or k[0] == \"--ssDNA\": opts.double = False\n\t\t\tif k[0] == '-n' or k[0] == \"--nicked\": opts.nicked = True\n\t\t\tif k[0] == '-p' or k[0] == \"--supercoiling\": opts.supercoiling = float(k[1])\n\t\t\tif k[0] == '-w' or k[0] == \"--writhe\": opts.writhe = float(k[1])\n\t\t\tif k[0] == '-e' or k[0] == \"--seed\": opts.seed = int(k[1])\n\t\t\tif k[0] == '-q' or k[0] == \"--sequence\": opts.sequence_file = k[1]\n\t\t\t\n\t\topts.centerline_file = files[0]\n\texcept Exception:\n\t\tprint_usage()\n\t\t\n\treturn opts\n\n\n# base-base distance along the helical pitch\nBASE_BASE = 0.3897628551303122\n# distance between the helix centre and the nucleotides' centre of mass\nCM_CENTER_DS = 0.6\n\nif __name__ == '__main__':\n\topts = parse_options()\n\topts.check()\n\t\n\tif opts.seed != None:\n\t\tnp.random.seed(opts.seed)\n\t\n\t# import the coordinates from the user-provided file\n\tcoordxyz = np.loadtxt(opts.centerline_file, float)\n\t\n\t# number of base pairs\n\tnbases = len(coordxyz)\n\t\n\t# use the model parameters to scale the distances \n\tscaling = BASE_BASE / la.norm(coordxyz[1, :] - coordxyz[0, :]) \n\tcoordxyz *= scaling\n\n\t#initialize vectors\n\tdist = np.copy(coordxyz)\n\tdist_norm = np.copy(coordxyz)\n\tp = np.copy(coordxyz)\n\t\n\tssdna1 = np.copy(coordxyz)\n\tv_perp_ssdna1 = np.copy(coordxyz)\n\t\n\tssdna2 = np.copy(coordxyz)\n\tv_perp_ssdna2 = np.copy(coordxyz)\n\t\n\t\n\t# take the bounding box as the simulation box for the output configuration\n\tboxx = max(coordxyz[:nbases, 0]) - min(coordxyz[:nbases, 0])\n\tboxy = max(coordxyz[:nbases, 1]) - min(coordxyz[:nbases, 1])\n\tboxz = max(coordxyz[:nbases, 2]) - min(coordxyz[:nbases, 2])\n\tboxmax = 1.5 * max(boxx, boxy, boxz)\n\t\n\t# centerline base_to_base vectors\n\tfor c in range(0, nbases): \n\t\tind = c \n\t\tind1 = (c + 1) % nbases\n\t\t#open chain cannot compute dist at c=nbases-1 \n\t\t#so we use as reference the previus dist\n\t\tif opts.closed or (not opts.closed and c!=nbases-1):\t\n\t\t\tdist[ind, :] = coordxyz[ind1, :] - coordxyz[ind, :]\n\t\t\tdist_norm[ind, :] = dist[ind, :] / la.norm(dist[ind, :])\n\t\telse:\n\t\t\tdist[ind, :] = dist[ind-1, :]\n\t\t\tdist_norm[ind, :] = dist_norm[ind-1, :]\n\n\t# vectors perpendicular between two consecutive centerline vectors (normalized)\n\tfor c in range(0, nbases): \n\t\tind_1 = (c - 1 + nbases) % nbases \n\t\tind = c\n\t\t\t\n\t\t#opens chain have random p at c=0 and at c=nbases-1 due to absence of neighbours\n\t\tif opts.closed or (not opts.closed and c!=0 and c!=nbases-1):\n\t\t\t#check that dist[ind_1, :] and dist[ind, :] are not equals\n\t\t\tif not np.all(np.isclose( dist[ind_1, :] , dist[ind, :]) ):\n\t\t\t\tp[ind, :] = np.cross(dist[ind_1, :] , dist[ind, :])\n\t\t\t\tp[ind, :] /= la.norm(p[ind, :])\n\t\t\t#else assign random p\n\t\t\telse:\n\t\t\t\trv=np.random.uniform(-1,1,3)\n\t\t\t\tp[ind, :] = rv - (np.dot(dist_norm[ind, :],rv)) * dist_norm[ind, :]\n\t\t\t\tp[ind, :] /= la.norm(p[ind, :])\n\t\telse:\n\t\t\trv=np.random.uniform(-1,1,3)\n\t\t\tp[ind, :] = rv - (np.dot(dist_norm[ind, :],rv)) * dist_norm[ind, :]\n\t\t\tp[ind, :] /= la.norm(p[ind, :])\n\n\t# chain writhe\n\tWR = 0.\n\tif opts.closed:\n\t\tWR = top.get_writhe(coordxyz)\n\n\t#oxdna equiibrium pitch\n\tpitch = 10.5\n\n\t#global linking number\n\tLK = round((nbases / pitch) * (opts.supercoiling + 1) + opts.writhe) \n\t\n\tTW = LK - WR \n\n\t#twisting angle between two consecutive bases\n\trot_base = TW * 2.0 * np.pi / nbases  \n\n\t#recap\n\tif opts.closed:\n\t\tprint >> sys.stderr, \"Total Linking Number (LK) %f, composed of:\" % ((nbases / pitch) * (opts.supercoiling + 1) + opts.writhe)\n\t\tprint  >> sys.stderr, \"1) Equilibrium number of DNA turns %f\" % (nbases / pitch)\n\t\tprint  >> sys.stderr, \"2) Target writhe %f = Topological writhe %f + Turns imposed by supercoiling  %f \" % (opts.writhe+(nbases / pitch) *opts.supercoiling,opts.writhe,(nbases / pitch) *opts.supercoiling)\n\t\tprint >> sys.stderr, \"LK has been rounded to %f\" % LK\n\t\tprint >> sys.stderr, \"Initial chain writhe %f\" % WR\n\n\n\t####################################\n\t# Initialize DNA strand \n\t####################################\n\t\n\t#First hydrogen-hydrogen bond vector\n\tv_perp_ssdna1[0, :] = np.cross(dist_norm[0, :], p[0, :]) \n\tv_perp_ssdna1[0, :] /= la.norm(v_perp_ssdna1[0, :])\n\tv_perp_ssdna2[0, :] = -v_perp_ssdna1[0, :]\n\t\n\tfor c in range(nbases): \n\t\t#dna center of mass positions\n\t\tssdna1[c, :] = coordxyz[c, :] - CM_CENTER_DS * v_perp_ssdna1[c, :] \n\t\tssdna2[c, :] = coordxyz[c, :] + CM_CENTER_DS * v_perp_ssdna1[c, :] \n\t\n\t\t#Update v_perp_ssdna1\n\t\t\n\t\tind_1 = c \n\t\tind = (c + 1) % nbases \n\t\t\n\t\talpha = top.py_ang(v_perp_ssdna1[ind_1, :] , p[ind, :] , dist[ind_1, :])\n\t\tgamma = rot_base - alpha\n\t\t#prevent change when ind=0 on open chain\n\t\tif c!=nbases-1:\t\t\n\t\t\tR = utils.get_rotation_matrix(dist[ind, :], gamma)\n\t\t\tv_perp_ssdna1[ind, :] = np.dot(R , p[ind, :])  \n\t\t\tv_perp_ssdna2[ind, :] = -v_perp_ssdna1[ind, :]\n\t\t\n\t# check LK imposed and measured\n\tif opts.closed:\n\t\tTW_measured = top.get_twist(coordxyz, ssdna1)\n\tbox = np.array([boxmax, boxmax, boxmax])\n\tsystem = base.System(box)\n\t\n\tif opts.sequence_file == None:\n\t\tssdna1_base = np.zeros(nbases, int)\n\t\tfor c in range(nbases):\n\t\t\tssdna1_base[c] = np.random.randint(0, 4)\n\telse:\n\t\ttry:\n\t\t\tseq_file = open(opts.sequence_file)\n\t\texcept Exception:\n\t\t\tprint >> sys.stderr, \"The sequence file '%s' is unreadable\" % opts.sequence_file\n\t\t\texit(1)\n\t\t\t\n\t\tcontents = seq_file.read()\n\t\t# remove all whitespace from the file's contents\n\t\tsequence = ''.join(contents.split())\n\t\tif len(sequence) != nbases:\n\t\t\tprint >> sys.stderr, \"The length of the given sequence (%d) should be equal to the number of coordinates in the centerline file (%d)\" % (len(sequence), nbases)\n\t\t\texit(1)\n\t\t\t\n\t\tssdna1_base = map(lambda x: base.base_to_number[x], sequence)\t\t\n\t\t\t\n\t\tseq_file.close()\n\n\tstrand1 = base.Strand()\t\n\tfor c in range(nbases):\n\t\tb = ssdna1_base[c]\n\t\tstrand1.add_nucleotide(base.Nucleotide(ssdna1[c], v_perp_ssdna1[c], dist_norm[c], b, b))\n\tif opts.closed:\n\t\tstrand1.make_circular()\n\tsystem.add_strand(strand1)\n\n\tif opts.double:\n\t\tstrand2 = base.Strand()\n\t\tfor c in range(nbases):\n\t\t\treverse_idx = nbases - 1 - c\n\t\t\tb = 3 - ssdna1_base[reverse_idx]\n\t\t\tstrand2.add_nucleotide(base.Nucleotide(ssdna2[reverse_idx], v_perp_ssdna2[reverse_idx], -dist_norm[reverse_idx], b, b))\n\t\tif opts.closed and not opts.nicked:\n\t\t\tstrand2.make_circular()\n\t\tsystem.add_strand(strand2)\n\t\t\n\tbasename = os.path.basename(sys.argv[1])\n\ttopology_file = basename + \".top\"\n\tconfiguration_file = basename + \".oxdna\"\n\tsystem.print_lorenzo_output(configuration_file, topology_file)\n\t\n\tprint >> sys.stderr, \"## Wrote data to '%s' / '%s'\" % (configuration_file, topology_file)\n\tprint >> sys.stderr, \"## DONE\"\n", "meta": {"hexsha": "4523e9f7beea5df8778e16a6ff45f5b4d74c6223", "size": 7913, "ext": "py", "lang": "Python", "max_stars_repo_path": "supporting_scripts/tacoxDNA/src/XYZ_oxDNA.py", "max_stars_repo_name": "ItsTheSebbe/4vHelix_GUI", "max_stars_repo_head_hexsha": "6626d29bf9a2150b2ab49104918ab2faa5f45c30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "supporting_scripts/tacoxDNA/src/XYZ_oxDNA.py", "max_issues_repo_name": "ItsTheSebbe/4vHelix_GUI", "max_issues_repo_head_hexsha": "6626d29bf9a2150b2ab49104918ab2faa5f45c30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "supporting_scripts/tacoxDNA/src/XYZ_oxDNA.py", "max_forks_repo_name": "ItsTheSebbe/4vHelix_GUI", "max_forks_repo_head_hexsha": "6626d29bf9a2150b2ab49104918ab2faa5f45c30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1666666667, "max_line_length": 206, "alphanum_fraction": 0.6407178061, "include": true, "reason": "import numpy", "num_tokens": 2576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.19188052045792536}}
{"text": "#-------------------------------------------------------------------------------\n#\n#  IGRF format parser\n#\n# Author: Martin Paces <martin.paces@eox.at>\n#\n#-------------------------------------------------------------------------------\n# Copyright (C) 2018 EOX IT Services GmbH\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all\n# copies of this Software or works derived from this Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#-------------------------------------------------------------------------------\n\nfrom numpy import array\n\nIGRF_EXTRAPOLATION_PERIOD = 5.0 # years\n\n\ndef parse_igrf_file(file_in):\n    \"\"\" Parse IGRF file format and return a dictionary containing the parsed\n    model data.\n    \"\"\"\n    lines = strip_igrf_comments(file_in)\n    data = {}\n    data[\"labels\"] = parse_igrf_header(next(lines))\n    data[\"t\"] = parse_igrf_times(next(lines))\n    data[\"nm\"], data[\"gh\"] = parse_igrf_coefficients(lines)\n    data[\"degree_min\"] = data[\"nm\"][:, 0].min()\n    data[\"degree_max\"] = data[\"nm\"][:, 0].max()\n    return data\n\n\ndef parse_igrf_coefficients(lines):\n    \"\"\" Parse IGRF coefficients. \"\"\"\n    nm_idx = []\n    coeff = []\n    for line in lines:\n        fields = line.split()\n        label, n_idx, m_idx = fields[0], int(fields[1]), int(fields[2])\n        if label == \"h\":\n            m_idx = -m_idx\n        nm_idx.append((n_idx, m_idx))\n        coeff.append([float(v) for v in fields[3:]])\n    coeff = array(coeff)\n    coeff[:, -1] = coeff[:, -2] + coeff[:, -1] * IGRF_EXTRAPOLATION_PERIOD\n    return array(nm_idx), coeff\n\n\ndef parse_igrf_times(line):\n    \"\"\" Parse SHC times. \"\"\"\n    times = [float(v) for v in line.split()[3:-1]]\n    times.append(times[-1] + IGRF_EXTRAPOLATION_PERIOD)\n    return array(times)\n\n\ndef parse_igrf_header(line):\n    \"\"\" Parse IGRF header with the column labels. \"\"\"\n    return line.split()\n\n\ndef strip_igrf_comments(file_in):\n    \"\"\" Strip initial comments and empty lines from a text file stream. \"\"\"\n    for line in file_in:\n        line = line.partition(\"#\")[0].strip()\n        if line:\n            yield line\n            break\n    for line in file_in:\n        line = line.strip()\n        yield line\n", "meta": {"hexsha": "2eaa2aac5b543109e62edff366b82bfa32b762c3", "size": 3072, "ext": "py", "lang": "Python", "max_stars_repo_path": "geoist/magmod/magnetic_model/parser_igrf.py", "max_stars_repo_name": "CHEN-Zhaohui/geoist", "max_stars_repo_head_hexsha": "06a00db3e0ed3d92abf3e45b7b3bfbef6a858a5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 53, "max_stars_repo_stars_event_min_datetime": "2018-11-17T03:29:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T02:36:25.000Z", "max_issues_repo_path": "geoist/magmod/magnetic_model/parser_igrf.py", "max_issues_repo_name": "CHEN-Zhaohui/geoist", "max_issues_repo_head_hexsha": "06a00db3e0ed3d92abf3e45b7b3bfbef6a858a5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-11-28T11:37:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-30T01:52:45.000Z", "max_forks_repo_path": "geoist/magmod/magnetic_model/parser_igrf.py", "max_forks_repo_name": "CHEN-Zhaohui/geoist", "max_forks_repo_head_hexsha": "06a00db3e0ed3d92abf3e45b7b3bfbef6a858a5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2018-11-17T03:29:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T17:57:06.000Z", "avg_line_length": 35.3103448276, "max_line_length": 80, "alphanum_fraction": 0.6236979167, "include": true, "reason": "from numpy", "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.19188052045792536}}
{"text": "#! /usr/bin/env python\n\"\"\"\nagilent4155_matlab_param.py\nPrarmeter extractor for matlab generated .xlsx files\n\nCreated by Jeremy Smith on 2015-07-07\nUniversity of California, Berkeley\nj-smith@eecs.berkeley.edu\n\"\"\"\n\nimport os\nimport sys\nimport xlrd\nimport numpy as np\nimport myfunctions as mf\nfrom scipy import stats\n\n__author__ = \"Jeremy Smith\"\n__version__ = \"1.5\"\n\ndata_path = os.path.dirname(__file__)    # Path name for location of script\n\nfiles = os.listdir(data_path)   # All files in directory\ndata_summary = []\ncolheads = ['VG', 'ID1', 'ID2', 'IG1', 'IG2']\nskipinit = 3          # skip initial data points \nrangefittop = 20.0    # % from max for fit range\nrangefitbot = 20.0    # % from min for fit range\nmobilitycorrection = 1.000     # K_actual/K_file\nsummary_list_header = [[\"filename\", \"satmob_tmax\", \"vthsat_tmax\", \"satmob_rev_tmax\", \"vthsat_rev_tmax\",\n\t\t\t\t\t\t\"linmob_tmax\", \"vthlin_tmax\", \"linmob_rev_tmax\", \"vthlin_rev_tmax\",\n\t\t\t\t\t\t\"hysteresis_lin\", \"hysteresis_sat\",\n\t\t\t\t\t\t\"onoffratio_lin\", \"onoffratio_sat\",\n\t\t\t\t\t\t\"leakage_ratio_lin\", \"leakage_ratio_sat\",\n\t\t\t\t\t\t\"Slin\", \"Slin_rev\", \"Ssat\", \"Ssat_rev\",\n\t\t\t\t\t\t\"satmob_FITTED\", \"vthsat_FITTED\", \"r_value\"]]\nsweepfwddirection = True       # True if sweeping from depletion to accumulation\n\ndef main():\n\t\"\"\"Main function\"\"\"\n\n\tprint \"\\nBatch importing .xlsx files...\"\n\tprint data_path, '\\n'\n\n\tfor f in files:\n\t\tprint f\n\t\t# Loops through all transfer files\n\t\tif \"IDVG.xlsx\" in f:\n\n\t\t\tworkbook = xlrd.open_workbook(f, logfile=open(os.devnull, 'w'))\n\n\t\t\tfor dev in workbook.sheet_names():\n\t\t\t\tif \"Sheet\" in dev:\n\t\t\t\t\tcontinue\n\t\t\t\tprint \"  - device {:s}\".format(dev)\n\t\t\t\tdatasheet = workbook.sheet_by_name(dev)\n\t\t\t\trun_numbers = [str(int(x)) for x in datasheet.row_values(2) if x]\n\n\t\t\t\tfor i, run in enumerate(run_numbers):\n\t\t\t\t\tprint \"    - run {:s}\".format(run)\n\t\t\t\t\tdata = {}\n\t\t\t\t\t# File name for outputs\n\t\t\t\t\toutname = f[:-5] + '_' + dev + '_' + run\n\t\t\t\t\t# Constant parameters taken from header of .xlsx file\n\t\t\t\t\tvd1 = float(datasheet.cell_value(3, 6*i + 3))\n\t\t\t\t\tvd2 = float(datasheet.cell_value(4, 6*i + 3))\n\t\t\t\t\tchl = float(datasheet.cell_value(1, 1))\n\t\t\t\t\tchw = float(datasheet.cell_value(0, 1))\n\t\t\t\t\ttox = float(datasheet.cell_value(1, 3))\n\t\t\t\t\tkox = float(datasheet.cell_value(0, 3))\n\t\t\t\t\tldr = float(datasheet.cell_value(1, 5))\n\t\t\t\t\tlso = float(datasheet.cell_value(0, 5))\n\t\t\t\t\t# Calculation of geometric capacitance\n\t\t\t\t\tci = 8.85418782e-7*kox/tox\n\t\t\t\t\t# Extract data\n\t\t\t\t\tfor h in colheads:\n\t\t\t\t\t\tdata[h] = []\n\t\t\t\t\tfor row in range(datasheet.nrows - 9):\n\t\t\t\t\t\tfor col, h in enumerate(colheads):\n\t\t\t\t\t\t\tif datasheet.cell_type(9 + row, 6*i + col) is 0:\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\tdata[h].append(float(datasheet.cell_value(9 + row, 6*i + col)))\n\t\t\t\t\tp = len(data['VG'])/2\n\t\t\t\t\t# Forward scan\n\t\t\t\t\tif sweepfwddirection:\n\t\t\t\t\t\tvg = np.array(data['VG'][:p])\n\t\t\t\t\t\tid1 = np.array(data['ID1'][:p])\n\t\t\t\t\t\tid2 = np.array(data['ID2'][:p])\n\t\t\t\t\t\tig1 = np.array(data['IG1'][:p])\n\t\t\t\t\t\tig2 = np.array(data['IG2'][:p])\n\t\t\t\t\telse:\n\t\t\t\t\t\tvg = np.array(data['VG'][:p][::-1])\n\t\t\t\t\t\tid1 = np.array(data['ID1'][:p][::-1])\n\t\t\t\t\t\tid2 = np.array(data['ID2'][:p][::-1])\n\t\t\t\t\t\tig1 = np.array(data['IG1'][:p][::-1])\n\t\t\t\t\t\tig2 = np.array(data['IG2'][:p][::-1])\n\t\t\t\t\t# Reverse scan\n\t\t\t\t\tif sweepfwddirection:\n\t\t\t\t\t\tvg_r = np.array(data['VG'][p:][::-1])\n\t\t\t\t\t\tid1_r = np.array(data['ID1'][p:][::-1])\n\t\t\t\t\t\tid2_r = np.array(data['ID2'][p:][::-1])\n\t\t\t\t\t\tig1_r = np.array(data['IG1'][p:][::-1])\n\t\t\t\t\t\tig2_r = np.array(data['IG2'][p:][::-1])\n\t\t\t\t\telse:\n\t\t\t\t\t\tvg_r = np.array(data['VG'][p:])\n\t\t\t\t\t\tid1_r = np.array(data['ID1'][p:])\n\t\t\t\t\t\tid2_r = np.array(data['ID2'][p:])\n\t\t\t\t\t\tig1_r = np.array(data['IG1'][p:])\n\t\t\t\t\t\tig2_r = np.array(data['IG2'][p:])\n\n\t\t\t\t\t# Smoothing Id for fitting\n\t\t\t\t\tid1_smoothed = mf.adjAvSmooth(abs(id1), N=1)\n\t\t\t\t\tid2_smoothed = mf.adjAvSmooth(abs(id2), N=1)\n\t\t\t\t\tid1_r_smoothed = mf.adjAvSmooth(abs(id1_r), N=1)\n\t\t\t\t\tid2_r_smoothed = mf.adjAvSmooth(abs(id2_r), N=1)\n\t\t\t\t\t# On-off ratio\n\t\t\t\t\tonoffratio1 = np.log10(max(id1[skipinit:-1])/min(abs(id1[skipinit:-1])))\n\t\t\t\t\tonoffratio2 = np.log10(max(id2[skipinit:-1])/min(abs(id2[skipinit:-1])))\n\t\t\t\t\t# Leakage ratio\n\t\t\t\t\tleakage_ratio1 = np.log10(abs(id1/ig1))\n\t\t\t\t\tleakage_ratio2 = np.log10(abs(id2/ig2))\n\n\t\t\t\t\t# Finding max saturation transconductance\n\t\t\t\t\tsqrtid2 = np.sqrt(id2_smoothed)\n\t\t\t\t\tsqrtid2_r = np.sqrt(id2_r_smoothed)\n\t\t\t\t\tdiff_sqrt_id2_smoothed = np.array(mf.numDiff(sqrtid2, vg))\n\t\t\t\t\tdiff_sqrt_id2_r_smoothed = np.array(mf.numDiff(sqrtid2_r, vg_r))\n\t\t\t\t\ttsmaxarg = np.argmax(diff_sqrt_id2_smoothed[skipinit:-1]) + skipinit\n\t\t\t\t\ttsmaxarg_r = np.argmax(diff_sqrt_id2_r_smoothed[skipinit:-1]) + skipinit\n\t\t\t\t\t# Saturation mobility (max transconductance)\n\t\t\t\t\tsatmob_t = mobilitycorrection * (2*chl/(chw*ci))*(diff_sqrt_id2_smoothed)**2\n\t\t\t\t\tsatmob_r_t = mobilitycorrection * (2*chl/(chw*ci))*(diff_sqrt_id2_r_smoothed)**2\n\t\t\t\t\tsatmob_tmax = satmob_t[tsmaxarg]\n\t\t\t\t\tsatmob_r_tmax = satmob_r_t[tsmaxarg_r]\n\t\t\t\t\t# Saturation threshold voltage (max transconductance)\n\t\t\t\t\tvthsat_tmax = vg[tsmaxarg] - sqrtid2[tsmaxarg]/diff_sqrt_id2_smoothed[tsmaxarg]\n\t\t\t\t\tvthsat_r_tmax = vg_r[tsmaxarg_r] - sqrtid2_r[tsmaxarg_r]/diff_sqrt_id2_r_smoothed[tsmaxarg_r]\n\t\t\t\t\t# Hysteresis\n\t\t\t\t\thysteresissat = vthsat_tmax - vthsat_r_tmax\n\t\t\t\t\t# Calculate subthreshold slopes\n\t\t\t\t\tsts_sat = min(abs(1/np.array(mf.numDiff([np.log10(abs(x)) for x in id2_smoothed[skipinit:-1]], vg[skipinit:-1]))))\n\t\t\t\t\tsts_r_sat = min(abs(1/np.array(mf.numDiff([np.log10(abs(x)) for x in id2_r_smoothed[skipinit:-1]], vg_r[skipinit:-1]))))\n\n\t\t\t\t\t# Finding max linear transconductance\n\t\t\t\t\tdiff_id1_smoothed = np.array(mf.numDiff(id1_smoothed, vg))\n\t\t\t\t\tdiff_id1_r_smoothed = np.array(mf.numDiff(id1_r_smoothed, vg_r))\n\t\t\t\t\ttlmaxarg = np.argmax(diff_id1_smoothed[skipinit:-1]) + skipinit\n\t\t\t\t\ttlmaxarg_r = np.argmax(diff_id1_r_smoothed[skipinit:-1]) + skipinit\n\t\t\t\t\t# Linear mobility (max transconductance)\n\t\t\t\t\tlinmob_t = mobilitycorrection * (chl/(chw*ci*vd1))*(diff_id1_smoothed)\n\t\t\t\t\tlinmob_r_t = mobilitycorrection * (chl/(chw*ci*vd1))*(diff_id1_r_smoothed)\n\t\t\t\t\tlinmob_tmax = linmob_t[tlmaxarg]\n\t\t\t\t\tlinmob_r_tmax = linmob_r_t[tlmaxarg_r]\n\t\t\t\t\t# Linear threshold voltage (max transconductance)\n\t\t\t\t\tvthlin_tmax = vg[tlmaxarg] - id1_smoothed[tlmaxarg]/diff_id1_smoothed[tlmaxarg]\n\t\t\t\t\tvthlin_r_tmax = vg_r[tlmaxarg_r] - id1_r_smoothed[tlmaxarg_r]/diff_id1_r_smoothed[tlmaxarg_r]\n\t\t\t\t\t# Hysteresis\n\t\t\t\t\thysteresislin = vthlin_tmax - vthlin_r_tmax\n\t\t\t\t\t# Calculate subthreshold slopes\n\t\t\t\t\tsts_lin = min(abs(1/np.array(mf.numDiff([np.log10(abs(x)) for x in id1_smoothed[skipinit:-1]], vg[skipinit:-1]))))\n\t\t\t\t\tsts_r_lin = min(abs(1/np.array(mf.numDiff([np.log10(abs(x)) for x in id1_r_smoothed[skipinit:-1]], vg_r[skipinit:-1]))))\n\n\t\t\t\t\t# Finds range of data that lies within the minimum+x% and the maximum-x% and also has a positive transconductance\n\t\t\t\t\tfitrange_id_lo = (1-rangefitbot/100.0)*min(sqrtid2[skipinit:-1]) + (rangefitbot/100.0)*max(sqrtid2[skipinit:-1])\n\t\t\t\t\tfitrange_id_hi = (1-rangefittop/100.0)*max(sqrtid2[skipinit:-1]) + (rangefittop/100.0)*min(sqrtid2[skipinit:-1])\n\t\t\t\t\tfitrange_bool = np.bitwise_and(np.bitwise_and(sqrtid2 > fitrange_id_lo, sqrtid2 < fitrange_id_hi), diff_sqrt_id2_smoothed > 0)\n\t\t\t\t\t# Checks that there are at least 3 data points to fit\n\t\t\t\t\tif sum(fitrange_bool) < 3:\n\t\t\t\t\t\tprint \"      NOT ENOUGH DATA TO FIT\"\n\t\t\t\t\t\tsatmob_FITTED = np.nan\n\t\t\t\t\t\tvthsat_FITTED = np.nan\n\t\t\t\t\t\tr_value = np.nan\n\t\t\t\t\telse:\n\t\t\t\t\t\t# Linear Fitting to sqrt(Idrain)\n\t\t\t\t\t\tslope, intercept, r_value, p_value, std_err = stats.linregress(vg[fitrange_bool][skipinit:-1], sqrtid2[fitrange_bool][skipinit:-1])\n\t\t\t\t\t\tfitline = slope*vg + intercept\n\t\t\t\t\t\t# Saturation mobility (from slope of sqrt(Idrain) fit)\n\t\t\t\t\t\tsatmob_FITTED = mobilitycorrection * (2*chl/(chw*ci))*slope**2\n\t\t\t\t\t\t# Threshold Voltage (from slope of sqrt(Idrain) fit)\n\t\t\t\t\t\tvthsat_FITTED = -intercept/slope\n\t\t\t\t\t\t# Plot sqrt(Isd)\n\t\t\t\t\t\tmf.quickPlot(outname+\"_SQRTplot\", data_path, [vg, sqrtid2, fitline],\n\t\t\t\t\t\txlabel=\"VG [V]\", ylabel=\"sqrt(Id) [A^0.5]\", yrange=[0, 'auto'])\n\n\t\t\t\t\t# Output data\n\t\t\t\t\tdata_summary.append([outname,\n\t\t\t\t\t\tsatmob_tmax, vthsat_tmax,\n\t\t\t\t\t\tsatmob_r_tmax, vthsat_r_tmax,\n\t\t\t\t\t\tlinmob_tmax, vthlin_tmax,\n\t\t\t\t\t\tlinmob_r_tmax, vthlin_r_tmax,\n\t\t\t\t\t\thysteresislin, hysteresissat,\n\t\t\t\t\t\tonoffratio1, onoffratio2,\n\t\t\t\t\t\tleakage_ratio1[-skipinit],\n\t\t\t\t\t\tleakage_ratio2[-skipinit],\n\t\t\t\t\t\tsts_lin, sts_r_lin, sts_sat, sts_r_sat,\n\t\t\t\t\t\tsatmob_FITTED, vthsat_FITTED, r_value**2])\n\n\t\t\t\t\t# Ouput files\n\t\t\t\t\tmf.dataOutputHead(outname+\"_transfer.txt\", data_path, [np.array(data['VG']), abs(np.array(data['ID1'])), abs(np.array(data['ID2'])), abs(np.array(data['IG1'])), abs(np.array(data['IG2'])),\n\t\t\t\t\t\tnp.concatenate((linmob_t, linmob_r_t[::-1])), np.concatenate((satmob_t, satmob_r_t[::-1]))],\n\t\t\t\t\t\t[[\"vg\", \"idlin\", \"idsat\", \"iglin\", \"igsat\", \"LINMOB\", \"SATMOB\"]], \n\t\t\t\t\t\tformat_d=\"%.3f\\t %.5e\\t %.5e\\t %.5e\\t %.5e\\t %.5e\\t %.5e\\n\", \n\t\t\t\t\t\tformat_h=\"%s\\t\")\n\t\t\t\t\t\n\t\t\t\t\t# Plot transfer\n\t\t\t\t\tmf.quickPlot(outname+\"_TRANSFERplot\", data_path, [vg, id1_smoothed, id1_r_smoothed, abs(ig1), id2_smoothed, id2_r_smoothed, abs(ig2)],\n\t\t\t\t\t\txlabel=\"VG [V]\", ylabel=\"Id,g [A]\", yscale=\"log\", yrange=[1e-12, 1e-2], col=[\"r\", \"r\", \"r\", \"b\", \"b\", \"b\"])\n\n\tmf.dataOutputHead(\"SUMMARY.txt\", data_path, map(list, zip(*data_summary)), summary_list_header,\n\t\tformat_d=\"%s\\t %.5e\\t %.5f\\t %.5e\\t %.5f\\t %.5e\\t %.5f\\t %.5e\\t %.5f\\t %.5f\\t %.5f\\t %.5f\\t %.5f\\t %.5f\\t %.5f\\t %.5f\\t %.5f\\t %.5f\\t %.5f\\t %.5e\\t %.5f\\t %.6f\\n\", \n\t\tformat_h=\"%s\\t\")\n\n\treturn\n\n\nif __name__ == \"__main__\":\n\tsys.exit(main())\n", "meta": {"hexsha": "5ae5ad84fb48f9d07029041d84f361fa6d1f6203", "size": 9549, "ext": "py", "lang": "Python", "max_stars_repo_path": "agilent4155_matlab_param.py", "max_stars_repo_name": "jzmnd/fet-py-scripts", "max_stars_repo_head_hexsha": "c3709c1ed3078d3f9cc1eebc658814842a59e380", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "agilent4155_matlab_param.py", "max_issues_repo_name": "jzmnd/fet-py-scripts", "max_issues_repo_head_hexsha": "c3709c1ed3078d3f9cc1eebc658814842a59e380", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "agilent4155_matlab_param.py", "max_forks_repo_name": "jzmnd/fet-py-scripts", "max_forks_repo_head_hexsha": "c3709c1ed3078d3f9cc1eebc658814842a59e380", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.8027522936, "max_line_length": 193, "alphanum_fraction": 0.6526337836, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.19175670530902317}}
{"text": "# coding=utf-8\n# Copyright (c) 2015-2018, UT-BATTELLE, LLC\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its contributors\n# may be used to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\nCISM_glissade module for numerics analysis\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport math\n\nimport numpy as np\n\nfrom netCDF4 import Dataset\nfrom scipy import interpolate\n\n\nclass DataGrid:\n    \"\"\"\n    Class to handle the CISM_glissade grids, which are cell-centered grids.\n    \"\"\"\n    def __init__(self, data):\n        self.y = data.variables['y1']\n        self.ny = self.y[:].shape[0]\n        self.dy = self.y[1] - self.y[0]\n\n        # NOTE: cell centered grids, hence the dy.\n        self.Ly = self.y[-1] - self.y[0] + self.dy\n\n        self.x = data.variables['x1']\n        self.nx = self.x[:].shape[0]\n        self.dx = self.x[1] - self.x[0]\n\n        # NOTE: cell centered grids, hence the dx.\n        self.Lx = self.x[-1] - self.x[0] + self.dx\n\n        self.y_hat = (self.y[:] + self.y[0])/self.Ly\n        self.x_hat = (self.x[:] + self.x[0])/self.Lx\n\n\nclass RotatedGrid:\n    \"\"\"\n    For the ISMIP-HOM f tests, CISM computes the flow of a glacier down an\n    inclined plane:\n\n    ::\n\n        z\n        ^\n        |\n        * .\n        .    .\n        .        .\n        *           .\n        | .             .\n        |    .     ICE      .\n        |        .              .\n        |            .             .\n        |  BED           .            .\n        |                    .           *\n        |                       .        .\n        |                          .     .\n        |                             .  .\n        |                                *\n        |                                |\n        |                                |\n        |                                |\n        0------------------------------------->x\n\n\n    The origin is at point 0 in the above figure, and the topmost point of the\n    glacier is at x=0, z=7 (in km). The slope is 3 degrees. The ice is 1000 m\n    tall and flows down the inclined plane.\n\n    ISMIP-HOM, however, defines the coordinate system with the origin located at\n    the topmost point of the glacier (0,7) with the x' axis pointing down slope\n    and z' pointing perpendicular to the slope. So the coordinate system is\n    shifted, and rotated by a=3 degrees from the CISM glissade grid.\n\n    An additional complication is that the surface is computed in CISM on the\n    standard grid, but velocities are computed on a staggered, grid.\n\n    This class converts the CISM_glissade coordinate system to the ISMIP-HOM\n    coordinate system.\n    \"\"\"\n    def __init__(self, alpha, data):\n        self.alpha = alpha\n        self.y0 = data.variables['y0'][:]\n        self.x0 = data.variables['x0'][:]\n\n        self.usurf_ustag = data.variables['usurf'][-1,:,:]\n        self.usurf_stag = (  self.usurf_ustag[1: , 1: ] + self.usurf_ustag[1: , :-1]\n                           + self.usurf_ustag[:-1, :-1] + self.usurf_ustag[:-1, 1: ]) / 4.0\n\n        self.usurf = -(self.x0)*math.sin(alpha) + (self.usurf_stag-7000.0)*math.cos(alpha)\n\n        self.uvel_stag = data.variables['uvel'][-1,0,:,:]\n        self.vvel_stag = data.variables['uvel'][-1,0,:,:]\n\n        try:\n            self.wvel_ustag = data.variables['wvel_ho'][-1,0,:,:]\n        except:\n            self.wvel_ustag = data.variables['wvel'][-1,0,:,:]\n        self.wvel_stag = (  self.wvel_ustag[1: , 1: ] + self.wvel_ustag[1: , :-1]\n                          + self.wvel_ustag[:-1, :-1] + self.wvel_ustag[:-1, 1: ]) / 4.0\n\n        self.uvel =  self.uvel_stag*math.cos(alpha) + self.wvel_stag*math.sin(alpha)\n        self.vvel = -self.uvel_stag*math.sin(alpha) + self.wvel_stag*math.cos(alpha)\n\n        self.x = (self.x0*math.cos(alpha)\n                  + (self.usurf_stag[20,:]-7000.0)*math.sin(alpha)\n                  )/1000.0 - 50.0\n        self.y = self.y0/1000.0 - 50.0\n\n\ndef get_plot_data(test_file, bench_file, setup, config):\n    test_plot_data = {}\n    bench_plot_data = {}\n    exp = config['name'].split('-')[-1]\n    test_data = Dataset(test_file, 'r')\n    bench_data = Dataset(bench_file, 'r')\n\n    test = DataGrid(test_data)\n    bench = DataGrid(bench_data)\n\n    x_coord = setup['interp_points']\n    y_coord = np.linspace(setup['y'][0], setup['y'][1], len(x_coord))\n\n    test_plot_data['y_hat'] = y_coord\n    test_plot_data['x_hat'] = x_coord\n    bench_plot_data['y_hat'] = y_coord\n    bench_plot_data['x_hat'] = x_coord\n\n    if exp in ['a', 'c']:\n        for var in config['interp_vars']:\n            if var == 'usurf':\n                # regular 2d linear interp. but faster.\n                test2plot = interpolate.RectBivariateSpline(test.y_hat, test.x_hat,\n                                                            test_data.variables[var][-1,:,:],\n                                                            kx=1, ky=1, s=0)\n                bench2plot = interpolate.RectBivariateSpline(bench.y_hat, bench.x_hat,\n                                                             bench_data.variables[var][-1,:,:],\n                                                             kx=1, ky=1, s=0)\n            else:\n                # regular 2d linear interp. but faster.\n                test2plot = interpolate.RectBivariateSpline(test.y_hat, test.x_hat,\n                                                            test_data.variables[var][-1,0,:,:],\n                                                            kx=1, ky=1, s=0)\n                bench2plot = interpolate.RectBivariateSpline(bench.y_hat, bench.x_hat,\n                                                             bench_data.variables[var][-1,0,:,:],\n                                                             kx=1, ky=1, s=0)\n\n            test_plot_data[var] = test2plot(y_coord, x_coord, grid=False)\n            bench_plot_data[var] = bench2plot(y_coord, x_coord, grid=False)\n\n        test_plot_data['velnorm_extend'] = \\\n            np.linalg.norm(\n                np.array([test_plot_data['uvel_extend'],\n                          test_plot_data['vvel_extend'] ]),\n                axis=0)\n        bench_plot_data['velnorm_extend'] = \\\n            np.linalg.norm(\n                np.array([bench_plot_data['uvel_extend'],\n                          bench_plot_data['vvel_extend'] ]),\n                axis=0)\n    else:  # f\n        alpha = math.radians(-3.0)\n\n        test_rotated = RotatedGrid(alpha, test_data)\n        bench_rotated = RotatedGrid(alpha, bench_data)\n\n        for var in config['interp_vars']:\n            # regular 2d linear interp. but faster.\n            test2plot = interpolate.RectBivariateSpline(test_rotated.x, test_rotated.y,\n                                                        getattr(test_rotated, var),\n                                                        kx=1, ky=1, s=0)\n            bench2plot = interpolate.RectBivariateSpline(bench_rotated.x, bench_rotated.y,\n                                                         getattr(bench_rotated, var),\n                                                         kx=1, ky=1, s=0)\n\n            test_plot_data[var] = test2plot(y_coord, x_coord, grid=False)\n            bench_plot_data[var] = bench2plot(y_coord, x_coord, grid=False)\n\n        test_plot_data['velnorm'] = \\\n            np.linalg.norm(\n                np.array([test_plot_data['uvel'],\n                          test_plot_data['vvel'] ]),\n                axis=0)\n        bench_plot_data['velnorm'] = \\\n            np.linalg.norm(\n                np.array([bench_plot_data['uvel'],\n                          bench_plot_data['vvel'] ]),\n                axis=0)\n\n    return {'test': test_plot_data, 'bench': bench_plot_data}\n", "meta": {"hexsha": "1fbd088aa0f95e399caa0a71d6259ce024ccfab8", "size": 9063, "ext": "py", "lang": "Python", "max_stars_repo_path": "livvkit/bundles/CISM_glissade/numerics.py", "max_stars_repo_name": "jhkennedy/LIVVkit", "max_stars_repo_head_hexsha": "680120cd437e408673e62e535fc0a246c7fc17db", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "livvkit/bundles/CISM_glissade/numerics.py", "max_issues_repo_name": "jhkennedy/LIVVkit", "max_issues_repo_head_hexsha": "680120cd437e408673e62e535fc0a246c7fc17db", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "livvkit/bundles/CISM_glissade/numerics.py", "max_forks_repo_name": "jhkennedy/LIVVkit", "max_forks_repo_head_hexsha": "680120cd437e408673e62e535fc0a246c7fc17db", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1954545455, "max_line_length": 97, "alphanum_fraction": 0.5407701644, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.35577490034429643, "lm_q1q2_score": 0.19175670162740874}}
{"text": "\"\"\"\n    Qunantum Transport simulator using QUEST.\n    Copyright (C) 2014  K M Masum Habib <masum.habib@gmail.com>\n\n    Last update: 05/12/2014\n\"\"\"\n\nimport os\nimport pickle as pk\nimport numpy as np\nimport random as rn\n\nfrom quest import setVerbosity, greet, vprint\nfrom quest.vprint import nprint, dprint, eprint\nfrom quest.linspace import linspace\nfrom quest.atoms import AtomicStruct, SVec, LCoord\nfrom quest.hamiltonian import TISurfKpParams4, TISurfKpParams, TI3DKpParams, GrapheneKpParams, GrapheneOneValleyKpParams, GrapheneTwoValleyKpParams, GrapheneTbParams, generateHamOvl\nfrom quest.negf import CohRgfLoop\nfrom quest.kpoints import KPoints\nfrom quest.potential import LinearPot\nfrom quest.utils import Timer, Workers, Quadrilateral, Point\n\nclass Transport(object):\n    \"\"\"\n    Qunantum Transport simulator using QUEST.\n        \n    * Device geometry:\n        ----------------------------------------\n         ... |-1 | 0 | 1 |  ...  | N |N+1|N+2| ...\n        ----------------------------------------\n                   ^  <------^------>  ^\n                 left      Device    right\n               contact              contact\n\n    Notes:\n        1. Coherent RGF calculation for non-uniform devices requires at least \n           5 blocks: 1 source block, 1 drain block and 3 device blocks as \n           shown in the following fig:\n\n           --------------------------\n             | 0 | 1 | 2 | 3 | 4 |\n           --------------------------\n               ^  <--------->  ^\n            source  Device   drain \n\n           Block  0 and block 1 has to be identical. \n           Simularly, block 3 and block 4 hast to be identical.\n\n        2. Any uniform device needs atleast 3 blocks: two contact\n           blocks and one device block.\n           \n    Attributes:\n    \n        \n    \"\"\"\n\n    def __init__(self, workers = None):   \n        \"\"\" \n        Class constructor. \n        param:\n          workers: mpi.world - MPI world communicator.\n        \"\"\"  \n\n        self.verbosity = vprint.MSG_NORMAL # Verbosity level\n        \n        # MPI stuff\n        if workers is None:\n            self.workers = Workers()\n        else:\n            self.workers = Workers(workers)\n        vprint.IAmMaster = self.workers.IAmMaster()\n    \n        # Timer\n        self.clock = Timer()\n\n        # output path settings\n        self.OutPath    = \"./out/\"     # Output path\n        self.OutFileName = \"TR\"        # Output file name prefix\n        \n        # Bias\n        self.VDD        = np.zeros(1)  # Drain bias\n        self.VGG        = np.zeros(1)  # Gate bias\n        self.Vo         = 0.0          # Built in potential\n        \n        # Device geometry\n        self.nb         = 11           # Length of the device+contacts\n        self.nw         = 9            # Width of the device\n        self.nh         = 1\n        self.nbw        = []           # Width of all layers\n\n        # for k-loop\n        self.nk2         = 0            # number of k points along a2        \n        self.kp         = KPoints()    # K point generator\n        \n        # Hamiltonian type\n        self.HAM_TI_SURF_KP  = 10       # TI surface k.p hamiltonian\n        self.HAM_TI_SURF_KP4 = 11       # TI surface k.p hamiltonian with 4 spin basis set\n        self.HAM_TI_3D_KP    = 15       # TI 3D k.p hamiltonian with 4 spin basis set        \n        self.HAM_GRAPHENE_KP = 20       # Graphene k.p Hamiltonian\n        self.HAM_GRAPHENE_TWO_VALLEY_KP = 21       # Graphene k.p Hamiltonian\n        self.HamType         = self.HAM_TI_SURF_KP \n        \n        # Device types\n        self.COH_RGF_UNI    = 10       # Coherent uniform RGF type device\n        self.COH_RGF_NON_UNI= 20       # Coherent Non-uniform RGF type device\n        self.DevType        = self.COH_RGF_UNI\n        \n        # Potential profile type\n        self.POT_LINEAR     = 10       # Linear potential model\n        self.PotType        = self.POT_LINEAR  \n        \n        # Calculations\n        self.Calculations = {}\n        self.Calculations[\"TE\"] = 1\n        \n        # \n        self.kT             = 0.0259        # Temperature in eV (300 K)\n        self.ieta           = 1E-3j         # Contact imaginary potential\n        self.mu             = 0.0           # Device Fermi level\n        self.OrthoBasis     = True          # Orthogonal basis?\n        self.Emin           =-1.0           # Minimum energy \n        self.Emax           = 1.0           # Maximum energy\n        self.dE             = 0.005         # Energy step\n        self.AutoGenE       = False         # Generate grid automatically?\n        \n        # Debug stuffs\n        self.DebugPotFile   = \"dbg_pot.dat\"\n        self.DebugGeomFile  = \"dbg_geom.svg\"\n        \n        # Dry run\n        self.DryRun         = False\n        \n        # Skip if resulting dat file already exists?\n        self.SkipExistingSimulation = False\n\n        # Print welcome message.\n        nprint(greet())\n\n    @property \n    def verbosity(self):\n        return self._verbosity  \n    @verbosity.setter\n    def verbosity(self, value):\n        self._verbosity = value\n        # Set verbosity level of QUEST library.\n        setVerbosity(self._verbosity)\n        vprint.verbosity = self._verbosity\n   \n    def muS(self, VDD):\n        \"\"\"Calculates the fermi energy level of the source.\"\"\"\n        return self.mu - VDD*self.V.rVS\n    \n    def muD(self, VDD):\n        \"\"\"Calculates the drain energy level of the source.\"\"\"\n        return self.mu - VDD*self.V.rVD\n \n    \n    def VG(self, VGG, Vo, ig):\n        \"\"\" Computes the gate voltage of gate #ig. \"\"\"\n        # Set gate voltages\n        return VGG*self.V.rVG[ig] + Vo*self.V.rVo[ig]\n      \n    def addSource(self, sql, rVS = -0.5):\n        \"\"\" Adds a source contact to the device for electrostatics calculation.\"\"\"\n        self.V.addSource(sql)\n        self.V.rVS = rVS\n        # just for pickling\n        self.V.sql = sql    \n    \n    def addDrain(self, dql, rVD = 0.5):\n        \"\"\" Adds a drain contact to the device for electrostatics calculation.\"\"\"\n        self.V.addDrain(dql)\n        self.V.rVD = rVD\n        # just for pickling\n        self.V.dql = dql \n\n    def addGate(self, gql, rVo = 1, rVG = 1):\n        \"\"\" Adds a gate to the device for electrostatics calculation.\"\"\"\n        self.V.addGate(gql)\n        self.V.rVG.append(rVG)\n        self.V.rVo.append(rVo)\n         # just for pickling\n        self.V.gql.append(gql) \n\n    def addLinearRegion(self, lql):\n        \"\"\" Adds a linear region to the device for electrostatics calculation.\"\"\"\n        self.V.addLinearRegion(lql)\n        # just for pickling\n        self.V.lql.append(lql) \n               \n    def createAtomicGeom(self):\n        \"\"\" Creates atomistic geometry. \"\"\"\n\n        nprint(\"\\n Creating atomistic geometry ...\")\n\n        if not hasattr(self, \"hp\"): # if hp does not exist, create it.\n            if self.HamType == self.HAM_TI_SURF_KP:\n                self.hp = TISurfKpParams()\n            elif self.HamType == self.HAM_TI_SURF_KP4:\n                self.hp = TISurfKpParams4()\n            elif self.HamType == self.HAM_TI_3D_KP:\n                self.hp = TI3DKpParams()\n            elif self.HamType == self.HAM_GRAPHENE_KP:\n                self.hp = GrapheneOneKpParams()\n            elif self.HamType == self.HAM_GRAPHENE_TWO_VALLEY_KP:\n                self.hp = GrapheneTwoKpParams()\n            else:\n                raise RuntimeError(\" Unsupported Hamiltonian type. \")\n\n        dev = AtomicStruct(self.hp.ptable)\n        dev.genSimpleCubicStruct(self.hp.ptable[0], self.hp.a, self.nb-2, self.nw, self.nh)\n\n        if not hasattr(self, \"nlc\"):\n            self.nlc = self.nw\n\n        if not hasattr(self, \"nrc\"):\n            self.nrc = self.nw\n\n        cont_left = AtomicStruct(self.hp.ptable)\n        cont_left.genSimpleCubicStruct(self.hp.ptable[0], self.hp.a, 1, self.nlc, self.nh)\n        xs = dev.xmin\n        cont_left += np.array([xs, 0, 0])\n        cont_left += LCoord(-1, 0, 0)\n\n        cont_right = AtomicStruct(self.hp.ptable)\n        cont_right.genSimpleCubicStruct(self.hp.ptable[0], self.hp.a, 1, self.nrc, self.nh)\n        xs = dev.xmax\n        cont_right += np.array([xs, 0, 0])\n        cont_right += LCoord(1, 0, 0)\n\n        self.geom = cont_left + dev + cont_right\n        self.lyr_0 = cont_left\n        self.lyr_nbm1 = cont_right\n        cont_left += LCoord(-1, 0, 0)\n        cont_right += LCoord(1, 0, 0)\n        self.lyr_0m1 = cont_left\n        self.lyr_nb = cont_right\n\n        self.nbw = [self.nw]*self.nb\n        self.nbw[0] = self.nlc\n        self.nbw[self.nb-1] = self.nrc\n        self.updateBoundingBox()\n\n        nprint(\" done.\")\n\n    def createRoughEdges(self, sigma):\n        \"\"\" \n        Creates rough edges. Works only for sorted lattice points.\n        For rectangular lattice \n        \"\"\"\n\n        nprint(\"\\n Creating rough edges ...\")\n\n        if (self.HamType == self.HAM_TI_SURF_KP \n                    or self.HamType == self.HAM_TI_SURF_KP4\n                    or self.HamType == self.HAM_GRAPHENE_KP\n                    or self.HamType == self.HAM_GRAPHENE_TWO_VALLEY_KP):\n            nw = []\n            geom = AtomicStruct()\n            beg = 0\n            # loop through the layers and \n            # remove some atoms randomly from the edges.\n            for ib in range(0, self.nb):\n                end = beg + self.nw - 1\n                lyr = self.geom.span(beg, end)\n                beg = end + 1\n                \n                if ( ib > 1 and ib < self.nb - 2):\n                    # Remove or add some atoms from the bottom edge.\n                    nr = int(rn.gauss(0, sigma))\n                    while abs(nr) > 3*sigma:\n                        nr = int(rn.gauss(0, sigma))\n                    if nr <= 0: \n                        lyr = lyr.span(abs(nr), lyr.NumOfAtoms - 1)\n                    else:\n                        xtra = lyr.span(0, nr-1)\n                        lv = SVec(0, - self.hp.ay*nr, 0)\n                        xtra = xtra + lv\n                        lyr = xtra + lyr \n                        \n                    # Remove or add some atoms from the top edge\n                    nr = int(rn.gauss(0, sigma))\n                    while abs(nr) > 3*sigma:\n                        nr = int(rn.gauss(0, sigma))\n                    if nr <= 0: \n                        lyr = lyr.span(0, lyr.NumOfAtoms - 1 - abs(nr))\n                    else:\n                        xtra = lyr.span(lyr.NumOfAtoms - nr, lyr.NumOfAtoms - 1)\n                        lv = SVec(0, self.hp.ay*nr, 0)\n                        xtra = xtra + lv\n                        lyr = lyr + xtra\n                        \n                # save this layer\n                geom = geom + lyr\n                nw.append(lyr.NumOfAtoms)\n                \n            # save geometry\n            self.geom = geom\n            self.nbw = nw\n            self.DevType = self.COH_RGF_NON_UNI\n            \n            # update bounding box\n            self.updateBoundingBox()\n\n        else:           \n            raise RuntimeError(\" Unsupported Hamiltonian type. \")\n\n        nprint(\" done.\")\n                \n    def generateHamiltonian(self):\n        \"\"\" Generates hamiltonian and overlap matrices. \"\"\"\n\n        nprint(\"\\n Generating Hamiltonian matrix ...\")\n\n        # For uniform RGF blocks\n        if (self.DevType == self.COH_RGF_UNI): \n            # no k-loop, real space hamiltonian only\n            if self.kp.N == 0:\n                \n                lyr0 = self.geom.span(0, self.nw*self.nh-1)               # extract block # 0\n                lyr1 = self.geom.span(self.nw*self.nh, 2*self.nw*self.nh-1)    # extract block # 1\n                \n                self.H0, self.S0 = generateHamOvl(self.hp, lyr0, lyr0)\n\n                self.Hl, S = generateHamOvl(self.hp, lyr1, lyr0)\n\n#                np.set_printoptions(linewidth=200)\n#                print \"\\nS0\\n\"\n#                print self.S0\n#                print \"\\nH0\\n\"\n#                print self.H0\n#                print \"\\nHl\\n\"\n#                print self.Hl\n#                self.geom.exportGjf('dbg_geom.gjf')\n#                lyr0.exportGjf('lyr0.gjf')\n#                lyr1.exportGjf('lyr1.gjf')\n#                lyr01 = lyr0+lyr1;\n#                lyr01.exportGjf('lyr01.gjf')\n                \n            # nearest neighbors in transverse direction for k-loop\n            else:\n                self.H0 = []\n                self.S0 = []\n                self.Hl = []\n                self.pv = []\n                self.pvl = []\n                \n                lv = self.geom.LatticeVector\n                self.pv.append(lv*LCoord(0,0,0))\n                self.pvl.append(lv*LCoord(0,0,0))\n                lyr0 = self.geom.span(0, self.nw*self.nh-1)               # extract block # 0\n                lyr1 = self.geom.span(self.nw*self.nh, 2*self.nw*self.nh-1)    # extract block # 1\n                \n                H, S = generateHamOvl(self.hp, lyr0, lyr0)\n                self.H0.append(H); self.S0.append(S)\n                H, S = generateHamOvl(self.hp, lyr1, lyr0)\n                self.Hl.append(H)\n                \n                self.pv.append(lv*LCoord(0,1,0))\n                lyr0top = lyr0 + self.pv[1]                # top neighbor of layer 0\n                H, S = generateHamOvl(self.hp, lyr0, lyr0top)\n                self.H0.append(H)\n                \n                self.pv.append(lv*LCoord(0, -1, 0))\n                lyr0bot = lyr0 + self.pv[2]                # bottom neighbor of layer 0\n                H, S = generateHamOvl(self.hp, lyr0, lyr0bot)\n                self.H0.append(H)\n               \n                self.pvl.append(lv*LCoord(-1,1,0))\n                H, S = generateHamOvl(self.hp, lyr1, lyr0top)\n                self.Hl.append(H)\n                \n                self.pvl.append(lv*LCoord(-1,-1,0))\n                H, S = generateHamOvl(self.hp, lyr1, lyr0bot)        \n                self.Hl.append(H)\n        # Non-uniform RGF blocks        \n        elif (self.DevType == self.COH_RGF_NON_UNI):\n            self.H0 = []\n            self.S0 = []\n            self.Hl = []\n            beg = 0\n            for ib in range(0, self.nb):                    # setup the block hamiltonian\n                end = beg + self.nbw[ib] - 1\n                \n                # generate H_i,i and S_i,i\n                lyri = self.geom.span(beg, end)            # extract block # i\n                H0,S0 = generateHamOvl(self.hp, lyri, lyri)\n                self.H0.append(H0)\n                self.S0.append(S0)\n\n                # generate H_i,i-1\n                if ib > 0:\n                    Hl,Sl = generateHamOvl(self.hp, lyri, lyrim1)\n                    self.Hl.append(Hl)\n                \n                lyrim1 = lyri\n                beg = end + 1\n            # Coupling matrix between two blocks of left contact\n            Hl,Sl = generateHamOvl(self.hp, self.lyr_0, self.lyr_0m1)\n            self.Hl.insert(0, Hl)\n            # Coupling matrix between two blocks of right contact\n            Hl,Sl = generateHamOvl(self.hp, self.lyr_nb, self.lyr_nbm1)\n            self.Hl.append(Hl)\n\n        nprint(\" done.\")\n        \n    def setupPotential(self):\n        \"\"\" Sets up the potential profile \"\"\"\n\n        nprint(\"\\n Setting up potential ...\")\n        # Linear\n        if (self.PotType == self.POT_LINEAR):\n            self.V = LinearPot(self.geom)\n        nprint(\" done.\")\n    \n    def check(self):\n        ret = True\n        if (self.DevType == self.COH_RGF_UNI):\n            ret = ret and (self.nb >= 3)\n        if (self.DevType == self.COH_RGF_NON_UNI):\n            ret = ret and (self.nb >= 5)\n            \n        return ret\n\n    def runBiasStep(self, VGG, Vo, VDD):            \n        \"\"\"Runs the sumulation.\"\"\"\n\n        # Set drain and Fermi levels\n        self.rgf.mu(self.muD(VDD), self.muS(VDD))\n            \n        nprint(\"\\n Bias loop:\")                                \n        nprint(\"\\n  VGG = \" + str(VGG) + \", Vo = \" + str(Vo) \n                    + \", VDD = \" + str(VDD) + \".\")\n        \n        fileName = self.OutFileName + \"_VGG{0:2.3f}_Vo{1:2.3f}_VDD{2:2.3f}\".format(VGG, Vo, VDD)\n\n        # skip calculation if result file exists.\n        if self.SkipExistingSimulation == True:\n            if os.path.isfile(self.OutPath + fileName + \".dat\"):\n                nprint(\"\\n  Result exists, skipping.\")\n                return\n            \n        # Set gate voltages\n        for ig in range(self.V.NG):\n            VG = self.VG(VGG, Vo, ig)\n            # bias voltage for gate # ig\n            self.V.VG(ig, VG)\n            # For linear potential profile\n            if (self.PotType == self.POT_LINEAR):\n                # set potential of source\n                if (ig == 0):\n                    self.V.VS(VG)\n                # set potential of drain\n                if (ig == self.V.NG - 1):\n                    self.V.VD(VG)\n        \n        # Potential of linear region\n        if (self.PotType == self.POT_LINEAR):\n            for il in range(self.V.NLR):\n                VG1 = self.VG(VGG, Vo, il)\n                VG2 = self.VG(VGG, Vo, il+1)\n                self.V.VLR(il, VG1, VG2)        \n\n        # Print some useful information\n        nprint(\"\\n\")\n        nprint(self.dynamicnstr())\n \n        # Compute the electrostatic potential\n        self.V.compute()\n        eprint(self.V)\n        \n        # Save the calculated potential.\n        if (self.verbosity >= vprint.MSG_DEBUG):\n            if (self.workers.IAmMaster()):\n                # Create directory if not exist.\n                if not os.path.exists(self.OutPath):\n                    os.makedirs(self.OutPath) \n                self.V.exportPotential(self.OutPath + self.DebugPotFile)\n        \n        # Export potential to NEGF\n        beg = 0\n        self.Vo = []\n        for ib in range(self.nb):                  # setup the block hamiltonian\n            end = beg + self.nbw[ib]*self.nh - 1\n            self.Vo.append(self.V.toOrbPot(beg, end)) \n            self.rgf.V(self.Vo[ib], ib)\n            beg = end + 1\n            \n            \n        # Create energy grid\n        if (self.AutoGenE):\n            Emin = self.muD(VDD) - 10*self.kT\n            Emax = self.muS(VDD) + 10*self.kT\n        else:\n            Emin = self.Emin\n            Emax = self.Emax\n            \n        EE = linspace(Emin, Emax, self.dE)\n\n        \n        nprint(\"\\n Energy grid:\\n  Min: \" + str(Emin) + \", max: \" \n                    + str(Emax) + \", interval \" + str(self.dE)\n                    + \".\")\n        nprint(\"\\n Total \" + str(len(EE)) + \" energy point(s) \" \n                    + \"running on \" + str(self.workers.N()) + \" CPU(s): \" \n                    + str(int(round(len(EE)/self.workers.N()))) + \" pts/CPU ... \\n\")\n                                \n        # Set energy\n        self.rgf.E(EE)\n\n        # Run the simulation\n        if (self.DryRun == False):\n            self.rgf.run()\n        nprint(\"\\n  done.\")\n        \n        nprint(\"\\n Saving results to disk ...\")\n        # save results\n        if (self.workers.IAmMaster()):\n            # Create directory if not exist.\n            if not os.path.exists(self.OutPath):\n                os.makedirs(self.OutPath)            \n            # save results to file.\n            if (self.DryRun == False):\n                fo = open(self.OutPath + fileName + \".dat\", \"wt\")\n                fo.close()\n                self.rgf.save(self.OutPath + fileName + \".dat\")            \n\n        nprint(\" done.\\n\")\n        nprint(\" ------------------------------------------------------------------\")\n    \n    def run(self):\n        \"\"\"Runs the sumulation.\"\"\"\n\n        self.clock.tic()\n        \n        nprint(\"\\n\\n Starting simulation ...\")\n\n        # Print simulation info\n        nprint(self.staticnstr())\n        eprint(self.debugstr())\n             \n        if (self.check() == False):\n            raise error(\" ERROR: Check failed !!!\")        \n        \n        # Debug print\n        dprint(\"\\n\" + str(self.VDD))\n        dprint(\"\\n\" + str(self.VGG))\n\n        # save simulation parameters\n        if (self.workers.IAmMaster()):\n            # Create directory if not exist.\n            if not os.path.exists(self.OutPath):\n                os.makedirs(self.OutPath)            \n            # save simulation parameters to a pickle file\n            fp = open(self.OutPath + self.OutFileName + \".pkl\", 'wb')\n            pk.dump(self, fp)\n            fp.close()                        \n\n        # Save electrostatic geometry\n        if (self.verbosity >= vprint.MSG_DEBUG):\n            if (self.workers.IAmMaster()):\n                # Create directory if not exist.\n                if not os.path.exists(self.OutPath):\n                    os.makedirs(self.OutPath) \n                self.V.exportSvg(self.OutPath + self.DebugGeomFile)\n        \n        # Configure the RGF solver\n        if self.kp.N == 0: # without k-loop\n            self.rgf = CohRgfLoop(self.workers, self.nb, self.kT, self.ieta,  \n                    self.OrthoBasis)\n        else:# with k-loop\n            self.rgf = CohRgfLoop(self.workers, self.nb, self.kT, self.ieta,  \n                    self.OrthoBasis, 2)\n\n        # Setup H and S \n        if (self.DevType == self.COH_RGF_UNI):        # for uniform RGF blocks\n\n            for ib in range(0, self.nb+1):            # setup the block hamiltonian\n                if self.kp.N == 0: # no k-loop\n                    if (ib != self.nb):\n                        self.rgf.H0(self.H0, ib)          # H0: 0 to N+1\n                        self.rgf.S0(self.S0, ib)          # S0: 0 to N+1\n                    self.rgf.Hl(self.Hl, ib)              # Hl: 0 to N+2\n                    \n                else: # we have k-loop, add transverse neighbors\n                    self.rgf.k(self.kp.kp)                      # set k-points\n                    if (ib != self.nb):\n                        self.rgf.H0(self.H0[0], ib, 0)          # H0_i,i: 0 to N+1 \n                        self.rgf.H0(self.H0[1], ib, 1)          # H0_i,i+1: 0 to N+1\n                        self.rgf.H0(self.H0[2], ib, 2)          # H0_i,i-1: 0 to N+1\n                        self.rgf.S0(self.S0[0], ib, 0)          # S0_i,i: 0 to N+1\n                        self.rgf.pv0(self.pv[0], ib, 0)\n                        self.rgf.pv0(self.pv[1], ib, 1)\n                        self.rgf.pv0(self.pv[2], ib, 2)\n                    self.rgf.Hl(self.Hl[0], ib, 0)              # Hl_i,i: 0 to N+2\n                    self.rgf.Hl(self.Hl[1], ib, 1)              # Hl_i,i: 0 to N+2\n                    self.rgf.Hl(self.Hl[2], ib, 2)              # Hl_i,i: 0 to N+2\n                    self.rgf.pvl(self.pvl[0], ib, 0)\n                    self.rgf.pvl(self.pvl[1], ib, 1)\n                    self.rgf.pvl(self.pvl[2], ib, 2)                \n                    \n        elif (self.DevType == self.COH_RGF_NON_UNI):  # Non-uniform RGF blocks        \n            for ib in range(0, self.nb):                 # setup the block hamiltonian\n                self.rgf.H0(self.H0[ib], ib)             # H0: 0 to N+1=nb-1\n                self.rgf.S0(self.S0[ib], ib)              # S0: just the identity matrix stored in S0(0)\n                if ib > 0:\n                    self.rgf.Hl(self.Hl[ib], ib)     # Hl: 1 to N+1=nb-1\n            self.rgf.Hl(self.Hl[0], 0)               # Hl(0) = H_0,-1\n            self.rgf.Hl(self.Hl[ib+1], ib+1)           # Set H_N+2,N+1 = H_N+1,N\n        # Clean up unused memory; we alredy have copies of these variables\n        # in self.rgf.\n        self.H0 = None\n        self.Hl = None\n        self.S0 = None\n        self.Sl = None\n\n        # Enable calculations\n        for type, value in self.Calculations.items():\n            # transmission\n            if (type == \"TE\"):\n                self.rgf.enableTE(value)\n            # current\n            if (type == \"I\"):\n                if (isinstance( value, int)):\n                    self.rgf.enableI(value, 0, 1)\n                else:\n                    for I in self.Calculations[\"I\"]:\n                        if (\"Block\" in I and I[\"Block\"] == \"All\"):\n                            for ib in range(0, self.nb-1):\n                                self.rgf.enableI(I[\"N\"], ib, ib+1)\n                        else:\n                            self.rgf.enableI(I[\"N\"], I[\"From\"], I[\"To\"])\n            if (type == \"DOS\"):\n                self.rgf.enableDOS(value)\n            if (type == \"n\"):\n                if (isinstance( value, int)):\n                    self.rgf.enablen(value)\n                else:\n                    for n in self.Calculations[\"n\"]:\n                        if (n[\"Block\"] == \"All\"):\n                            for ib in range(1, self.nb-1):\n                                self.rgf.enablen(n[\"N\"], ib)                    \n                        else:\n                            self.rgf.enablen(n[\"N\"], n[\"Block\"])\n        if hasattr(self, \"atomsTracedOver\"):\n            self.rgf.atomsTracedOver(self.atomsTracedOver);\n    \n        # Loop over drain and gate bias\n        for VDD in self.VDD:\n            for VGG in self.VGG:\n                self.runBiasStep(VGG, self.Vo, VDD)\n                pass\n        self.clock.toc()           \n        nprint(\"\\n\" + str(self.clock) + \"\\n\")\n \n    def updateBoundingBox(self):\n        \"\"\"Updates the bounding box of atomistic geometry.\"\"\"\n        # Just to make sure that no point of gate regions is    \n        # at the border\n        a = self.hp.a\n        delta = a*7.0/220.0\n        self.xmn = self.geom.xmin - delta   \n        self.xmx = self.geom.xmax + delta\n        self.ymn = self.geom.ymin - delta\n        self.ymx = self.geom.ymax + delta        \n        \n    def __str__(self):\n        msg = self.staticnstr()\n        msg += self.dynamicnstr()\n        return msg\n    \n    def staticnstr(self):\n        msg = \"\\n Transport simulation parameters:\"\n        \n        msg += \"\\n  Device geometry:\"\n        msg += \"\\n  ---------------------------------------------\"\n        msg += \"\\n  ... |-1 | 0 | 1 |   ...  | \" + str(self.nb-2) + \" | \" + str(self.nb-1) + \" | \" + str(self.nb) + \" | ...\"\n        msg += \"\\n  ---------------------------------------------\"\n        msg += \"\\n            ^  <-------^------->  ^\"\n        msg += \"\\n          left       Device     right\"\n        msg += \"\\n        contact                contact\"\n        \n        # Bias information\n        msg += \"\\n Bias: \"\n        msg += \"\\n  VDD: min \" + str(min(self.VDD)) + \", max \" + str(max(self.VDD)) \n        msg += \", number \" + str(len(self.VDD))\n        msg += \"\\n  VGG: min \" + str(min(self.VGG)) + \", max \" + str(max(self.VGG)) \n        msg += \", number \" + str(len(self.VGG))\n        msg += \"\\n  Vo: \" + str(self.Vo)\n        \n        # Device information\n        msg += \"\\n Device:\"\n        msg += \"\\n  Lengh: \" + str(self.geom.xl) + \"(\" + str(self.geom.xl/10.0) + \" nm)\"\n        msg += \", Width: \" +  str(self.geom.yl) + \"(\" + str(self.geom.yl/10.0) + \" nm)\"\n        msg += \", Height: \" + str(self.geom.zl)+ \"(\" + str(self.geom.zl/10.0) + \" nm)\"\n        msg += \"\\n  Num of atoms: \" + str(self.geom.NumOfAtoms) \n        msg += \", Num of orbitals: \" +  str(self.geom.NumOfOrbitals)\n        \n        # Print Hamiltonian parameters.\n        msg += \"\\n\"\n        msg += str(self.hp)\n       \n        # Calculations to perform\n        msg += \" Calculations:\\n\"\n        for type, value in self.Calculations.items():\n            if (type == \"TE\"):\n                msg += \"  Transmission.\\n\"\n            if (type == \"I\"):\n                if (isinstance( value, int)):\n                    msg += \"  Current at left contact\"\n                    msg += \" (\" + str(I[\"N\"]) + \").\\n\"\n                else:\n                    for I in self.Calculations[\"I\"]:\n                        if (\"Block\" in I and I[\"Block\"] == \"All\"):\n                            msg += \"  Current of all blocks\"\n                            msg += \" (\" + str(I[\"N\"]) + \").\\n\"\n                        else:\n                            msg += \"  Current from block # \" + str(I[\"From\"])\n                            msg += \" to block # \" + str(I[\"To\"]) \n                            msg += \" (\" + str(I[\"N\"]) + \").\\n\"\n            if (type == \"n\"):\n                if (isinstance( value, int)):\n                    msg += \"  Electron density of the device\"\n                    msg += \" (\" + str(n[\"N\"]) + \").\\n\"\n                else:\n                    for n in self.Calculations[\"n\"]:\n                        if (n[\"Block\"] == \"All\"):\n                            msg += \"  Electron density of all blocks\"\n                            msg += \" (\" + str(n[\"N\"]) + \").\\n\"\n                        else:\n                            msg += \"  Electron density of block # \" + str(n[\"Block\"])\n                            msg += \" (\" + str(n[\"N\"]) + \").\\n\"\n                \n        msg += \"  Save output at: \" + self.OutPath + self.OutFileName + \"*\\n\"\n                    \n        # End of info section\n        msg += \" ------------------------------------------------------------------\"\n        \n        return msg\n    \n    def dynamicnstr(self):\n        # NEGF parameters\n        msg = str(self.rgf)\n        # Electrostatics\n        msg += \"\\n\"\n        msg += str(self.V)\n\n        return msg\n \n\n    def debugstr(self):\n        msg = \" Debugging information: \\n\"\n        msg = \"  Atomic structure: \\n\"\n        msg += str(self.geom)\n        msg += \" ------------------------------------------------------------------\"\n        return msg\n        \n    def __getstate__(self):\n        dct = dict(self.__dict__)\n        del dct['workers']\n        del dct['clock']\n        del dct['kp']\n        #del dct['H0']\n        #del dct['Hl']\n        #del dct['S0']\n        #del dct['Sl']\n        #del dct['geom']\n        #del dct['rgf']\n        return dct\n    \n    def __setstate__(self, dct):\n        self.__dict__.update(dct)\n        \n\"\"\"\n Loads and returns a Transport object from pickle file\n\"\"\"\ndef loadTransport(fileName):\n    pf = open(fileName)\n    tr = pk.load(pf)\n    pf.close()\n    return tr\n\n\n\n\n\n\n", "meta": {"hexsha": "0c5cf5e108444ebd00e5e47a8c8da2998ba71f69", "size": 29929, "ext": "py", "lang": "Python", "max_stars_repo_path": "simulators/python/dirackp/Transport.py", "max_stars_repo_name": "masumhabib/quest", "max_stars_repo_head_hexsha": "afef1166b361236144be83f07303a3ec0d5c187c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-04-04T20:57:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-23T02:08:22.000Z", "max_issues_repo_path": "simulators/python/dirackp/Transport.py", "max_issues_repo_name": "masumhabib/quest", "max_issues_repo_head_hexsha": "afef1166b361236144be83f07303a3ec0d5c187c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2016-10-06T03:00:24.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-30T06:43:32.000Z", "max_forks_repo_path": "simulators/python/dirackp/Transport.py", "max_forks_repo_name": "masumhabib/quest", "max_forks_repo_head_hexsha": "afef1166b361236144be83f07303a3ec0d5c187c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-10-03T04:09:25.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-03T04:09:25.000Z", "avg_line_length": 37.980964467, "max_line_length": 181, "alphanum_fraction": 0.4582177821, "include": true, "reason": "import numpy", "num_tokens": 7530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.19175669058256567}}
{"text": "#!/usr/bin/python3\n\n\"\"\"Read .out files from ORCA IRC calculations and create graphs.\"\"\"\n\nimport argparse\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.constants import calorie\nfrom scipy.constants import kilo\nfrom scipy.constants import N_A\nfrom scipy.constants import physical_constants\nfrom scipy import interpolate\n\nfrom rmsd import calc_rmsd\nfrom rmsd import read_xyz\n\nhartree, _, _ = physical_constants[\"Hartree energy\"]\n\n\ndef main():\n    \"\"\"Run main procedure.\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"out_file\", type=argparse.FileType(\"r\"), default=\"-\")\n    parser.add_argument(\"--classic\", action=\"store_true\")\n    args = parser.parse_args()\n\n    irc = False\n    data = []\n    for line in args.out_file:\n        if \"Step        E(Eh)      dE(kcal/mol)  max(|G|)   RMS(G)\" in line:\n            irc = True\n        elif irc:\n            line = line.strip()\n            if line:\n                fields = line.split()\n                data.append([float(x) for x in fields[:5]])\n                if len(fields) > 5 and fields[5] == \"<=\":\n                    ts_step = int(data[-1][0]) - 1  # first step is one\n            else:\n                break\n\n    try:\n        coords = read_xyz(args.out_file.name.replace(\".out\", \"_TSOpt_IRC_Full_trj.xyz\"))[2]\n    except ValueError:\n        coords = read_xyz(args.out_file.name.replace(\".out\", \"_IRC_Full_trj.xyz\"))[2]\n\n    rmsd = [0.0]\n    for i in range(1, len(coords)):\n        rmsd.append(rmsd[-1] + calc_rmsd(coords[i - 1], coords[i]))\n    rmsd = np.array(rmsd)\n\n    data = np.array(data)\n    # xi = (data[:, 0] - data[:, 0].min()) / data[:, 0].max()\n    xi = rmsd\n    y = data[:, 1] - data[:, 1].min()\n\n    forward_barrier = y.max() - y[0]\n    backward_barrier = y.max() - y[-1]\n    print(\n        f\"forward barrier  = {forward_barrier:6.4f} Eh = {forward_barrier * hartree * N_A / kilo:5.1f} kJ/mol = {forward_barrier * hartree * N_A / (kilo * calorie):5.1f} kcal/mol\"\n    )\n    print(\n        f\"backward barrier = {backward_barrier:6.4f} Eh = {backward_barrier * hartree * N_A / kilo:5.1f} kJ/mol = {backward_barrier * hartree * N_A / (kilo * calorie):5.1f} kcal/mol\"\n    )\n\n    if not args.classic:\n        xi_new = np.linspace(xi.min(), xi.max(), 10000)\n\n        # points = ~np.isclose(xi, xi[ts_step])\n        # f = interpolate.InterpolatedUnivariateSpline(xi[points], y[points])\n        f = interpolate.InterpolatedUnivariateSpline(xi, y, k=4)\n        fp = f.derivative()\n        fpp = f.derivative(n=2)\n\n        plt.subplot(311)\n    else:\n        plt.subplot(211)\n\n    plt.plot(xi, y, \"o\", label=\"calculated\")\n    plt.vlines(xi[ts_step], y.min(), y.max())\n    plt.xlabel(r\"IRC ($\\xi$)\")\n    plt.ylabel(r\"Potential Energy, V($\\xi$) [Eh]\")\n\n    if not args.classic:\n        # add interpolation\n        pass\n        plt.plot(xi_new, f(xi_new), \"--\", label=\"interpolated\")\n        plt.legend()\n\n        plt.subplot(312)\n        rf = -fp(xi_new)\n        plt.plot(xi_new, rf, \"--\")\n        plt.vlines(xi[ts_step], rf.min(), rf.max())\n        plt.xlabel(r\"IRC ($\\xi$)\")\n        plt.ylabel(r\"Reaction Force, F($\\xi$) [Eh/$\\Delta\\xi$]\")\n\n        # TODO(schneiderfelipe): get max and min force along the coordinate\n        # and do the usual analysis\n        plt.subplot(313)\n        rfc = fpp(xi_new)\n        plt.plot(xi_new, rfc, \"--\")\n        plt.vlines(xi[ts_step], rfc.min(), rfc.max())\n        plt.xlabel(r\"IRC ($\\xi$)\")\n        plt.ylabel(r\"Reaction Force Constant, $\\kappa$($\\xi$) [Eh/$\\Delta\\xi^2$]\")\n    else:\n        plt.subplot(212)\n        plt.plot(xi, data[:, 3], \"o\", label=\"max(|G|)\")\n        plt.vlines(xi[ts_step], 0, data[:, 3].max())\n        plt.plot(xi, data[:, 4], \"o\", label=\"RMS(G)\")\n        plt.xlabel(r\"IRC ($\\xi$)\")\n        plt.ylabel(r\"Gradient, G($\\xi$) [Eh/Bohr]\")\n        plt.legend()\n\n    # plt.tight_layout()\n    plt.show()\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "1ad135d15f1ff5360272a04517585d949988d65e", "size": 3886, "ext": "py", "lang": "Python", "max_stars_repo_path": "irc.py", "max_stars_repo_name": "schneiderfelipe/scripts", "max_stars_repo_head_hexsha": "43bb3d02d0b043f80a4840f4cc222944aad683c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "irc.py", "max_issues_repo_name": "schneiderfelipe/scripts", "max_issues_repo_head_hexsha": "43bb3d02d0b043f80a4840f4cc222944aad683c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "irc.py", "max_forks_repo_name": "schneiderfelipe/scripts", "max_forks_repo_head_hexsha": "43bb3d02d0b043f80a4840f4cc222944aad683c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1157024793, "max_line_length": 182, "alphanum_fraction": 0.5717961915, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.19175668531333312}}
{"text": "#!/usr/bin/env python\n\n# ----------------------------------------------------------------------------\n# Copyright (c) 2015--, The WGS-HGT Development Team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n# ----------------------------------------------------------------------------\n\n# Implement Distance Method for HGT detection based on algorithm described\n#    in:\n#        Wei. X et al., \"A Distance-Based Method for Detecting HGT in Whole\n#        Genomes\", International Symposium on Bioinformatics Research and\n#        Applications (ISBRA), 2008, pages 26-37\n#\n#    The workflow follows the algorithm:\n#    1. For each gene in target genome,\n#        i.    BLAST sequence against all other genes in the reference\n#              genomes;\n#        ii.   Go to step 3 if gene has more than threshold number of homologs\n#              (min-num-homologs), otherwise go to next gene in target genome;\n#        iii.  Compute multiple sequence alignment on homolog genes using\n#              CLUSTAL;\n#        iv.   Compute pairwise distance matrix using PHYLIP's protdist\n#              function and Z-score normalize the set of pairwise distances\n#              for each gene family and species;\n#        v.    Add distance matrix for all pairwise distances into global\n#              distance matrix storing results for all genes\n#\n#    2. Cluster gene families by species,\n#        vi.   Compute all species sets (sets of genes whose orthologs are\n#              detectable in exactly the same subset of the considered\n#              species);\n#        vii.  Cluster genes to each core species set cluster using the\n#              Hamming distance clustering algorithm;\n#        viii. Run outlier detection algorithm on each cluster (paragraph 2\n#              of section 'Detecting Outlier Genes' in original paper)\n#\n#    Requires protdist version 3.696\n#\n\nimport sys\nimport click\nimport numpy\nimport operator\nimport threading\nimport subprocess\nimport traceback\nimport shlex\nfrom os.path import join, basename, isdir, exists, getsize\nfrom os import mkdir\n\nfrom glob import glob\n\nimport skbio.io\n\n\nclass Command(object):\n    \"\"\"Run subprocess commands in a different thread with TIMEOUT option.\n\n    Based on jcollado's solution:\n    http://stackoverflow.com/questions/1191374/subprocess-with-timeout/4825933#4825933\n    https://gist.github.com/kirpit/1306188\n    \"\"\"\n    process = None\n    status = None\n    output, error = '', ''\n\n    def __init__(self, command):\n        if isinstance(command, str):\n            command = shlex.split(command)\n        self.command = command\n\n    def run(self, timeout=None, **kwargs):\n        \"\"\" Run a command then return: (status, output, error). \"\"\"\n        def target(**kwargs):\n            try:\n                self.process = subprocess.Popen(self.command, **kwargs)\n                self.output, self.error = self.process.communicate()\n                self.status = self.process.returncode\n            except subprocess.CalledProcessError:\n                self.error = traceback.format_exc()\n                self.status = -1\n        # default stdout and stderr\n        if 'stdout' not in kwargs:\n            kwargs['stdout'] = subprocess.PIPE\n        if 'stderr' not in kwargs:\n            kwargs['stderr'] = subprocess.PIPE\n        # thread\n        thread = threading.Thread(target=target, kwargs=kwargs)\n        thread.start()\n        thread.join(timeout)\n        if thread.is_alive():\n            self.process.terminate()\n            thread.join()\n        return self.status, self.output, self.error\n\n\ndef hamming(str1, str2):\n    \"\"\"Compute the Hamming distance between two strings.\n\n    Parameters\n    ----------\n    str1: string\n        string\n    str2: string\n        string\n    \"\"\"\n    assert len(str1) == len(str2)\n    return sum(map(operator.ne, str1, str2))\n\n\ndef preprocess_data(working_dir,\n                    target_proteomes_dir,\n                    extensions,\n                    verbose=False):\n    \"\"\" Map each gene to sudo name (ex. 1_1 for species 1, gene 1).\n\n    Parameters\n    ----------\n    working_dir:  string\n        path to working directory\n    target_proteomes_dir: string\n        path to directory holding proteomes for all target organisms\n    extensions: list\n        list of extensions for reference proteomes\n    verbose: boolean, optional\n        output details about the running processes of this function\n\n    Returns\n    -------\n    gene_map: dictionary\n        \"two-way\" dictionary storing gene names as keys and their pseudo\n        names as values, and vica versa\n    ref_db: dictionary\n        dictionary storing FASTA label as key and sequence as value for the\n        reference databases\n    species: integer\n        the number of species in the reference databases\n\n    Notes\n    -----\n        This will facilitate easier output comparison and the 10 character\n        name limitation in PHYLIP output. This format is limited up to 9999\n        species and 99999 genes per species.\n    \"\"\"\n    gene_map = {}\n    ref_db = {}\n    if verbose:\n        sys.stdout.write(\"Target organism\\tNumber of genes\\n\")\n    # each file contains genes for species\n    files = [f\n             for ext in extensions\n             for f in glob(\"%s/*%s\" % (target_proteomes_dir, ext))]\n    for species, _file in enumerate(files):\n        if verbose:\n            sys.stdout.write(\"%s. %s\\t\" % (\n                species+1, basename(_file)))\n        for gene, seq in enumerate(skbio.io.read(_file, format='fasta')):\n            label = seq.metadata['id']\n            ref_db[label] = seq\n            sudo_label = \"%s_%s\" % (species, gene)\n            if label in gene_map:\n                raise ValueError(\"Duplicate sequence labels are \"\n                                 \"not allowed: %s\" % label)\n            gene_map[label] = sudo_label\n            gene_map[sudo_label] = label\n        if verbose:\n            sys.stdout.write(\"%s\\n\" % gene)\n    return gene_map, ref_db, species+1\n\n\ndef launch_diamond(query_proteome_fp,\n                   ref_fp,\n                   working_dir,\n                   tmp_dir,\n                   e_value=10e-20,\n                   threads=1,\n                   debug=False):\n    \"\"\" Launch DIAMOND for a query and a reference database of proteomes.\n\n    Parameters\n    ----------\n    query_proteome_fp: string\n      filepath to query proteome\n    ref_fp: string\n      filepath to reference proteome\n    working_dir: string\n      working directory path\n    tmp_dir:\n      temporary working directory for DIAMOND\n    e_value: float, optional\n      the cutoff E-value for BLASTP results\n    threads: integer\n      number of threads to use for running DIAMOND BLASTP\n    debug: boolean\n      if True, run function in debug mode\n\n    Returns\n    -------\n    out_file_fp: string\n      filepath to tabular alignment file output by DIAMOND\n    \"\"\"\n    db_file_fp = join(working_dir, \"%s\" % basename(ref_fp))\n    # build DIAMOND database\n    makediamonddb_command = [\"diamond\",\n                             \"makedb\",\n                             \"--in\", ref_fp,\n                             \"-d\", db_file_fp,\n                             \"--threads\", str(threads)]\n    proc = subprocess.Popen(makediamonddb_command,\n                            stdout=subprocess.PIPE,\n                            stderr=subprocess.PIPE,\n                            close_fds=True)\n    proc.wait()\n    stdout, stderr = proc.communicate()\n    if (stderr and debug):\n        print(\"[DEBUG] %s\\n\" % stderr)\n\n    # launch DIAMOND\n    out_file_fp = join(\n        working_dir, \"%s.daa\" % basename(query_proteome_fp))\n    diamond_command = [\"diamond\",\n                       \"blastp\",\n                       \"-t\", tmp_dir,\n                       \"--db\", \"%s.dmnd\" % db_file_fp,\n                       \"--query\", query_proteome_fp,\n                       \"--evalue\", str(e_value),\n                       \"--threads\", str(threads),\n                       \"--daa\", out_file_fp,\n                       \"--sensitive\"]\n    proc = subprocess.Popen(diamond_command,\n                            stdout=subprocess.PIPE,\n                            stderr=subprocess.PIPE,\n                            close_fds=True)\n    proc.wait()\n    stdout, stderr = proc.communicate()\n    if (stderr and debug):\n        print(\"[DEBUG] %s\\n\" % stderr)\n\n    # convert output to tab delimited file\n    out_file_conv_fp = join(\n        working_dir, \"%s.m8\" % basename(query_proteome_fp))\n    diamond_convert_command = [\"diamond\",\n                               \"view\",\n                               \"--daa\", out_file_fp,\n                               \"-f\", \"tab\",\n                               \"-o\", out_file_conv_fp]\n    proc = subprocess.Popen(diamond_convert_command,\n                            stdout=subprocess.PIPE,\n                            stderr=subprocess.PIPE,\n                            close_fds=True)\n    proc.wait()\n    stdout, stderr = proc.communicate()\n    if (stderr and debug):\n        print(\"[DEBUG] %s\\n\" % stderr)\n\n    return out_file_conv_fp\n\n\ndef launch_blast(query_proteome_fp,\n                 ref_fp,\n                 working_dir,\n                 e_value=10e-20,\n                 threads=1,\n                 debug=False):\n    \"\"\" Launch BLASTp for a query and a reference database of proteomes.\n\n    Parameters\n    ----------\n    query_proteome_fp: string\n      filepath to query proteome\n    ref_fp: string\n      filepath to reference proteome\n    working_dir: string\n      working directory path\n    e_value: float, optional\n      the cutoff E-value for BLASTP results\n    threads: integer\n      number of threads to use for running BLASTP\n    debug: boolean\n      if True, run function in debug mode\n\n    Returns\n    -------\n    out_file_fp: string\n      filepath to tabular alignment file output by\n      BLASTP\n    \"\"\"\n    db_file_fp = join(working_dir, \"%s\" % basename(ref_fp))\n    # build blast database\n    makeblastdb_command = [\"makeblastdb\",\n                           \"-in\", ref_fp,\n                           \"-out\", db_file_fp,\n                           \"-dbtype\", \"prot\"]\n    proc = subprocess.Popen(makeblastdb_command,\n                            stdout=subprocess.PIPE,\n                            stderr=subprocess.PIPE,\n                            close_fds=True)\n    proc.wait()\n    stdout, stderr = proc.communicate()\n    if (stderr and debug):\n        print(\"[DEBUG] %s\\n\" % stderr)\n\n    # launch blast\n    out_file_fp = join(\n        working_dir, \"%s.blast\" % basename(query_proteome_fp))\n    blastp_command = [\"blastp\",\n                      \"-db\", db_file_fp,\n                      \"-query\", query_proteome_fp,\n                      \"-evalue\", str(e_value),\n                      \"-num_threads\", str(threads),\n                      \"-outfmt\", \"6 std qcovs\",\n                      \"-task\", \"blastp\",\n                      \"-out\", out_file_fp]\n    proc = subprocess.Popen(blastp_command,\n                            stdout=subprocess.PIPE,\n                            stderr=subprocess.PIPE,\n                            close_fds=True)\n    proc.wait()\n    stdout, stderr = proc.communicate()\n    if (stderr and debug):\n        print(\"[DEBUG] %s\\n\" % stderr)\n\n    return out_file_fp\n\n\ndef parse_blast(alignments_fp,\n                hits,\n                gene_map,\n                debug=False):\n    \"\"\" Parse BLASTp alignment file into a dictionary.\n\n    Parameters\n    ----------\n    alignments_fp: string\n      filepath to tabular alignment file output by BLASTP\n    hits: dictionary\n      dictionary storing query (gene) names as keys and the best aligning\n      reference sequences as values (one alignment per reference sequence)\n    gene_map: dictionary\n      \"two-way\" dictionary storing gene names as keys and their pseudo\n      names as values, and vica versa\n    debug: boolean\n      if True, run function in debug mode\n\n    Notes\n    -----\n        The keys are the queries and the values are all the reference\n        sequences to which the query mapped with E-value cutoff score.\n    \"\"\"\n    # read blastp results\n    with open(alignments_fp, 'r') as alignments_f:\n        for line in alignments_f:\n            if debug:\n                sys.stdout.write(\"[DEBUG] %s\" % line)\n            query, ref = line.split()[:2]\n            if query not in hits:\n                hits[query] = [ref]\n            else:\n                # check that the query mapped to a different species\n                # since we only want the best homolog per species\n                if gene_map[ref].split('_')[0] not in [\n                        gene_map[gene].split('_')[0] for gene in hits[query]]:\n                    hits[query].append(ref)\n\n\ndef launch_msa(fasta_in_fp,\n               clustal_command_fp,\n               gene_map,\n               ref_db,\n               hits,\n               query,\n               timeout):\n    \"\"\" Create MSA for all gene othologs using Clustalw.\n\n    Parameters\n    ----------\n    fasta_in_fp: string\n      filepath to FASTA file of protein sequences to use as input to\n      Clustalw\n    clustal_command_fp: string\n      filepath to Clustalw command (interactive)\n    gene_map: dictionary\n      \"two-way\" dictionary storing gene names as keys and their pseudo\n      names as values, and vica versa\n    ref_db: dictionary\n      dictionary storing FASTA label as key and sequence as value for the\n      reference databases\n    hits: dictionary\n      dictionary storing query (gene) names as keys and the best aligning\n      reference sequences as values (one alignment per reference sequence)\n    query: string\n      query gene name\n    timeout: integer\n      number of seconds to allow Clustalw to run before terminating the\n      process\n    \"\"\"\n    with open(fasta_in_fp, 'w') as in_f:\n        for ref in hits[query]:\n            in_f.write(\">%s\\n%s\\n\" % (gene_map[ref], ref_db[ref]))\n\n    with open(clustal_command_fp, 'r') as clustal_command_f:\n        clustalw_command = Command(\"clustalw\")\n        status, output, error = clustalw_command.run(\n            timeout=timeout,\n            stdin=clustal_command_f,\n            close_fds=True)\n        if status < 0:\n            sys.stdout.write(\n                \"status: %s\\noutput: %s\\terror: %s\\t\" % (\n                    status, output, error))\n\n\ndef compute_distances(phylip_command_fp,\n                      warnings=False):\n    \"\"\" Compute distances between each pair of sequences in the MSA.\n\n    Parameters\n    ----------\n    phylip_command_fp: string\n      filepath to the PHYLIP command (interactive)\n    warnings: boolean, optional\n      print warnings output by PHYLIP\n\n    Notes\n    -----\n        Use PHYLIP's protdist function.\n    \"\"\"\n    with open(phylip_command_fp, 'r') as phylip_command_f:\n        proc = subprocess.Popen(\"protdist\",\n                                stdin=phylip_command_f,\n                                stdout=subprocess.PIPE,\n                                stderr=subprocess.PIPE,\n                                close_fds=True)\n        proc.wait()\n        stdout, stderr = proc.communicate()\n        if stderr and warnings:\n            print(stderr)\n\n\ndef normalize_distances(phylip_fp,\n                        full_distance_matrix,\n                        num_species,\n                        full_distance_matrix_offset,\n                        species_set_dict,\n                        gene_bitvector_map,\n                        debug=False):\n    \"\"\" Parse and normalize the output file of PHYLIP's protdist function.\n\n    Parameters\n    ----------\n    phylip_fp: string\n        filepath to distance matrix output by PHYLIP's protdist function\n    full_distance_matrix: dictionary\n        complete distance matrix for pairwise alignments between all species\n        for every gene\n    num_species: integer\n        number of species in the reference database\n    full_distance_matrix_offset: integer\n        the index offset for elements in full_distance_matrix where to write\n        the next array\n    species_set_dict: dictionary\n        dictionary containing the binary indicator vectors as keys and the\n        number of genes with identical species set represented by the binary\n        vectors as values\n    gene_bitvector_map: list\n        list containing the binary indicator vector for each query gene\n    debug: boolean\n        if True, run function in debug mode\n\n    Notes\n    -----\n        Parse PHYLIP's protdist output containing the distance matrix, Z-score\n        normalize the set of pairwise distances between the gene in a species\n        and all other species and stores the results in a separate array.\n\n        Each normalized distance matrix is then sorted by species name and\n        added to the complete array storing distance matrices for all genes.\n        In addition, a list of missing species (species which did not include\n        a certain gene) is also maintained and used for setting nan's in array\n        cells which represent those species.\n\n        Below is an example of a parsed distance matrix\n        for 3 genes and 3 species:\n            0         1         2        (genes)\n        0_0 nan       nan       nan\n        0_1 0.53099   0.878855  0.83673\n        0_2 0.642856  1.083039  1.083039\n        1_0 0.300297  0.300297  0.702003\n        1_1 nan       nan       nan\n        1_2 0.399722  0.379156  0.356543\n        2_0 0.53099   0.53099   0.83673\n        2_1 0.399722  0.399722  0.356543\n        2_2 nan       nan       nan\n\n        (species pairs)\n\n        Example of Z-score normalized distance matrix from\n        above:\n            0            1           2          (genes)\n        0_0 nan          nan         nan\n        0_1 -1.40548346  0.83861735  0.56686611\n        0_2 -1.41421356  0.70710678  0.70710678\n        1_0 -0.70710678 -0.70710678  1.41421356\n        1_1 nan          nan         nan\n        1_2 1.20493966   0.03869341 -1.24363308\n        2_0 -0.70710678 -0.70710678  1.41421356\n        2_1 0.70710678   0.70710678 -1.41421356\n        2_2 nan          nan         nan\n\n        (species pairs)\n    \"\"\"\n    # assume a pairwise alignment exists for all species\n    missing_species = [str(x) for x in range(0, num_species)]\n    # scan through file and remove species that exist\n    # from missing_species list\n    if exists(phylip_fp) and getsize(phylip_fp) > 0:\n        with open(phylip_fp, 'r') as phylip_f:\n            next(phylip_f)\n            for line in phylip_f:\n                if not line.startswith(' '):\n                    species = line.split()[0].split('_')[0]\n                    missing_species.remove(species)\n    else:\n        raise ValueError('%s does not exist or is empty' % phylip_fp)\n\n    # scan through file again, collecting alignment\n    # distances\n    orig_order_labels = []\n    p = numpy.empty(shape=(num_species, num_species))\n    p.fill(numpy.nan)\n    idx = 0\n    with open(phylip_fp, 'r') as phylip_f:\n        alignment_list = []\n        # skip first line containing number of lines in\n        # the file\n        next(phylip_f)\n        for line in phylip_f:\n            if debug:\n                sys.stdout.write(\"[DEBUG] %s\" % line)\n            alignment_dist = line.strip().split()\n            if line.startswith(' '):\n                alignment_list.extend(alignment_dist)\n            else:\n                # new species alignment pairs\n                if alignment_list:\n                    for i in range(0, len(missing_species)):\n                        alignment_list.append(None)\n                    a = numpy.asarray(alignment_list[1:], dtype=float)\n                    a[idx] = numpy.nan\n                    p[idx] = (a - numpy.nanmean(a)) / numpy.nanstd(a)\n                    idx += 1\n                    orig_order_labels.append(alignment_list[0])\n                alignment_list = alignment_dist\n\n    # add distance on final line\n    for i in range(0, len(missing_species)):\n        alignment_list.append(None)\n    a = numpy.asarray(alignment_list[1:], dtype=float)\n    a[idx] = numpy.nan\n    p[idx] = (a - numpy.nanmean(a)) / numpy.nanstd(a)\n    orig_order_labels.append(alignment_list[0])\n\n    # add the missing species names to the labels array\n    bitvector_gene = 'I' * num_species\n    for species in missing_species:\n        orig_order_labels.append(\"%s_X\" % species)\n        # indicate missing gene for current species\n        x = list(bitvector_gene)\n        x[int(species)] = 'O'\n        bitvector_gene = ''.join(x)\n\n    # update species set counts\n    if bitvector_gene not in species_set_dict:\n        species_set_dict[bitvector_gene] = 1\n    else:\n        species_set_dict[bitvector_gene] += 1\n\n    gene_bitvector_map[full_distance_matrix_offset] = bitvector_gene\n\n    # sort the distance matrix based on species names (S1, S2, S3 ..)\n    # in order to be consistent across all gene families\n    x = numpy.argsort(numpy.array(orig_order_labels))\n\n    # re-order rows and columns by ordered species name (0,1,2 ..)\n    p2 = numpy.zeros(shape=(num_species, num_species))\n    for idx_a, arr in enumerate(p):\n        t = numpy.zeros(shape=num_species)\n        for idx_b, el in enumerate(arr):\n            t[x[idx_b]] = el\n        p2[x[idx_a]] = t\n    del p\n\n    # add normalized distance matrix for current gene\n    # to full distance matrix\n    full_distance_matrix[full_distance_matrix_offset] = p2\n\n\ndef cluster_distances(species_set_dict,\n                      species_set_size,\n                      hamming_distance):\n    \"\"\" Hamming distance clustering algorithm\n\n    Parameters\n    ----------\n    species_set_dict: dictionary\n        dictionary containing the binary indicator vectors as\n        keys and the number of genes with identical species\n        set represented by the binary vectors as values\n    species_set_size: integer\n        threshold number of genes in a species set to\n        allow it to form a core cluster\n    hamming_distance: integer\n        maximum number of mismatches between two binary\n        indicator vectors (ex. IIII and I0II) for the\n        genes in a candidate vector to be merged into the\n        core cluster\n\n    Returns\n    -------\n    gene_clusters_list: list of tuples\n        list of tuples containing core species sets and all belonging species\n        sets (determined by the Hamming distance clustering algorithm)\n\n    Notes\n    -----\n        Cluster gene families by species with detectable orthologs in exactly\n        the same subset of the considered species.\n\n        Ex. Assume we have 4 genes and 5 species with the following distance\n        matrix:\n\n            0             1             2             3\n        0_0 nan           nan           nan           nan\n        0_1 -1.59564844   -1.388031632  -0.9634704748 -1.342272936\n        0_2 -0.4259542606 nan           0.7035215923  1.223837777\n        0_3 -1.55041393   -1.51499567   -0.9634704748 -1.330178178\n        0_4 -0.3659762821 0.8346037464  0.6565725705  1.15274682\n        ..\n        ..\n\n        There are two binary indicator vectors to represent the species\n        present in the four genes: IIIII (gene 0, 2 and 3), II0II (gene 1). If\n        the core set threshold was 3, then there would be 1 core species set\n        represented by IIIII.\n    \"\"\"\n    sorted_species_set = sorted(list(species_set_dict.items()),\n                                key=operator.itemgetter(1), reverse=True)\n    # determine core clusters (initial species sets with more than\n    # species_set_size genes)\n    gene_clusters_list = []\n    # if the largest species set contains less than threshold\n    # (species_set_size) elements, set the only core cluster to the largest\n    # species set\n    if sorted_species_set[0][1] < species_set_size:\n        cluster_core = (sorted_species_set[0][0], [])\n        gene_clusters_list = []\n    for bitvector in sorted_species_set:\n        if bitvector[1] >= species_set_size:\n            cluster_core = (bitvector[0], [])\n            gene_clusters_list.append(cluster_core)\n    # assign species sets with fewer than species_set_size species to core\n    # clusters if the Hamming distance between the two bitvectors is less than\n    # hamming_distance\n    species_set_assigned = []\n    for idx, cluster_core in enumerate(gene_clusters_list):\n        for bitvector in sorted_species_set:\n            bv = bitvector[0]\n            if (bv not in species_set_assigned and\n                    hamming(cluster_core[0], bv) <= hamming_distance):\n                gene_clusters_list[idx][1].append(bv)\n                species_set_assigned.append(bv)\n    # assign the remaining species sets to the cluster with the closest core\n    # Hamming distance\n    for bitvector in sorted_species_set:\n        bv = bitvector[0]\n        if bv not in species_set_assigned:\n            min_hamming_cluster = -1\n            min_hamming_distance = sys.maxsize\n            # find cluster core with smallest Hamming distance to species set\n            for idx, cluster_core in enumerate(gene_clusters_list):\n                dist = hamming(cluster_core[0], bv)\n                if dist < min_hamming_distance:\n                    min_hamming_distance = dist\n                    min_hamming_cluster = idx\n            if min_hamming_cluster >= 0:\n                gene_clusters_list[min_hamming_cluster][1].append(bv)\n\n    return gene_clusters_list\n\n\ndef detect_outlier_genes(species_set,\n                         gene_bitvector_map,\n                         full_distance_matrix,\n                         stdev_offset,\n                         outlier_hgt,\n                         num_species,\n                         total_genes,\n                         debug=False):\n    \"\"\" Detect outlier genes.\n\n    Parameters\n    ----------\n    species_set: list\n        list of bitvectors representing species clusters to use in detecting\n        outlier genes\n    gene_bitvector_map: list\n        list containing the binary indicator vector for each query gene\n    full_distance_matrix: dictionary\n        complete distance matrix for pairwise alignments between all species\n        for every gene\n    stdev_offset: integer\n        the number of standard deviations a gene's normalized distance is from\n        the mean to identify it as an outlier for a species pair\n    outlier_hgt: float\n        the fraction (value between (0,1]) of normalized pairwise distances\n        over all species-pair vectors belonging to the same gene that are\n        z-score standard deviations from the mean\n    num_species: integer\n        number of species in the reference database\n    total_genes: integer\n        total number of genes in the query genome with at least\n        min_num_homologs (determined by BLAST search)\n    debug: boolean\n        if True, run function in debug mode\n\n    Returns\n    -------\n    outlier_genes: set\n        set of atypical genes\n\n    Notes\n    -----\n        Algorithm described in section \"Detecting `Outlier' Genes\" of the Wei.\n        X et al. paper. The full distance matrix is represented in the format:\n\n        full_distance_matrix[#genes][#species][#species] =\n        [[[0_0, 0_1, 0_2, .., 0_n]\n          [1_0, 1_1, 1_2, .., 1_n]\n          ..\n          [n_0, n_1, n_2, .., n_n]]\n\n         [[0_0, 0_1, 0_2, .., 0_n]\n          [1_0, 1_1, 1_2, .., 1_n]\n          ..\n          [n_0, n_1, n_2, .., n_n]]\n\n          ..\n         [[0_0, 0_1, 0_2, .., 0_n]\n          [1_0, 1_1, 1_2, .., 1_n]\n          ..\n          [n_0, n_1, n_2, .., n_n]]]\n\n        The mean and standard deviation are computed for each species pair\n        including all genes.\n    \"\"\"\n    numpy.around(full_distance_matrix, decimals=5, out=full_distance_matrix)\n    outlier_flag_matrix = numpy.zeros(\n        shape=(total_genes, num_species, num_species), dtype=bool)\n    distance_vector = numpy.zeros(total_genes)\n    if debug:\n        sys.stdout.write(\"[DEBUG] species_species\\t\")\n        for k in range(total_genes):\n            sys.stdout.write(\"gene # %s\".ljust(12) % k)\n        sys.stdout.write(\"[low_bound, up_bound]\\n\")\n    for i in range(num_species):\n        for j in range(num_species):\n            if i != j:\n                for k in range(total_genes):\n                    distance_vector[k] = full_distance_matrix[k][i][j]\n                mean = numpy.nanmean(distance_vector)\n                stdev = numpy.nanstd(distance_vector)\n                low_bound = round(mean - stdev_offset*stdev, 5)\n                up_bound = round(mean + stdev_offset*stdev, 5)\n                if debug:\n                    sys.stdout.write(\"[DEBUG] %s_%s\\t\".ljust(20) % (i, j))\n                for k, distance in enumerate(distance_vector):\n                    spaces = \"\".ljust(2)\n                    if distance < 0:\n                        spaces = \"\".ljust(1)\n                    if (distance != numpy.nan and\n                       ((distance < low_bound) or (distance > up_bound))):\n                        outlier_flag_matrix[k][i][j] = 1\n                        if debug:\n                            sys.stdout.write(\n                                \"%s\\033[92m%s\\033[0m\" % (spaces, distance))\n                    elif debug:\n                        sys.stdout.write(\"%s%s\" % (spaces, distance))\n                if debug:\n                    sys.stdout.write(\"\\t[%s, %s]\\n\" % (low_bound, up_bound))\n\n    # traverse outlier_matrix by gene and count the number of outlier\n    # distances by species\n    outlier_count_matrix = numpy.zeros(\n        shape=(total_genes, num_species), dtype=int)\n    for i in range(total_genes):\n        for j in range(num_species):\n            for k in range(num_species):\n                if outlier_flag_matrix[i][j][k]:\n                    outlier_count_matrix[i][k] += 1\n\n    # if number of outlier distances exceeds threshold, label gene as outlier\n    outlier_genes = set()\n    for i in range(total_genes):\n        for j in range(num_species):\n            if outlier_count_matrix[i][j] > num_species*outlier_hgt:\n                outlier_genes.add(i)\n\n    return outlier_genes\n\n\ndef output_full_matrix(matrix, num_species):\n    \"\"\" Output distance matrix to stdout\n    \"\"\"\n    for i in range(num_species):\n        for j in range(num_species):\n            # for gene number\n            for k in range(len(matrix)):\n                sys.stdout.write(\"%s\\t\" % matrix[k][i][j])\n            sys.stdout.write(\"\\n\")\n\n\ndef distance_method(query_proteome_fp,\n                    target_proteomes_dir,\n                    working_dir,\n                    output_hgt_fp,\n                    align_software,\n                    tabular_alignments_fp=None,\n                    ext=['fa', 'fasta', 'faa'],\n                    min_num_homologs=3,\n                    e_value=10e-20,\n                    threads=1,\n                    stdev_offset=2.326,\n                    outlier_hgt=0.5,\n                    species_set_size=30,\n                    hamming_distance=2,\n                    verbose=False,\n                    debug=False,\n                    warnings=False,\n                    timeout=120):\n    \"\"\" Run Distance Method algorithm\n\n    Parameters\n    ----------\n    query_proteome_fp: string\n        filepath to query proteome\n    target_proteomes_dir: string\n        dirpath to target proteomes\n    working_dir: string\n        dirpath to working directory\n    output_hgt_fp: string\n        filepath to output file for storing detected HGTs\n    align_software: string\n        software to use for sequence alignment (BLAST or DIAMOND)\n    tabular_alignments_fp: string, optional\n        filepath to tabular sequence alignments\n    ext: list, optional\n        list of file extensions to open in the target proteomes directory\n    min_num_homologs: integer, optional\n        the mininum number of homologs (determined by BLAST search)\n        for each gene to test\n    e_value: float, optional\n        the E-value cutoff to identify orthologous genes using BLASTP\n    threads: integer, optional\n        number of threads to use for sequence alignment\n    stdev_offset: float, optional\n        the number of standard deviations a gene's normalized distance\n        is from the mean to identify it as an outlier for a species pair\n    outlier_hgt: float, optional\n        the fraction (value between (0,1]) of normalized pairwise distances\n        over all species-pair vectors belonging to the same gene that are\n        z-score standard deviations from the mean\n    species_set_size: integer, optional\n        threshold number of genes to consider a species set large (a species\n        set is a set of genes whose orthologs are detectable in exactly the\n        same subset of the considered species)\n    hamming_distance: integer, optional\n        distance between two binary vectors indicating the species in which\n        the corresponding ortholog gene appears\n    verbose: boolean, optional\n        if True, run in verbose mode\n    debug: boolean, optional\n        if True, run in debug mode\n    warnings: boolean, optional\n        if True, output warnings\n    timeout: integer, optional\n        number of seconds to allow Clustalw to run per call\n    \"\"\"\n    if verbose:\n        sys.stdout.write(\n            \"Begin whole-genome HGT detection using the Distance method.\\n\\n\")\n        sys.stdout.write(\"Query genome: %s\\n\" % query_proteome_fp)\n\n    extensions = set(['fa', 'fasta', 'faa'])\n    extensions.update(ext)\n\n    # create working directory if doesn't exist\n    if not isdir(working_dir):\n        mkdir(working_dir)\n\n    gene_map, ref_db, num_species = preprocess_data(\n        working_dir=working_dir,\n        target_proteomes_dir=target_proteomes_dir,\n        extensions=extensions,\n        verbose=verbose)\n\n    if debug:\n        sys.stdout.write(\"\\n[DEBUG] gene map:\\n\")\n        for gene in gene_map:\n            sys.stdout.write(\"[DEBUG] %s: %s\\n\" % (gene, gene_map[gene]))\n\n    if verbose:\n        sys.stdout.write(\"\\nRunning BLASTp ..\\n\")\n    hits = {}\n\n    # tabular alignments provided\n    if tabular_alignments_fp is not None:\n        # generate a dictionary of orthologous genes\n        parse_blast(alignments_fp=tabular_alignments_fp,\n                    hits=hits,\n                    gene_map=gene_map,\n                    debug=debug)\n    # tabular alignments to be created\n    else:\n        files = [f\n                 for e in extensions\n                 for f in glob(\"%s/*%s\" % (target_proteomes_dir, e))]\n        for _file in files:\n            # launch BLASTp\n            if align_software == \"blast\":\n                alignments_fp = launch_blast(\n                    query_proteome_fp=query_proteome_fp,\n                    ref_fp=_file,\n                    working_dir=working_dir,\n                    e_value=e_value,\n                    threads=threads,\n                    debug=debug)\n            elif align_software == \"diamond\":\n                alignments_fp = launch_diamond(\n                    query_proteome_fp=query_proteome_fp,\n                    ref_fp=_file,\n                    working_dir=working_dir,\n                    tmp_dir=working_dir,\n                    e_value=e_value,\n                    threads=threads,\n                    debug=debug)\n            else:\n                raise ValueError(\n                    \"Software not supported: %s\" % align_software)\n\n            # generate a dictionary of orthologous genes\n            parse_blast(alignments_fp=alignments_fp,\n                        hits=hits,\n                        gene_map=gene_map,\n                        debug=debug)\n\n    # keep only genes with >= min_num_homologs\n    hits_min_num_homologs = {}\n    max_homologs = 0\n    for query in hits:\n        len_hits = len(hits[query])\n        if query in hits[query]:\n            len_hits -= 1\n        if len_hits >= min_num_homologs:\n            if query in hits_min_num_homologs:\n                raise ValueError(\"Duplicate gene names found: %s\" % query)\n            hits_min_num_homologs[query] = hits[query]\n            if len_hits > max_homologs:\n                max_homologs = len_hits\n    hits.clear()\n\n    if verbose:\n        sys.stdout.write(\n            \"Total number of orthologous gene families with at \"\n            \"least %s genes: %s\\n\" % (\n                min_num_homologs, len(hits_min_num_homologs)))\n    if debug:\n        sys.stdout.write(\"[DEBUG] Blast matches:\\n\")\n        for query in hits_min_num_homologs:\n            sys.stdout.write(\n                \"[DEBUG] %s: %s\\n\" % (query, hits_min_num_homologs[query]))\n    # generate command for CLUSTALW\n    phy_msa_fp = join(working_dir, \"msa.phy\")\n    open(phy_msa_fp, 'a').close()\n    dnd_msa_fp = join(working_dir, \"msa.dnd\")\n    open(dnd_msa_fp, 'a').close()\n    phylip_fp = join(working_dir, \"msa.dis\")\n    open(phylip_fp, 'a').close()\n    # create fasta file for each gene family and run CLUSTALW\n    fasta_in_fp = join(working_dir, \"input.faa\")\n    clustal_command_fp = join(working_dir, \"clustal_command.txt\")\n    with open(clustal_command_fp, 'w') as clustal_command_f:\n        clustal_command_f.write(\n            '1\\n%s\\n2\\n9\\n1\\n4\\n\\n1\\n%s\\n%s\\nX\\n\\nX\\n' % (\n                fasta_in_fp, phy_msa_fp, dnd_msa_fp))\n    phylip_command_fp = join(working_dir, \"phylip_command.txt\")\n    with open(phylip_command_fp, 'w') as phylip_command_f:\n        phylip_command_f.write('%s\\nF\\n%s\\nR\\nY\\n' % (phy_msa_fp, phylip_fp))\n\n    total_genes = len(hits_min_num_homologs)\n    if verbose:\n        sys.stdout.write(\"\\nRunning CLUSTALW and PROTDIST ..\\n\")\n    if max_homologs > num_species:\n        raise ValueError(\n            \"max_homologs > num_species: %s > %s \" % (\n                max_homologs, num_species))\n    # distance matrix containing distances between all ortholog genes\n    full_distance_matrix = numpy.zeros(\n        shape=(total_genes, num_species, num_species), dtype=float)\n    # dictionary to store all subsets of orthologs (keys) and\n    # their number of occurrences (values) (maximum occurrences\n    # is equal to the number of genes)\n    species_set_dict = {}\n    gene_bitvector_map = {}\n    gene_id = {}\n    for i, query in enumerate(hits_min_num_homologs):\n        if verbose:\n            print(\"Computing MSA and distances for gene %s .. (%s/%s)\" % (\n                query, i+1, total_genes))\n        gene_id[i] = query\n        # generate a multiple sequence alignment\n        # for each orthologous gene family\n        launch_msa(fasta_in_fp=fasta_in_fp,\n                   clustal_command_fp=clustal_command_fp,\n                   ref_db=ref_db,\n                   gene_map=gene_map,\n                   hits=hits_min_num_homologs,\n                   query=query,\n                   timeout=timeout)\n\n        # compute distances between each pair of sequences in MSA\n        compute_distances(phylip_command_fp=phylip_command_fp,\n                          warnings=warnings)\n\n        # Z-score normalize distance matrix and add results\n        # to full distance matrix (for all genes)\n        normalize_distances(phylip_fp=phylip_fp,\n                            full_distance_matrix=full_distance_matrix,\n                            num_species=num_species,\n                            full_distance_matrix_offset=i,\n                            species_set_dict=species_set_dict,\n                            gene_bitvector_map=gene_bitvector_map,\n                            debug=debug)\n\n    # output_full_matrix(full_distance_matrix, num_species)\n\n    # cluster gene families by species\n    gene_clusters_dict = cluster_distances(\n        species_set_dict=species_set_dict,\n        species_set_size=species_set_size,\n        hamming_distance=hamming_distance)\n\n    # detect outlier genes per core cluster of genes\n    with open(output_hgt_fp, 'w') as output_hgt_f:\n        output_hgt_f.write(\"\\n# Candidate HGT genes: \\n\")\n        for core_cluster in gene_clusters_dict:\n            outlier_genes = detect_outlier_genes(\n                species_set=gene_clusters_dict[core_cluster],\n                gene_bitvector_map=gene_bitvector_map,\n                full_distance_matrix=full_distance_matrix,\n                stdev_offset=stdev_offset,\n                outlier_hgt=outlier_hgt,\n                num_species=num_species,\n                total_genes=total_genes,\n                debug=debug)\n\n            if outlier_genes:\n                for gene in outlier_genes:\n                    output_hgt_f(\"%s\\n\" % gene_id[gene])\n\n    # output_full_matrix(outlier_genes, num_species)\n\n\n@click.command()\n@click.argument('query-proteome-fp', required=True,\n                type=click.Path(resolve_path=True, readable=True, exists=True,\n                                file_okay=True))\n@click.argument('target-proteomes-dir', required=True,\n                type=click.Path(resolve_path=True, readable=True, exists=True,\n                                file_okay=True))\n@click.argument('working-dir', required=True,\n                type=click.Path(resolve_path=True, readable=True, exists=False,\n                                file_okay=True))\n@click.argument('output-hgt-fp', required=True,\n                type=click.Path(resolve_path=True, readable=True, exists=False,\n                                file_okay=True))\n@click.option('--align-software', type=click.Choice(['diamond', 'blast']),\n              required=False, default=['diamond'], show_default=True,\n              help=\"Software to use for blasting sequences\")\n@click.option('--tabular-alignments-fp', required=False,\n              type=click.Path(resolve_path=True, readable=True, exists=False,\n                              file_okay=True),\n              help=\"Tabular alignments in m6 format (output from BLAST or \"\n                   \"DIAMOND)\")\n@click.option('--ext', multiple=True, type=str, required=False,\n              default=['fa', 'fasta', 'faa'], show_default=True,\n              help=\"File extensions of target proteomes (multiple extensions \"\n                   \"can be given by calling --ext ext1 --ext ext2)\")\n@click.option('--min-num-homologs', type=int, required=False, default=3,\n              show_default=True, help=\"The mininum number of homologs \"\n                                      \"(determined by BLAST search) for each \"\n                                      \"gene to test\")\n@click.option('--e-value', type=float, required=False, default=10e-20,\n              show_default=True, help=\"The E-value cutoff to identify \"\n                                      \"orthologous genes using BLASTP\")\n@click.option('--threads', type=int, required=False, default=1,\n              show_default=True, help=\"Number of threads to use\")\n@click.option('--stdev-offset', type=float, required=False, default=2.326,\n              show_default=True, help=\"The number of standard deviations a \"\n                                      \"gene's normalized distance is from \"\n                                      \"the mean to identify it as an outlier \"\n                                      \"for a species pair\")\n@click.option('--outlier-hgt', type=float, default=0.5, show_default=True,\n              required=False, help=\"The fraction (value between (0,1]) of \"\n                                   \"normalized pairwise distances over all \"\n                                   \"species-pair vectors belonging to the \"\n                                   \"same gene that are z-score standard \"\n                                   \"deviations from the mean\")\n@click.option('--species-set-size', type=int, required=False, default=30,\n              show_default=True, help=\"Threshold number of genes to consider \"\n                                      \"a species set large (a species set is \"\n                                      \"a set of genes whose orthologs are \"\n                                      \"detectable in exactly the same subset \"\n                                      \"of the considered species)\")\n@click.option('--hamming-distance', type=int, required=False, default=2,\n              show_default=True, help=\"Distance between two binary vectors \"\n                                      \"indicating the species in which the \"\n                                      \"corresponding ortholog gene appears\")\n@click.option('--verbose', type=bool, required=False, default=False,\n              show_default=True, help=\"Run in verbose mode\")\n@click.option('--debug', type=bool, required=False, default=False,\n              show_default=True, help=\"Run in debug mode\")\n@click.option('--warnings', type=bool, required=False, default=False,\n              show_default=True, help=\"Print program warnings\")\n@click.option('--timeout', type=int, required=False, default=120,\n              show_default=True, help=\"Number of seconds to allow Clustalw \"\n                                      \"to run per call\")\ndef distance_method_main(query_proteome_fp,\n                         target_proteomes_dir,\n                         working_dir,\n                         output_hgt_fp,\n                         align_software,\n                         tabular_alignments_fp,\n                         ext,\n                         min_num_homologs,\n                         e_value,\n                         threads,\n                         stdev_offset,\n                         outlier_hgt,\n                         species_set_size,\n                         hamming_distance,\n                         verbose,\n                         debug,\n                         warnings,\n                         timeout):\n    \"\"\" Run the Distance-Method HGT detection algorithm.\n    \"\"\"\n    distance_method(query_proteome_fp=query_proteome_fp,\n                    target_proteomes_dir=target_proteomes_dir,\n                    working_dir=working_dir,\n                    output_hgt_fp=output_hgt_fp,\n                    align_software=align_software,\n                    tabular_alignments_fp=tabular_alignments_fp,\n                    ext=ext,\n                    min_num_homologs=min_num_homologs,\n                    e_value=e_value,\n                    threads=threads,\n                    stdev_offset=stdev_offset,\n                    outlier_hgt=outlier_hgt,\n                    species_set_size=species_set_size,\n                    hamming_distance=hamming_distance,\n                    verbose=verbose,\n                    debug=debug,\n                    warnings=warnings,\n                    timeout=timeout)\n\n\nif __name__ == \"__main__\":\n    distance_method_main()\n", "meta": {"hexsha": "7e7e2e42028d4d52007ec63cc34fb75d38a5c747", "size": 46259, "ext": "py", "lang": "Python", "max_stars_repo_path": "horizomer/misc/distance-method/distance_method.py", "max_stars_repo_name": "biocore/horizomer", "max_stars_repo_head_hexsha": "6b30d7f3b79f4f4ce7cc6502f5b820c9b53ab52e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-10-17T12:27:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-09T14:34:05.000Z", "max_issues_repo_path": "horizomer/misc/distance-method/distance_method.py", "max_issues_repo_name": "biocore/WGS-HGT", "max_issues_repo_head_hexsha": "6b30d7f3b79f4f4ce7cc6502f5b820c9b53ab52e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2015-09-11T22:22:39.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-30T18:31:15.000Z", "max_forks_repo_path": "horizomer/misc/distance-method/distance_method.py", "max_forks_repo_name": "biocore/WGS-HGT", "max_forks_repo_head_hexsha": "6b30d7f3b79f4f4ce7cc6502f5b820c9b53ab52e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2015-09-10T17:55:22.000Z", "max_forks_repo_forks_event_max_datetime": "2017-02-22T05:47:13.000Z", "avg_line_length": 39.1362098139, "max_line_length": 86, "alphanum_fraction": 0.5794764262, "include": true, "reason": "import numpy", "num_tokens": 10150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.37754068280545827, "lm_q1q2_score": 0.1917196379766835}}
{"text": "\"\"\"\n\nThis module is used for constructing a `PyMC3' model of the power spectrum using\nthe outputs from asy_peakbag as priors. \n\n\"\"\"\n\nimport numpy as np\nimport pymc3 as pm\nimport warnings\nfrom .plotting import plotting\n\nclass peakbag(plotting):\n    \"\"\" Class for the final peakbagging.\n\n    This class is used after getting the frequency intervals from asy_peakbag,\n    that include the $l=0,2$ mode pairs. \n    \n    The\n\n    Examples\n    --------\n    Using peakbag from the star class instance (recommended)    \n    \n    >>> st = pbjam.star(ID='KIC4448777', pg=pg, numax=[220.0, 3.0], \n                           dnu=[16.97, 0.01], teff=[4750, 100],\n                           bp_rp = [1.34, 0.01])\n    >>> st.run_kde()\n    >>> st.run_asy_peakbag(norders=7)\n    >>> st.run_peakbag()\n\n    Using peakbag on it's own. Requires output from `asy_peakbag'.\n    \n    >>> pb = pbjam.peakbag(st.asy_fit)\n    >>> pb()\n    \n    Parameters\n    ----------\n    f : float, array\n        Array of frequency bins of the spectrum (muHz). Truncated to the range\n        around numax.\n    snr : float, array\n        Array of SNR values for the frequency bins in f (dimensionless).\n    asy_fit : asy_fit\n        The result from the asy_peakbag method.\n    init : bool\n        If true runs make_start and trim_ladder to prepare starting\n        guesses for sampling and transforms the data onto a ladder.\n\n    Attributes\n    ----------\n    f : float, ndarray\n        Array of frequency bins of the spectrum (muHz). Truncated to the range\n        around numax.\n    snr : float, ndarray\n        Array of SNR values for the frequency bins in f (dimensionless).\n    asy_fit : asy_fit\n        The result from the asy_peakbag method.\n        This is a dictionary of 'modeID' and 'summary'.\n        'modeID' is a DataFrame with a list of modes and basic properties.\n        'summary' are summary statistics from the asymptotic_fit.\n        See asy_peakbag asymptotic_fit for more details.\n\n    \"\"\"\n\n    def __init__(self, starinst, init=True, path=None,  verbose=False):\n\n        self.pg = starinst.pg\n        self.f = starinst.f\n        self.s = starinst.s\n        self.asy_fit = starinst.asy_fit\n        self.norders = self.asy_fit.norders\n        if init:\n            self.make_start()\n            self.trim_ladder(verbose=verbose)\n        self.gp0 = [] # Used for gp linewidth info.\n\n        starinst.references._addRef('pymc3')\n        \n        starinst.peakbag = self\n\n\n    def make_start(self):\n        \"\"\" Set the starting model for peakbag\n        \n        Function uses the result of the asymptotic peakbagging and builds a \n        dictionary of starting values for the peakbagging methods.\n\n        \"\"\"\n\n        idxl0 = self.asy_fit.modeID.ell == 0\n        idxl2 = self.asy_fit.modeID.ell == 2\n\n        l0 = self.asy_fit.modeID.loc[idxl0, 'nu_med'].values.flatten()\n        l2 = self.asy_fit.modeID.loc[idxl2, 'nu_med'].values.flatten()\n\n        l0, l2 = self.remove_outsiders(l0, l2)\n\n        width = 10**(np.ones(len(l0)) * self.asy_fit.summary.loc['mode_width', 'mean']).flatten()\n        height =  (10**self.asy_fit.summary.loc['env_height', 'mean'] * \\\n                 np.exp(-0.5 * (l0 - 10**self.asy_fit.summary.loc['numax', 'mean'])**2 /\n                 (10**self.asy_fit.summary.loc['env_width', 'mean'])**2)).flatten()\n        back = np.ones(len(l0))\n\n        self.parnames = ['l0', 'l2', 'width0', 'width2', 'height0', 'height2',\n                         'back']\n\n        pars = [l0, l2, width, width, height, 0.7*height, back]\n\n        self.start ={x:y for x,y in zip(self.parnames, pars)}\n\n        self.n = np.linspace(0.0, 1.0, len(self.start['l0']))[:, None]\n\n    def remove_outsiders(self, l0, l2):\n        \"\"\" Drop outliers\n\n        Drops modes where the guess frequency is outside of the supplied\n        frequency range.\n        \n        Parameters\n        ----------\n        \n        l0 : ndarray\n            Array of l0 mode frequencies\n        l2 : ndarray\n            Array of l2 mode frequencies\n\n        \"\"\"\n\n        sel = np.where(np.logical_and(l0 < self.f.max(), l0 > self.f.min()))\n        return l0[sel], l2[sel]\n\n    def trim_ladder(self, lw_fac=10, extra=0.01, verbose=False):\n        \"\"\" Turns mode frequencies into list of pairs\n        \n        This function turns the list of mode frequencies into pairs and then \n        selects only the pairs in the ladder that have modes that are to be fit.\n\n        Each pair is constructed so that the central frequency is\n        the mid point between the l=0 and l=2 modes as determined by the\n        information in the asy_fit dictionary.\n\n        Parameters\n        ----------\n        lw_fac: float\n            The factor by which the mode line width is multiplied in order\n            to contribute to the pair width.\n        extra: float\n            The factor by which dnu is multiplied in order to contribute to\n            the pair width.\n\n        \"\"\"\n\n        d02 = 10**self.asy_fit.summary.loc['d02', 'mean']\n        d02_lw = d02 + lw_fac * 10**self.asy_fit.summary.loc['mode_width', 'mean']\n        w = d02_lw + (extra * 10**self.asy_fit.summary.loc['dnu', 'mean'])\n        bw = self.f[1] - self.f[0]\n        w /= bw\n        if verbose:\n            print(f'w = {int(w)}')\n            print(f'bw = {bw}')\n        ladder_trim_f = np.zeros([len(self.start['l0']), int(w)])\n        ladder_trim_s = np.zeros([len(self.start['l0']), int(w)])\n        for idx, freq in enumerate(self.start['l0']):\n            loc_mid_02 = np.argmin(np.abs(self.f - (freq - d02/2.0)))\n            if loc_mid_02 == 0:\n                warnings.warn('Did not find optimal pair location')\n            if verbose:\n                print(f'loc_mid_02 = {loc_mid_02}')\n                print(f'w/2 = {int(w/2)}')\n            ladder_trim_f[idx, :] = \\\n                self.f[loc_mid_02 - int(w/2): loc_mid_02 - int(w/2) + int(w)]\n            ladder_trim_s[idx, :] = \\\n                self.s[loc_mid_02 - int(w/2): loc_mid_02 - int(w/2) + int(w) ]\n        self.ladder_f = ladder_trim_f\n        self.ladder_s = ladder_trim_s\n\n    def lor(self, freq, w, h):\n        \"\"\" Simple Lorentzian profile\n        \n        Calculates N Lorentzian profiles, where N is the number of pairs in the\n        frequency list. \n        \n        Parameters\n        ----------\n        freq : float, ndarray\n            Central frequencies the N Lorentzians\n        w : float, ndarray\n            Widths of the N Lorentzians\n        h : float, ndarray\n            Heights of the N Lorentzians   \n         \n        Returns\n        -------\n        lors : ndarray\n           A list containing one Lorentzian per pair.\n\n        \"\"\"\n\n        norm = 1.0 + 4.0 / w**2 * (self.ladder_f.T - freq)**2\n        \n        return h / norm\n\n    def model(self, l0, l2, width0, width2, height0, height2, back):\n        \"\"\"\n        Calcuates a simple model of a flat backgroud plus two lorentzians\n        for each of the N pairs in the list of frequencies under consideration.\n\n        Parameters\n        ----------\n        l0 : ndarray\n            Array of length N, of the l=0 mode frequencies.\n        l2 : ndarray\n            Array of length N, of the l=2 mode frequencies.\n        width0 : ndarray\n            Array of length N, of the l=0 mode widths.\n        width2 : ndarray\n            Array of length N, of the l=2 mode widths.\n        height0 : ndarray\n            Array of length N, of the l=0 mode heights.\n        height2 : ndarray\n            Array of length N, of the l=2 mode heights.\n        back : ndarray\n            Array of length N, of the background levels.\n\n        Returns\n        -------\n        mod : ndarray\n            A 2D array (or 'ladder') containing the calculated models for each\n            of the N pairs.\n\n        \"\"\"\n\n        mod = np.ones(self.ladder_f.shape).T * back\n        mod += self.lor(l0, width0, height0)\n        mod += self.lor(l2, width2, height2)\n        return mod.T\n\n    def init_model(self, model_type):\n        \"\"\" Initialize the pymc3 model for peakbag\n        \n        Sets up the pymc3 model to sample, to perform the final peakbagging. \n        \n        Two treatements of the mode widths are available, the default\n        independent mode widths for each pair, or modeling the mode widths as\n        a function of freqeuency as a Gaussian Process. \n\n        Parameters\n        ----------\n        model_type : str\n            Model choice for the mode widths. The default is to treat the all\n            mode widths independently. Alternatively they can be modeled as\n            a GP.\n\n        \"\"\"\n\n        self.pm_model = pm.Model()\n\n        dnu = 10**self.asy_fit.summary.loc['dnu', 'mean']\n        dnu_fac = 0.03 # Prior on mode frequency has width 3% of Dnu.\n        height_fac = 0.4 # Lognorrmal prior on height has std=0.4.\n        width_fac = 1.0 # Lognorrmal prior on width has std=1.0.\n        back_fac = 0.5 # Lognorrmal prior on back has std=0.5.\n        N = len(self.start['l2'])\n\n        with self.pm_model:\n\n            if model_type != 'model_gp':\n                if model_type != 'simple': # defaults to simple if bad input\n                    warnings.warn('Model not defined - using simple model')\n                width0 = pm.Lognormal('width0', mu=np.log(self.start['width0']),\n                                  sigma=width_fac, shape=N)\n                width2 = pm.Lognormal('width2', mu=np.log(self.start['width2']),\n                                  sigma=width_fac, shape=N)\n\n                self.init_sampler = 'adapt_diag'\n                self.target_accept = 0.9\n\n            elif model_type == 'model_gp':\n                warnings.warn('This model is developmental - use carefully')\n                # Place a GP over the l=0 mode widths ...\n                m0 = pm.Normal('gradient0', 0, 10)\n                c0 = pm.Normal('intercept0', 0, 10)\n                sigma0 = pm.Lognormal('sigma0', np.log(1.0), 1.0)\n                ls = pm.Lognormal('ls', np.log(0.3), 1.0)\n                mean_func0 = pm.gp.mean.Linear(coeffs=m0, intercept=c0)\n                cov_func0 = sigma0 * pm.gp.cov.ExpQuad(1, ls=ls)\n                self.gp0 = pm.gp.Latent(cov_func=cov_func0, mean_func=mean_func0)\n                ln_width0 = self.gp0.prior('ln_width0', X=self.n)\n                width0 = pm.Deterministic('width0', pm.math.exp(ln_width0))\n                # and on the l=2 mode widths\n                m2 = pm.Normal('gradient2', 0, 10)\n                c2 = pm.Normal('intercept2', 0, 10)\n                sigma2 = pm.Lognormal('sigma2', np.log(1.0), 1.0)\n                mean_func2 = pm.gp.mean.Linear(coeffs=m2, intercept=c2)\n                cov_func2 = sigma2 * pm.gp.cov.ExpQuad(1, ls=ls)\n                self.gp2 = pm.gp.Latent(cov_func=cov_func2, mean_func=mean_func2)\n                ln_width2 = self.gp2.prior('ln_width2', X=self.n)\n                width2 = pm.Deterministic('width2', pm.math.exp(ln_width2))\n\n                self.init_sampler = 'advi+adapt_diag'\n                self.target_accept = 0.99\n\n\n            l0 = pm.Normal('l0', self.start['l0'], dnu*dnu_fac, shape=N)\n\n            l2 = pm.Normal('l2', self.start['l2'], dnu*dnu_fac, shape=N)\n\n            height0 = pm.Lognormal('height0', mu=np.log(self.start['height0']),\n                                    sigma=height_fac, shape=N)\n            height2 = pm.Lognormal('height2', mu=np.log(self.start['height2']),\n                                    sigma=height_fac, shape=N)\n            back = pm.Lognormal('back', mu=np.log(1.0), sigma=back_fac, shape=N)\n\n            limit = self.model(l0, l2, width0, width2, height0, height2, back)\n            \n            pm.Gamma('yobs', alpha=1, beta=1.0/limit, observed=self.ladder_s)\n\n\n    def _addPPRatio(self):\n        \"\"\" Add the prior/posterior width ratio to summary\n        \n        Computes the ratio of the prior width and the posterior width. This is a\n        quantity which indicates which probability predominantly informs the \n        resulting mode frequency. If the ratio is < 1 the prior dominates, and\n        vice versa for ratios > 1. \n        \n        No cut-off is made based on this ratio, it is merely to inform the user.\n                \n        \"\"\"\n        \n        dnu = 10**self.asy_fit.summary.loc['dnu', 'mean']\n        \n        log_ppr = np.log10((0.03*dnu))-np.log10(self.summary['sd'])\n        \n        idx = np.array(['l' in name for name in self.summary.index], dtype = 'bool')\n        \n        self.summary['log_ppr'] = np.nan\n        \n        self.summary.at[idx, 'log_ppr'] = log_ppr[idx]\n\n\n    def __call__(self, model_type='simple', tune=1500, nthreads=1, maxiter=4,\n                     advi=False):\n        \"\"\" Perform all the steps in peakbag.\n        \n        Initializes and samples the `PyMC3' model that is set up using the\n        outputs from asy_peakbag as priors. \n\n        Parameters\n        ----------\n        model_type : str\n            Defaults to 'simple'.\n            Can be either 'simple' or 'model_gp' which sets the type of model\n            to be fitted to the data.\n        tune : int, optional\n            Numer of tuning steps passed to pym3.sample. Default is 1500.\n        nthreads : int, optional\n            Number of cores to use - passed to pym3.sample. Default is 1.\n        maxiter : int, optional\n            Number of times to attempt to reach convergence. Default is 4.\n        advi : bool, optional\n            Whether or not to fit using the fullrank_advi option in pymc3. \n            Default is False.\n\n        \"\"\"\n\n        self.init_model(model_type=model_type)\n               \n        # REMOVE THIS WHEN pymc3 v3.8 is a bit older. \n        try:\n            rhatfunc = pm.diagnostics.gelman_rubin\n            warnings.warn('pymc3.diagnostics.gelman_rubin is depcrecated; upgrade pymc3 to v3.8 or newer.', DeprecationWarning)\n        except:\n            rhatfunc = pm.stats.rhat\n        \n\n        if advi:\n            with self.pm_model:\n                cb = pm.callbacks.CheckParametersConvergence(every=1000,\n                                                             diff='absolute',\n                                                             tolerance=0.01)\n\n                mean_field = pm.fit(n=200000, method='fullrank_advi',\n                                    start=self.start,\n                                    callbacks=[cb])\n                self.traces = mean_field.sample(1000)\n        else:\n            Rhat_max = 10\n            niter = 1\n            while Rhat_max > 1.05:\n                if niter > maxiter:\n                    warnings.warn('Did not converge!')\n                    break\n                with self.pm_model:\n                    self.traces = pm.sample(tune=tune * niter, cores=nthreads,\n                                             start=self.start,\n                                             init=self.init_sampler,\n                                             target_accept=self.target_accept,\n                                             progressbar=False)\n                Rhat_max = np.max([v.max() for k, v in rhatfunc(self.traces).items()])\n                niter += 1\n        \n        # REMOVE THIS WHEN pymc3 v3.8 is a bit older\n        try:\n            self.summary = pm.summary(self.traces)\n        except:\n            self.summary = pm.stats.summary(self.traces)\n        \n        self.par_names = self.summary.index\n        \n        samps = np.array([self.traces[x] for x in self.traces.varnames if not x.endswith('_log__')])\n        self.samples = np.array([]).reshape((samps.shape[1], 0))\n        for i in range(samps.shape[0]):   \n            self.samples = np.concatenate((self.samples, samps[i, :, :]), axis =1)\n        ", "meta": {"hexsha": "860a02fbea497abb0458922a5df57529e2730bcd", "size": 15648, "ext": "py", "lang": "Python", "max_stars_repo_path": "pbjam/peakbag.py", "max_stars_repo_name": "nielsenmb/PBjam", "max_stars_repo_head_hexsha": "973625e0cea1b8bf9cbdd621ec3483ac02ce8907", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-11-19T13:45:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T10:44:56.000Z", "max_issues_repo_path": "pbjam/peakbag.py", "max_issues_repo_name": "nielsenmb/PBjam", "max_issues_repo_head_hexsha": "973625e0cea1b8bf9cbdd621ec3483ac02ce8907", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 138, "max_issues_repo_issues_event_min_datetime": "2019-07-17T18:37:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-12T09:39:12.000Z", "max_forks_repo_path": "pbjam/peakbag.py", "max_forks_repo_name": "nielsenmb/PBjam", "max_forks_repo_head_hexsha": "973625e0cea1b8bf9cbdd621ec3483ac02ce8907", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 54, "max_forks_repo_forks_event_min_datetime": "2019-07-17T10:09:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-29T08:39:57.000Z", "avg_line_length": 37.6153846154, "max_line_length": 127, "alphanum_fraction": 0.5499744376, "include": true, "reason": "import numpy,import pymc3", "num_tokens": 3880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19171963086360388}}
{"text": "from __future__ import print_function\n\nimport string\nimport sys\nfrom collections import deque\n\nimport numpy as np\nfrom sklearn.base import BaseEstimator\nfrom sklearn.utils import check_array, check_random_state\nfrom sklearn.utils.validation import check_is_fitted\n\nfrom . import _hmmc\nfrom .utils import normalize, logsumexp, iter_from_X_lengths\n\n\nDECODER_ALGORITHMS = frozenset((\"viterbi\", \"map\"))\n\n\nclass ConvergenceMonitor(object):\n    \"\"\"Monitors and reports convergence to :data:`sys.stderr`.\n\n    Parameters\n    ----------\n    thresh : double\n        Convergence threshold. The algorithm has convereged eitehr if\n        the maximum number of iterations is reached or the log probability\n        improvement between the two consecutive iterations is less than\n        threshold.\n\n    n_iter : int\n        Maximum number of iterations to perform.\n\n    verbose : bool\n        If ``True`` then per-iteration convergence reports are printed,\n        otherwise the monitor is mute.\n\n    Attributes\n    ----------\n    history : deque\n        The log probability of the data for the last two training\n        iterations. If the values are not strictly increasing, the\n        model did not converge.\n\n    iter : int\n        Number of iterations performed while training the model.\n    \"\"\"\n    fmt = \"{iter:>10d} {logprob:>16.4f} {delta:>+16.4f}\"\n\n    def __init__(self, thresh, n_iter, verbose):\n        self.thresh = thresh\n        self.n_iter = n_iter\n        self.verbose = verbose\n        self.history = deque(maxlen=2)\n        self.iter = 1\n\n    def report(self, logprob):\n        if self.history and self.verbose:\n            delta = logprob - self.history[-1]\n            message = self.fmt.format(\n                iter=self.iter, logprob=logprob, delta=delta)\n            print(message, file=sys.stderr)\n\n        self.history.append(logprob)\n        self.iter += 1\n\n    @property\n    def converged(self):\n        return (self.iter == self.n_iter or\n                (len(self.history) == 2 and\n                 self.history[1] - self.history[0] < self.thresh))\n\n\nclass _BaseHMM(BaseEstimator):\n    \"\"\"Hidden Markov Model base class.\n\n    Representation of a hidden Markov model probability distribution.\n    This class allows for easy evaluation of, sampling from, and\n    maximum-likelihood estimation of the parameters of a HMM.\n\n    See the instance documentation for details specific to a\n    particular object.\n\n    Parameters\n    ----------\n    n_components : int\n        Number of states in the model.\n\n    startprob_prior : array, shape (n_components, )\n        Initial state occupation prior distribution.\n\n    transmat_prior : array, shape (n_components, n_components)\n        Matrix of prior transition probabilities between states.\n\n    algorithm : string, one of the ``DECODER_ALGORITHMS```\n        Decoder algorithm.\n\n    random_state: RandomState or an int seed (0 by default)\n        A random number generator instance.\n\n    n_iter : int, optional\n        Maximum number of iterations to perform.\n\n    thresh : float, optional\n        Convergence threshold.\n\n    verbose : bool, optional\n        When ``True`` per-iteration convergence reports are printed\n        to :data:`sys.stderr`. You can diagnose convergence via the\n        :attr:`monitor_` attribute.\n\n    params : string, optional\n        Controls which parameters are updated in the training\n        process.  Can contain any combination of 's' for startprob,\n        't' for transmat, and other characters for subclass-specific\n        emmission parameters. Defaults to all parameters.\n\n    init_params : string, optional\n        Controls which parameters are initialized prior to\n        training.  Can contain any combination of 's' for\n        startprob, 't' for transmat, and other characters for\n        subclass-specific emmission parameters. Defaults to all\n        parameters.\n\n    Attributes\n    ----------\n    startprob_ : array, shape (n_components, )\n        Initial state occupation distribution.\n\n    transmat_ : array, shape (n_components, n_components)\n        Matrix of transition probabilities between states.\n    \"\"\"\n\n    # This class implements the public interface to all HMMs that\n    # derive from it, including all of the machinery for the\n    # forward-backward and Viterbi algorithms.  Subclasses need only\n    # implement _generate_sample_from_state(), _compute_log_likelihood(),\n    # _init(), _initialize_sufficient_statistics(),\n    # _accumulate_sufficient_statistics(), and _do_mstep(), all of\n    # which depend on the specific emission distribution.\n    #\n    # Subclasses will probably also want to implement properties for\n    # the emission distribution parameters to expose them publicly.\n\n    def __init__(self, n_components=1,\n                 startprob_prior=1.0, transmat_prior=1.0,\n                 algorithm=\"viterbi\", random_state=None,\n                 n_iter=10, thresh=1e-2, verbose=False,\n                 params=string.ascii_letters,\n                 init_params=string.ascii_letters):\n        self.n_components = n_components\n        self.monitor_ = ConvergenceMonitor(thresh, n_iter, verbose)\n        self.params = params\n        self.init_params = init_params\n        self.startprob_prior = startprob_prior\n        self.transmat_prior = transmat_prior\n        self.algorithm = algorithm\n        self.random_state = random_state\n        self.n_iter = n_iter\n        self.thresh = thresh\n\n    def score_samples(self, X, lengths=None):\n        \"\"\"Compute the log probability under the model and compute posteriors.\n\n        Parameters\n        ----------\n        X : array-like, shape (n_samples, n_features)\n            Feature matrix of individual samples.\n        lengths : array-like of integers, shape (n_sequences, ), optional\n            Lengths of the individual sequences in ``X``. The sum of\n            these should be ``n_samples``.\n\n        Returns\n        -------\n        logprob : float\n            Log likelihood of ``X``.\n\n        posteriors : array, shape (n_samples, n_components)\n            State-membership probabilities for each sample in ``X``.\n\n        See Also\n        --------\n        score : Compute the log probability under the model.\n        decode : Find most likely state sequence corresponding to ``X``.\n        \"\"\"\n        check_is_fitted(self, \"startprob_\")\n        self._check()\n\n        X = check_array(X)\n        n_samples = X.shape[0]\n        logprob = 0\n        posteriors = np.zeros((n_samples, self.n_components))\n        for i, j in iter_from_X_lengths(X, lengths):\n            framelogprob = self._compute_log_likelihood(X[i:j])\n            logprobij, fwdlattice = self._do_forward_pass(framelogprob)\n            logprob += logprobij\n\n            bwdlattice = self._do_backward_pass(framelogprob)\n            posteriors[i:j] = self._compute_posteriors(fwdlattice, bwdlattice)\n        return logprob, posteriors\n\n    def score(self, X, lengths=None):\n        \"\"\"Compute the log probability under the model.\n\n        Parameters\n        ----------\n        X : array-like, shape (n_samples, n_features)\n            Feature matrix of individual samples.\n        lengths : array-like of integers, shape (n_sequences, ), optional\n            Lengths of the individual sequences in ``X``. The sum of\n            these should be ``n_samples``.\n\n        Returns\n        -------\n        logprob : float\n            Log likelihood of ``X``.\n\n        See Also\n        --------\n        score_samples : Compute the log probability under the model and\n            posteriors.\n        decode : Find most likely state sequence corresponding to ``X``.\n        \"\"\"\n        check_is_fitted(self, \"startprob_\")\n        self._check()\n\n        # XXX we can unroll forward pass for speed and memory efficiency.\n        logprob = 0\n        for i, j in iter_from_X_lengths(X, lengths):\n            framelogprob = self._compute_log_likelihood(X[i:j])\n            logprobij, _fwdlattice = self._do_forward_pass(framelogprob)\n            logprob += logprobij\n        return logprob\n\n    def _decode_viterbi(self, X):\n        framelogprob = self._compute_log_likelihood(X)\n        return self._do_viterbi_pass(framelogprob)\n\n    def _decode_map(self, X):\n        _, posteriors = self.score_samples(X)\n        logprob = np.max(posteriors, axis=1).sum()\n        state_sequence = np.argmax(posteriors, axis=1)\n        return logprob, state_sequence\n\n    def decode(self, X, lengths=None, algorithm=None):\n        \"\"\"Find most likely state sequence corresponding to ``X``.\n\n        Parameters\n        ----------\n        X : array-like, shape (n_samples, n_features)\n            Feature matrix of individual samples.\n        lengths : array-like of integers, shape (n_sequences, ), optional\n            Lengths of the individual sequences in ``X``. The sum of\n            these should be ``n_samples``.\n        algorithm : string, one of the ``DECODER_ALGORITHMS``\n            decoder algorithm to be used\n\n        Returns\n        -------\n        logprob : float\n            Log probability of the produced state sequence.\n\n        state_sequence : array, shape (n_samples, )\n            Labels for each sample from ``X`` obtained via a given\n            decoder ``algorithm``.\n\n        See Also\n        --------\n        score_samples : Compute the log probability under the model and\n            posteriors.\n\n        score : Compute the log probability under the model.\n        \"\"\"\n        check_is_fitted(self, \"startprob_\")\n        self._check()\n\n        algorithm = algorithm or self.algorithm\n        if algorithm not in DECODER_ALGORITHMS:\n            raise ValueError(\"Unknown decoder {0!r}\".format(algorithm))\n\n        decoder = {\n            \"viterbi\": self._decode_viterbi,\n            \"map\": self._decode_map\n        }[algorithm]\n\n        X = check_array(X)\n        n_samples = X.shape[0]\n        logprob = 0\n        state_sequence = np.empty(n_samples, dtype=int)\n        for i, j in iter_from_X_lengths(X, lengths):\n            # XXX decoder works on a single sample at a time!\n            logprobij, state_sequenceij = decoder(X[i:j])\n            logprob += logprobij\n            state_sequence[i:j] = state_sequenceij\n\n        return logprob, state_sequence\n\n    def predict(self, X, lengths=None):\n        \"\"\"Find most likely state sequence corresponding to ``X``.\n\n        Parameters\n        ----------\n        X : array-like, shape (n_samples, n_features)\n            Feature matrix of individual samples.\n        lengths : array-like of integers, shape (n_sequences, ), optional\n            Lengths of the individual sequences in ``X``. The sum of\n            these should be ``n_samples``.\n\n        Returns\n        -------\n        state_sequence : array, shape (n_samples, )\n            Labels for each sample from ``X``.\n        \"\"\"\n        _, state_sequence = self.decode(X, lengths)\n        return state_sequence\n\n    def predict_proba(self, X, lengths=None):\n        \"\"\"Compute the posterior probability for each state in the model.\n\n        X : array-like, shape (n_samples, n_features)\n            Feature matrix of individual samples.\n        lengths : array-like of integers, shape (n_sequences, ), optional\n            Lengths of the individual sequences in ``X``. The sum of\n            these should be ``n_samples``.\n\n        Returns\n        -------\n        posterios : array, shape (n_samples, n_components)\n            State-membership probabilities for each sample from ``X``.\n        \"\"\"\n        _, posteriors = self.score_samples(X, lengths)\n        return posteriors\n\n    def sample(self, n_samples=1, random_state=None):\n        \"\"\"Generate random samples from the model.\n\n        Parameters\n        ----------\n        n_samples : int\n            Number of samples to generate.\n\n        random_state: RandomState or an int seed (0 by default)\n            A random number generator instance. If ``None``, the object's\n            random_state is used.\n\n        Returns\n        -------\n        X : array, shape (n_samples, n_features)\n            Feature matrix.\n        state_sequence : array, shape (n_samples, )\n            State sequence produced by the model.\n        \"\"\"\n        check_is_fitted(self, \"startprob_\")\n\n        if random_state is None:\n            random_state = self.random_state\n        random_state = check_random_state(random_state)\n\n        startprob_cdf = np.cumsum(self.startprob_)\n        transmat_cdf = np.cumsum(self.transmat_, axis=1)\n\n        currstate = (startprob_cdf > random_state.rand()).argmax()\n        state_sequence = [currstate]\n        X = [self._generate_sample_from_state(\n            currstate, random_state=random_state)]\n\n        for t in range(n_samples - 1):\n            currstate = (transmat_cdf[currstate] > random_state.rand()) \\\n                .argmax()\n            state_sequence.append(currstate)\n            X.append(self._generate_sample_from_state(\n                currstate, random_state=random_state))\n\n        return np.atleast_2d(X), np.array(state_sequence, dtype=int)\n\n    def fit(self, X, lengths=None):\n        \"\"\"Estimate model parameters.\n\n        An initialization step is performed before entering the\n        EM-algorithm. If you want to avoid this step for a subset of\n        the parameters, pass proper ``init_params`` keyword argument\n        to estimator's constructor.\n\n        Parameters\n        ----------\n        X : array-like, shape (n_samples, n_features)\n            Feature matrix of individual samples.\n        lengths : array-like of integers, shape (n_sequences, )\n            Lengths of the individual sequences in ``X``. The sum of\n            these should be ``n_samples``.\n\n        Returns\n        -------\n        self : object\n            Returns self.\n        \"\"\"\n        X = check_array(X)\n        self._init(X, lengths=lengths, params=self.init_params)\n        self._check()\n\n        for iter in range(self.n_iter):\n            stats = self._initialize_sufficient_statistics()\n            curr_logprob = 0\n            for i, j in iter_from_X_lengths(X, lengths):\n                framelogprob = self._compute_log_likelihood(X[i:j])\n                logprob, fwdlattice = self._do_forward_pass(framelogprob)\n                curr_logprob += logprob\n                bwdlattice = self._do_backward_pass(framelogprob)\n                posteriors = self._compute_posteriors(fwdlattice, bwdlattice)\n                self._accumulate_sufficient_statistics(\n                    stats, X[i:j], framelogprob, posteriors, fwdlattice,\n                    bwdlattice, self.params)\n\n            self.monitor_.report(curr_logprob)\n            if self.monitor_.converged:\n                break\n\n            self._do_mstep(stats, self.params)\n\n        return self\n\n    def _do_viterbi_pass(self, framelogprob):\n        n_observations, n_components = framelogprob.shape\n        state_sequence, logprob = _hmmc._viterbi(\n            n_observations, n_components, np.log(self.startprob_),\n            np.log(self.transmat_), framelogprob)\n        return logprob, state_sequence\n\n    def _do_forward_pass(self, framelogprob):\n        n_observations, n_components = framelogprob.shape\n        fwdlattice = np.zeros((n_observations, n_components))\n        _hmmc._forward(n_observations, n_components, np.log(self.startprob_),\n                       np.log(self.transmat_), framelogprob, fwdlattice)\n        return logsumexp(fwdlattice[-1]), fwdlattice\n\n    def _do_backward_pass(self, framelogprob):\n        n_observations, n_components = framelogprob.shape\n        bwdlattice = np.zeros((n_observations, n_components))\n        _hmmc._backward(n_observations, n_components, np.log(self.startprob_),\n                        np.log(self.transmat_), framelogprob, bwdlattice)\n        return bwdlattice\n\n    def _compute_posteriors(self, fwdlattice, bwdlattice):\n        log_gamma = fwdlattice + bwdlattice\n        # gamma is guaranteed to be correctly normalized by logprob at\n        # all frames, unless we do approximate inference using pruning.\n        # So, we will normalize each frame explicitly in case we\n        # pruned too aggressively.\n        log_gamma += np.finfo(float).eps\n        log_gamma -= logsumexp(log_gamma, axis=1)[:, np.newaxis]\n        out = np.exp(log_gamma)\n        normalize(out, axis=1)\n        return out\n\n    def _compute_log_likelihood(self, X):\n        pass\n\n    def _generate_sample_from_state(self, state, random_state=None):\n        pass\n\n    def _init(self, X, lengths, params):\n        init = 1. / self.n_components\n        if 's' in params or not hasattr(self, \"startprob_\"):\n            self.startprob_ = np.full(self.n_components, init)\n        if 't' in params or not hasattr(self, \"transmat_\"):\n            self.transmat_ = np.full((self.n_components, self.n_components),\n                                     init)\n\n    def _check(self):\n        self.startprob_ = np.asarray(self.startprob_)\n        if len(self.startprob_) != self.n_components:\n            raise ValueError(\"startprob_ must have length n_components\")\n        if not np.allclose(self.startprob_.sum(), 1.0):\n            raise ValueError(\"startprob_ must sum to 1.0 (got {0:.4f})\"\n                             .format(self.startprob_.sum()))\n\n        self.transmat_ = np.asarray(self.transmat_)\n        if self.transmat_.shape != (self.n_components, self.n_components):\n            raise ValueError(\n                \"transmat_ must have shape (n_components, n_components)\")\n        if not np.allclose(self.transmat_.sum(axis=1), 1.0):\n            raise ValueError(\"rows of transmat_ must sum to 1.0 (got {0})\"\n                             .format(self.transmat_.sum(axis=1)))\n\n    # Methods used by self.fit()\n\n    def _initialize_sufficient_statistics(self):\n        stats = {'nobs': 0,\n                 'start': np.zeros(self.n_components),\n                 'trans': np.zeros((self.n_components, self.n_components))}\n        return stats\n\n    def _accumulate_sufficient_statistics(self, stats, seq, framelogprob,\n                                          posteriors, fwdlattice, bwdlattice,\n                                          params):\n        stats['nobs'] += 1\n        if 's' in params:\n            stats['start'] += posteriors[0]\n        if 't' in params:\n            n_observations, n_components = framelogprob.shape\n            # when the sample is of length 1, it contains no transitions\n            # so there is no reason to update our trans. matrix estimate\n            if n_observations <= 1:\n                return\n\n            lneta = np.zeros((n_observations - 1, n_components, n_components))\n            _hmmc._compute_lneta(n_observations, n_components, fwdlattice,\n                                 np.log(self.transmat_),\n                                 bwdlattice, framelogprob, lneta)\n            stats['trans'] += np.exp(logsumexp(lneta, axis=0))\n\n    def _do_mstep(self, stats, params):\n        # Based on Huang, Acero, Hon, \"Spoken Language Processing\",\n        # p. 443 - 445\n        if 's' in params:\n            self.startprob_ = self.startprob_prior - 1.0 + stats['start']\n            normalize(self.startprob_)\n        if 't' in params:\n            self.transmat_ = self.transmat_prior - 1.0 + stats['trans']\n            normalize(self.transmat_, axis=1)\n", "meta": {"hexsha": "057861527b53a09ce99297455edda45c079d4ca2", "size": 19245, "ext": "py", "lang": "Python", "max_stars_repo_path": "hmmlearn/base.py", "max_stars_repo_name": "paschalidoud/hmmlearn", "max_stars_repo_head_hexsha": "9d1ef3e82f0ff4bc5fc81b0c2e928692d0c0f90d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hmmlearn/base.py", "max_issues_repo_name": "paschalidoud/hmmlearn", "max_issues_repo_head_hexsha": "9d1ef3e82f0ff4bc5fc81b0c2e928692d0c0f90d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hmmlearn/base.py", "max_forks_repo_name": "paschalidoud/hmmlearn", "max_forks_repo_head_hexsha": "9d1ef3e82f0ff4bc5fc81b0c2e928692d0c0f90d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-14T08:41:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-14T08:41:28.000Z", "avg_line_length": 37.0096153846, "max_line_length": 78, "alphanum_fraction": 0.6196934269, "include": true, "reason": "import numpy", "num_tokens": 4243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.19171963086360388}}
{"text": "from stuff import *\nimport sys,re,argparse,pickle\nfrom scipy.optimize import minimize\nfrom scipy.stats import norm\nfrom scipy.special import gammaln\nfrom math import log,exp,sqrt,sin,pi\nimport numpy as np\nfrom subprocess import Popen,PIPE\nfrom datetime import datetime\n\n# (Make it auto download files?)\n# Get ltla.csv from https://coronavirus.data.gov.uk/api/v2/data?areaType=ltla&metric=newCasesBySpecimenDate&format=csv\n# Sanger data from https://covid-surveillance-data.cog.sanger.ac.uk/download/lineages_by_ltla_and_week.tsv\n# COG-UK data from https://cog-uk.s3.climb.ac.uk/phylogenetics/latest/cog_metadata.csv\n# SGTF   data from Fig.16 Tech Briefing 12: https://assets.publishing.service.gov.uk/government/uploads/system/uploads/attachment_data/file/988608/Variants_of_Concern_Technical_Briefing_12_Data_England.xlsx\n\n# LTLA_age.csv from https://api.coronavirus.data.gov.uk/v2/data?areaType=ltla&metric=newCasesBySpecimenDateAgeDemographics&format=csv\n\ndef sanitise(fn): return fn.replace(' ','_').replace(\"'\",\"\")\n\nltlaengdata=loadcsv(\"Local_Authority_District_to_Region__December_2020__Lookup_in_England.csv\")\nltla2region=dict(zip(ltlaengdata['LAD20CD'],ltlaengdata['RGN20NM']))\nltla2name=dict(zip(ltlaengdata['LAD20CD'],map(sanitise,ltlaengdata['LAD20NM'])))\nltlapopdata=loadcsv(\"LTLA-NIMS-populations.csv\")\n\n# 1. Sanger uses LAD19 except E06000053 (Isles of Scilly) isn't present. I assume it's fused into E06000052 (Cornwall).\n# 2. Dashboard/api use LAD19 except that E09000001 (City of London) has been fused into E09000012 (Hackney).\n#    and E06000053 (Isles of Scilly) is fused into E06000052 (Cornwall).\n# 3. NIMS (population and vaccine data) uses LAD20 (E070000[4567] fused into E06000060).\n# Easier to fuse than to split, so standardise on LAD20 with E09000001 fused into E09000012 and E06000053 fused into E06000052.\nfuseltla=dict(zip(ltlaengdata['LAD20CD'],ltlaengdata['LAD20CD']))\nfuseltla['E07000004']='E06000060'\nfuseltla['E07000005']='E06000060'\nfuseltla['E07000006']='E06000060'\nfuseltla['E07000007']='E06000060'\nfuseltla['E09000001']='E09000012'\nfuseltla['E06000053']='E06000052'\n\ndef coglab2uk(x): return \"UK\"\ndef coglab2country(x): return x.split('/')[0].replace('_',' ')\ndef coglab2coglab(x): return x\ndef sgtf2region(x):\n  if x=='Yorkshire and Humber': return 'Yorkshire and The Humber'\n  return x\ndef sgtf2country(x): return 'England'\ndef includeltla(ltla,ltlaset):\n  if ltlaset==\"London\":\n    return ltla2region[ltla]=='London'\n  elif ltlaset==\"test\":\n    return ltla2region[ltla]=='London' and ltla<'E09000010'\n  elif ltlaset==\"Bolton\":\n    return ltla=='E08000001'\n  elif ltlaset==\"Hartlepool\":\n    return ltla=='E06000001'\n  elif ltlaset==\"NE\":\n    return ltla2region[ltla]=='North East'\n  elif ltlaset==\"All\":\n    return True\n  else:\n    raise RuntimeError(\"Unrecognised ltla set \"+ltlaset)\n\nparser=argparse.ArgumentParser()\nparser.add_argument('-l', '--load-options',   help='Load options from a file')\nparser.add_argument('-s', '--save-options',   help='Save options to a file')\nparser.add_argument('-g', '--graph-filename', help='Stem of graph filenames')\nargs=parser.parse_args()\n\n# Up to 5 parameters to be optimised:\n# 0: g    Difference of weekly growth rates (g(V1)-g(V0)) for unvaccinated people\n# 1: rw   Weight of region counts in hierarchy\n# 2: tw   Weight of total counts in hierarchy\n# 3: r1   RR (= 1-VE) of vaccine for variant 1 (delta)\n# 4: r0   RR (= 1-VE) of vaccine for variant 0 (alpha)\n\ndesc=[\"Δg_week\",\"region_wt\",\"eng_wt\",\"r1\",\"r0\"]\n\n### Model ###\n### End Model ###\n\n\n### Options ###\n\nsource=\"Sanger\"\n#source=\"COG-UK\"\n#source=\"SGTF\"\n\n# Number of parameters to optimise\nN=4;r0=0.3\n#N=3\n#N=5\n\nvaxeffecttime=20# Days before vaccine is presumed to have a decent effect\n\n# Can choose location size from \"LTLA\", \"region\", \"country\", \"UK\"\n# Sanger works with LTLA, region, country\n# COG-UK works with country, UK\n# SGTF works with region, country\nlocationsize=\"LTLA\"\n\nltlaexclude=set()\n#ltlaexclude=set(['E08000001','E12000002'])# Bolton, Manchester\nltlaset=\"All\"\n#ltlaset=\"London\"\n#ltlaset=\"Bolton\"\n#ltlaset=\"Hartlepool\"\n\n# Will plot graph of these locations even if only encountered during subdivision of global growth mode\nspecialinterest=set(['E08000001'])\n\nmgt=5# Mean generation time in days\n\n# Earliest day to use case data\nminday=datetoday('2021-04-01')# Inclusive\n\n# Earliest day to use VOC count data, given as end-of-week. Will be rounded up to match same day of week as lastweek.\n#firstweek=minday+6\nfirstweek=datetoday('2021-05-01')\n\nnif1=0.048 # Non-independence factor (1/overdispersion) for cases (less than 1 means information is downweighted)\nnif2=0.255 # Non-independence factor (1/overdispersion) for VOC counts (ditto)\nisd0=1.0   # Inverse sd for prior on starting number of cases of non-B.1.617.2: assume starts off similar to total number of cases\nisd1=0.3   # Inverse sd for prior on starting number of cases of B.1.617.2 (0.3 is very weak)\nisd2=1     # Inverse sd for prior on transmission advantage (as growth rate per day). 0 means uniform prior. 1 is very weak.\n\n# Prior linking initial daily growth rate to estimate from pre-B.1.617.2 era\nsig0=0.004\n\n# Timescale in days over which growth rate can change significantly\n# (lower = more wiggles)\nbmsig=25\n\n# Lengthscale for filtered Brownian motion\n# (higher = greater amplitude for the wiggles)\nbmscale=0.01\n\n# Case ascertainment rate\nasc=0.4\n\n# Discard this many cases at the end of the list of cases by specimen day\ndiscardcasedays=3# Pro tem to allow for Wales and NI late reporting at weekends and bank holidays\n\n# Discard this many days of the latest COG data\ndiscardcogdays=2\n\nminopts={\"maxiter\":10000,\"eps\":1e-4}\n\nmode=\"local growth rates\"\n#mode=\"global growth rate\"\n#mode=\"fixed growth rate\",0.1\n\nvoclen=(1 if source==\"COG-UK\" else 7)\n\nconf=0.95\n\nmodel=\"scaledpoisson\"\n#model=\"NBBB\"\n#model=\"NBBB+magicprior\"\n\n### End options ###\n\nopts={\n  \"Source\": source,\n  \"Location size\": locationsize,\n  \"LTLA set\": ltlaset,\n  \"LTLA exclude\": list(ltlaexclude),\n  \"Generation time (days)\": mgt,\n  \"Earliest day for case data\": daytodate(minday),\n  \"Earliest week (using end of week date) to use VOC count data\": daytodate(firstweek),\n  \"Optimisation mode\": mode,\n  \"nif1\": nif1,\n  \"nif2\": nif2,\n  \"Inverse sd for prior on initial non-B.1.617.2\": isd0,\n  \"Inverse sd for prior on initial B.1.617.2\": isd1,\n  \"Inverse sd for prior on growth\": isd2,\n  \"Timescale of growth rate change (days)\": bmsig,\n  \"Lengthscale for filtered Brownian motion\": bmscale,\n  \"Case ascertainment rate\": asc,\n  \"Number of days of case data to discard\": discardcasedays,\n  \"Number of days of COG-UK data to discard\": discardcogdays,\n  \"Minimiser options\": minopts,\n  \"Length of time period over which VOC counts are given (days)\": voclen,\n  \"Confidence level\": conf,\n  \"Model\": model\n}\n\nif args.save_options!=None:\n  with open(args.save_options,'w') as fp: json.dump(opts,fp,indent=2)\n\nif args.load_options!=None:\n  with open(args.load_options,'r') as fp: lopts=json.load(fp)\n  for x in lopts: opts[x]=lopts[x]\n  \nsource=opts[\"Source\"]\nlocationsize=opts[\"Location size\"]\nltlaset=opts[\"LTLA set\"]\nltlaexclude=set(opts[\"LTLA exclude\"])\nmgt=opts[\"Generation time (days)\"]\nminday=datetoday(opts[\"Earliest day for case data\"])\nfirstweek=datetoday(opts[\"Earliest week (using end of week date) to use VOC count data\"])\nmode=opts[\"Optimisation mode\"]\nnif1=opts[\"nif1\"]\nnif2=opts[\"nif2\"]\nisd0=opts[\"Inverse sd for prior on initial non-B.1.617.2\"]\nisd1=opts[\"Inverse sd for prior on initial B.1.617.2\"]\nisd2=opts[\"Inverse sd for prior on growth\"]\nbmsig=opts[\"Timescale of growth rate change (days)\"]\nbmscale=opts[\"Lengthscale for filtered Brownian motion\"]\nasc=opts[\"Case ascertainment rate\"]\ndiscardcasedays=opts[\"Number of days of case data to discard\"]\ndiscardcogdays=opts[\"Number of days of COG-UK data to discard\"]\nminopts=opts[\"Minimiser options\"]\nvoclen=opts[\"Length of time period over which VOC counts are given (days)\"]\nconf=opts[\"Confidence level\"]\nmodel=opts[\"Model\"]\n\nzconf=norm.ppf((1+conf)/2)\n\nprint(\"Options:\")\nprint()\nfor x in sorted(list(opts)): print(\"%s:\"%x,opts[x])\nprint()\nsys.stdout.flush()\n\nnp.set_printoptions(precision=3,linewidth=150)\n\nokplaces=set(ltla for ltla in fuseltla.values() if includeltla(ltla,ltlaset) and not ltla in ltlaexclude)\nplaces=sorted(list(okplaces))\n\nif source==\"Sanger\":\n  fullsource=\"Wellcome Sanger Institute\"\n  assert voclen==7\n  sanger=loadcsv(\"lineages_by_ltla_and_week.tsv\",sep='\\t')\n  \n  lastweek=datetoday(max(sanger['WeekEndDate']))\n  nweeks=(lastweek-firstweek)//voclen+1\n  # Sanger week number is nweeks-1-(lastweek-day)//voclen\n\n  # Get Sanger (variant) data into a suitable form\n  vocnum={}#ltla: np.zeros([nweeks,2],dtype=int) for ltla in ltla2region if ltla[0]=='E'}\n  rvocnum={}\n  for (date,lad19,var,n) in zip(sanger['WeekEndDate'],sanger['LTLA'],sanger['Lineage'],sanger['Count']):\n    day=datetoday(date)\n    week=nweeks-1-(lastweek-day)//voclen\n    if week>=0 and week<nweeks:\n      ltla=fuseltla[lad19]\n      if ltla not in okplaces: continue\n      if ltla not in vocnum: vocnum[ltla]=np.zeros([nweeks,2],dtype=int)\n      if var==\"B.1.617.2\": vocnum[ltla][week][1]+=n\n      else: vocnum[ltla][week][0]+=n\n      place=ltla2region[ltla]\n      if place not in rvocnum: rvocnum[place]=np.zeros([nweeks,2],dtype=int)\n      if var==\"B.1.617.2\": rvocnum[place][week][1]+=n\n      else: rvocnum[place][week][0]+=n\nelse: raise RuntimeError(\"Unrecognised source: \"+source)\n\ntvocnum=sum(rvocnum.values())\n\n\nltlapop={}\nregionpop={}\nfor (lad20,n1,n2) in zip(ltlapopdata['LTLA Code'],ltlapopdata['Under 16'],ltlapopdata['16+']):\n  ltla=fuseltla[lad20]\n  if ltla not in okplaces: continue\n  ltlapop[ltla]=ltlapop.get(ltla,0)+n1+n2\n  region=ltla2region[ltla]\n  regionpop[region]=regionpop.get(region,0)+n1+n2\nrpopratio={ltla:ltlapop[ltla]/regionpop[ltla2region[ltla]] for ltla in ltlapop}\ntpop=sum(regionpop.values())\ntpopratio={ltla:ltlapop[ltla]/tpop for ltla in ltlapop}\n\n# Convert daily growth rate & uncertainty into R-number-based description\n# dh = 1 standard deviation\ndef Rdesc(h0,dh):\n  (Tmin,T,Tmax)=[(exp(h*mgt)-1)*100 for h in [h0-zconf*dh,h0,h0+zconf*dh]]\n  return \"%.0f%% (%.0f%% - %.0f%%)\"%(T,Tmin,Tmax)\n\n# Need to scale the variables being optimised over to keep SLSQP happy\ncondition=np.zeros(N)+1\n\n# Return negative log likelihood (negative because scipy can only minimise, not maximise)\n# If const is true then add in all the constant terms (that don't affect the optimisation)\ndef NLL(xx_conditioned,const=False,pic=False):\n  xx=xx_conditioned/condition\n  tot=0\n\n  # Prior on G\n  #a0=log(lcases[0]+.5)\n  #tot+=-((xx[0]-a0)*isd0)**2/2\n  #if const: tot-=log(2*pi/isd0**2)/2\n  \n  # Prior on rweight\n  #tot+=-((xx[1]-(a0-4))*isd1)**2/2\n  #if const: tot-=log(2*pi/isd1**2)/2\n  \n  # Prior on tweight\n  #tot+=-((xx[2]-(a0-4))*isd1)**2/2\n  #if const: tot-=log(2*pi/isd1**2)/2\n\n  # Prior on r1\n  #tot+=-(xx[3]*isd2)**2/2\n  #if const: tot-=log(2*pi/isd2**2)/2\n  \n  # Prior on r0\n  #tot+=-(xx[4]*isd2)**2/2\n  #if const: tot-=log(2*pi/isd2**2)/2\n\n  if pic: fp=open(\"temp\",\"w\")\n  for place in places:\n    if place not in vocnum: continue\n    vv=vocnum[place]\n    rv=rvocnum[ltla2region[place]]\n    rpr=rpopratio[place]\n    tpr=tpopratio[place]\n    for w in range(nweeks-1):\n      rho=exp(xx[0])\n      AB=vv[w]+xx[1]*rpr*rv[w]+xx[2]*tpr*tvocnum[w]\n      CD=vv[w+1]\n      if CD.sum()==0: continue\n      if N>=4:\n        r1=xx[3]\n        if N>=5: r0_=xx[4]\n        else: r0_=r0\n        pp=pvax[place][w]\n        if pp==[]:\n          print(place,w,CD);raise RuntimeError(\"Shouldn't happen: Sanger[%s] has a case but api shows none\"%place)\n        #if pic: print(\"%s.%d  %8.5f  %12g  %12g\"%(place,w,p,CD[0]/AB[0],CD[1]/AB[1]),file=fp)\n      else:\n        r1=r0_=0\n        pp=[(1,0)]\n      tl=0;tn=0\n      for (n,p) in pp:\n        rho_=rho*(1-p+p*r1)/(1-p+p*r0_)\n        s=AB[0]+rho_*AB[1]\n        #print(AB,CD,rho_,s,p,r0_,r1)\n        tl+=n*(CD[0]*log(AB[0]/s)+CD[1]*log(rho_*AB[1]/s))\n        tn+=n\n      assert tn>0\n      tot+=tl/tn\n      if const: tot+=gammaln(CD[0]+CD[1]+1)-gammaln(CD[0]+1)-gammaln(CD[1]+1)# Could make a table\n  if pic: fp.close()\n  return -tot\n\ndef Hessian(xx):\n  eps=1e-3\n  H=np.zeros([N,N])\n  for i in range(N-1):\n    for j in range(i+1,N):\n      v=0\n      eps1=eps/condition[i]\n      eps2=eps/condition[j]\n      for (s1,s2) in [(-1,-1),(-1,1),(1,-1),(1,1)]:\n        x=np.copy(xx)\n        x[i]+=s1*eps1\n        x[j]+=s2*eps2\n        v+=s1*s2*NLL(x*condition)\n      e=v/(4*eps1*eps2)\n      H[i,j]=e\n      H[j,i]=e\n  for i in range(N):\n    x=np.copy(xx)\n    v=0\n    eps1=eps/condition[i]\n    for s in [-1,0,1]:\n      x=np.copy(xx)\n      x[i]+=s*eps1\n      v+=(s*s*3-2)*NLL(x*condition)\n    H[i,i]=v/eps1**2\n  return H\n\n# Returns log likelihood\ndef optimise(hint=[0.7,.25,.2,0.3,0.3][:N],statphase=False):\n  xx=np.copy(hint)\n  bounds=[(-5,10),(1e-2,100),(1e-2,100),(0.01,5),(0.01,5)][:N]\n  res=minimize(NLL,xx*condition,bounds=bounds,method=\"SLSQP\",options=minopts)\n  if not res.success:\n    print(res)\n    print(place)\n    print(\"xx =\",xx)\n    for x in sorted(list(opts)): print(\"%s:\"%x,opts[x])\n    print(\"bounds =\",bounds)\n    raise RuntimeError(res.message)\n  xx=res.x/condition\n\n  # Work out log likelihood including constant terms\n  LL=-NLL(res.x,const=True)\n  \n  # If 'statphase', make the log likelihood a better approximation to log(integral over all parameters) using stationary phase approximation\n  if statphase:\n    H=Hessian(xx)\n    det=np.linalg.det(H)\n    if det<=0: print(\"Warning: Hessian not positive for %s. Can't make corrected log likelihood.\"%place);det=1\n    LL+=N*log(2*pi)/2-log(det)/2\n\n  # Return optimum xx log likelihood\n  return res.x/condition,LL\n\n# Assumes xx is at a local max of log likelihood\ndef makesamples(xx,H=None):\n  if H is None: H=Hessian(xx)\n  Hcond=H/condition/condition[:,None]\n  eig=np.linalg.eigh(Hcond)\n  # np.diag(np.matmul(np.matmul(np.transpose(eig[1]),Hcond),eig[1])) ~= eig[0]\n  if not (eig[0]>0).all(): print(\"Hessian not +ve definite so can't do full confidence calculation\");return None,None\n  nsamp=100000\n  t=norm.rvs(size=[nsamp,N])# nsamp x N\n  sd=eig[0]**(-.5)# N\n  u=t*sd# nsamp x N\n  samp_cond=np.matmul(u,np.transpose(eig[1]))# nsamp x N\n  samp=samp_cond/condition+xx\n  cc=[]\n  n0=int((1-conf)/2*nsamp)\n  n1=int((1+conf)/2*nsamp)\n  for i in range(N):\n    a=list(samp[:,i])\n    a.sort()\n    cc.append((a[nsamp//2],a[n0],a[n1]))\n  return samp,cc\n\ndef printplaceinfo(place,using=''):\n  name=ltla2name.get(place,place)+using\n  print()\n  print(name)\n  print(\"=\"*len(name))\n  print()\n  print(\"                        Nonvar    Var   Seen\")\n  for w in range(nweeks):\n    day0,day1=lastweek-(nweeks-w)*voclen+1,lastweek-(nweeks-1-w)*voclen\n    print(daytodate(day0),\"-\",daytodate(day1),\"%6d %6d %6.0f\"%(vocnum[place][w][0],vocnum[place][w][1],sum(cases[place][day0-minday:day1-minday+1])))\n  print()\n\nvaxdir='VaccinationData'\nvaxdat={}\nfor x in sorted(os.listdir(vaxdir)):\n  f=x.find('20')\n  vaxdat[x[f:f+10]]=loadcsv(os.path.join(vaxdir,x))\n\ndef parseage_api(age):\n  if '_' in age: x=age.split('_');return int(x[0]),int(x[1])+1\n  if age[-1]=='+': return int(age[:-1]),150\n  if age=='unassigned': return 0,150\n  else: raise RuntimeError(\"Unrecognised age band: \"+age)\n\n# D*.0-50,D*.50-55,...,D1.0-30,D1.30-35,D1.35-40,D1.40-45,...,D2.40-45,D2.45-50,...\ndef parseage_nimsvax(age):\n  if age[:1]!='D': return None,None\n  f=age.find('.')\n  g=age.find('-',f+1)\n  return (age[:f],(int(age[f+1:g]),int(age[g+1:])))\n\n# Under 16,16-29,30-34,35-39,40-44,45-49,50-54,55-59,60-64,65-69,70-74,75-79,80+,16+\ndef parseage_nimspop(age):\n  if '-' in age: x=age.split('-');return int(x[0]),int(x[1])+1\n  if age[:5]=='Under': return 0,int(age[6:])\n  if age[-1]=='+': return int(age[:-1]),150\n  return None\n\nltlaagecachedir=\"LTLA_age_cache\"\nltlaagecachename=\"LTLA_age_weekly_%s_+%dweeks.pickle\"%(daytodate(firstweek),nweeks)\nfn=os.path.join(ltlaagecachedir,ltlaagecachename)\nos.makedirs(ltlaagecachedir,exist_ok=True)\nif os.path.isfile(fn):\n  with open(fn,'rb') as fp:\n    caseages=pickle.load(fp)\nelse:\n  print(\"Loading and processing case-age data from api\")\n  # Todo: automate loading of LTLA_age.csv if not present or out of date.\n  la=loadcsv(\"LTLA_age.csv\")\n  date0=daytodate(lastweek)\n  date1=max(la['date'])\n  if date1<date0: raise RuntimeError(\"LTLA_age.csv not up to date. Need up to %s but it ends at %s.\"%(date0,date1))\n  caseages={}\n  for lad19,date,age,cases in zip(la['areaCode'],la['date'],la['age'],la['cases']):\n    ltla=fuseltla[lad19]\n    day=datetoday(date)\n    w=nweeks-1-(lastweek-day)//voclen\n    if w>=0 and w<nweeks:\n      if ltla not in caseages: caseages[ltla]={}\n      a=parseage_api(age)\n      if a!=(0,60) and a!=(60,150):\n        caseages[ltla].setdefault(a,[0]*nweeks)[w]+=cases\n  with open(fn,'wb') as fp:\n    pickle.dump(caseages,fp)\n\n\nfrom random import random,seed\n#seed(42)\npvax={place:[[] for w in range(nweeks-1)] for place in places}\nfor w in range(nweeks-1):\n  date=daytodate(firstweek+w*7+10-vaxeffecttime)\n  id=max(dt for dt in vaxdat if dt<date)\n  print(\"Using NIMS vax w/e %s to correspond to Sanger w/e %s -> w/e %s\"%(id,daytodate(firstweek+w*7),daytodate(firstweek+w*7+7)))\n  v=vaxdat[id]\n  \n  vaxnum={}# Map from LTLA -> age -> numvaxed\n  for (i,lad20) in enumerate(v['LTLA Code']):\n    ltla=fuseltla[lad20]\n    if ltla in okplaces:\n      if ltla not in vaxnum: vaxnum[ltla]={}\n      for age in v:\n        d,a=parseage_nimsvax(age)\n        if a!=None:\n          vaxnum[ltla][a]=vaxnum[ltla].get(a,0)+v[age][i]\n\n  vaxpop={}# Map from LTLA -> age -> population\n  for (i,lad20) in enumerate(ltlapopdata['LTLA Code']):\n    ltla=fuseltla[lad20]\n    if ltla in okplaces:\n      if ltla not in vaxpop: vaxpop[ltla]={}\n      for age in ltlapopdata:\n        a=parseage_nimspop(age)\n        if a!=None:\n          vaxpop[ltla][a]=vaxpop[ltla].get(a,0)+ltlapopdata[age][i]\n  \n  for ltla in caseages:\n    if ltla in okplaces:\n      cas=caseages[ltla]\n      vax=vaxnum[ltla]\n      pop=vaxpop[ltla]\n      pp=[]\n      for ca in cas:\n        n=cas[ca][w+1]\n        if n==0: continue\n        num=den=0\n        for va in vax:\n          # Want (vax number) as weighted by P(case age interval|vax age interval) = |ca intersect va|/|va|\n          num+=max(min(va[1],ca[1],100)-max(va[0],ca[0]),0)/(min(va[1],100)-va[0])*vax[va]\n        for pa in pop:\n          den+=max(min(pa[1],ca[1],100)-max(pa[0],ca[0]),0)/(min(pa[1],100)-pa[0])*pop[pa]\n        pp.append((n,min(num/den,1)))\n      pvax[ltla][w]=pp\n\nxx,L=optimise()\nprint()\n\nprint(\"Variables:\",xx)\nprint(\"Log likelihood:\",L)\nNLL(xx*condition,const=True,pic=True)\nH=Hessian(xx)\nprint(\"Hessian:\");print(H)\neig=np.linalg.eigh(H)\nprint(\"Eigenvalues:\",eig[0])\nprint()\n\nh=xx[0]/7;dh=1/sqrt(H[0,0])/7\nprint(\"Logarithmic growth rate advantage/day: %.1f%% (%.1f%% - %.1f%%)\"%(h*100,(h-zconf*dh)*100,(h+zconf*dh)*100))\nprint(\"Multiplicative growth rate advantage/day: %.1f%% (%.1f%% - %.1f%%)\"%((exp(h)-1)*100,(exp(h-zconf*dh)-1)*100,(exp(h+zconf*dh)-1)*100))\nprint(\"R-number advantage: %.2f (%.2f - %.2f)\"%(exp(mgt*h),exp(mgt*(h-zconf*dh)),exp(mgt*(h+zconf*dh))))\nprint()\n\nprint(\"Confidence intervals from single variables:\")\nfor i in range(N):\n  x=xx[i];dx=1/sqrt(H[i,i])\n  print(\"%10s: %5.3f (%5.3f - %5.3f)\"%(desc[i],x,x-zconf*dx,x+zconf*dx))\nprint()\n\nprint(\"Confidence intervals from multivariate calculation:\")\nC=np.linalg.inv(H)\nfor i in range(N):\n  x=xx[i];dx=sqrt(C[i,i])\n  print(\"%10s: %5.3f (%5.3f - %5.3f)\"%(desc[i],x,x-zconf*dx,x+zconf*dx))\nprint()\n\nsamp,cc=makesamples(xx,H)\nprint(\"Confidence intervals from multivariate simulation:\")\nfor i in range(N):\n  print(\"%10s: %5.3f (%5.3f - %5.3f)\"%((desc[i],)+cc[i]))\n\nif 0:\n  l=list(pvax)\n  l.sort(key=lambda x: pvax[x][3])\n  for x in l:\n    print(x,\"%5.0f %5.0f %5.0f %5.0f\"%tuple([z*100 for z in pvax[x]]),\"  \",ltla2name[x])\n", "meta": {"hexsha": "a1fa2ecb6910e236b506bfecc716f7f47ba6e799", "size": 19767, "ext": "py", "lang": "Python", "max_stars_repo_path": "VOCgrowth/vocfit2.py", "max_stars_repo_name": "alex1770/Covid-19", "max_stars_repo_head_hexsha": "0212593bf5d9bcbb7009c7d1fb1710116ad8bf32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-06-26T09:22:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T21:29:22.000Z", "max_issues_repo_path": "VOCgrowth/vocfit2.py", "max_issues_repo_name": "alex1770/Covid-19", "max_issues_repo_head_hexsha": "0212593bf5d9bcbb7009c7d1fb1710116ad8bf32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-21T09:45:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T09:45:17.000Z", "max_forks_repo_path": "VOCgrowth/vocfit2.py", "max_forks_repo_name": "alex1770/Covid-19", "max_forks_repo_head_hexsha": "0212593bf5d9bcbb7009c7d1fb1710116ad8bf32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-25T18:27:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-12T17:49:31.000Z", "avg_line_length": 34.497382199, "max_line_length": 206, "alphanum_fraction": 0.6741033035, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19171963086360388}}
{"text": "#!/usr/bin/env python3\n#\n# gw2wannier90 interface\n#\n# This file is distributed as part of the Wannier90 code and\n# under the terms of the GNU General Public License. See the\n# file `LICENSE' in the root directory of the Wannier90\n# distribution, or http://www.gnu.org/copyleft/gpl.txt\n#\n# The webpage of the Wannier90 code is www.wannier.org\n#\n# The Wannier90 code is hosted on GitHub:\n#\n# https://github.com/wannier-developers/wannier90\n#\n# Designed and tested with: Quantum Espresso and Yambo\n# This interface should work with any G0W0 code\n# Originally written by Stepan Tsirkin\n# Extended, developed and documented by Antimo Marrazzo\n#\n# Updated on February 19th, 2017 by Antimo Marrazzo (antimo.marrazzo@epfl.ch)\n# Updated on October 7th, 2019 by Junfeng Qiao (qiaojunfeng@outlook.com)\n#\nimport argparse\nfrom dataclasses import dataclass\nimport datetime\nimport glob\nimport os\nimport shutil\nimport subprocess\n\nimport numpy as np\nfrom scipy.io import FortranFile\n\n\ndef parse_args(args=None):\n\n    parser = argparse.ArgumentParser(\n        description=r\"\"\"### gw2wannier90 interface ###\n\nUsage: gw2wannier90.py seedname options\n\nOptions can be:\n  mmn, amn, spn, unk, uhu, uiu,\n  spn_formatted, unk_formatted, uhu_formatted, uiu_formatted,\n  write_formatted\n\nIf no options are specified, all the files are considered.\n\nBe careful with unformatted files, they are compiler-dependent.\nA safer choice is to use (bigger) formatted files, with options:\n  spn_formatted, uiu_formatted, uhu_formatted, unk_formatted\n\nIn default, the output format is the same as the input format.\nTo generate formatted files with unformatted input, use option:\n  write_formatted\n\"\"\",\n        formatter_class=argparse.RawTextHelpFormatter,\n    )\n    parser.add_argument(\n        \"seedname\",\n        metavar=\"seedname\",\n        type=str,\n        help=\"Seedname of Wannier90 files.\",\n    )\n    parser.add_argument(\n        \"-o\",\n        \"--output_seedname\",\n        type=str,\n        help=\"The seedname of output files. Default is input_seedname.gw\",\n    )\n    parser.add_argument(\n        \"-e\",\n        \"--extensions\",\n        type=str,\n        help=(\n            \"Comma separated list of file extensions to be converted, \"\n            \"e.g. `-e amn,mmn` will only convert seedname.amn and seedname.mmn files. \"\n            \"If nothing provided, all files will be converted.\"\n        ),\n    )\n    parser.add_argument(\n        \"--no_sort\",\n        action=\"store_true\",\n        help=\"No sorting, only add GW corrections to eig.\",\n    )\n\n    parsed_args = parser.parse_args(args)\n\n    return parsed_args\n\n\ndef get_path_to_executable(executable: str) -> str:\n    \"\"\"Get path to local executable.\n    :param executable: Name of executable in the $PATH variable\n    :type executable: str\n    :return: path to executable\n    :rtype: str\n    \"\"\"\n    path = shutil.which(executable)\n    if path is None:\n        raise ValueError(f\"'{executable}' executable not found in PATH.\")\n    return path\n\n\n@dataclass\nclass Chk:\n    \"\"\"Class for storing matrices in seedname.chk file.\"\"\"\n\n    header: str = None\n    num_bands: int = None\n    num_exclude_bands: int = None\n    exclude_bands: np.ndarray = None\n    real_lattice: np.ndarray = None\n    recip_lattice: np.ndarray = None\n    num_kpts: int = None\n    mp_grid: list = None\n    kpt_latt: np.ndarray = None\n    nntot: int = None\n    num_wann: int = None\n    checkpoint: str = None\n    have_disentangled: bool = None\n    omega_invariant: float = None\n    lwindow: np.ndarray = None\n    ndimwin: np.ndarray = None\n    u_matrix_opt: np.ndarray = None\n    u_matrix: np.ndarray = None\n    m_matrix: np.ndarray = None\n    wannier_centres: np.ndarray = None\n    wannier_spreads: np.ndarray = None\n\n    def __eq__(self, other):\n        if not isinstance(other, Chk):\n            return NotImplemented(f\"comparing {self} {other}\")\n\n        if other is self:\n            return True\n\n        eq = True\n\n        eq = self.header == other.header\n        if not eq:\n            return False\n\n        eq = self.num_bands == other.num_bands\n        if not eq:\n            return False\n\n        eq = self.num_exclude_bands == other.num_exclude_bands\n        if not eq:\n            return False\n\n        eq = np.allclose(self.exclude_bands, other.exclude_bands)\n        if not eq:\n            return False\n\n        eq = np.allclose(self.real_lattice, other.real_lattice)\n        if not eq:\n            return False\n\n        eq = np.allclose(self.recip_lattice, other.recip_lattice)\n        if not eq:\n            return False\n\n        eq = self.num_kpts == other.num_kpts\n        if not eq:\n            return False\n\n        eq = np.allclose(self.mp_grid, other.mp_grid)\n        if not eq:\n            return False\n\n        eq = np.allclose(self.kpt_latt, other.kpt_latt)\n        if not eq:\n            return False\n\n        eq = self.nntot == other.nntot\n        if not eq:\n            return False\n\n        eq = self.num_wann == other.num_wann\n        if not eq:\n            return False\n\n        eq = self.checkpoint == other.checkpoint\n        if not eq:\n            return False\n\n        eq = self.have_disentangled == other.have_disentangled\n        if not eq:\n            return False\n\n        eq = np.allclose(self.omega_invariant, other.omega_invariant)\n        if not eq:\n            return False\n\n        eq = np.allclose(self.lwindow, other.lwindow)\n        if not eq:\n            return False\n\n        eq = np.allclose(self.ndimwin, other.ndimwin)\n        if not eq:\n            return False\n\n        eq = np.allclose(self.u_matrix_opt, other.u_matrix_opt)\n        if not eq:\n            return False\n\n        eq = np.allclose(self.u_matrix, other.u_matrix)\n        if not eq:\n            return False\n\n        eq = np.allclose(self.m_matrix, other.m_matrix)\n        if not eq:\n            return False\n\n        eq = np.allclose(self.wannier_centres, other.wannier_centres)\n        if not eq:\n            return False\n\n        eq = np.allclose(self.wannier_spreads, other.wannier_spreads)\n        if not eq:\n            return False\n\n        return True\n\n\ndef read_chk(filename: str, formatted: bool = None, keep_temp: bool = False) -> Chk:\n    \"\"\"Read seedname.chk file.\n\n    :param filename: filename\n    :type filename: str\n    :param formatted: defaults to None, auto detect from filename.\n    :type formatted: bool, optional\n    :param keep_temp: for unformatted file, creat a tempdir and run w90chk2chk.x\n    in it. If True, do not remove this tempdir. Defaults to False\n    :type keep_temp: bool, optional\n    :return: Chk\n    :rtype: Chk\n    \"\"\"\n    import pathlib\n    import tempfile\n\n    chk = Chk()\n\n    # From str to pathlib.Path\n    filename = pathlib.Path(filename)\n\n    if formatted is None:\n        if filename.name.endswith(\".chk\"):\n            formatted = False\n        elif filename.name.endswith(\".chk.fmt\"):\n            formatted = True\n        else:\n            raise ValueError(f\"Cannot detect the format of {filename}\")\n\n    valid_exts = [\".chk\", \".chk.fmt\"]\n    for ext in valid_exts:\n        if filename.name.endswith(ext):\n            seedname = filename.name[: -len(ext)]\n            break\n    else:\n        raise ValueError(f\"{filename} not ends with {valid_exts}?\")\n\n    if not formatted:\n        w90chk2chk = get_path_to_executable(\"w90chk2chk.x\")\n        tmpdir = pathlib.Path(tempfile.mkdtemp(dir=\".\"))\n        # cd tmpdir so that `w90chk2chk.log` is inside tmpdir\n        os.chdir(tmpdir)\n        if filename.root == \"/\":\n            os.symlink(filename, filename.name)\n        else:\n            os.symlink(pathlib.Path(\"..\") / filename, filename.name)\n        call_args = [w90chk2chk, \"-export\", str(seedname)]\n        # Some times need mpirun -n 1\n        # call_args = ['mpirun', '-n', '1'] + call_args\n        subprocess.check_call(call_args)\n        os.chdir(\"..\")\n        filename_fmt = f\"{tmpdir / filename.name}.fmt\"\n    else:\n        filename_fmt = filename\n\n    # Read formatted chk file\n    with open(filename_fmt) as handle:\n        #\n        chk.header = handle.readline().strip()\n        #\n        chk.num_bands = int(handle.readline().strip())\n        #\n        chk.num_exclude_bands = int(handle.readline().strip())\n        #\n        chk.exclude_bands = np.zeros(chk.num_exclude_bands, dtype=int)\n        #\n        if chk.num_exclude_bands > 0:\n            # line = handle.readline().strip().split()\n            # chk.exclude_bands[:] = [int(_) for _ in line]\n            for i in range(chk.num_exclude_bands):\n                line = handle.readline().strip()\n                chk.exclude_bands[i] = int(line)\n        # Just store as a 1D array\n        chk.real_lattice = np.zeros(9)\n        line = handle.readline().strip().split()\n        chk.real_lattice[:] = [float(_) for _ in line]\n        #\n        chk.recip_lattice = np.zeros(9)\n        line = handle.readline().strip().split()\n        chk.recip_lattice[:] = [float(_) for _ in line]\n        #\n        chk.num_kpts = int(handle.readline().strip())\n        #\n        chk.mp_grid = [int(_) for _ in handle.readline().strip().split()]\n        #\n        chk.kpt_latt = np.zeros((3, chk.num_kpts))\n        for ik in range(chk.num_kpts):\n            chk.kpt_latt[:, ik] = [float(_) for _ in handle.readline().strip().split()]\n        #\n        chk.nntot = int(handle.readline().strip())\n        #\n        chk.num_wann = int(handle.readline().strip())\n        #\n        chk.checkpoint = handle.readline().strip()\n        # 1 -> True, 0 -> False\n        chk.have_disentangled = bool(handle.readline().strip())\n        if chk.have_disentangled:\n            #\n            chk.omega_invariant = float(handle.readline().strip())\n            #\n            chk.lwindow = np.zeros((chk.num_bands, chk.num_kpts), dtype=bool)\n            for ik in range(chk.num_kpts):\n                for ib in range(chk.num_bands):\n                    # 1 -> True, 0 -> False\n                    chk.lwindow[ib, ik] = bool(int(handle.readline().strip()))\n            #\n            chk.ndimwin = np.zeros(chk.num_kpts, dtype=int)\n            for ik in range(chk.num_kpts):\n                chk.ndimwin[ik] = int(handle.readline().strip())\n            #\n            chk.u_matrix_opt = np.zeros(\n                (chk.num_bands, chk.num_wann, chk.num_kpts), dtype=complex\n            )\n            for ik in range(chk.num_kpts):\n                for iw in range(chk.num_wann):\n                    for ib in range(chk.num_bands):\n                        line = [float(_) for _ in handle.readline().strip().split()]\n                        chk.u_matrix_opt[ib, iw, ik] = line[0] + 1j * line[1]\n        #\n        chk.u_matrix = np.zeros(\n            (chk.num_wann, chk.num_wann, chk.num_kpts), dtype=complex\n        )\n        for ik in range(chk.num_kpts):\n            for iw in range(chk.num_wann):\n                for ib in range(chk.num_wann):\n                    line = [float(_) for _ in handle.readline().strip().split()]\n                    chk.u_matrix[ib, iw, ik] = line[0] + 1j * line[1]\n        #\n        chk.m_matrix = np.zeros(\n            (chk.num_wann, chk.num_wann, chk.nntot, chk.num_kpts), dtype=complex\n        )\n        for ik in range(chk.num_kpts):\n            for inn in range(chk.nntot):\n                for iw in range(chk.num_wann):\n                    for ib in range(chk.num_wann):\n                        line = [float(_) for _ in handle.readline().strip().split()]\n                        chk.m_matrix[ib, iw, inn, ik] = line[0] + 1j * line[1]\n        #\n        chk.wannier_centres = np.zeros((3, chk.num_wann), dtype=float)\n        for iw in range(chk.num_wann):\n            chk.wannier_centres[:, iw] = [\n                float(_) for _ in handle.readline().strip().split()\n            ]\n        #\n        chk.wannier_spreads = np.zeros(chk.num_wann, dtype=float)\n        for iw in range(chk.num_wann):\n            chk.wannier_spreads[iw] = float(handle.readline().strip())\n\n    # Read binary chk file, however its compiler dependent,\n    # and it seems scipy.io.FortranFile cannot handle bool type?\n    #\n    #     handle = FortranFile(filename, \"r\")\n    #     #\n    #     chk.header = b\"\".join(handle.read_record(dtype=\"c\"))\n    #     #\n    #     chk.num_bands = handle.read_record(dtype=np.int32).item()\n    #     #\n    #     chk.num_exclude_bands = handle.read_record(dtype=np.int32).item()\n    #     #\n    #     chk.exclude_bands = np.zeros(chk.num_exclude_bands, dtype=int)\n    #     #\n    #     if chk.num_exclude_bands > 0:\n    #         line = handle.read_record(dtype=np.int32).reshape(chk.num_exclude_bands)\n    #         chk.exclude_bands[:] = line[:]\n    #     else:\n    #         # read empty record\n    #         handle.read_record(dtype=np.int32)\n    #     # Just store as a 1D array\n    #     chk.real_lattice = np.zeros(9)\n    #     line = handle.read_record(dtype=np.float64).reshape(9)\n    #     chk.real_lattice[:] = line[:]\n    #     #\n    #     chk.recip_lattice = np.zeros(9)\n    #     line = handle.read_record(dtype=float).reshape(9)\n    #     chk.recip_lattice[:] = line[:]\n    #     #\n    #     chk.num_kpts = handle.read_record(dtype=np.int32).item()\n    #     #\n    #     chk.mp_grid = handle.read_record(dtype=np.int32).reshape(3).tolist()\n    #     #\n    #     chk.kpt_latt = np.zeros((3, chk.num_kpts))\n    #     line = handle.read_record(dtype=float).reshape((3, chk.num_kpts), order='F')\n    #     chk.kpt_latt[:, :] = line[:, :]\n    #     #\n    #     chk.nntot = handle.read_record(dtype=np.int32).item()\n    #     #\n    #     chk.num_wann = handle.read_record(dtype=np.int32).item()\n    #     #\n    #     chk.checkpoint = b\"\".join(handle.read_record(dtype=\"c\"))\n    #     # 1 -> True, 0 -> False\n    #     chk.have_disentangled = bool(handle.read_record(dtype=np.int32))\n    #     if chk.have_disentangled:\n    #         #\n    #         chk.omega_invariant = handle.read_record(dtype=float).item()\n    #         #\n    #         chk.lwindow = np.zeros((chk.num_bands, chk.num_kpts), dtype=bool)\n    #         line = handle.read_record(dtype=np.int32)\n    #         line = line.reshape((chk.num_bands, chk.num_kpts), order='F')\n    #         chk.lwindow[:, :] = line[:, :]\n    #         #\n    #         chk.ndimwin = np.array(chk.num_kpts, dtype=int)\n    #         line = handle.read_record(dtype=int).reshape(chk.num_kpts)\n    #         chk.ndimwin[:] = line[:]\n    #         #\n    #         chk.u_matrix_opt = np.array((chk.num_bands, chk.num_wann, chk.num_kpts), dtype=complex)\n    #         line = handle.read_record(dtype=complex).reshape((chk.num_bands, chk.num_wann, chk.num_kpts), order='F')\n    #         chk.u_matrix_opt[:, :, :] = line[:, :, :]\n    #     #\n    #     chk.u_matrix = np.array((chk.num_wann, chk.num_wann, chk.num_kpts), dtype=complex)\n    #     line = handle.read_record(dtype=complex).reshape((chk.num_wann, chk.num_wann, chk.num_kpts), order='F')\n    #     chk.u_matrix[:, :, :] = line[:, :, :]\n    #     #\n    #     chk.m_matrix = np.array((chk.num_wann, chk.num_wann, chk.nntot, chk.num_kpts), dtype=complex)\n    #     line = handle.read_record(dtype=complex).reshape((chk.num_wann, chk.num_wann, chk.nntot, chk.num_kpts), order='F')\n    #     chk.m_matrix[:, :, :, :] = line[:, :, :, :]\n    #     #\n    #     chk.wannier_centres = np.array((3, chk.num_wann), dtype=float)\n    #     line = handle.read_record(dtype=float).reshape((3, chk.num_wann), order='F')\n    #     chk.wannier_centres[:, :] = line[:, :]\n    #     #\n    #     chk.wannier_spreads = np.array(chk.num_wann, dtype=float)\n    #     line = handle.read_record(dtype=float).reshape(chk.num_wann)\n    #     chk.wannier_spreads[:] = line[:]\n    #     #\n    #     handle.close()\n\n    if not formatted:\n        if not keep_temp:\n            shutil.rmtree(tmpdir)\n\n    return chk\n\n\ndef write_chk(\n    chk: Chk, filename: str, formatted: bool = None, keep_temp: bool = False\n) -> None:\n    \"\"\"Write chk file.\n\n    :param chk: _description_\n    :type chk: Chk\n    :param filename: output filename\n    :type filename: str\n    :param formatted: defaults to None, i.e. auto detect by filename\n    :type formatted: bool, optional\n    :param keep_temp: _description_, defaults to False\n    :type keep_temp: bool, optional\n    \"\"\"\n    import pathlib\n    import tempfile\n\n    # From str to pathlib.Path\n    filename = pathlib.Path(filename)\n\n    if formatted is None:\n        if filename.name.endswith(\".chk\"):\n            formatted = False\n        elif filename.name.endswith(\".chk.fmt\"):\n            formatted = True\n        else:\n            raise ValueError(f\"Cannot detect the format of {filename}\")\n\n    valid_exts = [\".chk\", \".chk.fmt\"]\n    for ext in valid_exts:\n        if filename.name.endswith(ext):\n            seedname = filename.name[: -len(ext)]\n            break\n    else:\n        raise ValueError(f\"{filename} not ends with {valid_exts}?\")\n\n    if not formatted:\n        tmpdir = pathlib.Path(tempfile.mkdtemp(dir=\".\"))\n        filename_fmt = f\"{tmpdir / filename.name}.fmt\"\n    else:\n        filename_fmt = filename\n\n    # Write formatted chk file\n    with open(filename_fmt, \"w\") as handle:\n        #\n        handle.write(f\"{chk.header}\\n\")\n        #\n        handle.write(f\"{chk.num_bands}\\n\")\n        #\n        handle.write(f\"{chk.num_exclude_bands}\\n\")\n        #\n        if chk.num_exclude_bands > 0:\n            # line = \" \".join([str(_) for _ in chk.exclude_bands])\n            # handle.write(f\"{line}\\n\")\n            for i in range(chk.num_exclude_bands):\n                line = f\"{chk.exclude_bands[i]}\"\n                handle.write(f\"{line}\\n\")\n        # Just store as a 1D array\n        line = \" \".join([f\"{_:22.16f}\" for _ in chk.real_lattice])\n        handle.write(f\"{line}\\n\")\n        #\n        line = \" \".join([f\"{_:22.16f}\" for _ in chk.recip_lattice])\n        handle.write(f\"{line}\\n\")\n        #\n        handle.write(f\"{chk.num_kpts}\\n\")\n        #\n        line = \" \".join([f\"{_}\" for _ in chk.mp_grid])\n        handle.write(f\"{line}\\n\")\n        #\n        for ik in range(chk.num_kpts):\n            line = \" \".join([f\"{_:22.16f}\" for _ in chk.kpt_latt[:, ik]])\n            handle.write(f\"{line}\\n\")\n        #\n        handle.write(f\"{chk.nntot}\\n\")\n        #\n        handle.write(f\"{chk.num_wann}\\n\")\n        #\n        handle.write(f\"{chk.checkpoint}\\n\")\n        # 1 -> True, 0 -> False\n        line = 1 if chk.have_disentangled else 0\n        handle.write(f\"{line}\\n\")\n        if chk.have_disentangled:\n            #\n            handle.write(f\"{chk.omega_invariant:22.16f}\\n\")\n            #\n            for ik in range(chk.num_kpts):\n                for ib in range(chk.num_bands):\n                    # 1 -> True, 0 -> False\n                    line = 1 if chk.lwindow[ib, ik] else 0\n                    handle.write(f\"{line}\\n\")\n            #\n            for ik in range(chk.num_kpts):\n                handle.write(f\"{chk.ndimwin[ik]}\\n\")\n            #\n            for ik in range(chk.num_kpts):\n                for iw in range(chk.num_wann):\n                    for ib in range(chk.num_bands):\n                        line = chk.u_matrix_opt[ib, iw, ik]\n                        line = \" \".join([f\"{_:22.16f}\" for _ in [line.real, line.imag]])\n                        handle.write(f\"{line}\\n\")\n        #\n        for ik in range(chk.num_kpts):\n            for iw in range(chk.num_wann):\n                for ib in range(chk.num_wann):\n                    line = chk.u_matrix[ib, iw, ik]\n                    line = \" \".join([f\"{_:22.16f}\" for _ in [line.real, line.imag]])\n                    handle.write(f\"{line}\\n\")\n        #\n        for ik in range(chk.num_kpts):\n            for inn in range(chk.nntot):\n                for iw in range(chk.num_wann):\n                    for ib in range(chk.num_wann):\n                        line = chk.m_matrix[ib, iw, inn, ik]\n                        line = \" \".join([f\"{_:22.16f}\" for _ in [line.real, line.imag]])\n                        handle.write(f\"{line}\\n\")\n        #\n        for iw in range(chk.num_wann):\n            line = \" \".join([f\"{_:22.16f}\" for _ in chk.wannier_centres[:, iw]])\n            handle.write(f\"{line}\\n\")\n        #\n        for iw in range(chk.num_wann):\n            line = f\"{chk.wannier_spreads[iw]:22.16f}\"\n            handle.write(f\"{line}\\n\")\n\n    if not formatted:\n        w90chk2chk = get_path_to_executable(\"w90chk2chk.x\")\n        # cd tmpdir so that `w90chk2chk.log` is inside tmpdir\n        os.chdir(tmpdir)\n        call_args = [w90chk2chk, \"-import\", str(seedname)]\n        # Some times need mpirun -n 1\n        # call_args = ['mpirun', '-n', '1'] + call_args\n        subprocess.check_call(call_args)\n        os.chdir(\"..\")\n        shutil.copy(tmpdir / f\"{seedname}.chk\", filename.name)\n\n        if not keep_temp:\n            shutil.rmtree(tmpdir)\n\n\ndef reorder_chk(seedname_in: str, seedname_out: str, bandsort: np.ndarray) -> None:\n    print(\"----------\\n CHK module  \\n----------\")\n    filename_in = f\"{seedname_in}.chk\"\n    filename_out = f\"{seedname_out}.chk\"\n\n    if not os.path.exists(filename_in):\n        print(f\"WARNING: {filename_out} not written\")\n        return\n\n    chk = read_chk(filename_in, formatted=False)\n\n    # if chk.num_exclude_bands > 0:\n    #     # chk.exclude_bands =\n    #     # raise NotImplementedError(\"does not support exclude bands\")\n\n    if chk.have_disentangled:\n        for ik in range(chk.num_kpts):\n            chk.lwindow[:, ik] = chk.lwindow[bandsort[ik], ik]\n            chk.u_matrix_opt[:, :, ik] = chk.u_matrix_opt[bandsort[ik], :, ik]\n    else:\n        chk.u_matrix[:, :, ik] = chk.u_matrix[bandsort[ik], :, ik]\n\n    write_chk(chk, filename_out, formatted=False)\n\n    print(\"----------\\n CHK  - OK \\n----------\\n\")\n\n\ndef _test_chk():\n    import os\n    import pathlib\n\n    from gw2wannier90 import read_chk, write_chk\n\n    PATH = os.environ[\"PATH\"]\n    w90_path = \"/home/jqiao/git/wannier90\"\n    os.environ[\"PATH\"] = f\"{w90_path}:{PATH}\"\n\n    LD_LIBRARY_PATH = os.environ.get(\"LD_LIBRARY_PATH\", \"\")\n    mkl_path = \"/opt/intel/oneapi/mpi/2021.4.0/libfabric/lib:/opt/intel/oneapi/mpi/2021.4.0/lib/release:/opt/intel/oneapi/mpi/2021.4.0/lib:/opt/intel/oneapi/mkl/2021.4.0/lib/intel64:/opt/intel/oneapi/compiler/2021.4.0/linux/lib:/opt/intel/oneapi/compiler/2021.4.0/linux/lib/x64:/opt/intel/oneapi/compiler/2021.4.0/linux/lib/emu:/opt/intel/oneapi/compiler/2021.4.0/linux/compiler/lib/intel64_lin\"\n    os.environ[\"LD_LIBRARY_PATH\"] = f\"{mkl_path}:{LD_LIBRARY_PATH}\"\n\n    curdir = pathlib.Path(__file__).parent\n\n    chk = read_chk(curdir / \"read_chk/silicon.chk\")\n\n    write_chk(chk, curdir / \"osilicon.chk.fmt\", formatted=True)\n\n    chk2 = read_chk(curdir / \"osilicon.chk.fmt\")\n\n    write_chk(chk2, curdir / \"osilicon.chk\")\n\n    print(chk == chk2)\n\n\ndef gw2wannier90(\n    seedname: str, seednameGW: str, targets: list, no_sort: bool = False\n) -> None:\n    print(\"------------------------------\")\n    print(\"##############################\")\n    print(\"### gw2wannier90 interface ###\")\n    print(\"##############################\")\n    print(f\"Started on {datetime.datetime.now()}\")\n\n    # In case of formatted spn, uIu, uHu and UNK (mmn, amn, eig are formatted by default)\n    # NB: Formatted output is strongly reccommended! Fortran binaries are compilers dependent.\n    SPNformatted = \"spn_formatted\" in targets\n    UIUformatted = \"uiu_formatted\" in targets\n    UHUformatted = \"uhu_formatted\" in targets\n    UNKformatted = \"unk_formatted\" in targets\n    write_formatted = \"write_formatted\" in targets\n\n    if set(targets).intersection({\"spn\", \"uhu\", \"mmn\", \"amn\", \"unk\", \"uiu\", \"chk\"}):\n        calcAMN = \"amn\" in targets\n        calcMMN = \"mmn\" in targets\n        calcUHU = \"uhu\" in targets\n        calcUIU = \"uiu\" in targets\n        calcSPN = \"spn\" in targets\n        calcUNK = \"unk\" in targets\n        calcCHK = \"chk\" in targets\n    else:\n        calcAMN = True\n        calcMMN = True\n        calcUHU = True\n        calcUIU = True\n        calcSPN = True\n        calcUNK = True\n        calcCHK = True\n\n    if calcUHU:\n        calcMMN = True\n    if calcUIU:\n        calcMMN = True\n\n    if no_sort:\n        calcAMN = False\n        calcMMN = False\n        calcUHU = False\n        calcUIU = False\n        calcSPN = False\n        calcUNK = False\n        calcCHK = False\n\n    # Here we open a file to dump all the intermediate steps (mainly for debugging)\n    f_raw = open(seednameGW + \".gw2wannier90.raw\", \"w\")\n    # Opening seedname.nnkp file\n    f = open(seedname + \".nnkp\")\n    # It copies the seedname.win for GW, we should make this optional\n    # shutil.copy(seedname+\".win\",seednameGW+\".win\")\n    while True:\n        s = f.readline()\n        if \"begin kpoints\" in s:\n            break\n    NKPT = int(f.readline())\n    print(\"Kpoints number:\", NKPT)\n    n1 = np.array(NKPT, dtype=int)\n    IKP = [\n        tuple(\n            np.array(\n                np.round(np.array(f.readline().split(), dtype=float) * n1), dtype=int\n            )\n        )\n        for i in range(NKPT)\n    ]\n\n    while True:\n        s = f.readline()\n        if \"begin nnkpts\" in s:\n            break\n    NNB = int(f.readline())\n\n    KPNB = np.array(\n        [\n            [int(f.readline().split()[1]) - 1 for inb in range(NNB)]\n            for ikpt in range(NKPT)\n        ]\n    )\n\n    while True:\n        s = f.readline()\n        if \"begin exclude_bands\" in s:\n            break\n    exbands = np.array(f.readline().split(), dtype=int)\n    if len(exbands) > 1 or exbands[0] != 0:\n        print(\n            \"Exclude bands option is used: be careful to be consistent \"\n            \"with the choice of bands for the GW QP corrections.\"\n        )\n        nexbands = exbands[0]\n        exbands = np.zeros(nexbands, dtype=int)\n        for i in range(nexbands):\n            exbands[i] = int(f.readline().strip())\n        # 0-based indexing\n        exbands -= 1\n    else:\n        exbands = np.array([], dtype=int)\n\n    eigenDFT = np.loadtxt(seedname + \".eig\")\n    nk = int(eigenDFT[:, 1].max())\n    assert nk == NKPT\n    nbndDFT = int(eigenDFT[:, 0].max())\n    eigenDFT = eigenDFT[:, 2].reshape(NKPT, nbndDFT, order=\"C\")\n    # print(eigenDFT)\n    f_raw.write(\"------------------------------\\n\")\n    f_raw.write(\"Writing DFT eigenvalues\\n\")\n    for line in eigenDFT:\n        f_raw.write(str(line) + \"\\n\")\n    f_raw.write(\"------------------------------\\n\")\n\n    corrections = np.loadtxt(seedname + \".gw.unsorted.eig\")\n    # Indexing with dict is too slow, use np.array instead.\n    # corrections = {(int(l[1]) - 1, int(l[0]) - 1): l[2] for l in corrections}\n    # print(corrections)\n    corrections_val = np.zeros((nk, nbndDFT + len(exbands)))\n    corrections_mask = np.zeros_like(corrections_val, dtype=bool)\n    idx_b = corrections[:, 0].astype(int) - 1\n    idx_k = corrections[:, 1].astype(int) - 1\n    corrections_val[idx_k, idx_b] = corrections[:, 2]\n    corrections_mask[idx_k, idx_b] = True\n    # Strip excluded bands\n    if len(exbands) > 0:\n        corrections_val = np.delete(corrections_val, exbands, axis=1)\n        corrections_mask = np.delete(corrections_mask, exbands, axis=1)\n    print(\"G0W0 QP corrections read from \", seedname + \".gw.unsorted.eig\")\n\n    # providedGW = [\n    #     ib\n    #     for ib in range(nbndDFT)\n    #     if all((ik, ib) in list(corrections.keys()) for ik in range(NKPT))\n    # ]\n    providedGW = [ib for ib in range(nbndDFT) if np.all(corrections_mask[:, ib])]\n    # print(providedGW)\n    f_raw.write(\"------------------------------\\n\")\n    f_raw.write(\"List of provided GW corrections (bands indexes)\\n\")\n    f_raw.write(str(providedGW) + \"\\n\")\n    f_raw.write(\"------------------------------\\n\")\n    NBND = len(providedGW)\n    print(\"Adding GW QP corrections to KS eigenvalues\")\n    # eigenDE = np.array(\n    #     [[corrections[(ik, ib)] for ib in providedGW] for ik in range(NKPT)]\n    # )\n    # eigenDFTGW = np.array(\n    #     [\n    #         [eigenDFT[ik, ib] + corrections[(ik, ib)] for ib in providedGW]\n    #         for ik in range(NKPT)\n    #     ]\n    # )\n    eigenDE = corrections_val[:, providedGW]\n    eigenDFTGW = eigenDFT[:, providedGW] + eigenDE\n\n    f_raw.write(\"------------------------------\\n\")\n    f_raw.write(\"Writing GW eigenvalues unsorted (KS + QP correction)\\n\")\n    for line in eigenDFTGW:\n        f_raw.write(str(line) + \"\\n\")\n    f_raw.write(\"------------------------------\\n\")\n\n    if no_sort:\n        print(\"No sorting\")\n    else:\n        print(\"Sorting\")\n    bsort = np.array([np.argsort(eigenDFTGW[ik, :]) for ik in range(NKPT)])\n\n    # Even if no_sort, I still output sorting list for reference\n    f_raw.write(\"------------------------------\\n\")\n    f_raw.write(\"Writing sorting list\\n\")\n    for line in bsort:\n        f_raw.write(str(line) + \"\\n\")\n    f_raw.write(\"------------------------------\\n\")\n\n    if not no_sort:\n        eigenDE = np.array([eigenDE[ik][bsort[ik]] for ik in range(NKPT)])\n        eigenDFTGW = np.array([eigenDFTGW[ik][bsort[ik]] for ik in range(NKPT)])\n        BANDSORT = np.array([np.array(providedGW)[bsort[ik]] for ik in range(NKPT)])\n\n        f_raw.write(\"------------------------------\\n\")\n        f_raw.write(\"Writing sorted GW eigenvalues\\n\")\n        for line in eigenDFTGW:\n            f_raw.write(str(line) + \"\\n\")\n        f_raw.write(\"------------------------------\\n\")\n\n        print(\"GW eigenvalues sorted\")\n\n    # print eigenDFT\n    print(\"------------------------------\")\n    print(\"writing \" + seednameGW + \".eig\")\n    feig_out = open(seednameGW + \".eig\", \"w\")\n    for ik in range(NKPT):\n        for ib in range(NBND):\n            feig_out.write(f\" {ib + 1:4d} {ik + 1:4d} {eigenDFTGW[ik, ib]:17.12f}\\n\")\n    feig_out.close()\n    print(seednameGW + \".eig\", \" written.\")\n    print(\"------------------------------\\n\")\n\n    if calcAMN:\n        try:\n            print(\"----------\\n AMN module  \\n----------\")\n            f_amn_out = open(seednameGW + \".amn\", \"w\")\n            f_amn_in = open(seedname + \".amn\")\n            s = f_amn_in.readline().strip()\n            print(s)\n            f_amn_out.write(\n                \"{}, sorted by GW quasi-particle energies on {} \\n\".format(\n                    s, datetime.datetime.now().isoformat()\n                )\n            )\n            s = f_amn_in.readline()\n            nb, nk, npr = np.array(s.split(), dtype=int)\n            assert nk == NKPT\n            assert nb == nbndDFT\n            f_amn_out.write(f\"  {NBND}   {nk}    {npr}   \\n\")\n\n            AMN = np.loadtxt(f_amn_in, dtype=float)[:, 3:5]\n            AMN = np.reshape(AMN[:, 0] + AMN[:, 1] * 1j, (nb, npr, nk), order=\"F\")\n            for ik in range(nk):\n                amn = AMN[BANDSORT[ik], :, ik]\n                for ipr in range(npr):\n                    for ib in range(NBND):\n                        f_amn_out.write(\n                            \" {:4d} {:4d} {:4d}  {:16.12f}  {:16.12f}\\n\".format(\n                                ib + 1,\n                                ipr + 1,\n                                ik + 1,\n                                amn[ib, ipr].real,\n                                amn[ib, ipr].imag,\n                            )\n                        )\n            f_amn_in.close()\n            f_amn_out.close()\n            print(\"----------\\n AMN  - OK \\n----------\\n\")\n        except OSError as err:\n            print(f\"WARNING: {seednameGW}.amn not written : \", err)\n\n    if calcMMN:\n        try:\n            print(\"----------\\n MMN module  \\n----------\")\n\n            f_mmn_out = open(os.path.join(seednameGW + \".mmn\"), \"w\")\n            f_mmn_in = open(os.path.join(seedname + \".mmn\"))\n\n            s = f_mmn_in.readline().strip()\n            print(s)\n            f_mmn_out.write(\n                \"{}, sorted by GW quasi-particle energies on {} \\n\".format(\n                    s, datetime.datetime.now().isoformat()\n                )\n            )\n            s = f_mmn_in.readline()\n            nb, nk, nnb = np.array(s.split(), dtype=int)\n            assert nb == nbndDFT\n            assert nk == NKPT\n            f_mmn_out.write(f\"    {NBND}   {nk}    {nnb} \\n\")\n\n            MMN = np.zeros((nk, nnb, NBND, NBND), dtype=complex)\n            for ik in range(nk):\n                for ib in range(nnb):\n                    s = f_mmn_in.readline()\n                    f_mmn_out.write(s)\n                    ik1, ik2 = (int(i) - 1 for i in s.split()[:2])\n                    assert ik == ik1\n                    assert KPNB[ik][ib] == ik2\n                    tmp = np.array(\n                        [\n                            [f_mmn_in.readline().split() for m in range(nb)]\n                            for n in range(nb)\n                        ],\n                        dtype=str,\n                    )\n                    tmp = np.array(\n                        tmp[BANDSORT[ik2], :, :][:, BANDSORT[ik1], :], dtype=float\n                    )\n                    tmp = (tmp[:, :, 0] + 1j * tmp[:, :, 1]).T\n                    MMN[ik, ib, :, :] = tmp\n                    for n in range(NBND):\n                        for m in range(NBND):\n                            f_mmn_out.write(\n                                \"  {:16.12f}  {:16.12f}\\n\".format(\n                                    tmp[m, n].real, tmp[m, n].imag\n                                )\n                            )\n            print(\"----------\\n MMN OK  \\n----------\\n\")\n        except OSError as err:\n            print(f\"WARNING: {seednameGW}.mmn not written : \", err)\n            if calcUHU:\n                print(f\"WARNING: {seednameGW}.uHu file also will not be written : \")\n                calcUHU = False\n\n    def reorder_uXu(ext, formatted=False):\n        try:\n            print(f\"----------\\n {ext} module  \\n----------\")\n\n            if formatted:\n                f_uXu_in = open(seedname + \".\" + ext)\n                f_uXu_out = open(seednameGW + \".\" + ext, \"w\")\n                header = f_uXu_in.readline()\n                f_uXu_out.write(header)\n                nbnd, NK, nnb = np.array(f_uXu_in.readline().split(), dtype=int)\n                f_uXu_out.write(\"  \".join(str(x) for x in [NBND, NK, nnb]) + \"\\n\")\n            else:\n                f_uXu_in = FortranFile(seedname + \".\" + ext, \"r\")\n                header = f_uXu_in.read_record(dtype=\"c\")\n                nbnd, NK, nnb = np.array(f_uXu_in.read_record(dtype=np.int32))\n                if write_formatted:\n                    f_uXu_out = open(seednameGW + \".\" + ext, \"w\")\n                    f_uXu_out.write(\"\".join(header.astype(str)))\n                    f_uXu_out.write(\"\\n\")\n                    f_uXu_out.write(\"  \".join(str(x) for x in [NBND, NK, nnb]))\n                    f_uXu_out.write(\"\\n\")\n                else:\n                    f_uXu_out = FortranFile(seednameGW + \".\" + ext, \"w\")\n                    f_uXu_out.write_record(header)\n                    f_uXu_out.write_record(np.array([NBND, NK, nnb], dtype=np.int32))\n                header = \"\".join(header.astype(str))\n\n            print(header.strip())\n            print(nbnd, NK, nnb)\n\n            assert nbnd == nbndDFT\n\n            if formatted:\n                uXu = np.loadtxt(f_uXu_in).reshape(-1)\n                start = 0\n                length = nbnd * nbnd\n\n            for ik in range(NKPT):\n                for ib2 in range(nnb):\n                    for ib1 in range(nnb):\n                        if formatted:\n                            A = uXu[start : start + length]\n                            start += length\n                        else:\n                            A = f_uXu_in.read_record(dtype=np.complex)\n                        A = (\n                            A.reshape(nbnd, nbnd, order=\"F\")[\n                                BANDSORT[KPNB[ik][ib2]], :\n                            ][:, BANDSORT[KPNB[ik][ib1]]]\n                            + np.einsum(\n                                \"ln,lm,l->nm\",\n                                MMN[ik][ib2].conj(),\n                                MMN[ik][ib1],\n                                eigenDE[ik],\n                            )\n                        ).reshape(-1, order=\"F\")\n                        if formatted or write_formatted:\n                            f_uXu_out.write(\n                                \"\".join(\n                                    f\"{x.real:26.16e}  {x.imag:26.16e}\\n\" for x in A\n                                )\n                            )\n                        else:\n                            f_uXu_out.write_record(A)\n            f_uXu_out.close()\n            f_uXu_in.close()\n            print(f\"----------\\n {ext} OK  \\n----------\\n\")\n        except OSError as err:\n            print(f\"WARNING: {seednameGW}.{ext} not written : \", err)\n\n    if calcUHU:\n        reorder_uXu(\"uHu\", UHUformatted)\n    if calcUIU:\n        reorder_uXu(\"uIu\", UIUformatted)\n\n    if calcSPN:\n        try:\n            print(\"----------\\n SPN module  \\n----------\")\n\n            if SPNformatted:\n                f_spn_in = open(seedname + \".spn\")\n                f_spn_out = open(seednameGW + \".spn\", \"w\")\n                header = f_spn_in.readline()\n                f_spn_out.write(header)\n                nbnd, NK = np.array(f_spn_in.readline().split(), dtype=np.int32)\n                f_spn_out.write(\"  \".join(str(x) for x in (NBND, NKPT)))\n                f_spn_out.write(\"\\n\")\n            else:\n                f_spn_in = FortranFile(seedname + \".spn\", \"r\")\n                header = f_spn_in.read_record(dtype=\"c\")\n                nbnd, NK = f_spn_in.read_record(dtype=np.int32)\n                if write_formatted:\n                    f_spn_out = open(seednameGW + \".spn\", \"w\")\n                    f_spn_out.write(\"\".join(header.astype(str)))\n                    f_spn_out.write(\"\\n\")\n                    f_spn_out.write(\"  \".join(str(x) for x in (NBND, NKPT)))\n                    f_spn_out.write(\"\\n\")\n                else:\n                    f_spn_out = FortranFile(seednameGW + \".spn\", \"w\")\n                    f_spn_out.write_record(header)\n                    f_spn_out.write_record(np.array([NBND, NKPT], dtype=np.int32))\n                header = \"\".join(header.astype(str))\n\n            print(header.strip())\n            assert nbnd == nbndDFT\n\n            indm, indn = np.tril_indices(nbnd)\n            indmQP, indnQP = np.tril_indices(NBND)\n\n            if SPNformatted:\n                SPN = np.loadtxt(f_spn_in).view(complex).reshape(-1)\n                start = 0\n                length = (3 * nbnd * (nbnd + 1)) // 2\n\n            for ik in range(NK):\n                A = np.zeros((3, nbnd, nbnd), dtype=np.complex)\n                if SPNformatted:\n                    A[:, indn, indm] = SPN[start : (start + length)].reshape(\n                        3, nbnd * (nbnd + 1) // 2, order=\"F\"\n                    )\n                    start += length\n                else:\n                    A[:, indn, indm] = f_spn_in.read_record(dtype=np.complex).reshape(\n                        3, nbnd * (nbnd + 1) // 2, order=\"F\"\n                    )\n                A[:, indm, indn] = A[:, indn, indm].conj()\n                check = np.einsum(\"ijj->\", np.abs(A.imag))\n                if check > 1e-10:\n                    raise RuntimeError(f\"REAL DIAG CHECK FAILED for spn: {check}\")\n                A = A[:, :, BANDSORT[ik]][:, BANDSORT[ik], :][\n                    :, indnQP, indmQP\n                ].reshape((3 * NBND * (NBND + 1) // 2), order=\"F\")\n                if SPNformatted or write_formatted:\n                    f_spn_out.write(\n                        \"\".join(f\"{x.real:26.16e} {x.imag:26.16e}\\n\" for x in A)\n                    )\n                else:\n                    f_spn_out.write_record(A)\n\n            f_spn_in.close()\n            f_spn_out.close()\n            print(\"----------\\n SPN OK  \\n----------\\n\")\n        except OSError as err:\n            print(f\"WARNING: {seednameGW}.spn not written : \", err)\n\n    if calcUNK:\n        print(\"----------\\n UNK module  \\n----------\")\n\n        unkgwdir = \"UNK_GW\"\n        unkdftdir = \"UNK_DFT\"\n        files_list = []\n        for f_unk_name in glob.glob(\"UNK*.*\"):\n            files_list.append(f_unk_name)\n\n        try:\n            os.mkdir(unkgwdir)\n            os.mkdir(unkdftdir)\n        except OSError:\n            pass\n\n        for f_unk_name in files_list:\n            try:\n                NC = os.path.splitext(f_unk_name)[1] == \".NC\"\n                shutil.move(\"./\" + f_unk_name, \"./\" + unkdftdir + \"/\")\n                if UNKformatted:\n                    f_unk_out = open(os.path.join(unkgwdir, f_unk_name), \"w\")\n                    f_unk_in = open(os.path.join(unkdftdir, f_unk_name))\n                    nr1, nr2, nr3, ik, nbnd = np.array(\n                        f_unk_in.readline().split(), dtype=int\n                    )\n                    NR = nr1 * nr2 * nr3\n                    if NC:\n                        NR *= 2\n                    f_unk_out.write(\n                        \" \".join(str(x) for x in (nr1, nr2, nr3, ik, NBND)) + \"\\n\"\n                    )\n                    f_unk_out.write(\n                        \"\\n\".join(\n                            np.array([l.rstrip() for l in f_unk_in], dtype=str)\n                            .reshape((nbnd, NR), order=\"C\")[BANDSORT[ik - 1], :]\n                            .reshape(-1, order=\"C\")\n                        )\n                    )\n                else:\n                    f_unk_in = FortranFile(os.path.join(unkdftdir, f_unk_name), \"r\")\n                    nr1, nr2, nr3, ik, nbnd = f_unk_in.read_record(dtype=np.int32)\n                    NR = nr1 * nr2 * nr3\n                    unk = np.zeros((nbnd, NR), dtype=np.complex)\n                    if NC:\n                        unk2 = np.zeros((nbnd, NR), dtype=np.complex)\n                    for ib in range(nbnd):\n                        unk[ib, :] = f_unk_in.read_record(dtype=np.complex)\n                        if NC:\n                            unk2[ib, :] = f_unk_in.read_record(dtype=np.complex)\n                    unk = unk[BANDSORT[ik - 1], :]\n                    if NC:\n                        unk2 = unk2[BANDSORT[ik - 1], :]\n                    if write_formatted:\n                        f_unk_out = open(os.path.join(unkgwdir, f_unk_name), \"w\")\n                        f_unk_out.write(\n                            \" \".join(str(x) for x in (nr1, nr2, nr3, ik, NBND))\n                        )\n                        for i in range(NBND):\n                            for j in range(NR):\n                                f_unk_out.write(\n                                    \"\\n{:21.10e} {:21.10e}\".format(\n                                        unk[ib, j].real, unk[ib, j].imag\n                                    )\n                                )\n                            if NC:\n                                for j in range(NR):\n                                    f_unk_out.write(\n                                        \"\\n{:21.10e} {:21.10e}\".format(\n                                            unk2[ib, j].real, unk2[ib, j].imag\n                                        )\n                                    )\n                    else:\n                        f_unk_out = FortranFile(os.path.join(unkgwdir, f_unk_name), \"w\")\n                        f_unk_out.write_record(\n                            np.array([nr1, nr2, nr3, ik, NBND], dtype=np.int32)\n                        )\n                        for i in range(NBND):\n                            f_unk_out.write_record(unk[ib])\n                            if NC:\n                                f_unk_out.write_record(unk2[ib])\n                f_unk_in.close()\n                f_unk_out.close()\n                shutil.move(\"./\" + unkgwdir + \"/\" + f_unk_name, \"./\")\n            except OSError as err:\n                if err.errno == 21:\n                    pass\n                else:\n                    raise err\n        os.rmdir(unkgwdir)\n        print(\n            \"UNK files have been reordered, \"\n            + \"old files coming from DFT are available in UNK_DFT folder.\"\n        )\n        print(\"----------\\n UNK OK  \\n----------\\n\")\n\n    if calcCHK:\n        reorder_chk(seedname, seednameGW, BANDSORT)\n\n    f_raw.close()\n\n\nif __name__ == \"__main__\":\n    args = parse_args()\n\n    seedname = args.seedname  # for instance \"silicon\"\n\n    if args.output_seedname is None:\n        seednameGW = seedname + \".gw\"  # for instance \"silicon.gw\"\n    else:\n        seednameGW = args.output_seedname\n\n    targets = []\n    if args.extensions is not None:\n        targets = args.extensions.split(\",\")\n        targets = [s.lower() for s in targets]  # options read from command line\n\n    gw2wannier90(seedname, seednameGW, targets, args.no_sort)\n", "meta": {"hexsha": "6cec7cec54ce5f481f13b8d10379c90faff61dfc", "size": 44420, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/gw2wannier90.py", "max_stars_repo_name": "epfl-theos/aiida-yambo-wannier90", "max_stars_repo_head_hexsha": "dabfa402e779e9fc797dda15ec748b0c6c25d647", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/gw2wannier90.py", "max_issues_repo_name": "epfl-theos/aiida-yambo-wannier90", "max_issues_repo_head_hexsha": "dabfa402e779e9fc797dda15ec748b0c6c25d647", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-02-21T14:59:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T15:57:49.000Z", "max_forks_repo_path": "utils/gw2wannier90.py", "max_forks_repo_name": "epfl-theos/aiida-yambo-wannier90", "max_forks_repo_head_hexsha": "dabfa402e779e9fc797dda15ec748b0c6c25d647", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.801988401, "max_line_length": 395, "alphanum_fraction": 0.5104007204, "include": true, "reason": "import numpy,from scipy", "num_tokens": 11399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19171963086360388}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nfrom tc_python import *\nimport itertools as itertool\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# In[4]:\n\n\ndef manyPoints(database,T,P,components,phases=[\"bcc\"],point_compositions=[(99.02,0.08)]):\n    \"\"\"\n    Single point equilibrium calculations\n    \n    ## input: \n        database name: [string],\n        Temperature float,\n        Pressure float,\n        elements: [string], \n        phases [string], if empty all phases from the database are included\n        point_compositions [(float,float,...)]\n            \n    ## output: Dictionary {\"stable_phases\",\"npms\",\"vpvs\",\"ws\",\"xiphs\",\"ys\", \"acs\",\"mus\",\"bineries\" }\n        stable_phases: [string],\n        npms: phase fractions [float],\n        vpvs: volume fractions of phases [float], \n        ws: weight fractions of elements [float],\n        xiphs: mole fractions of elements in phases [float],\n        ys: y fractions of elements is phases [float], \n        bineries: binary list of all elements and stable phases [tuple (component,phase)]\n        acs: activities of elements with respect to all phases \n        mus: chemical potentials of all components\n    \"\"\"\n    with TCPython() as start:\n        if not phases:\n            system_int = start.select_database_and_elements(database,components)\n        else:    \n            system_int = start.select_database_and_elements(database,components).without_default_phases()\n            for phase in phases:\n                system_int.select_phase(phase)\n        system = system_int.get_system()\n        calc = system.with_single_equilibrium_calculation()\n        \n        volume_fractions,phase_fractions,weight_fractions,xs_in_phases,ys_in_phases,activities,chemical_potentials,sps,bn =         [],[],[],[],[],[],[],[],[]\n        for point_composition in point_compositions:\n            ticc=time.time()\n            for i in range(len(components)-1):\n                calc.set_condition(ThermodynamicQuantity.mole_fraction_of_a_component((components[i])), point_composition[i])\n            calc.set_condition(ThermodynamicQuantity.temperature(), 1723.15)\n            calc.set_condition(ThermodynamicQuantity.pressure(), 1e5)\n            calc_res = calc.calculate()\n            stable_phases = calc_res.get_stable_phases()\n            sps.append(stable_phases)\n            for phase in stable_phases:\n                volume_fractions.append(calc_res.get_value_of('vpv({})'.format(phase)))       \n                phase_fractions.append(calc_res.get_value_of('npm({})'.format(phase)))\n            for element in components:\n                weight_fractions.append(calc_res.get_value_of('w({})'.format(element)))\n                chemical_potentials.append(calc_res.get_value_of('mu({})'.format(element)))\n            binaries = list(itertool.product(stable_phases, components))\n            bn.append(binaries)\n            for binary in binaries:\n                xs_in_phases.append(calc_res.get_value_of('x({},{})'.format(binary[0], binary[1])))\n                try:\n                    ys_in_phases.append(calc_res.get_value_of('y({},{})'.format(binary[0], binary[1])))\n                except Exception as error:\n                    a=1\n                    #ys_in_phases.append(-1)\n                try:\n                    activities.append(calc_res.get_value_of('ac({},{})'.format(binary[1], binary[0])))                    \n                except Exception as error:\n                    a=1\n                    #ys_in_phases.append(-1)\n            tocc=time.time()\n            print(tocc-ticc)\n        weight_fractions = np.reshape(weight_fractions,(-1,len(components)))\n        chemical_potentials = np.reshape(chemical_potentials,(-1,len(components)))\n        \n        return {\"stable_phases\":sps,\"npms\":phase_fractions,                 \"vpvs\":volume_fractions,\"ws\":weight_fractions,\"xiph\":xs_in_phases,                 \"ys\":ys_in_phases,\"acs\":activities,\"mus\":chemical_potentials,\"binaries\":bn}\n\n\n# In[5]:\n\n\nhelp(manyPoints)\n\n\n# In[6]:\n\n\ndatabase = \"TCFE8\"\nelements = [\"C\",\"Co\",\"N\",\"Ti\",\"W\"]\nphases = [\"liquid\", \"fcc\", \"mc_shp\", \"graphite\"]\nmole_fractions=[]\nfor i in np.arange(0.1,0.5,0.01):\n    mole_fractions.append((0.43,i,0.02,0.02,0.43))\noutputs=[\"ws\"]\n\n\n# In[7]:\n\n\ntic=time.time()\na=manyPoints(database,1750,1e5,elements,phases,mole_fractions)\ntoc = time.time()\nprint(toc-tic)\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "ec31b1c1cfd4e161f0d514aaab336a54456f9cff", "size": 4377, "ext": "py", "lang": "Python", "max_stars_repo_path": "manypoints.py", "max_stars_repo_name": "arminsalmasi/tc_python", "max_stars_repo_head_hexsha": "0f1b5194bdf2a73cead490532eecd1b7da0823e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "manypoints.py", "max_issues_repo_name": "arminsalmasi/tc_python", "max_issues_repo_head_hexsha": "0f1b5194bdf2a73cead490532eecd1b7da0823e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "manypoints.py", "max_forks_repo_name": "arminsalmasi/tc_python", "max_forks_repo_head_hexsha": "0f1b5194bdf2a73cead490532eecd1b7da0823e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.475, "max_line_length": 234, "alphanum_fraction": 0.6132053918, "include": true, "reason": "import numpy", "num_tokens": 1032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3775406617944891, "lm_q1q2_score": 0.19171962730706413}}
{"text": "# coding=utf-8\nfrom collections import defaultdict, OrderedDict\nfrom material_parser.core.utils import simplify\n\nimport regex as re\nimport sympy as smp\nimport material_parser.core.regex_parser as rp\nimport material_parser.core.chemical_sets as cs\nimport material_parser.core.constants as cnst\n\nfrom pprint import pprint\n\n\ndef process_formula(formula, regex_parser):\n    \"\"\"\n    :param regex_parser:\n    :param formula: str\n    :return: chemical_structure\n    \"\"\"\n    for s, r in cs.species_acronyms.items():\n        formula = formula.replace(s, r)\n    \"\"\"\n    build dictionary of elements and stoichiometries\n    \"\"\"\n    formula_data = parse_formula(formula, regex_parser)\n\n    \"\"\"\n    looking for variables in elements and stoichiometry\n    \"\"\"\n    for el, amt in formula_data[\"composition\"].items():\n        if el not in cs.list_of_elements | formula_data[\"elements_x\"].keys() | cnst.VACANCIES:\n            formula_data[\"elements_x\"][el] = []\n        for var in re.findall(rp.re_variables, amt):\n            formula_data[\"amounts_x\"][var] = {}\n\n    formula, \\\n    elements, \\\n    elements_x, \\\n    stoichiometry_x, \\\n    oxygen_deficiency = __refine_variables(formula_data[\"formula\"],\n                                           formula_data[\"composition\"],\n                                           formula_data[\"elements_x\"],\n                                           formula_data[\"amounts_x\"],\n                                           formula_data[\"oxygen_deficiency\"],\n                                           formula_data[\"oxygen_deficiency_sym\"])\n\n    if __is_acronym(formula, elements, elements_x) or __has_negative_composition(elements):\n        return dict(formula=formula,\n                    elements=OrderedDict(),\n                    species=OrderedDict(),\n                    oxygen_deficiency=\"\",\n                    phase=\"\",\n                    amounts_x={},\n                    elements_x={})\n\n    species = __get_species(formula, regex_parser) if len(elements) > 2 or formula == \"H2O\" else elements\n\n    # print (formula)\n    # pprint(elements)\n\n    return dict(formula=formula,\n                elements=elements,\n                species=species,\n                oxygen_deficiency=oxygen_deficiency,\n                phase=formula_data[\"phase\"],\n                amounts_x={x: v for x, v in stoichiometry_x.items()},\n                elements_x={e: v for e, v in elements_x.items()})\n\n\ndef parse_formula(formula, regex_parser):\n    formula = formula.replace(\" \", \"\")\n    \"\"\"\n    separate phase, e.g. g-ABC\n    \"\"\"\n    phase, formula = regex_parser.separate_phase(formula)\n\n    \"\"\"\n    separate oxygen deficiency\n    \"\"\"\n    formula, oxygen_deficiency, oxygen_deficiency_sym = regex_parser.separate_oxygen_deficiency(formula)\n\n    \"\"\"\n    converting fractions a(b+x)/c into (a/c*b+a/c*x)\n    \"\"\"\n    formula = regex_parser.make_fraction_convertion(formula)\n\n    \"\"\"\n    check for any weird syntax (A,B)zElxEly...\n    replacing with MzElxEly... and M = [A, B]\n    \"\"\"\n    elements_x = defaultdict(str)\n    stoichiometry_x = defaultdict(str)\n    formula, variables = regex_parser.convert_weird_syntax(formula)\n    if variables:\n        elements_x[\"M\"] = variables\n\n    composition = __get_composition(formula)\n\n    return dict(formula=formula,\n                composition=composition,\n                oxygen_deficiency=oxygen_deficiency,\n                oxygen_deficiency_sym = oxygen_deficiency_sym,\n                phase=phase,\n                amounts_x={x: v for x, v in stoichiometry_x.items()},\n                elements_x={e: v for e, v in elements_x.items()})\n\n\ndef __get_composition(init_formula):\n    \"\"\"\n\n    :param init_formula:\n    :return:\n    \"\"\"\n    \"\"\"\n    if more than 4 repeating lowercase letters encountered then it is not chemical formula\n    \"\"\"\n    if re.findall(\"[a-z]{4,}\", init_formula):\n        return OrderedDict()\n\n    formula_dict = OrderedDict()\n    formula_dict = __parse_parentheses(init_formula, \"1\", formula_dict)\n\n    \"\"\"\n    refinement of non-variable values\n    \"\"\"\n    incorrect = []\n    for el, amt in formula_dict.items():\n        formula_dict[el] = simplify(amt)\n        if any(len(c) > 1 for c in re.findall(\"[A-Za-z]+\", formula_dict[el])):\n            incorrect.append(el)\n\n    for el in incorrect:\n        del formula_dict[el]\n\n    return formula_dict\n\n\ndef __parse_parentheses(init_formula, init_factor, curr_dict):\n    re_in_parentheses = r\"\\(((?>[^\\(\\)]+|(?R))*)\\)\\s*([-*\\.\\da-z\\+/]*)\"\n    for m in re.finditer(re_in_parentheses, init_formula):\n        factor = m.group(2) if m.group(2) != \"\" else \"1\"\n        factor = simplify(\"(\" + str(init_factor) + \")*(\" + str(factor) + \")\")\n        unit_sym_dict = __parse_parentheses(m.group(1), factor, curr_dict)\n        init_formula = init_formula.replace(m.group(0), \"\")\n\n    unit_sym_dict = __get_sym_dict(init_formula, init_factor)\n    for el, amt in unit_sym_dict.items():\n        if el in curr_dict:\n            if len(curr_dict[el]) != 0:\n                curr_dict[el] = \"(\" + str(curr_dict[el]) + \")\" + \"+\" + \"(\" + str(amt) + \")\"\n            else:\n                curr_dict[el] = amt\n        else:\n            curr_dict[el] = amt\n\n    return curr_dict\n\n\ndef __get_sym_dict(f, factor):\n    re_sym_dict = r\"([A-Z□]{1}[a-z]{0,1})\\s*([\\-\\*\\.\\da-z\" + \"\".join(cnst.GREEK_CHARS) + r\"\\+\\/]*)\"\n    sym_dict = OrderedDict()\n\n    def get_code_value(code, iterator):\n        code_mapping = {\"01\": (iterator.group(1), iterator.group(2)),\n                        \"11\": (iterator.group(1), iterator.group(2)),\n                        \"10\": (iterator.group(1)[0], iterator.group(1)[1:] + iterator.group(2)),\n                        \"00\": (iterator.group(1)[0], iterator.group(1)[1:] + iterator.group(2))}\n        return code_mapping[code]\n\n    for m in re.finditer(re_sym_dict, f):\n        \"\"\"\n        checking for correct elements names\n        \"\"\"\n        el_bin = \"{0}{1}\".format(str(int(m.group(1)[0] in cs.list_of_elements_1 | {\"M\"} | cnst.VACANCIES)),\n                                 str(int(m.group(1) in cs.list_of_elements | {\"Ln\", \"M\"} | cnst.VACANCIES)))\n        el, amt = get_code_value(el_bin, m)\n        if amt.strip() == \"\":\n            amt = \"1\"\n        if el in sym_dict:\n            sym_dict[el] = \"(\" + sym_dict[el] + \")\" + \"+\" + \"(\" + amt + \")\" + \"*\" + \"(\" + str(factor) + \")\"\n        else:\n            sym_dict[el] = \"(\" + amt + \")\" + \"*\" + \"(\" + str(factor) + \")\"\n        f = f.replace(m.group(), \"\", 1)\n    if f.strip():\n        return OrderedDict()\n\n    \"\"\"\n    refinement of non-variable values\n    \"\"\"\n    try:\n        for el, amt in sym_dict.items():\n            sym_dict[el] = simplify(amt)\n    except:\n        sym_dict = OrderedDict()\n    return sym_dict\n\n\ndef __get_species(formula, regex_parser):\n    species_in_material, species_indexs, species_dict = OrderedDict(), OrderedDict(), OrderedDict()\n    material_formula = formula\n    i = 0\n    for species in cs.species:\n        while species in material_formula:\n            # print(species)\n            material_formula = material_formula.replace(species, \"specie\" + str(i) + \"_\")\n            species_in_material[\"specie\" + str(i) + \"_\"] = species\n            i += 1\n\n    if not species_in_material:\n        return OrderedDict()\n\n    for species in cs.number_to_alphabet_dict:\n        while species in material_formula:\n            material_formula = material_formula.replace(species, cs.number_to_alphabet_dict[species])\n            species_indexs[cs.number_to_alphabet_dict[species]] = species_in_material[species]\n    species_info = parse_formula(material_formula, regex_parser)[\"composition\"]\n    for species_index in species_info:\n        species_dict[species_indexs[species_index]] = species_info[species_index]\n    return species_dict\n\n\ndef __refine_variables(formula, composition, elements_vars, stoichiometry_vars, oxy_def, oxy_def_sym):\n    \"\"\"\n    :return:\n    \"\"\"\n    \"\"\"\n    combining [RE, AE, TM] into one variable\n    \"\"\"\n    rename_variables = [(\"R\", \"E\"), (\"A\", \"E\"), (\"T\", \"M\")]\n    for v1, v2 in rename_variables:\n        if v1 in elements_vars and v2 in elements_vars and v1 + v2 in formula:\n            elements_vars[v1 + v2] = []\n            del elements_vars[v2]\n            del elements_vars[v1]\n            composition[v1 + v2] = composition[v2]\n            del composition[v1]\n            del composition[v2]\n\n    \"\"\"\n    correction for Me variable\n    \"\"\"\n    if \"M\" in elements_vars and \"e\" in stoichiometry_vars:\n        elements_vars[\"Me\"] = []\n        del elements_vars[\"M\"]\n        del stoichiometry_vars[\"e\"]\n        c = composition[\"M\"][1:]\n        composition[\"Me\"] = c if c != \"\" else \"1.0\"\n        del composition[\"M\"]\n\n    \"\"\"\n    remove oxygen deficiency from variables\n    \"\"\"\n    if not oxy_def and oxy_def_sym in stoichiometry_vars:\n        oxy_def = None\n    variables = [v for v in stoichiometry_vars.keys()\n                 if [e for e, s in composition.items() if v in s] == [\"O\"]]\n    oxy_def = chr(177) if len(variables) > 0 else oxy_def\n    for var in variables:\n        del stoichiometry_vars[var]\n        composition[\"O\"] = \"1\" if composition[\"O\"] == var else composition[\"O\"].replace(var, \"\").strip()\n        formula = formula.replace(var, \"\")\n    return formula, composition, elements_vars, stoichiometry_vars, oxy_def\n\n\ndef __is_acronym(formula, composition, variables):\n\n    if formula in cs.ions:\n        return False\n\n    if any(ion in formula and len(ion) > 1 for ion in cs.ions):\n        return False\n\n    if len(composition) == 2 and variables:\n        return True\n\n    capital_letters = cnst.LATIN_CAPITAL - set(cs.list_of_elements_1) - {\"M\", \"L\"}\n    if [r for c in capital_letters for r in re.findall(c + \"[A-Z0-9\\-]\", formula)] \\\n            and all(w not in formula for w in [\"RE\", \"OAC\", \"TM\", \"ME\"]):\n        return True\n\n    if all(e.isupper() and s in [\"1.0\", \"1\"] for e, s in composition.items()):\n        return True\n\n    elements_x = [el for el in variables.keys() if len(el) == 1 and el.isupper()]\n    if len(elements_x) > 1:\n        return True\n\n    if all(c.isupper() for c in formula) and any(c not in cs.list_of_elements_1 for c in formula):\n        return True\n\n    if re.findall(\"[A-Z]{3,}\", formula) != [] and \\\n        all(w not in formula for w in [\"CH\", \"COO\", \"OH\", \"NH\"] + [a for a in cs.default_abbreviations.keys()]):\n        return True\n\n    if \"PV\" == formula[0:2]:\n        return True\n\n    return False\n\n\ndef __has_negative_composition(composition):\n\n    flag = False\n    try:\n        flag = any(float(amt) < 0 for el, amt in composition.items())\n    except:\n        pass\n\n    return flag\n", "meta": {"hexsha": "cbc436ac6bfd9b40df4d2b3104747f6f64bd1407", "size": 10562, "ext": "py", "lang": "Python", "max_stars_repo_path": "material_parser/core/formula_processing.py", "max_stars_repo_name": "CederGroupHub/MaterialParser", "max_stars_repo_head_hexsha": "a747a30bbf36b59b44eaa2fd5bc0203d70fe12e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-12-17T23:51:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T17:44:40.000Z", "max_issues_repo_path": "material_parser/core/formula_processing.py", "max_issues_repo_name": "CederGroupHub/MaterialParser", "max_issues_repo_head_hexsha": "a747a30bbf36b59b44eaa2fd5bc0203d70fe12e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-01-10T00:07:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-16T23:52:41.000Z", "max_forks_repo_path": "material_parser/core/formula_processing.py", "max_forks_repo_name": "CederGroupHub/MaterialParser", "max_forks_repo_head_hexsha": "a747a30bbf36b59b44eaa2fd5bc0203d70fe12e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-02-28T22:03:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T15:12:40.000Z", "avg_line_length": 34.0709677419, "max_line_length": 112, "alphanum_fraction": 0.5907025185, "include": true, "reason": "import sympy", "num_tokens": 2563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.3276683139517237, "lm_q1q2_score": 0.19171911343017428}}
{"text": "from typing import Union, Optional, Tuple, Dict, Any\nimport os\n\nimport numpy as np\nimport torch as th\nfrom torch.cuda.amp import autocast\n\nfrom ail.agents.rl_agent.rl_core import OnPolicyAgent\nfrom ail.common.math import normalize\nfrom ail.common.pytorch_util import asarray_shape2d, obs_as_tensor, disable_gradient\nfrom ail.common.type_alias import AlgoTags, DoneMask, GymEnv, GymSpace, TensorDict\n\n\nclass PPO(OnPolicyAgent):\n    \"\"\"\n    Proximal Policy Optimization algorithm (PPO) (clip version)\n    Paper: https://arxiv.org/abs/1707.06347\n\n    :param state_space: state space.\n    :param action_space: action space.\n    :param device: PyTorch device to which the values will be converted.\n    :param seed: random seed.\n    :param batch_size: size of the batch (we assume batch_size == buffer_size).\n    :param policy_kwargs: arguments to be passed to the policy on creation.\n        e.g. : {\n            pi: [64, 64],\n            vf: [64, 64],\n            activation: 'relu',\n            lr_actor: 3e-4,\n            lr_critic: 3e-4,\n            critic_type=\"V\",\n            orthogonal_init: True,\n            }\n    :param epoch_ppo: Number of epoch when optimizing the surrogate loss.\n    :param gamma: Discount factor.\n    :param clip_eps: PPO clipping parameter.\n    :param coef_ent: Entropy coefficient for the loss calculation.\n    :param max_grad_norm: Maximum norm for the gradient clipping.\n    :param fp16: Whether to use float16 mixed precision training.\n    :optim_kwargs: arguments to be passed to the optimizer.\n        eg. : {\n            \"optim_cls\": adam,\n            \"optim_set_to_none\": True, # which set grad to None instead of zero.\n            }\n    :param buffer_kwargs: Arguments to be passed to the buffer.\n        eg. : {\n            with_reward: True,\n            extra_data: [\"log_pis\"]\n            }\n    :param init_buffer: Whether to create the buffer during initialization.\n    :param init_models: Whether to create the models during initialization.\n    \"\"\"\n\n    def __init__(\n        self,\n        state_space: GymSpace,\n        action_space: GymSpace,\n        device: Union[th.device, str],\n        seed: int,\n        policy_kwargs: Dict[str, Any],\n        batch_size: int = 2_000,\n        epoch_ppo: int = 10,\n        gamma: float = 0.99,\n        gae_lambda: float = 0.97,\n        clip_eps: float = 0.2,\n        coef_ent: float = 0.01,\n        max_grad_norm: Optional[float] = None,\n        fp16: bool = False,\n        optim_kwargs: Optional[dict] = None,\n        buffer_kwargs: Optional[Dict[str, Any]] = None,\n        init_buffer: bool = True,\n        init_models: bool = True,\n        expert_mode: bool = False,\n        **kwargs,\n    ):\n        super().__init__(\n            state_space,\n            action_space,\n            device,\n            fp16,\n            seed,\n            gamma,\n            max_grad_norm,\n            batch_size,\n            batch_size,  # * (Yifan) here assumes batch_size == buffer_size\n            policy_kwargs,\n            optim_kwargs,\n            buffer_kwargs,\n            init_buffer,\n            init_models,\n            expert_mode,\n        )\n\n        # learning rate scheduler.\n        # TODO: add learning rate scheduler.\n        # ? (Yifan) Is there one suitable for RL?\n\n        \"\"\"alpha_t = alpha_0 (1 - t/T)\"\"\"\n        # schedule = lambda epoch: 1 - epoch/(self.param.evaluation['total_timesteps'] // self.batch_size)\n        # self.scheduler_actor = optim.lr_scheduler.LambdaLR(self.optim_actor, schedule)\n        # self.scheduler_critic = optim.lr_scheduler.LambdaLR(self.optim_critic, schedule)\n\n        # Other algo params.\n        self.learning_steps_ppo = 0\n        self.epoch_ppo = epoch_ppo\n        self.clip_eps = clip_eps\n        self.gae_lambda = gae_lambda\n        self.coef_ent = coef_ent\n\n        self.tag = AlgoTags.PPO\n\n    def __repr__(self) -> str:\n        return f\"{self.__class__.__name__}\"\n\n    def is_update(self, step: int) -> bool:\n        \"\"\"Whether or not to update the agent\"\"\"\n        return step % self.batch_size == 0\n\n    def step(\n        self,\n        env: GymEnv,\n        state: th.Tensor,\n        episode_timesteps: th.Tensor,\n        global_timesteps: Optional[int] = None,\n        add_absorbing_state: bool = False,\n    ) -> Tuple[np.ndarray, int]:\n        \"\"\"\n        Intereact with environment and store the transition.\n\n        :param env: gym environment\n        :param state: orginal state return by the environment\n        :param episode_timesteps: number of timesteps this episode\n        :param total_timesteps: total number of timesteps to run in outer loop\n        :return: next_state, episode length\n        \"\"\"\n        episode_timesteps += 1\n\n        # Sample actions from action distribution.\n        # which is then wrapped by tanh transform to keep it in range [-1, 1].\n        action, log_pi = self.explore(obs_as_tensor(state, self.device), scale=False)\n\n        # Resacle actions to match original action space.\n        scale_action = (\n            self.scale_action(action) if not self.normalized_action_space else action\n        )\n\n        # Interact with environment (Info might be useful for some special env).\n        next_state, reward, done, info = env.step(scale_action)\n\n        # Done mask removes the time limit constrain of some env to keep makorvian.\n        # Agent keeps alive should not be done by env's time limit.\n        # See: https://github.com/sfujim/TD3/blob/master/main.py#L127\n        # * Here we use an inverse convention in which DONE = 0 and NOT_DONE = 1\n        # * to match absorbing state implementation in DAC paper.\n        done_mask: float\n        if (episode_timesteps == env._max_episode_steps) or not done:\n            done_mask = DoneMask.NOT_DONE.value\n        else:\n            done_mask = DoneMask.DONE.value\n\n        absorbing_cond = all(\n            [add_absorbing_state, done, episode_timesteps < env._max_episode_steps]\n        )\n        if absorbing_cond:\n            next_state = env.get_absorbing_state()\n\n        data = {\n            \"obs\": asarray_shape2d(state),\n            \"acts\": asarray_shape2d(action),\n            \"rews\": asarray_shape2d(reward),\n            \"dones\": asarray_shape2d(done_mask),\n            \"log_pis\": asarray_shape2d(log_pi),\n            \"next_obs\": asarray_shape2d(next_state),\n        }\n\n        # Store transition.\n        # * NOT ALLOW size larger than buffer capcity.\n        self.buffer.store(data, truncate_ok=False)\n\n        # Reset env if encounter done signal (not done mask!)\n        if done:\n            episode_timesteps = 0\n            next_state = env.reset()\n            # Add a absorbing state to buffer when done.\n            if add_absorbing_state and (episode_timesteps < env._max_episode_steps):\n                # A fake action for the absorbing state.\n                zero_action = np.zeros(env.action_space.shape)\n                absorbing_state = env.get_absorbing_state()\n                absorbing_data = {\n                    \"obs\": asarray_shape2d(absorbing_state),\n                    \"acts\": asarray_shape2d(zero_action),\n                    \"rews\": asarray_shape2d(0.0),\n                    \"dones\": asarray_shape2d(DoneMask.ABSORBING.value),\n                    \"log_pis\": asarray_shape2d(log_pi),  # TODO: what to do with log_pi?\n                    \"next_obs\": asarray_shape2d(absorbing_state),\n                }\n                self.buffer.store(absorbing_data, truncate_ok=False)\n        return next_state, episode_timesteps\n\n    def update(self, log_this_batch: bool = False) -> Dict[str, Any]:\n        \"\"\"\n        A general road map for updating the model.\n        Obtain the training batch and perform update.\n        :return train_logs: dict of training logs\n        \"\"\"\n        self.learning_steps += 1\n        rollout_data = self.buffer.get()\n\n        # Clear buffer after getting entire buffer.\n        self.buffer.reset()\n        train_logs = self.update_algo(rollout_data, log_this_batch)\n        return train_logs\n\n    def update_algo(\n        self, data: TensorDict, log_this_batch: bool = False\n    ) -> Dict[str, Any]:\n        \"\"\"\n        Update the actor and critic.\n        :param data: a batch of randomly sampled transitions\n        :return train_logs: dict of training logs\n        \"\"\"\n        states, actions, rewards, dones, next_states, log_pis = (\n            data[\"obs\"],\n            data[\"acts\"],\n            data[\"rews\"],\n            data[\"dones\"],\n            data[\"next_obs\"],\n            data[\"log_pis\"],\n        )\n        with th.no_grad():\n            values = self.critic(states)\n            next_values = self.critic(next_states)\n\n        targets, gaes = calculate_gae(\n            rewards, (1.0 - dones), values, next_values, self.gamma, self.gae_lambda\n        )\n\n        for _ in range(self.epoch_ppo):\n            self.learning_steps_ppo += 1\n            loss_critic = self._update_critic(states, targets)\n            loss_actor, pi_info = self._update_actor(states, actions, log_pis, gaes)\n\n        if log_this_batch:\n            # Return log changes(key used for logging name).\n            return {\n                \"actor_loss\": loss_actor,\n                \"critic_loss\": loss_critic,\n                \"approx_kl\": pi_info[\"kl\"],\n                \"entropy\": pi_info[\"ent\"],\n                \"clip_fraction\": pi_info[\"cf\"],\n                \"pi_lr\": self.lr_actor,\n                \"vf_lr\": self.lr_critic,\n                \"learn_steps_ppo\": self.learning_steps_ppo,\n            }\n        else:\n            return {}\n\n    def _update_critic(self, states: th.Tensor, targets: th.Tensor) -> th.Tensor:\n        \"\"\"\n        Update critic. (value function approximation)\n        :param states:\n        :param targets: should be gae + v_pred\n        return: critic loss\n        \"\"\"\n        self.optim_critic.zero_grad(set_to_none=self.optim_set_to_none)\n        with autocast(enabled=self.fp16):\n            loss_critic = (self.critic(states) - targets).pow(2).mean()\n        self.one_gradient_step(loss_critic, self.optim_critic, self.critic)\n        return loss_critic.detach()\n\n    def _update_actor(\n        self,\n        states: th.Tensor,\n        actions: th.Tensor,\n        log_pis_old: th.Tensor,\n        gaes: th.Tensor,\n    ) -> Tuple[th.Tensor, Dict[str, Any]]:\n        \"\"\"\n        Update actor. (function for computing PPO policy loss)\n        :param states:\n        :param actions:\n        :param log_pis_old:\n        :param gaes: general advantage estimation\n        : return: actor loss, policy_info\n        \"\"\"\n        log_pis = self.actor.evaluate_log_pi(states, actions)\n\n        # * (Yifan) Since we bounded the mean action with tanh(),\n        # * there is no analytical form of entropy\n        # Approximate entropy.\n        approx_ent = -log_pis.mean()\n\n        # ratio between old and new policy, should be one at the first iteration\n        log_ratios = log_pis - log_pis_old\n        ratios = (log_ratios).exp()\n\n        # clipped surrogate loss\n        loss_actor1 = ratios * gaes\n        loss_actor2 = th.clamp(ratios, 1.0 - self.clip_eps, 1.0 + self.clip_eps) * gaes\n        loss_actor = -th.min(loss_actor1, loss_actor2).mean()\n\n        self.optim_actor.zero_grad(set_to_none=self.optim_set_to_none)\n        with autocast(enabled=self.fp16):\n            loss_actor_ent = loss_actor - self.coef_ent * approx_ent\n        self.one_gradient_step(loss_actor_ent, self.optim_actor, self.actor)\n\n        \"\"\"\n        Calculate approximate form of reverse KL Divergence for early stopping.\n        See issue #417: https://github.com/DLR-RM/stable-baselines3/issues/417\n        and discussion in PR #419: https://github.com/DLR-RM/stable-baselines3/pull/419\n        and Schulman blog: https://joschu.net/blog/kl-approx.html\n        KL(q||p): (r-1) - log(r), where r = p(x)/q(x)\n        \"\"\"\n        # ! (Yifan) Deprecated :\n        # ! Naive version: approx_kl = (log_pi_old - log_pi).mean().item()\n        # ! This is an unbiased estimator, but it has large variance.\n        # ! Since it can take on negative values.\n        # ! as opposed to the actual KL Divergence measure\n        # Useful extra info\n        with th.no_grad():\n            approx_kl = ((ratios - 1) - log_ratios).mean()\n            clipped = ratios.gt(1 + self.clip_eps) | ratios.lt(1 - self.clip_eps)\n            clip_frac = th.as_tensor(clipped, dtype=th.float32).mean()\n            pi_info = {\"kl\": approx_kl, \"ent\": approx_ent.detach(), \"cf\": clip_frac}\n        return loss_actor.detach(), pi_info\n\n    def save_models(self, save_dir: str) -> None:\n        \"\"\"\n        Save the model. (Only save actor to reduce workloads)\n        \"\"\"\n        super().save_models(save_dir)\n        th.save(self.actor.state_dict(), os.path.join(save_dir, \"actor.pth\"))\n\n    @classmethod\n    def load(\n        cls,\n        path: str,\n        policy_kwargs: Dict[str, Any],\n        env: Union[GymEnv, str, None] = None,\n        state_space: Optional[GymSpace] = None,\n        action_space: Optional[GymSpace] = None,\n        device: Union[th.device, str] = \"cpu\",\n        seed: int = 42,\n        **kwargs,\n    ) -> \"PPO\":\n        \"\"\"\n        Load the model from a saved model directory.\n        we only load actor.\n        \"\"\"\n        super().load(env, state_space, action_space)\n        if env is not None:\n            if isinstance(env, str):\n                import gym\n\n                env = gym.make(env)\n            state_space, action_space = env.observation_space, env.action_space\n\n        ppo_expert = cls(\n            state_space,\n            action_space,\n            device,\n            seed,\n            policy_kwargs,\n            init_buffer=False,\n            init_models=False,\n            expert_mode=True,\n            **kwargs,\n        )\n        state_dict = th.load(path)\n        ppo_expert.actor.load_state_dict(state_dict)\n        disable_gradient(ppo_expert.actor)\n        ppo_expert.actor.eval()\n        return ppo_expert\n\n\ndef calculate_gae(\n    rewards: th.Tensor,\n    dones: th.Tensor,\n    values: th.Tensor,\n    next_values: th.Tensor,\n    gamma: float,\n    lambd: float,\n    normal: bool = True,\n) -> Tuple[th.Tensor, th.Tensor]:\n    \"\"\"\n    Compute the lambda-return (TD(lambda) estimate) and GAE(lambda) advantage.\n\n    Uses Generalized Advantage Estimation (https://arxiv.org/abs/1506.02438)\n    to compute the advantage. To obtain vanilla advantage (A(s) = R - V(S))\n    where R is the discounted reward with value bootstrap,\n    set `lambd=1.0`.\n    https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/ppo1/pposgd_simple.py#L66\n    \"\"\"\n    # Calculate TD errors.\n    deltas = rewards + gamma * next_values * (1.0 - dones) - values\n    # Initialize gae.\n    gaes = th.empty_like(rewards)\n\n    # Calculate gae recursively from behind.\n    gaes[-1] = deltas[-1]\n    for t in reversed(range(rewards.size(0) - 1)):\n        gaes[t] = deltas[t] + gamma * lambd * (1.0 - dones[t]) * gaes[t + 1]\n\n    targets = values + gaes\n\n    if normal:\n        return targets, normalize(gaes, gaes.mean(), gaes.std())\n    else:\n        return targets, gaes\n", "meta": {"hexsha": "37825ea0dd14a4963475fe770abf3d679851e111", "size": 15056, "ext": "py", "lang": "Python", "max_stars_repo_path": "ail/agents/rl_agent/ppo.py", "max_stars_repo_name": "tianyudwang/adversarial_imitation_learning", "max_stars_repo_head_hexsha": "1d5b0ce16cf6453ed29650b6ef565664d6742680", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ail/agents/rl_agent/ppo.py", "max_issues_repo_name": "tianyudwang/adversarial_imitation_learning", "max_issues_repo_head_hexsha": "1d5b0ce16cf6453ed29650b6ef565664d6742680", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ail/agents/rl_agent/ppo.py", "max_forks_repo_name": "tianyudwang/adversarial_imitation_learning", "max_forks_repo_head_hexsha": "1d5b0ce16cf6453ed29650b6ef565664d6742680", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7219512195, "max_line_length": 121, "alphanum_fraction": 0.6007571732, "include": true, "reason": "import numpy", "num_tokens": 3590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.3276683073862188, "lm_q1q2_score": 0.19171910010630178}}
{"text": "import os\nimport sys\nimport numpy as np\n\nimport pycuda.driver as cuda\nimport pycuda.autoinit\nfrom pycuda.compiler import SourceModule\n\nclass gpu_context:\n    \"\"\"\n    GPU context which manages the allocation of memory, the movement of memory between python and the GPU, \n    and the calling of GPU funcitons\n\n    Written: Devin Cody, 2021\n    \"\"\"\n    def __init__(self, len_gpu_arrays = 10000000):\n        self.gpu_initalized = False\n        self.len_gpu_arrays = len_gpu_arrays\n\n        try:\n            print(\"Compiling kernel\")\n            if \"win\" in sys.platform:\n                f_newton = open(os.path.dirname(__file__) + \"\\\\kernels\\\\newton.cu\", 'r')\n                f_mikkola = open(os.path.dirname(__file__) + \"\\\\kernels\\\\mikkola.cu\", 'r')\n            else:\n                f_newton = open(os.path.dirname(__file__) + \"/kernels/newton.cu\", 'r')\n                f_mikkola = open(os.path.dirname(__file__) + \"/kernels/mikkola.cu\", 'r')\n\n            fstr_newton = \"\".join(f_newton.readlines())\n            mod_newton = SourceModule(fstr_newton)\n            self.newton_gpu = mod_newton.get_function(\"newton_gpu\")\n\n            fstr_mikkola = \"\".join(f_mikkola.readlines())\n            mod_mikkola = SourceModule(fstr_mikkola)\n            self.mikkola_gpu = mod_mikkola.get_function(\"mikkola_gpu\")\n\n            print(\"Allocating with {} bytes\".format(self.len_gpu_arrays))\n            self.tolerance = np.array([1e-9], dtype = np.float64)\n            self.max_iter = np.array([100])\n            self.eanom = None\n\n            self.d_manom = cuda.mem_alloc(self.len_gpu_arrays)\n            self.d_ecc = cuda.mem_alloc(self.len_gpu_arrays)\n            self.d_eanom = cuda.mem_alloc(self.len_gpu_arrays)\n\n            self.d_tol = cuda.mem_alloc(self.tolerance.nbytes)\n            self.d_max_iter = cuda.mem_alloc(self.max_iter.nbytes)\n            \n            print(\"Copying parameters to GPU\")\n            cuda.memcpy_htod(self.d_tol, self.tolerance)\n            cuda.memcpy_htod(self.d_max_iter, self.max_iter)\n            gpu_initalized = True\n        except Exception as e:\n            print(\"Error: KEPLER: Unable to initialize Kepler GPU solver context\")\n            raise(e)\n\n    def newton(self, manom, ecc, eanom, eanom0 = None, tolerance=1e-9, max_iter=100):\n        \"\"\"\n        Moves numpy arrays onto the GPU memory, calls the Newton-Raphson solver for eccentric anomaly\n        and copies the result back into a numpy array.\n\n        Args:\n            manom (np.array): array of mean anomalies\n            ecc (np.array): array of eccentricities\n            eanom (np.array): array of eccentric anomalies (return by reference)\n            eanom0 (np.array, optional): array of first guess for eccentric anomaly, same shape as manom (optional)\n        Return:\n            None: eanom is changed by reference\n\n        Written: Devin Cody, 2021\n\n        \"\"\"\n        # Check to make sure we have enough data to process orbits\n        if (self.len_gpu_arrays < manom.nbytes):\n            self.len_gpu_arrays = manom.nbytes\n            self.d_manom = cuda.mem_alloc(self.len_gpu_arrays)\n            self.d_ecc = cuda.mem_alloc(self.len_gpu_arrays)\n            self.d_eanom = cuda.mem_alloc(self.len_gpu_arrays)\n\n        cuda.memcpy_htod(self.d_manom, manom)\n        cuda.memcpy_htod(self.d_ecc, ecc)\n        cuda.memcpy_htod(self.d_tol, tolerance)\n        cuda.memcpy_htod(self.d_max_iter, max_iter)\n\n        # Initialize at E=M, E=pi is better at very high eccentricities\n        if eanom0 is None:\n            cuda.memcpy_dtod(self.d_eanom, self.d_manom, self.len_gpu_arrays)\n        else:\n            cuda.memcpy_htod(self.d_eanom, eanom0)\n\n        self.newton_gpu(self.d_manom, self.d_ecc, self.d_eanom, self.d_max_iter, self.d_tol, grid = (len(manom)//64+1,1,1), block = (64,1,1))\n        cuda.memcpy_dtoh(eanom, self.d_eanom)\n\n    def mikkola(self, manom, ecc, eanom):\n        \"\"\"\n        Moves numpy arrays onto the GPU memory, calls the analtyical Mikkola solver for eccentric anomaly\n        and copies the result back into a numpy array.\n        \n        Args:\n            manom (np.array): array of mean anomalies between 0 and 2pi\n            ecc (np.array): eccentricity\n            eanom (np.array): array of eccentric anomalies (return by reference)\n        Return:\n            None: eanom is changed by reference\n\n        Written: Devin Cody, 2021\n        \"\"\"\n        # Check to make sure we have enough data to process orbits\n        if (self.len_gpu_arrays < manom.nbytes):\n            self.len_gpu_arrays = manom.nbytes\n            self.d_manom = cuda.mem_alloc(self.len_gpu_arrays)\n            self.d_ecc = cuda.mem_alloc(self.len_gpu_arrays)\n\n        cuda.memcpy_htod(self.d_manom, manom)\n        cuda.memcpy_htod(self.d_ecc, ecc)\n\n        self.mikkola_gpu(self.d_manom, self.d_ecc, self.d_eanom, grid = (len(manom)//64+1,1,1), block = (64,1,1))\n        cuda.memcpy_dtoh(eanom, self.d_eanom)", "meta": {"hexsha": "da0eae7fd927810bc42e850c31086f093b93750e", "size": 4919, "ext": "py", "lang": "Python", "max_stars_repo_path": "orbitize/gpu_context.py", "max_stars_repo_name": "sblunt/orbitize", "max_stars_repo_head_hexsha": "665ca4843d10ee1593665254354d934f37e1b5fc", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 60, "max_stars_repo_stars_event_min_datetime": "2018-01-12T17:16:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T01:39:39.000Z", "max_issues_repo_path": "orbitize/gpu_context.py", "max_issues_repo_name": "sblunt/orbitize", "max_issues_repo_head_hexsha": "665ca4843d10ee1593665254354d934f37e1b5fc", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": 278, "max_issues_repo_issues_event_min_datetime": "2018-01-12T17:25:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:28:27.000Z", "max_forks_repo_path": "orbitize/gpu_context.py", "max_forks_repo_name": "sblunt/orbitize", "max_forks_repo_head_hexsha": "665ca4843d10ee1593665254354d934f37e1b5fc", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": 49, "max_forks_repo_forks_event_min_datetime": "2018-10-30T19:34:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-31T13:28:45.000Z", "avg_line_length": 41.686440678, "max_line_length": 141, "alphanum_fraction": 0.6306159789, "include": true, "reason": "import numpy,import pycuda,from pycuda", "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.19170381884976143}}
{"text": "\"\"\"TODO.\"\"\"\n\nfrom __future__ import print_function, absolute_import\nimport numba\nfrom numba import jit\nimport numpy as np\nimport math\nimport random\nfrom numbskull_extend.inference import draw_sample, eval_factor\n\n\n@jit(cache=True, nogil=True)\ndef learnthread(shardID, nshards, step, regularization, reg_param,\n                truncation,var_copy, weight_copy, weight,variable,\n                factor, fmap,vmap, factor_index, Z,\n                fids,var_value, var_value_evid,weight_value, learn_non_evidence,\n                poential_weight,alpha_bound,tau_bound,sample_list=None, wmap=None,wfactor=None):\n    \"\"\"TODO.\"\"\"\n    # Identify start and end variable\n    nvar = variable.shape[0]\n    start = (shardID * nvar) // nshards\n    end = ((shardID + 1) * nvar) // nshards\n    if sample_list == None:     #sample_list为None表示不需要平衡化\n        for var_samp in range(start, end):\n            if variable[var_samp][\"isEvidence\"] == 4:\n                # This variable is not owned by this machine\n                continue\n            sample_and_sgd(var_samp, step, regularization, reg_param, truncation,\n                           var_copy, weight_copy, weight, variable,factor,\n                           fmap, vmap,factor_index, Z[shardID], fids[shardID],\n                           var_value,var_value_evid, weight_value, learn_non_evidence,poential_weight,\n                           alpha_bound,tau_bound)\n    else:      #需要平衡化\n        sample_num = sample_list.shape[0]\n        start = (shardID * sample_num) // nshards\n        end = ((shardID + 1) * sample_num) // nshards\n        for i in range(0,sample_num) :\n            var_samp = sample_list[i]['vid']\n            if variable[var_samp][\"isEvidence\"] == 4:\n                # This variable is not owned by this machine\n                continue\n            sample_and_sgd(var_samp, step, regularization, reg_param, truncation,\n                           var_copy, weight_copy, weight, variable,factor,\n                           fmap, vmap,factor_index, Z[shardID],fids[shardID],\n                           var_value,var_value_evid,weight_value, learn_non_evidence,poential_weight,\n                           alpha_bound,tau_bound)\n\n\n@jit(cache=True, nogil=True)\ndef learnthread_bgd(shardID, nshards, step, regularization, reg_param,\n                truncation,var_copy, weight_copy, weight,variable,\n                factor, fmap,vmap, factor_index, Z,\n                fids,var_value, var_value_evid,weight_value, learn_non_evidence,\n                poential_weight,alpha_bound,tau_bound,sample_list=None,wmap=None,wfactor=None):\n    nweight = weight.shape[0]\n    start = (shardID * nweight) // nshards\n    end = ((shardID + 1) * nweight) // nshards\n    for wid in range(start,end):\n        if weight[wid][\"isFixed\"]:\n            continue\n        else:\n            sample_and_bgd(wid,step, regularization, reg_param, truncation,\n                           var_copy, weight_copy, weight, variable,factor,\n                           fmap,vmap, factor_index, Z[shardID],fids[shardID],\n                           var_value, var_value_evid,weight_value, learn_non_evidence,poential_weight,\n                           alpha_bound,tau_bound,wmap,wfactor)\n\n\n@jit(nopython=True, cache=True, nogil=True)\ndef sample_and_bgd(wid,step, regularization, reg_param, truncation,\n                   var_copy, weight_copy, weight, variable,factor,\n                   fmap,vmap, factor_index, Z,fids,\n                   var_value, var_value_evid,weight_value, learn_non_evidence,poential_weight,\n                   alpha_bound,tau_bound,wmap,wfactor):    #批量梯度下降不需要考虑poential_weight\n    #1.计算梯度和\n    weight_id = wmap[wid][\"weightId\"]\n    weight_index_offset = wmap[wid][\"weight_index_offset\"]\n    weight_index_length = wmap[wid][\"weight_index_length\"]\n    #找到此权重相关的每一个factor\n    factor_count = weight_index_length   #此权重拥有的因子个数\n    for fIndex in range(weight_index_offset,weight_index_offset+weight_index_length):\n        factor_id = wfactor[fIndex][\"factorId\"]\n        ftv_offset = factor[factor_id][\"ftv_offset\"]\n        ftv_length = factor[factor_id][\"arity\"]\n        var_count = ftv_length          #此因子拥有的变量个数\n        gradient_sum = 0   #不需要参数化时，所有梯度的和\n        gradient1_sum = 0  #需要参数化时，参数1的梯度和\n        gradient2_sum = 0  # 需要参数化时，参数2的梯度和\n        # 找到每一个factor相关的每一个变量\n        for vIndex in range(ftv_offset,ftv_offset+ftv_length):\n            var_samp = fmap[vIndex][\"vid\"]\n            if variable[var_samp][\"isEvidence\"] != 1:\n                evidence = draw_sample(var_samp, var_copy, weight_copy,\n                                       weight, variable, factor,\n                                       fmap, vmap, factor_index, Z,\n                                       var_value_evid, weight_value)\n                # If evidence then store the initial value in a tmp variable\n            # then sample and compute the gradient.\n            else:\n                evidence = variable[var_samp][\"initialValue\"]\n            var_value_evid[var_copy][var_samp] = evidence\n            # Sample the variable\n            proposal = draw_sample(var_samp, var_copy, weight_copy, weight,\n                                   variable, factor, fmap, vmap,\n                                   factor_index, Z, var_value, weight_value)\n            var_value[var_copy][var_samp] = proposal\n            if not learn_non_evidence and variable[var_samp][\"isEvidence\"] != 1:\n                return\n            truncate = random.random() < 1.0 / truncation if regularization == 1 else False\n            p0 = eval_factor(factor_id, var_samp,\n                             evidence, var_copy,\n                             variable, factor, fmap,\n                             var_value_evid)\n            p1 = eval_factor(factor_id, var_samp,\n                             proposal, var_copy,\n                             variable, factor, fmap,\n                             var_value)\n            # if need parameterize\n            if weight[factor[factor_id]['weightId']]['parameterize']:\n                x = fmap[factor[factor_id][\"ftv_offset\"]]['x']\n                theta = fmap[factor[factor_id][\"ftv_offset\"]]['theta']\n                a = weight[factor[factor_id]['weightId']]['a']\n                b = weight[factor[factor_id]['weightId']]['b']\n                gradient1 = (p1 - p0) * theta * factor[factor_id][\"featureValue\"] * (x - b)\n                gradient2 = (p1 - p0) * theta * factor[factor_id][\"featureValue\"] * (-a)\n                gradient1_sum += gradient1\n                gradient2_sum += gradient2\n            # if not need parameterize\n            else:\n                gradient = (p1 - p0) * factor[factor_id][\"featureValue\"]\n                gradient_sum += gradient\n        #求平均值\n        # print(\"权重开始平均\")\n        gradient1_sum /= var_count\n        gradient2_sum /= var_count\n        gradient_sum /= var_count\n\n    #2.更新参数，分为需要参数化的和不需要参数化的\n    #if need parameterize\n    if weight[factor[factor_id]['weightId']]['parameterize'] == 1:\n            if regularization == 2:  # 是否需要正则化\n                a *= (1.0 / (1.0 + reg_param * step))\n                a -= step * gradient1_sum/factor_count\n                b *= (1.0 / (1.0 + reg_param * step))\n                b -= step * gradient2_sum/factor_count\n            elif regularization == 1:\n                # Truncated Gradient\n                # \"Sparse Online Learning via Truncated Gradient\"\n                #  Langford et al. 2009\n                a -= step * gradient1_sum/factor_count\n                b -= step * gradient2_sum/factor_count\n                if truncate:\n                    l1delta = reg_param * step * truncation\n                    a = max(0, a - l1delta) if a > 0 else min(0, a + l1delta)\n                    b = max(0, b - l1delta) if b > 0 else min(0, b + l1delta)\n            else:\n                a -= step * gradient1_sum/factor_count\n                b -= step * gradient2_sum/factor_count\n            if a < tau_bound[factor[factor_id]['weightId']]['lowerBound']:\n                a = tau_bound[factor[factor_id]['weightId']]['lowerBound']\n            elif a > tau_bound[factor[factor_id]['weightId']]['upperBound']:\n                a = tau_bound[factor[factor_id]['weightId']]['upperBound']\n            if b > alpha_bound[factor[factor_id]['weightId']]['upperBound']:\n                b = alpha_bound[factor[factor_id]['weightId']]['upperBound']\n            elif b < alpha_bound[factor[factor_id]['weightId']]['lowerBound']:\n                b = alpha_bound[factor[factor_id]['weightId']]['lowerBound']\n            w = theta * a * (x - b)\n            weight[factor[factor_id]['weightId']]['a'] = a\n            weight[factor[factor_id]['weightId']]['b'] = b\n    # if not need parameterize\n    elif weight[factor[factor_id]['weightId']]['parameterize'] == 0:\n        w = weight_value[weight_copy][weight_id]\n        if regularization == 2:\n            w *= (1.0 / (1.0 + reg_param * step))\n            w -= step * gradient_sum /factor_count\n        elif regularization == 1:\n            # Truncated Gradient\n            # \"Sparse Online Learning via Truncated Gradient\"\n            #  Langford et al. 2009\n            w -= step * gradient_sum /factor_count\n            if truncate:\n                l1delta = reg_param * step * truncation\n                w = max(0, w - l1delta) if w > 0 else min(0, w + l1delta)\n        else:\n            w -= step * gradient_sum /factor_count\n    weight_value[weight_copy][weight_id] = w\n    weight[factor[factor_id]['weightId']]['initialValue'] = w\n    if variable[var_samp][\"isEvidence\"] != 1:\n        poential_weight[factor[factor_id]['weightId']] = w\n\n\n@jit(nopython=True, cache=True, nogil=True)\ndef get_factor_id_range(variable, vmap, var_samp, val):\n    \"\"\"TODO.\"\"\"\n    varval_off = val\n    if variable[var_samp][\"dataType\"] == 0:\n        varval_off = 0\n    vtf = vmap[variable[var_samp][\"vtf_offset\"] + varval_off]\n    start = vtf[\"factor_index_offset\"]\n    end = start + vtf[\"factor_index_length\"]\n    return (start, end)\n\n@jit(nopython=True, cache=True, nogil=True)\ndef sample_and_sgd(var_samp, step, regularization, reg_param, truncation,\n                   var_copy, weight_copy, weight, variable,\n                   factor, fmap,vmap, factor_index, Z,\n                   fids, var_value, var_value_evid,\n                   weight_value, learn_non_evidence,\n                   poential_weight,alpha_bound,tau_bound):\n    \"\"\"TODO.\"\"\"\n    # If learn_non_evidence sample twice.\n    # The method corresponds to expectation-conjugate descent.\n    if variable[var_samp][\"isEvidence\"] != 1:\n        evidence = draw_sample(var_samp, var_copy, weight_copy,\n                               weight, variable, factor,\n                               fmap, vmap, factor_index, Z,\n                               var_value_evid, weight_value)\n        # If evidence then store the initial value in a tmp variable\n    # then sample and compute the gradient.\n    else:\n        evidence = variable[var_samp][\"initialValue\"]\n\n    var_value_evid[var_copy][var_samp] = evidence\n    # Sample the variabl e\n    proposal = draw_sample(var_samp, var_copy, weight_copy, weight,\n                           variable, factor, fmap, vmap,\n                           factor_index, Z, var_value, weight_value)\n\n    var_value[var_copy][var_samp] = proposal\n    if not learn_non_evidence and variable[var_samp][\"isEvidence\"] != 1:\n        return\n    # Compute the gradient and update the weights\n    # Iterate over corresponding factors\n\n    range_fids = get_factor_id_range(variable, vmap, var_samp, evidence)\n    # TODO: is it possible to avoid copying around fids\n    if evidence != proposal:\n        range_prop = get_factor_id_range(variable, vmap, var_samp, proposal)\n        s1 = range_fids[1] - range_fids[0]\n        s2 = range_prop[1] - range_prop[0]\n        s = s1 + s2\n        fids[:s1] = factor_index[range_fids[0]:range_fids[1]]\n        fids[s1:s] = factor_index[range_prop[0]:range_prop[1]]\n        fids[:s].sort()\n    else:\n        s = range_fids[1] - range_fids[0]\n        fids[:s] = factor_index[range_fids[0]:range_fids[1]]\n\n    truncate = random.random() < 1.0 / truncation if regularization == 1 else False\n    # go over all factor ids, ignoring dupes\n    last_fid = -1  # numba 0.28 would complain if this were None\n    for factor_id in fids[:s]:\n        if factor_id == last_fid:\n            continue\n        last_fid = factor_id\n        weight_id = factor[factor_id][\"weightId\"]\n        if weight[weight_id][\"isFixed\"]:\n            continue\n        # Compute Gradient\n        p0 = eval_factor(factor_id, var_samp,\n                         evidence, var_copy,\n                         variable, factor, fmap,\n                         var_value_evid)\n        p1 = eval_factor(factor_id, var_samp,\n                         proposal, var_copy,\n                         variable, factor, fmap,\n                         var_value)\n        #if need parameterize\n        if weight[factor[factor_id]['weightId']]['parameterize'] == 1:\n            x = fmap[factor[factor_id][\"ftv_offset\"]]['x']\n            theta = fmap[factor[factor_id][\"ftv_offset\"]]['theta']\n            a = weight[factor[factor_id]['weightId']]['a']\n            b = weight[factor[factor_id]['weightId']]['b']\n            gradient1 = (p1 - p0) * theta * factor[factor_id][\"featureValue\"] * (x - b)\n            gradient2 = (p1 - p0) * theta * factor[factor_id][\"featureValue\"] * (-a)\n            if regularization == 2:  # 是否需要正则化\n                a *= (1.0 / (1.0 + reg_param * step))\n                a -= step * gradient1\n                b *= (1.0 / (1.0 + reg_param * step))\n                b -= step * gradient2\n            elif regularization == 1:\n            # Truncated Gradient\n            # \"Sparse Online Learning via Truncated Gradient\"\n            #  Langford et al. 2009\n                a -= step * gradient1\n                b -= step * gradient2\n                if truncate:\n                    l1delta = reg_param * step * truncation\n                    a = max(0, a - l1delta) if a > 0 else min(0, a + l1delta)\n                    b = max(0, b - l1delta) if b > 0 else min(0, b + l1delta)\n            else:\n                a -= step * gradient1\n                b -= step * gradient2\n\n            # if alpha_bound != None and tau_bound != None:\n            if a < tau_bound[factor[factor_id]['weightId']]['lowerBound']:\n                a = tau_bound[factor[factor_id]['weightId']]['lowerBound']\n            elif a > tau_bound[factor[factor_id]['weightId']]['upperBound']:\n                a = tau_bound[factor[factor_id]['weightId']]['upperBound']\n            if b > alpha_bound[factor[factor_id]['weightId']]['upperBound']:\n                b = alpha_bound[factor[factor_id]['weightId']]['upperBound']\n            elif  b < alpha_bound[factor[factor_id]['weightId']]['lowerBound']:\n                b = alpha_bound[factor[factor_id]['weightId']]['lowerBound']\n            w = theta * a * (x - b)\n            weight[factor[factor_id]['weightId']]['a'] = a\n            weight[factor[factor_id]['weightId']]['b'] = b\n        #如果不需要参数化\n        elif weight[factor[factor_id]['weightId']]['parameterize'] == 0:\n            gradient = (p1 - p0) * factor[factor_id][\"featureValue\"]\n        # Update weight\n            w = weight_value[weight_copy][weight_id]\n            if regularization == 2:\n                w *= (1.0 / (1.0 + reg_param * step))\n                w -= step * gradient\n            elif regularization == 1:\n            # Truncated Gradient\n            # \"Sparse Online Learning via Truncated Gradient\"\n            #  Langford et al. 2009\n                w -= step * gradient\n                if truncate:\n                    l1delta = reg_param * step * truncation\n                    w = max(0, w - l1delta) if w > 0 else min(0, w + l1delta)\n            else:\n                w -= step * gradient\n        weight_value[weight_copy][weight_id] = w\n        weight[factor[factor_id]['weightId']]['initialValue'] = w\n        if variable[var_samp][\"isEvidence\"] != 1:\n            poential_weight[factor[factor_id]['weightId']] = w\n", "meta": {"hexsha": "43c30cfc83b96d165a88831b9deb36641496ab5f", "size": 16040, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/gradual-ml/numbskull_extend/learning.py", "max_stars_repo_name": "gml-explore/gradual-ml", "max_stars_repo_head_hexsha": "cc3b0806498798c394f844980d268a7ceac2228d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-12-22T13:29:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-08T02:09:00.000Z", "max_issues_repo_path": "src/gradual-ml/numbskull_extend/learning.py", "max_issues_repo_name": "gml-explore/gradual-ml", "max_issues_repo_head_hexsha": "cc3b0806498798c394f844980d268a7ceac2228d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gradual-ml/numbskull_extend/learning.py", "max_forks_repo_name": "gml-explore/gradual-ml", "max_forks_repo_head_hexsha": "cc3b0806498798c394f844980d268a7ceac2228d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-11T01:34:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T08:12:44.000Z", "avg_line_length": 48.7537993921, "max_line_length": 102, "alphanum_fraction": 0.5670822943, "include": true, "reason": "import numpy,import numba,from numba", "num_tokens": 3988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.2942149597859341, "lm_q1q2_score": 0.19163834531409568}}
{"text": "from __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\nimport sys\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nimport torch.nn.utils.rnn as rnn_utils\n\nfrom .loss import (\n    gaussian_log_pdf,\n    unit_gaussian_log_pdf,\n    bernoulli_log_pdf,\n    categorical_program_log_pdf,\n)\nfrom .utils import log_mean_exp\n\n\nclass ProgramRNN(nn.Module):\n    r\"\"\"Supervised recurrent neural network for predicting feedback labels.\n    Parameterizes p(label|program). \n\n    @param z_dim: integer\n                  size of latent vector\n    @param label_dim: integer\n                      number of (binary) labels\n    @param vocab_size: integer\n                       size of vocabulary\n    @param embedding_dim: integer [default: 300]\n                          size of learned embedding\n    @param hidden_dim: integer [default: 256]\n                       size of hidden layer\n    @param word_dropout: float [default: 0.5]\n                         probability to dropout input sequences to decoder\n    @param num_layers: integer [default: 2]\n                       number of hidden layers in GRU\n    \"\"\"\n    def __init__(   self, z_dim, label_dim, vocab_size, embedding_dim=300, \n                    hidden_dim=256, num_layers=2):\n        super(ProgramRNN, self).__init__()\n\n        self.z_dim = z_dim\n        self.label_dim = label_dim\n        self.vocab_size = vocab_size\n        self.embedding_dim = embedding_dim\n        self.hidden_dim = hidden_dim\n        self.num_layers = num_layers\n\n        self.embedding_module = nn.Embedding(self.vocab_size, self.embedding_dim)\n        self.encoder = ProgramEncoder(  self.embedding_module, self.z_dim, \n                                        hidden_dim=self.hidden_dim, \n                                        num_layers=self.num_layers)\n        self.decoder = LabelDecoder(self.z_dim, self.label_dim, \n                                    hidden_dim=self.hidden_dim)\n\n    def forward(self, seq, length):\n        z_mu, _  = self.encoder(seq, length)\n        return self.decoder(z_mu)\n\n\nclass ProgramMVAE(nn.Module):\n    r\"\"\"Multimodal Variational Autoencoder (MVAE) with Expert Supervision.\n    The MVAE is the equivalent of a soft transformation of the expert pCFG graph.\n\n    @param z_dim: integer\n                  size of latent vector\n    @param label_dim: integer\n                      number of (binary) labels\n    @param vocab_size: integer\n                       size of vocabulary\n    @param sutilos_idx: integer\n                    index for start-of-sentence\n    @param eos_idx: integer\n                    index for end-of-sentence\n    @param pad_idx: integer\n                    index for padding\n    @param unk_idx: integer\n                    index for unknown tokens\n    @param embedding_dim: integer [default: 300]\n                          size of learned embedding\n    @param hidden_dim: integer [default: 256]\n                       size of hidden layer\n    @param word_dropout: float [default: 0.5]\n                         probability to dropout input sequences to decoder\n    @param num_layers: integer [default: 2]\n                       number of hidden layers in GRU\n    \"\"\"\n    def __init__(self, z_dim, label_dim, vocab_size, sos_idx, eos_idx, pad_idx, unk_idx,\n                 embedding_dim=300, hidden_dim=256, word_dropout=0.5, num_layers=2):\n        super(ProgramMVAE, self).__init__()\n\n        self.z_dim = z_dim\n        self.label_dim = label_dim\n        self.embedding_dim = embedding_dim\n        self.hidden_dim = hidden_dim\n        self.vocab_size = vocab_size\n        self.sos_idx = sos_idx\n        self.eos_idx = eos_idx\n        self.pad_idx = pad_idx\n        self.unk_idx = unk_idx\n        self.word_dropout = word_dropout\n        self.num_layers = num_layers\n\n        self.product_experts = ProductOfExperts()\n        self.embedding_module = nn.Embedding(self.vocab_size, self.embedding_dim)\n\n        self.program_encoder = ProgramEncoder(  self.embedding_module, self.z_dim, \n                                                hidden_dim=self.hidden_dim, \n                                                num_layers=self.num_layers)\n        self.program_decoder = ProgramDecoder(\n            self.embedding_module, self.z_dim, self.sos_idx, self.eos_idx, self.pad_idx, self.unk_idx,\n            hidden_dim=self.hidden_dim, word_dropout=self.word_dropout, num_layers=self.num_layers)\n        \n        self.label_encoder = LabelEncoder(\n            self.z_dim, self.label_dim, hidden_dim=self.hidden_dim)\n        self.label_decoder = LabelDecoder(\n            self.z_dim, self.label_dim, hidden_dim=self.hidden_dim)\n        \n    def reparameterize(self, z_mu, z_logvar):\n        std = torch.exp(0.5 * z_logvar)\n        eps = torch.randn_like(std)\n        return eps.mul(std).add_(z_mu)\n\n    def forward(self, seq, length, label, hide_seq=False):\n        if hide_seq:\n            z_mu, z_logvar = self.inference(None, None, label)\n        else:\n            z_mu, z_logvar = self.inference(seq, length, label)\n\n        z = self.reparameterize(z_mu, z_logvar)\n        seq_logits = self.program_decoder(z, seq, length)\n        label_out = self.label_decoder(z)\n\n        return seq_logits, label_out, z, z_mu, z_logvar\n\n    def prior_expert(self, mu):\n        p_mu = torch.zeros_like(mu)\n        p_logvar = torch.zeros_like(mu)\n        return p_mu, p_logvar\n\n    def inference(self, seq, length, label):\n        z_mu, z_logvar = [], []\n        \n        if seq is not None:\n            program_mu, program_logvar = self.program_encoder(seq, length)\n            z_mu.append(program_mu.unsqueeze(0))\n            z_logvar.append(program_logvar.unsqueeze(0))\n\n        if label is not None:\n            label_mu, label_logvar = self.label_encoder(label)\n            z_mu.append(label_mu.unsqueeze(0))\n            z_logvar.append(label_logvar.unsqueeze(0))\n\n        prior_mu, prior_logvar = self.prior_expert(z_mu[0])\n        z_mu.append(prior_mu)\n        z_logvar.append(prior_logvar)\n\n        z_mu = torch.cat(z_mu, dim=0)\n        z_logvar = torch.cat(z_logvar, dim=0)\n\n        z_mu, z_logvar = self.product_experts(z_mu, z_logvar)\n\n        return z_mu, z_logvar\n\n    def get_joint_marginal(self, seq, length, label, n_samples=100):\n        z_mu, z_logvar = self.inference(seq, length, label)\n\n        log_w = []\n        for i in xrange(n_samples):\n            z_i = self.reparameterize(z_mu, z_logvar)\n            x_logits_i = self.program_decoder(z_i, seq, length)\n            y_out_i = self.label_decoder(z_i)\n\n            log_p_x_given_z_i = categorical_program_log_pdf(seq[:, 1:], x_logits_i[:, :-1])\n            log_p_y_given_z_i = bernoulli_log_pdf(label, y_out_i)\n            log_q_z_given_x_y_i = gaussian_log_pdf(z_i, z_mu, z_logvar)\n            log_p_z_i = unit_gaussian_log_pdf(z_i)\n\n            log_w_i = log_p_x_given_z_i + log_p_y_given_z_i + log_p_z_i - log_q_z_given_x_y_i\n            log_w.append(log_w_i.unsqueeze(1))\n\n        log_w = torch.cat(log_w, dim=1)\n        log_p_x_y = log_mean_exp(log_w, dim=1)\n        log_p_x_y = -torch.mean(log_p_x_y)\n\n        return log_p_x_y\n\n    def get_program_marginal(self, seq, length, n_samples=100):\n        z_mu, z_logvar = self.inference(seq, length, None)\n\n        log_w = []\n        for i in xrange(n_samples):\n            z_i = self.reparameterize(z_mu, z_logvar)\n            seq_logits_i = self.program_decoder(z_i, seq, length)\n\n            # probability of text is product of probabilities of each word\n            log_p_x_given_z_i = categorical_program_log_pdf(seq[:, 1:], seq_logits_i[:, :-1])\n            log_q_z_given_x_i = gaussian_log_pdf(z_i, z_mu, z_logvar)\n            log_p_z_i = unit_gaussian_log_pdf(z_i)\n\n            log_w_i = log_p_x_given_z_i + log_p_z_i - log_q_z_given_x_i\n            log_w.append(log_w_i.unsqueeze(1))\n\n        log_w = torch.cat(log_w, dim=1)\n        log_p_x = log_mean_exp(log_w, dim=1)\n        log_p_x = -torch.mean(log_p_x)\n\n        return log_p_x\n\n    def get_label_marginal(self, y, n_samples=100):\n        z_mu, z_logvar = self.inference(None, None, y)\n\n        log_w = []\n        for i in xrange(n_samples):\n            z_i = self.reparameterize(z_mu, z_logvar)\n            y_out_i = self.label_decoder(z_i)\n\n            log_p_y_given_z_i = bernoulli_log_pdf(y, y_out_i)\n            log_q_z_given_y_i = gaussian_log_pdf(z_i, z_mu, z_logvar)\n            log_p_z_i = unit_gaussian_log_pdf(z_i)\n\n            log_w_i = log_p_y_given_z_i + log_p_z_i - log_q_z_given_y_i\n            log_w.append(log_w_i.unsqueeze(1))\n\n        log_w = torch.cat(log_w, dim=1)\n        log_p_y = log_mean_exp(log_w, dim=1)\n        log_p_y = -torch.mean(log_p_y)\n\n        return log_p_y\n\n\nclass ProgramEncoder(nn.Module):\n    r\"\"\"Parameterizes q(z|program) with RNN.\n\n    Inspired by Bowman et. al. (https://arxiv.org/abs/1511.06349).\n\n    @param embedding_module: nn.Embedding\n                             we initialize this separately from the encoder\n    @param z_dim: integer\n                  size of latent vector\n    @param hidden_dim: integer [default: 256]\n                       size of hidden layer\n    @param num_layers: integer [default: 2]\n                       number of hidden layers in GRU\n    \"\"\"\n    def __init__(self, embedding_module, z_dim, hidden_dim=256, num_layers=2):\n        super(ProgramEncoder, self).__init__()\n\n        self.embedding = embedding_module\n        self.embedding_dim = self.embedding.embedding_dim\n        self.z_dim = z_dim\n        self.hidden_dim = hidden_dim\n        self.num_layers = num_layers\n\n        self.gru = nn.GRU(self.embedding_dim, self.hidden_dim, num_layers=num_layers)\n        self.h2mu = nn.Linear(self.hidden_dim * self.num_layers, self.z_dim)\n        self.h2logvar = nn.Linear(self.hidden_dim * self.num_layers, self.z_dim)\n\n    def forward(self, seq, length):\n        batch_size = seq.size(0)\n\n        if batch_size > 1:\n            # sort in decreasing order of length in order to pack\n            # sequence; if only 1 element in batch, nothing to do.\n            sorted_lengths, sorted_idx = torch.sort(length, descending=True)\n            seq = seq[sorted_idx]\n\n        embed_seq = self.embedding(seq)\n        # reorder from (B,L,D) to (L,B,D)\n        embed_seq = embed_seq.transpose(0, 1)\n\n        packed = rnn_utils.pack_padded_sequence(\n            embed_seq,\n            sorted_lengths.data.tolist() if batch_size > 1 else length.data.tolist())\n\n        _, hidden = self.gru(packed)\n        hidden = hidden.permute(1, 0, 2).contiguous()\n        hidden = hidden.view(batch_size, self.hidden_dim * self.num_layers)\n\n        if batch_size > 1:\n            _, reversed_idx = torch.sort(sorted_idx)\n            hidden = hidden[reversed_idx]\n\n        z_mu = self.h2mu(hidden)\n        z_logvar = self.h2logvar(hidden)\n\n        return z_mu, z_logvar\n\n\nclass ProgramDecoder(nn.Module):\n    r\"\"\"Parameterizes p(program|z) with RNN to generate a distribution of a \n    sequence of tokens. Assumes a maximum sequence length and a fixed vocabulary.\n\n    We return logits to a categorical so please use\n        nn.CrossEntropy\n    instead of\n        nn.NLLLoss\n\n    Inspired by Bowman et. al. (https://arxiv.org/abs/1511.06349).\n\n    @param embedding_module: nn.Embedding\n                             pass the embedding module (share with encoder)\n    @param z_dim: integer\n                  size of latent vector\n    @param sos_idx: integer\n                    index for start-of-sentence\n    @param eos_idx: integer\n                    index for end-of-sentence\n    @param pad_idx: integer\n                    index for padding\n    @param unk_idx: integer\n                    index for unknown tokens\n    @param hidden_dim: integer [default: 256]\n                       size of hidden layer\n    @param word_dropout: float [default: 0.5]\n                         probability to dropout input sequences to decoder\n    @param num_layers: integer [default: 2]\n                       number of hidden layers in GRU\n    \"\"\"\n    def __init__(   self, embedding_module, z_dim, sos_idx, eos_idx, pad_idx, unk_idx,\n                    hidden_dim=256, word_dropout=0.5, num_layers=2):\n        super(ProgramDecoder, self).__init__()\n\n        self.embedding = embedding_module\n        self.embedding_dim = embedding_module.embedding_dim\n        self.vocab_size = embedding_module.num_embeddings\n        self.z_dim = z_dim\n        self.hidden_dim = hidden_dim\n        self.sos_idx = sos_idx\n        self.eos_idx = eos_idx\n        self.pad_idx = pad_idx\n        self.unk_idx = unk_idx\n        self.word_dropout = word_dropout\n        self.num_layers = num_layers\n        self.gru = nn.GRU(  self.embedding_dim, self.hidden_dim,\n                            num_layers=self.num_layers)\n        self.z2h = nn.Linear(self.z_dim, self.hidden_dim * self.num_layers)\n        self.outputs2vocab = nn.Linear(self.hidden_dim, self.vocab_size)\n\n    def forward(self, z, seq, length):\n        batch_size = z.size(0)\n\n        if batch_size > 1:\n            sorted_lengths, sorted_idx = torch.sort(length, descending=True)\n\n            z = z[sorted_idx]\n            seq = seq[sorted_idx]\n\n        if self.word_dropout > 0:\n            # randomly replace with unknown tokens\n            prob = torch.rand(seq.size())\n            prob[(seq.cpu().data - self.sos_idx) & \\\n                 (seq.cpu().data - self.pad_idx) == 0] = 1\n            mask_seq = seq.clone()\n            mask_seq[(prob < self.word_dropout).to(z.device)] = self.unk_idx\n            seq = mask_seq\n\n        embed_seq = self.embedding(seq)\n        # reorder from (B,L,D) to (L,B,D)\n        embed_seq = embed_seq.transpose(0, 1)\n\n        packed = rnn_utils.pack_padded_sequence(\n            embed_seq,\n            sorted_lengths.data.tolist() if batch_size > 1 else length.data.tolist())\n\n        hidden = self.z2h(z)\n        hidden = hidden.view(batch_size, self.num_layers, self.hidden_dim)\n        hidden = hidden.permute(1, 0, 2).contiguous()\n\n        outputs, _ = self.gru(packed, hidden)\n        outputs = rnn_utils.pad_packed_sequence(outputs, batch_first=True)[0]\n        outputs = outputs.contiguous()\n\n        # reorder from (L,B,D) to (B,L,D)\n        outputs = outputs.transpose(0, 1)\n\n        if batch_size > 1:\n            _, reversed_idx = torch.sort(sorted_idx)\n            outputs = outputs[reversed_idx]\n\n        max_length = outputs.size(1)\n        outputs_2d = outputs.view(batch_size * max_length, self.hidden_dim)\n        outputs_2d = self.outputs2vocab(outputs_2d)\n        outputs = outputs_2d.view(batch_size, max_length, self.vocab_size)\n\n        return outputs.contiguous()\n\n    def sample(self, z, max_seq_len, greedy=False):\n        r\"\"\"Sample tokens in an auto-regressive framework.\n        \n        @param z: torch.Tensor\n                  sample of latent variables\n        @param max_seq_len: integer\n                            maximum size of sequence\n        @param greedy: boolean [default: False]\n                       pick most likely token or sample token?\n        \"\"\"\n        with torch.no_grad():\n            batch_size = z.size(0) \n\n            # initialize hidden state\n            hidden = self.z2h(z)\n            hidden = hidden.view(batch_size, self.num_layers, self.hidden_dim)\n            hidden = hidden.permute(1, 0, 2).contiguous()\n\n            # first input is SOS token\n            inputs = np.array([self.sos_idx for _ in xrange(batch_size)])\n            inputs = torch.from_numpy(inputs)\n            inputs = inputs.unsqueeze(1)\n            inputs = inputs.to(z.device)\n            \n            # save SOS as first generated token\n            inputs_npy = inputs.squeeze(1).cpu().numpy()\n            sampled_ids = [[w] for w in inputs_npy]\n\n            # (B,L,D) to (L,B,D)\n            inputs = inputs.transpose(0, 1)\n\n            # compute embeddings\n            inputs = self.embedding(inputs)\n\n            for i in xrange(max_seq_len):\n                outputs, hidden = self.gru(inputs, hidden)  # outputs: (L=1,B,H)\n                outputs = outputs.squeeze(0)                # outputs: (B,H)\n                outputs = self.outputs2vocab(outputs)       # outputs: (B,V)\n\n                if greedy:\n                    predicted = outputs.max(1)[1]\n                    predicted = predicted.unsqueeze(1)\n                else:\n                    outputs = F.softmax(outputs, dim=1)\n                    predicted = torch.multinomial(outputs, 1)\n\n                predicted_npy = predicted.squeeze(1).cpu().numpy()\n                predicted_lst = predicted_npy.tolist()\n\n                for w, so_far in zip(predicted_lst, sampled_ids):\n                    if so_far[-1] != self.eos_idx:\n                        so_far.append(w)\n\n                inputs = predicted.transpose(0, 1)          # inputs: (L=1,B)\n                inputs = self.embedding(inputs)             # inputs: (L=1,B,E)\n\n            sampled_lengths = [len(text) for text in sampled_ids]\n            sampled_lengths = np.array(sampled_lengths)\n\n            max_length = max(sampled_lengths)\n            padded_ids = np.ones((batch_size, max_length)) * self.pad_idx\n\n            for i in xrange(batch_size):\n                padded_ids[i, :sampled_lengths[i]] = sampled_ids[i]\n\n            sampled_lengths = torch.from_numpy(sampled_lengths).long()\n            sampled_ids = torch.from_numpy(padded_ids).long()\n\n        return sampled_ids, sampled_lengths\n\n\nclass LabelEncoder(nn.Module):\n    r\"\"\"Parameterizes q(z|label).\n\n    @param z_dim: integer\n                  number of latent dimensions\n    @param label_dim: integer\n                      number of label dimensions\n    @param hidden_dim: integer [default: 256]\n                       number of hidden dimensions\n    \"\"\"\n    def __init__(self, z_dim, label_dim, hidden_dim=256):\n        super(LabelEncoder, self).__init__()\n        self.z_dim = z_dim\n        self.label_dim = label_dim\n        self.hidden_dim = hidden_dim\n\n        self.net = nn.Sequential(\n            nn.Linear(self.label_dim, self.hidden_dim),\n            Swish(),\n            nn.Linear(self.hidden_dim, self.hidden_dim),\n            Swish(),\n            # here we don't explicitly separate into (mu, logvar)\n            # but equivalent thing\n            nn.Linear(self.hidden_dim, self.z_dim * 2))\n\n    def forward(self, x):\n        h = self.net(x)\n        z_mu, z_logvar = torch.chunk(h, 2, dim=1)\n\n        return z_mu, z_logvar\n\n\nclass LabelDecoder(nn.Module):\n    r\"\"\"Parameterizes p(label|z).\n    \n    @param z_dim: integer\n                  number of latent dimensions\n    @param label_dim: integer\n                      number of label dimensions\n    @param hidden_dim: integer [default: 256]\n                       number of hidden dimensions\n    \"\"\"\n    def __init__(self, z_dim, label_dim, hidden_dim=256):\n        super(LabelDecoder, self).__init__()\n\n        self.z_dim = z_dim\n        self.label_dim = label_dim\n        self.hidden_dim = hidden_dim\n\n        self.net = nn.Sequential(\n            nn.Linear(self.z_dim, self.hidden_dim),\n            Swish(),\n            nn.Linear(self.hidden_dim, self.hidden_dim),\n            Swish(),\n            nn.Linear(self.hidden_dim, self.hidden_dim),\n            Swish(),\n            nn.Linear(self.hidden_dim, self.label_dim))\n\n    def forward(self, z):\n        # we assume binary labels\n        return torch.sigmoid(self.net(z))\n\n\nclass ProductOfExperts(nn.Module):\n    r\"\"\"Return parameters for product of independent experts.\n    See https://arxiv.org/pdf/1410.7827.pdf for equations.\n\n    @param mu: M x D for M experts\n    @param logvar: M x D for M experts\n    \"\"\"\n    def forward(self, mu, logvar, eps=1e-8):\n        var = torch.exp(logvar) + eps\n        T = 1 / var  # precision of i-th Gaussian expert at point x\n        pd_mu = torch.sum(mu * T, dim=0) / torch.sum(T, dim=0)\n        pd_var = 1 / torch.sum(T, dim=0)\n        pd_logvar = torch.log(pd_var)\n\n        return pd_mu, pd_logvar\n\n\nclass Swish(nn.Module):\n    def forward(self, x):\n        return x * torch.sigmoid(x)\n\n\ndef swish(x):\n    return x * torch.sigmoid(x)\n", "meta": {"hexsha": "4e684a0622546775a0d35bbba5c380a5adf9ee1c", "size": 20086, "ext": "py", "lang": "Python", "max_stars_repo_path": "rubric_sampling/experiments/models.py", "max_stars_repo_name": "YangAzure/rubric-sampling-public", "max_stars_repo_head_hexsha": "24e8c6bc154633566f93a20661c67484029c3591", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2019-01-29T03:21:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T08:52:24.000Z", "max_issues_repo_path": "rubric_sampling/experiments/models.py", "max_issues_repo_name": "YangAzure/rubric-sampling-public", "max_issues_repo_head_hexsha": "24e8c6bc154633566f93a20661c67484029c3591", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rubric_sampling/experiments/models.py", "max_forks_repo_name": "YangAzure/rubric-sampling-public", "max_forks_repo_head_hexsha": "24e8c6bc154633566f93a20661c67484029c3591", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-08-31T11:49:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-18T13:22:58.000Z", "avg_line_length": 36.5865209472, "max_line_length": 102, "alphanum_fraction": 0.6031564274, "include": true, "reason": "import numpy", "num_tokens": 4683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.29746994883293104, "lm_q1q2_score": 0.19163760539955416}}
{"text": "#!/usr/bin/env python\n# -*- coding:utf8 -*-\n\"\"\"\n@author: ruohua\n@file: eval.py\n@time: 2021/2/22 8:03 PM\n\"\"\"\nimport numpy as np\nimport argparse\nfrom multiprocessing.dummy import Pool as ThreadPool\nimport os\nimport cv2\nfrom functools import partial\nimport glob\n\n\ndef single_eval_boundary(fg_boundary, gt_boundary, bound_pix=0):\n    \"\"\"\n    Compute mean,recall and decay from per-frame evaluation.\n    Calculates precision/recall for boundaries between foreground_mask and\n    gt_mask using morphological operators to speed it up.\n\n    Arguments:\n        fg_boundary (ndarray): binary boundary prediction image.     Shape: H x W     Value: 0 and 255\n        gt_boundary (ndarray): binary annotated boundary image.      Shape: H x W     Value: 0 and 255\n        bound_pix: half of the thickness of boundary.\n                  A morphology dilation will make the thickness of edge to what we set here\n                   this is the radius of disk\n\n    Returns:\n        F (float): boundaries F-measure\n        P (float): boundaries precision\n        R (float): boundaries recall\n    \"\"\"\n    assert np.atleast_3d(fg_boundary).shape[2] == 1\n\n    from skimage.morphology import binary_dilation, disk\n\n    fg_dil = binary_dilation(fg_boundary, disk(bound_pix))\n    gt_dil = binary_dilation(gt_boundary, disk(bound_pix))\n\n    # Get the intersection\n    gt_match = gt_boundary * fg_dil\n    fg_match = fg_boundary * gt_dil\n\n    # Area of the intersection\n    n_fg = np.sum(fg_boundary)\n    n_gt = np.sum(gt_boundary)\n\n    # % Compute precision and recall\n    if n_fg == 0 and n_gt > 0:\n        precision = 1\n        recall = 0\n    elif n_fg > 0 and n_gt == 0:\n        precision = 0\n        recall = 1\n    elif n_fg == 0 and n_gt == 0:\n        precision = 1\n        recall = 1\n    else:\n        precision = np.sum(fg_match) / float(n_fg)\n        recall = np.sum(gt_match) / float(n_gt)\n\n    # Compute F meas\n    # ure\n    if precision + recall == 0:\n        F = 0\n    else:\n        F = 2 * precision * recall / (precision + recall)\n\n    return F, precision, recall\n\n\ndef reverse_black_and_white(img):\n    \"\"\"\n    reverse black and white color\n    :param img: binary img\n    :return:\n    \"\"\"\n    img = 255 - img\n\n    return img\n\n\ndef check_if_white_back_black_edge(pred):\n    \"\"\"\n        check if the prediction image is binary\n            1. 0 for membrane; 255 for not manbrane\n            2. check if binary\n    \"\"\"\n    values = np.unique(pred)\n    # print(values)\n\n    # check if binary\n    if len(values) > 2:\n        print(\"Your prediction result has not been binarized, please prompt them to choose the appropriate threshold for binarization.\")\n        raise ValueError\n\n    white_pos = np.where(pred == 255)\n    # print(len(white_pos[0]))\n    white_count = len(white_pos[0])\n    black_pos = np.where(pred == 0)\n    # print(len(black_pos[0]))\n    black_count = len(black_pos[0])\n    # print(black_count / white_count)\n    rate = black_count / white_count\n    if rate < 5:\n        print(\"The results must be submitted with white background and black edge. Please submit after correction.\")\n        raise ValueError\n\n\ndef single_eval_wrapper(bound_pix, result_matrix, data_list_line):\n    id_, pred_path, gt_path = data_list_line\n\n    print(\"Now evaluating the %s prediction, path = %s\" % (id_, pred_path))\n\n    pred_ = cv2.imread(pred_path, 0)\n    gt_ = cv2.imread(gt_path, 0)\n\n    pred_ = reverse_black_and_white(pred_)\n    gt_ = reverse_black_and_white(gt_)\n\n    check_if_white_back_black_edge(pred_)\n\n    F, precision, recall = single_eval_boundary(pred_, gt_, bound_pix)\n\n    result_matrix[int(id_)] = [F, precision, recall]\n\n\ndef eval_on_whole_dataset(pred_folder_path, gt_folder_path, bound_pix, thread_num):\n    pred_list_all =  glob.glob(pred_folder_path + '/*.png')\n    print(pred_list_all)\n\n    gt_list_all = []\n    for pre in pred_list_all:\n        gt_list_all.append(pre.replace(pred_folder_path,gt_folder_path))\n    print(gt_list_all)\n\n    id_list = [x for x in range(len(gt_list_all))]\n\n    gt_list = np.asarray(gt_list_all)\n    pred_list = np.asarray(pred_list_all)\n    id_list = np.asarray(id_list)\n\n    gt_list = np.expand_dims(gt_list, 1)\n    pred_list = np.expand_dims(pred_list, 1)\n    id_list = np.expand_dims(id_list, 1)\n\n    data_list = np.concatenate([id_list, pred_list, gt_list], axis=1)  # data list for pool\n\n    result_matrix = np.zeros_like(data_list)  # each line contains: F-score, precision, recall\n\n    pool = ThreadPool(thread_num) \n\n    pool.map(partial(single_eval_wrapper, bound_pix, result_matrix), data_list)\n\n    pool.close()\n    pool.join()\n\n    result_matrix = np.asarray(result_matrix, dtype=np.float)\n    F_score = result_matrix[:, 0]\n    print(F_score)\n    mean_F = np.mean(F_score)\n\n    return mean_F\n\ndef eval_on_onepic(pred_path, gt_path, bound_pix=0):\n    pred_ = cv2.imread(pred_path, 0)\n    gt_ = cv2.imread(gt_path, 0)\n\n    pred_ = 255 - pred_\n    gt_ = 255 - gt_\n\n    check_if_white_back_black_edge(pred_)\n    print(\"Check format: OK!\")\n\n    F, precision, recall = single_eval_boundary(pred_, gt_, bound_pix=0)\n    return F\n\ndef calc_ap(prec, rec):\n    mrec = np.array([0, rec, 1])\n    mpre = np.array([0, prec, 0])\n\n    for i in range(mrec.size - 2, -1, -1):\n        mpre[i] = max(mpre[i], mpre[i+1]);\n        #print mpre[i]\n\n    idx1 = np.where(mrec[1 : ]   != mrec[0 : 2])\n    idx2 = [x + 1 for x in idx1]\n\n    ap = sum((mrec.take(idx2) - mrec.take(idx1)) * mpre.take(idx2))\n    print(\"ap = \" + str(ap[0]))\n    return ap[0]\n\n\nif __name__ == '__main__':\n\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--evalon1pic', type=str,\n                    default='True', help='if evaluate on one image, True or False')\n    parser.add_argument('--pre_path', type=str,\n                    default='./pre.png', help='prediction path')\n    parser.add_argument('--gt_path', type=str,\n                    default='./gt.png', help='ground truth path')\n    args = parser.parse_args()\n    \n    \n    pre_path = args.pre_path\n    gt_path = args.gt_path\n    bound_pix = 0  # the thickness of boundary\n    thread_num = 4  # number of parallel threads\n\n    print(\"Evaluate on one image? {}\".format(args.evalon1pic))\n\n    if args.evalon1pic == 'True':\n        # eval on single image\n        print(\"evaluate {} and {}\".format(pre_path,gt_path))\n        mean_F = eval_on_onepic(pre_path, gt_path, bound_pix)\n        print(\"The F1-score of prediction is : {}\".format(mean_F))\n\n    if args.evalon1pic == 'False':\n        # eval on folder\n        mean_F = eval_on_whole_dataset(pre_path, gt_path, bound_pix, thread_num)\n        print(\"Mean F_score of all prediction is {}\".format(mean_F))\n\n\n", "meta": {"hexsha": "5cb023fa94c81fa7959e75615012c1c4ce6056e7", "size": 6627, "ext": "py", "lang": "Python", "max_stars_repo_path": "Evaluation/eval.py", "max_stars_repo_name": "EmmaSRH/U-RISC-Data-Code", "max_stars_repo_head_hexsha": "eaddb4a883f1db784834a457fafabad340717bcc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-08T01:11:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T01:11:17.000Z", "max_issues_repo_path": "Evaluation/eval.py", "max_issues_repo_name": "EmmaSRH/U-RISC-Data-Code", "max_issues_repo_head_hexsha": "eaddb4a883f1db784834a457fafabad340717bcc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-07T14:04:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-08T08:16:50.000Z", "max_forks_repo_path": "Evaluation/eval.py", "max_forks_repo_name": "EmmaSRH/U-RISC-Data-Code", "max_forks_repo_head_hexsha": "eaddb4a883f1db784834a457fafabad340717bcc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1938325991, "max_line_length": 136, "alphanum_fraction": 0.6487098234, "include": true, "reason": "import numpy", "num_tokens": 1755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.19139965591472596}}
{"text": "# -*- coding: utf-8 -*-\n# Author: Daniel Ryan <ryand5@tcd.ie>\n\n\"\"\"Some IRIS instrument tools.\"\"\"\n\nimport datetime\nimport warnings\nimport os.path\n\nimport numpy as np\nimport astropy.units as u\nfrom astropy.units.quantity import Quantity\nfrom astropy.modeling import fitting\nfrom astropy.modeling.models import custom_model\nfrom astropy import constants\nimport scipy.io\nfrom scipy import ndimage\nfrom scipy import interpolate\nfrom sunpy.time import parse_time\nimport sunpy.util.config\nfrom sunpy.util.net import check_download_file\nfrom ndcube import NDCube\n\n# Define some properties of IRIS detectors.  Source: IRIS instrument\n# paper.\nDETECTOR_GAIN = {\"NUV\": 18., \"FUV\": 6., \"SJI\": 18.}\nDETECTOR_YIELD = {\"NUV\": 1., \"FUV\": 1.5, \"SJI\": 1.}\nSJI_DEFAULT_BSCALE = 0.25\nSJI_DEFAULT_BZERO = 7992.0\nDN_UNIT = {\n    \"NUV\": u.def_unit(\"DN_IRIS_NUV\",\n                      DETECTOR_GAIN[\"NUV\"] / DETECTOR_YIELD[\"NUV\"]*u.photon),\n    \"FUV\": u.def_unit(\"DN_IRIS_FUV\",\n                      DETECTOR_GAIN[\"FUV\"]/DETECTOR_YIELD[\"FUV\"]*u.photon),\n    \"SJI\": u.def_unit(\"DN_IRIS_SJI\",\n                      DETECTOR_GAIN[\"SJI\"]/DETECTOR_YIELD[\"SJI\"]*u.photon),\n    \"SJI_UNSCALED\": u.def_unit(\"DN_IRIS_SJI_UNSCALED\", u.ct)}\n# Define an equivalency between SJI and SJI_UNSCALED units\nSJI_SCALING = [(DN_UNIT[\"SJI\"],\n                DN_UNIT[\"SJI_UNSCALED\"],\n                lambda x: (x - SJI_DEFAULT_BZERO) / SJI_DEFAULT_BSCALE,\n                lambda x: x * SJI_DEFAULT_BSCALE + SJI_DEFAULT_BZERO)]\n\nREADOUT_NOISE = {\"NUV\": 1.2*DN_UNIT[\"NUV\"],\n                 \"FUV\": 3.1*DN_UNIT[\"FUV\"],\n                 \"SJI\": 1.2*DN_UNIT[\"SJI\"]}\nRADIANCE_UNIT = u.erg / u.cm ** 2 / u.s / u.steradian / u.Angstrom\nSLIT_WIDTH = 0.33*u.arcsec\n\nIRIS_RESPONSE_REMOTE_PATH = \"https://sohowww.nascom.nasa.gov/solarsoft/iris/response/\"\nRESPONSE_VERSION_FILENAMES = {\"1\": \"iris_sra_20130211.geny\",\n                              \"2\": \"iris_sra_20130715.geny\",\n                              \"3\": \"iris_sra_c_20150331.geny\",\n                              \"4\": \"iris_sra_c_20161022.geny\"}\n\n# Define some custom error messages.\nAPPLY_EXPOSURE_TIME_ERROR = (\"Exposure time correction has probably already \"\n                             \"been applied since the unit already includes \"\n                             \"inverse time. To apply exposure time correction \"\n                             \"anyway, set 'force' kwarg to True.\")\nUNDO_EXPOSURE_TIME_ERROR = (\"Exposure time correction has probably already \"\n                            \"been undone since the unit does not include \"\n                            \"inverse time. To undo exposure time correction \"\n                            \"anyway, set 'force' kwarg to True.\")\n\n# Define whether IRIS WCS is 0 or 1 origin based.\nWCS_ORIGIN = 1\n\ndef get_iris_response(pre_launch=False, response_file=None, response_version=None,\n                      force_download=False):\n    \"\"\"Returns IRIS response structure.\n\n    One and only one of pre_launch, response_file and response_version must be set.\n\n    Parameters\n    ----------\n    pre_launch: `bool`\n        Equivalent to setting response_version=2.  Cannot be set\n        simultaneously with response_file kwarg. Default=False\n    response_file: `str`\n        Version number of effective area file to be used.  Cannot be set\n        simultaneously with pre_launch kwarg.  Default=latest\n    response_version : `int`\n        Version number of effective area file to be used. Cannot be set\n        simultaneously with response_file or pre_launch kwarg. Default=latest\n\n    Returns\n    -------\n    iris_response: `dict`\n        Various parameters regarding IRIS response.  The following keys:\n        date_obs: `datetime.datetime`\n        lambda: `astropy.units.Quantity`\n        area_sg: `astropy.units.Quantity`\n        name_sg: `str`\n        dn2phot_sg: `tuple` of length 2\n        area_sji: `astropy.units.Quantity`\n        name_sji: `str`\n        dn2phot_sji:  `tuple` of length 4\n        comment: `str`\n        version: `int`\n        version_date: `datetime.datetime`\n\n    Notes\n    -----\n    This routine does not calculate time dependent effective areas using\n    version 3 and above of the response functions as is done in the SSW version\n    of this code.  Therefore, asking it to read a version 3 or above response\n    function will result in an error.  This code should be updated in future\n    versions to calculate time dependent effective areas.\n\n    \"\"\"\n    # Ensures the file exits in the path given.\n    if response_file is not None:\n        if not(os.path.isfile(response_file)):\n            raise KeyError(\"Not a valid file path\")\n\n    # Ensure conflicting kwargs are not set.\n    if response_file:\n        response_file_set = True\n    else:\n        response_file_set = False\n    if response_version:\n        response_version_set = True\n    else:\n        response_version_set = False\n    if response_file_set+pre_launch+response_version_set != 1:\n        raise ValueError(\"One and only one of kwargs pre_launch, response_file \"\n                         \"and response_version must be set.\")\n    # If pre_launch set, define response_version to 2.\n    if pre_launch:\n        response_version = 2\n    # If response_file not set, define appropriate response file\n    # based on version.\n    if not response_file:\n        try:\n            response_filename = RESPONSE_VERSION_FILENAMES[str(response_version)]\n        except KeyError:\n            raise KeyError(\"Version number not recognized.\")\n        if response_version > 2:\n            warnings.warn(\"Effective areas are not available (i.e. set  to zero).  \"\n                  \"For response file versions > 2 time dependent effective \"\n                  \"areas must be calculated via fitting, which is not supported \"\n                  \"by this function at this time. \"\n                  \"Version of this response file = {0}\".format(response_version))\n        # Define the directory in which the response file should exist\n        # to be the sunpy download directory.\n        config = sunpy.util.config.load_config()\n        download_dir = config.get('downloads', 'download_dir')\n        # Check response file exists in download_dir.  If not, download it.\n        check_download_file(response_filename, IRIS_RESPONSE_REMOTE_PATH, download_dir,\n                            replace=force_download)\n        # Define response file as path + filename.\n        response_file = os.path.join(download_dir, response_filename)\n\n    # Read response file and store in a dictionary.\n    raw_response_data = scipy.io.readsav(response_file)\n    iris_response = dict([(name, raw_response_data[\"p0\"][name][0])\n                          for name in raw_response_data[\"p0\"].dtype.names])\n    # Convert some properties to more convenient types.\n    iris_response[\"LAMBDA\"] = Quantity(iris_response[\"LAMBDA\"], unit=u.nm)\n    iris_response[\"AREA_SG\"] = Quantity(iris_response[\"AREA_SG\"], unit=u.cm**2)\n    iris_response[\"AREA_SJI\"] = Quantity(iris_response[\"AREA_SJI\"], unit=u.cm**2)\n    iris_response[\"GEOM_AREA\"] = Quantity(iris_response[\"GEOM_AREA\"], unit=u.cm**2)\n    iris_response[\"VERSION\"] = int(iris_response[\"VERSION\"])\n    # Convert some properties not found in version below version 3 to\n    # more convenient types.\n    if iris_response[\"VERSION\"] > 2:\n        # If DATE_OBS has a value, convert to datetime, else set to\n        # None.\n        try:\n            iris_response[\"DATE_OBS\"] = parse_time(iris_response[\"DATE_OBS\"])\n        except:\n            iris_response[\"DATE_OBS\"] = None\n        # Convert C_F_TIME to array of datetime objects while\n        # conserving shape.\n        c_f_time = np.empty(iris_response[\"C_F_TIME\"].shape, dtype=object)\n        for i, row in enumerate(iris_response[\"C_F_TIME\"]):\n            for j, t in enumerate(row):\n                c_f_time[i][j] = parse_time(float(t))\n        iris_response[\"C_F_TIME\"] = c_f_time\n        # Convert C_F_LAMBDA to Quantity.\n        iris_response[\"C_F_LAMBDA\"] = Quantity(iris_response[\"C_F_LAMBDA\"], unit=\"nm\")\n        # Convert C_N_TIME to array of datetime objects while\n        # conserving shape.\n        c_n_time = np.empty(iris_response[\"C_N_TIME\"].shape, dtype=object)\n        for i, row in enumerate(iris_response[\"C_N_TIME\"]):\n            for j, t in enumerate(row):\n                c_n_time[i][j] = parse_time(float(t))\n        iris_response[\"C_N_TIME\"] = c_n_time\n        # Convert C_N_LAMBDA to Quantity.\n        iris_response[\"C_N_LAMBDA\"] = Quantity(iris_response[\"C_N_LAMBDA\"], unit=\"nm\")\n        # Convert C_S_TIME to array of datetime objects while\n        # conserving shape.\n        c_s_time = np.empty(iris_response[\"C_S_TIME\"].shape, dtype=object)\n        for i, row in enumerate(iris_response[\"C_S_TIME\"]):\n            for j, column in enumerate(row):\n                for k, t in enumerate(column):\n                    c_s_time[i][j][k] = parse_time(float(t))\n        iris_response[\"C_S_TIME\"] = c_s_time\n        # Convert DATE in ELEMENTS array to array of datetime objects.\n        for i, t in enumerate(iris_response[\"ELEMENTS\"][\"DATE\"]):\n            iris_response[\"ELEMENTS\"][\"DATE\"][i] = parse_time(t.decode())\n        # Convert VERSION_DATE to datetime object.\n        iris_response[\"VERSION_DATE\"] = parse_time(iris_response[\"VERSION_DATE\"].decode())\n    else:\n        # Change DATE tag in data with version < 2 to VERSION_DATE to\n        # be consistent with more recent versions.\n        iris_response[\"VERSION_DATE\"] = datetime.datetime(int(iris_response[\"DATE\"][0:4]),\n                                                          int(iris_response[\"DATE\"][4:6]),\n                                                          int(iris_response[\"DATE\"][6:8]))\n        del(iris_response[\"DATE\"])\n    return iris_response\n\n\n@custom_model\ndef _gaussian1d_on_linear_bg(x, amplitude=None, mean=None, standard_deviation=None,\n                             constant_term=None, linear_term=None):\n    return amplitude * np.exp(-((x - mean) / standard_deviation) ** 2) + constant_term + linear_term * x\n\n\ndef _calculate_orbital_wavelength_variation(data_array, date_data_created, slit_pixel_range=None,\n                                            spline_smoothing=False, fit_individual_profiles=False,\n                                            spacecraft_velocity=None, orbital_phase=None, roll_angle=None):\n    \"\"\"Calculates orbital corrections of spectral line positions using level 2 files.\n\n    For data generated from the April 2014 pipeline, thermal and spacecraft velocity components\n    have both been subtracted in the level 2 files.  Therefore, this routine calculates the\n    residual orbital (thermal) variation.  For data generated from the Oct 2013 pipeline,\n    this routine calculates the total of thermal and spacecraft velocity components.\n\n    Parameters\n    ----------\n    data_array: `xarray.DataArray`\n        IRIS spectrograph data from spectral window Mg II k 2796 as generated by\n        `sunpy.spectra.sources.IRISRaster.`\n    date_data_created: `datetime.datetime`\n        Date the data was created by IRIS pipeline.  Used to determine where spacecraft\n        velocity etc. needs to be accounted for.\n    spacecraft_velocity: `astropy.units.quantity.Quantity`\n        Velocity of spacecraft at each exposure in data_array.\n        Must be set if date_data_created < 1 April 2014.\n    orbital_phase: `numpy.array`\n        Orbital phase of spacecraft at each exposure in data_array.  Available from\n        auxiliary data in IRIS spectrograph fits files.\n        Must be set if date_data_created < 1 April 2014.\n    roll_angle: `astropy.units.quantity.Quantity`\n        Roll angle of spacecraft. Must be set if date_data_created < 1 April 2014.\n\n    Returns\n    -------\n    orbital_wavelength_variation: `astropy.table.Table`\n        Contains the following columns:\n        time: `datetime.datetime` objects\n            Observation times of wavelength variations.\n        FUV: `astropy.quantity.Quantity`\n            Wavelength variation in the FUV.\n        NUV: `astropy.quantity.Quantity`\n            Wavelength variation in the NUV.\n\n    \"\"\"\n    # Define vacuum rest wavelength of Ni I 2799 line.\n    wavelength_nii = 2799.474 * u.Angstrom\n    # Define factor converting NUV spectral pixel size to Angstrom\n    specsize = 0.0255\n    # Define date of new pipeline.\n    date_new_pipeline = datetime.datetime(2014, 4, 1)\n    if date_data_created < date_new_pipeline:\n        # Check that there are measurement times with good values of\n        # spacecraft velocity and orbital phase.\n        bad_aux = np.asarray(np.isfinite(spacecraft_velocity) * np.isfinite(orbital_phase) * (-1), dtype=bool)\n    # Generate wavelength vector containing only Ni I line.\n    wavelength_window = Quantity(data_array.coords[\"wavelength\"].values,\n                                 unit=data_array.attrs[\"units\"][\"wavelength\"])\n    wavelength_roi_index = np.arange(len(wavelength_window))[\n        np.logical_and(wavelength_window >= 2799.3 * u.Angstrom, wavelength_window <= 2799.8 * u.Angstrom)]\n    # Check that there are at least 5 points in wavelength region.\n    # Must have at least this many for a gaussian fit.\n    if len(wavelength_roi_index) < 5:\n        wavelength_roi_index = np.arange(5) + wavelength_roi_index[0]\n    # Extract wavelength of region around Ni I line as array in units\n    # of Angstroms.\n    wavelength_roi = wavelength_window.to(u.Angstrom).value[wavelength_roi_index]\n    # Keep only data within wavelength region of interest.\n    data_array = data_array.isel(spectral_axis=slice(wavelength_roi_index[0], wavelength_roi_index[-1] + 1))\n    # If user selected a sub-region of the slit, reduce data to just\n    # that region.\n    if slit_pixel_range:\n        if len(slit_pixel_range) == 2:\n            data_array = data_array.isel(slit_axis, slice(slit_pixel_range[0], slit_pixel_range[1]))\n        else:\n            raise TypeError(\"slit_pixel_range must be tuple of length 2 giving lower and \" +\n                            \"upper bounds of section of slit over which to average line fits.\")\n\n    # Derive residual orbital variation.\n    # Define array to hold averaged position of Ni I line at different\n    # times.\n    mean_line_wavelengths = np.empty(len(data_array.time)) * np.nan\n    # Define initial guess for gaussian model.\n    g_init = _gaussian1d_on_linear_bg(amplitude=-2., mean=wavelength_nii.value,\n                                      standard_deviation=2., constant_term=50., linear_term=1.5)\n    # Define fitting method.\n    fit_g = fitting.LevMarLSQFitter()\n    # Depending on user choice, either fit line as measured by each\n    # pixel then average line position, or fit average line spectrum\n    # from all slit pixels.\n    if fit_individual_profiles:\n        pixels_in_slit = len(raster.slit_axis)\n        for k in range(len(raster.time)):\n            pixel_line_wavelengths = np.empty(pixels_in_slit)*np.nan\n            data_single_time = raster.isel(raster_axis=k)\n            # Iterate through each pixel along slit and perform fit to\n            # Ni I line.\n            for j in range(2, pixels_in_slit-2):\n                # Average over 5 pixels to improve signal-to-noise.\n                intensity_mean_5pix = data_single_time.isel(slit_axis=slice(j-2, j+3)).mean(axis=0)\n                # Fit gaussian to Ni I line.\n                g = fit_g(g_init, wavelength_roi, intensity_mean_5pix)\n                # Check that fit is within physically reasonable\n                # limits.  If so, store line center wavelength in\n                # mean_line_wavelengths array. Else leave element as\n                # defined, i.e. NaN.\n                if np.isfinite(g.amplitude) and g.amplitude < 0. and \\\n                            wavelength_roi[0] < g.mean < wavelength_roi[-1]:\n                    pixel_line_wavelengths[j] = g.mean\n            # Take average of Ni I line position from fits in each\n            # pixel.\n            mean_line_wavelengths[k] = np.nanmean(pixel_line_wavelengths)\n    else:\n        # Else average all line profiles then perform fit.\n        # Iterate through each measurement time and fit a gaussian to\n        # Ni I line.\n        for k in range(len(raster.time)):\n            # Get data averaged over slit.\n            data_single_time = raster.isel(raster_axis=k)\n            data_slit_averaged = data_single_time.to_masked_array().mean(axis=0).data\n            # Fit Ni I line with a gaussian.\n            # Perform fit.\n            g = fit_g(g_init, wavelength_roi, data_slit_averaged)\n            # Check that fit is within physically reasonable limits.\n            # If so, store line center wavelength in\n            # mean_line_wavelengths array. Else leave element as\n            # defined, i.e. NaN.\n            if np.isfinite(g.amplitude) and g.amplitude < 0. and \\\n                        wavelength_roi[0] < g.mean < wavelength_roi[-1]:\n                mean_line_wavelengths[k] = g.mean\n            # If data produced by old pipeline, subtract spacecraft velocity\n            # from the line position.\n            if date_created < date_new_pipeline:\n                mean_line_wavelengths[k] = \\\n                    mean_line_wavelengths[k]-spacecraft_velocity[k]/3e8*wavelength_nii.to(u.Angstrom).value\n\n    # Mark abnormal values.  Thermal drift is of the order of 2\n    # unsummed wavelength pixels peak-to-peak.\n    w_abnormal = np.where(np.abs(mean_line_wavelengths-np.nanmedian(mean_line_wavelengths)) >= specsize*2)[0]\n    if len(w_abnormal) > 0:\n        mean_line_wavelengths[w_abnormal] = np.nan\n    # Further data reduction required for files from old pipeline.\n    if date_created < date_new_pipeline:\n        dw_th_A = mean_line_wavelengths - np.nanmean(mean_line_wavelengths)\n        # Change the unit from Angstrom into unsummed wavelength pixel.\n        dw_th_p = dw_th_A/specsize\n        # Adjust reference wavelength using orbital phase information.\n        if not(np.isfinite(orbital_phase)).all():\n            warnings.warn(\"Orbital phase values are invalid.  Thermal drift may be offset by at most one pixel.\")\n            dw_th = dw_th\n            # For absolute wavelength calibration of NUV, the\n            # following amount (unit Angstrom) has to be\n            # subtracted from the wavelengths.\n            abswvl_nuv = np.nanmean(mean_line_wavelengths)-wavelength_nii.to(u.Angstrom).value\n        else:\n            # Define empirical sine fitting at 0 roll angle shifted by\n            # different phase.\n            sine_params = [-0.66615146, -1.0, 53.106583-roll_angle/360.*2*np.pi]\n            phase_adj=np.nanmean(sine_params[0]*np.sin(sine_params[1]*orbital_phase+sine_params[2]))\n            # thermal component of the orbital variation, in the unit of unsummed wavelength pixel\n            dw_th=dw_th_p+phase_adj\n            # For absolute wavelength calibration of NUV the following\n            # amount (unit Angstrom) has to be subtracted from the\n            # wavelengths.\n            abswvl_nuv = np.nanmean(mean_line_wavelengths)-wavelength_nii.to(u.Angstrom).value-phase_adj*specsize\n    else:\n        # Calculate relative variation of the line position.\n        dw_th = mean_line_wavelengths-np.nanmean(mean_line_wavelengths)\n\n    # If spline_smoothing=True, perform spline fit a smoothing to\n    # eliminate the 5 minute photospheric oscillation.\n    if spline_smoothing:\n        # Define spacing of spline knots in seconds.\n        spline_knot_spacing = 300.\n        # Create array of time in seconds from first time and\n        # calculate duration of fitting period.\n        time_s = np.asarray(x.coords[\"time\"]-x.coords[\"time\"][0], dtype=float)/1e9\n        duration = time_s[-1]-time_s[0]\n        # Check whether there is enough good data for a spline fit.\n        if duration < spline_knot_spacing:\n            raise ValueError(\"Not enough data for spline fit.\")\n        # Check whether there is enough good data for a spline fit.\n        wgood = np.isfinite(mean_line_wavelengths)\n        ngood = float(sum(wgood))\n        wbad = not(np.isfinite(mean_line_wavelengths))\n        nbad = float(sum(wbad))\n        if nbad/ngood > 0.25:\n            raise ValuError(\"Not enough good data for spline fit.\")\n        # Smooth residual thermal variation curve to eliminate the\n        # 5-min photospheric oscillation.\n        # Determine number of smoothing point using 3 point\n        # lagrangian derivative.\n        deriv_time = np.array([(time_s[i+1]-time_s[i-1])/2. for i in range(1,len(time_s)-1)])\n        deriv_time = np.insert(deriv_time, 0, (-3*time_s[0]+4*time_s[1]-time_s[2])/2)\n        deriv_time = np.insert(deriv_time, -1, (3*time_s[-1]-4*time_s[-2]+time_s[-3])/2)\n        n_smooth = int(spline_knot_spacing/deriv_time.mean())\n        if n_smooth < len(wgood):\n            dw_good = convolve(dw_th[good], Box1DKernel(n_smooth))\n        else:\n            dw_good = dw_th[good]\n        time_good = time_s[good]\n        # Fit spline.\n        tck = interpolate.splrep(time_good, dw_good, s=0)\n        dw_th = interpolate.splev(time_s, tck)\n\n    # Derive residual orbital curves in FUV and NUV and store\n    # in a table.\n    times = [datetime.datetime.utcfromtimestamp(t/1e9) for t in raster.coords[\"time\"].values.tolist()]\n    # Depeding on which pipeline produced the files...\n    if date_created < date_new_pipeline:\n        dw_orb_fuv = dw_th * (-0.013) + spacecraft_velocity.to(u.km/u.s).value / (3.e5) * 1370. * u.Angstrom\n        dw_orb_nuv = dw_th * 0.0255 + spacecraft_velocity.to(u.km/u.s).value / (3.e5) * 2800. * u.Angstrom\n    else:\n        dw_orb_fuv = dw_th*(-1)*u.Angstrom\n        dw_orb_nuv = dw_th*u.Angstrom\n\n    orbital_wavelength_variation = Table([times, dw_orb_fuv, dw_orb_nuv],\n                                         names=(\"time\", \"wavelength variation FUV\", \"wavelength variation NUV\"))\n    return orbital_wavelength_variation\n\ndef get_detector_type(meta):\n    \"\"\"\n    Gets the IRIS detector type from a meta dictionary.\n\n    In this function, FUV1 and FUV2 are just assigned as FUV.\n\n    Parameters\n    ----------\n    meta: dict-like\n        Dictionary-like object containing entry for \"detector type\"\n\n    Returns\n    -------\n    detector_type: `str`\n       Detector type.\n\n    \"\"\"\n    if \"FUV\" in meta[\"detector type\"]:\n        detector_type = \"FUV\"\n    else:\n        detector_type = meta[\"detector type\"]\n    return detector_type\n\ndef convert_between_DN_and_photons(old_data_arrays, old_unit, new_unit):\n    \"\"\"Converts arrays from IRIS DN to photons or vice versa.\n\n    In this function, an inverse time component due to exposure time\n    correction is ignored during calculations but preserved in final unit.\n\n    Parameters\n    ----------\n    old_data_arrays: iterable of `numpy.ndarray`s\n        Arrays of data to be converted.\n\n    old_unit: `astropy.unit.Unit`\n        Unit of data arrays.\n\n    new_unit: `astropy.unit.Unit`\n        Unit to convert data arrays to.\n\n    Returns\n    -------\n    new_data_arrays: `list` of `numpy.ndarray`s\n        Data arrays converted to new_unit.\n\n    new_unit_time_accounted: `astropy.unit.Unit`\n        Unit of new data arrays with any inverse time component preserved.\n\n    \"\"\"\n    if old_unit == new_unit or old_unit == new_unit / u.s:\n        new_data_arrays = [data for data in old_data_arrays]\n        new_unit_time_accounted = old_unit\n    else:\n        # During calculations, the time component due to exposure\n        # time correction, if it has been applied, is ignored.\n        # Check here whether the time correction is present in the\n        # original unit so that is carried through to new unit.\n        if u.s not in (old_unit * u.s).decompose().bases:\n            old_unit_without_time = old_unit * u.s\n            new_unit_time_accounted = new_unit / u.s\n        else:\n            old_unit_without_time = old_unit\n            new_unit_time_accounted = new_unit\n        # Convert data and uncertainty to new unit.\n        new_data_arrays = [(data * old_unit_without_time).to(new_unit).value\n                           for data in old_data_arrays]\n    return new_data_arrays, new_unit_time_accounted\n\ndef calculate_exposure_time_correction(old_data_arrays, old_unit, exposure_time,\n                                       force=False):\n    \"\"\"\n    Applies exposure time correction to data arrays.\n\n    Parameters\n    ----------\n    old_data_arrays: iterable of `numpy.ndarray`s\n        Arrays of data to be converted.\n\n    old_unit: `astropy.unit.Unit`\n        Unit of data arrays.\n\n    exposure_time: `numpy.ndarray`\n        Exposure time in seconds for each exposure in data arrays.\n\n    Returns\n    -------\n    new_data_arrays: `list` of `numpy.ndarray`s\n        Data arrays with exposure time corrected for.\n\n    new_unit_time_accounted: `astropy.unit.Unit`\n        Unit of new data arrays after exposure time correction.\n\n    \"\"\"\n    # If force is not set to True and unit already includes inverse time,\n    # raise error as exposure time correction has probably already been\n    # applied and should not be applied again.\n    if force is not True and u.s in old_unit.decompose().bases:\n        raise ValueError(APPLY_EXPOSURE_TIME_ERROR)\n    else:\n        # Else, either unit does not include inverse time and so\n        # exposure does need to be applied, or\n        # user has set force=True and wants the correction applied\n        # regardless of the unit.\n        new_data_arrays = [old_data/exposure_time for old_data in old_data_arrays]\n        new_unit = old_unit/u.s\n    return new_data_arrays, new_unit\n\ndef uncalculate_exposure_time_correction(old_data_arrays, old_unit, exposure_time,\n                                         force=False):\n    \"\"\"\n    Removes exposure time correction from data arrays.\n\n    Parameters\n    ----------\n    old_data_arrays: iterable of `numpy.ndarray`s\n        Arrays of data to be converted.\n\n    old_unit: `astropy.unit.Unit`\n        Unit of data arrays.\n\n    exposure_time: `numpy.ndarray`\n        Exposure time in seconds for each exposure in data arrays.\n\n    Returns\n    -------\n    new_data_arrays: `list` of `numpy.ndarray`s\n        Data arrays with exposure time correction removed.\n\n    new_unit_time_accounted: `astropy.unit.Unit`\n        Unit of new data arrays after exposure time correction removed.\n\n    \"\"\"\n    # If force is not set to True and unit does not include inverse time,\n    # raise error as exposure time correction has probably already been\n    # undone and should not be undone again.\n    if force is not True and u.s in (old_unit*u.s).decompose().bases:\n        raise ValueError(UNDO_EXPOSURE_TIME_ERROR)\n    else:\n        # Else, either unit does include inverse time and so\n        # exposure does need to be removed, or\n        # user has set force=True and wants the correction removed\n        # regardless of the unit.\n        new_data_arrays = [old_data * exposure_time for old_data in old_data_arrays]\n        new_unit = old_unit*u.s\n    return new_data_arrays, new_unit\n\ndef convert_or_undo_photons_per_sec_to_radiance(\n        data_quantities, obs_wavelength, detector_type,\n        spectral_dispersion_per_pixel, solid_angle, undo=False):\n    \"\"\"\n    Converts data quantities from counts/s to radiance (or vice versa).\n\n    Parameters\n    ----------\n    data_quantities: iterable of `astropy.units.Quantity`s\n        Quantities to be converted.  Must have units of counts/s or\n        radiance equivalent counts, e.g. erg / cm**2 / s / sr / Angstrom.\n\n    obs_wavelength: `astropy.units.Quantity`\n        Wavelength at each element along spectral axis of data quantities.\n\n    detector_type: `str`\n        Detector type: 'FUV', 'NUV', or 'SJI'.\n\n    spectral_dispersion_per_pixel: scalar `astropy.units.Quantity`\n        spectral dispersion (wavelength width) of a pixel.\n\n    solid_angle: scalar `astropy.units.Quantity`\n        Solid angle corresponding to a pixel.\n\n    undo: `bool`\n        If False, converts counts/s to radiance.\n        If True, converts radiance to counts/s.\n        Default=False\n\n    Returns\n    -------\n    new_data_quantities: `list` of `astropy.units.Quantity`s\n        Data quantities converted to radiance or counts/s\n        depending on value of undo kwarg.\n\n    \"\"\"\n    # Check data quantities are in the right units.\n    if undo is True:\n        for i, data in enumerate(data_quantities):\n            if not data.unit.is_equivalent(RADIANCE_UNIT):\n                raise ValueError(\n                    \"Invalid unit provided.  As kwarg undo=True, \"\n                    \"unit must be equivalent to {0}.  Error found for {1}th element \"\n                    \"of data_quantities. Unit: {2}\".format(RADIANCE_UNIT, i, data.unit))\n    else:\n        for data in data_quantities:\n            if data.unit != u.photon/u.s:\n                raise ValueError(\n                    \"Invalid unit provided.  As kwarg undo=False, \"\n                    \"unit must be equivalent to {0}.  Error found for {1}th element \"\n                    \"of data_quantities. Unit: {2}\".format(u.photon/u.s, i, data.unit))\n    photons_per_sec_to_radiance_factor = calculate_photons_per_sec_to_radiance_factor(\n        obs_wavelength, detector_type, spectral_dispersion_per_pixel, solid_angle)\n    # Change shape of arrays so they are compatible for broadcasting\n    # with data and uncertainty arrays.\n    photons_per_sec_to_radiance_factor = \\\n        _reshape_1D_wavelength_dimensions_for_broadcast(photons_per_sec_to_radiance_factor,\n                                                        data_quantities[0].ndim)\n    # Perform (or undo) radiometric conversion.\n    if undo is True:\n        new_data_quantities = [(data / photons_per_sec_to_radiance_factor).to(u.photon/u.s)\n                               for data in data_quantities]\n    else:\n        new_data_quantities = [(data*photons_per_sec_to_radiance_factor).to(RADIANCE_UNIT)\n                               for data in data_quantities]\n    return new_data_quantities\n\ndef calculate_photons_per_sec_to_radiance_factor(\n        wavelength, detector_type, spectral_dispersion_per_pixel, solid_angle):\n    \"\"\"\n    Calculates multiplicative factor that converts counts/s to radiance for given wavelengths.\n\n    Parameters\n    ----------\n    wavelength: `astropy.units.Quantity`\n        Wavelengths for which counts/s-to-radiance factor is to be calculated\n\n    detector_type: `str`\n        Detector type: 'FUV' or 'NUV'.\n\n    spectral_dispersion_per_pixel: scalar `astropy.units.Quantity`\n        spectral dispersion (wavelength width) of a pixel.\n\n    solid_angle: scalar `astropy.units.Quantity`\n        Solid angle corresponding to a pixel.\n\n    Returns\n    -------\n    radiance_factor: `astropy.units.Quantity`\n        Mutliplicative conversion factor from counts/s to radiance units\n        for input wavelengths.\n\n    \"\"\"\n    # Get effective area and interpolate to observed wavelength grid.\n    eff_area_interp = _get_interpolated_effective_area(detector_type, wavelength)\n    # Return radiometric conversed data assuming input data is in units of photons/s.\n    return constants.h * constants.c / wavelength / u.photon / \\\n           spectral_dispersion_per_pixel / eff_area_interp / solid_angle\n\ndef _get_interpolated_effective_area(detector_type, obs_wavelength):\n    # Get effective area\n    ########### This needs to be generalized to the time of OBS once that functionality is written #########\n    iris_response = get_iris_response(pre_launch=True)\n    if detector_type == \"FUV\":\n        detector_type_index = 0\n    elif detector_type == \"NUV\":\n        detector_type_index = 1\n    else:\n        raise ValueError(\"Detector type not recognized.\")\n    eff_area = iris_response[\"AREA_SG\"][detector_type_index, :]\n    response_wavelength = iris_response[\"LAMBDA\"]\n    # Interpolate the effective areas to cover the wavelengths\n    # at which the data is recorded:\n    eff_area_interp_base_unit = u.Angstrom\n    tck = interpolate.splrep(response_wavelength.to(eff_area_interp_base_unit).value,\n                             eff_area.to(eff_area_interp_base_unit ** 2).value, s=0)\n    eff_area_interp = interpolate.splev(\n        obs_wavelength.to(eff_area_interp_base_unit).value, tck) * eff_area_interp_base_unit ** 2\n    return eff_area_interp\n\ndef _reshape_1D_wavelength_dimensions_for_broadcast(wavelength, n_data_dim):\n    if n_data_dim == 1:\n        pass\n    elif n_data_dim == 2:\n        wavelength = wavelength[np.newaxis, :]\n    elif n_data_dim == 3:\n        wavelength = wavelength[np.newaxis, np.newaxis, :]\n    else:\n        raise ValueError(\"IRISSpectrogram dimensions must be 2 or 3.\")\n    return wavelength\n\ndef _convert_iris_sequence(sequence, new_unit):\n    \"\"\"Converts data and uncertainty in an IRISSpectrogramSequence between units.\n\n    Parameters\n    ----------\n    sequence: `NDCubeSequence`, `SpectrogramSequence` or `IRISSpectrogramSequence`\n        Sequence whose constituent NDCubes are be converted to new units.\n\n    new_unit: `astropy.units.Unit` or `str`\n       Unit to which the data is to be converted.\n\n    Returns\n    -------\n    converted_data_list: `list` of `NDCube`s.\n       List of NDCubes with data and uncertainty attributes converted to new_unit.\n\n    \"\"\"\n    # Define empty list to hold NDCubes with converted data and uncertainty.\n    converted_data_list = []\n    # Cycle through each NDCube, convert data and uncertainty to new\n    # units, and append to list.\n    for i, cube in enumerate(sequence.data):\n        # Determine what type of DN unit is needed based on detector type.\n        detector_type = _get_detector_type(cube.meta)\n        if new_unit == \"DN\":\n            new_unit = DN_UNIT[detector_type]\n        # If NDCube is already in new unit, add NDCube as is to list.\n        if cube.unit is new_unit or cube.unit is new_unit / u.s:\n            converted_data_list.append(cube)\n        # Else convert data and uncertainty to new unit.\n        if cube.unit != new_unit or cube.unit != new_unit / u.s:\n            # During calculations, the time component due to exposure\n            # time correction, if it has been applied, is ignored.\n            # Check here whether the time correction is present in the\n            # original unit so that is carried through to new unit.\n            if u.s not in (cube.unit.decompose() * u.s).bases:\n                new_unit_time_accounted = new_unit / u.s\n            else:\n                new_unit_time_accounted = new_unit\n            # Convert data and uncertainty to new unit.\n            data = (cube.data * cube.unit).to(new_unit).value\n            uncertainty = (cube.uncertainty.array * cube.unit).to(new_unit).value\n            # Append new instance of NDCube in new unit to list.\n            converted_data_list.append(NDCube(\n                data, wcs=cube.wcs, meta=cube.meta, mask=cube.mask,\n                unit=new_unit_time_accounted, uncertainty=uncertainty,\n                extra_coords=_extra_coords_to_input_format(cube._extra_coords)))\n    return converted_data_list\n\ndef _apply_or_undo_exposure_time_correction(sequence, correction_function):\n    \"\"\"Applies or undoes exposure time correction to a sequence of NDCubes.\n\n    Correction is applied (or undone) to both data and uncertainty attributes of NDCubes.\n\n    Parameters\n    ----------\n    sequence: `NDCubeSequence`, `SpectrogramSequence` or `IRISSpectrogramSequence`\n        Sequence whose constituent NDCubes are be converted to new units.\n        NDCubes with sequence must have an 'exposure time' entry in its extra\n        coords attribute.\n\n    correction_function: function\n        Function applying or undoing exposure time correction.\n\n    Returns\n    -------\n    converted_data_list: `list` of `NDCube`s.\n       List of NDCubes with data and uncertainty corrected (or uncorrected)\n       for exposure time.\n\n    \"\"\"\n    converted_data_list = []\n    for i, cube in enumerate(sequence.data):\n        if u.s not in cube.unit.decompose().bases:\n            exposure_time_s = cube._extra_coords[\"exposure time\"][\"value\"].to(u.s).value\n            if len(cube.dimensions.shape) == 1:\n                pass\n            elif len(cube.dimensions.shape) == 2:\n                exposure_time_s = exposure_time_s[:, np.newaxis]\n            elif len(cube.dimensions.shape) == 3:\n                exposure_time_s = exposure_time_s[:, np.newaxis, np.newaxis]\n            else:\n                raise ValueError(\"NDCube dimensions must be 2 or 3. Dimensions={0}\".format(\n                    len(cube.dimensions.shape)))\n            data = correction_function(cube.data, exposure_time_s)\n            uncertainty = correction_function(cube.uncertainty.array, exposure_time_s)\n            converted_data_list.append(NDCube(\n                data, wcs=cube.wcs, meta=cube.meta, mask=cube.mask, unit=cube.unit / u.s,\n                uncertainty=uncertainty,\n                extra_coords=_extra_coords_to_input_format(cube._extra_coords)))\n        else:\n            converted_data_list.append(cube)\n    return converted_data_list\n\ndef calculate_dust_mask(data_array):\n    \"\"\"Calculate a mask with the dust positions in a given arrayself.\n\n    Parameters\n    ----------\n    data_array : `numpy.ndarray`\n        This array contains some dust poisition that will be calculated. The array\n        must have scaled values.\n\n    Returns\n    -------\n    dust : `numpy.ndarray` of `bool`\n        This array has the same shape than data_array and contains the dust positions\n        when the value is True.\n\n    \"\"\"\n    # Creating a mask with the same shape than the inputed data array.\n    mask = np.zeros_like(data_array, dtype=bool)\n    # Set the pixel value to True is the pixel is recognized as a dust pixel.\n    mask[(data_array < 0.5) & (data_array > -200)] = True\n    # Extending the mask to avoid the neighbours pixel influenced by the dust pixels.\n    struct = np.array([np.zeros((3, 3)), np.ones((3, 3)), np.zeros((3, 3))], dtype=bool)\n    mask = ndimage.binary_dilation(mask, structure=struct).astype(mask.dtype)\n    return mask\n", "meta": {"hexsha": "14c181ea4b1d5a7b1f58c2576725bd50d0e8babf", "size": 37900, "ext": "py", "lang": "Python", "max_stars_repo_path": "irispy/iris_tools.py", "max_stars_repo_name": "DanRyanIrish/slitspectrographpy", "max_stars_repo_head_hexsha": "63d0c35c562551079608a5e89b72f9607711f43a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-03T13:29:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-03T13:29:58.000Z", "max_issues_repo_path": "irispy/iris_tools.py", "max_issues_repo_name": "DanRyanIrish/slitspectrographpy", "max_issues_repo_head_hexsha": "63d0c35c562551079608a5e89b72f9607711f43a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-04-04T06:28:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-11T15:34:42.000Z", "max_forks_repo_path": "irispy/iris_tools.py", "max_forks_repo_name": "DanRyanIrish/sunraster", "max_forks_repo_head_hexsha": "63d0c35c562551079608a5e89b72f9607711f43a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-09T18:39:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-09T18:39:57.000Z", "avg_line_length": 45.6077015644, "max_line_length": 113, "alphanum_fraction": 0.6578100264, "include": true, "reason": "import numpy,import scipy,from scipy,import astropy,from astropy", "num_tokens": 8714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.19135791481981002}}
{"text": "\n\nfrom __future__ import division, print_function, absolute_import\n\nfrom tmm.tmm_core import (coh_tmm, unpolarized_RT, ellips,\n                       position_resolved, find_in_structure_with_inf)\n\n\nimport tmm.tmm_core as tmm\n\nimport numpy\nfrom numpy import pi, linspace, inf, array\nimport pandas\nfrom scipy.interpolate import interp1d\nimport matplotlib.pyplot as plt\n\ntry:\n    import colorpy.illuminants\n    import colorpy.colormodels\n    from . import color\n    colors_were_imported = True\nexcept ImportError:\n    # without colorpy, you can't run sample5(), but everything else is fine.\n    colors_were_imported = False\n\n\nfrom matplotlib.pyplot import show\nfrom argparse import ArgumentParser\nimport lowtran\nfrom lowtran.lowtran.plots import plottrans\n\nimport xarray\n\n\n#def main():\np = ArgumentParser(description='Lowtran 7 interface')\np.add_argument('-z', '--obsalt', help='altitude of observer [km]', type=float, default=0.)\np.add_argument('-a', '--zenang', help='observer zenith angle [deg]', type=float, nargs='+', default=[0, 45, 60, 80])\np.add_argument('-s', '--short', help='shortest wavelength nm ', type=float, default=200)\np.add_argument('-l', '--long', help='longest wavelength cm^-1 ', type=float, default=30000)\np.add_argument('-step', help='wavelength step size cm^-1', type=float, default=20)\np.add_argument('--model', help='0-6, see Card1 \"model\" reference. 6 = 1976 US Standard', type=int, default=6)\nP = p.parse_args()\n\nc1 = {'model': P.model,\n      'h1': P.obsalt,\n      'angle': P.zenang,\n      'wlshort': P.short,\n      'wllong': P.long,\n      'wlstep': P.step,\n      }\n\ntr = lowtran.transmittance(c1)\nwl = tr.wavelength_nm.data # This gives the wavelength range\n#a_transmission_data = tr.transmission.data.squeeze() # Transmission data as a funciton of angle. \n\n#a = tr.transmission # make a DataArray from a DataSet from Xarray package\n#a2 = a.values # make \n#a3 = a.to_dataset\n#a4 = a.to_dataframe\n#a5 = a.to_series\n#a6 = a.to_pandas\n# to convert to pandas series to tr.transmission.to_series()\n\n\nplottrans(tr, c1)\n#\nshow()\n\n\n\n\n\"\"\"\nHere's a thin non-absorbing layer, on top of a thick absorbing layer, with\nair on both sides. Plotting reflected intensity versus wavenumber, at two\ndifferent incident angles.\n\"\"\"\ndegree = pi/180\n\n# list of layer thicknesses in nm\nd_list = [inf, 100, 300, inf]\n# list of refractive indices\nn_list = [1, 2.2, 3.3+0.3j, 1]\n# list of wavenumbers to plot in nm^-1\nks = linspace(0.0001, .01, num=400)\n# initialize lists of y-values to plot\nrnorm = []\nr45 = []\nfor k in ks:\n\t\t# For normal incidence, s and p polarizations are identical.\n\t\t# I arbitrarily decided to use 's'.\n    rnorm.append(tmm.coh_tmm('s', n_list, d_list, 0, 1/k)['R'])\n    r45.append(tmm.unpolarized_RT(n_list, d_list, 45*degree, 1/k)['R'])\nkcm = ks * 1e7 #ks in cm^-1 rather than nm^-1\nplt.figure()\nplt.plot(kcm, rnorm, 'blue', kcm, r45, 'purple')\nplt.xlabel('k (cm$^{-1}$)')\nplt.ylabel('Fraction reflected')\nplt.title('Reflection of unpolarized light at 0$^\\circ$ incidence (blue), '\n          '45$^\\circ$ (purple)')\nplt.show() \n\n    \n\n#if __name__ == '__main__':\n#    main()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "d27187a6b4a0bb38428daaf9a52103b6d18b20a6", "size": 3123, "ext": "py", "lang": "Python", "max_stars_repo_path": "test_lowtran_tmm_integration.py", "max_stars_repo_name": "parkerwray/tmm", "max_stars_repo_head_hexsha": "8c27a56163d33de5955611eee35864c4485d1b2b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test_lowtran_tmm_integration.py", "max_issues_repo_name": "parkerwray/tmm", "max_issues_repo_head_hexsha": "8c27a56163d33de5955611eee35864c4485d1b2b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test_lowtran_tmm_integration.py", "max_forks_repo_name": "parkerwray/tmm", "max_forks_repo_head_hexsha": "8c27a56163d33de5955611eee35864c4485d1b2b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0230769231, "max_line_length": 116, "alphanum_fraction": 0.6913224464, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.1913579098698953}}
{"text": "#!/usr/bin/python\n# -*- coding: latin-1 -*-\n\"\"\"\nMaterials define the surface properties and specify how light rays get coloured and reflected. All materials are callables - they implement the __call__ method\nand can be used like functions.\n\n.. moduleauthor:: Adrian Köring\n\"\"\"\n\nimport numpy as np\n\nfrom padvinder.util import normalize\nfrom padvinder.util import check_finite\n\nclass Material(object):\n    \"\"\"\n    An emission material consists of an emitted colour only.\n    Without gradients, lighting or anything.\n\n    Parameters\n    ----------\n    color : numpy.ndarray_like\n        of three dimensions and contains colors as (Red, Green, Blue) where\n        (0,0,0) is black and (1,1,1) is white\n\n    Raises\n    ------\n    ValueError\n        if the color contains any non-finite (inf, nan) values\n\n    Examples\n    --------\n    >>> Material((0.8, 0.8, 0.8))\n    Material(color=[.8 .8 .8])\n    \"\"\"\n    def __init__(self, color = (.5, .5, .5)):\n        check_finite(color)\n        self._color = np.array(color).astype(np.float64)\n\n    @property\n    def color(self):\n        \"\"\"\n        Returns the color of the material.\n        \"\"\"\n        return self._color\n\n    def __call__(self, surface_normal,\n                       incoming_color,\n                       incoming_direction,\n                       outgoing_direction):\n        \"\"\"\n        Calculate light reflected from the material toward the outgoing\n        direction. Keep in mind, while pathtracing starts at the camera and\n        heads into the scene, the rays contribution is accumulated 'backwards'.\n        Therefore the incoming direction is further down the path and\n        outgoing_direction is closer towards the camera.\n\n        Parameters\n        ----------\n        surface_normal : numpy.ndarray_like\n            normal vector at the geometries surface\n        incoming_color : numpy.ndarray_like\n            the color the ray has accumulated up to this point\n        incoming_direction : numpy.ndarray_like\n            the direction from where the 'light shines' onto the surface\n        outgoing_direction : numpy.ndarray_like\n            the direction into which the 'light gets reflected' from the surface\n\n        Returns\n        -------\n        color : numpy.ndarray_like\n            the light color 'getting reflected' from the surface\n        \"\"\"\n        return self._color\n\n    def outgoing_direction(self, normal, incoming_direction):\n        \"\"\"\n        Given a surface normal and an incoming direction, determine the\n        direction in which the path continues.\n\n        normal : numpy.ndarray_like of shape (3, )\n            the surface normal at the intersection point\n\n        incoming_direction : numpy.ndarray_like of shape (3, )\n            the direction from which light hits the surface\n\n        Returns\n        -------\n        outgoing direction : numpy.ndarray_like of shape (3, 0)\n            the direction in which light is reflected from the surface\n        \"\"\"\n        # BaseClass randomly (not uniformly) samples the hemisphere\n        point_on_sphere = normalize(np.random.uniform(0, 1, size=(3, )))\n        # ensure it is in the same hemisphere as the normal\n        if np.dot(normal, point_on_sphere) < 0:\n            point_on_sphere = -point_on_sphere\n        return normalize(normal + point_on_sphere)\n\n\n    def __repr__(self):\n        return \"Material(color={})\".format(self._color)\n\n\nclass Emission(Material):\n    \"\"\"\n    Emission is equivalent to the abstract base class Material. Due to semantics\n    this class exists and merely inherits without modifications.\n\n    Parameters\n    ----------\n    color : numpy.ndarray_like\n        of three dimensions and contains colors as (Red, Green, Blue) where\n        (0,0,0) is black and (1,1,1) is white\n\n    Raises\n    ------\n    ValueError\n        if the color contains any non-finite (inf, nan) values\n\n    Examples\n    --------\n    >>> Emission()\n    Emission(color=[10.0, 10.0, 10.0])\n    \"\"\"\n    def __init__(self, color = (10, 10, 10)):\n        super().__init__(color)\n\n    def __repr__(self):\n        return \"Emission(color={})\".format(self._color)\n\n\nclass Lambert(Material):\n    def __init__(self, color = (0.5, 0.5, 0.5), diffuse = 1):\n        \"\"\"\n        A lambert material consists of a colour value and a diffuse coefficient.\n\n        Parameters\n        ----------\n        color : numpy.ndarray_like\n            of three dimensions and contains colors as (Red, Green, Blue) where\n            (0,0,0) is black and (1,1,1) is white\n        diffuse : number in [0, 1]\n            percentage of incoming light that is reflected again\n\n        Raises\n        ------\n        ValueError\n            if the color contains any non-finite (inf, nan) values\n\n        Examples\n        --------\n        >>> Lambert((0.8, 0.8, 0.8), 1)\n        Lambert(color=[0.8, 0.8, 0.8], diffuse=1)\n        \"\"\"\n        super().__init__(color)\n        self._diffuse = diffuse\n\n    @property\n    def diffuse(self):\n        \"\"\"\n        Returns the diffuse value of the material.\n        \"\"\"\n        return self._diffuse\n\n    # def __call__(self, surface_normal,\n    #                    incoming_light,\n    #                    incoming_direction,\n    #                    outgoing_direction):\n    #     \"\"\"\n    #     Calculate light reflected from the material toward the outgoing\n    #     direction. Keep in mind, while pathtracing starts at the camera and\n    #     heads into the scene, the rays contribution is accumulated 'backwards'.\n    #     Therefore the incoming direction is further down the path and\n    #     outgoing_direction is closer towards the camera.\n    #\n    #     Parameters\n    #     ----------\n    #     surface_normal : numpy.ndarray_like\n    #         normal vector at the geometries surface\n    #     incoming_color : numpy.ndarray_like\n    #         the color the ray has accumulated up to this point\n    #     incoming_direction : numpy.ndarray_like\n    #         the direction from where the 'light shines' onto the surface\n    #     outgoing_direction : numpy.ndarray_like\n    #         the direction into which the 'light gets reflected' from the surface\n    #\n    #     Returns\n    #     -------\n    #     color : numpy.ndarray_like\n    #         the light color 'getting reflected' from the surface\n    #     \"\"\"\n    #     raise NotImplemented()\n\n    def __repr__(self):\n        c, d = self._color, self._diffuse\n        return \"Lambert(color={0}, diffuse={1})\".format(c, d)\n", "meta": {"hexsha": "a460999e30fb82bd5259d9bf97915e5ded54b443", "size": 6450, "ext": "py", "lang": "Python", "max_stars_repo_path": "padvinder/material.py", "max_stars_repo_name": "adriankoering/padvinder", "max_stars_repo_head_hexsha": "eaebd80867f22c8ca8cc3b97bf0b726f408d928a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "padvinder/material.py", "max_issues_repo_name": "adriankoering/padvinder", "max_issues_repo_head_hexsha": "eaebd80867f22c8ca8cc3b97bf0b726f408d928a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "padvinder/material.py", "max_forks_repo_name": "adriankoering/padvinder", "max_forks_repo_head_hexsha": "eaebd80867f22c8ca8cc3b97bf0b726f408d928a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7411167513, "max_line_length": 159, "alphanum_fraction": 0.6069767442, "include": true, "reason": "import numpy", "num_tokens": 1429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.1913506837829705}}
{"text": "#!/bin/python\n#\n# Create a plot of free energy vs temperature for a polymorph\n# \n# Copyright Michael R. Shirts, University of Virginia, 2014\n#\nfrom __future__ import print_function\nimport numpy as np\nimport pymbar # multistate Bennett acceptance ratio\nfrom pymbar import timeseries # timeseries analysis\nfrom optparse import OptionParser # for parsing command-line options\nimport mdtraj as md\nimport MBARBootstrap # Bootstrapping algorithm\nimport random\nimport os\nimport usefulFuncs #Useful math functions\nimport Harvist #Hamiltonian Reweighting Visualization Toolkik\nimport pdb\nimport sys\nimport panedr\nimport matplotlib\nimport subprocess \nimport matplotlib.pyplot as plt\n\nfont = {'family': 'normal',\n        'weight': 'normal',\n        'size': 16}\n\n\n\ndef old_systems_dictionary(potential, molecule):\n    Polys = dict()  # Name of the polymorphs\n    refTs = dict()  # Reference temperatures for the PSCP for each system\n    refdGs = dict()  # Reference free energies for the PSCP for each system\n    refddGs = dict()  # Reference uncertainties for the PSCP for each system\n    refdUs = dict()  # Reference lattice minima for each system\n    absolutedUs = dict()  # Absolute lattice energy for each system\n    \n    \n    # Oplsaa\n    if potential == \"oplsaa\":\n        Potentials = ['oplsaa']\n        PotNAME = 'OPLS'\n        Charges = ['0.1150', '0.1150', '0.0700', '0.0850', '0.1000', '0.1150', '0.1300', '0.1450', '0.1600', '0.1750',\n                   '0.1900', '0.1000', '0.0900', '0.0800', '0.0700', '0.0600', '0.0500', '0.0400', '0.0300', '0.0200',\n                   '0.0100']\n        Chargenames = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',\n                       '', '', '', '', '', '', '', '']\n        #Chargenames=['C01150', 'C01150', 'C00700', 'C00850', 'C01000', 'C01150', 'C01300', 'C01450', 'C01600', 'C01750', 'C01900', 'C00900', 'C00800', 'C00700', 'C00600', 'C00500', 'C00400', 'C00300', 'C00200', 'C00100']\n        PotNAMES=['OPLS']\n        SimNAMES=['GRO']\n        Temperatures = np.array([50, 100, 200, 300])\n    \n        #Temperatures=np.array([45,50]) #Overlap Check\n        #Temperatures=np.array([10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,70,80,90,100,110,120,130,140])#,80,90,100,110])#Zzzvye\n        #Temperatures=np.array([10,15,20,25,30,35,40,45,50,60,70,80,90,100,110])#Zzzvye\n        #Temperatures = np.array([10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250,260,270,280,290,300])#,320,340])#,360,380,400,420,440,460,480,500])#,320,340,360,380,400]) #benzene\n        #Temperatures=np.array([10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250,260,270,280,290,300])#,320,340])#,360,380,400,420,440,460,480,500])#,320,340,360,380,400]) #kobfud\n        #Temperatures=np.array([10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250,260,270,280,290,300])#,320,340,360,380,400,420,440,460,480,500])#,320,340,360,380,400]) #cbmzpn\n        #Temperatures=np.array([10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250,260,270,280,290,300])#,320,340])#,360,380,400,420,440,460,480,500])#,320,340,360,380,400]) #melfit\n        #Temperatures=np.array([10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250,260,270,280,290,300])#,320,340,360,380,400,420,440,460,480,500])\n        #Temperatures=np.array([100,130,140,160,180,200,220,240,260,280,300,340,360,380,400])\n        #Temperatures=np.array([100,120,140,160,180,200]) #MelfitTest\n        #ExtraPressures=np.array([5000,15000,35000]) #benzene\n        #Temperatures=np.array([40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250,260,270,280,290,300]) #imazol\n        #ExtraPressures=np.array([5000,10000,16000,20000,26000,31000,36000,40000]) #imazol\n        #Temperatures=np.array([20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250,220,240,260,280,300,300,300,300,300,300,300,300]) #acetac\n        #ExtraPressures=np.array([5000,5000,5000,5000,5000,10000,16000,20000,26000,31000,36000,40000]) #acetac\n        #Temperatures=np.array([20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250,200,200,200,200,220,240,260,280,300,300,300,300,300,300,300,300]) #formam\n        #ExtraPressures=np.array([1500,2000,5000,10000,10000,10000,10000,10000,5000,10000,15000,20000,26000,31000,36000,40000]) #formam\n        #Temperatures=np.array([20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,220,240,250,270,290,300,320,340,360,380,400,420,440,460,480,500]) #glycin\n        ExtraPressures = []\n        Pressures = np.ones(len(Temperatures), int)\n        Pressures[len(Pressures) - len(ExtraPressures): len(Pressures)] = ExtraPressures\n        #Temperatures=np.array([200,200,200,200,200])\n        #Pressures=np.array([1,500,1000,1500,2000,2500,3000,3500,4000,4500,5000])\n        refPot = 0\n        \n        #Benzene\n        Polys['benzene']=['p1', 'p2', 'p3']\n        refTs['benzene']=200\n        refdGs['benzene']=[0.000, 0.185, 0.306]\n        refddGs['benzene']=[0.000, 0.019, 0.019]\n        refdUs['benzene'] = [0.000, 0.267, 0.240]\n        absolutedUs['benzene'] = [-5.624, -5.362, -5.380]\n        \n        #Formam\n        Polys['formam']=['p1', 'p2']\n        refTs['formam']=200\n        refdGs['formam']=[0.000, 0.118]\n        refddGs['formam']=[0.005, 0.005]\n        refdUs['formam'] = [0.000, 0.343]\n        absolutedUs['formam'] = [-41.04733, -40.7076]   \n     \n        #Acetac\n        Polys['acetac']=['p1', 'p2']\n        refTs['acetac']=200\n        refdGs['acetac']=[0.000, 0.001]\n        refddGs['acetac']=[0.005, 0.005]\n        refdUs['acetac'] = [0.000, 0.020]\n        absolutedUs['acetac'] = [-36.4858, -36.466]\n    \n        \n        #Imazol\n        Polys['imazol']=['p1', 'p2']\n        refTs['imazol']=100\n        refdGs['imazol']=[0.000, -0.436]\n        refddGs['imazol']=[0.005, 0.005]\n        refdUs['imazol'] = [0.000, -0.464]\n        absolutedUs['imazol'] = [-15.399, -15.863]\n    \n        #Glycin\n        Polys['glycin']=['p1', 'p2', 'p4']#, 'p3']\n        refTs['glycin']=200\n        refdGs['glycin']=[0.000, -0.034, -0.067]#, 1.087]\n        refddGs['glycin']=[0.005, 0.005, 0.005]#, 0.005]\n        refdUs['glycin'] = [0.000, 0.117, 0.288]#, 1.235]\n        absolutedUs['glycin'] = [-131.950, -131.778, -131.609]#, -130.715]\n    \n        #Bismev\n        Polys['bismev']=['p3', 'p1', 'p2']\n        refTs['bismev']=200\n        refdGs['bismev']=[0.000, -1.474, -0.186]\n        refddGs['bismev']=[0.005, 0.005, 0.005]#, 0.005]\n        refdUs['bismev'] = [0.000, -1.459, -0.245]#, 1.235]\n        absolutedUs['bismev'] = [-64.3467, -65.8055, -64.5916]#, -130.715]\n    \n        #Cbmzpn\n        Polys['cbmzpn']=['p3', 'p1']\n        refTs['cbmzpn']=200\n        refdGs['cbmzpn']=[0.000, 0.195]\n        refddGs['cbmzpn']=[0.0, 0.005]\n        refdUs['cbmzpn'] = [0.000, 0.565]\n        absolutedUs['cbmzpn'] = [-34.3933, -33.8283]\n    \n        #Hxacan\n        Polys['hxacan']=['p2', 'p1']\n        refTs['hxacan']=200\n        refdGs['hxacan']=[0.000, -0.619]\n        refddGs['hxacan']=[0.005, 0.005]\n        refdUs['hxacan'] = [0.000, -0.446]\n        absolutedUs['hxacan'] = [-46.965, -47.411]\n    \n        #Kobfud\n        Polys['kobfud']=['p1', 'p2']\n        refTs['kobfud']=200\n        refdGs['kobfud']=[0.000, 1.832]\n        refddGs['kobfud']=[0.005, 0.005]\n        refdUs['kobfud'] = [0.000, 2.255]\n        absolutedUs['kobfud'] = [-49.974, -47.719]\n    \n        ##Pyrzin\n        #Polys['pyrzin']=['p2']#, 'p3', 'p1', 'p5', 'p2']\n        #refTs['pyrzin']=200\n        #refdGs['pyrzin']=[0.000] #, -0.483, -0.689, -1.055, -1.056]\n        #refddGs['pyrzin']=[0.005] #, 0.005, 0.005, 0.005, 0.005]\n        #refdUs['pyrzin'] = [0.000] #, -0.176, -0.695, -1.246, 0.951]\n        #absolutedUs['pyrzin'] = [-13.348] #, -14.475, -14.993, -15.545, -13.348]\n    \n    \n        #Pyrzin\n        Polys['pyrzin']=['p4', 'p3', 'p1', 'p5', 'p2']\n        refTs['pyrzin']=200\n        refdGs['pyrzin']=[0.000, -0.483, -0.689, -1.055, -1.056]\n        refddGs['pyrzin']=[0.005, 0.005, 0.005, 0.005, 0.005]\n        refdUs['pyrzin'] = [0.000, -0.176, -0.695, -1.246, 0.951]\n        absolutedUs['pyrzin'] = [-14.299, -14.475, -14.993, -15.545, -13.348]\n    \n        #Qopbed\n        Polys['qopbed']=['p1', 'p3']#, 'p2']\n        refTs['qopbed']=200\n        refdGs['qopbed']=[0.000, 0.878] #1.699]\n        refddGs['qopbed']=[0.005, 0.005]\n        refdUs['qopbed'] = [0.000, 1.235]# 2.778]\n        absolutedUs['qopbed'] = [-41.135, -39.900] # -38.357]\n    \n        #Zzzvye\n        Polys['zzzvye']=['p3', 'p1']\n        refTs['zzzvye']=50\n        refdGs['zzzvye']=[0.000, 0.190]\n        refddGs['zzzvye']=[0.005, 0.005]\n        refdUs['zzzvye'] = [0.000, 0.351]\n        absolutedUs['zzzvye'] = [11.103, 11.454]\n    \n        #Resora\n        Polys['resora']=['p1', 'p2']\n        refTs['resora']=200\n        refdGs['resora']=[0.000, -0.337]\n        refddGs['resora']=[0.005, 0.005]\n        refdUs['resora'] = [0.000, -0.278]\n        absolutedUs['resora'] = [-22.506, -22.784]\n    \n        #Zzzpro\n        Polys['zzzpro']=['p1', 'p3']#, 'p2']\n        refTs['zzzpro']=200\n        refdGs['zzzpro']=[0.000, 0.223]#, 0.409]\n        refddGs['zzzpro']=[0.01, 0.01]#, 0.01]\n        refdUs['zzzpro'] = [0.000, 0.258]#, 0.480]\n        absolutedUs['zzzpro'] = [-19.393, -19.135]#, -18.913]\n    \n        #Zzzpus\n        Polys['zzzpus']=['p6', 'p2'] #, 'p1']#, 'p3', 'p7']\n        refTs['zzzpus']=200\n        refdGs['zzzpus']=[0.000, -1.713] #, -1.713]#, -1.713, -1.713]\n        refddGs['zzzpus']=[0.00, 0.028] #, 0.02]#, 0.02, 0.02]\n        refdUs['zzzpus'] = [0.000, -2.226] #, 1.4102]#, -2.249, -3.067]\n        absolutedUs['zzzpus'] = [-84.917, -87.143] #, -83.507]#, -87.166, -87.985]\n    \n        ##Melfit\n        #Polys['melfit']=['p7', 'p6']#, 'p8']\n        #refTs['melfit']=200\n        #refdGs['melfit']=[0.000, 0.52]#, 0.52]\n        #refddGs['melfit']=[0.00, 0.015]#, 0.02]\n        #refdUs['melfit'] = [0.000, 0.596]#, 1.187]\n        #absolutedUs['melfit'] = [-12.456, -11.818]#, -11.268]\n    \n        #Melfit\n        Polys['melfit']=['p7', 'p6', 'p8', 'p1', 'p5']\n        refTs['melfit']=200\n        refdGs['melfit']=[0.000, 0.52, 0.52, 0.52, 0.52]\n        refddGs['melfit']=[0.02, 0.02, 0.02, 0.02, 0.02]\n        refdUs['melfit'] = [0.000, 0.637, 1.187, 1.966, 0.927]\n        absolutedUs['melfit'] = [-12.456, -11.818, -11.268, -10.489, -11.529]\n    \n    \n    \n        ##Melfit\n        #Polys['melfit']=['p7', 'p6', 'p1', 'p5']#, 'p2', 'p3']#, 'p4']\n        #refTs['melfit']=200\n        #refdGs['melfit']=[0.000, 0.279, 1.581, 0.542]#, -0.962, 1.361]#, -0.679]\n        #refddGs['melfit']=[0.02, 0.02, 0.02, 0.02]#, 0.02, 0.02]#, 0.02]\n        #refdUs['melfit'] = [0.000, 0.279, 1.581, 0.542]#, -0.962, 1.361]#, -0.679]\n        #absolutedUs['melfit'] = [-12.070, -11.792, -10.489, -11.529]#, -13.032, -10.709]#, -12.749]\n    \n        ##Bedmig\n        #Polys['bedmig']=['p1', 'p2', 'p6', 'p4', 'p7', 'p3', 'p5']\n        #refTs['bedmig']=200\n        #refdGs['bedmig']=[0.000, 1.678, -0.372, -2.878, 1.955, -0.322, -1.146]\n        #refddGs['bedmig']=[0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02]\n        #refdUs['bedmig'] = [0.000, 3.803, -0.649, -1.217, 2.772, 2.777, 5.638]\n        #absolutedUs['bedmig'] = [-92.82, -89.01, -93.46, -94.03, -90.03, -90.0378, -87.1763]\n    \n        #Bedmig\n        Polys['bedmig']=['p1', 'p7']\n        refTs['bedmig']=200\n        refdGs['bedmig']=[0.000, 1.955]\n        refddGs['bedmig']=[0.00, 0.016]\n        refdUs['bedmig'] = [0.000, 2.789]\n        absolutedUs['bedmig'] = [-92.814, -90.025]\n    \n        ##Bedmig\n        #Polys['bedmig']=['p5']\n        #refTs['bedmig']=200\n        #refdGs['bedmig']=[0.000]\n        #refddGs['bedmig']=[0.00]\n        #refdUs['bedmig'] = [0.000]\n        #absolutedUs['bedmig'] = [-87.1763]\n    \n    \n        ##Bedmig\n        #Polys['bedmig']=['p1', 'p7', 'p3', 'p5', 'p6']\n        #refTs['bedmig']=200\n        #refdGs['bedmig']=[0.000, 1.955, -0.322, -1.146, -0.372]\n        #refddGs['bedmig']=[0.02, 0.02, 0.02, 0.02, 0.02]\n        #refdUs['bedmig'] = [0.000, 2.772, 2.777, 5.638, -0.649]\n        #absolutedUs['bedmig'] = [-92.82, -90.03, -90.0378, -87.1763, -93.46]\n    \n        #Cafine\n        Polys['cafine']=['p1', 'p2']\n        refTs['cafine']=200\n        refdGs['cafine']=[0.000, 1.846]\n        refddGs['cafine']=[0.005, 0.005]\n        refdUs['cafine'] = [0.000, 2.375]\n        absolutedUs['cafine'] = [-28.737, -26.362]\n    \n        SystemNAME = \"OPLSAA\"\n    \n    # Amoeba Reweighting\n    if potential == \"amoeba09\":\n        #Potentials=['amoeba09','designeda']#, 'designeda', 'designeda', 'designeda', 'designeda', 'designeda']\n        Potentials=['amoeba09']\n        PotNAME='AMO'\n        Charges=['0.1150', '0.1150', '0.0700', '0.0850', '0.1000', '0.1150', '0.1300', '0.1450', '0.1600', '0.1750', '0.1900', '0.1000', '0.0900', '0.0800', '0.0700','0.0600','0.0500','0.0400','0.0300','0.0200','0.0100']\n        Chargenames=['', '', 'C00700', 'C00850', 'C01000', 'C01150', 'C01300', 'C01450', 'C01600', 'C01750', 'C01900', 'C00900', 'C00800', 'C00700', 'C00600', 'C00500', 'C00400', 'C00300', 'C00200', 'C00100']\n        PotNAMES=['AMO', 'DESA']\n        SimNAMES=['TIN', 'GRO']\n        #PotNAMES=['AMO']\n        #SimNAMES=['TIN']\n        refPot=0\n        Temperatures=np.array([30,40,50,60,70,80,90,100,110,130,140,150,160,170,180,190,200,210,220,230,240,250])\n        Pressures=np.ones(len(Temperatures),int);\n        #Temperatures=np.array([60,100,140,200])\n        \n        #Benzene\n        Polys['benzene']=['p1', 'p2', 'p3']\n        refTs['benzene']=200\n        refdGs['benzene']=[0.000, -0.362, -0.291]\n        #refdGs['benzene']=[0.000, 0.390, 0.330]\n        refddGs['benzene']=[0.000, 0.031, 0.032]\n        refdUs['benzene'] = [0.000, 0.781, 0.643]\n        absolutedUs['benzene'] = [-3.587, -2.807, -2.944]\n        \n        #Formam\n        Polys['formam']=['p1', 'p2']\n        refTs['formam']=100\n        refdGs['formam']=[0.000, 0.293]\n        refddGs['formam']=[0.000, 0.020]\n        refdUs['formam'] = [0.000, 0.487]\n        absolutedUs['formam'] = [-26.237, -25.750]\n        \n        #Acetac\n        Polys['acetac']=['p1', 'p2']\n        refTs['acetac']=50\n        refdGs['acetac']=[0.000, -0.106]\n        refddGs['acetac']=[0.02, 0.02]\n        refdUs['acetac'] = [0.000, -0.136]\n        absolutedUs['acetac'] = [-34.028, -34.163]\n        \n        #Imazol\n        Polys['imazol']=['p1', 'p2']\n        refTs['imazol']=200\n        refdGs['imazol']=[0.000, 0.125]\n        refddGs['imazol']=[0.020, 0.020]\n        refdUs['imazol'] = [0.000, 0.201]\n        absolutedUs['imazol'] = [-23.186, -22.985]\n    \n        #Glycin\n        Polys['glycin']=['p1', 'p2', 'p3']\n        refTs['glycin']=10\n        refdGs['glycin']=[0.000, 0.163, 1.222]\n        refddGs['glycin']=[0.000, 0.000, 0.000]\n        refdUs['glycin'] = [0.000, 0.163, 1.222]\n        absolutedUs['glycin'] = [0.000, 0.000, 0.000]\n    \n        SystemName = \"AMOEBA\"\n    \n    #Gromos\n    if potential == \"gromos\":\n        Potentials=['gromos54a7']\n        PotNAME='GROM'\n        Charges=['0.1150', '0.1150', '0.0700', '0.0850', '0.1000', '0.1150', '0.1300', '0.1450', '0.1600', '0.1750', '0.1900', '0.1000', '0.0900', '0.0800', '0.0700','0.0600','0.0500','0.0400','0.0300','0.0200','0.0100']\n        Chargenames=['C01150', 'C01150', 'C00700', 'C00850', 'C01000', 'C01150', 'C01300', 'C01450', 'C01600', 'C01750', 'C01900', 'C00900', 'C00800', 'C00700', 'C00600', 'C00500', 'C00400', 'C00300', 'C00200', 'C00100']\n        PotNAMES=['GROM']\n        SimNAMES=['GRO']\n        Temperatures=np.array([10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250])\n        refPot=0\n    \n        #Benzene\n        Polys['benzene']=['p1', 'p2', 'p3']\n        refTs['benzene']=200\n        refdGs['benzene']=[0.000, 0.251, 0.345]\n        refddGs['benzene']=[0.000, 0.019, 0.018]\n        refdUs['benzene'] = [0.000, 0.314, 0.328]\n        absolutedUs['benzene'] = [-10.184, -9.869, -9.853]\n    \n        SystemName = \"GROMOS\"\n    \n    Polymorphs = Polys[molecule]\n    refT = refTs[molecule]\n    refdG = refdGs[molecule]\n    refddG = refddGs[molecule]\n    refdU = refdUs[molecule]\n    absolutedU = absolutedUs[molecule]\n    return Polymorphs, refT, refdG, refddG, refdU, absolutedU\n\ndef get_potential_info(potential):\n    if potential == 'oplsaa':\n        SimNAMES=['GRO']\n        Chargenames = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',\n                       '', '', '', '', '', '', '', '', '']\n        PotNAMES = ['OPLS']\n    elif potential == 'amoeba09':\n        SimNAMES=['TIN', 'GRO']\n        Chargenames = ['', '', 'C00700', 'C00850', 'C01000', 'C01150', 'C01300', 'C01450', 'C01600', 'C01750', 'C01900',\n                       'C00900', 'C00800', 'C00700', 'C00600', 'C00500', 'C00400', 'C00300', 'C00200', 'C00100']\n        PotNAMES = ['AMO', 'DESA']\n    elif potential == \"gromos\":\n        SimNAMES = ['GRO']\n        Chargenames = ['C01150', 'C01150', 'C00700', 'C00850', 'C01000', 'C01150', 'C01300', 'C01450', 'C01600',\n                       'C01750', 'C01900', 'C00900', 'C00800', 'C00700', 'C00600', 'C00500', 'C00400', 'C00300',\n                       'C00200', 'C00100']\n        PotNAMES = ['GROM']\n    return SimNAMES, Chargenames, PotNAMES\n\n\ndef crystal_matrix_to_lattice_parameters(crystal_matrix):\n    \"\"\"\n    This function takes any strained crystal lattice matrix and return the lattice parameters\n\n    **Required Inputs\n    crystal_matrix = crystal lattice matrix ([[Vxx,Vxy,Vxz],\n                                              [Vyx,Vyy,Vyz],\n                                              [Vzx,Vzy,Vzz]])\n    \"\"\"\n    # Computing lattice parameters\n    a = np.linalg.norm(crystal_matrix[:, 0])\n    b = np.linalg.norm(crystal_matrix[:, 1])\n    c = np.linalg.norm(crystal_matrix[:, 2])\n\n    gamma = np.arccos(np.dot(np.squeeze(np.asarray(crystal_matrix[:, 0])), np.squeeze(np.asarray(crystal_matrix[:, 1])))\n                      / (a * b)) * 180. / np.pi\n    alpha = np.arccos(np.dot(np.squeeze(np.asarray(crystal_matrix[:, 1])), np.squeeze(np.asarray(crystal_matrix[:, 2])))\n                      / (b * c)) * 180. / np.pi\n    beta = np.arccos(np.dot(np.squeeze(np.asarray(crystal_matrix[:, 2])), np.squeeze(np.asarray(crystal_matrix[:, 0])))\n                     / (c * a)) * 180. / np.pi\n\n    # Creating an array of lattice parameters\n    lattice_parameters = np.array([a, b, c, alpha, beta, gamma])\n    return lattice_parameters\n\n\ndef dGvsT(plot_out=False, Temperatures=np.array([100,200,300]), Temperatures_unsampled=[], Pressure=1, Molecules=72, molecule='benzene', \n          Independent=0, potential='oplsaa', ignoreframes=200, includeframes=100000,\n          simulation='gromacs', directory='', ensemble='NVT', spacing=1, hinge='DefaultHinge', phase='solid',\n          Polymorphs=['p1', 'p2', 'p3'], refT=200, refdG=[0.000, 0.185, 0.306], refddG=[0.000, 0.019, 0.019],\n          refdU=[0.000, 0.267, 0.240], absolutedU=[-5.624, -5.362, -5.380], output_directory='output'):\n#NSA: Is this needed?\n    Colors = ['b', 'g', 'r', 'm', 'c', 'y', 'k', 'g', 'g', 'g', 'g', 'g', 'g', 'g', 'g', 'g', 'g', 'g', 'g']\n\n    if Independent == 0:\n        Independent = Molecules\n\n    # Hard set from old dictionary funciton\n    refPot = 0\n    ExtraPressures = []\n\n    if np.all(Temperatures_unsampled == None):\n        Temperatures_unsampled = np.array([])\n\n    if (not np.any(Temperatures == refT)) and (not np.any(Temperatures_unsampled == refT)):\n        Temperatures_unsampled = np.append(Temperatures_unsampled, refT)\n\n    Temperatures = np.sort(np.append(Temperatures, Temperatures_unsampled))\n    Pressures = np.ones(len(Temperatures), int)\n    Pressures[len(Pressures) - len(ExtraPressures): len(Pressures)] = ExtraPressures\n    Potentials = [potential]\n\n    if (plot_out):\n#        import matplotlib.cm as cm\n#        from matplotlib.font_manager import FontProperties as FP\n        font = {'family': 'normal',\n                'weight': 'normal',\n                'size': 14}\n        matplotlib.rc('font', **font)\n    \n    # =============================================================================================\n    # ENSURE THAT USER INPUTS ARE SENSIBLE\n    # =============================================================================================\n    # Pressure\n    if Pressure < 0:\n        print(\"Invalid Pressure: \" + str(Pressure))\n        sys.exit()\n    \n    # ENSEMBLE\n    if ensemble != \"NVE\" and ensemble != \"NVT\" and ensemble != \"NPT\":\n        print(\"Invalid Ensemble\")\n        print(\"Supported Ensembles: NVE NVT NPT\")\n        sys.exit()\n    \n    # =============================================================================================\n    # FORMAT INPUTS\n    # =============================================================================================\n    # TEMPERATURE\n    refk = -1\n    for k, temp in enumerate(Temperatures):\n        if temp == refT and refk == -1:\n            refk = k + refPot * len(Temperatures)\n\n    # =============================================================================================\n    # READ IN RAW DATA\n    # =============================================================================================\n    # Constants.\n    kB = 1.3806488e-23 * 6.0221413e23 / (1000.0 * 4.184)  # Boltzmann constant in kcal/mol/K\n    \n    # Parameters\n    # How many states?\n    K = len(Potentials) * len(Temperatures)\n    \n    #  maximum number of snapshots/simulation (could make this automated) - doesn't matter, as long as it's long enough.\n    N_max = 5000\n    \n    # beta factor for the different temperatures\n    beta_k = 1.0 / (kB * Temperatures)\n    beta_k = np.tile(beta_k, (1, len(Potentials)))[0]\n    \n    # Conversion from kJ to kcal\n    kJ_to_kcal = 0.2390057\n\n    # This is the sampling efficiency for each potential in each combination of potentials\n    Efficiency = np.zeros(K, float)\n    \n    # Allocate storage for simulation data\n    # u_pklnT is the complete matrix of all energy data. 'p' is the polymorph, 'k' is the sampled state, 'l' is the\n    #    evaluated state, 'n' is the sample number,  and T is the energy term\n    #u_pklnT = np.zeros([len(Polymorphs), K, K, N_max, 20])\n    \n    # N_k[k] is the total number of snapshots from alchemical state k\n    N_k = np.zeros(K, np.int32)\n    \n    # Terms_l is the list of all energy terms for the 'l' state\n    Terms_l = []\n    \n    # dA[p,i,k] is the free energy between potential 0 and state k for spacing i in polymorph p\n    dA = np.zeros([len(Polymorphs), spacing + 1, K], float)\n    \n    # ddA[p,i,k] is the uncertainty in the free energy between potential 0 and state k for spacing i in polymorph p\n    ddA = np.zeros([len(Polymorphs), spacing + 1, K], float)\n    \n    # dG[p,i,t] is the free energy between polymorph 1 and polymorph p for spacing i and temperature t\n    dG = np.zeros([len(Polymorphs), spacing + 1, len(Temperatures)])\n    \n    # ddG[p,i,t] is the uncertanity in the free energy between polymorph 1 and polymorph p for spacing i and temperature t\n    ddG = np.zeros([len(Polymorphs), spacing + 1, len(Temperatures)])\n    \n    # dS[p,i,t] is the relative entropy between polymorph 1 and polymorph p for spacing i and temperature t\n    dS = np.zeros([len(Polymorphs), spacing + 1, len(Temperatures)])\n    \n    # ddS[p,i,t] is the uncertanity in the relative entropy between polymorph 1 and polymorph p for spacing i and temperature t\n    ddS = np.zeros([len(Polymorphs), spacing + 1, len(Temperatures)])\n    \n    dS_mbar = np.zeros([len(Polymorphs), spacing + 1, len(Temperatures)])\n    ddS_mbar = np.zeros([len(Polymorphs), spacing + 1, len(Temperatures)])\n    dH_mbar = np.zeros([len(Polymorphs), spacing + 1, len(Temperatures)])\n    \n    # O_pij[p,i,j] is the overlap within polymorph p between temperature state i and temperature state j\n    O_pij = np.zeros([len(Polymorphs), len(Temperatures), len(Temperatures)])\n    dU = np.zeros([len(Polymorphs), len(Temperatures)])\n    ddU = np.zeros([len(Polymorphs), len(Temperatures)])\n    \n    # u_kln[k,l,n] is the reduced potential energy of configuration n from potential k in potential l\n    u_kln = np.zeros([K, K, N_max], np.float64)\n    \n    # V_pkn is the volume of configuration n of polymorph p at temperature k\n    V_pkn = np.zeros([len(Polymorphs), len(Temperatures), N_max], float)\n\n    # V_avg is the average volume of polymorph p at temperature k\n    V_avg = np.zeros([len(Polymorphs), len(Temperatures)], float)\n    \n    # ddV_avg is the standard deviation of the volume of polymorph p at temperature k\n    ddV_avg = np.zeros([len(Polymorphs), len(Temperatures)], float)\n\n    # C_pkn is the lattice tensor of the polymorph p at temperature k\n    box_place = np.matrix([[0, 0], [1, 1], [2, 2], [0, 1], [0, 2], [1, 2]])\n    C_pkn = np.zeros([len(Polymorphs), len(Temperatures), N_max, 3, 3], float)\n\n    # h_avg is the average lattice parameters of polymorph p at temperature k\n    h_avg = np.zeros([len(Polymorphs), len(Temperatures), 6], float)\n    \n    # dh is the standard deviation of the lattice parameters of polymorph p at temperature k\n    dh = np.zeros([len(Polymorphs), len(Temperatures), 6], float)\n\n    # Cycle through all polymorphs\n    for p, polymorph in enumerate(Polymorphs):\n        # Cycle through all sampled potentials\n        for i, potential_k in enumerate(Potentials):\n            count = 0\n            for t in range(len(Temperatures)):\n                k = len(Temperatures) * i + t\n                # Cycle through all evaluated potentials\n                for j, potential_l in enumerate(Potentials):\n                    l = len(Temperatures) * j\n    \n                    dirpath = polymorph + '/temperature/' + str(count) + '/'\n                    if os.path.isfile(dirpath + 'PROD.edr') and (Temperatures[t] not in Temperatures_unsampled):\n                        count += 1\n                        print(\"loading \" + dirpath + 'PROD.edr')\n                        all_energy = panedr.edr_to_df(dirpath + 'PROD.edr')\n                        if len(all_energy['Potential'].values) > N_max:\n                            [start_production, _, _] = timeseries.detectEquilibration(all_energy['Potential'].values[::10])\n                            start_production *= 10\n                        else:\n                            [start_production, _, _] = timeseries.detectEquilibration(all_energy['Potential'].values)\n\n                        # Now read in the lattice tensor and average them\n                        if 'Box-XX' in list(all_energy):\n                            box_letters = ['XX', 'YY', 'ZZ', 'YX', 'ZX', 'ZY']\n                        else:\n                            box_letters = ['X', 'Y', 'Z']\n    \n                        for b in range(len(box_letters)):\n                            if len(all_energy['Potential'].values) > N_max:\n                                [hold,_,_] = timeseries.detectEquilibration(all_energy['Box-' + box_letters[b]].values[::10])\n                                hold *= 10\n                            else:\n                                [hold,_,_] = timeseries.detectEquilibration(all_energy['Box-' + box_letters[b]].values)\n\n                            if hold > start_production:\n                                start_production = hold\n\n                        if len(all_energy['Total Energy'].values[start_production:]) > N_max:\n                            start_production = len(all_energy['Total Energy'].values) - N_max\n\n                        # Setting the end point of the simulation\n                        N = len(all_energy['Total Energy'].values[start_production:])\n                        N_k[k] = N\n    \n                        u_kln[k, l, :N] = all_energy['Potential'].values[start_production:]\n    \n                        # Now set these energies over all temperatures\n                        u_kln[k, l:(l + len(Temperatures)), :N] = u_kln[k, l, :N]\n    \n                        # Now read in the volumes and average them\n                        V_pkn[p, t, :N] = all_energy['Volume'].values[start_production:]\n                        V_avg[p, t] = np.average(V_pkn[p, t, :N]) / float(Independent)\n                        ddV_avg[p, t] = np.std(V_pkn[p, t, :N]) / float(Independent)\n    \n                        # Making the lattice tensor all the correct sign with time    \n                        if count == 1:\n                            sign = np.sign(md.load(dirpath + 'pre_EQ.gro').unitcell_vectors[0].T)\n                            #sign = np.sign(md.load(polymorph + '/temperature/0/ANNEAL.gro').unitcell_vectors[0].T)\n                            for s in range(3):\n                                for j in range(3):\n                                    if sign[s, j] == 0.:\n                                        # Correcting for the sign of the lattice parameters\n                                        sign[s, j] = 1.\n\n                        for b in range(len(box_letters)):\n                            C_pkn[p, t, :N, box_place[b, 0], box_place[b, 1]] = np.absolute(all_energy['Box-' + box_letters[b]].values[start_production:]) * \\\n                                    sign[box_place[b, 0], box_place[b, 1]] * 10\n                        C_avg = np.average(C_pkn[p, t, :N], axis=0)\n                        dC = np.std(C_pkn[p, t, :N], axis=0)\n                        h_avg[p, t] = crystal_matrix_to_lattice_parameters(C_avg) \n                        dh[p, t] = np.absolute(crystal_matrix_to_lattice_parameters(C_avg + dC) - h_avg[p, t])\n                    else:\n                        N_k[k] = 0\n                        V_avg[p, t] = np.nan\n                        ddV_avg[p, t] = np.nan\n                        h_avg[p, t] = np.nan\n                        dh[p, t] = np.nan\n\n        print(\"Start1\")\n        # Convert all units to kcal\n        #u_pklnT[p, :, :, :] *= kJ_to_kcal\n        u_kln *= kJ_to_kcal\n        \n        print(\"Start2\")\n        # If this was already in kcal or already fully independent, revert\n        for j in range(len(Potentials)):\n            if Potentials[j][:6] == \"amoeba\":\n                #u_pklnT[p, :, j * len(Temperatures):(j + 1) * len(Temperatures), :, :] /= kJ_to_kcal\n                u_kln[:, j * len(Temperatures):(j + 1) * len(Temperatures), :] /= kJ_to_kcal\n        \n        print(\"Start3\")\n        # Remove dependent molecules\n        for j in range(len(Potentials)):\n            if Potentials[j][:6] != \"amoeba\":\n                #u_pklnT[p, :, j * len(Temperatures):(j + 1) * len(Temperatures), :, :] *= float(Independent) / Molecules\n                u_kln[:, j * len(Temperatures):(j + 1) * len(Temperatures), :] *= float(Independent) / Molecules\n    \n        print(\"Start4\")\n        # Now average together the energies and volumes at each state\n        for t in range(len(Temperatures)):\n            dU[p, t] = np.average(u_kln[t, t, :N_k[t]]) / float(Independent)\n            ddU[p, t] = np.std(u_kln[t, t, :N_k[t]]) / N_k[t] ** 0.5 / float(Independent)\n    \n        print(\"Start5\")\n        # convert to nondimensional units from kcal/mol\n        for k, beta in enumerate(beta_k):\n            u_kln[:, k, :] *= beta\n    \n        u_kln_save = u_kln.copy()\n        N_k_save = N_k.copy()\n        print(\"End!\")\n    \n        print(\"Number of retained samples\")\n        print(N_k)\n    \n        # Now create the full N_k matrix including the roll-backs as well as the free energy container\n        # N_k_matrix[i,k] is the total number of snapshots from alchemical state k using in spacing i\n        N_k_matrix = np.zeros([spacing + 1, K], np.int32)\n        for i in range(spacing + 1):\n            N_k_matrix[i, :] = N_k_save.copy()\n            N_k_matrix[i, 0: len(Temperatures)] = N_k_matrix[i, 0:len(Temperatures)] * float(i) / float(spacing)\n    \n        # =============================================================================================\n        # COMPUTE FREE ENERGY DIFFERENCE USING MBAR FOR EACH SPACING\n        # =============================================================================================\n        for i in range(spacing+1):\n            if i == 0 and len(Potentials) == 1:\n                continue\n            # Initialize MBAR.\n            print(\"Running MBAR...\")\n\n            # generate the weights of each of the umbrella set\n            mbar = pymbar.MBAR(u_kln, N_k_matrix[i, :], verbose=True)\n            print(\"MBAR Converged...\")\n       \n            hold = mbar.computeEffectiveSampleNumber(verbose=True)\n            print(hold)\n             \n            # extract self-consistent weights and uncertainties\n            (df_i, ddf_i, theta_i) = mbar.getFreeEnergyDifferences()\n\n            # extract entropy\n            [_, _, Delta_u_ij, _, Delta_s_ij, dDelta_s_ij] = mbar.computeEntropyAndEnthalpy()\n            print(\"Free Energies Optained...\")\n        \n            # Store the dimensionless results in the dA container\n            dA[p, i, :] = df_i[refk]\n            dH_mbar[p, i, :] = Delta_u_ij[0]\n            dS_mbar[p, i, :] = Delta_s_ij[0]\n            ddS_mbar[p, i, :] = dDelta_s_ij[0]\n            print(dA)\n        \n        # =============================================================================================\n        # COMPUTE UNCERTAINTY USING MBAR\n        # =============================================================================================\n        g_k = np.zeros([K])\n        for i in range(spacing + 1):\n            if i == 0 and len(Potentials) == 1:\n                continue\n\n            for k in range(K):\n                # subsample correlated data - for now, use energy from current state\n                if N_k_matrix[i, k] > 0:\n                    print(N_k_matrix[i, k])\n                    g_k[k] = timeseries.statisticalInefficiency(u_kln_save[k, k, 0:100])\n                    print(\"Correlation time for phase (%s), sampled state %d is %10.3f\" % (phase, k, g_k[k]))\n\n                    # subsample the data to get statistically uncorrelated data\n                    indices = np.array(timeseries.subsampleCorrelatedData(u_kln_save[k, k, 0:N_k_matrix[i, k]],\n                                                                          g=g_k[k]))\n                    N_k_matrix[i, k] = len(indices)\n                    u_kln[k, :, 0:N_k_matrix[i, k]] = u_kln_save[k, :, indices].transpose()  # not sure why we have to transpose\n    \n            print(\"Number of retained samples\")\n            print(N_k)\n    \n            print(\"Running MBAR...\")\n    \n            # generate the weights of each state\n            mbar = pymbar.MBAR(u_kln, N_k_matrix[i, :], verbose=True)\n            print(\"MBAR Converged...\") \n    \n            # extract self-consistent weights and uncertainties\n            (df_u, ddf_u, theta_u) = mbar.getFreeEnergyDifferences()\n    \n            # calculate the overlap it necessary\n            if len(Temperatures) == 2:\n                O_pij[p, :, :] = mbar.computeOverlap()[2]\n    \n            # testing\n            weights_in_gromos = np.zeros(K, float)\n            for k in range(K):\n                w = np.exp(mbar.Log_W_nk[:, k])\n                print(\"max weight in state %d is %12.7f\" % (k, np.max(w)))\n                neff = 1 / np.sum(w ** 2)\n\n                print(\"Effective number of sample in state %d is %10.3f\" % (k, neff))\n                print(\"Efficiency for state %d is %d/%d = %10.4f\" % (k, neff, len(w), neff / len(w)))\n                Efficiency[k] = neff / len(w)  # Store the efficiency\n                w_0 = np.exp(mbar.Log_W_nk[:, 0])  # Weights in gromos\n                initial_configs = np.sum(N_k[0:k])\n                final_configs = np.sum(N_k[0:k + 1])\n\n                print(\"Total weight in gromos \" + str(np.sum(w_0[initial_configs:final_configs])))\n                weights_in_gromos[k] = np.sum(w_0[initial_configs:final_configs])\n        \n            # Write out free energy differences\n            print(\"Free Energy Difference (in units of kcal/mol)\")\n            for k in range(K):\n                print(\"%8.3f %8.3f\" % (-df_i[k, 0], ddf_u[k, 0]))\n    \n            # Store the dimensionless results in the ddA container\n            ddA[p, i, :] = ddf_u[refk]\n\n    # Check the overlap it necessary\n    if len(Temperatures) == 2:\n        print(\"Overlap:\")\n        print(O_pij)\n        pdb.set_trace()\n    \n    # =============================================================================================\n    # FINALIZE THE RELATIVE FREE ENERGY AND ENTROPY\n    # =============================================================================================\n    for i in range(spacing + 1):\n        for t, T in enumerate(Temperatures):\n            for p in range(len(Polymorphs)):\n                #print('HERE!!!!!', dA[p, i, t], dA[0, i, t], (dA[p, i, t] - dA[0, i, t]), (beta_k[t] * float(Independent)), float(T),  float(refT), refdG[p])\n                dG[p, i, t] = (dA[p, i, t] - dA[0, i, t]) / (beta_k[t] * float(Independent)) + float(T) / float(refT) * \\\n                                                                                               refdG[p]\n                ddG[p, i, t] = ((ddA[p, i, t] ** 2 + ddA[0, i, t] ** 2) / (beta_k[t] * float(Independent)) ** 2 +\n                                float(T) / float(refT) * float(refddG[p]) ** 2) ** 0.5\n                if p == 0:\n                    continue\n                dS[p, i, t] = (dU[p, t] - dU[0, t] - dG[p, i, t]) / float(T)\n                ddS[p, i, t] = (ddU[p, t] ** 2 + ddU[p, t] ** 2 + ddG[p, i, t] ** 2) ** 0.5 / float(T)\n    \n    print(\"Polymorph Free Energy:\")\n    for p in range(len(Polymorphs)):\n        print(\"%8.3f %8.3f\" % (dG[p, spacing, len(Temperatures) - 1], ddG[p, spacing, len(Temperatures) - 1]))\n    \n    # =============================================================================================\n    # PLOT THE RELATIVE FREE ENERGY VS TEMPERATURE\n    # =============================================================================================\n\n#    Temperatures2 = np.array([0] + [j for j in Temperatures])\n#    Pressures2 = np.array([1] + [j for j in Pressures])\n#    dG2 = np.insert(dG, 0, np.transpose(np.tile(refdU, (1, 1))), axis=2)\n#    ddG2 = np.insert(ddG, 0, np.zeros([len(Polymorphs), spacing + 1]), axis=2)\n#    dS2 = np.insert(dS, 0, np.zeros([len(Polymorphs), spacing + 1]), axis=2)\n#    ddS2 = np.insert(ddS, 0, np.zeros([len(Polymorphs), spacing + 1]), axis=2)\n    PlotPress = 1  # Pressure to plot the dGvT curve at\n    Temperatures_P = Temperatures[Pressures == PlotPress]\n\n    if plot_out == True:\n        f, a = plt.subplots(1, 1)\n        xlabel = 'Temperature (K)'\n        ylabel = 'Relative Free Energy (kcal/mol)'\n\n        a.errorbar(Temperatures, dG[0, 0, :], yerr=np.zeros(len(dG[0, 0, :]), float), linestyle='--', marker='.',\n                   linewidth=2, alpha=0.6, color='b', label=Polymorphs[0])\n        for p in range(len(Polymorphs)):\n            if p == 0:\n                continue\n            if len(Potentials) > 1:\n                a.errorbar(Temperatures, dG[p, 0, :], yerr=ddG[p, 0, :], linestyle='--', marker='.', linewidth=2,\n                           alpha=0.6, color=Colors[p], label=Polymorphs[p])\n            a.errorbar(Temperatures_P, dG[p, 1, Pressures == PlotPress], yerr=ddG[p, 1, Pressures == PlotPress],\n                       linestyle='-', marker='.', linewidth=2, alpha=0.6, color=Colors[p], label=Polymorphs[p])\n    \n        a.set_xlabel(xlabel)\n        a.set_ylabel(ylabel)\n\n    if not os.path.isdir(output_directory):\n        subprocess.call(['mkdir', output_directory])\n\n    np.save(output_directory + '/T_' + molecule + '_' + potential, Temperatures_P)\n    for p, Poly in enumerate(Polymorphs):\n        np.save(output_directory + '/dGvT_' + molecule + '_' + Poly + '_' + potential, dG[p, spacing, Pressures == PlotPress])\n        np.save(output_directory + '/ddGvT_' + molecule + '_' + Poly + '_' + potential, ddG[p, spacing, Pressures == PlotPress])\n        if len(Potentials) > 1:\n            np.save(output_directory + '/dGvT_' + molecule + '_' + Poly + '_' + potential + '_indirect', dG[p, 0, :])\n            np.save(output_directory + '/ddGvT_' + molecule + '_' + Poly + '_' + potential + '_indirect', ddG[p, 0, :])\n            if spacing > 1:\n                np.save(output_directory + '/dGvT_' + molecule + '_' + Poly + '_' + potential + '_convergence', dG[p, :, :])\n                np.save(output_directory + '/ddGvT_' + molecule + '_' + Poly + '_' + potential + '_convergence', ddG[p, :, :])\n        np.save(output_directory + '/dS_' + molecule + '_' + Poly + '_' + potential, dS[p, spacing, :])\n        np.save(output_directory + '/ddS_' + molecule + '_' + Poly + '_' + potential, ddS[p, spacing, :])\n    \n    # =============================================================================================\n    # PLOT THE RELATIVE ENTROPY VS TEMPERATURE\n    # =============================================================================================\n\n    if plot_out == True:\n        f, a = plt.subplots(1, 1)\n        plt.xlabel('Temperature (K)', fontsize=20)\n        plt.ylabel('Relative Entropy (kcal/molK)', fontsize=20)\n        for p in range(len(Polymorphs)):\n            a.errorbar(Temperatures2, dS[p, spacing, :], yerr=ddS[p, spacing, :], linestyle='--', marker='.', linewidth=2,\n                       alpha=0.6, color=Colors[p], label=Polymorphs[p])\n    \n    # =============================================================================================\n    # PLOT THE AVERAGE ENERGY VS TEMPERATURE\n    # =============================================================================================\n\n#    dU2 = np.insert(dU, 0, np.transpose(absolutedU), axis=1)\n#    ddU2 = np.insert(ddU, 0, 0, axis=1)\n\n    if plot_out == True:\n        f, a = plt.subplots(1, 1)\n        plt.xlabel('Temperature (K)', fontsize=20)\n        plt.ylabel('Average Energy (kcal/mol)', fontsize=20)\n        for p in range(len(Polymorphs)):\n            a.errorbar(Temperatures2, dU[p, :], yerr=ddU[p, :], linestyle='--', marker='.', linewidth=2, alpha=0.6,\n                       color=Colors[p], label=Polymorphs[p])\n        plt.legend(loc='upper left')\n\n    for p, Poly in enumerate(Polymorphs):\n        np.save(output_directory + '/UvT_' + molecule + '_' + Poly + '_' + potential, dU[p, :])\n    \n    # =============================================================================================\n    # PLOT THE AVERAGE BOX VOLUME VS TEMPERATURE\n    # =============================================================================================\n    \n    if plot_out == True:\n        f, a = plt.subplots(1, 1)\n        plt.xlabel('Temperature (K)', fontsize=20)\n        for p in range(len(Polymorphs)):\n            a.errorbar(Temperatures, V_avg[p, :], yerr=ddV_avg[p, :], linestyle='--', marker='.', linewidth=2,\n                       alpha=0.6, color=Colors[p], label=Polymorphs[p])\n\n    for p, Poly in enumerate(Polymorphs):\n        np.save(output_directory + '/VvT_' + molecule + '_' + Poly + '_' + potential, V_avg[p, :])\n        np.save(output_directory + '/dVvT_' + molecule + '_' + Poly + '_' + potential, ddV_avg[p, :])\n\n    # =============================================================================================\n    # SAVE THE AVERAGE BOX VECTORS AND ANGLES VS TEMPERATURE\n    # =============================================================================================\n\n    for p, Poly in enumerate(Polymorphs):\n        np.save(output_directory + '/hvT_' + molecule + '_' + Poly + '_' + potential, h_avg[p, :])\n        np.save(output_directory + '/dhvT_' + molecule + '_' + Poly + '_' + potential, dh[p, :])\n\n    # =============================================================================================\n    # PLOT THE DIFFERENCE IN AVERAGE ENERGY VS TEMPERATURE\n    # =============================================================================================\n    \n    if plot_out == True:\n        f, a = plt.subplots(1, 1)\n        plt.xlabel('Temperature (K)', fontsize=20)\n        plt.ylabel('Average Energy Difference (kcal/mol)', fontsize=20)\n        for p in range(len(Polymorphs)):\n            if p == 0:\n                yerror = np.zeros(len(ddU[0, :]))\n            else:\n                yerror = []\n                for t in range(len(ddU[0, :])):\n                    yerror.append(float((ddU[0, t] ** 2 + ddU[p, t] ** 2) ** 0.5))\n            a.errorbar(Temperatures2, dU[p, :] - dU[0, :], yerr=yerror, linestyle='--', marker='.', linewidth=2,\n                       alpha=0.6, color=Colors[p], label=Polymorphs[p])\n    \n    # Save the data for future use.\n    for p, Poly in enumerate(Polymorphs):\n        np.save(output_directory + '/dUvT_' + molecule + '_' + Poly + '_' + potential, dU[p, :] - dU[0, :])\n        np.save(output_directory + '/ddUvT_' + molecule + '_' + Poly + '_' + potential, (ddU[p, :] ** 2 + ddU[0, :] ** 2) ** 0.5)\n\n    if plot_out == True:\n        plt.tight_layout()\n        plt.show()\n\n\nif __name__ == '__main__':\n    # =============================================================================================\n    # READ IN USER INPUTS\n    # =============================================================================================\n    parser = OptionParser()\n    parser.add_option('-p', '--plot', dest='plot', help='Plot output (default false)', default=True, action='store_true')\n#    parser.add_option('-T', dest='temp', help='Temperature', default=200)\n    parser.add_option('-P', dest='Pressure', help='Pressure', default=1)\n#    parser.add_option('-n', dest='polymorphs', help='Polymorphs to analyze', default='p1 p2 p3')\n    parser.add_option('-N', dest='molecules', help='number of supercell molecules', default=72)\n    parser.add_option('-M', dest='molecule', help='name of the molecule', default='benzene')\n    parser.add_option('-I', dest='independent', help='number of independent molecules', default='Same')\n    parser.add_option('-u', dest='potential', help='potential to create the phase diagram in', default='oplsaa')\n    parser.add_option('-i', dest='ignoreframes', help='Initial frames to ignore', default=200)\n    parser.add_option('-j', dest='includeframes', help='Number of frames to include', default=100000)\n    parser.add_option('-z', dest='simulation', help='The simulation package that was used', default='gromacs')\n    parser.add_option('-d', dest='directory', help='Parent directory of the reweight directories', default='None')\n    parser.add_option('-E', dest='ensemble', help='Simulation Ensemble', default='NVT')\n    parser.add_option('-s', dest='spacing', help='spacing for the plot rolling back the state 0 sampling', default=1)\n    parser.add_option('-H', '--hinge', dest='hinge', help='Optional string at end of jobs', default='DefaultHinge')\n    \n    (options, args) = parser.parse_args()\n    plot_out = options.plot\n    Temp = options.temp\n    Pressure = int(options.Pressure)\n    Molecules = int(options.molecules)\n    molecule = options.molecule\n    if options.independent == 'Same':\n        Independent = Molecules\n    else:\n        Independent = int(options.independent)\n    potential = options.potential\n    ignoreframes = int(options.ignoreframes)\n    includeframes = int(options.includeframes)\n    simulation = options.simulation\n    directory = options.directory\n    if directory == 'None':\n        directory = ''\n    ensemble = options.ensemble\n    spacing = int(options.spacing)\n    hinge = options.hinge\n    phase = \"solid\"\n    \n    Polymorphs, refT, refdG, refddG, refdU, absolutedU = old_systems_dictionary(potential, molecule)\n    dGvsT(plot_out=plot_out, Temperatures=Temp, Temperatures_unsampled=[], Pressure=Pressure, Molecules=Molecules, molecule=molecule,\n          Independent=Independent, potential=potential, ignoreframes=ignoreframes, includeframes=includeframes, \n          simulation=simulation, directory=directory, ensemble=ensemble, spacing=spacing, hinge=hinge, phase=phase, \n          Polymorphs=Polymorphs, refT=refT, refdG=refdG, refddG=refddG, refdU=refdU, absolutedU=absolutedU)\n\n", "meta": {"hexsha": "071b35ca7b8d9f41a488c9aa9d06b59c079e1728", "size": 48962, "ext": "py", "lang": "Python", "max_stars_repo_path": "PSCP/analysis-scripts/dGvsT.py", "max_stars_repo_name": "shirtsgroup/finite-temperature-crystal-scripts", "max_stars_repo_head_hexsha": "799bc882d958d9afa264a168dae0b3051bafaf0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PSCP/analysis-scripts/dGvsT.py", "max_issues_repo_name": "shirtsgroup/finite-temperature-crystal-scripts", "max_issues_repo_head_hexsha": "799bc882d958d9afa264a168dae0b3051bafaf0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2017-07-25T04:59:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-25T22:48:53.000Z", "max_forks_repo_path": "PSCP/analysis-scripts/dGvsT.py", "max_forks_repo_name": "shirtsgroup/finite-temperature-crystal-scripts", "max_forks_repo_head_hexsha": "799bc882d958d9afa264a168dae0b3051bafaf0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-04T07:01:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T07:01:25.000Z", "avg_line_length": 50.3724279835, "max_line_length": 458, "alphanum_fraction": 0.5242228667, "include": true, "reason": "import numpy", "num_tokens": 15796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.1913506800483058}}
{"text": "\"\"\" Parameters module. \"\"\"\n\n#  ISC License\n#\n#  Copyright (c) 2020–2022, Paul Wilhelm <anfrage@paulwilhelm.de>\n#\n#  Permission to use, copy, modify, and/or distribute this software for any\n#  purpose with or without fee is hereby granted, provided that the above\n#  copyright notice and this permission notice appear in all copies.\n#\n#  THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n#  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n#  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n#  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n#  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n#  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n#  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\nfrom __future__ import annotations\nfrom typing import Callable\nimport numpy as np\nfrom numba import jit, prange\nfrom magneticalc.Backend_Types import get_jit_enabled\nfrom magneticalc.ConditionalDecorator import ConditionalDecorator\nfrom magneticalc.Constants import Constants\nfrom magneticalc.Debug import Debug\nfrom magneticalc.Field_Types import FIELD_TYPE_A, FIELD_TYPE_B\nfrom magneticalc.Metric import Metric\nfrom magneticalc.Validatable import Validatable, require_valid, validator\n\n\nclass Parameters(Validatable):\n    \"\"\" Parameters class. \"\"\"\n\n    def __init__(self) -> None:\n        \"\"\"\n        Initializes parameters class.\n        \"\"\"\n        Validatable.__init__(self)\n        Debug(self, \": Init\", init=True)\n\n        self._energy: float = 0.0\n        self._self_inductance: float = 0.0\n        self._magnetic_dipole_moment: float = 0.0\n\n    def set(self, *args, **kwargs):\n        \"\"\"\n        Sets the parameters\n        \"\"\"\n\n    # ------------------------------------------------------------------------------------------------------------------\n\n    def _get_squared_field(\n            self,\n            sampling_volume: SamplingVolume,  # type: ignore\n            field: Field  # type: ignore\n    ) -> float:\n        \"\"\"\n        Returns the \"squared\" field scalar.\n\n        @param sampling_volume: SamplingVolume\n        @param field: B-field\n        @return: Float\n        \"\"\"\n        return self._get_squared_field_worker(sampling_volume.permeabilities, field.vectors)\n\n    @staticmethod\n    @ConditionalDecorator(get_jit_enabled(), jit, nopython=True, parallel=True)\n    def _get_squared_field_worker(sampling_volume_permeabilities: np.ndarray, field_vectors: np.ndarray) -> float:\n        \"\"\"\n        Returns the \"squared\" field scalar.\n\n        @param sampling_volume_permeabilities: Ordered list of sampling volume's relative permeabilities µ_r\n        @param field_vectors: Ordered list of 3D vectors (B-field)\n        @return: Float\n        \"\"\"\n        squared = 0\n        for i in prange(len(field_vectors)):\n            squared += np.dot(field_vectors[i], field_vectors[i] / sampling_volume_permeabilities[i])\n        return squared\n\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n    def _get_magnetic_dipole_moment(\n            self, wire: Wire,  # type: ignore\n            length_scale: float\n    ) -> float:\n        \"\"\"\n        Returns the magnetic dipole moment scalar.\n\n        @param wire: Wire\n        @param length_scale: Length scale (m)\n        @return: Float\n        \"\"\"\n        elements_center = np.array([element[0] for element in wire.elements])\n        elements_direction = np.array([element[1] for element in wire.elements])\n        vector = self._get_magnetic_dipole_moment_worker(elements_center, elements_direction, length_scale)\n        return np.abs(wire.dc * np.linalg.norm(vector) / 2)\n\n    @staticmethod\n    @ConditionalDecorator(get_jit_enabled(), jit, nopython=True, parallel=True)\n    def _get_magnetic_dipole_moment_worker(\n            elements_center: np.ndarray,\n            elements_direction: np.ndarray,\n            length_scale: float\n    ):\n        \"\"\"\n        Returns the (unscaled) magnetic dipole moment vector.\n\n        @param elements_center: Current element centers\n        @param elements_direction: Current element directions\n        @param length_scale: Length scale (m)\n        @return: Magnetic dipole moment vector\n        \"\"\"\n        squared = np.zeros(3)\n        for i in prange(len(elements_center)):\n            squared += np.cross(elements_center[i] * length_scale, elements_direction[i] * length_scale)\n        return squared\n\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n    @validator\n    def recalculate(\n            self,\n            wire: Wire,  # type: ignore\n            sampling_volume: SamplingVolume,  # type: ignore\n            field: Field,  # type: ignore\n            progress_callback: Callable\n    ) -> bool:\n        \"\"\"\n        Recalculates parameters.\n\n        @param wire: Wire\n        @param sampling_volume: SamplingVolume\n        @param field: Field\n        @param progress_callback: Progress callback\n        @return: True (currently non-interruptable)\n        \"\"\"\n        Debug(self, \".recalculate()\")\n\n        progress_callback(0)\n\n        self._magnetic_dipole_moment = self._get_magnetic_dipole_moment(wire, Metric.LengthScale)\n\n        progress_callback(33)\n\n        if field.type == FIELD_TYPE_A:\n\n            pass\n\n        elif field.type == FIELD_TYPE_B:\n\n            dV = (Metric.LengthScale / sampling_volume.resolution) ** 3  # Sampling volume element\n            self._energy = self._get_squared_field(sampling_volume, field) * dV / Constants.mu_0\n\n            progress_callback(66)\n\n            self._self_inductance = self._energy / np.square(wire.dc)\n\n        progress_callback(100)\n\n        return True\n\n    @property\n    @require_valid\n    def energy(self) -> float:\n        \"\"\"\n        Returns calculated energy.\n\n        @return: Float\n        \"\"\"\n        return self._energy\n\n    @property\n    @require_valid\n    def self_inductance(self) -> float:\n        \"\"\"\n        Returns calculated self-inductance.\n\n        @return: Float\n        \"\"\"\n        return self._self_inductance\n\n    @property\n    @require_valid\n    def magnetic_dipole_moment(self) -> float:\n        \"\"\"\n        Returns calculated magnetic dipole moment.\n\n        @return: Float\n        \"\"\"\n        return self._magnetic_dipole_moment\n", "meta": {"hexsha": "db2cc2af3baaa00b689c36b5a4bb58675112e371", "size": 6416, "ext": "py", "lang": "Python", "max_stars_repo_path": "magneticalc/Parameters.py", "max_stars_repo_name": "CSChisholm/MagnetiCalc", "max_stars_repo_head_hexsha": "19b6897677c334de18ba2ea82395f941c77a2849", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "magneticalc/Parameters.py", "max_issues_repo_name": "CSChisholm/MagnetiCalc", "max_issues_repo_head_hexsha": "19b6897677c334de18ba2ea82395f941c77a2849", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "magneticalc/Parameters.py", "max_forks_repo_name": "CSChisholm/MagnetiCalc", "max_forks_repo_head_hexsha": "19b6897677c334de18ba2ea82395f941c77a2849", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2435233161, "max_line_length": 120, "alphanum_fraction": 0.6206359102, "include": true, "reason": "import numpy,from numba", "num_tokens": 1488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.3208212878370535, "lm_q1q2_score": 0.19134845009332282}}
{"text": "# ------------------------------------------------------------------------------\n# Copyright (c) Microsoft\n# Licensed under the MIT License.\n# Some code is from https://github.com/princeton-vl/pose-ae-train/blob/454d4ba113bbb9775d4dc259ef5e6c07c2ceed54/utils/group.py\n# Written by Bin Xiao (leoxiaobin@gmail.com)\n# Modified by Bowen Cheng (bcheng9@illinois.edu)\n# ------------------------------------------------------------------------------\n\"\"\"\n############################################################################\n将检测分组为个体实例姿态。为此, 网络将在每个关节的像素位置生成一个标记。\n换句话说, 每个关节热图都有相应的 \"tag标签\" 热图。\n因此, 如果有m个人体关节需要预测, 那么网络将输出总共2m通道, m用于检测和m用于分组。\n为了将检测解析成个体实例, \n我们使用非最大抑制来获取每个关节的峰值检测, 并在相同的像素位置检索其相应的tag标记。\n然后, 我们通过比较检测的标记值和匹配足够接近的标记值, 对整个人体关节点检测进行分组。\n而后一组检测形成了一个人的姿势估计。\n############################################################################\n为了产生最后一个最终预测集合，我们对每个关节点进行迭代。\n迭代的顺序是先考虑头和躯干而后逐渐像肢体移动。\n我们从第一个关节点开始，NMS后得到每个超过阈值的关节点。\n这些关键点组组成了我们待检测人的最初候选池。\n我们之后考虑检测后续的关节点。我们将后续关节点与我们现有关节点候选池相比，得到其最优匹配。\n只有当两个标记相差小于一个特别的阈值时才会被匹配。\n除此之外，我们因此基于标记距离和检测分数的最大匹配。\n如果没有任何检测额被匹配，则被视为一个新的人体实例。这种情况可能是因为某个特定人体只有手或脚可见。\n我们在每类关节点上循环匹配，直到每个检测都被匹配到一个人。\n##########################################################################################\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom munkres import Munkres\nimport numpy as np\nimport torch\n\n\ndef py_max_match(scores):\n    m = Munkres()   # 匈牙利算法\n    \"\"\"\n    ##################################################################\n    Compute the indexes for the lowest-cost pairings between rows and\n    columns in the database. Returns a list of `(row, column)` tuples\n    that can be used to traverse the matrix.\n    ##################################################################\n    \"\"\"\n    tmp = m.compute(scores)\n    tmp = np.array(tmp).astype(np.int32)\n    return tmp\n\n\n\"\"\"\n##########################\n# 通过tag值，对节点进行匹配\n##########################\n# 一张图片检测出了几个人，最终有几个人，就有几个tag键，最后在\n            # grouped_keys中就会有几个不同的值，每个人对应一个值，\n            # grouped_keys: [ tag1,tag2,...,tag_?? ]\n            # joints_dict: { tag1: array(17*5) , tag2: array(17*5), .... ,tag_??: array(17*5) }    ，\n            # 最终有几个人，就有几个tag键\n            # grouped_key中的值和joints_dict中的键一致。\n            # grouped_tags形如:[array([ 3.0320523, -2.9441261] ), array([-3.2409573,  3.267928 ] ), array([-0.46144685,  0.43847117] ), array([-6.7198505,  6.6868863] )]\n            # tag_dict形如:\n            #            {3.0482664: [array([ 3.0482664, -2.942074 ] ), array([ 3.0499892, -2.9416664] ), array([ 3.04908 , -2.946251] ), array([ 3.0546198, -2.9452639] ), array([ 3.0284576, -2.9707832] ), array([ 3.011262 , -2.9344423] ), array([ 3.0276155, -2.9461455] ), array([ 3.022631, -2.930122] ), array([ 3.0320063, -2.947176 ] ), array([ 3.0340366, -2.9682217] ), array([ 3.0116858, -2.9123354] ), array([ 3.0149767, -2.9450297] ), array([ 3.0390344, -2.9229352] )], \n            #            -3.204033: [array([-3.204033 ,  3.2672586] ), array([-3.224389 ,  3.2966106] ), array([-3.2322555,  3.254828 ] ), array([-3.2290933,  3.2748113] ), array([-3.2254848,  3.290883 ] ), array([-3.2734041,  3.2389045] ), array([-3.262566 ,  3.2427683] ), array([-3.270686,  3.308473] ), array([-3.240734 ,  3.2396798] ), array([-3.22856  ,  3.2748213] ), array([-3.2633042,  3.247148 ] ), array([-3.2369757,  3.2789457] ), array([-3.2354915,  3.1973739] )], \n            #            -0.48780698: [array([-0.48780698,  0.4803399 ] ), array([-0.4915051 ,  0.48355848] ), array([-0.47469807,  0.46150476] ), array([-0.43962345,  0.45701584] ), array([-0.47148287,  0.45973817] ), array([-0.38883165,  0.44795612] ), array([-0.39312   ,  0.29450473] ), array([-0.49791056,  0.4785707 ] ), array([-0.4475416 ,  0.36834407] ), array([-0.47388119,  0.49372977] ), array([-0.47124237,  0.3472029 ] ), array([-0.49971843,  0.48918843] ), array([-0.49369287,  0.46173176] )], \n            #            -6.7378864: [array([-6.7378864,  6.6715736] ), array([-6.738204,  6.720743] ), array([-6.7024045,  6.702105 ] ), array([-6.674477 ,  6.6906085] ), array([-6.7082214,  6.6431236] ), array([-6.8019643,  6.791915 ] ), array([-6.6872525,  6.6337585] ), array([-6.708395 ,  6.6412625] ), array([-6.686763,  6.692321] )]\n            #            }\n##################################################\n\"\"\"\n\ndef match_by_tag(inp, params):\n    assert isinstance(params, Params), 'params should be class Params()'\n    \"\"\"\n    # zip后的inp，使得：\n    # tag_k.shape=(17,30,2)\n    # loc_k.shape=(17,30,2)\n    # val_k.shape=(17,30)\n    \"\"\"\n    tag_k, loc_k, val_k = inp   \n                    \n    default_ = np.zeros((params.num_joints, 3 + tag_k.shape[2]))   # shape=(17,5)\n\n    joint_dict = {}\n    tag_dict = {}\n    for i in range(params.num_joints): # 17\n        idx = params.joint_order[i]\n        \"\"\"\n        # 17类中的第idx类节点\n        \"\"\"          \n        # tags.shape=(30,2)                   \n        tags = tag_k[idx]   \n        # joints.shape=(30,2+1+2)  , 二维坐标 + value值 + tag值\n        joints = np.concatenate(\n            (loc_k[idx], val_k[idx, :, None], tags), 1\n        )\n        # 从30个节点中选择val值大于阈值的节点,\n        # 这些关键点组组成了我们待检测人的最初候选池.                                                       \n        # mask.shape=(30)              \n        mask = joints[:, 2] > params.detection_threshold\n\n        \"\"\"\n        ##############################################\n        # 从该类节点的30个中，\n        # 挑选出val大于阈值的节点对应的tags和joints\n        # 假设有m个节点满足阈值条件，则\n        # tags.shape=(k,2)\n        # joints.shape=(k,5)  \n        ##############################################\n        \"\"\"\n        # tags.shape=(k,2)\n        tags = tags[mask]                      \n        # joints.shape=(k,5)  , 二维坐标 + value值 + tag值\n        print('joints.shape:{}'.format(joints.shape))\n\n        if joints.shape[0] == 0:\n            continue\n\n        \"\"\"\n        注意：注意：注意：注意：\n        这些键tag都是第一次出现的值（所以几乎都是第一类节点中的tag值，不过如果某些人的第一类节点可能被遮挡，这些人的tag键开始时就没有出现）\n        \"\"\"\n        # 当此时访问的是第一类节点\n        if i == 0 or len(joint_dict) == 0:\n            for tag, joint in zip(tags, joints):   # 逐一访问第一类节点的30个中的k=m个\n                # tag.shape=2 , joint.shape=5   \n                # 以该点的tag值作为字典的键\n                # 共生成m个键值对\n                key = tag[0]\n                # Python字典setdefault()方法和get()方法类似,如果键不已经存在于字典中,将会添加键并将值设为默认值。\n\n                joint_dict.setdefault(key, np.copy(default_))[idx] = joint\n                tag_dict[key] = [tag]\n        \n        # 当该类节点不是第一类节点时\n        # 假设此时访问第二类节点\n        else:\n            # grouped_keys和grouped_tags为之前的值\n            # grouped_keys = [ tag_1 , tag_2 , ... , tag_?? ]\n            grouped_keys = list(joint_dict.keys())[:params.max_num_people]\n\n            # grouped_tags = [ array([a_1,b_1]) , array([a_2,b_2]) , ... , array([a_????,b_????]) ]\n            \"\"\"\n            tag_dict: 不同的键tag代表不同一个人，而在一个键tag中，保存着该人存在的节点的真实tag值，\n            因为一个人的节点最多有17个，所以一个键tag最多会有17个节点的tag值,最少一个tag值。\n            \"\"\"\n            grouped_tags = [np.mean(tag_dict[i], axis=0) for i in grouped_keys] \n                                                 \n            # False\n            if params.ignore_too_much \\\n               and len(grouped_keys) == params.max_num_people:\n                continue\n            \n            \"\"\"                         \n            ##########################################################\n            # joints为当前节点，假设有k=n个候选点，则joints.shape=(n,5)，\n            # grouped_tags为之前的tags值。np.array(grouped_tags) = array([[a_1,b_1],[a_2,b_2],...,[a_m,b_m]])  , shape=(m,2)\n            ##################################################################################################################     \n            \"\"\"\n            \"\"\"\n            $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n            # 计算了“当前类别的n个节点”分别与“之前的m个节点”差值diff=(n,1,2)-(1,m,2),再求L2范数\n            # 得到diff.shape=(n,m)                                                                                \n            $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n            注意：\n            注意：\n            注意：\n            当前类别的节点是与到目前为止已存在的人的代表节点的tag(即：已存在的字典的键)。\n            注意：\n            注意：\n            注意：\n            当前类别的节点是与到目前为止已存在的人的代表节点的tag(即：已存在的字典的键)。\n            注意：\n            \"\"\"    \n            diff = joints[:, None, 3:] - np.array(grouped_tags)[None, :, :]  # diff.shape=(n,m,2)\n            diff_normed = np.linalg.norm(diff, ord=2, axis=2)    # diff_normed.shape=(n,m)\n\n            diff_saved = np.copy(diff_normed)\n\n            if params.use_detection_val: # True\n                diff_normed = np.round(diff_normed) * 100 - joints[:, 2:3]\n\n            num_added = diff.shape[0]    # 当前类节点的 k2 个值\n            num_grouped = diff.shape[1]  # 之前类节点的 k1 个值\n\n            # 如果 “当前类节点数n” 比 “之前类别节点m” 大。\n            if num_added > num_grouped:\n                # np.concatenate(([n,m],[n,n-m]),axis=1) ----> diff_normed.shape=( n , n )\n                diff_normed = np.concatenate(\n                    (\n                        diff_normed,\n                        np.zeros((num_added, num_added-num_grouped))+1e10\n                    ),\n                    axis=1\n                )\n\n            \"\"\"\n            ###########################################\n            # 运用匈牙利算法寻找相邻节点的最优匹配。\n            # 获取相邻节点的匹配对,pair.shape=(n,2)         \n            ###########################################\n            \"\"\"\n            pairs = py_max_match(diff_normed)   # 运用匈牙利算法\n            \n            for row, col in pairs:\n                if (row < num_added and col < num_grouped and diff_saved[row][col] < params.tag_threshold):  \n                    \"\"\"\n                    # 注意：\n                    # 注意：\n                    # 注意：\n                    # 注意：\n                    # 当前的tag值与之前的键tag相匹配。\n                    # 说明当前值为tag的节点属于已经存在的一个人。\n                    # 注意：\n                    # 注意：\n                    \"\"\"\n                    key = grouped_keys[col]       # grouped_ksys[col]是之前已检测到的人的键tag   , 其与当前的tag是最佳匹配。                               \n                    joint_dict[key][idx] = joints[row]  # joints[row]是当前的n个节点的第row个节点的joint ，将其添加到joint_dict[前tag][第idx类节点]\n                    tag_dict[key].append(tags[row])     # tags[row]是当前的n个节点的第row个节点的tag ，将其添加到tag_dict[前tag]          \n                else: \n                    \"\"\"\n                    # 注意：\n                    # 注意：\n                    # 注意：\n                    # 当当前类别的某一节点的tag与已存在的人的代表tag(即：已存在的字典键tag)都不匹配时，\n                    # 说明：当前出现的不能匹配tag值表明了一个新的人体出现，\n                    # 所以，需要更新旧的字典，添加新的键tag，并将该节点(即该人体)的joints和tagsdian加入该键值中。\n                    # 注意：\n                    # 注意：\n                    \"\"\"                                                                                              \n                    key = tags[row][0]\n                    joint_dict.setdefault(key, np.copy(default_))[idx] = \\\n                        joints[row]\n                    tag_dict[key] = [tags[row]]\n\n            \"\"\"\n            ####################################################################################################################################\n            # 最终，\n            # 得到该幅图片的所有检测到的一个一个单独的人体肢体节点集合。 \n            # joint_dict:{tag1:array(x1,5),tag2:array(x2,5),...,tag_i:array(xi,5)}\n            # 其中，有几个人体就有几个tag键，并且每个人体出现的关节点数也是不相同的，即每个\"x\"的数值是不定的，x在(1-->17)之间。\n            # 注意：\n            # 注意：\n            # 注意：这里的idx不是一个连续的数值，每一类的节点都有对应的idx，并且初始化的数组default_=np.zeros(17,5)！！！！！！！！！！！！！！！\n            # 注意：因此，最后的joint_dict中的数组array是有全零行的；最终的每个人体的数组shape=(17,5)！！！！！！！！！！！！！！！！！！！！！！\n            # 注意：\n            # 注意：\n            ------------------------------------------------------------------------------------------------------------------------------------\n            # 其中，tag_dict和joint_dict是相对应的，joint_dict包含tag_dict , \n            # tag_dict:{tag1:[array(tag11),..,array(tag_x1)],tag2:[array(tag22),..,array(tag_x2)],....,tag_i:[array(tagii),..,array(tag_xi)]}\n            #####################################################################################################################################\n            \"\"\"\n\n    ans = np.array([joint_dict[i] for i in joint_dict]).astype(np.float32)\n    # ans.shape=(人体数目，17，5)\n    print('ans.shape={}'.format(ans.shape))\n    return ans\n\n\nclass Params(object):\n    def __init__(self, cfg):\n        self.num_joints = cfg.DATASET.NUM_JOINTS\n        self.max_num_people = cfg.DATASET.MAX_NUM_PEOPLE   # 30\n\n        self.detection_threshold = cfg.TEST.DETECTION_THRESHOLD\n        self.tag_threshold = cfg.TEST.TAG_THRESHOLD\n        self.use_detection_val = cfg.TEST.USE_DETECTION_VAL\n        self.ignore_too_much = cfg.TEST.IGNORE_TOO_MUCH\n\n        if cfg.DATASET.WITH_CENTER and cfg.TEST.IGNORE_CENTER:\n            self.num_joints -= 1\n\n        if cfg.DATASET.WITH_CENTER and not cfg.TEST.IGNORE_CENTER:\n            self.joint_order = [\n                i-1 for i in [18, 1, 2, 3, 4, 5, 6, 7, 12, 13, 8, 9, 10, 11, 14, 15, 16, 17]\n            ]\n        else:\n            self.joint_order = [\n                i-1 for i in [1, 2, 3, 4, 5, 6, 7, 12, 13, 8, 9, 10, 11, 14, 15, 16, 17]\n            ]\n\n\nclass HeatmapParser(object):\n    def __init__(self, cfg):\n        self.params = Params(cfg)\n        self.tag_per_joint = cfg.MODEL.TAG_PER_JOINT\n        self.pool = torch.nn.MaxPool2d(\n            cfg.TEST.NMS_KERNEL, 1, cfg.TEST.NMS_PADDING\n        )\n\n    def nms(self, det):\n        \"\"\"\n        # # 对热力图进行最大池化torch.nn.MaxPool2d(5,1,2)\n        \"\"\"\n        maxm = self.pool(det)\n        \"\"\"\n        # 挑选出最大值位置，maxm在该处值为1\n        \"\"\"    \n        maxm = torch.eq(maxm, det).float()\n        \"\"\"\n        # 将热力图det中的极大值保留，去除非极大值\n        \"\"\"\n        det = det * maxm\n        return det\n\n    def match(self, tag_k, loc_k, val_k):\n        # tag_k.shape=(1,17,30,2)\n        # loc_k.shape=(1,17,30,2)二维坐标(x,y)\n        # val_k.shape=(1,17,30)\n        match = lambda x: match_by_tag(x, self.params)\n        \"\"\"\n        # zip() 函数用于将可迭代的对象作为参数，将对象中对应的元素打包成一个个元组，然后返回由这些元组组成的对象 \n        # 如果各个迭代器的元素个数不一致，则返回列表长度与最短的对象相同\n        \"\"\"\n        \"\"\"\n        # match函数返回该幅图片的所有检测到的一个一个单独的人体肢体节点集合。 \n        # joint_dict:{tag1:array(x1,5),tag2:array(x2,5),...,tag_i:array(xi,5)}\n        # 其中，有几个人体就有几个tag键，并且每个人体出现的关节点数也是不相同的，所以每个人体对应的array(17,5)中的“一些行是全零行”。\n        # 接着再将其转换为numpy数组ans,ans.shape=(人体数，17，5),其中ans.shape[0]等于检测到的人体数。\n        # 最后，再将其第0维的每个array(17，5)变为list列表元素。\n        ################################################################\n\n        \"\"\"\n        return list(map(match, zip(tag_k, loc_k, val_k)))\n\n\n\n    \"\"\"\n    #############################################\n    # tensor张量：热力图det.shape=(1,17,h,w)\n    # tensor张量：tag图tag.shape=(1,17,h,w,2)\n    #############################################\n    \"\"\"\n    def top_k(self, det, tag):\n        # det = torch.Tensor(det, requires_grad=False)\n        # tag = torch.Tensor(tag, requires_grad=False)\n\n        \"\"\"\n        ##################################\n        # 对热力图进行NMS非极大值抑制，\n        # 通过最大池化操作，找到极大值位置，\n        # 保留热力图中的极大值，去除非极大值 \n        ##################################\n        \"\"\"\n        det = self.nms(det)\n        num_images = det.size(0)   # 1\n        num_joints = det.size(1)   # 17\n        h = det.size(2)     # 512\n        w = det.size(3)     # 512\n\n        \"\"\"\n        #######################################\n        # 将每个节点的二维(h,w)热力图展开为一维 \n        # det.shape=(1,17,262144)\n        #######################################\n        \"\"\"\n        det = det.view(num_images, num_joints, -1)     # shape=(1,17,262144)\n\n        \"\"\"\n        ###########################################################################\n        # topk:沿给定dim=2维度返回输入张量input中 k=30 个最大值。\n        # 如果不指定dim，则默认为input的最后一维,\n        # 返回一个元组 (values,indices)，其中indices是原始输入张量input中测元素下标\n        ##########################################################################\n        # 得到每个节点的前30个最大值，及其对应的下标\n        # val_k.shape=(1,17,30)\n        # ind.shape=(1,17,30)    \n        # ind为“一维坐标值”\n        ############################################\n        \"\"\"\n        val_k, ind = det.topk(self.params.max_num_people, dim=2)      # 得到每个节点的前30个最大值，及其对应位置一维坐标\n\n        \"\"\"\n        ###################################################\n        # 将tag.shape=(1,17,512,512,2) ---> (1,17,262144,2)\n        ###################################################\n        \"\"\"\n        tag = tag.view(tag.size(0), tag.size(1), w*h, -1)\n\n        if not self.tag_per_joint:  # not True\n            tag = tag.expand(-1, self.params.num_joints, -1, -1)\n\n        \"\"\"\n        ######################################################################\n        # torch.gather(input,dim,index),从原tensor中获取指定dim和指定index的数据,\n        # 在tag图中索取热力图中前30个人每个节点位置对应的tag值\n        # tag_k.shape=(1,17,30,2)\n        ######################################################################\n        \"\"\"\n        tag_k = torch.stack(\n            [\n                torch.gather(tag[:, :, :, i], 2, ind)\n                for i in range(tag.size(3))\n            ],\n            dim=3\n        )\n\n        \"\"\"\n        ################################\n        # 将“一维坐标ind”转换为二维坐标(x,y)\n        # ind.shape=(1,17,30)\n        # --->\n        # ind_k.shape=(1,17,30,2)\n        ################################\n        \"\"\"\n        x = ind % w\n        y = (ind / w).long()    # self.long() is equivalent to self.to(torch.int64)\n        ind_k = torch.stack((x, y), dim=3)   # ind_k.shape=(1,17,30,2)\n\n        \"\"\"\n        ####################################\n        # tag_k.shape=(1,17,30,2)\n        # ind_k.shape=(1,17,30,2)二维坐标(x,y)\n        # val_k.shape=(1,17,30)\n        ####################################\n        \"\"\"\n        ans = {\n            'tag_k': tag_k.cpu().numpy(),\n            'loc_k': ind_k.cpu().numpy(),\n            'val_k': val_k.cpu().numpy()\n        }\n\n        return ans\n\n    def adjust(self, ans, det):\n        # ans为列表，图片batch_size数目len(ans)=1 ，ans=[array(num_people，17，5),]\n        for batch_id, peoples in enumerate(ans): \n            # 对一张图片中的所有人   \n            # peoples.shape=(num_people,17,5)\n            for people_id, people in enumerate(peoples):\n                # people.shape=(17,5)                       \n                for joint_id, joint in enumerate(people):\n                    # joint.shape=(5,)  , 二维节点坐标(x,y) + 一维热图value值 + 二维(tag,tag')值\n                    if joint[2] > 0:\n                        # 该节点在对应的热力图中的坐标\n                        y, x = joint[0:2]\n                        xx, yy = int(x), int(y)\n                        # print(batch_id, joint_id, det[batch_id].shape)\n                        # 热力图det.shape=(1,17,h,w) \n                        # 该节点所在的热力图tmp\n                        # tmp.shape=(h,w)\n                        tmp = det[batch_id][joint_id]\n\n                        # 微调该节点的y坐标\n                        if tmp[xx, min(yy+1, tmp.shape[1]-1)] > tmp[xx, max(yy-1, 0)]:\n                            y += 0.25\n                        else:\n                            y -= 0.25\n\n                        # 微调该节点的x坐标                                                     \n                        if tmp[min(xx+1, tmp.shape[0]-1), yy] > tmp[max(0, xx-1), yy]:\n                            x += 0.25\n                        else:\n                            x -= 0.25\n                        # 更新节点坐标(x,y)\n                        ans[batch_id][people_id, joint_id, 0:2] = (y+0.5, x+0.5)\n        return ans\n\n    def refine(self, det, tag, keypoints):\n        \"\"\"\n        Given initial keypoint predictions, we identify missing joints\n        :param det: numpy.ndarray of size (17, 128, 128)\n        :param tag: numpy.ndarray of size (17, 128, 128) if not flip\n        :param keypoints: numpy.ndarray of size (17, 4) if not flip, last dim is (x, y, det score, tag score)\n        :return: \n        \"\"\"\n        if len(tag.shape) == 3:\n            # tag shape: (17, 128, 128, 1)\n            tag = tag[:, :, :, None]\n\n        tags = []\n        for i in range(keypoints.shape[0]):\n            if keypoints[i, 2] > 0:\n                # save tag value of detected keypoint\n                x, y = keypoints[i][:2].astype(np.int32)\n                tags.append(tag[i, y, x])\n\n        # mean tag of current detected people\n        prev_tag = np.mean(tags, axis=0)\n        ans = []\n\n        for i in range(keypoints.shape[0]):\n            # score of joints i at all position\n            tmp = det[i, :, :]\n            # distance of all tag values with mean tag of current detected people\n            tt = (((tag[i, :, :] - prev_tag[None, None, :]) ** 2).sum(axis=2) ** 0.5)\n            tmp2 = tmp - np.round(tt)\n\n            # find maximum position\n            y, x = np.unravel_index(np.argmax(tmp2), tmp.shape)\n            xx = x\n            yy = y\n            # detection score at maximum position\n            val = tmp[y, x]\n            # offset by 0.5\n            x += 0.5\n            y += 0.5\n\n            # add a quarter offset\n            if tmp[yy, min(xx + 1, tmp.shape[1] - 1)] > tmp[yy, max(xx - 1, 0)]:\n                x += 0.25\n            else:\n                x -= 0.25\n\n            if tmp[min(yy + 1, tmp.shape[0] - 1), xx] > tmp[max(0, yy - 1), xx]:\n                y += 0.25\n            else:\n                y -= 0.25\n\n            ans.append((x, y, val))\n        ans = np.array(ans)\n\n        if ans is not None:\n            for i in range(det.shape[0]):\n                # add keypoint if it is not detected\n                if ans[i, 2] > 0 and keypoints[i, 2] == 0:\n                # if ans[i, 2] > 0.01 and keypoints[i, 2] == 0:\n                    keypoints[i, :2] = ans[i, :2]\n                    keypoints[i, 2] = ans[i, 2]\n\n        return keypoints\n\n                          \n    \"\"\"\n    #############################################\n    # tensor张量：热力图det.shape=(1,17,h,w)\n    # tensor张量：tag图tag.shape=(1,17,h,w,2)\n    #############################################\n    \"\"\"\n    def parse(self, det, tag, adjust=True, refine=True):\n        \"\"\"\n        ####################################\n        topk返回值：\n        # tag_k.shape=(1,17,30,2)\n        # ind_k.shape=(1,17,30,2)二维坐标(x,y)\n        # val_k.shape=(1,17,30)\n        ####################################\n        match返回值：\n        # ans为列表，图片batch_size数目len(ans)=1\n        # ans=[array(num_people,17,5),] ，一张图有num_people个人 ，每个人体对应一个17*5的array数组。            \n        #######################################################################################\n        \"\"\"\n        # ans为列表，图片batch_size数目len(ans)=1 ，ans=[array(num_people，17，5),]\n        ans = self.match(**self.top_k(det, tag))\n\n        if adjust:\n            # 微调整每个节点的(x,y)坐标\n            ans = self.adjust(ans, det)\n\n\n        \"\"\"\n        求一个人的所有17节点的热图值的均值，\n        并将每个人的热图均值加入到scores列表中。\n        \"\"\"\n        # ans[0]是一个numpy数组，ans[0]=array(num_people,17,5)\n        # len(scores)=num_people\n        # scores=[ heatpoint1,heatpoint2,...,heatpoint_numpeople ]\n        scores = [i[:, 2].mean() for i in ans[0]]\n\n        if refine:\n            ans = ans[0]\n            # for every detected person\n            for i in range(len(ans)):\n                det_numpy = det[0].cpu().numpy()\n                tag_numpy = tag[0].cpu().numpy()\n                if not self.tag_per_joint:      #  self.tag_per_joint=True\n                    tag_numpy = np.tile(\n                        tag_numpy, (self.params.num_joints, 1, 1, 1)\n                    )\n                ans[i] = self.refine(det_numpy, tag_numpy, ans[i])\n            ans = [ans]\n\n        \"\"\"\n        ##################################\n        ans = [ans]\n        得到ans=[ array(num_people,17,5),]\n        ##################################\n        len(scores)=num_people\n        scores=[ heatpoint1,heatpoint2,...,heatpoint_numpeople ]\n        ##########################################################\n        \"\"\"\n        return ans, scores\n\n\n\n\n\n", "meta": {"hexsha": "c49ff533e83dcb24c81dd3e51b434b0e4029587a", "size": 23830, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/core/group.py", "max_stars_repo_name": "MingheWang/HigherHRNet-Human-Pose-Estimation", "max_stars_repo_head_hexsha": "65bf3a5654999d5349c1103e43334118bda136c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-17T19:01:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-17T19:01:30.000Z", "max_issues_repo_path": "lib/core/group.py", "max_issues_repo_name": "MingheWang/HigherHRNet-Human-Pose-Estimation", "max_issues_repo_head_hexsha": "65bf3a5654999d5349c1103e43334118bda136c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/core/group.py", "max_forks_repo_name": "MingheWang/HigherHRNet-Human-Pose-Estimation", "max_forks_repo_head_hexsha": "65bf3a5654999d5349c1103e43334118bda136c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5272108844, "max_line_length": 508, "alphanum_fraction": 0.4315568611, "include": true, "reason": "import numpy", "num_tokens": 7697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19131846660970886}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nContains helper code for running spatial nulls models\n\"\"\"\n\nfrom pathlib import Path\nimport warnings\n\nimport numpy as np\nfrom scipy import optimize, spatial\ntry:  # scipy >= 1.8.0\n    from scipy.ndimage._measurements import _stats, labeled_comprehension\nexcept ImportError:  # scipy < 1.8.0\n    from scipy.ndimage.measurements import _stats, labeled_comprehension\nfrom sklearn.utils.validation import check_random_state\n\nfrom neuromaps.images import load_gifti, PARCIGNORE\nfrom neuromaps.points import _geodesic_parcel_centroid\n\n\ndef load_spins(fn, n_perm=None):\n    \"\"\"\n    Loads spins from `fn`\n\n    Parameters\n    ----------\n    fn : os.PathLike\n        Filepath to file containing spins to load\n    n_perm : int, optional\n        Number of spins to retain (i.e., subset data)\n\n    Returns\n    -------\n    spins : (N, P) array_like\n        Loaded spins\n    \"\"\"\n\n    try:\n        npy = Path(fn).with_suffix('.npy')\n        if npy.exists():\n            spins = np.load(npy, allow_pickle=False, mmap_mode='c')\n        else:\n            spins = np.loadtxt(fn, delimiter=',', dtype='int32')\n    except TypeError:\n        spins = np.asarray(fn, dtype='int32')\n\n    if n_perm is not None:\n        spins = spins[..., :n_perm]\n\n    return spins\n\n\ndef get_parcel_centroids(surfaces, parcellation=None, method='surface',\n                         drop=None):\n    \"\"\"\n    Returns vertex coordinates corresponding to parcel centroids\n\n    If `parcellation` is not specified then returned `centroids` are vertex\n    coordinates of `surfaces`\n\n    Parameters\n    ----------\n    surfaces : (2,) list-of-str\n        Surfaces on which to compute parcel centroids; generally spherical\n        surfaces are recommended. Surfaces should be (left, right) hemisphere.\n        If no parcellations are provided then returned `centroids` represent\n        all vertices in `surfaces`\n    parcellation : (2,) list-of-str, optional\n        Path to GIFTI label files containing labels of parcels on the\n        (left, right) hemisphere. If not specified then vertex coordinates from\n        `surfaces` are returned instead. Default: None\n    method : {'average', 'surface', 'geodesic'}, optional\n        Method for calculation of parcel centroid. See Notes for more\n        information. Default: 'surface'\n    drop : list, optional\n        Specifies regions in `parcellation` for which the parcel centroid\n        should not be calculated. If not specified, centroids for parcels\n        defined in `PARCIGNORE` are not calculated. Default: None\n\n    Returns\n    -------\n    centroids : (N, 3) numpy.ndarray\n        Coordinates of parcel centroids. If `parcellation` is not specified\n        these are simply the vertex coordinates\n    hemiid : (N,) numpy.ndarray\n        Array denoting hemisphere designation of coordinates in `centroids`,\n        where `hemiid=0` denotes the left and `hemiid=1` the right hemisphere\n\n    Notes\n    -----\n    The following methods can be used for finding parcel centroids:\n\n    1. ``method='average'``\n\n       Uses the arithmetic mean of the coordinates for the vertices in each\n       parcel. Note that in this case the calculated centroids will not act\n       actually fall on the surface of `surf`.\n\n    2. ``method='surface'``\n\n       Calculates the 'average' coordinates and then finds the closest vertex\n       on `surf`, where closest is defined as the vertex with the minimum\n       Euclidean distance.\n\n    3. ``method='geodesic'``\n\n       Uses the coordinates of the vertex with the minimum average geodesic\n       distance to all other vertices in the parcel. Note that this is slightly\n       more time-consuming than the other two methods, especially for\n       high-resolution meshes.\n    \"\"\"\n\n    methods = ['average', 'surface', 'geodesic']\n    if method not in methods:\n        raise ValueError('Provided method for centroid calculation {} is '\n                         'invalid. Must be one of {}'.format(methods, methods))\n\n    if drop is None:\n        drop = PARCIGNORE\n    if parcellation is None:\n        parcellation = (None, None)\n\n    centroids, hemiid = [], []\n    for n, (parc, surf) in enumerate(zip(parcellation, surfaces)):\n        vertices, faces = load_gifti(surf).agg_data()\n        if parc is not None:\n            labels = load_gifti(parc).agg_data()\n            labeltable = parc.labeltable.get_labels_as_dict()\n\n            for lab in np.unique(labels):\n                if labeltable.get(lab) in drop:\n                    continue\n\n                mask = labels == lab\n                if method in ('average', 'surface'):\n                    roi = np.atleast_2d(vertices[mask].mean(axis=0))\n                    if method == 'surface':  # find closest vertex on surf\n                        idx = np.argmin(spatial.distance_matrix(vertices, roi),\n                                        axis=0)[0]\n                        roi = vertices[idx]\n                elif method == 'geodesic':\n                    inds, = np.where(mask)\n                    roi = _geodesic_parcel_centroid(vertices, faces, inds)\n\n                centroids.append(roi)\n                hemiid.append(n)\n        else:\n            centroids.append(vertices)\n            hemiid.extend([n] * len(vertices))\n\n    return np.row_stack(centroids), np.asarray(hemiid)\n\n\ndef _gen_rotation(seed=None):\n    \"\"\"\n    Generates random matrix for rotating spherical coordinates\n\n    Parameters\n    ----------\n    seed : {int, np.random.RandomState instance, None}, optional\n        Seed for random number generation\n\n    Returns\n    -------\n    rotate_{l,r} : (3, 3) numpy.ndarray\n        Rotations for left and right hemisphere coordinates, respectively\n    \"\"\"\n\n    rs = check_random_state(seed)\n\n    # for reflecting across Y-Z plane\n    reflect = np.array([[-1, 0, 0], [0, 1, 0], [0, 0, 1]])\n\n    # generate rotation for left\n    rotate_l, temp = np.linalg.qr(rs.normal(size=(3, 3)))\n    rotate_l = rotate_l @ np.diag(np.sign(np.diag(temp)))\n    if np.linalg.det(rotate_l) < 0:\n        rotate_l[:, 0] = -rotate_l[:, 0]\n\n    # reflect the left rotation across Y-Z plane\n    rotate_r = reflect @ rotate_l @ reflect\n\n    return rotate_l, rotate_r\n\n\ndef gen_spinsamples(coords, hemiid, n_rotate=1000, check_duplicates=True,\n                    method='original', seed=None, verbose=False,\n                    return_cost=False):\n    \"\"\"\n    Returns a resampling array for `coords` obtained from rotations / spins\n\n    Using the method initially proposed in [ST1]_ (and later modified + updated\n    based on findings in [ST2]_ and [ST3]_), this function applies random\n    rotations to the user-supplied `coords` in order to generate a resampling\n    array that preserves its spatial embedding. Rotations are generated for one\n    hemisphere and mirrored for the other (see `hemiid` for more information).\n\n    Due to irregular sampling of `coords` and the randomness of the rotations\n    it is possible that some \"rotations\" may resample with replacement (i.e.,\n    will not be a true permutation). The likelihood of this can be reduced by\n    either increasing the sampling density of `coords` or changing the\n    ``method`` parameter (see Notes for more information on the latter).\n\n    Parameters\n    ----------\n    coords : (N, 3) array_like\n        X, Y, Z coordinates of `N` nodes/parcels/regions/vertices defined on a\n        sphere\n    hemiid : (N,) array_like\n        Array denoting hemisphere designation of coordinates in `coords`, where\n        values should be {0, 1} denoting the different hemispheres. Rotations\n        are generated for one hemisphere and mirrored across the y-axis for the\n        other hemisphere.\n    n_rotate : int, optional\n        Number of rotations to generate. Default: 1000\n    check_duplicates : bool, optional\n        Whether to check for and attempt to avoid duplicate resamplings. A\n        warnings will be raised if duplicates cannot be avoided. Setting to\n        True may increase the runtime of this function! Default: True\n    method : {'original', 'vasa', 'hungarian'}, optional\n        Method by which to match non- and rotated coordinates. Specifying\n        'original' will use the method described in [ST1]_. Specfying 'vasa'\n        will use the method described in [ST4]_. Specfying 'hungarian' will use\n        the Hungarian algorithm to minimize the global cost of reassignment\n        (will dramatically increase runtime). Default: 'original'\n    seed : {int, np.random.RandomState instance, None}, optional\n        Seed for random number generation. Default: None\n    verbose : bool, optional\n        Whether to print occasional status messages. Default: False\n    return_cost : bool, optional\n        Whether to return cost array (specified as Euclidean distance) for each\n        coordinate for each rotation Default: True\n\n    Returns\n    -------\n    spinsamples : (N, `n_rotate`) numpy.ndarray\n        Resampling matrix to use in permuting data based on supplied `coords`.\n    cost : (N, `n_rotate`,) numpy.ndarray\n        Cost (specified as Euclidean distance) of re-assigning each coordinate\n        for every rotation in `spinsamples`. Only provided if `return_cost` is\n        True.\n\n    Notes\n    -----\n    By default, this function uses the minimum Euclidean distance between the\n    original coordinates and the new, rotated coordinates to generate a\n    resampling array after each spin. Unfortunately, this can (with some\n    frequency) lead to multiple coordinates being re-assigned the same value:\n\n        >>> from neuromaps.nulls.spins import gen_spinsamples\n        >>> coords = [[0, 0, 1], [1, 0, 0], [0, 0, 1], [1, 0, 0]]\n        >>> hemi = [0, 0, 1, 1]\n        >>> gen_spinsamples(coords, hemi, n_rotate=1, seed=1,\n        ...                 check_duplicates=False)\n        array([[0],\n               [0],\n               [2],\n               [3]])\n\n    While this is reasonable in most circumstances, if you feel incredibly\n    strongly about having a perfect \"permutation\" (i.e., all indices appear\n    once and exactly once in the resampling), you can set the ``method``\n    parameter to either 'vasa' or 'hungarian':\n\n        >>> gen_spinsamples(coords, hemi, n_rotate=1, seed=1,\n        ...                 method='vasa', check_duplicates=False)\n        array([[1],\n               [0],\n               [2],\n               [3]])\n        >>> gen_spinsamples(coords, hemi, n_rotate=1, seed=1,\n        ...                 method='hungarian', check_duplicates=False)\n        array([[0],\n               [1],\n               [2],\n               [3]])\n\n    Note that setting this parameter may increase the runtime of the function\n    (especially for `method='hungarian'`). Refer to [ST1]_ for information on\n    why the default suffices in most cases.\n\n    For the original MATLAB implementation of this function refer to [ST5]_.\n\n    References\n    ----------\n    .. [ST1] Alexander-Bloch, A., Shou, H., Liu, S., Satterthwaite, T. D.,\n       Glahn, D. C., Shinohara, R. T., Vandekar, S. N., & Raznahan, A. (2018).\n       On testing for spatial correspondence between maps of human brain\n       structure and function. NeuroImage, 178, 540-51.\n\n    .. [ST2] Blaser, R., & Fryzlewicz, P. (2016). Random Rotation Ensembles.\n       Journal of Machine Learning Research, 17(4), 1–26.\n\n    .. [ST3] Lefèvre, J., Pepe, A., Muscato, J., De Guio, F., Girard, N.,\n       Auzias, G., & Germanaud, D. (2018). SPANOL (SPectral ANalysis of Lobes):\n       A Spectral Clustering Framework for Individual and Group Parcellation of\n       Cortical Surfaces in Lobes. Frontiers in Neuroscience, 12, 354.\n\n    .. [ST4] Váša, F., Seidlitz, J., Romero-Garcia, R., Whitaker, K. J.,\n       Rosenthal, G., Vértes, P. E., ... & Jones, P. B. (2018). Adolescent\n       tuning of association cortex in human structural brain networks.\n       Cerebral Cortex, 28(1), 281-294.\n\n    .. [ST5] https://github.com/spin-test/spin-test\n    \"\"\"\n\n    methods = ['original', 'vasa', 'hungarian']\n    if method not in methods:\n        raise ValueError('Provided method \"{}\" invalid. Must be one of {}.'\n                         .format(method, methods))\n\n    seed = check_random_state(seed)\n\n    coords = np.asanyarray(coords)\n    hemiid = np.squeeze(np.asanyarray(hemiid, dtype='int8'))\n\n    # check supplied coordinate shape\n    if coords.shape[-1] != 3 or coords.squeeze().ndim != 2:\n        raise ValueError('Provided `coords` must be of shape (N, 3), not {}'\n                         .format(coords.shape))\n\n    # ensure hemisphere designation array is correct\n    if hemiid.ndim != 1:\n        raise ValueError('Provided `hemiid` array must be one-dimensional.')\n    if len(coords) != len(hemiid):\n        raise ValueError('Provided `coords` and `hemiid` must have the same '\n                         'length. Provided lengths: coords = {}, hemiid = {}'\n                         .format(len(coords), len(hemiid)))\n    if np.max(hemiid) > 1 or np.min(hemiid) < 0:\n        raise ValueError('Hemiid must have values in {0, 1} denoting left and '\n                         'right hemisphere coordinates, respectively. '\n                         + 'Provided array contains values: {}'\n                         .format(np.unique(hemiid)))\n\n    # empty array to store resampling indices\n    spinsamples = np.zeros((len(coords), n_rotate), dtype=int)\n    cost = np.zeros((len(coords), n_rotate))\n    inds = np.arange(len(coords), dtype=int)\n\n    # generate rotations and resampling array!\n    msg, warned = '', False\n    for n in range(n_rotate):\n        count, duplicated = 0, True\n\n        if verbose:\n            msg = 'Generating spin {:>5} of {:>5}'.format(n, n_rotate)\n            print(msg, end='\\r', flush=True)\n\n        while duplicated and count < 500:\n            count, duplicated = count + 1, False\n            resampled = np.zeros(len(coords), dtype='int32')\n\n            # rotate each hemisphere separately\n            for h, rot in enumerate(_gen_rotation(seed=seed)):\n                hinds = (hemiid == h)\n                coor = coords[hinds]\n                if len(coor) == 0:\n                    continue\n\n                # if we need an \"exact\" mapping (i.e., each node needs to be\n                # assigned EXACTLY once) then we have to calculate the full\n                # distance matrix which is a nightmare with respect to memory\n                # for anything that isn't parcellated data.\n                # that is, don't do this with vertex coordinates!\n                if method == 'vasa':\n                    dist = spatial.distance_matrix(coor, coor @ rot)\n                    # min of max a la Vasa et al., 2018\n                    col = np.zeros(len(coor), dtype='int32')\n                    for r in range(len(dist)):\n                        # find parcel whose closest neighbor is farthest away\n                        # overall; assign to that\n                        row = dist.min(axis=1).argmax()\n                        col[row] = dist[row].argmin()\n                        cost[inds[hinds][row], n] = dist[row, col[row]]\n                        # set to -inf and inf so they can't be assigned again\n                        dist[row] = -np.inf\n                        dist[:, col[row]] = np.inf\n                # optimization of total cost using Hungarian algorithm. this\n                # may result in certain parcels having higher cost than with\n                # `method='vasa'` but should always result in the total cost\n                # being lower #tradeoffs\n                elif method == 'hungarian':\n                    dist = spatial.distance_matrix(coor, coor @ rot)\n                    row, col = optimize.linear_sum_assignment(dist)\n                    cost[hinds, n] = dist[row, col]\n                # if nodes can be assigned multiple targets, we can simply use\n                # the absolute minimum of the distances (no optimization\n                # required) which is _much_ lighter on memory\n                # huge thanks to https://stackoverflow.com/a/47779290 for this\n                # memory-efficient method\n                elif method == 'original':\n                    dist, col = spatial.cKDTree(coor @ rot).query(coor, 1)\n                    cost[hinds, n] = dist\n\n                resampled[hinds] = inds[hinds][col]\n\n            # if we want to check for duplicates ensure that we don't have any\n            if check_duplicates:\n                if np.any(np.all(resampled[:, None] == spinsamples[:, :n], 0)):\n                    duplicated = True\n                # if our \"spin\" is identical to the input then that's no good\n                elif np.all(resampled == inds):\n                    duplicated = True\n\n        # if we broke out because we tried 500 rotations and couldn't generate\n        # a new one, warn that we're using duplicate rotations and give up.\n        # this should only be triggered if check_duplicates is set to True\n        if count == 500 and not warned:\n            warnings.warn('Duplicate rotations used. Check resampling array '\n                          'to determine real number of unique permutations.')\n            warned = True\n\n        spinsamples[:, n] = resampled\n\n    if verbose:\n        print(' ' * len(msg) + '\\b' * len(msg), end='', flush=True)\n\n    if return_cost:\n        return spinsamples, cost\n\n    return spinsamples\n\n\ndef spin_parcels(surfaces, parcellation, method='surface', n_rotate=1000,\n                 spins=None, verbose=False, **kwargs):\n    \"\"\"\n    Rotates parcels in `parcellation` and re-assigns based on maximum overlap\n\n    Vertex labels are rotated and a new label is assigned to each *parcel*\n    based on the region maximally overlapping with its boundaries.\n\n    Parameters\n    ----------\n    surfaces : (2,) list-of-str\n        Surfaces to use for rotating parcels; generally spherical surfaces\n        are recommended. Surfaces should be (left, right) hemisphere\n    parcellation : (2,) list-of-str, optional\n        Path to GIFTI label files containing parcel labels on the (left, right)\n        hemisphere of `surfaces`\n    n_rotate : int, optional\n        Number of rotations to generate. Default: 1000\n    spins : array_like, optional\n        Pre-computed spins to use instead of generating them on the fly. If not\n        provided will use other provided parameters to create them. Default:\n        None\n    seed : {int, np.random.RandomState instance, None}, optional\n        Seed for random number generation. Default: None\n    verbose : bool, optional\n        Whether to print occasional status messages. Default: False\n    return_cost : bool, optional\n        Whether to return cost array (specified as Euclidean distance) for each\n        coordinate for each rotation. Default: True\n    kwargs : key-value pairs\n        Keyword arguments passed to :func:`~.gen_spinsamples`\n\n    Returns\n    -------\n    spinsamples : (N, `n_rotate`) numpy.ndarray\n        Resampling matrix to use in permuting data parcellated with labels from\n        `parcellation`, where `N` is the number of parcels. Indices of -1\n        indicate that the parcel was completely encompassed by regions in\n        `drop` and should be ignored.\n    \"\"\"\n\n    def overlap(vals):\n        \"\"\" Returns most common positive value in `vals`; -1 if all negative\n        \"\"\"\n        vals = np.asarray(vals)\n        vals, counts = np.unique(vals[vals > 0], return_counts=True)\n        try:\n            return vals[counts.argmax()] - 1\n        except ValueError:\n            return -1\n\n    # get vertex-level labels (set drop labels to - values)\n    vertices = np.hstack([\n        load_gifti(parc).agg_data() for parc in parcellation\n    ])\n    labels = np.unique(vertices)\n    mask = labels != 0\n\n    # get spins + cost (if requested)\n    if spins is None:\n        coords, hemiid = get_parcel_centroids(surfaces, method=method)\n        spins = gen_spinsamples(coords, hemiid, n_rotate=n_rotate,\n                                verbose=verbose, **kwargs)\n        if kwargs.get('return_cost'):\n            spins, cost = spins\n    spins = load_spins(spins)\n\n    if len(vertices) != len(spins):\n        raise ValueError('Provided annotation files have a different '\n                         'number of vertices than the specified fsaverage '\n                         'surface.\\n    ANNOTATION: {} vertices\\n     '\n                         'FSAVERAGE:  {} vertices'\n                         .format(len(vertices), len(spins)))\n\n    # spin and assign regions based on max overlap\n    regions = np.zeros((len(labels[mask]), n_rotate), dtype='int32')\n    for n in range(n_rotate):\n        if verbose:\n            msg = f'Calculating parcel overlap: {n:>5}/{n_rotate}'\n            print(msg, end='\\b' * len(msg), flush=True)\n        regions[:, n] = labeled_comprehension(vertices[spins[:, n]], vertices,\n                                              labels, overlap, int, -1)[mask]\n\n    if kwargs.get('return_cost'):\n        return regions, cost\n\n    return regions\n\n\ndef parcels_to_vertices(data, parcellation):\n    \"\"\"\n    Projects parcellated `data` to vertices as defined by `parcellation`\n\n    Parameters\n    ----------\n    data : (N,) numpy.ndarray\n        Parcellated data to be projected to vertices\n    parcellation : tuple-of-str or os.PathLike\n        Filepaths to parcellation images to project `data` to vertices\n\n    Reurns\n    ------\n    projected : numpy.ndarray\n        Vertex-level data\n    \"\"\"\n\n    data = np.vstack(data).astype(float)\n    vertices = np.hstack([\n        load_gifti(parc).agg_data() for parc in parcellation\n    ])\n    expected = np.unique(vertices)[1:].size\n    n_vert = vertices.shape[0]\n    if expected != len(data):\n        raise ValueError('Number of parcels in provided annotation files '\n                         'differs from size of parcellated data array.\\n'\n                         '    EXPECTED: {} parcels\\n'\n                         '    RECEIVED: {} parcels'\n                         .format(expected, len(data)))\n\n    projected = np.zeros((n_vert, data.shape[-1]), dtype=data.dtype)\n    n_vert = 0\n    for parc in parcellation:\n        labels = load_gifti(parc).agg_data().astype('int')\n        currdata = np.append([[np.nan]], data, axis=0)\n        projected[n_vert:n_vert + len(labels), :] = currdata[labels, :]\n        n_vert += len(labels)\n\n    return np.squeeze(projected)\n\n\ndef vertices_to_parcels(data, parcellation):\n    \"\"\"\n    Reduces vertex-level `data` to parcels defined by `parcellation`\n\n    Takes average of vertices within each parcel (excluding NaN values).\n    Assigns NaN to parcels for which *all* vertices are NaN.\n\n    Parameters\n    ----------\n    data : (N,) numpy.ndarray\n        Vertex-level data to be reduced to parcels\n    parcellation : tuple-of-str or os.PathLike\n        Filepaths to parcellation images to parcellate `data`\n\n    Reurns\n    ------\n    reduced : numpy.ndarray\n        Parcellated `data`\n    \"\"\"\n\n    data = np.vstack(data)\n    vertices = np.hstack([\n        load_gifti(parc).agg_data() for parc in parcellation\n    ])\n    n_parc = np.unique(vertices).size\n    expected = vertices.shape[0]\n    if expected != len(data):\n        raise ValueError('Number of vertices in provided annotation files '\n                         'differs from size of vertex-level data array.\\n'\n                         '    EXPECTED: {} vertices\\n'\n                         '    RECEIVED: {} vertices'\n                         .format(expected, len(data)))\n\n    numerator = np.zeros((n_parc, data.shape[-1]), dtype=data.dtype)\n    denominator = np.zeros((n_parc, data.shape[-1]), dtype=data.dtype)\n    start = end = 0\n    for parc in parcellation:\n        labels = load_gifti(parc).agg_data().astype('int')\n        indices = np.unique(labels)\n        end += len(labels)\n\n        for idx in range(data.shape[-1]):\n            currdata = np.squeeze(data[start:end, idx])\n            counts, sums = _stats(np.nan_to_num(currdata), labels, indices)\n            _, nacounts = _stats(np.isnan(currdata), labels, indices)\n            counts = (np.asanyarray(counts, dtype=float)\n                      - np.asanyarray(nacounts, dtype=float))\n\n            numerator[indices, idx] += sums\n            denominator[indices, idx] += counts\n\n        start = end\n\n    with np.errstate(divide='ignore', invalid='ignore'):\n        reduced = np.squeeze(numerator / denominator)[1:]\n\n    return reduced\n\n\ndef spin_data(data, surfaces, parcellation, method='surface', n_rotate=1000,\n              spins=None, verbose=False, **kwargs):\n    \"\"\"\n    Projects parcellated `data` to `surfaces`, rotates, and re-parcellates\n\n    Projection of `data` to `surfaces` uses provided `parcellation` files.\n    Re-parcellated data will not be exactly identical to original values due to\n    re-averaging process. Parcels subsumed by regions in `drop` will be listed\n    as NaN.\n\n    Parameters\n    ----------\n    data : (N,) numpy.ndarray\n        Parcellated data to be rotated. Parcels should be ordered by [left,\n        right] hemisphere; ordering within hemisphere should correspond to the\n        provided `parcellation` files.\n    surfaces : (2,) list-of-str\n        Surfaces to use for rotating parcels; generally spherical surfaces\n        are recommended. Surfaces should be (left, right) hemisphere\n    parcellation : (2,) list-of-str, optional\n        Path to GIFTI label files containing parcel labels on the (left, right)\n        hemisphere of `surfaces` mapping `data` to vertices in `surfaces`\n    n_rotate : int, optional\n        Number of rotations to generate. Default: 1000\n    spins : array_like, optional\n        Pre-computed spins to use instead of generating them on the fly. If not\n        provided will use other provided parameters to create them. Default:\n        None\n\n    verbose : bool, optional\n        Whether to print occasional status messages. Default: False\n    kwargs : key-value pairs\n        Keyword arguments passed to function used to generate rotations\n\n    Returns\n    -------\n    rotated : (N, `n_rotate`) numpy.ndarray\n        Rotated `data\n    \"\"\"\n\n    # get coordinates and hemisphere designation for spin generation\n    vertices = parcels_to_vertices(data, parcellation)\n\n    if spins is None:\n        coords, hemiid = get_parcel_centroids(surfaces, method=method)\n        spins = gen_spinsamples(coords, hemiid, n_rotate=n_rotate,\n                                verbose=verbose, **kwargs)\n        if kwargs.get('return_cost'):\n            spins, cost = spins\n    spins = load_spins(spins)\n\n    if len(vertices) != len(spins):\n        raise ValueError('Provided parcellation files have a different '\n                         'number of vertices than the specified surfaces.\\n'\n                         '    ANNOTATION: {} vertices\\n'\n                         '     FSAVERAGE: {} vertices'\n                         .format(len(vertices), len(spins)))\n\n    spun = np.zeros(data.shape + (n_rotate,))\n    for n in range(n_rotate):\n        if verbose:\n            msg = f'Reducing vertices to parcels: {n:>5}/{n_rotate}'\n            print(msg, end='\\b' * len(msg), flush=True)\n        spun[..., n] = vertices_to_parcels(vertices[spins[:, n]], parcellation)\n\n    if verbose:\n        print(' ' * len(msg) + '\\b' * len(msg), end='', flush=True)\n\n    if kwargs.get('return_cost'):\n        return spun, cost\n\n    return spun\n", "meta": {"hexsha": "75e5a2eb4c4d95dac1a50cfa3debaa3d8940004c", "size": 27271, "ext": "py", "lang": "Python", "max_stars_repo_path": "neuromaps/nulls/spins.py", "max_stars_repo_name": "VinceBaz/neuromaps", "max_stars_repo_head_hexsha": "6758b53e127d1563fa06eb26bc5f08a4e24ae7e7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "neuromaps/nulls/spins.py", "max_issues_repo_name": "VinceBaz/neuromaps", "max_issues_repo_head_hexsha": "6758b53e127d1563fa06eb26bc5f08a4e24ae7e7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "neuromaps/nulls/spins.py", "max_forks_repo_name": "VinceBaz/neuromaps", "max_forks_repo_head_hexsha": "6758b53e127d1563fa06eb26bc5f08a4e24ae7e7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8116788321, "max_line_length": 79, "alphanum_fraction": 0.6110887023, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19131846660970886}}
{"text": "from pyscf import scf, dft, gto, ao2mo, df, lib, cc\nfrom pyscf.dft.numint import eval_ao, eval_rho\nfrom pyscf.dft.gen_grid import Grids\nfrom pyscf.pbc.tools.pyscf_ase import atoms_from_ase\nimport numpy as np\nimport logging\n\n\nCALC_TYPES = {\n    'RHF'   : scf.hf.RHF,\n    'UHF'   : scf.uhf.UHF,\n    'RKS'   : dft.rks.RKS,\n    'UKS'   : dft.uks.UKS,\n    'CCSD'  : cc.ccsd.CCSD,\n    'UCCSD' : cc.uccsd.UCCSD\n}\n\nSCF_TYPES = {\n    'RHF'  : scf.hf.RHF,\n    'ROHF' : scf.rohf.ROHF,\n    'UHF'  : scf.uhf.UHF,\n    'RKS'  : dft.RKS,\n    'UKS'  : dft.UKS\n}\n\n########################################################\n# BASIC HELPER ROUTINES FOR RUNNING PYSCF CALCULATIONS #\n########################################################\n\ndef mol_from_ase(atoms, basis, spin=0, charge=0):\n    \"\"\"\n    Get a pyscf gto.Mole object from an ase Atoms object (atoms).\n    Assign it the atomic basis set (basis).\n    Return the Mole object.\n    \"\"\"\n    mol = gto.Mole()\n    mol.atom = atoms_from_ase(atoms)\n    mol.basis = basis\n    mol.spin = spin\n    mol.charge = charge\n    mol.build()\n    return mol\n\ndef setup_rks_calc(mol, xc, grid_level=3, vv10=False, **kwargs):\n    \"\"\"\n    Set up a PySCF RKS calculation with sensible defaults.\n    \"\"\"\n    rks = dft.RKS(mol)\n    rks.xc = xc\n    rks.grids.level = grid_level\n    rks.grids.build()\n    logging.warning('xc: {}, grid level: {}'.format(xc, grid_level))\n    if vv10:\n        logging.warning('Using VV10 in UKS setup')\n        rks.nlc = 'VV10'\n        if np.array([gto.charge(mol.atom_symbol(i)) <= 18 for i in range(mol.natm)]).all():\n            rks.nlcgrids.prune = dft.gen_grid.sg1_prune\n        else:\n            rks.nlcgrids.prune = None\n        rks.nlcgrids.level = 1\n    return rks\n\ndef setup_uks_calc(mol, xc, grid_level=3, vv10=False, **kwargs):\n    \"\"\"\n    Set up a PySCF UKS calculation with sensible defaults.\n    \"\"\"\n    uks = dft.UKS(mol)\n    uks.xc = xc\n    uks.grids.level = grid_level\n    uks.grids.build()\n    logging.warning('xc: {}, grid level: {}'.format(xc, grid_level))\n    if vv10:\n        logging.warning('Using VV10 in UKS setup')\n        uks.nlc = 'VV10'\n        if np.array([gto.charge(mol.atom_symbol(i)) <= 18 for i in range(mol.natm)]).all():\n            uks.nlcgrids.prune = dft.gen_grid.sg1_prune\n        else:\n            uks.nlcgrids.prune = None\n        uks.nlcgrids.level = 1\n    return uks\n\ndef run_scf(mol, calc_type, functional=None, remove_ld=False, dm0=None):\n    \"\"\"\n    Run an SCF calculation on a gto.Mole object (Mole)\n    of a given calc_type in SCF_TYPES. Return the calc object.\n    Note, if RKS or UKS is the calc_type, default functional is used.\n    \"\"\"\n    if not calc_type in SCF_TYPES:\n        raise ValueError('Calculation type must be in {}'.format(list(SCF_TYPES.keys())))\n\n    calc = SCF_TYPES[calc_type](mol)\n    if remove_ld:\n        logging.info(\"Removing linear dependence from overlap matrix\")\n        calc = scf.addons.remove_linear_dep_(calc)\n    if 'KS' in calc_type and functional is not None:\n        calc.xc = functional\n        if 'MN' in functional:\n            logging.info('MN grid level 4')\n            calc.grids.level = 4\n        if functional == 'wB97M_V':\n            logging.info('Using Specialized wB97M-V params')\n            calc.nlc = 'VV10'\n            calc.grids.prune = None\n            calc.grids.level = 4\n            if np.array([gto.charge(mol.atom_symbol(i)) <= 18 for i in range(mol.natm)]).all():\n                calc.nlcgrids.prune = dft.gen_grid.sg1_prune\n            else:\n                calc.nlcgrids.prune = None\n            calc.nlcgrids.level = 1\n\n    calc.kernel(dm0 = dm0)\n    return calc\n\ndef run_cc(hf):\n    \"\"\"\n    Run and return a restricted CCSD calculation on mol,\n    with HF molecular orbital coefficients in the RHF object hf.\n    \"\"\"\n    if type(hf) == SCF_TYPES['RHF']:\n        calc_cls = cc.CCSD\n    elif type(hf) == SCF_TYPES['UHF']:\n        calc_cls = cc.UCCSD\n    else:\n        raise NotImplementedError('HF type {} not supported'.format(type(hf)) +\\\n            '\\nSupported Types: {}'.format(SCF_TYPES['RHF'], SCF_TYPES['UHF']))\n    calc = calc_cls(hf)\n    calc.kernel()\n    return calc\n\n\n\n#############################################\n# HELPER FUNCTIONS FOR THE analyzers MODULE #\n#############################################\n\n\ndef get_grid(mol, level=3):\n    \"\"\"\n    Get the real-space grid of a molecule for numerical integration.\n    \"\"\"\n    grid = Grids(mol)\n    grid.level = level\n    grid.kernel()\n    return grid\n\ndef get_ha_total(rdm1, eeint):\n    return np.sum(np.sum(eeint * rdm1, axis=(2,3)) * rdm1)\n\ndef get_hf_coul_ex_total(mol, hf):\n    rdm1 = hf.make_rdm1()\n    jmat, kmat = hf.get_jk(mol, rdm1)\n    return np.sum(jmat * rdm1) / 2, -np.sum(kmat * rdm1) / 4\n\ndef get_hf_coul_ex_total2(rdm1, jmat, kmat):\n    if len(rdm1.shape) == 2:\n        return np.sum(jmat * rdm1) / 2, -np.sum(kmat * rdm1) / 4\n    else:\n        return np.sum(jmat * np.sum(rdm1, axis=0)) / 2, -np.sum(kmat * rdm1) / 2\n\ndef get_hf_coul_ex_total_unrestricted(mol, hf):\n    rdm1 = hf.make_rdm1()\n    jmat, kmat = hf.get_jk(mol, rdm1)\n    return np.sum(jmat * np.sum(rdm1, axis=0)) / 2, -np.sum(kmat * rdm1) / 2\n\ndef transform_basis_1e(mat, coeff):\n    \"\"\"\n    Transforms the 1-electron matrix mat into the basis\n    described by coeff (with the basis vectors being the columns).\n    To transform AO operator to MO operator, pass mo_coeff.\n    To transform MO operator to AO operator, pass inv(mo_coeff).\n    To transform AO density matrix to MO density matrix, pass inv(transpose(mo_coeff)).\n    To transform MO density matrix to AO density matrix, pass transpose(mo_coeff).\n    \"\"\"\n    if len(coeff.shape) == 2:\n        return np.matmul(coeff.transpose(), np.matmul(mat, coeff))\n    else:\n        if len(coeff) != 2 or len(mat) != 2:\n            raise ValueError('Need two sets of orbitals, two mats for unrestricted case.')\n        part0 = np.matmul(coeff[0].transpose(), np.matmul(mat[0], coeff[0]))\n        part1 = np.matmul(coeff[1].transpose(), np.matmul(mat[1], coeff[1]))\n        return np.array([part0, part1])\n\ndef make_rdm2_from_rdm1(rdm1):\n    \"\"\"\n    For an RHF calculation, return the 2-RDM from\n    a given 1-RDM. Given D2(ijkl)=<psi| i+ k+ l j |psi>,\n    and D(ij)=<psi| i+ j |psi>, then\n    D2(ijkl) = D(ij) * D(kl) - 0.5 * D(lj) * D(ki)\n    \"\"\"\n    rdm1copy = rdm1.copy()\n    part1 = np.einsum('ij,kl->ijkl', rdm1, rdm1copy)\n    part2 = np.einsum('lj,ki->ijkl', rdm1, rdm1copy)\n    return part1 - 0.5 * part2\n\ndef make_rdm2_from_rdm1_unrestricted(rdm1):\n    \"\"\"\n    For a UHF calculation, return the 2-RDM from\n    a given 1-RDM. Given D2(ijkl)=<psi| i+ k+ l j |psi>,\n    and D(ij)=<psi| i+ j |psi>, then:\n    For like spin, D2(ijkl) = D(ij) * D(kl) - D(lj) * D(ki).\n    For opposite spin, D2(ijkl) = D(ij) * D(kl)\n    Return D(uu,ijkl), D(ud,ijkl), D(dd,ijkl)\n    \"\"\"\n    spinparts = []\n    rdm1copy = rdm1.copy()\n    for s in [0,1]:\n        part1 = np.einsum('ij,kl->ijkl', rdm1[s], rdm1copy[s])\n        part2 = np.einsum('lj,ki->ijkl', rdm1[s], rdm1copy[s])\n        spinparts.append(part1 - part2)\n    mixspinpart = np.einsum('ij,kl->ijkl', rdm1[0], rdm1copy[1])\n    return np.array([spinparts[0], mixspinpart, spinparts[1]])\n\ndef get_ao_vals(mol, points):\n    return eval_ao(mol, points)\n\ndef get_mgga_data(mol, grid, rdm1):\n    \"\"\"\n    Get atomic orbital and density data.\n    See eval_ao and eval_rho docs for details.\n    Briefly, returns 0-3 derivatives of the atomic orbitals\n    in ao_data;\n    and the density, first derivatives of density,\n    Laplacian of density, and kinetic energy density\n    in rho_data.\n    \"\"\"\n    ao_data = eval_ao(mol, grid.coords, deriv=3)\n    if len(rdm1.shape) == 2:\n        rho_data = eval_rho(mol, ao_data, rdm1, xctype='mGGA')\n    else:\n        part0 = eval_rho(mol, ao_data, rdm1[0], xctype='mGGA')\n        part1 = eval_rho(mol, ao_data, rdm1[1], xctype='mGGA')\n        rho_data = np.array([part0, part1])\n    return ao_data, rho_data\n\ndef get_tau_and_grad_helper(mol, grid, rdm1, ao_data):\n    \"\"\"\n    Passes the derivatives of the atomic orbitals\n    to eval_rho to get the kinetic energy density and its\n    derivatives. Not sure if this works.\n    \"\"\"\n    # 0 1 2 3 4  5  6  7  8  9\n    # 0 x y z xx xy xz yy yz zz\n    aox = ao_data[[1, 4, 5, 6]]\n    aoy = ao_data[[2, 5, 7, 8]]\n    aoz = ao_data[[3, 6, 8, 9]]\n    tau  = eval_rho(mol, aox, rdm1, xctype='GGA')\n    tau += eval_rho(mol, aoy, rdm1, xctype='GGA')\n    tau += eval_rho(mol, aoz, rdm1, xctype='GGA')\n    return 0.5 * tau\n\ndef get_tau_and_grad(mol, grid, rdm1, ao_data):\n    if len(rdm1.shape) == 2:\n        return get_tau_and_grad_helper(mol, grid, rdm1, ao_data)\n    else:\n        return np.array([get_tau_and_grad_helper(mol, grid, rdm1[0], ao_data),\\\n                        get_tau_and_grad_helper(mol, grid, rdm1[1], ao_data)])\n\ndef get_rho_second_deriv_helper(mol, grid, dm, ao):\n    from pyscf.dft.numint import _contract_rho, _dot_ao_dm\n    from pyscf.dft.gen_grid import make_mask, BLKSIZE\n\n    nao = mol.nao_nr()\n    N = grid.weights.shape[0]\n    non0tab = np.ones(((N+BLKSIZE-1)//BLKSIZE, mol.nbas),\n                         dtype=np.uint8)\n    shls_slice = (0, mol.nbas)\n    ao_loc = mol.ao_loc_nr()\n    c0 = _dot_ao_dm(mol, ao[0], dm, non0tab, shls_slice, ao_loc)\n    c1 = np.zeros((3, N, nao))\n    # 0 1 2 3 4  5  6  7  8  9\n    # 0 x y z xx xy xz yy yz zz\n    # - - - - 0  1  2  3  4  5\n    # - - - - 11 12 13 22 23 33\n    ddrho = np.zeros((6, N))\n    alphas = [0, 0, 0, 1, 1, 2]\n    betas =  [0, 1, 2, 1, 2, 2]\n    for i in range(3):\n        c1[i] = _dot_ao_dm(mol, ao[i+1], dm.T, non0tab, shls_slice, ao_loc)\n    for i in range(6):\n        term1 = _contract_rho(c0, ao[i + 4])\n        term2 = _contract_rho(c1[alphas[i]], ao[betas[i]+1])\n        total = term1 + term2\n        ddrho[i] = total + total.conj()\n    return ddrho\n\ndef get_rho_second_deriv(mol, grid, rdm1, ao_data):\n    if len(rdm1.shape) == 2:\n        return get_rho_second_deriv_helper(mol, grid, rdm1, ao_data)\n    else:\n        return np.array([get_rho_second_deriv_helper(mol, grid, rdm1[0], ao_data),\\\n                        get_rho_second_deriv_helper(mol, grid, rdm1[1], ao_data)])\n\ndef get_vele_mat(mol, points):\n    \"\"\"\n    Return shape (N, nao, nao)\n    \"\"\"\n    auxmol = gto.fakemol_for_charges(points)\n    vele_mat = df.incore.aux_e2(mol, auxmol)\n    return np.ascontiguousarray(np.transpose(vele_mat, axes=(2,0,1)))\n\ndef get_mo_vals(ao_vals, mo_coeff):\n    \"\"\"\n    Args:\n        ao_vals shape (N,nao)\n        mo_coeff shape (nao,nao)\n    Returns\n        shape (N,nao)\n    \"\"\"\n    return np.matmul(ao_vals, mo_coeff)\n\ndef get_mo_vele_mat(vele_mat, mo_coeff):\n    \"\"\"\n    Convert the return value of get_vele_mat to the MO basis.\n    \"\"\"\n    if len(mo_coeff.shape) == 2:\n        return np.matmul(mo_coeff.transpose(),\n            np.matmul(vele_mat, mo_coeff))\n    else:\n        tmp = np.einsum('puv,svj->spuj', vele_mat, mo_coeff)\n        return np.einsum('sui,spuj->spij', mo_coeff, tmp)\n\ndef get_vele_mat_chunks(mol, points, num_chunks, orb_vals, mo_coeff=None):\n    \"\"\"\n    Generate chunks of vele_mat on the fly to reduce memory load.\n    \"\"\"\n    num_pts = points.shape[0]\n    for i in range(num_chunks):\n        start = (i * num_pts) // num_chunks\n        end = ((i+1) * num_pts) // num_chunks\n        auxmol = gto.fakemol_for_charges(points[start:end])\n        orb_vals_chunk = orb_vals[start:end]\n        vele_mat_chunk = df.incore.aux_e2(mol, auxmol)\n        vele_mat_chunk = np.ascontiguousarray(np.transpose(\n                                vele_mat_chunk, axes=(2,0,1)))\n        if mo_coeff is not None:\n            vele_mat_chunk = get_mo_vele_mat(vele_mat_chunk, mo_coeff)\n        yield vele_mat_chunk, orb_vals_chunk\n\ndef get_vele_mat_generator(mol, points, num_chunks, mo_coeff=None):\n    get_generator = lambda orb_vals: get_vele_mat_chunks(mol, points,\n                                num_chunks, orb_vals, mo_coeff)\n    return get_generator\n\ndef get_ha_energy_density(mol, rdm1, vele_mat, ao_vals):\n    \"\"\"\n    Get the classical Hartree energy density on a real-space grid,\n    for a given molecular structure with basis set (mol),\n    for a given 1-electron reduced density matrix (rdm1).\n    Returns the Hartree energy density.\n    \"\"\"\n    if len(rdm1.shape) == 2:\n        Vele = np.einsum('pij,ij->p', vele_mat, rdm1)\n    else:\n        rdm1 = np.array(rdm1)\n        Vele = np.einsum('pij,sij->p', vele_mat, rdm1)\n    rho = eval_rho(mol, ao_vals, rdm1)\n    return 0.5 * Vele * rho\n\ndef get_fx_energy_density(mol, mo_occ, mo_vele_mat, mo_vals):\n    \"\"\"\n    Get the Hartree Fock exchange energy density on a real-space grid,\n    for a given molecular structure with basis set (mol),\n    for a given atomic orbital (AO) 1-electron reduced density matrix (rdm1).\n    Returns the exchange energy density, which is negative.\n    \"\"\"\n    A = mo_occ * mo_vals\n    tmp = np.einsum('pi,pij->pj', A, mo_vele_mat)\n    return -0.25 * np.sum(A * tmp, axis=1)\n\n\n# The following functions are helpers that check whether vele_mat\n# is a numpy array or a generator before passing to the methods\n# above. This allows one to integrate the memory-saving (but slower)\n# chunk-generating approach smoothly.\n\ndef get_ha_energy_density2(mol, rdm1, vele_mat, ao_vals):\n    if isinstance(vele_mat, np.ndarray):\n        return get_ha_energy_density(mol, rdm1, vele_mat, ao_vals)\n    else:\n        ha_energy_density = np.array([])\n        for vele_mat_chunk, orb_vals_chunk in vele_mat(ao_vals):\n            ha_energy_density = np.append(ha_energy_density,\n                                    get_ha_energy_density(mol, rdm1,\n                                        vele_mat_chunk, orb_vals_chunk))\n        return ha_energy_density\n\ndef get_fx_energy_density2(mol, mo_occ, mo_vele_mat, mo_vals):\n    # make sure to test that the grids end up the same\n    if isinstance(mo_vele_mat, np.ndarray):\n        return get_fx_energy_density(mol, mo_occ, mo_vele_mat, mo_vals)\n    else:\n        fx_energy_density = np.array([])\n        for vele_mat_chunk, orb_vals_chunk in mo_vele_mat(mo_vals):\n            fx_energy_density = np.append(fx_energy_density,\n                                    get_fx_energy_density(mol, mo_occ,\n                                        vele_mat_chunk, orb_vals_chunk))\n        return fx_energy_density\n\n\ndef mol_from_dict(mol_dict):\n    for item in ['charge', 'spin', 'symmetry', 'verbose']:\n        if type(mol_dict[item]).__module__ == np.__name__:\n            mol_dict[item] = mol_dict[item].item()\n    mol = gto.mole.unpack(mol_dict)\n    mol.build()\n    return mol\n\ndef get_scf(calc_type, mol, calc_data = None):\n    calc = CALC_TYPES[calc_type](mol)\n    calc.__dict__.update(calc_data)\n    return calc\n\ndef get_ccsd(calc_type, mol, calc_data = None):\n    if calc_type == 'CCSD':\n        hf = scf.hf.RHF(mol)\n    else:\n        hf = scf.uhf.UHF(mol)\n    hf.e_tot = calc_data.pop('e_tot') - calc_data['e_corr']\n    calc = CALC_TYPES[calc_type](hf)\n    calc.__dict__.update(calc_data)\n    return calc\n\ndef load_calc(fname):\n    analyzer_dict = lib.chkfile.load(fname, 'analyzer')\n    mol = mol_from_dict(analyzer_dict['mol'])\n    calc_type = analyzer_dict['calc_type']\n    if 'CCSD' in calc_type:\n        return get_ccsd(calc_type, mol, analyzer_dict['calc']), calc_type\n    else:\n        return get_scf(calc_type, mol, analyzer_dict['calc']), calc_type\n\ndef load_analyzer_data(fname):\n    data_file = os.path.join(dirname, fname)\n    return lib.chkfile.load(data_file, 'analyzer/data')\n\n\n\n\n##################################################\n# HELPER FUNCTIONS FOR COMPUTING DFT INGREDIENTS #\n##################################################\n\n\ndef get_ws_radii(rho):\n    return (3.0 / (4 * np.pi * rho + 1e-16))**(1.0/3)\n\ndef get_gradient_magnitude(rho_data):\n    return np.linalg.norm(rho_data[1:4,:], axis=0)\n\ndef get_normalized_grad(rho, mag_grad):\n    sprefac = 2 * (3 * np.pi * np.pi)**(1.0/3)\n    n43 = rho**(4.0/3)\n    s = mag_grad / (sprefac * n43 + 1e-16)\n    return s\n\ndef get_single_orbital_tau(rho, mag_grad):\n    return mag_grad**2 / (8 * rho + 1e-16)\n\ndef get_uniform_tau(rho):\n    return (3.0/10) * (3*np.pi**2)**(2.0/3) * rho**(5.0/3)\n\ndef get_regularized_tau(tau, tau_w, tau_unif):\n    alpha = (tau - tau_w) / (tau_unif + 1e-4)\n    return alpha**3 / (alpha**2 + 1e-3)\n\ndef get_normalized_tau(tau, tau_w, tau_unif):\n    return (tau - tau_w) / (tau_unif + 1e-16)\n\ndef get_dft_input(rho_data):\n    rho = rho_data[0,:]\n    r_s = get_ws_radii(rho)\n    mag_grad = get_gradient_magnitude(rho_data)\n    s = get_normalized_grad(rho, mag_grad)\n    tau_w = get_single_orbital_tau(rho, mag_grad)\n    tau_unif = get_uniform_tau(rho)\n    alpha = get_regularized_tau(rho_data[5], tau_w, tau_unif)\n    return rho, s, alpha, tau_w, tau_unif\n\ndef get_dft_input2(rho_data):\n    rho = rho_data[0,:]\n    r_s = get_ws_radii(rho)\n    mag_grad = get_gradient_magnitude(rho_data)\n    s = get_normalized_grad(rho, mag_grad)\n    tau_w = get_single_orbital_tau(rho, mag_grad)\n    tau_unif = get_uniform_tau(rho)\n    alpha = get_normalized_tau(rho_data[5], tau_w, tau_unif)\n    return rho, s, alpha, tau_w, tau_unif\n\ndef squish_density(rho_data, coords, weights, alpha):\n    new_coords = coords / alpha\n    new_weights = weights / alpha**3\n    rho_data = rho_data.copy()\n    rho_data[0,:] *= alpha**3\n    rho_data[1:4,:] *= alpha**4\n    rho_data[4:6,:] *= alpha**5\n    return new_coords, new_weights, rho_data\n\ndef squish_tau(tau_data, alpha):\n    tau_data = tau_data.copy()\n    tau_data[0,:] *= alpha**5\n    tau_data[1:4] *= alpha**6\n    return tau_data\n", "meta": {"hexsha": "ede53793a8e56890916db1147c97448128e05d73", "size": 17511, "ext": "py", "lang": "Python", "max_stars_repo_path": "mldftdat/pyscf_utils.py", "max_stars_repo_name": "mir-group/CiderPress", "max_stars_repo_head_hexsha": "bf2b3536e6bd7432645c18dce5a745d63bc9df59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-09-09T06:51:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T09:48:41.000Z", "max_issues_repo_path": "mldftdat/pyscf_utils.py", "max_issues_repo_name": "mir-group/CiderPress", "max_issues_repo_head_hexsha": "bf2b3536e6bd7432645c18dce5a745d63bc9df59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mldftdat/pyscf_utils.py", "max_forks_repo_name": "mir-group/CiderPress", "max_forks_repo_head_hexsha": "bf2b3536e6bd7432645c18dce5a745d63bc9df59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8131212724, "max_line_length": 95, "alphanum_fraction": 0.6190965679, "include": true, "reason": "import numpy", "num_tokens": 5467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19131846660970886}}
{"text": "#########################################################################\n# Dicomifier - Copyright (C) Universite de Strasbourg\n# Distributed under the terms of the CeCILL-B license, as published by\n# the CEA-CNRS-INRIA. Refer to the LICENSE file or to\n# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html\n# for details.\n#########################################################################\n\n\"\"\"\nExtract diffusion-related information from JSON meta-data and convert it to \nother formats. Unless otherwise specified, all b-values extracted from meta-data\nare expressed in :math:`s/m^2` (i.e. SI units).\n\"\"\"\n\nimport base64\nimport binascii\nimport re\n\nimport numpy\n\nfrom .. import dicom_to_nifti\nfrom .. import logger\n\ndef from_standard(data):\n    \"\"\" Extract diffusion gradient direction and b-value from standard DICOM\n        elements (MR Diffusion Sequence).\n    \"\"\"\n    \n    diffusion_data = data[\"MRDiffusionSequence\"]\n    \n    scheme = []\n    for entry in diffusion_data:\n        entry = entry[0]\n        if \"DiffusionBValue\" not in entry:\n            raise Exception(\"Missing b-value\")\n        b_value = entry[\"DiffusionBValue\"][0]\n        # Convert from s/mm^2 to s/m^2\n        b_value *= 1e6\n        \n        if \"DiffusionGradientDirectionSequence\" not in entry:\n            if b_value != 0:\n                raise Exception(\"Missing direction\")\n            else:\n                entry[\"DiffusionGradientDirectionSequence\"] = [{\n                    \"DiffusionGradientOrientation\": [0,0,0]}]\n        direction = entry[\"DiffusionGradientDirectionSequence\"][0]\n        if \"DiffusionGradientOrientation\" not in direction:\n            raise Exception(\"Missing direction\")\n        direction = numpy.array(direction[\"DiffusionGradientOrientation\"])\n        norm = numpy.linalg.norm(direction)\n        if norm > 0:\n            direction /= norm\n        \n        scheme.append((b_value, direction))\n    \n    return scheme\n\ndef from_siemens_csa(data):\n    \"\"\" Extract diffusion gradient direction and b-value from Siemens-specific\n        elements (CSA Image Header Info (0029,xx10)).\n    \"\"\"\n    \n    logger.warning(\n        \"The coordinate system of the gradient direction is unspecified. \"\n        \"Results may be wrong on non-axial images.\")\n    \n    scheme = []\n    \n    # Look for \"SIEMENS CSA HEADER\" private creator and get the concrete tag\n    # of CSA Image Header Info (0029,xx10)\n    element = None\n    for tag, item in data.items():\n        match = re.match(r\"([\\da-f]{4})00([\\da-f]{2})\", tag)\n        if match:\n            try:\n                item = [base64.b64decode(item[0]).decode()]\n            except binascii.Error:\n                pass\n            except UnicodeDecodeError:\n                pass\n            if item[0] == \"SIEMENS CSA HEADER\":\n                element = match.group(1)+match.group(2)+\"10\"\n                break\n    \n    item = data[element]\n    for entry in numpy.ravel(item):\n        siemens_data = dicom_to_nifti.siemens.parse_csa(base64.b64decode(entry))\n        \n        b_value = siemens_data[\"B_value\"][0]\n        # Convert from s/mm^2 to s/m^2\n        b_value *= 1e6\n        \n        direction = siemens_data[\"DiffusionGradientDirection\"]\n        if len(direction) == 0:\n            direction = [0,0,0]\n        norm = numpy.linalg.norm(direction)\n        if norm > 0:\n            direction /= norm\n        \n        scheme.append((b_value, direction))\n    return scheme\n\ndef from_ge_private(data):\n    \"\"\" Extract diffusion gradient direction and b-value from GE-specific\n        elements (0019,xxbb, 0019,xxbc, 0019,xxbd, and 0043,xx39).\n    \"\"\"\n    \n    # Look for \"GEMS_ACQU_01\" and \"GEMS_PARM_01\" private creators and build base\n    # tags.\n    gems_acq = None\n    gems_parm = None\n    for tag, item in sorted(data.items()):\n        if tag[:4] == \"0019\" and tag[-4:-2] == \"00\":\n            if item and item[0] == \"GEMS_ACQU_01\":\n                gems_acq = \"0019\"+tag[-2:]\n        if tag[:4] == \"0043\" and tag[-4:-2] == \"00\":\n            if item and item[0] == \"GEMS_PARM_01\":\n                gems_parm = \"0043\"+tag[-2:]\n        if tag>\"004300ff\" or None not in [gems_acq, gems_parm]:\n            break\n    \n    directions = None\n    if gems_acq is not None:\n        directions = numpy.squeeze(\n            numpy.transpose([data[gems_acq+x] for x in [\"bb\", \"bc\", \"bd\"]]))\n        norm = numpy.maximum(1e-30, numpy.linalg.norm(directions, axis=1))\n        directions /= norm[:,None]\n    \n    b_values = None\n    if gems_parm is not None:\n        b_values = data.get(gems_parm+\"39\")\n        if b_values is not None:\n            b_values = [x[0] for x in b_values]\n    if b_values is None:\n        b_values = [x[0] if x else 0 for x in data.get(\"DiffusionBValue\")]\n    # Convert from s/mm^2 to s/m^2\n    b_values = [x*1e6 for x in b_values]\n    \n    return list(zip(b_values, directions))\n\ndef to_mrtrix(scheme, fd):\n    \"\"\" Save a diffusion scheme in MRtrix format to a file-like object.\n    \"\"\"\n    \n    # https://mrtrix.readthedocs.io/en/latest/concepts/dw_scheme.html\n    # > the direction vectors are assumed to be provided with respect to real \n    # > or scanner coordinates. This is the same convention as is used in the \n    # > DICOM format.\n    # NOTE: DICOM uses *patient* coordinates, not *scanner* coordinates\n    for b_value, direction in scheme:\n        # Convert from s/m^2 to s/mm^2\n        b_value /= 1e6\n        print(*direction, b_value, file=fd)\n\ndef to_fsl(scheme, transform, bvecs_fd, bvals_fd):\n    \"\"\" Save a diffusion scheme in FSL bvecs+bvals format. A reference \n        transform is required as the bvecs are store in image coordinates, not \n        in patient coordinates. This transform must correspond to an \n        image-to-patient transform, e.g. what is stored in the *affine* member\n        of nibabel images.\n    \"\"\"\n    \n    # https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FDT/UserGuide#Diffusion_data_in_FSL\n    # https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FDT/FAQ#What_conventions_do_the_bvecs_use.3F\n    \n    directions = numpy.array([direction for b_value, direction in scheme])\n    # Convert from patient coordinates to image coordinates\n    # WARNING: for highly anisotropic images and non axis-aligned transforms,\n    # this seem to introduce a slight bias in the directions.\n    bvecs = numpy.array([numpy.linalg.inv(transform) @ d for d in directions])\n    \n    if numpy.linalg.det(transform)>0:\n        bvecs[:,0] *= -1\n    \n    bvecs[bvecs == numpy.NZERO] = 0\n    \n    # Re-normalize (not required by FSL)\n    norm = numpy.maximum(1e-20, numpy.linalg.norm(bvecs, axis=1))\n    bvecs /= norm[:,None]\n    for row in bvecs.T:\n        print(*row, file=bvecs_fd)\n    \n    # Convert from s/m^2 to s/mm^2\n    b_values = numpy.array([b_value for b_value, direction in scheme]) / 1e6\n    print(*b_values, file=bvals_fd)\n", "meta": {"hexsha": "8794722504438bf5894296c7cb9a9036508501b7", "size": 6802, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/python/dicomifier/nifti/diffusion.py", "max_stars_repo_name": "DimitriPapadopoulos/dicomifier", "max_stars_repo_head_hexsha": "708e4e1c932f6411200aa010f857823dfcc495f1", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/python/dicomifier/nifti/diffusion.py", "max_issues_repo_name": "DimitriPapadopoulos/dicomifier", "max_issues_repo_head_hexsha": "708e4e1c932f6411200aa010f857823dfcc495f1", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/python/dicomifier/nifti/diffusion.py", "max_forks_repo_name": "DimitriPapadopoulos/dicomifier", "max_forks_repo_head_hexsha": "708e4e1c932f6411200aa010f857823dfcc495f1", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5698924731, "max_line_length": 89, "alphanum_fraction": 0.608056454, "include": true, "reason": "import numpy", "num_tokens": 1715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.37387582277169656, "lm_q1q2_score": 0.19131846660970883}}
{"text": "import sys\n# from bfuncs import *\nfrom math import *\nimport copy\nimport re\nimport numpy\n\nfrom Scientific.Geometry import Vector, isVector, Tensor, isTensor\nfrom Scientific.indexing import index_expression\nfrom Scientific import N\n\nfrom MMTK import *\nfrom MMTK.MoleculeFactory import *\nfrom MMTK.ForceFields import Amber99ForceField\nfrom MMTK import Universe\nfrom MMTK.InternalCoordinates import *\nfrom MMTK.ChemicalObjects import *\n\n\n########################################\n########## AUX FUNCTIONS ###############\n########################################\n\n# START FUNC bsubstr @@@@@\ndef bsubstr(astring, pos, nchar):\n\t\"\"\"Awk substr equivalent\"\"\" \n\tresult = 0;\n\tl = len(astring);\n\tif((pos > 0) & (nchar <= l)):\n\t\tf = pos+nchar-1;\n\t\tif(f <= l):\n\t\t\treturn astring[(pos-1):f];\n\telse:\n\t\treturn result;\n\n# END FUNC   bsubstr @@@@@\n\n\n# START FUNC bsubstr @@@@@\ndef bcontains(basket, apple):\n\t\"\"\"\n\tChecks if apple is in the basket\n\t@basket: container\n\t@basket type: list\n\t@apple: subset\n\t@apple type type: list\n\t@returns 1 if apple is contained in basket\n\t\"\"\"\n\tfound = 0\n\tlapple = len(apple)\n\tlbasket = len(basket)\n\n\tif lapple >= lbasket : return 0\n\n\tfor i in range(lapple) :\n\t\tfound = 0\n\t\tfor j in range(lbasket) :\n\t\t\tif apple[i] == basket[j]:\n\t\t\t\tfound = 1\n\t\t\t\tbreak\n\t\tif found == 0 :\n\t\t\treturn 0\n\n\treturn 1\n\n# START FUNC bdiff @@@@@\ndef bPDBprint_atom(record, name, position):\n\tserial = 1\n\taltLoc = ' '\n\tresName = 'LIG'\n\tchainID = 'X'\n\tresSeq = 1\n\toccupancy = 1.0\n\ttempFactor = 0.0\n\tprint '{0:<6}{1:>5}{2:>4}{3} {4} {5}{6:>4}    {7:8.3f}{8:8.3f}{9:8.3f}  {10:4.2f}{11:6.2f}'.format\\\n\t\t(record, serial, name, altLoc, resName, chainID, resSeq, \\\n\t\tposition.x(), position.y(), position.z(), occupancy, tempFactor)\n# END FUNC   bdiff  @@@@@\n\n\n# START FUNC bisSaturated @@@@@\ndef bisSaturated(element, bonds):\n\t\"\"\"\n\tChecks if an atom is involved in multiple bonds\n\t@element: the atom\n\t@element type: string\n\t@bonds: how many bonds is the atom involved in\n\t@bonds type: integer\n\t@rvalue: difference between the valence and bonds (unsaturated value)\n\t@rtype: integer\n\t\"\"\"\n\tif element == 'C' :\n\t\treturn 4 - bonds\n\telif element == 'Si' :\n\t\treturn 4 - bonds\n\telif element == 'N' :\n\t\treturn 3 - bonds\n\telif element == 'O' :\n\t\treturn 2 - bonds\n\telif element == 'S' :\n\t\treturn 2 - bonds\n\telif element == 'P' :\n\t\treturn 5 - bonds\n\telif element == 'Se' :\n\t\treturn 2 - bonds\n\telse :\n\t\treturn 0\n\n####################################\n########## FUNCTIONS ###############\n####################################\n\ndef anchor(universe):\n\t\"\"\"Anchor a universe\"\"\"\n\tif(universe.numberOfAtoms() >=3):\n\t\t#set anchor atoms indexes\t\n\t\ta1i\t= 0\n\t\tfor i in range(len(universe.atomList()[a1i].bondedTo())):\n\t\t\tfor j in range(len(universe.atomList()[a1i].bondedTo()[i].bondedTo())):\n\t\t\t\tif universe.atomList()[a1i] is not \\\n\t\t\t\t\tuniverse.atomList()[a1i].bondedTo()[i].bondedTo()[j] :\n\t\t\t\t\ta2i = i;\n\t\t\t\t\ta3i = j;\n\t\t\t\t\tbreak\n\t\tprint 'anchor using: ', a1i, a2i, a3i\n\t\t\n\t\tv1 = universe.atomList()[a1i].position();\n\t\tv2 = universe.atomList()[a1i].bondedTo()[a2i].position();\n\t\tv3 = universe.atomList()[a1i].bondedTo()[a2i].bondedTo()[a3i].position();\n\t\n\t\tvT01 = -v1;\n\t\ttra01 = Translation(vT01);\n\t\tuniverse.applyTransformation(tra01);\n\t\n\t\n\t\tx = universe.atomList()[a1i].bondedTo()[a2i].position().x();\n\t\ty = 0;\n\t\tz = universe.atomList()[a1i].bondedTo()[a2i].position().z();\n\t\tvR01 = Vector(x,y,z);\n\t\tvR02 = Vector(1,0,0);\n\t\n\t\tsign = 1.0\n\t\tif ((z > 0) and (x > 0)) or ((z < 0) and (x < 0)):\n\t\t\tsign = -1.0\n\t\t\n\t\trot01 = Rotation(Vector(0,1,0), sign*vR01.angle(vR02));\n\t\tuniverse.applyTransformation(rot01);\n\t\n\t\tv4 = universe.atomList()[a1i].bondedTo()[a2i].position();\n\t\n\t\tsign = -1.0\n\t\tif ((x > 0) and (y > 0)) or ((x < 0) and (y < 0)):\n\t\t\tsign = 1.0\n\t\trot02 = Rotation(Vector(0,0,1), sign*v4.angle(Vector(1,0,0)));\n\t\tuniverse.applyTransformation(rot02);\n\t\n\t\tx = 0;\n\t\ty = universe.atomList()[a1i].bondedTo()[a2i].bondedTo()[a3i].position().y();\n\t\tz = universe.atomList()[a1i].bondedTo()[a2i].bondedTo()[a3i].position().z();\n\t\n\t\tsign = 1.0\n\t\tif ((z > 0) and (y > 0)) or ((z < 0) and (y < 0)):\n\t\t\tsign = -1.0\n\t\n\t\tvR03 = Vector(x,y,z);\n\t\tvR04 = Vector(0,1,0);\n\t\trot03 = Rotation(Vector(1,0,0), sign*vR03.angle(vR04));\n\t\tuniverse.applyTransformation(rot03);\n\t\n\telse:\n\t\tprint \"Molecule too little to be anchored\";\n#--------------------------------------------------\n\n\n\n####################################\n############ CLASSES ###############\n####################################\n\nclass bConvertor():\n\t\"\"\"\n\tConverts from cartesian coordinates\n\tfound in universe to bonds, angles, dihedrals\n\tlists found within self\n\t\"\"\"\n\tdef __init__(self, universe):\n\t\t\"\"\"\n\t\t:param universe: an MMTK universe\n\t\t:type universe: MMTK universe\n\t\t\"\"\"\n\t\t#Variables\n\t\tself.bonds = []\t\t#list of bonds\n\t\tself.angles = []\t#list of angles\n\t\tself.dihedrals = [] #list of dihedrals\n\n\tdef cart2all_internals(self):\n\t\tk = -1\n\t\t# Bonds\n\t\tfor i in universe[0].bonds :\n\t\t\tk += 1;\n\t\t\tx = universe.distance(i.a1, i.a2);\n\t\t\tself.bonds.append([i.a1, i.a2, x]);\n\t\t\n\t\t# Angles\n\t\tk = -1;\n\t\tfor i in self.bonds :\n\t\t\tfor j in self.bonds:\n\t\t\t\tif j != i :\n\t\t\t\t\tif (i[0] == j[0]):\n\t\t\t\t\t\tk += 1;\n\t\t\t\t\t\tx = universe.angle(i[1], i[0], j[1]);\n\t\t\t\t\t\tself.angles.append([[i[1], i[0], i[2]],\\\n\t\t\t\t\t\t\t\t\t\t\t[i[0], j[1], j[2]],\\\n\t\t\t\t\t\t\t\t\t\t \tx]);\n\t\t\t\t\telif (i[0] == j[1]):\n\t\t\t\t\t\tk += 1;\n\t\t\t\t\t\tx = universe.angle(i[1], i[0], j[0]);\n\t\t\t\t\t\tself.angles.append([[i[1], i[0], i[2]],\\\n\t\t\t\t\t\t\t\t\t\t\t[i[0], j[0], j[2]],\\\n\t\t\t\t\t\t\t\t\t\t \tx]);\n\t\t\t\t\telif (i[1] == j[0]):\n\t\t\t\t\t\tk += 1;\n\t\t\t\t\t\tx = universe.angle(i[0], i[1], j[1]);\n\t\t\t\t\t\tself.angles.append([[i[0], i[1], i[2]],\\\n\t\t\t\t\t\t\t\t\t\t\t[i[1], j[1], j[2]],\\\n\t\t\t\t\t\t\t\t\t\t \tx]);\n\t\t\t\t\telif (i[1] == j[1]):\n\t\t\t\t\t\tk += 1;\n\t\t\t\t\t\tx = universe.angle(i[0], i[1], j[0]);\n\t\t\t\t\t\tself.angles.append([[i[0], i[1], i[2]],\\\n\t\t\t\t\t\t\t\t\t\t\t[i[1], j[0], j[2]],\\\n\t\t\t\t\t\t\t\t\t\t \tx]);\n\t\t\n\t\t# Dihedrals\n\t\tk = -1;\n\t\tfor i in self.angles :\n\t\t\tfor j in self.angles:\n\t\t\t\tif j < i :\n\t\t\t\t\tif (i[0] == j[1]) :\n\t\t\t\t\t\tk += 1;\n\t\t\t\t\t\tx = universe.dihedral(j[0][0], j[0][1], j[1][1], i[1][1]);\n\t\t\t\t\t\tself.dihedrals.append([j,i,x])\n\t\t\t\t\tif (i[1] == j[0]) :\n\t\t\t\t\t\tk += 1;\n\t\t\t\t\t\tx = universe.dihedral(i[0][0], i[0][1], i[1][1], j[1][1]);\n\t\t\t\t\t\tself.dihedrals.append([i,j,x])\n\t#---------------------------------------------\n\t\n\tdef print_internals(self):\n\t\t\"\"\"Writes Bonds, Angles & Dihedrals to stdout\"\"\"\n\t\tprint \"Bonds\";\n\t\tfor i in self.bonds :\n\t\t\tprint i;\n\t\tprint \"Angles\";\n\t\tfor i in self.angles :\n\t\t\tprint i\n\t\tprint \"Dihedrals\"\n\t\tfor i in self.dihedrals :\n\t\t\tprint i;\n\t#---------------------------------------------\n\t\n\tdef swap_bond(self, bond):\n\t\t\"\"\"Reverses the atoms order\"\"\"\n\t\t\"\"\"in a [a1,a2,val] type bond\"\"\"\n\t\trbond = copy.deepcopy(bond)\n\t\tx = rbond[0]\n\t\trbond[0] = rbond[1]\n\t\trbond[1] = x\n\t\treturn rbond\n\t#---------------------------------------------\n\t\n\tdef swap_angle(self, angle):\n\t\t\"\"\"Reverses the atoms order in a\"\"\"\n\t\t\"\"\"[[a1,a2,bval], [a2,a3,bval], aval] type angle\"\"\"\n\t\trangle = copy.deepcopy(angle)\n\t\ta1 =  angle[0][0]\n\t\ta2l = angle[0][1]\n\t\tbvall = angle[0][2]\n\t\ta2r = angle[1][0]\n\t\ta3  = angle[1][1]\n\t\tbvalr = angle[1][2]\n\t\t\n\t\trangle[0][0] = a3\n\t\trangle[0][1] = a2r\n\t\trangle[0][2] = bvalr\n\t\trangle[1][0] = a2l\n\t\trangle[1][1] = a1\n\t\trangle[1][2] = bvall\n\t\treturn rangle\n\t#---------------------------------------------\n\t\n\tdef swap_dihe(self, dihe):\n\t\t\"\"\"Reverses the atoms order in a\"\"\"\n\t\t\"\"\"[ [[a1,a2,bv1],[a2l,a3l,bv2l], av1],\"\"\"\n\t\t\"\"\"  [[a2r,a3r,bv2r],[a3,a4,bv3], av2],\"\"\"\n\t\t\"\"\"  dv ] type dihedral angle\"\"\"\n\t\trdihe = copy.deepcopy(dihe)\n\t\n\t\ta1   = dihe[0][0][0]\n\t\ta2   = dihe[0][0][1]\n\t\tbv1  = dihe[0][0][2]\n\t\ta2l  = dihe[0][1][0]\n\t\ta3l  = dihe[0][1][1]\n\t\tbv2l = dihe[0][1][2]\n\t\tav1  = dihe[0][2]\n\t\ta2r  = dihe[1][0][0]\n\t\ta3r  = dihe[1][0][1]\n\t\tbv2r = dihe[1][0][2]\n\t\ta3   = dihe[1][1][0]\n\t\ta4   = dihe[1][1][1]\n\t\tbv3  = dihe[1][1][2]\n\t\tav2  = dihe[1][2]\n\t\n\t\trdihe[0][0][0] = a4\n\t\trdihe[0][0][1] = a3\n\t\trdihe[0][0][2] = bv3\n\t\trdihe[0][1][0] = a3r\n\t\trdihe[0][1][1] = a2r\n\t\trdihe[0][1][2] = bv2r\n\t\trdihe[0][2] = av2\n\t\trdihe[1][0][0] = a3l\n\t\trdihe[1][0][1] = a2l\n\t\trdihe[1][0][2] = bv2l\n\t\trdihe[1][1][0] = a2\n\t\trdihe[1][1][1] = a1\n\t\trdihe[1][1][2] = bv1\n\t\trdihe[1][2] = av1\n\t\treturn rdihe\n\t#---------------------------------------------\n\n\tdef sprint_zmat_dihe(self, dihe):\n\t\t\"\"\"Write dihedral to stdout\"\"\"\n\t\t\"\"\" in Z-matrix format\"\"\"\n\t\ta1   = dihe[0][0][0]\n\t\ta2   = dihe[0][0][1]\n\t\tbv1  = dihe[0][0][2]\n\t\ta2l  = dihe[0][1][0]\n\t\ta3l  = dihe[0][1][1]\n\t\tbv2l = dihe[0][1][2]\n\t\tav1  = dihe[0][2]\n\t\ta2r  = dihe[1][0][0]\n\t\ta3r  = dihe[1][0][1]\n\t\tbv2r = dihe[1][0][2]\n\t\ta3   = dihe[1][1][0]\n\t\ta4   = dihe[1][1][1]\n\t\tbv3  = dihe[1][1][2]\n\t\tav2  = dihe[1][2]\n\t\treturn '{0:>4} {1:>4} {2:>4} {3:>4} {4:>10.6f} {5:>4} {6:>10.6f} {7:>4} {8:>10.6f}'.format(a1.index+1, a1.name, a1.name[0], a2.index+1, bv1*10.0, a3.index+1, av1, a4.index+1, dihe[2])\n\t#---------------------------------------------\n\t\n\t\n\tdef print_zmat_dihe(self, dihe):\n\t\t\"\"\"Write dihedral to stdout\"\"\"\n\t\t\"\"\" in Z-matrix format\"\"\"\n\t\ta1   = dihe[0][0][0]\n\t\ta2   = dihe[0][0][1]\n\t\tbv1  = dihe[0][0][2]\n\t\ta2l  = dihe[0][1][0]\n\t\ta3l  = dihe[0][1][1]\n\t\tbv2l = dihe[0][1][2]\n\t\tav1  = dihe[0][2]\n\t\ta2r  = dihe[1][0][0]\n\t\ta3r  = dihe[1][0][1]\n\t\tbv2r = dihe[1][0][2]\n\t\ta3   = dihe[1][1][0]\n\t\ta4   = dihe[1][1][1]\n\t\tbv3  = dihe[1][1][2]\n\t\tav2  = dihe[1][2]\n\t\tprint '{0:>4} {1:>4} {2:>4} {3:>4} {4:>10.6f} {5:>4} {6:>10.6f} {7:>4} {8:>10.6f}'.format(a1.index+1, a1.name, a1.name[0], a2.index+1, bv1*10.0, a3.index+1, av1, a4.index+1, dihe[2])\n\t#---------------------------------------------\n\n\n\tdef NeRFinte2cart(self, dihe):\t# Needs debug\n\t\t\"\"\"\n\t\tReconstructs atomlist positions\n\t\t2005 Parsons et al - NeRF algorithm\n\t\t:param universe: MMTK universe\n\t\t:type universe: MMTK universe\n\t\t:param dihe: list of dihedrals\n\t\t:type dihe: [[[],[],aval] , [[],[],aval] , dval] where [] is a bond\n\t\t\"\"\"\n\t\tknown_atoms = []\n\t\tunknown_atoms = copy.deepcopy(universe.atomList())\n\t\tC = Vector(0,0,0)\n\t\tD = Vector(0,0,0)\n\t\tD2 = Vector(0,0,0)\n\t\tl = len(dihe)\n\t\tfor di in range(l):\t# Create the START stack\n\t\t\tdihe.append(self.swap_dihe(dihe[di]))\n\t\n\t\t#for i in dihe:\n\t\t#\tprint_zmat_dihe(i)\n\t\n\t\t# Assign initial values\n\t\ti = dihe[0]\n\t\ta1 = i[0][0][0]\n\t\ta2 = i[0][0][1]\n\t\ta3 = i[1][1][0]\n\t\ta4 = i[1][1][1]\n\t\tR1 = i[0][0][2]\n\t\tR2 = i[1][1][2]\n\t\ttheta1 = i[0][2]\n\t\tphi = i[2]\n\t\tuniverse.atomList()[a1.index].setPosition(Vector(0,0,0))\n\t\tuniverse.atomList()[a2.index].setPosition(Vector(R1,0,0))\n\t\tuniverse.atomList()[a3.index].setPosition(Vector(R1-R2*cos(theta1), R2*sin(theta1), 0))\n\t\tknown_atoms.append(a1)\n\t\tknown_atoms.append(a2)\n\t\tknown_atoms.append(a3)\n\t\t#print 'initialize at: ', a1, a2, a3\n\t\t#bPDBprint_atom('HETATM', a1.name, 10*a1.position())\n\t\t#bPDBprint_atom('HETATM', a2.name, 10*a2.position())\n\t\t#bPDBprint_atom('HETATM', a3.name, 10*a3.position())\n\t\t# Main loop\n\t\tcnt=0;\n\t\twhile len(known_atoms) < len(universe.atomList()):\n\t\t\tcnt += 1\n\t\t\tif cnt > 9999:\n\t\t\t\tprint 'NeRFinte2cart() cnt EXCEEDED: 9999'\n\t\t\t\tbreak\n\t\t\tai = -1\n\t\t\tfor a in unknown_atoms:\n\t\t\t\tai += 1\n\t\t\t\tfor i in dihe:\t\t\t\t# Search if atom a is a4 in any dihe\n\t\t\t\t\ta1 = i[0][0][0]\n\t\t\t\t\ta2 = i[0][0][1]\n\t\t\t\t\ta3 = i[1][0][1]\n\t\t\t\t\ta4 = i[1][1][1]\n\t\t\t\t\ta1known = 0\n\t\t\t\t\ta2known = 0\n\t\t\t\t\ta3known = 0\n\t\t\t\t\ta4known = 0\n\t\t\t\t\tif a4.index == a.index:\n\t\t\t\t\t\tfor k in known_atoms:\t# Check if atom is in KNOWN stack\n\t\t\t\t\t\t\tif a4.index == k.index:\n\t\t\t\t\t\t\t\ta4known = 1\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tif a1.index == k.index :\n\t\t\t\t\t\t\t\ta1known = 1\n\t\t\t\t\t\t\tif a2.index == k.index :\n\t\t\t\t\t\t\t\ta2known = 1\n\t\t\t\t\t\t\tif a3.index == k.index :\n\t\t\t\t\t\t\t\ta3known = 1\n\t\t\t\t\t\tif ((a4known == 0) and \\\n\t\t\t\t\t\t\t(a1known == 1) and (a2known == 1) and (a3known == 1)):\n\t\t\t\t\t\t\t\t# Move everything so that a3 is in the center\n\t\t\t\t\t\t\t\tM = Translation(-1*a3.position())\n\t\t\t\t\t\t\t\tuniverse.applyTransformation(M)\n\t\t\t\t\t\t\t\tfor k in known_atoms:\n\t\t\t\t\t\t\t\t\tM(k.position())\n\t\t\t\t\t\t\t\t# Solve a4\n\t\t\t\t\t\t\t\t#print 'SOLVE: ', a4\n\t\t\t\t\t\t\t\tprint_zmat_dihe(i)\n\t\t\t\t\t\t\t\tA = a1.position()\n\t\t\t\t\t\t\t\tB = a2.position()\n\t\t\t\t\t\t\t\tC = a3.position()\n\t\t\t\t\t\t\t\t#print 'A = ', A, '(', a1.name , ')'\n\t\t\t\t\t\t\t\t#print 'B = ', B, '(', a2.name , ')'\n\t\t\t\t\t\t\t\t#print 'C = ', C, '(', a3.name , ')'\n\t\t\t\t\t\t\t\tR = i[1][1][2]\n\t\t\t\t\t\t\t\t#print 'R = ', R\n\t\t\t\t\t\t\t\ttheta = i[1][2]\n\t\t\t\t\t\t\t\tif theta > pi/2:\n\t\t\t\t\t\t\t\t\ttheta = pi - theta\n\t\t\t\t\t\t\t\t#print 'theta = ', theta, numpy.rad2deg(theta)\n\t\t\t\t\t\t\t\tphi = i[2]\n\t\t\t\t\t\t\t\tif phi < 0:\n\t\t\t\t\t\t\t\t\tphi = pi - phi\n\t\t\t\t\t\t\t\t#print 'phi = ', phi, numpy.rad2deg(phi)\n\t\t\t\t\t\t\t\tAB = B - A\t# B - A\n\t\t\t\t\t\t\t\t#print 'AB = ', AB\n\t\t\t\t\t\t\t\tBC = C - B\t# C - B\n\t\t\t\t\t\t\t\t#print 'BC = ', BC\n\t\t\t\t\t\t\t\tbc = BC.normal()\n\t\t\t\t\t\t\t\t#print 'bc = ', bc\n\t\t\t\t\t\t\t\tn = AB.cross(bc)\n\t\t\t\t\t\t\t\tn = n.normal()\n\t\t\t\t\t\t\t\t#print 'n = ', n\n\t\t\t\t\t\t\t\tMx = bc\n\t\t\t\t\t\t\t\t#print 'Mx = ', Mx\n\t\t\t\t\t\t\t\tMy = n.cross(bc)\n\t\t\t\t\t\t\t\tMy = My.normal()\n\t\t\t\t\t\t\t\t#print 'My = ', My\n\t\t\t\t\t\t\t\tMz = n\n\t\t\t\t\t\t\t\t#print 'Mz = ', Mz\n\t\t\t\t\t\t\t\tM = Tensor([ [Mx.x(), Mx.y(), Mx.z()],\\\n\t\t\t\t\t\t\t\t\t\t\t [My.x(), My.y(), My.z()],\\\n\t\t\t\t\t\t\t\t\t\t\t [Mz.x(), Mz.y(), Mz.z()] ])\n\t\t\t\t\t\t\t\t#print 'M: '\n\t\t\t\t\t\t\t\t#print M\n\t\t\t\t\t\t\t\tD2 = Vector(R*cos(theta), R*cos(phi)*sin(theta), R*sin(phi)*sin(theta))\n\t\t\t\t\t\t\t\t#print 'D2: '\n\t\t\t\t\t\t\t\t#print D2\n\t\t\t\t\t\t\t\tD = M*D2\n\t\t\t\t\t\t\t\tD = D + C\n\t\t\t\t\t\t\t\t#print 'D: '\n\t\t\t\t\t\t\t\t#print D\n\t\t\t\t\t\t\t\ta.setPosition(D)\n\t\t\t\t\t\t\t\tuniverse.atomList()[a4.index].setPosition(D)\n\t\t\t\t\t\t\t\t# Add a4 to KNOWN\n\t\t\t\t\t\t\t\tknown_atoms.append(a4)\n\t\t\t\t\t\t\t\tunknown_atoms.pop(ai)\n\t\t\t\t\t\t\t\t#print '========================'\n\t\t\t\t\t\t\t\tbreak\n\t\n\t\tfor k in known_atoms:\n\t\t\tbPDBprint_atom('HETATM', k.name, 10*k.position())\n\t\n\t\n\t# -----------------------------------\n\t\n\t\n\tdef inte2cart(self, dihe):\n\t\t\"\"\"\n\t\tReconstructs atomlist positions\n\t\tClassic\n\t\t:param universe: MMTK universe\n\t\t:type universe: MMTK universe\n\t\t:param dihe: list of dihedrals\n\t\t:type dihe: [[[],[],aval] , [[],[],aval] , dval] where [] is a bond\n\t\t\"\"\"\n\t\tknown_atoms = []\n\t\tunknown_atoms = copy.deepcopy(universe.atomList())\n\t\tC = Vector(0,0,0)\n\t\tD0 = Vector(0,0,0)\n\t\tD1 = Vector(0,0,0)\n\t\tD = Vector(0,0,0)\n\t\tD2 = Vector(0,0,0)\n\t\tl = len(dihe)\n\t\tfor di in range(l):\t# Create the START stack\n\t\t\tdihe.append(self.swap_dihe(dihe[di]))\n\t\n\t\n\t\t# Assign initial values\n\t\ti = dihe[0]\n\t\ta1 = i[0][0][0]\n\t\ta2 = i[0][0][1]\n\t\ta3 = i[1][1][0]\n\t\ta4 = i[1][1][1]\n\t\tR1 = i[0][0][2]\n\t\tR2 = i[1][1][2]\n\t\ttheta1 = i[0][2]\n\t\tphi = i[2]\n\t\tuniverse.atomList()[a1.index].setPosition(Vector(0,0,0))\n\t\tuniverse.atomList()[a2.index].setPosition(Vector(R1,0,0))\n\t\tuniverse.atomList()[a3.index].setPosition(Vector(R1-R2*cos(theta1), R2*sin(theta1), 0))\n\t\tknown_atoms.append(a1)\n\t\tknown_atoms.append(a2)\n\t\tknown_atoms.append(a3)\n\t\n\t\t# Main loop\n\t\tcnt=0;\n\t\twhile len(known_atoms) < len(universe.atomList()):\n\t\t\tcnt += 1\n\t\t\tif cnt > 9999:\n\t\t\t\tprint 'inte2cart() cnt EXCEEDED: 9999'\n\t\t\t\tbreak\n\t\t\tai = -1\n\t\t\tfor a in unknown_atoms:\n\t\t\t\tai += 1\n\t\t\t\tfor i in dihe:\t\t\t\t# Search if atom a is a4 in any dihe\n\t\t\t\t\ta1 = i[0][0][0]\n\t\t\t\t\ta2 = i[0][0][1]\n\t\t\t\t\ta3 = i[1][0][1]\n\t\t\t\t\ta4 = i[1][1][1]\n\t\t\t\t\ta1known = 0\n\t\t\t\t\ta2known = 0\n\t\t\t\t\ta3known = 0\n\t\t\t\t\ta4known = 0\n\t\t\t\t\tif a4.index == a.index:\n\t\t\t\t\t\tfor k in known_atoms:\t# Check if atom is in KNOWN stack\n\t\t\t\t\t\t\tif a4.index == k.index:\n\t\t\t\t\t\t\t\ta4known = 1\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tif a1.index == k.index :\n\t\t\t\t\t\t\t\ta1known = 1\n\t\t\t\t\t\t\tif a2.index == k.index :\n\t\t\t\t\t\t\t\ta2known = 1\n\t\t\t\t\t\t\tif a3.index == k.index :\n\t\t\t\t\t\t\t\ta3known = 1\n\t\t\t\t\t\tif ((a4known == 0) and \\\n\t\t\t\t\t\t\t(a1known == 1) and (a2known == 1) and (a3known == 1)):\n\t\t\t\t\t\t\t\t# Move everything so that a3 is in the center\n\t\t\t\t\t\t\t\tM = Translation(-1*a3.position())\n\t\t\t\t\t\t\t\tuniverse.applyTransformation(M)\n\t\t\t\t\t\t\t\tfor k in known_atoms:\n\t\t\t\t\t\t\t\t\tM(k.position())\n\t\t\t\t\t\t\t\t# Solve a4\n\t\t\t\t\t\t\t\tA = a1.position()\n\t\t\t\t\t\t\t\tB = a2.position()\n\t\t\t\t\t\t\t\tC = a3.position()\n\t\t\t\t\t\t\t\t#print 'SOLVE: ', a4\n\t\t\t\t\t\t\t\tR = i[1][1][2]\n\t\t\t\t\t\t\t\ttheta = pi-i[1][2]\n\t\t\t\t\t\t\t\tphi = i[2]\n\t\t\t\t\t\t\t\tAB = B - A\t# B - A\n\t\t\t\t\t\t\t\tBC = C - B\t# C - B\n\t\t\t\t\t\t\t\tbc = BC.normal()\n\t\t\t\t\t\t\t\tn = AB.cross(bc)\n\t\t\t\t\t\t\t\tn = n.normal()\n\t\t\t\t\t\t\t\tD0 = C + (bc*R)\n\t\t\t\t\t\t\t\tM = Rotation(n, theta)\n\t\t\t\t\t\t\t\tD1 = M(D0)\n\t\t\t\t\t\t\t\tM = Rotation(bc, phi)\n\t\t\t\t\t\t\t\tD = M(D1)\n\t\t\t\t\t\t\t\ta.setPosition(D)\n\t\t\t\t\t\t\t\tuniverse.atomList()[a4.index].setPosition(D)\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t# Add a4 to KNOWN\n\t\t\t\t\t\t\t\tknown_atoms.append(a4)\n\t\t\t\t\t\t\t\tunknown_atoms.pop(ai)\n\t\t\t\t\t\t\t\tbreak\n\t\n\t\tfor k in known_atoms:\n\t\t\tbPDBprint_atom('HETATM', k.name, 10*k.position())\n\t\n\t# -----------------------------------\n\n\nclass bRBSelector():\n\t\"\"\"\n\tFinds and writes rigid bodies as lists\n\t\"\"\"\n\tdef __init__(self, universe, convertor):\n\t\t\"\"\"\n\t\t:param universe: an MMTK universe\n\t\t:type universe: MMTK universe\n\t\t:param bonds: lists of precomputed bonds\n\t\t:type bonds: a list of 3 element lists: [a1,a2,bval]\n\t\t\"\"\"\n\t\t#Variables\n\t\tself.bonds = convertor.bonds\t#\n\t\tself.dihedrals = convertor.dihedrals\n\t\tself.convertor = convertor #\n\t\tself.cnt = 0\t\t#checks if infinite loop\n\t\tself.bibonds = []\t#an element is a bond with an index attached\n\t\tself.bibonds_dict = {}\n\t\tself.wostack = []\t#stack which uses bibonds element types (work)\n\t\tself.rings = []\t\t#stack which uses bibonds element types\t(rings deposit)\n\t\tself.trash = []\t\t#stack which uses bibonds element types (recovery)\n\t\tself.index = 0\t\t#used to identify bonds !not the same as Atom.index\n\t\tself.inbuff = []\t#indexes buffer used in inrings\n\t\tself.inrings = []\t#list of sorted lists of indexes\n\t\tself.buff = []\n\t\tself.conv = 0\n\t\tself.atring = []\t#list of lists of atom indexes in rings\n\t\tself.atbond = []\t#list of 2-tuples atom indexes in rigid bonds\n\t\tself.atatom = []\t#list of 2 tuples [atom, valence]\n\t\tself.atconj = []\t#list of conjugate multiple bonds\n\t\tself.atrb = []\n\t\tself.stickbonds = []\n\n\tdef __getstate__(self):\n\t\treturn self.atring\n\n\tdef findPaths(self):\n\t\t# Fill the START stack (bibonds)\n\t\tself.index = 0\n\t\tfor i in self.bonds :\n\t\t\tself.index += 1\n\t\t\tself.bibonds.append([i, self.index])\n\t\t\tself.bibonds.append([convertor.swap_bond(i), self.index])\n\t\t\tself.bibonds_dict[self.index] = i\n\t\t# Kickstart - put the first element in WORK stack (wostack)\n\t\tself.wostack.append(self.bibonds[-1])\n\t\tself.bibonds.pop()\n\t\t# Main\n\t\twhile True:\n\t\t\tif not self.bibonds:\n\t\t\t\tbreak\n\t\t\telif not self.wostack:\n\t\t\t\tself.wostack.append(self.bibonds[-1])\n\t\t\t\tself.bibonds.pop()\n\t\t\telse:\n\t\t\t\tself.cnt += 1\n\t\t\t\tif self.cnt > (universe.numberOfAtoms()*universe.numberOfAtoms()):\n\t\t\t\t\tprint 'findPaths(): cnt EXCEEDED!'\n\t\t\t\t\tbreak\n\t\t\t\tif not self.wostack:\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tfound_link = 0\n\t\t\t\t\tfor i in range(len(self.bibonds)) :\n\t\t\t\t\t\tif ( (self.wostack[-1][0][1].index == self.bibonds[i][0][0].index) and \\\n\t\t\t\t\t\t\t (self.wostack[-1][1] != self.bibonds[i][1])):\n\t\t\t\t\t\t\tfound_link = 1\n\t\t\t\t\t\t\tself.wostack.append(self.bibonds[i])\n\t\t\t\t\t\t\tself.bibonds.pop(i)\n\t\t\t\t\t\t\t# Check for rings\n\t\t\t\t\t\t\twolen = len(self.wostack)\n\t\t\t\t\t\t\tif(wolen >=3):\n\t\t\t\t\t\t\t\tfor j in range(-3, -1 * wolen, -1) :\n\t\t\t\t\t\t\t\t\t#print 'wostack[',j,']:',wostack[j]\n\t\t\t\t\t\t\t\t\t#Check for circular path\n\t\t\t\t\t\t\t\t\tif ((self.wostack[-1][0][1].index == self.wostack[j][0][0].index) and\\\n\t\t\t\t\t\t\t\t\t\t(self.wostack[-1][1] != self.wostack[j][1])):\n\t\t\t\t\t\t\t\t\t\tself.inbuff = []\n\t\t\t\t\t\t\t\t\t\tfor k in range(wolen+j, wolen):\n\t\t\t\t\t\t\t\t\t\t\tself.inbuff.append(self.wostack[k][1])\n\t\t\t\t\t\t\t\t\t\t#Check if path has two way bonds\n\t\t\t\t\t\t\t\t\t\tbonds_doubled = 0\n\t\t\t\t\t\t\t\t\t\tif len(self.inbuff) > len(set(self.inbuff)) :\n\t\t\t\t\t\t\t\t\t\t\tbonds_doubled = 1\n\t\t\t\t\t\t\t\t\t\t#Check if ring is already in the rings stack\n\t\t\t\t\t\t\t\t\t\tself.inbuff.sort()\n\t\t\t\t\t\t\t\t\t\tring_already_in = 0\n\t\t\t\t\t\t\t\t\t\tfor t in self.inrings :\n\t\t\t\t\t\t\t\t\t\t\tif self.inbuff == t:\n\t\t\t\t\t\t\t\t\t\t\t\tring_already_in = 1\n\t\t\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\t\t#Copy a new ring to rings\n\t\t\t\t\t\t\t\t\t\tif (ring_already_in == 0) and (bonds_doubled == 0):\n\t\t\t\t\t\t\t\t\t\t\tfor k in range(wolen+j, wolen):\n\t\t\t\t\t\t\t\t\t\t\t\tself.rings.append(self.wostack[k])\n\t\t\t\t\t\t\t\t\t\t\tself.inrings.append(self.inbuff)\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tif found_link == 0:\n\t\t\t\t\t\tself.trash.append(self.wostack[-1])\n\t\t\t\t\t\tself.wostack.pop()\n\n\t\t# Prepare a list of names\n\t\ti = 0\n\t\tfor m in self.inrings :\n\t\t\tself.buff = []\n\t\t\tfor n in m :\n\t\t\t\tself.buff.append(self.bibonds_dict[n][0].index)\n\t\t\t\tself.buff.append(self.bibonds_dict[n][1].index)\n\t\t\tself.buff = set(self.buff)\n\t\t\tself.atring.append(list(self.buff))\n\n\t\t# ---------------------------------------------------------------\n\n\tdef check_for_cond_rings(self, bonds, conv) :\n\t\tfor mi in range(len(self.atring)) :\n\t\t\tfor ni in range(len(self.atring)) :\n\t\t\t\tself.buff = []\n\t\t\t\tif bcontains(self.atring[mi], self.atring[ni]) == 1 :\n\t\t\t\t\t# Extract the hidden ring\n\t\t\t\t\tself.buff = list(set(self.atring[mi])-set(self.atring[ni]))\n\t\t\t\t\tbuffbuff = []\n\t\t\t\t\tfor o in self.atring[ni] :\t# closed ring\n\t\t\t\t\t\tfor p in self.buff :\t\t# diff\n\t\t\t\t\t\t\tfound_bond = 0\n\t\t\t\t\t\t\tif (p != o) :\n\t\t\t\t\t\t\t\tfor r in bonds :\n\t\t\t\t\t\t\t\t\tif ( ((r[0].index == o) and (r[1].index == p)) or\\\n\t\t\t\t\t\t\t\t\t\t ((r[1].index == o) and (r[0].index == p)) ):\n\t\t\t\t\t\t\t\t\t\tbuffbuff.append(o)\n\t\t\t\t\t\t\t\t\t\tfound_bond = 1\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tif found_bond == 1 :\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\tfor s in list(set(buffbuff)) :\n\t\t\t\t\t\tself.buff.append(s)\n\t\t\t\t\t\n\t\t\t\t\tself.atring.append(self.buff)\n\t\t\t\t\tself.atring.pop(mi)\n\t\n\t\t\t\t\tc = 0\n\t\t\t\t\tfor zi in (range(len(self.atring))) :\n\t\t\t\t\t\tc += len(self.atring[zi])\n\t\t\t\t\tif c == conv : # check for convergence\n\t\t\t\t\t\treturn\n\t\n\t\t\t\t\tself.check_for_cond_rings( bonds, c)\t#recursivity\n\t\t\t\t\t#break\n\t\n\tdef untangleCondensed(self):\n\t\tself.conv = 0\t#convergence\n\t\tself.check_for_cond_rings(self.bonds, self.conv)\n\t\t# Sort atring\n\t\tfor i in self.atring:\n\t\t\ti.sort()\n\t\tself.atring.sort()\n\n\tdef find_rings(self):\n\t\tself.findPaths()\n\t\tself.untangleCondensed()\n\n\tdef print_atring(self):\n\t\t\"\"\"Prints atring list to stdout\"\"\"\n\t\tif(len(self.atring) > 1) :\n\t\t\tif(self.atring[0] != self.atring[1]) :\n\t\t\t\tprint self.atring[0]\n\t\t\tfor i in range(1,len(self.atring)):\n\t\t\t\tif self.atring[i] != self.atring[i-1] :\n\t\t\t\t\tprint self.atring[i]\n\t\telif (len(self.atring) == 1):\n\t\t\tprint self.atring[0]\n\t\telse:\n\t\t\tprint 'No rings found'\n\t#---------------------------------------------\n\n\tdef print_rings(self):\n\t\t\"\"\"Prints ring atom names to stdout\"\"\"\n\t\tfin_string = \"\"\n\t\tfin_string += 'rings = ['\n\t\tt = 0\n\t\tif(len(self.atring) > 1) :\n\t\t\tif(self.atring[0] != self.atring[1]) :\n\t\t\t\t#print self.atring[0]\n\t\t\t\tif t != 0: fin_string += ', '\n\t\t\t\tt += 1\n\t\t\t\tfin_string += '['\n\t\t\t\tk = 0\n\t\t\t\tfor z in self.atring[0]:\n\t\t\t\t\tif k != 0: fin_string += ', '\n\t\t\t\t\tfin_string += universe.atomList()[z].name\n\t\t\t\t\tk += 1\n\t\t\t\tfin_string += ']'\n\t\t\tfor i in range(1,len(self.atring)):\n\t\t\t\tif self.atring[i] != self.atring[i-1] :\n\t\t\t\t\t#print self.atring[i]\n\t\t\t\t\tif t != 0: fin_string += ', '\n\t\t\t\t\tt += 1\n\t\t\t\t\tfin_string += '['\n\t\t\t\t\tk = 0\n\t\t\t\t\tfor z in self.atring[i]:\n\t\t\t\t\t\tif k != 0: fin_string += ', '\n\t\t\t\t\t\tfin_string += universe.atomList()[z].name\n\t\t\t\t\t\tk += 1\n\t\t\t\t\tfin_string += ']'\n\t\telif (len(self.atring) == 1):\n\t\t\t#print self.atring[0]\n\t\t\tif t != 0: fin_string += ', '\n\t\t\tt += 1\n\t\t\tfin_string += '['\n\t\t\tk = 0\n\t\t\tfor z in self.atring[0]:\n\t\t\t\tif k != 0: fin_string += ', '\n\t\t\t\tfin_string += universe.atomList()[z].name\n\t\t\t\tk += 1\n\t\t\tfin_string += ']'\n\t\telse:\n\t\t\tpass\n\t\t\t#print 'No rings found'\n\t\tfin_string += ']'\n\t\tprint fin_string\n\t#---------------------------------------------\n\n\n\tdef growRB(self):\n\t\t\"\"\"\n\t\tGrows rigid bodies starting from\n\t\trigid bonds (C-H, X=X) and rings\n\t\t\"\"\"\n#\t\tprint 'BEGIN growRB ============='\n\t\t# Build atatom list ([atom, unsaturated rank])\n\t\tfor ai in universe.atomList():\n\t\t\tunsat = bisSaturated(ai.type.symbol, len(ai.bondedTo()))\n\t\t\tif unsat > 0:\n\t\t\t\tself.atatom.append([ai.index, unsat])\n\n\t\t# Build atbond list (bonds with sp2 or sp atoms)\n\t\tself.atbond = []\n\t\tfor ata in self.atatom:\n\t\t\tring_found1 = 0\n\t\t\tfor ri in self.atring:\t\t# Check if ata is in any ring\n\t\t\t\tfor rj in ri:\n\t\t\t\t\tif ata[0] == rj:\n\t\t\t\t\t\tring_found1 = 1\n\t\t\t\t\t\t#break\t\t\t# Atom 1 touches a ring\n\t\t\t\tif ring_found1 == 1:\n\t\t\t\t\tpass\n\t\t\t\t\t#break\t\t\t\t# Checked\n\t\t\tfor atb in self.atatom:\t# Check if atb is in any ring\n\t\t\t\tring_found2 = 0\n\t\t\t\tfor ri in self.atring:\n\t\t\t\t\tfor rj in ri:\n\t\t\t\t\t\tif atb[0] == rj:\n\t\t\t\t\t\t\tring_found2 = 1\n\t\t\t\t\t\t\t#break\t# Atom 2 touches a ring\n\t\t\t\tif (ring_found2 == 0) or (ring_found1 == 0):\n\t\t\t\t\tif ata.index < atb.index:\n\t\t\t\t\t\tfor bo in universe.atomList()[ata[0]].bondedTo():\n\t\t\t\t\t\t\tif bo.index == atb[0]:\n\t\t\t\t\t\t\t\tself.atbond.append([ata[0],atb[0]])\n\t\t\t\t\t\t\t\tbreak\n\n\n\t\tfin_str = \"\"\n\t\tfin_str += 'non_ring_pi_bonds = [' # len(self.atbond)\n\t\tk = 0\n\t\tfor bo in self.atbond:\n\t\t\t#print universe.atomList()[bo[0]].name, universe.atomList()[bo[1]].name\n\t\t\tif k != 0: fin_str += ', '\n\t\t\tfin_str += 'Bond('\n\t\t\tfin_str += universe.atomList()[bo[0]].name\n\t\t\tfin_str += ', '\n\t\t\tfin_str += universe.atomList()[bo[1]].name\n\t\t\tfin_str += ')'\n\t\t\tk += 1\n\t\tfin_str += ']'\n\t\tprint fin_str\n#\t\t\tprint bo\n#\t\tprint '------------------'\n\n\n# THE FOLLOWING CODE IS NOT NECESSARY\n#\t\tfor ri in self.atring:\t# Eliminates bonds sticked into rings BUG !!\n#\t\t\tfor rj in ri:\n#\t\t\t\tle = len(self.atbond)\n#\t\t\t\tfor bi in range(le):\n#\t\t\t\t\tif (self.atbond[bi][0] == rj) or (self.atbond[bi][1] == rj):\n#\t\t\t\t\t\tself.atbond.pop(bi)\n#\t\t\t\t\t\tbreak\n#\n#\t\tprint len(self.atbond), ': multiple bonds without sticked: '\n#\t\tfor bo in self.atbond:\n#\t\t\tprint universe.atomList()[bo[0]].name, universe.atomList()[bo[1]].name\n#\t\t\t#print bo\n#\t\tprint '------------------'\n\n\t\t# Build atconj - merge multiple bonds in conjugated systems\n\t\tself.atconj = copy.deepcopy(self.atbond)\n\t\tbuff = []\n\t\tcnt = 0\n\t\tmerge_found = 1\n\t\twhile (merge_found == 1) and (cnt < 100):\n\t\t\tcnt += 1\n\t\t\tmerge_found = 0\n\t\t\tfor coi in range(len(self.atconj)):\n\t\t\t\tfor coj in range(len(self.atconj)):\n\t\t\t\t\tif coj != coi:\n\t\t\t\t\t\t# Check if they have a common atom (to merge them)\n\t\t\t\t\t\tfor i in self.atconj[coi]:\n\t\t\t\t\t\t\tfor j in self.atconj[coj]:\n\t\t\t\t\t\t\t\tif i == j:\n\t\t\t\t\t\t\t\t\tmerge_found = 1\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tif merge_found == 1:\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tif merge_found == 1:\t# Add coj to coi (merge)\n\t\t\t\t\t\t\tbuff = []\n\t\t\t\t\t\t\tfor j in self.atconj[coj]:\n\t\t\t\t\t\t\t\tcommon = 0\n\t\t\t\t\t\t\t\tfor i in self.atconj[coi]:\n\t\t\t\t\t\t\t\t\tif i == j:\n\t\t\t\t\t\t\t\t\t\tcommon = 1\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\tif common == 0:\n\t\t\t\t\t\t\t\t\tbuff.append(j)\n\t\t\t\t\t\t\tfor t in buff:\n\t\t\t\t\t\t\t\tself.atconj[coi].append(t)\n\t\t\t\t\t\t\t# Print the new conj\n\t\t\t\t\t\t\t# Remove bond coj \n\t\t\t\t\t\t\tself.atconj.pop(coj) # Eliminate coj from atconj\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tif merge_found == 1:\n\t\t\t\t\t\tbreak\n\t\t\t\tif merge_found == 1:\n\t\t\t\t\tbreak\n\n\n#\t\tprint 'Conjugated systems: '\n#\t\tfor coi in self.atconj:\n#\t\t\t\tfor k in coi:\n#\t\t\t\t\tprint universe.atomList()[k].name, ' ',\n#\t\t\t\tprint\n\t\t\t\n#\t\tprint 'END growRB ================'\n\n\n\tdef diffPseudoDihe(self):\n\t\t\"\"\"\n\t\tEliminates correlated dihedrals by \n\t\treplacing them with differences\n\t\t\"\"\"\n\t\tprint 'BEGIN diffPseudoDihe() =========='\n\t\t#for ai in universe.atomList():\n\t\t#\tprint ai.position()\n\n\t\t#for bi in self.atbond:\n\t\t#\tprint 'atbond', universe.atomList()[bi[0]].name, universe.atomList()[bi[1]].name\n\n\t\t#for di in self.dihedrals:\n\t\t#\tconvertor.print_zmat_dihe(di)\n\n\t\t#Stickbonds\n\t\tself.stickbonds = []\n\t\tfor bi in self.bonds:\n\t\t\tat1found =  -1\n\t\t\tat2found =  -1\n\t\t\tfor ri in self.atring: # Search the rings\n\t\t\t\tfor rj in ri:\n\t\t\t\t\tif (bi[0].index == rj) and \\\n\t\t\t\t\t\t(universe.atomList()[bi[1].index].type.symbol != 'H'):\n\t\t\t\t\t\tat1found = rj\n\t\t\t\t\telif (bi[1].index == rj)  and \\\n\t\t\t\t\t\t(universe.atomList()[bi[0].index].type.symbol != 'H'):\n\t\t\t\t\t\tat2found = rj\n\t\t\tif ((at1found >= 0) and (at2found == -1) or\\\n\t\t\t\t(at1found == -1) and (at2found >= 0)):\n\t\t\t\tself.stickbonds.append([bi[0].index, bi[1].index])\n\t\t\n#\t\tprint 'Sticked bonds:'\t\t\t\t\n#\t\tfor bi in self.stickbonds:\n#\t\t\tprint universe.atomList()[bi[0]].name, universe.atomList()[bi[1]].name\n\n\n\t\tfor ri in self.atring:\n\t\t\tprint ri\n\t\t\tfor rj in ri:\n\t\t\t\tstick = -1\n\t\t\t\tfor bi in self.stickbonds:\n\t\t\t\t\tif bi[0] == rj:\n\t\t\t\t\t\tstick = 1\n\t\t\t\t\telif bi[1] == rj:\n\t\t\t\t\t\tstick = 0\n\t\t\t\t\tif stick >= 0:\n\t\t\t\t\t\tprint '[',universe.atomList()[bi[0]].name,\\\n\t\t\t\t\t\t\t\tuniverse.atomList()[bi[1]].name, '] :'\n\t\t\t\t\t\t# Search dihedrals\n\t\t\t\t\t\tfor di in self.dihedrals:\n\t\t\t\t\t\t\ta2 = di[0][0][1]\n\t\t\t\t\t\t\ta3 = di[1][0][1]\n\t\t\t\t\t\t\tif ((a2.index == bi[0] and a3.index == bi[1]) or\\\n\t\t\t\t\t\t\t\t(a2.index == bi[1] and a3.index == bi[0])):\n\t\t\t\t\t\t\t\t\tconvertor.print_zmat_dihe(di)\n\t\t\t\t\t\tprint '+++++++++++++++'\n\t\t\t\t\t\tbreak\n\n\t\tprint 'END   diffPseudoDihe() =========='\n\n#-------------------------------------------------------------------------\n\n\n########\n# MAIN #\n########\n\n# BUILD MOLECULE #\n\n# \"Declare\" some variables\nnatm = 0;\natmi = 0;\nx = .0;\ny = .0;\nz = .0;\nelem = '--';\nname = [];\n##################\n\nfpo1 = open(sys.argv[1], 'r');\n\nfactory = MoleculeFactory();\nfactory.createGroup('main');\n\nlinecnt = 0;\nwhile True:\n\tline = fpo1.readline();\n\tif not line: break;\n\tlinecnt += 1;\n\tif linecnt == 4:\n\t\tnatm = int(bsubstr(line, 1, 3));\n\tif (linecnt >= 5) and (linecnt < (5 + natm)):   # Read cart coords\n\t\tatmi += 1;\n\t\tx = float(bsubstr(line,  2, 9));\n\t\ty = float(bsubstr(line, 12, 9));\n\t\tz = float(bsubstr(line, 22, 9));\n\t\telem = bsubstr(line, 32, 2);\n\t\tif elem[1] == ' ':\n\t\t\telem = elem[0];\n\t\tname.append(elem + str(atmi));\n\t\tfactory.addAtom('main',name[atmi-1],elem);\n\t\tfactory.setPosition('main',name[atmi-1],Vector\\\n\t\t\t(x*Units.Ang, y*Units.Ang, z*Units.Ang));\n\tif linecnt >= (5 + natm):\n\t\tif line[0] == 'M': break\n\t\tfactory.addBond('main',\\\n\t\t\tname[int(bsubstr(line,1,3))-1], name[int(bsubstr(line,4,3))-1]);\n\nfpo1.close();\n\nnewmol = factory.retrieveMolecule('main');\nuniverse = InfiniteUniverse(Amber99ForceField(mod_files=['frcmod.ff99SB']));\nuniverse.addObject(newmol);\nuniverse.configuration();\n\n# -------------------------------------------\n\n#anchor(universe)\t# BUG pseudo01.sdf when first atom has only one bond\n\n#universe.writeXML(file('out.xml', 'w'));\n#universe.writeToFile('out.pdb');\n\nconvertor = bConvertor(universe)\nconvertor.cart2all_internals()\n#convertor.print_internals()\n\n#print '\\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\\n'\n#for i in convertor.dihedrals:\n#\tconvertor.print_zmat_dihe(i)\n#convertor.inte2cart(convertor.dihedrals)\n\n# Print rings\nrb_selector = bRBSelector(universe, convertor)\nrb_selector.find_rings()\n#rb_selector.print_atring()\nrb_selector.print_rings()\nrb_selector.growRB()\n#rb_selector.diffPseudoDihe()\n\n\n\n\n\n\n\n", "meta": {"hexsha": "c7aa64e124bba8575a3c48fac02aca0f9eae1a48", "size": 29770, "ext": "py", "lang": "Python", "max_stars_repo_path": "Pipeline/32rigid_bodies.py", "max_stars_repo_name": "CCBatIIT/AlGDock", "max_stars_repo_head_hexsha": "25c376e9d860d50696f5e20f1b107d289ec0903c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2015-06-16T19:25:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T05:50:47.000Z", "max_issues_repo_path": "Pipeline/32rigid_bodies.py", "max_issues_repo_name": "biocheming/AlGDock", "max_issues_repo_head_hexsha": "25c376e9d860d50696f5e20f1b107d289ec0903c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2015-05-06T21:05:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T09:51:45.000Z", "max_forks_repo_path": "Pipeline/32rigid_bodies.py", "max_forks_repo_name": "biocheming/AlGDock", "max_forks_repo_head_hexsha": "25c376e9d860d50696f5e20f1b107d289ec0903c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2015-04-13T21:11:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T00:25:42.000Z", "avg_line_length": 26.7715827338, "max_line_length": 185, "alphanum_fraction": 0.5418878065, "include": true, "reason": "import numpy", "num_tokens": 10424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19131846660970883}}
{"text": "# %% [markdown]\n\"\"\"\ncalculate ODNP using DNPLab\n===========================\n\nThis example demonstrates how to use the dnplab.dnpHydration module\n\n\"\"\"\n# %%\n\n# %% [markdown]\n# First import dnplab and numpy,\nimport dnplab\nimport numpy as np\n\n# %%\n\n# %% [markdown]\n# To use the dnpHydration module first create a dictionary with the necessary inputs. Start by creating a workspace and assinging an inputs dictionary to the key **'hydration_inputs'**. For example,\n\nEnhancements = [] # list of signal enhancements\nEnhancement_powers = [] # list of powers in Watts corresponding to Enhancements\nT1s = [] # list of T1 values in seconds\nT1_powers = [] # list of powers in Watts corresponding to T1s\n\ninputs = {\n          'E_array' : np.array(Enhancements),\n          'E_powers' : np.array(Enhancement_powers),\n          'T1_array' : np.array(T1s),\n          'T1_powers' : np.array(T1_powers),\n          'T10': 2.0, # T1 measured with power=0\n          'T100': 2.5, # T1 measured with SL=0 and power=0\n          'spin_C': 100, # spin concentration in micromolar\n          'field': 350, # magnetic field in mT\n          'smax_model': 'tethered', # choice of smax model\n          'interpolate_method': 'second_order' # choice of interpolation method\n          }\n# %%\n\n# %% [markdown]\n# Now you can either create a workspace and add the dictionary under the key **'hydration_inputs'**,\nworkspace = dnplab.create_workspace('hydration_inputs', inputs)\n# %%\n\n# %% [markdown]\n# Or add to an existing workspace,\nworkspace.add('hydration_inputs', inputs)\n# %%\n\n# %% [markdown]\n# In rare cases the bulk water or second order T1 interpolation constants may need to be altered. This is not necessary for the odnp module to operate, but if needed this can be done by adding the dictionary **'hydration_constants'** to the workspace. For example,\nconstants = {\n             'ksigma_bulk': 95.4, # bulk ksigma value\n             'krho_bulk': 353.4, # bulk krho value\n             'klow_bulk': 366, # bulk klow value\n             'tcorr_bulk': 54, # bulk tcorr value\n             'D_H2O': 2.3e-9, # bulk water diffusivity\n             'D_SL': 4.1e-10, # diffusivity of spin probe in bulk water\n             'delta_T1_water': 1, # change in water proton T1 due to microwaves\n             'T1_water': 2.5, # T1 of bulk water protons\n             'macro_C': 100, # concentration of macromolecule in uM\n             }\n\nworkspace.add('hydration_constants', constants)\n# %%\n\n# %% [markdown]\n# Next, pass the workspace to dnplab.dnpHydration.hydration to perform calculations using,\nhydration_results = dnplab.dnpHydration.hydration(workspace)\n# %%\n\n# %% [markdown]\n# or operate in-place with:\ndnplab.dnpHydration.hydration(workspace)\n# %%\n\n\n# %% [markdown]\n# For use without creating a DNPLab workspace simply skip the above steps and pass the dictionaries to dnpHydration directly,\nhydration_results = dnplab.dnpHydration.odnp(inputs=inputs, constants=constants)\n# %%\n", "meta": {"hexsha": "c292bab0e7c7679344fccdab60453dda562e57c5", "size": 2938, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/calculate_ODNP.py", "max_stars_repo_name": "tkeller12/hanlab", "max_stars_repo_head_hexsha": "9ce9d2545106b08256cc5bf16ea7e950c0603af6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/calculate_ODNP.py", "max_issues_repo_name": "tkeller12/hanlab", "max_issues_repo_head_hexsha": "9ce9d2545106b08256cc5bf16ea7e950c0603af6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/calculate_ODNP.py", "max_forks_repo_name": "tkeller12/hanlab", "max_forks_repo_head_hexsha": "9ce9d2545106b08256cc5bf16ea7e950c0603af6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-22T22:04:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T22:04:26.000Z", "avg_line_length": 35.8292682927, "max_line_length": 264, "alphanum_fraction": 0.6678012253, "include": true, "reason": "import numpy", "num_tokens": 779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3738758157951908, "lm_q1q2_score": 0.191318463039715}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# ### Hill Climber algorithm to generate a team\n# \n# - takes in the list of available players for the gameweek with their predicted scores from the player model\n# - constructs a 15-man squad adhering to budget connstraints and team constraints set by FPL\n\n# In[ ]:\n\n\nimport numpy as np\nimport pandas as pd\nimport random as rd\nimport random\nfrom random import randint\nfrom random import sample\nimport matplotlib.pyplot as plt\nimport requests\npd.options.display.max_rows = None\npd.options.display.max_columns = None\nimport itertools\n\n\n# In[78]:\n\n\nclass generate_team():\n    \n    def __init__(self, players):\n        self.players = players\n        self.initiate()\n    \n    def init_player_lists(self,players):\n        #Method to initialise four vectors of 0, where each defines the position and is the length of the amount of\n        #players in that position. Randomly assign 1's to an index in each list to initiate a squad\n        #@params players = the list of available players\n        #@return goalkeeper, defender, midfielder, attacker lists\n        \n        #make the lists from the actual players\n        goalks, defs, mids, atts = [], [], [], []\n        for i in players:\n            if i[1] == 1:\n                goalks.append(i)\n            elif i[1] == 2:\n                defs.append(i)\n            elif i[1] == 3:\n                mids.append(i)\n            elif i[1] == 4:\n                atts.append(i)\n        \n        #initialise each vector to have a random player, goalkeepers 2 players, def 5, mid 5, atk 3.\n        goalkeepers = [0 for i in range(len(goalks))]\n        x = [i for i in range(len(goalks))]\n        random_numbers = random.sample(x, 2)\n        for random_number in random_numbers:\n            goalkeepers[random_number] = 1\n\n        defenders = [0 for i in range(len(defs))]\n        x = [i for i in range(len(defs))]\n        random_numbers = random.sample(x, 5)\n        for random_number in random_numbers:\n            defenders[random_number] = 1\n\n        midfielders = [0 for i in range(len(mids))]\n        x = [i for i in range(len(mids))]\n        random_numbers = random.sample(x, 5)\n        for random_number in random_numbers:\n            midfielders[random_number] = 1\n\n        attackers = [0 for i in range(len(atts))]\n        x = [i for i in range(len(atts))]\n        random_numbers = random.sample(x, 3)\n        for random_number in random_numbers:\n            attackers[random_number] = 1\n\n        return goalkeepers, defenders, midfielders ,attackers\n    \n    def init_hc(self,max_threshold, players):\n        #Method to call initialise squad vectors. If the constraints are not met, repeat the initialisation\n        #@params max_threshold = the budget constraint, players = the available players\n        #@return goalkeeper, defender, midfielder, attacker lists\n        \n        goalkeeper, defender, midfielder, attacker = [], [], [], []\n        for i in players:\n            if i[1] == 1:\n                goalkeeper.append(i)\n            elif i[1] == 2:\n                defender.append(i)\n            elif i[1] == 3:\n                midfielder.append(i)\n            elif i[1] == 4:\n                attacker.append(i)\n\n        total_weight = max_threshold +1\n        total_points = 51\n        #total_weight cannot go over budget constraint\n        while (total_weight > 100 or total_points < 50):\n            gkp, defs, mids, atks = self.init_player_lists(players)\n            g_weight = (sum([goalkeeper[i][4] for i in range(len(goalkeeper)) if gkp[i] == 1]))\n            d_weight = (sum([defender[i][4] for i in range(len(defender)) if defs[i] == 1]))\n            m_weight = (sum([midfielder[i][4] for i in range(len(midfielder)) if mids[i] == 1]))\n            a_weight = (sum([attacker[i][4] for i in range(len(attacker)) if atks[i] == 1]))\n            total_weight = g_weight + d_weight + m_weight + a_weight \n\n            team_points = []\n            team_points.append([goalkeeper[i][3] for i in range(len(goalkeeper)) if gkp[i] == 1])\n            team_points.append([defender[i][3] for i in range(len(defender)) if defs[i] == 1])\n            team_points.append([midfielder[i][3] for i in range(len(midfielder)) if mids[i] == 1]) \n            team_points.append([attacker[i][3] for i in range(len(attacker)) if atks[i] == 1])\n            team_points = list(itertools.chain(*team_points))\n            total_points = sum(team_points)\n        return gkp, defs, mids, atks\n\n    def evaluate_fitness(self,max_threshold, players, gkp, defs, mids, atks):\n        #Method to evaluate fitness by looking at the weight of the squad. Similarly, to see if any team has\n        #more than 3 players in the squad. This is not allowed in FPL rules\n        #@params max-threshold = budget, players = available players, gkp,defs,mids,atks = squad player vectors\n        #@return fitness = how many projected points, team_weight = cost of squad, team_points = indiv player points\n        team_weight= []\n        team_points = []\n        fitness = 0\n\n        goalkeeper, defender, midfielder, attacker = [], [], [], []\n        for i in players:\n            if i[1] == 1:\n                goalkeeper.append(i)\n            elif i[1] == 2:\n                defender.append(i)\n            elif i[1] == 3:\n                midfielder.append(i)\n            elif i[1] == 4:\n                attacker.append(i)\n        \n        #calculate weight of squad (total cost)\n        team_weight.append([goalkeeper[i][4] for i in range(len(goalkeeper)) if gkp[i] == 1])\n        team_weight.append([defender[i][4] for i in range(len(defender)) if defs[i] == 1])\n        team_weight.append([midfielder[i][4] for i in range(len(midfielder)) if mids[i] == 1]) \n        team_weight.append([attacker[i][4] for i in range(len(attacker)) if atks[i] == 1])\n        team_weight = list(itertools.chain(*team_weight))\n\n        #calculate total team points predicted \n        team_points.append([goalkeeper[i][3] for i in range(len(goalkeeper)) if gkp[i] == 1])\n        team_points.append([defender[i][3] for i in range(len(defender)) if defs[i] == 1])\n        team_points.append([midfielder[i][3] for i in range(len(midfielder)) if mids[i] == 1]) \n        team_points.append([attacker[i][3] for i in range(len(attacker)) if atks[i] == 1])\n        team_points = list(itertools.chain(*team_points))\n\n        #calculate how many players are from each team to see if gone over\n        team_code = []\n        team_code.append([goalkeeper[i][2] for i in range(len(goalkeeper)) if gkp[i] == 1])\n        team_code.append([defender[i][2] for i in range(len(defender)) if defs[i] == 1])\n        team_code.append([midfielder[i][2] for i in range(len(midfielder)) if mids[i] == 1]) \n        team_code.append([attacker[i][2] for i in range(len(attacker)) if atks[i] == 1])\n        team_code = list(itertools.chain(*team_code))\n        overkill_team = False\n        for team in range(1,21):\n            i = 0\n            for team_ in team_code:\n                if team == team_:\n                    i+= 1\n                    if i > 3:\n                        #overkill = too many players from one team\n                        overkill_team = True\n        \n        #If team weight is too high or overkill is true, fitness of the squad is 0\n        if sum(team_weight) > max_threshold or overkill_team is True:\n            fitness = 0\n        else:\n            fitness = sum(team_points)\n        return fitness, team_weight, team_points\n    \n    def mutate(self,mutation_rate, gkp, defs, mids, atks):\n        #Method to mutate the squad in a certain way to find new better squads\n        #@params mutation_rate = the likelihood of change, gkp,def,mids,atks = squad vectors\n        #@return gkp,defs,mids,atks = new mutated squad\n    \n        a = rd.random()\n        b = rd.random()\n        c = rd.random()\n        d = rd.random()\n        \n        #For each position, get a random number, swap out a current player and change a position in the vector\n        #from zero to one to add a new player\n\n        if a <= mutation_rate:\n            x = [i for i in range(len(gkp))]\n            random_number = random.sample(x, 1)\n            present_numbers = [i for i in range(len(gkp))if gkp[i] == 1]\n            #if player is already in the squad, dont do anything, if not carry on\n            if random_number[0] not in present_numbers:\n                #choose which player to remove randomly out of 2 players\n                r = [i for i in range(0,2)]\n                #remove the player\n                remove_index = random.sample(r,1)\n                for player in range(len(gkp)):\n                    if player == present_numbers[remove_index[0]]:\n                        gkp[player] = 0\n                    if player == random_number[0]:\n                        gkp[player] = 1\n\n        if b <= mutation_rate:\n            x = [i for i in range(len(defs))]\n            random_number = random.sample(x, 1)\n            present_numbers = [i for i in range(len(defs))if defs[i] == 1]\n            #if player is already in the squad, dont do anything, if not carry on\n            if random_number[0] not in present_numbers:\n                #choose which player to remove randomly out of 5 players\n                r = [i for i in range(0,5)]\n                #remove the player\n                remove_index = random.sample(r,1)\n                for player in range(len(defs)):\n                    if player == present_numbers[remove_index[0]]:\n                        defs[player] = 0\n                    if player == random_number[0]:\n                        defs[player] = 1\n\n        if c <= mutation_rate:\n            x = [i for i in range(len(mids))]\n            random_number = random.sample(x, 1)\n            present_numbers = [i for i in range(len(mids))if mids[i] == 1]\n            #if player is already in the squad, dont do anything, if not carry on\n            if random_number[0] not in present_numbers:\n                r = [i for i in range(0,5)]\n                #choose which player to remove randomly out of 5 players\n                remove_index = random.sample(r,1)\n                #remove the player\n                for player in range(len(mids)):\n                    if player == present_numbers[remove_index[0]]:\n                        mids[player] = 0\n                    if player == random_number[0]:\n                        mids[player] =1\n\n        if d <= mutation_rate:\n            x = [i for i in range(len(atks))]\n            random_number = random.sample(x, 1)\n            present_numbers = [i for i in range(len(atks))if atks[i] == 1]\n            #if player is already in the squad, dont do anything, if not carry on\n            if random_number[0] not in present_numbers:\n                #choose which player to remove randomly out of 3 players\n                r = [i for i in range(0,3)]\n                #remove the player\n                remove_index = random.sample(r,1)\n                for player in range(len(atks)):\n                    if player == present_numbers[remove_index[0]]:\n                        atks[player] = 0\n                    if player == random_number[0]:\n                        atks[player] = 1\n\n        return gkp, defs, mids, atks\n\n    def hillclimber(self,gkp, defs, mids, atks, players, max_threshold, generations, mutation_rate):\n        #Method to call hill climber algorithm with each individual method, used to rretrieve new better squads\n        #@params gkp,defs,mids,atks = player vectors, max_threshold = budget, generations, mutation_rate\n        #@return gkp,defs,mids,atks = player vectors, fitness = list of squad projected points over time\n    \n        fitness = []\n        for i in range(generations):\n            #if (i % 50000) == 0:\n                #print(i/50000, \"% completed\")\n            \n            #make a copy of the exisiting squad\n            gkp1 = gkp.copy()\n            defs1 = defs.copy()\n            mids1 = mids.copy()\n            atks1 = atks.copy()\n\n            #mutate copied squad, calc fitness of both new and old squads\n            gkp1, defs1, mids1, atks1 = self.mutate(mutation_rate, gkp1, defs1, mids1, atks1)\n            g0_fitness, team_weight, team_points = self.evaluate_fitness(max_threshold, players, gkp, defs, mids, atks)\n            g1_fitness, team_weight, team_points = self.evaluate_fitness(max_threshold, players, gkp1, defs1, mids1, atks1)\n\n            #if new squad has better fitness, this becomes the main squad\n            if g1_fitness > g0_fitness:\n                gkp = gkp1\n                mids = mids1\n                defs = defs1\n                atks = atks1\n\n            fitness.append(g0_fitness)\n\n        return gkp, defs, mids, atks, fitness\n    \n    def graph(self,fitness,mutation_rate, players, gkp, defs, mids, atks,generations):\n        #Method to call a visual representation of the graph\n        #@params fitness = squad fitness, mutation_rate, players = available players, squad vectors, generations\n        #@return total team points and total team weight\n        \n        #print(\"Mutation rate = \", mutation_rate)\n        team_weight= []\n        team_points = []\n\n        goalkeeper, defender, midfielder, attacker = [], [], [], []\n        for i in players:\n            if i[1] == 1:\n                goalkeeper.append(i)\n            elif i[1] == 2:\n                defender.append(i)\n            elif i[1] == 3:\n                midfielder.append(i)\n            elif i[1] == 4:\n                attacker.append(i)\n\n        team_weight.append([goalkeeper[i][4] for i in range(len(goalkeeper)) if gkp[i] == 1])\n        team_weight.append([defender[i][4] for i in range(len(defender)) if defs[i] == 1])\n        team_weight.append([midfielder[i][4] for i in range(len(midfielder)) if mids[i] == 1]) \n        team_weight.append([attacker[i][4] for i in range(len(attacker)) if atks[i] == 1])\n        team_weight = list(itertools.chain(*team_weight))\n\n        team_points.append([goalkeeper[i][3] for i in range(len(goalkeeper)) if gkp[i] == 1])\n        team_points.append([defender[i][3] for i in range(len(defender)) if defs[i] == 1])\n        team_points.append([midfielder[i][3] for i in range(len(midfielder)) if mids[i] == 1]) \n        team_points.append([attacker[i][3] for i in range(len(attacker)) if atks[i] == 1])\n        team_points = list(itertools.chain(*team_points))\n\n        #print(\"Total final points:\", sum(team_points))\n        #print(\"Total final cost:\", sum(team_weight))\n\n        #plt.plot(range(generations), fitness, label = 'Fitness')\n        #plt.legend()\n        #plt.title('Fitness level of hill Climber over 500 generations')\n        #plt.xlabel('Generations')\n        #plt.ylabel('Fitness')\n        #plt.show()\n\n        return (sum(team_points)), (sum(team_weight))\n    \n    def project_squad(self,players, top_choice):\n        #Method to get the best squad vector and change it from the labels back into the real projected points\n        #@params players = available players, top_choice = top squad vectors\n        #@return None\n\n        goalks, defs, mids, atts = [], [], [], []\n        for i in players:\n            if i[1] == 1:\n                goalks.append(i)\n            elif i[1] == 2:\n                defs.append(i)\n            elif i[1] == 3:\n                mids.append(i)\n            elif i[1] == 4:\n                atts.append(i)\n\n        squad = []\n        for i in range(len(top_choice[0])):\n            if top_choice[0][i] == 1:\n                squad.append(goalks[i])\n        for i in range(len(top_choice[1])):\n            if top_choice[1][i] == 1:\n                squad.append(defs[i])\n        for i in range(len(top_choice[2])):\n            if top_choice[2][i] == 1:\n                squad.append(mids[i])\n        for i in range(len(top_choice[3])):\n            if top_choice[3][i] == 1:\n                squad.append(atts[i])\n\n        #amend dataframe to change labels into actual predicted FPL poinnts\n        full_squad = pd.DataFrame(squad, columns= [\"Player Name\", \"Element Type\", \"Team\", \"Predicted_Points\", \"Cost\"])\n        full_squad.insert(loc = 3, column = \"Xg_Points\", value = \"0\")\n        for index,row in full_squad.iterrows():\n            po = full_squad[\"Predicted_Points\"][index]\n            if po == 1:\n                full_squad.at[index,\"Xg_Points\"] = \"-1\"\n            elif po == 2:\n                full_squad.at[index,\"Xg_Points\"]  =  \"0\"\n            elif po == 3:\n                full_squad.at[index,\"Xg_Points\"]  = \"1\"\n            elif po == 4:\n                full_squad.at[index,\"Xg_Points\"]  = \"2\"\n            elif po == 5:\n                full_squad.at[index,\"Xg_Points\"]  = \"3\"\n            elif po == 6:\n                full_squad.at[index,\"Xg_Points\"] = \"4\"\n            elif po == 7:\n                full_squad.at[index,\"Xg_Points\"]  = \"5\"\n            elif po == 8:\n                full_squad.at[index,\"Xg_Points\"]  = \"6\"\n            elif po == 9:\n                full_squad.at[index,\"Xg_Points\"] = \"7\"\n            elif po == 10:\n                full_squad.at[index,\"Xg_Points\"]  = \"8 - 9\" \n            elif po == 11:\n                full_squad.at[index,\"Xg_Points\"]  = \"10 - 12\" \n            elif po == 12:\n                full_squad.at[index,\"Xg_Points\"]  = \"12 - 14\"\n            elif po == 13:\n                full_squad.at[index,\"Xg_Points\"]  = \"15+\"\n            elif po >= 14:\n                full_squad.at[index,\"Xg_Points\"]  = str(po+2)\n        del full_squad[\"Predicted_Points\"]\n\n\n        return full_squad, squad\n    \n    def initiate(self):\n        #Method to initiate the hillcimber \n        #@params None\n        #@return None\n        \n        max_threshold = 100\n        generations = 10000\n        #mutation rates chosen\n        mutation_rates =[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]\n        iterations = 3\n\n        fit_group = []\n        totalp = [0]\n        totalc = [0] \n        final_choices = []\n        #make a new squad\n        gkp, defs, mids, atks = self.init_hc(max_threshold, self.players)\n        for i in range(iterations):\n            for mutation_rate in mutation_rates:\n                \n                final_choices = []\n                #make a copy of the init hill climber so each iteration has the same initial starting squad\n                gkp1 = gkp\n                mids1 = mids\n                defs1 = defs\n                atks1 = atks\n                fitness_history = []\n                #call the hillclimber on the squad\n                gkp1, defs1, mids1, atks1, fitness = self.hillclimber(gkp1, defs1, mids1, atks1, self.players, max_threshold, generations, mutation_rate)\n                fit_group.append(fitness)\n                final_points, final_cost = self.graph(fitness,mutation_rate, self.players, gkp1, defs1, mids1, atks1,generations)\n                final_choices.append([gkp1, defs1, mids1, atks1])\n                #if squad is optimal, append to optimal squad\n                if final_points >= max(totalp):\n                    if final_points == max(totalp) and final_cost < max(totalc):\n                        continue\n                    else:\n                        top_choice  = [gkp1,defs1,mids1,atks1]\n                        top_cost = final_cost\n                        top_points = final_points\n                totalp.append(final_points) \n                totalc.append(final_cost)\n        full_squad, squad = self.project_squad(self.players,top_choice)\n        self.full_squad = full_squad\n        self.squad = squad\n        #top choice is the vector representation of the best squad, used for transfer model\n        self.top_choice = top_choice\n        print(\"Squad Selection is Completed\")\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "5f3eed145700af55558775746e0884ec99f322da", "size": 19605, "ext": "py", "lang": "Python", "max_stars_repo_path": "generate_team.py", "max_stars_repo_name": "jesperdj9/FantasyFootballProj", "max_stars_repo_head_hexsha": "0cefa051d7c77d3786f239806887ee5b7be72bda", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "generate_team.py", "max_issues_repo_name": "jesperdj9/FantasyFootballProj", "max_issues_repo_head_hexsha": "0cefa051d7c77d3786f239806887ee5b7be72bda", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "generate_team.py", "max_forks_repo_name": "jesperdj9/FantasyFootballProj", "max_forks_repo_head_hexsha": "0cefa051d7c77d3786f239806887ee5b7be72bda", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4700665188, "max_line_length": 153, "alphanum_fraction": 0.5611833716, "include": true, "reason": "import numpy", "num_tokens": 4866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.19131845946972112}}
{"text": "\"\"\"Boundary condition implementations.\n\nBoundary Conditions\n^^^^^^^^^^^^^^^^^^^\n\n.. autoclass:: PrescribedBoundary\n.. autoclass:: DummyBoundary\n.. autoclass:: AdiabaticSlipBoundary\n\"\"\"\n\n__copyright__ = \"\"\"\nCopyright (C) 2020 University of Illinois Board of Trustees\n\"\"\"\n\n__license__ = \"\"\"\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\n\nimport numpy as np\nfrom meshmode.dof_array import thaw\nfrom meshmode.mesh import BTAG_ALL, BTAG_NONE  # noqa\n# from mirgecom.eos import IdealSingleGas\nfrom grudge.symbolic.primitives import TracePair\nfrom mirgecom.euler import split_conserved, join_conserved\n\n\nclass PrescribedBoundary:\n    \"\"\"Boundary condition prescribes boundary soln with user-specified function.\n\n    .. automethod:: __init__\n    .. automethod:: boundary_pair\n    \"\"\"\n\n    def __init__(self, userfunc):\n        \"\"\"Set the boundary function.\n\n        Parameters\n        ----------\n        userfunc\n            User function must take two parameters: time and nodal\n            coordinates, and produce the solution at each node.\n        \"\"\"\n        self._userfunc = userfunc\n\n    def boundary_pair(\n            self, discr, q, btag, eos, t=0.0\n    ):\n        \"\"\"Get the interior and exterior solution on the boundary.\"\"\"\n        actx = q[0].array_context\n\n        boundary_discr = discr.discr_from_dd(btag)\n        nodes = thaw(actx, boundary_discr.nodes())\n        ext_soln = self._userfunc(t, nodes)\n        int_soln = discr.project(\"vol\", btag, q)\n        return TracePair(btag, interior=int_soln, exterior=ext_soln)\n\n\nclass DummyBoundary:\n    \"\"\"Boundary condition that assigns boundary-adjacent soln as the boundary solution.\n\n    .. automethod:: boundary_pair\n    \"\"\"\n\n    def boundary_pair(\n            self, discr, q, btag, eos, t=0.0\n    ):\n        \"\"\"Get the interior and exterior solution on the boundary.\"\"\"\n        dir_soln = discr.project(\"vol\", btag, q)\n        return TracePair(btag, interior=dir_soln, exterior=dir_soln)\n\n\nclass AdiabaticSlipBoundary:\n    r\"\"\"Boundary condition implementing inviscid slip boundary.\n\n    a.k.a. Reflective inviscid wall boundary\n\n    This class implements an adiabatic reflective slip boundary given\n    by\n    $\\mathbf{q^{+}} = [\\rho^{-}, (\\rho{E})^{-}, (\\rho\\vec{V})^{-}\n    - 2((\\rho\\vec{V})^{-}\\cdot\\hat{\\mathbf{n}}) \\hat{\\mathbf{n}}]$\n    wherein the normal component of velocity at the wall is 0, and\n    tangential components are preserved. These perfectly reflecting\n    conditions are used by the forward-facing step case in\n    [Hesthaven_2008]_, Section 6.6, and correspond to the characteristic\n    boundary conditions described in detail in [Poinsot_1992]_.\n\n    .. automethod:: boundary_pair\n    \"\"\"\n\n    def boundary_pair(\n            self, discr, q, btag, eos, t=0.0\n    ):\n        \"\"\"Get the interior and exterior solution on the boundary.\n\n        The exterior solution is set such that there will be vanishing\n        flux through the boundary, preserving mass, momentum (magnitude) and\n        energy.\n        rho_plus = rho_minus\n        v_plus = v_minus - 2 * (v_minus . n_hat) * n_hat\n        mom_plus = rho_plus * v_plus\n        E_plus = E_minus\n        \"\"\"\n        # Grab some boundary-relevant data\n        dim = discr.dim\n        cv = split_conserved(dim, q)\n        actx = cv.mass.array_context\n\n        # Grab a unit normal to the boundary\n        nhat = thaw(actx, discr.normal(btag))\n\n        # Get the interior/exterior solns\n        int_soln = discr.project(\"vol\", btag, q)\n        int_cv = split_conserved(dim, int_soln)\n\n        # Subtract out the 2*wall-normal component\n        # of velocity from the velocity at the wall to\n        # induce an equal but opposite wall-normal (reflected) wave\n        # preserving the tangential component\n        mom_normcomp = np.dot(int_cv.momentum, nhat)  # wall-normal component\n        wnorm_mom = nhat * mom_normcomp  # wall-normal mom vec\n        ext_mom = int_cv.momentum - 2.0 * wnorm_mom  # prescribed ext momentum\n\n        # Form the external boundary solution with the new momentum\n        bndry_soln = join_conserved(dim=dim, mass=int_cv.mass,\n                                    energy=int_cv.energy,\n                                    momentum=ext_mom)\n\n        return TracePair(btag, interior=int_soln, exterior=bndry_soln)\n", "meta": {"hexsha": "b7146adc6cdc26c7787f7d7b186a8700aef2a733", "size": 5250, "ext": "py", "lang": "Python", "max_stars_repo_path": "mirgecom/boundary.py", "max_stars_repo_name": "anderson2981/mirgecom", "max_stars_repo_head_hexsha": "8d5d44145b5984f27a3dcda30956756a9cbcd284", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mirgecom/boundary.py", "max_issues_repo_name": "anderson2981/mirgecom", "max_issues_repo_head_hexsha": "8d5d44145b5984f27a3dcda30956756a9cbcd284", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mirgecom/boundary.py", "max_forks_repo_name": "anderson2981/mirgecom", "max_forks_repo_head_hexsha": "8d5d44145b5984f27a3dcda30956756a9cbcd284", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2068965517, "max_line_length": 87, "alphanum_fraction": 0.6805714286, "include": true, "reason": "import numpy", "num_tokens": 1259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.19131845946972112}}
{"text": "#! /usr/bin/env python\n\n\"\"\"\nInstrumentData Class -- defines data format, wavelength info, mask geometry\n\nInstruments/masks supported:\nNIRISS AMI\nGPI, VISIR, NIRC2 removed - too much changed for the JWST NIRISS class\n\"\"\"\n\n# Standard Imports\nimport numpy as np\nfrom astropy.io import fits\nimport os, sys, time\nimport copy\n# Module imports\nimport synphot\n# import stsynphot\n# mask geometries, GPI, NIRISS, VISIR supported...\nfrom nrm_analysis.misctools.mask_definitions import NRM_mask_definitions \nfrom nrm_analysis.misctools import utils\nfrom nrm_analysis.misctools import lpl_ianc\n\n\n\num = 1.0e-6\n\n# utility routines for InstrumentData classes\n\ndef show_cvsupport_threshold(instr):\n    \"\"\" Show threshold for where 'splodge' data in CV space contains signal \"\"\"\n    print(\"InstrumentData: \", \"cvsupport_threshold is: \", instr.cvsupport_threshold)\n    print(\"InstrumentData: \", instr.cvsupport_threshold)\n\ndef set_cvsupport_threshold(instr, k, v):\n    \"\"\" Set threshold for where 'splodge' data in CV space contains signal\n        \n    Parameters\n    ----------\n    instr: InstrumentData instance\n    thresh: Threshold for the absolute value of the FT(interferogram).\n            Normalize abs(CV = FT(a)) for unity peak, and define the support \n            of \"good\" CV when this is above threshold\n    \"\"\"\n    \n    instr.cvsupport_threshold[k] = v\n    print(\"InstrumentData: \", \"New cvsupport_threshold is: \", instr.cvsupport_threshold)\n\n\n\nclass NIRISS:\n    def __init__(self, filt, \n                       objname=\"obj\", \n                       src='A0V', \n                       chooseholes=None, \n                       affine2d=None, \n                       bandpass=None,\n                       nbadpix=4,\n                       usebp=True,\n                       firstfew=None,\n                       nspecbin=None,\n                       **kwargs):\n        \"\"\"\n        Initialize NIRISS class\n\n        ARGUMENTS:\n\n        kwargs:\n        UTR\n        Or just look at the file structure\n        Either user has webbpsf and filter file can be read, or...\n        chooseholes: None, or e.g. ['B2', 'B4', 'B5', 'B6'] for a four-hole mask\n        filt:     Filter name string like \"F480M\"\n        bandpass: None or [(wt,wlen),(wt,wlen),...].  Monochromatic would be e.g. [(1.0, 4.3e-6)]\n                  Explicit bandpass arg will replace *all* niriss filter-specific variables with \n                  the given bandpass (src, nspecbin, filt), so you can simulate 21cm psfs through \n                  something called \"F430M\". Can also be synphot.spectrum.SourceSpectrum object.\n        firstfew: None or the number of slices to truncate input cube to in memory,\n                  the latter for fast developmpent\n        nbadpix:  Number of good pixels to use when fixing bad pixels DEPRECATED\n        usebp:    Convert to usedq during initialization\n                  Internally this is changed to sellf.usedq = usebp immediately for code clarity\n                  True (default) do not use DQ with DO_NOT_USE flag in input MAST data when\n                  fitting data with model.  False: Assume no bad pixels in input\n        noise:    standard deviation of noise added to perfect images to enable candid\n                  plots without crashing on np.inf limits!  Image assumed to be in (np.float64) dn.\n                  Suggested noise: 1e-6.\n        src:      source spectral type string e.g. \"A0V\" OR user-defined synphot.spectrum.SourceSpectrum object\n        nspecbin: Number of wavelength bins to use across the bandpass. Replaces deprecated `usespecbin` which \n                  set **number of wavelengths to into each bin**, not nbins.\n\n        \"\"\"\n\n        self.verbose = False\n        if \"verbose\" in kwargs:\n            self.verbose = kwargs[\"verbose\"]\n\n        self.noise = None\n        if \"noise\" in kwargs:\n            self.noise = kwargs[\"noise\"]\n        if \"usespecbin\" in kwargs: # compatability with previous arg\n            # but not really, usespecbin was binning factor, not number of bins\n            nspecbin = kwargs[\"usespecbin\"]\n        # change how many wavelength bins will be used across the bandpass\n        if nspecbin is None:\n            nspecbin = 19\n\n        self.lam_bin = nspecbin\n\n        # src can be either a spectral type string or a user-defined synphot spectrum object\n        if isinstance(src, synphot.spectrum.SourceSpectrum):\n            print(\"Using user-defined synphot SourceSpectrum\")\n\n        if chooseholes:\n            print(\"InstrumentData.NIRISS: \", chooseholes)\n        self.chooseholes = chooseholes\n\n    \n        # USEBP is USEDQ in the rest of code - use\n        self.usedq = usebp\n        print(\"Fitting omits bad pixels (identified by DO_NOT_USE value in the DQ extension)\")\n        self.jwst_dqflags() # creates dicts self.bpval, self.bpgroup\n        # self.bpexist set True/False if  DQ fits image extension exists/doesn't\n\n        self.firstfew = firstfew\n        if firstfew is not None: print(\"InstrumentData.NIRISS: analysing firstfew={:d} slices\".format(firstfew))\n\n        self.objname = objname\n\n        self.filt = filt\n\n        if bandpass is not None:\n            print(\"InstrumentData.NIRISS: OVERRIDING BANDPASS WITH USER-SUPPLIED VALUES.\")\n            print(\"\\t src, filt, nspecbin parameters will not be used\")\n            # check type of bandpass. can be synphot spectrum\n            # if so, get throughput and wavelength arrays\n            if isinstance(bandpass, synphot.spectrum.SpectralElement):\n                wl, wt = bandpass._get_arrays(bandpass.waveset)\n                self.throughput = np.array((wt,wl)).T\n            else:\n                self.throughput = np.array(bandpass)  # type simplification\n        else:\n            filt_spec = utils.get_filt_spec(self.filt)\n            src_spec = utils.get_src_spec(src)\n            # **NOTE**: As of WebbPSF version 1.0.0 filter is trimmed to where throughput is 10% of peak\n            # For consistency with WebbPSF simultions, use trim=0.1\n            self.throughput = utils.combine_src_filt(filt_spec, \n                                          src_spec, \n                                          trim=0.01, \n                                          nlambda=nspecbin,\n                                          verbose=self.verbose, \n                                          plot=False)\n\n        self.lam_c, self.lam_w = utils.get_cw_beta(self.throughput)\n\n        if self.verbose: print(\"InstrumentData.NIRISS: \", self.filt, \n              \": central wavelength {:.4e} microns, \".format(self.lam_c/um), end=\"\")\n        if self.verbose: print(\"InstrumentData.NIRISS: \", \"fractional bandpass {:.3f}\".format(self.lam_w))\n\n        self.wls = [self.throughput,] \n\n        if self.verbose: print(\"self.throughput:\\n\", self.throughput)\n\n        # Wavelength info for NIRISS bands F277W, F380M, F430M, or F480M\n        self.wavextension = ([self.lam_c,], [self.lam_w,])\n        self.nwav=1 # these are 'slices' if the data is pure imaging integrations - \n        #             nwav is old nomenclature from GPI IFU data.  Refactor one day...\n        #############################\n\n        # only one NRM on JWST:\n        self.telname = \"JWST\"\n        self.instrument = \"NIRISS\"\n        self.arrname = \"jwst_g7s6c\"  # implaneia mask set with this - unify to short form later \n        self.holeshape=\"hex\"\n        self.mask = NRM_mask_definitions(maskname=self.arrname, chooseholes=chooseholes, \n                                         holeshape=self.holeshape )\n\n        # save affine deformation of pupil object or create a no-deformation object. \n        # We apply this when sampling the PSF, not to the pupil geometry.\n        # This will set a default Ideal or a measured rotation, for example,\n        # and include pixel scale changes due to pupil distortion.\n        # Separating detector tilt pixel scale effects from pupil distortion effects is \n        # yet to be determined... see comments in Affine class definition.\n        # AS AZG 2018 08 15 Ann Arbor\n        if affine2d is None:\n            self.affine2d = utils.Affine2d(mx=1.0,my=1.0, \n                                           sx=0.0,sy=0.0, \n                                           xo=0.0,yo=0.0, name=\"Ideal\")\n        else:\n            self.affine2d = affine2d\n\n        # finding centroid from phase slope only considered cv_phase data \n        # when cv_abs data exceeds this cvsupport_threshold.  \n        # Absolute value of cv data normalized to unity maximum\n        # for the threshold application.\n        # Data reduction gurus: tweak the threshold value with experience...\n        # Gurus: tweak cvsupport with use...\n        self.cvsupport_threshold = {\"F277W\":0.02, \"F380M\": 0.02, \"F430M\": 0.02, \"F480M\": 0.02}\n        if self.verbose: show_cvsupport_threshold(self)\n        self.threshold = self.cvsupport_threshold[filt]\n\n\n    def set_pscale(self, pscalex_deg=None, pscaley_deg=None):\n        \"\"\"\n        Override pixel scale in header\n        \"\"\"\n        if pscalex_deg is not None:\n            self.pscalex_deg = pscalex_deg\n        if pscaley_deg is not None:\n            self.pscaley_deg = pscaley_deg\n        self.pscale_mas = 0.5 * (pscalex_deg +  pscaley_deg) * (60*60*1000)\n        self.pscale_rad = utils.mas2rad(self.pscale_mas)\n\n    def read_data(self, fn, mode=\"slice\"):\n        # mode options are slice or UTR\n        # for single slice data, need to read as 3D (1, npix, npix)\n        # for utr data, need to read as 3D (ngroup, npix, npix)\n        # fix bad pixels using DQ extension and LPL local averaging, \n        # but send bad pixel array down to where fringes are fit so they can be ignored.\n        # For perfectly noiseless data we add GFaussian zero mean self.noise std dev\n        # to imagge data.  Then std devs don't cause plot crashes with limits problems.\n        \n        with fits.open(fn, memmap=False, do_not_scale_image_data=True) as fitsfile:\n            # use context manager, memmap=False, deepcopy to avoid memory leaks\n            scidata = copy.deepcopy(fitsfile[1].data)\n            if self.noise is not None: scidata += np.random.normal(0, self.noise, scidata.shape)\n        \n            # usually DQ ext in MAST file... make it non-fatal for DQ to be missing\n            try:\n                bpdata=copy.deepcopy(fitsfile['DQ'].data).astype(np.uint32) # bad pixel extension, forced to uint32\n                self.bpexist = True\n                dqmask = bpdata & self.bpval[\"DO_NOT_USE\"] == self.bpval[\"DO_NOT_USE\"] #\n                del bpdata # free memory\n\n                # True => driver wants to omit using pixels with dqflag raised in fit,\n                if self.usedq == True:\n                    print('InstrumentData.NIRISS.read_data: will not use flagged DQ pixels in fit')\n            except Exception as e:\n                print('InstrumentData.NIRISS.read_data: raised exception', e)\n                self.bpexist = False\n                dqmask = np.zeros(scidata.shape, dtype=np.uint32) # so it doesn't break if issues with DQ data\n\n            if scidata.ndim == 3:  #len(scidata.shape)==3:\n                print(\"read_data() input: 3D cube\")\n\n                # Truncate all but the first few slices od data and DQ array for rapid development\n                if self.firstfew is not None:\n                    if scidata.shape[0] > self.firstfew:\n                        scidata = scidata[:self.firstfew, :, :]\n                        dqmask = dqmask[:self.firstfew, :, :]\n                # 'nwav' name (historical) is actually number of data slices in the 3Dimage cube\n                self.nwav=scidata.shape[0]\n                [self.wls.append(self.wls[0]) for f in range(self.nwav-1)]\n\n            elif len(scidata.shape)==2: # 'cast' 2d array to 3d with shape[0]=1\n                print(\"'InstrumentData.NIRISS.read_data: 2D data array converting to 3D one-slice cube\")\n                scidata = np.array([scidata,])\n                dqmask = np.array([dqmask,])\n            else:\n                sys.exit(\"InstrumentData.NIRISS.read_data: invalid data dimensions for NIRISS. \\nShould have dimensionality of 2 or 3.\")\n\n            # refpix removal by trimming\n            scidata = scidata[:,4:, :] # [all slices, imaxis[0], imaxis[1]]\n            print('\\tRefpix-trimmed scidata:', scidata.shape)\n            #### fix pix using bad pixel map - runs now.  Need to sanity-check.\n            if self.bpexist:\n                # refpix removal by trimming to match image trim\n                dqmask = dqmask[:,4:, :]     # dqmask bool array to match image trimmed shape\n                print('\\tRefpix-trimmed dqmask: ', dqmask.shape)\n\n            prihdr=fitsfile[0].header\n            scihdr=fitsfile[1].header\n            # MAST header or similar kwds info for oifits writer:\n            self.updatewithheaderinfo(prihdr, scihdr)\n\n            # Directory name into which to write txt observables & optional fits diagnostic files\n            # The input fits image or cube of images file rootname is used to create the output\n            # text&fits dir, using the data file's root name as the directory name: for example,\n            # /abc/.../imdir/xyz_calints.fits  results in a directory /abc/.../imdir/xyz_calints/\n            self.rootfn =  fn.split('/')[-1].replace('.fits', '')\n        return prihdr, scihdr, scidata, dqmask\n\n\n    def cdmatrix_to_sky(self, vec, cd11, cd12, cd21, cd22):\n        \"\"\" use the global header values explicitly, for clarity \n            vec is 2d, units of pixels\n            cdij 4 scalars, conceptually 2x2 array in units degrees/pixel\n        \"\"\"\n        return np.array((cd11*vec[0] + cd12*vec[1], cd21*vec[0] + cd22*vec[1]))\n\n\n    def degrees_per_pixel(self, hdr):\n        \"\"\"\n        input: hdr:  fits data file's header with or without CDELT1, CDELT2 (degrees per pixel)\n        returns: cdelt1, cdelt2: tuple, degrees per pixel along axes 1, 2\n                         EITHER: read from header CDELT[12] keywords \n                             OR: calculated using CD matrix (Jacobian of RA-TAN, DEC-TAN degrees\n                                 to pixel directions 1,2.  No deformation included in this routine,\n                                 but the CD matric includes non-linear field distortion.\n                                 No pupil distortion or rotation here.\n                        MISSING: If keywords are missing default hardcoded cdelts are returned.\n                                 The exact algorithm may substitute this later.\n                                 Below seems good to ~5th significant figure when compared to \n                                 cdelts header values prior to replacement by cd matrix approach.\n            N.D. at stsci 11 Mar 20212\n\n            We start in Level 1 with the PC matrix and CDELT.\n            CDELTs come from the SIAF.\n\n            The PC matrix is computed from the roll angle, V3YANG and the parity.\n            The code is here\n            https://github.com/spacetelescope/jwst/blob/master/jwst/assign_wcs/util.py#L153\n\n            In the level 2 imaging pipeline, assign_wcs adds the distortion to the files.\n            At the end it computes an approximation of the entire distortion transformation\n            by fitting a polynomial. This approximated distortion is represented as SIP\n            polynomials in the FITS headers.\n\n            Because SIP, by definition, uses a CD matrix, the PC + CDELT are replaced by CD.\n\n            How to get CDELTs back?\n\n            I think once the rotation, skew and scale are in the CD matrix it's very hard to\n            disentangle them. The best way IMO is to calculate the local scale using three\n            point difference. There is a function in jwst that does this.\n\n            Using a NIRISS image as an example:\n\n            from jwst.assign_wcs import util\n            from jwst import datamodels\n\n            im=datamodels.open('niriss_image_assign_wcs.fits')\n\n            util.compute_scale(im.meta.wcs, (im.meta.wcsinfo.ra_ref, im.meta.wcsinfo.dec_ref))\n\n            1.823336635353374e-05\n\n            The function returns a constant scale. Is this sufficient for what you need or\n            do you need scales and sheer along each axis? The code in util.compute_scale can\n            help with figuring out how to get scales along each axis.\n\n            I hope this answers your question.\n        \"\"\"\n\n        if 'CD1_1' in hdr.keys() and 'CD1_2' in hdr.keys() and  \\\n             'CD2_1' in hdr.keys() and 'CD2_2' in hdr.keys():\n            cd11 = hdr['CD1_1']\n            cd12 = hdr['CD1_2']\n            cd21 = hdr['CD2_1']\n            cd22 = hdr['CD2_2']\n            # Create unit vectors in detector pixel X and Y directions, units: detector pixels\n            dxpix  =  np.array((1.0, 0.0)) # axis 1 step\n            dypix  =  np.array((0.0, 1.0)) # axis 2 step\n            # transform pixel x and y steps to RA-tan, Dec-tan degrees\n            dxsky = self.cdmatrix_to_sky(dxpix, cd11, cd12, cd21, cd22)\n            dysky = self.cdmatrix_to_sky(dypix, cd11, cd12, cd21, cd22)\n            print(\"Used CD matrix for pixel scales\")\n            return np.linalg.norm(dxsky, ord=2), np.linalg.norm(dysky, ord=2)\n        elif 'CDELT1' in hdr.keys() and 'CDELT2' in hdr.keys():\n            return hdr['CDELT1'], hdr['CDELT2']\n            print(\"Used CDDELT[12] for pixel scales\")\n        else:\n            print('InstrumentData.NIRISS: Warning: NIRISS pixel scales not in header.  Using 65.6 mas in deg/pix')\n            return 65.6/(60.0*60.0*1000), 65.6/(60.0*60.0*1000)\n\n    \n    def updatewithheaderinfo(self, ph, sh):\n        \"\"\" input: primary header, science header MAST\"\"\"\n\n        # The info4oif_dict will get pickled to disk when we write txt files of results.\n        # That way we don't drag in objects like InstrumentData into code that reads text results\n        # and writes oifits files - a simple built-in dictionary is the only object used in this transfer.\n        info4oif_dict = {}\n        info4oif_dict['telname'] = self.telname\n\n        info4oif_dict['filt'] = self.filt\n        info4oif_dict['lam_c'] = self.lam_c\n        info4oif_dict['lam_w'] = self.lam_w\n        info4oif_dict['lam_bin'] = self.lam_bin\n\n\n        # Target information - 5/21 targname UNKNOWN in nis019 rehearsal data\n        # Name in the proposal always non-trivial, targname still UNKNOWN...:\n        if ph[\"TARGNAME\"] == 'UNKNOWN': objname = ph['TARGPROP']\n        else: objname = ph['TARGNAME'] # allegedly apt name for archive, standard form\n        #\n        # if target name has confusing-to-astroquery dash\n        self.objname =  objname.replace('-', ' '); info4oif_dict['objname'] = self.objname\n        # AB Dor, ab dor, AB DOR,  ab  dor are all acceptable.\n        #\n        self.ra = ph[\"TARG_RA\"]; info4oif_dict['ra'] = self.ra\n        self.dec = ph[\"TARG_DEC\"]; info4oif_dict['dec'] = self.dec\n\n        # / axis 1 DS9 coordinate of the reference pixel (always POS1)\n        # / axis 2 DS9 coordinate of the reference pixel (always POS1)\n        self.crpix1 = sh[\"CRPIX1\"]; info4oif_dict['crpix1'] = self.crpix1\n        self.crpix2 = sh[\"CRPIX2\"]; info4oif_dict['crpix2'] = self.crpix2\n        # need Paul Goudfrooij's table for actual crval[1,2] for true pointing to detector pixel coords (DS9)\n\n        self.instrument = ph[\"INSTRUME\"]; info4oif_dict['instrument'] = self.instrument\n        self.pupil =  ph[\"PUPIL\"]; info4oif_dict['pupil'] = self.pupil\n        # \"ImPlaneIA internal mask name\" - oifwriter looks for 'mask'...\n        self.arrname = \"jwst_g7s6c\"  # implaneia internal name - historical\n        info4oif_dict['arrname'] = 'g7s6' # for oif\n        info4oif_dict['mask'] = info4oif_dict['arrname']  # Soulain mask goes into oif arrname\n\n        # if data was generated on the average pixel scale of the header\n        # then this is the right value that gets read in, and used in fringe fitting\n        pscalex_deg, pscaley_deg = self.degrees_per_pixel(sh)\n        #\n        info4oif_dict['pscalex_deg'] = pscalex_deg\n        info4oif_dict['pscaley_deg'] = pscaley_deg\n        # Whatever we did set is averaged for isotropic pixel scale here\n        self.pscale_mas = 0.5 * (pscalex_deg + pscaley_deg) * (60*60*1000); \\\n        info4oif_dict['pscale_mas'] = self.pscale_mas\n        self.pscale_rad = utils.mas2rad(self.pscale_mas); info4oif_dict['pscale_rad'] = self.pscale_rad\n\n        self.mask = NRM_mask_definitions(maskname=self.arrname, chooseholes=self.chooseholes,\n                                         holeshape=self.holeshape) # for STAtions x y in oifs\n\n        self.date = ph[\"DATE-OBS\"] + \"T\" + ph[\"TIME-OBS\"]; info4oif_dict['date'] = self.date\n        datestr = ph[\"DATE-OBS\"]\n        self.year = datestr[:4]; info4oif_dict['year'] = self.year\n        self.month = datestr[5:7]; info4oif_dict['month'] = self.month\n        self.day = datestr[8:10]; info4oif_dict['day'] = self.day\n        self.parangh= sh[\"ROLL_REF\"]; info4oif_dict['parangh'] = self.parangh\n        self.pa = sh[\"PA_V3\"]; info4oif_dict['pa'] = self.pa\n        self.vparity = sh[\"VPARITY\"]; info4oif_dict['vparity'] = self.vparity\n\n        # An INTegration is NGROUPS \"frames\", not relevant here but context info.\n        # 2d => \"cal\" file combines all INTegrations (ramps)\n        # 3d=> \"calints\" file is a cube of all INTegrations (ramps)\n        if sh[\"NAXIS\"] == 2:\n            # all INTegrations or 'ramps'\n            self.itime = ph[\"EFFINTTM\"] * ph[\"NINTS\"]; info4oif_dict['itime'] = self.itime\n        elif sh[\"NAXIS\"] == 3:\n            # each slice is one INTegration or 'ramp'\n            self.itime = ph[\"EFFINTTM\"]; info4oif_dict['itime'] = self.itime\n\n\n        np.set_printoptions(precision=5, suppress=True, linewidth=160, \n                            formatter={'float': lambda x: \"%10.5f,\" % x})\n        self.v3i_yang = sh['V3I_YANG']  # Angle from V3 axis to Ideal y axis (deg)\n        # rotate mask hole center coords by PAV3 # RAC 2021\n        ctrs_sky = self.mast2sky()\n        oifctrs = np.zeros(self.mask.ctrs.shape)\n        oifctrs[:,0] = ctrs_sky[:,1].copy() * -1\n        oifctrs[:,1] = ctrs_sky[:,0].copy() * -1\n        info4oif_dict['ctrs_eqt'] = oifctrs # mask centers rotated by PAV3 (equatorial coords)\n        info4oif_dict['ctrs_inst'] = self.mask.ctrs # as-built instrument mask centers\n        info4oif_dict['hdia'] = self.mask.hdia\n        info4oif_dict['nslices'] = self.nwav # nwav: number of image slices or IFU cube slices - AMI is imager\n        self.info4oif_dict = info4oif_dict # save it when writing extracted observables txt\n\n\n    # rather than calling InstrumentData in the niriss example just to reset just call this routine\n    def reset_nwav(self, nwav):\n        print(\"InstrumentData.NIRISS: \", \"Resetting InstrumentData instantiation's nwave to\", nwav)\n        self.nwav = nwav\n\n\n    def jwst_dqflags(self):\n        \"\"\" \n            dqdata is a 2d (32-bit U?)INT array from the DQ extension of the input file.\n            We ignore all data with a non-zero DQ flag.  I copied all values from a 7.5 build jwst...\n            but we ignore any non-zero flag meaning, and ignore the pixel in fringe-fitting\n            The refpix are non-zero DQ, btw...\n            I changed \"pixel\" to self.pbval and \"group\" to self.bpgroup. We may use these later, \n            so here they are but initially we just discriminate between good (zero value) and non-good.\n        \"\"\"\n\n        \"\"\" JWST Data Quality Flags\n            The definitions are documented in the JWST RTD:\n            https://jwst-pipeline.readthedocs.io/en/latest/jwst/references_general/references_general.html#data-quality-flags \n        \"\"\"\n        \"\"\" JWST Data Quality Flags\n        The definitions are documented in the JWST RTD:\n        https://jwst-pipeline.readthedocs.io/en/latest/jwst/references_general/references_general.html#data-quality-flags\n        Implementation\n        -------------\n        The flags are implemented as \"bit flags\": Each flag is assigned a bit position\n        in a byte, or multi-byte word, of memory. If that bit is set, the flag assigned\n        to that bit is interpreted as being set or active.\n        The data structure that stores bit flags is just the standard Python `int`,\n        which provides 32 bits. Bits of an integer are most easily referred to using\n        the formula `2**bit_number` where `bit_number` is the 0-index bit of interest.\n        2**n is gauche but not everyone loves 1<<n\n\n\n        Rachel uses:\n        from jwst.datamodels import dqflags\n        DO_NOT_USE = dqflags.pixel[\"DO_NOT_USE\"]\n        dqmask = pxdq0 & DO_NOT_USE == DO_NOT_USE\n        pxdq = np.where(dqmask, pxdq0, 0)\n\n        \"\"\"\n\n        # Pixel-specific flags\n        self.bpval = {\n                 'GOOD':             0,      # No bits set, all is good\n                 'DO_NOT_USE':       2**0,   # Bad pixel. Do not use.\n                 'SATURATED':        2**1,   # Pixel saturated during exposure\n                 'JUMP_DET':         2**2,   # Jump detected during exposure\n                 'DROPOUT':          2**3,   # Data lost in transmission\n                 'OUTLIER':          2**4,   # Flagged by outlier detection. Was RESERVED_1\n                 'RESERVED_2':       2**5,   #\n                 'RESERVED_3':       2**6,   #\n                 'RESERVED_4':       2**7,   #\n                 'UNRELIABLE_ERROR': 2**8,   # Uncertainty exceeds quoted error\n                 'NON_SCIENCE':      2**9,   # Pixel not on science portion of detector\n                 'DEAD':             2**10,  # Dead pixel\n                 'HOT':              2**11,  # Hot pixel\n                 'WARM':             2**12,  # Warm pixel\n                 'LOW_QE':           2**13,  # Low quantum efficiency\n                 'RC':               2**14,  # RC pixel\n                 'TELEGRAPH':        2**15,  # Telegraph pixel\n                 'NONLINEAR':        2**16,  # Pixel highly nonlinear\n                 'BAD_REF_PIXEL':    2**17,  # Reference pixel cannot be used\n                 'NO_FLAT_FIELD':    2**18,  # Flat field cannot be measured\n                 'NO_GAIN_VALUE':    2**19,  # Gain cannot be measured\n                 'NO_LIN_CORR':      2**20,  # Linearity correction not available\n                 'NO_SAT_CHECK':     2**21,  # Saturation check not available\n                 'UNRELIABLE_BIAS':  2**22,  # Bias variance large\n                 'UNRELIABLE_DARK':  2**23,  # Dark variance large\n                 'UNRELIABLE_SLOPE': 2**24,  # Slope variance large (i.e., noisy pixel)\n                 'UNRELIABLE_FLAT':  2**25,  # Flat variance large\n                 'OPEN':             2**26,  # Open pixel (counts move to adjacent pixels)\n                 'ADJ_OPEN':         2**27,  # Adjacent to open pixel\n                 'UNRELIABLE_RESET': 2**28,  # Sensitive to reset anomaly\n                 'MSA_FAILED_OPEN':  2**29,  # Pixel sees light from failed-open shutter\n                 'OTHER_BAD_PIXEL':  2**30,  # A catch-all flag\n                 'REFERENCE_PIXEL':  2**31,  # Pixel is a reference pixel\n        }\n\n        # Group-specific flags. Once groups are combined, these flags\n        # are equivalent to the pixel-specific flags.\n        self.bpgroup = {\n                 'GOOD':       self.bpval['GOOD'],\n                 'DO_NOT_USE': self.bpval['DO_NOT_USE'],\n                 'SATURATED':  self.bpval['SATURATED'],\n                 'JUMP_DET':   self.bpval['JUMP_DET'],\n                 'DROPOUT':    self.bpval['DROPOUT'],\n        }\n\n\n    def mast2sky(self):\n        \"\"\"\n        Rotate hole center coordinates:\n            Clockwise by the V3 position angle - V3I_YANG from north in degrees if VPARITY = -1\n            Counterclockwise by the V3 position angle - V3I_YANG from north in degrees if VPARITY = 1\n        Hole center coords are in the V2, V3 plane in meters.\n        Return rotated coordinates to be put in info4oif_dict.\n        implane2oifits.ObservablesFromText uses these to calculate baselines.\n        \"\"\"\n        pa = self.pa\n        mask_ctrs = copy.deepcopy(self.mask.ctrs)\n        # rotate by an extra 90 degrees (RAC 9/21)\n        # these coords are just used to orient output in OIFITS files\n        # NOT used for the fringe fitting itself\n        mask_ctrs = utils.rotate2dccw(mask_ctrs,np.pi/2.)\n        vpar = self.vparity # Relative sense of rotation between Ideal xy and V2V3\n        v3iyang = self.v3i_yang\n        rot_ang = pa - v3iyang # subject to change!\n\n        if pa != 0.0:\n            # Using rotate2sccw, which rotates **vectors** CCW in a fixed coordinate system,\n            # so to rotate coord system CW instead of the vector, reverse sign of rotation angle.  Double-check comment\n            if vpar == -1:\n                # rotate clockwise  <rotate coords clockwise?>\n                ctrs_rot = utils.rotate2dccw(mask_ctrs, np.deg2rad(-rot_ang))\n                print(f'InstrumentData.mast2sky: Rotating mask hole centers clockwise by {rot_ang:.3f} degrees')\n            else:\n                # counterclockwise  <rotate coords counterclockwise?>\n                ctrs_rot = utils.rotate2dccw(mask_ctrs, np.deg2rad(rot_ang))\n                print('InstrumentData.mast2sky: Rotating mask hole centers counterclockwise by {rot_ang:.3f} degrees')\n        else:\n            ctrs_rot = mask_ctrs\n        return ctrs_rot\n", "meta": {"hexsha": "3ab46632f2488904ed4e0bf9faed6b2a0899ecf6", "size": 29326, "ext": "py", "lang": "Python", "max_stars_repo_path": "nrm_analysis/InstrumentData.py", "max_stars_repo_name": "vandalt/ImPlaneIA", "max_stars_repo_head_hexsha": "72b22e487ef45a8a665e4a6a88a91e99e382fdd0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nrm_analysis/InstrumentData.py", "max_issues_repo_name": "vandalt/ImPlaneIA", "max_issues_repo_head_hexsha": "72b22e487ef45a8a665e4a6a88a91e99e382fdd0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nrm_analysis/InstrumentData.py", "max_forks_repo_name": "vandalt/ImPlaneIA", "max_forks_repo_head_hexsha": "72b22e487ef45a8a665e4a6a88a91e99e382fdd0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.6493955095, "max_line_length": 136, "alphanum_fraction": 0.6009002251, "include": true, "reason": "import numpy,from astropy", "num_tokens": 7486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.331119752830196, "lm_q1q2_score": 0.19122012258090978}}
{"text": "import argparse\nimport glob\nimport itertools\nfrom nuosc.tools import cache, progress\nimport numpy\nimport ROOT\nimport math\nimport simplot.io\nimport nuosc.model\nfrom simplot import histogram\nimport matplotlib.pyplot as plt \nimport os\nimport scipy.stats\nimport matplotlib\nfrom nuosc.model import constants, runtime\nimport collections\nimport re\nimport scipy.interpolate\n\n###############################################################################\n\nGenEvFile = collections.namedtuple(\"GenEvFile\", [\"polarity\", \"ndid\", \"r\", \"z\", \"n\", \"orientation\"])\nBeamFile = collections.namedtuple(\"BeamFile\", [\"polarity\"])\n\n###############################################################################\n\nclass FileNameParser:\n    def __init__(self, patterns):\n        self._flist = _expandfilelist(patterns)\n        \n    def __call__(self):\n        r = None\n        fname = self._flist[0]\n        for f in [self._parse_genev, self._parse_beam]:\n            r = f(fname)\n            if r is not None:\n                break\n        #check for success\n        if r is None:\n            raise ValueError(\"cannot parse \", fname)\n        return r\n    \n    def _parse_genev(self, fname):\n        pat = \"genev_(.*?)_(.*?)_(.*?)_.(.*?)_z(.*?)_(.)_(.*?).root\"\n        match = re.search(pat, fname)\n        if not match:\n            return None\n        polarity = match.group(1)\n        det = match.group(2)\n        ndid = nuosc.model.constants.DetectorId.tostring(det)\n        geo = match.group(3)\n        r = float(int(match.group(4))) / 100.0\n        z = float(int(match.group(5))) / 100.0\n        orientation = match.group(6)\n        n = match.group(7)\n        return GenEvFile(polarity=polarity,\n                  ndid=ndid,\n                  r=r,\n                  z=z,\n                  n=n,\n                  orientation=orientation,\n                  )\n        \n    def _parse_beam(self, fname):\n        pat = \"merged_beamfiles_(.*?).root\"\n        match = re.search(pat, fname)\n        if not match:\n            return None\n        polarity = match.group(1)\n        return BeamFile(polarity=polarity)\n\n###############################################################################\n\nclass Record:\n    pdg = \"pdg\"\n    reactioncode = \"reactioncode\"\n    enu = \"enu\"\n    x = \"x\"\n    y = \"y\"\n    z = \"z\"\n    weight = \"weight\"\n    ndid = \"ndid\"\n    \n    ALL = (pdg, reactioncode, enu, x, y, z, weight)\n    \n    _axis_labels = {pdg : \"PDG code\",\n                    reactioncode : \"NEUT reaction code\",\n                    enu : r\"$E_{\\nu}$ [GeV]\",\n                    x : \"$x$ [m]\",\n                    y : \"$y$ [m]\",\n                    z : \"$z$ [m]\",\n                    weight : \"event weight\",\n                    ndid : \"near detector ID\",\n                    }\n\n    @classmethod\n    def label(cls, field):\n        return cls._axis_labels[field]\n\ndef _expandfilelist(filelist):\n    return list(itertools.chain.from_iterable(map(glob.glob, filelist)))\n\n###############################################################################\n\nclass NeutEventReader:\n    \n    def __call__(self, event):\n        x, y, z = self._pos(event)\n        return [event.StdHepPdg[0],\n                event.NEneutmode,\n                self._enu(event),\n                x,\n                y,\n                z,\n                1.0,\n                0.0,\n                ]\n        \n    def _pos(self, event):\n        r = event.EvtVtx\n        return (r[0],\n                r[1],\n                r[2],\n                )\n        \n    def _convert2Darray(self, arr, nrows, ncols):\n        out = numpy.zeros(shape=(nrows,ncols))\n        for i in xrange(nrows):\n            for j in xrange(ncols):\n                out[i, j] = arr[(i * ncols) + j]\n        return out\n        \n    def _enu(self, event):\n        arr = self._convert2Darray(event.StdHepP4, event.StdHepN, 4)\n        return arr[0][3]\n        \n    def indices(self):\n        return [Record.pdg,\n                Record.reactioncode,\n                Record.enu,\n                Record.x,\n                Record.y,\n                Record.z,\n                Record.weight,\n                Record.ndid,\n                ]\n\n\n###############################################################################\n\nclass FluxEventReader:\n    \n    def __call__(self, event):\n        return [event.pdg,\n                0.0,\n                event.enu,\n                event.xnu,\n                event.ynu,\n                0.0,\n                event.norm,\n                event.ndid,\n                ]\n        \n    def indices(self):\n        return [Record.pdg,\n                Record.reactioncode,\n                Record.enu,\n                Record.x,\n                Record.y,\n                Record.z,\n                Record.weight,\n                Record.ndid,\n                ]\n\n###############################################################################\n\nclass Reader(object):\n    def __init__(self, filelist, treename, func, prescale=1):\n        self._filenames = _expandfilelist(filelist)\n        self._func = func\n        self._treename = treename\n        self._prescale = prescale\n        \n    def read(self):\n        indices = self._func.indices()\n        uniquestr = \"_\".join(indices \n                             + self._filenames\n                             + [type(self._func).__name__,\n                                str(self._prescale),\n                                ]\n                             )\n        cachetool = cache.CacheNumpy(uniquestr, prefix=\"tmp_verify_genev\")\n        if cachetool.exists():\n            data = cachetool.read()\n        else:\n            data = self._load_data()\n            cachetool.write(data)\n        indices = dict(zip(indices, xrange(len(indices))))\n        return indices, data\n    \n    def _load_data(self):\n        data = []\n        for fname in self._filenames:\n            tfile = ROOT.TFile(fname, \"READ\")\n            treename = self._treename\n            tree = tfile.Get(treename)\n            if not tree:\n                raise Exception(\"Input file does not contain tree with name\", treename, fname)\n            for event in tree:\n                data.append(self._func(event))\n        print len(data), data[0]\n        data = numpy.array(data)\n        return data\n    \n    def _iterprescale(self, tree, prescale):\n        n = tree.GetEntries()\n        for i in xrange(n):\n            if i % prescale == 0:\n                tree.GetEntry(i)\n                yield tree\n                \n    def _load_data(self):\n        data = []\n        for fname in self._filenames:\n            tfile = ROOT.TFile(fname, \"READ\")\n            treename = self._treename\n            tree = tfile.Get(treename)\n            if not tree:\n                raise Exception(\"Input file does not contain tree with name\", treename, fname)\n            prescale = self._prescale\n            iterevents = progress.printProgress(\"Reading \" + treename, tree.GetEntries()/prescale, self._iterprescale(tree, prescale))\n            for event in iterevents:\n                data.append(self._func(event))\n        print len(data), data[0]\n        data = numpy.array(data)\n        return data\n\n###############################################################################\n\nclass NeutFileReader(Reader):\n    def __init__(self, filelist):\n        super(NeutFileReader, self).__init__(filelist, \"nRooTracker\", NeutEventReader(), prescale=1)\n\n###############################################################################\n\nclass FluxFileReader(Reader):\n    def __init__(self, filelist):\n        super(FluxFileReader, self).__init__(filelist, \"flux\", FluxEventReader(), prescale=20)\n        \n\n###############################################################################\n\nclass PlotInteractionRate:\n    def __init__(self, outdir, indices, data, scale_to_m=1.0, namemod=None, numbins=25):\n        self._scale_to_m = scale_to_m\n        self._outdir = outdir\n        self._data = data\n        self._indices = indices\n        self._namemod = namemod\n        self._numbins = numbins\n    \n    def __iter__(self):\n        if len(self._data):\n            for p in self._plot_xy_hist():\n                yield p\n            for p in self._plot_xz_hist():\n                yield p\n#             for p in self._plot_histograms():\n#                 yield p\n    \n    def _plot_histograms(self):\n        for var in Record.ALL:\n            fig = plt.figure()\n            d = self._data[:, self._indices[var]]\n            weights = self._data[:, self._indices[Record.weight]]\n            y, xbinning = numpy.histogram(d, weights=weights)\n            ax = fig.add_subplot(1, 1, 1)\n            histogram.plot_hist_points(ax, xbinning, y)\n            ax.set_xlabel(Record.label(var))\n            ax.set_ylabel(\"N events\")\n            name = os.sep.join((self._outdir, \"hist_1d\", var))\n            if self._namemod is not None:\n                name += \"_\" + self._namemod\n            yield name, fig\n            plt.close(fig)\n    \n    def _plot_xy_hist(self):\n        fig = plt.figure()\n        name = os.sep.join((self._outdir, \"hist_2d\", \"xy\"))\n        if self._namemod is not None:\n            name += \"_\" + self._namemod\n        ax = fig.add_subplot(1, 1, 1)\n        ax.set_xlabel(Record.label(Record.x))\n        ax.set_ylabel(Record.label(Record.y))\n        #Get data\n        dx = self._data[:, self._indices[Record.x]]\n        dy = self._data[:, self._indices[Record.y]]\n        #scale dx and dy\n        dx *= self._scale_to_m\n        dy *= self._scale_to_m\n        weights = self._data[:, self._indices[Record.weight]]\n        #Plot data\n        xmin = -10.0\n        xmax = 10.0\n        prange = ((xmin, xmax), (xmin, xmax))\n        ret = ax.hist2d(dx, dy, bins=self._numbins, weights=weights, cmap=matplotlib.cm.get_cmap(\"hot\"), range=prange)\n        img = ret[-1]\n        fig.colorbar(img)\n        yield name, fig\n\n    def _plot_xz_hist(self):\n        fig = plt.figure()\n        name = os.sep.join((self._outdir, \"hist_2d\", \"xz\"))\n        if self._namemod is not None:\n            name += \"_\" + self._namemod\n        ax = fig.add_subplot(1, 1, 1)\n        ax.set_xlabel(Record.label(Record.x))\n        ax.set_ylabel(Record.label(Record.z))\n        #Get data\n        dx = self._data[:, self._indices[Record.x]]\n        dz = self._data[:, self._indices[Record.z]]\n        #scale dx and dy\n        dx *= self._scale_to_m\n        dz *= self._scale_to_m\n        weights = self._data[:, self._indices[Record.weight]]\n        #Plot data\n        #xmin = -4.0\n        #xmax = 4.0\n        #prange = ((xmin, xmax), (xmin, xmax))\n        ret = ax.hist2d(dx, dz, bins=self._numbins, weights=weights, cmap=matplotlib.cm.get_cmap(\"hot\"), )#range=prange)\n        img = ret[-1]\n        fig.colorbar(img)\n        yield name, fig\n    \n#     def _plot_xy_kernel(self):\n#         fig = plt.figure()\n#         ax = fig.add_subplot(1, 1, 1)\n#         ax.set_xlabel(Record.label(Record.x))\n#         ax.set_ylabel(Record.label(Record.y))\n#         #Get data\n#         dx = self._data[:, self._indices[Record.x]]\n#         dy = self._data[:, self._indices[Record.y]]\n#         #Plot histogram\n#         heatmap, xedges, yedges = numpy.histogram2d(dx, dy, bins=20)\n#         extent = [min(xedges), max(xedges), min(yedges), max(yedges)]\n#         ax.imshow(heatmap, extent=extent, interpolation=\"nearest\")\n#         dataset = numpy.row_stack((dx, dy))\n#         x = numpy.linspace(min(dx), max(dx))\n#         y = numpy.linspace(min(dy), max(dy))\n#         X, Y = numpy.meshgrid(x, y)\n#         kernel = scipy.stats.gaussian_kde(dataset)\n#         Z = kernel(numpy.row_stack((X.ravel(), Y.ravel()))).reshape(X.shape)\n#         ax.contour(X, Y, Z, color=\"black\", linecolor=\"black\")\n#         name = os.sep.join((\"hist_2d\", \"xy\"))\n#         yield name, fig\n\n###############################################################################\n\nclass Flux:\n    def __init__(self, data, weights):\n        #bin the data\n        nbins = 100.0\n        enurange = (0.0, 5.0)\n        hist, edge = numpy.histogram(data, bins=nbins, range=enurange, density=True, weights=weights)\n        y = hist\n        x = (edge[1:] + edge[:-1] ) / 2.0\n        self.f = scipy.interpolate.interp1d(x, y)\n    \n    def __call__(self, x):\n        return self.f(x)\n\n###############################################################################\n\nclass Xsec:\n    def __init__(self):\n        pass\n    \n    def __call__(self, x):\n        return 1.0\n\n###############################################################################\n\nclass FluxIntXsec:\n    def __init__(self, flux, xsec):\n        enu = numpy.linspace(start=0.01, stop=5.0, num=1000)\n        ff = numpy.vectorize(flux)\n        fa = ff(enu)\n        xf = numpy.vectorize(xsec)\n        xa = xf(enu)\n        avg = numpy.average(xa, weights=fa)\n        self._result = avg\n    \n    def __call__(self):\n        return self._result\n\n###############################################################################\n\nclass Ratio(object):\n    def __init__(self, numerator, denominator):\n        self._n = numerator\n        self._d = denominator\n        try:\n            self._r = float(self._n) / float(self._d)\n        except ZeroDivisionError:\n            self._r = 0.0\n    \n    def __div__(self, rhs):\n        return Ratio(self, rhs)\n    \n    def __sub__(self, rhs):\n        return Difference(self, rhs)\n    \n    def __float__(self):\n        return self._r\n        \n    def __str__(self):\n        #return \"{0:.3e} +- {1:.3e}\".format(self._r, self.error())\n        return \"{0:.3f} +- {1:.3f}\".format(self._r, self.error())\n#         return \"\\n\".join((\"Num=\"+str(self._n),\n#                          \"Den=\"+str(self._d),\n#                          \"R=\"+str(self._r),\n#                          ))\n        \n    def error(self):\n        err = 0.0\n        try:\n            n = float(self._n)\n            d = float(self._d)\n            ne = self._n.error()\n            de = self._d.error()\n            err = self._r * math.sqrt((ne/n)**2 + (de/d)**2) \n        except AttributeError:\n            #assume binomial error\n            eff = self._r\n            err = 0.0\n            if self._d > 0:\n                var = eff * (1.0 - eff) / float(self._n)\n            err = math.sqrt(var)\n        return err\n    \nclass Difference(Ratio):\n    def __init__(self, numerator, denominator):\n        self._n = numerator\n        self._d = denominator\n        self._r = float(self._n) - float(self._d)\n        \n    def error(self):\n        err = 0.0\n        n = float(self._n)\n        d = float(self._d)\n        ne = self._n.error()\n        de = self._d.error()\n        err = math.sqrt((ne)**2 + (de)**2)\n        return err\n\n###############################################################################\n\n\nclass PlotFluxIntXsec:\n    def __init__(self, neutindices, neutdata, fluxindices, fluxdata, scale_to_m = 1.0/100.0):\n        self._neut_indices = neutindices\n        self._neut_data = neutdata\n        self._fluxindices = fluxindices\n        self._fluxdata = fluxdata\n        self._scale_to_m = scale_to_m\n    \n    def __iter__(self):\n        rad = 4.0\n        outer_xmax = rad / math.sqrt(2.0)\n        outer_ymax = outer_xmax\n        outer_xmin = -outer_xmax\n        outer_ymin = -outer_ymax\n        #get fiducial flux\n        fvflux = _spacecut(self._fluxindices, self._fluxdata, outer_xmin, outer_xmax, outer_ymin, outer_ymax, scale_to_m=self._scale_to_m)\n        fvneut = _spacecut(self._neut_indices, self._neut_data, outer_xmin, outer_xmax, outer_ymin, outer_ymax)\n        #divide square into quadrants\n        rad = 4.0\n        outer_xmax = rad / math.sqrt(2.0)\n        outer_ymax = outer_xmax\n        outer_xmin = -outer_xmax\n        outer_ymin = -outer_ymax\n        for name, xmin, xmax, ymin, ymax in [(\"(+x, +y)\", 0.0, outer_xmax, 0.0, outer_ymax),\n                                             (\"(+x, -y)\", 0.0, outer_xmax, outer_ymin, 0.0),\n                                             (\"(-x, +y)\", outer_xmin, 0.0, 0.0, outer_ymax),\n                                             (\"(-x, -y)\",outer_xmin, 0.0, outer_ymin, 0.0),\n                                       \n                                       \n                                       ]:\n            #print \"Plotting \", name\n            for p in self._plot(xmin, xmax, ymin, ymax, fvflux, fvneut, self._fluxindices, self._neut_indices):\n                yield p\n        return\n        \n    def _plot(self, xmin, xmax, ymin, ymax, fluxdata, neut_data, fluxindices, neut_indices):\n        fd = _spacecut(fluxindices, fluxdata, xmin, xmax, ymin, ymax, scale_to_m=self._scale_to_m)\n        gd = _spacecut(neut_indices, neut_data, xmin, xmax, ymin, ymax)\n#         #calc flux integrated xsec\n#         flux = Flux(fd[:, Record.enu], fd[:, Record.weight])\n#         xsec = Xsec()\n#         fluxintxsec = FluxIntXsec(flux, xsec)\n        #yield figname, fig\n        expected_frac = Ratio(self._sumflux(fluxindices, fd), self._sumflux(fluxindices, fluxdata))\n        observed_frac = Ratio(len(gd), len(neut_data))\n        diff = observed_frac - expected_frac\n        #print \"expected=\", str(expected_frac), \", observed=\", str(observed_frac),\", diff=\",(diff)\n        l = [(100.0*float(v), 100.0*v.error()) for v in (expected_frac, observed_frac, diff)]\n        for t in l: \n            print t,\",\"\n        yield None\n        \n    def _sumflux(self, indices, fd):\n        return numpy.sum(fd[:, indices[Record.weight]])\n        \ndef _spacecut(indices, fd, xmin, xmax, ymin, ymax, scale_to_m=1.0):\n        xmin, xmax, ymin, ymax = [[v / scale_to_m] for v in [xmin, xmax, ymin, ymax]]\n        #x-cut\n        ix = indices[Record.x]\n        fd = fd[fd[:, ix] > xmin]\n        fd = fd[fd[:, ix] < xmax]\n        #y cut\n        iy = indices[Record.y]\n        fd = fd[fd[:, iy] > ymin]\n        fd = fd[fd[:, iy] < ymax]\n        return fd\n            \n\n###############################################################################\n\ndef plot_interaction_rate(args):\n    parser = FileNameParser(args.patterns)\n    f = parser()\n    reader = NeutFileReader(args.patterns)\n    indices, data = reader.read()\n    out = simplot.io.FigureWriter()\n    name = \"_\".join([f.polarity, f.ndid])\n    plotter = PlotInteractionRate(\"evgen\", indices, data,\n                                  namemod=name,\n                                  numbins=100,\n                                  )\n    out(plotter)\n    return\n\n###############################################################################\n\ndef plot_flux(args):\n    ntuple = nuosc.model.beam.FluxNtuple(runtime.getcontext().beamcontext)\n    reader = FluxFileReader([ntuple.filename()])\n    indices, data = reader.read()\n    DetectorId = nuosc.model.beam.constants.DetectorId\n    out = simplot.io.FigureWriter()\n    for polarity in nuosc.model.constants.Polarity.ALL:\n        for ndid in DetectorId.ALL:\n            #filter out particular near detector\n            indid = DetectorId.toint(ndid)\n            fluxdata = data[data[:, indices[Record.ndid]] == indid]\n            if len(fluxdata) > 0:\n                if polarity > 0:\n                    fluxdata = fluxdata[fluxdata[:, indices[Record.pdg]] > 0]\n                else:\n                    fluxdata = fluxdata[fluxdata[:, indices[Record.pdg]] < 0]\n            detstr = DetectorId.tostring(ndid)\n            cm_to_m = 1.0 / 100.0\n            name = \"_\".join((detstr, str(polarity)))\n            plotter = PlotInteractionRate(\"flux\", indices, fluxdata, \n                                          scale_to_m=cm_to_m, \n                                          namemod=name,\n                                          numbins=10,\n                                          )\n            out(plotter)\n\n###############################################################################\n\ndef plot_flux_int_xsec(args):\n    parser = FileNameParser(args.patterns)\n    f = parser()\n    #load neut data\n    reader = NeutFileReader(args.patterns)\n    neutindices, neutdata = reader.read()\n    #load flux data\n    ntuple = nuosc.model.beam.FluxNtuple(runtime.getcontext().beamcontext)\n    reader = FluxFileReader([ntuple.filename()])\n    fluxindices, fluxdata = reader.read()\n    DetectorId = nuosc.model.beam.constants.DetectorId\n    ndid = DetectorId.toint(f.ndid)\n    #filter out particular near detector\n    fluxdata = fluxdata[fluxdata[:, fluxindices[Record.ndid]] == ndid]\n    #make plot\n    out = simplot.io.FigureWriter()\n    cm_to_m = 1.0 / 100.0\n    #cut on flux energy\n    plotter = PlotFluxIntXsec(neutindices, neutdata, fluxindices, fluxdata, \n                              scale_to_m=cm_to_m,\n                              )\n    #out(plotter)\n    for p in plotter:\n        pass \n\ndef testcut(indices, d, scale_to_m):\n        rad = 3.0\n        outer_xmax = rad / math.sqrt(2.0)\n        outer_ymax = outer_xmax\n        outer_xmin = -outer_xmax\n        outer_ymin = -outer_ymax\n        #get fiducial flux\n        return _spacecut(indices, d, outer_xmin, outer_xmax, outer_ymin, outer_ymax, scale_to_m=scale_to_m)\n\n###############################################################################\n\ndef parsecml():\n    parser = argparse.ArgumentParser(description=\"Verify genev.\")\n    parser.add_argument(\"patterns\", metavar=\"M\", type=str, nargs='+', help=\"Input file list.\")\n    #parser.add_argument(\"-f\", \"--flux\", metavar=\"F\", dest=\"fluxpatterns\", type=str, nargs='+', help=\".\")\n    parser.add_argument(\"-p\", \"--plot\", metavar=\"P\", dest=\"plot\", type=str, choices=[\"flux\", \"rate\", \"ratio\"], help=\"Choose which plot to make.\")\n    args = parser.parse_args()\n    return args\n\n###############################################################################\n\ndef sanitize(args):\n    for p in args.patterns:\n        if len(glob.glob(p)) < 1:\n            raise Exception(\"Input file does not exist or no matches to the pattern.\", p)\n    return\n\n###############################################################################\n\ndef main():\n    #ROOT.gROOT.ProcessLine(\".L rootrackerhelper.cxx++\")\n    args = parsecml()\n    sanitize(args)\n    if args.plot == \"flux\":\n        plot_flux(args)\n    elif args.plot == \"rate\":\n        plot_interaction_rate(args)\n    elif args.plot == \"ratio\":\n        plot_flux_int_xsec(args)\n    return\n\n###############################################################################\n\nif __name__ == \"__main__\":\n    main()\n\n###############################################################################\n", "meta": {"hexsha": "80f05e3ce9364668a95b1175c0d0eb713f2e5e7b", "size": 22349, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/vectorgen/verify_genev.py", "max_stars_repo_name": "davehadley/hk-vectorgen", "max_stars_repo_head_hexsha": "620a17b6a36357188e8d5b74867c497114edb178", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/vectorgen/verify_genev.py", "max_issues_repo_name": "davehadley/hk-vectorgen", "max_issues_repo_head_hexsha": "620a17b6a36357188e8d5b74867c497114edb178", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vectorgen/verify_genev.py", "max_forks_repo_name": "davehadley/hk-vectorgen", "max_forks_repo_head_hexsha": "620a17b6a36357188e8d5b74867c497114edb178", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6496124031, "max_line_length": 145, "alphanum_fraction": 0.4923710233, "include": true, "reason": "import numpy,import scipy", "num_tokens": 5323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.19122011977281708}}
{"text": "import numpy as np\n\n'''\nLower body model\n\tstate vector\n\tx = [\n\t\troot: \t\t\t3D(6)\tp(x,y,z), u(x,y,z), \t \t,\n\n\t\tl_root: \t\t3D(6)\t\t\t\t\t\ttheta(x,y,z), \tw(x,y,z),\n\t\tl-hip: \t\t\t3D(6) \t\t\t\t\t\ttheta(x,y,z), \tw(x,y,z)\t,\n\t\tl-knee: \t\t1D(2) \t\t\t\t\t\ttheta(z), \t\tw(z)\t\t,\n\t\tl-ankle: \t\t2D(4) \t\t\t\t\t\ttheta(y,z), \tw(y,z)\t\t,\n\n        r_root:         3D(6)                       theta(x,y,z),   w(x,y,z),\n\t\tr-hip: \t\t\t3D(6)\t\t\t\t\t\ttheta(x,y,z), \tw(x,y,z)\t,\n\t\tr-knee: \t\t1D(2)\t\t\t\t\t\ttheta(z), \t\tw(z)\t\t,\n\t\tr-ankle: \t\t2D(4) \t\t\t\t\t\ttheta(y,z), \tw(y,z)\t\t,\n\n\t\tD_l_root_hip: \t1D(1)\tL\t\t\t\t\t\t\t\t\t\t\t\t,\n\t\tD_l_hip_knee: \t1D(1)\tL\t\t\t\t\t\t\t\t\t\t\t\t,\n\t\tD_l_knee_ankle: \t1D(1)\tL\t\t\t\t\t\t\t\t\t\t\t\t,\n\t\tD_l_ankle_foot: \t1D(1)\tL\t\t\t\t\t\t\t\t\t\t\t\t,\n\t\tD_r_root_hip: \t1D(1)\tL\t\t\t\t\t\t\t\t\t\t\t\t,\n\t\tD_r_hip_knee: \t1D(1)\tL\t\t\t\t\t\t\t\t\t\t\t\t,\n\t\tD_r_knee_ankle: \t1D(1)\tL\t\t\t\t\t\t\t\t\t\t\t\t,\n\t\tD_r_ankle_foot: \t1D(1)\tL\t\t\t\t\t\t\t\t\t\t\t\t,\n\t]\n    cal: 42 + 8\n\ttotal vector length(DP): 50\n\n\tmeasurement vector\n\ty = [\n\t\tx_root: \t\t3D(3)\n\t\tx_l_hip: \t\t3D(3)\n\t\tx_l-knee:\t\t3D(3)\n\t\tx_l-ankle:\t\t3D(3)\n\t\tx_l-foot:\t\t3D(3)\n\t\tx_r-hip:\t\t3D(3)\n\t\tx_r-knee:\t\t3D(3)\n\t\tx_r-ankle:\t\t3D(3)\n\t\tx_r-foot:\t\t3D(3)\n\t]\n\ttotal vector length(MP): 27\n'''\nclass ukf_Lower_Params:\n    def __init__(self, init_mean, init_cov=[1e-6, 1e-4, 1e-6, 1e-4, 1e-6, 1e-1, 1e-6, 1e-1, 1e-6, 1e-4, 1e-9, 1e-4, 100]):\n    \tself.set_trans_covariance(init_cov[:11])\n    \tself.set_obs_covariance(init_cov[11])\n    \tself.set_mean(init_mean)\n    \tself.set_init_trans_cov(init_cov[12])\n    \tself.set_trans_matrix()\n\n    def set_state_covariance(self, init_cov):\n        root_p = init_cov[0]\n        root_v = init_cov[1]\n        root_l_t = root_r_t = init_cov[2]\n        root_l_w = root_r_w = init_cov[3]\n        hip_l_t = hip_r_t = init_cov[4]\n        hip_l_w = hip_r_w = init_cov[5]\n        knee_l_t = knee_r_t = init_cov[6]\n        knee_l_w = knee_r_w = init_cov[7]\n        ankle_l_t = ankle_r_t = init_cov[8]\n        ankle_l_w = ankle_r_w = init_cov[9]\n        link_length = init_cov[10]\n        self.state_cov_list = [root_p,root_v,root_l_t,root_l_w,hip_l_t,hip_l_w,knee_l_t,knee_l_w,ankle_l_t,ankle_l_w,root_r_t,root_r_w,hip_r_t,hip_r_w,knee_r_t,knee_r_w,ankle_r_t,ankle_r_w,link_length]\n\n    def set_state_dim(self):\n        root_dim = 3\n        root_l_dim =  root_r_dim = 3\n        hip_l_dim = hip_r_dim = 3\n        knee_l_dim = knee_r_dim = 1\n        ankle_l_dim = ankle_r_dim = 2\n        link_length = 8\n        self.state_cov_dim_list = [root_dim,root_dim,root_l_dim,root_l_dim,hip_l_dim,hip_l_dim,knee_l_dim,knee_l_dim,ankle_l_dim,ankle_l_dim,root_r_dim,root_r_dim,hip_r_dim,hip_r_dim,knee_r_dim,knee_r_dim,ankle_r_dim,ankle_r_dim,link_length]\n        self.state_cov_total_dim = sum(self.state_cov_dim_list)\n\n    def gen_trans_covariance(self):\n        tmp = np.eye(self.state_cov_total_dim)\n\n        idx = 0\n        for i in range(len(self.state_cov_list)):\n            for j in range(self.state_cov_dim_list[i]):\n                tmp[idx+j][idx+j] = self.state_cov_list[i]\n            idx = idx + self.state_cov_dim_list[i]\n\n        self.trans_cov = tmp\n\n    def set_trans_covariance(self, init_cov):\n        self.set_state_covariance(init_cov)\n        self.set_state_dim()\n        self.gen_trans_covariance()\n\n    def set_obs_covariance(self, init_obs_cov_factor):\n        self.obs_cov_dim = 27\n        self.obs_cov_factor = init_obs_cov_factor\n        self.obs_cov = np.eye(self.obs_cov_dim)*self.obs_cov_factor\n\n    def set_mean(self, init_mean):\n        self.mean = init_mean\n\n    def set_init_trans_cov(self, t_factor):\n    \tself.init_trans_cov_factor = t_factor\n    \tself.init_trans_cov = self.trans_cov * self.init_trans_cov_factor\n\n    def set_trans_matrix(self):\n        self.fps = 10\n        self.is_velocity = [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0]\n        tmp = np.eye(self.state_cov_total_dim)\n\n        idx = 0\n        for i in range(len(self.state_cov_list)):\n        \tif self.is_velocity[i] == 1:\n\t        \tfor j in range(self.state_cov_dim_list[i]):\n\t        \t\ttmp[idx+j-self.state_cov_dim_list[i]][idx+j] = 1/self.fps\n        \tidx = idx + self.state_cov_dim_list[i]\n\n        self.trans_matrx = tmp\n\n'''\nUpper body model\n    state vector\n    x = [\n        root:               3D(6)   p(x,y,z), u(x,y,z),                             ;\n        s_root:             3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n        spine_naval:        3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n        l_spine_chest:      3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n        l_shoulder:         3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n        l_shoulder_center:  3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n        l_elbow:            3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n        l_wrist_u:          3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n        l_hand:             3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n        l_wrist_d:          3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n\n        r_spine_chest:      3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n        r_shoulder:         3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n        r_shoulder_center:  3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n        r_elbow:            3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n        r_wrist_u:          3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n        r_hand:             3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n        r_wrist_d:          3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n        u_spine_chest:      3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n        neck:               3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n        head:               3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n\n        l_nose:             3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n        l_eye:              3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n        r_nose:             3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n        r_eye:              3D(6)                       theta(x,y,z),   w(x,y,z),   ;\n\n        D_root_spine:       1D(1)                                                   ,\n        D_spine_chest:      1D(1)                                                   ,\n        D_l_chest_sh:       1D(1)                                                   ,\n        D_l_sh_shc:         1D(1)                                                   ,\n        D_l_shc_elbow:      1D(1)                                                   ,\n        D_l_elbow_wrist:    1D(1)                                                   ,\n        D_l_wrist_hand      1D(1)                                                   ,\n        D_l_hand_handtip:   1D(1)                                                   ,\n        D_l_wrist_thumb:    1D(1)                                                   ,\n        D_r_chest_sh:       1D(1)                                                   ,\n\n        D_r_sh_shc:         1D(1)                                                   ,\n        D_r_shc_elbow:      1D(1)                                                   ,\n        D_r_elbow_wrist:    1D(1)                                                   ,\n        D_r_wrist_hand:     1D(1)                                                   ,\n        D_r_hand_handtip:   1D(1)                                                   ,\n        D_r_wrist_thumb:    1D(1)                                                   ,\n        D_chest_neck:       1D(1)                                                   ,\n        D_neck_head:        1D(1)                                                   ,\n        D_head_nose:        1D(1)                                                   ,\n        D_l_nose_eye:       1D(1)                                                   ,\n\n        D_l_eye_ear:        1D(1)                                                   ,\n        D_r_nose_eye:       1D(1)                                                   ,\n        D_r_eye_ear:        1D(1)                                                   ,\n    ]\n    cal: 24*6 - 8 + 23 = 144 + 23 = 167\n    total vector length(DP): 167\n\n    measurement vector\n    y = [\n        root:               3D(3)       0\n        spine_naval:        3D(3)       1\n        spine_chest:        3D(3)       2\n        l_shoulder:         3D(3)       4\n        l_shoulder_center:  3D(3)       5\n        l_elbow:            3D(3)       6\n        l_wrist:            3D(3)       7\n        l_hand:             3D(3)       8\n        l_handtip:          3D(3)       9\n        l_thumb:            3D(3)       10\n\n        r_shoulder:         3D(3)       11\n        r_shoulder_center:  3D(3)       12\n        r_elbow:            3D(3)       13\n        r_wrist:            3D(3)       14\n        r_hand:             3D(3)       15\n        r_handtip:          3D(3)       16\n        r_thumb:            3D(3)       17\n        neck:               3D(3)       3\n        head:               3D(3)       26\n        nose:               3D(3)       27\n\n        l_eye:              3D(3)       28\n        l_ear:              3D(3)       29\n        r_eye:              3D(3)       30\n        r_ear:              3D(3)       31\n    ]\n    cal: 24 * 3 = 72\n    total vector length(MP): 72\n'''\n\nclass ukf_Upper_Params:\n    def __init__(self, init_mean, init_cov=[]):\n        self.set_trans_covariance(init_cov[:35])\n        self.set_obs_covariance(init_cov[35])\n        self.set_mean(init_mean)\n        self.set_init_trans_cov(init_cov[36])\n        self.set_trans_matrix()\n\n    def set_state_covariance(self, init_cov):\n        root_p,                 root_v              = init_cov[0:2]\n        s_root_t,               s_root_w            = init_cov[2:4]\n        spine_naval_t,          spine_naval_w       = init_cov[4:6]\n\n        l_spine_chest_t,        l_spine_chest_w     = init_cov[6:8]\n        l_shoulder_t,           l_shoulder_w        = init_cov[8:10]\n        l_shoulder_center_t,    l_shoulder_center_w = init_cov[10:12]\n        l_elbow_t,              l_elbow_w           = init_cov[12:14]\n        l_wrist_u_t,            l_wrist_u_w         = init_cov[14:16]\n        l_hand_t,               l_hand_w            = init_cov[16:18]\n        l_wrist_d_t,            l_wrist_d_w         = init_cov[18:20]\n\n        r_spine_chest_t,        r_spine_chest_w     = init_cov[6:8]\n        r_shoulder_t,           r_shoulder_w        = init_cov[8:10]\n        r_shoulder_center_t,    r_shoulder_center_w = init_cov[10:12]\n        r_elbow_t,              r_elbow_w           = init_cov[12:14]\n        r_wrist_u_t,            r_wrist_u_w         = init_cov[14:16]\n        r_hand_t,               r_hand_w            = init_cov[16:18]\n        r_wrist_d_t,            r_wrist_d_w         = init_cov[18:20]\n\n        u_spine_chest_t,        u_spine_chest_w     = init_cov[20:22]\n        neck_t,                 neck_w              = init_cov[22:24]\n        head_t,                 head_w              = init_cov[24:26]\n        l_nose_t,               l_nose_w            = init_cov[26:28]\n        l_eye_t,                l_eye_w             = init_cov[28:30]\n        r_nose_t,               r_nose_w            = init_cov[30:32]\n        r_eye_t,                r_eye_w             = init_cov[32:34]\n\n        link_length                                 = init_cov[34]\n\n        self.state_cov_list = [root_p,root_v,s_root_t,s_root_w,spine_naval_t,spine_naval_w,l_spine_chest_t,l_spine_chest_w,l_shoulder_t,l_shoulder_w,l_shoulder_center_t,l_shoulder_center_w,l_elbow_t,l_elbow_w,l_wrist_u_t,l_wrist_u_w,l_hand_t,l_hand_w,l_wrist_d_t,l_wrist_d_w,r_spine_chest_t,r_spine_chest_w,r_shoulder_t,r_shoulder_w,r_shoulder_center_t,r_shoulder_center_w,r_elbow_t,r_elbow_w,r_wrist_u_t,r_wrist_u_w,r_hand_t,r_hand_w,r_wrist_d_t,r_wrist_d_w,u_spine_chest_t,u_spine_chest_w,neck_t,neck_w,head_t,head_w,l_nose_t,l_nose_w,l_eye_t,l_eye_w,r_nose_t,r_nose_w,r_eye_t,r_eye_w,link_length]\n\n    def set_state_dim(self):\n        root_dim = 3\n        s_root_dim = 3\n        spine_naval_dim = 3\n\n        l_spine_chest_dim = 3\n        l_shoulder_dim = 3\n        l_shoulder_center_dim = 3\n        l_elbow_dim = 3\n        l_wrist_u_dim = 3\n        l_hand_dim = 3\n        l_wrist_d_dim = 3\n\n        r_spine_chest_dim = 3\n        r_shoulder_dim = 3\n        r_shoulder_center_dim = 3\n        r_elbow_dim = 3\n        r_wrist_u_dim = 3\n        r_hand_dim = 3\n        r_wrist_d_dim = 3\n\n        u_spine_chest_dim = 3\n        neck_dim = 3\n        head_dim = 3\n        l_nose_dim = 3\n        l_eye_dim = 3\n        r_nose_dim = 3\n        r_eye_dim = 3\n\n        link_length_dim = 23\n\n        self.state_cov_dim_list = [root_dim,root_dim,s_root_dim,s_root_dim,spine_naval_dim,spine_naval_dim,l_spine_chest_dim,l_spine_chest_dim,l_shoulder_dim,l_shoulder_dim,l_shoulder_center_dim,l_shoulder_center_dim,l_elbow_dim,l_elbow_dim,l_wrist_u_dim,l_wrist_u_dim,l_hand_dim,l_hand_dim,l_wrist_d_dim,l_wrist_d_dim,r_spine_chest_dim,r_spine_chest_dim,r_shoulder_dim,r_shoulder_dim,r_shoulder_center_dim,r_shoulder_center_dim,r_elbow_dim,r_elbow_dim,r_wrist_u_dim,r_wrist_u_dim,r_hand_dim,r_hand_dim,r_wrist_d_dim,r_wrist_d_dim,u_spine_chest_dim,u_spine_chest_dim,neck_dim,neck_dim,head_dim,head_dim,l_nose_dim,l_nose_dim,l_eye_dim,l_eye_dim,r_nose_dim,r_nose_dim,r_eye_dim,r_eye_dim,link_length_dim]\n        self.state_cov_total_dim = sum(self.state_cov_dim_list)\n\n    def gen_trans_covariance(self):\n        tmp = np.eye(self.state_cov_total_dim)\n\n        idx = 0\n        for i in range(len(self.state_cov_list)):\n            for j in range(self.state_cov_dim_list[i]):\n                tmp[idx+j][idx+j] = self.state_cov_list[i]\n            idx = idx + self.state_cov_dim_list[i]\n\n        self.trans_cov = tmp\n\n    def set_trans_covariance(self, init_cov):\n        self.set_state_covariance(init_cov)\n        self.set_state_dim()\n        self.gen_trans_covariance()\n\n    def set_obs_covariance(self, init_obs_cov_factor):\n        self.obs_cov_dim = 72\n        self.obs_cov_factor = init_obs_cov_factor\n        self.obs_cov = np.eye(self.obs_cov_dim)*self.obs_cov_factor\n\n    def set_mean(self, init_mean):\n        self.mean = init_mean\n\n    def set_init_trans_cov(self, t_factor):\n        self.init_trans_cov_factor = t_factor\n        self.init_trans_cov = self.trans_cov * self.init_trans_cov_factor\n\n    def set_trans_matrix(self):\n        self.fps = 10\n        self.is_velocity = [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0]\n        tmp = np.eye(self.state_cov_total_dim)\n\n        idx = 0\n        for i in range(len(self.state_cov_list)):\n            if self.is_velocity[i] == 1:\n                for j in range(self.state_cov_dim_list[i]):\n                    tmp[idx+j-self.state_cov_dim_list[i]][idx+j] = 1/self.fps\n            idx = idx + self.state_cov_dim_list[i]\n\n        self.trans_matrx = tmp\n", "meta": {"hexsha": "c2ebb461cc355c886ef46ebc9e87aa3468978c55", "size": 14973, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/ukf_params.py", "max_stars_repo_name": "fbdp1202/pyukf_kinect_body_tracking", "max_stars_repo_head_hexsha": "c44477149cfc22abfe9121c2604dc284c93fbd42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-04-23T06:03:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T21:16:23.000Z", "max_issues_repo_path": "src/ukf_params.py", "max_issues_repo_name": "fbdp1202/pyukf_kinect_body_tracking", "max_issues_repo_head_hexsha": "c44477149cfc22abfe9121c2604dc284c93fbd42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ukf_params.py", "max_forks_repo_name": "fbdp1202/pyukf_kinect_body_tracking", "max_forks_repo_head_hexsha": "c44477149cfc22abfe9121c2604dc284c93fbd42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-07-12T15:07:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-05T09:27:18.000Z", "avg_line_length": 45.6493902439, "max_line_length": 703, "alphanum_fraction": 0.490549656, "include": true, "reason": "import numpy", "num_tokens": 4586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3311197462295937, "lm_q1q2_score": 0.19122011876909256}}
{"text": "#!/usr/bin/env python\n\n\"\"\"main Absorb routines\n   Copyright: 2009, Robert B. Von Dreele (Argonne National Laboratory)\n\"\"\"\nfrom __future__ import division, print_function\nimport platform\nimport math\nimport wx\nimport numpy as np\nimport sys\nimport matplotlib as mpl\nimport GSASIIpath\nGSASIIpath.SetVersionNumber(\"$Revision: 4672 $\")\nimport GSASIIElem as G2elem\nimport GSASIIElemGUI as G2elemGUI\n\ntry:\n    wx.NewIdRef\n    wx.NewId = wx.NewIdRef\nexcept AttributeError:\n    pass\n\nif '2' in platform.python_version_tuple()[0]:\n    Gktheta = unichr(0x3b8)\n    Gklambda = unichr(0x3bb)\n    GkDelta = unichr(0x0394)\n    Pwr10 = unichr(0x0b9)+unichr(0x2070)\n    Pwr20 = unichr(0x0b2)+unichr(0x2070)\n    Pwrm1 = unichr(0x207b)+unichr(0x0b9)\n    Pwrm2 = unichr(0x207b)+unichr(0x0b2)\n    Pwrm6 = unichr(0x207b)+unichr(0x2076)\n    Pwrm4 = unichr(0x207b)+unichr(0x2074)\n    Angstr = unichr(0x00c5)\n    Gkmu = unichr(0x3bc)\n    Pwr3 = unichr(0x0b3)\n    Pwr4 = unichr(0x2074)\n    Pwr20 = unichr(0x0b2)+unichr(0x0b0)\n    Pwrm1 = unichr(0x207b)+unichr(0x0b9)\n\nelse:\n    Gktheta = chr(0x3b8)\n    Gklambda = chr(0x3bb)\n    GkDelta = chr(0x0394)\n    Pwr10 = chr(0x0b9)+chr(0x2070)\n    Pwr20 = chr(0x0b2)+chr(0x2070)\n    Pwrm1 = chr(0x207b)+chr(0x0b9)\n    Pwrm2 = chr(0x207b)+chr(0x0b2)\n    Pwrm6 = chr(0x207b)+chr(0x2076)\n    Pwrm4 = chr(0x207b)+chr(0x2074)\n    Angstr = chr(0x00c5)   \n    Gkmu = chr(0x3bc)\n    Pwr3 = chr(0x0b3)\n    Pwr4 = chr(0x2074)\n    Pwr20 = chr(0x0b2)+chr(0x0b0)\n    Pwrm1 = chr(0x207b)+chr(0x0b9)\n\n[wxID_CHOICE1, wxID_SPINTEXT1, wxID_SPINTEXT2, wxID_SPINTEXT3, wxID_SPINTEXT4,\n wxID_RESULTS,wxID_SLIDER1, wxID_SPINBUTTON, wxID_NUMELEM, wxID_SPINTEXT5,wxID_SPINTEXT6,\n] = [wx.NewId() for _init_ctrls in range(11)]\n\n[wxID_EXIT, wxID_DELETE, wxID_NEW, \n] = [wx.NewId() for _init_coll_ABSORB_Items in range(3)]\n    \n[wxID_KALPHAAGKA, wxID_KALPHACOKA, wxID_KALPHACRKA, \n wxID_KALPHACUKA, wxID_KALPHAFEKA, wxID_KALPHAMNKA, \n wxID_KALPHAMOKA, wxID_KALPHANIKA, wxID_KALPHAZNKA, \n] = [wx.NewId() for _init_coll_KALPHA_Items in range(9)]\n\n[wxID_ABSORBABOUT] = [wx.NewId() for _init_coll_ABOUT_Items in range(1)]\n\nclass Absorb(wx.Frame):\n    ''' '''\n    Elems = []\n    Wave = 1.5405      #CuKa default\n    Kev = 12.397639    #keV for 1A x-rays\n    for arg in sys.argv:\n        if '-w' in arg:\n            Wave = float(arg.split('-w')[1])\n        elif '-e' in arg:\n            E = float(arg.split('-e')[1])\n            Wave = Kev/E\n        elif '-h' in arg:\n            print ('''\nAbsorb.py can take the following arguments:\n-h   -  this help listing\n-wv  -  set default wavelength to v, e.g. -w1.54 sets wavelength to 1.54A\n-ev  -  set default energy to v, e.g. -e27 sets energy to 27keV\nwithout arguments Absorb uses CuKa as default (Wave=1.54052A, E=8.0478keV)\n''')\n            sys.exit()\n    Wmin = 0.05        #wavelength range\n    Wmax = 3.0\n    Wres = 0.004094    #plot resolution step size as const delta-lam/lam - gives 1000 steps for Wmin to Wmax\n    Eres = 1.5e-4      #typical energy resolution for synchrotron x-ray sources\n    Energy = Kev/Wave\n    ifWave = True\n    Volume = 0\n    ifVol = False\n    Zcell = 1\n    Pack = 0.50\n    Radius = 0.4\n    def _init_coll_ABOUT_Items(self, parent):\n\n        parent.Append(wxID_ABSORBABOUT,'About')\n        self.Bind(wx.EVT_MENU, self.OnABOUTItems0Menu, id=wxID_ABSORBABOUT)\n\n    def _init_coll_menuBar1_Menus(self, parent):\n\n        parent.Append(menu=self.ABSORB, title='Absorb')\n        parent.Append(menu=self.KALPHA, title='Kalpha')\n        parent.Append(menu=self.ABOUT, title='About')\n\n    def _init_coll_KALPHA_Items(self, parent):\n        \"Set of characteristic radiation from sealed tube sources\"\n        def OnCrkaMenu(event):\n            self.SetWaveEnergy(2.28962)\n    \n        def OnMnkaMenu(event):\n            self.SetWaveEnergy(2.10174)\n    \n        def OnFekaMenu(event):\n            self.SetWaveEnergy(1.93597)\n    \n        def OnCokaMenu(event):\n            self.SetWaveEnergy(1.78896)\n    \n        def OnNikaMenu(event):\n            self.SetWaveEnergy(1.65784)\n    \n        def OnCukaMenu(event):\n            self.SetWaveEnergy(1.54052)\n    \n        def OnZnkaMenu(event):\n            self.SetWaveEnergy(1.43510)\n    \n        def OnMokaMenu(event):\n            self.SetWaveEnergy(0.70926)\n    \n        def OnAgkaMenu(event):\n            self.SetWaveEnergy(0.55936)\n            \n        parent.Append(wxID_KALPHACRKA, 'CrKa')\n        parent.Append(wxID_KALPHAMNKA, 'MnKa')\n        parent.Append(wxID_KALPHAFEKA, 'FeKa')\n        parent.Append(wxID_KALPHACOKA, 'CoKa')\n        parent.Append(wxID_KALPHANIKA, 'NiKa')\n        parent.Append(wxID_KALPHACUKA, 'CuKa')\n        parent.Append(wxID_KALPHAZNKA, 'ZnKa')\n        parent.Append(wxID_KALPHAMOKA, 'MoKa')\n        parent.Append(wxID_KALPHAAGKA, 'AgKa')\n        self.Bind(wx.EVT_MENU, OnCrkaMenu, id=wxID_KALPHACRKA)\n        self.Bind(wx.EVT_MENU, OnMnkaMenu, id=wxID_KALPHAMNKA)\n        self.Bind(wx.EVT_MENU, OnFekaMenu, id=wxID_KALPHAFEKA)\n        self.Bind(wx.EVT_MENU, OnCokaMenu, id=wxID_KALPHACOKA)\n        self.Bind(wx.EVT_MENU, OnNikaMenu, id=wxID_KALPHANIKA)\n        self.Bind(wx.EVT_MENU, OnCukaMenu, id=wxID_KALPHACUKA)\n        self.Bind(wx.EVT_MENU, OnZnkaMenu, id=wxID_KALPHAZNKA)\n        self.Bind(wx.EVT_MENU, OnMokaMenu, id=wxID_KALPHAMOKA)\n        self.Bind(wx.EVT_MENU, OnAgkaMenu, id=wxID_KALPHAAGKA)\n\n    def _init_coll_ABSORB_Items(self, parent):\n        parent.Append(wxID_NEW,'&New Element','Add new element')\n        self.Delete = parent.Append(wxID_DELETE,'&Delete Element','Delete an element')\n        self.Delete.Enable(False)\n        parent.Append(wxID_EXIT,'&Exit','Exit Fprime')\n        self.Bind(wx.EVT_MENU, self.OnExitMenu, id=wxID_EXIT)\n        self.Bind(wx.EVT_MENU, self.OnNewMenu, id=wxID_NEW)\n        self.Bind(wx.EVT_MENU, self.OnDeleteMenu, id=wxID_DELETE)\n        \n    def _init_utils(self):\n        self.ABSORB = wx.Menu(title='')\n\n        self.KALPHA = wx.Menu(title='')\n        self.KALPHA.SetEvtHandlerEnabled(True)\n\n        self.ABOUT = wx.Menu(title='')\n\n        self.menuBar1 = wx.MenuBar()\n\n        self._init_coll_ABSORB_Items(self.ABSORB)\n        self._init_coll_KALPHA_Items(self.KALPHA)\n        self._init_coll_ABOUT_Items(self.ABOUT)\n        self._init_coll_menuBar1_Menus(self.menuBar1)\n\n    def _init_ctrls(self, parent):\n        wx.Frame.__init__(self, parent=parent,\n              size=wx.Size(500, 400),style=wx.DEFAULT_FRAME_STYLE ^ wx.CLOSE_BOX, title='Absorb')              \n        self._init_utils()\n        self.SetMenuBar(self.menuBar1)\n        self.DrawPanel()\n        \n    def SetSize(self):\n        w,h = self.GetClientSize()\n        self.panel.SetSize(wx.Size(w,h))\n\n    def DrawPanel(self):\n        self.panel = wx.Panel(self)\n\n        mainSizer = wx.BoxSizer(wx.VERTICAL)\n        self.Results = wx.TextCtrl( parent=self.panel,\n            style=wx.TE_MULTILINE|wx.TE_DONTWRAP )\n        self.Results.SetEditable(False)\n        mainSizer.Add(self.Results,1,wx.EXPAND)\n        mainSizer.Add((10,15),0)\n        \n        if self.Elems:\n            lablSizer = wx.BoxSizer(wx.HORIZONTAL)\n            lablSizer.Add((5,10),0)\n            lablSizer.Add(wx.StaticText(parent=self.panel,label='Chemical Formula:'),0,\n                wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT)\n            mainSizer.Add(lablSizer,0)\n            mainSizer.Add((5,5),0)\n            nRow = len(self.Elems)/5\n            compSizer = wx.FlexGridSizer(nRow+1,10,0,0)\n            for Elem in self.Elems:\n                compSizer.Add(wx.StaticText(parent=self.panel,label=\"  \"+Elem[0].capitalize(),\n                    size=wx.Size(30,20)),0,wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT)\n                numElem = wx.TextCtrl(id=wxID_NUMELEM,parent=self.panel,name=Elem[0],\n                    size=wx.Size(70,20),value=\"%.2f\" % (Elem[2]),style=wx.TE_PROCESS_ENTER)\n                compSizer.Add(numElem,0)\n                numElem.Bind(wx.EVT_TEXT_ENTER, self.OnNumElem, id=wxID_NUMELEM)\n            mainSizer.Add(compSizer,0)\n            mainSizer.Add((10,15),0)           \n\n        selSizer = wx.BoxSizer(wx.HORIZONTAL)\n        selSizer.Add((5,10),0)\n        selSizer.Add(wx.StaticText(parent=self.panel, label='Wavelength:'),0,wx.EXPAND)\n        selSizer.Add((5,10),0)\n        self.SpinText1 = wx.TextCtrl(id=wxID_SPINTEXT1, parent=self.panel, \n            size=wx.Size(100,20), value = \"%.4f\" % (self.Wave),style=wx.TE_PROCESS_ENTER )\n        selSizer.Add(self.SpinText1,0)\n        selSizer.Add((5,10),0)\n        self.SpinText1.Bind(wx.EVT_TEXT_ENTER, self.OnSpinText1, id=wxID_SPINTEXT1)\n        \n        selSizer.Add(wx.StaticText(parent=self.panel, label='Energy:'),0,wx.EXPAND)\n        selSizer.Add((5,10),0)\n        self.SpinText2 = wx.TextCtrl(id=wxID_SPINTEXT2, parent=self.panel, \n            size=wx.Size(100,20), value = \"%.4f\" % (self.Energy),style=wx.TE_PROCESS_ENTER) \n        selSizer.Add(self.SpinText2,0)\n        selSizer.Add((5,10),0)\n        self.SpinText2.Bind(wx.EVT_TEXT_ENTER, self.OnSpinText2, id=wxID_SPINTEXT2)\n        \n        selSizer.Add(wx.StaticText(parent=self.panel, label='Plot scale:'),0,wx.EXPAND)\n        selSizer.Add((5,10),0)\n        self.choice1 = wx.ComboBox(id=wxID_CHOICE1, parent=self.panel, value='Wavelength',\n             choices=['Wavelength','Energy'],style=wx.CB_READONLY|wx.CB_DROPDOWN)\n        selSizer.Add(self.choice1,0)\n        selSizer.Add((10,10),0)\n        self.choice1.Bind(wx.EVT_COMBOBOX, self.OnChoice1, id=wxID_CHOICE1)\n        mainSizer.Add(selSizer,0)\n        mainSizer.Add((10,10),0)\n        \n        slideSizer = wx.BoxSizer(wx.HORIZONTAL)\n        self.SpinButton = wx.SpinButton(id=wxID_SPINBUTTON, parent=self.panel, \n              size=wx.Size(25,24), style=wx.SP_VERTICAL | wx.SP_ARROW_KEYS)\n        slideSizer.Add(self.SpinButton,0,wx.ALIGN_RIGHT)\n        self.SpinButton.SetRange(-1,1)\n        self.SpinButton.SetValue(0)\n        self.SpinButton.Bind(wx.EVT_SPIN, self.OnSpinButton, id=wxID_SPINBUTTON)\n\n        self.slider1 = wx.Slider(id=wxID_SLIDER1, maxValue=int(1000.*self.Wmax),\n            minValue=int(1000.*self.Wmin), parent=self.panel,style=wx.SL_HORIZONTAL,\n            value=int(self.Wave*1000.), )\n        slideSizer.Add(self.slider1,1,wx.EXPAND)\n        self.slider1.Bind(wx.EVT_SLIDER, self.OnSlider1, id=wxID_SLIDER1)\n        mainSizer.Add(slideSizer,0,wx.EXPAND)\n        mainSizer.Add((10,10),0)\n        \n        cellSizer = wx.BoxSizer(wx.HORIZONTAL)\n        cellSizer.Add((5,10),0)\n        cellSizer.Add(wx.StaticText(parent=self.panel, label='Volume:'),0,wx.EXPAND)\n        cellSizer.Add((5,10),0)\n        self.SpinText3 = wx.TextCtrl(id=wxID_SPINTEXT3, parent=self.panel, \n              size=wx.Size(100,20), value = \"%.2f\" % (self.Volume),style=wx.TE_PROCESS_ENTER )\n        cellSizer.Add(self.SpinText3,0)\n        cellSizer.Add((5,10),0)\n        self.SpinText3.Bind(wx.EVT_TEXT_ENTER, self.OnSpinText3, id=wxID_SPINTEXT3)\n        \n        cellSizer.Add((5,10),0)\n        cellSizer.Add(wx.StaticText(parent=self.panel, label='Z(vol):'),0,wx.EXPAND)\n        cellSizer.Add((5,10),0)\n        self.SpinText4 = wx.TextCtrl(id=wxID_SPINTEXT4, parent=self.panel, \n              size=wx.Size(50,20), value = \"%d\" % (self.Zcell),style=wx.TE_PROCESS_ENTER )\n        cellSizer.Add(self.SpinText4,0)\n        cellSizer.Add((5,10),0)\n        self.SpinText4.Bind(wx.EVT_TEXT_ENTER, self.OnSpinText4, id=wxID_SPINTEXT4)\n        \n        cellSizer.Add((5,10),0)\n        cellSizer.Add(wx.StaticText(parent=self.panel, label='Sample R:'),0,wx.EXPAND)\n        cellSizer.Add((5,10),0)\n        self.SpinText5 = wx.TextCtrl(id=wxID_SPINTEXT5, parent=self.panel, \n              size=wx.Size(50,20), value = \"%.2f\" % (self.Radius),style=wx.TE_PROCESS_ENTER )\n        cellSizer.Add(self.SpinText5,0)\n        cellSizer.Add((5,10),0)\n        self.SpinText5.Bind(wx.EVT_TEXT_ENTER, self.OnSpinText5, id=wxID_SPINTEXT5)\n\n        cellSizer.Add((5,10),0)\n        cellSizer.Add(wx.StaticText(parent=self.panel, label='packing:'),0,wx.EXPAND)\n        cellSizer.Add((5,10),0)\n        self.SpinText6 = wx.TextCtrl(id=wxID_SPINTEXT6, parent=self.panel, \n              size=wx.Size(50,20), value = \"%.2f\" % (self.Pack),style=wx.TE_PROCESS_ENTER )\n        cellSizer.Add(self.SpinText6,0)\n        cellSizer.Add((5,10),0)\n        self.SpinText6.Bind(wx.EVT_TEXT_ENTER, self.OnSpinText6, id=wxID_SPINTEXT6)\n\n        mainSizer.Add(cellSizer,0)\n        mainSizer.Add((10,10),0)\n        self.panel.SetSizer(mainSizer)\n        self.panel.Fit()\n        self.panel.GetParent().SetSize()\n\n    def __init__(self, parent):\n        self._init_ctrls(parent)\n        self.parent = parent\n        self.Lines = []\n        self.Elems = []\n        self.linePicked = None\n\n    def OnExitMenu(self, event):\n        self.parent.G2plotNB.Delete('Absorb')\n        self.Close()\n        self.Destroy()\n\n    def OnNewMenu(self, event):\n        ElList = []\n        for Elem in self.Elems: ElList.append(Elem[0])\n        PE = G2elemGUI.PickElements(self,ElList)\n        if PE.ShowModal() == wx.ID_OK:\n            Elem = PE.Elem\n        PE.Destroy()\n        if Elem:\n            for El in Elem:\n                ElemSym = El.strip().upper()\n                if ElemSym not in ElList:\n                    atomData = G2elem.GetAtomInfo(ElemSym.capitalize())\n                    FormFactors = G2elem.GetFormFactorCoeff(ElemSym)\n                    for FormFac in FormFactors:\n                        FormSym = FormFac['Symbol'].strip()\n                        if FormSym == ElemSym:\n                            Z = FormFac['Z']                #At. No.\n                            N = 1.                          #no atoms / formula unit\n                            Orbs = G2elem.GetXsectionCoeff(ElemSym)\n                            Elem = [ElemSym,Z,N,FormFac,Orbs,atomData]\n                    self.Elems.append(Elem)\n            self.Delete.Enable(True)\n            self.panel.Destroy()\n            self.DrawPanel()\n            self.NewFPPlot = True\n            self.SetWaveEnergy(self.Wave)\n            \n    def OnDeleteMenu(self, event):\n        if len(self.Elems):\n            ElList = []\n            for Elem in self.Elems: ElList.append(Elem[0])\n            S = []\n            DE = G2elemGUI.DeleteElement(self,ElList)\n            if DE.ShowModal() == wx.ID_OK:\n                El = DE.GetDeleteElement().strip().upper()\n                for Elem in self.Elems:\n                    if Elem[0] != El:\n                        S.append(Elem)\n                self.Elems = S\n                self.CalcFPPS()\n                if not self.Elems:\n                    self.Delete.Enable(False)\n                self.panel.Destroy()\n                self.DrawPanel()\n                self.NewFPPlot = True\n                self.SetWaveEnergy(self.Wave)\n        \n    def OnNumElem(self, event):\n        for Elem in self.Elems:\n            if event.GetEventObject().GetName() == Elem[0]:\n                Elem[2] = float(event.GetEventObject().GetValue())\n                event.GetEventObject().SetValue(\"%8.2f\" % (Elem[2]))\n                self.SetWaveEnergy(self.Wave)                \n        \n    def OnSpinText1(self, event):\n        self.SetWaveEnergy(float(self.SpinText1.GetValue()))\n        \n    def OnSpinText2(self, event):\n        self.SetWaveEnergy(self.Kev/(float(self.SpinText2.GetValue())))\n        \n    def OnSpinText3(self,event):\n        self.Volume = max(10.,float(self.SpinText3.GetValue()))\n        self.ifVol = True\n        self.SetWaveEnergy(self.Wave)\n        \n    def OnSpinText4(self,event):\n        self.Zcell = max(1,float(self.SpinText4.GetValue()))\n        self.SetWaveEnergy(self.Wave)\n        \n    def OnSpinText5(self, event):\n        self.Radius = max(0.01,float(self.SpinText5.GetValue()))\n        self.SetWaveEnergy(self.Wave)\n       \n    def OnSpinText6(self, event):\n        self.Pack = min(1.0,max(0.01,float(self.SpinText6.GetValue())))\n        self.SetWaveEnergy(self.Wave)\n       \n    def OnSpinButton(self, event):\n        move = self.SpinButton.GetValue()/10000.\n        self.Wave = min(max(self.Wave+move,self.Wmin),self.Wmax)\n        self.SpinButton.SetValue(0)\n        self.SetWaveEnergy(self.Wave)\n\n    def OnSlider1(self, event):\n        if self.ifWave:\n            Wave = float(self.slider1.GetValue())/1000.\n        else:\n            Wave = self.Kev/(float(self.slider1.GetValue())/1000.)\n        self.SetWaveEnergy(Wave)\n        \n    def SetWaveEnergy(self,Wave):\n        self.Wave = Wave\n        self.Energy = self.Kev/self.Wave\n        self.Energy = round(self.Energy,4)\n        E = self.Energy\n        DE = E*self.Eres                         #smear by defined source resolution\n        self.SpinText1.SetValue(\"%.4f\" % (self.Wave))\n        self.SpinText2.SetValue(\"%.4f\" % (self.Energy))\n        self.SpinText1.Update()\n        self.SpinText2.Update()\n        if self.ifWave:\n            self.slider1.SetValue(int(1000.*self.Wave))\n        else:\n            self.slider1.SetValue(int(1000.*self.Energy))\n        Text = ''\n        if not self.ifVol:\n            self.Volume = 0\n            for Elem in self.Elems:\n                self.Volume += 10.*Elem[2]\n        muT = 0\n        Mass = 0\n        Fo = 0\n        Fop = 0\n        for Elem in self.Elems:\n            Mass += self.Zcell*Elem[2]*Elem[5]['Mass']\n            r1 = G2elem.FPcalc(Elem[4],E+DE)\n            r2 = G2elem.FPcalc(Elem[4],E-DE)\n            Els = Elem[0]\n            Els = Els.ljust(2).lower().capitalize()\n            mu = 0\n            Fo += Elem[2]*Elem[1]\n            if Elem[1] > 78 and self.Energy+DE > self.Kev/0.16:\n                mu = self.Zcell*Elem[2]*(r1[2]+r2[2])/2.0\n                Text += \"%s\\t%s%8.2f  %s%6s  %s%6.3f  %s%10.2f %s\\n\" %    (\n                    'Element= '+str(Els),\"N = \",Elem[2],\" f'=\",'not valid',\n                    ' f\"=',(r1[1]+r2[1])/2.0,' '+Gkmu+'=',mu,'barns')\n            elif Elem[1] > 94 and self.Energy-DE < self.Kev/2.67:\n                mu = 0\n                Text += \"%s\\t%s%8.2f  %s%6s  %s%6s  %s%10s%s\\n\" %    (\n                    'Element= '+str(Els),\"N = \",Elem[2],\" f'=\",'not valid',\n                    ' f\"=','not valid',' '+Gkmu+'=','not valid')\n            else:\n                mu = self.Zcell*Elem[2]*(r1[2]+r2[2])/2.0\n                Fop += Elem[2]*(Elem[1]+(r1[0]+r2[0])/2.0)\n                Text += \"%s\\t%s%8.2f  %s%6.3f  %s%6.3f  %s%10.2f %s\\n\" %    (\n                    'Element= '+str(Els),\"N = \",Elem[2],\" f'=\",(r1[0]+r2[0])/2.0,\n                    ' f\"=',(r1[1]+r2[1])/2.0,' '+Gkmu+'=',mu,'barns')\n            muT += mu\n        \n        if self.Volume:\n            Text += \"%s %s%10.2f %s\" % (\"Total\",' '+Gkmu+'=',self.Pack*muT/self.Volume,'cm'+Pwrm1+', ')\n            Text += \"%s%10.2f%s\" % ('Total '+Gkmu+'R=',self.Radius*self.Pack*muT/(10.0*self.Volume),', ')\n            Text += \"%s%10.4f%s\\n\" % ('Transmission exp(-2'+Gkmu+'R)=', \\\n                100.0*math.exp(-2*self.Radius*self.Pack*muT/(10.0*self.Volume)),'%')\n            self.Results.SetValue(Text)\n            den = Mass/(0.602*self.Volume)                \n            if self.ifVol:\n                Text += '%s' % ('Theor. density=')\n            else:  \n                Text += '%s' % ('Est. density=')\n            Text += '%6.3f %s%.3f %s\\n' % (den,'g/cm'+Pwr3+', Powder density=',self.Pack*den,'g/cm'+Pwr3)\n            Text += '%s%10.2f%s\\n'%('X-ray small angle scattering contrast',(28.179*Fo/self.Volume)**2,'*10'+Pwr20+'/cm'+Pwr4)\n            if Fop:\n                Text += '%s%10.2f%s\\n'%('Anomalous X-ray small angle scattering contrast',(28.179*Fop/self.Volume)**2,'*10'+Pwr20+'/cm'+Pwr4)\n            self.Results.SetValue(Text)\n        self.Results.Update()\n        self.SpinText3.SetValue(\"%.2f\" % (self.Volume))\n        self.SpinText3.Update()\n        self.SpinText4.SetValue(\"%d\" % (self.Zcell))\n        self.SpinText4.Update()\n        self.SpinText5.SetValue(\"%.2f\" % (self.Radius))\n        self.SpinText5.Update()\n        self.SpinText6.SetValue(\"%.2f\" % (self.Pack))\n        self.SpinText6.Update()\n        if len(self.Elems):\n            self.CalcFPPS()\n            self.UpDateAbsPlot(Wave,rePlot=True)\n\n    def CalcFPPS(self):\n        \"\"\"generate f\" curves for selected elements\n           does constant delta-lambda/lambda steps over defined range\n        \"\"\"\n        FPPS = []\n        if self.Elems:\n            wx.BeginBusyCursor()\n            Corr = self.Zcell*self.Radius*self.Pack/(10.0*self.Volume)\n            try:\n                muT = []\n                for iE,Elem in enumerate(self.Elems):\n                    Els = Elem[0]\n                    Els = Els = Els.ljust(2).lower().capitalize()\n                    Wmin = self.Wmin\n                    Wmax = self.Wmax\n                    lWmin = math.log(Wmin)\n                    N = int(round(math.log(Wmax/Wmin)/self.Wres))    #number of constant delta-lam/lam steps\n                    I = range(N+1)\n                    Ws = []\n                    for i in I: Ws.append(math.exp(i*self.Wres+lWmin))\n                    mus = []\n                    Es = []\n                    for j,W in enumerate(Ws):\n                        E = self.Kev/W\n                        DE = E*self.Eres                         #smear by defined source resolution\n                        res1 = G2elem.FPcalc(Elem[4],E+DE)\n                        res2 = G2elem.FPcalc(Elem[4],E-DE)\n                        muR = Corr*Elem[2]*(res1[2]+res2[2])/2.0\n                        mus.append(muR)\n                        if iE:\n                            muT[j] += muR\n                        else:\n                            muT.append(muR)\n                        Es.append(E)\n                    if self.ifWave:\n                        Fpps = (Els,Ws,mus)\n                    else:\n                        Fpps = (Els,Es,mus)\n                    FPPS.append(Fpps)\n                if self.ifWave:\n                    Fpps = ('Total',Ws,muT)\n                else:\n                    Fpps = ('Total',Es,muT)\n                FPPS.append(Fpps)\n            finally:\n                wx.EndBusyCursor()\n        self.FPPS = FPPS\n\n    def OnChoice1(self, event):\n        if event.GetString() == \"Wavelength\":\n            self.ifWave = True\n            self.NewFPPlot = True\n            self.Wave = round(self.Wave,4)\n            self.slider1.SetRange(int(1000.*self.Wmin),int(1000.*self.Wmax))\n            self.slider1.SetValue(int(1000.*self.Wave))\n            self.SpinText1.SetValue(\"%6.4f\" % (self.Wave))\n            self.SpinText2.SetValue(\"%7.4f\" % (self.Energy))\n        else:\n            self.ifWave = False\n            self.NewFPPlot = True\n            Emin = self.Kev/self.Wmax\n            Emax = self.Kev/self.Wmin\n            self.Energy = round(self.Energy,4)\n            self.slider1.SetRange(int(1000.*Emin),int(1000.*Emax))\n            self.slider1.SetValue(int(1000.*self.Energy))\n            self.SpinText1.SetValue(\"%6.4f\" % (self.Wave))\n            self.SpinText2.SetValue(\"%7.4f\" % (self.Energy))\n        if len(self.Elems):\n            self.CalcFPPS()\n            self.UpDateAbsPlot(self.Wave,rePlot=False)\n        \n    def OnKeyPress(self,event):\n        if event.key == 'g':\n            mpl.rcParams['axes.grid'] = not mpl.rcParams['axes.grid']\n            self.UpDateAbsPlot(self.Wave,rePlot=False)\n\n    def UpDateAbsPlot(self,Wave,rePlot=True):\n        \"\"\"Plot mu vs wavelength 0.05-3.0A\"\"\"\n        xylim = []\n        try:\n            if rePlot:\n                asb = self.Page.figure.get_axes()[1]\n                xylim = asb.get_xlim(),asb.get_ylim()\n            newPlot = False\n        except:\n            new,plotNum,self.Page,self.fplot,lim = self.parent.G2plotNB.FindPlotTab('Absorb','mpl')\n            self.Page.canvas.mpl_connect('pick_event', self.OnPick)\n            self.Page.canvas.mpl_connect('button_release_event', self.OnRelease)\n            self.Page.canvas.mpl_connect('motion_notify_event', self.OnMotion)\n            self.Page.canvas.mpl_connect('key_press_event', self.OnKeyPress)\n            newPlot = True\n            self.ax = self.Page.figure.add_subplot(111,label='absorb')\n        self.fplot.set_visible(False)\n        self.Page.Choice = (' key press','g: toggle grid',)\n        self.Page.keyPress = self.OnKeyPress    \n        self.ax.clear()\n        self.ax.set_title('X-Ray Absorption',x=0,ha='left')\n        self.ax.set_ylabel(r\"$\\mu R$\",fontsize=14)\n        Ymin = 0.0\n        Ymax = 0.0\n        if self.FPPS: \n            for Fpps in self.FPPS:\n                Ymin = min(Ymin,min(Fpps[2]))\n                Ymax = max(Ymax,max(Fpps[2]))\n                fppsP1 = np.array(Fpps[1])\n                fppsP2 = np.array(Fpps[2])\n                self.ax.plot(fppsP1,fppsP2,label=r'$\\mu R$ '+Fpps[0])\n        if self.ifWave: \n            self.ax.set_xlabel(r'$\\mathsf{\\lambda, \\AA}$',fontsize=14)\n            self.ax.axvline(x=Wave,picker=3,color='black')\n        else:\n            self.ax.set_xlabel(r'$\\mathsf{E, keV}$',fontsize=14)\n            self.ax.set_xscale('log')\n            self.ax.axvline(x=self.Kev/Wave,picker=3,color='black')\n        self.ax.axhline(y=1.0,color='b')\n        self.ax.axhline(y=5.0,color='r')\n        self.ax.set_ylim(Ymin,Ymax)\n        if self.FPPS:\n            self.ax.legend(loc='best')\n        if newPlot:\n            newPlot = False\n            self.Page.canvas.draw()\n        else:\n            if rePlot:\n                tb = self.Page.canvas.toolbar\n                tb.push_current()\n                self.ax.set_xlim(xylim[0])\n                self.ax.set_ylim(xylim[1])\n                xylim = []\n                tb.push_current()\n            self.Page.canvas.draw()\n        \n    def OnPick(self, event):\n        self.linePicked = event.artist\n        \n    def OnMotion(self,event):\n        xpos = event.xdata\n        if xpos and xpos>0.1:\n            ypos = event.ydata\n            if self.ifWave:\n                Wave = xpos\n            else:\n                Wave = self.Kev/xpos\n            Wave = min(max(Wave,self.Wmin),self.Wmax)\n            self.parent.G2plotNB.status.SetStatusText('Wavelength: %.4f, Energy: %.3f, %sR: %.3f'%(Wave,self.Kev/Wave,Gkmu,ypos),1)\n        if self.linePicked:\n            self.SetWaveEnergy(Wave)\n                \n    def OnRelease(self, event):\n        if self.linePicked is None: return\n        self.linePicked = None\n        xpos = event.xdata\n        if xpos:\n            if self.ifWave:\n                Wave = xpos\n            else:\n                Wave = self.Kev/xpos               \n            self.SetWaveEnergy(Wave)\n            \n    def OnABOUTItems0Menu(self, event):\n        ''' '''\n        try:\n            import wx.adv as wxadv  # AboutBox moved here in Phoenix\n        except:\n            wxadv = wx\n        info = wxadv.AboutDialogInfo()\n        info.Name = 'Absorb'\n        info.Copyright = '''\nRobert B. Von Dreele, 2009(C)\nArgonne National Laboratory\nThis product includes software developed \nby the UChicago Argonne, LLC, as \nOperator of Argonne National Laboratory.        '''\n        info.Description = '''\nFor calculating X-ray absorption factors to 250keV for cylindrical      \npowder samples; based on Fortran program Fprime of Cromer & Liberman \n(D. T. Cromer and D. A. Liberman, Acta Cryst. (1981). A37, 267-268.)\ncorrected for Kissel & Pratt energy term; Jensen term not included\n        '''\n        wxadv.AboutBox(info)\n\n", "meta": {"hexsha": "dcf957eb5707da00eedd3d2582260535317d898f", "size": 27235, "ext": "py", "lang": "Python", "max_stars_repo_path": "Xerus/GSASII/Absorb.py", "max_stars_repo_name": "pedrobcst/Xerus", "max_stars_repo_head_hexsha": "09df088e0207176df0d20715e1c9778d09d28250", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2021-12-10T03:05:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T15:48:35.000Z", "max_issues_repo_path": "Xerus/GSASII/Absorb.py", "max_issues_repo_name": "pedrobcst/Xerus", "max_issues_repo_head_hexsha": "09df088e0207176df0d20715e1c9778d09d28250", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2022-02-24T11:09:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T07:42:17.000Z", "max_forks_repo_path": "Xerus/GSASII/Absorb.py", "max_forks_repo_name": "pedrobcst/Xerus", "max_forks_repo_head_hexsha": "09df088e0207176df0d20715e1c9778d09d28250", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-25T16:26:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T16:26:54.000Z", "avg_line_length": 40.4080118694, "max_line_length": 141, "alphanum_fraction": 0.5625481917, "include": true, "reason": "import numpy", "num_tokens": 7776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.19122011495727528}}
{"text": "\"\"\"\nBEACON\n\"\"\"\n\nimport sys, os\nimport numpy as np\nimport libraries as lib\n\ndef parameters_generator(Filename='Options'):\n    import imp\n\n    options = imp.load_source(os.path.splitext(os.path.basename(Filename))[0], Filename)\n\n    class galaxy:\n        def __init__(self):\n            self.Name = options.Galaxy_Name\n            self.Sky_Coo = np.array(options.Galaxy_Coordinates)\n            self.Distance =  options.Galaxy_Distance\n            self.RH = options.Galaxy_rh\n            self.RT = options.Galaxy_rt\n            self.PA = options.Galaxy_pa\n            self.E =  options.Galaxy_e\n            self.Sky_Vel =  options.Galaxy_Velocity\n            \n    class read_data_options:\n        def __init__(self):\n            self.Data_file = options.Galaxy_Data_file\n            self.Clean_sample = options.Clean_sample\n            self.Admisible_range_Vel = options.Admisible_range_Velocity\n            self.Admisible_max_error_Vel = options.Admisible_max_error_Velocity\n            self.Admisible_max_error_Extra_Coo = options.Admisible_max_error_Extra_Coo\n   \n    class beacon_options:\n        def __init__(self):\n            self.Smoothing = options.Smoothing\n            self.Min_cluster_size = options.Min_cluster_size\n            self.Maxima_ratio = options.Maxima_ratio\n            self.Epsilon = options.Epsilon\n            self.Standarization_Method = options.Standarization_Method\n            self.Standarization_Weights = np.array(options.Standarization_Weights)\n            self.Coordinate_system = options.Coordinate_system\n            self.Velocity_system = options.Velocity_system\n            self.Uniqueness_Method = options.Uniqueness_Method\n            self.NStars_normed = options.NStars_normed\n     \n    class sref_options:\n        def __init__(self):\n            self.WCS = options.Galaxy_WCS\n            self.Extra_Coo_is_FeH = options.Extra_Coo_is_FeH\n            self.Use_elliptical_coordinates = options.Use_elliptical_coordinates\n            self.Find_centre_sky_radius = options.Find_centre_sky_radius\n            self.Find_centre_sky_resolution = options.Find_centre_sky_resolution\n            self.Find_centre_vhel_radius = options.Find_centre_vhel_radius\n            self.Find_centre_vhel_resolution = options.Find_centre_vhel_resolution\n\n    class plotting_options:\n        def __init__(self):\n            self.Plot_maps = options.Plot_maps\n            self.wcs = options.Galaxy_WCS\n            self.Maps_plotting_radius = options.Maps_plotting_radius\n            self.Maps_vlos_limits = options.Maps_vlos_limits\n            self.Auxiliar_axes_limits = options.Auxiliar_axes_limits\n            self.Draw_markers = options.Draw_markers\n            self.Markers_color = options.Markers_color\n            self.Markers_size = options.Markers_size\n            self.Markers_linewidth = options.Markers_linewidth\n            self.Plot_angular_momenta = options.Plot_angular_momenta\n            self.Plot_extra_coo = options.Plot_extra_coo\n            self.Plot_elliptical_radius = options.Use_elliptical_coordinates         \n            if options.Auxiliar_axes_label:            \t\n               self.Auxiliar_axes_label = options.Auxiliar_axes_label\n\n    return galaxy(), read_data_options(), beacon_options(), sref_options(), plotting_options()\n  \ndef stars_generator(Rest_frame_coo):\n    class stars_data(object):\n        def __init__(self):\n            self.Sky_Coo = Rest_frame_coo[0]\n            self.Gref_car_Coo = Rest_frame_coo[1]\n            self.Gref_car_Vel = Rest_frame_coo[2]\n            self.Gref_car_eVel = Rest_frame_coo[3]\n            self.Gref_pol_Coo = Rest_frame_coo[4]\n            self.Gref_pol_Vel = Rest_frame_coo[5]    \n            self.Gref_pol_eVel = Rest_frame_coo[6]\n            try:\n               self.Z = Rest_frame_coo[7]\n               self.eZ = Rest_frame_coo[8]\n               self.FeH = Rest_frame_coo[9]\n               self.eFeH = Rest_frame_coo[10]\n            except:\n               pass\n            try:\n               self.Extra_Coo = Rest_frame_coo[7]\n               self.eExtra_Coo = Rest_frame_coo[8]\n            except:\n               pass\n\n    return stars_data\n\ndef read_data(read_data_options):\n  \n    Stars_data = np.loadtxt(read_data_options.Data_file, skiprows=1)\n\n    try:\n       Sky_Coo = Stars_data[:,0:2]\n       Sky_Vel = Stars_data[:,2:7:2]\n       Sky_eVel = Stars_data[:,3:8:2]\n       Extra_Coo = Stars_data[:,-2:7:-2]\n       Extra_eCoo = Stars_data[:,-1:7:-2]\n    except:\n       print 'Bad format in input table.\\n'\n       print 'Format shoud be:\\n'\n       print 'RA Dec VRA eVRA VDec eVDec Vlos eVlos Extra_Coo eExtra_Coo Extra_Coo_2 eExtra_Coo_2 ...'\n       print 'Quitting now...'\n       sys.exit(0)\n\n    Sky_eVel = np.where(Sky_eVel < 1e-5, np.average(Sky_eVel), Sky_eVel)\n    Extra_eCoo = np.where(Extra_eCoo < 1e-5, np.average(Extra_eCoo), Extra_eCoo)\n\n    Std_stars_data = [Sky_Coo, Sky_Vel, Sky_eVel, Extra_Coo, Extra_eCoo]\n\n    return Std_stars_data\n\ndef ref_frame(Std_data, galaxy, sref_options):\n\n    \"\"\"\n    Sky, WCS and physical coordinates\n    \"\"\"\n    if sref_options.WCS:\n       Sky_Coo = Std_data[0]\n       Gref_car_Coo = lib.wcs2xy(Sky_Coo, galaxy.Sky_Coo, galaxy.Distance)\n\n    else:\n       Gref_car_Coo = Std_data[0]\n       Sky_Coo = lib.xy2wcs(Gref_car_Coo, galaxy.Sky_Coo, galaxy.Distance)\n\n    \"\"\"\n    Galactic velocity rest frame\n    \"\"\"\n    Gref_car_Vel = Std_data[1] - galaxy.Sky_Vel\n    Gref_car_eVel = Std_data[2]\n\n    if sref_options.Use_elliptical_coordinates:\n       Gref_car_Coo = lib.deproject_ellip(Gref_car_Coo, Ellipticity = galaxy.E, PA = galaxy.PA)\n       try:\n          Gref_car_Vel[:,0:2] = lib.deproject_ellip(Gref_car_Vel[:,0:2], Ellipticity = galaxy.E, PA = galaxy.PA)\n          Gref_car_eVel[:,0:2] = lib.deproject_ellip(Gref_car_eVel[:,0:2], Ellipticity = galaxy.E, PA = galaxy.PA)\n       except:\n          pass\n    \"\"\"\n    Galactic elliptical coordinates\n    \"\"\"\n    Gref_pol_Coo = lib.polar_coo(Gref_car_Coo)\n    Gref_pol_Vel = lib.polar_vel(Gref_car_Coo, Gref_car_Vel)\n    Gref_pol_eVel = np.abs(lib.polar_vel(Gref_car_Coo, Gref_car_eVel))\n    \n    print 'Right now beacon accepts either FeH and eFeH, or whatever linear coordinates user may provide, but NOT both (FeH and linear coordinates) at the same time!'\n    try:\n       Extra_Coo, Extra_eCoo = Std_data[3], Std_data[4]\n       if sref_options.Extra_Coo_is_FeH:\n          Z, eZ = lib.log2lin_metal(Extra_Coo, Extra_eCoo)\n          FeH, eFeH = Extra_Coo, Extra_eCoo\n          Rest_frame_coo = [Sky_Coo, Gref_car_Coo, Gref_car_Vel, Gref_car_eVel, Gref_pol_Coo, Gref_pol_Vel, Gref_pol_eVel, Z, eZ, FeH, eFeH]\n       else:\n          Rest_frame_coo = [Sky_Coo, Gref_car_Coo, Gref_car_Vel, Gref_car_eVel, Gref_pol_Coo, Gref_pol_Vel, Gref_pol_eVel, Extra_Coo, Extra_eCoo]\n    except:\n       Rest_frame_coo = [Sky_Coo, Gref_car_Coo, Gref_car_Vel, Gref_car_eVel, Gref_pol_Coo, Gref_pol_Vel, Gref_pol_eVel]\n\n    Stars_data_rf = stars_generator(Rest_frame_coo)\n    \n    return Stars_data_rf()\n\ndef rest_frame_generator(galaxy, read_data_options, sref_options):\n            \n    if (sref_options.Find_centre_sky_radius != 0) and (sref_options.Find_centre_vhel_radius !=0):\n        Find_centre_coordinates_list = np.mgrid[galaxy.Sky_Coo[0]-sref_options.Find_centre_sky_radius/60. : galaxy.Sky_Coo[0]+sref_options.Find_centre_sky_radius/60. :  sref_options.Find_centre_sky_resolution/60., galaxy.Sky_Coo[1]-sref_options.Find_centre_sky_radius/60. :  galaxy.Sky_Coo[1]+sref_options.Find_centre_sky_radius/60. : sref_options.Find_centre_sky_resolution/60., galaxy.Sky_Vel-sref_options.Find_centre_vhel_radius : galaxy.Sky_Vel+sref_options.Find_centre_vhel_radius: sref_options.Find_centre_vhel_resolution]\n        \n        Find_centre_RA_sky_coordinates_List = Find_centre_coordinates_list[0].flatten()\n        Find_centre_Dec_sky_coordinates_List = Find_centre_coordinates_list[1].flatten()\n        Find_centre_Vhel_sky_coordinates_List = Find_centre_coordinates_list[2].flatten()\n        Dimensions = np.shape(Find_centre_coordinates_list[0])\n        \n    elif (sref_options.Find_centre_sky_radius != 0) and (sref_options.Find_centre_vhel_radius == 0):\n        Sky_coo_list = np.mgrid[galaxy.Sky_Coo[0]-sref_options.Find_centre_sky_radius/60. : galaxy.Sky_Coo[0]+sref_options.Find_centre_sky_radius/60. :  sref_options.Find_centre_sky_resolution/60., galaxy.Sky_Coo[1]-sref_options.Find_centre_sky_radius/60. :  galaxy.Sky_Coo[1]+sref_options.Find_centre_sky_radius/60. : sref_options.Find_centre_sky_resolution/60.]\n        \n        Find_centre_RA_sky_coordinates_List = Sky_coo_list[0].flatten()\n        Find_centre_Dec_sky_coordinates_List = Sky_coo_list[1].flatten()\n        Find_centre_Vhel_sky_coordinates_List = np.ones(len(Sky_coo_list[0].flatten()))*galaxy.Sky_Vel\n        Dimensions = np.shape(Sky_coo_list[0])\n    \n    elif (sref_options.Find_centre_sky_radius == 0) and (sref_options.Find_centre_vhel_radius != 0):        \n        Find_centre_RA_sky_coordinates_List = np.ones(len(Vhel_coo_list))*galaxy.Sky_Coo[0]\n        Find_centre_Dec_sky_coordinates_List = np.ones(len(Vhel_coo_list))*galaxy.Sky_Coo[1]\n        Find_centre_Vhel_sky_coordinates_List = np.arange(galaxy.Sky_Vel-sref_options.Find_centre_vhel_radius, galaxy.Sky_Vel+sref_options.Find_centre_vhel_radius, sref_options.Find_centre_vhel_resolution)\n        Dimensions = 1\n\n    else:\n        Find_centre_RA_sky_coordinates_List = [galaxy.Sky_Coo[0]]\n        Find_centre_Dec_sky_coordinates_List = [galaxy.Sky_Coo[1]]\n        Find_centre_Vhel_sky_coordinates_List = [galaxy.Sky_Vel]\n        Dimensions = 0\n    \n    Std_data = read_data(read_data_options)\n    \n    Stars_data_lis = []\n    \n    for Find_centre_RA_sky_coordinates, Find_centre_Dec_sky_coordinates, Find_centre_Vhel_coordinates in zip(Find_centre_RA_sky_coordinates_List, Find_centre_Dec_sky_coordinates_List, Find_centre_Vhel_sky_coordinates_List):\n             \n       galaxy.Sky_Coo = np.array([Find_centre_RA_sky_coordinates, Find_centre_Dec_sky_coordinates])\n       galaxy.Sky_Vel = np.array([Find_centre_Vhel_coordinates])\n                     \n       Stars_data_lis.append(ref_frame(Std_data, galaxy, sref_options))\n    \n    return Stars_data_lis, Find_centre_RA_sky_coordinates_List, Find_centre_Dec_sky_coordinates_List, Find_centre_Vhel_sky_coordinates_List, Dimensions\n\ndef autoorder(Possible_Circular_Stream_Indices, Possible_NonCircular_Stream_Indices, stars_data):\n\n    try:\n       OV = stars_data.Z\n    except:\n       OV = stars_data.Extra_Coo\n       \n    Possible_Circular_Stream_Mean_OV = []\n    for Circ_Index in Possible_Circular_Stream_Indices:\n        Possible_Circular_Stream_Mean_OV.append(np.mean(OV[list(Circ_Index)]))\n\n    Possible_NonCircular_Stream_Mean_OV = []\n    for NonCirc_Index in Possible_NonCircular_Stream_Indices:\n        Possible_NonCircular_Stream_Mean_OV.append(np.mean(OV[list(NonCirc_Index)]))        \n        \n    \"\"\"\n    Order Results By OV\n    \"\"\"\n    Possible_Circular_Stream_Sorted_Indices = sorted(range(len(Possible_Circular_Stream_Mean_OV)), key=lambda k: Possible_Circular_Stream_Mean_OV[k])\n    Possible_NonCircular_Stream_Sorted_Indices = sorted(range(len(Possible_NonCircular_Stream_Mean_OV)), key=lambda k: Possible_NonCircular_Stream_Mean_OV[k])\n\n    Possible_Circular_Stream_Indices = [Possible_Circular_Stream_Indices[i] for i in Possible_Circular_Stream_Sorted_Indices]\n\n    Possible_NonCircular_Stream_Indices = [Possible_NonCircular_Stream_Indices[i] for i in Possible_NonCircular_Stream_Sorted_Indices]\n\n    return Possible_Circular_Stream_Indices, Possible_NonCircular_Stream_Indices\n    \ndef beacon(Rest_frame_coo, beacon_options):\n\n    \"\"\"\n    This routine will call OPTICS with an apropiate set of coordinates. \n    Tipically coordinates, velocities, and chemical abundances\n    \"\"\"\n\n    if (beacon_options.Coordinate_system == 'pol'):\n       \"\"\"\n       Coo are the coordinates of the stars. The angle (Theta), must be inverted, but not the radius\n       \"\"\"\n       Coo = Rest_frame_coo.Gref_pol_Coo\n       Simmet_Coo = np.array([Rest_frame_coo.Gref_pol_Coo[:,0], (Rest_frame_coo.Gref_pol_Coo[:,1]+np.pi) % (2.*np.pi)]).T\n       \n    if (beacon_options.Velocity_system == 'pol'):\n       \"\"\"\n       Polar velocities are expected to be the same at both sides of\n       the CM, except for the line-of-sight (z) component, that shoud be inverted.\n       \"\"\"\n       Vel = Rest_frame_coo.Gref_pol_Vel\n       Simmet_Vel = np.array([Vel[:,0], Vel[:,1], -1.*Vel[:,2]]).T\n\n    if (beacon_options.Coordinate_system == 'car'):\n       \"\"\"\n       If one prefers cartesian coordinates, then both have to be inverted\n       \"\"\"\n       Coo = Rest_frame_coo.Gref_car_Coo\n       Simmet_Coo = np.array([(-Rest_frame_coo.Gref_car_Coo[:,0]), -Rest_frame_coo.Gref_car_Coo[:,1]]).T\n\n    if (beacon_options.Velocity_system == 'car'):\n       \"\"\"\n       All cartesian components of the velocity are expected to be the\n       oposite at the other side of the CM.\n       \"\"\"\n       Vel = Rest_frame_coo.Gref_car_Vel\n       Simmet_Vel = -1.*Vel    \n\n    \"\"\"\n    Extra properties should be consistently equal at both sides of the CM (In case they exist)\n    \"\"\"\n    try:\n       Extra = Rest_frame_coo.Z\n    except:\n       pass\n    try:\n       Extra = Rest_frame_coo.Extra_Coo\n    except:\n       pass\n    try:\n       if Extra.ndim == 1:\n          Extra = np.expand_dims(Extra, axis=1)\n\n       Direct_Clustering_Data = np.hstack([Coo, Vel, Extra])\n       Simmet_Clustering_Data = np.hstack([Simmet_Coo, Simmet_Vel, Extra])\n    except:\n       Direct_Clustering_Data = np.hstack([Coo, Vel])\n       Simmet_Clustering_Data = np.hstack([Simmet_Coo, Simmet_Vel])\n\n    OAL = len(Direct_Clustering_Data)   # Original Array Length\n\n    \"\"\"\n    If the only coordinates being used are v_rot and v_rad then don't use the simmetric vector\n    \"\"\"\n    if (beacon_options.Velocity_system == 'pol') & (beacon_options.Standarization_Weights[4] == 0):\n      Clustering_Data = Direct_Clustering_Data\n      mcs = beacon_options.Min_cluster_size\n    else:\n      Clustering_Data = np.vstack([Direct_Clustering_Data, Simmet_Clustering_Data])\n      mcs = float(beacon_options.Min_cluster_size)*2.\n\n    if not Clustering_Data.size:\n      print 'No stars remain after cleaning, check option file!'\n      quit()\n    \"\"\"\n    Standardization\n    \"\"\"\n    if beacon_options.Standarization_Method == 'ptp':\n        Clustering_Data /= np.ptp(Direct_Clustering_Data, axis=0)\n    elif beacon_options.Standarization_Method == 'std':\n        Clustering_Data /= np.std(Direct_Clustering_Data, axis=0)\n    elif beacon_options.Standarization_Method == 'var':\n        Clustering_Data /= np.var(Direct_Clustering_Data, axis=0)\n\n    else:\n        print \"Non standarization was applied!\"\n    \n    try:\n        Clustering_Data *= beacon_options.Standarization_Weights\n    except:\n        print \"Incorrect dimension of weights. Same weight applied to all coordinates.\"\n    \n    Clustering_Data = Clustering_Data[:,np.where(beacon_options.Standarization_Weights != 0)[0]]\n\n    \"\"\"\n    OPTICS call\n    \"\"\"\n    Indices = optics_launcher(Clustering_Data, beacon_options.Smoothing, min_cluster_size = mcs, maxima_ratio = beacon_options.Maxima_ratio)\n    \n    Possible_Circular_Stream_Indices = []\n    Possible_NonCircular_Stream_Indices = []\n    for ii, Index in enumerate(Indices):\n        if (sum(1 for i in Index if i >= OAL) > len(Index)/beacon_options.Epsilon) & (sum(1 for i in Index if i < OAL) > len(Index)/beacon_options.Epsilon):\n            Possible_Circular_Stream = True\n            Possible_Nonirc_streams = False\n        elif ((Index < OAL).all()) or ((Index >= OAL).all()):\n            Possible_Circular_Stream = False\n            Possible_Nonirc_streams = True\n        else:\n            Possible_Circular_Stream = False\n            Possible_Nonirc_streams = False  \n        Index[Index >= OAL] -= OAL\n        if Possible_Circular_Stream:\n            Possible_Circular_Stream_Indices.append(set(Index))\n        elif Possible_Nonirc_streams:\n            Possible_NonCircular_Stream_Indices.append(set(Index))\n          \n    \"\"\"\n    Uniqueness of the groups\n    \"\"\"\n    if beacon_options.Uniqueness_Method == 'all':    \n        Possible_Circular_Stream_Indices = [list(i) for i in set(tuple(i) for i in Possible_Circular_Stream_Indices)]\n        Possible_NonCircular_Stream_Indices = [list(i) for i in set(tuple(i) for i in Possible_NonCircular_Stream_Indices)]\n        \n    if beacon_options.Uniqueness_Method == 'any':\n        from networkx.algorithms.components.connected import connected_components\n        Possible_Circular_Stream_Indices = list(connected_components(lib.to_graph(Possible_Circular_Stream_Indices)))\n        Possible_NonCircular_Stream_Indices = list(connected_components(lib.to_graph(Possible_NonCircular_Stream_Indices)))\n    \n    \"\"\"\n    If there are many groups, exit program\n    \"\"\"\n    if (len(Possible_Circular_Stream_Indices) > 1000) or (len(Possible_NonCircular_Stream_Indices) > 1000):\n        print 'To many groups: ',len(Possible_Circular_Stream_Indices),' aborting to prevent computer failure...'\n        sys.exit(0)\n\n    return Possible_Circular_Stream_Indices, Possible_NonCircular_Stream_Indices   \n\n\ndef useful_quantities(stars_data, galaxy, sref_options, Indices_list=None):\n    \"\"\"\n    This routine calculates some useful quantities for plotting and arranging results\n    \"\"\"\n    if Indices_list is None:\n        Indices_list = [list(np.arange(len(stars_data.Gref_car_Coo)))]\n\n    \"\"\"\n    Averages must be derived using linear quantities\n    \"\"\"\n    N_Stars = []\n    Velocities_stars = []\n    Extra_Coo_stars = []\n    Radius_stars = []\n    \n    Velocity_groups = []\n    Extra_Coo_groups = []\n    Radius_groups = []\n    Angular_Momenta_groups = []\n\n    print 'WARNING: Projected angular momentum (line-of-sight velocities) with no error!'\n\n    for ii, Indices in enumerate(Indices_list):\n        Indices = list(Indices)\n        \"\"\"\n        Angular Momentum\n        \"\"\"\n        L_k = lib.kinetic_pa(stars_data.Gref_car_Coo[Indices, :], stars_data.Gref_car_Vel[Indices, 2], 1./stars_data.Gref_car_eVel[Indices, 2])\n\n        kl = lib.kinetic_pa(stars_data.Gref_car_Coo[Indices, :], stars_data.Gref_car_Vel[Indices, 2], 1./stars_data.Gref_car_eVel[Indices, 2])\n        if sref_options.Use_elliptical_coordinates:\n           kl[0:2] =  lib.deproject_ellip(kl[0:2], Ellipticity = 1./(1.-1./galaxy.E), PA = galaxy.PA)\n\n        Angular_Momenta_groups.append(kl)\n\n        try:\n           Extra_Coo_stars.append([stars_data.FeH[Indices], stars_data.eFeH[Indices]])\n\n           Avg_Std_Z = lib.avg_std(stars_data.Z[Indices], 1./(stars_data.eZ[Indices])**2)\n\n           Extra_Coo_groups.append(lib.lin2log_metal(Avg_Std_Z[0], Avg_Std_Z[1]))\n        except:\n           pass\n        try:\n           Extra_Coo_stars.append([stars_data.Extra_Coo[Indices], stars_data.Extra_eCoo[Indices]])\n           \n           Extra_Coo_groups.append(lib.avg_std(stars_data.Extra_Coo[Indices], 1./(stars_data.Extra_eCoo[Indices])**2))\n        except:\n           pass\n\n\n        N_Stars.append(len(Indices))\n        Velocities_stars.append([stars_data.Gref_car_Vel[Indices],stars_data.Gref_car_eVel[Indices]])\n        \n        Radius_stars.append(np.sqrt(np.sum(stars_data.Gref_car_Coo[Indices, :]**2, axis = 1)))\n        \n        Velocity_groups.append(lib.avg_std((stars_data.Gref_car_Coo[Indices]), 1./(stars_data.Gref_car_Coo[Indices])**2))\n\n        Radius_groups.append(np.average(np.sqrt(np.sum(stars_data.Gref_car_Coo[Indices, :]**2, axis = 1))))\n\n    \"\"\"\n    CONVERTING LISTS TO ARRAYS\n    \"\"\"\n    N_Stars = np.array(N_Stars)\n    Angular_Momenta_groups = np.array(Angular_Momenta_groups)\n\n    Radius_stars = np.array(Radius_stars)\n    Velocity_groups = np.array(Velocity_groups)\n\n    \"\"\"\n    These quantities may be optional\n    \"\"\"\n    Extra_Coo_stars = np.array(Extra_Coo_stars)    \n    Extra_Coo_groups =  np.array(Extra_Coo_groups)\n    \n\n    Mean_quantities = [Extra_Coo_groups, Velocity_groups, Radius_groups, Angular_Momenta_groups]\n    Raw_quantities = [N_Stars, Extra_Coo_stars, Velocities_stars, Radius_stars]\n\n    return Raw_quantities, Mean_quantities\n\ndef save_clusters(Circ_mean_quantities, File_name = 'Output/Clusters.dat'):\n    Circ_Mean_Metallicity, Circ_Mean_Velocity, Circ_Mean_rDistance, Circ_KL = Circ_mean_quantities\n\n    np.savetxt(File_name, np.array([np.arange(len(Circ_Mean_Metallicity))+1, Circ_Mean_Metallicity[:,0], Circ_Mean_Metallicity[:,1], Circ_KL[:,0], Circ_KL[:,1]]).T, fmt='%i  %.3f  %.3f  %.3f  %.3f', header='Pop   Metal   eMetal   L_angle  L_modulus')\n\ndef save_clustered_stars(stars_data, Stream_Indices, File_name = 'Output/Stars.dat'):\n   Circ_clustered_stars = []\n   for kk, Indices  in enumerate(Stream_Indices):\n      Indices = list(Indices)\n\n      Cluster = np.array([np.array(Indices)+1., stars_data.Sky_Coo[Indices,0], stars_data.Sky_Coo[Indices,1], stars_data.Gref_car_Vel[Indices,2], stars_data.Gref_car_eVel[Indices,2], np.squeeze(stars_data.FeH[Indices]), np.squeeze(stars_data.eFeH[Indices]), np.ones(len(stars_data.FeH[Indices]))*(kk+1)]).T\n\n      Circ_clustered_stars.append(Cluster)\n   Circ_clustered_stars = np.array([item for sublist in Circ_clustered_stars for item in sublist])\n\n   np.savetxt(File_name, Circ_clustered_stars, fmt='%i  %.8f  %.8f  %.3f  %.3f  %.3f  %.3f  %i', header='Indices    RA    DEC    V_los    eV_los    Metal    eMetal    Pop')\n\n\ndef optics_launcher(Data, Smoothing, min_cluster_size = 5., maxima_ratio = 0.75):\n    import optics_core as core\n\n    RD, CD, Order = core.optics(Data,Smoothing)\n\n    Reach_Plot = []\n    Reach_Points = []\n\n    for item in Order:\n        Reach_Plot.append(RD[item])\n        Reach_Points.append(Data[item])\n\n    min_cluster_size_ratio = min_cluster_size / float(len(Data))\n\n    rootNode = core.auto_cluster(Reach_Plot, Reach_Points, min_cluster_size_ratio, maxima_ratio)\n\n    #get only the leaves of the tree\n    leaves = core.get_leaves(rootNode, [])\n\n    index_ordered = []\n    for item in leaves:\n        index_ordered.append(np.array(Order[item.start:item.end]))\n    return index_ordered\n\n\n\"\"\"\nAndres del Pino Molina\n\"\"\"\n", "meta": {"hexsha": "8fe0333f43c50ef112da5211dcbe25765a7aecde", "size": 22062, "ext": "py", "lang": "Python", "max_stars_repo_path": "beacon.py", "max_stars_repo_name": "AndresdPM/BEACON", "max_stars_repo_head_hexsha": "f0206fb67ae900e676b0f4476b7274ee7a6adfc9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "beacon.py", "max_issues_repo_name": "AndresdPM/BEACON", "max_issues_repo_head_hexsha": "f0206fb67ae900e676b0f4476b7274ee7a6adfc9", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "beacon.py", "max_forks_repo_name": "AndresdPM/BEACON", "max_forks_repo_head_hexsha": "f0206fb67ae900e676b0f4476b7274ee7a6adfc9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4291338583, "max_line_length": 528, "alphanum_fraction": 0.6980328166, "include": true, "reason": "import numpy,from networkx", "num_tokens": 5866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.19122010733364103}}
{"text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\nfrom .module import *\n\nAlign_Corners_Range = False\n\n\nclass DepthNet(nn.Module):\n    def __init__(self, mode=\"regression\"):\n        super(DepthNet, self).__init__()\n        self.mode = mode\n        assert self.mode in (\"regression\", \"classification\", \"unification\"), \"Don't support {}!\".format(mode)\n\n    def forward(self, cost_reg, depth_values, num_depth, interval, prob_volume_init=None):\n        prob_volume_pre = cost_reg.squeeze(1)  # (b, d, h, w)\n\n        if prob_volume_init is not None:\n            prob_volume_pre += prob_volume_init\n\n        if self.mode == \"regression\":\n            prob_volume = F.softmax(prob_volume_pre, dim=1)  # (b, ndepth, h, w)\n            depth = depth_regression(prob_volume, depth_values=depth_values)  # (b, h, w)\n            with torch.no_grad():\n                # photometric confidence\n                prob_volume_sum4 = 4 * F.avg_pool3d(F.pad(prob_volume.unsqueeze(1), pad=(0, 0, 0, 0, 1, 2)), (4, 1, 1), stride=1,\n                                                    padding=0).squeeze(1)\n                depth_index = depth_regression(prob_volume,\n                                               depth_values=torch.arange(num_depth, device=prob_volume.device, dtype=torch.float)).long()\n                depth_index = depth_index.clamp(min=0, max=num_depth - 1)\n                photometric_confidence = torch.gather(prob_volume_sum4, 1, depth_index.unsqueeze(1)).squeeze(1)\n        elif self.mode == \"classification\":\n            prob_volume = F.softmax(prob_volume_pre, dim=1)  # (b, ndepth, h, w)\n            depth = winner_take_all(prob_volume, depth_values)  # (b, h, w)\n            photometric_confidence, _ = torch.max(prob_volume, dim=1)\n        elif self.mode == \"unification\":\n            prob_volume = torch.sigmoid(prob_volume_pre)  # (b, ndepth, h, w)\n            depth = unity_regression(prob_volume, depth_values, interval)\n            photometric_confidence, _ = torch.max(F.softmax(prob_volume_pre, dim=1), dim=1)\n            # photometric_confidence = torch.max(prob_volume, dim=1)[0] / torch.sum(prob_volume, dim=1)\n        else:\n            raise NotImplementedError(\"Don't support {}!\".format(self.mode))\n\n        return {\"depth\": depth, \"photometric_confidence\": photometric_confidence, \"prob_volume\": prob_volume,\n                \"depth_values\": depth_values, \"interval\": interval}\n\n\nclass CostAgg(nn.Module):\n    def __init__(self, mode=\"variance\", in_channels=None):\n        super(CostAgg, self).__init__()\n        self.mode = mode\n        assert mode in (\"variance\", \"adaptive\"), \"Don't support {}!\".format(mode)\n        if self.mode == \"adaptive\":\n            self.weight_net = nn.ModuleList([AggWeightNetVolume(in_channels[i]) for i in range(len(in_channels))])\n\n    def forward(self, features, proj_matrices, depth_values, stage_idx):\n        \"\"\"\n        :param stage_idx: stage\n        :param features: [ref_fea, src_fea1, src_fea2, ...], fea shape: (b, c, h, w)\n        :param proj_matrices: (b, nview, ...) [ref_proj, src_proj1, src_proj2, ...]\n        :param depth_values: (b, ndepth, h, w)\n        :return: matching cost volume (b, c, ndepth, h, w)\n        \"\"\"\n        ref_feature, src_features = features[0], features[1:]\n        proj_matrices = torch.unbind(proj_matrices, 1)  # to list\n        ref_proj, src_projs = proj_matrices[0], proj_matrices[1:]\n\n        num_views = len(features)\n        num_depth = depth_values.shape[1]\n\n        ref_volume = ref_feature.unsqueeze(2).repeat(1, 1, num_depth, 1, 1)\n        if self.mode == \"variance\":\n            volume_sum = ref_volume\n            volume_sq_sum = ref_volume ** 2\n            del ref_volume\n        elif self.mode == \"adaptive\":\n            volume_adapt = None\n\n        for src_fea, src_proj in zip(src_features, src_projs):\n            # warpped features\n            src_proj_new = src_proj[:, 0].clone()\n            src_proj_new[:, :3, :4] = torch.matmul(src_proj[:, 1, :3, :3], src_proj[:, 0, :3, :4])\n            ref_proj_new = ref_proj[:, 0].clone()\n            ref_proj_new[:, :3, :4] = torch.matmul(ref_proj[:, 1, :3, :3], ref_proj[:, 0, :3, :4])\n            warped_volume = homo_warping(src_fea, src_proj_new, ref_proj_new, depth_values)\n\n            if self.mode == \"variance\":\n                volume_sum = volume_sum + warped_volume\n                volume_sq_sum = volume_sq_sum + warped_volume ** 2\n            elif self.mode == \"adaptive\":\n                # (b, c, d, h, w)\n                warped_volume = (ref_volume - warped_volume).pow_(2)\n                weight = self.weight_net[stage_idx](warped_volume)\n                if volume_adapt is None:\n                    volume_adapt = (weight + 1) * warped_volume\n                else:\n                    volume_adapt = volume_adapt + (weight + 1) * warped_volume\n\n            del warped_volume\n\n        # aggregate multiple feature volumes by variance\n        if self.mode == \"variance\":\n            volume_variance = volume_sq_sum.div_(num_views).sub_(volume_sum.div_(num_views).pow_(2))\n            return volume_variance\n        elif self.mode == \"adaptive\":\n            return volume_adapt / (num_views - 1)\n\n\nclass MVSNet(nn.Module):\n    def __init__(self, ndepths, depth_interval_ratio, cr_base_chs=None, fea_mode=\"fpn\", agg_mode=\"variance\", depth_mode=\"regression\"):\n        super(MVSNet, self).__init__()\n\n        if cr_base_chs is None:\n            cr_base_chs = [8] * len(ndepths)\n        self.ndepths = ndepths\n        self.depth_interval_ratio = depth_interval_ratio\n        self.fea_mode = fea_mode\n        self.cr_base_chs = cr_base_chs\n        self.num_stage = len(ndepths)\n\n        print(\"netphs:\", ndepths)\n        print(\"depth_intervals_ratio:\", depth_interval_ratio)\n        print(\"cr_base_chs:\", cr_base_chs)\n        print(\"fea_mode:\", fea_mode)\n        print(\"agg_mode:\", agg_mode)\n        print(\"depth_mode:\", depth_mode)\n\n        assert len(ndepths) == len(depth_interval_ratio)\n\n        self.feature = FeatureNet(base_channels=8, stride=4, num_stage=self.num_stage, mode=self.fea_mode)\n        self.cost_aggregation = CostAgg(agg_mode, self.feature.out_channels)\n\n        self.cost_regularization = nn.ModuleList(\n            [CostRegNet(in_channels=self.feature.out_channels[i], base_channels=self.cr_base_chs[i]) for i in range(self.num_stage)])\n\n        self.DepthNet = DepthNet(depth_mode)\n\n    def forward(self, imgs, proj_matrices, depth_values):\n        \"\"\"\n        :param is_flip: augment only for 3D-UNet\n        :param imgs: (b, nview, c, h, w)\n        :param proj_matrices:\n        :param depth_values:\n        :return:\n        \"\"\"\n        depth_interval = (depth_values[0, -1] - depth_values[0, 0]) / depth_values.size(1)\n\n        # step 1. feature extraction\n        features = []\n        for nview_idx in range(imgs.size(1)):  # imgs shape (B, N, C, H, W)\n            img = imgs[:, nview_idx]\n            features.append(self.feature(img))\n\n        ori_shape = imgs[:, 0].shape[2:]  # (H, W)\n\n        outputs = {}\n        last_depth = None\n        for stage_idx in range(self.num_stage):\n            # print(\"*********************stage{}*********************\".format(stage_idx + 1))\n            # stage feature, proj_mats, scales\n            features_stage = [feat[\"stage{}\".format(stage_idx + 1)] for feat in features]\n            proj_matrices_stage = proj_matrices[\"stage{}\".format(stage_idx + 1)]\n            # stage1: 1/4, stage2: 1/2, stage3: 1\n            stage_scale = 2 ** (3 - stage_idx - 1)\n\n            stage_shape = [ori_shape[0] // int(stage_scale), ori_shape[1] // int(stage_scale)]\n\n            if stage_idx == 0:\n                last_depth = depth_values\n            else:\n                last_depth = last_depth.detach()\n\n            # (B, D, H, W)\n            depth_range_samples, interval = get_depth_range_samples(last_depth=last_depth,\n                                                                    ndepth=self.ndepths[stage_idx],\n                                                                    depth_inteval_pixel=self.depth_interval_ratio[\n                                                                                            stage_idx] * depth_interval,\n                                                                    shape=stage_shape  # only for first stage\n                                                                    )\n\n            if stage_idx > 0:\n                depth_range_samples = F.interpolate(depth_range_samples, stage_shape, mode='bilinear', align_corners=Align_Corners_Range)\n\n            # (b, c, d, h, w)\n            cost_volume = self.cost_aggregation(features_stage, proj_matrices_stage, depth_range_samples, stage_idx)\n            # cost volume regularization\n            # (b, 1, d, h, w)\n            cost_reg = self.cost_regularization[stage_idx](cost_volume)\n\n            # depth\n            outputs_stage = self.DepthNet(cost_reg, depth_range_samples, num_depth=self.ndepths[stage_idx], interval=interval)\n\n            last_depth = outputs_stage['depth']\n\n            outputs[\"stage{}\".format(stage_idx + 1)] = outputs_stage\n            outputs.update(outputs_stage)\n\n        return outputs\n", "meta": {"hexsha": "46ba0b06354ee1c63842cdd0c6c94d51dd1af738", "size": 9193, "ext": "py", "lang": "Python", "max_stars_repo_path": "networks/mvsnet.py", "max_stars_repo_name": "prstrive/UniMVSNet", "max_stars_repo_head_hexsha": "7c1c9862cc6f2eb0b74c0569d58826d9416195b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 75, "max_stars_repo_stars_event_min_datetime": "2022-01-06T05:23:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:14:29.000Z", "max_issues_repo_path": "networks/mvsnet.py", "max_issues_repo_name": "prstrive/UniMVSNet", "max_issues_repo_head_hexsha": "7c1c9862cc6f2eb0b74c0569d58826d9416195b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2022-02-15T03:19:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T04:42:39.000Z", "max_forks_repo_path": "networks/mvsnet.py", "max_forks_repo_name": "prstrive/UniMVSNet", "max_forks_repo_head_hexsha": "7c1c9862cc6f2eb0b74c0569d58826d9416195b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2022-03-11T11:45:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T02:43:39.000Z", "avg_line_length": 45.736318408, "max_line_length": 137, "alphanum_fraction": 0.5820733167, "include": true, "reason": "import numpy", "num_tokens": 2200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.19119742095137066}}
{"text": "# Copyright (c) 2018 Patricio Cubillos and contributors.\n# eclipse is open-source software under the MIT license (see LICENSE).\n\n__all__ = [\"eclipse\", \"mandelecl\"]\n\n\nimport os\nimport sys\nimport numpy as np\n\nlibdir = os.path.realpath(os.path.dirname(__file__) + \"/lib\")\nsys.path.append(libdir)\nimport _eclipse as ecl\n\n\nclass Ecl(object):\n  \"\"\"\n  Eclipse-model superclass.\n  \"\"\"\n  def __init__(self, time=None, mask=None, params=None):\n    self.type = \"astro\"\n    self.npars = len(self.pnames)\n    self.params = np.zeros(self.npars)\n    if params is not None:\n      self.params[:] = params\n    self.pmin   = np.tile(-np.inf, self.npars)\n    self.pmax   = np.tile( np.inf, self.npars)\n    self.pstep  = np.zeros(self.npars)\n    if time is not None:\n      self.setup(time)\n\n\n  def __call__(self, params, time=None, mask=None, update=False):\n    \"\"\"\n    Call function using self values as defaults.\n\n    Parameters\n    ----------\n    params: 1D float ndarray\n       Model parameters (see class docstring for details).\n    time: 1D float ndarray\n       Phase/times where to evaluate the model.\n    mask: 1D bool ndarray\n       Times good-value mask.\n    update: Bool\n       If True, updated the object's attributes.\n    \"\"\"\n    if update:\n      self.setup(time, mask, params)\n\n    if time is None:\n      time = self.time\n\n    if mask is not None:\n      return self.eval(params, time[mask])\n    elif self.mask is not None:\n      return self.eval(params, time[self.mask])\n\n    return self.eval(params, time)\n\n\n  def setup(self, time=None, mask=None, params=None, obj=None):\n    \"\"\"\n    Set the model's attributes (when not None).\n\n    Parameters\n    ----------\n    time: 1D float ndarray\n       Phase/times where to evaluate the model.\n    mask: 1D bool ndarray\n       Times good-value mask.\n    params: 1D float ndarray\n       Model parameters.\n    obj: An object\n       If not None, extract the time and mask values from the\n       object's attributes.\n    \"\"\"\n    if obj is not None:\n      time = obj.time\n      if mask is None:  # Input mask takes priority over obj.mask\n        mask = obj.mask\n      # FINDME: do I want params?\n\n    # Independent variables:\n    if time is not None:\n      if mask is None:\n        mask = np.ones(len(time), bool)\n      self.time = time\n      self.mask = mask\n    # Model parameters:\n    if params is not None:\n      self.params[:] = params\n\n\nclass eclipse(Ecl):\n  \"\"\"\n  A secondary-eclipse model for the times of the Webb.\n\n  This class implements a Mandel & Agol eclipse model with independent\n  ingress and egress depths, and the out-of-eclipse flux as a second-\n  degree polynomial.\n\n  This model has nine parameters (self.params, see also self.pnames):\n   - midpt: Mid-eclipse epoch.\n   - width: Eclipse duration between first and fourth contacts (T14).\n   - idepth: Normalized eclipse depth at ingress (T1) relative to a\n             stellar flux of 1.0.  That is,\n             idepth = (flux(T1) - flux(T2))/flux(T2).\n   - edepth: Normalized eclipse depth at egress (T4) relative to a\n             stellar flux of 1.0.  That is,\n             edepth = (flux(T4) - flux(T3))/flux(T3).\n   - ting: Ingress duration (time between first and second contacts, T12).\n   - tegr: Egress duration (time between third and fourth contacts, T34).\n   - flux: Stellar flux level.  That is, flux during eclipse:\n           flux = flux(T2) = flux(T3).\n   - slope: Out-of-eclipse linear slope.\n   - quad: Out-of-eclipse quadratic term slope.\n\n  The time units are arbitrary, and thus, a user's choice.  Note that\n  midpt, width, ting, terg, and time must have consistent units.\n\n  Attributes\n  ----------\n  name: String\n     The model's name.\n  type: String\n     The type of model.\n  pnames: 1D string list\n     Names of the model parameters.\n  npars: Integer\n     The number of model parameters.\n  params: 1D float ndarray\n     The model parameter values.\n  pmin: 1D float ndarray\n     Minimum-value boundary of the parameters (for MCMCs).\n  pmax: 1D float ndarray\n     Maximum-value boundary of the parameters (for MCMCs).\n  pstep: 1D float ndarray\n     Parameter stepsize (for MCMCs).\n  time: 1D float ndarray\n     The model's independent variable (timestamps where to evaluate).\n  mask: 1D bool ndarray\n     Time good-value mask.\n\n  Example\n  -------\n  >>> import sys\n  >>> import numpy as np\n  >>> import matplotlib.pyplot as plt\n\n  >>> sys.path.append(\"../eclipse\")\n  >>> import eclipse as ecl\n\n  >>> # Create an eclipse model with given orbital-phase timestamps:\n  >>> phase = np.linspace(0.35, 0.65, 300)\n  >>> model = ecl.eclipse(time=phase)\n  >>> # Define eclipse parameters:\n  >>> #               [midpt width idepth edepth ting  tegr  flux slope  quad]\n  >>> params = np.array([0.5, 0.1, 0.01, 0.008,  0.01, 0.01, 1.0, -0.02, -0.03])\n  >>> # One can call the eval function:\n  >>> eclipse1 = model.eval(params, phase)\n  >>> # Or directly call the object (no need to pass the phase):\n  >>> params[8] = 0.0  # Linear-slope model\n  >>> eclipse2 = model(params)\n\n  >>> # Show results:\n  >>> plt.figure(0)\n  >>> plt.clf()\n  >>> plt.plot(phase, eclipse1, \".-\", color='b')\n  >>> plt.plot(phase, eclipse2, \".-\", color='orange')\n  >>> plt.xlim(0.34, 0.66)\n  >>> plt.ylim(0.999, 1.013)\n  >>> plt.xlabel(\"Orbital phase\")\n  >>> plt.ylabel(\"Flux\")\n  \"\"\"\n  def __init__(self, time=None, mask=None, params=None):\n    \"\"\"\n    Class constructor.\n\n    Parameters\n    ----------\n    time: 1D float ndarray\n       Phase/times where to evaluate the model.\n    mask: 1D bool ndarray\n       Times good-value mask.\n    params: 1D float ndarray\n       Model parameters (see class docstring for details).\n    \"\"\"\n    self.name = \"eclipse\"\n    self.pnames = [\"midpt\", \"width\", \"idepth\", \"edepth\", \"ting\", \"tegr\",\n                   \"flux\", \"slope\", \"quad\"]\n    super(eclipse, self).__init__(time, mask, params)\n    # Update pmin:\n    self.pmin = np.array([-np.inf, 0, 0, 0, 0, 0, 0, -np.inf, -np.inf])\n\n\n  def eval(self, params, time):\n    \"\"\"\n    Evaluate the eclipse function at the specified times.\n\n    Parameters\n    ----------\n    params: 1D float ndarray\n       Model parameters (see class docstring for details).\n    time: 1D float ndarray\n       Phase/times where to evaluate the model.\n    \"\"\"\n    return ecl.eclipse_quad(params, time)\n\n\nclass mandelecl(Ecl):\n  \"\"\"\n  Secondary-eclipse model from Mandel & Agol (2002).\n\n  This model has six parameters (self.params, see also self.pnames):\n   - midpt: mid-eclipse epoch.\n   - width: Eclipse duration between first and fourth contacts (T14).\n   - depth: Normalized eclipse depth relative to a stellar flux of 1.0.\n            That is, depth = dflux/flux.\n   - ting:  Ingress duration (time between first and second contacts, T12).\n   - tegr:  Egress duration (time between third and fourth contacts, T34).\n   - flux:  Stellar flux level, i.e., flux during eclipse.\n\n  The time units are arbitrary, and thus, a user's choice.  Note that\n  midpt, width, ting, terg, and time must have consistent units.\n\n  Attributes\n  ----------\n  name: String\n     The model's name.\n  type: String\n     The type of model.\n  pnames: 1D string list\n     Names of the model parameters.\n  npars: Integer\n     The number of model parameters.\n  params: 1D float ndarray\n     The model parameter values.\n  pmin: 1D float ndarray\n     Minimum-value boundary of the parameters (for MCMCs).\n  pmax: 1D float ndarray\n     Maximum-value boundary of the parameters (for MCMCs).\n  pstep: 1D float ndarray\n     Parameter stepsize (for MCMCs).\n  time: 1D float ndarray\n     The model's independent variable (timestamps where to evaluate).\n  mask: 1D bool ndarray\n     Time good-value mask.\n\n  Example\n  -------\n  >>> import sys\n  >>> import numpy as np\n  >>> import matplotlib.pyplot as plt\n\n  >>> sys.path.append(\"../eclipse\")\n  >>> import eclipse as ecl\n\n  >>> # Create a mandelecl model (setting model.time):\n  >>> phase = np.linspace(0.35, 0.65, 300)\n  >>> model = ecl.mandelecl(phase)\n  >>> # Define eclipse parameters:\n  >>> #                 midpt width depth ting  tegr  flux\n  >>> params = np.array([0.5, 0.1,  0.01, 0.01, 0.01, 1.0])\n  >>> # One can call the eval function:\n  >>> eclipse1 = model.eval(params, phase)\n  >>> # Or directly call the object:\n  >>> params[2] = 0.015  # Change eclipse depth\n  >>> eclipse2 = model(params, phase)\n  >>> # This call can use the default phase, so no need to pass as argument:\n  >>> params[5] = 1.005  # Change flux level\n  >>> eclipse3 = model(params)\n\n  >>> # Show results:\n  >>> plt.figure(0)\n  >>> plt.clf()\n  >>> plt.plot(phase, eclipse1, \".-\", color='b')\n  >>> plt.plot(phase, eclipse2, \".-\", color='orange')\n  >>> plt.plot(phase, eclipse3, \".-\", color='limegreen')\n  >>> plt.xlim(0.34, 0.66)\n  >>> plt.xlabel(\"Orbital phase\")\n  >>> plt.ylabel(\"Flux\")\n  \"\"\"\n  def __init__(self, time=None, mask=None, params=None):\n    \"\"\"\n    Class constructor.\n\n    Parameters\n    ----------\n    time: 1D float ndarray\n       Phase/times where to evaluate the model.\n    mask: 1D bool ndarray\n       Times good-value mask.\n    params: 1D float ndarray\n       Model parameters (see class docstring for details).\n    \"\"\"\n    self.name = \"mandelecl\"\n    self.pnames = [\"midpt\",  \"width\",  \"depth\",  \"ting\",  \"tegr\",  \"flux\"]\n    super(mandelecl, self).__init__(time, mask, params)\n    # Update pmin:\n    self.pmin   = np.array([-np.inf, 0.0, 0.0, 0.0, 0.0, -np.inf])\n\n\n  def eval(self, params, time):\n    \"\"\"\n    Evaluate the eclipse function at the specified times.\n\n    Parameters\n    ----------\n    params: 1D float ndarray\n       Model parameters (see class docstring for details).\n    time: 1D float ndarray\n       Phase/times where to evaluate the model.\n    \"\"\"\n    return ecl.mandelecl(params, time)\n", "meta": {"hexsha": "6181c2877688353c02eff3287ff7a4f4b0633e1c", "size": 9671, "ext": "py", "lang": "Python", "max_stars_repo_path": "eclipse/eclmodels.py", "max_stars_repo_name": "pcubillos/eclipse", "max_stars_repo_head_hexsha": "3a8da9cbdac4782bfe286b3a4a6582c157ef1625", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eclipse/eclmodels.py", "max_issues_repo_name": "pcubillos/eclipse", "max_issues_repo_head_hexsha": "3a8da9cbdac4782bfe286b3a4a6582c157ef1625", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eclipse/eclmodels.py", "max_forks_repo_name": "pcubillos/eclipse", "max_forks_repo_head_hexsha": "3a8da9cbdac4782bfe286b3a4a6582c157ef1625", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6044303797, "max_line_length": 80, "alphanum_fraction": 0.6326129666, "include": true, "reason": "import numpy", "num_tokens": 2646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.542863297964157, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.19119741726013398}}
{"text": "\"\"\"\nCoordinateMaps map (transform) an image from an input space to an output space.\n\nA CoordinateMap object contains all the details about an input\nCoordinateSystem, an output CoordinateSystem and the mappings between\nthem.  The *mapping* transforms an image from the input coordinate\nsystem to the output coordinate system.  And the *inverse_mapping*\nperforms the opposite transformation.  The *inverse_mapping* can be\nspecified explicity when creating the CoordinateMap or implicitly in the\ncase of an Affine CoordinateMap.\n\n\"\"\"\n\n\"\"\"\nMatthew, Cindee thoughts\n\nShould we change the order of input args to CoordinateMap to:\n\nCoordinateMap(input_coords, output_coords, mapping, inverse_mapping=None)\nor keep as\nCoordinateMap(mapping, input_coords, output_coords, inverse_mapping=None)\n\nCoordinateMap.ndim should be renamed to CoordinateMap.ndims, because it returns more than one value.\n\nAffine should be renamed to AffineMap, or AffineCoordMap, or something\n\nWe need to think about whether coordinate values should be N by 3\n(where 3 is the number of coordinates in the coordinate system), or 3\nby N.\n\n3 by N makes more sense when we think of applying an affine matrix to the points.\n\nWe might think, that if we have a matrix ``arr`` with points in, then\n``arr[0]`` should be the first point [x,y,z], rather then the first coordinate\nvalue of all the points - N values of [x]\n\nConsider renaming reorder_input to self.input_reordered() or\nsomething.  reorder_output similarly.\n\nThat's as far as we got.\n\n\"\"\"\n\n\nimport warnings\n\nimport numpy as np\n\nimport nipy.core.transforms.affines as affines\nfrom nipy.core.reference.coordinate_system import(CoordinateSystem, \n                                                          safe_dtype)\nfrom nipy.core.reference.coordinate_system import product as coordsys_product\n\n__docformat__ = 'restructuredtext'\n\nclass CoordinateMap(object):\n    \"\"\"A set of input and output CoordinateSystems and a mapping between them.\n\n    For example, the mapping may represent the mapping of an image\n    from voxel space (the input coordinates) to real space (the output\n    coordinates).  The mapping may be an affine or non-affine\n    transformation.\n\n    Attributes\n    ----------\n    input_coords : :class:`CoordinateSystem`\n        The input coordinate system.\n    output_coords : :class:`CoordinateSystem`\n        The output coordinate system.\n    mapping : callable\n        A callable that maps the input_coords to the output_coords.\n    inverse_mapping : None or callable\n        A callable that maps the output_coords to the input_coords.\n        Not all mappings have an inverse, in which case\n        inverse_mapping is None.\n        \n    Examples\n    --------\n    >>> input_coords = CoordinateSystem('ijk', 'voxels')\n    >>> output_coords = CoordinateSystem('xyz', 'world')\n    >>> mni_orig = np.array([-90.0, -126.0, -72.0])\n    >>> mapping = lambda x: x + mni_orig\n    >>> inv_mapping = lambda x: x - mni_orig\n    >>> cm = CoordinateMap(mapping, input_coords, output_coords, inv_mapping)\n\n    Map the first 3 voxel coordinates, along the x-axis, to mni space:\n\n    >>> x = np.array([[0,0,0], [1,0,0], [2,0,0]])\n    >>> cm.mapping(x)\n    array([[ -90., -126.,  -72.],\n           [ -89., -126.,  -72.],\n           [ -88., -126.,  -72.]])\n\n\n    \"\"\"\n    def __init__(self, mapping, \n                 input_coords, \n                 output_coords, \n                 inverse_mapping=None):\n        \"\"\"Create a CoordinateMap given the input/output coords and mappings.\n\n        Parameters\n        ----------\n        mapping : callable\n           The mapping between input and output coordinates\n        input_coords : :class:`CoordinateSystem`\n           The input coordinate system\n        output_coords : :class:`CoordinateSystem`\n           The output coordinate system\n        inverse_mapping : None or callable, optional\n           The optional inverse of mapping, with the intention being\n           ``x = inverse_mapping(mapping(x))``.  If the mapping is\n           affine and invertible, then this is true for all x.  The\n           default is None\n\n        Returns\n        -------\n        coordmap : CoordinateMap\n        \"\"\"\n        # These attrs define the structure of the coordmap.\n        self._mapping = mapping\n        self._input_coords = input_coords\n        self._output_coords = output_coords\n        self._inverse_mapping = inverse_mapping\n\n        if not callable(mapping):\n            raise ValueError('The mapping must be callable.')\n        if inverse_mapping is not None:\n            if not callable(inverse_mapping):\n                raise ValueError('The inverse_mapping must be callable.')\n        self._checkmapping()\n\n    @property\n    def input_coords(self):\n        'input coordinate system'\n        return self._input_coords\n\n    @property\n    def output_coords(self):\n        'output coordinate system'\n        return self._output_coords\n\n    @property\n    def mapping(self):\n        'The mapping from input_coords to output_coords.'\n        return self._mapping\n\n    @property\n    def inverse_mapping(self):\n        'The mapping from output_coords to input_coords'\n        return self._inverse_mapping\n\n    @property\n    def inverse(self):\n        \"\"\"\n        Return a new CoordinateMap with the mappings reversed\n        \"\"\"\n        if self._inverse_mapping is None:\n            return None\n        return CoordinateMap(self._inverse_mapping, \n                             self._output_coords, \n                             self._input_coords, \n                             inverse_mapping=self._mapping)\n\n    @property\n    def ndim(self):\n        'Number of dimensions of input and output coordinates.'\n        return (self._input_coords.ndim, self._output_coords.ndim)\n\n    def _checkmapping(self):\n        \"\"\"Verify that the input and output dimensions of self.mapping work.\n\n        We do this by passing something that should work, through __call__\n        \"\"\"\n        inp = np.zeros((10, self.ndim[0]),\n                       dtype=self._input_coords.coord_dtype)\n        out = self(inp)\n\n    def __call__(self, x):\n        \"\"\"Return mapping evaluated at x\n\n        Check input and output of mapping for compatiblity with input\n        and output coordinate systems respectively.\n\n        Parameters\n        ----------\n        x : array-like\n           Values in input coordinate system space that will be mapped\n           to the output coordinate system space, using\n           ``self.mapping``\n           \n        Returns\n        -------\n        y : array\n           Values in output coordinate system space\n\n        Examples\n        --------\n        >>> input_cs = CoordinateSystem('ijk')\n        >>> output_cs = CoordinateSystem('xyz')\n        >>> mapping = lambda x:x+1\n        >>> inverse = lambda x:x-1\n        >>> cm = CoordinateMap(mapping, input_cs, output_cs, inverse)\n        >>> cm([2,3,4])\n        array([[3, 4, 5]])\n        >>> cmi = cm.inverse\n        >>> cmi([2,6,12])\n        array([[ 1,  5, 11]])\n\n        \"\"\"\n\n        in_vals = self._input_coords._checked_values(x)\n        out_vals = self._mapping(in_vals)\n        return self._output_coords._checked_values(out_vals)\n\n    def copy(self):\n        \"\"\"Create a copy of the coordmap.\n\n        Returns\n        -------\n        coordmap : CoordinateMap\n\n        \"\"\"\n\n        return CoordinateMap(self._mapping, \n                             self._input_coords,\n                             self._output_coords, \n                             inverse_mapping=self._inverse_mapping)\n\nclass Affine(CoordinateMap):\n    \"\"\"\n    A class representing an affine transformation from an input\n    coordinate system to an output coordinate system.\n    \n    This class has an affine property, which is a matrix representing\n    the affine transformation in homogeneous coordinates.  This matrix\n    is used to perform mappings, rather than having an explicit\n    mapping function.\n\n    >>> inp_cs = CoordinateSystem('ijk')\n    >>> out_cs = CoordinateSystem('xyz')\n    >>> cm = Affine(np.diag([1, 2, 3, 1]), inp_cs, out_cs)\n    >>> cm.affine\n    array([[ 1.,  0.,  0.,  0.],\n           [ 0.,  2.,  0.,  0.],\n           [ 0.,  0.,  3.,  0.],\n           [ 0.,  0.,  0.,  1.]])\n    >>> cm([1,1,1])\n    array([[ 1.,  2.,  3.]])\n    >>> icm = cm.inverse\n    >>> icm([1,2,3])\n    array([[ 1.,  1.,  1.]])\n    \"\"\"\n\n    def __init__(self, affine, input_coords, output_coords):\n        \"\"\"\n        Return an CoordinateMap specified by an affine transformation\n        in homogeneous coordinates.\n        \n        Parameters\n        ----------\n        affine : array-like\n           affine homogenous coordinate matrix\n        input_coords : :class:`CoordinateSystem`\n           input coordinates\n        output_coords : :class:`CoordinateSystem`\n           output coordinates\n\n        Notes\n        -----\n        The dtype of the resulting matrix is determined by finding a\n        safe typecast for the input_coords, output_coords and affine.\n        \"\"\"\n        affine = np.asarray(affine)\n        dtype = safe_dtype(affine.dtype,\n                           input_coords.coord_dtype,\n                           output_coords.coord_dtype)\n        inaxes = input_coords.coord_names\n        outaxes = output_coords.coord_names\n        self._input_coords = CoordinateSystem(inaxes,\n                                              input_coords.name,\n                                              dtype)\n        self._output_coords = CoordinateSystem(outaxes,\n                                               output_coords.name,\n                                               dtype)\n        affine = np.asarray(affine, dtype=dtype)\n        if affine.shape != (self.ndim[1]+1, self.ndim[0]+1):\n            raise ValueError('coordinate lengths do not match '\n                             'affine matrix shape')\n        self._affine = affine\n        A, b = affines.to_matrix_vector(affine)\n        def _mapping(x):\n            value = np.dot(x, A.T)\n            value += b\n            return value\n        self._mapping = _mapping\n\n    @property\n    def affine(self):\n        \"\"\"The affine transform matrix of the Affine CoordinateMap.\"\"\"\n        return self._affine\n    \n    @property\n    def inverse_mapping(self):\n        \"\"\"The inverse affine mapping from the Affine CoordinateMap.\"\"\"\n        inverse = self.inverse\n        if inverse is None:\n            raise ValueError('There is no inverse for this affine')\n        return inverse.mapping\n\n    @property\n    def inverse(self):\n        \"\"\"\n        Return the inverse coordinate map.\n        \"\"\"\n        try:\n            return Affine(np.linalg.inv(self.affine), \n                          self.output_coords, \n                          self.input_coords)\n        except np.linalg.linalg.LinAlgError:\n            pass\n\n    @staticmethod\n    def from_params(innames, outnames, params):\n        \"\"\"\n        Create an `Affine` instance from sequences of innames and outnames.\n\n        Parameters\n        ----------\n        innames : ``tuple`` of ``string``\n           The names of the axes of the input coordinate systems\n        outnames : ``tuple`` of ``string``\n           The names of the axes of the output coordinate systems\n        params : `Affine`, `ndarray` or `(ndarray, ndarray)`\n           An affine mapping between the input and output coordinate\n           systems.  This can be represented either by a single\n           ndarray (which is interpreted as the representation of the\n           mapping in homogeneous coordinates) or an (A,b) tuple.\n\n        Returns\n        -------\n        aff : `Affine` object instance\n        \n        Notes\n        -----\n        :Precondition: ``len(shape) == len(names)``\n        \n        :Raises ValueError: ``if len(shape) != len(names)``\n        \"\"\"\n        if type(params) == type(()):\n            A, b = params\n            params = affines.from_matrix_vector(A, b)\n\n        ndim = (len(innames) + 1, len(outnames) + 1)\n        if params.shape != ndim[::-1]:\n            raise ValueError('shape and number of axis names do not agree')\n        dtype = params.dtype\n\n        input_coords = CoordinateSystem(innames, \"input\")\n        output_coords = CoordinateSystem(outnames, 'output')\n        return Affine(params, input_coords, output_coords)\n\n    @staticmethod\n    def from_start_step(innames, outnames, start, step):\n        \"\"\"\n        Create an `Affine` instance from sequences of names, start\n        and step.\n\n        Parameters\n        ----------\n        innames : ``tuple`` of ``string``\n            The names of the axes of the input coordinate systems\n        outnames : ``tuple`` of ``string``\n            The names of the axes of the output coordinate systems\n        start : ``tuple`` of ``float``\n            Start vector used in constructing affine transformation\n        step : ``tuple`` of ``float``\n            Step vector used in constructing affine transformation\n\n        Returns\n        -------\n        cm : `CoordinateMap`\n\n        Examples\n        --------\n        >>> cm = Affine.from_start_step('ijk', 'xyz', [1, 2, 3], [4, 5, 6])\n        >>> cm.affine\n        array([[ 4.,  0.,  0.,  1.],\n               [ 0.,  5.,  0.,  2.],\n               [ 0.,  0.,  6.,  3.],\n               [ 0.,  0.,  0.,  1.]])\n        \n        Notes\n        -----\n        ``len(names) == len(start) == len(step)``\n        \n        \"\"\"\n        ndim = len(innames)\n        if len(outnames) != ndim:\n            raise ValueError('len(innames) != len(outnames)')\n        return Affine.from_params(innames, \n                                  outnames, \n                                  (np.diag(step), start))\n\n    @staticmethod\n    def identity(names):\n        \"\"\"\n        Return an identity coordmap of the given shape.\n        \n        Parameters\n        ----------\n        names : ``tuple`` of ``string`` \n           Names of Axes in output CoordinateSystem\n\n        Returns\n        -------\n        cm : `CoordinateMap` \n           ``CoordinateMap`` with `CoordinateSystem` input and an\n           identity transform, with identical input and output coords.\n\n        Examples\n        --------\n        >>> cm = Affine.identity('ijk')\n        >>> cm.affine\n        array([[ 1.,  0.,  0.,  0.],\n               [ 0.,  1.,  0.,  0.],\n               [ 0.,  0.,  1.,  0.],\n               [ 0.,  0.,  0.,  1.]])\n        >>> print cm.input_coords\n        name: 'input', coord_names: ('i', 'j', 'k'), coord_dtype: float64\n        >>> print cm.output_coords\n        name: 'output', coord_names: ('i', 'j', 'k'), coord_dtype: float64\n        \"\"\"\n        return Affine.from_start_step(names, names, [0]*len(names),\n                                      [1]*len(names))\n\n    def copy(self):\n        \"\"\"\n        Create a copy of the coordmap.\n\n        Returns\n        -------\n        cm : `CoordinateMap`\n\n        Examples\n        --------\n        >>> cm = Affine(np.eye(4), CoordinateSystem('ijk'), CoordinateSystem('xyz'))\n        >>> cm_copy = cm.copy()\n        >>> cm is cm_copy\n        False\n\n        Note that the matrix (affine) is not a pointer to the\n        same data, it's a full independent copy\n\n        >>> cm.affine[0,0] = 2.0\n        >>> cm_copy.affine[0,0]\n        1.0\n        \"\"\"\n        return Affine(self._affine.copy(), self._input_coords,\n                      self._output_coords)\n\n\ndef reorder_input(coordmap, order=None):\n    \"\"\"\n    Create a new coordmap with reversed input_coords.\n    Default behaviour is to reverse the order of the input_coords.\n    If the coordmap has a shape, the resulting one will as well.\n\n    Inputs:\n    -------\n    order: sequence\n         Order to use, defaults to reverse. The elements\n         can be integers, strings or 2-tuples of strings.\n         If they are strings, they should be in coordmap.input_coords.coord_names.\n\n    Returns:\n    --------\n\n    newcoordmap: `CoordinateMap`\n         A new CoordinateMap with reversed input_coords.\n\n    >>> input_cs = CoordinateSystem('ijk')\n    >>> output_cs = CoordinateSystem('xyz')\n    >>> cm = Affine(np.identity(4), input_cs, output_cs)\n    >>> print reorder_input(cm, 'ikj').input_coords\n    name: '-reordered', coord_names: ('i', 'k', 'j'), coord_dtype: float64\n    \"\"\"\n    ndim = coordmap.ndim[0]\n    if order is None:\n        order = range(ndim)[::-1]\n    elif type(order[0]) == type(''):\n        order = [coordmap.input_coords.index(s) for s in order]\n\n    newaxes = [coordmap.input_coords.coord_names[i] for i in order]\n    newincoords = CoordinateSystem(newaxes, \n                                   coordmap.input_coords.name + '-reordered', \n                                   coord_dtype=coordmap.input_coords.coord_dtype)\n    perm = np.zeros((ndim+1,)*2)\n    perm[-1,-1] = 1.\n\n    for i, j in enumerate(order):\n        perm[j,i] = 1.\n\n    perm = perm.astype(coordmap.input_coords.coord_dtype)\n    A = Affine(perm, newincoords, coordmap.input_coords)\n    return compose(coordmap, A)\n\n\ndef reorder_output(coordmap, order=None):\n    \"\"\"\n    Create a new coordmap with reversed output_coords.\n    Default behaviour is to reverse the order of the input_coords.\n    \n    Inputs:\n    -------\n\n    order: sequence\n         Order to use, defaults to reverse. The elements\n         can be integers, strings or 2-tuples of strings.\n         If they are strings, they should be in coordmap.output_coords.coord_names.\n\n    Returns:\n    --------\n        \n    newcoordmap: `CoordinateMap`\n         A new CoordinateMap with reversed output_coords.\n\n    >>> input_cs = CoordinateSystem('ijk')\n    >>> output_cs = CoordinateSystem('xyz')\n    >>> cm = Affine(np.identity(4), input_cs, output_cs)\n    >>> print reorder_output(cm, 'xzy').output_coords\n    name: '-reordered', coord_names: ('x', 'z', 'y'), coord_dtype: float64\n    >>> print reorder_output(cm, [0,2,1]).output_coords.coord_names\n    ('x', 'z', 'y')\n\n    >>> newcm = reorder_output(cm, 'yzx')\n    >>> newcm.output_coords.coord_names\n    ('y', 'z', 'x')\n\n    \"\"\"\n\n    ndim = coordmap.ndim[1]\n    if order is None:\n        order = range(ndim)[::-1]\n    elif type(order[0]) == type(''):\n        order = [coordmap.output_coords.index(s) for s in order]\n\n    newaxes = [coordmap.output_coords.coord_names[i] for i in order]\n    newoutcoords = CoordinateSystem(newaxes, coordmap.output_coords.name + '-reordered', coordmap.output_coords.coord_dtype)\n    \n    perm = np.zeros((ndim+1,)*2)\n    perm[-1,-1] = 1.\n\n    for i, j in enumerate(order):\n        perm[j,i] = 1.\n\n    perm = perm.astype(coordmap.output_coords.coord_dtype)\n    A = Affine(perm, coordmap.output_coords, newoutcoords)\n    return compose(A, coordmap)\n\n\ndef product(*cmaps):\n    \"\"\"\n    Return the \"topological\" product of two or more CoordinateMaps.\n\n    Inputs:\n    -------\n    cmaps : sequence of CoordinateMaps\n\n    Returns:\n    --------\n    cmap : ``CoordinateMap``\n\n    >>> inc1 = Affine.from_params('i', 'x', np.diag([2,1]))\n    >>> inc2 = Affine.from_params('j', 'y', np.diag([3,1]))\n    >>> inc3 = Affine.from_params('k', 'z', np.diag([4,1]))\n\n    >>> cmap = product(inc1, inc3, inc2)\n    >>> cmap.input_coords.coord_names\n    ('i', 'k', 'j')\n    >>> cmap.output_coords.coord_names\n    ('x', 'z', 'y')\n    >>> cmap.affine\n    array([[ 2.,  0.,  0.,  0.],\n           [ 0.,  4.,  0.,  0.],\n           [ 0.,  0.,  3.,  0.],\n           [ 0.,  0.,  0.,  1.]])\n\n    \"\"\"\n    ndimin = [cmap.ndim[0] for cmap in cmaps]\n    ndimin.insert(0,0)\n    ndimin = tuple(np.cumsum(ndimin))\n\n    def mapping(x):\n        x = np.asarray(x)\n        y = []\n        for i in range(len(ndimin)-1):\n            cmap = cmaps[i]\n            if x.ndim == 2:\n                yy = cmaps[i](x[:,ndimin[i]:ndimin[i+1]])\n            else:\n                yy = cmaps[i](x[ndimin[i]:ndimin[i+1]])\n            y.append(yy)\n        yy = np.hstack(y)\n        return yy\n\n    notaffine = filter(lambda x: not isinstance(x, Affine), cmaps)\n\n    incoords = coordsys_product(*[cmap.input_coords for cmap in cmaps])\n    outcoords = coordsys_product(*[cmap.output_coords for cmap in cmaps])\n\n    if not notaffine:\n\n        affine = linearize(mapping, ndimin[-1], dtype=incoords.coord_dtype)\n        return Affine(affine, incoords, outcoords)\n    return CoordinateMap(mapping, incoords, outcoords)\n\n\ndef compose(*cmaps):\n    \"\"\"\n    Return the composition of two or more CoordinateMaps.\n\n    Inputs:\n    -------\n    cmaps : sequence of CoordinateMaps\n\n    Returns:\n    --------\n    cmap : ``CoordinateMap``\n         The resulting CoordinateMap has input_coords == cmaps[-1].input_coords\n         and output_coords == cmaps[0].output_coords\n\n    >>> cmap = Affine.from_params('i', 'x', np.diag([2.,1.]))\n    >>> cmapi = cmap.inverse\n    >>> id1 = compose(cmap,cmapi)\n    >>> print id1.affine\n    [[ 1.  0.]\n     [ 0.  1.]]\n\n    >>> id2 = compose(cmapi,cmap)\n    >>> id1.input_coords.coord_names\n    ('x',)\n    >>> id2.input_coords.coord_names\n    ('i',)\n    >>> \n\n    \"\"\"\n\n    def _compose2(cmap1, cmap2):\n        forward = lambda input: cmap1.mapping(cmap2.mapping(input))\n        if cmap1.inverse is not None and cmap2.inverse is not None:\n            backward = lambda output: cmap2.inverse.mapping(cmap1.inverse.mapping(output))\n        else:\n            backward = None\n        return forward, backward\n\n    cmap = cmaps[-1]\n    for i in range(len(cmaps)-2,-1,-1):\n        m = cmaps[i]\n        if m.input_coords == cmap.output_coords:\n            forward, backward = _compose2(m, cmap)\n            cmap = CoordinateMap(forward, \n                                 cmap.input_coords, \n                                 m.output_coords, \n                                 inverse_mapping=backward)\n        else:\n            raise ValueError(\n                'input and output coordinates do not match: '\n                'input=%s, output=%s' % \n                (`m.input_coords.dtype`, `cmap.output_coords.dtype`))\n\n    notaffine = filter(lambda cmap: not isinstance(cmap, Affine), cmaps)\n    if not notaffine:\n        affine = linearize(cmap, \n                           cmap.ndim[0], \n                           dtype=cmap.output_coords.coord_dtype)\n        return Affine(affine, cmap.input_coords,\n                      cmap.output_coords)\n    return cmap\n    \n\ndef replicate(coordmap, n, concataxis='concat'):\n    \"\"\"\n    Create a CoordinateMap by taking the product\n    of coordmap with a 1-dimensional 'concat' CoordinateSystem\n\n    :Parameters:\n         coordmap : `CoordinateMap`\n                The coordmap to be used\n         n : ``int``\n                The number of tiems to concatenate the coordmap\n         concataxis : ``string``\n                The name of the new dimension formed by concatenation\n    \"\"\"\n\n    raise NotImplementedError('The method this function depends on' \n                              'no longer exists.')\n    \"\"\"\n    concat = CoordinateMap.from_affine([concataxis], [concataxis], \n                                       Affine(np.identity(2)), (n,))\n    return product(concat, coordmap)\n    \"\"\"\n\n\ndef linearize(mapping, ndimin, step=1, origin=None, dtype=None):\n    \"\"\"\n    Given a Mapping of ndimin variables, return the linearization of\n    mapping at origin based on a given step size in each coordinate\n    axis.\n\n    If not specified, origin defaults to np.zeros(ndimin, dtype=dtype).\n    \n    Parameters\n    ----------\n    mapping : callable\n       A function to linearize\n    ndimin : int\n       Number of input dimensions to mapping\n    step : scalar, optional\n       step size over which to calculate linear components.  Default 1\n    origin : None or array, optional\n       Origin at which to linearize mapping.  If None, origin is\n       ``np.zeros(ndimin)``\n    dtype : None or np.dtype, optional\n       dtype for return.  Default is None.  If ``dtype`` is None, and\n       ``step`` is an ndarray, use ``step.dtype``.  Otherwise use\n       np.float.\n\n    Returns\n    -------\n    C : array \n       Linearization of mapping in homogeneous coordinates, i.e.  an\n       array of size (ndimout+1, ndimin+1) where ndimout =\n       mapping(origin).shape[0].\n    \"\"\"\n    if dtype is None:\n        try:\n            dtype = step.dtype\n        except AttributeError:\n            dtype = np.float\n    step = np.array(step, dtype=dtype)\n    if origin is None:\n        origin = np.zeros(ndimin, dtype)\n    else:\n        if origin.dtype != dtype:\n            warnings.warn('origin.dtype != dtype in function linearize, using input dtype')\n        origin = np.asarray(origin, dtype=dtype)\n        if origin.shape != (ndimin,):\n            raise ValueError('origin.shape != (%d,)' % ndimin)\n    b = mapping(origin)\n\n    origin = np.multiply.outer(np.ones(ndimin, dtype), origin)\n    y1 = mapping(step*np.eye(ndimin, dtype=dtype) + origin)\n    y0 = mapping(origin)\n\n    ndimout = y1.shape[1]\n    C = np.zeros((ndimout+1, ndimin+1), (y0/step).dtype)\n    C[-1,-1] = 1\n    C[:ndimout,-1] = b\n    C[:ndimout,:ndimin] = (y1 - y0).T / step\n    return C\n\n\ndef drop_io_dim(cm, name):\n    ''' Drop dimension from coordinate map, if orthogonal to others\n\n    Drops both input and corresponding output dimension.  Thus there\n    should be a corresponding input dimension for a selected output\n    dimension, or a corresponding output dimension for an input\n    dimension. \n\n    Parameters\n    ----------\n    cm : Affine\n       Affine coordinate map instance\n    name : str\n       Name of input or output dimension to drop.  If this is an input\n       dimension, there must be a corresponding output dimension with\n       the same index, and vica versa.  The check for orthogonality\n       ensures that the input and output dimensions are only related to\n       each other, and not to the other dimensions.\n\n    Returns\n    -------\n    cm_redux : Affine\n       Affine coordinate map with orthogonal input + output dimension\n       dropped\n\n    Examples\n    --------\n    Typical use is in getting a 3D coordinate map from 4D\n\n    >>> cm4d = Affine.from_params('ijkl', 'xyzt', np.diag([1,2,3,4,1]))\n    >>> cm3d = drop_io_dim(cm4d, 't')\n    >>> cm3d.affine\n    array([[ 1.,  0.,  0.,  0.],\n           [ 0.,  2.,  0.,  0.],\n           [ 0.,  0.,  3.,  0.],\n           [ 0.,  0.,  0.,  1.]])\n    '''\n    aff = cm.affine\n    in_dims = list(cm.input_coords.coord_names)\n    nin = len(in_dims)\n    out_dims = list(cm.output_coords.coord_names)\n    nout = len(out_dims)\n    try:\n        i = in_dims.index(name)\n    except ValueError:\n        try:\n            i = out_dims.index(name)\n        except ValueError:\n            raise ValueError('No input or output dimension '\n                             'with name (%s)' % name)\n    col_inds = range(nin)\n    row_inds = range(nout)\n    try:\n        col_inds.remove(i)\n    except IndexError:\n        raise ValueError('Should be corresponding input and '\n                         'output dims')\n    try:\n        row_inds.remove(i)\n    except IndexError:\n        raise ValueError('Should be corresponding input and '\n                         'output dims')\n    removed_col = aff[row_inds, i]\n    if np.any(removed_col):\n        raise ValueError('Elements in dimension %d to remove (%s) '\n                         'appear not to be orthogonal '\n                         'to remaining dimensions' % (i, removed_col))\n    aff = aff[:, col_inds + [nin]]\n    aff = aff[row_inds + [nout],:]\n    in_dims = [n for i, n in enumerate(in_dims) if i in col_inds]\n    out_dims = [n for i, n in enumerate(out_dims) if i in row_inds]\n    return Affine.from_params(in_dims, out_dims, aff)\n\n\ndef append_io_dim(cm, in_name, out_name, start=0, step=1):\n    ''' Append input and output dimension to coordmap\n\n    Parameters\n    ----------\n    cm : Affine\n       Affine coordinate map instance to which to append dimension\n    in_name : str\n       Name for new input dimension\n    out_name : str\n       Name for new output dimension\n    start : float, optional\n       Offset for transformed values in new dimension\n    step : float, optional\n       Step, or scale factor for transformed values in new dimension\n\n    Returns\n    -------\n    cm_plus : Affine\n       New coordinate map with appended dimension\n\n    Examples\n    --------\n    Typical use is creating a 4D coordinate map from a 3D\n\n    >>> cm3d = Affine.from_params('ijk', 'xyz', np.diag([1,2,3,1]))\n    >>> cm4d = append_io_dim(cm3d, 'l', 't', 9, 5)\n    >>> cm4d.affine\n    array([[ 1.,  0.,  0.,  0.,  0.],\n           [ 0.,  2.,  0.,  0.,  0.],\n           [ 0.,  0.,  3.,  0.,  0.],\n           [ 0.,  0.,  0.,  5.,  9.],\n           [ 0.,  0.,  0.,  0.,  1.]])\n    '''\n    aff = cm.affine\n    in_dims = list(cm.input_coords.coord_names)\n    nin = len(in_dims)\n    out_dims = list(cm.output_coords.coord_names)\n    nout = len(out_dims)\n    in_dims.append(in_name)\n    out_dims.append(out_name)\n    aff_plus = np.zeros((nout+2, nin+2))\n    aff_plus[:nout,:nin] = aff[:nout, :nin]\n    aff_plus[:nout,-1] = aff[:nout,-1]\n    aff_plus[nout,nin] = step\n    aff_plus[-1,-1] = 1\n    aff_plus[nout,-1] = start\n    return Affine.from_params(in_dims, out_dims, aff_plus)\n\n    \n", "meta": {"hexsha": "a27272d664ba5b7dedba65a098bb3abf5e6011a6", "size": 28946, "ext": "py", "lang": "Python", "max_stars_repo_path": "nipy/core/reference/coordinate_map.py", "max_stars_repo_name": "yarikoptic/NiPy-OLD", "max_stars_repo_head_hexsha": "8759b598ac72d3b9df7414642c7a662ad9c55ece", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-08-22T16:14:45.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-22T16:14:45.000Z", "max_issues_repo_path": "nipy/core/reference/coordinate_map.py", "max_issues_repo_name": "yarikoptic/NiPy-OLD", "max_issues_repo_head_hexsha": "8759b598ac72d3b9df7414642c7a662ad9c55ece", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nipy/core/reference/coordinate_map.py", "max_forks_repo_name": "yarikoptic/NiPy-OLD", "max_forks_repo_head_hexsha": "8759b598ac72d3b9df7414642c7a662ad9c55ece", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5968468468, "max_line_length": 124, "alphanum_fraction": 0.578421889, "include": true, "reason": "import numpy", "num_tokens": 6957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.19119741205048796}}
{"text": "\"\"\"\nProcedures needed for Common support estimation.\n\nCreated on Thu Dec  8 15:48:57 2020.\n\n@author: MLechner\n\n# -*- coding: utf-8 -*-\n\"\"\"\nimport copy\nimport numpy as np\nimport pandas as pd\nfrom mcf import mcf_data_functions as mcf_data\nfrom mcf import general_purpose as gp\nfrom mcf import general_purpose_estimation as gp_est\n\n\ndef common_support(predict_file, tree_file, fill_y_file, fs_file, var_x_type,\n                   v_dict, c_dict, cs_list=None, prime_values_dict=None,\n                   pred_tr_np=None, d_tr_np=None):\n    \"\"\"\n    Remove observations from data files that are off-support.\n\n    Parameters\n    ----------\n    predict_file : String of csv-file. Data to predict the RF.\n    train_file : String of csv-file. Data to train the RF.\n    fill_y_file : String of csv-file. Data with y to be used by RF.\n    fs_file : String of csv-file. Data with y to be used by RF.\n    var_x_type : Dict. Features.\n    v_dict : Dict. Variables.\n    c_dict : Dict. Parameters.\n    cs_list: Tuple. Contains the information from estimated propensity score\n                    needed to predict for other data. Default is None.\n    prime_values_dict: Dict. List of unique values for variables to dummy.\n                    Default is None.\n    pred_t: Numpy array. Predicted treatment probabilities in training data.\n                         Needed to define cut-offs.\n    d_train: Numpy series. Observed treatment in training data (tree_file).\n\n    Returns\n    -------\n    predict_file_new : String of csv-file. Adjusted data.\n    cs_list: Tuple. Contains the information from estimated propensity score\n                    needed to predict for other data.\n    pred_t: Numpy array. Predicted treatment probabilities in training data.\n    d_train_tree: estimated tree by sklearn.\n\n    \"\"\"\n    def r2_obb(c_dict, idx, oob_best):\n        if c_dict['with_output']:\n            print('\\n')\n            print('-' * 80)\n            print('Treatment: {:2}'.format(c_dict['d_values'][idx]),\n                  'OOB Score (R2 in %): {:6.3f}'.format(oob_best * 100))\n            print('-' * 80)\n\n    def get_data(file_name, x_name):\n        data = pd.read_csv(file_name)\n        x_all = data[x_name]    # deep copies\n        obs = len(x_all.index)\n        return data, x_all, obs\n\n    def check_cols(x_1, x_2, name1, name2):\n        var1 = set(x_1.columns)\n        var2 = set(x_2.columns)\n        if var1 != var2:\n            if len(var1-var2) > 0:\n                print('Variables in ', name1, 'not contained in ', name2,\n                      *(var1-var2))\n            if len(var2-var1) > 0:\n                print('Variables in ', name2, 'not contained in ', name1,\n                      *(var2-var1))\n            raise Exception(name1 + ' data and ' + name2 + ' data contain' +\n                            ' differnt variables. Programm stopped.')\n\n    def mean_by_treatment(treat_pd, data_pd):\n        treat_pd = treat_pd.squeeze()\n        treat_vals = pd.unique(treat_pd)\n        print('--------------- Mean by treatment status ------------------')\n        if len(treat_vals) > 0:\n            mean = data_pd.groupby(treat_pd).mean()\n            print(mean.transpose())\n        else:\n            print('All obs have same treatment:', treat_vals)\n\n    def on_support_data_and_stats(obs_to_del_np, data_pd, x_data_pd, out_file,\n                                  upper_l, lower_l, c_dict, header=False,\n                                  d_name=None):\n        obs_to_keep = np.invert(obs_to_del_np)\n        data_keep = data_pd[obs_to_keep]\n        gp.delete_file_if_exists(out_file)\n        data_keep.to_csv(out_file, index=False)\n        if c_dict['with_output']:\n            x_keep = x_data_pd[obs_to_keep]\n            x_delete = x_data_pd[obs_to_del_np]\n            if header:\n                print('\\n')\n                print('=' * 80)\n                print('Common support check')\n                print('-' * 80)\n                print('Upper limits on treatment probabilities: ', upper_l)\n                print('Lower limits on treatment probabilities: ', lower_l)\n            print('-' * 80)\n            print('Data investigated and saved:', out_file)\n            print('-' * 80)\n            print('Observations deleted: {:4}'.format(np.sum(obs_to_del_np)),\n                  ' ({:6.3f}%)'.format(np.mean(obs_to_del_np)*100))\n            with pd.option_context(\n                    'display.max_rows', 500,\n                    'display.max_columns', 500,\n                    'display.expand_frame_repr', True,\n                    'display.width', 150,\n                    'chop_threshold', 1e-13):\n                all_var_names = [name.upper() for name in data_pd.columns]\n                if d_name[0].upper() in all_var_names:\n                    d_keep = data_keep[d_name]\n                    d_delete = data_pd[d_name]\n                    d_delete = d_delete[obs_to_del_np]\n                    d_keep_count = d_keep.value_counts(sort=False)\n                    d_delete_count = d_delete.value_counts(sort=False)\n                    d_keep_count = pd.concat(\n                        [d_keep_count,\n                         d_keep_count / np.sum(obs_to_keep) * 100], axis=1)\n                    d_delete_count = pd.concat(\n                        [d_delete_count,\n                         d_delete_count / np.sum(obs_to_del_np) * 100], axis=1)\n                    d_keep_count.columns = ['Obs.', 'Share in %']\n                    d_delete_count.columns = ['Obs.', 'Share in %']\n                    if c_dict['panel_data']:\n                        cluster_id = data_pd[v_dict['cluster_name']].squeeze()\n                        cluster_keep = cluster_id[obs_to_keep].squeeze()\n                        cluster_delete = cluster_id[obs_to_del_np].squeeze()\n                    print('-' * 80)\n                    print('Observations kept by treatment')\n                    print(d_keep_count)\n                    print('-   ' * 20)\n                    print('Observations deleted by treatment')\n                    print(d_delete_count)\n                    if c_dict['panel_data']:\n                        print('-   ' * 20)\n                        print('Total number of panel unit:',\n                              len(cluster_id.unique()))\n                        print('Observations belonging to ',\n                              len(cluster_keep.unique()),\n                              'panel units are ON support')\n                        print('Observations belonging to ',\n                              len(cluster_delete.unique()),\n                              'panel units are OFF support')\n                if d_name[0].upper() in all_var_names:\n                    print()\n                    print('Full sample (ON and OFF support observations)')\n                    mean_by_treatment(data_pd[d_name], x_data_pd)\n                print('-' * 80)\n                print('Data ON support')\n                print('-' * 80)\n                print(x_keep.describe().transpose())\n                if d_name[0].upper() in all_var_names:\n                    print()\n                    mean_by_treatment(d_keep, x_keep)\n                print('-' * 80)\n                print('Data OFF support')\n                print('-' * 80)\n                print(x_delete.describe().transpose())\n                if d_name[0].upper() in all_var_names:\n                    print()\n                    if np.sum(obs_to_del_np) > 1:\n                        mean_by_treatment(d_delete, x_delete)\n                    else:\n                        print('Only single observation deleted.')\n            if np.mean(obs_to_del_np) > c_dict['support_max_del_train']:\n                raise Exception(\n                    'Less than {:3}%'.format(\n                        100-c_dict['support_max_del_train']*100)\n                    + ' observations left after common support check of'\n                    + ' training data. Programme terminated. Improve'\n                    + ' balance of input data for forest building.')\n\n    x_name, x_type = gp.get_key_values_in_list(var_x_type)\n    names_unordered = []  # Split ordered variables into dummies\n    for j, val in enumerate(x_type):\n        if val > 0:\n            names_unordered.append(x_name[j])\n    fs_adjust = False\n    obs_fs = 0\n    if c_dict['train_mcf']:\n        data_tr, x_tr, obs_tr = get_data(tree_file, x_name)  # train,adj.\n        data_fy, x_fy, obs_fy = get_data(fill_y_file, x_name)  # adj.\n        if c_dict['fs_yes']:\n            # if not ((fs_file == tree_file) or (fs_file == fill_y_file)):\n            if fs_file not in (tree_file, fill_y_file):\n                data_fs, x_fs, obs_fs = get_data(fs_file, x_name)  # adj.\n                fs_adjust = True\n    if c_dict['pred_mcf']:\n        data_pr, x_pr, obs_pr = get_data(predict_file, x_name)\n    else:\n        obs_pr = 0\n    if names_unordered:  # List is not empty\n        if c_dict['train_mcf'] and c_dict['pred_mcf']:\n            x_total = pd.concat([x_tr, x_fy, x_pr], axis=0)\n            if fs_adjust:\n                x_total = pd.concat([x_total, x_fs], axis=0)\n            x_dummies = pd.get_dummies(x_total[names_unordered],\n                                       columns=names_unordered)\n            x_total = pd.concat([x_total, x_dummies], axis=1)\n            x_tr = x_total[:obs_tr]\n            x_fy = x_total[obs_tr:obs_tr+obs_fy]\n            x_pr = x_total[obs_tr+obs_fy:obs_tr+obs_fy+obs_pr]\n            if fs_adjust:\n                x_fs = x_total[obs_tr+obs_fy+obs_pr:]\n        elif c_dict['train_mcf'] and not c_dict['pred_mcf']:\n            x_total = pd.concat([x_tr, x_fy], axis=0)\n            if fs_adjust:\n                x_total = pd.concat([x_total, x_fs], axis=0)\n            x_dummies = pd.get_dummies(x_total[names_unordered],\n                                       columns=names_unordered)\n            x_total = pd.concat([x_total, x_dummies], axis=1)\n            x_tr = x_total[:obs_tr]\n            x_fy = x_total[obs_tr:obs_tr+obs_fy]\n            if fs_adjust:\n                x_fs = x_total[obs_tr+obs_fy:]\n        else:\n            x_add_tmp = check_if_obs_needed(names_unordered, x_pr,\n                                            prime_values_dict)\n            if x_add_tmp is not None:\n                x_total = pd.concat([x_pr, x_add_tmp], axis=0)\n            else:\n                x_total = x_pr\n            x_dummies = pd.get_dummies(x_total[names_unordered],\n                                       columns=names_unordered)\n            x_pr = pd.concat([x_total, x_dummies], axis=1)\n            if x_add_tmp is not None:  # remove add_temp\n                x_pr = x_pr[:obs_pr]\n    if c_dict['train_mcf']:\n        x_name_all = x_tr.columns.values.tolist()\n    else:\n        x_name_all = x_pr.columns.values.tolist()\n    if c_dict['train_mcf']:\n        x_tr_np = x_tr.to_numpy(copy=True)\n        d_all_in = pd.get_dummies(data_tr[v_dict['d_name']],\n                                  columns=v_dict['d_name'])\n        d_tr_np = d_all_in.to_numpy(copy=True)\n        pred_tr_np = np.empty((np.shape(x_tr_np)[0], c_dict['no_of_treat']))\n    if c_dict['train_mcf']:\n        x_pred_all = x_fy.copy()\n        if c_dict['pred_mcf']:\n            x_pred_all = pd.concat([x_pred_all, x_pr], axis=0)\n        if fs_adjust:\n            x_pred_all = pd.concat([x_pred_all, x_fs], axis=0)\n    else:\n        obs_fy = 0\n        x_pred_all = x_pr.copy()\n    x_pred_all_np = x_pred_all.to_numpy(copy=True)\n    pred_all_np = np.empty((obs_fy+obs_fs+obs_pr, c_dict['no_of_treat']))\n    if c_dict['no_parallel'] > 1:\n        workers_mp = copy.copy(c_dict['no_parallel'])\n    else:\n        workers_mp = None\n    if c_dict['train_mcf']:\n        check_cols(x_tr, x_fy, 'Tree', 'Fill_y')\n        if fs_adjust:\n            check_cols(x_tr, x_fs, 'Tree', 'Feature selection')\n    if c_dict['train_mcf'] and c_dict['pred_mcf']:\n        check_cols(x_tr, x_pr, 'Tree', 'Prediction')\n    if c_dict['train_mcf']:\n        if c_dict['with_output'] and c_dict['verbose']:\n            print('\\n')\n            print('-' * 80)\n            print('Computing random forest based common support')\n    if c_dict['train_mcf']:\n        cs_list = []\n        c_dict_new = mcf_data.m_n_grid(copy.deepcopy(c_dict),    # dict only\n                                       len(x_pred_all.columns))  # used here\n        for idx in range(c_dict['no_of_treat']):\n            return_forest = bool(c_dict['save_forest'])\n            ret_rf = gp_est.RandomForest_scikit(\n                x_tr_np, d_tr_np[:, idx], x_pred_all_np, boot=c_dict['boot'],\n                n_min=c_dict_new['grid_n_min'],\n                no_features=c_dict_new['grid_m'], workers=workers_mp,\n                pred_p_flag=True, pred_t_flag=True, pred_oob_flag=True,\n                with_output=False, variable_importance=True, x_name=x_name_all,\n                var_im_with_output=c_dict['with_output'],\n                return_forest_object=return_forest)\n            pred_all_np[:, idx] = np.copy(ret_rf[0])\n            pred_tr_np[:, idx] = np.copy(ret_rf[1])\n            oob_best = np.copy(ret_rf[2])\n            if c_dict['save_forest']:\n                cs_list.append(ret_rf[6])\n            r2_obb(c_dict, idx, oob_best)\n            if c_dict['no_of_treat'] == 2:\n                pred_all_np[:, idx+1] = 1 - pred_all_np[:, idx]\n                pred_tr_np[:, idx+1] = 1 - pred_tr_np[:, idx]\n                break\n    else:\n        for idx in range(c_dict['no_of_treat']):\n            pred_all_np[:, idx] = cs_list[idx].predict(x_pred_all_np)\n            if c_dict['no_of_treat'] == 2:\n                pred_all_np[:, idx+1] = 1 - pred_all_np[:, idx]\n                break\n    obs_to_del_all, obs_to_del_tr, upper_l, lower_l = indicate_off_support(\n        pred_tr_np, pred_all_np, d_tr_np, c_dict)\n    # split obs_to_del_all into its parts\n    obs_to_del_fs, obs_to_del_fy, obs_to_del_pr = False, False, False\n    predict_file_new = None\n    if c_dict['train_mcf']:\n        obs_to_del_fy = obs_to_del_all[:obs_fy]\n        if c_dict['pred_mcf']:\n            obs_to_del_pr = obs_to_del_all[obs_fy:obs_fy+obs_pr]\n        if fs_adjust:\n            obs_to_del_fs = obs_to_del_all[obs_fy+obs_pr:]\n    else:\n        obs_to_del_pr = obs_to_del_all\n    if c_dict['train_mcf']:\n        if np.any(obs_to_del_tr):\n            on_support_data_and_stats(obs_to_del_tr, data_tr, x_tr, tree_file,\n                                      upper_l, lower_l, c_dict, header=True,\n                                      d_name=v_dict['d_name'])\n        if np.any(obs_to_del_fs):\n            on_support_data_and_stats(obs_to_del_fs, data_fs, x_fs, fs_file,\n                                      upper_l, lower_l, c_dict,\n                                      d_name=v_dict['d_name'])\n        if np.any(obs_to_del_fy):\n            on_support_data_and_stats(obs_to_del_fy, data_fy, x_fy,\n                                      fill_y_file, upper_l, lower_l, c_dict,\n                                      d_name=v_dict['d_name'])\n    if c_dict['pred_mcf']:\n        if np.any(obs_to_del_pr):\n            on_support_data_and_stats(\n                obs_to_del_pr, data_pr, x_pr, c_dict['preddata3_temp'],\n                upper_l, lower_l, c_dict, d_name=v_dict['d_name'])\n            predict_file_new = c_dict['preddata3_temp']\n        else:\n            predict_file_new = predict_file\n    else:\n        predict_file_new = None\n    return predict_file_new, cs_list, pred_tr_np, d_tr_np\n\n\ndef check_if_obs_needed(names_unordered, x_all_p, prime_values_dict):\n    \"\"\"Generate new rows -> all values of unordered variables are in data.\"\"\"\n    no_change = True\n    max_length = 1\n    for name in names_unordered:\n        length = len(prime_values_dict[name])\n        if length > max_length:\n            max_length = length\n    x_add_tmp = x_all_p[:max_length].copy()\n    for name in names_unordered:\n        unique_vals_p = np.sort(x_all_p[name].unique())\n        unique_vals_t = np.sort(prime_values_dict[name])\n        if len(unique_vals_p) > len(unique_vals_t) or (\n               (len(unique_vals_p) == len(unique_vals_t))\n               and not np.all(unique_vals_p == unique_vals_t)):\n            print(name, 'Training values: ', unique_vals_t,\n                  'Prediction values:', unique_vals_p)\n            raise Exception('Common support variable value error')\n        add_vals_in_train = np.setdiff1d(unique_vals_t, unique_vals_p)\n        if add_vals_in_train.size > 0:\n            for i, val in enumerate(add_vals_in_train):\n                x_add_tmp[i, name] = val\n            no_change = False\n    if no_change:\n        return None\n    return x_add_tmp\n\n\ndef indicate_off_support(pred_t, pred_p, d_t, c_dict):\n    \"\"\"\n    Indicate which observations are off support.\n\n    Parameters\n    ----------\n    pred_t : N x no of treat Numpy array. Predictions of treat probs in train.\n    pred_p : N x no of treat Numpy array. Predictions of treat probs in pred.\n    d_t: N x no of treat Numpy array. Treatment dummies.\n    c_dict : Dict. Parameters.\n\n    Returns\n    -------\n    off_support_p : N x 1 Numpy array of boolean. True if obs is off support.\n    off_support_t : N x 1 Numpy array of boolean. True if obs is off support.\n    upper : No of treatment x 1 Numpy array of float. Upper limits.\n    lower : No of treatment x 1 Numpy array of float. Lower limits.\n\n    \"\"\"\n    # Normalize such that probabilities add up to 1\n    pred_t = pred_t / pred_t.sum(axis=1, keepdims=True)\n    pred_p = pred_p / pred_p.sum(axis=1, keepdims=True)\n    n_p = np.shape(pred_p)[0]\n    n_t = np.shape(pred_t)[0]\n    q_s = c_dict['support_quantil']\n    if c_dict['common_support'] == 1:\n        upper_limit = np.empty((c_dict['no_of_treat'], c_dict['no_of_treat']))\n        lower_limit = np.empty_like(upper_limit)\n        for idx in range(c_dict['no_of_treat']):\n            if q_s == 1:\n                upper_limit[idx, :] = np.max(pred_t[d_t[:, idx] == 1], axis=0)\n                lower_limit[idx, :] = np.min(pred_t[d_t[:, idx] == 1], axis=0)\n            else:\n                upper_limit[idx, :] = np.quantile(pred_t[d_t[:, idx] == 1],\n                                                  q_s, axis=0)\n                lower_limit[idx, :] = np.quantile(pred_t[d_t[:, idx] == 1],\n                                                  1-q_s, axis=0)\n        if c_dict['with_output']:\n            print('Treatment sample     Treatment probabilities in %')\n            print('--------------------- Upper limits ----------------')\n            for idx, ival in enumerate(c_dict['d_values']):\n                print('D = {:2}'.format(ival), end='              ')\n                for jdx in range(c_dict['no_of_treat']):\n                    print('{:7.4f} '.format(upper_limit[idx, jdx]), end=' ')\n                print(' ')\n            print('--------------------- Lower limits ----------------')\n            for idx, ival in enumerate(c_dict['d_values']):\n                print('D = {:2}'.format(ival), end='              ')\n                for jdx in range(c_dict['no_of_treat']):\n                    print('{:7.4f} '.format(lower_limit[idx, jdx]), end=' ')\n                print(' ')\n        upper = np.min(upper_limit, axis=0)\n        lower = np.max(lower_limit, axis=0)\n    else:\n        # Normalize such that probabilities add up to 1\n        upper = np.ones(\n            c_dict['no_of_treat']) * (1 - c_dict['support_min_p'])\n        lower = np.ones(c_dict['no_of_treat']) * c_dict['support_min_p']\n    off_support_p = np.empty(n_p, dtype=bool)\n    off_support_t = np.empty(n_t, dtype=bool)\n    off_upper = np.empty(c_dict['no_of_treat'], dtype=bool)\n    off_lower = np.empty_like(off_upper)\n    for i in range(n_p):\n        off_upper = np.any(pred_p[i, :] > upper)\n        off_lower = np.any(pred_p[i, :] < lower)\n        off_support_p[i] = off_upper or off_lower\n    for i in range(n_t):\n        off_upper = np.any(pred_t[i, :] > upper)\n        off_lower = np.any(pred_t[i, :] < lower)\n        off_support_t[i] = off_upper or off_lower\n    return off_support_p, off_support_t, upper, lower\n", "meta": {"hexsha": "4efdf6cdcc649b6f98c8d2592a526ff01e70b56a", "size": 19989, "ext": "py", "lang": "Python", "max_stars_repo_path": "mcf/mcf_cs_functions.py", "max_stars_repo_name": "MCFpy/mcf", "max_stars_repo_head_hexsha": "dac9056ed63620e3225903582d50e89af87b6896", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-06-19T08:27:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T17:51:39.000Z", "max_issues_repo_path": "mcf/mcf_cs_functions.py", "max_issues_repo_name": "MCFpy/mcf", "max_issues_repo_head_hexsha": "dac9056ed63620e3225903582d50e89af87b6896", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-21T11:40:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-13T11:14:12.000Z", "max_forks_repo_path": "mcf/mcf_cs_functions.py", "max_forks_repo_name": "MCFpy/mcf", "max_forks_repo_head_hexsha": "dac9056ed63620e3225903582d50e89af87b6896", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-05T08:08:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T15:39:09.000Z", "avg_line_length": 45.6369863014, "max_line_length": 79, "alphanum_fraction": 0.5519535745, "include": true, "reason": "import numpy", "num_tokens": 4760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.19119740835925148}}
{"text": "import os\nimport time\nfrom datetime import datetime\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom ops import *\n\n\"\"\"\ncppgan-vae\n\ncompositional pattern-producing generative adversarial network combined with variational autoencoder\n\nUPDATE: modified to get rid of likelihood function, and use pure GAN to draw to correct class.\n\nI learned a lot from studying the below pages:\n\nhttps://github.com/carpedm20/DCGAN-tensorflow\nhttps://jmetzen.github.io/2015-11-27/vae.html\n\nit wouldn't have been possible without referencing those two guy's code!\n\nDescription of CPPNs:\n\nhttps://en.wikipedia.org/wiki/Compositional_pattern-producing_network\n\n\"\"\"\n\n\nclass CPPNResnet:\n    def __init__(\n        self,\n        batch_size=1,\n        z_dim=32,\n        x_dim=26,\n        y_dim=26,\n        c_dim=1,\n        scale=8.0,\n        learning_rate_g=0.01,\n        learning_rate_d=0.001,\n        learning_rate_vae=0.0001,\n        beta1=0.9,\n        net_size_g=6,\n        net_depth_g=24,\n        subnet_depth_g=4,\n        net_size_q=512,\n        keep_prob=1.0,\n        df_dim=32,\n        model_name=\"cppn_resnet\",\n        grad_clip=5.0,\n        logdir=\"save\",\n    ):\n        \"\"\"\n\n        Args:\n        z_dim               dimensionality of the latent vector\n        x_dim, y_dim        default resolution of generated images for training\n        c_dim               1 for monotone, 3 for colour\n        learning_rate_g     learning rate for the generator\n                     _d    learning rate for the discriminiator\n                     _vae  learning rate for the variational autoencoder\n        net_size_g          number of activations per layer for cppn generator function\n        net_depth_g         depth of generator\n        net_size_q          number of activations per layer for decoder (real image -> z). 2 layers.\n        df_dim              discriminiator is a convnet.  higher -> more activtions -> smarter.\n        keep_prob           dropout probability\n\n        when training, use I used dropout on training the decoder, batch norm on discriminator, nothing on cppn\n        choose training parameters so that over the long run, decoder and encoder log errors hover around 0.7 each (so they are at the same skill level)\n        while the error for vae should slowly move lower over time with D and G balanced.\n\n        \"\"\"\n\n        self.batch_size = batch_size\n        self.learning_rate_g = learning_rate_g\n        self.learning_rate_d = learning_rate_d\n        self.learning_rate_vae = learning_rate_vae\n        self.beta1 = beta1\n        self.net_size_g = net_size_g\n        self.net_size_q = net_size_q\n        self.x_dim = x_dim\n        self.y_dim = y_dim\n        self.scale = scale\n        self.c_dim = c_dim\n        self.z_dim = z_dim\n        self.net_depth_g = net_depth_g\n        self.subnet_depth_g = subnet_depth_g\n        self.model_name = model_name\n        self.keep_prob = keep_prob\n        self.df_dim = df_dim\n        self.num_class = 11  # 0->9 are MNIST classes, 10 are fake digits.\n        self.grad_clip = grad_clip\n        self.logdir = logdir\n\n        # tf Graph batch of image (batch_size, height, width, depth)\n        self.batch = tf.placeholder(tf.float32, [batch_size, x_dim, y_dim, c_dim])\n        self.batch_flatten = tf.reshape(self.batch, [batch_size, -1])\n        self.batch_label = tf.placeholder(\n            tf.float32, [batch_size, self.num_class]\n        )  # mnist labels for the batch (one-hot)\n        self.fake_label = np.array(\n            self.batch_size * [10], dtype=np.int32\n        )  # label of fake batches\n        self.fake_label_one_hot = self.to_one_hot(self.fake_label)\n\n        n_points = x_dim * y_dim\n        self.n_points = n_points\n\n        self.x_vec, self.y_vec, self.r_vec = self.coordinates(x_dim, y_dim, scale)\n\n        # latent vector\n        # self.z = tf.placeholder(tf.float32, [self.batch_size, self.z_dim])\n        # inputs to cppn, like coordinates and radius from centre\n        self.x = tf.placeholder(tf.float32, [self.batch_size, None, 1])\n        self.y = tf.placeholder(tf.float32, [self.batch_size, None, 1])\n        self.r = tf.placeholder(tf.float32, [self.batch_size, None, 1])\n\n        # batch normalization : deals with poor initialization helps gradient flow\n        self.d_bn1 = batch_norm(batch_size, name=self.model_name + \"_d_bn1\")\n        self.d_bn2 = batch_norm(batch_size, name=self.model_name + \"_d_bn2\")\n\n        # Use recognition network to determine mean and\n        # (log) variance of Gaussian distribution in latent\n        # space\n        self.z_mean, self.z_log_sigma_sq = self.encoder()\n\n        # Draw one sample z from Gaussian distribution\n        eps = tf.random_normal((self.batch_size, self.z_dim), 0, 1, dtype=tf.float32)\n        # z = mu + sigma*epsilon\n        self.z = tf.add(\n            self.z_mean, tf.multiply(tf.sqrt(tf.exp(self.z_log_sigma_sq)), eps)\n        )\n\n        # Use generator to determine mean of\n        # Bernoulli distribution of reconstructed input\n        self.G = self.generator()\n        # self.batch_reconstruct_flatten = tf.reshape(self.G, [batch_size, -1]) # not needed\n\n        self.predict_real_samples = self.discriminator(\n            self.batch\n        )  # discriminiator on correct examples\n        self.predict_fake_samples = self.discriminator(\n            self.G, reuse=True\n        )  # feed generated images into D\n\n        self.create_vae_loss_terms()\n        self.create_gan_loss_terms()\n\n        self.balanced_loss = (\n            1.0 * self.g_loss + 10.0 * self.vae_loss\n        )  # can try to weight these.\n\n        self.t_vars = tf.trainable_variables()\n\n        self.q_vars = [\n            var for var in self.t_vars if (self.model_name + \"_q_\") in var.name\n        ]\n        self.g_vars = [\n            var for var in self.t_vars if (self.model_name + \"_g_\") in var.name\n        ]\n        self.d_vars = [\n            var for var in self.t_vars if (self.model_name + \"_d_\") in var.name\n        ]\n        self.both_vars = self.q_vars + self.g_vars\n        # self.vae_vars = self.q_vars # in this version, g_vars don't concern vae_loss\n\n        # clip gradients\n        d_opt_real_grads, _ = tf.clip_by_global_norm(\n            tf.gradients(self.d_loss_real, self.d_vars), self.grad_clip\n        )\n        d_opt_grads, _ = tf.clip_by_global_norm(\n            tf.gradients(self.d_loss, self.d_vars), self.grad_clip\n        )\n        g_opt_grads, _ = tf.clip_by_global_norm(\n            tf.gradients(self.balanced_loss, self.both_vars), self.grad_clip\n        )\n        vae_opt_grads, _ = tf.clip_by_global_norm(\n            tf.gradients(self.vae_loss, self.q_vars), self.grad_clip\n        )\n\n        # Use ADAM optimizer\n        with tf.variable_scope(self.model_name + \"_opt\", reuse=tf.AUTO_REUSE) as scope:\n            d_real_optimizer = tf.train.AdamOptimizer(\n                self.learning_rate_d, beta1=self.beta1\n            )\n            d_optimizer = tf.train.AdamOptimizer(self.learning_rate_d, beta1=self.beta1)\n            g_optimizer = tf.train.AdamOptimizer(self.learning_rate_g, beta1=self.beta1)\n            vae_optimizer = tf.train.AdamOptimizer(\n                self.learning_rate_vae, beta1=self.beta1\n            )\n\n            self.d_opt_real = d_real_optimizer.apply_gradients(\n                zip(d_opt_real_grads, self.d_vars)\n            )\n            self.d_opt = d_optimizer.apply_gradients(zip(d_opt_grads, self.d_vars))\n            self.g_opt = g_optimizer.apply_gradients(zip(g_opt_grads, self.both_vars))\n            self.vae_opt = vae_optimizer.apply_gradients(\n                zip(vae_opt_grads, self.q_vars)\n            )\n\n        \"\"\"\n    self.d_opt_real = tf.train.AdamOptimizer(self.learning_rate_d, beta1=self.beta1) \\\n                      .minimize(self.d_loss_real, var_list=self.d_vars)\n    self.d_opt = tf.train.AdamOptimizer(self.learning_rate_d, beta1=self.beta1) \\\n                      .minimize(self.d_loss, var_list=self.d_vars)\n    self.g_opt = tf.train.AdamOptimizer(self.learning_rate_g, beta1=self.beta1) \\\n                      .minimize(self.g_loss, var_list=self.both_vars)\n    self.vae_opt = tf.train.AdamOptimizer(self.learning_rate_vae, beta1=self.beta1) \\\n                      .minimize(self.vae_loss, var_list=self.q_vars)\n    \"\"\"\n\n        \"\"\"\n    tvars = tf.trainable_variables()\n    grads, _ = tf.clip_by_global_norm(tf.gradients(self.cost, tvars), args.grad_clip)\n    optimizer = tf.train.AdamOptimizer(self.lr, epsilon=0.001)\n    self.train_op = optimizer.apply_gradients(zip(grads, tvars))\n    \"\"\"\n\n        self.init()\n        # self.saver = tf.train.Saver(tf.all_variables())\n\n    def init(self):\n        # Launch the session\n        self.sess = tf.InteractiveSession()\n\n        # init all vars\n        self.all_vars = tf.get_collection_ref(tf.GraphKeys.GLOBAL_VARIABLES)\n        self.sess.run(tf.variables_initializer(self.all_vars))\n\n        # filter to trainable vars, and include only those in the Saver\n        self.trainable_vars = [\n            v\n            for v in self.all_vars\n            if \"beta1_power\" not in v.name and \"beta2_power\" not in v.name\n        ]\n        self.saver = tf.train.Saver(var_list=self.trainable_vars, max_to_keep=50)\n\n        # initialize writer for tensorboard logs\n        self.writer = tf.summary.FileWriter(self.logdir)\n\n    def reinit(self):\n        self.all_vars = tf.get_collection_ref(tf.GraphKeys.GLOBAL_VARIABLES)\n        self.sess.run(tf.variables_initializer(self.all_vars))\n\n    def to_one_hot(self, label):\n        # convert labels, a numpy list of labels (of size batch_size) to the one hot equivalent\n        return np.eye(self.num_class)[label]\n\n    def create_vae_loss_terms(self):\n        # The loss is composed of two terms:\n        # 1.) The reconstruction loss (the negative log probability\n        #     of the input under the reconstructed Bernoulli distribution\n        #     induced by the decoder in the data space).\n        #     This can be interpreted as the number of \"nats\" required\n        #     for reconstructing the input when the activation in latent\n        #     is given.\n        # Adding 1e-10 to avoid evaluatio of log(0.0)\n\n        # stop using likelihood function for similarity\n        # reconstr_loss = \\\n        #     -tf.reduce_sum(self.batch_flatten * tf.log(1e-10 + self.batch_reconstruct_flatten)\n        #                    + (1-self.batch_flatten) * tf.log(1e-10 + 1 - self.batch_reconstruct_flatten), 1)\n\n        # 2.) The latent loss, which is defined as the Kullback Leibler divergence\n        ##    between the distribution in latent space induced by the encoder on\n        #     the data and some prior. This acts as a kind of regularizer.\n        #     This can be interpreted as the number of \"nats\" required\n        #     for transmitting the the latent space distribution given\n        #     the prior.\n\n        latent_loss = -0.5 * tf.reduce_sum(\n            1\n            + self.z_log_sigma_sq\n            - tf.square(self.z_mean)\n            - tf.exp(self.z_log_sigma_sq),\n            1,\n        )\n\n        # self.vae_loss = tf.reduce_mean(reconstr_loss + latent_loss) / self.n_points # average over batch and pixel\n\n        # vae loss is now purely kl divergence loss term.  let GAN take care of mnist class accuracy.\n        self.vae_loss = (\n            tf.reduce_mean(latent_loss) / self.n_points\n        )  # average over batch and pixel\n        self.summ_vae_loss = tf.summary.scalar(\"vae_loss\", self.vae_loss)\n\n    def create_gan_loss_terms(self):\n        # Define loss function and optimiser\n        \"\"\"replace below with class-based disriminiator\n        self.d_loss_real = binary_cross_entropy_with_logits(tf.ones_like(self.D_right), self.D_right)\n        self.d_loss_fake = binary_cross_entropy_with_logits(tf.zeros_like(self.D_wrong), self.D_wrong)\n        self.d_loss = 1.0*(self.d_loss_real + self.d_loss_fake)/ 2.0\n        self.g_loss = 1.0*binary_cross_entropy_with_logits(tf.ones_like(self.D_wrong), self.D_wrong)\n        \"\"\"\n\n        # cross entropy loss of predicting real mnist to real classes\n        self.d_loss_real = tf.reduce_mean(\n            -tf.reduce_sum(\n                self.batch_label * tf.log(self.predict_real_samples),\n                reduction_indices=[1],\n            )\n        )\n        # accuracy of using discriminiator as a normal mnist classifier\n        self.d_loss_real_accuracy = tf.reduce_mean(\n            tf.cast(\n                tf.equal(\n                    tf.argmax(self.predict_real_samples, 1),\n                    tf.argmax(self.batch_label, 1),\n                ),\n                tf.float32,\n            )\n        )\n        # cross entropy loss of predicting that fake generated mnist are in fact fake\n        self.d_loss_fake = tf.reduce_mean(\n            -tf.reduce_sum(\n                self.fake_label_one_hot * tf.log(self.predict_fake_samples),\n                reduction_indices=[1],\n            )\n        )\n        # accuracy of discriminator predicting a fake mnist digit\n        self.d_loss_fake_accuracy = tf.reduce_mean(\n            tf.cast(\n                tf.equal(\n                    tf.argmax(self.predict_fake_samples, 1),\n                    tf.argmax(self.fake_label_one_hot, 1),\n                ),\n                tf.float32,\n            )\n        )\n        # take the average of two d_loss to be the defacto d_loss\n        self.d_loss = (\n            10.0 * self.d_loss_real + self.d_loss_fake\n        ) / 11.0  # balance out the classes\n        self.summ_d_loss = tf.summary.scalar(\"d_loss\", self.d_loss)\n        self.summ_d_loss_fake = tf.summary.scalar(\"d_loss_fake\", self.d_loss_fake)\n        self.summ_d_loss_real = tf.summary.scalar(\"d_loss_real\", self.d_loss_real)\n        self.summ_d_loss_fake_accuracy = tf.summary.scalar(\n            \"d_loss_fake_accuracy\", self.d_loss_fake_accuracy\n        )\n        self.summ_d_loss_real_accuracy = tf.summary.scalar(\n            \"d_loss_real_accuracy\", self.d_loss_real_accuracy\n        )\n\n        # cross entropy of generator fooling discriminiator that its shit is real.\n        self.g_loss = tf.reduce_mean(\n            -tf.reduce_sum(\n                self.batch_label * tf.log(self.predict_fake_samples),\n                reduction_indices=[1],\n            )\n        )\n        # accuracy of generated samples being fooled to be classified as their supposed ground truth labels\n        self.g_loss_accuracy = tf.reduce_mean(\n            tf.cast(\n                tf.equal(\n                    tf.argmax(self.predict_fake_samples, 1),\n                    tf.argmax(self.batch_label, 1),\n                ),\n                tf.float32,\n            )\n        )\n        self.summ_g_loss = tf.summary.scalar(\"g_loss\", self.g_loss)\n        self.summ_g_loss_accuracy = tf.summary.scalar(\n            \"g_loss_accuracy\", self.g_loss_accuracy\n        )\n\n    def coordinates(self, x_dim=32, y_dim=32, scale=1.0):\n        n_pixel = x_dim * y_dim\n        x_range = scale * (np.arange(x_dim) - (x_dim - 1) / 2.0) / (x_dim - 1) / 0.5\n        y_range = scale * (np.arange(y_dim) - (y_dim - 1) / 2.0) / (y_dim - 1) / 0.5\n        x_mat = np.matmul(np.ones((y_dim, 1)), x_range.reshape((1, x_dim)))\n        y_mat = np.matmul(y_range.reshape((y_dim, 1)), np.ones((1, x_dim)))\n        r_mat = np.sqrt(x_mat * x_mat + y_mat * y_mat)\n        x_mat = np.tile(x_mat.flatten(), self.batch_size).reshape(\n            self.batch_size, n_pixel, 1\n        )\n        y_mat = np.tile(y_mat.flatten(), self.batch_size).reshape(\n            self.batch_size, n_pixel, 1\n        )\n        r_mat = np.tile(r_mat.flatten(), self.batch_size).reshape(\n            self.batch_size, n_pixel, 1\n        )\n        return x_mat, y_mat, r_mat\n\n    def show_image(self, image):\n        \"\"\"\n        image is in [height width depth]\n        \"\"\"\n        plt.subplot(1, 1, 1)\n        y_dim = image.shape[0]\n        x_dim = image.shape[1]\n        if self.c_dim > 1:\n            plt.imshow(image, interpolation=\"nearest\")\n        else:\n            plt.imshow(\n                image.reshape(y_dim, x_dim), cmap=\"Greys\", interpolation=\"nearest\"\n            )\n        plt.axis(\"off\")\n        plt.show()\n\n    def encoder(self):\n        # Generate probabilistic encoder (recognition network), which\n        # maps inputs onto a normal distribution in latent space.\n        # The transformation is parametrized and can be learned.\n        H1 = tf.nn.dropout(\n            tf.nn.softplus(\n                linear(self.batch_flatten, self.net_size_q, self.model_name + \"_q_lin1\")\n            ),\n            self.keep_prob,\n        )\n        H2 = tf.nn.dropout(\n            tf.nn.softplus(linear(H1, self.net_size_q, self.model_name + \"_q_lin2\")),\n            self.keep_prob,\n        )\n        z_mean = linear(H2, self.z_dim, self.model_name + \"_q_lin3_mean\")\n        z_log_sigma_sq = linear(\n            H2, self.z_dim, self.model_name + \"_q_lin3_log_sigma_sq\"\n        )\n        return (z_mean, z_log_sigma_sq)\n\n    def discriminator(self, image, reuse=False):\n\n        if reuse:\n            tf.get_variable_scope().reuse_variables()\n\n        h0 = lrelu(conv2d(image, self.df_dim, name=self.model_name + \"_d_h0_conv\"))\n        h1 = lrelu(\n            self.d_bn1(conv2d(h0, self.df_dim * 2, name=self.model_name + \"_d_h1_conv\"))\n        )\n        h2 = lrelu(\n            self.d_bn2(conv2d(h1, self.df_dim * 4, name=self.model_name + \"_d_h2_conv\"))\n        )\n        h3 = linear(\n            tf.reshape(h2, [self.batch_size, -1]),\n            self.num_class,\n            self.model_name + \"_d_h2_lin\",\n        )\n\n        return tf.nn.softmax(h3)\n\n    def generator(self, gen_x_dim=26, gen_y_dim=26, reuse=False):\n\n        if reuse:\n            tf.get_variable_scope().reuse_variables()\n\n        n_network = self.net_size_g\n        gen_n_points = gen_x_dim * gen_y_dim\n\n        z_scaled = (\n            tf.reshape(self.z, [self.batch_size, 1, self.z_dim])\n            * tf.ones([gen_n_points, 1], dtype=tf.float32)\n            * self.scale\n        )\n        z_unroll = tf.reshape(z_scaled, [self.batch_size * gen_n_points, self.z_dim])\n        x_unroll = tf.reshape(self.x, [self.batch_size * gen_n_points, 1])\n        y_unroll = tf.reshape(self.y, [self.batch_size * gen_n_points, 1])\n        r_unroll = tf.reshape(self.r, [self.batch_size * gen_n_points, 1])\n\n        U = (\n            fully_connected(z_unroll, n_network, self.model_name + \"_g_0_z\")\n            + fully_connected(\n                x_unroll, n_network, self.model_name + \"_g_0_x\", with_bias=False\n            )\n            + fully_connected(\n                y_unroll, n_network, self.model_name + \"_g_0_y\", with_bias=False\n            )\n            + fully_connected(\n                r_unroll, n_network, self.model_name + \"_g_0_r\", with_bias=False\n            )\n        )\n\n        # H = tf.nn.relu(U)\n        H = tf.nn.tanh(U)\n\n        for i in range(0, self.net_depth_g):\n            H0 = H\n            for j in range(0, self.subnet_depth_g):\n                H0 = tf.nn.relu(\n                    fully_connected(\n                        H0,\n                        n_network,\n                        self.model_name + \"_g_relu_skip_\" + str(i) + \"_\" + str(j),\n                        stddev=1.0,\n                    )\n                )\n            H0 = tf.nn.tanh(\n                fully_connected(\n                    H0,\n                    n_network,\n                    self.model_name + \"_g_tanh_skip_\" + str(i),\n                    stddev=0.001,\n                )\n            )\n            H = H + H0\n\n        output = tf.sigmoid(\n            fully_connected(\n                H, self.c_dim, self.model_name + \"_g_\" + str(self.net_depth_g)\n            )\n        )\n\n        result = tf.reshape(output, [self.batch_size, gen_y_dim, gen_x_dim, self.c_dim])\n\n        return result\n\n    def partial_train(self, batch, label):\n        \"\"\"Train model based on mini-batch of input data.\n\n        Return cost of mini-batch.\n\n        I should really seperate the below tricks into parameters, like number of times/pass\n        and also the regulator threshold levels.\n        \"\"\"\n\n        counter = 0\n\n        label_one_hot = self.to_one_hot(label)\n\n        \"\"\"\n    for i in range(1):\n      counter += 1\n      _, vae_loss = self.sess.run((self.vae_opt, self.vae_loss),\n                              feed_dict={self.batch: batch, self.x: self.x_vec, self.y: self.y_vec, self.r: self.r_vec, self.batch_label: label_one_hot})\n    \"\"\"\n\n        for i in range(16):\n            counter += 1\n            _, g_loss, vae_loss, g_accuracy = self.sess.run(\n                (self.g_opt, self.g_loss, self.vae_loss, self.g_loss_accuracy),\n                feed_dict={\n                    self.batch: batch,\n                    self.x: self.x_vec,\n                    self.y: self.y_vec,\n                    self.r: self.r_vec,\n                    self.batch_label: label_one_hot,\n                },\n            )\n            if g_accuracy > 0.98:\n                break\n\n        # train classifier on only real mnist digits\n        # _ = self.sess.run((self.d_opt_real), feed_dict={self.batch: batch, self.x: self.x_vec, self.y: self.y_vec, self.r: self.r_vec, self.batch_label: label_one_hot})\n\n        # calculate accuracy before deciding whether to train discriminator\n        (\n            d_loss,\n            d_loss_real,\n            d_loss_fake,\n            d_real_accuracy,\n            d_fake_accuracy,\n        ) = self.sess.run(\n            (\n                self.d_loss,\n                self.d_loss_real,\n                self.d_loss_fake,\n                self.d_loss_real_accuracy,\n                self.d_loss_fake_accuracy,\n            ),\n            feed_dict={\n                self.batch: batch,\n                self.x: self.x_vec,\n                self.y: self.y_vec,\n                self.r: self.r_vec,\n                self.batch_label: label_one_hot,\n            },\n        )\n\n        if (\n            d_fake_accuracy < 0.7 and g_accuracy > 0.6\n        ):  # only train discriminiator if generator is good and d is behind.\n            for i in range(8):\n                counter += 1\n                (\n                    _,\n                    d_loss,\n                    d_loss_real,\n                    d_loss_fake,\n                    d_real_accuracy,\n                    d_fake_accuracy,\n                ) = self.sess.run(\n                    (\n                        self.d_opt,\n                        self.d_loss,\n                        self.d_loss_real,\n                        self.d_loss_fake,\n                        self.d_loss_real_accuracy,\n                        self.d_loss_fake_accuracy,\n                    ),\n                    feed_dict={\n                        self.batch: batch,\n                        self.x: self.x_vec,\n                        self.y: self.y_vec,\n                        self.r: self.r_vec,\n                        self.batch_label: label_one_hot,\n                    },\n                )\n                if d_fake_accuracy > 0.75:\n                    break\n        elif d_real_accuracy < 0.6:\n            for i in range(8):\n                counter += 1\n                _, d_real_accuracy = self.sess.run(\n                    (self.d_opt_real, self.d_loss_real_accuracy),\n                    feed_dict={\n                        self.batch: batch,\n                        self.x: self.x_vec,\n                        self.y: self.y_vec,\n                        self.r: self.r_vec,\n                        self.batch_label: label_one_hot,\n                    },\n                )\n                if d_real_accuracy > 0.7:\n                    break\n\n        return (\n            d_loss,\n            g_loss,\n            vae_loss,\n            counter,\n            d_real_accuracy,\n            d_fake_accuracy,\n            g_accuracy,\n            d_loss_real,\n            d_loss_fake,\n        )\n\n    def encode(self, X):\n        \"\"\"Transform data by mapping it into the latent space.\"\"\"\n        # Note: This maps to mean of distribution, we could alternatively\n        # sample from Gaussian distribution\n        return self.sess.run(self.z_mean, feed_dict={self.batch: X})\n\n    def generate(self, z=None, x_dim=26, y_dim=26, scale=5.0):\n        \"\"\"Generate data by sampling from latent space.\n\n        If z is not None, data for this point in latent space is\n        generated. Otherwise, z is drawn from prior in latent\n        space.\n        \"\"\"\n        if z is None:\n            z = np.random.normal(size=self.z_dim).astype(np.float32)\n        # Note: This maps to mean of distribution, we could alternatively\n        # sample from Gaussian distribution\n\n        z = np.reshape(z, (self.batch_size, self.z_dim))\n\n        G = self.generator(gen_x_dim=x_dim, gen_y_dim=y_dim, reuse=True)\n        gen_x_vec, gen_y_vec, gen_r_vec = self.coordinates(x_dim, y_dim, scale=scale)\n        image = self.sess.run(\n            G,\n            feed_dict={\n                self.z: z,\n                self.x: gen_x_vec,\n                self.y: gen_y_vec,\n                self.r: gen_r_vec,\n            },\n        )\n        return image\n\n    def save_model(self, checkpoint_path, epoch):\n        \"\"\" saves the model to a file \"\"\"\n        self.saver.save(self.sess, checkpoint_path, global_step=epoch)\n\n    def load_model(self, checkpoint_path):\n\n        ckpt = tf.train.get_checkpoint_state(checkpoint_path)\n        print(\"loading model: \", ckpt.model_checkpoint_path)\n\n        # self.saver.restore(self.sess, checkpoint_path+'/'+ckpt.model_checkpoint_path)\n        # use the below line for tensorflow 0.7\n        self.saver.restore(self.sess, ckpt.model_checkpoint_path)\n\n    def close(self):\n        self.sess.close()\n", "meta": {"hexsha": "b0091a9aaeaf3d6f931b768ae578a2d3731ca206", "size": 25589, "ext": "py", "lang": "Python", "max_stars_repo_path": "model.py", "max_stars_repo_name": "andrewlook/resnet-cppn-gan-tensorflow", "max_stars_repo_head_hexsha": "92491254795a85c41c1365ed3629f89d45d238d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "model.py", "max_issues_repo_name": "andrewlook/resnet-cppn-gan-tensorflow", "max_issues_repo_head_hexsha": "92491254795a85c41c1365ed3629f89d45d238d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model.py", "max_forks_repo_name": "andrewlook/resnet-cppn-gan-tensorflow", "max_forks_repo_head_hexsha": "92491254795a85c41c1365ed3629f89d45d238d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9096296296, "max_line_length": 170, "alphanum_fraction": 0.5750908594, "include": true, "reason": "import numpy", "num_tokens": 5874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.35220176844875106, "lm_q1q2_score": 0.19119740835925145}}
{"text": "\"\"\"\noptimize.py: Driver and core functions for geometry optimization\n\nCopyright 2016-2020 Regents of the University of California and the Authors\n\nAuthors: Lee-Ping Wang, Chenchen Song\n\nContributors: Yudong Qiu, Daniel G. A. Smith, Alberto Gobbi, Josh Horton\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand/or other materials provided with the distribution.\n \n3. Neither the name of the copyright holder nor the names of its contributors\nmay be used to endorse or promote products derived from this software\nwithout specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\nIN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\nWHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\nfrom __future__ import print_function, division\n\nimport os\nimport sys\nimport time\nimport traceback\nimport pkg_resources\nfrom copy import deepcopy\n\nimport numpy as np\nfrom numpy.linalg import multi_dot\n\nimport geometric\nfrom .info import print_logo, print_citation\nfrom .internal import CartesianCoordinates, PrimitiveInternalCoordinates, DelocalizedInternalCoordinates\nfrom .ic_tools import check_internal_grad, check_internal_hess, write_displacements\nfrom .normal_modes import calc_cartesian_hessian, frequency_analysis\nfrom .step import brent_wiki, Froot, calc_drms_dmax, get_cartesian_norm, rebuild_hessian, get_delta_prime, trust_step, force_positive_definite\nfrom .prepare import get_molecule_engine, parse_constraints\nfrom .params import OptParams, parse_optimizer_args\nfrom .nifty import row, col, flat, bohr2ang, ang2bohr, logger, bak, createWorkQueue\nfrom .errors import InputError, HessianExit, EngineError, GeomOptNotConvergedError, GeomOptStructureError, LinearTorsionError\n\nclass Optimizer(object):\n    def __init__(self, coords, molecule, IC, engine, dirname, params):\n        \"\"\"\n        Object representing the geometry optimization of a molecular system.\n\n        Parameters\n        ----------\n        coords : np.ndarray\n            Nx3 array of Cartesian coordinates in atomic units\n        molecule : Molecule\n            Molecule object (Units Angstrom)\n        IC : InternalCoordinates\n            Object describing the internal coordinate system\n        engine : Engine\n            Object containing methods for calculating energy and gradient\n        dirname : str\n            Directory name for files to be written\n        params : OptParams object\n            Contains optimization parameters (really just a struct)\n            Includes xyzout and qdata output file names (written if not None)\n        \"\"\"\n        # Copies of data passed into constructor\n        self.coords = coords\n        self.molecule = deepcopy(molecule)\n        self.IC = IC\n        self.engine = engine\n        self.dirname = dirname\n        self.params = params\n        # Set initial value of the trust radius.\n        self.trust = self.params.trust\n        # Copies of molecule object for preserving the optimization trajectory and the last frame\n        self.progress = deepcopy(self.molecule)\n        self.progress.xyzs = []\n        self.progress.qm_energies = []\n        self.progress.qm_grads = []\n        self.progress.comms = []\n        # Cartesian coordinates\n        self.X = self.coords.copy()\n        # Loop of optimization\n        self.Iteration = 0\n        # Counts how many steps it has been since checking the coordinate system\n        self.CoordCounter = 0\n        # Current state, used to control logic of optimization loop.\n        self.state = OPT_STATE.NEEDS_EVALUATION\n        # Some more variables to be updated throughout the course of the optimization\n        self.trustprint = \"=\"\n        self.ForceRebuild = False\n        # Sanity check - if there's only one atom, it will probably crash\n        if self.molecule.na < 2:\n            raise InputError(\"Geometry optimizer assumes there are at least two atoms in the system\")\n\n    def get_cartesian_norm(self, dy, verbose=None):\n        if not verbose: verbose = self.params.verbose\n        return get_cartesian_norm(self.X, dy, self.IC, self.params.enforce, self.params.verbose)\n\n    def get_delta_prime(self, v0, verbose=None):\n        # This method can be called at a different verbose level than the master\n        # because it can occur inside a nested loop\n        if not verbose: verbose = self.params.verbose\n        return get_delta_prime(v0, self.X, self.G, self.H, self.IC, self.params.transition, verbose)\n\n    def createFroot(self, v0):\n        return Froot(self.trust, v0, self.X, self.G, self.H, self.IC, self.params)\n\n    def refreshCoordinates(self):\n        \"\"\"\n        Refresh the Cartesian coordinates used to define parts of the internal coordinate system.\n        These include definitions of delocalized internal coordinates and reference coordinates for rotators.\n        \"\"\"\n        logger.info(\"Refreshing coordinate system and resetting rotations\\n\")\n        # Resetting of rotations\n        self.IC.resetRotations(self.X)\n        if isinstance(self.IC, DelocalizedInternalCoordinates):\n            self.IC.build_dlc(self.X)\n        # With redefined internal coordinates, the Hessian needs to be rebuilt\n        self.H0 = self.IC.guess_hessian(self.coords)\n        self.rebuild_hessian()\n        # Current values of internal coordinates and IC gradient are recalculated\n        self.Y = self.IC.calculate(self.X)\n        self.G = self.IC.calcGrad(self.X, self.gradx)\n\n    def checkCoordinateSystem(self, recover=False, cartesian=False):\n        \"\"\"\n        Build a new internal coordinate system from current Cartesians and replace the current one if different.\n        \"\"\"\n        # Reset the check counter\n        self.CoordCounter = 0\n        # Build a new molecule object and connectivity graph\n        newmol = deepcopy(self.molecule)\n        newmol.xyzs[0] = self.X.reshape(-1,3) * bohr2ang\n        newmol.build_topology()\n        # Build the new internal coordinate system\n        if cartesian:\n            if self.IC.haveConstraints():\n                raise ValueError(\"Cannot continue a constrained optimization; please implement constrained optimization in Cartesian coordinates\")\n            IC1 = CartesianCoordinates(newmol)\n        else:\n            IC1 = self.IC.__class__(newmol, connect=self.IC.connect, addcart=self.IC.addcart, build=False, conmethod=self.IC.conmethod)\n            if self.IC.haveConstraints(): IC1.getConstraints_from(self.IC)\n        # Check for differences\n        changed = (IC1 != self.IC)\n        if changed:\n            logger.info(\"\\x1b[1;94mInternal coordinate system may have changed\\x1b[0m\\n\")\n            if self.IC.repr_diff(IC1) != \"\":\n                logger.info(self.IC.repr_diff(IC1)+'\\n')\n        # Set current ICs to the new one\n        if changed or recover or cartesian:\n            self.IC = IC1\n            self.refreshCoordinates()\n            return True\n        else: return False\n\n    def trust_step(self, iopt, v0, verbose=None):\n        # This method can be called at a different verbose level than the master\n        # because it can occur inside a nested loop\n        if not verbose: verbose = self.params.verbose\n        return trust_step(iopt, v0, self.X, self.G, self.H, self.IC, self.params.transition, verbose)\n\n    def newCartesian(self, dy):\n        if self.IC.haveConstraints() and self.params.enforce:\n            self.X = self.IC.newCartesian_withConstraint(self.X, dy, thre=self.params.enforce, verbose=self.params.verbose)\n        else:\n            self.X = self.IC.newCartesian(self.X, dy, self.params.verbose)\n\n    def calcGradNorm(self):\n        gradxc = self.IC.calcGradProj(self.X, self.gradx) if self.IC.haveConstraints() else self.gradx.copy()\n        atomgrad = np.sqrt(np.sum((gradxc.reshape(-1,3))**2, axis=1))\n        rms_gradient = np.sqrt(np.mean(atomgrad**2))\n        max_gradient = np.max(atomgrad)\n        return rms_gradient, max_gradient\n\n    def rebuild_hessian(self):\n        self.H = rebuild_hessian(self.IC, self.H0, self.X_hist, self.Gx_hist, self.params)\n\n    def frequency_analysis(self, hessian, suffix, afterOpt):\n        do_wigner = False\n        if self.params.wigner:\n            # Wigner sampling should only be performed on the final Hessian calculation of a run\n            if self.params.hessian in ['last', 'first+last', 'each'] and afterOpt:\n                do_wigner = True\n            elif self.params.hessian in ['first', 'stop']:\n                do_wigner = True\n        if do_wigner:\n            logger.info(\"Requesting %i samples from Wigner distribution.\\n\" % self.params.wigner)\n        prefix = self.params.xyzout.replace(\"_optim.xyz\", \"\").replace(\".xyz\", \"\")\n        # Call the frequency analysis function with an input Hessian, with most arguments populated from self.params\n        frequency_analysis(self.X, hessian, self.molecule.elem, energy=self.E, temperature=self.params.temperature, pressure=self.params.pressure, verbose=self.params.verbose, \n                           outfnm='%s.vdata_%s' % (prefix, suffix), note='Iteration %i Energy % .8f%s' % (self.Iteration, self.E, ' (Optimized Structure)' if afterOpt else ''),\n                           wigner=((self.params.wigner, os.path.join(self.dirname, 'wigner')) if do_wigner else None))\n\n\n    def calcEnergyForce(self):\n        \"\"\"\n        Calculate the energy and Cartesian gradients of the current structure.\n        \"\"\"\n        # Check to confirm that the structure has nothing that would cause a cryptic error\n        self.checkStructure()\n        ### Calculate Energy and Gradient ###\n        # Dictionary containing single point properties (energy, gradient)\n        # For frequency calculations and multi-step jobs, the gradient from an existing\n        # output file may be read in.\n        spcalc = self.engine.calc(self.X, self.dirname, read_data=(self.Iteration==0))\n        self.E = spcalc['energy']\n        self.gradx = spcalc['gradient']\n        # Calculate Hessian at the first step, or at each step if desired\n        if self.params.hessian == 'each':\n            # Hx is assumed to be the Cartesian Hessian at the current step.\n            # Otherwise we use the variable name Hx0 to avoid almost certain confusion.\n            self.Hx = calc_cartesian_hessian(self.X, self.molecule, self.engine, self.dirname, read_data=True, verbose=self.params.verbose)\n            if self.params.frequency:\n                self.frequency_analysis(self.Hx, 'iter%03i' % self.Iteration, False)\n        elif self.Iteration == 0:\n            if self.params.hessian in ['first', 'stop', 'first+last']:\n                self.Hx0 = calc_cartesian_hessian(self.X, self.molecule, self.engine, self.dirname, read_data=True, verbose=self.params.verbose)\n                if self.params.frequency:\n                    self.frequency_analysis(self.Hx0, 'first', False)\n                if self.params.hessian == 'stop':\n                    logger.info(\"Exiting as requested after Hessian calculation.\\n\")\n                    logger.info(\"Cartesian Hessian is stored in %s/hessian/hessian.txt.\\n\" % self.dirname)\n                    raise HessianExit\n                    # sys.exit(0)\n            elif hasattr(self.params, 'hess_data') and self.Iteration == 0:\n                self.Hx0 = self.params.hess_data.copy()\n                if self.params.frequency:\n                    self.frequency_analysis(self.Hx0, 'first', False)\n                if self.Hx0.shape != (self.X.shape[0], self.X.shape[0]):\n                    raise IOError('hess_data passed in via OptParams does not have the right shape')\n            # self.Hx = self.Hx0.copy()\n        # Add new Cartesian coordinates, energies, and gradients to history\n        self.progress.xyzs.append(self.X.reshape(-1,3) * bohr2ang)\n        self.progress.qm_energies.append(self.E)\n        self.progress.qm_grads.append(self.gradx.copy())\n        self.progress.comms.append('Iteration %i Energy % .8f' % (self.Iteration, self.E))\n\n    def prepareFirstStep(self):\n        \"\"\"\n        After computing the initial set of energies and forces, carry out some preparatory tasks\n        prior to entering the optimization loop.\n        \"\"\"\n        # Initial internal coordinates (optimization variables) and internal gradient\n        self.Y = self.IC.calculate(self.coords)\n        self.G = self.IC.calcGrad(self.X, self.gradx).flatten()\n        # Print initial iteration\n        rms_gradient, max_gradient = self.calcGradNorm()\n        msg = \"Step %4i :\" % self.Iteration\n        logger.info(msg + \" Gradient = %.3e/%.3e (rms/max) Energy = % .10f\\n\" % (rms_gradient, max_gradient, self.E))\n        # Initial history\n        self.X_hist = [self.X]\n        self.Gx_hist = [self.gradx]\n        # Initial Hessian\n        if hasattr(self, 'Hx'):\n            # Compute IC Hessian from Cartesian Hessian at the current step\n            self.H0 = self.IC.calcHess(self.X, self.gradx, self.Hx)\n        elif hasattr(self, 'Hx0'):\n            # Compute IC Hessian from input Cartesian Hessian\n            self.H0 = self.IC.calcHess(self.X, self.gradx, self.Hx0)\n        else:\n            # Form guess Hessian if initial Hessian is not provided\n            self.H0 = self.IC.guess_hessian(self.coords)\n        self.H = self.H0.copy()\n\n    def SortedEigenvalues(self):\n        Eig = sorted(np.linalg.eigh(self.H)[0])\n        if self.params.transition and len(Eig) >= 12:\n            # logger.info(\"Hessian Eigenvalues:  %.3e %.3e %.3e %.3e %.3e %.3e %.3e %.3e %.3e ... %.3e %.3e %.3e\\n\" %\n            #             (Eig[0],Eig[1],Eig[2],Eig[3],Eig[4],Eig[5],Eig[6],Eig[7],Eig[8],Eig[-3],Eig[-2],Eig[-1]))\n            logger.info(\"Hessian Eigenvalues:  % .3e % .3e % .3e % .3e % .3e % .3e % .3e\\n\" % (Eig[0],Eig[1],Eig[2],Eig[3],Eig[4],Eig[5],Eig[6])),\n            logger.info(\"% .3e % .3e % .3e % .3e % .3e    .....   % .3e % .3e % .3e\\n\" % (Eig[7],Eig[8],Eig[9],Eig[10],Eig[11],Eig[-3],Eig[-2],Eig[-1])),\n        elif len(Eig) >= 6:\n            logger.info(\"Hessian Eigenvalues: %.5e %.5e %.5e ... %.5e %.5e %.5e\\n\" % (Eig[0],Eig[1],Eig[2],Eig[-3],Eig[-2],Eig[-1]))\n        else:\n            logger.info(\"Hessian Eigenvalues: \" + ' '.join(\"%.5e\" % i for i in Eig) + '\\n')\n        return Eig\n        \n    def step(self):\n        \"\"\"\n        Perform one step of the optimization.\n        \"\"\"\n        params = self.params\n        if np.isnan(self.G).any():\n            raise RuntimeError(\"Gradient contains nan - check output and temp-files for possible errors\")\n        if np.isnan(self.H).any():\n            raise RuntimeError(\"Hessian contains nan - check output and temp-files for possible errors\")\n        self.Iteration += 1\n        if (self.Iteration%5) == 0:\n            self.engine.clearCalcs()\n            self.IC.clearCache()\n\n        # At the start of the loop, the optimization variables, function value, gradient and Hessian are known.\n        # (i.e. self.Y, self.E, self.G, self.H)\n        if params.verbose: self.IC.printRotations(self.X)\n        Eig = self.SortedEigenvalues()\n        Emin = Eig[0].real\n        if params.transition:\n            v0 = 1.0\n        elif Emin < params.epsilon:\n            v0 = params.epsilon-Emin\n        else:\n            v0 = 0.0\n        # Are we far from constraint satisfaction?\n        self.farConstraints = self.IC.haveConstraints() and self.IC.maxConstraintViolation(self.X) > 1e-1\n        ### OBTAIN AN OPTIMIZATION STEP ###\n        # The trust radius is to be computed in Cartesian coordinates.\n        # First take a full-size optimization step\n        if params.verbose: logger.info(\"  Optimizer.step : Attempting full-size optimization step\\n\")\n        dy, _, __ = self.get_delta_prime(v0, verbose=self.params.verbose)\n        # Internal coordinate step size\n        inorm = np.linalg.norm(dy)\n        # Cartesian coordinate step size\n        self.cnorm = self.get_cartesian_norm(dy)\n        # If the full-size step is within the trust radius, then call get_delta_prime again with diagnostic messages if needed\n        if (self.params.verbose >= 2 and self.params.verbose < 4 and self.cnorm <= 1.1*self.trust):\n            self.get_delta_prime(v0, verbose=self.params.verbose+2)\n        if params.verbose: logger.info(\"  Optimizer.step : Internal-step: %.4f Cartesian-step: %.4f Trust-radius: %.4f\\n\" % (inorm, self.cnorm, self.trust))\n        # If the step is above the trust radius in Cartesian coordinates, then\n        # do the following to reduce the step length:\n        if self.cnorm > 1.1 * self.trust:\n            # This is the function f(inorm) = cnorm-target that we find a root\n            # for obtaining a step with the desired Cartesian step size.\n            froot = self.createFroot(v0)\n            froot.stores[inorm] = self.cnorm\n            ### Find the internal coordinate norm that matches the desired Cartesian coordinate norm\n            if params.verbose: logger.info(\"  Optimizer.step : Using Brent algorithm to target Cartesian trust radius\\n\")\n            iopt = brent_wiki(froot.evaluate, 0.0, inorm, self.trust, cvg=0.1, obj=froot, verbose=params.verbose)\n            if froot.brentFailed and froot.stored_arg is not None:\n                # If Brent fails but we obtained an IC step that is smaller than the Cartesian trust radius, use it\n                if params.verbose: logger.info(\"  Optimizer.step : \\x1b[93mUsing stored solution at %.3e\\x1b[0m\\n\" % froot.stored_val)\n                iopt = froot.stored_arg\n            elif self.IC.bork:\n                # Decrease the target Cartesian step size and try again\n                for i in range(3):\n                    froot.target /= 2\n                    if params.verbose: logger.info(\"  Optimizer.step : \\x1b[93mReducing target to %.3e\\x1b[0m\\n\" % froot.target)\n                    froot.above_flag = True # Stop at any valid step between current target step size and trust radius\n                    iopt = brent_wiki(froot.evaluate, 0.0, iopt, froot.target, cvg=0.1, verbose=params.verbose)\n                    if not self.IC.bork: break\n            LastForce = self.ForceRebuild\n            self.ForceRebuild = False\n            if self.IC.bork:\n                logger.info(\"\\x1b[91mInverse iteration for Cartesians failed\\x1b[0m\\n\")\n                # This variable is added because IC.bork is unset later.\n                self.ForceRebuild = True\n            else:\n                if params.verbose: logger.info(\"  Optimizer.step : \\x1b[93mBrent algorithm requires %i evaluations\\x1b[0m\\n\" % froot.counter)\n            ##### If IC failed to produce valid Cartesian step, it is \"borked\" and we need to rebuild it.\n            if self.ForceRebuild:\n                # Force a rebuild of the coordinate system and skip the energy / gradient and evaluation steps.\n                if LastForce:\n                    logger.warning(\"\\x1b[1;91mFailed twice in a row to rebuild the coordinate system; continuing in Cartesian coordinates\\x1b[0m\\n\")\n                self.checkCoordinateSystem(recover=True, cartesian=LastForce)\n                logger.info(\"\\x1b[1;93mSkipping optimization step\\x1b[0m\\n\")\n                self.Iteration -= 1\n                self.state = OPT_STATE.SKIP_EVALUATION\n                return\n            ##### End Rebuild\n            # Finally, take an internal coordinate step of the desired length.\n            dy, _ = self.trust_step(iopt, v0, verbose=(self.params.verbose+1 if self.params.verbose >= 2 else 0))\n            self.cnorm = self.get_cartesian_norm(dy)\n        ### DONE OBTAINING THE STEP ###\n        if isinstance(self.IC, PrimitiveInternalCoordinates):\n            idx = np.argmax(np.abs(dy))\n            iunit = np.zeros_like(dy)\n            iunit[idx] = 1.0\n            self.prim_msg = \"Along %s %.3f\" % (self.IC.Internals[idx], np.dot(dy/np.linalg.norm(dy), iunit))\n        ### These quantities, computed previously, are no longer used.\n        # Dot product of the gradient with the step direction\n        # Dot = -np.dot(dy/np.linalg.norm(dy), self.G/np.linalg.norm(self.G))\n        # Whether the Cartesian norm comes close to the trust radius\n        # bump = cnorm > 0.8 * self.trust\n        ### Before updating any of our variables, copy current variables to \"previous\"\n        self.Yprev = self.Y.copy()\n        self.Xprev = self.X.copy()\n        self.Gxprev = self.gradx.copy()\n        self.Gprev = self.G.copy()\n        self.Eprev = self.E\n        ### Update the Internal Coordinates ###\n        X0 = self.X.copy()\n        self.newCartesian(dy)\n        ## The \"actual\" dy may be different from the one passed to newCartesian(),\n        ## for example if we enforce constraints or don't get the step we expect.\n        dy = self.IC.calcDiff(self.X, X0)\n        # dyp = self.IC.Prims.calcDiff(self.X, X0)\n        # print(\"Actual dy:\", dy)\n        self.Y += dy\n        self.expect = flat(0.5*multi_dot([row(dy),self.H,col(dy)]))[0] + np.dot(dy,self.G)\n        self.state = OPT_STATE.NEEDS_EVALUATION\n\n    def evaluateStep(self):\n        ### At this point, the state should be NEEDS_EVALUATION\n        assert self.state == OPT_STATE.NEEDS_EVALUATION\n        # Shorthand for self.params\n        params = self.params\n        # Write current optimization trajectory to file\n        if self.params.xyzout is not None: self.progress.write(self.params.xyzout)\n        if self.params.qdata is not None: self.progress.write(self.params.qdata, ftype='qdata')\n        # Project out the degrees of freedom that are constrained\n        rms_gradient, max_gradient = self.calcGradNorm()\n        rms_displacement, max_displacement = calc_drms_dmax(self.X, self.Xprev)\n        # The ratio of the actual energy change to the expected change\n        Quality = (self.E-self.Eprev)/self.expect\n        colors = {}\n        colors['quality'] = \"\\x1b[0m\"\n        # 2020-03-10: Step quality thresholds are hard-coded here.\n        # At the moment, no need to set them as variables.\n        if params.transition:\n            if Quality > 0.8 and Quality < 1.2: step_state = StepState.Good\n            elif Quality > 0.5 and Quality < 1.5: step_state = StepState.Okay\n            elif Quality > 0.0 and Quality < 2.0: step_state = StepState.Poor\n            else:\n                colors['energy'] = \"\\x1b[91m\"\n                colors['quality'] = \"\\x1b[91m\"\n                step_state = StepState.Reject\n        else:\n            if Quality > 0.75: step_state = StepState.Good\n            elif Quality > 0.25: step_state = StepState.Okay\n            elif Quality > 0.0: step_state = StepState.Poor\n            else:\n                colors['energy'] = \"\\x1b[91m\"\n                colors['quality'] = \"\\x1b[91m\"\n                step_state = StepState.Poor if Quality > -1.0 else StepState.Reject\n        # Check convergence criteria\n        Converged_energy = np.abs(self.E-self.Eprev) < params.Convergence_energy\n        Converged_grms = rms_gradient < params.Convergence_grms\n        Converged_gmax = max_gradient < params.Convergence_gmax\n        Converged_drms = rms_displacement < params.Convergence_drms\n        Converged_dmax = max_displacement < params.Convergence_dmax\n        if 'energy' not in colors: colors['energy'] = \"\\x1b[92m\" if Converged_energy else \"\\x1b[0m\"\n        colors['grms'] = \"\\x1b[92m\" if Converged_grms else \"\\x1b[0m\"\n        colors['gmax'] = \"\\x1b[92m\" if Converged_gmax else \"\\x1b[0m\"\n        colors['drms'] = \"\\x1b[92m\" if Converged_drms else \"\\x1b[0m\"\n        colors['dmax'] = \"\\x1b[92m\" if Converged_dmax else \"\\x1b[0m\"\n        # Molpro defaults for convergence\n        Converged_molpro_gmax = max_gradient < params.Convergence_molpro_gmax\n        Converged_molpro_dmax = max_displacement < params.Convergence_molpro_dmax\n        self.conSatisfied = not self.IC.haveConstraints() or self.IC.maxConstraintViolation(self.X) < 1e-2\n        # Print status\n        msg = \"Step %4i :\" % self.Iteration\n        msg += \" Displace = %s%.3e\\x1b[0m/%s%.3e\\x1b[0m (rms/max)\" % (colors['drms'], rms_displacement, colors['dmax'], max_displacement)\n        msg += \" Trust = %.3e (%s)\" % (self.trust, self.trustprint)\n        msg += \" Grad%s = %s%.3e\\x1b[0m/%s%.3e\\x1b[0m (rms/max)\" % (\"_T\" if self.IC.haveConstraints() else \"\", colors['grms'], rms_gradient, colors['gmax'], max_gradient)\n        logger.info(msg + \" E (change) = % .10f (%s%+.3e\\x1b[0m) Quality = %s%.3f\\x1b[0m\" % (self.E, colors['energy'], self.E-self.Eprev, colors['quality'], Quality) + \"\\n\")\n\n        if self.IC is not None and self.IC.haveConstraints():\n            self.IC.printConstraints(self.X, thre=1e-3)\n        if isinstance(self.IC, PrimitiveInternalCoordinates):\n            logger.info(self.prim_msg + '\\n')\n\n        ### Check convergence criteria ###\n        if Converged_energy and Converged_grms and Converged_drms and Converged_gmax and Converged_dmax and self.conSatisfied:\n            self.SortedEigenvalues()\n            logger.info(\"Converged! =D\\n\")\n            self.state = OPT_STATE.CONVERGED\n            return\n\n        if self.Iteration > params.maxiter:\n            self.SortedEigenvalues()\n            logger.info(\"Maximum iterations reached (%i); increase --maxiter for more\\n\" % params.maxiter)\n            self.state = OPT_STATE.FAILED\n            return\n\n        if params.qccnv and Converged_grms and (Converged_drms or Converged_energy) and self.conSatisfied:\n            self.SortedEigenvalues()\n            logger.info(\"Converged! (Q-Chem style criteria requires grms and either drms or energy)\\n\")\n            self.state = OPT_STATE.CONVERGED\n            return\n\n        if params.molcnv and Converged_molpro_gmax and (Converged_molpro_dmax or Converged_energy) and self.conSatisfied:\n            self.SortedEigenvalues()\n            logger.info(\"Converged! (Molpro style criteria requires gmax and either dmax or energy)\\nThis is approximate since convergence checks are done in cartesian coordinates.\\n\")\n            self.state = OPT_STATE.CONVERGED\n            return\n\n        assert self.state == OPT_STATE.NEEDS_EVALUATION\n        \n        ### Adjust Trust Radius and/or Reject Step ###\n        prev_trust = self.trust\n        if step_state in (StepState.Poor, StepState.Reject):\n            new_trust = max(params.tmin, min(self.trust, self.cnorm)/2)\n            self.trustprint = \"\\x1b[91m-\\x1b[0m\" if new_trust < self.trust else \"=\"\n            self.trust = new_trust\n        elif step_state == StepState.Good:\n            new_trust = min(params.tmax, np.sqrt(2)*self.trust)\n            self.trustprint = \"\\x1b[92m+\\x1b[0m\" if new_trust > self.trust else \"=\"\n            self.trust = new_trust\n        elif step_state == StepState.Okay:\n            self.trustprint = \"=\"\n\n        if step_state == StepState.Reject:\n            if prev_trust <= params.thre_rj:\n                logger.info(\"\\x1b[93mNot rejecting step - trust below %.3e\\x1b[0m\\n\" % params.thre_rj)\n            elif (not params.transition) and self.E < self.Eprev:\n                logger.info(\"\\x1b[93mNot rejecting step - energy decreases during minimization\\x1b[0m\\n\")\n            elif self.farConstraints:\n                logger.info(\"\\x1b[93mNot rejecting step - far from constraint satisfaction\\x1b[0m\\n\")\n            else:\n                logger.info(\"\\x1b[93mStep Is Rejected\\x1b[0m\\n\")\n                self.trustprint = \"\\x1b[1;91mx\\x1b[0m\"\n                self.Y = self.Yprev.copy()\n                self.X = self.Xprev.copy()\n                self.gradx = self.Gxprev.copy()\n                self.G = self.Gprev.copy()\n                self.E = self.Eprev\n                return\n\n        # Append steps to history (for rebuilding Hessian)\n        self.X_hist.append(self.X)\n        self.Gx_hist.append(self.gradx)\n\n        ### Rebuild Coordinate System if Necessary ###\n        UpdateHessian = (not self.params.hessian == 'each')\n        if self.IC.bork:\n            logger.info(\"Failed inverse iteration - checking coordinate system\\n\")\n            self.checkCoordinateSystem(recover=True)\n            UpdateHessian = False\n        elif self.CoordCounter == (params.check - 1):\n            logger.info(\"Checking coordinate system as requested every %i cycles\\n\" % params.check)\n            if self.checkCoordinateSystem(): UpdateHessian = False\n        else:\n            self.CoordCounter += 1\n        # Check for large rotations (debugging purposes)\n        if self.params.verbose >= 1: self.IC.largeRots()\n        # Check for large rotations in linear molecules\n        if self.IC.linearRotCheck():\n            logger.info(\"Large rotations in linear molecules - refreshing Rotator reference points and DLC vectors\\n\")\n            self.refreshCoordinates()\n            UpdateHessian = False\n        self.G = self.IC.calcGrad(self.X, self.gradx).flatten()\n\n        ### Update the Hessian ###\n        if UpdateHessian:\n            self.UpdateHessian()\n        if hasattr(self, 'Hx'):\n            self.H = self.IC.calcHess(self.X, self.gradx, self.Hx)\n        # Then it's on to the next loop iteration!\n        return\n\n    def UpdateHessian(self):\n        params = self.params\n\n        if params.transition:\n            ts_bfgs = False\n            if ts_bfgs: # pragma: no cover\n                logger.info(\"TS-BFGS Hessian update\\n\")\n                # yk = Dg; dk = Dy\n                dk = col(self.Y - self.Yprev)\n                yk = col(self.G - self.Gprev)\n                jk = yk - np.dot(self.H, dk)\n                B = force_positive_definite(self.H)\n                # Scalar 1: dk^T |Bk| dk\n                s1 = multi_dot([dk.T, B, dk])\n                # Scalar 2: (yk^T dk)^2 + (dk^T |Bk| dk)^2\n                s2 = np.dot(yk.T, dk)**2 + s1**2\n                # Vector quantities\n                v2 = np.dot(yk.T, dk)*yk + s1*np.dot(B, dk)\n                uk = v2/s2\n                Ek = np.dot(jk, uk.T) + np.dot(uk, jk.T) + np.dot(jk.T, dk) * np.dot(uk, uk.T)\n                self.H += Ek\n            else:\n                Dy   = col(self.Y - self.Yprev)\n                Dg   = col(self.G - self.Gprev)\n                # Murtagh-Sargent-Powell update\n                Xi = Dg - np.dot(self.H,Dy)\n                # ndy2 = np.dot(Dy.T,Dy)\n                dH_MS = np.dot(Xi, Xi.T)/np.dot(Dy.T, Xi)\n                dH_P = np.dot(Xi, Dy.T) + np.dot(Dy, Xi.T) - np.dot(Dy, Dy.T)*np.dot(Xi.T, Dy)/np.dot(Dy.T, Dy)\n                dH_P /= np.dot(Dy.T, Dy)\n                phi = 1.0 - np.dot(Dy.T,Xi)**2/(np.dot(Dy.T,Dy)*np.dot(Xi.T,Xi))\n                # phi = 1.0\n                self.H += (1.0-phi)*dH_MS + phi*dH_P\n                if params.verbose:\n                    logger.info(\"Hessian update: %.5f Powell + %.5f Murtagh-Sargent\\n\" % (phi, 1.0-phi))\n        else:\n            Dy   = col(self.Y - self.Yprev)\n            Dg   = col(self.G - self.Gprev)\n            # Catch some abnormal cases of extremely small changes.\n            if np.linalg.norm(Dg) < 1e-6: return\n            if np.linalg.norm(Dy) < 1e-6: return\n            # BFGS Hessian update\n            Mat1 = np.dot(Dg,Dg.T)/np.dot(Dg.T,Dy)[0,0]\n            Mat2 = np.dot(np.dot(self.H,Dy), np.dot(self.H,Dy).T)/multi_dot([Dy.T,self.H,Dy])[0,0]\n            Eig = np.linalg.eigh(self.H)[0]\n            Eig.sort()\n            ndy = np.array(Dy).flatten()/np.linalg.norm(np.array(Dy))\n            ndg = np.array(Dg).flatten()/np.linalg.norm(np.array(Dg))\n            nhdy = np.dot(self.H,Dy).flatten()/np.linalg.norm(np.dot(self.H,Dy))\n            if params.verbose:\n                msg = \"Denoms: %.3e %.3e\" % (np.dot(Dg.T,Dy)[0,0], multi_dot((Dy.T,self.H,Dy))[0,0])\n                msg +=\" Dots: %.3e %.3e\" % (np.dot(ndg, ndy), np.dot(ndy, nhdy))\n            #H1 = H.copy()\n            self.H += Mat1-Mat2\n            Eig1 = np.linalg.eigh(self.H)[0]\n            Eig1.sort()\n            if params.verbose:\n                msg += \" Eig-ratios: %.5e ... %.5e\" % (np.min(Eig1)/np.min(Eig), np.max(Eig1)/np.max(Eig))\n                logger.info(msg+'\\n')\n            if np.min(Eig1) <= params.epsilon and params.reset:\n                logger.info(\"Eigenvalues below %.4e (%.4e) - returning guess\\n\" % (params.epsilon, np.min(Eig1)))\n                self.H = self.IC.guess_hessian(self.coords)\n\n    def optimizeGeometry(self):\n        \"\"\"\n        High-level optimization loop.\n        This allows calcEnergyForce() to be separated from the rest of the codes\n        \"\"\"\n        self.calcEnergyForce()\n        self.prepareFirstStep()\n        while self.state not in [OPT_STATE.CONVERGED, OPT_STATE.FAILED]:\n            self.step()\n            if self.state == OPT_STATE.NEEDS_EVALUATION:\n                self.calcEnergyForce()\n                self.evaluateStep()\n        if self.state == OPT_STATE.FAILED:\n            raise GeomOptNotConvergedError(\"Optimizer.optimizeGeometry() failed to converge.\")\n        # If we want to save the Hessian used by the optimizer (in Cartesian coordinates)\n        if self.params.write_cart_hess:\n            # One last Hessian update before writing it out\n            self.UpdateHessian()\n            logger.info(\"Saving current approximate Hessian (Cartesian coordinates) to %s\" % self.params.write_cart_hess)\n            Hx = self.IC.calcHessCart(self.X, self.G, self.H)\n            np.savetxt(self.params.write_cart_hess, Hx, fmt='% 14.10f')\n        if self.params.hessian in ['last', 'first+last', 'each']:\n            Hx = calc_cartesian_hessian(self.X, self.molecule, self.engine, self.dirname, read_data=False, verbose=self.params.verbose)\n            if self.params.frequency:\n                self.frequency_analysis(Hx, 'last', True)\n        return self.progress\n\n    def checkStructure(self):\n        \"\"\"\n        A function that checks for problematic structures and throws an error before\n        calling any QC method.\n        \"\"\"\n        # Check for three consecutive atoms in torsion angle becoming linear\n        torsion_constraint_linear_angles = self.IC.torsionConstraintLinearAngles(self.X)\n        if torsion_constraint_linear_angles:\n            errorStr = \"> Atoms Angle\\n\"\n            for key, val in torsion_constraint_linear_angles.items():\n                errorStr += \"> %i-%i-%i %6.2f\\n\" % (key[0]+1, key[1]+1, key[2]+1, val)\n            raise LinearTorsionError(\"A constrained torsion has three consecutive atoms\\n\"\n                                     \"forming a nearly linear angle, making the torsion angle poorly defined.\\n\"+errorStr)\n        \n\nclass OPT_STATE(object):\n    \"\"\" This describes the state of an OptObject during the optimization process\n    \"\"\"\n    NEEDS_EVALUATION = 0  # convergence has not been evaluated -> calcualte Energy, Forces\n    SKIP_EVALUATION  = 1  # We know this is not yet converged -> skip Energy\n    CONVERGED        = 2\n    FAILED           = 3  # optimization failed with no recovery option\n\nclass StepState(object):\n    \"\"\" This describes the state of an OptObject during the optimization process\n    \"\"\"\n    Reject  = 0 # Reject the step\n    Poor    = 1 # Poor step; decrease the trust radius down to the lower limit.\n    Okay    = 2 # Okay step; do not change the trust radius.\n    Good    = 3 # Good step; increase the trust radius up to the limit.\n    \ndef Optimize(coords, molecule, IC, engine, dirname, params):\n    \"\"\"\n    Optimize the geometry of a molecule. This function used to contain the whole\n    optimization loop, which has since been moved to the Optimizer() class;\n    now a wrapper and kept for compatibility.\n\n    Parameters\n    ----------\n    coords : np.ndarray\n        Nx3 array of Cartesian coordinates in atomic units\n    molecule : Molecule\n        Molecule object\n    IC : InternalCoordinates\n        Object describing the internal coordinate system\n    engine : Engine\n        Object containing methods for calculating energy and gradient\n    dirname : str\n        Directory name for files to be written\n    params : OptParams object\n        Contains optimization parameters (really just a struct)\n    hessian : np.ndarray, optional\n        3Nx3N array of Cartesian Hessian of initial structure\n\n    Returns\n    -------\n    progress: Molecule\n        A molecule object for opt trajectory and energies\n    \"\"\"\n    optimizer = Optimizer(coords, molecule, IC, engine, dirname, params)\n    return optimizer.optimizeGeometry()\n\ndef run_optimizer(**kwargs):\n    \"\"\"\n    Run geometry optimization, constrained optimization, or\n    constrained scan job given arguments from command line.\n    \"\"\"\n    #==============================#\n    #|   Log file configuration   |#\n    #==============================#\n    # By default, output should be written to <args.prefix>.log and also printed to the terminal.\n    # This behavior may be changed by editing the log.ini file.\n    # Output will only be written to log files after the 'logConfig' line is called!\n    if kwargs.get('logIni') is None:\n        import geometric.optimize\n        logIni = pkg_resources.resource_filename(geometric.optimize.__name__, 'config/log.ini')\n    else:\n        logIni = kwargs.get('logIni')\n    logfilename = kwargs.get('prefix')\n    # Input file for optimization; QC input file or OpenMM .xml file\n    inputf = kwargs.get('input')\n    verbose = kwargs.get('verbose', False)\n    # Get calculation prefix and temporary directory name\n    arg_prefix = kwargs.get('prefix', None) #prefix for output file and temporary directory\n    prefix = arg_prefix if arg_prefix is not None else os.path.splitext(inputf)[0]\n    logfilename = prefix + \".log\"\n    # Create a backup if the log file already exists\n    backed_up = bak(logfilename)\n    import logging.config\n    logging.config.fileConfig(logIni,defaults={'logfilename': logfilename},disable_existing_loggers=False)\n    #==============================#\n    #| End log file configuration |#\n    #==============================#\n\n    import geometric\n    logger.info('geometric-optimize called with the following command line:\\n')\n    logger.info(' '.join(sys.argv)+'\\n')\n    print_logo(logger)\n    logger.info('-=# \\x1b[1;94m geomeTRIC started. Version: %s \\x1b[0m #=-\\n' % geometric.__version__)\n    if backed_up:\n        logger.info('Backed up existing log file: %s -> %s\\n' % (logfilename, os.path.basename(backed_up)))\n\n    t0 = time.time()\n\n    # Create the params object, containing data to be passed into the optimizer\n    params = OptParams(**kwargs)\n    params.printInfo()\n\n    # Create \"dirname\" folder for writing\n    dirname = prefix+\".tmp\"\n    if not os.path.exists(dirname):\n        os.makedirs(dirname)\n    kwargs['dirname'] = dirname\n    \n    # Get the Molecule and engine objects needed for optimization\n    M, engine = get_molecule_engine(**kwargs)\n\n    # Create Work Queue object\n    if kwargs.get('port', 0):\n        logger.info(\"Creating Work Queue object for distributed Hessian calculation\\n\")\n        createWorkQueue(kwargs['port'], debug=verbose>1)\n\n    # Get initial coordinates in bohr\n    coords = M.xyzs[0].flatten() * ang2bohr\n\n    # Read in the constraints\n    constraints = kwargs.get('constraints', None) #Constraint input file (optional)\n\n    if constraints is not None:\n        Cons, CVals = parse_constraints(M, open(constraints).read())\n    else:\n        Cons = None\n        CVals = None\n\n    #=========================================#\n    #| Set up the internal coordinate system |#\n    #=========================================#\n    # First item in tuple: The class to be initialized\n    # Second item in tuple: Whether to connect nonbonded fragments\n    # Third item in tuple: Whether to throw in all Cartesians (no effect if second item is True)\n    CoordSysDict = {'cart':(CartesianCoordinates, False, False),\n                    'prim':(PrimitiveInternalCoordinates, True, False),\n                    'dlc':(DelocalizedInternalCoordinates, True, False),\n                    'hdlc':(DelocalizedInternalCoordinates, False, True),\n                    'tric-p':(PrimitiveInternalCoordinates, False, False),\n                    'tric':(DelocalizedInternalCoordinates, False, False)}\n    coordsys = kwargs.get('coordsys', 'tric')\n    CoordClass, connect, addcart = CoordSysDict[coordsys.lower()]\n\n    IC = CoordClass(M, build=True, connect=connect, addcart=addcart, constraints=Cons, cvals=CVals[0] if CVals is not None else None,\n                    conmethod=params.conmethod)\n    #========================================#\n    #| End internal coordinate system setup |#\n    #========================================#\n\n    # Auxiliary functions (will not do optimization):\n    displace = kwargs.get('displace', False) # Write out the displacements of the coordinates.\n    if displace:\n        write_displacements(coords, M, IC, dirname, verbose)\n        return\n\n    fdcheck = kwargs.get('fdcheck', False) # Check internal coordinate gradients using finite difference..\n    if fdcheck:\n        IC.Prims.checkFiniteDifferenceGrad(coords)\n        IC.Prims.checkFiniteDifferenceHess(coords)\n        check_internal_grad(coords, M, IC.Prims, engine, dirname, verbose)\n        check_internal_hess(coords, M, IC.Prims, engine, dirname, verbose)\n        return\n\n    # Print out information about the coordinate system\n    if isinstance(IC, CartesianCoordinates):\n        logger.info(\"%i Cartesian coordinates being used\\n\" % (3*M.na))\n    else:\n        logger.info(\"%i internal coordinates being used (instead of %i Cartesians)\\n\" % (len(IC.Internals), 3*M.na))\n    logger.info(IC)\n    logger.info(\"\\n\")\n\n    if Cons is None:\n        # Run a standard geometry optimization\n        params.xyzout = prefix+\"_optim.xyz\"\n        progress = Optimize(coords, M, IC, engine, dirname, params)\n    else:\n        # Run a single constrained geometry optimization or scan over a grid of values\n        if isinstance(IC, (CartesianCoordinates, PrimitiveInternalCoordinates)):\n            raise RuntimeError(\"Constraints only work with delocalized internal coordinates\")\n        Mfinal = None\n        for ic, CVal in enumerate(CVals):\n            if len(CVals) > 1:\n                logger.info(\"---=== Scan %i/%i : Constrained Optimization ===---\\n\" % (ic+1, len(CVals)))\n            IC = CoordClass(M, build=True, connect=connect, addcart=addcart, constraints=Cons, cvals=CVal, conmethod=params.conmethod)\n            IC.printConstraints(coords, thre=-1)\n            if len(CVals) > 1:\n                params.xyzout = prefix+\"_scan-%03i.xyz\" % (ic+1)\n                # In the special case of a constraint scan, we write out multiple qdata.txt files\n                if params.qdata is not None: params.qdata = 'qdata_scan-%03i.txt' % (ic+1)\n            else:\n                params.xyzout = prefix+\"_optim.xyz\"\n            if ic == 0:\n                progress = Optimize(coords, M, IC, engine, dirname, params)\n            else:\n                progress += Optimize(coords, M, IC, engine, dirname, params)\n            # update the structure for next optimization in SCAN (by CNH)\n            M.xyzs[0] = progress.xyzs[-1]\n            coords = progress.xyzs[-1].flatten() * ang2bohr\n            if Mfinal:\n                Mfinal += progress[-1]\n            else:\n                Mfinal = progress[-1]\n            cNames = IC.getConstraintNames()\n            cVals = IC.getConstraintTargetVals()\n            comment = ', '.join([\"%s = %.2f\" % (cName, cVal) for cName, cVal in zip(cNames, cVals)])\n            Mfinal.comms[-1] = \"Scan Cycle %i/%i ; %s ; %s\" % (ic+1, len(CVals), comment, progress.comms[-1])\n            #print\n        if len(CVals) > 1:\n            Mfinal.write('scan-final.xyz')\n            if params.qdata is not None: Mfinal.write('qdata-final.txt')\n    print_citation(logger)\n    logger.info(\"Time elapsed since start of run_optimizer: %.3f seconds\\n\" % (time.time()-t0))\n    return progress\n\ndef main(): # pragma: no cover\n    # Read user input (look in params.py for full list of options).\n    # args is a dictionary containing only user-specified arguments\n    # (i.e. keys without provided values are removed.)\n    args = parse_optimizer_args(sys.argv[1:])\n\n    # Run the optimizer.\n    try:\n        run_optimizer(**args)\n    except EngineError:\n        logger.info(\"EngineError:\\n\" + traceback.format_exc())\n        sys.exit(51)\n    except GeomOptNotConvergedError:\n        logger.info(\"Geometry Converge Failed Error:\\n\" + traceback.format_exc())\n        sys.exit(50)\n    except GeomOptStructureError:\n        logger.info(\"Structure Error:\\n\" + traceback.format_exc())\n        sys.exit(50)\n    except HessianExit:\n        logger.info(\"Exiting normally.\\n\")\n        sys.exit(0)\n    except:\n        logger.info(\"Unknown Error:\\n\" + traceback.format_exc())\n        raise\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "7fea845d0ac92f83cf209e5e3a865224d49d5b9d", "size": 45320, "ext": "py", "lang": "Python", "max_stars_repo_path": "geometric/optimize.py", "max_stars_repo_name": "AnthoniAlcaraz/geomeTRIC", "max_stars_repo_head_hexsha": "de6d688a7c4928b7afe89493b3cb8cfc25d580f1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "geometric/optimize.py", "max_issues_repo_name": "AnthoniAlcaraz/geomeTRIC", "max_issues_repo_head_hexsha": "de6d688a7c4928b7afe89493b3cb8cfc25d580f1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geometric/optimize.py", "max_forks_repo_name": "AnthoniAlcaraz/geomeTRIC", "max_forks_repo_head_hexsha": "de6d688a7c4928b7afe89493b3cb8cfc25d580f1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.8071748879, "max_line_length": 184, "alphanum_fraction": 0.625419241, "include": true, "reason": "import numpy,from numpy", "num_tokens": 10968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.3242353989809524, "lm_q1q2_score": 0.19093869759126986}}
{"text": "# Radau ODE system\nfrom __future__ import division, absolute_import, print_function\n\nimport imp\n\nfrom .allimports import *\nfrom PyDSTool.Generator import ODEsystem as ODEsystem\nfrom .baseclasses import theGenSpecHelper, genDB, _pollInputs\nfrom .mixins import CompiledMixin, full_path\nfrom PyDSTool.utils import *\nfrom PyDSTool.common import *\n# for future cleanup of * imports\nfrom PyDSTool import utils\nfrom PyDSTool import common\nfrom PyDSTool.ModelSpec import QuantSpec\nfrom PyDSTool.integrator import integrator\nimport numpy as npy\n\n# Other imports\nfrom numpy import Inf, NaN, isfinite, int, int32, float, float64, \\\n    sometrue, alltrue, any, all, concatenate, transpose, array, zeros\nimport operator\nfrom copy import copy, deepcopy\n\n\nclass radau(integrator):\n    \"\"\"Radau 5 specialization of the basic integrator class.\"\"\"\n\n    def __init__(self, modname, rhs='default_name', phaseDim=0, paramDim=0,\n                 nAux=0, nEvents=0, nExtInputs=0, hasJac=0, hasJacP=0,\n                 hasMass=0, extraSpace=0, defaultBound=1e8):\n        integrator.__init__(self, rhs=rhs, phaseDim=phaseDim, paramDim=paramDim,\n                            nAux=nAux, nEvents=nEvents, nExtInputs=nExtInputs, hasJac=hasJac,\n                            hasJacP=hasJacP, hasMass=hasMass, extraSpace=extraSpace,\n                            defaultBound=defaultBound)\n        self.modname = modname\n        try:\n            self._integMod = imp.load_module(\n                modname, *imp.find_module(modname, [\"radau5_temp\"]))\n        except:\n            print(\"Error in importing compiled vector field and integrator.\")\n            print(\"Did you compile the RHS C code?\")\n            raise\n        # check module's directory\n        assert 'Integrate' in dir(self._integMod), \\\n               \"radau library does not contain Integrate()\"\n\n        self.safety = []\n        self.jacRecompute = []\n        self.newtonStop = []\n        self.stepChangeLB = []\n        self.stepChangeUB = []\n        self.stepSizeLB = []\n        self.stepSizeUB = []\n        self.hessenberg = []\n        self.maxNewton = []\n        self.newtonStart = []\n        self.index1dim = []\n        self.index2dim = []\n        self.index3dim = []\n        self.stepSizeStrategy = []\n        self.DAEstructureM1 = []\n        self.DAEstructureM2 = []\n\n        retval = self._integMod.InitBasic(self.phaseDim, self.paramDim, self.nAux,\n                                          self.nEvents, self.nExtInputs, self.hasJac,\n                                          self.hasJacP, self.hasMass, self.extraSpace)\n\n        if retval[0] != 1:\n            raise PyDSTool_InitError('Call to InitBasic failed! (radau)')\n\n        self.initBasic = True\n\n\n    def Run(self, hinit=0, hmax=1.0, checkAux=0, calcSpecTimes=0, verbose=0,\n            safety=0.9, jacRecompute=0.001, newtonStop=-1, stepChangeLB=1,\n            stepChangeUB=1.2, stepSizeLB=0.2, stepSizeUB=8.0, hessenberg=0,\n            maxNewton=7, newtonStart=0, index1dim=-1, index2dim=0, index3dim=0,\n            stepSizeStrategy=1, DAEstructureM1=0, DAEstructureM2=0, useJac=0, useMass=0):\n        if not self.initBasic:\n            raise PyDSTool_InitError('initBasic is False (radau)')\n        if not self.initEvents:\n            raise PyDSTool_InitError('initEvents is False (radau)')\n        if not self.initIntegrate:\n            raise PyDSTool_InitError('initInteg is False (radau)')\n        if not self.setParams:\n            raise PyDSTool_InitError('setParams is False (radau)')\n        if self.nExtInputs > 0 and not self.initExtInputs:\n            raise PyDSTool_InitError('initExtInputs is False (radau)')\n\n        self.setRadauParams(hinit=hinit, hmax=hmax, checkAux=checkAux,\n                            calcSpecTimes=calcSpecTimes,\n                            verbose=verbose, safety=safety,\n                            jacRecompute=jacRecompute, newtonStop=newtonStop,\n                            stepChangeLB=stepChangeLB, stepChangeUB=stepChangeUB,\n                            stepSizeLB=stepSizeLB, stepSizeUB=stepSizeUB,\n                            hessenberg=hessenberg,maxNewton=maxNewton,\n                            newtonStart=newtonStart, index1dim=index1dim,\n                            index2dim=index2dim, index3dim=index3dim,\n                            stepSizeStrategy=stepSizeStrategy,\n                            DAEstructureM1=DAEstructureM1,\n                            DAEstructureM2=DAEstructureM2,\n                            useJac=useJac,useMass=useMass)\n\n        # For a run, we want to ensure indices are set to 0\n        self.Reset()\n        T, P, A, Stats, H, Err, EvtT, EvtP = self._integMod.Integrate(self.ic,\n                                                      self.t0,\n                                                      self.hinit,\n                                                      self.hmax,\n                                                      self.safety,\n                                                      self.jacRecompute,\n                                                      self.newtonStop,\n                                                      self.stepChangeLB,\n                                                      self.stepChangeUB,\n                                                      self.stepSizeLB,\n                                                      self.stepSizeUB,\n                                                      self.hessenberg,\n                                                      self.maxNewton,\n                                                      self.newtonStart,\n                                                      self.index1dim,\n                                                      self.index2dim,\n                                                      self.index3dim,\n                                                      self.stepSizeStrategy,\n                                                      self.DAEstructureM1,\n                                                      self.DAEstructureM2,\n                                                      self.useJac,\n                                                      self.useMass,\n                                                      self.verbose,\n                                                      self.checkAux,\n                                                      self.calcSpecTimes)\n        self.points = P\n        self.times = T\n        self.auxPoints = A\n        self.eventTimes = EvtT\n        self.eventPoints = EvtP\n        self.errors = Err\n        self.stats = Stats\n        self.step = H\n\n        try:\n            self.lastTime = self.times[-1]\n            self.lastPoint = [self.points[i][-1] for i in range(self.phaseDim)]\n            self.lastStep = self.step\n        except IndexError:\n            self.lastTime = self.t0\n            self.lastPoint = self.ic\n            self.lastStep = self.hinit\n        self.numRuns += 1\n        self.canContinue = True\n\n        return T, P, A, Stats, H, Err, EvtT, EvtP\n\n\n    def Continue(self, tend, params=[], calcSpecTimes=0, verbose=0,\n                 extInputChanged=False, extInputVals=[], extInputTimes=[],\n                 bounds=[]):\n        if not self.initBasic:\n            raise PyDSTool_InitError('initBasic is False (radau)')\n        if not self.initEvents:\n            raise PyDSTool_InitError('initEvents is False (radau)')\n        if not self.initIntegrate:\n            raise PyDSTool_InitError('initInteg is False (radau)')\n        if not self.setParams:\n            raise PyDSTool_InitError('setParams is False (radau)')\n        if self.nExtInputs > 0 and not self.initExtInputs:\n            raise PyDSTool_InitError('initExtInputs is False (radau)')\n\n        if not self.canContinue:\n            raise PyDSTool_ContError('Unable to continue trajectory -- '\n                        'have you run the integrator and reset events, etc?')\n\n        self.setContParams(tend=tend, params=copy(params),\n                           calcSpecTimes=calcSpecTimes, verbose=verbose, extInputChanged=extInputChanged,\n                           extInputVals=copy(extInputVals), extInputTimes=copy(extInputTimes),\n                           bounds=copy(bounds))\n\n        # For a continue, we do not set indices to 0\n        T, P, A, Stats, H, Err, EvtT, EvtP = \\\n                self._integMod.Integrate(self.lastPoint,\n                                      self.lastTime,\n                                      self.lastStep, self.hmax,\n                                      self.safety,\n                                      self.jacRecompute,\n                                      self.newtonStop,\n                                      self.stepChangeLB,\n                                      self.stepChangeUB,\n                                      self.stepSizeLB,\n                                      self.stepSizeUB,\n                                      self.hessenberg,\n                                      self.maxNewton,\n                                      self.newtonStart,\n                                      self.index1dim,\n                                      self.index2dim,\n                                      self.index3dim,\n                                      self.stepSizeStrategy,\n                                      self.DAEstructureM1,\n                                      self.DAEstructureM2,\n                                      self.useJac,\n                                      self.useMass,\n                                      self.verbose,\n                                      self.checkAux,\n                                      self.calcSpecTimes)\n\n        self.points = P\n        self.times = T\n        self.auxPoints = A\n        self.eventTimes = EvtT\n        self.eventPoints = EvtP\n        self.errors = Err\n        self.stats = Stats\n        self.step = H\n\n        try:\n            self.lastTime = self.times[-1]\n            self.lastPoint = [self.points[i][-1] for i in range(self.phaseDim)]\n            self.lastStep = self.step\n        except IndexError:\n            self.lastTime = self.t0\n            self.lastPoint = self.ic\n            self.lastStep = self.hinit\n        self.numRuns += 1\n        self.numContinues += 1\n        self.canContinue = True\n\n        return T, P, A, Stats, H, Err, EvtT, EvtP\n\n\n    def setRadauParams(self, hinit, hmax, checkAux, calcSpecTimes,\n                       verbose, safety, jacRecompute, newtonStop,\n                       stepChangeLB, stepChangeUB, stepSizeLB, stepSizeUB,\n                       hessenberg, maxNewton, newtonStart, index1dim,\n                       index2dim, index3dim, stepSizeStrategy,\n                       DAEstructureM1, DAEstructureM2, useJac, useMass):\n        useJac = int(useJac)\n        useMass = int(useMass)\n        checkAux = int(checkAux)\n        calcSpecTimes = int(calcSpecTimes)\n        hessenberg = int(hessenberg)\n\n        if not isinstance(hinit, _num_types):\n            raise TypeError(\"hinit must be int, float\")\n\n        if not isinstance(hmax, _num_types):\n            raise TypeError(\"hmax must be int, float\")\n\n        if abs(hinit) > abs(hmax):\n            raise ValueError(\"Abs value of hinit (%g) must be less than hmax (%g)\"%(hinit,hmax))\n\n        if not isinstance(checkAux, _int_types):\n            raise TypeError(\"checkAux must be int\")\n        if checkAux not in (0,1):\n            raise TypeError(\"checkAux must be 0 or 1\")\n        if checkAux == 1 and self.nAux <= 0:\n            raise ValueError(\"checkAux cannot be 1 if nAux is 0\")\n\n        if not isinstance(verbose, _int_types):\n            raise TypeError(\"verbose must be int\")\n        if verbose not in (0,1):\n            if verbose >= 2:\n                # interpret all greater values as 1\n                verbose = 1\n            else:\n                raise TypeError(\"verbose must be 0 or 1\")\n\n        if not isinstance(calcSpecTimes, _int_types):\n            raise TypeError(\"calcSpecTimes must be int\")\n        if calcSpecTimes not in (0,1):\n            raise TypeError(\"calcSpecTimes must be 0 or 1\")\n        if calcSpecTimes == 1 and len(self.specTimes) <= 0:\n            raise ValueError(\"calcSpecTimes cannot be 1 if specTimes is empty\")\n\n        if safety < 0:\n            raise ValueError(\"safety must be non-negative\")\n        if jacRecompute <= 0.0:\n            raise ValueError(\"jacRecompute must be positive\")\n        if newtonStop < 0:\n            newtonStop = 0\n        if stepChangeLB <= 0:\n            raise ValueError(\"stepChangeLB must be positive\")\n        if stepChangeUB <= 0:\n            raise ValueError(\"stepChangeUB must be positive\")\n        if stepSizeLB <= 0:\n            raise ValueError(\"stepSizeLB must be positive\")\n        if stepSizeUB <= 0:\n            raise ValueError(\"stepSizeUB must be positive\")\n\n        if stepChangeLB > stepChangeUB:   # was >= but this allows fac1=fac2=1\n            raise ValueError(\"stepChangeLB must be less than stepChangeUB\")\n        if stepSizeLB >= stepSizeUB:\n            raise ValueError(\"stepSizeLB must be less than stepSizeUB\")\n\n        if hessenberg not in (0,1):\n            raise ValueError(\"hessenberg must be 0 or 1\")\n        if hessenberg == 1 and useMass != 0:\n            raise ValueError(\"hessenberg form cannot be used for implicit systems (mass matrix)\")\n        if not isinstance(maxNewton, _int_types):\n            raise TypeError(\"maxNewton must be int\")\n        if maxNewton <= 0:\n            raise ValueError(\"maxNewton must be positive\")\n\n        if newtonStart not in (0,1):\n            raise ValueError(\"newtonStart must be 0 or 1\")\n\n        if index1dim <= 0:\n            index1dim = self.phaseDim\n        if index2dim != 0:\n            raise ValueError(\"Currently index2dim must be 0\")\n        if index3dim != 0:\n            raise ValueError(\"Currently index3dim must be 0\")\n\n        if stepSizeStrategy not in (1,2):\n            raise ValueError(\"stepSizeStrategy must be 1 or 2\")\n\n        if DAEstructureM1 != 0:\n            raise ValueError(\"Currently DAEstructureM1 must be 0\")\n        if DAEstructureM2 != 0:\n            raise ValueError(\"Currently DAEstructureM2 must be 0\")\n\n        if useJac not in (0,1):\n            raise ValueError(\"useJac must be 0 or 1\")\n        if useMass not in (0,1):\n            raise ValueError(\"useMass must be 0 or 1\")\n\n        if useJac == 1 and self.hasJac != 1:\n            raise ValueError(\"useJac must be 0 if hasJac is not 1\")\n        if useMass == 1 and self.hasMass != 1:\n            raise ValueError(\"useMass must be 0 if hasMass is not 1\")\n\n        self.hinit = hinit\n        self.hmax = hmax\n        self.safety = safety\n        self.jacRecompute = jacRecompute\n        self.newtonStop = newtonStop\n        self.stepChangeLB = stepChangeLB\n        self.stepChangeUB = stepChangeUB\n        self.stepSizeLB = stepSizeLB\n        self.stepSizeUB = stepSizeUB\n        self.hessenberg = hessenberg\n        self.maxNewton = maxNewton\n        self.newtonStart = newtonStart\n        self.index1dim = index1dim\n        self.index2dim = index2dim\n        self.index3dim = index3dim\n        self.stepSizeStrategy = stepSizeStrategy\n        self.DAEstructureM1 = DAEstructureM1\n        self.DAEstructureM2 = DAEstructureM2\n        self.useJac = useJac\n        self.useMass = useMass\n        self.verbose = verbose\n        self.checkAux = checkAux\n        self.calcSpecTimes = calcSpecTimes\n\n\nclass Radau_ODEsystem(ODEsystem, CompiledMixin):\n    \"\"\"Wrapper for Radau integrator (with support for differential-algebraic equations).\n\n    Uses C target language only for functional specifications\"\"\"\n    _paraminfo = {'rtol': 'Relative error tolerance.',\n                  'atol': 'Absolute error tolerance.',\n                  'safety': 'Safety factor in the step size prediction, default 0.9.',\n                  'max_step': 'Maximal step size, default tend-tstart.',\n                  'init_step': 'Initial step size, default is a guess computed by the function init_step.',\n                  'fac1': 'Parameter for step size selection; the new step size is chosen subject to the restriction  fac1 <= new_step/old_step <= fac2. Default value is 1.0.',\n                  'fac2': 'Parameter for step size selection; the new step size is chosen subject to the restriction  fac1 <= new_step/old_step <= fac2. Default value is 1.2.',\n                  'stepLB': '',\n                  'stepUB': '',\n                  'refine': 'Refine output by adding points interpolated using the RK4 polynomial (0, 1 or 2).',\n                  'step_strategy': \"\"\"Switch for step size strategy;\nIf step_strategy=1  mod. predictive controller (Gustafsson).\nIf step_strategy=2  classical step size control.\nThe default value (for step_strategy=0) is step_strategy=1.\nthe choice step_strategy=1 seems to produce safer results;\nfor simple problems, the choice step_strategy=2 produces\noften slightly faster runs.\"\"\",\n                  'jac_recompute': \"\"\"Decides whether the Jacobian should be recomputed;\nincrease jac_recompute to 0.1 say, when Jacobian evaluations\nare costly. for small systems jac_recompute should be smaller\n(0.001, say). negative jac_recompute forces the code to\ncompute the Jacobian after every accepted step.\nDefault 0.001.\"\"\",\n                  'newton_start': \"\",\n                  'newton_stop': \"\",\n                  'max_newton': \"Maximum number of Newton iterations to take in solving the implicit system at each step (default 7)\",\n                  'DAEstructureM1': \"\",\n                  'DAEstructureM2': \"\",\n                  'hessenberg': \"\",\n                  'index1dim': \"\",\n                  'index2dim': \"\",\n                  'index3dim': \"\",\n                  'use_special': \"Switch for using special times\",\n                  'specialtimes': \"List of special times to use during integration\",\n                  'check_aux': \"Switch\",\n                  'extraspace': \"\"\n                  }\n\n    def __init__(self, kw):\n        \"\"\"Use the nobuild key to postpone building of the library, e.g. in\n        order to provide additional build options to makeLibSource and\n        compileLib methods or to make changes to the C code by hand.\n        No build options can be specified otherwise.\"\"\"\n\n        # delete because not covered in ODEsystem\n        nobuild = kw.pop('nobuild', False)\n        ODEsystem.__init__(self, kw)\n        self._solver = None\n        self.diagnostics._errorcodes = {\n              0: 'Unrecognized error code returned (see stderr output)',\n            -1 : 'input is not consistent',\n            -2 : 'larger nmax is needed',\n             2 : 'larger nmax or maxevtpts is probably needed (error raised by solout)',\n            -3 : 'step size becomes too small',\n            -4 : 'the matrix is repeatedly singular (interrupted)',\n            -8 : 'The solution exceeded a magbound (poor choice of initial step)'}\n        self.diagnostics.outputStatsInfo = {\n            'last_step': 'Predicted step size of the last accepted step (useful for a subsequent call to radau).',\n            'num_steps': 'Number of used steps.',\n            'num_accept': 'Number of accepted steps.',\n            'num_reject': 'Number of rejected steps.',\n            'num_fcns': 'Number of function evaluations.',\n            'num_jacs': 'Number of Jacobian evaluations.',\n            'num_dec': 'Number of LU-decompositions',\n            'num_subs': 'Number of forward-backward substitutions',\n            'errorStatus': 'Error status on completion.'\n             }\n\n        # currently the final four of these params are for event handling\n        algparams_def = {'poly_interp': False,\n                        'init_step': 0,\n                        'max_step': 0,\n                        'rtol': [1e-9 for i in range(self.dimension)],\n                        'atol': [1e-12 for i in range(self.dimension)],\n                        'fac1': 1.0,\n                        'fac2': 1.2,\n                        'stepLB': 0.2,\n                        'stepUB': 8.0,\n                        'safety': 0.9,\n                        'max_pts': 10000,\n                        'refine': 0,\n                        'maxbisect': [], # for events\n                        'maxevtpts': 1000, # for events\n                        'eventInt': [], # set using setEventInterval only\n                        'eventDelay': [], # set using setEventDelay only\n                        'eventTol': [], # set using setEventTol only\n                        'use_special': 0,\n                        'specialtimes': [],\n                        'check_aux': 1,\n                        'extraspace': 100,\n                        'verbose': 0,\n                        'jac_recompute': 0.001,\n                        'step_strategy': 1,\n                        'index1dim': -1,\n                        'index2dim': 0,\n                        'index3dim': 0,\n                        'DAEstructureM1': 0,\n                        'DAEstructureM2': 0,\n                        'hessenberg': 0,\n                        'newton_start': 0,\n                        'newton_stop': -1,\n                        'max_newton': 7,\n                        'hasJac': 0,\n                        'hasJacP': 0,\n                        'checkBounds': self.checklevel\n                        }\n        for k, v in algparams_def.items():\n            if k not in self.algparams:\n                self.algparams[k] = v\n        # verify that no additional keys are present in algparams, after\n        # defaults are added above\n        if len(self.algparams) != len(algparams_def):\n            raise ValueError(\"Invalid keys present in algparams argument: \" \\\n                     + str(remain(self.algparams.keys(),algparams_def.keys())))\n        # Check for non-constant mass matrix\n        if self.haveMass():\n            mspec = self.funcspec.auxfns['massMatrix']\n            lensig = len(mspec[1])\n            body_str = mspec[0][lensig:].replace('\\n','')\n            qbody = QuantSpec('__body__', body_str, treatMultiRefs=False,\n                              ignoreSpecial=['[',']','{','}'])\n            self._const_massmat = intersect(['Y_','t'], qbody.usedSymbols) == []\n        else:\n            self._const_massmat = True\n\n        self._prepareEventSpecs()\n        self._inputVarList = []\n        self._inputTimeList = []\n\n        if nobuild:\n            print(\"Build the library using the makeLib method, or in \")\n            print(\"stages using the makeLibSource and compileLib methods.\")\n        else:\n            self.makeLib()\n\n    @property\n    def integrator(self):\n        return {\n            'name': ('radau5' if self._const_massmat else 'radau5v', 'Radau'),\n            'description': \"Radau5 integrator\" + \\\n            \"\" if self._const_massmat else \" (version for non-constant mass matrices)\",\n            'src': [\"radau5mod.c\"],\n            'cflags': [\"-D__RADAU__\"],\n            'libs': [\n                ('radau5', {\n                    'sources': full_path(['radau5.f' if self._const_massmat else 'radau5v.f']),\n                    'extra_f77_compile_args': utils.extra_arch_arg(['-w']),\n                }),\n                ('lapack_lite', {\n                    'sources': full_path(['lapackc.f', 'lapack.f', 'dc_lapack.f']),\n                    'extra_f77_compile_args': utils.extra_arch_arg(['-w']),\n                })\n            ],\n        }\n\n    def _prepareEventSpecs(self):\n        eventActive = []\n        eventTerm = []\n        eventDir = []\n        eventDelay = []\n        eventTol = []\n        maxbisect = []\n        eventInt = []\n        # convert event specs (term, active, etc.) into integparam specs\n        self._eventNames = self.eventstruct.sortedEventNames()\n        for evname in self._eventNames:\n            ev = self.eventstruct.events[evname]\n            assert isinstance(ev, LowLevelEvent), (\"Radau can only \"\n                                                \"accept low level events\")\n        # if event 'precise' flags set to False then set their tolerances\n        # to be > max_step\n        maxstep = self.algparams['max_step']\n        for evname in self._eventNames:\n            ev = self.eventstruct.events[evname]\n            eventActive.append(int(ev.activeFlag))\n            eventTerm.append(int(ev.termFlag))\n            eventDir.append(ev.dircode)\n            eventInt.append(ev.eventinterval)\n            eventDelay.append(ev.eventdelay)\n            if ev.preciseFlag:\n                eventTol.append(ev.eventtol)\n                maxbisect.append(ev.bisectlimit)\n            else:\n                eventTol.append(maxstep*1.5)\n                maxbisect.append(1)\n        self.algparams['eventTol'] = eventTol\n        self.algparams['eventDelay'] = eventDelay\n        self.algparams['eventInt'] = eventInt\n        self.algparams['maxbisect'] = maxbisect\n        self.algparams['eventActive'] = eventActive\n        self.algparams['eventTerm'] = eventTerm\n        self.algparams['eventDir'] = eventDir\n\n    def compute(self, trajname, dirn='f', ics=None):\n        continue_integ = ODEsystem.prepDirection(self, dirn)\n        if ics is not None:\n            self.set(ics=ics)\n        self.validateICs()\n        self.diagnostics.clearWarnings()\n        self.diagnostics.clearErrors()\n        if isinstance(self.algparams['rtol'], list):\n            if len(self.algparams['rtol']) != self.dimension:\n                raise ValueError('rtol list must have same length as phase dimension')\n        else:\n            rtol = self.algparams['rtol']\n            self.algparams['rtol'] = [rtol for i in range(self.dimension)]\n        if isinstance(self.algparams['atol'], list):\n            if len(self.algparams['atol']) != self.dimension:\n                raise ValueError('atol list must have same length as phase dimension')\n        else:\n            atol = self.algparams['atol']\n            self.algparams['atol'] = [atol for i in range(self.dimension)]\n        anames = self.funcspec.auxvars\n        # Check i.c.'s are well defined (finite)\n        self.checkInitialConditions()\n        self.setEventICs(self.initialconditions, self.globalt0)\n        # update event params in case changed since last run\n        self._prepareEventSpecs()\n        # Main integration\n        t0 = self.indepvariable.depdomain[0]\n        t1 = self.indepvariable.depdomain[1]\n        plist = sortedDictValues(self.pars)\n        self.algparams['hasJac'] = self.haveJacobian()\n        self.algparams['hasJacP'] = self.haveJacobian_pars()\n        self._ensure_solver()\n        if self._dircode == 1:\n            tbegin = t0\n            tend = t1\n        elif self._dircode == -1:\n            # radau does reverse time integration simply by switching t0 and t1\n            tbegin = t1\n            tend = t0\n        if len(self.algparams['specialtimes'])>0:\n            use_special = self.algparams['use_special']\n        else:\n            use_special = 0\n        bounds = [[],[]]  # lower, then upper\n        for v in self.funcspec.vars:\n            bds = self.xdomain[v]\n            try:\n                bounds[0].append(bds[0])\n                bounds[1].append(bds[1])\n            except TypeError:\n                print(\"%r %s %r\" % (v, type(bds), bds))\n                print(self.xdomain)\n                raise\n        for p in self.funcspec.pars:\n            bds = self.pdomain[p]\n            try:\n                bounds[0].append(bds[0])\n                bounds[1].append(bds[1])\n            except TypeError:\n                print(\"%s %r\" % (type(bds), bds))\n                raise\n        if continue_integ:\n            x0 = self._solver.lastPoint\n            # overwrite t0 from self.indepvariable.domain, but use its t1\n            tbegin = self._solver.lastTime\n            if abs(self._solver.lastStep) < abs(self.algparams['init_step']):\n                self.algparams['init_step'] = self._solver.lastStep\n            if abs(t1-tbegin) < abs(self.algparams['init_step']):\n                raise ValueError(\"Integration end point too close to initial \"\n                                 \"point\")\n#            if self.inputs and self._extInputsChanged:\n#                self._extInputsChanged = False\n#                self._solver.setContParams(tend, plist,\n#                                           use_special,\n#                                           self.algparams['verbose'],\n#                                           True, deepcopy(self._inputVarList),\n#                                           deeppcopy(self._inputTimeList))\n        else:\n            if self._solver.numRuns > 0:\n                self._solver.clearAll()\n            x0 = sortedDictValues(self.initialconditions, self.funcspec.vars)\n            self._solver.setInteg(maxpts=self.algparams['max_pts'],\n                rtol=self.algparams['rtol'], atol=self.algparams['atol'])\n            self._solver.setRunParams(ic=x0, params=plist,\n                                  t0=tbegin, tend=tend, gt0=self.globalt0,\n                                  refine=self.algparams['refine'],\n                                  specTimes=self.algparams['specialtimes'],\n                                  bounds=bounds)\n        if self.inputs:\n            # self._extInputsChanged if global t0 changed so that can\n            # adjust times given to the integrator (it is blind to global t0\n            # when accesses input variable times)\n            self._ensure_inputs(self._extInputsChanged)\n        # hinit only set if not continue_integ\n        if len(anames)>0:\n            check_aux = self.algparams['check_aux']\n        else:\n            check_aux = 0\n        if self.algparams['max_step'] == 0:\n            max_step = abs(tend-tbegin)\n        else:\n            max_step = self.algparams['max_step']\n        init_step = self.algparams['init_step']\n        if self._dircode == 1:\n            if init_step < 0:\n                init_step = -init_step\n            if max_step < 0:\n                max_step = -max_step\n        else:\n            if init_step > 0:\n                init_step = -init_step\n            if max_step > 0:\n                max_step = -max_step\n        if continue_integ:\n            # record needed for bounds checking and truncation\n            old_highest_ix = self._solver.points.shape[1]\n            alltData, X, A, Stats, H, Err, Evtimes, \\\n                Evpoints = self._solver.Continue(tend, plist,\n                                  use_special, self.algparams['verbose'],\n                                  self._extInputsChanged,\n                                  deepcopy(self._inputVarList),\n                                  deepcopy(self._inputTimeList), bounds)\n        else:\n            old_highest_ix = 0\n            self._solver.setEvents(eventActive=self.algparams['eventActive'],\n                            eventTerm=self.algparams['eventTerm'],\n                            eventDir=self.algparams['eventDir'],\n                            eventDelay=self.algparams['eventDelay'],\n                            eventInt=self.algparams['eventInt'],\n                            eventTol=self.algparams['eventTol'],\n                            maxevtpts=self.algparams['maxevtpts'],\n                            maxbisect=self.algparams['maxbisect'])\n            alltData, X, A, Stats, H, Err, Evtimes, \\\n                Evpoints = self._solver.Run(init_step,\n                                    max_step,\n                                    check_aux,\n                                    use_special,\n                                    self.algparams['verbose'],\n                                    self.algparams['safety'],\n                                    self.algparams['jac_recompute'],\n                                    self.algparams['newton_stop'],\n                                    self.algparams['fac1'],\n                                    self.algparams['fac2'],\n                                    self.algparams['stepLB'],\n                                    self.algparams['stepUB'],\n                                    self.algparams['hessenberg'],\n                                    self.algparams['max_newton'],\n                                    self.algparams['newton_start'],\n                                    self.algparams['index1dim'],\n                                    self.algparams['index2dim'],\n                                    self.algparams['index3dim'],\n                                    self.algparams['step_strategy'],\n                                    self.algparams['DAEstructureM1'],\n                                    self.algparams['DAEstructureM2'],\n                                    self.haveJacobian(),\n                                    self.haveMass())\n        self._extInputsChanged = False    # reset this now\n        self.diagnostics.outputStats = {'last_step': H,\n                            'last_time': self._solver.lastTime,\n                            'last_point': self._solver.lastPoint,\n                            'num_fcns': Stats[0],\n                            'num_jacs': Stats[1],\n                            'num_steps': Stats[2],\n                            'num_accept': Stats[3],\n                            'num_reject': Stats[4],\n                            'num_dec': Stats[5],\n                            'num_subs': Stats[6],\n                            'errorStatus': Err\n                            }\n        if self._dircode == -1:\n            # reverse the array object (no reverse method!)\n            alltData = alltData[::-1]\n            X = X[:,::-1]\n            if anames != []:\n                A = A[:,::-1]\n        xnames = self._var_ixmap\n        # Package up computed trajectory in Variable variables\n        # Add external inputs warnings to self.diagnostics.warnings, if any\n##        for f in inputVarList:\n##            for winfo in f.diagnostics.warnings:\n##                self.diagnostics.warnings.append((W_NONTERMSTATEBD,\n##                                     (winfo[0], f.name, winfo[1],\n##                                      f.depdomain)))\n        eventslist = self.eventstruct.query(['lowlevel', 'active'])\n        termevents = self.eventstruct.query(['term'], eventslist)\n        if self._eventNames != []:\n            # build self.diagnostics.warnings because events happened --\n            # and keep a record of which times terminal events happened because\n            # Model.py's event handling procedure assumes multiple events\n            # happening at one time are listed in one warning\n            termevtimes = {}\n            nontermevtimes = {}\n            try:\n                for evix in range(len(self._eventNames)):\n                    if Evpoints[evix] is None:\n                        continue\n                    evname = self._eventNames[evix]\n                    numevs = len(Evtimes[evix])\n                    if self.algparams['eventTerm'][evix]:\n                        if numevs > 1:\n                            print(\"Event info: %r %r\" % (Evpoints, Evtimes))\n                        assert numevs <= 1, (\"Internal error: more than one \"\n                                         \"terminal event of same type found\")\n                        # For safety, we should assert that this event\n                        # also appears in termevents, but we don't\n                        if Evtimes[evix][0] in termevtimes.keys():\n                            # append event name to this warning\n                            warning_ix = termevtimes[Evtimes[evix][0]]\n                            self.diagnostics.warnings[warning_ix][1][1].append(evname)\n                        else:\n                            # make new termevtime entry for the new warning\n                            termevtimes[Evtimes[evix][0]] = \\\n                                       len(self.diagnostics.warnings)\n                            self.diagnostics.warnings.append((W_TERMEVENT,\n                                             (Evtimes[evix][0],\n                                             [evname])))\n                    else:\n                        for ev in range(numevs):\n                            if Evtimes[evix][ev] in nontermevtimes.keys():\n                                # append event name to this warning\n                                warning_ix = nontermevtimes[Evtimes[evix][ev]]\n                                self.diagnostics.warnings[warning_ix][1][1].append(evname)\n                            else:\n                                # make new nontermevtime entry for the new warning\n                                nontermevtimes[Evtimes[evix][ev]] = \\\n                                                    len(self.diagnostics.warnings)\n                                self.diagnostics.warnings.append((W_NONTERMEVENT,\n                                                 (Evtimes[evix][ev],\n                                                  [evname])))\n            except IndexError:\n                print(\"Events returned from integrator are the wrong size.\")\n                print(\"  Did you change the system and not refresh the C \" \\\n                      + \"library using the forcelibrefresh() method?\")\n                raise\n        termcount = 0\n        for (w,i) in self.diagnostics.warnings:\n            if w == W_TERMEVENT or w == W_TERMSTATEBD:\n                if termcount > 0:\n                    raise ValueError(\"Internal error: more than one terminal \"\n                                     \"event found\")\n                termcount += 1\n        # post-process check of variable bounds (if defined and algparams['checkBounds'] True)\n        if self._dircode > 0:\n            compare = operator.lt\n            last_ix = Inf\n        else:\n            compare = operator.gt\n            last_ix = -Inf\n        highest_ix = X.shape[1]-1\n        last_t = Inf\n        if self.algparams['checkBounds'] > 0:\n            # temp storage for repeatedly used object attributes (for lookup efficiency)\n            depdomains = dict(zip(range(self.dimension),\n                                  [self.variables[xn].depdomain for xn in xnames]))\n            offender_ix = None\n            for xi in range(self.dimension):\n                if not any(depdomains[xi].isfinite()):\n                    # no point in checking when the bounds are +/- infinity\n                    continue\n                next_last_ix = array_bounds_check(X[xi][old_highest_ix:],\n                                    depdomains[xi], self._dircode) + old_highest_ix\n                if compare(next_last_ix, last_ix):\n                    # won't count as truncating unless the following checks\n                    # hold\n                    last_ix = next_last_ix\n                    offender_ix = xi\n            if not isfinite(last_ix) and last_ix < 0:\n                # only use +Inf hereon to flag no truncation needed\n                last_ix = Inf\n            elif last_ix >= 0 and last_ix < highest_ix:\n                # truncate data\n                last_t = alltData[last_ix]\n                print(\"Warning; domain bound reached (because algparams['checkBounds'] > 0)\")\n                self.diagnostics.warnings.append((W_TERMSTATEBD,\n                                    (last_t, xnames[offender_ix],\n                                     X[offender_ix, last_ix],\n                                     depdomains[offender_ix].get())))\n        # Create variables (self.variables contains no actual data)\n        variables = copyVarDict(self.variables)\n        # build event pointset information (reset previous trajectory's)\n        # don't include events after any truncation due to state bound violation\n        self.trajevents = {}\n        for evix in range(len(self._eventNames)):\n            evname = self._eventNames[evix]\n            if Evpoints[evix] is None:\n                self.trajevents[evname] = None\n            else:\n                try:\n                    ev_a_list = []\n                    for t in Evtimes[evix]:\n                        tix = find(alltData, t)\n                        ev_a_list.append(A[:,tix])\n                    ev_array = concatenate((Evpoints[evix],\n                                         transpose(array(ev_a_list, 'd'))))\n                    del ev_a_list, tix\n                except TypeError:\n                    # A is empty\n                    ev_array = Evpoints[evix]\n                if last_ix >= 0 and last_ix < highest_ix:\n                    # don't count last_ix = -1 which is the same as highest_ix\n                    last_ev_tix = npy.argmax(Evtimes[evix] >= alltData[last_ix])\n                    if last_ev_tix == 0 and Evtimes[evix][0] >= last_t:\n                        # checks that there was actually a violation\n                        # - so no events to record\n                        self.trajevents[evname] = None\n                    else:\n                        # truncation needed\n                        ev_array = ev_array[:, :last_ev_tix+1]\n                        ev_times = Evtimes[evix][:last_ev_tix+1]\n                        self.trajevents[evname] = Pointset({'coordnames': xnames+anames,\n                                               'indepvarname': 't',\n                                               'coordarray': ev_array,\n                                               'indepvararray': ev_times})\n                else:\n                    # no truncation needed\n                    self.trajevents[evname] = Pointset({'coordnames': xnames+anames,\n                                               'indepvarname': 't',\n                                               'coordarray': ev_array,\n                                               'indepvararray': Evtimes[evix]})\n        if last_ix >= 0 and last_ix < highest_ix:\n            # truncate\n            X = X[:, :last_ix]\n            alltData = alltData[:last_ix]\n        try:\n            allxDataDict = dict(zip(xnames,X))\n        except IndexError:\n            print(\"Integration returned variable values of unexpected dimensions.\")\n            print(\"  Did you change the system and not refresh the C library\" \\\n                  + \" using the forcelibrefresh() method?\")\n            raise\n        # storage of all auxiliary variable data\n        anames = self.funcspec.auxvars\n        try:\n            if anames != []:\n                if last_ix < highest_ix:\n                    A = A[:, :last_ix]\n                try:\n                    allaDataDict = dict(zip(anames,A))\n                except TypeError:\n                    print(\"Internal error!  Type of A: %s\" % type(A))\n                    raise\n        except IndexError:\n            print(\"Integration returned auxiliary values of unexpected dimensions.\")\n            print(\"  Did you change the system and not refresh the C library\" \\\n                  + \" using the forcelibrefresh() method?\")\n            raise\n        if int(Err) == 1 or (int(Err) == 2 and termcount == 1):\n            # output OK\n            if self.algparams['poly_interp']:\n                rhsfn = self._solver.Rhs\n                # when Dopri can output the Rhs values alongside variable\n                # values then this won't be necessary\n                dxvals = zeros((len(alltData),self.dimension),float)\n                for tix, tval in enumerate(alltData):\n                    # solver's Rhs function already contains the inputs so no\n                    # need to recompute and provide here.\n                    #i = _pollInputs(sortedDictValues(self.inputs), tval,\n                    #                        self.checklevel)\n                    # X is the output variable array, but rhsfn demands a list\n                    dxvals[tix] = rhsfn(tval, list(X[:,tix]), plist)[0]\n            for xi, x in enumerate(xnames):\n                if len(alltData) > 1:\n                    if self.algparams['poly_interp']:\n                        interp = PiecewisePolynomial(alltData,\n                                    array([allxDataDict[x], dxvals[:,xi]]).T, 2)\n                    else:\n                        interp = interp1d(alltData, allxDataDict[x])\n                    variables[x] = Variable(interp, 't', x, x)\n                else:\n                    raise PyDSTool_ValueError(\"Fewer than 2 data points computed\")\n            for a in anames:\n                if len(alltData) > 1:\n                    variables[a] = Variable(interp1d(alltData,allaDataDict[a]),\n                                             't', a, a)\n                else:\n                    raise PyDSTool_ValueError(\"Fewer than 2 data points computed\")\n            # final checks\n            #self.validateSpec()\n            self.defined = True\n            return Trajectory(trajname, list(variables.values()),\n                              abseps=self._abseps, globalt0=self.globalt0,\n                              checklevel=self.checklevel,\n                              FScompatibleNames=self._FScompatibleNames,\n                              FScompatibleNamesInv=self._FScompatibleNamesInv,\n                              events=self.trajevents,\n                              modelNames=self.name,\n                              modelEventStructs=self.eventstruct)\n        else:\n            try:\n                diagnost_info = self.diagnostics._errorcodes[int(Err)]\n            except TypeError:\n                # errcode messed up from Radau\n                print(\"Error code: %d\" % Err)\n                diagnost_info = self.diagnostics._errorcodes[0]\n            if self._solver.verbose:\n                info(self.diagnostics.outputStats, \"Output statistics\")\n            self.defined = False\n            # Did the solver run out of memory?\n            if (len(alltData) == self.algparams['max_pts'] or \\\n                self.diagnostics.outputStats['num_steps'] >= self.algparams['max_pts']) \\\n                   and alltData[-1] < tend:\n                print(\"max_pts algorithmic parameter too small: current \" + \\\n                      \"value is %i\"%self.algparams['max_pts'])\n#                avstep = (self.algparams['init_step']+self.diagnostics.outputStats['last_step'])/2.\n                if self.diagnostics.outputStats['last_time']-tbegin > 0:\n                    ms = str(int(round(self.algparams['max_pts'] / \\\n                              (self.diagnostics.outputStats['last_time'] - \\\n                               tbegin)*(tend-tbegin))))\n                else:\n                    ms = 'Inf'\n                print(\"(recommended value for this trajectory segment is \" + \\\n                      \"estimated to be %s (saved in diagnostics.errors attribute))\"%str(ms))\n                diagnost_info += \" -- recommended value is \" + ms\n            self.diagnostics.errors.append((E_COMPUTFAIL,\n                                    (self._solver.lastTime, diagnost_info)))\n            raise PyDSTool_ExistError(\"No trajectory created\")\n\n\n    def Rhs(self, t, xdict, pdict=None, asarray=True):\n        \"\"\"asarray is an unused, dummy argument for compatibility with Model.Rhs\"\"\"\n        # must convert names to FS-compatible as '.' sorts before letters\n        # while '_' sorts after!\n        x = sortedDictValues(filteredDict(self._FScompatibleNames(xdict),\n                                          self.funcspec.vars))\n        if pdict is None:\n            pdict = self.pars\n            # internal self.pars already is FS-compatible\n            p = sortedDictValues(pdict)\n        else:\n            p = sortedDictValues(self._FScompatibleNames(pdict))\n        i = _pollInputs(sortedDictValues(self.inputs),\n                        t, self.checklevel)\n        self._ensure_solver({'params': p, 't0': 0, 'tend': 1})\n        self._ensure_inputs()\n        return self._solver.Rhs(t, x, p+i)[0]\n\n\n    def Jacobian(self, t, xdict, pdict=None, asarray=True):\n        \"\"\"asarray is an unused, dummy argument for compatibility with\n        Model.Jacobian\"\"\"\n        if self.haveJacobian():\n            x = sortedDictValues(filteredDict(self._FScompatibleNames(xdict),\n                                              self.funcspec.vars))\n            if pdict is None:\n                pdict = self.pars\n                # internal self.pars already is FS-compatible\n                p = sortedDictValues(pdict)\n            else:\n                p = sortedDictValues(self._FScompatibleNames(pdict))\n            i = _pollInputs(sortedDictValues(self.inputs),\n                            t, self.checklevel)\n            self._ensure_solver({'params': p, 't0': 0, 'tend': 1})\n            self._ensure_inputs()\n            return self._solver.Jacobian(t, x, p+i)[0]\n        else:\n            raise PyDSTool_ExistError(\"Jacobian not defined\")\n\n\n    def JacobianP(self, t, xdict, pdict=None, asarray=True):\n        \"\"\"asarray is an unused, dummy argument for compatibility with\n        Model.JacobianP\"\"\"\n        if self.haveJacobian_pars():\n            x = sortedDictValues(filteredDict(self._FScompatibleNames(xdict),\n                                              self.funcspec.vars))\n            if pdict is None:\n                pdict = self.pars\n                # internal self.pars already is FS-compatible\n                p = sortedDictValues(pdict)\n            else:\n                p = sortedDictValues(self._FScompatibleNames(pdict))\n            i = _pollInputs(sortedDictValues(self.inputs),\n                            t, self.checklevel)\n            self._ensure_solver({'params': p, 't0': 0, 'tend': 1})\n            self._ensure_inputs()\n            return self._solver.JacobianP(t, x, p+i)[0]\n        else:\n            raise PyDSTool_ExistError(\"Jacobian w.r.t. parameters not defined\")\n\n\n    def AuxVars(self, t, xdict, pdict=None, asarray=True):\n        \"\"\"asarray is an unused, dummy argument for compatibility with\n        Model.AuxVars\"\"\"\n        x = sortedDictValues(filteredDict(self._FScompatibleNames(xdict),\n                                          self.funcspec.vars))\n        if pdict is None:\n            pdict = self.pars\n            # internal self.pars already is FS-compatible\n            p = sortedDictValues(pdict)\n        else:\n            p = sortedDictValues(self._FScompatibleNames(pdict))\n        i = _pollInputs(sortedDictValues(self.inputs),\n                        t, self.checklevel)\n        self._ensure_solver({'params': p, 't0': 0, 'tend': 1})\n        self._ensure_inputs()\n        return self._solver.AuxFunc(t, x, p+i)[0]\n\n\n    def MassMatrix(self, t, xdict, pdict=None, asarray=True):\n        \"\"\"asarray is an unused, dummy argument for compatibility with\n        Model.MassMatrix\"\"\"\n        if self.haveMass():\n            x = sortedDictValues(filteredDict(self._FScompatibleNames(xdict),\n                                              self.funcspec.vars))\n            if pdict is None:\n                pdict = self.pars\n                # internal self.pars already is FS-compatible\n                p = sortedDictValues(pdict)\n            else:\n                p = sortedDictValues(self._FScompatibleNames(pdict))\n            i = _pollInputs(sortedDictValues(self.inputs),\n                            t, self.checklevel)\n            self._ensure_solver({'params': p, 't0': 0, 'tend': 1})\n            self._ensure_inputs()\n            return self._solver.MassMatrix(t, x, p+i)[0]\n        else:\n            raise PyDSTool_ExistError(\"Mass matrix not defined\")\n\n\n    def _ensure_solver(self, pars=None):\n        if self._solver is None:\n            x0 = sortedDictValues(filteredDict(self.initialconditions, self.funcspec.vars))\n#            _integMod = self._ensureLoaded(self.modname)\n            self._solver = radau(self.modname,\n                                 rhs=self.name, phaseDim=self.dimension,\n                                 paramDim=self.numpars,\n                                 nAux=len(self.funcspec.auxvars),\n                                 nEvents=len(self._eventNames),\n                                 nExtInputs=len(self.inputs),\n                                 hasJac=self.haveJacobian(),\n                                 hasJacP=self.haveJacobian_pars(),\n                                 hasMass=self.haveMass(),\n                                 extraSpace=self.algparams['extraspace'])\n            try:\n                genDB.register(self)\n            except PyDSTool_KeyError:\n                errstr = \"Generator \" + self.name + \": this vector field's \" +\\\n                         \"DLL is already in use\"\n                raise RuntimeError(errstr)\n            if pars is not None:\n                # tend value doesn't matter\n                self._solver.setRunParams(\n                              ic=sortedDictValues(filteredDict(self.initialconditions,\n                                                               self.funcspec.vars)),\n                              params=pars['params'],\n                              t0=pars['t0'], tend=pars['tend'],\n                              gt0=self.globalt0,\n                              refine=0, specTimes=[])\n\n    def _ensure_inputs(self, force=False):\n        if not self.inputs:\n            return\n        if force:\n            listOK = False\n        else:\n            try:\n                listOK = self._inputTimest0 == self.globalt0\n            except AttributeError:\n                # not yet defined, so proceed\n                listOK = False\n        if not listOK:\n            self._inputVarList = []\n            self._inputTimeList = []\n            self._inputTimest0 = self.globalt0\n            # inputVarList is a list of Variables or Pointsets\n            for inp in sortedDictValues(self.inputs):\n                if isinstance(inp, Variable):\n                    pts = inp.getDataPoints()\n                    if pts is None:\n                        raise TypeError(\"Can only pass external input Variable objects if based on\"\n                                        \" an underlying mesh\")\n                    else:\n                        tvals = copy(pts[inp.indepvarname])\n                        tvals -= self.globalt0\n                    self._inputVarList.append(pts[inp.coordname].tolist())\n                    self._inputTimeList.append(tvals.tolist())\n                elif isinstance(inp, Pointset):\n                    tvals = copy(inp.indepvararray)\n                    tvals -= self.globalt0\n                    self._inputVarList.append(inp[inp.coordname].tolist())\n                    self._inputTimeList.append(tvals.tolist())\n                else:\n                    raise TypeError(\"Invalid type of input\")\n        if not self._solver.initExtInputs:\n            self._solver.setExtInputs(True, deepcopy(self._inputVarList),\n                                        deepcopy(self._inputTimeList))\n        elif not listOK:\n            self._solver.clearExtInputs()\n            self._solver.setExtInputs(True, deepcopy(self._inputVarList),\n                                    deepcopy(self._inputTimeList))\n            self._solver.canContinue=True\n\n\n    def __del__(self):\n        genDB.unregister(self)\n        ODEsystem.__del__(self)\n\n\n\n# Register this Generator with the database\n\nsymbolMapDict = {'abs': 'fabs', 'sign': 'signum', 'mod': 'fmod'}\n# in future, provide appropriate mappings for libraries math,\n# random, etc. (for now it's left to FuncSpec)\ntheGenSpecHelper.add(Radau_ODEsystem, symbolMapDict, 'c')\n", "meta": {"hexsha": "4f2d91bd498bab45830c07a60ea7863b59e2a2a7", "size": 55116, "ext": "py", "lang": "Python", "max_stars_repo_path": "PyDSTool/Generator/Radau_ODEsystem.py", "max_stars_repo_name": "mdlama/pydstool", "max_stars_repo_head_hexsha": "3d298e908ff55340cd3612078508be0c791f63a8", "max_stars_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-04T15:01:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-25T16:08:43.000Z", "max_issues_repo_path": "PyDSTool/Generator/Radau_ODEsystem.py", "max_issues_repo_name": "mdlama/pydstool", "max_issues_repo_head_hexsha": "3d298e908ff55340cd3612078508be0c791f63a8", "max_issues_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PyDSTool/Generator/Radau_ODEsystem.py", "max_forks_repo_name": "mdlama/pydstool", "max_forks_repo_head_hexsha": "3d298e908ff55340cd3612078508be0c791f63a8", "max_forks_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-25T14:43:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-25T14:43:36.000Z", "avg_line_length": 47.678200692, "max_line_length": 176, "alphanum_fraction": 0.5091806372, "include": true, "reason": "import numpy,from numpy", "num_tokens": 11686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.190897607697573}}
{"text": "\"\"\" Starting point for DEM retrieval utilities.\n\"\"\"\nfrom math import pi, sin, cos\nfrom os import unlink, close\nfrom itertools import product\nfrom tempfile import mkstemp\nfrom sys import modules\n\nimport NED10m, NED100m, NED1km, SRTM1, SRTM3, VFP, Worldwide\n\nfrom ModestMaps.Core import Coordinate\nfrom TileStache.Geography import SphericalMercator\nfrom TileStache.Core import Layer, Metatile\nfrom TileStache.Config import Configuration\nfrom TileStache.Caches import Disk\n\nfrom osgeo import gdal, osr\nfrom PIL import Image\nimport numpy\n\nfrom .. import save_slope_aspect\n\n# used to prevent clobbering in /vsimem/, see:\n# http://osgeo-org.1803224.n2.nabble.com/gdal-dev-Outputting-to-vsimem-td6221295.html\nvsimem_counter = 1\n\n#\n# Set up some useful projections.\n#\n\nosr.UseExceptions() # <-- otherwise errors will be silent and useless.\n\nwebmerc_proj = SphericalMercator()\nwebmerc_sref = osr.SpatialReference()\nwebmerc_sref.ImportFromProj4(webmerc_proj.srs)\n\nclass SeedingLayer (Layer):\n    \"\"\" Tilestache-compatible seeding layer for preparing tiled data.\n    \n        Intended for use in hillup-seed.py script for preparing a tile directory.\n    \"\"\"\n    def __init__(self, demdir, tiledir, tmpdir, source, size):\n        \"\"\"\n        \"\"\"\n        cache = Disk(tiledir, dirs='safe')\n        config = Configuration(cache, '.')\n        Layer.__init__(self, config, SphericalMercator(), Metatile(), tile_height=size)\n        \n        self.provider = Provider(self, demdir, tmpdir, source)\n\n    def name(self):\n        return '.'\n\nclass Provider:\n    \"\"\" TileStache provider for generating tiles of DEM slope and aspect data.\n    \n        Source parameter can be \"srtm-ned\" (default) or \"ned-only\".\n\n        See http://tilestache.org/doc/#custom-providers for information\n        on how the Provider object interacts with TileStache.\n    \"\"\"\n    def __init__(self, layer, demdir, tmpdir=None, source='srtm-ned'):\n        self.tmpdir = tmpdir\n        self.demdir = demdir\n        self.source = source\n    \n    def getTypeByExtension(self, ext):\n        if ext.lower() != 'tiff':\n            raise Exception()\n        \n        return 'image/tiff', 'TIFF'\n    \n    def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom):\n        \"\"\" Return an instance of SlopeAndAspect for requested area.\n        \"\"\"\n        assert srs == webmerc_proj.srs # <-- good enough for now\n        \n        if self.source == 'srtm-ned':\n            providers = choose_providers_srtm(zoom)\n        \n        elif self.source == 'ned-only':\n            providers = choose_providers_ned(zoom)\n\n        elif self.source == 'vfp':\n            providers = [(VFP, 1)]\n\n        elif self.source == 'worldwide':\n            providers = [(Worldwide, 1)]\n\n        else:\n            providers = load_func_path(self.source)(zoom)\n        \n        assert sum([proportion for (mod, proportion) in providers]) == 1.0\n        \n        #\n        # Prepare information for datasets of the desired extent and projection.\n        #\n        \n        xres = (xmax - xmin) / width\n        yres = (ymin - ymax) / height\n\n        area_wkt = webmerc_sref.ExportToWkt()\n        buffered_xform = xmin - xres, xres, 0, ymax - yres, 0, yres\n        \n        #\n        # Reproject and merge DEM datasources into destination datasets.\n        #\n        \n        driver = gdal.GetDriverByName('GTiff')\n        \n        composite_ds = make_empty_datasource(width+2, height+2, buffered_xform, area_wkt, self.tmpdir)\n        proportion_complete = 0.\n\n        for (module, proportion) in providers:\n        \n            cs2cs = osr.CoordinateTransformation(webmerc_sref, module.sref)\n            \n            # get a lat/lon bbox buffered by one pixel on all sides\n            minlon, minlat, z = cs2cs.TransformPoint(xmin - xres, ymin + yres)\n            maxlon, maxlat, z = cs2cs.TransformPoint(xmax + xres, ymax - yres)\n            \n            #\n            # Keep a version of the composite without the\n            # current layer applied for later alpha-blending.\n            #\n            do_blending = bool(proportion_complete > 0 and proportion < 1)\n            \n            if do_blending:\n                composite_without = composite_ds.ReadAsArray()\n            \n            ds_args = minlon, minlat, maxlon, maxlat, self.demdir\n            \n            for ds_dem in module.datasources(*ds_args):\n            \n                # estimate the raster density across source DEM and output\n                dem_samples = (maxlon - minlon) / ds_dem.GetGeoTransform()[1]\n                area_pixels = (xmax - xmin) / composite_ds.GetGeoTransform()[1]\n                \n                if dem_samples > area_pixels:\n                    # cubic looks better squeezing down\n                    resample = gdal.GRA_Cubic\n                else:\n                    # cubic spline looks better stretching out\n                    resample = gdal.GRA_CubicSpline\n\n                gdal.ReprojectImage(ds_dem, composite_ds, ds_dem.GetProjection(), composite_ds.GetProjection(), resample)\n                ds_dem = None\n            \n            #\n            # Perform alpha-blending if needed.\n            #\n            if do_blending:\n                proportion_with = proportion / (proportion_complete + proportion)\n                proportion_without = 1 - proportion_with\n                \n                composite_with = composite_ds.ReadAsArray() * proportion_with\n                composite_with += composite_without * proportion_without\n\n                composite_ds.GetRasterBand(1).WriteArray(composite_with, 0, 0)\n            \n            proportion_complete += proportion\n                \n        elevation = composite_ds.ReadAsArray()\n\n        unlink(composite_ds.GetFileList()[0])\n        composite_ds = None\n        \n        #\n        # Calculate and save slope and aspect.\n        #\n        \n        slope, aspect = calculate_slope_aspect(elevation, xres, yres)\n\n        tile_xform = xmin, xres, 0, ymax, 0, yres\n        \n        return SlopeAndAspect(self.tmpdir, slope, aspect, area_wkt, tile_xform)\n\nclass SlopeAndAspect:\n    \"\"\" TileStache response object with PIL-like save() and crop() methods.\n    \n        This object knows only how to save two-band 8-bit GeoTIFFs.\n        \n        See http://tilestache.org/doc/#custom-providers for information\n        on how the SlopeAndAspect object interacts with TileStache.\n    \"\"\"\n    def __init__(self, tmpdir, slope, aspect, wkt, xform):\n        \"\"\" Instantiate with array of slope and aspect, and minimal geographic information.\n        \"\"\"\n        self.tmpdir = tmpdir\n        \n        self.slope = slope\n        self.aspect = aspect\n        \n        self.w, self.h = self.slope.shape\n\n        self.wkt = wkt\n        self.xform = xform\n    \n    def save(self, output, format):\n        \"\"\" Save a two-band GeoTIFF to output file-like object.\n        \"\"\"\n        if format != 'TIFF':\n            raise Exception('File format other than TIFF for slope and aspect: \"%s\"' % format)\n        \n        save_slope_aspect(self.slope, self.aspect, self.wkt, self.xform, output, self.tmpdir)\n    \n    def crop(self, box):\n        \"\"\" Returns a rectangular region from the current image.\n        \n            Box is a 4-tuple with left, upper, right, and lower pixels.\n            Not yet implemented!\n        \"\"\"\n        raise NotImplementedError()\n\ndef choose_providers_srtm(zoom):\n    \"\"\" Return a list of data sources and proportions for given zoom level.\n        \n        Each data source is a module such as SRTM1 or SRTM3, and the proportions\n        must all add up to one. Return list has either one or two items.\n    \"\"\"\n    if zoom <= SRTM3.ideal_zoom:\n        return [(SRTM3, 1)]\n\n    elif SRTM3.ideal_zoom < zoom and zoom < SRTM1.ideal_zoom:\n        #bottom, top = SRTM3, SRTM1 # SRTM1 looks terrible\n        bottom, top = SRTM3, NED10m\n\n    elif zoom == SRTM1.ideal_zoom:\n        #return [(SRTM1, 1)] # SRTM1 looks terrible\n        bottom, top = SRTM3, NED10m\n\n    elif SRTM1.ideal_zoom < zoom and zoom < NED10m.ideal_zoom:\n        #bottom, top = SRTM1, NED10m # SRTM1 looks terrible\n        bottom, top = SRTM3, NED10m\n\n    elif zoom >= NED10m.ideal_zoom:\n        return [(NED10m, 1)]\n\n    difference = float(top.ideal_zoom) - float(bottom.ideal_zoom)\n    proportion = 1. - (zoom - float(bottom.ideal_zoom)) / difference\n\n    return [(bottom, proportion), (top, 1 - proportion)]\n\ndef choose_providers_ned(zoom):\n    \"\"\" Return a list of data sources and proportions for given zoom level.\n    \n        Each data source is a module such as NED10m or NED1km, and the proportions\n        must all add up to one. Return list has either one or two items.\n    \"\"\"\n    if zoom <= NED1km.ideal_zoom:\n        return [(NED1km, 1)]\n\n    elif NED1km.ideal_zoom < zoom and zoom < NED100m.ideal_zoom:\n        #bottom, top = NED1km, NED100m\n        bottom, top = NED1km, NED100m\n\n    elif zoom == NED100m.ideal_zoom:\n        return [(NED100m, 1)]\n\n    elif NED100m.ideal_zoom < zoom and zoom < NED10m.ideal_zoom:\n        #bottom, top = NED100m, NED10m\n        bottom, top = NED100m, NED10m\n\n    elif zoom >= NED10m.ideal_zoom:\n        return [(NED10m, 1)]\n\n    difference = float(top.ideal_zoom) - float(bottom.ideal_zoom)\n    proportion = 1. - (zoom - float(bottom.ideal_zoom)) / difference\n\n    return [(bottom, proportion), (top, 1 - proportion)]\n\ndef make_empty_datasource(width, height, xform, wkt, tmpdir):\n    '''\n    '''\n    driver = gdal.GetDriverByName('GTiff')\n    handle, filename = mkstemp(dir=tmpdir, prefix='dem-tools-hillup-data-render-', suffix='.tif')\n    close(handle)\n\n    ds = driver.Create(filename, width, height, 1, gdal.GDT_Float32)\n    ds.SetGeoTransform(xform)\n    ds.SetProjection(wkt)\n    \n    ds.GetRasterBand(1).WriteArray(numpy.ones((width, height), numpy.float32) * -9999, 0, 0)\n    ds.GetRasterBand(1).SetNoDataValue(-9999)\n    \n    return ds\n\ndef calculate_slope_aspect(elevation, xres, yres, z=1.0):\n    \"\"\" Return a pair of arrays 2 pixels smaller than the input elevation array.\n    \n        Slope is returned in radians, from 0 for sheer face to pi/2 for\n        flat ground. Aspect is returned in radians, counterclockwise from -pi\n        at north around to pi.\n        \n        Logic here is borrowed from hillshade.cpp:\n          http://www.perrygeo.net/wordpress/?p=7\n    \"\"\"\n    width, height = elevation.shape[0] - 2, elevation.shape[1] - 2\n    \n    window = [z * elevation[row:(row + height), col:(col + width)]\n              for (row, col)\n              in product(range(3), range(3))]\n    \n    x = ((window[0] + window[3] + window[3] + window[6]) \\\n       - (window[2] + window[5] + window[5] + window[8])) \\\n      / (8.0 * xres);\n    \n    y = ((window[6] + window[7] + window[7] + window[8]) \\\n       - (window[0] + window[1] + window[1] + window[2])) \\\n      / (8.0 * yres);\n\n    # in radians, from 0 to pi/2\n    slope = pi/2 - numpy.arctan(numpy.sqrt(x*x + y*y))\n    \n    # in radians counterclockwise, from -pi at north back to pi\n    aspect = numpy.arctan2(x, y)\n    \n    return slope, aspect\n\ndef load_func_path(funcpath):\n    \"\"\" Load external function based on a path.\n        \n        Example funcpath: \"Module.Submodule:Function\".\n    \"\"\"\n    modname, objname = funcpath.split(':', 1)\n\n    __import__(modname)\n    module = modules[modname]\n    _func = eval(objname, module.__dict__)\n    \n    if _func is None:\n        raise Exception('eval(%(objname)s) in %(modname)s came up None' % locals())\n\n    return _func\n", "meta": {"hexsha": "6e15a0914d68c0d6c9d36849ccdb771ea1ea077d", "size": 11459, "ext": "py", "lang": "Python", "max_stars_repo_path": "Hillup/data/__init__.py", "max_stars_repo_name": "migurski/DEM-Tools", "max_stars_repo_head_hexsha": "5462f35f3ec1fec6fbe8288019a3af92d53ac310", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2015-01-17T19:03:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T15:25:16.000Z", "max_issues_repo_path": "Hillup/data/__init__.py", "max_issues_repo_name": "migurski/DEM-Tools", "max_issues_repo_head_hexsha": "5462f35f3ec1fec6fbe8288019a3af92d53ac310", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Hillup/data/__init__.py", "max_forks_repo_name": "migurski/DEM-Tools", "max_forks_repo_head_hexsha": "5462f35f3ec1fec6fbe8288019a3af92d53ac310", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2015-05-18T18:57:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-10T10:08:48.000Z", "avg_line_length": 34.2059701493, "max_line_length": 121, "alphanum_fraction": 0.6109608168, "include": true, "reason": "import numpy", "num_tokens": 2925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.19089760600819367}}
{"text": "#!/usr/bin/env python\n\"\"\"Random sequences and random evolution of sequences in a tree\"\"\"\n\nimport bisect\n\nimport numpy\n\n\n__author__ = \"Peter Maxwell\"\n__copyright__ = \"Copyright 2007-2020, The Cogent Project\"\n__credits__ = [\"Peter Maxwell\"]\n__license__ = \"BSD-3\"\n__version__ = \"2020.6.30a\"\n__maintainer__ = \"Peter Maxwell\"\n__email__ = \"pm67nz@gmail.com\"\n__status__ = \"Production\"\n\n\ndef argpicks(freqs, random_series):\n    partition = numpy.add.accumulate(freqs)\n    assert abs(partition[-1] - 1.0) < 1e-6, (freqs, partition)\n    while True:\n        x = random_series.uniform(0.0, 1.0)\n        i = bisect.bisect_left(partition, x)\n        yield i\n\n\ndef argpick(freqs, random_series):\n    return next(argpicks(freqs, random_series))\n\n\ndef _randomMotifGenerator(random_series, motif_probs):\n    motifs = list(motif_probs.keys())\n    freqs = [motif_probs[m] for m in motifs]\n    for i in argpicks(freqs, random_series):\n        yield motifs[i]\n\n\ndef evolve_sequence(\n    random_series, motifs, parent_seq, site_cats, psubs, preserved_sites=()\n):\n    \"\"\"Evolve a new sequence derived from parent_seq.  Uses psubs[site_cats[i]]\n    to pick a new motif derived from parent_seq[i]\"\"\"\n    seq = []\n    randomMotifSources = {}\n    for (i, parent_motif) in enumerate(parent_seq):\n        if i in preserved_sites:\n            edge_motif = preserved_sites[i]\n        else:\n            if parent_motif not in randomMotifSources:\n                mprobs = {}\n                parent_motif_index = motifs.index(parent_motif)\n                site_cat = site_cats[i]\n                psub = psubs[site_cat]\n                for (dest_motif_index, dest_motif) in enumerate(motifs):\n                    prob = psub[parent_motif_index, dest_motif_index]\n                    mprobs[dest_motif] = prob\n                randomMotifSources[site_cat, parent_motif] = _randomMotifGenerator(\n                    random_series, mprobs\n                )\n            edge_motif = next(randomMotifSources[site_cat, parent_motif])\n        seq.append(edge_motif)\n    return seq\n\n\ndef random_sequence(random_series, motif_probs, sequence_length):\n    getRootRandomMotif = _randomMotifGenerator(random_series, motif_probs).__next__\n    return [getRootRandomMotif() for i in range(sequence_length)]\n\n\nclass AlignmentEvolver(object):\n    # Encapsulates settings that are constant throughout the recursive generation\n    # of a synthetic alignment.\n\n    def __init__(\n        self,\n        random_series,\n        orig_ambig,\n        exclude_internal,\n        bin_names,\n        site_bins,\n        psub_for,\n        motifs,\n    ):\n        self.random_series = random_series\n        self.orig_ambig = orig_ambig\n        self.exclude_internal = exclude_internal\n        self.bin_names = bin_names\n        self.site_bins = site_bins\n        self.psub_for = psub_for\n        self.motifs = motifs\n\n    def __call__(self, tree, root_sequence):\n        # probsd = dict(enumerate(self.bin_probs))\n        # bprobs = _randomMotifGenerator(self.random_series, probsd)\n        # site_bins = [bprobs.next() for c in range(len(root_sequence))]\n        return self.generate_simulated_seqs(tree, root_sequence)\n\n    def generate_simulated_seqs(self, parent, parent_seq):\n        \"\"\"recursively generate the descendant sequences by descending the tree\n        from root.\n        Each child will be set by mutating the parent motif based on the probs\n        in the psub matrix of this edge.\n\n        random_series - get a random numer 0-1 by calling random_series.random()\n        length - the desired alignment length\n        parent - the edge structure.\n        parent_seq - the corresponding sequence. This will be mutated for each\n        of its children, based on their psub matricies.\n        \"\"\"\n\n        # This depends on parameter names 'mprobs', 'alignment2', 'bprobs' and\n        # 'psubs'.  Might be better to integrate it into likelihood_calculation.\n\n        if self.exclude_internal and parent.children:\n            simulated_sequences = {}\n        else:\n            simulated_sequences = {parent.name: \"\".join(parent_seq)}\n\n        for edge in parent.children:\n            # The result for this edge - a list of motifs\n\n            # Keep original ambiguity codes\n            if edge.name in self.orig_ambig:\n                orig_seq_ambig = self.orig_ambig[edge.name]\n            else:\n                orig_seq_ambig = {}\n\n            # Matrix of substitution probabilities\n            psubs = [self.psub_for(edge.name, bin) for bin in self.bin_names]\n\n            # Make the semi-random sequence for this edge.\n            edge_seq = evolve_sequence(\n                self.random_series,\n                self.motifs,\n                parent_seq,\n                self.site_bins,\n                psubs,\n                orig_seq_ambig,\n            )\n\n            # Pass this new edge sequence on down the tree\n            descendant_sequences = self.generate_simulated_seqs(edge, edge_seq)\n            simulated_sequences.update(descendant_sequences)\n\n        return simulated_sequences\n", "meta": {"hexsha": "b9d84092b0a46605edbbf2b287da75ed7114bdca", "size": 5037, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/cogent3/evolve/simulate.py", "max_stars_repo_name": "wjjmjh/cogent3", "max_stars_repo_head_hexsha": "e10f4f933921d52b000096b7c016190a1602add6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cogent3/evolve/simulate.py", "max_issues_repo_name": "wjjmjh/cogent3", "max_issues_repo_head_hexsha": "e10f4f933921d52b000096b7c016190a1602add6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cogent3/evolve/simulate.py", "max_forks_repo_name": "wjjmjh/cogent3", "max_forks_repo_head_hexsha": "e10f4f933921d52b000096b7c016190a1602add6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2653061224, "max_line_length": 83, "alphanum_fraction": 0.6426444312, "include": true, "reason": "import numpy", "num_tokens": 1147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.3593641382989649, "lm_q1q2_score": 0.1908976040528726}}
{"text": "import xarray as xr\nimport pandas as pd\nimport numpy as np\nimport os\nimport numba as nb\nimport time\nimport dask.array as da\n\n\ndef compute_all(work_dir, memory_to_allocate_gb, date_strings):\n    array_size_bytes = 3060  # Based on 15 x 51 member array\n    memory_to_allocate_bytes = memory_to_allocate_gb * 1e9\n\n    files = [os.path.join(work_dir, i + \".nc\") for i in date_strings]\n\n    chunk_size = int(np.floor(memory_to_allocate_bytes / ((array_size_bytes * len(files)) + len(files))))\n\n    print(\"Chunk Size:\", chunk_size)\n\n    list_of_dask_q_arrays = []\n    list_of_dask_init_arrays = []\n\n    # Creating a large dask array with all of the data in it\n    start = time.time()\n    for file in files:\n        ds = xr.open_dataset(file, chunks={\"rivid\": chunk_size})\n\n        tmp_dask_q_array = ds[\"Qout\"].data\n        list_of_dask_q_arrays.append(tmp_dask_q_array)\n\n        tmp_dask_init_array = ds[\"initialization_values\"].data\n        list_of_dask_init_arrays.append(tmp_dask_init_array)\n\n        ds.close()\n    end = time.time()\n\n    big_dask_q_array = da.stack(list_of_dask_q_arrays)\n    big_dask_init_array = da.stack(list_of_dask_init_arrays)\n\n    print(big_dask_q_array.shape)\n    print(big_dask_init_array.shape)\n\n    print(\"Time to create dask arrays: \", end - start)\n\n    # Retrieving the number of streams and their corresponding Rivids\n    tmp_dataset = xr.open_dataset(files[0])\n\n    num_of_streams = tmp_dataset['rivid'].size\n    rivids = tmp_dataset['rivid'].data\n\n    tmp_dataset.close()\n\n    num_chunk_iterations = int(np.ceil(num_of_streams / chunk_size))\n    start_chunk = 0\n    end_chunk = chunk_size\n    list_of_tuples_with_metrics = []\n\n    for chunk_number in range(num_chunk_iterations):\n\n        start = time.time()\n        big_forecast_data_array = np.asarray(big_dask_q_array[:, start_chunk:end_chunk, :, :])\n        big_init_data_array = np.asarray(big_dask_init_array[:, start_chunk:end_chunk])\n        end = time.time()\n        print(\"Time to read from disk:\", end - start)\n\n        rivids_chunk = rivids[start_chunk:end_chunk]\n\n        start = time.time()\n        results_array = numba_calculate_metrics(\n            big_forecast_data_array, big_init_data_array, len(files), big_forecast_data_array.shape[1], 15\n        )\n        end = time.time()\n        print(\"Numba Calculation Time: \", end - start)\n\n        for rivid in range(results_array.shape[1]):\n            for forecast_day in range(results_array.shape[0]):\n                tmp_array = results_array[forecast_day, rivid, :]\n                tuple_to_append = (rivids_chunk[rivid], '{} Day Forecast'.format(str(forecast_day + 1).zfill(2)),\n                                   tmp_array[0], tmp_array[1], tmp_array[2])\n                list_of_tuples_with_metrics.append(tuple_to_append)\n\n        start_chunk += chunk_size\n        end_chunk += chunk_size\n\n    final_df = pd.DataFrame(list_of_tuples_with_metrics,\n                            columns=['Rivid', 'Forecast Day', 'CRPS', 'CRPS BENCH', 'CRPSS'])\n    final_df.to_csv(r'/Users/wade/PycharmProjects/Forecast_Validation/South_America_Test_DF.csv', index=False)\n\n\n@nb.njit(parallel=True)\ndef numba_calculate_metrics(forecast_array, initialization_array, number_of_start_dates, number_of_streams,\n                            num_forecast_days):\n    \"\"\"\n    Parameters\n    ----------\n\n    forecast_array: 4D ndarray\n        A 4 dimensional numPy array with the following dimensions: 1) Start Date Number (365 if there are a year's\n        forecasts), 2) Unique stream ID, 3) Forecast Days (e.g. 1-15 in a 15 day forecast), 4) Ensembles\n\n    initialization_array: 2D ndarray\n        A 2 dimenensional NumPy array with the following dimensions: 1) Start Dates, 2) Unique stream ID\n\n    number_of_start_dates: The number of start dates for the analysis to perform\n\n    number_of_streams:\n        The number of streams in the analysis\n\n    num_forecast_days:\n        The number of forecast days in the analysis\n\n    Returns\n    -------\n    ndarray\n        An ndarray with the folowing dimenstions:\n        1) Forecast Day: 1-15 in the case of a 15 day forecast\n        2) Rivid: The stream unique ID\n        3) Metrics: CRPS, CRPS_BENCH, CRPSS\n\n    \"\"\"\n    return_array = np.zeros((num_forecast_days, number_of_streams, 3), dtype=np.float32)\n\n    for stream in nb.prange(number_of_streams):\n        for forecast_day in range(num_forecast_days):\n            initialization_vals = initialization_array[(forecast_day + 1):, stream]\n            # np.savetxt(\"init_test.txt\", initialization_vals)\n            forecasts = forecast_array[:(number_of_start_dates - (forecast_day + 1)), stream, forecast_day, :]\n            # np.savetxt(\"forecasts_test.txt\", forecasts)\n            benchmark_forecasts = initialization_array[:(number_of_start_dates - (forecast_day + 1)), stream]\n            # np.savetxt(\"benchmark_forecasts_test.txt\", benchmark_forecasts)\n\n            crps = ens_crps(initialization_vals, forecasts)\n            crps_bench = mae(initialization_vals, benchmark_forecasts)\n            if crps_bench == 0:\n                crpss = np.inf\n                print(\"Warning: Division by zero on: \", stream)\n            else:\n                crpss = 1 - crps / crps_bench\n\n            return_array[forecast_day, stream, 0] = crps\n            return_array[forecast_day, stream, 1] = crps_bench\n            return_array[forecast_day, stream, 2] = crpss\n\n            # print(crps, crps_bench, crpss)\n        if (stream % 1000) == 0:\n            print(\"Count: \", stream)\n\n    return return_array\n\n\n@nb.njit()\ndef mae(sim, obs):\n    return np.mean(np.abs(sim - obs))\n\n\n@nb.njit()\ndef ens_crps(obs, fcst_ens, adj=np.nan):\n\n    rows = obs.size\n    cols = fcst_ens.shape[1]\n\n    col_len_array = np.ones(rows) * cols\n    sad_ens_half = np.zeros(rows)\n    sad_obs = np.zeros(rows)\n    crps = np.zeros(rows)\n\n    crps = numba_crps(\n        fcst_ens, obs, rows, cols, col_len_array, sad_ens_half, sad_obs, crps, np.float64(adj)\n    )\n\n    # Calc mean crps as simple mean across crps[i]\n    crps_mean = np.mean(crps)\n\n    return crps_mean\n\n\n@nb.njit()\ndef numba_crps(ens, obs, rows, cols, col_len_array, sad_ens_half, sad_obs, crps, adj):\n    for i in range(rows):\n        the_obs = obs[i]\n        the_ens = ens[i, :]\n        the_ens = np.sort(the_ens)\n        sum_xj = 0.\n        sum_jxj = 0.\n\n        j = 0\n        while j < cols:\n            sad_obs[i] += np.abs(the_ens[j] - the_obs)\n            sum_xj += the_ens[j]\n            sum_jxj += (j + 1) * the_ens[j]\n            j += 1\n\n        sad_ens_half[i] = 2.0 * sum_jxj - (col_len_array[i] + 1) * sum_xj\n\n    if np.isnan(adj):\n        for i in range(rows):\n            crps[i] = sad_obs[i] / col_len_array[i] - sad_ens_half[i] / \\\n                      (col_len_array[i] * col_len_array[i])\n    elif adj > 1:\n        for i in range(rows):\n            crps[i] = sad_obs[i] / col_len_array[i] - sad_ens_half[i] / \\\n                      (col_len_array[i] * (col_len_array[i] - 1)) * (1 - 1 / adj)\n    elif adj == 1:\n        for i in range(rows):\n            crps[i] = sad_obs[i] / col_len_array[i]\n    else:\n        for i in range(rows):\n            crps[i] = np.nan\n\n    return crps\n\n\nif __name__ == \"__main__\":\n\n    starting_date = \"2018-08-19\"\n    ending_date = \"2018-12-16\"\n\n    dates_range = pd.date_range(starting_date, ending_date)\n    dates_strings = dates_range.strftime(\"%Y%m%d\").tolist()\n\n    workspace = r'/Users/wade/Documents/South_America_Forecasts'\n    MEMORY_TO_ALLOCATE = 1.0  # GB\n\n    start = time.time()\n    compute_all(workspace, MEMORY_TO_ALLOCATE, dates_strings)\n    end = time.time()\n    print(end - start)\n", "meta": {"hexsha": "7e8d5dc539cf5cde78ac4c683aa89c61bb068cf0", "size": 7609, "ext": "py", "lang": "Python", "max_stars_repo_path": "validate_forecasts.py", "max_stars_repo_name": "jorgessanchez7/Global_Forecast_Validation", "max_stars_repo_head_hexsha": "d3178acaa2a67801e832554a3f871b36c266fe3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "validate_forecasts.py", "max_issues_repo_name": "jorgessanchez7/Global_Forecast_Validation", "max_issues_repo_head_hexsha": "d3178acaa2a67801e832554a3f871b36c266fe3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "validate_forecasts.py", "max_forks_repo_name": "jorgessanchez7/Global_Forecast_Validation", "max_forks_repo_head_hexsha": "d3178acaa2a67801e832554a3f871b36c266fe3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3728070175, "max_line_length": 114, "alphanum_fraction": 0.6395058483, "include": true, "reason": "import numpy,import numba", "num_tokens": 1999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.19089760236349332}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport numpy\nfrom PIL import Image, ImageFile\n__version__ = \"1.0\"\n\n\"\"\"Visualization of 2-dimensional numpy arrays.\"\"\"\n\n\ndef array2im(a, brightness=1, contrast=1):\n    P = (a.real * (a.real > 0) * brightness) ** contrast\n    N = (-a.real * (a.real < 0) * brightness) ** contrast\n    R = numpy.array(\n        (256 * (1 - numpy.float64(0.5) ** P)).clip(max=255), dtype=numpy.uint8)[::-1]\n    G = numpy.zeros(R.shape, dtype=numpy.uint8)\n    B = numpy.array(\n        (256 * (1 - numpy.float64(0.5) ** N)).clip(max=255), dtype=numpy.uint8)[::-1]\n    return Image.fromarray(numpy.array([R, G, B]).swapaxes(0, 1).swapaxes(1, 2))\n\nif __name__ == \"__main__\":\n    import argparse\n    import struct\n    import os\n    import sys\n    import time\n    from numpy import dtype, fromfile\n    from numpy import save as npsave\n    from numpy import load as npload\n    import warnings\n    warnings.filterwarnings('ignore')\n\n    parser = argparse.ArgumentParser(\n        description=\"Converts a two-dimensional numpy array into an image.\")\n    parser.add_argument(\"--in\", \"-i\", dest=\"input\", action=\"store\",\n                        help=\"Input file. Default: <stdin>.\", default=\"-\")\n    parser.add_argument(\"--out\", \"-o\", dest=\"output\", action=\"store\",\n                        help=\"Output file. Default: <stdout>.\", default=\"-\")\n    parser.add_argument(\"--brightness\", \"-b\", dest=\"brightness\",\n                        action=\"store\", help=\"Adjust brightness. Default: 1.\", default=1)\n    parser.add_argument(\"--contrast\", \"-c\", dest=\"contrast\",\n                        action=\"store\", help=\"Adjust contrast. Default: 1.\", default=1)\n    parser.add_argument(\"--quality\", \"-q\", dest=\"quality\", action=\"store\",\n                        help=\"JPEG quality, between 1 and 100. Only valid when saving image as a JPEG. Default: 95.\", default=95)\n    parser.add_argument(\"--progressive\", \"-p\", dest=\"progressive\", action=\"store_const\",\n                        help=\"Save progressive JPEG. Only valid when saving image as a JPEG.\", const=True)\n    parser.add_argument(\"--overwrite\", \"-y\", dest=\"overwrite\",\n                        action='store_const', help=\"Overwrite output file, if it exists.\", const=True)\n    parser.add_argument(\"--no-overwrite\", \"-n\", dest=\"nooverwrite\", action='store_const',\n                        help=\"Do not overwrite output file, if it exists.\", const=True)\n    args = parser.parse_args()\n\n    msgout = sys.stdout if sys.stdout.isatty() else sys.stderr\n\n    if args.overwrite and args.nooverwrite:\n        print >>sys.stderr, \"Cannot specify both '-y' and '-n'!\"\n        sys.exit()\n\n    if args.input == \"-\":\n        if sys.stdin.isatty():\n            print >>sys.stderr, \"Surely you are not typing the raw data into the terminal. Please specify input file, or pipe input from another program.\\n\"\n            parser.print_help(sys.stderr)\n            sys.exit()\n        infile = sys.stdin\n    else:\n        infile = open(args.input, \"rb\")\n\n    if args.output == \"-\":\n        if sys.stdout.isatty():\n            print >>sys.stderr, \"Cowardly refusing to write binary data to terminal. Please specify output file, or redirect output to a pipe.\\n\"\n            parser.print_help(sys.stderr)\n            sys.exit()\n        outfile = sys.stdout\n        print >>sys.stderr, \"Writing data to <stdout>.\"\n    else:\n        if os.path.exists(args.output):\n            if args.nooverwrite:\n                print >>sys.stderr, \"Error: Output file '%s' exists. Terminating because '-n' was specified.\" % args.output\n                sys.exit()\n            elif args.overwrite:\n                print >>msgout, \"Warning: Output file '%s' exists. Overwriting because '-y' was specified.\" % args.output\n            elif sys.stdin.isatty() and sys.stdout.isatty():\n                overwrite = raw_input(\n                    \"Warning: Output file '%s' exists. Do you wish to overwrite file? (Y/N) \" % args.output)\n                while overwrite.upper() not in (\"Y\", \"N\", \"YES\", \"NO\"):\n                    print >>msgout, \"Invalid answer: '%s'\" % overwrite\n                    overwrite = raw_input(\n                        \"Warning: Output file '%s' exists. Do you wish to overwrite file? (Y/N) \" % args.output)\n\n                if overwrite.upper() in (\"Y\", \"YES\"):\n                    print >>msgout, \"Overwriting '%s'.\" % args.output\n                    print >>msgout, \"\"\n                elif overwrite.upper() in (\"N\", \"NO\"):\n                    print >>msgout, \"Operation aborted.\"\n                    sys.exit()\n            else:\n                print >>sys.stderr, \"Operation aborted. Cowardly refusing to overwrite '%s'.\" % args.output\n                sys.exit()\n\n        outfile = args.output\n\n    tag = npload(infile)\n    metadata = npload(infile)\n    data = npload(infile)\n    if infile is not sys.stdin:\n        infile.close()\n\n    if len(data.shape) != 2:\n        print >>sys.stderr, \"Expected a two-dimensional array. Got an array with shape %s instead.\" % (\n            data.shape,)\n        sys.exit()\n\n    kind_str = {\n        \"f\": \"floating point\",\n        \"i\": \"integer\",\n        \"u\": \"unsigned integer\",\n        \"b\": \"boolean\",\n        \"c\": \"complex\"\n    }\n\n    if data.dtype.kind in \"iub\":\n        print >>sys.stderr, \"Error: Data type '%s' not supported.\" % kind_str[\n            data.dtype.kind]\n        sys.exit()\n    elif data.dtype.kind == \"c\":\n        print >>msgout, \"Warning: Discarding imaginary part of 'complex' array.\"\n\n    try:\n        args.brightness = float(args.brightness)\n    except ValueError:\n        print >>sys.stderr, \"Bad parameter for brightness. Expected floating point or integer, got '%s' instead.\" % args.brightness\n        sys.exit()\n\n    try:\n        args.contrast = float(args.contrast)\n    except ValueError:\n        print >>sys.stderr, \"Bad parameter for contrast. Expected floating point or integer, got '%s' instead.\" % args.contrast\n        sys.exit()\n\n    try:\n        args.quality = int(args.quality)\n    except ValueError:\n        print >>sys.stderr, \"Bad parameter for quality. Expected integer between 1 and 100, got '%s' instead.\" % args.quality\n        sys.exit()\n\n    if not (1 <= args.quality <= 100):\n        print >>sys.stderr, \"Bad parameter for quality. Expected integer between 1 and 100, got '%s' instead.\" % args.quality\n        sys.exit()\n\n    H, W = data.shape\n\n    t0 = time.time()\n    print >>msgout, u\"Saving %d×%d image to '%s'...\" % (W, H, args.output),\n    msgout.flush()\n    img = array2im(data, brightness=args.brightness, contrast=args.contrast)\n    ImageFile.MAXBLOCK = img.size[0] * img.size[1]\n    img.save(outfile, progressive=args.progressive, quality=args.quality)\n    print >>msgout, \"%.2f seconds\" % (time.time() - t0)\n", "meta": {"hexsha": "1f16cddb95e5616b13b1205a28d4fa7512a8af6f", "size": 6737, "ext": "py", "lang": "Python", "max_stars_repo_path": "array2im.py", "max_stars_repo_name": "shersonb/python-array2im", "max_stars_repo_head_hexsha": "6af0e5fb88d2e31fb906a5c29c32e9008ab24ed8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "array2im.py", "max_issues_repo_name": "shersonb/python-array2im", "max_issues_repo_head_hexsha": "6af0e5fb88d2e31fb906a5c29c32e9008ab24ed8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "array2im.py", "max_forks_repo_name": "shersonb/python-array2im", "max_forks_repo_head_hexsha": "6af0e5fb88d2e31fb906a5c29c32e9008ab24ed8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.6392405063, "max_line_length": 156, "alphanum_fraction": 0.584236307, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.35936413829896496, "lm_q1q2_score": 0.19089759871879308}}
{"text": "''' FSL IO '''\n\nfrom __future__ import with_statement\n\nimport os\nfrom os.path import join as pjoin\nfrom subprocess import Popen,PIPE\n\nimport numpy as np\nimport numpy.linalg as npl\nfrom numpy import newaxis\n\nfrom scipy.ndimage import map_coordinates as mc\nfrom scipy.ndimage import affine_transform\nfrom dipy.io.dpy import Dpy\n\nimport nibabel as nib\nfrom nibabel.tmpdirs import InTemporaryDirectory\n\n_VAL_FMT = '   %e'\n\nclass FSLError(Exception):\n    \"\"\" Class signals error in FSL processing \"\"\"\n\n\ndef have_flirt():\n    \"\"\" Return True if we can call flirt without error\n\n    Relies on the fact that flirt produces text on stdout when called with no\n    arguments\n    \"\"\"\n    p = Popen('flirt', stdout=PIPE, stderr=PIPE, shell=True)\n    stdout, stderr = p.communicate()\n    return stdout != ''\n\n\ndef write_bvals_bvecs(bvals, bvecs, outpath=None, prefix=''):\n    ''' Write FSL FDT bvals and bvecs files\n\n    Parameters\n    -------------\n    bvals : (N,) sequence\n       Vector with diffusion gradient strength (one per diffusion\n       acquisition, N=no of acquisitions)\n    bvecs : (N, 3) array-like\n       diffusion gradient directions\n    outpath : None or str\n       path to write FDT bvals, bvecs text files\n       None results in current working directory.\n    prefix : str\n       prefix for bvals, bvecs files in directory.  Defaults to ''\n    '''\n    if outpath is None:\n        outpath = os.getcwd()\n    bvals = tuple(bvals)\n    bvecs = np.asarray(bvecs)\n    bvecs[np.isnan(bvecs)] = 0\n    N = len(bvals)\n    fname = pjoin(outpath, prefix + 'bvals')\n    fmt = _VAL_FMT * N + '\\n'\n    open(fname, 'wt').write(fmt % bvals)\n    fname = pjoin(outpath, prefix + 'bvecs')\n    bvf = open(fname, 'wt')\n    for dim_vals in bvecs.T:\n        bvf.write(fmt % tuple(dim_vals))\n\n\ndef flirt2aff(mat, in_img, ref_img):\n    \"\"\" Transform from `in_img` voxels to `ref_img` voxels given `mat`\n\n    Parameters\n    ----------\n    mat : (4,4) array\n        contents (as array) of output ``-omat`` transformation file from flirt\n    in_img : img\n        image passed (as filename) to flirt as ``-in`` image\n    ref_img : img\n        image passed (as filename) to flirt as ``-ref`` image\n\n    Returns\n    -------\n    aff : (4,4) array\n        Transform from voxel coordinates in ``in_img`` to voxel coordinates in\n        ``ref_img``\n\n    Notes\n    -----\n    Thanks to Mark Jenkinson and Jesper Andersson for the correct statements\n    here, apologies for any errors we've added.\n\n    ``flirt`` registers an ``in`` image to a ``ref`` image.  It can produce\n    (with the ``-omat`` option) - a 4 x 4 affine matrix giving the mapping from\n    *inspace* to *refspace*.\n\n    The rest of this note is to specify what *inspace* and *refspace* are.\n\n    In what follows, a *voxtrans* for an image is the 4 by 4 affine\n    ``np.diag([vox_i, vox_j, vox_k, 1])`` where ``vox_i`` etc are the voxel\n    sizes for the first second and third voxel dimension.  ``vox_i`` etc are\n    always positive.\n\n    If the input image has an affine with a negative determinant, then the\n    mapping from voxel coordinates in the input image to *inspace* is simply\n    *voxtrans* for the input image.  If the reference image has a negative\n    determinant, the mapping from voxel space in the reference image to\n    *refspace* is simply *voxtrans* for the reference image.\n\n    A negative determinant for the image affine is the common case, of an image\n    with a x voxel flip.  Analyze images don't store affines and flirt assumes a\n    negative determinant in these cases.\n\n    For positive determinant affines, flirt starts *inspace* and / or *refspace*\n    with an x voxel flip.  The mapping implied for an x voxel flip for image\n    with shape (N_i, N_j, N_k) is:\n\n        [[-1, 0, 0, N_i - 1],\n         [ 0, 1, 0,       0],\n         [ 0, 0, 1,       0],\n         [ 0, 0, 0,       1]]\n\n    If the input image has an affine with a positive determinant, then mapping\n    from input image voxel coordinates to *inspace* is ``np.dot(input_voxtrans,\n    input_x_flip)`` - where ``input_x_flip`` is the matrix above with ``N_i``\n    given by the input image first axis length.  Similarly the mapping from\n    reference voxel coordinates to *refspace*, if the reference image has a\n    positive determinant, is ``np.dot(ref_voxtrans, ref_x_flip)`` - where\n    ``ref_x_flip`` is the matrix above with ``N_i`` given by the reference image\n    first axis length.\n    \"\"\"\n    in_hdr = in_img.get_header()\n    ref_hdr = ref_img.get_header()\n    # get_zooms gets the positive voxel sizes as returned in the header\n    inspace = np.diag(in_hdr.get_zooms() + (1,))\n    refspace = np.diag(ref_hdr.get_zooms() + (1,))\n    if npl.det(in_img.get_affine())>=0:\n        inspace = np.dot(inspace, _x_flipper(in_hdr.get_data_shape()[0]))\n    if npl.det(ref_img.get_affine())>=0:\n        refspace = np.dot(refspace, _x_flipper(ref_hdr.get_data_shape()[0]))\n    # Return voxel to voxel mapping\n    return np.dot(npl.inv(refspace), np.dot(mat, inspace))\n\n\ndef _x_flipper(N_i):\n    flipr = np.diag([-1, 1, 1, 1])\n    flipr[0,3] = N_i - 1\n    return flipr\n\n\ndef flirt2aff_files(matfile, in_fname, ref_fname):\n    \"\"\" Map from `in_fname` image voxels to `ref_fname` voxels given `matfile`\n\n    See :func:`flirt2aff` docstring for details.\n\n    Parameters\n    ------------\n    matfile : str\n        filename of output ``-omat`` transformation file from flirt\n    in_fname : str\n        filename for image passed to flirt as ``-in`` image\n    ref_fname : str\n        filename for image passed to flirt as ``-ref`` image\n\n    Returns\n    -------\n    aff : (4,4) array\n        Transform from voxel coordinates in image for ``in_fname`` to voxel\n        coordinates in image for ``ref_fname``\n    \"\"\"\n    mat = np.loadtxt(matfile)\n    in_img = nib.load(in_fname)\n    ref_img = nib.load(ref_fname)\n    return flirt2aff(mat, in_img, ref_img)\n\n\ndef warp_displacements(ffa,flaff,fdis,fref,ffaw,order=1):\n    ''' Warp an image using fsl displacements \n\n    Parameters\n    ------------\n    ffa : filename of nifti to be warped\n    flaff : filename of .mat  (flirt)\n    fdis :  filename of displacements (fnirtfileutils)\n    fref : filename of reference volume e.g. (FMRIB58_FA_1mm.nii.gz)\n    ffaw : filename for the output warped image\n    '''\n    refaff=nib.load(fref).get_affine()    \n    disdata=nib.load(fdis).get_data()\n    imgfa=nib.load(ffa)\n    fadata=imgfa.get_data()\n    fazooms=imgfa.get_header().get_zooms()    \n    #from fa index to ref index\n    res=flirt2aff_files(flaff,ffa,fref)\n    #from ref index to fa index\n    ires=np.linalg.inv(res)    \n    #create the 4d volume which has the indices for the reference image  \n    reftmp=np.zeros(disdata.shape)\n    '''    \n    #create the grid indices for the reference\n    #refinds = np.ndindex(disdata.shape[:3])  \n    for ijk_t in refinds:\n        i,j,k = ijk_t   \n        reftmp[i,j,k,0]=i\n        reftmp[i,j,k,1]=j\n        reftmp[i,j,k,2]=k\n    '''\n    #same as commented above but much faster\n    reftmp[...,0] = np.arange(disdata.shape[0])[:,newaxis,newaxis]\n    reftmp[...,1] = np.arange(disdata.shape[1])[newaxis,:,newaxis]\n    reftmp[...,2] = np.arange(disdata.shape[2])[newaxis,newaxis,:]\n        \n    #affine transform from reference index to the fa index\n    A = np.dot(reftmp,ires[:3,:3].T)+ires[:3,3]\n    #add the displacements but first devide them by the voxel sizes\n    A2=A+disdata/fazooms\n    #hold the displacements' shape reshaping\n    di,dj,dk,dl=disdata.shape\n    #do the interpolation using map coordinates\n    #the list of points where the interpolation is done given by the reshaped in 2D A2 (list of 3d points in fa index)\n    W=mc(fadata,A2.reshape(di*dj*dk,dl).T,order=order).reshape(di,dj,dk)    \n    #save the warped image\n    Wimg=nib.Nifti1Image(W,refaff)\n    nib.save(Wimg,ffaw)\n    \n    \ndef warp_displacements_tracks(fdpy,ffa,fmat,finv,fdis,fdisa,fref,fdpyw):\n    \"\"\" Warp tracks from native space to the FMRIB58/MNI space\n    \n    We use here the fsl displacements. Have a look at create_displacements to\n    see an example of how to use these displacements.  \n    \n    Parameters\n    ------------\n    fdpy : filename of the .dpy file with the tractography\n    ffa : filename of nifti to be warped\n    fmat : filename of .mat  (flirt)\n    fdis :  filename of displacements (fnirtfileutils)\n    fdisa :  filename of displacements (fnirtfileutils + affine)\n    finv : filename of invwarp displacements (invwarp)\n    fref : filename of reference volume e.g. (FMRIB58_FA_1mm.nii.gz)\n    fdpyw : filename of the warped tractography\n       \n    \n    See also\n    -----------\n    dipy.external.fsl.create_displacements\n    \n    \"\"\"   \n    \n    #read the tracks from the image space \n    dpr=Dpy(fdpy,'r')\n    T=dpr.read_tracks()\n    dpr.close()    \n    \n    #copy them in a new file\n    dpw=Dpy(fdpyw,'w',compression=1)\n    dpw.write_tracks(T)\n    dpw.close()\n    \n    #from fa index to ref index\n    res=flirt2aff_files(fmat,ffa,fref)\n    \n    #load the reference img    \n    imgref=nib.load(fref)\n    refaff=imgref.get_affine()\n    \n    #load the invwarp displacements\n    imginvw=nib.load(finv)\n    invwdata=imginvw.get_data()\n    invwaff = imginvw.get_affine()\n    \n    #load the forward displacements\n    imgdis=nib.load(fdis)\n    disdata=imgdis.get_data()\n    \n    #load the forward displacements + affine\n    imgdis2=nib.load(fdisa)\n    disdata2=imgdis2.get_data()\n    \n    #from their difference create the affine\n    disaff=disdata2-disdata\n    \n    del disdata\n    del disdata2\n    \n    shape=nib.load(ffa).get_data().shape\n    \n    #transform the displacements affine back to image space\n    disaff0=affine_transform(disaff[...,0],res[:3,:3],res[:3,3],shape,order=1)\n    disaff1=affine_transform(disaff[...,1],res[:3,:3],res[:3,3],shape,order=1)\n    disaff2=affine_transform(disaff[...,2],res[:3,:3],res[:3,3],shape,order=1)\n    \n    #remove the transformed affine from the invwarp displacements\n    di=invwdata[:,:,:,0] + disaff0\n    dj=invwdata[:,:,:,1] + disaff1\n    dk=invwdata[:,:,:,2] + disaff2    \n    \n    dprw=Dpy(fdpyw,'r+')\n    rows=len(dprw.f.root.streamlines.tracks)   \n    blocks=np.round(np.linspace(0,rows,10)).astype(int)#lets work in blocks\n    #print rows\n    for i in range(len(blocks)-1):        \n        #print blocks[i],blocks[i+1]   \n        #copy a lot of tracks together\n        caboodle=dprw.f.root.streamlines.tracks[blocks[i]:blocks[i+1]]\n        mci=mc(di,caboodle.T,order=1) #interpolations for i displacement\n        mcj=mc(dj,caboodle.T,order=1) #interpolations for j displacement\n        mck=mc(dk,caboodle.T,order=1) #interpolations for k displacement            \n        D=np.vstack((mci,mcj,mck)).T\n        #go back to mni image space                        \n        WI2=np.dot(caboodle,res[:3,:3].T)+res[:3,3]+D\n        #and then to mni world space\n        caboodlew=np.dot(WI2,refaff[:3,:3].T)+refaff[:3,3]\n        #write back       \n        dprw.f.root.streamlines.tracks[blocks[i]:blocks[i+1]]=caboodlew.astype('f4')\n    dprw.close()\n    \ndef pipe(cmd):\n    \"\"\" A tine pipeline system to run external tools.\n            \n    For more advanced pipelining use nipype http://www.nipy.org/nipype    \n    \"\"\"\n    p = Popen(cmd, shell=True,stdout=PIPE,stderr=PIPE)\n    sto=p.stdout.readlines()\n    ste=p.stderr.readlines()\n    print(sto)\n    print(ste)\n\n\ndef dcm2nii(dname,outdir,filt='*.dcm',options='-d n -g n -i n -o'):\n    cmd='dcm2nii '+options +' ' + outdir +' ' + dname + '/' + filt\n    print(cmd)\n    pipe(cmd)\n\n\ndef eddy_correct(in_nii,out_nii,ref=0):\n    cmd='eddy_correct '+in_nii+' '+ out_nii + ' '+str(ref)\n    print(cmd)\n    pipe(cmd)\n\n\ndef bet(in_nii,out_nii,options=' -F -f .2 -g 0'):\n    cmd='bet '+in_nii+' '+ out_nii + options\n    print(cmd)\n    pipe(cmd)\n\n\ndef run_flirt_imgs(in_img, ref_img, dof=6, flags=''):\n    \"\"\" Run flirt on nibabel images, returning affine\n\n    Parameters\n    ----------\n    in_img : `SpatialImage'\n        image to register\n    ref_img : `SpatialImage`\n        image to register to\n    dof : int, optional\n        degrees of freedom for registration (default 6)\n    flags : str, optional\n        other flags to pass to flirt command string\n\n    Returns\n    -------\n    in_vox2out_vox : (4,4) ndarray\n        affine such that, if [i, j, k] is a coordinate in voxels in the\n        `in_img`, and [p, q, r] are the equivalent voxel coordinates in the\n        reference image, then [p, q, r] = np.dot(in_vox2out_vox[:3,:3]), [i, j,\n        k] + in_vox2out_vox[:3,3])\n    \"\"\"\n    omat = 'reg.mat'\n    with InTemporaryDirectory():\n        nib.save(in_img, 'in.nii')\n        nib.save(ref_img, 'ref.nii')\n        cmd = 'flirt %s -dof %d -in in.nii -ref ref.nii -omat %s' % (\n            flags, dof, omat)\n        proc = Popen(cmd, shell=True,stdout=PIPE,stderr=PIPE)\n        stdout, stderr = proc.communicate()\n        if not os.path.isfile(omat):\n            raise FSLError('Command \"%s\" failed somehow - stdout: %s\\n'\n                           'and stderr: %s\\n' % (cmd, stdout, stderr))\n        res = np.loadtxt(omat)\n    return flirt2aff(res, in_img, ref_img)\n\n\ndef apply_warp(in_nii,affine_mat,nonlin_nii,out_nii):\n    cmd='applywarp --ref=${FSLDIR}/data/standard/FMRIB58_FA_1mm --in='+in_nii+' --warp='+nonlin_nii+' --out='+out_nii\n    print(cmd)\n    pipe(cmd)\n\ndef create_displacements(in_nii,affine_mat,nonlin_nii,invw_nii,disp_nii,dispa_nii):\n    commands=[]    \n    commands.append('flirt -ref ${FSLDIR}/data/standard/FMRIB58_FA_1mm -in '+in_nii+' -omat ' + affine_mat)\n    commands.append('fnirt --in='+in_nii+' --aff='+affine_mat+' --cout='+nonlin_nii+' --config=FA_2_FMRIB58_1mm')\n    commands.append('invwarp --ref='+in_nii+' --warp='+nonlin_nii+' --out='+invw_nii)\n    commands.append('fnirtfileutils --in='+nonlin_nii+' --ref=${FSLDIR}/data/standard/FMRIB58_FA_1mm --out='+disp_nii)\n    commands.append('fnirtfileutils --in='+nonlin_nii+' --ref=${FSLDIR}/data/standard/FMRIB58_FA_1mm --out='+dispa_nii + ' --withaff')\n    for c in commands:\n        print(c)\n        pipe(c)\n", "meta": {"hexsha": "c46e7e99471ce546c423d0da75768827c46b33eb", "size": 13988, "ext": "py", "lang": "Python", "max_stars_repo_path": "dipy/external/fsl.py", "max_stars_repo_name": "stefanv/dipy", "max_stars_repo_head_hexsha": "4d4518861a796502826f053c17161487db126487", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-07-31T20:43:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-26T13:58:07.000Z", "max_issues_repo_path": "dipy/external/fsl.py", "max_issues_repo_name": "stefanv/dipy", "max_issues_repo_head_hexsha": "4d4518861a796502826f053c17161487db126487", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2015-05-13T17:44:42.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-27T20:09:55.000Z", "max_forks_repo_path": "dipy/external/fsl.py", "max_forks_repo_name": "stefanv/dipy", "max_forks_repo_head_hexsha": "4d4518861a796502826f053c17161487db126487", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-08-05T22:43:16.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-23T18:35:13.000Z", "avg_line_length": 35.0576441103, "max_line_length": 134, "alphanum_fraction": 0.6426222476, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 4050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306515, "lm_q2_score": 0.359364145160102, "lm_q1q2_score": 0.19089759702941372}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n\nCreated on Sun Aug 23 12:11:15 2020\n\nModified from the cornstover biorefinery constructed in Cortes-Peña et al., 2020,\nwith modification of fermentation system for 2,3-Butanediol instead of the original ethanol\n\n[1] Cortes-Peña et al., BioSTEAM: A Fast and Flexible Platform for the Design, \n    Simulation, and Techno-Economic Analysis of Biorefineries under Uncertainty. \n    ACS Sustainable Chem. Eng. 2020, 8 (8), 3302–3310. \n    https://doi.org/10.1021/acssuschemeng.9b07040.\n\nAll units are explicitly defined here for transparency and easy reference\n\n[1] Cortes-Peña et al., BioSTEAM: A Fast and Flexible Platform for the Design, \n    Simulation, and Techno-Economic Analysis of Biorefineries under Uncertainty. \n    ACS Sustainable Chem. Eng. 2020, 8 (8), 3302–3310. \n    https://doi.org/10.1021/acssuschemeng.9b07040.\n\nNaming conventions:\n    D = Distillation column\n    F = Flash tank\n    H = Heat exchange\n    M = Mixer\n    P = Pump (including conveying belt)\n    R = Reactor\n    S = Splitter (including solid/liquid separator)\n    T = Tank or bin for storage\n    U = Other units\n    PS = Process specificiation, not physical units, but for adjusting streams\n\nProcesses:\n    100: Feedstock preprocessing\n    200: Pretreatment\n    300: Conversion\n    400: Separation\n    500: Wastewater treatment\n    600: Facilities\n\n@author: sarangbhagwat\n\"\"\"\n\n\n# %% Setup\n\nimport biosteam as bst\nimport thermosteam as tmo\nimport flexsolve as flx\nimport numpy as np\nfrom biosteam import main_flowsheet as F\nfrom biorefineries import BST222\nfrom biorefineries.cornstover import CellulosicEthanolTEA\nfrom biosteam import System\nfrom thermosteam import Stream\nfrom biorefineries import BDO as bdo\nfrom biorefineries.BDO import units, facilities\nfrom biorefineries.BDO._process_specification import ProcessSpecification\nfrom biorefineries.BDO.process_settings import price, CFs\nfrom biorefineries.BDO.utils import find_split, splits_df, baseline_feedflow\nfrom biorefineries.BDO.chemicals_data import BDO_chemicals, chemical_groups, \\\n                                soluble_organics, combustibles\nfrom biorefineries.BDO.tea import BDOTEA\nfrom biorefineries.HP.lca import LCA\n\nbst.speed_up()\nflowsheet = bst.Flowsheet('BDO')\nbst.main_flowsheet.set_flowsheet(flowsheet)\nbst.System.default_relative_molar_tolerance = 1e-4\nbst.System.default_maxiter = 100\nbst.System.default_molar_tolerance = 0.1\n\n# Speeds up ShortcutDistillation\nbst.units.ShortcutColumn.minimum_guess_distillate_recovery = 0\n\n# Baseline cost year is 2016\nbst.CE = 541.7\n# _labor_2007to2016 = 22.71 / 19.55\n\n# Set default thermo object for the system\ntmo.settings.set_thermo(BDO_chemicals)\n\nBDO_sys = bdo.create_system_broth()\nu = flowsheet.unit\nfeedstock = BDO_sys.ins[0]\n# feedstock.mol[:] = baseline_feedflow[:]\nconc_aqueous_broth, = BDO_sys.outs\nget_flow_tpd = lambda: (feedstock.F_mass-feedstock.imass['H2O'])*24/907.185\nu = F.unit\ns = F.stream\n# globals().update(F.to_dict())\n\n# %%\n# =============================================================================\n# TEA\n# =============================================================================\n\n# BDO_tea = bst.CombinedTEA([BDO_no_BT_tea, BT_tea], IRR=0.10)\nBDO_tea = CellulosicEthanolTEA(system=BDO_sys, IRR=0.10, duration=(2016, 2046),\n        depreciation='MACRS7', income_tax=0.21, operating_days=0.9*365,\n        lang_factor=None, construction_schedule=(0.08, 0.60, 0.32),\n        startup_months=3, startup_FOCfrac=1, startup_salesfrac=0.5,\n        startup_VOCfrac=0.75, WC_over_FCI=0.05,\n        finance_interest=0.08, finance_years=10, finance_fraction=0.4,\n        # biosteam Splitters and Mixers have no cost, \n        # cost of all wastewater treatment units are included in WWT_cost,\n        # BT is not included in this TEA\n        OSBL_units=bst.get_OSBL(BDO_sys.units),\n        warehouse=0.04, site_development=0.09, additional_piping=0.045,\n        proratable_costs=0.10, field_expenses=0.10, construction=0.20,\n        contingency=0.10, other_indirect_costs=0.10, \n        labor_cost=3212962*get_flow_tpd()/2205,\n        labor_burden=0.90, property_insurance=0.007, maintenance=0.03,\n        steam_power_depreciation='MACRS20', boiler_turbogenerator=u.BT701)\n\n# sub_units = BDO_sys.units[:BDO_sys.units.index(u.R401)]\n# sub_sys = bst.System(sub_units)\n# sub_tea = CellulosicEthanolTEA(system=sub_sys, IRR=0.10, duration=(2016, 2046),\n#         depreciation='MACRS7', income_tax=0.21, operating_days=0.9*365,\n#         lang_factor=None, construction_schedule=(0.08, 0.60, 0.32),\n#         startup_months=3, startup_FOCfrac=1, startup_salesfrac=0.5,\n#         startup_VOCfrac=0.75, WC_over_FCI=0.05,\n#         finance_interest=0.08, finance_years=10, finance_fraction=0.4,\n#         # biosteam Splitters and Mixers have no cost, \n#         # cost of all wastewater treatment units are included in WWT_cost,\n#         # BT is not included in this TEA\n#         OSBL_units=bst.get_OSBL(sub_sys.units),\n#         warehouse=0.04, site_development=0.09, additional_piping=0.045,\n#         proratable_costs=0.10, field_expenses=0.10, construction=0.20,\n#         contingency=0.10, other_indirect_costs=0.10, \n#         labor_cost=3212962*get_flow_tpd()/2205,\n#         labor_burden=0.90, property_insurance=0.007, maintenance=0.03,\n#         steam_power_depreciation='MACRS20', boiler_turbogenerator=u.BT)\n\narea_names = [\n    'feedstock',\n    'pretreatment',\n    'conversion',\n    'separation',\n    'wastewater',\n    'storage',\n    'co-heat and power',\n    'cooling tower and chilled water package',\n    'other facilities',\n    'heat exchanger network',\n]\n# u.CWP901.ID = 'CWP802' \nfor ui in u:\n    if type(ui) == bst.ChilledWaterPackage:\n        ui.ID = 'CWP802' # group with CT for system cooling demand\n        break\nunit_groups = bst.UnitGroup.group_by_area(BDO_sys.units)\nfor i, j in zip(unit_groups, area_names): i.name = j\nfor i in unit_groups: i.autofill_metrics(shorthand=True, \n                                         electricity_production=True, \n                                         material_cost=True)\nfor i in unit_groups:\n    if i.name == 'storage' or i.name=='other facilities' or i.name == 'cooling tower and chilled water package':\n        i.metrics[-1].getter = lambda: 0. # Material cost\n    if i.name == 'cooling tower and chilled water package':\n        i.metrics[1].getter = lambda: 0. # Cooling duty\nHXN = None\nfor HXN_group in unit_groups:\n    if HXN_group.name == 'heat exchanger network':\n        HXN_group.filter_savings = False\n        HXN = HXN_group.units[0]\n        assert isinstance(HXN, bst.HeatExchangerNetwork)\n\nunit_groups_dict = {}\nfor i in unit_groups:\n    unit_groups_dict[i.name] = i\n# HXN.force_ideal_thermo = True\nCT = u.CT801\nBT = u.BT701\nCWP = u.CWP802\n\n# %% \n# =============================================================================\n# Simulate system and get results\n# =============================================================================\n\nTEA_feeds = set([i for i in BDO_sys.feeds if i.price])\n\nTEA_products = set([i for i in BDO_sys.products if i.price])\nconc_aqueous_broth.price = 0.\ndef get_conc_aqueous_broth_MPSP():\n    BDO_sys.simulate()\n    \n    for i in range(3):\n        conc_aqueous_broth.price = BDO_tea.solve_price(conc_aqueous_broth)\n    return conc_aqueous_broth.price\n\nM401, F401 = flowsheet('M401'), flowsheet('F401')\ndef set_target_BDO_x(target_BDO_x):\n    F401.target_BDO_x = target_BDO_x\n    M401.target_BDO_x = target_BDO_x\n    \ndef get_x(chem_ID, stream):\n    return stream.imol[chem_ID]/sum(stream.imol[tuple([i.ID for i in stream.vle_chemicals])])\n\n# get_conc_aqueous_broth_MPSP()\n\n# R301 = F('R301') # Fermentor\nseed_train_system = bst.System('seed_train_system', path=(u.S302, u.R303, u.T301))\n\n# yearly_production = 125000 # ton/yr\nspec = ProcessSpecification(\n    evaporator = u.F301,\n    evaporator_pump = u.F301_P,\n    pump = u.M304_H_P,\n    mixer = u.M304,\n    heat_exchanger = u.M304_H,\n    seed_train_system = seed_train_system,\n    reactor= u.R302,\n    reaction_name='fermentation_reaction',\n    substrates=('Xylose', 'Glucose'),\n    products=('BDO',),\n    spec_1=0.36,\n    spec_2=109.9,\n    spec_3=1.,\n    xylose_utilization_fraction = 0.80,\n    feedstock = feedstock,\n    dehydration_reactor = None,\n    byproduct_streams = [],\n    HXN = u.HXN1001,\n    tolerable_HXN_energy_balance_percent_error=5,\n    maximum_inhibitor_concentration = 1.,\n    # pre_conversion_units = process_groups_dict['feedstock_group'].units + process_groups_dict['pretreatment_group'].units + [u.H301], # if the line below does not work (depends on BioSTEAM version)\n    # pre_conversion_units = BDO_sys.split(u.F301.ins[0])[0],\n    baseline_titer = 54.8,\n    feedstock_mass = feedstock.F_mass,\n    pretreatment_reactor = u.R201)\n\n\n\nspec.load_spec_1 = spec.load_yield\nspec.load_spec_2 = spec.load_titer\nspec.load_spec_3 = spec.load_productivity\n\n\n# spec = ProcessSpecification(\n#     evaporator = u.F301,\n#     mixer = u.M304,\n#     reactor=u.R302,\n#     reaction_name='fermentation_reaction',\n#     substrates=('Xylose', 'Glucose'),\n#     products=('BDO',),\n#     spec_1=0.8,\n#     spec_2=109.9,\n#     spec_3=1.,\n#     path = (u.M304_H, u.M304_H_P),\n#     xylose_utilization_fraction = 0.80,\n#     feedstock = feedstock,\n#     dehydration_reactor = u.R401,\n#     byproduct_streams = [s.isobutanol],\n#     evaporator_pump = u.F301_P)\n\npath = (u.F301, u.R302)\n@np.vectorize\ndef calculate_titer(V):\n    u.F301.V = V\n    for i in path: i._run()\n    return spec._calculate_titer()\n\n@np.vectorize   \ndef calculate_MPSP(V):\n    u.F301.V = V\n    BDO_sys.simulate()\n    MPSP = conc_aqueous_broth.price = BDO_tea.solve_price(conc_aqueous_broth)\n    return MPSP\n\n# vapor_fractions = np.linspace(0.20, 0.80)\n# titers = calculate_titer(vapor_fractions)\n# MPSPs = calculate_MPSP(vapor_fractions)\n# import matplotlib.pyplot as plt\n# plt.plot(vapor_fractions, titers)\n# plt.show()\n\n# plt.plot(titers, MPSPs)\n# plt.show()   \n\n# %%\n\n# =============================================================================\n# Life cycle analysis (LCA), waste disposal emission not included\n# =============================================================================\n\n# 100-year global warming potential (GWP) from material flows\nLCA_streams = TEA_feeds.copy()\nLCA_stream = Stream('LCA_stream', units='kg/hr')\n\nget_Isobutanol_GWP = lambda: 0.\nget_Isobutanol_FEC = lambda: 0.\n\ndef get_material_GWP():\n    LCA_stream.mass = sum(i.mass for i in LCA_streams)\n    chemical_GWP = LCA_stream.mass*CFs['GWP_CF_stream'].mass\n    # feedstock_GWP = feedstock.F_mass*CFs['GWP_CFs']['Corn stover']\n    return chemical_GWP.sum()/conc_aqueous_broth.F_mass\n\n# GWP from combustion of non-biogenic carbons\nget_non_bio_GWP = lambda: (s.natural_gas.get_atomic_flow('C') \n                           + s.oleyl_alcohol.get_atomic_flow('C')) \\\n                           * BDO_chemicals.CO2.MW / conc_aqueous_broth.F_mass\n\n# GWP from electricity\nget_electricity_use = lambda: sum(i.power_utility.rate for i in BDO_sys.units)\nget_electricity_GWP = lambda: get_electricity_use()*CFs['GWP_CFs']['Electricity'] \\\n    / conc_aqueous_broth.F_mass\n\n# CO2 fixed in lactic acid product\nget_fixed_GWP = lambda: \\\n    conc_aqueous_broth.get_atomic_flow('C')*BDO_chemicals.CO2.MW/conc_aqueous_broth.F_mass\n\nget_GWP = lambda: get_material_GWP()+get_non_bio_GWP()+get_electricity_GWP() - get_Isobutanol_GWP()\n\n# Fossil energy consumption (FEC) from materials\ndef get_material_FEC():\n    LCA_stream.mass = sum(i.mass for i in LCA_streams)\n    chemical_FEC = LCA_stream.mass*CFs['FEC_CF_stream'].mass\n    # feedstock_FEC = feedstock.F_mass*CFs['FEC_CFs']['Corn stover']\n    return chemical_FEC.sum()/conc_aqueous_broth.F_mass\n\n# FEC from electricity\nget_electricity_FEC = lambda: \\\n    get_electricity_use()*CFs['FEC_CFs']['Electricity']/conc_aqueous_broth.F_mass\n\n# Total FEC\nget_FEC = lambda: get_material_FEC() + get_electricity_FEC() - get_Isobutanol_FEC()\n\nget_SPED = lambda: u.BT.system_heating_demand*0.001/conc_aqueous_broth.F_mass\nconc_aqueous_broth_LHV = 31.45 # MJ/kg conc_aqueous_broth\n\nBDO_lca = LCA(BDO_sys, BDO_chemicals, CFs, feedstock, 'Corn stover', conc_aqueous_broth, [CT, CWP], BT=BT, CT=CT)\n\n#%% TEA breakdown\ndef TEA_breakdown():\n    metric_breakdowns = {i.name: {} for i in unit_groups[0].metrics}\n    for ug in unit_groups:\n        for metric in ug.metrics:\n            # storage_metric_val = None\n            if not ug.name=='storage':\n                if ug.name=='other facilities':\n                    metric_breakdowns[metric.name]['storage and ' + ug.name] = metric() + unit_groups[5].metrics[ug.metrics.index(metric)]()\n                else:\n                    metric_breakdowns[metric.name][ug.name] = metric()\n            # else:\n            #     storage_metric_val = metric()\n                \n    # return metric_breakdowns\n    for i in unit_groups[0].metrics:\n        print(f\"\\n\\n----- {i.name} ({i.units}) -----\")\n        metric_breakdowns_i = metric_breakdowns[i.name]\n        for j in metric_breakdowns_i.keys():\n            print(f\"{j}: {format(metric_breakdowns_i[j], '.3f')}\")\n\n# %% LCA breakdown\n\ndef FEC_breakdown():\n    return {\n        'feedstock': BDO_lca.feedstock_FEC,\n        'heating demand': BDO_lca.heating_demand_FEC,\n        'cooling demand': BDO_lca.cooling_demand_FEC,\n        'electricity demand (non-cooling)': BDO_lca.electricity_demand_non_cooling_FEC,\n        'other materials': BDO_lca.material_FEC,\n    }\n\ndef GWP_breakdown():\n    return {\n        'feedstock': BDO_lca.FGHTP_GWP,\n        'heating demand': BDO_lca.heating_demand_GWP,\n        'cooling demand': BDO_lca.cooling_demand_GWP,\n        'electricity demand (non-cooling)': BDO_lca.electricity_demand_non_cooling_GWP,\n        'other direct non-biogenic emissions': BDO_lca.non_BT_direct_emissions_GWP,\n        'other materials': BDO_lca.material_GWP,\n    }\n\n\n# %% Full analysis\nget_conc_aqueous_broth_MPSP()\n\nR302 = flowsheet('R302')\nset_target_BDO_x(250e-6)\n# Overall yield assuming yield on xylose is 80% of yield on glucose:\n# (0.64*0.36+0.36*0.8*0.36) * 2 = 0.33408 * 2\n# saccharified stream mass ratio of glucose:xylose is 0.64:0.36\n\n\n# to achieve $1.98/kg: spec_1=0.353*2\nspec.load_specifications(0.33408*2, 109.9, 1.0)\n\ndef print_recycles():\n    sys = BDO_sys.copy()\n    sys.flatten()\n    for i in sys.recycle:\n        print(i, i.imass['OleylAlcohol'] / 1e3)\n\ndef print_capital_cost():\n    print('TCI', BDO_tea.TCI / 1e6, 'MM$')\n    print('Fermentation installed cost', u.R302.installed_cost / 1e6, 'MM$')\n    print(u.R302.results())\n\ndef print_specs():\n    print(spec.spec_1, spec.spec_2, spec.spec_3)\n\ndef simulate_and_print():\n    get_conc_aqueous_broth_MPSP()\n    print('\\n---------- Simulation Results ----------')\n    # print_recycles()\n    # print_specs()\n    # print_capital_cost()\n    print(f'MPSP is ${get_conc_aqueous_broth_MPSP():.3f}/kg')\n    print(f'GWP is {BDO_lca.GWP:.3f} kg CO2-eq/kg conc_aqueous_broth')\n    # print(f'Non-bio GWP is {():.3f} kg CO2-eq/kg conc_aqueous_broth')\n    print(f'FEC is {BDO_lca.FEC:.2f} MJ/kg conc_aqueous_broth or {get_FEC()/conc_aqueous_broth_LHV:.2f} MJ/MJ conc_aqueous_broth')\n    # print(f'SPED is {get_SPED():.2f} MJ/kg conc_aqueous_broth or {get_SPED()/conc_aqueous_broth_LHV:.2f} MJ/MJ conc_aqueous_broth')\n    print('--------------------\\n')\n\nsimulate_and_print()\n# spec.load_specifications(0.36, 13.7, 1.0)\n# simulate_and_print()\n# spec.load_specifications(0.36, 109.9, 1.0)\n# simulate_and_print()\n\n# %% Maximum BDO titer (given by maximum sugar concentration)\n\n\n\n# %%% conc_aqueous_broth environmental impacts\n\n# GREET 2020:\n#     GHG100 = 1.04 kgCO2-eq/kg\n#     FEC = 43 MJ/kg\n# Ecoinvent 3.7.1:\n#     IPCC 2013 GWP100 = 1.9166 kgCO2-eq/kg\n#     CED-f = 58.707 MJ/kg\n\n# %%\n\n# =============================================================================\n# For Monte Carlo and analyses\n# =============================================================================\n\n# BDO_sub_sys = {\n#     'feedstock_sys': (U101,),\n#     'pretreatment_sys': (T201, M201, M202, M203, \n#                          R201, R201_H, T202, T203,\n#                          F201, F201_H,\n#                          M204, T204, T204_P,\n#                          M205, M205_P),\n#     'conversion_sys': (H301, M301, M302, R301, R302, T301),\n    # 'separation_sys': (u.S401, u.M401, u.M401_P,\n    #                     u.S402, \n    #                     # F401, F401_H, F401_P,\n    #                     u.D401, u.D401_H, u.D401_P, u.S403,\n    #                     u.M402_P, u.S403,\n    #                     u.D403, u.D403_H, u.D403_P,\n    #                     u.M501,\n    #                     u.T606, u.T606_P)\n                        # F402, F402_H, F402_P,\n                        # D405, D405_H1, D405_H2, D405_P,\n                        # M401, M401_P)\n#     'wastewater_sys': (M501, WWT_cost, R501,\n#                        M502, R502, S501, S502, M503,\n#                        M504, S503, S504, M505),\n#     'HXN': (HXN,),\n#     'BT': (BT,),\n#     'CT': (CT,),\n#     'other_facilities': (T601, S601,\n#                          T602, T603,\n#                          T604, T604_P,\n#                          T605, T605_P,\n#                          T606, T606_P,\n#                          PWC, CIP, ADP, FWT)\n    # }\n\n\n\n\n", "meta": {"hexsha": "9c552353811c9079fed9657b8f8f612f988860ee", "size": 17275, "ext": "py", "lang": "Python", "max_stars_repo_path": "BioSTEAM 2.x.x/biorefineries/BDO/system_broth.py", "max_stars_repo_name": "yoelcortes/Bioindustrial-Complex", "max_stars_repo_head_hexsha": "d39edfec88e443ef7a62218ca0215e3b105f4b96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-03T21:04:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-09T01:15:48.000Z", "max_issues_repo_path": "BioSTEAM 2.x.x/biorefineries/BDO/system_broth.py", "max_issues_repo_name": "yoelcortes/Bioindustrial-Complex", "max_issues_repo_head_hexsha": "d39edfec88e443ef7a62218ca0215e3b105f4b96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-01-03T21:31:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-28T13:53:56.000Z", "max_forks_repo_path": "BioSTEAM 2.x.x/biorefineries/BDO/system_broth.py", "max_forks_repo_name": "yoelcortes/Bioindustrial-Complex", "max_forks_repo_head_hexsha": "d39edfec88e443ef7a62218ca0215e3b105f4b96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-07T14:04:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-08T23:05:25.000Z", "avg_line_length": 35.9147609148, "max_line_length": 199, "alphanum_fraction": 0.6475253256, "include": true, "reason": "import numpy", "num_tokens": 5133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306515, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.19089758974001333}}
{"text": "# -*- coding: utf-8 -*-\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n#\n# LICENSE\n#\n# Copyright (C) 2010-2018 GEM Foundation, G. Weatherill, M. Pagani,\n# D. Monelli.\n#\n# The Hazard Modeller's Toolkit is free software: you can redistribute\n# it and/or modify it under the terms of the GNU Affero General Public\n# License as published by the Free Software Foundation, either version\n# 3 of the License, or (at your option) any later version.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>\n#\n# DISCLAIMER\n#\n# The software Hazard Modeller's Toolkit (openquake.hmtk) provided herein\n# is released as a prototype implementation on behalf of\n# scientists and engineers working within the GEM Foundation (Global\n# Earthquake Model).\n#\n# It is distributed for the purpose of open collaboration and in the\n# hope that it will be useful to the scientific, engineering, disaster\n# risk and software design communities.\n#\n# The software is NOT distributed as part of GEM’s OpenQuake suite\n# (https://www.globalquakemodel.org/tools-products) and must be considered as a\n# separate entity. The software provided herein is designed and implemented\n# by scientific staff. It is not developed to the design standards, nor\n# subject to same level of critical review by professional software\n# developers, as GEM’s OpenQuake software suite.\n#\n# Feedback and contribution to the software is welcome, and can be\n# directed to the hazard scientific staff of the GEM Model Facility\n# (hazard@globalquakemodel.org).\n#\n# The Hazard Modeller's Toolkit (openquake.hmtk) is therefore distributed WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n# for more details.\n#\n# The GEM Foundation, and the authors of the software, assume no\n# liability for use of the software.\n\nimport numpy as np\n\nfrom openquake.hmtk.seismicity.declusterer.base import (\n    BaseCatalogueDecluster, DECLUSTERER_METHODS)\nfrom openquake.hmtk.seismicity.utils import decimal_year, haversine\nfrom openquake.hmtk.seismicity.declusterer.distance_time_windows import (\n    TIME_DISTANCE_WINDOW_FUNCTIONS)\n\n\n@DECLUSTERER_METHODS.add(\n    \"decluster\",\n    time_distance_window=TIME_DISTANCE_WINDOW_FUNCTIONS,\n    time_window=np.float)\nclass Afteran(BaseCatalogueDecluster):\n    \"\"\"\n    This implements the Afteran algorithm as described in this paper:\n    Musson, R. (1999), Probabilistic seismic hazard maps for the North\n    Balkan Region, Annali Di Geofisica, 42(6), 1109 - 1124\n    \"\"\"\n\n    def decluster(self, catalogue, config):\n        \"\"\"\n        catalogue_matrix, window_opt=TDW_GARDNERKNOPOFF, time_window=60.):\n\n        :param catalogue: a catalogue object\n        :type catalogue: Instance of the openquake.hmtk.seismicity.catalogue.Catalogue()\n                         class\n        :keyword window_opt: method used in calculating distance and time\n            windows\n        :type window_opt: string\n        :keyword time_window: Length (in days) of moving time window\n        :type time_window: positive float\n        :returns: **vcl vector** indicating cluster number,\n                  **flagvector** indicating which earthquakes belong to a\n                  cluster\n        :rtype: numpy.ndarray\n        \"\"\"\n        # Convert time window from days to decimal years\n        time_window = config['time_window'] / 365.\n        # Pre-processing steps are the same as for Gardner & Knopoff\n        # Get relevent parameters\n        mag = catalogue.data['magnitude']\n        neq = np.shape(mag)[0]  # Number of earthquakes\n        # Get decimal year (needed for time windows)\n        year_dec = decimal_year(catalogue.data['year'],\n                                catalogue.data['month'],\n                                catalogue.data['day'])\n        # Get space windows corresponding to each event\n        sw_space, _ = (\n            config['time_distance_window'].calc(catalogue.data['magnitude']))\n\n        # Pre-allocate cluster index vectors\n        vcl = np.zeros(neq, dtype=int)\n        flagvector = np.zeros(neq, dtype=int)\n        # Rank magnitudes into descending order\n        id0 = np.flipud(np.argsort(mag, kind='heapsort'))\n\n        clust_index = 0\n        for imarker in id0:\n            # Earthquake not allocated to cluster - perform calculation\n            if vcl[imarker] == 0:\n                # Perform distance calculation\n                mdist = haversine(\n                    catalogue.data['longitude'],\n                    catalogue.data['latitude'],\n                    catalogue.data['longitude'][imarker],\n                    catalogue.data['latitude'][imarker]).flatten()\n\n                # Select earthquakes inside distance window, later than\n                # mainshock and not already assigned to a cluster\n                vsel1 = np.where(\n                    np.logical_and(vcl == 0,\n                                   np.logical_and(\n                                       mdist <= sw_space[imarker],\n                                       year_dec > year_dec[imarker])))[0]\n                has_aftershocks = False\n                if len(vsel1) > 0:\n                    # Earthquakes after event inside distance window\n                    temp_vsel1, has_aftershocks = self._find_aftershocks(\n                        vsel1,\n                        year_dec,\n                        time_window,\n                        imarker,\n                        neq)\n                    if has_aftershocks:\n                        flagvector[temp_vsel1] = 1\n                        vcl[temp_vsel1] = clust_index + 1\n\n                # Select earthquakes inside distance window, earlier than\n                # mainshock and not already assigned to a cluster\n                has_foreshocks = False\n                vsel2 = np.where(\n                    np.logical_and(\n                        vcl == 0,\n                        np.logical_and(mdist <= sw_space[imarker],\n                                       year_dec < year_dec[imarker])))[0]\n                if len(vsel2) > 0:\n                    # Earthquakes before event inside distance window\n                    temp_vsel2, has_foreshocks = self._find_foreshocks(\n                        vsel2,\n                        year_dec,\n                        time_window,\n                        imarker,\n                        neq)\n                    if has_foreshocks:\n                        flagvector[temp_vsel2] = -1\n                        vcl[temp_vsel2] = clust_index + 1\n\n                if has_aftershocks or has_foreshocks:\n                    # Assign mainshock to cluster\n                    vcl[imarker] = clust_index + 1\n                    clust_index += 1\n\n        return vcl, flagvector\n\n    def _find_aftershocks(self, vsel, year_dec, time_window, imarker, neq):\n        '''\n        Function to identify aftershocks from a set of potential\n        events inside the distance window of an earthquake.\n        :param vsel: Pointer vector to the location of the events in distance\n                     window\n        :type vsel: numpy.ndarray\n        :param year_dec: Vector of decimal catalogue event times\n        :type year_dec: numpy.ndarray\n        :param time_window: Moving time window for selection of time clusters\n        :type time_window: float\n        :param imarker: Index of the mainshock in the catalogue vector\n        :type imarker: Integer\n        :param neq: Number of events in distance window of mainshock\n        :type neq: Integer\n        '''\n        temp_vsel1 = np.zeros(neq, dtype=bool)\n        has_aftershocks = False\n\n        # Finds the time difference between events\n        delta_time = np.diff(\n            np.hstack([year_dec[imarker], year_dec[vsel]]))\n        for iloc in range(0, len(vsel)):\n            # If time difference between event is smaller than\n            # time window - is an aftershock -> continue\n\n            if delta_time[iloc] < time_window:\n                temp_vsel1[vsel[iloc]] = True\n                has_aftershocks = True\n            else:\n                # Time difference between events is larger than\n                # window -> no more aftershocks -> return\n                return temp_vsel1, has_aftershocks\n\n        return temp_vsel1, has_aftershocks\n\n    def _find_foreshocks(self, vsel, year_dec, time_window, imarker, neq):\n        '''\n        Finds foreshocks from a set of potential events within\n        the distance window of a mainshock.\n        :param vsel: Pointer vector to the location of the events in distance\n                     window\n        :type vsel: numpy.ndarray\n        :param year_dec: Vector of decimal catalogue event times\n        :type year_dec: numpy.ndarray\n        :param time_window: Moving time window for selection of time clusters\n        :type time_window: float\n        :param imarker: Index of the mainshock in the catalogue vector\n        :type imarker: Integer\n        :param neq: Number of events in distance window of mainshock\n        :type neq: Integer\n        '''\n\n        temp_vsel2 = np.zeros(neq, dtype=bool)\n        has_foreshocks = False\n\n        # The initial time is the time of the mainshock\n        initial_time = year_dec[imarker]\n        year_dec = year_dec[vsel]\n        for jloc in range(len(vsel) - 1, -1, -1):\n            # If the time between the mainshock and the preceeding\n            # event is smaller than the time_window then event\n            # is a foreshock\n\n            if (initial_time - year_dec[jloc]) < time_window:\n                temp_vsel2[vsel[jloc]] = True\n                has_foreshocks = True\n                # Update target time to consider current foreshock\n                # Then continue\n                initial_time = year_dec[jloc]\n            else:\n                # No events inside time window\n                # end of foreshock sequence - return\n                return temp_vsel2, has_foreshocks\n\n        return temp_vsel2, has_foreshocks\n", "meta": {"hexsha": "3536056b7535f3e05be260f13c2beccf10a07146", "size": 10043, "ext": "py", "lang": "Python", "max_stars_repo_path": "openquake/hmtk/seismicity/declusterer/dec_afteran.py", "max_stars_repo_name": "gfzriesgos/shakyground-lfs", "max_stars_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-01T00:28:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-01T00:28:24.000Z", "max_issues_repo_path": "openquake/hmtk/seismicity/declusterer/dec_afteran.py", "max_issues_repo_name": "gfzriesgos/shakyground-lfs", "max_issues_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-08-31T14:14:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-11T12:53:13.000Z", "max_forks_repo_path": "openquake/hmtk/seismicity/declusterer/dec_afteran.py", "max_forks_repo_name": "gfzriesgos/shakyground-lfs", "max_forks_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-08-31T14:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-17T10:06:02.000Z", "avg_line_length": 42.0209205021, "max_line_length": 88, "alphanum_fraction": 0.6089813801, "include": true, "reason": "import numpy", "num_tokens": 2234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.1908955928943983}}
{"text": "# Helper functions for running autoencoder\n\nimport os\nimport argparse\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\n# To ensure reproducibility using Keras during development\n# https://keras.io/getting-started/faq/#how-can-i-obtain-reproducible-results-using-keras-during-development\nimport numpy as np\nimport random as rn\n\n# The below is necessary in Python 3.2.3 onwards to\n# have reproducible behavior for certain hash-based operations.\n# See these references for further details:\n# https://docs.python.org/3.4/using/cmdline.html#envvar-PYTHONHASHSEED\n# https://github.com/keras-team/keras/issues/2280#issuecomment-306959926\nrandomState = 123\nimport os\nos.environ['PYTHONHASHSEED'] = '0'\n\n# The below is necessary for starting Numpy generated random numbers\n# in a well-defined initial state.\n\nnp.random.seed(42)\n\n# The below is necessary for starting core Python generated random numbers\n# in a well-defined state.\n\nrn.seed(12345)\n\n# Force TensorFlow to use single thread.\n# Multiple threads are a potential source of\n# non-reproducible results.\n# For further details, see: https://stackoverflow.com/questions/42022950/which-seeds-have-to-be-set-where-to-realize-100-reproducibility-of-training-res\n\nsession_conf = tf.ConfigProto(\n    intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)\n\nfrom keras import backend as K\n\n# The below tf.set_random_seed() will make random number generation\n# in the TensorFlow backend have a well-defined initial state.\n# For further details, see: https://www.tensorflow.org/api_docs/python/tf/set_random_seed\n\ntf.set_random_seed(1234)\n\nsess = tf.Session(graph=tf.get_default_graph(), config=session_conf)\nK.set_session(sess)\n\nfrom keras.layers import Input, Dense, Lambda, Layer, Activation\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.models import Model, Sequential\nfrom keras import metrics, optimizers\nfrom keras.callbacks import Callback\n\n# Functions\n#\n# Based on publication by Way et. al. (https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5728678/)\n# Github repo (https://github.com/greenelab/tybalt/blob/master/scripts/vae_pancancer.py)\n\n\n# Function for reparameterization trick to make model differentiable\n\n\ndef sampling_maker(epsilon_std):\n    def sampling(args):\n        # Function with args required for Keras Lambda function\n        z_mean, z_log_var = args\n\n        # Draw epsilon of the same shape from a standard normal distribution\n        epsilon = K.random_normal(shape=tf.shape(z_mean), mean=0.,\n                                  stddev=epsilon_std)\n\n        # The latent vector is non-deterministic and differentiable\n        # in respect to z_mean and z_log_var\n        z = z_mean + K.exp(z_log_var / 2) * epsilon\n        return z\n    return sampling\n\n\nclass CustomVariationalLayer(Layer):\n    \"\"\"\n    Define a custom layer that learns and performs the training\n    \"\"\"\n\n    def __init__(self, original_dim, z_log_var_encoded,\n                 z_mean_encoded, beta, **kwargs):\n        # https://keras.io/layers/writing-your-own-keras-layers/\n        self.is_placeholder = True\n        self.original_dim = original_dim\n        self.z_log_var_encoded = z_log_var_encoded\n        self.z_mean_encoded = z_mean_encoded\n        self.beta = beta\n\n        super(CustomVariationalLayer, self).__init__(**kwargs)\n\n    def vae_loss(self, x_input, x_decoded):\n        reconstruction_loss = self.original_dim * \\\n            metrics.binary_crossentropy(x_input, x_decoded)\n        \n        kl_loss = - 0.5 * K.sum(1 + self.z_log_var_encoded \n                                - K.square(self.z_mean_encoded) \n                                - K.exp(self.z_log_var_encoded), axis=-1)\n        \n        return K.mean(reconstruction_loss + (K.get_value(self.beta) * kl_loss))\n\n    def call(self, inputs):\n        x = inputs[0]\n        x_decoded = inputs[1]\n        loss = self.vae_loss(x, x_decoded)\n        self.add_loss(loss, inputs=inputs)\n        # We won't actually use the output.\n        return x\n\n\nclass WarmUpCallback(Callback):\n    def __init__(self, beta, kappa):\n        self.beta = beta\n        self.kappa = kappa\n\n    # Behavior on each epoch\n    def on_epoch_end(self, epoch, logs={}):\n        if K.get_value(self.beta) <= 1:\n            K.set_value(self.beta, K.get_value(self.beta) + self.kappa)\n", "meta": {"hexsha": "6fac04b808c6527b91cc29f97f88a4236f5887be", "size": 4316, "ext": "py", "lang": "Python", "max_stars_repo_path": "archive/scripts/functions/helper_ae.py", "max_stars_repo_name": "ajlee21/Batch_effects_simulation", "max_stars_repo_head_hexsha": "d707321346de48de5e63cf251280bdf9372be59c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-05-04T15:16:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-28T04:49:21.000Z", "max_issues_repo_path": "archive/scripts/functions/helper_ae.py", "max_issues_repo_name": "ajlee21/Batch_effects_simulation", "max_issues_repo_head_hexsha": "d707321346de48de5e63cf251280bdf9372be59c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-02-27T20:12:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T20:28:35.000Z", "max_forks_repo_path": "archive/scripts/functions/helper_ae.py", "max_forks_repo_name": "ajlee21/Batch_effects_simulation", "max_forks_repo_head_hexsha": "d707321346de48de5e63cf251280bdf9372be59c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-06-02T18:29:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T09:33:37.000Z", "avg_line_length": 33.9842519685, "max_line_length": 152, "alphanum_fraction": 0.7099165894, "include": true, "reason": "import numpy", "num_tokens": 1013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.19089559289439825}}
{"text": "# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\n\"\"\"\nThis module implements a FloatWithUnit, which is a subclass of float. It\nalso defines supported units for some commonly used units for energy, length,\ntemperature, time and charge. FloatWithUnit also support conversion to one\nanother, and additions and subtractions perform automatic conversion if\nunits are detected. An ArrayWithUnit is also implemented, which is a subclass\nof numpy's ndarray with similar unit features.\n\"\"\"\n\nimport collections\nimport numbers\nfrom functools import partial\n\nimport numpy as np\nimport scipy.constants as const\n\n__author__ = \"Shyue Ping Ong, Matteo Giantomassi\"\n__copyright__ = \"Copyright 2011, The Materials Project\"\n__version__ = \"1.0\"\n__maintainer__ = \"Shyue Ping Ong, Matteo Giantomassi\"\n__status__ = \"Production\"\n__date__ = \"Aug 30, 2013\"\n\n\"\"\"\nSome conversion factors\n\"\"\"\nHa_to_eV = 1 / const.physical_constants[\"electron volt-hartree relationship\"][0]\neV_to_Ha = 1 / Ha_to_eV\nRy_to_eV = Ha_to_eV / 2\namu_to_kg = const.physical_constants[\"atomic mass unit-kilogram relationship\"][0]\nmile_to_meters = const.mile\nbohr_to_angstrom = const.physical_constants[\"Bohr radius\"][0] * 1e10\nbohr_to_ang = bohr_to_angstrom\nang_to_bohr = 1 / bohr_to_ang\nkCal_to_kJ = const.calorie\nkb = const.physical_constants[\"Boltzmann constant in eV/K\"][0]\n\n\"\"\"\nDefinitions of supported units. Values below are essentially scaling and\nconversion factors. What matters is the relative values, not the absolute.\nThe SI units must have factor 1.\n\"\"\"\nBASE_UNITS = {\n    \"length\": {\n        \"m\": 1,\n        \"km\": 1000,\n        \"mile\": mile_to_meters,\n        \"ang\": 1e-10,\n        \"cm\": 1e-2,\n        \"pm\": 1e-12,\n        \"bohr\": bohr_to_angstrom * 1e-10,\n    },\n    \"mass\": {\n        \"kg\": 1,\n        \"g\": 1e-3,\n        \"amu\": amu_to_kg,\n    },\n    \"time\": {\n        \"s\": 1,\n        \"min\": 60,\n        \"h\": 3600,\n        \"d\": 3600 * 24,\n    },\n    \"current\": {\"A\": 1},\n    \"temperature\": {\n        \"K\": 1,\n    },\n    \"amount\": {\"mol\": 1, \"atom\": 1 / const.N_A},\n    \"intensity\": {\"cd\": 1},\n    \"memory\": {\n        \"byte\": 1,\n        \"Kb\": 1024,\n        \"Mb\": 1024**2,\n        \"Gb\": 1024**3,\n        \"Tb\": 1024**4,\n    },\n}\n\n# Accept kb, mb, gb ... as well.\nBASE_UNITS[\"memory\"].update({k.lower(): v for k, v in BASE_UNITS[\"memory\"].items()})\n\n# This current list are supported derived units defined in terms of powers of\n# SI base units and constants.\nDERIVED_UNITS = {\n    \"energy\": {\n        \"eV\": {\"kg\": 1, \"m\": 2, \"s\": -2, const.e: 1},\n        \"meV\": {\"kg\": 1, \"m\": 2, \"s\": -2, const.e * 1e-3: 1},\n        \"Ha\": {\"kg\": 1, \"m\": 2, \"s\": -2, const.e * Ha_to_eV: 1},\n        \"Ry\": {\"kg\": 1, \"m\": 2, \"s\": -2, const.e * Ry_to_eV: 1},\n        \"J\": {\"kg\": 1, \"m\": 2, \"s\": -2},\n        \"kJ\": {\"kg\": 1, \"m\": 2, \"s\": -2, 1000: 1},\n        \"kCal\": {\"kg\": 1, \"m\": 2, \"s\": -2, 1000: 1, kCal_to_kJ: 1},\n    },\n    \"charge\": {\n        \"C\": {\"A\": 1, \"s\": 1},\n        \"e\": {\"A\": 1, \"s\": 1, const.e: 1},\n    },\n    \"force\": {\n        \"N\": {\"kg\": 1, \"m\": 1, \"s\": -2},\n        \"KN\": {\"kg\": 1, \"m\": 1, \"s\": -2, 1000: 1},\n        \"MN\": {\"kg\": 1, \"m\": 1, \"s\": -2, 1e6: 1},\n        \"GN\": {\"kg\": 1, \"m\": 1, \"s\": -2, 1e9: 1},\n    },\n    \"frequency\": {\n        \"Hz\": {\"s\": -1},\n        \"KHz\": {\"s\": -1, 1000: 1},\n        \"MHz\": {\"s\": -1, 1e6: 1},\n        \"GHz\": {\"s\": -1, 1e9: 1},\n        \"THz\": {\"s\": -1, 1e12: 1},\n    },\n    \"pressure\": {\n        \"Pa\": {\"kg\": 1, \"m\": -1, \"s\": -2},\n        \"KPa\": {\"kg\": 1, \"m\": -1, \"s\": -2, 1000: 1},\n        \"MPa\": {\"kg\": 1, \"m\": -1, \"s\": -2, 1e6: 1},\n        \"GPa\": {\"kg\": 1, \"m\": -1, \"s\": -2, 1e9: 1},\n    },\n    \"power\": {\n        \"W\": {\"m\": 2, \"kg\": 1, \"s\": -3},\n        \"KW\": {\"m\": 2, \"kg\": 1, \"s\": -3, 1000: 1},\n        \"MW\": {\"m\": 2, \"kg\": 1, \"s\": -3, 1e6: 1},\n        \"GW\": {\"m\": 2, \"kg\": 1, \"s\": -3, 1e9: 1},\n    },\n    \"emf\": {\"V\": {\"m\": 2, \"kg\": 1, \"s\": -3, \"A\": -1}},\n    \"capacitance\": {\"F\": {\"m\": -2, \"kg\": -1, \"s\": 4, \"A\": 2}},\n    \"resistance\": {\"ohm\": {\"m\": 2, \"kg\": 1, \"s\": -3, \"A\": -2}},\n    \"conductance\": {\"S\": {\"m\": -2, \"kg\": -1, \"s\": 3, \"A\": 2}},\n    \"magnetic_flux\": {\"Wb\": {\"m\": 2, \"kg\": 1, \"s\": -2, \"A\": -1}},\n    \"cross_section\": {\"barn\": {\"m\": 2, 1e-28: 1}, \"mbarn\": {\"m\": 2, 1e-31: 1}},\n}\n\nALL_UNITS = dict(list(BASE_UNITS.items()) + list(DERIVED_UNITS.items()))  # type: ignore\nSUPPORTED_UNIT_NAMES = tuple(i for d in ALL_UNITS.values() for i in d.keys())\n\n# Mapping unit name --> unit type (unit names must be unique).\n_UNAME2UTYPE = {}  # type: ignore\nfor utype, d in ALL_UNITS.items():\n    assert not set(d.keys()).intersection(_UNAME2UTYPE.keys())\n    _UNAME2UTYPE.update({uname: utype for uname in d})\ndel utype, d\n\n\ndef _get_si_unit(unit):\n    unit_type = _UNAME2UTYPE[unit]\n    si_unit = filter(lambda k: BASE_UNITS[unit_type][k] == 1, BASE_UNITS[unit_type].keys())\n    return list(si_unit)[0], BASE_UNITS[unit_type][unit]\n\n\nclass UnitError(BaseException):\n    \"\"\"\n    Exception class for unit errors.\n    \"\"\"\n\n\ndef _check_mappings(u):\n    for v in DERIVED_UNITS.values():\n        for k2, v2 in v.items():\n            if all(v2.get(ku, 0) == vu for ku, vu in u.items()) and all(\n                u.get(kv2, 0) == vv2 for kv2, vv2 in v2.items()\n            ):\n                return {k2: 1}\n    return u\n\n\nclass Unit(collections.abc.Mapping):\n    \"\"\"\n    Represents a unit, e.g., \"m\" for meters, etc. Supports compound units.\n    Only integer powers are supported for units.\n    \"\"\"\n\n    Error = UnitError\n\n    def __init__(self, unit_def):\n        \"\"\"\n        Constructs a unit.\n\n        Args:\n            unit_def: A definition for the unit. Either a mapping of unit to\n                powers, e.g., {\"m\": 2, \"s\": -1} represents \"m^2 s^-1\",\n                or simply as a string \"kg m^2 s^-1\". Note that the supported\n                format uses \"^\" as the power operator and all units must be\n                space-separated.\n        \"\"\"\n\n        if isinstance(unit_def, str):\n            unit = collections.defaultdict(int)\n            import re\n\n            for m in re.finditer(r\"([A-Za-z]+)\\s*\\^*\\s*([\\-0-9]*)\", unit_def):\n                p = m.group(2)\n                p = 1 if not p else int(p)\n                k = m.group(1)\n                unit[k] += p\n        else:\n            unit = {k: v for k, v in dict(unit_def).items() if v != 0}\n        self._unit = _check_mappings(unit)\n\n    def __mul__(self, other):\n        new_units = collections.defaultdict(int)\n        for k, v in self.items():\n            new_units[k] += v\n        for k, v in other.items():\n            new_units[k] += v\n        return Unit(new_units)\n\n    def __rmul__(self, other):\n        return self.__mul__(other)\n\n    def __div__(self, other):\n        new_units = collections.defaultdict(int)\n        for k, v in self.items():\n            new_units[k] += v\n        for k, v in other.items():\n            new_units[k] -= v\n        return Unit(new_units)\n\n    def __truediv__(self, other):\n        return self.__div__(other)\n\n    def __pow__(self, i):\n        return Unit({k: v * i for k, v in self.items()})\n\n    def __iter__(self):\n        return self._unit.__iter__()\n\n    def __getitem__(self, i):\n        return self._unit[i]\n\n    def __len__(self):\n        return len(self._unit)\n\n    def __repr__(self):\n        sorted_keys = sorted(self._unit.keys(), key=lambda k: (-self._unit[k], k))\n        return \" \".join(\n            [f\"{k}^{self._unit[k]}\" if self._unit[k] != 1 else k for k in sorted_keys if self._unit[k] != 0]\n        )\n\n    def __str__(self):\n        return self.__repr__()\n\n    @property\n    def as_base_units(self):\n        \"\"\"\n        Converts all units to base SI units, including derived units.\n\n        Returns:\n            (base_units_dict, scaling factor). base_units_dict will not\n            contain any constants, which are gathered in the scaling factor.\n        \"\"\"\n        b = collections.defaultdict(int)\n        factor = 1\n        for k, v in self.items():\n            derived = False\n            for d in DERIVED_UNITS.values():\n                if k in d:\n                    for k2, v2 in d[k].items():\n                        if isinstance(k2, numbers.Number):\n                            factor *= k2 ** (v2 * v)\n                        else:\n                            b[k2] += v2 * v\n                    derived = True\n                    break\n            if not derived:\n                si, f = _get_si_unit(k)\n                b[si] += v\n                factor *= f**v\n        return {k: v for k, v in b.items() if v != 0}, factor\n\n    def get_conversion_factor(self, new_unit):\n        \"\"\"\n        Returns a conversion factor between this unit and a new unit.\n        Compound units are supported, but must have the same powers in each\n        unit type.\n\n        Args:\n            new_unit: The new unit.\n        \"\"\"\n        uo_base, ofactor = self.as_base_units\n        un_base, nfactor = Unit(new_unit).as_base_units\n        units_new = sorted(un_base.items(), key=lambda d: _UNAME2UTYPE[d[0]])\n        units_old = sorted(uo_base.items(), key=lambda d: _UNAME2UTYPE[d[0]])\n        factor = ofactor / nfactor\n        for uo, un in zip(units_old, units_new):\n            if uo[1] != un[1]:\n                raise UnitError(f\"Units {uo} and {un} are not compatible!\")\n            c = ALL_UNITS[_UNAME2UTYPE[uo[0]]]\n            factor *= (c[uo[0]] / c[un[0]]) ** uo[1]\n        return factor\n\n\nclass FloatWithUnit(float):\n    \"\"\"\n    Subclasses float to attach a unit type. Typically, you should use the\n    pre-defined unit type subclasses such as Energy, Length, etc. instead of\n    using FloatWithUnit directly.\n\n    Supports conversion, addition and subtraction of the same unit type. E.g.,\n    1 m + 20 cm will be automatically converted to 1.2 m (units follow the\n    leftmost quantity). Note that FloatWithUnit does not override the eq\n    method for float, i.e., units are not checked when testing for equality.\n    The reason is to allow this class to be used transparently wherever floats\n    are expected.\n\n    >>> e = Energy(1.1, \"Ha\")\n    >>> a = Energy(1.1, \"Ha\")\n    >>> b = Energy(3, \"eV\")\n    >>> c = a + b\n    >>> print(c)\n    1.2102479761938871 Ha\n    >>> c.to(\"eV\")\n    32.932522246000005 eV\n    \"\"\"\n\n    Error = UnitError\n\n    @classmethod\n    def from_string(cls, s):\n        \"\"\"\n        Initialize a FloatWithUnit from a string. Example Memory.from_string(\"1. Mb\")\n        \"\"\"\n        # Extract num and unit string.\n        s = s.strip()\n        for i, char in enumerate(s):\n            if char.isalpha() or char.isspace():\n                break\n        else:\n            raise Exception(f\"Unit is missing in string {s}\")\n        num, unit = float(s[:i]), s[i:]\n\n        # Find unit type (set it to None if it cannot be detected)\n        for unit_type, d in BASE_UNITS.items():\n            if unit in d:\n                break\n        else:\n            unit_type = None\n\n        return cls(num, unit, unit_type=unit_type)\n\n    def __new__(cls, val, unit, unit_type=None):\n        \"\"\"Overrides __new__ since we are subclassing a Python primitive/\"\"\"\n        new = float.__new__(cls, val)\n        new._unit = Unit(unit)\n        new._unit_type = unit_type\n        return new\n\n    def __init__(self, val, unit, unit_type=None):\n        \"\"\"\n        Initializes a float with unit.\n\n        Args:\n            val (float): Value\n            unit (Unit): A unit. E.g., \"C\".\n            unit_type (str): A type of unit. E.g., \"charge\"\n        \"\"\"\n        if unit_type is not None and str(unit) not in ALL_UNITS[unit_type]:\n            raise UnitError(f\"{unit} is not a supported unit for {unit_type}\")\n        self._unit = Unit(unit)\n        self._unit_type = unit_type\n\n    def __repr__(self):\n        return super().__repr__()\n\n    def __str__(self):\n        s = super().__str__()\n        return f\"{s} {self._unit}\"\n\n    def __add__(self, other):\n        if not hasattr(other, \"unit_type\"):\n            return super().__add__(other)\n        if other.unit_type != self._unit_type:\n            raise UnitError(\"Adding different types of units is not allowed\")\n        val = other\n        if other.unit != self._unit:\n            val = other.to(self._unit)\n        return FloatWithUnit(float(self) + val, unit_type=self._unit_type, unit=self._unit)\n\n    def __sub__(self, other):\n        if not hasattr(other, \"unit_type\"):\n            return super().__sub__(other)\n        if other.unit_type != self._unit_type:\n            raise UnitError(\"Subtracting different units is not allowed\")\n        val = other\n        if other.unit != self._unit:\n            val = other.to(self._unit)\n        return FloatWithUnit(float(self) - val, unit_type=self._unit_type, unit=self._unit)\n\n    def __mul__(self, other):\n        if not isinstance(other, FloatWithUnit):\n            return FloatWithUnit(float(self) * other, unit_type=self._unit_type, unit=self._unit)\n        return FloatWithUnit(float(self) * other, unit_type=None, unit=self._unit * other._unit)\n\n    def __rmul__(self, other):\n        if not isinstance(other, FloatWithUnit):\n            return FloatWithUnit(float(self) * other, unit_type=self._unit_type, unit=self._unit)\n        return FloatWithUnit(float(self) * other, unit_type=None, unit=self._unit * other._unit)\n\n    def __pow__(self, i):\n        return FloatWithUnit(float(self) ** i, unit_type=None, unit=self._unit**i)\n\n    def __truediv__(self, other):\n        val = super().__truediv__(other)\n        if not isinstance(other, FloatWithUnit):\n            return FloatWithUnit(val, unit_type=self._unit_type, unit=self._unit)\n        return FloatWithUnit(val, unit_type=None, unit=self._unit / other._unit)\n\n    def __neg__(self):\n        return FloatWithUnit(super().__neg__(), unit_type=self._unit_type, unit=self._unit)\n\n    def __getnewargs__(self):\n        \"\"\"Function used by pickle to recreate object.\"\"\"\n        # print(self.__dict__)\n        # FIXME\n        # There's a problem with _unit_type if we try to unpickle objects from file.\n        # since self._unit_type might not be defined. I think this is due to\n        # the use of decorators (property and unitized). In particular I have problems with \"amu\"\n        # likely due to weight in core.composition\n        if hasattr(self, \"_unit_type\"):\n            args = float(self), self._unit, self._unit_type\n        else:\n            args = float(self), self._unit, None\n\n        return args\n\n    def __getstate__(self):\n        state = self.__dict__.copy()\n        state[\"val\"] = float(self)\n        return state\n\n    def __setstate__(self, state):\n        self._unit = state[\"_unit\"]\n\n    @property\n    def unit_type(self) -> str:\n        \"\"\"\n        :return: The type of unit. Energy, Charge, etc.\n        \"\"\"\n        return self._unit_type\n\n    @property\n    def unit(self) -> str:\n        \"\"\"\n        :return: The unit, e.g., \"eV\".\n        \"\"\"\n        return self._unit\n\n    def to(self, new_unit):\n        \"\"\"\n        Conversion to a new_unit. Right now, only supports 1 to 1 mapping of\n        units of each type.\n\n        Args:\n            new_unit: New unit type.\n\n        Returns:\n            A FloatWithUnit object in the new units.\n\n        Example usage:\n        >>> e = Energy(1.1, \"eV\")\n        >>> e = Energy(1.1, \"Ha\")\n        >>> e.to(\"eV\")\n        29.932522246 eV\n        \"\"\"\n        return FloatWithUnit(\n            self * self.unit.get_conversion_factor(new_unit),\n            unit_type=self._unit_type,\n            unit=new_unit,\n        )\n\n    @property\n    def as_base_units(self):\n        \"\"\"\n        Returns this FloatWithUnit in base SI units, including derived units.\n\n        Returns:\n            A FloatWithUnit object in base SI units\n        \"\"\"\n        return self.to(self.unit.as_base_units[0])\n\n    @property\n    def supported_units(self):\n        \"\"\"\n        Supported units for specific unit type.\n        \"\"\"\n        return tuple(ALL_UNITS[self._unit_type].keys())\n\n\nclass ArrayWithUnit(np.ndarray):\n    \"\"\"\n    Subclasses `numpy.ndarray` to attach a unit type. Typically, you should\n    use the pre-defined unit type subclasses such as EnergyArray,\n    LengthArray, etc. instead of using ArrayWithFloatWithUnit directly.\n\n    Supports conversion, addition and subtraction of the same unit type. E.g.,\n    1 m + 20 cm will be automatically converted to 1.2 m (units follow the\n    leftmost quantity).\n\n    >>> a = EnergyArray([1, 2], \"Ha\")\n    >>> b = EnergyArray([1, 2], \"eV\")\n    >>> c = a + b\n    >>> print(c)\n    [ 1.03674933  2.07349865] Ha\n    >>> c.to(\"eV\")\n    array([ 28.21138386,  56.42276772]) eV\n    \"\"\"\n\n    Error = UnitError\n\n    def __new__(cls, input_array, unit, unit_type=None):\n        \"\"\"\n        Override __new__.\n        \"\"\"\n        # Input array is an already formed ndarray instance\n        # We first cast to be our class type\n        obj = np.asarray(input_array).view(cls)\n        # add the new attributes to the created instance\n        obj._unit = Unit(unit)\n        obj._unit_type = unit_type\n        return obj\n\n    def __array_finalize__(self, obj):\n        \"\"\"\n        See http://docs.scipy.org/doc/numpy/user/basics.subclassing.html for\n        comments.\n        \"\"\"\n        if obj is None:\n            return\n        self._unit = getattr(obj, \"_unit\", None)\n        self._unit_type = getattr(obj, \"_unit_type\", None)\n\n    @property\n    def unit_type(self) -> str:\n        \"\"\"\n        :return: The type of unit. Energy, Charge, etc.\n        \"\"\"\n        return self._unit_type\n\n    @property\n    def unit(self) -> str:\n        \"\"\"\n        :return: The unit, e.g., \"eV\".\n        \"\"\"\n        return self._unit\n\n    def __reduce__(self):\n        # print(\"in reduce\")\n        reduce = list(super().__reduce__())\n        # print(\"unit\",self._unit)\n        # print(reduce[2])\n        reduce[2] = {\"np_state\": reduce[2], \"_unit\": self._unit}\n        return tuple(reduce)\n\n    def __setstate__(self, state):\n        # pylint: disable=E1101\n        super().__setstate__(state[\"np_state\"])\n        self._unit = state[\"_unit\"]\n\n    def __repr__(self):\n        return f\"{np.array(self).__repr__()} {self.unit}\"\n\n    def __str__(self):\n        return f\"{np.array(self).__str__()} {self.unit}\"\n\n    def __add__(self, other):\n        if hasattr(other, \"unit_type\"):\n            if other.unit_type != self.unit_type:\n                raise UnitError(\"Adding different types of units is not allowed\")\n\n            if other.unit != self.unit:\n                other = other.to(self.unit)\n\n        return self.__class__(np.array(self) + np.array(other), unit_type=self.unit_type, unit=self.unit)\n\n    def __sub__(self, other):\n        if hasattr(other, \"unit_type\"):\n            if other.unit_type != self.unit_type:\n                raise UnitError(\"Subtracting different units is not allowed\")\n\n            if other.unit != self.unit:\n                other = other.to(self.unit)\n\n        return self.__class__(np.array(self) - np.array(other), unit_type=self.unit_type, unit=self.unit)\n\n    def __mul__(self, other):\n        # FIXME\n        # Here we have the most important difference between FloatWithUnit and\n        # ArrayWithFloatWithUnit:\n        # If other does not have units, I return an object with the same units\n        # as self.\n        # if other *has* units, I return an object *without* units since\n        # taking into account all the possible derived quantities would be\n        # too difficult.\n        # Moreover Energy(1.0) * Time(1.0, \"s\") returns 1.0 Ha that is a\n        # bit misleading.\n        # Same protocol for __div__\n        if not hasattr(other, \"unit_type\"):\n            return self.__class__(\n                np.array(self).__mul__(np.array(other)),\n                unit_type=self._unit_type,\n                unit=self._unit,\n            )\n        # Cannot use super since it returns an instance of self.__class__\n        # while here we want a bare numpy array.\n        return self.__class__(np.array(self).__mul__(np.array(other)), unit=self.unit * other.unit)\n\n    def __rmul__(self, other):\n        # pylint: disable=E1101\n        if not hasattr(other, \"unit_type\"):\n            return self.__class__(\n                np.array(self).__rmul__(np.array(other)),\n                unit_type=self._unit_type,\n                unit=self._unit,\n            )\n        return self.__class__(np.array(self).__rmul__(np.array(other)), unit=self.unit * other.unit)\n\n    def __div__(self, other):\n        # pylint: disable=E1101\n        if not hasattr(other, \"unit_type\"):\n            return self.__class__(\n                np.array(self).__div__(np.array(other)),\n                unit_type=self._unit_type,\n                unit=self._unit,\n            )\n        return self.__class__(np.array(self).__div__(np.array(other)), unit=self.unit / other.unit)\n\n    def __truediv__(self, other):\n        # pylint: disable=E1101\n        if not hasattr(other, \"unit_type\"):\n            return self.__class__(\n                np.array(self).__truediv__(np.array(other)),\n                unit_type=self._unit_type,\n                unit=self._unit,\n            )\n        return self.__class__(np.array(self).__truediv__(np.array(other)), unit=self.unit / other.unit)\n\n    def __neg__(self):\n        return self.__class__(np.array(self).__neg__(), unit_type=self.unit_type, unit=self.unit)\n\n    def to(self, new_unit):\n        \"\"\"\n        Conversion to a new_unit.\n\n        Args:\n            new_unit:\n                New unit type.\n\n        Returns:\n            A ArrayWithFloatWithUnit object in the new units.\n\n        Example usage:\n        >>> e = EnergyArray([1, 1.1], \"Ha\")\n        >>> e.to(\"eV\")\n        array([ 27.21138386,  29.93252225]) eV\n        \"\"\"\n        return self.__class__(\n            np.array(self) * self.unit.get_conversion_factor(new_unit),\n            unit_type=self.unit_type,\n            unit=new_unit,\n        )\n\n    @property\n    def as_base_units(self):\n        \"\"\"\n        Returns this ArrayWithUnit in base SI units, including derived units.\n\n        Returns:\n            An ArrayWithUnit object in base SI units\n        \"\"\"\n        return self.to(self.unit.as_base_units[0])\n\n    # TODO abstract base class property?\n    @property\n    def supported_units(self):\n        \"\"\"\n        Supported units for specific unit type.\n        \"\"\"\n        return ALL_UNITS[self.unit_type]\n\n    # TODO abstract base class method?\n    def conversions(self):\n        \"\"\"\n        Returns a string showing the available conversions.\n        Useful tool in interactive mode.\n        \"\"\"\n        return \"\\n\".join(str(self.to(unit)) for unit in self.supported_units)\n\n\ndef _my_partial(func, *args, **kwargs):\n    \"\"\"\n    Partial returns a partial object and therefore we cannot inherit class\n    methods defined in FloatWithUnit. This function calls partial and patches\n    the new class before returning.\n    \"\"\"\n    newobj = partial(func, *args, **kwargs)\n    # monkey patch\n    newobj.from_string = FloatWithUnit.from_string\n    return newobj\n\n\nEnergy = partial(FloatWithUnit, unit_type=\"energy\")\n\"\"\"\nA float with an energy unit.\n\nArgs:\n    val (float): Value\n    unit (Unit): E.g., eV, kJ, etc. Must be valid unit or UnitError is raised.\n\"\"\"\nEnergyArray = partial(ArrayWithUnit, unit_type=\"energy\")\n\nLength = partial(FloatWithUnit, unit_type=\"length\")\n\"\"\"\nA float with a length unit.\n\nArgs:\n    val (float): Value\n    unit (Unit): E.g., m, ang, bohr, etc. Must be valid unit or UnitError is\n        raised.\n\"\"\"\nLengthArray = partial(ArrayWithUnit, unit_type=\"length\")\n\nMass = partial(FloatWithUnit, unit_type=\"mass\")\n\"\"\"\nA float with a mass unit.\n\nArgs:\n    val (float): Value\n    unit (Unit): E.g., amu, kg, etc. Must be valid unit or UnitError is\n        raised.\n\"\"\"\nMassArray = partial(ArrayWithUnit, unit_type=\"mass\")\n\nTemp = partial(FloatWithUnit, unit_type=\"temperature\")\n\"\"\"\nA float with a temperature unit.\n\nArgs:\n    val (float): Value\n    unit (Unit): E.g., K. Only K (kelvin) is supported.\n\"\"\"\nTempArray = partial(ArrayWithUnit, unit_type=\"temperature\")\n\nTime = partial(FloatWithUnit, unit_type=\"time\")\n\"\"\"\nA float with a time unit.\n\nArgs:\n    val (float): Value\n    unit (Unit): E.g., s, min, h. Must be valid unit or UnitError is\n        raised.\n\"\"\"\nTimeArray = partial(ArrayWithUnit, unit_type=\"time\")\n\nCharge = partial(FloatWithUnit, unit_type=\"charge\")\n\"\"\"\nA float with a charge unit.\n\nArgs:\n    val (float): Value\n    unit (Unit): E.g., C, e (electron charge). Must be valid unit or UnitError\n        is raised.\n\"\"\"\nChargeArray = partial(ArrayWithUnit, unit_type=\"charge\")\n\nMemory = _my_partial(FloatWithUnit, unit_type=\"memory\")\n\"\"\"\nA float with a memory unit.\n\nArgs:\n    val (float): Value\n    unit (Unit): E.g., Kb, Mb, Gb, Tb. Must be valid unit or UnitError\n        is raised.\n\"\"\"\n\n\ndef obj_with_unit(obj, unit):\n    \"\"\"\n    Returns a `FloatWithUnit` instance if obj is scalar, a dictionary of\n    objects with units if obj is a dict, else an instance of\n    `ArrayWithFloatWithUnit`.\n\n    Args:\n        unit: Specific units (eV, Ha, m, ang, etc.).\n    \"\"\"\n    unit_type = _UNAME2UTYPE[unit]\n\n    if isinstance(obj, numbers.Number):\n        return FloatWithUnit(obj, unit=unit, unit_type=unit_type)\n    if isinstance(obj, collections.abc.Mapping):\n        return {k: obj_with_unit(v, unit) for k, v in obj.items()}\n    return ArrayWithUnit(obj, unit=unit, unit_type=unit_type)\n\n\ndef unitized(unit):\n    \"\"\"\n    Useful decorator to assign units to the output of a function. You can also\n    use it to standardize the output units of a function that already returns\n    a FloatWithUnit or ArrayWithUnit. For sequences, all values in the sequences\n    are assigned the same unit. It works with Python sequences only. The creation\n    of numpy arrays loses all unit information. For mapping types, the values\n    are assigned units.\n\n    Args:\n        unit: Specific unit (eV, Ha, m, ang, etc.).\n\n    Example usage::\n\n        @unitized(unit=\"kg\")\n        def get_mass():\n            return 123.45\n\n    \"\"\"\n\n    def wrap(f):\n        def wrapped_f(*args, **kwargs):\n            val = f(*args, **kwargs)\n            unit_type = _UNAME2UTYPE[unit]\n\n            if isinstance(val, (FloatWithUnit, ArrayWithUnit)):\n                return val.to(unit)\n\n            if isinstance(val, collections.abc.Sequence):\n                # TODO: why don't we return a ArrayWithUnit?\n                # This complicated way is to ensure the sequence type is\n                # preserved (list or tuple).\n                return val.__class__([FloatWithUnit(i, unit_type=unit_type, unit=unit) for i in val])\n            if isinstance(val, collections.abc.Mapping):\n                for k, v in val.items():\n                    val[k] = FloatWithUnit(v, unit_type=unit_type, unit=unit)\n            elif isinstance(val, numbers.Number):\n                return FloatWithUnit(val, unit_type=unit_type, unit=unit)\n            elif val is None:\n                pass\n            else:\n                raise TypeError(f\"Don't know how to assign units to {str(val)}\")\n            return val\n\n        return wrapped_f\n\n    return wrap\n\n\nif __name__ == \"__main__\":\n    import doctest\n\n    doctest.testmod()\n", "meta": {"hexsha": "ab2b3048e485e2cca443facf01ae2cb7362b293e", "size": 27043, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymatgen/core/units.py", "max_stars_repo_name": "dskoda/pymatgen", "max_stars_repo_head_hexsha": "ba23f32abd857c92d5fdd19a8b62b17af6697841", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-24T04:12:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T04:12:16.000Z", "max_issues_repo_path": "pymatgen/core/units.py", "max_issues_repo_name": "dskoda/pymatgen", "max_issues_repo_head_hexsha": "ba23f32abd857c92d5fdd19a8b62b17af6697841", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pymatgen/core/units.py", "max_forks_repo_name": "dskoda/pymatgen", "max_forks_repo_head_hexsha": "ba23f32abd857c92d5fdd19a8b62b17af6697841", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9279811098, "max_line_length": 108, "alphanum_fraction": 0.5765632511, "include": true, "reason": "import numpy,import scipy", "num_tokens": 7224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.19089559289439825}}
{"text": "import torch\nimport torch.utils.data\nimport math\nimport numpy as np\nfrom collections import defaultdict\n\n\ndef pad(species):\n    \"\"\"Put different species together into single tensor.\n\n    If the species are from molecules of different number of total atoms, then\n    ghost atoms with atom type -1 will be added to make it fit into the same\n    shape.\n\n    Arguments:\n        species (:class:`collections.abc.Sequence`): sequence of species.\n            Species must be of shape ``(N, A)``, where ``N`` is the number of\n            3D structures, ``A`` is the number of atoms.\n\n    Returns:\n        :class:`torch.Tensor`: species batched together.\n    \"\"\"\n    max_atoms = max([s.shape[1] for s in species])\n    padded_species = []\n    for s in species:\n        natoms = s.shape[1]\n        if natoms < max_atoms:\n            padding = torch.full((s.shape[0], max_atoms - natoms), -1,\n                                 dtype=torch.long, device=s.device)\n            s = torch.cat([s, padding], dim=1)\n        padded_species.append(s)\n    return torch.cat(padded_species)\n\n\ndef pad_atomic_properties(atomic_properties, padding_values=defaultdict(lambda: 0.0, species=-1)):\n    \"\"\"Put a sequence of atomic properties together into single tensor.\n\n    Inputs are `[{'species': ..., ...}, {'species': ..., ...}, ...]` and the outputs\n    are `{'species': padded_tensor, ...}`\n\n    Arguments:\n        species_coordinates (:class:`collections.abc.Sequence`): sequence of\n             atomic properties.\n        padding_values (dict): the value to fill to pad tensors to same size\n    \"\"\"\n    keys = list(atomic_properties[0])\n    anykey = keys[0]\n    max_atoms = max(x[anykey].shape[1] for x in atomic_properties)\n    padded = {k: [] for k in keys}\n    for p in atomic_properties:\n        num_molecules = 1\n        for v in p.values():\n            assert num_molecules in {1, v.shape[0]}, 'Number of molecules in different atomic properties mismatch'\n            if v.shape[0] != 1:\n                num_molecules = v.shape[0]\n        for k, v in p.items():\n            shape = list(v.shape)\n            padatoms = max_atoms - shape[1]\n            shape[1] = padatoms\n            padding = v.new_full(shape, padding_values[k])\n            v = torch.cat([v, padding], dim=1)\n            shape = list(v.shape)\n            shape[0] = num_molecules\n            v = v.expand(*shape)\n            padded[k].append(v)\n    return {k: torch.cat(v) for k, v in padded.items()}\n\n\n# @torch.jit.script\ndef present_species(species):\n    \"\"\"Given a vector of species of atoms, compute the unique species present.\n\n    Arguments:\n        species (:class:`torch.Tensor`): 1D vector of shape ``(atoms,)``\n\n    Returns:\n        :class:`torch.Tensor`: 1D vector storing present atom types sorted.\n    \"\"\"\n    # present_species, _ = species.flatten()._unique(sorted=True)\n    present_species = species.flatten().unique(sorted=True)\n    if present_species[0].item() == -1:\n        present_species = present_species[1:]\n    return present_species\n\n\ndef strip_redundant_padding(atomic_properties):\n    \"\"\"Strip trailing padding atoms.\n\n    Arguments:\n        atomic_properties (dict): properties to strip\n\n    Returns:\n        dict: same set of properties with redundant padding atoms stripped.\n    \"\"\"\n    species = atomic_properties['species']\n    non_padding = (species >= 0).any(dim=0).nonzero().squeeze()\n    for k in atomic_properties:\n        atomic_properties[k] = atomic_properties[k].index_select(1, non_padding)\n    return atomic_properties\n\n\ndef map2central(cell, coordinates, pbc):\n    \"\"\"Map atoms outside the unit cell into the cell using PBC.\n\n    Arguments:\n        cell (:class:`torch.Tensor`): tensor of shape (3, 3) of the three\n            vectors defining unit cell:\n\n            .. code-block:: python\n\n                tensor([[x1, y1, z1],\n                        [x2, y2, z2],\n                        [x3, y3, z3]])\n\n        coordinates (:class:`torch.Tensor`): Tensor of shape\n            ``(molecules, atoms, 3)``.\n\n        pbc (:class:`torch.Tensor`): boolean vector of size 3 storing\n            if pbc is enabled for that direction.\n\n    Returns:\n        :class:`torch.Tensor`: coordinates of atoms mapped back to unit cell.\n    \"\"\"\n    # Step 1: convert coordinates from standard cartesian coordinate to unit\n    # cell coordinates\n    inv_cell = torch.inverse(cell)\n    coordinates_cell = torch.matmul(coordinates, inv_cell)\n    # Step 2: wrap cell coordinates into [0, 1)\n    coordinates_cell -= coordinates_cell.floor() * pbc.to(coordinates_cell.dtype)\n    # Step 3: convert from cell coordinates back to standard cartesian\n    # coordinate\n    return torch.matmul(coordinates_cell, cell)\n\n\nclass EnergyShifter(torch.nn.Module):\n    \"\"\"Helper class for adding and subtracting self atomic energies\n\n    This is a subclass of :class:`torch.nn.Module`, so it can be used directly\n    in a pipeline as ``[input->AEVComputer->ANIModel->EnergyShifter->output]``.\n\n    Arguments:\n        self_energies (:class:`collections.abc.Sequence`): Sequence of floating\n            numbers for the self energy of each atom type. The numbers should\n            be in order, i.e. ``self_energies[i]`` should be atom type ``i``.\n        fit_intercept (bool): Whether to calculate the intercept during the LSTSQ\n            fit. The intercept will also be taken into account to shift energies.\n    \"\"\"\n\n    def __init__(self, self_energies, fit_intercept=False):\n        super(EnergyShifter, self).__init__()\n\n        self.fit_intercept = fit_intercept\n        if self_energies is not None:\n            self_energies = torch.tensor(self_energies, dtype=torch.double)\n\n        self.register_buffer('self_energies', self_energies)\n\n    def sae_from_dataset(self, atomic_properties, properties):\n        \"\"\"Compute atomic self energies from dataset.\n\n        Least-squares solution to a linear equation is calculated to output\n        ``self_energies`` when ``self_energies = None`` is passed to\n        :class:`torchani.EnergyShifter`\n        \"\"\"\n        species = atomic_properties['species']\n        energies = properties['energies']\n        present_species_ = present_species(species)\n        X = (species.unsqueeze(-1) == present_species_).sum(dim=1).to(torch.double)\n        # Concatenate a vector of ones to find fit intercept\n        if self.fit_intercept:\n            X = torch.cat((X, torch.ones(X.shape[0], 1).to(torch.double)), dim=-1)\n        y = energies.unsqueeze(dim=-1)\n        coeff_, _, _, _ = np.linalg.lstsq(X, y, rcond=None)\n        return coeff_.squeeze()\n\n    def sae(self, species):\n        \"\"\"Compute self energies for molecules.\n\n        Padding atoms will be automatically excluded.\n\n        Arguments:\n            species (:class:`torch.Tensor`): Long tensor in shape\n                ``(conformations, atoms)``.\n\n        Returns:\n            :class:`torch.Tensor`: 1D vector in shape ``(conformations,)``\n            for molecular self energies.\n        \"\"\"\n        intercept = 0.0\n        if self.fit_intercept:\n            intercept = self.self_energies[-1]\n\n        self_energies = self.self_energies[species]\n        self_energies[species == -1] = 0\n        return self_energies.sum(dim=1) + intercept\n\n    def subtract_from_dataset(self, atomic_properties, properties):\n        \"\"\"Transformer for :class:`torchani.data.BatchedANIDataset` that\n        subtract self energies.\n        \"\"\"\n        if self.self_energies is None:\n            self_energies = self.sae_from_dataset(atomic_properties, properties)\n            self.self_energies = torch.tensor(self_energies, dtype=torch.double)\n\n        species = atomic_properties['species']\n        energies = properties['energies']\n        device = energies.device\n        energies = energies.to(torch.double) - self.sae(species).to(device)\n        properties['energies'] = energies\n        return atomic_properties, properties\n\n    def forward(self, species_energies):\n        \"\"\"(species, molecular energies)->(species, molecular energies + sae)\n        \"\"\"\n        species, energies = species_energies\n        sae = self.sae(species).to(energies.dtype).to(energies.device)\n        return species, energies + sae\n\n\nclass ChemicalSymbolsToInts:\n    \"\"\"Helper that can be called to convert chemical symbol string to integers\n\n    Arguments:\n        all_species (:class:`collections.abc.Sequence` of :class:`str`):\n            sequence of all supported species, in order.\n    \"\"\"\n\n    def __init__(self, all_species):\n        self.rev_species = {}\n        for i, s in enumerate(all_species):\n            self.rev_species[s] = i\n\n    def __call__(self, species):\n        \"\"\"Convert species from squence of strings to 1D tensor\"\"\"\n        rev = [self.rev_species[s] for s in species]\n        return torch.tensor(rev, dtype=torch.long)\n\n\ndef hessian(coordinates, energies=None, forces=None):\n    \"\"\"Compute analytical hessian from the energy graph or force graph.\n\n    Arguments:\n        coordinates (:class:`torch.Tensor`): Tensor of shape `(molecules, atoms, 3)`\n        energies (:class:`torch.Tensor`): Tensor of shape `(molecules,)`, if specified,\n            then `forces` must be `None`. This energies must be computed from\n            `coordinates` in a graph.\n        forces (:class:`torch.Tensor`): Tensor of shape `(molecules, atoms, 3)`, if specified,\n            then `energies` must be `None`. This forces must be computed from\n            `coordinates` in a graph.\n\n    Returns:\n        :class:`torch.Tensor`: Tensor of shape `(molecules, 3A, 3A)` where A is the number of\n        atoms in each molecule\n    \"\"\"\n    if energies is None and forces is None:\n        raise ValueError('Energies or forces must be specified')\n    if energies is not None and forces is not None:\n        raise ValueError('Energies or forces can not be specified at the same time')\n    if forces is None:\n        forces = -torch.autograd.grad(energies.sum(), coordinates, create_graph=True)[0]\n    flattened_force = forces.flatten(start_dim=1)\n    force_components = flattened_force.unbind(dim=1)\n    return -torch.stack([\n        torch.autograd.grad(f.sum(), coordinates, retain_graph=True)[0].flatten(start_dim=1)\n        for f in force_components\n    ], dim=1)\n\n\ndef vibrational_analysis(masses, hessian, unit='cm^-1'):\n    \"\"\"Computing the vibrational wavenumbers from hessian.\"\"\"\n    if unit != 'cm^-1':\n        raise ValueError('Only cm^-1 are supported right now')\n    assert hessian.shape[0] == 1, 'Currently only supporting computing one molecule a time'\n    # Solving the eigenvalue problem: Hq = w^2 * T q\n    # where H is the Hessian matrix, q is the normal coordinates,\n    # T = diag(m1, m1, m1, m2, m2, m2, ....) is the mass\n    # We solve this eigenvalue problem through Lowdin diagnolization:\n    # Hq = w^2 * Tq ==> Hq = w^2 * T^(1/2) T^(1/2) q\n    # Letting q' = T^(1/2) q, we then have\n    # T^(-1/2) H T^(-1/2) q' = w^2 * q'\n    inv_sqrt_mass = (1 / masses.sqrt()).repeat_interleave(3, dim=1)  # shape (molecule, 3 * atoms)\n    mass_scaled_hessian = hessian * inv_sqrt_mass.unsqueeze(1) * inv_sqrt_mass.unsqueeze(2)\n    if mass_scaled_hessian.shape[0] != 1:\n        raise ValueError('The input should contain only one molecule')\n    mass_scaled_hessian = mass_scaled_hessian.squeeze(0)\n    eigenvalues, eigenvectors = torch.symeig(mass_scaled_hessian, eigenvectors=True)\n    angular_frequencies = eigenvalues.sqrt()\n    frequencies = angular_frequencies / (2 * math.pi)\n    # converting from sqrt(hartree / (amu * angstrom^2)) to cm^-1\n    wavenumbers = frequencies * 17092\n    modes = (eigenvectors.t() * inv_sqrt_mass).reshape(frequencies.numel(), -1, 3)\n    return wavenumbers, modes\n\n\n__all__ = ['pad', 'pad_atomic_properties', 'present_species', 'hessian',\n           'vibrational_analysis', 'strip_redundant_padding',\n           'ChemicalSymbolsToInts']\n", "meta": {"hexsha": "db8718b1d759a050e935374b60385e0c250ffd40", "size": 11821, "ext": "py", "lang": "Python", "max_stars_repo_path": "torchani/utils.py", "max_stars_repo_name": "chc273/torchani", "max_stars_repo_head_hexsha": "bbcd7bedc254796f0c2f839c4868ac211ad9078d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "torchani/utils.py", "max_issues_repo_name": "chc273/torchani", "max_issues_repo_head_hexsha": "bbcd7bedc254796f0c2f839c4868ac211ad9078d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "torchani/utils.py", "max_forks_repo_name": "chc273/torchani", "max_forks_repo_head_hexsha": "bbcd7bedc254796f0c2f839c4868ac211ad9078d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6677852349, "max_line_length": 114, "alphanum_fraction": 0.6444463243, "include": true, "reason": "import numpy", "num_tokens": 2840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3702254064929193, "lm_q1q2_score": 0.19089559289439822}}
{"text": "\"\"\"\nFile: pylinex/util/RectangularBinner.py\nAuthor: Keith Tauscher\nDate: 20 Sep 2018\n\nDescription: File containing a class and function which bins using a\n             rectangular window function defined by bin edges.\n\"\"\"\nfrom __future__ import division\nimport numpy as np\nfrom distpy import Savable, Loadable, sequence_types, create_hdf5_dataset,\\\n    get_hdf5_value\n\nclass RectangularBinner(Savable, Loadable):\n    \"\"\"\n    Class which bins using a rectangular window function defined by bin edges.\n    \"\"\"\n    def __init__(self, unbinned_x_values, bin_edges):\n        \"\"\"\n        Initializes a RectangularBinner with unbinned x values and edges of\n        bins with which to define new points.\n        \n        unbinned_x_values: x_values associated with points to bin\n        bin_edges: edges of bins with which to create new x values\n        \"\"\"\n        self.unbinned_x_values = unbinned_x_values\n        self.bin_edges = bin_edges\n        self.digitize()\n    \n    def digitize(self):\n        \"\"\"\n        Digitizes the bins so that binning can proceed quickly once data values\n        are given.\n        \"\"\"\n        bin_indices = np.digitize(self.unbinned_x_values, self.bin_edges)\n        (bins_to_keep, unique_indices, unique_counts) =\\\n            np.unique(bin_indices, return_index=True, return_counts=True)\n        if bins_to_keep[0] == 0:\n            bins_to_keep = bins_to_keep[1:]\n            unique_indices = unique_indices[1:]\n            unique_counts = unique_counts[1:]\n        if bins_to_keep[-1] == len(self.bin_edges):\n            bins_to_keep = bins_to_keep[:-1]\n            unique_indices = unique_indices[:-1]\n            unique_counts = unique_counts[:-1]\n        self._bins_to_keep = bins_to_keep - 1\n        self._unique_indices = unique_indices\n        self._unique_counts = unique_counts\n    \n    @property\n    def unique_indices(self):\n        \"\"\"\n        Property storing indices in the space of unbinned_x_values which share\n        bins.\n        \"\"\"\n        if not hasattr(self, '_unique_indices'):\n            raise AttributeError(\"unique_indices was referenced before \" +\\\n                \"bins were digitized.\")\n        return self._unique_indices\n    \n    @property\n    def unique_counts(self):\n        \"\"\"\n        \"\"\"\n        if not hasattr(self, '_unique_counts'):\n            raise AttributeError(\"unique_counts was referenced before bins \" +\\\n                \"were digitized.\")\n        return self._unique_counts\n    \n    @property\n    def unbinned_x_values(self):\n        \"\"\"\n        Property storing the x values of the unbinned points.\n        \"\"\"\n        if not hasattr(self, '_unbinned_x_values'):\n            raise AttributeError(\"unbinned_x_values was referenced before \" +\\\n                \"it was set.\")\n        return self._unbinned_x_values\n    \n    @unbinned_x_values.setter\n    def unbinned_x_values(self, value):\n        \"\"\"\n        Setter for the independent variable of the underlying model.\n        \"\"\"\n        if type(value) in sequence_types:\n            value = np.array(value)\n            if value.ndim == 1:\n                self._unbinned_x_values = value\n            else:\n                raise ValueError(\"unbinned_x_values was set to something \" +\\\n                    \"other than a 1D numpy.ndarray.\")\n        else:\n            raise TypeError(\"unbinned_x_values was set to something other \" +\\\n                \"than a 1D numpy.ndarray.\")\n    \n    @property\n    def bin_edges(self):\n        \"\"\"\n        Property storing the bin edges.\n        \"\"\"\n        if not hasattr(self, '_bin_edges'):\n            raise AttributeError(\"bin_edges was referenced before it was set.\")\n        return self._bin_edges\n    \n    @bin_edges.setter\n    def bin_edges(self, value):\n        \"\"\"\n        Setter for the bin edges.\n        \n        value: 1D array of bin edges (must be of length num_channels+1)\n        \"\"\"\n        if type(value) in sequence_types:\n            value = np.array(value)\n            if value.ndim == 1:\n                self._bin_edges = value\n            else:\n                raise ValueError(\"bin_edges was set to something other \" +\\\n                    \"than a 1D numpy.ndarray.\")\n        else:\n            raise TypeError(\"bin_edges was set to something other than a \" +\\\n                \"1D numpy.ndarray.\")\n    \n    @property\n    def nbins(self):\n        \"\"\"\n        Property storing the number of bins implied by the bin edges.\n        \"\"\"\n        if not hasattr(self, '_nbins'):\n            self._nbins = len(self.bin_edges) - 1\n        return self._nbins\n    \n    @property\n    def bins_to_keep(self):\n        \"\"\"\n        Property storing the indices of bin with nonzero weight in order.\n        \"\"\"\n        if not hasattr(self, '_bins_to_keep'):\n            raise AttributeError(\"bins_to_keep referenced before it was set.\")\n        return self._bins_to_keep\n    \n    @property\n    def nbins_to_keep(self):\n        \"\"\"\n        Property storing the number of bins in the results of this binner.\n        \"\"\"\n        if not hasattr(self, '_nbins_to_keep'):\n            self._nbins_to_keep = len(self.bins_to_keep)\n        return self._nbins_to_keep\n    \n    @property\n    def binned_x_values(self):\n        \"\"\"\n        Property storing the binned x values.\n        \"\"\"\n        if not hasattr(self, '_binned_x_values'):\n            self._binned_x_values = (self.bin_edges[self.bins_to_keep] +\\\n                self.bin_edges[self.bins_to_keep+1]) / 2\n        return self._binned_x_values\n    \n    @property\n    def x_samples(self):\n        \"\"\"\n        Property storing the x values in each bin. It is a list of arrays.\n        \"\"\"\n        if not hasattr(self, '_x_samples'):\n            self._x_samples = [np.array([])] * self.nbins\n            for (final_bin_index, original_bin_index) in\\\n                enumerate(self.bins_to_keep):\n                index = self.unique_indices[final_bin_index]\n                count = self.unique_counts[final_bin_index]\n                self._x_samples[original_bin_index] =\\\n                    self.unbinned_x_values[index:index+count]\n        return self._x_samples\n    \n    def bin(self, old_y_values, weights=None, return_weights=False):\n        \"\"\"\n        Bins the given data.\n        \n        old_y_values: data to bin\n        weights: weights to associate with each unbinned y value (should be of\n                 same shape as old_y_values)\n        return_weights: if True, weights are returned alongside binned data\n        \n        returns: if return_weights is False, new_y_values\n                 if return_weights is True, (new_y_values, new_weights)\n        \"\"\"\n        shape = old_y_values.shape[:-1] + (len(self.bins_to_keep),)\n        new_y_values = np.zeros(shape)\n        if type(weights) is type(None):\n            weights = np.ones_like(old_y_values)\n        if return_weights:\n            new_weights = np.zeros(shape)\n        for final_bin_index in range(len(self.bins_to_keep)):\n            unique_index = self.unique_indices[final_bin_index]\n            unique_count = self.unique_counts[final_bin_index]\n            where = slice(unique_index, unique_index + unique_count)\n            old_y_slice = old_y_values[...,where]\n            weight_slice = weights[...,where]\n            new_weight = np.sum(weight_slice, axis=-1)\n            new_y_values[...,final_bin_index] =\\\n                np.sum(old_y_slice * weight_slice, axis=-1) / new_weight\n            if return_weights:\n                new_weights[...,final_bin_index] = new_weight\n        if return_weights:\n            return (new_y_values, new_weights)\n        else:\n            return new_y_values\n    \n    def bin_error(self, old_error, weights=None, return_weights=False):\n        \"\"\"\n        Bins the given error vector(s).\n        \n        old_error: error to bin containing positive numbers with the last axis\n                   being the binning axis.\n        weights: weights to associate with each unbinned y value (should be of\n                 same shape as old_y_values)\n        return_weights: if True, weights are returned alongside binned data\n        \n        returns: if return_weights is False, new_y_values\n                 if return_weights is True, (new_y_values, new_weights)\n        \"\"\"\n        shape = old_error.shape[:-1] + (self.nbins_to_keep,)\n        new_error = np.zeros(shape)\n        if type(weights) is type(None):\n            weights = np.ones_like(old_error)\n        if return_weights:\n            new_weights = np.zeros(shape)\n        for final_bin_index in range(self.nbins_to_keep):\n            unique_index = self.unique_indices[final_bin_index]\n            unique_count = self.unique_counts[final_bin_index]\n            where = slice(unique_index, unique_index + unique_count)\n            old_error_slice = old_error[...,where]\n            weight_slice = weights[...,where]\n            new_weight = np.sum(weight_slice, axis=-1)\n            new_error[...,final_bin_index] = np.sqrt(np.sum(np.power(\\\n                weight_slice * old_error_slice, 2), axis=-1)) / new_weight\n            if return_weights:\n                new_weights[...,final_bin_index] = new_weight\n        if return_weights:\n            return (new_error, new_weights)\n        else:\n            return new_error\n    \n    def __call__(self, old_y_values, weights=None, return_weights=False):\n        \"\"\"\n        Bins the given data.\n        \n        old_y_values: data to bin\n        weights: weights to associate with each unbinned y value (should be of\n                 same shape as old_y_values)\n        return_weights: if True, weights are returned alongside binned data\n        \n        returns: if return_weights is False, new_y_values\n                 if return_weights is True, (new_y_values, new_weights)\n        \"\"\"\n        return self.bin(old_y_values, weights=weights,\\\n            return_weights=return_weights)\n    \n    def fill_hdf5_group(self, group):\n        \"\"\"\n        Fills the given hdf5 file group with data about this RectangularBinner.\n        \"\"\"\n        create_hdf5_dataset(group, 'unbinned_x_values',\\\n            data=self.unbinned_x_values)\n        create_hdf5_dataset(group, 'bin_edges', data=self.bin_edges)\n    \n    @staticmethod\n    def load_from_hdf5_group(group):\n        \"\"\"\n        Loads a RectangularBinner from the given hdf5 file group.\n        \n        group: group where RectangularBinner was once saved\n        \n        returns: RectangularBinner whose info was saved in the given group\n        \"\"\"\n        unbinned_x_values = get_hdf5_value(group['unbinned_x_values'])\n        bin_edges = get_hdf5_value(group['bin_edges'])\n        return RectangularBinner(unbinned_x_values, bin_edges)\n    \n    def __eq__(self, other):\n        \"\"\"\n        Checks if other is the same binner as this.\n        \n        other: object to check for equality\n        \n        returns: True only if other is a RectangularBinner with the same\n                 unbinned x values and bin edges. False otherwise\n        \"\"\"\n        if not isinstance(other, RectangularBinner):\n            return False\n        if (self.unbinned_x_values.shape != other.unbinned_x_values.shape) or\\\n            np.any(self.unbinned_x_values != other.unbinned_x_values):\n            return False\n        if (self.bin_edges.shape != other.bin_edges.shape) or\\\n            np.any(self.bin_edges != other.bin_edges):\n            return False\n        return True\n    \n    def __ne__(self, other):\n        \"\"\"\n        Checks if other is not the same binner as this.\n        \n        other: object to check for inequality\n        \n        returns: False only if other is a RectangularBinner with the same\n                 unbinned x values and bin edges. True otherwise\n        \"\"\"\n        return (not self.__eq__(other))\n\ndef rect_bin(bin_edges, unbinned_x_values, old_y_values, weights=None,\\\n    return_weights=False):\n    \"\"\"\n    Bins on final axis.\n    \n    bin_edges: 1D numpy.ndarray of length Nafter+1 containing bin edges\n    unbinned_x_values: 1D numpy.ndarray of length Nbefore containing x values\n                       of points\n    old_y_values: ND numpy.ndarray whose final axis length is Nbefore\n    return_weights: if True, extra array of new weights is returned\n                    (Default False)\n    \n    returns: (binned_x_values, new_y_values[, new_weights])\n             binned_x_values: 1D numpy.ndarray of length Nafter\n             new_y_values: ND numpy.ndarray of the same shape as old_y_values\n                           with Nafter instead of Nbefore as the final axis\n                           length\n             [new_weights]: new weights to associate with the binned data\n                            points, given by the sum of the weights that went\n                            into each bin (returned only if return_weights is\n                            True)\n    \"\"\"\n    binner = RectangularBinner(unbinned_x_values, bin_edges)\n    bin_results =\\\n        binner(old_y_values, weights=weights, return_weights=return_weights)\n    if return_weights:\n        return (binner.binned_x_values,) + bin_results\n    else:\n        return (binner.binned_x_values, binner.new_y_values)\n\n", "meta": {"hexsha": "dcd9b7e275e9e35c10bf6368b4c7b535af64b9f0", "size": 13120, "ext": "py", "lang": "Python", "max_stars_repo_path": "pylinex/util/RectangularBinner.py", "max_stars_repo_name": "CU-NESS/pylinex", "max_stars_repo_head_hexsha": "b6f342595b6a154e129eb303782e5268088f34d5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pylinex/util/RectangularBinner.py", "max_issues_repo_name": "CU-NESS/pylinex", "max_issues_repo_head_hexsha": "b6f342595b6a154e129eb303782e5268088f34d5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pylinex/util/RectangularBinner.py", "max_forks_repo_name": "CU-NESS/pylinex", "max_forks_repo_head_hexsha": "b6f342595b6a154e129eb303782e5268088f34d5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5882352941, "max_line_length": 79, "alphanum_fraction": 0.6089176829, "include": true, "reason": "import numpy", "num_tokens": 2813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.19089558572865678}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated by Kleber Noel for disseration: \n    inversion mapping using a Local Linear embedding\nJune 2019\n\"\"\"\nimport numpy as np \nfrom numpy import mean\n\n#import pandas as pd \nimport os, pdb, argparse, re\nfrom random import shuffle\nfrom tqdm import tqdm\nfrom collections import defaultdict, OrderedDict\nfrom time import time\nimport torch, torch.nn as nn\nimport torch.optim as optim\nfrom torch import FloatTensor\nfrom torch.autograd import Variable\nfrom torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence\n\nget_seq_lens = lambda l : [x[-1] for x in l]\nget_names    = lambda l : [x[0] for x in l]\ndim1_list    = lambda l : [x.shape[1] for x in l]\nreport = 'count:{}, batch_size:{}, loss:{:.4}; mm:{:.4}, frames:{}, cor:{:.4}'\n\n# GET CUDA STATUS:\n\ndef get_args():\n    \"\"\"\n    Args define program usage.\n    \"\"\"\n    info = 'Script preprocesses data and saves, given i/o directories.'\n    parser = argparse.ArgumentParser(info)\n    parser.add_argument('--train', action='store_true', default=False)\n    parser.add_argument('--test',  action='store_true', default=False)\n    \n    parser.add_argument('--lsf-dir',  help='path to lsf directory')\n    parser.add_argument('--mfcc-dir', help='path to mfcc directory')\n    parser.add_argument('--ema-dir',  help='path to ema directory')\n    parser.add_argument('--bilstm-layers', type=int, default=2, help='number of bi-directional LSTM layers')\n\n    parser.add_argument('--shuffle', default=False, action='store_true', help='shuffle batches')\n    parser.add_argument('--batch-size', type=int, default=6, help='shuffle batches')\n    \n    parser.add_argument('--cuda', action='store_true', default=False, help='GPU support')\n\n    parser.add_argument('--load-dir', help='directory to load a saved model from')\n    parser.add_argument('--save-dir', help='directory to save a final model in')\n    \n    parser.add_argument('--checkpoint-dir', default = '', help='checkpoint directory to load/save model from/in')\n    parser.add_argument('--patience', type=int, default=10, help='save model after n epochs without improvement')\n    parser.add_argument('--save-internal', default=5, help='epoch arg to save the model parameters every *n* times')\n\n    parser.add_argument('--graph-data', action='store_true', help='graph data')\n    \n    return parser.parse_args()\n\nclass LoadInputOutput():\n    def __init__(self, args, d):\n        if args.lsf_dir: self.lsf_dict = self.load_data(args.lsf_dir)\n        if args.mfcc_dir: self.mfcc_dict= self.load_data(args.mfcc_dir)\n        self.ema_dict = self.load_data(args.ema_dir)\n        self.device   = d\n        self.shuffle  = args.shuffle\n        self.input_dim, self.output_dim = self.get_io_dims()\n        print('input dimensionality of lsfs:\\t\\t{} '.format(self.input_dim))\n        print('output dimensionality of emas:\\t\\t{}'.format(self.output_dim))\n    \n    def get_io_dims(self):\n        n_input_dims  = set(dim1_list(self.lsf_dict['channel_lsfd'].values()))\n        n_output_dims = set(dim1_list(self.ema_dict['channel_ema'].values()))\n        assert {len(n_output_dims),len(n_input_dims)}.pop()==1 # sanity check\n        return n_input_dims.pop(), n_output_dims.pop()\n\n    def load_means(self):\n        return np.array([float(i[0])*10**int(i[1]) for i in self.norm])\n    \n    def load_4xSTDs(self):\n        return np.array([4*(float(i[0])*10**int(i[1])) for i in self.norm])\n    \n    def load_data(self, directory):\n        ema_norm_str, data_dict = '(\\d+\\.\\d+)e([\\-\\+]\\d+)', defaultdict(dict)\n        for d1 in os.listdir(\"./{}\".format(directory)):\n            print('loading data to dict from {} : {}'.format(directory, d1))\n            if not \"channel\" in d1: continue\n            for d2 in os.listdir(\"./{}/{}\".format(directory,d1)):\n                key = d2.split('.')[0]\n                if re.match('ema_.*.txt',d2): \n                    with open(os.path.join(directory, d1, d2), 'r') as f:\n                        self.norm = re.findall(ema_norm_str,f.readlines()[0])\n                    if 'means' in d2: data_dict.update({key:FloatTensor(self.load_means())})\n                    elif 'stds' in d2:data_dict.update({key:FloatTensor(self.load_4xSTDs())})\n                    continue\n                np_array = np.load(os.path.join(directory, d1, d2), \n                                   allow_pickle = True)\n                if d1=='channel_name': data_dict.update({key:np_array})\n                else:  data_dict[d1].update({key:FloatTensor(np_array)})\n        return data_dict\n    \n    def get_batches(self):\n        total_samples = len(self.lsf_dict['channel_lsfd'].values())\n        # currently just choose a validation index: 10%, training 90%\n        self.val_idx = int(total_samples * (1 - 0.1))\n        self.sample_names = sorted([k for k in self.lsf_dict['channel_lsfd'].keys()])\n        report = 'minimum batch target size = {}\\nsegmenting data into batches...'\n        print(report.format(args.batch_size))\n        # define batch TRAINING (t) and VALIDATION (v) for...\n        #   SOURCE set (s) & TARGET set (t)\n        self.bts, self.bvs = self.make_batches(self.lsf_dict['channel_lsfd'])\n        self.btt, self.bvt = self.make_batches(self.ema_dict['channel_ema'])\n        # Normalize outputs to millimeters (for calculating RMSE in mm)\n        ### DO FOR WHOLE BATCH\n        batch_list_tt = [i for i in self.btt[0]]\n        batch_list_vt = [i for i in self.bvt[0]]\n        self.bttm = self.unnormalize_output(batch_list_tt, True)\n        self.bvtm = self.unnormalize_output(batch_list_vt, True)\n    \n    def reorder(self, t, i, tup=False):\n        if tup: return ([t[0][n] for n in i],[t[1][n] for n in i])\n        if not tup: return [t[n] for n in i]\n    \n    def shuffle_batches(self):\n        \"\"\"\n        Shuffles batches based on numpy:\n            get len of training/validation batches -> 0,1, ... len(batch).\n        \"\"\"\n        t, v = np.arange(len(self.bts[0])), np.arange(len(self.bvs[0]))\n        np.random.shuffle(t), np.random.shuffle(v) # new order for t & v.\n        t, v = t.tolist(), v.tolist()\n        self.bts  = self.reorder(self.bts, t, tup=True)\n        self.bvs  = self.reorder(self.bvs, v, tup=True)\n        self.btt  = self.reorder(self.btt, t, tup=True)\n        self.bvt  = self.reorder(self.bvt, v, tup=True)\n        self.bttm = self.reorder(self.bttm, t, tup=False)\n        self.bvtm = self.reorder(self.bvtm, v, tup=False)\n        \n    def make_batches(self, in_dict, split=True):\n        \"\"\"\n        Makes and pads a batch using data dictionary\n        \"\"\"\n        if split: #split into train, validation sets\n            t, v = self.return_train_valid(in_dict) #INSERT NEW make_batch var to give random sequence for train/val\n            return self.make_batches(t, False), self.make_batches(v, False)\n        batches, batch, =  [], []\n        frames_to_names, mxfr2nmfr = defaultdict(set), defaultdict(int)\n        for k,s in [(k,v.shape[0]) for k,v in in_dict.items()]: frames_to_names[s].add(k)\n        # Run through k:frames --> v:names dict in order (lowest to highest)\n        for frames, names in sorted(frames_to_names.items(), key=lambda x:x[0]):\n            batch.extend([(n,frames) for n in names])\n            ### Aim to get up to or above batch size... issue: dif batch sizes.\n            if len(batch) >= args.batch_size and batch!=0: ## why batch=0? FIX!\n                mxfr2nmfr.update({frames:sorted(batch,reverse=True, key=lambda x:x[1])})\n                batch = []\n        if len(batch) > 0: # remainder that didn't fit into target batch sizes\n            mxfr2nmfr.update({frames:sorted(batch,reverse=True, key=lambda x:x[1])})\n        n2f=[]\n        for batch in mxfr2nmfr.values():\n            if batch==0: continue\n            t = [FloatTensor(in_dict[k]).to(self.device) for k, f in batch]\n            batches.append(pad_sequence(t, batch_first=True))\n            n2f.append([(k,in_dict[k].shape[0]) for k, f in batch])\n        return batches, n2f\n    \n    def return_train_valid(self, in_dict):\n        t, v, = defaultdict(str), defaultdict(str)\n        t = {k:in_dict[k] for k in self.sample_names[:self.val_idx]}\n        v = {k:in_dict[k] for k in self.sample_names[self.val_idx:]}   \n        return t,v\n    \n    def unnormalize_output(self, batches, batches_set=True):\n        unnormalized_data = []\n        stds_tensor = FloatTensor(self.ema_dict['ema_stds']).to(self.device)\n        if batches_set==True: # A WHOLE BATCH\n            for b in batches:\n                norm = stds_tensor.repeat(b.shape[0],b.shape[1],1)\n                unnormalized_data.append(torch.mul(norm, b))\n            return unnormalized_data\n        else:\n            b = batches\n            norm = stds_tensor.repeat(b.shape[0],b.shape[1],1)\n            return torch.mul(norm, b)\n\n    def zip_validation_batches(self):\n        \"\"\"\n        Val args in zip: 1. src; 2. tgt; 3. tgt (mm), 4. names & sizes\n        \"\"\"\n        return zip(self.bvs[0], self.bvt[0], self.bvtm, self.bvt[1])\n\n    def zip_training_batches(self):\n        \"\"\"\n        Train args in zip: 1. src; 2. tgt; 3. tgt (mm), 4. names & sizes\n        \"\"\"\n        return zip(self.bts[0], self.btt[0], self.bttm, self.btt[1])\n\n    def get_prog_bar(self, zipped_batches, batches_type, epoch):\n        t = len(self.bts[0]) if batches_type=='training' else len(self.bvs[0])\n        bar = tqdm(iterable = zipped_batches, \n                   total = t,\n                   desc = '| {} Epoch {:03d}'.format(batches_type, epoch),\n                   leave = False,\n                   disable = False)\n        return bar\n\nclass BuildModel(nn.Module):\n    def __init__(self, args, d, input_dim, output_dim):\n        super(BuildModel, self).__init__()\n        self.args          = args\n        self.device        = d\n        self.input_dim     = input_dim\n        self.output_dim    = output_dim\n        self.hidden_dim    = 256\n        self.fc_hidden_dim = 512\n        self.bilstm_layers = args.bilstm_layers\n        self.batch_size    = args.batch_size # default: 6\n        # L1 lstm cell: should use sigmoid as R activation and tanh as final\n        self.bidirlstm = nn.LSTM(input_size    = self.input_dim, \n                                 hidden_size   = self.hidden_dim,\n                                 bidirectional = True,\n                                 num_layers    = self.bilstm_layers)\n        \n        self.fc = nn.Linear(in_features  = self.fc_hidden_dim,\n                            out_features = self.output_dim)\n        self.hc = None\n        self.criterion, self.criterion_mm = nn.MSELoss(), nn.MSELoss()\n        self.optimizer = optim.Adam(self.parameters(), lr=0.001)\n        self.is_new = False # assume model loaded from chkpnt til proven otherwise\n\n    def forward(self, padded_seq_batch):\n        \"\"\"\n            padded_seq_batch: padded sequence\n            hc: hidden and cell states\n            tuple of hidden and cell state\n        \"\"\"\n        self.get_len(padded_seq_batch.shape[0])\n        self.out_seq = torch.empty((self.sequence_len,\n                                       self.batch_size,\n                                       self.output_dim))\n        packed_seq_batch =  pack_padded_sequence(padded_seq_batch, \n                                                 lengths=self.seq_lens, \n                                                 batch_first=True)\n        \n        ## Reinitialize hidden state, WRT to the dimensions of the LSTM\n        ## as LSTM input dim1 changes due to packed sequence dim1 changes in \n        ## batch. Some batches are dif sizes, hidden state size changes \n        ## Before, I was only passing the packed_seq_batch to bidirlstm.\n\n        self.hc = self.init_hidden(2*self.bilstm_layers, \n                                   max(packed_seq_batch[1].tolist()), \n                                   self.hc)\n        packed_outputs, self.hc = self.bidirlstm(packed_seq_batch, self.hc)\n        lstm_out, _ = pad_packed_sequence(packed_outputs, batch_first=True)\n        self.out_seq = self.fc(lstm_out)\n    \n    def init_hidden(self, a, b, x = None):\n        return (Variable(torch.randn(a, b, self.hidden_dim,device=self.device)),\n                Variable(torch.randn(a, b, self.hidden_dim,device=self.device)))\n\n    def init_history(self):\n        if self.args.checkpoint_dir:\n            print('checkpoint \"{}\" not found'.format(args.checkpoint_dir))\n            print('initialising history and creating new model...')\n        self.history, self.is_new = defaultdict(dict), True \n        self.history['training'], self.history['validation'] = OrderedDict(), OrderedDict()\n\n    def get_len(self, length):\n        self.sequence_len = length\n    \n    def get_cor(self, output, target):\n        \"\"\"\n        function for correlations between target and output in a batch\n        normalized over the number of frames samples\n        \"\"\"\n        self.av_cor = float(0)\n        for frames, o, t in zip(self.seq_lens, output, target):\n            vo = o - torch.mean(o[:frames,:])\n            vt = t - torch.mean(o[:frames,:])\n            numerator = torch.sum(vo * vt)\n            denominator = (torch.sqrt(torch.sum(vo ** 2)) * torch.sqrt(torch.sum(vt ** 2)))\n            cor = numerator/denominator\n            self.av_cor += cor.item()*frames/sum(self.seq_lens)\n        \n    def get_lens_names_frames(self, names_to_frames):\n        \"\"\"\n        computed batch-wise\n        \"\"\"\n        self.seq_lens = get_seq_lens(names_to_frames)\n        self.names = get_names(names_to_frames)\n        self.frames = sum(self.seq_lens)\n\n    def get_losses(self, out_seqm, pad_tgt_seq, pad_tgt_seqm):\n        self.loss    = self.criterion(self.out_seq, pad_tgt_seq)\n        self.loss_mm = self.criterion_mm(out_seqm, pad_tgt_seqm).item()*1000\n\n    def propagate_loss(self):\n        self.loss.backward()\n        self.optimizer.step()\n    \n    def update_info(self, epoch, phase):\n        \"\"\"\n        phase is either training or testing.\n        info during epoch is updated as a set of loss values (mm and norm), \n        frame number, correlation, sample number for each minibatch\n        at end, average loss is computed.\n        \"\"\"\n        self.epoch = epoch\n        sample_number = len(self.names)\n        s = tuple([sample_number, self.frames, self.loss.item(), self.loss_mm, self.av_cor])\n        if self.history[phase].get(epoch): self.history[phase][epoch].append(s)\n        else: self.history[phase].update({epoch:[s]})\n\n    def set_prog_bar_desc(self, prog_bar, c):\n        batch_size = len(self.names)\n        prog_bar.set_description(report.format(c, batch_size, self.loss.item(), \n                                               self.loss_mm, self.frames, \n                                               self.av_cor))\n        \n    def get_epoch(self):\n        \"\"\"\n        since checkpoints/models are only saved after validation,\n        we only look into epoch of validation set here.\n        If process was cancelled in 1st train, start new history\n        \"\"\"\n        if dict(self.history.get('validation'))=={}: \n            self.init_history()\n            self.__init__(self.args, self.input_dim, self.output_dim)\n            return 0\n        else:\n            last_epoch = max(dict(self.history.get('validation')).keys())\n            return last_epoch\n        \n    def compute_batch_averages(self, phase):\n        \"\"\"\n        average loss (norm & mm), and cor calculated over batch for phase\n        normalize over entire batch instead of retaining single batch samples\n        \"\"\"\n        b_lm, b_l, b_c = float(0), float(0), float(0)\n        total_in_batch = sum([i[0] for i in dict(self.history[phase])[self.epoch]])\n        for n, f, l, lm, c in dict(self.history[phase])[self.epoch]:\n            b_c  += c * n  / total_in_batch\n            b_l  += l * n  / total_in_batch \n            b_lm += lm * n / total_in_batch \n        del self.history[phase][self.epoch]\n        self.history[phase].update({self.epoch:{b_l, b_c, b_lm}})\n        print('\\nOverall {0}: lossmm = {1:.3f} cor = {2:.3f}'.format(phase, b_lm, b_c))\n        if phase=='validation': return b_l\n\ndef save_model(model, model_path):\n    torch.save(model.state_dict(), model_path)\n\ndef load_model(model, model_path, device):\n    model.load_state_dict(torch.load(model_path, device.type))\n\ndef save_checkpoint(model, history, filepath):\n    state = {'epoch': model.epoch,\n             'state_dict': model.state_dict(),\n             'optimizer': model.optimizer.state_dict(),\n             'history': model.history}\n    torch.save(state, filepath)\n\ndef load_checkpoint(model, args, device):\n    checkpoint = torch.load(args.checkpoint_dir, map_location = device.type)\n    model.epoch = checkpoint['epoch']\n    model.load_state_dict(checkpoint['state_dict'])\n    model.to(device)\n    model.optimizer.load_state_dict(checkpoint['optimizer'])\n    model.history = checkpoint['history']\n\ndef get_knn(batch_out_seq, seq_lens, kneighbors):\n    from sklearn.manifold import locally_linear_embedding as lle\n    from sklearn.neighbors import NearestNeighbors\n    import numpy.matlib as matlib\n    from numpy.linalg import inv\n    \n    # By default the knn function below will return the same vector.\n    # e.g. k = 4 vector: 0, neighbors [0, 1, 2, 3]. We want [1, 2, 3, 4]\n    # therefore add one to get distinct from the reference.\n    knn = NearestNeighbors(n_neighbors = kneighbors + 1)\n    pdb.set_trace()\n    for sample, l in zip(batch_out_seq, seq_lens):\n        W = np.zeros((kneighbors,sample.shape[0]))\n        knn.fit(sample[:l,:])\n        k_nn, k_ni = knn.kneighbors(sample[:l,:], return_distance=True)\n        k_nn, k_ni = k_nn[:,1:], k_ni[:,1:]\n        for i in range(l):\n            Z = sample[:l,][k_ni[i]] - matlib.repmat(sample[:l,][i], kneighbors, 1)\n            C = Z @ Z.T\n            W[:,i] = inv(C)*np.ones((kneighbors, 1))\n            W[:,i] = W[:,i]/W[:,i].sum(axis=1,keepdims=1)\n            \n\ndef get_device(cuda):\n    if torch.cuda.is_available() and cuda: return torch.device('cuda')\n    else: return torch.device('cpu')\n\ndef validate(model, data, epoch, count):\n    val_prog_bar = data.get_prog_bar(data.zip_validation_batches(), \n                                     'validation', epoch)\n    torch.no_grad(), model.eval()\n    for pad_src_seq, pad_tgt_seq, pad_tgt_seqm, n2f in val_prog_bar:\n        count += 1\n\n        #if count > 4:  break # CODE TO STOP AND TEST \n            #k_nearest_neighbors = get_knn(model.out_seq.detach().numpy(), model.seq_lens)\n        model.get_lens_names_frames(n2f)\n        model.forward(Variable(pad_src_seq)) # pass thru model\n        model.get_cor(model.out_seq, pad_tgt_seq) # get correlation\n        out_seq_mm = data.unnormalize_output(model.out_seq, False) #MSE(mm)\n        model.get_losses(out_seq_mm, pad_tgt_seq, pad_tgt_seqm)\n        \n        model.update_info(epoch, 'validation')\n        model.set_prog_bar_desc(val_prog_bar, count)\n\ndef train(model, data, epoch, count):\n    train_prog_bar = data.get_prog_bar(data.zip_training_batches(), \n                                       'training', epoch)\n    model.train()\n    for pad_src_seq, pad_tgt_seq, pad_tgt_seqm, n2f in train_prog_bar:\n        count += 1\n        #if count > 2: break # CODE TO STOP AND TEST\n        model.get_lens_names_frames(n2f)\n        model.forward(Variable(pad_src_seq)) # pass thru model\n        model.get_cor(model.out_seq, pad_tgt_seq) # get correlation\n        out_seq_mm = data.unnormalize_output(model.out_seq, False) #MSE(mm)\n        model.get_losses(out_seq_mm, pad_tgt_seq, pad_tgt_seqm)\n        model.propagate_loss()\n        model.optimizer.zero_grad()\n        model.update_info(epoch, 'training')\n        model.set_prog_bar_desc(train_prog_bar, count)\n\ndef train_val_loop(model, data):\n    bad_epochs = 0\n    best_valid_loss = float('inf')\n    print('Model Overview:\\n\\n{}'.format(model))\n    while bad_epochs < args.patience:\n        count = 0\n        epoch += 1\n        if args.shuffle: data.shuffle_batches()\n        train(model, data, epoch, count)\n        validate(model, data, epoch, count)\n        model.compute_batch_averages('training')\n        bv_l = model.compute_batch_averages('validation')\n        if bv_l < best_valid_loss: # Decide whether to terminate training while loop\n            best_valid_loss, bad_epochs = bv_l, 0\n            if epoch % args.save_internal ==0: save_checkpoint(model, model.history, args.checkpoint_dir)\n        else: bad_epochs += 1\n    print('No validation set improvements observed for {:d} epochs. Early stop!'.format(args.patience))\n    print('Saving Model...')\n    try: save_model(model, args.save_model)\n    except: save_checkpoint(model, model.history, args.checkpoint_dir)\n\n\ndef test(model, data, count, epoch):\n    val_prog_bar = data.get_prog_bar(data.zip_validation_batches(), \n                                     'validation', epoch)\n    torch.no_grad(), model.eval()\n    for pad_src_seq, pad_tgt_seq, pad_tgt_seqm, n2f in val_prog_bar:\n        count += 1\n        model.get_lens_names_frames(n2f)\n        model.forward(Variable(pad_src_seq)) # pass thru model\n        model.get_cor(model.out_seq, pad_tgt_seq) # get correlation\n        out_seq_mm = data.unnormalize_output(model.out_seq, False) #MSE(mm)\n        model.get_losses(out_seq_mm, pad_tgt_seq, pad_tgt_seqm)\n        if count > 0: # break # CODE TO STOP AND TEST \n            k_nearest_neighbors = get_knn(model.out_seq.detach().numpy(), \n                                          model.seq_lens,\n                                          kneighbors = 5)\n            pdb.set_trace()\n            model.out_seq.detach()\n            k_nearest_neighbors\n            \n        \n        model.set_prog_bar_desc(val_prog_bar, count)\n\ndef run():\n    \"\"\"\n    Run Training and Validation over a number of epochs\n    \"\"\"\n    d = get_device(args.cuda)\n    data  = LoadInputOutput(args, d)\n    model = BuildModel(args, d, data.input_dim, data.output_dim)\n    data.get_batches()\n    if args.cuda: model = model.cuda()\n    if args.load_dir: load_model(model, args.load_dir, d)\n    elif os.path.isfile(args.checkpoint_dir): load_checkpoint(model, args, d) \n    else: model.init_history()\n    \n    epoch = 0 if model.is_new else model.get_epoch()\n    if args.train: train_val_loop(model, data, epoch)\n    if args.test: test(model, data, 0, epoch)\n\ndef main(args):\n    run()\n\nif __name__ == '__main__':\n    args = get_args()\n    main(args)\n", "meta": {"hexsha": "d69484993f919620baa892afb8a02616be3d833b", "size": 22380, "ext": "py", "lang": "Python", "max_stars_repo_path": "model1e.py", "max_stars_repo_name": "klebster2/inversion_mapping_dissertation", "max_stars_repo_head_hexsha": "568a043086207d1170410068213179b437b26e80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "model1e.py", "max_issues_repo_name": "klebster2/inversion_mapping_dissertation", "max_issues_repo_head_hexsha": "568a043086207d1170410068213179b437b26e80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model1e.py", "max_forks_repo_name": "klebster2/inversion_mapping_dissertation", "max_forks_repo_head_hexsha": "568a043086207d1170410068213179b437b26e80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8496993988, "max_line_length": 116, "alphanum_fraction": 0.6127792672, "include": true, "reason": "import numpy,from numpy", "num_tokens": 5386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.19089558572865675}}
{"text": "from __future__ import print_function\nimport abc\n\nimport numpy as np\nimport logging\nimport torch\nimport torch.utils.data\nfrom torch import nn\nfrom torch.autograd import Variable\nfrom torch.nn import functional as F\n\nfrom .nearest_embed import NearestEmbed\n\n\nclass AbstractAutoEncoder(nn.Module):\n    __metaclass__ = abc.ABCMeta\n\n    @abc.abstractmethod\n    def encode(self, x):\n        return\n\n    @abc.abstractmethod\n    def decode(self, z):\n        return\n\n    @abc.abstractmethod\n    def forward(self, x):\n        \"\"\"model return (reconstructed_x, *)\"\"\"\n        return\n\n    @abc.abstractmethod\n    def sample(self, size):\n        \"\"\"sample new images from model\"\"\"\n        return\n\n    @abc.abstractmethod\n    def loss_function(self, **kwargs):\n        \"\"\"accepts (original images, *) where * is the same as returned from forward()\"\"\"\n        return\n\n    @abc.abstractmethod\n    def latest_losses(self):\n        \"\"\"returns the latest losses in a dictionary. Useful for logging.\"\"\"\n        return\n\n\nclass VAE(nn.Module):\n    \"\"\"Variational AutoEncoder for MNIST\n       Taken from pytorch/examples: https://github.com/pytorch/examples/tree/master/vae\"\"\"\n    def __init__(self, kl_coef=1, **kwargs):\n        super(VAE, self).__init__()\n\n        self.fc1 = nn.Linear(784, 400)\n        self.fc21 = nn.Linear(400, 20)\n        self.fc22 = nn.Linear(400, 20)\n        self.fc3 = nn.Linear(20, 400)\n        self.fc4 = nn.Linear(400, 784)\n\n        self.relu = nn.ReLU()\n        self.sigmoid = nn.Sigmoid()\n        self.kl_coef = kl_coef\n        self.bce = 0\n        self.kl = 0\n\n    def encode(self, x):\n        h1 = self.relu(self.fc1(x))\n        return self.fc21(h1), self.fc22(h1)\n\n    def reparameterize(self, mu, logvar):\n        if self.training:\n            std = logvar.mul(0.5).exp_()\n            eps = Variable(std.new(std.size()).normal_())\n            return eps.mul(std).add_(mu)\n        else:\n            return mu\n\n    def decode(self, z):\n        h3 = self.relu(self.fc3(z))\n        return self.tanh(self.fc4(h3))\n\n    def forward(self, x):\n        mu, logvar = self.encode(x.view(-1, 784))\n        z = self.reparameterize(mu, logvar)\n        return self.decode(z), mu, logvar\n\n    def sample(self, size):\n        sample = Variable(torch.randn(size, 20))\n        if self.cuda():\n            sample = sample.cuda()\n        sample = self.decode(sample).cpu()\n        return sample\n\n    def loss_function(self, x, recon_x, mu, logvar):\n        self.bce = F.binary_cross_entropy(recon_x, x.view(-1, 784), size_average=False)\n        batch_size = x.size(0)\n\n        # see Appendix B from VAE paper:\n        # Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014\n        # https://arxiv.org/abs/1312.6114\n        # 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)\n        self.kl = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())\n\n        return self.bce + self.kl_coef*self.kl\n\n    def latest_losses(self):\n        return {'bce': self.bce, 'kl': self.kl}\n\n\nclass VQ_VAE(nn.Module):\n    \"\"\"Vector Quantized AutoEncoder for mnist\"\"\"\n    def __init__(self, hidden=200, k=10, vq_coef=0.2, comit_coef=0.4, **kwargs):\n        super(VQ_VAE, self).__init__()\n\n        self.emb_size = k\n        self.fc1 = nn.Linear(784, 400)\n        self.fc2 = nn.Linear(400, hidden)\n        self.fc3 = nn.Linear(hidden, 400)\n        self.fc4 = nn.Linear(400, 784)\n\n        self.emb = NearestEmbed(k, self.emb_size)\n\n        self.relu = nn.ReLU()\n        self.sigmoid = nn.Sigmoid()\n        self.vq_coef = vq_coef\n        self.comit_coef = comit_coef\n        self.hidden = hidden\n        self.ce_loss = 0\n        self.vq_loss = 0\n        self.commit_loss = 0\n\n    def encode(self, x):\n        h1 = self.relu(self.fc1(x))\n        h2 = self.fc2(h1)\n        return h2.view(-1, self.emb_size, int(self.hidden / self.emb_size))\n\n    def decode(self, z):\n        h3 = self.relu(self.fc3(z))\n        return self.tanh(self.fc4(h3))\n\n    def forward(self, x):\n        z_e = self.encode(x.view(-1, 784))\n        z_q, _ = self.emb(z_e, weight_sg=True).view(-1, self.hidden)\n        emb, _ = self.emb(z_e.detach()).view(-1, self.hidden)\n        return self.decode(z_q), z_e, emb\n\n    def sample(self, size):\n        sample = Variable(torch.randn(size, self.emb_size, int(self.hidden / self.emb_size)))\n        if self.cuda():\n            sample = sample.cuda()\n        emb, _ = self.emb(sample)\n        sample = self.decode(emb(sample).view(-1, self.hidden)).cpu()\n        return sample\n\n    def loss_function(self, x, recon_x, z_e, emb):\n        self.ce_loss = F.binary_cross_entropy(recon_x, x.view(-1, 784))\n        self.vq_loss = F.mse_loss(emb, z_e.detach())\n        self.commit_loss = F.mse_loss(z_e, emb.detach())\n\n        return self.ce_loss + self.vq_coef*self.vq_loss + self.comit_coef*self.commit_loss\n\n    def latest_losses(self):\n        return {'cross_entropy': self.ce_loss, 'vq': self.vq_loss, 'commitment': self.commit_loss}\n\n\nclass ResBlock(nn.Module):\n    def __init__(self, in_channels, channels, bn=False):\n        super(ResBlock, self).__init__()\n\n        layers = [\n            nn.ReLU(),\n            nn.Conv2d(in_channels, channels, kernel_size=3, stride=1, padding=1),\n            nn.ReLU(),\n            nn.Conv2d(in_channels, channels, kernel_size=1, stride=1, padding=0)]\n        if bn:\n            layers.insert(2, nn.BatchNorm2d(channels))\n        self.convs = nn.Sequential(*layers)\n\n    def forward(self, x):\n        return x + self.convs(x)\n\n\nclass CVAE(AbstractAutoEncoder):\n    def __init__(self, d, kl_coef=0.1, **kwargs):\n        super(CVAE, self).__init__()\n\n        self.encoder = nn.Sequential(\n            nn.Conv2d(3, d // 2, kernel_size=4, stride=2, padding=1, bias=False),\n            nn.BatchNorm2d(d // 2),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(d // 2, d, kernel_size=4, stride=2, padding=1, bias=False),\n            nn.BatchNorm2d(d),\n            nn.ReLU(inplace=True),\n            ResBlock(d, d, bn=True),\n            nn.BatchNorm2d(d),\n            ResBlock(d, d, bn=True),\n        )\n        self.decoder = nn.Sequential(\n            ResBlock(d, d, bn=True),\n            nn.BatchNorm2d(d),\n            ResBlock(d, d, bn=True),\n            nn.BatchNorm2d(d),\n\n            nn.ConvTranspose2d(d, d // 2, kernel_size=4, stride=2, padding=1, bias=False),\n            nn.BatchNorm2d(d//2),\n            nn.ReLU(inplace=True),\n            nn.ConvTranspose2d(d // 2, 3, kernel_size=4, stride=2, padding=1, bias=False),\n        )\n        self.f = 8\n        self.d = d\n        self.fc11 = nn.Linear(d * self.f ** 2, d * self.f ** 2)\n        self.fc12 = nn.Linear(d * self.f ** 2, d * self.f ** 2)\n        self.kl_coef = kl_coef\n        self.kl_loss = 0\n        self.mse = 0\n\n    def encode(self, x):\n        h1 = self.encoder(x)\n        h1 = h1.view(-1, self.d * self.f ** 2)\n        return self.fc11(h1), self.fc12(h1)\n\n    def reparameterize(self, mu, logvar):\n        if self.training:\n            std = logvar.mul(0.5).exp_()\n            eps = Variable(std.new(std.size()).normal_())\n            return eps.mul(std).add_(mu)\n        else:\n            return mu\n\n    def decode(self, z):\n        z = z.view(-1, self.d, self.f, self.f)\n        h3 = self.decoder(z)\n        return F.tanh(h3)\n\n    def forward(self, x):\n        mu, logvar = self.encode(x)\n        z = self.reparameterize(mu, logvar)\n        return self.decode(z), mu, logvar\n\n    def sample(self, size):\n        sample = Variable(torch.randn(size, self.d * self.f ** 2), requires_grad=False)\n        if self.cuda():\n            sample = sample.cuda()\n        return self.decode(sample).cpu()\n\n    def loss_function(self, x, recon_x, mu, logvar):\n        self.mse = F.mse_loss(recon_x, x)\n        batch_size = x.size(0)\n\n        # see Appendix B from VAE paper:\n        # Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014\n        # https://arxiv.org/abs/1312.6114\n        # 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)\n        self.kl_loss = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())\n        # Normalise by same number of elements as in reconstruction\n        self.kl_loss /= batch_size * 3 * 1024\n\n        # return mse\n        return self.mse + self.kl_coef * self.kl_loss\n\n    def latest_losses(self):\n        return {'mse': self.mse, 'kl': self.kl_loss}\n\n\nclass VQ_CVAE(nn.Module):\n    def __init__(self, d, k=10, bn=True, vq_coef=1, commit_coef=0.5, num_channels=3, **kwargs):\n        super(VQ_CVAE, self).__init__()\n\n        self.encoder = nn.Sequential(\n            nn.Conv2d(num_channels, d, kernel_size=4, stride=2, padding=1),\n            nn.BatchNorm2d(d),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(d, d, kernel_size=4, stride=2, padding=1),\n            nn.BatchNorm2d(d),\n            nn.ReLU(inplace=True),\n            ResBlock(d, d, bn),\n            nn.BatchNorm2d(d),\n            ResBlock(d, d, bn),\n            nn.BatchNorm2d(d),\n        )\n        self.decoder = nn.Sequential(\n            ResBlock(d, d),\n            nn.BatchNorm2d(d),\n            ResBlock(d, d),\n            nn.ConvTranspose2d(d, d, kernel_size=4, stride=2, padding=1),\n            nn.BatchNorm2d(d),\n            nn.ReLU(inplace=True),\n            nn.ConvTranspose2d(d, num_channels, kernel_size=4, stride=2, padding=1),\n        )\n        self.d = d\n        self.emb = NearestEmbed(k, d)\n        self.vq_coef = vq_coef\n        self.commit_coef = commit_coef\n        self.mse = 0\n        self.vq_loss = Variable(torch.zeros(1))\n        self.commit_loss = 0\n\n        for l in self.modules():\n            if isinstance(l, nn.Linear) or isinstance(l, nn.Conv2d):\n                l.weight.detach().normal_(0, 0.02)\n                torch.fmod(l.weight, 0.04)\n                nn.init.constant_(l.bias, 0)\n\n        self.encoder[-1].weight.detach().fill_(1 / 40)\n\n        self.emb.weight.detach().normal_(0, 0.02)\n        torch.fmod(self.emb.weight, 0.04)\n\n    def encode(self, x):\n        return self.encoder(x)\n\n    def decode(self, x):\n        return F.tanh(self.decoder(x))\n\n    def forward(self, x):\n        z_e = self.encode(x)\n        self.f = z_e.shape[-1]\n        z_q, argmin = self.emb(z_e, weight_sg=True)\n        emb, _ = self.emb(z_e.detach())\n        return self.decode(z_q), z_e, emb, argmin\n\n    def sample(self, size):\n        sample = Variable(torch.randn(size, self.d, self.f, self.f), requires_grad=False)\n        if self.cuda():\n            sample = sample.cuda()\n        emb, _ = self.emb(sample)\n        return self.decode(emb.view(size, self.d, self.f, self.f)).cpu()\n\n    def loss_function(self, x, recon_x, z_e, emb, argmin):\n        self.mse = F.mse_loss(recon_x, x)\n\n        self.vq_loss = torch.mean(torch.norm((emb - z_e.detach())**2, 2, 1))\n        self.commit_loss = torch.mean(torch.norm((emb.detach() - z_e)**2, 2, 1))\n\n        return self.mse + self.vq_coef*self.vq_loss + self.commit_coef*self.commit_loss\n\n    def latest_losses(self):\n        return {'mse': self.mse, 'vq': self.vq_loss, 'commitment': self.commit_loss}\n\n    def print_atom_hist(self, argmin):\n\n        argmin = argmin.detach().cpu().numpy()\n        unique, counts = np.unique(argmin, return_counts=True)\n        logging.info(counts)\n        logging.info(unique)\n", "meta": {"hexsha": "86a542fbcd4700f90b5dc302a0fe6391f21ec9e0", "size": 11184, "ext": "py", "lang": "Python", "max_stars_repo_path": "vq_vae/auto_encoder.py", "max_stars_repo_name": "pedrodiamel/VQ-VAE", "max_stars_repo_head_hexsha": "32268f783f54305f234d205ad12ff5a02b3fa191", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vq_vae/auto_encoder.py", "max_issues_repo_name": "pedrodiamel/VQ-VAE", "max_issues_repo_head_hexsha": "32268f783f54305f234d205ad12ff5a02b3fa191", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vq_vae/auto_encoder.py", "max_forks_repo_name": "pedrodiamel/VQ-VAE", "max_forks_repo_head_hexsha": "32268f783f54305f234d205ad12ff5a02b3fa191", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4173913043, "max_line_length": 98, "alphanum_fraction": 0.576269671, "include": true, "reason": "import numpy", "num_tokens": 3063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.19089558214578603}}
{"text": "\"\"\"Example to perform the combination between ANTARES and Super-Kamiokande.\n\nThis is taking benefit of the the specific formats described in ANTARES and Super-Kamiokande examples.\nAll provided values are dummy.\n\"\"\"\n\nimport healpy as hp\nimport numpy as np\n\nimport jang.gw\nimport jang.limits\nimport jang.results\nfrom jang.parameters import Parameters\nfrom jang.neutrinos import BackgroundFixed, Detector, SuperDetector\n\nfrom examples.superkamiokande import EffectiveAreaSK\n\n\ndef single_event(\n    gwname: str,\n    gwdbfile: str,\n    ant_results: dict,\n    sk_results: dict,\n    pars: Parameters,\n    dbfile: str = None,\n):\n\n    database_gw = jang.gw.Database(gwdbfile)\n    database_res = jang.results.Database(dbfile)\n\n    antares = Detector(\"examples/input_files/detector_antares.yaml\")\n    sk = Detector(\"examples/input_files/detector_superk.yaml\")\n    effarea_sk = [\n        EffectiveAreaSK(filename=sk_results[\"effarea\"], sample=s) for s in sk.samples\n    ]\n\n    # Combination\n    ant_sk = SuperDetector(\"ANTARES + Super-Kamiokande\")\n    ant_sk.add_detector(antares)\n    ant_sk.add_detector(sk)\n\n    gw = database_gw.find_gw(gwname)\n\n    antares.set_acceptances(ant_results[\"acceptances\"], pars.spectrum, pars.nside)\n    bkg_ant = [BackgroundFixed(b) for b in ant_results[\"nbkg\"]]\n    antares.set_observations(ant_results[\"nobs\"], bkg_ant)\n    pars.nside = antares.get_acceptances(pars[\"spectrum\"])[0].nside\n\n    accs = [\n        effarea.to_acceptance(sk, pars.nside, gw.jd, pars.spectrum)\n        for effarea in effarea_sk\n    ]\n    sk.set_acceptances(accs, pars.spectrum, pars.nside)\n    bkg_sk = [BackgroundFixed(b) for b in sk_results[\"nbkg\"]]\n    sk.set_observations(sk_results[\"nobs\"], bkg_sk)\n\n    limit_flux = jang.limits.get_limit_flux(ant_sk, gw, pars)\n    limit_etot = jang.limits.get_limit_etot(ant_sk, gw, pars)\n    limit_fnu = jang.limits.get_limit_fnu(ant_sk, gw, pars)\n    database_res.add_entry(\n        ant_sk, gw, pars, limit_flux, limit_etot, limit_fnu, None, None, None\n    )\n\n    if dbfile is not None:\n        database_res.save()\n\n\nif __name__ == \"__main__\":\n\n    pars = Parameters(\"examples/input_files/config.yaml\")\n    pars.set_models(\"x**-2\", jang.conversions.JetIsotropic())\n\n    gw_db_file = \"examples/input_files/gw_catalogs/database_example.csv\"\n    npix = hp.nside2npix(8)\n    ant_results = {\n        \"nobs\": [0, 0, 0, 0],\n        \"nbkg\": [0, 0, 0, 0],\n        \"acceptances\": [np.ones(npix), np.zeros(npix), np.ones(npix), np.zeros(npix)],\n    }\n    sk_results = {\n        \"nobs\": [0, 0, 0],\n        \"nbkg\": [0, 0, 0],\n        \"effarea\": \"examples/input_files/effarea_superk.root\",\n    }\n    single_event(\"GW190412\", gw_db_file, ant_results, sk_results, pars)\n", "meta": {"hexsha": "b3ccee223eb846fcbc7a11b1b8f02d28f484e57c", "size": 2694, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/combination.py", "max_stars_repo_name": "mlamo/pyjang", "max_stars_repo_head_hexsha": "7aa5c9ef8b14d672c4f231e25b809eaa4ca1015d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/combination.py", "max_issues_repo_name": "mlamo/pyjang", "max_issues_repo_head_hexsha": "7aa5c9ef8b14d672c4f231e25b809eaa4ca1015d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/combination.py", "max_forks_repo_name": "mlamo/pyjang", "max_forks_repo_head_hexsha": "7aa5c9ef8b14d672c4f231e25b809eaa4ca1015d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-19T22:02:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T22:02:24.000Z", "avg_line_length": 31.3255813953, "max_line_length": 102, "alphanum_fraction": 0.6948775056, "include": true, "reason": "import numpy", "num_tokens": 765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.19071473771351058}}
{"text": "#!/usr/bin/env python3\n#--coding:utf-8 --\n\"\"\"\ncallTransLoops.py\n\"\"\"\n\n#sys\nimport os\nimport sys\nimport json\nfrom glob import glob\nfrom datetime import datetime\nfrom collections import Counter\n\n#3rd\nimport joblib\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nfrom joblib import Parallel, delayed\nfrom sklearn import linear_model\nfrom scipy.stats import hypergeom, binom, poisson, combine_pvalues\n\n#cLoops\nfrom cLoops2.ds import Loop, XY\nfrom cLoops2.io import parseIxy, ixy2pet, loops2juiceTxt, loops2washuTxt, ixy2pet, updateJson, loops2txt\nfrom cLoops2.geo import checkLoopOverlap, combineLoops\nfrom cLoops2.settings import *\nfrom cLoops2.blockDBSCAN import blockDBSCAN as DBSCAN\nfrom cLoops2.callCisLoops import getPerRegions, selSigLoops, estAnchorSig\n\n\ndef runTransDBSCANLoops(fixy, eps, minPts):\n    \"\"\"\n    Run DBSCAN to detect interactions for one .ixy file.\n    @param fixy: str, .ixy file name \n    @param eps: int, eps for DBSCAN\n    @param minPts: int, minPts for DBSCAN\n    \"\"\"\n    loops, loopReads = [], []\n    key, mat = parseIxy(fixy, cut=0)\n    #gave mat each PET a id\n    mat2 = np.zeros((mat.shape[0],3))\n    mat2[:,0] = np.arange(mat.shape[0])\n    mat2[:,1] = mat[:,0]\n    mat2[:,2] = mat[:,1]\n    mat = mat2\n\n    #data for interaction records, read for readId\n    report = \"%s \\t Clustering %s and %s using eps %s, minPts %s\\n\" % (\n        datetime.now(), key[0], key[1], eps, minPts)\n    sys.stderr.write(report)\n    db = DBSCAN(mat, eps, minPts)\n    labels = pd.Series(db.labels)\n    mat = pd.DataFrame(mat[:, 1:].astype(\"int\"),\n                       index=mat[:, 0],\n                       columns=[\"X\", \"Y\"])\n    nlabels = set(labels.values)\n    #collect clusters\n    for label in nlabels:\n        los = list(labels[labels == label].index)\n        loopReads.extend(los)\n        sub = mat.loc[los, :]\n        if int(np.min(sub[\"X\"])) == int(np.max(sub[\"X\"])) or int(\n                np.min(sub[\"Y\"])) == int(np.max(sub[\"Y\"])):\n            continue\n        #define loops\n        loop = Loop()\n        loop.rab = sub.shape[0]\n        loop.chromX = key[0]\n        loop.chromY = key[1]\n        loop.x_start = int(np.min(sub[\"X\"]))\n        loop.x_end = int(np.max(sub[\"X\"]))\n        loop.x_center = (loop.x_start + loop.x_end) / 2\n        loop.y_start = int(np.min(sub[\"Y\"]))\n        loop.y_end = int(np.max(sub[\"Y\"]))\n        loop.y_center = (loop.y_start + loop.y_end) / 2\n        loop.distance = -1\n        loop.cis = False\n        loops.append(loop)\n    report = \"%s \\t Clustering %s and %s finished. Estimated %s reads for %s candidate loops. \\n\" % (\n        datetime.now(), key[0], key[1], len(loopReads), len(loops))\n    sys.stderr.write(report)\n    return \"-\".join(key), loops\n\n\n#related\ndef parallelRunTransDBSCANLoops(meta, eps, minPts, cpu=1):\n    \"\"\"\n    Paralle version of runCisDBSCANLoops\n    @param meta: meta information parsed form petMeta.json\n    @param eps: int, eps for DBSCAN\n    @param minPts: int, minPts for DBSCAN\n    \"\"\"\n    ds = Parallel(n_jobs=cpu,backend=\"multiprocessing\")(delayed(runTransDBSCANLoops)(\n        meta[\"data\"][\"trans\"][key][\"ixy\"], eps, minPts)\n                              for key in meta[\"data\"][\"trans\"].keys())\n    loops = {}\n    for d in ds:\n        if d is not None and len(d[1]) > 0:\n            key, di = d[0], d[1]\n            loops[key] = di\n    return loops\n\n\ndef estLoopSig(key,\n               loops,\n               fixy,\n               minPts=5,\n               pseudo=1,\n               peakPcut=1e-5,\n               peakFccut=2,\n               countDiffCut=10):\n    \"\"\"\n    Estimate the loop statstical significance for one chromosomal.\n    @param loops: list of Loop object\n    @param fixy: cLoops2 pre generated .ixy file\n    @param minPts: int, minPts\n    \"\"\"\n    xy = ixy2pet(fixy, cut=0)\n    N = xy.number\n    print(\"%s \\t Estimate significance for %s candidate interactions in %s.\" %\n          (datetime.now(), len(loops), key))\n    nloops = []\n    for loop in tqdm(loops):\n        ra, rb, rab = xy.queryLoop(loop.x_start, loop.x_end, loop.y_start,\n                                   loop.y_end)\n        ra, rb, rab = len(ra), len(rb), len(rab)\n        if rab < minPts:\n            continue\n        loop.ra = ra\n        loop.rb = rb\n        loop.rab = rab\n        #unbalanced anchor density, to avoid lines, unknow reason for lines, maybe stripes\n        if ra / float(rb) > countDiffCut or rb / float(ra) > countDiffCut:\n            continue\n        if (loop.x_end -\n                loop.x_start) / (loop.y_end - loop.y_start) > countDiffCut or (\n                    loop.y_end - loop.y_start) / (loop.x_end -\n                                                  loop.x_start) > countDiffCut:\n            continue\n        lowerra, lowerrb, lowerrab = xy.queryLoop(\n            loop.x_start - (loop.x_end - loop.x_start), loop.x_start,\n            loop.y_start - (loop.y_end - loop.y_start), loop.y_start)  #p2ll\n        loop.P2LL = float(rab) / max(len(lowerrab), pseudo)\n        px, esx = estAnchorSig(xy, loop.x_start, loop.x_end)\n        py, esy = estAnchorSig(xy, loop.y_start, loop.y_end)\n        loop.x_peak_poisson_p_value = px\n        loop.x_peak_es = esx\n        loop.y_peak_poisson_p_value = py\n        loop.y_peak_es = esy\n        #hypergeometric p-value\n        hyp = max([1e-300, hypergeom.sf(rab - 1.0, N, ra, rb)])\n        #start caculate the permutated background\n        rabs, nbps = [], []\n        nas, nbs = getPerRegions(loop, xy)\n        for na in nas:\n            nac = float(len(na))\n            for nb in nbs:\n                nbc = float(len(nb))\n                nrab = float(len(na.intersection(nb)))\n                #collect the value for poisson test\n                rabs.append(nrab)\n                #collect the possibility for following binomial test\n                if nac > 0 and nbc > 0:\n                    den = nrab / (nac * nbc)\n                    nbps.append(den)\n                else:\n                    nbps.append(0.0)\n        rabs, nbps = np.array(rabs), np.array(nbps)\n        mrabs = float(np.mean(rabs))\n        mbps = np.mean(nbps)\n        #local fdr\n        fdr = len(rabs[rabs > rab]) / float(len(rabs))\n        #enrichment score\n        es = rab / max(mrabs, pseudo)\n        #simple possion test\n        pop = max([1e-300, poisson.sf(rab - 1.0, mrabs)])\n        #simple binomial test\n        nbp = max([\n            1e-300, binom.sf(rab - 1.0, ra * rb, mbps)\n        ])  #the p-value is quit similar to that of cLoops 1 binomial test\n        loop.FDR = fdr\n        loop.ES = es\n        loop.density = float(\n            loop.rab) / (loop.x_end - loop.x_start + loop.y_end -\n                         loop.y_start) / N * 10.0**9\n        loop.hypergeometric_p_value = hyp\n        loop.poisson_p_value = pop\n        loop.binomial_p_value = nbp\n        nloops.append(loop)\n        #print(ra,rb,rab,mrabs,es,fdr,hyp,pop,nbp,n,nbp2)\n    return key, nloops\n\n\ndef markSigLoops(key, loops):\n    \"\"\"\n    Mark the significance of different loops.\n    \"\"\"\n    sig = lambda x: True if x.binomial_p_value <= 1e-10 and x.FDR <= 0.05 and loop.ES >= 2 else False\n    for loop in loops:\n        if sig(loop):\n            loop.significant = 1\n        else:\n            loop.significant = 0\n    return key, loops\n\n\ndef callTransLoops(\n        predir,\n        fout,\n        logger,\n        eps=[2000, 5000],\n        minPts=[5, 10],\n        cpu=1,\n        filter=False,\n        washU=False,\n        juicebox=False,\n):\n    \"\"\"\n    Call inter-chromosomal loops parallel.\n    @param metaf: str, petMeta.json file for calling peaks\n    @param eps: list\n    @param minPts: list\n    \"\"\"\n\n    metaf = predir + \"/petMeta.json\"\n    meta = json.loads(open(metaf).read())\n    ## step 1 find the candidate loops by running multiple times of clustering\n    loops = {}  #candidate loops\n    for ep in eps:\n        for minPt in minPts:\n            loops_2 = parallelRunTransDBSCANLoops(meta, ep, minPt, cpu=cpu)\n            loops = combineLoops(loops, loops_2)\n    ## step 2 determine the statstical significance of candidate loops\n    logger.info(\"Estimating loop statstical significance.\")\n    ds = Parallel(n_jobs=cpu,backend=\"multiprocessing\")(delayed(estLoopSig)(\n        key,\n        loops[key],\n        meta[\"data\"][\"trans\"][key][\"ixy\"],\n        minPts=max(minPts),\n    ) for key in loops.keys())\n    nds = {}\n    for d in ds:\n        nds[d[0]] = d[1]\n\n    #mark the significant loops\n    ds = Parallel(n_jobs=cpu,backend=\"multiprocessing\")(delayed(markSigLoops)(key, nds[key])\n                              for key in nds.keys())\n    nds = {}\n    for d in ds:\n        nds[d[0]] = d[1]\n\n    ## step 4 for the overlapped loops, output the most significant one\n    logger.info(\"Selecting the most significant loops of overlapped ones. \")\n    ds = Parallel(n_jobs=cpu,backend=\"multiprocessing\")(delayed(selSigLoops)(key, nds[key])\n                              for key in nds.keys())\n    nds = {}\n    for d in ds:\n        nds[d[0]] = d[1]\n    ds = Parallel(n_jobs=cpu,backend=\"multiprocessing\")(delayed(selSigLoops)(key, nds[key])\n                              for key in nds.keys())\n    nds = {}\n    for d in ds:\n        nds[d[0]] = d[1]\n    loops = []\n    for d in ds:\n        loops.extend(d[1])\n    ## step 5 output\n    logger.info(\"Output %s loops to %s_loops.txt\" % (len(loops), fout))\n    loops2txt(loops, fout + \"_trans_loops.txt\")\n    if washU:\n        loops2washuTxt(loops, fout + \"_trans_loops_washU.txt\")\n    if juicebox:\n        loops2juiceTxt(loops, fout + \"_trans_loops_juicebox.txt\")\n", "meta": {"hexsha": "ff16627b9a8237e598a037f05e540d69240b678d", "size": 9513, "ext": "py", "lang": "Python", "max_stars_repo_path": "cLoops2/callTransLoops.py", "max_stars_repo_name": "KejiZhaoLab/cLoops2", "max_stars_repo_head_hexsha": "2a1ce6b63a912cdd282dc40718d2c7333e3c16b2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2021-07-17T07:39:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T05:35:59.000Z", "max_issues_repo_path": "cLoops2/callTransLoops.py", "max_issues_repo_name": "KejiZhaoLab/cLoops2", "max_issues_repo_head_hexsha": "2a1ce6b63a912cdd282dc40718d2c7333e3c16b2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-31T07:56:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T16:20:29.000Z", "max_forks_repo_path": "cLoops2/callTransLoops.py", "max_forks_repo_name": "KejiZhaoLab/cLoops2", "max_forks_repo_head_hexsha": "2a1ce6b63a912cdd282dc40718d2c7333e3c16b2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-07-22T03:56:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T05:52:14.000Z", "avg_line_length": 34.4673913043, "max_line_length": 104, "alphanum_fraction": 0.5724797645, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.19071473397123534}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 10 10:32:04 2018\n\n@author: smrak\n\"\"\"\nimport numpy as np\nfrom datetime import datetime\nimport apexpy as ap\nimport igrf12\nimport cartopy.crs as ccrs\nimport cartopy.feature as cfeature\nfrom cartopy.feature.nightshade import Nightshade\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mticker\nfrom sunrise import terminator as ter\n\nprojection_dict = {'stereo': ccrs.Stereographic(), \n              'merc': ccrs.Mercator(),\n              'plate': ccrs.PlateCarree(),\n              'lambert': ccrs.LambertConformal(),\n              'mollweide': ccrs.Mollweide(),\n              'north': ccrs.NorthPolarStereo(),\n              'south': ccrs.NorthPolarStereo(),\n              'ortographic': ccrs.Orthographic()\n                  }\n\ndef plotCartoMap(latlim=[0, 75], lonlim=[-40, 40], parallels=None, meridians=None,\n                 pole_center_lon=0,figsize=(12, 8), terrain=False, ax=False,\n                 projection='stereo', title='', resolution='110m', lon0=None,lat0=None,\n                 states=True, grid_linewidth=0.5, grid_color='black', \n                 grid_linestyle='--', background_color=None, border_color='k',\n                 figure=False, nightshade=False, ns_alpha=0.1,\n                 apex=False, igrf=False, date=None, \n                 mlat_levels=None, mlon_levels=None, alt_km=0.0,\n                 mlon_colors='blue', mlat_colors='red', mgrid_width=1,\n                 mgrid_labels=True, mgrid_fontsize=12, mlon_cs='mlon',\n                 incl_levels=None, decl_levels=None, igrf_param='incl',\n                 mlon_labels=True, mlat_labels=True, mgrid_style='--',\n                 label_colors='k', apex_alt=0,\n                 decl_colors='k', incl_colors='k',\n                 terminator=False, terminator_altkm=350,\n                 polarization_terminator=False, pt_hemisphere='north',\n                 ter_color='red', ter_style='--', ter_width=2,\n                 midnight=False, midnight_colors='m', midnight_width=2,\n                 midnight_style='--'):\n    if lonlim is None or lonlim == []:\n        lonlim = [-180, 180]\n    STATES = cfeature.NaturalEarthFeature(\n        category='cultural',\n        name='admin_1_states_provinces_lines',\n        scale='50m',\n        facecolor='none')\n    \n    \n    if not ax:\n        if figsize is None:\n            fig = plt.figure()\n        else:\n            fig = plt.figure(figsize=figsize)\n        \n        if projection == 'stereo':\n            ax = plt.axes(projection=ccrs.Stereographic(central_longitude=(sum(lonlim)/2)))\n        elif projection == 'merc':\n            ax = plt.axes(projection=ccrs.Mercator())\n        elif projection == 'plate':\n            ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=(sum(lonlim)/2)))\n        elif projection == 'lambert':\n            ax = plt.axes(projection=ccrs.LambertConformal(central_longitude=(sum(lonlim)/2),\n                                                           central_latitude=(sum(latlim)/2)))\n        elif projection == 'mollweide':\n            ax = plt.axes(projection=ccrs.Mollweide(central_longitude=(sum(lonlim)/2)))\n        elif projection == 'north':\n            if lon0 is None:\n                lon0 = 0\n            ax = plt.axes(projection=ccrs.NorthPolarStereo(central_longitude=lon0))\n        elif projection == 'south':\n            if lon0 is None:\n                lon0 = 0\n            ax = plt.axes(projection=ccrs.SouthPolarStereo(central_longitude=lon0))\n        elif projection == 'ortographic':\n            if lon0 is None:\n                lon0 = 0\n            if lat0 is None:\n                lat0 = 0\n            ax = plt.axes(projection=ccrs.Orthographic(central_longitude=lon0, central_latitude=lat0))\n        else:\n            print (\"Projection is invalid. Please enter the right one. \\n \\\n                   'stereo', 'merc', 'plate', 'lambret', mollweide', 'north, 'south', 'ortographic'\")\n            return 0\n    if background_color is not None:\n        ax.background_patch.set_facecolor(background_color)\n    ax.set_title(title)\n    ax.coastlines(color=border_color, resolution=resolution)  # 110m, 50m or 10m\n    if states:\n        ax.add_feature(STATES, edgecolor=border_color)\n    ax.add_feature(cfeature.BORDERS, edgecolor=border_color)\n    if terrain:\n        ax.stock_img()\n    if nightshade:\n        assert date is not None\n        assert ns_alpha is not None\n        ax.add_feature(Nightshade(date, ns_alpha))\n    # Draw Parralels\n    if projection == 'merc' or projection == 'plate':\n        if isinstance(meridians, np.ndarray):\n            meridians = list(meridians)\n        if isinstance(parallels, np.ndarray):\n            parallels = list(parallels)\n        \n        gl = ax.gridlines(crs=ccrs.PlateCarree(), color=grid_color, draw_labels=False,\n                          linestyle=grid_linestyle, linewidth=grid_linewidth)\n        if meridians is None:\n            gl.xlines = False\n        else:\n            if len(meridians) > 0:\n                gl.xlocator = mticker.FixedLocator(meridians)\n                gl.xlabels_bottom = True\n            else:\n                gl.ylines = False\n                \n        if parallels is None:\n            gl.ylines = False\n        else:\n            if len(parallels) > 0:\n                gl.ylocator = mticker.FixedLocator(parallels)\n                gl.ylabels_left = True\n            else:\n                gl.ylines = False\n    else:\n        gl = ax.gridlines(crs=ccrs.PlateCarree(), color=grid_color, draw_labels=False,\n                          linestyle=grid_linestyle, linewidth=grid_linewidth)\n        if meridians is None:\n            gl.xlines = False\n        else:\n            gl.xlocator = mticker.FixedLocator(meridians)\n        if parallels is not None: \n            if isinstance(parallels, np.ndarray):\n                parallels = list(parallels)\n            gl.ylocator = mticker.FixedLocator(parallels)\n        else:\n            gl.ylines = False\n        \n    # Geomagnetic coordinates @ Apex\n    if apex:\n        if date is None:\n            date = datetime(2017, 12, 31, 0, 0, 0)\n        assert isinstance(date, datetime)\n        \n        A = ap.Apex(date = date)\n        # Define levels and ranges for conversion\n        if mlon_cs == 'mlt':\n            if mlon_levels is None:\n                mlon_levels = np.array([])\n                mlon_range = np.arange(0, 24.01, 0.01)\n            elif isinstance(mlon_levels, bool):\n                if mlon_levels == False:\n                    mlon_levels = np.array([])\n                    mlon_range = np.arange(0, 24.01, 0.01)\n            else:\n                mlon_range = np.arange(mlon_levels[0], mlon_levels[-1]+0.1, 0.01)\n        else:\n            if mlon_levels is None:\n                mlon_levels = np.array([])\n                mlon_range = np.arange(-180,180,0.5)\n            elif isinstance(mlon_levels, bool):\n                if mlon_levels == False:\n                    mlon_levels = np.array([])\n                    mlon_range = np.arange(-180, 181, 0.1)\n            else:\n                mlon_range = np.arange(mlon_levels[0], mlon_levels[0]+362, 0.1)\n        if mlat_levels is None:\n            mlat_levels = np.arange(-90, 90.1, 1)\n        mlat_range = np.arange(mlat_levels[0], mlat_levels[-1]+0.1, 0.1)\n        \n        # Do meridans\n        for mlon in mlon_levels:\n            MLON = mlon * np.ones(mlat_range.size)\n            if mlon_cs == 'mlt':\n                y, x = A.convert(mlat_range, MLON, 'mlt', 'geo', datetime=date, height=apex_alt)\n            else:\n                y, x  = A.convert(mlat_range, MLON, 'apex', 'geo', height=apex_alt)\n            mlat_mask_extent = (y >=  latlim[0] + 0.2) & (y <=  latlim[1] - 0.2)\n            # Plot meridian\n            inmap = np.logical_and(x >= lonlim[0], x <= lonlim[1])\n            if np.sum(inmap) > 10:\n                ax.plot(np.unwrap(x[mlat_mask_extent], 180), \n                        np.unwrap(y[mlat_mask_extent], 90), c=mlon_colors, \n                         lw=mgrid_width, linestyle=mgrid_style, zorder=90,\n                         transform=ccrs.PlateCarree())\n                \n            # Labels\n            if mlon_labels:\n                ix = abs(y-np.mean(latlim)).argmin()\n                mx = x[ix] - 1 if mlon >=10 else x[ix] - 0.5\n                my = np.mean(latlim)\n                if np.logical_and(mx >= lonlim[0], mx <= lonlim[1]):\n                    if mlon_cs == 'mlt' and mlon != 0:\n                        ax.text(mx, my, str(int(mlon)), color=label_colors, \n                                 fontsize=14, backgroundcolor='white',\n                                 transform=ccrs.PlateCarree())\n                    elif mlon_cs != 'mlt' and mlon != 360:\n                        ax.text(mx, my, str(int(mlon)), color=label_colors, \n                                 fontsize=14, backgroundcolor='white',\n                                 transform=ccrs.PlateCarree())\n        # Do parallels\n        for mlat in mlat_levels:\n            MLAT = mlat * np.ones(mlon_range.size)\n            if mlon_cs == 'mlt':\n                gy, gx = A.convert(MLAT, mlon_range, 'mlt', 'geo', datetime=date, height=apex_alt)\n            else:\n                \n                gy, gx = A.convert(MLAT, mlon_range, 'apex', 'geo', datetime=date, height=apex_alt)\n            inmap = np.logical_and(gy >= latlim[0], gy <= latlim[1])\n            if np.sum(inmap) > 20:\n                ax.plot(np.unwrap(gx, 180), np.unwrap(gy, 90), c=mlat_colors,\n                         lw=mgrid_width, linestyle=mgrid_style, zorder=90,\n                         transform=ccrs.PlateCarree())\n                \n            # Labels\n            if mlat_labels:\n                ix = abs(gx-np.mean(lonlim)).argmin()\n                mx = np.mean(lonlim)\n                my = gy[ix] - 0.5\n                if np.logical_and(mx >= lonlim[0], mx <= lonlim[1]) and \\\n                np.logical_and(my >= latlim[0], my <= latlim[1]):\n                    ax.text(mx, my, str(int(mlat)), color=label_colors, \n                             fontsize=14, backgroundcolor='white',\n                             transform=ccrs.PlateCarree())\n    if igrf:\n        glon = np.arange(lonlim[0]-40, lonlim[1] + 40.1, 0.5)\n        glat = np.arange(-90, 90 + 0.1, 0.5)\n        longrid, latgrid = np.meshgrid(glon, glat)\n        mag = igrf12.gridigrf12(t=date, glat=latgrid, glon=longrid, alt_km=alt_km)\n        if decl_levels is not None:\n            z = mag.decl.values\n            for declination in decl_levels:\n                ax.contour(longrid, latgrid, z, levels=declination,  zorder=90,\n                             colors=decl_colors, transform=ccrs.PlateCarree())\n        if incl_levels is not None:\n            z = mag.incl.values\n            for inclination in incl_levels:\n                ax.contour(longrid, latgrid, z, levels=declination,  zorder=90,\n                                 colors=incl_colors, transform=ccrs.PlateCarree())\n    # Terminators\n    if terminator:\n        assert date is not None\n        if not isinstance(terminator_altkm, list):\n            terminator_altkm = [terminator_altkm]\n        for takm in terminator_altkm:\n            try:\n                glon_ter, glat_ter = ter.get_terminator(date, alt_km = takm)\n                if glon_ter is not None and glat_ter is not None:\n                    if isinstance(glon_ter, list):\n                        for i in range(len(glon_ter)):\n                            ax.plot(np.unwrap(glon_ter[i], 180), np.unwrap(glat_ter[i], 90),\n                                c=ter_color, lw=ter_width, ls=ter_style, zorder=90,\n                                transform=ccrs.PlateCarree())\n                    else:\n                        ax.plot(np.unwrap(glon_ter, 180), np.unwrap(glat_ter, 90),\n                                c=ter_color, lw=ter_width, ls=ter_style, zorder=90,\n                                transform=ccrs.PlateCarree())\n            except:\n                pass\n    if midnight:\n        mlat_range = np.arange(-89.9, 90.1, 0.1)\n        MLON = 0 * np.ones(mlat_range.size)\n        if mlon_cs == 'mlt':\n            y, x = A.convert(mlat_range, MLON, 'mlt', 'geo', datetime=date, height=apex_alt)\n        else:\n            y, x  = A.convert(mlat_range, MLON, 'apex', 'geo', height=apex_alt)\n        mlat_mask_extent = (y >=  latlim[0] + 0.2) & (y <=  latlim[1] - 0.2)\n        # Plot meridian\n        inmap = np.logical_and(x >= lonlim[0], x <= lonlim[1])\n        if np.sum(inmap) > 10:\n            ax.plot(np.unwrap(x[mlat_mask_extent], 180), \n                    np.unwrap(y[mlat_mask_extent], 90), c=midnight_colors, \n                     lw=midnight_width, linestyle=midnight_style, zorder=90,\n                     transform=ccrs.PlateCarree())\n    # Set Extent\n    if projection == 'north' or projection == 'south':\n        import matplotlib.path as mpath\n        ax.set_extent([-180, 181, latlim[0], latlim[1]], crs=ccrs.PlateCarree())\n        theta = np.linspace(0, 2*np.pi, 100)\n        center, radius = [0.5, 0.5], 0.5\n        verts = np.vstack([np.sin(theta), np.cos(theta)]).T\n        circle = mpath.Path(verts * radius + center)\n        ax.set_boundary(circle, transform=ax.transAxes)\n    elif lonlim[0] != -180 and lonlim[1] != 180:\n        ax.set_extent([lonlim[0], lonlim[1], latlim[0], latlim[1]], crs=ccrs.PlateCarree())#ccrs.PlateCarree())\n    \n    if 'fig' in locals():\n        return fig, ax\n    else:\n        return ax\n", "meta": {"hexsha": "dbc17ca8255edefea09cbad613cd0a9e66e9700e", "size": 13445, "ext": "py", "lang": "Python", "max_stars_repo_path": "cartomap/geogmap.py", "max_stars_repo_name": "gregstarr/cartomap", "max_stars_repo_head_hexsha": "46f0917c4315dede1a12a663de80cdde0ae73393", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-06-21T01:18:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-21T22:17:40.000Z", "max_issues_repo_path": "cartomap/geogmap.py", "max_issues_repo_name": "gregstarr/cartomap", "max_issues_repo_head_hexsha": "46f0917c4315dede1a12a663de80cdde0ae73393", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-10T13:05:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-10T13:05:18.000Z", "max_forks_repo_path": "cartomap/geogmap.py", "max_forks_repo_name": "gregstarr/cartomap", "max_forks_repo_head_hexsha": "46f0917c4315dede1a12a663de80cdde0ae73393", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-08-29T00:08:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T21:51:19.000Z", "avg_line_length": 45.2693602694, "max_line_length": 111, "alphanum_fraction": 0.5373744887, "include": true, "reason": "import numpy", "num_tokens": 3458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.1907147302289603}}
{"text": "\n# WaveformToVolume Paraview filter\n\n# Load the `WaveformDataReader` to access its VTK keys\n# sys.path.append(os.path.dirname(__file__))\n# from WaveformDataReader import WaveformDataReader\n\nimport numpy as np\nimport logging\nimport time\nfrom vtkmodules.vtkCommonDataModel import vtkUniformGrid\nfrom vtkmodules.vtkCommonCore import vtkDataArraySelection\nfrom vtkmodules.util.vtkAlgorithm import VTKPythonAlgorithmBase\nfrom vtkmodules.numpy_interface import dataset_adapter as dsa\nfrom paraview.util.vtkAlgorithm import smproxy, smproperty, smdomain\nfrom paraview import util\nfrom paraview.vtk.util import numpy_support as vtknp\nimport gwpv.plugin_util.timesteps as timesteps_util\nimport gwpv.plugin_util.data_array_selection as das_util\nfrom gwpv import swsh_cache\nimport h5py\nfrom os.path import exists\nlogger = logging.getLogger(__name__)\n\n# A grid is created  here, and if analytical data created by creator.py\n# is recognized iti is loaded into the grid...\n\ngb_path = None\n\nif exists(\"timeseparated.h5\"):\n    gb_path = \"timeseparated.h5\"\nelif exists(\"gwpv/timeseparated.h5\"):\n    gb_path = \"gwpv/timeseparated.h5\"\nelse:\n    gb_path = None\n\nlogger.warning(\"Retrieving data from \"+str(gb_path)+\".\")\n\nif gb_path != None:\n    with h5py.File(gb_path, \"r\") as f:\n        h = f['Extrapolated_N2.dir']\n        tick = np.real(h['t_values.dir'])\n        strains = np.zeros((len(tick), 1000000), dtype=np.complex)\n        for i in range(len(tick)):\n            strains[i] += np.real(h['t_{}.dir'.format(tick[i])]) + 1j*np.imag(h['t_{}.dir'.format(tick[i])])\nelse:\n     logger.warning('No Bremsstrahlung data found, proceeding with merger visualization.')\n\n\n        \ndef get_mode_name(l, abs_m):\n    return \"({}, {}) Mode\".format(l, abs_m)\n\n\n# Reproduces `spherical_functions.LM_index` so we don't need to import the\n# `spherical_functions` module when using a cached SWSH grid\ndef LM_index(ell, m, ell_min):\n    return ell * (ell + 1) - ell_min ** 2 + m\n\n\ndef smoothstep(x):\n    return np.where(x < 0, 0, np.where(x <= 1, 3 * x**2 - 2 * x**3, 1))\n\n\ndef activation(x, width):\n    return smoothstep(x / width)\n\n\ndef deactivation(x, width, outer):\n    return smoothstep((outer - x) / width)\n\n\n# Caching\n# When using SwshGrid input this is not necessary anymore\n# These are global variables because setting them on the filter object appears\n# to trigger a \"ModifiedEvent\" so the data is recomputed.\n_cached_swsh_grid = None\n_cached_r = None\n_cached_grid_id = None\ndef cached_swsh_grid(size, radial_scale, activation_offset, activation_width, deactivation_width, add_one_over_r_scaling, **swsh_grid_kwargs):\n    global _cached_swsh_grid, _cached_r, _cached_grid_id\n    grid_id = dict(size=size,\n                   radial_scale=radial_scale,\n                   activation_offset=activation_offset,\n                   activation_width=activation_width,\n                   deactivation_width=deactivation_width,\n                   add_one_over_r_scaling=add_one_over_r_scaling)\n    grid_id.update(swsh_grid_kwargs)\n    if _cached_grid_id == grid_id:\n        logger.debug(\"Using cached SWSHs grid from memory.\")\n        return _cached_swsh_grid, _cached_r\n    else:\n        logger.debug(\"No SWSH grid in memory, retrieving from disk cache.\")\n        swsh_grid, r = swsh_cache.cached_swsh_grid(size=size,\n                                                   **swsh_grid_kwargs)\n        # Apply screening\n        screen = activation(r - activation_offset,\n                            activation_width) * deactivation(\n                                r, deactivation_width, size)\n        swsh_grid *= screen.reshape(screen.shape + (1, ))\n        # Apply radial scale\n        r *= radial_scale\n        if add_one_over_r_scaling:\n            swsh_grid /= (r + 1.e-30).reshape(r.shape + (1,))\n        # Cache and return\n        _cached_swsh_grid = swsh_grid\n        _cached_r = r\n        _cached_grid_id = grid_id\n        return swsh_grid, r\n\n\nhas_shown_warning_nonuniformly_sampled = False\n\n\n@smproxy.filter(label=\"Waveform To Volume\")\n@smproperty.input(name=\"WaveformData\", port_index=0)\n@smdomain.datatype(dataTypes=[\"vtkTable\"])\n# TODO: We should be able to use a `SwshGrid` as a second input to this filter\n# and use this class to compute the volume data for the waveform without having\n# to generate the grid. Multiple inputs work fine, but for some reason\n# `pv.LoadPlugin` doesn't load `SwshGrid`.\n# @smproperty.input(name=\"GridData\", port_index=1)\n# @smdomain.datatype(dataTypes=[\"vtkUniformGrid\"])\nclass WaveformToVolume(VTKPythonAlgorithmBase):\n    def __init__(self):\n        VTKPythonAlgorithmBase.__init__(\n            self,\n            # nInputPorts=2,\n            nInputPorts=1,\n            nOutputPorts=1,\n            # Choosing `vtkUniformGrid` for the output for the following reasons:\n            # - `vtkRectilinearGrid` doesn't support volume rendering\n            #   (in Paraview v5.7.0 at least)\n            # - The unstructured grids don't support the 'GPU Based'\n            #   volume rendering mode, which can do shading and looks nice\n            outputType='vtkUniformGrid')\n        self.modes_selection = vtkDataArraySelection()\n        # TODO: We should really retrieve the available modes from the input\n        # info in `RequestInformation`, but the `WAVEFORM_MODES` keys is not\n        # propagating downstream for some reason...\n        # modes_arrays_key = WaveformDataReader.MODES_ARRAYS_KEY\n        # if waveform_data_info.Has(modes_arrays_key):\n        #     for i in range(waveform_data_info.Length(modes_arrays_key)):\n        #         self.modes_selection.AddArray(waveform_data_info.Get(\n        #             modes_arrays_key, i))\n        for l in range(2, 5 + 1):\n            for m in range(0, l + 1):\n                self.modes_selection.AddArray(get_mode_name(l, m))\n        self.modes_selection.AddObserver(\n            \"ModifiedEvent\", das_util.create_modified_callback(self))\n        self.polarizations_selection = vtkDataArraySelection()\n        self.polarizations_selection.AddArray(\"Plus\")\n        self.polarizations_selection.AddArray(\"Cross\")\n        self.polarizations_selection.AddObserver(\n            \"ModifiedEvent\", das_util.create_modified_callback(self))\n\n    def FillInputPortInformation(self, port, info):\n        # When using multiple inputs we (may) have to set their data types here\n        # info.Set(self.INPUT_REQUIRED_DATA_TYPE(),\n        #          'vtkTable' if port == 0 else 'vtkUniformGrid')\n        info.Set(self.INPUT_REQUIRED_DATA_TYPE(), 'vtkTable')\n\n    def _get_waveform_data(self):\n        return dsa.WrapDataObject(self.GetInputDataObject(0, 0))\n\n    # def _get_grid_data(self):\n    #     return dsa.WrapDataObject(self.GetInputDataObject(1, 0))\n\n    @smproperty.dataarrayselection(name=\"Modes\")\n    def GetModes(self):\n        return self.modes_selection\n\n    @smproperty.intvector(name=\"StoreIndividualModes\", default_values=False)\n    def SetStoreIndividualModes(self, value):\n        self.store_individual_modes = value\n        self.Modified()\n\n    @smproperty.intvector(name=\"NormalizeEachMode\", default_values=False)\n    def SetNormalizeEachMode(self, value):\n        self.normalize_each_mode = value\n        self.Modified()\n\n    @smproperty.dataarrayselection(name=\"Polarizations\")\n    def GetPolarizations(self):\n        return self.polarizations_selection\n\n    # Not needed when using SwshGrid input\n    @smproperty.doublevector(name=\"Size\", default_values=100)\n    def SetSize(self, value):\n        self.size = value\n        self.Modified()\n\n    # Not needed when using SwshGrid input\n    @smproperty.intvector(name=\"SpatialResolution\", default_values=100)\n    def SetSpatialResolution(self, value):\n        self.num_points_per_dim = value\n        self.Modified()\n\n    @smproperty.intvector(name=\"KeepEveryNthTimestep\", default_values=1)\n    def SetKeepEveryNthTimestep(self, value):\n        self.keep_every_n_timestep = value\n        self.Modified()\n\n    # Not needed when using SwshGrid input\n    @smproperty.intvector(name=\"EllMax\", default_values=2)\n    def SetEllMax(self, value):\n        self.ell_max = value\n        self.Modified()\n\n    @smproperty.doublevector(name=\"RadialScale\", default_values=10)\n    def SetRadialScale(self, value):\n        self.radial_scale = value\n        self.Modified()\n\n    @smproperty.intvector(name=\"ClipYNormal\", default_values=False)\n    @smdomain.xml('<BooleanDomain name=\"bool\"/>')\n    def SetClipYNormal(self, value):\n        self.clip_y_normal = value\n        self.Modified()\n\n    @smproperty.intvector(name=\"ClipZNormal\", default_values=False)\n    @smdomain.xml('<BooleanDomain name=\"bool\"/>')\n    def SetClipZNormal(self, value):\n        self.clip_z_normal = value\n        self.Modified()\n\n    @smproperty.intvector(name=\"OneOverRScaling\", default_values=False)\n    @smdomain.xml('<BooleanDomain name=\"bool\"/>')\n    def SetOneOverRScaling(self, value):\n        self.add_one_over_r_scaling = value\n        self.Modified()\n\n    @smproperty.intvector(name=\"InvertRotationDirection\", default_values=False)\n    @smdomain.xml('<BooleanDomain name=\"bool\"/>')\n    def SetInvertRotationDirection(self, value):\n        self.invert_rotation_direction = value\n        self.Modified()\n\n    @smproperty.doublevector(name=\"ActivationOffset\", default_values=10)\n    def SetActivationOffset(self, value):\n        self.activation_offset = value\n        self.Modified()\n\n    @smproperty.doublevector(name=\"ActivationWidth\", default_values=10)\n    def SetActivationWidth(self, value):\n        self.activation_width = value\n        self.Modified()\n\n    @smproperty.doublevector(name=\"DeactivationWidth\", default_values=10)\n    def SetDeactivationWidth(self, value):\n        self.deactivation_width = value\n        self.Modified()\n\n    @smproperty.stringvector(name=\"SwshCacheDirectory\", default_values=\"\")\n    def SetSwshCacheDirectory(self, value):\n        self.swsh_cache_dir = value\n        self.Modified()\n\n    def _get_timesteps(self):\n        logger.debug(\"Getting time range from data...\")\n        waveform_data = self._get_waveform_data()\n        ts = waveform_data.RowData['Time']\n        # Using a few timesteps within the data range so we can animate through\n        # them in the GUI\n        return np.linspace(ts[0], ts[-1], 100)\n\n    @smproperty.doublevector(name=\"TimestepValues\",\n                             information_only=\"1\",\n                             si_class=\"vtkSITimeStepsProperty\")\n    def GetTimestepValues(self):\n        return self._get_timesteps().tolist()\n\n    def RequestInformation(self, request, inInfo, outInfo):\n        logger.debug(\"Requesting information...\")\n        waveform_data_info = inInfo[0].GetInformationObject(0)\n        # Careful with printing these information objects, their stream operator\n        # may randomly crash...\n        # logger.debug(\"Waveform data info: {}\".format(waveform_data_info))\n        # grid_info = inInfo[1].GetInformationObject(0)\n        info = outInfo.GetInformationObject(0)\n\n        # For the `vtkUniformGrid` output we need to provide extents\n        # so that it gets rendered at all.\n        # When using the SwshGrid input we can retrieve them from the\n        # information object and pass them on.\n        # grid_extents = grid_info.Get(self.GetExecutive().WHOLE_EXTENT())\n        N = self.num_points_per_dim\n        N_y = N // 2 if self.clip_y_normal else N\n        N_z = N // 2 if self.clip_z_normal else N\n        grid_extents = [0, N - 1, 0, N_y - 1, 0, N_z - 1]\n        util.SetOutputWholeExtent(self, grid_extents)\n\n        # This needs the time data from the waveform file, so we may have to\n        # set the `TIME_RANGE` and `TIME_STEPS` already in the\n        # WaveformDataReader.\n        timesteps_util.set_timesteps(self,\n                                     self._get_timesteps(),\n                                     logger=logger)\n\n        # logger.debug(\"Information object: {}\".format(info))\n        return 1\n\n    def RequestData(self, request, inInfo, outInfo):\n        logger.debug(\"Requesting data...\")\n        waveform_data = self._get_waveform_data()\n        # grid_data = self._get_grid_data()\n        output = dsa.WrapDataObject(vtkUniformGrid.GetData(outInfo))\n\n        t = timesteps_util.get_timestep(self, logger=logger)\n        N = self.num_points_per_dim\n        D = self.size\n\n        # We may have to forward the grid data here when using SwshGrid input\n        # output.SetDimensions(*grid_data.GetDimensions())\n        # output.SetOrigin(*grid_data.GetOrigin())\n        # output.SetSpacing(*grid_data.GetSpacing())\n        dx = 2. * D / N\n        N_y = N // 2 if self.clip_y_normal else N\n        N_z = N // 2 if self.clip_z_normal else N\n        output.SetDimensions(N, N_y, N_z)\n        output.SetOrigin(-D, -D, -D)\n        output.SetSpacing(dx, dx, dx)\n\n        # Compute the SWSHs on the grid\n        # This section can be deleted when using SwshGrid input\n        spin_weight = -2\n        ell_max = self.ell_max\n        \n        # We skip this section of the code if non-simulation data is handled\n        # since it becomes simply unnecessary.\n        if type(waveform_data.RowData['Y_l2_m2'][5]) is not dsa.VTKNoneArray:\n            swsh_grid, r = cached_swsh_grid(\n                size=D,\n                num_points=N,\n                spin_weight=spin_weight,\n                ell_max=ell_max,\n                radial_scale=self.radial_scale,\n                clip_y_normal=self.clip_y_normal,\n                clip_z_normal=self.clip_z_normal,\n                activation_offset=self.activation_offset,\n                activation_width=self.activation_width,\n                deactivation_width=self.deactivation_width,\n                add_one_over_r_scaling=self.add_one_over_r_scaling,\n                cache_dir=self.swsh_cache_dir)\n\n            logger.info(\"Computing volume data at t={}...\".format(t))\n        start_time = time.time()\n        \n        # We skip this section of the code if non-simulation data is handled\n        # since it becomes simply unnecessary.\n        if type(waveform_data.RowData['Y_l2_m2'][5]) is not dsa.VTKNoneArray:\n\n            # Compute scaled waveform phase on the grid\n            # r = vtknp.vtk_to_numpy(grid_data.GetPointData()['RadialCoordinate'])\n            phase = t - r\n\n            # Invert rotation direction\n            rotation_direction = -1. if self.invert_rotation_direction else 1.\n\n            # Compute strain in the volume from the input waveform data\n            skip_timesteps = self.keep_every_n_timestep\n            waveform_timesteps = waveform_data.RowData['Time'][::skip_timesteps]\n            strain = np.zeros(len(r), dtype=np.complex)\n            # Optimization for when the waveform is sampled uniformly\n            # TODO: Cache this\n        \n        # Here the code checks if non-simulation data was passed and visualizes the\n        # analytical data loaded erlier\n\n        if type(waveform_data.RowData['Y_l2_m2'][5]) is dsa.VTKNoneArray:\n            strain = np.zeros(1000000, dtype=np.complex)\n            # generate the index of the current timestep...\n            indexx = list(map(abs, list(waveform_data.RowData['Time'] - t + 1000))).index(\n                    np.min(list(map(abs, list(waveform_data.RowData['Time'] - t + 1000)))))\n            # ...and pass the associated column of the strains grid to teh starin value\n            # which is then visualized at the bottom\n            strain += 100*strains[indexx]\n                \n        else:\n\n\n            dt = np.diff(waveform_timesteps)\n            waveform_uniformly_sampled = np.allclose(dt, dt[0])\n            global has_shown_warning_nonuniformly_sampled\n            if waveform_uniformly_sampled:\n                dt = dt[0]\n                logger.debug(\"Waveform sampled uniformly with dt={:.2e}, using optimized interpolation:\".format(dt))\n                waveform_start_time = waveform_timesteps[0]\n                waveform_start_index = min(len(waveform_timesteps) - 2, max(\n                    0, int(np.floor((np.min(phase) - waveform_start_time) / dt))))\n                waveform_stop_index = max(waveform_start_index + 1, min(\n                    len(waveform_timesteps),\n                    int(np.ceil((np.max(phase) - waveform_start_time) / dt))))\n                if waveform_stop_index == len(waveform_timesteps):\n                    waveform_stop_index = -1\n                logger.debug(\n                    \"Restricting interpolation to waveform indices {}, that's between waveform times {}. We will interpolate to times between {} (should be contained in restricted waveform range except for boundary effects).\"\n                    .format((waveform_start_index, waveform_stop_index),\n                            (waveform_timesteps[waveform_start_index],\n                             waveform_timesteps[waveform_stop_index]),\n                            (np.min(phase), np.max(phase))))\n                waveform_timesteps = waveform_timesteps[waveform_start_index:waveform_stop_index]\n            elif not has_shown_warning_nonuniformly_sampled:\n                logger.warning(\"Waveform is not sampled uniformly so interpolation is slightly more expensive.\")\n                has_shown_warning_nonuniformly_sampled = True\n            # for i in range(self.modes_selection.GetNumberOfArrays()):\n            #     mode_name = self.modes_selection.GetArrayName(i)\n            for l in range(abs(spin_weight), ell_max + 1):\n                for abs_m in range(0, l + 1):\n                    mode_name = get_mode_name(l, abs_m)\n                    strain_mode = np.zeros(len(r), dtype=np.complex)\n                    if not self.modes_selection.ArrayIsEnabled(mode_name):\n                        continue\n                    for sign_m in (-1, 1):\n                        m = abs_m * sign_m\n                        dataset_name = \"Y_l{}_m{}\".format(l, m)\n                        mode_profile = swsh_grid[:, LM_index(l, m, 0)]\n                        # mode_profile = vtknp.vtk_to_numpy(grid_data.GetPointData()[dataset_name])\n                        waveform_mode_data = waveform_data.RowData[dataset_name][::skip_timesteps]\n                        if isinstance(waveform_mode_data, dsa.VTKNoneArray):\n                            logger.warning(\n                                \"Dataset '{}' for mode {} not available in waveform data, skipping.\"\n                                .format(dataset_name, (l, m)))\n                            continue\n                        # TODO: Make sure inverting the rotation direction like this\n                        # is correct.\n                        waveform_mode_data = waveform_mode_data[:, 0] + rotation_direction * 1j * waveform_mode_data[:, 1]\n                        if self.normalize_each_mode:\n                            waveform_mode_data /= np.max(np.abs(waveform_mode_data))\n                        if waveform_uniformly_sampled:\n                            waveform_mode_data = waveform_mode_data[waveform_start_index:waveform_stop_index]\n                        mode_data = np.interp(phase,\n                                              waveform_timesteps,\n                                              waveform_mode_data,\n                                              left=0.,\n                                              right=0.)\n                        strain_mode += mode_data * mode_profile\n                    strain += strain_mode\n                    # Expose individual modes in output\n                    if self.store_individual_modes:\n                        if self.polarizations_selection.ArrayIsEnabled(\"Plus\"):\n                            strain_mode_real_vtk = vtknp.numpy_to_vtk(\n                                np.real(strain_mode), deep=True)\n                            strain_mode_real_vtk.SetName(mode_name + ' Plus')\n                            output.GetPointData().AddArray(strain_mode_real_vtk)\n                        if self.polarizations_selection.ArrayIsEnabled(\"Cross\"):\n                            strain_mode_imag_vtk = vtknp.numpy_to_vtk(\n                                np.imag(strain_mode), deep=True)\n                            strain_mode_imag_vtk.SetName(mode_name + ' Cross')\n                            output.GetPointData().AddArray(strain_mode_imag_vtk)\n        if self.polarizations_selection.ArrayIsEnabled(\"Plus\"):\n            strain_real_vtk = vtknp.numpy_to_vtk(np.real(strain), deep=True)\n            strain_real_vtk.SetName('Plus strain')\n            output.GetPointData().AddArray(strain_real_vtk)\n        if self.polarizations_selection.ArrayIsEnabled(\"Cross\"):\n            strain_imag_vtk = vtknp.numpy_to_vtk(np.imag(strain), deep=True)\n            strain_imag_vtk.SetName('Cross strain')\n            output.GetPointData().AddArray(strain_imag_vtk)\n\n        logger.info(\"Volume data computed in {:.3f}s.\".format(time.time() -\n                                                              start_time))\n        return 1\n    \n", "meta": {"hexsha": "91c499e78b818def32e0d6a54bb6c3483bed7449", "size": 20906, "ext": "py", "lang": "Python", "max_stars_repo_path": "paraview_plugins/WaveformToVolume.py", "max_stars_repo_name": "damibabayemi/gwpv", "max_stars_repo_head_hexsha": "e6705787fc2e25b72eaef2508357b1f0b9258581", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paraview_plugins/WaveformToVolume.py", "max_issues_repo_name": "damibabayemi/gwpv", "max_issues_repo_head_hexsha": "e6705787fc2e25b72eaef2508357b1f0b9258581", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paraview_plugins/WaveformToVolume.py", "max_forks_repo_name": "damibabayemi/gwpv", "max_forks_repo_head_hexsha": "e6705787fc2e25b72eaef2508357b1f0b9258581", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-30T19:37:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-30T19:37:13.000Z", "avg_line_length": 45.0560344828, "max_line_length": 225, "alphanum_fraction": 0.631732517, "include": true, "reason": "import numpy", "num_tokens": 4631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3415824927356586, "lm_q1q2_score": 0.1907147264866851}}
{"text": "# all lifetimes in years\n\nimport numpy as np\n\nCO2         = np.nan # dummy - to preserve indexing order\nCH4         = 9.3   # for constant lifetime runs\nN2O         = 121.\nCF4         = 50000.\nC2F6        = 10000.\nC3F8        = 2600. \nC4F10       = 2600.\nC5F12       = 4100.\nC6F14       = 3100.\nC7F16       = 3000.\nC8F18       = 3000.\nC_C4F8      = 3200.\nHFC23       = 222.\nHFC32       = 5.2\nHFC43_10    = 16.1\nHFC43_10MEE = HFC43_10\nHFC125      = 28.2\nHFC134A     = 13.4\nHFC143A     = 47.1\nHFC152A     = 1.5\nHFC227EA    = 38.9\nHFC236FA    = 242.\nHFC245FA    = 7.7\nHFC365MFC   = 8.7\nSF6         = 3200.\nNF3         = 500.\nSO2F2       = 36.\nCFC11       = 45.\nCFC12       = 100.\nCFC113      = 85.\nCFC114      = 190.\nCFC115      = 1020.\nCARB_TET    = 26.\nCCL4        = CARB_TET\nMCF         = 5.\nCH3CCL3     = MCF\nHCFC22      = 11.9\nHCFC141B    = 9.2\nHCFC142B    = 17.2\nHALON1211   = 16.\nHALON1202   = 2.9\nHALON1301   = 65.\nHALON2402   = 20.\nCH3BR       = 0.8\nCH3CL       = 1.\nCH2CL2      = 0.3945  # from Hodnebrog et al., 2013\nCHCL3       = 0.4082  # from Hodnebrog et al., 2013\n\n# This is the list of gases included in the RCPs/AR5/CMIP5.\naslist   = [CO2, CH4, N2O, CF4, C2F6, C6F14, HFC23, HFC32, HFC43_10, HFC125,\n            HFC134A, HFC143A, HFC227EA, HFC245FA, SF6, CFC11, CFC12, CFC113,\n            CFC114, CFC115, CARB_TET, MCF, HCFC22, HCFC141B, HCFC142B,\n            HALON1211, HALON1202, HALON1301, HALON2402, CH3BR, CH3CL]\n", "meta": {"hexsha": "86f0c1c572942a092023270beb99cef1a587a2aa", "size": 1433, "ext": "py", "lang": "Python", "max_stars_repo_path": "fair/constants/lifetime.py", "max_stars_repo_name": "markperri/FAIR", "max_stars_repo_head_hexsha": "4aa7c6137a07585b7d56044a3e4506ca9c7de03c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 66, "max_stars_repo_stars_event_min_datetime": "2017-06-20T10:30:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T19:11:06.000Z", "max_issues_repo_path": "fair/constants/lifetime.py", "max_issues_repo_name": "juliaeis/FAIR", "max_issues_repo_head_hexsha": "997fb82f954a41196808ec74113207de38d4b295", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 99, "max_issues_repo_issues_event_min_datetime": "2017-03-29T01:59:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T08:45:23.000Z", "max_forks_repo_path": "fair/constants/lifetime.py", "max_forks_repo_name": "juliaeis/FAIR", "max_forks_repo_head_hexsha": "997fb82f954a41196808ec74113207de38d4b295", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2017-03-30T04:02:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T17:13:43.000Z", "avg_line_length": 24.7068965517, "max_line_length": 76, "alphanum_fraction": 0.5540823447, "include": true, "reason": "import numpy", "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.1907147252082495}}
{"text": "# This script computes the relative hydration free energy with a single topology protocol.\n# It checks to make sure the estimated dG is in agreement between the following three methods:\n# 1) Two seperate absolute free energy calculations\n# 2) Relative free energy with full atom-mapping\n# 3) Relative free energy with partial atom-mapping (4D-decoupling)\n\nimport os\nimport argparse\nimport numpy as np\n\nfrom rdkit import Chem\nfrom rdkit.Chem import rdFMCS\nfrom rdkit.Chem import AllChem\n\nfrom fe import topology\nfrom md import builders\nfrom md import minimizer\n\nimport functools\n\nfrom ff import Forcefield\nfrom ff.handlers.deserialize import deserialize_handlers\n\nimport multiprocessing\n\nfrom fe import free_energy\n\n\ndef wrap_method(args, fn):\n    gpu_idx = args[0]\n    os.environ['CUDA_VISIBLE_DEVICES'] = str(gpu_idx)\n    return fn(*args[1:])\n\nif __name__ == \"__main__\":\n\n    parser = argparse.ArgumentParser(\n        description=\"Relative Hydration Free Energy Consistency Testing\",\n        formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n    )\n\n    parser.add_argument(\n        \"--num_gpus\",\n        type=int,\n        help=\"number of gpus\",\n        required=True\n    )\n\n    parser.add_argument(\n        \"--num_vacuum_windows\",\n        type=int,\n        help=\"number of vacuum lambda windows\",\n        required=True\n    )\n\n    parser.add_argument(\n        \"--num_solvent_windows\",\n        type=int,\n        help=\"number of solvent lambda windows\",\n        required=True\n    )\n\n    parser.add_argument(\n        \"--num_equil_steps\",\n        type=int,\n        help=\"number of equilibration steps for each lambda window\",\n        required=True\n    )\n\n    parser.add_argument(\n        \"--num_prod_steps\",\n        type=int,\n        help=\"number of production steps for each lambda window\",\n        required=True\n    )\n\n    parser.add_argument(\n        \"--num_absolute_windows\",\n        type=int,\n        help=\"number of absolute lambda windows\",\n        required=True\n    )\n\n    cmd_args = parser.parse_args()\n\n    multiprocessing.set_start_method('spawn') # CUDA runtime is not forkable\n    pool = multiprocessing.Pool(cmd_args.num_gpus)\n\n    suppl = Chem.SDMolSupplier('tests/data/benzene_fluorinated.sdf', removeHs=False)\n    all_mols = [x for x in suppl]\n    mol_a = all_mols[0]\n    mol_b = all_mols[1]\n\n    ff_handlers = deserialize_handlers(open('ff/params/smirnoff_1_1_0_ccc.py').read())\n    ff = Forcefield(ff_handlers)\n\n    # the water system first.\n    solvent_system, solvent_coords, solvent_box, omm_topology = builders.build_water_system(4.0)\n    solvent_box += np.eye(3)*0.1 # BFGS this later\n\n    print(\"Minimizing the host structure to remove clashes.\")\n    minimized_solvent_coords = minimizer.minimize_host_4d([mol_a], solvent_system, solvent_coords, ff, solvent_box)\n\n    absolute_lambda_schedule = np.concatenate([\n        np.linspace(0.0, 0.333, cmd_args.num_absolute_windows - cmd_args.num_absolute_windows//3, endpoint=False),\n        np.linspace(0.333, 1.0, cmd_args.num_absolute_windows//3),\n    ])\n\n    abs_dGs = []\n\n    for idx, mol in enumerate([mol_a, mol_b]):\n\n        afe = free_energy.AbsoluteFreeEnergy(mol, ff)\n        absolute_args = []\n\n        for lambda_idx, lamb in enumerate(absolute_lambda_schedule):\n            gpu_idx = lambda_idx % cmd_args.num_gpus\n            absolute_args.append((gpu_idx, lamb, solvent_system, minimized_solvent_coords, solvent_box, cmd_args.num_equil_steps, cmd_args.num_prod_steps))\n\n        results = pool.map(functools.partial(wrap_method, fn=afe.host_edge), absolute_args, chunksize=1)\n\n        for lamb, (bonded_du_dl, nonbonded_du_dl) in zip(absolute_lambda_schedule, results):\n            print(\"final absolute\", idx, \"lambda\", lamb, \"bonded:\", bonded_du_dl[0], bonded_du_dl[1], \"nonbonded:\", nonbonded_du_dl[0], nonbonded_du_dl[1])\n\n        dG = np.trapz([x[0][0]+x[1][0] for x in results], absolute_lambda_schedule)\n        print(\"mol\", idx, \"dG absolute:\", dG)\n        abs_dGs.append(dG)\n\n    print(\"Absolute Difference\", abs_dGs[0] - abs_dGs[1])\n\n    # relative free energy, compare two different core approaches\n\n    core_full = np.stack([\n        np.arange(mol_a.GetNumAtoms()),\n        np.arange(mol_b.GetNumAtoms())\n    ], axis=1)\n\n    core_part = np.stack([\n        np.arange(mol_a.GetNumAtoms() - 1),\n        np.arange(mol_b.GetNumAtoms() - 1)\n    ], axis=1)\n\n    for core_idx, core in enumerate([core_full, core_part]):\n        single_topology = topology.SingleTopology(mol_a, mol_b, core, ff)\n\n        rfe = free_energy.RelativeFreeEnergy(single_topology)\n\n        vacuum_lambda_schedule = np.linspace(0.0, 1.0, cmd_args.num_vacuum_windows)\n        solvent_lambda_schedule = np.linspace(0.0, 1.0, cmd_args.num_solvent_windows)\n\n        # vacuum leg\n        vacuum_args = []\n        for lambda_idx, lamb in enumerate(vacuum_lambda_schedule):\n            gpu_idx = lambda_idx % cmd_args.num_gpus\n            vacuum_args.append((gpu_idx, lamb, cmd_args.num_equil_steps, cmd_args.num_prod_steps))\n\n        results = pool.map(functools.partial(wrap_method, fn=rfe.vacuum_edge), vacuum_args, chunksize=1)\n\n        # TODO: update this to reflect new return type of rfe.vacuum_edge\n        for lamb, (bonded_du_dl, nonbonded_du_dl) in zip(vacuum_lambda_schedule, results):\n            print(\"final vacuum lambda\", lamb, \"bonded:\", bonded_du_dl[0], bonded_du_dl[1], \"nonbonded:\", nonbonded_du_dl[0], nonbonded_du_dl[1])\n\n        dG_vacuum = np.trapz([x[0][0]+x[1][0] for x in results], vacuum_lambda_schedule)\n        print(\"dG vacuum:\", dG_vacuum)\n\n        # solvent leg\n        solvent_args = []\n        for lambda_idx, lamb in enumerate(solvent_lambda_schedule):\n            gpu_idx = lambda_idx % cmd_args.num_gpus\n            solvent_args.append((gpu_idx, lamb, solvent_system, minimized_solvent_coords, solvent_box, cmd_args.num_equil_steps, cmd_args.num_prod_steps))\n        \n        results = pool.map(functools.partial(wrap_method, fn=rfe.host_edge), solvent_args, chunksize=1)\n        # TODO: update this to reflect new return type of rfe.vacuum_edge\n\n        for lamb, (bonded_du_dl, nonbonded_du_dl) in zip(solvent_lambda_schedule, results):\n            print(\"final solvent lambda\", lamb, \"bonded:\", bonded_du_dl[0], bonded_du_dl[1], \"nonbonded:\", nonbonded_du_dl[0], nonbonded_du_dl[1])\n\n        dG_solvent = np.trapz([x[0][0]+x[1][0] for x in results], solvent_lambda_schedule)\n        print(\"dG solvent:\", dG_solvent)\n\n        print(\"Core map\", core_idx, \"Difference\", dG_solvent - dG_vacuum)\n\n", "meta": {"hexsha": "ca46f5061e5c48a87ac168e5a70d90b5d47eb596", "size": 6491, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/rhfe_single.py", "max_stars_repo_name": "fehomi/timemachine", "max_stars_repo_head_hexsha": "594b10c03a6688c008eb4d35e612dbd98f5eede4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/rhfe_single.py", "max_issues_repo_name": "fehomi/timemachine", "max_issues_repo_head_hexsha": "594b10c03a6688c008eb4d35e612dbd98f5eede4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/rhfe_single.py", "max_forks_repo_name": "fehomi/timemachine", "max_forks_repo_head_hexsha": "594b10c03a6688c008eb4d35e612dbd98f5eede4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6648351648, "max_line_length": 155, "alphanum_fraction": 0.6871052226, "include": true, "reason": "import numpy", "num_tokens": 1660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.1906666813407014}}
{"text": "#!/usr/bin/env python\r\n#-*- coding:utf-8 -*-\r\n\"\"\"\r\n    Author:             Benjamin Rumeau (intern at CLS in 2014 under supervision\r\n                        of Philippe Gaspard and Anne-Cecile Dragon.\r\n    Module description: Library containing all the geographical classes and fun-\r\n                        ctions.\r\n\"\"\"\r\nimport numpy as np\r\n\r\n\r\n# ||==========================================\r\n# ||                                        || \r\n# ||           Objets géographiques         ||\r\n# ||             et biologiques             ||\r\n# ||                                        ||\r\n# ==========================================||\r\n\r\n\r\nclass NestingPeriod :\r\n    \"\"\"\r\n    class nesting_period used as a structure\r\n    contains the begin, end and peak of the nesting season\r\n    \"\"\"\r\n    def __init__(self,first=0.,last=0.,peak=0.,incubation_time=60):\r\n        self.begin = np.float32(first)\r\n        self.end = np.float32(last)\r\n        self.peak = np.float32(peak)\r\n        self.incubation_time=incubation_time\r\n\r\n    def incubation(self):\r\n        \"\"\"                                                                  \r\n        Corrects nesting period to take into account incubation time.\r\n        Incubation time must be expressed in days.\r\n        \"\"\"\r\n        print(\"\\n=> correcting nesting periods with incubation times\")\r\n        self.begin+=self.incubation_time\r\n        self.end+=self.incubation_time\r\n        self.peak+=self.incubation_time\r\n        \r\n\r\nclass Beach :\r\n    \"\"\"\r\n    class beach is used as a structure\r\n    contains all information needed about the nesting beach\r\n    => launching area\r\n    => nesting season\r\n    => geographic coordinates of the beach\r\n    => name of the beach\r\n    => eventually the reference of those information\r\n    \"\"\"\r\n    def __init__(self,\r\n                 nesting_period=NestingPeriod(),\r\n                 north_pt=[1,1],\r\n                 south_pt=[0,0],\r\n                 orientation=\"east\",\r\n                 d_min=30,\r\n                 d_max=50,\r\n                 ref=\"no reference\",\r\n                 beach_name=\"no name\",\r\n                 file_name=\"no name\"):\r\n        self.nesting_period=nesting_period\r\n        self.north_pt=north_pt\r\n        self.south_pt=south_pt\r\n        if orientation==\"east\":\r\n            self.orientation=1\r\n        elif orientation==\"west\":\r\n            self.orientation=-1\r\n        else:\r\n            print(\"Error: orientation must be east or west\")\r\n        self.d_min=d_min\r\n        self.d_max=d_max\r\n        self.ref=str(ref)\r\n        self.beach_name=str(beach_name)\r\n        self.nesting_period.incubation()\r\n\r\n\r\nclass Geolocation:\r\n    \"\"\" \r\n    class position_4D contains the a 4 uplet x,y,z,t giving the time ans space\r\n    localisation of a particle, as well as an information about the coordinate\r\n    system.\r\n    \"\"\"\r\n    def __init__(self,x=0.,y=0.,t=0.,z=-1.0,coord_sys=\"geo\"):\r\n        self.x=np.float32(x)\r\n        self.y=np.float32(y)\r\n        self.z=np.float32(z)\r\n        self.t=np.float32(t)\r\n        self.coord_sys=coord_sys\r\n    \r\n    def geo_to_grid(self,lon_mat,lat_mat):\r\n        \"\"\"\r\n        converts (lon,lat) geographical coordinate to grid coordinates (conti-\r\n        nuous conversion as coordinates of the closest neighbour are computed\r\n        in Ariane.\r\n        - lon,lat are the geographical coordinate of the point.\r\n        - lon_mat, lat are matrices containing the longitudes (resp. latitudes) of the centers of the cells of the Arakawa C grid.\r\n        NB : this function is only appropriate for regular, square grids.\r\n        \"\"\"\r\n        if self.coord_sys==\"grid\":\r\n            print(\"\\n Warning: already in grid coordinates\")\r\n        else:\r\n            # Read extreme coordinates\r\n            lon_max=np.max(lon_mat)\r\n            lon_min=np.min(lon_mat)\r\n            lat_max=np.max(lat_mat)\r\n            lat_min=np.min(lat_mat)\r\n            # Converts to grid coordinate\r\n            if ((self.x> lon_max) or (self.x< lon_min) or (self.y>lat_max) or (self.y<lat_min)):\r\n                print(\"\\n Longitude or latitude out of range, must be between \", lon_min, \" & \", lon_max, \" for longitude and \", lat_min, \" & \", lat_max, \" for latitude \\n\")\r\n            else:\r\n                h_x=(lon_max-lon_min)/len(lon_mat)\r\n                h_y=(lat_max-lat_min)/len(lat_mat)\r\n                self.x=(self.x-lon_min)/h_x\r\n                self.y=(self.y-lat_min)/h_y\r\n                self.coord_sys=\"grid\"\r\n\r\n    def grid_to_geo(self, lon_mat, lat_mat) : \r\n        if self.coord_sys==\"grid\":\r\n            print(\"\\n Warning: already in geographical coordinates\")\r\n        # Read extreme coordinates\r\n        lon_max=np.max(lon_mat)\r\n        lon_min=np.min(lon_mat)\r\n        lat_max=np.max(lat_mat)\r\n        lat_min=np.min(lat_mat)\r\n        # Converts to grid coordinate\r\n        h_x=(lon_max-lon_min)/len(lon_mat)\r\n        h_y=(lat_max-lat_min)/len(lat_mat)\r\n        self.x=h_x * self.x + lon_min\r\n        self.y=h_y * self.y + lat_min\r\n        self.coord_sys=\"grid\"\r\n\r\n\r\n    def write_line(self,f):\r\n        \"\"\"\r\n        write as a proper line readable for Ariane the position in a given file\r\n        \"\"\"\r\n        line=' '+\"%.3f\" % self.x+' '+\\\r\n             \"%.3f\" % self.y+'    '+\\\r\n             \"%.1f\" % self.z+'  '+\\\r\n             \"%.2f\" % self.t+'     '+\\\r\n             '1.0\\n'\r\n\r\n        line=line.replace(',','.')\r\n        f.write(line)\r\n\r\n\r\n\r\n# ||==========================================\r\n# ||                                        || \r\n# ||       Transformations géométriques     ||\r\n# ||                                        ||\r\n# ==========================================||\r\n\r\n\r\ndef rotation(x,y,Ox,Oy,theta):\r\n    \"\"\"\r\n        Computes coordinates X,Y in referential R' from a poin (x,y) in a referential R\r\n        where R' is obtained by a rotation of R of angle theta and center O(Ox,Oy)\r\n    \"\"\"      \r\n    X=Ox+(x-Ox)*np.cos(theta)+(y-Oy)*np.sin(theta)\r\n    Y=Oy-(x-Ox)*np.sin(theta)+(y-Oy)*np.cos(theta)\r\n    return(X,Y)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef geo_to_grid(lon,lat,lon_mat,lat_mat):\r\n    \"\"\"\r\n    converts (lon,lat) geographical coordinate to grid coordinates (conti-\r\n    nuous conversion as coordinates of the closest neighbour are computed\r\n    in Ariane.\r\n    - lon,lat are the geographical coordinate of the point.\r\n    - lon_mat, lat are matrices containing the longitudes (resp. latitudes) of the centers of the cells of the Arakawa C grid.\r\n    NB : this function is only appropriate for regular, square grids.\r\n    \"\"\"\r\n    # Read extreme coordinates\r\n    lon_max=np.max(lon_mat)\r\n    lon_min=np.min(lon_mat)\r\n    lat_max=np.max(lat_mat)\r\n    lat_min=np.min(lat_mat)\r\n    # Converts to grid coordinate\r\n    if ((lon> lon_max) or (lon< lon_min) or (lat>lat_max) or (lat<lat_min)):\r\n        print(\"\\n Longitude or latitude out of range, must be between \", lon_min, \" & \", lon_max, \" for longitude and \", lat_min, \" & \", lat_max, \" for latitude \\n\")\r\n    else:\r\n        h_x=(lon_max-lon_min)/len(lon_mat)\r\n        h_y=(lat_max-lat_min)/len(lat_mat)\r\n        i1 = int((lon-lon_min)/h_x)\r\n        i2 = i1 + 1\r\n        I = [i1,i2]\r\n        i0 = np.argmin([abs(lon - lon_mat[i1]), abs(lon - lon_mat[i2])])\r\n        i = I[i0]\r\n        j1 = int((lat-lat_min)/h_y)\r\n        j2 = j1 + 1\r\n        J = [j1,j2]\r\n        j0 = np.argmin([abs(lat - lat_mat[j1]), abs(lat - lat_mat[j2])])\r\n        j = J[j0]\r\n    return i,j\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "05c6f0bdd8e3beb57d60eaeda4476a95a03a5291", "size": 7449, "ext": "py", "lang": "Python", "max_stars_repo_path": "LIB/biogeolib.py", "max_stars_repo_name": "pierrick-giffard/STAMM-Sea_Turtle_Active_Movement_Model", "max_stars_repo_head_hexsha": "dcd94c8968cd8e7a4daa56ae566707ace19885fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-14T09:27:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T09:27:46.000Z", "max_issues_repo_path": "LIB/biogeolib.py", "max_issues_repo_name": "pierrick-giffard/STAMM-Sea_Turtle_Active_Movement_Model", "max_issues_repo_head_hexsha": "dcd94c8968cd8e7a4daa56ae566707ace19885fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LIB/biogeolib.py", "max_forks_repo_name": "pierrick-giffard/STAMM-Sea_Turtle_Active_Movement_Model", "max_forks_repo_head_hexsha": "dcd94c8968cd8e7a4daa56ae566707ace19885fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-29T13:50:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-29T13:50:46.000Z", "avg_line_length": 30.4040816327, "max_line_length": 174, "alphanum_fraction": 0.5259766412, "include": true, "reason": "import numpy", "num_tokens": 1730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.3486451353339457, "lm_q1q2_score": 0.1906175969909071}}
{"text": "#! /usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\n    .. _schedule_targets:\n\n    *******\n    TARGETS\n    *******\n\"\"\"\n\n\n__author__ = 'Alan Loh'\n__copyright__ = 'Copyright 2021, nenupy'\n__credits__ = ['Alan Loh']\n__maintainer__ = 'Alan'\n__email__ = 'alan.loh@obspm.fr'\n__status__ = 'Production'\n__all__ = [\n    '_Target',\n    'ESTarget',\n    'SSTarget'\n]\n\n\nimport astropy.units as u\nfrom astropy.time import Time\nfrom astropy.coordinates import (\n    Angle,\n    SkyCoord,\n    FK5,\n    EarthLocation,\n    solar_system_ephemeris,\n    get_body\n)\nimport numpy as np\n\nimport logging\nlog = logging.getLogger(__name__)\n\n\n# ============================================================= #\n# ============================================================= #\nNENUFAR_LOC = EarthLocation(\n    lat=47.376511 * u.deg,\n    lon=2.192400 * u.deg,\n    height=150 * u.m\n)\n\n\nSS_SOURCES = [\n    'sun',\n    'moon',\n    'mercury',\n    'venus',\n    'mars',\n    'jupiter',\n    'saturn',\n    'uranus',\n    'neptune'\n]\n# ============================================================= #\n# ============================================================= #\n\n\n# ============================================================= #\n# -------------------------- _Target -------------------------- #\n# ============================================================= #\nclass _Target(object):\n    \"\"\"\n    \"\"\"\n\n    def __init__(self, target):\n        self._target = target\n        self._lst = None\n        self._fk5 = None\n        self._hourAngle = None\n        self._elevation = None\n        self._azimuth = None\n\n\n    # --------------------------------------------------------- #\n    # --------------------- Getter/Setter --------------------- #\n    @property\n    def target(self):\n        \"\"\"\n        \"\"\"\n        return self._target\n\n\n    @property\n    def hourAngle(self):\n        \"\"\" Gets the Local Hour Angle.\n        \"\"\"\n        if self._hourAngle is None:\n            self._attrWarning('hourAngle')\n        return self._hourAngle\n\n\n    @property\n    def elevation(self):\n        \"\"\" Gets the elevation.\n        \"\"\"\n        if self._elevation is None:\n            self._attrWarning('elevation')\n        return self._elevation\n\n\n    @property\n    def azimuth(self):\n        \"\"\" Gets the azimuth.\n        \"\"\"\n        if self._azimuth is None:\n            self._attrWarning('azimuth')\n        return self._azimuth\n\n\n    # --------------------------------------------------------- #\n    # ------------------------ Methods ------------------------ #\n    def computePosition(self, time):\n        \"\"\"\n        \"\"\"\n        if not isinstance(time, Time):\n            raise TypeError(\n                f'<time> should be a {Time} object.'\n            )\n        if time.isscalar:\n            time = Time([time.isot, time.isot])\n\n        self._localSiderealTime(time)\n        self._positionAtEquinox(time)\n        self._computeHourAngle()\n        self._computeHorizontalCoords()\n\n\n    # --------------------------------------------------------- #\n    # ----------------------- Internal ------------------------ #\n    def _localSiderealTime(self, time):\n        \"\"\"\n        \"\"\"\n        # Number of days since 2000 January 1, 12h UT\n        nDays = time.jd - 2451545.\n        # Greenwich mean sidereal time\n        gmst = 18.697374558 + 24.06570982441908 * nDays\n        gmst %= 24.\n        # Local Sidereal Time\n        lst = gmst + NENUFAR_LOC.lon.hour\n        if np.isscalar(lst):\n            if lst < 0:\n                lst += 24\n        else:\n            lst[lst < 0] += 24.   \n        self._lst = Angle(lst, 'hour')\n\n\n    def _positionAtEquinox(self, time):\n        \"\"\"\n        \"\"\"\n        fk5 = self.target.transform_to(\n            FK5(equinox=time)\n        )\n        self._fk5 = fk5\n\n\n    def _computeHourAngle(self):\n        \"\"\"\n        \"\"\"\n        twoPi = Angle(360.000000, unit='deg')\n        ha = self._lst - self._fk5.ra\n        if ha.isscalar:\n            if ha.deg < 0:\n                ha += twoPi\n            elif ha.deg > 360:\n                ha -= twoPi\n        else:\n            ha[ha.deg < 0] += twoPi\n            ha[ha.deg > 360] -= twoPi\n        self._hourAngle = ha\n\n\n    def _computeHorizontalCoords(self):\n        \"\"\"\n        \"\"\"\n        twoPi = Angle(360.000000, unit='deg')\n\n        decRad = self._fk5.dec.rad\n        sinDec = np.sin(decRad)\n        haRad = self._hourAngle.rad\n        latRad = NENUFAR_LOC.lat.rad\n        sinLat = np.sin(latRad)\n        cosLat = np.cos(latRad)\n        sinEl = sinDec * sinLat +\\\n            np.cos(decRad) * cosLat * np.cos(haRad)\n        self._elevation = Angle(\n            np.arcsin(sinEl),\n            unit='rad'\n        ).to('deg')\n\n        elRad = self._elevation.rad\n        cosAz = (sinDec - np.sin(elRad) * sinLat)/\\\n            (np.cos(elRad) * cosLat)\n        azRad = Angle(np.arccos(cosAz), unit='rad')\n\n        if azRad.isscalar:\n            if np.sin(self._hourAngle.rad) > 0:\n                azRad *= -1\n                azRad += twoPi\n        else:\n            posMask = np.sin(self._hourAngle.rad) > 0\n            azRad[posMask] *= -1\n            azRad[posMask] += twoPi\n\n        self._azimuth = azRad.to('deg')\n\n\n    # --------------------------------------------------------- #\n    # ----------------------- Internal ------------------------ #\n    @staticmethod\n    def _attrWarning(self, attr):\n        \"\"\"\n        \"\"\"\n        log.warning(\n            'Target position must be computed using '\n            '<.computePosition(time)> method, prior to asking'\n            f' for the <{attr}> attribute.'\n        )\n# ============================================================= #\n# ============================================================= #\n\n\n# ============================================================= #\n# ------------------------- SSTarget -------------------------- #\n# ============================================================= #\nclass SSTarget(_Target):\n    \"\"\" Solar System target\n    \"\"\"\n\n    def __init__(self, target):\n        super().__init__(target=target)\n\n\n    # --------------------------------------------------------- #\n    # --------------------- Getter/Setter --------------------- #\n    @property\n    def isCircumpolar(self):\n        \"\"\"\n        \"\"\"\n        ninetyDeg = Angle(90, 'deg')\n        decAndLat = self._fk5.dec + NENUFAR_LOC.lat\n        return any(decAndLat > ninetyDeg) # not sure about that\n\n\n    # --------------------------------------------------------- #\n    # ------------------------ Methods ------------------------ #\n    @classmethod\n    def fromName(cls, sourceName):\n        \"\"\"\n        \"\"\"\n        if not isinstance(sourceName, str):\n            raise TypeError(\n                f\"<sourceName> '{sourceName}' must be a {str}.\"\n            )\n        sourceName = sourceName.lower()\n        if sourceName not in SS_SOURCES:\n            raise ValueError(\n                f\"Solar System target '{sourceName}'' not in \"\n                f\"{SS_SOURCES}.\"\n            )\n\n        log.debug(\n            f\"Solar System target '{sourceName}' loaded.\"\n        )\n        return cls(\n            target=sourceName\n        )\n\n\n    # --------------------------------------------------------- #\n    # ----------------------- Internal ------------------------ #\n    def _positionAtEquinox(self, time):\n        \"\"\" Over define this _Target method\n        \"\"\"\n        with solar_system_ephemeris.set('builtin'):\n            source = get_body(\n                self.target,\n                time,\n                NENUFAR_LOC\n            ) # GCRS\n        ssSource = SkyCoord(source.ra, source.dec)\n\n        fk5 = ssSource.transform_to(\n            FK5(equinox=time)\n        )\n        self._fk5 = fk5\n# ============================================================= #\n# ============================================================= #\n\n\n# ============================================================= #\n# ------------------------- ESTarget -------------------------- #\n# ============================================================= #\nclass ESTarget(_Target):\n    \"\"\" ExtraSolar System target\n    \"\"\"\n\n    def __init__(self, target):\n        super().__init__(target=target)\n\n\n    # --------------------------------------------------------- #\n    # --------------------- Getter/Setter --------------------- #\n    @property\n    def isCircumpolar(self):\n        \"\"\"\n        \"\"\"\n        return self.target.dec + NENUFAR_LOC.lat > Angle(90, 'deg')\n\n\n    # --------------------------------------------------------- #\n    # ------------------------ Methods ------------------------ #\n    @classmethod\n    def fromName(cls, sourceName):\n        \"\"\"\n        \"\"\"\n        if not isinstance(sourceName, str):\n            raise TypeError(\n                f\"<sourceName> '{sourceName}'' must be a {str}.\"\n            )\n        esSource = SkyCoord.from_name(sourceName)\n        log.debug(\n            f\"ExtraSolar target '{sourceName}' loaded.\"\n        )\n        return cls(\n            target=esSource\n        )\n\n\n    @classmethod\n    def fromCoordinates(cls, coordinates):\n        \"\"\"\n        \"\"\"\n        if isinstance(coordinates, str):\n            esSource = SkyCoord(coordinates, unit=(u.hourangle, u.deg))\n        else:\n            esSource = SkyCoord(*coordinates, unit=u.deg)\n        return cls(\n            target=esSource\n        )\n# ============================================================= #\n# ============================================================= #\n\n", "meta": {"hexsha": "4f68cef903df92a025d0c88acdd844954418bfbe", "size": 9406, "ext": "py", "lang": "Python", "max_stars_repo_path": "nenupy/schedule/targets.py", "max_stars_repo_name": "coutouly/nenupy", "max_stars_repo_head_hexsha": "76cf9f6a6a93e9eed16f8450e3cfe385440a212e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-10-02T16:32:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:55:36.000Z", "max_issues_repo_path": "nenupy/schedule/targets.py", "max_issues_repo_name": "coutouly/nenupy", "max_issues_repo_head_hexsha": "76cf9f6a6a93e9eed16f8450e3cfe385440a212e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 54, "max_issues_repo_issues_event_min_datetime": "2018-10-16T14:48:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T11:02:59.000Z", "max_forks_repo_path": "nenupy/schedule/targets.py", "max_forks_repo_name": "coutouly/nenupy", "max_forks_repo_head_hexsha": "76cf9f6a6a93e9eed16f8450e3cfe385440a212e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-12T14:29:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-24T13:11:16.000Z", "avg_line_length": 26.6458923513, "max_line_length": 71, "alphanum_fraction": 0.3943227727, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 1975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.19061758959041242}}
{"text": "# - * - coding: utf-8 - * -\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches\nimport matplotlib.gridspec as gridspec\nimport scipy.signal\nimport scipy.stats\n\n\ndef ecg_fixpeaks(rpeaks, sampling_rate=1000, iterative=True, show=False):\n    \"\"\"Correct R-peaks location based on their interval (RRi).\n\n    Identify erroneous inter-beat-intervals. Lipponen & Tarvainen (2019).\n\n    Parameters\n    ----------\n    rpeaks : dict\n        The samples at which the R-peak occur. Dict returned by\n        `ecg_findpeaks()`.\n    sampling_rate : int\n        The sampling frequency of the signal that contains the peaks (in Hz,\n        i.e., samples/second).\n    iterative : bool\n        Whether or not to apply the artifact correction repeatedly (results\n        in superior artifact correction).\n    show : bool\n        Whether or not to visualize artifacts and artifact thresholds.\n\n    Returns\n    -------\n    artifacts : dict\n        A dictionary containing the indices of artifacts, accessible with the\n        keys \"ectopic\", \"missed\", \"extra\", and \"longshort\".\n\n    See Also\n    --------\n    ecg_clean, ecg_findpeaks, ecg_peaks, ecg_rate, ecg_process, ecg_plot\n\n    Examples\n    --------\n    >>> import neurokit2 as nk\n    >>> import matplotlib.pyplot as plt\n\n    >>> ecg = nk.ecg_simulate(duration=240, noise=0.1, heart_rate=70,\n    >>>                       random_state=41)\n    >>> rpeaks_uncorrected = nk.ecg_findpeaks(ecg)\n    >>> artifacts, rpeaks_corrected = nk.ecg_fixpeaks(rpeaks_uncorrected,\n    >>>                                               iterative=True,\n    >>>                                               show=True)\n    >>> rate_corrected = nk.ecg_rate(rpeaks_uncorrected,\n    >>>                              desired_length=len(ecg))\n    >>> rate_uncorrected = nk.ecg_rate(rpeaks, desired_length=len(ecg_signal))\n    >>>\n    >>> fig, ax = plt.subplots()\n    >>> ax.plot(rate_uncorrected, label=\"heart rate without artifact correction\")\n    >>> ax.plot(rate_corrected, label=\"heart rate with artifact correction\")\n    >>> ax.legend(loc=\"upper right\")\n\n    References\n    ----------\n    - Lipponen, J. A., & Tarvainen, M. P. (2019). A robust algorithm for heart\n    rate variability time series artefact correction using novel beat\n    classification. Journal of medical engineering & technology, 43(3),\n    173-181. 10.1080/03091902.2019.1640306\n\n    \"\"\"\n    # Format input.\n    rpeaks = rpeaks[\"ECG_R_Peaks\"]\n    artifacts, subspaces = _find_artifacts_lipponen2019(rpeaks, sampling_rate)\n    rpeaks_corrected = _fix_artifacts_lipponen2019(rpeaks, artifacts,\n                                                   sampling_rate)\n\n    if iterative:\n        # Iteratively apply the artifact correction until the number of\n        # artifact reaches an equilibrium (i.e., the number of artifacts\n        # does not change anymore from one iteration to the next)\n        n_artifacts_previous = np.inf\n        n_artifacts_current = sum([len(i) for i in artifacts.values()])\n\n        previous_diff = 0\n\n        while n_artifacts_current - n_artifacts_previous != previous_diff:\n\n            previous_diff = n_artifacts_previous - n_artifacts_current\n\n            artifacts, subspaces = _find_artifacts_lipponen2019(rpeaks_corrected,\n                                                                sampling_rate)\n            rpeaks_corrected = _fix_artifacts_lipponen2019(rpeaks_corrected,\n                                                           artifacts,\n                                                           sampling_rate)\n\n            n_artifacts_previous = n_artifacts_current\n            n_artifacts_current = sum([len(i) for i in artifacts.values()])\n\n    if show:\n        _plot_artifacts_lipponen2019(artifacts, subspaces)\n\n    return artifacts, {\"ECG_R_Peaks\": rpeaks_corrected}\n\n\n# =============================================================================\n# Lipponen & Tarvainen (2019).\n# =============================================================================\ndef _find_artifacts_lipponen2019(rpeaks, sampling_rate=1000):\n\n    # Set fixed parameters.\n    c1 = 0.13\n    c2 = 0.17\n    alpha = 5.2\n    window_half = 45\n    medfilt_order = 11\n\n    # Compute period series (make sure it has same numer of elements as peaks);\n    # peaks are in samples, convert to seconds.\n    rr = np.ediff1d(rpeaks, to_begin=0) / sampling_rate\n    # For subsequent analysis it is important that the first element has\n    # a value in a realistic range (e.g., for median filtering).\n    rr[0] = np.mean(rr[1:])\n\n    # Compute differences of consecutive periods.\n    drrs = np.ediff1d(rr, to_begin=0)\n    drrs[0] = np.mean(drrs[1:])\n    # Normalize by threshold.\n    drrs, _ = _threshold_normalization(drrs, alpha, window_half)\n\n    # Pad drrs with one element.\n    padding = 2\n    drrs_pad = np.pad(drrs, padding, \"reflect\")\n    # Cast drrs to two-dimesnional subspace s1.\n    s12 = np.zeros(drrs.size)\n    for d in np.arange(padding, padding + drrs.size):\n\n        if drrs_pad[d] > 0:\n            s12[d - padding] = np.max([drrs_pad[d - 1], drrs_pad[d + 1]])\n        elif drrs_pad[d] < 0:\n            s12[d - padding] = np.min([drrs_pad[d - 1], drrs_pad[d + 1]])\n\n    # Cast drrs to two-dimensional subspace s2 (looping over d a second\n    # consecutive time is choice to be explicit rather than efficient).\n    s22 = np.zeros(drrs.size)\n    for d in np.arange(padding, padding + drrs.size):\n\n        if drrs_pad[d] > 0:\n            s22[d - padding] = np.max([drrs_pad[d + 1], drrs_pad[d + 2]])\n        elif drrs_pad[d] < 0:\n            s22[d - padding] = np.min([drrs_pad[d + 1], drrs_pad[d + 2]])\n\n    # Compute deviation of RRs from median RRs.\n    padding = medfilt_order // 2    # pad RR series before filtering\n    rr_pad = np.pad(rr, padding, \"reflect\")\n    medrr = scipy.signal.medfilt(rr_pad, medfilt_order)\n    medrr = medrr[padding:padding + rr.size]    # remove padding\n    mrrs = rr - medrr\n    mrrs[mrrs < 0] = mrrs[mrrs < 0] * 2\n    mrrs, th2 = _threshold_normalization(mrrs, alpha, window_half)    # normalize by threshold\n\n    # Artifact identification\n    #########################\n    # Keep track of indices that need to be interpolated, removed, or added.\n    extra_idcs = []\n    missed_idcs = []\n    ectopic_idcs = []\n    longshort_idcs = []\n\n    for i in range(rpeaks.size - 2):\n\n        # Check for ectopic peaks.\n        if np.abs(drrs[i]) <= 1:\n            continue\n\n        # Based on Figure 2a.\n        eq1 = np.logical_and(drrs[i] > 1, s12[i] < (-c1 * drrs[i] - c2))\n        eq2 = np.logical_and(drrs[i] < -1, s12[i] > (-c1 * drrs[i] + c2))\n\n        if np.any([eq1, eq2]):\n            # If any of the two equations is true.\n            ectopic_idcs.append(i)\n            continue\n\n        # If none of the two equations is true.\n        # Based on Figure 2b.\n        if ~np.any([np.abs(drrs[i]) > 1, np.abs(mrrs[i]) > 3]):\n            continue\n\n        # Long beat.\n        eq3 = np.logical_and(drrs[i] > 1, s22[i] < -1)\n        eq4 = np.abs(mrrs[i]) > 3\n        # Short beat.\n        eq5 = np.logical_and(drrs[i] < -1, s22[i] > 1)\n\n        if ~np.any([eq3, eq4, eq5]):\n            # If none of the three equations is true: normal beat.\n            continue\n\n        # If any of the three equations is true: check for missing or extra\n        # peaks.\n\n        # Missing.\n        eq6 = np.abs(rr[i] / 2 - medrr[i]) < th2[i]\n        # Extra.\n        eq7 = np.abs(rr[i] + rr[i + 1] - medrr[i]) < th2[i]\n\n        # Check if short or extra.\n        if eq5:\n            if eq7:\n                extra_idcs.append(i)\n            else:\n                longshort_idcs.append(i)\n                if np.abs(drrs[i + 1]) < np.abs(drrs[i + 2]):\n                    longshort_idcs.append(i + 1)\n        # Check if long or missing.\n        if np.any([eq3, eq4]):\n            if eq6:\n                missed_idcs.append(i)\n            else:\n                longshort_idcs.append(i)\n                if np.abs(drrs[i + 1]) < np.abs(drrs[i + 2]):\n                    longshort_idcs.append(i + 1)\n\n    # Prepare output\n    artifacts = {\"ectopic\": ectopic_idcs, \"missed\": missed_idcs,\n                 \"extra\": extra_idcs, \"longshort\": longshort_idcs}\n\n    subspaces = {\"rr\": rr, \"drrs\": drrs, \"mrrs\": mrrs, \"s12\": s12, \"s22\": s22,\n                 \"c1\": c1, \"c2\": c2}\n\n    return artifacts, subspaces\n\n\ndef _fix_artifacts_lipponen2019(rpeaks, artifacts, sampling_rate):\n\n    extra_idcs = artifacts[\"extra\"]\n    missed_idcs = artifacts[\"missed\"]\n    ectopic_idcs = artifacts[\"ectopic\"]\n    longshort_idcs = artifacts[\"longshort\"]\n\n    # Delete extra peaks.\n    if extra_idcs:\n        rpeaks = np.delete(rpeaks, extra_idcs)\n        # Update remaining indices.\n        missed_idcs = _update_indices(extra_idcs, missed_idcs, -1)\n        ectopic_idcs = _update_indices(extra_idcs, ectopic_idcs, -1)\n        longshort_idcs = _update_indices(extra_idcs, longshort_idcs, -1)\n\n    # Add missing peaks.\n    if missed_idcs:\n        # Calculate the position(s) of new beat(s). Make sure to not generate\n        # negative indices. prev_peaks and next_peaks must have the same\n        # number of elements.\n        missed_idcs = np.array(missed_idcs)\n        valid_idcs = np.logical_and(missed_idcs > 1, missed_idcs < len(rpeaks))\n        missed_idcs = missed_idcs[valid_idcs]\n        prev_rpeaks = rpeaks[[i - 1 for i in missed_idcs]]\n        next_rpeaks = rpeaks[missed_idcs]\n        added_rpeaks = prev_rpeaks + (next_rpeaks - prev_rpeaks) / 2\n        # Add the new peaks before the missed indices (see numpy docs).\n        rpeaks = np.insert(rpeaks, missed_idcs, added_rpeaks)\n        # Update remaining indices.\n        ectopic_idcs = _update_indices(missed_idcs, ectopic_idcs, 1)\n        longshort_idcs = _update_indices(missed_idcs, longshort_idcs, 1)\n\n    # Interpolate ectopic as well as long or short peaks (important to do\n    # this after peaks are deleted and/or added).\n    interp_idcs = np.concatenate((ectopic_idcs, longshort_idcs)).astype(int)\n    if interp_idcs.size > 0:\n        interp_idcs.sort(kind='mergesort')\n        # Make sure to not generate negative indices, or indices that exceed\n        # the total number of peaks.\n        # Make sure to not generate negative indices, or indices that exceed\n        # the total number of peaks. prev_peaks and next_peaks must have the\n        # same number of elements.\n        valid_idcs = np.logical_and(interp_idcs > 1, interp_idcs < len(rpeaks))\n        interp_idcs = interp_idcs[valid_idcs]\n        prev_rpeaks = rpeaks[[i - 1 for i in interp_idcs]]\n        next_rpeaks = rpeaks[[i + 1 for i in interp_idcs]]\n        rpeaks_interp = prev_rpeaks + (next_rpeaks - prev_rpeaks) / 2\n        # Shift the R-peaks from the old to the new position.\n        rpeaks = np.delete(rpeaks, interp_idcs)\n        rpeaks = np.concatenate((rpeaks, rpeaks_interp)).astype(int)\n        rpeaks.sort(kind=\"mergesort\")\n        rpeaks = np.unique(rpeaks)\n\n    return rpeaks\n\n\ndef _plot_artifacts_lipponen2019(artifacts, info):\n    \"\"\"\n    \"\"\"\n    # Extract parameters\n    longshort_idcs = artifacts[\"longshort\"]\n    ectopic_idcs = artifacts[\"ectopic\"]\n    extra_idcs = artifacts[\"extra\"]\n    missed_idcs = artifacts[\"missed\"]\n\n    rr = info[\"rr\"]\n    drrs = info[\"drrs\"]\n    mrrs = info[\"mrrs\"]\n    s12 = info[\"s12\"]\n    s22 = info[\"s22\"]\n    c1 = info[\"c1\"]\n    c2 = info[\"c2\"]\n\n    # Visualize artifact type indices.\n\n    # Set grids\n    gs = matplotlib.gridspec.GridSpec(ncols=4, nrows=3,\n                                      width_ratios=[1, 2, 2, 2])\n    fig = plt.figure(constrained_layout=False)\n    ax0 = fig.add_subplot(gs[0, :-2])\n    ax1 = fig.add_subplot(gs[1, :-2])\n    ax2 = fig.add_subplot(gs[2, :-2])\n    ax3 = fig.add_subplot(gs[:, -1])\n    ax4 = fig.add_subplot(gs[:, -2])\n\n    ax0.set_title(\"Artifact types\", fontweight=\"bold\")\n    ax0.plot(rr, label=\"heart period\")\n    ax0.scatter(longshort_idcs, rr[longshort_idcs], marker='x', c='m',\n                s=100, zorder=3, label=\"long/short\")\n    ax0.scatter(ectopic_idcs, rr[ectopic_idcs], marker='x', c='g', s=100,\n                zorder=3, label=\"ectopic\")\n    ax0.scatter(extra_idcs, rr[extra_idcs], marker='x', c='y', s=100,\n                zorder=3, label=\"false positive\")\n    ax0.scatter(missed_idcs, rr[missed_idcs], marker='x', c='r', s=100,\n                zorder=3, label=\"false negative\")\n    ax0.legend(loc=\"upper right\")\n\n    # Visualize first threshold.\n    ax1.set_title(\"Consecutive-difference criterion\", fontweight=\"bold\")\n    ax1.plot(np.abs(drrs), label=\"difference consecutive heart periods\")\n    ax1.axhline(1, c='r', label=\"artifact threshold\")\n    ax1.legend(loc=\"upper right\")\n\n    # Visualize second threshold.\n    ax2.set_title(\"Difference-from-median criterion\", fontweight=\"bold\")\n    ax2.plot(np.abs(mrrs), label=\"difference from median over 11 periods\")\n    ax2.axhline(3, c=\"r\", label=\"artifact threshold\")\n    ax2.legend(loc=\"upper right\")\n\n    # Visualize subspaces.\n    ax4.set_title(\"Subspace 1\", fontweight=\"bold\")\n    ax4.set_xlabel(\"S11\")\n    ax4.set_ylabel(\"S12\")\n    ax4.scatter(drrs, s12, marker=\"x\", label=\"heart periods\")\n    verts0 = [(min(drrs), max(s12)),\n              (min(drrs), -c1 * min(drrs) + c2),\n              (-1, -c1 * -1 + c2),\n              (-1, max(s12))]\n    poly0 = matplotlib.patches.Polygon(verts0, alpha=0.3, facecolor=\"r\",\n                                       edgecolor=None, label=\"ectopic periods\")\n    ax4.add_patch(poly0)\n    verts1 = [(1, -c1 * 1 - c2),\n              (1, min(s12)),\n              (max(drrs), min(s12)),\n              (max(drrs), -c1 * max(drrs) - c2)]\n    poly1 = matplotlib.patches.Polygon(verts1, alpha=0.3, facecolor=\"r\",\n                                       edgecolor=None)\n    ax4.add_patch(poly1)\n    ax4.legend(loc=\"upper right\")\n\n    ax3.set_title(\"Subspace 2\", fontweight=\"bold\")\n    ax3.set_xlabel(\"S21\")\n    ax3.set_ylabel(\"S22\")\n    ax3.scatter(drrs, s22, marker=\"x\", label=\"heart periods\")\n    verts2 = [(min(drrs), max(s22)),\n              (min(drrs), 1),\n              (-1, 1),\n              (-1, max(s22))]\n    poly2 = matplotlib.patches.Polygon(verts2, alpha=0.3, facecolor=\"r\",\n                                       edgecolor=None, label=\"short periods\")\n    ax3.add_patch(poly2)\n    verts3 = [(1, -1),\n              (1, min(s22)),\n              (max(drrs), min(s22)),\n              (max(drrs), -1)]\n    poly3 = matplotlib.patches.Polygon(verts3, alpha=0.3, facecolor=\"y\",\n                                       edgecolor=None, label=\"long periods\")\n    ax3.add_patch(poly3)\n    ax3.legend(loc=\"upper right\")\n\n\ndef _threshold_normalization(data, alpha, window_half):\n    wh = window_half\n    # compute threshold\n    th = np.zeros(data.size)\n    if data.size <= 2 * wh:\n        th[:] = alpha * (scipy.stats.iqr(np.abs(data)) / 2)\n        # normalize data by threshold\n        data_th = np.divide(data, th)\n    else:\n        data_pad = np.pad(data, wh, \"reflect\")\n        for i in np.arange(wh, wh + data.size):\n            th[i - wh] = alpha * (scipy.stats.iqr(np.abs(data_pad[i - wh:i + wh])) / 2)\n        # normalize data by threshold (remove padding)\n        data_th = np.divide(data_pad[wh:wh + data.size], th)\n    return data_th, th\n\n\ndef _update_indices(source_idcs, update_idcs, update):\n    \"\"\"\n    for every element s in source_idcs, change every element u in update_idcs\n    according to update, if u is larger than s\n    \"\"\"\n    update_idcs_buffer = update_idcs\n    for s in source_idcs:\n        # find the indices (of indices) that need to be updated\n        updates = [i for i, j in enumerate(update_idcs) if j > s]\n        for u in updates:\n            update_idcs_buffer[u] += update\n    return update_idcs_buffer\n", "meta": {"hexsha": "604280cb5b0369e2fb3a217a613eb90d966cbd58", "size": 15688, "ext": "py", "lang": "Python", "max_stars_repo_path": "neurokit2/ecg/ecg_fixpeaks.py", "max_stars_repo_name": "purpl3F0x/NeuroKit", "max_stars_repo_head_hexsha": "bd41f2bf7692bc8ed4c85608daa535293a33a1d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "neurokit2/ecg/ecg_fixpeaks.py", "max_issues_repo_name": "purpl3F0x/NeuroKit", "max_issues_repo_head_hexsha": "bd41f2bf7692bc8ed4c85608daa535293a33a1d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "neurokit2/ecg/ecg_fixpeaks.py", "max_forks_repo_name": "purpl3F0x/NeuroKit", "max_forks_repo_head_hexsha": "bd41f2bf7692bc8ed4c85608daa535293a33a1d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2634146341, "max_line_length": 94, "alphanum_fraction": 0.5936384498, "include": true, "reason": "import numpy,import scipy", "num_tokens": 4343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.34864512856608554, "lm_q1q2_score": 0.19061758814083732}}
{"text": "# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/06_bilateral_filtering.ipynb (unless otherwise specified).\n\n__all__ = ['sparse_bilateral_filtering', 'vis_depth_discontinuity', 'bilateral_filter', 'rolling_window']\n\n# Cell\nimport numpy as np\nfrom functools import reduce\n\n# Cell\ndef sparse_bilateral_filtering(\n    depth, image, config, HR=False, mask=None, gsHR=True, edge_id=None, num_iter=None, num_gs_iter=None, spdb=False\n):\n    \"\"\"\n    config:\n    - filter_size\n    \"\"\"\n    import time\n\n    save_images = []\n    save_depths = []\n    save_discontinuities = []\n    vis_depth = depth.copy()\n    backup_vis_depth = vis_depth.copy()\n\n    depth_max = vis_depth.max()\n    depth_min = vis_depth.min()\n    vis_image = image.copy()\n    for i in range(num_iter):\n        if isinstance(config[\"filter_size\"], list):\n            window_size = config[\"filter_size\"][i]\n        else:\n            window_size = config[\"filter_size\"]\n        vis_image = image.copy()\n        save_images.append(vis_image)\n        save_depths.append(vis_depth)\n        u_over, b_over, l_over, r_over = vis_depth_discontinuity(vis_depth, config, mask=mask)\n        vis_image[u_over > 0] = np.array([0, 0, 0])\n        vis_image[b_over > 0] = np.array([0, 0, 0])\n        vis_image[l_over > 0] = np.array([0, 0, 0])\n        vis_image[r_over > 0] = np.array([0, 0, 0])\n\n        discontinuity_map = (u_over + b_over + l_over + r_over).clip(0.0, 1.0)\n        discontinuity_map[depth == 0] = 1\n        save_discontinuities.append(discontinuity_map)\n        if mask is not None:\n            discontinuity_map[mask == 0] = 0\n        vis_depth = bilateral_filter(\n            vis_depth, config, discontinuity_map=discontinuity_map, HR=HR, mask=mask, window_size=window_size\n        )\n\n    return save_images, save_depths\n\n# Cell\ndef vis_depth_discontinuity(depth, config, vis_diff=False, label=False, mask=None):\n    \"\"\"\n    config:\n    -\n    \"\"\"\n    if label == False:\n        disp = 1./depth\n        u_diff = (disp[1:, :] - disp[:-1, :])[:-1, 1:-1]\n        b_diff = (disp[:-1, :] - disp[1:, :])[1:, 1:-1]\n        l_diff = (disp[:, 1:] - disp[:, :-1])[1:-1, :-1]\n        r_diff = (disp[:, :-1] - disp[:, 1:])[1:-1, 1:]\n        if mask is not None:\n            u_mask = (mask[1:, :] * mask[:-1, :])[:-1, 1:-1]\n            b_mask = (mask[:-1, :] * mask[1:, :])[1:, 1:-1]\n            l_mask = (mask[:, 1:] * mask[:, :-1])[1:-1, :-1]\n            r_mask = (mask[:, :-1] * mask[:, 1:])[1:-1, 1:]\n            u_diff = u_diff * u_mask\n            b_diff = b_diff * b_mask\n            l_diff = l_diff * l_mask\n            r_diff = r_diff * r_mask\n        u_over = (np.abs(u_diff) > config['depth_threshold']).astype(np.float32)\n        b_over = (np.abs(b_diff) > config['depth_threshold']).astype(np.float32)\n        l_over = (np.abs(l_diff) > config['depth_threshold']).astype(np.float32)\n        r_over = (np.abs(r_diff) > config['depth_threshold']).astype(np.float32)\n    else:\n        disp = depth\n        u_diff = (disp[1:, :] * disp[:-1, :])[:-1, 1:-1]\n        b_diff = (disp[:-1, :] * disp[1:, :])[1:, 1:-1]\n        l_diff = (disp[:, 1:] * disp[:, :-1])[1:-1, :-1]\n        r_diff = (disp[:, :-1] * disp[:, 1:])[1:-1, 1:]\n        if mask is not None:\n            u_mask = (mask[1:, :] * mask[:-1, :])[:-1, 1:-1]\n            b_mask = (mask[:-1, :] * mask[1:, :])[1:, 1:-1]\n            l_mask = (mask[:, 1:] * mask[:, :-1])[1:-1, :-1]\n            r_mask = (mask[:, :-1] * mask[:, 1:])[1:-1, 1:]\n            u_diff = u_diff * u_mask\n            b_diff = b_diff * b_mask\n            l_diff = l_diff * l_mask\n            r_diff = r_diff * r_mask\n        u_over = (np.abs(u_diff) > 0).astype(np.float32)\n        b_over = (np.abs(b_diff) > 0).astype(np.float32)\n        l_over = (np.abs(l_diff) > 0).astype(np.float32)\n        r_over = (np.abs(r_diff) > 0).astype(np.float32)\n    u_over = np.pad(u_over, 1, mode='constant')\n    b_over = np.pad(b_over, 1, mode='constant')\n    l_over = np.pad(l_over, 1, mode='constant')\n    r_over = np.pad(r_over, 1, mode='constant')\n    u_diff = np.pad(u_diff, 1, mode='constant')\n    b_diff = np.pad(b_diff, 1, mode='constant')\n    l_diff = np.pad(l_diff, 1, mode='constant')\n    r_diff = np.pad(r_diff, 1, mode='constant')\n\n    if vis_diff:\n        return [u_over, b_over, l_over, r_over], [u_diff, b_diff, l_diff, r_diff]\n    else:\n        return [u_over, b_over, l_over, r_over]\n\n# Cell\ndef bilateral_filter(depth, config, discontinuity_map=None, HR=False, mask=None, window_size=False):\n    sort_time = 0\n    replace_time = 0\n    filter_time = 0\n    init_time = 0\n    filtering_time = 0\n    sigma_s = config['sigma_s']\n    sigma_r = config['sigma_r']\n    if window_size == False:\n        window_size = config['filter_size']\n    midpt = window_size//2\n    ax = np.arange(-midpt, midpt+1.)\n    xx, yy = np.meshgrid(ax, ax)\n    if discontinuity_map is not None:\n        spatial_term = np.exp(-(xx**2 + yy**2) / (2. * sigma_s**2))\n\n    # padding\n    depth = depth[1:-1, 1:-1]\n    depth = np.pad(depth, ((1,1), (1,1)), 'edge')\n    pad_depth = np.pad(depth, (midpt,midpt), 'edge')\n    if discontinuity_map is not None:\n        discontinuity_map = discontinuity_map[1:-1, 1:-1]\n        discontinuity_map = np.pad(discontinuity_map, ((1,1), (1,1)), 'edge')\n        pad_discontinuity_map = np.pad(discontinuity_map, (midpt,midpt), 'edge')\n        pad_discontinuity_hole = 1 - pad_discontinuity_map\n    # filtering\n    output = depth.copy()\n    pad_depth_patches = rolling_window(pad_depth, [window_size, window_size], [1,1])\n    if discontinuity_map is not None:\n        pad_discontinuity_patches = rolling_window(pad_discontinuity_map, [window_size, window_size], [1,1])\n        pad_discontinuity_hole_patches = rolling_window(pad_discontinuity_hole, [window_size, window_size], [1,1])\n\n    if mask is not None:\n        pad_mask = np.pad(mask, (midpt,midpt), 'constant')\n        pad_mask_patches = rolling_window(pad_mask, [window_size, window_size], [1,1])\n    from itertools import product\n    if discontinuity_map is not None:\n        pH, pW = pad_depth_patches.shape[:2]\n        for pi in range(pH):\n            for pj in range(pW):\n                if mask is not None and mask[pi, pj] == 0:\n                    continue\n                if discontinuity_map is not None:\n                    if bool(pad_discontinuity_patches[pi, pj].any()) is False:\n                        continue\n                    discontinuity_patch = pad_discontinuity_patches[pi, pj]\n                    discontinuity_holes = pad_discontinuity_hole_patches[pi, pj]\n                depth_patch = pad_depth_patches[pi, pj]\n                depth_order = depth_patch.ravel().argsort()\n                patch_midpt = depth_patch[window_size//2, window_size//2]\n                if discontinuity_map is not None:\n                    coef = discontinuity_holes.astype(np.float32)\n                    if mask is not None:\n                        coef = coef * pad_mask_patches[pi, pj]\n                else:\n                    range_term = np.exp(-(depth_patch-patch_midpt)**2 / (2. * sigma_r**2))\n                    coef = spatial_term * range_term\n                if coef.max() == 0:\n                    output[pi, pj] = patch_midpt\n                    continue\n                if discontinuity_map is not None and (coef.max() == 0):\n                    output[pi, pj] = patch_midpt\n                else:\n                    coef = coef/(coef.sum())\n                    coef_order = coef.ravel()[depth_order]\n                    cum_coef = np.cumsum(coef_order)\n                    ind = np.digitize(0.5, cum_coef)\n                    output[pi, pj] = depth_patch.ravel()[depth_order][ind]\n    else:\n        pH, pW = pad_depth_patches.shape[:2]\n        for pi in range(pH):\n            for pj in range(pW):\n                if discontinuity_map is not None:\n                    if pad_discontinuity_patches[pi, pj][window_size//2, window_size//2] == 1:\n                        continue\n                    discontinuity_patch = pad_discontinuity_patches[pi, pj]\n                    discontinuity_holes = (1. - discontinuity_patch)\n                depth_patch = pad_depth_patches[pi, pj]\n                depth_order = depth_patch.ravel().argsort()\n                patch_midpt = depth_patch[window_size//2, window_size//2]\n                range_term = np.exp(-(depth_patch-patch_midpt)**2 / (2. * sigma_r**2))\n                if discontinuity_map is not None:\n                    coef = spatial_term * range_term * discontinuity_holes\n                else:\n                    coef = spatial_term * range_term\n                if coef.sum() == 0:\n                    output[pi, pj] = patch_midpt\n                    continue\n                if discontinuity_map is not None and (coef.sum() == 0):\n                    output[pi, pj] = patch_midpt\n                else:\n                    coef = coef/(coef.sum())\n                    coef_order = coef.ravel()[depth_order]\n                    cum_coef = np.cumsum(coef_order)\n                    ind = np.digitize(0.5, cum_coef)\n                    output[pi, pj] = depth_patch.ravel()[depth_order][ind]\n\n    return output\n\n# Cell\ndef rolling_window(a, window, strides):\n    assert len(a.shape)==len(window)==len(strides), \"\\'a\\', \\'window\\', \\'strides\\' dimension mismatch\"\n    shape_fn = lambda i,w,s: (a.shape[i]-w)//s + 1\n    shape = [shape_fn(i,w,s) for i,(w,s) in enumerate(zip(window, strides))] + list(window)\n    def acc_shape(i):\n        if i+1>=len(a.shape):\n            return 1\n        else:\n            return reduce(lambda x,y:x*y, a.shape[i+1:])\n    _strides = [acc_shape(i)*s*a.itemsize for i,s in enumerate(strides)] + list(a.strides)\n\n    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=_strides)", "meta": {"hexsha": "fe2fcd494ed44b2986890531adbb8b5c033d64c2", "size": 9729, "ext": "py", "lang": "Python", "max_stars_repo_path": "pomerantz/bilateral_filtering.py", "max_stars_repo_name": "bitcloud2/3d-photo-inpainting", "max_stars_repo_head_hexsha": "5570e95f699effa0fbae3f49abf2b5f505831e30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-25T07:08:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T07:08:05.000Z", "max_issues_repo_path": "pomerantz/bilateral_filtering.py", "max_issues_repo_name": "bitcloud2/pomerantz", "max_issues_repo_head_hexsha": "5570e95f699effa0fbae3f49abf2b5f505831e30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pomerantz/bilateral_filtering.py", "max_forks_repo_name": "bitcloud2/pomerantz", "max_forks_repo_head_hexsha": "5570e95f699effa0fbae3f49abf2b5f505831e30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.6278026906, "max_line_length": 115, "alphanum_fraction": 0.5610031864, "include": true, "reason": "import numpy", "num_tokens": 2668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883592602051, "lm_q2_score": 0.3174262785020255, "lm_q1q2_score": 0.19051555728020358}}
{"text": "# -*- coding: utf-8 -*-\n\ntry:\n    from ducc0.wgridder import dirty2ms, ms2dirty\nexcept ImportError as e:\n    ducc_import_error = e\nelse:\n    ducc_import_error = None\n\nimport numpy as np\nfrom africanus.util.docs import DocstringTemplate\nfrom africanus.util.requirements import requires_optional\n\n\n@requires_optional('ducc0.wgridder', ducc_import_error)\ndef _hessian_internal(uvw, freq, image, freq_bin_idx, freq_bin_counts,\n                      cell, weights, flag, celly, epsilon, nthreads,\n                      do_wstacking, double_accum):\n\n    # adjust for chunking\n    # need a copy here if using multiple row chunks\n    freq_bin_idx2 = freq_bin_idx - freq_bin_idx.min()\n    nband = freq_bin_idx.size\n    _, nx, ny = image.shape\n    # the extra dimension is required to allow for chunking over row\n    convolvedim = np.zeros((1, nband, nx, ny), dtype=image.dtype)\n    for i in range(nband):\n        ind = slice(freq_bin_idx2[i], freq_bin_idx2[i] + freq_bin_counts[i])\n        if weights is not None:\n            wgt = weights[:, ind]\n        else:\n            wgt = None\n        if flag is not None:\n            mask = flag[:, ind]\n        else:\n            mask = None\n        modelvis = dirty2ms(uvw=uvw, freq=freq[ind],\n                            dirty=image[i], wgt=None,\n                            pixsize_x=cell, pixsize_y=celly,\n                            nu=0, nv=0, epsilon=epsilon,\n                            nthreads=nthreads, mask=mask,\n                            do_wstacking=do_wstacking)\n        convolvedim[0, i] = ms2dirty(\n                                uvw=uvw, freq=freq[ind], ms=modelvis,\n                                wgt=wgt, npix_x=nx, npix_y=ny,\n                                pixsize_x=cell, pixsize_y=celly,\n                                nu=0, nv=0, epsilon=epsilon,\n                                nthreads=nthreads, mask=mask,\n                                do_wstacking=do_wstacking,\n                                double_precision_accumulation=double_accum)\n    return convolvedim\n\n\n# This additional wrapper is required to allow the dask wrappers\n# to chunk over row\n@requires_optional('ducc0.wgridder', ducc_import_error)\ndef hessian(uvw, freq, image, freq_bin_idx, freq_bin_counts, cell,\n            weights=None, flag=None, celly=None, epsilon=1e-5, nthreads=1,\n            do_wstacking=True, double_accum=False):\n\n    if celly is None:\n        celly = cell\n\n    if not nthreads:\n        import multiprocessing\n        nthreads = multiprocessing.cpu_count()\n\n    residim = _hessian_internal(uvw, freq, image, freq_bin_idx,\n                                freq_bin_counts, cell, weights, flag,\n                                celly, epsilon, nthreads, do_wstacking,\n                                double_accum)\n    return residim[0]\n\n\nHESSIAN_DOCS = DocstringTemplate(\n    r\"\"\"\n    Compute action of Hessian on an image using ducc\n\n    .. math::\n\n\n        R^\\dagger \\Sigma^{-1} R x\n\n    where :math:`R` is an implicit degridding operator and\n    :math:`x` is the image of shape :code:`(band, nx, ny)`.\n\n    The number of imaging bands :code:`(band)` must\n    be less than or equal to the number of channels\n    :code:`(chan)` at which the data were obtained.\n    The mapping from :code:`(chan)` to :code:`(band)` is described\n    by :code:`freq_bin_idx` and :code:`freq_bin_counts` as\n    described below.\n\n\n    Parameters\n    ----------\n    uvw : $(array_type)\n        uvw coordinates at which visibilities were\n        obtained with shape :code:`(row, 3)`.\n    freq : $(array_type)\n        Observational frequencies of shape :code:`(chan,)`.\n    model : $(array_type)\n        Model image to degrid of shape :code:`(band, nx, ny)`.\n    weights : $(array_type)\n        Imaging weights of shape :code:`(row, chan)`.\n    freq_bin_idx : $(array_type)\n        Starting indices of frequency bins for each imaging\n        band of shape :code:`(band,)`.\n    freq_bin_counts : $(array_type)\n        The number of channels in each imaging band of shape :code:`(band,)`.\n    cell : float\n        The cell size of a pixel along the :math:`x` direction in radians.\n    flag: $(array_type), optional\n        Flags of shape :code:`(row,chan)`. Will only process visibilities\n        for which flag!=0\n    celly : float, optional\n        The cell size of a pixel along the :math:`y` direction in radians.\n        By default same as cell size along :math:`x` direction.\n    nu : int, optional\n        The number of pixels in the padded grid along the :math:`x` direction.\n        Chosen automatically by default.\n    nv : int, optional\n        The number of pixels in the padded grid along the :math:`y` direction.\n        Chosen automatically by default.\n    epsilon : float, optional\n        The precision of the gridder with respect to the direct Fourier\n        transform. By deafult, this is set to :code:`1e-5` for single\n        precision and :code:`1e-7` for double precision.\n    nthreads : int, optional\n        The number of threads to use. Defaults to one.\n    do_wstacking : bool, optional\n        Whether to correct for the w-term or not. Defaults to True\n    double_accum : bool, optional\n        If true ducc will accumulate in double precision regardless of\n        the input type.\n\n    Returns\n    -------\n    residual : $(array_type)\n        Residual image corresponding to :code:`model` of shape\n        :code:`(band, nx, ny)`.\n    \"\"\")\n\ntry:\n    hessian.__doc__ = HESSIAN_DOCS.substitute(\n                        array_type=\":class:`numpy.ndarray`\")\nexcept AttributeError:\n    pass\n", "meta": {"hexsha": "fd367813f9487c8ce3cb907eefa9301883a9bca8", "size": 5540, "ext": "py", "lang": "Python", "max_stars_repo_path": "africanus/gridding/wgridder/hessian.py", "max_stars_repo_name": "JoshVStaden/codex-africanus", "max_stars_repo_head_hexsha": "4a38994431d51510b1749fa0e4b8b6190b8b530f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2018-04-06T09:36:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-13T13:11:00.000Z", "max_issues_repo_path": "africanus/gridding/wgridder/hessian.py", "max_issues_repo_name": "JoshVStaden/codex-africanus", "max_issues_repo_head_hexsha": "4a38994431d51510b1749fa0e4b8b6190b8b530f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 153, "max_issues_repo_issues_event_min_datetime": "2018-03-28T14:13:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T07:49:17.000Z", "max_forks_repo_path": "africanus/gridding/wgridder/hessian.py", "max_forks_repo_name": "JoshVStaden/codex-africanus", "max_forks_repo_head_hexsha": "4a38994431d51510b1749fa0e4b8b6190b8b530f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2018-03-29T13:30:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T02:56:55.000Z", "avg_line_length": 37.1812080537, "max_line_length": 78, "alphanum_fraction": 0.6064981949, "include": true, "reason": "import numpy", "num_tokens": 1351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.1904953324873069}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nHelper functions and variables for the MVA analysis\n\nIn case some other isotopes are of interest, the isotopes variable can be extended.\n\nzs. elter 2020\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib\n\nimport matplotlib.pyplot as plt\nimport random\nimport os\nimport math\nimport re\n\nfrom sklearn import preprocessing\nfrom sklearn import decomposition\n\nisotopes={'Cs134': {'hl':2.065*365,\n                        'energies': [0.563,0.569,0.604,0.795,0.801,1.038,1.167,1.365],\n                        'strength': [8.338,15.373,97.62,85.46,8.688,0.990,1.790,3.017]},\n              'Cs137': {'hl':30.1*365,\n                        'energies': [0.662],\n                        'strength': [85.1]},\n              'Eu154': {'hl':8.6*365,\n                        'energies': [0.723,0.756,0.873,0.996,1.004,1.246,1.274,1.494,1.596],\n                        'strength': [20.06,4.52,12.08,10.48,18.01,0.856,34.8,0.698,1.797]}}\n              \n\ndef AssemblyMap(deftype):\n    \"\"\"Function to produce a 17x17 assembly map with partial defects in it.\n    '1' represents fuel, '2' represent control rod guide, and '3' represents dummy rods.\n    \n    Parameters\n    ----------\n    deftype : str\n       String variable to describe the assembly map (it takes values 'A', 'B', etc) \n    \n    Returns\n    -------\n    mapArray : list of lists\n        A list of list to represent a matrix describing the rod types in the assembly.\n    \"\"\"\n    \n    import random\n    import math\n    SubAsStr=''\n    CrPos=[40,43,46,55,65,88,91,94,97,100,139,142,145,148,151,190,193,196,199,202,225,235,244,247,250]\n    FuelPos=[]\n    for i in range(17*17):\n        j=i+1\n        if j not in CrPos:        \n            FuelPos.append(j)\n    \n    if deftype=='A':\n        DummyPos=[1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,45,47,49,51,53,57,59,61,63,67,69,71,73,75,77,79,81,83,85,87,89,93,95,99,101,103,105,107,109,111,113,115,117,119,121,123,125,127,129,131,133,135,137,141,143,147,149,153,155,157,159,161,163,165,167,169,171,173,175,177,179,181,183,185,187,189,191,195,197,201,203,205,207,209,211,213,215,217,219,221,223,227,229,231,233,237,239,241,243,245,249,251,253,255,257,259,261,263,265,267,269,271,273,275,277,279,281,283,285,287,289]\n    elif deftype=='B':\n        DummyPos=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,21,23,25,27,29,31,33,34,35,37,39,41,45,47,49,51,52,53,57,59,61,63,67,68,69,71,73,81,83,85,86,87,89,99,101,102,103,105,117,119,120,121,123,133,135,136,137,153,154,155,157,167,169,170,171,173,185,187,188,189,191,201,203,204,205,207,209,217,219,221,222,223,227,229,231,233,237,238,239,241,243,245,249,251,253,255,256,257,259,261,263,265,267,269,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289]\n    elif deftype=='C':\n        DummyPos=[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19,21,23,25,27,29,31,33,34,35,37,39,41,45,47,49,51,52,53,57,59,61,63,67,68,69,71,73,75,79,81,83,85,86,87,89,99,101,102,103,105,117,119,120,121,123,133,135,136,137,153,154,155,157,167,169,170,171,173,185,187,188,189,191,201,203,204,205,207,209,211,215,217,219,221,222,223,227,229,231,233,237,238,239,241,243,245,249,251,253,255,256,257,259,261,263,265,267,269,271,272,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288]\n    elif deftype=='D':\n        DummyPos=[2,3,4,5,6,7,8,10,11,12,13,14,15,16,18,21,23,25,27,29,31,34,35,37,39,41,45,47,49,51,52,53,57,59,61,63,67,68,69,71,73,75,79,81,83,85,86,87,89,99,101,102,103,105,107,109,113,115,117,119,120,121,123,133,135,136,154,155,157,167,169,170,171,173,175,177,181,183,185,187,188,189,191,201,203,204,205,207,209,211,215,217,219,221,222,223,227,229,231,233,237,238,239,241,243,245,249,251,253,255,256,259,261,263,265,267,269,272,274,275,276,277,278,279,280,282,283,284,285,286,287,288]\n    elif deftype=='E':\n        DummyPos=[22,24,25,27,28,30,37,49,58,59,61,62,70,73,75,76,78,79,81,84,104,106,107,109,110,112,113,115,116,118,121,123,124,126,127,129,130,132,133,135,155,157,158,160,161,163,164,166,167,169,172,174,175,177,178,180,181,183,184,186,206,209,211,212,214,215,217,220,228,229,231,232,241,253,260,262,263,265,266,268]\n    elif deftype=='F':\n        DummyPos=[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,48,50,52,54,58,62,66,68,70,73,81,84,86,102,104,106,116,118,120,136,138,152,154,170,172,174,184,186,188,204,206,209,217,220,222,224,228,232,236,238,240,242,252,254,256,258,260,262,264,266,268,270,272,274,276,278,280,282,284,286,288]\n    elif deftype=='G':\n        DummyPos=[1,2,3,4,7,8,9,10,11,14,15,16,17,18,19,22,30,33,34,35,37,49,51,52,68,70,84,103,109,113,119,120,136,137,153,154,170,171,177,181,187,206,220,222,238,239,241,253,255,256,257,260,268,271,272,273,274,275,276,279,280,281,282,283,286,287,288,289]    \n    elif deftype=='H':\n        DummyPos=[1,2,4,6,8,9,10,12,14,16,17,18,20,24,28,32,34,36,50,52,58,62,68,73,81,86,102,104,106,116,118,120,136,137,153,154,170,172,174,184,186,188,204,209,217,222,228,232,238,240,254,256,258,262,266,270,272,273,274,276,278,280,281,282,284,286,288,289]\n    elif deftype=='I':\n        DummyPos=[1,2,3,5,8,9,10,13,15,16,17,18,19,33,34,35,51,56,64,69,75,79,85,120,136,137,153,154,170,205,211,215,221,226,234,239,255,256,257,271,272,273,274,275,277,280,281,282,285,287,288,289]  \n    elif deftype=='J':\n        DummyPos=[1,2,4,6,8,10,12,14,16,17,18,20,24,28,32,34,36,50,52,68,86,102,104,118,120,136,154,170,172,186,188,204,222,238,240,254,256,258,262,266,270,272,273,274,276,278,280,282,284,286,288,289]   \n    elif deftype=='K':\n        DummyPos=[1,2,3,5,8,10,13,15,16,17,18,19,33,34,35,51,69,85,120,136,154,170,205,221,239,255,256,257,271,272,273,274,275,277,280,282,285,287,288,289]  \n    elif deftype=='L':\n        DummyPos=[1,2,5,9,13,16,17,18,19,24,28,33,34,37,49,69,85,104,118,137,153,172,186,205,221,241,253,256,257,262,266,271,272,273,274,277,281,285,288,289]\n    elif deftype=='M':\n        DummyPos=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,51,52,68,69,85,86,102,103,119,120,136,137,153,154,170,171,187,188,204,205,221,222,238,239,255,256,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289]\n    elif deftype=='N':\n        DummyPos=[37,38,39,41,45,47,48,49,54,57,59,61,63,66,71,73,75,77,79,81,83,89,93,95,99,105,107,109,111,113,115,117,123,125,127,129,131,133,141,143,147,149,157,159,161,163,165,167,173,175,177,179,181,183,185,191,195,197,201,207,209,211,213,215,217,219,224,227,229,231,233,236,241,242,243,245,249,251,252,253]\n    elif deftype=='O':\n        DummyPos=[]\n    elif deftype=='P':\n        DummyPos=[37,38,39,41,42,54,56,57,58,59,60,71,72,73,74,75,76,77,89,90,92,93,105,106,107,108,109,110,111,122,123,124,125,126,127,128,140,141,143,144]\n    elif deftype=='Q':\n        DummyPos=[92,93,95,96,108,109,110,111,112,113,114,125,126,127,128,129,130,131,143,144,146,147,159,160,161,162,163,164,165,176,177,178,179,180,181,182,194,195,197,198]\n    elif deftype=='R':\n        DummyPos=[5,14,21,24,27,28,30,37,42,44,45,49,50,53,58,64,69,70,72,75,76,78,79,82,85,89,90,92,96,98,101,106,107,110,115,116,123,124,129,134,140,144,147,156,158,159,163,167,168,171,174,177,178,180,181,194,205,211,213,215,216,219,222,224,232,236,237,239,240,246,257,260,261,268,276,278,282,283,285,286]\n    elif deftype=='S':\n        DummyPos=[1,2,3,4,5,6,7,8,9,18,19,20,21,22,23,24,25,35,36,37,38,39,41,42,52,53,54,56,57,58,59,60,69,70,71,72,73,74,75,76,86,87,89,90,92,93,103,104,105,106,107,108,109,110,111,120,121,122,123,124,125,126,127,138,141,144,146,149,152,163,164,165,166,167,168,169,170,179,180,181,182,183,184,185,186,187,197,198,200,201,203,204,214,215,216,217,218,219,220,221,230,231,232,233,234,236,237,238,248,249,251,252,253,254,255,265,266,267,268,269,270,271,272,281,282,283,284,285,286,287,288,289]\n    elif deftype=='T':\n        DummyPos=[1,2,3,4,5,6,7,8,9,18,19,20,21,22,23,24,25,35,36,37,38,39,41,42,52,53,54,56,57,58,59,60,69,70,71,72,73,74,75,76,86,87,89,90,92,93,103,104,105,106,107,108,109,110,111,120,121,122,123,124,125,126,127,137,138,140,141,143,144,154,155,156,157,158,159,160,161,162,171,172,173,174,175,176,177,178,188,189,191,192,194,195,205,206,207,208,209,210,211,212,213,222,223,224,226,227,228,229,239,240,241,242,243,245,246,256,257,258,259,260,261,262,263,264,273,274,275,276,277,278,279,280]\n    ND=len(DummyPos)\n    mapArray=[]\n    col=1\n    for i in range(17*17):\n        j=i+1\n        if col==1:\n            SubAsStr=SubAsStr+'        '\n            mapArray.append([])\n        if j in CrPos:\n            SubAsStr=SubAsStr+' '+str(3)#str(random.choice([4,6]))\n            mapArray[-1].append('3')\n        elif j in DummyPos:\n            SubAsStr=SubAsStr+' '+str(2)\n            mapArray[-1].append('2')\n        else:\n            SubAsStr=SubAsStr+' '+str(1)\n            mapArray[-1].append('1')\n        if col==17:\n            SubAsStr=SubAsStr+'\\n'\n            col=0\n        col=col+1\n    SubAsStr=SubAsStr[:-1]\n        \n    return mapArray\n\n\ndef detectorEff(E):\n    \"\"\"Function to describe the detector efficiency. It is based on a fit of \n    Serpent2 results.\n    \n    Parameters\n    ----------\n    E : float or list\n        Energy in MeV\n    \n    Returns\n    -------\n    Eps : float or list\n        Detector efficiency at energy/energies E\n    \"\"\"\n    E=E*1000 #change MeV to keV\n    a=-8.02741343e-02\n    b=-1.49151904e-01\n    c=-2.84160334e-01\n    d=4.39778388e-02\n    e=1.19674986e-03\n    f=1.26102944e+02\n    \n    lnEps=a+b*np.log(E/f)+c*(np.log(E/f))**2+d*(np.log(E/f))**3+e*(np.log(E/f))**4\n    \n    Eps=np.exp(lnEps)\n    return Eps\n              \ndef gammaLines(row,nuclides=['Cs137','Cs134','Eu154']):\n    \"\"\"\n    Function to return the energy line intensities. For this the concentrations of nuclides\n    are converted into activity concentrations, and then into the intensity of the lines. This\n    value is basically in emission/cm3/s units.\n    \n    Parameters\n    ----------\n    row : dict or pandas dataframe row\n        dictionary to keep track of the spent fuel inventory.\n    nuclides : list\n        list of the nuclide identifiers for which the gamma line intensities are to be evaluated\n    \n    Returns\n    -------\n    lines : dict\n        nested dictionary to store the gamma line intensities. outer keys are nuclide identifiers,\n        inner keys are 'energies' and 'strength'. \n    energies : numpy array\n        List of gamma line energies.\n    \"\"\"\n    d2s=86400\n    \n    lines={}\n    for iso in isotopes:\n        lines[iso]={'energies':[],'strength':[]}\n        conci=row[iso]\n        acti=conci*1e24*(np.log(2)/(isotopes[iso]['hl']*d2s))\n        for en,br in zip(isotopes[iso]['energies'],isotopes[iso]['strength']):\n            enfreq=acti*br\n            lines[iso]['energies'].append(en)\n            lines[iso]['strength'].append(enfreq)\n    \n    energies=[]\n    for key in nuclides:\n        for en in isotopes[key]['energies']:\n            energies.append(key+': '+str(en))\n    energies=np.array(energies)\n    return lines,energies\n\n\ndef prepareX(fuellib=None, cases=['O','R'],nuclides=['Cs137','Cs134','Eu154'],ratio=False,scaling=True,normalization=True,\n             encoding={'O':0,'R':1},gefffilestem='outs/geomEff_',fresh=False):\n    \"\"\"\n    Function to create the X matrix, which has the feature vectors as its rows.\n    This is not a very straightforward function, it is just to wrap up some data \n    management.\n    \n    Parameters\n    ----------\n    fuellib : pandas dataframe\n        Fuel library. For further details see https://doi.org/10.1016/j.dib.2020.106429\n    cases : list of strings\n        The assembly types in the analysis. It is important that the geometric efficiency files\n        include these strings in it.\n    ratio : bool\n        if True the pairwise ratios of the features are returned.\n    scaling : bool\n        if True standard scaling is performed on the data\n    normalization : bool\n        if True, the feature vectors are normalized to sum to 1\n    encoding : dictionary\n        For classification numeric labels are preferred, thuse the cases need to be ecoded.\n        Here one can also make sure whether several cases should be encoded into only 2 classes.\n    gefffilestem : str\n        The path and filename stem of the geometric efficiency curves. This will be \n        extended with the string describing the case.\n    fresh : bool\n        If True, always the geometric efficiency of fresh fuel is used.\n        \n    Returns\n    -------\n    data : numpy array\n        The data matrix. If the ratios are requested, then the matrix of the ratios\n    labels : numpy array\n        Encoded labels for all samples\n    energies : numpy array\n        Array of energies or energie ratios to identify the columns of the data matrix\n    \"\"\"\n    if fuellib is None:\n        raise TypeError('No fuel library is added.')\n    colN=0\n    for nucl in nuclides:\n        colN=colN+len(isotopes[nucl]['energies'])\n    \n    data=np.empty((0,colN))\n    dataratio=np.empty((0,int((colN**2-colN)/2)))\n    labels=[]    \n    \n    \n    for index, fuel in fuellib.iterrows():\n        lines,energies=gammaLines(fuel)\n        peaks=['']\n        for c in cases:\n            if fresh:\n                engeff=np.loadtxt(gefffilestem+'%s_orig.dat'%c)\n            else:\n                engeff=np.loadtxt(gefffilestem+'%s_%d.dat'%(c,fuel['id']))\n            peaks={}\n            for iso in lines:\n                peaks[iso]={'energies': [], 'strength':[]}\n                for en,st in zip(lines[iso]['energies'],lines[iso]['strength']):\n                    peaks[iso]['energies'].append(en)\n                    peaki=st*np.interp(en,engeff[:,0],engeff[:,1])*detectorEff(en)\n                    peaks[iso]['strength'].append(peaki)\n\n            feature=[]\n            for nucl in nuclides:\n                for strength in peaks[nucl]['strength']:\n                    feature.append(strength)\n            feature=np.array(feature)\n            \n            featureratio=[]\n            energiesratio=[]\n            for i,(fi,ei) in enumerate(zip(feature,energies)):\n                for j,(fj,ej) in enumerate(zip(feature,energies)):\n                    if j>i:\n                        if fi/fj >= fj/fi:\n                            featureratio.append(fi/fj)\n                        else:\n                            featureratio.append(fj/fi)\n                        energiesratio.append(ei+' / '+ej)\n            featureratio=np.array(featureratio)\n\n            if normalization:\n                feature=feature/sum(feature)\n                featureratio=featureratio/sum(featureratio)\n            \n            data=np.vstack([data,feature])\n            dataratio=np.vstack([dataratio,featureratio])\n            \n            labels.append(encoding[c]) \n    #TODO bring normalization here, to see the impact of doing scaling first\n    labels=np.array(labels)\n    \n    if scaling:\n        data = preprocessing.scale(data)\n        dataratio = preprocessing.scale(dataratio)\n    \n    if ratio:\n        return dataratio,labels,np.array(energiesratio)\n    else:\n        return data,labels,energies\n\ndef AtConc_to_ZWeightPer(row):\n    \"\"\"Function to convert spent fuel inventory from nuclidewise atom concentration\n    to elementwise weight percentage. \n    The function expects a pandas row from the MVA dataset.\n    1, calculates the mass per cm3 for each isotope\n    2, changes the ZAID into elements and sums the mass of each element\n    3, returns the normalized mass (ie w%) for each element\n    \n    Parameters\n    ----------\n    row : pandas dataframe\n        Row in dataframe describing the fuel inventory\n    \n    Returns\n    -------\n    masspervolume : dict\n        Dictionary which stores the mass percentage for each element (which are the keys).\n    \"\"\"\n    \n    #precondition row into dictionary\n    inventory = row.to_dict()\n    inventory.pop('Unnamed: 0') #note this is highly specific\n    inventory.pop('BU')\n    inventory.pop('CT')\n    inventory.pop('IE')\n    inventory.pop('fuelType')\n    inventory.pop('TOT_SF')\n    inventory.pop('TOT_GSRC')\n    inventory.pop('TOT_A')\n    inventory.pop('TOT_H')\n    \n    NA = 6.022140857E23\n    masspervolume = {}\n    \n    \n    for iso in inventory:\n        isoText = re.findall('\\D+', iso)\n        isoNum =  re.findall('\\d+', iso)\n        Z=isoText[0]\n        A=float(isoNum[0])\n            \n        massconci = A*((inventory[iso]*1e24)/NA)  #this gives the mass of that isotope in g/cm3\n        \n        if Z in masspervolume:\n            masspervolume[Z]=masspervolume[Z]+massconci\n        else:\n            masspervolume[Z]=massconci\n            \n        \n    #getting weight%\n    summass=sum(masspervolume.values())\n    for element in masspervolume:\n        masspervolume[element]=masspervolume[element]/summass\n    return masspervolume\n    \n\n    \ndef XCOMmaterial(massdic):\n    \"\"\"\n    Function to convert the mass percentages into XCOM readable input string\n    \n    Parameters\n    ----------\n    massdic : dict\n        Dictionary which stores the mass percentage for each element (which are the keys).\n    \n    Returns\n    -------\n    xcomstr : str\n        String which includes the elementwise mass percentages in an XCOM readable form.\n    \"\"\"\n    #printf 'spentfuel\\n4\\n2\\nH\\n0.1\\nO\\n0.9\\n1\\n3\\n1\\n3\\n0.6\\n0.8\\n0.9\\nN\\ntestauto.out\\n1\\n' | ./XCOMtest\n    xcomstr=''    \n    for element in massdic:\n        xcomstr=xcomstr+element+'\\n'+str(massdic[element])+'\\n'\n    return xcomstr\n    \n\n#Variable to match element symbol to Z. not used in these functions!\nnametoZ= {'Mt': 109,\n          'Hs': 108,\n          'Bh': 107,\n          'Sg': 106,\n          'Db': 105,\n          'Rf': 104,\n          'Lr': 103,\n          'No': 102,\n          'Md': 101,\n          'Fm': 100,\n          'Es': 99,\n          'Cf': 98,\n          'Bk': 97,\n          'Cm': 96,\n          'Am': 95,\n          'Pu': 94,\n          'Np': 93,\n          'U': 92,\n          'Pa': 91,\n          'Th': 90,\n          'Ac': 89,\n          'Ra': 88,\n          'Fr': 87,\n          'Rn': 86,\n          'At': 85,\n          'Po': 84,\n          'Bi': 83,\n          'Pb': 82,\n          'Tl': 81,\n          'Hg': 80,\n          'Au': 79,\n          'Pt': 78,\n          'Ir': 77,\n          'Os': 76,\n          'Re': 75,\n          'W': 74,\n          'Ta': 73,\n          'Hf': 72,\n          'Lu': 71,\n          'Yb': 70,\n          'Tm': 69,\n          'Er': 68,\n          'Ho': 67,\n          'Dy': 66,\n          'Tb': 65,\n          'Gd': 64,\n          'Eu': 63,\n          'Sm': 62,\n          'Pm': 61,\n          'Nd': 60,\n          'Pr': 59,\n          'Ce': 58,\n          'La': 57,\n          'Ba': 56,\n          'Cs': 55,\n          'Xe': 54,\n          'I': 53,\n          'Te': 52,\n          'Sb': 51,\n          'Sn': 50,\n          'In': 49,\n          'Cd': 48,\n          'Ag': 47,\n          'Pd': 46,\n          'Rh': 45,\n          'Ru': 44,\n          'Tc': 43,\n          'Mo': 42,\n          'Nb': 41,\n          'Zr': 40,\n          'Y': 39,\n          'Sr': 38,\n          'Rb': 37,\n          'Kr': 36,\n          'Br': 35,\n          'Se': 34,\n          'As': 33,\n          'Ge': 32,\n          'Ga': 31,\n          'Zn': 30,\n          'Cu': 29,\n          'Ni': 28,\n          'Co': 27,\n          'Fe': 26,\n          'Mn': 25,\n          'Cr': 24,\n          'V': 23,\n          'Ti': 22,\n          'Sc': 21,\n          'Ca': 20,\n          'K': 19,\n          'Ar': 18,\n          'Cl': 17,\n          'S': 16,\n          'P': 15,\n          'Si': 14,\n          'Al': 13,\n          'Mg': 12,\n          'Na': 11,\n          'Ne': 10,\n          'F': 9,\n          'O': 8,\n          'N': 7,\n          'C': 6,\n          'B': 5,\n          'Be': 4,\n          'Li': 3,\n          'He': 2,\n          'H': 1}", "meta": {"hexsha": "cf906f1bb92b9c6837c45fa33afada7ad67e588c", "size": 19619, "ext": "py", "lang": "Python", "max_stars_repo_path": "MVAfunctions.py", "max_stars_repo_name": "ezsolti/PartialDefect", "max_stars_repo_head_hexsha": "06b7ddfc17fac64a8f540502e9c1422003e48ae2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MVAfunctions.py", "max_issues_repo_name": "ezsolti/PartialDefect", "max_issues_repo_head_hexsha": "06b7ddfc17fac64a8f540502e9c1422003e48ae2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MVAfunctions.py", "max_forks_repo_name": "ezsolti/PartialDefect", "max_forks_repo_head_hexsha": "06b7ddfc17fac64a8f540502e9c1422003e48ae2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-09T13:28:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-09T13:28:57.000Z", "avg_line_length": 40.5351239669, "max_line_length": 496, "alphanum_fraction": 0.5784188797, "include": true, "reason": "import numpy", "num_tokens": 7038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.32766831395172374, "lm_q1q2_score": 0.19047460360634821}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# OSeMOSYS-PLEXOS global model: Powerplant data\n\n# Import modules\nimport pandas as pd\nimport os\npd.options.mode.chained_assignment = None  # default='warn'\nimport numpy as np\nimport itertools\nfrom urllib import request\n\nPLEXOS_URL = \"https://dataverse.harvard.edu/api/access/datafile/4008393?format=original&gbrecs=true\"\nPLEXOS_DATA = \"PLEXOS_World_2015_Gold_V1.1.xlsx\"\n\nMODE_LIST = [1, 2]\n\n\ndef get_data(INPUT_PATH):\n    # Import data files and user input\n    # Checks whether PLEXOS-World 2015 data needs to be retrieved from the PLEXOS-World Harvard Dataverse.\n    path = os.path.join(INPUT_PATH, PLEXOS_DATA)\n    try:\n        workbook = open(path, 'rb')\n    except IOError:\n        request.urlretrieve(PLEXOS_URL, path)\n        workbook = open(path, 'rb')\n    finally:\n        df = pd.read_excel(workbook, sheet_name=\"Properties\")\n        df_dict = pd.read_excel(workbook, sheet_name=\"Memberships\")\n        workbook.close()\n\n    df_dict = df_dict[df_dict[\"parent_class\"] == \"Generator\"].rename(\n        {\"parent_object\": \"powerplant\"}, axis=1\n    )\n    return df, df_dict\n\n\ndef create_main_generator_table(df):\n    # Create main generator table\n    gen_cols_1 = [\"child_class\", \"child_object\", \"property\", \"value\"]\n    df_gen = df[gen_cols_1]\n    df_gen = df_gen[df_gen[\"child_class\"] == \"Generator\"]\n    df_gen.rename(columns={\"child_object\": \"powerplant\"}, inplace=True)\n    df_gen.drop(\"child_class\", axis=1, inplace=True)\n    df_gen = pd.pivot_table(df_gen,\n                            index=\"powerplant\",\n                            columns=\"property\",\n                            values=\"value\",\n                            aggfunc=np.sum,\n                            fill_value=0,\n                           )\n    df_gen[\"total_capacity\"] = (df_gen[\"Max Capacity\"].astype(float)) * (\n        df_gen[\"Units\"].astype(int)\n    )\n\n    gen_cols_2 = [\"Commission Date\", \"Heat Rate\", \"Max Capacity\", \"total_capacity\"]\n    df_gen_2 = df_gen[gen_cols_2]\n    return df_gen_2\n\n\ndef compile_powerplants_nodes_fuels(df_dict):\n    ## Compile dataframe with powerplants, nodes, and fuels\n    df_dict_fuel = df_dict[df_dict[\"collection\"] == \"Fuels\"]\n    df_dict_fuel = df_dict_fuel[[\"powerplant\", \"child_object\"]]\n    df_dict_nodes = df_dict[df_dict[\"collection\"] == \"Nodes\"]\n    df_dict_nodes = df_dict_nodes[[\"powerplant\", \"child_object\"]]\n    df_dict_2 = pd.merge(df_dict_fuel, df_dict_nodes, how=\"outer\", on=\"powerplant\")\n    return df_dict_2\n\n\ndef calculate_activity_ratios(thermal_fuel_list, region_name, thermal_fuel_list_iar, renewables_list,\n                              df_gen_2, df, model_start_year, model_end_year, df_trn_efficiencies):\n    # Create master table for activity ratios\n    years = get_years(model_start_year, model_end_year)\n    df_ratios = ratio_master_table(df_gen_2, years)\n    # Calculate Input and OutputActivityRatio for: Power Generation\n    df_oar, df_oar_final = output_activity_ratios(df_ratios, thermal_fuel_list, region_name)\n    df_iar_final = input_activity_ratio(df_oar, thermal_fuel_list_iar, renewables_list, df_gen_2, region_name)\n    # Upstream,\n    df_oar_upstream = upstream_output_activity_ratios(df_iar_final, renewables_list)\n    # international markets,\n    df_oar_int = international_output_activity_ratios(df_oar_upstream)\n    df_iar_int = international_input_activity_ratio(df_oar_int)\n    # domestic transmission and\n    df_iar_trn = domestic_transmission_iar(df_oar_final)\n    df_oar_trn = domestic_transmission_oar(df_iar_trn)\n    # international transmission\n    df_int_trn = create_international_transmission(df, region_name, model_start_year, model_end_year)\n    df_int_trn_iar = international_transmission_iar(df_int_trn)\n    df_trn_efficiencies = transmission_efficiency(df_trn_efficiencies)\n    df_int_trn_oar = international_transmission_oar(df_int_trn, df_trn_efficiencies)\n\n    # Combine the pieces from above and output to csv:\n    df_oar_final = pd.concat([df_oar_final, df_oar_upstream, df_oar_int, df_oar_trn, df_int_trn_oar])\n\n    # Select columns for final output table\n    df_oar_final = df_oar_final.dropna()\n    df_oar_final = df_oar_final[['REGION', 'TECHNOLOGY', 'FUEL', 'MODE_OF_OPERATION', 'YEAR', 'VALUE']]\n\n    df_iar_final = pd.concat([df_iar_final, df_iar_int, df_iar_trn, df_int_trn_iar])\n\n    # Select columns for final output table\n    df_iar_final = df_iar_final.dropna()\n    df_iar_final = df_iar_final[['REGION', 'TECHNOLOGY', 'FUEL', 'MODE_OF_OPERATION', 'YEAR', 'VALUE']]\n    return df_oar_final, df_iar_final\n\n\ndef international_transmission_oar(df_int_trn, df_trn_efficiencies):\n    df_int_trn_oar = df_int_trn.copy()\n    # OAR Mode 2 is output to first country:\n    df_int_trn_oar.loc[df_int_trn_oar[\"MODE_OF_OPERATION\"] == 2, \"FUEL\"] = (\n        \"ELC\" + df_int_trn_oar[\"TECHNOLOGY\"].str[3:8] + \"01\"\n    )\n    # OAR Mode 1 is out to the second country:\n    df_int_trn_oar.loc[df_int_trn_oar[\"MODE_OF_OPERATION\"] == 1, \"FUEL\"] = (\n        \"ELC\" + df_int_trn_oar[\"TECHNOLOGY\"].str[8:13] + \"01\"\n    )\n\n    # and add values into OAR matrix\n    df_int_trn_oar = df_int_trn_oar.drop([\"VALUE\"], axis=1)\n    df_int_trn_oar = pd.merge(\n        df_int_trn_oar, df_trn_efficiencies, how=\"outer\", on=\"TECHNOLOGY\"\n    )\n    return df_int_trn_oar\n\n\ndef transmission_efficiency(df_trn_efficiencies):\n    # Drop unneeded columns\n    df_trn_efficiencies = df_trn_efficiencies.drop(\n        [\n            \"Line\",\n            \"KM distance\",\n            \"HVAC/HVDC/Subsea\",\n            \"Build Cost ($2010 in $000)\",\n            \"Annual FO&M (3.5% of CAPEX) ($2010 in $000)\",\n            \"Unnamed: 8\",\n            \"Line Max Size (MW)\",\n            \"Unnamed: 10\",\n            \"Unnamed: 11\",\n            \"Unnamed: 12\",\n            \"Subsea lines\",\n        ],\n        axis=1,\n    )\n\n    # Drop NaN values\n    df_trn_efficiencies = df_trn_efficiencies.dropna(subset=[\"From\"])\n\n    # Create To and From Codes:\n    # If from column has length 6 then it's the last three chars plus XX\n    df_trn_efficiencies.loc[df_trn_efficiencies[\"From\"].str.len() == 6, \"From\"] = (\n        df_trn_efficiencies[\"From\"].str[3:6] + \"XX\"\n    )\n    # If from column has length 9 then it's the 3:6 and 7:9 three chars plus XX\n    df_trn_efficiencies.loc[df_trn_efficiencies[\"From\"].str.len() == 9, \"From\"] = (\n        df_trn_efficiencies[\"From\"].str[3:6] + df_trn_efficiencies[\"From\"].str[7:9]\n    )\n    # If from column has length 6 then it's the last three chars plus XX\n    df_trn_efficiencies.loc[df_trn_efficiencies[\"To\"].str.len() == 6, \"To\"] = (\n        df_trn_efficiencies[\"To\"].str[3:6] + \"XX\"\n    )\n    # If from column has length 9 then it's the 3:6 and 7:9 three chars plus XX\n    df_trn_efficiencies.loc[df_trn_efficiencies[\"To\"].str.len() == 9, \"To\"] = (\n        df_trn_efficiencies[\"To\"].str[3:6] + df_trn_efficiencies[\"To\"].str[7:9]\n    )\n\n    # Combine From and To columns.\n    # If the From is earlier in the alphabet the technology is in order, add tech with mode 1.\n    df_trn_efficiencies[\"TECHNOLOGY\"] = (\"TRN\" + df_trn_efficiencies[\"From\"] + df_trn_efficiencies[\"To\"])\n\n    # Drop to and from columns\n    df_trn_efficiencies = df_trn_efficiencies.drop([\"From\", \"To\"], axis=1)\n\n    # Rename column 'VALUES'\n    df_trn_efficiencies = df_trn_efficiencies.rename(columns={\"Losses\": \"VALUE\"})\n\n    # And adjust OAR values to be output amounts vs. losses:\n    df_trn_efficiencies['VALUE'] = 1.0 - df_trn_efficiencies['VALUE']\n    return df_trn_efficiencies\n\n\ndef international_transmission_iar(df_int_trn):\n    # Now create the input and output activity ratios\n    df_int_trn_iar = df_int_trn.copy()\n    # IAR Mode 1 is input from first country:\n    df_int_trn_iar.loc[df_int_trn_iar[\"MODE_OF_OPERATION\"] == 1, \"FUEL\"] = (\n        \"ELC\" + df_int_trn_iar[\"TECHNOLOGY\"].str[3:8] + \"02\"\n    )\n    # IAR Mode 2 is input from second country:\n    df_int_trn_iar.loc[df_int_trn_iar[\"MODE_OF_OPERATION\"] == 2, \"FUEL\"] = (\n        \"ELC\" + df_int_trn_iar[\"TECHNOLOGY\"].str[8:13] + \"02\"\n    )\n    return df_int_trn_iar\n\n\ndef create_international_transmission(df, region_name, model_start_year, model_end_year):\n    # Build international transmission system from original input data, but for Line rather than Generator:\n    int_trn_cols = [\"child_class\", \"child_object\", \"property\", \"value\"]\n    df_int_trn = df[int_trn_cols]\n    df_int_trn = df_int_trn[df_int_trn[\"child_class\"] == \"Line\"]\n\n    # For IAR and OAR we can drop the value:\n    df_int_trn = df_int_trn.drop([\"child_class\", \"value\"], axis=1)\n\n    # Create MofO column based on property:\n    df_int_trn[\"MODE_OF_OPERATION\"] = 1\n    df_int_trn.loc[df_int_trn[\"property\"] == \"Min Flow\", \"MODE_OF_OPERATION\"] = 2\n\n    # Use the child_object column to build the technology names:\n    df_int_trn[\"codes\"] = df_int_trn[\"child_object\"].str.split(pat=\"-\")\n\n    # If there are only two locations, then the node is XX\n    df_int_trn.loc[df_int_trn[\"codes\"].str.len() == 2, \"TECHNOLOGY\"] = (\n        \"TRN\" + df_int_trn[\"codes\"].str[0] + \"XX\" + df_int_trn[\"codes\"].str[1] + \"XX\"\n    )\n    # If there are four locations, the node is already included\n    df_int_trn.loc[df_int_trn[\"codes\"].str.len() == 4, \"TECHNOLOGY\"] = (\n        \"TRN\"\n        + df_int_trn[\"codes\"].str[0]\n        + df_int_trn[\"codes\"].str[1]\n        + df_int_trn[\"codes\"].str[2]\n        + df_int_trn[\"codes\"].str[3]\n    )\n    # If there are three items, and the last item is two characters, then the second item is an XX:\n    df_int_trn.loc[\n        (df_int_trn[\"codes\"].str.len() == 3) & (df_int_trn[\"codes\"].str[2].str.len() == 2),\n        \"TECHNOLOGY\",\n    ] = (\n        \"TRN\"\n        + df_int_trn[\"codes\"].str[0]\n        + \"XX\"\n        + df_int_trn[\"codes\"].str[1]\n        + df_int_trn[\"codes\"].str[2]\n    )\n    # If there are three items, and the last item is three characters, then the last item is an XX:\n    df_int_trn.loc[\n        (df_int_trn[\"codes\"].str.len() == 3) & (df_int_trn[\"codes\"].str[2].str.len() == 3),\n        \"TECHNOLOGY\",\n    ] = (\n        \"TRN\"\n        + df_int_trn[\"codes\"].str[0]\n        + df_int_trn[\"codes\"].str[1]\n        + df_int_trn[\"codes\"].str[2]\n        + \"XX\"\n    )\n\n    # Set the value (of either IAR or OAR) to 1\n    df_int_trn[\"VALUE\"] = 1\n    df_int_trn[\"REGION\"] = region_name\n\n    df_int_trn = df_int_trn.drop([\"property\", \"child_object\", \"codes\"], axis=1)\n    df_int_trn[\"YEAR\"] = model_start_year\n    # Add in the years:\n    df_temp = df_int_trn.copy()\n    for year in range(model_start_year + 1, model_end_year + 1):\n        df_temp[\"YEAR\"] = year\n        df_int_trn = df_int_trn.append(df_temp)\n\n    df_int_trn = df_int_trn.reset_index(drop=True)\n    return df_int_trn\n\n\ndef domestic_transmission_oar(df_iar_trn):\n    # OAR for transmission technologies is IAR, but the fuel is 02 instead of 01:\n    df_oar_trn = df_iar_trn.copy()\n    df_oar_trn[\"FUEL\"] = df_oar_trn[\"FUEL\"].str[0:8] + \"02\"\n    return df_oar_trn\n\n\ndef domestic_transmission_iar(df_oar_final):\n    # Build transmission system outputs\n\n    df_iar_trn = df_oar_final.copy()\n\n    # Change the technology name to PWRTRNXXXXX\n    df_iar_trn[\"TECHNOLOGY\"] = \"PWRTRN\" + df_iar_trn[\"FUEL\"].str[3:8]\n    # Make all modes of operation 1\n    df_iar_trn[\"MODE_OF_OPERATION\"] = 1\n    # And remove all the duplicate entries\n    df_iar_trn.drop_duplicates(keep=\"first\", inplace=True)\n    return df_iar_trn\n\n\ndef international_input_activity_ratio(df_oar_int):\n    # All we need to do is take in the thermal fuels for the MINXXXINT technologies.  This already exists as df_oar_int with the XXINT fuel so we can simply copy that:\n    df_iar_int = df_oar_int.copy()\n    df_iar_int['FUEL'] = df_iar_int['FUEL'].str[0:3]\n    return df_iar_int\n\n\ndef international_output_activity_ratios(df_oar_upstream):\n    # Now we have to create the MINXXXINT technologies.  They are all based on the MODE_OF_OPERATION == 2:\n    df_oar_int = pd.DataFrame(df_oar_upstream.loc[df_oar_upstream['MODE_OF_OPERATION'] == 2, :])\n\n    # At this point we should have only the internationally traded fuels since they're all mode 2.  So we can make the tech MINXXXINT and that's that.\n    df_oar_int['TECHNOLOGY'] = 'MIN'+df_oar_int['FUEL']+'INT'\n    # And rename the fuel to XXXINT\n    df_oar_int['FUEL'] = df_oar_int['FUEL']+'INT'\n    df_oar_int['MODE_OF_OPERATION'] = 1  # This is probably not strictly necessary as long as they're always the same in and out...\n\n    # and de-duplicate this list:\n    df_oar_int.drop_duplicates(keep='first',inplace=True)\n    return df_oar_int\n\n\ndef upstream_output_activity_ratios(df_iar_final, renewables_list):\n    # #### OutputActivityRatios - Upstream\n\n    thermal_fuels = ['COA', 'COG', 'GAS', 'PET', 'URN', 'OIL', 'OTH']\n\n    # We have to create a technology to produce every fuel that is input into any of the power technologies:\n\n    df_oar_upstream = df_iar_final.copy()\n\n    # All mining and resource technologies have an OAR of 1...\n    df_oar_upstream['VALUE'] = 1\n\n    # Renewables - set the technology as RNW + FUEL\n    df_oar_upstream.loc[df_oar_upstream['FUEL'].str[0:3].isin(renewables_list),\n            'TECHNOLOGY'] = 'RNW'+df_oar_upstream['FUEL']\n\n    # If the fuel is a thermal fuel, we need to create the OAR for the mining technology... BUT NOT FOR THE INT FUELS...\n    df_oar_upstream.loc[df_oar_upstream['FUEL'].str[0:3].isin(thermal_fuels) & ~(df_oar_upstream['FUEL'].str[3:6] == \"INT\"),\n            'TECHNOLOGY'] = 'MIN'+df_oar_upstream['FUEL']\n\n    # Above should get all the outputs for the MIN technologies, but we need to adjust the mode 2 ones to just the fuel code (rather than MINCOAINT)\n    df_oar_upstream.loc[df_oar_upstream['MODE_OF_OPERATION']==2,\n            'TECHNOLOGY'] = 'MIN'+df_oar_upstream['FUEL'].str[0:3]+df_oar_upstream['TECHNOLOGY'].str[6:9]\n    df_oar_upstream.loc[df_oar_upstream['MODE_OF_OPERATION']==2,\n            'FUEL'] = df_oar_upstream['FUEL'].str[0:3]\n\n    # Now remove the duplicate fuels that the above created (because there's now a COA for each country, not each region, and GAS is repeated twice for each region as well):\n    df_oar_upstream.drop_duplicates(keep='first',inplace=True)\n    return df_oar_upstream\n\n\ndef input_activity_ratio(df_oar, thermal_fuel_list_iar, renewables_list, df_gen_2, region_name):\n    # #### InputActivityRatio - Power Generation Technologies\n    # Copy OAR table with all columns to IAR\n    df_iar = df_oar.copy()\n\n    df_iar['FUEL'] = 0\n\n    # Deal with GAS techs first...  OCG and CCG\n    # OCG Mode 1: Domestic GAS\n    df_iar.loc[(df_iar['MODE_OF_OPERATION'] == 1) &\n            (df_iar['TECHNOLOGY'].str[3:6].isin(['OCG'])),\n            'FUEL'] = 'GAS'+df_iar['TECHNOLOGY'].str[6:9]\n    # OCG Mode 2: International GAS\n    df_iar.loc[(df_iar['MODE_OF_OPERATION'] == 2) &\n            (df_iar['TECHNOLOGY'].str[3:6].isin(['OCG'])),\n            'FUEL'] = 'GASINT'\n\n    # CCG Mode 1: Domestic GAS\n    df_iar.loc[(df_iar['MODE_OF_OPERATION'] == 1) &\n            (df_iar['TECHNOLOGY'].str[3:6].isin(['CCG'])),\n            'FUEL'] = 'GAS'+df_iar['TECHNOLOGY'].str[6:9]\n\n    # CCG Mode 2: International GAS\n    df_iar.loc[(df_iar['MODE_OF_OPERATION'] == 2) &\n            (df_iar['TECHNOLOGY'].str[3:6].isin(['CCG'])),\n            'FUEL'] = 'GASINT'\n\n    # For non-GAS thermal fuels, domestic fuel input by country in mode 1 and\n    # 'international' fuel input in mode 2\n    df_iar.loc[(df_iar['MODE_OF_OPERATION'] == 1) &\n            (df_iar['TECHNOLOGY'].str[3:6].isin(thermal_fuel_list_iar)),\n            'FUEL'] = df_iar['TECHNOLOGY'].str[3:9]\n\n    df_iar.loc[(df_iar['MODE_OF_OPERATION'] == 2) &\n            (df_iar['TECHNOLOGY'].str[3:6].isin(thermal_fuel_list_iar)),\n            'FUEL'] = df_iar['TECHNOLOGY'].str[3:6] + 'INT'\n\n    # For renewable fuels, input by node in mode 1\n    df_iar.loc[(df_iar['MODE_OF_OPERATION'] == 1) &\n            (df_iar['TECHNOLOGY'].str[3:6].isin(renewables_list)),\n            'FUEL'] = df_iar['TECHNOLOGY'].str[3:11]\n\n    # Remove mode 2 when not used\n    df_iar = df_iar.loc[df_iar['FUEL'] != 0]\n\n    # ### Calculate average InputActivityRatio by node+technology and only by technology\n    df_eff_node, df_eff_tech = average_inputactivityratio_by_node_tech(df_gen_2)\n\n    # Join efficiency columns: one with node and technology average, and the\n    # other with technology average\n    df_iar = df_iar.join(df_eff_node.set_index(['tech_code', 'node_code']),\n                        on=['tech_code', 'node_code'])\n\n    df_iar = df_iar.join(df_eff_tech.set_index('tech_code'),\n                        on='tech_code')\n\n    # When available, choose node and technology average. Else,\n    # choose technology average\n    df_iar['VALUE'] = df_iar['node_average_iar']\n    df_iar.loc[df_iar['VALUE'].isna(),\n            'VALUE'] = df_iar['tech_average_iar']\n\n    # Add 'REGION' column and fill 'GLOBAL' throughout\n    df_iar['REGION'] = region_name\n\n    # Select columns for final output table\n    df_iar_final = df_iar[['REGION',\n                        'TECHNOLOGY',\n                        'FUEL',\n                        'MODE_OF_OPERATION',\n                        'YEAR',\n                        'VALUE',]]\n\n    # Don't write this yet - we'll write both IAR and OAR at the end...\n    # df_iar_final.to_csv(r\"output/InputActivityRatio.csv\", index = None)\n    return df_iar_final\n\n\ndef output_activity_ratios(df_ratios, thermal_fuel_list, region_name):\n    \"\"\"OutputActivityRatio - Power Generation Technologies\n    \"\"\"\n    df_oar = df_ratios.copy()\n    mask = df_oar['TECHNOLOGY'].apply(lambda x: x[3:6] in thermal_fuel_list)\n    df_oar['FUEL'] = 0\n    df_oar['FUEL'][mask] = 1\n    df_oar = df_oar.loc[~((df_oar['MODE_OF_OPERATION'] > 1) &\n                        (df_oar['FUEL'] == 0))]\n    df_oar['FUEL'] = ('ELC' +\n                    df_oar['TECHNOLOGY'].str[6:11] +\n                    '01'\n                    )\n    df_oar['VALUE'] = 1\n\n    # Add 'REGION' column and fill 'GLOBAL' throughout\n    df_oar['REGION'] = region_name\n\n    # Select columns for final output table\n    df_oar_final = df_oar[['REGION',\n                    'TECHNOLOGY',\n                    'FUEL',\n                    'MODE_OF_OPERATION',\n                    'YEAR',\n                    'VALUE',]]\n    return df_oar, df_oar_final\n\n\ndef create_generators(df, df_dict, model_start_year, df_op_life, df_tech_code):\n    df_gen_2 = create_main_generator_table(df)\n    df_dict_2 = compile_powerplants_nodes_fuels(df_dict)\n\n    ## Merge original generator dataframe with nodes and fuels\n    df_gen_2 = pd.merge(df_gen_2, df_dict_2, how=\"outer\", on=\"powerplant\")\n    df_gen_2.rename(\n        {\"child_object_x\": \"fuel\", \"child_object_y\": \"node\"}, axis=1, inplace=True\n    )\n\n    ## Extract start year from Commission Date\n    df_gen_2[\"Commission Date\"] = pd.to_datetime(df_gen_2[\"Commission Date\"])\n    df_gen_2[\"start_year\"] = df_gen_2[\"Commission Date\"].dt.year\n    df_gen_2.drop(\"Commission Date\", axis=1, inplace=True)\n\n    ## Calculate efficiency from heat rate. Units of heat rate in MJ/kWh\n    df_gen_2[\"efficiency\"] = 3.6 / df_gen_2[\"Heat Rate\"].astype(float)\n    df_gen_2.drop(\"Heat Rate\", axis=1, inplace=True)\n\n    ## Calcluate years of operation from start year until 2015\n    df_gen_2[\"years_of_operation\"] = model_start_year - df_gen_2[\"start_year\"]\n\n    ## Fix blank spaces in 'fuels' columns. Appearing for 'Oil' powerplants in certain countries\n    df_gen_2.loc[df_gen_2[\"fuel\"].isna(), \"fuel\"] = (\n        df_gen_2[\"node\"].str.split(\"-\").str[:2].str.join(\"-\")\n        + \" \"\n        + df_gen_2[\"powerplant\"].str.split(\"_\", expand=True)[1]\n    )\n\n    ## Create column for technology\n    df_gen_2[\"technology\"] = df_gen_2[\"powerplant\"].str.split(\"_\").str[1]\n    df_gen_2[\"technology\"] = df_gen_2[\"technology\"].str.title()\n\n    ## Divide Gas into CCGT and OCGT based on max capacity\n    df_gen_2.loc[\n        (df_gen_2[\"technology\"] == \"Gas\") & (df_gen_2[\"Max Capacity\"].astype(float) > 130),\n        \"technology\",\n    ] = \"Gas-CCGT\"\n    df_gen_2.loc[\n        (df_gen_2[\"technology\"] == \"Gas\") & (df_gen_2[\"Max Capacity\"].astype(float) <= 130),\n        \"technology\",\n    ] = \"Gas-OCGT\"\n\n    # Add region and country code columns\n    df_gen_2['region_code'] = df_gen_2['node'].str[:2]\n    df_gen_2['country_code'] = df_gen_2['node'].str[3:]\n\n    # ### Add operational life column\n    op_life_dict = dict(zip(list(df_op_life['tech']),\n                            list(df_op_life['years'])))\n\n    df_gen_2['operational_life'] = df_gen_2['technology'].map(op_life_dict)\n    df_gen_2['retirement_year_data'] = (df_gen_2['operational_life']\n                                        + df_gen_2['start_year'])\n    df_gen_2['retirement_diff'] = ((df_gen_2['years_of_operation']\n                                - df_gen_2['operational_life'])/\n                                df_gen_2['operational_life'])\n\n    ''' Set retirement year based on years of operation.\n    If (years of operation - operational life) is more than 50% of\n    operational life, set retirement year\n    '''\n    df_gen_2.loc[df_gen_2['retirement_diff'] >= 0.5,\n                'retirement_year_model'] = 2025\n    df_gen_2.loc[(df_gen_2['retirement_diff'] < 0.5) &\n                (df_gen_2['retirement_diff'] > 0),\n                'retirement_year_model'] = 2030\n    df_gen_2.loc[df_gen_2['retirement_diff'] <= 0,\n                'retirement_year_model'] = df_gen_2['retirement_year_data']\n\n    # ### Add naming convention\n    tech_code_dict = dict(zip(list(df_tech_code['tech']),\n                            list(df_tech_code['code'])))\n    df_gen_2['tech_code'] = df_gen_2['technology'].map(tech_code_dict)\n\n    df_gen_2.loc[df_gen_2['node'].str.len() <= 6,\n                'node_code'] = (df_gen_2['node'].\n                                str.split('-').\n                                str[1:].\n                                str.join(\"\") +\n                                'XX')\n    df_gen_2.loc[df_gen_2['node'].str.len() > 6,\n                'node_code'] = (df_gen_2['node'].\n                                str.split('-').\n                                str[1:].\n                                str.join(\"\")\n                                )\n\n    df_gen_2 = df_gen_2.loc[~df_gen_2['tech_code'].isna()]\n\n    return df_gen_2\n\n\ndef residual_capacity(df_gen_2, model_start_year, model_end_year, region_name):\n    \"\"\"Calculate residual capacity\"\"\"\n    res_cap_cols = [\n        \"node_code\",\n        \"tech_code\",\n        \"total_capacity\",\n        \"start_year\",\n        \"retirement_year_model\",\n    ]\n\n    df_res_cap = df_gen_2[res_cap_cols]\n\n    for each_year in range(model_start_year, model_end_year+1):\n        df_res_cap[str(each_year)] = 0\n\n    df_res_cap = pd.melt(\n        df_res_cap,\n        id_vars=res_cap_cols,\n        value_vars=[x for x in df_res_cap.columns if x not in res_cap_cols],\n        var_name=\"model_year\",\n        value_name=\"value\",\n    )\n    df_res_cap[\"model_year\"] = df_res_cap[\"model_year\"].astype(int)\n    df_res_cap.loc[\n        (df_res_cap[\"model_year\"] >= df_res_cap[\"start_year\"])\n        & (df_res_cap[\"model_year\"] <= df_res_cap[\"retirement_year_model\"]),\n        \"value\",\n    ] = df_res_cap[\"total_capacity\"]\n\n    df_res_cap = df_res_cap.groupby(\n        [\"node_code\", \"tech_code\", \"model_year\"], as_index=False\n    )[\"value\"].sum()\n\n    # Add column with naming convention\n    df_res_cap['node_code'] = df_res_cap['node_code']\n    df_res_cap['tech'] = ('PWR' +\n                        df_res_cap['tech_code'] +\n                        df_res_cap['node_code'] + '01'\n                        )\n    # Convert total capacity from MW to GW\n    df_res_cap['value'] = df_res_cap['value'].div(1000)\n\n\n    df_res_cap_plot = df_res_cap[['node_code',\n                                'tech_code',\n                                'model_year',\n                                'value']]\n\n    # Rename 'model_year' to 'year' and 'total_capacity' to 'value'\n    df_res_cap.rename({'tech':'TECHNOLOGY',\n                    'model_year':'YEAR',\n                    'value':'VALUE'},\n                    inplace = True,\n                    axis=1)\n    # Drop 'tech_code' and 'node_code'\n    df_res_cap.drop(['tech_code', 'node_code'], inplace = True, axis=1)\n\n    # Add 'REGION' column and fill 'GLOBAL' throughout\n    df_res_cap['REGION'] = region_name\n\n    #Reorder columns\n    df_res_cap = df_res_cap[['REGION', 'TECHNOLOGY', 'YEAR', 'VALUE']]\n    return df_res_cap\n\n\ndef average_inputactivityratio_by_node_tech(df_gen_2):\n    \"\"\"Calculate average InputActivityRatio by node+technology and only by technology\n    \"\"\"\n    df_eff = df_gen_2[['node_code',\n                    'efficiency',\n                    'tech_code']]\n\n    # Average efficiency by node and technology\n    df_eff_node = df_eff.groupby(['tech_code',\n                                'node_code'],\n                                as_index = False).agg('mean')\n\n    df_eff_node['node_average_iar'] = ((1 / df_eff_node['efficiency']).\n                                    round(2))\n\n    df_eff_node.drop('efficiency',\n                    axis = 1,\n                    inplace = True)\n\n    # Average efficiency by technology\n    df_eff_tech = df_eff.groupby('tech_code',\n                                as_index = False).agg('mean')\n\n    df_eff_tech['tech_average_iar'] = ((1 / df_eff_tech['efficiency']).\n                                    round(2))\n\n    df_eff_tech.drop('efficiency',\n                    axis = 1,\n                    inplace = True)\n    return df_eff_node, df_eff_tech\n\n\ndef final_costs(each_cost, df_costs, df_oar_final, weo_regions_dict):\n    df_costs_temp = df_costs.loc[df_costs['parameter'].str.contains(each_cost)]\n    df_costs_temp.drop(['technology', 'parameter'],\n                    axis = 1,\n                    inplace = True)\n    df_costs_final = df_oar_final[['REGION',\n                                'TECHNOLOGY',\n                                'YEAR'\n                                ]]\n    df_costs_final['YEAR'] = df_costs_final['YEAR'].astype(int)\n    df_costs_final = df_costs_final.drop_duplicates()\n    df_costs_final = (df_costs_final\n                    .loc[(df_costs_final['TECHNOLOGY']\n                            .str.startswith('PWR')\n                        ) &\n                        (~df_costs_final['TECHNOLOGY']\n                            .str.contains('TRN')\n                        )\n                        ]\n                    )\n    df_costs_final['technology_code'] = df_costs_final['TECHNOLOGY'].str[3:6]\n    df_costs_final['weo_region'] = df_costs_final['TECHNOLOGY'].str[6:9]\n    df_costs_final['weo_region'] = (df_costs_final['weo_region']\n                                        .replace(weo_regions_dict))\n\n    df_costs_final = pd.merge(df_costs_final,\n                            df_costs_temp,\n                            on = ['technology_code', 'weo_region', 'YEAR'],\n                            how = 'left'\n                            )\n    df_costs_final.drop(['technology_code', 'weo_region'],\n                        axis = 1,\n                        inplace = True)\n    df_costs_final = df_costs_final.fillna(-9)\n    df_costs_final = pd.pivot_table(df_costs_final,\n                                    index = ['REGION', 'YEAR'],\n                                    columns = 'TECHNOLOGY',\n                                    values = 'value').reset_index()\n    df_costs_final = df_costs_final.replace([-9],[np.nan])\n    #df_costs_final.set_index(['REGION', 'YEAR'],\n    #                         inplace = True)\n\n\n    df_costs_final = df_costs_final.interpolate(method = 'linear',\n                                                limit_direction='forward').round(2)\n    df_costs_final = df_costs_final.interpolate(method = 'linear',\n                                                limit_direction='backward').round(2)\n    df_costs_final = pd.melt(df_costs_final,\n                            id_vars = ['REGION', 'YEAR'],\n                            value_vars = [x for x in df_costs_final.columns\n                                        if x not in ['REGION', 'YEAR']\n                                        ],\n                            var_name = 'TECHNOLOGY',\n                            value_name = 'VALUE'\n                            )\n    df_costs_final = df_costs_final[['REGION', 'TECHNOLOGY', 'YEAR', 'VALUE']]\n    df_costs_final = df_costs_final[~df_costs_final['VALUE'].isnull()]\n    return df_costs_final\n\n\ndef create_weo_region_mapping(df_weo_regions):\n    weo_regions_dict = dict([(k, v)\n                            for k, v\n                            in zip(df_weo_regions['technology_code'],\n                                    df_weo_regions['weo_region']\n                                )\n                            ]\n                        )\n    return weo_regions_dict\n\n\ndef capital_fixed_var_costs(df_weo_data):\n    # ### Costs: Capital, fixed, and variable\n\n    df_costs = pd.melt(df_weo_data,\n                    id_vars = ['technology', 'weo_region', 'parameter'],\n                    value_vars = ['2017', '2030', '2040'],\n                    var_name = ['YEAR'])\n    df_costs['parameter'] = df_costs['parameter'].str.split('\\r\\n').str[0]\n    df_costs['value'] = df_costs['value'].replace({'n.a.':0})\n    df_costs['value'] = df_costs['value'].astype(float)\n    df_costs = df_costs.pivot_table(index = ['technology', 'parameter', 'YEAR'],\n                                    columns = 'weo_region',\n                                    values = 'value').reset_index()\n    df_costs['AS_average'] = (df_costs['China'] +\n                                df_costs['India'] +\n                                df_costs['Japan'] +\n                                df_costs['Middle East']).div(4)\n    df_costs['NA_average'] = (df_costs['United States'])\n    df_costs['SA_average'] = (df_costs['Brazil'])\n    df_costs['Global_average'] = (df_costs['Africa'] +\n                                df_costs['Brazil'] +\n                                df_costs['Europe'] +\n                                df_costs['China'] +\n                                df_costs['India'] +\n                                df_costs['Japan'] +\n                                df_costs['Middle East'] +\n                                df_costs['Russia'] +\n                                df_costs['United States']).div(9)\n    df_costs = pd.melt(df_costs,\n                    id_vars = ['technology', 'parameter', 'YEAR'],\n                    value_vars = [x\n                                    for x\n                                    in df_costs.columns\n                                    if x not in ['technology', 'parameter', 'YEAR']\n                                    ]\n                    )\n    df_costs['YEAR'] = df_costs['YEAR'].astype(int)\n    costs_dict = {'Biomass - waste incineration - CHP':'WAS',\n                  'Biomass Power plant':'BIO',\n                  'CCGT':'CCG',\n                  'CCGT - CHP':'COG',\n                  'Concentrating solar power':'CSP',\n                  'Gas turbine':'OCG',\n                  'Geothermal':'GEO',\n                  'Hydropower - large-scale':'HYD',\n                  'Marine':'WAV',\n                  'Nuclear':'URN',\n                  'Solar photovoltaics - Large scale':'SPV',\n                  'Steam Coal - SUBCRITICAL':'COA',\n                  'Steam Coal - SUPERCRITICAL':'COA',\n                  'Steam Coal - ULTRASUPERCRITICAL':'COA',\n                  'Wind onshore':'WON'} # Missing OIL, OTH, PET, WOF\n\n    df_costs = df_costs.loc[df_costs['technology'].isin(costs_dict.keys())]\n    df_costs['technology_code'] = df_costs['technology'].replace(costs_dict)\n    return df_costs\n\n\ndef ratio_master_table(df_gen_2, years):\n    # Create master table for activity ratios\n    node_list = list(df_gen_2['node_code'].unique())\n\n    # Add extra nodes which are not present in 2015 but will be by 2050\n    nodes_extra_list = ['AF-SOM', 'AF-TCD', 'AS-TLS', 'EU-MLT', 'NA-BLZ', 'NA-HTI', 'SA-BRA-J1', 'SA-BRA-J2', 'SA-BRA-J3', 'SA-SUR']\n    for each_node in nodes_extra_list:\n        if len(each_node) <= 6:\n            node_list.append(\"\".join(each_node.split('-')[1:]) + 'XX')\n        else:\n            node_list.append(\"\".join(each_node.split('-')[1:]))\n\n    master_fuel_list = list(df_gen_2['tech_code'].unique())\n\n    df_ratios = pd.DataFrame(list(itertools.product(node_list,\n                                                    master_fuel_list,\n                                                    MODE_LIST,\n                                                    years)\n                                  ),\n                             columns=['node_code', 'tech_code', 'MODE_OF_OPERATION', 'YEAR']\n                             )\n\n    df_ratios['TECHNOLOGY'] = ('PWR' +\n                               df_ratios['tech_code'] +\n                               df_ratios['node_code'] + '01'\n                               )\n    return df_ratios\n\n\ndef get_years(model_start_year, model_end_year):\n    return list(range(model_start_year,\n                       model_end_year + 1))\n\n\ndef main(INPUT_PATH, OUTPUT_PATH, model_start_year=2015, model_end_year=2050, region_name='GLOBAL'):\n    df, df_dict = get_data(INPUT_PATH)\n\n    df_weo_data = pd.read_csv(os.path.join(INPUT_PATH, \"weo_2018_powerplant_costs.csv\"))\n    df_op_life = pd.read_csv(os.path.join(INPUT_PATH, \"operational_life.csv\"))\n    df_tech_code = pd.read_csv(os.path.join(INPUT_PATH, \"naming_convention_tech.csv\"))\n    df_trn_efficiencies = pd.read_excel(os.path.join(INPUT_PATH, \"Costs Line expansion.xlsx\"))\n    df_weo_regions = pd.read_csv(os.path.join(INPUT_PATH, \"weo_region_mapping.csv\"))\n\n    emissions = []\n\n    # Create 'output' directory if it doesn't exist\n    if not os.path.exists(OUTPUT_PATH):\n        os.makedirs(OUTPUT_PATH)\n\n    df_gen_2 = create_generators(df, df_dict, model_start_year, df_op_life, df_tech_code)\n\n    df_res_cap = residual_capacity(df_gen_2, model_start_year, model_end_year, region_name)\n\n    filepath = os.path.join(OUTPUT_PATH, 'ResidualCapacity.csv')\n    df_res_cap.to_csv(filepath, index=None)\n\n    # ### Add input and output activity ratios\n\n\n\n    thermal_fuel_list = ['COA', 'COG', 'OCG', 'CCG', 'PET', 'URN', 'OIL', 'OTH']\n    thermal_fuel_list_iar = ['COA', 'COG', 'PET', 'URN', 'OIL', 'OTH']\n    renewables_list = ['BIO', 'GEO', 'HYD', 'SPV', 'CSP', 'WAS', 'WAV', 'WON', 'WOF']\n\n    # Calculate Input and OutputActivityRatio for: Power Generation\n    df_oar_final, df_iar_final = calculate_activity_ratios(thermal_fuel_list, region_name,\n                                                           thermal_fuel_list_iar, renewables_list,\n                                                           df_gen_2, df, model_start_year,\n                                                           model_end_year, df_trn_efficiencies)\n\n    filepath = os.path.join(OUTPUT_PATH, \"OutputActivityRatio.csv\")\n    df_oar_final.to_csv(filepath, index=None)\n    filepath = os.path.join(OUTPUT_PATH, \"InputActivityRatio.csv\")\n    df_iar_final.to_csv(filepath, index=None)\n\n\n    # ### Costs: Capital, fixed, and variable\n    df_costs = capital_fixed_var_costs(df_weo_data)\n    weo_regions_dict = create_weo_region_mapping(df_weo_regions)\n    capex = final_costs(\"Capital\", df_costs, df_oar_final, weo_regions_dict)\n    capex.to_csv(os.path.join(OUTPUT_PATH, 'CapitalCost.csv'), index=None)\n    fixed = final_costs(\"O&M\", df_costs, df_oar_final, weo_regions_dict)\n    fixed.to_csv(os.path.join(OUTPUT_PATH, 'FixedCost.csv'), index=None)\n\n    # ## Create sets for TECHNOLOGIES, FUELS\n    def create_sets(x: str) -> None:\n        set_elements = list(df_iar_final[x].unique()) + list(df_oar_final[x].unique())\n        set_elements = list(set(set_elements))\n        set_elements.sort()\n        set_elements_df = pd.DataFrame(set_elements, columns=['VALUE'])\n        return set_elements_df.to_csv(os.path.join(OUTPUT_PATH, str(x) + '.csv'),\n                                      index=None\n                                      )\n\n    create_sets('TECHNOLOGY')\n    create_sets('FUEL')\n\n    # ## Create set for YEAR, REGION, MODE_OF_OPERATION\n    years = get_years(model_start_year, model_end_year)\n    years_df = pd.DataFrame(years, columns=['VALUE'])\n    years_df.to_csv(os.path.join(OUTPUT_PATH, 'YEAR.csv'),\n                    index=None)\n\n    mode_list_df = pd.DataFrame(MODE_LIST, columns=['VALUE'])\n    mode_list_df.to_csv(os.path.join(OUTPUT_PATH, 'MODE_OF_OPERATION.csv'),\n                        index=None)\n\n    regions_df = pd.DataFrame(columns=['VALUE'])\n    regions_df.loc[0] = region_name\n    regions_df.to_csv(os.path.join(OUTPUT_PATH, 'REGION.csv'),\n                      index=None)\n\n    # ## Create set for EMISSION\n    emissions_df = pd.DataFrame(emissions, columns=['VALUE'])\n    emissions_df.to_csv(os.path.join(OUTPUT_PATH, 'EMISSION.csv'),\n                        index=None)\n\n\n\nif __name__ == \"__main__\":\n\n    args = sys.argv[1:]\n    if len(args) != 2:\n        print(\"Usage: python OPG_powerplant_data <input_data_path> <output_path>\")\n        exit(1)\n\n    input_path = args[0]\n    output_path = args[1]\n\n    main(input_path, output_path)", "meta": {"hexsha": "2b6089554cc58f31c96f9b84e924a2f525fef962", "size": 36952, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/osemosys_global/OPG_powerplant_data.py", "max_stars_repo_name": "ClimateCompatibleGrowth/osemosys_global", "max_stars_repo_head_hexsha": "a7ac030c21aec75e39aa3cba5cb2b92860fd6ab5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/osemosys_global/OPG_powerplant_data.py", "max_issues_repo_name": "ClimateCompatibleGrowth/osemosys_global", "max_issues_repo_head_hexsha": "a7ac030c21aec75e39aa3cba5cb2b92860fd6ab5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/osemosys_global/OPG_powerplant_data.py", "max_forks_repo_name": "ClimateCompatibleGrowth/osemosys_global", "max_forks_repo_head_hexsha": "a7ac030c21aec75e39aa3cba5cb2b92860fd6ab5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3796192609, "max_line_length": 173, "alphanum_fraction": 0.5999134012, "include": true, "reason": "import numpy", "num_tokens": 9715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.1904511970727748}}
{"text": "# Copyright (c) Stanford University, The Regents of the University of\n#               California, and others.\n#\n# All Rights Reserved.\n#\n# See Copyright-SimVascular.txt for additional details.\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject\n# to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n# IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n# OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\nimport os\nfrom sv_ml.base.model import AbstractModel\nimport numpy as np\nimport tensorflow as tf\nimport sv_ml.modules.layers as tf_util\n\n# import matplotlib\n# matplotlib.use('Agg')\n# import matplotlib.pyplot as plt\n\nimport sv_ml.modules.vessel_regression as vr\n\ndef get_batch(X,Y, batch_size=16):\n    ids = np.random.choice(X.shape[0], size=batch_size)\n\n    x   = np.array([X[i] for i in ids])\n    y   = np.array([Y[i] for i in ids])\n\n    return x,y\n\nclass Model(AbstractModel):\n    def setup(self):\n        self.start_iter = 0\n        self.build_model()\n        self.configure_trainer()\n        self.finalize()\n\n        self.losses = []\n        self.iters = []\n\n    def train_step(self,x,y):\n        self.global_step = self.global_step+1\n\n        if np.sum(np.isnan(x)) > 0: return\n        if np.sum(np.isnan(y)) > 0: return\n\n        self.sess.run(self.train_op,{self.x:x,self.y:y})\n\n    def save(self, model_path=None):\n        if model_path == None:\n            model_path = os.path.join(self.config['MODEL_DIR'], self.config['MODEL_NAME'])\n        else:\n            model_path = os.path.join(model_path, self.config['MODEL_NAME'])\n        self.saver.save(self.sess,model_path)\n\n    def load(self, model_path=None):\n        if model_path == None:\n            model_path = os.path.join(self.config['MODEL_DIR'],self.config['MODEL_NAME'])\n        else:\n            model_path = os.path.join(model_path,self.config['MODEL_NAME'])\n        self.saver.restore(self.sess, model_path)\n\n    def predict(self,x):\n        S = list(x.shape)\n        if len(S) == 3:\n            x_ = x.reshape([1]+S)\n            return self._predict(x_)[0]\n        else:\n            out = []\n            for i in range(S[0]):\n                x_ = x[i].reshape([1]+S[1:4])\n                y = self._predict(x_)[0].copy()\n                out.append(y)\n            return np.array(out)\n\n    def calculate_loss(self,x,y):\n        return self.sess.run(self.loss,{self.x:x,self.y:y})\n\n    def build_model(self):\n        raise RuntimeError(\"Abstract not implemented\")\n\n    def build_loss(self):\n        self.loss = tf.reduce_mean(tf.square(self.y-self.yhat))\n\n    def configure_trainer(self):\n        LEARNING_RATE = self.config[\"LEARNING_RATE\"]\n        self.global_step = tf.Variable(0, trainable=False)\n        boundaries = [2000,\n                      5000,\n                      10000,\n                      15000,\n                      150000]\n\n        values = [LEARNING_RATE,\n                  LEARNING_RATE/3,\n                  LEARNING_RATE/10,\n                  LEARNING_RATE/100,\n                  LEARNING_RATE/1000,\n                  LEARNING_RATE/10000,]\n\n        learning_rate = tf.train.piecewise_constant(self.global_step, boundaries, values)\n\n\n        self.opt = tf.train.AdamOptimizer(learning_rate)\n\n        #self.opt = tf.train.MomentumOptimizer(learning_rate, momentum=0.9)\n        self.train_op = self.opt.minimize(self.loss)\n\n    def train(self, X,Y):\n        for i in range(self.start_iter,\n            self.config['TRAIN_STEPS']+self.start_iter):\n            x,y = get_batch(X,Y, self.config['BATCH_SIZE'])\n\n\n\n            self.train_step(x,y)\n\n            if i % self.config['LOG_STEP'] == 0:\n                l = self.calculate_loss(x,y)\n                self.losses.append(l)\n                self.iters.append(i)\n\n                self.log(i,x,y)\n                self.log(i,X[:4],Y[:4])\n                self.save()\n\n    def _predict(self,x):\n        return self.sess.run(self.yhat,{self.x:x})\n\n    def finalize(self):\n        self.sess = tf.Session()\n        self.sess.run(tf.global_variables_initializer())\n\n    def log(self,i,x,y):\n        pass\n        # f = open(self.config['ITER_FILE'], 'w')\n        # f.write(str(i))\n        # f.close()\n        #\n        # l = self.calculate_loss(x,y)\n        # yhat = self.predict(x)[0]\n        #\n        # print(\"{}: loss={}\\n\".format(i,l))\n        # print(\"yhat = {}\".format(yhat))\n        #\n        # f = open(self.config[\"LOG_FILE\"],\"a+\")\n        # f.write(\"{}: loss={}\\n\".format(i,l))\n        # f.write(\"{}: yhat={}\\n\".format(i,yhat))\n        # f.close()\n        #\n        # self.save()\n        #\n        # x_ = x[0,:,:,0]\n        # y_ = y[0]\n        # if self.config['DATASET'] == 'axial2d_point':\n        #     ctrue = vr.point_pred_to_contour(y_)\n        #     cpred = vr.point_pred_to_contour(yhat)\n        #\n        # else:\n        #     ctrue = vr.pred_to_contour(y_)\n        #     cpred = vr.pred_to_contour(yhat)\n        #\n        # plt.figure()\n        # plt.imshow(x_,cmap='gray',extent=[-1, 1, 1, -1])\n        # plt.colorbar()\n        # plt.scatter(cpred[:,0], cpred[:,1], color='r', label='predicted',s=4)\n        # plt.scatter(ctrue[:,0], ctrue[:,1], color='y', label='true', s=4)\n        # plt.show()\n        # plt.close()\n        #\n        # W = x_.shape[0]\n        # s = int(0.25*W)\n        # e = int(0.75*W)\n        #\n        # plt.figure()\n        # plt.imshow(x_[s:e,s:e],cmap='gray',extent=[-0.5, 0.5, 0.5, -0.5])\n        # plt.colorbar()\n        # plt.scatter(cpred[:,0], cpred[:,1], color='r', label='predicted',s=4)\n        # plt.scatter(ctrue[:,0], ctrue[:,1], color='y', label='true', s=4)\n        # plt.show()\n        # plt.close()\n        #\n        #\n        # c = self.config\n        # log_dir = c['RESULTS_DIR']+'/'+c['NAME']+'/log/'\n        #\n        # plt.figure()\n        # plt.plot(self.iters, self.losses)\n        # plt.savefig(log_dir+'loss.png',dpi=300)\n        # plt.close()\n        #\n        # plt.figure()\n        # plt.plot(self.iters, self.losses)\n        # plt.ylim(0,1)\n        # plt.savefig(log_dir+'loss_1.png',dpi=300)\n        # plt.close()\n        #\n        # plt.figure()\n        # plt.plot(self.iters, self.losses)\n        # plt.ylim(0,0.1)\n        # plt.savefig(log_dir+'loss_2.png',dpi=300)\n        # plt.close()\n        #\n        # plt.figure()\n        # plt.plot(self.iters, self.losses)\n        # plt.ylim(0,0.01)\n        # plt.savefig(log_dir+'loss_3.png',dpi=300)\n        # plt.close()\n\nclass FcNet(Model):\n    def build_model(self):\n        CROP_DIMS   = self.config['CROP_DIMS']\n        LEAK        = self.config['LEAK']\n        C           = self.config['NUM_CHANNELS']\n        LAMBDA      = self.config['L2_REG']\n        INIT        = self.config['INIT']\n        NUM_POINTS  = self.config['NUM_CONTOUR_POINTS']\n\n        leaky_relu = tf.contrib.keras.layers.LeakyReLU(LEAK)\n\n        self.x = tf.placeholder(shape=[None,CROP_DIMS,CROP_DIMS,C],dtype=tf.float32)\n        self.y = tf.placeholder(shape=[None,NUM_POINTS],dtype=tf.float32)\n\n        o = self.x\n        if \"INPUT_POOL\" in self.config:\n            d = self.config['INPUT_POOL']\n\n            o = tf.nn.pool(o, [d,d], \"MAX\", \"VALID\", strides=[d,d])\n\n        s = o.get_shape().as_list()\n\n        o_vec = tf.reshape(o,shape=[-1,s[1]*s[2]*s[3]])\n\n        for i,h in enumerate(self.config['HIDDEN_SIZES']):\n\n            o_vec = tf_util.fullyConnected(o_vec, h,\n                leaky_relu, std=INIT, scope='fc_'+str(i))\n\n            if \"DROPOUT\" in self.config:\n                o_vec = tf.nn.dropout(o_vec, self.config['DROPOUT'])\n\n        self.yhat = tf_util.fullyConnected(o_vec, NUM_POINTS,\n            tf.sigmoid, std=INIT, scope='fc_final')\n\n        self.build_loss()\n\n        self.saver = tf.train.Saver()\n\nclass I2INetReg(Model):\n    def build_model(self):\n        CROP_DIMS   = self.config['CROP_DIMS']\n        C           = self.config['NUM_CHANNELS']\n        LEAK        = self.config['LEAK']\n        NUM_FILTERS = self.config['NUM_FILTERS']\n        LAMBDA      = self.config['L2_REG']\n        INIT        = self.config['INIT']\n        NUM_POINTS  = self.config['NUM_CONTOUR_POINTS']\n\n        leaky_relu = tf.contrib.keras.layers.LeakyReLU(LEAK)\n\n        self.x = tf.placeholder(shape=[None,CROP_DIMS,CROP_DIMS,C],dtype=tf.float32)\n        self.y = tf.placeholder(shape=[None,NUM_POINTS],dtype=tf.float32)\n\n        self.yclass,self.yhat,_,_ = tf_util.I2INet(self.x,nfilters=NUM_FILTERS,\n            activation=leaky_relu,init=INIT)\n\n        o = leaky_relu(self.yhat)\n\n        s = o.get_shape().as_list()\n\n        o_vec = tf.reshape(o,shape=[-1,s[1]*s[2]*s[3]])\n\n        for i in range(self.config['FC_LAYERS']-1):\n            if \"HIDDEN_SIZES\" in self.config:\n                h = self.config['HIDDEN_SIZES'][i]\n            else:\n                h = self.config['HIDDEN_SIZE']\n\n            o_vec = tf_util.fullyConnected(o_vec, h,\n                leaky_relu, std=INIT, scope='fc_'+str(i))\n\n        self.yhat = tf_util.fullyConnected(o_vec, NUM_POINTS,\n            tf.identity, std=INIT, scope='fc_final')\n\n        self.build_loss()\n\n        self.saver = tf.train.Saver()\n\nclass ResNetReg(Model):\n    def build_model(self):\n        CROP_DIMS   = self.config['CROP_DIMS']\n        C           = self.config['NUM_CHANNELS']\n        LEAK        = self.config['LEAK']\n        LAMBDA      = self.config['L2_REG']\n        INIT        = self.config['INIT']\n\n        NLAYERS     = int(self.config['NLAYERS']/2)\n        NFILTERS_SMALL = self.config['NFILTERS_SMALL']\n        NFILTERS_LARGE = self.config['NFILTERS_LARGE']\n\n        NUM_POINTS  = self.config['NUM_CONTOUR_POINTS']\n\n        leaky_relu = tf.contrib.keras.layers.LeakyReLU(LEAK)\n\n        self.x = tf.placeholder(shape=[None,CROP_DIMS,CROP_DIMS,C],dtype=tf.float32)\n        self.y = tf.placeholder(shape=[None,NUM_POINTS],dtype=tf.float32)\n\n        self.yclass,self.yhat,_,_ = tf_util.resNet(self.x,\n            nlayers_before=NLAYERS, nlayers_after=NLAYERS,\n            nfilters=NFILTERS_SMALL, nfilters_large=NFILTERS_LARGE,\n            output_filters=NFILTERS_LARGE, activation=leaky_relu, init=INIT)\n\n        o = leaky_relu(self.yhat)\n\n        d = self.config['POOL']\n\n        o = tf.nn.pool(o, [d,d], \"MAX\", \"VALID\", strides=[d,d])\n\n        s = o.get_shape().as_list()\n\n        o_vec = tf.reshape(o,shape=[-1,s[1]*s[2]*s[3]])\n\n        for i in range(self.config['FC_LAYERS']):\n            if \"HIDDEN_SIZES\" in self.config:\n                h = self.config['HIDDEN_SIZES'][i]\n            else:\n                h = self.config['HIDDEN_SIZE']\n\n            o_vec = tf_util.fullyConnected(o_vec, h,\n                leaky_relu, std=INIT, scope='fc_'+str(i))\n\n        self.yhat = tf_util.fullyConnected(o_vec, NUM_POINTS,\n            tf.sigmoid, std=INIT, scope='fc_final')\n\n        self.build_loss()\n\n        self.saver = tf.train.Saver()\n\nclass ResNetRegMultiscale(Model):\n    def build_model(self):\n        CROP_DIMS   = self.config['CROP_DIMS']\n        C           = self.config['NUM_CHANNELS']\n        LEAK        = self.config['LEAK']\n        LAMBDA      = self.config['L2_REG']\n        INIT        = self.config['INIT']\n\n        NLAYERS     = int(self.config['NLAYERS']/2)\n        NFILTERS_SMALL = self.config['NFILTERS_SMALL']\n        NFILTERS_LARGE = self.config['NFILTERS_LARGE']\n\n        NUM_POINTS  = self.config['NUM_CONTOUR_POINTS']\n\n        leaky_relu = tf.contrib.keras.layers.LeakyReLU(LEAK)\n\n        self.x = tf.placeholder(shape=[None,CROP_DIMS,CROP_DIMS,C],dtype=tf.float32)\n\n        if self.config['MULTI_TYPE'] == \"POOL\":\n            self.x_1 = tf.nn.pool(self.x, [2,2], \"MAX\", \"VALID\", strides=[2,2])\n            self.x_2 = tf.nn.pool(self.x_1, [2,2], \"MAX\", \"VALID\", strides=[2,2])\n        elif self.config['MULTI_TYPE'] == \"CROP\":\n            self.x_1 = tf.image.central_crop(self.x, central_fraction=0.5)\n            self.x_2 = tf.image.central_crop(self.x_1, central_fraction=0.5)\n        else:\n            raise RuntimeError(\"Unrecognized multi type\")\n\n        self.y = tf.placeholder(shape=[None,NUM_POINTS],dtype=tf.float32)\n\n        self.yclass,self.yhat,_,_ = tf_util.resNet(self.x,\n            nlayers_before=NLAYERS, nlayers_after=NLAYERS,\n            nfilters=NFILTERS_SMALL, nfilters_large=NFILTERS_LARGE,\n            output_filters=NFILTERS_LARGE, activation=leaky_relu, init=INIT)\n\n        self.yclass_1,self.yhat_1,_,_ = tf_util.resNet(self.x_1,\n            nlayers_before=NLAYERS, nlayers_after=NLAYERS,\n            nfilters=NFILTERS_SMALL, nfilters_large=NFILTERS_LARGE,\n            output_filters=NFILTERS_LARGE, activation=leaky_relu, init=INIT,\n            scope=\"resnet_1\")\n\n        self.yclass_2,self.yhat_2,_,_ = tf_util.resNet(self.x_2,\n            nlayers_before=NLAYERS, nlayers_after=NLAYERS,\n            nfilters=NFILTERS_SMALL, nfilters_large=NFILTERS_LARGE,\n            output_filters=NFILTERS_LARGE, activation=leaky_relu, init=INIT,\n            scope=\"resnet_2\")\n\n\n        o   = leaky_relu(self.yhat)\n        o_1 = leaky_relu(self.yhat_1)\n        o_2 = leaky_relu(self.yhat_2)\n\n        s   = o.get_shape().as_list()\n        s_1 = o_1.get_shape().as_list()\n        s_2 = o_2.get_shape().as_list()\n\n        o_vec   = tf.reshape(o,shape=[-1,s[1]*s[2]*s[3]])\n        o_vec_1 = tf.reshape(o_1,shape=[-1,s_1[1]*s_1[2]*s_1[3]])\n        o_vec_2 = tf.reshape(o_2,shape=[-1,s_2[1]*s_2[2]*s_2[3]])\n\n        o = tf.concat([o_vec, o_vec_1, o_vec_2], axis=1)\n\n        print(o)\n\n        for i in range(self.config['FC_LAYERS']-1):\n            if \"HIDDEN_SIZES\" in self.config:\n                h = self.config['HIDDEN_SIZES'][i]\n            else:\n                h = self.config['HIDDEN_SIZE']\n\n            o = tf_util.fullyConnected(o, h,\n                leaky_relu, std=INIT, scope='fc_'+str(i))\n\n        self.yhat = tf_util.fullyConnected(o, NUM_POINTS,\n            tf.identity, std=INIT, scope='fc_final')\n\n        self.build_loss()\n\n        self.saver = tf.train.Saver()\n\nclass ConvNet(Model):\n    def build_model(self):\n        CROP_DIMS   = self.config['CROP_DIMS']\n        C           = self.config['NUM_CHANNELS']\n        LEAK        = self.config['LEAK']\n        LAMBDA      = self.config['L2_REG']\n        INIT        = self.config['INIT']\n\n        NLAYERS     = self.config['NLAYERS']\n        NFILTERS    = self.config['NFILTERS']\n\n        NUM_POINTS  = self.config['NUM_CONTOUR_POINTS']\n        DIMS = [self.config['CONV_DIMS']]*2\n\n        leaky_relu = tf.contrib.keras.layers.LeakyReLU(LEAK)\n\n        self.x = tf.placeholder(shape=[None,CROP_DIMS,CROP_DIMS,C],dtype=tf.float32)\n        self.y = tf.placeholder(shape=[None,NUM_POINTS],dtype=tf.float32)\n\n        o = self.x\n\n        if \"INPUT_POOL\" in self.config:\n            d = self.config['INPUT_POOL']\n\n            o = tf.nn.pool(o, [d,d], \"MAX\", \"VALID\", strides=[d,d])\n\n\n        for i in range(NLAYERS):\n            o = tf_util.conv2D(o,dims=DIMS,nfilters=NFILTERS,\n                               init=INIT,\n                          activation=leaky_relu,scope=\"conv_{}\".format(i))\n\n        s   = o.get_shape().as_list()\n        o = tf.reshape(o,shape=[-1,s[1]*s[2]*s[3]])\n\n        for i in range(self.config['FC_LAYERS']):\n            if \"HIDDEN_SIZES\" in self.config:\n                h = self.config['HIDDEN_SIZES'][i]\n            else:\n                h = self.config['HIDDEN_SIZE']\n\n            o = tf_util.fullyConnected(o, h,\n                leaky_relu, std=INIT, scope='fc_'+str(i))\n            print(o)\n\n            if \"DROPOUT\" in self.config:\n                o = tf.nn.dropout(o, self.config['DROPOUT'])\n\n\n        self.yhat = tf_util.fullyConnected(o, NUM_POINTS,\n            tf.sigmoid, std=INIT, scope='fc_final')\n\n        self.build_loss()\n\n        self.saver = tf.train.Saver()\n\nclass ConvNetMulti(Model):\n    def build_model(self):\n        CROP_DIMS   = self.config['CROP_DIMS']\n        C           = self.config['NUM_CHANNELS']\n        LEAK        = self.config['LEAK']\n        LAMBDA      = self.config['L2_REG']\n        INIT        = self.config['INIT']\n\n        NLAYERS     = int(self.config['NLAYERS']/2)\n        NFILTERS    = self.config['NFILTERS']\n\n        NUM_POINTS  = self.config['NUM_CONTOUR_POINTS']\n        DIMS = [self.config['CONV_DIMS']]*2\n\n        leaky_relu = tf.contrib.keras.layers.LeakyReLU(LEAK)\n\n        self.x = tf.placeholder(shape=[None,CROP_DIMS,CROP_DIMS,C],dtype=tf.float32)\n        self.y = tf.placeholder(shape=[None,NUM_POINTS],dtype=tf.float32)\n\n        self.x_1 = tf.nn.pool(self.x, [2,2], \"MAX\", \"VALID\", strides=[2,2])\n        self.x_2 = tf.nn.pool(self.x_1, [2,2], \"MAX\", \"VALID\", strides=[2,2])\n\n        o = self.x\n\n        for i in range(NLAYERS):\n            o = tf_util.conv2D(o,dims=DIMS, nfilters=NFILTERS,init=INIT,activation=leaky_relu,\n                scope=\"conv_{}\".format(i))\n\n        o_1 = self.x_1\n\n        for i in range(NLAYERS):\n            o_1 = tf_util.conv2D(o_1,dims=DIMS, nfilters=NFILTERS,init=INIT,activation=leaky_relu, scope=\"conv_1_{}\".format(i))\n\n        o_2 = self.x_2\n\n        for i in range(NLAYERS):\n            o_2 = tf_util.conv2D(o_2,dims=DIMS, nfilters=NFILTERS,init=INIT,activation=leaky_relu, scope=\"conv_2_{}\".format(i))\n\n\n        s = o.get_shape().as_list()\n        s_1 = o_1.get_shape().as_list()\n        s_2 = o_2.get_shape().as_list()\n\n        o_vec   = tf.reshape(o,shape=[-1,s[1]*s[2]*s[3]])\n        o_vec_1 = tf.reshape(o_1,shape=[-1,s_1[1]*s_1[2]*s_1[3]])\n        o_vec_2 = tf.reshape(o_2,shape=[-1,s_2[1]*s_2[2]*s_2[3]])\n\n        o = tf.concat([o_vec, o_vec_1, o_vec_2], axis=1)\n\n        for i in range(self.config['FC_LAYERS']-1):\n            if \"HIDDEN_SIZES\" in self.config:\n                h = self.config['HIDDEN_SIZES'][i]\n            else:\n                h = self.config['HIDDEN_SIZE']\n\n            o = tf_util.fullyConnected(o, h,\n                leaky_relu, std=INIT, scope='fc_'+str(i))\n\n        self.yhat = tf_util.fullyConnected(o, NUM_POINTS,\n            tf.identity, std=INIT, scope='fc_final')\n\n        self.build_loss()\n\n        self.saver = tf.train.Saver()\n\nclass GoogleNet(Model):\n    def build_model(self):\n        CROP_DIMS   = self.config['CROP_DIMS']\n        C           = self.config['NUM_CHANNELS']\n        LEAK        = self.config['LEAK']\n        LAMBDA      = self.config['L2_REG']\n        INIT        = self.config['INIT']\n        DROPOUT     = self.config['DROPOUT']\n        NUM_POINTS  = self.config['NUM_CONTOUR_POINTS']\n\n        leaky_relu = tf.contrib.keras.layers.LeakyReLU(LEAK)\n\n        self.x = tf.placeholder(shape=[None,CROP_DIMS,CROP_DIMS,C],dtype=tf.float32)\n        self.y = tf.placeholder(shape=[None,NUM_POINTS],dtype=tf.float32)\n\n        o,o_side = tf_util.GoogleNet(self.x, activation=leaky_relu, init=INIT,\n            scope='googlenet', output_size=NUM_POINTS, dropout=DROPOUT)\n\n        print(o)\n        print(o_side)\n\n        self.yhat = tf.nn.sigmoid(o)\n        self.yhat_side = tf.nn.sigmoid(o_side)\n\n        self.build_loss()\n\n        self.saver = tf.train.Saver()\n\n        self.dropout_mask_op = op = tf.get_default_graph().get_tensor_by_name(\n            \"googlenet/dropout_1/random_uniform:0\")\n\n        self.dropout_mask = None\n        self.dropout_fixed = False\n\n    def build_loss(self):\n        self.loss = tf.reduce_mean(tf.square(self.y-self.yhat))\n        self.loss += 0.3*tf.reduce_mean(tf.square(self.y-self.yhat_side))\n\n    def sample(self):\n        self.dropout_mask = (np.random.uniform(size=(1,9216))<=0.6).astype(int)\n        self.dropout_fixed = True\n\n    def _predict(self,x):\n        if not self.dropout_fixed:\n            return self.sess.run(self.yhat,{self.x:x})\n        else:\n            return self.sess.run(self.yhat,{self.x:x,\n                self.dropout_mask_op:self.dropout_mask})\n", "meta": {"hexsha": "bddecdc24d5dda914e8f1e564a28e56753843320", "size": 20733, "ext": "py", "lang": "Python", "max_stars_repo_path": "SimVascular-master/Python/site-packages/sv_ml/components/models/nn.py", "max_stars_repo_name": "mccsssk2/SimVascularPM3_March2020", "max_stars_repo_head_hexsha": "3cce6cc7be66545bea5dc3915a2db50a3892bf04", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SimVascular-master/Python/site-packages/sv_ml/components/models/nn.py", "max_issues_repo_name": "mccsssk2/SimVascularPM3_March2020", "max_issues_repo_head_hexsha": "3cce6cc7be66545bea5dc3915a2db50a3892bf04", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SimVascular-master/Python/site-packages/sv_ml/components/models/nn.py", "max_forks_repo_name": "mccsssk2/SimVascularPM3_March2020", "max_forks_repo_head_hexsha": "3cce6cc7be66545bea5dc3915a2db50a3892bf04", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1565074135, "max_line_length": 127, "alphanum_fraction": 0.5780157237, "include": true, "reason": "import numpy", "num_tokens": 5536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.1904511844281577}}
{"text": "# -*- coding: utf-8 -*-\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n#\n# Copyright (C) 2014-2018 GEM Foundation\n#\n# OpenQuake is free software: you can redistribute it and/or modify it\n# under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# OpenQuake is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"\nModule exports :class:`YuEtAl2013`, :class:`YuEtAl2013Tibet`,\n:class:`YuEtAl2013Eastern`, :class:`YuEtAl2013Stable`\n\n\"\"\"\nimport numpy as np\nfrom scipy.constants import g\n\nfrom openquake.hazardlib.gsim.base import GMPE, CoeffsTable\nfrom openquake.hazardlib import const\nfrom openquake.hazardlib.imt import PGA, PGV, SA\n\n\ndef gc(coeff, mag):\n    \"\"\"\n    Returns the set of coefficients to be used for the calculation of GM\n    as a function of earthquake magnitude\n\n    :param coeff:\n        A dictionary of parameters for the selected IMT\n    :param mag:\n        Magnitude value\n    :returns:\n        The set of coefficients\n    \"\"\"\n    if mag > 6.5:\n        a1ca = coeff['ua']\n        a1cb = coeff['ub']\n        a1cc = coeff['uc']\n        a1cd = coeff['ud']\n        a1ce = coeff['ue']\n        a2ca = coeff['ia']\n        a2cb = coeff['ib']\n        a2cc = coeff['ic']\n        a2cd = coeff['id']\n        a2ce = coeff['ie']\n    else:\n        a1ca = coeff['a']\n        a1cb = coeff['b']\n        a1cc = coeff['c']\n        a1cd = coeff['d']\n        a1ce = coeff['e']\n        a2ca = coeff['ma']\n        a2cb = coeff['mb']\n        a2cc = coeff['mc']\n        a2cd = coeff['md']\n        a2ce = coeff['me']\n    return a1ca, a1cb, a1cc, a1cd, a1ce, a2ca, a2cb, a2cc, a2cd, a2ce\n\n\ndef rbf(ra, coeff, mag):\n    \"\"\"\n    Calculate the median ground motion for a given magnitude and distance\n\n    :param ra:\n        Distance value [km]\n    :param coeff:\n        The set of coefficients\n    :param mag:\n        Magnitude value\n    :returns:\n\n    \"\"\"\n    a1ca, a1cb, a1cc, a1cd, a1ce, a2ca, a2cb, a2cc, a2cd, a2ce = gc(coeff, mag)\n    term1 = a1ca + a1cb * mag + a1cc * np.log(ra + a1cd*np.exp(a1ce*mag))\n    term2 = a2ca + a2cb * mag\n    term3 = a2cd*np.exp(a2ce*mag)\n    return np.exp((term1 - term2) / a2cc) - term3\n\n\ndef fnc(ra, *args):\n    \"\"\"\n    Function used in the minimisation problem.\n\n    :param ra:\n        Semi-axis of the ellipses used in the Yu et al.\n    :returns:\n        The absolute difference between the epicentral distance and the\n        adjusted distance\n    \"\"\"\n    #\n    # epicentral distance\n    repi = args[0]\n    #\n    # azimuth\n    theta = args[1]\n    #\n    # magnitude\n    mag = args[2]\n    #\n    # coefficients\n    coeff = args[3]\n    #\n    # compute the difference between epicentral distances\n    rb = rbf(ra, coeff, mag)\n    t1 = ra**2 * (np.sin(np.radians(theta)))**2\n    t2 = rb**2 * (np.cos(np.radians(theta)))**2\n    xx = ra * rb / (t1+t2)**0.5\n    return xx-repi\n\n\ndef get_ras(repi, theta, mag, coeff):\n    \"\"\"\n    Computes equivalent distance\n\n    :param repi:\n        Epicentral distance\n    :param theta:\n        Azimuth value\n    :param mag:\n        Magnitude\n    :param coeff:\n        GMPE coefficients\n    \"\"\"\n    rx = 150.\n    ras = 300.\n    dff = 1.e0\n    while abs(dff) > 1e-5:\n        #\n        # calculate the difference between epicentral distances\n        dff = fnc(ras, repi, theta, mag, coeff)\n        #\n        # update the value of distance computed\n        ras -= np.sign(dff) * rx\n        rx = rx / 2.\n        if rx < 1e-3:\n            break\n    return ras\n\n\nclass YuEtAl2013Ms(GMPE):\n    \"\"\"\n    Implements the Yu et al. (2013) GMPE used for the calculation of the 2015\n    version of the national seismic hazard maps for China. Note that magnitude\n    supported is Ms.\n    \"\"\"\n\n    #: Supported tectonic region type is active shallow crust\n    DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.ACTIVE_SHALLOW_CRUST\n\n    #: Supported intensity measure types are peak ground velocity and\n    #: peak ground acceleration\n    DEFINED_FOR_INTENSITY_MEASURE_TYPES = set([\n        PGA,\n        PGV,\n        SA\n    ])\n\n    #: Supported intensity measure component is geometric mean (supposed)\n    DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = const.IMC.AVERAGE_HORIZONTAL\n\n    #: Supported standard deviation types is total\n    DEFINED_FOR_STANDARD_DEVIATION_TYPES = set([\n        const.StdDev.TOTAL\n    ])\n\n    #: No site parameters required\n    REQUIRES_SITES_PARAMETERS = set(())\n\n    #: Required rupture parameter is magnitude\n    REQUIRES_RUPTURE_PARAMETERS = set(('mag',))\n\n    #: Required distance measures are epicentral distance and azimuth\n    REQUIRES_DISTANCES = set(('repi', 'azimuth'))\n\n    def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):\n        \"\"\"\n        See :meth:`superclass method\n        <.base.GroundShakingIntensityModel.get_mean_and_stddevs>`\n        for spec of input and result values.\n        \"\"\"\n        # Check that the requested standard deviation type is available\n        assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES\n                    for stddev_type in stddev_types)\n        #\n        # Set parameters\n        mag = rup.mag\n        epi = dists.repi\n        theta = dists.azimuth\n        #\n        # Set coefficients\n        coeff = self.COEFFS[imt]\n        a1ca, a1cb, a1cc, a1cd, a1ce, a2ca, a2cb, a2cc, a2cd, a2ce = \\\n            gc(coeff, mag)\n        #\n        # Get correction coefficients. Here for each site we find the\n        # the geometry of the ellipses\n        ras = []\n        for epi, theta in zip(dists.repi, dists.azimuth):\n            res = get_ras(epi, theta, mag, coeff)\n            ras.append(res)\n        ras = np.array(ras)\n        rbs = rbf(ras, coeff, mag)\n        #\n        # Compute values of ground motion for the two cases. The value of\n        # 225 is hardcoded under the assumption that the hypocentral depth\n        # corresponds to 15 km (i.e. 15**2)\n        mean1 = (a1ca + a1cb * mag +\n                    a1cc * np.log((ras**2+225)**0.5 +\n                                a1cd * np.exp(a1ce * mag)))\n        mean2 = (a2ca + a2cb * mag +\n                    a2cc * np.log((rbs**2+225)**0.5 +\n                                a2cd * np.exp(a2ce * mag)))\n        #\n        # Get distances\n        x = (mean1 * np.sin(np.radians(dists.azimuth)))**2\n        y = (mean2 * np.cos(np.radians(dists.azimuth)))**2\n        mean = mean1 * mean2 / np.sqrt(x+y)\n        if isinstance(imt, (PGA)):\n            mean = np.exp(mean)/g/100\n        elif isinstance(imt, (PGV)):\n            mean = np.exp(mean)\n        else:\n            raise ValueError('Unsupported IMT')\n        #\n        # Get the standard deviation\n        stddevs = self._compute_std(coeff, stddev_types, len(dists.repi))\n        #\n        # Return results\n        return np.log(mean), stddevs\n\n    def _compute_std(self, C, stddev_types, num_sites):\n        return [np.ones(num_sites)*C['sigma']]\n\n    #: Coefficient table\n    COEFFS = CoeffsTable(sa_damping=5, table=\"\"\"\\\nIMT a b c d e ua ub uc ud ue ma mb mc md me ia ib ic id ie sigma\nPGA 4.1193 1.656 -2.389 1.772 0.424 7.8269 1.0856 -2.389 1.772 0.424 2.2609 1.6399 -2.118 0.825 0.465 6.003 1.0649 -2.118 0.825 0.465 0.5428\nPGV -1.2581 1.932 -2.181 1.772 0.424 3.013 1.2742 -2.181 1.772 0.424 -3.1073 1.9389 -1.945 0.825 0.465 1.3087 1.2627 -1.945 0.825 0.465 0.6233\n        \"\"\")\n\n\nclass YuEtAl2013MsTibet(YuEtAl2013Ms):\n    #: Supported tectonic region type is Tibetan plateau\n    DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.ACTIVE_SHALLOW_CRUST\n    #: Coefficient table\n    COEFFS = CoeffsTable(sa_damping=5, table=\"\"\"\\\nIMT a b c d e ua ub uc ud ue ma mb mc md me ia ib ic id ie sigma\nPGA 5.4901 1.4835 -2.416 2.647 0.366 8.7561 0.9453 -2.416 2.647 0.366 2.3069 1.4007 -1.854 0.612 0.457 5.6511 0.8924 -1.854 0.612 0.457 0.5428\nPGV -0.1472 1.7618 -2.205 2.647 0.366 3.9422 1.1293 -2.205 2.647 0.366 -2.9923 1.7043 -1.696 0.612 0.457 1.0189 1.0902 -1.696 0.612 0.457 0.6233\n     \"\"\")\n\n\nclass YuEtAl2013MsEastern(YuEtAl2013Ms):\n    #: Supported tectonic region type is eastern part of China\n    DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.STABLE_CONTINENTAL\n    #: Coefficient table\n    COEFFS = CoeffsTable(sa_damping=5, table=\"\"\"\\\nIMT a b c d e ua ub uc ud ue ma mb mc md me ia ib ic id ie sigma\nPGA 4.5517 1.5433 -2.315 2.088 0.399 8.1259 0.9936 -2.315 2.088 0.399 2.7048 1.518 -2.004 0.944 0.447 6.3319 0.9614 -2.004 0.944 0.447 0.5428\nPGV -0.8349 1.8193 -2.103 2.088 0.399 3.3051 1.1799 -2.103 2.088 0.399 -2.6381 1.8124 -1.825 0.944 0.447 1.6376 1.1546 -1.825 0.944 0.447 0.6233\n     \"\"\")\n\n\nclass YuEtAl2013MsStable(YuEtAl2013Ms):\n    #: Supported tectonic region type is stable part of China\n    DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.STABLE_CONTINENTAL\n    #: Coefficient table\n    COEFFS = CoeffsTable(sa_damping=5, table=\"\"\"\\\nIMT a b c d e ua ub uc ud ue ma mb mc md me ia ib ic id ie sigma\nPGA 5.5591 1.1454 -2.079 2.802 0.295 8.5238 0.6854 -2.079 2.802 0.295 3.9445 1.0833 -1.723 1.295 0.331 6.187 0.7383 -1.723 1.295 0.331 0.5428\nPGV 0.2139 1.4283 -1.889 2.802 0.295 3.772 0.8786 -1.889 2.802 0.295 -1.3547 1.3823 -1.559 1.295 0.331 1.5433 0.9361 -1.559 1.295 0.331 0.6233\n     \"\"\")\n\n\nclass YuEtAl2013Mw(YuEtAl2013Ms):\n    \"\"\"\n    This is a modified version of the original Yu et al. (2013) that supports\n    the use of Mw rather than Ms. The Mw to Ms conversion equation used is the\n    one proposed by Cheng et al. (2017). Note that this version does not\n    propagate the uncertainty related to the magnitude conversion process.\n    \"\"\"\n\n    def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):\n        \"\"\"\n        See :meth:`superclass method\n        <.base.GroundShakingIntensityModel.get_mean_and_stddevs>`\n        for spec of input and result values.\n        \"\"\"\n        # Check that the requested standard deviation type is available\n        assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES\n                   for stddev_type in stddev_types)\n        #\n        # Set parameters\n        magn = rup.mag\n        epi = dists.repi\n        theta = dists.azimuth\n        #\n        # Convert Mw into Ms\n        if magn < 6.58:\n            mag = (magn - 0.59) / 0.86\n        else:\n            mag = (magn + 2.42) / 1.28\n        #\n        # Set coefficients\n        coeff = self.COEFFS[imt]\n        a1ca, a1cb, a1cc, a1cd, a1ce, a2ca, a2cb, a2cc, a2cd, a2ce = \\\n            gc(coeff, mag)\n        #\n        # Get correction coefficients. Here for each site we find the\n        # the geometry of the ellipses\n        ras = []\n        for epi, theta in zip(dists.repi, dists.azimuth):\n            res = get_ras(epi, theta, mag, coeff)\n            ras.append(res)\n        ras = np.array(ras)\n        rbs = rbf(ras, coeff, mag)\n        #\n        # Compute values of ground motion for the two cases. The value of\n        # 225 is hardcoded under the assumption that the hypocentral depth\n        # corresponds to 15 km (i.e. 15**2)\n        mean1 = (a1ca + a1cb * mag +\n                 a1cc * np.log((ras**2+225)**0.5 +\n                               a1cd * np.exp(a1ce * mag)))\n        mean2 = (a2ca + a2cb * mag +\n                 a2cc * np.log((rbs**2+225)**0.5 +\n                               a2cd * np.exp(a2ce * mag)))\n        #\n        # Get distances\n        x = (mean1 * np.sin(np.radians(dists.azimuth)))**2\n        y = (mean2 * np.cos(np.radians(dists.azimuth)))**2\n        mean = mean1 * mean2 / np.sqrt(x+y)\n        if isinstance(imt, (PGA)):\n            mean = np.exp(mean)/g/100\n        elif isinstance(imt, (PGV)):\n            mean = np.exp(mean)\n        else:\n            raise ValueError('Unsupported IMT')\n        #\n        # Get the standard deviation\n        stddevs = self._compute_std(coeff, stddev_types, len(dists.repi))\n        #\n        # Return results\n        return np.log(mean), stddevs\n\n\nclass YuEtAl2013MwTibet(YuEtAl2013Mw):\n    #: Supported tectonic region type is Tibetan plateau\n    DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.ACTIVE_SHALLOW_CRUST\n    #: Coefficient table\n    COEFFS = CoeffsTable(sa_damping=5, table=\"\"\"\\\nIMT a b c d e ua ub uc ud ue ma mb mc md me ia ib ic id ie sigma\nPGA 5.4901 1.4835 -2.416 2.647 0.366 8.7561 0.9453 -2.416 2.647 0.366 2.3069 1.4007 -1.854 0.612 0.457 5.6511 0.8924 -1.854 0.612 0.457 0.5428\nPGV -0.1472 1.7618 -2.205 2.647 0.366 3.9422 1.1293 -2.205 2.647 0.366 -2.9923 1.7043 -1.696 0.612 0.457 1.0189 1.0902 -1.696 0.612 0.457 0.6233\n     \"\"\")\n\n\nclass YuEtAl2013MwEastern(YuEtAl2013Mw):\n    #: Supported tectonic region type is eastern part of China\n    DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.STABLE_CONTINENTAL\n    #: Coefficient table\n    COEFFS = CoeffsTable(sa_damping=5, table=\"\"\"\\\nIMT a b c d e ua ub uc ud ue ma mb mc md me ia ib ic id ie sigma\nPGA 4.5517 1.5433 -2.315 2.088 0.399 8.1259 0.9936 -2.315 2.088 0.399 2.7048 1.518 -2.004 0.944 0.447 6.3319 0.9614 -2.004 0.944 0.447 0.5428\nPGV -0.8349 1.8193 -2.103 2.088 0.399 3.3051 1.1799 -2.103 2.088 0.399 -2.6381 1.8124 -1.825 0.944 0.447 1.6376 1.1546 -1.825 0.944 0.447 0.6233\n     \"\"\")\n\n\nclass YuEtAl2013MwStable(YuEtAl2013Mw):\n    #: Supported tectonic region type is stable part of China\n    DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.STABLE_CONTINENTAL\n    #: Coefficient table\n    COEFFS = CoeffsTable(sa_damping=5, table=\"\"\"\\\nIMT a b c d e ua ub uc ud ue ma mb mc md me ia ib ic id ie sigma\nPGA 5.5591 1.1454 -2.079 2.802 0.295 8.5238 0.6854 -2.079 2.802 0.295 3.9445 1.0833 -1.723 1.295 0.331 6.187 0.7383 -1.723 1.295 0.331 0.5428\nPGV 0.2139 1.4283 -1.889 2.802 0.295 3.772 0.8786 -1.889 2.802 0.295 -1.3547 1.3823 -1.559 1.295 0.331 1.5433 0.9361 -1.559 1.295 0.331 0.6233\n     \"\"\")\n", "meta": {"hexsha": "e6989bd535f400e7cf4ab90273487526a0b7332b", "size": 14004, "ext": "py", "lang": "Python", "max_stars_repo_path": "openquake/hazardlib/gsim/yu_2013.py", "max_stars_repo_name": "gfzriesgos/shakyground-lfs", "max_stars_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-01T00:28:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-01T00:28:24.000Z", "max_issues_repo_path": "openquake/hazardlib/gsim/yu_2013.py", "max_issues_repo_name": "gfzriesgos/shakyground-lfs", "max_issues_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-08-31T14:14:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-11T12:53:13.000Z", "max_forks_repo_path": "openquake/hazardlib/gsim/yu_2013.py", "max_forks_repo_name": "gfzriesgos/shakyground-lfs", "max_forks_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-08-31T14:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-17T10:06:02.000Z", "avg_line_length": 36.2797927461, "max_line_length": 144, "alphanum_fraction": 0.6162524993, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.19045118442815762}}
{"text": "\"\"\"\nCustomised implementation of FermiDos. Will Move back to pymatgen at some point.\n\"\"\"\nimport logging\nfrom typing import Dict, Optional, Tuple, Union\n\nimport numpy as np\nfrom monty.json import MSONable\nfrom pymatgen import Spin, Structure\nfrom pymatgen.electronic_structure.dos import Dos\n\nfrom amset.constants import boltzmann_au, ev_to_hartree, hartree_to_ev\nfrom amset.electronic_structure.fd import fd\n\n__author__ = \"Alex Ganose\"\n__maintainer__ = \"Alex Ganose\"\n__email__ = \"aganose@lbl.gov\"\n\nlogger = logging.getLogger(__name__)\n\n\nclass FermiDos(Dos, MSONable):\n    \"\"\"\n    This wrapper class helps relate the density of states, doping levels\n    (i.e. carrier concentrations) and corresponding fermi levels. A negative\n    doping concentration indicates the majority carriers are electrons\n    (n-type doping); a positive doping concentration indicates holes are the\n    majority carriers (p-type doping).\n\n    Args:\n        efermi: The Fermi level energy in Hartree.\n        energies: A sequences of energies in Hartree.\n        densities ({Spin: np.array}): representing the density of states\n            for each Spin.\n        structure: A structure. If not provided, the structure\n            of the dos object will be used. If the dos does not have an\n            associated structure object, an error will be thrown.\n        dos_weight: The weighting for the dos. Defaults to 2 for non-spin\n            polarized calculations and 1 for spin-polarized calculations.\n        atomic_units: Whether energies are given in eV or Hartree.\n        num_electrons: The number of electrons in the system. If None, this will be\n            calculated by integrating up to the intrinsic Fermi level.\n    \"\"\"\n\n    def __init__(\n        self,\n        efermi: float,\n        energies: np.ndarray,\n        densities: Dict[Spin, np.ndarray],\n        structure: Structure,\n        dos_weight: Optional[float] = None,\n        atomic_units: bool = True,\n        num_electrons: Optional[float] = None,\n    ):\n        # structure should be atomic structure\n        super().__init__(efermi, energies, densities)\n        self.structure = structure\n        self.atomic_units = atomic_units\n\n        if not dos_weight:\n            dos_weight = 2 if len(self.densities) == 1 else 1\n\n        self.dos_weight = dos_weight\n        self.tdos = np.array(self.get_densities()) * self.dos_weight\n        self.de = self.energies[1] - self.energies[0]\n        self._num_electrons = num_electrons  # this is just for msonability\n\n        if num_electrons is None:\n            # integrate up to Fermi level to get number of electrons\n            self.nelect = self.tdos[self.energies <= self.efermi].sum() * self.de\n        else:\n            self.nelect = num_electrons\n\n        logger.info(\n            \"Intrinsic DOS Fermi level: {:.4f} eV\".format(\n                self.efermi * hartree_to_ev if atomic_units else self.efermi\n            )\n        )\n        logger.info(\"DOS contains {:.3f} electrons\".format(self.nelect))\n\n    def get_doping(\n        self,\n        fermi_level: float,\n        temperature: float,\n        return_electron_hole_conc: bool = False,\n    ) -> Union[float, Tuple[float, float, float]]:\n        \"\"\"\n        Calculate the doping (majority carrier concentration) at a given\n        fermi level  and temperature. A simple Left Riemann sum is used for\n        integrating the density of states over energy & equilibrium Fermi-Dirac\n        distribution.\n\n        Args:\n            fermi_level: The fermi_level level in Hartree.\n            temperature: The temperature in Kelvin.\n            return_electron_hole_conc: Whether to also return the separate\n                electron and hole concentrations at the doping level.\n\n        Returns:\n            If return_electron_hole_conc is False: the doping concentration in\n            units of 1/Bohr^3. Negative values indicate that the majority carriers\n            are electrons (n-type doping) whereas positive values indicates the\n            majority carriers are holes (p-type doping).\n\n            If return_electron_hole_conc is True: the doping concentration,\n            electron concentration and hole concentration as a tuple.\n        \"\"\"\n        wdos = _get_weighted_dos(\n            self.energies,\n            self.tdos,\n            fermi_level,\n            temperature,\n            atomic_units=self.atomic_units,\n        )\n\n        num_electrons = wdos.sum() * self.de\n        conc = (self.nelect - num_electrons) / self.structure.volume\n\n        if return_electron_hole_conc:\n            cb_conc = wdos[self.energies > self.efermi].sum() * self.de\n            vb_conc = wdos[self.energies <= self.efermi].sum() * self.de\n            cb_conc = cb_conc / self.structure.volume\n            vb_conc = (self.nelect - vb_conc) / self.structure.volume\n            return conc, cb_conc, vb_conc\n\n        else:\n            return conc\n\n    def get_num_electrons(self, fermi_level: float, temperature: float) -> float:\n        \"\"\"\n        Calculate the number of electrons at a given fermi level and temperature.\n        A simple Left Riemann sum is used for integrating the density of states over\n        energy & equilibrium Fermi-Dirac distribution.\n\n        Args:\n            fermi_level: The fermi_level level in Hartree.\n            temperature: The temperature in Kelvin.\n\n        Returns:\n            The number of electrons.\n        \"\"\"\n        wdos = _get_weighted_dos(\n            self.energies,\n            self.tdos,\n            fermi_level,\n            temperature,\n            atomic_units=self.atomic_units,\n        )\n\n        num_electrons = wdos.sum() * self.de\n        return num_electrons\n\n    def get_fermi_from_num_electrons(\n        self,\n        num_electrons: float,\n        temperature: float,\n        tol: float = 0.01,\n        nstep: int = 50,\n        step: float = 0.1,\n        precision: int = 10,\n    ):\n        # this is finding the Fermi level of metals\n        fermi = self.efermi  # initialize target fermi\n        relative_error = float(\"inf\")\n        for _ in range(precision):\n            frange = np.arange(-nstep, nstep + 1) * step + fermi\n            calc_nelectrons = [self.get_num_electrons(f, temperature) for f in frange]\n            relative_error = abs(np.array(calc_nelectrons) / num_electrons - 1.0)\n            fermi = frange[np.argmin(relative_error)]\n            step /= 10.0\n\n        if min(relative_error) > tol:\n            raise ValueError(\n                \"Could not find fermi within {}% of num electrons={}\".format(\n                    tol * 100, num_electrons\n                )\n            )\n\n        return fermi\n\n    def get_fermi(\n        self,\n        concentration: float,\n        temperature: float,\n        tol: float = 0.01,\n        nstep: int = 50,\n        step: float = 0.1,\n        precision: int = 10,\n        return_electron_hole_conc=False,\n    ):\n        \"\"\"\n        Finds the fermi level at which the doping concentration at the given\n        temperature (T) is equal to concentration. A greedy algorithm is used\n        where the relative error is minimized by calculating the doping at a\n        grid which continually becomes finer.\n\n        Args:\n            concentration: The doping concentration in 1/Bohr^3. Negative values\n                represent n-type doping and positive values represent p-type\n                doping.\n            temperature: The temperature in Kelvin.\n            return_electron_hole_conc: Whether to also return the separate\n                electron and hole concentrations at the doping level.\n\n        Returns:\n            If return_electron_hole_conc is False: The Fermi level in eV. Note\n            that this is different from the default dos.efermi.\n\n            If return_electron_hole_conc is True: the Fermi level, electron\n            concentration and hole concentration at the Fermi level as a tuple.\n            The electron and hole concentrations are in Bohr^-3.\n        \"\"\"\n        fermi = self.efermi  # initialize target fermi\n        relative_error = float(\"inf\")\n        for _ in range(precision):\n            frange = np.arange(-nstep, nstep + 1) * step + fermi\n            calc_doping = np.array([self.get_doping(f, temperature) for f in frange])\n            relative_error = abs(calc_doping / concentration - 1.0)\n            fermi = frange[np.argmin(relative_error)]\n            step /= 10.0\n\n        if min(relative_error) > tol:\n            raise ValueError(\n                \"Could not find fermi within {}% of concentration={}\".format(\n                    tol * 100, concentration\n                )\n            )\n\n        if return_electron_hole_conc:\n            _, n_elec, n_hole = self.get_doping(\n                fermi, temperature, return_electron_hole_conc=True\n            )\n            return fermi, n_elec, n_hole\n        else:\n            return fermi\n\n\ndef _get_weighted_dos(energies, dos, fermi_level, temperature, atomic_units=True):\n    if temperature == 0.0:\n        occ = np.where(energies < fermi_level, 1.0, 0.0)\n        occ[energies == fermi_level] = 0.5\n    else:\n        kbt = temperature * boltzmann_au\n        if atomic_units:\n            occ = fd(energies, fermi_level, kbt)\n        else:\n            occ = fd(energies * ev_to_hartree, fermi_level * ev_to_hartree, kbt)\n\n    wdos = dos * occ\n    return wdos\n", "meta": {"hexsha": "4db3afb6cca766b4593c86d8de3afc6f60cfadf8", "size": 9326, "ext": "py", "lang": "Python", "max_stars_repo_path": "amset/electronic_structure/dos.py", "max_stars_repo_name": "kbspooner/amset", "max_stars_repo_head_hexsha": "1e341d68bd03eef47916e680e687fc085966a0c0", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "amset/electronic_structure/dos.py", "max_issues_repo_name": "kbspooner/amset", "max_issues_repo_head_hexsha": "1e341d68bd03eef47916e680e687fc085966a0c0", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "amset/electronic_structure/dos.py", "max_forks_repo_name": "kbspooner/amset", "max_forks_repo_head_hexsha": "1e341d68bd03eef47916e680e687fc085966a0c0", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-12T12:00:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T12:00:30.000Z", "avg_line_length": 37.1553784861, "max_line_length": 86, "alphanum_fraction": 0.6213810851, "include": true, "reason": "import numpy", "num_tokens": 2185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.1904511772378268}}
{"text": "import nest\nimport os\nimport subprocess\nimport sys\nimport itertools\nfrom scipy.optimize import minimize\nimport scipy.special as sp_spec\nimport numpy as np\n# from nest_elephant_tvb.simulation.file_tvb.Zerlaut import ZerlautAdaptationSecondOrder as model\nfrom nest_elephant_tvb.Tvb import Matteo_2 as model\nfrom nest_elephant_tvb.Tvb import excitatory\n\n\n# Matteo function\n# # excitatory\n# excitatory={\n#         'C_m':200.0,\n#         't_ref':5.0,\n#         'V_reset':-64.5,\n#         'E_L':-64.5,\n#         'g_L':10.0,\n#         'I_e':0.0,\n#         'a':0.0,\n#         'b':0.0,\n#         'Delta_T':2.0,\n#         'tau_w':500.0,\n#         'V_th':-50.0,\n#         'E_ex':0.0,\n#         'tau_syn_ex':5.0,\n#         'E_in':-80.0,\n#         'tau_syn_in':5.0,\n#     'V_peak': 10.0,\n#     'N_tot':10**4,\n#     'p_connect':0.05,\n#     'g':0.2,\n#     'Q_e':1.0,\n#     'Q_i':2.5,\n# }\n# #inhibitory\n# inhibitory={\n#         'C_m':200.0,\n#         't_ref':5.0,\n#         'V_reset':-65.0,\n#         'E_L':-65.,\n#         'g_L':10.0,\n#         'I_e':0.0,\n#         'a':0.0,\n#         'b':0.0,\n#         'Delta_T':0.5,\n#         'tau_w':1.0,\n#         'V_th':-50.0,\n#         'E_ex':0.0,\n#         'tau_syn_ex':5.0,\n#         'E_in':-80.0,\n#         'tau_syn_in':5.0,\n#     'V_peak': 10.0,\n#     'N_tot':10**4,\n#     'p_connect':0.05,\n#     'g':0.2,\n#     'Q_e':1.0,\n#     'Q_i':2.5\n# }\n\n\ndef compute_rate(data,begin,end,nb):\n    \"\"\"\n    Compute the firing rate\n    :param data: the spike of all neurons between end and begin\n    :param begin: the time of the first spike\n    :param end: the time of the last spike\n    :return: the mean and the standard deviation of firing rate, the maximum and minimum of firing rate\n    \"\"\"\n    #get data\n    n_fil = data[:, 0]\n    n_fil = n_fil.astype(int)\n    #count the number of the same id\n    count_of_n = np.bincount(n_fil)\n    #compute the rate\n    rate_each_n_incomplet = count_of_n / (end - begin)\n    #fill the table with the neurons which are not firing\n    rate_each_n = np.concatenate(\n        (rate_each_n_incomplet, np.zeros(-np.shape(rate_each_n_incomplet)[0] + nb +1)))\n    #save the value\n\n\n    return rate_each_n[1:]\n\ndef load_event(events):\n    \"\"\"\n    Get the id of the neurons which create the spike and time\n    :param path: the path to the file\n    :return: The spike of all neurons\n    \"\"\"\n    data_concatenated =  np.concatenate(([events['senders']],[events['times']]))\n    if data_concatenated.size < 5:\n        print('empty file')\n        return None\n    data_raw = data_concatenated[np.argsort(data_concatenated[:, 1])]\n    return np.swapaxes(data_raw,0,1)\n\ndef load_spike(path):\n    \"\"\"\n    Get the id of the neurons which create the spike and time\n    :param path: the path to the file\n    :return: The spike of all neurons\n    \"\"\"\n    if not os.path.exists(path + \"/spike_detector.gdf\"):\n        print('no file')\n        return None\n    data_concatenated = np.loadtxt(path + \"/spike_detector.gdf\")\n    if data_concatenated.size < 5:\n        print('empty file')\n        return None\n    data_raw = data_concatenated[np.argsort(data_concatenated[:, 1])]\n    return data_raw\n\ndef create_transfer_function(parameter,excitatory):\n    model_test = model()\n    model_test.g_L = np.array(parameter['g_L'])\n    model_test.E_L_e =  np.array(parameter['E_L'])\n    model_test.E_L_i = np.array(parameter['E_L'])\n    model_test.C_m = np.array(parameter['C_m'])\n    model_test.b_e = np.array(parameter['b'])\n    model_test.a_e = np.array(parameter['a'])\n    model_test.b_i = np.array(parameter['b'])\n    model_test.a_i = np.array(parameter['a'])\n    model_test.tau_w_e = np.array(parameter['tau_w'])\n    model_test.tau_w_i = np.array(parameter['tau_w'])\n    model_test.E_e = np.array(parameter['E_ex'])\n    model_test.E_i = np.array(parameter['E_in'])\n    model_test.Q_e = np.array(parameter['Q_e'])\n    model_test.Q_i = np.array(parameter['Q_i'])\n    model_test.tau_e = np.array(parameter['tau_syn_ex'])\n    model_test.tau_i = np.array(parameter['tau_syn_in'])\n    model_test.N_tot = np.array(parameter['N_tot'])\n    model_test.p_connect = np.array(parameter['p_connect'])\n    model_test.g = np.array(parameter['g'])\n    model_test.T = np.array(parameter['t_ref'])\n    model_test.external_input_in_in = np.array(0.0)\n    model_test.external_input_in_ex = np.array(0.0)\n    model_test.external_input_ex_in = np.array(0.0)\n    model_test.external_input_ex_ex = np.array(0.0)\n    model_test.K_ext_e=np.array(1)\n    model_test.K_ext_i=np.array(0)\n    if excitatory:\n        def TF(fe,fi,p,f_ext_e=0.0,f_ext_i=0.0,w=0.0):\n            model_test.P_e=p\n            return model_test.TF_excitatory(fe,fi,f_ext_e,f_ext_i,w)\n    else:\n       def TF(fe,fi,p,f_ext_e=0.0,f_ext_i=0.0,w=0.0):\n            model_test.P_i=p\n            return model_test.TF_inhibitory(fe,fi,f_ext_e,f_ext_i,w)\n    return TF\n\ndef effective_Vthre(Y, muV, sV, Tv):\n    Vthre_eff = muV+np.sqrt(2)*sV*sp_spec.erfcinv(Y*2.*Tv) # effective threshold\n    return Vthre_eff\n\ndef engin(parameters,excitatory,max_frequency=40.0,precision=0.5,frequency=None,rescale=None):\n    name_file ='/home/kusch/Documents/project/co_simulation/co-simulation_mouse/test_nest/test_file/fitting/'\n    for name,value in parameters.items():\n        name_file += name+'_'+str(value)+'/'\n    if frequency is None:\n        frequency = np.arange(0.0,max_frequency,precision)\n    frequencies = np.array(list(itertools.product(frequency,frequency)))\n\n    if os.path.exists(name_file+'/P.npy'):\n        return np.load(name_file+'/P.npy')\n    elif os.path.exists(name_file+'/rate.npy'):\n        rate = np.load(name_file+'/rate.npy')\n    else:\n        if os.path.exists(name_file+'/spike_detector.gdf'):\n            print('analysis')\n            data = load_spike(name_file)\n\n        else:\n            if not os.path.exists(name_file):\n                os.makedirs(name_file)\n            #initialisation of the parameter\n            params = {      'g_L':parameters['g_L'],\n                            'E_L':parameters['E_L'],\n                            'V_reset':parameters['V_reset'],\n                            'I_e':parameters['I_e'],\n                            'C_m':parameters['C_m'],\n                            'V_th':parameters['V_th'],\n                            't_ref':parameters['t_ref'],\n                            'tau_w':parameters['tau_w'],\n                            'Delta_T':parameters['Delta_T'],\n                            'b':parameters['b'],\n                            'a':parameters['a'],\n                            'V_peak':parameters['V_peak'],\n                            'E_ex':parameters['E_ex'],\n                            'E_in':parameters['E_in'],\n                            'tau_syn_ex':parameters['tau_syn_ex'],\n                            'tau_syn_in':parameters['tau_syn_in'],\n                            'gsl_error_tol':1e-8\n                            }\n            Number_connexion_ex = parameters['N_tot']*parameters['p_connect']*(1-parameters['g'])\n            Number_connexion_in = parameters['N_tot']*parameters['p_connect']*parameters['g']\n            simtime=100000.0\n            master_seed = 5\n            local_num_threads = 8\n            # simulation\n            simulation = False\n            error = 1.0e-6\n\n            while error > 1.0e-20 and not simulation:\n                params['gsl_error_tol'] = error\n                # initialisation of nest\n                nest.ResetKernel()\n                nest.SetKernelStatus({\n                    # Resolution of the simulation (in ms).\n                    \"resolution\": 0.05,\n                    # Print the time progress, this should only be used when the simulation\n                    # is run on a local machine.\n                    \"print_time\": True,\n                    # If True, data will be overwritten,\n                    # If False, a NESTError is raised if the files already exist.\n                    \"overwrite_files\": True,\n                    # Number of threads per MPI process.\n                    'local_num_threads': local_num_threads,\n                    # Path to save the output data\n                    'data_path':  name_file,\n                    # Masterseed for NEST and NumPy\n                    'grng_seed': master_seed + local_num_threads,\n                    # Seeds for the individual processes\n                    'rng_seeds': range(master_seed + 1 + local_num_threads, master_seed + 1 + (2 * local_num_threads)),\n                    })\n\n                #create the network\n                nest.SetDefaults('aeif_cond_exp', params)\n                neurons = nest.Create('aeif_cond_exp', frequency.shape[0]**2)\n                poisson_generator_ex = nest.Create('poisson_generator', frequency.shape[0])\n                poisson_generator_in = nest.Create('poisson_generator', frequency.shape[0])\n                nest.SetStatus(poisson_generator_ex,'rate',frequency*Number_connexion_ex)\n                nest.SetStatus(poisson_generator_in,'rate',frequency*Number_connexion_in)\n                nest.CopyModel(\"static_synapse\", \"excitatory\",\n                               {\"weight\": parameters['Q_e'], \"delay\": 1.0})\n                nest.CopyModel(\"static_synapse\", \"inhibitory\",\n                               {\"weight\": -parameters['Q_i'], \"delay\": 1.0})\n                for inh in range(len(frequency)):\n                    for ex in range(len(frequency)):\n                        nest.Connect(poisson_generator_ex[ex],neurons[ex+inh*len(frequency)],syn_spec=\"excitatory\")\n                        nest.Connect(poisson_generator_in[inh],neurons[ex+inh*len(frequency)],syn_spec=\"inhibitory\")\n\n                #create spike detector\n                spikes_dec = nest.Create(\"spike_detector\")\n                nest.SetStatus(spikes_dec, [{\"label\": \"spike\",\n                                          # \"withtime\": True,\n                                          # \"withgid\": True,\n                                          # \"to_file\": True,\n                                            \"record_to\":\"ascii\",\n                                           }])\n                nest.Connect(neurons,spikes_dec)\n                try :\n                    nest.Simulate(simtime)\n                    simulation = True\n                    print('end')\n                except nest.NESTError as exception:\n                    template = \"An exception of type {0} occurred. Arguments:\\n{1!r}\"\n                    message = template.format(type(exception).__name__, exception.args)\n                    print(message)\n                    error = error/10.0\n            print('analysis')\n\n            # Concatenate the different spike files\n            if subprocess.call([os.path.join(os.path.dirname(__file__),'script.sh'),name_file]) == 1:\n                sys.stderr.write('ERROR bad concatenation of spikes file\\n')\n                exit(1)\n\n            #Compute rate\n            # data = load_event(nest.GetStatus(spikes_dec)[0]['events'] )\n            data = load_spike(name_file)\n\n        if data is None:\n            print('compute rate')\n            rate = np.zeros_like(frequencies)\n            return [0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]\n        else:\n            rate = compute_rate(data,0.0,100000.0,len(frequencies))\n        np.save(name_file+'/rate.npy', rate)\n        del data\n\n    nb_freq = len (frequency)\n    if rescale is not None:\n        index = np.arange(0,nb_freq,1)\n        index = index[np.where(np.logical_not(np.isin(index,rescale)))]\n        rate = rate.reshape(nb_freq,nb_freq)\n        rate = np.ravel(rate[index,:][:,index])\n        frequencies =  np.array(list(itertools.product(frequency[index],frequency[index])))\n        nb_freq -=len(rescale)\n\n    # data = np.load('/home/kusch/Documents/project/Zerlaut/travail/Zerlaut/mean_field_for_multi_input_integration/transfer_functions/data/FS-cell_CONFIG1.npy')\n    # data = np.load('/home/kusch/Documents/project/Zerlaut/travail/Zerlaut/mean_field_for_multi_input_integration/transfer_functions/data/RS-cell_CONFIG1.npy')\n    # rate = np.ravel(data[0])*1e-3\n    # frequencies = np.empty((len(rate),2))\n    # frequencies[:,1] = np.ravel(data[2])\n    # frequencies[:,0] = np.ravel(np.repeat([data[3]],data[2].shape[1],axis=0))\n\n    #Compute mean of value for the model\n    # rate+=1e-10\n    muV, sV, Tv =model.get_fluct_regime_vars(frequencies[:,1]*1e-3,frequencies[:,0]*1e-3,0.00,0.0,0.0,parameters['Q_e'],parameters['tau_syn_ex'],parameters['E_ex'],parameters['Q_i'],parameters['tau_syn_in'],parameters['E_in'],\n                          parameters['g_L'],parameters['C_m'],parameters['E_L'],parameters['N_tot'],parameters['p_connect'],parameters['g'],0.0,0.0)\n    Tv+= parameters['g_L']/parameters['C_m']\n    i_non_zeros = np.where((rate>=1/100000.0)  &(rate*Tv<1.0))\n    # i_non_zeros=np.arange(0,len(rate),1)\n\n    Vthre_eff = effective_Vthre(rate[i_non_zeros], muV[i_non_zeros], sV[i_non_zeros], Tv[i_non_zeros])*1e-3\n    TvN = Tv[i_non_zeros]*parameters['g_L']/parameters['C_m']\n\n    import matplotlib.pylab as plt\n    # all = frequency[index]\n    all =frequency\n    index = i_non_zeros[0]; not_index = np.where(np.logical_not(np.isin(np.arange(0,nb_freq*nb_freq,1),i_non_zeros)))[0];\n    fig = plt.figure();ax = fig.add_subplot(111, projection='3d');ax.scatter(muV, sV, Tv*parameters['g_L']/parameters['C_m'], marker='x',s=0.1);ax.set_xlabel('Vm');ax.set_ylabel('sV');ax.set_zlabel('Tv')\n    fig = plt.figure();ax = fig.add_subplot(111, projection='3d');ax.scatter(muV[index], sV[index], Tv[index]*parameters['g_L']/parameters['C_m'], marker='x',s=0.1);ax.set_xlabel('Vm');ax.set_ylabel('sV');ax.set_zlabel('Tv');ax.scatter(muV[not_index], sV[not_index], Tv[not_index]*parameters['g_L']/parameters['C_m'], marker='o',s=0.1);\n    plt.figure(); plt.plot(all,muV.reshape(nb_freq,nb_freq),'x',markersize=0.5);\n    plt.figure(); plt.plot(all,sV.reshape(nb_freq,nb_freq),'x',markersize=0.5);\n    plt.figure(); plt.plot(all,Tv.reshape(nb_freq,nb_freq)*parameters['g_L']/parameters['C_m'],'x',markersize=0.5)\n    plt.figure(); plt.plot(index,TvN,'bx',markersize=0.5); plt.plot(not_index,Tv[not_index]*parameters['g_L']/parameters['C_m'],'rx',markersize=0.5)\n    plt.figure(); plt.plot(index,muV[index],'bx',markersize=0.5); plt.plot(not_index,muV[not_index],'rx',markersize=0.5)\n    plt.figure(); plt.plot(index,sV[index],'bx',markersize=0.5); plt.plot(not_index,sV[not_index],'rx',markersize=0.5)\n    plt.figure();plt.plot(Vthre_eff,rate[index],'x',markersize=0.5);\n    plt.figure();plt.plot(Vthre_eff,muV[index],'x',markersize=0.5);\n    plt.figure();plt.plot(Vthre_eff,sV[index],'x',markersize=0.5);\n    plt.figure();plt.plot(Vthre_eff,TvN,'x',markersize=0.5);\n    plt.figure(); plt.plot(frequencies[:,1].reshape(nb_freq,nb_freq).transpose(),rate.reshape(nb_freq,nb_freq).transpose()*1e3)\n    plt.show()\n\n\n    TF = create_transfer_function(parameters,excitatory=excitatory)\n    P = np.zeros(20)\n    P[:5] = Vthre_eff.mean(), 1e-3, 1e-3, 1e-3, 1e-3\n\n    def Res(p):\n        pp=p\n        vthre = model.threshold_func(muV[i_non_zeros], sV[i_non_zeros], TvN, *pp)\n        return np.mean((Vthre_eff-vthre)**2)\n        # return np.mean(np.abs(Vthre_eff-vthre)*1e3)\n        # return np.mean(np.abs((Vthre_eff - vthre) / Vthre_eff))\n    plsq = minimize(Res, P, method='SLSQP',options={'ftol': 1e-15, 'disp': True, 'maxiter':40000})\n    # plsq = minimize(Res, P, method='SLSQP',tol=1e-10,\\\n    #                 options={'ftol': 1e-12, 'eps':1e-8,'disp': True, 'maxiter':100000})\n\n    P = plsq.x\n    def Res_1(p):\n        return np.mean((rate[i_non_zeros] - TF(frequencies[i_non_zeros,1]*1e-3,frequencies[i_non_zeros,0]*1e-3,p)) ** 2)\n        # return np.mean(np.abs((rate[i_non_zeros] - TF(frequencies[i_non_zeros,1]*1e-3,frequencies[i_non_zeros,0]*1e-3,p)))*1e3)\n        # return np.mean(np.abs( (rate[i_non_zeros] - TF(frequencies[i_non_zeros, 1] * 1e-3, frequencies[i_non_zeros, 0] * 1e-3, p)) / rate[i_non_zeros]))\n    # plsq = minimize(Res_1, P, method='nelder-mead',options={'xtol': 1e-5, 'disp': True, 'maxiter': 50000})\n    # plsq = minimize(Res_1, P, method='nelder-mead',tol=1e-12, \\\n    #                 options={'xtol': 1., 'disp': True, 'maxiter': 100000, 'maxfev':100000})\n    # p = plsq.x\n    # index = np.argsort(np.abs(((rate - TF(frequencies[:, 1] * 1e-3, frequencies[:, 0] * 1e-3, p)) * 1e3)))[-10:]\n    # print('first part ')\n    # print(P)\n    # print(\"frequency\", frequencies[index])\n    # print(\"expected : \", rate[index] * 1e3)\n    # print(\"got : \", TF(frequencies[:, 1] * 1e-3, frequencies[:, 0] * 1e-3, p)[index] * 1e3)\n    # print(\"error : \", np.abs(((rate - TF(frequencies[:, 1] * 1e-3, frequencies[:, 0] * 1e-3, p)) * 1e3))[index])\n    # print(\"max error \", np.abs(((rate - TF(frequencies[:, 1] * 1e-3, frequencies[:, 0] * 1e-3, p)) * 1e3))[index[-1]])\n\n    P = plsq.x\n    def Res_2(p):\n        return np.mean((rate - TF(frequencies[:,1]*1e-3,frequencies[:,0]*1e-3,p)) ** 2)\n        # return np.mean(np.abs((rate - TF(frequencies[:,1]*1e-3,frequencies[:,0]*1e-3,p)))*1e3)\n        # return np.mean(np.abs((rate - TF(frequencies[:,1]*1e-3,frequencies[:,0]*1e-3,p))/rate))\n    plsq = minimize(Res_2, P, method='nelder-mead',options={'xtol': 1e-5, 'disp': True, 'maxiter': 50000})\n    # plsq = minimize(Res_2, P, method='nelder-mead',tol=1e-12, \\\n    #                 options={'xtol': 1.0, 'disp': True, 'maxiter': 100000, 'maxfev':100000})\n\n    # network = np.empty((651,9))\n    # range_rate = np.arange(0.0,105.0,5.0)\n    # range_b =  np.arange(0.,3.1,0.1)\n    # range_test = np.array(list(itertools.product(range_b,range_rate)))\n    # for i in range(651):\n    #     network[i,:7]=np.load(\"/home/kusch/Documents/project/co_simulation/co-simulation_mouse/test_nest/test_file/fitting/network_\"+str(i)+\".npy\")\n    # network[:,7:]=range_test\n    # network = network[np.where(network[:,6]==0)[0],:]\n    # index_network = 2 if excitatory else 0\n    # P = plsq.x\n    # def Res_3(p):\n        # return np.mean((( network[:,index_network]*1e-3- TF(network[:,2]*1e-3,network[:,0]*1e-3,p,network[:,8]*1e-3,0.0,network[:,4]))*1e3) ** 2)\n        # return np.mean(np.abs( network[:,index_network]- TF(network[:,2]*1e-3,network[:,0]*1e-3,p,network[:,8]*1e-3,0.0,network[:,4])*1e3))\n        # return np.mean(np.abs( (network[:,index_network] - TF(network[:,2]*1e-3,network[:,0]*1e-3,p,network[:,8]*1e-3,0.0,network[:,4])*1e3))/network[:,index_network])\n    # plsq = minimize(Res_3, P, method='nelder-mead',tol=1e-12, \\\n    #             options={'xtol': 1.0, 'disp': True, 'maxiter': 100000, 'maxfev':100000})\n\n    p = plsq.x\n    index = np.argsort(np.abs(((rate - TF(frequencies[:, 1] * 1e-3, frequencies[:, 0] * 1e-3, p)) * 1e3)))[-10:]\n    # print(\"frequency\", frequencies[index])\n    # print(\"expected : \", rate[index] * 1e3)\n    # print(\"got : \", TF(frequencies[:, 1] * 1e-3, frequencies[:, 0] * 1e-3, p)[index] * 1e3)\n    # print(\"error : \", np.abs(((rate - TF(frequencies[:, 1] * 1e-3, frequencies[:, 0] * 1e-3, p)) * 1e3))[index])\n    # print(\"max error \", np.abs(((rate - TF(frequencies[:, 1] * 1e-3, frequencies[:, 0] * 1e-3, p)) * 1e3))[index[-1]])\n    # np.save(name_file+'/P.npy', plsq.x)\n\n\n\n    TF(frequencies[:,1]*1e-3,frequencies[:,0]*1e-3,p)\n    plt.figure(); plt.plot(frequencies[:,1].reshape(nb_freq,nb_freq).transpose(),TF(frequencies[:,1]*1e-3,frequencies[:,0]*1e-3,p).reshape(nb_freq,nb_freq).transpose()*1e3)\n    plt.figure(); plt.plot(frequencies[:,1].reshape(nb_freq,nb_freq).transpose(),rate.reshape(nb_freq,nb_freq).transpose()*1e3)\n    plt.show()\n    return plsq.x\n\n\n\n# frequency = np.array([0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.61,0.62,0.63,0.64,0.65,0.66,0.67,0.68,0.69,0.7,0.71,0.72,0.73,0.74,0.75,0.76,0.77,0.78,0.79,0.8,0.81,0.82,0.83,0.84,0.85,0.86,0.87,0.88,0.89,0.9,0.92,0.95,0.97,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.2,2.5,2.7,3.0,3.2,3.5,3.7,4.0,4.2,4.5,4.7,5.0,5.2,5.7,6.0,6.5,7.0,7.5,8.0,8.5,9.0,\n#              10.0,11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0,20.0,21.0,22.0,23.0,24.0,25.0,26.0,27.0,28.0,29.0,30.0,31.0,32.0,33.0,34.0,35.0,36.0,37.0,38.0,39.0,40.0,\n#                       50.0,60.0])\n#                       41.0,42.0,43.0,44.0,45.0,46.0,47.0,48.0,49.0,50.0,51.0,52.0,53.0,54.0,55.0,56.0,57.0,58.0,59.0,60.0])\n                      # 41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, 48.0, 49.0, 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0,\n                      # 57.0, 58.0, 59.0, 60.0,61.0,62.0,63.0,64.0,65.0,66.0,67.0,68.0,69.0,70.0,71.0,72.0,73.0,74.0,75.0,76.0,77.0,78.0,79.0,80.0,\n                      # 85.0,90.0,100.0,110.0,120.0,130.0,140.0,150.0,160.0,170.0,180.0,200.0])\n\nprint(\"EXCITATORY\")\nprint(\"'P_e':\",np.array2string(engin(parameters=excitatory,excitatory=True,max_frequency=40.0,precision=0.5), separator=', '),\",\",sep='')\n# print(\"'P_e':\",np.array2string(engin(parameters=excitatory,excitatory=True,max_frequency=40.0,precision=0.5,rescale=[32,33,56,57,59,60,62,63]), separator=', '),\",\",sep='')\nprint(\"INHIBITORY\")\n# print(\"'P_i':\",np.array2string(engin(parameters=inhibitory,excitatory=False,max_frequency=40.0,precision=0.5), separator=', '),\",\",sep='')\n# print(\"'P_i':\",np.array2string(engin(parameters=inhibitory,excitatory=False,max_frequency=40.0,precision=0.5,rescale=[5,6]), separator=', '),\",\",sep='')\n# print(engin(parameters=default,frequency=frequency))\n# print(engin(parameters=default,max_frequency=60.0,precision=0.5))\n# print(engin(parameters=default,max_frequency=100.0,precision=0.5))\n# np.set_printoptions(linewidth=500)\n# int_first = 200\nprint(\"EXCITATORY\")\n# print(\"'P_e':\",np.array2string(engin(parameters=excitatory,excitatory=True,max_frequency=100.0,precision=0.5,rescale=[10,12,123,124,174]), separator=', '),\",\",sep='')\n# rescale = np.arange(int_first,200)\n# print(\"'P_e':\",np.array2string(engin(parameters=excitatory,excitatory=True,max_frequency=100.0,precision=0.5,rescale=rescale), separator=', '),\",\",sep='')\n# print(\"'P_e':\",np.array2string(engin(parameters=excitatory,max_frequency=40.0,precision=0.5), separator=', '),\",\",sep='')\nprint(\"INHIBITORY\")\n# print(\"'P_i':\",np.array2string(engin(parameters=inhibitory,excitatory=False,max_frequency=100.0,precision=0.5,rescale=[3,4,44,45,59,60,81,82,105,106,109,110,111,112,113,114,194,195]), separator=', '),\",\",sep='')\n# print(\"'P_i':\",np.array2string(engin(parameters=inhibitory,excitatory=False,max_frequency=100.0,precision=0.5,rescale=[44,45,59,60,81,82,105,106,109,110,111,112,194,195]), separator=', '),\",\",sep='')\n# rescale = np.arange(int_first,200)\n# print(\"'P_i':\",np.array2string(engin(parameters=inhibitory,excitatory=False,max_frequency=100.0,precision=0.5,rescale=rescale), separator=', '),\",\",sep='')\n# print(\"'P_i':\",np.array2string(engin(parameters=inhibitory,max_frequency=40.0,precision=0.5), separator=', '),\",\",sep='')\n\n\ndef model_end (g_L,E_L,V_reset,I_e,C_m,V_th,t_ref,tau_w,Delta_T,b,a,E_ex,E_in,tau_syn_ex,tau_syn_in,Q_e,Q_i,N_tot,p_connect,g):\n    parameters= {   'g_L':g_L,\n                    'E_L':E_L,\n                    'V_reset':V_reset,\n                    'I_e':I_e,\n                    'C_m':C_m,\n                    'V_th':V_th,\n                    't_ref':t_ref,\n                    'tau_w':tau_w,\n                    'Delta_T':Delta_T,\n                    'b':b,\n                    'a':a,\n                    'V_peak':-10.0,\n                    'E_ex':E_ex,\n                    'E_in':E_in,\n                    'tau_syn_ex':tau_syn_ex,\n                    'tau_syn_in':tau_syn_in,\n                    'Q_e': Q_e,\n                    'Q_i' : Q_i,\n                    'N_tot' : N_tot,\n                    'p_connect' : p_connect,\n                    'g': g\n                    }\n\n    return None, engin(parameters=parameters,max_frequency=40.0)", "meta": {"hexsha": "731680adcbe95e2447018ee17a5495206c5daca5", "size": 23603, "ext": "py", "lang": "Python", "max_stars_repo_path": "fitting_TF/history/function_fitting.py", "max_stars_repo_name": "lionelkusch/compare_zerlaut", "max_stars_repo_head_hexsha": "4e22d1fdc5889fb404187bb7a48d7847759443d6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fitting_TF/history/function_fitting.py", "max_issues_repo_name": "lionelkusch/compare_zerlaut", "max_issues_repo_head_hexsha": "4e22d1fdc5889fb404187bb7a48d7847759443d6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fitting_TF/history/function_fitting.py", "max_forks_repo_name": "lionelkusch/compare_zerlaut", "max_forks_repo_head_hexsha": "4e22d1fdc5889fb404187bb7a48d7847759443d6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.8685344828, "max_line_length": 342, "alphanum_fraction": 0.5872558573, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 7308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.19037458646394367}}
{"text": "\"\"\" scan info for specific reaction classes\n\"\"\"\n\nimport math\nimport numpy\nimport more_itertools as mit\nfrom phydat import phycon, bnd\nfrom automol.graph import ts\nfrom automol.par import ReactionClass\nimport automol.zmat\nfrom automol.util import dict_\n# from automol.util import numpy_to_float\nfrom automol.reac._util import hydrogen_migration_atom_keys\nfrom automol.reac._util import ring_forming_scission_chain\nfrom automol.reac._util import insertion_forming_bond_keys\nfrom automol.reac._util import elimination_breaking_bond_keys\n\n\n# Wrapper function to obtain all of the scan data for a reaction\ndef build_scan_info(zrxn, zma, var=False):\n    \"\"\" Build all of the scan information\n    \"\"\"\n\n    # Obtain the reactions scan and constraint coordinates\n    scan_names = scan_coordinate(zrxn, zma)\n    const_names = constraint_coordinates(zrxn, zma)\n\n    constraint_dct = automol.zmat.constraint_dct(zma, const_names)\n\n    # Build the grid\n    grids = scan_grid(zrxn, zma, var=var)\n\n    # Set the update guess\n    update_guess = scan_update_guess(zrxn, var=var)\n\n    return scan_names, constraint_dct, grids, update_guess\n\n\n# SCAN AND CONSTRAINT COORDINATES #\n# Unimolecular reactions\n# 1. Hydrogen migrations\ndef hydrogen_migration_scan_coordinate(rxn, zma):\n    \"\"\" Obtain the scan coordinate for a hydrogen migration.\n\n    :param rxn: a Reaction object\n    :returns: the name of the scan coordinate in the z-matrix\n    :rtype: str\n    \"\"\"\n    frm_bnd_key, = ts.forming_bond_keys(rxn.forward_ts_graph)\n    scan_name = automol.zmat.distance_coordinate_name(zma, *frm_bnd_key)\n    return (scan_name,)\n\n\ndef hydrogen_migration_constraint_coordinates(rxn, zma):\n    \"\"\" Obtain the constraint coordinates for a hydrogen migration\n\n    :param rxn: a Reaction object\n    :returns: the names of the constraint coordinates in the z-matrix\n    :rtype: tuple[str]\n    \"\"\"\n    att_key, _, _, ngb_key = hydrogen_migration_atom_keys(rxn)\n    dist_name = automol.zmat.distance_coordinate_name(zma, att_key, ngb_key)\n    return (dist_name,)\n\n\ndef hydrogen_migration_grid(zrxn, zma, npoints=(18,)):\n    \"\"\" Build forward 1D grid  for addition reaction\n    \"\"\"\n\n    # Obtain the reactions scan and constraint coordinates\n    scan_name, = hydrogen_migration_scan_coordinate(zrxn, zma)\n\n    # Build the scan grid\n    npoints1 = npoints[0]\n    interval = 0.3 * phycon.ANG2BOHR\n\n    frm_bnd_len = _ts_bnd_len(zma, scan_name)\n    rmin1 = 2.0 * phycon.ANG2BOHR\n    rmin2 = frm_bnd_len + (0.05 * phycon.ANG2BOHR)\n    rmax = frm_bnd_len\n\n    if rmax > rmin1:\n        npoints = math.ceil((rmax-rmin1)/interval)\n        if npoints < 1:\n            grid1 = []\n        else:\n            grid1 = numpy.linspace(rmax, rmin1, npoints)\n    else:\n        grid1 = []\n\n    grid2 = numpy.linspace(rmin1, rmin2, npoints1)\n    grid = numpy.concatenate((grid1, grid2), axis=None)\n\n    return (grid,)\n\n\n# 2. Beta scissions\ndef beta_scission_scan_coordinate(rxn, zma):\n    \"\"\" Obtain the scan coordinate for a beta scission\n\n    :param rxn: a Reaction object\n    :returns: the name of the scan coordinate in the z-matrix\n    :rtype: str\n    \"\"\"\n    brk_bnd_key, = ts.breaking_bond_keys(rxn.forward_ts_graph)\n    scan_name = automol.zmat.distance_coordinate_name(zma, *brk_bnd_key)\n    return (scan_name,)\n\n\ndef beta_scission_grid(zrxn, zma, npoints=(14,)):\n    \"\"\" Build forward 1D grid for a beta scission reaction\n    \"\"\"\n\n    # Obtain the reactions scan and constraint coordinates\n    scan_name, = beta_scission_scan_coordinate(zrxn, zma)\n\n    # Build the scan grid\n    npoints1 = npoints[0]\n\n    frm_bnd_len = _ts_bnd_len(zma, scan_name)\n    if frm_bnd_len is not None:\n        rmin = frm_bnd_len + (0.1 * phycon.ANG2BOHR)\n        rmax = frm_bnd_len + (0.8 * phycon.ANG2BOHR)\n    else:\n        rmin = 1.4 * phycon.ANG2BOHR\n        rmax = 2.0 * phycon.ANG2BOHR\n    grid = numpy.linspace(rmin, rmax, npoints1)\n\n    return (grid,)\n\n\n# 3. Ring-forming scissions\ndef ring_forming_scission_scan_coordinate(rxn, zma):\n    \"\"\" Obtain the scan coordinate for a ring-forming scission\n\n    :param rxn: a Reaction object\n    :returns: the name of the scan coordinate in the z-matrix\n    :rtype: str\n    \"\"\"\n    brk_bnd_key, = ts.breaking_bond_keys(rxn.forward_ts_graph)\n    scan_name = automol.zmat.distance_coordinate_name(zma, *brk_bnd_key)\n    return (scan_name,)\n\n\ndef ring_forming_scission_constraint_coordinates(rxn, zma):\n    \"\"\" Obtain the constraint coordinates for a ring-forming scission\n\n    :param rxn: a Reaction object\n    :returns: the names of the constraint coordinates in the z-matrix\n    :rtype: str\n    \"\"\"\n    chain_keys = ring_forming_scission_chain(rxn)\n    ang_keys_lst = sorted(mit.windowed(chain_keys[1:], 3))\n    dih_keys_lst = sorted(mit.windowed(chain_keys, 4))\n    ang_names = [automol.zmat.central_angle_coordinate_name(zma, *ks)\n                 for ks in ang_keys_lst]\n    dih_names = [automol.zmat.dihedral_angle_coordinate_name(zma, *ks)\n                 for ks in dih_keys_lst]\n    const_names = tuple(ang_names + dih_names)\n    return const_names\n\n\ndef ring_forming_scission_grid(zrxn, zma, npoints=(7,)):\n    \"\"\" Build forward WD grid for a ring forming scission reaction\n        # the following allows for a 2-d grid search in the initial ts_search\n        # for now try 1-d grid and see if it is effective\n    \"\"\"\n\n    # Obtain the scan coordinate\n    scan_name, = ring_forming_scission_scan_coordinate(zrxn, zma)\n\n    # Build the grid\n    npoints1 = npoints[0]\n\n    brk_bnd_len = _ts_bnd_len(zma, scan_name)\n    if brk_bnd_len is not None:\n        r1min = brk_bnd_len + (0.1 * phycon.ANG2BOHR)\n        r1max = brk_bnd_len + (0.7 * phycon.ANG2BOHR)\n    else:\n        r1min = (1.54 + 0.1) * phycon.ANG2BOHR\n        r1max = (1.54 + 0.7) * phycon.ANG2BOHR\n\n    grid1 = numpy.linspace(r1min, r1max, npoints1)\n    grid = tuple(val.item() for val in grid1)\n\n    return (grid,)\n\n\n# 4. Eliminations\ndef elimination_scan_coordinate(rxn, zma):\n    \"\"\" Obtain the scan coordinate for an elimination\n\n    :param rxn: a Reaction object\n    :returns: the name of the scan coordinate in the z-matrix\n    :rtype: str\n    \"\"\"\n    frm_bnd_key, = ts.forming_bond_keys(rxn.forward_ts_graph)\n\n    brk_bnd_key1, _ = elimination_breaking_bond_keys(rxn)\n\n    frm_name = automol.zmat.distance_coordinate_name(zma, *frm_bnd_key)\n    brk_name = automol.zmat.distance_coordinate_name(zma, *brk_bnd_key1)\n\n    return (frm_name, brk_name)\n\n\ndef elimination_grid(zrxn, zma, npoints=(7, 5)):\n    \"\"\" Build forward 2D grid for elimination reaction\n    \"\"\"\n\n    # Obtain the scan coordinate\n    frm_name, brk_name = elimination_scan_coordinate(zrxn, zma)\n\n    # Build the grid\n    npoints1, npoints2 = npoints\n\n    frm_bnd_len = _ts_bnd_len(zma, frm_name)\n    brk_bnd_len = _ts_bnd_len(zma, brk_name)\n    if frm_bnd_len is not None:\n        r1min = frm_bnd_len + (0.1 * phycon.ANG2BOHR)\n        r1max = frm_bnd_len + (0.6 * phycon.ANG2BOHR)\n    else:\n        r1min = (0.85 + 0.1) * phycon.ANG2BOHR\n        r1max = (0.85 + 0.8) * phycon.ANG2BOHR\n    if brk_bnd_len is not None:\n        r2min = brk_bnd_len + (0.3 * phycon.ANG2BOHR)\n        r2max = brk_bnd_len + (1.2 * phycon.ANG2BOHR)\n    else:\n        r2min = (1.50 + 0.3) * phycon.ANG2BOHR\n        r2max = (1.50 + 1.2) * phycon.ANG2BOHR\n\n    grid1 = numpy.linspace(r1min, r1max, npoints1) * phycon.ANG2BOHR\n    grid2 = numpy.linspace(r2min, r2max, npoints2) * phycon.ANG2BOHR\n\n    return (grid1, grid2)\n\n\n# Bimolecular reactions\n# 1. Hydrogen abstractions\ndef hydrogen_abstraction_scan_coordinate(rxn, zma):\n    \"\"\" Obtain the scan coordinate for a hydrogen abstraction\n\n    :param rxn: a Reaction object\n    :returns: the name of the scan coordinate in the z-matrix\n    :rtype: str\n    \"\"\"\n    frm_bnd_key, = ts.forming_bond_keys(rxn.forward_ts_graph)\n    scan_name = automol.zmat.distance_coordinate_name(zma, *frm_bnd_key)\n    return (scan_name,)\n\n\ndef hydrogen_abstraction_grid(zrxn, zma, npoints=(8,)):\n    \"\"\" Build forward 1D grid for hydrogen abstraction reaction\n    \"\"\"\n\n    # Obtain the scan coordinate\n    scan_name, = hydrogen_abstraction_scan_coordinate(zrxn, zma)\n\n    # Build the grid\n    npoints1 = npoints[0]\n\n    frm_bnd_len = _ts_bnd_len(zma, scan_name)\n    if frm_bnd_len is not None:\n        rmin = frm_bnd_len + (0.1 * phycon.ANG2BOHR)\n        rmax = frm_bnd_len + (1.0 * phycon.ANG2BOHR)\n    else:\n        rmin = 0.7 * phycon.ANG2BOHR\n        rmax = 2.2 * phycon.ANG2BOHR\n    grid = numpy.linspace(rmin, rmax, npoints1)\n\n    return (grid,)\n\n\ndef radrad_hydrogen_abstraction_grid(zrxn, zma, npoints=(8, 4)):\n    \"\"\" Build forward 1D grid for elimination reaction\n    \"\"\"\n\n    # Obtain the scan coordinate\n    scan_name, = hydrogen_abstraction_scan_coordinate(zrxn, zma)\n\n    # Build the grid\n    npoints1, npoints2 = npoints\n\n    # Get the first grid from close to the mid\n    frm_bnd_len = _ts_bnd_len(zma, scan_name)\n    if frm_bnd_len is not None:\n        rmin = frm_bnd_len + (0.1 * phycon.ANG2BOHR)\n        rmax = frm_bnd_len + (1.0 * phycon.ANG2BOHR)\n    else:\n        rmin = 0.7 * phycon.ANG2BOHR\n        rmax = 2.2 * phycon.ANG2BOHR\n\n    grid1 = numpy.linspace(rmin, rmax, npoints1)\n    grid1 = numpy.flip(grid1)\n\n    # Get the outer grid from mid to long-distance\n    rend2 = 4.0 * phycon.ANG2BOHR\n    grid2 = numpy.linspace(rmax, rend2, npoints2+1)\n    # grid2 = numpy.delete(grid2, 0)\n\n    return (grid1, grid2)\n\n\n# 2. Additions\ndef addition_scan_coordinate(rxn, zma):\n    \"\"\" Obtain the scan coordinate for an addition\n\n    :param rxn: a Reaction object\n    :returns: the name of the scan coordinate in the z-matrix\n    :rtype: str\n    \"\"\"\n    frm_bnd_key, = ts.forming_bond_keys(rxn.forward_ts_graph)\n    scan_name = automol.zmat.distance_coordinate_name(zma, *frm_bnd_key)\n    return (scan_name,)\n\n\ndef addition_grid(zrxn, zma, npoints=(14,)):\n    \"\"\" Build forward 1D grid for addition reaction\n    \"\"\"\n\n    # Obtain the scan coordinate\n    scan_name, = addition_scan_coordinate(zrxn, zma)\n\n    # Build the grid\n    npoints1 = npoints[0]\n\n    frm_bnd_len = _ts_bnd_len(zma, scan_name)\n    if frm_bnd_len is not None:\n        rmin = frm_bnd_len + (0.1 * phycon.ANG2BOHR)\n        rmax = frm_bnd_len + (1.2 * phycon.ANG2BOHR)\n    else:\n        rmin = 1.6 * phycon.ANG2BOHR\n        rmax = 2.8 * phycon.ANG2BOHR\n\n    grid = _geometric_progression(\n        rmin, rmax, npoints1, gfact=1.1, rstp=0.05)\n\n    return (grid,)\n\n\ndef radrad_addition_grid(zrxn, zma, npoints=(8, 4)):\n    \"\"\" Build forward 1D grid for a beta scission reaction\n    \"\"\"\n\n    # Obtain the scan coordinate\n    scan_name, = addition_scan_coordinate(zrxn, zma)\n\n    # Build the grid\n    npoints1, npoints2 = npoints\n\n    # Get the first grid from close to the mid\n    frm_bnd_len = _ts_bnd_len(zma, scan_name)\n    if frm_bnd_len is not None:\n        rmin = frm_bnd_len + (0.2 * phycon.ANG2BOHR)\n        rmax = frm_bnd_len + (1.2 * phycon.ANG2BOHR)\n    else:\n        rmin = 1.5 * phycon.ANG2BOHR\n        rmax = 2.8 * phycon.ANG2BOHR\n\n    grid1 = numpy.linspace(rmin, rmax, npoints1)\n    grid1 = numpy.flip(grid1)\n    # grid1 = _geometric_progression(\n    #     rmin, rmax, npoints1, gfact=1.1, rstp=0.05)\n\n    # Get the outer grid from mid to long-distance\n    # Add extra point since initial will be dropped\n    rend2 = 4.00 * phycon.ANG2BOHR\n    grid2 = numpy.linspace(rmax, rend2, npoints2+1)\n    # grid2 = numpy.delete(grid2, 0)\n\n    return (grid1, grid2)\n\n\n# 3. Insertions\ndef insertion_scan_coordinate(rxn, zma):\n    \"\"\" Obtain the scan coordinate for an insertion\n\n    :param rxn: a Reaction object\n    :returns: the name of the scan coordinate in the z-matrix\n    :rtype: str\n    \"\"\"\n    frm_bnd_key, _ = insertion_forming_bond_keys(rxn)\n    scan_name = automol.zmat.distance_coordinate_name(zma, *frm_bnd_key)\n    return (scan_name,)\n\n\ndef insertion_grid(zrxn, zma, npoints=(16,)):\n    \"\"\" Build forward 1D grid for insertion reaction\n    \"\"\"\n\n    # Obtain the scan coordinate\n    scan_name, = insertion_scan_coordinate(zrxn, zma)\n\n    # Build the grid\n    npoints1 = npoints[0]\n\n    frm_bnd_len = _ts_bnd_len(zma, scan_name)\n    if frm_bnd_len is not None:\n        rmin = frm_bnd_len\n        rmax = frm_bnd_len + (1.4 * phycon.ANG2BOHR)\n    else:\n        rmin = 1.4 * phycon.ANG2BOHR\n        rmax = 2.4 * phycon.ANG2BOHR\n\n    grid = numpy.linspace(rmin, rmax, npoints1)\n\n    return (grid,)\n\n\n# 4. Substitution\ndef substitution_scan_coordinate(rxn, zma):\n    \"\"\" Obtain the scan coordinate for a substitution\n\n    :param rxn: a Reaction object\n    :returns: the name of the scan coordinate in the z-matrix\n    :rtype: str\n    \"\"\"\n    frm_bnd_key, = ts.forming_bond_keys(rxn.forward_ts_graph)\n    scan_name = automol.zmat.distance_coordinate_name(zma, *frm_bnd_key)\n    return (scan_name,)\n\n\ndef substitution_grid(zrxn, zma, npoints=(14,)):\n    \"\"\" Build forward 1D grid for substitution reaction\n    \"\"\"\n\n    # Obtain the scan coordinate\n    scan_name, = substitution_scan_coordinate(zrxn, zma)\n\n    # Build the grid\n    npoints1 = npoints[0]\n\n    frm_bnd_len = _ts_bnd_len(zma, scan_name)\n    if frm_bnd_len is not None:\n        rmin = frm_bnd_len\n        rmax = frm_bnd_len + (1.4 * phycon.ANG2BOHR)\n    else:\n        rmin = 0.7 * phycon.ANG2BOHR\n        rmax = 2.4 * phycon.ANG2BOHR\n\n    grid = numpy.linspace(rmin, rmax, npoints1)\n\n    return (grid,)\n\n\n# Aux function to return empty tuple when info not require for class\ndef _return_empty_tuple(*_):\n    \"\"\" Return empty tuple\n    \"\"\"\n    return ()\n\n\n# Wrapper functions to handle rxn obj and zma for any reaction class\nSCAN_COORD_DCT = {\n    # unimolecular\n    ReactionClass.Typ.HYDROGEN_MIGRATION:\n    hydrogen_migration_scan_coordinate,\n    ReactionClass.Typ.BETA_SCISSION: beta_scission_scan_coordinate,\n    ReactionClass.Typ.RING_FORM_SCISSION:\n    ring_forming_scission_scan_coordinate,\n    ReactionClass.Typ.ELIMINATION: elimination_scan_coordinate,\n    # bimolecular\n    ReactionClass.Typ.HYDROGEN_ABSTRACTION:\n    hydrogen_abstraction_scan_coordinate,\n    ReactionClass.Typ.ADDITION: addition_scan_coordinate,\n    ReactionClass.Typ.INSERTION: insertion_scan_coordinate,\n    ReactionClass.Typ.SUBSTITUTION: substitution_scan_coordinate,\n}\n\n\ndef scan_coordinate(rxn, zma):\n    \"\"\" Obtain the scan coordinates\n\n    :param rxn: a hydrogen migration Reaction object\n    \"\"\"\n    return SCAN_COORD_DCT[rxn.class_](rxn, zma)\n\n\nCONSTRAINT_COORD_DCT = {\n    # unimolecular\n    ReactionClass.Typ.HYDROGEN_MIGRATION:\n    hydrogen_migration_constraint_coordinates,\n    ReactionClass.Typ.BETA_SCISSION: _return_empty_tuple,\n    ReactionClass.Typ.RING_FORM_SCISSION:\n    ring_forming_scission_constraint_coordinates,\n    ReactionClass.Typ.ELIMINATION: _return_empty_tuple,\n    # bimolecular\n    ReactionClass.Typ.HYDROGEN_ABSTRACTION:\n    _return_empty_tuple,\n    ReactionClass.Typ.ADDITION: _return_empty_tuple,\n    ReactionClass.Typ.INSERTION: _return_empty_tuple,\n    ReactionClass.Typ.SUBSTITUTION: _return_empty_tuple,\n}\n\n\ndef constraint_coordinates(rxn, zma):\n    \"\"\" Obtain the constraint coordinates\n\n    :param rxn: a hydrogen migration Reaction object\n    \"\"\"\n    return CONSTRAINT_COORD_DCT[rxn.class_](rxn, zma)\n\n\nTIGHT_TS_GRID_DCT = {\n    ReactionClass.Typ.BETA_SCISSION: beta_scission_grid,\n    ReactionClass.Typ.ADDITION: addition_grid,\n    ReactionClass.Typ.HYDROGEN_MIGRATION: hydrogen_migration_grid,\n    ReactionClass.Typ.ELIMINATION: elimination_grid,\n    ReactionClass.Typ.RING_FORM_SCISSION: ring_forming_scission_grid,\n    ReactionClass.Typ.HYDROGEN_ABSTRACTION: hydrogen_abstraction_grid,\n    ReactionClass.Typ.SUBSTITUTION: substitution_grid,\n    ReactionClass.Typ.INSERTION: insertion_grid\n}\nVAR_TS_GRID_DCT = {\n    ReactionClass.Typ.ADDITION: radrad_addition_grid,\n    ReactionClass.Typ.HYDROGEN_ABSTRACTION: radrad_hydrogen_abstraction_grid\n}\n\n\ndef scan_grid(zrxn, zma, var=False):\n    \"\"\" Set the grid for a transition state search\n    \"\"\"\n\n    if not var:\n        grid = TIGHT_TS_GRID_DCT[zrxn.class_](zrxn, zma)\n    else:\n        grid = VAR_TS_GRID_DCT[zrxn.class_](zrxn, zma)\n\n    return grid\n\n\n# UPDATE GUESS DICTIONARY #\nTIGHT_TS_UPDATE_GUESS_DCT = {\n    ReactionClass.Typ.BETA_SCISSION: False,\n    ReactionClass.Typ.ADDITION: False,\n    ReactionClass.Typ.HYDROGEN_MIGRATION: True,\n    ReactionClass.Typ.ELIMINATION: False,\n    ReactionClass.Typ.RING_FORM_SCISSION: False,\n    ReactionClass.Typ.HYDROGEN_ABSTRACTION: False,\n    ReactionClass.Typ.SUBSTITUTION: False,\n    ReactionClass.Typ.INSERTION: False\n}\nVAR_TS_UPDATE_GUESS_DCT = {\n    ReactionClass.Typ.ADDITION: True,\n    ReactionClass.Typ.HYDROGEN_ABSTRACTION: True\n}\n\n\ndef scan_update_guess(zrxn, var=False):\n    \"\"\" Set boolean to control whether the initial guess structure for\n        optimization updates along scan, i.e., uses optimized geometry\n        from previous grid point\n    \"\"\"\n\n    if not var:\n        _update = TIGHT_TS_UPDATE_GUESS_DCT[zrxn.class_]\n    else:\n        _update = VAR_TS_UPDATE_GUESS_DCT[zrxn.class_]\n\n    return _update\n\n\n# Helper functions\ndef _ts_bnd_len(zma, scan_coord):\n    \"\"\" Obtain the current value of the bond defined by the scam coordinate\n    \"\"\"\n\n    symbs = automol.zmat.symbols(zma)\n    dist_coo, = automol.zmat.coordinates(zma)[scan_coord]\n    ts_bnd_symbs = tuple(sorted(map(symbs.__getitem__, dist_coo)))\n    ts_bnd_len = dict_.values_by_unordered_tuple(bnd.LEN_DCT, ts_bnd_symbs)\n\n    return ts_bnd_len\n\n\ndef _geometric_progression(rmin, rmax, npoints, gfact=1.1, rstp=0.05):\n    \"\"\" Build a grid using a geometric progresion\n    \"\"\"\n    grid = [rmin]\n    rgrid = rmin\n    for _ in range(npoints):\n        rgrid += rstp\n        if rgrid == rmax:\n            break\n        grid.append(rgrid)\n        rstp = rstp * gfact\n    grid = numpy.array(grid)\n\n    return grid\n", "meta": {"hexsha": "4ac287082dfa978a60928cb34b6bbeb7caa7c9a8", "size": 17675, "ext": "py", "lang": "Python", "max_stars_repo_path": "automol/reac/_scan.py", "max_stars_repo_name": "sjklipp/automol", "max_stars_repo_head_hexsha": "ba87f4443ebe2ceb5929d4269c4be93fd28f68ca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "automol/reac/_scan.py", "max_issues_repo_name": "sjklipp/automol", "max_issues_repo_head_hexsha": "ba87f4443ebe2ceb5929d4269c4be93fd28f68ca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "automol/reac/_scan.py", "max_forks_repo_name": "sjklipp/automol", "max_forks_repo_head_hexsha": "ba87f4443ebe2ceb5929d4269c4be93fd28f68ca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-12-18T20:11:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T08:54:16.000Z", "avg_line_length": 29.9576271186, "max_line_length": 77, "alphanum_fraction": 0.6981612447, "include": true, "reason": "import numpy", "num_tokens": 5263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.19037458646394362}}
{"text": "# Copyright 2016-2021 The Van Valen Lab at the California Institute of\n# Technology (Caltech), with support from the Paul Allen Family Foundation,\n# Google, & National Institutes of Health (NIH) under Grant U24CA224309-01.\n# All rights reserved.\n#\n# Licensed under a modified Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.github.com/vanvalenlab/deepcell-tf/LICENSE\n#\n# The Work provided may be used for non-commercial academic purposes only.\n# For any other use of the Work, including commercial use, please contact:\n# vanvalenlab@gmail.com\n#\n# Neither the name of Caltech nor the names of its contributors may be used\n# to endorse or promote products derived from this software without specific\n# prior written permission.\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Custom metrics for pixel-based and object-based classification accuracy.\n\nThe schema for this analysis was adopted from the description of object-based\nstatistics in Caicedo et al. (2018) Evaluation of Deep Learning Strategies for\nNucleus Segmentation in Fluorescence Images. BioRxiv 335216.\n\nThe SEG metric was adapted from Maska et al. (2014). A benchmark for comparison\nof cell tracking algorithms. Bioinformatics 30, 1609-1617.\n\nThe linear classification schema used to match objects in truth and prediction\nframes was adapted from Jaqaman et al. (2008). Robust single-particle tracking\nin live-cell time-lapse sequences. Nature Methods 5, 695-702.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport datetime\nimport json\nimport logging\nimport operator\nimport os\nimport warnings\n\nimport numpy as np\nimport pandas as pd\nimport networkx as nx\n\nfrom scipy.optimize import linear_sum_assignment\nfrom scipy.stats import hmean\nfrom skimage.measure import regionprops\nfrom skimage.segmentation import relabel_sequential\nfrom sklearn.metrics import confusion_matrix\nfrom tqdm import tqdm\n\nfrom deepcell_toolbox import erode_edges\nfrom deepcell_toolbox.compute_overlap import compute_overlap  # pylint: disable=E0401\nfrom deepcell_toolbox.compute_overlap import compute_overlap_3D\n\n\ndef _cast_to_tuple(x):\n    try:\n        tup_x = tuple(x)\n    except TypeError:\n        tup_x = () if x is None else (x,)\n    return tup_x\n\n\nclass Detection(object):  # pylint: disable=useless-object-inheritance\n    \"\"\"Object to hold relevant information about a given detection.\"\"\"\n\n    def __init__(self, true_index=None, pred_index=None):\n        # cast the indices as tuples if possible to make them immutable\n        try:\n            self.true_index = tuple(true_index)\n        except TypeError:\n            self.true_index = true_index\n        try:\n            self.pred_index = tuple(pred_index)\n        except TypeError:\n            self.pred_index = pred_index\n\n    def __eq__(self, other):\n        \"\"\"Custom comparator. Detections with the same indices are the same.\"\"\"\n        try:\n            is_true_same = self.true_index == other.true_index\n            is_pred_same = self.pred_index == other.pred_index\n            return is_true_same and is_pred_same\n        except AttributeError:\n            return False\n\n    def __hash__(self):\n        \"\"\"Custom hasher, allow Detections to be hashable.\"\"\"\n        return tuple((self.true_index, self.pred_index)).__hash__()\n\n    def __repr__(self):\n        return 'Detection({}, {})'.format(self.true_index, self.pred_index)\n\n    @property\n    def is_correct(self):\n        is_linked = self.true_index is not None and self.pred_index is not None\n        return is_linked and not self.is_split and not self.is_merge\n\n    @property\n    def is_gained(self):\n        return self.true_index is None and self.pred_index is not None\n\n    @property\n    def is_missed(self):\n        return self.true_index is not None and self.pred_index is None\n\n    @property\n    def is_split(self):\n        if self.is_gained or self.is_missed:\n            return False\n\n        try:\n            is_many_pred = len(self.pred_index) > 1\n        except TypeError:\n            is_many_pred = False\n\n        try:\n            is_single_true = len(tuple(self.true_index)) == 1\n        except TypeError:\n            is_single_true = isinstance(self.true_index, int)\n\n        return is_single_true and is_many_pred\n\n    @property\n    def is_merge(self):\n        if self.is_gained or self.is_missed:\n            return False\n\n        try:\n            is_many_true = len(self.true_index) > 1\n        except TypeError:\n            is_many_true = False\n\n        try:\n            is_single_pred = len(tuple(self.pred_index)) == 1\n        except TypeError:\n            is_single_pred = isinstance(self.pred_index, int)\n\n        return is_single_pred and is_many_true\n\n    @property\n    def is_catastrophe(self):\n        if self.is_gained or self.is_missed:\n            return False\n\n        try:\n            is_many_true = len(self.true_index) > 1\n        except TypeError:\n            is_many_true = False\n\n        try:\n            is_many_pred = len(self.pred_index) > 1\n        except TypeError:\n            is_many_pred = False\n\n        return is_many_true and is_many_pred\n\n\nclass BaseMetrics(object):  # pylint: disable=useless-object-inheritance\n\n    \"\"\"Base class for Metrics classes.\"\"\"\n\n    def __init__(self, y_true, y_pred):\n        if y_pred.shape != y_true.shape:\n            raise ValueError('Input shapes must match. Shape of prediction '\n                             'is: {}.  Shape of y_true is: {}'.format(\n                                 y_pred.shape, y_true.shape))\n\n        if not np.issubdtype(y_true.dtype, np.integer):\n            warnings.warn('Casting y_true from {} to int'.format(y_true.dtype))\n            y_true = y_true.astype('int32')\n\n        if not np.issubdtype(y_pred.dtype, np.integer):\n            warnings.warn('Casting y_pred from {} to int'.format(y_pred.dtype))\n            y_pred = y_pred.astype('int32')\n\n        self.y_true = y_true\n        self.y_pred = y_pred\n\n\nclass PixelMetrics(BaseMetrics):\n    \"\"\"Calculates pixel-based statistics.\n    (Dice, Jaccard, Precision, Recall, F-measure)\n\n    Takes in raw prediction and truth data in order to calculate accuracy\n    metrics for pixel based classfication. Statistics were chosen according\n    to the guidelines presented in Caicedo et al. (2018) Evaluation of Deep\n    Learning Strategies for Nucleus Segmentation in Fluorescence Images.\n    BioRxiv 335216.\n\n    Args:\n        y_true (numpy.array): Binary ground truth annotations for a single\n            feature, (batch,x,y)\n        y_pred (numpy.array): Binary predictions for a single feature,\n            (batch,x,y)\n\n    Raises:\n        ValueError: Shapes of y_true and y_pred do not match.\n\n    Warning:\n        Comparing labeled to unlabeled data will produce low accuracy scores.\n        Make sure to input the same type of data for y_true and y_pred\n    \"\"\"\n\n    def __init__(self, y_true, y_pred):\n        super(PixelMetrics, self).__init__(\n            y_true=(y_true != 0).astype('int'),\n            y_pred=(y_pred != 0).astype('int'))\n\n        self._y_true_sum = np.count_nonzero(self.y_true)\n        self._y_pred_sum = np.count_nonzero(self.y_pred)\n\n        # Calculations for IOU\n        self._intersection = np.count_nonzero(np.logical_and(self.y_true, self.y_pred))\n        self._union = np.count_nonzero(np.logical_or(self.y_true, self.y_pred))\n\n    @classmethod\n    def get_confusion_matrix(cls, y_true, y_pred, axis=-1):\n        \"\"\"Calculate confusion matrix for pixel classification data.\n\n        Args:\n            y_true (numpy.array): Ground truth annotations after any\n                necessary transformations\n            y_pred (numpy.array): Prediction array\n            axis (int): The channel axis of the input arrays.\n\n        Returns:\n            numpy.array: nxn confusion matrix determined by number of features.\n        \"\"\"\n        # Argmax collapses on feature dimension to assign class to each pixel\n        # Flatten is required for confusion matrix\n        y_true = y_true.argmax(axis=axis).flatten()\n        y_pred = y_pred.argmax(axis=axis).flatten()\n        return confusion_matrix(y_true, y_pred)\n\n    @property\n    def recall(self):\n        try:\n            _recall = self._intersection / self._y_true_sum\n        except ZeroDivisionError:\n            _recall = np.nan\n        return _recall\n\n    @property\n    def precision(self):\n        try:\n            _precision = self._intersection / self._y_pred_sum\n        except ZeroDivisionError:\n            _precision = 0\n        return _precision\n\n    @property\n    def f1(self):\n        _recall = self.recall\n        _precision = self.precision\n\n        # f1 is nan if recall is nan and no false negatives\n        if np.isnan(_recall) and _precision == 0:\n            return np.nan\n\n        f_measure = hmean([_recall, _precision])\n        # f_measure = (2 * _precision * _recall) / (_precision + _recall)\n        return f_measure\n\n    @property\n    def dice(self):\n        y_sum = self._y_true_sum + self._y_pred_sum\n        if y_sum == 0:\n            warnings.warn('DICE score is technically 1.0, '\n                          'but prediction and truth arrays are empty.')\n            return 1.0\n\n        return 2.0 * self._intersection / y_sum\n\n    @property\n    def jaccard(self):\n        try:\n            _jaccard = self._intersection / self._union\n        except ZeroDivisionError:\n            _jaccard = np.nan\n        return _jaccard\n\n    def to_dict(self):\n        return {\n            'jaccard': self.jaccard,\n            'recall': self.recall,\n            'precision': self.precision,\n            'f1': self.f1,\n            'dice': self.dice,\n        }\n\n\ndef get_box_labels(arr):\n    \"\"\"Get the bounding box and label for all objects in the image.\n\n    Args:\n        arr (np.array): integer label array of objects.\n\n    Returns:\n        tuple(list(np.array), list(int)): A tuple of bounding boxes and\n            the corresponding integer labels.\n    \"\"\"\n    props = regionprops(np.squeeze(arr.astype('int')), cache=False)\n    boxes, labels = [], []\n    for prop in props:\n        boxes.append(np.array(prop.bbox))\n        labels.append(int(prop.label))\n    boxes = np.array(boxes).astype('double')\n    return boxes, labels\n\n\nclass ObjectMetrics(BaseMetrics):\n    \"\"\"Classifies object prediction errors as TP, FP, FN, merge or split\n\n    The schema for this analysis was adopted from the description of\n    object-based statistics in Caicedo et al. (2018) Evaluation of Deep\n    Learning Strategies for Nucleus Segmentation in Fluorescence Images.\n    BioRxiv 335216.\n    The SEG metric was adapted from Maska et al. (2014). A benchmark for\n    comparison of cell tracking algorithms.\n    Bioinformatics 30, 1609-1617.\n    The linear classification schema used to match objects in truth and\n    prediction frames was adapted from Jaqaman et al. (2008).\n    Robust single-particle tracking in live-cell time-lapse sequences.\n    Nature Methods 5, 695-702.\n\n    Args:\n        y_true (numpy.array): Labeled ground truth annotation\n        y_pred (numpy.array): Labled object prediction, same size as y_true\n        cutoff1 (:obj:`float`, optional): Threshold for overlap in cost matrix,\n            smaller values are more conservative, default 0.4\n        cutoff2 (:obj:`float`, optional): Threshold for overlap in unassigned\n            cells, smaller values are better, default 0.1\n        seg (:obj:`bool`, optional): Calculates SEG score for cell tracking\n            competition\n        force_event_links(:obj:'bool, optional): Flag that determines whether to modify IOU\n            calculation so that merge or split events with cells of very different sizes are\n            never misclassified as misses/gains.\n        is_3d(:obj:'bool', optional): Flag that determines whether or not the input data\n            should be treated as 3-dimensional.\n\n    Raises:\n        ValueError: If y_true and y_pred are not the same shape\n        ValueError: If data_type is 2D, if input shape does not have ndim 2 or 3\n        ValueError: If data_type is 3D, if input shape does not have ndim 3\n    \"\"\"\n    def __init__(self,\n                 y_true,\n                 y_pred,\n                 cutoff1=0.4,\n                 cutoff2=0.1,\n                 force_event_links=False,\n                 is_3d=False):\n\n        # If 2D, dimensions can be 3 or 4 (with or without channel dimension)\n        if not is_3d and y_true.ndim not in {2, 3}:\n            raise ValueError('Expected dimensions for y_true (2D data) are 2 '\n                             '(x, y) and 3 (x, y, chan). '\n                             'Got ndim: {}'.format(y_true.ndim))\n\n        elif is_3d and y_true.ndim != 3:\n            raise ValueError('Expected dimensions for y_true (3D data) is 3.'\n                             'Requires format is: (z, x, y)'\n                             'Got ndim: {}'.format(y_true.ndim))\n\n        super(ObjectMetrics, self).__init__(y_true=y_true, y_pred=y_pred)\n\n        self.cutoff1 = cutoff1\n        self.cutoff2 = cutoff2\n        self.is_3d = is_3d\n\n        self.compute_overlap = compute_overlap_3D if is_3d else compute_overlap\n\n        self.n_true = len(np.unique(self.y_true[np.nonzero(self.y_true)]))\n        self.n_pred = len(np.unique(self.y_pred[np.nonzero(self.y_pred)]))\n\n        # keep track of every pair of objects through the detections dict\n        # using tuple(true_index, pred_index): Detection as a key/vaue pair\n        self._detections = set()\n\n        # store the keys of relevant Detections in a set for easy fetching\n        # types of detections\n        self._splits = set()\n        self._gained = set()\n        self._missed = set()\n        # types of errors\n        self._merges = set()\n        self._catastrophes = set()\n        self._correct = set()\n\n        # IoU: used to determine relative overlap of y_pred and y_true\n        self.iou = np.zeros((self.n_true, self.n_pred))\n\n        # used to determine seg score\n        self.seg_thresh = np.zeros((self.n_true, self.n_pred))\n\n        # Check if either frame is empty before proceeding\n        if self.n_true == 0:\n            logging.info('Ground truth frame is empty')\n\n        if self.n_pred == 0:\n            logging.info('Prediction frame is empty')\n\n        self._calc_iou()  # set self.iou and update self.seg_thresh\n\n        self.iou_modified = self._get_modified_iou(force_event_links)\n\n        matrix = self._linear_assignment()\n\n        # Identify direct matches as true positives\n        correct_index = np.nonzero(matrix[:self.n_true, :self.n_pred])\n\n        for i, j in zip(correct_index[0], correct_index[1]):\n            self._add_detection(true_index=int(i), pred_index=int(j))\n\n        # Calc seg score for true positives if requested\n        iou_mask = np.where(self.seg_thresh == 0, self.iou, np.nan)\n\n        with warnings.catch_warnings():\n            warnings.simplefilter('ignore', category=RuntimeWarning)\n            # correct_index may be empty, suppress mean of empty slice warning\n            self.seg_score = np.nanmean(iou_mask[correct_index])\n\n        # Classify other errors using a graph\n        G = self._array_to_graph(matrix)\n        self._classify_graph(G)\n\n        # Calculate pixel-level stats\n        self.pixel_stats = PixelMetrics(y_true, y_pred)\n\n    def _add_detection(self, true_index=None, pred_index=None):\n        detection = Detection(true_index=true_index, pred_index=pred_index)\n\n        self._detections.add(detection)\n\n        # keep track of all error types\n        # TODO: better way to do this?\n        if detection.is_correct:\n            self._correct.add(detection)\n        if detection.is_gained:\n            self._gained.add(detection)\n        if detection.is_missed:\n            self._missed.add(detection)\n        if detection.is_split:\n            self._splits.add(detection)\n        if detection.is_merge:\n            self._merges.add(detection)\n        if detection.is_catastrophe:\n            self._catastrophes.add(detection)\n\n    def _calc_iou(self):\n        \"\"\"Calculates IoU matrix for each pairwise comparison between true and\n        predicted. Additionally, if seg is True, records a 1 for each pair of\n        objects where $|Tbigcap P| > 0.5 * |T|$\n        \"\"\"\n        # Use bounding boxes to find masks that are likely to overlap\n        y_true_boxes, y_true_labels = get_box_labels(self.y_true)\n        y_pred_boxes, y_pred_labels = get_box_labels(self.y_pred)\n\n        if not y_true_boxes.shape[0] or not y_pred_boxes.shape[0]:\n            return  # cannot compute overlaps of nothing\n\n        # has the form [gt_bbox, res_bbox]\n        overlaps = self.compute_overlap(y_true_boxes, y_pred_boxes)\n\n        # Find the bboxes that have any overlap\n        # (ind_ corresponds to box number - starting at 0)\n        ind_true, ind_pred = np.nonzero(overlaps)\n\n        # TODO: this accounts for ~50+% of the time spent on calc_iou\n        for index in range(ind_true.shape[0]):\n            iou_y_true_idx = y_true_labels[ind_true[index]]\n            iou_y_pred_idx = y_pred_labels[ind_pred[index]]\n\n            is_true = self.y_true == iou_y_true_idx\n            is_pred = self.y_pred == iou_y_pred_idx\n\n            intersection = np.count_nonzero(np.logical_and(is_true, is_pred))\n            union = np.count_nonzero(np.logical_or(is_true, is_pred))\n\n            iou = intersection / union\n\n            # Subtract 1 from index to account for skipping 0\n            self.iou[iou_y_true_idx - 1, iou_y_pred_idx - 1] = iou\n\n            if intersection > 0.5 * np.count_nonzero(self.y_true == index):\n                self.seg_thresh[iou_y_true_idx - 1, iou_y_pred_idx - 1] = 1\n\n    def _get_modified_iou(self, force_event_links):\n        \"\"\"Modifies the IoU matrix to boost the value for small cells.\n\n        Args:\n            force_event_links (:obj:`bool'): Whether to modify IOU values of\n                large objects if they have been split or merged by\n                a small object.\n\n        Returns:\n            np.array: The modified IoU matrix.\n        \"\"\"\n        # identify cells that have matches in IOU but may be too small\n        true_labels, pred_labels = np.nonzero(\n            np.logical_and(self.iou > 0, self.iou < 1 - self.cutoff1)\n        )\n\n        iou_modified = self.iou.copy()\n\n        for idx in range(len(true_labels)):\n            # add 1 to get back to original label id\n            true_idx, pred_idx = true_labels[idx], pred_labels[idx]\n            true_label, pred_label = true_idx + 1, pred_idx + 1\n            true_mask = self.y_true == true_label\n            pred_mask = self.y_pred == pred_label\n\n            # fraction of true cell that is contained within pred cell, vice versa\n            true_in_pred = np.count_nonzero(\n                self.y_true[pred_mask] == true_label) / np.sum(true_mask)\n            pred_in_true = np.count_nonzero(\n                self.y_pred[true_mask] == pred_label) / np.sum(pred_mask)\n\n            iou_val = self.iou[true_idx, pred_idx]\n            max_val = np.max([true_in_pred, pred_in_true])\n\n            # if this cell has a small IOU due to its small size,\n            # but is at least half contained within the big cell,\n            # we bump its IOU value up so it doesn't get dropped from the graph\n            if iou_val <= self.cutoff1 and max_val > 0.5:\n                iou_modified[true_idx, pred_idx] = self.cutoff2\n\n                # optionally, we can also decrease the IOU value of the cell\n                # that swallowed up the small cell so that it doesn't directly\n                # match a different cell\n                if force_event_links and true_in_pred > 0.5:\n                    fix_idx = np.nonzero(self.iou[:, pred_idx] >= 1 - self.cutoff1)\n                    iou_modified[fix_idx, pred_idx] = 1 - self.cutoff1 - 0.01\n\n                if force_event_links and pred_in_true > 0.5:\n                    fix_idx = np.nonzero(self.iou[true_idx, :] >= 1 - self.cutoff1)\n                    iou_modified[true_idx, fix_idx] = 1 - self.cutoff1 - 0.01\n\n        return iou_modified\n\n    def _get_cost_matrix(self):\n        \"\"\"Assembles cost matrix using the iou matrix and cutoff1\n\n        The previously calculated iou matrix is cast into the top left and\n        transposed for the bottom right corner. The diagonals of the two\n        remaining corners are populated according to cutoff1. The lower the\n        value of cutoff1 the more likely it is for the linear sum assignment\n        to pick unmatched assignments for objects.\n        \"\"\"\n        n_obj = self.n_true + self.n_pred\n        matrix = np.ones((n_obj, n_obj))\n\n        # Assign 1 - iou to top left and bottom right\n        cost = 1 - self.iou_modified\n        matrix[:self.n_true, :self.n_pred] = cost\n        matrix[n_obj - self.n_pred:, n_obj - self.n_true:] = cost.T\n\n        # Calculate diagonal corners\n        bl = (self.cutoff1 * np.eye(self.n_pred)\n              + np.ones((self.n_pred, self.n_pred))\n              - np.eye(self.n_pred))\n        tr = (self.cutoff1 * np.eye(self.n_true)\n              + np.ones((self.n_true, self.n_true))\n              - np.eye(self.n_true))\n\n        # Assign diagonals to cm\n        matrix[n_obj - self.n_pred:, :self.n_pred] = bl\n        matrix[:self.n_true, n_obj - self.n_true:] = tr\n        return matrix\n\n    def _linear_assignment(self):\n        \"\"\"Runs linear sun assignment on cost matrix, identifies true\n        positives and unassigned true and predicted cells.\n\n        True positives correspond to assignments in the top left or bottom\n        right corner. There are two possible unassigned positions: true cell\n        unassigned in bottom left or predicted cell unassigned in top right.\n        \"\"\"\n        cost_matrix = self._get_cost_matrix()\n\n        results = linear_sum_assignment(cost_matrix)\n\n        # Map results onto cost matrix\n        assignment_matrix = np.zeros_like(cost_matrix)\n        assignment_matrix[results] = 1\n        return assignment_matrix\n\n    def _array_to_graph(self, matrix):\n        \"\"\"Transform matrix for unassigned cells into a graph object\n\n        In order to cast the iou matrix into a graph form, we treat each\n        unassigned cell as a node. The iou values for each pair of cells is\n        treated as an edge between nodes/cells. Any iou values equal to 0 are\n        dropped because they indicate no overlap between cells.\n\n        Args:\n            matrix (np.array): Assignment matrix.\n        \"\"\"\n        # Collect unassigned objects\n        x, y = matrix.shape\n        gained, _ = np.nonzero(matrix[x - self.n_pred:, :self.n_pred])\n        missed, _ = np.nonzero(matrix[:self.n_true, y - self.n_true:])\n\n        # Use meshgrid to get true and predicted object index for each val\n        tt, pp = np.meshgrid(missed, gained, indexing='ij')\n\n        true_nodes = tt.flatten()\n        pred_nodes = pp.flatten()\n\n        # construct list of edges for networkx\n        G = nx.Graph()\n\n        for t, p in zip(true_nodes, pred_nodes):\n            # edges between overlapping objects only\n            if self.iou_modified[t, p] >= self.cutoff2:\n                G.add_edge('true_{}'.format(t), 'pred_{}'.format(p))\n\n        # Add nodes to ensure all cells are included\n        G.add_nodes_from(('true_{}'.format(n) for n in missed))\n        G.add_nodes_from(('pred_{}'.format(n) for n in gained))\n\n        return G\n\n    def _classify_graph(self, G):\n        \"\"\"Assign each node in graph to an error type\n\n        Nodes with a degree (connectivity) of 0 correspond to either false\n        positives or false negatives depending on the origin of the node from\n        either the predicted objects (false positive) or true objects\n        (false negative). Any nodes with a connectivity of 1 are considered to\n        be true positives that were missed during linear assignment.\n        Finally any nodes with degree >= 2 are indicative of a merge or split\n        error. If the top level node is a predicted cell, this indicates a merge\n        event. If the top level node is a true cell, this indicates a split event.\n        \"\"\"\n        # Find subgraphs, e.g. merge/split\n        for g in (G.subgraph(c) for c in nx.connected_components(G)):\n            # Get the highest degree node\n            _, max_d = max(dict(g.degree).items(), key=operator.itemgetter(1))\n\n            true_indices, pred_indices = [], []\n\n            for node in g.nodes:\n                node_type, index = node.split('_')\n                index = int(index) + 1\n\n                if node_type == 'true':\n                    if max_d > 1:\n                        true_indices.append(index)\n                    else:\n                        self._add_detection(true_index=index)\n\n                if node_type == 'pred':\n                    if max_d > 1:\n                        pred_indices.append(index)\n                    else:\n                        self._add_detection(pred_index=index)\n\n            self._add_detection(\n                true_index=tuple(true_indices) if true_indices else None,\n                pred_index=tuple(pred_indices) if pred_indices else None,\n            )\n\n    def _get_props(self, detection_type):\n        prediction_types = {\n            'gained',\n        }\n        is_pred_type = detection_type in prediction_types\n        arr = self.y_pred if is_pred_type else self.y_true\n        label_image = np.zeros_like(arr)\n        attrname = '_{}'.format(detection_type)\n\n        try:\n            detections = getattr(self, attrname)\n        except AttributeError:\n            raise ValueError('Invalid detection_type: {}'.format(\n                detection_type))\n\n        for det in detections:\n            idx = det.pred_index if is_pred_type else det.true_index\n            idx = idx if isinstance(idx, tuple) else (idx,)\n            for i in idx:\n                label_image[arr == i] = i\n\n        return regionprops(label_image)\n\n    def __repr__(self):\n        \"\"\"Format the calculated statistics as a ``pd.DataFrame``.\"\"\"\n        return json.dumps(self.to_dict())\n\n    def to_dict(self):\n        \"\"\"Return a dictionary representation of the calclulated metrics.\"\"\"\n        return {\n            'n_pred': self.n_pred,\n            'n_true': self.n_true,\n            'correct_detections': self.correct_detections,\n            'missed_detections': self.missed_detections,\n            'gained_detections': self.gained_detections,\n            'missed_det_from_merge': self.missed_det_from_merge,\n            'gained_det_from_split': self.gained_det_from_split,\n            'true_det_in_catastrophe': self.true_det_in_catastrophe,\n            'pred_det_in_catastrophe': self.pred_det_in_catastrophe,\n            'merge': self.merges,\n            'split': self.splits,\n            'catastrophe': self.catastrophes,\n            'precision': self.precision,\n            'recall': self.recall,\n            'f1': self.f1,\n            'seg': self.seg_score,\n            'jaccard': self.jaccard,\n            'dice': self.dice,\n        }\n\n    @property\n    def correct_detections(self):\n        return len(self._correct)\n\n    @property\n    def missed_detections(self):\n        return len(self._missed)\n\n    @property\n    def gained_detections(self):\n        return len(self._gained)\n\n    @property\n    def splits(self):\n        return len(self._splits)\n\n    @property\n    def merges(self):\n        return len(self._merges)\n\n    @property\n    def catastrophes(self):\n        return len(self._catastrophes)\n\n    @property\n    def gained_det_from_split(self):\n        gained_dets = 0\n        for det in self._splits:\n            true_idx = _cast_to_tuple(det.true_index)\n            pred_idx = _cast_to_tuple(det.pred_index)\n            gained_dets += len(true_idx) + len(pred_idx) - 2\n        return gained_dets\n\n    @property\n    def missed_det_from_merge(self):\n        missed_dets = 0\n        for det in self._merges:\n            true_idx = _cast_to_tuple(det.true_index)\n            pred_idx = _cast_to_tuple(det.pred_index)\n            missed_dets += len(true_idx) + len(pred_idx) - 2\n        return missed_dets\n\n    @property\n    def true_det_in_catastrophe(self):\n        return sum([len(d.true_index) for d in self._catastrophes])\n\n    @property\n    def pred_det_in_catastrophe(self):\n        return sum([len(d.pred_index) for d in self._catastrophes])\n\n    @property\n    def split_props(self):\n        return self._get_props('splits')\n\n    @property\n    def merge_props(self):\n        return self._get_props('merges')\n\n    @property\n    def missed_props(self):\n        return self._get_props('missed')\n\n    @property\n    def gained_props(self):\n        return self._get_props('gained')\n\n    @property\n    def recall(self):\n        try:\n            recall = self.correct_detections / self.n_true\n        except ZeroDivisionError:\n            recall = 0\n        return recall\n\n    @property\n    def precision(self):\n        try:\n            precision = self.correct_detections / self.n_pred\n        except ZeroDivisionError:\n            precision = 0\n        return precision\n\n    @property\n    def f1(self):\n        return hmean([self.recall, self.precision])\n\n    @property\n    def jaccard(self):\n        return self.pixel_stats.jaccard\n\n    @property\n    def dice(self):\n        return self.pixel_stats.jaccard\n\n    def plot_errors(self):\n        \"\"\"Plots the errors identified from linear assignment code.\n\n        This must be run with sequentially relabeled data.\n\n        TODO: this is not working!\n        \"\"\"\n\n        import matplotlib as mpl\n        import matplotlib.pyplot as plt\n\n        # erode edges for easier visualization of adjacent cells\n        y_true = erode_edges(self.y_true.copy(), 1)\n        y_pred = erode_edges(self.y_pred.copy(), 1)\n\n        # semantic labels for each error\n        categories = ['Background', 'missed', 'splits', 'merges',\n                      'gained', 'catastrophes', 'correct']\n\n        # Background is set to zero\n        plotting_tif = np.zeros_like(y_true)\n\n        # missed detections are tracked with true labels\n        misses = [d.true_index for d in self._missed]\n        plotting_tif[np.isin(y_true, misses)] = 1\n\n        # skip background and misses, already done\n        for i, category in enumerate(categories[2:]):\n            # the rest are all on y_pred\n            labels = list(getattr(self, '_{}'.format(category)))\n            plotting_tif[np.isin(y_pred, labels)] = i + 2\n\n        plotting_colors = ['Black', 'Pink', 'Blue', 'Green',\n                           'tan', 'Red', 'Grey']\n\n        cmap = mpl.colors.ListedColormap(plotting_colors)\n\n        fig, ax = plt.subplots(nrows=1, ncols=1)\n        mat = ax.imshow(plotting_tif, cmap=cmap,\n                        vmin=np.min(plotting_tif) - .5,\n                        vmax=np.max(plotting_tif) + .5)\n\n        # tell the colorbar to tick at integers\n        ticks = np.arange(len(categories))\n        cbar = fig.colorbar(mat, ticks=ticks)\n        cbar.ax.set_yticklabels(categories)\n        fig.tight_layout()\n\n\nclass Metrics(object):\n    \"\"\"Class to calculate and save various segmentation metrics.\n\n    Args:\n        model_name (str): Name of the model which determines output file names\n        outdir (:obj:`str`, optional): Directory to save json file, default ''\n        cutoff1 (:obj:`float`, optional): Threshold for overlap in cost matrix,\n            smaller values are more conservative, default 0.4\n        cutoff2 (:obj:`float`, optional): Threshold for overlap in unassigned\n            cells, smaller values are better, default 0.1\n        pixel_threshold (:obj:`float`, optional): Threshold for converting\n            predictions to binary\n        ndigits (:obj:`int`, optional): Sets number of digits for rounding,\n            default 4\n        feature_key (:obj:`list`, optional): List of strings, feature names\n        json_notes (:obj:`str`, optional): Str providing any additional\n            information about the model\n        force_event_links(:obj:`bool`, optional): Flag that determines whether to modify IOU\n            calculation so that merge or split events with cells of very different sizes are\n            never misclassified as misses/gains.\n        is_3d(:obj:`bool`, optional): Flag that determines whether or not the input data\n            should be treated as 3-dimensional.\n\n    Examples:\n        >>> from deepcell import metrics\n        >>> m = metrics.Metrics('model_name')\n        >>> all_metrics = m.run_all(y_true, y_pred)\n        >>> m.save_to_json(all_metrics)\n    \"\"\"\n    def __init__(self, model_name,\n                 outdir='',\n                 cutoff1=0.4,\n                 cutoff2=0.1,\n                 pixel_threshold=0.5,\n                 ndigits=4,\n                 crop_size=None,\n                 feature_key=[],\n                 json_notes='',\n                 force_event_links=False,\n                 is_3d=False,\n                 **kwargs):\n        self.model_name = model_name\n        self.outdir = outdir\n        self.cutoff1 = cutoff1\n        self.cutoff2 = cutoff2\n        self.pixel_threshold = pixel_threshold\n        self.ndigits = ndigits\n        self.crop_size = crop_size\n        self.feature_key = feature_key\n        self.json_notes = json_notes\n        self.force_event_links = force_event_links\n        self.is_3d = is_3d\n\n        if 'seg' in kwargs:\n            warnings.warn('seg is deprecated and will be removed '\n                          'in a future release', DeprecationWarning)\n\n        # Initialize output list to collect stats\n        self.object_metrics = []\n        self.pixel_metrics = []\n\n    def df_to_dict(self, df, stat_type='pixel'):\n        \"\"\"Output pandas df as a list of dictionary objects\n\n        Args:\n            df (pandas.DataFrame): Dataframe of statistics for each channel\n            stat_type (str): Category of statistic.\n\n        Returns:\n            list: List of dictionaries\n        \"\"\"\n\n        # Initialize output dictionary\n        L = []\n\n        # Write out average statistics\n        for k, v in df.mean().iteritems():\n            L.append(dict(\n                name=k,\n                value=v,\n                feature='average',\n                stat_type=stat_type,\n            ))\n\n        # Save individual stats to list\n        for i, row in df.iterrows():\n            for k, v in row.iteritems():\n                L.append(dict(\n                    name=k,\n                    value=v,\n                    feature=i,\n                    stat_type=stat_type,\n                ))\n\n        return L\n\n    def calc_pixel_stats(self, y_true, y_pred, axis=-1):\n        \"\"\"Calculate pixel statistics for each feature.\n\n        ``y_true`` should have the appropriate transform applied to match\n        ``y_pred``. Each channel is converted to binary using the threshold\n        ``pixel_threshold`` prior to calculation of accuracy metrics.\n\n        Args:\n            y_true (numpy.array): Ground truth annotations after transform\n            y_pred (numpy.array): Model predictions without labeling\n\n        Returns:\n            list: list of dictionaries with each stat being a key.\n\n        Raises:\n            ValueError: If y_true and y_pred are not the same shape\n        \"\"\"\n        n_features = y_pred.shape[axis]\n\n        pixel_metrics = []\n\n        slc = [slice(None)] * y_pred.ndim\n        for i in range(n_features):\n            slc[axis] = slice(i, i + 1)\n            yt = y_true[slc] > self.pixel_threshold\n            yp = y_pred[slc] > self.pixel_threshold\n            pm = PixelMetrics(yt, yp)\n            pixel_metrics.append(pm.to_dict())\n\n        pixel_df = pd.DataFrame.from_records(pixel_metrics)\n\n        # Calculate confusion matrix\n        cm = PixelMetrics.get_confusion_matrix(y_true, y_pred, axis=axis)\n\n        print('\\n____________Pixel-based statistics____________\\n')\n        print(pixel_df)\n        print('\\nConfusion Matrix')\n        print(cm)\n\n        output = self.df_to_dict(pixel_df)\n\n        output.append(dict(\n            name='confusion_matrix',\n            value=cm.tolist(),\n            feature='all',\n            stat_type='pixel'\n        ))\n        return output\n\n    def calc_pixel_confusion_matrix(self, y_true, y_pred, axis=-1):\n        \"\"\"DEPRECATED: Use ``PixelMetrics.get_confusion_matrix``.\n\n        Calculate confusion matrix for pixel classification data.\n\n        Args:\n            y_true (numpy.array): Ground truth annotations after any\n                necessary transformations\n            y_pred (numpy.array): Prediction array\n            axis (int): The channel axis of the input arrays.\n\n        Returns:\n            numpy.array: nxn confusion matrix determined by number of features.\n        \"\"\"\n        return PixelMetrics.get_confusion_matrix(y_true, y_pred, axis=axis)\n\n    def calc_object_stats(self, y_true, y_pred, progbar=True):\n        \"\"\"Calculate object statistics and save to output\n\n        Loops over each frame in the zeroth dimension, which should pass in\n        a series of 2D arrays for analysis. 'metrics.split_stack' can be\n        used to appropriately reshape the input array if necessary\n\n        Args:\n            y_true (numpy.array): Labeled ground truth annotations\n            y_pred (numpy.array): Labeled prediction mask\n            progbar (bool): Whether to show the progress tqdm progress bar\n\n        Returns:\n            list: list of dictionaries with each stat being a key.\n\n        Raises:\n            ValueError: If y_true and y_pred are not the same shape\n            ValueError: If data_type is 2D, if input shape does not have ndim 3 or 4\n            ValueError: If data_type is 3D, if input shape does not have ndim 4\n        \"\"\"\n        if y_pred.shape != y_true.shape:\n            raise ValueError('Input shapes need to match. Shape of prediction '\n                             'is: {}.  Shape of y_true is: {}'.format(\n                                 y_pred.shape, y_true.shape))\n\n        # If 2D, dimensions can be 3 or 4 (with or without channel dimension)\n        if not self.is_3d:\n            if y_true.ndim not in {3, 4}:\n                raise ValueError('Expected dimensions for y_true (2D data) are 3 or 4.'\n                                 'Accepts: (batch, x, y), or (batch, x, y, chan)'\n                                 'Got ndim: {}'.format(y_true.ndim))\n\n        # If 3D, inputs must have 4 dimensions (batch, z, x, y) - cannot have channel dimension or\n        # _classify_graph breaks, as it expects input to be 2D or 3D\n        # TODO - add compatibility for multi-channel 3D-data\n        else:\n            if y_true.ndim != 4:\n                raise ValueError('Expected dimensions for y_true (3D data) is 4. '\n                                 'Required format is: (batch, z, x, y) '\n                                 'Got ndim: {}'.format(y_true.ndim))\n\n        all_object_metrics = []  # store all calculated metrics\n        is_batch_relabeled = False  # used to warn if batches were relabeled\n\n        for i in tqdm(range(y_true.shape[0]), disable=not progbar):\n            # check if labels aren't sequential, raise warning on first occurence if so\n            true_batch, pred_batch = y_true[i], y_pred[i]\n            true_batch_relabel, _, _ = relabel_sequential(true_batch)\n            pred_batch_relabel, _, _ = relabel_sequential(pred_batch)\n\n            # check if segmentations were relabeled\n            if not is_batch_relabeled:  # only one True is required\n                is_batch_relabeled = not (\n                    np.array_equal(true_batch, true_batch_relabel)\n                    and np.array_equal(pred_batch, pred_batch_relabel)\n                )\n\n            o = ObjectMetrics(\n                true_batch_relabel,\n                pred_batch_relabel,\n                cutoff1=self.cutoff1,\n                cutoff2=self.cutoff2,\n                force_event_links=self.force_event_links,\n                is_3d=self.is_3d)\n\n            all_object_metrics.append(o)\n\n        if is_batch_relabeled:\n            warnings.warn(\n                'Provided data is being relabeled. Cell ids from metrics will not match '\n                'cell ids in original data. Relabel your data prior to running the '\n                'metrics package if you wish to maintain cell ids. ')\n\n        # print the object report\n        object_metrics = pd.DataFrame.from_records([\n            o.to_dict() for o in all_object_metrics\n        ])\n        self.print_object_report(object_metrics)\n        return object_metrics\n\n    def summarize_object_metrics_df(self, df):\n        correct_detections = int(df['correct_detections'].sum())\n        n_true = int(df['n_true'].sum())\n        n_pred = int(df['n_pred'].sum())\n\n        _round = lambda x: round(x, self.ndigits)\n\n        seg = df['seg'].mean()\n        jaccard = df['jaccard'].mean()\n\n        try:\n            recall = correct_detections / n_true\n        except ZeroDivisionError:\n            recall = np.nan\n        try:\n            precision = correct_detections / n_pred\n        except ZeroDivisionError:\n            precision = 0\n\n        errors = [\n            'gained_detections',\n            'missed_detections',\n            'split',\n            'merge',\n            'catastrophe',\n        ]\n\n        bad_detections = [\n            'gained_det_from_split',\n            'missed_det_from_merge',\n            'true_det_in_catastrophe',\n            'pred_det_in_catastrophe',\n        ]\n\n        summary = {\n            'correct_detections': correct_detections,\n            'n_true': n_true,\n            'n_pred': n_pred,\n            'recall': _round(recall),\n            'precision': _round(precision * 100),\n            'seg': _round(seg * 100),\n            'jaccard': _round(jaccard),\n            'total_errors': 0,\n        }\n        # update bad detections\n        for k in bad_detections:\n            summary[k] = int(df[k].sum())\n        # update error counts\n        for k in errors:\n            count = int(df[k].sum())\n            summary[k] = count\n            summary['total_errors'] += count\n        return summary\n\n    def print_object_report(self, object_metrics):\n        \"\"\"Print neat report of object based statistics\n\n        Args:\n            object_metrics (pd.DataFrame): DataFrame of all calculated metrics\n        \"\"\"\n        summary = self.summarize_object_metrics_df(object_metrics)\n        errors = [\n            'gained_detections',\n            'missed_detections',\n            'split',\n            'merge',\n            'catastrophe'\n        ]\n\n        bad_detections = [\n            'gained_det_from_split',\n            'missed_det_from_merge',\n            'true_det_in_catastrophe',\n            'pred_det_in_catastrophe',\n        ]\n\n        print('\\n____________Object-based statistics____________\\n')\n        print('Number of true cells:\\t\\t', summary['n_true'])\n        print('Number of predicted cells:\\t', summary['n_pred'])\n\n        print('\\nCorrect detections:  {}\\tRecall: {}%'.format(\n            summary['correct_detections'], summary['recall']))\n\n        print('Incorrect detections: {}\\tPrecision: {}%'.format(\n            summary['n_pred'] - summary['correct_detections'],\n            summary['precision']))\n\n        print('\\n')\n        for k in errors:\n            v = summary[k]\n            name = k.replace('_', ' ').capitalize()\n            if not name.endswith('s'):\n                name += 's'\n\n            try:\n                err_fraction = v / summary['total_errors']\n            except ZeroDivisionError:\n                err_fraction = 0\n\n            print('{name}: {val}{tab}Perc Error {percent}%'.format(\n                name=name, val=v,\n                percent=round(100 * err_fraction, self.ndigits),\n                tab='\\t' * (1 if ' ' in name else 2)))\n\n        for k in bad_detections:\n            name = k.replace('_', ' ').capitalize().replace(' det ', ' detections')\n            print('{name}: {val}'.format(name=name, val=summary[k]))\n\n        print('SEG:', round(summary['seg'], self.ndigits), '\\n')\n\n        print('Average Pixel IOU (Jaccard Index):',\n              round(summary['jaccard'], self.ndigits), '\\n')\n\n    def run_all(self, y_true, y_pred, axis=-1):\n        object_metrics = self.calc_object_stats(y_true, y_pred)\n        pixel_metrics = self.calc_pixel_stats(y_true, y_pred, axis=axis)\n\n        object_list = self.df_to_dict(object_metrics, stat_type='object')\n        all_output = object_list + pixel_metrics\n        self.save_to_json(all_output)\n\n    def save_to_json(self, L):\n        \"\"\"Save list of dictionaries to json file with file metadata\n\n        Args:\n            L (list): List of metric dictionaries\n        \"\"\"\n        todays_date = datetime.datetime.now().strftime('%Y-%m-%d')\n        outname = os.path.join(\n            self.outdir, '{}_{}.json'.format(self.model_name, todays_date))\n\n        # Configure final output\n        D = {}\n\n        # Record metadata\n        D['metadata'] = dict(\n            model_name=self.model_name,\n            date=todays_date,\n            notes=self.json_notes\n        )\n\n        # Record metrics\n        D['metrics'] = L\n\n        with open(outname, 'w') as outfile:\n            json.dump(D, outfile)\n\n        logging.info('Saved to {}'.format(outname))\n\n\ndef split_stack(arr, batch, n_split1, axis1, n_split2, axis2):\n    \"\"\"Crops an array in the width and height dimensions to produce\n    a stack of smaller arrays\n\n    Args:\n        arr (numpy.array): Array to be split with at least 2 dimensions\n        batch (bool): True if the zeroth dimension of arr is a batch or\n            frame dimension\n        n_split1 (int): Number of sections to produce from the first split axis\n            Must be able to divide arr.shape[axis1] evenly by n_split1\n        axis1 (int): Axis on which to perform first split\n        n_split2 (int): Number of sections to produce from the second split axis\n            Must be able to divide arr.shape[axis2] evenly by n_split2\n        axis2 (int): Axis on which to perform first split\n\n    Returns:\n        numpy.array: Array after dual splitting with frames in the zeroth dimension\n\n    Raises:\n        ValueError: arr.shape[axis] must be evenly divisible by n_split\n            for both the first and second split\n\n    Examples:\n        >>> from deepcell import metrics\n        >>> from numpy import np\n        >>> arr = np.ones((10, 100, 100, 1))\n        >>> out = metrics.split_stack(arr, True, 10, 1, 10, 2)\n        >>> out.shape\n        (1000, 10, 10, 1)\n        >>> arr = np.ones((100, 100, 1))\n        >>> out = metrics.split_stack(arr, False, 10, 1, 10, 2)\n        >>> out.shape\n        (100, 10, 10, 1)\n    \"\"\"\n    # Check that n_split will divide equally\n    if ((arr.shape[axis1] % n_split1) != 0) | ((arr.shape[axis2] % n_split2) != 0):\n        raise ValueError(\n            'arr.shape[axis] must be evenly divisible by n_split'\n            'for both the first and second split')\n\n    split1 = np.split(arr, n_split1, axis=axis1)\n\n    # If batch dimension doesn't exist, create and adjust axis2\n    if batch is False:\n        split1con = np.stack(split1)\n        axis2 += 1\n    else:\n        split1con = np.concatenate(split1, axis=0)\n\n    split2 = np.split(split1con, n_split2, axis=axis2)\n    split2con = np.concatenate(split2, axis=0)\n\n    return split2con\n\n\ndef match_nodes(y_true, y_pred):\n    \"\"\"Loads all data that matches each pattern and compares the graphs.\n\n    Args:\n        y_true (numpy.array): ground truth array with all cells labeled uniquely.\n        y_pred (numpy.array): data array to match to unique.\n\n    Returns:\n        numpy.array: IoU of ground truth cells and predicted cells.\n    \"\"\"\n    num_frames = y_true.shape[0]\n    # TODO: does max make the shape bigger than necessary?\n    iou = np.zeros((num_frames, np.max(y_true) + 1, np.max(y_pred) + 1))\n\n    # Compute IOUs only when neccesary\n    # If bboxs for true and pred do not overlap with each other, the assignment\n    # is immediate. Otherwise use pixelwise IOU to determine which cell is which\n\n    # Regionprops expects one frame at a time\n    for frame in range(num_frames):\n        gt_frame = y_true[frame]\n        res_frame = y_pred[frame]\n\n        gt_props = regionprops(np.squeeze(gt_frame.astype('int')))\n        gt_boxes = [np.array(gt_prop.bbox) for gt_prop in gt_props]\n        gt_boxes = np.array(gt_boxes).astype('double')\n        gt_box_labels = [int(gt_prop.label) for gt_prop in gt_props]\n\n        res_props = regionprops(np.squeeze(res_frame.astype('int')))\n        res_boxes = [np.array(res_prop.bbox) for res_prop in res_props]\n        res_boxes = np.array(res_boxes).astype('double')\n        res_box_labels = [int(res_prop.label) for res_prop in res_props]\n\n        # has the form [gt_bbox, res_bbox]\n        overlaps = compute_overlap(gt_boxes, res_boxes)\n\n        # Find the bboxes that have overlap at all\n        # (ind_ corresponds to box number - starting at 0)\n        ind_gt, ind_res = np.nonzero(overlaps)\n\n        # frame_ious = np.zeros(overlaps.shape)\n        for index in range(ind_gt.shape[0]):\n            iou_gt_idx = gt_box_labels[ind_gt[index]]\n            iou_res_idx = res_box_labels[ind_res[index]]\n            intersection = np.logical_and(\n                gt_frame == iou_gt_idx, res_frame == iou_res_idx)\n            union = np.logical_or(\n                gt_frame == iou_gt_idx, res_frame == iou_res_idx)\n            iou[frame, iou_gt_idx, iou_res_idx] = intersection.sum() / union.sum()\n\n    return iou\n", "meta": {"hexsha": "a60b458e928a8bf6c5e7bd68d17c573d4dd1cd1a", "size": 49805, "ext": "py", "lang": "Python", "max_stars_repo_path": "deepcell_toolbox/metrics.py", "max_stars_repo_name": "vanvalenlab/deepcell-toolbox", "max_stars_repo_head_hexsha": "7df2e11284147e2afa976584074e02488c26e834", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-16T21:15:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T05:19:50.000Z", "max_issues_repo_path": "deepcell_toolbox/metrics.py", "max_issues_repo_name": "vanvalenlab/deepcell-toolbox", "max_issues_repo_head_hexsha": "7df2e11284147e2afa976584074e02488c26e834", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 81, "max_issues_repo_issues_event_min_datetime": "2019-03-26T18:27:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T21:41:18.000Z", "max_forks_repo_path": "deepcell_toolbox/metrics.py", "max_forks_repo_name": "vanvalenlab/deepcell-toolbox", "max_forks_repo_head_hexsha": "7df2e11284147e2afa976584074e02488c26e834", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-01-30T12:54:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T04:05:45.000Z", "avg_line_length": 36.4604685212, "max_line_length": 98, "alphanum_fraction": 0.6126493324, "include": true, "reason": "import numpy,from numpy,from scipy,import networkx", "num_tokens": 11323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.3557748866829643, "lm_q1q2_score": 0.19037458280886502}}
{"text": "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport itertools\nimport numpy as np\nimport re\n\nfrom .linalg import dot, matmul, transpose\nfrom .manipulation import squeeze, unsqueeze, reshape\nfrom .math import multiply\nfrom .math import sum as paddle_sum\nfrom ..fluid.framework import _in_legacy_dygraph\nfrom paddle import _C_ops\nfrom ..fluid.data_feeder import check_variable_and_dtype, check_type, check_dtype\nfrom ..fluid.layer_helper import LayerHelper\nfrom ..fluid.framework import _non_static_mode, in_dygraph_mode, _in_legacy_dygraph\nimport collections\nimport string\nimport opt_einsum\n\nfrom paddle.common_ops_import import dygraph_only\n\n__all__ = []\n\n\ndef parse_op_labels(labelstr, operand):\n    '''\n    Parse labels for an input operand.\n\n    Parameters\n    ----------\n    labelstr:\n        the input label string\n    operand:\n        the input operand\n\n    Returns\n    -------\n    the input operand's full label string in which all anonymous dimensions are \n    labeled in dots. \n    '''\n    # Sanity checks\n    for c in labelstr.replace('.', ''):\n        assert c.isalpha(), (\n            f\"Invalid equation: {c} is not a valid label, which should be letters.\"\n        )\n\n    assert labelstr.replace('...', '', 1).find('.') == -1, (\n        f\"Invalid equation: `.` is found outside of an ellipsis.\")\n\n    # Check shape. Note, in Paddle a tensor rank is always nonzero\n    ndims = len(operand.shape)\n    assert ndims > 0\n\n    full_labelstr = labelstr.replace('...', '.' * (ndims - len(labelstr) + 3))\n\n    assert len(full_labelstr) == ndims, (\n        f\"Invalid equation: the label string '{labelstr}' misses dimensions.\")\n\n    return full_labelstr\n\n\ndef parse_labels(labelstr, operands):\n    '''\n    Parse label strings for all input operands.\n    \n    Parameters\n    ----------\n    labelstr:\n        The equation's label string\n    operands:\n        The input operands\n    \n    Returns\n    -------\n    list of full label strings for all input operands\n    '''\n\n    nop_labels = labelstr.split(',')\n    assert len(nop_labels) == len(operands), (\n        f\"Invalid equation: the number of operands is {len(operands)}, \"\n        f\"but found {len(nop_labels)} segments in the label equation.\")\n\n    return list(map(parse_op_labels, nop_labels, operands))\n\n\ndef validate_rhs(rhs, input_labels, n_bcast_dims):\n    '''\n    Check whether the equation's right hand side is valid \n    '''\n    # Sanity check.\n    if n_bcast_dims > 0:\n        assert '...' in rhs, (\n            f\"Invalid equation: missing ellipsis in output labels.\")\n\n    rhs = rhs.replace('...', '')\n    rhs_set = set(rhs)\n\n    # Hidden assumption: availble labels don't include '.'\n    assert '.' not in input_labels\n\n    # Verify that output labels all come from the set of input labels\n    non_input_labels = rhs_set.difference(input_labels)\n    assert not non_input_labels, (\n        f\"Invalid equation: \"\n        f\"output label {sorted(non_input_labels)} not used by any input.\")\n    # Verify that output labels are not duplicate\n    assert len(rhs) == len(rhs_set), (\n        f\"Invalid equation: duplicate output labels are found.\")\n\n\ndef build_view(in_labels, out_labels):\n    '''\n    Build an inverse map of dimension indices. Three conditions must hold for \n    the result to be meaningful. \n    First, no duplicate letter labels in each label string.\n    Second, the number of dots in dimout_labels >= that in in_labels.\n    Third, dots are contiguous in each label string.\n\n    Parameters\n    ----------\n    in_labels:\n        The dimension labels to map to\n    out_labels:\n        The dimension labels to map from\n    \n    Returns\n    -------\n    The inverse map from out_labels to in_labels. The length of the inverse map equals that of\n    out_labels. -1 is filled if there's no matching intput dimension for a specific label.\n\n    Examples\n    --------\n    in_labels = 'ij..', out_labels = '..ji'\n    inv_map = [2, 3, 1, 0]\n    in_labels = 'ij..', out_labels = '..kji'\n    inv_map = [2, 3, -1, 1, 0]\n    '''\n\n    inv_map = [-1] * len(out_labels)\n\n    # First build the broadcast dimension mapping\n    # Find the broadcast index range in out_labels\n    r = re.search(r'\\.+', out_labels)\n    if r:\n        start, end = r.start(), r.end()\n        s = re.search(r'\\.+', in_labels)\n        # fill the broadcast dimension indices from right to left.\n        if s:\n            for ax, dim in zip(\n                    range(start, end)[::-1], range(s.start(), s.end())[::-1]):\n                inv_map[ax] = dim\n\n    # Now work on non-broadcast dimensions \n    if r:\n        it = itertools.chain(range(start), range(end, len(out_labels)))\n    else:\n        it = iter(range(len(out_labels)))\n\n    for i in it:\n        inv_map[i] = in_labels.find(out_labels[i])\n\n    return inv_map\n\n\ndef build_global_view(nop_labels, rhs, n_bcast_dims):\n    '''\n    Build the global view, which is a layout of all dimension labels\n    plus an index table that maps from the layout to the dimensions\n    in each operand. In the global view, the dimensions are arranged\n    such that output ones are put on the left and contraction ones\n    are put on the right.  \n\n    Parameters\n    ----------\n    nop_labels:\n        The input full label strings of all input operands\n    rhs:\n        The equation right hand side\n    n_bcast_dims:\n        The maxium number of broadcast dimensions\n    \n    Returns\n    -------\n    A tuple of g_labels, g_view, g_nout, g_count\n    g_labels:\n        the layout of all labels in a string\n    g_view:\n        the index table\n    g_nout:\n        the number of output dimensions\n    g_count:\n        the counter array for dimension contractions\n    '''\n    # Put all labels in alphabetical order\n    concat = sorted(''.join(nop_labels).replace('.', ''))\n    labels, count = [], []\n    for a, b in zip(['.'] + concat, concat):\n        if a != b:\n            labels.append(b)\n            count.append(1)\n        else:\n            count[-1] += 1\n\n    if rhs != None:\n        validate_rhs(rhs, labels, n_bcast_dims)\n        g_labels_out = rhs.replace('...', '.' * n_bcast_dims)\n    else:\n        g_labels_out = '.' * n_bcast_dims + ''.join(\n            l for l, c in zip(labels, count) if c == 1)\n\n    for i in range(len(count))[::-1]:\n        if labels[i] in g_labels_out:\n            labels.pop(i)\n            count.pop(i)\n\n    g_labels_sum = ''.join(labels)\n    g_labels = g_labels_out + g_labels_sum\n    g_view = list(map(lambda i: build_view(i, g_labels), nop_labels))\n    g_nout = len(g_labels_out)\n    g_count = count\n\n    return g_labels, g_view, g_nout, g_count\n\n\ndef build_global_shape(g_view, g_labels, op_shapes):\n    '''\n    The global shape is the shape of all dimensions rearranged and broadcasting \n    to the global view. It's a reference data structure for einsum planning.\n\n    Parameters\n    ----------\n    g_view:\n        the global view\n    op_shapes:\n        the shapes of the all operands\n\n    Returns\n    -------\n    g_shape:\n        the global shape vector\n    g_masks:\n        list of shape masks for each operand. A dimension's shape mask is a boolean\n        indicating whether its size > 1, in other words, it's not squeezable\n    '''\n    view_shapes = []\n    g_masks = []\n\n    for view, op_shape in zip(g_view, op_shapes):\n        view_shapes.append([op_shape[dim] if dim > -1 else 1 for dim in view])\n\n    g_shape = [set(sizes_per_ax) - {1} for sizes_per_ax in zip(*view_shapes)]\n\n    non_bcastable = [ax for ax, sizes in enumerate(g_shape) if len(sizes) > 1]\n\n    assert not non_bcastable, (\n        f\"Invalid operands: label {g_labels[non_bcastable[0]]} \"\n        f\"corresponds to non-broadcastable dimensions.\")\n\n    g_shape = [sizes.pop() if len(sizes) > 0 else 1 for sizes in g_shape]\n\n    g_masks = [[s > 1 or s == -1 for s in view_shape]\n               for view_shape in view_shapes]\n\n    return g_shape, g_masks\n\n\ndef has_duplicated_labels(labels):\n    '''\n    Returns True if there is any duplicate label.\n    '''\n    labels = labels.replace('.', '')\n    return len(labels) > len(set(labels))\n\n\ndef diagonalize(labels, operand):\n    '''\n    Merges dimensions with duplicate labels. \n    \n    For those dimensions with duplicate labels, merge them into one dimension\n    which represents the diagonal elements. This requires the dimensions with\n    duplicate labels are equal sized.\n    \n    Examples\n    -------- \n    'ijj...i' would be merged into 'ij...'\n    '''\n    assert not has_duplicated_labels(labels), (\n        f'Duplicate labels are not supported.')\n\n    return labels, operand\n\n\ndef plan_reduce(plan, op, reduce_dims, keepdim):\n    '''\n    Add reduce to the plan\n    '''\n    varname = f'op{op}'\n\n    f = lambda var, dims: paddle_sum(var, dims, keepdim=keepdim)\n    step = f, [varname], varname, reduce_dims\n    plan.add_step(step)\n\n\ndef plan_scalar_prod(plan, op1, op2):\n    varnames = [f'op{op1}', f'op{op2}']\n    f = lambda var1, var2: paddle_sum(var1) * var2\n    # f = lambda var1, var2: var1 * var2\n    step = f, varnames, varnames[1]\n    plan.add_step(step)\n\n\ndef plan_matmul(plan, g_view, op1, op2, g_supports, g_shape, I, J1, J2, K):\n    '''\n    plan matmul\n    '''\n    # Transpose and re-shape op1 and op2 in I, J1, K and I, J2, K\n    # Then apply matmul(x, y, transpose_x=False, tranpose_y=True)\n    var1, var2 = f'op{op1}', f'op{op2}'\n\n    op1_view, op2_view = [g_view[op] for op in (op1, op2)]\n\n    I1 = [idx for idx in I if op1_view[idx] >= 0]\n    I2 = [idx for idx in I if op2_view[idx] >= 0]\n    op1_view = np.array(op1_view)\n    op1_dims = op1_view[I1 + J1 + K]\n\n    op2_view = np.array(op2_view)\n    op2_dims = op2_view[I2 + J2 + K]\n\n    op1_mask, op2_mask = [g_supports[op] for op in (op1, op2)]\n    op1_vshape = np.array([s if m else 1 for s, m in zip(g_shape, op1_mask)])\n    op2_vshape = np.array([s if m else 1 for s, m in zip(g_shape, op2_mask)])\n    vshape = np.maximum(op1_vshape, op2_vshape)\n\n    i1, i2, j1, j2, k = map(len, (I1, I2, J1, J2, K))\n\n    if any(op1_dims != np.arange(len(op1_dims))):\n        # print(f'perm1: {perm1}')\n        step = transpose, [var1], var1, list(op1_dims)\n        plan.add_step(step)\n\n    if any(op2_dims != np.arange(len(op2_dims))):\n        # print(f'perm2: {perm2}')\n        step = transpose, [var2], var2, list(op2_dims)\n        plan.add_step(step)\n\n    # Check if conditions hold for turnning the operation into a matmul\n    if j1 + j2 > 0 and k > 0 and -1 not in np.concatenate(\n        (op1_vshape, op2_vshape)):\n        op1_shape = list(op1_vshape[I]) + [np.prod(op1_vshape[J1])\n                                           ] + [np.prod(op1_vshape[K])]\n        op2_shape = list(op2_vshape[I]) + [np.prod(op2_vshape[J2])\n                                           ] + [np.prod(op2_vshape[K])]\n\n        # Merge J dims and K dims by reshaping\n        step = reshape, [var1], var1, op1_shape\n        plan.add_step(step)\n        step = reshape, [var2], var2, op2_shape\n        plan.add_step(step)\n\n        # Matmul\n        step = matmul, [var1, var2], var2, False, True\n        plan.add_step(step)\n\n        # Reshape back\n        shape = list(vshape[I + J1 + J2])\n        step = reshape, [var2], var2, shape\n        plan.add_step(step)\n\n    elif j1 == j2 == k == 1:\n        # Can still do matmul even unknown shapes are present\n        step = matmul, [var1, var2], var2, False, True\n        plan.add_step(step)\n\n    # In the rest cases we opt for ops other than matmul \n    else:\n        # unsqueeze operands include J1...J2... dimensions\n        if j2:\n            fill = list(range(i1 + j1, i1 + j1 + j2))\n            step = unsqueeze, [var1], var1, fill\n            plan.add_step(step)\n        if j1:\n            fill = list(range(i2, i2 + j1))\n            step = unsqueeze, [var2], var2, fill\n            plan.add_step(step)\n        # In case of no dimensions to contract, do an elementwise multiply\n        if k == 0:\n            # make broadcast\n            step = multiply, [var1, var2], var2\n            plan.add_step(step)\n        # Contract and no join, turn into a dot\n        elif j1 + j2 == 0 and k == 1:\n            step = unsqueeze, [var1], var1, [-2]\n            plan.add_step(step)\n            step = unsqueeze, [var2], var2, [-1]\n            plan.add_step(step)\n            step = matmul, [var1, var2], var2\n            plan.add_step(step)\n            step = squeeze, [var2], var2, [-1, -2]\n            plan.add_step(step)\n        elif j1 + j2 == 0 and not-1 in np.concatenate(\n            (op1_vshape[K], op2_vshape[K])):\n            assert all(op1_vshape[K] == op2_vshape[K])\n            step = reshape, [var1], var1, list(op1_vshape[\n                I]) + [1] + [np.prod(op1_vshape[K])]\n            plan.add_step(step)\n            step = reshape, [var2], var2, list(op2_vshape[\n                I]) + [1] + [np.prod(op2_vshape[K])]\n            plan.add_step(step)\n            step = matmul, [var1, var2], var2, False, True\n            plan.add_step(step)\n            step = squeeze, [var2], var2, [-1, -2]\n            plan.add_step(step)\n        else:\n            step = multiply, [var1, var2], var2\n            plan.add_step(step)\n            reduce_dims = list(range(-k, 0))\n            plan_reduce(plan, op2, reduce_dims, keepdim=False)\n\n    # Wrap up, updating auxiliary data\n    # Updating g_mask for I and J axes\n    for ax in I + J1 + J2:\n        op2_mask[ax] = vshape[ax] > 1 or vshape[ax] == -1\n\n    for ax in K:\n        op2_mask[ax] = False\n\n    for ax in range(len(op2_view)):\n        op2_view[ax] = -1\n    dim = 0\n    for ax in I + J1 + J2:\n        op2_view[ax], dim = dim, dim + 1\n\n    g_view[op2] = list(op2_view)\n\n\ndef plan_summation(plan, g_view, op1, op2, g_supports, g_shape, g_count,\n                   n_bcast):\n    '''\n    Plan various kinds of summation\n    '''\n    op1_view, op2_view = g_view[op1], g_view[op2]\n    op1_mask, op2_mask = g_supports[op1], g_supports[op2]\n\n    ndim = len(op1_view)\n    nout = ndim - len(g_count)\n\n    count = [0] * nout + g_count\n\n    I, K, J1, J2 = list(range(n_bcast)), [], [], []\n\n    for ax, dim1, dim2 in zip(\n            range(n_bcast, ndim), op1_view[n_bcast:], op2_view[n_bcast:]):\n\n        if (dim1 != -1) != (dim2 != -1):\n            if dim1 != -1:\n                J1.append(ax)\n            else:\n                J2.append(ax)\n        elif dim1 != -1:\n            fold = int(op1_mask[ax]) + int(op2_mask[ax])\n            if ax >= nout and fold == count[ax]:\n                # Ready to fold the dimensions\n                K.append(ax)\n                count[ax] -= fold\n            else:\n                I.append(ax)\n                count[ax] -= max(fold - 1, 0)\n\n    # Update g_count\n    g_count[:] = count[nout:]\n\n    # Now it's OK to merge the K dims as the same shape holds\n    # print(f'I: {I}   J1: {J1}    J2: {J2}   K: {K}')\n    plan_matmul(plan, g_view, op1, op2, g_supports, g_shape, I, J1, J2, K)\n\n\ndef rearrange(axes):\n    perm, fill = [], []\n    for ax, dim in enumerate(axes):\n        if dim < 0:\n            fill.append(ax)\n        else:\n            perm.append(dim)\n    # Trivial permutation returns []\n    if all(i == dim for i, dim in enumerate(perm)):\n        perm = []\n\n    return perm, fill\n\n\ndef plan_broadcast(plan, operands, nop_axes):\n    '''\n    Plan broadcast across\n    '''\n    nop = len(operands)\n    varnames = [f'op{i}' for i in range(nop)]\n\n    for i, op_axes in zip(range(nop), nop_axes):\n        # Re-arrange the dimesions according to the global layout\n        perm, fill = rearrange(op_axes)\n        var = varnames[i]\n        if perm:\n            step = transpose, [var], var, perm\n            plan.add_step(step)\n        if fill:\n            step = unsqueeze, [var], var, fill\n            plan.add_step(step)\n\n    def f(*args):\n        expr = ' * '.join(varnames)\n        return eval(expr, dict(zip(varnames, args)))\n\n    step = f, varnames, None\n    plan.add_step(step)\n\n\nclass Plan:\n    def __init__(self):\n        self.env = {}\n        self.steps = []\n\n    def add_step(self, step):\n        self.steps.append(step)\n\n    def get_var(self, varname):\n        return self.env[varname] if varname in self.env else None\n\n    def set_var(self, varname, var):\n        self.env[varname] = var\n\n    def show(self):\n        res = None\n        for f, in_varnames, out_varname, *args in self.steps:\n            print(repr((out_varname, f, *in_varnames, *args)))\n        return res\n\n    def execute(self):\n        res = None\n        for f, in_varnames, out_varname, *args in self.steps:\n            res = f(*map(self.get_var, in_varnames), *args)\n            if out_varname:\n                self.set_var(out_varname, res)\n        return res\n\n\ndef plan_einsum(operands, g_view, g_shape, g_supports, g_count, n_bcast):\n    '''\n    Plans the actual execution steps.\n    Results\n    -------\n    the execution plan\n    '''\n    nop = len(operands)\n    ndim = len(g_view[0])\n    nout = ndim - len(g_count)\n\n    # Initialize a plan with an environment\n    plan = Plan()\n    op_names = [f'op{i}' for i in range(nop)]\n    list(map(plan.set_var, op_names, operands))\n\n    # In case no dimensions to combine, do broadcast straight across\n    if not g_count:\n        plan_broadcast(plan, operands, g_view)\n        return plan\n\n    # Down count degenerate contraction dimensions.\n    for view, support in zip(g_view, g_supports):\n        # To collect the down count number, we use a type casting trick\n        down_count = [\n            int((d + 1) and (not s))\n            for d, s in zip(view[nout:], support[nout:])\n        ]\n        for i, count in enumerate(down_count):\n            g_count[i] -= count\n\n    # Reduce any dimension for which g_support is set and g_count == 1\n    for i, view, mask in zip(range(nop), g_view, g_supports):\n        to_reduce = []\n        for dim, masked, count in zip(view[nout:], mask[nout:], g_count):\n            to_reduce.append(dim if (masked and count == 1) else -1)\n\n        reduce_dims = list(filter(lambda x: x > -1, to_reduce))\n        if reduce_dims:\n            plan_reduce(plan, i, reduce_dims, keepdim=True)\n\n        # Unset mask and decrease g_count for the reduced dimensions\n        for i, d in enumerate(to_reduce):\n            ax = i + nout\n            mask[ax] = mask[ax] and (d == -1)\n            g_count[i] -= 0 if d == -1 else 1\n\n    # Plan the summations over the operand sequence\n    for i in range(nop):\n        # plan a single step\n\n        if i == 0:\n            continue\n\n        # We'd like to arrange the dimensions in the following way:\n        # [I...  J... K...]\n        # [I...  J... K...]\n        # where  \n        #       I... are aligned and not to be combined immediately \n        #       J... are not aligned and not to be combined immediately\n        #       K... are aligned and should be immediately combined\n        # At this point the non-trivial broadcast dimensinos in K are already reduced\n        # and removed. That means all K dimensions are aligned and their sizes are not 1.\n        # We then inspect the layout of I,J,K plus the above observation to make\n        # specializatoin decisions.  The current strategy is set as follows:\n        #  (1) if I... J... K... are all empty, it's multiplying a scalar\n        #  (2) if K... are empty, better use a broadcast\n        #  (3) if I... J... empty and K... not empty, a vector-vector multiply (or a dot)\n        #  (4) Elsewise, either I... or J... not empty, and K... not empty, use a general matmul\n\n        # Resolve the summation kind: dot, matmul or *\n        if not any(g_supports[i - 1]):\n            # op1 is a one element tensor.\n            plan_scalar_prod(plan, i - 1, i)\n        else:\n            plan_summation(plan, g_view, i - 1, i, g_supports, g_shape, g_count,\n                           n_bcast)\n\n    # for ax, dim in enumerate(g_view[nop-1][:nout]):\n    #     assert dim == ax\n    assert all(not masked for masked in g_supports[nop - 1][nout:])\n\n    view = g_view[-1]\n    if any(ax != dim for ax, dim in enumerate(view[:nout])):\n        perm = [dim for dim in view if dim >= 0]\n        if sorted(perm) != perm:\n            varname = f'op{nop-1}'\n            step = transpose, [varname], varname, perm\n            plan.add_step(step)\n        dim = 0\n        unsqueeze_dims = []\n        for ax, d in enumerate(view):\n            if d != -1:\n                view[ax], dim = dim, dim + 1\n        for ax, d in enumerate(view[:nout]):\n            if d == -1:\n                unsqueeze_dims.append(ax)\n        if unsqueeze_dims:\n            varname = f'op{nop-1}'\n            step = unsqueeze, [varname], varname, unsqueeze_dims\n            plan.add_step(step)\n\n    squeeze_dims = [dim for dim in view[nout:] if dim != -1]\n    if squeeze_dims:\n        # plan_reduce(plan, nop-1, reduce_dims, keepdim=False)\n        varname = f'op{nop-1}'\n        step = squeeze, [varname], varname, squeeze_dims\n        plan.add_step(step)\n\n    return plan\n\n\ndef preprocess(equation, *operands):\n    \"\"\"\n    check equation / raise error, default right labels generation\n    \"\"\"\n    equation = equation.replace(\" \", \"\")\n    nop = len(operands)\n    assert nop > 0, \"Required at least one operand in Einsum API, but received %s \" % nop\n\n    # Part the equation to left hand side and right hand side\n    lhs, *rhs = equation.lower().split('->')\n    assert len(rhs) < 2, \"Invalid equation: multiple `->` were found.\"\n\n    labels = parse_labels(lhs, operands)\n    # Note, we distinguish between 'ij->' and 'ij' by setting rhs to '' and None\n    rhs = rhs[0] if rhs else None\n    if rhs is None:\n        rhs = rhs_inference(lhs)\n\n    assert len(lhs.split(',')) == len(operands), (\n        f\"Invalid equation: the number of operands is {len(operands)}, \"\n        f\"but found {len(lhs.split(','))} segments in the label equation.\")\n\n    assert not ('...' in lhs and '...' not in rhs\n                ), f'Invalid equation: missing ellipsis in output labels.'\n\n    assert not (len(list(filter(has_duplicated_labels, lhs.split(',')))) > 0\n                ), f'Duplicate labels are not supported.'\n\n    assert not has_duplicated_labels(\n        rhs), f'Invalid equation: duplicate output labels are found.'\n\n    return lhs, rhs, labels\n\n\ndef parse_fake_shape(equation, operands, labels):\n    \"\"\" \n    this shape is just used for operands planning. may differ with the original shape.\n    for example: \n    ... is replaced by 1\n    -1  is replaced by 1\n    Results\n    -------\n    list of shape\n    \"\"\"\n    shaped = collections.namedtuple('shaped', ['shape'])\n\n    def fake_shape(label, op):\n        assert len(op.shape) == len(\n            label\n        ), \"length of shape and length of label must be the same, but received %d != %d\" % (\n            len(op.shape), len(label))\n        fakes = [s for i, (l, s) in enumerate(zip(label, op.shape)) if l != '.']\n        fakes = list(map(abs, fakes))  # make -1 -> 1\n        if '.' in label:\n            fakes.insert(label.index('.'), 1)\n        return shaped(fakes)\n\n    out = list(map(fake_shape, labels, operands))\n    return out\n\n\ndef rhs_inference(lhs):\n    def is_free(key):\n        return cnt.get(key) == 1 and key not in ['.', ',']\n\n    cnt = collections.Counter(lhs)\n    rhs = \"...\" if '...' in lhs else \"\"\n    rhs = rhs + \"\".join(filter(is_free, sorted(cnt.elements())))\n    return rhs\n\n\ndef gen_equation_for_opteinsum(lhs, rhs):\n    \"\"\" \n    1. gen rhs if rhs is None\n    2. '...' -> 'A'\n    \"\"\"\n\n    def get_used_label(counter):\n        used = set(counter.elements())\n        for c in string.ascii_lowercase:\n            if c not in used: return c\n        raise ValueError(\n            \"You have used all `a` - `z`, there can't find a unused for einsum optimization\"\n        )\n\n    cnt = collections.Counter(lhs)\n    broadcast_label = get_used_label(cnt)\n    if rhs is None:\n        rhs = rhs_inference(lhs)\n    lhs = lhs.replace(\"...\", broadcast_label)\n    rhs = rhs.replace(\"...\", broadcast_label)\n    return lhs + \"->\" + rhs, broadcast_label\n\n\ndef einsum_v2(equation, *operands):\n    \"\"\" \n    einsum v2 implementation.\n    1. Implement C++ EinsumOp.\n    2. V2 create the EinsumOp to calculate, so just a little verifty work in python.\n    3. V2 use opt_einsum.contract_path to optimize the multivariable einsum.\n    \"\"\"\n    n_op = len(operands)\n    lhs, rhs, labels = preprocess(equation, *operands)\n\n    if n_op <= 2:\n        return gen_einsum_op(lhs + '->' + rhs, *operands)\n\n    shapes = parse_fake_shape(lhs, operands, labels)\n    opt_equation, broadcast_label = gen_equation_for_opteinsum(lhs, rhs)\n    _, cons = opt_einsum.contract_path(opt_equation, *shapes, einsum_call=True)\n    var_list = list(operands)\n    for path in cons:\n        (a, b), _, eq, *__ = path\n        assert a > b, \"Assume the first var_idx is smaller than the second_idx. opt_einsum can guarantee it.\"\n        var_s = [var_list.pop(a), var_list.pop(b)]\n        eq = eq.replace(broadcast_label, \"...\")\n        var_list.append(gen_einsum_op(eq, *var_s))\n    assert len(\n        var_list\n    ) == 1, \"There must be one elements in list, but received %d.\" % len(\n        var_list)\n    return var_list[0]\n\n\ndef gen_einsum_op(equation, *operands):\n    \"\"\" \n    EinsumOp Python Interface: \n    \"\"\"\n    assert len(operands) <= 2, \"Only support two operands in EinsumOp.\"\n    if in_dygraph_mode():\n        return _C_ops.final_state_einsum(operands, equation)[0]\n\n    if _in_legacy_dygraph():\n        # dygraph\n        return _C_ops.einsum(operands, len(operands), 'equation', equation)[0]\n\n    # static graph \n    for inp in operands:\n        check_variable_and_dtype(inp, 'dtype', ['float32', 'float64'], 'einsum')\n    check_type(equation, 'equation', str, 'einsum')\n    helper = LayerHelper('einsum', **locals())\n    out = helper.create_variable_for_type_inference(dtype=operands[0].dtype)\n    attrs = dict()\n    attrs['equation'] = equation\n    caches = [\n        helper.create_variable_for_type_inference(dtype=operands[0].dtype)\n        for i in range(len(operands))\n    ]\n    helper.append_op(\n        type='einsum',\n        inputs={'Operands': operands},\n        outputs={'Out': out,\n                 \"InnerCache\": caches},\n        attrs=attrs)\n    return out\n\n\ndef einsum(equation, *operands):\n    r\"\"\"\n    einsum(equation, *operands)\n\n    The current version of this API should be used in dygraph only mode.\n\n    Einsum offers a tensor operation API which allows using the Einstein summation\n    convention or Einstain notation. It takes as input one or multiple tensors and\n    produces as output one tensor.\n\n    Einsum is able to perform a variety of tensor operations. Following lists a few:\n\n        - for single operand\n            - trace\n            - diagonal\n            - transpose\n            - sum\n        - for double operands\n            - dot\n            - outer\n            - broadcasting and elementwise multiply\n            - matrix multiply\n            - batched matrix multiply\n        - for many operads\n            - broadcasting multiply\n            - chained matrix multiply\n    \n    **The summation notation**\n\n        - The tensor dimensions are labeled using uncased English letters. E.g., `ijk`\n        relates to a three dimensional tensor whose dimensions are labeled i, j, and k.\n        - The equation is `,` separated into terms, each being a distinct input's\n        dimension label string.\n        - Ellipsis `...` enables broadcasting by automatically converting the unlabeled\n        dimensions into broadcasting dimensions. \n        - Singular labels are called free labels, duplicate are dummy labels. Dummy labeled\n        dimensions will be reduced and removed in the output.\n        - Output labels can be explicitly specified on the right hand side of `->` or omitted.\n        In the latter case, the output labels will be inferred from the input labels.\n            - Inference of output labels\n                - Broadcasting label `...`, if present, is put on the leftmost position.\n                - Free labels are reordered alphabetically and put after `...`.\n            - On explicit output labels\n                - If broadcasting is enabled, then `...` must be present.\n                - The output labels can be an empty, an indication to output as a scalar\n                the sum over the original output.\n                - Non-input labels are invalid.\n                - Duplicate labels are invalid.\n                - For any dummmy label which is present for the output, it's promoted to\n                a free label.\n                - For any free label which is not present for the output, it's lowered to\n                a dummy label.\n        - Examples\n            - '...ij, ...jk', where i and k are free labels, j is dummy. The output label\n            string is '...ik'\n            - 'ij -> i', where i is a free label and j is a dummy label. \n            - '...ij, ...jk -> ...ijk', where i, j and k are all free labels.\n            - '...ij, ...jk -> ij', an invalid equation since `...` is not present for\n            the output.\n\n    **The summation rule**\n\n    The summation procedure can be outlined as follows, although the actual steps taken\n    may vary significantly due to implementation specific optimization.\n\n        - Step 1: preparation for broadcasting, that is, transposing and unsqueezing\n        the input operands to have each resulting dimension identically labeled across\n        all the input operands.\n        - Step 2: broadcasting multiply all the resulting operands from step 1.\n        - Step 3: reducing dummy labeled dimensions.\n        - Step 4: transposing the result tensor to match the output labels.\n\n    **On trace and diagonal**\n\n    The trace and diagonal are planned yet unimplemented features. \n\n    Args:\n        equation (`str`):\n            The summation terms using the Einstein summation notation.\n        operands (`list|Tensor`):\n            The input tensors over which to compute the Einstein summation. The number of\n            operands should equal the number of input terms in the equation.\n    \n    Returns:\n        result (`Tensor`): the result tensor.\n    \n    Examples:\n        .. code-block:: python\n\n        import paddle\n        paddle.seed(102)\n        x = paddle.rand([4])\n        y = paddle.rand([5])\n\n        # sum\n        print(paddle.einsum('i->', x))\n        # Tensor(shape=[], dtype=float32, place=CUDAPlace(0), stop_gradient=True,\n        #   1.95791852)\n\n        # dot\n        print(paddle.einsum('i,i->', x, x))\n        # Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=True,\n        #   [1.45936954])\n        \n        # outer\n        print(paddle.einsum(\"i,j->ij\", x, y))\n        # Tensor(shape=[4, 5], dtype=float32, place=CUDAPlace(0), stop_gradient=True,\n        #   [[0.00079869, 0.00120950, 0.00136844, 0.00187187, 0.00192194],\n        #    [0.23455200, 0.35519385, 0.40186870, 0.54970956, 0.56441545],\n        #    [0.11773264, 0.17828843, 0.20171674, 0.27592498, 0.28330654],\n        #    [0.32897076, 0.49817693, 0.56364071, 0.77099484, 0.79162055]])\n        \n        A = paddle.rand([2, 3, 2])\n        B = paddle.rand([2, 2, 3])\n        \n        # transpose\n        print(paddle.einsum('ijk->kji', A))\n        #  Tensor(shape=[2, 3, 2], dtype=float32, place=CUDAPlace(0), stop_gradient=True,\n        #   [[[0.95649719, 0.49684682],\n        #     [0.80071914, 0.46258664],\n        #     [0.49814570, 0.33383518]],\n        #\n        #    [[0.07637714, 0.29374704],\n        #     [0.51470858, 0.51907635],\n        #     [0.99066722, 0.55802226]]])\n        \n        # batch matrix multiplication\n        print(paddle.einsum('ijk, ikl->ijl', A,B))\n        # Tensor(shape=[2, 3, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=True,\n        #   [[[0.32172769, 0.50617385, 0.41394392],\n        #     [0.51736701, 0.49921003, 0.38730967],\n        #     [0.69078457, 0.42282537, 0.30161136]],\n        #\n        #    [[0.32043904, 0.18164253, 0.27810261],\n        #     [0.50226176, 0.24512935, 0.39881429],\n        #     [0.51476848, 0.23367381, 0.39229113]]])\n        \n        # Ellipsis transpose\n        print(paddle.einsum('...jk->...kj', A))\n        # Tensor(shape=[2, 2, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=True,\n        #   [[[0.95649719, 0.80071914, 0.49814570],\n        #     [0.07637714, 0.51470858, 0.99066722]],\n        #\n        #    [[0.49684682, 0.46258664, 0.33383518],\n        #     [0.29374704, 0.51907635, 0.55802226]]])\n        \n        # Ellipsis batch matrix multiplication\n        print(paddle.einsum('...jk, ...kl->...jl', A,B))\n        # Tensor(shape=[2, 3, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=True,\n        #   [[[0.32172769, 0.50617385, 0.41394392],\n        #     [0.51736701, 0.49921003, 0.38730967],\n        #     [0.69078457, 0.42282537, 0.30161136]],\n        #\n        #    [[0.32043904, 0.18164253, 0.27810261],\n        #     [0.50226176, 0.24512935, 0.39881429],\n        #     [0.51476848, 0.23367381, 0.39229113]]])\n    \"\"\"\n    import os\n    if int(os.environ.get('FLAGS_new_einsum', \"1\")):\n        return einsum_v2(equation, *operands)\n\n    nop = len(operands)\n    assert nop > 0, \"At least one operand is expected.\"\n\n    # Part the equation to left hand side and right hand side\n    lhs, *rhs = equation.lower().replace(' ', '').split('->')\n    assert len(rhs) < 2, \"Invalid equation: multiple `->` were found.\"\n\n    # Note, we distinguish between 'ij->' and 'ij' by setting rhs to '' and None\n    rhs = rhs[0] if rhs else None\n\n    # Parse labels for each operand and count the number of occurrences for each alphabet label\n    nop_labels = parse_labels(lhs, operands)\n\n    # Diagonalize the operands which have duplicate labels\n    nop_labels, operands = list(zip(*map(diagonalize, nop_labels, operands)))\n\n    # To handle broadcasting, we should first know how many dimensions are there\n    # We need to use that number to generate output labels\n    # e.g. 1 for ['ij', 'i.', '.k']\n    n_bcast_dims = max(map(lambda s: s.count('.'), nop_labels))\n\n    # Build the data structures for planning. It's helpful to think of all the operands\n    # broadcasting together from a global view. In this view, dimensions from multiple \n    # operands are mapped to the same position if they are labeled uniquely. Broadcasting\n    # dimensions are mapped to adjacent positions with the right bound fixed. Subject to\n    # each operand, the map is injective but for all operands the map is on-to.  \n    # g_labels:\n    #   The labels of the global view \n    # g_view:\n    #   Includes a list of maps from each operand's dimensions to the global view's dimensions\n    #   which we refer to as ax or axes in the code to distinguish from operand's dims\n    # g_shape:\n    #   The shape of the global view. The size of each dimension is what the aligned dimensions\n    #   should broadcast to\n    # g_nout:\n    #   Number of output axes\n    # g_supports\n    #   Booleans indicating each operand's non-trivial dimensions\n    # g_count\n    #   Counting how many non-trivial dimensions remain for each ax\n\n    g_labels, g_view, g_nout, g_count = build_global_view(nop_labels, rhs,\n                                                          n_bcast_dims)\n    g_shape, g_supports = build_global_shape(g_view, g_labels,\n                                             [op.shape for op in operands])\n\n    # Now we're ready to build up an execution plan\n    args = operands, g_view, g_shape, g_supports, g_count, n_bcast_dims\n    plan = plan_einsum(*args)\n    result = plan.execute()\n\n    return result\n", "meta": {"hexsha": "49cc426a00fd998c2ed24f94fb0002e4466065af", "size": 35918, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/paddle/tensor/einsum.py", "max_stars_repo_name": "RangeKing/Paddle", "max_stars_repo_head_hexsha": "2d87300809ae75d76f5b0b457d8112cb88dc3e27", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2016-08-15T07:02:27.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-24T09:34:00.000Z", "max_issues_repo_path": "python/paddle/tensor/einsum.py", "max_issues_repo_name": "RangeKing/Paddle", "max_issues_repo_head_hexsha": "2d87300809ae75d76f5b0b457d8112cb88dc3e27", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/paddle/tensor/einsum.py", "max_forks_repo_name": "RangeKing/Paddle", "max_forks_repo_head_hexsha": "2d87300809ae75d76f5b0b457d8112cb88dc3e27", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5033621518, "max_line_length": 109, "alphanum_fraction": 0.5976112256, "include": true, "reason": "import numpy", "num_tokens": 9542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3775406828054583, "lm_q1q2_score": 0.19024507969143278}}
{"text": "#!/usr/bin/env python\n# Copyright 2018-2020 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#\n\n'''\nPseudo-spectral methods (COSX, PS, SN-K)\n'''\n\nimport copy\nimport numpy\nfrom pyscf import lib\nfrom pyscf import gto\nfrom pyscf import scf\nfrom pyscf import mcscf\nfrom pyscf.scf import _vhf\nfrom pyscf.lib import logger\nfrom pyscf.sgx import sgx_jk\nfrom pyscf.df import df_jk\nfrom pyscf import __config__\n\ndef sgx_fit(mf, auxbasis=None, with_df=None):\n    '''For the given SCF object, update the J, K matrix constructor with\n    corresponding SGX or density fitting integrals.\n\n    Args:\n        mf : an SCF object\n\n    Kwargs:\n        auxbasis : str or basis dict\n            Same format to the input attribute mol.basis.  If auxbasis is\n            None, optimal auxiliary basis based on AO basis (if possible) or\n            even-tempered Gaussian basis will be used.\n\n    Returns:\n        An SCF object with a modified J, K matrix constructor which uses density\n        fitting integrals to compute J and K\n\n    Examples:\n\n    >>> mol = gto.M(atom='H 0 0 0; F 0 0 1', basis='ccpvdz', verbose=0)\n    >>> mf = sgx_fit(scf.RHF(mol))\n    >>> mf.scf()\n    -100.00978770917165\n\n    >>> mol.symmetry = 1\n    >>> mol.build(0, 0)\n    >>> mf = sgx_fit(scf.UHF(mol))\n    >>> mf.scf()\n    -100.00978770951018\n    '''\n    assert(isinstance(mf, scf.hf.SCF))\n\n    if with_df is None:\n        with_df = SGX(mf.mol)\n        with_df.max_memory = mf.max_memory\n        with_df.stdout = mf.stdout\n        with_df.verbose = mf.verbose\n        with_df.auxbasis = auxbasis\n\n    mf_class = mf.__class__\n\n    if isinstance(mf, _SGXHF):\n        if mf.with_df is None:\n            mf = mf_class(mf, with_df, auxbasis)\n        elif mf.with_df.auxbasis != auxbasis:\n            #logger.warn(mf, 'DF might have been initialized twice.')\n            mf = copy.copy(mf)\n            mf.with_df = with_df\n        return mf\n\n    class SGXHF(_SGXHF, mf_class):\n        def __init__(self, mf, df, auxbasis):\n            self.__dict__.update(mf.__dict__)\n            self._eri = None\n            self.auxbasis = auxbasis\n            self.with_df = df\n\n            # Grids/Integral quality varies during SCF. VHF cannot be\n            # constructed incrementally.\n            self.direct_scf = False\n\n            self._last_dm = 0\n            self._in_scf = False\n            self._keys = self._keys.union(['auxbasis', 'with_df'])\n\n        def build(self, mol=None, **kwargs):\n            if self.direct_scf:\n                self.with_df.build(level=self.with_df.grids_level_f)\n            else:\n                self.with_df.build(level=self.with_df.grids_level_i)\n            return mf_class.build(self, mol, **kwargs)\n\n        def reset(self, mol=None):\n            self.with_df.reset(mol)\n            return mf_class.reset(self, mol)\n\n        def pre_kernel(self, envs):\n            self._in_scf = True\n\n        def get_jk(self, mol=None, dm=None, hermi=1, with_j=True, with_k=True,\n                  omega=None):\n            if dm is None: dm = self.make_rdm1()\n            with_df = self.with_df\n            if not with_df:\n                return mf_class.get_jk(self, mol, dm, hermi, with_j, with_k, omega)\n\n            if self._in_scf and not self.direct_scf:\n                if numpy.linalg.norm(dm - self._last_dm) < with_df.grids_switch_thrd:\n                    logger.debug(self, 'Switching SGX grids')\n                    with_df.build(level=with_df.grids_level_f)\n                    self._in_scf = False\n                    self._last_dm = 0\n                else:\n                    self._last_dm = numpy.asarray(dm)\n\n            return with_df.get_jk(dm, hermi, with_j, with_k,\n                                  self.direct_scf_tol, omega)\n\n        def post_kernel(self, envs):\n            self._in_scf = False\n            self._last_dm = 0\n\n        def nuc_grad_method(self):\n            raise NotImplementedError\n\n    return SGXHF(mf, with_df, auxbasis)\n\n# A tag to label the derived SCF class\nclass _SGXHF(object):\n    def method_not_implemented(self, *args, **kwargs):\n        raise NotImplementedError\n    nuc_grad_method = Gradients = method_not_implemented\n    Hessian = method_not_implemented\n    NMR = method_not_implemented\n    NSR = method_not_implemented\n    Polarizability = method_not_implemented\n    RotationalGTensor = method_not_implemented\n    MP2 = method_not_implemented\n    CISD = method_not_implemented\n    CCSD = method_not_implemented\n    CASCI = method_not_implemented\n    CASSCF = method_not_implemented\n\nscf.hf.SCF.COSX = sgx_fit\nmcscf.casci.CASCI.COSX = sgx_fit\n\n\ndef _make_opt(mol):\n    '''Optimizer to genrate 3-center 2-electron integrals'''\n    intor = mol._add_suffix('int3c2e')\n    cintopt = gto.moleintor.make_cintopt(mol._atm, mol._bas, mol._env, intor)\n    # intor 'int1e_ovlp' is used by the prescreen method\n    # 'SGXnr_ovlp_prescreen' only. Not used again in other places.\n    # It can be released early\n    vhfopt = _vhf.VHFOpt(mol, 'int1e_ovlp', 'SGXnr_ovlp_prescreen',\n                         'SGXsetnr_direct_scf')\n    vhfopt._intor = intor\n    vhfopt._cintopt = cintopt\n    return vhfopt\n\n\nclass SGX(lib.StreamObject):\n    def __init__(self, mol, auxbasis=None):\n        self.mol = mol\n        self.stdout = mol.stdout\n        self.verbose = mol.verbose\n        self.max_memory = mol.max_memory\n        self.grids_thrd = 1e-10\n        self.grids_level_i = 0  # initial grids level\n        self.grids_level_f = 1  # final grids level\n        self.grids_switch_thrd = 0.03\n        # compute J matrix using DF and K matrix using SGX. It's identical to\n        # the RIJCOSX method in ORCA\n        self.dfj = False\n        self._auxbasis = auxbasis\n\n        # debug=True generates a dense tensor of the Coulomb integrals at each\n        # grids. debug=False utilizes the sparsity of the integral tensor and\n        # contracts the sparse tensor and density matrices on the fly.\n        self.debug = False\n\n        self.grids = None\n        self.blockdim = 1200\n        self.auxmol = None\n        self._vjopt = None\n        self._opt = None\n        self._last_dm = 0\n        self._rsh_df = {}  # Range separated Coulomb DF objects\n        self._keys = set(self.__dict__.keys())\n\n    @property\n    def auxbasis(self):\n        return self._auxbasis\n    @auxbasis.setter\n    def auxbasis(self, x):\n        if self._auxbasis != x:\n            self._auxbasis = x\n            self.auxmol = None\n\n    def dump_flags(self, verbose=None):\n        log = logger.new_logger(self, verbose)\n        log.info('******** %s ********', self.__class__)\n        log.info('max_memory = %s', self.max_memory)\n        log.info('grids_level_i = %s', self.grids_level_i)\n        log.info('grids_level_f = %s', self.grids_level_f)\n        log.info('grids_thrd = %s', self.grids_thrd)\n        log.info('grids_switch_thrd = %s', self.grids_switch_thrd)\n        log.info('df_j = %s', self.df_j)\n        log.info('auxbasis = %s', self.auxbasis)\n        return self\n\n    # To mimic DF object, so that SGX can be used as in DF-SCF method by setting\n    # mf.with_df = SGX(mol)\n    @property\n    def _cderi(self):\n        return self.grids\n\n    def build(self, level=None):\n        if level is None:\n            level = self.grids_level_f\n        self.grids = sgx_jk.get_gridss(self.mol, level, self.grids_thrd)\n        self._opt = _make_opt(self.mol)\n\n        # In the RSH-integral temporary treatment, recursively rebuild SGX\n        # objects in _rsh_df.\n        if self._rsh_df:\n            for k, v in self._rsh_df.items():\n                v.build(level)\n        return self\n\n    def kernel(self, *args, **kwargs):\n        return self.build(*args, **kwargs)\n\n    def reset(self, mol=None):\n        '''Reset mol and clean up relevant attributes for scanner mode'''\n        if mol is not None:\n            self.mol = mol\n        self.grids = None\n        self.auxmol = None\n        self._vjopt = None\n        self._opt = None\n        self._last_dm = 0\n        self._rsh_df = {}\n        return self\n\n    def get_jk(self, dm, hermi=1, with_j=True, with_k=True,\n               direct_scf_tol=getattr(__config__, 'scf_hf_SCF_direct_scf_tol', 1e-13),\n               omega=None):\n        if omega is not None:\n            # A temporary treatment for RSH integrals\n            key = '%.6f' % omega\n            if key in self._rsh_df:\n                rsh_df = self._rsh_df[key]\n            else:\n                rsh_df = copy.copy(self)\n                rsh_df._rsh_df = None  # to avoid circular reference\n                # Not all attributes need to be reset. Resetting _vjopt\n                # because it is used by get_j method of regular DF object.\n                rsh_df._vjopt = None\n                self._rsh_df[key] = rsh_df\n                logger.info(self, 'Create RSH-SGX object %s for omega=%s', rsh_df, omega)\n\n            with rsh_df.mol.with_range_coulomb(omega):\n                return rsh_df.get_jk(dm, hermi, with_j, with_k,\n                                     direct_scf_tol)\n\n        if with_j and self.dfj:\n            vj = df_jk.get_j(self, dm, hermi, direct_scf_tol)\n            if with_k:\n                vk = sgx_jk.get_jk(self, dm, hermi, False, with_k, direct_scf_tol)[1]\n            else:\n                vk = None\n        else:\n            vj, vk = sgx_jk.get_jk(self, dm, hermi, with_j, with_k, direct_scf_tol)\n        return vj, vk\n\n\nif __name__ == '__main__':\n    from pyscf import scf\n    mol = gto.Mole()\n    mol.build(\n        atom = [[\"O\" , (0. , 0.     , 0.)],\n                [1   , (0. , -0.757 , 0.587)],\n                [1   , (0. , 0.757  , 0.587)] ],\n        basis = 'ccpvdz',\n    )\n    method = sgx_fit(scf.RHF(mol), 'weigend')\n    energy = method.scf()\n    print(energy - -76.02673747045691)\n\n    method.with_df.dfj = True\n    energy = method.scf()\n    print(energy - -76.02686422219752)\n", "meta": {"hexsha": "07944afff49fa24e07a81620b7148f2200f931cc", "size": 10403, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/sgx/sgx.py", "max_stars_repo_name": "mfkasim1/pyscf", "max_stars_repo_head_hexsha": "7be5e015b2b40181755c71d888449db936604660", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-12T11:55:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T11:55:25.000Z", "max_issues_repo_path": "pyscf/sgx/sgx.py", "max_issues_repo_name": "mfkasim1/pyscf", "max_issues_repo_head_hexsha": "7be5e015b2b40181755c71d888449db936604660", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2018-08-22T19:44:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-09T10:02:36.000Z", "max_forks_repo_path": "pyscf/sgx/sgx.py", "max_forks_repo_name": "mfkasim1/pyscf", "max_forks_repo_head_hexsha": "7be5e015b2b40181755c71d888449db936604660", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-02-14T16:28:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-12T16:40:30.000Z", "avg_line_length": 33.775974026, "max_line_length": 89, "alphanum_fraction": 0.6042487744, "include": true, "reason": "import numpy", "num_tokens": 2817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.37754067580180184, "lm_q1q2_score": 0.19024507616224706}}
{"text": "#! /usr/bin/env python3\n\nimport random\nimport copy\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.signal import find_peaks_cwt\n\n\nLENGTH = 50000000\nN_TRIALS = 350\nselection_strength = 1\n\nreplicates = 3000\nplot_all = False\nwindow = 1000000\nstep = 10000\n\nout_pre = '/Volumes/Jacob_2TB_storage/sim_sec_recombination_mapping/genomics_scripts/analysis/'\n\n\nclass Sample_pool():\n    \"\"\"Holds samples, which need to be Sequence objects\"\"\"\n\n    def __init__(self):\n        self.pool = {}\n        self.keys = []\n    \n    def add_sample(self, sequence):\n        if self.keys:\n            newkey = max(self.keys) + 1\n        else:\n            newkey = 0\n        self.pool[newkey] = sequence\n        self.keys = list(self.pool.keys())\n\n    def pick_sample(self):\n        \"\"\"Selects a random sample\"\"\"\n        sample = random.choice(self.keys)\n        return self.pool[sample]\n\n    def sample_freq(self, position):\n        \"\"\"Gathers a sample allele frequency for a given position\"\"\"\n        reps = random.randint(36,40)\n        mel = 0\n        sim = 0\n        sec = 0\n        for i in range(reps):\n            sample = self.pick_sample()\n            if sample[position] == 1:\n                mel += 1\n            elif sample[position] == 2:\n                sim += 1\n            elif sample[position] == 3:\n                sec += 1\n\n        melf = mel / (mel + sim + sec)\n        simf = sim / (mel + sim + sec)\n        secf = sec / (mel + sim + sec)\n\n        return melf, simf, secf\n\ndef bool_chance(num):\n    x = random.random()\n    if x < num:\n        return True\n    else:\n        return False\n\ndef generate_parents():\n    \"\"\"\n    Generate a set of 3 parents where all positions are 0, if mel specific 1,\n    if sim specific 2, and if sec specific 3.\n    Return Dicitonary of parents\n    \"\"\"\n\n    everyN = 6000\n    \n    # get a list of the positions that would be differentiating spots\n    id_spots = [random.randint(0,LENGTH) for i in range(int(LENGTH/everyN))]\n    id_spots.sort()\n\n    # make a list of the same length for each species\n    mel_seq = [1] * len(id_spots)\n    sim_seq = [2] * len(id_spots)\n    sec_seq = [3] * len(id_spots)\n\n    parents = {\n        'mel' : mel_seq,\n        'sim' : sim_seq,\n        'sec' : sec_seq,\n\n    }\n\n    return parents, id_spots\n\ndef pick_selected_index(id_spots):\n    \"\"\"\n    Takes the list of different sites between the three sequences\n    Picks a random spot in the middle half of the sequences to be the selected site\n    Returns the index of the differentiated spots list that is closest to the \n        selected point, and the selected point\n    \"\"\"\n\n    q1 = int(LENGTH / 8)\n    q3 = int(7 * LENGTH / 8)\n    sel_spot = random.randint(q1, q3)\n\n    hold = 0\n    for idx, x in enumerate(id_spots):\n        if x < sel_spot:\n            hold = x\n        else:\n            if (sel_spot - hold) <= (x - sel_spot):\n                return (idx-1), sel_spot\n            else:\n                return idx, sel_spot\n\ndef reorder(one, two):\n    if one >= two:\n        return two, one\n    else:\n        return one, two\n\ndef gamma_model():\n    \"\"\"Compute the gamma distrubtion model for recombination.\n    Return a dictionary with 100 steps (should never need that many)\n    \"\"\"\n    model = {}\n    prev = 0\n    for i in range(1,101):\n        # the computation:\n            # (5*1morgan) (sum_to_i)(\n            #   1 / (5i-1) * 1M^(5i) * dist^(5i-1) * e^(-(1M)*dist)  \n            # )\n            # where distance is in morgans\n        prev += ((1**(5*i)) * ((0.01*i)**((5*i)-1)) * (np.e ** (-(0.01*i)))) / (5*(i) - 1)\n        model[i] = 5 * prev\n    return model\n\ndef recombine(seq1, seq2, model):\n    \"\"\"Make a recombinant sequence from sequence 1 and 2\"\"\"\n\n    idxs = [idx for idx, x in enumerate(seq1)]\n\n    co1 = random.choice(idxs)\n\n    half = int(len(idxs) / 2)\n\n    if co1 < half:\n        co2 = random.choice(idxs[half:])\n    else:\n        co2 = random.choice(idxs[:half])\n\n    co1, co2 = reorder(co1, co2)\n\n    if bool_chance(0.5):\n        rec_seq = seq1[:co1] + seq2[co1:co2] + seq1[co2:]\n    else:\n        rec_seq = seq2[:co1] + seq1[co1:co2] + seq2[co2:]\n\n    return rec_seq\n\ndef filter(seq, sel_idx, sel_strength):\n    \"\"\"Checks if a sequence contains the selected site\"\"\"\n    if seq[sel_idx] == 2:\n        return True\n    else:\n        if bool_chance(1-sel_strength):\n            return True\n        else:\n            return False\n\ndef make_pool(parents, sel_idx, sex, sel_strength, model):\n    \"\"\"\n    Input: mel, sim, sec parent sequence  , site to be selected on\n    Returns: sample pool of recombinant sequences and mel sequences\n    \"\"\"\n\n    pool = Sample_pool()\n    for i in range(N_TRIALS):\n        survive = False\n        while not survive:\n            recseq = recombine(parents['sim'], parents['sec'], model)\n            survive = filter(recseq, sel_idx, sel_strength)\n            if sex == 'female':\n                survive = True\n        pool.add_sample(recseq)\n        # because diploids, we add one mel sequence for each recombinant sequence\n        pool.add_sample(parents['mel'])\n\n    return pool\n\ndef simulate_sequencing(pool, id_spots):\n    table = []\n    for idx, x in enumerate(id_spots):\n        mel, sim, sec = pool.sample_freq(idx)\n        table.append([x,mel,sim,sec])\n    return table\n\ndef sex_difference(male_reps, female_reps):\n    reps = {}\n\n    for i in male_reps:\n        reps[i] = []\n        for idx, entry in enumerate(male_reps[i]):\n            male = male_reps[i][idx]\n            female = female_reps[i][idx]\n            freq = [(male[0]), (male[1] - female[1]), (male[2] - female[2]), (male[3] - female[3])]\n            reps[i].append(freq)\n    \n    return reps\n\ndef average_replicates(reps):\n    table = []\n    for pos, lis in enumerate(reps[0]):\n        melav = (reps[0][pos][1] + reps[1][pos][1] + reps[2][pos][1]) / 3\n        simav = (reps[0][pos][2] + reps[1][pos][2] + reps[2][pos][2]) / 3\n        secav = (reps[0][pos][3] + reps[1][pos][3] + reps[2][pos][3]) / 3\n        table.append([reps[0][pos][0], melav, simav, secav])\n    return table\n\ndef rolling_average(table, window, step):\n    \n    win2 = window/2\n    pos = window/2\n\n    window_table = []\n    posits = [x[0] for x in table]\n    while pos < max(posits):\n        melav = []\n        simav = []\n        secav = []\n        for x in table:\n            if (x[0] > pos-win2):\n                if (x[0] < pos+win2):\n                    melav.append(x[1])\n                    simav.append(x[2])\n                    secav.append(x[3])\n                else:\n                    break\n        if melav and simav and secav:\n            window_table.append([pos, np.mean(melav), np.mean(simav), np.mean(secav)])\n        pos += step\n\n    \n    newtable = [['position','mel','sim','sec']]\n    for x in window_table:\n        newtable.append(x)\n\n    return newtable\n\ndef estimate_max(table):\n    table = table[1:]\n    sim_freqs = [(x[0],(x[2]-x[3]))for x in table]\n    sim_freqs = sorted(sim_freqs, key=lambda x: x[1])\n\n    # find the peaks\n    xs = [x[1] for x in sim_freqs]\n    peaks = list(find_peaks_cwt(xs, np.arange(50, 200)))\n\n    # this produces a list. Find the biggest one in the list\n    big = (0,0)\n    for peak in peaks:\n        if sim_freqs[peak][1] > big[1]:\n            big = (sim_freqs[peak][0], sim_freqs[peak][1])\n\n    return big[0]\n\ndef write_to_csv(table, filename):\n    with open(filename, 'w') as f:\n        for line in table:\n            line = [str(x) for x in line]\n            f.write(','.join(line))\n            f.write('\\n')\n\ndef plot_frequencies(filename, sel_spot, esitmate, num):\n    df = pd.read_csv(filename)\n    fig = plt.figure(figsize=(6, 8))\n    plt.plot(df['position'], df['mel'], color = 'blue', label = 'D.mel')\n    plt.plot(df['position'], df['sim'], color = 'orange', label = 'D.sim')\n    plt.plot(df['position'], df['sec'], color = 'red', label = 'D.sec')\n    plt.axvline(x=sel_spot, color='black', label = 'actual site')\n    plt.axvline(x=esitmate, color='green', label = 'estimated site')\n    plt.ylim(-0.4,0.4)\n    plt.legend()\n    plt.ylabel('Allele Frequency (Male - Female)')\n    plt.xlabel('Genomic position')\n    plotname = filename.split('.csv')[0] + str(num) + '.pdf'\n    plt.savefig(plotname)\n\n\nparents, id_spots = generate_parents()\nmodel = gamma_model()\ndifferences = []\nfor i2 in range(replicates):\n    sel_idx, sel_spot = pick_selected_index(id_spots)\n    male_reps = {}\n    female_reps = {}\n    reps = {}\n    # replicate 3 times\n    for i in range(3):\n        male_pool = make_pool(parents, sel_idx, 'male', selection_strength, model)\n        female_pool = make_pool(parents, sel_idx, 'female', selection_strength, model)\n        male_reps[i] = simulate_sequencing(male_pool, id_spots)\n        female_reps[i] = simulate_sequencing(female_pool, id_spots)\n    reps = sex_difference(male_reps, female_reps)\n    table = average_replicates(reps)\n    table = rolling_average(table, window, step)\n    estimated_site = estimate_max(table)\n    differences.append(estimated_site-sel_spot)\n    if plot_all:\n        outtable = out_pre + str(i2) + 'simulation_out.csv'\n        write_to_csv(table, outtable)\n        plot_frequencies(outtable, sel_spot, estimated_site, i2)\n\n\nprint(differences)\nprint(\"2x std:\", np.std(differences))\nprint(\"Average:\", np.average(differences))\nplt.hist(differences, bins=20)\nplt.savefig(out_pre+'confidence_hist.pdf')\n\nouttable = out_pre + 'final_simulation_out.csv'\nwrite_to_csv(table, outtable)\nplot_frequencies(outtable, sel_spot, estimated_site, 'final')\n", "meta": {"hexsha": "28acbd9212671df05033225818b866597962a501", "size": 9489, "ext": "py", "lang": "Python", "max_stars_repo_path": "simulation/frequency_estimation_mega_script.py", "max_stars_repo_name": "jcooper036/tri_hybid_mapping", "max_stars_repo_head_hexsha": "a4a0aebcf1a1fb3773b1b402a25635b53004856a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulation/frequency_estimation_mega_script.py", "max_issues_repo_name": "jcooper036/tri_hybid_mapping", "max_issues_repo_head_hexsha": "a4a0aebcf1a1fb3773b1b402a25635b53004856a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulation/frequency_estimation_mega_script.py", "max_forks_repo_name": "jcooper036/tri_hybid_mapping", "max_forks_repo_head_hexsha": "a4a0aebcf1a1fb3773b1b402a25635b53004856a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9298780488, "max_line_length": 99, "alphanum_fraction": 0.5843608389, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.1902450726330614}}
{"text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n################################################################################\n#\n#   RMG - Reaction Mechanism Generator\n#\n#   Copyright (c) 2002-2010 Prof. William H. Green (whgreen@mit.edu) and the\n#   RMG Team (rmg_dev@mit.edu)\n#\n#   Permission is hereby granted, free of charge, to any person obtaining a\n#   copy of this software and associated documentation files (the 'Software'),\n#   to deal in the Software without restriction, including without limitation\n#   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n#   and/or sell copies of the Software, and to permit persons to whom the\n#   Software is furnished to do so, subject to the following conditions:\n#\n#   The above copyright notice and this permission notice shall be included in\n#   all copies or substantial portions of the Software.\n#\n#   THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n#   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n#   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n#   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n#   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n#   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n#   DEALINGS IN THE SOFTWARE.\n#\n################################################################################\n\n\"\"\"\n\n\"\"\"\n\nimport os\nimport os.path\nimport math\nimport logging\nimport numpy\nfrom copy import copy, deepcopy\n\nfrom base import Database, Entry, makeLogicNode\n\nfrom rmgpy.quantity import constants\nfrom rmgpy.thermo import *\nfrom rmgpy.molecule import Molecule, Atom, Bond, Group\n\n################################################################################\n\ndef saveEntry(f, entry):\n    \"\"\"\n    Write a Pythonic string representation of the given `entry` in the thermo\n    database to the file object `f`.\n    \"\"\"\n    \n    f.write('entry(\\n')\n    f.write('    index = {0:d},\\n'.format(entry.index))\n    f.write('    label = \"{0}\",\\n'.format(entry.label))\n\n    if isinstance(entry.item, Molecule):\n        f.write('    molecule = \\n')\n        f.write('\"\"\"\\n')\n        f.write(entry.item.toAdjacencyList(removeH=True))\n        f.write('\"\"\",\\n')\n    elif isinstance(entry.item, Group):\n        f.write('    group = \\n')\n        f.write('\"\"\"\\n')\n        f.write(entry.item.toAdjacencyList())\n        f.write('\"\"\",\\n')\n    else:\n        f.write('    group = \"{0}\",\\n'.format(entry.item))\n\n    if isinstance(entry.data, ThermoData):\n        f.write('    thermo = ThermoData(\\n')\n        f.write('        Tdata = {0!r},\\n'.format(entry.data.Tdata))\n        f.write('        Cpdata = {0!r},\\n'.format(entry.data.Cpdata))\n        f.write('        H298 = {0!r},\\n'.format(entry.data.H298))\n        f.write('        S298 = {0!r},\\n'.format(entry.data.S298))\n        if entry.data.Tmin is not None: f.write('        Tmin = {0!r},\\n'.format(entry.data.Tmin))\n        if entry.data.Tmax is not None: f.write('        Tmax = {0!r},\\n'.format(entry.data.Tmax))\n        f.write('    ),\\n')\n    elif isinstance(entry.data, Wilhoit):\n        f.write('    thermo = Wilhoit(\\n')\n        f.write('        cp0 = {0!r},\\n'.format(entry.data.cp0))\n        f.write('        cpInf = {0!r},\\n'.format(entry.data.cpInf))\n        f.write('        a0 = {0:g},\\n'.format(entry.data.a0))\n        f.write('        a1 = {0:g},\\n'.format(entry.data.a1))\n        f.write('        a2 = {0:g},\\n'.format(entry.data.a2))\n        f.write('        a3 = {0:g},\\n'.format(entry.data.a3))\n        f.write('        B = {0!r},\\n'.format(entry.data.B))\n        f.write('        H0 = {0!r},\\n'.format(entry.data.H0))\n        f.write('        S0 = {0!r},\\n'.format(entry.data.S0))\n        if entry.data.Tmin is not None: f.write('        Tmin = {0!r},\\n'.format(entry.data.Tmin))\n        if entry.data.Tmax is not None: f.write('        Tmax = {0!r},\\n'.format(entry.data.Tmax))\n        f.write('    ),\\n')\n    elif isinstance(entry.data, MultiNASA):\n        f.write('    thermo = MultiNASA(\\n')\n        f.write('        polynomials = [\\n')\n        for poly in entry.data.polynomials:\n            f.write('            {0!r},\\n'.format(poly))\n        f.write('        ],\\n')\n        if entry.data.Tmin is not None: f.write('        Tmin = {0!r},\\n'.format(entry.data.Tmin))\n        if entry.data.Tmax is not None: f.write('        Tmax = {0!r},\\n'.format(entry.data.Tmax))\n        f.write('    ),\\n')\n    else:\n        f.write('    thermo = {0!r},\\n'.format(entry.data))\n\n    if entry.reference is not None: f.write('    reference = {0!r},\\n'.format(entry.reference))\n    if entry.referenceType != \"\": f.write('    referenceType = \"{0}\",\\n'.format(entry.referenceType))\n    f.write('    shortDesc = u\"\"\"{0}\"\"\",\\n'.format(entry.shortDesc))\n    f.write('    longDesc = \\n')\n    f.write('u\"\"\"\\n')\n    f.write(entry.longDesc.strip() + \"\\n\")\n    f.write('\"\"\",\\n')\n\n    f.write('    history = [\\n')\n    for time, user, action, description in entry.history:\n        f.write('        (\"{0}\",\"{1}\",\"{2}\",\"\"\"{3}\"\"\"),\\n'.format(time, user, action, description))\n    f.write('    ],\\n')\n\n    f.write(')\\n\\n')\n\ndef generateOldLibraryEntry(data):\n    \"\"\"\n    Return a list of values used to save entries to the old-style RMG\n    thermo database based on the thermodynamics object `data`.\n    \"\"\"\n    if isinstance(data, ThermoData):\n        return '{0:9g} {1:9g} {2:9g} {3:9g} {4:9g} {5:9g} {6:9g} {7:9g} {8:9g} {9:9g} {10:9g} {11:9g}'.format(\n            data.H298.value/4184.,\n            data.S298.value/4.184,\n            data.Cpdata.values[0]/4.184,\n            data.Cpdata.values[1]/4.184,\n            data.Cpdata.values[2]/4.184,\n            data.Cpdata.values[3]/4.184,\n            data.Cpdata.values[4]/4.184,\n            data.Cpdata.values[5]/4.184,\n            data.Cpdata.values[6]/4.184,\n            data.H298.uncertainty/4184.,\n            data.S298.uncertainty/4.184,\n            data.Cpdata.uncertainty/4.184,\n        )\n    else:\n        return '{0:9g} {1:9g} {2:9g} {3:9g} {4:9g} {5:9g} {6:9g} {7:9g} {8:9g} {9:9g} {10:9g} {11:9g}'.format(\n            data.getEnthalpy(298)/4184.,\n            data.getEntropy(298)/4.184,\n            data.getHeatCapacity(300)/4.184,\n            data.getHeatCapacity(400)/4.184,\n            data.getHeatCapacity(500)/4.184,\n            data.getHeatCapacity(600)/4.184,\n            data.getHeatCapacity(800)/4.184,\n            data.getHeatCapacity(1000)/4.184,\n            data.getHeatCapacity(1500)/4.184,\n            0,\n            0,\n            0,\n        )\n\ndef processOldLibraryEntry(data):\n    \"\"\"\n    Process a list of parameters `data` as read from an old-style RMG\n    thermo database, returning the corresponding thermodynamics object.\n    \"\"\"\n    return ThermoData(\n        Tdata = ([300,400,500,600,800,1000,1500],\"K\"),\n        Cpdata = ([float(d) for d in data[2:9]],\"cal/(mol*K)\",\"+|-\",float(data[11])),\n        H298 = (float(data[0]),\"kcal/mol\",\"+|-\",float(data[9])),\n        S298 = (float(data[1]),\"cal/(mol*K)\",\"+|-\",float(data[10])),\n    )\n\n\n################################################################################\n\nclass ThermoDepository(Database):\n    \"\"\"\n    A class for working with the RMG thermodynamics depository.\n    \"\"\"\n\n    def __init__(self, label='', name='', shortDesc='', longDesc=''):\n        Database.__init__(self, label=label, name=name, shortDesc=shortDesc, longDesc=longDesc)\n\n    def loadEntry(self, index, label, molecule, thermo, reference=None, referenceType='', shortDesc='', longDesc='', history=None):\n        self.entries[label] = Entry(\n            index = index,\n            label = label,\n            item = Molecule().fromAdjacencyList(molecule),\n            data = thermo,\n            reference = reference,\n            referenceType = referenceType,\n            shortDesc = shortDesc,\n            longDesc = longDesc.strip(),\n            history = history or [],\n        )\n\n    def saveEntry(self, f, entry):\n        \"\"\"\n        Write the given `entry` in the thermo database to the file object `f`.\n        \"\"\"\n        return saveEntry(f, entry)\n\n################################################################################\n\nclass ThermoLibrary(Database):\n    \"\"\"\n    A class for working with a RMG thermodynamics library.\n    \"\"\"\n\n    def __init__(self, label='', name='', shortDesc='', longDesc=''):\n        Database.__init__(self, label=label, name=name, shortDesc=shortDesc, longDesc=longDesc)\n\n    def loadEntry(self,\n                  index,\n                  label,\n                  molecule,\n                  thermo,\n                  reference=None,\n                  referenceType='',\n                  shortDesc='',\n                  longDesc='',\n                  history=None\n                  ):\n        self.entries[label] = Entry(\n            index = index,\n            label = label,\n            item = Molecule().fromAdjacencyList(molecule),\n            data = thermo,\n            reference = reference,\n            referenceType = referenceType,\n            shortDesc = shortDesc,\n            longDesc = longDesc.strip(),\n            history = history or [],\n        )\n\n    def saveEntry(self, f, entry):\n        \"\"\"\n        Write the given `entry` in the thermo database to the file object `f`.\n        \"\"\"\n        return saveEntry(f, entry)\n\n    def generateOldLibraryEntry(self, data):\n        \"\"\"\n        Return a list of values used to save entries to the old-style RMG\n        thermo database based on the thermodynamics object `data`.\n        \"\"\"\n        return generateOldLibraryEntry(data)\n\n    def processOldLibraryEntry(self, data):\n        \"\"\"\n        Process a list of parameters `data` as read from an old-style RMG\n        thermo database, returning the corresponding thermodynamics object.\n        \"\"\"\n        return processOldLibraryEntry(data)\n\n################################################################################\n\nclass ThermoGroups(Database):\n    \"\"\"\n    A class for working with an RMG thermodynamics group additivity database.\n    \"\"\"\n\n    def __init__(self, label='', name='', shortDesc='', longDesc=''):\n        Database.__init__(self, label=label, name=name, shortDesc=shortDesc, longDesc=longDesc)\n\n    def loadEntry(self,\n                  index,\n                  label,\n                  group,\n                  thermo,\n                  reference=None,\n                  referenceType='',\n                  shortDesc='',\n                  longDesc='',\n                  history=None\n                  ):\n        if group[0:3].upper() == 'OR{' or group[0:4].upper() == 'AND{' or group[0:7].upper() == 'NOT OR{' or group[0:8].upper() == 'NOT AND{':\n            item = makeLogicNode(group)\n        else:\n            item = Group().fromAdjacencyList(group)\n        self.entries[label] = Entry(\n            index = index,\n            label = label,\n            item = item,\n            data = thermo,\n            reference = reference,\n            referenceType = referenceType,\n            shortDesc = shortDesc,\n            longDesc = longDesc.strip(),\n            history = history or [],\n        )\n    \n    def saveEntry(self, f, entry):\n        \"\"\"\n        Write the given `entry` in the thermo database to the file object `f`.\n        \"\"\"\n        return saveEntry(f, entry)\n\n    def generateOldLibraryEntry(self, data):\n        \"\"\"\n        Return a list of values used to save entries to the old-style RMG\n        thermo database based on the thermodynamics object `data`.\n        \"\"\"\n        return generateOldLibraryEntry(data)\n\n    def processOldLibraryEntry(self, data):\n        \"\"\"\n        Process a list of parameters `data` as read from an old-style RMG\n        thermo database, returning the corresponding thermodynamics object.\n        \"\"\"\n        return processOldLibraryEntry(data)\n\n################################################################################\n\nclass ThermoDatabase:\n    \"\"\"\n    A class for working with the RMG thermodynamics database.\n    \"\"\"\n\n    def __init__(self):\n        self.depository = {}\n        self.libraries = {}\n        self.groups = {}\n        self.libraryOrder = []\n        self.local_context = {\n            'ThermoData': ThermoData,\n            'Wilhoit': Wilhoit,\n            'NASA': NASA,\n            'MultiNASA': MultiNASA,\n        }\n        self.global_context = {}\n\n    def load(self, path, libraries=None, depository=True):\n        \"\"\"\n        Load the thermo database from the given `path` on disk, where `path`\n        points to the top-level folder of the thermo database.\n        \"\"\"\n        if depository:\n            self.loadDepository(os.path.join(path, 'depository'))\n        else:\n            self.depository = {}\n        self.loadLibraries(os.path.join(path, 'libraries'), libraries)\n        self.loadGroups(os.path.join(path, 'groups'))\n        \n    def loadDepository(self, path):\n        \"\"\"\n        Load the thermo database from the given `path` on disk, where `path`\n        points to the top-level folder of the thermo database.\n        \"\"\"\n        self.depository = {}\n        self.depository['stable']  = ThermoDepository().load(os.path.join(path, 'stable.py'), self.local_context, self.global_context)\n        self.depository['radical'] = ThermoDepository().load(os.path.join(path, 'radical.py'), self.local_context, self.global_context)\n\n    def loadLibraries(self, path, libraries=None):\n        \"\"\"\n        Load the thermo database from the given `path` on disk, where `path`\n        points to the top-level folder of the thermo database.\n        \"\"\"\n        self.libraries = {}; self.libraryOrder = []\n        for (root, dirs, files) in os.walk(os.path.join(path)):\n            for f in files:\n                name, ext = os.path.splitext(f)\n                if ext.lower() == '.py' and (libraries is None or name in libraries):\n                    logging.info('Loading thermodynamics library from {0} in {1}...'.format(f, root))\n                    library = ThermoLibrary()\n                    library.load(os.path.join(root, f), self.local_context, self.global_context)\n                    library.label = os.path.splitext(f)[0]\n                    self.libraries[library.label] = library\n                    self.libraryOrder.append(library.label)\n        if libraries is not None:\n            self.libraryOrder = libraries\n\n    def loadGroups(self, path):\n        \"\"\"\n        Load the thermo database from the given `path` on disk, where `path`\n        points to the top-level folder of the thermo database.\n        \"\"\"\n        logging.info('Loading thermodynamics group database from {0}...'.format(path))\n        self.groups = {}\n        self.groups['group']   =   ThermoGroups(label='group').load(os.path.join(path, 'group.py'  ), self.local_context, self.global_context)\n        self.groups['gauche']  =  ThermoGroups(label='gauche').load(os.path.join(path, 'gauche.py' ), self.local_context, self.global_context)\n        self.groups['int15']   =   ThermoGroups(label='int15').load(os.path.join(path, 'int15.py'  ), self.local_context, self.global_context)\n        self.groups['ring']    =    ThermoGroups(label='ring').load(os.path.join(path, 'ring.py'   ), self.local_context, self.global_context)\n        self.groups['radical'] = ThermoGroups(label='radical').load(os.path.join(path, 'radical.py'), self.local_context, self.global_context)\n        self.groups['other']   =   ThermoGroups(label='other').load(os.path.join(path, 'other.py'  ), self.local_context, self.global_context)\n\n    def save(self, path):\n        \"\"\"\n        Save the thermo database to the given `path` on disk, where `path`\n        points to the top-level folder of the thermo database.\n        \"\"\"\n        path = os.path.abspath(path)\n        if not os.path.exists(path): os.mkdir(path)\n        self.saveDepository(os.path.join(path, 'depository'))\n        self.saveLibraries(os.path.join(path, 'libraries'))\n        self.saveGroups(os.path.join(path, 'groups'))\n\n    def saveDepository(self, path):\n        \"\"\"\n        Save the thermo depository to the given `path` on disk, where `path`\n        points to the top-level folder of the thermo depository.\n        \"\"\"\n        if not os.path.exists(path): os.mkdir(path)\n        self.depository['stable'].save(os.path.join(path, 'stable.py'))\n        self.depository['radical'].save(os.path.join(path, 'radical.py'))\n\n    def saveLibraries(self, path):\n        \"\"\"\n        Save the thermo libraries to the given `path` on disk, where `path`\n        points to the top-level folder of the thermo libraries.\n        \"\"\"\n        if not os.path.exists(path): os.mkdir(path)\n        for library in self.libraries.values():\n            library.save(os.path.join(path, '{0}.py'.format(library.label)))\n\n    def saveGroups(self, path):\n        \"\"\"\n        Save the thermo groups to the given `path` on disk, where `path`\n        points to the top-level folder of the thermo groups.\n        \"\"\"\n        if not os.path.exists(path): os.mkdir(path)\n        self.groups['group'].save(os.path.join(path, 'group.py'))\n        self.groups['gauche'].save(os.path.join(path, 'gauche.py'))\n        self.groups['int15'].save(os.path.join(path, 'int15.py'))\n        self.groups['ring'].save(os.path.join(path, 'ring.py'))\n        self.groups['radical'].save(os.path.join(path, 'radical.py'))\n        self.groups['other'].save(os.path.join(path, 'other.py'))\n\n    def loadOld(self, path):\n        \"\"\"\n        Load the old RMG thermo database from the given `path` on disk, where\n        `path` points to the top-level folder of the old RMG database.\n        \"\"\"\n        # The old database does not have a depository, so create an empty one\n        self.depository = {}\n        self.depository['stable']  = ThermoDepository(label='stable', name='Stable Molecules')\n        self.depository['radical'] = ThermoDepository(label='radical', name='Radical Molecules')\n        \n        for (root, dirs, files) in os.walk(os.path.join(path, 'thermo_libraries')):\n            if os.path.exists(os.path.join(root, 'Dictionary.txt')) and os.path.exists(os.path.join(root, 'Library.txt')):\n                library = ThermoLibrary(label=os.path.basename(root), name=os.path.basename(root))\n                library.loadOld(\n                    dictstr = os.path.join(root, 'Dictionary.txt'),\n                    treestr = '',\n                    libstr = os.path.join(root, 'Library.txt'),\n                    numParameters = 12,\n                    numLabels = 1,\n                    pattern = False,\n                )\n                library.label = os.path.basename(root)\n                self.libraries[library.label] = library\n\n        self.groups = {}\n        self.groups['group'] = ThermoGroups(label='group', name='Functional Group Additivity Values').loadOld(\n            dictstr = os.path.join(path, 'thermo_groups', 'Group_Dictionary.txt'),\n            treestr = os.path.join(path, 'thermo_groups', 'Group_Tree.txt'),\n            libstr = os.path.join(path, 'thermo_groups', 'Group_Library.txt'),\n            numParameters = 12,\n            numLabels = 1,\n            pattern = True,\n        )\n        self.groups['gauche'] = ThermoGroups(label='gauche', name='Gauche Interaction Corrections').loadOld(\n            dictstr = os.path.join(path, 'thermo_groups', 'Gauche_Dictionary.txt'),\n            treestr = os.path.join(path, 'thermo_groups', 'Gauche_Tree.txt'),\n            libstr = os.path.join(path, 'thermo_groups', 'Gauche_Library.txt'),\n            numParameters = 12,\n            numLabels = 1,\n            pattern = True,\n        )\n        self.groups['int15'] = ThermoGroups(label='int15', name='1,5-Interaction Corrections').loadOld(\n            dictstr = os.path.join(path, 'thermo_groups', '15_Dictionary.txt'),\n            treestr = os.path.join(path, 'thermo_groups', '15_Tree.txt'),\n            libstr = os.path.join(path, 'thermo_groups', '15_Library.txt'),\n            numParameters = 12,\n            numLabels = 1,\n            pattern = True,\n        )\n        self.groups['radical'] = ThermoGroups(label='radical', name='Radical Corrections').loadOld(\n            dictstr = os.path.join(path, 'thermo_groups', 'Radical_Dictionary.txt'),\n            treestr = os.path.join(path, 'thermo_groups', 'Radical_Tree.txt'),\n            libstr = os.path.join(path, 'thermo_groups', 'Radical_Library.txt'),\n            numParameters = 12,\n            numLabels = 1,\n            pattern = True,\n        )\n        self.groups['ring'] = ThermoGroups(label='ring', name='Ring Corrections').loadOld(\n            dictstr = os.path.join(path, 'thermo_groups', 'Ring_Dictionary.txt'),\n            treestr = os.path.join(path, 'thermo_groups', 'Ring_Tree.txt'),\n            libstr = os.path.join(path, 'thermo_groups', 'Ring_Library.txt'),\n            numParameters = 12,\n            numLabels = 1,\n            pattern = True,\n        )\n        self.groups['other'] = ThermoGroups(label='other', name='Other Corrections').loadOld(\n            dictstr = os.path.join(path, 'thermo_groups', 'Other_Dictionary.txt'),\n            treestr = os.path.join(path, 'thermo_groups', 'Other_Tree.txt'),\n            libstr = os.path.join(path, 'thermo_groups', 'Other_Library.txt'),\n            numParameters = 12,\n            numLabels = 1,\n            pattern = True,\n        )\n\n    def saveOld(self, path):\n        \"\"\"\n        Save the old RMG thermo database to the given `path` on disk, where\n        `path` points to the top-level folder of the old RMG database.\n        \"\"\"\n\n        # Depository not used in old database, so it is not saved\n\n        librariesPath = os.path.join(path, 'thermo_libraries')\n        if not os.path.exists(librariesPath): os.mkdir(librariesPath)\n        for library in self.libraries.values():\n            libraryPath = os.path.join(librariesPath, library.label)\n            if not os.path.exists(libraryPath): os.mkdir(libraryPath)\n            library.saveOld(\n                dictstr = os.path.join(libraryPath, 'Dictionary.txt'),\n                treestr = '',\n                libstr = os.path.join(libraryPath, 'Library.txt'),\n            )\n\n        groupsPath = os.path.join(path, 'thermo_groups')\n        if not os.path.exists(groupsPath): os.mkdir(groupsPath)\n        self.groups['group'].saveOld(\n            dictstr = os.path.join(groupsPath, 'Group_Dictionary.txt'),\n            treestr = os.path.join(groupsPath, 'Group_Tree.txt'),\n            libstr = os.path.join(groupsPath, 'Group_Library.txt'),\n        )\n        self.groups['gauche'].saveOld(\n            dictstr = os.path.join(groupsPath, 'Gauche_Dictionary.txt'),\n            treestr = os.path.join(groupsPath, 'Gauche_Tree.txt'),\n            libstr = os.path.join(groupsPath, 'Gauche_Library.txt'),\n        )\n        self.groups['int15'].saveOld(\n            dictstr = os.path.join(groupsPath, '15_Dictionary.txt'),\n            treestr = os.path.join(groupsPath, '15_Tree.txt'),\n            libstr = os.path.join(groupsPath, '15_Library.txt'),\n        )\n        self.groups['radical'].saveOld(\n            dictstr = os.path.join(groupsPath, 'Radical_Dictionary.txt'),\n            treestr = os.path.join(groupsPath, 'Radical_Tree.txt'),\n            libstr = os.path.join(groupsPath, 'Radical_Library.txt'),\n        )\n        self.groups['ring'].saveOld(\n            dictstr = os.path.join(groupsPath, 'Ring_Dictionary.txt'),\n            treestr = os.path.join(groupsPath, 'Ring_Tree.txt'),\n            libstr = os.path.join(groupsPath, 'Ring_Library.txt'),\n        )\n        self.groups['other'].saveOld(\n            dictstr = os.path.join(groupsPath, 'Other_Dictionary.txt'),\n            treestr = os.path.join(groupsPath, 'Other_Tree.txt'),\n            libstr = os.path.join(groupsPath, 'Other_Library.txt'),\n        )\n\n    def getThermoData(self, species):\n        \"\"\"\n        Return the thermodynamic parameters for a given :class:`Species`\n        object `species`. This function first searches the loaded libraries\n        in order, returning the first match found, before falling back to\n        estimation via group additivity.\n        \"\"\"\n        thermoData = None\n        # Check the libraries in order first; return the first successful match\n        for label in self.libraryOrder:\n            thermoData = self.getThermoDataFromLibrary(species, self.libraries[label])\n            if thermoData is not None: break\n        else:\n            # Thermo not found in any loaded libraries, so estimate\n            thermoData = self.getThermoDataFromGroups(species)\n        return thermoData[0]\n\n    def getAllThermoData(self, species):\n        \"\"\"\n        Return all possible sets of thermodynamic parameters for a given\n        :class:`Species` object `species`. The hits from the depository come\n        first, then the libraries (in order), and then the group additivity\n        estimate. This method is useful for a generic search job.\n        \"\"\"\n        thermoData = []\n        # Data from depository comes first\n        thermoData.extend(self.getThermoDataFromDepository(species))\n        # Data from libraries comes second\n        for label in self.libraryOrder:\n            data = self.getThermoDataFromLibrary(species, self.libraries[label])\n            if data: \n                thermoData.append(data)\n        # Last entry is always the estimate from group additivity\n        thermoData.append(self.getThermoDataFromGroups(species))\n        return thermoData\n\n    def getThermoDataFromDepository(self, species):\n        \"\"\"\n        Return all possible sets of thermodynamic parameters for a given\n        :class:`Species` object `species` from the depository. If no\n        depository is loaded, a :class:`DatabaseError` is raised.\n        \"\"\"\n        items = []\n        for label, entry in self.depository['stable'].entries.iteritems():\n            for molecule in species.molecule:\n                if molecule.isIsomorphic(entry.item):\n                    items.append((deepcopy(entry.data), self.depository['stable'], entry))\n                    break\n        for label, entry in self.depository['radical'].entries.iteritems():\n            for molecule in species.molecule:\n                if molecule.isIsomorphic(entry.item):\n                    items.append((deepcopy(entry.data), self.depository['radical'], entry))\n                    break\n        return items\n\n    def getThermoDataFromLibrary(self, species, library):\n        \"\"\"\n        Return the set of thermodynamic parameters corresponding to a given\n        :class:`Species` object `species` from the specified thermodynamics\n        `library`. If `library` is a string, the list of libraries is searched\n        for a library with that name. If no match is found in that library,\n        ``None`` is returned. If no corresponding library is found, a\n        :class:`DatabaseError` is raised.\n        \"\"\"\n        for label, entry in library.entries.iteritems():\n            for molecule in species.molecule:\n                if molecule.isIsomorphic(entry.item) and entry.data is not None:\n                    return (deepcopy(entry.data), library, entry)\n        return None\n\n    def getThermoDataFromGroups(self, species):\n        \"\"\"\n        Return the set of thermodynamic parameters corresponding to a given\n        :class:`Species` object `species` by estimation using the group\n        additivity values. If no group additivity values are loaded, a\n        :class:`DatabaseError` is raised.\n        \"\"\"       \n        thermo = []\n        for molecule in species.molecule:\n            molecule.clearLabeledAtoms()\n            molecule.updateAtomTypes()\n            tdata = self.estimateThermoViaGroupAdditivity(molecule)\n            thermo.append(tdata)\n\n        H298 = numpy.array([t.getEnthalpy(298.) for t in thermo])\n        indices = H298.argsort()\n        \n        species.molecule = [species.molecule[ind] for ind in indices]\n        \n        return (thermo[indices[0]], None, None)\n        \n    def estimateThermoViaGroupAdditivity(self, molecule):\n        \"\"\"\n        Return the set of thermodynamic parameters corresponding to a given\n        :class:`Molecule` object `molecule` by estimation using the group\n        additivity values. If no group additivity values are loaded, a\n        :class:`DatabaseError` is raised.\n        \"\"\"\n        # For thermo estimation we need the atoms to already be sorted because we\n        # iterate over them; if the order changes during the iteration then we\n        # will probably not visit the right atoms, and so will get the thermo wrong\n        molecule.sortVertices()\n\n        thermoData = None\n\n        if sum([atom.radicalElectrons for atom in molecule.atoms]) > 0: # radical species\n\n            # Make a copy of the structure so we don't change the original\n            saturatedStruct = molecule.copy(deep=True)\n\n            # Saturate structure by replacing all radicals with bonds to\n            # hydrogen atoms\n            added = {}\n            for atom in saturatedStruct.atoms:\n                for i in range(atom.radicalElectrons):\n                    H = Atom('H')\n                    bond = Bond(atom, H, 'S')\n                    saturatedStruct.addAtom(H)\n                    saturatedStruct.addBond(bond)\n                    if atom not in added:\n                        added[atom] = []\n                    added[atom].append([H, bond])\n                    atom.decrementRadical()\n\n            # Update the atom types of the saturated structure (not sure why\n            # this is necessary, because saturating with H shouldn't be\n            # changing atom types, but it doesn't hurt anything and is not\n            # very expensive, so will do it anyway)\n            saturatedStruct.updateConnectivityValues()\n            saturatedStruct.sortVertices()\n            saturatedStruct.updateAtomTypes()\n\n            # Get thermo estimate for saturated form of structure\n            thermoData = self.estimateThermoViaGroupAdditivity(saturatedStruct)\n            assert thermoData is not None, \"Thermo data of saturated {0} of molecule {1} is None!\".format(saturatedStruct, molecule)\n            # Undo symmetry number correction for saturated structure\n            thermoData.S298.value += constants.R * math.log(saturatedStruct.symmetryNumber)\n\n            # For each radical site, get radical correction\n            # Only one radical site should be considered at a time; all others\n            # should be saturated with hydrogen atoms\n            for atom in added:\n\n                # Remove the added hydrogen atoms and bond and restore the radical\n                for H, bond in added[atom]:\n                    saturatedStruct.removeBond(bond)\n                    saturatedStruct.removeAtom(H)\n                    atom.incrementRadical()\n\n                saturatedStruct.updateConnectivityValues()\n                \n                try:\n                    thermoData = self.__addThermoData(thermoData, self.__getGroupThermoData(self.groups['radical'], saturatedStruct, {'*':atom}))\n                except KeyError:\n                    logging.error(\"Couldn't find in radical thermo database:\")\n                    logging.error(molecule)\n                    logging.error(molecule.toAdjacencyList())\n                    raise\n                        \n                # Re-saturate\n                for H, bond in added[atom]:\n                    saturatedStruct.addAtom(H)\n                    saturatedStruct.addBond(bond)\n                    atom.decrementRadical()\n\n                # Subtract the enthalpy of the added hydrogens\n                for H, bond in added[atom]:\n                    thermoData.H298.value -= 52.103 * 4184\n\n            # Correct the entropy for the symmetry number\n\n        else: # non-radical species\n            # Generate estimate of thermodynamics\n            for atom in molecule.atoms:\n                # Iterate over heavy (non-hydrogen) atoms\n                if atom.isNonHydrogen():\n                    # Get initial thermo estimate from main group database\n                    try:\n                        if thermoData is None:\n                            thermoData = self.__getGroupThermoData(self.groups['group'], molecule, {'*':atom})\n                        else:\n                            thermoData = self.__addThermoData(thermoData, self.__getGroupThermoData(self.groups['group'], molecule, {'*':atom}))\n                    except KeyError:\n                        logging.error(\"Couldn't find in main thermo database:\")\n                        logging.error(molecule)\n                        logging.error(molecule.toAdjacencyList())\n                        raise\n                    # Correct for gauche and 1,5- interactions\n                    try:\n                        thermoData = self.__addThermoData(thermoData, self.__getGroupThermoData(self.groups['gauche'], molecule, {'*':atom}))\n                    except KeyError: pass\n                    try:\n                        thermoData = self.__addThermoData(thermoData, self.__getGroupThermoData(self.groups['int15'], molecule, {'*':atom}))\n                    except KeyError: pass\n                    try:\n                        thermoData = self.__addThermoData(thermoData, self.__getGroupThermoData(self.groups['other'], molecule, {'*':atom}))\n                    except KeyError: pass\n\n            # Do ring corrections separately because we only want to match\n            # each ring one time; this doesn't work yet\n            rings = molecule.getSmallestSetOfSmallestRings()\n            for ring in rings:\n                # Make a temporary structure containing only the atoms in the ring\n                # NB. if any of the ring corrections depend on ligands not in the ring, they will not be found!\n                ringStructure = Molecule()\n                newAtoms = dict()\n                for atom in ring:\n                    newAtoms[atom] = atom.copy()\n                    ringStructure.addAtom(newAtoms[atom]) # (addAtom deletes the atom's bonds)\n                for atom1 in ring:\n                    for atom2 in ring:\n                        if molecule.hasBond(atom1, atom2):\n                            ringStructure.addBond(Bond(newAtoms[atom1], newAtoms[atom2], atom1.bonds[atom2].order ))\n\n                # Get thermo correction for this ring\n                try:\n                    thermoData = self.__addThermoData(thermoData, self.__getGroupThermoData(self.groups['ring'], ringStructure, {}))\n                except KeyError:\n                    logging.error(\"Couldn't find in ring database:\")\n                    logging.error(ringStructure)\n                    logging.error(ringStructure.toAdjacencyList())\n                    raise\n                \n        # Correct entropy for symmetry number\n        molecule.calculateSymmetryNumber()\n        thermoData.S298.value -= constants.R * math.log(molecule.symmetryNumber)\n\n        return thermoData\n\n    def __addThermoData(self, thermoData1, thermoData2):\n        \"\"\"\n        Add two :class:`ThermoData` objects `thermoData1` and `thermoData2`\n        together, returning their sum as a new :class:`ThermoData` object.\n        \"\"\"\n        if len(thermoData1.Tdata.values) != len(thermoData2.Tdata.values) or any([T1 != T2 for T1, T2 in zip(thermoData1.Tdata.values, thermoData2.Tdata.values)]):\n            raise ThermoError('Cannot add these ThermoData objects due to their having different temperature points.')\n        new = ThermoData(\n            Tdata = (thermoData1.Tdata.values, thermoData1.Tdata.units),\n            Cpdata = (thermoData1.Cpdata.values + thermoData2.Cpdata.values, thermoData1.Tdata.units),\n            H298 = (thermoData1.H298.value + thermoData2.H298.value, thermoData1.Tdata.units),\n            S298 = (thermoData1.S298.value + thermoData2.S298.value, thermoData1.Tdata.units),\n        )\n        if thermoData1.comment == '': new.comment = thermoData2.comment\n        elif thermoData2.comment == '': new.comment = thermoData1.comment\n        else: new.comment = thermoData1.comment + ' + ' + thermoData2.comment\n        return new\n    \n    def __getGroupThermoData(self, database, molecule, atom):\n        \"\"\"\n        Determine the group additivity thermodynamic data for the atom `atom`\n        in the structure `structure`.\n        \"\"\"\n\n        node0 = database.descendTree(molecule, atom, None)\n\n        if node0 is None:\n            raise KeyError('Node not found in database.')\n\n        # It's possible (and allowed) that items in the tree may not be in the\n        # library, in which case we need to fall up the tree until we find an\n        # ancestor that has an entry in the library\n        node = node0\n        while node.data is None and node is not None:\n            node = node.parent\n        if node is None:\n            raise InvalidDatabaseError('Unable to determine thermo parameters for {0}: no library entries for {1} or any of its ancestors.'.format(molecule, node0) )\n\n        data = node.data; comment = node.label\n        while isinstance(data, str) and data is not None:\n            for entry in database.entries.values():\n                if entry.label == data:\n                    data = entry.data\n                    comment = entry.label\n                    break\n        data = deepcopy(data)\n        data.comment = '{0}({1})'.format(database.label, comment)\n\n        # This code prints the hierarchy of the found node; useful for debugging\n        #result = ''\n        #while node is not None:\n        #   result = ' -> ' + node + result\n        #   node = database.tree.parent[node]\n        #print result[4:]\n\n        return data\n", "meta": {"hexsha": "cd066bbd73ee983f296e4802479c73b7f8688f99", "size": 37592, "ext": "py", "lang": "Python", "max_stars_repo_path": "rmgpy/data/thermo.py", "max_stars_repo_name": "sean-v8/RMG-Py", "max_stars_repo_head_hexsha": "7cc7c3bfb330786526c56113d98c785bcaaa161a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rmgpy/data/thermo.py", "max_issues_repo_name": "sean-v8/RMG-Py", "max_issues_repo_head_hexsha": "7cc7c3bfb330786526c56113d98c785bcaaa161a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rmgpy/data/thermo.py", "max_forks_repo_name": "sean-v8/RMG-Py", "max_forks_repo_head_hexsha": "7cc7c3bfb330786526c56113d98c785bcaaa161a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8591885442, "max_line_length": 165, "alphanum_fraction": 0.5769046606, "include": true, "reason": "import numpy", "num_tokens": 8456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3775406547908327, "lm_q1q2_score": 0.19024506557469006}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport functools\nimport numpy as np\nimport pycuda.driver as cuda\nfrom graphdot.cuda.array import umempty, umzeros\nfrom graphdot.codegen import Template\nfrom graphdot.codegen.cpptool import decltype\nfrom graphdot.microkernel import TensorProduct, Product\nfrom graphdot.kernel.marginalized._backend_cuda import CUDABackend\nfrom graphdot.kernel.marginalized._octilegraph import OctileGraph\n\n\nclass AltCUDABackend(CUDABackend):\n\n    def __init__(self, **kwargs):\n        super().__init__(**kwargs)\n\n    def allocate_pcg_scratch(self, number, max_graph_size, traits):\n        length = max_graph_size**2\n        n_temporaries = 5\n\n        self.scratch_pcg, self.scratch_pcg_d = self._allocate_scratch(\n            self.scratch_pcg, self.scratch_pcg_d, number, length,\n            n_temporaries\n        )\n        return self.scratch_pcg_d\n\n    @property\n    @functools.lru_cache(maxsize=1)\n    def template(self):\n        return Template(os.path.join(os.path.dirname(__file__), 'template.cu'))\n\n    def __call__(self, graphs, node_kernel, edge_kernel, p, q, eps, ftol, gtol,\n                 jobs, gramian, traits, timer):\n        ''' transfer graphs and starting probabilities to GPU '''\n        timer.tic('transferring graphs to GPU')\n\n        og_last = None\n        graphs_d = umempty(len(graphs), dtype=OctileGraph.dtype)\n        for i, g in enumerate(graphs):\n            og, ogstate = self._register_graph(g)\n            if i > 0:\n                self._assert_homogeneous(og_last, og)\n            og_last = og\n            graphs_d[i] = ogstate\n\n        weighted = og_last.weighted\n        node_t = og_last.node_t\n        edge_t = og_last.edge_t\n\n        timer.toc('transferring graphs to GPU')\n\n        ''' allocate global job counter '''\n        timer.tic('allocate global job counter')\n        i_job_global = umzeros(1, np.uint32)\n        timer.toc('allocate global job counter')\n\n        ''' code generation '''\n        timer.tic('code generation')\n        if weighted:\n            edge_kernel = TensorProduct(weight=Product(),\n                                        label=edge_kernel)\n\n        node_kernel_src = self.gencode_kernel(node_kernel, 'node_kernel')\n        edge_kernel_src = self.gencode_kernel(edge_kernel, 'edge_kernel')\n        p_start_src = self.gencode_probability(p, 'p_start')\n\n        with self.template.context(traits=traits) as template:\n            self.source = template.render(\n                node_kernel=node_kernel_src,\n                edge_kernel=edge_kernel_src,\n                p_start=p_start_src,\n                node_t=decltype(node_t),\n                edge_t=decltype(edge_t)\n            )\n        timer.toc('code generation')\n\n        ''' JIT '''\n        timer.tic('JIT')\n        kernel = self.module.get_function('alt_graph_kernel_solver')\n        timer.toc('JIT')\n\n        ''' calculate launch configuration '''\n        timer.tic('calculating launch configuration')\n        launch_block_count = (self.device.MULTIPROCESSOR_COUNT\n                              * self.block_per_sm)\n        shmem_bytes_per_warp = self.module.get_global(\n            'shmem_bytes_per_warp'\n        )[1]\n        shmem_bytes_per_block = (shmem_bytes_per_warp * self.block_size\n                                 // self.device.WARP_SIZE)\n\n        ''' allocate scratch buffers '''\n        max_graph_size = np.max([len(g.nodes) for g in graphs])\n        scratch_pcg = self.allocate_pcg_scratch(\n            launch_block_count, max_graph_size, traits\n        )\n\n        ''' copy micro kernel parameters to GPU '''\n        for name, uker in [('node_kernel', node_kernel),\n                           ('edge_kernel', edge_kernel)]:\n            states = np.array(\n                self.pack_state(uker, diff_grid=False, diff_eps=eps),\n                dtype=uker.dtype\n            )\n\n            p_uker, _ = self.module.get_global(name)\n            cuda.memcpy_htod(p_uker, states[:1])\n\n        p_p_start, _ = self.module.get_global('p_start')\n        cuda.memcpy_htod(\n            p_p_start, np.array([p.state], dtype=p.dtype)\n        )\n\n        timer.toc('calculating launch configuration')\n\n        ''' GPU kernel execution '''\n        timer.tic('GPU kernel execution')\n        kernel(\n            graphs_d,\n            scratch_pcg,\n            jobs,\n            gramian,\n            i_job_global,\n            np.uint32(len(jobs)),\n            np.float32(q),\n            np.float32(q),  # placeholder for q0\n            np.float32(eps),\n            np.float32(ftol),\n            np.float32(gtol),\n            grid=(launch_block_count, 1, 1),\n            block=(self.block_size, 1, 1),\n            shared=shmem_bytes_per_block,\n        )\n        self.ctx.synchronize()\n        timer.toc('GPU kernel execution')\n", "meta": {"hexsha": "49860676656b2ac7bd18434bb789f2d0cfb04757", "size": 4777, "ext": "py", "lang": "Python", "max_stars_repo_path": "graphdot/experimental/alterantive_mgk/_backend_cuda.py", "max_stars_repo_name": "yhtang/GraphDot", "max_stars_repo_head_hexsha": "3d5ed4fbb2f6912052baa42780b436da76979691", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-02-14T18:07:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T12:07:31.000Z", "max_issues_repo_path": "graphdot/experimental/alterantive_mgk/_backend_cuda.py", "max_issues_repo_name": "yhtang/graphdot", "max_issues_repo_head_hexsha": "3d5ed4fbb2f6912052baa42780b436da76979691", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-03-19T19:07:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-24T06:08:51.000Z", "max_forks_repo_path": "graphdot/experimental/alterantive_mgk/_backend_cuda.py", "max_forks_repo_name": "yhtang/graphdot", "max_forks_repo_head_hexsha": "3d5ed4fbb2f6912052baa42780b436da76979691", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-17T06:11:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-07T11:56:33.000Z", "avg_line_length": 34.3669064748, "max_line_length": 79, "alphanum_fraction": 0.5978647687, "include": true, "reason": "import numpy,import pycuda", "num_tokens": 1086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.19018713523796368}}
{"text": "# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>\n#         Daniel Strohmeier <daniel.strohmeier@gmail.com>\n#\n# License: Simplified BSD\n\nimport numpy as np\nfrom scipy import linalg\n\nfrom ..source_estimate import (SourceEstimate, VolSourceEstimate,\n                               _BaseSourceEstimate)\nfrom ..minimum_norm.inverse import (combine_xyz, _prepare_forward,\n                                    _check_reference)\nfrom ..forward import is_fixed_orient\nfrom ..io.pick import pick_channels_evoked\nfrom ..io.proj import deactivate_proj\nfrom ..utils import logger, verbose, _check_depth\nfrom ..dipole import Dipole\n\nfrom .mxne_optim import (mixed_norm_solver, iterative_mixed_norm_solver, _Phi,\n                         norm_l2inf, tf_mixed_norm_solver, norm_epsilon_inf)\n\n\n@verbose\ndef _prepare_weights(forward, gain, source_weighting, weights, weights_min):\n    mask = None\n    if isinstance(weights, _BaseSourceEstimate):\n        weights = np.max(np.abs(weights.data), axis=1)\n    weights_max = np.max(weights)\n    if weights_min > weights_max:\n        raise ValueError('weights_min > weights_max (%s > %s)' %\n                         (weights_min, weights_max))\n    weights_min = weights_min / weights_max\n    weights = weights / weights_max\n    n_dip_per_pos = 1 if is_fixed_orient(forward) else 3\n    weights = np.ravel(np.tile(weights, [n_dip_per_pos, 1]).T)\n    if len(weights) != gain.shape[1]:\n        raise ValueError('weights do not have the correct dimension '\n                         ' (%d != %d)' % (len(weights), gain.shape[1]))\n    if len(source_weighting.shape) == 1:\n        source_weighting *= weights\n    else:\n        source_weighting *= weights[:, None]\n    gain *= weights[None, :]\n\n    if weights_min is not None:\n        mask = (weights > weights_min)\n        gain = gain[:, mask]\n        n_sources = np.sum(mask) // n_dip_per_pos\n        logger.info(\"Reducing source space to %d sources\" % n_sources)\n\n    return gain, source_weighting, mask\n\n\ndef _prepare_gain(forward, info, noise_cov, pca, depth, loose, rank,\n                  weights=None, weights_min=None):\n    depth = _check_depth(depth, 'depth_sparse')\n    forward, gain_info, gain, _, _, source_weighting, _, _, whitener = \\\n        _prepare_forward(forward, info, noise_cov, 'auto', loose, rank, pca,\n                         use_cps=True, **depth)\n\n    if weights is None:\n        mask = None\n    else:\n        gain, source_weighting, mask = _prepare_weights(\n            forward, gain, source_weighting, weights, weights_min)\n\n    return forward, gain, gain_info, whitener, source_weighting, mask\n\n\ndef _reapply_source_weighting(X, source_weighting, active_set):\n    X *= source_weighting[active_set][:, None]\n    return X\n\n\ndef _compute_residual(forward, evoked, X, active_set, info):\n    # OK, picking based on row_names is safe\n    sel = [forward['sol']['row_names'].index(c) for c in info['ch_names']]\n    residual = evoked.copy()\n    residual = pick_channels_evoked(residual, include=info['ch_names'])\n    r_tmp = residual.copy()\n\n    r_tmp.data = np.dot(forward['sol']['data'][sel, :][:, active_set], X)\n\n    # Take care of proj\n    active_projs = list()\n    non_active_projs = list()\n    for p in evoked.info['projs']:\n        if p['active']:\n            active_projs.append(p)\n        else:\n            non_active_projs.append(p)\n\n    if len(active_projs) > 0:\n        r_tmp.info['projs'] = deactivate_proj(active_projs, copy=True)\n        r_tmp.apply_proj()\n        r_tmp.add_proj(non_active_projs, remove_existing=False)\n\n    residual.data -= r_tmp.data\n\n    return residual\n\n\n@verbose\ndef _make_sparse_stc(X, active_set, forward, tmin, tstep,\n                     active_is_idx=False, verbose=None):\n    if not is_fixed_orient(forward):\n        logger.info('combining the current components...')\n        X = combine_xyz(X)\n\n    if not active_is_idx:\n        active_idx = np.where(active_set)[0]\n    else:\n        active_idx = active_set\n\n    n_dip_per_pos = 1 if is_fixed_orient(forward) else 3\n    if n_dip_per_pos > 1:\n        active_idx = np.unique(active_idx // n_dip_per_pos)\n\n    src = forward['src']\n\n    if src.kind != 'surface':\n        vertices = src[0]['vertno'][active_idx]\n        stc = VolSourceEstimate(X, vertices=vertices, tmin=tmin, tstep=tstep)\n    else:\n        vertices = []\n        n_points_so_far = 0\n        for this_src in src:\n            this_n_points_so_far = n_points_so_far + len(this_src['vertno'])\n            this_active_idx = active_idx[(n_points_so_far <= active_idx) &\n                                         (active_idx < this_n_points_so_far)]\n            this_active_idx -= n_points_so_far\n            this_vertno = this_src['vertno'][this_active_idx]\n            n_points_so_far = this_n_points_so_far\n            vertices.append(this_vertno)\n\n        stc = SourceEstimate(X, vertices=vertices, tmin=tmin, tstep=tstep)\n\n    return stc\n\n\n@verbose\ndef _make_dipoles_sparse(X, active_set, forward, tmin, tstep, M, M_est,\n                         active_is_idx=False, verbose=None):\n    times = tmin + tstep * np.arange(X.shape[1])\n\n    if not active_is_idx:\n        active_idx = np.where(active_set)[0]\n    else:\n        active_idx = active_set\n\n    n_dip_per_pos = 1 if is_fixed_orient(forward) else 3\n    if n_dip_per_pos > 1:\n        active_idx = np.unique(active_idx // n_dip_per_pos)\n\n    gof = np.zeros(M_est.shape[1])\n    M_norm2 = np.sum(M ** 2, axis=0)\n    R_norm2 = np.sum((M - M_est) ** 2, axis=0)\n    gof[M_norm2 > 0.0] = 1. - R_norm2[M_norm2 > 0.0] / M_norm2[M_norm2 > 0.0]\n    gof *= 100.\n\n    dipoles = []\n    for k, i_dip in enumerate(active_idx):\n        i_pos = forward['source_rr'][i_dip][np.newaxis, :]\n        i_pos = i_pos.repeat(len(times), axis=0)\n        X_ = X[k * n_dip_per_pos: (k + 1) * n_dip_per_pos]\n        if n_dip_per_pos == 1:\n            amplitude = X_[0]\n            i_ori = forward['source_nn'][i_dip][np.newaxis, :]\n            i_ori = i_ori.repeat(len(times), axis=0)\n        else:\n            if forward['surf_ori']:\n                X_ = np.dot(forward['source_nn'][\n                    i_dip * n_dip_per_pos:(i_dip + 1) * n_dip_per_pos].T, X_)\n\n            amplitude = np.sqrt(np.sum(X_ ** 2, axis=0))\n            i_ori = np.zeros((len(times), 3))\n            i_ori[amplitude > 0.] = (X_[:, amplitude > 0.] /\n                                     amplitude[amplitude > 0.]).T\n\n        dipoles.append(Dipole(times, i_pos, amplitude, i_ori, gof))\n\n    return dipoles\n\n\n@verbose\ndef make_stc_from_dipoles(dipoles, src, verbose=None):\n    \"\"\"Convert a list of spatio-temporal dipoles into a SourceEstimate.\n\n    Parameters\n    ----------\n    dipoles : Dipole | list of instances of Dipole\n        The dipoles to convert.\n    src : instance of SourceSpaces\n        The source space used to generate the forward operator.\n    %(verbose)s\n\n    Returns\n    -------\n    stc : SourceEstimate\n        The source estimate.\n    \"\"\"\n    logger.info('Converting dipoles into a SourceEstimate.')\n    if isinstance(dipoles, Dipole):\n        dipoles = [dipoles]\n    if not isinstance(dipoles, list):\n        raise ValueError('Dipoles must be an instance of Dipole or '\n                         'a list of instances of Dipole. '\n                         'Got %s!' % type(dipoles))\n    tmin = dipoles[0].times[0]\n    tstep = dipoles[0].times[1] - tmin\n    X = np.zeros((len(dipoles), len(dipoles[0].times)))\n    source_rr = np.concatenate([_src['rr'][_src['vertno'], :] for _src in src],\n                               axis=0)\n    n_lh_points = len(src[0]['vertno'])\n    lh_vertno = list()\n    rh_vertno = list()\n    for i in range(len(dipoles)):\n        if not np.all(dipoles[i].pos == dipoles[i].pos[0]):\n            raise ValueError('Only dipoles with fixed position over time '\n                             'are supported!')\n        X[i] = dipoles[i].amplitude\n        idx = np.all(source_rr == dipoles[i].pos[0], axis=1)\n        idx = np.where(idx)[0][0]\n        if idx < n_lh_points:\n            lh_vertno.append(src[0]['vertno'][idx])\n        else:\n            rh_vertno.append(src[1]['vertno'][idx - n_lh_points])\n    vertices = [np.array(lh_vertno).astype(int),\n                np.array(rh_vertno).astype(int)]\n    stc = SourceEstimate(X, vertices=vertices, tmin=tmin, tstep=tstep,\n                         subject=src._subject)\n    logger.info('[done]')\n    return stc\n\n\n@verbose\ndef mixed_norm(evoked, forward, noise_cov, alpha, loose='auto', depth=0.8,\n               maxit=3000, tol=1e-4, active_set_size=10,\n               debias=True, time_pca=True, weights=None, weights_min=0.,\n               solver='auto', n_mxne_iter=1, return_residual=False,\n               return_as_dipoles=False, dgap_freq=10, rank=None,\n               verbose=None):\n    \"\"\"Mixed-norm estimate (MxNE) and iterative reweighted MxNE (irMxNE).\n\n    Compute L1/L2 mixed-norm solution [1]_ or L0.5/L2 [2]_ mixed-norm\n    solution on evoked data.\n\n    Parameters\n    ----------\n    evoked : instance of Evoked or list of instances of Evoked\n        Evoked data to invert.\n    forward : dict\n        Forward operator.\n    noise_cov : instance of Covariance\n        Noise covariance to compute whitener.\n    alpha : float in range [0, 100)\n        Regularization parameter. 0 means no regularization, 100 would give 0\n        active dipole.\n    loose : float in [0, 1] | 'auto'\n        Value that weights the source variances of the dipole components\n        that are parallel (tangential) to the cortical surface. If loose\n        is 0 then the solution is computed with fixed orientation.\n        If loose is 1, it corresponds to free orientations.\n        The default value ('auto') is set to 0.2 for surface-oriented source\n        space and set to 1.0 for volumic or discrete source space.\n    %(depth)s\n    maxit : int\n        Maximum number of iterations.\n    tol : float\n        Tolerance parameter.\n    active_set_size : int | None\n        Size of active set increment. If None, no active set strategy is used.\n    debias : bool\n        Remove coefficient amplitude bias due to L1 penalty.\n    time_pca : bool or int\n        If True the rank of the concatenated epochs is reduced to\n        its true dimension. If is 'int' the rank is limited to this value.\n    weights : None | array | SourceEstimate\n        Weight for penalty in mixed_norm. Can be None, a\n        1d array with shape (n_sources,), or a SourceEstimate (e.g. obtained\n        with wMNE, dSPM, or fMRI).\n    weights_min : float\n        Do not consider in the estimation sources for which weights\n        is less than weights_min.\n    solver : 'prox' | 'cd' | 'bcd' | 'auto'\n        The algorithm to use for the optimization. 'prox' stands for\n        proximal iterations using the FISTA algorithm, 'cd' uses\n        coordinate descent, and 'bcd' applies block coordinate descent.\n        'cd' is only available for fixed orientation.\n    n_mxne_iter : int\n        The number of MxNE iterations. If > 1, iterative reweighting\n        is applied.\n    return_residual : bool\n        If True, the residual is returned as an Evoked instance.\n    return_as_dipoles : bool\n        If True, the sources are returned as a list of Dipole instances.\n    dgap_freq : int or np.inf\n        The duality gap is evaluated every dgap_freq iterations. Ignored if\n        solver is 'cd'.\n    %(rank_None)s\n\n        .. versionadded:: 0.18\n    %(verbose)s\n\n    Returns\n    -------\n    stc : SourceEstimate | list of SourceEstimate\n        Source time courses for each evoked data passed as input.\n    residual : instance of Evoked\n        The residual a.k.a. data not explained by the sources.\n        Only returned if return_residual is True.\n\n    See Also\n    --------\n    tf_mixed_norm\n\n    References\n    ----------\n    .. [1] A. Gramfort, M. Kowalski, M. Hämäläinen,\n       \"Mixed-norm estimates for the M/EEG inverse problem using accelerated\n       gradient methods\", Physics in Medicine and Biology, 2012.\n       https://doi.org/10.1088/0031-9155/57/7/1937\n\n    .. [2] D. Strohmeier, Y. Bekhti, J. Haueisen, A. Gramfort,\n       \"The Iterative Reweighted Mixed-Norm Estimate for Spatio-Temporal\n       MEG/EEG Source Reconstruction\", IEEE Transactions of Medical Imaging,\n       Volume 35 (10), pp. 2218-2228, 2016.\n    \"\"\"\n    if not (0. <= alpha < 100.):\n        raise ValueError('alpha must be in [0, 100). '\n                         'Got alpha = %s' % alpha)\n    if n_mxne_iter < 1:\n        raise ValueError('MxNE has to be computed at least 1 time. '\n                         'Requires n_mxne_iter >= 1, got %d' % n_mxne_iter)\n    if dgap_freq <= 0.:\n        raise ValueError('dgap_freq must be a positive integer.'\n                         ' Got dgap_freq = %s' % dgap_freq)\n\n    pca = True\n    if not isinstance(evoked, list):\n        evoked = [evoked]\n\n    _check_reference(evoked[0])\n\n    all_ch_names = evoked[0].ch_names\n    if not all(all_ch_names == evoked[i].ch_names\n               for i in range(1, len(evoked))):\n        raise Exception('All the datasets must have the same good channels.')\n\n    forward, gain, gain_info, whitener, source_weighting, mask = _prepare_gain(\n        forward, evoked[0].info, noise_cov, pca, depth, loose, rank,\n        weights, weights_min)\n\n    sel = [all_ch_names.index(name) for name in gain_info['ch_names']]\n    M = np.concatenate([e.data[sel] for e in evoked], axis=1)\n\n    # Whiten data\n    logger.info('Whitening data matrix.')\n    M = np.dot(whitener, M)\n\n    if time_pca:\n        U, s, Vh = linalg.svd(M, full_matrices=False)\n        if not isinstance(time_pca, bool) and isinstance(time_pca, int):\n            U = U[:, :time_pca]\n            s = s[:time_pca]\n            Vh = Vh[:time_pca]\n        M = U * s\n\n    # Scaling to make setting of alpha easy\n    n_dip_per_pos = 1 if is_fixed_orient(forward) else 3\n    alpha_max = norm_l2inf(np.dot(gain.T, M), n_dip_per_pos, copy=False)\n    alpha_max *= 0.01\n    gain /= alpha_max\n    source_weighting /= alpha_max\n\n    if n_mxne_iter == 1:\n        X, active_set, E = mixed_norm_solver(\n            M, gain, alpha, maxit=maxit, tol=tol,\n            active_set_size=active_set_size, n_orient=n_dip_per_pos,\n            debias=debias, solver=solver, dgap_freq=dgap_freq, verbose=verbose)\n    else:\n        X, active_set, E = iterative_mixed_norm_solver(\n            M, gain, alpha, n_mxne_iter, maxit=maxit, tol=tol,\n            n_orient=n_dip_per_pos, active_set_size=active_set_size,\n            debias=debias, solver=solver, dgap_freq=dgap_freq, verbose=verbose)\n\n    if time_pca:\n        X = np.dot(X, Vh)\n        M = np.dot(M, Vh)\n\n    # Compute estimated whitened sensor data\n    M_estimated = np.dot(gain[:, active_set], X)\n\n    if mask is not None:\n        active_set_tmp = np.zeros(len(mask), dtype=np.bool)\n        active_set_tmp[mask] = active_set\n        active_set = active_set_tmp\n        del active_set_tmp\n\n    if active_set.sum() == 0:\n        raise Exception(\"No active dipoles found. alpha is too big.\")\n\n    # Reapply weights to have correct unit\n    X = _reapply_source_weighting(X, source_weighting, active_set)\n\n    outs = list()\n    residual = list()\n    cnt = 0\n    for e in evoked:\n        tmin = e.times[0]\n        tstep = 1.0 / e.info['sfreq']\n        Xe = X[:, cnt:(cnt + len(e.times))]\n        if return_as_dipoles:\n            out = _make_dipoles_sparse(\n                Xe, active_set, forward, tmin, tstep,\n                M[:, cnt:(cnt + len(e.times))],\n                M_estimated[:, cnt:(cnt + len(e.times))], verbose=None)\n        else:\n            out = _make_sparse_stc(Xe, active_set, forward, tmin, tstep)\n        outs.append(out)\n        cnt += len(e.times)\n\n        if return_residual:\n            residual.append(_compute_residual(forward, e, Xe, active_set,\n                                              gain_info))\n\n    logger.info('[done]')\n\n    if len(outs) == 1:\n        out = outs[0]\n        if return_residual:\n            residual = residual[0]\n    else:\n        out = outs\n\n    if return_residual:\n        out = out, residual\n\n    return out\n\n\ndef _window_evoked(evoked, size):\n    \"\"\"Window evoked (size in seconds).\"\"\"\n    if isinstance(size, (float, int)):\n        lsize = rsize = float(size)\n    else:\n        lsize, rsize = size\n    evoked = evoked.copy()\n    sfreq = float(evoked.info['sfreq'])\n    lsize = int(lsize * sfreq)\n    rsize = int(rsize * sfreq)\n    lhann = np.hanning(lsize * 2)[:lsize]\n    rhann = np.hanning(rsize * 2)[-rsize:]\n    window = np.r_[lhann, np.ones(len(evoked.times) - lsize - rsize), rhann]\n    evoked.data *= window[None, :]\n    return evoked\n\n\n@verbose\ndef tf_mixed_norm(evoked, forward, noise_cov,\n                  loose='auto', depth=0.8, maxit=3000,\n                  tol=1e-4, weights=None, weights_min=0., pca=True,\n                  debias=True, wsize=64, tstep=4, window=0.02,\n                  return_residual=False, return_as_dipoles=False,\n                  alpha=None, l1_ratio=None, dgap_freq=10, rank=None,\n                  verbose=None):\n    \"\"\"Time-Frequency Mixed-norm estimate (TF-MxNE).\n\n    Compute L1/L2 + L1 mixed-norm solution on time-frequency\n    dictionary. Works with evoked data [1]_ [2]_.\n\n    Parameters\n    ----------\n    evoked : instance of Evoked\n        Evoked data to invert.\n    forward : dict\n        Forward operator.\n    noise_cov : instance of Covariance\n        Noise covariance to compute whitener.\n    loose : float in [0, 1] | 'auto'\n        Value that weights the source variances of the dipole components\n        that are parallel (tangential) to the cortical surface. If loose\n        is 0 then the solution is computed with fixed orientation.\n        If loose is 1, it corresponds to free orientations.\n        The default value ('auto') is set to 0.2 for surface-oriented source\n        space and set to 1.0 for volumic or discrete source space.\n    %(depth)s\n    maxit : int\n        Maximum number of iterations.\n    tol : float\n        Tolerance parameter.\n    weights: None | array | SourceEstimate\n        Weight for penalty in mixed_norm. Can be None or\n        1d array of length n_sources or a SourceEstimate e.g. obtained\n        with wMNE or dSPM or fMRI.\n    weights_min: float\n        Do not consider in the estimation sources for which weights\n        is less than weights_min.\n    pca: bool\n        If True the rank of the data is reduced to true dimension.\n    debias: bool\n        Remove coefficient amplitude bias due to L1 penalty.\n    wsize: int or array-like\n        Length of the STFT window in samples (must be a multiple of 4).\n        If an array is passed, multiple TF dictionaries are used (each having\n        its own wsize and tstep) and each entry of wsize must be a multiple\n        of 4. See [3]_.\n    tstep: int or array-like\n        Step between successive windows in samples (must be a multiple of 2,\n        a divider of wsize and smaller than wsize/2) (default: wsize/2).\n        If an array is passed, multiple TF dictionaries are used (each having\n        its own wsize and tstep), and each entry of tstep must be a multiple\n        of 2 and divide the corresponding entry of wsize. See [3]_.\n    window : float or (float, float)\n        Length of time window used to take care of edge artifacts in seconds.\n        It can be one float or float if the values are different for left\n        and right window length.\n    return_residual : bool\n        If True, the residual is returned as an Evoked instance.\n    return_as_dipoles : bool\n        If True, the sources are returned as a list of Dipole instances.\n    alpha : float in [0, 100) or None\n        Overall regularization parameter.\n        If alpha and l1_ratio are not None, alpha_space and alpha_time are\n        overridden by alpha * alpha_max * (1. - l1_ratio) and alpha * alpha_max\n        * l1_ratio. 0 means no regularization, 100 would give 0 active dipole.\n    l1_ratio : float in [0, 1] or None\n        Proportion of temporal regularization.\n        If l1_ratio and alpha are not None, alpha_space and alpha_time are\n        overridden by alpha * alpha_max * (1. - l1_ratio) and alpha * alpha_max\n        * l1_ratio. 0 means no time regularization aka MxNE.\n    dgap_freq : int or np.inf\n        The duality gap is evaluated every dgap_freq iterations.\n    %(rank_None)s\n\n        .. versionadded:: 0.18\n    %(verbose)s\n\n\n    Returns\n    -------\n    stc : instance of SourceEstimate\n        Source time courses.\n    residual : instance of Evoked\n        The residual a.k.a. data not explained by the sources.\n        Only returned if return_residual is True.\n\n    See Also\n    --------\n    mixed_norm\n\n    References\n    ----------\n    .. [1] A. Gramfort, D. Strohmeier, J. Haueisen, M. Hämäläinen, M. Kowalski\n       \"Time-Frequency Mixed-Norm Estimates: Sparse M/EEG imaging with\n       non-stationary source activations\",\n       Neuroimage, Volume 70, pp. 410-422, 15 April 2013.\n       DOI: 10.1016/j.neuroimage.2012.12.051\n\n    .. [2] A. Gramfort, D. Strohmeier, J. Haueisen, M. Hämäläinen, M. Kowalski\n       \"Functional Brain Imaging with M/EEG Using Structured Sparsity in\n       Time-Frequency Dictionaries\",\n       Proceedings Information Processing in Medical Imaging\n       Lecture Notes in Computer Science, Volume 6801/2011, pp. 600-611, 2011.\n       DOI: 10.1007/978-3-642-22092-0_49\n\n    .. [3] Y. Bekhti, D. Strohmeier, M. Jas, R. Badeau, A. Gramfort.\n       \"M/EEG source localization with multiscale time-frequency dictionaries\",\n       6th International Workshop on Pattern Recognition in Neuroimaging\n       (PRNI), 2016.\n       DOI: 10.1109/PRNI.2016.7552337\n    \"\"\"\n    _check_reference(evoked)\n\n    all_ch_names = evoked.ch_names\n    info = evoked.info\n\n    if not (0. <= alpha < 100.):\n        raise ValueError('alpha must be in [0, 100). '\n                         'Got alpha = %s' % alpha)\n\n    if not (0. <= l1_ratio <= 1.):\n        raise ValueError('l1_ratio must be in range [0, 1].'\n                         ' Got l1_ratio = %s' % l1_ratio)\n    alpha_space = alpha * (1. - l1_ratio)\n    alpha_time = alpha * l1_ratio\n\n    if dgap_freq <= 0.:\n        raise ValueError('dgap_freq must be a positive integer.'\n                         ' Got dgap_freq = %s' % dgap_freq)\n\n    tstep = np.atleast_1d(tstep)\n    wsize = np.atleast_1d(wsize)\n    if len(tstep) != len(wsize):\n        raise ValueError('The same number of window sizes and steps must be '\n                         'passed. Got tstep = %s and wsize = %s' %\n                         (tstep, wsize))\n\n    forward, gain, gain_info, whitener, source_weighting, mask = _prepare_gain(\n        forward, evoked.info, noise_cov, pca, depth, loose, rank,\n        weights, weights_min)\n    n_dip_per_pos = 1 if is_fixed_orient(forward) else 3\n\n    if window is not None:\n        evoked = _window_evoked(evoked, window)\n\n    sel = [all_ch_names.index(name) for name in gain_info[\"ch_names\"]]\n    M = evoked.data[sel]\n\n    # Whiten data\n    logger.info('Whitening data matrix.')\n    M = np.dot(whitener, M)\n\n    # Scaling to make setting of alpha easy\n    n_steps = np.ceil(M.shape[1] / tstep.astype(float)).astype(int)\n    n_freqs = wsize // 2 + 1\n    n_coefs = n_steps * n_freqs\n    phi = _Phi(wsize, tstep, n_coefs)\n\n    alpha_max = norm_epsilon_inf(gain, M, phi, l1_ratio, n_dip_per_pos)\n    alpha_max *= 0.01\n    gain /= alpha_max\n    source_weighting /= alpha_max\n\n    X, active_set, E = tf_mixed_norm_solver(\n        M, gain, alpha_space, alpha_time, wsize=wsize, tstep=tstep,\n        maxit=maxit, tol=tol, verbose=verbose, n_orient=n_dip_per_pos,\n        dgap_freq=dgap_freq, debias=debias)\n\n    if active_set.sum() == 0:\n        raise Exception(\"No active dipoles found. \"\n                        \"alpha_space/alpha_time are too big.\")\n\n    # Compute estimated whitened sensor data\n    M_estimated = np.dot(gain[:, active_set], X)\n\n    if mask is not None:\n        active_set_tmp = np.zeros(len(mask), dtype=np.bool)\n        active_set_tmp[mask] = active_set\n        active_set = active_set_tmp\n        del active_set_tmp\n\n    X = _reapply_source_weighting(X, source_weighting, active_set)\n\n    if return_residual:\n        residual = _compute_residual(\n            forward, evoked, X, active_set, gain_info)\n\n    if return_as_dipoles:\n        out = _make_dipoles_sparse(\n            X, active_set, forward, evoked.times[0], 1.0 / info['sfreq'],\n            M, M_estimated, verbose=None)\n    else:\n        out = _make_sparse_stc(\n            X, active_set, forward, evoked.times[0], 1.0 / info['sfreq'])\n\n    logger.info('[done]')\n\n    if return_residual:\n        out = out, residual\n\n    return out\n", "meta": {"hexsha": "76e6706ec0a6ca9b555e5741d2810c2201d352e4", "size": 24544, "ext": "py", "lang": "Python", "max_stars_repo_path": "mne/inverse_sparse/mxne_inverse.py", "max_stars_repo_name": "kostasde/mne-python", "max_stars_repo_head_hexsha": "ac4abee16e1f106055437f5b7feaa99786831a6f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mne/inverse_sparse/mxne_inverse.py", "max_issues_repo_name": "kostasde/mne-python", "max_issues_repo_head_hexsha": "ac4abee16e1f106055437f5b7feaa99786831a6f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-26T15:50:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-27T07:30:26.000Z", "max_forks_repo_path": "mne/inverse_sparse/mxne_inverse.py", "max_forks_repo_name": "kostasde/mne-python", "max_forks_repo_head_hexsha": "ac4abee16e1f106055437f5b7feaa99786831a6f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-15T11:33:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-15T11:33:50.000Z", "avg_line_length": 37.0196078431, "max_line_length": 79, "alphanum_fraction": 0.6240221643, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.30735800417608683, "lm_q1q2_score": 0.19018711481720446}}
{"text": "\nimport logging\n\nfrom abc import ABC, abstractmethod\n\nimport numpy as np\n\nfrom typing import Dict, Tuple, Any\n\nfrom scipy.constants import epsilon_0\nfrom scipy.integrate import trapz\n\nfrom amset.misc.constants import k_B, e, hbar\nfrom amset.data import AmsetData\nfrom amset.misc.log import log_list\nfrom amset.misc.util import f0\nfrom pymatgen import Spin\n\n__author__ = \"Alex Ganose\"\n__maintainer__ = \"Alex Ganose\"\n__email__ = \"aganose@lbl.gov\"\n__date__ = \"June 21, 2019\"\n\nlogger = logging.getLogger(__name__)\n\n\nclass AbstractElasticScattering(ABC):\n\n    name: str\n    required_properties: Tuple[str]\n\n    def __init__(self,\n                 materials_properties: Dict[str, Any],\n                 amset_data: AmsetData):\n        self.properties = {p: materials_properties[p]\n                           for p in self.required_properties}\n        self.doping = amset_data.doping\n        self.temperatures = amset_data.temperatures\n        self.nbands = {s: len(amset_data.energies[s]) for s in amset_data.spins}\n        self.spins = amset_data.spins\n\n    @abstractmethod\n    def prefactor(self, spin: Spin, b_idx: int):\n        pass\n\n    @abstractmethod\n    def factor(self, k_diff_sq: np.ndarray):\n        pass\n\n\nclass AcousticDeformationPotentialScattering(AbstractElasticScattering):\n\n    name = \"ACD\"\n    required_properties = (\"deformation_potential\", \"elastic_constant\")\n\n    def __init__(self,\n                 materials_properties: Dict[str, Any],\n                 amset_data: AmsetData):\n        super().__init__(materials_properties, amset_data)\n        self.vb_idx = amset_data.vb_idx\n        self.is_metal = amset_data.is_metal\n        self._prefactor = (1e18 * e * k_B / (\n                4.0 * np.pi ** 2 * hbar * self.properties[\"elastic_constant\"]))\n\n        self.deformation_potential = self.properties[\"deformation_potential\"]\n        if self.is_metal and isinstance(self.deformation_potential, tuple):\n            logger.warning(\n                \"System is metallic but deformation potentials for both \"\n                \"the valence and conduction bands have been set... using the \"\n                \"valence band potential for all bands\")\n            self.deformation_potential = self.deformation_potential[0]\n\n        elif not self.is_metal and not isinstance(\n                self.deformation_potential, tuple):\n            logger.warning(\n                \"System is semiconducting but only one deformation \"\n                \"potential has been set... using this potential for all bands.\")\n            self.deformation_potential = (self.deformation_potential,\n                                          self.deformation_potential)\n\n    def prefactor(self, spin: Spin, b_idx: int):\n        prefactor = self._prefactor * self.temperatures[None, :] * np.ones(\n            (len(self.doping), len(self.temperatures)))\n\n        if self.is_metal:\n            prefactor *= self.properties[\"deformation_potential\"] ** 2\n\n        else:\n            def_idx = 1 if b_idx > self.vb_idx[spin] else 0\n            prefactor *= self.properties[\"deformation_potential\"][def_idx] ** 2\n\n        return prefactor\n\n    def factor(self, k_diff_sq: np.ndarray):\n        return np.ones((len(self.doping), len(self.temperatures),\n                        k_diff_sq.shape[0]))\n\n\nclass IonizedImpurityScattering(AbstractElasticScattering):\n\n    name = \"IMP\"\n    required_properties = (\"acceptor_charge\", \"donor_charge\",\n                           \"static_dielectric\")\n\n    def __init__(self,\n                 materials_properties: Dict[str, Any],\n                 amset_data: AmsetData):\n        super().__init__(materials_properties, amset_data)\n        logger.debug(\"Initializing IMP scattering\")\n\n        self.beta_sq = np.zeros(amset_data.fermi_levels.shape)\n        self.impurity_concentration = np.zeros(amset_data.fermi_levels.shape)\n\n        tdos = amset_data.dos.tdos\n        energies = amset_data.dos.energies\n        fermi_levels = amset_data.fermi_levels\n        vol = amset_data.structure.volume\n\n        imp_info = []\n        for n, t in np.ndindex(self.beta_sq.shape):\n            ef = fermi_levels[n, t]\n            temp = amset_data.temperatures[t]\n            f = f0(energies, ef, temp)\n            integral = trapz(tdos * f * (1 - f), x=energies)\n            self.beta_sq[n, t] = (\n                e ** 2 * integral * 1e12 /\n                (self.properties[\"static_dielectric\"] * epsilon_0 * k_B *\n                 temp * e * vol))\n\n            n_conc = np.abs(amset_data.electron_conc[n, t])\n            p_conc = np.abs(amset_data.hole_conc[n, t])\n\n            self.impurity_concentration[n, t] = (\n                    n_conc * self.properties[\"donor_charge\"] ** 2 +\n                    p_conc * self.properties[\"acceptor_charge\"] ** 2)\n            imp_info.append(\n                \"{:.2g} cm⁻³ & {} K: β² = {:.4g}, Nᵢᵢ = {:.4g}\".format(\n                    amset_data.doping[n], temp, self.beta_sq[n, t],\n                    self.impurity_concentration[n, t]))\n\n        logger.debug(\"Inverse screening length (β) and impurity concentration \"\n                     \"(Nᵢᵢ):\")\n        log_list(imp_info, level=logging.DEBUG)\n\n        self._prefactor = (\n                (1e-3 / (e ** 2)) * e ** 4 * self.impurity_concentration /\n                (4.0 * np.pi ** 2 * epsilon_0 ** 2 * hbar *\n                 self.properties[\"static_dielectric\"] ** 2))\n\n    def prefactor(self, spin: Spin, b_idx: int):\n        # need to return prefactor with shape (nspins, ndops, ntemps, nbands)\n        return self._prefactor\n\n    def factor(self, k_diff_sq: np.ndarray):\n        # tile k_diff_sq to make it commensurate with the dimensions of beta\n        return 1 / (np.tile(k_diff_sq, (len(self.doping),\n                                        len(self.temperatures), 1)) +\n                    self.beta_sq[..., None]) ** 2\n\n\nclass PiezoelectricScattering(AbstractElasticScattering):\n\n    name = \"PIE\"\n    required_properties = (\"piezoelectric_coefficient\", \"static_dielectric\")\n\n    def __init__(self,\n                 materials_properties: Dict[str, Any],\n                 amset_data: AmsetData):\n        super().__init__(materials_properties, amset_data)\n        unit_conversion = 1e9 / e\n        self._prefactor = (unit_conversion * e ** 2 * k_B *\n                           self.properties[\"piezoelectric_coefficient\"] ** 2 /\n                           (4.0 * np.pi ** 2 * hbar * epsilon_0 *\n                            self.properties[\"static_dielectric\"]))\n\n    def prefactor(self, spin: Spin, b_idx: int):\n        # need to return prefactor with shape (ndops, ntemps)\n        return self._prefactor * self.temperatures[None, :] * np.ones(\n                (len(self.doping), len(self.temperatures)))\n\n    def factor(self, k_diff_sq: np.ndarray):\n        # factor should have shape (ndops, ntemps, nkpts)\n        return 1 / np.tile(k_diff_sq, (len(self.doping),\n                                       len(self.temperatures), 1))\n", "meta": {"hexsha": "ab6a414b20a01357b2f7065882b673558c244b47", "size": 6928, "ext": "py", "lang": "Python", "max_stars_repo_path": "amset/scattering/elastic.py", "max_stars_repo_name": "Navolo/amset", "max_stars_repo_head_hexsha": "964cf847d777faba9888e934ffe2ac0813ff9c71", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-19T16:27:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-19T16:27:01.000Z", "max_issues_repo_path": "amset/scattering/elastic.py", "max_issues_repo_name": "Navolo/amset", "max_issues_repo_head_hexsha": "964cf847d777faba9888e934ffe2ac0813ff9c71", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "amset/scattering/elastic.py", "max_forks_repo_name": "Navolo/amset", "max_forks_repo_head_hexsha": "964cf847d777faba9888e934ffe2ac0813ff9c71", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4486486486, "max_line_length": 80, "alphanum_fraction": 0.6020496536, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.2814056194821861, "lm_q1q2_score": 0.19016395984899379}}
{"text": "#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\nPipelines for fitting PHAT CMDs.\n\"\"\"\nimport os\nfrom glob import glob\nfrom functools import partial\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport palettable\n\nimport numpy as np\n# import astropy\nfrom astropy.coordinates import Distance\nimport astropy.units as u\nfrom astropy.table import Table\n\nfrom m31hst import phat_v2_phot_path\nfrom m31hst.phatast import PhatAstTable\n\nfrom padova import AgeGridRequest\nfrom padova.isocdata import join_isochrone_sets, Isochrone\n\nfrom starfisher import Lockfile\nfrom starfisher import ExtantCrowdingTable\nfrom starfisher import MockNullCrowdingTable\nfrom starfisher.dust import ExtinctionDistribution\nfrom starfisher.pipeline import (\n    PipelineBase, IsochroneSetBase, DatasetBase, LockBase,\n    CrowdingBase, ExtinctionBase)\n\nfrom androcmd.planes import RgbPhatPlanes, CompletePhatPlanes\nfrom androcmd.dust import mw_Av, phat_rel_extinction, LewisDustLaw\n\n\nPHAT_BANDS = ('F475W', 'F814W', 'F275W', 'F336W', 'F110W', 'F160W')\nSTARFISH = os.getenv(\"STARFISH\")\n\n\nclass SolarZIsocs(IsochroneSetBase):\n    \"\"\"Solar metallicity isochrone set.\"\"\"\n    def __init__(self, **kwargs):\n        self.isoc_args = kwargs.pop('isoc_args', dict())\n        self.isoc_phases = kwargs.pop('isoc_phases', None)\n        self.z_grid = [0.015, 0.019, 0.024]\n        print \"SolarZIsocs\", kwargs\n        super(SolarZIsocs, self).__init__(**kwargs)\n\n    @property\n    def bands(self):\n        return ('F475W', 'F814W', 'F275W', 'F336W', 'F110W', 'F160W')\n\n    @property\n    def distance(self):\n        return Distance(785. * u.kpc)\n\n    def setup_isochrones(self):\n        \"\"\"Download Padova isochrones.\"\"\"\n        print \"Running SolarZIsocs setup_isochrones\"\n        WFC3_BANDS = ['F275W1', 'F336W', 'F110W', 'F160W']\n        ACS_BANDS = ['F475W', 'F814W']\n\n        if not os.path.exists(os.path.join(STARFISH, self.isoc_dir)):\n            make_isocs = True\n        elif len(glob(os.path.join(STARFISH, self.isoc_dir, \"*\"))) == 0:\n            make_isocs = True\n        else:\n            make_isocs = False\n\n        if self.isoc_args is None:\n            self.isoc_args = {}\n        if make_isocs:\n            for z in self.z_grid:\n                r_wfc3 = AgeGridRequest(z,\n                                        min_log_age=6.6,\n                                        max_log_age=10.13,\n                                        delta_log_age=0.02,\n                                        photsys='wfc3_wide', **self.isoc_args)\n                r_acs = AgeGridRequest(z,\n                                       min_log_age=6.6,\n                                       max_log_age=10.13,\n                                       delta_log_age=0.02,\n                                       photsys='acs_wfc', **self.isoc_args)\n                isoc_set = join_isochrone_sets(r_wfc3.isochrone_set,\n                                               r_acs.isochrone_set,\n                                               left_bands=WFC3_BANDS,\n                                               right_bands=ACS_BANDS)\n                for isoc in isoc_set:\n                    isoc = Isochrone(isoc)\n                    isoc.rename_column('F275W1', 'F275W')\n                    if self.isoc_phases is not None:\n                        sels = []\n                        for p in self.isoc_phases:\n                            sels.append(np.where(isoc['stage'] == p)[0])\n                        s = np.concatenate(sels)\n                        isoc = isoc[s]\n                    isoc.export_for_starfish(os.path.join(STARFISH,\n                                                          self.isoc_dir),\n                                             bands=list(self.bands))\n        super(SolarZIsocs, self).setup_isochrones()\n\n\nclass ExtendedSolarIsocs(IsochroneSetBase):\n    \"\"\"Solar metallicity isochrone set.\"\"\"\n    def __init__(self, **kwargs):\n        self.isoc_args = kwargs.pop('isoc_args', dict())\n        self.isoc_phases = kwargs.pop('isoc_phases', None)\n        self.z_grid = (0.0096, 0.012, 0.015, 0.019, 0.024, 0.030, 0.04)\n        print \"ExtendedSolarZIsocs\", kwargs\n        super(ExtendedSolarIsocs, self).__init__(**kwargs)\n\n    @property\n    def bands(self):\n        return ('F475W', 'F814W', 'F275W', 'F336W', 'F110W', 'F160W')\n\n    @property\n    def distance(self):\n        return Distance(785. * u.kpc)\n\n    def setup_isochrones(self):\n        \"\"\"Download Padova isochrones.\"\"\"\n        print \"Running ExtendedSolarIsocs setup_isochrones\"\n        WFC3_BANDS = ['F275W1', 'F336W', 'F110W', 'F160W']\n        ACS_BANDS = ['F475W', 'F814W']\n\n        if not os.path.exists(os.path.join(STARFISH, self.isoc_dir)):\n            make_isocs = True\n        elif len(glob(os.path.join(STARFISH, self.isoc_dir, \"*\"))) == 0:\n            make_isocs = True\n        else:\n            make_isocs = False\n\n        if self.isoc_args is None:\n            self.isoc_args = {}\n        if make_isocs:\n            for z in self.z_grid:\n                r_wfc3 = AgeGridRequest(z,\n                                        min_log_age=6.6,\n                                        max_log_age=10.13,\n                                        delta_log_age=0.02,\n                                        photsys='wfc3_wide', **self.isoc_args)\n                r_acs = AgeGridRequest(z,\n                                       min_log_age=6.6,\n                                       max_log_age=10.13,\n                                       delta_log_age=0.02,\n                                       photsys='acs_wfc', **self.isoc_args)\n                isoc_set = join_isochrone_sets(r_wfc3.isochrone_set,\n                                               r_acs.isochrone_set,\n                                               left_bands=WFC3_BANDS,\n                                               right_bands=ACS_BANDS)\n                for isoc in isoc_set:\n                    isoc = Isochrone(isoc)\n                    isoc.rename_column('F275W1', 'F275W')\n                    if self.isoc_phases is not None:\n                        sels = []\n                        for p in self.isoc_phases:\n                            sels.append(np.where(isoc['stage'] == p)[0])\n                        s = np.concatenate(sels)\n                        isoc = isoc[s]\n                    isoc.export_for_starfish(os.path.join(STARFISH,\n                                                          self.isoc_dir),\n                                             bands=list(self.bands))\n        super(ExtendedSolarIsocs, self).setup_isochrones()\n\n\nclass PhatCatalog(DatasetBase):\n    \"\"\"Mixin for PHAT photometry data.\n\n    Photometry is lazy loaded to it is efficient to rebuild the pipeline\n    object.\n    \"\"\"\n    def __init__(self, brick, **kwargs):\n        self.brick = brick\n        self._phat_data = None\n        super(PhatCatalog, self).__init__(**kwargs)\n\n    def _load_phat_data(self):\n        self._phat_data = Table.read(phat_v2_phot_path(self.brick),\n                                     format='fits')\n        phat_bands = ('F475W', 'F814W', 'F275W', 'F336W', 'F110W', 'F160W')\n        # Normalize bandpass names\n        for band in phat_bands:\n            old_name = \"_\".join((band.lower(), 'vega'))\n            self._phat_data.rename_column(old_name, band)\n\n    def get_phot(self, band):\n        if self._phat_data is None:\n            self._load_phat_data()  # lazy loading\n\n        if not isinstance(band, basestring):\n            band1, band2 = band\n            return self._phat_data[band1] - self._phat_data[band2]\n        else:\n            return self._phat_data[band]\n\n    def _select_gst(self, x_band, y_band):\n        mags = []\n        if not isinstance(x_band, basestring):\n            mags.extend(x_band)\n        else:\n            mags.append(x_band)\n\n        if not isinstance(y_band, basestring):\n            mags.extend(y_band)\n        else:\n            mags.append(y_band)\n        mags = list(set(mags))\n\n        gsts = []\n        for band in mags:\n            key = '{0}_gst'.format(band.lower())\n            gsts.append(self._phat_data[key])\n        gsts_array = np.vstack(gsts).T\n        gsts = np.all(gsts_array, axis=1)\n        return np.where(gsts == True)[0]  # NOQA\n\n    def write_phot(self, x_band, y_band, data_root, suffix):\n        \"\"\"Only good (GST=1 in all relevant bands) photometry is written.\"\"\"\n        if self._phat_data is None:\n            self._load_phat_data()  # lazy loading\n\n        x = self.get_phot(x_band)\n        y = self.get_phot(y_band)\n        gst_sel = self._select_gst(x_band, y_band)\n\n        phot_dtype = np.dtype([('x', np.float), ('y', np.float)])\n        photdata = np.empty(len(gst_sel), dtype=phot_dtype)\n        photdata['x'][:] = x[gst_sel]\n        photdata['y'][:] = y[gst_sel]\n\n        path = data_root + suffix\n        full_path = os.path.join(STARFISH, path)\n        fit_dir = os.path.dirname(full_path)\n        if not os.path.exists(fit_dir):\n            os.makedirs(fit_dir)\n        np.savetxt(full_path, photdata, delimiter=' ', fmt='%.4f')\n\n    @property\n    def polygon(self):\n        \"\"\"Polygon bounding box around the dataset.\"\"\"\n        if self._phat_data is None:\n            self._load_phat_data()  # lazy loading\n\n        ra = self._phat_data['ra']\n        dec = self._phat_data['dec']\n        return np.array([[ra.min(), dec.min()],\n                         [ra.min(), dec.max()],\n                         [ra.max(), dec.max()],\n                         [ra.max(), dec.min()]])\n\n\nclass SolarLockfile(LockBase):\n    \"\"\"Lockfile mixin to create an iso-metallicity Hess set.\"\"\"\n    def __init__(self, **kwargs):\n        print \"SolarLockfile\", kwargs\n        super(SolarLockfile, self).__init__(**kwargs)\n\n    def build_lockfile(self):\n        self.lockfile = Lockfile(self.builder.read_isofile(), self.synth_dir,\n                                 unbinned=False)\n\n        # Bin young isochrones\n        young_grid = np.linspace(6.5, 8.95, 10)\n        for i, logage0 in enumerate(young_grid[:-1]):\n            logage0 = logage0\n            logage1 = young_grid[i + 1]\n            z_str = \"0019\"\n            mean_age = (logage0 + logage1) / 0.2\n            name = \"z{0}_{1:05.2f}\".format(z_str, mean_age)\n            self.lockfile.lock_box(name, (logage0, logage1), (0.014, 0.025))\n\n        # Bin old isochrones\n        old_grid = np.arange(1e9, 14 * 1e9, 1e9)\n        for i, age0 in enumerate(old_grid[:-1]):\n            logage0 = np.log10(age0 - 0.05 * 1e9)\n            logage1 = np.log10(old_grid[i + 1])\n            z_str = \"0019\"\n            mean_age = (logage0 + logage1) / 0.2\n            name = \"z{0}_{1:05.2f}\".format(z_str, mean_age)\n            self.lockfile.lock_box(name, (logage0, logage1), (0.014, 0.025))\n\n\nclass ExtendedSolarLockfile(LockBase):\n    \"\"\"Lockfile mixin to create an sub-, solar and super solar Z Hess set.\"\"\"\n    def __init__(self, **kwargs):\n        print \"ExtendedSolarLockfile\", kwargs\n        super(ExtendedSolarLockfile, self).__init__(**kwargs)\n\n    def build_lockfile(self):\n        self.lockfile = Lockfile(self.builder.read_isofile(), self.synth_dir,\n                                 unbinned=False)\n\n        z_bins = [(0.009, 0.0135), (0.014, 0.025), (0.027, 0.042)]\n        z_strs = ['0010', '0019', '0028']\n\n        # Bin young isochrones\n        for zbin, z_str in zip(z_bins, z_strs):\n            young_grid = np.linspace(6.5, 8.95, 10)\n            for i, logage0 in enumerate(young_grid[:-1]):\n                logage0 = logage0\n                logage1 = young_grid[i + 1]\n                mean_age = (logage0 + logage1) / 0.2\n                name = \"z{0}_{1:05.2f}\".format(z_str, mean_age)\n                self.lockfile.lock_box(name, (logage0, logage1), zbin)\n\n            # Bin old isochrones\n            old_grid = np.arange(1e9, 14 * 1e9, 1e9)\n            for i, age0 in enumerate(old_grid[:-1]):\n                logage0 = np.log10(age0 - 0.05 * 1e9)\n                logage1 = np.log10(old_grid[i + 1])\n                mean_age = (logage0 + logage1) / 0.2\n                name = \"z{0}_{1:05.2f}\".format(z_str, mean_age)\n                self.lockfile.lock_box(name, (logage0, logage1), zbin)\n\n\nclass PhatCrowding(CrowdingBase):\n    \"\"\"Use crowding from the PHAT AST fields.\"\"\"\n    def __init__(self, **kwargs):\n        self._ast_field = kwargs.pop('ast_field', 0)\n        super(PhatCrowding, self).__init__(**kwargs)\n\n    def build_crowding(self):\n        # Use PHAT AST from the outer field (field 0)\n        crowd_path = os.path.join(self.synth_dir, \"crowding.dat\")\n        full_crowd_path = os.path.join(STARFISH, crowd_path)\n        tbl = PhatAstTable()\n        tbl.write_crowdfile_for_field(full_crowd_path,\n                                      self._ast_field,\n                                      bands=self.bands)\n        self.crowd = ExtantCrowdingTable(crowd_path)\n\n    def mask_planes(self):\n        \"\"\"Mask each CMD plane based on the incomplete or empty regions of\n        the PHAT artificial star testing projected into the Hess plane.\n\n        This hook is called automatically by the base pipeline before\n        synth is run.\n        \"\"\"\n        # FIXME note that AST field 0 *is always* used\n        print \"Using PhatCrowding.mask_planes\"\n        ast = PhatAstTable()\n        for key, plane in self.planes.iteritems():\n            band = plane.y_mag  # FIXME assumes CMD; only 1 y axis mag.\n            hess, x_grid, y_grid = ast.completeness_hess(\n                0, band,\n                plane.x_mag, plane.y_mag,\n                plane.xlim, plane.ylim, 0.5)\n            yidx, xidx = np.where(hess < 0.5)  # mask less than 50% complete\n            for yi, xi in zip(yidx, xidx):\n                plane.mask_region((x_grid[xi], x_grid[xi + 1]),\n                                  (y_grid[yi], y_grid[yi + 1]))\n            yidx, xidx = np.where(~np.isfinite(hess))  # mask empty AST\n            for yi, xi in zip(yidx, xidx):\n                plane.mask_region((x_grid[xi], x_grid[xi + 1]),\n                                  (y_grid[yi], y_grid[yi + 1]))\n\n\nclass NullCrowding(object):\n    \"\"\"Crowding pipeline for no photometric errors due to crowidng.\"\"\"\n    def __init__(self, **kwargs):\n        super(NullCrowding, self).__init__(**kwargs)\n\n    def mask_planes(self):\n        pass\n\n    def build_crowding(self):\n        path = os.path.join(self.synth_dir, \"crowding.dat\")\n        self.crowd = MockNullCrowdingTable(path, self.n_bands)\n\n\nclass NoDust(ExtinctionBase):\n    \"\"\"Mixin for no dust.\"\"\"\n    def __init__(self, **kwargs):\n        super(NoDust, self).__init__(**kwargs)\n\n    def build_extinction(self):\n        # Add MW dust screen\n        self.young_av = ExtinctionDistribution()\n        self.young_av.set_uniform(mw_Av())\n        self.old_av = ExtinctionDistribution()\n        self.old_av.set_uniform(mw_Av())\n\n        self.rel_extinction = phat_rel_extinction()\n\n\nclass PhatGaussianDust(ExtinctionBase):\n    \"\"\"Mixin for Gaussian dust distributions for PHAT filters.\"\"\"\n    def __init__(self, **kwargs):\n        self._young_av = kwargs.pop('young_av', 1.0)\n        self._old_av = kwargs.pop('old_av', 0.5)\n        self._av_sigma_ratio = kwargs.pop('av_sigma_ratio', 0.5)\n        super(PhatGaussianDust, self).__init__(**kwargs)\n\n    def build_extinction(self):\n        # NOTE includes the E(V\n        self.young_av = ExtinctionDistribution()\n        if self._young_av > 0.:\n            av = np.random.normal(\n                loc=self._young_av,\n                scale=self._young_av * self._av_sigma_ratio,\n                size=1000)\n            av[av < 0.] = 0.\n            self.young_av.set_samples(av + mw_Av())\n        else:\n            self.young_av.set_samples(np.zeros(1000) + mw_Av())\n\n        self.old_av = ExtinctionDistribution()\n        if self._old_av > 0.:\n            av = np.random.normal(\n                loc=self._old_av,\n                scale=self._old_av * self._av_sigma_ratio,\n                size=1000)\n            av[av < 0.] = 0.\n            self.old_av.set_samples(av + mw_Av())\n        else:\n            self.old_av.set_samples(np.zeros(1000) + mw_Av())\n\n        self.rel_extinction = phat_rel_extinction()\n\n\nclass PhatStepDust(ExtinctionBase):\n    \"\"\"Mixin for Uniform dust distributions for PHAT filters.\"\"\"\n    def __init__(self, **kwargs):\n        self._young_av = kwargs.pop('young_av', 0.0) + mw_Av()\n        self._old_av = kwargs.pop('old_av', 0.0) + mw_Av()\n        self._young_dav = kwargs.pop('young_dav', 1.0)\n        self._old_dav = kwargs.pop('old_dav', 1.0)\n        super(PhatStepDust, self).__init__(**kwargs)\n\n    def build_extinction(self):\n        # NOTE includes MW extinction from __init__\n        self.young_av = ExtinctionDistribution()\n        self.young_av.set_samples(np.random.uniform(\n            low=self._young_av,\n            high=self._young_av + self._young_dav,\n            size=1000))\n\n        self.old_av = ExtinctionDistribution()\n        self.old_av.set_samples(np.random.uniform(\n            low=self._old_av,\n            high=self._old_av + self._old_dav,\n            size=1000))\n\n        self.rel_extinction = phat_rel_extinction()\n\n\nclass LewisBrickDust(ExtinctionBase):\n    \"\"\"Mixin for a uniform dust distribution fitted from Lewis et al 15 Fig 17.\n\n    The maximum extinction is estimated from a Draine et al 2015 dust map.\n    Requires that the brick be known.\n    \"\"\"\n    def __init__(self, **kwargs):\n        self.brick = kwargs.pop('brick', 23)\n        super(LewisBrickDust, self).__init__(**kwargs)\n\n    def build_extinction(self):\n        \"\"\"Young and old dust at equal here.\"\"\"\n        # Get the coordinate of the brick\n        # brick_fits = phat_brick_path(self.brick, 'F814W')\n        # wcs = astropy.io.WCS(brick_fits[0].header)\n        # poly = wcs.calc_footprint()\n        data = PhatCatalog(self.brick)  # FIXME pretty brick-specific\n        poly = data.polygon\n\n        lewis = LewisDustLaw()\n        max_av = lewis.estimate_mean_extinction(poly)\n        av = np.random.uniform(low=mw_Av(),\n                               high=max_av,\n                               size=1000)\n\n        self.young_av = ExtinctionDistribution()\n        self.young_av.set_samples(av)\n\n        self.old_av = ExtinctionDistribution()\n        self.old_av.set_samples(av)\n\n        self.rel_extinction = phat_rel_extinction()\n\n\nclass SolarZPhatPipeline(CompletePhatPlanes, SolarZIsocs,\n                         SolarLockfile, NoDust, PhatCrowding, PipelineBase):\n    \"\"\"A pipeline for fitting PHAT bricks with solar metallicity isochrones.\"\"\"\n    def __init__(self, **kwargs):\n        print \"SolarZPhatPipeline\", kwargs\n        super(SolarZPhatPipeline, self).__init__(**kwargs)\n\n\nclass SolarRgbPipeline(RgbPhatPlanes, SolarZIsocs,\n                       SolarLockfile, NoDust, PhatCrowding, PipelineBase):\n    \"\"\"A pipeline for fitting PHAT bricks with solar metallicity isochrones.\"\"\"\n    def __init__(self, **kwargs):\n        print \"SolarRgbPipeline\", kwargs\n        super(SolarRgbPipeline, self).__init__(**kwargs)\n\n\ndef build_phat_filter_set(**kwargs):\n    r_wfc3 = AgeGridRequest(photsys='wfc3_wide', **kwargs)\n    r_acs = AgeGridRequest(photsys='acs_wfc', **kwargs)\n    isoc_set = join_isochrone_sets(r_wfc3.isochrone_set,\n                                   r_acs.isochrone_set,\n                                   left_bands=['F275W1', 'F336W',\n                                               'F110W', 'F160W'],\n                                   right_bands=['F475W', 'F814W'])\n    return isoc_set\n\n\nget_demo_age_grid = partial(build_phat_filter_set,\n                            z=0.019, min_log_age=6.6, max_log_age=10.13,\n                            delta_log_age=0.2)\n\n\ndef plot_isochrone_phases(ax, band1, band2, show_cb=False, cb_ax=None):\n    isoc_set = get_demo_age_grid(**dict(isoc_kind='parsec_CAF09_v1.2S',\n                                        photsys_version='yang'))\n    phase_labels = {0: 'Pre-MS', 1: 'MS', 2: 'SGB', 3: 'RGB',\n                    4: 'CHeB(1)', 5: 'CHeB(2)', 6: 'CHeB(3)',\n                    7: 'E-AGB', 8: 'TP-AGB'}\n    cmap = mpl.colors.ListedColormap(\n        palettable.colorbrewer.qualitative.Set1_9.mpl_colors)\n    scalar_map = mpl.cm.ScalarMappable(norm=mpl.colors.Normalize(vmin=-0.5,\n                                                                 vmax=8.5),\n                                       cmap=cmap)\n    scalar_map.set_array(np.array(range(0, 9)))\n\n    d = Distance(785 * u.kpc)\n    for isoc in isoc_set:\n        phases = np.unique(isoc['stage'])\n        srt = np.argsort(phases)\n        phases = phases[srt]\n        for p in phases:\n            s = np.where(isoc['stage'] == p)[0]\n            ax.plot(isoc[band1][s] - isoc[band2][s],\n                    isoc[band2][s] + d.distmod.value,\n                    c=scalar_map.to_rgba(p),\n                    lw=0.8)\n    if show_cb:\n        cb = plt.colorbar(mappable=scalar_map,\n                          cax=cb_ax, ax=ax, ticks=range(0, 9))\n        cb.ax.set_yticklabels([phase_labels[p] for p in range(0, 9)])\n        cb.set_label(r\"Stage\")\n", "meta": {"hexsha": "ba81881272b0bbae1eb8f8ae965a7b4b2d6f490d", "size": 20978, "ext": "py", "lang": "Python", "max_stars_repo_path": "androcmd/phatpipeline.py", "max_stars_repo_name": "jonathansick/androcmd", "max_stars_repo_head_hexsha": "aa01b201b29fde701c07627063f55b67b71fb333", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "androcmd/phatpipeline.py", "max_issues_repo_name": "jonathansick/androcmd", "max_issues_repo_head_hexsha": "aa01b201b29fde701c07627063f55b67b71fb333", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "androcmd/phatpipeline.py", "max_forks_repo_name": "jonathansick/androcmd", "max_forks_repo_head_hexsha": "aa01b201b29fde701c07627063f55b67b71fb333", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5625, "max_line_length": 79, "alphanum_fraction": 0.5549623415, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 5440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.19014007340120628}}
{"text": "import os\nimport glob\nimport numpy as np\nimport spiceypy as spice\nfrom astropy.time import Time\n\n\nclass StereoSpice:\n\n    def __init__(self):\n        \"\"\"\n        Load in the general spice kernals and stereo spice keranls\n        \"\"\"\n        self.__load_general_kernals__()\n\n        self.__load_stereo_kernals__()\n        return\n        \n\n    def __get_spice_range__(self, filename):\n        \"\"\"\n        Function to calculate the range of coverage of a spice file given by filename\n        :param filename: String, full path to spice file.\n        :return dates_min: Astropy time object giving start of period spanned by spice file\n        :return dates_max: Astropy time object giving end of period spanned by spice file\n        :return craft_ids: List of craft ids represented by the spice file\n        \"\"\"\n\n        # Ephemeris files:\n        if filename.endswith('bsp'):\n            # Get craft id's\n            craft_ids = spice.spkobj(filename)\n            times = []\n            for s in craft_ids:\n                cover = spice.utils.support_types.SPICEDOUBLE_CELL(2000)\n                spice.spkcov(filename, s, cover)\n                times.append([c for c in cover])\n        # Pointing files\n        elif filename.endswith('bc'):\n            # Get craft id's\n            craft_ids = spice.ckobj(filename)\n            times = []\n            for s in craft_ids:\n                cover = spice.utils.support_types.SPICEDOUBLE_CELL(2000)\n                try:\n                    print('spice.ckcov: compute segment')\n                    spice.ckcov(filename, s, False, 'segment', 0.0, 'TDB', cover)\n                except:\n                    print('spice.ckcov: compute interval')\n                    spice.ckcov(filename, s, False, 'interval', 0.0, 'TDB', cover)\n\n                times.append([c for c in cover])\n        else:\n            print('Unrecognized file extension : ' + filename.split('.')[-1])\n            dates_min = np.NaN\n            dates_max = np.NaN\n            craft_ids = np.NaN\n            return dates_min, dates_max, craft_ids\n\n        # Format the dates.\n        min_time = min([min(t) for t in times])\n        dates_min = Time(spice.et2utc(min_time, 'ISOC', 3))\n        max_time = max([max(t) for t in times])\n        dates_max = Time(spice.et2utc(max_time, 'ISOC', 3))\n        return dates_min, dates_max, craft_ids\n        \n\n    def __get_kernal_files__(self):\n        \"\"\"\n        Function to load in the paths to the relevant spice kernals and files with lists of spice kernals.\n        :return kernals_dict: Dictionary containing the full paths to the kernal files needed.\n        \"\"\"\n\n        root  = os.path.abspath(os.path.dirname(__file__))\n        kernal_files = os.path.join(root,'config.dat')\n        \n        if os.path.exists(kernal_files):\n\n            with open(kernal_files, \"r\") as f:\n                kernals_dict = {}\n                lines = f.read().splitlines()\n                for l in lines:\n                    name, rel_path = l.split(';')\n                    abs_path = os.path.join(root, rel_path)\n                    kernals_dict[name] = abs_path\n\n            # Check that each file exists.\n            for k, f in kernals_dict.items():\n                \n                if not os.path.exists(f):\n                    print(\"Error: {} kernal file/file-list not found\".format(k))\n        else:\n            print(\"Error: Kernal files list not found.\")\n            kernals_dict = {}\n\n        return kernals_dict\n        \n\n    def __load_general_kernals__(self):\n        \"\"\"\n        Function to load in all the general kernals.\n        :return:\n        \"\"\"\n\n        # Load in the necessary Spice kernels\n        kernals_dict = self.__get_kernal_files__()\n        \n        # Load in the leap seconds kernal\n        spice.furnsh(kernals_dict['leap_seconds'])\n        self.__LeapSec__ = kernals_dict['leap_seconds']\n\n        # Load in the solar system kernal\n        spice.furnsh(kernals_dict['solar_system'])\n        self.__SolarSystem__ = kernals_dict['solar_system']\n\n        # Load in the planetary constants kernal\n        spice.furnsh(kernals_dict['planet_constants'])\n        self.__PlanetConstants__ = kernals_dict['planet_constants']\n\n        # Load in the heliospheric frames kernal\n        spice.furnsh(kernals_dict['heliospheric_frames'])\n        self.__HeliosphericFrames__ = kernals_dict['heliospheric_frames']\n\n        # Load in the stereo frames kernal\n        spice.furnsh(kernals_dict['stereo_frames'])\n        self.__StereoFrames__ = kernals_dict['stereo_frames']\n\n        # Load in the stereo a clock kernal\n        spice.furnsh(kernals_dict['stereo_frames'])\n        self.__staclock__ = kernals_dict['sta_clock']\n\n        # Load in the stereo b clock kernal\n        spice.furnsh(kernals_dict['stereo_frames'])\n        self.__stbclock__ = kernals_dict['stb_clock']\n\n        return\n        \n\n    def __load_stereo_kernals__(self):\n        \"\"\"\n        Function to load in the STEREO specific kernals\n        \"\"\"\n        # Load in the necessary Spice kernels\n        kernals_dict = self.__get_kernal_files__()\n        \n        # Load in the predicted ephemeris, and collect all ephem files.\n        # >> Initialise record of maximum dates covered by the ephemeris\n        self.__PredMaxdates__ = {'sta': Time(0.0, format='jd'),\n                                'stb': Time(0.0, format='jd')}\n\n        # >> Initialise the conic to cover the predicted ephemeris outside covered range\n        self.__PredConic__ = {'sta': None, 'stb': None}\n        self.__mu__ = 1.32712440018\n        self.__AllPredictedEphem__ = []\n\n        for craft in ['sta', 'stb']:\n            # Load in the predicted ephemeris files\n            key = craft + \"_ephem_filelist\"\n            with open(kernals_dict[key]) as f:\n                all_ephem_files = f.read().splitlines()\n                for ephem_file in all_ephem_files:\n                    full_ephem_path = os.path.join(kernals_dict['data_root'], ephem_file)\n                    if os.path.exists(full_ephem_path):\n                        spice.furnsh(full_ephem_path)\n                        self.__AllPredictedEphem__.append(full_ephem_path)\n\n                        # Extract the orbital parameters for conic extrapolation on predicted ephemeris\n                        dates_min, dates_max, craft_ids = self.__get_spice_range__(full_ephem_path)\n                        if dates_max > self.__PredMaxdates__[craft]:\n                            self.__PredMaxdates__[craft] = dates_max\n                            state = self.get_coord(dates_max, craft, system='HAE')\n                            et = spice.utc2et(dates_max.isot)\n                            elts = spice.oscelt(state, et, self.__mu__)\n                            self.__PredConic__[craft] = elts\n                    else:\n                        print(\"Error: File not found - {}\".format(full_ephem_path))\n\n        # Load in the definitive ephemeris, and collect all ephem files.\n        # >> Initialise record of maximum dates covered by the ephemeris\n        self.__DefMaxdates__ = {'sta': Time(0.0, format='jd'),\n                               'stb': Time(0.0, format='jd')}\n\n        # >> Initialise the conic to cover the predicted ephemeris outside covered range\n        self.__DefConic__ = {'sta': None, 'stb': None}\n        self.__AllDefEphem__ = []\n\n        for craft in ['sta', 'stb']:\n            # Load in the predicted ephemeris files\n            key = craft + \"_def_ephem_filelist\"\n            with open(kernals_dict[key]) as f:\n                all_ephem_files = f.read().splitlines()\n                for ephem_file in all_ephem_files:\n                    full_ephem_path = os.path.join(kernals_dict['data_root'], ephem_file)\n                    if os.path.exists(full_ephem_path):\n                        spice.furnsh(full_ephem_path)\n                        self.__AllDefEphem__.append(full_ephem_path)\n\n                        # Extract the orbital parameters for conic extrapolation on definitive ephemers\n                        dates_min, dates_max, sid = self.__get_spice_range__(full_ephem_path)\n                        if dates_max > self.__DefMaxdates__[craft]:\n                            self.__DefMaxdates__[craft] = dates_max\n                            state = self.get_coord(dates_max, craft, system='HAE')\n                            et = spice.utc2et(dates_max.isot)\n                            elts = spice.oscelt(state, et, self.__mu__)\n                            self.__DefConic__[craft] = elts\n                    else:\n                        print(\"Error: File not found - {}\".format(full_ephem_path))\n\n        # TODO: Load in Attitude kernals if want to use CMAT stuff?\n\n        return\n    \n    \n    def convert_hpc_to_hpr(self, hpc_lon, hpc_lat, degrees=True):\n        \"\"\"\n        Function to convert helioprojective cartesian coordinates (longitudes and latitudes) into helioprojective radial\n        coordinates (elongations and position angles). Conversion done by Eqn. 19 in Thompson 2006.\n        :param hpc_lon: Float or array of longitudes, in degrees.\n        :param hpc_lat: Float or array of latitudes, in degrees.\n        :param degrees: Boolean, if True (default), angles are parsed and returned in degrees.\n        :return hpr_el: Float or array of elongations, in degrees.\n        :return hpr_pa: Float or array of position angles, in degrees.\n        \"\"\"\n        \n        if degrees:\n            hpc_lon = np.deg2rad(hpc_lon)\n            hpc_lat = np.deg2rad(hpc_lat)\n            \n        # Elongation calc:\n        # Get numerator and denomenator for atan2 calculation\n        btm = np.cos(hpc_lat) * np.cos(hpc_lon)\n        top = np.sqrt((np.cos(hpc_lat) ** 2) * (np.sin(hpc_lon) ** 2) + (np.sin(hpc_lat) ** 2))\n        hpr_el = np.arctan2(top, btm)\n        # Position angle calc:\n        btm = np.sin(hpc_lat)\n        top = -np.cos(hpc_lat) * np.sin(hpc_lon)\n        hpr_pa = np.arctan2(top, btm)\n        # Correct eastern longitudes so pa runs from 0>2pi, rather than 0>pi.\n        if isinstance(hpr_pa, np.float):\n            if hpc_lon >= 0:\n                hpr_pa += 2 * np.pi\n        else:\n            hpr_pa[hpc_lon >= 0] += 2 * np.pi\n\n        if degrees:\n            # Put it back into degs\n            hpr_el = np.rad2deg(hpr_el)\n            hpr_pa = np.rad2deg(hpr_pa)\n            \n        return hpr_el, hpr_pa\n        \n        \n    def convert_hpr_to_hpc(self, hpr_el, hpr_pa, degrees=True):\n        \"\"\"\n        Function to convert helioprojective radial coordinates (elongations and position angles) into helioprojective\n        cartesian coordinates (longitudes and latitudes) . Conversion done by Eqn. 20 in Thompson 2006.\n        :param hpr_el: Array of elongations. Should have astropy unit of degrees.\n        :param hpr_pa: Array of position angles. Should have astropy unit of degrees.\n        :param degrees: Boolean, if True (default), angles are parsed and returned in degrees.\n        :return hpc_lon: Array of longitudes with astropy unit of degrees.\n        :return hpc_lat: Array of latitudes angles with astropy unit of degrees.\n        \"\"\"\n        if degrees:\n            hpr_el = np.deg2rad(hpr_el)\n            hpr_pa = np.deg2rad(hpr_pa)\n        \n        # Longitude calc:\n        # Get numerator and denomenator for atan2 calculation\n        btm = np.cos(hpr_el)\n        top = -np.sin(hpr_el) * np.sin(hpr_pa)\n        hpc_lon = np.arctan2(top, btm)\n        # Latitude calc:\n        hpc_lat = np.arcsin(np.sin(hpr_el) * np.cos(hpr_pa))\n        \n        if degrees:\n            hpc_lon = np.rad2deg(hpc_lon)\n            hpc_lat = np.rad2deg(hpc_lat)\n            \n        return hpc_lon, hpc_lat\n\n        \n    def convert_hpc_to_rtn(self, hpc_lon, hpc_lat, degrees=True):\n        \"\"\"\n        Function to convert helioprojective cartesian coordinates (longitudes and latitudes) into RTN longitude and latitudes.\n        :param hpc_lon: Float or array of HPC longitudes, in degrees.\n        :param hpc_lat: Float or array of HPC latitudes, in degrees.\n        :param degrees: Boolean, if True (default), angles are parsed and returned in degrees.\n        :return rtn_lon: Float or array of RTN longitudes, in degrees.\n        :return rtn_lat: Float or array of RTN latitudes, in degrees.\n        \"\"\"\n        rtn_lat = hpc_lat\n        \n        if degrees:\n            hpc_lon = np.deg2rad(hpc_lon)\n        \n        rtn_lon = np.pi - hpc_lon\n        \n        if degrees:\n            rtn_lon = np.rad2deg(rtn_lon)\n            \n        return rtn_lon, rtn_lat\n    \n    \n    def convert_rtn_to_hpc(self, rtn_lon, rtn_lat, degrees=True):\n        \"\"\"\n        Function to convert helioprojective cartesian coordinates (longitudes and latitudes) into RTN longitude and latitudes.\n        :param hpc_lon: Float or array of HPC longitudes, in degrees.\n        :param hpc_lat: Float or array of HPC latitudes, in degrees.\n        :param degrees: Boolean, if True (default), angles are parsed and returned in degrees.\n        :return rtn_lon: Float or array of RTN longitudes, in degrees.\n        :return rtn_lat: Float or array of RTN latitudes, in degrees.\n        \"\"\"\n        hpc_lat = rtn_lat\n        \n        if degrees:\n            rtn_lon = np.deg2rad(rtn_lon)\n            \n        if isinstance(rtn_lon,float):\n            hpc_lon = np.pi - rtn_lon\n            if hpc_lon > np.pi:\n                hpc_lon -= 2*np.pi\n\n            if hpc_lon < -np.pi:\n                hpc_lon += 2*np.pi\n        else:\n            hpc_lon = np.pi - rtn_lon\n            id_over = hpc_lon > np.pi\n            if any(id_over):\n                hpc_lon[id_over] -= 2*np.pi\n\n            id_under = hpc_lon < -np.pi\n            if any(id_under):\n                hpc[id_under] += 2*np.pi\n        \n        if degrees:\n            hpc_lon = np.rad2deg(hpc_lon)\n        \n        return hpc_lon, hpc_lat\n\n        \n    def convert_coord(self, dates, coord_src, system_src, system_dst, observe_src=None, observe_dst=None, precess=False):\n        \"\"\"\n        Function to convert coordinates betwen different reference frames.\n        :param dates: Astropy time object of dates(s).\n        :param coord_src: Array of coordinates to convert. Should be len(dates)*3 for positions only, or len(dates)*6 for full state\n        :param system_src: String name of coordinate system of coord array.\n        :param system_dst: String name of coordinate system to transform coord array to.\n        :param observe_src: String name of observatory for origin of system from. Only needed for some systems.\n        :param observe_dst: String name of observatory for origin of system to. Only needed for some systems.\n        :param precess: Boolean. If True accounts for precession in coordinate system.\n        :return state: Array, giving state at each dates. Either len(dates)x3 or len(dates)x6, depending on no_velocity\n        :return ltime (optional): The light travel time between observatory and target\n        \"\"\"\n        # If coordinates input as a list, then bung them into an array.\n        if isinstance(coord_src, list):\n            if all([isinstance(c, (float, int)) for c in coord_src]):\n                coord_src = np.array(coord_src)\n                coord_src = np.squeeze(coord_src)\n            else:\n                print(\"ERROR: coord_src should be a numpy array of coordinates or a list of floats/ints.\")\n            \n        # If coord only has one dimension, set it so that time is zeroth.\n        if coord_src.ndim == 1:\n            n_coords = 1\n            n_components = coord_src.size\n        else:\n            n_coords = coord_src.shape[0]\n            n_components = coord_src.shape[1]\n            \n        # Check dates and coord sizes match.\n        if dates.size != n_coords:\n            print(\"Error: Number of dates does not correspond to number of coordinates.\")\n            \n        # Check coord components are either 3 or 6, for position or state. Set no_velocity flag too.\n        if n_components == 3:\n            no_velocity = True\n        elif n_components == 6:\n            no_velocity = False\n        else:    \n            print(\"ERROR: Invalid dimension of position vector or state vector\")\n    \n        # Get NAIF formated name for src and dst observer and frame.\n        # Get SRC frame and osberver\n        if observe_src is None:\n            # Observer defined by the frame.\n            frame_src, observe_src = self.get_system_frame_names(system_src, precess=precess)\n        else:\n            # Observer must be specified for this frame\n            observe_src = self.get_naif_body_code(observe_src)\n            # Get naif frame and observer\n            frame_src, observe_src = self.get_system_frame_names(system_src, observatory=observe_src, precess=precess)\n            \n        # Repeat for DST frame and observer\n        if observe_dst is None:\n            # Observer defined by frame\n            frame_dst, observe_dst = self.get_system_frame_names(system_dst, precess=precess)\n        else:\n            # Observer must be specified for this frame\n            observe_dst = self.get_naif_body_code(observe_dst)\n            # Get naif frame and observ\n            frame_dst, observe_dst = self.get_system_frame_names(system_dst, observatory=observe_dst, precess=precess)\n                \n        # Convert to ephemeris time\n        if dates.isscalar:\n            et = spice.str2et(dates.isot)\n        else:\n            et = spice.str2et(dates.isot.tolist())\n            \n        # If observer changes, first do origin shift.\n        if observe_src != observe_dst:\n            \n            # Get location of observe_dst relative to observe_src in frame_src\n            corr = 'NONE'\n            if no_velocity:\n                observe_src_state, ltime = spice.spkpos(observe_dst, et, frame_src, corr, observe_src)\n            else:\n                # Velocity requested. This needs spkezr, which only accepts floats. So loop through et and call spkezr for\n                #  each et. Preallocate state and ltime, in this case state is a len(et)x6 array.\n                if dates.isscalar:\n                    observe_src_state, ltime = spice.spkezr(observe_dst, et, frame_src, corr, observe_src)\n                else:\n                    observe_src_state = np.zeros(coord_src.shape, dtype=float)\n                    ltime = np.zeros(dates.size, dtype=float)\n                    for i in range(dates.size):\n                        observe_src_state[i, :], ltime[i] = spice.spkezr(observe_dst, et[i], frame_src, corr, observe_src)\n            \n            # Now shift the origin         \n            coord_src = coord_src - observe_src_state\n        \n        # Must loop through dates for the matrix multiplication. Preallocate space for output.\n        # Now rotate from src frame to dst frame.\n        if dates.isscalar:\n            if no_velocity:\n                # Get rotation matrix for position only\n                transform = spice.pxform(frame_src, frame_dst, et)\n                coord_dst = np.matmul(transform, coord_src)\n            else:\n                # Get rotation matrix for full state\n                transform = spice.sxform(frame_src, frame_dst, et)\n                coord_dst = np.matmul(transform, coord_src)\n        else:\n            # Must loop through dates for the matrix multiplication. Preallocate space for output.\n            coord_dst = np.zeros(coord_src.shape, dtype=float)\n            \n            for i in range(dates.size):\n                if no_velocity:\n                    transform = spice.pxform(frame_src, frame_dst, et[i])\n                else:\n                    transform = spice.sxform(frame_src, frame_dst, et[i])\n                \n                coord_dst[i, :] = np.matmul(transform, coord_src[i,:])\n        \n        return coord_dst\n        \n    \n    def convert_lonlat(self, dates, coord_src, system_src, system_dst, observe_src=None, observe_dst=None, degrees=True):\n        \"\"\"\n        Function to convert latitudinal coordinates betwen different reference \n        frames.\n        :param dates: Astropy time object of dates(s).\n        :param coord_src: Array of latitudinal coordinates (rad, lon, lat) to convert. Should \n                          be either a numpy array of len(dates)*3, or a list of floats.\n        :param system_src: String name of coordinate system of coord array.\n        :param system_dst: String name of coordinate system to transform coord array to.\n        :param observe_src: String name of observatory for origin of system from. Only needed for some systems.\n        :param observe_dst: String name of observatory for origin of system to. Only needed for some systems.\n        :param degrees: Boolean. If true indicates that units of coord_src, and returned coord_dst, are in degrees.\n        :return coord_dst: Array, giving state at each dates. Shape of len(dates)x3.\n        \"\"\"\n        \n        # If coordinates input as a list, then bung them into an array.\n        if isinstance(coord_src, list):\n            if all([isinstance(c, (float, int)) for c in coord_src]):\n                coord_src = np.array(coord_src)\n                coord_src = np.squeeze(coord_src)\n            else:\n                print(\"ERROR: coord_src should be a numpy array of coordinates or a list of floats.\")\n            \n        # If coord only has one dimension, set it so that time is zeroth.\n        if coord_src.ndim == 1:\n            n_coords = 1\n            n_components = coord_src.size\n        else:\n            n_coords = coord_src.shape[0]\n            n_components = coord_src.shape[1]\n            \n        # Check dates and coord sizes match.\n        if dates.size != n_coords:\n            print(\"Error: Number of dates does not correspond to number of coordinates.\")\n            \n        # Check coords have 3 components.\n        if n_components != 3:\n            print(\"ERROR: Invalid dimension of position vector or state vector\")\n                \n        if (system_src in ['HPC', 'hpc', 'HPR', 'hpr', 'RTN', 'rtn']) & (observe_src is None):\n            print(\"ERROR: system_src given as {}, but no observe_src specified. Assuming Earth\".format(system_src))\n            observer_src = 'earth'\n        \n        if (system_dst in ['HPC', 'hpc', 'HPR', 'hpr', 'RTN', 'rtn']) & (observe_dst is None):\n            print(\"ERROR: system_dst given as {}, but no observe_src specified. Assuming Earth\".format(system_dst))\n            observer_dst = 'earth'\n        \n        # Parse out the coordinates.\n        if dates.isscalar:\n            rad = coord_src[0]\n            lon = coord_src[1]\n            lat = coord_src[2]\n        else:\n            rad = np.squeeze(coord_src[:,0])\n            lon = np.squeeze(coord_src[:,1])\n            lat = np.squeeze(coord_src[:,2])\n        \n        # Put angles into radians for spice.\n        if degrees:\n            lon = np.deg2rad(lon)\n            lat = np.deg2rad(lat)\n            \n        if system_src in ['HPC', 'hpc']:\n            # Convert to RTN and updates system_src tag\n            lon, lat = self.convert_hpc_to_rtn(lon, lat, degrees=False)\n            system_src = 'RTN'\n        elif system_src in ['HPR', 'hpr']:\n            # Convert to HPC and then to RTN, updates system_src tag\n            lon, lat = self.convert_hpr_to_hpc(lon, lat, degrees=False)\n            lon, lat = self.convert_hpc_to_rtn(lon, lat, degrees=False)\n            system_src = 'RTN'\n        \n        # Now convert to rectangular coords.\n        if dates.isscalar:\n            coord_src_rec = spice.latrec(rad, lon, lat)\n        else:\n            # Loop through state to do conversion (as spice.reclat doesn't handle arrays yet)\n            coord_src_rec = np.zeros(coord_src.shape, dtype=float)\n            for i in range(dates.size):\n                coord_src_rec[i,:] = spice.latrec(rad[i], lon[i], lat[i])\n    \n        # If system_dst was HPC or HPR, do conversion in RTN and apply correction.\n        if system_dst in ['HPC', 'hpc']:\n            system_dst = 'RTN'\n            calc_hpc = True\n        else:\n            calc_hpc = False\n            \n        if system_dst in ['HPR', 'hpr']:\n            system_dst = 'RTN'\n            calc_hpr = True\n        else:\n            calc_hpr = False\n        \n        coord_dst_rec = self.convert_coord(dates, coord_src_rec, system_src, \\\n                                           system_dst, observe_src=observe_src, \\\n                                           observe_dst=observe_dst)\n                                           \n        # Convert back to latitude coords.\n        if dates.isscalar:\n            rad_dst, lon_dst, lat_dst = spice.reclat(coord_dst_rec)\n        else:\n            # Loop through state to do conversion (as spice.reclat doesn't handle arrays yet)\n            rad_dst = np.zeros(dates.size, dtype=float)\n            lon_dst = np.zeros(dates.size, dtype=float)\n            lat_dst = np.zeros(dates.size, dtype=float)\n            for i in range(dates.size):\n                rad_dst[i], lon_dst[i], lat_dst[i] = spice.reclat(coord_dst_rec[i,:])\n\n        # Correct HPC coords if necessary\n        if calc_hpc:\n            lon_dst, lat_dst = self.convert_rtn_to_hpc(lon_dst, lat_dst, degrees=False)\n            \n        # Correct HPR coords if necessary\n        if calc_hpr:\n            lon_dst, lat_dst = self.convert_rtn_to_hpc(lon_dst, lat_dst, degrees=False)\n            lon_dst, lat_dst = self.convert_hpc_to_hpr(lon_dst, lat_dst, degrees=False)\n\n        # Correct Carrington longitudes if neccesary\n        carrington_names = ['CARR', 'CARRINGTON', 'carr', 'carrington']\n        if system_dst in carrington_names:\n            if dates.size > 1:\n                id_under = lon_dst < 0\n                if any(id_under):\n                    lon_dst[id_under] += 2*np.pi\n\n            elif dates.size == 1:\n                if lon_dst < 0:\n                    lon_dst += 2*np.pi\n\n        if degrees:\n            lon_dst = np.rad2deg(lon_dst)\n            lat_dst = np.rad2deg(lat_dst)\n\n        # Bundle the output into one array.\n        if dates.isscalar:\n            coord_dst = np.array([rad_dst, lon_dst, lat_dst])\n        else:\n            rad_dst = np.expand_dims(rad_dst, axis=1)\n            lon_dst = np.expand_dims(lon_dst, axis=1)\n            lat_dst = np.expand_dims(lat_dst, axis=1)\n            coord_dst = np.hstack((rad_dst, lon_dst, lat_dst))\n\n        return coord_dst\n        \n    \n    def convert_lat2rec(self, coord_lat, degrees=True):\n        \"\"\"\n        Function to convert latitudinal coordinates to rectangular coordinates.\n        :param coord_lat: Array of latitudinal coordinates (rad, lon, lat) to convert. Should \n                          be either a numpy array of len(dates)*3, or a list of floats.\n        :param degrees: Boolean, True if units is in degrees.\n        :return coord_rec: Array, giving position (km) for each latitudinal coordinate. Shape of coord_lat.\n        \"\"\"\n        \n        # If coordinates input as a list, then bung them into an array.\n        if isinstance(coord_lat, list):\n            if all([isinstance(c, (float, int)) for c in coord_lat]):\n                coord_lat = np.array(coord_lat)\n                coord_lat = np.squeeze(coord_lat)\n            else:\n                print(\"ERROR: coord_src should be a numpy array of coordinates or a list of floats.\")\n            \n        # If coord only has one dimension, set it so that time is zeroth.\n        if coord_lat.ndim == 1:\n            n_coords = 1\n            n_components = coord_lat.size\n        else:\n            n_coords = coord_lat.shape[0]\n            n_components = coord_lat.shape[1]\n                 \n        # Check coords have 3 components.\n        if n_components != 3:\n            print(\"ERROR: Invalid dimension of position vector or state vector\")\n                \n        # Get the coordinates.\n        if n_coords == 1:\n            rad = coord_lat[0]\n            lon = coord_lat[1]\n            lat = coord_lat[2]\n        else:\n            rad = np.squeeze(coord_lat[:,0])\n            lon = np.squeeze(coord_lat[:,1])\n            lat = np.squeeze(coord_lat[:,2])\n        \n        # Put angles into radians for spice.\n        if degrees:\n            lon = np.deg2rad(lon)\n            lat = np.deg2rad(lat)\n                   \n        # Now convert to rectangular coords.\n        if n_coords == 1:\n            coord_rec = spice.latrec(rad, lon, lat)\n        else:\n            # Loop through state to do conversion (as spice.reclat doesn't handle arrays yet)\n            coord_rec = np.zeros(coord_lat.shape, dtype=float)\n            for i in range(n_coords):\n                coord_rec[i,:] = spice.latrec(rad[i], lon[i], lat[i])\n               \n        return coord_rec\n            \n                \n    def convert_rec2lat(self, coord_rec, degrees=True):\n        \"\"\"\n        Function to convert rectangular coordinates to latitudinal coordinates.\n        :param coord_rec: Array of rectangular coordinates (in km) to convert. Should \n                          be either a numpy array of len(dates)*3, or a list of floats.\n        :param degrees: Boolean, True if units of latitudinal coords should be in degrees.\n        :return coord_lat: Array, giving latitudinal position for each rectangular coord. Shape of coor_rec.\n        \"\"\"\n        \n        # If coordinates input as a list, then bung them into an array.\n        if isinstance(coord_rec, list):\n            if all([isinstance(c, (float, int)) for c in coord_rec]):\n                coord_rec = np.array(coord_rec)\n                coord_rec = np.squeeze(coord_rec)\n            else:\n                print(\"ERROR: coord_src should be a numpy array of coordinates or a list of floats.\")\n            \n        # If coord only has one dimension, set it so that time is zeroth.\n        if coord_rec.ndim == 1:\n            n_coords = 1\n            n_components = coord_rec.size\n        else:\n            n_coords = coord_rec.shape[0]\n            n_components = coord_rec.shape[1]\n                 \n        # Check coords have 3 components.\n        if n_components != 3:\n            print(\"ERROR: Invalid dimension of position vector or state vector\")\n                                   \n        # Now convert to latitudinal coords\n        if n_coords == 1:\n            coord_lat = spice.reclat(coord_rec)\n        else:\n            # Loop through state to do conversion (as spice.reclat doesn't handle arrays yet)\n            coord_lat = np.zeros(coord_rec.shape, dtype=float)\n            for i in range(n_coords):\n                coord_lat[i,:] = spice.reclat(coord_rec[i,:])\n        \n        if degrees:\n            if n_coords == 1:\n                coord_lat[1:] = np.rad2deg(coord_lat[1:])\n            else:\n                coord_lat[:,1:] = np.rad2deg(coord_lat[:,1:])\n        \n        return coord_lat\n        \n    \n    def get_naif_body_code(self, body):\n        \"\"\"\n        Function to return the numeric NAIF body code of a spacecraft or solar system body.\n        :param body: String name of solar system body or spacecraft\n        :return naif_body: String of numeric NAIF body code, fit for use with spiceypy\n        \"\"\"\n\n        # Get set of pseudonyms for stereo a and stereo b and Earth\n        sta_names = {'A', 'sta', 'STA', 'Ahead', 'STEREO Ahead', 'STEREO-Ahead', 'STEREO_Ahead', '-234', -234}\n        stb_names = {'B', 'stb', 'STB', 'Behind', 'STEREO Behind', 'STEREO-Behind', 'STEREO_Behind', '-235', -235}\n        sun_names = {'S', 'Sun', 'sun', 'SUN', '10', 10}\n        mercury_names = {'Mercury', 'mercury', 'MERCURY', '199', 199}\n        venus_names = {'Venus', 'venus', 'VENUS', '299', 299}\n        earth_names = {'E','Earth', 'earth', 'EARTH', 'ERT', 'ert', '399', 399}\n        moon_names = {'Moon', 'moon', 'Moon', '301', 301}\n        mars_names = {'Mars', 'mars', 'MARS', '499', 499}\n        # Get NAIF code of user input observatory\n        if body in sta_names:\n            naif_body = '-234'\n        elif body in stb_names:\n            naif_body = '-235'\n        elif body in sun_names:\n            naif_body = '10'\n        elif body in mercury_names:\n            naif_body = '199'\n        elif body in venus_names:\n            naif_body = '299'\n        elif body in earth_names:\n            naif_body = '399'\n        elif body in moon_names:\n            naif_body = '301'\n        elif body in mars_names:\n            naif_body = '499'\n        else:\n            print(body)\n            print('ERROR: Body name not recognised. Allowed bodies: STA, STB, Sun, Mercury, Venus, Earth, Moon, Mars.\\n\\\n                  More codes available at Get more codes at http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/FORTRAN/req/naif_ids.html ')\n            \n            naif_body = 'ERROR'\n\n        return naif_body\n        \n\n    def get_coord(self, dates, target, system, observatory=None, corr='NONE', precess=False, return_ltime=False,\n                  no_velocity=False):\n        \"\"\"\n        Function to calculate the coordinates of a spacecraft or solar system body\n        :param dates: Astropy time object of dates(s).\n        :param target: String name of target body to calculate the position of.\n        :param system: String name of coordinate system to calculate position in.\n        :param observatory: String name of observatory for origin of coordinate system.\n        :param corr: Boolean. If True performs correction for planetary abberation.\n        :param precess: Boolean. If True accounts for precession in ..\n        :param return_ltime: Boolean. If True also returns light travel time between observatory and target.\n        :param no_velocity: Boolean. If True, the velocity components are not returned in the state vector.\n        :return state: Array, giving state at each dates. Either len(dates)x3 or len(dates)x6, depending on no_velocity\n        :return ltime (optional): The light travel time between observatory and target\n        \"\"\"\n        # TODO: Add in error checks to make sure target is specified.\n\n        # The NAIF codes for stereo a and b are:\n        sta_naif_code = '-234'\n        stb_naif_code = '-235'\n\n        target = self.get_naif_body_code(target)\n\n        if observatory is not None:\n            observatory = self.get_naif_body_code(observatory)\n\n        frame, observatory = self.get_system_frame_names(system, observatory, precess)\n\n        # Pull out the max valid ephemeris time for each craft\n        if target == sta_naif_code:\n            max_dates = self.__PredMaxdates__['sta']\n        else:\n            max_dates = self.__PredMaxdates__['stb']\n\n        # Get ephemeris times for the input dates. If larger than max dates, set to max dates and set correct flag.\n        correct_late_times = False\n        if dates.isscalar:\n            if dates <= max_dates:\n                et = [spice.str2et(dates.isot)]\n            else:\n                et = [spice.str2et(max_dates.isot)]\n                correct_late_times = True\n        else:\n            if all(dates <= max_dates):\n                et = spice.str2et(dates.isot.tolist())\n            else:\n                et = spice.str2et(dates.isot.tolist())\n                id_gt_max = dates > max_dates\n                et[id_gt_max] = spice.str2et(max_dates.isot)\n                correct_late_times = True\n\n        # Now add in the calls to spice functions to get the state variables\n        # If no velocity, use spkpos.\n        if no_velocity:\n            state, ltime = spice.spkpos(target, et, frame, corr, observatory)\n            # Convert state from list of arrays to numpy array\n            state = np.array(state)\n        else:\n            # Velocity requested. This needs spkezr, which only accepts floats. So loop through et and call spkezr for            \n            state = np.zeros((dates.size, 6), dtype=float)\n            ltime = np.zeros(dates.size, dtype=float)\n            for i in range(dates.size):\n                state[i, :], ltime[i] = spice.spkezr(target, et[i], frame, corr, observatory)\n\n        # Add in correction to get states for times after max ephemeris time using\n        # Conics. Loop over entries after maximum time\n        if correct_late_times:\n            if observatory == sta_naif_code:\n                elts = self.__PredConic__['sta']\n            elif observatory == stb_naif_code:\n                elts = self.__PredConic__['stb']\n\n        \n            for idt in np.argwhere(id_gt_mxt is True):\n                et = spice.str2et(dates.isot[idt])\n                temp = spice.conics(elts, et)\n                # Updates state with conics estimate.\n                if no_velocity:\n                    state[idt, :] = temp[0:3]\n                else:\n                    state[idt, :] = temp\n\n                ltime[idt] = -1\n\n            # Now convert updatesd coords from HAE to specified system\n            temp = state[:, id_gt_mxt]\n            temp = convert_stereo_coord(dates.isot[id_gt_mxt], temp, 'HAE', system)\n            state[:, id_gt_mxt] = temp\n        \n        # If only one date, loose first dimension\n        if dates.isscalar:\n            state = np.squeeze(state)\n            \n        if return_ltime:\n            return state, ltime\n        else:\n            return state\n            \n\n    def get_lonlat(self, dates, target, system, observatory=None, corr='NONE', precess=False, degrees=True):\n        \"\"\"\n        Function to calculate the radius, longitude and lataitude of a target in coordinate system given by system,\n        centered on an observatory. Observatory doesn't always need to be specified, but for some coordinate systems\n        needs to be. Doesnt handle velocity components of state vector.\n        :param dates: Astropy time object of dates(s) to get\n        :param target: String name of target body.\n        :param system: String name of coordinate system.\n        :param observatory: String name of observatory.\n        :param corr: String specifying whether to perform correction for planetary abberation.\n        :param precess: Boolean. If true perform a calculation for precession.\n        :param degrees: Boolean. If true return latitude and longitude in degrees\n        :return coords: Float array of coords.\n        \"\"\"\n\n        # Add in calculation for Helioprojective Cartesian coordinates.\n        if system in ['HPC', 'hpc']:\n            system = 'RTN'\n            calc_hpc = True\n        else:\n            calc_hpc = False\n            \n        if system in ['HPR', 'hpr']:\n            system = 'RTN'\n            calc_hpr = True\n        else:\n            calc_hpr = False\n            \n        # Get the position of the target for this dates/system/observatory\n        state = self.get_coord(dates, target, system=system, observatory=observatory, corr=corr, precess=precess,\n                               no_velocity=True)\n\t\t\n\t\t\n        # Use spice to convert to lon/lat\n        state = np.array(state)\n        \n        if state.ndim == 1:\n            rad, lon, lat = spice.reclat(state)\n        else:\n            # Loop through state to do conversion (as spice.reclat doesn't handle arrays yet)\n            rad = np.zeros(len(dates), dtype=float)\n            lon = np.zeros(len(dates), dtype=float)\n            lat = np.zeros(len(dates), dtype=float)\n            for i in range(len(dates)):\n                rad[i], lon[i], lat[i] = spice.reclat(state[i])\n\n        # Correct HPC coords if necessary\n        if calc_hpc:\n            lon, lat = self.convert_rtn_to_hpc(lon, lat, degrees=False)\n            \n        if calc_hpr:\n            lon, lat = self.convert_rtn_to_hpc(lon, lat, degrees=False)\n            lon, lat = self.convert_hpc_to_hpr(lon, lat, degrees=False)\n\n        # Correct Carrington longitudes if neccesary\n        carrington_names = ['CARR', 'CARRINGTON', 'carr', 'carrington']\n        if system in carrington_names:\n            if dates.size > 1:\n                id_under = lon < 0\n                if any(id_under):\n                    lon[id_under] += 2*np.pi\n\n            elif dates.size == 1:\n                if lon < 0:\n                    lon += 2*np.pi\n\n        if degrees:\n            lon = np.rad2deg(lon)\n            lat = np.rad2deg(lat)\n\n        # Make state vector with same structure as output by spkpos\n        if dates.isscalar:\n            coords = np.array([rad,lon,lat]).T\n            # If only one date, loose first dimension\n            coords = np.squeeze(coords)\n        else:\n            rad = np.expand_dims(rad, axis=1)\n            lon = np.expand_dims(lon, axis=1)\n            lat = np.expand_dims(lat, axis=1)\n            coords = np.hstack((rad,lon,lat))\n        return coords\n        \n\n    def get_system_frame_names(self, system, observatory=None, precess=False):\n        \"\"\"\n        Function to return the spice friendly name of the frame relevant for a given coordinate system and observatory.\n        For some systems, an observatory must also be specified.\n        :param system: String name of the requested coordinate system.\n        :param observatory: String name of observatory. Not needed for all systems (e.g HCI or GEO).\n        :param precess: Boolean. If true select frame that accounts for precession.\n        :return frame: String name of frame in spice friendly format.\n        :return observatory: String of observatory in spice friendly format.\n        \"\"\"\n        \n        # Get NAIF codes needed to identify which observatory was parsed.\n        sta_naif_code = self.get_naif_body_code('STA')\n        stb_naif_code = self.get_naif_body_code('STB')\n        sun_naif_code = self.get_naif_body_code('SUN')\n        earth_naif_code = self.get_naif_body_code('EARTH')\n                \n        # If an observatory was parsed, make sure it is in naif format.\n        if observatory is not None:\n            observatory = self.get_naif_body_code(observatory)\n         \n        # Get lists of system names and their synonyms\n        heeq_names = ['HEQ','HEEQ', 'heq', 'heeq']\n        carrington_names = ['CARR', 'CARRINGTON', 'carr', 'carrington']\n        hci_names = ['HCI', 'hci']\n        hae_names = ['HAE', 'hae']\n        hee_names = ['HEE', 'hee']\n        hgrtn_names = ['HGRTN', 'hgrtn']\n        rtn_names = ['RTN', 'rtn']\n        sci_names = ['SCI', 'sci']\n        hertn_names = ['HERTN', 'hertn']\n        gei_names = ['GEI', 'gei']\n        geo_names = ['GEO', 'geo']\n        gse_names = ['GSE', 'gse']\n        \n        # If system is RTN then an observatory should have been specified.\n        if (system == 'RTN') & (observatory is None):\n            print(\"ERROR: RTN system specified, but no corresponding observatory. Assuming Earth.\")\n            observatory = earth_naif_code\n            \n        # Some systems have defined observatory. Check input observatory doesnt clash with this.\n        # Helio systems:\n        all_helio = heeq_names + carrington_names + hci_names + hae_names + hee_names + hgrtn_names\n        if (system in all_helio) & (observatory not in [None, sun_naif_code]):\n            print(\"ERROR: Observatory {0} specified for Sun based system ({1}).\\n\\\n            Input observatory will be overridden\".format(observatory, system))\n            \n        all_geo = gei_names + geo_names + gse_names\n        if (system in all_geo) & (observatory not in [None, earth_naif_code]): \n            print(\"ERROR: Observatory {0} specified for Earth based system ({1}).\\n\\\n            Input observatory will be overridden\".format(observatory, system))\n\n        # Find out which coordinate system / frame required\n        if system in heeq_names:\n            frame = 'HEEQ'\n            observatory = 'Sun'\n\n        elif system in carrington_names:\n            frame = 'IAU_SUN'\n            observatory = 'Sun'\n\n        elif system in hci_names:\n            frame = 'HCI'\n            observatory = 'Sun'\n\n        elif system in hae_names:\n            observatory = 'Sun'\n            if precess:\n                frame = 'ECLIPdates'\n            else:\n                frame = 'ECLIPJ2000'\n\n        elif system in hee_names:\n            frame = 'HEE'\n            observatory = 'Sun'\n        \n        elif system in rtn_names:\n            if observatory == sta_naif_code:\n                frame = 'STAHGRTN'\n            elif observatory == stb_naif_code:\n                frame = 'STBHGRTN'\n            elif observatory == earth_naif_code:\n                frame = 'GEORTN'\n            elif observatory == sun_naif_code:\n                frame = 'HGRTN'\n        \n        elif system in hgrtn_names:\n                frame = 'HGRTN'\n                observatory = 'Sun'\n\n        elif system in sci_names:\n            # Check observaotry input\n            if observatory == sta_naif_code:\n                frame = 'STASCPNT'\n            elif observatory == stb_naif_code:\n                frame = 'STBSCPNT'\n            else:\n                print('ERROR: INCORRECT SPACECARFT TARGET PARSED')\n\n        elif system in hertn_names:\n            # Check observatory input\n            if observatory == sta_naif_code:\n                frame = 'STAHERTN'\n            elif observatory == stb_naif_code:\n                frame = 'STBHERTN'\n            else:\n                print('ERROR: INCORRECT SPACECARFT TARGET PARSED')\n\n        elif system in gei_names:\n            frame = 'J200'\n            observatory = 'Earth'\n\n        elif system in geo_names:\n            frame = 'J200'\n            observatory = 'Earth'\n\n        elif system in gse_names:\n            frame = 'GSE'\n            observatory = 'Earth'\n        else:\n            print(\"ERROR: System not recognised\")\n\n        return frame, observatory\n        \n\n    def clear_kernals(self):\n        \"\"\"\n        A function to clear out the loaded spice kernals.\n        :return:\n        \"\"\"\n        spice.kclear()\n        return\n    ", "meta": {"hexsha": "6a9c1f3d2be479da6266046c5f889802f8a15d73", "size": 45572, "ext": "py", "lang": "Python", "max_stars_repo_path": "stereo_spice/coordinates.py", "max_stars_repo_name": "LukeBarnard/stereo_spice", "max_stars_repo_head_hexsha": "6944d2a3225ada4d9c062bdfa048dc3632a81dc6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stereo_spice/coordinates.py", "max_issues_repo_name": "LukeBarnard/stereo_spice", "max_issues_repo_head_hexsha": "6944d2a3225ada4d9c062bdfa048dc3632a81dc6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stereo_spice/coordinates.py", "max_forks_repo_name": "LukeBarnard/stereo_spice", "max_forks_repo_head_hexsha": "6944d2a3225ada4d9c062bdfa048dc3632a81dc6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9114877589, "max_line_length": 135, "alphanum_fraction": 0.5777670499, "include": true, "reason": "import numpy,from astropy", "num_tokens": 10484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.19014007032032054}}
{"text": "\"\"\"\n\n\"\"\"\n\nimport datetime\nimport numpy as np\nimport scipy.stats as ss\nimport configparser\nimport sys\n\nclass TimingError(Exception):\n    def __init__(self, starttime, stoptime, index):\n        self.index = index\n        self.start = starttime\n        self.stop = stoptime\n        self.dateformat = \"%Y-%m-%d %H:%M:%S\"\n\n\nclass AEPcounter:\n    \"\"\"\n    set of functions to calculate AEP losses from structured data\n    \"\"\"\n    def __init__(self):\n        \"\"\"\n        Initialize all relevant variables to some values. These need to be set\n        based on the structure of the actual data\n\n        wind_bins and direction_bins contain the CENTERS of bins\n\n        \"\"\"\n        self.id = '' # data id used to id the data\n        self.ts_index = 0  # column of TIMESTAMP in source data\n        self.ws_index = 1  # column of WIND SPEED in source data\n        self.wd_index = 2  # column of WIND DIRECTION index in source data\n        self.temp_index = 3  # column of TEMPERATURE in source data\n        self.pow_index = 4  # column of POWER in source data\n        self.state_index = [5]  # column of TURBINE STATE INFORMATION\n        self.normal_state = [0]  # normal/default value of state variable\n        self.wind_bins = np.arange(0, 20, 1)  # wind speed binning\n        self.direction_bins = np.arange(0, 360, 360)  # wind direction binning\n        self.rated_power = 1.0  # rated power of the turbine (1.0 if power given as relative to rated power)\n        self.icing_time = 3 # icing length in samples for now\n        self.stop_time = 6 # time filter for stops in number of samples\n        self.pc_low_limit = 10 # lower limit for power curve checks\n        self.pc_high_limit = 90 # lower limit for power curve checks\n        self.stop_level = 0.005 # level used to define stops\n        self.state_filter_type = 1 # type 1 inclusive 2 exclusive\n        self.power_level_filter_limit = 0.01 # limit for self.power_level_filter\n        self.reference_temperature_limit = 3\n        self.icing_temperature_limit = 3\n        self.pc_binsize = 36 # bin size filter for power curve\n        self.pc_dist_filter = True # filter out obviously wrong values from power curves.\n        self.site_elevation = 0.0\n        self.fault_dict = {} # used in case fault codes need to be replaced very non-elegant solution, but...\n        self.result_dir = '.'\n        self.starttimestamp = datetime.datetime.min\n        self.stoptimestamp = datetime.datetime.max\n        self.stopcodes = [] # status codes for icing related stops\n        self.stop_filter_type = 0 # 0 for power level based 1 for status code based where stop if true 2 for stop if false\n        self.status_stop_index = None\n        self.heated_site = False\n        self.ice_detection = False\n        self.ice_alarm_index = 0\n        self.ice_alarm_value = 0\n        self.heating_status_index = 0\n        self.heating_status_value = 0\n        self.heating_status_type = 0\n        self.heating_power_index = 0\n        self.replace_faults = False\n        self.fault_columns = []\n        # TODO:\n        # fix icing and stoptime to be actual minutes instead of sample count\n\n    def get_fallback_value(self, section, config_var):\n        \"\"\"\n        Helper function used when reading .ini files. Sets non-mandatory values to common fallback settings\n        :param section, where config_var is defined\n        :param config_var:\n        :return: fallback value\n        \"\"\"\n        # so far all config var names are unique, no need to split this by section yet, do it anyway\n        if section == 'Source file':\n            sf_fallbacks = {'delimiter': ',',\n                            'quotechar': 'NONE',\n                            'datetime format': '%Y-%m-%d %H:%M:%S',\n                            'datetime extra char': '0',\n                            'replace fault codes': 'False'}\n            return sf_fallbacks[config_var]\n        elif section == 'Output':\n            o_fallbacks = {'result directory': '.',\n                           'summary': 'True',\n                           'plot': 'True',\n                           'alarm time series': 'True',\n                           'filtered raw data': 'True',\n                           'icing events': 'False','power curve': 'True'}\n            return o_fallbacks[config_var]\n        elif section == 'Data Structure':\n            # these are all mandatory, except this one, it needs a fallback to maintain compatibility with old inifiles\n            # need to define this anyway\n            ds_fallbacks = {\"status code stop value\": '0',\n                            \"status index\": '-1'}\n            return ds_fallbacks[config_var]\n        elif section == 'Icing':\n            # icing is not mandatory anyway\n            i_fallbacks = {}\n            return None\n        elif section == 'Binning':\n            b_fallbacks = {'minimum wind speed': '0',\n                           'maximum wind speed': '20',\n                           'wind speed bin size': '1',\n                           'wind direction bin size': '360'}\n            return b_fallbacks[config_var]\n        elif section == 'Filtering':\n            f_fallbacks = {'power drop limit': '10',\n                           'overproduction limit': '90',\n                           'power level filter': '0.01',\n                           'temperature filter': '1',\n                           'reference temperature': '3',\n                           'icing time': '3',\n                           'stop filter type': '0',\n                           'stop limit multiplier': '0.005',\n                           'stop time filter': '6',\n                           'statefilter type': '1',\n                           'min bin size': '36',\n                           'distance filter': 'True',\n                           'start time': 'None',\n                           'stop time': 'None'}\n            return f_fallbacks[config_var]\n        else:\n            print('section \"{0}\" does not exist in config file'.format(section))\n            sys.exit(1)\n\n\n    def set_data_options_from_file(self,filename):\n        \"\"\"\n        read in configuration settings from a config file\n        \"\"\"\n        config = configparser.ConfigParser()\n        config.read(filename)\n        try:\n            self.ts_index = int(config.get('Data Structure','timestamp index'))\n            self.ws_index = int(config.get('Data Structure','wind speed index'))\n            self.wd_index  = int(config.get('Data Structure','wind direction index'))\n            self.temp_index = int(config.get('Data Structure','temperature index'))\n            self.pow_index = int(config.get('Data Structure','power index'))\n            self.rated_power = float(config.get('Data Structure','rated power'))\n            state_index_raw = config.get('Data Structure','state index')\n            self.state_index = [int(column_index) for column_index in state_index_raw.split(',')]\n            self.site_elevation = float(config.get('Data Structure','site elevation'))\n            stop_codes_raw = config.get('Data Structure', 'status code stop value', fallback=self.get_fallback_value('Data Structure', 'status code stop value'))\n            normal_state_raw = config.get('Data Structure','normal state')\n            # normal state can be given as text or as a list of codes, all cases need to be sorted\n            self.replace_faults = config.getboolean('Source file','replace fault codes')\n            if self.replace_faults: # fault codes as text\n                fault_codes = [self.replace_faultcode(codestring) for codestring in normal_state_raw.split(',')]\n                stop_code_values = [self.replace_faultcode(stop_code_string) for stop_code_string in stop_codes_raw.split(',')]\n            else:\n                fault_codes = [int(code) for code in normal_state_raw.split(',')]\n                stop_code_values = [int(stop_code) for stop_code in stop_codes_raw.split(',')]\n            self.normal_state = fault_codes\n            self.stopcodes = stop_code_values\n            self.id = config.get('Source file','id')\n            self.result_dir = config.get('Output', 'result directory', fallback=self.get_fallback_value('Output','result directory'))\n            status_stops_raw = config.get('Data Structure', 'status index', fallback=self.get_fallback_value('Data Structure', 'status index'))\n            self.status_stop_index = [int(code) for code in status_stops_raw.split(',')]\n            fault_column_string = config.get('Source file','fault columns')\n            self.fault_columns = [int(column_index) for column_index in fault_column_string.split(',')]\n        except configparser.NoOptionError as missing_value:\n            print(\"missing config option in {0}: {1}\".format(filename, missing_value))\n            sys.exit(1)\n        except configparser.NoSectionError as missing_section:\n            print(\"missing config section in {0}: {1}\".format(filename, missing_section))\n            sys.exit(1)\n        except ValueError as wrong_value:\n            print(\"Wrong type of value in {0}: {1}\".format(filename, wrong_value))\n            sys.exit(1)\n\n    def replace_faultcode(self, code):\n        \"\"\"\n        Replace textual fault_code with a value from fault_dict. If the wanted faultcode is not in fault_dict,\n        add it as a new maximum value into it and then return the new replacement value.\n\n        :param code:\n        :return the replacement fault code:\n        \"\"\"\n\n        if code in self.fault_dict:\n            return self.fault_dict[code]\n        else:\n            self.fault_dict[code] = max(self.fault_dict.values()) + 1\n            return self.fault_dict[code]\n\n    def set_binning_options_from_file(self, filename):\n        \"\"\"\n        set bin division based on a config file\n        \"\"\"\n        config = configparser.ConfigParser()\n        config.read(filename)\n        if config.has_section('Binning'):\n            try:\n                min_windbin = float(config.get('Binning', 'minimum wind speed', fallback=self.get_fallback_value('Binning', 'minimum wind speed')))\n                max_windbin = float(config.get('Binning', 'maximum wind speed', fallback=self.get_fallback_value('Binning', 'maximum wind speed')))\n                windbin_width = float(config.get('Binning', 'wind speed bin size', fallback=self.get_fallback_value('Binning', 'wind speed bin size')))\n                directionbin_width = float(config.get('Binning', 'wind direction bin size', fallback=self.get_fallback_value('Binning', 'wind direction bin size')))\n                self.wind_bins = np.arange(min_windbin, max_windbin, windbin_width)\n                self.direction_bins = np.arange(0,360,directionbin_width)\n            except configparser.NoOptionError as missing_value:\n                print(\"missing config option in {0}: {1}\".format(filename, missing_value))\n                sys.exit(1)\n            except ValueError as wrong_value:\n                print(\"Wrong type of value in {0}: {1}\".format(filename, wrong_value))\n                sys.exit(1)\n        else:\n            print(\"No binning options set, using defaults\")\n\n    def set_filtering_options_from_file(self, filename):\n        \"\"\"\n        set filtering options based on a config file\n        \"\"\"\n        config = configparser.ConfigParser()\n        config.read(filename)\n        if config.has_section('Filtering'):\n            try:\n                self.pc_low_limit = int(config.get('Filtering', 'power drop limit', fallback=self.get_fallback_value('Filtering', 'power drop limit')))\n                self.pc_high_limit = int(config.get('Filtering', 'overproduction limit', fallback=self.get_fallback_value('Filtering', 'overproduction limit')))\n                self.icing_time = int(config.get('Filtering', 'icing time', fallback=self.get_fallback_value('Filtering', 'icing time')))\n                self.stop_level = float(config.get('Filtering', 'stop limit multiplier', fallback=self.get_fallback_value('Filtering',  'stop limit multiplier')))\n                self.stop_time = int(config.get('Filtering', 'stop time filter', fallback=self.get_fallback_value('Filtering',  'stop time filter')))\n                self.state_filter_type = int(config.get('Filtering', 'statefilter type', fallback=self.get_fallback_value('Filtering',  'statefilter type')))\n                self.pc_binsize = int(config.get('Filtering', 'min bin size', fallback=self.get_fallback_value('Filtering',  'min bin size')))\n                self.pc_dist_filter = config.getboolean('Filtering', 'distance filter', fallback=self.get_fallback_value('Filtering',  'distance filter'))\n                self.power_level_filter_limit = float(config.get('Filtering', 'power level filter', fallback=self.get_fallback_value('Filtering',  'power level filter')))\n                self.icing_temperature_limit = float(config.get('Filtering', 'temperature filter', fallback=self.get_fallback_value('Filtering',  'temperature filter')))\n                self.reference_temperature_limit = float(config.get('Filtering', 'reference temperature', fallback=self.get_fallback_value('Filtering',  'reference temperature')))\n                self.stop_filter_type = int(config.get('Filtering', 'stop filter type', fallback=self.get_fallback_value('Filtering',  'stop filter type')))\n                dt_format = config.get('Source file', 'datetime format', raw=True, fallback=self.get_fallback_value('Source file', 'datetime format'))\n                starttime_str = config.get('Filtering', 'Start time', fallback=self.get_fallback_value('Filtering', 'start time'))\n                if starttime_str.upper() != 'NONE':\n                    self.starttimestamp = datetime.datetime.strptime(starttime_str, dt_format)\n                stoptime_str = config.get('Filtering', 'Stop time', fallback=self.get_fallback_value('Filtering', 'stop time'))\n                if stoptime_str.upper() != 'NONE':\n                    self.stoptimestamp = datetime.datetime.strptime(stoptime_str, dt_format)\n\n            except configparser.NoOptionError as missing_value:\n                print(\"missing config option in {0}: {1}\".format(filename, missing_value))\n                sys.exit(1)\n            except ValueError as wrong_value:\n                print(\"Wrong type of value in {0}: {1}\".format(filename, wrong_value))\n                sys.exit(1)\n\n    def set_ips_options_from_file(self, filename):\n        \"\"\"\n        set config options for a heated site, first check if \"Icing\" section even exists, then set the options\n        \"\"\"\n        config = configparser.ConfigParser()\n        config.read(filename)\n        if config.has_section('Icing'):\n            try:\n                self.heated_site = config.getboolean(\"Icing\",\"heating\")\n                self.ice_detection = config.getboolean(\"Icing\",\"ice detection\")\n                self.ice_alarm_index = int(config.get(\"Icing\",\"icing alarm index\"))\n                if self.replace_faults and (self.ice_alarm_index in self.fault_columns):\n                    ice_alarm_raw = config.get(\"Icing\", \"icing alarm code\")\n                    self.ice_alarm_value = self.fault_dict[ice_alarm_raw]\n                else:\n                    self.ice_alarm_value = int(config.get(\"Icing\", \"icing alarm code\"))\n                heating_index_raw = config.get(\"Icing\",\"ips status index\")\n                heating_value_raw = config.get(\"Icing\",\"ips status code\")\n                self.heating_status_index = [int(code) for code in heating_index_raw.split(',')]\n                if self.replace_faults and any({*self.heating_status_index} & {*self.fault_columns}): # status codes as text\n                    self.heating_status_value = [self.fault_dict[codestring] for codestring in heating_value_raw.split(',')]\n                else:\n                    self.heating_status_value = [int(code) for code in heating_value_raw.split(',')]\n\n                self.heating_status_type = int(config.get(\"Icing\",\"ips status type\"))\n                self.heating_power_index = int(config.get(\"Icing\",\"ips power consumption index\"))\n            except configparser.NoOptionError as missing_value:\n                print(\"missing config option in {0}: {1}\".format(filename, missing_value))\n                sys.exit(1)\n            except configparser.NoSectionError as missing_section:\n                print(\"missing config section in {0}: {1}\".format(filename, missing_section))\n                sys.exit(1)\n            except ValueError as wrong_value:\n                print(\"Wrong type of value in {0}: {1}\".format(filename, wrong_value))\n                sys.exit(1)\n        else:\n            print(\"no [Icing] section in {0}, ignoring IPS options\".format(filename))\n\n    def state_filter_data(self, data):\n        \"\"\"\n        remove all data where the state variable is something else than normal_state\n        correct state variable values depend on turbine type\n        if exclude set to true, remove all lines where state==normal_state\n        exclude is set in a class variable\n\n        if state_filter_type == 3 filter removes data below a certain threshold\n        threshold is set in normal_state\n        state filter type 3 is used in case there is no explicit turbine state and the\n        filtering has to be done using output power or such\n\n\n        :param data: data to be filtered\n        :return: filtered data with the filterd liens removed\n        \"\"\"\n\n        if self.state_filter_type == 2:\n            exclude = True\n        else:\n            exclude = False\n\n        #if exclude:\n            #return data[data[:, self.state_index] != self.normal_state, :]\n            #return np.array([line for line in data if line[self.state_index] not in self.normal_state])\n        #else:\n            #return data[data[:, self.state_index] == self.normal_state, :]\n            #return np.array([line for line in data if line[self.state_index] in self.normal_state])\n        #TODO:\n            # fix this mess, remove exclude from where it iss and have all filter type switches in the same place\n        filtered_data = []\n        for line in data:\n            # state_vals = [line[i] for i in self.state_index]\n            # state_val_check = all([j in self.normal_state for j in state_vals]) # if all in state_vals are in normal state evaluates as True\n            state_val_check_vars = []\n            for normal_state_index,value_index in enumerate(self.state_index):\n                if self.state_filter_type == 3:\n                    state_val_check_vars.append(line[value_index] >= self.normal_state[normal_state_index])\n                elif self.state_filter_type == 4:\n                    state_val_check_vars.append(line[value_index] <= self.normal_state[normal_state_index])\n                else:\n                    state_val_check_vars.append(line[value_index] == self.normal_state[normal_state_index])\n            state_val_check = all(state_val_check_vars)\n            if exclude:\n                if not state_val_check:\n                    filtered_data.append(line)\n            else:\n                if state_val_check:\n                    filtered_data.append(line)\n        return np.array(filtered_data)\n\n    def temperature_filter_data(self, data):\n        \"\"\"\n        remove all data points with temperature below set threshold\n\n        :param data: input data\n        :return: data set containing only the data in previously specified range\n        \"\"\"\n        # suppress the runtimewarning caused by nans in data\n        # the result is what we want: nans case the comparison to evaluate as false\n        with np.errstate(invalid = 'ignore'):\n            return data[data[:, self.temp_index] >= self.reference_temperature_limit, :]\n\n    def power_level_filter(self, data):\n        \"\"\"\n        remove all data points where power is below the wanted limit level\n\n        limit is defined as percentage of rated power\n\n        :param data: unfiltered input data\n        :param limit_level: filtering level as fraction of rated\n        :return: data with the unwanted timestamps removed\n        \"\"\"\n        # suppress the runtimewarning caused by nans in data\n        # the result is what we want: nans case the comparison to evaluate as false\n        with np.errstate(invalid = 'ignore'):\n            return data[data[:, self.pow_index] >= (self.power_level_filter_limit * self.rated_power), :]\n\n    def wind_speed_filter(self,data,limit_level):\n        \"\"\"\n        remove all data points with wind speed below a preset level\n\n        :param data: original data\n        :param limit_level: filtering level\n        :return: filtered data\n        \"\"\"\n        # suppress the runtimewarning caused by nans in data\n        # the result is what we want: nans case the comparison to evaluate as false\n        with np.errstate(invalid = 'ignore'):\n            return data[data[:, self.ws_index] >= limit_level, :]\n\n    def time_filter_data(self, data):\n        \"\"\"\n\n        :param data: the data to be filtered\n        :param start: start time as datetime.datetime\n        :param stop: stop time as datetime.datetime\n        :return: filtered dataset\n        \"\"\"\n        return data[np.logical_and(data[:, self.ts_index] >= self.starttimestamp, data[:, self.ts_index] < self.stoptimestamp), :]\n\n\n    def expand_array(self, arr, n):\n        \"\"\"\n        add n columns to the right-hand side of a numpy ndarray\n        used for bin indices when binning data\n\n        :param arr: original array\n        :param n: number column to be added\n        :return: appended array\n        \"\"\"\n        for i in range(n):\n            arr = np.c_[arr, np.zeros(np.shape(arr)[0])]\n        return arr\n\n    def bin_measurement(self, data, bin_centers, comp_column, bin_index_column, direction=False):\n        \"\"\"\n        puts a measurement into an appropriate bin\n\n        :param data: contains a single line of measurements\n        :param bin_centers: a numpy.ndarray containing centerpoints of the bin division\n        :param comp_column: column index of the variable used for binning e.g.\n                            wind speed index when searching for the appropriate wind speed bin\n\n        :param bin_index_column: column index where bin indexes are stored\n        :return: parameter data with the bin index appended\n\n        \"\"\"\n        if direction:\n            value = data[comp_column]\n            x = np.cos(np.radians(value))\n            y = np.sin(np.radians(value))\n            bin_x = np.cos(np.radians(bin_centers))\n            bin_y = np.sin(np.radians(bin_centers))\n            bin_index = np.sqrt((x-bin_x)**2+(y-bin_y)**2).argmin()\n            data[bin_index_column] = bin_index\n        else:\n            data[bin_index_column] = abs(float(data[comp_column])-bin_centers).argmin()\n        return data\n\n    def wind_dir_mean(self,a):\n        \"\"\"\n        calculates the mean of wind direction measurements contained in array data\n\n        :param a: array of wind direction measurements in degrees\n        :return: mean of the array\n        \"\"\"\n        y = []\n        x = []\n        for item in a:\n            if not np.isnan(item):\n                y.append(np.sin(np.radians(item)))\n                x.append(np.cos(np.radians(item)))\n\n        if np.size(y) == 0 or np.size(x) == 0:\n            return np.nan\n        else:\n            my = np.nanmean(y)\n            mx = np.nanmean(x)\n            angle = np.degrees(np.arctan2(my,mx))\n\n            #wd_mean = np.remainder(360.0 + np.degrees(np.arctan2(my,mx)),360.0)\n            wd_mean = (angle +360) % 360\n            #print((mx,my,wd_mean))\n            return wd_mean\n\n    def put_data_into_bins(self, data, bins, comp_column,direction=False):\n        \"\"\"\n        Bins into externally defined set of bins. Adds a column to the data matrix containing a bin index.\n        After this contents of any bin can be found using features of a numpy.ndarray\n\n        Example:\n            we need contents of bin number 7. This is returned by\n                    data[data[:,-1]==7,:]\n\n\n        :param data: original data that needs to be separated in to bins. A numpy.ndarray\n        :param bins: center points of the bins\n        :param comp_column: column in the data containing the value used for binning\n                            (wind speed index when binning by wind speed)\n\n        :return: expanded array, contains the original data and one additional\n                 column that contains a bin index for each line\n\n        \"\"\"\n        binned_data = []\n        exp_data = self.expand_array(data, 1)\n        for line in exp_data:\n            if direction:\n                binned_data.append(self.bin_measurement(line, bins, comp_column, -1,True))\n            else:\n                binned_data.append(self.bin_measurement(line, bins, comp_column, -1))\n        return np.array(binned_data)\n\n    def fetch_bin_contents_2d(self, data, bin_index1, bin_number1, bin_index2, bin_number2):\n        \"\"\"\n        returns the contents of a particular bin in case that data is binned according to two different variables\n        for example wind speed and direction\n\n        :param data: binned data wind bin indexes\n        :param bin_index1: column where the first bin index is found\n        :param bin_number1: requested bin on the first bin index\n        :param bin_index2:  column where the second bin index is found\n        :param bin_number2: requested bin on the second bin index\n        :return: slice of the data containing the contents of the wanted bin\n        \"\"\"\n        return data[np.logical_and(data[:, bin_index1] == bin_number1, data[:, bin_index2] == bin_number2), :]\n\n    def nan_helper(self, y):\n        \"\"\"\n        Helper to handle indices and logical indices of NaNs.\n\n        | Input:\n        |    - y, 1d numpy array with possible NaNs\n        | Output:\n        |    - nans, logical indices of NaNs\n        |    - index, a function, with signature indices= index(logical_indices),\n        |      to convert logical indices of NaNs to 'equivalent' indices\n        | Example:\n        |     # linear interpolation of NaNs\n        |     nans, x= nan_helper(y)\n        |     y[nans]= np.interp(x(nans), x(~nans), y[~nans])\n\n        :param y: input array\n        :return: converted array\n        \"\"\"\n\n        return np.isnan(y), lambda z: z.nonzero()[0]\n\n    def interpolate_over_nans(self, pc):\n        \"\"\"\n        helper function to interpolate over possible nan values in power curves caused by empty bins\n        during binning\n        input is a single power curve i.e. 2d matrix of wind speed versus power\n\n        :param pc: power curve matrix as returned by self.count_power_curves\n        :return: interpolated power curves\n        \"\"\"\n        nans, x = self.nan_helper(pc)\n        pc[nans] = np.interp(x(nans), x(~nans), pc[~nans])\n        return pc\n\n    def distance_to_neighbours(self, pc, speed_bin, direction_bin, variable_index):\n        \"\"\"\n        helper function used in power curve post-processing:\n        calculates the mean distance of point at index in different curves stored in data\n        Operates only on one bin at a time.\n        requires power curves divided according to wind speed and direction\n\n        :param pc: original dataset containing the power curves as defined by count_power_curves function\n        :param speed_bin: index of active wind speed bin\n        :param direction_bin: index of active wind direction bin\n        :param variable_index: processed variable. usually power\n        :return: mean distance to all other power curves in the particular bin\n        \"\"\"\n        (x, y, z) = np.shape(pc)\n        # reduce the dimension\n        targets = pc[speed_bin, :, variable_index]\n        distances = []\n        neighbours = np.ones(y).astype('bool')\n        neighbours[direction_bin] = False\n        distances.append(np.abs(targets[neighbours]-targets[direction_bin]))\n        if len(distances) == 0:\n            return 0.0\n        else:\n            return np.nanmean(np.array(distances))\n\n    def distance_filter(self, pc, target_value):\n        \"\"\"\n        calculate distances between different power curves,\n        if value is dramatically different replace with mean of all others\n        goes through all curves bin by bin\n        can be useful to automatically weed out outliers in the data\n\n        :param pc: prefilterd power curves\n        :param target_value: index of the value used for filtering e.g. power\n        :return: fltered power curve matrix\n\n        \"\"\"\n        (x, y, z) = np.shape(pc)\n        value_filter = 2.5\n        for speed_bin in range(x):\n            mean_distances = np.zeros(y)\n            for direction_bin in range(y):\n                mean_distances[direction_bin] = self.distance_to_neighbours(pc, speed_bin, direction_bin, target_value)\n            med_dist = np.nanmedian(mean_distances)\n            bad_values = []\n            for index,value in enumerate(mean_distances):\n                if (value/med_dist) > value_filter:\n                    bad_values.append(index)\n\n            neighbours = np.ones(y).astype('bool')\n            neighbours[bad_values] = False\n            # print(\"{0}: {1}\".format(speed_bin,bad_values))\n            mpc = self.mean_power_curve(pc[:, neighbours,:])\n            for value in bad_values:\n                pc[speed_bin, value, target_value] = mpc[speed_bin, target_value]\n        return pc\n\n    def diff_filter(self,data,diff_limit=0.001):\n        \"\"\"\n        appplies a filter to data that discards all values that differ less than diff_limit from the previous one\n        :param data:\n        :param diff_limit:\n        :return:\n        \"\"\"\n        data_diff = np.diff(data[:,self.pow_index]) # start with power\n        data_diff = np.hstack((np.array(0), data_diff))\n        mask = data_diff > diff_limit\n        return data[mask,:]\n\n    def bin_size_filter(self, pc, size_limit):\n        \"\"\"\n        bin size based filtering for the power curve\n        removes all data from the bin if not enough values available\n\n        :param pc: power curve matrix\n        :param size_limit: number of measurements required for the bin to be used\n        :return: a boolean matrix that can be used to mark too small bin as empty\n        \"\"\"\n\n        (x, y, z) = np.shape(pc)\n        too_smalls = np.zeros(np.shape(pc)).astype('bool')\n        for speed_bin in range(x):\n            for direction_bin in range(y):\n                if pc[speed_bin, direction_bin, 7] < size_limit:\n                    too_smalls[speed_bin, direction_bin, 2] = True\n                    too_smalls[speed_bin, direction_bin, 3] = True\n                    too_smalls[speed_bin, direction_bin, 4] = True\n                    too_smalls[speed_bin, direction_bin, 5] = True\n                    too_smalls[speed_bin, direction_bin, 6] = True\n                    too_smalls[speed_bin, direction_bin, 8] = True\n                    too_smalls[speed_bin, direction_bin, 9] = True\n        return too_smalls\n\n    def theoretical_output_power(self, data, power_curves):\n        \"\"\"\n        calculates the theoretical, expected output power based on power curve and measured wind speed\n\n        :param data:\n        :param power_curve:\n        :return: rerference power, in structure [timestamp, interpolated reference power, actual measured output power]\n        \"\"\"\n        reference = []\n        time_limited_data = self.time_filter_data(data)\n        for line in time_limited_data:\n            dirbin = np.argmin(np.abs(self.direction_bins - line[self.wd_index]))\n            int_pow = np.interp(line[self.ws_index], power_curves[:, dirbin, 0], power_curves[:, dirbin, 2])\n            int_pow_p10 = np.interp(line[self.ws_index], power_curves[:, dirbin, 0], power_curves[:, dirbin, 3])\n            int_pow_p90 = np.interp(line[self.ws_index], power_curves[:, dirbin, 0], power_curves[:, dirbin, 4])\n            uncert_lower_lim = np.interp(line[self.ws_index], power_curves[:, dirbin, 0], power_curves[:, dirbin, 8])\n            uncert_upper_lim = np.interp(line[self.ws_index], power_curves[:, dirbin, 0], power_curves[:, dirbin, 9])\n            reference.append((line[self.ts_index], int_pow, line[self.pow_index], int_pow_p10, int_pow_p90, uncert_lower_lim, uncert_upper_lim))\n        return np.array(reference)\n\n    def calculate_production(self,data,index,delta=datetime.timedelta(seconds=10*60)):\n        \"\"\"\n        calculates total production between from previous time stamp to current, assuming the difference is constant\n        skips all occurrences where the difference between two adjacent timestamps is not constant\n\n        NOTE: assumes timestamp is at index 0\n\n        :param data: input data, containing the measured output\n        :param index: index of the production measurement\n        :param delta: difference between two timestamps defaults to ten minutes\n        :return: structure containing [end timestep, production]\n        \"\"\"\n        output_data = []\n        for i in range(len(data)):\n            if i != 0:\n                # integrity check\n                if ((data[i,0] - data[i-1,0]) > delta) or np.isnan(data[i,index]) or np.isnan(data[i-1,index]) or (data[i,index] <=0.0) or (data[i-1,index] <= 0.0):\n                    prod = 0\n                else:\n                    dur = (data[i,0]-data[i-1,0]).total_seconds()/60.0/60.0 # length in hours\n                    pow_at_start = data[i-1,index]\n                    pow_at_stop = data[i,index]\n                    prod = dur * ((pow_at_start+pow_at_stop) / 2.0)\n                output_data.append((data[i,0],prod))\n        output_datalen = len(output_data)\n        return np.array(output_data)\n\n    def count_power_curves(self, data):\n        \"\"\"\n        Calculates a set of power curves from the input data\n        bins the data according to wind speed and direction\n        the binning and the column indexes of the data are defined in the class variables\n\n        Power curves contain the power curve and the P10 limit for said curve separately\n        for each wind direction defined in the wind direction binning.\n\n        output is three dimensional array containing:\n\n            * median wind speed\n            * median wind direction\n            * P10 value\n            * bin size (number of measurements in this particular bin)\n\n        for each speed and direction defined in self.wind_bins and self_direction bins\n\n        missing data (empty bins) are marked as nan\n        missing values can then be interpolated over so that there are no empty bins.\n\n        Also possible to do other kinds of filtering to improve the end result and to reduce the\n        impact of outliers in the data\n\n        Method automatically filters the data according to elsewhere defined state variable filter\n        (is this a good idea???)\n\n        Only part of data where temperature is more than 3 degrees is used to make the power curves\n\n        :param data: input data time series. can be unfiltered\n        :param temperature_filter_level: temperature in degrees, all data with temperatures above this level are used to build the reference dataset\n        :param lower_limit: percentile used as limit for power reduction (default 10)\n        :param upper_limit: percentile used as limit for overproduction (default 90)\n        :return pc: a numpy.ndarray that contains the power curves, warning limits and bin sizes for each bin,\n                    sorted by wind speed and direction\n\n        \"\"\"\n        # direction_bins = np.array([0])\n        # st_data = self.state_filter_data(data, self.normal_state)\n        # ref_data = self.temperature_filter_data(data, temperature_filter_level)\n        pc = np.zeros((len(self.wind_bins), len(self.direction_bins), 10))\n        dir_data = self.put_data_into_bins(data, self.direction_bins, self.wd_index,direction=True)\n        binned_data = self.put_data_into_bins(dir_data, self.wind_bins, self.ws_index)\n        wind_speed_index = 0\n        wind_dir_index = 1\n        power_index = 2\n        low_limit_index = 3\n        high_limit_index = 4\n        bin_standard_dev_index = 5\n        bin_uncertainty = 6\n        bin_uncertainty_lower_lim_index = 8\n        bin_uncertainty_upper_lim_index = 9\n        bin_size_index = 7\n        #print(binned_data)\n        for speed_bin_index in range(len(self.wind_bins)):\n            for direction_bin_index in range(len(self.direction_bins)):\n                bin_contents = self.fetch_bin_contents_2d(binned_data, -1, speed_bin_index, -2, direction_bin_index)\n                if bin_contents.size == 0:\n                    pc[speed_bin_index, direction_bin_index, wind_speed_index] = self.wind_bins[speed_bin_index]\n                    pc[speed_bin_index, direction_bin_index, wind_dir_index] = self.direction_bins[direction_bin_index]\n                    # force power to be 0 at wind speed 0, helps with interpolation\n                    # and other tricks used to cover missing data\n                    if speed_bin_index == 0:\n                        replacement = 0\n                    else:\n                        replacement = np.nan\n                    pc[speed_bin_index, direction_bin_index, power_index] = replacement\n                    pc[speed_bin_index, direction_bin_index, low_limit_index] = replacement\n                    pc[speed_bin_index, direction_bin_index, high_limit_index] = replacement\n                    pc[speed_bin_index, direction_bin_index, bin_standard_dev_index] = replacement\n                    pc[speed_bin_index, direction_bin_index, bin_uncertainty] = replacement\n                    pc[speed_bin_index, direction_bin_index, bin_uncertainty_lower_lim_index] = replacement\n                    pc[speed_bin_index, direction_bin_index, bin_uncertainty_upper_lim_index] = replacement\n                    pc[speed_bin_index, direction_bin_index, bin_size_index] = bin_contents.size\n                else:\n                    # suppress runtime errors caused by bins with nothing but nans\n                    if np.isnan(bin_contents[:, self.ws_index].astype('float')).all():\n                        pc[speed_bin_index, direction_bin_index, wind_speed_index] = np.nan\n                    else:\n                        pc[speed_bin_index, direction_bin_index, wind_speed_index] = np.nanmedian(bin_contents[:, self.ws_index].astype('float'))\n                    if np.isnan(bin_contents[:, self.wd_index].astype('float')).all():\n                        pc[speed_bin_index, direction_bin_index, wind_dir_index] = np.nan\n                    else:\n                        pc[speed_bin_index, direction_bin_index, wind_dir_index] = self.wind_dir_mean(bin_contents[:, self.wd_index].astype('float'))\n                    if np.isnan(bin_contents[:, self.pow_index].astype('float')).all():\n                        pc[speed_bin_index, direction_bin_index, power_index] = np.nan\n                        pc[speed_bin_index, direction_bin_index, low_limit_index] = np.nan\n                        pc[speed_bin_index, direction_bin_index, high_limit_index] = np.nan\n                        pc[speed_bin_index, direction_bin_index, bin_standard_dev_index] = np.nan\n                        pc[speed_bin_index, direction_bin_index, bin_uncertainty] = np.nan\n                        pc[speed_bin_index, direction_bin_index, bin_uncertainty_lower_lim_index] = np.nan\n                        pc[speed_bin_index, direction_bin_index, bin_uncertainty_upper_lim_index] = np.nan\n                    else:\n                        #pc[speed_bin_index, direction_bin_index, power_index] = np.nanmean(bin_contents[:, self.pow_index].astype('float'))\n                        mean_power = np.nanmedian(bin_contents[:, self.pow_index].astype('float'))\n                        power_std_dev = np.nanstd(bin_contents[:, self.pow_index].astype('float'))\n                        pc[speed_bin_index, direction_bin_index, power_index] = mean_power\n                        pc[speed_bin_index, direction_bin_index, low_limit_index] = ss.scoreatpercentile(bin_contents[:, self.pow_index], self.pc_low_limit)\n                        pc[speed_bin_index, direction_bin_index, high_limit_index] = ss.scoreatpercentile(bin_contents[:, self.pow_index], self.pc_high_limit)\n                        pc[speed_bin_index, direction_bin_index, bin_standard_dev_index] = power_std_dev\n                        # divide by zero possible\n                        if pc[speed_bin_index, direction_bin_index, power_index] != 0.0:\n                            pc[speed_bin_index, direction_bin_index, bin_uncertainty] = power_std_dev / mean_power * 100.0\n                        else:\n                            pc[speed_bin_index, direction_bin_index, bin_uncertainty] = 0.0\n                        # upper and lower limits needed for production uncertainty\n                        pc[speed_bin_index, direction_bin_index, bin_uncertainty_lower_lim_index] = max(0.0, mean_power - power_std_dev)\n                        # prevent upper liimt from going below lower limit\n                        if mean_power > self.rated_power:\n                            power_upper_limit = mean_power + power_std_dev\n                        else:\n                            power_upper_limit = min(mean_power + power_std_dev, self.rated_power)\n                        pc[speed_bin_index, direction_bin_index, bin_uncertainty_upper_lim_index] = power_upper_limit\n                    bin_rows, bin_columns = bin_contents.shape\n                    pc[speed_bin_index, direction_bin_index, bin_size_index] = bin_rows\n\n        #TODO:\n            # make filtering optional, on by default\n\n        too_smalls = self.bin_size_filter(pc, self.pc_binsize)\n        pc[too_smalls] = np.nan\n        # interpolate over missing data\n        for dir_bin_index in range(len(self.direction_bins)):\n            try:\n                pc[:, dir_bin_index, power_index] = self.interpolate_over_nans(pc[:, dir_bin_index, power_index])\n                pc[:, dir_bin_index, low_limit_index] = self.interpolate_over_nans(pc[:, dir_bin_index, low_limit_index])\n                pc[:, dir_bin_index, high_limit_index] = self.interpolate_over_nans(pc[:, dir_bin_index, high_limit_index])\n                pc[:, dir_bin_index, bin_standard_dev_index] = self.interpolate_over_nans(pc[:,dir_bin_index, bin_standard_dev_index])\n                pc[:, dir_bin_index, bin_uncertainty] = self.interpolate_over_nans(pc[:, dir_bin_index, bin_uncertainty])\n                pc[:, dir_bin_index, bin_uncertainty_lower_lim_index] = self.interpolate_over_nans(pc[:, dir_bin_index, bin_uncertainty_lower_lim_index])\n                pc[:, dir_bin_index, bin_uncertainty_upper_lim_index] = self.interpolate_over_nans(pc[:, dir_bin_index, bin_uncertainty_upper_lim_index])\n            except ValueError:\n                # import ipdb;ipdb.set_trace()\n                print('Error in power curve generation!!')\n                print('Dir bin index: {}'.format(dir_bin_index))\n                print(pc[:, dir_bin_index, :])\n        # filter out obviously wrong values only usable if there is more than one direction bin\n        [x,y,z] = np.shape(pc)\n        if self.pc_dist_filter and (y > 1):\n            pc = self.distance_filter(pc, power_index)\n            pc = self.distance_filter(pc, low_limit_index)\n            pc = self.distance_filter(pc, high_limit_index)\n        return pc\n\n    def mean_power_curve(self, pc):\n        \"\"\"\n        calculates mean (direction independent power curve)\n\n        :param pc:\n        :return: mean power curve, averagesd accross direction bins\n        \"\"\"\n        return np.nanmean(pc, 1)\n\n    def prettyprint_power_curves(self, pc, index=2, print_result=False):\n        \"\"\"\n        print matrix representations of different variables inside the power curve data structure\n        returns a human readable matrix of wanted quantity\n\n        :param pc: power curve array\n        :param index: index in the power curve to be printed:\n\n                2 : mean power\n                3 : P90\n                4 : P10\n                5 : bin standard deviation\n                6 : bin uncertainty (std_dev / mean)\n                7 : bin size\n\n        :param print_result: if True, prints the resulting array to stdout, defaults to False\n        :return: sanitized matrix\n\n        \"\"\"\n        power_curve_table = pc[:, :, index]\n        # add headers\n        power_curve_table = np.r_[np.reshape(self.direction_bins, (1, len(self.direction_bins))), power_curve_table]\n        ws_column = np.r_[np.nan, self.wind_bins]\n        power_curve_table = np.c_[ws_column, power_curve_table]\n        field_width = 10\n        precision = 1\n        separator = '\\t'\n        output = []\n        for line in power_curve_table:\n            outputline = ''\n            for index, item in enumerate(line):\n                if np.isnan(item):\n                    token = field_width * ' '\n                else:\n                    token = '{0:>{1}.{2}f}'.format(item, field_width, precision)\n                if index == 0:\n                    outputline += token\n                else:\n                    outputline += separator\n                    outputline += token\n            outputline += '\\n'\n            if print_result:\n                print(outputline)\n            output.append(outputline)\n        return output\n\n    def power_curve_uncertainty_average(self, pc, low_limit=4, high_limit=15):\n        \"\"\"\n        Calculate a mean value for power curve uncertainty for the summary file\n        use only wind speeds between low_limit and high_limit and return just one value\n\n        :param pc: power curve structure\n        :param low_limit: lowest applicable wind speed\n        :param high_limit: highest applicable wind speed\n        :return: one value to represent power curve uncertainty\n        \"\"\"\n        # take direction bin wise mean of all power curves first\n        mpc = self.mean_power_curve(pc)\n        mask = (mpc[:,0]>= low_limit) & (mpc[:,0]<=high_limit)\n        uncertainties = mpc[mask,6]\n        return (np.nanmean(uncertainties))\n\n    def timefilter_ice_alarms(self, data, window):\n        \"\"\"\n        clean outliers from ice alarms, demand, that there is at least window number of consecutive alarms\n        begin the icing event from the first switch from 0->1 end at the switch from 1->0\n\n        :param data: time series of alarms created by the power_alarms function\n        :param window: length of hte filtering window\n        :return data: reformatted data, with individual events removed\n        \"\"\"\n        max_index = len(data)-window\n        data_index = 0\n        while data_index < max_index:\n            consecutive_alarms = 0\n            try:\n                while data[data_index + consecutive_alarms, 1] != 0:\n                    consecutive_alarms += 1\n            except IndexError:  # would raise error if this reaches the final index in the data, we can ignore this\n                pass\n            if consecutive_alarms > 0:\n                if consecutive_alarms < window:\n                    data[data_index:(data_index + consecutive_alarms), 1] = 0\n                data_index += consecutive_alarms\n            else:\n                data_index += 1\n        return data\n\n    def power_alarms(self, data, power_curves, time_filter=True, over=False):\n        \"\"\"\n        flag timestamps that match wanted power alarm criteria.\n\n        For each measurement in data, search the proper value from the power curves\n        If the power at any moment is below the previously calculated P10 value AND temperature is below a\n        threshold, flag the timestamp.\n\n\n        after all the data is processed do an additional time-based filtering step where all cases where there are not\n        enough consecutive alarms are discarded.\n        default idea is to demand that the power should remain below the P10 value for at least half an hour before\n        the incident is considered a confirmed icing event\n\n        Another considered ice class is cases where iced anemometer results in apparent overproduction.\n        These cases are seen in the data as appearing above the P90 line. They are flagged in a similar way and\n        same time filtering applies here as well\n\n        The specification lists these as ice case A (production loss) and ice case C (overproduction)\n        These are marked in the output as 1 for case A and 3 for case C in the alarm variable\n\n        TODO:\n            assumes ten minute data, should probably be a parameter\n\n\n        :param data: input data\n        :param power_curves: calculated power curves, binned based on wind speed and direction\n        :param time_filter: if True, an additional time filter is applied to the data\n        :param time_filter_length: number of consecutive values below the alarm limit required to trigger the icing alarm\n        :param over: if True, flags the timestamps where the power is above P90 instead\n        :return: an array of the format [timestamp, alarm, wind speed, reference power, temperature, power, limit]\n        \"\"\"\n        pow_alarms = []\n        timed = datetime.timedelta(seconds=601)\n        for index,line in enumerate(data):\n            # integrity check for the data\n            if (index != 0) and (index != len(data)-1):\n                continuous = (line[self.ts_index] - data[index-1,self.ts_index]) < timed and (data[index+1,self.ts_index] - line[self.ts_index]) < timed\n            else:\n                continuous = False\n            # pick index of active direction bin\n            dirbin = np.argmin(np.abs(line[self.wd_index]-self.direction_bins))\n            # pick the active wind speed bin\n            windbin = np.argmin(np.abs(line[self.ws_index]-self.wind_bins))\n            #wind and power at active bin\n\n            # interpolate the value from power and limit (P10) curve to matches the current wind speed\n            # np.interp does piecewise linear interpolation that can be assumed to be good enough in this\n            # case. The power curve is close to linear between any two bins\n            if over:\n                int_lim = np.interp(line[self.ws_index], power_curves[:, dirbin, 0], power_curves[:, dirbin, 4])\n            else:\n                int_lim = np.interp(line[self.ws_index], power_curves[:, dirbin, 0], power_curves[:, dirbin, 3])\n            int_pow = np.interp(line[self.ws_index], power_curves[:, dirbin, 0], power_curves[:, dirbin, 2])\n\n            if continuous:\n                if over:\n                    if (line[self.pow_index] >= int_lim) and (line[self.temp_index] <= self.icing_temperature_limit):\n                        pow_alrm = 3.0\n                    else:\n                        pow_alrm = 0.0\n                else:\n                    if (line[self.pow_index] <= int_lim) and (line[self.temp_index] <= self.icing_temperature_limit):\n                        pow_alrm = 1.0\n                    else:\n                        pow_alrm = 0.0\n            else:\n                pow_alrm = 0.0\n            pow_alarms.append((line[self.ts_index], pow_alrm, line[self.ws_index], int_pow, line[self.temp_index], line[self.pow_index], int_lim))\n        alarms = np.array(pow_alarms)\n        if time_filter:\n            filtered_alarms = self.timefilter_ice_alarms(alarms, self.icing_time)\n            return filtered_alarms\n        else:\n            return alarms\n\n    def power_loss_during_alarm(self, data, ips_alarm=False):\n        \"\"\"\n        Collect the start and stop times of icing alarms and calculate the total\n        power/production loss during the icing event\n\n        counts the production loss by calculating the approximate area between\n        the estimated production curve and the actual production curve as calculated by power_alarms\n\n        :param data: data produced by the power_alarms function\n        :param ips_alarm: set to True if alarm was caused by IPS system\n        :return: a structure containing the starts and stops and losses formatted as [starttime stoptime powerloss]\n        \"\"\"\n\n        datalen = np.shape(data)[0]\n        alarm_stats = []\n        if datalen > 0:\n            # calculate the times when the alarm changes on and off\n            # numpy.diff calculates array[n+1] - array[n]\n            alarm_diff = np.diff(data[:, 1])\n            # pad a zero to the beginning, unless data[0] is an alarm\n            if data[0,1] != 0.0:\n                alarm_diff = np.hstack((np.array(1), alarm_diff))\n            else:\n                alarm_diff = np.hstack((np.array(0), alarm_diff))\n\n\n            # now icing starts at times when diff == 1 and stops when diff == -1\n            starts = data[alarm_diff > 0, 0]\n            stops = data[alarm_diff < 0, 0]\n\n            num_starts = len(starts)\n            num_stops = len(stops)\n\n            max_index = min((num_starts, num_stops))\n            index = 0\n\n            # sort starts and stops into an array\n            try:\n                while (index < max_index) and (datalen > 0):\n                    try:\n                        starttime = starts[index]\n                        stoptime = stops[index]\n                        if starttime > stoptime:\n                            raise TimingError(starttime,stoptime,index)\n\n                        # pull thecorresponding start and stoptimes from real data\n                        start_index = np.argmin(np.abs(data[:, 0]-starttime))\n                        stop_index = np.argmin(np.abs(data[:, 0]-stoptime))\n\n                        loss_sum = 0\n                        ips_sum = 0\n                        for i in range(start_index, stop_index, 1):\n                            # step duration in hours\n                            step_duration = (data[i+1, 0]-data[i, 0]).total_seconds()/60.0/60.0\n                            loss_at_start = data[i, 3]-data[i, 5]\n                            loss_at_stop = data[i+1, 3]-data[i+1, 5]\n                            # if either of these is np.nan add a zero to the loss sum\n                            if np.isnan(loss_at_start) or np.isnan(loss_at_stop):\n                                loss_sum += 0.0\n                                if ips_alarm:\n                                    ips_sum += 0\n                            else:\n                                # integrate the losses using trapezoidal rule\n                                loss_sum += step_duration * ((loss_at_start + loss_at_stop)/2.0)\n                                if ips_alarm:\n                                    ips_sum += step_duration * ((data[i,7] + data[i+1,7])/2.0)\n                        # mean_power_drop = np.nanmean(data[start_index:stop_index,3].astype(np.float32)-data[start_index:stop_index,5].astype(np.float32))\n                        # mean_power = np.nanmean(data[start_index:stop_index,5].astype(np.float32))\n                        # mean_reference_power = np.nanmean(data[start_index:stop_index,3].astype(np.float32))\n                        # mean_wind_speed = np.nanmean(data[start_index:stop_index,2].astype(np.float32))\n                        # mean_temperature = np.nanmean(data[start_index:stop_index,4].astype(np.float32))\n                        event_length = (data[stop_index,0]- data[start_index,0]).total_seconds()/60.0/60.0\n                        #alarm_stats.append((starttime, stoptime, loss_sum, event_length , mean_power_drop, mean_power, mean_reference_power, mean_wind_speed, mean_temperature))\n                        if ips_alarm:\n                            if self.heating_power_index < 0:\n                                alarm_stats.append((starttime, stoptime, loss_sum, event_length,0.0))\n                            else:\n                                alarm_stats.append((starttime, stoptime, loss_sum, event_length,ips_sum))\n                        else:\n                            alarm_stats.append((starttime, stoptime, loss_sum, event_length))\n                    except TimingError as e:\n                        import pdb;pdb.set_trace()\n                        print(\"Start after stop at index {0} in {1}\".format(e.index, self.id))\n                        print(\"start: {0}; stop: {1}\".format(e.start.strftime(e.dateformat), e.stop.strftime(e.dateformat)))\n                    index += 1\n            except IndexError:\n                print(\"out of bounds at index: {0}\".format(index))\n                print(\"num starts: {0}; num stops: {1}\".format(num_starts, num_stops))\n\n\n        return np.array(alarm_stats)\n\n    def air_density_correction(self, data):\n        \"\"\"\n        Calculate air density correction for wind speed according to specifications in the IEA document\n        returns a new array with corrected wind speed in place of the measured one\n\n        Corrected wind speed for the site can be calculated as:\n\n        | ws_site = ws_std*((temp_site*P_std)/(temp_std*(101325*(1-2.2557e-5*h)^5.25588)))^(1/3)\n        |\n        | ws_site is the corrected wind speed for the site\n        | ws_std is the measured nacelle wind speed\n        | temp_site is the site temperature\n        | P_std is the standard air pressure at sea level (101325 Pa)\n        | temp_std is the standard temperature of 15 C (288.15 K)\n        | h is site height in meters\n\n        :param data:\n        :return: corrected data\n        \"\"\"\n\n        p_std = 101325\n        temp_std = 288.15\n        kelvin = 273.15\n        new_data = []\n        for i, line in enumerate(data):\n            new_line = []\n            for j, item in enumerate(line):\n                if j != self.ws_index:\n                    new_line.append(item)\n                else:\n                    # density_correction = ((line[self.temp_index]+kelvin)*p_std)/(temp_std*(p_std*((1-self.site_elevation*2.2557e-5)**5.25588)))\n                    density_correction = (temp_std/(line[self.temp_index]+kelvin))*((1-self.site_elevation*2.2557e-5)**5.25588)\n                    if np.isnan(density_correction):\n                        ws_site = np.nan\n                    else:\n                        sign = np.sign(density_correction)\n                        ws_site = line[self.ws_index] * sign * (np.abs(density_correction))**(1/3)\n                    new_line.append(ws_site)\n            new_data.append(new_line)\n        return np.array(new_data)\n\n    def count_availability(self, data):\n        \"\"\"\n        Calculate availability number for data\n\n        availability tells in % the amount of possible data available in the dataset\n        checks if there is data available for each timestamp between first and last timestamp\n        if there is, returns availability of 100 %\n\n        does not check data integrity, only if there is some kind of data available. Available data could be garbage.\n\n        :param data: data array of the time series\n        :return: availability number\n        \"\"\"\n        start_time = min(data[:, self.ts_index])\n        stop_time = max(data[:, self.ts_index])\n        # set timestep to smallest value found unless its 0\n        timestep = np.min(np.diff(data[:,self.ts_index]))\n        if timestep.total_seconds() == 0.0:\n            timestep = data[1, self.ts_index] - data[0, self.ts_index]\n        timelength = stop_time - start_time\n        stepcount = timelength / timestep\n        availability = len(data) / stepcount\n\n        return availability\n\n\n\n    def find_icing_related_stops(self, data, power_curve):\n        \"\"\"\n        Finds timestamps from the data, when the turbine has stopped for whatever reason\n\n        uses filtering requirements defined in the specification document: pwr_mean< 0.005*P_rated\n\n        :param data: timeseries data of output\n        :param power_curve: power curve array used\n        :return: filtered data with stops flagged\n        \"\"\"\n        filtered_data = []\n        stop_limit = self.stop_level * self.rated_power\n        # [timestamp, alarm, wind speed, reference power, temperature, power]\n        pow_alarms = self.power_alarms(data, power_curve, False) # do time filtering only once\n        for index, line in enumerate(pow_alarms):\n            # if (line[1] == 1) and (line[5] <= stop_limit) and (line[3] >= stop_limit):\n            #     line[1] = 2.0\n            if line[1] == 1:\n            # change this to look forward so tha tif the turbine will stop within a window of mark also the points where we\n            # are above the stop limit to belonging into the stop\n                stops = 0\n                for i in range(index, min(len(pow_alarms), index+self.stop_time)):\n                    templine = pow_alarms[i, :]\n                    if (templine[5] <= stop_limit) and (templine[3] >= stop_limit):\n                        stops += 1\n                if stops > 0:\n                    line[1] = 2.0\n                else:\n                    line[1] = 0\n            else:\n                line[1] = 0\n            filtered_data.append(line)\n\n        time_filtered_data = self.timefilter_ice_alarms(np.array(filtered_data), self.stop_time)\n        return time_filtered_data\n\n    def status_code_stops(self, data, power_curves, filter_type=\"stop\"):\n        \"\"\"\n        Flag the moments in data where the turbine status code indicates icing\n        The statuscode is defined in self.stopcodes\n\n        :param data: input data to be processed\n        :return [timestamp, alarm, wind speed, reference power, temperature, power, limit]:\n        \"\"\"\n        output = []\n        for line in data:\n            flag = False\n            # for item in self.ice_stop_index:\n            #     if line[item] in self.stopcodes:\n            #         flag = True\n            if filter_type == 'stop':\n                # if (self.stop_filter_type == 2 and line[self.status_stop_index] not in self.stopcodes) or \\\n                #         (self.stop_filter_type == 1 and line[self.status_stop_index] in self.stopcodes):\n                #     flag = True\n                if self.stop_filter_type == 2:\n                    flag = any([line[i] not in self.stopcodes for i in self.status_stop_index])\n                elif self.stop_filter_type == 1:\n                    flag = any([line[i] in self.stopcodes for i in self.status_stop_index])\n                else:\n                    pass\n            elif filter_type == 'ips':\n                # if (self.heating_status_type == 2 and line[self.heating_status_index] != self.heating_status_value) or \\\n                #         (self.heating_status_type == 1 and line[self.heating_status_index] == self.heating_status_value):\n                #     flag=True\n                if self.heating_status_type == 2:\n                    flag = any([line[i] not in self.heating_status_value for i in self.heating_status_index])\n                elif self.heating_status_type == 1:\n                    flag = any([line[i] in self.heating_status_value for i in self.heating_status_index])\n                else:\n                    pass\n            elif filter_type == 'icing':\n                if line[self.ice_alarm_index] == self.ice_alarm_value:\n                    flag = True\n            output_line =[]\n            output_line.append(line[self.ts_index]) # 0\n            if flag:\n                if filter_type == 'stop':\n                    output_line.append(4.0)\n                elif filter_type == 'ips':\n                    output_line.append(5.0)\n                elif filter_type == 'icing':\n                    output_line.append(6.0)\n            else:\n                output_line.append(0.0) # 1\n            output_line.append(line[self.ws_index]) # 2\n            # pick index of active direction bin\n            dirbin = np.argmin(np.abs(line[self.wd_index] - self.direction_bins))\n            int_lim = np.interp(line[self.ws_index], power_curves[:, dirbin, 0], power_curves[:, dirbin, 3])\n            int_pow = np.interp(line[self.ws_index], power_curves[:, dirbin, 0], power_curves[:, dirbin, 2])\n            output_line.append(int_pow) # 3\n            output_line.append(line[self.temp_index]) # 4\n            output_line.append(line[self.pow_index]) # 5\n            output_line.append(int_lim) # 6\n            if filter_type == 'ips':\n                if self.heating_power_index < 0:\n                    output_line.append(0.0)\n                else:\n                    output_line.append(line[self.heating_power_index]) # 7\n            output.append(output_line)\n        return np.array(output)\n\n    def combine_timeseries(self, pow_alms1,stops,pow_alms2):\n        \"\"\"\n        combine all different types of alarms into one big timeseries\n\n        Timeseries file combines the alarm files into one timeseries that classifies the ice cases according ot the naming convention in the documentation\n\n        1 = power loss\n        2 = stop\n        3 = overproduction\n\n        :param pow_alms1:\n        :param stops:\n        :param pow_alms2:\n        :return:\n        \"\"\"\n\n        # stops timeseries longer because it uses different source data\n\n        common_indexes1 = [index1 for index1, line1 in enumerate(stops) if line1[0] in pow_alms1[:,0]]\n        common_indexes2 = [index2 for index2, line2 in enumerate(stops) if line2[0] in pow_alms2[:,0]]\n        combined_ts = stops\n        combined_ts[common_indexes1,1] += pow_alms1[:,1]\n        combined_ts[common_indexes2,1] += pow_alms2[:,1]\n        return combined_ts\n\n\n    def define_removable_indexes(self,data,timings):\n        \"\"\"\n        calculate the start and stop indexes in data to remove all data defined in the array timings\n\n        :param data: original dataset\n        :param timings: array containg the incident starts and stops\n        :return: indexes that can be used to filter the original data, a list of ranges\n        \"\"\"\n        removed_indexes = []\n        for event in timings:\n            event_start = event[0]\n            event_stop = event[1]\n            event_start_index = np.fromiter(map(datetime.timedelta.total_seconds,np.abs(data[:,self.ts_index]-event_start)),dtype='float').argmin()\n            event_stop_index = np.fromiter(map(datetime.timedelta.total_seconds,np.abs(data[:,self.ts_index]-event_stop)),dtype='float').argmin()\n            removed_indexes.extend(list(range(event_start_index,event_stop_index,1)))\n        return removed_indexes\n\n    def increase_reference_dataset(self, data, stop_timings, alarm_timings, over_timings):\n        \"\"\"\n        re-increase the size of reference dataset to include all the non-iced datapoints.\n\n        :param data: original dataset\n        :param stop_timings: stops calculated from the data\n        :param alarm_timings: alarm incidents calculated from the data\n        :param over_timigns: overproduction incidents from the data\n        :return: new reference dataset\n        \"\"\"\n        stop_removal = self.define_removable_indexes(data,stop_timings)\n        alarm_removal = self.define_removable_indexes(data,alarm_timings)\n        over_removal = self.define_removable_indexes(data,over_timings)\n        removed_indexes = [*stop_removal,*alarm_removal,*over_removal]\n        new_ref = []\n        for index,line in enumerate(data):\n            if index not in removed_indexes:\n                new_ref.append(line)\n        return np.array(new_ref)\n\n\n\n    def one_year_month_sums(self, data, wanted_year, index):\n        \"\"\"\n        Helper function, calculates the monthly sums of any timeseries data  for a given year\n        :param data:\n        :param wanted_year:\n        :param index:\n        :return:\n        \"\"\"\n        months = np.arange(1, 13)\n        monthly_sums = np.zeros(12)\n        for line in data:\n            if line[0].year == wanted_year:\n                monthly_sums[line[0].month-1] += line[index]\n        dated_sums = []\n        for i, s in enumerate(monthly_sums):\n            dated_sums.append((datetime.datetime(wanted_year, months[i], 1), s))\n        return np.array(dated_sums)\n\n\n    def calculate_production_stats(self, data, pc, ice_alarms, ice_stops, status_stops, ips_on, ice_detection):\n        \"\"\"\n        Calculates month-by-month statistics from the data.\n\n        :param data: input data used to asses production\n        :param pc: power curve used to calculate theoretical production\n        :param ice_alarms: time series of icing alarms\n        :param ice_stops: time series of icing induced stops\n        :param status_stops: time series of stops as indicated by a statuscode in the scada\n        :param ips_on: toggle if IPS is available or not\n        :param ice_detection: timeseries of icing events as detected by an ice detector\n        :return:\n        \"\"\"\n\n        power_reference = self.theoretical_output_power(data,pc)\n        theoretical_production = self.calculate_production(power_reference,1)\n        actual_production = self.calculate_production(power_reference,2)\n        #pow_alarms.append((line[0], pow_alrm, line[self.ws_index], int_pow, line[self.temp_index], line[self.pow_index], int_lim))\n        iced_power_drop_events = ice_alarms[ice_alarms[:,1] == 1.0, :]\n        # iced_power_drops = np.hstack((iced_power_drop_events[:,0], iced_power_drop_events[:,3]-iced_power_drop_events[:,5]))\n        iced_power_drops_power = np.c_[iced_power_drop_events[:,0], iced_power_drop_events[:,3]-iced_power_drop_events[:,5]]\n        iced_power_drops = self.calculate_production(iced_power_drops_power,1)\n        ice_stop_events = ice_stops[ice_stops[:,1] == 2.0]\n        # iced_stops = np.hstack((ice_stop_events[:,0], ice_stop_events[:,3]-ice_stop_events[:,5]))\n        iced_stops_power = np.c_[ice_stop_events[:,0], ice_stop_events[:,3]-ice_stop_events[:,5]]\n        iced_stops = self.calculate_production(iced_stops_power,1)\n        # status\n        if status_stops is not None:\n            status_stop_events = status_stops[status_stops[:, 1] == 4.0]\n            # iced_stops = np.hstack((ice_stop_events[:,0], ice_stop_events[:,3]-ice_stop_events[:,5]))\n            status_stops_power = np.c_[status_stop_events[:,0], status_stop_events[:,3]-status_stop_events[:,5]]\n            status_stops_prod = self.calculate_production(status_stops_power,1)\n        else:\n            status_stop_events = None\n            status_stops_power = None\n            status_stops_prod = None\n\n        ##############\n        # IPS section\n        ##############\n        if ips_on is not None: # If there is no icing section IPS statistics are not calculated\n            ips_stop_events = ips_on[ips_on[:, 1] == 5.0]\n            # iced_stops = np.hstack((ice_stop_events[:,0], ice_stop_events[:,3]-ice_stop_events[:,5]))\n            ips_on_power = np.c_[ips_stop_events[:,0], ips_stop_events[:,3]-ips_stop_events[:,5]]\n            ips_on_prod = self.calculate_production(ips_on_power,1)\n            ice_detection_events = ice_detection[ice_detection[:, 1] == 6.0]\n\n            #ips consumption\n            if self.heating_power_index < 0:\n                ips_self_consumption = 0.0\n            else:\n                ips_self_consumption = self.calculate_production(data,self.heating_power_index)\n\n            # iced_stops = np.hstack((ice_stop_events[:,0], ice_stop_events[:,3]-ice_stop_events[:,5]))\n            ice_detection_power = np.c_[ice_detection_events[:, 0], ice_detection_events[:, 3] - ice_detection_events[:, 5]]\n            ice_detection_prod = self.calculate_production(ice_detection_power, 1)\n\n        # print(iced_power_drops)\n        years = set([point[0].year for point in data])\n        production_statistics = []\n        for year in years:\n            theoretical_production_sums = self.one_year_month_sums(theoretical_production,year,1)\n            actual_production_sums = self.one_year_month_sums(actual_production,year,1)\n            iced_power_sums = self.one_year_month_sums(iced_power_drops,year,1)\n            ice_stop_sums = self.one_year_month_sums(iced_stops,year,1)\n            if status_stops is not None:\n                status_stop_sums = self.one_year_month_sums(status_stops_prod,year,1)\n            else:\n                status_stop_sums = np.copy(theoretical_production_sums)\n                status_stop_sums[:, 1] = 0.0\n\n            if ips_on is not None:\n                ips_on_sums = self.one_year_month_sums(ips_on_prod,year,1)\n                ice_detection_sums = self.one_year_month_sums(ice_detection_prod, year,1)\n            else:\n                print(\"Dummy IPS Values\")\n                ips_on_sums = np.copy(theoretical_production_sums)\n                ips_on_sums[:,1] = 0.0\n                ice_detection_sums = ips_on_sums\n                ips_self_consumption = 0.0\n            for index, stat_month in enumerate(theoretical_production_sums):\n                # if theoretical_production_sums[index,0] == actual_production_sums[index,0]:\n                ice_loss = iced_power_sums[index,1] + ice_stop_sums[index,1] + ips_on_sums[index,1] + ice_detection_sums[index,1]\n                if theoretical_production_sums[index,1] == 0.0:\n                    reldiff = 0.0\n                    total_icediff = 0.0\n                    icediff = 0.0\n                    stopdiff = 0.0\n                    statusdiff = 0.0\n                    ipsdiff = 0.0\n                    iddiff = 0.0\n                else:\n                    reldiff = (theoretical_production_sums[index, 1] - actual_production_sums[index,1])/theoretical_production_sums[index, 1]\n                    icediff = (theoretical_production_sums[index, 1] - iced_power_sums[index,1])/theoretical_production_sums[index, 1]\n                    stopdiff = (theoretical_production_sums[index, 1] - ice_stop_sums[index,1])/theoretical_production_sums[index, 1]\n                    statusdiff = (theoretical_production_sums[index, 1] - status_stop_sums[index,1])/theoretical_production_sums[index, 1]\n                    ipsdiff = (theoretical_production_sums[index, 1] - ips_on_sums[index,1])/theoretical_production_sums[index, 1]\n                    iddiff = (theoretical_production_sums[index, 1] - ice_detection_sums[index,1])/theoretical_production_sums[index, 1]\n                    total_icediff = (theoretical_production_sums[index, 1] - ice_loss)/theoretical_production_sums[index, 1]\n                production_statistics.append(\n                    [theoretical_production_sums[index, 0], theoretical_production_sums[index, 1],\n                     actual_production_sums[index, 1],\n                     theoretical_production_sums[index, 1] - actual_production_sums[index, 1], reldiff,\n                     iced_power_sums[index, 1], icediff, ice_stop_sums[index, 1], stopdiff, status_stop_sums[index, 1],\n                     statusdiff, ips_on_sums[index,1], ipsdiff, ice_detection_sums[index, 1], iddiff,ice_loss, total_icediff, ips_self_consumption])\n        return np.array(production_statistics)\n\n", "meta": {"hexsha": "f4a9ed24453fb2cd1217585c105fb07b7be5adf8", "size": 74414, "ext": "py", "lang": "Python", "max_stars_repo_path": "t19_ice_loss/aep_counter.py", "max_stars_repo_name": "IEAWind-Task19/IceLossMethod", "max_stars_repo_head_hexsha": "c7f3c1230952e0b017ca571b03e51b68eb0a4806", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2019-12-07T14:56:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T08:42:06.000Z", "max_issues_repo_path": "t19_ice_loss/aep_counter.py", "max_issues_repo_name": "IEAWind-Task19/IceLossMethod", "max_issues_repo_head_hexsha": "c7f3c1230952e0b017ca571b03e51b68eb0a4806", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-03-23T19:29:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-25T07:50:51.000Z", "max_forks_repo_path": "t19_ice_loss/aep_counter.py", "max_forks_repo_name": "IEAWind-Task19/IceLossMethod", "max_forks_repo_head_hexsha": "c7f3c1230952e0b017ca571b03e51b68eb0a4806", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-11-22T04:06:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-04T09:04:11.000Z", "avg_line_length": 51.6763888889, "max_line_length": 179, "alphanum_fraction": 0.6120353697, "include": true, "reason": "import numpy,import scipy", "num_tokens": 16198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.3208213008246071, "lm_q1q2_score": 0.19014006955256169}}
{"text": "#! /usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\n\"\"\" \n    TO DO:\n    - flagging (en freq et temps)\n    - averaging (en temps et freq)\n    - split crosscorr matrix between cross and auto --> just a mask ?\n\"\"\"\n\n\n__author__ = 'Alan Loh, Julien Girard'\n__copyright__ = 'Copyright 2019, nenupytv'\n__credits__ = ['Alan Loh', 'Julien Girard']\n__maintainer__ = 'Alan'\n__email__ = 'alan.loh@obspm.fr'\n__status__ = 'Production'\n__all__ = [\n    'Crosslets'\n    ]\n\n\nimport numpy as np\nfrom os.path import abspath, isfile\nfrom itertools import islice\nfrom astropy.time import Time\n\n\n# ============================================================= #\n# ------------------------ Crosslets -------------------------- #\n# ============================================================= #\nclass Crosslets(object):\n    \"\"\"\n    \"\"\"\n\n    def __init__(self, xst_bin):\n        self.meta = {}\n        self.data = None\n        self.time = None\n        self.xst_bin = xst_bin\n\n\n    # --------------------------------------------------------- #\n    # --------------------- Getter/Setter --------------------- #\n    @property\n    def x_vis(self):\n        # x, y = np.tril_indices(self.meta['ma'].size, 0)\n        # xx = np.hstack((x[x!=y], y[x!=y]))\n        # yy = np.hstack((y[x!=y], x[x!=y]))\n        # return v[:, :, xx, yy, ...] + v[:, :, yy, xx, ...].conj()\n        self.data\n\n\n    @property\n    def xst_bin(self):\n        \"\"\" NenuFAR TV XST snapshot binary file\n        \"\"\"\n        return self._xst_bin\n    @xst_bin.setter\n    def xst_bin(self, x):\n        if not isinstance(x, str):\n            raise TypeError(\n                'String expected.'\n                )\n        x = abspath(x)\n        if not isfile(x):\n            raise FileNotFoundError(\n                'Unable to find {}'.format(x)\n                )\n        self._xst_bin = x\n        self._load()\n    \n\n    # --------------------------------------------------------- #\n    # ------------------------ Methods ------------------------ #\n    def cross_corr(self, vis=None, polar='xx'):\n        \"\"\" Given XST visibilities, returns the cross-correlation\n            matrix\n\n            Parameters\n            ----------\n            vis : `np.ndarray`\n                Array of visibilities (n_baselines * pol)\n                This can be `self.data[time_i, freq_j, :]`\n            polar : str\n                Polarization requested\n\n            Returns\n            -------\n            cross_correlation : `np.ndarray`\n                Matrix of cross-correlations (n_ant, n_ant)\n        \"\"\"\n        if vis is None:\n            vis = self.data[0, 0, :] # time, freq, vis\n\n        n_ma = self.meta['ma'].size\n        mat_size = n_ma*2\n        \n        mat_tot = np.zeros(\n            (mat_size, mat_size),\n            dtype='complex64'\n            )\n        mat_pol = np.zeros(\n            (n_ma, n_ma),\n            dtype='complex64'\n            )\n        \n        indices = np.tril_indices(mat_size, 0)\n        pol_idx = np.tril_indices(n_ma, 0)\n        diag_idx = np.arange(mat_size-1)\n\n        mat_tot[indices] = vis\n\n        # Reconstruct missing XY\n        mat_tot[diag_idx, diag_idx+1] = mat_tot[diag_idx+1, diag_idx].conj()\n\n        if polar.lower() == 'xx':\n            xx_idx = tuple([\n                pol_idx[0]*2,\n                pol_idx[1]*2\n                ])\n            # mat = mat_tot[::2, ::2]\n            selected_pol = mat_tot[xx_idx]\n        elif polar.lower() == 'xy':\n            xy_idx = tuple([\n                pol_idx[0]*2,\n                pol_idx[1]*2 + 1\n                ])\n            # mat = mat_tot[::2, 1::2]\n            selected_pol = mat_tot[xy_idx]\n        elif polar.lower() == 'yx':\n            yx_idx = tuple([\n                pol_idx[0]*2 + 1,\n                pol_idx[1]*2\n                ])\n            # mat = mat_tot[1::2, ::2]\n            selected_pol = mat_tot[yx_idx]\n        elif polar.lower() == 'yy':\n            yy_idx = tuple([\n                pol_idx[0]*2 + 1,\n                pol_idx[1]*2 + 1\n                ])\n            # mat = mat_tot[1::2, 1::2]\n            selected_pol = mat_tot[yy_idx]\n        else:\n            raise ValueError(\n                'Polarization not understood.'\n                )\n\n        mat_pol[pol_idx] = selected_pol\n\n        return mat_pol\n\n\n    def gen_cross(self, freq=None, polar='xx'):\n        \"\"\" Generator of correlation matrices for each time\n            at a particular frequency.\n        \"\"\"\n        if freq is not None:\n            sb_idx = np.argmin(np.abs(freq - self.meta['freq']))\n        else:\n            sb_idx = np.arange(self.meta['freq'].size)\n        \n        for it in range(self.time.size):\n            matrix = self.cross_corr(\n                vis=self.data[it, sb_idx, :],\n                polar=polar\n                )\n\n            yield matrix\n\n\n    def reshape(self, tidx=None, fmean=True, tmean=True):\n        \"\"\" Reshape the data to match the UVW array\n        \"\"\"\n        if tidx is not None:\n            raise Exception(\n                'tidx not suited for NenuFAR-TV data'\n            )\n        data = np.zeros(\n            (\n                self.time.size,\n                self.meta['freq'].size,\n                self.meta['ma'].size,\n                self.meta['ma'].size,\n                4\n            ),\n            dtype='complex64'\n        )\n        for i_p, pol in enumerate(['xx', 'xy', 'yx', 'yy']):\n            for i_f, freq in enumerate(self.meta['freq']):\n                i_t = 0\n                for data_block in self.gen_cross(freq=freq, polar=pol):\n                    data[i_t, i_f, ..., i_p] = data_block\n                    i_t += 1\n\n        if fmean:\n            data = np.expand_dims(\n                np.mean(data, axis=1),\n                axis=1\n                )\n        if tmean:\n            data = np.expand_dims(\n                np.mean(data, axis=0),\n                axis=0\n            )\n        return data\n\n\n    # --------------------------------------------------------- #\n    # ----------------------- Internal ------------------------ #\n    def _load(self):\n        \"\"\" Read the binary file\n        \"\"\"\n        # Extract the ASCII header (5 first lines)\n        with open(self._xst_bin, 'rb') as f:\n            header = list(islice(f, 0, 5))\n        assert header[0] == b'HeaderStart\\n',\\\n            'Wrong header start'\n        assert header[-1] == b'HeaderStop\\n',\\\n            'Wrong header stop'\n        header = [s.decode('utf-8') for s in header]\n        hd_size = sum([len(s) for s in header])\n\n        # Parse informations into a metadata dictionnary\n        keys = ['freq', 'ma', 'accu']\n        search = ['Freq.List', 'Mr.List', 'accumulation']\n        types = ['float64', 'int', 'int']\n        for key, word, typ in zip(keys, search, types):\n            for h in header:\n                if word in h:\n                    self.meta[key] = np.array(\n                        h.split('=')[1].split(','),\n                        dtype=typ\n                        )\n\n        # Deduce the dtype for decoding\n        n_ma = self.meta['ma'].size\n        n_sb = self.meta['freq'].size\n        dtype = np.dtype(\n            [('jd', 'float64'),\n            ('data', 'complex64', (n_sb, n_ma*n_ma*2 + n_ma))]\n            )\n\n        # Decoding the binary file\n        tmp = np.memmap(\n            filename=self._xst_bin,\n            dtype='int8',\n            mode='r',\n            offset=hd_size\n            )\n        decoded = tmp.view(dtype)\n\n        self.data = decoded['data'] / self.meta['accu']\n        self.time = Time(decoded['jd'], format='jd', precision=0)\n\n        return\n# ============================================================= #\n\n", "meta": {"hexsha": "ea3ffc9e4b1bb31d297b7163ed912715dec575b2", "size": 7620, "ext": "py", "lang": "Python", "max_stars_repo_path": "nenupytv/read/crosslets.py", "max_stars_repo_name": "AlanLoh/nenupy-tv", "max_stars_repo_head_hexsha": "9c33652521293eaba726f02fdb2331ae32dda6f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nenupytv/read/crosslets.py", "max_issues_repo_name": "AlanLoh/nenupy-tv", "max_issues_repo_head_hexsha": "9c33652521293eaba726f02fdb2331ae32dda6f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2019-11-12T09:48:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-28T17:02:54.000Z", "max_forks_repo_path": "nenupytv/read/crosslets.py", "max_forks_repo_name": "AlanLoh/nenupy-tv", "max_forks_repo_head_hexsha": "9c33652521293eaba726f02fdb2331ae32dda6f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-09T17:40:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-09T17:40:58.000Z", "avg_line_length": 29.1954022989, "max_line_length": 76, "alphanum_fraction": 0.4307086614, "include": true, "reason": "import numpy,from astropy", "num_tokens": 1782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.19014006108751347}}
{"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb  7 16:55:54 2019\nModule for the SitePair class.\n@author: parrenif\n\"\"\"\n\nimport os\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as mpl\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom scipy.linalg import lu_factor, lu_solve\nfrom scipy.linalg import cholesky\nimport pccfg\n\nclass SitePair(object):\n    \"\"\"Class for a pair of sites.\"\"\"\n\n    def __init__(self, site1, site2):\n        self.site1 = site1\n        self.site2 = site2\n        self.label = self.site1.label+'-'+self.site2.label\n\n        self.age_age_label = self.site1.age_label+self.site2.age_label\n        if len(self.age_age_label)>0:\n            self.age_age_label = self.age_age_label + '_'\n        self.age_age2_label = self.site1.age_label+self.site2.age2_label + '_'\n        self.age2_age_label = self.site1.age2_label+self.site2.age_label + '_'\n        self.age2_age2_label = self.site1.age2_label+self.site2.age2_label + '_'\n        \n\n#TODO: allow to have either dlabel1+'-'dlabel2 or dlbel2+'-'dlabel1 as directory\n        filename = pccfg.datadir+self.site1.label+'-'+self.site2.label+\\\n            '/'+self.age_age_label+'synchro_horizons.txt'\n        if not os.path.isfile(filename):\n            filename = pccfg.datadir+self.site1.label+'-'+self.site2.label+'/ice_depth.txt'\n        if os.path.isfile(filename) and open(filename).read():\n            readarray = np.loadtxt(filename)\n            if np.size(readarray) == np.shape(readarray)[0]:\n                readarray.resize(1, np.size(readarray))\n            self.iceicehorizons_depth1 = readarray[:, 0]\n            self.iceicehorizons_depth2 = readarray[:, 1]\n            self.iceicehorizons_sigma = readarray[:, 2]\n        else:\n            self.iceicehorizons_depth1 = np.array([])\n            self.iceicehorizons_depth2 = np.array([])\n            self.iceicehorizons_sigma = np.array([])\n        self.iceicehorizons_correlation = np.diag(np.ones(np.size(self.iceicehorizons_depth1)))\n\n        if self.site1.archive == 'icecore' and self.site2.archive == 'icecore':\n            filename = pccfg.datadir+self.site1.label+'-'+self.site2.label+\\\n                       '/'+self.age2_age2_label+'synchro_horizons.txt'\n            if not os.path.isfile(filename):\n                filename = pccfg.datadir+self.site1.label+'-'+self.site2.label+'/air_depth.txt'\n            if os.path.isfile(filename) and open(filename).read():\n                readarray = np.loadtxt(filename)\n                if np.size(readarray) == np.shape(readarray)[0]:\n                    readarray.resize(1, np.size(readarray))\n                self.airairhorizons_depth1 = readarray[:, 0]\n                self.airairhorizons_depth2 = readarray[:, 1]\n                self.airairhorizons_sigma = readarray[:, 2]\n            else:\n                self.airairhorizons_depth1 = np.array([])\n                self.airairhorizons_depth2 = np.array([])\n                self.airairhorizons_sigma = np.array([])\n            self.airairhorizons_correlation = np.diag(np.ones(np.size(self.airairhorizons_depth1)))\n\n        if self.site2.archive == 'icecore':\n            filename = pccfg.datadir+self.site1.label+'-'+\\\n                            self.site2.label+'/'+self.age_age2_label+'synchro_horizons.txt'\n            if not os.path.isfile(filename):\n                filename = pccfg.datadir+self.site1.label+'-'+self.site2.label+'/iceair_depth.txt'\n            if os.path.isfile(filename) and open(filename).read():\n                readarray = np.loadtxt(filename)\n                if np.size(readarray) == np.shape(readarray)[0]:\n                    readarray.resize(1, np.size(readarray))\n                self.iceairhorizons_depth1 = readarray[:, 0]\n                self.iceairhorizons_depth2 = readarray[:, 1]\n                self.iceairhorizons_sigma = readarray[:, 2]\n            else:\n                self.iceairhorizons_depth1 = np.array([])\n                self.iceairhorizons_depth2 = np.array([])\n                self.iceairhorizons_sigma = np.array([])\n            self.iceairhorizons_correlation = np.diag(np.ones(np.size(self.iceairhorizons_depth1)))\n\n        if self.site1.archive == 'icecore':\n            filename = pccfg.datadir+self.site1.label+'-'+\\\n                        self.site2.label+'/'+self.age2_age_label+'synchro_horizons.txt'\n            if not os.path.isfile(filename):\n                filename = pccfg.datadir+self.site1.label+'-'+self.site2.label+'/airice_depth.txt'\n            if os.path.isfile(filename) and open(filename).read():\n                readarray = np.loadtxt(filename)\n                if np.size(readarray) == np.shape(readarray)[0]:\n                    readarray.resize(1, np.size(readarray))\n                self.airicehorizons_depth1 = readarray[:, 0]\n                self.airicehorizons_depth2 = readarray[:, 1]\n                self.airicehorizons_sigma = readarray[:, 2]\n            else:\n                self.airicehorizons_depth1 = np.array([])\n                self.airicehorizons_depth2 = np.array([])\n                self.airicehorizons_sigma = np.array([])\n            self.airicehorizons_correlation = np.diag(np.ones(np.size(self.airicehorizons_depth1)))\n\n\n        filename1 = pccfg.datadir+'/parameters_covariance_observations_all_site_pairs.py'\n        filename2 = pccfg.datadir+'/parameters-CovarianceObservations-AllDrillings.py'\n        if os.path.isfile(filename1):\n            exec(open(filename1).read())\n        elif os.path.isfile(filename2):\n            exec(open(filename2).read())\n        filename3 = pccfg.datadir+self.label+'/parameters_covariance_observations.py'\n        filename4 = pccfg.datadir+self.label+'/parameters-CovarianceObservations.py'\n        if os.path.isfile(filename3):\n            exec(open(filename3).read())\n        elif os.path.isfile(filename4):\n            exec(open(filename4).read())\n            \n        if ((os.path.isfile(filename1) or os.path.isfile(filename2) or os.path.isfile(filename3)\\\n            or os.path.isfile(filename4)) and (pccfg.jacobian=='analytical' or \\\n            pccfg.jacobian=='semi_adjoint' or pccfg.jacobian=='adjoint')):\n            print('Covariance on observations not implemented for analytical Jacobian. Exiting.')\n            sys.exit()\n            \n        if np.any(self.iceicehorizons_correlation != \\\n                  np.diag(np.ones(np.size(self.iceicehorizons_depth1)))):\n            self.iceicehorizons_correlation_bool = True\n            self.iceicehorizons_chol = cholesky(self.iceicehorizons_correlation)\n            self.iceicehorizons_lu_piv = lu_factor(self.iceicehorizons_chol)\n        else:\n            self.iceicehorizons_correlation_bool = False\n            \n        if self.site1.archive == 'icecore' and self.site2.archive == 'icecore':\n            if np.any(self.airairhorizons_correlation != \\\n                  np.diag(np.ones(np.size(self.airairhorizons_depth1)))):\n                self.airairhorizons_correlation_bool = True\n                self.airairhorizons_chol = cholesky(self.airairhorizons_correlation)\n                self.airairhorizons_lu_piv = lu_factor(self.airairhorizons_chol)\n            else:\n                self.airairhorizons_correlation_bool = False\n                \n        if self.site2.archive == 'icecore':\n            if np.any(self.iceairhorizons_correlation != \\\n                  np.diag(np.ones(np.size(self.iceairhorizons_depth1)))):\n                self.iceairhorizons_correlation_bool = True\n                self.iceairhorizons_chol = cholesky(self.iceairhorizons_correlation)\n                self.iceairhorizons_lu_piv = lu_factor(self.iceairhorizons_chol)\n            else:\n                self.iceairhorizons_correlation_bool = False\n                \n        if self.site1.archive == 'icecore':\n            if np.any(self.airicehorizons_correlation != \\\n                  np.diag(np.ones(np.size(self.airicehorizons_depth1)))):\n                self.airicehorizons_correlation_bool = True\n                self.airicehorizons_chol = cholesky(self.airicehorizons_correlation)\n                self.airicehorizons_lu_piv = lu_factor(self.airicehorizons_chol)\n            else:\n                self.airicehorizons_correlation_bool = False\n\n    def residuals(self):\n        \"\"\"Calculate the residual terms of a pair of sites.\"\"\"\n\n        if np.size(self.iceicehorizons_depth1) > 0:\n            resi_iceice = (self.site1.fct_age(self.iceicehorizons_depth1)-\\\n                           self.site2.fct_age(self.iceicehorizons_depth2))/self.iceicehorizons_sigma\n            if self.iceicehorizons_correlation_bool:\n                resi_iceice = lu_solve(self.iceicehorizons_lu_piv, resi_iceice)\n            resi = [resi_iceice]\n        else:\n            resi = [np.array([])]\n\n        if self.site1.archive == 'icecore' and self.site2.archive == 'icecore' and \\\n            np.size(self.airairhorizons_depth1) > 0:\n            resi_airair = (self.site1.fct_airage(self.airairhorizons_depth1)-\\\n                          self.site2.fct_airage(self.airairhorizons_depth2))/\\\n                          self.airairhorizons_sigma\n            if self.airairhorizons_correlation_bool:\n                resi_airair = lu_solve(self.airairhorizons_lu_piv, resi_airair)\n            resi.append(resi_airair)\n\n        if self.site2.archive == 'icecore' and np.size(self.iceairhorizons_depth1) > 0:\n            resi_iceair = (self.site1.fct_age(self.iceairhorizons_depth1)-\\\n                          self.site2.fct_airage(self.iceairhorizons_depth2))/\\\n                          self.iceairhorizons_sigma\n            if self.iceairhorizons_correlation_bool:\n                resi_iceair = lu_solve(self.iceairhorizons_lu_piv, resi_iceair)\n            resi.append(resi_iceair)\n\n        if self.site1.archive == 'icecore' and np.size(self.airicehorizons_depth1) > 0:\n            resi_airice = (self.site1.fct_airage(self.airicehorizons_depth1)-\\\n                           self.site2.fct_age(self.airicehorizons_depth2))/self.airicehorizons_sigma\n            if self.airicehorizons_correlation_bool:\n                resi_airice = lu_solve(self.airicehorizons_lu_piv, resi_airice)\n            resi.append(resi_airice)\n\n        return np.concatenate(resi)\n\n\n    def residuals_jacobian1(self):\n#        if np.size(self.iceicehorizons_depth1) > 0:\n#            print(np.shape(self.site1.fct_age_jac(self.iceicehorizons_depth1)),\n#                  np.shape(self.site2.fct_age(self.iceicehorizons_depth2)),\n#                  np.shape(self.iceicehorizons_sigma)\n        resi_iceice = self.site1.fct_age_jac(self.iceicehorizons_depth1)/self.iceicehorizons_sigma\n        resi = [resi_iceice]\n        if self.site1.archive == 'icecore' and self.site2.archive == 'icecore':\n            resi_airair = self.site1.fct_airage_jac(self.airairhorizons_depth1)/\\\n                            self.airairhorizons_sigma\n            resi.append(resi_airair)\n        if self.site2.archive == 'icecore':\n            resi_iceair = self.site1.fct_age_jac(self.iceairhorizons_depth1)/\\\n                            self.iceairhorizons_sigma\n            resi.append(resi_iceair)\n        if self.site1.archive == 'icecore':\n            resi_airice = self.site1.fct_airage_jac(self.airicehorizons_depth1)/\\\n                            self.airicehorizons_sigma\n            resi.append(resi_airice)\n#       else:\n#            resi = [np.array([])]\n        return np.concatenate(resi, axis=1)\n\n    def residuals_jacobian2(self):\n#        if np.size(self.iceicehorizons_depth1) > 0:\n        resi_iceice = -self.site2.fct_age_jac(self.iceicehorizons_depth2)/self.iceicehorizons_sigma\n        resi = [resi_iceice]\n        if self.site1.archive == 'icecore' and self.site2.archive == 'icecore':\n            resi_airair = -self.site2.fct_airage_jac(self.airairhorizons_depth2)/\\\n                            self.airairhorizons_sigma\n            resi.append(resi_airair)\n        if self.site2.archive == 'icecore':\n            resi_iceair = -self.site2.fct_airage_jac(self.iceairhorizons_depth2)/\\\n                            self.iceairhorizons_sigma\n            resi.append(resi_iceair)\n        if self.site1.archive == 'icecore':\n            resi_airice = -self.site2.fct_age_jac(self.airicehorizons_depth2)/\\\n                            self.airicehorizons_sigma\n            resi.append(resi_airice)\n#        else:\n#            resi = [np.array([])]\n        return np.concatenate(resi, axis=1)\n\n    def residuals_delta(self):\n        resi_iceice = (self.site1.fct_age_delta(self.iceicehorizons_depth1)-\\\n            self.site2.fct_age_delta(self.iceicehorizons_depth2))/self.iceicehorizons_sigma\n        return resi_iceice\n\n    def figures(self):\n        \n        \"\"\"Build the figures related to a pair of sites.\"\"\"\n        if np.size(self.iceicehorizons_depth1)>0:\n            fig, ax = mpl.subplots()\n            mpl.xlabel(self.site1.label+' '+self.site1.age_labelsp+'age ('+pccfg.age_unit+' '+pccfg.age_unit_ref+')')\n            mpl.ylabel(self.site2.label+' '+self.site2.age_labelsp+'age ('+pccfg.age_unit+' '+pccfg.age_unit_ref+')')\n            if np.size(self.iceicehorizons_depth1) > 0:\n                if pccfg.show_initial:\n                    mpl.plot(self.site1.fct_age_init(self.iceicehorizons_depth1),\n                                 self.site2.fct_age_init(self.iceicehorizons_depth2),\n                                 color=pccfg.color_init, linestyle='', marker='o', markersize=2,\n                                 label=\"Initial\")\n                mpl.plot(self.site1.fct_age_model(self.iceicehorizons_depth1),\n                             self.site2.fct_age_model(self.iceicehorizons_depth2),\n                             color=pccfg.color_mod, linestyle='', marker='o', markersize=2,\n                             label=\"Prior\")\n                mpl.errorbar(self.site1.fct_age(self.iceicehorizons_depth1),\n                             self.site2.fct_age(self.iceicehorizons_depth2), color=pccfg.color_opt,\n                             ecolor=pccfg.color_ci,\n                             xerr=np.zeros(np.size(self.iceicehorizons_depth1)),\n                             linestyle='', marker='o', markersize=2,\n                             label=\"Posterior $\\pm\\sigma$\")\n                xstart = self.site1.fct_age(self.iceicehorizons_depth1)-self.iceicehorizons_sigma/2\n                ystart = self.site2.fct_age(self.iceicehorizons_depth2)+self.iceicehorizons_sigma/2\n                for i in range(np.size(self.iceicehorizons_depth1)):\n                    mpl.arrow(xstart[i], ystart[i], self.iceicehorizons_sigma[i],\n                              -self.iceicehorizons_sigma[i], color=pccfg.color_ci,\n                              width=0.0, head_length=0.0, head_width=0.0)\n            x_low, x_up, y_low, y_up = mpl.axis()\n#            x_low = self.site1.age_top\n#            y_low = self.site2.age_top\n#            mpl.axis((x_low, x_up, y_low, y_up))\n            rangefig = np.array([min(x_low, y_low), max(x_up, y_up)])\n            mpl.plot(rangefig, rangefig, color=pccfg.color_obs, label='Perfect agreement', zorder=0)\n            mpl.legend(loc=\"best\")\n            ax.set_aspect('equal')\n            printed_page = PdfPages(pccfg.datadir+self.label+'/'+self.age_age_label+'synchro.pdf')\n            printed_page.savefig(fig)\n            printed_page.close()\n            if not pccfg.show_figures:\n                mpl.close()\n\n        if self.site1.archive == 'icecore' and self.site2.archive == 'icecore':\n            if np.size(self.airairhorizons_depth1)>0:\n                fig, ax = mpl.subplots()\n                mpl.xlabel(self.site1.label+' '+self.site1.age2_labelsp+'age ('+pccfg.age_unit+' '+\n                           pccfg.age_unit_ref+')')\n                mpl.ylabel(self.site2.label+' '+self.site2.age2_labelsp+'age ('+pccfg.age_unit+' '+\n                           pccfg.age_unit_ref+')')\n                if np.size(self.airairhorizons_depth1) > 0:\n                    if pccfg.show_initial:\n                        mpl.plot(self.site1.fct_airage_init(self.airairhorizons_depth1),\n                                     self.site2.fct_airage_init(self.airairhorizons_depth2),\n                                     color=pccfg.color_init,\n                                     linestyle='',\n                                     marker='o', markersize=2, label=\"Initial\")\n                    mpl.plot(self.site1.fct_airage_model(self.airairhorizons_depth1),\n                                 self.site2.fct_airage_model(self.airairhorizons_depth2),\n                                 color=pccfg.color_mod,\n                                 linestyle='', marker='o', markersize=2,\n                                 label=\"Prior\")\n                    mpl.errorbar(self.site1.fct_airage(self.airairhorizons_depth1),\n                                 self.site2.fct_airage(self.airairhorizons_depth2),\n                                 color=pccfg.color_opt, ecolor=pccfg.color_ci,\n                                 xerr=np.zeros_like(self.airairhorizons_sigma),\n                                 linestyle='', marker='o', markersize=2,\n                                 label=\"Posterior $\\pm\\sigma$\")\n                    xstart = self.site1.fct_airage(self.airairhorizons_depth1)-\\\n                                 self.airairhorizons_sigma/2\n                    ystart = self.site2.fct_airage(self.airairhorizons_depth2)+\\\n                                 self.airairhorizons_sigma/2\n                    for i in range(np.size(self.airairhorizons_depth1)):\n                        mpl.arrow(xstart[i], ystart[i], self.airairhorizons_sigma[i],\n                                  -self.airairhorizons_sigma[i], color=pccfg.color_ci,\n                                  width=0.0, head_length=0.0, head_width=0.0)\n                x_low, x_up, y_low, y_up = mpl.axis()\n#                x_low = self.site1.age_top\n#                y_low = self.site2.age_top\n#                mpl.axis((x_low, x_up, y_low, y_up))\n                rangefig = np.array([min(x_low, y_low), max(x_up, y_up)])\n                mpl.plot(rangefig, rangefig, color=pccfg.color_obs, label='Perfect agreement',\n                         zorder=0)\n                mpl.legend(loc=\"best\")\n                ax.set_aspect('equal')\n                printed_page = PdfPages(pccfg.datadir+self.label+'/'+self.age2_age2_label+\n                                        'synchro.pdf')\n                printed_page.savefig(fig)\n                printed_page.close()\n                if not pccfg.show_figures:\n                    mpl.close()\n\n        if self.site2.archive == 'icecore':\n            if np.size(self.iceairhorizons_depth1)>0:\n                fig, ax = mpl.subplots()\n                mpl.xlabel(self.site1.label+' '+self.site1.age_labelsp+'age ('+pccfg.age_unit+' '+\n                           pccfg.age_unit_ref+')')\n                mpl.ylabel(self.site2.label+' '+self.site2.age2_labelsp+'age ('+pccfg.age_unit+' '+\n                           pccfg.age_unit_ref+')')\n                if np.size(self.iceairhorizons_depth1) > 0:\n                    if pccfg.show_initial:\n                        mpl.plot(self.site1.fct_age_init(self.iceairhorizons_depth1),\n                                     self.site2.fct_airage_init(self.iceairhorizons_depth2),\n                                     color=pccfg.color_init,\n                                     linestyle='',\n                                     marker='o', markersize=2, label=\"Initial\")\n                    mpl.plot(self.site1.fct_age_model(self.iceairhorizons_depth1),\n                                 self.site2.fct_airage_model(self.iceairhorizons_depth2),\n                                 color=pccfg.color_mod,\n                                 linestyle='', marker='o', markersize=2,\n                                 label=\"Prior\")\n                    mpl.errorbar(self.site1.fct_age(self.iceairhorizons_depth1),\n                                 self.site2.fct_airage(self.iceairhorizons_depth2),\n                                 color=pccfg.color_opt, ecolor=pccfg.color_ci,\n                                 xerr=np.zeros_like(self.iceairhorizons_sigma),\n                                 linestyle='', marker='o', markersize=2,\n                                 label=\"Posterior $\\pm\\sigma$\")\n                    xstart = self.site1.fct_age(self.iceairhorizons_depth1)-\\\n                                 self.iceairhorizons_sigma/2\n                    ystart = self.site2.fct_airage(self.iceairhorizons_depth2)+\\\n                                 self.iceairhorizons_sigma/2\n                    for i in range(np.size(self.iceairhorizons_depth1)):\n                        mpl.arrow(xstart[i], ystart[i], self.iceairhorizons_sigma[i],\n                                  -self.iceairhorizons_sigma[i], color=pccfg.color_ci,\n                                  width=0.0, head_length=0.0, head_width=0.0)                    \n                x_low, x_up, y_low, y_up = mpl.axis()\n#                x_low = self.site1.age_top\n#                y_low = self.site2.age_top\n#                mpl.axis((x_low, x_up, y_low, y_up))\n                rangefig = np.array([min(x_low, y_low), max(x_up, y_up)])\n                mpl.plot(rangefig, rangefig, color=pccfg.color_obs, label='Perfect agreement',\n                         zorder=0)\n                mpl.legend(loc=\"best\")\n                ax.set_aspect('equal')\n                printed_page = PdfPages(pccfg.datadir+self.label+'/'+self.age_age2_label+\n                                        'synchro.pdf')\n                printed_page.savefig(fig)\n                printed_page.close()\n                if not pccfg.show_figures:\n                    mpl.close()\n\n        if self.site1.archive == 'icecore':\n            if np.size(self.airicehorizons_depth1)>0:\n                fig, ax = mpl.subplots()\n                mpl.xlabel(self.site1.label+' '+self.site1.age2_labelsp+'age ('+pccfg.age_unit+' '+\n                           pccfg.age_unit_ref+')')\n                mpl.ylabel(self.site2.label+' '+self.site2.age_labelsp+'age ('+pccfg.age_unit+' '+\n                           pccfg.age_unit_ref+')')\n                if np.size(self.airicehorizons_depth1) > 0:\n                    if pccfg.show_initial:\n                        mpl.plot(self.site1.fct_airage_init(self.airicehorizons_depth1),\n                                     self.site2.fct_age_init(self.airicehorizons_depth2),\n                                     color=pccfg.color_init,\n                                     linestyle='', marker='o', markersize=2, label=\"Initial\")\n                    mpl.plot(self.site1.fct_airage_model(self.airicehorizons_depth1),\n                                 self.site2.fct_age_model(self.airicehorizons_depth2),\n                                 color=pccfg.color_mod,\n                                 linestyle='', marker='o', markersize=2,\n                                 label=\"Prior\")\n                    mpl.errorbar(self.site1.fct_airage(self.airicehorizons_depth1),\n                                 self.site2.fct_age(self.airicehorizons_depth2),\n                                 color=pccfg.color_opt, ecolor=pccfg.color_ci,\n                                 xerr=np.zeros_like(self.airicehorizons_sigma),\n                                 linestyle='', marker='o', markersize=2,\n                                 label=\"Posterior $\\pm\\sigma$\")\n                    xstart = self.site1.fct_airage(self.airicehorizons_depth1)-\\\n                                 self.airicehorizons_sigma/2\n                    ystart = self.site2.fct_age(self.airicehorizons_depth2)+\\\n                                 self.airicehorizons_sigma/2\n                    for i in range(np.size(self.airicehorizons_depth1)):\n                        mpl.arrow(xstart[i], ystart[i], self.airicehorizons_sigma[i],\n                                  -self.airicehorizons_sigma[i], color=pccfg.color_ci,\n                                  width=0.0, head_length=0.0, head_width=0.0)\n                x_low, x_up, y_low, y_up = mpl.axis()\n#                x_low = self.site1.age_top\n#                y_low = self.site2.age_top\n#                mpl.axis((x_low, x_up, y_low, y_up))\n                rangefig = np.array([min(x_low, y_low), max(x_up, y_up)])\n                mpl.plot(rangefig, rangefig, color=pccfg.color_obs, label='Perfect agreement')\n                mpl.legend(loc=\"best\")\n                ax.set_aspect('equal')\n                printed_page = PdfPages(pccfg.datadir+self.label+'/'+self.age2_age_label+\n                                        'synchro.pdf')\n                printed_page.savefig(fig)\n                printed_page.close()\n                if not pccfg.show_figures:\n                    mpl.close()\n", "meta": {"hexsha": "ae77cf29c28ee2c0b695a8bcce7005908d8795fd", "size": 24685, "ext": "py", "lang": "Python", "max_stars_repo_path": "pcsitepair.py", "max_stars_repo_name": "parrenin/PaleoChrono", "max_stars_repo_head_hexsha": "90237b551c569e55ee6e6696c4b176234da4d94f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcsitepair.py", "max_issues_repo_name": "parrenin/PaleoChrono", "max_issues_repo_head_hexsha": "90237b551c569e55ee6e6696c4b176234da4d94f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcsitepair.py", "max_forks_repo_name": "parrenin/PaleoChrono", "max_forks_repo_head_hexsha": "90237b551c569e55ee6e6696c4b176234da4d94f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.7471264368, "max_line_length": 117, "alphanum_fraction": 0.5645938829, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.19014006108751347}}
{"text": "# Licensed with the 3-clause BSD license.  See LICENSE for details.\nfrom itertools import groupby\nimport numpy as np\nimport astropy.units as u\nfrom astropy.time import Time\nfrom astropy.table import vstack\nfrom sbpy.data import Ephem, Orbit, Names, QueryError\nfrom sbpy.data.names import TargetNameParseError\nfrom . import util\n\nSTEP_LIMIT = 300\n\n\ndef generate(desg, location, epochs, source='jpl', orbit=None, cache=False):\n    \"\"\"Generate ephemeris at specific epochs from external source.\n\n    Parameters\n    ----------\n    desg : string\n        Object designation.\n\n    location : string\n        Observer location.\n\n    epochs : array-like, Time, or dict\n        Compute ephemeris at these epochs.  Arrays must be\n        floats (for Julian date) or else parsable by\n        `~astropy.time.Time`.  Dictionaries are passed to the\n        ephemeris source as is.  Set ``step=None`` for an\n        adaptable time step that mitigates interpolation errors.\n\n    source : string, optional\n        Source to use: 'mpc', 'jpl', or 'oorb'.  'oorb' requires\n        ``orbit`` parameter.\n\n    orbit : `~sbpy.data.Orbit`, optional\n        Orbital elements for ``source=oorb``.\n\n    cache : bool, optional\n        Use cached ephemerides; primarily for testing.\n\n    Returns\n    -------\n    eph : `~sbpy.data.ephem.Ephem`\n        Ephemeris.\n\n    \"\"\"\n\n    if source not in ['mpc', 'jpl', 'oorb']:\n        raise ValueError('Source must be \"mpc\", \"jpl\", or \"oorb\".')\n\n    _epochs = _format_epochs(epochs)\n    if isinstance(_epochs, dict):\n        if epochs.get('step') is None:\n            eph = _get_adaptable_steps(desg, location, _epochs,\n                                       source=source, orbit=orbit,\n                                       cache=cache)\n    else:\n        eph = _get_fixed_steps(desg, location, _epochs, source=source,\n                               orbit=orbit, cache=cache)\n    return eph\n\n\ndef generate_orbit(desg, epochs, cache=False):\n    \"\"\"Generate orbital parameters from JPL Horizons at specific epochs.\n\n    Parameters\n    ----------\n    desg: string\n        Object designation.\n\n    epochs: array-like or dict\n        Compute orbital elements at these epochs.  For arrays,\n        must be floats(for Julian date) or else parsable by\n        `~astropy.time.Time`.\n\n    cache: bool, optional\n        Use cached ephemerides; primarily for testing.\n\n    Returns\n    -------\n    orb: `~sbpy.data.Orbit`\n        Orbital elements.\n\n    \"\"\"\n\n    _epochs = _format_epochs(epochs)\n    if not isinstance(_epochs, dict):\n        if len(_epochs) > STEP_LIMIT:\n            orb = None\n            N = np.ceil(len(_epochs) / STEP_LIMIT)\n            for e in np.array_split(_epochs, N):\n                _orb = generate_orbit(desg, e, cache=cache)\n                if orb:\n                    orb.add_rows(_orb)\n                else:\n                    orb = _orb\n            return orb\n        else:\n            pass\n            # ... and continue\n\n    kwargs = dict(epochs=_epochs, cache=cache)\n    kwargs['id_type'] = 'smallbody'\n    comet = False\n    try:\n        Names.parse_comet(desg)\n        comet = True\n        kwargs['id_type'] = 'designation'\n        cap_limit = closest_apparition_limit(_epochs)\n        kwargs.update(closest_apparition=cap_limit,\n                      no_fragments=True)\n    except TargetNameParseError:\n        pass\n\n\n    try:\n        orb = Orbit.from_horizons(desg, **kwargs)\n    except QueryError:\n        # Dual-listed objects should be queried without CAP/NOFRAG.  If\n        # this was a comet query, try again.\n        if comet:\n            del kwargs['closest_apparition'], kwargs['no_fragments']\n\n            # fix for sbpy bug #xxx, remove once v0.2.2 is released\n            kwargs['epochs'] = _format_epochs(epochs)\n\n            orb = Orbit.from_horizons(desg, **kwargs)\n        else:\n            raise\n\n    return orb\n\n\ndef closest_apparition_limit(epochs):\n    if isinstance(epochs, dict):\n        start = epochs['start'].jd\n    else:\n        start = epochs[0].jd\n    return '<{}'.format(start)\n\n\ndef _format_epochs(epochs):\n    if isinstance(epochs, dict):\n        start, stop = util.epochs_to_time((epochs['start'], epochs['stop']))\n        step = (None if epochs.get('step') is None\n                else u.Quantity(epochs.get('step')))\n        e = {\n            'start': start,\n            'stop': stop,\n            'step': step\n        }\n    else:\n        e = util.epochs_to_time(epochs)\n        if len(epochs) > 1:\n            d = np.diff(e.jd)\n            if any(d <= 0):\n                raise ValueError('Epoch dates must be increasing and unique.')\n\n    return e\n\n\ndef _get_fixed_steps(desg, location, epochs, source='jpl', orbit=None,\n                     cache=False):\n    if not isinstance(epochs, dict):\n        # list of specific dates, divide into chunks, as needed\n        if len(epochs) > STEP_LIMIT:\n            eph = None\n            N = np.ceil(len(epochs) / STEP_LIMIT)\n            for e in np.array_split(epochs, N):\n                _eph = _get_fixed_steps(desg, location, list(e),\n                                        source=source, cache=cache)\n                if eph:\n                    eph.add_rows(_eph)\n                else:\n                    eph = _eph\n            return eph\n        else:\n            pass\n            # and proceed...\n\n    if source == 'mpc':\n        eph = Ephem.from_mpc(desg, epochs=epochs,\n                             location=location,\n                             proper_motion='sky',\n                             proper_motion_unit='rad/s',\n                             cache=cache)\n\n        z = np.zeros(len(eph))\n        if 'Uncertainty 3sig' not in eph.table.colnames:\n            eph.table.add_column(u.Quantity(z, 'arcsec'),\n                                 name='SMAA_3sigma')\n            eph.table.add_column(u.Quantity(z, 'arcsec'),\n                                 name='SMIA_3sigma')\n            eph.table.add_column(u.Quantity(z, 'rad'),\n                                 name='Theta_3sigma')\n        else:\n            # MPC's ephemeris uncertainty is a line, rather than\n            # an ellipse\n            eph.table.add_column(u.Quantity(z, 'arcsec'),\n                                 name='SMIA_3sigma')\n            eph.table.add_column(eph['Uncertainty 3sig'],\n                                 name='SMAA_3sigma')\n            eph.table.add_column(eph['Unc. P.A.'],\n                                 name='Theta_3sigma')\n\n        # convert date from Time to Julian date, this helps with table\n        # manipulation since Time columns cannot be appended to.\n        eph['jd'] = eph['date'].jd\n    elif source == 'jpl':\n        # column 7 (sidereal time) isn't needed, but adding to avoid sbpy-0.2.1 crash\n        kwargs = dict(\n            epochs=epochs,\n            location=location,\n            quantities='1,3,8,9,7,19,20,23,24,27,36,37',\n            cache=cache\n        )\n        kwargs['id_type'] = 'smallbody'\n        comet = False\n        try:\n            Names.parse_comet(desg)\n            comet = True\n            kwargs['id_type'] = 'designation'\n            cap_limit = closest_apparition_limit(epochs)\n            kwargs.update(\n                closest_apparition=cap_limit,\n                no_fragments=True\n            )\n        except TargetNameParseError:\n            pass\n\n        try:\n            eph = Ephem.from_horizons(desg, **kwargs)\n        except QueryError:\n            # Dual-listed objects should be queried without CAP/NOFRAG.  If\n            # this was a comet query, try again.\n            if comet:\n                del kwargs['closest_apparition'], kwargs['no_fragments']\n\n                # fix for sbpy bug #xxx, remove once v0.2.2 is released\n                kwargs['epochs'] = _format_epochs(epochs)\n\n                eph = Ephem.from_horizons(desg, **kwargs)\n            else:\n                raise\n\n        # Horizon's theta is measured N of E.  We want E of N.\n        eph['Theta_3sigma'] = (np.pi / 2) * u.rad - eph['Theta_3sigma']\n\n        # create a plain Julian date column, helps with table\n        # manipulation in _get_adaptable_steps\n        eph['jd'] = eph['epoch'].jd\n    elif source == 'oorb':\n        eph = Ephem.from_oo(orbit, epochs=epochs, location=location)\n        # no uncertainties from oorb\n        z = np.zeros(len(eph))\n        eph.table.add_column(u.Quantity(z, 'arcsec'),\n                             name='SMAA_3sigma')\n        eph.table.add_column(u.Quantity(z, 'arcsec'),\n                             name='SMIA_3sigma')\n        eph.table.add_column(u.Quantity(z, 'rad'),\n                             name='Theta_3sigma')\n        eph['jd'] = eph['epoch'].jd  # same note as for jpl\n\n    return eph\n\n\ndef _get_adaptable_steps(desg, location, epochs, source='jpl', orbit=None,\n                         cache=False):\n    \"\"\"Ephemerides with adaptable time step.\n\n    Based on ZChecker analysis, Oct 2018, the interpolation error is\n    ~2\" / delta for 6h time step.\n\n    \"\"\"\n\n    # daily ephemeris for delta > 1\n    epochs['step'] = 1 * u.day\n    eph = _get_fixed_steps(desg, location, epochs, source=source,\n                           cache=cache)\n\n    for limit, substep in ((1 * u.au, 4 * u.hr), (0.25 * u.au, 1 * u.hr)):\n        updated = []\n        groups = groupby(zip(eph['delta'], eph['jd']),\n                         lambda e: e[0] < limit)\n        for inside, epochs in groups:\n            if not inside:\n                continue\n\n            jd = [e[1] for e in epochs]\n            if len(jd) > 1:\n                sub_epochs = _format_epochs({\n                    'start': jd[0],\n                    'stop': jd[-1],\n                    'step': substep\n                })\n                update = _get_fixed_steps(desg, location, sub_epochs,\n                                          source=source, cache=cache)\n                updated.append(update.table)\n\n        eph = Ephem.from_table(vstack([eph.table] + updated))\n\n        # remove duplicates\n        eph.table.sort('jd')\n        d = np.diff(eph['jd'])\n        duplicates = np.flatnonzero(np.isclose(d, 0)) + 1\n        eph.table.remove_rows(duplicates)\n\n    return eph\n", "meta": {"hexsha": "7c4ffb0ff59e6c23cbf6bb5eaa62c666559722e4", "size": 10119, "ext": "py", "lang": "Python", "max_stars_repo_path": "sbsearch/ephem.py", "max_stars_repo_name": "Small-Bodies-Node/sbsearch", "max_stars_repo_head_hexsha": "987e8017f62ce2965eff2455b67a40c0f316c58d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-02T17:25:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-02T17:25:19.000Z", "max_issues_repo_path": "sbsearch/ephem.py", "max_issues_repo_name": "Small-Bodies-Node/sbsearch", "max_issues_repo_head_hexsha": "987e8017f62ce2965eff2455b67a40c0f316c58d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2018-11-29T15:46:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-12T01:43:39.000Z", "max_forks_repo_path": "sbsearch/ephem.py", "max_forks_repo_name": "Small-Bodies-Node/sbsearch", "max_forks_repo_head_hexsha": "987e8017f62ce2965eff2455b67a40c0f316c58d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6419354839, "max_line_length": 85, "alphanum_fraction": 0.5392825378, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 2419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565327, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.190059027142551}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2019 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#\n\n'''\nQM part interface\n'''\n\nimport numpy\nimport pyscf\nfrom pyscf import lib\nfrom pyscf import gto\nfrom pyscf import df\nfrom pyscf import scf\nfrom pyscf import mcscf\nfrom pyscf import grad\nfrom pyscf.lib import logger\n\n\ndef mm_charge(scf_method, coords, charges, unit=None):\n    '''Modify the QM method using the (non-relativistic) potential generated\n    by MM charges. Note the static Coulomb interactions of the background\n    charges are not included in the total energy.\n\n    Args:\n        scf_method : a HF or DFT object\n\n        coords : 2D array, shape (N,3)\n            MM particle coordinates\n        charges : 1D array\n            MM particle charges\n    Kwargs:\n        unit : str\n            Bohr, AU, Ang (case insensitive). Default is the same to mol.unit\n\n    Returns:\n        Same method object as the input scf_method with modified 1e Hamiltonian\n\n    Note:\n        1. if MM charge and X2C correction are used together, function mm_charge\n        needs to be applied after X2C decoration (.x2c method), eg\n        mf = mm_charge(scf.RHF(mol).x2c()), [(0.5,0.6,0.8)], [-0.5]).\n        2. Once mm_charge function is applied on the SCF object, it\n        affects all the post-HF calculations eg MP2, CCSD, MCSCF etc\n\n    Examples:\n\n    >>> mol = gto.M(atom='H 0 0 0; F 0 0 1', basis='ccpvdz', verbose=0)\n    >>> mf = mm_charge(dft.RKS(mol), [(0.5,0.6,0.8)], [-0.3])\n    >>> mf.kernel()\n    -101.940495711284\n    '''\n    assert(isinstance(scf_method, scf.hf.SCF) or\n           isinstance(scf_method, mcscf.casci.CASCI))\n\n    if unit is None:\n        unit = scf_method.mol.unit\n    if unit.startswith(('B','b','au','AU')):\n        coords = numpy.asarray(coords, order='C')\n    elif unit.startswith(('A','a')):\n        coords = numpy.asarray(coords, order='C') / lib.parameters.BOHR\n    else:\n        coords = numpy.asarray(coords, order='C') / unit\n    charges = numpy.asarray(charges)\n    method_class = scf_method.__class__\n\n    class QMMM(method_class, _QMMM):\n        def __init__(self):\n            self.__dict__.update(scf_method.__dict__)\n\n        def dump_flags(self, verbose=None):\n            method_class.dump_flags(self, verbose)\n            logger.info(self, '** Add background charges for %s **',\n                        method_class)\n            if self.verbose >= logger.DEBUG:\n                logger.debug(self, 'Charge      Location')\n                for i, z in enumerate(charges):\n                    logger.debug(self, '%.9g    %s', z, coords[i])\n            return self\n\n        def get_hcore(self, mol=None):\n            if mol is None: mol = self.mol\n            if getattr(scf_method, 'get_hcore', None):\n                h1e = method_class.get_hcore(self, mol)\n            else:  # DO NOT modify post-HF objects to avoid the MM charges applied twice\n                raise RuntimeError('mm_charge function cannot be applied on post-HF methods')\n\n            if pyscf.DEBUG:\n                v = 0\n                for i,q in enumerate(charges):\n                    mol.set_rinv_origin(coords[i])\n                    v += mol.intor('int1e_rinv') * -q\n            else:\n                if mol.cart:\n                    intor = 'int3c2e_cart'\n                else:\n                    intor = 'int3c2e_sph'\n                nao = mol.nao\n                max_memory = self.max_memory - lib.current_memory()[0]\n                blksize = int(min(max_memory*1e6/8/nao**2, 200))\n                cintopt = gto.moleintor.make_cintopt(mol._atm, mol._bas,\n                                                     mol._env, intor)\n                v = 0\n                for i0, i1 in lib.prange(0, charges.size, blksize):\n                    fakemol = gto.fakemol_for_charges(coords[i0:i1])\n                    j3c = df.incore.aux_e2(mol, fakemol, intor=intor,\n                                           aosym='s2ij', cintopt=cintopt)\n                    v += numpy.einsum('xk,k->x', j3c, -charges[i0:i1])\n                v = lib.unpack_tril(v)\n            return h1e + v\n\n        def energy_nuc(self):\n# nuclei lattice interaction\n            nuc = self.mol.energy_nuc()\n            for j in range(self.mol.natm):\n                q2, r2 = self.mol.atom_charge(j), self.mol.atom_coord(j)\n                r = lib.norm(r2-coords, axis=1)\n                nuc += q2*(charges/r).sum()\n            return nuc\n\n        def nuc_grad_method(self):\n            scf_grad = method_class.nuc_grad_method(self)\n            return mm_charge_grad(scf_grad, coords, charges, 'Bohr')\n\n    return QMMM()\nadd_mm_charges = mm_charge\n\ndef mm_charge_grad(scf_grad, coords, charges, unit=None):\n    '''Apply the MM charges in the QM gradients' method.  It affects both the\n    electronic and nuclear parts of the QM fragment.\n\n    Args:\n        scf_grad : a HF or DFT gradient object (grad.HF or grad.RKS etc)\n            Once mm_charge_grad function is applied on the SCF object,\n            it affects all post-HF calculations eg MP2, CCSD, MCSCF etc\n        coords : 2D array, shape (N,3)\n            MM particle coordinates\n        charges : 1D array\n            MM particle charges\n    Kwargs:\n        unit : str\n            Bohr, AU, Ang (case insensitive). Default is the same to mol.unit\n\n    Returns:\n        Same gradeints method object as the input scf_grad method\n\n    Examples:\n\n    >>> from pyscf import gto, scf, grad\n    >>> mol = gto.M(atom='H 0 0 0; F 0 0 1', basis='ccpvdz', verbose=0)\n    >>> mf = mm_charge(scf.RHF(mol), [(0.5,0.6,0.8)], [-0.3])\n    >>> mf.kernel()\n    -101.940495711284\n    >>> hfg = mm_charge_grad(grad.hf.RHF(mf), coords, charges)\n    >>> hfg.kernel()\n    [[-0.25912357 -0.29235976 -0.38245077]\n     [-1.70497052 -1.89423883  1.2794798 ]]\n    '''\n    assert(isinstance(scf_grad, grad.rhf.Gradients))\n    if getattr(scf_grad.base, 'with_x2c', None):\n        raise NotImplementedError('X2C with QM/MM charges')\n\n    if unit is None:\n        unit = scf_grad.mol.unit\n    if unit.startswith(('B','b','au','AU')):\n        coords = numpy.asarray(coords, order='C')\n    elif unit.startswith(('A','a')):\n        coords = numpy.asarray(coords, order='C') / lib.parameters.BOHR\n    else:\n        coords = numpy.asarray(coords, order='C') / unit\n    charges = numpy.asarray(charges)\n\n    grad_class = scf_grad.__class__\n    class QMMM(grad_class, _QMMMGrad):\n        def __init__(self, scf_grad):\n            self.__dict__.update(scf_grad.__dict__)\n\n        def dump_flags(self, verbose=None):\n            grad_class.dump_flags(self, verbose)\n            logger.info(self, '** Add background charges for %s **', grad_class)\n            if self.verbose >= logger.DEBUG1:\n                logger.debug1(self, 'Charge      Location')\n                for i, z in enumerate(charges):\n                    logger.debug1(self, '%.9g    %s', z, coords[i])\n            return self\n\n        def get_hcore(self, mol=None):\n            ''' (QM 1e grad) + <-d/dX i|q_mm/r_mm|j>'''\n            if mol is None: mol = self.mol\n            g_qm = grad_class.get_hcore(self, mol)\n            nao = g_qm.shape[1]\n            if pyscf.DEBUG:\n                v = 0\n                for i,q in enumerate(charges):\n                    mol.set_rinv_origin(coords[i])\n                    v += mol.intor('int1e_iprinv', comp=3) * q\n            else:\n                if mol.cart:\n                    intor = 'int3c2e_ip1_cart'\n                else:\n                    intor = 'int3c2e_ip1_sph'\n                nao = mol.nao\n                max_memory = self.max_memory - lib.current_memory()[0]\n                blksize = int(min(max_memory*1e6/8/nao**2, 200))\n                cintopt = gto.moleintor.make_cintopt(mol._atm, mol._bas,\n                                                     mol._env, intor)\n                v = 0\n                for i0, i1 in lib.prange(0, charges.size, blksize):\n                    fakemol = gto.fakemol_for_charges(coords[i0:i1])\n                    j3c = df.incore.aux_e2(mol, fakemol, intor, aosym='s1',\n                                           comp=3, cintopt=cintopt)\n                    v += numpy.einsum('ipqk,k->ipq', j3c, charges[i0:i1])\n            return g_qm + v\n\n        def grad_nuc(self, mol=None, atmlst=None):\n            if mol is None: mol = self.mol\n            g_qm = grad_class.grad_nuc(self, mol, atmlst)\n# nuclei lattice interaction\n            g_mm = numpy.empty((mol.natm,3))\n            for i in range(mol.natm):\n                q1 = mol.atom_charge(i)\n                r1 = mol.atom_coord(i)\n                r = lib.norm(r1-coords, axis=1)\n                g_mm[i] = -q1 * numpy.einsum('i,ix,i->x', charges, r1-coords, 1/r**3)\n            if atmlst is not None:\n                g_mm = g_mm[atmlst]\n            return g_qm + g_mm\n    return QMMM(scf_grad)\n\n# A tag to label the derived class\nclass _QMMM:\n    pass\nclass _QMMMGrad:\n    pass\n\n# Inject QMMM interface wrapper to other modules\nscf.hf.SCF.QMMM = mm_charge\nmcscf.casci.CASCI.QMMM = mm_charge\ngrad.rhf.Gradients.QMMM = mm_charge_grad\n\nif __name__ == '__main__':\n    from pyscf import scf, cc, grad\n    mol = gto.Mole()\n    mol.atom = ''' O                  0.00000000    0.00000000   -0.11081188\n                   H                 -0.00000000   -0.84695236    0.59109389\n                   H                 -0.00000000    0.89830571    0.52404783 '''\n    mol.basis = 'cc-pvdz'\n    mol.build()\n\n    coords = [(0.5,0.6,0.8)]\n    #coords = [(0.0,0.0,0.0)]\n    charges = [-0.5]\n    mf = mm_charge(scf.RHF(mol), coords, charges)\n    print(mf.kernel()) # -76.3206550372\n\n    g = mf.nuc_grad_method().kernel()\n    mfs = mf.as_scanner()\n    e1 = mfs(''' O                  0.00100000    0.00000000   -0.11081188\n             H                 -0.00000000   -0.84695236    0.59109389\n             H                 -0.00000000    0.89830571    0.52404783 ''')\n    e2 = mfs(''' O                 -0.00100000    0.00000000   -0.11081188\n             H                 -0.00000000   -0.84695236    0.59109389\n             H                 -0.00000000    0.89830571    0.52404783 ''')\n    print((e1 - e2)/0.002 * lib.param.BOHR, g[0,0])\n\n    mycc = cc.ccsd.CCSD(mf)\n    ecc, t1, t2 = mycc.kernel() # ecc = -0.228939687075\n\n    g = mycc.nuc_grad_method().kernel()\n    ccs = mycc.as_scanner()\n    e1 = ccs(''' O                  0.00100000    0.00000000   -0.11081188\n             H                 -0.00000000   -0.84695236    0.59109389\n             H                 -0.00000000    0.89830571    0.52404783 ''')\n    e2 = ccs(''' O                 -0.00100000    0.00000000   -0.11081188\n             H                 -0.00000000   -0.84695236    0.59109389\n             H                 -0.00000000    0.89830571    0.52404783 ''')\n    print((e1 - e2)/0.002 * lib.param.BOHR, g[0,0])\n\n", "meta": {"hexsha": "a1017ca0f74e847078c154667e7ae14279b868be", "size": 11370, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/qmmm/itrf.py", "max_stars_repo_name": "crisely09/pyscf", "max_stars_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-07T21:12:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-07T21:12:08.000Z", "max_issues_repo_path": "pyscf/qmmm/itrf.py", "max_issues_repo_name": "crisely09/pyscf", "max_issues_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-09-16T17:58:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-22T17:26:01.000Z", "max_forks_repo_path": "pyscf/qmmm/itrf.py", "max_forks_repo_name": "crisely09/pyscf", "max_forks_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8054607509, "max_line_length": 93, "alphanum_fraction": 0.554353562, "include": true, "reason": "import numpy", "num_tokens": 3198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.1900175165815165}}
{"text": "from __future__ import division, absolute_import, print_function\nfrom .. import affinitymat\nfrom .. import nearest_neighbors\nfrom .. import cluster\nfrom .. import aggregator\nfrom .. import core\nfrom .. import util\nfrom .. import seqlet_embedding\nfrom .. import pattern_filterer as pattern_filterer_module\nfrom joblib import Parallel, delayed\nfrom collections import defaultdict, OrderedDict, Counter\nimport numpy as np\nimport time\nimport sys\nimport gc\nimport json\nfrom ..util import print_memory_use\n\n\ndef get_seqlet_neighbors_with_initcluster(\n        nearest_neighbors_to_compute,\n        coarse_affmat, initclusters): \n    if (initclusters is not None):\n        assert len(initclusters)==len(coarse_affmat)\n    #get the argsort for coarse_affmat\n    coarse_affmat_argsort = np.argsort(-coarse_affmat, axis=-1)\n    nearest_neighbors = []\n    for row_idx,argsort_row in enumerate(coarse_affmat_argsort):\n        combined_neighbor_row = []\n        neighbor_row_topnn = argsort_row[:nearest_neighbors_to_compute+1]\n        neighbor_set_topnn = set(neighbor_row_topnn)\n        #combined_neighbor_row ends up being the union of the standard nearest\n        # neighbors plus the nearest neighbors if focusing on the initclusters\n        combined_neighbor_row.extend(neighbor_row_topnn)\n        if (initclusters is not None):\n            combined_neighbor_row.extend([\n                y for y in ([x for x in argsort_row\n                             if initclusters[x]==initclusters[row_idx]][\n                             :nearest_neighbors_to_compute+1])\n                if y not in neighbor_set_topnn])\n        nearest_neighbors.append(combined_neighbor_row) \n    return nearest_neighbors\n\n\ndef fish_out_kwargs(orig_kwargs, to_fish_out):\n    fished_out = {}\n    for kwarg_name in to_fish_out:\n        if kwarg_name in orig_kwargs:\n            fished_out[kwarg_name] = orig_kwargs[kwarg_name]\n            del orig_kwargs[kwarg_name] \n    return fished_out\n\n\n#adds backwargs compatibility re gapped kmer arguments\ndef legacy_tfmodiscoseqletstopatternsfactory(current_constructor):\n\n    def new_constructor(*args, **kwargs): \n        gapped_kmer_kwargs = fish_out_kwargs(\n            orig_kwargs=kwargs,\n            to_fish_out=['kmer_len', 'num_gaps',\n                         'num_mismatches', 'gpu_batch_size'])\n        if (len(gapped_kmer_kwargs) > 0):\n            assert 'embedder_factory' not in kwargs,\\\n                (\"Cannot both specify embedder_factory and \"\n                 +str(gapped_kmer_kwargs))\n            from modisco.seqlet_embedding import gapped_kmer\n            kwargs['embedder_factory'] = (\n                  seqlet_embedding.gapped_kmer\n                  .GappedKmerEmbedderFactory(**gapped_kmer_kwargs))\n        return current_constructor(*args, **kwargs) \n    return new_constructor \n\n\n##legacy\n#alphabet_size=None,\n#kmer_len=None, num_gaps=3, num_mismatches=2,\n#gpu_batch_size=20,\nclass TfModiscoSeqletsToPatternsFactory(object):\n\n    @legacy_tfmodiscoseqletstopatternsfactory\n    def __init__(self, n_cores=4,\n                       min_overlap_while_sliding=0.7,\n\n                       #init clusterer factory\n                       initclusterer_factory=None,                       \n\n                       embedder_factory=(\n                        seqlet_embedding.advanced_gapped_kmer\n                                        .AdvancedGappedKmerEmbedderFactory()),\n\n                       nearest_neighbors_to_compute=500,\n                       use_pynnd=False,\n\n                       affmat_correlation_threshold=0.15,\n                       filter_beyond_first_round=False,\n                       skip_fine_grained=False,\n\n                       tsne_perplexity=10,\n                       use_louvain=False,\n                       louvain_initclusters_weight=1.0,\n                       n_leiden_iterations_r1=-1,\n                       n_leiden_iterations_r2=-1,\n                       louvain_num_runs_and_levels_r1=[(200,-1)],\n                       louvain_num_runs_and_levels_r2=[(200,-1)], \n                       contin_runs_r1=50,\n                       contin_runs_r2=50,\n                       final_louvain_level_to_return=1,\n\n                       frac_support_to_trim_to=0.2,\n                       min_num_to_trim_to=30,\n                       trim_to_window_size=30,\n                       initial_flank_to_add=10,\n\n                       prob_and_pertrack_sim_merge_thresholds=[\n                       (0.8,0.8), (0.5, 0.85), (0.2, 0.9)],\n\n                       prob_and_pertrack_sim_dealbreaker_thresholds=[\n                        (0.4, 0.75), (0.2,0.8), (0.1, 0.85), (0.0,0.9)],\n\n                       subcluster_perplexity=50,\n                       merging_max_seqlets_subsample=300,\n                       #threshold_for_spurious_merge_detection=0.8,\n\n                       #min_similarity_for_seqlet_assignment=0.2,\n                       final_min_cluster_size=30,\n                       min_ic_in_window=0.6,#total IC in some windowsize window \n                       min_ic_windowsize=6,\n                       ppm_pseudocount=0.001,\n\n                       final_flank_to_add=0,\n\n                       verbose=True, seed=1234):\n\n        self.initclusterer_factory = initclusterer_factory\n        if (use_louvain==True):\n            assert self.initclusterer_factory==None,\\\n                    (\"Louvain doesn't support cluster initialization;\"\n                     +\" set use_louvain to False\")\n\n        #affinity_mat calculation\n        self.n_cores = n_cores\n        self.min_overlap_while_sliding = min_overlap_while_sliding\n\n        self.embedder_factory = embedder_factory\n\n        self.nearest_neighbors_to_compute = nearest_neighbors_to_compute\n        self.use_pynnd = use_pynnd\n\n        self.affmat_correlation_threshold = affmat_correlation_threshold\n        self.filter_beyond_first_round = filter_beyond_first_round\n        self.skip_fine_grained = skip_fine_grained\n\n        #affinity mat to tsne dist mat setting\n        self.tsne_perplexity = tsne_perplexity\n\n        #clustering settings\n        self.use_louvain = use_louvain\n        self.louvain_initclusters_weight = louvain_initclusters_weight\n        self.n_leiden_iterations_r1 = n_leiden_iterations_r1\n        self.n_leiden_iterations_r2 = n_leiden_iterations_r2\n        self.contin_runs_r1 = contin_runs_r1\n        self.contin_runs_r2 = contin_runs_r2\n        self.louvain_num_runs_and_levels_r1 = louvain_num_runs_and_levels_r1\n        self.louvain_num_runs_and_levels_r2 = louvain_num_runs_and_levels_r2\n        self.final_louvain_level_to_return = final_louvain_level_to_return\n\n        #postprocessor1 settings\n        self.frac_support_to_trim_to = frac_support_to_trim_to\n        self.min_num_to_trim_to = min_num_to_trim_to\n        self.trim_to_window_size = trim_to_window_size\n        self.initial_flank_to_add = initial_flank_to_add \n\n        #subclustering\n        self.subcluster_perplexity=subcluster_perplexity\n\n        #merging similar patterns\n        self.prob_and_pertrack_sim_merge_thresholds =\\\n            prob_and_pertrack_sim_merge_thresholds\n        self.prob_and_pertrack_sim_dealbreaker_thresholds =\\\n            prob_and_pertrack_sim_dealbreaker_thresholds\n\n        self.merging_max_seqlets_subsample = merging_max_seqlets_subsample\n        #self.threshold_for_spurious_merge_detection =\\\n        #    threshold_for_spurious_merge_detection\n\n        #reassignment settings\n        #self.min_similarity_for_seqlet_assignment =\\\n        #    min_similarity_for_seqlet_assignment\n        self.final_min_cluster_size = final_min_cluster_size\n        self.min_ic_in_window = min_ic_in_window\n        self.min_ic_windowsize = min_ic_windowsize\n        self.ppm_pseudocount = ppm_pseudocount\n\n        #final postprocessor settings\n        self.final_flank_to_add=final_flank_to_add\n\n        #other settings\n        self.verbose = verbose\n        self.seed = seed\n\n    def get_jsonable_config(self):\n        to_return =  OrderedDict([\n                ('class_name', type(self).__name__),\n                ('n_cores', self.n_cores),\n                ('initclusterer_factory',\n                 self.initclusterer_factory.get_jsonable_config()),\n                ('min_overlap_while_sliding', self.min_overlap_while_sliding),\n                ('embedder_factory',\n                 self.embedder_factory.get_jsonable_config()),\n                ('num_mismatches', self.num_mismatches),\n                ('nearest_neighbors_to_compute',\n                 self.nearest_neighbors_to_compute),\n                ('affmat_correlation_threshold',\n                 self.affmat_correlation_threshold),\n                ('filter_beyond_first_round', filter_beyond_first_round),\n                ('tsne_perplexity', self.tsne_perplexity),\n                ('use_louvain', self.use_louvain),\n                ('louvain_num_runs_and_levels_r1',\n                 self.louvain_num_runs_and_levels_r1),\n                ('louvain_num_runs_and_levels_r2',\n                 self.louvain_num_runs_and_levels_r2),\n                ('final_louvain_level_to_return',\n                 self.final_louvain_level_to_return),\n                ('contin_runs_r1',\n                 self.contin_runs_r1),\n                ('contin_runs_r2',\n                 self.contin_runs_r2),\n                ('frac_support_to_trim_to', self.frac_support_to_trim_to),\n                ('min_num_to_trim_to', self.min_num_to_trim_to),\n                ('trim_to_window_size', self.trim_to_window_size),\n                ('initial_flank_to_add', self.initial_flank_to_add),\n                ('subcluster_perplexity', self.subcluster_perplexity),\n                ('prob_and_pertrack_sim_merge_thresholds',\n                 self.prob_and_pertrack_sim_merge_thresholds),\n                ('prob_and_pertrack_sim_dealbreaker_thresholds',\n                 self.prob_and_pertrack_sim_dealbreaker_thresholds),\n                ('merging_max_seqlets_subsample',\n                 self.merging_max_seqlets_subsample),\n                #('threshold_for_spurious_merge_detection',\n                # self.threshold_for_spurious_merge_detection),\n                ('min_similarity_for_seqlet_assignment',\n                 self.min_similarity_for_seqlet_assignment),\n                ('final_min_cluster_size', self.final_min_cluster_size),\n                ('min_ic_in_window', self.min_ic_in_window),\n                ('min_ic_windowsize', self.min_ic_windowsize),\n                ('ppm_pseudocount', self.ppm_pseudocount),\n                ('final_flank_to_add', self.final_flank_to_add),\n                ]) \n        return to_return\n\n    def __call__(self, track_set, onehot_track_name,\n                       contrib_scores_track_names,\n                       hypothetical_contribs_track_names,\n                       track_signs,\n                       other_comparison_track_names=[]):\n\n        bg_freq = np.mean(\n            track_set.track_name_to_data_track[onehot_track_name].fwd_tracks,\n            axis=(0,1))\n        assert len(bg_freq.shape)==1 \n\n        assert len(track_signs)==len(hypothetical_contribs_track_names)\n        assert len(track_signs)==len(contrib_scores_track_names)\n\n        seqlets_sorter = (lambda arr:\n                          sorted(arr,\n                                 key=lambda x:\n                                  -np.sum([np.sum(np.abs(x[track_name].fwd))\n                                     for track_name\n                                     in contrib_scores_track_names])))\n\n        if (self.initclusterer_factory is not None):\n            self.initclusterer_factory.set_onehot_track_name(onehot_track_name)\n        initclusterer_factory = self.initclusterer_factory\n\n        pattern_comparison_settings =\\\n            affinitymat.core.PatternComparisonSettings(\n                track_names=hypothetical_contribs_track_names\n                            +contrib_scores_track_names\n                            +other_comparison_track_names, \n                track_transformer=affinitymat.L1Normalizer(), \n                min_overlap=self.min_overlap_while_sliding)\n\n        #coarse_grained 1d embedder\n        seqlets_to_1d_embedder = self.embedder_factory(\n                onehot_track_name=onehot_track_name,\n                toscore_track_names_and_signs=list(\n                zip(hypothetical_contribs_track_names,\n                    [np.sign(x) for x in track_signs])),\n                n_jobs=self.n_cores)\n\n        #affinity matrix from embeddings\n        if (self.use_pynnd):\n            sparse_affmat_from_fwdnrev1dvecs = (\n             affinitymat.core.PynndSparseNumpyCosineSimFromFwdAndRevOneDVecs(\n                n_neighbors=self.nearest_neighbors_to_compute,\n                verbose=self.verbose,\n                n_jobs=self.n_cores))\n        else:\n            sparse_affmat_from_fwdnrev1dvecs =\\\n                affinitymat.core.SparseNumpyCosineSimFromFwdAndRevOneDVecs(\n                        n_neighbors=self.nearest_neighbors_to_compute, \n                        verbose=self.verbose)\n        coarse_affmat_computer =\\\n          affinitymat.core.SparseAffmatFromFwdAndRevSeqletEmbeddings(\n            seqlets_to_1d_embedder=seqlets_to_1d_embedder,\n            sparse_affmat_from_fwdnrev1dvecs=sparse_affmat_from_fwdnrev1dvecs,\n            verbose=self.verbose)\n\n        affmat_from_seqlets_with_nn_pairs =\\\n            affinitymat.core.AffmatFromSeqletsWithNNpairs(\n                pattern_comparison_settings=pattern_comparison_settings,\n                sim_metric_on_nn_pairs=\\\n                    affinitymat.core.ParallelCpuCrossMetricOnNNpairs(\n                        n_cores=self.n_cores,\n                        cross_metric_single_region=\n                            affinitymat.core.CrossContinJaccardSingleRegion()))\n\n        filter_mask_from_correlation =\\\n            affinitymat.core.FilterMaskFromCorrelation(\n                correlation_threshold=self.affmat_correlation_threshold,\n                verbose=self.verbose)\n\n        aff_to_dist_mat = affinitymat.transformers.AffToDistViaInvLogistic() \n        #density_adapted_affmat_transformer =\\\n        #    affinitymat.transformers.NNTsneConditionalProbs(\n        #        perplexity=self.tsne_perplexity,\n        #        aff_to_dist_mat=aff_to_dist_mat)\n\n        #prepare the clusterers for the different rounds\n        # No longer a need for symmetrization because am symmetrizing by\n        # taking the geometric mean elsewhere\n        affmat_transformer_r1 =\\\n            affinitymat.transformers.AdhocAffMatTransformer(lambda x: x)\n        #affinitymat.transformers.SymmetrizeByAddition(\n        #                            probability_normalize=True)\n        print(\"TfModiscoSeqletsToPatternsFactory: seed=%d\" % self.seed)\n        if (self.use_louvain):\n            for n_runs, level_to_return in self.louvain_num_runs_and_levels_r1:\n                affmat_transformer_r1 = affmat_transformer_r1.chain(\n                    affinitymat.transformers.LouvainMembershipAverage(\n                        n_runs=n_runs,\n                        level_to_return=level_to_return,\n                        parallel_threads=self.n_cores, seed=self.seed))\n            clusterer_r1 = cluster.core.LouvainCluster(\n                level_to_return=self.final_louvain_level_to_return,\n                affmat_transformer=affmat_transformer_r1,\n                contin_runs=self.contin_runs_r1,\n                verbose=self.verbose, seed=self.seed)\n        else:\n            clusterer_r1 = cluster.core.LeidenClusterParallel(\n                n_jobs=self.n_cores, \n                affmat_transformer=affmat_transformer_r1,\n                numseedstotry=self.contin_runs_r1,\n                n_leiden_iterations=self.n_leiden_iterations_r1,\n                verbose=self.verbose)\n\n        #No longer a need for symmetrization because am symmetrizing by\n        # taking the geometric mean elsewhere\n        affmat_transformer_r2 =\\\n            affinitymat.transformers.AdhocAffMatTransformer(lambda x: x)\n        #affmat_transformer_r2 = affinitymat.transformers.SymmetrizeByAddition(\n        #                        probability_normalize=True)\n        if (self.use_louvain):\n            for n_runs, level_to_return in self.louvain_num_runs_and_levels_r2:\n                affmat_transformer_r2 = affmat_transformer_r2.chain(\n                    affinitymat.transformers.LouvainMembershipAverage(\n                        n_runs=n_runs,\n                        level_to_return=level_to_return,\n                        parallel_threads=self.n_cores, seed=self.seed))\n            clusterer_r2 = cluster.core.LouvainCluster(\n                level_to_return=self.final_louvain_level_to_return,\n                affmat_transformer=affmat_transformer_r2,\n                contin_runs=self.contin_runs_r2,\n                verbose=self.verbose, seed=self.seed,\n                initclusters_weight=self.louvain_initclusters_weight)\n        else:\n            clusterer_r2 = cluster.core.LeidenClusterParallel(\n                n_jobs=self.n_cores, \n                affmat_transformer=affmat_transformer_r2,\n                numseedstotry=self.contin_runs_r2,\n                n_leiden_iterations=self.n_leiden_iterations_r2,\n                verbose=self.verbose)\n        \n        clusterer_per_round = [clusterer_r1, clusterer_r2]\n\n        #prepare the seqlet aggregator\n        expand_trim_expand1 =\\\n            aggregator.ExpandSeqletsToFillPattern(\n                track_set=track_set,\n                flank_to_add=self.initial_flank_to_add).chain(\n            aggregator.TrimToBestWindowByIC(\n                window_size=self.trim_to_window_size,\n                onehot_track_name=onehot_track_name,\n                bg_freq=bg_freq)).chain(\n            aggregator.ExpandSeqletsToFillPattern(\n                track_set=track_set,\n                flank_to_add=self.initial_flank_to_add))\n        postprocessor1 =\\\n            aggregator.TrimToFracSupport(\n                        min_frac=self.frac_support_to_trim_to,\n                        min_num=self.min_num_to_trim_to,\n                        verbose=self.verbose)\\\n                      .chain(expand_trim_expand1)\n        seqlet_aggregator = aggregator.GreedySeqletAggregator(\n            pattern_aligner=core.CrossContinJaccardPatternAligner(\n                pattern_comparison_settings=pattern_comparison_settings),\n                seqlet_sort_metric=\n                    lambda x: -sum([np.sum(np.abs(x[track_name].fwd)) for\n                               track_name in contrib_scores_track_names]),\n            track_set=track_set, #needed for seqlet expansion\n            postprocessor=postprocessor1)\n\n        def sign_consistency_func(motif):\n            motif_track_signs = [\n                np.sign(np.sum(motif[contrib_scores_track_name].fwd)) for\n                contrib_scores_track_name in contrib_scores_track_names]\n            return all([(x==y) for x,y in zip(motif_track_signs, track_signs)])\n\n        #prepare the similar patterns collapser\n        pattern_to_seqlet_sim_computer =\\\n            affinitymat.core.AffmatFromSeqletsWithNNpairs(\n                pattern_comparison_settings=pattern_comparison_settings,\n                sim_metric_on_nn_pairs=\\\n                    affinitymat.core.ParallelCpuCrossMetricOnNNpairs(\n                        n_cores=self.n_cores,\n                        cross_metric_single_region=\\\n                            affinitymat.core.CrossContinJaccardSingleRegion(),\n                        verbose=False))\n\n        #similarity settings for merging\n        prob_and_sim_merge_thresholds =\\\n            self.prob_and_pertrack_sim_merge_thresholds\n        prob_and_sim_dealbreaker_thresholds =\\\n            self.prob_and_pertrack_sim_dealbreaker_thresholds\n\n        similar_patterns_collapser =\\\n            aggregator.DynamicDistanceSimilarPatternsCollapser2(\n                pattern_comparison_settings=pattern_comparison_settings,\n                track_set=track_set,\n                pattern_aligner=core.CrossCorrelationPatternAligner(\n                    pattern_comparison_settings=\n                        affinitymat.core.PatternComparisonSettings(\n                            track_names=(\n                                contrib_scores_track_names+\n                                other_comparison_track_names), \n                            track_transformer=\n                                affinitymat.MeanNormalizer().chain(\n                                affinitymat.MagnitudeNormalizer()), \n                            min_overlap=self.min_overlap_while_sliding)),\n                collapse_condition=(lambda prob, aligner_sim:\n                    any([(prob >= x[0] and aligner_sim >= x[1])\n                         for x in prob_and_sim_merge_thresholds])),\n                dealbreaker_condition=(lambda prob, aligner_sim:\n                    any([(prob <= x[0] and aligner_sim <= x[1])              \n                         for x in prob_and_sim_dealbreaker_thresholds])),\n                postprocessor=postprocessor1,\n                verbose=self.verbose,\n                max_seqlets_subsample=self.merging_max_seqlets_subsample,\n                n_cores=self.n_cores)\n\n        subcluster_settings = {\n            \"pattern_comparison_settings\": pattern_comparison_settings,\n            \"perplexity\": self.subcluster_perplexity,\n            \"n_jobs\": self.n_cores,\n        }\n        spurious_merge_detector = aggregator.DetectSpuriousMerging2(\n            subcluster_settings=subcluster_settings,\n            verbose=self.verbose,\n            min_in_subcluster=max(self.final_min_cluster_size,\n                                  self.subcluster_perplexity),\n            similar_patterns_collapser=similar_patterns_collapser)\n\n        #spurious_merge_detector = aggregator.DetectSpuriousMerging(\n        #    track_names=contrib_scores_track_names,\n        #    track_transformer=affinitymat.core.L1Normalizer(),\n        #    affmat_from_1d=affinitymat.core.ContinJaccardSimilarity(\n        #                    make_positive=True, verbose=False),\n        #    diclusterer=cluster.core.LouvainCluster(\n        #                    level_to_return=1,\n        #                    max_clusters=2, contin_runs=20,\n        #                    verbose=False, seed=self.seed),\n        #    is_dissimilar_func=aggregator.PearsonCorrIsDissimilarFunc(\n        #                threshold=self.threshold_for_spurious_merge_detection,\n        #                verbose=self.verbose),\n        #    min_in_subcluster=self.final_min_cluster_size)\n\n        #similar_patterns_collapser =\\\n        #    aggregator.DynamicDistanceSimilarPatternsCollapser(\n        #        pattern_to_pattern_sim_computer=\n        #            pattern_to_seqlet_sim_computer,\n        #        aff_to_dist_mat=aff_to_dist_mat,\n        #        pattern_aligner=core.CrossCorrelationPatternAligner(\n        #            pattern_comparison_settings=\n        #                affinitymat.core.PatternComparisonSettings(\n        #                    track_names=(\n        #                        contrib_scores_track_names+\n        #                        other_comparison_track_names), \n        #                    track_transformer=\n        #                        affinitymat.MeanNormalizer().chain(\n        #                        affinitymat.MagnitudeNormalizer()), \n        #                    min_overlap=self.min_overlap_while_sliding)),\n        #        collapse_condition=(lambda prob, aligner_sim:\n        #            any([(prob > x[0] and aligner_sim > x[1])\n        #                 for x in prob_and_sim_merge_thresholds])),\n        #        dealbreaker_condition=(lambda prob, aligner_sim:\n        #            any([(prob < x[0] and aligner_sim < x[1])              \n        #                 for x in prob_and_sim_dealbreaker_thresholds])),\n        #        postprocessor=postprocessor1,\n        #        verbose=self.verbose)\n\n        pattern_filterer = pattern_filterer_module.MinSeqletSupportFilterer(\n            min_seqlet_support=self.final_min_cluster_size).chain(\n                pattern_filterer_module.MinICinWindow(\n                    window_size=self.min_ic_windowsize,\n                    min_ic_in_window=self.min_ic_in_window,\n                    background=bg_freq,\n                    sequence_track_name=onehot_track_name,\n                    ppm_pseudocount=self.ppm_pseudocount   \n                ) \n            )\n\n        #seqlet_reassigner =\\\n        #   aggregator.ReassignSeqletsFromSmallClusters(\n        #    seqlet_assigner=aggregator.AssignSeqletsByBestMetric(\n        #        pattern_comparison_settings=pattern_comparison_settings,\n        #        individual_aligner_metric=\n        #            core.get_best_alignment_crosscontinjaccard,\n        #        matrix_affinity_metric=\n        #            affinitymat.core.CrossContinJaccardMultiCoreCPU(\n        #                verbose=self.verbose, n_cores=self.n_cores),\n        #        min_similarity=self.min_similarity_for_seqlet_assignment,\n        #        track_set=track_set),\n        #    min_cluster_size=self.final_min_cluster_size,\n        #    postprocessor=expand_trim_expand1,\n        #    verbose=self.verbose) \n\n        final_postprocessor = aggregator.ExpandSeqletsToFillPattern(\n                                        track_set=track_set,\n                                        flank_to_add=self.final_flank_to_add) \n\n        return TfModiscoSeqletsToPatterns(\n                seqlets_sorter=seqlets_sorter,\n                initclusterer_factory=initclusterer_factory,\n                coarse_affmat_computer=coarse_affmat_computer,\n                nearest_neighbors_to_compute=self.nearest_neighbors_to_compute,\n                affmat_from_seqlets_with_nn_pairs=\n                    affmat_from_seqlets_with_nn_pairs, \n                filter_mask_from_correlation=filter_mask_from_correlation,\n                filter_beyond_first_round=self.filter_beyond_first_round,\n                skip_fine_grained=self.skip_fine_grained,\n                aff_to_dist_mat=aff_to_dist_mat,\n                tsne_perplexity=self.tsne_perplexity,\n                #density_adapted_affmat_transformer=\n                #    density_adapted_affmat_transformer,\n                clusterer_per_round=clusterer_per_round,\n                seqlet_aggregator=seqlet_aggregator,\n                sign_consistency_func=sign_consistency_func,\n                subcluster_settings=subcluster_settings,\n                spurious_merge_detector=spurious_merge_detector,\n                similar_patterns_collapser=similar_patterns_collapser,\n                #seqlet_reassigner=seqlet_reassigner,\n                pattern_filterer=pattern_filterer,\n                final_postprocessor=final_postprocessor,\n                verbose=self.verbose,\n                n_cores=self.n_cores,\n                other_config={\n                 'onehot_track_name': onehot_track_name,\n                 'contrib_scores_track_names': contrib_scores_track_names,\n                 'hypothetical_contribs_track_names':\n                    hypothetical_contribs_track_names,\n                 'track_signs': track_signs, \n                 'other_comparison_track_names': other_comparison_track_names},\n                )\n\n    def save_hdf5(self, grp):\n        grp.attrs['jsonable_config'] =\\\n            json.dumps(self.jsonable_config, indent=4, separators=(',', ': ')) \n\n\nclass SeqletsToPatternsResults(object):\n\n    def __init__(self,\n                 each_round_initcluster_motifs, \n                 patterns, \n                 remaining_patterns,\n                 pattern_merge_hierarchy,\n                 cluster_results,\n                 total_time_taken,\n                 other_config={},\n                 success=True,\n                 **kwargs):\n        self.each_round_initcluster_motifs = each_round_initcluster_motifs\n        self.other_config = other_config\n        self.success = success\n        self.patterns = patterns\n        self.remaining_patterns = remaining_patterns\n        self.pattern_merge_hierarchy = pattern_merge_hierarchy\n        self.cluster_results = cluster_results\n        self.total_time_taken = total_time_taken\n        self.__dict__.update(**kwargs)\n\n    def save_each_round_initcluster_motifs(self, grp):\n        all_round_names = []\n        for (round_idx,initcluster_motifs)\\\n            in enumerate(self.each_round_initcluster_motifs):\n            round_name = \"round_\"+str(round_idx)\n            util.save_patterns(patterns=initcluster_motifs,\n                               grp=grp.create_group(round_name)) \n        util.save_string_list(\n            string_list=all_round_names,\n            dset_name=\"all_round_names\",          \n            grp=grp)\n\n    @classmethod\n    def load_each_round_initcluster_motifs(cls, grp, track_set):\n        all_round_names = util.load_string_list(dset_name=\"all_round_names\",\n                                                grp=grp) \n        each_round_initcluster_motifs = [] \n        for round_name in all_round_names:\n            round_grp = grp[round_name]\n            initcluster_motifs = load_patterns(grp=round_grp,\n                                               track_set=track_set)\n            each_round_initcluster_motifs.append(initcluster_motifs)\n        return each_round_initcluster_motifs\n             \n    @classmethod\n    def from_hdf5(cls, grp, track_set):\n        success = grp.attrs.get(\"success\", False)\n        if (success):\n            if (\"each_round_initcluster_motifs\" not in grp):\n                each_round_initcluster_motifs = None \n            else:\n                each_round_initcluster_motifs =\\\n                    cls.load_each_round_initcluster_motifs(\n                        grp=grp[\"each_round_initcluster_motifs\"],\n                        track_set=track_set)\n            patterns = util.load_patterns(grp=grp[\"patterns\"],\n                                          track_set=track_set) \n            if \"remaining_patterns\" in grp:\n                remaining_patterns = util.load_patterns(\n                    grp=grp[\"remaining_patterns\"],\n                    track_set=track_set) \n            else: #backwards compatibility\n                remaining_patterns = []\n            cluster_results = None\n            total_time_taken = grp.attrs[\"total_time_taken\"]\n            if (\"pattern_merge_hierarchy\" in grp):\n                pattern_merge_hierarchy =\\\n                    aggregator.PatternMergeHierarchy.from_hdf5(\n                        grp=grp[\"pattern_merge_hierarchy\"],\n                        track_set=track_set)\n            else:\n                pattern_merge_hierarchy = None\n            return cls(\n                each_round_initcluster_motifs=each_round_initcluster_motifs,\n                patterns=patterns,\n                remaining_patterns=remaining_patterns,\n                pattern_merge_hierarchy=pattern_merge_hierarchy,\n                cluster_results=cluster_results,\n                total_time_taken=total_time_taken)\n        else:\n            return cls(success=False, patterns=None, cluster_results=None,\n                       total_time_taken=None,\n                       each_round_initcluster_motifs=None,\n                       remaining_patterns=None,\n                       pattern_merge_hierarchy=None)\n\n    def save_hdf5(self, grp):\n        grp.attrs[\"success\"] = self.success\n        grp.attrs[\"other_config\"] =\\\n            json.dumps(self.other_config, indent=4, separators=(',', ': ')) \n        if (self.success):\n            grp.attrs[\"total_time_taken\"] = self.total_time_taken\n            if (self.each_round_initcluster_motifs is not None):\n                self.save_each_round_initcluster_motifs(\n                    grp=grp.create_group(\"each_round_initcluster_motifs\"))\n            util.save_patterns(self.patterns,\n                               grp.create_group(\"patterns\"))\n            util.save_patterns(\n                self.remaining_patterns,\n                grp.create_group(\"remaining_patterns\"))\n            self.cluster_results.save_hdf5(grp.create_group(\"cluster_results\"))   \n            grp.attrs['total_time_taken'] = self.total_time_taken\n            self.pattern_merge_hierarchy.save_hdf5(\n                    grp=grp.create_group(\"pattern_merge_hierarchy\"))\n\n\nclass AbstractSeqletsToPatterns(object):\n\n    def __call__(self, seqlets):\n        raise NotImplementedError()\n\n\nclass TfModiscoSeqletsToPatterns(AbstractSeqletsToPatterns):\n\n    def __init__(self, seqlets_sorter, \n                       initclusterer_factory,\n                       coarse_affmat_computer,\n                       nearest_neighbors_to_compute,\n                       affmat_from_seqlets_with_nn_pairs, \n                       filter_mask_from_correlation,\n                       filter_beyond_first_round,\n                       skip_fine_grained,\n                       aff_to_dist_mat,\n                       tsne_perplexity,\n                       #density_adapted_affmat_transformer,\n                       clusterer_per_round,\n                       seqlet_aggregator,\n                       sign_consistency_func,\n                       spurious_merge_detector,\n                       similar_patterns_collapser,\n                       pattern_filterer,\n                       #seqlet_reassigner,\n                       final_postprocessor,\n                       subcluster_settings,\n                       n_cores,\n                       other_config={},\n                       verbose=True):\n\n        self.seqlets_sorter = seqlets_sorter\n        self.initclusterer_factory = initclusterer_factory\n        self.coarse_affmat_computer = coarse_affmat_computer\n        self.nearest_neighbors_to_compute = nearest_neighbors_to_compute\n        self.affmat_from_seqlets_with_nn_pairs =\\\n            affmat_from_seqlets_with_nn_pairs\n        self.filter_mask_from_correlation = filter_mask_from_correlation\n        self.filter_beyond_first_round = filter_beyond_first_round\n        self.skip_fine_grained = skip_fine_grained\n        self.aff_to_dist_mat = aff_to_dist_mat\n        self.tsne_perplexity = tsne_perplexity\n        #self.density_adapted_affmat_transformer =\\\n        #    density_adapted_affmat_transformer\n        self.clusterer_per_round = clusterer_per_round \n        self.seqlet_aggregator = seqlet_aggregator\n        self.sign_consistency_func = sign_consistency_func\n        \n        self.spurious_merge_detector = spurious_merge_detector\n        self.similar_patterns_collapser = similar_patterns_collapser\n        #self.seqlet_reassigner = seqlet_reassigner\n        self.pattern_filterer = pattern_filterer\n        self.final_postprocessor = final_postprocessor\n\n        self.verbose = verbose\n        self.subcluster_settings = subcluster_settings\n        self.n_cores = n_cores\n        self.other_config = other_config\n\n    def get_cluster_to_aggregate_motif(self, seqlets, cluster_indices,\n                                       sign_consistency_check,\n                                       min_seqlets_in_motif):\n        num_clusters = max(cluster_indices+1)\n        cluster_to_seqlets = defaultdict(list) \n        assert len(seqlets)==len(cluster_indices)\n        for seqlet,idx in zip(seqlets, cluster_indices):\n            cluster_to_seqlets[idx].append(seqlet)\n\n        cluster_to_motif = OrderedDict()\n        cluster_to_eliminated_motif = OrderedDict()\n        for i in range(num_clusters):\n            if (len(cluster_to_seqlets[i]) >= min_seqlets_in_motif):\n                if (self.verbose):\n                    print(\"Aggregating for cluster \"+str(i)+\" with \"\n                          +str(len(cluster_to_seqlets[i]))+\" seqlets\")\n                    print_memory_use()\n                    sys.stdout.flush()\n                motifs = self.seqlet_aggregator(cluster_to_seqlets[i])\n                assert len(motifs)<=1\n                if (len(motifs) > 0):\n                    motif = motifs[0]\n                    if (sign_consistency_check==False or\n                        self.sign_consistency_func(motif)):\n                        cluster_to_motif[i] = motif\n                    else:\n                        if (self.verbose):\n                            print(\"Dropping cluster \"+str(i)+\n                                  \" with \"+str(motif.num_seqlets)\n                                  +\" seqlets due to sign disagreement\")\n                        cluster_to_eliminated_motif[i] = motif\n        return cluster_to_motif, cluster_to_eliminated_motif\n\n    def do_density_adaptation(self, new_rows_distmat_nn, new_rows_nn,\n                                    new_rows_betas, new_rows_normfactors):\n        new_rows_densadapted_affmat_nn = []\n        for i in range(len(new_rows_distmat_nn)):\n            densadapted_row = []\n            for j,distance in zip(new_rows_nn[i], new_rows_distmat_nn[i]):\n                densadapted_row.append(np.sqrt(\n                  (np.exp(-distance/new_rows_betas[i])/new_rows_normfactors[i])\n                 *(np.exp(-distance/new_rows_betas[j])/\n                   new_rows_normfactors[j]))) \n            new_rows_densadapted_affmat_nn.append(densadapted_row)\n        return new_rows_densadapted_affmat_nn\n\n    def __call__(self, seqlets):\n\n        seqlets = self.seqlets_sorter(seqlets)\n        if (self.initclusterer_factory is not None):\n            initclusterer = self.initclusterer_factory(seqlets=seqlets) \n        else:\n            initclusterer = None\n\n        start = time.time()\n\n        #seqlets_sets = []\n        #coarse_affmats = []\n        #nn_affmats = []\n        #filtered_seqlets_sets = []\n        #filtered_affmats = []\n        #density_adapted_affmats = []\n        #cluster_results_sets = []\n        #cluster_to_motif_sets = []\n        #cluster_to_eliminated_motif_sets = []\n\n        if (initclusterer is not None):\n            each_round_initcluster_motifs = []\n        else:\n            each_round_initcluster_motifs = None\n\n        for round_idx, clusterer in enumerate(self.clusterer_per_round):\n            import gc\n            gc.collect()\n\n            round_num = round_idx+1\n\n            if (initclusterer is not None): \n                initclusters = initclusterer(seqlets=seqlets)\n                initcluster_motifs =\\\n                    list(self.get_cluster_to_aggregate_motif(\n                            seqlets=seqlets,\n                            cluster_indices=initclusters,\n                            sign_consistency_check=False,\n                            min_seqlets_in_motif=2)[0].values())\n                each_round_initcluster_motifs.append(initcluster_motifs)\n            else:\n                initclusters = None\n                initcluster_motifs = None\n            \n            if (len(seqlets)==0):\n                if (self.verbose):\n                    print(\"len(seqlets) is 0 - bailing!\")\n                return SeqletsToPatternsResults(\n                        each_round_initcluster_motifs=None,\n                        patterns=None,\n                        remaining_patterns=None,\n                        pattern_merge_hierarchy=None,\n                        cluster_results=None, \n                        total_time_taken=None,\n                        success=False,\n                        seqlets=None,\n                        affmat=None)\n\n            if (self.verbose):\n                print(\"(Round \"+str(round_num)+\n                      \") num seqlets: \"+str(len(seqlets)))\n                print(\"(Round \"+str(round_num)+\") Computing coarse affmat\")\n                print_memory_use()\n                sys.stdout.flush()\n            #coarse_affmat = self.coarse_affmat_computer(seqlets)\n            #coarse_affmats.append(coarse_affmat)\n            coarse_affmat_nn, seqlet_neighbors =\\\n                self.coarse_affmat_computer(seqlets, initclusters=initclusters)\n            gc.collect()\n\n            if (self.verbose):\n                print(\"(Round \"+str(round_num)+\") Computed coarse affmat\")\n                print_memory_use()\n                sys.stdout.flush()\n\n            if (self.skip_fine_grained==False):\n                #nn_start = time.time() \n                #if (self.verbose):\n                #    print(\"(Round \"+str(round_num)+\") Compute nearest neighbors\"\n                #          +\" from coarse affmat\")\n                #    print_memory_use()\n                #    sys.stdout.flush()\n\n                #seqlet_neighbors = get_seqlet_neighbors_with_initcluster(\n                #    nearest_neighbors_to_compute=\n                #     self.nearest_neighbors_to_compute,\n                #    coarse_affmat=coarse_affmat,\n                #    initclusters=initclusters)\n\n                #if (self.verbose):\n                #    print(\"Computed nearest neighbors in\",\n                #          round(time.time()-nn_start,2),\"s\")\n                #    print_memory_use()\n                #    sys.stdout.flush()\n\n                nn_affmat_start = time.time() \n                if (self.verbose):\n                    print(\"(Round \"+str(round_num)+\") Computing affinity matrix\"\n                          +\" on nearest neighbors\")\n                    print_memory_use()\n                    sys.stdout.flush()\n                #nn_affmat = self.affmat_from_seqlets_with_nn_pairs(\n                #                    seqlet_neighbors=seqlet_neighbors,\n                #                    seqlets=seqlets) \n                #nn_affmats.append(nn_affmat)\n\n                fine_affmat_nn = self.affmat_from_seqlets_with_nn_pairs(\n                                    seqlet_neighbors=seqlet_neighbors,\n                                    seqlets=seqlets,\n                                    return_sparse=True)\n                #get the fine_affmat_nn reorderings\n                reorderings = np.array([np.argsort(-finesimsinrow)\n                                        for finesimsinrow in fine_affmat_nn])\n\n                #reorder fine_affmat_nn, coarse_affmat_nn and seqlet_neighbors\n                # according to reorderings\n                fine_affmat_nn = [finesimsinrow[rowreordering]\n                                      for (finesimsinrow, rowreordering)\n                                      in zip(fine_affmat_nn, reorderings)]\n                coarse_affmat_nn = [coarsesimsinrow[rowreordering]\n                                      for (coarsesimsinrow, rowreordering)\n                                      in zip(coarse_affmat_nn, reorderings)]\n                seqlet_neighbors = [nnrow[rowreordering]\n                                      for (nnrow, rowreordering)\n                                      in zip(seqlet_neighbors, reorderings)]\n\n                del reorderings\n                gc.collect()\n                \n                if (self.verbose):\n                    print(\"(Round \"+str(round_num)+\") Computed affinity matrix\"\n                          +\" on nearest neighbors in\",\n                          round(time.time()-nn_affmat_start,2),\"s\")\n                    print_memory_use()\n                    sys.stdout.flush()\n\n                #filter by correlation\n                if (round_idx == 0 or self.filter_beyond_first_round==True):\n                    #the filter_mask_from_correlation function only operates\n                    # on columns in which np.abs(main_affmat) > 0\n                    #filtered_rows_mask = self.filter_mask_from_correlation(\n                    #                        main_affmat=nn_affmat,\n                    #                        other_affmat=coarse_affmat) \n                    filtered_rows_mask = self.filter_mask_from_correlation(\n                                            main_affmat=fine_affmat_nn,\n                                            other_affmat=coarse_affmat_nn)\n                    if (self.verbose):\n                        print(\"(Round \"+str(round_num)+\") Retained \"\n                              +str(np.sum(filtered_rows_mask))\n                              +\" rows out of \"+str(len(filtered_rows_mask))\n                              +\" after filtering\")\n                        print_memory_use()\n                        sys.stdout.flush()\n                else:\n                    filtered_rows_mask = np.array([True for x in seqlets])\n                    if (self.verbose):\n                        print(\"Not applying filtering for \"\n                              +\"rounds above first round\")\n                        print_memory_use()\n                        sys.stdout.flush()\n\n                del coarse_affmat_nn \n                gc.collect()\n\n                filtered_seqlets = [x[0] for x in\n                    zip(seqlets, filtered_rows_mask) if (x[1])]\n                if (initclusters is not None):\n                    filtered_initclusters = initclusters[filtered_rows_mask] \n                else:\n                    filtered_initclusters = None\n                #filtered_seqlets_sets.append(filtered_seqlets)\n\n                #filtered_affmat =\\\n                #    nn_affmat[filtered_rows_mask][:,filtered_rows_mask]\n                #del coarse_affmat\n                #del nn_affmat\n\n                #figure out a mapping from pre-filtering to the\n                # post-filtering indices\n                new_idx_mapping = (\n                    np.cumsum(1.0*(filtered_rows_mask)).astype(\"int\")-1)\n                retained_indices = set(np.arange(len(filtered_rows_mask))[\n                                                  filtered_rows_mask])\n                del filtered_rows_mask\n                filtered_neighbors = []\n                filtered_affmat_nn = []\n                for old_row_idx, (old_neighbors,affmat_row) in enumerate(\n                                    zip(seqlet_neighbors, fine_affmat_nn)): \n                    if old_row_idx in retained_indices:\n                        filtered_old_neighbors = [\n                            neighbor for neighbor in old_neighbors if neighbor\n                            in retained_indices]\n                        filtered_affmat_row = [\n                            affmatval for affmatval,neighbor\n                            in zip(affmat_row,old_neighbors)\n                            if neighbor in retained_indices]\n                        filtered_neighbors_row = [\n                            new_idx_mapping[neighbor] for neighbor\n                            in filtered_old_neighbors]\n                        filtered_neighbors.append(filtered_neighbors_row)\n                        filtered_affmat_nn.append(filtered_affmat_row)\n\n                #overwrite seqlet_neighbors...should be ok if the rows are\n                # not all the same length\n                seqlet_neighbors = filtered_neighbors\n                del (filtered_neighbors, retained_indices, new_idx_mapping)\n            else:\n                filtered_affmat = coarse_affmat_nn\n                filtered_seqlets = seqlets\n                if (initclusters is not None):\n                    filtered_initclusters = initclusters\n                else:\n                    filtered_initclusters = None\n\n            if (self.verbose):\n                print(\"(Round \"+str(round_num)+\") Computing density \"\n                      +\"adapted affmat\")\n                print_memory_use()\n                sys.stdout.flush() \n\n            #density_adapted_affmat =\\\n            #    self.density_adapted_affmat_transformer(filtered_affmat)\n            #del filtered_affmat\n            #density_adapted_affmats.append(density_adapted_affmat)\n\n            #apply aff_to_dist_mat one row at a time\n            distmat_nn = [self.aff_to_dist_mat(affinity_mat=x)\n                          for x in filtered_affmat_nn] \n            del filtered_affmat_nn\n\n            if (self.verbose):\n                print(\"Symmetrizing nearest neighbors\")\n            #Note: the fine-grained similarity metric isn't actually symmetric\n            # because a different input will get padded with zeros depending\n            # on which seqlets are specified as the filters and which seqlets\n            # are specified as the 'thing to scan'. So explicit symmetrization\n            # is worthwhile\n            sym_seqlet_neighbors, sym_distmat_nn = util.symmetrize_nn_distmat(\n                distmat_nn=distmat_nn, nn=seqlet_neighbors,\n                average_with_transpose=True)\n            del distmat_nn\n            del seqlet_neighbors\n\n            if (self.verbose):\n                print(\"Computing betas for density adaptation\")\n\n            #Compute beta values for the density adaptation. *store it*\n            betas_and_ps = Parallel(n_jobs=self.n_cores)(\n                     delayed(util.binary_search_perplexity)(\n                          self.tsne_perplexity, distances)\n                     for distances in sym_distmat_nn)\n            betas = np.array([x[0] for x in betas_and_ps])\n\n            if (self.verbose):\n                print(\"Computing normalizing denominators\")\n\n            #also compute the normalization factor needed to get probs to sum to 1\n            #note: sticking to lists here because different rows of\n            # sym_distmat_nn may have different lengths after adding in\n            # the symmetric pairs\n            densadapted_affmat_nn_unnorm = [np.exp(-np.array(distmat_row)/beta)\n                for distmat_row, beta in zip(sym_distmat_nn, betas)]\n            normfactors = np.array([max(np.sum(x),1e-8) for x in\n                                    densadapted_affmat_nn_unnorm])\n\n            sym_densadapted_affmat_nn = self.do_density_adaptation(\n                new_rows_distmat_nn=sym_distmat_nn,\n                new_rows_nn=sym_seqlet_neighbors,\n                new_rows_betas=betas,\n                new_rows_normfactors=normfactors)\n\n            util.verify_symmetric_nn_affmat(\n                affmat_nn=sym_densadapted_affmat_nn,\n                nn=sym_seqlet_neighbors)\n\n            #Make csr matrix\n            csr_density_adapted_affmat =\\\n                util.coo_matrix_from_neighborsformat(\n                    entries=sym_densadapted_affmat_nn,\n                    neighbors=sym_seqlet_neighbors,\n                    ncols=len(sym_densadapted_affmat_nn)).tocsr()\n\n            if (self.verbose):\n                print(\"(Round \"+str(round_num)+\") Computing clustering\")\n                print_memory_use()\n                sys.stdout.flush() \n\n            #cluster_results = clusterer(density_adapted_affmat,\n            #                            initclusters=filtered_initclusters)\n            #del density_adapted_affmat\n            #cluster_results_sets.append(cluster_results)\n            cluster_results = clusterer(csr_density_adapted_affmat,\n                                        initclusters=filtered_initclusters)\n            del csr_density_adapted_affmat\n\n            num_clusters = max(cluster_results.cluster_indices+1)\n            cluster_idx_counts = Counter(cluster_results.cluster_indices)\n            if (self.verbose):\n                print(\"Got \"+str(num_clusters)\n                      +\" clusters after round \"+str(round_num))\n                print(\"Counts:\")\n                print(dict([x for x in cluster_idx_counts.items()]))\n                print_memory_use()\n                sys.stdout.flush()\n\n            if (self.verbose):\n                print(\"(Round \"+str(round_num)+\") Aggregating seqlets\"\n                      +\" in each cluster\")\n                print_memory_use()\n                sys.stdout.flush()\n\n            cluster_to_motif, cluster_to_eliminated_motif =\\\n                self.get_cluster_to_aggregate_motif(\n                    seqlets=filtered_seqlets,\n                    cluster_indices=cluster_results.cluster_indices,\n                    sign_consistency_check=True,\n                    min_seqlets_in_motif=0)\n\n            #obtain unique seqlets from adjusted motifs\n            seqlets = list(dict([(y.exidx_start_end_string, y)\n                             for x in cluster_to_motif.values()\n                             for y in x.seqlets]).values())\n\n        if (self.verbose):\n            print(\"Got \"+str(len(cluster_to_motif.values()))+\" clusters\")\n            print(\"Splitting into subclusters...\")\n            print_memory_use()\n            sys.stdout.flush()\n\n        split_patterns = self.spurious_merge_detector(\n                            cluster_to_motif.values())\n\n        if (len(split_patterns)==0):\n            if (self.verbose):\n                print(\"No more surviving patterns - bailing!\")\n            return SeqletsToPatternsResults(\n                    each_round_initcluster_motifs=None,\n                    patterns=None,\n                    remaining_patterns=None,\n                    pattern_merge_hierarchy=None,\n                    cluster_results=None, \n                    total_time_taken=None,\n                    success=False,\n                    seqlets=None,\n                    affmat=None)\n\n        #Now start merging patterns \n        if (self.verbose):\n            print(\"Merging on \"+str(len(split_patterns))+\" clusters\")\n            print_memory_use()\n            sys.stdout.flush()\n        merged_patterns, pattern_merge_hierarchy =\\\n            self.similar_patterns_collapser( \n                patterns=split_patterns) \n        merged_patterns = sorted(merged_patterns, key=lambda x: -x.num_seqlets)\n        if (self.verbose):\n            print(\"Got \"+str(len(merged_patterns))+\" patterns after merging\")\n            print_memory_use()\n            sys.stdout.flush()\n\n        if (self.verbose):\n            print(\"Performing filtering\")\n            print_memory_use()\n            sys.stdout.flush()\n\n        final_patterns, remaining_patterns = self.pattern_filterer(\n                                                    merged_patterns)\n        #reassigned_patterns = self.seqlet_reassigner(merged_patterns)\n        final_patterns = self.final_postprocessor(final_patterns)\n        remaining_patterns =\\\n            self.final_postprocessor(remaining_patterns)\n\n        if (self.verbose):\n            print(\"Got \"+str(len(final_patterns))\n                  +\" patterns after filtering\")\n            print_memory_use()\n            sys.stdout.flush()\n\n        total_time_taken = round(time.time()-start,2)\n        if (self.verbose):\n            print(\"Total time taken is \"\n                  +str(total_time_taken)+\"s\")\n            print_memory_use()\n            sys.stdout.flush()\n\n        #apply subclustering procedure on the final patterns\n        print(\"Applying subclustering to the final motifs\")\n        for patternidx, pattern in enumerate(final_patterns):\n            print(\"On pattern\",patternidx)\n            pattern.compute_subclusters_and_embedding(\n                verbose=self.verbose,\n                **self.subcluster_settings)\n\n        results = SeqletsToPatternsResults(\n            each_round_initcluster_motifs=each_round_initcluster_motifs,             \n            patterns=final_patterns,\n            remaining_patterns=remaining_patterns,\n            seqlets=filtered_seqlets, #last stage of filtered seqlets\n            #affmat=filtered_affmat,\n            cluster_results=cluster_results, \n            total_time_taken=total_time_taken,\n           \n            #seqlets_sets=seqlets_sets,\n            #coarse_affmats=coarse_affmats,\n            #nn_affmats=nn_affmats,\n            #filtered_seqlets_sets=filtered_seqlets_sets,\n            #filtered_affmats=filtered_affmats,\n            #density_adapted_affmats=density_adapted_affmats,\n            #cluster_results_sets=cluster_results_sets,\n            #cluster_to_motif_sets=cluster_to_motif_sets,\n            #cluster_to_eliminated_motif_sets=cluster_to_eliminated_motif_sets,\n\n            merged_patterns=merged_patterns,\n            pattern_merge_hierarchy=pattern_merge_hierarchy,\n            #reassigned_patterns=reassigned_patterns\n        )\n\n        return results\n", "meta": {"hexsha": "65a2a4a0319cf5fc0d5c564e05aa342c6fb5c5ee", "size": 55786, "ext": "py", "lang": "Python", "max_stars_repo_path": "modisco/tfmodisco_workflow/seqlets_to_patterns.py", "max_stars_repo_name": "kundajelab/tfmodisco", "max_stars_repo_head_hexsha": "cb2ec8ee33cbea1fe00ea41292075c8df4eabf44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70, "max_stars_repo_stars_event_min_datetime": "2018-05-21T01:47:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T04:15:27.000Z", "max_issues_repo_path": "modisco/tfmodisco_workflow/seqlets_to_patterns.py", "max_issues_repo_name": "kundajelab/tfmodisco", "max_issues_repo_head_hexsha": "cb2ec8ee33cbea1fe00ea41292075c8df4eabf44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2018-06-04T21:39:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T15:24:11.000Z", "max_forks_repo_path": "modisco/tfmodisco_workflow/seqlets_to_patterns.py", "max_forks_repo_name": "kundajelab/tfmodisco", "max_forks_repo_head_hexsha": "cb2ec8ee33cbea1fe00ea41292075c8df4eabf44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2018-06-04T19:51:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T23:27:18.000Z", "avg_line_length": 45.9901071723, "max_line_length": 85, "alphanum_fraction": 0.5851826623, "include": true, "reason": "import numpy", "num_tokens": 10844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3451052776934245, "lm_q1q2_score": 0.190017507783084}}
{"text": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\nfrom collections import namedtuple\nfrom contextlib import contextmanager\nfrom functools import partial\nfrom typing import Callable, Dict, List, Optional\nimport warnings\n\nimport numpy as np\n\nimport jax\nfrom jax import device_get, jacfwd, lax, random, tree_flatten, value_and_grad\nfrom jax.flatten_util import ravel_pytree\nfrom jax.lax import broadcast_shapes\nimport jax.numpy as jnp\nfrom jax.tree_util import tree_map\n\nimport numpyro\nfrom numpyro.distributions import constraints\nfrom numpyro.distributions.transforms import biject_to\nfrom numpyro.distributions.util import is_identically_one, sum_rightmost\nfrom numpyro.handlers import condition, replay, seed, substitute, trace\nfrom numpyro.infer.initialization import init_to_uniform, init_to_value\nfrom numpyro.util import (\n    _validate_model,\n    find_stack_level,\n    not_jax_tracer,\n    soft_vmap,\n    while_loop,\n)\n\n__all__ = [\n    \"find_valid_initial_params\",\n    \"get_potential_fn\",\n    \"log_density\",\n    \"log_likelihood\",\n    \"potential_energy\",\n    \"initialize_model\",\n    \"Predictive\",\n]\n\nModelInfo = namedtuple(\n    \"ModelInfo\", [\"param_info\", \"potential_fn\", \"postprocess_fn\", \"model_trace\"]\n)\nParamInfo = namedtuple(\"ParamInfo\", [\"z\", \"potential_energy\", \"z_grad\"])\n\n\ndef log_density(model, model_args, model_kwargs, params):\n    \"\"\"\n    (EXPERIMENTAL INTERFACE) Computes log of joint density for the model given\n    latent values ``params``.\n\n    :param model: Python callable containing NumPyro primitives.\n    :param tuple model_args: args provided to the model.\n    :param dict model_kwargs: kwargs provided to the model.\n    :param dict params: dictionary of current parameter values keyed by site\n        name.\n    :return: log of joint density and a corresponding model trace\n    \"\"\"\n    model = substitute(model, data=params)\n    model_trace = trace(model).get_trace(*model_args, **model_kwargs)\n    log_joint = jnp.zeros(())\n    for site in model_trace.values():\n        if site[\"type\"] == \"sample\":\n            value = site[\"value\"]\n            intermediates = site[\"intermediates\"]\n            scale = site[\"scale\"]\n            if intermediates:\n                log_prob = site[\"fn\"].log_prob(value, intermediates)\n            else:\n                guide_shape = jnp.shape(value)\n                model_shape = tuple(\n                    site[\"fn\"].shape()\n                )  # TensorShape from tfp needs casting to tuple\n                try:\n                    broadcast_shapes(guide_shape, model_shape)\n                except ValueError:\n                    raise ValueError(\n                        \"Model and guide shapes disagree at site: '{}': {} vs {}\".format(\n                            site[\"name\"], model_shape, guide_shape\n                        )\n                    )\n                log_prob = site[\"fn\"].log_prob(value)\n\n            if (scale is not None) and (not is_identically_one(scale)):\n                log_prob = scale * log_prob\n\n            log_prob = jnp.sum(log_prob)\n            log_joint = log_joint + log_prob\n    return log_joint, model_trace\n\n\nclass _without_rsample_stop_gradient(numpyro.primitives.Messenger):\n    \"\"\"\n    Stop gradient for samples at latent sample sites for which has_rsample=False.\n    \"\"\"\n\n    def postprocess_message(self, msg):\n        if (\n            msg[\"type\"] == \"sample\"\n            and (not msg[\"is_observed\"])\n            and (not msg[\"fn\"].has_rsample)\n        ):\n            msg[\"value\"] = lax.stop_gradient(msg[\"value\"])\n            # TODO: reconsider this logic\n            # here we clear all the cached value so that gradients of log_prob(value) w.r.t.\n            # all parameters of the transformed distributions match the behavior of\n            # TransformedDistribution(d, transform) in Pyro with transform.cache_size == 0\n            msg[\"intermediates\"] = None\n\n\ndef get_importance_trace(model, guide, args, kwargs, params):\n    \"\"\"\n    (EXPERIMENTAL) Returns traces from the guide and the model that is run against it.\n    The returned traces also store the log probability at each site.\n\n    .. note:: Gradients are blocked at latent sites which do not have reparametrized samplers.\n    \"\"\"\n    guide = substitute(guide, data=params)\n    with _without_rsample_stop_gradient():\n        guide_trace = trace(guide).get_trace(*args, **kwargs)\n    model = substitute(replay(model, guide_trace), data=params)\n    model_trace = trace(model).get_trace(*args, **kwargs)\n    for tr in (guide_trace, model_trace):\n        for site in tr.values():\n            if site[\"type\"] == \"sample\":\n                if \"log_prob\" not in site:\n                    value = site[\"value\"]\n                    intermediates = site[\"intermediates\"]\n                    scale = site[\"scale\"]\n                    if intermediates:\n                        log_prob = site[\"fn\"].log_prob(value, intermediates)\n                    else:\n                        log_prob = site[\"fn\"].log_prob(value)\n\n                    if (scale is not None) and (not is_identically_one(scale)):\n                        log_prob = scale * log_prob\n                    site[\"log_prob\"] = log_prob\n    return model_trace, guide_trace\n\n\ndef transform_fn(transforms, params, invert=False):\n    \"\"\"\n    (EXPERIMENTAL INTERFACE) Callable that applies a transformation from the `transforms`\n    dict to values in the `params` dict and returns the transformed values keyed on\n    the same names.\n\n    :param transforms: Dictionary of transforms keyed by names. Names in\n        `transforms` and `params` should align.\n    :param params: Dictionary of arrays keyed by names.\n    :param invert: Whether to apply the inverse of the transforms.\n    :return: `dict` of transformed params.\n    \"\"\"\n    if invert:\n        transforms = {k: v.inv for k, v in transforms.items()}\n    return {k: transforms[k](v) if k in transforms else v for k, v in params.items()}\n\n\ndef constrain_fn(model, model_args, model_kwargs, params, return_deterministic=False):\n    \"\"\"\n    (EXPERIMENTAL INTERFACE) Gets value at each latent site in `model` given\n    unconstrained parameters `params`. The `transforms` is used to transform these\n    unconstrained parameters to base values of the corresponding priors in `model`.\n    If a prior is a transformed distribution, the corresponding base value lies in\n    the support of base distribution. Otherwise, the base value lies in the support\n    of the distribution.\n\n    :param model: a callable containing NumPyro primitives.\n    :param tuple model_args: args provided to the model.\n    :param dict model_kwargs: kwargs provided to the model.\n    :param dict params: dictionary of unconstrained values keyed by site\n        names.\n    :param bool return_deterministic: whether to return the value of `deterministic`\n        sites from the model. Defaults to `False`.\n    :return: `dict` of transformed params.\n    \"\"\"\n\n    def substitute_fn(site):\n        if site[\"name\"] in params:\n            if site[\"type\"] == \"sample\":\n                with helpful_support_errors(site):\n                    return biject_to(site[\"fn\"].support)(params[site[\"name\"]])\n            else:\n                return params[site[\"name\"]]\n\n    substituted_model = substitute(model, substitute_fn=substitute_fn)\n    model_trace = trace(substituted_model).get_trace(*model_args, **model_kwargs)\n    return {\n        k: v[\"value\"]\n        for k, v in model_trace.items()\n        if (k in params) or (return_deterministic and (v[\"type\"] == \"deterministic\"))\n    }\n\n\ndef _unconstrain_reparam(params, site):\n    name = site[\"name\"]\n    if name in params:\n        p = params[name]\n        support = site[\"fn\"].support\n        with helpful_support_errors(site):\n            t = biject_to(support)\n        # in scan, we might only want to substitute an item at index i, rather than the whole sequence\n        i = site[\"infer\"].get(\"_scan_current_index\", None)\n        if i is not None:\n            event_dim_shift = t.codomain.event_dim - t.domain.event_dim\n            expected_unconstrained_dim = len(site[\"fn\"].shape()) - event_dim_shift\n            # check if p has additional time dimension\n            if jnp.ndim(p) > expected_unconstrained_dim:\n                p = p[i]\n\n        if support in [constraints.real, constraints.real_vector]:\n            return p\n        value = t(p)\n\n        log_det = t.log_abs_det_jacobian(p, value)\n        log_det = sum_rightmost(\n            log_det, jnp.ndim(log_det) - jnp.ndim(value) + len(site[\"fn\"].event_shape)\n        )\n        if site[\"scale\"] is not None:\n            log_det = site[\"scale\"] * log_det\n        numpyro.factor(\"_{}_log_det\".format(name), log_det)\n        return value\n\n\ndef potential_energy(model, model_args, model_kwargs, params, enum=False):\n    \"\"\"\n    (EXPERIMENTAL INTERFACE) Computes potential energy of a model given unconstrained params.\n    Under the hood, we will transform these unconstrained parameters to the values\n    belong to the supports of the corresponding priors in `model`.\n\n    :param model: a callable containing NumPyro primitives.\n    :param tuple model_args: args provided to the model.\n    :param dict model_kwargs: kwargs provided to the model.\n    :param dict params: unconstrained parameters of `model`.\n    :param bool enum: whether to enumerate over discrete latent sites.\n    :return: potential energy given unconstrained parameters.\n    \"\"\"\n    if enum:\n        from numpyro.contrib.funsor import log_density as log_density_\n    else:\n        log_density_ = log_density\n\n    substituted_model = substitute(\n        model, substitute_fn=partial(_unconstrain_reparam, params)\n    )\n    # no param is needed for log_density computation because we already substitute\n    log_joint, model_trace = log_density_(\n        substituted_model, model_args, model_kwargs, {}\n    )\n    return -log_joint\n\n\ndef _init_to_unconstrained_value(site=None, values={}):\n    if site is None:\n        return partial(_init_to_unconstrained_value, values=values)\n\n\ndef find_valid_initial_params(\n    rng_key,\n    model,\n    *,\n    init_strategy=init_to_uniform,\n    enum=False,\n    model_args=(),\n    model_kwargs=None,\n    prototype_params=None,\n    forward_mode_differentiation=False,\n    validate_grad=True,\n):\n    \"\"\"\n    (EXPERIMENTAL INTERFACE) Given a model with Pyro primitives, returns an initial\n    valid unconstrained value for all the parameters. This function also returns\n    the corresponding potential energy, the gradients, and an\n    `is_valid` flag to say whether the initial parameters are valid. Parameter values\n    are considered valid if the values and the gradients for the log density have\n    finite values.\n\n    :param jax.random.PRNGKey rng_key: random number generator seed to\n        sample from the prior. The returned `init_params` will have the\n        batch shape ``rng_key.shape[:-1]``.\n    :param model: Python callable containing Pyro primitives.\n    :param callable init_strategy: a per-site initialization function.\n    :param bool enum: whether to enumerate over discrete latent sites.\n    :param tuple model_args: args provided to the model.\n    :param dict model_kwargs: kwargs provided to the model.\n    :param dict prototype_params: an optional prototype parameters, which is used\n        to define the shape for initial parameters.\n    :param bool forward_mode_differentiation: whether to use forward-mode differentiation\n        or reverse-mode differentiation. Defaults to False.\n    :param bool validate_grad: whether to validate gradient of the initial params.\n        Defaults to True.\n    :return: tuple of `init_params_info` and `is_valid`, where `init_params_info` is the tuple\n        containing the initial params, their potential energy, and their gradients.\n    \"\"\"\n    model_kwargs = {} if model_kwargs is None else model_kwargs\n    init_strategy = (\n        init_strategy if isinstance(init_strategy, partial) else init_strategy()\n    )\n    # handle those init strategies differently to save computation\n    if init_strategy.func is init_to_uniform:\n        radius = init_strategy.keywords.get(\"radius\")\n        init_values = {}\n    elif init_strategy.func is _init_to_unconstrained_value:\n        radius = 2\n        init_values = init_strategy.keywords.get(\"values\")\n    else:\n        radius = None\n\n    def cond_fn(state):\n        i, _, _, is_valid = state\n        return (i < 100) & (~is_valid)\n\n    def body_fn(state):\n        i, key, _, _ = state\n        key, subkey = random.split(key)\n\n        if radius is None or prototype_params is None:\n            # XXX: we don't want to apply enum to draw latent samples\n            model_ = model\n            if enum:\n                from numpyro.contrib.funsor import enum as enum_handler\n\n                if isinstance(model, substitute) and isinstance(model.fn, enum_handler):\n                    model_ = substitute(model.fn.fn, data=model.data)\n                elif isinstance(model, enum_handler):\n                    model_ = model.fn\n\n            # Wrap model in a `substitute` handler to initialize from `init_loc_fn`.\n            seeded_model = substitute(seed(model_, subkey), substitute_fn=init_strategy)\n            model_trace = trace(seeded_model).get_trace(*model_args, **model_kwargs)\n            constrained_values, inv_transforms = {}, {}\n            for k, v in model_trace.items():\n                if (\n                    v[\"type\"] == \"sample\"\n                    and not v[\"is_observed\"]\n                    and not v[\"fn\"].support.is_discrete\n                ):\n                    constrained_values[k] = v[\"value\"]\n                    with helpful_support_errors(v):\n                        inv_transforms[k] = biject_to(v[\"fn\"].support)\n            params = transform_fn(\n                inv_transforms,\n                {k: v for k, v in constrained_values.items()},\n                invert=True,\n            )\n        else:  # this branch doesn't require tracing the model\n            params = {}\n            for k, v in prototype_params.items():\n                if k in init_values:\n                    params[k] = init_values[k]\n                else:\n                    params[k] = random.uniform(\n                        subkey, jnp.shape(v), minval=-radius, maxval=radius\n                    )\n                    key, subkey = random.split(key)\n\n        potential_fn = partial(\n            potential_energy, model, model_args, model_kwargs, enum=enum\n        )\n        if validate_grad:\n            if forward_mode_differentiation:\n                pe = potential_fn(params)\n                z_grad = jacfwd(potential_fn)(params)\n            else:\n                pe, z_grad = value_and_grad(potential_fn)(params)\n            z_grad_flat = ravel_pytree(z_grad)[0]\n            is_valid = jnp.isfinite(pe) & jnp.all(jnp.isfinite(z_grad_flat))\n        else:\n            pe = potential_fn(params)\n            is_valid = jnp.isfinite(pe)\n            z_grad = None\n\n        return i + 1, key, (params, pe, z_grad), is_valid\n\n    def _find_valid_params(rng_key, exit_early=False):\n        init_state = (0, rng_key, (prototype_params, 0.0, prototype_params), False)\n        if exit_early and not_jax_tracer(rng_key):\n            # Early return if valid params found. This is only helpful for single chain,\n            # where we can avoid compiling body_fn in while_loop.\n            _, _, (init_params, pe, z_grad), is_valid = init_state = body_fn(init_state)\n            if not_jax_tracer(is_valid):\n                if device_get(is_valid):\n                    return (init_params, pe, z_grad), is_valid\n\n        # XXX: this requires compiling the model, so for multi-chain, we trace the model 2-times\n        # even if the init_state is a valid result\n        _, _, (init_params, pe, z_grad), is_valid = while_loop(\n            cond_fn, body_fn, init_state\n        )\n        return (init_params, pe, z_grad), is_valid\n\n    # Handle possible vectorization\n    if rng_key.ndim == 1:\n        (init_params, pe, z_grad), is_valid = _find_valid_params(\n            rng_key, exit_early=True\n        )\n    else:\n        (init_params, pe, z_grad), is_valid = lax.map(_find_valid_params, rng_key)\n    return (init_params, pe, z_grad), is_valid\n\n\ndef _get_model_transforms(model, model_args=(), model_kwargs=None):\n    model_kwargs = {} if model_kwargs is None else model_kwargs\n    model_trace = trace(model).get_trace(*model_args, **model_kwargs)\n    inv_transforms = {}\n    # model code may need to be replayed in the presence of deterministic sites\n    replay_model = False\n    has_enumerate_support = False\n    for k, v in model_trace.items():\n        if v[\"type\"] == \"sample\" and not v[\"is_observed\"]:\n            if v[\"fn\"].support.is_discrete:\n                enum_type = v[\"infer\"].get(\"enumerate\")\n                if enum_type is not None and (enum_type != \"parallel\"):\n                    raise RuntimeError(\n                        \"This algorithm might only work for discrete sites with\"\n                        f\" enumerate marked 'parallel'. But the site {k} is marked\"\n                        f\" as '{enum_type}'.\"\n                    )\n                has_enumerate_support = True\n                if not v[\"fn\"].has_enumerate_support:\n                    dist_name = type(v[\"fn\"]).__name__\n                    raise RuntimeError(\n                        \"This algorithm might only work for discrete sites with\"\n                        f\" enumerate support. But the {dist_name} distribution at\"\n                        f\" site {k} does not have enumerate support.\"\n                    )\n                if enum_type is None:\n                    warnings.warn(\n                        \"Some algorithms will automatically enumerate the discrete\"\n                        f\" latent site {k} of your model. In the future,\"\n                        \" enumerated sites need to be marked with\"\n                        \" `infer={'enumerate': 'parallel'}`.\",\n                        FutureWarning,\n                        stacklevel=find_stack_level(),\n                    )\n            else:\n                support = v[\"fn\"].support\n                with helpful_support_errors(v, raise_warnings=True):\n                    inv_transforms[k] = biject_to(support)\n                # XXX: the following code filters out most situations with dynamic supports\n                args = ()\n                if isinstance(support, constraints._GreaterThan):\n                    args = (\"lower_bound\",)\n                elif isinstance(support, constraints._Interval):\n                    args = (\"lower_bound\", \"upper_bound\")\n                for arg in args:\n                    if not isinstance(getattr(support, arg), (int, float)):\n                        replay_model = True\n        elif v[\"type\"] == \"deterministic\":\n            replay_model = True\n    return inv_transforms, replay_model, has_enumerate_support, model_trace\n\n\ndef _partial_args_kwargs(fn, *args, **kwargs):\n    \"\"\"Returns a partial function of `fn` and args, kwargs.\"\"\"\n    return partial(fn, args, kwargs)\n\n\ndef _drop_args_kwargs(fn, *args, **kwargs):\n    \"\"\"Returns the input function `fn`, ignoring args and kwargs.\"\"\"\n    return fn\n\n\ndef get_potential_fn(\n    model,\n    inv_transforms,\n    *,\n    enum=False,\n    replay_model=False,\n    dynamic_args=False,\n    model_args=(),\n    model_kwargs=None,\n):\n    \"\"\"\n    (EXPERIMENTAL INTERFACE) Given a model with Pyro primitives, returns a\n    function which, given unconstrained parameters, evaluates the potential\n    energy (negative log joint density). In addition, this returns a\n    function to transform unconstrained values at sample sites to constrained\n    values within their respective support.\n\n    :param model: Python callable containing Pyro primitives.\n    :param dict inv_transforms: dictionary of transforms keyed by names.\n    :param bool enum: whether to enumerate over discrete latent sites.\n    :param bool replay_model: whether we need to replay model in\n        `postprocess_fn` to obtain `deterministic` sites.\n    :param bool dynamic_args: if `True`, the `potential_fn` and\n        `constraints_fn` are themselves dependent on model arguments.\n        When provided a `*model_args, **model_kwargs`, they return\n        `potential_fn` and `constraints_fn` callables, respectively.\n    :param tuple model_args: args provided to the model.\n    :param dict model_kwargs: kwargs provided to the model.\n    :return: tuple of (`potential_fn`, `postprocess_fn`). The latter is used\n        to constrain unconstrained samples (e.g. those returned by HMC)\n        to values that lie within the site's support, and return values at\n        `deterministic` sites in the model.\n    \"\"\"\n    if dynamic_args:\n        potential_fn = partial(\n            _partial_args_kwargs, partial(potential_energy, model, enum=enum)\n        )\n        if replay_model:\n            # XXX: we seed to sample discrete sites (but not collect them)\n            model_ = seed(model.fn, 0) if enum else model\n            postprocess_fn = partial(\n                _partial_args_kwargs,\n                partial(constrain_fn, model, return_deterministic=True),\n            )\n        else:\n            postprocess_fn = partial(\n                _drop_args_kwargs, partial(transform_fn, inv_transforms)\n            )\n    else:\n        model_kwargs = {} if model_kwargs is None else model_kwargs\n        potential_fn = partial(\n            potential_energy, model, model_args, model_kwargs, enum=enum\n        )\n        if replay_model:\n            model_ = seed(model.fn, 0) if enum else model\n            postprocess_fn = partial(\n                constrain_fn,\n                model_,\n                model_args,\n                model_kwargs,\n                return_deterministic=True,\n            )\n        else:\n            postprocess_fn = partial(transform_fn, inv_transforms)\n\n    return potential_fn, postprocess_fn\n\n\ndef _guess_max_plate_nesting(model_trace):\n    \"\"\"\n    Guesses max_plate_nesting by using model trace.\n    This optimistically assumes static model\n    structure.\n    \"\"\"\n    sites = [site for site in model_trace.values() if site[\"type\"] == \"sample\"]\n\n    dims = [\n        frame.dim\n        for site in sites\n        for frame in site[\"cond_indep_stack\"]\n        if frame.dim is not None\n    ]\n    max_plate_nesting = -min(dims) if dims else 0\n    return max_plate_nesting\n\n\ndef initialize_model(\n    rng_key,\n    model,\n    *,\n    init_strategy=init_to_uniform,\n    dynamic_args=False,\n    model_args=(),\n    model_kwargs=None,\n    forward_mode_differentiation=False,\n    validate_grad=True,\n):\n    \"\"\"\n    (EXPERIMENTAL INTERFACE) Helper function that calls :func:`~numpyro.infer.util.get_potential_fn`\n    and :func:`~numpyro.infer.util.find_valid_initial_params` under the hood\n    to return a tuple of (`init_params_info`, `potential_fn`, `postprocess_fn`, `model_trace`).\n\n    :param jax.random.PRNGKey rng_key: random number generator seed to\n        sample from the prior. The returned `init_params` will have the\n        batch shape ``rng_key.shape[:-1]``.\n    :param model: Python callable containing Pyro primitives.\n    :param callable init_strategy: a per-site initialization function.\n        See :ref:`init_strategy` section for available functions.\n    :param bool dynamic_args: if `True`, the `potential_fn` and\n        `constraints_fn` are themselves dependent on model arguments.\n        When provided a `*model_args, **model_kwargs`, they return\n        `potential_fn` and `constraints_fn` callables, respectively.\n    :param tuple model_args: args provided to the model.\n    :param dict model_kwargs: kwargs provided to the model.\n    :param bool forward_mode_differentiation: whether to use forward-mode differentiation\n        or reverse-mode differentiation. By default, we use reverse mode but the forward\n        mode can be useful in some cases to improve the performance. In addition, some\n        control flow utility on JAX such as `jax.lax.while_loop` or `jax.lax.fori_loop`\n        only supports forward-mode differentiation. See\n        `JAX's The Autodiff Cookbook <https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html>`_\n        for more information.\n    :param bool validate_grad: whether to validate gradient of the initial params.\n        Defaults to True.\n    :return: a namedtupe `ModelInfo` which contains the fields\n        (`param_info`, `potential_fn`, `postprocess_fn`, `model_trace`), where\n        `param_info` is a namedtuple `ParamInfo` containing values from the prior\n        used to initiate MCMC, their corresponding potential energy, and their gradients;\n        `postprocess_fn` is a callable that uses inverse transforms\n        to convert unconstrained HMC samples to constrained values that\n        lie within the site's support, in addition to returning values\n        at `deterministic` sites in the model.\n    \"\"\"\n    model_kwargs = {} if model_kwargs is None else model_kwargs\n    substituted_model = substitute(\n        seed(model, rng_key if jnp.ndim(rng_key) == 1 else rng_key[0]),\n        substitute_fn=init_strategy,\n    )\n    (\n        inv_transforms,\n        replay_model,\n        has_enumerate_support,\n        model_trace,\n    ) = _get_model_transforms(substituted_model, model_args, model_kwargs)\n    # substitute param sites from model_trace to model so\n    # we don't need to generate again parameters of `numpyro.module`\n    model = substitute(\n        model,\n        data={\n            k: site[\"value\"]\n            for k, site in model_trace.items()\n            if site[\"type\"] in [\"param\"]\n        },\n    )\n    constrained_values = {\n        k: v[\"value\"]\n        for k, v in model_trace.items()\n        if v[\"type\"] == \"sample\"\n        and not v[\"is_observed\"]\n        and not v[\"fn\"].support.is_discrete\n    }\n\n    if has_enumerate_support:\n        from numpyro.contrib.funsor import config_enumerate, enum\n\n        if not isinstance(model, enum):\n            max_plate_nesting = _guess_max_plate_nesting(model_trace)\n            _validate_model(model_trace, plate_warning=\"error\")\n            model = enum(config_enumerate(model), -max_plate_nesting - 1)\n    else:\n        _validate_model(model_trace, plate_warning=\"loose\")\n\n    potential_fn, postprocess_fn = get_potential_fn(\n        model,\n        inv_transforms,\n        replay_model=replay_model,\n        enum=has_enumerate_support,\n        dynamic_args=dynamic_args,\n        model_args=model_args,\n        model_kwargs=model_kwargs,\n    )\n\n    init_strategy = (\n        init_strategy if isinstance(init_strategy, partial) else init_strategy()\n    )\n    if (init_strategy.func is init_to_value) and not replay_model:\n        init_values = init_strategy.keywords.get(\"values\")\n        unconstrained_values = transform_fn(inv_transforms, init_values, invert=True)\n        init_strategy = _init_to_unconstrained_value(values=unconstrained_values)\n    prototype_params = transform_fn(inv_transforms, constrained_values, invert=True)\n    (init_params, pe, grad), is_valid = find_valid_initial_params(\n        rng_key,\n        substitute(\n            model,\n            data={\n                k: site[\"value\"]\n                for k, site in model_trace.items()\n                if site[\"type\"] in [\"plate\"]\n            },\n        ),\n        init_strategy=init_strategy,\n        enum=has_enumerate_support,\n        model_args=model_args,\n        model_kwargs=model_kwargs,\n        prototype_params=prototype_params,\n        forward_mode_differentiation=forward_mode_differentiation,\n        validate_grad=validate_grad,\n    )\n\n    if not_jax_tracer(is_valid):\n        if device_get(~jnp.all(is_valid)):\n            with numpyro.validation_enabled(), trace() as tr:\n                # validate parameters\n                substituted_model(*model_args, **model_kwargs)\n                # validate values\n                for site in tr.values():\n                    if site[\"type\"] == \"sample\":\n                        with warnings.catch_warnings(record=True) as ws:\n                            site[\"fn\"]._validate_sample(site[\"value\"])\n                        if len(ws) > 0:\n                            for w in ws:\n                                # at site information to the warning message\n                                w.message.args = (\n                                    \"Site {}: {}\".format(\n                                        site[\"name\"], w.message.args[0]\n                                    ),\n                                ) + w.message.args[1:]\n                                warnings.showwarning(\n                                    w.message,\n                                    w.category,\n                                    w.filename,\n                                    w.lineno,\n                                    file=w.file,\n                                    line=w.line,\n                                )\n            raise RuntimeError(\n                \"Cannot find valid initial parameters. Please check your model again.\"\n            )\n    return ModelInfo(\n        ParamInfo(init_params, pe, grad), potential_fn, postprocess_fn, model_trace\n    )\n\n\ndef _predictive(\n    rng_key,\n    model,\n    posterior_samples,\n    batch_shape,\n    return_sites=None,\n    infer_discrete=False,\n    parallel=True,\n    model_args=(),\n    model_kwargs={},\n):\n    masked_model = numpyro.handlers.mask(model, mask=False)\n    if infer_discrete:\n        # inspect the model to get some structure\n        rng_key, subkey = random.split(rng_key)\n        batch_ndim = len(batch_shape)\n        prototype_sample = tree_map(\n            lambda x: jnp.reshape(x, (-1,) + jnp.shape(x)[batch_ndim:])[0],\n            posterior_samples,\n        )\n        prototype_trace = trace(\n            seed(substitute(masked_model, prototype_sample), subkey)\n        ).get_trace(*model_args, **model_kwargs)\n        first_available_dim = -_guess_max_plate_nesting(prototype_trace) - 1\n\n    def single_prediction(val):\n        rng_key, samples = val\n        if infer_discrete:\n            from numpyro.contrib.funsor import config_enumerate\n            from numpyro.contrib.funsor.discrete import _sample_posterior\n\n            model_trace = prototype_trace\n            temperature = 1\n            pred_samples = _sample_posterior(\n                config_enumerate(condition(model, samples)),\n                first_available_dim,\n                temperature,\n                rng_key,\n                *model_args,\n                **model_kwargs,\n            )\n        else:\n            model_trace = trace(\n                seed(substitute(masked_model, samples), rng_key)\n            ).get_trace(*model_args, **model_kwargs)\n            pred_samples = {name: site[\"value\"] for name, site in model_trace.items()}\n\n        if return_sites is not None:\n            if return_sites == \"\":\n                sites = {\n                    k for k, site in model_trace.items() if site[\"type\"] != \"plate\"\n                }\n            else:\n                sites = return_sites\n        else:\n            sites = {\n                k\n                for k, site in model_trace.items()\n                if (site[\"type\"] == \"sample\" and k not in samples)\n                or (site[\"type\"] == \"deterministic\")\n            }\n        return {name: value for name, value in pred_samples.items() if name in sites}\n\n    num_samples = int(np.prod(batch_shape))\n    if num_samples > 1:\n        rng_key = random.split(rng_key, num_samples)\n    rng_key = rng_key.reshape((*batch_shape, 2))\n    chunk_size = num_samples if parallel else 1\n    return soft_vmap(\n        single_prediction, (rng_key, posterior_samples), len(batch_shape), chunk_size\n    )\n\n\nclass Predictive(object):\n    \"\"\"\n    This class is used to construct predictive distribution. The predictive distribution is obtained\n    by running model conditioned on latent samples from `posterior_samples`.\n\n    .. warning::\n        The interface for the `Predictive` class is experimental, and\n        might change in the future.\n\n    :param model: Python callable containing Pyro primitives.\n    :param dict posterior_samples: dictionary of samples from the posterior.\n    :param callable guide: optional guide to get posterior samples of sites not present\n        in `posterior_samples`.\n    :param dict params: dictionary of values for param sites of model/guide.\n    :param int num_samples: number of samples\n    :param list return_sites: sites to return; by default only sample sites not present\n        in `posterior_samples` are returned.\n    :param bool infer_discrete: whether or not to sample discrete sites from the\n        posterior, conditioned on observations and other latent values in\n        ``posterior_samples``. Under the hood, those sites will be marked with\n        ``site[\"infer\"][\"enumerate\"] = \"parallel\"``. See how `infer_discrete` works at\n        the `Pyro enumeration tutorial <https://pyro.ai/examples/enumeration.html>`_.\n        Note that this requires ``funsor`` installation.\n    :param bool parallel: whether to predict in parallel using JAX vectorized map :func:`jax.vmap`.\n        Defaults to False.\n    :param batch_ndims: the number of batch dimensions in posterior samples or parameters. If `None` defaults\n        to 0 if guide is set (i.e. not `None`) and 1 otherwise. Usages for batched posterior samples:\n\n        + set `batch_ndims=0` to get prediction for 1 single sample\n\n        + set `batch_ndims=1` to get prediction for `posterior_samples`\n          with shapes `(num_samples x ...)` (same as`batch_ndims=None` with `guide=None`)\n\n        + set `batch_ndims=2` to get prediction for `posterior_samples`\n          with shapes `(num_chains x N x ...)`. Note that if `num_samples`\n          argument is not None, its value should be equal to `num_chains x N`.\n\n        Usages for batched parameters:\n\n        + set `batch_ndims=0` to get 1 sample from the guide and parameters (same as `batch_ndims=None` with guide)\n\n        + set `batch_ndims=1` to get predictions from a one dimensional batch of the guide and parameters\n          with shapes `(num_samples x batch_size x ...)`\n\n    :return: dict of samples from the predictive distribution.\n\n    **Example:**\n\n    Given a model::\n\n        def model(X, y=None):\n            ...\n            return numpyro.sample(\"obs\", likelihood, obs=y)\n\n    you can sample from the prior predictive::\n\n        predictive = Predictive(model, num_samples=1000)\n        y_pred = predictive(rng_key, X)[\"obs\"]\n\n    If you also have posterior samples, you can sample from the posterior predictive::\n\n        predictive = Predictive(model, posterior_samples=posterior_samples)\n        y_pred = predictive(rng_key, X)[\"obs\"]\n\n    See docstrings for :class:`~numpyro.infer.svi.SVI` and :class:`~numpyro.infer.mcmc.MCMCKernel`\n    to see example code of this in context.\n    \"\"\"\n\n    def __init__(\n        self,\n        model: Callable,\n        posterior_samples: Optional[Dict] = None,\n        *,\n        guide: Optional[Callable] = None,\n        params: Optional[Dict] = None,\n        num_samples: Optional[int] = None,\n        return_sites: Optional[List[str]] = None,\n        infer_discrete: bool = False,\n        parallel: bool = False,\n        batch_ndims: Optional[int] = None,\n    ):\n        if posterior_samples is None and num_samples is None:\n            raise ValueError(\n                \"Either posterior_samples or num_samples must be specified.\"\n            )\n        if posterior_samples is not None and guide is not None:\n            raise ValueError(\n                \"Only one of guide or posterior_samples can be provided, not both.\"\n            )\n\n        batch_ndims = (\n            batch_ndims if batch_ndims is not None else 1 if guide is None else 0\n        )\n\n        posterior_samples = {} if posterior_samples is None else posterior_samples\n\n        prototype_site = batch_shape = batch_size = None\n        for name, sample in posterior_samples.items():\n            if batch_shape is not None and sample.shape[:batch_ndims] != batch_shape:\n                raise ValueError(\n                    f\"Batch shapes at site {name} and {prototype_site} \"\n                    f\"should be the same, but got \"\n                    f\"{sample.shape[:batch_ndims]} and {batch_shape}\"\n                )\n            else:\n                prototype_site = name\n                batch_shape = sample.shape[:batch_ndims]\n                batch_size = int(np.prod(batch_shape))\n                if (num_samples is not None) and (num_samples != batch_size):\n                    warnings.warn(\n                        \"Sample's batch dimension size {} is different from the \"\n                        \"provided {} num_samples argument. Defaulting to {}.\".format(\n                            batch_size, num_samples, batch_size\n                        ),\n                        UserWarning,\n                        stacklevel=find_stack_level(),\n                    )\n                num_samples = batch_size\n\n        if num_samples is None:\n            raise ValueError(\n                \"No sample sites in posterior samples to infer `num_samples`.\"\n            )\n\n        if batch_shape is None:\n            batch_shape = (1,) * (batch_ndims - 1) + (num_samples,)\n\n        if return_sites is not None:\n            assert isinstance(return_sites, (list, tuple, set))\n\n        self.model = model\n        self.posterior_samples = {} if posterior_samples is None else posterior_samples\n        self.num_samples = num_samples\n        self.guide = guide\n        self.params = {} if params is None else params\n        self.infer_discrete = infer_discrete\n        self.return_sites = return_sites\n        self.parallel = parallel\n        self.batch_ndims = batch_ndims\n        self._batch_shape = batch_shape\n\n    def _call_with_params(self, rng_key, params, args, kwargs):\n        posterior_samples = self.posterior_samples\n        if self.guide is not None:\n            rng_key, guide_rng_key = random.split(rng_key)\n            # use return_sites='' as a special signal to return all sites\n            guide = substitute(self.guide, params)\n            posterior_samples = _predictive(\n                guide_rng_key,\n                guide,\n                posterior_samples,\n                self._batch_shape,\n                return_sites=\"\",\n                parallel=self.parallel,\n                model_args=args,\n                model_kwargs=kwargs,\n            )\n        model = substitute(self.model, self.params)\n        return _predictive(\n            rng_key,\n            model,\n            posterior_samples,\n            self._batch_shape,\n            return_sites=self.return_sites,\n            infer_discrete=self.infer_discrete,\n            parallel=self.parallel,\n            model_args=args,\n            model_kwargs=kwargs,\n        )\n\n    def __call__(self, rng_key, *args, **kwargs):\n        \"\"\"\n        Returns dict of samples from the predictive distribution. By default, only sample sites not\n        contained in `posterior_samples` are returned. This can be modified by changing the\n        `return_sites` keyword argument of this :class:`Predictive` instance.\n\n        :param jax.random.PRNGKey rng_key: random key to draw samples.\n        :param args: model arguments.\n        :param kwargs: model kwargs.\n        \"\"\"\n        if self.batch_ndims == 0 or self.params == {} or self.guide is None:\n            return self._call_with_params(rng_key, self.params, args, kwargs)\n        elif self.batch_ndims == 1:  # batch over parameters\n            batch_size = jnp.shape(tree_flatten(self.params)[0][0])[0]\n            rng_keys = random.split(rng_key, batch_size)\n            return jax.vmap(\n                partial(self._call_with_params, args=args, kwargs=kwargs),\n                in_axes=0,\n                out_axes=1,\n            )(rng_keys, self.params)\n        else:\n            raise NotImplementedError\n\n\ndef log_likelihood(\n    model, posterior_samples, *args, parallel=False, batch_ndims=1, **kwargs\n):\n    \"\"\"\n    (EXPERIMENTAL INTERFACE) Returns log likelihood at observation nodes of model,\n    given samples of all latent variables.\n\n    :param model: Python callable containing Pyro primitives.\n    :param dict posterior_samples: dictionary of samples from the posterior.\n    :param args: model arguments.\n    :param batch_ndims: the number of batch dimensions in posterior samples. Some usages:\n\n        + set `batch_ndims=0` to get log likelihoods for 1 single sample\n\n        + set `batch_ndims=1` to get log likelihoods for `posterior_samples`\n          with shapes `(num_samples x ...)`\n\n        + set `batch_ndims=2` to get log likelihoods for `posterior_samples`\n          with shapes `(num_chains x num_samples x ...)`\n\n    :param kwargs: model kwargs.\n    :return: dict of log likelihoods at observation sites.\n    \"\"\"\n\n    def single_loglik(samples):\n        substituted_model = (\n            substitute(model, samples) if isinstance(samples, dict) else model\n        )\n        model_trace = trace(substituted_model).get_trace(*args, **kwargs)\n        return {\n            name: site[\"fn\"].log_prob(site[\"value\"])\n            for name, site in model_trace.items()\n            if site[\"type\"] == \"sample\" and site[\"is_observed\"]\n        }\n\n    prototype_site = batch_shape = None\n    for name, sample in posterior_samples.items():\n        if batch_shape is not None and jnp.shape(sample)[:batch_ndims] != batch_shape:\n            raise ValueError(\n                f\"Batch shapes at site {name} and {prototype_site} \"\n                f\"should be the same, but got \"\n                f\"{sample.shape[:batch_ndims]} and {batch_shape}\"\n            )\n        else:\n            prototype_site = name\n            batch_shape = jnp.shape(sample)[:batch_ndims]\n\n    if batch_shape is None:  # posterior_samples is an empty dict\n        batch_shape = (1,) * batch_ndims\n        posterior_samples = np.zeros(batch_shape)\n\n    batch_size = int(np.prod(batch_shape))\n    chunk_size = batch_size if parallel else 1\n    return soft_vmap(single_loglik, posterior_samples, len(batch_shape), chunk_size)\n\n\n@contextmanager\ndef helpful_support_errors(site, raise_warnings=False):\n    name = site[\"name\"]\n    support = getattr(site[\"fn\"], \"support\", None)\n    if isinstance(support, constraints.independent):\n        support = support.base_constraint\n\n    # Warnings\n    if raise_warnings:\n        if support is constraints.circular:\n            msg = (\n                f\"Continuous inference poorly handles circular sample site '{name}'. \"\n                + \"Consider using VonMises distribution together with \"\n                + \"a reparameterizer, e.g. \"\n                + f\"numpyro.handlers.reparam(config={{'{name}': CircularReparam()}}).\"\n            )\n            warnings.warn(msg, UserWarning, stacklevel=find_stack_level())\n\n    # Exceptions\n    try:\n        yield\n    except NotImplementedError as e:\n        support_name = repr(support).lower()\n        if \"integer\" in support_name or \"boolean\" in support_name:\n            # TODO: mention enumeration when it is supported in SVI\n            raise ValueError(\n                f\"Continuous inference cannot handle discrete sample site '{name}'.\"\n            )\n        if \"sphere\" in support_name:\n            raise ValueError(\n                f\"Continuous inference cannot handle spherical sample site '{name}'. \"\n                \"Consider using ProjectedNormal distribution together with \"\n                \"a reparameterizer, e.g. \"\n                f\"numpyro.handlers.reparam(config={{'{name}': ProjectedNormalReparam()}}).\"\n            )\n        raise e from None\n", "meta": {"hexsha": "c4a77889e0614caeb5f5082d856cf6cd6a61ec56", "size": 43600, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpyro/infer/util.py", "max_stars_repo_name": "karm-patel/numpyro", "max_stars_repo_head_hexsha": "34e0cdf4fa0ab9a0300a0d894d6758419fb46f40", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numpyro/infer/util.py", "max_issues_repo_name": "karm-patel/numpyro", "max_issues_repo_head_hexsha": "34e0cdf4fa0ab9a0300a0d894d6758419fb46f40", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpyro/infer/util.py", "max_forks_repo_name": "karm-patel/numpyro", "max_forks_repo_head_hexsha": "34e0cdf4fa0ab9a0300a0d894d6758419fb46f40", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9005628518, "max_line_length": 115, "alphanum_fraction": 0.6219036697, "include": true, "reason": "import numpy,from numpy,import jax,from jax", "num_tokens": 9267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.19001750407443946}}
{"text": "#!/usr/bin/env python3\n\"\"\"Calculates the Frechet Inception Distance (FID) to evalulate GANs\nThe FID metric calculates the distance between two distributions of images.\nTypically, we have summary statistics (mean & covariance matrix) of one\nof these distributions, while the 2nd distribution is given by a GAN.\nWhen run as a stand-alone program, it compares the distribution of\nimages that are stored as PNG/JPEG at a specified location with a\ndistribution given by summary statistics (in pickle format).\nThe FID is calculated by assuming that X_1 and X_2 are the activations of\nthe pool_3 layer of the inception net for generated samples and real world\nsamples respectively.\nSee --help to see further details.\nCode apapted from https://github.com/bioinf-jku/TTUR to use PyTorch instead\nof Tensorflow\nCopyright 2018 Institute of Bioinformatics, JKU Linz\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n   http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport os\nimport pathlib\n\nimport numpy as np\nimport torch\nfrom scipy import linalg\nfrom torch.nn.functional import adaptive_avg_pool2d\nfrom src.utils import read_config\nfrom src.Models.models import ImitateJoint\nimport matplotlib.pyplot as plt\nfrom globals import device\nfrom autoencoder import Autoencoder\nfrom PIL import Image\n\ntry:\n    from tqdm import tqdm\nexcept ImportError:\n    # If not tqdm is not available, provide a mock version of it\n    def tqdm(x): return x\n\nfrom src.Models.models import Encoder\nfrom src.utils.generators.wake_sleep_gen import WakeSleepGen\nfrom src.utils.generators.shapenet_generater import Generator\nfrom globals import device\n\ndef get_activations(generator, model, batch_size=50, dims=32, verbose=False):\n    \"\"\"Calculates the activations of the pool_3 layer for all images.\n    Params:\n    -- files       : List of image files paths\n    -- model       : Instance of inception model\n    -- batch_size  : Batch size of images for the model to process at once.\n                     Make sure that the number of samples is a multiple of\n                     the batch size, otherwise some samples are ignored. This\n                     behavior is retained to match the original FID score\n                     implementation.\n    -- dims        : Dimensionality of features returned by Inception\n    -- cuda        : If set to True, use GPU\n    -- verbose     : If set to True and parameter out_step is given, the number\n                     of calculated batches is reported.\n    Returns:\n    -- A numpy array of dimension (num images, dims) that contains the\n       activations of the given tensor when feeding inception with the\n       query tensor.\n    \"\"\"\n    model.eval()\n\n    test_size = 3000\n\n    pred_arr = np.empty((test_size, dims))\n\n    n_batches = test_size // batch_size\n\n    for i in tqdm(range(0, test_size, batch_size)):\n        if verbose:\n            print('\\rPropagating batch %d/%d' % ((i + 1) // batch_size, n_batches),\n                  end='', flush=True)\n        start = i\n        end = i + batch_size\n\n        images = next(generator)\n        images = torch.from_numpy(images).to(device)\n        if len(images.shape) == 3: # generated samples\n            # images = torch.from_numpy(np.random.randint(0, 2, (100, 64, 64))).to(device).float()\n            pred = model.encode(images.unsqueeze(1).float())\n        else: # cad data\n            pred = model.encode(images[-1, :, 0:1, :, :])\n\n        pred = pred.reshape((batch_size,-1, 1, 1))\n        # If model output is not scalar, apply global spatial average pooling.\n        # This happens if you choose a dimensionality not equal 2048.\n        # if pred.size(2) != 1 or pred.size(3) != 1:\n        #     pred = adaptive_avg_pool2d(pred, output_size=(1, 1))\n\n        pred_arr[start:end] = pred.cpu().data.numpy().reshape(pred.size(0), -1)\n\n    if verbose:\n        print(' done')\n\n    return pred_arr\n\n\ndef calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):\n    \"\"\"Numpy implementation of the Frechet Distance.\n    The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)\n    and X_2 ~ N(mu_2, C_2) is\n            d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).\n    Stable version by Dougal J. Sutherland.\n    Params:\n    -- mu1   : Numpy array containing the activations of a layer of the\n               inception net (like returned by the function 'get_predictions')\n               for generated samples.\n    -- mu2   : The sample mean over activations, precalculated on an\n               representative data set.\n    -- sigma1: The covariance matrix over activations for generated samples.\n    -- sigma2: The covariance matrix over activations, precalculated on an\n               representative data set.\n    Returns:\n    --   : The Frechet Distance.\n    \"\"\"\n\n    mu1 = np.atleast_1d(mu1)\n    mu2 = np.atleast_1d(mu2)\n\n    sigma1 = np.atleast_2d(sigma1)\n    sigma2 = np.atleast_2d(sigma2)\n\n    assert mu1.shape == mu2.shape, \\\n        'Training and test mean vectors have different lengths'\n    assert sigma1.shape == sigma2.shape, \\\n        'Training and test covariances have different dimensions'\n\n    diff = mu1 - mu2\n\n    # Product might be almost singular\n    covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)\n    if not np.isfinite(covmean).all():\n        msg = ('fid calculation produces singular product; '\n               'adding %s to diagonal of cov estimates') % eps\n        print(msg)\n        offset = np.eye(sigma1.shape[0]) * eps\n        covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))\n\n    # Numerical error might give slight imaginary component\n    if np.iscomplexobj(covmean):\n        if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):\n            m = np.max(np.abs(covmean.imag))\n            raise ValueError('Imaginary component {}'.format(m))\n        covmean = covmean.real\n\n    tr_covmean = np.trace(covmean)\n\n    return (diff.dot(diff) + np.trace(sigma1) +\n            np.trace(sigma2) - 2 * tr_covmean)\n\n\ndef calculate_activation_statistics(files, model, batch_size=50,\n                                    dims=32, verbose=False):\n    \"\"\"Calculation of the statistics used by the FID.\n    Params:\n    -- files       : List of image files paths\n    -- model       : Instance of inception model\n    -- batch_size  : The images numpy array is split into batches with\n                     batch size batch_size. A reasonable batch size\n                     depends on the hardware.\n    -- dims        : Dimensionality of features returned by Inception\n    -- cuda        : If set to True, use GPU\n    -- verbose     : If set to True and parameter out_step is given, the\n                     number of calculated batches is reported.\n    Returns:\n    -- mu    : The mean over samples of the activations of the pool_3 layer of\n               the inception model.\n    -- sigma : The covariance matrix of the activations of the pool_3 layer of\n               the inception model.\n    \"\"\"\n    act = get_activations(files, model, batch_size, dims, verbose)\n    mu = np.mean(act, axis=0)\n    sigma = np.cov(act, rowvar=False)\n    return mu, sigma\n\n\ndef _compute_statistics_of_path(path, model, batch_size, dims):\n    if path.endswith('.npz'):\n        f = np.load(path)\n        m, s = f['mu'][:], f['sigma'][:]\n        f.close()\n    else:\n        m, s = calculate_activation_statistics(path, model, batch_size,\n                                               dims)\n\n    return m, s\n\ndef calculate_fid_given_paths(model, images_path, model_path, batch_size, dims=32):\n    \"\"\"Calculates the FID of two paths\"\"\"\n    if not os.path.exists(images_path):\n        raise RuntimeError('Invalid path: %s' % images_path)\n    if not os.path.exists(model_path):\n        raise RuntimeError('Invalid path: %s' % model_path)\n\n    generator = FidGen(images_path).get_test_data()\n    # generator2 = FidGen(model_path).get_test_data()\n    cad_generator = Generator().test_gen(batch_size=batch_size,\n                                        path=\"data/cad/cad.h5\",\n                                        if_augment=False)\n    # cad_generator2 = Generator().val_gen(batch_size=batch_size,\n    #                                     path=\"data/cad/cad.h5\",\n    #                                     if_augment=False)\n\n    m1, s1 = calculate_activation_statistics(cad_generator, model, batch_size,\n                                         dims)\n    m2, s2 = calculate_activation_statistics(generator, model, batch_size,\n                                         dims)\n\n    fid_value = calculate_frechet_distance(m1, s1, m2, s2)\n\n    return fid_value\n\ndef get_csgnet():\n    config = read_config.Config(\"config_synthetic.yml\")\n\n    # Encoder\n    encoder_net = Encoder(config.encoder_drop)\n    encoder_net = encoder_net.to(device)\n\n    imitate_net = ImitateJoint(\n        hd_sz=config.hidden_size,\n        input_size=config.input_size,\n        encoder=encoder_net,\n        mode=config.mode,\n        num_draws=400,\n        canvas_shape=config.canvas_shape)\n    imitate_net = imitate_net.to(device)\n\n    print(\"pre loading model\")\n    pretrained_dict = torch.load(config.pretrain_modelpath, map_location=device)\n    imitate_net_dict = imitate_net.state_dict()\n    pretrained_dict = {\n        k: v\n        for k, v in pretrained_dict.items() if k in imitate_net_dict\n    }\n    imitate_net_dict.update(pretrained_dict)\n    imitate_net.load_state_dict(imitate_net_dict)\n\n    return imitate_net.encoder\n\nclass FidGen:\n    def __init__(self, images_path):\n        self.images = torch.load(images_path)\n    def get_test_data(self):\n        while True:\n            for i in range(0, 3000, 100):\n                batch_images = self.images[i:i+100]\n                yield batch_images\n\nif __name__ == '__main__':\n    # model = Autoencoder().to(device)\n    # model.load_state_dict(torch.load(\"trained_models/fid-model2.pth\"))\n    model = get_csgnet()\n    fids = []\n    fid_value = calculate_fid_given_paths(model,\n                                          f\"fid_images2/base.pt\",\n                                          \"trained_models/mix_len_cr_percent_equal_batch_3_13_prop_100_hdsz_2048_batch_2000_optim_adam_lr_0.001_wd_0.0_enocoderdrop_0.0_drop_0.2_step_mix_mode_12.pth\",\n                                          # \"random_images.pt\",\n                                          100,\n                                          2048)\n    print(fid_value)\n    # for i in range(17):\n    #     fid_value = calculate_fid_given_paths(model,\n    #                                           f\"fid_images2/{i}.pt\",\n    #                                           # \"trained_models/mix_len_cr_percent_equal_batch_3_13_prop_100_hdsz_2048_batch_2000_optim_adam_lr_0.001_wd_0.0_enocoderdrop_0.0_drop_0.2_step_mix_mode_12.pth\",\n    #                                           \"random_images.pt\",\n    #                                           100,\n    #                                           2048)\n    #\n    #     print('FID: ', fid_value)\n    #     fids.append(fid_value)\n\n    # fig, ax = plt.subplots()\n    # ax.plot(fids)\n    # plt.savefig(\"fids.png\")\n    # with open(\"fids_random.txt\", \"w\") as file:\n    #     for f in fids:\n", "meta": {"hexsha": "5c2a0abe62d4eb9d0ed464ee7a465755c1dfccc7", "size": 11558, "ext": "py", "lang": "Python", "max_stars_repo_path": "fid_score.py", "max_stars_repo_name": "HomerW/CSGNet", "max_stars_repo_head_hexsha": "4ecc7f3e836867118dba3d5f220ed5e74a536b93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fid_score.py", "max_issues_repo_name": "HomerW/CSGNet", "max_issues_repo_head_hexsha": "4ecc7f3e836867118dba3d5f220ed5e74a536b93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fid_score.py", "max_forks_repo_name": "HomerW/CSGNet", "max_forks_repo_head_hexsha": "4ecc7f3e836867118dba3d5f220ed5e74a536b93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2717770035, "max_line_length": 207, "alphanum_fraction": 0.6329814847, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.19001749665715037}}
{"text": "import os\r\nimport sys\r\nimport numpy as np\r\nfrom math import floor, ceil, sqrt\r\nfrom scipy.signal import convolve\r\n\r\nclass PDB(object):\r\n    def __init__(self, pdb_file):\r\n        self.pdb_file = pdb_file\r\n        self.coords = []\r\n        self.info = []\r\n\r\n        if not os.path.exists(self.pdb_file):\r\n            print(\"PDB> File not found: %s\"%self.pdb_file)\r\n            sys.exit(1)\r\n\r\n        '''\r\n        Load Coordinate sections of a PDB file as of PDB version 3.30\r\n\r\n        COLUMNS        DATA  TYPE    FIELD        DEFINITION\r\n        -------------------------------------------------------------------------------------\r\n         1 -  6        Record name   \"ATOM  \"\r\n         7 - 11        Integer       serial       Atom  serial number.\r\n        13 - 16        Atom          name         Atom name.\r\n        17             Character     altLoc       Alternate location indicator.\r\n        18 - 20        Residue name  resName      Residue name.\r\n        22             Character     chainID      Chain identifier.\r\n        23 - 26        Integer       resSeq       Residue sequence number.\r\n        27             AChar         iCode        Code for insertion of residues.\r\n        31 - 38        Real(8.3)     x            Orthogonal coordinates for X in Angstroms.\r\n        39 - 46        Real(8.3)     y            Orthogonal coordinates for Y in Angstroms.\r\n        47 - 54        Real(8.3)     z            Orthogonal coordinates for Z in Angstroms.\r\n        55 - 60        Real(6.2)     occupancy    Occupancy.\r\n        61 - 66        Real(6.2)     tempFactor   Temperature  factor.\r\n        77 - 78        LString(2)    element      Element symbol, right-justified.\r\n        79 - 80        LString(2)    charge       Charge  on the atom.\r\n        '''\r\n        self.CA_idx = []\r\n        self.BB_idx = []\r\n        c = 0\r\n        with open(self.pdb_file, 'r') as pdb:\r\n            for line in pdb:\r\n                line_type = line[0:6].strip()\r\n                if line_type in [\"ATOM\", \"HETATM\"]:\r\n                    try:\r\n                        at_num = int(line[6:11].strip())\r\n                        at_name = line[12:16].strip()\r\n                        res_name = line[17:20]\r\n                        chain_id = line[21]\r\n                        res_num = int(line[22:26].strip())\r\n                        x = float(line[30:38])\r\n                        y = float(line[38:46])\r\n                        z = float(line[46:54])\r\n                        element_symbol = line[76:78].strip()\r\n                    except Exception:\r\n                        # print(\"PDB> Error while reading line, skipping it: \\n     > %s\"%line)\r\n                        pass\r\n\r\n                    self.info.append([at_num, at_name, res_name, chain_id, res_num, element_symbol, line_type])\r\n                    self.coords.append([x, y, z])\r\n                    if at_name == \"CA\":\r\n                        self.CA_idx.append(c)\r\n                    if at_name in [\"C\", \"CA\", \"N\", \"O\"]:\r\n                        self.BB_idx.append(c)\r\n                    c += 1\r\n\r\n        self.coords = np.array(self.coords)\r\n        self.CA_idx = tuple(self.CA_idx)\r\n        self.n_atoms = len(self.coords)\r\n        self.n_CA = len(self.CA_idx)\r\n\r\n        # Extent of structure\r\n        self.minx = np.amin(self.coords[:, 0])\r\n        self.maxx = np.amax(self.coords[:, 0])\r\n        self.miny = np.amin(self.coords[:, 1])\r\n        self.maxy = np.amax(self.coords[:, 1])\r\n        self.minz = np.amin(self.coords[:, 2])\r\n        self.maxz = np.amax(self.coords[:, 2])\r\n\r\n    def write_pdb(self, outname):\r\n        occupancy = 1.0\r\n        tempFactor = 0.0\r\n        fout = open(outname, \"w\")\r\n        for i in range(self.n_atoms):\r\n            # Check for atom type: if 4 letters long, start in column 13 otherwise no space.\r\n            # Else, start in column 14. Differs from format convention v3.30 but always see it this way in files.\r\n            if len(self.info[i][1]) == 4:\r\n                line_model = \"%-6s%5i %-4s %3s%2s%4s    %8.3f%8.3f%8.3f%6.2f%6.2f          %-2s\"\r\n            else:\r\n                line_model = \"%-6s%5i  %-3s %3s%2s%4s    %8.3f%8.3f%8.3f%6.2f%6.2f          %-2s\"\r\n            line = line_model%(self.info[i][6], self.info[i][0], self.info[i][1], self.info[i][2], self.info[i][3], self.info[i][4], self.coords[i][0], self.coords[i][1], self.coords[i][2], occupancy, tempFactor, self.info[i][5])\r\n\r\n            fout.write(line+\"\\n\")\r\n        fout.close()\r\n\r\n    def rgyr(self):\r\n        rgyr = np.sqrt(np.sum(np.sum((self.coords - self.center())**2, axis=1) / self.coords.shape[0]))\r\n        return rgyr\r\n\r\n    ####################\r\n    # PDB manipulation #\r\n    ####################\r\n    def get_coords(self):\r\n        return self.coords\r\n\r\n    def set_coords(self, coords):\r\n        self.coords = coords.copy()\r\n\r\n    def rotate_atoms(self, rot_mat):\r\n        self.coords = np.dot(self.coords, rot_mat)\r\n\r\n    def translate_atoms(self, trans_vec):\r\n        self.coords += np.array(trans_vec)\r\n\r\n    def get_rmsd_with(self, pdb):\r\n        dist_sq = np.square(self.coords - pdb.coords)\r\n        return np.sqrt(np.sum(dist_sq, axis=(0,1)) / dist_sq.shape[0])\r\n\r\n    def get_rmsdCA_with(self, pdb):\r\n        if not len(self.CA_idx):\r\n            print(\"PDB> No alpha carbons detected; returning all-atom RMSD instead.\")\r\n            return self.get_rmsd_with(pdb)\r\n        dist_sq = np.square(self.coords[self.CA_idx, :] - pdb.coords[pdb.CA_idx, :])\r\n        return np.sqrt(np.sum(dist_sq, axis=(0,1)) / dist_sq.shape[0])\r\n\r\n\r\n    ###################\r\n    # Density related #\r\n    ###################\r\n    # Get density grid\r\n    def structure_to_density(self, resolution, voxelsp, isovalue=0.0, pad=0, outname=\"\"):\r\n        # Interpolate pdb to grid + box size + origin coordinates\r\n        grid_prot, pxb, pyb, pzb, minx, miny, minz = self.interpolate_to_grid_massweighted(voxelsp, pad=pad)\r\n\r\n        # Margin for convoluted box\r\n        margin = 2 + pad\r\n\r\n        # Sigma\r\n        # > Divide by pi*sqrt(2): it is a factor that affects the voxelsp of the gaussian.\r\n        #   Same factor as in chimera. Their explanation in documentation:\r\n        #       Fourier transform (FT) of the distribution fall to 1/e of its maximum value at wavenumber 1/resolution\r\n        # > Divide by voxel spacing to make sure kernel relates to structure space\r\n        # > Truncate values to 3 sigma\r\n        sig = resolution / (np.pi*sqrt(2)) / voxelsp\r\n        r = int(ceil(3.0 * sig))  # truncate at 3 sigma\r\n\r\n        # Make Gaussian kernel\r\n        z,y,x = np.ogrid[-r:r+1, -r:r+1, -r:r+1]\r\n        h = np.exp( -(x*x + y*y + z*z) / (2. * sig**2) )\r\n        kernel = h / h.sum()\r\n\r\n        # Make density map at given resolution from structure grid\r\n        grid_prot = np.reshape(grid_prot, (pxb, pyb, pzb), order='F')\r\n        grid_dens = convolve(grid_prot, kernel).astype(np.float32)\r\n\r\n        # Origin and size of convoluted map\r\n        dxi = minx - (r + margin) * voxelsp;\r\n        dyi = miny - (r + margin) * voxelsp;\r\n        dzi = minz - (r + margin) * voxelsp;\r\n\r\n        # Bring map in range [0,1] + apply isovalue threshold\r\n        grid_dens = np.divide(grid_dens, np.amax(grid_dens))\r\n        grid_dens[np.where(grid_dens < isovalue)] = 0\r\n\r\n        if outname != \"\":\r\n            extension = os.path.splitext(outname)[-1].lower()\r\n            if extension in [\".sit\", \".situs\"]:\r\n                dxb, dyb, dzb = grid_dens.shape\r\n                f_out = open(outname,\"w\")\r\n                f_out.write(\"%f %f %f %f %i %i %i\\n\\n\"%(voxelsp, dxi, dyi, dzi, dxb, dyb, dzb))\r\n                voxi = 0\r\n                for z in range(dzb):\r\n                    for y in range(dyb):\r\n                        for x in range(dxb):\r\n                            if (voxi+1)%10 == 0 :\r\n                                f_out.write(\"\\n\")\r\n                            f_out.write(\"   %6.6f   \"%grid_dens[x][y][z])\r\n                            voxi += 1\r\n                f_out.close()\r\n            else:\r\n                # assuming mrc/map\r\n                import mrcfile\r\n                with mrcfile.new(outname, overwrite=True) as mrc:\r\n                    mrc.set_data(grid_dens.transpose(2,1,0).astype(np.float32))\r\n                    xb, yb, zb = grid_dens.shape\r\n\r\n                    mrc.mode = 2\r\n\r\n                    mrc.header.mx = xb\r\n                    mrc.header.my = yb\r\n                    mrc.header.mz = zb\r\n\r\n                    mrc.header.nxstart = 0\r\n                    mrc.header.nystart = 0\r\n                    mrc.header.nzstart = 0\r\n                    mrc.header.origin.x = dxi\r\n                    mrc.header.origin.y = dyi\r\n                    mrc.header.origin.z = dzi\r\n\r\n                    mrc.header.cella.x = xb * voxelsp\r\n                    mrc.header.cella.y = yb * voxelsp\r\n                    mrc.header.cella.z = zb * voxelsp\r\n\r\n                    mrc.header.mapc = 1\r\n                    mrc.header.mapr = 2\r\n                    mrc.header.maps = 3\r\n\r\n        return grid_dens.astype(np.float32), dxi, dyi, dzi\r\n\r\n\r\n    #################\r\n    # Interpolation #\r\n    #################\r\n\r\n    def interpolate_to_grid_massweighted(self, voxelsp, pad=0):\r\n        # Convert 3D idx to 1D\r\n        def idz(kx, ky, k, j, i):\r\n            return kx * ky * k + kx * j + i\r\n\r\n        mass_dict = {\"H\" : 1.00797, \"BE\": 9.01218, \"C\" : 12.011, \"N\" : 14.0067, \"O\" : 15.9994, \"F\": 18.998403, \"S\" : 32.06, \"P\" : 30.97376,\r\n                     \"MG\": 24.305, \"CL\": 35.453, \"K\": 39.0983, \"CA\": 40.078, \"MN\": 54.9380, \"FE\": 55.847, \"NI\": 58.70, \"CU\": 63.546, \"ZN\": 65.38, \"SE\": 78.96}\r\n\r\n        # To build the density map, we need the XYZ coordinates and mass of for each atom from PDB\r\n        info_for_dens = []\r\n        element_list = [x[-2].upper() for x in self.info]\r\n        for xyz, elem in zip(self.coords, element_list):\r\n            x, y, z = xyz\r\n            if elem in mass_dict.keys():\r\n                mass = mass_dict[elem]\r\n            else:\r\n                print(\"PDB> (dens) Element %s not in dict. Using mass of carbon.\"%elem)\r\n                mass = mass_dict[\"C\"]  # default value\r\n            info_for_dens.append([x, y, z, mass])\r\n        info_for_dens = np.array(info_for_dens)\r\n\r\n        # Extent of structure\r\n        minx = np.amin(info_for_dens[:, 0])\r\n        maxx = np.amax(info_for_dens[:, 0])\r\n        miny = np.amin(info_for_dens[:, 1])\r\n        maxy = np.amax(info_for_dens[:, 1])\r\n        minz = np.amin(info_for_dens[:, 2])\r\n        maxz = np.amax(info_for_dens[:, 2])\r\n\r\n        # Lattice into register with origin\r\n\r\n        minx = voxelsp * floor(minx / voxelsp)\r\n        maxx = voxelsp * ceil(maxx / voxelsp)\r\n        miny = voxelsp * floor(miny / voxelsp)\r\n        maxy = voxelsp * ceil(maxy / voxelsp)\r\n        minz = voxelsp * floor(minz / voxelsp)\r\n        maxz = voxelsp * ceil(maxz / voxelsp)\r\n\r\n        # Size of box in each direction to contain structure\r\n        margin = 2 + pad\r\n        pxb = ceil((maxx - minx) / voxelsp) + 2 * margin + 1\r\n        pyb = ceil((maxy - miny) / voxelsp) + 2 * margin + 1\r\n        pzb = ceil((maxz - minz) / voxelsp) + 2 * margin + 1\r\n\r\n        nvox_prot = pxb * pyb * pzb\r\n        grid_prot = np.zeros((nvox_prot, 1))\r\n\r\n        # Trilinear interpolation of structure to box\r\n        for i in range(len(info_for_dens)):\r\n            # position within grid\r\n            gx = margin + (info_for_dens[i][0] - minx) / voxelsp\r\n            gy = margin + (info_for_dens[i][1] - miny) / voxelsp\r\n            gz = margin + (info_for_dens[i][2] - minz) / voxelsp\r\n\r\n            # XYZ coords surrounding atom position\r\n            x0 = floor(gx)\r\n            y0 = floor(gy)\r\n            z0 = floor(gz)\r\n            x1 = x0 + 1;\r\n            y1 = y0 + 1;\r\n            z1 = z0 + 1;\r\n\r\n            # interpolate\r\n            a = x1 - gx\r\n            b = y1 - gy\r\n            c = z1 - gz\r\n            grid_prot[idz(pxb, pyb, z0, y0, x0)] += info_for_dens[i][3] * a * b * c\r\n            grid_prot[idz(pxb, pyb, z1, y0, x0)] += info_for_dens[i][3] * a * b * (1 - c)\r\n            grid_prot[idz(pxb, pyb, z0, y1, x0)] += info_for_dens[i][3] * a * (1 - b) * c\r\n            grid_prot[idz(pxb, pyb, z0, y0, x1)] += info_for_dens[i][3] * (1 - a) * b * c\r\n            grid_prot[idz(pxb, pyb, z1, y1, x0)] += info_for_dens[i][3] * a * (1 - b) * (1 - c)\r\n            grid_prot[idz(pxb, pyb, z0, y1, x1)] += info_for_dens[i][3] * (1 - a) * (1 - b) * c\r\n            grid_prot[idz(pxb, pyb, z1, y0, x1)] += info_for_dens[i][3] * (1 - a) * b * (1 - c)\r\n            grid_prot[idz(pxb, pyb, z1, y1, x1)] += info_for_dens[i][3] * (1 - a) * (1 - b) * (1 - c)\r\n\r\n        grid_prot = np.divide(grid_prot, np.amax(grid_prot))\r\n\r\n        return grid_prot, pxb, pyb, pzb, minx, miny, minz\r\n", "meta": {"hexsha": "efeb01a3c0ae7b56fc65dbe4689a2d42300094b0", "size": 12776, "ext": "py", "lang": "Python", "max_stars_repo_path": "mad/PDB.py", "max_stars_repo_name": "LBM-EPFL/MaD", "max_stars_repo_head_hexsha": "593d416ea3829bd203383689fa9fd2095d9b88d6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mad/PDB.py", "max_issues_repo_name": "LBM-EPFL/MaD", "max_issues_repo_head_hexsha": "593d416ea3829bd203383689fa9fd2095d9b88d6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mad/PDB.py", "max_forks_repo_name": "LBM-EPFL/MaD", "max_forks_repo_head_hexsha": "593d416ea3829bd203383689fa9fd2095d9b88d6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.6040955631, "max_line_length": 230, "alphanum_fraction": 0.4864589856, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.1899854754199653}}
{"text": "\"\"\"\nPrototype of a \"Shakemap-Lite\" system for retreiving expected GMPE\nvalues from an earthquake\n\"\"\"\nimport os\nimport subprocess\nimport h5py\nimport numpy as np\nimport pandas as pd\nfrom openquake.hazardlib.geo import Point, PlanarSurface, MultiSurface, Mesh\nfrom openquake.hazardlib.gsim import get_available_gsims\nfrom openquake.hazardlib.imt import PGA, PGV, SA, from_string\nfrom openquake.hazardlib.contexts import (ContextMaker, get_distances,\n                                          SitesContext, DistancesContext)\nfrom openquake.hazardlib.source.rupture import ParametricProbabilisticRupture\nfrom openquake.hazardlib.site import Site, SiteCollection\nfrom openquake.hazardlib.scalerel.wc1994 import WC1994\nfrom openquake.hazardlib import const\nimport synthetic_rupture_generator as srg\n\n\nGSIM_SET = get_available_gsims()\n\n\ndef create_planar_surface(top_centroid, strike, dip, area, aspect):\n    \"\"\"\n    Given a central location, create a simple planar rupture\n    :param top_centroid:\n        Centroid of trace of the rupture, as instance of :class:\n            openquake.hazardlib.geo.point.Point\n    :param float strike:\n        Strike of rupture(Degrees)\n    :param float dip:\n        Dip of rupture (degrees)\n    :param float area:\n        Area of rupture (km^2)\n    :param float aspect:\n        Aspect ratio of rupture\n\n    :returns: Rupture as an instance of the :class:\n        openquake.hazardlib.geo.surface.planar.PlanarSurface\n    \"\"\"\n    rad_dip = dip * pi / 180.\n    width = sqrt(area / aspect)\n    length = aspect * width\n    # Get end points by moving the top_centroid along strike\n    top_right = top_centroid.point_at(length / 2., 0., strike)\n    top_left = top_centroid.point_at(length / 2.,\n                                     0.,\n                                     (strike + 180.) % 360.)\n    # Along surface width\n    surface_width = width * cos(rad_dip)\n    vertical_depth = width * sin(rad_dip)\n    dip_direction = (strike + 90.) % 360.\n\n    bottom_right = top_right.point_at(surface_width,\n                                      vertical_depth,\n                                      dip_direction)\n    bottom_left = top_left.point_at(surface_width,\n                                    vertical_depth,\n                                    dip_direction)\n\n    # Create the rupture\n    return PlanarSurface(strike, dip, top_left, top_right,\n                         bottom_right, bottom_left)\n\n\ndef vs30_to_z1pt0_cy14(vs30, japan=False):\n    \"\"\"\n    Returns the estimate depth to the 1.0 km/s velocity layer based on Vs30\n    from Chiou & Youngs (2014) California model\n\n    :param numpy.ndarray vs30:\n        Input Vs30 values in m/s\n    :param bool japan:\n        If true returns the Japan model, otherwise the California model\n    :returns:\n        Z1.0 in m\n    \"\"\"\n    if japan:\n        c1 = 412. ** 2.\n        c2 = 1360.0 ** 2.\n        return np.exp((-5.23 / 2.0) *\n                      np.log((np.power(vs30,2.) + c1) / (c2 + c1)))\n    else:\n        c1 = 571 ** 4.\n        c2 = 1360.0 ** 4.\n        return np.exp((-7.15 / 4.0) * np.log((vs30 ** 4. + c1) / (c2 + c1)))\n\n\ndef vs30_to_z2pt5_cb14(vs30, japan=False):\n    \"\"\"\n    Converts vs30 to depth to 2.5 km/s interface using model proposed by\n    Campbell & Bozorgnia (2014)\n\n    :param vs30:\n        Vs30 values (numpy array or float)\n\n    :param bool japan:\n        Use Japan formula (True) or California formula (False)\n\n    :returns:\n        Z2.5 in km\n    \"\"\"\n    if japan:\n        return np.exp(5.359 - 1.102 * np.log(vs30))\n    else:\n        return np.exp(7.089 - 1.144 * np.log(vs30))\n\n\ndef get_vs30_sites_from_bbox(bbox, isep=\"\\t\"):\n    \"\"\"\n    Returns a basic site dictionary from a bbox [llon, ulon, llat, ulat]\n    \"\"\"\n    filepath=os.path.dirname(__file__)\n    site_data_path = os.path.join(filepath, \"global_vs30.grd\")\n    tempfile = \"tempfile.grd\"\n    # Call grdcut\n    cutstring = \"/\".join([str(loc) for loc in bbox])\n    subprocess.run([\"gmt\", \"grdcut\", site_data_path,\n                    \"-G{:s}\".format(tempfile),\n                    \"-R{:s}\".format(cutstring)])\n    # Call grd2xyz\n    tempxyz = os.path.join(filepath,\"tempfile.xyz\")\n    subprocess.run([\"gmt\", \"grd2xyz\", tempfile, \"-sa\", \">\", tempxyz])\n    # Use pandas to read in the xyzdata\n    site_data = pd.read_csv(tempxyz, sep=isep)\n    sites = {\"lon\": site_data.iloc[:, 0].values,\n             \"lat\": site_data.iloc[:, 1].values,\n             \"vs30\": site_data.iloc[:, 2].values}\n    os.remove(tempfile)\n    os.remove(tempxyz)\n    return sites\n\n\nclass Event(object):\n    \"\"\"\n    Shakemap event object - requires a minimum of an ID, longitude, latitude,\n    depth and magnitude. Other attributes con be input to control the rupture\n    orientation and mechanism.\n\n    Can input a rupture geometry directly\n    \"\"\"\n    def __init__(self, i_d, lon, lat, hypo_depth, mag, strike=0.0, dip=90.,\n                 rake=0.0, aspect=1.0, msr=srg.Stafford2014(), usd=0.0,\n                 lsd=1000.0, rupture=None):\n\n        self.id = i_d\n        self.lon = lon\n        self.lat = lat\n        self.depth = hypo_depth\n        self.mag = mag\n        self.strike = strike\n        self.dip = dip\n        self.rake = rake\n        self.mechanism = []\n            #({\"strike\": strike, \"dip\": dip, \"rake\": rake}, 1.)]\n        self.aspect = aspect\n        self.msr = msr\n        if rupture:\n            assert isinstance(rupture, ParametricProbabilisticRupture)\n            self.rupture = rupture\n        else:\n            self.rupture = None\n        self.usd = usd\n        self.lsd = lsd\n        self.generator = srg.FiniteRuptureSampler(msr, self.usd, self.lsd)\n\n\n    def __repr__(self):\n        return \"{:s}|{:.5f}|{:.5f}|{:.5f}|{:.2f}\".format(self.id,\n                                                         self.lon,\n                                                         self.lat,\n                                                         self.depth,\n                                                         self.mag)\n    def get_rupture(self):\n        \"\"\"\n        If a rupture is provided then it is returned, otherwise it will\n        use a synthetic rupture generator\n        \"\"\"\n        if self.rupture:\n           return rupture\n        else:\n            if len(self.mechanism) >= 1:\n                # Define a set of rupture mechanisms with weight\n                mechanisms = []\n                for mech, weight in self.mechanism:\n                    npd = NodalPlane(self.mechanism[\"strike\"],\n                                     self.mechanism[\"dip\"],\n                                     self.mechanism[\"rake\"])\n                    mechanisms.append((weight, npd))\n                mechanisms = PMF(mechanisms)\n            else:\n                if self.rake:\n                    if self.rake >= 45.0 and self.rake <= 135.0:\n                        mechanisms = \"R\"\n                    elif self.rake >= -135.0 and self.rake <= -45.:\n                        mechanisms = \"N\"\n                    else:\n                        mechanisms = \"SS\"\n                else:\n                    mechanisms = \"U\"\n            # Build planar rupture\n            planar_surface = self.generator.sample_ruptures(\n                Point(self.lon, self.lat, self.depth),\n                      self.mag, nsamples=1, mechanisms=mechanisms,\n                      dimensions=None)[0]\n            return ParametricProbabilisticRupture(\n                self.mag, self.rake, None,\n                Point(self.lon, self.lat, self.depth),\n                planar_surface, 1.0, None)\n\n\nclass ShakemapLite(object):\n    \"\"\"\n    Class to implement a lightweight OpenQuake-based shakemap\n    \"\"\"\n    def __init__(self, database, gmpes, imts):\n        \"\"\"\n        Shakemap results are stored to an hdf5 databse\n        :param str database:\n            Path to database\n        :param list gmpes:\n            List of gmpes (as strings)\n        :param list imts:\n            List of IMTs (as strings)\n        \"\"\"\n\n        self.gmpes = [GSIM_SET[gmpe]() for gmpe in gmpes]\n        self.imts = [from_string(imt) for imt in imts]\n        self.db_file = database\n        self.context = ContextMaker(self.gmpes)\n        # Determine the site attributes\n        self.site_attribs = []\n        for gmpe in self.gmpes:\n            for site_attrib in gmpe.REQUIRES_SITES_PARAMETERS:\n                if not site_attrib in self.site_attribs:\n                    self.site_attribs.append(site_attrib)\n\n    def __call__(self, event, sites, vs30measured=False, backarc=False):\n        \"\"\"\n        Execute a shakemap\n        \"\"\"\n        # Build the contexts\n        sctx, dctx = self.build_sites_distances_contexts(event, sites,\n                                                         vs30measured,\n                                                         backarc)\n        # Connect to database\n        fle = h5py.File(self.db_file)\n        grp = fle.create_group(event.id)\n        # Store distance calculations to database\n        dists_grp = grp.create_group(\"Distances\")\n        for key, distance in list(dctx.__dict__.items()):\n            dset = dists_grp.create_dataset(key, distance.shape, dtype=\"f\")\n            dset[:] = distance\n        # Get the rupture\n        rctx = event.get_rupture()\n        # Run the calculations\n        for gmpe in self.gmpes:\n            gmpe_grp = grp.create_group(gmpe.__class__.__name__)\n            for imt in self.imts:\n                imt_grp = gmpe_grp.create_group(str(imt))\n                # Get ground motion values\n                mean, [sigma] = gmpe.get_mean_and_stddevs(\n                    sctx, rctx, dctx, imt, [const.StdDev.TOTAL])\n                mean_dset = imt_grp.create_dataset(\"median\",\n                                                   mean.shape,\n                                                   dtype=\"f\")\n                mean_dset[:] = np.exp(mean)\n                sigma_dset = imt_grp.create_dataset(\"sigma\",\n                                                    sigma.shape,\n                                                    dtype=\"f\")\n                sigma_dset[:] = sigma\n        fle.close()\n\n    def reset(self):\n        \"\"\"\n        Remove the database file then delete the object itself\n        \"\"\"\n        if os.path.exists(self.db_file):\n            os.remove(self.db_file)\n\n    def __getitem__(self, i):\n        \"\"\"\n        Returns a given data set on a path\n        \"\"\"\n        if not os.path.exists(self.db_file):\n            raise AttributeError(\"Database %s does not exist\" % self.db_file)\n        # Connect to the database\n        fle = h5py.File(self.db_file)\n        try:\n            data = fle[i][:]\n            return data\n        except:\n            # Data not found\n            fle.close()\n            raise AttributeError(\"%s not found in database\" % i)\n\n    def build_sites_distances_contexts(self, event, sites, vs30measured=False,\n                                       backarc=False):\n        \"\"\"\n        Builds the contexts from the event and sites\n        \"\"\"\n        # Get distances\n        mesh = Mesh(sites[\"lon\"], sites[\"lat\"])\n        mshape = mesh.lons.shape\n        dctx = DistancesContext()\n        for param in self.context.REQUIRES_DISTANCES:\n            setattr(dctx, param, get_distances(event.get_rupture(),\n                                               mesh, param))\n        # Get sites context\n        sctx = SitesContext()\n        for key in self.site_attribs:\n            if key.startswith(\"z1pt0\") and not \"z1pt0\" in sites:\n                setattr(sctx, \"z1pt0\",\n                        vs30_to_z1pt0_cy14(sites[\"vs30\"], japan=False))\n\n            elif key.startswith(\"z2pt5\") and not \"z5pt5\" in sites:\n                setattr(sctx, \"z2pt5\",\n                        vs30_to_z2pt5_cb14(sites[\"vs30\"], japan=False))\n\n            elif key.startswith(\"vs30measured\") and not \"vs30measured\" in sites:\n                if vs30measured:\n                    setattr(sctx, \"vs30measured\", np.ones(mshape, dtype=bool))\n                else:\n                    setattr(sctx, \"vs30measured\", np.zeros(mshape, dtype=bool))\n            elif key.startswith(\"vs30measured\") and not \"vs30measured\" in sites:\n                if vs30measured:\n                    setattr(sctx, \"vs30measured\", np.ones(mshape, dtype=bool))\n                else:\n                    setattr(sctx, \"vs30measured\", np.zeros(mshape, dtype=bool))\n            elif key.startswith(\"backarc\") and not \"backarc\" in sites:\n                if vs30measured:\n                    setattr(sctx, \"backarc\", np.ones(mshape, dtype=bool))\n                else:\n                    setattr(sctx, \"backarc\", np.zeros(mshape, dtype=bool))\n            else:\n                setattr(sctx, key, sites[key])\n        return sctx, dctx\n\n#\n#    def build_site_collection(self, sites, vs30measured=False, backarc=False):\n#        \"\"\"\n#        Sites should be a dictionary of site parameter\n#        {lon, lat, vs30, vs30measured, z1pt0, z2pt5, backarc}\n#        \"\"\"\n#        for key in [\"lon\", \"lat\", \"vs30\"]:\n#            # check in dict\n#            assert key in sites\n#        nsites = len(sites[\"lon\"])\n#        if not \"z1pt0\" in sites or sites[\"z1pt0\"] is None:\n#            sites[\"z1pt0\"] = vs30_to_z1pt0_cy14(sites[\"vs30\"], japan=False)\n#\n#        if not \"z2pt5\" in sites or sites[\"z2pt5\"] is None:\n#            sites[\"z2pt5\"] = vs30_to_z2pt5_cb14(sites[\"vs30\"], japan=False)\n#\n#        if not \"vs30measured\" in sites or sites[\"vs30measured\"] is None:\n#            if vs30measured:\n#                sites[\"vs30measured\"] = np.ones(nsites, dtype=bool)\n#            else:\n#                sites[\"vs30measured\"] = np.zeros(nsites, dtype=bool)\n#\n#        if not \"backarc\" in sites or sites[\"backarc\"] is None:\n#            sites[\"backarc\"] = backarc\n#        site_col = []\n#        for i in range(len(sites[\"lon\"])):\n#            site = Site(Point(sites[\"lon\"][i], sites[\"lat\"][i], 0.0),\n#                        sites[\"vs30\"][i], sites[\"vs30measured\"][i],\n#                        sites[\"z1pt0\"][i], sites[\"z2pt5\"][i],\n#                        sites[\"backarc\"][i])\n#            site_col.append(site)\n#        return SiteCollection(site_col)\n", "meta": {"hexsha": "e84882ff26cc7c7dfd1b344e995cd7d0bead5e8b", "size": 14103, "ext": "py", "lang": "Python", "max_stars_repo_path": "shakemap_lite.py", "max_stars_repo_name": "GFZ-Centre-for-Early-Warning/shakyground", "max_stars_repo_head_hexsha": "0da9ba5a575360081715e8b90c71d4b16c6687c8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-01T00:28:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-01T00:28:24.000Z", "max_issues_repo_path": "shakemap_lite.py", "max_issues_repo_name": "GFZ-Centre-for-Early-Warning/shakyground", "max_issues_repo_head_hexsha": "0da9ba5a575360081715e8b90c71d4b16c6687c8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-08-31T14:14:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-11T12:53:13.000Z", "max_forks_repo_path": "shakemap_lite.py", "max_forks_repo_name": "GFZ-Centre-for-Early-Warning/shakyground", "max_forks_repo_head_hexsha": "0da9ba5a575360081715e8b90c71d4b16c6687c8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-08-31T14:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-17T10:06:02.000Z", "avg_line_length": 37.8096514745, "max_line_length": 80, "alphanum_fraction": 0.5398142239, "include": true, "reason": "import numpy", "num_tokens": 3406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.3629692193015555, "lm_q1q2_score": 0.18998547002316932}}
{"text": "#!/usr/bin/env python3\n\n\"\"\"\nThis module provides classes used to\n  * define a phonon mode\n  * apply symmetry op to a phonon mode\n\"\"\"\n\n\nimport numpy as np\nfrom numpy.linalg import norm\n\nfrom .interface_vasp import Poscar\nfrom .cluster import Cluster\nfrom .coord_utils import ReadPBC2Cart, match_p1p0\nfrom .util.mathtool import relativePosition\nimport logging\nlogger = logging.getLogger(__name__)\n\ndebug_level = 10\n\nclass PhononMode():\n    \"\"\"\n\n    \"\"\"\n\n    def __init__(self, prim, clus, u, clus_dominant):\n        \"\"\"\n        a proper cluster decorated with displacement u\n        \"\"\"\n        self.prim = prim\n        self.cluster = clus\n        self.u = u\n        self.dominant_cluster = clus_dominant\n        # print(self.cluster)\n        # print(self.dominant_cluster)\n\n    def operated_by(self, isym):\n        return PhononMode(self.prim, Cluster.from_ijkl(self.cluster.operated_by(isym), self.prim),\n                          np.dot(self.u, self.prim.spacegroup[isym].rot.T),\n                          Cluster.from_ijkl(self.dominant_cluster.operated_by(isym), self.prim))\n\n\n    def __repr__(self):\n#        outs = [\"\"]\n#        outs.append(self.frac_coords.__str__())\n#        outs.append(\"ijk= \"+ self.ijk.__repr__()+ \" l=\"+ self.l.__repr__()+\"]\")\n#        outs.append(str(self.ijkl))\n#        return \" \".join(outs)\n        return str(self.cluster)+ repr(self.u)\n\n    @classmethod\n    def from_file(cls, prim, p1f, disp_cut, natom_dominant=2, p0f=None, dominant_specie=None, dominant_dr=True):\n        \"\"\"\n\n        :param p0: read an ideal structure,\n         p1: disturbed structure\n         disp_cut: retain only atoms with displacement larger than this cutoff\n         dominant_specie: which atoms may be the representative\n        :paramdominant_dr: Select dominant pairs by largest change in distance\n        :return: a phonon mode\n        \"\"\"\n        if p0f is None:\n            x0 = Poscar.from_file(p1f).structure.map_to_prim(prim)\n        else:\n            assert isinstance(p0f, str), TypeError(\"require p0f filename\")\n            x0 = Poscar.from_file(p0f).structure\n        scmat = prim.get_scmat(x0.lattice.matrix)\n\n        if debug_level > 10:\n            print(\"supercell clusters generated\")\n\n        u = ReadPBC2Cart(p1f, x0.frac_coords)\n        # center of mass\n        u -= np.average(u, axis=0)\n        unorm = norm(u, axis=1)\n        # print(unorm)\n        # print(u)\n        uidx = np.where(unorm > disp_cut)[0]\n        # print(uidx)\n        if len(uidx) < natom_dominant:\n            print(\"ERROR: found only %d displaced atoms\" % (len(uidx)))\n            exit(-1)\n\n        clus_xyz = x0.frac_coords[uidx].copy()\n        # move cluster atoms close to one atom considering PBC\n        imax = np.argmax(unorm)\n        pc0 = x0.frac_coords[imax:imax+1].copy()\n        for i in range(len(uidx)):\n            # print(\"debug\", i, ui, clus_xyz[i], clus_xyz[i:i+1], pc0)\n            clus_xyz[i] = match_p1p0(clus_xyz[i:i+1], pc0)[0]\n            # print(clus_xyz[i], x0.frac_coords[ui])\n        clus_xyz = np.dot(clus_xyz, scmat)\n\n        # now find out the dominant cluster\n        if dominant_dr and natom_dominant == 2:\n            max_dr = -1.\n            sel = [True for _ in uidx]\n            if isinstance(dominant_specie, list):\n                ele = x0.elements\n                sel = [ele[i] in dominant_specie for i in uidx]\n#            print(sel, ele)\n            for i1, i in enumerate(uidx):\n                if not sel[i1]:\n                    continue\n                for i2, j in enumerate(uidx):\n                    if (not sel[i2]) or (i1 >= i2):\n                        continue\n                    r0 = prim.lattice.norm(clus_xyz[i2]-clus_xyz[i1])\n                    r1 = np.linalg.norm(prim.lattice.get_cartesian_coords(clus_xyz[i2]-clus_xyz[i1]) + u[j]-u[i])\n                    dr = abs(r0-r1)\n                    if dr > max_dr:\n                        max_dr = dr\n#                        print(i, j, max_dr)\n                        atom_dominant = np.array([i1, i2])\n        else:\n            if dominant_specie is None:\n                udominant = unorm[uidx]\n            else:\n                ele = x0.elements\n                assert isinstance(dominant_specie, list)\n                # print(\"debug species=\", dominant_specie, ele, \"for finding dimer |u|=\", [unorm[i] if ele[i] in dominant_specie else -1. for i in uidx])\n                udominant = [unorm[i] if ele[i] in dominant_specie else -1. for i in uidx]\n            atom_dominant = np.argsort(udominant)[-natom_dominant:]\n#        print('dominant=', atom_dominant)\n        for i in uidx[atom_dominant]:\n            print(\"atom %4d element %3s   disp %8.3f\" % (i, x0[i].specie, unorm[i]), x0.frac_coords[i])\n\n\n        return cls(prim, Cluster.from_coords(clus_xyz, prim), u[uidx],\n                   Cluster.from_coords(clus_xyz[atom_dominant], prim))\n\n\n    def apply_to(self, dest, dest_clus, inv_sc_mat):\n        \"\"\"\n        Apply phonon mode to a supercell\n        :param dest: destination supercell\n        :param dest_clus: dominant cluster by which to identify or match the phonon\n        :param inv_sc_mat: inverse sc_mat belonging to the supercell\n        :return:\n        \"\"\"\n        prim = self.prim\n        syms = prim.spacegroup\n        for isym, sym in enumerate(syms):\n            s_pl = self.operated_by(isym)\n            is_eq, tr = dest_clus.equivalent_by_lattranslation(s_pl.dominant_cluster.ijkls)\n            if is_eq:\n                # print(isym, tr, s_pl.dominant_cluster.ijkls, dest_dimer.ijkls)\n                # found a sym op to move polaron to desired position\n                break\n        assert is_eq, ValueError(\"cannot apply phonon mode\")\n        pi = relativePosition(dest_clus.ijkls, tr)\n        tr_ijk = np.array(dest_clus.ijkls[0]) - np.array(s_pl.dominant_cluster.ijkls[pi[0]])\n        s_pl.cluster.move_to_prim(dijk=tr_ijk[:3])\n        dest_polaron = [dest.frac2ijkl(np.dot(s_pl.cluster.frac_coords[i], inv_sc_mat))[3] for i in\n                        range(s_pl.cluster.order)]\n\n        out_sc = dest.copy()\n        for i, isite in enumerate(dest_polaron):\n            out_sc[isite].move_by(s_pl.u[i])\n        return out_sc\n", "meta": {"hexsha": "7721dd175eb903d6d8e3902bfef8cdf4cbbf95c8", "size": 6172, "ext": "py", "lang": "Python", "max_stars_repo_path": "csld/phonon_mode.py", "max_stars_repo_name": "jsyony37/csld", "max_stars_repo_head_hexsha": "b0e6d5845d807174f24ca7b591bc164c608c99c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2019-07-22T18:49:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T10:22:05.000Z", "max_issues_repo_path": "csld/phonon_mode.py", "max_issues_repo_name": "jsyony37/csld", "max_issues_repo_head_hexsha": "b0e6d5845d807174f24ca7b591bc164c608c99c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-07-18T20:49:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-09T00:47:04.000Z", "max_forks_repo_path": "csld/phonon_mode.py", "max_forks_repo_name": "jsyony37/csld", "max_forks_repo_head_hexsha": "b0e6d5845d807174f24ca7b591bc164c608c99c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-07-18T17:52:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-04T11:35:04.000Z", "avg_line_length": 38.0987654321, "max_line_length": 153, "alphanum_fraction": 0.5814970836, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.18998546820621814}}
{"text": "\"\"\"Economy-level structuring of BLP problem results.\"\"\"\n\nimport time\nfrom typing import Any, Callable, Dict, Hashable, List, Optional, Sequence, TYPE_CHECKING, Tuple\n\nimport numpy as np\nimport scipy.linalg\n\nfrom .results import Results\nfrom .. import exceptions, options\nfrom ..configurations.iteration import Iteration\nfrom ..markets.results_market import ResultsMarket\nfrom ..parameters import Parameters\nfrom ..utilities.algebra import approximately_solve, multiply_matrix_and_tensor, precisely_compute_eigenvalues\nfrom ..utilities.basics import (\n    Array, Bounds, Error, TableFormatter, format_number, format_seconds, generate_items, output, output_progress\n)\nfrom ..utilities.statistics import compute_gmm_parameter_covariances, compute_gmm_weights\n\n\n# only import objects that create import cycles when checking types\nif TYPE_CHECKING:\n    from .bootstrapped_results import BootstrappedResults  # noqa\n    from .optimal_instrument_results import OptimalInstrumentResults  # noqa\n    from ..economies.problem import Progress  # noqa\n\n\nclass ProblemResults(Results):\n    r\"\"\"Results of a solved BLP problem.\n\n    Many results are class attributes. Other post-estimation outputs be computed by calling class methods.\n\n    .. note::\n\n       All methods in this class support :func:`parallel` processing. If multiprocessing is used, market-by-market\n       computation of each post-estimation output will be distributed among the processes.\n\n    Attributes\n    ----------\n    problem : `Problem`\n        :class:`Problem` that created these results.\n    last_results : `ProblemResults`\n        :class:`ProblemResults` from the last GMM step.\n    step : `int`\n        GMM step that created these results.\n    optimization_time : `float`\n        Number of seconds it took the optimization routine to finish.\n    cumulative_optimization_time : `float`\n        Sum of :attr:`ProblemResults.optimization_time` for this step and all prior steps.\n    total_time : `float`\n        Sum of :attr:`ProblemResults.optimization_time` and the number of seconds it took to set up the GMM step and\n        compute results after optimization had finished.\n    cumulative_total_time : `float`\n        Sum of :attr:`ProblemResults.total_time` for this step and all prior steps.\n    optimization_iterations : `int`\n        Number of major iterations completed by the optimization routine.\n    cumulative_optimization_iterations : `int`\n        Sum of :attr:`ProblemResults.optimization_iterations` for this step and all prior steps.\n    objective_evaluations : `int`\n        Number of GMM objective evaluations.\n    cumulative_objective_evaluations : `int`\n        Sum of :attr:`ProblemResults.objective_evaluations` for this step and all prior steps.\n    fp_converged : `ndarray`\n        Flags for convergence of the iteration routine used to compute :math:`\\delta(\\hat{\\theta})` in each market\n        during each objective evaluation. Rows are in the same order as :attr:`Problem.unique_market_ids` and column\n        indices correspond to objective evaluations.\n    cumulative_fp_converged : `ndarray`\n        Concatenation of :attr:`ProblemResults.fp_converged` for this step and all prior steps.\n    fp_iterations : `ndarray`\n        Number of major iterations completed by the iteration routine used to compute :math:`\\delta(\\hat{\\theta})` in\n        each market during each objective evaluation. Rows are in the same order as\n        :attr:`Problem.unique_market_ids` and column indices correspond to objective evaluations.\n    cumulative_fp_iterations : `ndarray`\n        Concatenation of :attr:`ProblemResults.fp_iterations` for this step and all prior steps.\n    contraction_evaluations : `ndarray`\n        Number of times the contraction used to compute :math:`\\delta(\\hat{\\theta})` was evaluated in each market during\n        each objective evaluation. Rows are in the same order as :attr:`Problem.unique_market_ids` and column\n        indices correspond to objective evaluations.\n    cumulative_contraction_evaluations : `ndarray`\n        Concatenation of :attr:`ProblemResults.contraction_evaluations` for this step and all prior steps.\n    converged : `bool`\n        Whether the optimization routine converged.\n    cumulative_converged : `bool`\n        Whether the optimization routine converged for this step and all prior steps.\n    parameters : `ndarray`\n        Stacked parameters in the following order: :math:`\\hat{\\theta}`, concentrated out elements of\n        :math:`\\hat{\\beta}`, and concentrated out elements of :math:`\\hat{\\gamma}`.\n    parameter_covariances : `ndarray`\n        Estimated covariance matrix of the stacked parameters, from which standard errors are extracted.\n    theta : `ndarray`\n        Estimated unfixed parameters, :math:`\\hat{\\theta}` in the following order: :math:`\\hat{\\Sigma}`,\n        :math:`\\hat{\\Pi}`, :math:`\\hat{\\rho}`, non-concentrated out elements from :math:`\\hat{\\beta}`, and\n        non-concentrated out elements from :math:`\\hat{\\gamma}`.\n    sigma : `ndarray`\n        Estimated Cholesky decomposition of the covariance matrix that measures agents' random taste distribution,\n        :math:`\\hat{\\Sigma}`.\n    pi : `ndarray`\n        Estimated parameters that measures how agent tastes vary with demographics, :math:`\\hat{\\Pi}`.\n    rho : `ndarray`\n        Estimated parameters that measure within nesting group correlations, :math:`\\hat{\\rho}`.\n    beta : `ndarray`\n        Estimated demand-side linear parameters, :math:`\\hat{\\beta}`.\n    gamma : `ndarray`\n        Estimated supply-side linear parameters, :math:`\\hat{\\gamma}`.\n    sigma_se : `ndarray`\n        Estimated standard errors for :math:`\\hat{\\Sigma}`.\n    pi_se : `ndarray`\n        Estimated standard errors for :math:`\\hat{\\Pi}`.\n    rho_se : `ndarray`\n        Estimated standard errors for :math:`\\hat{\\rho}`.\n    beta_se : `ndarray`\n        Estimated standard errors for :math:`\\hat{\\beta}`.\n    gamma_se : `ndarray`\n        Estimated standard errors for :math:`\\hat{\\gamma}`.\n    sigma_bounds : `tuple`\n        Bounds for :math:`\\Sigma` that were used during optimization, which are of the form ``(lb, ub)``.\n    pi_bounds : `tuple`\n        Bounds for :math:`\\Pi` that were used during optimization, which are of the form ``(lb, ub)``.\n    rho_bounds : `tuple`\n        Bounds for :math:`\\rho` that were used during optimization, which are of the form ``(lb, ub)``.\n    beta_bounds : `tuple`\n        Bounds for :math:`\\beta` that were used during optimization, which are of the form ``(lb, ub)``.\n    gamma_bounds : `tuple`\n        Bounds for :math:`\\gamma` that were used during optimization, which are of the form ``(lb, ub)``.\n    delta : `ndarray`\n        Estimated mean utility, :math:`\\delta(\\hat{\\theta})`.\n    tilde_costs : `ndarray`\n        Estimated transformed marginal costs, :math:`\\tilde{c}(\\hat{\\theta})`. Transformed marginal costs are simply\n        :math:`\\tilde{c} = c`, marginal costs, under a linear cost specification, and are :math:`\\tilde{c} = \\log c`\n        under a log-linear specification. If ``costs_bounds`` were specified in :meth:`Problem.solve`, :math:`c` may\n        have been clipped.\n    clipped_costs : `ndarray`\n        Vector of booleans indicating whether the associated marginal costs were clipped. All elements will be ``False``\n        if ``costs_bounds`` in :meth:`Problem.solve` was not specified.\n    xi : `ndarray`\n        Estimated unobserved demand-side product characteristics, :math:`\\xi(\\hat{\\theta})`, or equivalently, the\n        demand-side structural error term.\n    omega : `ndarray`\n        Estimated unobserved supply-side product characteristics, :math:`\\omega(\\hat{\\theta})`, or equivalently, the\n        supply-side structural error term.\n    objective : `float`\n        GMM objective value.\n    xi_by_theta_jacobian : `ndarray`\n        Estimated :math:`\\partial\\xi / \\partial\\theta = \\partial\\delta / \\partial\\theta`.\n    omega_by_theta_jacobian : `ndarray`\n        Estimated :math:`\\partial\\omega / \\partial\\theta = \\partial\\tilde{c} / \\partial\\theta`.\n    gradient : `ndarray`\n        Estimated gradient of the GMM objective with respect to :math:`\\theta`, which is computed after the optimization\n        routine finishes even if the routine was configured to not use analytic gradients.\n    sigma_gradient : `ndarray`\n        Estimated gradient of the GMM objective with respect to :math:`\\Sigma` elements in :math:`\\theta`.\n    pi_gradient : `ndarray`\n        Estimated gradient of the GMM objective with respect to :math:`\\Pi` elements in :math:`\\theta`.\n    rho_gradient : `ndarray`\n        Estimated gradient of the GMM objective with respect to :math:`\\rho` elements in :math:`\\theta`.\n    beta_gradient : `ndarray`\n        Estimated gradient of the GMM objective with respect to :math:`\\beta` elements in :math:`\\theta`.\n    gamma_gradient : `ndarray`\n        Estimated gradient of the GMM objective with respect to :math:`\\gamma` elements in :math:`\\theta`.\n    gradient_norm : `ndarray`\n        Infinity norm of :attr:`ProblemResults.gradient`.\n    hessian : `ndarray`\n        Estimated Hessian of the GMM objective with respect to :math:`\\theta`. By default, this is computed with finite\n        central differences after the optimization routine finishes.\n    hessian_eigenvalues : `ndarray`\n        Eigenvalues of :attr:`ProblemResults.hessian`.\n    W : `ndarray`\n        Weighting matrix, :math:`W`, used to compute these results.\n    updated_W : `ndarray`\n        Updated weighting matrix.\n\n    Examples\n    --------\n        - :doc:`Tutorial </tutorial>`\n\n    \"\"\"\n\n    last_results: Optional['ProblemResults']\n    step: int\n    optimization_time: float\n    cumulative_optimization_time: float\n    total_time: float\n    cumulative_total_time: float\n    optimization_iterations: int\n    cumulative_optimization_iterations: int\n    objective_evaluations: int\n    cumulative_objective_evaluations: int\n    fp_converged: Array\n    cumulative_fp_converged: Array\n    fp_iterations: Array\n    cumulative_fp_iterations: Array\n    contraction_evaluations: Array\n    cumulative_contraction_evaluations: Array\n    converged: bool\n    cumulative_converged: bool\n    parameters: Array\n    parameter_covariances: Array\n    theta: Array\n    sigma: Array\n    pi: Array\n    rho: Array\n    beta: Array\n    gamma: Array\n    sigma_se: Array\n    pi_se: Array\n    rho_se: Array\n    beta_se: Array\n    gamma_se: Array\n    sigma_bounds: Bounds\n    pi_bounds: Bounds\n    rho_bounds: Bounds\n    beta_bounds: Bounds\n    gamma_bounds: Bounds\n    delta: Array\n    tilde_costs: Array\n    clipped_costs: Array\n    xi: Array\n    omega: Array\n    objective: Array\n    xi_by_theta_jacobian: Array\n    omega_by_theta_jacobian: Array\n    gradient: Array\n    gradient_norm: Array\n    hessian: Array\n    hessian_eigenvalues: Array\n    sigma_gradient: Array\n    pi_gradient: Array\n    rho_gradient: Array\n    beta_gradient: Array\n    gamma_gradient: Array\n    W: Array\n    updated_W: Array\n    _costs_type: str\n    _se_type: str\n    _errors: List[Error]\n    _parameters: Parameters\n\n    def __init__(\n            self, progress: 'Progress', last_results: Optional['ProblemResults'], step_start_time: float,\n            optimization_start_time: float, optimization_end_time: float, iterations: int, evaluations: int,\n            converged_mappings: Sequence[Dict[Hashable, bool]], iteration_mappings: Sequence[Dict[Hashable, int]],\n            evaluation_mappings: Sequence[Dict[Hashable, int]], converged: bool, costs_type: str, costs_bounds: Bounds,\n            center_moments: bool, W_type: str, se_type: str) -> None:\n        \"\"\"Compute cumulative progress statistics, update weighting matrices, and estimate standard errors.\"\"\"\n\n        # initialize values from the progress structure\n        super().__init__(progress.problem)\n        self._errors = progress.errors\n        self.problem = progress.problem\n        self.W = progress.W\n        self.theta = progress.theta\n        self.delta = progress.delta\n        self.tilde_costs = progress.tilde_costs\n        self.xi_by_theta_jacobian = progress.xi_jacobian\n        self.omega_by_theta_jacobian = progress.omega_jacobian\n        self.xi = progress.xi\n        self.omega = progress.omega\n        self.beta = progress.beta\n        self.gamma = progress.gamma\n        self.objective = progress.objective\n        self.gradient = progress.gradient\n        self.gradient_norm = progress.gradient_norm\n        self.hessian = progress.hessian\n\n        # if the Hessian was computed, compute its eigenvalues and the ratio of the smallest to largest ones\n        self.hessian_eigenvalues = np.full(progress.parameters.P, np.nan, options.dtype)\n        if progress.parameters.P > 0 and np.isfinite(self.hessian).all():\n            self.hessian_eigenvalues, successful = precisely_compute_eigenvalues(self.hessian)\n            if not successful:\n                self._errors.append(exceptions.HessianEigenvaluesError(self.hessian))\n\n        # store information about cost bounds\n        self._costs_bounds = costs_bounds\n        self.clipped_costs = progress.clipped_costs\n\n        # initialize counts, times, and convergence\n        self.step = 1\n        self.total_time = self.cumulative_total_time = time.time() - step_start_time\n        self.optimization_time = self.cumulative_optimization_time = optimization_end_time - optimization_start_time\n        self.optimization_iterations = self.cumulative_optimization_iterations = iterations\n        self.objective_evaluations = self.cumulative_objective_evaluations = evaluations\n        self.fp_converged = self.cumulative_fp_converged = np.array(\n            [[m[t] if m else True for m in converged_mappings] for t in self.problem.unique_market_ids],\n            dtype=np.int\n        )\n        self.fp_iterations = self.cumulative_fp_iterations = np.array(\n            [[m[t] if m else 0 for m in iteration_mappings] for t in self.problem.unique_market_ids],\n            dtype=np.int\n        )\n        self.contraction_evaluations = self.cumulative_contraction_evaluations = np.array(\n            [[m[t] if m else 0 for m in evaluation_mappings] for t in self.problem.unique_market_ids],\n            dtype=np.int\n        )\n        self.converged = self.cumulative_converged = converged\n\n        # initialize last results and add to cumulative values\n        self.last_results = last_results\n        if last_results is not None:\n            self.step += last_results.step\n            self.cumulative_total_time += last_results.cumulative_total_time\n            self.cumulative_optimization_time += last_results.cumulative_optimization_time\n            self.cumulative_optimization_iterations += last_results.cumulative_optimization_iterations\n            self.cumulative_objective_evaluations += last_results.cumulative_objective_evaluations\n            self.cumulative_fp_converged = np.c_[\n                last_results.cumulative_fp_converged, self.cumulative_fp_converged\n            ]\n            self.cumulative_fp_iterations = np.c_[\n                last_results.cumulative_fp_iterations, self.cumulative_fp_iterations\n            ]\n            self.cumulative_contraction_evaluations = np.c_[\n                last_results.cumulative_contraction_evaluations, self.cumulative_contraction_evaluations\n            ]\n            self.cumulative_converged = last_results.converged and converged\n\n        # store estimated parameters and information about them (beta and gamma have already been stored above)\n        self._parameters = progress.parameters\n        self.sigma, self.pi, self.rho, _, _ = self._parameters.expand(self.theta)\n        self.parameters = np.c_[np.r_[\n            self.theta,\n            self.beta[self._parameters.eliminated_beta_index],\n            self.gamma[self._parameters.eliminated_gamma_index]\n        ]]\n        self.sigma_bounds = self._parameters.sigma_bounds\n        self.pi_bounds = self._parameters.pi_bounds\n        self.rho_bounds = self._parameters.rho_bounds\n        self.beta_bounds = self._parameters.beta_bounds\n        self.gamma_bounds = self._parameters.gamma_bounds\n\n        # collect inputs to weighting matrix and standard error computation\n        u_list = [self.xi]\n        Z_list = [self.problem.products.ZD]\n        jacobian_list = [np.c_[\n            self.xi_by_theta_jacobian,\n            -self.problem.products.X1[:, self._parameters.eliminated_beta_index.flat],\n            np.zeros_like(self.problem.products.X3[:, self._parameters.eliminated_gamma_index.flat])\n        ]]\n        if self.problem.K3 > 0:\n            u_list.append(self.omega)\n            Z_list.append(self.problem.products.ZS)\n            jacobian_list.append(np.c_[\n                self.omega_by_theta_jacobian,\n                np.zeros_like(self.problem.products.X1[:, self._parameters.eliminated_beta_index.flat]),\n                -self.problem.products.X3[:, self._parameters.eliminated_gamma_index.flat]\n            ])\n\n        # update the weighting matrix\n        with np.errstate(invalid='ignore'):\n            self.updated_W, W_errors = compute_gmm_weights(\n                u_list, Z_list, W_type, self.problem.products.clustering_ids, center_moments\n            )\n        self._errors.extend(W_errors)\n\n        # compute parameter covariances (if this is the first step, an unadjusted weighting matrix needs to be used so\n        #   that unadjusted covariances are scaled properly)\n        update_W = se_type == 'unadjusted' and self.step == 1\n        with np.errstate(all='ignore'):\n            self.parameter_covariances, covariance_errors = compute_gmm_parameter_covariances(\n                jacobian_list, u_list, Z_list, self.W, se_type, self.problem.products.clustering_ids, update_W\n            )\n        self._errors.extend(covariance_errors)\n\n        # compute standard errors\n        with np.errstate(invalid='ignore'):\n            se = np.sqrt(np.c_[self.parameter_covariances.diagonal()] / self.problem.N)\n        if np.isnan(se).any():\n            self._errors.append(exceptions.InvalidParameterCovariancesError())\n\n        # expand standard errors\n        theta_se, eliminated_beta_se, eliminated_gamma_se = np.split(se, [\n            self._parameters.P,\n            self._parameters.P + self._parameters.eliminated_beta_index.sum()\n        ])\n        self.sigma_se, self.pi_se, self.rho_se, self.beta_se, self.gamma_se = (\n            self._parameters.expand(theta_se, nullify=True)\n        )\n        self.beta_se[self._parameters.eliminated_beta_index] = eliminated_beta_se.flatten()\n        self.gamma_se[self._parameters.eliminated_gamma_index] = eliminated_gamma_se.flatten()\n\n        # expand gradients\n        self.sigma_gradient, self.pi_gradient, self.rho_gradient, self.beta_gradient, self.gamma_gradient = (\n            self._parameters.expand(self.gradient, nullify=True)\n        )\n\n        # store types that are used in other methods\n        self._costs_type = costs_type\n        self._se_type = se_type\n\n    def __str__(self) -> str:\n        \"\"\"Format problem results (including parameters estimates) as a string.\"\"\"\n\n        # construct a standard error description\n        if self._se_type == 'unadjusted':\n            se_description = \"Unadjusted SEs\"\n        elif self._se_type == 'robust':\n            se_description = \"Robust SEs\"\n        else:\n            assert self._se_type == 'clustered'\n            se_description = f'Robust SEs Adjusted for {np.unique(self.problem.products.clustering_ids).size} Clusters'\n\n        # combine a summary table section and another with formatted estimates into one string\n        return \"\\n\\n\".join([\n            self._format_summary(),\n            self._parameters.format_estimates(\n                f\"Estimates ({se_description} in Parentheses)\", self.sigma, self.pi, self.rho, self.beta, self.gamma,\n                self.sigma_se, self.pi_se, self.rho_se, self.beta_se, self.gamma_se\n            )\n        ])\n\n    def _format_summary(self) -> str:\n        \"\"\"Format a summary table of problem results.\"\"\"\n\n        # at a minimum include time and the GMM step\n        floats_index = 3\n        header = [(\"\", \"Computation\", \"Time\"), (\"\", \"GMM\", \"Step\")]\n        values = [format_seconds(self.cumulative_total_time), self.step]\n\n        # include any optimization information\n        if self._parameters.P > 0:\n            floats_index += 1\n            header.append((\"\", \"Optimization\", \"Iterations\"))\n            values.append(self.cumulative_optimization_iterations)\n\n        # include objective evaluation information\n        header.append((\"\", \"Objective\", \"Evaluations\"))\n        values.append(self.cumulative_objective_evaluations)\n\n        # include any fixed point information\n        if np.any(self.cumulative_contraction_evaluations > 0):\n            floats_index += 2\n            header.extend([(\"\", \"Fixed Point\", \"Iterations\"), (\"\", \"Contraction\", \"Evaluations\")])\n            values.extend([self.cumulative_fp_iterations.sum(), self.cumulative_contraction_evaluations.sum()])\n\n        # include any information about the final objective value\n        header.append((\"\", \"Objective\", \"Value\"))\n        values.append(format_number(float(self.objective)))\n        if np.isfinite(self.gradient_norm):\n            header.append((\"\", \"Gradient\", \"Infinity Norm\"))\n            values.append(format_number(float(self.gradient_norm)))\n        if np.isfinite(self.hessian_eigenvalues).any():\n            if self.hessian_eigenvalues.size == 1:\n                header.append((\"\", \"Hessian\", \"Eigenvalue\"))\n                values.append(format_number(float(self.hessian_eigenvalues)))\n            else:\n                header.extend([\n                    (\"Smallest\", \"Hessian\", \"Eigenvalue\"),\n                    (\"Largest\", \"Hessian\", \"Eigenvalue\")\n                ])\n                values.extend([\n                    format_number(float(np.min(self.hessian_eigenvalues))),\n                    format_number(float(np.max(self.hessian_eigenvalues)))\n                ])\n\n        # include any information about clipped marginal costs\n        if np.isfinite(self._costs_bounds).any():\n            header.append((\"Clipped\", \"Marginal\", \"Costs\"))\n            values.append(self.clipped_costs.sum())\n\n        # format the table\n        widths = [max(options.digits + 6 if i >= floats_index else 0, *map(len, k)) for i, k in enumerate(header)]\n        formatter = TableFormatter(widths)\n        lines = [\n            \"Problem Results Summary:\",\n            formatter.line()\n        ]\n        if any(k[0] for k in header):\n            lines.append(formatter([k[0] for k in header]))\n        lines.extend([\n            formatter([k[1] for k in header]),\n            formatter([k[2] for k in header], underline=True),\n            formatter(values),\n            formatter.line()\n        ])\n        return \"\\n\".join(lines)\n\n    def bootstrap(\n            self, draws: int = 1000, seed: Optional[int] = None, iteration: Optional[Iteration] = None) -> (\n            'BootstrappedResults'):\n        r\"\"\"Use a parametric bootstrap to create an empirical distribution of results.\n\n        The constructed :class:`BootstrappedResults` can be used just like :class:`ProblemResults` to compute various\n        post-estimation outputs. The only difference is that :class:`BootstrappedResults` methods return arrays with an\n        extra first dimension, along which bootstrapped results are stacked. These stacked results can be used to\n        construct, for example, confidence intervals for post-estimation outputs.\n\n        For each bootstrap draw, parameters are drawn from the estimated multivariate normal distribution of all\n        parameters defined by :attr:`ProblemResults.parameters` and :attr:`ProblemResults.parameter_covariances`. Note\n        that any bounds configured during the optimization routine will be used to bound parameter draws. These\n        parameters are used to compute the implied mean utility, :math:`\\delta`, and shares, :math:`s`. If a supply side\n        was estimated, the implied marginal costs, :math:`c`, and prices, :math:`p`, are computed as well. Specifically,\n        if a supply side was estimated, equilibrium prices and shares are computed by iterating over the\n        :math:`\\zeta`-markup equation from :ref:`references:Morrow and Skerlos (2011)`.\n\n        .. note::\n\n           By default, the bootstrapping procedure may use a lot of memory. This is because it stores in memory all\n           bootstrapped results (for all ``draws``) at the same time. To reduce the memory footprint of the procedure,\n           call this method in a loop with ``draws`` set to ``1``. In each iteration of the loop, compute the desired\n           post-estimation output with the proper method of the returned :class:`BootstrappedResults` class and store\n           these outputs.\n\n        Parameters\n        ----------\n        draws : `int, optional`\n            The number of draws that will be taken from the joint distribution of the parameters. The default is\n            ``1000``.\n        seed : `int, optional`\n            Passed to :class:`numpy.random.RandomState` to seed the random number generator before any draws are taken.\n            By default, a seed is not passed to the random number generator.\n        iteration : `Iteration, optional`\n            :class:`Iteration` configuration used to compute bootstrapped prices by iterating over the\n            :math:`\\zeta`-markup equation from :ref:`references:Morrow and Skerlos (2011)`. By default, if a supply side\n            was estimated, this is ``Iteration('simple', {'tol': 1e-12})``. Analytic Jacobians are not supported for\n            this contraction mapping and this configuration is not used if a supply side was not estimated.\n\n        Returns\n        -------\n        `BootstrappedResults`\n            Computed :class:`BootstrappedResults`.\n\n        Examples\n        --------\n            - :doc:`Tutorial </tutorial>`\n\n        \"\"\"\n        errors: List[Error] = []\n\n        # keep track of long it takes to bootstrap results\n        output(\"Bootstrapping results ...\")\n        start_time = time.time()\n\n        # validate the number of draws\n        if not isinstance(draws, int) or draws < 1:\n            raise ValueError(\"draws must be a positive int.\")\n\n        # validate the iteration configuration\n        if self.problem.K3 == 0:\n            iteration = None\n        elif iteration is None:\n            iteration = Iteration('simple', {'tol': 1e-12})\n        elif not isinstance(iteration, Iteration):\n            raise TypeError(\"iteration must be None or an iteration instance.\")\n        elif iteration._compute_jacobian:\n            raise ValueError(\"Analytic Jacobians are not supported for this contraction mapping.\")\n\n        # draw from the asymptotic distribution implied by the estimated parameters\n        state = np.random.RandomState(seed)\n        bootstrapped_parameters = np.atleast_3d(state.multivariate_normal(\n            self.parameters.flatten(), self.parameter_covariances, draws\n        ))\n\n        # extract the parameters\n        bootstrapped_sigma = np.zeros((draws, self.sigma.shape[0], self.sigma.shape[1]), options.dtype)\n        bootstrapped_pi = np.zeros((draws, self.pi.shape[0], self.pi.shape[1]), options.dtype)\n        bootstrapped_rho = np.zeros((draws, self.rho.shape[0], self.rho.shape[1]), options.dtype)\n        bootstrapped_beta = np.zeros((draws, self.beta.shape[0], self.beta.shape[1]), options.dtype)\n        bootstrapped_gamma = np.zeros((draws, self.gamma.shape[0], self.gamma.shape[1]), options.dtype)\n        bootstrapped_theta, bootstrapped_eliminated_beta, bootstrapped_eliminated_gamma = np.split(\n            bootstrapped_parameters,\n            [self._parameters.P, self._parameters.P + self._parameters.eliminated_beta_index.sum()],\n            axis=1\n        )\n        bootstrapped_beta[:, self._parameters.eliminated_beta_index.flat] = bootstrapped_eliminated_beta\n        bootstrapped_gamma[:, self._parameters.eliminated_gamma_index.flat] = bootstrapped_eliminated_gamma\n        for d in range(draws):\n            bootstrapped_sigma[d], bootstrapped_pi[d], bootstrapped_rho[d], beta_d, gamma_d = self._parameters.expand(\n                bootstrapped_theta[d]\n            )\n            bootstrapped_beta[d] = np.where(self._parameters.eliminated_beta_index, bootstrapped_beta[d], beta_d)\n            bootstrapped_gamma[d] = np.where(self._parameters.eliminated_gamma_index, bootstrapped_gamma[d], gamma_d)\n            bootstrapped_sigma[d] = np.clip(bootstrapped_sigma[d], *self.sigma_bounds)\n            bootstrapped_pi[d] = np.clip(bootstrapped_pi[d], *self.pi_bounds)\n            bootstrapped_rho[d] = np.clip(bootstrapped_rho[d], *self.rho_bounds)\n            bootstrapped_beta[d] = np.clip(bootstrapped_beta[d], *self.beta_bounds)\n            bootstrapped_gamma[d] = np.clip(bootstrapped_gamma[d], *self.gamma_bounds)\n\n        # compute bootstrapped prices, shares, delta and marginal costs\n        converged_mappings: List[Dict[Hashable, bool]] = []\n        iteration_mappings: List[Dict[Hashable, int]] = []\n        evaluation_mappings: List[Dict[Hashable, int]] = []\n        bootstrapped_prices = np.zeros((draws, self.problem.N, 1), options.dtype)\n        bootstrapped_shares = np.zeros((draws, self.problem.N, 1), options.dtype)\n        bootstrapped_delta = np.zeros((draws, self.problem.N, 1), options.dtype)\n        bootstrapped_costs = np.zeros((draws, self.problem.N, int(self.problem.K3 > 0)), options.dtype)\n        for d in output_progress(range(draws), draws, start_time):\n            prices_d, shares_d, delta_d, costs_d, converged_d, iterations_d, evaluations_d, errors_d = (\n                self._compute_bootstrap(\n                    iteration, bootstrapped_sigma[d], bootstrapped_pi[d], bootstrapped_rho[d], bootstrapped_beta[d],\n                    bootstrapped_gamma[d]\n                )\n            )\n            bootstrapped_prices[d] = prices_d\n            bootstrapped_shares[d] = shares_d\n            bootstrapped_delta[d] = delta_d\n            bootstrapped_costs[d] = costs_d\n            converged_mappings.append(converged_d)\n            iteration_mappings.append(iterations_d)\n            evaluation_mappings.append(evaluations_d)\n            errors.extend(errors_d)\n\n        # structure the results\n        from .bootstrapped_results import BootstrappedResults  # noqa\n        results = BootstrappedResults(\n            self, bootstrapped_sigma, bootstrapped_pi, bootstrapped_rho, bootstrapped_beta, bootstrapped_gamma,\n            bootstrapped_prices, bootstrapped_shares, bootstrapped_delta, bootstrapped_costs, start_time, time.time(),\n            draws, converged_mappings, iteration_mappings, evaluation_mappings\n        )\n        output(f\"Bootstrapped results after {format_seconds(results.computation_time)}.\")\n        output(\"\")\n        output(results)\n        return results\n\n    def _compute_bootstrap(\n            self, iteration: Optional[Iteration], sigma: Array, pi: Array, rho: Array, beta: Array, gamma: Array) -> (\n            Tuple[\n                Array, Array, Array, Array, Dict[Hashable, bool], Dict[Hashable, int], Dict[Hashable, int], List[Error]\n            ]):\n        \"\"\"Compute the equilibrium prices, shares, marginal costs, and delta associated with bootstrapped parameters\n        market-by-market\n        \"\"\"\n        errors: List[Error] = []\n\n        # compute delta (which will change under equilibrium prices) and marginal costs (which won't change)\n        delta = self.delta + self.problem._compute_true_X1() @ (beta - self.beta)\n        costs = self.tilde_costs + self.problem._compute_true_X3() @ (gamma - self.gamma)\n        if self._costs_type == 'log':\n            costs = np.exp(costs)\n\n        # prices will only change if there is an iteration configuration\n        prices = self.problem.products.prices if iteration is None else None\n\n        # define a factory for computing bootstrapped prices, shares, and delta in markets\n        def market_factory(s: Hashable) -> Tuple[ResultsMarket, Array, Optional[Array], Optional[Iteration]]:\n            \"\"\"Build a market along with arguments used to compute equilibrium prices and shares along with delta.\"\"\"\n            market_s = ResultsMarket(self.problem, s, sigma, pi, rho, beta, delta)\n            costs_s = costs[self.problem._product_market_indices[s]]\n            prices_s = prices[self.problem._product_market_indices[s]] if prices is not None else None\n            return market_s, costs_s, prices_s, iteration\n\n        # compute bootstrapped prices, shares, and delta market-by-market\n        converged_mapping: Dict[Hashable, bool] = {}\n        iteration_mapping: Dict[Hashable, int] = {}\n        evaluation_mapping: Dict[Hashable, int] = {}\n        equilibrium_prices = np.zeros_like(self.problem.products.prices)\n        equilibrium_shares = np.zeros_like(self.problem.products.shares)\n        generator = generate_items(self.problem.unique_market_ids, market_factory, ResultsMarket.solve_equilibrium)\n        for t, (prices_t, shares_t, delta_t, errors_t, converged_t, iterations_t, evaluations_t) in generator:\n            equilibrium_prices[self.problem._product_market_indices[t]] = prices_t\n            equilibrium_shares[self.problem._product_market_indices[t]] = shares_t\n            delta[self.problem._product_market_indices[t]] = delta_t\n            errors.extend(errors_t)\n            converged_mapping[t] = converged_t\n            iteration_mapping[t] = iterations_t\n            evaluation_mapping[t] = evaluations_t\n\n        # return all of the information associated with this bootstrap draw\n        return (\n            equilibrium_prices, equilibrium_shares, delta, costs, converged_mapping, iteration_mapping,\n            evaluation_mapping, errors\n        )\n\n    def compute_optimal_instruments(\n            self, method: str = 'normal', draws: int = 100, seed: Optional[int] = None,\n            expected_prices: Optional[Any] = None, iteration: Optional[Iteration] = None) -> 'OptimalInstrumentResults':\n        r\"\"\"Estimate optimal or efficient instruments, :math:`\\mathscr{Z}_D` and :math:`\\mathscr{Z}_S`.\n\n        Optimal instruments have been shown, for example, by :ref:`references:Reynaert and Verboven (2014)`, to reduce\n        bias, improve efficiency, and enhance stability of BLP estimates.\n\n        In the spirit of :ref:`references:Chamberlain (1987)`, optimal instruments for :math:`\\theta` are\n\n        .. math::\n\n           \\begin{bmatrix}\n               \\mathscr{Z}_D \\\\\n               \\mathscr{Z}_S\n           \\end{bmatrix}_{jt}\n           = \\text{Var}(\\xi, \\omega)^{-1}\\operatorname{\\mathbb{E}}\\left[\n           \\begin{matrix}\n               \\frac{\\partial\\xi_{jt}}{\\partial\\theta} \\\\\n               \\frac{\\partial\\omega_{jt}}{\\partial\\theta}\n           \\end{matrix}\n           \\mathrel{\\Bigg|} Z \\right],\n\n        The expectation is taken by integrating over the joint density of :math:`\\xi` and :math:`\\omega`. For each error\n        term realization, if not already estimated, equilibrium prices are computed via iteration over the\n        :math:`\\zeta`-markup equation from :ref:`references:Morrow and Skerlos (2011)`. Associated shares and\n        :math:`\\delta` are then computed before each Jacobian is evaluated.\n\n        The expected Jacobians are estimated with the average over all computed Jacobian realizations. The normalizing\n        matrix :math:`\\text{Var}(\\xi, \\omega)^{-1}` is estimated with the sample covariance matrix of the error terms.\n\n        Optimal instruments for linear parameters not included in :math:`\\theta` are simple product characteristics, so\n        they are not computed here but are rather included in the set of instruments by\n        :meth:`OptimalInstrumentResults.to_problem`.\n\n        Parameters\n        ----------\n        method : `str, optional`\n            The method by which the integral over the joint density of :math:`\\xi` and :math:`\\omega` is computed. The\n            following methods are supported:\n\n                - ``'normal'`` (default) - Draw from the normal approximation to the joint distribution of the error\n                  terms and take the average over the computed Jacobians (``draws`` determines the number of draws).\n\n                - ``'empirical'`` - Draw with replacement from the empirical joint distribution of the error terms and\n                  take the average over the computed Jacobians (``draws`` determines the number of draws).\n\n                - ``'approximate'`` - Evaluate the Jacobians at the expected value of the error terms: zero (``draws``\n                  will be ignored).\n\n        draws : `int, optional`\n            The number of draws that will be taken from the joint distribution of the error terms. This is ignored if\n            ``method`` is ``'approximate'``. The default is ``100``.\n        seed : `int, optional`\n            Passed to :class:`numpy.random.RandomState` to seed the random number generator before any draws are taken.\n            By default, a seed is not passed to the random number generator.\n        expected_prices : `array-like, optional`\n            Vector of expected prices conditional on all exogenous variables,\n            :math:`\\operatorname{\\mathbb{E}}[p \\mid Z]`. By default, if a supply side was estimated, ``iteration`` is\n            used. If only a demand side was estimated, this is by default estimated with the fitted values from a\n            reduced form regression of endogenous prices onto :math:`Z_D`: all exogenous variables including excluded\n            instruments.\n        iteration : `Iteration, optional`\n            :class:`Iteration` configuration used to estimate expected prices by iterating over the :math:`\\zeta`-markup\n            equation from :ref:`references:Morrow and Skerlos (2011)`. By default, if a supply side was estimated, this\n            is ``Iteration('simple', {'tol': 1e-12})``. Analytic Jacobians are not supported for this contraction\n            mapping and this configuration is not used if ``expected_prices`` is specified.\n\n        Returns\n        -------\n        `OptimalInstrumentResults`\n           Computed :class:`OptimalInstrumentResults`.\n\n        Examples\n        --------\n            - :doc:`Tutorial </tutorial>`\n\n        \"\"\"\n        errors: List[Error] = []\n\n        # keep track of long it takes to compute optimal instruments for theta\n        output(\"Computing optimal instruments for theta ...\")\n        start_time = time.time()\n\n        # validate the method and create a function that samples from the error distribution\n        if method == 'approximate':\n            sample = lambda: (np.zeros_like(self.xi), np.zeros_like(self.omega))\n        else:\n            state = np.random.RandomState(seed)\n            if method == 'normal':\n                if self.problem.K3 == 0:\n                    variance = np.var(self.xi)\n                    sample = lambda: (np.c_[state.normal(0, variance, self.problem.N)], self.omega)\n                else:\n                    covariances = np.cov(self.xi, self.omega, rowvar=False)\n                    sample = lambda: np.hsplit(state.multivariate_normal([0, 0], covariances, self.problem.N), 2)\n            elif method == 'empirical':\n                if self.problem.K3 == 0:\n                    sample = lambda: (self.xi[state.choice(self.problem.N, self.problem.N)], self.omega)\n                else:\n                    joint = np.c_[self.xi, self.omega]\n                    sample = lambda: np.hsplit(joint[state.choice(self.problem.N, self.problem.N)], 2)\n            else:\n                raise ValueError(\"method must be 'approximate', 'normal', or 'empirical'.\")\n\n        # validate the number of draws (there will be only one for the approximate method)\n        if method == 'approximate':\n            draws = 1\n        if not isinstance(draws, int) or draws < 1:\n            raise ValueError(\"draws must be a positive int.\")\n\n        # validate expected prices or their integration configuration (or compute expected prices with a reduced form\n        #   regression if unspecified and only a demand side)\n        if expected_prices is not None:\n            iteration = None\n            expected_prices = np.c_[np.asarray(expected_prices, options.dtype)]\n            if expected_prices.shape != (self.problem.N, 1):\n                raise ValueError(f\"expected_prices must be a {self.problem.N}-vector.\")\n        elif self.problem.K3 > 0:\n            if iteration is None:\n                iteration = Iteration('simple', {'tol': 1e-12})\n            elif not isinstance(iteration, Iteration):\n                raise TypeError(\"iteration must be None or an Iteration instance.\")\n        else:\n            prices = self.problem.products.prices\n            if self.problem._absorb_demand_ids is not None:\n                prices, absorption_errors = self.problem._absorb_demand_ids(prices)\n                errors.extend(absorption_errors)\n            covariances = self.problem.products.ZD.T @ self.problem.products.ZD\n            parameters, replacement = approximately_solve(covariances, self.problem.products.ZD.T @ prices)\n            if replacement:\n                errors.append(exceptions.FittedValuesInversionError(covariances, replacement))\n            expected_prices = self.problem.products.ZD @ parameters + self.problem.products.prices - prices\n\n        # validate expected prices or their iteration configuration\n        if expected_prices is None:\n            if self.problem.K3 == 0:\n                raise TypeError(\"A supply side was not estimated, so expected_prices must be specified.\")\n            if iteration is None:\n                iteration = Iteration('simple', {'tol': 1e-12})\n            elif not isinstance(iteration, Iteration):\n                raise TypeError(\"iteration must be None or an Iteration instance.\")\n            elif iteration._compute_jacobian:\n                raise ValueError(\"Analytic Jacobians are not supported for this contraction mapping.\")\n        else:\n            iteration = None\n            expected_prices = np.c_[np.asarray(expected_prices, options.dtype)]\n            if expected_prices.shape != (self.problem.N, 1):\n                raise ValueError(f\"expected_prices must be a {self.problem.N}-vector.\")\n\n        # average over Jacobian realizations\n        converged_mappings: List[Dict[Hashable, bool]] = []\n        iteration_mappings: List[Dict[Hashable, int]] = []\n        evaluation_mappings: List[Dict[Hashable, int]] = []\n        expected_xi_jacobian = np.zeros_like(self.xi_by_theta_jacobian)\n        expected_omega_jacobian = np.zeros_like(self.omega_by_theta_jacobian)\n        for _ in output_progress(range(draws), draws, start_time):\n            xi_jacobian_i, omega_jacobian_i, converged_i, iterations_i, evaluations_i, errors_i = (\n                self._compute_realizations(expected_prices, iteration, *sample())\n            )\n            expected_xi_jacobian += xi_jacobian_i / draws\n            expected_omega_jacobian += omega_jacobian_i / draws\n            converged_mappings.append(converged_i)\n            iteration_mappings.append(iterations_i)\n            evaluation_mappings.append(evaluations_i)\n            errors.extend(errors_i)\n\n        # output a warning about any errors\n        if errors:\n            output(\"\")\n            output(exceptions.MultipleErrors(errors))\n            output(\"\")\n\n        # compute the optimal instruments\n        if self.problem.K3 == 0:\n            inverse_covariance_matrix = np.c_[1 / np.var(self.xi)]\n            demand_instruments = inverse_covariance_matrix * expected_xi_jacobian\n            supply_instruments = np.full((self.problem.N, 0), np.nan, options.dtype)\n        else:\n            inverse_covariance_matrix = np.c_[scipy.linalg.inv(np.cov(self.xi, self.omega, rowvar=False))]\n            instruments = multiply_matrix_and_tensor(\n                inverse_covariance_matrix,\n                np.stack([expected_xi_jacobian, expected_omega_jacobian], axis=1)\n            )\n            demand_instruments, supply_instruments = np.split(instruments.reshape((self.problem.N, -1)), 2, axis=1)\n\n        # structure the results\n        from .optimal_instrument_results import OptimalInstrumentResults  # noqa\n        results = OptimalInstrumentResults(\n            self, demand_instruments, supply_instruments, inverse_covariance_matrix, expected_xi_jacobian,\n            expected_omega_jacobian, expected_prices, start_time, time.time(), draws, converged_mappings,\n            iteration_mappings, evaluation_mappings\n        )\n        output(f\"Computed optimal instruments after {format_seconds(results.computation_time)}.\")\n        output(\"\")\n        output(results)\n        return results\n\n    def _compute_realizations(\n            self, expected_prices: Optional[Array], iteration: Optional[Iteration], xi: Array, omega: Array) -> (\n            Tuple[Array, Array, Dict[Hashable, bool], Dict[Hashable, int], Dict[Hashable, int], List[Error]]):\n        \"\"\"If they have not already been estimated, compute the equilibrium prices, shares, and delta associated with a\n        realization of xi and omega market-by-market. Then, compute realizations of Jacobians of xi and omega with\n        respect to theta.\n        \"\"\"\n        errors: List[Error] = []\n\n        # compute delta (which will change under equilibrium prices) and marginal costs (which won't change)\n        delta = self.delta - self.xi + xi\n        costs = tilde_costs = self.tilde_costs - self.omega + omega\n        if self._costs_type == 'log':\n            costs = np.exp(costs)\n\n        # define a factory for computing realizations of prices, shares, and delta in markets\n        def market_factory(s: Hashable) -> Tuple[ResultsMarket, Array, Optional[Array], Optional[Iteration]]:\n            \"\"\"Build a market along with arguments used to compute equilibrium prices and shares along with delta.\"\"\"\n            market_s = ResultsMarket(self.problem, s, self.sigma, self.pi, self.rho, self.beta, delta)\n            costs_s = costs[self.problem._product_market_indices[s]]\n            prices_s = expected_prices[self.problem._product_market_indices[s]] if expected_prices is not None else None\n            return market_s, costs_s, prices_s, iteration\n\n        # compute realizations of prices, shares, and delta market-by-market\n        converged_mapping: Dict[Hashable, bool] = {}\n        iteration_mapping: Dict[Hashable, int] = {}\n        evaluation_mapping: Dict[Hashable, int] = {}\n        equilibrium_prices = np.zeros_like(self.problem.products.prices)\n        equilibrium_shares = np.zeros_like(self.problem.products.shares)\n        generator = generate_items(self.problem.unique_market_ids, market_factory, ResultsMarket.solve_equilibrium)\n        for t, (prices_t, shares_t, delta_t, errors_t, converged_t, iterations_t, evaluations_t) in generator:\n            equilibrium_prices[self.problem._product_market_indices[t]] = prices_t\n            equilibrium_shares[self.problem._product_market_indices[t]] = shares_t\n            delta[self.problem._product_market_indices[t]] = delta_t\n            errors.extend(errors_t)\n            converged_mapping[t] = converged_t\n            iteration_mapping[t] = iterations_t\n            evaluation_mapping[t] = evaluations_t\n\n        # compute the Jacobian of xi with respect to theta\n        xi_jacobian, demand_errors = self._compute_demand_realization(equilibrium_prices, equilibrium_shares, delta)\n        errors.extend(demand_errors)\n\n        # compute the Jacobian of omega with respect to theta\n        omega_jacobian = np.full((self.problem.N, self._parameters.P), np.nan, options.dtype)\n        if self.problem.K3 > 0:\n            omega_jacobian, supply_errors = self._compute_supply_realization(\n                equilibrium_prices, equilibrium_shares, delta, tilde_costs, xi_jacobian\n            )\n            errors.extend(supply_errors)\n\n        # return all of the information associated with this realization\n        return xi_jacobian, omega_jacobian, converged_mapping, iteration_mapping, evaluation_mapping, errors\n\n    def _compute_demand_realization(\n            self, equilibrium_prices: Array, equilibrium_shares: Array, delta: Array) -> Tuple[Array, List[Error]]:\n        \"\"\"Compute a realization of the Jacobian of xi with respect to theta market-by-market. If necessary, revert\n        problematic elements to their estimated values.\n        \"\"\"\n        errors: List[Error] = []\n\n        # check if the Jacobian does not need to be computed\n        xi_jacobian = np.full((self.problem.N, self._parameters.P), np.nan, options.dtype)\n        if self._parameters.P == 0:\n            return xi_jacobian, errors\n\n        # define a factory for computing the Jacobian of xi with respect to theta in markets\n        def market_factory(s: Hashable) -> Tuple[ResultsMarket, Parameters]:\n            \"\"\"Build a market with the data realization along with arguments used to compute the Jacobian.\"\"\"\n            data_override_s = {\n                'prices': equilibrium_prices[self.problem._product_market_indices[s]],\n                'shares': equilibrium_shares[self.problem._product_market_indices[s]]\n            }\n            market_s = ResultsMarket(self.problem, s, self.sigma, self.pi, self.rho, self.beta, delta, data_override_s)\n            return market_s, self._parameters\n\n        # compute the Jacobian market-by-market\n        generator = generate_items(\n            self.problem.unique_market_ids, market_factory, ResultsMarket.compute_xi_by_theta_jacobian\n        )\n        for t, (xi_jacobian_t, errors_t) in generator:\n            xi_jacobian[self.problem._product_market_indices[t]] = xi_jacobian_t\n            errors.extend(errors_t)\n\n        # replace invalid elements\n        bad_jacobian_index = ~np.isfinite(xi_jacobian)\n        if np.any(bad_jacobian_index):\n            xi_jacobian[bad_jacobian_index] = self.xi_by_theta_jacobian[bad_jacobian_index]\n            errors.append(exceptions.XiByThetaJacobianReversionError(bad_jacobian_index))\n        return xi_jacobian, errors\n\n    def _compute_supply_realization(\n            self, equilibrium_prices: Array, equilibrium_shares: Array, delta: Array, tilde_costs: Array,\n            xi_jacobian: Array) -> Tuple[Array, List[Error]]:\n        \"\"\"Compute a realization of the Jacobian of omega with respect to theta market-by-market. If necessary, revert\n        problematic elements to their estimated values.\n        \"\"\"\n        errors: List[Error] = []\n\n        # define a factory for computing the Jacobian of omega with respect to theta in markets\n        def market_factory(s: Hashable) -> Tuple[ResultsMarket, Array, Array, Parameters, str]:\n            \"\"\"Build a market with the data realization along with arguments used to compute the Jacobians.\"\"\"\n            data_override_s = {\n                'prices': equilibrium_prices[self.problem._product_market_indices[s]],\n                'shares': equilibrium_shares[self.problem._product_market_indices[s]]\n            }\n            market_s = ResultsMarket(self.problem, s, self.sigma, self.pi, self.rho, self.beta, delta, data_override_s)\n            tilde_costs_s = tilde_costs[self.problem._product_market_indices[s]]\n            xi_jacobian_s = xi_jacobian[self.problem._product_market_indices[s]]\n            return market_s, tilde_costs_s, xi_jacobian_s, self._parameters, self._costs_type\n\n        # compute the Jacobian market-by-market\n        omega_jacobian = np.full((self.problem.N, self._parameters.P), np.nan, options.dtype)\n        generator = generate_items(\n            self.problem.unique_market_ids, market_factory, ResultsMarket.compute_omega_by_theta_jacobian\n        )\n        for t, (omega_jacobian_t, errors_t) in generator:\n            omega_jacobian[self.problem._product_market_indices[t]] = omega_jacobian_t\n            errors.extend(errors_t)\n\n        # the Jacobian should be zero for any clipped marginal costs\n        omega_jacobian[self.clipped_costs.flat] = 0\n\n        # replace invalid elements\n        bad_jacobian_index = ~np.isfinite(omega_jacobian)\n        if np.any(bad_jacobian_index):\n            omega_jacobian[bad_jacobian_index] = self.omega_by_theta_jacobian[bad_jacobian_index]\n            errors.append(exceptions.OmegaByThetaJacobianReversionError(bad_jacobian_index))\n        return omega_jacobian, errors\n\n    def _coerce_matrices(self, matrices: Any) -> Array:\n        \"\"\"Coerce array-like stacked matrices into a stacked matrix and validate it.\"\"\"\n        matrices = np.c_[np.asarray(matrices, options.dtype)]\n        if matrices.shape != (self.problem.N, self.problem._max_J):\n            raise ValueError(f\"matrices must be {self.problem.N} by {self.problem._max_J}.\")\n        return matrices\n\n    def _coerce_optional_costs(self, costs: Optional[Any]) -> Array:\n        \"\"\"Coerce optional array-like costs into a column vector and validate it.\"\"\"\n        if costs is not None:\n            costs = np.c_[np.asarray(costs, options.dtype)]\n            if costs.shape != (self.problem.N, 1):\n                raise ValueError(f\"costs must be None or a {self.problem.N}-vector.\")\n        return costs\n\n    def _coerce_optional_prices(self, prices: Optional[Any]) -> Array:\n        \"\"\"Coerce optional array-like prices into a column vector and validate it.\"\"\"\n        if prices is not None:\n            prices = np.c_[np.asarray(prices, options.dtype)]\n            if prices.shape != (self.problem.N, 1):\n                raise ValueError(f\"prices must be None or a {self.problem.N}-vector.\")\n        return prices\n\n    def _coerce_optional_shares(self, shares: Optional[Any]) -> Array:\n        \"\"\"Coerce optional array-like shares into a column vector and validate it.\"\"\"\n        if shares is not None:\n            shares = np.c_[np.asarray(shares, options.dtype)]\n            if shares.shape != (self.problem.N, 1):\n                raise ValueError(f\"shares must be None or a {self.problem.N}-vector.\")\n        return shares\n\n    def _combine_arrays(\n            self, compute_market_results: Callable, fixed_args: Sequence = (), market_args: Sequence = ()) -> Array:\n        \"\"\"Compute an array for each market and stack them into a single matrix. An array for a single market is\n        computed by passing fixed_args (identical for all markets) and market_args (matrices with as many rows as there\n        are products that are restricted to the market) to compute_market_results, a ResultsMarket method that returns\n        the output for the market and a set of any errors encountered during computation.\n        \"\"\"\n        errors: List[Error] = []\n\n        # keep track of how long it takes to compute the arrays\n        start_time = time.time()\n\n        # define a factory for computing arrays in markets\n        def market_factory(s: Hashable) -> tuple:\n            \"\"\"Build a market along with arguments used to compute arrays.\"\"\"\n            indices_s = self.problem._product_market_indices[s]\n            market_s = ResultsMarket(self.problem, s, self.sigma, self.pi, self.rho, self.beta, self.delta)\n            args_s = [None if a is None else a[indices_s] for a in market_args]\n            return (market_s, *fixed_args, *args_s)\n\n        # construct a mapping from market IDs to market-specific arrays\n        matrix_mapping: Dict[Hashable, Array] = {}\n        generator = output_progress(\n            generate_items(self.problem.unique_market_ids, market_factory, compute_market_results), self.problem.T,\n            start_time\n        )\n        for t, (array_t, errors_t) in generator:\n            matrix_mapping[t] = np.c_[array_t]\n            errors.extend(errors_t)\n\n        # output a warning about any errors\n        if errors:\n            output(\"\")\n            output(exceptions.MultipleErrors(errors))\n            output(\"\")\n\n        # determine the number of rows and columns\n        row_count = sum(matrix_mapping[t].shape[0] for t in self.problem.unique_market_ids)\n        column_count = max(matrix_mapping[t].shape[1] for t in self.problem.unique_market_ids)\n\n        # preserve the original product order or the sorted market order when stacking the arrays\n        combined = np.full((row_count, column_count), np.nan, options.dtype)\n        for t, matrix_t in matrix_mapping.items():\n            if row_count == self.problem.N:\n                combined[self.problem._product_market_indices[t], :matrix_t.shape[1]] = matrix_t\n            else:\n                combined[self.problem.unique_market_ids == t, :matrix_t.shape[1]] = matrix_t\n\n        # output how long it took to compute the arrays\n        end_time = time.time()\n        output(f\"Finished after {format_seconds(end_time - start_time)}.\")\n        output(\"\")\n        return combined\n", "meta": {"hexsha": "222e8278e81c41ac1dc2eabc5ad020c745a67804", "size": 56667, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyblp/results/problem_results.py", "max_stars_repo_name": "yusukeaoki1223/pyblp", "max_stars_repo_head_hexsha": "71cea45251f3772ef8f3dc62c7e47b9820308396", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-02-10T14:25:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-10T14:25:08.000Z", "max_issues_repo_path": "pyblp/results/problem_results.py", "max_issues_repo_name": "yusukeaoki1223/pyblp", "max_issues_repo_head_hexsha": "71cea45251f3772ef8f3dc62c7e47b9820308396", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyblp/results/problem_results.py", "max_forks_repo_name": "yusukeaoki1223/pyblp", "max_forks_repo_head_hexsha": "71cea45251f3772ef8f3dc62c7e47b9820308396", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.8117427773, "max_line_length": 120, "alphanum_fraction": 0.6668607832, "include": true, "reason": "import numpy,import scipy", "num_tokens": 12301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.18998546820621814}}
{"text": "\nimport os\nimport time\nimport re\nfrom contextlib import contextmanager\nfrom copy import copy\nfrom pathlib import Path\n\nimport numpy as np\nimport math\nimport torch\nimport torch.nn as nn\nfrom helper.torch_utils import is_parallel\n\n@contextmanager\ndef torch_distributed_zero_first(local_rank: int):\n    \"\"\"\n    Decorator to make all processes in distributed training wait for each local_master to do something.\n    \"\"\"\n    if local_rank not in [-1, 0]:\n        torch.distributed.barrier()\n    yield\n    if local_rank == 0:\n        torch.distributed.barrier()\n\ndef xywh2xyxy(x):\n    # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right\n    y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x)\n    y[:, 0] = x[:, 0] - x[:, 2] / 2  # top left x\n    y[:, 1] = x[:, 1] - x[:, 3] / 2  # top left y\n    y[:, 2] = x[:, 0] + x[:, 2] / 2  # bottom right x\n    y[:, 3] = x[:, 1] + x[:, 3] / 2  # bottom right y\n    return y\n\ndef xyxy2xywh(x):\n    # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right\n    y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x)\n    y[:, 0] = (x[:, 0] + x[:, 2]) / 2  # x center\n    y[:, 1] = (x[:, 1] + x[:, 3]) / 2  # y center\n    y[:, 2] = x[:, 2] - x[:, 0]  # width\n    y[:, 3] = x[:, 3] - x[:, 1]  # height\n    return y\n\ndef smooth_BCE(eps=0.1):  # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441\n    # return positive, negative label smoothing BCE targets\n    return 1.0 - 0.5 * eps, 0.5 * eps\n\ndef compute_ap(recall, precision):\n    \"\"\" Compute the average precision, given the recall and precision curves.\n    Source: https://github.com/rbgirshick/py-faster-rcnn.\n    # Arguments\n        recall:    The recall curve (list).\n        precision: The precision curve (list).\n    # Returns\n        The average precision as computed in py-faster-rcnn.\n    \"\"\"\n\n    # Append sentinel values to beginning and end\n    mrec = np.concatenate(([0.], recall, [min(recall[-1] + 1E-3, 1.)]))\n    mpre = np.concatenate(([0.], precision, [0.]))\n\n    # Compute the precision envelope\n    mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))\n\n    # Integrate area under curve\n    method = 'interp'  # methods: 'continuous', 'interp'\n    if method == 'interp':\n        x = np.linspace(0, 1, 101)  # 101-point interp (COCO)\n        ap = np.trapz(np.interp(x, mrec, mpre), x)  # integrate\n    else:  # 'continuous'\n        i = np.where(mrec[1:] != mrec[:-1])[0]  # points where x axis (recall) changes\n        ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])  # area under curve\n\n    return ap\n\nclass FocalLoss(nn.Module):\n    # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)\n    def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):\n        super(FocalLoss, self).__init__()\n        self.loss_fcn = loss_fcn  # must be nn.BCEWithLogitsLoss()\n        self.gamma = gamma\n        self.alpha = alpha\n        self.reduction = loss_fcn.reduction\n        self.loss_fcn.reduction = 'none'  # required to apply FL to each element\n\n    def forward(self, pred, true):\n        loss = self.loss_fcn(pred, true)\n        # p_t = torch.exp(-loss)\n        # loss *= self.alpha * (1.000001 - p_t) ** self.gamma  # non-zero power for gradient stability\n\n        # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py\n        pred_prob = torch.sigmoid(pred)  # prob from logits\n        p_t = true * pred_prob + (1 - true) * (1 - pred_prob)\n        alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)\n        modulating_factor = (1.0 - p_t) ** self.gamma\n        loss *= alpha_factor * modulating_factor\n\n        if self.reduction == 'mean':\n            return loss.mean()\n        elif self.reduction == 'sum':\n            return loss.sum()\n        else:  # 'none'\n            return loss\n\ndef build_targets(p, targets, model):\n    # Build targets for compute_loss(), input targets(image,class,x,y,w,h)\n    det = model.module.model[-1] if is_parallel(model) else model.model[-1]  # Detect() module\n    na, nt = det.na, targets.shape[0]  # number of anchors, targets\n    tcls, tbox, indices, anch = [], [], [], []\n    gain = torch.ones(7, device=targets.device)  # normalized to gridspace gain\n    ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt)  # same as .repeat_interleave(nt)\n    targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2)  # append anchor indices\n\n    g = 0.5  # bias\n    off = torch.tensor([[0, 0],\n                        [1, 0], [0, 1], [-1, 0], [0, -1],  # j,k,l,m\n                        # [1, 1], [1, -1], [-1, 1], [-1, -1],  # jk,jm,lk,lm\n                        ], device=targets.device).float() * g  # offsets\n\n    for i in range(det.nl):\n        anchors = det.anchors[i]\n        gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]]  # xyxy gain\n\n        # Match targets to anchors\n        t = targets * gain\n        if nt:\n            # Matches\n            r = t[:, :, 4:6] / anchors[:, None]  # wh ratio\n            j = torch.max(r, 1. / r).max(2)[0] < model.hyp['anchor_t']  # compare\n            # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t']  # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))\n            t = t[j]  # filter\n\n            # Offsets\n            gxy = t[:, 2:4]  # grid xy\n            gxi = gain[[2, 3]] - gxy  # inverse\n            j, k = ((gxy % 1. < g) & (gxy > 1.)).T\n            l, m = ((gxi % 1. < g) & (gxi > 1.)).T\n            j = torch.stack((torch.ones_like(j), j, k, l, m))\n            t = t.repeat((5, 1, 1))[j]\n            offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]\n        else:\n            t = targets[0]\n            offsets = 0\n\n        # Define\n        b, c = t[:, :2].long().T  # image, class\n        gxy = t[:, 2:4]  # grid xy\n        gwh = t[:, 4:6]  # grid wh\n        gij = (gxy - offsets).long()\n        gi, gj = gij.T  # grid xy indices\n\n        # Append\n        a = t[:, 6].long()  # anchor indices\n        indices.append((b, a, gj, gi))  # image, anchor, grid indices\n        tbox.append(torch.cat((gxy - gij, gwh), 1))  # box\n        anch.append(anchors[a])  # anchors\n        tcls.append(c)  # class\n\n    return tcls, tbox, indices, anch\n\ndef bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-9):\n    # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4\n    box2 = box2.T\n\n    # Get the coordinates of bounding boxes\n    if x1y1x2y2:  # x1, y1, x2, y2 = box1\n        b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]\n        b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]\n    else:  # transform from xywh to xyxy\n        b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2\n        b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2\n        b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2\n        b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2\n\n    # Intersection area\n    inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \\\n            (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)\n\n    # Union Area\n    w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps\n    w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps\n    union = w1 * h1 + w2 * h2 - inter + eps\n\n    iou = inter / union\n    if GIoU or DIoU or CIoU:\n        cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1)  # convex (smallest enclosing box) width\n        ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1)  # convex height\n        if CIoU or DIoU:  # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1\n            c2 = cw ** 2 + ch ** 2 + eps  # convex diagonal squared\n            rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 +\n                    (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4  # center distance squared\n            if DIoU:\n                return iou - rho2 / c2  # DIoU\n            elif CIoU:  # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47\n                v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)\n                with torch.no_grad():\n                    alpha = v / ((1 + eps) - iou + v)\n                return iou - (rho2 / c2 + v * alpha)  # CIoU\n        else:  # GIoU https://arxiv.org/pdf/1902.09630.pdf\n            c_area = cw * ch + eps  # convex area\n            return iou - (c_area - union) / c_area  # GIoU\n    else:\n        return iou  # IoU\n\ndef ap_per_class(tp, conf, pred_cls, target_cls, plot=False, fname='precision-recall_curve.png'):\n    \"\"\" Compute the average precision, given the recall and precision curves.\n    Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.\n    # Arguments\n        tp:  True positives (nparray, nx1 or nx10).\n        conf:  Objectness value from 0-1 (nparray).\n        pred_cls:  Predicted object classes (nparray).\n        target_cls:  True object classes (nparray).\n        plot:  Plot precision-recall curve at mAP@0.5\n        fname:  Plot filename\n    # Returns\n        The average precision as computed in py-faster-rcnn.\n    \"\"\"\n\n    # Sort by objectness\n    i = np.argsort(-conf)\n    tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]\n\n    # Find unique classes\n    unique_classes = np.unique(target_cls)\n\n    # Create Precision-Recall curve and compute AP for each class\n    px, py = np.linspace(0, 1, 1000), []  # for plotting\n    pr_score = 0.1  # score to evaluate P and R https://github.com/ultralytics/yolov3/issues/898\n    s = [unique_classes.shape[0], tp.shape[1]]  # number class, number iou thresholds (i.e. 10 for mAP0.5...0.95)\n    ap, p, r = np.zeros(s), np.zeros(s), np.zeros(s)\n    for ci, c in enumerate(unique_classes):\n        i = pred_cls == c\n        n_gt = (target_cls == c).sum()  # Number of ground truth objects\n        n_p = i.sum()  # Number of predicted objects\n\n        if n_p == 0 or n_gt == 0:\n            continue\n        else:\n            # Accumulate FPs and TPs\n            fpc = (1 - tp[i]).cumsum(0)\n            tpc = tp[i].cumsum(0)\n\n            # Recall\n            recall = tpc / (n_gt + 1e-16)  # recall curve\n            r[ci] = np.interp(-pr_score, -conf[i], recall[:, 0])  # r at pr_score, negative x, xp because xp decreases\n\n            # Precision\n            precision = tpc / (tpc + fpc)  # precision curve\n            p[ci] = np.interp(-pr_score, -conf[i], precision[:, 0])  # p at pr_score\n\n            # AP from recall-precision curve\n            py.append(np.interp(px, recall[:, 0], precision[:, 0]))  # precision at mAP@0.5\n            for j in range(tp.shape[1]):\n                ap[ci, j] = compute_ap(recall[:, j], precision[:, j])\n\n    # Compute F1 score (harmonic mean of precision and recall)\n    f1 = 2 * p * r / (p + r + 1e-16)\n\n    return p, r, ap, f1, unique_classes.astype('int32')\n\ndef box_iou(box1, box2):\n    # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py\n    \"\"\"\n    Return intersection-over-union (Jaccard index) of boxes.\n    Both sets of boxes are expected to be in (x1, y1, x2, y2) format.\n    Arguments:\n        box1 (Tensor[N, 4])\n        box2 (Tensor[M, 4])\n    Returns:\n        iou (Tensor[N, M]): the NxM matrix containing the pairwise\n            IoU values for every element in boxes1 and boxes2\n    \"\"\"\n\n    def box_area(box):\n        # box = 4xn\n        return (box[2] - box[0]) * (box[3] - box[1])\n\n    area1 = box_area(box1.T)\n    area2 = box_area(box2.T)\n\n    # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)\n    inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)\n    return inter / (area1[:, None] + area2 - inter)  # iou = inter / (area1 + area2 - inter)\n\ndef clip_coords(boxes, img_shape):\n    # Clip bounding xyxy bounding boxes to image shape (height, width)\n    boxes[:, 0].clamp_(0, img_shape[1])  # x1\n    boxes[:, 1].clamp_(0, img_shape[0])  # y1\n    boxes[:, 2].clamp_(0, img_shape[1])  # x2\n    boxes[:, 3].clamp_(0, img_shape[0])  # y2\n\ndef non_max_suppression(prediction, conf_thres=0.1, iou_thres=0.6, merge=False, classes=None, agnostic=False):\n    \"\"\"Performs Non-Maximum Suppression (NMS) on inference results\n\n    Returns:\n         detections with shape: nx6 (x1, y1, x2, y2, conf, cls)\n    \"\"\"\n\n    nc = prediction[0].shape[1] - 5  # number of classes\n    xc = prediction[..., 4] > conf_thres  # candidates\n\n    # Settings\n    min_wh, max_wh = 2, 4096  # (pixels) minimum and maximum box width and height\n    max_det = 300  # maximum number of detections per image\n    time_limit = 10.0  # seconds to quit after\n    redundant = True  # require redundant detections\n    multi_label = nc > 1  # multiple labels per box (adds 0.5ms/img)\n\n    t = time.time()\n    output = [None] * prediction.shape[0]\n    for xi, x in enumerate(prediction):  # image index, image inference\n        # Apply constraints\n        # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0  # width-height\n        x = x[xc[xi]]  # confidence\n\n        # If none remain process next image\n        if not x.shape[0]:\n            continue\n\n        # Compute conf\n        x[:, 5:] *= x[:, 4:5]  # conf = obj_conf * cls_conf\n\n        # Box (center x, center y, width, height) to (x1, y1, x2, y2)\n        box = xywh2xyxy(x[:, :4])\n\n        # Detections matrix nx6 (xyxy, conf, cls)\n        if multi_label:\n            i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T\n            x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)\n        else:  # best class only\n            conf, j = x[:, 5:].max(1, keepdim=True)\n            x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]\n\n        # Filter by class\n        if classes:\n            x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]\n\n        # Apply finite constraint\n        # if not torch.isfinite(x).all():\n        #     x = x[torch.isfinite(x).all(1)]\n\n        # If none remain process next image\n        n = x.shape[0]  # number of boxes\n        if not n:\n            continue\n\n        # Sort by confidence\n        # x = x[x[:, 4].argsort(descending=True)]\n\n        # Batched NMS\n        c = x[:, 5:6] * (0 if agnostic else max_wh)  # classes\n        boxes, scores = x[:, :4] + c, x[:, 4]  # boxes (offset by class), scores\n        i = torch.ops.torchvision.nms(boxes, scores, iou_thres)\n        if i.shape[0] > max_det:  # limit detections\n            i = i[:max_det]\n        if merge and (1 < n < 3E3):  # Merge NMS (boxes merged using weighted mean)\n            try:  # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)\n                iou = box_iou(boxes[i], boxes) > iou_thres  # iou matrix\n                weights = iou * scores[None]  # box weights\n                x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True)  # merged boxes\n                if redundant:\n                    i = i[iou.sum(1) > 1]  # require redundancy\n            except:  # possible CUDA error https://github.com/ultralytics/yolov3/issues/1139\n                print(x, i, x.shape, i.shape)\n                pass\n\n        output[xi] = x[i]\n        if (time.time() - t) > time_limit:\n            break  # time limit exceeded\n\n    return output\n\n\ndef compute_loss(p, targets, model):  # predictions, targets, model\n    device = targets.device\n    lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)\n    tcls, tbox, indices, anchors = build_targets(p, targets, model)  # targets\n    h = model.hyp  # hyperparameters\n\n    # Define criteria\n    BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.Tensor([h['cls_pw']])).to(device)\n    BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.Tensor([h['obj_pw']])).to(device)\n\n    # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3\n    cp, cn = smooth_BCE(eps=0.0)\n\n    # Focal loss\n    g = h['fl_gamma']  # focal loss gamma\n    if g > 0:\n        BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)\n\n    # Losses\n    nt = 0  # number of targets\n    np = len(p)  # number of outputs\n    balance = [4.0, 1.0, 0.4] if np == 3 else [4.0, 1.0, 0.4, 0.1]  # P3-5 or P3-6\n    for i, pi in enumerate(p):  # layer index, layer predictions\n        b, a, gj, gi = indices[i]  # image, anchor, gridy, gridx\n        tobj = torch.zeros_like(pi[..., 0], device=device)  # target obj\n\n        n = b.shape[0]  # number of targets\n        if n:\n            nt += n  # cumulative targets\n            ps = pi[b, a, gj, gi]  # prediction subset corresponding to targets\n\n            # Regression\n            pxy = ps[:, :2].sigmoid() * 2. - 0.5\n            pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]\n            pbox = torch.cat((pxy, pwh), 1).to(device)  # predicted box\n            iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True)  # iou(prediction, target)\n            lbox += (1.0 - iou).mean()  # iou loss\n\n            # Objectness\n            tobj[b, a, gj, gi] = (1.0 - model.gr) + model.gr * iou.detach().clamp(0).type(tobj.dtype)  # iou ratio\n\n            # Classification\n            if model.nc > 1:  # cls loss (only if multiple classes)\n                t = torch.full_like(ps[:, 5:], cn, device=device)  # targets\n                t[range(n), tcls[i]] = cp\n                lcls += BCEcls(ps[:, 5:], t)  # BCE\n\n            # Append targets to text file\n            # with open('targets.txt', 'a') as file:\n            #     [file.write('%11.5g ' * 4 % tuple(x) + '\\n') for x in torch.cat((txy[i], twh[i]), 1)]\n\n        lobj += BCEobj(pi[..., 4], tobj) * balance[i]  # obj loss\n\n    s = 3 / np  # output count scaling\n    lbox *= h['box'] * s\n    lobj *= h['obj'] * s * (1.4 if np == 4 else 1.)\n    lcls *= h['cls'] * s\n    bs = tobj.shape[0]  # batch size\n\n    loss = lbox + lobj + lcls\n    return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()", "meta": {"hexsha": "0a961d5780f2816efa5b4cb424c54a4b676c687e", "size": 17935, "ext": "py", "lang": "Python", "max_stars_repo_path": "helper/general.py", "max_stars_repo_name": "imgcook/pipcook-plugin-pytorch-yolov5-evaluator", "max_stars_repo_head_hexsha": "eafac6d84d2e8b910a7600cc41c9045ca870acf9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-04T12:43:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-01T13:06:12.000Z", "max_issues_repo_path": "helper/general.py", "max_issues_repo_name": "imgcook/pipcook-plugin-pytorch-yolov5-evaluator", "max_issues_repo_head_hexsha": "eafac6d84d2e8b910a7600cc41c9045ca870acf9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "helper/general.py", "max_forks_repo_name": "imgcook/pipcook-plugin-pytorch-yolov5-evaluator", "max_forks_repo_head_hexsha": "eafac6d84d2e8b910a7600cc41c9045ca870acf9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3248847926, "max_line_length": 118, "alphanum_fraction": 0.5603568442, "include": true, "reason": "import numpy", "num_tokens": 5890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.18998546820621814}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May  5 21:08:51 2015\n\n@author: richard\n\nTODO: implemement unit tests with nose\n\"\"\"\n\nimport sys\nimport numpy as np\nimport pandas as pd\nfrom flight import Flight\nfrom decisions import Decisions\nfrom observations import Observations\nfrom random import choice as choose\nfrom roboskeeter.math.math_toolbox import generate_random_unit_vector\n\nclass Simulator:\n    \"\"\"Our simulated mosquito.\n    \"\"\"\n\n    def __init__(self, experiment, agent_kwargs):\n        \"\"\" Load params\n        \"\"\"\n        # dump kwarg dictionary into the agent object\n        for key, value in agent_kwargs.iteritems():\n            setattr(self, key, value)\n\n        self.decisions = Decisions(self.decision_policy, self.stimulus_memory_n_timesteps)\n\n        if experiment.is_simulation:\n            self._simulated_agent_init(experiment)\n\n    def _simulated_agent_init(self, experiment):\n        # defaults\n        self.mass = 2.88e-6  # avg. mass of our colony (kg) =2.88 mg,\n        self.time_max = 15.\n        self.dt = 0.01\n        self.max_bins = int(np.ceil(self.time_max / self.dt))  # N bins\n\n        # from gassian fit to experimental control data\n        self.initial_velocity_mu = 0.18\n        self.initial_velocity_stdev = 0.08\n\n        # useful aliases\n        self.experiment = experiment\n        self.windtunnel = self.experiment.environment.windtunnel\n        self.bounded = self.experiment.experiment_conditions['bounded']\n        self.boundary = self.windtunnel.boundary\n        self.heat = self.experiment.environment.heat\n\n        # useful lists TODO: get rid of?\n        self.kinematics_list = ['position', 'velocity', 'acceleration']  # curvature?\n        self.forces_list = ['total_f', 'random_f', 'stim_f']\n        self.other_list = ['tsi', 'times', 'decision', 'heat_signal', 'in_plume']\n\n        # mk forces\n        self.flight = Flight(self.random_f_strength,\n                             self.stim_f_strength,\n                             self.damping_coeff)\n\n        # turn thresh, in units deg s-1.\n        # From Sharri:\n        # it is the stdev of the broader of two Gaussians that fit the distribution of angular velocity\n\n        # # create repulsion landscape\n        # self._repulsion_funcs = repulsion_landscape3D.landscape(boundary=self.boundary)\n\n    def fly(self, n_trajectories=1):\n        \"\"\" runs _generate_flight n_trajectories times\n        \"\"\"\n        df_list = []\n        traj_i = 0\n        try:\n            if self.verbose:\n                print \"\"\"Starting simulations with {} heat model and {} decision policy.\n                If you run out of patience, press <CTL>-C to stop generating simulations and\n                cut to the chase scene.\"\"\".format(\n                self.heat.heat_model_name, self.decision_policy)\n\n            while traj_i < n_trajectories:\n                # print updates\n                if self.verbose:\n                    sys.stdout.write(\"\\rTrajectory {}/{}\".format(traj_i + 1, n_trajectories))\n                    sys.stdout.flush()\n\n                array_dict = self._generate_flight()\n\n                # if len(array_dict['velocity_x']) < 5:  # hack to catch when optimizer makes trajectories explode\n                #     print \"catching explosion\"\n                #     break\n\n                # add label column to enumerate the trajectories\n                array_len = len(array_dict['tsi'])\n                array_dict['trajectory_num'] = [traj_i] * array_len\n\n                # mk df, add to list of dfs\n                df = pd.DataFrame(array_dict)\n                # df = df.set_index(['trajectory_num'])\n                df_list.append(df)\n\n                traj_i += 1\n\n                if traj_i == n_trajectories:\n                    if self.verbose:\n                        sys.stdout.write(\"\\rSimulations finished. Performing deep magic.\")\n                        sys.stdout.flush()\n\n        except KeyboardInterrupt:\n            print \"\\n Simulations interrupted at iteration {}. Moving along...\".format(traj_i)\n            pass\n\n        observations = Observations()\n        observations.kinematics = pd.concat(df_list)  # concatenate all the data frames at once for performance boost.\n\n        return observations\n\n    def _generate_flight(self):\n        \"\"\"Generate a single trajectory using our model.\n    \n        First put everything into np arrays stored inside of a dictionary\n        \"\"\"\n        dt = self.dt\n        m = self.mass\n        vector_dict = self._initialize_vector_dict()\n\n        # # dynamically create easy-to-read aliases for the contents of vector_dict\n        # for key, value in vector_dict.iteritems():\n        #     exec(key + \" = vector_dict['\" + key + \"']\")\n        # unpack vector dict into nicer aliases\n        in_plume = vector_dict['in_plume']\n        heat_signal = vector_dict['heat_signal']\n        position = vector_dict['position']\n        velocity = vector_dict['velocity']\n        acceleration = vector_dict['acceleration']\n        random_f = vector_dict['random_f']\n        stim_f = vector_dict['stim_f']\n        total_f = vector_dict['total_f']\n        decision = vector_dict['decision']\n\n        position[0] = self._set_init_position()\n        velocity[0] = self._set_init_velocity()\n\n        for tsi in vector_dict['tsi']:\n            in_plume[tsi] = self.heat.check_in_plume_bounds(position[tsi])  # returns False for non-Bool plume\n\n            decision[tsi], heat_signal[tsi] = self.decisions.make_decision(in_plume[tsi], velocity[tsi][1])\n\n            if heat_signal[tsi] == 'X':  # this is an awful hack telling us to look up the gradient\n                heat_signal[tsi] = self.heat.get_nearest_gradient(position[tsi])\n\n            stim_f[tsi], random_f[tsi], total_f[tsi] = self.flight.calc_forces(velocity[tsi], decision[tsi], heat_signal[tsi])\n\n            # calculate current acceleration\n            acceleration[tsi] = total_f[tsi] / m\n\n            # check if time is out, end loop before we solve for future velo, position\n            if tsi == self.max_bins-1: # -1 because of how range() works\n                vector_dict = self._land(tsi, vector_dict)\n                break\n\n            ################################################\n            # Calculate candidate velocity and positions\n            ################################################\n            candidate_velo = velocity[tsi] + acceleration[tsi] * dt\n\n            # make sure velocity doesn't diverge to infinity if system is unstable\n            # this stops the optimizer from crashing\n            candidate_velo = self._velocity_ceiling(candidate_velo)\n\n            candidate_pos = position[tsi] + candidate_velo * dt\n\n            ################################################\n            # test candidates\n            ################################################\n            if self.bounded:\n                candidate_pos, candidate_velo = self._collide_with_wall(candidate_pos, candidate_velo)\n\n            position[tsi + 1] = candidate_pos\n            velocity[tsi + 1] = candidate_velo\n\n        # once flight is finished, make dictionary ready to be loaded into DF\n        vector_dict = self._fix_vector_dict(vector_dict)\n\n        return vector_dict\n\n    def _land(self, tsi, V):\n        ''' trim excess timebins in arrays\n        '''\n        if tsi == 0:  # hack for if we need to chop a trajectory at the very start\n            for k, array in V.iteritems():\n                V[k] = array[:1]\n        else:\n            for k, array in V.iteritems():\n                V[k] = array[:tsi - 1]\n                V[k] = array[:tsi - 1]\n        \n        return V\n\n    def _collide_with_wall(self, candidate_pos, candidate_velo):\n        walls = self.windtunnel.walls\n        xpos, ypos, zpos = candidate_pos\n        xvelo, yvelo, zvelo = candidate_velo\n        teleport_distance = 0.005  # this is arbitrary\n        crash = False\n\n        # print \"test\", candidate_velo\n\n        # x dim\n        if xpos < walls.downwind:  # too far behind\n            crash = True\n            xpos = walls.downwind + teleport_distance  # teleport back inside\n            if self.collision_type == 'elastic':\n                xvelo *= -1.\n            elif self.collision_type == 'part_elastic':\n                xvelo *= -self.restitution_coeff\n            elif self.collision_type == 'crash':\n                xvelo = 0.\n            else:\n                raise ValueError(\"unknown collision type {}\".format(self.collision_type))\n        if xpos > walls.upwind:  # reached far (upwind) wall (end)\n            crash = True\n            xpos = walls.upwind - teleport_distance  # teleport back inside\n            if self.collision_type == 'elastic':\n                xvelo *= -1.\n            elif self.collision_type == 'part_elastic':\n                xvelo *= -self.restitution_coeff\n            elif self.collision_type == 'crash':\n                xvelo = 0.\n\n\n        # y dim\n        if ypos < walls.left:  # too left\n            crash = True\n            ypos = walls.left + teleport_distance\n            if self.collision_type == 'elastic':\n                yvelo *= -1.\n            elif self.collision_type == 'part_elastic':\n                yvelo *= -self.restitution_coeff\n            elif self.collision_type == \"crash\":\n                yvelo = 0.\n\n        if ypos > walls.right:  # too far right\n            crash = True\n            ypos = walls.right - teleport_distance\n            if self.collision_type == 'elastic':\n                yvelo *= -1.\n            elif self.collision_type == 'part_elastic':\n                yvelo *= -self.restitution_coeff\n            elif self.collision_type == 'crash':\n                yvelo = 0.\n\n        # z dim\n        if zpos > walls.ceiling:  # too far above\n            crash = True\n            zpos = walls.ceiling - teleport_distance\n            if self.collision_type == 'elastic':\n                zvelo *= -1.\n            elif self.collision_type == 'part_elastic':\n                zvelo *= -self.restitution_coeff\n            elif self.collision_type == \"crash\":\n                zvelo = 0.\n        if zpos < walls.floor:  # too far below\n            crash = True\n            zpos = walls.floor + teleport_distance\n            if self.collision_type == 'elastic':\n                zvelo *= -1.\n            elif self.collision_type == 'part_elastic':\n                zvelo *= -self.restitution_coeff\n            elif self.collision_type == 'crash':\n                zvelo = 0.\n\n        try:\n            candidate_pos, candidate_velo = np.array([xpos, ypos, zpos]), np.array([xvelo, yvelo, zvelo])\n        except:\n            print \" cand velo\", [xvelo, yvelo, zvelo], \"before\", candidate_velo\n\n\n        return candidate_pos, candidate_velo\n\n    def _initialize_vector_dict(self):\n        \"\"\"\n        initialize np arrays, store in dictionary\n        \"\"\"\n        V = {}\n\n        for name in self.kinematics_list + self.forces_list:\n            V[name] = np.full((self.max_bins, 3), np.nan)\n\n        V['tsi'] = np.arange(self.max_bins)\n        V['times'] = np.linspace(0, self.time_max, self.max_bins)\n        V['in_plume'] = np.zeros(self.max_bins, dtype=bool)\n        V['heat_signal'] = np.array([None] * self.max_bins)\n        V['decision'] = np.array([None] * self.max_bins)\n\n        return V\n\n    def _set_init_velocity(self):\n        initial_velocity_norm = np.random.normal(self.initial_velocity_mu, self.initial_velocity_stdev, 1)\n\n        unit_vector = generate_random_unit_vector()\n        velocity_vec = initial_velocity_norm * unit_vector\n\n        return velocity_vec\n\n    def _set_init_position(self):\n        ''' puts the agent in an initial position, usually within the bounds of the\n        cage\n\n        Options: [the cage] door, or anywhere in the plane at x=.1 meters\n\n        set initial velocity from fitted distribution\n        '''\n\n        # generate random intial velocity condition using normal distribution fitted to experimental data\n        if self.initial_position_selection == 'realistic':\n            \"\"\"these were calculated by taking selecting the initial positions of all observed trajectories in all\n            conditions. Then, for each dimension, I calculated the distance of each initial position to the nearest wall\n            in that dimension (i.e. for each z I calculated the distance to the floor and ceiling and selected\n            the smallest distance. Then, Decisions aand\"\"\"\n            downwind, upwind, left, right, floor, ceiling = self.boundary\n            x_avg_dist_to_wall = 0.268\n            y_avg_dist_to_wall = 0.044\n            z_avg_dist_to_wall = 0.049\n            x = choose([(downwind + x_avg_dist_to_wall), (upwind - x_avg_dist_to_wall)])\n            y = choose([left + y_avg_dist_to_wall, (right - y_avg_dist_to_wall)])\n            z = ceiling - z_avg_dist_to_wall\n            initial_position = np.array([x,y,z])\n        elif self.initial_position_selection == 'downwind_high':\n            initial_position = np.array(\n                [0.05, np.random.uniform(-0.127, 0.127), 0.2373])  # 0.2373 is mode of z pos distribution\n        elif type(self.initial_position_selection) is list:\n            initial_position = np.array(self.initial_position_selection)\n        elif self.initial_position_selection == \"door\":  # start trajectories as they exit the front door\n            initial_position = np.array([0.1909, np.random.uniform(-0.0381, 0.0381), np.random.uniform(0., 0.1016)])\n            # FIXME cage is actually suspending above floor\n        elif self.initial_position_selection == 'downwind_plane':\n            initial_position = np.array([0.1, np.random.uniform(-0.127, 0.127), np.random.uniform(0., 0.254)])\n        else:\n            raise Exception('invalid agent position specified: {}'.format(self.initial_position_selection))\n\n        return initial_position\n\n    def _velocity_ceiling(self, candidate_velo):\n        \"\"\"check if we're seeing enormous velocities, which sometimes happens when running the optimization\n         algoirithm. if so, cap the velocity instead of landing. this allows the optimizer to keep running.\n        \"\"\"\n        for i, velo in enumerate(candidate_velo):\n            if velo > 20:\n                candidate_velo[i] = 20.\n            elif velo < -20:\n                candidate_velo[i] = -20.\n\n        return candidate_velo\n\n    def _fix_vector_dict(self, dct):\n        # prepare dict for loading into pandas (dataframe only accepts 1D vectors)\n        # split xyz dicts into separate x, y, z vectors for dataframe\n\n        fixed_dct = {}\n        for kinematic in self.kinematics_list + self.forces_list:\n            fixed_dct[kinematic + '_x'], fixed_dct[kinematic + '_y'], fixed_dct[kinematic + '_z'] = np.split(\n                dct[kinematic], 3, axis=1)\n\n        # migrate rest of dict\n        for v in self.other_list:\n            fixed_dct[v] = dct[v]\n\n        # fix pandas bug when trying to load (R,1) arrays when it expects (R,) arrays\n        for key, dct in fixed_dct.iteritems():\n            fixed_dct[key] = fixed_dct[key].reshape(len(dct))\n            if fixed_dct[key].size == 0:\n                fixed_dct[key] = np.array([0.])  # hack so that kde calculation doesn't freeze on empty arrays\n\n        return fixed_dct", "meta": {"hexsha": "8dc88ac8614c652f6749f58e54189e67c3ae008a", "size": 15206, "ext": "py", "lang": "Python", "max_stars_repo_path": "roboskeeter/simulator.py", "max_stars_repo_name": "crypdick/RoboSkeeter", "max_stars_repo_head_hexsha": "c905a69c4f7ecf1e1c3e950f36200610a903b6a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "roboskeeter/simulator.py", "max_issues_repo_name": "crypdick/RoboSkeeter", "max_issues_repo_head_hexsha": "c905a69c4f7ecf1e1c3e950f36200610a903b6a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "roboskeeter/simulator.py", "max_forks_repo_name": "crypdick/RoboSkeeter", "max_forks_repo_head_hexsha": "c905a69c4f7ecf1e1c3e950f36200610a903b6a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4414893617, "max_line_length": 126, "alphanum_fraction": 0.5897671972, "include": true, "reason": "import numpy", "num_tokens": 3454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.36296919173767833, "lm_q1q2_score": 0.1899854609924711}}
{"text": "import pdb  # noqa: F401\n\nimport numpy as np\nimport cupy as cp\nimport scipy.signal as scsig\n\nimport os\nfrom os import path\nimport time\nfrom glob import glob\nimport deepdish as dd\n\nfrom typing import Tuple, NamedTuple, TypeVar, List\n\nimport soundfile as sf\n\nimport multiprocessing as mp\nimport logging  # noqa: F401\n\nN_CUDA_DEV = 4\nNDArray = TypeVar('NDArray', np.ndarray, cp.ndarray)\n\n\ndef search_all_files(DIR_WAVFILE: str, ID: str) -> List[str]:\n    result = []\n    for folder, _, _ in os.walk(DIR_WAVFILE):\n        files = glob(path.join(folder, ID))\n        if not files:\n            continue\n        result += files\n\n    return result\n\n\nclass SFTData(NamedTuple):\n    \"\"\"\n    Constant Matrices/Vectors for Spherical Fourier Analysis\n    \"\"\"\n    bEQspec: NDArray\n    Yenc: NDArray\n    Wnv: NDArray\n    Wpv: NDArray\n    Vv: NDArray\n\n    def get_triags(self) -> Tuple:\n        return (self.Wnv, self.Wpv, self.Vv)\n\n\nclass PreProcessor:\n    def __init__(self, RIRs: np.ndarray, Ys: np.ndarray, sftdata: SFTData,\n                 L_WIN_MS=20., RIRs_0: np.ndarray=None):\n        # Bug Fix\n        np.fft.restore_all()\n        # From Parameters\n        self.RIRs = RIRs\n        self.N_LOC, self.N_MIC, self.L_RIR = RIRs.shape\n        self.Ys = Ys\n        self.RIRs_0 = RIRs_0\n        self.sftdata = sftdata\n\n        self.L_WIN_MS = L_WIN_MS\n\n        # Determined during process\n        self.DIR_IV = ''\n        self.all_files = []\n\n        # Common for all wave file\n        self.Fs = 0\n        self.N_wavfile = 0\n        self.N_fft = 0\n        self.N_freq = 0\n        self.L_frame = 0\n        self.L_hop = 0\n        self.win = None\n\n    def process(self, DIR_WAVFILE: str, ID: str, idx_start: int,\n                DIR_IV: str, FORM: str, N_CORES=mp.cpu_count()//4):\n        if not path.exists(DIR_IV):\n            os.makedirs(DIR_IV)\n        self.DIR_IV = DIR_IV\n\n        if self.N_LOC < mp.cpu_count():\n            N_CORES = self.N_LOC\n        n_loc_per_core = int(np.ceil(self.N_LOC//N_CORES))\n\n        max_n_pool = 1\n        while max_n_pool*int(np.ceil(n_loc_per_core*N_CORES/N_CUDA_DEV)) < 30:\n            max_n_pool += 1\n        max_n_pool -= 1\n\n        print(f'Start processing from the {idx_start}-th wave file')\n\n        # Search all wave files\n        # self.all_files = search_all_files(DIR_WAVFILE, ID)\n        self.Fs = 16000\n        data = np.random.normal(size=(16000*10))\n        self.L_frame = int(self.Fs*self.L_WIN_MS//1000)\n        self.N_fft = self.L_frame\n        if self.N_fft % 2 == 0:\n            self.N_freq = self.N_fft//2 + 1\n        else:\n            self.N_freq = self.N_fft//2\n        self.L_hop = self.L_frame//2\n\n        self.win = scsig.hamming(self.L_frame, sym=False)\n\n        pdb.set_trace()\n        # Main Process\n        for i_proc in range(N_CORES):\n            if (i_proc + 1) * n_loc_per_core <= self.N_LOC:\n                range_loc = range(i_proc * n_loc_per_core,\n                                  (i_proc+1) * n_loc_per_core)\n            elif i_proc * n_loc_per_core < self.N_LOC:\n                range_loc = range(i_proc * n_loc_per_core, self.N_LOC)\n            else:\n                break\n            self.save_IV(i_proc % N_CUDA_DEV,\n                         data,\n                         range_loc,\n                         FORM, self.N_wavfile+1)\n\n    def save_IV(self, i_dev: int, data: NDArray, range_loc: iter,\n                FORM: str, *args):\n        \"\"\"\n        Save IV files.\n\n        i_dev: GPU Device No.\n        range_loc: RIR Index Range(S/M Location Index Range)\n        FORM: format of filename\n        args: format string arguments\n\n        return: None\n        \"\"\"\n        # CUDA Ready\n        cp.cuda.Device(i_dev).use()\n        data = cp.array(data)\n        win = cp.array(self.win)\n        Ys = cp.array(self.Ys)\n        sftdata = SFTData(*[cp.array(item) for item in self.sftdata])\n\n        N_frame_free = data.shape[0]//self.L_hop - 1\n        N_frame_room = (data.shape[0]+self.L_RIR-1)//self.L_hop - 1\n\n        for i_loc in range_loc:\n            # RIR Filtering\n            data_0 \\\n                = cp.array(scsig.fftconvolve(cp.asnumpy(data.reshape(1, -1)),\n                                             self.RIRs_0[i_loc]))\n\n            # using 0-th Order RIR\n            iv_0 = cp.zeros((self.N_freq, N_frame_room, 16), dtype=complex)\n            for i_frame in range(N_frame_room):\n                interval = i_frame*self.L_hop + np.arange(self.L_frame)\n                fft = cp.fft.fft(data_0[:, interval]*win, n=self.N_fft)\n                anm = (sftdata.Yenc @ fft) * sftdata.bEQspec\n\n                iv_0[:, i_frame, :] = anm[:, :self.N_freq].T\n\n            # Free-field Intensity Vector Image\n            iv_free = cp.zeros((self.N_freq, N_frame_free, 16), dtype=complex)\n            for i_frame in range(N_frame_free):\n                interval = i_frame*self.L_hop + np.arange(self.L_frame)\n                fft = cp.fft.fft(data[interval]*win, n=self.N_fft)\n                anm = cp.outer(Ys[i_loc].conj(), fft)\n\n                iv_free[:, i_frame, :] = anm[:, :self.N_freq].T\n\n            # Save\n            dict_to_save = {'IV_free': cp.asnumpy(iv_free),\n                            # 'IV_room': cp.asnumpy(iv_room),\n                            'IV_0': cp.asnumpy(iv_0),\n                            # 'data': cp.asnumpy(data),\n                            # 'norm_factor_free': norm_factor_free,\n                            # 'norm_factor_room': norm_factor_room,\n                            }\n            FNAME = FORM % (*args, i_loc)\n            dd.io.save(path.join(self.DIR_IV, FNAME),\n                       dict_to_save,\n                       compression=None)\n\n            print(FORM % (*args, i_loc))\n\n    def __str__(self):\n        return ('Wave Files Processed/Total: '\n                f'{self.N_wavfile}/{len(self.all_files)}\\n'\n                f'Sample Rate: {self.Fs}\\n'\n                f'Number of source location: {self.N_LOC}\\n'\n                )\n\n    def print_save_info(self):\n        \"\"\"\n        Print __str__ and save metadata.\n        \"\"\"\n        print(self)\n\n        metadata = {'N_wavfile': self.N_wavfile,\n                    'Fs': self.Fs,\n                    # 'N_fft': self.N_fft,\n                    'N_freq': self.N_freq,\n                    'L_frame': self.L_frame,\n                    'L_hop': self.L_hop,\n                    'N_LOC': self.N_LOC,\n                    'path_wavfiles': self.all_files,\n                    }\n\n        dd.io.save(path.join(self.DIR_IV, 'metadata.h5'), metadata)\n\n    @staticmethod\n    def seltriag(Ain: NDArray, nrord: int, shft: Tuple[int, int]) -> NDArray:\n        xp = cp.get_array_module(Ain)\n        N_freq = 1 if Ain.ndim == 1 else Ain.shape[1]\n        N = int(np.ceil(np.sqrt(Ain.shape[0]))-1)\n        idx = 0\n        len_new = (N-nrord+1)**2\n\n        Aout = xp.zeros((len_new, N_freq), dtype=Ain.dtype)\n        for ii in range(N-nrord+1):\n            for jj in range(-ii, ii+1):\n                n = shft[0] + ii\n                m = shft[1] + jj\n                idx_from = m + n*(n+1)\n                if -n <= m and m <= n and 0 <= n and n <= N \\\n                        and idx_from < Ain.shape[0]:\n                    Aout[idx] = Ain[idx_from]\n                idx += 1\n        return Aout\n\n    @classmethod\n    def calc_intensity(cls, Asv: NDArray,\n                       Wnv: NDArray, Wpv: NDArray, Vv: NDArray) -> NDArray:\n        \"\"\"\n        Asv(anm) -> IV\n        \"\"\"\n        xp = cp.get_array_module(Asv)\n\n        aug1 = cls.seltriag(Asv, 1, (0, 0))\n        aug2 = cls.seltriag(Wpv, 1, (1, -1))*cls.seltriag(Asv, 1, (1, -1)) \\\n            - cls.seltriag(Wnv, 1, (0, 0))*cls.seltriag(Asv, 1, (-1, -1))\n        aug3 = cls.seltriag(Wpv, 1, (0, 0))*cls.seltriag(Asv, 1, (-1, 1)) \\\n            - cls.seltriag(Wnv, 1, (1, 1))*cls.seltriag(Asv, 1, (1, 1))\n        aug4 = cls.seltriag(Vv, 1, (0, 0))*cls.seltriag(Asv, 1, (-1, 0)) \\\n            + cls.seltriag(Vv, 1, (1, 0))*cls.seltriag(Asv, 1, (1, 0))\n\n        dx = (aug1.conj()*(aug2+aug3)/2).sum(axis=0)\n        dy = (aug1.conj()*(aug2-aug3)/2j).sum(axis=0)\n        dz = (aug1.conj()*aug4).sum(axis=0)\n\n        return 0.5*xp.real(xp.stack((dx, dy, dz), axis=1))\n\n\nif __name__ == '__main__':\n    pass\n", "meta": {"hexsha": "207f3186a394aa5c41bc0599eb6624482a1c8446", "size": 8207, "ext": "py", "lang": "Python", "max_stars_repo_path": "pre_processing_anm_check.py", "max_stars_repo_name": "WXB506/De-reverberation", "max_stars_repo_head_hexsha": "c0913d2a8804aa5176615e61d3b8956456bc51d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pre_processing_anm_check.py", "max_issues_repo_name": "WXB506/De-reverberation", "max_issues_repo_head_hexsha": "c0913d2a8804aa5176615e61d3b8956456bc51d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pre_processing_anm_check.py", "max_forks_repo_name": "WXB506/De-reverberation", "max_forks_repo_head_hexsha": "c0913d2a8804aa5176615e61d3b8956456bc51d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-27T08:03:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-27T08:03:56.000Z", "avg_line_length": 32.4387351779, "max_line_length": 78, "alphanum_fraction": 0.5201657122, "include": true, "reason": "import numpy,import scipy,import cupy", "num_tokens": 2303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.18998546099247107}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport logging\nimport numpy as np\nfrom itertools import combinations\nfrom astropy.coordinates import Angle, SkyOffsetFrame\nfrom astropy.table import Table\nimport astropy.units as u\nfrom gammapy.irf import EDispMap, PSFMap, FoVAlignment\nfrom gammapy.maps import Map, RegionGeom, RegionNDMap\nfrom gammapy.modeling.models import PowerLawSpectralModel\nfrom gammapy.stats import WStatCountsStatistic\nfrom gammapy.utils.coordinates import sky_to_fov\n\n\n__all__ = [\n    \"make_counts_rad_max\",\n    \"make_edisp_kernel_map\",\n    \"make_edisp_map\",\n    \"make_map_background_irf\",\n    \"make_map_exposure_true_energy\",\n    \"make_psf_map\",\n    \"make_theta_squared_table\",\n]\n\nlog = logging.getLogger(__name__)\n\n\ndef make_map_exposure_true_energy(\n    pointing, livetime, aeff, geom, use_region_center=True\n):\n    \"\"\"Compute exposure map.\n\n    This map has a true energy axis, the exposure is not combined\n    with energy dispersion.\n\n    Parameters\n    ----------\n    pointing : `~astropy.coordinates.SkyCoord`\n        Pointing direction\n    livetime : `~astropy.units.Quantity`\n        Livetime\n    aeff : `~gammapy.irf.EffectiveAreaTable2D`\n        Effective area\n    geom : `~gammapy.maps.WcsGeom`\n        Map geometry (must have an energy axis)\n    use_region_center: bool\n        If geom is a RegionGeom, whether to just\n        consider the values at the region center\n        or the instead the average over the whole region\n\n    Returns\n    -------\n    map : `~gammapy.maps.WcsNDMap`\n        Exposure map\n    \"\"\"\n    if not use_region_center:\n        coords, weights = geom.get_wcs_coord_and_weights()\n    else:\n        coords, weights = geom.get_coord(sparse=True), None\n\n    offset = coords.skycoord.separation(pointing)\n    exposure = aeff.evaluate(offset=offset, energy_true=coords[\"energy_true\"])\n\n    data = (exposure * livetime).to(\"m2 s\")\n    meta = {\"livetime\": livetime, \"is_pointlike\": aeff.is_pointlike}\n\n    if not use_region_center:\n        data = np.average(data, axis=1, weights=weights)\n\n    return Map.from_geom(geom=geom, data=data.value, unit=data.unit, meta=meta)\n\n\ndef _map_spectrum_weight(map, spectrum=None):\n    \"\"\"Weight a map with a spectrum.\n\n    This requires map to have an \"energy\" axis.\n    The weights are normalised so that they sum to 1.\n    The mean and unit of the output image is the same as of the input cube.\n\n    At the moment this is used to get a weighted exposure image.\n\n    Parameters\n    ----------\n    map : `~gammapy.maps.Map`\n        Input map with an \"energy\" axis.\n    spectrum : `~gammapy.modeling.models.SpectralModel`\n        Spectral model to compute the weights.\n        Default is power-law with spectral index of 2.\n\n    Returns\n    -------\n    map_weighted : `~gammapy.maps.Map`\n        Weighted image\n    \"\"\"\n    if spectrum is None:\n        spectrum = PowerLawSpectralModel(index=2.0)\n\n    # Compute weights vector\n    energy_edges = map.geom.axes[\"energy_true\"].edges\n    weights = spectrum.integral(\n        energy_min=energy_edges[:-1], energy_max=energy_edges[1:]\n    )\n    weights /= weights.sum()\n    shape = np.ones(len(map.geom.data_shape))\n    shape[0] = -1\n    return map * weights.reshape(shape.astype(int))\n\n\ndef make_map_background_irf(\n    pointing, ontime, bkg, geom, oversampling=None, use_region_center=True\n):\n    \"\"\"Compute background map from background IRFs.\n\n    Parameters\n    ----------\n    pointing : `~gammapy.data.FixedPointingInfo` or `~astropy.coordinates.SkyCoord`\n        Observation pointing\n\n        - If a `~gammapy.data.FixedPointingInfo` is passed, FOV coordinates are properly computed.\n        - If a `~astropy.coordinates.SkyCoord` is passed, FOV frame rotation is not taken into account.\n    ontime : `~astropy.units.Quantity`\n        Observation ontime. i.e. not corrected for deadtime\n        see https://gamma-astro-data-formats.readthedocs.io/en/stable/irfs/full_enclosure/bkg/index.html#notes)\n    bkg : `~gammapy.irf.Background3D`\n        Background rate model\n    geom : `~gammapy.maps.WcsGeom`\n        Reference geometry\n    oversampling: int\n        Oversampling factor in energy, used for the background model evaluation.\n    use_region_center: bool\n        If geom is a RegionGeom, whether to just\n        consider the values at the region center\n        or the instead the sum over the whole region\n\n    Returns\n    -------\n    background : `~gammapy.maps.WcsNDMap`\n        Background predicted counts sky cube in reco energy\n    \"\"\"\n    # TODO:\n    #  This implementation can be improved in two ways:\n    #  1. Create equal time intervals between TSTART and TSTOP and sum up the\n    #  background IRF for each interval. This is instead of multiplying by\n    #  the total ontime. This then handles the rotation of the FoV.\n    #  2. Use the pointing table (does not currently exist in CTA files) to\n    #  obtain the RA DEC and time for each interval. This then considers that\n    #  the pointing might change slightly over the observation duration\n\n    # Get altaz coords for map\n    if oversampling is not None:\n        geom = geom.upsample(factor=oversampling, axis_name=\"energy\")\n\n    coords = {\"energy\": geom.axes[\"energy\"].edges.reshape((-1, 1, 1))}\n\n    if not use_region_center:\n        image_geom = geom.to_wcs_geom().to_image()\n        region_coord, weights = geom.get_wcs_coord_and_weights()\n        idx = image_geom.coord_to_idx(region_coord)\n        sky_coord = region_coord.skycoord\n        d_omega = image_geom.solid_angle().T[idx]\n    else:\n        image_geom = geom.to_image()\n        map_coord = image_geom.get_coord()\n        sky_coord = map_coord.skycoord\n        d_omega = image_geom.solid_angle()\n\n    if bkg.has_offset_axis:\n        coords[\"offset\"] = sky_coord.separation(pointing)\n    else:\n        if bkg.fov_alignment == FoVAlignment.ALTAZ:\n            altaz_coord = sky_coord.transform_to(pointing.altaz_frame)\n\n            # Compute FOV coordinates of map relative to pointing\n            fov_lon, fov_lat = sky_to_fov(\n                altaz_coord.az, altaz_coord.alt, pointing.altaz.az, pointing.altaz.alt\n            )\n        elif bkg.fov_alignment == FoVAlignment.RADEC:\n            # Create OffsetFrame\n            frame = SkyOffsetFrame(origin=pointing.radec)\n            pseudo_fov_coord = sky_coord.transform_to(frame)\n            fov_lon = pseudo_fov_coord.lon\n            fov_lat = pseudo_fov_coord.lat\n        else:\n            raise ValueError(\n                f\"Unsupported background coordinate system: {bkg.fov_alignment!r}\"\n            )\n\n        coords[\"fov_lon\"] = fov_lon\n        coords[\"fov_lat\"] = fov_lat\n\n    bkg_de = bkg.integrate_log_log(**coords, axis_name=\"energy\")\n    data = (bkg_de * d_omega * ontime).to_value(\"\")\n\n    if not use_region_center:\n        data = np.sum(weights * data, axis=2)\n\n    bkg_map = Map.from_geom(geom, data=data)\n\n    if oversampling is not None:\n        bkg_map = bkg_map.downsample(factor=oversampling, axis_name=\"energy\")\n\n    return bkg_map\n\n\ndef make_psf_map(psf, pointing, geom, exposure_map=None):\n    \"\"\"Make a psf map for a single observation\n\n    Expected axes : rad and true energy in this specific order\n    The name of the rad MapAxis is expected to be 'rad'\n\n    Parameters\n    ----------\n    psf : `~gammapy.irf.PSF3D`\n        the PSF IRF\n    pointing : `~astropy.coordinates.SkyCoord`\n        the pointing direction\n    geom : `~gammapy.maps.Geom`\n        the map geom to be used. It provides the target geometry.\n        rad and true energy axes should be given in this specific order.\n    exposure_map : `~gammapy.maps.Map`, optional\n        the associated exposure map.\n        default is None\n\n    Returns\n    -------\n    psfmap : `~gammapy.irf.PSFMap`\n        the resulting PSF map\n    \"\"\"\n    coords = geom.get_coord(sparse=True)\n\n    # Compute separations with pointing position\n    offset = coords.skycoord.separation(pointing)\n\n    # Compute PSF values\n    data = psf.evaluate(\n        energy_true=coords[\"energy_true\"],\n        offset=offset,\n        rad=coords[\"rad\"],\n    )\n\n    # Create Map and fill relevant entries\n    psf_map = Map.from_geom(geom, data=data.value, unit=data.unit)\n    psf_map.normalize(axis_name=\"rad\")\n    return PSFMap(psf_map, exposure_map)\n\n\ndef make_edisp_map(edisp, pointing, geom, exposure_map=None, use_region_center=True):\n    \"\"\"Make a edisp map for a single observation\n\n    Expected axes : migra and true energy in this specific order\n    The name of the migra MapAxis is expected to be 'migra'\n\n    Parameters\n    ----------\n    edisp : `~gammapy.irf.EnergyDispersion2D`\n        the 2D Energy Dispersion IRF\n    pointing : `~astropy.coordinates.SkyCoord`\n        the pointing direction\n    geom : `~gammapy.maps.Geom`\n        the map geom to be used. It provides the target geometry.\n        migra and true energy axes should be given in this specific order.\n    exposure_map : `~gammapy.maps.Map`, optional\n        the associated exposure map.\n        default is None\n    use_region_center: Bool\n        If geom is a RegionGeom, whether to just\n        consider the values at the region center\n        or the instead the average over the whole region\n\n    Returns\n    -------\n    edispmap : `~gammapy.irf.EDispMap`\n        the resulting EDisp map\n    \"\"\"\n    # Compute separations with pointing position\n    if not use_region_center:\n        coords, weights = geom.get_wcs_coord_and_weights()\n    else:\n        coords, weights = geom.get_coord(sparse=True), None\n\n    offset = coords.skycoord.separation(pointing)\n\n    # Compute EDisp values\n    data = edisp.evaluate(\n        offset=offset,\n        energy_true=coords[\"energy_true\"],\n        migra=coords[\"migra\"],\n    )\n\n    if not use_region_center:\n        data = np.average(data, axis=2, weights=weights)\n\n    # Create Map and fill relevant entries\n    edisp_map = Map.from_geom(geom, data=data.to_value(\"\"), unit=\"\")\n    edisp_map.normalize(axis_name=\"migra\")\n    return EDispMap(edisp_map, exposure_map)\n\n\ndef make_edisp_kernel_map(\n    edisp, pointing, geom, exposure_map=None, use_region_center=True\n):\n    \"\"\"Make a edisp kernel map for a single observation\n\n    Expected axes : (reco) energy and true energy in this specific order\n    The name of the reco energy MapAxis is expected to be 'energy'.\n    The name of the true energy MapAxis is expected to be 'energy_true'.\n\n    Parameters\n    ----------\n    edisp : `~gammapy.irf.EnergyDispersion2D`\n        the 2D Energy Dispersion IRF\n    pointing : `~astropy.coordinates.SkyCoord`\n        the pointing direction\n    geom : `~gammapy.maps.Geom`\n        the map geom to be used. It provides the target geometry.\n        energy and true energy axes should be given in this specific order.\n    exposure_map : `~gammapy.maps.Map`, optional\n        the associated exposure map.\n        default is None\n    use_region_center: Bool\n        If geom is a RegionGeom, whether to just\n        consider the values at the region center\n        or the instead the average over the whole region\n\n    Returns\n    -------\n    edispmap : `~gammapy.irf.EDispKernelMap`\n        the resulting EDispKernel map\n    \"\"\"\n    # Use EnergyDispersion2D migra axis.\n    migra_axis = edisp.axes[\"migra\"]\n\n    # Create temporary EDispMap Geom\n    new_geom = geom.to_image().to_cube([migra_axis, geom.axes[\"energy_true\"]])\n\n    edisp_map = make_edisp_map(\n        edisp, pointing, new_geom, exposure_map, use_region_center\n    )\n\n    return edisp_map.to_edisp_kernel_map(geom.axes[\"energy\"])\n\n\ndef make_theta_squared_table(\n    observations, theta_squared_axis, position, position_off=None\n):\n    \"\"\"Make theta squared distribution in the same FoV for a list of `Observation`\n    objects.\n\n    The ON theta2 profile is computed from a given distribution, on_position.\n    By default, the OFF theta2 profile is extracted from a mirror position\n    radially symmetric in the FOV to pos_on.\n\n    The ON and OFF regions are assumed to be of the same size, so the normalisation\n    factor between both region alpha = 1.\n\n    Parameters\n    ----------\n    observations: `~gammapy.data.Observations`\n        List of observations\n    theta_squared_axis : `~gammapy.maps.geom.MapAxis`\n        Axis of edges of the theta2 bin used to compute the distribution\n    position : `~astropy.coordinates.SkyCoord`\n        Position from which the on theta^2 distribution is computed\n    position_off : `astropy.coordinates.SkyCoord`\n        Position from which the OFF theta^2 distribution is computed.\n        Default: reflected position w.r.t. to the pointing position\n\n    Returns\n    -------\n    table : `~astropy.table.Table`\n        Table containing the on counts, the off counts, acceptance, off acceptance and alpha\n        for each theta squared bin.\n    \"\"\"\n    if not theta_squared_axis.edges.unit.is_equivalent(\"deg2\"):\n        raise ValueError(\"The theta2 axis should be equivalent to deg2\")\n\n    table = Table()\n\n    table[\"theta2_min\"] = theta_squared_axis.edges[:-1]\n    table[\"theta2_max\"] = theta_squared_axis.edges[1:]\n    table[\"counts\"] = 0\n    table[\"counts_off\"] = 0\n    table[\"acceptance\"] = 0.0\n    table[\"acceptance_off\"] = 0.0\n\n    alpha_tot = np.zeros(len(table))\n    livetime_tot = 0\n\n    create_off = position_off is None\n    for observation in observations:\n        separation = position.separation(observation.events.radec)\n        counts, _ = np.histogram(separation ** 2, theta_squared_axis.edges)\n        table[\"counts\"] += counts\n\n        if create_off:\n            # Estimate the position of the mirror position\n            pos_angle = observation.pointing_radec.position_angle(position)\n            sep_angle = observation.pointing_radec.separation(position)\n            position_off = observation.pointing_radec.directional_offset_by(\n                pos_angle + Angle(np.pi, \"rad\"), sep_angle\n            )\n\n        # Angular distance of the events from the mirror position\n        separation_off = position_off.separation(observation.events.radec)\n\n        # Extract the ON and OFF theta2 distribution from the two positions.\n        counts_off, _ = np.histogram(separation_off ** 2, theta_squared_axis.edges)\n        table[\"counts_off\"] += counts_off\n\n        # Normalisation between ON and OFF is one\n        acceptance = np.ones(theta_squared_axis.nbin)\n        acceptance_off = np.ones(theta_squared_axis.nbin)\n\n        table[\"acceptance\"] += acceptance\n        table[\"acceptance_off\"] += acceptance_off\n        alpha = acceptance / acceptance_off\n        alpha_tot += alpha * observation.observation_live_time_duration.to_value(\"s\")\n        livetime_tot += observation.observation_live_time_duration.to_value(\"s\")\n\n    alpha_tot /= livetime_tot\n    table[\"alpha\"] = alpha_tot\n\n    stat = WStatCountsStatistic(table[\"counts\"], table[\"counts_off\"], table[\"alpha\"])\n    table[\"excess\"] = stat.n_sig\n    table[\"sqrt_ts\"] = stat.sqrt_ts\n    table[\"excess_errn\"] = stat.compute_errn()\n    table[\"excess_errp\"] = stat.compute_errp()\n\n    table.meta[\"ON_RA\"] = position.icrs.ra\n    table.meta[\"ON_DEC\"] = position.icrs.dec\n    return table\n\n\ndef make_counts_rad_max(geom, rad_max, events):\n    \"\"\"Extract the counts using for the ON region size the values in the\n    `RAD_MAX_2D` table.\n\n    Parameters\n    ----------\n    geom : `~gammapy.maps.RegionGeom`\n        reference map geom\n    rad_max : `~gammapy.irf.RadMax2D`\n        the RAD_MAX_2D table IRF\n    events : `~gammapy.data.EventList`\n        event list to be used to compute the ON counts\n\n    Returns\n    -------\n    counts : `~gammapy.maps.RegionNDMap`\n        Counts vs estimated energy extracted from the ON region.\n    \"\"\"\n    selected_events = events.select_rad_max(\n        rad_max=rad_max, position=geom.region.center\n    )\n\n    counts = Map.from_geom(geom=geom)\n    counts.fill_events(selected_events)\n    return counts\n\n\ndef are_regions_overlapping_rad_max(regions, rad_max, offset, e_min, e_max):\n    \"\"\"\n    Calculate pair-wise separations between all regions and compare with rad_max\n    to find overlaps.\n    \"\"\"\n    separations = u.Quantity([\n        a.center.separation(b.center)\n        for a, b in combinations(regions, 2)\n    ])\n\n    rad_max_at_offset = rad_max.evaluate(offset=offset)\n    # do not check bins outside of energy range\n    edges_min = rad_max.axes['energy'].edges_min\n    edges_max = rad_max.axes['energy'].edges_max\n    # to be sure all possible values are included, we check\n    # for the *upper* energy bin to be larger than e_min and the *lower* edge\n    # to be larger than e_max\n    mask = (edges_max >= e_min) & (edges_min <= e_max)\n    rad_max_at_offset = rad_max_at_offset[mask]\n\n    return np.any(separations[np.newaxis, :] < (2 * rad_max_at_offset))\n\n\ndef make_counts_off_rad_max(\n    on_geom,\n    rad_max,\n    events,\n    region_finder,\n    exclusion_mask=None,\n):\n    \"\"\"Extract the OFF counts and the ON / OFF acceptance considering for the\n    sizes of the ON and OFF regions the values in the `RAD_MAX_2D` table.\n    Per each estimated energy bin a `ReflectedRegionsFinder` is defined to\n    search for the OFF regions.\n\n    Parameters\n    ----------\n    geom: `~gammapy.maps.RegionGeom`\n        reference map geom for the on region\n    rad_max: `~gammapy.irf.RadMax2D`\n        the RAD_MAX_2D table IRF\n    events: `~gammapy.data.EventList`\n        event list to be used to compute the OFF counts\n    region_finder: `~gammapy.makers.background.reflected.RegionFinder`\n\n    Returns\n    -------\n    counts_off : `~gammapy.maps.RegionNDMap`\n        OFF Counts vs estimated energy extracted from the ON region.\n    acceptance_off : `~gammapy.maps.RegionNDMap`\n        ratio of the acceptances of the OFF to ON regions.\n    \"\"\"\n\n    off_regions, wcs = region_finder.run(\n        center=events.pointing_radec,\n        region=on_geom.region,\n        exclusion_mask=exclusion_mask,\n    )\n\n    if len(off_regions) == 0:\n        log.warning(\"RegionsFinder returned no regions\")\n        # counts_off=None, acceptance_off=0\n        return None, RegionNDMap.from_geom(on_geom, data=0)\n\n\n    # check for overlap\n    energy_axis = on_geom.axes[\"energy\"]\n    offset = on_geom.region.center.separation(events.pointing_radec)\n    e_min, e_max = energy_axis.edges[[0, -1]]\n    regions = [on_geom.region] + off_regions\n    if are_regions_overlapping_rad_max(regions, rad_max, offset, e_min, e_max):\n        log.warning(\"Found overlapping on/off regions, choose less off regions\")\n        # counts_off=None, acceptance_off=0\n        return None, RegionNDMap.from_geom(on_geom, data=0)\n\n    off_region_geom = RegionGeom.from_regions(\n        regions=off_regions,\n        axes=[energy_axis],\n        wcs=wcs,\n    )\n\n    counts_off = RegionNDMap.from_geom(geom=off_region_geom)\n    acceptance_off = RegionNDMap.from_geom(\n        geom=off_region_geom,\n        data=np.full(energy_axis.nbin, len(off_regions))\n    )\n\n    for off_region in off_regions:\n        selected_events = events.select_rad_max(\n            rad_max=rad_max, position=off_region.center\n        )\n        counts_off.fill_events(selected_events)\n\n    return counts_off, acceptance_off\n", "meta": {"hexsha": "166847246fa1f3023538d3875d37783a8af77b9a", "size": 19053, "ext": "py", "lang": "Python", "max_stars_repo_path": "gammapy/makers/utils.py", "max_stars_repo_name": "isu-veritas/gammapy", "max_stars_repo_head_hexsha": "715b041d7d3925bd51109dc9534634263a2f2d12", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gammapy/makers/utils.py", "max_issues_repo_name": "isu-veritas/gammapy", "max_issues_repo_head_hexsha": "715b041d7d3925bd51109dc9534634263a2f2d12", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gammapy/makers/utils.py", "max_forks_repo_name": "isu-veritas/gammapy", "max_forks_repo_head_hexsha": "715b041d7d3925bd51109dc9534634263a2f2d12", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3297297297, "max_line_length": 111, "alphanum_fraction": 0.6792631082, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 4622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.331119752830196, "lm_q1q2_score": 0.18995625247969547}}
{"text": "#!/usr/bin/env python\n\nfrom __future__ import division\nimport numpy as np\nimport scipy.spatial.distance as ssd\nimport h5py, sys\n\nimport pycuda.driver as drv\nimport pycuda.autoinit\nfrom pycuda import gpuarray\nfrom scikits.cuda import linalg\nlinalg.init()\n\nfrom tps import tps_kernel_matrix, tps_eval\nfrom transformations import unit_boxify\nfrom culinalg_exts import dot_batch_nocheck, get_gpu_ptrs, m_dot_batch\nfrom precompute import downsample_cloud, batch_get_sol_params\nfrom cuda_funcs import init_prob_nm, norm_prob_nm, get_targ_pts, check_cuda_err, \\\n    fill_mat, reset_cuda, sq_diffs\nfrom registration import registration_cost as cpu_registration_cost\nfrom defaults import N_ITER_CHEAP, EM_ITER_CHEAP, DEFAULT_LAMBDA, MAX_CLD_SIZE, \\\n    DATA_DIM, DS_SIZE, N_STREAMS, DEFAULT_NORM_ITERS, BEND_COEF_DIGITS\n\nimport IPython as ipy\nfrom pdb import pm, set_trace\nimport time\n\n\nclass Globals:\n    sync = False\n    streams = []\n    for i in range(N_STREAMS):\n        streams.append(drv.Stream())\n\ndef get_stream(i):\n    return Globals.streams[i % N_STREAMS]\n\ndef sync(override = False):\n    if Globals.sync or override:\n        check_cuda_err()\n\ndef loglinspace(a,b,n):\n    \"n numbers between a to b (inclusive) with constant ratio between consecutive numbers\"\n    return np.exp(np.linspace(np.log(a),np.log(b),n))    \n\ndef gpu_pad(x, shape, dtype=np.float32):\n    (m, n) = x.shape\n    if m > shape[0] or n > shape[1]:\n        raise ValueError(\"Cannot Pad Beyond Normal Dimension\")\n    x_new = np.zeros(shape, dtype=dtype)    \n    x_new[:m, :n] = x\n    return gpuarray.to_gpu(x_new)\n\nclass GPUContext(object):\n    \"\"\"\n    Class to contain GPU arrays\n    \"\"\"\n    def __init__(self, bend_coefs = None):\n        if bend_coefs is None:\n            lambda_init, lambda_final = DEFAULT_LAMBDA\n            bend_coefs = np.around(loglinspace(lambda_init, lambda_final, N_ITER_CHEAP), \n                                    BEND_COEF_DIGITS)\n        self.bend_coefs = bend_coefs\n        self.ptrs_valid = False\n        self.N = 0\n\n        self.tps_params     = []\n        self.tps_param_ptrs = None\n        self.trans_d        = []\n        self.trans_d_ptrs   = None\n        self.lin_dd         = []\n        self.lin_dd_ptrs    = None\n        self.w_nd           = []\n        self.w_nd_ptrs      = None\n        self.ident_mats     = [gpuarray.to_gpu(np.eye(MAX_CLD_SIZE, dtype=np.float32))]\n        self.ident_ptrs      = None\n        \n        \"\"\"\n        TPS PARAM FORMAT\n        [      np.zeros(DATA_DIM)      ]   [  trans_d  ]   [1 x d]\n        [       np.eye(DATA_DIM)       ] = [  lin_dd   ] = [d x d]\n        [np.zeros((np.zeros, DATA_DIM))]   [   w_nd    ]   [n x d]\n        \"\"\"\n        self.default_tps_params = gpuarray.zeros((DATA_DIM + 1 + MAX_CLD_SIZE, DATA_DIM), np.float32)\n        self.default_tps_params[1:DATA_DIM+1, :].set(np.eye(DATA_DIM, dtype=np.float32))\n\n        self.proj_mats       = dict([(b, []) for b in bend_coefs])\n        self.proj_mat_ptrs   = dict([(b, None) for b in bend_coefs])\n        self.offset_mats     = dict([(b, []) for b in bend_coefs])\n        self.offset_mat_ptrs = dict([(b, None) for b in bend_coefs])\n\n        self.pts             = []\n        self.pt_ptrs         = None\n        self.pt_t_pt         = []\n        self.pt_t_pt_ptrs    = None\n        self.kernels         = []\n        self.kernel_ptrs     = None\n        self.pts_w           = []\n        self.pt_w_ptrs       = None\n        self.pts_t           = []\n        self.pts_t_ptrs      = None\n        self.dims            = []\n        self.dims_gpu        = None\n\n        self.warp_err         = None\n        self.bend_res         = []\n        self_bend_res_ptrs    = None\n\n        self.corr_cm          = []\n        self.corr_cm_ptrs     = None\n        self.corr_rm          = []\n        self.corr_rm_ptrs     = None\n        self.r_coefs         = []\n        self.r_coef_ptrs     = None\n        self.c_coefs_rn      = []\n        self.c_coef_rn_ptrs  = None\n        self.c_coefs_cn      = []\n        self.c_coef_cn_ptrs  = None\n        self.seg_names        = []\n\n    def reset_tps_params(self):\n        \"\"\"\n        sets the tps params to be identity\n        \"\"\"\n        for p in self.tps_params:\n            drv.memcpy_dtod_async(p.gpudata, self.default_tps_params.gpudata, p.nbytes)            \n    def set_tps_params(self, vals):\n        for d, s in zip(self.tps_params, vals):\n            drv.memcpy_dtod_async(d.gpudata, s.gpudata, d.nbytes)            \n\n    def reset_warp_err(self):\n        self.warp_err.fill(0)\n\n    def check_cld(self, cloud_xyz):\n        if cloud_xyz.dtype != np.float32:\n            raise TypeError(\"only single precision operations supported\")\n        if cloud_xyz.shape[0] > MAX_CLD_SIZE:\n            raise ValueError(\"cloud size exceeds {}\".format(MAX_CLD_SIZE))\n        if cloud_xyz.shape[1] != DATA_DIM:\n            raise ValueError(\"point cloud must have cumn dimension {}\".format(DATA_DIM))\n    # @profile\n    def get_sol_params(self, cld):\n        self.check_cld(cld)\n        K = tps_kernel_matrix(cld)\n        proj_mats   = {}\n        offset_mats = {}\n        (proj_mats_arr, _), (offset_mats_arr, _) = batch_get_sol_params(cld, K, self.bend_coefs)\n        for i, b in enumerate(self.bend_coefs):\n            proj_mats[b]   = proj_mats_arr[i]\n            offset_mats[b] = offset_mats_arr[i]\n        return proj_mats, offset_mats, K\n\n    def add_cld(self, name, proj_mats, offset_mats, cloud_xyz, kernel, update_ptrs = False):\n        \"\"\"\n        adds a new cloud to our context for batch processing\n        \"\"\"\n        self.check_cld(cloud_xyz)\n        self.ptrs_valid = False\n        self.N += 1\n        self.seg_names.append(name)\n        self.tps_params.append(self.default_tps_params.copy())\n        self.trans_d.append(self.tps_params[-1][0, :])\n        self.lin_dd.append(self.tps_params[-1][1:DATA_DIM+1, :])\n        self.w_nd.append(self.tps_params[-1][DATA_DIM + 1:, :])\n        n = cloud_xyz.shape[0]\n        \n        for b in self.bend_coefs:\n            proj_mat   = proj_mats[b]\n            offset_mat = offset_mats[b]\n            self.proj_mats[b].append(gpu_pad(proj_mat, (MAX_CLD_SIZE + DATA_DIM + 1, MAX_CLD_SIZE)))\n\n            if offset_mat.shape != (n + DATA_DIM + 1, DATA_DIM):\n                raise ValueError(\"Offset Matrix has incorrect dimension\")\n            self.offset_mats[b].append(gpu_pad(offset_mat, (MAX_CLD_SIZE + DATA_DIM + 1, DATA_DIM)))\n\n\n        if n > MAX_CLD_SIZE or cloud_xyz.shape[1] != DATA_DIM:\n            raise ValueError(\"cloud_xyz has incorrect dimension\")\n        self.pts.append(gpu_pad(cloud_xyz, (MAX_CLD_SIZE, DATA_DIM)))\n        self.pt_t_pt.append(gpu_pad(cloud_xyz.T.dot(cloud_xyz), (MAX_CLD_SIZE, MAX_CLD_SIZE)))\n        if kernel.shape != (n, n):\n            raise ValueError(\"dimension mismatch b/t kernel and cloud\")\n        self.kernels.append(gpu_pad(kernel, (MAX_CLD_SIZE, MAX_CLD_SIZE)))\n        self.dims.append(n)\n\n        self.pts_w.append(gpuarray.zeros_like(self.pts[-1]))\n        self.pts_t.append(gpuarray.zeros_like(self.pts[-1]))\n        self.corr_cm.append(gpuarray.zeros((MAX_CLD_SIZE, MAX_CLD_SIZE), np.float32))\n        self.corr_rm.append(gpuarray.zeros((MAX_CLD_SIZE, MAX_CLD_SIZE), np.float32))\n        self.r_coefs.append(gpuarray.zeros((MAX_CLD_SIZE, 1), np.float32))\n        self.c_coefs_rn.append(gpuarray.zeros((MAX_CLD_SIZE, 1), np.float32))\n        self.c_coefs_cn.append(gpuarray.zeros((MAX_CLD_SIZE, 1), np.float32))\n\n        if update_ptrs:\n            self.update_ptrs()\n\n    def update_ptrs(self):\n        self.tps_param_ptrs = get_gpu_ptrs(self.tps_params)\n        self.trans_d_ptrs   = get_gpu_ptrs(self.trans_d)\n        self.lin_dd_ptrs    = get_gpu_ptrs(self.lin_dd)\n        self.w_nd_ptrs      = get_gpu_ptrs(self.w_nd)\n        \n        for b in self.bend_coefs:\n            self.proj_mat_ptrs[b]   = get_gpu_ptrs(self.proj_mats[b])\n            self.offset_mat_ptrs[b] = get_gpu_ptrs(self.offset_mats[b])\n\n        self.pt_ptrs         = get_gpu_ptrs(self.pts)\n        self.pt_t_pt_ptrs    = get_gpu_ptrs(self.pt_t_pt)\n        self.kernel_ptrs     = get_gpu_ptrs(self.kernels)\n        self.ident_ptrs      = get_gpu_ptrs([self.ident_mats[0] for _ in range(self.N)])\n        self.pt_w_ptrs       = get_gpu_ptrs(self.pts_w)\n        self.pt_t_ptrs       = get_gpu_ptrs(self.pts_t)\n        self.corr_cm_ptrs    = get_gpu_ptrs(self.corr_cm)\n        self.corr_rm_ptrs    = get_gpu_ptrs(self.corr_rm)\n        self.r_coef_ptrs    = get_gpu_ptrs(self.r_coefs)\n        self.c_coef_rn_ptrs = get_gpu_ptrs(self.c_coefs_rn)\n        self.c_coef_cn_ptrs = get_gpu_ptrs(self.c_coefs_cn)\n        ## temporary space used for bend/warp cost computations\n        self.warp_err        = gpuarray.zeros((self.N, MAX_CLD_SIZE), np.float32)\n        self.bend_res_mat    = gpuarray.zeros((DATA_DIM * self.N, DATA_DIM), np.float32)\n        self.bend_res        =[self.bend_res_mat[i*DATA_DIM:(i+1)*DATA_DIM] for i in range(self.N)]\n        self.bend_res_ptrs   = get_gpu_ptrs(self.bend_res)\n        \n        self.dims_gpu = gpuarray.to_gpu(np.array(self.dims, dtype=np.int32))\n        self.ptrs_valid = True\n\n    def read_h5(self, fname):\n        f = h5py.File(fname, 'r')\n        for seg_name, seg_info in f.iteritems():\n            if 'inv' not in seg_info:\n                raise KeyError(\"H5 File does not have precomputed values\")\n            seg_info = seg_info['inv']\n\n            proj_mats   = {}\n            offset_mats = {}\n            for b in self.bend_coefs:\n                k = str(b)\n                if k not in seg_info:\n                    raise KeyError(\"H5 File {} bend coeficient {}\".format(seg_name, k))\n                proj_mats[b] = seg_info[k]['proj_mat'][:]\n                offset_mats[b] = seg_info[k]['offset_mat'][:]\n\n            ds_key    = 'DS_SIZE_{}'.format(DS_SIZE)\n            cloud_xyz = seg_info[ds_key]['scaled_cloud_xyz'][:]\n            kernel    = seg_info[ds_key]['scaled_K_nn'][:]\n            self.add_cld(seg_name, proj_mats, offset_mats, cloud_xyz, kernel)\n        f.close()\n        self.update_ptrs()\n\n    # @profile\n    def setup_tgt_ctx(self, cloud_xyz):\n        \"\"\"\n        returns a GPUContext where all the clouds are cloud_xyz\n        and matched in length with this contex\n\n        assumes cloud_xyz is already downsampled and scaled\n        \"\"\"        \n        tgt_ctx = TgtContext(self)\n        tgt_ctx.set_cld(cloud_xyz)\n        return tgt_ctx\n\n    # @profile\n    def transform_points(self):\n        \"\"\"\n        computes the warp of self.pts under the current tps params\n        \"\"\"\n        fill_mat(self.pt_w_ptrs, self.trans_d_ptrs, self.dims_gpu, self.N)\n        dot_batch_nocheck(self.pts,         self.lin_dd,      self.pts_w,\n                          self.pt_ptrs,     self.lin_dd_ptrs, self.pt_w_ptrs) \n        dot_batch_nocheck(self.kernels,     self.w_nd,        self.pts_w,\n                          self.kernel_ptrs, self.w_nd_ptrs,   self.pt_w_ptrs) \n        sync()\n    \n    # @profile\n    def get_target_points(self, other, outlierprior=1e-1, outlierfrac=1e-2, outliercutoff=1e-2, \n                          T = 5e-3, norm_iters = DEFAULT_NORM_ITERS):\n        \"\"\"\n        computes the target points for self and other\n        using the current warped points for both                \n        \"\"\"\n        init_prob_nm(self.pt_ptrs, other.pt_ptrs, \n                     self.pt_w_ptrs, other.pt_w_ptrs, \n                     self.dims_gpu, other.dims_gpu,\n                     self.N, outlierprior, outlierfrac, T, \n                     self.corr_cm_ptrs, self.corr_rm_ptrs)\n        sync()\n        norm_prob_nm(self.corr_cm_ptrs, self.corr_rm_ptrs, \n                     self.dims_gpu, other.dims_gpu, self.N, outlierfrac, norm_iters,\n                     self.r_coef_ptrs, self.c_coef_rn_ptrs, self.c_coef_cn_ptrs)        \n        sync()\n        get_targ_pts(self.pt_ptrs, other.pt_ptrs,\n                     self.pt_w_ptrs, other.pt_w_ptrs,\n                     self.corr_cm_ptrs, self.corr_rm_ptrs,\n                     self.r_coef_ptrs, self.c_coef_rn_ptrs, self.c_coef_cn_ptrs,\n                     self.dims_gpu, other.dims_gpu, \n                     outliercutoff, self.N,\n                     self.pt_t_ptrs, other.pt_t_ptrs)\n        sync()\n\n    # @profile\n    def update_transform(self, b):\n        \"\"\"\n        computes the TPS associated with the current target pts\n        \"\"\"\n        self.set_tps_params(self.offset_mats[b])\n        dot_batch_nocheck(self.proj_mats[b],     self.pts_t,     self.tps_params,\n                          self.proj_mat_ptrs[b], self.pt_t_ptrs, self.tps_param_ptrs)\n        sync()\n    # @profile\n    def mapping_cost(self, other, bend_coef=DEFAULT_LAMBDA[1], outlierprior=1e-1, outlierfrac=1e-2, \n                       outliercutoff=1e-2,  T = 5e-3, norm_iters = DEFAULT_NORM_ITERS):\n        \"\"\"\n        computes the error in the current mapping\n        assumes that the target points have already been filled\n        \"\"\"\n        self.transform_points()\n        other.transform_points()\n        sums = []\n        sq_diffs(self.pt_w_ptrs, self.pt_t_ptrs, self.warp_err, self.N, True)\n        sq_diffs(other.pt_w_ptrs, other.pt_t_ptrs, self.warp_err, self.N, False)\n        warp_err = self.warp_err.get()\n        return np.sum(warp_err, axis=1)\n    # @profile\n    def bending_cost(self, b=DEFAULT_LAMBDA[1]):\n        ## b * w_nd' * K * w_nd\n        ## use pts_w as temporary storage\n        dot_batch_nocheck(self.kernels,     self.w_nd,      self.pts_w,\n                          self.kernel_ptrs, self.w_nd_ptrs, self.pt_w_ptrs,\n                          b = 0)\n\n        dot_batch_nocheck(self.pts_w,     self.w_nd,      self.bend_res,\n                          self.pt_w_ptrs, self.w_nd_ptrs, self.bend_res_ptrs,\n                          transa='T', b = 0)\n        bend_res = self.bend_res_mat.get()        \n        return b * np.array([np.trace(bend_res[i*DATA_DIM:(i+1)*DATA_DIM]) for i in range(self.N)])\n    # @profile\n    def bidir_tps_cost(self, other, bend_coef=1, outlierprior=1e-1, outlierfrac=1e-2, \n                       outliercutoff=1e-2,  T = 5e-3, norm_iters = DEFAULT_NORM_ITERS):\n        self.reset_warp_err()\n        mapping_err  = self.mapping_cost(other, outlierprior, outlierfrac, outliercutoff, T, norm_iters)\n        bending_cost = self.bending_cost(bend_coef)\n        bending_cost += other.bending_cost(bend_coef)\n        return mapping_err + bending_cost\n\n    \"\"\"\n    testing for custom kernels\n    \"\"\"\n\n    def test_mapping_cost(self, other, bend_coef=DEFAULT_LAMBDA[1], outlierprior=1e-1, outlierfrac=1e-2, \n                       outliercutoff=1e-2,  T = 5e-3, norm_iters = DEFAULT_NORM_ITERS):\n        mapping_err = self.mapping_cost(other, outlierprior, outlierfrac, outliercutoff, T, norm_iters)\n        for i in range(self.N):\n            ## compute error for 0 on cpu\n            s_gpu = mapping_err[i]\n            s_cpu = np.float32(0)\n            xt = self.pts_t[i].get()\n            xw = self.pts_w[i].get()\n            \n            yt = other.pts_t[i].get()\n            yw = other.pts_w[i].get()\n            \n            ##use the trace b/c then numpy will use float32s all the way\n            s_cpu += np.trace(xt.T.dot(xt) + xw.T.dot(xw) - 2 * xw.T.dot(xt))\n            s_cpu += np.trace(yt.T.dot(yt) + yw.T.dot(yw) - 2 * yw.T.dot(yt))\n            \n            if not np.isclose(s_cpu, s_gpu, atol=1e-4):\n                ## high err tolerance is b/c of difference in cpu and gpu precision?\n                print \"cpu and gpu sum sq differences differ!!!\"\n                ipy.embed()\n                sys.exit(1)\n\n    def test_bending_cost(self, other, bend_coef=DEFAULT_LAMBDA[1], outlierprior=1e-1, outlierfrac=1e-2, \n                       outliercutoff=1e-2,  T = 5e-3, norm_iters = DEFAULT_NORM_ITERS):\n        self.get_target_points(other, outlierprior, outlierfrac, outliercutoff,  T, norm_iters)\n        self.update_transform(bend_coef)\n        bending_costs = self.bending_cost(bend_coef)\n        for i in range(self.N):\n            c_gpu = bending_costs[i]\n            k_nn = self.kernels[i].get()\n            w_nd = self.w_nd[i].get()\n            c_cpu = np.float32(0)\n            for d in range(DATA_DIM):\n                r = np.dot(k_nn, w_nd[:, d]).astype(np.float32)\n                r = np.float32(np.dot(w_nd[:, d], r))\n                c_cpu += r\n            c_cpu *= np.float32(bend_coef)\n            if np.abs(c_cpu - c_gpu) > 1e-4:\n                ## high err tolerance is b/c of difference in cpu and gpu precision?\n                print \"cpu and gpu bend costs differ!!!\"\n                ipy.embed()\n                sys.exit(1)    \n\n    def test_init_corr(self, other, T = 5e-3, outlierprior=1e-1, outlierfrac=1e-2, outliercutoff=1e-2, ):\n        import scipy.spatial.distance as ssd\n        import sys\n        self.transform_points()\n        other.transform_points()\n        init_prob_nm(self.pt_ptrs, other.pt_ptrs, \n                     self.pt_w_ptrs, other.pt_w_ptrs, \n                     self.dims_gpu, other.dims_gpu,\n                     self.N, outlierprior, outlierfrac, T, \n                     self.corr_cm_ptrs, self.corr_rm_ptrs)\n        gpu_corr_rm = self.corr_rm[0].get()\n        gpu_corr_rm = gpu_corr_rm.flatten()[:(self.dims[0] + 1) * (other.dims[0] + 1)].reshape(self.dims[0]+1, other.dims[0]+1)\n        s_pt_w = self.pts_w[0].get()\n        s_pt   = self.pts[0].get()\n        o_pt_w = other.pts_w[0].get()\n        o_pt   = other.pts[0].get()\n\n        d1 = ssd.cdist(s_pt_w, o_pt, 'euclidean')\n        d2 = ssd.cdist(s_pt, o_pt_w, 'euclidean')\n\n        p_nm = np.exp( -(d1 + d2) / (2 * T))\n\n        for i in range(self.dims[0]):\n            for j in range(other.dims[0]):\n                if abs(p_nm[i, j] - gpu_corr_rm[i, j]) > 1e-7:\n                    print \"INIT CORR MATRICES DIFFERENT\"\n                    print i, j, p_nm[i, j], gpu_corr_rm[i, j]\n                    ipy.embed()\n                    sys.exit(1)\n\n    def test_norm_corr(self, other, T = 5e-3, outlierprior=1e-1, outlierfrac=1e-2, outliercutoff=1e-2, norm_iters = DEFAULT_NORM_ITERS):\n        import sys\n        self.transform_points()\n        other.transform_points()\n        init_prob_nm(self.pt_ptrs, other.pt_ptrs, \n                     self.pt_w_ptrs, other.pt_w_ptrs, \n                     self.dims_gpu, other.dims_gpu,\n                     self.N, outlierprior, outlierfrac, T, \n                     self.corr_cm_ptrs, self.corr_rm_ptrs)\n        n, m  = self.dims[0], other.dims[0]\n        init_corr = self.corr_rm[0].get()        \n        init_corr = init_corr.flatten()[:(n + 1) * (m + 1)].reshape(n+1, m+1).astype(np.float32)\n        \n        a_N = np.ones((n+1),dtype = np.float32)\n        a_N[n] = m*outlierfrac\n        b_M = np.ones((m+1), dtype = np.float32)\n        b_M[m] = n*outlierfrac\n\n        old_r_coefs = np.ones(n+1, dtype=np.float32)\n        old_c_coefs = np.ones(m+1, dtype=np.float32)\n        for n_iter in range(1, norm_iters):\n            init_prob_nm(self.pt_ptrs, other.pt_ptrs, \n                         self.pt_w_ptrs, other.pt_w_ptrs, \n                         self.dims_gpu, other.dims_gpu,\n                         self.N, outlierprior, outlierfrac, T, \n                         self.corr_cm_ptrs, self.corr_rm_ptrs)\n\n            norm_prob_nm(self.corr_cm_ptrs, self.corr_rm_ptrs, \n                         self.dims_gpu, other.dims_gpu, self.N, outlierfrac, n_iter,\n                         self.r_coef_ptrs, self.c_coef_rn_ptrs, self.c_coef_cn_ptrs)        \n            new_r_coefs = a_N/init_corr.dot(old_c_coefs[:m+1])\n            new_c_coefs = b_M/new_r_coefs[:n+1].dot(init_corr)\n            gpu_c_coefs = self.c_coefs_cn[0].get().flatten()[:m + 1].reshape(m+1)\n            gpu_r_coefs = self.r_coefs[0].get().flatten()[:n + 1].reshape(n+1)\n            if not np.allclose(new_r_coefs, gpu_r_coefs):\n                print \"row coeficients don't match\", n_iter\n                ipy.embed()\n                sys.exit(1)\n            if not np.allclose(new_c_coefs, gpu_c_coefs):\n                print \"column coeficients don't match\", n_iter\n                ipy.embed()\n                sys.exit(1)\n            # old_r_coefs = gpu_r_coefs\n            # old_c_coefs = gpu_c_coefs\n            old_r_coefs = new_r_coefs\n            old_c_coefs = new_c_coefs\n            \n    def test_get_targ(self, other, T = 5e-3, outlierprior=1e-1, outlierfrac=1e-2, outliercutoff=1e-2, norm_iters = DEFAULT_NORM_ITERS):\n        self.transform_points()\n        other.transform_points()\n        init_prob_nm(self.pt_ptrs, other.pt_ptrs, \n                     self.pt_w_ptrs, other.pt_w_ptrs, \n                     self.dims_gpu, other.dims_gpu,\n                     self.N, outlierprior, outlierfrac, T, \n                     self.corr_cm_ptrs, self.corr_rm_ptrs)\n        norm_prob_nm(self.corr_cm_ptrs, self.corr_rm_ptrs, \n                     self.dims_gpu, other.dims_gpu, self.N, outlierfrac, norm_iters,\n                     self.r_coef_ptrs, self.c_coef_rn_ptrs, self.c_coef_cn_ptrs)\n        get_targ_pts(self.pt_ptrs, other.pt_ptrs,\n                     self.pt_w_ptrs, other.pt_w_ptrs,\n                     self.corr_cm_ptrs, self.corr_rm_ptrs,\n                     self.r_coef_ptrs, self.c_coef_rn_ptrs, self.c_coef_cn_ptrs,\n                     self.dims_gpu, other.dims_gpu, \n                     outliercutoff, self.N,\n                     self.pt_t_ptrs, other.pt_t_ptrs)\n        n, m = self.dims[0], other.dims[0]\n        x = self.pts[0].get()[:n]\n        xw = self.pts_w[0].get()[:n]\n        xt = self.pts_t[0].get()[:n]\n        y = other.pts[0].get()[:m]\n        yw = other.pts_w[0].get()[:m]\n        yt = other.pts_t[0].get()[:m]\n\n        init_corr = self.corr_rm[0].get()        \n        init_corr = init_corr.flatten()[:(n + 1) * (m + 1)].reshape(n+1, m+1).astype(np.float32)\n        gpu_c_cn_coefs = self.c_coefs_cn[0].get().flatten()[:m + 1].reshape(m+1)\n        gpu_c_rn_coefs = self.c_coefs_rn[0].get().flatten()[:m + 1].reshape(m+1)\n        gpu_r_coefs = self.r_coefs[0].get().flatten()[:n + 1].reshape(n+1)\n\n        rn_corr = (init_corr * gpu_c_rn_coefs[None, :]) * gpu_r_coefs[:, None]\n        cn_corr = (init_corr * gpu_c_cn_coefs[None, :]) * gpu_r_coefs[:, None]        \n        rn_corr = rn_corr[:n, :m]\n        cn_corr = cn_corr[:n, :m]\n        \n        wt_n = rn_corr.sum(axis=1)\n        inlier = wt_n > outliercutoff\n        xtarg = np.empty((n, DATA_DIM))\n        xtarg[inlier, :] = rn_corr.dot(y)[inlier, :]\n        xtarg[~inlier, :] = xw[~inlier, :]\n\n        if not np.allclose(xtarg, xt):\n            print \"xt values differ\"\n            ipy.embed()\n            sys.exit(1)\n\n        wt_m = cn_corr.sum(axis=0)\n        inliner = wt_m > outliercutoff\n        ytarg = np.empty((m, DATA_DIM))\n        ytarg[inlier, :] = cn_corr.T.dot(x)[inliner, :]\n        ytarg[~inlier, :] = yw[~inlier, :]\n        if not np.allclose(ytarg, yt):\n            print \"yt values differ\"\n            ipy.embed()\n            sys.exit(1)                            \n\n    def unit_test(self, other):\n        print \"running basic unit tests\"\n        self.test_init_corr(other)\n        self.test_norm_corr(other)\n        self.test_get_targ(other)\n        self.test_mapping_cost(other)\n        self.test_bending_cost(other)\n        print \"UNIT TESTS PASSED\"\n        \n\nclass TgtContext(GPUContext):\n    \"\"\"\n    specialized class to handle the case where we are\n    mapping to a single target cloud --> only allocate GPU Memory once\n    \"\"\"\n    def __init__(self, src_ctx):\n        GPUContext.__init__(self, src_ctx.bend_coefs)\n        self.src_ctx = src_ctx\n        ## just setup with 0's\n        tgt_cld = np.zeros((MAX_CLD_SIZE, DATA_DIM), np.float32)\n        proj_mats = dict([(b, np.zeros((MAX_CLD_SIZE + DATA_DIM + 1, MAX_CLD_SIZE), np.float32)) \n                          for b in self.bend_coefs])\n        offset_mats = dict([(b, np.zeros((MAX_CLD_SIZE + DATA_DIM + 1, DATA_DIM), np.float32)) \n                            for b in self.bend_coefs])\n        tgt_K = np.zeros((MAX_CLD_SIZE, MAX_CLD_SIZE), np.float32)\n        for n in src_ctx.seg_names:\n            name = \"{}_tgt\".format(n)\n            GPUContext.add_cld(self, name, proj_mats, offset_mats, tgt_cld, tgt_K)\n        GPUContext.update_ptrs(self)\n    def add_cld(self, name, proj_mats, offset_mats, cloud_xyz, kernel, update_ptrs = False):\n        raise NotImplementedError(\"not implemented for TgtConext\")\n    def update_ptrs(self):\n        raise NotImplementedError(\"not implemented for TgtConext\")\n    # @profile\n    def set_cld(self, cld):\n        \"\"\"\n        sets the cloud for this appropriately\n        won't allocate any new memory\n        \"\"\"                          \n        proj_mats, offset_mats, K = self.get_sol_params(cld)\n        K_gpu = gpu_pad(K, (MAX_CLD_SIZE, MAX_CLD_SIZE))\n        cld_gpu = gpu_pad(cld, (MAX_CLD_SIZE, DATA_DIM))\n        self.pts         = [cld_gpu for _ in range(self.N)]\n        self.kernels     = [K_gpu for _ in range(self.N)]\n        proj_mats_gpu    = dict([(b, gpu_pad(p.get(), (MAX_CLD_SIZE + DATA_DIM + 1, MAX_CLD_SIZE)))\n                                 for b, p in proj_mats.iteritems()])\n        self.proj_mats   = dict([(b, [p for _ in range(self.N)])\n                                 for b, p in proj_mats_gpu.iteritems()])\n        offset_mats_gpu  = dict([(b, gpu_pad(p.get(), (MAX_CLD_SIZE + DATA_DIM + 1, DATA_DIM))) \n                                 for b, p in offset_mats.iteritems()])\n        self.offset_mats = dict([(b, [p for _ in range(self.N)])\n                                 for b, p in offset_mats_gpu.iteritems()])\n        self.dims        = [cld.shape[0]]\n\n        self.pt_ptrs.fill(int(self.pts[0].gpudata))\n        self.kernel_ptrs.fill(int(self.kernels[0].gpudata))\n        self.dims_gpu.fill(self.dims[0])\n        for b in self.bend_coefs:\n            self.proj_mat_ptrs[b].fill(int(self.proj_mats[b][0].gpudata))\n            self.offset_mat_ptrs[b].fill(int(self.offset_mats[b][0].gpudata))\n\ndef check_transform_pts(ctx, i = 0):\n    import scikits.cuda.linalg as la\n    n = ctx.dims[i]\n    w_nd = ctx.w_nd[i].get()[:n]\n    lin_dd = ctx.lin_dd[i].get()\n    trans_d = ctx.trans_d[i].get()\n    k_nn = ctx.kernels[i].get()[:n, :n].reshape(n, n).copy()\n    x_nd = ctx.pts[i].get()[:n]\n    xw_nd = ctx.pts_w[i].get()[:n]\n\n    _k_gpu = gpuarray.to_gpu(k_nn)\n    _x_gpu = gpuarray.to_gpu(x_nd)\n    _lin_gpu = gpuarray.to_gpu(lin_dd)\n    _trans_gpu = gpuarray.to_gpu(trans_d)\n    _w_gpu = gpuarray.to_gpu(w_nd)\n    \n    fill_mat(ctx.pt_w_ptrs, ctx.trans_d_ptrs, ctx.dims_gpu, ctx.N)\n    dot_batch_nocheck(ctx.pts,         ctx.lin_dd,      ctx.pts_w,\n                      ctx.pt_ptrs,     ctx.lin_dd_ptrs, ctx.pt_w_ptrs) \n\n    xw_nd = ctx.pts_w[i].get()[:n]\n    cpu_xw_nd = np.dot(x_nd, lin_dd) + trans_d[None, :]\n    # assert np.allclose(xw_nd, cpu_xw_nd)\n\n    dot_batch_nocheck(ctx.kernels,     ctx.w_nd,        ctx.pts_w,\n                      ctx.kernel_ptrs, ctx.w_nd_ptrs,   ctx.pt_w_ptrs) \n    xw_nd = ctx.pts_w[i].get()[:n]\n    cpu_xw_nd = cpu_xw_nd + np.dot(k_nn, w_nd)\n    # print \"w_nd\\n\", w_nd[:3], np.max(w_nd)\n    # print \"lin_dd\\n\", lin_dd[:3]\n    # print \"trans_d\\n\", trans_d\n    # print \"k_nn\\n\", k_nn[:3, :3]\n    # print \"x_nd\\n\", x_nd[:3, :3]\n    # print cpu_xw_nd[:3]\n    if not(np.allclose(xw_nd, cpu_xw_nd) ):\n        print \"k dot w_nd is difference on cpu and gpu\"\n        k_dot_w = np.dot(k_nn, w_nd)\n        k_gpu = [gpuarray.to_gpu(k_nn)]\n        w_gpu = [gpuarray.to_gpu(w_nd)]\n        res_gpu = [gpuarray.zeros((n, DATA_DIM), np.float32)]        \n        k_ptrs = get_gpu_ptrs(k_gpu)\n        w_ptrs = get_gpu_ptrs(w_gpu)\n        res_ptrs = get_gpu_ptrs(res_gpu)\n        dot_batch_nocheck(k_gpu, w_gpu, res_gpu, k_ptrs, w_ptrs, res_ptrs)\n        res = res_gpu[0].get()\n        single_gpu = la.dot(_k_gpu, _w_gpu)\n        print \"retry success {}\".format(np.allclose(res, k_dot_w))\n        print \"gpu success {}\".format(np.allclose(single_gpu.get(), res))\n        assert np.allclose(single_gpu.get(), res)\n        raw_input(\"go?\")\n\ndef check_update(ctx, b):\n    ctx.tps_params[0] = ctx.default_tps_params.copy()\n    ctx.update_ptrs()\n    xt = ctx.pts_t[0].get()\n    p_mat = ctx.proj_mats[b][0].get()\n    o_mat = ctx.offset_mats[b][0].get()\n    true_res = np.dot(p_mat, xt) + o_mat\n    ctx.set_tps_params(ctx.offset_mats[b])\n    o_gpu = ctx.tps_params[0].get()\n    if not np.allclose(o_gpu, o_mat):\n        print \"setting tps params failed\"\n        diff = np.abs(o_mat - o_gpu)\n        nz = np.nonzero(diff)\n        print nz\n        ipy.embed()\n        sys.exit(1)\n    ctx.update_transform(b)\n    p1 = ctx.tps_params[0].get()\n    if not np.allclose(true_res, p1):\n        print \"p1 and true res differ\"\n        print p1[:3]\n        diff = np.abs(p1 - true_res)\n        print np.max(diff)\n        amax = np.argmax(diff)\n        print amax\n        nz = np.nonzero(diff)\n        print nz[0]\n        ipy.embed()\n        sys.exit(1)\n\n# @profile\ndef batch_tps_rpm_bij(src_ctx, tgt_ctx, T_init = 1e-1, T_final = 5e-3, \n                      outlierfrac = 1e-2, outlierprior = 1e-1, outliercutoff = 1e-2, em_iter = EM_ITER_CHEAP):\n    \"\"\"\n    computes tps rpm for the clouds in src and tgt in batch\n    TODO: Fill out comment cleanly\n    \"\"\"\n    ##TODO: add check to ensure that src_ctx and tgt_ctx are formatted properly\n    n_iter = len(src_ctx.bend_coefs)\n    T_vals = loglinspace(T_init, T_final, n_iter)\n\n    src_ctx.reset_tps_params()\n    tgt_ctx.reset_tps_params()\n    for i, b in enumerate(src_ctx.bend_coefs):\n        T = T_vals[i]\n        for _ in range(em_iter):\n            src_ctx.transform_points()\n            tgt_ctx.transform_points()\n            src_ctx.get_target_points(tgt_ctx, outlierprior, outlierfrac, outliercutoff, T)\n            src_ctx.update_transform(b)\n            # check_update(src_ctx, b)\n            tgt_ctx.update_transform(b)\n    return src_ctx.bidir_tps_cost(tgt_ctx)\n\ndef test_batch_tps_rpm_bij(src_ctx, tgt_ctx, T_init = 1e-1, T_final = 5e-3, \n                           outlierfrac = 1e-2, outlierprior = 1e-1, outliercutoff = .5, em_iter = EM_ITER_CHEAP,\n                           test_ind = 0):\n    from transformations import ThinPlateSpline, set_ThinPlateSpline\n    import tps\n    n_iter = len(src_ctx.bend_coefs)\n    T_vals = loglinspace(T_init, T_final, n_iter)\n\n    x_nd = src_ctx.pts[test_ind].get()[:src_ctx.dims[test_ind]]\n    y_md = tgt_ctx.pts[0].get()[:tgt_ctx.dims[0]]\n    (n, d) = x_nd.shape\n    (m, _) = y_md.shape\n\n    f = ThinPlateSpline(d)    \n    g = ThinPlateSpline(d)    \n\n    src_ctx.reset_tps_params()\n    tgt_ctx.reset_tps_params()\n    for i, b in enumerate(src_ctx.bend_coefs):\n        T = T_vals[i]\n        for _ in range(em_iter):\n            src_ctx.transform_points()\n            tgt_ctx.transform_points()\n\n            xwarped_nd = f.transform_points(x_nd)\n            ywarped_md = g.transform_points(y_md)\n            gpu_xw = src_ctx.pts_w[test_ind].get()[:n, :]\n            gpu_yw = tgt_ctx.pts_w[test_ind].get()[:m, :]\n            assert np.allclose(xwarped_nd, gpu_xw, atol=1e-5)\n            assert np.allclose(ywarped_md, gpu_yw, atol=1e-5)\n\n            xwarped_nd = gpu_xw\n            ywarped_md = gpu_yw\n\n            src_ctx.get_target_points(tgt_ctx, outlierprior, outlierfrac, outliercutoff, T)\n            \n            fwddist_nm = ssd.cdist(xwarped_nd, y_md,'euclidean')\n            invdist_nm = ssd.cdist(x_nd, ywarped_md,'euclidean')\n            prob_nm = outlierprior * np.ones((n+1, m+1), np.float32)\n            prob_nm[:n, :m] = np.exp( -(fwddist_nm + invdist_nm) / float(2*T))\n            prob_nm[n, m] = outlierfrac * np.sqrt(n * m)\n\n            gpu_corr = src_ctx.corr_rm[test_ind].get()\n            gpu_corr = gpu_corr.flatten()\n            gpu_corr = gpu_corr[:(n + 1) * (m + 1)].reshape(n+1, m+1).astype(np.float32)\n\n            assert np.allclose(prob_nm[:n, :m], gpu_corr[:n, :m], atol=1e-5)\n            prob_nm[:n, :m] = gpu_corr[:n, :m]\n\n            r_coefs = np.ones(n+1, np.float32)\n            c_coefs = np.ones(m+1, np.float32)\n            a_N = np.ones((n+1),dtype = np.float32)\n            a_N[n] = m*outlierfrac\n            b_M = np.ones((m+1), dtype = np.float32)\n            b_M[m] = n*outlierfrac\n            for _ in range(DEFAULT_NORM_ITERS):\n                r_coefs = a_N/prob_nm.dot(c_coefs)\n                rn_c_coefs = c_coefs\n                c_coefs = b_M/r_coefs.dot(prob_nm)\n            gpu_r_coefs = src_ctx.r_coefs[test_ind].get()[:n+1].reshape(n+1)\n            gpu_c_coefs_cn = src_ctx.c_coefs_cn[test_ind].get()[:m+1].reshape(m+1)\n            gpu_c_coefs_rn = src_ctx.c_coefs_rn[test_ind].get()[:m+1].reshape(m+1)\n            assert np.allclose(r_coefs, gpu_r_coefs, atol=1e-5)\n            assert np.allclose(c_coefs, gpu_c_coefs_cn, atol=1e-5)\n            assert np.allclose(rn_c_coefs, gpu_c_coefs_rn, atol=1e-5)\n            \n            prob_nm = prob_nm[:n, :m]\n            prob_nm *= gpu_r_coefs[:n, None]\n            rn_p_nm = prob_nm * gpu_c_coefs_rn[None, :m]\n            cn_p_nm = prob_nm * gpu_c_coefs_cn[None, :m]\n\n            wt_n = rn_p_nm.sum(axis=1)\n            gpu_corr_cm = src_ctx.corr_cm[test_ind].get().flatten()[:(n+1)*(m+1)]\n            gpu_corr_cm = gpu_corr_cm.reshape(m+1, n+1)## b/c it is column major\n            assert np.allclose(wt_n, gpu_corr_cm[m, :n], atol=1e-4)\n\n            \n            inlier = wt_n > outliercutoff\n            xtarg_nd = np.empty((n, DATA_DIM), np.float32)\n            xtarg_nd[inlier, :] = rn_p_nm.dot(y_md)[inlier, :]\n            xtarg_nd[~inlier, :] = xwarped_nd[~inlier, :]\n\n            wt_m = cn_p_nm.sum(axis=0)\n            assert np.allclose(wt_m, gpu_corr[n, :m], atol=1e-4)\n\n            inlier = wt_m > outliercutoff\n            ytarg_md = np.empty((m, DATA_DIM), np.float32)\n            ytarg_md[inlier, :] = cn_p_nm.T.dot(x_nd)[inlier, :]\n            ytarg_md[~inlier, :] = ywarped_md[~inlier, :]\n            \n            xt_gpu = src_ctx.pts_t[test_ind].get()[:n, :]\n            yt_gpu = tgt_ctx.pts_t[test_ind].get()[:m, :]\n            assert np.allclose(xtarg_nd, xt_gpu, atol=1e-4)\n            assert np.allclose(ytarg_md, yt_gpu, atol=1e-4)\n\n            src_ctx.update_transform(b)\n            tgt_ctx.update_transform(b)\n\n            f_p_mat = src_ctx.proj_mats[b][test_ind].get()[:n+d+1, :n]\n            f_o_mat = src_ctx.offset_mats[b][test_ind].get()[:n+d+1]\n            b_p_mat = tgt_ctx.proj_mats[b][0].get()[:m+d+1, :m]\n            b_o_mat = tgt_ctx.offset_mats[b][0].get()[:m+d+1]\n            f_params = f_p_mat.dot(xtarg_nd) + f_o_mat\n            g_params = b_p_mat.dot(ytarg_md) + b_o_mat\n\n\n            gpu_fparams = src_ctx.tps_params[test_ind].get()[:n+d+1]\n            gpu_gparams = tgt_ctx.tps_params[test_ind].get()[:m+d+1]\n            assert np.allclose(f_params, gpu_fparams, atol=1e-4)\n            assert np.allclose(g_params, gpu_gparams, atol=1e-4)\n\n\n            set_ThinPlateSpline(f, x_nd, gpu_fparams)\n            set_ThinPlateSpline(g, y_md, gpu_gparams)\n\n    f._cost = tps.tps_cost(f.lin_ag, f.trans_g, f.w_ng, f.x_na, xtarg_nd, 1)\n    g._cost = tps.tps_cost(g.lin_ag, g.trans_g, g.w_ng, g.x_na, ytarg_md, 1)\n\n    gpu_cost = src_ctx.bidir_tps_cost(tgt_ctx)    \n    cpu_cost = f._cost + g._cost\n    assert np.isclose(gpu_cost[test_ind], cpu_cost, atol=1e-4)\n    \n        \n\ndef parse_arguments():\n    import argparse\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--input_file\", type=str, default='../data/actions.h5')\n    parser.add_argument(\"--sync\", action='store_true')\n    parser.add_argument(\"--n_copies\", type=int, default=1)\n    parser.add_argument(\"--test\", action='store_true')\n    parser.add_argument(\"--test_full\", action='store_true')\n    parser.add_argument(\"--timing_runs\", type=int, default=100)\n    return parser.parse_args()\n\nif __name__=='__main__':\n    reset_cuda()\n    args = parse_arguments()\n    Globals.sync = args.sync\n    src_ctx = GPUContext()\n    for _ in range(args.n_copies):\n        src_ctx.read_h5(args.input_file)\n    f = h5py.File(args.input_file, 'r')    \n    tgt_cld = downsample_cloud(f['demo1-seg00']['cloud_xyz'][:])\n    f.close()\n    scaled_tgt_cld, _ = unit_boxify(tgt_cld)\n    tgt_ctx = TgtContext(src_ctx)\n    tgt_ctx.set_cld(scaled_tgt_cld)\n    if args.test_full:\n        src_ctx.unit_test(tgt_ctx)\n        print \"unit tests passed, doing full check on batch tps rpm\"\n        for i in range(src_ctx.N):\n            sys.stdout.write(\"\\rtesting source cloud {}\".format(i))\n            sys.stdout.flush()\n            test_batch_tps_rpm_bij(src_ctx, tgt_ctx, test_ind=i)\n        print\"\"\n        print \"tests succeeded!\"\n        sys.exit()\n    if args.test:\n        src_ctx.unit_test(tgt_ctx)\n        print \"testing batch tps_rps\"\n        test_batch_tps_rpm_bij(src_ctx, tgt_ctx)\n        print \"test succeeded!!\"\n        sys.exit()    \n    times = []\n    print \"batchtps initialized\"\n    for i in range(args.timing_runs):\n        sys.stdout.write(\"\\rRunning Timing test {}/{}\".format(i, args.timing_runs))\n        sys.stdout.flush()\n        start = time.time()\n        tgt_ctx.set_cld(scaled_tgt_cld)\n        c = batch_tps_rpm_bij(src_ctx, tgt_ctx)\n        time_taken = time.time() - start\n        times.append(time_taken)\n    print \"\\nTiming Tests Complete\"\n    print \"Batch Size:\\t\\t\\t\", src_ctx.N\n    print \"Mean Compute Time per Batch:\\t\", np.mean(times)\n    print \"BiDirectional TPS fits/second:\\t\", float(args.timing_runs * src_ctx.N) / np.sum(times)\n", "meta": {"hexsha": "a24ed5ea4f795b3da8248c80c7fffd0bf721431d", "size": 37365, "ext": "py", "lang": "Python", "max_stars_repo_path": "tpsopt/batchtps.py", "max_stars_repo_name": "dhadfieldmenell/tps-opt", "max_stars_repo_head_hexsha": "3f7f468c1580f8fd2a740134b500ef2b226cd45a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-03-31T07:27:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-15T03:03:31.000Z", "max_issues_repo_path": "tpsopt/batchtps.py", "max_issues_repo_name": "dhadfieldmenell/tps-opt", "max_issues_repo_head_hexsha": "3f7f468c1580f8fd2a740134b500ef2b226cd45a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tpsopt/batchtps.py", "max_forks_repo_name": "dhadfieldmenell/tps-opt", "max_forks_repo_head_hexsha": "3f7f468c1580f8fd2a740134b500ef2b226cd45a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.8497706422, "max_line_length": 136, "alphanum_fraction": 0.5866452563, "include": true, "reason": "import numpy,import scipy,import pycuda,from pycuda", "num_tokens": 10306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.18995624869307245}}
{"text": "#!/usr/bin/env python3\nimport sys, getopt, math, os, time, traceback\nimport numpy as np\n\n################################# Arguments ###################################\n# Default parameters\nn_traj = 100\nnum_rep = 10\nmutant_type_list = ['fast', 'slow']\nn_window = 200\nco_msm_data_file = ''\npost_msm_data_file = ''\n\n# read control file\nctrlfile = ''\n\nif len(sys.argv) == 1:\n    print(usage)\n    sys.exit()\n\ntry:\n    opts, args = getopt.getopt(sys.argv[1:],\"hf:\", [\"ctrlfile=\"])\nexcept getopt.GetoptError:\n    print(usage)\n    sys.exit()\nfor opt, arg in opts:\n    if opt == '-h':\n        print(usage)\n        sys.exit()\n    elif opt in (\"-f\", \"--ctrlfile\"):\n        ctrlfile = arg\n        \nif not os.path.exists(ctrlfile):\n    print('Error: cannot find control file ' + ctrlfile + '.')\n    sys.exit()\n\nfile_object = open(ctrlfile,'r')\ntry:\n    for line in file_object:\n        line = line.strip()\n        if not line:\n            # This is a blank line\n            continue\n        if line.startswith('#'):\n            # This is a comment line\n            continue\n        if line.startswith('n_traj'):\n            words = line.split('=')\n            n_traj = int(words[1].strip())\n            continue\n        if line.startswith('num_rep'):\n            words = line.split('=')\n            num_rep = int(words[1].strip())\n            continue\n        if line.startswith('mutant_type_list'):\n            words = line.split('=')\n            mutant_type_list = words[1].strip().split()\n            continue\n        if line.startswith('n_window'):\n            words = line.split('=')\n            n_window = int(words[1].strip())\n            continue\n        if line.startswith('co_msm_data_file'):\n            words = line.split('=')\n            co_msm_data_file = words[1].strip()\n            continue\n        if line.startswith('post_msm_data_file'):\n            words = line.split('=')\n            post_msm_data_file = words[1].strip()\n            continue\nfinally:\n     file_object.close()\n\n################################# Functions ###################################\ndef get_pathways(meta_dtrajs, start_states, end_states):\n    pathways = {}\n    states_on_pathway = []\n    start_states = [str(s+1) for s in start_states]\n    end_states = [str(s+1) for s in end_states]\n\n    for traj_idx, md in enumerate(meta_dtrajs):\n        path = []\n        for idx, mdi in enumerate(md):\n            if str(mdi+1) in start_states:\n                path.append(str(mdi+1))\n                break\n        if idx == len(md)-1:\n            continue\n            \n        for mdi in md[idx+1:]:\n            tag_find = False\n            for pi in range(len(path)):\n                if path[pi] == str(mdi+1):\n                    path = path[0:pi+1]\n                    tag_find = True\n                    break\n            if not tag_find:\n                path.append(str(mdi+1))\n        \n        if path[-1] not in end_states:\n            continue      \n        \n        for p in path:\n            if not int(p) in states_on_pathway:\n                states_on_pathway.append(int(p))\n        \n        path = ' -> '.join(path)\n        if not path in pathways.keys():\n            pathways[path] = 1\n        else:\n            pathways[path] += 1\n    \n    tot_num = 0\n    for path in pathways.keys():\n        tot_num += pathways[path]\n    for path in pathways.keys():\n        pathways[path] /= tot_num\n\n    sort_pathways = sorted(pathways.items(), key=lambda x: x[1], reverse=True)\n    \n    states_on_pathway.sort()\n    return [sort_pathways, states_on_pathway]\n\n################################## MAIN #######################################\n# Read co-trans metastable dtrajs\nco_meta_dtrajs = np.load(co_msm_data_file, allow_pickle=True)['meta_dtrajs']\nco_n_states = 0\nfor i in range(len(co_meta_dtrajs)):\n    if np.max(co_meta_dtrajs[i]) > co_n_states:\n        co_n_states = np.max(co_meta_dtrajs[i])\nco_n_states += 1\n# Read post-trans metastable dtrajs\npost_meta_dtrajs = np.load(post_msm_data_file, allow_pickle=True)['meta_dtrajs']\nmax_T_len = 0\npost_n_states = 0\nfor i in range(len(post_meta_dtrajs)):\n    if post_meta_dtrajs[i].shape[0] > max_T_len:\n        max_T_len = post_meta_dtrajs[i].shape[0]\n    if np.max(post_meta_dtrajs[i]) > post_n_states:\n        post_n_states = np.max(post_meta_dtrajs[i])\npost_n_states += 1\npost_meta_dtrajs_extended = []\nfor i in range(len(post_meta_dtrajs)):\n    (N, be) = np.histogram(post_meta_dtrajs[i][-n_window:], bins=np.arange(-0.5, post_n_states, 1))\n    meta_dtraj_last = np.argwhere(N == np.max(N))[0][0]\n    mde = []\n    for j in range(max_T_len):\n        if j >= len(post_meta_dtrajs[i]): \n            state_0 = meta_dtraj_last\n        else:\n            state_0 = post_meta_dtrajs[i][j]\n        mde.append(state_0)\n    post_meta_dtrajs_extended.append(mde)\n\nprint('Total number of states: %d'%(co_n_states + post_n_states))\n\n# combine dtrajs\nmeta_dtrajs = []\nfor i in range(len(co_meta_dtrajs)):\n    for j in range(num_rep):\n        md = np.hstack((co_meta_dtrajs[i], post_meta_dtrajs_extended[i*num_rep+j] + co_n_states))\n        meta_dtrajs.append(md)\nmeta_dtrajs = np.array(meta_dtrajs, dtype=object)\n\nmtype2trajid = [np.arange(n_traj*num_rep*i_ax, n_traj*num_rep*(i_ax+1)).astype(int) for i_ax, mutant_type in enumerate(mutant_type_list)]\n\n# analysis MSM for each mutant\nfo = open('pathways.dat', 'w')\nfor i_ax, mutant_type in enumerate(mutant_type_list):    \n    # flux analysis\n    A = [0]\n    B = [md[-1] for md in meta_dtrajs[mtype2trajid[i_ax]]]\n    B = np.unique(B)\n    \n    [pathways, state_on_pathway] = get_pathways(meta_dtrajs[mtype2trajid[i_ax]], A, B)\n    \n    fo.write('%s pathways:\\n'%mutant_type)\n    fo.write('%-12s %s\\n'%('percentage','path'))\n    fo.write('-------------------------------------\\n')\n    for path in pathways:\n        fo.write('%-12s %-s\\n'%('%.2f %%'%(path[1] * 100), path[0]))\n    fo.write('\\n')\n", "meta": {"hexsha": "22a7fec19bc706f69b378fd9a7cb9c07e782e8d7", "size": 5861, "ext": "py", "lang": "Python", "max_stars_repo_path": "Analysis_protocol/get_co_post_folding_pathways.py", "max_stars_repo_name": "obrien-lab/cg_simtk_protain_folding", "max_stars_repo_head_hexsha": "c64aa49696afe6fc1680c083cda556697d937f52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Analysis_protocol/get_co_post_folding_pathways.py", "max_issues_repo_name": "obrien-lab/cg_simtk_protain_folding", "max_issues_repo_head_hexsha": "c64aa49696afe6fc1680c083cda556697d937f52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Analysis_protocol/get_co_post_folding_pathways.py", "max_forks_repo_name": "obrien-lab/cg_simtk_protain_folding", "max_forks_repo_head_hexsha": "c64aa49696afe6fc1680c083cda556697d937f52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0273224044, "max_line_length": 137, "alphanum_fraction": 0.564920662, "include": true, "reason": "import numpy", "num_tokens": 1516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.18995624490644947}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 29 09:38:12 2021\n\n@author: ruy\n\"\"\"\nfrom __future__ import annotations\nfrom abc import ABC\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom functools import cached_property as property\nimport numpy as np\nfrom dataclass_tools.tools import (\n    DESERIALIZER_OPTIONS,\n    DeSerializerOptions,\n    NamePrint,\n    PrintMetadata,\n    serialize_dataclass,\n)\n\nfrom pylatex import NoEscape, Quantity\n\nfrom .abrevitation_registry import abv_registry\nfrom .common_field_options import NAME_OPTIONS\nfrom .constants import GRAVITY\n\n\nclass TypeOfService(str, Enum):\n    \"\"\"Vessels service type in accordance to GL HSC 2012 rules.\"\"\"\n\n    PASSENGER = \"PASSENGER\"\n    FERRY = \"FERRY\"\n    CARGO = \"CARGO\"\n    SUPPLY = \"SUPPLY\"\n    PILOT = \"PILOT\"\n    RESCUE = \"RESCUE\"\n\n\nclass ServiceRange(str, Enum):\n    \"\"\"\n    Vessels service range in accordance to GL HSC 2012 rules.\n    USR - Unrestricted service range\n    RSA_200 - 200 nm range\n    RSA_50 - 50 nm range\n    RSA_20 - 20 nm range\n    RSA_SW - sheltered waters\n    \"\"\"\n\n    USR = \"USR\"\n    RSA_200 = \"RSA (200)\"\n    RSA_50 = \"RSA (50)\"\n    RSA_20 = \"RSA (20)\"\n    RSA_SW = \"RSA (SW)\"\n\n\nSPEED_OPTIONS = DeSerializerOptions(\n    metadata=PrintMetadata(long_name=\"Speed\", abreviation=\"S\", units=\"kt\")\n)\nabv_registry.append(SPEED_OPTIONS)\nDISPLACEMENT_OPTIONS = DeSerializerOptions(\n    metadata=PrintMetadata(\n        long_name=\"Displacement\", abreviation=NoEscape(r\"$\\Delta$\"), units=\"t\"\n    )\n)\nabv_registry.append(DISPLACEMENT_OPTIONS)\nLENGTH_OPTIONS = DeSerializerOptions(\n    metadata=PrintMetadata(long_name=\"Length\", abreviation=\"L\", units=\"m\")\n)\nabv_registry.append(LENGTH_OPTIONS)\nBEAM_OPTIONS = DeSerializerOptions(\n    metadata=PrintMetadata(long_name=\"Beam\", abreviation=\"B\", units=\"m\")\n)\nabv_registry.append(BEAM_OPTIONS)\nFWD_PERP_OPTIONS = DeSerializerOptions(\n    metadata=PrintMetadata(\n        long_name=\"Foward Perpendicular\",\n        abreviation=NoEscape(r\"F\\textsubscript{P}\"),\n        units=\"m\",\n    )\n)\nabv_registry.append(FWD_PERP_OPTIONS)\nAFT_PERP_OPTIONS = DeSerializerOptions(\n    metadata=PrintMetadata(\n        long_name=\"Aft Perpendicular\",\n        abreviation=NoEscape(r\"A\\textsubscript{P}\"),\n        units=\"m\",\n    )\n)\nabv_registry.append(AFT_PERP_OPTIONS)\nDRAFT_OPTIONS = DeSerializerOptions(\n    metadata=PrintMetadata(\n        long_name=\"Draft\",\n        abreviation=\"H\",\n        units=\"m\",\n    )\n)\nabv_registry.append(DRAFT_OPTIONS)\nZ_BASELINE_OPTIONS = DeSerializerOptions(\n    metadata=PrintMetadata(\n        long_name=\"Z from base line\",\n        abreviation=NoEscape(r\"z\\textsubscript{BL}\"),\n        units=\"m\",\n    )\n)\nabv_registry.append(Z_BASELINE_OPTIONS)\nBLOCK_COEF_OPTIONS = DeSerializerOptions(\n    metadata=PrintMetadata(\n        long_name=\"Block coefficient\",\n        abreviation=NoEscape(r\"C\\textsubscript{B}\"),\n        units=\"\",\n    )\n)\nabv_registry.append(BLOCK_COEF_OPTIONS)\nWATER_PLANE_AREA_OPTIONS = DeSerializerOptions(\n    metadata=PrintMetadata(\n        long_name=\"Water plane area\",\n        abreviation=NoEscape(r\"WP\\textsubscript{A}\"),\n        units=\"m**2\",\n    )\n)\nabv_registry.append(WATER_PLANE_AREA_OPTIONS)\nLCG_OPTIONS = DeSerializerOptions(\n    metadata=PrintMetadata(\n        long_name=\"Longitudinal center of gravity\",\n        abreviation=NoEscape(r\"L\\textsubscript{cg}\"),\n        units=\"m\",\n    )\n)\nabv_registry.append(LCG_OPTIONS)\nDEADRISE_LCG_OPTIONS = DeSerializerOptions(\n    metadata=PrintMetadata(\n        long_name=\"Deadrise at longitudinal center of gravity\",\n        abreviation=NoEscape(r\"$\\alpha$\\textsubscript{d}\"),\n        units=\"degree\",\n    )\n)\nabv_registry.append(DEADRISE_LCG_OPTIONS)\nDIST_HULL_CL_OPTIONS = DeSerializerOptions(\n    metadata=PrintMetadata(\n        long_name=\"Distance between hulls centerline\",\n        abreviation=NoEscape(r\"B\\textsubscript{CL}\"),\n        units=\"m\",\n    )\n)\nabv_registry.append(DIST_HULL_CL_OPTIONS)\nTYPE_OF_SERVICE_OPTIONS = DeSerializerOptions(\n    metadata=PrintMetadata(\n        long_name=\"Type of service\",\n        abreviation=\"ToS\",\n    )\n)\nabv_registry.append(TYPE_OF_SERVICE_OPTIONS)\nSERVICE_RANGE_OPTIONS = DeSerializerOptions(\n    metadata=PrintMetadata(\n        long_name=\"Service range\",\n        abreviation=\"SR\",\n    )\n)\nabv_registry.append(SERVICE_RANGE_OPTIONS)\nVERT_ACG_OPTIONS = DeSerializerOptions(\n    metadata=PrintMetadata(\n        long_name=\"Center of gravity's vertical acceleration\",\n        abreviation=NoEscape(r\"a\\textsubscript{CG}\"),\n        units=\"g\",\n    )\n)\nabv_registry.append(VERT_ACG_OPTIONS)\nSHEAR_FORCE_OPTIONS = DeSerializerOptions(\n    metadata=PrintMetadata(\n        long_name=\"Transverse shear force\",\n        abreviation=NoEscape(r\"T\\textsubscript{bt}\"),\n        units=\"kN\",\n    )\n)\nabv_registry.append(SHEAR_FORCE_OPTIONS)\nTRANSVERSE_BENDING_MOMENT_OPTIONS = DeSerializerOptions(\n    metadata=PrintMetadata(\n        long_name=\"Transverse bending moment\",\n        abreviation=NoEscape(r\"M\\textsubscript{bt}\"),\n        units=\"kN*m\",\n    )\n)\nabv_registry.append(TRANSVERSE_BENDING_MOMENT_OPTIONS)\nTRANSVERSE_TORSIONAL_MOMENT_OPTIONS = DeSerializerOptions(\n    metadata=PrintMetadata(\n        long_name=\"Transverse torsional moment\",\n        abreviation=NoEscape(r\"M\\textsubscript{tt}\"),\n        units=\"kN*m\",\n    )\n)\nabv_registry.append(TRANSVERSE_TORSIONAL_MOMENT_OPTIONS)\n\n\n@dataclass\nclass VesselLoads:\n    vert_acg: float = field(metadata={DESERIALIZER_OPTIONS: VERT_ACG_OPTIONS})\n    shear_force: float = field(metadata={DESERIALIZER_OPTIONS: SHEAR_FORCE_OPTIONS})\n    trans_bend_moment: float = field(\n        metadata={DESERIALIZER_OPTIONS: TRANSVERSE_BENDING_MOMENT_OPTIONS}\n    )\n    trans_tors_moment: float = field(\n        metadata={DESERIALIZER_OPTIONS: TRANSVERSE_TORSIONAL_MOMENT_OPTIONS}\n    )\n\n\n@dataclass\nclass Monohull:\n    \"\"\"Vessel for the 2012 German Lloyds High Speed Craft\n    scantling rules.\n    \"\"\"\n\n    name: str = field(metadata={DESERIALIZER_OPTIONS: NAME_OPTIONS})\n    speed: float = field(metadata={DESERIALIZER_OPTIONS: SPEED_OPTIONS})\n    displacement: float = field(metadata={DESERIALIZER_OPTIONS: DISPLACEMENT_OPTIONS})\n    length: float = field(metadata={DESERIALIZER_OPTIONS: LENGTH_OPTIONS})\n    beam: float = field(metadata={DESERIALIZER_OPTIONS: BEAM_OPTIONS})\n    fwd_perp: float = field(metadata={DESERIALIZER_OPTIONS: FWD_PERP_OPTIONS})\n    aft_perp: float = field(metadata={DESERIALIZER_OPTIONS: AFT_PERP_OPTIONS})\n    draft: float = field(metadata={DESERIALIZER_OPTIONS: DRAFT_OPTIONS})\n    z_baseline: float = field(metadata={DESERIALIZER_OPTIONS: Z_BASELINE_OPTIONS})\n    block_coef: float = field(metadata={DESERIALIZER_OPTIONS: BLOCK_COEF_OPTIONS})\n    water_plane_area: float = field(\n        metadata={DESERIALIZER_OPTIONS: WATER_PLANE_AREA_OPTIONS}\n    )\n    lcg: float = field(metadata={DESERIALIZER_OPTIONS: LCG_OPTIONS})\n    deadrise_lcg: float = field(metadata={DESERIALIZER_OPTIONS: DEADRISE_LCG_OPTIONS})\n\n    type_of_service: TypeOfService = field(\n        metadata={DESERIALIZER_OPTIONS: TYPE_OF_SERVICE_OPTIONS},\n        default=TypeOfService.PASSENGER,\n    )\n    service_range: ServiceRange = field(\n        metadata={DESERIALIZER_OPTIONS: SERVICE_RANGE_OPTIONS},\n        default=ServiceRange.USR,\n    )\n\n    # Table C3.3.1\n    @property\n    def serv_type_coef(self):\n        table = {\n            TypeOfService.PASSENGER: 0.24,\n            TypeOfService.FERRY: 0.24,\n            TypeOfService.CARGO: 0.24,\n            TypeOfService.SUPPLY: 0.36,\n            TypeOfService.PILOT: 0.5,\n            TypeOfService.RESCUE: 0.6,\n        }\n        return table[self.type_of_service]\n\n    # Table C3.3.1\n    @property\n    def serv_range_coef(self):\n        table = {\n            ServiceRange.USR: 1.0,\n            ServiceRange.RSA_200: 0.9,\n            ServiceRange.RSA_50: 0.75,\n            ServiceRange.RSA_20: 0.66,\n            ServiceRange.RSA_SW: 0.6,\n        }\n        return table[self.service_range]\n\n    @property\n    def z_waterline(self):\n        return self.z_baseline + self.draft\n\n    @property\n    def midship(self):\n        return (self.fwd_perp + self.aft_perp) / 2\n\n    @property\n    def x_pos_cg(self):\n        return (self.lcg - self.aft_perp) / (self.fwd_perp - self.aft_perp)\n\n    @property\n    def sp_len_ratio(self) -> float:\n        return self.speed / self.length**0.5\n\n    # C3.3.1\n    @property\n    def vert_acg(self):\n        \"\"\"Vertical acceletation at LCGm, output in g (9.81 m/s2)\"\"\"\n        acg = self.serv_type_coef * self.serv_range_coef * self.sp_len_ratio\n        if self.type_of_service == TypeOfService.PASSENGER:\n            return min([1.0, acg])\n        return acg\n\n    @property\n    def max_wave_height(self):\n        \"\"\"C3.3.3 Assessment of limit operating conditions\"\"\"\n        return (\n            5\n            * np.max([self.vert_acg, 1])\n            / self.speed\n            * self.length**1.5\n            / (6 + 0.14 * self.length)\n        )\n\n    @property\n    def sig_wave_height(self):\n        \"\"\"C3.3.3.2 Limitation imposed by vertical acceleration at LCG\"\"\"\n        return 10.9 * self.vert_acg * self.coef_kcat * self.coef_kh / self.coef_kf**2\n\n    # C3.3.3.2\n    @property\n    def coef_kcat(self):\n        return 1.0\n\n    # C3.3.3.2\n    @property\n    def coef_kf(self):\n        return 3.23 / self.length * (2.43 * self.length**0.5 + self.speed)\n\n    # C3.3.3.2\n    @property\n    def coef_kt(self):\n        return (\n            4.6 * self.water_plane_area / self.displacement * (self.x_pos_cg) ** 0.5\n        ) ** 0.5\n\n    # C3.3.3.2\n    @property\n    def coef_k(self):\n        return self.coef_kf / self.coef_kt\n\n    # C3.3.3.2\n    @property\n    def coef_kh(self):\n        return self.coef_k**0.35 * ((1 / self.coef_k**2 - 0.11) ** 2 + 1) ** 0.5\n\n\n@dataclass\nclass Catamaran(Monohull):\n    dist_hull_cl: float = field(\n        metadata={DESERIALIZER_OPTIONS: DIST_HULL_CL_OPTIONS}, default=0\n    )\n\n    # C3.3.3.2\n    @property\n    def coef_kcat(self):\n        return np.max(\n            [1 + (self.dist_hull_cl - self.max_wave_height) / self.length, 1.0]\n        )\n\n    # C3.4.2.3\n    @property\n    def transverse_bending_moment(self):\n        \"\"\"Transverse bending moment in kN*m.\"\"\"\n        return self.displacement * self.dist_hull_cl * self.vert_acg * GRAVITY / 5\n\n    # C3.4.2.3\n    @property\n    def transverse_shear_force(self):\n        \"\"\"Transverse shear force in kN.\"\"\"\n        return self.displacement * self.vert_acg * GRAVITY / 4\n\n    # C3.4.2.4\n    @property\n    def transverse_torsional_moment(self):\n        \"\"\"Transverse torsional moment in kN*m.\"\"\"\n        return 0.125 * self.displacement * self.length * self.vert_acg * GRAVITY\n\n    @property\n    def loads_names(self):\n        return [\n            \"vert_acg\",\n            \"shear_force\",\n            \"transverse_bending_moment\",\n            \"transverse_torsional_moment\",\n        ]\n\n    @property\n    def loads_asdict(self):\n        loads = VesselLoads(\n            vert_acg=self.vert_acg,\n            shear_force=self.transverse_shear_force,\n            trans_bend_moment=self.transverse_bending_moment,\n            trans_tors_moment=self.transverse_torsional_moment,\n        )\n        return serialize_dataclass(loads, printing_format=True, include_names=True)\n", "meta": {"hexsha": "d0a5624aaad5851f34f03539dafecbe8ec681e77", "size": 11202, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/gl_hsc_scantling/vessel.py", "max_stars_repo_name": "ruy-sevalho/german_lloyds_hsc_rules", "max_stars_repo_head_hexsha": "ac65158ddfeca0b96487c4959476256e83981d3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gl_hsc_scantling/vessel.py", "max_issues_repo_name": "ruy-sevalho/german_lloyds_hsc_rules", "max_issues_repo_head_hexsha": "ac65158ddfeca0b96487c4959476256e83981d3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gl_hsc_scantling/vessel.py", "max_forks_repo_name": "ruy-sevalho/german_lloyds_hsc_rules", "max_forks_repo_head_hexsha": "ac65158ddfeca0b96487c4959476256e83981d3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4789473684, "max_line_length": 86, "alphanum_fraction": 0.6727370112, "include": true, "reason": "import numpy", "num_tokens": 3054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.18985858565612163}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n################################################################################\n#\n#   RMG - Reaction Mechanism Generator\n#\n#   Copyright (c) 2002-2009 Prof. William H. Green (whgreen@mit.edu) and the\n#   RMG Team (rmg_dev@mit.edu)\n#\n#   Permission is hereby granted, free of charge, to any person obtaining a\n#   copy of this software and associated documentation files (the \"Software\"),\n#   to deal in the Software without restriction, including without limitation\n#   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n#   and/or sell copies of the Software, and to permit persons to whom the\n#   Software is furnished to do so, subject to the following conditions:\n#\n#   The above copyright notice and this permission notice shall be included in\n#   all copies or substantial portions of the Software.\n#\n#   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n#   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n#   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n#   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n#   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n#   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n#   DEALINGS IN THE SOFTWARE.\n#\n################################################################################\n\n\"\"\"\nThis module provides the :class:`StatMechJob` class, which represents a\nstatistical mechanics job used to compute and save the statistical mechanics\ninformation for a single species or transition state.\n\"\"\"\n\nimport os.path\nimport math\nimport numpy\nimport logging\n\nimport rmgpy.constants as constants\nfrom rmgpy.cantherm.output import prettify\nfrom rmgpy.cantherm.gaussian import GaussianLog\nfrom rmgpy.cantherm.molepro import MoleProLog\nfrom rmgpy.species import TransitionState\nfrom rmgpy.statmech import *\n\n################################################################################\n\nclass InputError(Exception):\n    \"\"\"\n    An exception raised when parsing an input file for a conformer. Pass a\n    string describing the error.\n    \"\"\"\n    pass\n\n################################################################################\n\nclass ScanLog:\n    \"\"\"\n    Represent a text file containing a table of angles and corresponding\n    scan energies.\n    \"\"\"\n\n    angleFactors = {\n        'radians': 1.0,\n        'rad': 1.0,\n        'degrees': 180.0 / math.pi,\n        'deg': 180.0 / math.pi,\n    }\n    energyFactors = {\n        'J/mol': 1.0,\n        'kJ/mol': 1.0/1000.,\n        'cal/mol': 1.0/4.184,\n        'kcal/mol': 1.0/4184.,\n        'cm^-1': 1.0/(constants.h * constants.c * 100. * constants.Na),\n        'hartree': 1.0/(constants.E_h * constants.Na),\n    }\n        \n    def __init__(self, path):\n        self.path = path\n\n    def load(self):\n        \"\"\"\n        Load the scan energies from the file. Returns arrays containing the\n        angles (in radians) and energies (in J/mol).\n        \"\"\"\n        angles = []; energies = []\n        angleUnits = None; energyUnits = None\n        angleFactor = None; energyFactor = None\n        \n        with open(self.path, 'r') as stream:\n            for line in stream:\n                line = line.strip()\n                if line == '': continue\n                \n                tokens = line.split()\n                if angleUnits is None or energyUnits is None:\n                    angleUnits = tokens[1][1:-1]\n                    energyUnits = tokens[3][1:-1]\n                    \n                    try:\n                        angleFactor = ScanLog.angleFactors[angleUnits]\n                    except KeyError:\n                        raise ValueError('Invalid angle units {0!r}.'.format(angleUnits))\n                    try:\n                        energyFactor = ScanLog.energyFactors[energyUnits]\n                    except KeyError:\n                        raise ValueError('Invalid energy units {0!r}.'.format(energyUnits))\n            \n                else:\n                    angles.append(float(tokens[0]) / angleFactor)\n                    energies.append(float(tokens[1]) / energyFactor)\n        \n        angles = numpy.array(angles)\n        energies = numpy.array(energies)\n        energies -= energies[0]\n        \n        return angles, energies\n        \n    def save(self, angles, energies, angleUnits='radians', energyUnits='kJ/mol'):\n        \"\"\"\n        Save the scan energies to the file using the given `angles` in radians\n        and corresponding energies `energies` in J/mol. The file is created to\n        use the given `angleUnits` for angles and `energyUnits` for energies.\n        \"\"\"\n        assert len(angles) == len(energies)\n        \n        try:\n            angleFactor = ScanLog.angleFactors[angleUnits]\n        except KeyError:\n            raise ValueError('Invalid angle units {0!r}.'.format(angleUnits))\n        try:\n            energyFactor = ScanLog.energyFactors[energyUnits]\n        except KeyError:\n            raise ValueError('Invalid energy units {0!r}.'.format(energyUnits))\n        \n        with open(self.path, 'w') as stream:\n            stream.write('{0:>24} {1:>24}\\n'.format(\n                'Angle ({0})'.format(angleUnits),\n                'Energy ({0})'.format(energyUnits),\n            ))\n            for angle, energy in zip(angles, energies):\n                stream.write('{0:23.10f} {1:23.10f}\\n'.format(angle * angleFactor, energy * energyFactor))\n\n################################################################################\n\ndef hinderedRotor(scanLog, pivots, top, symmetry, fit='best'):\n    return [scanLog, pivots, top, symmetry, fit]\n\nclass StatMechJob:\n    \"\"\"\n    A representation of a CanTherm statistical mechanics job. This job is used\n    to compute and save the statistical mechanics information for a single\n    species or transition state.\n    \"\"\"\n    \n    def __init__(self, species, path):\n        self.species = species\n        self.path = path\n        self.modelChemistry = ''\n        self.frequencyScaleFactor = 1.0\n        self.includeHinderedRotors = True\n        self.applyBondEnergyCorrections = True\n    \n    def execute(self, outputFile=None, plot=False):\n        \"\"\"\n        Execute the statistical mechanics job, saving the results to the\n        given `outputFile` on disk.\n        \"\"\"\n        self.load()\n        if outputFile is not None:\n            self.save(outputFile)\n    \n    def load(self):\n        \"\"\"\n        Load the statistical mechanics parameters for each conformer from\n        the associated files on disk. Creates :class:`Conformer` objects for\n        each conformer and appends them to the list of confomers on the\n        species object.\n        \"\"\"\n        logging.info('Loading statistical mechanics parameters for {0}...'.format(self.species.label))\n        \n        path = self.path\n        \n        TS = isinstance(self.species, TransitionState)\n    \n        global_context = {\n            '__builtins__': None,\n        }\n        local_context = {\n            '__builtins__': None,\n            'True': True,\n            'False': False,\n            'HinderedRotor': hinderedRotor,\n            # File formats\n            'GaussianLog': GaussianLog,\n            'MoleProLog': MoleProLog,\n            'ScanLog': ScanLog,\n        }\n    \n        directory = os.path.abspath(os.path.dirname(path))\n    \n        with open(path, 'r') as f:\n            try:\n                exec f in global_context, local_context\n            except (NameError, TypeError, SyntaxError), e:\n                logging.error('The species file {0} was invalid:'.format(path))\n                raise\n        \n        try:\n            atoms = local_context['atoms']\n        except KeyError:\n            raise InputError('Required attribute \"atoms\" not found in species file {0!r}.'.format(path))\n        \n        try:\n            bonds = local_context['bonds']\n        except KeyError:\n            bonds = {}\n            \n        try:\n            linear = local_context['linear']\n        except KeyError:\n            raise InputError('Required attribute \"linear\" not found in species file {0!r}.'.format(path))\n        \n        try:\n            externalSymmetry = local_context['externalSymmetry']\n        except KeyError:\n            raise InputError('Required attribute \"externalSymmetry\" not found in species file {0!r}.'.format(path))\n        \n        try:\n            spinMultiplicity = local_context['spinMultiplicity']\n        except KeyError:\n            raise InputError('Required attribute \"spinMultiplicity\" not found in species file {0!r}.'.format(path))\n       \n        try:\n            opticalIsomers = local_context['opticalIsomers']\n        except KeyError:\n            raise InputError('Required attribute \"opticalIsomers\" not found in species file {0!r}.'.format(path))\n        \n        try:\n            energy = local_context['energy']\n        except KeyError:\n            raise InputError('Required attribute \"energy\" not found in species file {0!r}.'.format(path))\n        if isinstance(energy, dict):\n            try:\n                energy = energy[self.modelChemistry]\n            except KeyError:\n                raise InputError('Model chemistry {0!r} not found in from dictionary of energy values in species file {1!r}.'.format(self.modelChemistry, path))\n        if isinstance(energy, GaussianLog):\n            energyLog = energy; E0 = 'Gaussian'\n            energyLog.path = os.path.join(directory, energyLog.path)\n        if isinstance(energy, MoleProLog):\n            energyLog = energy; E0 = 'MolePro'\n            energyLog.path = os.path.join(directory, energyLog.path)\n        elif isinstance(energy, float):\n            energyLog = None; E0 = energy\n        \n        try:\n            geomLog = local_context['geometry']\n        except KeyError:\n            raise InputError('Required attribute \"geometry\" not found in species file {0!r}.'.format(path))\n        geomLog.path = os.path.join(directory, geomLog.path)\n    \n        try:\n            statmechLog = local_context['frequencies']\n        except KeyError:\n            raise InputError('Required attribute \"frequencies\" not found in species file {0!r}.'.format(path))\n        statmechLog.path = os.path.join(directory, statmechLog.path)\n        \n        if 'frequencyScaleFactor' in local_context:\n            logging.warning('Ignoring frequency scale factor in species file {0!r}.'.format(path))\n        \n        try:\n            rotors = local_context['rotors']\n        except KeyError:\n            rotors = []\n        \n        # But don't consider hindered rotors if flag is not set\n        if not self.includeHinderedRotors:\n            rotors = []\n        \n        logging.debug('    Reading molecular degrees of freedom...')\n        conformer = statmechLog.loadConformer(symmetry=externalSymmetry, spinMultiplicity=spinMultiplicity, opticalIsomers=opticalIsomers)\n        \n        logging.debug('    Reading optimized geometry...')\n        coordinates, number, mass = geomLog.loadGeometry()\n        conformer.coordinates = (coordinates,\"angstroms\") \n        conformer.number = number\n        conformer.mass = (mass,\"amu\")\n        \n        logging.debug('    Reading energy...')\n        # The E0 that is read from the log file is without the ZPE and corresponds to E_elec\n        if E0 is 'Gaussian':\n            E0 = energyLog.loadEnergy(self.frequencyScaleFactor)\n        elif E0 is 'MolePro':\n            E0 = energyLog.loadCCSDEnergy()\n        else:\n            E0 = E0 * constants.E_h * constants.Na         # Hartree/particle to J/mol\n        E0 = applyEnergyCorrections(E0, self.modelChemistry, atoms, bonds if self.applyBondEnergyCorrections else {})\n        ZPE = statmechLog.loadZeroPointEnergy() * self.frequencyScaleFactor\n        \n        # The E0_withZPE at this stage contains the ZPE\n        E0_withZPE = E0 + ZPE\n        \n        logging.debug('         Scaling factor used = {0:g}'.format(self.frequencyScaleFactor))\n        logging.debug('         ZPE (0 K) = {0:g} kcal/mol'.format(ZPE / 4184.))\n        logging.debug('         E0 (0 K) = {0:g} kcal/mol'.format(E0_withZPE / 4184.))\n       \n        conformer.E0 = (E0_withZPE*0.001,\"kJ/mol\")\n        \n        # If loading a transition state, also read the imaginary frequency\n        if TS:\n            self.species.frequency = (statmechLog.loadNegativeFrequency() * self.frequencyScaleFactor, \"cm^-1\")\n\n        # Read and fit the 1D hindered rotors if applicable\n        # If rotors are found, the vibrational frequencies are also\n        # recomputed with the torsional modes removed\n        F = statmechLog.loadForceConstantMatrix()\n        if F is not None and len(mass) > 1 and len(rotors) > 0:\n            \n            logging.debug('    Fitting {0} hindered rotors...'.format(len(rotors)))\n            rotorCount = 0\n            for scanLog, pivots, top, symmetry, fit in rotors:\n                \n                # Load the hindered rotor scan energies\n                if isinstance(scanLog, GaussianLog):\n                    scanLog.path = os.path.join(directory, scanLog.path)\n                    Vlist, angle = scanLog.loadScanEnergies()\n                    scanLogOutput = ScanLog(os.path.join(directory, '{0}_rotor_{1}.txt'.format(self.species.label, rotorCount+1)))\n                    scanLogOutput.save(angle, Vlist)\n                elif isinstance(scanLog, ScanLog):\n                    scanLog.path = os.path.join(directory, scanLog.path)\n                    angle, Vlist = scanLog.load()\n                else:\n                    raise Exception('Invalid log file type {0} for scan log.'.format(scanLog.__class__))\n                    \n                inertia = conformer.getInternalReducedMomentOfInertia(pivots, top) * constants.Na * 1e23\n                \n                cosineRotor = HinderedRotor(inertia=(inertia,\"amu*angstrom^2\"), symmetry=symmetry)\n                cosineRotor.fitCosinePotentialToData(angle, Vlist)\n                fourierRotor = HinderedRotor(inertia=(inertia,\"amu*angstrom^2\"), symmetry=symmetry)\n                fourierRotor.fitFourierPotentialToData(angle, Vlist)\n                \n                Vlist_cosine = numpy.zeros_like(angle)\n                Vlist_fourier = numpy.zeros_like(angle)\n                for i in range(angle.shape[0]):\n                    Vlist_cosine[i] = cosineRotor.getPotential(angle[i])\n                    Vlist_fourier[i] = fourierRotor.getPotential(angle[i])\n                \n                if fit=='cosine':\n                    rotor=cosineRotor\n                elif fit =='fourier':\n                    rotor=fourierRotor\n                elif fit =='best':\n                \n                    rms_cosine = numpy.sqrt(numpy.sum((Vlist_cosine - Vlist) * (Vlist_cosine - Vlist)) / (len(Vlist) - 1)) / 4184.\n                    rms_fourier = numpy.sqrt(numpy.sum((Vlist_fourier - Vlist) * (Vlist_fourier - Vlist))/ (len(Vlist) - 1)) / 4184.\n                \n                    # Keep the rotor with the most accurate potential\n                    rotor = cosineRotor if rms_cosine < rms_fourier else fourierRotor\n                    # However, keep the cosine rotor if it is accurate enough, the\n                    # fourier rotor is not significantly more accurate, and the cosine\n                    # rotor has the correct symmetry \n                    if rms_cosine < 0.05 and rms_cosine / rms_fourier < 2.0 and rms_cosine / rms_fourier < 4.0 and symmetry == cosineRotor.symmetry:\n                        rotor = cosineRotor\n                    \n                    conformer.modes.append(rotor)\n                    \n                    self.plotHinderedRotor(angle, Vlist, cosineRotor, fourierRotor, rotor, rotorCount, directory)\n                    \n                    rotorCount += 1\n                       \n            logging.debug('    Determining frequencies from reduced force constant matrix...')\n            frequencies = numpy.array(projectRotors(conformer, F, rotors, linear, TS))\n            \n        elif len(conformer.modes) > 2:\n            frequencies = conformer.modes[2].frequencies.value_si\n            rotors = numpy.array([])\n        else:\n            frequencies = numpy.array([])\n            rotors = numpy.array([])\n    \n        for mode in conformer.modes:\n            if isinstance(mode, HarmonicOscillator):\n                mode.frequencies = (frequencies * self.frequencyScaleFactor,\"cm^-1\")\n                \n        self.species.conformer = conformer\n    \n    def save(self, outputFile):\n        \"\"\"\n        Save the results of the statistical mechanics job to the file located\n        at `path` on disk.\n        \"\"\"\n        \n        logging.info('Saving statistical mechanics parameters for {0}...'.format(self.species.label))\n        f = open(outputFile, 'a')\n    \n        numbers = {1: 'H', 6: 'C', 7: 'N', 8: 'O', 14: 'Si', 15: 'P', 16: 'S', 17: 'Cl'}\n        \n        conformer = self.species.conformer\n            \n        coordinates = conformer.coordinates.value_si * 1e10\n        number = conformer.number.value_si\n        \n        f.write('# Coordinates for {0} (angstroms):\\n'.format(self.species.label))\n        for i in range(coordinates.shape[0]):\n            x = coordinates[i,0] - coordinates[0,0]\n            y = coordinates[i,1] - coordinates[0,1]\n            z = coordinates[i,2] - coordinates[0,2]\n            f.write('#   {0} {1:9.4f} {2:9.4f} {3:9.4f}\\n'.format(numbers[number[i]], x, y, z))\n        \n        string = 'conformer(label={0!r}, E0={1!r}, modes={2!r}, spinMultiplicity={3:d}, opticalIsomers={4:d}'.format(\n            self.species.label, \n            conformer.E0,\n            conformer.modes,\n            conformer.spinMultiplicity,\n            conformer.opticalIsomers,\n        )\n        try:\n            string += ', frequency={0!r}'.format(self.species.frequency)\n        except AttributeError: pass\n        string += ')'\n        \n        f.write('{0}\\n\\n'.format(prettify(string)))\n        \n        f.close()\n\n    def plotHinderedRotor(self, angle, Vlist, cosineRotor, fourierRotor, rotor, rotorIndex, directory):\n        \"\"\"\n        Plot the potential for the rotor, along with its cosine and Fourier\n        series potential fits. The plot is saved to a set of files of the form\n        ``hindered_rotor_1.pdf``.\n        \"\"\"\n        try:\n            import pylab\n        except ImportError:\n            return\n        \n        phi = numpy.arange(0, 6.3, 0.02, numpy.float64)\n        Vlist_cosine = numpy.zeros_like(phi)\n        Vlist_fourier = numpy.zeros_like(phi)\n        for i in range(phi.shape[0]):\n            Vlist_cosine[i] = cosineRotor.getPotential(phi[i])\n            Vlist_fourier[i] = fourierRotor.getPotential(phi[i])\n        \n        fig = pylab.figure(figsize=(6,5))\n        pylab.plot(angle, Vlist / 4184., 'ok')\n        linespec = '-r' if rotor is cosineRotor else '--r'\n        pylab.plot(phi, Vlist_cosine / 4184., linespec)\n        linespec = '-b' if rotor is fourierRotor else '--b'\n        pylab.plot(phi, Vlist_fourier / 4184., linespec)\n        pylab.legend(['scan', 'cosine', 'fourier'], loc=1)\n        pylab.xlim(0, 2*constants.pi)\n        pylab.xlabel('Angle')\n        pylab.ylabel('Potential (kcal/mol)')\n        pylab.title('{0} hindered rotor #{1:d}'.format(self.species.label, rotorIndex+1))\n        \n        axes = fig.get_axes()[0]\n        axes.set_xticks([float(j*constants.pi/4) for j in range(0,9)])\n        axes.set_xticks([float(j*constants.pi/8) for j in range(0,17)], minor=True)\n        axes.set_xticklabels(['$0$', '$\\pi/4$', '$\\pi/2$', '$3\\pi/4$', '$\\pi$', '$5\\pi/4$', '$3\\pi/2$', '$7\\pi/4$', '$2\\pi$'])\n        \n        pylab.savefig(os.path.join(directory, '{0}_rotor_{1:d}.pdf'.format(self.species.label, rotorIndex+1)))\n        pylab.close()\n\n################################################################################\n\ndef applyEnergyCorrections(E0, modelChemistry, atoms, bonds):\n    \"\"\"\n    Given an energy `E0` in J/mol as read from the output of a quantum chemistry\n    calculation at a given `modelChemistry`, adjust the energy such that it\n    is consistent with the normal gas-phase reference states. `atoms` is a\n    dictionary associating element symbols with the number of that element in\n    the molecule. `bonds` is a dictionary associating bond types with the number\n    of that bond in the molecule.\n    \"\"\"\n    \n    # Spin orbit correction (SOC) in Hartrees\n    # Values taken from note 22 of http://jcp.aip.org/resource/1/jcpsa6/v109/i24/p10570_s1 and converted to hartrees\n    # Values in millihartree are also available (with fewer significant figures) from http://jcp.aip.org/resource/1/jcpsa6/v106/i3/p1063_s1\n    SOC = {'H':0.0, 'N':0.0, 'O': -0.000355, 'C': -0.000135, 'S':  -0.000893, 'P': 0.0, 'Cl': -0.001338} \n    \n    # Step 1: Reference all energies to a model chemistry-independent basis\n    # by subtracting out that model chemistry's atomic energies\n    # Note: If your model chemistry does not include spin orbit coupling, you should add the corrections to the energies here\n    if modelChemistry == 'CBS-QB3':\n        # 0K Energy\n        atomEnergies = {'H':-0.499818 , 'N':-54.520543, 'O':-74.987624, 'C':-37.785385, 'P':-340.817186, 'S': -397.657360, 'Cl': -459.683605}\n    elif modelChemistry == 'G3':\n        atomEnergies = {'H':-0.5010030, 'N':-54.564343, 'O':-75.030991, 'C':-37.827717, 'P':-341.116432, 'S': -397.961110}\n\n    elif modelChemistry == 'Klip_1':\n        atomEnergies = {'H':-0.50003976 + SOC['H'], 'N':-54.53383153 + SOC['N'], 'O':-75.00935474 + SOC['O'], 'C':-37.79266591 + SOC['C']}\n    elif modelChemistry == 'Klip_2':\n        #Klip QCI(tz,qz)\n        atomEnergies = {'H':-0.50003976 + SOC['H'], 'N':-54.53169400 + SOC['N'], 'O':-75.00714902 + SOC['O'], 'C':-37.79060419 + SOC['C']}\n    elif modelChemistry == 'Klip_3':\n        #Klip QCI(dz,tz)\n        atomEnergies = {'H':-0.50005578 + SOC['H'], 'N':-54.53128140 + SOC['N'], 'O':-75.00356581 + SOC['O'], 'C':-37.79025175 + SOC['C']}\n\n    elif modelChemistry == 'Klip_2_cc':\n        #Klip CCSD(T)(tz,qz)\n        atomEnergies = {'H':-0.50003976 + SOC['H'], 'O':-75.00681155 + SOC['O'], 'C':-37.79029443 + SOC['C']}\n\n    elif modelChemistry == 'CCSD(T)-F12/cc-pVDZ-F12_H-TZ':\n        atomEnergies = {'H':-0.499946213243 + SOC['H'], 'N':-54.526406291655 + SOC['N'], 'O':-74.995458316117 + SOC['O'], 'C':-37.788203485235 + SOC['C']}\n    elif modelChemistry == 'CCSD(T)-F12/cc-pVDZ-F12_H-QZ':\n        atomEnergies = {'H':-0.499994558325 + SOC['H'], 'N':-54.526406291655 + SOC['N'], 'O':-74.995458316117 + SOC['O'], 'C':-37.788203485235 + SOC['C']}\n\n    elif modelChemistry == 'CCSD(T)-F12/cc-pVDZ-F12':\n        atomEnergies = {'H':-0.499811124128 + SOC['H'], 'N':-54.526406291655 + SOC['N'], 'O':-74.995458316117 + SOC['O'], 'C':-37.788203485235 + SOC['C']}\n    elif modelChemistry == 'CCSD(T)-F12/cc-pVTZ-F12':\n        atomEnergies = {'H':-0.499946213243 + SOC['H'], 'N':-54.53000909621 + SOC['N'], 'O':-75.004127673424 + SOC['O'], 'C':-37.789862146471 + SOC['C']}\n    elif modelChemistry == 'CCSD(T)-F12/cc-pVQZ-F12':\n        atomEnergies = {'H':-0.499994558325 + SOC['H'], 'N':-54.530515226371 + SOC['N'], 'O':-75.005600062003 + SOC['O'], 'C':-37.789961656228 + SOC['C']}\n        \n    elif modelChemistry == 'CCSD(T)-F12/cc-pCVDZ-F12':\n        atomEnergies = {'H':-0.499811124128 + SOC['H'], 'N':-54.582137180344 + SOC['N'], 'O':-75.053045547421 + SOC['O'], 'C':-37.840869118707 + SOC['C']}\n    elif modelChemistry == 'CCSD(T)-F12/cc-pCVTZ-F12':\n        atomEnergies = {'H':-0.499946213243 + SOC['H'], 'N':-54.588545831900 + SOC['N'], 'O':-75.065995072347 + SOC['O'], 'C':-37.844662139972 + SOC['C']}\n    elif modelChemistry == 'CCSD(T)-F12/cc-pCVQZ-F12':\n        atomEnergies = {'H':-0.499994558325 + SOC['H'], 'N':-54.589137594139 + SOC['N'], 'O':-75.067412234737 + SOC['O'], 'C':-37.844893820561 + SOC['C']}\n\n    elif modelChemistry == 'CCSD(T)-F12/aug-cc-pVDZ':\n        atomEnergies = {'H':-0.499459066131 + SOC['H'], 'N':-54.524279516472 + SOC['N'], 'O':-74.992097308083 + SOC['O'], 'C':-37.786694171716 + SOC['C']}\n    elif modelChemistry == 'CCSD(T)-F12/aug-cc-pVTZ':\n        atomEnergies = {'H':-0.499844820798 + SOC['H'], 'N':-54.527419359906 + SOC['N'], 'O':-75.000001429806 + SOC['O'], 'C':-37.788504810868 + SOC['C']}\n    elif modelChemistry == 'CCSD(T)-F12/aug-cc-pVQZ':\n        atomEnergies = {'H':-0.499949526073 + SOC['H'], 'N':-54.529569719016 + SOC['N'], 'O':-75.004026586610 + SOC['O'], 'C':-37.789387892348 + SOC['C']}\n\n\n    elif modelChemistry == 'B-CCSD(T)-F12/cc-pVDZ-F12':\n        atomEnergies = {'H':-0.499811124128 + SOC['H'], 'N':-54.523269942190 + SOC['N'], 'O':-74.990725918500 + SOC['O'], 'C':-37.785409916465 + SOC['C']}\n    elif modelChemistry == 'B-CCSD(T)-F12/cc-pVTZ-F12':\n        atomEnergies = {'H':-0.499946213243 + SOC['H'], 'N':-54.528135889213 + SOC['N'], 'O':-75.001094055506 + SOC['O'], 'C':-37.788233578503 + SOC['C']}\n    elif modelChemistry == 'B-CCSD(T)-F12/cc-pVQZ-F12':\n        atomEnergies = {'H':-0.499994558325 + SOC['H'], 'N':-54.529425753163 + SOC['N'], 'O':-75.003820485005 + SOC['O'], 'C':-37.789006506290 + SOC['C']}\n        \n    elif modelChemistry == 'B-CCSD(T)-F12/cc-pCVDZ-F12':\n        atomEnergies = {'H':-0.499811124128 + SOC['H'], 'N':-54.578602780288 + SOC['N'], 'O':-75.048064317367 + SOC['O'], 'C':-37.837592033417 + SOC['C']}\n    elif modelChemistry == 'B-CCSD(T)-F12/cc-pCVTZ-F12':\n        atomEnergies = {'H':-0.499946213243 + SOC['H'], 'N':-54.586402551258 + SOC['N'], 'O':-75.062767632757 + SOC['O'], 'C':-37.842729156944 + SOC['C']}\n    elif modelChemistry == 'B-CCSD(T)-F12/cc-pCVQZ-F12':\n        atomEnergies = {'H':-0.49999456 + SOC['H'], 'N':-54.587781507581 + SOC['N'], 'O':-75.065397706471 + SOC['O'], 'C':-37.843634971592 + SOC['C']}\n\n    elif modelChemistry == 'B-CCSD(T)-F12/aug-cc-pVDZ':\n        atomEnergies = {'H':-0.499459066131 + SOC['H'], 'N':-54.520475581942 + SOC['N'], 'O':-74.986992215049 + SOC['O'], 'C':-37.783294495799 + SOC['C']}\n    elif modelChemistry == 'B-CCSD(T)-F12/aug-cc-pVTZ':\n        atomEnergies = {'H':-0.499844820798 + SOC['H'], 'N':-54.524927371700 + SOC['N'], 'O':-74.996328829705 + SOC['O'], 'C':-37.786320700792 + SOC['C']}\n    elif modelChemistry == 'B-CCSD(T)-F12/aug-cc-pVQZ':\n        atomEnergies = {'H':-0.499949526073 + SOC['H'], 'N':-54.528189769291 + SOC['N'], 'O':-75.001879610563 + SOC['O'], 'C':-37.788165047059 + SOC['C']}\n\n\n    elif modelChemistry == 'DFT_ks_b3lyp':\n        atomEnergies = {'H':-0.49785866 + SOC['H'], 'N':-54.45608798 + SOC['N'], 'O':-74.93566254 + SOC['O'], 'C':-37.76119132 + SOC['C']}\n    elif modelChemistry == 'DFT_uks_b3lyp':\n        atomEnergies = {'H':-0.49785866 + SOC['H'], 'N':-54.45729113 + SOC['N'], 'O':-74.93566254 + SOC['O'], 'C':-37.76119132 + SOC['C']}\n\n    elif modelChemistry == 'MP2_rmp2_pVDZ':\n        atomEnergies = {'H':-0.49927840 + SOC['H'], 'N':-54.46141996 + SOC['N'], 'O':-74.89408254 + SOC['O'], 'C':-37.73792713 + SOC['C']}\n    elif modelChemistry == 'MP2_rmp2_pVTZ':\n        atomEnergies = {'H':-0.49980981 + SOC['H'], 'N':-54.49615972 + SOC['N'], 'O':-74.95506980 + SOC['O'], 'C':-37.75833104 + SOC['C']}\n    elif modelChemistry == 'MP2_rmp2_pVQZ':\n        atomEnergies = {'H':-0.49994557 + SOC['H'], 'N':-54.50715868 + SOC['N'], 'O':-74.97515364 + SOC['O'], 'C':-37.76533215 + SOC['C']}\n\n    elif modelChemistry == 'CCSD_DZ':\n        atomEnergies = {'H':-0.499811124 + SOC['H'], 'N':-54.52640629 + SOC['N'], 'O':-74.99545832 + SOC['O'], 'C':-37.78820349 + SOC['C']}\n    elif modelChemistry == 'CCSD_TZ':\n        atomEnergies = {'H':-0.499946213 + SOC['H'], 'N':-54.5300091 + SOC['N'], 'O':-75.00412767 + SOC['O'], 'C':-37.78986215 + SOC['C']}\n    elif modelChemistry == 'CCSD_QZ':\n        atomEnergies = {'H':-0.499994558 + SOC['H'], 'N':-54.53051523 + SOC['N'], 'O':-75.00560006 + SOC['O'], 'C':-37.78996166 + SOC['C']}\n    elif modelChemistry == 'CCSD_core_DZ':\n        atomEnergies = {'H':-0.499811124 + SOC['H'], 'N':-54.58213718 + SOC['N'], 'O':-75.05304555 + SOC['O'], 'C':-37.84086912 + SOC['C']}\n    elif modelChemistry == 'BMK/cbsb7':\n        atomEnergies = {'H':-0.498618853119+ SOC['H'], 'N':-54.5697851544+ SOC['N'], 'O':-75.0515210278+ SOC['O'], 'C':-37.8287310027+ SOC['C'], 'P':-341.167615941+ SOC['P'], 'S': -398.001619915+ SOC['S']}\n        \n        \n    else:\n        logging.warning('Unknown model chemistry \"{0}\"; not applying energy corrections.'.format(modelChemistry))\n        return E0\n    for symbol, count in atoms.items():\n        if symbol in atomEnergies: E0 -= count * atomEnergies[symbol] * constants.E_h * constants.Na\n        else:\n            logging.warning('Ignored unknown atom type \"{0}\".'.format(symbol))\n    \n    # Step 2: Atom energy corrections to reach gas-phase reference state\n    # Experimental enthalpy of formation at 0 K \n    # See Gaussian thermo whitepaper at http://www.gaussian.com/g_whitepap/thermo.htm)\n    # Note: these values are relatively old and some improvement may be possible by using newer values, particularly for carbon\n    # However, care should be taken to ensure that they are compatible with the BAC values (if BACs are used)\n    atomHf = {'H': 51.63 , 'N': 112.53 ,'O': 58.99 ,'C': 169.98, 'S': 65.66, 'Cl': 28.59 }\n    # Thermal contribution to enthalpy Hss(298 K) - Hss(0 K) reported by Gaussian thermo whitepaper\n    # This will be subtracted from the corresponding value in atomHf to produce an enthalpy used in calculating the enthalpy of formation at 298 K\n    atomThermal = {'H': 1.01 , 'N': 1.04, 'O': 1.04 ,'C': 0.25, 'S': 1.05, 'Cl': 1.10 }\n    # Total energy correction used to reach gas-phase reference state\n    # Note: Spin orbit coupling no longer included in these energies, since some model chemistries include it automatically\n    atomEnergies = {}\n    for element in atomHf:\n        atomEnergies[element] = atomHf[element] - atomThermal[element]\n    for symbol, count in atoms.items():\n        if symbol in atomEnergies: E0 += count * atomEnergies[symbol] * 4184.\n    \n    # Step 3: Bond additivity corrections\n    if modelChemistry == 'CCSD(T)-F12/cc-pVDZ-F12':\n        bondEnergies = { 'C-H': -0.56, 'C-C': -0.53, 'C=C': -1.90, 'C#C': -0.64,\n            'O-H': -0.34, 'C-O': -0.30, 'C=O': -0.92, 'O-O': 0.03, 'N-C': -0.49,\n            'N=C': -1.50, 'N#C': -3.54, 'N-O': 0.60, 'N_O': -0.17, 'N=O': -0.72,\n            'N-H': -0.75, 'N-N': -1.45, 'N=N': -1.98, 'N#N': -2.05,}\n    else:\n        # BAC corrections from Table IX in http://jcp.aip.org/resource/1/jcpsa6/v109/i24/p10570_s1 for CBS-Q method\n        # H-Cl correction from CBS-QB3 enthalpy difference with Gurvich 1989, HF298=-92.31 kJ\n        bondEnergies = { 'C-H': -0.11, 'C-C': -0.3, 'C=C': -0.08, 'C#C': -0.64,\n            'O-H': 0.02, 'C-O': 0.33, 'C=O': 0.55, 'N#N': -2.0, 'O=O': -0.2, \n            'H-H': 1.1, 'C#N': -0.89, 'C-S': 0.43, 'S=O': -0.78, 'C-Cl': 1.29,\n            'N-H': -0.42, 'C-N': -0.13, 'S-H': 0.00, 'H-Cl': 1.16 }\n\n    for symbol, count in bonds.items():\n        if symbol in bondEnergies: E0 += count * bondEnergies[symbol] * 4184.\n        else:\n            logging.warning('Ignored unknown bond type {0!r}.'.format(symbol))\n    \n    return E0\n\ndef projectRotors(conformer, F, rotors, linear, TS):\n    \"\"\"\n    For a given `conformer` with associated force constant matrix `F`, lists of\n    rotor information `rotors`, `pivots`, and `top1`, and the linearity of the\n    molecule `linear`, project out the nonvibrational modes from the force\n    constant matrix and use this to determine the vibrational frequencies. The\n    list of vibrational frequencies is returned in cm^-1.\n    \"\"\"\n    \n    Nrotors = len(rotors)\n    Natoms = len(conformer.mass.value)\n    Nvib = 3 * Natoms - (5 if linear else 6) - Nrotors - (1 if (TS) else 0)\n    mass = conformer.mass.value_si\n    coordinates = conformer.coordinates.value_si\n    \n    if linear:\n        D = numpy.zeros((Natoms*3,5+Nrotors), numpy.float64)\n    else:\n        D = numpy.zeros((Natoms*3,6+Nrotors), numpy.float64)\n\n    for i in range(Natoms):\n        # Projection vectors for translation\n        D[3*i+0,0] = 1.0\n        D[3*i+1,1] = 1.0\n        D[3*i+2,2] = 1.0\n        # Projection vectors for [external] rotation\n        D[3*i:3*i+3,3] = numpy.array([0, -coordinates[i,2], coordinates[i,1]], numpy.float64)\n        D[3*i:3*i+3,4] = numpy.array([coordinates[i,2], 0, -coordinates[i,0]], numpy.float64)\n        if not linear:\n            D[3*i:3*i+3,5] = numpy.array([-coordinates[i,1], coordinates[i,0], 0], numpy.float64)\n    for i, rotor in enumerate(rotors):\n        scanLog, pivots, top, symmetry, fit = rotor\n        # Determine pivot atom\n        if pivots[0] in top: pivot = pivots[0]\n        elif pivots[1] in top: pivot = pivots[1]\n        else: raise Exception('Could not determine pivot atom.')\n        # Projection vectors for internal rotation\n        e12 = coordinates[pivots[0]-1,:] - coordinates[pivots[1]-1,:]\n        e12 /= numpy.linalg.norm(e12)\n        for atom in top:\n            e31 = coordinates[atom-1,:] - coordinates[pivot-1,:]\n            D[3*(atom-1):3*(atom-1)+3,-Nrotors+i] = numpy.cross(e31, e12)\n\n    # Make sure projection matrix is orthonormal\n    import scipy.linalg\n    D = scipy.linalg.orth(D)\n\n    # Project out the non-vibrational modes from the force constant matrix\n    P = numpy.dot(D, D.transpose())\n    I = numpy.identity(Natoms*3, numpy.float64)\n    F = numpy.dot(I - P, numpy.dot(F, I - P))\n\n    # Generate mass-weighted force constant matrix\n    # This converts the axes to mass-weighted Cartesian axes\n    # Units of Fm are J/m^2*kg = 1/s^2\n    Fm = F.copy()\n    for i in range(Natoms):\n        for j in range(Natoms):\n            for u in range(3):\n                for v in range(3):\n                    Fm[3*i+u,3*j+v] /= math.sqrt(mass[i] * mass[j])\n\n    # Get eigenvalues of mass-weighted force constant matrix\n    eig, V = numpy.linalg.eigh(Fm)\n    eig.sort()\n\n    # Convert eigenvalues to vibrational frequencies in cm^-1\n    # Only keep the modes that don't correspond to translation, rotation, or internal rotation\n    return numpy.sqrt(eig[-Nvib:]) / (2 * math.pi * constants.c * 100)\n", "meta": {"hexsha": "7cc125f20b2ff504d3bcd8637a84a57f9b16bda4", "size": 34119, "ext": "py", "lang": "Python", "max_stars_repo_path": "rmgpy/cantherm/statmech.py", "max_stars_repo_name": "vrlambert/RMG-Py", "max_stars_repo_head_hexsha": "0937b2e0a955dcf21b79674a4e89f43941c0dd85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-15T10:30:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T10:30:48.000Z", "max_issues_repo_path": "rmgpy/cantherm/statmech.py", "max_issues_repo_name": "vrlambert/RMG-Py", "max_issues_repo_head_hexsha": "0937b2e0a955dcf21b79674a4e89f43941c0dd85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rmgpy/cantherm/statmech.py", "max_forks_repo_name": "vrlambert/RMG-Py", "max_forks_repo_head_hexsha": "0937b2e0a955dcf21b79674a4e89f43941c0dd85", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-02-22T01:16:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-22T01:16:13.000Z", "avg_line_length": 49.0920863309, "max_line_length": 205, "alphanum_fraction": 0.5805855975, "include": true, "reason": "import numpy,import scipy", "num_tokens": 9646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.1898585785706167}}
{"text": "#!/usr/bin/env python\n#\n\n\"\"\" Library containing field information \"\"\"\nimport os, sys\nimport pandas\nimport numpy as np\nimport warnings\nfrom pandas import read_csv\nfrom astropy import units, coordinates, time\nimport matplotlib.pyplot as mpl\nfrom matplotlib.patches import Polygon\n\n\n\n\n_FIELD_SOURCE = os.path.dirname(os.path.realpath(__file__))+\"/data/ztf_fields.txt\"\nFIELD_DATAFRAME = read_csv(_FIELD_SOURCE, index_col=\"ID\")\nFIELDSNAMES = FIELD_DATAFRAME.index.values\n\n_CCD_COORDS  = read_csv(os.path.dirname(os.path.realpath(__file__))+\"/data/ztf_ccd_layout.tbl\").rename(columns={\"CCD \":\"CCD\"}) # corner of each CCDS\n\nFIELD_COLOR = {1: \"C2\", 2: \"C3\", 3:\"C1\"}\nFIELD_CMAP = {1: mpl.cm.Greens, 2:mpl.cm.Reds, 3:mpl.cm.Oranges}\nFIELDNAME_COLOR = {\"zg\": \"C2\", \"zr\":\"C3\", \"zi\":\"C1\"}\n\n_PLOTORIGIN = 180\n\ndef _load_fields_geoserie_(inclccd=False):\n    \"\"\" Loads the FIELDS_GEOSERIE global variable \n    = Internal Tools =\n    \"\"\"\n    if not inclccd:\n        global FIELDS_GEOSERIE\n    else:\n        global FIELD_CCDS_GEOSERIE\n    \n    try:\n        from geopandas import geoseries\n    except ImportError:\n        warnings.warn(\"You do not have geopandas, Please run pip install geopandas.\")\n        if not inclccd:\n            FIELDS_GEOSERIE = None\n        else:\n            FIELD_CCDS_GEOSERIE = None \n        return\n    \n    field_verts = get_field_vertices(fieldid=FIELDSNAMES, inclccd=inclccd, asdict=True, aspolygon=True)\n    if not inclccd:\n        FIELDS_GEOSERIE = geoseries.GeoSeries(field_verts)\n    else:\n        FIELD_CCDS_GEOSERIE = geoseries.GeoSeries(field_verts)\n\n    \ndef get_fields_geoserie(inclccd=False):\n    \"\"\" returns the global variable FIELDS_GEOSERIE, creates it if necessary \"\"\"\n    if not inclccd:\n        if not hasattr(sys.modules[__name__], 'FIELDS_GEOSERIE'):\n            _load_fields_geoserie_(inclccd=False)\n        \n        return FIELDS_GEOSERIE\n    else:\n        if not hasattr(sys.modules[__name__], 'FIELD_CCDS_GEOSERIE'):\n            _load_fields_geoserie_(inclccd=True)\n        \n        return FIELD_CCDS_GEOSERIE\n\n# ------------------ #\n#                    #\n# Generic Tools      #\n#                    #\n# ------------------ #\ndef get_fieldid(grid=None, decrange=None, rarange=None, \n                gallrange=None, galbrange=None, \n                ecllrange=None, eclbrange=None, \n                ebvrange=None, verbose=False):\n                \n    \"\"\" \n\n    Parameters\n    ----------\n    grid: [None/str] -optional-\n        Select the grid you want. If None the both will be considered.\n        'main' or 'secondary' expected otherwise.\n\n    decrange, rarange, galbrange, gallrange, ecllgrange, eclbrange: [2-array or None] -optional-\n        dec, ra, galactic l, galactic b, ecliptic long and ecliptic lat to be considered [inclusive]. \n        In degree.\n        3 formats available:\n        - None: means no selection\n        - [min,max]: means range to be considered, None means no limit. \n          example: decrange=[-10,None] means dec>-10.\n        - [[min1,max1],[min2,max2], ...]: means zones to be considered.\n          example: decrange=[[None, -10],[5,None]] will simply exclude the [-10,5] dec range.\n        - None means no selection.\n\n    ebvrange: [2-array or None] -optional-\n        same format as 'decrange' but for Mily way E(B-V) extinction.\n        \n    \"\"\"\n    def get_query(key, krange=None, merging_logic=\"or\"):\n        \"\"\" \"\"\"\n        def _build_2d_(kmin,kmax):\n            \"\"\" \"\"\"\n            if kmin is None and kmax is None:\n                return []\n            if kmin is None:\n                return [f\"{key}<={kmax}\"]\n            elif kmax is None:\n                return [f\"{key}>={kmin}\"]\n            else:\n                return [f\"{kmin}<={key}<={kmax}\"]\n        \n        if krange is None:\n            return []\n        if np.shape(krange) == (2,):\n            return _build_2d_(*krange)\n        if np.shape(krange) == (2,2):\n            query = [_build_2d_(*krange_) for krange_ in krange]\n            return [\"(\"+f\" {merging_logic} \".join(np.squeeze(query))+\")\"]\n        \n        raise ValueError(f\"Cannot for the format of the input krange: {krange}\")\n\n    query = []\n    # Grid\n    gridid = None if (grid is None or grid in [\"*\",\"all\"]) else get_grid_field(grid)\n    query.append([] if gridid is None else [\"ID in @gridid\"])\n    # Ra\n    \n    query.append(get_query(\"RA\", rarange))\n    # Dec\n    query.append(get_query(\"Dec\", decrange))\n    # gall\n    query.append(get_query(\"GalLong\", gallrange))\n    # galb\n    query.append(get_query(\"GalLat\", galbrange))\n    # ecll\n    query.append(get_query(\"EclLong\", ecllrange))\n    # eclb\n    query.append(get_query(\"EclLat\", eclbrange))\n    # MW ebmv\n    query.append(get_query(\"Ebv\", ebvrange))\n    \n    \n    queries = np.concatenate(query)\n    if verbose:\n        print(queries)\n    if len(queries) == 0:\n        return FIELD_DATAFRAME.index\n    if verbose:\n        print(\" & \".join(queries) ) \n    return FIELD_DATAFRAME.query( \" & \".join(queries) ).index\n\n\ndef get_field_ccd_qid(ra, dec):\n    \"\"\" \"\"\"\n    d_ = {}\n    field_ccds = get_fields_containing_target(ra,dec, inclccd=True)\n    for field_ccd in field_ccds:\n        (ramin,decmin),(ramax,decmax) = np.percentile(np.asarray(FIELD_CCDS_GEOSERIE[field_ccd].exterior.xy).T, [0,100], axis=0)\n        ccdpos=np.asarray([(ra-ramin)/(ramax-ramin)*6144,(dec-decmin)/(decmax-decmin)*6160])\n        qid = ccdpos_to_qid(*ccdpos)\n        field, ccd = field_ccd.split(\"_\")\n        d_[int(field)] = {\"ccd\":int(ccd), \"qid\":int(qid), \"rcid\":ccdid_qid_to_rcid(int(ccd), int(qid))}\n        \n    return d_\n    \ndef get_fields_containing_target(ra, dec, inclccd=False, buffer=None):\n    \"\"\" return the list of fields into which the position ra, dec is. \n    Remark that this is based on predefined field positions. \n    Hence, small attrition could affect this.\n\n    Parameters\n    ----------\n    ra,dec: [float,float]\n       coordinates in degree. \n    \n    inclccd: [bool] -optional-\n        do you want the details of the CCD id on top of the field\n        format: \"field_ccdid\"\n\n    buffer: [float] -optional-\n        buffer the polygon (fields or ccds). \n        In degree (unit of the polygons). The inter-ccd gap typically is 0.3 deg\n\n    Returns\n    -------\n    list (all the field ID that contain the given ra,dec coordinates)\n    \"\"\"\n    try:\n        from shapely import geometry\n    except ImportError:\n        raise ImportError(\"You need shapely to use this function. pip install shapely\")\n    \n    \n    coordpoint = geometry.Point(ra, dec)\n    fields_geoserie = get_fields_geoserie(inclccd=inclccd)\n    if fields_geoserie is None:\n        warnings.warn(\"get_fields_containing_target would be much faster if you install geopandas (pip install geopandas)\")\n        return [f for f in FIELDSNAMES\n                if geometry.Polygon( get_field_vertices(f)[0]).contains(coordpoint)]\n    if buffer is None:\n        return fields_geoserie.index[ fields_geoserie.contains(coordpoint) ]\n    return fields_geoserie.index[ fields_geoserie.buffer(buffer).contains(coordpoint) ]\n\n\ndef get_field_vertices(fieldid=None, inclccd=False, ccd=None, asdict=False, aspolygon=False,\n                        squeeze=True):\n    \"\"\" Get the fields countours \n    \n    Parameters\n    ----------\n    fieldid: [string or list of] -optional-\n        Field (or list of) names as int. \n        If None, all the fields will be used.\n\n    // output format\n\n    asdict: [bool] -optional-\n        Do you want to result as a list (asdict=False) following the input's fieldid sorting\n        or do you want a dict ({fieldid_: verts_ ... })\n\n    aspolygon: [bool] -optional-\n        Do you want the vertices as 2d-array (aspolygon=False) or as shapely Geometries (True)\n\n    squeeze: [bool] -optional-\n        Should unnecessary dimension be removed ?\n        if asdict is True:\n            if squeeze: {fid_ccdid: }\n            if not squeeze: {fid:{ccdid: }}\n            = if not inclccd, squeez ignored =\n        if not asdict:\n           using np.squeeze, basically doing [[]]->[]\n    Returns\n    -------\n    list of dict (see asdict)\n    \"\"\"\n    if fieldid is None:\n        fieldid = FIELDSNAMES\n        \n    if inclccd and ccd is None:\n        ccd = np.arange(1,17)\n\n    # - Actual calculation\n    rafields, decfields  = get_field_centroid( np.asarray(np.atleast_1d(fieldid), dtype=\"int\") ).T\n    fields_verts = get_corners(rafields, decfields, inclccd=inclccd, ccd=ccd,\n                                       inrad=False, squeeze=False)\n\n    # ----------- #\n    #  Format     #\n    # ----------- #    \n    if aspolygon:\n        try:\n            from shapely import geometry\n            fields_countours = [[geometry.Polygon(fields_verts[f_][c_])\n                                         for c_,ccd_ in enumerate(np.atleast_1d(ccd))]\n                                         for f_,field_ in enumerate(np.atleast_1d(fieldid))]\n        except ImportError:\n            warnings.warn(\"You do not have shapely, Please run pip install shapely. 'aspolygon' set to False\")\n    else:\n        fields_countours = fields_verts\n\n    # ----------- #\n    #  Output     #\n    # ----------- #    \n    if not asdict:\n        return fields_countours if not squeeze else np.squeeze(fields_countours)\n\n    # full camera dict\n    if not inclccd:\n        return {i:k[0] for i,k in zip(fieldid,fields_countours)}\n    \n    # ccd dict\n    if squeeze:\n        return {f\"{field_}_{ccd_}\":fields_countours[f_][c_]\n                    for c_,ccd_ in enumerate(np.atleast_1d(ccd)) for f_,field_ in enumerate(np.atleast_1d(fieldid))}\n    else:\n        return {field_:{ccd_:fields_countours[f_][c_] for c_,ccd_ in enumerate(np.atleast_1d(ccd))}\n                    for f_,field_ in enumerate(np.atleast_1d(fieldid))}\n\ndef get_field_centroid(fieldid, system=\"radec\"):\n    \"\"\" Returns the central coordinate [RA,Dec] or  of the given field \n\n    Parameters\n    ----------\n    fieldid: [int]\n        single field ID\n\n    system: [string] -optional-\n        which coordinate system ?\n        radec / galactic / ecliptic (default radec)\n\n    Returns\n    -------\n    [[x_i, y_i],[]]... (depending on your coordinate system)\n    Remark if only 1 fieldid given, you have [[x,y]] (not [x,y])\n    \"\"\"\n    if system in [\"radec\", \"RADec\",\"RA,Dec\", \"ra,dec\"]:\n        syst = [\"RA\", \"Dec\"]\n    elif system.lower() in [\"gal\",\"galactic\"]:\n        syst = [\"Gal Long\",\"Gal Lat\"]\n    elif system.lower() in [\"ecl\",\"ecliptic\"]:\n        syst = [\"Ecl Long\",\"Ecl Lat\"]\n    else:\n        raise ValueError(\"unknown coordinate system %s select among: [radec / galactic / ecliptic]\"%system)\n    fieldid = np.atleast_1d(fieldid)\n    radec = np.asarray(FIELD_DATAFRAME[np.in1d(FIELD_DATAFRAME.index, fieldid)][syst].values)\n    \n    return radec\n\ndef get_corners(ra_field, dec_field, inclccd=False, ccd=None, steps=5, squeeze=True, inrad=False):\n    \"\"\" \"\"\"\n    from .utils.tools import rot_xz_sph, _DEG2RA\n    \n    if not inclccd:\n        upper_left_corner = _CCD_COORDS.max()\n        lower_right_corner = _CCD_COORDS.min()\n    elif ccd is None:\n        upper_left_corner = _CCD_COORDS.groupby(\"CCD\").max()\n        lower_right_corner = _CCD_COORDS.groupby(\"CCD\").min()\n    else:\n        upper_left_corner = _CCD_COORDS.groupby(\"CCD\").max().loc[ccd]\n        lower_right_corner = _CCD_COORDS.groupby(\"CCD\").min().loc[ccd]\n        \n    ewmin = -np.atleast_1d(upper_left_corner[\"EW\"])\n    nsmax = np.atleast_1d(upper_left_corner[\"NS\"])\n    ewmax = -np.atleast_1d(lower_right_corner[\"EW\"])\n    nsmin = np.atleast_1d(lower_right_corner[\"NS\"])\n\n    ra1  = (np.linspace(ewmax, ewmin, steps)/np.cos(nsmax*_DEG2RA)).T\n    dec1 = (np.ones((steps,1))*nsmax).T\n    #\n    dec2  = np.linspace(nsmax,nsmin, steps).T\n    ra2   = ewmin[:,None]/np.cos(dec2*_DEG2RA)\n    #\n    ra3 = (np.linspace(ewmin,ewmax, steps)/np.cos(nsmin*_DEG2RA)).T\n    dec3 = (np.ones((steps,1))*nsmin).T\n    #\n    dec4  = np.linspace(nsmin,nsmax, steps).T\n    ra4 = ewmax[:,None]/np.cos(dec4*_DEG2RA)\n\n    ra_bd = np.concatenate((ra1, ra2, ra3, ra4  ), axis=1)  \n    dec_bd = np.concatenate((dec1, dec2, dec3,dec4 ), axis=1)\n    \n    ra,dec = rot_xz_sph(np.moveaxis(ra_bd,0,1), np.moveaxis(dec_bd,0,1), np.moveaxis(np.atleast_3d(dec_field),0,1))\n    ra += np.moveaxis(np.atleast_3d(ra_field),0,1)\n\n    if inrad:\n        ra *= _DEG2RA\n        dec *= _DEG2RA\n        \n    radec = np.moveaxis([ra,dec],(0,1,2,3),(3,0,2,1))\n    return radec if not squeeze else np.squeeze(radec)\n\ndef get_grid_field(which):\n    \"\"\" \"\"\"\n    if which in [\"main\",\"Main\",\"primary\"]:\n        return FIELDSNAMES[FIELDSNAMES<880]\n    if which in [\"aux\",\"secondary\", \"auxiliary\"]:\n       return FIELDSNAMES[FIELDSNAMES>999]\n    if which in [\"all\",\"*\",\"both\"]:\n        return FIELDSNAMES\n        \n    raise ValueError(f\"Cannot parse which field grid you want {which}\")\n\n\ndef get_rcid_centroid(rcid, fieldid):\n    \"\"\" \"\"\"\n    ccdid, q1d = rcid_to_ccdid_qid(rcid)\n    return get_qids_centroid(fieldid, ccdid)[f\"q{q1d}\"]\n\ndef get_qids_centroid(fieldid=None, ccdid=None, ccd_vertices=None):\n    if ccd_vertices is None:\n        if fieldid is None or ccdid is None:\n            raise ValueError(\"either fieldid and ccdid or ccd_vertices should be given\")\n        \n        ccd_vertices = get_field_vertices(fieldid=fieldid, inclccd=True, ccd=ccdid)\n        \n    min_,mean_,max_ = np.percentile(ccd_vertices, [0,50,100], axis=0)\n    return {\"q1\":np.mean([mean_, max_], axis=0),\n            \"q2\":[np.mean([mean_[0], min_[0]]),np.mean([mean_[1], max_[1]])],\n            \"q3\":np.mean([mean_, min_], axis=0),\n            \"q4\":[np.mean([mean_[0], max_[0]]),np.mean([mean_[1], min_[1]])]\n            }\n                \n\n\n\ndef ccdpos_to_qid(ccdx, ccdy):\n    \"\"\" returns the qid for the given ccd position \"\"\"\n    flagqid = np.asarray(np.asarray([ccdx<3072, ccdy<3080]), dtype=int)    \n    return np.asarray([[1,4],[2,3]])[flagqid[0]][flagqid[1]]\n\ndef ccdid_qid_to_rcid(ccdid, qid):\n    \"\"\" computes the rcid \"\"\"\n    return 4*(ccdid - 1) + qid - 1\n\ndef rcid_to_ccdid_qid(rcid):\n    \"\"\" computes the rcid \"\"\"\n    qid = (rcid%4)+1\n    ccdid  = int((rcid-(qid - 1))/4 +1)\n    return ccdid,qid\n\n##############################\n#                            #\n#  Fields and References     #\n#                            #\n##############################\ndef has_field_reference(fieldid, rcid_details=False, **kwargs):\n    \"\"\" get the following dictionary {zg:bool, zr:bool, zi:bool}\n    where bool is True if the field has a reference image and false otherwise\n    \n    **kwargs goes to load_metadata(), for instance auth=[username, password]\n    Returns\n    -------\n    {zg:bool, zr:bool, zi:bool}\n    \"\"\"\n    from .query import ZTFQuery\n    zquery_ = ZTFQuery()\n    zquery_.load_metadata(kind=\"ref\", sql_query=f\"field={fieldid}\", **kwargs)\n    if rcid_details:\n        return {k:zquery_.metatable.query(f\"filtercode in ['{k}']\")[\"rcid\"].value_counts(sort=False).to_dict() for k in [\"zg\", \"zr\",\"zi\"]}\n    return {k: k in zquery_.metatable[\"filtercode\"].values for k in [\"zg\", \"zr\",\"zi\"]}\n\ndef get_fields_with_band_reference(filter_, ccdid=1, qid=1, **kwargs):\n    \"\"\" returns the list of fieldid that have a reference image in the `filter_` band.\n    filter_ is a filtercode entry [zg, zr or zg]\n    \n    **kwargs goes to load_metadata(), for instance auth=[username, password]\n    Returns\n    -------\n    list of fieldid\n    \"\"\"\n    from .query import ZTFQuery\n    zquery_ = ZTFQuery()\n    zquery_.load_metadata(kind=\"ref\",\n            sql_query=\"filtercode='%s' and ccdid=%s and qid=%s\"%(filter_,ccdid,qid), **kwargs)\n    return zquery_.metatable[\"field\"].values\n\ndef show_reference_map(band, **kwargs):\n    \"\"\" Display the 'field plot' in which field with image reference in the given band are colored. \"\"\"\n    title   = \"Fields with reference in the %s-band\"%band[1]\n    field_i = get_fields_with_band_reference(band)\n    return show_fields(field_i, facecolor=FIELDNAME_COLOR[band], alpha=0.3, title=title, **kwargs)\n    \n# ===================== #\n#                       #\n#    SHOW FIELD         #\n#                       #\n# ===================== #\ndef show_fields(fields, vmin=None, vmax=None,\n                ax=None, cmap=\"viridis\", title=None,\n                colorbar=True, cax=None, hcax=None, clabel=\" \", inclhist=True, \n                show_ztf_fields=True, grid=\"main\", grid_prop={},\n                bkgd_fields=None, bkgd_prop={},\n                show_mw=True, mw_b=None, mw_prop={},\n                savefile=None, figsize=None,\n                axparam={}, get_fplot=False,\n                **kwargs):\n    \"\"\" \n    Parameters\n    ----------\n    colored_by: \n    \"\"\"\n    fplot = FieldPlotter(ax=ax, cax=cax, hcax=hcax, figsize=figsize, inclcax=colorbar,\n                             inclhist=inclhist, **axparam)\n    # - Plotting\n    if show_ztf_fields:\n        fplot.show_ztf_grid(which=grid, **grid_prop)\n        \n    if bkgd_fields is not None:\n        def_prop = dict(facecolor=\"0.7\", edgecolor=\"0.5\", alpha=0.2, zorder=2)\n        fplot.show_fields(bkgd_fields,**{**def_prop,**bkgd_prop})\n        \n    if show_mw:\n        fplot.show_milkyway(b=mw_b, **mw_prop)\n\n    # Removing the NaNs\n    fplot.show_fields(fields,\n                        colorbar=colorbar,\n                        clabel=clabel,cmap=cmap,\n                        vmin=vmin, vmax=vmax,**kwargs)\n    \n    if title is not None:\n        fplot.fig.text(0.5,0.9, title,\n                     va=\"top\", ha=\"center\", fontsize=\"large\")\n    # Output\n    if savefile is not None:\n        fplot.fig.savefig(savefile, dpi=150)\n    if get_fplot:\n        return fplot\n    return fplot.fig\n\ndef show_field_ccds(fieldid, ax=None, ccd=None, textcolor=\"k\", facecolor=\"0.9\", edgecolor=\"k\",\n                        autoscale=True, **kwargs):\n    \"\"\" \"\"\"\n    if ax is None:\n        fig = mpl.figure(figsize=[8,6])\n        ax = fig.add_subplot(111)\n    else:\n        fig = ax.figure\n\n    if ccd is None:\n        ccd = range(1,17)\n    ff = get_fields_geoserie(inclccd=True)\n    fccd = {i:ff[f\"{fieldid}_{i}\"] for i in ccd}\n    for i,s_ in fccd.items():\n        verts = np.asarray(s_.exterior.xy).T\n        ax.add_patch( Polygon(verts, facecolor=facecolor, edgecolor=edgecolor, **kwargs))\n        ax.text(*np.mean(verts,axis=0),i, color=textcolor, va=\"center\", ha=\"center\")\n\n    if autoscale:\n        ax.autoscale()\n        \n    return fig\n\ndef show_gri_fields(fieldsg=None, fieldsr=None, fieldsi=None,\n                    fig=None,\n                    title=\" \", alignment=\"horizontal\",\n                    show_ztf_fields=True, colorbar=True,\n                    show_mw=True, mw_b=None, mw_prop={},\n                    projection=\"hammer\", moveup=0.05, vscale=1, hscale=1,\n                    **kwargs):\n    \"\"\"  \"\"\"\n    prop = {**dict(colorbar=colorbar, edgecolor=\"0.5\", linewidth=0.5),**kwargs}\n    \n    used_fields = {i+1:f for i,f in enumerate([fieldsg,fieldsr,fieldsi]) if f is not None and len(f)>0}\n    \n    # None\n    if len(used_fields) == 0:\n        raise ValueError(\"No fields given\")\n    \n    # Only one\n    if len(used_fields) == 1:\n        warnings.warn(\"Only one color given, favor using show_fields() directly\")\n        which = list(used_fields.keys())[0]\n        return show_fields(used_fields[which], cmap=FIELD_CMAP[which],\n                            show_ztf_fields=show_ztf_fields,\n                            show_mw=show_mw, mw_b=mw_b, mw_prop=mw_prop,\n                            **prop)\n    \n    # 2 or More\n    onlytwo = len(used_fields)==2\n    ax, cax = _get_gri_axes_(alignment=alignment, title=title, projection=projection,\n                             moveup=moveup, onlytwo=onlytwo, fig=fig, vscale=vscale, hscale=hscale)\n    \n    fbands = list(used_fields.keys())\n    afields_ = list(used_fields.values())\n    for i,ax_,cax_,fields_ in zip(fbands, ax, cax, afields_):\n        \n        if fields_ is not None:\n            patch = {}\n            if len(np.unique(fields_))==1:\n                patch[\"inclhist\"] = False\n                if np.unique(fields_)[0]==1:\n                    patch[\"colorbar\"] = False\n                \n            _ = show_fields(fields_, ax=ax_, cax=cax_, cmap=FIELD_CMAP[i],\n                            show_ztf_fields=show_ztf_fields,\n                            show_mw=show_mw, mw_b=mw_b, mw_prop=mw_prop,\n                            **{**prop,**patch})\n    return ax[0].figure\n\ndef _get_gri_axes_(alignment=\"classic\", title=None, titlefontsize=\"large\", projection=\"hammer\",\n                   labelsize=\"x-small\", labelcolor=\"0.7\",  clabelsize=\"x-small\", clabelcolor=\"k\",\n                   moveup=None, fig=None, vscale=1, hscale=1, onlytwo=False):\n    \"\"\" \"\"\"\n    if alignment is None or onlytwo:\n        alignment = \"flat\"\n\n    if moveup is None:\n        moveup=0        \n        \n    if alignment in [\"classic\"]:\n        if fig is None:\n            fig = mpl.figure(figsize=[9,6])\n        # G\n        axg   = fig.add_axes([0.03,0.52+moveup,0.43,0.48], projection=projection)\n        caxg  = fig.add_axes([0.03,0.54+moveup,0.43,0.015])\n        # R\n        axr   = fig.add_axes([0.54,0.52+moveup,0.43,0.48], projection=projection)\n        caxr  = fig.add_axes([0.54,0.54+moveup,0.43,0.015])\n        # I\n        axi   = fig.add_axes([0.27,0.04+moveup,0.43,0.48], projection=projection)\n        caxi  = fig.add_axes([0.27,0.05+moveup,0.43,0.015])\n        ax = [axg,axr,axi]\n        cax = [caxg,caxr,caxi]\n    elif alignment in [\"flat\",\"aligned\", \"horizontal\"]:\n        naxes = 3 if not onlytwo else 2\n        if fig is None:\n            fig = mpl.figure(figsize=[3.2*naxes,2.5])\n        # G\n        spanx, spanm = 0.05,0.05\n        width = (1-(2*spanx+2*spanm))/naxes\n        ax  = [fig.add_axes([ spanm+(i*(width*hscale+spanx)), (0.20+moveup)*vscale, width*hscale, 0.700*vscale],\n                                projection=projection) for i in range(naxes)]\n        cax = [fig.add_axes([ spanm+(i*(width*hscale+spanx)), (0.12+moveup)*vscale, width*hscale, 0.025*vscale])\n                   for i in range(naxes)]\n    else:\n        raise ValueError(f\"cannot parse the given show_gri alignment {alignment}, classic or horizontal\")\n\n    if title is not None:\n        fig.suptitle(title, fontsize=titlefontsize)\n    # labels\n    for ax_ in ax:\n        ax_.tick_params(labelsize=labelsize, labelcolor=labelcolor)\n    for ax_ in cax:        \n        ax_.tick_params(labelsize=clabelsize, labelcolor=clabelcolor)\n        \n    return ax,cax\n\n\ndef show_ztf_fieldvalues(key=\"Ebv\", fieldid=\"main\", mindec=-30,\n                        vmin=None, vmax=None,\n                        ax=None, cmap=\"viridis\", title=None,\n                        colorbar=True, cax=None, clabel=\" \",\n                        show_ztf_fields=True, grid=\"main\", grid_prop={},\n                        show_mw=True, mw_b=None, mw_prop={},\n                        savefile=None, **kwargs):\n    \"\"\" \"\"\"\n    if key not in FIELD_DATAFRAME.columns:\n        raise ValueError(f\"cannot parse the given key {key}, only columns from FIELD_DATAFRAME available\")\n    \n    \n    if type(fieldid) is str or fieldid is None:\n        fieldid = get_grid_field(fieldid)\n    query_ = \"index in @fieldid\"\n    if mindec is not None:\n        query_ +=\" and Dec > @mindec\"\n    # Serie to plot \n    serie = FIELD_DATAFRAME.query(query_)[key]\n    return show_fields(fields=serie, vmin=vmin, vmax=vmax,\n                           ax=ax, cmap=cmap, title=title,\n                           colorbar=colorbar, cax=cax, clabel=clabel,\n                           show_ztf_fields=show_ztf_fields, grid=grid, grid_prop=grid_prop,\n                           show_mw=show_mw, mw_b=mw_b, mw_prop=mw_prop,\n                           savefile=savefile, **kwargs)\n    \n    \ndef display_field(ax, fieldid, origin=None, facecolor=\"0.8\", lower_dec=None, edgecolor=None, **kwargs):\n    \"\"\" \"\"\"\n    print(\"display_field is DEPRECATED\")\n\ndef _radec_to_plot_(self, ra, dec):\n    \"\"\" \"\"\"\n    return np.asarray([-(np.asarray(ra)-self.origin)*np.pi/180, np.asarray(dec)*np.pi/180])\n\n        \n##############################\n#                            #\n#  Individual Field Class    #\n#                            #\n##############################\nclass FieldPlotter( object ):\n    \"\"\" \"\"\"\n    def __init__(self, ax=None, origin=180, inclcax=True, inclhist=False, cax=None, hcax=None, **kwargs):\n        \"\"\" \"\"\"\n        self.origin = origin        \n        self.load_ax(ax, inclcax=inclcax, cax=cax, inclhist=inclhist, **kwargs)\n\n        \n    def load_ax(self, ax=None, update_ticks=True, cax=None, hcax=None, inclcax=True, inclhist=False, figsize=None,\n                    **kwargs):\n        \"\"\" \"\"\"\n        if ax is None or len(np.atleast_1d(ax))==4:\n            self.fig = mpl.figure(figsize=(8,5) if figsize is None else figsize)\n            self.ax = self.fig.add_axes([0.15,0.2,0.75,0.75] if ax is None else ax, projection=\"hammer\")\n        else:\n            self.ax = ax\n            self.fig = self.ax\n            \n        if inclcax:\n            from .utils.plots import HistColorbar\n            if cax is None and hcax is None:\n                from .utils.plots import insert_ax\n                cax = insert_ax(self.ax, \"bottom\",\n                                    shrunk=0.98, space=-0.15, axspace=0.13)\n            if inclhist and hcax is None:\n                if len(np.atleast_1d(cax)) == 4:\n                    xmin, ymin, width, height= cax\n                    hcax = [xmin, ymin+np.min([height*1.5,height+0.005]), width, height*1.8]\n                else:    \n                    bcax = cax.get_position()\n                    xmin, ymin, width, height= bcax.xmin, bcax.ymin, bcax.width, bcax.height\n                    hcax = cax.figure.add_axes([xmin, ymin+np.min([height*1.5,height+0.005]) , width, height*1.8])\n                    \n            self.histcbar = HistColorbar(ax=hcax, cax=cax, fig=self.fig, draw=False)\n        else:\n            self.histcbar = None\n            \n        if update_ticks:\n            tick_labels = np.array([150, 120, 90, 60, 30, 0, 330, 300, 270, 240, 210])\n            tick_labels = np.remainder(tick_labels+360+self.origin,360)\n            self.ax.set_xticklabels(tick_labels)     # we add the scale on the x axis\n\n        # Label param\n        if len(kwargs)>0:\n            self.ax.tick_params(**kwargs)\n            \n    # ---------- #\n    #  PLOTTER   #\n    # ---------- #\n    def show_ztf_grid(self, which=\"main\", \n                  facecolor=\"None\", edgecolor=\"0.7\", alpha=0.1, zorder=1, **kwargs):\n        \"\"\" \"\"\"\n        fields_ = get_grid_field(which)\n        self._ztfgrid = self.show_fields(fields_, \n                                             facecolor=facecolor, edgecolor=edgecolor, \n                                             alpha=alpha, zorder=zorder, **kwargs)\n\n    def show_milkyway(self, b=None, nbins=100, l_start=-241, l_stop=116,**kwargs):\n        \"\"\" \"\"\"\n        \n        nbins=100\n        if b is None:\n            gal = coordinates.Galactic(np.linspace(l_start,l_stop,nbins)*units.deg, np.zeros(nbins)*units.deg\n                                           ).transform_to(coordinates.ICRS)\n            prop = dict(ls=\"-\", color=\"0.7\", alpha=0.5)\n            self.ax.plot(*self.radec_to_plot(gal.ra, gal.dec), **{**prop, **kwargs})\n        else:\n            gal_dw = coordinates.Galactic(np.linspace(l_start,l_stop,100)*units.deg, +b*np.ones(nbins)*units.deg\n                                         ).transform_to(coordinates.ICRS)\n            gal_up = coordinates.Galactic(np.linspace(l_start,l_stop,100)*units.deg, -b*np.ones(nbins)*units.deg\n                                         ).transform_to(coordinates.ICRS)\n            ra_dw,dec_dw = self.radec_to_plot(gal_dw.ra, gal_dw.dec)\n            ra_up,dec_up = self.radec_to_plot(gal_up.ra, gal_up.dec)\n\n            prop = dict(facecolor=\"0.7\", alpha=0.2)\n            self.ax.fill_between(ra_dw, dec_dw, dec_up, **{**prop, **kwargs})\n        \n    def add_fields(self, fields, facecolor=\"0.7\", edgecolor=\"k\", lw=0.5, **kwargs):\n        \"\"\" \"\"\"\n        fields_verts = self.get_field_vertices(fields)\n        self.poly_ = [self.ax.add_patch(Polygon(p_, facecolor=facecolor, \n                                        edgecolor=edgecolor, lw=lw, **kwargs))\n                     for p_ in fields_verts]\n\n    def show_fields(self, fields, cmap=None,\n                        colorbar=True, clabel=None, cfontsize=None,\n                        vmin=None, vmax=None, bins=\"auto\", **kwargs):\n        \"\"\" fields could be a list of field or a dictionary with single values \"\"\"\n        \n        # For now, then will move to pandas.Series as native\n        if type(fields) is pandas.Series:\n            fields = fields.to_dict()\n            \n        if type(fields)==dict:\n            # popint out nans\n            fields = {f:v for f,v in fields.items() if not np.isnan(v)} \n            values = list(fields.values())\n            if len(values)==0 or not np.any(values):\n                if self.histcbar is not None:\n                    self.histcbar.set_visible(False)\n                return\n            \n            if vmin is None: vmin = \"0\"\n            if type(vmin) == str:\n                vmin=np.percentile(values, float(vmin))\n            if vmax is None: vmax = \"100\"\n            if type(vmax) == str:\n                vmax=np.percentile(values, float(vmax))\n\n            values = np.asarray(values)\n            if self.histcbar is not None:\n                if bins is None or bins in ['auto']:\n                    if values.dtype == int:\n                        bins = int((vmax-vmin))+1\n                        vmax +=1\n                self.histcbar.build_histrogram(data=values, vmin=vmin, vmax=vmax, bins=bins)\n                \n            # - CBAR\n            if cmap is None and self.histcbar is not None:\n                cmap = self.histcbar.cmap\n                \n            elif type(cmap) == str:\n                if self.histcbar is not None:\n                    self.histcbar.load_cmap(cmap)\n                    cmap = self.histcbar.cmap\n                else:\n                    cmap = mpl.get_cmap(cmap)\n            else:\n                self.histcbar.load_cmap(cmap.name)\n                \n                \n#            _ = kwargs.pop(\"facecolor\",None) #remove facecolor is any\n            for f,v in fields.items():\n                self.add_fields(f, **{**dict(facecolor=cmap((v-vmin)/(vmax-vmin)) if vmax-vmin !=0 else cmap(0)), **kwargs})\n\n            # - Cbar\n            if colorbar:\n                self.show_colorbar(clabel=clabel, cfontsize=cfontsize)\n            elif self.histcbar is not None:\n                 self.histcbar.set_visible(False)\n                 \n        else:\n            self.add_fields(fields, **kwargs)\n        \n    def show_point(self, radec, **kwargs):\n        \"\"\" \"\"\"\n        xy = self.radec_to_plot(*radec)\n        self.ax.scatter(*xy, **kwargs)\n\n    def show_colorbar(self, clabel=None, cfontsize=None):\n        \"\"\" \"\"\"\n        if self.histcbar is None:\n            return\n\n        self.histcbar.draw()\n        self.histcbar.set_label(clabel, fontsize=cfontsize)\n        \n    def get_field_vertices(self, fields_):\n        \"\"\" Get the field vertices in plotting coordinates. \"\"\"\n        fields_ = np.squeeze(get_field_vertices(fields_, squeeze=False), axis=1) # remove CCDs\n        return [self.radec_to_plot(*f_.T).T for f_ in fields_] \n    \n    def radec_to_plot(self, ra, dec):\n        \"\"\" \"\"\"\n        return np.asarray([-(np.asarray(ra)-self.origin)*np.pi/180, np.asarray(dec)*np.pi/180])\n\n\n   \n##############################\n#                            #\n#    ZTF Fields Class        #\n#                            #\n##############################\n\nclass FieldAnimation( FieldPlotter ):\n    \n    def __init__(self, fields, ax=None,dates=None, facecolors=None, alphas=None, edgecolors=None, inclcax=False):\n        \"\"\" \"\"\"\n        super().__init__(ax=ax, inclcax=inclcax)\n        \n        self.set_fields(fields)\n        self.set_dates(dates)\n        self.set_properties(facecolors=facecolors, alphas=alphas, edgecolors=edgecolors)\n        \n    # ================= #\n    #   Methods         #\n    # ================= #\n    def set_dates(self, dates):\n        \"\"\" \"\"\"\n        self._dates = np.atleast_1d(dates) if dates is not None else None\n\n    def set_fields(self, fields):\n        \"\"\" \"\"\"\n        self._fields = fields\n        self._unique_fields = np.unique(self._fields)\n        self._field_vertices = {i:v for i,v in zip(self._unique_fields,self.get_field_vertices(self._unique_fields))}\n        \n    def set_properties(self, facecolors=None, edgecolors=None, alphas=None):\n        \"\"\" \"\"\"\n        self._display_prop = {}\n        self._set_prop_(\"facecolor\", facecolors, \"0.7\")\n        self._set_prop_(\"edgecolor\", edgecolors, \"None\")\n        self._set_prop_(\"alpha\", alphas, 1)\n\n    def _set_prop_(self, key, value, default=None):\n        \"\"\" \"\"\"\n        if not hasattr(self,\"_display_prop\"):\n            self._display_prop = {}\n            \n        if value is None:\n            value = default\n            \n        if len(np.atleast_1d(value)) == 1:\n            self.display_prop[key] = np.atleast_1d(value)\n            self.display_prop[f\"unique_{key}\"] = True\n        else:\n            self.display_prop[key] = value\n            self.display_prop[f\"unique_{key}\"] = False\n            \n    # ---------- #\n    #  SETUP     #\n    # ---------- #\n    def reset(self):\n        \"\"\" \"\"\"\n        self.intpoly_ = Polygon(self.field_vertices[self.fields[0]],\n                                    facecolor=self.display_prop[\"facecolor\"][0],\n                                    edgecolor=self.display_prop[\"edgecolor\"][0],\n                                    alpha=self.display_prop[\"alpha\"][0])\n        \n        if self._dates is not None:\n            self.inttext_ = self.fig.text(0.01,0.99, self._dates[0],\n                                           va=\"top\", ha=\"left\", weight=\"bold\")\n            \n        p_ = self.ax.add_patch(self.intpoly_)\n        return self.intpoly_\n        \n\n    # ---------- #\n    #  Animate   #\n    # ---------- #    \n    def update_field_to(self, i):\n        \"\"\" \"\"\"\n        try:\n            self.intpoly_.set_xy(self.field_vertices[ self.fields[i] ])\n            if self.dates is not None and len(self.dates)>1:\n                self.inttext_.set_text(self.dates[i])\n        except:\n            print(f\"FAILES for i={i}\")\n            \n        for key in [\"facecolor\",\"edgecolor\",\"alpha\"]:\n            if not self.display_prop[f\"unique_{key}\"]:\n                getattr(self.intpoly_,f\"set_{key}\")(self.display_prop[key][i])\n                \n        return self.intpoly_\n\n    def launch(self, interval=5, repeat=False, blit=True, savefile=None):\n        \"\"\" \"\"\"\n        from matplotlib import animation\n        self.anim = animation.FuncAnimation(self.fig, self.update_field_to,\n                                                init_func=self.reset,\n                               frames=self.nfields, interval=interval, repeat=repeat, blit=blit)\n        \n    # ================= #\n    #   Properties      #\n    # ================= #\n    @property\n    def fields(self):\n        \"\"\" Fields that should be shown \"\"\"\n        return self._fields\n\n    @property\n    def dates(self):\n        \"\"\" Observation dates if any \"\"\"\n        return self._dates\n    @property\n    def nfields(self):\n        \"\"\" size of self.fields \"\"\"\n        return len(self.fields)\n\n    @property\n    def field_vertices(self):\n        \"\"\" vertices of the fields \"\"\"\n        return self._field_vertices\n\n    @property\n    def display_prop(self):\n        \"\"\" \"\"\"\n        return self._display_prop\n\n\n    \n##############################\n#                            #\n#    Planner Class           #\n#                            #\n##############################\n\nclass PalomarPlanning( object):\n    \"\"\" \"\"\"\n    def __init__(self, date=None, **kwargs):\n        \"\"\" \"\"\"\n        self._site = coordinates.EarthLocation.of_site(\"palomar\")\n        self._utcshift = -8*units.h\n        if date is not None:\n            self.set_date(date, **kwargs)\n\n    # --------- #\n    #  SETTER   #\n    # --------- #\n    def set_date(self, date, timerange=[-7,7], to_utc=True, **kwargs):\n        \"\"\" \"\"\"\n        self._date = date\n        self.set_night(date,timerange=[-7,7], to_utc=True, **kwargs)\n        \n    def set_night(self, night, timerange=[-7,7], to_utc=True, **kwargs):\n        \"\"\" \"\"\"    \n        self._night = self.get_night(night, timerange=timerange, to_utc=to_utc, **kwargs)\n        self._nightaltaz = self._get_night_altaz_(self.night)\n        \n    # --------- #\n    #  GETTER   #\n    # --------- #\n    @classmethod\n    def get_date_night_duration(cls, date, twilight=-12*units.deg, **kwargs):\n        \"\"\" ClassMethod to directly get the night duration at a given date or list of dates. \"\"\"\n        return cls().get_night_duration(date, twilight=twilight, **kwargs)\n\n    \n    def get_night(self, date, timerange=[-7,7], to_utc=True, range_units=units.h, bins=100, **kwargs):\n        \"\"\" \"\"\"\n        if type(date) is not time.Time:\n            date = time.Time(date, **kwargs)\n        if to_utc:\n            date -= self.utcshift\n            \n        if timerange is None:\n            return date\n        if len(np.atleast_1d(date))==1:\n            return date + np.linspace(*timerange, bins)*range_units\n        return date + np.linspace(*timerange, bins)[:,None]*range_units\n\n    def get_night_duration(self, date=None, twilight=-12*units.deg, bins=500):\n        \"\"\" in hours \"\"\"\n        if date is None:\n            date =self.date\n        \n        time_, sunaltaz = self.get_body_altaz(\"sun\",  date, bins=bins)\n        flagnight = sunaltaz.alt<twilight\n        \n        if len(np.atleast_1d(date))==1:\n            nigh_time = time_[flagnight][[0,-1]].jd\n            return np.diff(nigh_time)[0]*units.day.to(\"h\")*units.h\n        \n        length = []\n        for i,d_ in enumerate(date):\n            nigh_time_ = time_[:,i][flagnight[:,i]][[0,-1]].jd\n            night_length = np.diff(nigh_time_)[0]*units.day.to(\"h\")*units.h\n            length.append(night_length)\n        return length\n\n    def get_fields_altaz(self, fieldid, date=None, **kwargs):\n        \"\"\" \"\"\"\n        radec = get_field_centroid(fieldid)\n        return self.get_coord_altaz(radec, date=date, **kwargs)\n\n    def get_coord_altaz(self, radec, date=None, **kwargs):\n        \"\"\" \"\"\"\n        if type(radec) is not coordinates.SkyCoord:\n            radec = coordinates.SkyCoord(radec, unit=\"deg\")\n            \n        date, datealtaz = self._read_date_input_(date, **kwargs)\n            \n        return date, radec.transform_to( datealtaz[:,None] )\n    \n    def get_body_altaz(self, bodyname, date=None, **kwargs):\n        \"\"\" \n        'sun', 'moon', 'mercury', 'venus', 'earth-moon-barycenter', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune'\n        \"\"\"\n        date, datealtaz = self._read_date_input_(date, **kwargs)\n        body = coordinates.get_body(bodyname, date)\n        return date, body.transform_to( datealtaz )\n        \n        \n    def get_fields_observability(self, fieldid, date=None, airmasslimit=[1,1.5], minobservability=90*units.min,\n                                     twilight=-18*units.deg, still_observablein=None):#2*units.week):\n        \"\"\" \"\"\"\n        nighttime, field_altaz = self.get_fields_altaz(fieldid, date=date)\n\n        airmasses = np.asarray(field_altaz.secz)\n        # Twilight Cut\n        flagtwilight = self.is_twilight(date, twilight, squeeze=True)\n        flag_good = ((~flagtwilight[:,None]) * (airmasses>=airmasslimit[0]) * (airmasses<airmasslimit[1]) )\n        if minobservability is not None:\n            min_night_frac = minobservability/(nighttime[~flagtwilight].max()-nighttime[~flagtwilight].min()).to(\"min\")\n            flag_nightfrac = (np.sum(flag_good, axis=0)/len(nighttime[~flagtwilight])>=min_night_frac)\n            flag_good *= flag_nightfrac[None,:]\n\n\n        stime, ffrac = [pandas.Series(np.sum(flag_good, axis=1), index=pandas.DatetimeIndex(nighttime.datetime)),\n                        pandas.Series(np.sum(flag_good, axis=0)/len(nighttime[~flagtwilight]), index=fieldid)]\n        \n        if still_observablein is not None:\n            print(\"using still_observablein options\") \n            if date is None:\n                date = self.date\n                \n            delay_date = (time.Time(date) + still_observablein).iso.split(\" \")[0]\n            delay_stime, delay_ffrac = self.get_fields_observability(fieldid, date=delay_date,\n                                                                    airmasslimit=airmasslimit, minobservability=minobservability,\n                                                                    twilight=twilight, still_observablein=None)\n            fieldidstillin = ffrac[ffrac>0].index[np.in1d(ffrac[ffrac>0].index,delay_ffrac[delay_ffrac>0].index)]\n            flagstillin = np.in1d(ffrac.index,fieldidstillin)\n            flag_good *= flagstillin[None,:]\n            \n        return [pandas.Series(np.sum(flag_good, axis=1), index=pandas.DatetimeIndex(nighttime.datetime)),\n                pandas.Series(np.sum(flag_good, axis=0)/len(nighttime[~flagtwilight]), index=fieldid)]\n    \n        \n    def get_observable_fields(self, fieldids, date=None, airmasslimit=[1,1.5],\n                                minobservability=90*units.min, twilight=-18*units.deg,\n                                **kwargs):\n        \"\"\" \"\"\"\n        stime, ffrac = self.get_fields_observability(fieldids, date=date, airmasslimit=airmasslimit,\n                                                     twilight=twilight, minobservability=minobservability,\n                                                     **kwargs)\n        return ffrac[ffrac>0].index\n    \n        \n    def is_twilight(self, date=None, sunlimit=-18*units.deg, squeeze=True):\n        \"\"\" \"\"\"\n        time_, sunaltaz = self.get_body_altaz(\"sun\", date)\n        sunlimit = np.atleast_1d(sunlimit)\n        \n        flags = [sunaltaz.alt>slimit for slimit in sunlimit]\n        \n        if len(sunlimit) ==1 and squeeze:\n            return flags[0]\n        return flags\n    \n    def is_day(self, date, sunlimit=0*units.deg, squeeze=True, **kwargs):\n        \"\"\" \"\"\"\n        return self.is_twilight(sunlimit=0*units.deg, squeeze=squeeze, **kwargs)\n\n    def _get_night_altaz_(self, night, **kwargs):\n        \"\"\" \n        **kwargs goes to astropy.time.Time if date is not one already.\n        \"\"\"\n        return coordinates.AltAz(obstime=night, location=self.site)\n    \n    def _read_date_input_(self, date, **kwargs):\n        \"\"\" \"\"\"\n        if date is not None:\n            if type(date) is not time.Time:\n                date = self.get_night(date, **kwargs)\n            datealtaz = self._get_night_altaz_(date)\n        elif self.has_night():\n            date      = self.night\n            datealtaz = self.nightaltaz\n        else:\n            raise ValueError(\"No night set (self.set_night), no date given (see date option).\")\n            \n        return date, datealtaz\n    # -------- #\n    #  PLOTTER #\n    # -------- #\n    def show(self, date=None, fields=None, radec=None, body=None, propdate={},\n            show_twilight=True, as_airmass=False, ctwilight=\"0.7\"):\n        \"\"\" \"\"\"\n        import matplotlib.pyplot as mpl\n        from matplotlib import dates as mdates\n        \n        fig = mpl.figure(figsize=[7,4])\n        ax = fig.add_subplot(111)\n\n        if date is not None:\n            if type(date) is not time.Time:\n                date = self.get_night(date, **propdate)\n        else:\n            date = self.night\n            \n        # \n        # - start: Plotting\n        for type_ in [\"fields\", \"radec\", \"body\"]:\n            t_ = eval(type_)\n            if t_ is not None:\n                _, v_ = getattr(self,f\"get_{type_}_altaz\")(t_, date)\n                ax.plot(date.datetime, v_.alt if not as_airmass else v_.secz)\n        # - end: Plotting\n        # \n            \n        # \n        # - start: Twilight bands\n        if show_twilight:\n            self.show_twilight(ax=ax, date=date)\n            \n        # - start: End bands\n        # \n        \n        # - \n        ax.set_ylabel(\"Altitude [deg]\" if not as_airmass else \"Airmass\")\n        # - cleaning\n        locator = mdates.AutoDateLocator()\n        formatter = mdates.ConciseDateFormatter(locator)\n        ax.xaxis.set_major_locator(locator)\n        ax.xaxis.set_major_formatter(formatter)\n        # - Limites\n        ax.set_xlim(date.datetime[0],date.datetime[-1])\n        \n        ax.set_ylim(-1,3) if as_airmass else ax.set_ylim(-10,95)\n        \n    def show_twilight(self, date=None, ax=None, sunlimit=[0,-12,-18]*units.deg,\n                     ctwilights=\"0.7\", alphas=[0.8,0.3,0.1], propdate={}):\n        \"\"\" \"\"\"\n        import matplotlib.pyplot as mpl\n                \n        ctwilights = np.atleast_1d(ctwilights)\n        alphas = np.atleast_1d(alphas)\n        \n        if len(ctwilights)==1:\n            ctwilights = list(ctwilights)*len(sunlimit)\n        if len(alphas)==1:\n            alphas = list(alphas)*len(alphas)\n            \n        if ax is None:\n            fig = mpl.figure(figsize=[7,4])\n            ax = fig.add_subplot(111)\n        else:\n            fig = ax.figure\n            \n        \n        if date is not None:\n            if type(date) is not time.Time:\n                date = self.get_night(date, **propdate)\n        else:\n            date = self.night\n        \n        for i, tflag in enumerate(self.is_twilight(date=date, sunlimit=sunlimit, squeeze=False)):\n            ax.fill_between(date.datetime, 0,1, where=tflag, \n                            transform=ax.get_xaxis_transform(), \n                            color=ctwilights[i], alpha=alphas[i])\n        \n        \n    def show_fields_observability(self, fieldids, show_twilight=True, cmap=\"viridis\",\n                                      airmasslimit=[1,1.5], twilight=-18*units.deg, minobservability=90*units.min,\n                                      show_notobs=True, cmapv=0.1,\n                                      fcno=\"0.7\",ecno=\"0.7\", alphano=0.15, nolw=0, noprop={},\n                                      **kwargs):\n        \"\"\" \n        **kwargs foes to get_fields_observability() \n        \"\"\"\n        import matplotlib.pyplot as mpl        \n        from matplotlib import dates as mdates\n\n        figsize = [9,3.5]\n        axmap   = [0.05,0.21,0.45,0.7]\n        caxmap  = [0.05,0.18,0.45,0.02]\n\n        stime, ffrac = self.get_fields_observability(fieldids, airmasslimit=airmasslimit, twilight=twilight, minobservability=minobservability)\n        \n        fig = show_fields( ffrac[ffrac.values>0],\n                               bkgd_fields=fieldids[ffrac.values==0] if show_notobs else None,\n                               bkgd_prop={**dict(facecolor=fcno, edgecolor=ecno, alpha=alphano, lw=nolw),**noprop},\n                                  ax=axmap, cax=caxmap, figsize=figsize, cmap=cmap,\n                                  axparam={\"labelsize\":\"x-small\",\"color\":\"0.7\", \"labelcolor\":\"0.7\"},\n                                  clabel=\"Fraction of night observable\", cfontsize=\"medium\")\n\n        axh = fig.add_axes([0.6,0.17,0.35,0.68])\n        axh.fill_between(stime.index, stime.values, \n                         facecolor=mpl.cm.get_cmap(cmap)(cmapv,0.2), \n                         edgecolor=mpl.cm.get_cmap(cmap)(cmapv,0.9), lw=2, **kwargs)\n\n\n        locator = mdates.AutoDateLocator(minticks=4, maxticks=6)\n        formatter = mdates.ConciseDateFormatter(locator)\n        axh.xaxis.set_major_locator(locator)\n        axh.xaxis.set_major_formatter(formatter)\n        axh.set_ylim(bottom=0)\n        axh.set_xlim(*self.night.datetime[[0,-1]])\n        axh.set_ylabel(\"Number of fields observable\")\n        if show_twilight:\n            self.show_twilight(ax=axh, date=self.night, ctwilights=\"0.9\")\n            \n        fig.text(0.02,0.98, f\"Field Observability | {len(ffrac[ffrac>0])} fields\", color=\"0.7\", fontsize=\"medium\", va=\"top\",ha=\"left\")\n        \n        return fig\n    \n    # ============= #\n    #  Properties   #\n    # ============= #\n    @property\n    def site(self):\n        \"\"\" \"\"\"\n        return self._site\n    @property\n    def utcshift(self):\n        \"\"\" \"\"\"\n        return self._utcshift\n\n    @property\n    def date(self):\n        \"\"\" \"\"\"\n        return None if not hasattr(self,\"_date\") else self._date\n    \n    @property\n    def night(self):\n        \"\"\" \"\"\"\n        if not self.has_night():\n            return None\n        return self._night\n    \n    def has_night(self):\n        \"\"\" \"\"\"\n        return getattr(self,\"_night\") and self._night is not None\n    \n    @property\n    def nightaltaz(self):\n        \"\"\" \"\"\"\n        if not self.has_night():\n            raise AttributeError(\"No night set.\")\n            \n        return self._nightaltaz\n", "meta": {"hexsha": "38e626ffc401975468705df65cb5b647f4c3c423", "size": 48643, "ext": "py", "lang": "Python", "max_stars_repo_path": "ztfquery/fields.py", "max_stars_repo_name": "pierfra-ro/ztfquery", "max_stars_repo_head_hexsha": "8e0389719be3127887655f147f69350d316d8fd0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2019-03-08T17:01:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T15:57:49.000Z", "max_issues_repo_path": "ztfquery/fields.py", "max_issues_repo_name": "pierfra-ro/ztfquery", "max_issues_repo_head_hexsha": "8e0389719be3127887655f147f69350d316d8fd0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2018-08-20T13:33:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-23T09:20:54.000Z", "max_forks_repo_path": "ztfquery/fields.py", "max_forks_repo_name": "pierfra-ro/ztfquery", "max_forks_repo_head_hexsha": "8e0389719be3127887655f147f69350d316d8fd0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2018-11-26T22:41:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T13:21:08.000Z", "avg_line_length": 38.151372549, "max_line_length": 148, "alphanum_fraction": 0.5568735481, "include": true, "reason": "import numpy,from astropy", "num_tokens": 12535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.18985857148511184}}
{"text": "import abc\nfrom collections import defaultdict\nfrom typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union, overload\n\nimport numpy\nfrom openff.utilities import requires_package\nfrom pydantic import BaseModel, Field, constr\nfrom typing_extensions import Literal\n\nfrom openff.recharge.aromaticity import AromaticityModel, AromaticityModels\nfrom openff.recharge.charges.exceptions import UnableToAssignChargeError\nfrom openff.recharge.utilities.openeye import import_oechem\n\nif TYPE_CHECKING:\n\n    try:\n        import torch\n    except ImportError:\n        torch = None\n\n    from openeye.oechem import OEMol\n    from openff.toolkit.topology import Molecule\n    from openff.toolkit.typing.engines.smirnoff import VirtualSiteHandler\n\nExclusionPolicy = Literal[\"none\", \"parents\"]\n\nVirtualSiteKey = Tuple[str, str, str]\nVirtualSiteChargeKey = Tuple[str, str, str, int]\nVirtualSiteGeometryKey = Tuple[\n    str, str, str, Literal[\"distance\", \"in_plane_angle\", \"out_of_plane_angle\"]\n]\n\n_DEGREES_TO_RADIANS = numpy.pi / 180.0\n\n\nclass _VirtualSiteParameter(BaseModel, abc.ABC):\n    \"\"\"The base class for virtual site parameters.\"\"\"\n\n    type: Literal[\"base-virtual-site\"]\n\n    smirks: constr(min_length=1) = Field(\n        ...,\n        description=\"A SMIRKS pattern that encodes the chemical environment that \"\n        \"this parameter should be applied to.\",\n    )\n    name: Optional[str] = Field(\n        None, description=\"An optional name associated with this virtual site.\"\n    )\n\n    distance: float = Field(\n        ...,\n        description=\"The distance to place the virtual site along its associated basis.\",\n    )\n    charge_increments: Tuple[float, ...] = Field(\n        ...,\n        description=\"The amount of charge [e] to be transferred from the virtual site \"\n        \"to each tagged atom that forms the basis for the virtual site.\",\n    )\n\n    sigma: float = Field(\n        ..., description=\"The LJ sigma parameter [A] associated with the virtual site.\"\n    )\n    epsilon: float = Field(\n        ...,\n        description=\"The LJ espilon [kJ / mol] parameter associated with the virtual \"\n        \"site.\",\n    )\n\n    match: Literal[\"once\", \"all-permutations\"] = Field(..., description=\"...\")\n\n    @classmethod\n    @abc.abstractmethod\n    def local_frame_weights(cls) -> numpy.ndarray:\n        \"\"\"Returns a matrix of the weights to apply to a matrix of the coordinates of\n        the virtual sites' parent atoms to yield the origin, x and y vectors of the\n        virtual sites local frame with shape=(3, n_parent_atoms).\"\"\"\n        raise NotImplementedError()\n\n    @property\n    @abc.abstractmethod\n    def local_frame_coordinates(self) -> numpy.ndarray:\n        \"\"\"Returns a 1 X 3 array of the spherical coordinates (``[d, theta, phi]``) of\n        this virtual site with respect to its local frame.\n        \"\"\"\n        raise NotImplementedError()\n\n\nclass BondChargeSiteParameter(_VirtualSiteParameter):\n\n    type: Literal[\"BondCharge\"] = \"BondCharge\"\n\n    @classmethod\n    def local_frame_weights(cls) -> numpy.ndarray:\n        return numpy.array([[1.0, 0.0], [-1.0, 1.0], [-1.0, 1.0]])\n\n    @property\n    def local_frame_coordinates(self) -> numpy.ndarray:\n        # distance, theta, phi\n        return numpy.array([[self.distance, 180.0, 0.0]])\n\n\nclass MonovalentLonePairParameter(_VirtualSiteParameter):\n\n    type: Literal[\"MonovalentLonePair\"] = \"MonovalentLonePair\"\n\n    in_plane_angle: float = Field(\n        ...,\n        description=\"The angle [deg] to move the virtual site in the plane defined \"\n        \"by the tagged atoms by.\",\n    )\n    out_of_plane_angle: float = Field(\n        ...,\n        description=\"The angle [deg] to move the virtual site out of the plane \"\n        \"defined by the tagged atoms by.\",\n    )\n\n    @classmethod\n    def local_frame_weights(cls) -> numpy.ndarray:\n        return numpy.array([[1.0, 0.0, 0.0], [-1.0, 1.0, 0.0], [-1.0, 0.0, 1.0]])\n\n    @property\n    def local_frame_coordinates(self) -> numpy.ndarray:\n        # distance, theta, phi\n        return numpy.array(\n            [[self.distance, self.in_plane_angle, self.out_of_plane_angle]]\n        )\n\n\nclass DivalentLonePairParameter(_VirtualSiteParameter):\n\n    type: Literal[\"DivalentLonePair\"] = \"DivalentLonePair\"\n\n    out_of_plane_angle: float = Field(\n        ...,\n        description=\"The angle [deg] to move the virtual site out of the plane \"\n        \"defined by the tagged atoms by.\",\n    )\n\n    @classmethod\n    def local_frame_weights(cls) -> numpy.ndarray:\n        return numpy.array([[0.0, 1.0, 0.0], [0.5, -1.0, 0.5], [1.0, -1.0, 0.0]])\n\n    @property\n    def local_frame_coordinates(self) -> numpy.ndarray:\n        # distance, theta, phi\n        return numpy.array([[self.distance, 180.0, self.out_of_plane_angle]])\n\n\nclass TrivalentLonePairParameter(_VirtualSiteParameter):\n\n    type: Literal[\"TrivalentLonePair\"] = \"TrivalentLonePair\"\n\n    @classmethod\n    def local_frame_weights(cls) -> numpy.ndarray:\n        return numpy.array(\n            [\n                [0.0, 1.0, 0.0, 0.0],\n                [1.0 / 3.0, -1.0, 1.0 / 3.0, 1.0 / 3.0],\n                [1.0, -1.0, 0.0, 0.0],\n            ]\n        )\n\n    @property\n    def local_frame_coordinates(self) -> numpy.ndarray:\n        # distance, theta, phi\n        return numpy.array([[self.distance, 180.0, 0.0]])\n\n\nVirtualSiteParameterType = Union[\n    BondChargeSiteParameter,\n    MonovalentLonePairParameter,\n    DivalentLonePairParameter,\n    TrivalentLonePairParameter,\n]\n\n\nclass VirtualSiteCollection(BaseModel):\n    \"\"\"A collection of virtual site parameters that are based off of the SMIRNOFF\n    specification.\"\"\"\n\n    parameters: List[VirtualSiteParameterType] = Field(\n        ...,\n        description=\"The virtual site parameters to apply.\",\n    )\n    aromaticity_model: AromaticityModels = Field(\n        AromaticityModels.MDL,\n        description=\"The model to use when assigning aromaticity.\",\n    )\n\n    exclusion_policy: ExclusionPolicy = Field(\"parents\", description=\"...\")\n\n    @requires_package(\"openff.toolkit\")\n    @requires_package(\"simtk\")\n    def to_smirnoff(self) -> \"VirtualSiteHandler\":\n        \"\"\"Converts this collection of virtual site parameters to a SMIRNOFF virtual\n        site parameter handler.\n\n        Returns\n        -------\n            The constructed parameter handler.\n        \"\"\"\n\n        from openff.toolkit.typing.engines.smirnoff import VirtualSiteHandler\n        from simtk import unit\n\n        # noinspection PyTypeChecker\n        parameter_handler = VirtualSiteHandler(\n            version=\"0.3\", exclusion_policy=self.exclusion_policy\n        )\n\n        for parameter in reversed(self.parameters):\n\n            parameter_kwargs = dict(\n                smirks=parameter.smirks,\n                type=parameter.type,\n                name=parameter.name,\n                distance=parameter.distance * unit.angstrom,\n                charge_increment=[\n                    charge * unit.elementary_charge\n                    for charge in parameter.charge_increments\n                ],\n                sigma=parameter.sigma * unit.angstrom,\n                epsilon=parameter.epsilon * unit.kilojoules_per_mole,\n                match=parameter.match.replace(\"-\", \"_\").lower(),\n            )\n\n            if parameter.type == \"MonovalentLonePair\":\n\n                parameter_kwargs[\"outOfPlaneAngle\"] = (\n                    parameter.out_of_plane_angle * unit.degrees\n                )\n                parameter_kwargs[\"inPlaneAngle\"] = (\n                    parameter.in_plane_angle * unit.degrees\n                )\n\n            elif parameter.type == \"DivalentLonePair\":\n\n                parameter_kwargs[\"outOfPlaneAngle\"] = (\n                    parameter.out_of_plane_angle * unit.degrees\n                )\n\n            parameter_handler.add_parameter(parameter_kwargs=parameter_kwargs)\n\n        return parameter_handler\n\n    @classmethod\n    @requires_package(\"simtk\")\n    def from_smirnoff(\n        cls,\n        parameter_handler: \"VirtualSiteHandler\",\n        aromaticity_model=AromaticityModels.MDL,\n    ) -> \"VirtualSiteCollection\":\n        \"\"\"Attempts to convert a SMIRNOFF virtual site parameter handler to a virtual\n        site parameter collection.\n\n        Parameters\n        ----------\n        parameter_handler\n            The parameter handler to convert.\n        aromaticity_model\n            The model which describes how aromaticity should be assigned\n            when applying the virtual site correction parameters.\n\n        Returns\n        -------\n            The converted virtual site collection.\n        \"\"\"\n\n        from simtk import unit\n\n        parameters = []\n\n        for smirnoff_parameter in reversed(parameter_handler.parameters):\n\n            base_kwargs = dict(\n                smirks=smirnoff_parameter.smirks,\n                name=smirnoff_parameter.name,\n                distance=smirnoff_parameter.distance.value_in_unit(unit.angstrom),\n                charge_increments=tuple(\n                    charge.value_in_unit(unit.elementary_charge)\n                    for charge in smirnoff_parameter.charge_increment\n                ),\n                sigma=smirnoff_parameter.sigma.value_in_unit(unit.angstrom),\n                epsilon=smirnoff_parameter.epsilon.value_in_unit(\n                    unit.kilojoules_per_mole\n                ),\n                match=smirnoff_parameter.match.replace(\"_\", \"-\").lower(),\n            )\n\n            if smirnoff_parameter.type == \"BondCharge\":\n                parameter = BondChargeSiteParameter(**base_kwargs)\n\n            elif smirnoff_parameter.type == \"MonovalentLonePair\":\n\n                parameter = MonovalentLonePairParameter(\n                    **base_kwargs,\n                    out_of_plane_angle=smirnoff_parameter.outOfPlaneAngle.value_in_unit(\n                        unit.degrees\n                    ),\n                    in_plane_angle=smirnoff_parameter.inPlaneAngle.value_in_unit(\n                        unit.degrees\n                    ),\n                )\n\n            elif smirnoff_parameter.type == \"DivalentLonePair\":\n\n                parameter = DivalentLonePairParameter(\n                    **base_kwargs,\n                    out_of_plane_angle=smirnoff_parameter.outOfPlaneAngle.value_in_unit(\n                        unit.degrees\n                    ),\n                )\n\n            elif smirnoff_parameter.type == \"TrivalentLonePair\":\n                parameter = TrivalentLonePairParameter(**base_kwargs)\n\n            else:\n                raise NotImplementedError()\n\n            parameters.append(parameter)\n\n        return VirtualSiteCollection(\n            parameters=parameters,\n            aromaticity_model=aromaticity_model,\n            exclusion_policy=parameter_handler.exclusion_policy.lower(),\n        )\n\n    def vectorize_coordinates(\n        self, parameter_keys: List[VirtualSiteGeometryKey]\n    ) -> numpy.ndarray:\n        \"\"\"Returns a flat vector of the local frame coordinate values associated with a\n        specified set of 'keys'.\n\n        Parameters\n        ----------\n        parameter_keys\n            A list of parameter 'keys' of the form ``(smirks, type, name, attr)`` that\n            specify which local frame coordinate to include in the returned vector.\n\n            The allowed attributes are ``distance``, ``in_plane_angle``,\n            ``out_of_plane_angle``\n\n        Returns\n        -------\n            A vector of local frame coordinate with shape=(n_keys, 1)\n        \"\"\"\n\n        parameters_by_key = {\n            (parameter.smirks, parameter.type, parameter.name): parameter\n            for parameter in self.parameters\n        }\n\n        parameter_values = numpy.array(\n            [\n                [getattr(parameters_by_key[tuple(parameter_key)], attribute)]\n                for *parameter_key, attribute in parameter_keys\n            ]\n        )\n\n        return parameter_values\n\n    def vectorize_charge_increments(\n        self, parameter_keys: List[VirtualSiteChargeKey]\n    ) -> numpy.ndarray:\n        \"\"\"Returns a flat vector of the charge increment values associated with a\n        specified set of 'keys'.\n\n        Parameters\n        ----------\n        parameter_keys\n            A list of parameter 'keys' of the form ``(smirks, type, name, idx)`` that\n            specify which charge increments to include in the returned vector, where\n            `idx` is an integer index into a parameters' ``charge_increments`` tuple.\n\n        Returns\n        -------\n            A vector of charge increments with shape=(n_keys, 1)\n        \"\"\"\n\n        parameters_by_key = {\n            (parameter.smirks, parameter.type, parameter.name): parameter\n            for parameter in self.parameters\n        }\n\n        return numpy.array(\n            [\n                [\n                    parameters_by_key[tuple(parameter_key)].charge_increments[\n                        charge_index\n                    ]\n                ]\n                for *parameter_key, charge_index in parameter_keys\n            ]\n        )\n\n\nclass VirtualSiteGenerator:\n    @classmethod\n    def _apply_virtual_sites(\n        cls, oe_molecule: \"OEMol\", vsite_collection: VirtualSiteCollection\n    ) -> Tuple[\"Molecule\", Dict[Tuple[int, ...], List[VirtualSiteKey]]]:\n        \"\"\"Applies a virtual site collection to a molecule.\n\n        Parameters\n        ----------\n        oe_molecule\n            The molecule to build the virtual sites for.\n        vsite_collection\n            The v-site collection to use to create the virtual sites.\n\n        Returns\n        -------\n            An OpenFF molecule with virtual sites as well as a dictionary that maps each\n            virtual site back to the parameter that yielded it.\n        \"\"\"\n\n        from openff.toolkit.topology import Molecule\n\n        parameter_handler = vsite_collection.to_smirnoff()\n\n        off_topology = parameter_handler.create_openff_virtual_sites(\n            Molecule.from_openeye(oe_molecule).to_topology()\n        )\n        off_molecule = next(off_topology.reference_molecules)\n\n        term_topology = parameter_handler._term_map_topology(off_topology)\n\n        assigned_vsite_keys = defaultdict(set)\n\n        for (_, atom_indices), vsite_keys in term_topology.items():\n\n            for vsite_key in vsite_keys:\n\n                (_, (smirks, (vsite_type, (vsite_name, _)))) = vsite_key\n                assigned_vsite_keys[atom_indices].add((smirks, vsite_type, vsite_name))\n\n        return off_molecule, {\n            atom_indices: [*keys] for atom_indices, keys in assigned_vsite_keys.items()\n        }\n\n    @classmethod\n    def _build_charge_increment_array(\n        cls, vsite_collection: VirtualSiteCollection\n    ) -> Tuple[numpy.ndarray, List[VirtualSiteChargeKey]]:\n        \"\"\"Returns a flat vector of the charge increments contained within a virtual site\n        collection as well as a list of keys that map each value back to its original\n        parameter.\n\n        Parameters\n        ----------\n        vsite_collection\n            The collection containing the v-site parameters.\n\n        Returns\n        -------\n            ...\n        \"\"\"\n\n        charge_values = []\n        charge_keys = []\n\n        for parameter in vsite_collection.parameters:\n\n            for i, charge_increment in enumerate(parameter.charge_increments):\n\n                charge_values.append(charge_increment)\n\n                charge_keys.append(\n                    (parameter.smirks, parameter.type, parameter.name, i)\n                )\n\n        return numpy.array(charge_values), charge_keys\n\n    @classmethod\n    def _validate_charge_assignment_matrix(\n        cls,\n        assignment_matrix: numpy.ndarray,\n    ):\n        \"\"\"Validates the charge increment assignment matrix.\n\n        Parameters\n        ----------\n        assignment_matrix\n            The assignment matrix to validate with\n            shape=(n_atoms + n_vsites, n_charge_increments)\n        \"\"\"\n\n        non_zero_assignments = assignment_matrix.sum(axis=0).astype(bool)\n\n        if non_zero_assignments.any():\n\n            raise UnableToAssignChargeError(\n                \"An internal error occurred. The v-site charge increments alter the \"\n                \"total charge of the molecule\"\n            )\n\n    @classmethod\n    def build_charge_assignment_matrix(\n        cls,\n        oe_molecule: \"OEMol\",\n        vsite_collection: VirtualSiteCollection,\n    ) -> numpy.ndarray:\n        \"\"\"Generates a matrix that specifies which v-site charge increments have been\n        applied to which atoms in the molecule.\n\n        The matrix takes the form ...\n\n        Parameters\n        ----------\n        oe_molecule\n            The molecule to assign the v-site charge increments to.\n        vsite_collection\n            The v-site parameters that may be assigned.\n\n        Returns\n        -------\n            The assignment matrix with shape=(n_atoms + n_vsites, n_charge_increments)\n            where ...\n        \"\"\"\n\n        oechem = import_oechem()\n\n        # Make a copy of the molecule to assign the aromatic flags to.\n        oe_molecule = oechem.OEMol(oe_molecule)\n        # Assign aromaticity flags to ensure correct smirks matches.\n        AromaticityModel.assign(oe_molecule, vsite_collection.aromaticity_model)\n\n        off_molecule, assigned_vsite_keys = cls._apply_virtual_sites(\n            oe_molecule, vsite_collection\n        )\n\n        _, all_vsite_keys = cls._build_charge_increment_array(vsite_collection)\n\n        n_particles = off_molecule.n_particles\n        n_corrections = len(all_vsite_keys)\n\n        assignment_matrix = numpy.zeros((n_particles, n_corrections))\n\n        for vsite_particle in [\n            vsite_particle\n            for vsite in off_molecule.virtual_sites\n            for vsite_particle in vsite.particles\n        ]:\n\n            vsite_index = vsite_particle.molecule_particle_index\n            vsite_parameter_keys = assigned_vsite_keys[vsite_particle.orientation]\n\n            for vsite_parameter_key in vsite_parameter_keys:\n\n                for i, atom_index in enumerate(vsite_particle.orientation):\n\n                    # noinspection PyTypeChecker\n                    vsite_parameter_index = all_vsite_keys.index(\n                        (*vsite_parameter_key, i)\n                    )\n\n                    assignment_matrix[atom_index, vsite_parameter_index] += 1\n                    assignment_matrix[vsite_index, vsite_parameter_index] -= 1\n\n        cls._validate_charge_assignment_matrix(assignment_matrix)\n        return assignment_matrix\n\n    @classmethod\n    def apply_charge_assignment_matrix(\n        cls,\n        assignment_matrix: numpy.ndarray,\n        vsite_collection: VirtualSiteCollection,\n    ) -> numpy.ndarray:\n        \"\"\"Applies an assignment matrix to a list of virtual site parameters to yield the\n        final charges increments due to the virtual sites for a molecule.\n\n        Parameters\n        ----------\n        assignment_matrix\n            The virtual site charge increment assignment matrix constructed using\n            ``build_charge_assignment_matrix`` that describes how the virtual site\n            charge increments should be applied. This should have\n            shape=(n_atoms + n_vsites, n_charge_increments)\n        vsite_collection\n            The virtual site parameters that may be assigned.\n\n        Returns\n        -------\n            The charge increments with shape=(n_atoms + n_vsites, 1).\n        \"\"\"\n\n        correction_values, _ = cls._build_charge_increment_array(vsite_collection)\n        charge_corrections = assignment_matrix @ correction_values\n\n        if not numpy.isclose(charge_corrections.sum(), 0.0):\n\n            raise UnableToAssignChargeError(\n                \"An internal error occurred. The bond charge corrections were applied \"\n                \"in such a way so that the total charge of the molecule will be \"\n                \"altered.\"\n            )\n\n        return charge_corrections.reshape(-1, 1)\n\n    @classmethod\n    def generate_charge_increments(\n        cls,\n        oe_molecule: \"OEMol\",\n        vsite_collection: VirtualSiteCollection,\n    ) -> numpy.ndarray:\n        \"\"\"Generate a set of charge increments due to virtual sites for a molecule.\n\n        Parameters\n        ----------\n        oe_molecule\n            The molecule to generate the charge increments for.\n        vsite_collection\n            The virtual site parameters that may be assigned.\n\n        Returns\n        -------\n            The charge increments with shape=(n_atoms + n_vsites, 1) that should be\n            applied to the molecule.\n        \"\"\"\n\n        assignment_matrix = cls.build_charge_assignment_matrix(\n            oe_molecule, vsite_collection\n        )\n\n        generated_corrections = cls.apply_charge_assignment_matrix(\n            assignment_matrix, vsite_collection\n        )\n\n        return generated_corrections\n\n    @classmethod\n    def build_local_coordinate_frames(\n        cls,\n        conformer: numpy.ndarray,\n        assigned_parameters: Dict[Tuple[int, ...], List[VirtualSiteParameterType]],\n    ) -> numpy.ndarray:\n        \"\"\"Builds an orthonormal coordinate frame for each virtual particle\n        based on the type of virtual site and the coordinates of the parent atoms.\n\n        Notes\n        -----\n        * See `the OpenMM documentation for further information\n          <http://docs.openmm.org/7.0.0/userguide/theory.html#virtual-sites>`_.\n\n        Parameters\n        ----------\n        conformer\n            The conformer of the molecule that the virtual sites are being added to\n            with shape=(n_atoms, 3) and units of [A].\n        assigned_parameters\n            A dictionary of the form ``assigned_parameters[atom_indices] = parameters``\n            where ``atom_indices`` is a tuple of indices corresponding to the atoms\n            that the virtual site is connected to, and ``parameters`` is a list of the\n            parameters that describe the virtual sites.\n\n        Returns\n        -------\n            An array storing the local frames of all virtual sites with\n            shape=(4, n_vsites, 3) whereby ``local_frames[0]`` is an array of the\n            origins of each frame, ``local_frames[1]`` the x-directions,\n            ``local_frames[2]`` the y-directions, and ``local_frames[2]`` the\n            z-directions.\n        \"\"\"\n\n        stacked_frames = [[], [], [], []]\n\n        for parent_indices, vsite_parameter in (\n            (parent_indices, vsite_parameter)\n            for parent_indices, vsite_parameters in assigned_parameters.items()\n            for vsite_parameter in vsite_parameters\n        ):\n            parent_coordinates = conformer[parent_indices, :]\n\n            weighted_coordinates = (\n                vsite_parameter.local_frame_weights() @ parent_coordinates\n            )\n\n            origin = weighted_coordinates[0, :]\n\n            xy_plane = weighted_coordinates[1:, :]\n            xy_plane_norm = xy_plane / numpy.sqrt(\n                (xy_plane * xy_plane).sum(-1)\n            ).reshape(-1, 1)\n\n            x_hat = xy_plane_norm[0, :]\n            z_hat = numpy.cross(x_hat, xy_plane[1, :])\n            y_hat = numpy.cross(z_hat, x_hat)\n\n            stacked_frames[0].append(origin.reshape(1, -1))\n            stacked_frames[1].append(x_hat.reshape(1, -1))\n            stacked_frames[2].append(y_hat.reshape(1, -1))\n            stacked_frames[3].append(z_hat.reshape(1, -1))\n\n        local_frames = numpy.stack([numpy.vstack(frames) for frames in stacked_frames])\n        return local_frames\n\n    @classmethod\n    @overload\n    def convert_local_coordinates(\n        cls,\n        local_frame_coordinates: numpy.ndarray,\n        local_coordinate_frames: numpy.ndarray,\n        backend: Literal[\"numpy\"],\n    ) -> numpy.ndarray:\n        ...\n\n    @classmethod\n    @overload\n    def convert_local_coordinates(\n        cls,\n        local_frame_coordinates: \"torch.Tensor\",\n        local_coordinate_frames: \"torch.Tensor\",\n        backend: Literal[\"torch\"],\n    ) -> \"torch.Tensor\":\n        ...\n\n    @classmethod\n    def convert_local_coordinates(\n        cls,\n        local_frame_coordinates,\n        local_coordinate_frames,\n        backend: Literal[\"numpy\", \"torch\"] = \"numpy\",\n    ) -> numpy.ndarray:\n        \"\"\"Converts a set of local virtual site coordinates defined in a spherical\n        coordinate system into a full set of cartesian coordinates.\n\n        Parameters\n        ----------\n        local_frame_coordinates\n            An array containing the local coordinates with shape=(n_vsites, 3) and with\n            columns of distance [A], 'in plane angle' [deg] and 'out of plane'\n            angle [deg].\n        local_coordinate_frames\n            The orthonormal basis associated with each of the virtual sites with\n            shape=(4, n_vsites, 3). See the ``build_local_coordinate_frames`` function\n            for more details.\n        backend\n            The framework to use when performing mathematical operations.\n\n        Returns\n        -------\n            An array of the cartesian coordinates of the virtual sites with\n            shape=(n_vsites, 3) and units of [A].\n        \"\"\"\n\n        if backend == \"numpy\":\n            np = numpy\n        elif backend == \"torch\":\n            import torch\n\n            np = torch\n        else:\n            raise NotImplementedError()\n\n        d = local_frame_coordinates[:, 0].reshape(-1, 1)\n\n        theta = (local_frame_coordinates[:, 1] * _DEGREES_TO_RADIANS).reshape(-1, 1)\n        phi = (local_frame_coordinates[:, 2] * _DEGREES_TO_RADIANS).reshape(-1, 1)\n\n        cos_theta = np.cos(theta)\n        sin_theta = np.sin(theta)\n\n        cos_phi = np.cos(phi)\n        sin_phi = np.sin(phi)\n\n        # Here we use cos(phi) in place of sin(phi) and sin(phi) in place of cos(phi)\n        # this is because we want phi=0 to represent a 0 degree angle from the x-y plane\n        # rather than 0 degrees from the z-axis.\n        vsite_positions = (\n            local_coordinate_frames[0]\n            + d * cos_theta * cos_phi * local_coordinate_frames[1]\n            + d * sin_theta * cos_phi * local_coordinate_frames[2]\n            + d * sin_phi * local_coordinate_frames[3]\n        )\n\n        return vsite_positions\n\n    @classmethod\n    def generate_positions(\n        cls,\n        oe_molecule: \"OEMol\",\n        vsite_collection: VirtualSiteCollection,\n        conformer: numpy.ndarray,\n    ):\n        \"\"\"Computes the positions of a set of virtual sites relative to a provided\n        molecule in a given conformer.\n\n        Parameters\n        ----------\n        oe_molecule\n            The molecule to apply virtual sites to.\n        vsite_collection\n            The virtual site parameters to apply to the molecule\n        conformer\n            The conformer [A] of the molecule with shape=(n_atoms, 3) that the virtual\n            sites should be placed relative to.\n\n        Returns\n        -------\n            An array of virtual site positions [A] with shape=(n_vsites, 3).\n        \"\"\"\n\n        vsite_parameters_by_key = {\n            (parameter.smirks, parameter.type, parameter.name): parameter\n            for parameter in vsite_collection.parameters\n        }\n\n        # Extract the values of the assigned parameters.\n        _, assigned_parameter_map = cls._apply_virtual_sites(\n            oe_molecule, vsite_collection\n        )\n        assigned_parameters = {\n            atom_indices: [vsite_parameters_by_key[key] for key in parameter_keys]\n            for atom_indices, parameter_keys in assigned_parameter_map.items()\n        }\n\n        local_frame_coordinates = numpy.vstack(\n            [\n                parameter.local_frame_coordinates\n                for parent_indices, parameters in assigned_parameters.items()\n                for parameter in parameters\n            ]\n        )\n\n        # Construct the global cartesian coordinates of the v-sites.\n        local_coordinate_frames = cls.build_local_coordinate_frames(\n            conformer, assigned_parameters\n        )\n        vsite_positions = VirtualSiteGenerator.convert_local_coordinates(\n            local_frame_coordinates, local_coordinate_frames, backend=\"numpy\"\n        )\n\n        return vsite_positions\n", "meta": {"hexsha": "95f4edf1428834604ad8848f2194ec5442b01b6c", "size": 28128, "ext": "py", "lang": "Python", "max_stars_repo_path": "openff/recharge/charges/vsite.py", "max_stars_repo_name": "openforcefield/openff-recharge", "max_stars_repo_head_hexsha": "0ea3ef986e33c3ecf05924e64fb2e1872913b093", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-07-20T02:56:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T18:09:00.000Z", "max_issues_repo_path": "openff/recharge/charges/vsite.py", "max_issues_repo_name": "openforcefield/openff-recharge", "max_issues_repo_head_hexsha": "0ea3ef986e33c3ecf05924e64fb2e1872913b093", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 94, "max_issues_repo_issues_event_min_datetime": "2020-07-07T23:59:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T09:03:22.000Z", "max_forks_repo_path": "openff/recharge/charges/vsite.py", "max_forks_repo_name": "openforcefield/openff-recharge", "max_forks_repo_head_hexsha": "0ea3ef986e33c3ecf05924e64fb2e1872913b093", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.726618705, "max_line_length": 89, "alphanum_fraction": 0.6161831627, "include": true, "reason": "import numpy", "num_tokens": 5872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.35220179564702847, "lm_q1q2_score": 0.18983085814982092}}
{"text": "\"\"\"\nCopyright 2021 The CVXPY Developers\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\n\nimport warnings\n\nimport scipy  # For version checks\n\nimport cvxpy.settings as s\nfrom cvxpy.constraints import NonNeg, Zero\nfrom cvxpy.reductions.solution import Solution, failure_solution\nfrom cvxpy.reductions.solvers import utilities\nfrom cvxpy.reductions.solvers.conic_solvers.conic_solver import ConicSolver\nfrom cvxpy.utilities.versioning import Version\n\n\nclass SCIPY(ConicSolver):\n    \"\"\"An interface for the SciPy linprog function.\n    Note: This requires a version of SciPy which is >= 1.6.1\n    \"\"\"\n\n    # Solver capabilities.\n    MIP_CAPABLE = False\n    SUPPORTED_CONSTRAINTS = ConicSolver.SUPPORTED_CONSTRAINTS\n\n    # Map of SciPy linprog status\n    STATUS_MAP = {0: s.OPTIMAL,  # Optimal\n                  1: s.SOLVER_ERROR,  # Iteration limit reached\n                  2: s.INFEASIBLE,  # Infeasible\n                  3: s.UNBOUNDED,  # Unbounded\n                  4: s.SOLVER_ERROR  # Numerical difficulties encountered\n                  }\n\n    def import_solver(self) -> None:\n        \"\"\"Imports the solver.\n        \"\"\"\n        from scipy import optimize as opt\n        opt  # For flake8\n\n    def name(self):\n        \"\"\"The name of the solver.\n        \"\"\"\n        return s.SCIPY\n\n    def apply(self, problem):\n        \"\"\"Returns a new problem and data for inverting the new solution.\n\n        Returns\n        -------\n        tuple\n            (dict of arguments needed for the solver, inverse data)\n        \"\"\"\n        data = {}\n        inv_data = {self.VAR_ID: problem.x.id}\n\n        if not problem.formatted:\n            problem = self.format_constraints(problem, None)\n        data[s.PARAM_PROB] = problem\n        data[self.DIMS] = problem.cone_dims\n        inv_data[self.DIMS] = problem.cone_dims\n\n        constr_map = problem.constr_map\n        inv_data[self.EQ_CONSTR] = constr_map[Zero]\n        inv_data[self.NEQ_CONSTR] = constr_map[NonNeg]\n        len_eq = problem.cone_dims.zero\n\n        c, d, A, b = problem.apply_parameters()\n        data[s.C] = c\n        inv_data[s.OFFSET] = d\n        data[s.A] = -A[:len_eq]\n        if data[s.A].shape[0] == 0:\n            data[s.A] = None\n        data[s.B] = b[:len_eq].flatten()\n        if data[s.B].shape[0] == 0:\n            data[s.B] = None\n        data[s.G] = -A[len_eq:]\n        if 0 in data[s.G].shape:\n            data[s.G] = None\n        data[s.H] = b[len_eq:].flatten()\n        if 0 in data[s.H].shape:\n            data[s.H] = None\n        return data, inv_data\n\n    def solve_via_data(self, data, warm_start: bool, verbose: bool, solver_opts, solver_cache=None):\n        from scipy import optimize as opt\n\n        # Set default method which can be overriden by user inputs\n        if (Version(scipy.__version__) < Version('1.6.1')):\n            meth = \"interior-point\"\n        else:\n            meth = \"highs\"\n\n        # Extract solver options which are not part of the options dictionary\n        if solver_opts:\n\n            # Raise error message if the parameters are not passed in\n            # a dictionary called 'scipy_options'.\n            if \"scipy_options\" not in solver_opts:\n                raise ValueError(\"All parameters for the SCIPY solver should \"\n                                 \"be incased within a dictionary called \"\n                                 \"scipy_options e.g. \\n\"\n                                 \"prob.solve(solver='SCIPY', verbose=True,\"\n                                 \" scipy_options={'method':'highs-ds', 'maxiter':10000})\")\n\n            # Raise warning if the 'method' parameter is not specified\n            if \"method\" not in solver_opts['scipy_options']:\n                warnings.warn(\"It is best to specify the 'method' parameter \"\n                              \"within scipy_options. The main advantage \"\n                              \"of this solver, is its ability to use the \"\n                              \"HiGHS LP solvers via scipy.optimize.linprog() \"\n                              \"which require a SciPy version >= 1.6.1 .\"\n                              \"\\n\\nThe default method '{}' will be\"\n                              \" used in this case.\\n\".format(meth))\n\n            else:\n                meth = solver_opts['scipy_options'].pop(\"method\")\n\n                # Check to see if scipy version larger than 1.6.1 is installed\n                # if method chosen is one of the highs methods.\n                ver = (Version(scipy.__version__) < Version('1.6.1'))\n                if ((meth in ['highs-ds', 'highs-ipm', 'highs']) & ver):\n                    raise ValueError(\"The HiGHS solvers require a SciPy version >= 1.6.1\")\n\n            # Disable the 'bounds' parameter to avoid problems with\n            # canonicalised problems.\n            if \"bounds\" in solver_opts['scipy_options']:\n                raise ValueError(\"Please do not specify bounds through \"\n                                 \"scipy_options. Please specify bounds \"\n                                 \"through CVXPY.\")\n\n            # Not supported by HiGHS solvers:\n            # callback = solver_opts['scipy_options'].pop(\"callback\", None)\n            # x0 = solver_opts['scipy_options'].pop(\"x0\", None)\n\n            # Run the optimisation using scipy.optimize.linprog\n            solution = opt.linprog(data[s.C], A_ub=data[s.G], b_ub=data[s.H],\n                                   A_eq=data[s.A], b_eq=data[s.B], method=meth,\n                                   bounds=(None, None), options=solver_opts['scipy_options'])\n        else:\n\n            warnings.warn(\"It is best to specify the 'method' parameter \"\n                          \"within scipy_options. The main advantage \"\n                          \"of this solver, is its ability to use the \"\n                          \"HiGHS LP solvers via scipy.optimize.linprog() \"\n                          \"which require a SciPy version >= 1.6.1 .\"\n                          \"\\n\\nThe default method '{}' will be\"\n                          \" used in this case.\\n\".format(meth))\n\n            # Run the optimisation using scipy.optimize.linprog\n            solution = opt.linprog(data[s.C], A_ub=data[s.G], b_ub=data[s.H],\n                                   A_eq=data[s.A], b_eq=data[s.B], method=meth,\n                                   bounds=(None, None))\n\n        if verbose is True:\n            print(\"Solver terminated with message: \" + solution.message)\n\n        return solution\n\n    def invert(self, solution, inverse_data):\n        \"\"\"Returns the solution to the original problem given the inverse_data.\n        \"\"\"\n        status = self.STATUS_MAP[solution['status']]\n\n        primal_vars = None\n        dual_vars = None\n        if status in s.SOLUTION_PRESENT:\n            primal_val = solution['fun']\n            opt_val = primal_val + inverse_data[s.OFFSET]\n            primal_vars = {inverse_data[self.VAR_ID]: solution['x']}\n\n            # SciPy linprog only returns duals for version >= 1.7.0\n            # and method is one of 'highs', 'highs-ds' or 'highs-ipm'\n            if ('ineqlin' in solution.keys()):\n                eq_dual = utilities.get_dual_values(\n                    -solution['eqlin']['marginals'],\n                    utilities.extract_dual_value,\n                    inverse_data[self.EQ_CONSTR])\n                leq_dual = utilities.get_dual_values(\n                    -solution['ineqlin']['marginals'],\n                    utilities.extract_dual_value,\n                    inverse_data[self.NEQ_CONSTR])\n                eq_dual.update(leq_dual)\n                dual_vars = eq_dual\n\n            return Solution(status, opt_val, primal_vars, dual_vars, {})\n        else:\n            return failure_solution(status)\n", "meta": {"hexsha": "4ada088bd56770082f57d98de21cbd1538f85ab9", "size": 8157, "ext": "py", "lang": "Python", "max_stars_repo_path": "cvxpy/reductions/solvers/conic_solvers/scipy_conif.py", "max_stars_repo_name": "QiuWJX/cvxpy", "max_stars_repo_head_hexsha": "fd1c225b0cdf541618e292cae1a4c7ea25ddc934", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cvxpy/reductions/solvers/conic_solvers/scipy_conif.py", "max_issues_repo_name": "QiuWJX/cvxpy", "max_issues_repo_head_hexsha": "fd1c225b0cdf541618e292cae1a4c7ea25ddc934", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cvxpy/reductions/solvers/conic_solvers/scipy_conif.py", "max_forks_repo_name": "QiuWJX/cvxpy", "max_forks_repo_head_hexsha": "fd1c225b0cdf541618e292cae1a4c7ea25ddc934", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5820895522, "max_line_length": 100, "alphanum_fraction": 0.5666298884, "include": true, "reason": "import scipy,from scipy,import cvxpy,from cvxpy", "num_tokens": 1820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.18983085082011333}}
{"text": "# THIS IS AN OLD FILE TO REIMPLEMENT, NOT MEANT TO BE IMPORTED\nraise ImportError()\n\n\n\"\"\"Deep Belief Netork as Bandit\n\"\"\"\nimport copy\nimport cPickle\nimport logging\nimport os\nimport subprocess\nimport sys\nimport time\nlogger = logging.getLogger(__name__)\n\nimport numpy\nfrom bson import SON, BSON\n\nimport theano\nfrom theano import tensor\n\n# scikit-data\nfrom skdata.tasks import classification_train_valid_test\n\n# XXX use scikits-learn for PCA\nimport pylearn_pca\n\nfrom base import Bandit\nfrom utils import json_call\n\ntry:\n    RandomStreams = theano.sandbox.cuda.CURAND_RandomStreams\nexcept:\n    RandomStreams = tensor.shared_randomstreams.RandomStreams\n\nfrom ht_dist2 import rSON2, one_of, rlist, uniform, lognormal, ceil_lognormal\n\n\nclass LogisticRegression(object):\n    def __init__(self, x, w, b, params=None):\n        if params is None:\n            params = []\n        self.input = x\n        self.output = tensor.nnet.softmax(tensor.dot(x, w) + b)\n        self.l1 = abs(w).sum()\n        self.l2_sqr = (w**2).sum()\n        self.argmax = tensor.argmax(\n                tensor.dot(x, w) + b,\n                axis=x.ndim - 1)\n        self.w = w\n        self.b = b\n        self.params = params\n\n    @classmethod\n    def new(cls, input, n_in, n_out, dtype=None, name=None):\n        if dtype is None:\n            dtype = input.dtype\n        if name is None:\n            name = cls.__name__\n        logger.debug('allocating params w, b: %s' % str((n_in, n_out, dtype)))\n        w = theano.shared(\n                numpy.zeros((n_in, n_out), dtype=dtype),\n                name='%s.w' % name)\n        b = theano.shared(\n                numpy.zeros((n_out,), dtype=dtype),\n                name='%s.b' % name)\n        return cls(input, w, b, params=[w, b])\n\n\n    def nll(self, target):\n        \"\"\"Return the negative log-likelihood of the prediction of this model under a given\n        target distribution.  Passing symbolic integers here means 1-hot.\n        WRITEME\n        \"\"\"\n        return tensor.nnet.categorical_crossentropy(self.output, target)\n\n    def errors(self, target):\n        \"\"\"Return a vector of 0s and 1s, with 1s on every line that was mis-classified.\n        \"\"\"\n        if target.ndim != self.argmax.ndim:\n            raise TypeError('target should have the same shape as self.argmax',\n                    ('target', target.type, 'argmax', self.argmax.type))\n        if target.dtype.startswith('int'):\n            return theano.tensor.neq(self.argmax, target)\n        else:\n            raise NotImplementedError()\n\n\ndef sgd_updates(params, grads, stepsizes):\n    \"\"\"Return a list of (pairs) that can be used as updates in theano.function to implement\n    stochastic gradient descent.\n\n    :param params: variables to adjust in order to minimize some cost\n    :type params: a list of variables (theano.function will require shared variables)\n    :param grads: the gradient on each param (with respect to some cost)\n    :type grads: list of theano expressions\n    :param stepsizes: step by this amount times the negative gradient on each iteration\n    :type stepsizes: [symbolic] scalar or list of one [symbolic] scalar per param\n    \"\"\"\n    try:\n        iter(stepsizes)\n    except Exception:\n        stepsizes = [stepsizes for p in params]\n    if len(params) != len(grads):\n        raise ValueError('params and grads have different lens')\n    updates = [(p, p - step * gp) for (step, p, gp) in zip(stepsizes, params, grads)]\n    return updates\n\n\ndef geom(lower, upper, round=1):\n    ll = numpy.log(lower)\n    lu = numpy.log(upper)\n    return ceil_lognormal(.5 * (ll + lu), .4 * (lu - ll), round)\n\n\ndef dbn_template(dataset_name='skdata.larochelle_etal_2007.Rectangles',\n        sup_min_epochs=300,\n        sup_max_epochs=4000):\n    template = rSON2(\n        'preprocessing', one_of(\n            rSON2(\n                'kind', 'raw'),\n            rSON2(\n                'kind', 'zca',\n                'energy', uniform(0.5, 1.0))),\n        'dataset_name', dataset_name,\n        'sup_max_epochs', sup_max_epochs,\n        'sup_min_epochs', sup_min_epochs,\n        'iseed', one_of(5, 6, 7, 8),\n        'batchsize', one_of(20, 100),\n        'lr', lognormal(numpy.log(.01), 3),\n        'lr_anneal_start', geom(100, 10000),\n        'l2_penalty', one_of(0, lognormal(numpy.log(1.0e-6), 2)),\n        'next_layer', one_of(None,\n            rSON2(\n                'n_hid', geom(2**7, 2**12, round=16),\n                'W_init_dist', one_of('uniform', 'normal'),\n                'W_init_algo', one_of('old', 'Xavier'),\n                'W_init_algo_old_multiplier', lognormal(0.0, 1.0),\n                'cd_epochs', geom(1, 3000),\n                'cd_batchsize', 100,\n                'cd_sample_v0s', one_of(False, True),\n                'cd_lr', lognormal(numpy.log(.01), 2),\n                'cd_lr_anneal_start', geom(10, 10000),\n                'next_layer', one_of(None,\n                    rSON2(\n                        'n_hid', geom(2**7, 2**12, round=16),\n                        'W_init_dist', one_of('uniform', 'normal'),\n                        'W_init_algo', one_of('old', 'Xavier'),\n                        'W_init_algo_old_multiplier', lognormal(0.0, 1.0),\n                        'cd_epochs', geom(1, 2000),\n                        'cd_batchsize', 100,\n                        'cd_sample_v0s', one_of(False, True),\n                        'cd_lr', lognormal(numpy.log(.01), 2),\n                        'cd_lr_anneal_start', geom(10, 10000),\n                        'next_layer', one_of(None,\n                            rSON2(\n                                'n_hid', geom(2**7, 2**12, round=16),\n                                'W_init_dist', one_of('uniform', 'normal'),\n                                'W_init_algo', one_of('old', 'Xavier'),\n                                'W_init_algo_old_multiplier', lognormal(0., 1.),\n                                'cd_epochs', geom(1, 1500),\n                                'cd_batchsize', 100,\n                                'cd_sample_v0s', one_of(False, True),\n                                'cd_lr', lognormal(numpy.log(.01), 2),\n                                'cd_lr_anneal_start', geom(10, 10000),\n                                'next_layer', None,\n                                )))))))\n    return template\n\n\ndef nnet1_template(dataset_name='skdata.larochelle_etal_2007.Rectangles',\n            sup_min_epochs=30, # THESE ARE KINDA SMALL FOR SERIOUS RESULTS\n            sup_max_epochs=400):\n    template = rSON2(\n        'preprocessing', one_of(\n            rSON2(\n                'kind', 'raw'),\n            rSON2(\n                'kind', 'zca',\n                'energy', uniform(0.5, 1.0))),\n        'dataset_name', dataset_name,\n        'sup_max_epochs', sup_max_epochs,\n        'sup_min_epochs', sup_min_epochs,\n        'iseed', one_of(5, 6, 7, 8),\n        'batchsize', one_of(20, 100),\n        'lr', lognormal(numpy.log(.01), 3),\n        'lr_anneal_start', geom(100, 10000),\n        'l2_penalty', one_of(0, lognormal(numpy.log(1.0e-6), 3)),\n        'next_layer', rSON2(\n            'n_hid', geom(2**4, 2**10, round=16),\n            'W_init_dist', one_of('uniform', 'normal'),\n            'W_init_algo', one_of('old', 'Xavier'),\n            'W_init_algo_old_multiplier', uniform(.2, 2),\n            'cd_epochs', 0,\n            'cd_batchsize', 100,\n            'cd_sample_v0s', one_of(False, True),\n            'cd_lr', lognormal(numpy.log(.01), 3),\n            'cd_lr_anneal_start', geom(10, 10000),\n            'next_layer', None))\n    return template\n\n\ndef preprocess_data(config, ctrl):\n    dataset = json_call(config['dataset_name'])\n    train, valid, test = classification_train_valid_test(dataset)\n    X_train, y_train = numpy.asarray(train[0]), numpy.asarray(train[1])\n    X_valid, y_valid = numpy.asarray(valid[0]), numpy.asarray(valid[1])\n    X_test, y_test = numpy.asarray(test[0]), numpy.asarray(test[1])\n\n    if config['preprocessing']['kind'] == 'pca':\n        # compute pca of input (TODO: retrieve only pca_whitened input)\n        raise NotImplementedError('rewrite since cut and paste')\n        (eigvals,eigvecs), centered_trainset = pylearn_pca.pca_from_examples(\n                X=dataset['inputs'][:dataset['n_train']],\n                max_energy_fraction=config['pca_energy'])\n        eigmean = dataset['inputs'][0] - centered_trainset[0]\n\n        whitened_inputs = pylearn_pca.pca_whiten((eigvals,eigvecs),\n                dataset['inputs']-eigmean)\n        ctrl.info('PCA kept %i of %i components'%(whitened_inputs.shape[1],\n            dataset['n_inputs']))\n    elif config['preprocessing']['kind'] == 'zca':\n        (eigvals,eigvecs), centered_trainset = pylearn_pca.pca_from_examples(\n                X=X_train,\n                max_energy_fraction=config['preprocessing']['energy'])\n        eigmean = X_train[0] - centered_trainset[0]\n\n        def whiten(X):\n            X = pylearn_pca.pca_whiten((eigvals,eigvecs),\n                    X - eigmean)\n            X = pylearn_pca.pca_whiten_inverse((eigvals, eigvecs),\n                    X) + eigmean\n            X = X.astype('float32')\n            X_min = X.min()\n            X_max = X.max()\n            ctrl.info('ZCA min:%f max:%f' % (X_min, X_max))\n            if X_min < 0 or X_max > 1.0:\n                ctrl.info('ZCA clamping return value to (0, 1) interval')\n                X = numpy.clip(X, 0, 1, out=X)\n            return X\n\n        X_train, X_valid, X_test = [whiten(X)\n                for X in [X_train, X_valid, X_test]]\n\n    elif config['preprocessing']['kind'] == 'normalize':\n        raise NotImplementedError('rewrite since cut and paste')\n        n_train=dataset['n_train']\n        whitened_inputs = dataset['inputs']\n        whitened_inputs = whitened_inputs - whitened_inputs[:n_train].mean(axis=0)\n        whitened_inputs /= whitened_inputs[:n_train].std(axis=0)+1e-7\n    elif config['preprocessing']['kind'] == 'raw':\n        pass\n    else:\n        raise ValueError(\n                'unrecognized preprocessing',\n                config['preprocessing']['kind'])\n\n    for Xy in 'X', 'y':\n        for suffix in 'train', 'valid', 'test':\n            varname = '%s_%s'%(Xy, suffix)\n            var = locals()[varname]\n            ctrl.info('%s shape=%s max=%f min=%f' % (\n                varname,\n                var.shape,\n                var.max(),\n                var.min()))\n\n    s_X_train = theano.shared(X_train)\n    s_y_train = theano.shared(y_train)\n    s_X_valid = theano.shared(X_valid)\n    s_y_valid = theano.shared(y_valid)\n    s_X_test = theano.shared(X_test)\n    s_y_test = theano.shared(y_test)\n\n    return (dataset,\n            (s_X_train, s_y_train),\n            (s_X_valid, s_y_valid),\n            (s_X_test, s_y_test))\n\n\ndef train_rbm(s_rng, s_idx, s_batchsize, s_features, W, vbias, hbias, n_in,\n        n_hid, batchsize, sample_v0s,\n        cdlr, n_epochs, n_batches_per_epoch, lr_anneal_start,\n        givens={},\n        time_limit=None):\n    logger.info('rbm training n_in=%i n_hid=%i batchsize=%i' % (\n        n_in, n_hid, batchsize))\n    v0m = s_features\n    if sample_v0s:\n        v0s = tensor.cast(\n                s_rng.uniform(size=(batchsize, n_in)) < v0m,\n                'float32')\n    else:\n        v0s = v0m\n\n    h0m = tensor.nnet.sigmoid(tensor.dot(v0s, W) + hbias)\n    h0s = tensor.cast(s_rng.uniform(size=(batchsize, n_hid)) < h0m, 'float32')\n    v1m = tensor.nnet.sigmoid(tensor.dot(h0s, W.T)+vbias)\n    v1s = tensor.cast(s_rng.uniform(size=(batchsize, n_in)) < v1m, 'float32')\n    h1m = tensor.nnet.sigmoid(tensor.dot(v1s, W) + hbias)\n\n    s_lr = tensor.scalar(dtype='float32')\n\n    logger.debug('compiling cd1_fn')\n    cd1_fn = theano.function([s_idx, s_batchsize, s_lr],\n            [abs(v0m-v1m).mean()],\n            updates={\n                W: W + s_lr * (\n                    tensor.dot(v0s.T, h0m) - tensor.dot(v1s.T, h1m)),\n                vbias: vbias + s_lr * (\n                    (v0s - v1s).sum(axis=0)),\n                hbias: hbias + s_lr * (\n                    (h0m - h1m).sum(axis=0)),\n                },\n            givens=givens)\n    for epoch in xrange(n_epochs):\n        costs = []\n        if time_limit and time.time() > time_limit:\n            break\n        e_lr = cdlr * min(1, (float(lr_anneal_start)/(epoch+1)))\n        for batch_idx in xrange(n_batches_per_epoch):\n            costs.append(cd1_fn(batch_idx, batchsize, e_lr))\n        if not epoch % 10:\n            logger.info('CD1 epoch:%i  avg L1: %f'% (epoch, numpy.mean(costs)))\n    if costs:\n        return dict(final_recon_l1=float(numpy.mean(costs)),)\n    else:\n        return dict(final_recon_l1=float('nan'))\n\n_dataset_cache = {}\n\nclass DBN_Base(Bandit):\n    def dryrun_config(self, *args, **kwargs):\n        return dict(\n                lr=.01,\n                sup_max_epochs=500,\n                sup_min_epochs=50,\n                batchsize=10,\n                preprocessing=dict(kind='zca', energy=0.8),\n                iseed=5,\n                n_layers=1,\n                next_layer = dict(\n                    n_hid=50,\n                    W_init_dist='uniform',\n                    W_init_algo='Xavier',\n                    cd_epochs=100,\n                    cd_batchsize=50,\n                    cd_sample_v0s=True,\n                    cd_lr=0.1,\n                    cd_lr_anneal_start=3,\n                    next_layer = dict(\n                        n_hid=75,\n                        W_init_dist='uniform',\n                        W_init_algo='old',\n                        W_init_algo_old_multiplier=2.2,\n                        cd_epochs=70,\n                        cd_batchsize=10,\n                        cd_sample_v0s=False,\n                        cd_lr=0.01,\n                        cd_lr_anneal_start=30\n                        ),\n                    ),\n                l2_penalty=0.1,\n                lr_anneal_start=20,\n                dataset_name='skdata.larochelle_etal_2007.Rectangles',\n                )\n\n    @classmethod\n    def evaluate(cls, config, ctrl):\n        time_limit = time.time() + 60 * 60 # 1hr from now\n        rval = SON(dbn_train_fn_version=1)\n\n        ctrl.info('starting dbn_train_fn')\n        kv = config.items()\n        kv.sort()\n        for k,v in kv:\n            ctrl.info('key=%s\\t%s' %(k,str(v)))\n\n        rng = numpy.random.RandomState(config['iseed'])\n        s_rng = RandomStreams(int(rng.randint(2**30)))\n\n        dataset, train_Xy, valid_Xy, test_Xy = preprocess_data(config, ctrl)\n\n        # allocate learning function parameters\n        s_inputs_all = tensor.fmatrix('inputs')\n        s_labels_all = tensor.ivector('labels')\n        s_idx = tensor.lscalar('batch_idx')\n        s_batchsize=tensor.lscalar('batch_size')\n        s_low = s_idx * s_batchsize\n        s_high = s_low + s_batchsize\n        s_inputs = s_inputs_all[s_low:s_high]\n        s_labels = s_labels_all[s_low:s_high]\n        s_lr = tensor.scalar('lr')\n        s_features = s_inputs # s_features will be modified in the model-building loop\n\n        weights = []\n        vbiases = []\n        hbiases = []\n\n        n_inputs_i = valid_Xy[0].get_value(borrow=True).shape[1]\n\n        rval['cd_reports'] = []\n\n        try:\n            layer_config = config['next_layer']\n            # allocate model parameters\n            while layer_config:\n                i = len(rval['cd_reports'])\n                n_hid_i = layer_config['n_hid']\n                if layer_config['W_init_dist']=='uniform':\n                    W = rng.uniform(low=-1,high=1,size=(n_hid_i, n_inputs_i)).T.astype('float32')\n                elif layer_config['W_init_dist'] == 'normal':\n                    W = rng.randn(n_hid_i, n_inputs_i).T.astype('float32')\n                else:\n                    raise ValueError('W_init_dist', layer_config['W_init_dist'])\n\n                if layer_config['W_init_algo'] == 'old':\n                    #N.B. the weights are transposed so that as the number of hidden units changes,\n                    # the first hidden units are always the same vectors.\n                    # this makes it easier to isolate the effect of random initialization\n                    # from the other hyper-parameters under review\n                    W *= layer_config['W_init_algo_old_multiplier'] / numpy.sqrt(n_inputs_i)\n                elif layer_config['W_init_algo'] == 'Xavier':\n                    W *= numpy.sqrt(6.0 / (n_inputs_i + n_hid_i))\n                else:\n                    raise ValueError(layer_config['W_init_algo'])\n\n                layer_idx = len(rval['cd_reports'])\n                weights.append(theano.shared(W, 'W_%i' % layer_idx))\n                hbiases.append(theano.shared(numpy.zeros(n_hid_i, dtype='float32'),\n                    'h_%i' % layer_idx))\n                vbiases.append(theano.shared(numpy.zeros(n_inputs_i, dtype='float32'),\n                    'v_%i' % layer_idx))\n                del W\n\n                # allocate RBM training function for this layer\n                # this version re-calculates the training set every time\n                # TODO: cache the training set for each layer\n                # TODO: consider sparsity?\n                # TODO: consider momentum?\n                if layer_config['cd_epochs']:\n                    cd_report = train_rbm(\n                            s_rng, s_idx, s_batchsize, s_features,\n                            W=weights[-1],\n                            vbias=vbiases[-1],\n                            hbias=hbiases[-1],\n                            n_in=n_inputs_i,\n                            n_hid=n_hid_i,\n                            batchsize=layer_config['cd_batchsize'],\n                            sample_v0s=layer_config['cd_sample_v0s'],\n                            cdlr=layer_config['cd_lr'] / float(layer_config['cd_batchsize']),\n                            n_epochs=layer_config['cd_epochs'],\n                            n_batches_per_epoch=dataset.descr['n_train'] // layer_config['cd_batchsize'],\n                            lr_anneal_start=layer_config['cd_lr_anneal_start'],\n                            givens = {\n                                s_inputs_all: tensor.as_tensor_variable(train_Xy[0])\n                                },\n                            time_limit=time_limit\n                            )\n                else:\n                    cd_report = None\n                rval['cd_reports'].append(cd_report)\n\n                # update s_features to point to top layer\n                s_features = tensor.nnet.sigmoid(\n                        tensor.dot(s_features, weights[-1]) + hbiases[-1])\n                n_inputs_i = n_hid_i\n                layer_config = layer_config.get('next_layer', None)\n\n        except (MemoryError,):\n            rval['abort'] = 'MemoryError'\n            rval['status'] = 'ok'\n            rval['loss'] = 1.0\n            rval['best_epoch_valid'] = 0.0\n            return rval\n\n        # allocate model\n\n        logreg = LogisticRegression.new(s_features, n_in=n_inputs_i,\n                n_out=dataset.descr['n_classes'])\n        traincost = logreg.nll(s_labels).mean()\n        def ssq(X):\n            return (X**2).sum()\n        traincost = traincost + config['l2_penalty'] * (\n                sum([ssq(w_i) for w_i in weights]) + ssq(logreg.w))\n        # params = weights+hbiases+vbiases+logreg.params\n        # vbiases are not involved in the supervised network\n        params = weights + hbiases + logreg.params\n        train_logreg_fn = theano.function([s_idx, s_lr],\n                [logreg.nll(s_labels).mean()],\n                updates=sgd_updates(\n                    params=params,\n                    grads=tensor.grad(traincost, params),\n                    stepsizes=[s_lr] * len(params)),\n                givens={s_batchsize:config['batchsize'],\n                    s_inputs_all: tensor.as_tensor_variable(train_Xy[0]),\n                    s_labels_all: train_Xy[1]})\n        valid_logreg_fn = theano.function([s_idx],\n            logreg.errors(s_labels).mean(),\n            givens={s_batchsize:config['batchsize'],\n                s_inputs_all: tensor.as_tensor_variable(valid_Xy[0]),\n                s_labels_all: valid_Xy[1]})\n        test_logreg_fn = theano.function([s_idx],\n            logreg.errors(s_labels).mean(),\n            givens={s_batchsize:config['batchsize'],\n                s_inputs_all: tensor.as_tensor_variable(test_Xy[0]),\n                s_labels_all: test_Xy[1]})\n\n        rval['best_epoch'] = -1\n        rval['best_epoch_valid'] = -1\n        rval['best_epoch_train'] = -1\n        rval['best_epoch_test'] = -1\n        rval['status'] = 'ok'\n        valid_rate=-1\n        test_rate=-1\n        train_rate=-1\n\n        n_train_batches = dataset.descr['n_train'] // config['batchsize']\n        n_valid_batches = dataset.descr['n_valid'] // config['batchsize']\n        n_test_batches = dataset.descr['n_test'] // config['batchsize']\n\n        n_iters = 0\n        for epoch in xrange(config['sup_max_epochs']):\n            e_lr = config['lr']\n            e_lr *= min(1, config['lr_anneal_start'] / float(n_iters+1)) #anneal learning rate\n            valid_rate = float(1 - numpy.mean([valid_logreg_fn(i)\n                for i in range(n_valid_batches)]))\n            valid_rate_std_thresh = 0.5 * numpy.sqrt(valid_rate *\n                    (1 - valid_rate) / (n_valid_batches * config['batchsize']))\n\n            if valid_rate > (rval['best_epoch_valid']+valid_rate_std_thresh):\n                rval['best_epoch'] = epoch\n                rval['best_epoch_test'] = test_rate\n                rval['best_epoch_valid'] = valid_rate\n                rval['best_epoch_train'] = train_rate\n                best_params = copy.deepcopy(params)\n            logger.info('Epoch=%i best epoch %i valid %f test %f best_epoch_train %f prev_train %f'%(\n                epoch, rval['best_epoch'], rval['best_epoch_valid'], rval['best_epoch_test'],\n                    rval['best_epoch_train'], train_rate))\n            #ctrl.info('Epoch %i train nll: %f'%(epoch, train_rate))\n            ctrl.checkpoint(rval)\n\n            if epoch > config['sup_min_epochs'] and epoch > 2*rval['best_epoch']:\n                break\n            if time.time() > time_limit:\n                break\n            train_rate = float(numpy.mean([train_logreg_fn(i,e_lr) for i in\n                range(n_train_batches)]))\n            if not numpy.isfinite(train_rate):\n                do_test = False\n                rval['status'] = 'fail'\n                rval['status_info'] = 'train_rate %f' % train_rate\n                break\n            ++n_iters\n\n        do_test = 1\n        if do_test and rval['status'] == 'ok':\n            # copy best params back into place\n            for p, bp in zip(params, best_params):\n                p.set_value(bp.get_value())\n            rval['best_epoch_test'] = 1 - float(\n                    numpy.mean(\n                        [test_logreg_fn(i) for i in range(n_test_batches)]))\n            rval['loss'] = 1.0 - rval['best_epoch_valid']\n        ctrl.info('rval: %s' % str(rval))\n        return rval\n\n    @classmethod\n    def loss(cls, result, config=None):\n        \"\"\"Extract the scalar-valued loss from a result document\n        \"\"\"\n        try:\n            if numpy.isnan(float(result['loss'])):\n                return None\n            else:\n                return float(result['loss'])\n        except KeyError, TypeError:\n            return None\n\n    @classmethod\n    def loss_variance(cls, result, config=None):\n        if config['dataset_name'] not in _dataset_cache:\n            _dataset_cache[config['dataset_name']] = json_call(\n                config['dataset_name'])\n        dataset = _dataset_cache[config['dataset_name']]\n        n_valid = dataset.descr['n_valid']\n        p = cls.loss(result, config)\n        if p is None:\n            return None\n        return p * (1.0 - p) / (n_valid - 1)\n\n    @classmethod\n    def true_loss(cls, result, config=None):\n        try:\n            rval =  float(1 - result['best_epoch_test'])\n            if 0 <= rval <= 1:\n                return rval\n        except (KeyError, TypeError):\n            return None\n\n    @classmethod\n    def status(cls, result, config=None):\n        \"\"\"Extract the job status from a result document\n        \"\"\"\n        if (result['status'] == 'ok' and\n            (cls.loss(result) is None\n                or cls.true_loss(result) is None)):\n            return 'fail'\n        else:\n            return result['status']\n\n\ndef DBN_Convex():\n    return DBN_Base(\n            dbn_template(\n                dataset_name='skdata.larochelle_etal_2007.Convex'))\n\n\ndef DBN_MRBI():\n    ds =  'skdata.larochelle_etal_2007.MNIST_RotatedBackgroundImages'\n    return DBN_Base(dbn_template(dataset_name=ds))\n\n\nclass Dummy_DBN_Base(Bandit):\n    \"\"\"\n    A DBN_Base stub.\n\n    This class is used in unittests of optimization algorithms to ensure they\n    can deal with large nested specifications that include lots of distribution\n    types.\n\n    The evaluate function simply returns a random score.\n    \"\"\"\n    def __init__(self):\n        Bandit.__init__(self, template=dbn_template())\n        self.rng = numpy.random.RandomState(234)\n\n    def evaluate(self, argd, ctrl):\n        rval = dict(dbn_train_fn_version=-1)\n        # XXX: TODO: make up a loss function that depends on argd.\n        rval['status'] = 'ok'\n        rval['best_epoch_valid'] = float(self.rng.rand())\n        rval['loss'] = 1.0 - rval['best_epoch_valid']\n        return rval\n\n    def loss_variance(self, result, config=None):\n        return 0.01**2\n", "meta": {"hexsha": "97f8eee7024ead5b53f7b563a9ad8591cff1d03f", "size": 25454, "ext": "py", "lang": "Python", "max_stars_repo_path": "hpnnet/orig_dbn.py", "max_stars_repo_name": "hyperopt/hyperopt-nnet", "max_stars_repo_head_hexsha": "766811d1128cda02d41c95ae118fd938e023c605", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2015-02-06T03:54:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T16:49:11.000Z", "max_issues_repo_path": "hpnnet/orig_dbn.py", "max_issues_repo_name": "hyperopt/hyperopt-nnet", "max_issues_repo_head_hexsha": "766811d1128cda02d41c95ae118fd938e023c605", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hpnnet/orig_dbn.py", "max_forks_repo_name": "hyperopt/hyperopt-nnet", "max_forks_repo_head_hexsha": "766811d1128cda02d41c95ae118fd938e023c605", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2016-01-09T21:54:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-17T16:41:19.000Z", "avg_line_length": 39.2203389831, "max_line_length": 105, "alphanum_fraction": 0.5452581127, "include": true, "reason": "import numpy,import theano,from theano", "num_tokens": 6145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.18971051468946917}}
{"text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport re\nimport numpy as np\n\nfrom .dbmgr import get_cursor\n\nclass Element(object):\n\t\"\"\"Elemental data\n\n\t...\n\t\n\tParameters\n\t----------\n\tx : type\n\t\tDescription of parameter `x`.\n\n\tAttributes\n\t----------\n\n\tMethods\n\t-------\n\n\tNotes\n\t-----\n\n\tReferences\n\t----------\n\n\tExamples\n\t--------\n\n\t\"\"\"\n\n\tdef __init__(self, element):\n\t\tself.element = element.title()\n\t\tself._meta = None\n\n\t@property\n\tdef meta(self):\n\t\tif self._meta is None:\n\t\t\tfrom scipy.interpolate import interp1d\n\n\t\t\tself._meta = {}\n\t\t\tzg = get_cursor('ziegler')\n\t\t\tself._meta['Z'] = [str(i[2]).split(':')[0] for i in zg.execute('SELECT * FROM compounds WHERE compound=?',(self.element,))][0]\n\t\t\tself._meta['mass'], self._meta['density'] = [(i[1],i[2]) for i in zg.execute('SELECT * FROM weights WHERE Z=?',(self._meta['Z'],))][0]\n\t\t\tcoeff = np.array([i[1:] for i in zg.execute('SELECT * FROM mass_coeff WHERE Z=? ORDER BY energy',(self._meta['Z'],))])\n\t\t\tself._meta['mass_coeff'] = interp1d(coeff[:,0], coeff[:,1], bounds_error=False, fill_value=0.0)\n\t\t\tself._meta['mass_coeff_en'] = interp1d(coeff[:,0], coeff[:,2], bounds_error=False, fill_value=0.0)\n\t\t\tdb = get_cursor('decay')\n\t\t\tself._meta['abundances'] = {str(i[1]):i[12] for i in db.execute('SELECT * FROM chart WHERE element=? AND abundance>0.0',(self.element,))}\n\t\t\tself._meta['isotopes'] = sorted([i for i in self._meta['abundances']])\n\n\t\treturn self._meta\n\n\t@property\n\tdef Z(self):\n\t\treturn self.meta['Z']\n\n\t@property\n\tdef mass(self):\n\t\treturn self.meta['mass']\n\n\t@property\n\tdef isotopes(self):\n\t\treturn self.meta['isotopes']\n\n\t@property\n\tdef abundances(self):\n\t\treturn self.meta['abundances']\n\n\t@property\n\tdef mass_coeff(self):\n\t\treturn self.meta['mass_coeff']\n\n\t@property\n\tdef mass_coeff_en(self):\n\t\treturn self.meta['mass_coeff_en']\n\n\tdef attenuation(self, E, x=1.0):\n\t\treturn np.exp(-self.mass_coeff(E)*self.density*x)\n\n\tdef transmission(self, E, x=1.0):\n\t\treturn 1.0-np.exp(-self.mass_coeff(E)*self.density*x)\n\t\n\t@property\n\tdef density(self):\n\t\treturn self.meta['density']\n\t\n\t\n\t\n\n\nclass Isotope(object):\n\t\"\"\"Isotopic data\n\n\t...\n\t\n\tParameters\n\t----------\n\tx : type\n\t\tDescription of parameter `x`.\n\n\tAttributes\n\t----------\n\n\tMethods\n\t-------\n\n\tNotes\n\t-----\n\n\tReferences\n\t----------\n\n\tExamples\n\t--------\n\n\t\"\"\"\n\n\tdef __init__(self, istp):\n\t\tif istp=='1n' or istp=='1ng':\n\t\t\tself.element, self.A, self.isomer = 'n', 1, 'g'\n\t\telse:\n\t\t\tself.element = ''.join(re.findall('[A-Z]+',istp))\n\t\t\tif istp.startswith('nat'):\n\t\t\t\tself.A = 'nat'\n\t\t\telse:\n\t\t\t\tself.A = int(istp.split(self.element)[0])\n\t\t\tself.isomer = istp.split(self.element)[1]\n\t\tself.isotope = str(self.A)+self.element\n\t\tif self.isomer=='' and type(self.A)==int:\n\t\t\tself.isomer = 'g'\n\t\tif self.isomer=='m':\n\t\t\tself.isomer = 'm1'\n\t\tself.name = self.isotope+self.isomer\n\t\tself._meta = None\n\t\t\t\n\t@property\n\tdef meta(self):\n\t\tif self._meta is None:\n\t\t\tself._meta = {}\n\t\t\tself.db = get_cursor('decay')\n\t\t\tfor i in ['SFY','gm','el','bm','bp','al']:\n\t\t\t\tself._meta[i] = None\n\t\t\tQ = list(self.db.execute('SELECT * FROM chart WHERE isotope=?',(self.isotope,)))\n\t\t\tq = [i for i in Q if i[3]==self.isomer]\n\t\t\tif len(q):\n\t\t\t\tq = q[0]\n\t\t\telif len(Q):\n\t\t\t\tq = Q[0]\n\t\t\telse:\n\t\t\t\tq = [0,0,0,0,'',0,None,None,None,None,None,None,None,None,None,None,'']\n\t\t\tself._meta['E_level'] = q[2]\n\t\t\tself._meta['J_pi'] = str(q[4]) if q[4] else '?'\n\t\t\tself._meta['Z'] = q[6]\n\t\t\tself._meta['N'] = q[7]\n\t\t\tself._meta['stable'] = bool(q[9])\n\t\t\tself._meta['t_half'] = q[10]\n\t\t\tself._meta['unc_t_half'] = q[11]\n\t\t\tself._meta['abundance'] = q[12]\n\t\t\tself._meta['unc_abundance'] = q[13]\n\t\t\tif self._meta['stable'] and self._meta['abundance'] is None:\n\t\t\t\tself._meta['abundance'] = 100.0\n\t\t\t\tself._meta['unc_abundance'] = 0.0\n\t\t\tself._meta['mass'] = q[14]\n\t\t\tself._meta['Delta'] = q[15]\n\t\t\tself._meta['decay_mode'] = list(map(lambda i:[float(p) if n==2 else p for n,p in enumerate(i.split(':'))], str(q[16]).split(',')))\n\t\t\tstate = '' if len(Q)==1 else (self.isomer[0] if len(Q)==2 else self.isomer)\n\t\t\tself._meta['TeX'] = r'$^{'+str(self.A)+state+r'}$'+self.element.title()\n\t\treturn self._meta\n\t\n\t@property\n\tdef E_level(self):\n\t\treturn self.meta['E_level']\n\n\t@property\n\tdef J_pi(self):\n\t\treturn self.meta['J_pi']\n\n\t@property\n\tdef Z(self):\n\t\treturn self.meta['Z']\n\n\t@property\n\tdef N(self):\n\t\treturn self.meta['N']\n\n\t@property\n\tdef stable(self):\n\t\treturn self.meta['stable']\n\n\t@property\n\tdef mass(self):\n\t\treturn self.meta['mass']\n\n\t@property\n\tdef Delta(self):\n\t\treturn self.meta['Delta']\n\n\t@property\n\tdef TeX(self):\n\t\treturn self.meta['TeX']\n\n\tdef __str__(self):\n\t\treturn self.name\n\n\tdef half_life(self, units='s', unc=False):\n\t\t\"\"\"Description\n\n\t\t...\n\n\t\tParameters\n\t\t----------\n\t\tx : type\n\t\t\tDescription of parameter `x`.\n\n\t\tReturns\n\t\t-------\n\n\t\tNotes\n\t\t-----\n\n\t\tReferences\n\t\t----------\n\n\t\tExamples\n\t\t--------\n\n\t\t\"\"\"\n\n\t\tif self.stable:\n\t\t\treturn (np.inf,0.0) if unc else np.inf\n\t\thalf_conv = {'ns':1e-9,'us':1e-6,'ms':1e-3,'s':1.0,'m':60.0,'h':3600.0,'d':86400.0,'y':31557.6E3,'ky':31557.6E6}[units]\n\t\tif unc:\n\t\t\treturn self.meta['t_half']/half_conv,self.meta['unc_t_half']/half_conv\n\t\treturn self.meta['t_half']/half_conv\n\n\tdef decay_const(self, units='s', unc=False):\n\t\t\"\"\"Description\n\n\t\t...\n\n\t\tParameters\n\t\t----------\n\t\tx : type\n\t\t\tDescription of parameter `x`.\n\n\t\tReturns\n\t\t-------\n\n\t\tNotes\n\t\t-----\n\n\t\tReferences\n\t\t----------\n\n\t\tExamples\n\t\t--------\n\n\t\t\"\"\"\n\n\t\tif self.stable:\n\t\t\treturn (0.0,0.0) if unc else 0.0\n\t\tif unc:\n\t\t\tT2,uT2 = self.half_life(units, True)\n\t\t\treturn np.log(2.0)/T2,np.log(2.0)*uT2/T2**2\n\t\treturn np.log(2.0)/self.half_life(units)\n\n\tdef optimum_units(self):\n\t\t\"\"\"Description\n\n\t\t...\n\n\t\tParameters\n\t\t----------\n\t\tx : type\n\t\t\tDescription of parameter `x`.\n\n\t\tReturns\n\t\t-------\n\n\t\tNotes\n\t\t-----\n\n\t\tReferences\n\t\t----------\n\n\t\tExamples\n\t\t--------\n\n\t\t\"\"\"\n\n\t\topt = ['ns']\n\t\tfor units in ['us','ms','s','m','h','d','y']:\n\t\t\tif self.half_life(units)>1.0:\n\t\t\t\topt.append(units)\n\t\treturn opt[-1]\n\n\tdef abundance(self, unc=False):\n\t\t\"\"\"Description\n\n\t\t...\n\n\t\tParameters\n\t\t----------\n\t\tx : type\n\t\t\tDescription of parameter `x`.\n\n\t\tReturns\n\t\t-------\n\n\t\tNotes\n\t\t-----\n\n\t\tReferences\n\t\t----------\n\n\t\tExamples\n\t\t--------\n\n\t\t\"\"\"\n\n\t\tif unc:\n\t\t\treturn self.meta['abundance'], self.meta['unc_abundance']\n\t\treturn self.meta['abundance']\n\n\tdef get_SFY(self, unc=False, closest_SFY=False):\n\t\t\"\"\"Description\n\n\t\t...\n\n\t\tParameters\n\t\t----------\n\t\tx : type\n\t\t\tDescription of parameter `x`.\n\n\t\tReturns\n\t\t-------\n\n\t\tNotes\n\t\t-----\n\n\t\tReferences\n\t\t----------\n\n\t\tExamples\n\t\t--------\n\n\t\t\"\"\"\n\n\t\tif self.meta['SFY'] is None:\n\t\t\tself.meta['SFY'] = [(str(i[1]),i[2],i[3]) for i in self.db.execute('SELECT * FROM SFY WHERE parent=?',(self.name,))]\n\t\tSFY = list(self.meta['SFY'])\n\t\tif len(SFY)==0 and closest_SFY:\n\t\t\titps = list(set([str(i[0]) for i in self.db.execute('SELECT parent FROM SFY')]))\n\t\t\tdA = [abs(self.A-int(i[:3])) for i in itps]\n\t\t\tSFY = [(str(i[1]),i[2],i[3]) for i in self.db.execute('SELECT * FROM SFY WHERE parent=?',(itps[dA.index(min(dA))],))]\n\t\tif unc:\n\t\t\treturn [[i[0], i[1], i[2]] for i in SFY]\n\t\treturn [[i[0], i[1]] for i in SFY]\n\n\tdef decay_products(self, closest_SFY=False):\n\t\t\"\"\"Description\n\n\t\t...\n\n\t\tParameters\n\t\t----------\n\t\tx : type\n\t\t\tDescription of parameter `x`.\n\n\t\tReturns\n\t\t-------\n\n\t\tNotes\n\t\t-----\n\n\t\tReferences\n\t\t----------\n\n\t\tExamples\n\t\t--------\n\n\t\t\"\"\"\n\n\t\tprods = []\n\t\tfor (mode, product, br) in self.meta['decay_mode']:\n\t\t\tif product=='SFY':\n\t\t\t\tprods += [[i, br*y] for i,y in self.get_SFY(False, closest_SFY)]\n\t\t\telse:\n\t\t\t\tprods.append([product, br])\n\t\treturn [[i, br] for i,br in prods if br>1E-8]\n\n\tdef gammas(self, I_lim=[None,None], E_lim=[None,None], xrays=False, dE_511=3.5):\n\t\t\"\"\"Description\n\n\t\t...\n\n\t\tParameters\n\t\t----------\n\t\tx : type\n\t\t\tDescription of parameter `x`.\n\n\t\tReturns\n\t\t-------\n\n\t\tNotes\n\t\t-----\n\n\t\tReferences\n\t\t----------\n\n\t\tExamples\n\t\t--------\n\n\t\t\"\"\"\n\n\t\tif self.meta['gm'] is None:\n\t\t\tself.meta['gm'] = [[float(i[3]),float(i[4]),float(i[5]),str(i[6])] for i in self.db.execute('SELECT * FROM gammas WHERE isotope=? AND isomer=?',(self.isotope,self.isomer))]\n\t\tgammas = list(self.meta['gm'])\n\t\tfor n,L in enumerate([E_lim,I_lim]):\n\t\t\tif L[0] is not None:\n\t\t\t\tgammas = [g for g in gammas if g[n]>=L[0]]\n\t\t\tif L[1] is not None:\n\t\t\t\tgammas = [g for g in gammas if g[n]<=L[1]]\n\t\tif not xrays:\n\t\t\tgammas = [g for g in gammas if g[3]=='']\n\t\treturn {l:[g[n] for g in gammas if abs(g[0]-511.0)>=dE_511] for n,l in enumerate(['E','I','dI','notes'])}\n\n\tdef electrons(self,I_lim=(None,None),E_lim=(None,None),CE_only=False,Auger_only=False):\n\t\t\"\"\"Description\n\n\t\t...\n\n\t\tParameters\n\t\t----------\n\t\tx : type\n\t\t\tDescription of parameter `x`.\n\n\t\tReturns\n\t\t-------\n\n\t\tNotes\n\t\t-----\n\n\t\tReferences\n\t\t----------\n\n\t\tExamples\n\t\t--------\n\n\t\t\"\"\"\n\n\t\tif self.meta['el'] is None:\n\t\t\tself.meta['el'] = [[float(i[3]),float(i[4]),float(i[5]),str(i[6])] for i in self.db.execute('SELECT * FROM electrons WHERE isotope=? AND isomer=?',(self.isotope,self.isomer))]\n\t\telectrons = list(self.meta['el'])\n\t\tfor n,L in enumerate([E_lim,I_lim]):\n\t\t\tif L[0] is not None:\n\t\t\t\telectrons = [e for e in electrons if e[n]>=L[0]]\n\t\t\tif L[1] is not None:\n\t\t\t\telectrons = [e for e in electrons if e[n]<=L[1]]\n\t\tif CE_only:\n\t\t\telectrons = [e for e in electrons if e[3].startswith('CE')]\n\t\tif Auger_only:\n\t\t\telectrons = [e for e in electrons if e[3].startswith('Aug')]\n\t\treturn {l:[e[n]for e in electrons] for n,l in enumerate(['E','I','dI','notes'])}\n\n\tdef beta_minus(self,I_lim=(None,None),Endpoint_lim=(None,None)):\n\t\t\"\"\"Description\n\n\t\t...\n\n\t\tParameters\n\t\t----------\n\t\tx : type\n\t\t\tDescription of parameter `x`.\n\n\t\tReturns\n\t\t-------\n\n\t\tNotes\n\t\t-----\n\n\t\tReferences\n\t\t----------\n\n\t\tExamples\n\t\t--------\n\n\t\t\"\"\"\n\n\t\tif self.meta['bm'] is None:\n\t\t\tself.meta['bm'] = [[float(i[3]),float(i[4]),float(i[5]),float(i[6])] for i in self.db.execute('SELECT * FROM beta_minus WHERE isotope=? AND isomer=?',(self.isotope,self.isomer))]\n\t\tbetas = list(self.meta['bm'])\n\t\tfor n,L in zip([3,1],[Endpoint_lim,I_lim]):\n\t\t\tif L[0] is not None:\n\t\t\t\tbetas = [b for b in betas if b[n]>=L[0]]\n\t\t\tif L[1] is not None:\n\t\t\t\tbetas = [b for b in betas if b[n]<=L[1]]\n\t\treturn {l:[b[n] for b in betas] for n,l in enumerate(['muE','I','dI','endE'])}\n\n\tdef beta_plus(self, I_lim=(None,None), Endpoint_lim=(None,None)):\n\t\t\"\"\"Description\n\n\t\t...\n\n\t\tParameters\n\t\t----------\n\t\tx : type\n\t\t\tDescription of parameter `x`.\n\n\t\tReturns\n\t\t-------\n\n\t\tNotes\n\t\t-----\n\n\t\tReferences\n\t\t----------\n\n\t\tExamples\n\t\t--------\n\n\t\t\"\"\"\n\n\t\tif self.meta['bp'] is None:\n\t\t\tself.meta['bp'] = [[float(i[3]),float(i[4]),float(i[5]),float(i[6])] for i in self.db.execute('SELECT * FROM beta_plus WHERE isotope=? AND isomer=?',(self.isotope,self.isomer))]\n\t\tbetas = list(self.meta['bp'])\n\t\tfor n,L in zip([3,1],[Endpoint_lim,I_lim]):\n\t\t\tif L[0] is not None:\n\t\t\t\tbetas = [b for b in betas if b[n]>=L[0]]\n\t\t\tif L[1] is not None:\n\t\t\t\tbetas = [b for b in betas if b[n]<=L[1]]\n\t\treturn {l:[b[n] for b in betas] for n,l in enumerate(['muE','I','dI','endE'])}\n\n\tdef alphas(self, I_lim=(None,None), E_lim=(None,None)):\n\t\t\"\"\"Description\n\n\t\t...\n\n\t\tParameters\n\t\t----------\n\t\tx : type\n\t\t\tDescription of parameter `x`.\n\n\t\tReturns\n\t\t-------\n\n\t\tNotes\n\t\t-----\n\n\t\tReferences\n\t\t----------\n\n\t\tExamples\n\t\t--------\n\n\t\t\"\"\"\n\n\t\tif self.meta['al'] is None:\n\t\t\tself.meta['al'] = [[float(i[3]),float(i[4]),float(i[5])] for i in self.db.execute('SELECT * FROM alphas WHERE isotope=? AND isomer=?',(self.isotope,self.isomer))]\n\t\talphas = list(self.meta['al'])\n\t\tfor n,L in enumerate([E_lim,I_lim]):\n\t\t\tif L[0] is not None:\n\t\t\t\talphas = [a for a in alphas if a[n]>=L[0]]\n\t\t\tif L[1] is not None:\n\t\t\t\talphas = [a for a in alphas if a[n]<=L[1]]\n\t\treturn {l:[a[n] for a in alphas] for n,l in enumerate(['E','I','dI'])}\n\n\tdef dose_rate(self, activity=1.0, distance=30.0, units='R/hr'):\n\t\t\"\"\"Description\n\n\t\t...\n\n\t\tParameters\n\t\t----------\n\t\tx : type\n\t\t\tDescription of parameter `x`.\n\n\t\tReturns\n\t\t-------\n\n\t\tNotes\n\t\t-----\n\n\t\tReferences\n\t\t----------\n\n\t\tExamples\n\t\t--------\n\n\t\t\"\"\"\n\n\t\tdef beta2(E_MeV, m_amu):\n\t\t\treturn 1.0-(1.0/(1.0+(E_MeV/m_amu))**2)\n\n\t\tdef e_range(E_keV):\n\t\t\tdEdx = lambda b2, t: 0.17*((np.log(3.61E5*t*np.sqrt(t+2)))+(0.5*(1-b2)*(1+t**2/8-(2*t+1)*np.log(2)))-4.312)/b2\n\t\t\tE = np.linspace(1E-12, E_keV*1E-3, 100)\n\t\t\treturn np.trapz(1.0/((1.0+(E*7.22/800.0))*dEdx(beta2(E, 0.5109), E/0.5109)), E)\n\n\t\tdef pos_range(E_keV):\n\t\t\tdEdx = lambda b2, t: 0.17*((np.log(3.61E5*t*np.sqrt(t+2)))+(np.log(2)-(b2/24)*(23+14/(t+2)+10/(t+2)**2+4/(t+2)**3))-4.312)/b2\n\t\t\tE = np.linspace(1E-12, E_keV*1E-3, 100)\n\t\t\treturn np.trapz(1.0/((1.0+(E*7.22/800.0))*dEdx(beta2(E, 0.5109), E/0.5109)), E)\n\n\t\tdef alpha_range(E_keV):\n\t\t\tdEdx = lambda b2: 0.17*4.0*((np.log(1.02E6*b2/(1.0-b2))-b2)-4.312)/b2\n\t\t\treturn np.trapz(1.0/dEdx(beta2(np.linspace(1E-9, E_keV*1E-3, 100), 3.7284E3)), np.linspace(1E-9, E_keV*1E-3, 100))\n\n\t\tdose = {}\n\t\tgm = self.gammas(xrays=True, dE_511=0.0)\n\t\tal = self.alphas()\n\t\tbm = self.beta_minus()\n\t\tbp = self.beta_plus()\n\t\tel = self.electrons()\n\n\t\tdose['gammas'] = 1.4042E-12*np.sum(np.array(gm['E'])*np.array(gm['I']))*activity/distance**2\n\t\tdose['alphas'] = 5.2087E-14*np.sum([al['I'][n]*e/alpha_range(e) for n,e in enumerate(al['E'])])*activity/distance**2\n\t\tdose['beta_minus'] = 5.2087E-14*np.sum([bm['I'][n]*e/e_range(e) for n,e in enumerate(bm['muE'])])*activity/distance**2\n\t\tdose['beta_plus'] = 5.2087E-14*np.sum([bp['I'][n]*e/pos_range(e) for n,e in enumerate(bp['muE'])])*activity/distance**2\n\t\tdose['electrons'] = 5.2087E-14*np.sum([el['I'][n]*e/e_range(e) for n,e in enumerate(el['E'])])*activity/distance**2\n\t\treturn dose\n\n\n", "meta": {"hexsha": "9a9503a1fc2ee81a3e03f84c743956c27b8ca158", "size": 13485, "ext": "py", "lang": "Python", "max_stars_repo_path": "npat/isotope.py", "max_stars_repo_name": "CallumCordwell/npat", "max_stars_repo_head_hexsha": "9990ed982948389af78cc456fd579b98732b6490", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-27T15:00:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-27T15:00:30.000Z", "max_issues_repo_path": "npat/isotope.py", "max_issues_repo_name": "CallumCordwell/npat", "max_issues_repo_head_hexsha": "9990ed982948389af78cc456fd579b98732b6490", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "npat/isotope.py", "max_forks_repo_name": "CallumCordwell/npat", "max_forks_repo_head_hexsha": "9990ed982948389af78cc456fd579b98732b6490", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-06-27T17:29:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-15T10:42:23.000Z", "avg_line_length": 21.4047619048, "max_line_length": 181, "alphanum_fraction": 0.5842788283, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.32423540551084407, "lm_q1q2_score": 0.18971051468946915}}
{"text": "# Copyright (c) FULIUCANSHENG.\n# Licensed under the MIT License.\n\nimport logging\nimport math\nimport time\nimport numpy as np\nimport torch\nimport torchvision\nfrom torch import nn, Tensor\nfrom typing import List, Dict, Tuple\n\nfrom detectron2.config import configurable\nfrom detectron2.layers import ShapeSpec, Conv2d\nfrom detectron2.modeling.meta_arch.build import META_ARCH_REGISTRY\nfrom detectron2.modeling.backbone import Backbone\nfrom detectron2.structures import ImageList, Instances, Boxes\nfrom detectron2.utils.events import get_event_storage\nfrom detectron2.data.detection_utils import convert_image_to_rgb\nfrom detectron2.modeling.postprocessing import detector_postprocess\nfrom detectron2.modeling import build_backbone\n\n\nclass YoloV5Head(nn.Module):\n    @configurable\n    def __init__(\n        self,\n        *,\n        input_shape: List[ShapeSpec],\n        nc,\n        anchors,\n    ):\n\n        super().__init__()\n        self.nc = nc  # number of classes\n        self.no = nc + 5  # number of outputs per anchor\n        self.nl = len(anchors)  # number of detection layers\n        assert self.nl == len(input_shape)\n        self.na = len(anchors[0]) // 2  # number of anchors\n        self.grid = [torch.zeros(1)] * self.nl  # init grid\n        a = torch.tensor(anchors).float().view(self.nl, -1, 2)\n        self.register_buffer(\"anchors\", a)  # shape(nl,na,2)\n        self.register_buffer(\"anchor_grid\", a.clone().view(self.nl, 1, -1, 1, 1, 2))  # shape(nl,1,na,1,1,2)\n        ch = [x.channels for x in input_shape]\n        self.m = nn.ModuleList(Conv2d(x, self.no * self.na, 1) for x in ch)\n\n    @classmethod\n    def from_config(cls, cfg, input_shape: List[ShapeSpec]):\n        nc = cfg.MODEL.YOLOV5.NUM_CLASSES\n        anchors = cfg.MODEL.YOLOV5.ANCHORS\n        return {\n            \"input_shape\": input_shape,\n            \"nc\": nc,\n            \"anchors\": anchors,\n        }\n\n    def forward(self, x: List[Tensor]):\n        \"\"\"\n        Arguments:\n            features (list[Tensor]): FPN feature map tensors in high to low resolution.\n                Each tensor in the list correspond to different feature levels.\n        Returns:\n            x (list[Tensor]): #nl tensors,\n                                each having shape [N, na, Hi, Wi, nc + 5]\n            z (Tensor) : [N, nl*na*(sum of grid sizes) , no] indictaing\n                    1. Box position z[..., 0:2]\n                    2. Box width and height z[..., 2:4]\n                    3. Objectness z[..., 5]\n                    4. Class probabilities z[..., 6:]\n        \"\"\"\n        for i in range(self.nl):\n            x[i] = self.m[i](x[i])  # conv\n            bs, _, ny, nx = x[i].shape  # x(bs,255,20,20) to x(bs,3,20,20,85)\n            x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()\n        return x\n\n    @staticmethod\n    def _make_grid(nx=20, ny=20):\n        yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])\n        return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()\n\n    def _initialize_biases(self, cf=None):  # initialize biases into Detect(), cf is class frequency\n        # https://arxiv.org/abs/1708.02002 section 3.3\n        # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.\n        for mi, s in zip(self.m, self.stride):  # from\n            b = mi.bias.view(self.na, -1)  # conv.bias(255) to (3,85)\n            b.data[:, 4] += math.log(8 / (640 / s) ** 2)  # obj (8 objects per 640 image)\n            b.data[:, 5:] += math.log(0.6 / (self.nc - 0.99)) if cf is None else torch.log(cf / cf.sum())  # cls\n            mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)\n\n\ndef xywh2xyxy(x):\n    # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[:, 0] = x[:, 0] - x[:, 2] / 2  # top left x\n    y[:, 1] = x[:, 1] - x[:, 3] / 2  # top left y\n    y[:, 2] = x[:, 0] + x[:, 2] / 2  # bottom right x\n    y[:, 3] = x[:, 1] + x[:, 3] / 2  # bottom right y\n    return y\n\n\ndef non_max_suppression(\n    prediction,\n    conf_thres=0.25,\n    iou_thres=0.45,\n    classes=None,\n    agnostic=False,\n    multi_label=False,\n    labels=(),\n    max_det=300,\n):\n    \"\"\"Runs Non-Maximum Suppression (NMS) on inference results\n        conf_thresh - 0.1 (for yolov4)\n        iou_thresh - 0.6 (for yolov4)\n        multi_label - not in yolov4\n        merge = False - in yolov4 not in yolov3\n        Labesl = () not in yolov4\n    Returns:\n         list of detections, on (n,6) tensor per image [xyxy, conf, cls]\n    \"\"\"\n    # if yolov3 or yolov5:\n    nc = prediction.shape[2] - 5  # number of classes\n    # else\n    nc = prediction[0].shape[1] - 5  # Number of classes\n    xc = prediction[..., 4] > conf_thres  # candidates\n\n    # Checks\n    assert 0 <= conf_thres <= 1, f\"Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0\"\n    assert 0 <= iou_thres <= 1, f\"Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0\"\n\n    # Settings\n    # (pixels) minimum and maximum box width and height\n    _, max_wh = 2, 4096\n    max_nms = 30000  # maximum number of boxes into torchvision.ops.nms()\n    time_limit = 10.0  # seconds to quit after\n    redundant = True  # require redundant detections\n    multi_label &= nc > 1  # multiple labels per box (adds 0.5ms/img)\n    merge = False  # use merge-NMS\n\n    t = time.time()\n    output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0]\n    for xi, x in enumerate(prediction):  # image index, image inference\n        # Apply constraints\n        # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0  # width-height\n        x = x[xc[xi]]  # confidence\n\n        # Cat apriori labels if autolabelling - Not used in the YOLOV4\n        if labels and len(labels[xi]):\n            l_ = labels[xi]\n            v = torch.zeros((len(l_), nc + 5), device=x.device)\n            v[:, :4] = l_[:, 1:5]  # box\n            v[:, 4] = 1.0  # conf\n            v[range(len(l_)), l_[:, 0].long() + 5] = 1.0  # cls\n            x = torch.cat((x, v), 0)\n        #################################################################\n        # If none remain process next image\n        if not x.shape[0]:\n            continue\n\n        # Compute conf\n        x[:, 5:] *= x[:, 4:5]  # conf = obj_conf * cls_conf\n\n        # Box (center x, center y, width, height) to (x1, y1, x2, y2)\n        box = xywh2xyxy(x[:, :4])\n\n        # Detections matrix nx6 (xyxy, conf, cls)\n        if multi_label:\n            i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T\n            x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)\n        else:  # best class only\n            conf, j = x[:, 5:].max(1, keepdim=True)\n            x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]\n\n        # Filter by class\n        if classes is not None:\n            x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]\n\n        # Apply finite constraint\n        # if not torch.isfinite(x).all():\n        #     x = x[torch.isfinite(x).all(1)]\n\n        # Check shape\n        n = x.shape[0]  # number of boxes\n        if not n:  # no boxes\n            continue\n        # #### Not in Yolov4 ######################\n        elif n > max_nms:  # excess boxes\n            # sort by confidence\n            x = x[x[:, 4].argsort(descending=True)[:max_nms]]\n        ###############################################\n        # Batched NMS\n        c = x[:, 5:6] * (0 if agnostic else max_wh)  # classes\n        # boxes (offset by class), scores\n        boxes, scores = x[:, :4] + c, x[:, 4]\n        i = torchvision.ops.nms(boxes, scores, iou_thres)  # NMS\n        if i.shape[0] > max_det:  # limit detections\n            i = i[:max_det]\n        if merge and (1 < n < 3e3):  # Merge NMS (boxes merged using weighted mean)\n            # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)\n            iou = box_iou(boxes[i], boxes) > iou_thres  # iou matrix\n            weights = iou * scores[None]  # box weights\n            x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True)  # merged boxes\n            if redundant:\n                i = i[iou.sum(1) > 1]  # require redundancy\n\n        output[xi] = x[i]\n        if (time.time() - t) > time_limit:\n            print(f\"WARNING: NMS time limit {time_limit}s exceeded\")\n            break  # time limit exceeded\n\n    return output\n\n\ndef bbox_iou(\n    box1,\n    box2,\n    x1y1x2y2=True,\n    GIoU=False,\n    DIoU=False,\n    CIoU=False,\n    EIoU=False,\n    ECIoU=False,\n    eps=1e-7,\n):\n    # eps default value used in yolov4 is 1e-9\n    # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4\n    box2 = box2.T\n\n    # Get the coordinates of bounding boxes\n    if x1y1x2y2:  # x1, y1, x2, y2 = box1\n        b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]\n        b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]\n    else:  # transform from xywh to xyxy\n        b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2\n        b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2\n        b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2\n        b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2\n\n    # Intersection area\n    inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * (\n        torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)\n    ).clamp(0)\n\n    # Union Area\n    w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps\n    w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps\n    union = w1 * h1 + w2 * h2 - inter + eps\n\n    iou = inter / union\n    if GIoU or DIoU or CIoU or EIoU or ECIoU:\n        # convex (smallest enclosing box) width\n        cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1)\n        ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1)  # convex height\n        if CIoU or DIoU or EIoU or ECIoU:  # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1\n            c2 = cw ** 2 + ch ** 2 + eps  # convex diagonal squared\n            rho2 = (\n                (b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2\n            ) / 4  # center distance squared\n            if DIoU:\n                return iou - rho2 / c2  # DIoU\n            elif CIoU:  # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47\n                v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)\n                with torch.no_grad():\n                    alpha = v / (v - iou + (1 + eps))\n                return iou - (rho2 / c2 + v * alpha)  # CIoU\n\n            # ################### Function from Yolov4 ###########################################\n            elif EIoU:  # Efficient IoU https://arxiv.org/abs/2101.08158\n                rho3 = (w1 - w2) ** 2\n                c3 = cw ** 2 + eps\n                rho4 = (h1 - h2) ** 2\n                c4 = ch ** 2 + eps\n                return iou - rho2 / c2 - rho3 / c3 - rho4 / c4  # EIoU\n            elif ECIoU:\n                v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)\n                with torch.no_grad():\n                    alpha = v / ((1 + eps) - iou + v)\n                rho3 = (w1 - w2) ** 2\n                c3 = cw ** 2 + eps\n                rho4 = (h1 - h2) ** 2\n                c4 = ch ** 2 + eps\n                return iou - v * alpha - rho2 / c2 - rho3 / c3 - rho4 / c4  # ECIoU\n            ############################################################################################\n        else:  # GIoU https://arxiv.org/pdf/1902.09630.pdf\n            c_area = cw * ch + eps  # convex area\n            return iou - (c_area - union) / c_area  # GIoU\n    else:\n        return iou  # IoU\n\n\ndef smooth_BCE(\n    eps=0.1,\n):  # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441\n    # return positive, negative label smoothing BCE targets\n    return 1.0 - 0.5 * eps, 0.5 * eps\n\n\nclass FocalLoss(nn.Module):\n    # Wraps focal loss around existing loss_fcn(), i.e. criteria =\n    # FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)\n    def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):\n        super().__init__()\n        self.loss_fcn = loss_fcn  # must be nn.BCEWithLogitsLoss()\n        self.gamma = gamma\n        self.alpha = alpha\n        self.reduction = loss_fcn.reduction\n        self.loss_fcn.reduction = \"none\"  # required to apply FL to each element\n\n    def forward(self, pred, true):\n        loss = self.loss_fcn(pred, true)\n        # p_t = torch.exp(-loss)\n        # loss *= self.alpha * (1.000001 - p_t) ** self.gamma  # non-zero power\n        # for gradient stability\n\n        # TF implementation\n        # https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py\n        pred_prob = torch.sigmoid(pred)  # prob from logits\n        p_t = true * pred_prob + (1 - true) * (1 - pred_prob)\n        alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)\n        modulating_factor = (1.0 - p_t) ** self.gamma\n        loss *= alpha_factor * modulating_factor\n\n        if self.reduction == \"mean\":\n            return loss.mean()\n        elif self.reduction == \"sum\":\n            return loss.sum()\n        else:  # 'none'\n            return loss\n\n\nclass ComputeLoss(object):\n    # Compute losses\n\n    @configurable\n    def __init__(\n        self,\n        *,\n        focal_loss_gamma,\n        box_loss_gain,\n        cls_loss_gain,\n        cls_positive_weight,\n        obj_loss_gain,\n        obj_positive_weight,\n        label_smoothing=0.0,\n        gr,\n        na,\n        nc,\n        nl,\n        anchors,\n        anchor_t,\n        autobalance=False,\n    ):\n        super().__init__()\n        self.sort_obj_iou = False\n        self.na = na\n        self.nc = nc\n        self.nl = nl\n        self.anchors = anchors\n        self.box_loss_gain = box_loss_gain\n        self.cls_loss_gain = cls_loss_gain\n        self.obj_loss_gain = obj_loss_gain\n        self.anchor_t = anchor_t\n\n        # Define criteria\n        BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([cls_positive_weight]))\n        BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([obj_positive_weight]))\n\n        # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3\n        # positive, negative BCE targets\n        self.cp, self.cn = smooth_BCE(eps=label_smoothing)\n\n        # Focal loss\n        if focal_loss_gamma > 0:\n            BCEcls = FocalLoss(BCEcls, focal_loss_gamma)\n            BCEobj = FocalLoss(BCEobj, focal_loss_gamma)\n\n        # Detect() module\n        self.balance = {3: [4.0, 1.0, 0.4]}.get(nl, [4.0, 1.0, 0.25, 0.06, 0.02])  # P3-P7\n        self.ssi = 0  # stride 16 index\n        self.BCEcls, self.BCEobj, self.gr, self.autobalance = (\n            BCEcls,\n            BCEobj,\n            gr,\n            autobalance,\n        )\n\n    @classmethod\n    def from_config(cls, cfg, head):\n        return {\n            \"focal_loss_gamma\": cfg.MODEL.YOLOV5.FOCAL_LOSS_GAMMA,\n            \"box_loss_gain\": cfg.MODEL.YOLOV5.BOX_LOSS_GAIN,\n            \"cls_loss_gain\": cfg.MODEL.YOLOV5.CLS_LOSS_GAIN,\n            \"cls_positive_weight\": cfg.MODEL.YOLOV5.CLS_POSITIVE_WEIGHT,\n            \"obj_loss_gain\": cfg.MODEL.YOLOV5.OBJ_LOSS_GAIN,\n            \"obj_positive_weight\": cfg.MODEL.YOLOV5.OBJ_POSITIVE_WEIGHT,\n            \"label_smoothing\": cfg.MODEL.YOLOV5.LABEL_SMOOTHING,\n            \"gr\": 1.0,\n            \"na\": head.na,\n            \"nc\": head.nc,\n            \"nl\": head.nl,\n            \"anchors\": head.anchors,\n            \"anchor_t\": cfg.MODEL.YOLOV5.ANCHOR_T,\n            \"autobalance\": False,\n        }\n\n    def _initialize_ssi(self, stride):\n        if self.autobalance:\n            self.ssi = list(stride).index(16)\n\n    def __call__(self, p, instances):  # predictions, targets, model is ignored\n        device = instances[0].gt_boxes.device\n        self.to(device)\n        lcls, lbox, lobj = (\n            torch.zeros(1, device=device),\n            torch.zeros(1, device=device),\n            torch.zeros(1, device=device),\n        )\n        tcls, tbox, indices, anchors = self.build_targets(p, instances)  # targets\n\n        # Losses\n        for i, pi in enumerate(p):  # layer index, layer predictions\n            b, a, gj, gi = indices[i]  # image, anchor, gridy, gridx\n            tobj = torch.zeros_like(pi[..., 0], device=device)  # target obj\n\n            n = b.shape[0]  # number of targets\n            if n:\n                # prediction subset corresponding to targets\n                ps = pi[b, a, gj, gi]\n\n                # Regression\n                pxy = ps[:, :2].sigmoid() * 2.0 - 0.5\n                pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]\n                pbox = torch.cat((pxy, pwh), 1)  # predicted box\n                # iou(prediction, target)\n                iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True)\n                lbox += (1.0 - iou).mean()  # iou loss\n\n                # Objectness\n                score_iou = iou.detach().clamp(0).type(tobj.dtype)\n                if self.sort_obj_iou:\n                    sort_id = torch.argsort(score_iou)\n                    b, a, gj, gi, score_iou = (\n                        b[sort_id],\n                        a[sort_id],\n                        gj[sort_id],\n                        gi[sort_id],\n                        score_iou[sort_id],\n                    )\n                tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * score_iou  # iou ratio\n\n                # Classification\n                if self.nc > 1:  # cls loss (only if multiple classes)\n                    t = torch.full_like(ps[:, 5:], self.cn, device=device)  # targets\n                    t[range(n), tcls[i]] = self.cp\n                    lcls += self.BCEcls(ps[:, 5:], t)  # BCE\n\n                # Append targets to text file\n                # with open('targets.txt', 'a') as file:\n                #     [file.write('%11.5g ' * 4 % tuple(x) + '\\n') for x in torch.cat((txy[i], twh[i]), 1)]\n\n            obji = self.BCEobj(pi[..., 4], tobj)\n            lobj += obji * self.balance[i]  # obj loss\n            if self.autobalance:\n                self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()\n\n        if self.autobalance:\n            self.balance = [x / self.balance[self.ssi] for x in self.balance]\n        lbox *= self.box_loss_gain\n        lobj *= self.obj_loss_gain\n        lcls *= self.cls_loss_gain\n        # bs = tobj.shape[0]  # batch size\n\n        # loss = lbox + lobj + lcls\n        # return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()\n        return {\n            \"loss_box\": lbox,\n            \"loss_obj\": lobj,\n            \"loss_cls\": lcls,\n        }\n\n    def build_targets(self, p, gt_instances):\n        \"\"\"\n        Args:\n            p (list[Tensors]): A list of #feature level predictions\n            gt_instances (list[Instances]): a list of N `Instances`s. The i-th\n                `Instances` contains the ground-truth per-instance annotations\n                for the i-th input image.\n        \"\"\"\n        # Build targets for compute_loss(), input targets(image,class,x,y,w,h)\n        targets = []\n        for i, gt_per_image in enumerate(gt_instances):\n            # Convert the boxes to target format of shape [sum(nL per image), 6]\n            # where each target entry is [img_index, class, x, y, w, h],\n            # x, y, w, h - relative and x, y are centers\n            if len(gt_per_image) > 0:\n                boxes = gt_per_image.gt_boxes.tensor.clone()\n                h, w = gt_per_image.image_size\n                boxes[:, 0:2] = (boxes[:, 0:2] + boxes[:, 2:4]) / 2\n                boxes[:, 2:4] = (boxes[:, 2:4] - boxes[:, 0:2]) * 2\n                boxes[:, ::2] /= float(w)\n                boxes[:, 1::2] /= float(h)\n                classes = torch.unsqueeze(gt_per_image.gt_classes.clone(), dim=1)\n                t = torch.cat([torch.ones_like(classes) * i, classes, boxes], dim=1)\n                targets.append(t)\n        targets = torch.cat(targets, 0)\n\n        na, nt = self.na, targets.shape[0]  # number of anchors, targets\n        tcls, tbox, indices, anch = [], [], [], []\n        # normalized to gridspace gain\n        gain = torch.ones(7, device=targets.device)\n        ai = (\n            torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt)\n        )  # same as .repeat_interleave(nt)\n        # append anchor indices\n        targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2)\n\n        g = 0.5  # bias\n        off = (\n            torch.tensor(\n                [\n                    [0, 0],\n                    [1, 0],\n                    [0, 1],\n                    [-1, 0],\n                    [0, -1],  # j,k,l,m\n                    # [1, 1], [1, -1], [-1, 1], [-1, -1],  # jk,jm,lk,lm\n                ],\n                device=targets.device,\n            ).float()\n            * g\n        )  # offsets\n\n        for i in range(self.nl):\n            anchors = self.anchors[i]\n            gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]]  # xyxy gain\n\n            # Match targets to anchors\n            t = targets * gain\n            if nt:\n                # Matches\n                r = t[:, :, 4:6] / anchors[:, None]  # wh ratio\n                j = torch.max(r, 1.0 / r).max(2)[0] < self.anchor_t  # compare\n                # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t']  #\n                # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))\n                t = t[j]  # filter\n\n                # Offsets\n                gxy = t[:, 2:4]  # grid xy\n                gxi = gain[[2, 3]] - gxy  # inverse\n                j, k = ((gxy % 1.0 < g) & (gxy > 1.0)).T\n                l, m = ((gxi % 1.0 < g) & (gxi > 1.0)).T\n                j = torch.stack((torch.ones_like(j), j, k, l, m))\n                t = t.repeat((5, 1, 1))[j]\n                offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]\n            else:\n                t = targets[0]\n                offsets = 0\n\n            # Define\n            b, c = t[:, :2].long().T  # image, class\n            gxy = t[:, 2:4]  # grid xy\n            gwh = t[:, 4:6]  # grid wh\n            gij = (gxy - offsets).long()\n            gi, gj = gij.T  # grid xy indices\n\n            # Append\n            a = t[:, 6].long()  # anchor indices\n            # image, anchor, grid indices\n            indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1)))\n            tbox.append(torch.cat((gxy - gij, gwh), 1))  # box\n            anch.append(anchors[a])  # anchors\n            tcls.append(c)  # class\n\n        return tcls, tbox, indices, anch\n\n    def to(self, device):\n        self.anchors = self.anchors.to(device)\n        self.BCEcls.pos_weight = self.BCEcls.pos_weight.to(device)\n        self.BCEobj.pos_weight = self.BCEobj.pos_weight.to(device)\n\n\n@META_ARCH_REGISTRY.register()\nclass YoloV5(nn.Module):\n    \"\"\"\n    Implement YoloV5\n    \"\"\"\n\n    @configurable\n    def __init__(\n        self,\n        *,\n        backbone: Backbone,\n        head: nn.Module,\n        loss,\n        num_classes,\n        conf_thres,\n        iou_thres,\n        pixel_mean,\n        pixel_std,\n        vis_period=0,\n        input_format=\"BGR\",\n    ):\n        super().__init__()\n\n        self.backbone = backbone\n        self.head = head\n\n        self.num_classes = num_classes\n        self.single_cls = num_classes == 1\n        # Inference Parameters\n        self.conf_thres = conf_thres\n        self.iou_thres = iou_thres\n        # Vis parameters\n        self.vis_period = vis_period\n        self.input_format = input_format\n\n        self.register_buffer(\"pixel_mean\", torch.tensor(pixel_mean).view(-1, 1, 1), False)\n        self.register_buffer(\"pixel_std\", torch.tensor(pixel_std).view(-1, 1, 1), False)\n\n        \"\"\"\n        In Detectron1, loss is normalized by number of foreground samples in the batch.\n        When batch size is 1 per GPU, #foreground has a large variance and\n        using it lead to lower performance. Here we maintain an EMA of #foreground to\n        stabilize the normalizer.\n        \"\"\"\n        self.loss = loss\n        # self.loss_normalizer = 100  # initialize with any reasonable #fg that's not too small\n        # self.loss_normalizer_momentum = 0.9\n        self.init_stride()\n        self.apply(self._init_weights)\n\n    def _init_weights(self, module):\n        \"\"\"Initialize the weights\"\"\"\n        if isinstance(module, nn.BatchNorm2d):\n            module.eps = 1e-3\n            module.momentum = 0.03\n\n    @classmethod\n    def from_config(cls, cfg):\n        backbone = build_backbone(cfg)\n        backbone_shape = backbone.output_shape()\n        feature_shapes = list(backbone_shape.values())\n        head = YoloV5Head(cfg, feature_shapes)\n        loss = ComputeLoss(cfg, head)\n        return {\n            \"backbone\": backbone,\n            \"head\": head,\n            \"loss\": loss,\n            \"num_classes\": head.nc,\n            \"conf_thres\": cfg.MODEL.YOLOV5.CONF_THRESH,\n            \"iou_thres\": cfg.MODEL.YOLOV5.IOU_THRES,\n            \"pixel_mean\": cfg.MODEL.PIXEL_MEAN,\n            \"pixel_std\": cfg.MODEL.PIXEL_STD,\n            \"vis_period\": cfg.VIS_PERIOD,\n            \"input_format\": cfg.INPUT.FORMAT,\n        }\n\n    @property\n    def device(self):\n        return self.pixel_mean.device\n\n    def visualize_training(self, batched_inputs, results):\n        \"\"\"\n        A function used to visualize ground truth images and final network predictions.\n        It shows ground truth bounding boxes on the original image and up to 20\n        predicted object bounding boxes on the original image.\n        Args:\n            batched_inputs (list): a list that contains input to the model.\n            results (List[Instances]): a list of #images elements.\n        \"\"\"\n        from detectron2.utils.visualizer import Visualizer\n\n        assert len(batched_inputs) == len(results), \"Cannot visualize inputs and results of different sizes\"\n        storage = get_event_storage()\n        max_boxes = 20\n\n        image_index = 0  # only visualize a single image\n        img = batched_inputs[image_index][\"image\"]\n        img = convert_image_to_rgb(img.permute(1, 2, 0), self.input_format)\n        v_gt = Visualizer(img, None)\n        v_gt = v_gt.overlay_instances(boxes=batched_inputs[image_index][\"instances\"].gt_boxes)\n        anno_img = v_gt.get_image()\n        processed_results = detector_postprocess(results[image_index], img.shape[0], img.shape[1])\n        predicted_boxes = processed_results.pred_boxes.tensor.detach().cpu().numpy()\n\n        v_pred = Visualizer(img, None)\n        v_pred = v_pred.overlay_instances(boxes=predicted_boxes[0:max_boxes])\n        prop_img = v_pred.get_image()\n        vis_img = np.vstack((anno_img, prop_img))\n        vis_img = vis_img.transpose(2, 0, 1)\n        vis_name = f\"Top: GT bounding boxes; Bottom: {max_boxes} Highest Scoring Results\"\n        storage.put_image(vis_name, vis_img)\n\n    def init_stride(self):\n        s = 256  # 2x min stride\n        dummy_input = torch.zeros(1, len(self.pixel_mean), s, s)\n        features = self.backbone(dummy_input)\n        features = list(features.values())\n        pred = self.head(features)\n        self.head.stride = torch.tensor([s / x.shape[-2] for x in pred])  # forward\n        self.head.anchors /= self.head.stride.view(-1, 1, 1)\n        self.stride = self.head.stride\n        self.head._initialize_biases()  # only run once\n        self.loss._initialize_ssi(self.stride)\n\n    def forward(self, batched_inputs: Tuple[Dict[str, Tensor]]):\n        \"\"\"\n        Args:\n            batched_inputs: a list, batched outputs of :class:`DatasetMapper` .\n                Each item in the list contains the inputs for one image.\n                For now, each item in the list is a dict that contains:\n                * image: Tensor, image in (C, H, W) format.\n                * instances: Instances\n                Other information that's included in the original dicts, such as:\n                * \"height\", \"width\" (int): the output resolution of the model, used in inference.\n                  See :meth:`postprocess` for details.\n        Returns:\n            In training, dict[str, Tensor]: mapping from a named loss to a tensor storing the\n            loss. Used during training only. In inference, the standard output format, described\n            in :doc:`/tutorials/models`.\n        \"\"\"\n        images = self.preprocess_image(batched_inputs)\n        features = self.backbone(images.tensor)\n        features = list(features.values())\n\n        pred = self.head(features)\n\n        if self.training:\n            assert not torch.jit.is_scripting(), \"Not supported\"\n            assert \"instances\" in batched_inputs[0], \"Instance annotations are missing in training!\"\n            gt_instances = [x[\"instances\"].to(self.device) for x in batched_inputs]\n\n            losses = self.loss(pred, gt_instances)\n\n            if self.vis_period > 0:\n                storage = get_event_storage()\n                if storage.iter % self.vis_period == 0:\n                    results = self.inference(pred, images.image_sizes)\n                    self.visualize_training(batched_inputs, results)\n\n            return losses\n        else:\n            results = self.inference(pred, images.image_sizes)\n            if torch.jit.is_scripting():\n                return results\n            processed_results = []\n            for results_per_image, input_per_image, image_size in zip(results, batched_inputs, images.image_sizes):\n                height = input_per_image.get(\"height\", image_size[0])\n                width = input_per_image.get(\"width\", image_size[1])\n                r = detector_postprocess(results_per_image, height, width)\n                processed_results.append({\"instances\": r})\n            return processed_results\n\n    def inference(self, x, image_sizes):\n        \"\"\"\n        Returns:\n        z (Tensor) : [N, nl*na*(sum of grid sizes) , no] indictaing\n                    1. Box position z[..., 0:2]\n                    2. Box width and height z[..., 2:4]\n                    3. Objectness z[..., 5]\n                    4. Class probabilities z[..., 6:]\n        \"\"\"\n        z = []\n        for i in range(self.head.nl):\n            # x(bs,na,ny,nx,no)\n            bs, _, ny, nx, _ = x[i].shape\n            if self.head.grid[i].shape[2:4] != x[i].shape[2:4]:\n                self.head.grid[i] = self.head._make_grid(nx, ny).to(x[i].device)\n\n            y = x[i].sigmoid()\n            # if self.head.inplace:\n            y[..., 0:2] = (y[..., 0:2] * 2.0 - 0.5 + self.head.grid[i]) * self.head.stride[i]  # xy\n            y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.head.anchor_grid[i]  # wh\n            # else:  # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953\n            #     xy = (y[..., 0:2] * 2. - 0.5 + self.head.grid[i]) * self.head.stride[i]  # xy\n            #     wh = (y[..., 2:4] * 2) ** 2 * self.head.anchor_grid[i].view(1, self.head.na, 1, 1, 2)  # wh\n            #     y = torch.cat((xy, wh, y[..., 4:]), -1)\n            z.append(y.view(bs, -1, self.head.no))\n        return self.process_inference(torch.cat(z, 1), image_sizes)\n\n    def process_inference(self, out, image_sizes):\n        out = non_max_suppression(\n            out,\n            self.conf_thres,\n            self.iou_thres,\n            multi_label=True,\n            agnostic=self.single_cls,\n        )\n        assert len(out) == len(image_sizes)\n        results_all: List[Instances] = []\n        # Statistics per image\n        for si, (pred, img_size) in enumerate(zip(out, image_sizes)):\n\n            if len(pred) == 0:\n                result = Instances(img_size)\n                result.pred_boxes = Boxes(torch.tensor([]))\n                result.scores = torch.tensor([])\n                result.pred_classes = torch.tensor([])\n            else:\n                # Predictions\n                if self.single_cls:\n                    pred[:, 5] = 0\n                predn = pred.clone()\n                # Predn shape [ndets, 6] of format [xyxy, conf, cls] relative to the input image size\n                result = Instances(img_size)\n                result.pred_boxes = Boxes(predn[:, :4])  # TODO: Check if resizing needed\n                result.scores = predn[:, 4]\n                result.pred_classes = predn[:, 5].int()  # TODO: Check the classes\n            results_all.append(result)\n        return results_all\n\n    def preprocess_image(self, batched_inputs: Tuple[Dict[str, Tensor]]):\n        \"\"\"\n        Normalize, pad and batch the input images.\n        \"\"\"\n        images = [x[\"image\"].to(self.device) for x in batched_inputs]\n        images = [(x - self.pixel_mean) / self.pixel_std for x in images]\n        images = ImageList.from_tensors(images, self.backbone.size_divisibility)\n        return images\n", "meta": {"hexsha": "c071b66bd691c5570255d730ff26a600cdb6ff5a", "size": 32839, "ext": "py", "lang": "Python", "max_stars_repo_path": "unitorch/models/detectron2/meta_arch/yolo5.py", "max_stars_repo_name": "fuliucansheng/UniTorch", "max_stars_repo_head_hexsha": "47038321593ce4e7eabda555bd58c0cf89482146", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-02-05T08:52:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T07:01:34.000Z", "max_issues_repo_path": "unitorch/models/detectron2/meta_arch/yolo5.py", "max_issues_repo_name": "Lixin-Qian/unitorch", "max_issues_repo_head_hexsha": "47038321593ce4e7eabda555bd58c0cf89482146", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unitorch/models/detectron2/meta_arch/yolo5.py", "max_forks_repo_name": "Lixin-Qian/unitorch", "max_forks_repo_head_hexsha": "47038321593ce4e7eabda555bd58c0cf89482146", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-27T07:01:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:01:13.000Z", "avg_line_length": 40.0475609756, "max_line_length": 115, "alphanum_fraction": 0.5374706903, "include": true, "reason": "import numpy", "num_tokens": 9236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032313, "lm_q2_score": 0.3242354120407358, "lm_q1q2_score": 0.1897105138185948}}
{"text": "\"\"\"API for joint-density-of-states calculation.\"\"\"\n# Copyright (C) 2019 Atsushi Togo\n# All rights reserved.\n#\n# This file is part of phono3py.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n#   notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n#   notice, this list of conditions and the following disclaimer in\n#   the documentation and/or other materials provided with the\n#   distribution.\n#\n# * Neither the name of the phonopy project nor the names of its\n#   contributors may be used to endorse or promote products derived\n#   from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport numpy as np\nfrom phonopy.structure.cells import Primitive, Supercell\nfrom phonopy.structure.symmetry import Symmetry\nfrom phonopy.units import VaspToTHz\n\nfrom phono3py.file_IO import write_joint_dos\nfrom phono3py.phonon3.imag_self_energy import (\n    get_freq_points_batches,\n    get_frequency_points,\n)\nfrom phono3py.phonon3.joint_dos import JointDos\nfrom phono3py.phonon.grid import BZGrid\n\n\nclass Phono3pyJointDos:\n    \"\"\"Class to calculate joint-density-of-states.\"\"\"\n\n    def __init__(\n        self,\n        supercell: Supercell,\n        primitive: Primitive,\n        fc2,\n        mesh=None,\n        nac_params=None,\n        nac_q_direction=None,\n        sigmas=None,\n        cutoff_frequency=1e-4,\n        frequency_step=None,\n        num_frequency_points=None,\n        num_points_in_batch=None,\n        temperatures=None,\n        frequency_factor_to_THz=VaspToTHz,\n        frequency_scale_factor=None,\n        use_grg=False,\n        SNF_coordinates=\"reciprocal\",\n        is_mesh_symmetry=True,\n        is_symmetry=True,\n        store_dense_gp_map=False,\n        symprec=1e-5,\n        output_filename=None,\n        log_level=0,\n    ):\n        \"\"\"Init method.\"\"\"\n        self._primitive = primitive\n        self._supercell = supercell\n        self._fc2 = fc2\n        self._temperatures = temperatures\n        self._nac_params = nac_params\n        self._nac_q_direction = nac_q_direction\n        if sigmas is None:\n            self._sigmas = [None]\n        else:\n            self._sigmas = sigmas\n        self._cutoff_frequency = cutoff_frequency\n        self._frequency_factor_to_THz = frequency_factor_to_THz\n        self._frequency_scale_factor = frequency_scale_factor\n        self._is_mesh_symmetry = is_mesh_symmetry\n        self._is_symmetry = is_symmetry\n        self._store_dense_gp_map = store_dense_gp_map\n        self._use_grg = use_grg\n        self._SNF_coordinates = SNF_coordinates\n        self._symprec = symprec\n        self._filename = output_filename\n        self._log_level = log_level\n\n        self._bz_grid = None\n        self._joint_dos = None\n        self._num_frequency_points_in_batch = num_points_in_batch\n        self._frequency_step = frequency_step\n        self._num_frequency_points = num_frequency_points\n\n        self._primitive_symmetry = Symmetry(\n            self._primitive, self._symprec, self._is_symmetry\n        )\n\n        if mesh is not None:\n            self.mesh_numbers = mesh\n            self.initialize(mesh)\n\n    @property\n    def grid(self):\n        \"\"\"Return BZGrid class instance.\"\"\"\n        return self._bz_grid\n\n    @property\n    def nac_params(self):\n        \"\"\"Setter and getter of parameters for non-analytical term correction.\"\"\"\n        return self._nac_params\n\n    @property\n    def num_frequency_points_in_batch(self):\n        \"\"\"Getter and setter of num_frequency_points_in_batch.\n\n        Number of sampling frequency points per batch.\n        Larger value gives better concurrency in tetrahedron method,\n        but requires more memory.\n\n        \"\"\"\n        return self._num_frequency_points_in_batch\n\n    @num_frequency_points_in_batch.setter\n    def num_frequency_points_in_batch(self, nelems_in_batch):\n        self._num_frequency_points_in_batch = nelems_in_batch\n\n    @property\n    def mesh_numbers(self):\n        \"\"\"Setter and getter of sampling mesh numbers in reciprocal space.\"\"\"\n        if self._bz_grid is None:\n            return None\n        else:\n            return self._bz_grid.D_diag\n\n    @mesh_numbers.setter\n    def mesh_numbers(self, mesh_numbers):\n        self._bz_grid = BZGrid(\n            mesh_numbers,\n            lattice=self._primitive.cell,\n            symmetry_dataset=self._primitive_symmetry.dataset,\n            is_time_reversal=self._is_symmetry,\n            use_grg=self._use_grg,\n            force_SNF=False,\n            SNF_coordinates=self._SNF_coordinates,\n            store_dense_gp_map=self._store_dense_gp_map,\n        )\n\n    def initialize(self, mesh_numbers):\n        \"\"\"Initialize JointDos.\"\"\"\n        self._jdos = JointDos(\n            self._primitive,\n            self._supercell,\n            self._bz_grid,\n            self._fc2,\n            nac_params=self._nac_params,\n            cutoff_frequency=self._cutoff_frequency,\n            frequency_factor_to_THz=self._frequency_factor_to_THz,\n            frequency_scale_factor=self._frequency_scale_factor,\n            is_mesh_symmetry=self._is_mesh_symmetry,\n            store_dense_gp_map=self._store_dense_gp_map,\n            symprec=self._symprec,\n            filename=self._filename,\n            log_level=self._log_level,\n        )\n        if self._log_level:\n            print(\"Generating grid system ... \", end=\"\", flush=True)\n\n        self.mesh_numbers = mesh_numbers\n\n        if self._log_level:\n            if self._bz_grid.grid_matrix is None:\n                print(\"[ %d %d %d ]\" % tuple(self._bz_grid.D_diag))\n            else:\n                print(\"\")\n                print(\n                    \"Generalized regular grid: [ %d %d %d ]\"\n                    % tuple(self._bz_grid.D_diag)\n                )\n                print(\"Grid generation matrix:\")\n                print(\"  [ %d %d %d ]\" % tuple(self._bz_grid.grid_matrix[0]))\n                print(\"  [ %d %d %d ]\" % tuple(self._bz_grid.grid_matrix[1]))\n                print(\"  [ %d %d %d ]\" % tuple(self._bz_grid.grid_matrix[2]))\n\n    def run(self, grid_points, write_jdos=False):\n        \"\"\"Calculate joint-density-of-states.\"\"\"\n        if self._log_level:\n            print(\n                \"--------------------------------- Joint DOS \"\n                \"---------------------------------\"\n            )\n            print(\"Running harmonic phonon calculations...\", flush=True)\n\n        self._jdos.run_phonon_solver()\n        frequencies, _, _ = self._jdos.get_phonons()\n        self._jdos.run_phonon_solver_at_gamma()\n        max_phonon_freq = np.max(frequencies)\n        self._jdos.run_phonon_solver_at_gamma(is_nac=True)\n\n        self._frequency_points = get_frequency_points(\n            max_phonon_freq=max_phonon_freq,\n            sigmas=self._sigmas,\n            frequency_points=None,\n            frequency_step=self._frequency_step,\n            num_frequency_points=self._num_frequency_points,\n        )\n        batches = get_freq_points_batches(\n            len(self._frequency_points), nelems=self._num_frequency_points_in_batch\n        )\n        if self._temperatures is None:\n            temperatures = [None]\n        else:\n            temperatures = self._temperatures\n        self._joint_dos = np.zeros(\n            (\n                len(self._sigmas),\n                len(temperatures),\n                len(self._frequency_points),\n                2,\n            ),\n            dtype=\"double\",\n            order=\"C\",\n        )\n\n        for i, gp in enumerate(grid_points):\n            if (self._bz_grid.addresses[gp] == 0).all():\n                self._jdos.nac_q_direction = self._nac_q_direction\n            else:\n                self._jdos.nac_q_direction = None\n            self._jdos.set_grid_point(gp)\n\n            if self._log_level:\n                weights = self._jdos.get_triplets_at_q()[1]\n                print(\n                    \"======================= \"\n                    \"Grid point %d (%d/%d) \"\n                    \"=======================\" % (gp, i + 1, len(grid_points))\n                )\n                adrs = self._jdos.bz_grid.addresses[gp]\n                q = np.dot(adrs, self._bz_grid.QDinv.T)\n                print(\"q-point: (%5.2f %5.2f %5.2f)\" % tuple(q))\n                print(\"Number of triplets: %d\" % len(weights))\n                print(\"Frequency\")\n                for f in self._jdos.get_phonons()[0][gp]:\n                    print(\"%8.3f\" % f)\n\n            if not self._sigmas:\n                raise RuntimeError(\"sigma or tetrahedron method has to be set.\")\n\n            for i_s, sigma in enumerate(self._sigmas):\n                self._jdos.sigma = sigma\n                if self._log_level:\n                    if sigma is None:\n                        print(\"Tetrahedron method is used.\")\n                    else:\n                        print(\"Smearing method with sigma=%s is used.\" % sigma)\n                    print(\n                        f\"Calculations at {len(self._frequency_points)} \"\n                        f\"frequency points are devided into {len(batches)} batches.\"\n                    )\n                for i_t, temperature in enumerate(temperatures):\n                    self._jdos.temperature = temperature\n\n                    for ib, freq_indices in enumerate(batches):\n                        if self._log_level:\n                            print(\n                                f\"{ib + 1}/{len(batches)}: {freq_indices + 1}\",\n                                flush=True,\n                            )\n                        self._jdos.frequency_points = self._frequency_points[\n                            freq_indices\n                        ]\n                        self._jdos.run()\n                        self._joint_dos[i_s, i_t, freq_indices] = self._jdos.joint_dos\n\n                    if write_jdos:\n                        filename = self._write(gp, i_sigma=i_s)\n                        if self._log_level:\n                            print('JDOS is written into \"%s\".' % filename)\n\n    @property\n    def dynamical_matrix(self):\n        \"\"\"Return DynamicalMatrix class instance.\"\"\"\n        return self._jdos.dynamical_matrix\n\n    @property\n    def frequency_points(self):\n        \"\"\"Return frequency points.\"\"\"\n        return self._frequency_points\n\n    @property\n    def joint_dos(self):\n        \"\"\"Return calculated joint-density-of-states.\"\"\"\n        return self._joint_dos\n\n    def _write(self, gp, i_sigma=0):\n        return write_joint_dos(\n            gp,\n            self._bz_grid.D_diag,\n            self._frequency_points,\n            self._joint_dos[i_sigma],\n            sigma=self._sigmas[i_sigma],\n            temperatures=self._temperatures,\n            filename=self._filename,\n            is_mesh_symmetry=self._is_mesh_symmetry,\n        )\n", "meta": {"hexsha": "cd240405c31cc95803cd5acdf4f3e7d235fdf75e", "size": 11726, "ext": "py", "lang": "Python", "max_stars_repo_path": "phono3py/api_jointdos.py", "max_stars_repo_name": "MSimoncelli/phono3py", "max_stars_repo_head_hexsha": "b28b45a025c279833e9269e5d91330c75d3f6ae0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2016-04-27T04:43:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-01T07:46:56.000Z", "max_issues_repo_path": "phono3py/api_jointdos.py", "max_issues_repo_name": "MSimoncelli/phono3py", "max_issues_repo_head_hexsha": "b28b45a025c279833e9269e5d91330c75d3f6ae0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2016-12-22T12:42:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-02T07:31:53.000Z", "max_forks_repo_path": "phono3py/api_jointdos.py", "max_forks_repo_name": "MSimoncelli/phono3py", "max_forks_repo_head_hexsha": "b28b45a025c279833e9269e5d91330c75d3f6ae0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2016-02-11T13:33:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-01T21:36:50.000Z", "avg_line_length": 36.7586206897, "max_line_length": 86, "alphanum_fraction": 0.5960259253, "include": true, "reason": "import numpy", "num_tokens": 2539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.3140505578320071, "lm_q1q2_score": 0.1896651337516641}}
{"text": "from abc import ABC\nfrom typing import Union\n\nimport numpy as np\nfrom qcore import geo\nfrom qcore.nhm import NHMFault\n\nfrom srf_generation.source_parameter_generation.uncertainties.mag_scaling import (\n    MagnitudeScalingRelations,\n    get_area,\n    get_length,\n    get_width,\n    mag2mom,\n    round_subfault_size,\n    lw_to_mw_scaling_relation,\n)\n\nLEONARD_SEISMOGENIC_DEPTH_DIFFERENCE = 3\nNHM_SEISMOGENIC_DEPTH = 12\n\n\ndef fault_factory(fault_type: int):\n    return [Type1, Type2, Type3, Type4][fault_type - 1]\n\n\nclass Fault(ABC):\n    subfault_spacing = 0.1\n    type = 0\n    _mag = None\n    _moment = None\n    name = None\n    _latitude = None\n    _longitude = None\n    _strike = None\n    _rake = None\n    _dip = None\n    _depth = None\n    _width = None\n    _length = None\n    _shypo = None\n    _dhypo = None\n\n    @property\n    def pid(self):\n        return self.name\n\n    @pid.setter\n    def pid(self, value):\n        self.name = value\n\n    @property\n    def mom(self):\n        if self._moment is None:\n            self._moment = mag2mom(self._mag)\n        return self._moment\n\n    @property\n    def latitude(self):\n        return self._latitude\n\n    @latitude.setter\n    def latitude(self, value):\n        self._latitude = value\n\n    @property\n    def longitude(self):\n        return self._longitude\n\n    @longitude.setter\n    def longitude(self, value):\n        self._longitude = value\n\n    @property\n    def magnitude(self):\n        return self._mag\n\n    @magnitude.setter\n    def magnitude(self, mag):\n        if mag > 11:\n            raise ValueError(\n                f\"Given mag {mag} is greater than theoretically possible 11\"\n            )\n        self._mag = mag\n\n    @property\n    def length(self):\n        return self._length\n\n    @property\n    def width(self):\n        return self._width\n\n    def to_dict(self):\n        return {\n            \"type\": self.type,\n            \"magnitude\": self._mag,\n            \"moment\": self.mom,\n            \"name\": self.name,\n            \"longitude\": self.longitude,\n            \"latitude\": self.latitude,\n            \"strike\": self._strike,\n            \"rake\": self._rake,\n            \"dip\": self._dip,\n            \"depth\": self._depth,\n        }\n\n    @property\n    def rake(self):\n        return self._rake\n\n    @rake.setter\n    def rake(self, value):\n        value = ((value + 180) % 360) - 180\n        self._set_rake(value)\n\n    def _set_rake(self, value):\n        self._rake = value\n\n    @property\n    def dip(self):\n        return self._dip\n\n    @dip.setter\n    def dip(self, value):\n        if 90 < value < 180:\n            self.strike = self.strike + 180\n            self.rake = -self.rake\n            value = 180 - value\n        elif value < 0 or value > 180:\n            # The fault is now above ground\n            raise ValueError(f\"Invalid dip value: {value}\")\n\n        self._set_dip(value)\n\n    def _set_dip(self, value):\n        self._dip = value\n\n\nclass SinglePlaneFault(Fault):\n    def __init__(self, name, magnitude, strike, rake, dip):\n        self.name = name\n        self._mag = magnitude\n        self._strike = strike\n        self._rake = rake\n        self._dip = dip\n\n    _length: float = None\n    _width: float = None\n    _dtop: float = None\n    _dbottom: float = None\n\n    @property\n    def strike(self):\n        return self._strike\n\n    @strike.setter\n    def strike(self, value):\n        self._strike = value % 360\n\n    @property\n    def dhypo(self):\n        return self.width / 2\n\n    @property\n    def dbottom(self):\n        return self._dbottom\n\n    @property\n    def dtop(self):\n        return self._dtop\n\n    @property\n    def hypocentre_lonlat(self):\n        return self._longitude, self._latitude\n\n\nclass MultiPlaneFault(Fault):\n    pass\n\n\nclass PointSourceFault(SinglePlaneFault):\n\n    type = 1\n\n    # vs = 3.2\n    # rh0 = 2.44\n    # risetime = 0.5\n    # stype = \"cos\"\n    # inittime = 0.0\n    vs = None\n    rh0 = None\n    risetime = None\n    stype = None\n    inittime = None\n\n    def __init__(self, name, latitude, longitude, magnitude, strike, rake, dip, depth):\n        self._depth = depth\n        self._latitude = latitude\n        self._longitude = longitude\n        super().__init__(name, magnitude, strike, rake, dip)\n\n    @property\n    def dbottom(self):\n        return self._depth\n\n    def to_dict(self):\n        base_dict = super().to_dict()\n        base_dict.update({\"type\": 1})\n        if self.vs is not None:\n            base_dict[\"vs\"] = self.vs\n        if self.rh0 is not None:\n            base_dict[\"rho\"] = self.rh0\n        if self.risetime is not None:\n            base_dict[\"risetime\"] = self.risetime\n        if self.stype is not None:\n            base_dict[\"stype\"] = self.stype\n        if self.inittime is not None:\n            base_dict[\"inittime\"] = self.inittime\n        return base_dict\n\n\nType1 = PointSourceFault\n\n\nclass FiniteFault(SinglePlaneFault):\n\n    dlen = 0.1\n    dwid = 0.1\n    shypo = 0.00\n    depths = None\n\n    def to_dict(self):\n        base_dict: dict = super().to_dict()\n        base_dict.update(\n            {\n                \"flen\": self.length,\n                \"dlen\": self.dlen,\n                \"fwid\": self.width,\n                \"dwid\": self.dwid,\n                \"dtop\": self.dtop,\n                \"shypo\": self.shypo,\n                \"dhypo\": self.dhypo,\n            }\n        )\n        return base_dict\n\n\nclass Type2(FiniteFault):\n\n    type = 2\n\n    _ratio_override: Union[float, None] = None\n    _magnitude_scaling_relation: MagnitudeScalingRelations = None\n\n    def __init__(self, name, latitude, longitude, magnitude, strike, rake, dip, depth):\n        self._depth = depth\n        self._latitude = latitude\n        self._longitude = longitude\n        super().__init__(name, magnitude, strike, rake, dip)\n\n    def to_dict(self):\n        base_dict: dict = super().to_dict()\n        base_dict.update(\n            {\n                \"type\": 2,\n                \"longitude\": self._lon_hyp,\n                \"latitude\": self._lat_hyp,\n                \"mwsr\": self._magnitude_scaling_relation.name,\n                \"dbottom\": self.dbottom,\n            }\n        )\n        return base_dict\n\n    def _set_rake(self, value):\n        self._rake = value\n        if self._magnitude_scaling_relation is not None:\n            self._calculate_dimensions()\n\n    def set_ratio_override(self, ratio):\n        self._ratio_override = ratio\n\n    def reset_ratio_override(self):\n        self._ratio_override = None\n\n    @property\n    def magnitude_scaling_relation(self):\n        return self._magnitude_scaling_relation\n\n    @magnitude_scaling_relation.setter\n    def magnitude_scaling_relation(self, value: MagnitudeScalingRelations):\n        self._magnitude_scaling_relation = value\n        self._calculate_dimensions()\n\n    @property\n    def length(self):\n        if self.magnitude_scaling_relation is None:\n            raise ValueError(\"No magnitude scaling relation given\")\n\n        return self._length\n\n    @property\n    def width(self):\n        if self.magnitude_scaling_relation is None:\n            raise ValueError(\"No magnitude scaling relation given\")\n\n        return self._width\n\n    @property\n    def dhypo(self):\n        return self.width / 2\n\n    @property\n    def dbottom(self):\n        if self.magnitude_scaling_relation is None:\n            raise ValueError(\"No magnitude scaling relation given\")\n        return self._dbottom\n\n    @property\n    def dtop(self):\n        if self.magnitude_scaling_relation is None:\n            raise ValueError(\"No magnitude scaling relation given\")\n        return self._dtop\n\n    @property\n    def hypocentre_lonlat(self):\n        if self.magnitude_scaling_relation is None:\n            raise ValueError(\"No magnitude scaling relation given\")\n        return self._lon_hyp, self._lat_hyp\n\n    def _calculate_dimensions(self):\n        if self.magnitude_scaling_relation is None:\n            raise ValueError(\"No magnitude scaling relation given\")\n\n        area = get_area(self)\n        length = get_length(self)\n        width = get_width(self)\n\n        if self._ratio_override is not None:\n            r = self._ratio_override\n        else:\n            r = max(length / width, 1)\n\n        self._width = np.sqrt(area / r)\n        self._length = r * np.sqrt(area / r)\n\n        self._dtop = self._depth - np.sin(np.radians(self._dip)) * self.width / 2\n        shift = min(self._dtop, 0)\n        if shift != 0:\n            self._dtop = 0\n        self._dbottom = (\n            self._depth + np.sin(np.radians(self._dip)) * self.width / 2 + shift\n        )\n        if (\n            self.magnitude_scaling_relation == MagnitudeScalingRelations.LEONARD2014\n            and self._dbottom > NHM_SEISMOGENIC_DEPTH\n        ):\n            self._dbottom += LEONARD_SEISMOGENIC_DEPTH_DIFFERENCE\n\n        self.ny = int(round(self.width / self.dwid))\n        self.nx = int(round(self.length / self.dlen))\n        self.dlen = self.length / float(self.nx)\n        self.dwid = self.width / float(self.ny)\n\n        # self._calculate_finite_fault_properties()\n        # self._calculate_corners()\n        self._get_hypocentre(0, -self.dhypo)\n\n    def _get_hypocentre(self, shypo, dhypo):\n        \"\"\"\n        Same logic as corners, for a single point.\n        \"\"\"\n        if self.magnitude_scaling_relation is None:\n            raise ValueError(\"No magnitude scaling relation given\")\n        ONE_DEG_LAT = np.radians(6371.0072)\n        azimuth = np.radians(self.strike - 90)\n        rot_matrix = np.array(\n            [[np.cos(azimuth), np.sin(azimuth)], [-np.sin(azimuth), np.cos(azimuth)]]\n        )\n\n        y_pos_surf_proj_hyp = -dhypo * np.cos(np.radians(self._dip))\n        hypocentre_points = np.dot(rot_matrix, [[shypo], [y_pos_surf_proj_hyp]])\n\n        self._lat_hyp = self.latitude + hypocentre_points[1][0] / ONE_DEG_LAT\n        self._lon_hyp = self.longitude + (\n            hypocentre_points[0][0] / ONE_DEG_LAT\n        ) / np.cos(np.radians(self.latitude))\n\n    def _calculate_corners(self):\n        # use cartesian coordinate system to define the along strike and downdip\n        # locations taking the center of the fault plane as (x,y)=(0,0)\n        if self.magnitude_scaling_relation is None:\n            raise ValueError(\"No magnitude scaling relation given\")\n        ONE_DEG_LAT = np.radians(6371.0072)\n\n        x_pos = np.arange(self.dlen / 2.0, self.length, self.dlen) - self.length / 2.0\n        y_pos = (\n            np.arange(self.dwid / 2.0, self.width, self.dwid)[::-1] - self.width / 2.0\n        )\n\n        # now use a coordinate transformation to go from fault plane to North and\n        # East cartesian plane (again with (0,0) ==(0,0)  )\n        y_pos_surf_proj = y_pos * np.cos(np.radians(self._dip))\n        azimuth = np.radians(self.strike - 90)\n        rot_matrix = np.array(\n            [[np.cos(azimuth), np.sin(azimuth)], [-np.sin(azimuth), np.cos(azimuth)]]\n        )\n        east_loc_relative, north_loc_relative = np.dot(\n            rot_matrix, [np.tile(x_pos, self.ny), y_pos_surf_proj.repeat(self.nx)]\n        ).reshape((2, self.nx, self.ny))\n        # now use a coordinate transformation to go from the North East cartesian\n        # plane to the spherical earth WGS84 coordinate system\n        self.lats = self.latitude + north_loc_relative / ONE_DEG_LAT\n        self.lons = self.longitude + (east_loc_relative / ONE_DEG_LAT) * 1 / np.cos(\n            np.radians(self.latitude)\n        )\n\n    def _calculate_finite_fault_properties(self):\n        \"\"\"\n        Purpose: To create a finite fault geometry based on centroid moment tensor\n        solution information and magnitude scaling relationships.\n        The use of such finite fault geometry is for first order computation of\n        source-to-site distances.\n\n        revisions\n        v2 - reoriented fault plane to be consistent with along strike direction\n        v3 - added 'argout_emod3d' output and associated commands to output details\n             which are input in the finite fault model generation for EMOD3D graves methodology\n\n        assumptions:\n        1) The centroid moment tensor represents the centroid of the fault plane,\n        located half way along strike and downdip\n        2) The fault area is computed from the median of a Moment scaling\n        relationship and thus is assumed to be a 'typical' stress drop event for\n        the Mw-relationship used.\n        Should only be used for small events where the downdip width is smaller\n        than the seismogenic depth (i.e. so the assumption of a square fault plane\n        is reasonable); depth is reset to zero if above ground values determined\n        3) srike in deg measured clockwise from N; rake in deg measured\n        anti-clockwise from the strike direction (and in the range\n        -180<lambda<180; dip in deg measured downward from horizontal\n\n        Input variables:\n        Lat    - the latitude of the focal mechanism (-ve below equator)\n        Lon    - the lon of the focal mech (-180<lon<180)\n        Depth  - the depth of the focal mech (in km)\n        Mw     - the moment magnitude from the Mw tensor soln\n        strike - the strike of the focal mech (only 1)\n        rake   - rake (not used, but carried forward)\n        dip    - the dip angle of the fault plane\n\n        output variables:\n        lat       - the latitude of the subfault\n        lon       - the lon of the subfault\n        depth     - depth of the subfault\n        lonAsList - as a 1D array\n        \"\"\"\n        if self.magnitude_scaling_relation is None:\n            raise ValueError(\"No magnitude scaling relation given\")\n        # rounded subfault spacing\n\n        # use cartesian coordinate system to define the along strike and downdip\n        # locations taking the center of the fault plane as (x,y)=(0,0)\n        y_pos: np.ndarray = (\n            np.arange(self.dwid / 2.0, self.width, self.dwid)[::-1] - self.width / 2.0\n        )\n\n        depth_loc_relative = (\n            (-y_pos * np.sin(np.radians(self._dip)))\n            .repeat(self.nx)\n            .reshape((self.nx, self.ny))\n        )\n        shift = np.min(self.dtop + depth_loc_relative, 0)\n        self.depths = self.dtop + depth_loc_relative - shift\n        if np.any(0 > self.depths):\n            raise ValueError(\n                \"Some points are above the ground. This represents a logic problem and should be referred to the \"\n                \"developers.\"\n            )\n\n\nclass Type3(FiniteFault):\n    def __init__(\n        self,\n        name,\n        magnitude,\n        lon1,\n        lat1,\n        lon2,\n        lat2,\n        dip,\n        rake,\n        dtop,\n        dbottom,\n        dip_dir,\n        tectonic_type,\n    ):\n        self._trace = ((lon1, lat1), (lon2, lat2))\n        self._dtop = dtop\n        self._dbottom = dbottom\n        self._dip_dir = dip_dir\n\n        self._length = round_subfault_size(\n            geo.ll_dist(lon1, lat1, lon2, lat2), magnitude\n        )\n\n        if tectonic_type == \"SUBDUCTION_INTERFACE\":\n            self.mwsr = MagnitudeScalingRelations.SKARLATOUDIS2016\n\n        else:\n            self.mwsr = MagnitudeScalingRelations.LEONARD2014\n            self._dbottom += 3\n\n        raw_fwid = (self._dbottom - dtop) / np.sin(np.radians(dip))\n        self._width = round_subfault_size(raw_fwid, magnitude)\n\n        strike = geo.ll_bearing(lon1, lat1, lon2, lat2)\n\n        if (self._dip_dir - strike + 360) % 360 > 180:\n            # Reverse the order of the points so the dipdir is to the right of the strike\n            self._trace = self._trace[::-1]\n            strike = geo.ll_bearing(lon2, lat2, lon1, lat1)\n\n        super().__init__(name, magnitude, strike, rake, dip)\n\n    def to_dict(self):\n        base_dict = {\n            \"clon\": geo.ll_mid(*self._trace[0], *self._trace[1])[0],\n            \"clat\": geo.ll_mid(*self._trace[0], *self._trace[1])[1],\n            \"type\": self.type,\n            \"magnitude\": self._mag,\n            \"moment\": self.mom,\n            \"name\": self.name,\n            \"strike\": self._strike,\n            \"rake\": self._rake,\n            \"dip\": self._dip,\n            \"dtop\": self._dtop,\n            \"dbottom\": self._dbottom,\n            \"length\": self._length,\n            \"width\": self._width,\n            \"dip_dir\": self._dip_dir,\n        }\n        return base_dict\n\n\nclass Type4(MultiPlaneFault):\n\n    type = 4\n\n    def __init__(self, nhm_data: NHMFault):\n        self.name = nhm_data.name\n        self._dbottom = nhm_data.dbottom\n        self.fault_type = nhm_data.fault_type\n        self.tectonic_type = nhm_data.tectonic_type\n        self._dip = nhm_data.dip\n        self._rake = nhm_data.rake\n        self._dtop = nhm_data.dtop\n        self._slip_rate = nhm_data.slip_rate\n        self._dip_dir = nhm_data.dip_dir\n\n        self._n_planes = len(nhm_data.trace) - 1\n\n        if nhm_data.tectonic_type == \"SUBDUCTION_INTERFACE\":\n            self.mwsr = MagnitudeScalingRelations.SKARLATOUDIS2016\n\n        else:\n            self.mwsr = MagnitudeScalingRelations.LEONARD2014\n            self._dbottom += 3\n\n        dummy_plane = Type3(\n            nhm_data.name,\n            nhm_data.mw,\n            *nhm_data.trace[0],\n            *nhm_data.trace[1],\n            nhm_data.dip,\n            nhm_data.rake,\n            nhm_data.dtop,\n            nhm_data.dbottom,\n            nhm_data.dip_dir,\n            nhm_data.tectonic_type,\n        )\n\n        length = sum(\n            [\n                geo.ll_dist(*nhm_data.trace[i], *nhm_data.trace[i + 1])\n                for i in range(self._n_planes)\n            ]\n        )\n\n        self._mag = lw_to_mw_scaling_relation(\n            length, dummy_plane.width, self.mwsr, nhm_data.rake\n        )\n\n        if dummy_plane.strike != geo.ll_bearing(*nhm_data.trace[0], *nhm_data.trace[1]):\n            nhm_data.trace = nhm_data.trace[::-1]\n\n        self._planes = []\n        for i in range(self._n_planes):\n            self._planes.append(\n                Type3(\n                    nhm_data.name,\n                    self._mag,\n                    *nhm_data.trace[i],\n                    *nhm_data.trace[i + 1],\n                    nhm_data.dip,\n                    nhm_data.rake,\n                    nhm_data.dtop,\n                    nhm_data.dbottom,\n                    nhm_data.dip_dir,\n                    nhm_data.tectonic_type,\n                )\n            )\n\n    @property\n    def length(self):\n        return sum([f.length for f in self._planes])\n\n    @property\n    def width(self):\n        return self._planes[0].width\n\n    @property\n    def dhypo(self):\n        return self._dhypo\n\n    @dhypo.setter\n    def dhypo(self, dhypo):\n        if dhypo > self.width:\n            raise ValueError(\n                f\"Cannot place hypocentre outside fault plane. dhpyo: {dhypo}, fault width: {self.width}\"\n            )\n        self._dhypo = dhypo\n        for sub_plane in self._planes:\n            sub_plane._dhypo = dhypo\n\n    @property\n    def shypo(self):\n        return self._shypo\n\n    @shypo.setter\n    def shypo(self, shypo):\n        if shypo > self.length:\n            raise ValueError(\n                f\"Cannot place hypocentre outside fault plane. shpyo: {shypo}, fault length: {self.length}\"\n            )\n        self._shypo = shypo\n        for sub_plane in self._planes:\n            sub_plane._shypo = shypo\n\n    def to_dict(self):\n\n        base_dict = {\n            \"type\": self.type,\n            \"magnitude\": self._mag,\n            \"moment\": self.mom,\n            \"name\": self.name,\n            \"fault_type\": self.fault_type,\n            \"tect_type\": self.tectonic_type,\n            \"rake\": self._rake,\n            \"dip\": self._dip,\n            \"dtop\": self._dtop,\n            \"dbottom\": self._dbottom,\n            \"length\": self.length,\n            \"plane_count\": self._n_planes,\n            \"slip_rate\": self._slip_rate,\n            \"dip_dir\": self._dip_dir,\n            \"shypo\": self.shypo,\n            \"dhypo\": self.dhypo,\n        }\n        for i, sub_fault in enumerate(self._planes):\n            for key, item in sub_fault.to_dict().items():\n                base_dict[f\"{key}_subfault_{i}\"] = item\n        return base_dict\n\n    @property\n    def trace(self):\n        points = [x._trace[0] for x in self._planes]\n        points.append(self._planes[-1]._trace[1])\n        return np.asarray(points)\n\n    @trace.setter\n    def trace(self, values):\n        for i in range(self._n_planes):\n            sub_plane = self._planes[i]\n            sub_plane._trace = (tuple(values[i]), tuple(values[i + 1]))\n\n    @property\n    def dtop(self):\n        return self._dtop\n\n    @dtop.setter\n    def dtop(self, value):\n        if value < 0:\n            raise ValueError(\"dtop must be below ground level\")\n        self._dtop = value\n\n    @property\n    def dbottom(self):\n        return self._dbottom\n\n    @dbottom.setter\n    def dbottom(self, value):\n        if value < 0:\n            raise ValueError(\"dtop must be below ground level\")\n        self._dbottom = value\n\n    @property\n    def dip_dir(self):\n        return self._dip_dir\n\n    @dip_dir.setter\n    def dip_dir(self, value):\n        self._dip_dir = value\n\n    def _set_dip(self, value):\n        for sub_fault in self._planes:\n            sub_fault.dip = value\n        self._dip = value\n\n    @property\n    def strike(self):\n        return np.asarray([x.strike for x in self._planes])\n\n    @strike.setter\n    def strike(self, values):\n        for i in range(self._n_planes):\n            self._planes[i].strike = values[i]\n", "meta": {"hexsha": "a1535ba59581f83b8c60257888a2db33c4222cc5", "size": 21376, "ext": "py", "lang": "Python", "max_stars_repo_path": "srf_generation/Fault.py", "max_stars_repo_name": "ucgmsim/Pre-processing", "max_stars_repo_head_hexsha": "c4b9ae20a9e5e4f96f930bde29aa15176d9c8b64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-01T10:36:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-01T10:36:09.000Z", "max_issues_repo_path": "srf_generation/Fault.py", "max_issues_repo_name": "ucgmsim/Pre-processing", "max_issues_repo_head_hexsha": "c4b9ae20a9e5e4f96f930bde29aa15176d9c8b64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38, "max_issues_repo_issues_event_min_datetime": "2018-08-01T04:25:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T23:37:53.000Z", "max_forks_repo_path": "srf_generation/Fault.py", "max_forks_repo_name": "ucgmsim/Pre-processing", "max_forks_repo_head_hexsha": "c4b9ae20a9e5e4f96f930bde29aa15176d9c8b64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-17T21:44:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-17T21:44:14.000Z", "avg_line_length": 29.4030261348, "max_line_length": 114, "alphanum_fraction": 0.5840194611, "include": true, "reason": "import numpy", "num_tokens": 5338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.3140505514119072, "lm_q1q2_score": 0.18966512091932153}}
{"text": "#!/usr/bin/python3\n#\n##########################################################################################################################\n#                                                                                                                        #\n#                   What follows are options of the PP-STM code for calculating inner PDOS                               #\n#                                                                                                                        #\n##########################################################################################################################\n#\n# Note : This type of simulations works for solid slabs or molecules on slabs (substrate) ; for freestanding molecule it can give you nonsences\n#\n# ***** System information: *****\n#\nppstm_path = './PPSTM/'      # path (absolute or relative) to your PPSTM code #\n#\n# ***** Main informations ******\n#\nV_min         = -2.0         # V_min for plotting \nV_max         = +2.0         # V_max for plotting #\neta           =  0.1         # Lorentzian width of states in energy scale: typically 0.1; can be in range of 0.3-0.05 eV in some cases (low amount of layers ...) even up to 1.0 eV #\ndV            =  eta/5.0     # voltage/energy step , default : eta/5.0  #\nsample_orbs   = 'spd'        # orbitals of the sample 'sp' (light atoms only, faster) or 'spd' (all atoms) #\ndft_code      = 'AIMS'       # 'fireball'='Fireball'='FIREBALL' ; 'aims'='AIMS'='FHI-AIMS' ; 'cp2k'='CP2K' ; 'gpaw'='GPAW' #\ngeometry_file = 'geom-cube.in'   # E.G. 'input.xyz' , 'input.bas' , 'geometry.in'; None for GPAW #\nspin          =  'both'      # None=False ; for FHI-AIMS & CP2K: None -- spin-unpolarized/spin-restricted calc. ;  'both'--  up will be plotted as + and down as - , 'up'='alpha' or 'down\"='beta' (last 3 are for spin-polarizes or spin-unrestricted calculations) #\ncp2k_name     = 'FePc'       # Name used in CP2K calculations or GPAW calc #\n#\n# *****Plotting options ******\n#\nred_line_atoms    = [0]     # atoms to plot: !!! DO NOT FORGET PYTHON NUMBERING starts from 0 !!!, always use list-like structure; 'all' = -1 -- all atoms; [0] -- means 1st atom #\nred_line_shell    = 'dz2'   # which chells to plot: 'all' = all sample orbitals, 's', 'p', 'd', 'px', 'py', 'pz', 'dxy', 'dyz', 'dyz', 'dz2', 'dxz', 'dx2y2' #\n#\nblue_line_atoms   = [0,1]     # atoms to plot: !!! DO NOT FORGET PYTHON NUMBERING starts from 0 !!!, always use list-like structure; 'all' = -1 -- all atoms; [1] -- means 2nd atom #\nblue_line_shell   = 'all'     # which chells to plot: 'all' = all sample orbitals, 's', 'p', 'd', 'px', 'py', 'pz', 'dxy', 'dyz', 'dyz', 'dz2', 'dxz', 'dx2y2' #\n#\ngreen_line_atoms  = [0]     # atoms to plot: !!! DO NOT FORGET PYTHON NUMBERING starts from 0 !!!, always use list-like structure; 'all' = -1 -- all atoms; range(2,8) = [2,3,4,5,6,7]-- means atoms: 3,4,5,6,7 and 8 #\ngreen_line_shell  = 'all'   # which chells to plot: 'all' = all sample orbitals, 's', 'p', 'd', 'px', 'py', 'pz', 'dxy', 'dyz', 'dyz', 'dz2', 'dxz', 'dx2y2' #\n#\norange_line_atoms = list(range(1,57))   # atoms to plot: !!! DO NOT FORGET PYTHON NUMBERING starts from 0 !!!, always use list-like structure; 'all' = -1 -- all atoms; [8,9] -- means 9th and 10th atom #\norange_line_shell = 'pz'    # which chells to plot: 'all' = all sample orbitals, 's', 'p', 'd', 'px', 'py', 'pz', 'dxy', 'dyz', 'dyz', 'dz2', 'dxz', 'dx2y2' #\n#\nblack_line_atoms  = list(range(1,57))   # atoms to plot: !!! DO NOT FORGET PYTHON NUMBERING starts from 0 !!!, always use list-like structure; 'all' = -1 -- all atoms; None -- no line #\nblack_line_shell  = 'all'   # which chells to plot: 'all' = all sample orbitals, 's', 'p', 'd', 'px', 'py', 'pz', 'dxy', 'dyz', 'dyz', 'dz2', 'dxz', 'dx2y2' #\n#\nyellow_line_atoms = None    # atoms to plot: !!! DO NOT FORGET PYTHON NUMBERING starts from 0 !!!, always use list-like structure; 'all' = -1 -- all atoms; None -- no line #\nyellow_line_shell = 'all'   # which chells to plot: 'all' = all sample orbitals, 's', 'p', 'd', 'px', 'py', 'pz', 'dxy', 'dyz', 'dyz', 'dz2', 'dxz', 'dx2y2' #\n#\ngray_line_atoms   = None    # atoms to plot: !!! DO NOT FORGET PYTHON NUMBERING starts from 0 !!!, always use list-like structure; 'all' = -1 -- all atoms; None -- no line #\ngray_line_shell   = 'all'   # which chells to plot: 'all' = all sample orbitals, 's', 'p', 'd', 'px', 'py', 'pz', 'dxy', 'dyz', 'dyz', 'dz2', 'dxz', 'dx2y2' #\n#\n# *****Output options ******\n#\nPNG  = True                  # True / False -- plot \"png\" images (2D graph height) #\nTXT = False                  # **** Not working yet *** True / False -- write \".txt\" files with 1st column energy, other columns PDOS#\n#\n# ***** Advanced options ******\n#\ncut_atoms   = None           # Not really neccessary for these calculations, unless really big files and memory; None = -1 -- All atoms of the sample contributes to tunelling ; 1 -- only 1st atom of the sample contributes to the tunelling ; 57 -- first 57 atoms of the sample contributes to the tunelling ; ... #\n#\n# ***** More advanced options ******\n#\nfermi        = None          # None=0.0 -- no change to the Fermi Level ; -0.1 -- shifts the Fermi Level by 0.1 eV lower ... #\ncut_min      = V_min-3*eta   # cut out all orbitals lower than  -default: V_min-3*eta bellow Fermi (should be: cut_min <= Vmin-2*eta) . taken to the Fermi Level #\ncut_max      = V_max+3*eta   # cut out all orbitals higher than -default: V_max+3*eta above  Fermi (should be: cut_max >= Vmax+2*eta) . taken to the Fermi Level #\nfiles_path   = ''            # where are files fron DFT code ; rather do not use this #\nlower_atoms  = 'no-d-rescalling' # normally d-orbs are rescalled by factor of 0.2 #\n#\n#\n##########################################################################################################################\n#                                                                                                                        #\n#                                 DO NOT TOUCH LATER CODE (unless you know what you are doing)                           #\n#                                                                                                                        #\n##########################################################################################################################\n\nprint(\"Importing libraries\")\n\nimport os\nimport sys\nsys.path.append(ppstm_path) \n\nimport numpy as np\n#import pyPPSTM                   as PS\nimport pyPPSTM.ReadSTM           as RS\nimport pyPPSTM.PreSTMutils       as SU\nimport matplotlib\nmatplotlib.use('Agg') # Force matplotlib to not use any Xwindows backend. ## !!! important for working on clusters !!!!\nimport matplotlib.pyplot as plt\nfrom matplotlib.font_manager import FontProperties\n#if (plot_atoms):\n#    import pyPPSTM.basUtils as Bu\n#    import pyPPSTM.elements as elements\n\n\nprint(\"Libraries imported\")\n\n# --- some function definition --- #\n\ndef printf(*args):\n    together = ''.join(map(str, args))    # avoid the arg is not str\n    #print together\n    return together\n\n# --- Initial check --- #\n\nassert( PNG or TXT ), \"No output set to be True; I'm not going to do anything if there is no output. I'm too lazy like a Gartfield. \"\n\n# --- reading of the eigen-energies, the LCAO coefficients and geometry --- #\n\nprint(\"Reading electronic & geometry structure files\")\n\ncell=[[0,0],[0,0]];pbc=(0,0);lower_coefs=[];\n\nif ((dft_code == 'fireball') or(dft_code == 'Fireball') or (dft_code == 'FIREBALL')):\n    eigEn, coefs, Ratin = RS.read_FIREBALL_all(name = files_path + 'phik_0001_', geom=files_path+geometry_file, lvs = cell, fermi=fermi, orbs = sample_orbs, pbc=pbc, cut_min=cut_min, cut_max=cut_max,cut_at=cut_atoms, lower_atoms=lower_atoms, lower_coefs=lower_coefs);\n\nelif ((dft_code == 'gpaw') or(dft_code == 'GPAW')):\n    eigEn, coefs, Ratin = RS.read_GPAW_all(    name = files_path + cp2k_name + '.gpw', fermi=fermi, orbs = sample_orbs, pbc=pbc, cut_min=cut_min, cut_max=cut_max, cut_at=cut_atoms, lower_atoms=lower_atoms, lower_coefs=lower_coefs);\n\nelif ((dft_code == 'aims') or(dft_code == 'AIMS') or (dft_code == 'FHI-AIMS')):\n    if ((spin == None) or (spin == False)):\n        name = 'KS_eigenvectors.band_1.kpt_1.out'\n    elif ((spin == 'up')or(spin == 'alpha')or(spin == 'both')):\n        name = 'KS_eigenvectors_up.band_1.kpt_1.out'\n    elif ((spin == 'down')or(spin == 'beta')or(spin == 'dn')):\n        name = 'KS_eigenvectors_dn.band_1.kpt_1.out'\n    else :\n        print(\"unknown spin, I'm going to sleep. Good Night\"); exit()\n    eigEn, coefs, Ratin = RS.read_AIMS_all(name = files_path + name , geom= files_path + geometry_file, fermi=fermi, orbs = sample_orbs, pbc=pbc, cut_min=cut_min, cut_max=cut_max, cut_at=cut_atoms, lower_atoms=lower_atoms, lower_coefs=lower_coefs);\n    if (spin == 'both'):\n        name = 'KS_eigenvectors_dn.band_1.kpt_1.out'\n        eigEn2, coefs2, Ratin = RS.read_AIMS_all(name = files_path + name , geom= files_path + geometry_file, fermi=fermi, orbs = sample_orbs, pbc=pbc, cut_min=cut_min, cut_max=cut_max, cut_at=cut_atoms, lower_atoms=lower_atoms, lower_coefs=lower_coefs);\n        #coefs2 *= -1;\n\nelif ((dft_code == 'cp2k') or(dft_code == 'CP2K')):\n    if ((spin == None)or(spin == False)):\n        eigEn, coefs, Ratin  = RS.read_CP2K_all(name = files_path + cp2k_name , lvs=cell, fermi=fermi, orbs = sample_orbs, pbc=pbc, cut_min=cut_min, cut_max=cut_max, cut_at=cut_atoms, lower_atoms=lower_atoms, lower_coefs=lower_coefs);\n    elif ((spin == 'up')or(spin == 'alpha')):\n        eigEn, coefs, Ratin  = RS.read_CP2K_all(name = files_path + cp2k_name , lvs=cell, fermi=fermi, orbs = sample_orbs, pbc=pbc, cut_min=cut_min, cut_max=cut_max, cut_at=cut_atoms, lower_atoms=lower_atoms, lower_coefs=lower_coefs, spin='alpha');\n    elif (spin == 'both'):\n        eigEn, coefs, Ratin  = RS.read_CP2K_all(name = files_path + cp2k_name , lvs=cell, fermi=fermi, orbs = sample_orbs, pbc=pbc, cut_min=cut_min, cut_max=cut_max, cut_at=cut_atoms, lower_atoms=lower_atoms, lower_coefs=lower_coefs, spin='alpha');\n        eigEn2, coefs2, Ratin  = RS.read_CP2K_all(name = files_path + cp2k_name , lvs=cell, fermi=fermi, orbs = sample_orbs, pbc=pbc, cut_min=cut_min, cut_max=cut_max, cut_at=cut_atoms, lower_atoms=lower_atoms, lower_coefs=lower_coefs, spin='beta');\n        #coefs2 *= -1;\n    elif ((spin == 'down')or(spin == 'beta')or(spin == 'dn')):\n        eigEn, coefs, Ratin  = RS.read_CP2K_all(name = files_path + cp2k_name , lvs=cell, fermi=fermi, orbs = sample_orbs, pbc=pbc, cut_min=cut_min, cut_max=cut_max, cut_at=cut_atoms, lower_atoms=lower_atoms, lower_coefs=lower_coefs, spin='beta');\n    else :\n        print(\"unknown spin, I'm going to sleep. Good Night\"); exit()\n\n#print \"DEBUG: eigEn.shape \", eigEn.shape\n#print \"DEBUG: coefs.shape \", coefs.shape\n#print \"DEBUG: Ratin.shape \", Ratin.shape\n\nenergies = np.arange(V_min,V_max,dV)\n\nprint(\"energies prepared, coeffecients read\")\n\n# --- the PDOS calculations --- #\n\nplot = True if ( (red_line_atoms != None)or(blue_line_atoms != None)or(green_line_atoms != None)or(orange_line_atoms != None)or(black_line_atoms != None)or(yellow_line_atoms != None)or (gray_line_atoms != None) ) else False\n\nprint(\"DEBUG: plot\", plot)\n\nassert plot!=False, \"No lines to plot\"\n\nlatomslegend = 4\n\nif (red_line_atoms != None) :\n    atoms=red_line_atoms\n    PDOS1 = SU.pPDOS(eigEn,coefs, energies, eta=eta, orbs= sample_orbs, atoms=atoms   , spherical=red_line_shell   )\n    red_line_legend     = ','.join(map(str, atoms)) if len(atoms) < latomslegend else str(atoms[0])+\"..\"+str(atoms[-1])\n    print(\"DEBUG: red_line_legend\", red_line_legend)\nelse:\t#(red_line_atoms != None) :\n    PDOS1 = None\n\nif (blue_line_atoms != None) :\n    atoms=blue_line_atoms\n    PDOS2 = SU.pPDOS(eigEn,coefs, energies, eta=eta, orbs= sample_orbs, atoms=atoms  , spherical=blue_line_shell  )\n    blue_line_legend    = ','.join(map(str, atoms)) if len(atoms) < latomslegend else str(atoms[0])+\"..\"+str(atoms[-1])\nelse:\t#(blue_line_atoms != None) :\n    PDOS2 = None\n\nif (green_line_atoms != None) :\n    atoms=green_line_atoms\n    PDOS3 = SU.pPDOS(eigEn,coefs, energies, eta=eta, orbs= sample_orbs, atoms=atoms , spherical=green_line_shell )\n    green_line_legend   = ','.join(map(str, atoms)) if len(atoms) < latomslegend else str(atoms[0])+\"..\"+str(atoms[-1])\nelse:\t#(green_line_atoms != None) :\n    PDOS3 = None\n\nif (orange_line_atoms != None) :\n    atoms=orange_line_atoms\n    PDOS4 = SU.pPDOS(eigEn,coefs, energies, eta=eta, orbs= sample_orbs, atoms=atoms, spherical=orange_line_shell)\n    orange_line_legend  = ','.join(map(str, atoms)) if len(atoms) < latomslegend else str(atoms[0])+\"..\"+str(atoms[-1])\nelse:\t#(orange_line_atoms != None) :\n    PDOS4 = None\n\nif (black_line_atoms != None) :\n    atoms=black_line_atoms\n    PDOS5 = SU.pPDOS(eigEn,coefs, energies, eta=eta, orbs= sample_orbs, atoms=atoms , spherical=black_line_shell )\n    black_line_legend   = ','.join(map(str, atoms)) if len(atoms) < latomslegend else str(atoms[0])+\"..\"+str(atoms[-1])\nelse:\t#(black_line_atoms != None) :\n    PDOS5 = None\n\nif (yellow_line_atoms != None) :\n    atoms=yellow_line_atoms\n    PDOS6 = SU.pPDOS(eigEn,coefs, energies, eta=eta, orbs= sample_orbs, atoms=atoms, spherical=yellow_line_shell)\n    yellow_line_legend  = ','.join(map(str, atoms)) if len(atoms) < latomslegend else str(atoms[0])+\"..\"+str(atoms[-1])\nelse:\t#(yellow_line_atoms != None) :\n    PDOS6 = None\n\nif (gray_line_atoms != None) :\n    atoms=gray_line_atoms\n    PDOS7 = SU.pPDOS(eigEn,coefs, energies, eta=eta, orbs= sample_orbs, atoms=atoms  , spherical=gray_line_shell  )\n    gray_line_legend    = ','.join(map(str, atoms)) if len(atoms) > latomslegend else str(atoms[0])+\"..\"+str(atoms[-1])\nelse:\t#(gray_line_atoms != None) :\n    PDOS7 = None\n\nif spin=='both' :\n    print(\"DEBUG: printing spin down in both spins\")\n\n    PDOS1d = -1*SU.pPDOS(eigEn2,coefs2, energies, eta=eta, orbs= sample_orbs, atoms=red_line_atoms   , spherical=red_line_shell   ) if (red_line_atoms != None) else None\n    PDOS2d = -1*SU.pPDOS(eigEn2,coefs2, energies, eta=eta, orbs= sample_orbs, atoms=blue_line_atoms  , spherical=blue_line_shell  ) if (blue_line_atoms != None) else None\n    PDOS3d = -1*SU.pPDOS(eigEn2,coefs2, energies, eta=eta, orbs= sample_orbs, atoms=green_line_atoms , spherical=green_line_shell ) if (green_line_atoms != None) else None\n    PDOS4d = -1*SU.pPDOS(eigEn2,coefs2, energies, eta=eta, orbs= sample_orbs, atoms=orange_line_atoms, spherical=orange_line_shell) if (orange_line_atoms != None) else None\n    PDOS5d = -1*SU.pPDOS(eigEn2,coefs2, energies, eta=eta, orbs= sample_orbs, atoms=black_line_atoms , spherical=black_line_shell ) if (black_line_atoms != None) else None\n    PDOS6d = -1*SU.pPDOS(eigEn2,coefs2, energies, eta=eta, orbs= sample_orbs, atoms=yellow_line_atoms, spherical=yellow_line_shell) if (yellow_line_atoms != None) else None\n    PDOS7d = -1*SU.pPDOS(eigEn2,coefs2, energies, eta=eta, orbs= sample_orbs, atoms=gray_line_atoms  , spherical=gray_line_shell  ) if (gray_line_atoms != None) else None\n\nelse: \n    print(\"DEBUG: both spins are not used\")\n    PDOS1d = PDOS2d = PDOS3d = PDOS4d = PDOS5d = PDOS6d = PDOS7d = None\n\n# --- plotting part here, plots all calculated signals --- #\n\nif PDOS1 is not None:\n    plt.plot(energies, PDOS1, ls='-',c='r'      ,label= 'PDOS atoms:'+red_line_legend+\";\"+red_line_shell+\"-shell\")\nif PDOS2 is not None:\n    plt.plot(energies, PDOS2, ls='-',c='g'      ,label= 'PDOS atoms:'+blue_line_legend+\";\"+blue_line_shell+\"-shell\")\nif PDOS3 is not None:\n    plt.plot(energies, PDOS3, ls='-',c='b'      ,label= 'PDOS atoms:'+green_line_legend+\";\"+green_line_shell+\"-shell\")\nif PDOS4 is not None:\n    plt.plot(energies, PDOS4, ls='-',c='#FFA500',label= 'PDOS atoms:'+orange_line_legend+\";\"+orange_line_shell+\"-shell\")\nif PDOS5 is not None:\n    plt.plot(energies, PDOS5, ls='-',c='k'      ,label= 'PDOS atoms:'+black_line_legend+\";\"+black_line_shell+\"-shell\")\nif PDOS6 is not None:\n    plt.plot(energies, PDOS6, ls='-',c='y'      ,label= 'PDOS atoms:'+yellow_line_legend+\";\"+yellow_line_shell+\"-shell\")\nif PDOS7 is not None:\n    plt.plot(energies, PDOS7, ls='-',c='g'      ,label= 'PDOS atoms:'+gray_line_legend+\";\"+gray_line_shell+\"-shell\")\n\n# spin down if \"both\"\nif PDOS1d is not None:\n    plt.plot(energies, PDOS1d, ls='--',c='r')#,label= 'PDOS atoms:'+str(red_line_atoms)+\";\"+red_line_shell+\"shell\")\nif PDOS2d is not None:\n    plt.plot(energies, PDOS2d, ls='--',c='g')#,label= 'PDOS atoms:'+str(blue_line_atoms)+\";\"+red_line_shell+\"shell\")\nif PDOS3d is not None:\n    plt.plot(energies, PDOS3d, ls='--',c='b')#,label= 'PDOS atoms:'+str(green_line_atoms)+\";\"+red_line_shell+\"shell\")\nif PDOS4d is not None:\n    plt.plot(energies, PDOS4d, ls='--',c='#FFA500')#,label= 'PDOS atoms:'+str(orange_line_atoms)+\";\"+red_line_shell+\"shell\")\nif PDOS5d is not None:\n    plt.plot(energies, PDOS5d, ls='--',c='k')#,label= 'PDOS atoms:'+str(red_line_atoms)+\";\"+red_line_shell+\"shell\")\nif PDOS6d is not None:\n    plt.plot(energies, PDOS6d, ls='--',c='y')#,label= 'PDOS atoms:'+str(red_line_atoms)+\";\"+red_line_shell+\"shell\")\nif PDOS7d is not None:\n    plt.plot(energies, PDOS7d, ls='--',c='g')#,label= 'PDOS atoms:'+str(red_line_atoms)+\";\"+red_line_shell+\"shell\")\n\nif (plot and PNG) :\n    plt.title(\"PDOS eta: \"+str(eta)+' eV')\n    plt.xlabel(\"E-Efermi [eV]\")\n    plt.ylabel(\"DOS [arb.un]\")\n    plt.legend(loc='center left',bbox_to_anchor=(1,0.5))\n    plt.savefig('PDOS_eta_'+str(eta)+'eV_orbs_'+sample_orbs+'.png', bbox_inches='tight')\n\n\n# --- the end --- #\n\nprint() \nprint()\nprint(\"Done\")\nprint()\n\n", "meta": {"hexsha": "0a6025bc2d43b29d7e05b9943c7026ad941e00e7", "size": 17539, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/FePc_Au/PPdos_simple.py", "max_stars_repo_name": "Probe-Particle/PPSTM", "max_stars_repo_head_hexsha": "4434739bd737e58a2fc556dff24e8e7d6eab084e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/FePc_Au/PPdos_simple.py", "max_issues_repo_name": "Probe-Particle/PPSTM", "max_issues_repo_head_hexsha": "4434739bd737e58a2fc556dff24e8e7d6eab084e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/FePc_Au/PPdos_simple.py", "max_forks_repo_name": "Probe-Particle/PPSTM", "max_forks_repo_head_hexsha": "4434739bd737e58a2fc556dff24e8e7d6eab084e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.0899280576, "max_line_length": 312, "alphanum_fraction": 0.6220993215, "include": true, "reason": "import numpy", "num_tokens": 5348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.2909808785120009, "lm_q1q2_score": 0.1895318107435939}}
{"text": "\nimport numpy as np\nimport numpy.random as npr\nimport time#, timer\nfrom . import gelmanrubin as gr\n#reload(gr)\n#import python_models as mc\n#import models_c as mc\nimport multiprocessing as mp\n\n\ndef calcModel(nchains, functype, myfuncs, pedit, nextp, iortholist, funcx, cummodels, numparams, j, iblock=None, chains=None):\n    '''\n    Compute model light curve by combining model components.  Also returns correlated noise parameters.\n    '''\n    #Build final model from model components\n    ymodels     = np.ones((nchains, fit[j].nobj))\n    noisepars   = [[] for i in range(nchains)]\n    k           = 0\n    if chains == None:\n        chains = range(nchains)\n    if iblock == None:\n        iblock = range(cummodels[j],cummodels[j+1])\n    for i in range(cummodels[j],cummodels[j+1]):\n        if iblock.__contains__(i):\n            for n in chains:\n                if   functype[i] == 'ortho':\n                    #MODIFY COPY OF nextp ONLY\n                    pedit[n,iortholist] = myfuncs[i](pedit[n,iortholist], funcx[i], fit[j].etc[k])\n                elif (functype[i] == 'ipmap') or (functype[i] == 'spline'):\n                    ymodels[n] *= myfuncs[i](pedit[n,numparams[i]:numparams[i+1]], funcx[i], ymodels[n])\n                elif functype[i] == 'posoffset':\n                    # Record change in Position 0 => cannot orthogonalize position parameters\n                    ymodels[n] *= myfuncs[i](nextp[n,numparams[i]:numparams[i+1]], funcx[i], fit[j].etc[k])\n                elif hasattr(fit[j], 'timebins') and (functype[i] == 'ecl/tr'\n                                                  or  functype[i] == 'ramp'\n                                                  or  functype[i] == 'sinusoidal'):\n                    # Average over high-resolution model\n                    hiresmodel = myfuncs[i](pedit[n,numparams[i]:numparams[i+1]], funcx[i], fit[j].etc[k])\n                    if len(fit[j].timebins) == fit[j].nobj:\n                        for tb in range(len(fit[j].timebins)):\n                            ymodels[n,tb] *= np.mean(hiresmodel[fit[j].timebins[tb]])\n                    else:\n                        for tb in range(len(fit[j].timebinsuc)):\n                            ymodels[n,tb] *= np.mean(hiresmodel[fit[j].timebinsuc[tb]])\n                elif functype[i] == 'noise':\n                    noisepars[n]  = pedit[n,numparams[i]:numparams[i+1]]\n                else:\n                    ymodels[n] *= myfuncs[i](pedit[n,numparams[i]:numparams[i+1]], funcx[i], fit[j].etc[k])\n        k += 1\n    return ymodels, noisepars\n\n# Calculate chi^2\ndef calcChisq(y, sigma, ymodels, nchains, nextp, j, noisepars, isrednoise, wavelet, noisefunc, chains=None):\n    '''\n    Compute chi-squared with priors.\n    '''\n    if chains == None:\n        chains = range(nchains)\n    chi2 = np.zeros(nchains)\n    for n in chains:\n        if isrednoise == False:\n            #chi2[n] = mc.chisq(ymodels[n], y, sigma)\n            chi2[n]  += np.sum((ymodels[n] - y)**2 / sigma**2)\n        else:\n            chi2[n] = noisefunc(noisepars[n], ymodels[n]-y, wavelet)\n        # Apply prior, if one exists\n        if len(fit[j].ipriors) > 0:\n            pbar   = fit[j].priorvals[:,0]  #prior mean\n            psigma = np.zeros(len(pbar))    #prior standard deviation\n            # Determine psigma based on which side of asymmetric Gaussian nextp is on\n            for i in range(len(fit[j].ipriors)):\n                if nextp[n,fit[j].ipriors[i]] < pbar[i]:\n                    psigma[i] = fit[j].priorvals[i,1]\n                else:\n                    psigma[i] = fit[j].priorvals[i,2]\n                #chi2[n] += fit[j].nobj*((nextp[n,fit[j].ipriors[i]] - pbar[i])/psigma[i])**2\n                chi2[n] += ((nextp[n,fit[j].ipriors[i]] - pbar[i])/psigma[i])**2\n\n    return chi2\n\ndef demc_block(y, pars, pmin, pmax, stepsize, numit, sigma, numparams, cummodels, functype, myfuncs, funcx, iortholist, fits, gamma=None, isGR=True, ncpu=1):\n    \"\"\"\n    This function uses a differential evolution Markov chain with block updating to assess uncertainties.\n\n    PARAMETERS\n    ----------\n    y:         Array containing dependent data\n    Params:    Array of initial guess for parameters\n    #Pmin:      Array of parameter minimum values\n    #Pmax:      Array of parameter maximum values\n    stepsize:  Array of 1-sigma change in parameter per iteration\n    Numit:\t   Number of iterations to perform\n    Sigma:\t   Standard deviation of data noise in y\n    Numparams: Number of parameters for each model\n    Cummodels: Cumulative number of models used\n    Functype:  Define function type (eclipse, ramp, ip, etc), see models.py\n    Myfuncs:   Pointers to model functions\n    Funcx:\t   Array of x-axis values for myfuncs\n    fit:       List of fit objects\n    gamma:     Multiplcation factor in parameter differential, establishes acceptance rate\n\n    OUTPUTS\n    -------\n    This function returns an array of the best fitting parameters,\n    an array of all parameters over all iterations, and numaccept.\n\n    REFERENCES\n    ----------\n    Cajo J. F. Ter Braak, \"Genetic algorithms and Markov Chain Monte Carlo: Differential Evolution Markov Chain makes Bayesian computing easy,\" Biometrics, 2006.\n\n    HISTORY\n    -------\n    Adapted from mcmc.py\n        Kevin Stevenson, UChicago   August 2012\n    \"\"\"\n    global fit\n    fit   = fits\n\n    params          = np.copy(pars)\n    nchains, nump   = params.shape\n    nextp           = np.copy(params)       #Proposed parameters\n    bestp           = np.copy(params[0])    #Best-fit parameters\n    pedit           = np.copy(params)       #Editable parameters\n\n    numaccept       = 0\n    allparams       = np.zeros((nump, nchains, numit))\n    inotfixed       = np.where(stepsize != 0)[0]\n    ishare          = np.where(stepsize < 0)[0]\n    #ifree           = np.where(stepsize > 0)[0]\n    outside         = np.zeros((nchains, nump))\n    numevents       = len(fit)\n    intsteps        = np.min((numit/5,1e5))\n    isrednoise      = False\n    wavelet         = None\n    noisefunc       = None\n\n    #UPDATE PARAMTER(S) EQUAL TO OTHER PARAMETER(S)\n    if (ishare.size > 0):\n        for s in range(ishare.size):\n            params[:,ishare[s]] = params[:,int(abs(stepsize[ishare[s]])-1)]\n\n    #Define blocks\n    blocks = []\n    for j in range(numevents):\n        #Build list of blocks\n        blocks = np.concatenate((blocks, fit[j].blocks))\n        for i in range(cummodels[j],cummodels[j+1]):\n            if functype[i] == 'noise':\n                # Set up for modified chi-squared calculation using correlated noise\n                isrednoise   = True\n                wavelet      = fit[j].etc[k]\n                noisefunc    = myfuncs[i]\n\n    blocks    = blocks.astype(int)\n    iblocks   = []\n    eps       = []\n    numblocks = blocks.max() + 1\n    numbp     = np.zeros(numblocks)\n    ifree     = [[] for i in range(numblocks)]\n    for b in range(numblocks):\n        #Map block indices\n        whereb = np.where(blocks == b)[0]\n        iblocks.append(whereb)\n        #Locate indices of free parameters in each block\n        for w in whereb:\n            ifree[b] = np.concatenate((ifree[b],numparams[w]+np.where(stepsize[numparams[w]:numparams[w+1]] > 0)[0])).astype(int)\n        #Calculate number of free parameters per block\n        numbp[b] += len(ifree[b])\n        eps.append(npr.normal(0, stepsize[ifree[b]]/100., [numit,numbp[b]]))\n\n    print(\"Number of free parameters per block:\")\n    print(numbp)\n    numa        = np.zeros(numblocks)\n    if gamma == None:\n        gamma   = 2.38/np.sqrt(2.*numbp)\n    print(\"gamma:\")\n    print(gamma)\n\n    #Calc chi-squared for model type using current params\n    currchisq   = np.zeros(nchains)\n    currmodel   = [[] for i in range(numevents)]\n    for j in range(numevents):\n        currmodel[j], noisepars = calcModel(nchains, functype, myfuncs, pedit, params, iortholist[j],\n                                            funcx, cummodels, numparams, j)\n        currchisq += calcChisq(y[j], sigma[j], currmodel[j], nchains, params, j, noisepars, isrednoise, wavelet, noisefunc)\n\n    bestchisq = currchisq[0]\n\n    #GENERATE RANDOM NUMBERS FOR MCMC\n    numnotfixed = len(inotfixed)\n    unif        = npr.rand(numit,nchains)\n    randchains  = npr.randint(0,nchains,[numit,nchains,2])\n\n    #START TIMER\n    clock = timer.Timer(numit,progress = np.arange(0.05,1.01,0.05))\n\n    #Run Differential Evolution Monte Carlo algorithm 'numit' times\n    for m in range(numit):\n        #Select next event (block) to update\n        b           = m % numblocks\n        #Remove model component(s) that are taking a step\n        pedit       = np.copy(params)\n        nextmodel   = currmodel[:]\n        for j in range(numevents):\n            ymodels, noisepars = calcModel(nchains, functype, myfuncs, pedit, params, iortholist[j],\n                                           funcx, cummodels, numparams, j, iblocks[b])\n            nextmodel[j] = np.divide(currmodel[j],ymodels)\n        #Generate next step using differential evolution\n        for n in range(nchains):\n            rand1, rand2 = randchains[m,n]\n            while rand1 == n or rand2 == n or rand1 == rand2:\n                rand1, rand2 = npr.randint(0,nchains,2)\n            nextp[n,ifree[b]] = params[n,ifree[b]] + gamma[b]*(params[rand1,ifree[b]]-params[rand2,ifree[b]]) + eps[b][m]\n            #CHECK FOR NEW STEPS OUTSIDE BOUNDARIES\n            ioutside     = np.where(np.bitwise_or(nextp[n] < pmin, nextp[n] > pmax))[0]\n            if (len(ioutside) > 0):\n                nextp[n,ioutside]    = np.copy(params[n,ioutside])\n                outside[n,ioutside] += 1\n        #UPDATE PARAMTER(S) EQUAL TO OTHER PARAMETER(S)\n        if (ishare.size > 0):\n            for s in range(ishare.size):\n                nextp[:,ishare[s]] = nextp[:,int(abs(stepsize[ishare[s]])-1)]\n        #COMPUTE NEXT CHI SQUARED AND ACCEPTANCE VALUES\n        pedit       = np.copy(nextp)\n        nextchisq   = np.zeros(nchains)\n        for j in range(numevents):\n            ymodels, noisepars = calcModel(nchains, functype, myfuncs, pedit, params, iortholist[j], funcx, cummodels, numparams, j, iblocks[b])\n            nextmodel[j] = np.multiply(nextmodel[j],ymodels)\n            nextchisq   += calcChisq(y[j], sigma[j], nextmodel[j], nchains, params, j, noisepars, isrednoise, wavelet, noisefunc)\n        #CALCULATE ACCEPTANCE PROBABILITY\n        accept = np.exp(0.5 * (currchisq - nextchisq))\n        #print(b,currchisq[0], nextchisq[0], accept[0])\n        for n in range(nchains):\n            if accept[n] >= 1:\n                #ACCEPT BETTER STEP\n                numaccept    += 1\n                numa[b]      += 1\n                params[n]     = np.copy(nextp[n])\n                currchisq[n]  = np.copy(nextchisq[n])\n                if (currchisq[n] < bestchisq):\n                    bestp     = np.copy(params[n])\n                    bestchisq = np.copy(currchisq[n])\n            elif unif[m,n] <= accept[n]:\n                #ACCEPT WORSE STEP\n                numaccept    += 1\n                numa[b]      += 1\n                params[n]     = np.copy(nextp[n])\n                currchisq[n]  = np.copy(nextchisq[n])\n\n        allparams[:,:,m] = params.T\n        #PRINT INTERMEDIATE INFO\n        if ((m+1) % intsteps == 0) and (m > 0):\n            print(\"\\n\" + time.ctime())\n            #print(\"Number of times parameter tries to step outside its prior:\")\n            #print(outside)\n            print(\"Current Best Parameters: \")\n            print(bestp)\n\n            #Apply Gelman-Rubin statistic\n            if isGR:\n                #Check for no accepted steps in each chain\n                #stdev   = np.std(allparams[inotfixed],axis=1)\n                #ichain  = np.where(stdev > 0.)[0]\n                #Call test\n                #psrf, meanpsrf = gr.convergetest(allparams[inotfixed,ichain,:m+1], len(ichain))\n                psrf, meanpsrf = gr.convergetest(allparams[inotfixed,:,:m+1], nchains)\n                numconv = np.sum(np.bitwise_and(psrf < 1.01, psrf >= 1.00))\n                print(\"Gelman-Rubin statistic for free parameters:\")\n                print(psrf)\n                if numconv == numnotfixed: #and m >= 1e4:\n                    print(\"All parameters have converged to within 1% of unity. Halting MCMC.\")\n                    allparams = allparams[:,:,:m+1]\n                    break\n        clock.check(m+1)\n\n    print(\"Acceptance rate per block (%):\")\n    print(100.*numa*numblocks/numit/nchains)\n    allparams = np.reshape(allparams,(nump, (m+1)*nchains))\n    return allparams, bestp, numaccept, (m+1)*nchains\n\n#****************************************************************\n\ndef calcChi2(nchains, functype, myfuncs, pedit, nextp, iortholist, funcx, cummodels, numparams, j, isrednoise, wavelet, noisefunc, systematics, chains=None):\n    '''\n    Compute model light curve by combining model components.\n    '''\n    #Build final model from model components\n    ymodels     = np.ones((nchains, fit[j].nobj))\n    noisepars   = [[] for i in range(nchains)]\n    k           = 0\n    if chains == None:\n        chains = range(nchains)\n    for i in range(cummodels[j],cummodels[j+1]):\n        for n in chains:\n            if   functype[i] == 'ortho':\n                #MODIFY COPY OF nextp ONLY\n                pedit[n,iortholist] = myfuncs[i](pedit[n,iortholist], funcx[i], fit[j].etc[k])\n            elif (functype[i] == 'ipmap') or (functype[i] == 'spline'):\n                ymodels[n] *= myfuncs[i](pedit[n,numparams[i]:numparams[i+1]], funcx[i], ymodels[n])\n            elif functype[i] == 'posoffset':\n                # Record change in Position 0 => cannot orthogonalize position parameters\n                ymodels[n] *= myfuncs[i](nextp[n,numparams[i]:numparams[i+1]], funcx[i], fit[j].etc[k])\n            elif hasattr(fit[j], 'timebins') and (functype[i] == 'ecl/tr'\n                                              or  functype[i] == 'ramp'\n                                              or  functype[i] == 'sinusoidal'):\n                # Average over high-resolution model\n                hiresmodel = myfuncs[i](pedit[n,numparams[i]:numparams[i+1]], funcx[i], fit[j].etc[k])\n                if len(fit[j].timebins) == fit[j].nobj:\n                    for tb in range(len(fit[j].timebins)):\n                        ymodels[n,tb] *= np.mean(hiresmodel[fit[j].timebins[tb]])\n                else:\n                    for tb in range(len(fit[j].timebinsuc)):\n                        ymodels[n,tb] *= np.mean(hiresmodel[fit[j].timebinsuc[tb]])\n            elif functype[i] == 'noise':\n                noisepars[n]  = pedit[n,numparams[i]:numparams[i+1]]\n            else:\n                ymodels[n] *= myfuncs[i](pedit[n,numparams[i]:numparams[i+1]], funcx[i], fit[j].etc[k])\n        k += 1\n\n    # Calculate chi^2\n    chi2 = np.zeros(nchains)\n    for n in chains:\n        if isrednoise == False:\n            #chi2[n] = mc.chisq(ymodels[n]*systematics[n][j], data[j], unc[j])\n            chi2[n] = np.sum((ymodels[n]*systematics[n][j] - data[j])**2 / unc[j]**2)\n        else:\n            chi2[n] = noisefunc(noisepars[n], ymodels[n]*systematics[n][j]-data[j], wavelet)\n        # Apply prior, if one exists\n        if len(fit[j].ipriors) > 0:\n            pbar   = fit[j].priorvals[:,0]  #prior mean\n            psigma = np.zeros(len(pbar))    #prior standard deviation\n            # Determine psigma based on which side of asymmetric Gaussian nextp is on\n            for i in range(len(fit[j].ipriors)):\n                if nextp[n,fit[j].ipriors[i]] < pbar[i]:\n                    psigma[i] = fit[j].priorvals[i,1]\n                else:\n                    psigma[i] = fit[j].priorvals[i,2]\n                #chi2[n] += fit[j].nobj*((nextp[n,fit[j].ipriors[i]] - pbar[i])/psigma[i])**2\n                chi2[n] += ((nextp[n,fit[j].ipriors[i]] - pbar[i])/psigma[i])**2\n\n    return chi2\n\n#\ndef writeChi2(chi2):\n    '''\n    Write models after multiprocessing.\n    '''\n    global nextchisq\n    nextchisq += chi2\n    return\n\ndef demc(y, pars, pmin, pmax, stepsize, numit, sigma, numparams, cummodels, functype, myfuncs, funcx, iortholist, nights, fits, gamma=None, isGR=True, ncpu=1):\n    \"\"\"\n    This function uses a differential evolution Markov chain to assess uncertainties.\n\n    PARAMETERS\n    ----------\n    y:         Array containing dependent data\n    Params:    Array of initial guess for parameters\n    #Pmin:      Array of parameter minimum values\n    #Pmax:      Array of parameter maximum values\n    stepsize:  Array of 1-sigma change in parameter per iteration\n    Numit:\t   Number of iterations to perform\n    Sigma:\t   Standard deviation of data noise in y\n    Numparams: Number of parameters for each model\n    Cummodels: Cumulative number of models used\n    Functype:  Define function type (eclipse, ramp, ip, etc), see models.py\n    Myfuncs:   Pointers to model functions\n    Funcx:\t   Array of x-axis values for myfuncs\n    fit:       List of fit objects\n    gamma:     Multiplcation factor in parameter differential, establishes acceptance rate\n\n    OUTPUTS\n    -------\n    This function returns an array of the best fitting parameters,\n    an array of all parameters over all iterations, and numaccept.\n\n    REFERENCES\n    ----------\n    Cajo J. F. Ter Braak, \"Genetic algorithms and Markov Chain Monte Carlo: Differential Evolution Markov Chain makes Bayesian computing easy,\" Biometrics, 2006.\n\n    HISTORY\n    -------\n    Adapted from mcmc.py\n        Kevin Stevenson, UChicago   August 2012\n    Multiplied prior by number of points in fit\n                                    January 2014\n    \"\"\"\n    global nextchisq, fit, data, unc\n    fit   = fits\n    data  = y\n    unc   = sigma\n\n    params          = np.copy(pars)\n    nchains, nump   = params.shape\n    nextp           = np.copy(params)       #Proposed parameters\n    bestp           = np.copy(params[0])    #Best-fit parameters\n    pedit           = np.copy(params)       #Editable parameters\n\n    numaccept       = 0\n    #allparams must be 64-bit!\n    allparams       = np.zeros((nump, nchains, numit))\n    inotfixed       = np.where(stepsize != 0)[0]\n    ishare          = np.where(stepsize < 0)[0]\n    ifree           = np.where(stepsize > 0)[0]\n    outside         = np.zeros((nchains, nump))\n    numevents       = len(fit)\n    intsteps        = np.min((numit/5,1e5))\n    isrednoise      = False\n    wavelet         = None\n    noisefunc       = None\n    numfree         = len(ifree)\n    print(\"Number of free parameters:\")\n    print(len(ifree))\n    if gamma == None:\n        gamma     = 2.38/np.sqrt(2*numfree)\n    print('Gamma = ' + str(gamma))\n\n    #UPDATE PARAMTER(S) EQUAL TO OTHER PARAMETER(S)\n    if (ishare.size > 0):\n        for s in range(ishare.size):\n            params[:,ishare[s]] = params[:,int(abs(stepsize[ishare[s]])-1)]\n\n    # Construct non-analytic systematic model\n    for nn in np.unique(nights):\n        tonight   = np.where(nights == nn)[0]\n        if hasattr(fit[tonight[0]], 'whiteparams') and fit[tonight[0]].whiteparams != None:\n            if type(fit[tonight[0]].whiteparams) == type(np.array([])):\n                #Only 1 model in model for white LC, grandfathered code\n                #print(\"WARNING: You are using grandfathered code.  Update whiteparams to handle multiple models.\")\n                #whitemodel  = np.zeros((nchains,len(fit[tonight[0]].good)))\n                i = int(fit[tonight[0]].whiteparams[0])\n                whitemodel = myfuncs[i](fit[tonight[0]].whiteparams[1:], fit[tonight[0]].tuall, None)\n            else:\n                #Any number of models can be used to build white LC\n                whitemodel  = np.ones((nchains,len(fit[tonight[0]].good)))\n                for k in range(len(fit[tonight[0]].whiteparams)):\n                    i = int(fit[tonight[0]].whiteparams[k][0])\n                    whitemodel *= myfuncs[i](fit[tonight[0]].whiteparams[k][1:], fit[tonight[0]].tuall, None)\n                    #whitemodel *= myfuncs[i](fit[tonight[0]].whiteparams[k][1:], funcxuc[i], None)\n            for j in tonight:\n                fit[j].whitemodel = whitemodel\n        elif hasattr(fit[tonight[0]], 'iswhitelc') and fit[tonight[0]].iswhitelc != False:\n            whitemodel = np.zeros((nchains,len(fit[tonight[0]].good)))\n            weight     = np.zeros((nchains,len(fit[tonight[0]].good)))\n            for n in range(nchains):\n                for j in tonight:\n                    k = 0\n                    for i in range(cummodels[j],cummodels[j+1]):\n                        if functype[i] == 'ecl/tr':\n                            specmodel = myfuncs[i](pedit[n,numparams[i]:numparams[i+1]], funcx[i], fit[j].etc[k])\n                            specmodeluc = np.zeros(len(fit[j].clipmask))\n                            specmodeluc[fit[j].isclipmask] = specmodel\n                            whitemodel[n,fit[j].isgood] += specmodeluc\n                            weight    [n,fit[j].isgood] += specmodel[0]\n                        k    += 1\n                whitemodel[n] /= weight[n]\n                #FINDME: Need to determine exact anchor point\n                #slope      = fit[0].iswhitelc / (1-whitemodel[n].min())\n                #offset     = 1 - slope\n                #whitemodel[n] = slope*whitemodel[n] + offset\n            for j in tonight:\n                fit[j].whitemodel = whitemodel\n        else:\n            for j in tonight:\n                fit[j].whitemodel = np.ones((nchains,len(fit[j].good)))\n\n    #Calc chi-squared for model type using current params\n    currchisq   = np.zeros(nchains)\n    noisepars   = [[] for i in range(nchains)]\n    for j in range(numevents):\n        #Build final model from model components\n        ymodels     = np.ones((nchains, fit[j].nobj))\n        k           = 0\n        for i in range(cummodels[j],cummodels[j+1]):\n            for n in range(nchains):\n                if   functype[i] == 'ortho':\n                    #MODIFY COPY OF nextp ONLY\n                    pedit[n,iortholist[j]] = myfuncs[i](pedit[n,iortholist[j]], funcx[i], fit[j].etc[k])\n                elif (functype[i] == 'ipmap') or (functype[i] == 'spline'):\n                    ymodels[n] *= myfuncs[i](pedit[n,numparams[i]:numparams[i+1]], funcx[i], ymodels[n])\n                elif functype[i] == 'posoffset':\n                    # Record change in Position 0 => cannot orthogonalize position parameters\n                    ymodels[n] *= myfuncs[i](nextp[n,numparams[i]:numparams[i+1]], funcx[i], fit[j].etc[k])\n                elif hasattr(fit[j], 'timebins') and (functype[i] == 'ecl/tr'\n                                                  or  functype[i] == 'ramp'\n                                                  or  functype[i] == 'sinusoidal'):\n                    # Average over high-resolution model\n                    hiresmodel = myfuncs[i](pedit[n,numparams[i]:numparams[i+1]], funcx[i], fit[j].etc[k])\n                    if len(fit[j].timebins) == fit[j].nobj:\n                        for tb in range(len(fit[j].timebins)):\n                            ymodels[n,tb] *= np.mean(hiresmodel[fit[j].timebins[tb]])\n                    else:\n                        for tb in range(len(fit[j].timebinsuc)):\n                            ymodels[n,tb] *= np.mean(hiresmodel[fit[j].timebinsuc[tb]])\n                elif functype[i] == 'noise':\n                    # Set up for modified chi-squared calculation using correlated noise\n                    isrednoise   = True\n                    wavelet      = fit[j].etc[k]\n                    noisefunc    = myfuncs[i]\n                    noisepars[n] = pedit[n,numparams[i]:numparams[i+1]]\n                else:\n                    ymodels[n] *= myfuncs[i](pedit[n,numparams[i]:numparams[i+1]], funcx[i], fit[j].etc[k])\n            k += 1\n            #Multiply analytic model by non-analytic systematics model\n            systematics = fit[j].whitelc*fit[j].refspeclc/(fit[j].whitemodel[n][fit[j].isgood].flatten())[fit[j].isclipmask]\n            ymodels[n] *= systematics\n        # Calculate chi^2\n        for n in range(nchains):\n            if isrednoise == False:\n                currchisq[n]  += np.sum((ymodels[n] - y[j])**2 / sigma[j]**2)\n                #currchisq[n]  += mc.chisq(ymodels[n], y[j], sigma[j])\n            else:\n                currchisq[n]  += noisefunc(noisepars[n], ymodels[n]-y[j], wavelet)\n            # Apply prior, if one exists\n            if len(fit[j].ipriors) > 0:\n                pbar   = fit[j].priorvals[:,0]  #prior mean\n                psigma = np.zeros(len(pbar))    #prior standard deviation\n                # Determine psigma based on which side of asymmetric Gaussian nextp is on\n                for i in range(len(fit[j].ipriors)):\n                    if nextp[n,fit[j].ipriors[i]] < pbar[i]:\n                        psigma[i] = fit[j].priorvals[i,1]\n                    else:\n                        psigma[i] = fit[j].priorvals[i,2]\n                    #currchisq[n] += fit[j].nobj*((nextp[n,fit[j].ipriors[i]] - pbar[i])/psigma[i])**2\n                    currchisq[n] += ((nextp[n,fit[j].ipriors[i]] - pbar[i])/psigma[i])**2\n\n    bestchisq = currchisq[0]\n\n    #GENERATE RANDOM NUMBERS FOR MCMC\n    numnotfixed = len(inotfixed)\n    unif        = npr.rand(numit,nchains)\n\n    #START TIMER\n    clock = timer.Timer(numit,progress = np.arange(0.05,1.01,0.05))\n\n    #Run Differential Evolution Monte Carlo algorithm 'numit' times\n    b = gamma*stepsize[ifree]/100.\n    for m in range(numit):\n        for n in range(nchains):\n            #Generate next step using differential evolution\n            rand1, rand2 = npr.randint(0,nchains,2)\n            while rand1 == n or rand2 == n or rand1 == rand2:\n                rand1, rand2 = npr.randint(0,nchains,2)\n            nextp[n,ifree] = params[n,ifree] + gamma*(params[rand1,ifree]-params[rand2,ifree]) \\\n                                             + npr.normal(0, b, numfree)\n            #CHECK FOR NEW STEPS OUTSIDE BOUNDARIES\n            ioutside     = np.where(np.bitwise_or(nextp[n] < pmin, nextp[n] > pmax))[0]\n            if (len(ioutside) > 0):\n                nextp[n,ioutside]    = np.copy(params[n,ioutside])\n                outside[n,ioutside] += 1\n        #UPDATE PARAMTER(S) EQUAL TO OTHER PARAMETER(S)\n        if (ishare.size > 0):\n            for s in range(ishare.size):\n                nextp[:,ishare[s]] = nextp[:,int(abs(stepsize[ishare[s]])-1)]\n        # Construct non-analytic systematic model\n        for nn in np.unique(nights):\n            tonight   = np.where(nights == nn)[0]\n            if hasattr(fit[tonight[0]], 'whiteparams') and fit[tonight[0]].whiteparams != None:\n                pass\n            elif hasattr(fit[tonight[0]], 'iswhitelc') and fit[tonight[0]].iswhitelc != False:\n                whitemodel = np.zeros((nchains,len(fit[tonight[0]].good)))\n                weight     = np.zeros((nchains,len(fit[tonight[0]].good)))\n                for n in range(nchains):\n                    for j in tonight:\n                        k = 0\n                        for i in range(cummodels[j],cummodels[j+1]):\n                            if functype[i] == 'ecl/tr':\n                                specmodel = myfuncs[i](nextp[n,numparams[i]:numparams[i+1]], funcx[i], fit[j].etc[k])\n                                specmodeluc = np.zeros(len(fit[j].clipmask))\n                                specmodeluc[fit[j].isclipmask] = specmodel\n                                whitemodel[n,fit[j].isgood] += specmodeluc\n                                weight    [n,fit[j].isgood] += specmodel[0]\n                            k    += 1\n                    whitemodel[n] /= weight[n]\n                    #FINDME: Need to determine exact anchor point\n                    #Also modify statement in w6model.py\n                    #slope      = fit[0].iswhitelc / (1-whitemodel[n].min())\n                    #offset     = 1 - slope\n                    #whitemodel[n] = slope*whitemodel[n] + offset\n                for j in tonight:\n                    fit[j].whitemodel = whitemodel\n            else:\n                for j in tonight:\n                    fit[j].whitemodel = np.ones((nchains,len(fit[j].good)))\n        # Assemble systematics models\n        systematics = [[] for n in range(nchains)]\n        for n in range(nchains):\n            for j in range(numevents):\n                systematics[n].append(fit[j].whitelc*fit[j].refspeclc/(fit[j].whitemodel[n][fit[j].isgood].flatten())[fit[j].isclipmask])\n                #systematics[n].append(((fit[j].whitelc/whitemodel[n])[fit[j].isgood].flatten())[fit[j].isclipmask])\n        #COMPUTE NEXT CHI SQUARED AND ACCEPTANCE VALUES\n        pedit        = np.copy(nextp)\n        nextchisq    = np.zeros(nchains)\n        if ncpu == 1:\n            # Only 1 CPU\n            for j in range(numevents):\n                nextchisq += calcChi2(nchains, functype, myfuncs, pedit, nextp, iortholist[j], funcx, cummodels, numparams, j, isrednoise=isrednoise, wavelet=wavelet, noisefunc=noisefunc, systematics=systematics)\n        else:\n            # Multiple CPUs\n            # Code works but is less efficient\n            pool = mp.Pool(ncpu)\n            for j in range(numevents):\n                res = pool.apply_async(calcChi2, args=(nchains, functype, myfuncs, pedit, nextp, iortholist[j], funcx, cummodels, numparams, j, isrednoise, wavelet, noisefunc, systematics), callback=writeChi2)\n\n            pool.close()\n            pool.join()\n            res.wait()\n\n        #CALCULATE ACCEPTANCE PROBABILITY\n        accept = np.exp(0.5 * (currchisq - nextchisq))\n        for n in range(nchains):\n            if (accept[n] >= 1) or (unif[m,n] <= accept[n]):\n                #ACCEPT STEP\n                numaccept    += 1\n                params[n]     = np.copy(nextp[n])\n                currchisq[n]  = nextchisq[n]\n                if (currchisq[n] < bestchisq):\n                    bestp     = np.copy(params[n])\n                    bestchisq = np.copy(currchisq[n])\n\n        allparams[:,:,m] = params.T\n        #PRINT INTERMEDIATE INFO\n        if ((m+1) % intsteps == 0) and (m > 0):\n            print(\"\\n\" + time.ctime())\n            #print(\"Number of times parameter tries to step outside its prior:\")\n            #print(outside)\n            print(\"Current Best Parameters: \")\n            print(bestp)\n\n            #Apply Gelman-Rubin statistic\n            if isGR:\n                #Check for no accepted steps in each chain\n                stdev   = np.std(allparams[inotfixed[0],:,:m+1],axis=1)\n                ichain  = np.where(stdev > 1e-8)[0]\n                #Call test\n                foo = allparams[inotfixed]\n                psrf, meanpsrf = gr.convergetest(foo[:,ichain,:m+1], len(ichain))\n                #psrf, meanpsrf = gr.convergetest(allparams[inotfixed,:,:m+1], nchains)\n                numconv = np.sum(np.bitwise_and(psrf < 1.01, psrf >= 1.00))\n                print(\"Gelman-Rubin statistic for free parameters:\")\n                print(psrf)\n                if numconv == numnotfixed: #and j >= 1e4:\n                    print(\"All parameters have converged to within 1% of unity. Halting MCMC.\")\n                    allparams = allparams[:,:,:m+1]\n                    break\n        clock.check(m+1)\n\n    #Check for no accepted steps in each chain\n    stdev   = np.std(allparams[inotfixed[0]],axis=1)\n    ichain  = np.where(stdev > 1e-8)[0]\n    print(\"Number of good chains: \" + str(len(ichain)))\n    #print(len(ichain), ichain)\n    #print(stdev)\n    allparams = allparams[:,ichain]\n    allparams = np.reshape(allparams,(nump, (m+1)*len(ichain)))\n    return allparams, bestp, numaccept, (m+1)*len(ichain)\n\n\n\ndef demcz(y, pars, stdpburnin, pmin, pmax, stepsize, numit, sigma, numparams, cummodels, functype, myfuncs, funcx, iortholist, nights, fits, gamma=None, isGR=True, ncpu=1):\n    \"\"\"\n    This function uses a differential evolution Markov chain with fewer chains to assess uncertainties.\n\n    PARAMETERS\n    ----------\n    y:         Array containing dependent data\n    Params:    Array of initial guess for parameters\n    stdpburnin:Standard deviation of allparams from burn-in\n    Pmin:      Array of parameter minimum values\n    Pmax:      Array of parameter maximum values\n    stepsize:  Array of 1-sigma change in parameter per iteration\n    Numit:\t   Number of iterations to perform\n    Sigma:\t   Standard deviation of data noise in y\n    Numparams: Number of parameters for each model\n    Cummodels: Cumulative number of models used\n    Functype:  Define function type (eclipse, ramp, ip, etc), see models.py\n    Myfuncs:   Pointers to model functions\n    Funcx:\t   Array of x-axis values for myfuncs\n    fit:       List of fit objects\n    gamma:     Multiplication factor in parameter differential, establishes acceptance rate\n\n    OUTPUTS\n    -------\n    This function returns an array of the best fitting parameters,\n    an array of all parameters over all iterations, and numaccept.\n\n    REFERENCES\n    ----------\n    Cajo J. F. Ter Braak, \"Differential Evolution Markov Chain with snooker updater and fewer chains\" Stat Comput, 2008.\n\n    HISTORY\n    -------\n    Adapted from mcmc.py                            August 2012\n        Kevin Stevenson, UChicago\n    Multiplied prior by number of points in fit     January 2014\n    Adapted from demc()                             August 2014\n\n    \"\"\"\n    global nextchisq, fit, data, unc\n    fit   = fits\n    data  = y\n    unc   = sigma\n\n    params          = np.copy(pars)\n    nchains, nump   = params.shape\n    nextp           = np.copy(params)       #Proposed parameters\n    bestp           = np.copy(params[0])    #Best-fit parameters\n    pedit           = np.copy(params)       #Editable parameters\n\n    numaccept       = 0\n    ifixed          = np.where(stepsize == 0)[0]    #Indices of fixed parameters\n    inotfixed       = np.where(stepsize != 0)[0]    #Indices of non-fixed parameters\n    ishare          = np.where(stepsize < 0)[0]     #Indices of shared parameters\n    ifree           = np.where(stepsize > 0)[0]     #Indices of free parameters\n    #outside         = np.zeros((nchains, nump))\n    numevents       = len(fit)\n    intsteps        = np.min((numit/5,1e5))         #Number of steps before checking G-R statistic\n    isrednoise      = False\n    wavelet         = None\n    noisefunc       = None\n    numfree         = len(ifree)\n    print(\"Number of free parameters: \" + str(len(ifree)))\n    if gamma == None:\n        gamma     = 2.38/np.sqrt(2*numfree)\n    print('Gamma = ' + str(gamma))\n\n    #UPDATE PARAMETER(S) EQUAL TO OTHER PARAMETER(S)\n    if (ishare.size > 0):\n        ishareptr = []\n        for s in range(ishare.size):\n            ishareptr.append(int(abs(stepsize[ishare[s]])-1))   #Pointer to where parameter is shared from\n            params[:,ishare[s]] = params[:,ishareptr[s]]\n\n    #INITIALIZE FIRST 10*numfree PARAMETERS IN allparams\n    ninit   = 10*numfree\n    numit  += ninit\n    #if numit < (ninit + 10):\n    #    numit == 1ninit + 10\n    allparams       = np.zeros((nump, nchains, numit))  #allparams must be 64-bit!\n    #Populate fixed parameters\n    allparams[ifixed,:,:ninit] = params[:,ifixed].T[:,:,np.newaxis]\n    #Populate free parameters\n    for p in ifree:\n        allparams[p,:,:ninit] = np.random.normal(params[0,p],stdpburnin[p],[nchains,ninit])\n    #Update shared parameters\n    if (ishare.size > 0):\n        allparams[ishare,:,:ninit] = allparams[ishareptr,:,:ninit]\n\n    # Construct non-analytic systematic model\n    for nn in np.unique(nights):\n        tonight   = np.where(nights == nn)[0]\n        if hasattr(fit[tonight[0]], 'whiteparams') and fit[tonight[0]].whiteparams != None:\n            if type(fit[tonight[0]].whiteparams) == type(np.array([])):\n                #Only 1 model in model for white LC, grandfathered code\n                #print(\"WARNING: You are using grandfathered code.  Update whiteparams to handle multiple models.\")\n                #whitemodel  = np.zeros((nchains,len(fit[tonight[0]].good)))\n                i = int(fit[tonight[0]].whiteparams[0])\n                whitemodel = myfuncs[i](fit[tonight[0]].whiteparams[1:], fit[tonight[0]].tuall, None)\n            else:\n                #Any number of models can be used to build white LC\n                whitemodel  = np.ones((nchains,len(fit[tonight[0]].good)))\n                for k in range(len(fit[tonight[0]].whiteparams)):\n                    i = int(fit[tonight[0]].whiteparams[k][0])\n                    whitemodel *= myfuncs[i](fit[tonight[0]].whiteparams[k][1:], fit[tonight[0]].tuall, None)\n                    #whitemodel *= myfuncs[i](fit[tonight[0]].whiteparams[k][1:], funcxuc[i], None)\n            for j in tonight:\n                fit[j].whitemodel = whitemodel\n        elif hasattr(fit[tonight[0]], 'iswhitelc') and fit[tonight[0]].iswhitelc != False:\n            whitemodel = np.zeros((nchains,len(fit[tonight[0]].good)))\n            weight     = np.zeros((nchains,len(fit[tonight[0]].good)))\n            for n in range(nchains):\n                for j in tonight:\n                    k = 0\n                    for i in range(cummodels[j],cummodels[j+1]):\n                        if functype[i] == 'ecl/tr':\n                            specmodel = myfuncs[i](pedit[n,numparams[i]:numparams[i+1]], funcx[i], fit[j].etc[k])\n                            specmodeluc = np.zeros(len(fit[j].clipmask))\n                            specmodeluc[fit[j].isclipmask] = specmodel\n                            whitemodel[n,fit[j].isgood] += specmodeluc\n                            weight    [n,fit[j].isgood] += specmodel[0]\n                        k    += 1\n                whitemodel[n] /= weight[n]\n                #FINDME: Need to determine exact anchor point\n                #slope      = fit[0].iswhitelc / (1-whitemodel[n].min())\n                #offset     = 1 - slope\n                #whitemodel[n] = slope*whitemodel[n] + offset\n            for j in tonight:\n                fit[j].whitemodel = whitemodel\n        else:\n            for j in tonight:\n                fit[j].whitemodel = np.ones((nchains,len(fit[j].good)))\n\n    #Calc chi-squared for model type using current params\n    currchisq   = np.zeros(nchains)\n    noisepars   = [[] for i in range(nchains)]\n    for j in range(numevents):\n        #Build final model from model components\n        ymodels     = np.ones((nchains, fit[j].nobj))\n        k           = 0\n        for i in range(cummodels[j],cummodels[j+1]):\n            for n in range(nchains):\n                if   functype[i] == 'ortho':\n                    #MODIFY COPY OF nextp ONLY\n                    pedit[n,iortholist[j]] = myfuncs[i](pedit[n,iortholist[j]], funcx[i], fit[j].etc[k])\n                elif (functype[i] == 'ipmap') or (functype[i] == 'spline'):\n                    ymodels[n] *= myfuncs[i](pedit[n,numparams[i]:numparams[i+1]], funcx[i], ymodels[n])\n                elif functype[i] == 'posoffset':\n                    # Record change in Position 0 => cannot orthogonalize position parameters\n                    ymodels[n] *= myfuncs[i](nextp[n,numparams[i]:numparams[i+1]], funcx[i], fit[j].etc[k])\n                elif hasattr(fit[j], 'timebins') and (functype[i] == 'ecl/tr'\n                                                  or  functype[i] == 'ramp'\n                                                  or  functype[i] == 'sinusoidal'):\n                    # Average over high-resolution model\n                    hiresmodel = myfuncs[i](pedit[n,numparams[i]:numparams[i+1]], funcx[i], fit[j].etc[k])\n                    if len(fit[j].timebins) == fit[j].nobj:\n                        for tb in range(len(fit[j].timebins)):\n                            ymodels[n,tb] *= np.mean(hiresmodel[fit[j].timebins[tb]])\n                    else:\n                        for tb in range(len(fit[j].timebinsuc)):\n                            ymodels[n,tb] *= np.mean(hiresmodel[fit[j].timebinsuc[tb]])\n                elif functype[i] == 'noise':\n                    # Set up for modified chi-squared calculation using correlated noise\n                    isrednoise   = True\n                    wavelet      = fit[j].etc[k]\n                    noisefunc    = myfuncs[i]\n                    noisepars[n] = pedit[n,numparams[i]:numparams[i+1]]\n                else:\n                    ymodels[n] *= myfuncs[i](pedit[n,numparams[i]:numparams[i+1]], funcx[i], fit[j].etc[k])\n            k += 1\n            #Multiply analytic model by non-analytic systematics model\n            systematics = fit[j].whitelc*fit[j].refspeclc/(fit[j].whitemodel[n][fit[j].isgood].flatten())[fit[j].isclipmask]\n            ymodels[n] *= systematics\n        # Calculate chi^2\n        for n in range(nchains):\n            if isrednoise == False:\n                #currchisq[n]  += mc.chisq(ymodels[n], y[j], sigma[j])\n                currchisq[n]  += np.sum((ymodels[n] - y[j])**2 / sigma[j]**2)\n            else:\n                currchisq[n]  += noisefunc(noisepars[n], ymodels[n]-y[j], wavelet)\n            # Apply prior, if one exists\n            if len(fit[j].ipriors) > 0:\n                pbar   = fit[j].priorvals[:,0]  #prior mean\n                psigma = np.zeros(len(pbar))    #prior standard deviation\n                # Determine psigma based on which side of asymmetric Gaussian nextp is on\n                for i in range(len(fit[j].ipriors)):\n                    if nextp[n,fit[j].ipriors[i]] < pbar[i]:\n                        psigma[i] = fit[j].priorvals[i,1]\n                    else:\n                        psigma[i] = fit[j].priorvals[i,2]\n                    #currchisq[n] += fit[j].nobj*((nextp[n,fit[j].ipriors[i]] - pbar[i])/psigma[i])**2\n                    currchisq[n] += ((nextp[n,fit[j].ipriors[i]] - pbar[i])/psigma[i])**2\n\n    bestchisq = currchisq[0]\n\n    #GENERATE RANDOM NUMBERS FOR MCMC\n    unif        = npr.rand(numit,nchains)           #Acceptance\n    snooker     = npr.rand(numit,nchains)           #If <0.1, set gamma = 1 during step\n    randchain   = npr.randint(0,nchains,[2,numit,nchains])  #Pairs of chains\n    b = gamma*stepsize[ifree]/100.\n    epsilon     = npr.normal(0, b, [numit,nchains,numfree])\n\n    #START TIMER\n    clock = timer.Timer(numit-ninit,progress = np.arange(0.05,1.01,0.05))\n\n    #Run Differential Evolution Monte Carlo algorithm 'numit' times\n    numnotfixed = len(inotfixed)\n    for m in range(ninit,numit):\n        '''\n        #Code below is slower, possibly because array copies are made???\n        #Generate next step using differential evolution\n        randstep    = npr.randint(0,m,[2,nchains])\n        nextp[:,ifree] = params[:,ifree] + gamma*(allparams[ifree][:,randchain[0,m],randstep[0]] \\\n                                                - allparams[ifree][:,randchain[1,m],randstep[1]]).T \\\n                                                + epsilon[m]\n        '''\n        randstep    = npr.randint(0,m,[2,nchains])\n        for n in range(nchains):\n            #Generate next step using differential evolution\n            if snooker[m,n] < 0.1:\n                #Set gamma = 1 to jump between modes (bimodal distribution)\n                nextp[n,ifree] = params[n,ifree] + (allparams[ifree,randchain[0,m,n],randstep[0,n]] \\\n                                                  - allparams[ifree,randchain[1,m,n],randstep[1,n]]) \\\n                                                  + epsilon[m,n]\n            else:\n                nextp[n,ifree] = params[n,ifree] + gamma*(allparams[ifree,randchain[0,m,n],randstep[0,n]] \\\n                                                        - allparams[ifree,randchain[1,m,n],randstep[1,n]]) \\\n                                                        + epsilon[m,n]\n        #CHECK FOR NEW STEPS OUTSIDE BOUNDARIES\n        ioutside     = np.where(np.bitwise_or(nextp < pmin, nextp > pmax))\n        if (len(ioutside) > 0):\n            nextp[ioutside]    = np.copy(params[ioutside])\n        #UPDATE PARAMTER(S) EQUAL TO OTHER PARAMETER(S)\n        if (ishare.size > 0):\n            nextp[:,ishare] = nextp[:,ishareptr]\n        # Construct non-analytic systematic model\n        for nn in np.unique(nights):\n            tonight   = np.where(nights == nn)[0]\n            if hasattr(fit[tonight[0]], 'whiteparams') and fit[tonight[0]].whiteparams != None:\n                pass\n            elif hasattr(fit[tonight[0]], 'iswhitelc') and fit[tonight[0]].iswhitelc != False:\n                print(\"***WARNING: whiteparams not defined.***\")\n                whitemodel = np.zeros((nchains,len(fit[tonight[0]].good)))\n                weight     = np.zeros((nchains,len(fit[tonight[0]].good)))\n                for n in range(nchains):\n                    for j in tonight:\n                        k = 0\n                        for i in range(cummodels[j],cummodels[j+1]):\n                            if functype[i] == 'ecl/tr':\n                                specmodel = myfuncs[i](nextp[n,numparams[i]:numparams[i+1]], funcx[i], fit[j].etc[k])\n                                specmodeluc = np.zeros(len(fit[j].clipmask))\n                                specmodeluc[fit[j].isclipmask] = specmodel\n                                whitemodel[n,fit[j].isgood] += specmodeluc\n                                weight    [n,fit[j].isgood] += specmodel[0]\n                            k    += 1\n                    whitemodel[n] /= weight[n]\n                    #FINDME: Need to determine exact anchor point\n                    #Also modify statement in w6model.py\n                    #slope      = fit[0].iswhitelc / (1-whitemodel[n].min())\n                    #offset     = 1 - slope\n                    #whitemodel[n] = slope*whitemodel[n] + offset\n                for j in tonight:\n                    fit[j].whitemodel = whitemodel\n            else:\n                for j in tonight:\n                    fit[j].whitemodel = np.ones((nchains,len(fit[j].good)))\n        # Assemble systematics models\n        systematics = [[] for n in range(nchains)]\n        for n in range(nchains):\n            for j in range(numevents):\n                systematics[n].append(fit[j].whitelc*fit[j].refspeclc/(fit[j].whitemodel[n][fit[j].isgood].flatten())[fit[j].isclipmask])\n                #systematics[n].append(((fit[j].whitelc/whitemodel[n])[fit[j].isgood].flatten())[fit[j].isclipmask])\n        #COMPUTE NEXT CHI SQUARED AND ACCEPTANCE VALUES\n        pedit        = np.copy(nextp)\n        nextchisq    = np.zeros(nchains)\n        if ncpu == 1:\n            # Only 1 CPU\n            for j in range(numevents):\n                nextchisq += calcChi2(nchains, functype, myfuncs, pedit, nextp, iortholist[j], funcx, cummodels, numparams, j, isrednoise=isrednoise, wavelet=wavelet, noisefunc=noisefunc, systematics=systematics)\n        else:\n            # Multiple CPUs\n            # Code works but is less efficient\n            pool = mp.Pool(ncpu)\n            for j in range(numevents):\n                res = pool.apply_async(calcChi2, args=(nchains, functype, myfuncs, pedit, nextp, iortholist[j], funcx, cummodels, numparams, j, isrednoise, wavelet, noisefunc, systematics), callback=writeChi2)\n\n            pool.close()\n            pool.join()\n            res.wait()\n\n        #CALCULATE ACCEPTANCE PROBABILITY\n        accept = np.exp(0.5 * (currchisq - nextchisq))\n        for n in range(nchains):\n            if (accept[n] >= 1) or (unif[m,n] <= accept[n]):\n                #ACCEPT STEP\n                numaccept    += 1\n                params[n]     = np.copy(nextp[n])\n                currchisq[n]  = nextchisq[n]\n                if (currchisq[n] < bestchisq):\n                    bestp     = np.copy(params[n])\n                    bestchisq = np.copy(currchisq[n])\n\n        allparams[:,:,m] = params.T\n        #PRINT INTERMEDIATE INFO\n        if ((m+1-ninit) % intsteps == 0) and (m > ninit):\n            print(\"\\n\" + time.ctime())\n            #print(\"Number of times parameter tries to step outside its prior:\")\n            #print(outside)\n            print(\"Current Best Parameters: \")\n            print(bestp)\n\n            #Apply Gelman-Rubin statistic\n            if isGR:\n                #Check for no accepted steps in each chain\n                stdev   = np.std(allparams[inotfixed[0],:,ninit:m+1],axis=1)\n                ichain  = np.where(stdev > 1e-8)[0]\n                if len(ichain) > 1:\n                    #Call test\n                    foo = allparams[inotfixed]\n                    psrf, meanpsrf = gr.convergetest(foo[:,ichain,ninit:m+1], len(ichain))\n                    #psrf, meanpsrf = gr.convergetest(allparams[inotfixed,:,:m+1], nchains)\n                    numconv = np.sum(np.bitwise_and(psrf < 1.01, psrf >= 1.00))\n                    print(\"Gelman-Rubin statistic for free parameters:\")\n                    print(psrf)\n                    if numconv == numnotfixed: #and j >= 1e4:\n                        print(\"All parameters have converged to within 1% of unity. Halting MCMC.\")\n                        allparams = allparams[:,:,:m+1]\n                        break\n        clock.check(m+1-ninit)\n\n    #Check for no accepted steps in each chain\n    stdev   = np.std(allparams[inotfixed[0]],axis=1)\n    ichain  = np.where(stdev > 1e-8)[0]\n    print(\"Number of good chains: \" + str(len(ichain)))\n    #FINDME\n    allparams = allparams[:,ichain,ninit:]\n    allparams = np.reshape(allparams,(nump, (m+1-ninit)*len(ichain)))\n    #allparams = allparams[:,ichain]\n    #allparams = np.reshape(allparams,(nump, (m+1)*len(ichain)))\n    return allparams, bestp, numaccept, (m+1-ninit)*len(ichain)\n", "meta": {"hexsha": "0330189515983ac5d7b75493a1a3b33135772c0a", "size": 49328, "ext": "py", "lang": "Python", "max_stars_repo_path": "eureka/lib/demc.py", "max_stars_repo_name": "iancrossfield/Eureka", "max_stars_repo_head_hexsha": "88b178d1b830c16915045b6387cf91955e0071e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2020-08-07T12:12:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T10:20:38.000Z", "max_issues_repo_path": "eureka/lib/demc.py", "max_issues_repo_name": "iancrossfield/Eureka", "max_issues_repo_head_hexsha": "88b178d1b830c16915045b6387cf91955e0071e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 159, "max_issues_repo_issues_event_min_datetime": "2020-08-05T14:34:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:02:10.000Z", "max_forks_repo_path": "eureka/lib/demc.py", "max_forks_repo_name": "iancrossfield/Eureka", "max_forks_repo_head_hexsha": "88b178d1b830c16915045b6387cf91955e0071e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2021-06-16T09:40:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T18:28:07.000Z", "avg_line_length": 49.2295409182, "max_line_length": 212, "alphanum_fraction": 0.5387812196, "include": true, "reason": "import numpy", "num_tokens": 13107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.2909808723634538, "lm_q1q2_score": 0.18953180673870784}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nPython wrapper around the C extension for the counts-in-cells\nfor positions on the sky. Corresponding C codes are in ``mocks/vpf_mocks/``\nwhile the python wrapper is in :py:mod:`Corrfunc.mocks.vpf_mocks`\n\"\"\"\n\nfrom __future__ import (division, print_function, absolute_import,\n                        unicode_literals)\n\n__author__ = ('Manodeep Sinha')\n__all__ = ('vpf_mocks', )\n\n\ndef vpf_mocks(rmax, nbins, nspheres, numpN,\n              threshold_ngb, centers_file, cosmology,\n              RA, DEC, CZ,\n              RAND_RA, RAND_DEC, RAND_CZ,\n              verbose=False, is_comoving_dist=False,\n              xbin_refine_factor=1, ybin_refine_factor=1,\n              zbin_refine_factor=1, max_cells_per_dim=100,\n              c_api_timer=False, isa=r'fastest'):\n    \"\"\"\n    Function to compute the counts-in-cells on points on the sky. Suitable\n    for mock catalogs and observed galaxies.\n\n    Returns a numpy structured array containing the probability of a\n    sphere of radius up to ``rmax`` containing ``0--numpN-1`` galaxies.\n\n    Parameters\n    ----------\n\n    rmax : double\n       Maximum radius of the sphere to place on the particles\n\n    nbins : integer\n       Number of bins in the counts-in-cells. Radius of first shell\n       is rmax/nbins\n\n    nspheres : integer (>= 0)\n       Number of random spheres to place within the particle distribution.\n       For a small number of spheres, the error is larger in the measured\n       pN's.\n\n    numpN : integer (>= 1)\n       Governs how many unique pN's are to returned. If ``numpN`` is set to 1,\n       then only the vpf (p0) is returned. For ``numpN=2``, p0 and p1 are\n       returned.\n\n       More explicitly, the columns in the results look like the following:\n\n         ======   ==========================\n         numpN    Columns in output\n         ======   ==========================\n            1      p0\n            2      p0      p1\n            3      p0      p1     p2\n            4      p0      p1     p2     p3\n         ======   ==========================\n\n       and so on...\n\n       Note: ``p0`` is the vpf\n\n    threshold_ngb : integer\n       Minimum number of random points needed in a ``rmax`` sphere such that it\n       is considered to be entirely within the mock footprint. The\n       command-line version, ``mocks/vpf/vpf_mocks.c``, assumes that the\n       minimum number of randoms can be at most a 1-sigma deviation from\n       the expected random number density.\n\n    centers_file : string, filename\n       A file containing random sphere centers. If the file does not exist,\n       then a list of random centers will be written out. In that case, the\n       randoms arrays, ``RAND_RA``, ``RAND_DEC`` and ``RAND_CZ`` are used to\n       check that the sphere is entirely within the footprint. If the file does\n       exist but either ``rmax`` is too small or there are not enough centers\n       then the file will be overwritten.\n\n       Note: If the centers file has to be written, the code will take\n       significantly longer to finish. However, subsequent runs can re-use\n       that centers file and will be faster.\n\n    cosmology : integer, required\n        Integer choice for setting cosmology. Valid values are 1->LasDamas\n        cosmology and 2->Planck cosmology. If you need arbitrary cosmology,\n        easiest way is to convert the ``CZ`` values into co-moving distance,\n        based on your preferred cosmology. Set ``is_comoving_dist=True``, to\n        indicate that the co-moving distance conversion has already been done.\n\n        Choices:\n                 1. LasDamas cosmology. :math:`\\\\Omega_m=0.25`, :math:`\\\\Omega_\\Lambda=0.75`\n                 2. Planck   cosmology. :math:`\\\\Omega_m=0.302`, :math:`\\\\Omega_\\Lambda=0.698`\n\n        To setup a new cosmology, add an entry to the function,\n        ``init_cosmology`` in ``ROOT/utils/cosmology_params.c`` and re-install\n        the entire package.\n\n    RA : array-like, real (float/double)\n       The array of Right Ascensions for the first set of points. RA's\n       are expected to be in [0.0, 360.0], but the code will try to fix cases\n       where the RA's are in [-180, 180.0]. For peace of mind, always supply\n       RA's in [0.0, 360.0].\n\n       Calculations are done in the precision of the supplied arrays.\n\n    DEC : array-like, real (float/double)\n       Array of Declinations for the first set of points. DEC's are expected\n       to be in the [-90.0, 90.0], but the code will try to fix cases where\n       the DEC's are in [0.0, 180.0]. Again, for peace of mind, always supply\n       DEC's in [-90.0, 90.0].\n\n       Must be of same precision type as RA.\n\n    CZ : array-like, real (float/double)\n       Array of (Speed Of Light * Redshift) values for the first set of\n       points. Code will try to detect cases where ``redshifts`` have been\n       passed and multiply the entire array with the ``speed of light``.\n\n       If ``is_comoving_dist`` is set, then ``CZ`` is interpreted as the\n       co-moving distance, rather than (Speed Of Light * Redshift).\n\n    RAND_RA : array-like, real (float/double)\n       The array of Right Ascensions for the randoms. RA's are expected to be\n       in [0.0, 360.0], but the code will try to fix cases where the RA's are\n       in [-180, 180.0]. For peace of mind, always supply RA's in\n       [0.0, 360.0].\n\n       Must be of same precision type as RA/DEC/CZ.\n\n    RAND_DEC : array-like, real (float/double)\n       Array of Declinations for the randoms. DEC's are expected to be in the\n       [-90.0, 90.0], but the code will try to fix cases where the DEC's are\n       in [0.0, 180.0]. Again, for peace of mind, always supply DEC's in\n       [-90.0, 90.0].\n\n       Must be of same precision type as RA/DEC/CZ.\n\n    RAND_CZ : array-like, real (float/double)\n       Array of (Speed Of Light * Redshift) values for the randoms. Code\n       will try to detect cases where ``redshifts`` have been\n       passed and multiply the entire array with the ``speed of light``.\n\n       If ``is_comoving_dist`` is set, then ``CZ2`` is interpreted as the\n       co-moving distance, rather than ``(Speed Of Light * Redshift)``.\n\n       Note: RAND_RA, RAND_DEC and RAND_CZ are only used when the\n          ``centers_file``  needs to be written out. In that case, the\n          RAND_RA, RAND_DEC, and RAND_CZ are used as random centers.\n\n    verbose : boolean (default false)\n       Boolean flag to control output of informational messages\n\n    is_comoving_dist : boolean (default false)\n       Boolean flag to indicate that ``cz`` values have already been\n       converted into co-moving distances. This flag allows arbitrary\n       cosmologies to be used in ``Corrfunc``.\n\n    (xyz)bin_refine_factor : integer, default is (1,1,1); typically within [1-3]\n       Controls the refinement on the cell sizes. Can have up to a 20% impact\n       on runtime. \n\n       Note: Since the counts in spheres calculation is symmetric\n       in all 3 dimensions, the defaults are different from the clustering\n       routines.\n\n    max_cells_per_dim : integer, default is 100, typical values in [50-300]\n       Controls the maximum number of cells per dimension. Total number of\n       cells can be up to (max_cells_per_dim)^3. Only increase if ``rmax`` is\n       too small relative to the boxsize (and increasing helps the runtime).\n\n    c_api_timer : boolean (default false)\n       Boolean flag to measure actual time spent in the C libraries. Here\n       to allow for benchmarking and scaling studies.\n\n    isa : string (default ``fastest``)\n       Controls the runtime dispatch for the instruction set to use. Possible\n       options are: [``fastest``, ``avx``, ``sse42``, ``fallback``]\n\n       Setting isa to ``fastest`` will pick the fastest available instruction\n       set on the current computer. However, if you set ``isa`` to, say,\n       ``avx`` and ``avx`` is not available on the computer, then the code will\n       revert to using ``fallback`` (even though ``sse42`` might be available).\n\n       Unless you are benchmarking the different instruction sets, you should\n       always leave ``isa`` to the default value. And if you *are*\n       benchmarking, then the string supplied here gets translated into an\n       ``enum`` for the instruction set defined in ``utils/defs.h``.\n\n\n    Returns\n    --------\n\n    results : Numpy structured array\n       A numpy structured array containing [rmax, pN[numpN]] with ``nbins``\n       elements. Each row contains the maximum radius of the sphere and the\n       ``numpN`` elements in the ``pN`` array. Each element of this array\n       contains the probability that a sphere of radius ``rmax`` contains\n       *exactly* ``N`` galaxies. For example, pN[0] (p0, the void probibility\n       function) is the probability that a sphere of radius ``rmax`` contains 0\n       galaxies.\n\n    api_time : float, optional\n       Only returned if ``c_api_timer`` is set.  ``api_time`` measures only the time\n       spent within the C library and ignores all python overhead.\n\n\n    Example\n    --------\n\n    >>> from __future__ import print_function\n    >>> import math\n    >>> from os.path import dirname, abspath, join as pjoin\n    >>> import numpy as np\n    >>> import Corrfunc\n    >>> from Corrfunc.mocks.vpf_mocks import vpf_mocks\n    >>> rmax = 10.0\n    >>> nbins = 10\n    >>> numbins_to_print = nbins\n    >>> nspheres = 10000\n    >>> numpN = 6\n    >>> threshold_ngb = 1  # does not matter since we have the centers\n    >>> cosmology = 1  # LasDamas cosmology\n    >>> centers_file = pjoin(dirname(abspath(Corrfunc.__file__)),\n    ...                      \"../mocks/tests/data/\",\n    ...                      \"Mr19_centers_xyz_forVPF_rmax_10Mpc.txt\")\n    >>> N = 1000000\n    >>> boxsize = 420.0\n    >>> seed = 42\n    >>> np.random.seed(seed)\n    >>> X = np.random.uniform(-0.5*boxsize, 0.5*boxsize, N)\n    >>> Y = np.random.uniform(-0.5*boxsize, 0.5*boxsize, N)\n    >>> Z = np.random.uniform(-0.5*boxsize, 0.5*boxsize, N)\n    >>> CZ = np.sqrt(X*X + Y*Y + Z*Z)\n    >>> inv_cz = 1.0/CZ\n    >>> X *= inv_cz\n    >>> Y *= inv_cz\n    >>> Z *= inv_cz\n    >>> DEC = 90.0 - np.arccos(Z)*180.0/math.pi\n    >>> RA = (np.arctan2(Y, X)*180.0/math.pi) + 180.0\n    >>> results = vpf_mocks(rmax, nbins, nspheres, numpN, threshold_ngb,\n    ...                     centers_file, cosmology,\n    ...                     RA, DEC, CZ,\n    ...                     RA, DEC, CZ,\n    ...                     is_comoving_dist=True)\n    >>> for r in results:\n    ...     print(\"{0:10.1f} \".format(r[0]), end=\"\")\n    ...     # doctest: +NORMALIZE_WHITESPACE\n    ...     for pn in r[1]:\n    ...         print(\"{0:10.3f} \".format(pn), end=\"\")\n    ...         # doctest: +NORMALIZE_WHITESPACE\n    ...     print(\"\") # doctest: +NORMALIZE_WHITESPACE\n       1.0      0.999      0.001      0.000      0.000      0.000      0.000\n       2.0      0.992      0.007      0.001      0.000      0.000      0.000\n       3.0      0.982      0.009      0.005      0.002      0.001      0.000\n       4.0      0.975      0.006      0.006      0.005      0.003      0.003\n       5.0      0.971      0.004      0.003      0.003      0.004      0.003\n       6.0      0.967      0.003      0.003      0.001      0.003      0.002\n       7.0      0.962      0.004      0.002      0.003      0.002      0.001\n       8.0      0.958      0.004      0.002      0.003      0.001      0.002\n       9.0      0.953      0.003      0.003      0.002      0.003      0.001\n      10.0      0.950      0.003      0.002      0.002      0.001      0.002\n\n    \"\"\"\n\n    try:\n        from Corrfunc._countpairs_mocks import countspheres_vpf_mocks\\\n            as vpf_extn\n    except ImportError:\n        msg = \"Could not import the C extension for the Counts-in-Cells \"\\\n              \" (vpf)\"\n        raise ImportError(msg)\n\n    import numpy as np\n    from warnings import warn\n    from future.utils import bytes_to_native_str\n    from Corrfunc.utils import translate_isa_string_to_enum,\\\n        return_file_with_rbins, convert_to_native_endian,\\\n        is_native_endian\n        \n    # Warn about non-native endian arrays\n    if not all(is_native_endian(arr) for arr in [RA, DEC, CZ, RAND_RA, RAND_DEC, RAND_CZ]):\n        warn('One or more input array has non-native endianness!  A copy will be made with the correct endianness.')\n    RA, DEC, CZ, RAND_RA, RAND_DEC, RAND_CZ = [convert_to_native_endian(arr) for arr in [RA, DEC, CZ, RAND_RA, RAND_DEC, RAND_CZ]]\n\n\n    integer_isa = translate_isa_string_to_enum(isa)\n    extn_results, api_time = vpf_extn(rmax, nbins, nspheres, numpN,\n                                      threshold_ngb, centers_file,\n                                      cosmology,\n                                      RA, DEC, CZ,\n                                      RAND_RA, RAND_DEC, RAND_CZ,\n                                      verbose=verbose,\n                                      is_comoving_dist=is_comoving_dist,\n                                      xbin_refine_factor=xbin_refine_factor,\n                                      ybin_refine_factor=ybin_refine_factor,\n                                      zbin_refine_factor=zbin_refine_factor,\n                                      max_cells_per_dim=max_cells_per_dim,\n                                      c_api_timer=c_api_timer,\n                                      isa=integer_isa)\n\n    if extn_results is None:\n        msg = \"RuntimeError occurred\"\n        raise RuntimeError(msg)\n\n    results_dtype = np.dtype([(bytes_to_native_str(b'rmax'), np.float),\n                              (bytes_to_native_str(b'pN'),\n                               (np.float, numpN))])\n    nbin = len(extn_results)\n    results = np.zeros(nbin, dtype=results_dtype)\n\n    for ii, r in enumerate(extn_results):\n        results['rmax'][ii] = r[0]\n        if numpN == 1:\n            results['pN'] = r[1]\n        else:\n            for j in range(numpN):\n                results['pN'][ii][j] = r[1 + j]\n\n    if not c_api_timer:\n        return results\n    else:\n        return results, api_time\n\n\nif __name__ == '__main__':\n    import doctest\n    doctest.testmod()\n", "meta": {"hexsha": "5872de4bb2e7795e9d2ad42ad5718d038724f711", "size": 14131, "ext": "py", "lang": "Python", "max_stars_repo_path": "Corrfunc/mocks/vpf_mocks.py", "max_stars_repo_name": "rainwoodman/Corrfunc", "max_stars_repo_head_hexsha": "0474ae79cffe55463bd82708f9235cf03266672e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Corrfunc/mocks/vpf_mocks.py", "max_issues_repo_name": "rainwoodman/Corrfunc", "max_issues_repo_head_hexsha": "0474ae79cffe55463bd82708f9235cf03266672e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Corrfunc/mocks/vpf_mocks.py", "max_forks_repo_name": "rainwoodman/Corrfunc", "max_forks_repo_head_hexsha": "0474ae79cffe55463bd82708f9235cf03266672e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-21T06:36:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-21T06:36:14.000Z", "avg_line_length": 42.6918429003, "max_line_length": 130, "alphanum_fraction": 0.5945085274, "include": true, "reason": "import numpy", "num_tokens": 3754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.18949865165309507}}
{"text": "from __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\nfrom future import standard_library\nstandard_library.install_aliases()\nfrom builtins import str\nfrom builtins import range\nfrom builtins import object\nfrom past.utils import old_div\nimport contextlib\nfrom datetime import date, timedelta\nimport glob\nimport numpy as np\nimport os\nimport shutil\nimport sys\nimport warnings\nimport urllib.request, urllib.error, urllib.parse\n\nfrom . import coord\nfrom .get_kpap import get_kpap\nfrom .get_apmsis import get_apmsis\nfrom hwm93py import gws5 as hwm93\nfrom hwm07py import hwmqt as hwm07\nfrom hwm14py import hwm14\nfrom igrf11py import igrf11syn as igrf11\nfrom igrf12py import igrf12syn as igrf12\nfrom iri12py import iri_sub as iri12\nfrom iri16py import iri_sub as iri16\nfrom iri16py import read_ig_rz, readapf107\nfrom msis00py import gtd7 as msis00\n\n# Pyglow version:\nVERSION = '1.4'\n\n# Global variable indicating if IRI 2016 has been initialized with the contents\n# of the ionosphere global index (ig_rz.dat) and Ap/F10.7 index (apf107.dat)\n# files. IRI 2016 initialization is required only once per session.\n__INIT_IRI16 = False\n\n# Directory of pyglow files:\nDIR_FILE = os.path.dirname(__file__)\n\n__version__ = VERSION\n\n\nclass Point(object):\n\n    def __init__(\n        self,\n        dn,\n        lat,\n        lon,\n        alt,\n        user_ind=False,\n    ):\n        \"\"\"\n        An instance of Point is the fundamental data object\n        for running each climatological model.\n\n        Instantation of a Point initializes member variables,\n        and also grabs the corresponding geophysical indices.\n\n        :param dn: datetime.datetime object\n        :param lat: Latitude [degrees]\n        :param lon: Longitude [degrees]\n        :param alt: Altitude [km]\n        :param user_ind: (optional) Boolean switch to calculate\n                         geophysical indices. If True, then it\n                         is up to the user to assign geophysical\n                         indices to the Point\n        \"\"\"\n\n        nan = float('nan')\n\n        # Record input:\n        self.dn = dn\n        self.lat = lat\n        self.lon = lon\n        self.alt = alt\n\n        # Error if date is too early\n        if self.dn.year < 1932:\n            raise ValueError('Date cannot be before 1932!')\n\n        # Time variables:\n        self.doy = self.dn.timetuple().tm_yday\n        self.utc_sec = self.dn.hour*3600. + self.dn.minute*60.\n        self.utc_hour = self.dn.hour\n        self.slt_hour = np.mod(self.utc_sec/3600. + self.lon/15., 24)\n        self.iyd = np.mod(self.dn.year, 100)*1000 + self.doy\n\n        # For kp, ap function\n        self.kp = nan\n        self.ap = nan\n        self.f107 = nan\n        self.f107a = nan\n        self.f107p = nan  # previous day's F10.7\n        self.kp_daily = nan\n        self.ap_daily = nan\n        self.apmsis = [nan, ] * 7\n        self.dst = nan\n        self.ae = nan\n\n        # For iri:\n        self.ne = nan\n        ions = ['O+', 'H+', 'HE+', 'O2+', 'NO+']\n        self.ni = {}\n        for ion in ions:\n            self.ni[ion] = nan\n\n        self.Ti = nan\n        self.Te = nan\n        self.Tn_iri = nan\n\n        self.NmF2 = nan\n        self.hmF2 = nan\n\n        # For msis:\n        self.Tn_msis = nan\n        self.nn = {}\n        for neutral in ['HE', 'O', 'N2', 'O2', 'AR', 'H', 'N', 'O_anomalous']:\n            self.nn[neutral] = nan\n        self.rho = nan\n\n        # For hwm 93/07:\n        self.u = nan\n        self.v = nan\n        self.hwm_version = nan\n\n        # For igrf:\n        self.Bx = nan\n        self.By = nan\n        self.Bz = nan\n        self.B = nan\n        self.dip = nan\n        self.dec = nan\n\n        # For run_airglow:\n        self.ag6300 = nan\n        self.ag7774 = nan\n\n        # Flag for user indices:\n        self.user_ind = user_ind\n\n        if not self.user_ind:\n            # Call the indice models:\n            self.get_indices()\n            self.apmsis = get_apmsis(self.dn)\n\n    def __str__(self):\n        \"\"\" String representation of pyglow class \"\"\"\n\n        pyglow_str = \"pyglow.Point: dn = {dn}, lat = {lat:3.2f} [deg], \"\\\n                     \"lon = {lon:3.2f} [deg], alt = {alt:3.2f} [km]\".format(\n                        dn=self.dn.strftime(\"%Y-%m-%d %H:%M:%S\"),\n                        lat=self.lat,\n                        lon=self.lon,\n                        alt=self.alt,\n                     )\n\n        return pyglow_str\n\n    def __repr__(self):\n        \"\"\" Representation value of pyglow class \"\"\"\n\n        pyglow_repr = \"pyglow.Point({dn}, {lat}, {lon}, {alt})\".format(\n                        dn=self.dn.__repr__(),\n                        lat=self.lat,\n                        lon=self.lon,\n                        alt=self.alt,\n                     )\n\n        return pyglow_repr\n\n    def get_indices(self):\n        \"\"\"\n        Retreives geophysical indices.\n        \"\"\"\n        self.kp, self.ap, self.f107, self.f107a, self.f107p, \\\n            self.kp_daily, self.ap_daily, self.dst, self.ae  \\\n            = get_kpap(self.dn)\n        return self\n\n    @staticmethod\n    def init_iri16():\n        \"\"\"\n        If required (depending on the global variable *__INIT_IRI16*),\n        initialize IRI 2016. Return `True` if the model was\n        initialized and `False` otherwise.\n        \"\"\"\n        if not globals()['__INIT_IRI16']:\n            read_ig_rz()\n            readapf107()\n            globals()['__INIT_IRI16'] = True\n            return True\n        else:\n            return False\n\n    def run_iri(\n        self,\n        NmF2=None,\n        hmF2=None,\n        version=2016,\n        compute_Ne=True,\n        compute_Te_Ti=True,\n        compute_Ni=True,\n        debug=False,\n    ):\n        \"\"\"\n        Run IRI model at point time/location and update the object state\n        accordingly. If *NmF2* (in [cm^{-3}}]) or *hmF2* (in [km]) are\n        specified, input them to the model (see documentation for\n        IRI_SUB)). Override the model with *version* --- valid options\n        are currently 2016 or 2012. Output debugging information if\n        *debug* is true. The toggles *compute_Ne*, *compute_Te_Ti*,\n        and *compute_Ni* control, respectively, whether electron\n        density, electron and ion temperatures, and ion density are\n        computed (restricting the model to only what is required can\n        reduce run time) or set to `NaN`.\n        \"\"\"\n\n        if version == 2016:\n            iri_data_stub = 'iri16_data/'\n            iri = iri16\n            init_iri = Point.init_iri16\n        elif version == 2012:\n            iri_data_stub = 'iri12_data/'\n            iri = iri12\n            init_iri = lambda: False\n        else:\n            raise ValueError(\n                \"Invalid version of {} for IRI.\\n\".format(version) +\n                \"Either 2016 (default) or 2012 is valid.\"\n            )\n\n        if debug:\n            print(\"Version = {}\".format(version))\n\n        jf = np.ones((50,))  # JF switches\n        # Standard IRI model flags\n        #             | FORTRAN Index\n        #             |\n        #             V\n        jf[3] = 0  # 4 B0,B1 other model-31\n        jf[4] = 0  # 5  foF2 - URSI\n        jf[5] = 0  # 6  Ni - RBV-10 & TTS-03\n        jf[20] = 0  # 21 ion drift not computed\n        jf[22] = 0  # 23 Te_topside (TBT-2011)\n        jf[27] = 0  # 28 spreadF prob not computed\n        jf[28] = 0  # 29 (29,30) => NeQuick\n        jf[29] = 0  # 30\n        # (Brian found a case that stalled IRI when on):\n        jf[32] = 0  # 33 Auroral boundary model off\n        jf[34] = 0  # 35 no foE storm update\n\n        # Not standard, but outputs same as values as standard so not an issue\n        jf[21] = 0  # 22 ion densities in m^-3 (not %)\n        jf[33] = 0  # 34 turn messages off\n\n        if not compute_Ne:\n            jf[0] = 0\n\n        if not compute_Te_Ti:\n            jf[1] = 0\n\n        if not compute_Ni:\n            jf[2] = 0\n\n        oarr = np.zeros((100,))\n\n        if NmF2 is not None:\n            # use specified F2 peak density\n            jf[7] = 0\n            oarr[0] = NmF2 * 100.**3  # IRI expects [m^{-3}]\n\n        if hmF2 is not None:\n            # use specified F2 peak height\n            jf[8] = 0\n            oarr[1] = hmF2\n\n        if self.user_ind:\n            # Set jf(25) switch to false (in Fortran)\n            #   which is jf[24] in Python\n            jf[24] = 0\n\n            # Set jf(32) switch to false (in Fortran)\n            #   which is jf[31] in Python\n            jf[31] = 0\n\n            # Store user indice for F10.7 in oarr:\n            oarr[40] = self.f107\n\n            # Store user index for F10.7 81 day average in oarr:\n            oarr[45] = self.f107a\n\n            # Reference:\n            # https://github.com/timduly4/pyglow/issues/34#issuecomment-340645358\n\n        # Get current directory:\n        my_pwd = os.getcwd()\n\n        # IRI data path.  We need to change directories\n        # into where the IRI data are located in order\n        # to run IRI:\n        iri_data_path = os.path.join(\n            DIR_FILE,\n            iri_data_stub,\n        )\n        if debug:\n            print(\"Changing directory to {}\".format(iri_data_path))\n\n        os.chdir(iri_data_path)\n        init_iri()\n        outf = iri(\n            jf,\n            0,\n            self.lat,\n            self.lon,\n            int(self.dn.year),\n            -self.doy,\n            (self.utc_sec/3600.+25.),\n            self.alt,\n            self.alt+1,\n            1,\n            oarr,\n        )\n        os.chdir(my_pwd)\n\n        if compute_Te_Ti:\n            self.Te = outf[3, 0]  # Electron temperature from IRI (K)\n            self.Ti = outf[2, 0]  # Ion temperature from IRI (K)\n        else:\n            self.Te = float('NaN')\n            self.Ti = float('NaN')\n\n        self.Tn_iri = outf[1, 0]  # Neutral temperature from IRI (K)\n\n        self.ne = outf[0, 0]  # Electron density (m^-3)\n        self.ni['O+'] = outf[4, 0]  # O+ Density (%, or m^-3 with JF(22) = 0)\n        self.ni['H+'] = outf[5, 0]  # H+ Density (%, or m^-3 with JF(22) = 0)\n        self.ni['HE+'] = outf[6, 0]  # HE+ Density (%, or m^-3 with JF(22) = 0)\n        self.ni['O2+'] = outf[7, 0]  # O2+ Density (%, or m^-3 with JF(22) = 0)\n        self.ni['NO+'] = outf[8, 0]  # NO+ Density (%, or m^-3 with JF(22) = 0)\n\n        self.NmF2 = oarr[0]\n        self.hmF2 = oarr[1]\n\n        if compute_Ne:\n            self.ne = outf[0, 0]  # Electron density (m^-3)\n        else:\n            self.ne = float('NaN')\n\n        # Densities are now in cm^-3:\n        self.ne = self.ne / 100.**3  # [items/cm^3]\n        self.ni['O+'] = self.ni['O+'] / 100.**3  # [items/cm^3]\n        self.ni['H+'] = self.ni['H+'] / 100.**3  # [items/cm^3]\n        self.ni['HE+'] = self.ni['HE+'] / 100.**3  # [items/cm^3]\n        self.ni['O2+'] = self.ni['O2+'] / 100.**3  # [items/cm^3]\n        self.ni['NO+'] = self.ni['NO+'] / 100.**3  # [items/cm^3]\n        self.NmF2 = self.NmF2 / 100.**3  # [items/cm^3]\n\n        return self\n\n    def run_msis(self, version=2000):\n        \"\"\"\n        Method to call MSIS model\n        \"\"\"\n\n        if version == 2000:\n            msis = msis00\n        else:\n            raise ValueError(\n                \"Invalid version of '{}' for MSIS.\\n\".format(version) +\n                \"2000 (default) is valid.\"\n            )\n\n        [d, t] = msis(\n            self.doy,\n            self.utc_sec,\n            self.alt,\n            self.lat,\n            np.mod(self.lon, 360),\n            self.slt_hour,\n            self.f107a,\n            self.f107p,\n            self.apmsis,\n            48,\n        )\n        self.Tn_msis = t[1]  # neutral temperature from MSIS (K)\n\n        self.nn = {}\n        self.nn['HE'] = d[0]  # [items/cm^3]\n        self.nn['O'] = d[1]  # [items/cm^3]\n        self.nn['N2'] = d[2]  # [items/cm^3]\n        self.nn['O2'] = d[3]  # [items/cm^3]\n        self.nn['AR'] = d[4]  # [items/cm^3]\n        # [5] is below\n        self.nn['H'] = d[6]  # [items/cm^3]\n        self.nn['N'] = d[7]  # [items/cm^3]\n        self.nn['O_anomalous'] = d[8]  # [items/cm^3]\n\n        self.rho = d[5]  # total mass density [grams/cm^3]\n\n        return self\n\n    def run_hwm(self, version=2014):\n        \"\"\"\n        Wrapper to call various HWM models\n        \"\"\"\n        if version == 2014:\n            self._run_hwm14()\n        elif version == 2007:\n            self._run_hwm07()\n        elif version == 1993:\n            self._run_hwm93()\n        else:\n            raise ValueError(\n                \"Invalid version of {} for HWM.\\n\".format(version) +\n                \"Either 2014 (default), 2007, or 1993 is valid.\"\n            )\n\n        return self\n\n    def _run_hwm93(self):\n        \"\"\"\n        HWM 1993 Climatological model.\n\n        \"\"\"\n\n        w = hwm93(\n            self.iyd,\n            self.utc_sec,\n            self.alt,\n            self.lat,\n            np.mod(self.lon, 360),\n            self.slt_hour,\n            self.f107a,\n            self.f107,\n            self.ap_daily,\n        )\n        self.v = w[0]\n        self.u = w[1]\n        self.hwm_version = '93'\n\n        return self\n\n    def _run_hwm07(self):\n        \"\"\"\n        HWM 2007 Climatological model.\n\n        \"\"\"\n\n        my_pwd = os.getcwd()\n\n        hwm07_data_path = os.path.join(DIR_FILE, \"hwm07_data/\")\n\n        os.chdir(hwm07_data_path)\n        aphwm07 = [float('NaN'), self.ap]\n        w = hwm07(\n            self.iyd,\n            self.utc_sec,\n            self.alt,\n            self.lat,\n            np.mod(self.lon, 360),\n            self.slt_hour,\n            self.f107a,\n            self.f107,\n            aphwm07,\n        )\n\n        # Change back to original directory:\n        os.chdir(my_pwd)\n        self.v = w[0]\n        self.u = w[1]\n        self.hwm_version = '07'\n\n        return self\n\n    def _run_hwm14(self):\n        \"\"\"\n        HWM 2014 Climatological model.\n\n        \"\"\"\n\n        my_pwd = os.getcwd()\n\n        hwm14_data_path = os.path.join(DIR_FILE, \"hwm14_data/\")\n\n        os.chdir(hwm14_data_path)\n\n        v, u = hwm14(\n            self.iyd,\n            self.utc_sec,\n            self.alt,\n            self.lat,\n            np.mod(self.lon, 360),\n            np.nan,\n            np.nan,\n            np.nan,\n            [np.nan, self.ap],\n        )\n\n        # Change back to original directory:\n        os.chdir(my_pwd)\n        self.v = v\n        self.u = u\n        self.hwm_version = '14'\n\n        return self\n\n    def run_igrf(self, version=12):\n        \"\"\"\n        Run the IGRF climatological model\n        \"\"\"\n\n        if version == 12:\n            igrf = igrf12\n        elif version == 11:\n            igrf = igrf11\n        else:\n            raise ValueError(\n                \"Invalid version of {} for IGRF.\\n\".format(version) +\n                \"Version 12 (default) and 11 are valid.\"\n            )\n\n        x, y, z, f = igrf(\n            0,\n            self.dn.year,\n            1,\n            self.alt,\n            90.-self.lat,\n            np.mod(self.lon, 360),\n        )\n\n        h = np.sqrt(x**2 + y**2)\n        dip = 180./np.pi * np.arctan2(z ,h)\n        dec = 180./np.pi * np.arctan2(y, x)\n\n        # Note that the changes here match\n        # coordinate convention with other models\n        # (i.e., HWM), that is:\n        # (x -> east, y -> north, z -> up)\n        #\n        # IGRF gives (x -> north, y -> east, z -> down)\n        warnings.warn(\n            \"Caution: IGRF coordinates have been recently changed to\\n\" +\n            \"Bx -> positive eastward\\n\" +\n            \"By -> positive northward\\n\" +\n            \" Bz -> positive upward\\n\"\n        )\n        self.Bx = y/1e9  # [T] (positive eastward) (note x/y switch here)\n        self.By = x/1e9  # [T] (positive northward) (note x/y switch here)\n        self.Bz = -z/1e9  # [T] (positive upward) (note negation here)\n        self.B = f/1e9  # [T]\n\n        self.dip = dip\n        self.dec = dec\n\n        return self\n\n    def run_airglow(self):\n        \"\"\"\n        Computes airglow intensities\n\n\n        After running, self.ag6300 has the 630.0-nm volume emission\n        rate (ph/cm^3/s) and self.ag7774 has the 777.4-nm volume\n        emission rate.\n\n\n        History\n        ------\n        9/9/13 -- implemented into pyglow\n                  based on Jonathan J. Makela's MATLAB\n                  and subsequent python code\n        9/13/16 -- added 7774 calculation\n        \"\"\"\n\n        # Let's see if IRI and MSIS have been executed.\n        # If not, run the appropriate models:\n        if np.isnan(self.ne):\n            self.run_iri()\n        if np.isnan(self.nn['O2']):\n            self.run_msis()\n\n        # Perform 630.0-nm calculation\n        Ne = self.ne        # electron density [cm^-3]\n        Tn = self.Tn_msis   # neutral temperature [K]\n        Ti = self.Ti        # ion temperature [K]\n        Te = self.Te        # electron temperature [K]\n        O2 = self.nn['O2']  # O2 density [cm^-3]\n        N2 = self.nn['N2']  # N2 density [cm^-3]\n        O = self.nn['O']   # O density [cm^-3]\n\n        te = Te/300.\n        ti = Ti/300.\n\n        # These coefs are from Link and Cogger, JGR 93(A9), 988309892, 1988\n        K1_6300 = 3.23e-12*np.exp(3.72/ti - 1.87/ti**2)\n        K2_6300 = 2.78e-13*np.exp(2.07/ti - 0.61/ti**2)\n        K3_6300 = 2.0e-11*np.exp(111.8/Tn)\n        K4_6300 = 2.9e-11*np.exp(67.5/Tn)\n        K5_6300 = 1.6e-12*Te**0.91\n        b6300 = 1.1\n        a1D = 7.45e-3  # Corr. value from Link and Cogger, JGR, 94(A2), 1989\n        a6300 = 5.63e-3  # Corr. value form Link and Cogger, JGR, 94(A2), 1989\n\n        # Calculate O+ assuming mixture of ions\n        # (also from Link and Cogger, 1988):\n        a1 = 1.95e-7*te**-0.7\n        a2 = 4.00e-7*te**-0.9\n        Oplus = Ne/(1.+K2_6300*N2/a2/Ne + K1_6300*O2/a1/Ne)\n\n        AGNumerator = a6300/a1D*b6300*K1_6300*Oplus*O2\n        AGDenominator = 1.+(K3_6300*N2+K4_6300*O2+K5_6300*Ne)/a1D\n        self.ag6300 = AGNumerator / AGDenominator\n\n        # Perform the 777.4-nm calculation\n\n        # These coefs are from a number of sources (see Makela's\n        # dissertation Table 2.3 or Makela et al., \"Ionospheric\n        # topography maps using multiple-wavelength all-sky images\",\n        # JGR, 106, 29161--29174, 2001.)\n        alpha1_7774 = 7.8e-13\n        beta_7774 = 0.42\n        K1_7774 = 1.3e-15\n        K2_7774 = 1.5e-7\n        K3_7774 = 1.4e-10\n\n        # Makela shows that Oplus may be replaced by Ne below in his\n        # dissertation (see p. 25) with only a 0.5% impact. Since we\n        # have Oplus at hand, we use it in the calculation.\n        V7774_rr = alpha1_7774 * Oplus * Ne\n\n        V7774_ii_num = beta_7774 * K1_7774 * K2_7774 * O * Oplus * Ne\n        V7774_ii_den = K2_7774 * Oplus + K3_7774 * O\n\n        self.ag7774 = V7774_rr + V7774_ii_num / float(V7774_ii_den)\n\n        return self\n\n\ndef _igrf_tracefield(dn, lat, lon, alt, target_ht, step):\n    \"\"\"\n    Helper function to trace along a magnetic field line using IGRF\n\n    :param dn: datetime.datetime object of requested trace\n    :param lat: Latitude [degrees]\n    :param lon: Longitude [degrees]\n    :param alt: Altitude [km]\n    :param target_ht: Altitude to stop trace [km]\n    :param step: Step size of trace [km]\n\n    :return lla: (latitude, longitude, altitude) data structure of trace\n                 with dimentions [Nsteps x 3]\n\n    \"\"\"\n\n    # Go North:\n    lla_north = _igrf_tracefield_hemis(\n        dn,\n        lat,\n        lon,\n        alt,\n        target_ht,\n        step,\n    )\n\n    # Go South:\n    lla_south = _igrf_tracefield_hemis(\n        dn,\n        lat,\n        lon,\n        alt,\n        target_ht,\n        -step,\n    )\n\n    # Stack them together:\n    lla = np.vstack(\n        [\n            np.flipud(lla_north)[:-1, :],\n            lla_south,\n        ]\n    )\n\n    return lla\n\n\ndef _igrf_tracefield_hemis(dn, lat, lon, alt, target_ht, step):\n    \"\"\"\n    Helper function to trace along a magnetic field line using IGRF\n    for only one hemisphere\n\n    :param dn: datetime.datetime object of requested trace\n    :param lat: Latitude [degrees]\n    :param lon: Longitude [degrees]\n    :param alt: Altitude [km]\n    :param target_ht: Altitude to stop trace [km]\n    :param step: Step size of trace [km]\n\n    :return lla: (latitude, longitude, altitude) data structure of trace\n                 with dimentions [Nsteps x 3]\n\n    \"\"\"\n\n    lat = float(lat)\n    lon = float(lon)\n    alt = float(alt)\n    target_ht = float(target_ht)\n    step = float(step)\n\n    target_ht = target_ht*1e3\n    step = step*1e3\n\n    lla = np.array([lat, lon, alt*1e3])\n\n    lla_field = lla\n\n    \"\"\" Step 1: trace the field along a given direction \"\"\"\n    TOLERANCE = 10  # [m]\n    i = 0\n    while (lla[2] > target_ht):\n        # convert to ECEF:\n        ecef = coord.lla2ecef(lla)\n\n        # Grab field line information:\n        p = Point(dn, lla[0], lla[1], lla[2]/1e3)\n        p.run_igrf()\n\n        # coordinates follow pyglow's convention:\n        # (x -> east, y -> north, z -> up)\n\n        N = p.By  # North\n        E = p.Bx  # East\n        D = -p.Bz  # Down\n        A = p.B   # Total\n\n        # Step along the field line\n        ecef_new = ecef + coord.ven2ecef(\n            lla,\n            [-D/A*step, E/A*step, N/A*step],\n        )\n\n        # Convert to lla coordinates:\n        lla = coord.ecef2lla(ecef_new)\n\n        # add the field line to our collection:\n        lla_field = np.vstack([lla_field, lla])\n        i = i + 1\n\n    \"\"\" Step 2: Make the last point close to target_ht \"\"\"\n    while (abs(lla[2]-target_ht) > TOLERANCE):\n\n        # Find out how much we need to step by:\n        step = -np.sign(step)*abs(lla[2]-target_ht)\n\n        ecef = coord.lla2ecef(lla)\n\n        p = Point(dn, lla[0], lla[1], lla[2]/1e3)\n        p.run_igrf()\n\n        N = p.Bx  # North\n        E = p.By  # East\n        D = p.Bz  # Down\n        A = p.B   # Total\n\n        # Trace the field, but use the modified step:\n        ecef_new = ecef + coord.ven2ecef(\n            lla,\n            np.array([-D/A, E/A, N/A]) * step/(-D/A),\n        )\n\n        # TODO : I changed this, is this correct?\n        lla = coord.ecef2lla(ecef_new)\n\n    # replace last entry with the point close to target_ht:\n    lla_field[-1, :] = lla\n\n    return lla_field\n\n\ndef Line(dn, lat, lon, alt, target_ht=90., step=15.):\n    \"\"\"\n    Return a list of instances of Point by\n    tracing along the geomagnetic field line.\n\n    pts = Line(dn, lat, lon, alt, target_ht=90., step=15.)\n\n    :param dn: datetime.datetime object of requested trace\n    :param lat: Latitude [degrees]\n    :param lon: Longitude [degrees]\n    :param alt: Altitude [km]\n    :param target_ht: (optional) Altitude to stop trace [km]\n    :param step: (optional) Step size of trace [km]\n\n    \"\"\"\n    llas = _igrf_tracefield(dn, lat, lon, alt, target_ht, step)\n    pts = []\n\n    for lla in llas:\n        pts.append(\n            Point(dn, lla[0], lla[1], lla[2]/1e3)\n        )\n\n    return pts\n\n\ndef update_kpap(years=None):\n    '''\n    Update the Kp and Ap indices used in pyglow.\n    The files will be downloaded from noaa to your pyglow\n    installation directory.\n\n    update_kpap(years=None)\n\n    :param years: (optional) a list of years to download.\n            If this input is not provided, the full\n            range of years starting from 1932 to the\n            current year will be downloaded.\n    '''\n\n    # Load all data up until today\n    if years is None:\n        years = range(1932, date.today().year + 1)[::-1]  # reverse\n\n    pyglow_dir = os.path.join(DIR_FILE, \"kpap/\")\n\n    for year in years:\n        src = 'ftp://ftp.ngdc.noaa.gov/'\\\n                + 'STP/GEOMAGNETIC_DATA/INDICES/KP_AP/%4i'\\\n                % (year,)\n        des = pyglow_dir + \"%4i\" % (year,)\n        print(\"\\nDownloading\\n{src}\\nto\\n{des}\".format(src=src, des=des))\n        try:\n            with contextlib.closing(urllib.request.urlopen(src)) as r:\n                with open(des, 'wb') as f:\n                    shutil.copyfileobj(r, f)\n        except IOError as e:\n            print(\n                \"Failed downloading data for year {}.\"\n                \"File does not exist ({})\".format(\n                    year,\n                    str(e),\n                ),\n            )\n\n\ndef update_dst(years=None):\n    \"\"\"\n    Update the Dst index files used in pyglow.\n    The files will be downloaded from WDC Kyoto\n    to your pyglow installation directory.\n\n    update_dst(years=None)\n\n    :param years: (optional) a list of years to download.\n            If this input is not provided, the full\n            range of years starting from 2005 to the\n            current year will be downloaded. Pre-2005\n            files are shipped with pyglow.\n    \"\"\"\n\n    def download_dst(year, month, des):\n        \"\"\"\n        Helper function to earch for the appropriate location\n        and download the DST index file from WDC Kyoto for the\n        given month and year. Save it to the specified file \"des\".\n        Return True if successful, False if not.\n        \"\"\"\n        # There are three possible sources of data. Search for\n        # them in the following order:\n        # 1) Final\n        # 2) Provisional\n        # 3) Realtime\n        year_month = '%i%02i' % (year, month)\n        wgdc_fn = 'dst%s%02i.for.request' % (str(year)[2:], month)\n        src_final = 'http://wdc.kugi.kyoto-u.ac.jp/dst_final/%s/%s' % \\\n            (year_month, wgdc_fn)\n        src_provisional = \\\n            'http://wdc.kugi.kyoto-u.ac.jp/dst_provisional/%s/%s' % \\\n            (year_month, wgdc_fn)\n        src_realtime = 'http://wdc.kugi.kyoto-u.ac.jp/dst_realtime/%s/%s' % \\\n            (year_month, wgdc_fn)\n\n        success = False\n        for src in [src_final, src_provisional, src_realtime]:\n            try:\n                with contextlib.closing(urllib.request.urlopen(src)) as r:\n                    contents = r.read().decode('utf8')\n                    # If that succeeded, then the file exists\n                    print(\n                        \"\\nDownloading\\n{src}\\nto\\n{des}\".format(\n                            src=src,\n                            des=des\n                        )\n                    )\n                    with open(des, 'w') as f:\n                        f.write(contents)\n                    success = True\n                    break\n            except urllib.error.HTTPError:\n                pass\n        return success\n\n    # Read files from 2005 until today. Pre-2005\n    # files are shipped with pyglow.\n    if years is None:\n        years = list(range(2005, date.today().year + 1))[::-1]  # reversed\n    pyglow_dir = os.path.join(DIR_FILE, \"dst/\")\n\n    for year in years:\n        for month in range(1, 13):\n            des = '%s%i%02i' % (pyglow_dir, year, month)\n            download_dst(year, month, des)\n\n    return\n\n\ndef update_ae(years=None):\n    '''\n    Update the AE index files used in pyglow.\n    The files will be downloaded from WDC Kyoto\n    to your pyglow installation directory.\n\n    update_ae(years=None)\n\n    :param years: (optional) a list of years to download.\n            If this input is not provided, the full\n            range of years starting from 2005 to the\n            current year will be downloaded. Pre-2005\n            files are shipped with pyglow.\n    '''\n\n    def download_ae(year, month, des):\n        '''\n        Helper function to earch for the appropriate location\n        and download the AE index file from WDC Kyoto for the\n        given month and year. Save it to the specified file \"des\".\n        Return True if successful, False if not.\n        '''\n        # There are three possible sources of data. Search for\n        # them in the following order:\n        # 1) Final\n        # 2) Provisional\n        # 3) Realtime\n        year_month = '%i%02i' % (year, month)\n        wgdc_fn = 'ae%s%02i.for.request' % (str(year)[2:], month)\n        src_provisional = \\\n            'http://wdc.kugi.kyoto-u.ac.jp/ae_provisional/%s/%s' % \\\n            (year_month, wgdc_fn)\n        src_realtime = 'http://wdc.kugi.kyoto-u.ac.jp/ae_realtime/%s/%s' % \\\n            (year_month, wgdc_fn)\n\n        success = False\n        for src in [src_provisional, src_realtime]:\n            try:\n                with contextlib.closing(urllib.request.urlopen(src)) as r:\n                    contents = r.readlines()\n                    # If that succeeded, then the file exists\n                    print(\n                        \"\\nDownloading\\n{src}\\nto\\n{des}\".format(\n                            src=src,\n                            des=des,\n                        )\n                    )\n                    with open(des, 'w') as f:\n                        # this shrinks the filesize to hourly\n                        for c in contents:\n                            c = c.decode('utf8')\n                            f.write(\n                                \"%s%s%s\\n\" % (c[12:18], c[19:21], c[394:400])\n                            )\n                    success = True\n                    break\n            except urllib.error.HTTPError:\n                pass\n        return success\n\n    # Read files from 2000 until today. Pre-2000\n    # files are shipped with pyglow.\n    if years is None:\n        years = list(range(2000, date.today().year + 1))[::-1]  # reversed\n    pyglow_dir = os.path.join(DIR_FILE, \"ae/\")\n\n    for year in years:\n        for month in range(1, 13):\n            des = '%s%i%02i' % (pyglow_dir, year, month)\n            download_ae(year, month, des)\n\n\ndef update_indices(years=None):\n    '''\n    Update all geophysical indices (e.g., KP, DST, AE).\n\n    update_indices(years=None)\n\n    :param years: (optional) a list of years to download.\n            If this input is not provided, default\n            values will be used.\n    '''\n\n    update_kpap(years=years)\n    update_dst(years=years)\n    update_ae(years=years)\n\n    return\n", "meta": {"hexsha": "30f90defea366450f18f134a6c378f7ef8fb6a36", "size": 29705, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/pyglow/pyglow.py", "max_stars_repo_name": "JinYunfei/pyglow", "max_stars_repo_head_hexsha": "9829acc82d69ce5d9049b3c85286b4e51201d6c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-23T15:41:07.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-23T15:41:07.000Z", "max_issues_repo_path": "src/pyglow/pyglow.py", "max_issues_repo_name": "JinYunfei/pyglow", "max_issues_repo_head_hexsha": "9829acc82d69ce5d9049b3c85286b4e51201d6c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pyglow/pyglow.py", "max_forks_repo_name": "JinYunfei/pyglow", "max_forks_repo_head_hexsha": "9829acc82d69ce5d9049b3c85286b4e51201d6c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4108910891, "max_line_length": 81, "alphanum_fraction": 0.5218650059, "include": true, "reason": "import numpy", "num_tokens": 8484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.18949864631413527}}
{"text": "import re\nimport os\nimport sys\nimport RNA\nimport gzip\nimport pickle\nimport random\nimport subprocess\nimport numpy as np\nimport scipy.sparse as sp\nfrom functools import partial\nimport forgi.graph.bulge_graph as fgb\n\nbasedir = os.path.split(os.path.dirname(os.path.abspath(__file__)))[0]\nsys.path.append(basedir)\nsys.path.append(os.path.dirname(os.path.abspath(__file__)))\n\nfrom lib.general_utils import Pool\n\n\ndef adj_to_bias(adj, nhood=1):\n    # [batch_size, nb_nodes, nb_nodes]\n    mt = np.stack([np.eye(adj.shape[1])] * adj.shape[0], axis=0)  # self-connection\n    for _ in range(nhood):\n        mt = np.matmul(mt, (adj + np.stack([np.eye(adj.shape[1])] * adj.shape[0], axis=0)))\n    mt = np.greater(mt, 0.).astype(np.float32)\n    return -1e9 * (1.0 - mt)\n\n\n# >>>> equilibrium probability using RNAplfold >>>>>>>\n\ndef fold_seq_rnashapes(seq, winsize, iterations=100):\n    stride = winsize // 4\n    cmd = 'echo %s | RNAshapes -w %d -W %d -i %d -A -t 1 -c %d -M 0 -o 1' % (seq, winsize, stride, iterations, 10)\n    ret = subprocess.check_output(cmd, shell=True)\n    lines = re.sub(' +', ' ', ret.decode('utf-8')).rstrip().split('\\n')\n\n    # assemble adjacency matrix\n    row_col, link, prob, norm = [], [], [], []\n    length = len(seq)\n    for i in range(length):\n        if i != length - 1:\n            row_col.append((i, i + 1))\n            link.append(1)\n            prob.append(1.)\n            norm.append(1)\n        if i != 0:\n            row_col.append((i, i - 1))\n            link.append(2)\n            prob.append(1.)\n            norm.append(1)\n    for line in lines:\n        if len(line) > 0:\n            if line[0] >= '0' and line[0] <= '9':\n                # indices\n                start_idx = int(line.split(' ')[0]) - 1\n                local_idx = []\n            elif line[0] in ['(', '.', ')']:\n                # secondary structures\n                tokens = line.split(' ')\n                struct = tokens[0]\n                probability = float(tokens[2])\n\n                bg = fgb.BulgeGraph.from_dotbracket(struct)\n                for i, ele in enumerate(struct):\n                    if ele == '(':\n                        pair_from = i + start_idx\n                        pair_to = bg.pairing_partner(i + 1) - 1 + start_idx\n                        if not (pair_from, pair_to) in row_col:\n                            row_col.append((pair_from, pair_to))\n                            link.append(3)\n                            prob.append(probability)\n                            norm.append(1)\n                            local_idx.append((pair_from, pair_to))\n                            # symmetric\n                            row_col.append((pair_to, pair_from))\n                            link.append(4)\n                            prob.append(probability)\n                            norm.append(1)\n                        else:\n                            idx = row_col.index((pair_from, pair_to))\n                            prob[idx] += probability\n                            prob[idx + 1] += probability\n                            if not (pair_from, pair_to) in local_idx:\n                                local_idx.append((pair_from, pair_to))\n                                norm[idx] += 1\n                                norm[idx + 1] += 1\n\n    prob = np.array(prob) / np.array(norm)\n    print(norm)\n    return (sp.csr_matrix((link, (np.array(row_col)[:, 0], np.array(row_col)[:, 1])), shape=(length, length)),\n            sp.csr_matrix((prob, (np.array(row_col)[:, 0], np.array(row_col)[:, 1])), shape=(length, length)),)\n\n\n# >>>> equilibrium probability using RNAplfold >>>>>>>\n# when on compute canada, make sure this is happening on the compute nodes\n\ndef fold_seq_rnaplfold(seq, w, l, cutoff, no_lonely_bps):\n    np.random.seed(random.seed())\n    name = str(np.random.rand())\n    # Call RNAplfold on command line.\n    no_lonely_bps_str = \"\"\n    if no_lonely_bps:\n        no_lonely_bps_str = \"--noLP\"\n    cmd = 'echo %s | RNAplfold -W %d -L %d -c %.4f --id-prefix %s %s' % (seq, w, l, cutoff, name, no_lonely_bps_str)\n    ret = subprocess.call(cmd, shell=True)\n\n    # assemble adjacency matrix\n    row_col, link, prob = [], [], []\n    length = len(seq)\n    for i in range(length):\n        if i != length - 1:\n            row_col.append((i, i + 1))\n            link.append(1)\n            prob.append(1.)\n        if i != 0:\n            row_col.append((i, i - 1))\n            link.append(2)\n            prob.append(1.)\n    # Extract base pair information.\n    name += '_0001_dp.ps'\n    start_flag = False\n    with open(name) as f:\n        for line in f:\n            if start_flag:\n                values = line.split()\n                if len(values) == 4:\n                    source_id = int(values[0]) - 1\n                    dest_id = int(values[1]) - 1\n                    avg_prob = float(values[2])\n                    # source_id < dest_id\n                    row_col.append((source_id, dest_id))\n                    link.append(3)\n                    prob.append(avg_prob ** 2)\n                    row_col.append((dest_id, source_id))\n                    link.append(4)\n                    prob.append(avg_prob ** 2)\n            if 'start of base pair probability data' in line:\n                start_flag = True\n    # delete RNAplfold output file.\n    os.remove(name)\n    # placeholder for dot-bracket structure\n    return (sp.csr_matrix((link, (np.array(row_col)[:, 0], np.array(row_col)[:, 1])), shape=(length, length)),\n            sp.csr_matrix((prob, (np.array(row_col)[:, 0], np.array(row_col)[:, 1])), shape=(length, length)),)\n\n\n# >>>> Boltzmann sampling using RNAsubopt >>>>>>>\n\ndef sample_one_seq(seq, passes=10):\n    max_len = len(seq)\n    adj_mat_tmp = np.zeros((max_len, max_len), dtype=np.int32)\n    for i in range(max_len):\n        if i != max_len - 1:\n            adj_mat_tmp[i, i + 1] = 1\n        if i != 0:\n            adj_mat_tmp[i, i - 1] = 2\n    cmd = 'echo \"%s\" | RNAsubopt --stochBT=%d' % (seq, passes)\n    all_struct = subprocess.check_output(cmd, shell=True). \\\n                     decode('utf-8').rstrip().split('\\n')[1:]\n    all_adj_mat = []\n    for struct in all_struct:\n        adj_mat = adj_mat_tmp.copy()\n        bg = fgb.BulgeGraph.from_dotbracket(struct)\n        for i, ele in enumerate(struct):\n            if ele == '(':\n                adj_mat[i, bg.pairing_partner(i + 1) - 1] = 3\n            elif ele == ')':\n                adj_mat[i, bg.pairing_partner(i + 1) - 1] = 4\n        all_adj_mat.append(adj_mat)\n    all_adj_mat = np.stack(all_adj_mat, axis=0)\n    return all_adj_mat\n\n\ndef fold_seq_subopt(seq, probabilistic=False, sampling_amount=1000):\n    # RNAfold is only suitable for short RNA sequences within 100 nucleotides\n    if probabilistic:\n        # sampling from a boltzmann ensemble\n        cmd = 'echo \"%s\" | RNAsubopt --stochBT=%d' % (seq, sampling_amount)\n        struct_list = subprocess.check_output(cmd, shell=True). \\\n                          decode('utf-8').rstrip().split('\\n')[1:]\n    else:\n        struct_list, energy_list = [], []\n\n        def collect_subopt_result(structure, energy, *args):\n            if not structure == None:\n                struct_list.append(structure)\n                energy_list.append(energy)\n\n        # Enumerate all structures 100 dacal/mol = 1 kcal/mol around\n        # default deltaEnergy is the MFE\n        RNA.fold_compound(seq).subopt_cb(100, collect_subopt_result, None)\n\n        # sort\n        struct_list = list(np.array(struct_list)[np.argsort(energy_list)])\n\n    # merging all structures into a single adjacency matrix\n    # probability returning two matrices\n    matrix = adj_mat_subopt(struct_list, probabilistic)\n    # process the structures\n    return structural_content(struct_list), matrix\n\n\ndef structural_content(struct_list):\n    size = len(struct_list)\n    length = len(struct_list[0])\n    content = np.zeros((length, 3), dtype=np.int32)\n    for i in range(length):\n        for j in range(size):\n            idx = '.()'.index(struct_list[j][i])\n            content[i][idx] += 1\n    return content.astype(np.float32) / size\n\n\ndef adj_mat_subopt(struct_list, probabilistic):\n    # create sparse matrix\n    row_col, data = [], []\n    length = len(struct_list[0])\n    counts = []\n    for i in range(length):\n        if i != length - 1:\n            row_col.append((i, i + 1))\n            data.append(1)\n            counts.append(0)\n        if i != 0:\n            row_col.append((i, i - 1))\n            data.append(2)\n            counts.append(0)\n    if probabilistic:\n        for struct in struct_list:\n            bg = fgb.BulgeGraph.from_dotbracket(struct)\n            for i, ele in enumerate(struct):\n                if ele == '(':\n                    if not (i, bg.pairing_partner(i + 1) - 1) in row_col:\n                        row_col.append((i, bg.pairing_partner(i + 1) - 1))\n                        data.append(3)\n                        counts.append(1)\n                    else:\n                        idx = row_col.index((i, bg.pairing_partner(i + 1) - 1))\n                        counts[idx] += 1\n                elif ele == ')':\n                    if not (i, bg.pairing_partner(i + 1) - 1) in row_col:\n                        row_col.append((i, bg.pairing_partner(i + 1) - 1))\n                        data.append(4)\n                        counts.append(1)\n                    else:\n                        idx = row_col.index((i, bg.pairing_partner(i + 1) - 1))\n                        counts[idx] += 1\n        # normalize each row into probabilities\n        for i in range(len(row_col)):\n            if counts[i] > 0:\n                # have to be a hydrogen bond\n                counts[i] /= len(struct_list)\n            else:\n                # covalent bond that forms the stem\n                counts[i] = 1.\n        return (sp.csr_matrix((data, (np.array(row_col)[:, 0], np.array(row_col)[:, 1])), shape=(length, length)),\n                sp.csr_matrix((counts, (np.array(row_col)[:, 0], np.array(row_col)[:, 1])), shape=(length, length)),)\n    else:\n        for struct in struct_list:\n            bg = fgb.BulgeGraph.from_dotbracket(struct)\n            for i, ele in enumerate(struct):\n                if ele == '(':\n                    if not (i, bg.pairing_partner(i + 1) - 1) in row_col:\n                        row_col.append((i, bg.pairing_partner(i + 1) - 1))\n                        data.append(3)\n                elif ele == ')':\n                    if not (i, bg.pairing_partner(i + 1) - 1) in row_col:\n                        row_col.append((i, bg.pairing_partner(i + 1) - 1))\n                        data.append(4)\n        return sp.csr_matrix((data, (np.array(row_col)[:, 0], np.array(row_col)[:, 1])),\n                             shape=(length, length))\n\n\n# >>>> MFE structure using RNAfold >>>>>>>\n\ndef fold_seq_rnafold(seq):\n    '''fold sequence using RNAfold'''\n    struct = RNA.fold(seq)[0]\n    matrix = adj_mat(struct)\n    return structural_content([struct]), matrix\n\n\ndef adj_mat(struct):\n    # create sparse matrix\n    row_col, data = [], []\n    length = len(struct)\n    for i in range(length):\n        if i != length - 1:\n            row_col.append((i, i + 1))\n            data.append(1)\n        if i != 0:\n            row_col.append((i, i - 1))\n            data.append(2)\n    bg = fgb.BulgeGraph.from_dotbracket(struct)\n    for i, ele in enumerate(struct):\n        if ele == '(':\n            row_col.append((i, bg.pairing_partner(i + 1) - 1))\n            data.append(3)\n        elif ele == ')':\n            row_col.append((i, bg.pairing_partner(i + 1) - 1))\n            data.append(4)\n    return sp.csr_matrix((data, (np.array(row_col)[:, 0], np.array(row_col)[:, 1])),\n                         shape=(length, length))\n\n\ndef augment_features(path):\n    '''\n    try to avoid this as much as possible.\n    we are mostly interested in an end-to-end learning scenario\n    '''\n    # region type: 101 x 5\n    region_types = np.loadtxt(gzip.open(os.path.join(path, \"matrix_RegionType.tab.gz\")), skiprows=1)\n    assert (region_types.shape[1] == 505)  # 4 region types\n    region_types = np.transpose(region_types.reshape((region_types.shape[0], 5, 101)), [0, 2, 1])\n\n    coclip = np.loadtxt(gzip.open(os.path.join(path, \"matrix_Cobinding.tab.gz\")), skiprows=1)\n    assert (coclip.shape[1] % 101 == 0)\n    nb_exprs = coclip.shape[1] // 101\n    coclip = np.transpose(coclip.reshape((coclip.shape[0], nb_exprs, 101)), [0, 2, 1])\n\n    return np.concatenate([region_types, coclip], axis=-1)\n\n\ndef load_fasta_format(file):\n    all_id = []\n    all_seq = []\n    seq = ''\n    for row in file:\n        if type(row) is bytes:\n            row = row.decode('utf-8')\n        row = row.rstrip()\n        if row.startswith('>'):\n            all_id.append(row)\n            if seq != '':\n                all_seq.append(seq)\n                seq = ''\n        else:\n            seq += row\n    all_seq.append(seq)\n    return all_id, all_seq\n\n\ndef load_dotbracket(filepath, pool=None, fold_algo='rnafold', probabilistic=False, **kwargs):\n    prefix = '%s_%s_' % (fold_algo, probabilistic)\n    if fold_algo == 'rnaplfold' or fold_algo == 'rnashapes':\n        prefix += '%d_' % (kwargs.get('w', 150))\n    full_path = os.path.join(os.path.dirname(filepath), '{}structures.npy'.format(prefix))\n    if not os.path.exists(full_path):\n        print(full_path, 'is missing. Begin folding from scratch.')\n        fold_rna_from_file(filepath, pool, fold_algo, probabilistic, **kwargs)\n    # load secondary structures\n    all_struct = np.load(\n        os.path.join(os.path.dirname(filepath), '{}structures.npy'.format(prefix)))\n    return all_struct\n\n\ndef load_mat(filepath, pool=None, fold_algo='rnafold', probabilistic=False, **kwargs):\n    prefix = '%s_%s_' % (fold_algo, probabilistic)\n    # folding length is crucial hyperparam for local RNA folding, therefore should be marked\n    if fold_algo == 'rnaplfold' or fold_algo == 'rnashapes':\n        prefix += '%d_' % (kwargs.get('w', 150))\n    if kwargs.get('modify_leaks', False):\n        # this will make sure we load the modified sequences\n        # incorrect secondary structure may still give away information / data statistics\n        prefix = 'modified_' + prefix\n\n    if not os.path.exists(\n            os.path.join(os.path.dirname(filepath), '{}rel_mat.obj'.format(prefix))) or probabilistic and \\\n            not os.path.exists(os.path.join(os.path.dirname(filepath), '{}prob_mat.obj'.format(prefix))):\n        print('adj mat or prob mat is missing. Begin folding from scratch.')\n        fold_rna_from_file(filepath, pool, fold_algo, probabilistic, **kwargs)\n\n    load_dense = kwargs.get('load_dense', True)\n    sp_rel_matrix = pickle.load(open(os.path.join(os.path.dirname(filepath), '{}rel_mat.obj'.format(prefix)), 'rb'))\n    if load_dense:\n        adjacency_matrix = np.array([mat.toarray() for mat in sp_rel_matrix])\n    else:\n        adjacency_matrix = np.array(sp_rel_matrix)\n\n    if probabilistic:\n        sp_prob_matrix = pickle.load(\n            open(os.path.join(os.path.dirname(filepath), '{}prob_mat.obj'.format(prefix)), 'rb'))\n        if load_dense:\n            probability_matrix = np.array([mat.toarray() for mat in sp_prob_matrix])\n        else:\n            probability_matrix = np.array(sp_prob_matrix)\n        matrix = (adjacency_matrix, probability_matrix)\n    else:\n        matrix = adjacency_matrix\n\n    return matrix\n\n\ndef load_seq(filepath):\n    if filepath.endswith('.fa'):\n        file = open(filepath, 'r')\n    else:\n        file = gzip.open(filepath, 'rb')\n\n    all_id, all_seq = load_fasta_format(file)\n    return all_id, all_seq\n\n\ndef fold_rna_from_file(filepath, p=None, fold_algo='rnafold', probabilistic=False, **kwargs):\n    assert (fold_algo in ['rnafold', 'rnasubopt', 'rnaplfold'])\n    if fold_algo == 'rnafold':\n        assert (probabilistic is False)\n    if fold_algo == 'rnaplfold':\n        assert (probabilistic is True)\n    print('Parsing', filepath)\n    _, all_seq = load_seq(filepath)\n\n    # compatible with already computed structures with RNAfold\n    prefix = '%s_%s_' % (fold_algo, probabilistic)\n    if fold_algo == 'rnaplfold' or fold_algo == 'rnashapes':\n        prefix += '%d_' % (kwargs.get('w', 150))\n    if kwargs.get('modify_leaks', False):\n        prefix = 'modified_' + prefix\n\n    if p is None:\n        pool = Pool(int(os.cpu_count() * 2 / 3))\n    else:\n        pool = p\n\n    if fold_algo == 'rnafold':\n        fold_func = fold_seq_rnafold\n        res = list(pool.imap(fold_func, all_seq))\n        sp_rel_matrix = []\n        structural_content = []\n        for struct, matrix in res:\n            structural_content.append(struct)\n            sp_rel_matrix.append(matrix)\n        np.save(os.path.join(os.path.dirname(filepath), '{}structures.npy'.format(prefix)),\n                np.array(structural_content))  # [size, length, 3]\n        pickle.dump(sp_rel_matrix,\n                    open(os.path.join(os.path.dirname(filepath), '{}rel_mat.obj'.format(prefix)), 'wb'))\n    elif fold_algo == 'rnasubopt':\n        fold_func = partial(fold_seq_subopt, fold_algo=fold_algo, probabilistic=probabilistic)\n        res = list(pool.imap(fold_func, all_seq))\n        sp_rel_matrix = []\n        sp_prob_matrix = []\n        structural_content = []\n        for struct, matrix in res:\n            structural_content.append(struct)\n            if probabilistic:\n                rel_mat, prob_mat = matrix\n                sp_prob_matrix.append(prob_mat)\n            else:\n                rel_mat = matrix\n            sp_rel_matrix.append(rel_mat)\n        np.save(os.path.join(os.path.dirname(filepath), '{}structures.npy'.format(prefix)),\n                np.array(structural_content))  # [size, length, 3]\n        pickle.dump(sp_rel_matrix,\n                    open(os.path.join(os.path.dirname(filepath), '{}rel_mat.obj'.format(prefix)), 'wb'))\n        if probabilistic:\n            pickle.dump(sp_prob_matrix,\n                        open(os.path.join(os.path.dirname(filepath), '{}prob_mat.obj'.format(prefix)), 'wb'))\n    elif fold_algo == 'rnaplfold':\n        winsize = kwargs.get('w', 150)\n        print('running rnaplfold with winsize %d' % (winsize))\n        fold_func = partial(fold_seq_rnaplfold, w=winsize, l=min(winsize, 150), cutoff=1e-4, no_lonely_bps=True)\n        res = list(pool.imap(fold_func, all_seq))\n        sp_rel_matrix = []\n        sp_prob_matrix = []\n        for rel_mat, prob_mat in res:\n            sp_rel_matrix.append(rel_mat)\n            sp_prob_matrix.append(prob_mat)\n        pickle.dump(sp_rel_matrix,\n                    open(os.path.join(os.path.dirname(filepath), '{}rel_mat.obj'.format(prefix)), 'wb'))\n        pickle.dump(sp_prob_matrix,\n                    open(os.path.join(os.path.dirname(filepath), '{}prob_mat.obj'.format(prefix)), 'wb'))\n    else:\n        raise ValueError('Supported folding algorithms are ' + ', '.join(['rnafold', 'rnasubopt', 'rnaplfold']))\n\n    if p is None:\n        pool.close()\n        pool.join()\n\n    print('Parsing', filepath, 'finished')\n\n\ndef fold_and_check_hairpin(seq, return_label=True):\n    regex = r'^\\(\\(\\(\\.\\.\\.\\)\\)\\)[\\.\\(]|[\\.\\)]\\(\\(\\(\\.\\.\\.\\)\\)\\)$|[\\.\\)]\\(\\(\\(\\.\\.\\.\\)\\)\\)|\\(\\(\\(\\.\\.\\.\\)\\)\\)[\\.\\(]'\n    '''return label, or an annotation over the entire seq'''\n    '''fold rna and check if the structure contains a hairpin of 3 loose nucleotide connected by a stem of 3 basepairs'''\n    struct = RNA.fold(seq)[0]\n    mat = adj_mat(struct)\n    if return_label:\n        match = re.search(regex, struct)\n        return struct, mat, int(match is not None)\n    else:\n        annotation = [0] * len(seq)\n        for match in re.finditer(regex, struct):\n            start_idx = struct[match.start(): match.end()].index('(((...)))') + match.start()\n            annotation[start_idx:start_idx + 9] = [1] * 9\n        return struct, mat, annotation\n\n\ndef fold_and_check_element(seq, element_symbol, return_label=True):\n    '''simply use forgi to annotate the whole string and check if it contains the element'''\n    '''return label, or an annotation over the entire seq'''\n    '''fold rna and check if the structure contains a hairpin of 3 loose nucleotide connected by a stem of 3 basepairs'''\n    struct = RNA.fold(seq)[0]\n    mat = adj_mat(struct)\n    bg = fgb.BulgeGraph.from_dotbracket(struct)\n    annotation = bg.to_element_string(())\n    if return_label:\n        return struct, mat, int(element_symbol in annotation)\n    else:\n        return struct, mat, [int(element_symbol == c) for c in annotation]\n\n\ndef generate_hairpin_dataset(n, length, p=None, return_label=True):\n    '''\n    generate toy dataset\n    positive examples: RNA sequences that contain specific structural motifs:\n        1. a hairpin of three nucleotides connected by a stem of 3 base-pairs\n        2. nucleotidal composition does not matter.\n    negative examples: RNA sequences that do not contain this specific motifs\n    '''\n    data_path = os.path.join(basedir, 'Data/toy-data/hairpin/%s' % ('label' if return_label else 'annotation'))\n    if not os.path.exists(data_path):\n        os.makedirs(data_path)\n\n    if os.path.exists(os.path.join(data_path, 'seq-and-struct.fa')) and \\\n            os.path.exists(os.path.join(data_path, 'adj_mat.obj')):\n        all_labels = []\n        all_seqs = []\n        all_struct = []\n        with open(os.path.join(data_path, 'seq-and-struct.fa'), 'r') as file:\n            for line in file:\n                if line[0] == '>':\n                    label = line.rstrip().split(' ')[-1].split(':')[-1]\n                    if return_label:\n                        all_labels.append(int(label))\n                    else:\n                        all_labels.append([int(c) for c in label.split(',')])\n                elif line[0] in 'ACGT':\n                    all_seqs.append(['ACGT'.index(c) for c in line.rstrip()])\n                elif line[0] in '.()':\n                    all_struct.append(['.()'.index(c) for c in line.rstrip()])\n\n        all_seqs = np.array(all_seqs)\n        sp_adj_matrix = pickle.load(open(os.path.join(data_path, 'adj_mat.obj'), 'rb'))\n    else:\n        all_seqs = np.zeros((n, length), dtype=int)\n        for j in range(length):\n            all_seqs[:, j] = np.random.choice([0, 1, 2, 3], n, p=[0.25, 0.25, 0.25, 0.25])\n        seqs_str = [''.join(['ACGT'[c] for c in seq]) for seq in all_seqs]\n\n        if p is None:\n            pool = Pool(8)\n        else:\n            pool = p\n\n        res = list(pool.imap(partial(fold_and_check_hairpin, return_label=return_label), seqs_str))\n\n        sp_adj_matrix = []\n        all_labels = []\n        all_struct = []\n        with open(os.path.join(data_path, 'seq-and-struct.fa'), 'w') as file:\n            for seq, (struct, mat, label) in zip(seqs_str, res):\n                file.writelines('> label:%s\\n%s\\n%s\\n' %\n                                (label if return_label else ','.join([str(c) for c in label]), seq, struct))\n                sp_adj_matrix.append(mat)\n                all_labels.append(label)\n                all_struct.append(['.()'.index(c) for c in struct])\n\n        pickle.dump(sp_adj_matrix, open(os.path.join(data_path, 'adj_mat.obj'), 'wb'))\n        if p is None:\n            pool.close()\n            pool.join()\n\n    all_labels = np.array(all_labels)\n    adjacency_matrix = np.stack([mat.toarray() for mat in sp_adj_matrix], axis=0)\n    all_struct = np.array(all_struct)\n    return all_seqs, adjacency_matrix, all_labels, all_struct\n\n\ndef generate_element_dataset(n, length, element_symbol, p=None, return_label=True):\n    '''\n    generate toy dataset\n    positive examples: RNA sequences that contain specific structural motifs:\n        1. a hairpin of three nucleotides connected by a stem of 3 base-pairs\n        2. nucleotidal composition does not matter.\n    negative examples: RNA sequences that do not contain this specific motifs\n    '''\n    assert (len(element_symbol) == 1 and str.isalpha(element_symbol))\n    data_path = os.path.join(basedir,\n                             'Data/toy-data/%s/%s' % (element_symbol, 'label' if return_label else 'annotation'))\n    if not os.path.exists(data_path):\n        os.makedirs(data_path)\n\n    if os.path.exists(os.path.join(data_path, 'seq-and-struct.fa')) and \\\n            os.path.exists(os.path.join(data_path, 'adj_mat.obj')):\n        all_labels = []\n        all_seqs = []\n        all_struct = []\n        with open(os.path.join(data_path, 'seq-and-struct.fa'), 'r') as file:\n            for line in file:\n                if line[0] == '>':\n                    label = line.rstrip().split(' ')[-1].split(':')[-1]\n                    if return_label:\n                        all_labels.append(int(label))\n                    else:\n                        all_labels.append([int(c) for c in label.split(',')])\n                elif line[0] in 'ACGT':\n                    all_seqs.append(['ACGT'.index(c) for c in line.rstrip()])\n                elif line[0] in '.()':\n                    all_struct.append(['.()'.index(c) for c in line.rstrip()])\n\n        all_seqs = np.array(all_seqs)\n        sp_adj_matrix = pickle.load(open(os.path.join(data_path, 'adj_mat.obj'), 'rb'))\n    else:\n        all_seqs = np.zeros((n, length), dtype=int)\n        for j in range(length):\n            all_seqs[:, j] = np.random.choice([0, 1, 2, 3], n, p=[0.25, 0.25, 0.25, 0.25])\n        seqs_str = [''.join(['ACGT'[c] for c in seq]) for seq in all_seqs]\n\n        if p is None:\n            pool = Pool(8)\n        else:\n            pool = p\n\n        res = list(pool.imap(partial(fold_and_check_element,\n                                     element_symbol=element_symbol,\n                                     return_label=return_label), seqs_str))\n\n        sp_adj_matrix = []\n        all_labels = []\n        all_struct = []\n        with open(os.path.join(data_path, 'seq-and-struct.fa'), 'w') as file:\n            for seq, (struct, mat, label) in zip(seqs_str, res):\n                file.writelines('> label:%s\\n%s\\n%s\\n' %\n                                (label if return_label else ','.join([str(c) for c in label]), seq, struct))\n                sp_adj_matrix.append(mat)\n                all_labels.append(label)\n                all_struct.append(['.()'.index(c) for c in struct])\n\n        pickle.dump(sp_adj_matrix, open(os.path.join(data_path, 'adj_mat.obj'), 'wb'))\n        if p is None:\n            pool.close()\n            pool.join()\n\n    all_labels = np.array(all_labels)\n    adjacency_matrix = np.stack([mat.toarray() for mat in sp_adj_matrix], axis=0)\n    all_struct = np.array(all_struct)\n    return all_seqs, adjacency_matrix, all_labels, all_struct\n\n\nif __name__ == \"__main__\":\n    np.set_printoptions(threshold=np.inf, edgeitems=30, linewidth=100000, )\n\n    # res = fold_seq_rnaplfold(\n    #     'cgcgggacgcggcccgaggccgtgcgcgagccggggcaccgggcggcggcggcggcggcgcgcgccatgtcgttcagtgaaatgaaccgcaggacgctggcgttccgaggaggcgggttggtcaccgctagcggcggcggctccacgaacAATAACGCTGGCGGGGAGGCCTCAGcttggcctccgcagccccagccgagacagcccccgccgccagcgccgcccgcgcttcagccgcctaatgggcggggggccgacgaggaagtggaattggagggcctggagccccaagacctggaggcctccgccgggccggccgccggcg',\n    #     150, 150, 0.0001, True)\n    # print(res[1].todense().sum(axis=-1))\n    res = fold_seq_rnashapes(\n        'cgcgggacgcggcccgaggccgtgcgcgagccggggcaccgggcggcggcggcggcggcgcgcgccatgtcgttcagtgaaatgaaccgcaggacgctggcgttccgaggaggcgggttggtcaccgctagcggcggcggctccacgaacAATAACGCTGGCGGGGAGGCCTCAGcttggcctccgcagccccagccgagacagcccccgccgccagcgccgcccgcgcttcagccgcctaatgggcggggggccgacgaggaagtggaattggagggcctggagccccaagacctggaggcctccgccgggccggccgccggcg',\n        150, iterations=100)\n    # print(res[0].todense())\n    print(res[1].todense().sum(axis=-1))\n\n    # with open('boltzmann-sampling-acc.txt', 'w') as file:\n    #     for amount in [5, 10, 100, 1000, 5000, 10000]:\n    #         rel_diff, prob_diff = [], []\n    #         for replcate in range(100):\n    #             _, res = fold_seq_subopt(\n    #                 'TGTGAAGCGCGGCTAGCTGCCGGGGTTCGAGGTGGGTCCCAGGGTTAAAATCCCTTGTTGTCTTACTGGTGGCAGCAAGCTAGGACTATACTCCTCGGTCG',\n    #                 'rnafold', True, amount)\n    #             _, new_res = fold_seq_subopt(\n    #                 'TGTGAAGCGCGGCTAGCTGCCGGGGTTCGAGGTGGGTCCCAGGGTTAAAATCCCTTGTTGTCTTACTGGTGGCAGCAAGCTAGGACTATACTCCTCGGTCG',\n    #                 'rnafold', True, amount)\n    #\n    #             diff = (res[0].todense() != new_res[0].todense()).astype(np.int32)\n    #             rel_diff.append(np.sum(diff))\n    #\n    #             diff = np.abs(res[1].todense() - new_res[1].todense())\n    #             prob_diff.append(np.mean(np.max(diff, axis=-1)))\n    #         file.writelines('sampling amount %d, relation difference: %.4f\\u00b1%.4f, probability difference: %.4f\\u00b1%.4f' %\n    #               (amount, np.mean(rel_diff), np.std(rel_diff), np.mean(prob_diff), np.std(prob_diff)))\n    #         print('sampling amount %d, relation difference: %.4f\\u00b1%.4f, probability difference: %.4f\\u00b1%.4f' %\n    #               (amount, np.mean(rel_diff), np.std(rel_diff), np.mean(prob_diff), np.std(prob_diff)))\n\n    # annotation for the multiloop elements\n    # all_seqs, adjacency_matrix, all_labels, _ = generate_element_dataset(80000, 101, 'i', return_label=False)\n    # print(all_labels.shape)\n    # print(np.where(np.count_nonzero(all_labels, axis=-1) > 0)[0].__len__())\n    #\n    # all_seqs, adjacency_matrix, all_labels, _ = generate_hairpin_dataset(80000, 101, 'm', return_label=False)\n    # print(all_labels.shape)\n    # print(np.where(np.count_nonzero(all_labels, axis=-1) > 0)[0].__len__())\n", "meta": {"hexsha": "9ad46591b466e19699f398dd45535fc5fc4d7ba6", "size": 29418, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/rna_utils.py", "max_stars_repo_name": "HarveyYan/RNAonGraph", "max_stars_repo_head_hexsha": "0056cc465f7bc4a89c4955d2cee88d6a858cef71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2020-06-27T08:08:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T03:29:45.000Z", "max_issues_repo_path": "lib/rna_utils.py", "max_issues_repo_name": "HarveyYan/RNAonGraph", "max_issues_repo_head_hexsha": "0056cc465f7bc4a89c4955d2cee88d6a858cef71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-10T00:46:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-20T21:25:27.000Z", "max_forks_repo_path": "lib/rna_utils.py", "max_forks_repo_name": "HarveyYan/RNAonGraph", "max_forks_repo_head_hexsha": "0056cc465f7bc4a89c4955d2cee88d6a858cef71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-02-19T16:04:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T22:32:23.000Z", "avg_line_length": 42.4502164502, "max_line_length": 338, "alphanum_fraction": 0.5751580665, "include": true, "reason": "import numpy,import scipy", "num_tokens": 7555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.3593641314378279, "lm_q1q2_score": 0.18949864441711325}}
{"text": "import numpy as np\nfrom skimage.future.graph import RAG\nimport heapq\nfrom skimage.segmentation import find_boundaries\nfrom skimage.morphology import skeletonize\nfrom sklearn.linear_model import LogisticRegression\nfrom lib.utils import get_xymaps, shuffler\nfrom .nmf import NMFDataCompressor\n\n\ndef run_lrc_mrm(dataset_slice, cps, sample_size):\n    compressor = NMFDataCompressor(cps)\n    compressor.fit(dataset_slice, sample_size)\n    compressed_dataset = compressor.transform(dataset_slice['data'])\n    dataset_slice['data'] = compressed_dataset\n    dataset_slice = _fit_lrc_model(\n        dataset_slice,\n        model=LogisticRegression(penalty='none'),\n        training_set_size=sample_size,\n    )\n    dataset_slice = _lrc_mrm_segmentation(dataset_slice)\n    return dataset_slice\n\n\ndef _lrc_mrm_segmentation(dataset):\n    \"\"\"\n    Implementation of the multi-region merging segmentation controlled by\n    a trained classifier model. Design of the function was originally inspired\n    by the merge_hierarchical function of Skimage:\n    (https://github.com/scikit-image/scikit-image/blob/master/skimage/)\n    \"\"\"\n    # Collect spatial resolution and data from dataset\n    rx, ry = dataset.get('spatial_resol')\n    data = dataset.get('data')\n    model = dataset.get('lrc_model')\n\n    # Define merging decision function\n    def mdf(v):\n        return model.predict_proba(np.atleast_2d(v))[0, 1]\n\n    # Initialize region adjacency graph (RAG)\n    rag, edge_heap, segments = _initialize_graph(rx, ry, data, model)\n\n    # Start the region-merging algorithm\n    while (len(edge_heap) > 0) and (edge_heap[0][0] < 0.5):\n        # Pop the smallest edge from the heap if weight < 0.5\n        smallest_weight, n1, n2, valid = heapq.heappop(edge_heap)\n\n        # Check that the edge is valid\n        if valid:\n            # Make sure that n1 is the smallest regiom\n            if rag.nodes[n1]['count'] > rag.nodes[n2]['count']:\n                n1, n2 = n2, n1\n\n            # Update properties of n2\n            rag.nodes[n2]['labels'] = (rag.nodes[n1]['labels']\n                                       + rag.nodes[n2]['labels'])\n            rag.nodes[n2]['count'] = (rag.nodes[n1]['count']\n                                      + rag.nodes[n2]['count'])\n\n            # Get new neighbors of n2\n            n1_numbers = set(rag.neighbors(n1))\n            n2_numbers = set(rag.neighbors(n2))\n            new_neighbors = (n1_numbers | n2_numbers) - n2_numbers - {n1, n2}\n\n            # Disable edges of n1 in the heap list\n            for nbr in rag.neighbors(n1):\n                edge = rag[n1][nbr]\n                edge['heap item'][3] = False\n\n            # Remove n1 from the graph (edges are still in the heap list)\n            rag.remove_node(n1)\n\n            # Update new edges of n2\n            for nbr in new_neighbors:\n                rag.add_edge(n2, nbr)\n                edge = rag[n2][nbr]\n                master_n2 = rag.nodes[n2]['master']\n                master_nbr = rag.nodes[nbr]['master']\n                weight = mdf(_vector_similarity(master_n2, master_nbr))\n                heap_item = [weight, n2, nbr, (weight < 0.5)]\n                edge['heap item'] = heap_item\n                # Push edges to the heap\n                heapq.heappush(edge_heap, heap_item)\n\n    # Compute grain segmentation map\n    label_map = np.arange(segments.max() + 1)\n    for ix, (n, d) in enumerate(rag.nodes(data=True)):\n        for lab in d['labels']:\n            label_map[lab] = ix\n    segmentation = label_map[segments]\n\n    # Compute grain boundary map\n    gbs = skeletonize(find_boundaries(segmentation, mode='inner'))\n\n    # Return updated dataset\n    dataset['segmentation'] = segmentation.ravel()\n    dataset['boundaries'] = gbs.ravel()\n\n    return dataset\n\n\ndef _fit_lrc_model(dataset, model, training_set_size):\n    \"\"\"Fits a model, computes precision, recall and accuracy\"\"\"\n    training_set = _get_sample_set(dataset, training_set_size)\n    model.fit(training_set['x'], training_set['y'])\n    dataset['lrc_model'] = model\n    return dataset\n\n\ndef _initialize_graph(rx, ry, data, model):\n    \"\"\"Initializes the Region Adjacency Graph (RAG).\"\"\"\n\n    # Define merging decision function\n    def mdf(v):\n        return model.predict_proba(np.atleast_2d(v))[0, 1]\n\n    # Initialize RAG\n    x_map, y_map = get_xymaps(rx, ry)\n    segments = np.arange(rx * ry).reshape((rx, ry))\n    rag = RAG(segments)\n\n    # Initialize nodes\n    data_reshaped = data.reshape((rx, ry, data.shape[1]))\n    for n in rag:\n        rag.nodes[n].update({'labels': [n]})\n    for index in np.ndindex(segments.shape):\n        current = segments[index]\n        rag.nodes[current]['count'] = 1\n        rag.nodes[current]['master'] = data_reshaped[index]\n        rag.nodes[current]['xpos'] = x_map[current]\n        rag.nodes[current]['ypos'] = y_map[current]\n\n    # Initialize edges\n    edge_heap = []\n    for n1, n2, d in rag.edges(data=True):\n        master_x = rag.nodes[n1]['master']\n        master_y = rag.nodes[n2]['master']\n        weight = mdf(_vector_similarity(master_x, master_y))\n        # Push the edge into the heap\n        heap_item = [weight, n1, n2, (weight < 0.5)]\n        d['heap item'] = heap_item\n        heapq.heappush(edge_heap, heap_item)\n\n    return rag, edge_heap, segments\n\n\ndef _get_sample_set(dataset, sample_size):\n    \"\"\"\n    Randomly extracts a training or test set from the dataset.\n    - Class 0: pairs of adjacent voxels\n    - Class 1: pairs of non-adjacent voxels\n    \"\"\"\n    # Collect data from the dataset\n    rx, ry = dataset.get('spatial_resol')\n    data = dataset.get('data')\n    x_map, y_map = get_xymaps(rx, ry)\n\n    # Extract adjacent sample\n    x_close, y_close = _get_adjacent_sample(\n        rx, ry, data, sample_size, x_map, y_map)\n\n    # Extract non-adjacent sample\n    x_far, y_far = _get_non_adjacent_sample(data, sample_size, x_map, y_map)\n\n    # Stack both samples\n    x = np.vstack((x_close, x_far))\n    y = np.hstack((y_close, y_far))\n\n    # Shuffle extracted set\n    idx = np.arange(0, x.shape[0])\n    np.random.shuffle(idx)\n    x = x[idx]\n    y = y[idx]\n\n    sample_set = {'x': x, 'y': y}\n\n    return sample_set\n\n\ndef _get_adjacent_sample(rx, ry, data, sample_size, xmap, ymap):\n    \"\"\"Samples Sbar, the distribution of adjacent pixel feature vectors.\"\"\"\n\n    # Get set of random data\n    x0, idx = shuffler(data, sample_size)\n\n    # Modify location by 1 pixel\n    modified_x = xmap[idx] + (np.random.randint(0, 2, sample_size) * 2 - 1)\n    modified_x = np.clip(modified_x.astype('int'), 0, rx - 1)\n    modified_y = ymap[idx] + (np.random.randint(0, 2, sample_size) * 2 - 1)\n    modified_y = np.clip(modified_y.astype('int'), 0, ry - 1)\n\n    # Find corresponding signal\n    x1 = np.empty_like(x0)\n    c = 0\n    i = np.arange(rx * ry)\n    for xc, yc in zip(modified_x, modified_y):\n        u = np.zeros((rx, ry))\n        u[xc, yc] = 1\n        num = i[(u.ravel() == 1)]\n        x1[c] = data[num]\n        c += 1\n\n    # Compute distance vectors\n    x_close = _vector_similarity(x1, x0)\n\n    # Label as 0\n    y_close = np.zeros(x_close.shape[0], dtype=np.uint8)\n\n    return x_close, y_close\n\n\ndef _get_non_adjacent_sample(data, sample_size, xmap, ymap):\n    \"\"\"Samples the distribution of non-adjacent pixels.\"\"\"\n\n    # Get random set of data and location of selected pixel pairs, twice\n    x0, idx = shuffler(data, sample_size)\n    loc_x_0, loc_y_0 = xmap[idx], ymap[idx]\n    x1, idx = shuffler(data, sample_size)\n    loc_x_1, loc_y_1 = xmap[idx], ymap[idx]\n\n    # Compute distance vectors\n    x_far = _vector_similarity(x1, x0)\n\n    # Filter out adjacent examples\n    adjacent_filter = np.abs(loc_x_0 - loc_x_1) + np.abs(loc_y_0 - loc_y_1) < 2\n    x_far = x_far[~adjacent_filter]\n\n    # Label as 1\n    y_far = np.ones(x_far.shape[0], dtype=np.uint8)\n\n    return x_far, y_far\n\n\ndef _vector_similarity(a, b):\n    \"\"\"Returns distance vector of two input feature vectors\"\"\"\n    return np.square(np.subtract(a, b))\n", "meta": {"hexsha": "89a4d97a94a6d612d8c142620e4dee56b65c7bab", "size": 7924, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/segmentation/segmentation.py", "max_stars_repo_name": "MalloryWittwer/drm_ml_demo", "max_stars_repo_head_hexsha": "03ec73bc6c5b8807767d4c38ac8649ec4ffbea37", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-24T03:19:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T03:19:28.000Z", "max_issues_repo_path": "lib/segmentation/segmentation.py", "max_issues_repo_name": "MalloryWittwer/drm_ml_demo", "max_issues_repo_head_hexsha": "03ec73bc6c5b8807767d4c38ac8649ec4ffbea37", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/segmentation/segmentation.py", "max_forks_repo_name": "MalloryWittwer/drm_ml_demo", "max_forks_repo_head_hexsha": "03ec73bc6c5b8807767d4c38ac8649ec4ffbea37", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2941176471, "max_line_length": 79, "alphanum_fraction": 0.6317516406, "include": true, "reason": "import numpy", "num_tokens": 2099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.28776782186926264, "lm_q1q2_score": 0.1894713738748583}}
{"text": "# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\nscikit-rebate was primarily developed at the University of Pennsylvania by:\r\n    - Randal S. Olson (rso@randalolson.com)\r\n    - Pete Schmitt (pschmitt@upenn.edu)\r\n    - Ryan J. Urbanowicz (ryanurb@upenn.edu)\r\n    - Weixuan Fu (weixuanf@upenn.edu)\r\n    - and many more generous open source contributors\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software\r\nand associated documentation files (the \"Software\"), to deal in the Software without restriction,\r\nincluding without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\nand/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,\r\nsubject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all copies or substantial\r\nportions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT\r\nLIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\r\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\r\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\n\r\n# (Subset of continuous-valued feature data, Subset of discrete-valued feature data, max/min difference, instance index, boolean mask for continuous, boolean mask for discrete)\r\ndef get_row_missing(xc, xd, cdiffs, index, cindices, dindices):\r\n    \"\"\" Calculate distance between index instance and all other instances. \"\"\"\r\n    row = np.empty(0, dtype=np.double)  # initialize empty row\r\n    cinst1 = xc[index]  # continuous-valued features for index instance\r\n    dinst1 = xd[index]  # discrete-valued features for index instance\r\n    # Boolean mask locating missing values for continuous features for index instance\r\n    can = cindices[index]\r\n    # Boolean mask locating missing values for discrete features for index instance\r\n    dan = dindices[index]\r\n    tf = len(cinst1) + len(dinst1)  # total number of features.\r\n\r\n    # Progressively compare current instance to all others. Excludes comparison with self indexed instance. (Building the distance matrix triangle).\r\n    for j in range(index):\r\n        dist = 0\r\n        dinst2 = xd[j]  # discrete-valued features for compared instance\r\n        cinst2 = xc[j]  # continuous-valued features for compared instance\r\n\r\n        # Manage missing values in discrete features\r\n        # Boolean mask locating missing values for discrete features for compared instance\r\n        dbn = dindices[j]\r\n        # indexes where there is at least one missing value in the feature between an instance pair.\r\n        idx = np.unique(np.append(dan, dbn))\r\n        # Number of features excluded from distance calculation due to one or two missing values within instance pair. Used to normalize distance values for comparison.\r\n        dmc = len(idx)\r\n        d1 = np.delete(dinst1, idx)  # delete unique missing features from index instance\r\n        d2 = np.delete(dinst2, idx)  # delete unique missing features from compared instance\r\n\r\n        # Manage missing values in continuous features\r\n        # Boolean mask locating missing values for continuous features for compared instance\r\n        cbn = cindices[j]\r\n        # indexes where there is at least one missing value in the feature between an instance pair.\r\n        idx = np.unique(np.append(can, cbn))\r\n        # Number of features excluded from distance calculation due to one or two missing values within instance pair. Used to normalize distance values for comparison.\r\n        cmc = len(idx)\r\n        c1 = np.delete(cinst1, idx)  # delete unique missing features from index instance\r\n        c2 = np.delete(cinst2, idx)  # delete unique missing features from compared instance\r\n        # delete unique missing features from continuous value difference scores\r\n        cdf = np.delete(cdiffs, idx)\r\n\r\n        # Add discrete feature distance contributions (missing values excluded) - Hamming distance\r\n        dist += len(d1[d1 != d2])\r\n\r\n        # Add continuous feature distance contributions (missing values excluded) - Manhattan distance (Note that 0-1 continuous value normalization is included ~ subtraction of minimums cancel out)\r\n        dist += np.sum(np.absolute(np.subtract(c1, c2)) / cdf)\r\n\r\n        # Normalize distance calculation based on total number of missing values bypassed in either discrete or continuous features.\r\n        tnmc = tf - dmc - cmc  # Total number of unique missing counted\r\n        # Distance normalized by number of features included in distance sum (this seeks to handle missing values neutrally in distance calculation)\r\n        dist = dist/float(tnmc)\r\n\r\n        row = np.append(row, dist)\r\n\r\n    return row\r\n\r\n\r\n# For iter relief\r\ndef get_row_missing_iter(xc, xd, cdiffs, index, cindices, dindices, weights):\r\n    \"\"\" Calculate distance between index instance and all other instances. \"\"\"\r\n    row = np.empty(0, dtype=np.double)  # initialize empty row\r\n    cinst1 = xc[index]  # continuous-valued features for index instance\r\n    dinst1 = xd[index]  # discrete-valued features for index instance\r\n    # Boolean mask locating missing values for continuous features for index instance\r\n    can = cindices[index]\r\n    # Boolean mask locating missing values for discrete features for index instance\r\n    dan = dindices[index]\r\n    tf = len(cinst1) + len(dinst1)  # total number of features.\r\n    # Progressively compare current instance to all others. Excludes comparison with self indexed instance. (Building the distance matrix triangle).\r\n    for j in range(index):\r\n        dist = 0\r\n        dinst2 = xd[j]  # discrete-valued features for compared instance\r\n        cinst2 = xc[j]  # continuous-valued features for compared instance\r\n\r\n        # Manage missing values in discrete features\r\n        # Boolean mask locating missing values for discrete features for compared instance\r\n        dbn = dindices[j]\r\n        # indexes where there is at least one missing value in the feature between an instance pair.\r\n        idx = np.unique(np.append(dan, dbn))\r\n        # Number of features excluded from distance calculation due to one or two missing values within instance pair. Used to normalize distance values for comparison.\r\n        dmc = len(idx)\r\n        d1 = np.delete(dinst1, idx)  # delete unique missing features from index instance\r\n        d2 = np.delete(dinst2, idx)  # delete unique missing features from compared instance\r\n\r\n        wd = np.delete(weights, idx)  # delete weights corresponding to missing discrete features\r\n        # Manage missing values in continuous features\r\n        # Boolean mask locating missing values for continuous features for compared instance\r\n        cbn = cindices[j]\r\n        # indexes where there is at least one missing value in the feature between an instance pair.\r\n        idx = np.unique(np.append(can, cbn))\r\n        # Number of features excluded from distance calculation due to one or two missing values within instance pair. Used to normalize distance values for comparison.\r\n        cmc = len(idx)\r\n        c1 = np.delete(cinst1, idx)  # delete unique missing features from index instance\r\n        c2 = np.delete(cinst2, idx)  # delete unique missing features from compared instance\r\n        # delete unique missing features from continuous value difference scores\r\n        cdf = np.delete(cdiffs, idx)\r\n        wc = np.delete(weights, idx)  # delete weights corresponding to missing continuous features\r\n\r\n        # Add discrete feature distance contributions (missing values excluded) - Hamming distance\r\n        if len(d1)!=0: #To ensure there is atleast one discrete variable\r\n            hamming_dist = np.not_equal(d1, d2).astype(float)\r\n            weight_hamming_dist = np.dot(hamming_dist, wd)/np.sum(wd)\r\n            dist += weight_hamming_dist\r\n\r\n        # Add continuous feature distance contributions (missing values excluded) - Manhattan distance (Note that 0-1 continuous value normalization is included ~ subtraction of minimums cancel out)\r\n        if len(c1)!=0: #To ensure there is atleast one continuous variable\r\n            dist += np.dot((np.absolute(np.subtract(c1, c2)) / cdf), wc)/np.sum(wc)\r\n\r\n        # Normalize distance calculation based on total number of missing values bypassed in either discrete or continuous features.\r\n        tnmc = tf - dmc - cmc  # Total number of unique missing counted\r\n        # Distance normalized by number of features included in distance sum (this seeks to handle missing values neutrally in distance calculation)\r\n        dist = dist/float(tnmc)\r\n\r\n        row = np.append(row, dist)\r\n\r\n    return row\r\n\r\n\r\ndef ramp_function(data_type, attr, fname, xinstfeature, xNNifeature):\r\n    \"\"\" Our own user simplified variation of the ramp function suggested by Hong 1994, 1997. Hong's method requires the user to specifiy two thresholds\r\n    that indicate the max difference before a score of 1 is given, as well a min difference before a score of 0 is given, and any in the middle get a\r\n    score that is the normalized difference between the two continuous feature values. This was done because when discrete and continuous features were mixed,\r\n    continuous feature scores were underestimated.  Towards simplicity, automation, and a dataset adaptable approach,\r\n    here we simply check whether the difference is greater than the standard deviation for the given feature; if so we assign a score of 1, otherwise we\r\n    assign the normalized feature score difference.  This should help compensate for the underestimation. \"\"\"\r\n    diff = 0\r\n    mmdiff = attr[fname][3]  # Max/Min range of values for target feature\r\n    rawfd = abs(xinstfeature - xNNifeature)  # prenormalized feature value difference\r\n\r\n    if data_type == 'mixed':  # Ramp function utilized\r\n        # Check whether feature value difference is greater than the standard deviation\r\n        standDev = attr[fname][4]\r\n        if rawfd > standDev:  # feature value difference is is wider than a standard deviation\r\n            diff = 1\r\n        else:\r\n            diff = abs(xinstfeature - xNNifeature) / mmdiff\r\n\r\n    else:  # Normal continuous feature scoring\r\n        diff = abs(xinstfeature - xNNifeature) / mmdiff\r\n\r\n    return diff\r\n\r\n\r\ndef compute_score(attr, mcmap, NN, feature, inst, nan_entries, headers, class_type, X, y, labels_std, data_type, near=True):\r\n    \"\"\"Flexible feature scoring method that can be used with any core Relief-based method. Scoring proceeds differently\r\n    based on whether endpoint is binary, multiclass, or continuous. This method is called for a single target instance\r\n    + feature combination and runs over all items in NN. \"\"\"\r\n\r\n    fname = headers[feature]  # feature identifier\r\n    ftype = attr[fname][0]  # feature type\r\n    ctype = class_type  # class type (binary, multiclass, continuous)\r\n    diff_hit = diff_miss = 0.0  # Tracks the score contribution\r\n    # Tracks the number of hits/misses. Used in normalizing scores by 'k' in ReliefF, and by m or h in SURF, SURF*, MultiSURF*, and MultiSURF\r\n    count_hit = count_miss = 0.0\r\n    # Initialize 'diff' (The score contribution for this target instance and feature over all NN)\r\n    diff = 0\r\n    # mmdiff = attr[fname][3] # Max/Min range of values for target feature\r\n\r\n    datalen = float(len(X))\r\n\r\n    # If target instance is missing, then a 'neutral' score contribution of 0 is returned immediately since all NN comparisons will be against this missing value.\r\n    if nan_entries[inst][feature]:\r\n        return 0.\r\n    # Note missing data normalization below regarding missing NN feature values is accomplished by counting hits and misses (missing values are not counted) (happens in parallel with hit/miss imbalance normalization)\r\n\r\n    xinstfeature = X[inst][feature]  # value of target instances target feature.\r\n\r\n    #--------------------------------------------------------------------------\r\n    if ctype == 'binary':\r\n        for i in range(len(NN)):\r\n            if nan_entries[NN[i]][feature]:  # skip any NN with a missing value for this feature.\r\n                continue\r\n\r\n            xNNifeature = X[NN[i]][feature]\r\n\r\n            if near:  # SCORING FOR NEAR INSTANCES\r\n                if y[inst] == y[NN[i]]:   # HIT\r\n                    count_hit += 1\r\n                    if ftype == 'continuous':\r\n                        # diff_hit -= abs(xinstfeature - xNNifeature) / mmdiff #Normalize absolute value of feature value difference by max-min value range for feature (so score update lies between 0 and 1)\r\n                        diff_hit -= ramp_function(data_type, attr, fname, xinstfeature, xNNifeature)\r\n                    else:  # discrete feature\r\n                        if xinstfeature != xNNifeature:  # A difference in feature value is observed\r\n                            # Feature score is reduced when we observe feature difference between 'near' instances with the same class.\r\n                            diff_hit -= 1\r\n                else:  # MISS\r\n                    count_miss += 1\r\n                    if ftype == 'continuous':\r\n                        # diff_miss += abs(xinstfeature - xNNifeature) / mmdiff\r\n                        diff_miss += ramp_function(data_type, attr, fname,\r\n                                                   xinstfeature, xNNifeature)\r\n                    else:  # discrete feature\r\n                        if xinstfeature != xNNifeature:  # A difference in feature value is observed\r\n                            # Feature score is increase when we observe feature difference between 'near' instances with different class values.\r\n                            diff_miss += 1\r\n\r\n            else:  # SCORING FOR FAR INSTANCES (ONLY USED BY MULTISURF* BASED ON HOW CODED)\r\n                if y[inst] == y[NN[i]]:   # HIT\r\n                    count_hit += 1\r\n                    if ftype == 'continuous':\r\n\r\n                        # diff_hit -= abs(xinstfeature - xNNifeature) / mmdiff  #Hits differently add continuous value differences rather than subtract them\r\n                        # Sameness should yield most negative score\r\n                        diff_hit -= (1-ramp_function(data_type, attr,\r\n                                                     fname, xinstfeature, xNNifeature))\r\n                    else:  # discrete feature\r\n                        # The same feature value is observed (Used for more efficient 'far' scoring, since there should be fewer same values for 'far' instances)\r\n                        if xinstfeature == xNNifeature:\r\n                            # Feature score is reduced when we observe the same feature value between 'far' instances with the same class.\r\n                            diff_hit -= 1\r\n                else:  # MISS\r\n                    count_miss += 1\r\n                    if ftype == 'continuous':\r\n                        # diff_miss += abs(xinstfeature - xNNifeature) / mmdiff #Misses differntly subtract continuous value differences rather than add them\r\n                        # Sameness should yield most negative score\r\n                        diff_miss += (1-ramp_function(data_type, attr,\r\n                                                      fname, xinstfeature, xNNifeature))\r\n                    else:  # discrete feature\r\n                        # The same feature value is observed (Used for more efficient 'far' scoring, since there should be fewer same values for 'far' instances)\r\n                        if xinstfeature == xNNifeature:\r\n                            # Feature score is increased when we observe the same feature value between 'far' instances with different class values.\r\n                            diff_miss += 1\r\n\r\n        \"\"\" Score Normalizations:\r\n        *'n' normalization dividing by the number of training instances (this helps ensure that all final scores end up in the -1 to 1 range\r\n        *'k','h','m' normalization dividing by the respective number of hits and misses in NN (after ignoring missing values), also helps account for class imbalance within nearest neighbor radius)\"\"\"\r\n        if count_hit == 0.0 or count_miss == 0.0:  # Special case, avoid division error\r\n            if count_hit == 0.0 and count_miss == 0.0:\r\n                return 0.0\r\n            elif count_hit == 0.0:\r\n                diff = (diff_miss / count_miss) / datalen\r\n            else:  # count_miss == 0.0\r\n                diff = (diff_hit / count_hit) / datalen\r\n        else:  # Normal diff normalization\r\n            diff = ((diff_hit / count_hit) + (diff_miss / count_miss)) / datalen\r\n\r\n    #--------------------------------------------------------------------------\r\n    elif ctype == 'multiclass':\r\n        class_store = dict()  # only 'miss' classes will be stored\r\n        # missClassPSum = 0\r\n\r\n        for each in mcmap:\r\n            if(each != y[inst]):  # Identify miss classes for current target instance.\r\n                class_store[each] = [0, 0]\r\n                # missClassPSum += mcmap[each]\r\n\r\n        for i in range(len(NN)):\r\n            if nan_entries[NN[i]][feature]:  # skip any NN with a missing value for this feature.\r\n                continue\r\n\r\n            xNNifeature = X[NN[i]][feature]\r\n\r\n            if near:  # SCORING FOR NEAR INSTANCES\r\n                if(y[inst] == y[NN[i]]):  # HIT\r\n                    count_hit += 1\r\n                    if ftype == 'continuous':\r\n                        # diff_hit -= abs(xinstfeature - xNNifeature) / mmdiff\r\n                        diff_hit -= ramp_function(data_type, attr, fname, xinstfeature, xNNifeature)\r\n                    else:  # discrete feature\r\n                        if xinstfeature != xNNifeature:\r\n                            # Feature score is reduced when we observe feature difference between 'near' instances with the same class.\r\n                            diff_hit -= 1\r\n                else:  # MISS\r\n                    for missClass in class_store:\r\n                        if(y[NN[i]] == missClass):  # Identify which miss class is present\r\n                            class_store[missClass][0] += 1\r\n                            if ftype == 'continuous':\r\n                                # class_store[missClass][1] += abs(xinstfeature - xNNifeature) / mmdiff\r\n                                class_store[missClass][1] += ramp_function(\r\n                                    data_type, attr, fname, xinstfeature, xNNifeature)\r\n                            else:  # discrete feature\r\n                                if xinstfeature != xNNifeature:\r\n                                    # Feature score is increase when we observe feature difference between 'near' instances with different class values.\r\n                                    class_store[missClass][1] += 1\r\n\r\n            else:  # SCORING FOR FAR INSTANCES (ONLY USED BY MULTISURF* BASED ON HOW CODED)\r\n                if(y[inst] == y[NN[i]]):  # HIT\r\n                    count_hit += 1\r\n                    if ftype == 'continuous':\r\n                        # diff_hit -= abs(xinstfeature - xNNifeature) / mmdiff  #Hits differently add continuous value differences rather than subtract them\r\n                        # Sameness should yield most negative score\r\n                        diff_hit -= (1-ramp_function(data_type, attr,\r\n                                                     fname, xinstfeature, xNNifeature))\r\n                    else:  # discrete features\r\n                        if xinstfeature == xNNifeature:\r\n                            # Feature score is reduced when we observe the same feature value between 'far' instances with the same class.\r\n                            diff_hit -= 1\r\n                else:  # MISS\r\n                    for missClass in class_store:\r\n                        if(y[NN[i]] == missClass):\r\n                            class_store[missClass][0] += 1\r\n                            if ftype == 'continuous':\r\n                                # class_store[missClass][1] += abs(xinstfeature - xNNifeature) / mmdiff\r\n                                # Sameness should yield most negative score\r\n                                class_store[missClass][1] += (1-ramp_function(data_type,\r\n                                                                              attr, fname, xinstfeature, xNNifeature))\r\n                            else:  # discrete feature\r\n                                if xinstfeature == xNNifeature:\r\n                                    # Feature score is increased when we observe the same feature value between 'far' instances with different class values.\r\n                                    class_store[missClass][1] += 1\r\n\r\n        \"\"\" Score Normalizations:\r\n        *'n' normalization dividing by the number of training instances (this helps ensure that all final scores end up in the -1 to 1 range\r\n        *'k','h','m' normalization dividing by the respective number of hits and misses in NN (after ignoring missing values), also helps account for class imbalance within nearest neighbor radius)\r\n        * multiclass normalization - accounts for scoring by multiple miss class, so miss scores don't have too much weight in contrast with hit scoring. If a given miss class isn't included in NN\r\n        then this normalization will account for that possibility. \"\"\"\r\n        # Miss component\r\n        for each in class_store:\r\n            count_miss += class_store[each][0]\r\n\r\n        if count_hit == 0.0 and count_miss == 0.0:\r\n            return 0.0\r\n        else:\r\n            if count_miss == 0:\r\n                pass\r\n            else:  # Normal diff normalization\r\n                for each in class_store:  # multiclass normalization\r\n                    # Contribution of given miss class weighted by it's observed frequency within NN set.\r\n                    diff += class_store[each][1] * \\\r\n                        (class_store[each][0] / count_miss) * len(class_store)\r\n                diff = diff / count_miss  # 'm' normalization\r\n\r\n            # Hit component: with 'h' normalization\r\n            if count_hit == 0:\r\n                pass\r\n            else:\r\n                diff += (diff_hit / count_hit)\r\n\r\n        diff = diff / datalen  # 'n' normalization\r\n\r\n    #--------------------------------------------------------------------------\r\n    else:  # CONTINUOUS endpoint\r\n        same_class_bound = labels_std\r\n\r\n        for i in range(len(NN)):\r\n            if nan_entries[NN[i]][feature]:  # skip any NN with a missing value for this feature.\r\n                continue\r\n\r\n            xNNifeature = X[NN[i]][feature]\r\n\r\n            if near:  # SCORING FOR NEAR INSTANCES\r\n                if abs(y[inst] - y[NN[i]]) < same_class_bound:  # HIT approximation\r\n                    count_hit += 1\r\n                    if ftype == 'continuous':\r\n                        # diff_hit -= abs(xinstfeature - xNNifeature) / mmdiff\r\n                        diff_hit -= ramp_function(data_type, attr, fname, xinstfeature, xNNifeature)\r\n                    else:  # discrete feature\r\n                        if xinstfeature != xNNifeature:\r\n                            # Feature score is reduced when we observe feature difference between 'near' instances with the same 'class'.\r\n                            diff_hit -= 1\r\n                else:  # MISS approximation\r\n                    count_miss += 1\r\n                    if ftype == 'continuous':\r\n                        # diff_miss += abs(xinstfeature - xNNifeature) / mmdiff\r\n                        diff_miss += ramp_function(data_type, attr, fname,\r\n                                                   xinstfeature, xNNifeature)\r\n                    else:  # discrete feature\r\n                        if xinstfeature != xNNifeature:\r\n                            # Feature score is increase when we observe feature difference between 'near' instances with different class value.\r\n                            diff_miss += 1\r\n\r\n            else:  # SCORING FOR FAR INSTANCES (ONLY USED BY MULTISURF* BASED ON HOW CODED)\r\n                if abs(y[inst] - y[NN[i]]) < same_class_bound:  # HIT approximation\r\n                    count_hit += 1\r\n                    if ftype == 'continuous':\r\n                        # diff_hit += abs(xinstfeature - xNNifeature) / mmdiff\r\n                        # Sameness should yield most negative score\r\n                        diff_hit -= (1-ramp_function(data_type, attr,\r\n                                                     fname, xinstfeature, xNNifeature))\r\n                    else:  # discrete feature\r\n                        if xinstfeature == xNNifeature:\r\n                            # Feature score is reduced when we observe the same feature value between 'far' instances with the same class.\r\n                            diff_hit -= 1\r\n                else:  # MISS approximation\r\n                    count_miss += 1\r\n                    if ftype == 'continuous':\r\n                        # diff_miss -= abs(xinstfeature - xNNifeature) / mmdiff\r\n                        # Sameness should yield most negative score\r\n                        diff_miss += (1-ramp_function(data_type, attr,\r\n                                                      fname, xinstfeature, xNNifeature))\r\n                    else:  # discrete feature\r\n                        if xinstfeature == xNNifeature:\r\n                            # Feature score is increased when we observe the same feature value between 'far' instances with different class values.\r\n                            diff_miss += 1\r\n\r\n        \"\"\" Score Normalizations:\r\n        *'n' normalization dividing by the number of training instances (this helps ensure that all final scores end up in the -1 to 1 range\r\n        *'k','h','m' normalization dividing by the respective number of hits and misses in NN (after ignoring missing values), also helps account for class imbalance within nearest neighbor radius)\"\"\"\r\n\r\n        if count_hit == 0.0 or count_miss == 0.0:  # Special case, avoid division error\r\n            if count_hit == 0.0 and count_miss == 0.0:\r\n                return 0.0\r\n            elif count_hit == 0.0:\r\n                diff = (diff_miss / count_miss) / datalen\r\n            else:  # count_miss == 0.0\r\n                diff = (diff_hit / count_hit) / datalen\r\n        else:  # Normal diff normalization\r\n            diff = ((diff_hit / count_hit) + (diff_miss / count_miss)) / datalen\r\n\r\n    return diff\r\n\r\n\r\ndef ReliefF_compute_scores(inst, attr, nan_entries, num_attributes, mcmap, NN, headers, class_type, X, y, labels_std, data_type, weight_flag=0, weights=None):\r\n    \"\"\" Unique scoring procedure for ReliefF algorithm. Scoring based on k nearest hits and misses of current target instance. \"\"\"\r\n    scores = np.zeros(num_attributes)\r\n    if weight_flag == 2:\r\n        for feature_num in range(num_attributes):\r\n            scores[feature_num] += weights[feature_num]*compute_score(attr, mcmap, NN, feature_num, inst,\r\n                                                                      nan_entries, headers, class_type, X, y, labels_std, data_type)\r\n    else:\r\n        for feature_num in range(num_attributes):\r\n            scores[feature_num] += compute_score(attr, mcmap, NN, feature_num, inst,\r\n                                                 nan_entries, headers, class_type, X, y, labels_std, data_type)\r\n    return scores\r\n\r\n\r\ndef SURF_compute_scores(inst, attr, nan_entries, num_attributes, mcmap, NN, headers, class_type, X, y, labels_std, data_type, weight_flag=0, weights=None):\r\n    \"\"\" Unique scoring procedure for SURF algorithm. Scoring based on nearest neighbors within defined radius of current target instance. \"\"\"\r\n    scores = np.zeros(num_attributes)\r\n    if weight_flag == 2:\r\n        if len(NN) <= 0:\r\n            return scores\r\n        for feature_num in range(num_attributes):\r\n            scores[feature_num] += weights[feature_num]*compute_score(attr, mcmap, NN, feature_num, inst,\r\n                                                                      nan_entries, headers, class_type, X, y, labels_std, data_type)\r\n    else:\r\n        if len(NN) <= 0:\r\n            return scores\r\n        for feature_num in range(num_attributes):\r\n            scores[feature_num] += compute_score(attr, mcmap, NN, feature_num, inst,\r\n                                                 nan_entries, headers, class_type, X, y, labels_std, data_type)\r\n    return scores\r\n\r\n\r\ndef SURFstar_compute_scores(inst, attr, nan_entries, num_attributes, mcmap, NN_near, NN_far, headers, class_type, X, y, labels_std, data_type, weight_flag=0, weights=None):\r\n    \"\"\" Unique scoring procedure for SURFstar algorithm. Scoring based on nearest neighbors within defined radius, as well as\r\n    'anti-scoring' of far instances outside of radius of current target instance\"\"\"\r\n    scores = np.zeros(num_attributes)\r\n    if weight_flag == 2:\r\n        for feature_num in range(num_attributes):\r\n            if len(NN_near) > 0:\r\n                scores[feature_num] += weights[feature_num]*compute_score(attr, mcmap, NN_near, feature_num, inst,\r\n                                                                          nan_entries, headers, class_type, X, y, labels_std, data_type)\r\n            # Note that we are using the near scoring loop in 'compute_score' and then just subtracting it here, in line with original SURF* paper.\r\n            if len(NN_far) > 0:\r\n                scores[feature_num] -= weights[feature_num]*compute_score(attr, mcmap, NN_far, feature_num, inst,\r\n                                                                          nan_entries, headers, class_type, X, y, labels_std, data_type)\r\n    else:\r\n        for feature_num in range(num_attributes):\r\n            if len(NN_near) > 0:\r\n                scores[feature_num] += compute_score(attr, mcmap, NN_near, feature_num, inst,\r\n                                                     nan_entries, headers, class_type, X, y, labels_std, data_type)\r\n            # Note that we are using the near scoring loop in 'compute_score' and then just subtracting it here, in line with original SURF* paper.\r\n            if len(NN_far) > 0:\r\n                scores[feature_num] -= compute_score(attr, mcmap, NN_far, feature_num, inst,\r\n                                                     nan_entries, headers, class_type, X, y, labels_std, data_type)\r\n    return scores\r\n\r\n\r\ndef MultiSURF_compute_scores(inst, attr, nan_entries, num_attributes, mcmap, NN_near, headers, class_type, X, y, labels_std, data_type, weight_flag=0, weights=None):\r\n    \"\"\" Unique scoring procedure for MultiSURF algorithm. Scoring based on 'extreme' nearest neighbors within defined radius of current target instance. \"\"\"\r\n    scores = np.zeros(num_attributes)\r\n    if weight_flag == 2:\r\n        for feature_num in range(num_attributes):\r\n            if len(NN_near) > 0:\r\n                scores[feature_num] += weights[feature_num]*compute_score(attr, mcmap, NN_near, feature_num, inst,\r\n                                                                          nan_entries, headers, class_type, X, y, labels_std, data_type)\r\n    else:\r\n        for feature_num in range(num_attributes):\r\n            if len(NN_near) > 0:\r\n                scores[feature_num] += compute_score(attr, mcmap, NN_near, feature_num, inst,\r\n                                                     nan_entries, headers, class_type, X, y, labels_std, data_type)\r\n\r\n    return scores\r\n\r\n\r\ndef MultiSURFstar_compute_scores(inst, attr, nan_entries, num_attributes, mcmap, NN_near, NN_far, headers, class_type, X, y, labels_std, data_type, weight_flag=0, weights=None):\r\n    \"\"\" Unique scoring procedure for MultiSURFstar algorithm. Scoring based on 'extreme' nearest neighbors within defined radius, as\r\n    well as 'anti-scoring' of extreme far instances defined by outer radius of current target instance. \"\"\"\r\n    scores = np.zeros(num_attributes)\r\n    if weight_flag == 2:\r\n        for feature_num in range(num_attributes):\r\n            if len(NN_near) > 0:\r\n                scores[feature_num] += weights[feature_num]*compute_score(attr, mcmap, NN_near, feature_num, inst,\r\n                                                                          nan_entries, headers, class_type, X, y, labels_std, data_type)\r\n            # Note that we add this term because we used the far scoring above by setting 'near' to False.  This is in line with original MultiSURF* paper.\r\n            if len(NN_far) > 0:\r\n                scores[feature_num] += weights[feature_num]*compute_score(attr, mcmap, NN_far, feature_num, inst,\r\n                                                                          nan_entries, headers, class_type, X, y, labels_std, data_type, near=False)\r\n    else:\r\n        for feature_num in range(num_attributes):\r\n            if len(NN_near) > 0:\r\n                scores[feature_num] += compute_score(attr, mcmap, NN_near, feature_num, inst,\r\n                                                     nan_entries, headers, class_type, X, y, labels_std, data_type)\r\n            # Note that we add this term because we used the far scoring above by setting 'near' to False.  This is in line with original MultiSURF* paper.\r\n            if len(NN_far) > 0:\r\n                scores[feature_num] += compute_score(attr, mcmap, NN_far, feature_num, inst,\r\n                                                     nan_entries, headers, class_type, X, y, labels_std, data_type, near=False)\r\n\r\n    return scores\r\n", "meta": {"hexsha": "b85cccd32bed48c022fab840698e08e6e1313230", "size": 33644, "ext": "py", "lang": "Python", "max_stars_repo_path": "skrebatedev/scoring_utils.py", "max_stars_repo_name": "athril/scikit-rebate", "max_stars_repo_head_hexsha": "bfc8dd6aab9ea7b5a196e318322a938d36723955", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "skrebatedev/scoring_utils.py", "max_issues_repo_name": "athril/scikit-rebate", "max_issues_repo_head_hexsha": "bfc8dd6aab9ea7b5a196e318322a938d36723955", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "skrebatedev/scoring_utils.py", "max_forks_repo_name": "athril/scikit-rebate", "max_forks_repo_head_hexsha": "bfc8dd6aab9ea7b5a196e318322a938d36723955", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.5992438563, "max_line_length": 217, "alphanum_fraction": 0.6007311854, "include": true, "reason": "import numpy", "num_tokens": 6987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041655, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.18945048798577618}}
{"text": "#!/usr/bin/env python3\n\n\n\"\"\"\nMIT License\n\nCopyright (c) 2018 Jiun Yen\n\"\"\"\n\n\n# Imports\nimport os\nimport argparse\nimport numpy as np\nfrom datetime import datetime\nfrom random import sample\nfrom multiprocessing import Pool, cpu_count\nfrom functools import partial\nfrom time import time\n\n# Constants\n_amino_acids_ = 'ARNDCQEGHILKMFPSTWYVXBZUO'\n_aa_set_ = set(_amino_acids_)\n_blank_ = [0 for _ in range(len(_amino_acids_) + 1)]\n_verbose_ = False\n_p_test_ = '../test/'\n_p_data_ = '../data/'\n_cpu_ = cpu_count()\n\n# Functions\ndef composition(sequence):\n\n    # Compute properties\n    sequence = sequence.upper()\n    query_length = len(sequence)\n    mass = 1 / query_length\n\n    query_unique = list(set(sequence) - _aa_set_)\n    if query_unique:\n        print('There are special residues in sequence: %s (ignored during comparison)' % ','.join(query_unique))\n        sequence = ''.join([i for i in sequence if i not in query_unique])\n\n    # Compute composition\n    comp = _blank_.copy()\n    comp[0] = query_length\n    for e in sequence:\n        comp[1 + _amino_acids_.index(e)] += mass\n\n    return comp\n\ndef build_db(p_fasta, p_db=''):\n\n    t0 = time()\n\n    if not p_db:\n        p_db = p_fasta + '.disorderdb'\n\n    if _verbose_:\n        print('Building database from FASTA: %s ...' % p_fasta)\n\n    n_seqs = 0\n    db_comps = []\n    with open(p_fasta, 'r') as fi, open(p_db, 'w+') as fo:\n        seq = ''\n        header = ''\n        for l in fi:\n            if l.startswith('>'):\n                if seq:\n                    comp = composition(seq)\n                    _ = fo.write('%s\\t%d\\t%s\\n' % (header, comp[0], '\\t'.join(['%.6f' % i for i in comp[1:]])))\n                    db_comps.append([header] + comp)\n                    n_seqs += 1\n\n                seq = ''\n                header = l[1:].strip().replace('\\t', ' ')\n\n            else:\n                seq += l.strip()\n\n            if n_seqs % 100 == 0:\n                fo.flush()\n\n        if seq:\n            comp = composition(seq)\n            _ = fo.write('%s\\t%d\\t%s\\n' % (header, comp[0], '\\t'.join(['%.6f' % i for i in comp[1:]])))\n            db_comps.append([header] + comp)\n            n_seqs += 1\n\n    if _verbose_:\n        print('\\tCompleted in %.1f minutes' % ((time() - t0)/60))\n        print('Generated database for %d sequences at %s' % (n_seqs, p_db))\n\n    return p_db, db_comps\n\ndef read_db(p_db):\n\n    db_comps = []\n    with open(p_db, 'r') as f:\n        for l in f:\n            tmp = l.split('\\t')\n            comp = [tmp[0]]\n            comp.append(int(tmp[1]))\n            comp += [float(i) for i in tmp[2:]]\n            db_comps.append(comp)\n\n    return db_comps\n\ndef search(p_query, db_comps, p_out=''):\n\n    t0 = time()\n\n    if not p_out:\n        stamp = 'search-%s-%s.csv' % (datetime.now().strftime('%Y%m%d%H%M%S'), ''.join(sample('ABCDEF', 4)))\n        p_file, _  = os.path.splitext(p_query)\n        p_out = p_file + '_' + stamp\n\n    with open(p_out, 'w+') as f:\n        _ = f.write('Queries,Hits,Distances\\n')\n\n    query_seqs = read_fasta(p_query)\n\n    if _verbose_:\n        print('Searching on %d CPUs ...' % _cpu_)\n\n    for q_header, q_seq in query_seqs.items():\n\n        print('\\tQuery: %s' % q_header)\n\n        query_comp = composition(q_seq)\n\n        with Pool(processes=_cpu_) as pool:\n            res = pool.map(partial(_compare_, q_comp=query_comp), db_comps)\n\n        candidates = {h:d for h,d in res if h}\n\n        candidates_sorted = sorted(candidates.items(), key=lambda x: x[1])\n\n        with open(p_out, 'a') as f:\n\n            for h,d in candidates_sorted:\n                _ = f.write('%s,%s,%.4f\\n' % (q_header, h, d))\n\n    if _verbose_:\n        print('\\tCompleted in %.1f minutes' % ((time() - t0) / 60))\n        print('Search complete, results saved as %s' % p_out)\n\n    return p_out\n\ndef _compare_(t_db_comp, q_comp):\n\n    header = ''\n    dist = 1000.\n\n    if q_comp[0] == t_db_comp[1]:\n        header = t_db_comp[0]\n\n        # Compute Euclidean distance\n        dist = np.linalg.norm(np.array(q_comp[1:]) - np.array(t_db_comp[2:]))\n\n    return header, dist\n\ndef read_fasta(p_fasta):\n\n    sequences = {}\n\n    n_seqs = 0\n    with open(p_fasta, 'r') as f:\n        seq = ''\n        header = ''\n        for l in f:\n            if l.startswith('>'):\n                if seq:\n                    sequences[header] = seq\n                    n_seqs += 1\n\n                seq = ''\n                header = l[1:].strip().replace('\\t',' ')\n\n            else:\n                seq += l.strip()\n\n        if seq:\n            sequences[header] = seq\n            n_seqs += 1\n\n    if _verbose_:\n        print('Found %d sequences in %s' % (n_seqs, p_fasta))\n\n    return sequences\n\n# Run\nif __name__ == '__main__':\n\n    parser = argparse.ArgumentParser(description='Search similar proteins by composition.')\n    parser.add_argument('-i', dest='p_query', default='', help='Query FASTA')\n    parser.add_argument('-fb', dest='p_db_fasta', default='', help='FASTA of database')\n    parser.add_argument('-o', dest='p_out', default='', help='Output file name/path')\n    parser.add_argument('-db', dest='p_db', default='', help='Database name/path')\n    parser.add_argument('-v', dest='verbose', action='store_true', help='To verbose')\n\n    args = parser.parse_args()\n\n    _verbose_ = args.verbose\n\n    if args.p_db_fasta:\n        _, db_comps = build_db(args.p_db_fasta, args.p_db)\n    else:\n        db_comps = read_db(args.p_db)\n\n    if args.p_query:\n        search(args.p_query, db_comps, args.p_out)\n", "meta": {"hexsha": "1be9613eea99e33fca56db418543b64793ac752a", "size": 5472, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/disorderly.py", "max_stars_repo_name": "qks1lver/disorderly", "max_stars_repo_head_hexsha": "bfe462676bd0c0d95e88a10fcd1f47dd7da07381", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/disorderly.py", "max_issues_repo_name": "qks1lver/disorderly", "max_issues_repo_head_hexsha": "bfe462676bd0c0d95e88a10fcd1f47dd7da07381", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/disorderly.py", "max_forks_repo_name": "qks1lver/disorderly", "max_forks_repo_head_hexsha": "bfe462676bd0c0d95e88a10fcd1f47dd7da07381", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8113207547, "max_line_length": 112, "alphanum_fraction": 0.5561038012, "include": true, "reason": "import numpy", "num_tokens": 1489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.18945048798577616}}
{"text": "#!/usr/bin/env python\n#\n# A script topographically correct SAR data using RIOS applier.\n#\n# Dan Clewley (clewley@usc.edu) - 05/02/2013\n#\n# The correction uses:\n#\n# sigma0_norm = sigma0 * (A_flat / A_slope) * (cos(theta_ref) / cos(theta_loc))^n\n#\n# Where n is a parameter related to optical thicknes. Defaults to 1.\n#\n# Castel et al. 2001. Sensitivity of space-borne SAR data to forest parameters over sloping terrain. \n# Theory and experiment. International journal of remote sensing. 22(12) pp. 2351-2376\n#\n# Designed to take outputs of GAMMA:\n# - Sigma0\n# - Normalised pixel area (A_flat / A_slope) '.pix'\n# - Local incidence angle '.inc'\n#\n# Can be run as a stand alone script or from within BatchGamma.py to process\n# multiple files (different polarizations).\n#\n# Copyright 2014 Daniel Clewley. All rights reserved.\n#\n# Permission is hereby granted, free of charge, to any person \n# obtaining a copy of this software and associated documentation \n# files (the \"Software\"), to deal in the Software without restriction, \n# including without limitation the rights to use, copy, modify, \n# merge, publish, distribute, sublicense, and/or sell copies of the \n# Software, and to permit persons to whom the Software is furnished \n# to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be \n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, \n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES \n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. \n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR \n# ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF \n# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION \n# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n#\n\nimport sys\nimport argparse\nfrom rios import applier\nfrom rios import cuiprogress\nimport numpy as np\nimport os, glob\n\nhavescipy = True\n\ntry:\n    from scipy import ndimage\nexcept ImportError:\n    havescipy = False\n\ndef getOutDriver(outFileName):\n    \n    \"\"\" Set output driver type and creation options\n        based on file extension.\n\n        Returns driver name and list of creation options\n        as dictionary.\n    \"\"\"\n\n    outControls = {}\n\n    gdalFormat = 'ENVI'\n    gdalCOOptions = []\n    calcStats = False\n\n    extension = os.path.splitext(outFileName)[-1] \n    if extension == '.kea':\n        gdalFormat = 'KEA'\n        calcStats = True\n    elif extension == '.tif':\n        gdalFormat = 'GTiff'\n        gdalCOOptions = ['COMPRESS=DEFLATE']\n        calcStats = True\n    elif extension == '.img':\n        gdalFormat = 'HFA'\n        gdalCOOptions = ['COMPRESSED=YES']\n        calcStats = True\n    elif extension == '.pix':\n        gdalFormat = 'PCIDSK'\n        gdalCOOptions = ['COMPRESSION=RLE']\n        calcStats = True\n\n    outControls['gdalFormat'] = gdalFormat\n    outControls['gdalCOOptions'] = gdalCOOptions\n    outControls['calcStats'] = gdalCOOptions\n\n    return outControls\n    \n\ndef castelCorrection(info, inputs, outputs, otherargs):\n    \"\"\"\n    Apply topographic correction of Castel et al (2001)\n    \"\"\"\n    theta_ref_deg = otherargs.thetaref\n    nFactor = otherargs.nFactor\n    filterSize = otherargs.filterSize\n    theta_ref = np.deg2rad(theta_ref_deg)\n    insigma=inputs.insigma.astype(np.float32)\n    inpix=inputs.inpix.astype(np.float32)\n    inlinc=inputs.inlinc.astype(np.float32)\n    \n    if havescipy and filterSize is not None:\n        inpix = ndimage.uniform_filter(inpix,size=filterSize)\n        inlinc = ndimage.uniform_filter(inlinc,size=filterSize)\n\n    outputs.outimage = insigma * inpix * (np.cos(theta_ref) / np.cos(inlinc))\n\ndef runCorrection(insigma, inlinc, inpix, outsigma, thetaref=39.0, nFactor=1.0, filterSize=None):\n\n    controls = applier.ApplierControls()\n    \n    # Set up input images\n    infiles = applier.FilenameAssociations()\n    infiles.insigma = insigma\n    infiles.inlinc = inlinc\n    infiles.inpix = inpix\n    \n    # Set up output image\n    outfiles = applier.FilenameAssociations()\n    outfiles.outimage = outsigma\n\n    # Set format for output image\n    outControls = getOutDriver(outsigma)\n\n    # Set options\n    controls.setOutputDriverName(outControls['gdalFormat'])\n    controls.setCreationOptions(outControls['gdalCOOptions'])\n    controls.setCalcStats(outControls['calcStats'])\n\n    # Set up parameters\n    otherargs = applier.OtherInputs()\n    otherargs.thetaref = thetaref\n    otherargs.nFactor = nFactor\n    otherargs.filterSize = filterSize\n    \n    # Run correction\n    controls.progress = cuiprogress.CUIProgressBar()\n    applier.apply(castelCorrection, infiles, outfiles, otherargs, controls=controls)\n\ndef runCorrectionDIR(inDIR, sigmaExt='utm', lincExt='inc', pixExt='pix', outExt='kea', thetaref=39.0, nFactor=1, filterSize=None):\n    \"\"\" Run correction for directory.\n        Finds files based on supplied extension.\n    \"\"\"\n    try:\n        inlinc = glob.glob(inDIR + '/*' + lincExt)[0]\n        inpix = glob.glob(inDIR + '/*' + pixExt)[0]\n    except Exception as err:\n        print(\"Couldn't find local incidence angle or pixel area images, is the extension correct?\")\n        print(err)\n    \n    inSigmaList = glob.glob(inDIR + '/*' + sigmaExt)\n    \n    for insigma in inSigmaList:\n        insigmaBase = os.path.splitext(insigma)[0]\n        outsigma = insigmaBase + '_topo.' + outExt\n        runCorrection(insigma, inlinc, inpix, outsigma, thetaref, nFactor, filterSize)\n\nif __name__ == '__main__':\n\n    # Read in parameters\n       \n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"-i\", \"--insigma\", type=str, required=True, help=\"Input sigma0 file\")\n    parser.add_argument(\"-p\", \"--inpix\", type=str, required=True, help=\"Input pixel area\")\n    parser.add_argument(\"-l\", \"--inlinc\", type=str, required=True, help=\"Input local incidence angle\")\n    parser.add_argument(\"-o\", \"--outsigma\", type=str, required=True, help=\"Output topographically corrected sigma0\")\n    parser.add_argument(\"--thetaref\", type=float, required=False, default=39.0, help=\"Reference incidence angle (default 39)\")\n    parser.add_argument(\"--n\", type=float, required=False, default=1.0, help=\"n parameter (default 1)\")\n    parser.add_argument(\"--filterSize\", type=int, required=False, default=None, help=\"Size of filter to apply to linc and pix data\")\n    args = parser.parse_args()    \n\n    # Run\n    runCorrection(args.insigma, args.inlinc, args.inpix, args.outsigma, args.thetaref, args.n, args.filterSize)\n  \n\n", "meta": {"hexsha": "d9d01ceb1fc503f079fd242bfa6f643d23dad04b", "size": 6579, "ext": "py", "lang": "Python", "max_stars_repo_path": "Gamma/Python/TopoCorrect/topoCorrection.py", "max_stars_repo_name": "petebunting/rsgis_scripts", "max_stars_repo_head_hexsha": "b35b0403cdfad6c63824d4f8c038f190cdb5978d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-09-16T10:45:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-06T04:34:32.000Z", "max_issues_repo_path": "Gamma/Python/TopoCorrect/topoCorrection.py", "max_issues_repo_name": "petebunting/rsgis_scripts", "max_issues_repo_head_hexsha": "b35b0403cdfad6c63824d4f8c038f190cdb5978d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Gamma/Python/TopoCorrect/topoCorrection.py", "max_forks_repo_name": "petebunting/rsgis_scripts", "max_forks_repo_head_hexsha": "b35b0403cdfad6c63824d4f8c038f190cdb5978d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-06T18:03:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T12:45:34.000Z", "avg_line_length": 35.3709677419, "max_line_length": 132, "alphanum_fraction": 0.699498404, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166195971441, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.1894504863880391}}
{"text": "#from phil import *\nfrom sys import exit\nimport math\nfrom os.path import exists\nfrom pathlib import Path\nimport pandas as pd\nimport numpy as np\nfrom . import util\nfrom . import preprocess\nfrom . import imhc_scoring\nfrom . import cd8_scoring\nfrom .tcrdist.all_genes import all_genes\n\n\ncdr3_score_FG = 'fg'\ncdr3_score_CENTER = 'cen'\n\ncdr3_score_modes = [ cdr3_score_FG, cdr3_score_CENTER ]\ndefault_cdr3_score_mode = cdr3_score_FG\n\nfg_trim = 4\ncenter_len = 5\n\naa_props_file = Path.joinpath( Path(util.path_to_data), 'aa_props.tsv')\nassert exists(aa_props_file)\naa_props_df = pd.read_csv(aa_props_file, sep='\\t')\naa_props_df.set_index('aa', inplace=True)\n\n# all_tcr_scorenames = ['alphadist', 'cd8', 'cdr3len', 'imhc', 'mait', 'inkt'] +\\\n#                      [ '{}_{}'.format(x,y) for x in aa_props_df.columns for y in cdr3_score_modes ]\n\n#tmp hacking SIMPLIFY -- dont include info on which version of the loop is used for scoring\nall_tcr_scorenames = ['alphadist', 'cd8', 'cdr3len', 'imhc', 'mait', 'inkt', 'nndists_tcr'] + list(aa_props_df.columns)\n\namino_acids = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', \\\n               'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y']\n\ndef read_cd8_score_params():\n    # setup the scoring params\n    # made by read_flunica_gene_usage_clustermaps*py\n    infofile = Path.joinpath( Path(util.path_to_data), 'cd48_score_params_nomait.txt')\n\n    scoretags = 'cdr3_len cdr3_aa gene'.split()\n\n    all_scorevals = {'A':{}, 'B':{} }\n    for tag in scoretags:\n        all_scorevals['A'][tag] = {}\n        all_scorevals['B'][tag] = {}\n\n\n    min_l2e = -0.6\n    max_l2e = 0.6\n\n    # scores reflect cd8 versus cd4 preference\n\n    for line in open(infofile,'r'):\n        l = line.split()\n        tag = l[0]\n        assert tag.endswith('_cdx_pval:')\n        tag = tag[:-10]\n        key = l[10]\n        if tag[:4] == 'cdr3':\n            ab = tag[4]\n            tag = tag[:4]+tag[5:]\n        else:\n            assert key[:2] == 'TR'\n            ab = key[2]\n        assert tag in scoretags\n        assert l[6] == 'cd4:'\n        cd4_mean = float(l[7])\n        cd8_mean = float(l[9])\n        tot = 0.5*(cd4_mean + cd8_mean)\n        if not tot:\n            l2e = 0.0\n        elif cd8_mean==0:\n            l2e = min_l2e\n        else:\n            l2e = max( min_l2e, min( max_l2e, math.log( cd8_mean / tot, 2.0 ) ) )\n\n        all_scorevals[ab][tag][key] = l2e\n        #print '{:7.3f} {} {} {}'.format(l2e,ab,tag,key)\n    return all_scorevals\n\nall_scorevals = read_cd8_score_params()\n\ndef cd8_score_tcr_chain( ab, v, j, cdr3 ):\n    global all_scorevals\n\n    cdr3_len_ranges = { 'A': ( min( int(x) for x in all_scorevals['A']['cdr3_len'] ),\n                               max( int(x) for x in all_scorevals['A']['cdr3_len'] ) ),\n                        'B': ( min( int(x) for x in all_scorevals['B']['cdr3_len'] ),\n                               max( int(x) for x in all_scorevals['B']['cdr3_len'] ) ) }\n\n    assert ab in 'AB'\n    if '-' in v:\n        v = v[:v.index('-')]\n    if '-' in j:\n        j = j[:j.index('-')]\n    v_score = all_scorevals[ab]['gene'].get(v,0.0)\n    j_score = all_scorevals[ab]['gene'].get(j,0.0)\n    mn,mx = cdr3_len_ranges[ab]\n    L = max( mn, min( mx, len(cdr3) ) )\n    cdr3_len_score = all_scorevals[ab]['cdr3_len'][str(L)]\n    cdr3_aa_score = 0.0\n    if L>8:\n        for aa in cdr3[4:-4]:\n            cdr3_aa_score += all_scorevals[ab]['cdr3_aa'][aa]\n    score = v_score + j_score + cdr3_len_score + cdr3_aa_score\n\n    return ( score, v_score, j_score, cdr3_len_score, cdr3_aa_score )\n\ndef old_imhc_score_cdr3( cdr3 ): # cdr3 is untrimmed!\n    '''This is the old version of the score, \"fit\" by staring at the sequences a little bit\n    '''\n    if len(cdr3) <= 8:\n        return 0\n    fgloop = cdr3[4:-4]\n    return ( len(fgloop) + 3.0 * fgloop.count('C') + 2.0 * fgloop.count('W') + fgloop.count('R') + fgloop.count('K')\n             + 0.5*fgloop.count('H') - fgloop.count('D') - fgloop.count('E') )\n\ndef old_imhc_score_tcr( tcr ):\n    '''This is the old version of the score, \"fit\" by staring at the sequences a little bit\n    '''\n    return old_imhc_score_cdr3( tcr[0][2] ) + 2*old_imhc_score_cdr3( tcr[1][2] ) # double-weight the beta CDR3\n\n\ndef cd8_score_tcr( tcr ):\n    atcr, btcr = tcr\n    return ( cd8_score_tcr_chain( 'A', atcr[0], atcr[1], atcr[2] )[0] +\n             cd8_score_tcr_chain( 'B', btcr[0], btcr[1], btcr[2] )[0] )\n\ndef is_human_mait_alpha_chain(atcr):\n    return ( atcr[0].startswith('TRAV1-2') and\n             ( atcr[1].startswith('TRAJ33') or\n               atcr[1].startswith('TRAJ20') or\n               atcr[1].startswith('TRAJ12') ) and\n             len(atcr[2]) == 12 )\n\ndef is_mouse_mait_alpha_chain(atcr):\n    return ( atcr[0].startswith('TRAV1-') and atcr[1].startswith('TRAJ33') and len(atcr[2]) == 12 )\n\ndef is_mouse_inkt_alpha_chain(atcr):\n    return ( atcr[0].startswith('TRAV11') and atcr[1].startswith('TRAJ18') and len(atcr[2]) == 15 )\n\ndef is_human_inkt_tcr(tcr):\n    # could also put some limits on cdr3s?\n    return ( tcr[0][0].startswith('TRAV10') and\n             tcr[0][1].startswith('TRAJ18') and\n             len(tcr[0][2]) in [14,15,16] and  # 15 seems to be the consensus\n             tcr[1][0].startswith('TRBV25') )\n\n\ndef mait_score_tcr(tcr, organism):\n    if 'human' in organism:\n        return float(is_human_mait_alpha_chain(tcr[0]))\n\n    elif 'mouse' in organism:\n        return float(is_mouse_mait_alpha_chain(tcr[0]))\n\n    else:\n        print('unrecognized organism:', organism)\n        exit()\n        return 0.\n\n\ndef inkt_score_tcr(tcr, organism):\n    if 'human' in organism:\n        return float(is_human_inkt_tcr(tcr))\n\n    elif 'mouse' in organism:\n        return float(is_mouse_inkt_alpha_chain(tcr[0]))\n\n    else:\n        print('unrecognized organism:', organism)\n        exit()\n        return 0.\n\n\ndef read_locus_order( remove_slashes_from_gene_names= False ):\n    ''' returns  all_locus_order:  all_locus_order[ab][gene] = int(l[1])\n    '''\n    # read the gene order from imgt\n    all_locus_order = {'A':{}, 'B':{}}\n    for ab in 'AB':\n        fn = f'imgt_tr{ab.lower()}_locus_order.txt'\n        filename = Path.joinpath( Path( util.path_to_data ), fn)\n        assert exists(filename)\n        for line in open(filename,'r'):\n            l = line.split()\n            if l[0] == 'IMGT':continue\n            assert len(l) in [2,3]\n            gene = l[0]\n            if '/' in gene and remove_slashes_from_gene_names:\n                print( 'remove /',gene)\n                gene = gene.replace('/','')\n            all_locus_order[ab][gene] = int(l[1])\n    return all_locus_order\n\nall_locus_order = read_locus_order()\n\ntrav_list = [ x[1] for x in sorted( (y,x) for x,y in all_locus_order['A'].items() if x[:4] == 'TRAV' ) ]\ntraj_list = [ x[1] for x in sorted( (y,x) for x,y in all_locus_order['A'].items() if x[:4] == 'TRAJ' ) ]\n\n\ndef alphadist_score_tcr( tcr ):\n    global trav_list\n    global traj_list\n    va, ja = tcr[0][:2]\n    # print(va)\n    # print(ja)\n    if \"-\" in va :\n        va = va[:va.index('-')]\n    if \"-\" in ja :\n        ja = ja[:ja.index('-')]\n    if va in trav_list:\n        va_dist = len(trav_list)-1 -trav_list.index(va)\n    else:\n        #print('alphadist_score_tcr: unrecognized va:', va)\n        va_dist = 0.5*(len(trav_list)-1)\n\n    if ja in traj_list:\n        ja_dist = traj_list.index(ja)\n    else:\n        #print('alphadist_score_tcr: unrecognized ja:', ja)\n        ja_dist = 0.5*(len(traj_list)-1)\n    return va_dist + ja_dist\n\ndef cdr3len_score_tcr(tcr):\n    ''' double-weight the beta chain\n    '''\n    return len(tcr[0][2]) + 2*len(tcr[1][2])\n\n\n\ndef property_score_cdr3(cdr3, score_name, score_mode):\n    ''' Currently averages the score over the number of aas scores\n    '''\n    global aa_props_df\n    global cdr3_score_CENTER\n    global cdr3_score_FG\n    global fg_trim\n    global center_len\n\n    col = aa_props_df[score_name]\n\n    if score_mode == cdr3_score_CENTER:\n        cdr3 = cdr3[1:] # trim off the first 'C', makes structurally symmetric\n        if len(cdr3)<center_len:\n            return np.mean(col)\n        else:\n            ntrim = (len(cdr3)-center_len)//2\n            return sum(col[aa] for aa in cdr3[ntrim:ntrim+center_len])/center_len\n\n    elif score_mode == cdr3_score_FG:\n        fgloop = cdr3[fg_trim:-fg_trim]\n        if fgloop:\n            return sum( col[aa] for aa in fgloop )/len(fgloop)\n        else:\n            return np.mean(col) # was returning 0 here; prob should use aa-frequency-weighted average...\n    else:\n        print( 'property_score_cdr3:: unrecognized score_mode:', score_mode)\n        exit()\n        return 0.0\n\ndef property_score_tcr(tcr, score_name, score_mode, alpha_weight=1.0, beta_weight=1.0):\n    return ( alpha_weight * property_score_cdr3(tcr[0][2], score_name, score_mode ) +\n             beta_weight  * property_score_cdr3(tcr[1][2], score_name, score_mode ) )\n\n\ndef make_tcr_score_table(adata, scorenames):\n    ''' Returns an array of the tcr scores of shape: (adata.shape[0], len(scorenames))\n    '''\n    global aa_props_df\n    organism = adata.uns['organism']\n\n    tcrs = preprocess.retrieve_tcrs_from_adata(adata)\n    clusters_tcr = np.array(adata.obs['clusters_tcr'])\n\n    organism_genes = all_genes[organism]\n    genes = frozenset( organism_genes.keys())\n    count_reps = frozenset( [ x.count_rep for x in organism_genes.values() ] )\n\n    cols = []\n    for name in scorenames:\n        if name == 'cdr3len':\n            cols.append( [ cdr3len_score_tcr(x) for x in tcrs ])\n        elif name.startswith('tcr_cluster'):\n            num = int(name[11:])\n            cols.append( [ float(x==num) for x in clusters_tcr])\n        elif name == 'alphadist':\n            cols.append( [ alphadist_score_tcr(x) for x in tcrs ])\n        elif name == 'oldcd8':# the 'old' cd8 score\n            cols.append( [ cd8_score_tcr(x) for x in tcrs ])\n        elif name == 'cd8': # see comparison between old/new in cd8_scoring.py\n            cols.append(cd8_scoring.make_cd8_score_table_column(tcrs))\n        elif name == 'old_imhc':\n            cols.append( [ old_imhc_score_tcr(x) for x in tcrs ])\n        elif name == 'imhc':\n            cols.append( imhc_scoring.make_imhc_score_table_column(tcrs, aa_props_df))\n        elif name == 'mait':\n            organism = adata.uns['organism']\n            cols.append( [ mait_score_tcr(x, organism) for x in tcrs ])\n        elif name == 'inkt':\n            organism = adata.uns['organism']\n            cols.append( [ inkt_score_tcr(x, organism) for x in tcrs ])\n        elif name == 'nndists_tcr':\n            if 'nndists_tcr' not in adata.obs_keys():\n                print('WARNING nndists_tcr score requested but not present in adata.obs!!!!')\n                cols.append( np.zeros( adata.shape[0] ) )\n            else:\n                cols.append( np.array(adata.obs['nndists_tcr']) )\n        elif name == 'N_ins': # number of N insertions\n            if 'N_ins' not in adata.obs_keys():\n                print('WARNING N_ins requested but not present in adata.obs!!!!')\n                cols.append( np.zeros( adata.shape[0] ) )\n            else:\n                cols.append( np.array(adata.obs['N_ins']).astype(float) )\n        elif name in genes:\n            matched = False\n            for i_ab,ab in enumerate('AB'):\n                for i_vj,vj in enumerate('VJ'):\n                    ii_genes = set([x for x,y in organism_genes.items() if y.chain==ab and y.region==vj ])\n                    if name in ii_genes:\n                        assert not matched\n                        matched = True\n                        cols.append( [float(x[i_ab][i_vj]==name) for x in tcrs])\n            assert matched\n\n        elif name in count_reps:\n            matched = False\n            for i_ab,ab in enumerate('AB'):\n                for i_vj,vj in enumerate('VJ'):\n                    ii_count_reps = set([x.count_rep for x in organism_genes.values() if x.chain==ab and x.region==vj ])\n                    if name in ii_count_reps:\n                        assert not matched\n                        matched = True\n                        cols.append( [float(organism_genes[x[i_ab][i_vj]].count_rep==name) for x in tcrs])\n            assert matched\n\n        else:\n            score_mode = name.split('_')[-1]\n            score_name = '_'.join( name.split('_')[:-1])\n            if score_mode not in cdr3_score_modes:\n                score_mode = default_cdr3_score_mode\n                score_name = name\n            cols.append( [ property_score_tcr(x, score_name, score_mode) for x in tcrs ] )\n    table = np.array(cols).transpose()#[:,np.newaxis]\n    #print( table.shape, (adata.shape[0], len(scorenames)) )\n    assert table.shape == (adata.shape[0], len(scorenames))\n\n    return table\n\n", "meta": {"hexsha": "0c75d16a5348f52fc2c6410258f0792c91181876", "size": 12717, "ext": "py", "lang": "Python", "max_stars_repo_path": "conga/tcr_scoring.py", "max_stars_repo_name": "nealpsmith/conga", "max_stars_repo_head_hexsha": "a28566e25e939749a4e31c51c0443f4eea0f5557", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "conga/tcr_scoring.py", "max_issues_repo_name": "nealpsmith/conga", "max_issues_repo_head_hexsha": "a28566e25e939749a4e31c51c0443f4eea0f5557", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conga/tcr_scoring.py", "max_forks_repo_name": "nealpsmith/conga", "max_forks_repo_head_hexsha": "a28566e25e939749a4e31c51c0443f4eea0f5557", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0254957507, "max_line_length": 120, "alphanum_fraction": 0.586852245, "include": true, "reason": "import numpy", "num_tokens": 3712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.511716619597144, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.18945048638803905}}
{"text": "#!/usr/bin/env python\n\n\"\"\"skynet.py: Image segnemtation algoritm for Solar Disk: SkyNet\"\"\"\n\n__author__ = \"Chakraborty, S.\"\n__copyright__ = \"\"\n__credits__ = []\n__license__ = \"MIT\"\n__version__ = \"1.0.\"\n__maintainer__ = \"Chakraborty, S.\"\n__email__ = \"shibaji7@vt.edu\"\n__status__ = \"Research\"\n\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl    \nfrom dateutil import parser as prs\nimport pandas as pd\nimport datetime as dt\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nfrom torch.autograd import Variable\nimport cv2\nimport sys\nimport numpy as np\nimport torch.nn.init\nimport random\nimport os\nimport json\n\n_params_ = {\n    \"_desc\": \"PyTorch Unsupervised Segmentation\",\n    \"nChannel\": \"Number of channels\",\n    \"maxIter\": \"Number of maximum iterations\",\n    \"minLabels\": \"Minimum number of labels\",\n    \"lr\": \"Learning rate\",\n    \"nConv\": \"Number of convolutional layers\",\n    \"nConv\": \"Number of convolutional layers\",\n    \"stepsize_sim\": \"Step size for similarity loss\",\n    \"stepsize_con\": \"Step size for continuity loss\",\n}\n\nimport astropy.units as u\nfrom sunpy.net import Fido, attrs\nimport sunpy.map\nfrom aiapy.calibrate import register, update_pointing, normalize_exposure\n\nimport matplotlib.pyplot as plt\nimport cv2\nimport os\n\nclass RegisterAIA(object):\n    \n    def __init__(self, date, wavelength=193, resolution=1024, vmin=10):\n        self.wavelength = wavelength\n        self.date = date\n        self.resolution = resolution\n        self.vmin = vmin\n        self.folder = \"data/SDO-Database/{:4d}.{:02d}.{:02d}/{:04d}/{:03d}/\".format(self.date.year, self.date.month, self.date.day,\n                                                                             self.resolution, self.wavelength)\n        self.fname = \"{:4d}_{:02d}_{:02d}_{:02d}{:02d}{:02d}.png\".format(self.date.year, self.date.month,\n                                                                         self.date.day, self.date.hour,\n                                                                         self.date.minute, self.date.second)\n        if not os.path.exists(self.folder): os.system(\"mkdir -p \" + self.folder)\n        if not os.path.exists(self.folder + self.fname):\n            self.normalized()\n            self.to_png()\n        return\n    \n    def normalized(self):\n        q = Fido.search(\n            attrs.Time(self.date.strftime(\"%Y-%m-%dT%H:%M:%S\"), (self.date + dt.timedelta(seconds=11)).strftime(\"%Y-%m-%dT%H:%M:%S\")),\n            attrs.Instrument(\"AIA\"),\n            attrs.Wavelength(wavemin=self.wavelength*u.angstrom, wavemax=self.wavelength*u.angstrom),\n        )\n        self.m = sunpy.map.Map(Fido.fetch(q[0,0]))\n        m_updated_pointing = update_pointing(self.m)\n        m_registered = register(m_updated_pointing)\n        self.m_normalized = normalize_exposure(m_registered)\n        return\n    \n    def to_png(self):\n        norm, m = self.m_normalized, self.m\n        fig, ax = plt.subplots(nrows=1,ncols=1,dpi=100,figsize=(2048/100, 2048/100))\n        norm.plot(annotate=False, axes=ax, vmin=self.vmin)\n        ax.set_xticks([])\n        ax.set_yticks([])\n        fig.savefig(\"tmp.png\",bbox_inches=\"tight\")\n        im = cv2.imread(\"tmp.png\")\n        im = im[10:-10,10:-10]\n        im = cv2.resize(im, (self.resolution, self.resolution))\n        os.remove(\"tmp.png\")\n        cv2.imwrite(self.folder + self.fname, im)\n        return\n\n# CNN model\nclass SkyNet(nn.Module):\n    \n    def __init__(self, input_dim, params):\n        super(SkyNet, self).__init__()\n        self.params = params\n        self.conv1 = nn.Conv2d(input_dim, self.params.nChannel, kernel_size=3, stride=1, padding=1 )\n        self.bn1 = nn.BatchNorm2d(self.params.nChannel)\n        self.conv2 = nn.ModuleList()\n        self.bn2 = nn.ModuleList()\n        for i in range(args.nConv-1):\n            self.conv2.append( nn.Conv2d(self.params.nChannel, self.params.nChannel, kernel_size=3, stride=1, padding=1 ) )\n            self.bn2.append( nn.BatchNorm2d(self.params.nChannel) )\n        self.conv3 = nn.Conv2d(self.params.nChannel, self.params.nChannel, kernel_size=1, stride=1, padding=0 )\n        self.bn3 = nn.BatchNorm2d(self.params.nChannel)\n        return\n\n    def forward(self, x):\n        x = self.conv1(x)\n        x = F.relu( x )\n        x = self.bn1(x)\n        for i in range(self.params.nConv-1):\n            x = self.conv2[i](x)\n            x = F.relu( x )\n            x = self.bn2[i](x)\n        x = self.conv3(x)\n        x = self.bn3(x)\n        return x\n\nclass Loader(object):\n    \n    def __init__(self, fname, folder, date, params, save=True, cfg_file = \"data/config/{:3d}.json\"):\n        self.fname = fname\n        self.folder = folder\n        self.setup(cfg_file, params)\n        self.date = date        \n        self.params = params\n        self.resolution = params.resolution\n        self.wavelength = params.wavelength\n        self.save = save\n        self.extn = \".\" + fname.split(\".\")[-1]\n        self.use_cuda = torch.cuda.is_available()\n        self.detect_hough_circles()\n        self.im = cv2.imread(self.folder + self.fname)\n        self.data = torch.from_numpy( np.array([self.im.transpose( (2, 0, 1) ).astype(\"float32\")/255.]) )\n        if self.use_cuda: self.data = self.data.cuda()\n        self.data = Variable(self.data)\n        return\n    \n    def rescale(self, img, to):\n        \"\"\" Resacle the images \"\"\"\n        dsize = (to, to)\n        img = cv2.resize(img, dsize)\n        return img\n    \n    def setup(self, cfg_file, params):\n        \"\"\" Load parameters \"\"\"\n        _dict_ = {}\n        for k in vars(params).keys():\n            _dict_[k] = vars(args)[k]\n        cfg_file = cfg_file.format(_dict_[\"wavelength\"])\n        with open(cfg_file, \"r\") as fp:\n            dic = json.load(fp)\n            for p in dic.keys():\n                if not hasattr(self, p): setattr(self, p, dic[p])\n        for p in _dict_.keys():\n            setattr(self, p, _dict_[p])\n        self._dict_ = _dict_\n        mult = int(self.resolution/512) + 0.5\n        self.prims = np.array(self.prims) * mult\n        self.delta = int(self.resolution/128)\n        \n        self.images = {}\n        self.images[\"src\"] = cv2.imread(cv2.samples.findFile(self.folder+self.fname), cv2.IMREAD_COLOR)\n        self.img_params = {\"resolution\": self.images[\"src\"].shape[0]}\n        self.images[\"src\"] = self.rescale(self.images[\"src\"], self.resolution)\n        self.images[\"org\"] = np.copy(cv2.cvtColor(self.images[\"src\"], cv2.COLOR_BGR2RGB))            \n        self.images[\"prob_masked_gray_image\"], self.images[\"prob_masked_image\"] =\\\n        np.zeros_like(self.images[\"src\"]), np.copy(self.images[\"src\"])\n        self.images[\"gray\"] = cv2.cvtColor(self.images[\"src\"], cv2.COLOR_BGR2GRAY)\n        self.images[\"contours\"] = np.zeros_like(self.images[\"gray\"])\n        self.images[\"contour_maps\"] = np.zeros_like(self.images[\"gray\"])\n        self.images[\"bin_map\"] = np.zeros_like(self.images[\"gray\"])\n        self.images[\"hc_mask\"] = np.zeros_like(self.images[\"gray\"])\n        self.images[\"prob_masked_image_ol\"] = np.copy(self.images[\"src\"])\n        return\n    \n    def detect_hough_circles(self):\n        \"\"\" Detecting the Hough Circles \"\"\"\n        gray = np.copy(self.images[\"gray\"])\n        rows = self.resolution\n        circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, rows / 8,\n                                   param1=self.hc_param1, param2=self.hc_param2,\n                                   minRadius=int(rows/3), maxRadius=int(rows/2))\n        if circles is not None:\n            circles = np.uint16(np.around(circles))\n            radi = int(rows/2)\n            for i in circles[0, :]:\n                if radi - self.alpha <= i[0] <= radi + self.alpha and radi - self.alpha <= i[1] <= radi + self.alpha:\n                    self.center = (i[0], i[1])\n                    self.radius = i[2]\n                    self.create_hc_mask()\n        return\n    \n    def create_hc_mask(self):\n        # HC mask create\n        mask = cv2.circle(self.images[\"hc_mask\"], self.center, self.radius, 255, -1)\n        self.images[\"hc_mask\"] = mask\n        self.NzC = np.count_nonzero(mask)\n        return\n    \n    def load_model(self):\n        # Load & train model\n        self.model = SkyNet( self.data.size(1), self.params)\n        if self.use_cuda: self.model.cuda()\n        self.model.train()\n        self.loss_fn = torch.nn.CrossEntropyLoss()\n        # scribble loss definition\n        loss_fn_scr = torch.nn.CrossEntropyLoss()\n        # continuity loss definition\n        self.loss_hpy = torch.nn.L1Loss(size_average = True)\n        self.loss_hpz = torch.nn.L1Loss(size_average = True)\n\n        self.HPy_target = torch.zeros(self.im.shape[0]-1, self.im.shape[1], self.params.nChannel)\n        self.HPz_target = torch.zeros(self.im.shape[0], self.im.shape[1]-1, self.params.nChannel)\n        if self.use_cuda: self.HPy_target, self.HPz_target = self.HPy_target.cuda(), self.HPz_target.cuda()\n        self.optimizer = optim.SGD(self.model.parameters(), lr=args.lr, momentum=0.9)\n        self.label_colours = np.random.randint(255, size=(100,3))\n        return self\n    \n    def run_forwarding(self):\n        if not os.path.exists(self.folder + self.fname.replace(self.extn, \"_seg\" + self.extn)):\n            for batch_idx in range(self.params.maxIter):\n                self.optimizer.zero_grad()\n                self.output = self.model( self.data )[ 0 ]\n                self.output = self.output.permute( 1, 2, 0 ).contiguous().view( -1, self.params.nChannel )\n\n                self.outputHP = self.output.reshape( (self.im.shape[0], self.im.shape[1], self.params.nChannel) )\n                self.HPy = self.outputHP[1:, :, :] - self.outputHP[0:-1, :, :]\n                self.HPz = self.outputHP[:, 1:, :] - self.outputHP[:, 0:-1, :]\n                self.lhpy = self.loss_hpy(self.HPy, self.HPy_target)\n                self.lhpz = self.loss_hpz(self.HPz, self.HPz_target)\n\n                ignore, target = torch.max( self.output, 1 )\n                im_target = target.data.cpu().numpy()\n                nLabels = len(np.unique(im_target))\n                self.loss = self.params.stepsize_sim * self.loss_fn(self.output, target) + self.params.stepsize_con * (self.lhpy + self.lhpz)\n                self.loss.backward()\n                self.optimizer.step()\n                print (batch_idx, \"/\", self.params.maxIter, \"|\", \" label num :\", nLabels, \" | loss : %.2f\"%self.loss.item())\n                if nLabels <= self.params.minLabels or self.params.los > self.loss: \n                    print (\" >> nLabels:\", nLabels, \" reached minLabels:\", self.params.minLabels, \" with loss: %.2f.\"%self.loss.item())\n                    break\n        return self\n    \n    def save_outputs(self):\n        if not os.path.exists(self.folder + self.fname.replace(self.extn, \"_seg\" + self.extn)):\n            output = self.model(self.data)[0]\n            output = output.permute(1, 2, 0).contiguous().view(-1, self.params.nChannel)\n            ignore, target = torch.max(output, 1)\n            self.im_target = target.data.cpu().numpy()\n            self.unique_targets = np.array([self.label_colours[c % 100] for c in np.unique(self.im_target)])\n            self.im_target_rgb = np.array([self.label_colours[c % 100] for c in self.im_target])\n            self.im_target_rgb = self.im_target_rgb.reshape(self.im.shape).astype(np.uint8)\n            cv2.imwrite(self.folder + self.fname.replace(self.extn, \"_seg\" + self.extn), self.im_target_rgb)\n        return self\n    \n    def check_intensity(self, mask):\n        # Check the intensity bound on the output\n        ints = False\n        gray = np.copy(self.images[\"gray\"])\n        gray = cv2.bitwise_and(gray, gray, mask=mask)\n        if np.quantile(gray.ravel(), 0.05) >= 0 and np.quantile(gray.ravel(), 0.95) <= 100: ints = True\n        return ints\n    \n    def estimate_CHB(self):\n        if not os.path.exists(self.folder + self.fname.replace(self.extn, \"_msk\" + self.extn)):\n            maskList = []\n            for targ in self.unique_targets:\n                mask = cv2.inRange(self.im_target_rgb, targ-1, targ+1)\n                mask = cv2.bitwise_and(mask, mask, mask=self.images[\"hc_mask\"])\n                if np.count_nonzero(mask) < 0.1*self.NzC and self.check_intensity(mask):\n                    maskList.append(mask)\n            self.totalmask = np.array(maskList).sum(axis=0)\n            cv2.imwrite(self.folder + self.fname.replace(self.extn, \"_msk\" + self.extn), self.totalmask)\n        else:\n            fname = self.folder + self.fname.replace(self.extn, \"_msk\" + self.extn)\n            self.totalmask = cv2.cvtColor(cv2.imread(fname, cv2.IMREAD_COLOR), cv2.COLOR_BGR2GRAY)\n        return self\n    \n    def rescale_prob(self, prob, l=0., u=0.5):\n        prob = prob*(u-l) + l\n        return prob\n    \n    def calculate_probabilistic_boundaries(self):\n        self.contours, self.hierarchy = cv2.findContours((255-self.totalmask).astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n        for ix in range(len(self.contours)):\n            if ix > 0: self.draw_contour(self.contours[int(ix)], self.images[\"prob_masked_image\"])\n        cv2.imwrite(self.folder + self.fname.replace(self.extn, \"_stg0.0_out\" + self.extn), self.images[\"prob_masked_image\"])\n        gray, mask = np.copy(self.images[\"gray\"]), np.zeros_like(self.images[\"gray\"])\n        contours = self.contours[1:]\n        cv2.drawContours(mask, contours, -1, 255, -1); mask = cv2.bitwise_and(gray, gray, mask=mask)\n        maskplot = np.copy(mask)\n        cv2.imwrite(self.folder + self.fname.replace(self.extn, \"_stg0.1_out\" + self.extn), mask)\n        thds = [16, 24, 32, 48, 64, 96, 128, 255]\n        linked_list = []\n        for td in thds:\n            masked = np.zeros_like(mask)\n            masked[mask <= td] = 255\n            masked = cv2.bitwise_and(masked, masked, mask=mask)\n            blurs = cv2.blur((255 - masked).astype(np.uint8), (3, 3))\n            contours, hierarchy = cv2.findContours(blurs, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n            for ix in range(len(contours)):\n                if ix > 0 and hierarchy[0,ix,3] == 0:\n                    cimg = np.zeros_like(gray)\n                    cv2.drawContours(cimg, contours, int(ix), color=255, thickness=-1)\n                    pts = np.where(cimg == 255)\n                    intensity = self.intensity_threshold-gray[pts[0], pts[1]].ravel().astype(int)\n                    prob = 1-np.mean(1./(1.+np.exp(intensity)))\n                    colw = np.array([255,255,255])\n                    #print(td, \"->\", prob)\n                    linked_list.append({\"prob\":prob, \"color\":255*prob, \"contour\":contours[int(ix)]})\n                    cv2.drawContours(maskplot, contours, int(ix), color=255*prob, thickness=1)\n                    self.draw_contour(contours[int(ix)], self.images[\"prob_masked_image_ol\"], col=tuple(colw*prob), line_thick=1)\n            cv2.imwrite(self.folder + self.fname.replace(self.extn, \"_stg0.2.%03d_out\" + self.extn)%td, masked)\n        cv2.imwrite(self.folder + self.fname.replace(self.extn, \"_stg1.0_out\" + self.extn), self.images[\"prob_masked_image_ol\"])\n        maskplot = cv2.cvtColor(maskplot, cv2.COLOR_GRAY2RGB)\n        maskplot = cv2.applyColorMap(maskplot, cv2.COLORMAP_JET)\n        cv2.imwrite(self.folder + self.fname.replace(self.extn, \"_stg1.1_out\" + self.extn), maskplot)\n        self.plot_image_dev(self.images[\"prob_masked_image_ol\"], linked_list)\n        self.plot_image_dev(maskplot, linked_list, cmap=mpl.cm.jet, ext=\"_cb_jet\")\n        return self\n    \n    def plot_image_dev(self, image, objs, shape=(15,14), cmap=mpl.cm.gray, ext=\"_cb_gray\"):\n        df = pd.DataFrame.from_records(objs)[[\"prob\",\"color\"]]\n        fig = plt.figure(figsize=(4, 4), dpi=180)\n        ax = plt.subplot2grid(shape, (0,0), rowspan=shape[0]-2, colspan=shape[0]-2)\n        ax.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\n        ax.set_xticks([])\n        ax.set_yticks([])\n        norm = mpl.colors.Normalize(vmin=0, vmax=1)\n        ax = plt.subplot2grid(shape, (2,shape[0]-2), rowspan=9, colspan=1)\n        cb1 = mpl.colorbar.ColorbarBase(ax, cmap=cmap,\n                                        norm=norm,\n                                        orientation=\"vertical\")\n        cb1.set_label(\"Pr(CH)\")\n        fig.savefig(self.folder + self.fname.replace(self.extn, ext + self.extn), bbox_inches=\"tight\")\n        return\n    \n    def draw_contour(self, contour, img, gray=False, col=None, line_thick=None):\n        if line_thick is None: line_thick = self.draw_param[\"contur\"][\"thick\"]\n        if col is None: col=tuple(self.draw_param[\"contur\"][\"color\"])\n        for _x in range(contour.shape[0]-1):\n            if gray: cv2.line(img, (contour[_x,0,0], contour[_x,0,1]), (contour[_x+1,0,0], contour[_x+1,0,1]), (255,255,255), line_thick)\n            else: cv2.line(img, (contour[_x,0,0], contour[_x,0,1]), (contour[_x+1,0,0], contour[_x+1,0,1]), col, line_thick)\n        if gray: cv2.line(img, (contour[0,0,0], contour[0,0,1]), (contour[-1,0,0], contour[-1,0,1]), (255,255,255), line_thick)\n        else: cv2.line(img, (contour[0,0,0], contour[0,0,1]), (contour[-1,0,0], contour[-1,0,1]),  col, line_thick)\n        return\n    \n    def save_files_outputs(self):\n        return self\n\ndef run_skynet(args, save=True):\n    aia = RegisterAIA(args.date, args.wavelength, args.resolution, vmin=10)\n    load = Loader(aia.fname, aia.folder, args.date, args, save)\n    load.load_model().run_forwarding().save_outputs().estimate_CHB()\n    load.calculate_probabilistic_boundaries()\n    if save: load.save_files_outputs()\n    return\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(description=\"PyTorch Unsupervised Segmentation\")\n    parser.add_argument(\"-dn\", \"--date\", default=dt.datetime(2018,5,30,12), help=\"Date [2018,5,30,12]\", type=prs.parse)\n    parser.add_argument(\"-r\", \"--resolution\", default=1024, help=\"Resolution of the files [1024]\", type=int)\n    parser.add_argument(\"-w\", \"--wavelength\", default=193, help=\"Wavelength of the files [193]\", type=int)\n    parser.add_argument(\"--nChannel\", metavar=\"N\", default=50, type=int, help=\"number of channels\")\n    parser.add_argument(\"--maxIter\", metavar=\"T\", default=100, type=int, help=\"number of maximum iterations\")\n    parser.add_argument(\"--minLabels\", metavar=\"minL\", default=3, type=int, help=\"minimum number of labels\")\n    parser.add_argument(\"--lr\", metavar=\"LR\", default=0.3, type=float, help=\"learning rate\")\n    parser.add_argument(\"--nConv\", metavar=\"M\", default=2, type=int, help=\"number of convolutional layers\")\n    parser.add_argument(\"--stepsize_sim\", metavar=\"SIM\", default=1, type=float, help=\"step size for similarity loss\", required=False)\n    parser.add_argument(\"--stepsize_con\", metavar=\"CON\", default=1, type=float, help=\"step size for continuity loss\")\n    parser.add_argument(\"--los\", metavar=\"LOS\", default=.1, type=float, help=\"Final loss value\")\n    args = parser.parse_args()\n    print(\"\\n Parameter list for SkyNet simulation \")\n    for k in vars(args).keys():\n        print(\"     \" + k + \"->\" + str(vars(args)[k]))\n    run_skynet(args)\n", "meta": {"hexsha": "0dcb4b1ac0e12b9497901e7590f0fcb1cf68ac17", "size": 19146, "ext": "py", "lang": "Python", "max_stars_repo_path": "core/skynet.py", "max_stars_repo_name": "shibaji7/ISWAT_CV", "max_stars_repo_head_hexsha": "6239f021b597b66bca213cbc28ad7185f566c0f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-30T14:18:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-30T14:18:49.000Z", "max_issues_repo_path": "core/skynet.py", "max_issues_repo_name": "shibaji7/ISWAT_CV", "max_issues_repo_head_hexsha": "6239f021b597b66bca213cbc28ad7185f566c0f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core/skynet.py", "max_forks_repo_name": "shibaji7/ISWAT_CV", "max_forks_repo_head_hexsha": "6239f021b597b66bca213cbc28ad7185f566c0f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.4728682171, "max_line_length": 141, "alphanum_fraction": 0.6054528361, "include": true, "reason": "import numpy,import astropy", "num_tokens": 4936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.370225399544253, "lm_q1q2_score": 0.18945048443002818}}
{"text": "\"\"\"\ngc.head() offers functions for calling specific simulation scenarios and\nproducing plots and processed data files from the simulation results. Contains\nfunctionality better suited for smaller as well as larger simulations as well\nas evaluations of specific parameter changes or vaccination scenarios.\n\"\"\"\n\nfrom __future__ import division\nfrom builtins import range\nimport math\nimport numpy as np\nimport pandas as pd\nimport scipy.stats\nimport time\nimport seaborn\nfrom collections import Counter\nfrom importlib import *\n\nimport cf\nimport gc_memo\nimport gc_plots\n\nreload(cf)\nreload(gc_memo)\nreload(gc_plots)\n\nfrom gc_memo import main\nfrom gc_plots import *\n\n\ndef small_scale(store_export='dictionary'):\n    \"\"\" Performs a single simulation of the given system, creates\n    the following plots:\n            - population dynamics overview (free naive cells, free memory cells\n            and GC populations over time)\n            - for each GC, a clonal composition plot together with its memory\n            output in a separate panel\n            - for each GC, the evolution of its largest clone's affinities over\n            mutation count (this plot contains aritificial noise to increase\n            visibility!).\n\n    If store_export is set 'datafile', the simulation data is stored in a\n    hdf5 file for future purposes, for 'dictionary' the data is passed\n    internally and discarded after the run.\n\n    Recommended only for small simulation sizes with up to ~5 GCs and ~5k\n    cells, as otherwise things get crowded and plots get large.\n    \"\"\"\n    # get runID from current system time\n    runID = int(time.time())\n    # run simulation and get filepath or dict\n    simdata = main(runID, store_export=store_export, evalperday=12)\n    # import required information for small scale plots\n    l_times, l_fn, l_fm, l_GCs, LFcurve, Agcurve, evaltimes, freePan, GCPans, \\\n        ms_times, ms_vals, ms_fams, ms_muts, mut_list, \\\n        E_list = import_file(simdata)\n    # plot population behaviour\n    population_plot(l_times, l_fn, l_fm, l_GCs, runID)\n    # plot GC contents and memory output for every GC\n    for i in range(len(l_GCs)):\n        GC_dynamics_plot(GCPans[i], ms_times[i], ms_fams[i], ms_vals[i],\n                         ms_muts[i], runID, i)\n\n    return(simdata)\n\n\ndef TUCHMI_sampling(store_export='datafile', d_export=True, subsample=12):\n    \"\"\" Performs a single simulation of a given size using the TUCHMI vaccination\n    protocol, samples memory from the simulated pool and creates several plots\n    summarising the information. User settings regarding the protocol are\n    overwritten.\n\n    Plots produced include:\n        - mean SHMs and clonal expansion (fraction of cells sampled from\n        clones that appeared more than once within the sample) in samples of\n        size subsample\n        - scatter plot of affinity over mutational status in polyclonal samples\n        at TUCHMI time points I, II and III\n        - scatter plot of affinity over mutational status at a clonal level,\n        cells sampled from three TUCHMI time points merged into single plots\n        (but sampling time point encoded in colouring)\n\n    If store_export is set 'datafile', the simulation data is stored in a\n    hdf5 file for future purposes, for 'dictionary' the data is passed\n    internally and lost after the run.\n\n    If d_export is set True, textfiles containing the sampled data (used for\n    plotting) are exported for each plot individually.\n\n    Subsample gives the number of cells to be sampled at each timepoint in\n    oder to calculate entropy and unique fraction.\n\n    Can be used for all simulation sizes, but is especially useful for larger\n    simulations (e.g. >=50 GCs, 50k cells).\n    \"\"\"\n    # give protocol\n    cf.endtime = 126*12\n    cf.tinf = [0*12, 28*12, 56*12]\n    cf.dose = [1, 1, 1]\n\n    # get runID from current system time\n    runID = int(time.time())\n\n    # run simulation and get filepath or dict\n    simdata = main(runID, store_export=store_export, evalperday=1)\n\n    # import required information\n    l_times, l_fn, l_fm, l_GCs, LFcurve, Agcurve, evaltimes, freePan, GCPans, \\\n        ms_times, ms_vals, ms_fams, ms_muts, mut_list, E_list = \\\n        import_file(simdata)\n\n    # for affinity-mutation scatter plot, downsample for visibility\n    pick_tp = 35*12\n    samplefrac = 100./len(freePan.sel(timepoint = pick_tp).dropna(\"dim_0\"))\n\n    # get list of lists to catch values at every timepoint\n    tList = list(freePan[\"timepoint\"].values)\n    TT = len(tList)\n    SHM_means = [[] for t in range(TT)]\n    Entropies = [[] for t in range(TT)]\n    clusterfracs = [[] for t in range(TT)]\n\n    \"\"\" Cell pool affinity over time \"\"\"\n    # get mean affinity at all time points\n    Elist = []\n    for tp in range(len(tList)):\n        C = freePan.sel(timepoint = tList[tp]).loc[dict(dim_1=\"affinity\")].dropna(\"dim_0\").values.mean()\n        Elist.append(C)\n    # pass energies to plot function\n    pool_affinity_plot(tList, Elist)\n\n    \"\"\" Mean SHM and clonal expansion within sample of size subsample \"\"\"\n    # sample 100 times to calculate standard deviations\n    for nn in range(100):\n        for tp in range(TT):\n            ttp = 12*tp\n            # cellnumber to be sampled is either subsample or, if less cells\n            # are available (more of a hypothetic case really), all cells\n            freePan_no_na = freePan.sel(timepoint = ttp).dropna(\"dim_0\")\n            cellnum = min(subsample, len(freePan_no_na))\n            if cellnum > 0:\n                cell_id = np.random.choice(len(freePan_no_na), cellnum)\n                cells = freePan_no_na[cell_id, :]\n                c_muts = list(cells.loc[dict(dim_1=\"mutations\")].values)\n                SHM_means[tp].append(np.nanmean(c_muts))\n                # evaluate entropies and clusterfractions\n                CC = Counter(list(cells.loc[dict(dim_1=\"family\")].values))\n                Entropies[tp].append(scipy.stats.entropy(list(CC.values()), base=2)\n                                     / math.log(cellnum, 2))\n                # count again to find how many clones have one member only,\n                # calculate clusterfrac from this\n                sizedist = list(CC.values())\n                C2 = Counter(sizedist)\n                uniquefrac = float(C2[1])/cellnum\n                clusterfracs[tp].append(1-uniquefrac)\n            else:\n                SHM_means[tp].append(np.nan)\n                Entropies[tp].append(np.nan)\n                uniquefrac[tp].append(np.nan)\n                clusterfracs[tp].append(np.nan)\n\n    # pass information to plotting function\n    MSHM = np.nanmean(SHM_means, axis=1)\n    SSHM = np.nanstd(SHM_means, axis=1)\n    MEntropies = np.nanmean(Entropies, axis=1)\n    SEntropies = np.nanstd(Entropies, axis=1)\n    Mclusterfracs = np.nanmean(clusterfracs, axis=1)\n    Sclusterfracs = np.nanstd(clusterfracs, axis=1)\n\n    sample_statistics_plot(subsample, tList, MSHM, SSHM,\n                           MEntropies, SEntropies, Mclusterfracs,\n                           Sclusterfracs)\n\n    \"\"\" Plot of affinity/mutations on tps I, II and III \"\"\"\n    # sample cells 7 days post each infection, record SHM, KD and origin\n    # (memory versus naive first activated ancestor)\n    timecourse = [7*12, 35*12, 63*12]\n    SHM_list = [[] for t in timecourse]\n    KD_list = [[] for t in timecourse]\n    orglist = [[] for t in timecourse]\n\n    for d in range(len(timecourse)):\n        tp = timecourse[d]\n        freePan_no_na = freePan.sel(timepoint = tp).dropna(\"dim_0\")\n        cellnum = int(np.round(len(freePan_no_na)*samplefrac))\n        if cellnum > 0:\n            cell_id = np.random.choice(len(freePan_no_na), cellnum)\n            cells = freePan_no_na[cell_id, :]\n            kdl = list(cells.loc[dict(dim_1=\"affinity\")].values)\n            # transform norm E to KD\n            kdll = np.exp(cf.y0+np.array(kdl)*cf.m)\n            KD_list[d] = list(kdll)\n            # get mutation counts, correct them and origin\n            SHM_list[d] = list(cells.loc[dict(dim_1=\"mutations\")].values)\n            orglist[d] = list(cells.loc[dict(dim_1=\"origin\")].values)\n\n    # pass information to plot function\n    sample_scatter_plot(KD_list, SHM_list, orglist)\n\n    \"\"\" Affinity/mutation plots for individual clusters \"\"\"\n    # samples from the memory pool at the given timepoints, split information\n    # into clusters and plot SHM/KD scatter plots for some of these clusters.\n\n    # lists to collect SHM, KD values, families and timepoints for all panels\n    SHM_list = []\n    KD_list = []\n    fam_list = []\n    tp_list = []\n\n    for d in range(len(timecourse)):\n        tp = timecourse[d]\n        freePan_no_na = freePan.sel(timepoint = tp).dropna(\"dim_0\")\n        cellnum = int(len(freePan_no_na)*samplefrac)\n        if cellnum > 0:\n            cell_id = np.random.choice(len(freePan_no_na), cellnum)\n            cells = freePan_no_na[cell_id, :]\n            kdl = list(cells.loc[dict(dim_1=\"affinity\")].values)\n            # transform norm E to KD\n            kdll = np.exp(cf.y0+np.array(kdl)*cf.m)\n            KD_list += list(kdll)\n            SHM_list += list(list(cells.loc[dict(dim_1=\"mutations\")].values))\n            fam_list += list(cells.loc[dict(dim_1=\"family\")].values)\n            tp_list += [tp for k in range(cellnum)]\n\n    # count into families and find clusters with more than xx members\n    famcounter = Counter(fam_list)\n    fams = list(famcounter.keys())\n    clusters = []\n    for fam in fams:\n        if famcounter[fam] > 1:\n            clusters.append(fam)\n\n    # make separate lists for SHM, KD and TP (defining color) within clusters\n    # and add information to list\n    iSHMs = [[] for i in clusters]\n    iKDs = [[] for i in clusters]\n    iTPs = [[] for i in clusters]\n\n    for ff in range(len(fam_list)):\n        if fam_list[ff] in clusters:\n            ii = clusters.index(fam_list[ff])\n            iSHMs[ii].append(SHM_list[ff])\n            iKDs[ii].append(KD_list[ff])\n            # give different colors for different timepoints\n            if tp_list[ff] == timecourse[0]:\n                iTPs[ii].append('lightcoral')\n            elif tp_list[ff] == timecourse[1]:\n                iTPs[ii].append('indianred')\n            else:\n                iTPs[ii].append('firebrick')\n    # pass information to plot function\n    clonal_scatter_plot(iSHMs, iKDs, iTPs)\n\n    # write information to file\n    if d_export:\n        datafile = open('processed_data/TUCHMI_sampling_data', 'w')\n\n        datafile.write('1) SAMPLE STATISTICS \\n \\n')\n        datafile.write('sampled fraction = {} \\n \\n'.format(samplefrac))\n        datafile.write('timecourse (days) \\n {} \\n \\n'.format(np.array(tList)/12.))\n        datafile.write('SHMs of cells in sample, mean and std \\n {} \\n {} \\n \\n'.format(MSHM, SSHM))\n        datafile.write('normalised Shannon entropy of cells in sample, mean and std \\n {} \\n {} \\n \\n'.format(MEntropies, SEntropies))\n        datafile.write('fraction of non-unique cells in sample, mean and std \\n {} \\n {} \\n \\n'.format(Mclusterfracs, Sclusterfracs))\n\n        datafile.close()\n\n    return(simdata)\n\n\ndef selection_vs_mutation(store_export='dictionary', d_export=True):\n    \"\"\" Performs a single simulation of a given size using a specified protocol\n    of vaccination boosters. At specified timepoints, a specified number of\n    memory cells is sampled and the affinities of their ancestors as well as\n    their current affinities are written to a list. Also written to list\n    are the binding energies of the naive cells. These three lists are then\n    passed on to be plotted as distribution histograms.\n\n    Plots produced include a collection of three histograms (unselected,\n    selected germline energies, actual energies after mutations) for each\n    queried timepoint and a more complex scatter plot with marginal histograms\n    for each queried timepoint.\n\n    For each timepoint, the fraction of cells with unaltered/improved/impaired\n    affinity is printed to screen.\n\n    If store_export is set 'datafile', the simulation data is stored in a\n    hdf5 file for future purposes, for 'dictionary' the data is passed\n    internally and lost after the run.\n\n    If d_export is set True, textfiles containing the sampled data (used for\n    plotting) are exported for each plot individually.\n    \"\"\"\n    # parameters relevant to this analysis\n    # evaluation timepoint in days\n    analysis_times = [29]\n    # prepare lists\n    ancestor_dists = []\n    final_dists = []\n    # get runID from current system time\n    runID = int(time.time())\n    # run simulation and get filepath or dict\n    simdata = main(runID, store_export=store_export, evalperday=1)\n    # import required information for small scale plots\n    l_times, l_fn, l_fm, l_GCs, LFcurve, Agcurve, evaltimes, freePan, GCPans, \\\n        ms_times, ms_vals, ms_fams, ms_muts, mut_list, E_list = \\\n        import_file(simdata)\n    # extract the affinities and ancestor affinities at the analysis points\n    tList = list(freePan[\"timepoint\"].values)\n    for i in range(len(analysis_times)):\n        # limit cell number to be drawn in order not to clatter the plot\n        tp = analysis_times[i]\n        freePan_no_na = freePan.sel(timepoint = tList[tp]).dropna(\"dim_0\")\n        cellnum = min(2000, len(freePan_no_na))\n        cellnum = len(freePan_no_na)\n        cell_id = np.random.choice(len(freePan_no_na), cellnum)\n        cells = freePan_no_na[cell_id, :]\n        afflist = list(cells.loc[dict(dim_1=\"affinity\")].values)\n        final_dists.append(afflist)\n        aff0list = list(cells.loc[dict(dim_1=\"affinity0\")].values)\n        ancestor_dists.append(aff0list)\n    # send energy lists to histogram plot\n    for i in range(len(analysis_times)):\n        energy_distributions_plot(E_list, ancestor_dists[i], final_dists[i],\n                                  analysis_times[i])\n        energy_scatter_plot(ancestor_dists[i], final_dists[i],\n                            analysis_times[i])\n\n    if d_export:\n        datafile = open('processed_data/energy_distribution_data', 'w')\n\n        datafile.write('1) naive distribution \\n \\n')\n        datafile.write('{} \\n \\n'.format(E_list))\n\n        datafile.write('2) analysis days \\n \\n')\n        datafile.write('{} \\n \\n'.format(analysis_times))\n\n        datafile.write('3) ancestor distributions per time point \\n \\n')\n        datafile.write('{} \\n \\n'.format(ancestor_dists))\n\n        datafile.write('4) memory distributions per time point \\n \\n')\n        datafile.write('{} \\n \\n'.format(final_dists))\n\n        datafile.close()\n\n    return(simdata)\n\n\ndef stacked_mutations(store_export='dictionary', d_export=True,\n                      repeats=10):\n    \"\"\" Performs a number of simulation runs, computes histograms for\n    improved, impaired and unchanged binders at a single given timepoint\n    and saves the individual as well as the summed values to file. For several\n    repeats, data is accumulated in the histograms as well.\n\n    If store_export is set 'datafile', the simulation data is stored in a\n    hdf5 file for future purposes, for 'dictionary' the data is passed\n    internally and lost after the run.\n\n    If d_export is set True, textfiles containing the sampled data (used for\n    plotting) are exported for each plot individually.\"\"\"\n    # parameters relevant to this analysis\n    # evaluation timepoint in days\n    analysis_time = 29\n    bins = np.linspace(0.6, 1, 17)\n    # collect results\n    sum_zero = np.zeros(len(bins)-1)\n    sum_plus = np.zeros(len(bins)-1)\n    sum_minus = np.zeros(len(bins)-1)\n    list_zero = []\n    list_plus = []\n    list_minus = []\n\n    for i in range(repeats):\n        # get runID from current system time\n        runID = int(time.time())\n        # run simulation and get filepath or dict\n        simdata = main(runID, store_export=store_export, evalperday=1)\n        # import required information for small scale plots\n        l_times, l_fn, l_fm, l_GCs, LFcurve, Agcurve, evaltimes, freePan, \\\n            GCPans, ms_times, ms_vals, ms_fams, ms_muts, mut_list, E_list = \\\n            import_file(simdata)\n        # extract the affinities and ancestor affinities at the analysis points\n        tList = list(freePan[\"timepoint\"].values)\n        # limit cell number to be drawn in order not to clatter the plot\n        # possibility of subsampling here\n        tp = analysis_time\n\n        freePan_no_na = freePan.sel(timepoint = tList[tp]).dropna(\"dim_0\")\n        cellnum = len(freePan_no_na)\n        cell_id = np.random.choice(len(freePan_no_na), cellnum)\n        cells = freePan_no_na[cell_id, :]\n\n        final_dist = list(cells.loc[dict(dim_1=\"affinity\")].dropna(\"dim_0\").values)\n        ancestor_dist = list(cells.loc[dict(dim_1=\"affinity0\")].dropna(\"dim_0\").values)\n\n        # extract counts of unchanged, improved and impaired cells\n        unchanged_list = np.array(final_dist)[np.where(np.array(\n            ancestor_dist) == np.array(final_dist))[0]]\n        improved_list = np.array(final_dist)[np.where(np.array(\n            ancestor_dist) < np.array(final_dist))[0]]\n        impaired_list = np.array(final_dist)[np.where(np.array(\n            ancestor_dist) > np.array(final_dist))[0]]\n\n        # make histograms, store information both in list and in sum.\n        U_counts, _ = np.histogram(unchanged_list, bins=bins)\n        plus_counts, _ = np.histogram(improved_list, bins=bins)\n        minus_counts, _ = np.histogram(impaired_list, bins=bins)\n\n        # collect results\n        sum_zero += U_counts\n        sum_plus += plus_counts\n        sum_minus += minus_counts\n        list_zero.append(U_counts)\n        list_plus.append(plus_counts)\n        list_minus.append(minus_counts)\n    cellsum = np.sum(sum_zero)+np.sum(sum_plus)+np.sum(sum_minus)\n\n    # plot\n    stacked_energy_plot(bins, sum_plus, sum_minus, sum_zero, analysis_time)\n\n    if d_export:\n        datafile = open('processed_data/stacked_histogram_data', 'w')\n\n        datafile.write('1) day \\n \\n')\n        datafile.write('{} \\n \\n'.format(analysis_time))\n\n        datafile.write('2) bins \\n \\n')\n        datafile.write('{} \\n \\n'.format(bins))\n\n        datafile.write('3) runs \\n \\n')\n        datafile.write('{} \\n \\n'.format(repeats))\n\n        datafile.write('4) sum of counts with unchanged energies\\n \\n')\n        datafile.write('{} \\n \\n'.format(sum_zero))\n\n        datafile.write('5) sum of counts with improved energies\\n \\n')\n        datafile.write('{} \\n \\n'.format(sum_plus))\n\n        datafile.write('6) sum of counts with impaired energies\\n \\n')\n        datafile.write('{} \\n \\n'.format(sum_minus))\n\n        datafile.write('7) list of counts with unchanged energies\\n \\n')\n        datafile.write('{} \\n \\n'.format(list_zero))\n\n        datafile.write('8) list of counts with improved energies\\n \\n')\n        datafile.write('{} \\n \\n'.format(list_plus))\n\n        datafile.write('9) list of counts with impaired energies\\n \\n')\n        datafile.write('{} \\n \\n'.format(list_minus))\n\n        datafile.write('10) percentage of umutated, improved, impaired \\n \\n')\n        datafile.write('{}, {}, {}'.format(np.sum(sum_zero)/cellsum,\n                       np.sum(sum_plus)/cellsum, np.sum(sum_minus)/cellsum))\n        datafile.close()\n\n\ndef AM_effect_nkey(nkeys=[1, 5, 10, 15], repeats=100, d_export=True):\n    \"\"\" Given a list of values for nkey and a number of individual GC reactions\n    to be averaged over for each of them, computes and plots the improvement\n    within single GCs for one infection. Thus, overwrites parameters giving\n    the infection protocol and duration of the simulation as well as setting\n    the nubmer of GCs to 1. Other parameters remain untouched. A textfile with\n    the computed mean results is exported if d_export==True.\n    \"\"\"\n\n    # set single infection and single GC for this analysis\n    cf.endtime = 30*12\n    cf.tinf = [0*12]\n    cf.dose = [1]\n    cf.nGCs = 1\n    cf.naive_pool = 1000*1  # size of the naive precursor pool\n    cf.memory_pool = 100*1  # size of the initial unspecific memory pool\n    # function for calculating mean E_norm from GC panel\n\n    def GC_affinity(GCPan):\n        \"\"\" Given a GC panel, gets the mean E_norm for each timepoint.\"\"\"\n        energies = []\n        tList = list(GCPan[\"timepoint\"].values)\n\n        for tp in range(len(tList)):\n            energy = GCPan.sel(timepoint = tList[tp]).loc[dict(dim_1=\"affinity\")].dropna(\"dim_0\").values.mean()\n            energies.append(energy)\n\n        return tList, energies\n\n    topElist = []\n    for hs in nkeys:\n        # set binding model parameters accordingly\n        cf.nkey = hs\n        cf.lAg = hs\n        cf.lAb = 220 - hs\n        eL = []  # list for collecting energies timecurses of all runs\n        for r in range(repeats):\n            simdata = main(store_export='dictionary', evalperday=12)\n            l_times, l_fn, l_fm, l_GCs, LFcurve, Agcurve, evaltimes, freePan, \\\n                GCPans, ms_times, ms_vals, ms_fams, ms_muts, mut_list, E_list\\\n                = import_file(simdata)\n            tList, energies = GC_affinity(GCPans[0])\n            eL.append(energies)\n\n        # calculate mean and std of all runs and plot\n        eM = np.nanmean(np.array(eL), axis=0)\n        eStd = np.nanstd(np.array(eL), axis=0)\n        topElist.append((hs, tList, eM, eStd))\n\n    # write information to file\n    if d_export:\n        datafile = open('processed_data/AM_effect_data', 'w')\n        datafile.write('number of simulation runs per n_key = {} \\n'.format(repeats))\n        datafile.write('n_key, time (days), mean(normalised energies), std(normalised energies) \\n')\n        for i in range(len(nkeys)):\n            datafile.write('{0}, {1}, {2}, {3}\\n \\n'.format(topElist[i][0], np.array(topElist[i][1])/12., topElist[i][2], topElist[i][3]))\n        datafile.close()\n    # plot\n    AM_effect_plot(topElist)\n", "meta": {"hexsha": "b7cd536f816c12a4262bd6234bb738e80b62beab", "size": 21753, "ext": "py", "lang": "Python", "max_stars_repo_path": "gc_memo/gc_head.py", "max_stars_repo_name": "obrzts/gc_memo", "max_stars_repo_head_hexsha": "334a11765cc257848c6c4da1f99fa5559c10f2c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gc_memo/gc_head.py", "max_issues_repo_name": "obrzts/gc_memo", "max_issues_repo_head_hexsha": "334a11765cc257848c6c4da1f99fa5559c10f2c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gc_memo/gc_head.py", "max_forks_repo_name": "obrzts/gc_memo", "max_forks_repo_head_hexsha": "334a11765cc257848c6c4da1f99fa5559c10f2c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.1569767442, "max_line_length": 138, "alphanum_fraction": 0.6521399347, "include": true, "reason": "import numpy,import scipy", "num_tokens": 5489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.18945048087428024}}
{"text": "\"\"\"\nBy Dr Jie Zheng -Q, NAOC\nv1 2019-04-27\n\"\"\"\n\n\nimport numpy as np\nfrom..util import *\n\n\ndef date_conv():\n    pass\n\n\n  #function date_conv,date,type, BAD_DATE = bad_date\n  #;+\n  #; NAME:\n  #;     DATE_CONV\n  #; PURPOSE:\n  #;     Procedure to perform conversion of dates to one of three possible formats.\n  #;\n  #; EXPLANATION:\n  #;     The following date formats are allowed\n  #;\n  #;       format 1: real*8 scalar encoded as:\n  #;               year*1000 + day + hour/24. + min/24./60 + sec/24./60/60\n  #;               where day is the day of year (1 to 366)\n  #;       format 2: Vector encoded as:\n  #;               date[0] = year (eg. 2005)\n  #;               date[1] = day of year (1 to 366)\n  #;               date[2] = hour\n  #;               date[3] = minute\n  #;               date[4] = second\n  #;               To indicate a date only, set a negative hour.\n  #;       format 3: string (ascii text) encoded as\n  #;               DD-MON-YEAR HH:MM:SS.SS\n  #;               (eg.  14-JUL-2005 15:25:44.23)\n  #;            OR\n  #;               YYYY-MM-DD HH:MM:SS.SS  (ISO standard)\n  #;               (eg.  1987-07-14 15:25:44.23 or 1987-07-14T15:25:44.23)\n  #;\n  #;            OR \n  #;               DD/MM/YY (pre-2000 option for FITS DATE keywords)\n  #;            Time of day segment is optional in all of these.\n  #;       \n  #;       format 4: three element vector giving spacecraft time words\n  #;       from a Hubble Space Telescope (HST) telemetry packet.   Based on\n  #;       total number of secs since midnight, JAN. 1, 1979\n  #;\n  #;       format 5: Julian day. As this is also a scalar, like format 1, \n  #;       \tthe distinction between the two on input is made based on their\n  #;       \tvalue. Numbers > 2300000 are interpreted as Julian days.\n  #;\n  #; CALLING SEQUENCE\n  #;       results = DATE_CONV( DATE, TYPE )\n  #;\n  #; INPUTS:\n  #;       DATE - input date in one of the possible formats. Must be scalar.\n  #;       TYPE - type of output format desired.  If not supplied then\n  #;               format 3 (real*8 scalar) is used.\n  #;                       valid values:\n  #;                       'REAL'  - format 1\n  #;                       'VECTOR' - format 2\n  #;                       'STRING' - format 3\n  #;                       'FITS' - YYYY-MM-DDTHH:MM:SS.SS'\n  #;                       'JULIAN' - Julian date\n  #;                       'MODIFIED' - Modified Julian date (JD-2400000.5)\n  #;               TYPE can be abbreviated to the single character strings 'R',\n  #;               'V', 'S', 'F', 'J', and 'M'.\n  #;               Nobody wants to convert TO spacecraft time (I hope!)\n  #; OUTPUTS:\n  #;       The converted date is returned as the function value.\n  #;       Output is -1 if date is unrecognisable. \n  #;\n  #;       If the time of day is omitted from the input, it will also\n  #;       be omitted from any output string (format STRING or FITS). \n  #;       Note that date-only strings are allowed by the FITS standard. \n  #;       For other output formats any missing time of day is set to \n  #;       00:00:00.0\n  #;\n  #; KEYWORD OUTPUTS\n  #;\n  #;        BAD_DATE set to 1B if date is unrecognisable\n  #;\n  #; EXAMPLES:\n  #;       IDL> print,date_conv('2006-03-13 19:58:00.00'),f='(f15.5)' \n  #;             2006072.83194 \n  #;       IDL> print,date_conv( 2006072.8319444d,'F')\n  #;             2006-03-13T19:58:00.00\n  #;       IDL> print,date_conv( 2006072.8319444d,'V')\n  #;             2006.00      72.0000      19.0000      57.0000      59.9962\n  #;       IDL> print,date_conv( 2006072.8319444d,'J'), f='(f15.5)'\n  #;             2453808.33194\n  #;\n  #;\n  #; HISTORY:\n  #;      version 1  D. Lindler  July, 1987\n  #;      adapted for IDL version 2  J. Isensee  May, 1990\n  #;      Made year 2000 compliant; allow ISO format input  jls/acc Oct 1998\n  #;      DJL/ACC Jan 1998, Modified to work with dates such as 6-JAN-1996 where\n  #;               day of month has only one digit.\n  #;      DJL, Nov. 2000, Added input/output format YYYY-MM-DDTHH:MM:SS.SS\n  #;      Replace spaces with '0' in output FITS format  W.Landsman April 2006\n  #;      Added Julian date capabilities on input and output.  M.Perrin, July 2007\n  #;      Removed spurious /WARN keyword to MESSAGE W.L. Feb 2012\n  #;      ...and another /WARN; added BAD_DATE, drop spurious time-of-day\n  #;      output from strings. J. P. Leahy July 2013\n  #;      changed all /CONTINUE warning messages to /INFO: can be suppressed \n  #;      by setting !QUIET = 1.  J. P. Leahy July 2013\n  #;-\n  #;-------------------------------------------------------------\n  #;\n  #compile_opt idl2\n  #; data declaration\n  #;\n  #days = [0,31,28,31,30,31,30,31,31,30,31,30,31]\n  #months = ['   ','JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT',$\n  #        'NOV','DEC']\n  #;\n  #; set default type if not supplied\n  #;\n  #if N_params() lt 2 then type = 'REAL'\n  #;\n  #; Determine type of input supplied\n  #;\n  #s = size(date) & ndim = s[0] & datatype = s[ndim+1]\n  #if ndim gt 0 then begin                 ;vector?\n  #        if ndim gt 1 then goto,notvalid\n  #        if (s[1] ne 5) && (s[1] ne 3) then goto,notvalid\n  #        if (s[1] eq 5) then form = 2 else form = 4\n  #   end else begin                       ;scalar input\n  #        if datatype eq 0 then goto,notvalid\n  #        if datatype eq 7 then form = 3 $        ;string\n  #                         else form = 1  ;numeric scalar\n  #end\n  #;\n  #;      -----------------------------------\n  #;\n  #;*** convert input to year,day,hour,minute,second\n  #;\n  #;      -----------------------------------\n  #case form of\n  #\n  #        1: begin                                        ;real scalar\n  #\t\t\t; The 'real' input format may be interpreted EITHER\n  #\t\t\t; a) if < 2300000\n  #\t\t\t;    as the traditional 'real*8 encoded' format used by date_conv\n  #\t\t\t; b) if > 2300000\n  #\t\t\t;    as a Julian Day Number\n  #                idate = long(date)\n  #                year = long(idate/1000)\n  #\n  #\t\t\t\tif year lt 2300 then begin\n  #\t\t\t\t\t\n  #\t\t\t\t\t; if year is only 2 digits, assume 1900\n  #\t                if year lt 100 then begin\n  #\t                   message,/INF, $\n  #\t                     'Warning: Year specified is only 2 digits, assuming 19xx'\n  #\t                   year=1900+year\n  #\t                   idate=1900000+idate\n  #\t                   date=1900000.+date\n  #\t                end\n  #\t                day = idate - year*1000\n  #\t                fdate = date-idate\n  #\t                fdate = fdate*24.\n  #\t                hour = fix(fdate)\n  #\t                fdate = (fdate-hour)*60.0\n  #\t                minute = fix(fdate)\n  #\t                sec = float((fdate-minute)*60.0)\n  #\n  #\t\t\t\tendif else begin\n  #\t\t\t\t\tdaycnv, date, year, mn, mndy, hr\n  #\t\t\t\t\t; convert from month/day to day of year\n  #\t\t\t\t\t; how many days PRECEED the start of each month?\n  #\t\t\t\t\tYDAYS = [0,31,59,90,120,151,181,212,243,273,304,334,366] \n  #\t\t\t\t\tLEAP =  (((YeaR MOD 4) EQ 0) AND ((YeaR MOD 100) NE 0)) OR $\n  #\t\t\t\t\t                 ((YeaR MOD 400) EQ 0)\n  #\t\t\t        IF LEAP THEN YDAYS[2:*] = YDAYS[2:*] + 1\n  #\t\t\t\t\tday = ydays[mn-1]+mndy\n  #\t\t\t\t\t\n  #\t\t\t\t\thour = fix(hr)\n  #\t\t\t\t\tfmin = (hr-hour)*60\n  #\t\t\t\t\tminute = fix(fmin)\n  #\t\t\t\t\tsec = float((fmin-minute)*60)\n  #\t\t\t\tendelse\n  #           end\n  #\n  #        2: begin                                        ;vector\n  #                year = fix(date[0])\n  #;\n  #; if year is only 2 digits, assume 1900\n  #;\n  #                if year lt 100 then begin\n  #                   message,/INF, $\n  #                    'Warning: Year specified is only 2 digits, assuming 19xx'\n  #                   year=1900+year\n  #                end\n  #;\n  #                day = fix(date[1])\n  #                hour = fix(date[2])\n  #                minute = fix(date[3])\n  #                sec = float(date[4])\n  #           end\n  #\n  #        3: begin                                        ;string\n  #                temp = date\n  #;\n  #; check for old type of date, DD-MMM-YYYY\n  #;\n  #                test = STRPOS(temp,'-')            \n  #                if test ge 0 && test le 2 then begin\n  #                  day_of_month = fix(gettok(temp,'-'))\n  #                  month_name = gettok(temp,'-')\n  #                  year = fix(gettok(temp,' '))\n  #;\n  #; determine month number from month name\n  #;\n  #                  month_name = strupcase(month_name)\n  #                  for mon = 1,12 do begin\n  #                        if month_name eq months[mon] then goto,found\n  #                  end\n  #                  message,/INFORMATIONAL, 'Invalid month name specified'\n  #                  goto, notvalid\n  #;\n  #; check for new type of date, ISO: YYYY-MM-DD\n  #;\n  #                end else if strpos(temp,'-') eq 4 then begin\n  #                  year = fix(gettok(temp,'-'))\n  #                  month_name = gettok(temp,'-')\n  #                  mon= FIX(month_name)\n  #                  day_of_month=gettok(temp,' ')\n  #                  if strlen(temp) eq 0 then begin\n  #                        dtmp=gettok(day_of_month,'T')\n  #                        temp=day_of_month\n  #                        day_of_month=dtmp\n  #                  end\n  #                  day_of_month=fix(day_of_month)\n  #;\n  #; check for DD/MM/YY\n  #;\n  #                end else if STRPOS(temp,'/') eq 2 then begin\n  #                  day_of_month = FIX(gettok(temp,'/'))\n  #                  mon = FIX(gettok(temp,'/'))\n  #                  year = 1900 + FIX(STRMID(temp,0,2))\n  #                end else goto, notvalid\n  #                \n  #    found:\n  #                hour = gettok(temp,':')\n  #                hour =  hour NE '' ? FIX(hour) : -1\n  #                minute = fix(gettok(temp,':'))\n  #                sec = float(strtrim(strmid(temp,0,5)))\n  #             \n  #                IF (mon LT 1 || mon GT 12) THEN BEGIN\n  #                    MESSAGE, /INFORMATIONAL, 'Invalid month specified'\n  #                    goto, notvalid\n  #                ENDIF\n  #;\n  #; if year is only 2 digits, assume 1900\n  #;\n  #                if year lt 100 then begin\n  #                   message,/INFORMATIONAL, $ \n  #                     'Warning: Year specified is only 2 digits, assuming 19xx'\n  #                   year=1900+year\n  #                end\n  #;\n  #;\n  #;            convert to day of year from month/day_of_month\n  #;\n  #;            correction for leap years\n  #;\n  #;               if (fix(year) mod 4) eq 0 then days(2) = 29     ;add one to february\n  #                lpyr = ((year mod 4) eq 0) and ((year mod 100) ne 0) $\n  #                        or ((year mod 400) eq 0)\n  #                if lpyr eq 1 then days[2] = 29 ; if leap year, add day to Feb.\n  #;\n  #;\n  #;            compute day of year\n  #;\n  #                  day = fix(total(days[0:mon-1])+day_of_month)\n  #           end\n  #\n  #        4 : begin                       ;spacecraft time\n  #                SC = DOUBLE(date)\n  #                SC = SC + (SC LT 0.0)*65536.    ;Get rid of neg. numbers \n  #;\n  #;            Determine total number of secs since midnight, JAN. 1, 1979\n  #;\n  #                SECS = SC[2]/64 + SC[1]*1024 + SC[0]*1024*65536.\n  #                SECS = SECS/8192.0D0            ;Convert from spacecraft units \n  #;\n  #;            Determine number of years \n  #;\n  #                MINS = SECS/60.\n  #                HOURS = MINS/60.\n  #                TOTDAYS = HOURS/24.\n  #                YEARS = TOTDAYS/365.\n  #                YEARS = FIX(YEARS)\n  #;\n  #;            Compute number of leap years past \n  #;\n  #                LEAPYEARS = (YEARS+2)/4\n  #;\n  #;           Compute day of year \n  #;\n  #                DAY = FIX(TOTDAYS-YEARS*365.-LEAPYEARS)\n  #;\n  #;           Correct for case of being right at end of leapyear\n  #;\n  #                IF DAY LT 0 THEN BEGIN\n  #                  DAY = DAY+366\n  #                  LEAPYEARS = LEAPYEARS-1\n  #                  YEARS = YEARS-1\n  #                END\n  #;\n  #;            COMPUTE HOUR OF DAY\n  #;\n  #                TOTDAYS = YEARS*365.+DAY+LEAPYEARS\n  #                HOUR = FIX(HOURS - 24*TOTDAYS)\n  #                TOTHOURS = TOTDAYS*24+HOUR\n  #;\n  #;            COMPUTE MINUTE\n  #;\n  #                MINUTE = FIX(MINS-TOTHOURS*60)\n  #                TOTMIN = TOTHOURS*60+MINUTE\n  #;\n  #;            COMPUTE SEC\n  #;\n  #                SEC = SECS-TOTMIN*60\n  #;\n  #;            COMPUTE ACTUAL YEAR\n  #;\n  #                YEAR = YEARS+79\n  #;\n  #; if year is only 2 digits, assume 1900\n  #;\n  #                if year lt 100 then begin\n  #                   message, /INF, $ \n  #                     'Warning: Year specified is only 2 digits, assuming 19xx'\n  #                   year=1900+year\n  #                end\n  #;\n  #;\n  #;            START DAY AT ONE AND NOT ZERO\n  #;\n  #                DAY++\n  #           END\n  #ENDCASE\n  #;\n  #;            correction for leap years\n  #;\n  #        if form ne 3 then begin         ;Was it already done?\n  #           lpyr = ((year mod 4) eq 0) && ((year mod 100) ne 0) $\n  #                || ((year mod 400) eq 0)\n  #           if lpyr eq 1 then days[2] = 29 ; if leap year, add day to Feb.\n  #        end\n  #;\n  #;            check for valid day\n  #;\n  #        if (day lt 1) || (day gt total(days)) then begin\n  #            message, /INFORMATIONAL, $\n  #                'ERROR -- There are only ' + strtrim(fix(total(days)),2) + $\n  #\t              ' days  in year '+strtrim(year,2)\n  #            goto, notvalid\n  #        endif    \n  #;\n  #;            find month which day occurs\n  #;\n  #        day_of_month = day\n  #        month_num = 1\n  #        while day_of_month gt days[month_num] do begin\n  #               day_of_month = day_of_month - days[month_num]\n  #               month_num = month_num+1\n  #        end\n  #;           ---------------------------------------\n  #;\n  #;   *****       Now convert to output format\n  #;\n  #;           ---------------------------------------\n  #;\n  #; is type a string\n  #;\n  #s = size(type)\n  #if (s[0] ne 0) or (s[1] ne 7) then $\n  #        message,'ERROR - Output type specification must be a string'\n  #;\n  #outcode = STRMID(STRUPCASE(type),0,1)\n  #IF (outcode EQ 'S' || outcode EQ 'F') && hour GE 0 THEN BEGIN\n  #    xsec = strmid(string(sec+100,'(f6.2)'),1,5)\n  #    if xsec EQ '60.00' then begin\n  #        minute = minute+1\n  #        xsec = '00.00'\n  #    endif\n  #    xminute =   string(minute,'(i2.2)')\n  #    if xminute EQ '60' then begin\n  #        hour = hour+1\n  #        xminute = '00'                  \n  #    endif          \n  #    tod = string(hour,'(i2.2)') +  ':' +xminute + ':'+ xsec\n  #ENDIF\n  # \n  #case outcode of\n  #\n  #        'V' : begin                             ;vector output\n  #                out = fltarr(5)\n  #                out[0] = year\n  #                out[1] = day\n  #                out[2] = hour > 0\n  #                out[3] = minute\n  #                out[4] = sec\n  #             end\n  # \n  #        'R' : begin                             ;floating point scalar\n  #;               if year gt 1900 then year = year-1900\n  #                out = sec/24.0d0/60./60. + minute/24.0d0/60. $\n  #                + (hour > 0)/24.0d0  +  day + year*1000d0\n  #              end\n  #\n  #        'S' : begin                             ;string output \n  #\n  #                month_name = months[month_num]\n  #;\n  #;            encode into ascii_date\n  #;\n  #                out = string(day_of_month,'(i2)') +'-'+ month_name +'-' + $\n  #                        string(year,'(i4)')\n  #                        \n  #  ; Omit time of day from output string if not specified on input\n  #                IF hour GE 0 THEN out += ' '+tod\n  #           end\n  #        'F' : begin\n  #                out = string(year,'(i4)')+'-'+string(month_num,'(I2.2)') $\n  #                      + '-' +  string(day_of_month,'(i2.2)')\n  #                IF hour GE 0 THEN out += 'T' + tod             \n  #           end\n  #\n  #\t\t'J' : begin\t; Julian Date\n  #\t\t\t\tydn2md, year, day, mn, dy\n  #\t\t\t\tjuldate, [year, mn, dy, hour, minute, sec], rjd\n  #\t\t\t\tout = rjd+2400000   ; convert from reduced to regular JD\n  #\t\t\t  end\n  #\t\t'M' : begin ; Modified Julian Date = JD - 2400000.5\n  #\t\t\t\tydn2md, year, day, mn, dy\n  #\t\t\t\tjuldate, [year, mn, dy, hour, minute, sec], rjd\n  #\t\t\t\tout = rjd-0.5   ; convert from reduced to modified JD\n  #\t\t\t  end\n  #\n  #        else: begin                     ;invalid type specified\n  #                print,'DATE_CONV-- Invalid output type specified'\n  #                print,' It must be ''REAL'', ''STRING'', ''VECTOR'', ''JULIAN'', ''MODIFIED'', or ''FITS''.'\n  #                return,-1\n  #              end\n  #endcase\n  #\n  #bad_date = 0B\n  #return,out\n  #;\n  #; invalid input date error section\n  #;\n  #NOTVALID:\n  #bad_date = 1B\n  #message, 'Invalid input date specified', /INFORMATIONAL\n  #return, -1\n  #end\n", "meta": {"hexsha": "7d3668bc20cc41c77a492037b38636ea05eaf9d5", "size": 16861, "ext": "py", "lang": "Python", "max_stars_repo_path": "idl2py/jd/date_conv.py", "max_stars_repo_name": "RapidLzj/idl2py", "max_stars_repo_head_hexsha": "193051cd8d01db0d125b8975713b885ad521a992", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "idl2py/jd/date_conv.py", "max_issues_repo_name": "RapidLzj/idl2py", "max_issues_repo_head_hexsha": "193051cd8d01db0d125b8975713b885ad521a992", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "idl2py/jd/date_conv.py", "max_forks_repo_name": "RapidLzj/idl2py", "max_forks_repo_head_hexsha": "193051cd8d01db0d125b8975713b885ad521a992", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.338362069, "max_line_length": 111, "alphanum_fraction": 0.4513967143, "include": true, "reason": "import numpy", "num_tokens": 5203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.37022538564692037, "lm_q1q2_score": 0.18945047731853232}}
{"text": "# Copyright 2022 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"target assigner\"\"\"\nimport logging\n\nimport numpy as np\nimport numpy.random as npr\n\nlogger = logging.getLogger(__name__)\n\n\ndef unmap(data, count, inds, fill=0):\n    \"\"\"\n    Unmap a subset of item (data) back to the original set of items\n    (of size count)\n    \"\"\"\n    if count == len(inds):\n        return data\n\n    if len(data.shape) == 1:\n        ret = np.empty((count,), dtype=data.dtype)\n        ret.fill(fill)\n        ret[inds] = data\n    else:\n        ret = np.empty((count,) + data.shape[1:], dtype=data.dtype)\n        ret.fill(fill)\n        ret[inds, :] = data\n    return ret\n\n\ndef create_target_np(all_anchors,\n                     gt_boxes,\n                     similarity_fn,\n                     box_encoding_fn,\n                     prune_anchor_fn=None,\n                     gt_classes=None,\n                     matched_threshold=0.6,\n                     unmatched_threshold=0.45,\n                     positive_fraction=None,\n                     rpn_batch_size=300,\n                     norm_by_num_examples=False,\n                     box_code_size=7):\n    \"\"\"Modified from FAIR detectron.\n    Args:\n        all_anchors: [num_of_anchors, box_ndim] float tensor.\n        gt_boxes: [num_gt_boxes, box_ndim] float tensor.\n        similarity_fn: a function, accept anchors and gt_boxes, return\n            similarity matrix(such as IoU).\n        box_encoding_fn: a function, accept gt_boxes and anchors, return\n            box encodings(offsets).\n        prune_anchor_fn: a function, accept anchors, return indices that\n            indicate valid anchors.\n        gt_classes: [num_gt_boxes] int tensor. indicate gt classes, must\n            start with 1.\n        matched_threshold: float, iou greater than matched_threshold will\n            be treated as positives.\n        unmatched_threshold: float, iou smaller than unmatched_threshold will\n            be treated as negatives.\n        positive_fraction: [0-1] float or None. if not None, we will try to\n            keep ratio of pos/neg equal to positive_fraction when sample.\n            if there is not enough positives, it fills the rest with negatives\n        rpn_batch_size: int. sample size\n        norm_by_num_examples: bool. norm box_weight by number of examples, but\n            I recommend to do this outside.\n        box_code_size: int. box coder size\n    Returns:\n        labels, bbox_targets, bbox_outside_weights\n    \"\"\"\n    total_anchors = all_anchors.shape[0]\n    if prune_anchor_fn is not None:\n        inds_inside = prune_anchor_fn(all_anchors)\n        anchors = all_anchors[inds_inside, :]\n        if not isinstance(matched_threshold, float):\n            matched_threshold = matched_threshold[inds_inside]\n        if not isinstance(unmatched_threshold, float):\n            unmatched_threshold = unmatched_threshold[inds_inside]\n    else:\n        anchors = all_anchors\n        inds_inside = None\n    num_inside = len(inds_inside) if inds_inside is not None else total_anchors\n\n    if gt_classes is None:\n        gt_classes = np.ones([gt_boxes.shape[0]], dtype=np.int32)\n    labels = np.empty((num_inside,), dtype=np.int32)\n    gt_ids = np.empty((num_inside,), dtype=np.int32)\n    labels.fill(-1)\n    gt_ids.fill(-1)\n    if np.array(gt_boxes).shape[0] > 0 and anchors.shape[0] > 0:\n        anchor_by_gt_overlap = similarity_fn(anchors, gt_boxes)\n        anchor_to_gt_argmax = anchor_by_gt_overlap.argmax(axis=1)\n        anchor_to_gt_max = anchor_by_gt_overlap[np.arange(num_inside), anchor_to_gt_argmax]\n        gt_to_anchor_argmax = anchor_by_gt_overlap.argmax(axis=0)\n        gt_to_anchor_max = anchor_by_gt_overlap[gt_to_anchor_argmax,\n                                                np.arange(anchor_by_gt_overlap.shape[1])]\n        empty_gt_mask = gt_to_anchor_max == 0\n        gt_to_anchor_max[empty_gt_mask] = -1\n        anchors_with_max_overlap = np.where(anchor_by_gt_overlap == gt_to_anchor_max)[0]\n        gt_inds_force = anchor_to_gt_argmax[anchors_with_max_overlap]\n        labels[anchors_with_max_overlap] = gt_classes[gt_inds_force]\n        gt_ids[anchors_with_max_overlap] = gt_inds_force\n        pos_inds = anchor_to_gt_max >= matched_threshold\n        gt_inds = anchor_to_gt_argmax[pos_inds]\n        labels[pos_inds] = gt_classes[gt_inds]\n        gt_ids[pos_inds] = gt_inds\n        bg_inds = np.where(anchor_to_gt_max < unmatched_threshold)[0]\n    else:\n        bg_inds = np.arange(num_inside)\n    fg_inds = np.where(labels > 0)[0]\n    fg_max_overlap = None\n    if np.array(gt_boxes).shape[0] > 0 and anchors.shape[0] > 0:\n        fg_max_overlap = anchor_to_gt_max[fg_inds]\n    gt_pos_ids = gt_ids[fg_inds]\n    if positive_fraction is not None:\n        num_fg = int(positive_fraction * rpn_batch_size)\n        if len(fg_inds) > num_fg:\n            disable_inds = npr.choice(fg_inds, size=(len(fg_inds) - num_fg), replace=False)\n            labels[disable_inds] = -1\n            fg_inds = np.where(labels > 0)[0]\n\n        num_bg = rpn_batch_size - np.sum(labels > 0)\n        if len(bg_inds) > num_bg:\n            enable_inds = bg_inds[npr.randint(len(bg_inds), size=num_bg)]\n            labels[enable_inds] = 0\n    else:\n        if np.array(gt_boxes).shape[0] == 0 or anchors.shape[0] == 0:\n            labels[:] = 0\n        else:\n            labels[bg_inds] = 0\n            labels[anchors_with_max_overlap] = gt_classes[gt_inds_force]\n    bbox_targets = np.zeros((num_inside, box_code_size), dtype=all_anchors.dtype)\n    if np.array(gt_boxes).shape[0] > 0 and anchors.shape[0] > 0:\n        bbox_targets[fg_inds, :] = box_encoding_fn(gt_boxes[anchor_to_gt_argmax[fg_inds], :],\n                                                   anchors[fg_inds, :])\n\n    bbox_outside_weights = np.zeros((num_inside,), dtype=all_anchors.dtype)\n    if norm_by_num_examples:\n        num_examples = np.sum(labels >= 0)  # neg + pos\n        num_examples = np.maximum(1.0, num_examples)\n        bbox_outside_weights[labels > 0] = 1.0 / num_examples\n    else:\n        bbox_outside_weights[labels > 0] = 1.0\n\n    if inds_inside is not None:\n        labels = unmap(labels, total_anchors, inds_inside, fill=-1)\n        bbox_targets = unmap(bbox_targets, total_anchors, inds_inside, fill=0)\n        bbox_outside_weights = unmap(bbox_outside_weights, total_anchors, inds_inside, fill=0)\n    ret = {\n        \"labels\": labels,\n        \"bbox_targets\": bbox_targets,\n        \"bbox_outside_weights\": bbox_outside_weights,\n        \"assigned_anchors_overlap\": fg_max_overlap,\n        \"positive_gt_id\": gt_pos_ids,\n    }\n    if inds_inside is not None:\n        ret[\"assigned_anchors_inds\"] = inds_inside[fg_inds]\n    else:\n        ret[\"assigned_anchors_inds\"] = fg_inds\n    return ret\n\n\nclass TargetAssigner:\n    \"\"\"target assigner\"\"\"\n\n    def __init__(self,\n                 box_coder,\n                 anchor_generators,\n                 region_similarity_calculator=None,\n                 positive_fraction=None,\n                 sample_size=512):\n        self._region_similarity_calculator = region_similarity_calculator\n        self._box_coder = box_coder\n        self._anchor_generators = anchor_generators\n        self._positive_fraction = positive_fraction\n        self._sample_size = sample_size\n\n    @property\n    def box_coder(self):\n        \"\"\"box coder\"\"\"\n        return self._box_coder\n\n    def assign(self,\n               anchors,\n               gt_boxes,\n               anchors_mask=None,\n               gt_classes=None,\n               matched_thresholds=None,\n               unmatched_thresholds=None):\n        \"\"\"assign\"\"\"\n\n        def similarity_fn(anchors, gt_boxes):\n            \"\"\"similarity fn\"\"\"\n            anchors_rbv = anchors[:, [0, 1, 3, 4, 6]]\n            gt_boxes_rbv = gt_boxes[:, [0, 1, 3, 4, 6]]\n            return self._region_similarity_calculator.compare(anchors_rbv, gt_boxes_rbv)\n\n        def box_encoding_fn(boxes, anchors):\n            \"\"\"box encoding fn\"\"\"\n            return self._box_coder.encode(boxes, anchors)\n\n        if anchors_mask is not None:\n            prune_anchor_fn = lambda _: np.where(anchors_mask)[0]\n        else:\n            prune_anchor_fn = None\n\n        return create_target_np(anchors,\n                                gt_boxes,\n                                similarity_fn,\n                                box_encoding_fn,\n                                prune_anchor_fn=prune_anchor_fn,\n                                gt_classes=gt_classes,\n                                matched_threshold=matched_thresholds,\n                                unmatched_threshold=unmatched_thresholds,\n                                positive_fraction=self._positive_fraction,\n                                rpn_batch_size=self._sample_size,\n                                norm_by_num_examples=False,\n                                box_code_size=self.box_coder.code_size)\n\n    def generate_anchors(self, feature_map_size):\n        \"\"\"generate anchors\"\"\"\n        anchors_list = []\n        matched_thresholds = [\n            a.match_threshold for a in self._anchor_generators\n        ]\n        unmatched_thresholds = [\n            a.unmatch_threshold for a in self._anchor_generators\n        ]\n        match_list, unmatch_list = [], []\n        for anchor_generator, match_thresh, unmatch_thresh in zip(self._anchor_generators,\n                                                                  matched_thresholds,\n                                                                  unmatched_thresholds):\n            anchors = anchor_generator.generate(feature_map_size)\n            anchors = anchors.reshape([*anchors.shape[:3], -1, 7])\n            anchors_list.append(anchors)\n            num_anchors = np.prod(anchors.shape[:-1])\n            match_list.append(np.full([num_anchors], match_thresh, anchors.dtype))\n            unmatch_list.append(np.full([num_anchors], unmatch_thresh, anchors.dtype))\n        anchors = np.concatenate(anchors_list, axis=-2)\n        matched_thresholds = np.concatenate(match_list, axis=0)\n        unmatched_thresholds = np.concatenate(unmatch_list, axis=0)\n        return {\n            \"anchors\": anchors,\n            \"matched_thresholds\": matched_thresholds,\n            \"unmatched_thresholds\": unmatched_thresholds\n        }\n\n    @property\n    def num_anchors_per_location(self):\n        \"\"\"num anchors per location\"\"\"\n        num = 0\n        for a_generator in self._anchor_generators:\n            num += a_generator.num_anchors_per_localization\n        return num\n", "meta": {"hexsha": "65d34a9a4c00f1aa16a68872252948dfda52e53a", "size": 11086, "ext": "py", "lang": "Python", "max_stars_repo_path": "research/cv/pointpillars/src/core/target_assigner.py", "max_stars_repo_name": "mindspore-ai/models", "max_stars_repo_head_hexsha": "9127b128e2961fd698977e918861dadfad00a44c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 77, "max_stars_repo_stars_event_min_datetime": "2021-10-15T08:32:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:09:11.000Z", "max_issues_repo_path": "research/cv/pointpillars/src/core/target_assigner.py", "max_issues_repo_name": "mindspore-ai/models", "max_issues_repo_head_hexsha": "9127b128e2961fd698977e918861dadfad00a44c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-10-30T14:44:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T06:57:57.000Z", "max_forks_repo_path": "research/cv/pointpillars/src/core/target_assigner.py", "max_forks_repo_name": "mindspore-ai/models", "max_forks_repo_head_hexsha": "9127b128e2961fd698977e918861dadfad00a44c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2021-10-15T08:32:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T18:45:20.000Z", "avg_line_length": 41.8339622642, "max_line_length": 94, "alphanum_fraction": 0.6144686993, "include": true, "reason": "import numpy", "num_tokens": 2438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.1894504773185323}}
{"text": "import numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nconfig = tf.compat.v1.ConfigProto()\nconfig.gpu_options.allow_growth = True\nsession = tf.compat.v1.Session(config=config)\nimport matplotlib.pyplot as plt\nimport tensorflow_probability as tfp\ntfd = tfp.distributions\n\nfrom mpi4py import MPI\ncomm = MPI.COMM_WORLD\nrank = comm.Get_rank()\nsize = comm.Get_size()\n\n\nimport argparse\n\nparser = argparse.ArgumentParser(description='Process some integers.')\nparser.add_argument('--jobid', type=int, default=0, help='an integer for the accumulator')\nparser.add_argument('--eps', type=float, default=0.001, help='step size')\nparser.add_argument('--seed', type=int, default=100, help='random seed')\nparser.add_argument('--nc', type=int, default=32, help='mesh size')\nparser.add_argument('--bs', type=float, default=200, help='box size')\nparser.add_argument('--suffix', type=str, default=\"\", help='suffix to fpath')\nparser.add_argument('--nR', type=int, default=0, help=\"number of smoothings\")\nparser.add_argument('--scaleprior', type=int, default=1, help=\"add power to scale to prior\")\nparser.add_argument('--nchains', type=int, default=1, help=\"number of chains\")\nparser.add_argument('--debug', type=int, default=0, help=\"debug run\")\nparser.add_argument('--reconiter', type=int, default=100, help=\"number of iterations for reconstruction\")\nparser.add_argument('--burnin', type=int, default=200, help=\"number of iterations for burnin\")\nparser.add_argument('--tadapt', type=int, default=50, help=\"number of iterations for eps adaptation\")\nparser.add_argument('--ntrain', type=int, default=10, help=\"number of training iterations\")\nparser.add_argument('--prentrain', type=int, default=200, help=\"number of training iterations\")\nparser.add_argument('--thinning', type=int, default=10, help=\"thinning\")\nparser.add_argument('--kwts', type=int, default=4, help='number of trenf layers')\nparser.add_argument('--lpsteps1', type=int, default=25, help=\"min leapfrog steps\")\nparser.add_argument('--lpsteps2', type=int, default=50, help=\"max leapfrog steps\")\nparser.add_argument('--mcmciter', type=int, default=5, help=\"number of only mcmc iterations\")\nparser.add_argument('--order', type=int, default=1, help=\"ZA or LPT\")\n#\nparser.add_argument('--mode', type=str, default=\"classic\", help='mode for trenf')\nparser.add_argument('--nlayers', type=int, default=3, help='number of trenf layers')\nparser.add_argument('--nbins', type=int, default=32, help=\"number of bins in trenf spline\")\nparser.add_argument('--fitnoise', type=int, default=1, help='fitnoise')\nparser.add_argument('--fitscale', type=int, default=1, help='fitscale')\nparser.add_argument('--fitmean', type=int, default=1, help='fitmean')\nparser.add_argument('--meanfield', type=int, default=1, help='meanfield for affine')\nparser.add_argument('--nknots', type=int, default=100, help='number of trenf layers')\nparser.add_argument('--linknots', type=int, default=0, help='linear spacing for knots')\n#\nparser.add_argument('--probjump', type=float, default=0.3, help='probability of jump')\nparser.add_argument('--regwt0', type=float, default=0., help='regularization weight')\n\nargs = parser.parse_args()\ndevice = args.jobid\nsuffix = args.suffix\n\nfrom tensorflow.python.client import device_lib\n\ndef get_available_gpus():\n    local_device_protos = device_lib.list_local_devices()\n    return [x.name for x in local_device_protos if x.device_type == 'GPU']\n#print(\"\\nDevice name\\n\", tf.test.gpu_device_name(), \"\\n\")\nprint(\"\\nDevices\\n\", get_available_gpus())\n\n\nimport sys, os, time\nimport flowpm\nsys.path.append('../../galference/utils/')\nimport tools\nimport diagnostics as dg\n\nsys.path.append('../src/')\nfrom pmfuncs import Evolve\nfrom pyhmc import PyHMC, PyHMC_batch, DualAveragingStepSize\nfrom trenfmodel import VItrenf\nfrom hmcfuncs import DM_config, DM_fourier, Kwts\nimport recon, trenfmodel\nfrom callback import callback, datafig, callback_fvi, callback_sampling\n\n##########\nnchains = args.nchains\nreconiter = args.reconiter\nburnin = args.burnin\nmcmciter = args.mcmciter\nntrain = args.ntrain\ntadapt = args.tadapt\nthinning = args.thinning\nlpsteps1, lpsteps2 = args.lpsteps1, args.lpsteps2\nnsamples = 1\nprentrain = args.prentrain\nnR = args.nR\nregwt0 = args.regwt0\nrecalib = 1\n#\nif args.debug:\n    reconiter = 5\n    burnin = 5\n    mcmciter = 5\n    tadapt = 5\n    thinning = 2 \n    lpsteps1, lpsteps2 = 3, 5\n    nsamples = 1\n    prentrain = 10\n    nR = 0 \nprobjump = args.probjump\nallRs = [0., 1., 2., 4.]\nallR = allRs[:nR + 1][::-1]\n\n#\nbs, nc = args.bs, args.nc\nnsteps = 3\na0, af, nsteps = 0.1, 1.0,  nsteps\nstages = np.linspace(a0, af, nsteps, endpoint=True)\nnsims = 200\ndonbody = False\norder = args.order\nshotnoise = bs**3/nc**3\ndnoise = 1. #shotnoise/nc**1.5  \nif donbody: fpath = '/mnt/ceph/users/cmodi/galference/dm_fvi/L%04d_N%04d_T%02d'%(bs, nc, nsteps)\nelif order == 2: fpath = '/mnt/ceph/users/cmodi/galference/dm_fvi/L%04d_N%04d_LPT'%(bs, nc)\nelif order == 1: fpath = '/mnt/ceph/users/cmodi/galference/dm_fvi/L%04d_N%04d_ZA'%(bs, nc)\nif suffix == \"\": fpath = fpath + '/'\nelse: fpath = fpath + \"-\" + suffix + '/'\nos.makedirs('%s'%fpath, exist_ok=True)\nos.makedirs('%s'%fpath + '/figs/', exist_ok=True)\nos.makedirs('%s'%fpath + '/opt/', exist_ok=True)\nos.makedirs('%s'%fpath + '/weights/', exist_ok=True)\nos.makedirs('%s'%fpath + '/burnin/', exist_ok=True)\n\n\nevolve = Evolve(nc, bs, a0=a0, af=af, nsteps = nsteps, donbody=donbody, order=order)     \n\n##############################################\n##Generate DATA\nprint(\"\\nFor seed : \", args.seed)\nnp.random.seed(args.seed)\nzic = np.random.normal(0, 1, nc**3).reshape(1, nc, nc, nc).astype(np.float32)\nnoise = np.random.normal(0, dnoise, nc**3).reshape(1, nc, nc, nc).astype(np.float32)\nic = evolve.z_to_lin(zic).numpy()\nfin = evolve.pm(tf.constant(ic)).numpy()\ndata = fin + noise\ndata = data.astype(np.float32)\ntfdata = tf.constant(data)\ntfnoise = tf.constant(dnoise)\nnp.save(fpath + 'ic', ic)\nnp.save(fpath + 'fin', fin)\nnp.save(fpath + 'data', data)\nfig = datafig(ic, fin, data, bs, dnoise)\nplt.savefig(fpath + 'data')\nplt.close()\nk, pic = tools.power(ic[0], boxsize=bs)\nk, pf = tools.power(fin[0], boxsize=bs)\nk, pd = tools.power(data[0], boxsize=bs)\nk, pn = tools.power(1+noise[0], boxsize=bs)\nknoise = evolve.kmesh[evolve.kmesh > k[(pn > pf)][0]].min()\nprint(\"Noise dominated after : \", knoise, (evolve.kmesh > knoise).sum()/nc**3)\n\n    \ndmfuncs = DM_fourier(evolve, tfdata, dnoise=dnoise)\nkwts = Kwts(evolve, mode=args.kwts, knoise=knoise)\npy_log_prob = lambda x: dmfuncs.unnormalized_log_prob(tf.constant(x, dtype=tf.float32), tf.constant(1.)).numpy().astype(np.float32)\npy_grad_log_prob = lambda x: dmfuncs.grad_log_prob(tf.constant(x, dtype=tf.float32), tf.constant(1.)).numpy().astype(np.float32)\nhmckernel = PyHMC_batch(py_log_prob, py_grad_log_prob, invmetric_diag=kwts.kwts, returnV=True)\nepsadapt = DualAveragingStepSize(args.eps)\nstepsize = args.eps\nsamples, pyacc = [], []\n\nprint(\"HMC kernels setup\")\n##############################################\n\n\n\n\ndef flow_step(model, x, lpx):\n    nsamples = x.shape[0]\n    xk = tf.identity(x)\n    x = evolve.zk_to_z(x)\n    lqx = model.q.log_prob(x)\n    \n    y = model.q.sample(nsamples)*1.\n    yk = evolve.z_to_zk(y)\n    lpy = dmfuncs.unnormalized_log_prob(yk)\n    lqy = model.q.log_prob(y)\n    print(tf.stack([lpx, lpy, lqx, lqy], axis=0).numpy())\n    prob = tf.exp((lpy - lpx)/nc**3 + lqx - lqy)\n    #prob = tf.exp((lpy - lpx + lqx - lqy))\n\n    accept = tf.where(tf.random.uniform([1]) <= tf.minimum(1., prob))\n    reject = tf.where(tf.random.uniform([1]) > tf.minimum(1., prob))\n    z = tf.scatter_nd(accept, tf.gather_nd(yk, accept), yk.shape) + \\\n         tf.scatter_nd(reject, tf.gather_nd(xk, reject), yk.shape)\n\n    lpz = tf.where(tf.random.uniform([1]) <= tf.minimum(1., prob), lpy, lpx)\n    acc = tf.where(tf.random.uniform([1]) <= tf.minimum(1., prob), tf.ones(lpx.shape)*11, tf.ones(lpx.shape)*10.)\n    return z, lpz, prob, acc, tf.constant(1.)\n\n\ndef mcmc_step(q, stepsize):\n    #stepsize = np.random.uniform(0.01, 0.02, 1)\n    lpsteps = np.random.randint(lpsteps1, lpsteps2, 1)[0]\n    print(\"mcmc : \", q.shape)\n    q, _, acc, prob, _ = hmckernel.hmc_step(q.numpy(), lpsteps, stepsize)\n    lpq = tf.constant(prob[2]*-1.)\n    prob = np.exp(prob[0] - prob[1])\n    q = tf.constant(q, dtype=tf.float32)\n    return q, lpq, tf.constant(prob), tf.constant(acc*1.), tf.constant(0.)\n\n\n#@tf.function\ndef fvi(model, q, logpq, i, stepsize):   \n    \n    elbos = []\n    start = time.time()\n    if i < mcmciter:\n        print(\"MCMC only\")\n        q, logpq, prob, acc, jump =  mcmc_step(q, stepsize)\n    else:    \n        q, logpq, prob, acc, jump = tf.cond(tf.random.uniform([1]) > probjump, \\\n                                      lambda : mcmc_step(q, stepsize), \\\n                            lambda : flow_step(model, q, logpq))\n        if jump == 1:\n            for _ in range(recalib):\n                print(\"Jump, recaliberate\")\n                q, logpq, prob2, acc2, jump2 =  mcmc_step(q, stepsize)\n                \n            \n    print(\"prob \", prob.numpy(), \"to accept/reject with \", acc.numpy(), \" in time %0.3f\"%(time.time() - start))\n    return q, logpq, acc, jump\n\n\n@tf.function\ndef fvi_grads(model, samples, opt, samples2, regwt):\n    samples = evolve.zk_to_z(samples)    \n    with tf.GradientTape(persistent=True) as tape:\n        tape.watch(model.trainable_variables)\n        #q, logpq, acc = fvi_step(model, q, logpq)\n        neglogq = - tf.reduce_mean(model.q.log_prob(samples))\n        if regwt0 ==  0:\n            loss = neglogq*1.\n        else:\n            logq2 = - tf.reduce_mean(model.q.log_prob(evolve.zk_to_z(samples2)))\n            samplevi = model.sample(samples.shape[0])*1.\n            logqvi = - tf.reduce_mean(model.q.log_prob(samplevi))\n            reg = regwt * tf.reduce_mean((logq2 - logqvi)**2.)\n            loss = neglogq + reg\n            \n    gradients = tape.gradient(loss, model.trainable_variables)\n    return neglogq, gradients\n\n\n\ndef fvi_train(model, samples, opt, batch2, regwt):\n    neglogq, gradients = fvi_grads(model, samples, opt, batch2, regwt)\n    opt.apply_gradients(zip(gradients, model.trainable_variables))\n    return neglogq\n\n\n\n\ndef optimizetrenf(model, data, opt,  Rsm, niter=100, callback=callback, citer=50, nsamples=1, saveiter=20, sample=None, batch_size=1, stepsize=0.01, samples=[]):\n    \n    pss, psslin, pssx = [], [], []\n    if sample is None: \n        sample = tf.random.normal([nsamples, nc, nc, nc])\n    logpsample = dmfuncs.unnormalized_log_prob(sample)\n        \n    accs, losses = [], []\n    samples.append(sample)\n    idxtrain = list(np.arange(len(samples)))\n    #\n    start = time.time()\n    #dry run\n    sample, logpsample, acc, jump = fvi(model, sample, logpsample, 0, stepsize)\n    print(sample.shape, samples[0].shape, samples[-1].shape)\n    accs.append(acc)\n    #samples.append(sample)\n    #idxtrain = idxtrain + [len(samples)-1]\n    trainsize = len(samples)\n    print(\"Training size of %d is maintained\"%trainsize)\n    for epoch in range(niter+1):\n        print(epoch)\n        sample, logpsample, acc, jump = fvi(model, sample, logpsample, epoch, stepsize)\n        accs.append(acc)\n        #save power spectrum\n        if sample.shape[-1] == 2:\n            ssz = evolve.zk_to_z(sample).numpy()\n        else: ssz = tf.identity(sample)\n        sslin = evolve.z_to_lin(tf.constant(ssz)).numpy()\n        pss.append([tools.power(j+1, boxsize=evolve.bs)[1] for j in ssz])\n        psslin.append([tools.power(j+1, boxsize=evolve.bs)[1] for j in sslin])\n        pssx.append([tools.power(j+1, ic[0] + 1, boxsize=evolve.bs)[1] for j in sslin])\n        samples.append(sample)\n        idxtrain = idxtrain + [len(samples)-1]\n        print(max(idxtrain), len(idxtrain), len(samples))\n        if (epoch > 0) & (epoch %100 == 0): \n            ntrain = 500\n            print(\"Train %d times to recaliberate\"%ntrain)\n        else: ntrain = args.ntrain\n        for itrain in range(ntrain):\n            if jump == 1: \n                print(\"Jump, no train\")\n                break\n            if itrain == 0: idxsample = idxtrain[-batch_size:]\n            else: idxsample = np.random.choice(idxtrain, batch_size, replace=False)\n            #$# idxsample = np.random.choice(idx, batch_size, p=idx/idx.sum(), replace=False)\n            idlast = min(-1 * np.random.choice(10), -1)\n            idxsample = [idlast] + list(idxsample)\n            print(itrain, \", idx :\", idxsample)\n            batch = tf.concat([samples[i] for i in idxsample], axis=0)\n            batch2, regwt = None, tf.constant(regwt0)\n            if regwt0 != 0.:\n                if itrain == 0: idxsample = idxtrain[-batch_size:]\n                else: idxsample = np.random.choice(idxtrain, batch_size, replace=False)\n                #idxsample = idxtrain[np.random.choice(np.arange(trainsize), batch_size, replace=False)]\n                idxsample = list(idxsample)\n                print(\"idx2 :\", idxsample)\n                batch2 = tf.concat([samples[i] for i in idxsample], axis=0)\n            loss = fvi_train(model, batch, opt, batch2, regwt)\n            losses.append(loss/nc**3)\n        print(\"Logq at epoch %d is: \"%epoch, loss.numpy())\n        #iddel = np.random.randint(trainsize)\n        #print(\"Remove index from train : %d \"%idxtrain[iddel])\n        #del idxtrain[iddel]\n\n        if epoch%citer == 0: \n            print(\"pss shape \", pss[-1][0].shape, len(pss[-1]))\n            print(\"Time taken for %d iterations : \"%citer, time.time() - start)\n            print(\"Accept counts : \", np.unique(accs, return_counts=True))\n            #\n            fig = callback_fvi(model, ic, bs, losses)\n            plt.savefig(fpath + '/figs/iter%05d'%epoch)\n            plt.close()\n\n            #\n            fig = callback_sampling([evolve.zk_to_lin(i) for i in samples[-2:]], ic, bs)\n            plt.savefig(fpath + '/figs/samples%05d'%epoch)\n            plt.close()\n            np.save(fpath + 'loss', np.array(losses))\n            np.save(fpath + 'samples', np.array(samples))\n            np.save(fpath + '/psz', pss)\n            np.save(fpath + '/pslin', psslin) #\n            np.save(fpath + '/pslinx', pssx) #\n            np.save(fpath + 'samplesthin%d'%thinning, np.array(samples)[::thinning])\n            np.save(fpath + 'accepts', np.array(accs))\n            start = time.time()\n        if epoch%saveiter == 0: \n            model.save_weights(fpath + '/weights/iter%04d'%(epoch//saveiter))\n            #np.save(fpath + '/opt/iter%04d'%(epoch//saveiter), opt.get_weights(), allow_pickle=True)\n            #print('Weights saved')\n            \n    return losses \n\n\n\n\n#$####################################################################################\n#$################################################################\n###################VI\nprint(\"\\nStart VI\\n\")\n#vitrenf = trenfmodel.VItrenf(nc, nlayers=args.nlayers, evolve=evolve, nbins=32, mode=args.mode)\nvitrenf = trenfmodel.VItrenf(nc, nlayers=args.nlayers, evolve=evolve, nbins=args.nbins, nknots=args.nknots, mode=args.mode, \\\n                             linknots=bool(args.linknots), fitnoise=bool(args.fitnoise), fitscale=bool(args.fitscale), \\\n                             fitmean=bool(args.fitmean), meanfield=bool(args.meanfield))\nfor i in vitrenf.variables:\n    print(i.name, i.shape)\n\n\nlr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(\n    5e-3,\n    decay_steps=200,\n    decay_rate=0.95,\n    staircase=True)\n\n#Train FLOW using previos samples assuming we have them\nprint(\"Load old samples\")\nsamplepath = '/mnt/ceph/users/cmodi/galference/dm_hmc/L1000_N0128_ZA-kwts4-fourier-corr/'\n#samplepath = '/mnt/ceph/users/cmodi/galference/dm_hmc/L0200_N0064_ZA-fourier-minlininit2/'\nallsamples = []\nperchain = 201\nfor i in range(nchains):\n    f = np.load(samplepath + '/samples%d-00.npy'%i)[:perchain, 0]\n    allsamples.append(f)\nallsamples = np.stack(allsamples, axis=1).astype(np.float32)\nprint(allsamples.shape)\nstepsize = np.array([np.load(samplepath + '/stepsizes%d-00.npy'%i) for i in range(nchains)]).flatten()\nprint(\"stepsize : \", stepsize)\n\nlosses = []\n\nopt = tf.keras.optimizers.Adam(learning_rate= lr_schedule)\n#opt = tf.keras.optimizers.RMSprop(learning_rate= 1e-3)\nsaveiter = 100\n\nprint(\"Train on old samples\")\nfor i in range(prentrain+1):\n    \n    for itrain in range(min(ntrain, int(ntrain*(2*i/prentrain)))):\n    \n        #idx = np.random.choice(i + 1, size=nsamples+1)\n        idx = np.random.choice(allsamples.shape[0], size=nsamples+1)\n        #idx = [-1] + list(idx)\n        batch = tf.concat([allsamples[i] for i in idx], axis=0)\n        #batch = tf.concat(allsamples[idx], axis=0)\n        batch2, regwt = None, None\n        if regwt0 !=0 :\n            batch2 = tf.concat(allsamples[np.random.choice(allsamples.shape[0], nsamples)], axis=0)\n            regwt = tf.constant(args.regwt0*i/prentrain)\n        losses.append(fvi_train(vitrenf, batch, opt, batch2, regwt))\n        #if itrain == 0: print(idx, batch.shape)\n    if i%10 == 0: \n        print(\"Iter : \", i)\n        fig = callback_fvi(vitrenf, ic, bs, losses)\n        plt.savefig(fpath + 'figs/trainr%05d'%i)\n        plt.close()\n\n#$#        lqs = []\n#$#        for j in range(allsamples.shape[0]//10):\n#$#            batch = tf.concat(evolve.zk_to_z(allsamples[j:j+2]), axis=0)\n#$#            lq = vitrenf.q.log_prob(batch).numpy()\n#$#            lqs = lqs + list(lq.flatten())\n#$#        plt.plot(lqs, '.', label='train samples', lw=2)\n#$#\n#$#        lqs = []\n#$#        for j in range(allsamples.shape[0]//10):\n#$#            batch = vitrenf.sample(nchains)\n#$#            lq = vitrenf.q.log_prob(batch).numpy()\n#$#            lqs = lqs + list(lq.flatten())\n#$#        plt.plot(lqs, '.', label='flow samples', lw=2)\n#$#        plt.legend()\n#$#        plt.savefig(fpath + '/figs/lgoqtrain%05d'%i)\n#$#        plt.close()\n#$#\n    if (i > 0) & (i%saveiter == 0): \n        vitrenf.save_weights(fpath + '/weights/preiter%04d'%(i//saveiter))\n\n\n\nplt.imshow(vitrenf.sample(1)[0].numpy().sum(axis=0))\nplt.colorbar()\nplt.savefig(fpath + 'initsample')\nplt.colorbar()\nplt.close()\n\nsample = tf.constant(allsamples[-1])\nprint(sample.shape)\nR = 0.\n\nopt2 = tf.keras.optimizers.Adam(learning_rate= 1e-3)\nbatch = tf.concat([allsamples[i] for i in idx], axis=0)\n_ = fvi_train(vitrenf, batch, opt2, batch2, regwt)\nopt2.set_weights(opt.get_weights())\n\nlosses = optimizetrenf(vitrenf, tf.constant(data), opt2, tf.constant(R), 5001, callback, citer=10, sample=sample, stepsize=stepsize, samples=list(allsamples[::thinning]))\n\n\n\n\n\n\n#$#            #\n#$#            lqs = []\n#$#            for j in range(10):\n#$#                idxsample = np.random.choice(idxtrain, batch_size, replace=False)\n#$#                idxsample = list(idxsample)\n#$#                try:\n#$#                    print(idxsample)\n#$#                    batch = tf.concat([samples[i:i+2] for i in list(idxsample)], axis=0)\n#$#                    batch = evolve.zk_to_z(batch)\n#$#                    lq = model.q.log_prob(batch).numpy()\n#$#                    plt.plot(lq.flatten(), 'C0.')\n#$#                    lqs = lqs + list(lq.flatten())\n#$#                    #plt.plot(lqs, '.', label='train samples', lw=2)\n#$#                except Exception as e:\n#$#                    print(e)\n#$#            lqs = []\n#$#            for j in range(10):\n#$#                try:\n#$#                    batch = model.sample(nchains)\n#$#                    lq = model.q.log_prob(batch).numpy()\n#$#                    lqs = lqs + list(lq.flatten())\n#$#                    plt.plot(lq.flatten(), 'C1.', lw=2)\n#$#                except Exception as e:\n#$#                    print(e)\n#$#            plt.savefig(fpath + '/figs/lgoqiter%05d'%epoch)\n#$#            plt.close()\n#$#\n", "meta": {"hexsha": "c34c52810755fde07640ff3940cd7e85f99db527", "size": 19705, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/fvi_trenf_phase3128.py", "max_stars_repo_name": "modichirag/VI_reconstruction", "max_stars_repo_head_hexsha": "64def5226a5723877a60943c29f592319bbe8e95", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/fvi_trenf_phase3128.py", "max_issues_repo_name": "modichirag/VI_reconstruction", "max_issues_repo_head_hexsha": "64def5226a5723877a60943c29f592319bbe8e95", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/fvi_trenf_phase3128.py", "max_forks_repo_name": "modichirag/VI_reconstruction", "max_forks_repo_head_hexsha": "64def5226a5723877a60943c29f592319bbe8e95", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0508130081, "max_line_length": 170, "alphanum_fraction": 0.619791931, "include": true, "reason": "import numpy", "num_tokens": 5623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.18945047731853226}}
{"text": "# Very slightly adapted from perses https://github.com/choderalab/perses\n# License: MIT\n# OpenFE note: eventually we aim to move this to openmmtools where possible\n\nimport numpy as np\nimport warnings\nimport copy\nfrom openmmtools.alchemy import AlchemicalState\n\n\nclass LambdaProtocol(object):\n    \"\"\"Protocols for perturbing each of the compent energy terms in alchemical\n    free energy simulations.\n\n    TODO\n    ----\n    * Class needs cleaning up and made more consistent\n    \"\"\"\n\n    default_functions = {'lambda_sterics_core':\n                         lambda x: x,\n                         'lambda_electrostatics_core':\n                         lambda x: x,\n                         'lambda_sterics_insert':\n                         lambda x: 2.0 * x if x < 0.5 else 1.0,\n                         'lambda_sterics_delete':\n                         lambda x: 0.0 if x < 0.5 else 2.0 * (x - 0.5),\n                         'lambda_electrostatics_insert':\n                         lambda x: 0.0 if x < 0.5 else 2.0 * (x - 0.5),\n                         'lambda_electrostatics_delete':\n                         lambda x: 2.0 * x if x < 0.5 else 1.0,\n                         'lambda_bonds':\n                         lambda x: x,\n                         'lambda_angles':\n                         lambda x: x,\n                         'lambda_torsions':\n                         lambda x: x\n                         }\n\n    # lambda components for each component,\n    # all run from 0 -> 1 following master lambda\n    def __init__(self, functions='default', windows=10, lambda_schedule=None):\n        \"\"\"Instantiates lambda protocol to be used in a free energy\n        calculation. Can either be user defined, by passing in a dict, or using\n        one of the pregenerated sets by passing in a string 'default', 'namd'\n        or 'quarters'\n\n        All protocols must begin and end at 0 and 1 respectively. Any energy\n        term not defined in `functions` dict will be set to the function in\n        `default_functions`\n\n        Pre-coded options:\n        default : ele and LJ terms of the old system are turned off between\n        0.0 -> 0.5 ele and LJ terms of the new system are turned on between\n        0.5 -> 1.0 core terms treated linearly\n\n        quarters : 0.25 of the protocol is used in turn to individually change\n        the (a) off old ele, (b) off old sterics, (c) on new sterics (d) on new\n        ele core terms treated linearly\n\n        namd : follows the protocol outlined here:\n        https://pubs.acs.org/doi/full/10.1021/acs.jcim.9b00362#\n        Jiang, Wei, Christophe Chipot, and Benoît Roux. \"Computing Relative\n        Binding Affinity of Ligands to Receptor: An Effective Hybrid\n        Single-Dual-Topology Free-Energy Perturbation Approach in NAMD.\"\n        Journal of chemical information and modeling 59.9 (2019): 3794-3802.\n\n        ele-scaled : all terms are treated as in default, except for the old\n        and new ele these are scaled with lambda^0.5, so as to be linear in\n        energy, rather than lambda\n\n        Parameters\n        ----------\n        functions : str or dict\n            One of the predefined lambda protocols\n            ['default','namd','quarters'] or a dictionary. Default \"default\".\n        windows : int\n            Number of windows which this lambda schedule is intended to be used\n            with. This value is used to validate the lambda function.\n        lambda_schedule : list of floats\n            Schedule of lambda windows to be sampled. If ``None`` will default\n            to a linear spacing of windows as defined by\n            ``np.linspace(0. ,1. ,windows)``. Default ``None``.\n\n        Attributes\n        ----------\n        functions : dict\n            Lambda protocol to be used.\n        lambda_schedule : list\n            Schedule of windows to be sampled.\n        \"\"\"\n        self.functions = copy.deepcopy(functions)\n\n        # set the lambda schedule\n        self.lambda_schedule = self._validate_schedule(lambda_schedule,\n                                                       windows)\n        if lambda_schedule:\n            self.lambda_schedule = lambda_schedule\n        else:\n            self.lambda_schedule = np.linspace(0., 1., windows)\n\n        if type(self.functions) == dict:\n            self.type = 'user-defined'\n        elif type(self.functions) == str:\n            self.functions = None  # will be set later\n            self.type = functions\n\n        if self.functions is None:\n            if self.type == 'default':\n                self.functions = copy.deepcopy(\n                                     LambdaProtocol.default_functions)\n            elif self.type == 'namd':\n                self.functions = {\n                    'lambda_sterics_core': lambda x: x,\n                    'lambda_electrostatics_core': lambda x: x,\n                    'lambda_sterics_insert': lambda x: (3. / 2.) * x if x < (2. / 3.) else 1.0,\n                    'lambda_sterics_delete': lambda x: 0.0 if x < (1. / 3.) else (x - (1. / 3.)) * (3. / 2.),\n                    'lambda_electrostatics_insert': lambda x: 0.0 if x < 0.5 else 2.0 * (x - 0.5),\n                    'lambda_electrostatics_delete': lambda x: 2.0 * x if x < 0.5 else 1.0,\n                    'lambda_bonds': lambda x: x,\n                    'lambda_angles': lambda x: x,\n                    'lambda_torsions': lambda x: x\n                }\n            elif self.type == 'quarters':\n                self.functions = {\n                    'lambda_sterics_core': lambda x: x,\n                    'lambda_electrostatics_core': lambda x: x,\n                    'lambda_sterics_insert': lambda x: 0. if x < 0.5 else 1 if x > 0.75 else 4 * (x - 0.5),\n                    'lambda_sterics_delete': lambda x: 0. if x < 0.25 else 1 if x > 0.5 else 4 * (x - 0.25),\n                    'lambda_electrostatics_insert': lambda x: 0. if x < 0.75 else 4 * (x - 0.75),\n                    'lambda_electrostatics_delete': lambda x: 4.0 * x if x < 0.25 else 1.0,\n                    'lambda_bonds': lambda x: x,\n                    'lambda_angles': lambda x: x,\n                    'lambda_torsions': lambda x: x\n                }\n            elif self.type == 'ele-scaled':\n                self.functions = {\n                    'lambda_electrostatics_insert': lambda x: 0.0 if x < 0.5 else ((2*(x-0.5))**0.5),\n                    'lambda_electrostatics_delete': lambda x: (2*x)**2 if x < 0.5 else 1.0\n                }\n            elif self.type == 'user-defined':\n                self.functions = functions\n            else:\n                errmsg = f\"LambdaProtocol type : {self.type} not recognised \"\n                raise ValueError(errmsg)\n\n        self._validate_functions(n=windows)\n        self._check_for_naked_charges()\n\n    @staticmethod\n    def _validate_schedule(schedule, windows):\n        \"\"\"\n        Checks that the input lambda schedule is valid.\n\n        Rules are:\n          - Must begin at 0 and end at 1\n          - Must be monotonically increasing\n\n        Parameters\n        ----------\n        schedule : list of floats\n            The lambda schedule. If ``None`` the method returns\n            ``np.linspace(0. ,1. ,windows)``.\n        windows : int\n            Number of windows to be sampled.\n\n        Returns\n        -------\n        schedule : list of floats\n            A valid lambda schedule.\n        \"\"\"\n        if schedule is None:\n            return np.linspace(0., 1., windows)\n\n        # Check end states\n        if schedule[0] != 0 or schedule[-1] != 1:\n            errmsg = (\"end and start lambda windows must be lambda 0 and 1 \"\n                      \"respectively\")\n            raise ValueError(errmsg)\n\n        # Check monotonically increasing\n        difference = np.diff(schedule)\n\n        if not all(i >= 0. for i in difference):\n            errmsg = \"The lambda schedule is not monotonic\"\n            raise ValueError(errmsg)\n\n        return schedule\n\n    def _validate_functions(self, n=10):\n        \"\"\"Ensures that all the lambda functions adhere to the rules:\n            - must begin at 0.\n            - must finish at 1.\n            - must be monotonically increasing\n\n        Parameters\n        ----------\n        n : int, default 10\n            number of grid points used to check monotonicity\n        \"\"\"\n        # the individual lambda functions that must be defined for\n        required_functions = list(LambdaProtocol.default_functions.keys())\n\n        for function in required_functions:\n            if function not in self.functions:\n                # IA switched from warn to error here\n                errmsg = (f\"function {function} is missing from \"\n                          \"self.lambda_functions.\")\n                raise ValueError(errmsg)\n\n            # Check that the function starts and ends at 0 and 1 respectively\n            if self.functions[function](0) != 0:\n                raise ValueError(\"lambda functions must start at 0\")\n            if self.functions[function](1) != 1:\n                raise ValueError(\"lambda fucntions must end at 1\")\n\n            # now validatate that it's monotonic\n            global_lambda = np.linspace(0., 1., n)\n            sub_lambda = [self.functions[function](lam) for\n                          lam in global_lambda]\n            difference = np.diff(sub_lambda)\n\n            if not all(i >= 0. for i in difference):\n                wmsg = (f\"The function {function} is not monotonic as \"\n                        \"typically expected.\")\n                warnings.warn(wmsg)\n\n    def _check_for_naked_charges(self):\n        \"\"\"\n        Checks that there are no cases where atoms have charge but no sterics.\n\n        This avoids issues with singularities and/or excessive forces near\n        the end states (even when using softcore electrostatics).\n        \"\"\"\n        global_lambda = self.lambda_schedule\n\n        def check_overlap(ele, sterics, global_lambda, functions, endstate):\n            for lam in global_lambda:\n                ele_val = functions[ele](lam)\n                ster_val = functions[sterics](lam)\n                # if charge > 0 and sterics == 0 raise error\n                if ele_val != endstate and ster_val == endstate:\n                    errmsg = (\"There are states along this lambda schedule \"\n                              \"where there are atoms with charges but no LJ \"\n                              f\"interactions: {lam} {ele_val} {ster_val}\")\n                    raise ValueError(errmsg)\n\n        # checking unique new terms first\n        ele = 'lambda_electrostatics_insert'\n        sterics = 'lambda_sterics_insert'\n        check_overlap(ele, sterics, global_lambda, self.functions, endstate=0)\n\n        # checking unique old terms now\n        ele = 'lambda_electrostatics_delete'\n        sterics = 'lambda_sterics_delete'\n        check_overlap(ele, sterics, global_lambda, self.functions, endstate=1)\n\n    def get_functions(self):\n        return self.functions\n\n    def plot_functions(self, lambda_schedule=None):\n        \"\"\"\n        Plot the function for ease of visualisation.\n\n        Parameters\n        ----------\n        shedule : np.ndarray\n            The lambda schedule to plot the function along. If ``None`` plot\n            the one stored within this class. Default ``None``.\n        \"\"\"\n        import matplotlib.pyplot as plt\n\n        fig = plt.figure(figsize=(10, 5))\n\n        global_lambda = lambda_schedule if lambda_schedule else self.lambda_schedule\n\n        for f in self.functions:\n            plt.plot(global_lambda,\n                     [self.functions[f](lam) for lam in global_lambda],\n                     alpha=0.5, label=f)\n\n        plt.xlabel('global lambda')\n        plt.ylabel('sub-lambda')\n        plt.legend()\n        plt.show()\n\n\nclass RelativeAlchemicalState(AlchemicalState):\n    \"\"\"\n    Relative AlchemicalState to handle all lambda parameters required for\n    relative perturbations\n    lambda = 1 refers to ON, i.e. fully interacting while\n    lambda = 0 refers to OFF, i.e. non-interacting with the system\n    all lambda functions will follow from 0 -> 1 following the master lambda\n    lambda*core parameters perturb linearly\n    lambda_sterics_insert and lambda_electrostatics_delete perturb in the\n    first half of the protocol 0 -> 0.5\n    lambda_sterics_delete and lambda_electrostatics_insert perturb in the\n    second half of the protocol 0.5 -> 1\n\n    Attributes\n    ----------\n    lambda_sterics_core\n    lambda_electrostatics_core\n    lambda_sterics_insert\n    lambda_sterics_delete\n    lambda_electrostatics_insert\n    lambda_electrostatics_delete\n    \"\"\"\n\n    class _LambdaParameter(AlchemicalState._LambdaParameter):\n        pass\n\n    lambda_sterics_core = _LambdaParameter('lambda_sterics_core')\n    lambda_electrostatics_core = _LambdaParameter('lambda_electrostatics_core')\n    lambda_sterics_insert = _LambdaParameter('lambda_sterics_insert')\n    lambda_sterics_delete = _LambdaParameter('lambda_sterics_delete')\n    lambda_electrostatics_insert = _LambdaParameter(\n                                       'lambda_electrostatics_insert')\n    lambda_electrostatics_delete = _LambdaParameter(\n                                      'lambda_electrostatics_delete')\n\n    def set_alchemical_parameters(self, global_lambda,\n                                  lambda_protocol=LambdaProtocol()):\n        \"\"\"Set each lambda value according to the lambda_functions protocol.\n        The undefined parameters (i.e. those being set to None) remain\n        undefined.\n        Parameters\n        ----------\n        lambda_value : float\n            The new value for all defined parameters.\n        \"\"\"\n        self.global_lambda = global_lambda\n        for parameter_name in lambda_protocol.functions:\n            lambda_value = lambda_protocol.functions[parameter_name](global_lambda)\n            setattr(self, parameter_name, lambda_value)\n", "meta": {"hexsha": "71ba312858d2e3a42588030576ee971e1c062377", "size": 13859, "ext": "py", "lang": "Python", "max_stars_repo_path": "openfe/setup/_rbfe_utils/lambdaprotocol.py", "max_stars_repo_name": "mikemhenry/openfe", "max_stars_repo_head_hexsha": "d4c78af62a7ae05b99eb95d173661ac134b7e7b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2022-01-24T22:01:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:58:35.000Z", "max_issues_repo_path": "openfe/setup/_rbfe_utils/lambdaprotocol.py", "max_issues_repo_name": "mikemhenry/openfe", "max_issues_repo_head_hexsha": "d4c78af62a7ae05b99eb95d173661ac134b7e7b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 109, "max_issues_repo_issues_event_min_datetime": "2022-01-24T18:57:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:13:07.000Z", "max_forks_repo_path": "openfe/setup/_rbfe_utils/lambdaprotocol.py", "max_forks_repo_name": "mikemhenry/openfe", "max_forks_repo_head_hexsha": "d4c78af62a7ae05b99eb95d173661ac134b7e7b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2022-01-24T18:45:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T06:28:24.000Z", "avg_line_length": 41.1246290801, "max_line_length": 109, "alphanum_fraction": 0.5783245544, "include": true, "reason": "import numpy", "num_tokens": 3112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.3007455914759599, "lm_q1q2_score": 0.1894019326208192}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2019 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#\n\nimport os, sys\nimport imp\nimport numpy\nimport pyscf.ao2mo\n\ntry:\n    from pyscf.dmrgscf import settings\n    PyCheMPS2 = None\nexcept ImportError:\n    try:\n        import PyCheMPS2\n    except ImportError:\n        msg = ('settings.py not found.  Please create %s\\n' %\n               os.path.join(os.path.dirname(__file__), 'settings.py'))\n        sys.stderr.write(msg)\n\n# point group ID defined in CheMPS2, see\n# http://sebwouters.github.io/CheMPS2/classCheMPS2_1_1Irreps.html\nGROUPNAME_ID = {\n    'C1' : 0,\n    'Ci' : 1,\n    'C2' : 2,\n    'Cs' : 3,\n    'D2' : 4,\n    'C2v': 5,\n    'C2h': 6,\n    'D2h': 7,\n}\n\nclass CheMPS2(object):\n    def __init__(self, mol, **kwargs):\n        self.mol = mol\n        self.verbose = mol.verbose\n        self.stdout = mol.stdout\n        if self.mol.symmetry:\n            self.groupname = mol.groupname\n        else:\n            self.groupname = None\n        self.orbsym = []\n\n# ref.\n# https://github.com/SebWouters/CheMPS2/blob/master/psi4plugins/dmrgci.cc\n        self.wfn_irrep = 0\n        #self.spin_2s = 0  # spin = 2*s, 0 means singlet\n        self.dmrg_states = [ 200 , 500 , 1000 , 1000 ]\n        self.dmrg_noise = [ 1 , 1 , 1 , 0 ]\n        self.dmrg_e_convergence = 1e-8\n        self.dmrg_noise_factor = 0.03\n        self.dmrg_maxiter_noise = 5\n        self.dmrg_maxiter_silent = 100\n\n        self._keys = set(self.__dict__.keys())\n\n    def dump_flags(self, verbose=None):\n        log = pyscf.lib.logger.new_logger(self, verbose)\n        log.info('******** CheMPS2 flags ********')\n        log.info('dmrg_states = %s', str(self.dmrg_states))\n        log.info('dmrg_noise = %s', str(self.dmrg_noise))\n        log.info('dmrg_e_convergence = %g', self.dmrg_e_convergence)\n        log.info('dmrg_noise_factor = %g', self.dmrg_noise_factor)\n        log.info('dmrg_maxiter_noise = %d', self.dmrg_maxiter_noise)\n        log.info('dmrg_maxiter_silent = %d', self.dmrg_maxiter_silent)\n\n    def kernel(self, h1e, eri, norb, nelec, ci0=None, ecore=0, **kwargs):\n        global PyCheMPS2\n        if PyCheMPS2 is None:\n            PyCheMPS2 = imp.load_dynamic('PyCheMPS2', settings.PYCHEMPS2BIN)\n\n        Initializer = PyCheMPS2.PyInitialize()\n        Initializer.Init()\n\n        if self.groupname is not None:\n            groupNumber = GROUPNAME_ID[self.groupname]\n        else:\n            groupNumber = 0\n            self.orbsym = numpy.zeros(norb, numpy.int32)\n        Ham = PyCheMPS2.PyHamiltonian(norb, groupNumber,\n                                      numpy.asarray(self.orbsym, dtype=numpy.int32))\n        eri = pyscf.ao2mo.restore(1, eri, norb)\n        for i in range(norb):\n            for j in range(norb):\n                totsym = self.orbsym[i] ^ self.orbsym[j]\n                if 0 == totsym:\n                    Ham.setTmat(i, j, h1e[i,j])\n                for k in range(norb):\n                    for l in range(norb):\n                        totsym = self.orbsym[i] \\\n                               ^ self.orbsym[j] \\\n                               ^ self.orbsym[k] \\\n                               ^ self.orbsym[l]\n                        if 0 == totsym:\n                            Ham.setVmat(i, k, j, l, eri[i,j,k,l])\n        Ham.setEconst(0)\n\n        if isinstance(nelec, (int, numpy.integer)):\n            spin2 = 0\n        else:\n            spin2 = (nelec[0]-nelec[1])\n            nelec = sum(nelec)\n\n        Prob = PyCheMPS2.PyProblem(Ham, spin2, nelec, self.wfn_irrep)\n        Prob.SetupReorderD2h()\n\n        OptScheme = PyCheMPS2.PyConvergenceScheme(len(self.dmrg_states))\n        for cnt,m in enumerate(self.dmrg_states):\n            if self.dmrg_noise[cnt]:\n                OptScheme.setInstruction(cnt, m, self.dmrg_e_convergence,\n                                         self.dmrg_maxiter_noise,\n                                         self.dmrg_noise_factor)\n            else:\n                OptScheme.setInstruction(cnt, m, self.dmrg_e_convergence,\n                                         self.dmrg_maxiter_silent, 0.0)\n\n        with pyscf.lib.capture_stdout() as stdout:\n            theDMRG = PyCheMPS2.PyDMRG(Prob, OptScheme)\n            Energy = theDMRG.Solve() + ecore\n            theDMRG.calc2DMandCorrelations()\n            pyscf.lib.logger.debug1(self.mol, stdout.read())\n\n        rdm2 = numpy.empty((norb,)*4)\n        for i in range(norb):\n            for j in range(norb):\n                for k in range(norb):\n                    for l in range(norb):\n                        rdm2[i,j,k,l] = theDMRG.get2DMA(i, j, k, l)\n\n        with pyscf.lib.capture_stdout() as stdout:\n            theDMRG.deleteStoredOperators()\n            pyscf.lib.logger.debug1(self.mol, stdout.read())\n\n# The order of deallocation matters!\n        del(theDMRG)\n        del(OptScheme)\n        del(Prob)\n        del(Ham)\n        del(Initializer)\n\n        fakewfn_by_rdm2 = rdm2\n        return Energy, fakewfn_by_rdm2\n\n    def make_rdm12(self, fakewfn_by_rdm2, ncas, nelec, **kwargs):\n        if not isinstance(nelec, (int, numpy.integer)):\n            nelec = sum(nelec)\n# CheMPS2 uses physics notation\n        rdm2 = fakewfn_by_rdm2.transpose(0,2,1,3)\n        rdm1 = numpy.einsum('ijkk->ij', rdm2) / (nelec-1)\n        return rdm1, rdm2\n\n    def make_rdm1(self, fcivec, norb, nelec, link_index=None, **kwargs):\n        return self.make_rdm12(fcivec, norb, nelec, **kwargs)[0]\n\n\n\nif __name__ == '__main__':\n    from pyscf import gto\n    from pyscf import scf\n    from pyscf import mcscf\n\n    b = 1.4\n    mol = gto.Mole()\n    mol.build(\n        verbose = 5,\n        output = 'out-chemps2',\n        atom = [['H', (0.,0.,i)] for i in range(8)],\n        basis = {'H': 'sto-3g'},\n        symmetry = True,\n        symmetry_subgroup = 'D2h',\n    )\n    m = scf.RHF(mol)\n    m.scf()\n\n    mc = mcscf.CASSCF(m, 4, 4)\n    mc.fcisolver = CheMPS2(mol)\n    mc.fcisolver.dmrg_e_convergence = 1e-8\n    emc_1 = mc.mc2step()[0]\n\n    mc = mcscf.CASCI(m, 4, 4)\n    mc.fcisolver = CheMPS2(mol)\n    emc_0 = mc.casci()[0]\n\n    b = 1.4\n    mol = gto.Mole()\n    mol.build(\n        verbose = 5,\n        output = 'out-casscf',\n        atom = [['H', (0.,0.,i)] for i in range(8)],\n        basis = {'H': 'sto-3g'},\n        symmetry = True,\n    )\n    m = scf.RHF(mol)\n    m.scf()\n\n    mc = mcscf.CASSCF(m, 4, 4)\n    emc_1ref = mc.mc2step()[0]\n\n    mc = mcscf.CASCI(m, 4, 4)\n    emc_0ref = mc.casci()[0]\n\n    print('CheMPS2-CI  = %.15g CASCI  = %.15g' % (emc_0, emc_0ref))\n    print('CheMPS2-SCF = %.15g CASSCF = %.15g' % (emc_1, emc_1ref))\n", "meta": {"hexsha": "fc6b4cd1c42d874d22d2cb62d246dd3ca143a927", "size": 7134, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/dmrgscf/chemps2.py", "max_stars_repo_name": "crisely09/pyscf", "max_stars_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-30T22:33:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-22T18:02:36.000Z", "max_issues_repo_path": "pyscf/dmrgscf/chemps2.py", "max_issues_repo_name": "crisely09/pyscf", "max_issues_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2018-08-22T19:44:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-09T10:02:36.000Z", "max_forks_repo_path": "pyscf/dmrgscf/chemps2.py", "max_forks_repo_name": "crisely09/pyscf", "max_forks_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-02-14T16:28:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-12T16:40:30.000Z", "avg_line_length": 32.5753424658, "max_line_length": 84, "alphanum_fraction": 0.5663022147, "include": true, "reason": "import numpy", "num_tokens": 2127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.18939741603190216}}
{"text": "\"\"\"\nIMPORTANT : I have not written any exception handling here since this is just a prototype module.\n            But exceptions can be logged into database with \"traceback.format_exec()\"\n\"\"\"\n\nimport os\nimport numpy as np\nfrom PIL import Image\nimport torch\nimport torch.nn as nn\nimport torchvision.models as models\nfrom torchvision import transforms\nfrom vocabulary import Vocabulary\n\n\n# This python script will be called by Node.js as child process into project root directory, hence file paths will be from one level up.\n\nENCODER_CNN_CHECKPOINT = \"python_models/saved_models/encoderEpoch_2.pth\"\nDECODER_LSTM_RNN_CHECKPOINT = \"python_models/saved_models/decoderEpoch_2.pth\"\nVOCAB_FILE = \"python_models/saved_models/vocab.pkl\"\n\n# Globally Set device to CPU since GPU won't be necessary for making just one prediction at a time\ndevice = \"cpu\"\n\n\n#=========================================================================\n# Encoder - Decoder Model Class to be used for Generating Caption\n#=========================================================================\n\nclass EncoderCNN(nn.Module):\n    def __init__(self, embed_size):\n        super(EncoderCNN, self).__init__()\n        resnet = models.resnet50(pretrained=True)\n        for param in resnet.parameters():\n            param.requires_grad_(False)\n\n        modules = list(resnet.children())[:-1]\n        self.resnet = nn.Sequential(*modules)\n        self.embed = nn.Linear(resnet.fc.in_features, embed_size)\n\n    def forward(self, images):\n        features = self.resnet(images)\n        features = features.view(features.size(0), -1)\n        features = self.embed(features)\n        return features\n\n\nclass DecoderRNN(nn.Module):\n    def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1):\n        super(DecoderRNN, self).__init__()\n        self.embed_size = embed_size\n        self.hidden_size = hidden_size\n        self.vocab_size = vocab_size\n        self.num_layers = num_layers\n\n        self.embed = nn.Embedding(num_embeddings = self.vocab_size,\n                                  embedding_dim = self.embed_size)\n        self.lstm = nn.LSTM(input_size = self.embed_size,\n                           hidden_size = self.hidden_size,\n                           num_layers = self.num_layers,\n                           batch_first = True)\n        self.fc1 = nn.Linear(in_features = self.hidden_size,\n                            out_features = self.vocab_size)\n\n\n    def forward(self, features, captions):\n        captions = captions[:,:-1]\n        embeddings = self.embed(captions)\n        embeddings = torch.cat((features.unsqueeze(1), embeddings),dim=1)\n        batch_size = features.shape[0]\n\n        self.hidden = (torch.zeros((self.num_layers, batch_size, self.hidden_size), device=device),torch.zeros((self.num_layers, batch_size, self.hidden_size), device=device))\n\n        lstm_out, self.hidden = self.lstm(embeddings, self.hidden)\n        output = self.fc1(lstm_out)\n        return output\n\n    def sample(self, inputs, states=None, max_len=20):\n        \" accepts pre-processed image tensor (inputs) and returns predicted sentence (list of tensor ids of length max_len) \"\n\n        output = []\n        batch_size = inputs.shape[0]\n\n        self.hidden = (torch.zeros((self.num_layers, batch_size, self.hidden_size), device=device),torch.zeros((self.num_layers, batch_size, self.hidden_size), device=device))\n\n        while True:\n            lstm_out, self.hidden = self.lstm(inputs, self.hidden)\n            linear_out = self.fc1(lstm_out.squeeze(1))\n            top_score = linear_out.max(1)[1]\n            output.append(top_score.cpu().numpy()[0].item())\n            if top_score == 1:\n                break\n            inputs = self.embed(top_score)\n            inputs = inputs.unsqueeze(1)\n        return output\n\n\n\n\n\ndef clean_sentence(output,vocab):\n    cleaned = []\n    for index in output:\n        cleaned.append(vocab.idx2word[index])\n    cleaned = cleaned[1:-1]\n    sentence = ' '.join(cleaned)\n    return sentence\n\ndef generateCaptions(image_path):\n    vocab = Vocabulary(vocab_file=VOCAB_FILE,vocab_from_file=True,vocab_threshold=None)\n\n    # Model parameters\n    embed_size = 512\n    hidden_size = 512\n    vocab_size = len(vocab)\n\n    # Initialize the encoder and decoder, and set each to inference mode.\n    encoder = EncoderCNN(embed_size)\n    decoder = DecoderRNN(embed_size, hidden_size, vocab_size, num_layers=2)\n\n    # Load the trained weights.\n    encoder.load_state_dict(torch.load(ENCODER_CNN_CHECKPOINT))\n    decoder.load_state_dict(torch.load(DECODER_LSTM_RNN_CHECKPOINT))\n\n    # Put model to evaluation mode\n    encoder.eval()\n    decoder.eval()\n\n    # Move models to GPU if CUDA is available.\n    encoder.to(device)\n    decoder.to(device)\n\n    transform_predict = transforms.Compose([\n    transforms.Resize(256),                          # smaller edge of image resized to 256\n    transforms.RandomCrop(224),                      # get 224x224 crop from random location\n    transforms.RandomHorizontalFlip(),               # horizontally flip image with probability=0.5\n    transforms.ToTensor(),                           # convert the PIL Image to a tensor\n    transforms.Normalize((0.485, 0.456, 0.406),      # normalize image for pre-trained model\n                         (0.229, 0.224, 0.225))])\n\n\n    image = Image.open(image_path).convert('RGB')    # Convert to RGB in case additonal channel is there in image\n    original_image = np.copy(image)\n    image = torch.unsqueeze(transform_predict(image), 0).to(device)\n    features = encoder(image).unsqueeze(1)\n    output = decoder.sample(features)\n    sentence = clean_sentence(output, vocab)\n    return {\"sentence\":sentence}\n\n\n\n\n\n", "meta": {"hexsha": "d16d45066a52cbe842e7a305abbb5d10c2afb671", "size": 5686, "ext": "py", "lang": "Python", "max_stars_repo_path": "Node.js_Server/python_models/model.py", "max_stars_repo_name": "3ZadeSSG/Automatic-Image-Captioning", "max_stars_repo_head_hexsha": "5d58ba9bea972999317d4620b2780298562d2aa1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-05T20:18:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T20:18:48.000Z", "max_issues_repo_path": "Node.js_Server/python_models/model.py", "max_issues_repo_name": "3ZadeSSG/Automatic-Image-Captioning", "max_issues_repo_head_hexsha": "5d58ba9bea972999317d4620b2780298562d2aa1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Node.js_Server/python_models/model.py", "max_forks_repo_name": "3ZadeSSG/Automatic-Image-Captioning", "max_forks_repo_head_hexsha": "5d58ba9bea972999317d4620b2780298562d2aa1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-30T19:43:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-30T19:43:58.000Z", "avg_line_length": 36.9220779221, "max_line_length": 175, "alphanum_fraction": 0.6482588815, "include": true, "reason": "import numpy", "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3415824860330003, "lm_q1q2_score": 0.18939739985305634}}
{"text": "\"\"\"\n=======\nfourier\n=======\n\nThis module define the Fourier class and other functions related to\nthe fourier transformation.\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom javelin.grid import Grid\nfrom javelin.utils import get_unitcell, get_positions, get_atomic_numbers\nfrom javelin.fourier_cython import calculate_cython, approx_calculate_cython\n\n\nclass Fourier:\n    \"\"\"The Fourier class contains everything required to calculate the\n    diffuse scattering. The only required thing to be set is\n    :obj:`javelin.fourier.Fourier.structure`. There are defaults for\n    all other options including **grid**, **radiation**, **average**\n    structure subtraction and **lots** options.\n\n    :examples:\n\n    >>> from javelin.structure import Structure\n    >>> fourier = Fourier()\n    >>> print(fourier)\n    Radiation         : neutron\n    Fourier volume    : complete crystal\n    Aver. subtraction : False\n    <BLANKLINE>\n    Reciprocal layer  :\n    lower left  corner :     [ 0.  0.  0.]\n    lower right corner :     [ 1.  0.  0.]\n    upper left  corner :     [ 0.  1.  0.]\n    top   left  corner :     [ 0.  0.  1.]\n    <BLANKLINE>\n    hor. increment     :     [ 0.01  0.    0.  ]\n    vert. increment    :     [ 0.    0.01  0.  ]\n    top   increment    :     [ 0.  0.  1.]\n    <BLANKLINE>\n    # of points        :     101 x 101 x 1\n    >>> results = fourier.calc(Structure())\n    >>> print(results) # doctest: +SKIP\n    <xarray.DataArray 'Intensity' ([ 1.  0.  0.]: 101, [ 0.  1.  0.]: 101, [ 0.  0.  1.]: 1)>\n    array([[[ 0.],\n            [ 0.],\n            ...,\n            [ 0.],\n            [ 0.]],\n    <BLANKLINE>\n           [[ 0.],\n            [ 0.],\n            ...,\n            [ 0.],\n            [ 0.]],\n    <BLANKLINE>\n           ...,\n           [[ 0.],\n            [ 0.],\n            ...,\n            [ 0.],\n            [ 0.]],\n    <BLANKLINE>\n           [[ 0.],\n            [ 0.],\n            ...,\n            [ 0.],\n            [ 0.]]])\n    Coordinates:\n      * [ 1.  0.  0.]  ([ 1.  0.  0.]) float64 0.0 0.01 0.02 0.03 0.04 0.05 0.06 ...\n      * [ 0.  1.  0.]  ([ 0.  1.  0.]) float64 0.0 0.01 0.02 0.03 0.04 0.05 0.06 ...\n      * [ 0.  0.  1.]  ([ 0.  0.  1.]) float64 0.0\n    Attributes:\n        units:    r.l.u\n\n    \"\"\"\n    def __init__(self):\n        self._radiation = 'neutron'\n        self._lots = None\n        self._number_of_lots = None\n        self._average = False\n        self._magnetic = False\n        self._cython = True\n        self._approximate = True\n        self._fast = True\n\n        #: The **grid** attribute defines the reciprocal volume from\n        #: which the scattering will be calculated. Must of type\n        #: :class:`javelin.grid.Grid` And check\n        #: :class:`javelin.grid.Grid` for details on how to change the\n        #: grid.\n        self.grid = Grid()\n\n    def __str__(self):\n        return \"\"\"Radiation         : {}\nFourier volume    : {}\nAver. subtraction : {}\n\nReciprocal layer  :\n{}\"\"\".format(self.radiation,\n             \"complete crystal\" if self.lots is None else \"{} lots of {} x {} x {} unit cells\"\n             .format(self.number_of_lots, *self.lots),\n             self.average,\n             self.grid)\n\n    @property\n    def radiation(self):\n        \"\"\"The radiation used\n\n        :getter: Returns the radiation selected\n        :setter: Sets the radiation\n        :type: str ('xray' or 'neutron')\n        \"\"\"\n        return self._radiation\n\n    @radiation.setter\n    def radiation(self, rad):\n        if rad not in ('neutron', 'xray'):\n            raise ValueError(\"radiation must be one of 'neutron' or 'xray'\")\n        self._radiation = rad\n\n    @property\n    def lots(self):\n        \"\"\"The size of lots\n\n        :getter: Returns the lots size\n        :setter: Sets the lots size\n        :type: list of 3 integers or None\n        \"\"\"\n        return self._lots\n\n    @lots.setter\n    def lots(self, lots):\n        if lots is None:\n            self._lots = None\n        else:\n            lots = np.asarray(lots)\n            if len(lots) == 3:\n                self._lots = lots\n            else:\n                raise ValueError(\"Must provied 3 values for lots\")\n\n    @property\n    def number_of_lots(self):\n        \"\"\"The number of lots to use\n\n        :getter: Returns the number of lots\n        :setter: Sets the number of lots\n        :type: int\n        \"\"\"\n        return self._number_of_lots\n\n    @number_of_lots.setter\n    def number_of_lots(self, value):\n        self._number_of_lots = value\n\n    @property\n    def average(self):\n        \"\"\"This sets the options of calculating average structure and\n        subtracted it from the simulated scattering\n\n        :getter: Returns bool of average structure subtraction option\n        :setter: Sets whether average structure is subtracted\n        :type: bool\n        \"\"\"\n        return self._average\n\n    @average.setter\n    def average(self, value):\n        if isinstance(value, bool):\n            self._average = value\n        else:\n            raise TypeError(\"Expected a bool, True or False\")\n\n    @property\n    def magnetic(self):\n        \"\"\"This sets the options of calculating the magnetic scattering\n        instead of nuclear. This assume neutrons are being used.\n\n        :getter: Returns bool of magnetic scattering option\n        :setter: Sets whether magnetic sacttering is calculated\n        :type: bool\n\n        \"\"\"\n        return self._magnetic\n\n    @magnetic.setter\n    def magnetic(self, value):\n        if isinstance(value, bool):\n            self._magnetic = value\n        else:\n            raise TypeError(\"Expected a bool, True or False\")\n\n    @property\n    def approximate(self):\n        \"\"\"This sets the options of calculating the approximate scattering\n        instead of exact. This is much quicker and is likely good enough for\n        most cases.\n\n        :getter: Returns bool of approximate scattering option\n        :setter: Sets whether approximate sacttering is calculated\n        :type: bool\n\n        \"\"\"\n        return self._approximate\n\n    @approximate.setter\n    def approximate(self, value):\n        if isinstance(value, bool):\n            self._approximate = value\n        else:\n            raise TypeError(\"Expected a bool, True or False\")\n\n    def __get_q(self, unitcell):\n        qx, qy, qz = self.grid.get_q_meshgrid()\n        q = np.linalg.norm(np.array([qx.ravel(),\n                                     qy.ravel(),\n                                     qz.ravel()]).T @ unitcell.B, axis=1)\n        q.shape = qx.shape\n        return q*2*np.pi\n\n    def calc(self, structure):\n        \"\"\"Calculates the fourier transform\n\n        :param structure: The structure from which fourier transform\n        is calculated. The calculation work with any of the following\n        types of structures :class:`javelin.structure.Structure`,\n        :class:`ase.Atoms` or\n        :class:`diffpy.Structure.structure.Structure` but if you are\n        using average structure subtraction or the lots option it\n        needs to be :class:`javelin.structure.Structure` type.\n\n        :return: DataArray containing calculated diffuse scattering\n        :rtype: :class:`xarray.DataArray`\n\n        \"\"\"\n\n        if structure is None:\n            raise ValueError(\"You have not set a structure for this calculation\")\n\n        if self.average:\n            aver = self._calculate_average(structure)\n\n        unitcell = get_unitcell(structure)\n\n        if self.lots is None:\n            atomic_numbers = get_atomic_numbers(structure)\n            positions = get_positions(structure)\n            if self.magnetic:\n                magmons = structure.get_magnetic_moments()\n                return create_xarray_dataarray(self._calculate_magnetic(atomic_numbers,\n                                                                        positions,\n                                                                        unitcell,\n                                                                        magmons), self.grid)\n            else:\n                results = self._calculate(atomic_numbers, positions, unitcell)\n                if self.average:\n                    results -= aver\n\n                return create_xarray_dataarray(np.real(results*np.conj(results)), self.grid)\n\n        else:  # needs to be Javelin structure, lots by unit cell\n            total = np.zeros(self.grid.bins)\n            levels = structure.atoms.index.levels\n            for lot in range(self.number_of_lots):\n                print(lot+1, 'out of', self.number_of_lots)\n                starti = np.random.randint(len(levels[0]))\n                startj = np.random.randint(len(levels[1]))\n                startk = np.random.randint(len(levels[2]))\n                ri = np.roll(levels[0], -starti)[:self.lots[0]]\n                rj = np.roll(levels[1], -startj)[:self.lots[1]]\n                rk = np.roll(levels[2], -startk)[:self.lots[2]]\n                atoms = structure.atoms.loc[ri, rj, rk, :]\n                atomic_numbers = atoms.Z.values\n                positions = (atoms[['x', 'y', 'z']].values +\n                             np.asarray([np.mod(atoms.index.get_level_values(0).values-starti,\n                                                len(levels[0])),\n                                         np.mod(atoms.index.get_level_values(1).values-startj,\n                                                len(levels[1])),\n                                         np.mod(atoms.index.get_level_values(2).values-startk,\n                                                len(levels[2]))]).T)\n                if self.magnetic:\n                    magmons = structure.magmons.loc[ri, rj, rk, :].values\n                    total += self._calculate_magnetic(atomic_numbers, positions, unitcell, magmons)\n                else:\n                    results = self._calculate(atomic_numbers, positions, unitcell)\n                    if self.average:\n                        results -= aver\n                    total += np.real(results*np.conj(results))\n\n            scale = (structure.atoms.index.droplevel(3).drop_duplicates().size /\n                     (self.number_of_lots*self.lots.prod()))\n\n            return create_xarray_dataarray(total*scale, self.grid)\n\n    def calc_average(self, structure):\n        \"\"\"Calculates the scattering from the avarage structure\n\n        :param structure: The structure from which fourier transform\n        is calculated. The calculation work with any of the following\n        types of structures :class:`javelin.structure.Structure`,\n        :class:`ase.Atoms` or\n        :class:`diffpy.Structure.structure.Structure` but if you are\n        using average structure subtraction or the lots option it\n        needs to be :class:`javelin.structure.Structure` type.\n\n        :return: DataArray containing calculated average scattering\n        :rtype: :class:`xarray.DataArray`\n        \"\"\"\n\n        if structure is None:\n            raise ValueError(\"You have not set a structure for this calculation\")\n\n        aver = self._calculate_average(structure)\n        return create_xarray_dataarray(np.real(aver*np.conj(aver)), self.grid)\n\n    def _calculate_average(self, structure):\n        aver = self._calculate(get_atomic_numbers(structure),\n                               structure.xyz, get_unitcell(structure))\n\n        aver /= structure.atoms.index.droplevel(3).drop_duplicates().size\n\n        # compute the interference function of the lot shape\n\n        if self.lots is None:\n            index = structure.atoms.index.droplevel(3).drop_duplicates()\n        else:\n            index = structure.atoms.loc[pd.RangeIndex(self.lots[0]),\n                                        pd.RangeIndex(self.lots[1]),\n                                        pd.RangeIndex(self.lots[2]),\n                                        :].index.droplevel(3).drop_duplicates()\n\n        aver *= self._calculate(np.zeros(len(index), dtype=np.int),\n                                np.asarray([index.get_level_values(0).astype('double').values,\n                                            index.get_level_values(1).astype('double').values,\n                                            index.get_level_values(2).astype('double').values]).T,\n                                use_ff=False)\n\n        return aver\n\n    def _calculate(self, atomic_numbers, positions, unitcell=None, use_ff=True):\n        if self._fast and not self._cython:\n            qx, qy, qz = self.grid.get_squashed_q_meshgrid()\n        else:\n            qx, qy, qz = self.grid.get_q_meshgrid()\n        qx *= (2*np.pi)\n        qy *= (2*np.pi)\n        qz *= (2*np.pi)\n\n        # Get unique list of atomic numbers\n        unique_atomic_numbers = np.unique(atomic_numbers)\n\n        results = np.zeros(self.grid.bins, dtype=np.complex)\n        # Loop of atom types\n        for atomic_number in unique_atomic_numbers:\n            try:\n                ff = get_ff(atomic_number, self.radiation, self.__get_q(unitcell)) if use_ff else 1\n            except KeyError as e:\n                print(\"Skipping fourier calculation for atom \" + str(e) +\n                      \", unable to get scattering factors.\")\n                continue\n\n            atom_positions = positions[np.where(atomic_numbers == atomic_number)]\n            temp_array = np.zeros(self.grid.bins, dtype=np.complex)\n            print(\"Working on atom number\", atomic_number, \"Total atoms:\", len(atom_positions))\n\n            # Loop over atom positions of type atomic_number\n            if self._cython:\n                if self.approximate:\n                    cex = np.exp(np.linspace(0, 2j*np.pi*(1-2**-16), 2**16))\n                    approx_calculate_cython(self.grid.ll, self.grid.v1_delta,\n                                            self.grid.v2_delta, self.grid.v3_delta,\n                                            atom_positions, temp_array.real,\n                                            temp_array.imag, cex.real, cex.imag)\n                else:\n                    calculate_cython(qx, qy, qz, atom_positions, temp_array.real, temp_array.imag)\n            else:\n                if self._fast:\n                    for atom in atom_positions:\n                        dotx = np.exp(qx*atom[0]*1j)\n                        doty = np.exp(qy*atom[1]*1j)\n                        dotz = np.exp(qz*atom[2]*1j)\n                        temp_array += dotx * doty * dotz\n                else:\n                    for atom in atom_positions:\n                        dot = qx*atom[0] + qy*atom[1] + qz*atom[2]\n                        temp_array += np.exp(dot*1j)\n\n            results += temp_array * ff  # scale by form factor\n\n        return results\n\n    def _calculate_magnetic(self, atomic_numbers, positions, unitcell, magmons):\n        if self._fast:\n            qx, qy, qz = self.grid.get_squashed_q_meshgrid()\n        else:\n            qx, qy, qz = self.grid.get_q_meshgrid()\n        qx *= (2*np.pi)\n        qy *= (2*np.pi)\n        qz *= (2*np.pi)\n        q2 = self.__get_q(unitcell)**2\n\n        # Get unique list of atomic numbers\n        unique_atomic_numbers = np.unique(atomic_numbers)\n\n        # Loop of atom types\n        spinx = np.zeros(self.grid.bins, dtype=np.complex)\n        spiny = np.zeros(self.grid.bins, dtype=np.complex)\n        spinz = np.zeros(self.grid.bins, dtype=np.complex)\n        for atomic_number in unique_atomic_numbers:\n            try:\n                ff = get_mag_ff(atomic_number, self.__get_q(unitcell), ion=3)\n            except (AttributeError, KeyError) as e:\n                print(\"Skipping fourier calculation for atom \" + str(e) +\n                      \", unable to get magnetic scattering factors.\")\n                continue\n\n            atom_positions = positions[np.where(atomic_numbers == atomic_number)]\n            temp_spinx = np.zeros(self.grid.bins, dtype=np.complex)\n            temp_spiny = np.zeros(self.grid.bins, dtype=np.complex)\n            temp_spinz = np.zeros(self.grid.bins, dtype=np.complex)\n            print(\"Working on atom number\", atomic_number, \"Total atoms:\", len(atom_positions))\n            # Loop over atom positions of type atomic_number\n            if self._fast:\n                for atom, spin in zip(atom_positions, magmons):\n                    dotx = np.exp(qx*atom[0]*1j)\n                    doty = np.exp(qy*atom[1]*1j)\n                    dotz = np.exp(qz*atom[2]*1j)\n                    exp_temp = dotx * doty * dotz\n                    temp_spinx += exp_temp*spin[0]\n                    temp_spiny += exp_temp*spin[1]\n                    temp_spinz += exp_temp*spin[2]\n            else:\n                for atom, spin in zip(atom_positions, magmons):\n                    dot = qx*atom[0] + qy*atom[1] + qz*atom[2]\n                    exp_temp = np.exp(dot*1j)\n                    temp_spinx += exp_temp*spin[0]\n                    temp_spiny += exp_temp*spin[1]\n                    temp_spinz += exp_temp*spin[2]\n            spinx += temp_spinx * ff\n            spiny += temp_spiny * ff\n            spinz += temp_spinz * ff\n        # Calculate vector rejection of spin onto q\n        # M - M.Q/|Q|^2 Q\n        scale = (spinx*qx + spiny*qy + spinz*qz)/q2\n        spinx = spinx - scale * qx\n        spiny = spiny - scale * qy\n        spinz = spinz - scale * qz\n        return np.real(spinx*np.conj(spinx) + spiny*np.conj(spiny) + spinz*np.conj(spinz))\n\n\ndef create_xarray_dataarray(values, grid):\n    \"\"\"Create a xarry DataArray from the input numpy array and grid\n    object.\n\n    :param values: Input array containing the scattering intensities\n    :type values: :class:`numpy.ndarray`\n    :param numbers: Grid object describing the array properties\n    :type numbers: :class:`javelin.grid.Grid`\n    :return: DataArray produced from the values and grid object\n    :rtype: :class:`xarray.DataArray`\n    \"\"\"\n    import xarray as xr\n    return xr.DataArray(data=values,\n                        name=\"Intensity\",\n                        dims=(grid.get_axes_names()),\n                        coords=(grid.r1, grid.r2, grid.r3),\n                        attrs=((\"units\", grid.units),))\n\n\ndef get_ff(atomic_number, radiation, q=None):\n    \"\"\"Returns the form factor for a given atomic number, radiation and q\n    values\n\n    :param atomic_number: atomic number\n    :type atomic_number: int\n    :param radiation: type of radiation ('xray' or 'neutron')\n    :type radiation: str\n    :param q: value or values of q for which to get form factors\n    :type q: float, list, :class:`numpy.ndarray`\n    :return: form factors for given q\n    :rtype: float, :class:`numpy.ndarray`\n\n    :Examples:\n\n    >>> get_ff(8, 'neutron')\n    5.805\n\n    >>> get_ff(8, 'xray', q=2.0)\n    6.31826029176493\n\n    >>> get_ff(8, 'xray', q=[0.0, 3.5, 7.0])\n    array([ 7.999706  ,  4.38417867,  2.08928068])\n    \"\"\"\n    import periodictable\n\n    if atomic_number < 1:\n        raise KeyError(atomic_number)\n\n    if radiation == 'neutron':\n        return periodictable.elements[atomic_number].neutron.b_c\n    elif radiation == 'xray':\n        return periodictable.elements[atomic_number].xray.f0(q)\n    else:\n        raise ValueError(\"Unknown radition: \" + radiation)\n\n\ndef get_mag_ff(atomic_number, q, ion=0, j=0):\n    \"\"\"Returns the j0 magnetic form factor for a given atomic number,\n    radiation and q values\n\n    :param atomic_number: atomic number\n    :type atomic_number: int\n    :param q: value or values of q for which to get form factors\n    :type q: float, list, :class:`numpy.ndarray`\n    :param ion: charge of selected atom\n    :type ion: int\n    :param j: order of spherical Bessel function (0, 2, 4 or 6)\n    :type j: int\n    :return: magnetic form factor for given q\n    :rtype: float, :class:`numpy.ndarray`\n\n    :Examples:\n\n    >>> get_mag_ff(8, q=2, ion=1)\n    0.58510426376585045\n\n    >>> get_mag_ff(26, q=[0.0, 3.5, 7.0], ion=2)\n    array([ 1.        ,  0.49729671,  0.09979243])\n\n    >>> get_mag_ff(26, q=[0.0, 3.5, 7.0], ion=4)\n    array([ 0.9997    ,  0.58273549,  0.13948496])\n\n    >>> get_mag_ff(26, q=[0.0, 3.5, 7.0], ion=4, j=4)\n    array([ 0.       ,  0.0149604,  0.0759222])\n    \"\"\"\n    import periodictable\n    return getattr(periodictable.elements[atomic_number].magnetic_ff[ion], 'j'+str(j)+'_Q')(q)\n", "meta": {"hexsha": "b62820a67531659ac303aa167f5906d8d4a18c5c", "size": 20115, "ext": "py", "lang": "Python", "max_stars_repo_path": "javelin/fourier.py", "max_stars_repo_name": "rosswhitfield/Javelin", "max_stars_repo_head_hexsha": "a3538193343b5e086c8f4557d1890bac93dfddb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-01-30T21:43:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-02T12:24:51.000Z", "max_issues_repo_path": "javelin/fourier.py", "max_issues_repo_name": "rosswhitfield/Javelin", "max_issues_repo_head_hexsha": "a3538193343b5e086c8f4557d1890bac93dfddb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-01T18:45:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-01T18:45:43.000Z", "max_forks_repo_path": "javelin/fourier.py", "max_forks_repo_name": "rosswhitfield/Javelin", "max_forks_repo_head_hexsha": "a3538193343b5e086c8f4557d1890bac93dfddb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-11-16T18:48:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-19T03:55:41.000Z", "avg_line_length": 37.25, "max_line_length": 99, "alphanum_fraction": 0.5526721352, "include": true, "reason": "import numpy", "num_tokens": 4907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3345894478883556, "lm_q1q2_score": 0.18938382918583935}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n##############\n# GaudiMM: Genetic Algorithms with Unrestricted\n# Descriptors for Intuitive Molecular Modeling\n# \n# https://github.com/insilichem/gaudi\n#\n# Copyright 2017 Jaime Rodriguez-Guerra, Jean-Didier Marechal\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n#      http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n##############\n\n\"\"\"\nThis objective performs rough estimations\nof good orientations of ligating residues in a protein to\ncoordinate a given metal or small molecule. The geometry is approximated\nby computing average distances from ligating atoms the metal centre (``self.probe``)\nas well as the angles formed by the probe, the ligating atom and its immediate neighbor.\nGood planarity is assured by a dihedral check.\n\n\"\"\"\n\n# Python\nfrom __future__ import print_function, division\nimport math\nimport logging\nimport numpy as np\n# Chimera\nimport chimera\n# GAUDI\nfrom gaudi.objectives import ObjectiveProvider\nfrom gaudi.exceptions import AtomsNotFound, ResiduesNotFound, MoleculesNotFound\nfrom gaudi import parse\nfrom gaudi._cpdrift import coherent_point_drift\n\n\nlogger = logging.getLogger(__name__)\n\n\nGEOMETRIES = {\n    'cube': np.array([(1.0, 1.0, 1.0), (1.0, 1.0, -1.0), (1.0, -1.0, 1.0), (1.0, -1.0, -1.0), (-1.0, 1.0, 1.0), (-1.0, 1.0, -1.0), (-1.0, -1.0, 1.0), (-1.0, -1.0, -1.0), (0.0, 0.0, 0.0)]),\n    'hexagonal bipyramid': np.array([(0.0, 1.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, -1.0), (0.8660, 0.0, 0.5), (0.8660, 0.0, -0.5), (-0.8660, 0.0, 0.5), (-0.8660, 0.0, -0.5), (0.0, 0.0, 0.0)]),\n    'linear': np.array([(0.0, 1.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, 0.0)]),\n    'octahedron': np.array([(1.0, 0.0, 0.0), (-1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, -1.0), (0.0, 0.0, 0.0)]),\n    'pentagonal bipyramid': np.array([(0.0, 1.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, 1.0), (0.9511, 0.0, 0.30901), (0.5878, 0.0, -0.8090), (-0.5878, 0.0, -0.8090), (-0.9511, 0.0, 0.3090), (0.0, 0.0, 0.0)]),\n    'square planar': np.array([(1.0, 0.0, 0.0), (-1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, 0.0)]),\n    'square pyramid': np.array([(0.0, 1.0, 0.0), (-0.6123, -0.5, 0.6123), (0.6123, -0.5, 0.6123), (-0.6123, -0.5, -0.6123), (0.6123, -0.5, -0.6123), (0.0, 0.0, 0.0)]),\n    'tetrahedral': np.array([(1.0, 1.0, 1.0), (-1.0, -1.0, 1.0), (-1.0, 1.0, -1.0), (1.0, -1.0, -1.0), (0.0, 0.0, 0.0)]),\n    'trigonal planar': np.array([(1.0, 0.0, 0.0), (-0.5, 0.0, 0.8660), (-0.5, 0.0,-0.8660), (0.0, 0.0, 0.0)]),\n    'trigonal bipyramid': np.array([(0.0, 1.0, 0.0), (0.0, -1.0, 0.0), (1.0, 0.0, 0.0), (-0.5, 0.0, 0.8660), (-0.5, 0.0, -0.8660), (0.0, 0.0, 0.0)]),\n    'trigonal prism': np.array([(-0.6547, 0.6547, 0.3779), (0.6547, 0.6547, 0.3779), (0.0, 0.6547, -0.7559), (-0.6547, -0.6547, 0.3779), (0.6547, -0.6547, 0.3779), (0.0, -0.6547, -0.7559), (0.0, 0.0, 0.0)])}\n\ndef enable(**kwargs):\n    kwargs = Coordination.validate(kwargs)\n    return Coordination(**kwargs)\n\n\nclass Coordination(ObjectiveProvider):\n\n    \"\"\"\n    Coordination class\n\n    Parameters\n    ----------\n    probe : tuple\n        The atom that acts as the metal center, expressed as\n        <molecule_name>/<atom serial>. This will be parsed later on.\n    residues : list of str\n        Residues that must coordinate to `probe`, expressed as\n        <molecule_name>/<residue position>. Position can be `*`.\n    radius : float, optional, default=3.0\n        Distance from `probe` where ligating atoms must be found\n    atom_types : list of str, optional\n        Types of atoms that are considered ligands to `probe`\n    atom_names : list of str, optional\n        Names of atoms that are considered ligands to `probe`\n    atom_elements : list of str, optional\n        Elements of atoms that are considered ligands to `probe`        \n    distance : float, optional\n        Perfect distance a ligand atom should be from target.\n    geometry : str or list of 3-tuple floats, optional\n        Which geometry should be fitted. Choose from `GEOMETRIES` dict or\n        specify a set of vectors.\n    enforce_all_residues: bool, optional\n        Whether to force or not if all specified residues should coordinate.\n    only_one_ligand_per_residue : bool, optional\n        Enforce that only one ligand for each residue should coordinate.\n    prevent_intruders : bool, optional\n        Don't let non-ligand atoms to be closer to the target than the \n        selected ligand atoms.\n    center_of_mass_correction : bool, optional\n        If True, calculate the distance between the metal center \n        and the center of mass of the ligand atoms, and sum that\n        to the final score.\n    distance_correction : bool, optional\n        If True, report the deviation of the experimental coordination\n        bond length and the ideal one, as tabulated by ``chimera.Element``,\n        and sum that to the final score.\n\n    Returns\n    -------\n    float\n        Sum of RMSD of vertices from ideal RMSD and average cosine of\n        angle deviation from ideal orientation of ligand neighbors.\n        A perfect match should report 0.0.\n    \"\"\"\n    _validate = {\n        parse.Required('probe'): parse.Named_spec(\"molecule\", \"atom\"),\n        parse.Required('residues'): [parse.Named_spec(\"molecule\", \"residue\")],\n        'radius': parse.Coerce(float),\n        'atom_types': [basestring],\n        'atom_names': [basestring],\n        'atom_elements': [basestring],\n        'distance': parse.All(parse.Coerce(float), parse.Range(min=0)),\n        'min_atoms': parse.All(parse.Coerce(int), parse.Range(min=2)),\n        'geometry': parse.Any(parse.In(GEOMETRIES.keys()), [parse.Coordinates]),\n        'enforce_all_residues': parse.Coerce(bool),\n        'only_one_ligand_per_residue': parse.Coerce(bool),\n        'prevent_intruders': parse.Coerce(bool),\n        'center_of_mass_correction': parse.Coerce(bool),\n        'distance_correction': parse.Coerce(bool)\n        }\n    \n    def __init__(self, probe=None, radius=3.0, atom_types=(), atom_elements=(), \n                 atom_names=(), residues=(), geometry='tetrahedral', distance=0, \n                 min_atoms=1, prevent_intruders=True, enforce_all_residues=False, \n                 only_one_ligand_per_residue=False, center_of_mass_correction=False,\n                 distance_correction=False, *args, **kwargs):\n        ObjectiveProvider.__init__(self, **kwargs)\n        self._probe = probe\n        self._residues = residues\n        self.radius = radius\n        self.atom_types = atom_types\n        self.atom_names = atom_names\n        self.atom_elements = atom_elements\n        self.distance = distance\n        self.min_atoms = min_atoms\n        self.only_one_ligand_per_residue = only_one_ligand_per_residue\n        self.enforce_all_residues = enforce_all_residues\n        self.prevent_intruders = prevent_intruders\n        self.center_of_mass_correction = center_of_mass_correction\n        self.distance_correction = distance_correction\n        if isinstance(geometry, basestring):\n            self.geometry = np.copy(GEOMETRIES[geometry])\n        else:\n            self.geometry = np.array(geometry)\n        self.n_vertices = self.geometry.shape[0] - 1\n        if self.n_vertices < self.min_atoms:\n            self.min_ligands = self.n_vertices\n            logger.warn('# Vertices in selected geometry < min_ligands! Overriding '\n                        'min_ligands with {}'.format(self.n_vertices))\n        if not sum(map(bool, [atom_types, atom_elements, atom_names])):\n            raise ValueError('At least one of atom_types, atom_elements, atom_names '\n                             'must be specified')\n\n    def molecules(self, ind):\n        return [m.compound.mol for m in ind._molecules.values()]\n\n    def probe(self, ind):\n        mol, serial = self._probe\n        return ind.find_molecule(mol).find_atom(serial)\n\n    def residues(self, ind):\n        for mol, pos in self._residues:\n            for residue in ind.find_molecule(mol).find_residues(pos):\n                yield residue\n\n    def evaluate(self, ind):\n        \"\"\"\n        1. Get requested atoms sorted by distance\n        2. If they meet the minimum quantity, return the rmsd for\n           that geometry\n        3. If that's not possible of they are not enough, return penalty\n        \"\"\"\n        try:\n            test_atoms = [a for d, a in self.coordination_sphere(ind)]\n        except ResiduesNotFound:\n            logger.warning(\"Not enough atoms or some residues missing\")\n            return -1000 * self.weight\n       \n        missing_atoms = self.min_atoms - len(test_atoms)\n        if missing_atoms > 0:\n            logger.warning(\"Could not find enough ligand atoms in probe environment. \"\n                           \"{} missing\".format(missing_atoms))\n            return -100 * missing_atoms * self.weight\n\n        geometry = np.copy(self.geometry)\n        ligands = test_atoms[:self.n_vertices]\n        metal = self.probe(ind)\n        atom_points = [a.xformCoord() for a in ligands + [metal]]\n        atom_points_array = np.array(atom_points)\n        # rmsd\n        try:\n            _, _, rmsd = coherent_point_drift(atom_points_array, geometry, method='rigid',\n                                              guess_steps=2, max_iterations=10)\n        except Exception as e:\n            logger.exception(e)  #\n            logger.warning(\"Geometry not feasible in current conditions\")\n            return -1000 * self.weight\n        # directionality\n        directionality = sum(ideal_bond_deviation(metal, ligand, ligands) for ligand in ligands)\n        \n        com_deviation = 0\n        if self.center_of_mass_correction:\n            ligands_com = np.average(atom_points_array[:-1], axis=0)\n            com_deviation = atom_points[-1].distance(chimera.Point(*ligands_com))\n            \n        dist_deviation = 0\n        if self.distance_correction:\n            for ligand in ligands:\n                experimental_bond_length = ligand.xformCoord().distance(atom_points[-1])\n                ideal_bond_length = chimera.Element.bondLength(ligand.element, metal.element)\n                dist_deviation += abs(experimental_bond_length - ideal_bond_length)\n        \n        return rmsd + directionality + com_deviation + dist_deviation\n\n    def coordination_sphere(self, ind):\n        \"\"\"\n        1. Get atoms and residues found within ``self.radius`` \n        angstroms from ``self.probe``. Found residues MUST \n        include ``self.residues``. Otherwise, apply penalty.\n\n        2. Sort atoms by absolute difference of ``self.distance``\n        and distance to ``self.probe``. That way, nearest atoms are computed first.\n        If found atoms do not include some of the requested types, apply penalty.\n        \"\"\"\n        # Helpers\n        def abs_distance(a):\n            return abs(self.distance - metal.xformCoord().distance(a.xformCoord()))\n        if self.atom_types:\n            def atom_is_valid(a): return a.idatmType in self.atom_types\n        elif self.atom_elements:\n            def atom_is_valid(a): return a.element.name in self.atom_elements\n        elif self.atom_names:\n            def atom_is_valid(a): return a.name in self.atom_names\n        else:\n            def atom_is_valid(a): return True\n\n        self._update_zone(ind)\n        metal = self.probe(ind)\n        residues = list(self.residues(ind))\n        atoms = [a for a in self.zone.atoms() if a is not metal]\n            \n        atoms_by_distance = []\n        found_residues = set()\n        distance_and_atoms = sorted((abs_distance(a), a) for a in atoms)\n        for d, a in distance_and_atoms:\n            if atom_is_valid(a) and a.residue in residues and d > 1.0:\n                atoms_by_distance.append((d, a))\n                found_residues.add(a.residue)\n            elif self.prevent_intruders:\n                break\n\n        if self.enforce_all_residues and found_residues != residues:\n            logger.warning(\"Some atoms found, but some residues are missing\")\n            raise ResiduesNotFound\n\n        return atoms_by_distance\n\n    def _update_zone(self, ind):\n        \"\"\"\n        Clear existing selection and add atoms within `self.radius` from\n        `self.probe`, as long as they belong to one of `self.molecules`\n        \"\"\"\n        self.zone.clear()\n        self.zone.add(self.probe(ind))\n        self.zone.merge(chimera.selection.REPLACE,\n                        chimera.specifier.zone(\n                            self.zone, 'atom', None, self.radius, self.molecules(ind)))\n        return self.zone\n\n\ndef ideal_bond_deviation(metal, ligand, other_ligands=()):\n\n    \"\"\"\n    Assess if the current bond vector is well oriented with\n    respect to the ideal bond vector.\n\n    Parameters\n    ----------\n    metal : chimera.Atom\n        The ion `ligands` are coordinating to\n    ligand : chimera.Atom\n        Potential ligand atoms to `metal`\n\n    Returns\n    -------\n    float\n        Absolute sine of the angle between the ideal vector and\n        the ligand-metal one.\n    \"\"\"\n    ligand_idatm = chimera.idatm.typeInfo.get(ligand.idatmType)\n    ligand_geometry = ligand_idatm.geometry if ligand_idatm else 3\n    ideal_positions = ideal_bonded_positions(ligand, metal.element, geometry=ligand_geometry)\n    if not ideal_positions:\n        logger.warning(\"Ligand %s reports no available bonding positions. Check your atom_types!\", ligand)\n        return 1.0\n    # else we can go on\n    # Conditions and booleans\n    rotates = ligand_geometry == 4 and len(ligand.neighbors) == 1\n    bidentate = False\n    for bidentate_mate in other_ligands:\n        if bidentate_mate is not ligand:\n            shared_neighbors = set(ligand.neighbors) & set(bidentate_mate.neighbors)\n            if shared_neighbors:\n                bidentate = True\n                break\n\n    # Coordinates and positions\n    ligand_coord = ligand.xformCoord()\n    metal_coord = metal.xformCoord()\n    if not ligand.neighbors:\n        # If ligand has no neighbors, it's an isolated atom. This means it will always \n        # be well oriented towards the metal. Then we can just return 0.0\n        return 0.0\n    # else we can go on\n    neighbor = ligand.neighbors[0]\n    neighbor_coord = neighbor.xformCoord()\n    try:\n        n_neighbor = next(a for a in neighbor.neighbors if a is not ligand)\n        n_neighbor_coord = n_neighbor.xformCoord()\n    except StopIteration:\n        logger.warning('Ligand %s has no 2nd level neighbors. Dihedrals cannot be evaluated', ligand)\n        rotates = True # This will force to ignore dihedral calculation ;)\n    \n    ideal_pos = ideal_positions[0]\n    actual_angle = chimera.angle(neighbor_coord, ligand_coord, metal_coord)\n    ideal_angles = [chimera.angle(neighbor_coord, ligand_coord, ideal_pos)]\n    ideal_dihedrals = []\n    if bidentate and not rotates:\n        a = ligand_coord\n        b = bidentate_mate.xformCoord() \n        c = shared_neighbors.pop().xformCoord()\n        bidentate_ideal_pos = c + 1.5 * ((a-c) + (b-c))\n        bidentate_ideal_angle = chimera.angle(neighbor_coord, ligand_coord, bidentate_ideal_pos)\n        bidentate_ideal_dihedral = chimera.dihedral(n_neighbor_coord, neighbor_coord, \n                                                    ligand_coord, bidentate_ideal_pos)\n        ideal_angles.append(bidentate_ideal_angle)\n        ideal_dihedrals.append(bidentate_ideal_dihedral)\n        \n    angle_diff = min(delta - actual_angle for delta in ideal_angles)\n    abs_sin_angle = abs(math.sin(math.radians(angle_diff)))\n    if rotates:  # we don't care about the dihedral in this case\n        return abs_sin_angle\n    # else:\n    actual_dihedral = chimera.dihedral(n_neighbor_coord, neighbor_coord, ligand_coord, metal_coord)\n    ideal_dihedral = chimera.dihedral(n_neighbor_coord, neighbor_coord, ligand_coord, ideal_pos)\n    ideal_dihedrals.append(ideal_dihedral)\n    dihedral_diff = min(delta - actual_dihedral for delta in ideal_dihedrals)\n    abs_sin_dihedral = abs(math.sin(math.radians(dihedral_diff)))\n    return abs_sin_angle + abs_sin_dihedral\n\n\ndef ideal_bonded_positions(atom, element, geometry=None):\n    if geometry is None:\n        try:\n            geometry = chimera.idatm.typeInfo[atom.idatmType].geometry\n        except KeyError:\n            geometry = 3\n\n    bond_length = chimera.Element.bondLength(atom.element, element)\n    neighbors_crd = [a.xformCoord() for a in atom.neighbors]\n    return chimera.bondGeom.bondPositions(atom.xformCoord(), geometry, bond_length, neighbors_crd)\n", "meta": {"hexsha": "e5e3582c189d1784af2db87885d216a7a5be2cce", "size": 16886, "ext": "py", "lang": "Python", "max_stars_repo_path": "gaudi/objectives/coordination.py", "max_stars_repo_name": "jaimergp/gaudi", "max_stars_repo_head_hexsha": "8cb3ed9940e00c3d854c5c747b56a7a713ed7738", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2017-07-28T01:27:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T10:20:33.000Z", "max_issues_repo_path": "gaudi/objectives/coordination.py", "max_issues_repo_name": "jaimergp/gaudi", "max_issues_repo_head_hexsha": "8cb3ed9940e00c3d854c5c747b56a7a713ed7738", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2017-07-28T01:30:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-02T08:47:47.000Z", "max_forks_repo_path": "gaudi/objectives/coordination.py", "max_forks_repo_name": "jaimergp/gaudi", "max_forks_repo_head_hexsha": "8cb3ed9940e00c3d854c5c747b56a7a713ed7738", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25, "max_forks_repo_forks_event_min_datetime": "2017-05-05T09:01:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T05:05:41.000Z", "avg_line_length": 44.9095744681, "max_line_length": 209, "alphanum_fraction": 0.6395830866, "include": true, "reason": "import numpy", "num_tokens": 4671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3345894478883556, "lm_q1q2_score": 0.18938382918583935}}
{"text": "# Copyright 2022 The TEMPO Collaboration\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nModule for system 'control operations' as discussed in [Pollock2018].\n\n**[Pollock2018]**\nF.  A.  Pollock,  C.  Rodriguez-Rosario,  T.  Frauenheim,\nM. Paternostro, and K. Modi, *Non-Markovian quantumprocesses: Complete\nframework and efficient characterization*, Phys. Rev. A 97, 012127 (2018).\n\"\"\"\n\nfrom typing import Callable, List, Optional, Text, Tuple, Union\nfrom copy import deepcopy\n\nimport numpy as np\nfrom numpy import ndarray\n\nfrom oqupy.base_api import BaseAPIClass\nfrom oqupy.config import NpDtype\n\nclass Control(BaseAPIClass):\n    \"\"\"\n    Represents a set of system control operations.\n\n    A control operation is a superoperator that acts on the system\n    instantaneously at a particular time, as described in [Pollock2018].\n\n    Parameters\n    ----------\n    dimension: int\n        The Hilbert space dimension of the system.\n    name: str\n        An optional name for the set of control operations.\n    description: str\n        An optional description of the set of control operations.\n    \"\"\"\n    def __init__(\n            self,\n            dimension: int,\n            name: Optional[Text] = None,\n            description: Optional[Text] = None) -> None:\n        \"\"\"Creates a Control object. \"\"\"\n        self._dimension = dimension\n        self._step_controls = {'pre':{}, 'post':{}}\n        self._time_controls = {'pre':{}, 'post':{}}\n        self._control_times = {'pre':np.array([]), 'post':np.array([])}\n        super().__init__(name, description)\n\n    @property\n    def dimension(self):\n        \"\"\"Hilbert space dimension of the controlled system. \"\"\"\n        return self._dimension\n\n    def add_single(\n            self,\n            time: Union[int, float],\n            control_operation: ndarray,\n            post: Optional[bool] = False) -> None:\n        r\"\"\"\n        Adds a single control operation at time `time`.\n\n        Parameters\n        ----------\n        time: Union[int, float]\n            The time at which the operation should be applied. If `type(time)`\n            is `int` then `time` is understood as the *timestep* to which it\n            shall be applied.\n        control_operation: ndarray\n            The control operation super operator of shape\n            :math:`d^2 \\times d^2`, where :math:`d` is the system Hilbert space\n            dimension.\n        post: bool\n            If `True` (`False`) the operator is applied at the corresponding\n            time step *after* (*before*) a possible measurement of the state.\n        \"\"\"\n        if post:\n            pre_post = 'post'\n        else:\n            pre_post = 'pre'\n\n        if isinstance(time, int):\n            steps = self._step_controls[pre_post].keys()\n            if time in steps:\n                self._step_controls[pre_post][time] = \\\n                    control_operation @ self._step_controls[pre_post][time]\n            else:\n                self._step_controls[pre_post][time] = control_operation\n        elif isinstance(time, float):\n            if time in self._control_times[pre_post]:\n                self._time_controls[pre_post][time] = \\\n                    control_operation @ self._time_controls[pre_post][time]\n            else:\n                self._time_controls[pre_post][time] = control_operation\n                times = np.append(self._control_times[pre_post], time)\n                times.sort()\n                self._control_times[pre_post] = times\n        else:\n            raise TypeError(\"Parameter `time` must be either int or float.\")\n\n\n    def add_continuous(\n            self,\n            control_fct: Callable[[ndarray, float], ndarray],\n            post: Optional[bool] = False) -> None:\n        \"\"\"\n        ToDo\n        \"\"\"\n        raise NotImplementedError()\n\n    def get_controls(\n            self,\n            step: int,\n            dt: Optional[float] = None,\n            start_time: Optional[float] = 0.0,\n            ) -> Tuple[ndarray, ndarray]:\n        \"\"\"\n        Get the pre and post measurement control operation for a specific\n        time step.\n\n        Parameters\n        ----------\n        step: int\n            The time step.\n        dt: float\n            The time step length.\n        start_time: float\n            The initial time step off-set.\n\n        Returns\n        -------\n        pre: ndarray\n            The control superoperator that should be applied before a state\n            measurement.\n        post: ndarray\n            The control superoperator that should be applied after a state\n            measurement.\n        \"\"\"\n        pre_control_bool = False\n        post_control_bool = False\n        pre_control = np.identity(self.dimension**2)\n        post_control = np.identity(self.dimension**2)\n\n        # -- pre time-stamp controls --\n        a = np.round((self._control_times['pre'] - start_time) / dt)\n        times = np.array(self._control_times['pre'])[np.nonzero(a==step)]\n        if len(times) > 0:\n            print(times)\n            pre_control_bool = True\n            pre_control = self._time_controls['pre'][times[0]] @ pre_control\n            for t in times[1:]:\n                pre_control = self._time_controls['pre'][t] @ pre_control\n\n        # -- pre step controls --\n        steps = self._step_controls['pre'].keys()\n        if step in steps:\n            pre_control_bool = True\n            pre_control = self._step_controls['pre'][step] @ pre_control\n\n        # -- post step controls --\n        steps = self._step_controls['post'].keys()\n        if step in steps:\n            post_control_bool = True\n            post_control = self._step_controls['post'][step] @ post_control\n\n        # -- post time-stamp controls --\n        a = np.round((self._control_times['post'] - start_time) / dt)\n        times = np.array(self._control_times['post'])[np.nonzero(a==step)]\n        if len(times) > 0:\n            post_control_bool = True\n            post_control = self._time_controls['post'][times[0]] @ post_control\n            for t in times[1:]:\n                post_control = self._time_controls['post'][t] @ post_control\n\n        if not pre_control_bool:\n            pre_control = None\n        if not post_control_bool:\n            post_control = None\n        return pre_control, post_control\n\nclass ChainControl(BaseAPIClass):\n    \"\"\"\n    Control operations on a linear system chain.\n\n    Parameters\n    ----------\n    hilbert_space_dimensions: List[int]\n        Hilbert space dimension for each chain site.\n    name: str\n        An optional name for the chain controls.\n    description: str\n        An optional description of the chain controls.\n    \"\"\"\n    def __init__(\n            self,\n            hilbert_space_dimensions: List[int],\n            name: Optional[Text] = None,\n            description: Optional[Text] = None) -> None:\n        \"\"\"Create a ChainControl object. \"\"\"\n        tmp_hs_dims = np.array(hilbert_space_dimensions, int)\n        assert len(tmp_hs_dims.shape) == 1\n        assert len(tmp_hs_dims) >= 1\n        assert np.all(tmp_hs_dims > 0)\n        self._hs_dims = tmp_hs_dims\n\n        self._single_site_controls_pre = []\n        self._single_site_controls_post = []\n\n        super().__init__(name, description)\n\n    def __len__(self):\n        \"\"\"Length of the chain. \"\"\"\n        return len(self._hs_dims)\n\n    @property\n    def hs_dims(self):\n        \"\"\"Hilbert space dimensions. \"\"\"\n        return self._hs_dims\n\n    def add_single_site_control(\n            self,\n            control: ndarray,\n            site: int,\n            step: int,\n            post: Optional[bool] = False,\n            name: Optional[Text] = None) -> None:\n        \"\"\"\n        Add a control operation at site `site` and time step `step`.\n\n        Parameters\n        ----------\n        control: ndarray\n            Control operation in Liouville space.\n        site: int\n            Site index.\n        step: int\n            Timestep to which the control should be applied.\n        post: bool\n            True if the control should be applied *after* the measurement of\n            this time step.\n        name: Text\n            An optional name to recognize a control operation.\n        \"\"\"\n        assert isinstance(site, int)\n        assert site < len(self)\n        assert isinstance(step, int)\n        contr = np.array(control,  dtype=NpDtype)\n        assert contr.shape == (self._hs_dims[site]**2, self._hs_dims[site]**2)\n        if not post:\n            self._single_site_controls_pre.append({\n                \"contr\":contr,\n                \"site\":site,\n                \"step\":step,\n                \"name\":name})\n        else:\n            self._single_site_controls_post.append({\n                \"contr\":contr,\n                \"site\":site,\n                \"step\":step,\n                \"name\":name})\n\n    def get_single_site_controls(\n            self,\n            step: int,\n            post: bool) -> List[ndarray]:\n        \"\"\"\n        Get a list of single site controls for the time step `step`.\n\n        Parameters\n        ----------\n        step: int\n            The time step.\n        post: bool\n            If `True` (`False`) the set of control superoperators that should be\n            applied *after* (*before*) the measurement is returned.\n\n        Returns\n        -------\n        superoperators_list: list[ndarray]\n            List of single site control superoperators.\n        \"\"\"\n        empty = True\n        controls = [None] * len(self)\n\n        if not post:\n            ss_controls = self._single_site_controls_pre\n        else:\n            ss_controls = self._single_site_controls_post\n\n        for ssc in ss_controls:\n            if ssc[\"step\"] == step:\n                empty = False\n                if controls[ssc[\"site\"]] is None:\n                    controls[ssc[\"site\"]] = ssc[\"contr\"]\n                else:\n                    controls[ssc[\"site\"]] = \\\n                        controls[ssc[\"site\"]] @ ssc[\"contr\"]\n\n        if empty:\n            return None\n        return deepcopy(controls)\n", "meta": {"hexsha": "0908b6d5fa5802504625cb06b453e384d38a50c7", "size": 10501, "ext": "py", "lang": "Python", "max_stars_repo_path": "oqupy/control.py", "max_stars_repo_name": "gefux/OQuPy", "max_stars_repo_head_hexsha": "764528fb6181ea62f8829a9e0a9e3faa2af71e1f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2022-02-15T12:33:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T10:01:57.000Z", "max_issues_repo_path": "oqupy/control.py", "max_issues_repo_name": "gefux/OQuPy", "max_issues_repo_head_hexsha": "764528fb6181ea62f8829a9e0a9e3faa2af71e1f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2022-02-16T07:35:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T18:22:12.000Z", "max_forks_repo_path": "oqupy/control.py", "max_forks_repo_name": "gefux/OQuPy", "max_forks_repo_head_hexsha": "764528fb6181ea62f8829a9e0a9e3faa2af71e1f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-17T01:23:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T08:51:57.000Z", "avg_line_length": 33.6570512821, "max_line_length": 80, "alphanum_fraction": 0.5722312161, "include": true, "reason": "import numpy,from numpy", "num_tokens": 2292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.1893838254302104}}
{"text": "# pylint: skip-file\nimport os\nimport re\nimport sys\nimport warnings\n\nxla_flags = os.getenv(\"XLA_FLAGS\", \"\").lstrip(\"--\")\nxla_flags = re.sub(r\"xla_force_host_platform_device_count=.+\\s\", \"\", xla_flags).split()\nos.environ[\"XLA_FLAGS\"] = \" \".join([f\"--xla_force_host_platform_device_count={100}\"])\n\nimport aesara.tensor as at\nimport arviz as az\nimport jax\nimport numpy as np\nimport pandas as pd\n\nfrom aesara.compile import SharedVariable\nfrom aesara.graph.basic import Apply, Constant, clone, graph_inputs\nfrom aesara.graph.fg import FunctionGraph\nfrom aesara.graph.op import Op\nfrom aesara.graph.opt import MergeOptimizer\nfrom aesara.link.jax.dispatch import jax_funcify\nfrom aesara.tensor.type import TensorType\n\nfrom pymc3 import modelcontext\nfrom pymc3.aesaraf import compile_rv_inplace\n\nwarnings.warn(\"This module is experimental.\")\n\n\nclass NumPyroNUTS(Op):\n    def __init__(\n        self,\n        inputs,\n        outputs,\n        target_accept=0.8,\n        draws=1000,\n        tune=1000,\n        chains=4,\n        seed=None,\n        progress_bar=True,\n    ):\n        self.draws = draws\n        self.tune = tune\n        self.chains = chains\n        self.target_accept = target_accept\n        self.progress_bar = progress_bar\n        self.seed = seed\n\n        self.inputs, self.outputs = clone(inputs, outputs, copy_inputs=False)\n        self.inputs_type = tuple(input.type for input in inputs)\n        self.outputs_type = tuple(output.type for output in outputs)\n        self.nin = len(inputs)\n        self.nout = len(outputs)\n        self.nshared = len([v for v in inputs if isinstance(v, SharedVariable)])\n        self.samples_bcast = [self.chains == 1, self.draws == 1]\n\n        self.fgraph = FunctionGraph(self.inputs, self.outputs, clone=False)\n        MergeOptimizer().optimize(self.fgraph)\n\n        super().__init__()\n\n    def make_node(self, *inputs):\n\n        # The samples for each variable\n        outputs = [\n            TensorType(v.dtype, self.samples_bcast + list(v.broadcastable))() for v in inputs\n        ]\n\n        # The leapfrog statistics\n        outputs += [TensorType(\"int64\", self.samples_bcast)()]\n\n        all_inputs = list(inputs)\n        if self.nshared > 0:\n            all_inputs += self.inputs[-self.nshared :]\n\n        return Apply(self, all_inputs, outputs)\n\n    def do_constant_folding(self, *args):\n        return False\n\n    def perform(self, node, inputs, outputs):\n        raise NotImplementedError()\n\n\n@jax_funcify.register(NumPyroNUTS)\ndef jax_funcify_NumPyroNUTS(op, node, **kwargs):\n    from numpyro.infer import MCMC, NUTS\n\n    draws = op.draws\n    tune = op.tune\n    chains = op.chains\n    target_accept = op.target_accept\n    progress_bar = op.progress_bar\n    seed = op.seed\n\n    # Compile the \"inner\" log-likelihood function.  This will have extra shared\n    # variable inputs as the last arguments\n    logp_fn = jax_funcify(op.fgraph, **kwargs)\n\n    if isinstance(logp_fn, (list, tuple)):\n        # This handles the new JAX backend, which always returns a tuple\n        logp_fn = logp_fn[0]\n\n    def _sample(*inputs):\n\n        if op.nshared > 0:\n            current_state = inputs[: -op.nshared]\n            shared_inputs = tuple(op.fgraph.inputs[-op.nshared :])\n        else:\n            current_state = inputs\n            shared_inputs = ()\n\n        def log_fn_wrap(x):\n            res = logp_fn(\n                *(\n                    x\n                    # We manually obtain the shared values and added them\n                    # as arguments to our compiled \"inner\" function\n                    + tuple(\n                        v.get_value(borrow=True, return_internal_type=True) for v in shared_inputs\n                    )\n                )\n            )\n\n            if isinstance(res, (list, tuple)):\n                # This handles the new JAX backend, which always returns a tuple\n                res = res[0]\n\n            return -res\n\n        nuts_kernel = NUTS(\n            potential_fn=log_fn_wrap,\n            target_accept_prob=target_accept,\n            adapt_step_size=True,\n            adapt_mass_matrix=True,\n            dense_mass=False,\n        )\n\n        pmap_numpyro = MCMC(\n            nuts_kernel,\n            num_warmup=tune,\n            num_samples=draws,\n            num_chains=chains,\n            postprocess_fn=None,\n            chain_method=\"parallel\",\n            progress_bar=progress_bar,\n        )\n\n        pmap_numpyro.run(seed, init_params=current_state, extra_fields=(\"num_steps\",))\n        samples = pmap_numpyro.get_samples(group_by_chain=True)\n        leapfrogs_taken = pmap_numpyro.get_extra_fields(group_by_chain=True)[\"num_steps\"]\n        return tuple(samples) + (leapfrogs_taken,)\n\n    return _sample\n\n\ndef sample_numpyro_nuts(\n    draws=1000,\n    tune=1000,\n    chains=4,\n    target_accept=0.8,\n    random_seed=10,\n    model=None,\n    progress_bar=True,\n    keep_untransformed=False,\n):\n    model = modelcontext(model)\n\n    seed = jax.random.PRNGKey(random_seed)\n\n    rv_names = [rv.name for rv in model.value_vars]\n    init_state = [model.initial_point[rv_name] for rv_name in rv_names]\n    init_state_batched = jax.tree_map(lambda x: np.repeat(x[None, ...], chains, axis=0), init_state)\n    init_state_batched_at = [at.as_tensor(v) for v in init_state_batched]\n\n    nuts_inputs = sorted(\n        (v for v in graph_inputs([model.logpt]) if not isinstance(v, Constant)),\n        key=lambda x: isinstance(x, SharedVariable),\n    )\n    map_seed = jax.random.split(seed, chains)\n    numpyro_samples = NumPyroNUTS(\n        nuts_inputs,\n        [model.logpt],\n        target_accept=target_accept,\n        draws=draws,\n        tune=tune,\n        chains=chains,\n        seed=map_seed,\n        progress_bar=progress_bar,\n    )(*init_state_batched_at)\n\n    # Un-transform the transformed variables in JAX\n    sample_outputs = []\n    for i, (value_var, rv_samples) in enumerate(zip(model.value_vars, numpyro_samples[:-1])):\n        rv = model.values_to_rvs[value_var]\n        transform = getattr(value_var.tag, \"transform\", None)\n        if transform is not None:\n            untrans_value_var = transform.backward(rv, rv_samples)\n            untrans_value_var.name = rv.name\n            sample_outputs.append(untrans_value_var)\n\n            if keep_untransformed:\n                rv_samples.name = value_var.name\n                sample_outputs.append(rv_samples)\n        else:\n            rv_samples.name = rv.name\n            sample_outputs.append(rv_samples)\n\n    print(\"Compiling...\", file=sys.stdout)\n\n    tic1 = pd.Timestamp.now()\n    _sample = compile_rv_inplace(\n        [],\n        sample_outputs + [numpyro_samples[-1]],\n        allow_input_downcast=True,\n        on_unused_input=\"ignore\",\n        accept_inplace=True,\n        mode=\"JAX\",\n    )\n    tic2 = pd.Timestamp.now()\n\n    print(\"Compilation time = \", tic2 - tic1, file=sys.stdout)\n\n    print(\"Sampling...\", file=sys.stdout)\n\n    *mcmc_samples, leapfrogs_taken = _sample()\n    tic3 = pd.Timestamp.now()\n\n    print(\"Sampling time = \", tic3 - tic2, file=sys.stdout)\n\n    posterior = {k.name: v for k, v in zip(sample_outputs, mcmc_samples)}\n\n    az_trace = az.from_dict(posterior=posterior)\n\n    return az_trace\n", "meta": {"hexsha": "b4113ef2b0a2190b29fb92b96f527b0e86891582", "size": 7163, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymc3/sampling_jax.py", "max_stars_repo_name": "helmutsimon/pymc3", "max_stars_repo_head_hexsha": "ea263f6caaf81960792eb664fc5494659524b451", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-30T00:43:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T00:43:47.000Z", "max_issues_repo_path": "pymc3/sampling_jax.py", "max_issues_repo_name": "helmutsimon/pymc3", "max_issues_repo_head_hexsha": "ea263f6caaf81960792eb664fc5494659524b451", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pymc3/sampling_jax.py", "max_forks_repo_name": "helmutsimon/pymc3", "max_forks_repo_head_hexsha": "ea263f6caaf81960792eb664fc5494659524b451", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.223628692, "max_line_length": 100, "alphanum_fraction": 0.6306017032, "include": true, "reason": "import numpy,from numpy,from pymc3,import jax", "num_tokens": 1694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.18938382167458143}}
{"text": "from __future__ import annotations\nimport qimpy as qp\nimport numpy as np\nimport torch\nimport pathlib\nimport re\nfrom ._ions_projectors import _get_projectors\nfrom ._ions_atomic import get_atomic_orbitals, get_atomic_density\nfrom ._ions_update import update, _collect_ps_matrix\nfrom typing import Optional, Union, List\n\n\nclass Ions(qp.TreeNode):\n    \"\"\"Ionic system: ionic geometry and pseudopotentials.\"\"\"\n\n    __slots__ = (\n        \"n_ions\",\n        \"n_types\",\n        \"symbols\",\n        \"n_ions_type\",\n        \"slices\",\n        \"pseudopotentials\",\n        \"positions\",\n        \"types\",\n        \"M_initial\",\n        \"Z\",\n        \"Z_tot\",\n        \"rho_tilde\",\n        \"Vloc_tilde\",\n        \"n_core_tilde\",\n        \"beta\",\n        \"beta_full\",\n        \"beta_version\",\n        \"D_all\",\n    )\n    n_ions: int  #: number of ions\n    n_types: int  #: number of distinct ion types\n    n_ions_type: List[int]  #: number of ions of each type\n    symbols: List[str]  #: symbol for each ion type\n    slices: List[slice]  #: slice to get each ion type\n    pseudopotentials: List[qp.ions.Pseudopotential]  #: pseudopotential for each type\n    positions: torch.Tensor  #: fractional positions of each ion (n_ions x 3)\n    types: torch.Tensor  #: type of each ion (n_ions, int)\n    M_initial: Optional[torch.Tensor]  #: initial magnetic moment for each ion\n    Z: torch.Tensor  #: charge of each ion type (n_types, float)\n    Z_tot: float  #: total ionic charge\n    rho_tilde: qp.grid.FieldH  #: ionic charge density (uses coulomb.ion_width)\n    Vloc_tilde: qp.grid.FieldH  #: local potential due to ions (including from rho)\n    n_core_tilde: qp.grid.FieldH  #: partial core electronic density (for XC)\n    beta: qp.electrons.Wavefunction  #: pseudopotential projectors (split-basis only)\n    beta_full: Optional[qp.electrons.Wavefunction]  #: full-basis version of `beta`\n    beta_version: int  #: version of `beta` to invalidate cached projections\n    D_all: torch.Tensor  #: nonlocal pseudopotential matrix (all atoms)\n\n    _get_projectors = _get_projectors\n    get_atomic_orbitals = get_atomic_orbitals\n    get_atomic_density = get_atomic_density\n    update = update\n    _collect_ps_matrix = _collect_ps_matrix\n\n    def __init__(\n        self,\n        *,\n        process_grid: qp.utils.ProcessGrid,\n        checkpoint_in: qp.utils.CpPath = qp.utils.CpPath(),\n        coordinates: Optional[List] = None,\n        pseudopotentials: Optional[Union[str, List[str]]] = None,\n    ) -> None:\n        \"\"\"Initialize geometry and pseudopotentials.\n\n        Parameters\n        ----------\n        coordinates\n            :yaml:`List of [symbol, x, y, z, args] for each ion in unit cell.`\n            Here, symbol is the chemical symbol of the element,\n            x, y and z are in the selected coordinate system.\n            Optional args is a dictionary of additional per-ion\n            parameters that may include:\n\n                * `M`: initial magnetic moment for the ion, which would be a\n                  single Mz or [Mx, My, Mz] depending on if the calculation\n                  is spinorial. Only specify in spin-polarized calculations.\n                * Relaxation constraints: TODO\n\n            Ions of the same type (symbol) must be specified consecutively.\n        pseudopotentials\n            :yaml:`Pseudopotential filenames or filename templates.`\n            Templates for families of pseudopotentials are specified by\n            including a $ID in the name which is replaced by the chemical\n            symbol of the element. The list of specified file names and\n            templates is processed in order, and the first match for\n            each element takes precedence.\n        \"\"\"\n        super().__init__()\n        qp.log.info(\"\\n--- Initializing Ions ---\")\n\n        # Read ionic coordinates:\n        if coordinates is None:\n            coordinates = []\n        assert isinstance(coordinates, list)\n        self.n_ions = 0  # number of ions\n        self.n_types = 0  # number of distinct ion types\n        self.symbols = []  # symbol for each ion type\n        self.n_ions_type = []  # numebr of ions of each type\n        self.slices = []  # slice to get each ion type\n        positions = []  # position of each ion\n        types = []  # type of each ion (index into symbols)\n        M_initial = []  # initial magnetic moments\n        type_start = 0\n        for coord in coordinates:\n            # Check for optional attributes:\n            if len(coord) == 4:\n                attrib = {}\n            elif len(coord) == 5:\n                attrib = coord[4]\n                if not isinstance(attrib, dict):\n                    raise ValueError(\"ion attributes must be a dict\")\n            else:\n                raise ValueError(\"each ion must be 4 entries + optional dict\")\n            # Add new symbol or append to existing:\n            symbol = str(coord[0])\n            if (not self.symbols) or (symbol != self.symbols[-1]):\n                self.symbols.append(symbol)\n                self.n_types += 1\n                if type_start != self.n_ions:\n                    self.slices.append(slice(type_start, self.n_ions))\n                    self.n_ions_type.append(self.n_ions - type_start)\n                    type_start = self.n_ions\n            # Add type and position of current ion:\n            types.append(self.n_types - 1)\n            positions.append([float(x) for x in coord[1:4]])\n            M_initial.append(attrib.get(\"M\", None))\n            self.n_ions += 1\n        if type_start != self.n_ions:\n            self.slices.append(slice(type_start, self.n_ions))  # for last type\n            self.n_ions_type.append(self.n_ions - type_start)\n\n        # Check order:\n        if len(set(self.symbols)) < self.n_types:\n            raise ValueError(\"coordinates must group ions of same type together\")\n\n        # Convert to tensors before storing in class object:\n        self.positions = torch.tensor(positions, device=qp.rc.device)\n        self.types = torch.tensor(types, device=qp.rc.device, dtype=torch.long)\n        # --- Fill in missing magnetizations (if any specified):\n        M_lengths = set(\n            [(len(M) if isinstance(M, list) else 1) for M in M_initial if M]\n        )\n        if len(M_lengths) > 1:\n            raise ValueError(\"All M must be same type: 3-vector or scalar\")\n        elif len(M_lengths) == 1:\n            M_length = next(iter(M_lengths))\n            assert (M_length == 1) or (M_length == 3)\n            M_default = [0.0, 0.0, 0.0] if (M_length == 3) else 0.0\n            self.M_initial = torch.tensor(\n                [(M if M else M_default) for M in M_initial],\n                device=qp.rc.device,\n                dtype=torch.double,\n            )\n        else:\n            self.M_initial = None\n        self.report()\n\n        # Initialize pseudopotentials:\n        self.pseudopotentials = []\n        if pseudopotentials is None:\n            pseudopotentials = []\n        if isinstance(pseudopotentials, str):\n            pseudopotentials = [pseudopotentials]\n        for i_type, symbol in enumerate(self.symbols):\n            fname = None  # full filename for this ion type\n            symbol_variants = [symbol.lower(), symbol.upper(), symbol.capitalize()]\n            # Check each filename provided in order:\n            for ps_name in pseudopotentials:\n                if ps_name.count(\"$ID\"):\n                    # wildcard syntax\n                    for symbol_variant in symbol_variants:\n                        fname_test = ps_name.replace(\"$ID\", symbol_variant)\n                        if pathlib.Path(fname_test).exists():\n                            fname = fname_test  # found\n                            break\n                else:\n                    # specific filename\n                    basename = pathlib.PurePath(ps_name).stem\n                    ps_symbol = re.split(r\"[_\\-\\.]+\", basename)[0]\n                    if ps_symbol in symbol_variants:\n                        fname = ps_name\n                        if not pathlib.Path(fname).exists():\n                            raise FileNotFoundError(fname)\n                        break\n                if fname:\n                    break\n            # Read pseudopotential file:\n            if fname:\n                self.pseudopotentials.append(qp.ions.Pseudopotential(fname))\n            else:\n                raise ValueError(f\"no pseudopotential found for {symbol}\")\n        self.beta_version = 0\n\n        # Calculate total ionic charge (needed for number of electrons):\n        self.Z = torch.tensor(\n            [ps.Z for ps in self.pseudopotentials], device=qp.rc.device\n        )\n        self.Z_tot = self.Z[self.types].sum().item()\n        qp.log.info(f\"\\nTotal ion charge, Z_tot: {self.Z_tot:g}\")\n\n        # Initialize / check replica process grid dimension:\n        n_replicas = 1  # this will eventually change for NEB / phonon DFPT\n        process_grid.provide_n_tasks(\"r\", n_replicas)\n\n    def report(self) -> None:\n        \"\"\"Report ionic positions and attributes\"\"\"\n        qp.log.info(f\"{self.n_ions} total ions of {self.n_types} types;\" \" positions:\")\n        # Fetch to CPU for reporting:\n        positions = self.positions.to(qp.rc.cpu).numpy()\n        types = self.types.to(qp.rc.cpu).numpy()\n        M_initial = (\n            None if (self.M_initial is None) else self.M_initial.to(qp.rc.cpu).numpy()\n        )\n        for i_ion, position in enumerate(positions):\n            # Generate attribute string:\n            attrib_str = \"\"\n            attribs = {}\n            if M_initial is not None:\n                M_i = M_initial[i_ion]\n                if np.linalg.norm(M_i):\n                    attribs[\"M\"] = M_i\n            if attribs:\n                attrib_str = \", \" + str(attribs).replace(\"'\", \"\").replace(\n                    \"array(\", \"\"\n                ).replace(\")\", \"\")\n            # Report:\n            qp.log.info(\n                f\"- [{self.symbols[types[i_ion]]}, {position[0]:11.8f},\"\n                f\" {position[1]:11.8f}, {position[2]:11.8f}{attrib_str}]\"\n            )\n\n    def translation_phase(\n        self, iG: torch.Tensor, atom_slice: slice = slice(None)\n    ) -> torch.Tensor:\n        \"\"\"Get translation phases at `iG` for a slice of atoms.\n        The result has atoms as the final dimension; summing over that\n        dimension yields the structure factor corresponding to these atoms.\n        \"\"\"\n        return qp.utils.cis((-2 * np.pi) * (iG @ self.positions[atom_slice].T))\n\n    @property\n    def n_projectors(self) -> int:\n        \"\"\"Total number of pseudopotential projectors.\"\"\"\n        return sum(\n            (ps.n_projectors * self.n_ions_type[i_ps])\n            for i_ps, ps in enumerate(self.pseudopotentials)\n        )\n\n    @property\n    def n_orbital_projectors(self) -> int:\n        \"\"\"Total number of projectors used to generate atomic orbitals.\"\"\"\n        return sum(\n            (ps.n_orbital_projectors * self.n_ions_type[i_ps])\n            for i_ps, ps in enumerate(self.pseudopotentials)\n        )\n\n    def n_atomic_orbitals(self, n_spinor: int) -> int:\n        \"\"\"Total number of atomic orbitals. This depends on the number\n        of spinorial components `n_spinor`.\"\"\"\n        return sum(\n            (ps.n_atomic_orbitals(n_spinor) * self.n_ions_type[i_ps])\n            for i_ps, ps in enumerate(self.pseudopotentials)\n        )\n", "meta": {"hexsha": "48ac7d9f9f69e13bbf19502702c8a5e6c8b42a00", "size": 11333, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/qimpy/ions/_ions.py", "max_stars_repo_name": "shankar1729/qimpy", "max_stars_repo_head_hexsha": "5a4c1ea1fedc88909d426ce54101d6d07fa82e8c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-05-25T00:11:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T21:49:00.000Z", "max_issues_repo_path": "src/qimpy/ions/_ions.py", "max_issues_repo_name": "shankar1729/qimpy", "max_issues_repo_head_hexsha": "5a4c1ea1fedc88909d426ce54101d6d07fa82e8c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-09-28T19:18:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-23T13:23:17.000Z", "max_forks_repo_path": "src/qimpy/ions/_ions.py", "max_forks_repo_name": "shankar1729/qimpy", "max_forks_repo_head_hexsha": "5a4c1ea1fedc88909d426ce54101d6d07fa82e8c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9740740741, "max_line_length": 87, "alphanum_fraction": 0.5817524045, "include": true, "reason": "import numpy", "num_tokens": 2586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.33458942798284697, "lm_q1q2_score": 0.1893838179189525}}
{"text": "import os\nimport numpy as np\nfrom glob import iglob\nimport shutil\nimport os\nimport readline\nimport pprint\nimport sys\nfrom sys import argv\n#from NN_phasecorrection import check_phases\n\n'''This file should interpolate between a starting geometry taken from a QM.in file and an end-geometry (at which NNs broke down), also taken from a QM.in file_end\n      - The files should be transfered into zmat-files and linear interpolation between the start- and end-geometry will be carried out\n      - Later, the geometries will be written into the form of a QM.in file, the interface will then generate QM.out files - those will be written into an output.dat format and the output_all.dat can be appended later\n      - In the end, the phases should be compared between geometries and corrected in the output.dat files. After the last geometry is corrected, the \n        calculation using a QM-interface, should be carried out with corrected phases\n'''\n\n\n\n#============================================================================================================================================================#\n#======================================================================QM.out 2 output.dat===================================================================#\n#============================================================================================================================================================#\ndef qm2outputdat(Properties,outputdatfile):\n  #in order to use the generated data, the important quantities for running NNs (Energy, SOC, Dipole, NAC) will be written into an output.dat format\n  #therefore, the header of the output_all.dat file will be taken  -  every matrix (e.g. U matrix, property matrix) will be filled with zeros\n  #iterate over QM.out files\n  #TODO maybe change Overlap to True again - but right now although overlap and write_overlap is given, no overlaps are written by molpro\n  OUTPUT['Overlap']=False\n  file=open(\"output_new.dat\", 'w')\n  nmstates = OUTPUT['nmstates']\n  natoms = OUTPUT['natoms']\n  string_output=header\n  string_output+='! 0 Step\\n 0\\n'\n  string_hamilton='! 1 Hamiltonian (MCH) in a.u.\\n'\n  string_umatrix='! 2 U matrix\\n'\n  string_dipole_x='! 3 Dipole moments X (MCH) in a.u.\\n'\n  string_dipole_y='! 3 Dipole moments Y (MCH) in a.u.\\n'\n  string_dipole_z='! 3 Dipole moments Z (MCH) in a.u.\\n'\n  string_overlap=''\n  string_coefficient='! 5 Coefficients (diag)\\n'\n  string_hopping='! 6 Hopping Probabilities\\n'\n  string_ekin='! 7 Ekin (a.u.)\\n0.000000000\\n'\n  string_states='! 8 states (diag, MCH)\\n0.000000000 0.000000000\\n'\n  string_random='! 9 Random number\\n0.000000000\\n'\n  string_runtime='! 10 Runtime (sec)\\n0.000000000\\n'\n  #this is done because the file has problems to do the last step - thus one step more is done and an empty file will be written and removed later\n  #if index<= nsteps-1:\n  string_geom='! 11 Geometry in a.u.\\n'\n  string_velocities='! 12 Velocities in a.u.\\n'\n  string_property2d=''\n  string_property1d=''\n  string_gradient=''\n  string_nac=''\n\n  #write string for geometires\n  for atomnr in range(natoms):\n    string_geom+='%20.12f %20.12f %20.12f\\n' %(Properties['Geometries'][atomnr][0],Properties['Geometries'][atomnr][1],Properties['Geometries'][atomnr][2])\n\n  if OUTPUT['Overlap']==True:\n    string_overlap+='! 4 Overlap matrix (MCH)\\n'\n    for numberofstates in range(nmstates):\n      for real_imag in range(nmstates*2):\n        string_overlap+='0.000000000 '\n      string_overlap+='\\n'\n\n  for numberofstates in range(nmstates):\n    string_coefficient+='0.0000000000 0.0000000000\\n'\n    string_hopping+='0.000000000 0.000000000\\n'\n    for real_imag in range(nmstates*2):\n      #if phase correction applied: Properties should be replaced with phasecorrected properties. Hamiltonian --> Hamiltonian_phasecorrected \n      if (2*numberofstates)==real_imag:\n        string_hamilton+='%20.12f ' %(Properties['Hamiltonian'][numberofstates][real_imag]-OUTPUT['ezero'])\n      else:\n        string_hamilton+='%20.12f ' %(Properties['Hamiltonian'][numberofstates][real_imag])\n      string_umatrix+='0.000000000 '\n      string_dipole_x+='%20.12f ' %Properties['Dipole_x'][numberofstates][real_imag]\n      string_dipole_y+='%20.12f ' %Properties['Dipole_y'][numberofstates][real_imag]\n      string_dipole_z+='%20.12f ' %Properties['Dipole_z'][numberofstates][real_imag]\n    string_umatrix+='\\n'\n    string_hamilton+='\\n'\n    string_dipole_x+='\\n'\n    string_dipole_y+='\\n'\n    string_dipole_z+='\\n'\n  for numberofatoms in range(natoms):\n    string_velocities+='0.000000000 0.000000000 0.000000000\\n'\n\n  if OUTPUT['Gradient']==True:\n    for numberofstates in range(nmstates):\n      string_gradient+='! 15 Gradients (MCH) State %i\\n' %(int(numberofstates)+1)\n      xyz=0\n      for numberofatoms in range(natoms*3):\n        xyz+=1\n        string_gradient+='%20.12f ' %Properties['Gradient'][numberofstates][numberofatoms]\n        if xyz>=3:\n          xyz=0\n          string_gradient+='\\n'\n\n  if int(OUTPUT['Property2d'])==1:\n    n_property2d=int(OUTPUT['n_property2d'])\n    for number in range(n_property2d):\n      string_property2d+='! 13 Property matrix (MCH)  %i : N/A\\n' %(int(number)+1)\n      for numberofstates in range(nmstates):\n        for real_imag in range(nmstates*2):\n          string_property2d+='0.000000000 '\n        string_property2d+='\\n'\n\n  if int(OUTPUT['Property1d'])==1:\n    n_property1d=int(OUTPUT['n_property1d'])\n    for number in range(n_property1d):\n      string_property1d+='! 14 Property vector (MCH)  %i : N/A\\n' %(int(number)+1)\n      for numberofstates in range(nmstates):\n        string_property1d+='0.000000000\\n'\n\n  if OUTPUT['NACdr']==True:\n    state=0\n    firststate=1\n    for nacindex in range(nmstates*nmstates):\n      state+=1\n      string_nac+='! 16 NACdr matrix element (MCH)  %i %i\\n' %(firststate, state)\n      if state >= nmstates:\n        state=0\n        firststate+=1\n      xyz=0\n      for numberofatoms_xyz in range(natoms*3):\n        xyz+=1\n        string_nac+='%20.12f ' %(Properties['NonAdiabaticCouplings'][nacindex][numberofatoms_xyz])\n        if xyz>=3:\n          xyz=0\n          string_nac+='\\n'\n\n  string_output+=string_hamilton+string_umatrix+string_dipole_x+string_dipole_y+string_dipole_z+string_overlap+string_coefficient+string_hopping+string_ekin+string_states+string_random+string_runtime+string_geom+string_velocities+string_property2d+string_property1d+string_gradient+string_nac\n  file.write(string_output)\n  file.close()\n\n  return OUTPUT\n\n\"\"\"def generate_outputdat(scanpath, nsteps):\n  #merge all output.dat files to one file called output.dat\n  outputfile = open(scanpath+\"/output.dat\", \"w\")\n  header_exists=False\n  nsteps=int(nsteps)\n  for index in range(1,nsteps):\n    infile=open(scanpath+'/output'+str(index)+'.dat', 'r').readlines()\n    is_header=True\n    for line in infile:\n      if not header_exists:\n        outputfile.write(line)\n      if 'End of header' in line:\n        is_header=False\n        header_exists=True\n        continue\n      if not is_header:\n        outputfile.write(line)\n  outputfile.close()\n  for i in range(1,nsteps):\n    os.system('rm %s/output%i.dat' %(scanpath,i))\"\"\"\n\n\n#=================================================================GET HEADER OF OUTPUT.DAT===================================================================#\ndef get_header(outputdatfile):\n\n  OUTPUT={ 'Overlap':      False,\n           'Gradient':     False,\n           'NACdr':        False,\n           'Property1d':   0,\n           'Property2d':   0,\n           'n_property1d': 1,\n           'n_property2d': 1}\n\n  data=open(outputdatfile,'r').readlines()\n  iline=-1\n  header=''\n  for line in data:\n    iline+=1\n    line_string=data[iline]\n    line=line.strip()\n    header+='%s' %line_string\n    if line.startswith('nstates_m'):\n      line = line.split()\n      n_singlets=int(line[1])\n      n_triplets=int(line[3])\n      n_dubletts=int(line[2])\n      nmstates=1*int(line[1])+2*int(line[2])+3*int(line[3])\n      OUTPUT['nmstates']=int(nmstates)\n      OUTPUT['n_singlets']=int(n_singlets)\n      OUTPUT['n_triplets']=int(n_triplets)\n    elif line.startswith('natom'):\n      line = line.split()\n      natoms=line[1]\n      OUTPUT['natoms']=int(natoms)\n    elif line.startswith('write_overlap'):\n      line=line.split()\n      if int(line[1])==1:\n        OUTPUT['Overlap']=True\n    elif line.startswith('write_grad'):\n      line=line.split()\n      if int(line[1])==1:\n        OUTPUT['Gradient']=True\n    elif line.startswith('write_nacdr'):\n      line=line.split()\n      if int(line[1])==1:\n        OUTPUT['NACdr']=True\n    elif line.startswith('write_property1d'):\n      line=line.split()\n      if int(line[1])==1:\n        OUTPUT['Property1d']=1\n    elif line.startswith('write_property2d'):\n      line=line.split()\n      if int(line[1])==1:\n        OUTPUT['Property2d']=1\n    elif line.startswith('n_property1d'):\n      line = line.split()\n      OUTPUT['n_property1d']=int(line[1])\n    elif line.startswith('n_property2d'):\n      line = line.split()\n      OUTPUT['n_property2d']=int(line[1])\n    elif line.startswith( 'ezero' ):\n      line = line.split()\n      ezero = float(line[1])\n      OUTPUT['ezero']= ezero\n    else:\n      if 'End of header' in line:\n        break\n      else:\n        continue\n\n  return header, OUTPUT\n\n#==============================================================GET GEOMETRY FROM QM.in FILE===================================================================#\ndef get_geom(natoms,QMin,Properties):\n  #get information of the geometry from the interpolated and aligned xyz-files\n  data=open(QMin, 'r').readlines()\n  iline=0\n  \"\"\"string_geom='! 11 Geometry in a.u.\\n'\n  for line in data:\n    line.strip()\n    iline+=1\n    if iline==len(data):\n      break\n    if line.startswith('tmp.pdb'):\n      for atom in range(natoms):\n        iline+=1\n        line = data[iline]\n        line = line.split()\n        string_geom+='%20.12f %20.12f %20.12f \\n' %(float(line[1]),float(line[2]),float(line[3]))\"\"\"\t\n  Geometries=np.zeros((natoms,3))\n  for line in data:\n    line.strip()\n    iline+=1\n    if iline==len(data):\n      break\n    for atom in range(natoms):\n      iline+=1\n      line=data[iline]\n      #print line\n      line=line.split()\n      #convert from Angstrom to Bohr\n      Geometries[atom][0]=float(line[1])/0.529177\n      Geometries[atom][1]=float(line[2])/0.529177\n      Geometries[atom][2]=float(line[3])/0.529177\n    break\n  Properties['Geometries'] = Geometries\n  return Properties\n\n\n\n#============================================================================================================================================================#\n#======================================================================PHASECORRECTION=======================================================================#\n#============================================================================================================================================================#\ndef phasecorrection(Properties,oldfilename,filename,newfilename,outputdatfile,inputfile,QMin):\n  #corrects the phases of the Hamiltonian (SOCs), NACs and Dipole Moments (and additionally of Overlaps)\n  header,OUTPUT=get_header(outputdatfile)\n  nmstates=OUTPUT['nmstates']\n  natoms = OUTPUT['natoms']\n  n_singlets = OUTPUT['n_singlets']\n  n_triplets = OUTPUT['n_triplets']\n  #print(n_singlets,n_triplets)\n  #if n_triplets==None:\n  #  n_triplets = int(0)\n  Properties,data=read_QMout(Properties,nmstates,n_singlets,n_triplets,filename)\n  #get ezero\n  Properties=read_input(Properties,inputfile)\n  #multiply the phasevector with the previous phasevector\n  phasevector_old = Properties['phasevector_original']\n  phasevector = Properties['phasevector']\n  phasevector = phasevector_old*phasevector\n  #print phasevector_old\n  #print Properties['phasevector']\n  #print phasevector\n  Properties.update({'phasevector': phasevector})\n  phasevector2=np.zeros((nmstates*2))\n  #double each entry of the phasevector to make calculation of real and imaginary values easier\n  for numberofstates in range(nmstates):\n    phasevector2[numberofstates*2]=phasevector[numberofstates]\n    phasevector2[numberofstates*2+1]=phasevector[numberofstates]\n\n  #DO PHASECORRECTION\n  QMout=open(newfilename, \"w\")\n  iline=-1\n  line_index=-1\n  for line in data:\n    line = line.strip()\n    iline+=1\n    line_index+=1\n    if iline==len(data):\n      break\n\n    elif line.startswith('! 1 Hamiltonian Matrix'):\n      #write the next two lines to file\n      jline=line_index\n      for i in range(2):\n        line = data[jline]\n        QMout.write(line)\n        jline+=1\n      #instead of writing the original Hamiltonian, do phasecorrection and write the new Hamiltonian \n      Hamiltonian=Properties['Hamiltonian']\n      #do calculation of rows with vector\n      Hamiltonian_phasecorrected = Hamiltonian * phasevector2\n      #do calculation of columns with vector by calculation of each row with the first entry of the vector\n      for column in range(nmstates):\n        for row_element in range(nmstates*2):\n          Hamiltonian_phasecorrected[column][row_element]=Hamiltonian_phasecorrected[column][row_element]*phasevector[column]\n      Properties.update({'Hamiltonian_phasecorrected': Hamiltonian_phasecorrected})\n      #write the Hamiltonian to QM.out (next 8 lines)\n      string_hamiltonian=''\n      for hamilton in range(nmstates):\n        for row_elements in range(nmstates*2):\n          string_hamiltonian+='%20.12f '%Hamiltonian_phasecorrected[hamilton][row_elements]\n        string_hamiltonian+='\\n'\n      string_hamiltonian+='\\n'\n      QMout.write(string_hamiltonian)\n      #substract ezero from energy values of Hamiltonian for output.dat\n      ezero = Properties['ezero']\n      Hamiltonian_phasecorrected_ezero=Hamiltonian_phasecorrected\n      for numberofstates in range(nmstates):\n        for energyvalues in range(nmstates):\n          if numberofstates == energyvalues:\n            Hamiltonian_phasecorrected_ezero[numberofstates][energyvalues*2]=Hamiltonian_phasecorrected[numberofstates][energyvalues*2]-ezero\n      Properties.update({'Hamiltonian_phasecorrected_ezero': Hamiltonian_phasecorrected_ezero})\n\n    elif line.startswith('! 2 Dipole Moment'):\n      #write the next line to the file\n      jline = line_index\n      line=data[jline]\n      QMout.write(line)\n      #do phasecorrection\n      Dipole_x=Properties['Dipole_x']\n      Dipole_y=Properties['Dipole_y']\n      Dipole_z=Properties['Dipole_z']\n      #\n      Dipole_x_phasecorrected = []\n      Dipole_y_phasecorrected = []\n      Dipole_z_phasecorrected = []\n      #\n      Dipole_x_phasecorrected = Dipole_x * phasevector2\n      Dipole_y_phasecorrected = Dipole_y * phasevector2\n      Dipole_z_phasecorrected = Dipole_z * phasevector2\n      #\n      for column in range(nmstates):\n        for row_element in range(nmstates*2):\n          Dipole_x_phasecorrected[column][row_element]=Dipole_x_phasecorrected[column][row_element]*phasevector[column]\n          Dipole_y_phasecorrected[column][row_element]=Dipole_y_phasecorrected[column][row_element]*phasevector[column]\n          Dipole_z_phasecorrected[column][row_element]=Dipole_z_phasecorrected[column][row_element]*phasevector[column]\n      #\n      Properties.update({'Dipole_x_phasecorrected': Dipole_x_phasecorrected})\n      Properties.update({'Dipole_y_phasecorrected': Dipole_y_phasecorrected})\n      Properties.update({'Dipole_z_phasecorrected': Dipole_z_phasecorrected})\n      #\n      string_dipole=''\n      jline+=1\n      line=data[jline]\n      string_dipole+='%s' %line\n      for dipole in range(nmstates):\n        for row_elements in range(nmstates*2):\n          string_dipole+='%20.12f '%Dipole_x_phasecorrected[dipole][row_elements]\n        string_dipole+='\\n'\n        jline+=1\n      jline+=1\n      line = data[jline]\n      string_dipole+='%s' %line\n      for dipole in range(nmstates):\n        for row_elements in range(nmstates*2):\n          string_dipole+='%20.12f '%Dipole_y_phasecorrected[dipole][row_elements]\n        string_dipole+='\\n'\n        jline+=1\n      jline+=1\n      line = data[jline]\n      string_dipole+='%s'%line\n      for dipole in range(nmstates):\n        for row_elements in range(nmstates*2):\n          string_dipole+='%20.12f '%Dipole_z_phasecorrected[dipole][row_elements]\n        string_dipole+='\\n'\n        jline+=1\n      #print string_dipole\n      QMout.write(string_dipole)\n\n    elif line.startswith('! 3 Gradient Vectors'):\n      #only write lines - no phasecorrection for gradients\n      #write the next lines containing gradient information to the file to the file\n      jline = line_index\n      for gradient_index in range((natoms+1)*nmstates+1):\n        line=data[jline]\n        QMout.write(line)\n        jline+=1\n\n    elif line.startswith('! 5 Non-adiabatic couplings'):\n      #write first line to the QM.out file\n      jline = line_index\n      line = data[jline]\n      QMout.write(line)\n\n      #do phasecorrection\n      NAC=Properties['NonAdiabaticCouplings']\n      #the NAC matrix is saved as a matrix containing natoms*3 entries per line (so one line contains the nacs between a specific state and another specific one)\n      #each line will be corrected with the phase - first, every line has to be corrected with the first entry of the phasecorrection vector, the second line with the second,...\n      NAC_phasecorrected = np.zeros((nmstates*nmstates,natoms*3))\n\n      #correct by multiplication with phasecorrection_vector line by line\n      phasecorrection_index_line=0 \n      for nacindex_line in range(nmstates*nmstates):\n        for nac_state_line in range(natoms*3):\n          NAC_phasecorrected[nacindex_line][nac_state_line] = NAC[nacindex_line][nac_state_line] * phasevector[phasecorrection_index_line]\n        phasecorrection_index_line+=1\n        if phasecorrection_index_line >= nmstates:\n          phasecorrection_index_line=0\n\n      #do phasecorrection column by column\n      #this means, the first nmstates*line entries have to be multiplicated by the first entry of the phasecorrection vector\n      phasecorrection_index_column=0\n      iterator=0\n      for nacindex_column in range(nmstates*nmstates):\n        for nac_state_column in range(natoms*3):\n          NAC_phasecorrected[nacindex_column][nac_state_column] = NAC_phasecorrected[nacindex_column][nac_state_column] * phasevector[phasecorrection_index_column]\n        iterator+=1\n        if iterator >= nmstates:\n          iterator=0\n          phasecorrection_index_column+=1\n      Properties.update({'NAC_phasecorrected': NAC_phasecorrected})\n\n      #make string for writing to QM.out file\n      string_nac=''\n      for nacstring in range(nmstates*nmstates):\n        #contains information about the states of the NACs\n        jline+=1\n        line=data[jline]\n        string_nac+='%s' %line\n        jline+=natoms\n        xyz_index=0\n        for nacline in range(natoms*3):\n          xyz_index+=1\n          string_nac+='%20.12f ' %NAC_phasecorrected[nacstring][nacline]\n          if xyz_index>=3:\n            xyz_index=0\n            string_nac+='\\n'\n      QMout.write(string_nac)\n\n    elif line.startswith('! 6 Overlap matrix'):\n      #write the next 2 lines to the QM.out file\n      jline = line_index\n      for index in range(2):\n        line = data[jline]\n        QMout.write(line)\n        jline+=1\n\n      Overlap=Properties['Overlap']\n      #get the old phasevector since the overlaps are mutiplied line by line with the current phasevector and column by column with the one of the previous timestep (<S1|S2>)\n      phasevector_old=Properties['phasevector_original']\n      #first phasecorrection line by line\n      Overlap_phasecorrected = Overlap * phasevector2\n      #second phasecorrection column by column\n      for lineindex in range(nmstates):\n        for overlap_index in range(nmstates*2):\n          Overlap_phasecorrected[lineindex][overlap_index] = Overlap_phasecorrected[lineindex][overlap_index] * phasevector_old[lineindex] \n      #prepare String\n      string_overlap=''\n      for overlap in range(nmstates):\n        for line_value in range(nmstates*2):\n          string_overlap+='%20.12f ' %Overlap_phasecorrected[overlap][line_value]\n        string_overlap+='\\n'\n      string_overlap+='\\n'\n      QMout.write(string_overlap)\n\n    elif line.startswith('! 7 Phases'):\n      #writes the phase vector\n      jline = line_index\n      for phasestring in range(2):\n        line = data[jline]\n        QMout.write(line)\n        jline+=1\n      string_phase=''\n      for phases in range(nmstates):\n        string_phase+='%20.12f 0.000000000\\n' %phasevector[phases]\n      QMout.write(string_phase)\n\n    else:\n      pass\n\n  QMout.close()\n\n  Properties=get_geom(natoms,QMin,Properties)\n\n  return Properties, OUTPUT\n\n\n#======================================================================READ QM.out===================================================================#\n#complementary to function \"check_phases\" from \"NN_phasecorrection.py\"\n\ndef read_QMinit_out(oldfilename,QMin,OUTPUT):\n  Properties={}\n  #get the phasevector\n  readQMout=open(oldfilename,'r')\n  data=readQMout.readlines()\n  iline=-1\n  for line in data:\n    iline+=1\n    line = line.strip()\n    if iline==len(data):\n      break\n    line=data[1]\n    t = line.split()\n    nmstates=t[0]\n    nmstates=int(nmstates)\n    Properties['nmstates']=nmstates\n    break\n  iline = -1\n  for line in data:\n    iline += 1\n    line = data[iline]\n    line = line.strip()\n    if iline == len(data):\n      break\n    elif line.startswith('! 7 Phases'):\n      iline+=1\n      line=data[iline]\n      line=line.split()\n      phasevector=np.zeros((nmstates))\n      for numberofstates in range(nmstates):\n        line = data[iline+1+numberofstates]\n        line = line.split()\n        #print line\n        phasevector[numberofstates]=line[0]\n      Properties['phasevector_original']=phasevector\n      #print Properties['phasevector_original']\n      break\n    else:\n      #set the phasevector to +1\n      phasevector=np.ones((nmstates))\n      Properties['phasevector_original']=phasevector\n  Properties,data=read_QMout(Properties,nmstates,OUTPUT['n_singlets'], OUTPUT['n_triplets'],oldfilename)\n  Properties=get_geom(OUTPUT['natoms'],QMin,Properties)\n  return Properties\n\ndef read_QMout(Properties,nmstates,n_singlets,n_triplets,filename):\n  #iterate over QM.out files\n  Properties.update({'phasevector':\t\tFalse,\n\t\t\t  'Hamiltonian':\t\tFalse,\n\t\t\t  'Dipole_x':   \t\tFalse,\n\t\t\t  'Dipole_y':   \t\tFalse,\n\t\t\t  'Dipole_z':   \t\tFalse,\n\t\t\t  'Gradient':  \t\t\tFalse,\n\t\t\t  'NonAdibaticCouplings':\tFalse,\n\t\t\t  'Overlap':\t\t\tFalse})\n  #start from 1 because the inital file does not have to be included \n  readQMout=open(filename, \"r\")\n  data=readQMout.readlines()\n  readQMout.close()\n  overlap_vector_correct=np.zeros((nmstates))\n  threshold = float(0.5)\n  iline=-1\n  #print( n_singlets, n_triplets)\n  for line in data:\n    line=line.strip()\n    iline+=1\n    if line.startswith(\"! 6 Overlap matrix\" ):\n      iline+=1\n      #check phases of singlets only\n      for overlaps_singlets in range(n_singlets):\n        iline+=1\n        line = data[iline]\n        line = line.split()\n        overlap_singlets = float(line[2*overlaps_singlets])\n        #print( overlap)\n        if abs(overlap_singlets) < threshold:\n          for overlaps_stateswitch in range(n_singlets):\n            overlap_switched_state = float(line[2*overlaps_stateswitch])\n            #print (overlap_switched_state)\n            if abs(overlap_switched_state) > threshold:\n              #print(\"states switched\")\n              overlap_singlets = overlap_switched_state\n              if overlap_singlets < int(0):\n                overlap_singlets = int(-1)\n              else:\n                overlap_singlets = int(1)\n        else:\n          if overlap_singlets < int(0):\n            overlap_singlets = int(-1)\n          else:\n            overlap_singlets = int(1)\n        overlap_vector_correct[overlaps_singlets]=overlap_singlets\n      #check phases of triplets - do this three times since triplets are three times degenerated\n      triplet_nmstate_0=int(0)\n      triplet_nmstate_1=int(0)\n      if n_triplets==0:\n        pass\n      else:\n        for triplet_number in range(1):\n          triplet_nmstate_0=triplet_nmstate_1\n          triplet_nmstate_1=triplet_nmstate_0+1\n          #print(triplet_magnetic, \"should start with 1\")\n          for overlaps_triplets in range(n_singlets*triplet_nmstate_0,n_singlets+triplet_nmstate_1*n_triplets):\n            iline+=1 \n            line = data[iline]\n            line = line.split()\n            overlap_triplets = float(line[2*overlaps_triplets])\n            if abs(overlap_triplets) < threshold:\n              for overlaps_stateswitch_triplets in range(n_singlets*triplet_nmstate_0,n_singlets+triplet_nmstate_1*n_triplets):\n                overlap_switched_state_triplet = float(line[2*overlaps_stateswitch_triplets])\n                if abs(overlap_switched_state_triplet) > threshold:\n                  overlap_triplets = overlap_switched_state_triplet\n                  if overlap_triplets < int(0):\n                    overlap_triplets = int(-1)\n                  else:\n                    overlap_triplets = int(1)\n            else:\n              if overlap_triplets < int(0):\n                overlap_triplets = int(-1)\n              else:\n                overlap_triplets = int(1)\n            overlap_vector_correct[overlaps_triplets]=overlap_triplets\n    #get number of states and write out vector with phases\n    \"\"\"if line.startswith(\"! 7 Phases\"):\n      phasevector=np.zeros((nmstates))\n      for numberofstates in range(nmstates):\n        line=data[iline+2+numberofstates]\n        line=line.split()\n        phasevector[numberofstates]=line[0]\t\n      Properties['phasevector']=phasevector\n      break\"\"\"\n  iline=-1\n  #print(overlap_vector_correct)\n  Properties['phasevector']=overlap_vector_correct\n  for line in data:\n    line=line.strip()\n    iline+=1\n    if line.startswith('! 1 Hamiltonian Matrix'):\n      Hamiltonian=np.zeros((nmstates,nmstates*2))\n      for numberofstates in range(nmstates):\n        line=data[iline+2+numberofstates]\n        line=line.split()\n        for real_imag in range(nmstates*2):\n          Hamiltonian[numberofstates][real_imag]=line[real_imag]\n      Properties['Hamiltonian']=Hamiltonian\n    elif line.startswith('! 2 Dipole Moment Matrices'):\n      Dipole_x=np.zeros((nmstates,nmstates*2))\n      Dipole_y=np.zeros((nmstates,nmstates*2))\n      Dipole_z=np.zeros((nmstates,nmstates*2))\n      for numberofstates in range(nmstates):\n        line_x=data[iline+2+numberofstates]\n        line_x=line_x.split()\n        line_y=data[iline+3+nmstates+numberofstates]\n        line_y=line_y.split()\n        line_z=data[iline+4+nmstates*2+numberofstates]\n        line_z=line_z.split()\n        for real_imag in range(nmstates*2): \n          Dipole_x[numberofstates][real_imag]=line_x[real_imag]\n          Dipole_y[numberofstates][real_imag]=line_y[real_imag]\n          Dipole_z[numberofstates][real_imag]=line_z[real_imag]\n      Properties['Dipole_x']=Dipole_x\n      Properties['Dipole_y']=Dipole_y\n      Properties['Dipole_z']=Dipole_z\n    elif line.startswith('! 3 Gradient Vectors'):\n      line=data[iline+1]\n      line=line.split()\n      natoms=int(line[0])\n      Properties.update({'natoms': natoms})\n      #writes the gradient tensor in form of a matrix  -  every natomsx(x,y,z) matrix is written as one vector\n      Gradient=np.zeros((nmstates,natoms*3))\n      index=0\n      for numberofstates in range(nmstates):\n        index+=1\n        gradientindex=0\n        for atom_index in range(natoms):\n          index+=1\n          line=data[iline+index]\n          line=line.split()\n          for xyz in range(3):\n            Gradient[numberofstates][gradientindex]=line[xyz]\n            gradientindex+=1\n      Properties['Gradient']=Gradient\n    elif line.startswith('! 5 Non-adiabatic couplings'):\n      #the nacs will be written as a matrix with the size: (numberofstatesxnumberofstates)x(natoms*3(xyz))\n      NAC=np.zeros((nmstates*nmstates,natoms*3))\n      index=0\n      for numberofstates in range(nmstates*nmstates):\n        index+=1\n        nacindex=0\n        for atom_index in range(natoms):\n          index+=1\n          line=data[iline+index]\n          line=line.split()\n          for xyz in range(3):\n            NAC[numberofstates][nacindex]=line[xyz]\n            nacindex+=1\n      Properties['NonAdiabaticCouplings']=NAC\n    elif line.startswith('! 6 Overlap matrix'):\n      overlap=np.zeros((nmstates,nmstates*2))\n      for numberofstates in range(nmstates):\n        line=data[iline+2+numberofstates]\n        line=line.split()\n        for real_imag in range(nmstates*2):\n          overlap[numberofstates][real_imag]=line[real_imag]\n      Properties['Overlap']=overlap\n\n  return Properties, data\n\n\n\ndef read_input(Properties, inputfile):\n  inputf=open(inputfile, 'r').readlines()\n  for line in inputf:\n    line=line.strip()\n    if line.startswith( 'ezero' ):\n      line = line.split()\n      ezero = float(line[1])\n      Properties.update({'ezero': ezero})\n  return Properties\n\n\n\nif __name__ == \"__main__\":\n  try:\n    name,outputdatforheader, QMin = argv\n  except ValueError:\n    print( \"Usage: script <output.dat file for header information> <file of geometry used for calcualtion of QMout; often QM.in>\")\n    exit()\n  outputdatfile = argv[1]\n  filename=str(\"QM.out\")\n  inputfile=argv[2]\n  header,OUTPUT=get_header(outputdatfile)\n  Properties=read_QMinit_out(filename,QMin,OUTPUT)\n  #Properties,OUTPUT=phasecorrection(Properties,filename,outputdatfile,inputfile)\n  qm2outputdat(Properties,outputdatfile)\n", "meta": {"hexsha": "1ec3b605d8f8874737d51980730696b0c0a150c4", "size": 29526, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/scripts/QM2output.py", "max_stars_repo_name": "smausenberger/SchNarc", "max_stars_repo_head_hexsha": "727dedf300aa79c01217822c3a9a4f4ae96ede60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-05-07T19:45:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T22:22:18.000Z", "max_issues_repo_path": "src/scripts/QM2output.py", "max_issues_repo_name": "smausenberger/SchNarc", "max_issues_repo_head_hexsha": "727dedf300aa79c01217822c3a9a4f4ae96ede60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-25T10:39:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T10:39:16.000Z", "max_forks_repo_path": "src/scripts/QM2output.py", "max_forks_repo_name": "smausenberger/SchNarc", "max_forks_repo_head_hexsha": "727dedf300aa79c01217822c3a9a4f4ae96ede60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-08-13T19:57:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T10:37:04.000Z", "avg_line_length": 39.685483871, "max_line_length": 292, "alphanum_fraction": 0.6437377227, "include": true, "reason": "import numpy", "num_tokens": 7607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.18938381791895248}}
{"text": "\"\"\"\nClass interface to the model calculator.\n\nCalling a model is somewhat non-trivial since the functions called depend\non the data type.  For 1D data the *Iq* kernel needs to be called, for\n2D data the *Iqxy* kernel needs to be called, and for SESANS data the\n*Iq* kernel needs to be called followed by a Hankel transform.  Before\nthe kernel is called an appropriate *q* calculation vector needs to be\nconstructed.  This is not the simple *q* vector where you have measured\nthe data since the resolution calculation will require values beyond the\nrange of the measured data.  After the calculation the resolution calculator\nmust be called to return the predicted value for each measured data point.\n\n:class:`DirectModel` is a callable object that takes *parameter=value*\nkeyword arguments and returns the appropriate theory values for the data.\n\n:class:`DataMixin` does the real work of interpreting the data and calling\nthe model calculator.  This is used by :class:`DirectModel`, which uses\ndirect parameter values and by :class:`bumps_model.Experiment` which wraps\nthe parameter values in boxes so that the user can set fitting ranges, etc.\non the individual parameters and send the model to the Bumps optimizers.\n\"\"\"\nfrom __future__ import print_function\n\nimport numpy as np  # type: ignore\n\n# TODO: fix sesans module\nfrom . import sesans  # type: ignore\nfrom . import weights\nfrom . import resolution\nfrom . import resolution2d\nfrom .details import make_kernel_args, dispersion_mesh\n\ntry:\n    from typing import Optional, Dict, Tuple\nexcept ImportError:\n    pass\nelse:\n    from .data import Data\n    from .kernel import Kernel, KernelModel\n    from .modelinfo import Parameter, ParameterSet\n\ndef call_kernel(calculator, pars, cutoff=0., mono=False):\n    # type: (Kernel, ParameterSet, float, bool) -> np.ndarray\n    \"\"\"\n    Call *kernel* returned from *model.make_kernel* with parameters *pars*.\n\n    *cutoff* is the limiting value for the product of dispersion weights used\n    to perform the multidimensional dispersion calculation more quickly at a\n    slight cost to accuracy. The default value of *cutoff=0* integrates over\n    the entire dispersion cube.  Using *cutoff=1e-5* can be 50% faster, but\n    with an error of about 1%, which is usually less than the measurement\n    uncertainty.\n\n    *mono* is True if polydispersity should be set to none on all parameters.\n    \"\"\"\n    parameters = calculator.info.parameters\n    if mono:\n        active = lambda name: False\n    elif calculator.dim == '1d':\n        active = lambda name: name in parameters.pd_1d\n    elif calculator.dim == '2d':\n        active = lambda name: name in parameters.pd_2d\n    else:\n        active = lambda name: True\n\n    #print(\"pars\",[p.id for p in parameters.call_parameters])\n    vw_pairs = [(get_weights(p, pars) if active(p.name)\n                 else ([pars.get(p.name, p.default)], [1.0]))\n                for p in parameters.call_parameters]\n\n    call_details, values, is_magnetic = make_kernel_args(calculator, vw_pairs)\n    #print(\"values:\", values)\n    return calculator(call_details, values, cutoff, is_magnetic)\n\n\ndef call_ER(model_info, pars):\n    # type: (ModelInfo, ParameterSet) -> float\n    \"\"\"\n    Call the model ER function using *values*.\n\n    *model_info* is either *model.info* if you have a loaded model,\n    or *kernel.info* if you have a model kernel prepared for evaluation.\n    \"\"\"\n    if model_info.ER is None:\n        return 1.0\n    elif not model_info.parameters.form_volume_parameters:\n        # handle the case where ER is provided but model is not polydisperse\n        return model_info.ER()\n    else:\n        value, weight = _vol_pars(model_info, pars)\n        individual_radii = model_info.ER(*value)\n        return np.sum(weight*individual_radii) / np.sum(weight)\n\n\ndef call_VR(model_info, pars):\n    # type: (ModelInfo, ParameterSet) -> float\n    \"\"\"\n    Call the model VR function using *pars*.\n\n    *model_info* is either *model.info* if you have a loaded model,\n    or *kernel.info* if you have a model kernel prepared for evaluation.\n    \"\"\"\n    if model_info.VR is None:\n        return 1.0\n    elif not model_info.parameters.form_volume_parameters:\n        # handle the case where ER is provided but model is not polydisperse\n        return model_info.VR()\n    else:\n        value, weight = _vol_pars(model_info, pars)\n        whole, part = model_info.VR(*value)\n        return np.sum(weight*part)/np.sum(weight*whole)\n\n\ndef call_profile(model_info, **pars):\n    # type: (ModelInfo, ...) -> Tuple[np.ndarray, np.ndarray, Tuple[str, str]]\n    \"\"\"\n    Returns the profile *x, y, (xlabel, ylabel)* representing the model.\n    \"\"\"\n    args = {}\n    for p in model_info.parameters.kernel_parameters:\n        if p.length > 1:\n            value = np.array([pars.get(p.id+str(j), p.default)\n                              for j in range(1, p.length+1)])\n        else:\n            value = pars.get(p.id, p.default)\n        args[p.id] = value\n    x, y = model_info.profile(**args)\n    return x, y, model_info.profile_axes\n\n\ndef get_weights(parameter, values):\n    # type: (Parameter, Dict[str, float]) -> Tuple[np.ndarray, np.ndarray]\n    \"\"\"\n    Generate the distribution for parameter *name* given the parameter values\n    in *pars*.\n\n    Uses \"name\", \"name_pd\", \"name_pd_type\", \"name_pd_n\", \"name_pd_sigma\"\n    from the *pars* dictionary for parameter value and parameter dispersion.\n    \"\"\"\n    value = float(values.get(parameter.name, parameter.default))\n    relative = parameter.relative_pd\n    limits = parameter.limits\n    disperser = values.get(parameter.name+'_pd_type', 'gaussian')\n    npts = values.get(parameter.name+'_pd_n', 0)\n    width = values.get(parameter.name+'_pd', 0.0)\n    nsigma = values.get(parameter.name+'_pd_nsigma', 3.0)\n    if npts == 0 or width == 0:\n        return [value], [1.0]\n    value, weight = weights.get_weights(\n        disperser, npts, width, nsigma, value, limits, relative)\n    return value, weight / np.sum(weight)\n\n\ndef _vol_pars(model_info, pars):\n    # type: (ModelInfo, ParameterSet) -> Tuple[np.ndarray, np.ndarray]\n    vol_pars = [get_weights(p, pars)\n                for p in model_info.parameters.call_parameters\n                if p.type == 'volume']\n    #import pylab; pylab.plot(vol_pars[0][0],vol_pars[0][1]); pylab.show()\n    value, weight = dispersion_mesh(model_info, vol_pars)\n    return value, weight\n\n\nclass DataMixin(object):\n    \"\"\"\n    DataMixin captures the common aspects of evaluating a SAS model for a\n    particular data set, including calculating Iq and evaluating the\n    resolution function.  It is used in particular by :class:`DirectModel`,\n    which evaluates a SAS model parameters as key word arguments to the\n    calculator method, and by :class:`bumps_model.Experiment`, which wraps the\n    model and data for use with the Bumps fitting engine.  It is not\n    currently used by :class:`sasview_model.SasviewModel` since this will\n    require a number of changes to SasView before we can do it.\n\n    :meth:`_interpret_data` initializes the data structures necessary\n    to manage the calculations.  This sets attributes in the child class\n    such as *data_type* and *resolution*.\n\n    :meth:`_calc_theory` evaluates the model at the given control values.\n\n    :meth:`_set_data` sets the intensity data in the data object,\n    possibly with random noise added.  This is useful for simulating a\n    dataset with the results from :meth:`_calc_theory`.\n    \"\"\"\n    def _interpret_data(self, data, model):\n        # type: (Data, KernelModel) -> None\n        # pylint: disable=attribute-defined-outside-init\n\n        self._data = data\n        self._model = model\n\n        # interpret data\n        if hasattr(data, 'isSesans') and data.isSesans:\n            self.data_type = 'sesans'\n        elif hasattr(data, 'qx_data'):\n            self.data_type = 'Iqxy'\n        elif getattr(data, 'oriented', False):\n            self.data_type = 'Iq-oriented'\n        else:\n            self.data_type = 'Iq'\n\n        if self.data_type == 'sesans':\n            q = sesans.make_q(data.sample.zacceptance, data.Rmax)\n            index = slice(None, None)\n            res = None\n            if data.y is not None:\n                Iq, dIq = data.y, data.dy\n            else:\n                Iq, dIq = None, None\n            #self._theory = np.zeros_like(q)\n            q_vectors = [q]\n            q_mono = sesans.make_all_q(data)\n        elif self.data_type == 'Iqxy':\n            #if not model.info.parameters.has_2d:\n            #    raise ValueError(\"not 2D without orientation or magnetic parameters\")\n            q = np.sqrt(data.qx_data**2 + data.qy_data**2)\n            qmin = getattr(data, 'qmin', 1e-16)\n            qmax = getattr(data, 'qmax', np.inf)\n            accuracy = getattr(data, 'accuracy', 'Low')\n            index = ~data.mask & (q >= qmin) & (q <= qmax)\n            if data.data is not None:\n                index &= ~np.isnan(data.data)\n                Iq = data.data[index]\n                dIq = data.err_data[index]\n            else:\n                Iq, dIq = None, None\n            res = resolution2d.Pinhole2D(data=data, index=index,\n                                         nsigma=3.0, accuracy=accuracy)\n            #self._theory = np.zeros_like(self.Iq)\n            q_vectors = res.q_calc\n            q_mono = []\n        elif self.data_type == 'Iq':\n            index = (data.x >= data.qmin) & (data.x <= data.qmax)\n            if data.y is not None:\n                index &= ~np.isnan(data.y)\n                Iq = data.y[index]\n                dIq = data.dy[index]\n            else:\n                Iq, dIq = None, None\n            if getattr(data, 'dx', None) is not None:\n                q, dq = data.x[index], data.dx[index]\n                if (dq > 0).any():\n                    res = resolution.Pinhole1D(q, dq)\n                else:\n                    res = resolution.Perfect1D(q)\n            elif (getattr(data, 'dxl', None) is not None\n                  and getattr(data, 'dxw', None) is not None):\n                res = resolution.Slit1D(data.x[index],\n                                        qx_width=data.dxl[index],\n                                        qy_width=data.dxw[index])\n            else:\n                res = resolution.Perfect1D(data.x[index])\n\n            #self._theory = np.zeros_like(self.Iq)\n            q_vectors = [res.q_calc]\n            q_mono = []\n        elif self.data_type == 'Iq-oriented':\n            index = (data.x >= data.qmin) & (data.x <= data.qmax)\n            if data.y is not None:\n                index &= ~np.isnan(data.y)\n                Iq = data.y[index]\n                dIq = data.dy[index]\n            else:\n                Iq, dIq = None, None\n            if (getattr(data, 'dxl', None) is None\n                    or getattr(data, 'dxw', None) is None):\n                raise ValueError(\"oriented sample with 1D data needs slit resolution\")\n\n            res = resolution2d.Slit2D(data.x[index],\n                                      qx_width=data.dxw[index],\n                                      qy_width=data.dxl[index])\n            q_vectors = res.q_calc\n            q_mono = []\n        else:\n            raise ValueError(\"Unknown data type\") # never gets here\n\n        # Remember function inputs so we can delay loading the function and\n        # so we can save/restore state\n        self._kernel_inputs = q_vectors\n        self._kernel_mono_inputs = q_mono\n        self._kernel = None\n        self.Iq, self.dIq, self.index = Iq, dIq, index\n        self.resolution = res\n\n    def _set_data(self, Iq, noise=None):\n        # type: (np.ndarray, Optional[float]) -> None\n        # pylint: disable=attribute-defined-outside-init\n        if noise is not None:\n            self.dIq = Iq*noise*0.01\n        dy = self.dIq\n        y = Iq + np.random.randn(*dy.shape) * dy\n        self.Iq = y\n        if self.data_type in ('Iq', 'Iq-oriented'):\n            self._data.dy[self.index] = dy\n            self._data.y[self.index] = y\n        elif self.data_type == 'Iqxy':\n            self._data.data[self.index] = y\n        elif self.data_type == 'sesans':\n            self._data.y[self.index] = y\n        else:\n            raise ValueError(\"Unknown model\")\n\n    def _calc_theory(self, pars, cutoff=0.0):\n        # type: (ParameterSet, float) -> np.ndarray\n        if self._kernel is None:\n            self._kernel = self._model.make_kernel(self._kernel_inputs)\n            self._kernel_mono = (\n                self._model.make_kernel(self._kernel_mono_inputs)\n                if self._kernel_mono_inputs else None)\n\n        Iq_calc = call_kernel(self._kernel, pars, cutoff=cutoff)\n        # Storing the calculated Iq values so that they can be plotted.\n        # Only applies to oriented USANS data for now.\n        # TODO: extend plotting of calculate Iq to other measurement types\n        # TODO: refactor so we don't store the result in the model\n        self.Iq_calc = None\n        if self.data_type == 'sesans':\n            Iq_mono = (call_kernel(self._kernel_mono, pars, mono=True)\n                       if self._kernel_mono_inputs else None)\n            result = sesans.transform(self._data,\n                                      self._kernel_inputs[0], Iq_calc,\n                                      self._kernel_mono_inputs, Iq_mono)\n        else:\n            result = self.resolution.apply(Iq_calc)\n            if hasattr(self.resolution, 'nx'):\n                self.Iq_calc = (\n                    self.resolution.qx_calc, self.resolution.qy_calc,\n                    np.reshape(Iq_calc, (self.resolution.ny, self.resolution.nx))\n                )\n        return result\n\n\nclass DirectModel(DataMixin):\n    \"\"\"\n    Create a calculator object for a model.\n\n    *data* is 1D SAS, 2D SAS or SESANS data\n\n    *model* is a model calculator return from :func:`generate.load_model`\n\n    *cutoff* is the polydispersity weight cutoff.\n    \"\"\"\n    def __init__(self, data, model, cutoff=1e-5):\n        # type: (Data, KernelModel, float) -> None\n        self.model = model\n        self.cutoff = cutoff\n        # Note: _interpret_data defines the model attributes\n        self._interpret_data(data, model)\n\n    def __call__(self, **pars):\n        # type: (**float) -> np.ndarray\n        return self._calc_theory(pars, cutoff=self.cutoff)\n\n    def simulate_data(self, noise=None, **pars):\n        # type: (Optional[float], **float) -> None\n        \"\"\"\n        Generate simulated data for the model.\n        \"\"\"\n        Iq = self.__call__(**pars)\n        self._set_data(Iq, noise=noise)\n\n    def profile(self, **pars):\n        # type: (**float) -> None\n        \"\"\"\n        Generate a plottable profile.\n        \"\"\"\n        return call_profile(self.model.info, **pars)\n\ndef main():\n    # type: () -> None\n    \"\"\"\n    Program to evaluate a particular model at a set of q values.\n    \"\"\"\n    import sys\n    from .data import empty_data1D, empty_data2D\n    from .core import load_model_info, build_model\n\n    if len(sys.argv) < 3:\n        print(\"usage: python -m sasmodels.direct_model modelname (q|qx,qy) par=val ...\")\n        sys.exit(1)\n    model_name = sys.argv[1]\n    call = sys.argv[2].upper()\n    if call != \"ER_VR\":\n        try:\n            values = [float(v) for v in call.split(',')]\n        except Exception:\n            values = []\n        if len(values) == 1:\n            q, = values\n            data = empty_data1D([q])\n        elif len(values) == 2:\n            qx, qy = values\n            data = empty_data2D([qx], [qy])\n        else:\n            print(\"use q or qx,qy or ER or VR\")\n            sys.exit(1)\n    else:\n        data = empty_data1D([0.001])  # Data not used in ER/VR\n\n    model_info = load_model_info(model_name)\n    model = build_model(model_info)\n    calculator = DirectModel(data, model)\n    pars = dict((k, (float(v) if not k.endswith(\"_pd_type\") else v))\n                for pair in sys.argv[3:]\n                for k, v in [pair.split('=')])\n    if call == \"ER_VR\":\n        ER = call_ER(model_info, pars)\n        VR = call_VR(model_info, pars)\n        print(ER, VR)\n    else:\n        Iq = calculator(**pars)\n        print(Iq[0])\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "386e852f93c55ade7ad9e6563bf61d2a49ca80b8", "size": 16155, "ext": "py", "lang": "Python", "max_stars_repo_path": "sasmodels/direct_model.py", "max_stars_repo_name": "jmborr/sasmodels", "max_stars_repo_head_hexsha": "bedb9b0fed4f3f4bc2bbfa5878de6f2b6fdfbcc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sasmodels/direct_model.py", "max_issues_repo_name": "jmborr/sasmodels", "max_issues_repo_head_hexsha": "bedb9b0fed4f3f4bc2bbfa5878de6f2b6fdfbcc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sasmodels/direct_model.py", "max_forks_repo_name": "jmborr/sasmodels", "max_forks_repo_head_hexsha": "bedb9b0fed4f3f4bc2bbfa5878de6f2b6fdfbcc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-28T14:21:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T14:21:17.000Z", "avg_line_length": 38.7410071942, "max_line_length": 88, "alphanum_fraction": 0.6060662334, "include": true, "reason": "import numpy", "num_tokens": 3909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.18932354629148812}}
{"text": "# -*- coding: utf-8 -*-\n\n# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2020.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"Parametric waveforms module. These are pulses which are described by a specified\nparameterization.\n\nIf a backend supports parametric pulses, it will have the attribute\n`backend.configuration().parametric_pulses`, which is a list of supported pulse shapes, such as\n`['gaussian', 'gaussian_square', 'drag']`. A Pulse Schedule, using parametric pulses, which is\nassembled for a backend which supports those pulses, will result in a Qobj which is dramatically\nsmaller than one which uses Waveforms.\n\nThis module can easily be extended to describe more pulse shapes. The new class should:\n  - have a descriptive name\n  - be a well known and/or well described formula (include the formula in the class docstring)\n  - take some parameters (at least `duration`) and validate them, if necessary\n  - implement a `get_waveform` method which returns a corresponding Waveform in the\n    case that it is assembled for a backend which does not support it.\n\nThe new pulse must then be registered by the assembler in\n`qiskit/qobj/converters/pulse_instruction.py:ParametricPulseShapes`\nby following the existing pattern:\n\n    class ParametricPulseShapes(Enum):\n        gaussian = pulse_lib.Gaussian\n        ...\n        new_supported_pulse_name = pulse_lib.YourPulseWaveformClass\n\"\"\"\nimport warnings\nfrom abc import abstractmethod\nfrom typing import Any, Callable, Dict, Optional\nimport math\nimport numpy as np\n\nfrom . import continuous\nfrom .discrete import gaussian, gaussian_square, drag, constant\nfrom .pulse import Pulse\nfrom .waveform import Waveform\nfrom ..exceptions import PulseError\n\n\nclass ParametricPulse(Pulse):\n    \"\"\"The abstract superclass for parametric pulses.\"\"\"\n\n    @abstractmethod\n    def __init__(self, duration: int, name: Optional[str] = None):\n        \"\"\"Create a parametric pulse and validate the input parameters.\n\n        Args:\n            duration: Pulse length in terms of the the sampling period `dt`.\n            name: Display name for this pulse envelope.\n        \"\"\"\n        super().__init__(duration=duration, name=name)\n        self.validate_parameters()\n\n    @abstractmethod\n    def get_waveform(self) -> Waveform:\n        \"\"\"Return a Waveform with samples filled according to the formula that the pulse\n        represents and the parameter values it contains.\n        \"\"\"\n        raise NotImplementedError\n\n    def get_sample_pulse(self) -> Waveform:\n        \"\"\"Deprecated.\"\"\"\n        warnings.warn('`get_sample_pulse` has been deprecated. '\n                      ' Use `get_waveform` instead.', DeprecationWarning)\n        return self.get_waveform()\n\n    @abstractmethod\n    def validate_parameters(self) -> None:\n        \"\"\"\n        Validate parameters.\n\n        Raises:\n            PulseError: If the parameters passed are not valid.\n        \"\"\"\n        raise NotImplementedError\n\n    @property\n    @abstractmethod\n    def parameters(self) -> Dict[str, Any]:\n        \"\"\"Return a dictionary containing the pulse's parameters.\"\"\"\n        pass\n\n    def draw(self, dt: float = 1,\n             style=None,\n             filename: Optional[str] = None,\n             interp_method: Optional[Callable] = None,\n             scale: float = 1, interactive: bool = False):\n        \"\"\"Plot the pulse.\n\n        Args:\n            dt: Time interval of samples.\n            style (Optional[PulseStyle]): A style sheet to configure plot appearance\n            filename: Name required to save pulse image\n            interp_method: A function for interpolation\n            scale: Relative visual scaling of waveform amplitudes\n            interactive: When set true show the circuit in a new window\n                (this depends on the matplotlib backend being used supporting this)\n\n        Returns:\n            matplotlib.figure: A matplotlib figure object of the pulse envelope\n        \"\"\"\n        return self.get_waveform().draw(dt=dt, style=style, filename=filename,\n                                        interp_method=interp_method, scale=scale,\n                                        interactive=interactive)\n\n    def __eq__(self, other: Pulse) -> bool:\n        return super().__eq__(other) and self.parameters == other.parameters\n\n    def __hash__(self) -> int:\n        return hash(self.parameters[k] for k in sorted(self.parameters))\n\n\nclass Gaussian(ParametricPulse):\n    \"\"\"A truncated pulse envelope shaped according to the Gaussian function whose mean is centered\n    at the center of the pulse (duration / 2):\n\n    .. math::\n\n        f(x) = amp * exp( -(1/2) * (x - duration/2)^2 / sigma^2) )  ,  0 <= x < duration\n    \"\"\"\n\n    def __init__(self,\n                 duration: int,\n                 amp: complex,\n                 sigma: float,\n                 name: Optional[str] = None):\n        \"\"\"Initialize the gaussian pulse.\n\n        Args:\n            duration: Pulse length in terms of the the sampling period `dt`.\n            amp: The amplitude of the Gaussian envelope.\n            sigma: A measure of how wide or narrow the Gaussian peak is; described mathematically\n                   in the class docstring.\n            name: Display name for this pulse envelope.\n        \"\"\"\n        self._amp = complex(amp)\n        self._sigma = sigma\n        super().__init__(duration=duration, name=name)\n\n    @property\n    def amp(self) -> complex:\n        \"\"\"The Gaussian amplitude.\"\"\"\n        return self._amp\n\n    @property\n    def sigma(self) -> float:\n        \"\"\"The Gaussian standard deviation of the pulse width.\"\"\"\n        return self._sigma\n\n    def get_waveform(self) -> Waveform:\n        return gaussian(duration=self.duration, amp=self.amp,\n                        sigma=self.sigma, zero_ends=False)\n\n    def validate_parameters(self) -> None:\n        if abs(self.amp) > 1.:\n            raise PulseError(\"The amplitude norm must be <= 1, \"\n                             \"found: {}\".format(abs(self.amp)))\n        if self.sigma <= 0:\n            raise PulseError(\"Sigma must be greater than 0.\")\n\n    @property\n    def parameters(self) -> Dict[str, Any]:\n        return {\"duration\": self.duration, \"amp\": self.amp, \"sigma\": self.sigma}\n\n    def __repr__(self) -> str:\n        return \"{}(duration={}, amp={}, sigma={}{})\" \\\n               \"\".format(self.__class__.__name__, self.duration, self.amp, self.sigma,\n                         \", name='{}'\".format(self.name) if self.name is not None else \"\")\n\n\nclass GaussianSquare(ParametricPulse):\n    \"\"\"A square pulse with a Gaussian shaped risefall on either side:\n\n    .. math::\n\n        risefall = (duration - width) / 2\n\n        0 <= x < risefall\n\n        f(x) = amp * exp( -(1/2) * (x - risefall/2)^2 / sigma^2) )\n\n        risefall <= x < risefall + width\n\n        f(x) = amp\n\n        risefall + width <= x < duration\n\n        f(x) = amp * exp( -(1/2) * (x - (risefall + width)/2)^2 / sigma^2) )\n    \"\"\"\n\n    def __init__(self,\n                 duration: int,\n                 amp: complex,\n                 sigma: float,\n                 width: float,\n                 name: Optional[str] = None):\n        \"\"\"Initialize the gaussian square pulse.\n\n        Args:\n            duration: Pulse length in terms of the the sampling period `dt`.\n            amp: The amplitude of the Gaussian and of the square pulse.\n            sigma: A measure of how wide or narrow the Gaussian risefall is; see the class\n                   docstring for more details.\n            width: The duration of the embedded square pulse.\n            name: Display name for this pulse envelope.\n        \"\"\"\n        self._amp = complex(amp)\n        self._sigma = sigma\n        self._width = width\n        super().__init__(duration=duration, name=name)\n\n    @property\n    def amp(self) -> complex:\n        \"\"\"The Gaussian amplitude.\"\"\"\n        return self._amp\n\n    @property\n    def sigma(self) -> float:\n        \"\"\"The Gaussian standard deviation of the pulse width.\"\"\"\n        return self._sigma\n\n    @property\n    def width(self) -> float:\n        \"\"\"The width of the square portion of the pulse.\"\"\"\n        return self._width\n\n    def get_waveform(self) -> Waveform:\n        return gaussian_square(duration=self.duration, amp=self.amp,\n                               width=self.width, sigma=self.sigma,\n                               zero_ends=False)\n\n    def validate_parameters(self) -> None:\n        if abs(self.amp) > 1.:\n            raise PulseError(\"The amplitude norm must be <= 1, \"\n                             \"found: {}\".format(abs(self.amp)))\n        if self.sigma <= 0:\n            raise PulseError(\"Sigma must be greater than 0.\")\n        if self.width < 0 or self.width >= self.duration:\n            raise PulseError(\"The pulse width must be at least 0 and less than its duration.\")\n\n    @property\n    def parameters(self) -> Dict[str, Any]:\n        return {\"duration\": self.duration, \"amp\": self.amp, \"sigma\": self.sigma,\n                \"width\": self.width}\n\n    def __repr__(self) -> str:\n        return \"{}(duration={}, amp={}, sigma={}, width={}{})\" \\\n               \"\".format(self.__class__.__name__, self.duration, self.amp, self.sigma, self.width,\n                         \", name='{}'\".format(self.name) if self.name is not None else \"\")\n\n\nclass Drag(ParametricPulse):\n    r\"\"\"The Derivative Removal by Adiabatic Gate (DRAG) pulse is a standard Gaussian pulse\n    with an additional Gaussian derivative component. It is designed to reduce the frequency\n    spectrum of a normal gaussian pulse near the :math:`|1\\rangle` - :math:`|2\\rangle` transition,\n    reducing the chance of leakage to the :math:`|2\\rangle` state.\n\n    .. math::\n\n        f(x) = Gaussian + 1j * beta * d/dx [Gaussian]\n             = Gaussian + 1j * beta * (-(x - duration/2) / sigma^2) [Gaussian]\n\n    where 'Gaussian' is:\n\n    .. math::\n\n        Gaussian(x, amp, sigma) = amp * exp( -(1/2) * (x - duration/2)^2 / sigma^2) )\n\n    References:\n        1. |citation1|_\n\n        .. _citation1: https://link.aps.org/doi/10.1103/PhysRevA.83.012308\n\n        .. |citation1| replace:: *Gambetta, J. M., Motzoi, F., Merkel, S. T. & Wilhelm, F. K.\n           Analytic control methods for high-fidelity unitary operations\n           in a weakly nonlinear oscillator. Phys. Rev. A 83, 012308 (2011).*\n\n        2. |citation2|_\n\n        .. _citation2: https://link.aps.org/doi/10.1103/PhysRevLett.103.110501\n\n        .. |citation2| replace:: *F. Motzoi, J. M. Gambetta, P. Rebentrost, and F. K. Wilhelm\n           Phys. Rev. Lett. 103, 110501 – Published 8 September 2009.*\n    \"\"\"\n\n    def __init__(self,\n                 duration: int,\n                 amp: complex,\n                 sigma: float,\n                 beta: float,\n                 name: Optional[str] = None):\n        \"\"\"Initialize the drag pulse.\n\n        Args:\n            duration: Pulse length in terms of the the sampling period `dt`.\n            amp: The amplitude of the Drag envelope.\n            sigma: A measure of how wide or narrow the Gaussian peak is; described mathematically\n                   in the class docstring.\n            beta: The correction amplitude.\n            name: Display name for this pulse envelope.\n        \"\"\"\n        self._amp = complex(amp)\n        self._sigma = sigma\n        self._beta = beta\n        super().__init__(duration=duration, name=name)\n\n    @property\n    def amp(self) -> complex:\n        \"\"\"The Gaussian amplitude.\"\"\"\n        return self._amp\n\n    @property\n    def sigma(self) -> float:\n        \"\"\"The Gaussian standard deviation of the pulse width.\"\"\"\n        return self._sigma\n\n    @property\n    def beta(self) -> float:\n        \"\"\"The weighing factor for the Gaussian derivative component of the waveform.\"\"\"\n        return self._beta\n\n    def get_waveform(self) -> Waveform:\n        return drag(duration=self.duration, amp=self.amp, sigma=self.sigma,\n                    beta=self.beta, zero_ends=False)\n\n    def validate_parameters(self) -> None:\n        if abs(self.amp) > 1.:\n            raise PulseError(\"The amplitude norm must be <= 1, \"\n                             \"found: {}\".format(abs(self.amp)))\n        if self.sigma <= 0:\n            raise PulseError(\"Sigma must be greater than 0.\")\n        if isinstance(self.beta, complex):\n            raise PulseError(\"Beta must be real.\")\n        # Check if beta is too large: the amplitude norm must be <=1 for all points\n        if self.beta > self.sigma:\n            # If beta <= sigma, then the maximum amplitude is at duration / 2, which is\n            # already constrainted by self.amp <= 1\n\n            # 1. Find the first maxima associated with the beta * d/dx gaussian term\n            #    This eq is derived from solving for the roots of the norm of the drag function.\n            #    There is a second maxima mirrored around the center of the pulse with the same\n            #    norm as the first, so checking the value at the first x maxima is sufficient.\n            argmax_x = (self.duration / 2\n                        - (self.sigma / self.beta) * math.sqrt(self.beta ** 2 - self.sigma ** 2))\n            if argmax_x < 0:\n                # If the max point is out of range, either end of the pulse will do\n                argmax_x = 0\n\n            # 2. Find the value at that maximum\n            max_val = continuous.drag(np.array(argmax_x), sigma=self.sigma,\n                                      beta=self.beta, amp=self.amp, center=self.duration / 2)\n            if abs(max_val) > 1.:\n                raise PulseError(\"Beta is too large; pulse amplitude norm exceeds 1.\")\n\n    @property\n    def parameters(self) -> Dict[str, Any]:\n        return {\"duration\": self.duration, \"amp\": self.amp, \"sigma\": self.sigma,\n                \"beta\": self.beta}\n\n    def __repr__(self) -> str:\n        return \"{}(duration={}, amp={}, sigma={}, beta={}{})\" \\\n               \"\".format(self.__class__.__name__, self.duration, self.amp, self.sigma, self.beta,\n                         \", name='{}'\".format(self.name) if self.name is not None else \"\")\n\n\nclass Constant(ParametricPulse):\n    \"\"\"\n    A simple constant pulse, with an amplitude value and a duration:\n\n    .. math::\n\n        f(x) = amp    ,  0 <= x < duration\n        f(x) = 0      ,  elsewhere\n    \"\"\"\n\n    def __init__(self,\n                 duration: int,\n                 amp: complex,\n                 name: Optional[str] = None):\n        \"\"\"\n        Initialize the constant-valued pulse.\n\n        Args:\n            duration: Pulse length in terms of the the sampling period `dt`.\n            amp: The amplitude of the constant square pulse.\n            name: Display name for this pulse envelope.\n        \"\"\"\n        self._amp = complex(amp)\n        super().__init__(duration=duration, name=name)\n\n    @property\n    def amp(self) -> complex:\n        \"\"\"The constant value amplitude.\"\"\"\n        return self._amp\n\n    def get_waveform(self) -> Waveform:\n        return constant(duration=self.duration, amp=self.amp)\n\n    def validate_parameters(self) -> None:\n        if abs(self.amp) > 1.:\n            raise PulseError(\"The amplitude norm must be <= 1, \"\n                             \"found: {}\".format(abs(self.amp)))\n\n    @property\n    def parameters(self) -> Dict[str, Any]:\n        return {\"duration\": self.duration, \"amp\": self.amp}\n\n    def __repr__(self) -> str:\n        return \"{}(duration={}, amp={}{})\" \\\n               \"\".format(self.__class__.__name__, self.duration, self.amp,\n                         \", name='{}'\".format(self.name) if self.name is not None else \"\")\n\n\nclass ConstantPulse(Constant):\n    \"\"\"\n    Deprecated. A simple constant pulse, with an amplitude value and a duration:\n\n    .. math::\n\n        f(x) = amp    ,  0 <= x < duration\n        f(x) = 0      ,  elsewhere\n    \"\"\"\n\n    def __init__(self,\n                 duration: int,\n                 amp: complex,\n                 name: Optional[str] = None):\n        \"\"\"\n        Initialize the constant-valued pulse.\n\n        Args:\n            duration: Pulse length in terms of the the sampling period `dt`.\n            amp: The amplitude of the constant square pulse.\n            name: Display name for this pulse envelope.\n        \"\"\"\n        super(ConstantPulse, self).__init__(duration, amp, name)\n        warnings.warn(\"The ConstantPulse is deprecated. Use Constant instead\", DeprecationWarning)\n", "meta": {"hexsha": "d9c9e136cb13dccef6417ae3fa420c6efe87dc50", "size": 16671, "ext": "py", "lang": "Python", "max_stars_repo_path": "qiskit/pulse/library/parametric_pulses.py", "max_stars_repo_name": "romainfd/qiskit-terra", "max_stars_repo_head_hexsha": "b5285ccc5cb1d17b7c73402833f2750b93652426", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "qiskit/pulse/library/parametric_pulses.py", "max_issues_repo_name": "romainfd/qiskit-terra", "max_issues_repo_head_hexsha": "b5285ccc5cb1d17b7c73402833f2750b93652426", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qiskit/pulse/library/parametric_pulses.py", "max_forks_repo_name": "romainfd/qiskit-terra", "max_forks_repo_head_hexsha": "b5285ccc5cb1d17b7c73402833f2750b93652426", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9645232816, "max_line_length": 98, "alphanum_fraction": 0.5969048048, "include": true, "reason": "import numpy", "num_tokens": 3779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3486451353339458, "lm_q1q2_score": 0.18926664282950822}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nTHOR detects differential peaks in multiple ChIP-seq profiles associated\nwith two distinct biological conditions.\n\nCopyright (C) 2014-2016 Manuel Allhoff (allhoff@aices.rwth-aachen.de)\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n@author: Manuel Allhoff\n\"\"\"\n\nfrom __future__ import print_function\nimport string\nfrom hmmlearn.hmm import _BaseHMM\n\nimport sys\nfrom math import fabs\nfrom scipy.special import logsumexp\n\nimport numpy as np\nfrom .neg_bin import NegBin\n\nimport warnings\n\n\ndef _get_pvalue_distr(mu, alpha, tracker):\n    \"\"\"Derive NB1 parameters for p-value calculation\"\"\"\n    mu = mu[0,0]\n    alpha = alpha[0,0] / 10000.\n    tracker.write(text=str(mu), header=\"Neg. Bin. distribution for p-value estimates (mu)\")\n    tracker.write(text=str(alpha), header=\"Neg. Bin. distribution for p-value estimates (alpha)\")\n    \n    nb = NegBin(mu, alpha)\n    return {'distr_name': 'nb', 'distr': nb}\n\ndef get_init_parameters(s0, s1, s2, **info):\n    \"\"\"For given training set (s0: Background, s1: Gaining, s2: loseing) get inital mu, alpha for NB1.\"\"\"\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n        mu = np.matrix([np.mean(map(lambda x: x[i], s)) for i in range(2) for s in [s0, s1, s2]]).reshape(2, 3)\n        var = np.matrix([np.var(map(lambda x: x[i], s)) for i in range(2) for s in [s0, s1, s2]]).reshape(2, 3)\n\n    alpha = (var - mu) / np.square(mu)\n\n    # alpha[np.isnan(alpha)] = 0.001\n\n    alpha[alpha < 0] = 0.001\n\n    for el in [mu, alpha]:\n        high = min(el[0,1], el[1,2]) + 0.5 * fabs(el[0,1] - el[1,2])\n        low = min(el[1,1], el[0,2]) + 0.5 * fabs(el[1,1] - el[0,2])\n        med = np.mean([el[0,0], el[1,0]])\n        el[0,1] = high\n        el[1,2] = high\n        el[1,1] = low\n        el[0,2] = low\n        el[0,0] = med\n        el[1,0] = med\n\n    return alpha, mu\n    \nclass NegBinRepHMM(_BaseHMM):\n    def __init__(self, alpha, mu, dim_cond_1, dim_cond_2, init_state_seq=None, n_components=3, covariance_type='diag',\n                  startprob_prior=1.0, transmat_prior=1.0, func=None,\n                 algorithm=\"viterbi\", means_prior=None, means_weight=0,\n                 covars_prior=1e-2, covars_weight=1,\n                 random_state=None, n_iter=30, thresh=1e-2,\n                 params=string.ascii_letters,\n                 init_params=string.ascii_letters):\n    \n        _BaseHMM.__init__(self, n_components,\n                          startprob_prior=startprob_prior,\n                          transmat_prior=transmat_prior, algorithm=algorithm,\n                          random_state=random_state, n_iter=n_iter,\n                          tol=thresh, params=params,\n                          init_params=init_params)\n        \n        self.dim = [dim_cond_1, dim_cond_2] #dimension of one emission\n        self.n_features = 2 #sum(self.dim) #emission dimension\n        self.alpha = alpha\n        self.mu = mu\n        self._update_distr(self.mu, self.alpha)\n        self.func = func\n        self.em_prob = 0\n    \n    \n    def fit(self, obs, three_para):\n        \"\"\"Estimate model parameters.\n\n        An initialization step is performed before entering the EM\n        algorithm. If you want to avoid this step, pass proper\n        ``init_params`` keyword argument to estimator's constructor.\n\n        Parameters\n        ----------\n        obs : list\n            List of array-like observation sequences, each of which\n            has shape (n_i, n_features), where n_i is the length of\n            the i_th observation.\n\n        Notes\n        -----\n        In general, `logprob` should be non-decreasing unless\n        aggressive pruning is used.  Decreasing `logprob` is generally\n        a sign of overfitting (e.g. a covariance parameter getting too\n        small).  You can fix this by getting more training data,\n        or strengthening the appropriate subclass-specific regularization\n        parameter.\n        \"\"\"\n\n        # what does this mean??\n        self._init(obs, self.init_params)\n\n        logprob = []\n        for i in range(self.n_iter):\n            # Expectation step\n            stats = self._initialize_sufficient_statistics()\n            curr_logprob = 0\n            for seq in obs:\n                framelogprob = self._compute_log_likelihood(seq)\n                lpr, fwdlattice = self._do_forward_pass(framelogprob)\n                bwdlattice = self._do_backward_pass(framelogprob)\n                gamma = fwdlattice + bwdlattice\n                posteriors = np.exp(gamma.T - logsumexp(gamma, axis=1)).T\n                curr_logprob += lpr\n                self._accumulate_sufficient_statistics(\n                    stats, seq, framelogprob, posteriors, fwdlattice,\n                    bwdlattice)\n            logprob.append(curr_logprob)\n\n            # Check for convergence.\n            if i > 0 and logprob[-1] - logprob[-2] < self.tol:\n                break\n\n            # Maximization step\n            self._do_mstep(stats, three_para)\n        #print(\"Logprob of all M-steps: %s\" %logprob, file=sys.stderr)\n        self.em_prob = logprob[-1]\n        return self\n    \n    def _update_distr(self, mu, alpha):\n        \"\"\"Update distributions assigned to each state with new mu and alpha\"\"\"\n        raw1 = [NegBin(mu[0, 0], alpha[0, 0]), NegBin(mu[0, 1], alpha[0, 1]), NegBin(mu[0, 2], alpha[0, 2])]\n        raw2 = [NegBin(mu[1, 0], alpha[1, 0]), NegBin(mu[1, 1], alpha[1, 1]), NegBin(mu[1, 2], alpha[1, 2])]\n        \n        self.neg_distr = np.matrix([raw1, raw2]) #matrix of all Neg. Bin. Distributions, columns=HMM's state (3), row=#samples (2)\n        \n    def get_alpha(self, m):\n        \"\"\"Return alpha for a given mu based on empirical variance\"\"\"\n        var = self.func(m)\n        try:\n            return max((var - m) / m**2, 1e-300)\n        except Warning:\n            if m**2 > 1e-300:\n                return max((var - m) / m**2, 1e-300)\n            else:\n                return 1e-300\n    \n    def _compute_log_likelihood(self, X):\n        matrix = []\n        lookup = {}\n        for x in X: #over all observations\n            row = []\n            for i in range(self.n_components): #over number of HMM's state\n                r_sum = 0\n                for j in range(self.n_features): #over dim\n                    it = range(self.dim[0]) if j == 0 else range(self.dim[0], self.dim[0] + self.dim[1]) #grab proper ob\n                    for k in it:\n                        index = (int(x[k]), i, j)\n                        if lookup.has_key( index ):\n                            r_sum += lookup[index]\n                        else:\n                            y = float(self.neg_distr[j,i].logpdf(x[k]))\n                            lookup[index] = y\n                            r_sum += y\n                row.append(r_sum)\n        \n            matrix.append(row)\n        return np.asarray(matrix)\n    \n    \n    def _generate_sample_from_state(self, state, random_state=None):\n        output = []\n        for i, d in enumerate(self.dim):\n            for _ in range(d):\n                output.append( self.neg_distr[i,state].rvs() )\n        \n        return np.array(output)\n    \n    def _initialize_sufficient_statistics(self):\n        stats = super(NegBinRepHMM, self)._initialize_sufficient_statistics()\n        stats['post'] = np.zeros([self.n_features, self.n_components])\n        stats['post_emission'] = np.zeros([self.n_features, self.n_components]) #dim X states\n        \n        return stats\n    \n    def _help_accumulate_sufficient_statistics(self, obs, stats, posteriors):\n        for t, symbol in enumerate(obs):\n            stats['post'][0] += posteriors[t]\n            stats['post'][1] += posteriors[t]\n            \n            pot_it = [range(self.dim[0]), range(self.dim[0], self.dim[0] + self.dim[1])] #consider both classes\n            for j, it in enumerate(pot_it):\n                for i in it:\n                    stats['post_emission'][j] += posteriors[t] * symbol[i]\n        \n        stats['post'][0] = stats['post'][0] * self.dim[0]\n        stats['post'][1] = stats['post'][1] * self.dim[1]\n        \n        stats['posterior'] = np.copy(posteriors)\n    \n    def _valid_posteriors(self, posteriors, obs):\n    \n        warnings.filterwarnings('error')\n        \n        for i in range(len(obs)):\n            state_1 = False\n            c1, c2 = np.mean(obs[i][:self.dim[0]]), np.mean(obs[i][self.dim[0]:]) #counts of samples\n    \n            if posteriors[i][0] > 0.5: \n                state_1 = True\n                \n            if c1 > c2: #state 1\n                if fabs(posteriors[i][2] - 1) < 1e-200:\n                    posteriors[i] = np.array([1, 0, 0])\n                else:\n                    if not state_1 and posteriors[i][2] > posteriors[i][1]:\n                        try:                        \n                            post_s2 = 0\n                            post_s0 = posteriors[i][0] / (posteriors[i][0] + posteriors[i][1])\n                            post_s1 = posteriors[i][1] / (posteriors[i][0] + posteriors[i][1])\n                            posteriors[i] = np.array([post_s0, post_s1, post_s2])\n                        except RuntimeWarning:\n                            print(posteriors[i], c1, c2, file=sys.stderr)\n            \n            if c2 > c1: #state 2\n                if fabs(posteriors[i][1] - 1) < 1e-200:\n                    posteriors[i] = np.array([1, 0, 0])\n                else:\n                    if not state_1 and posteriors[i][1] > posteriors[i][2]:\n                        try:\n                            post_s1 = 0\n                            post_s0 = posteriors[i][0] / (posteriors[i][0] + posteriors[i][2])\n                            post_s2 = posteriors[i][2] / (posteriors[i][0] + posteriors[i][2])\n                            posteriors[i] = np.array([post_s0, post_s1, post_s2])\n                        except RuntimeWarning:\n                            print(posteriors[i], c1, c2, file=sys.stderr)\n\n        warnings.resetwarnings()\n\n        return posteriors\n\n    def _accumulate_sufficient_statistics(self, stats, obs, framelogprob,\n                                      posteriors, fwdlattice, bwdlattice\n                                      ):\n        super(NegBinRepHMM, self)._accumulate_sufficient_statistics(\n            stats, obs, framelogprob, posteriors, fwdlattice, bwdlattice,\n            )\n        posteriors = self._valid_posteriors(posteriors, obs)\n        self._help_accumulate_sufficient_statistics(obs, stats, posteriors)        \n    \n    def _do_mstep(self, stats, three_para):\n        super(NegBinRepHMM, self)._do_mstep(stats)\n        \n        if three_para:\n            self.mu[0,1] = (stats['post_emission'][0][1] + stats['post_emission'][1][2]) / (stats['post'][0][1] + stats['post'][1][2])\n            self.mu[1,1] = (stats['post_emission'][1][1] + stats['post_emission'][0][2]) / (stats['post'][1][1] + stats['post'][0][2])\n            self.mu[0,0] = (stats['post_emission'][0][0] + stats['post_emission'][1][0]) / (stats['post'][0][0] + stats['post'][1][0])\n            \n            self.mu[1,2] = self.mu[0,1]\n            self.mu[0,2] = self.mu[1,1]\n            self.mu[1,0] = self.mu[0,0]\n        else:\n            self.mu[0,1] = (stats['post_emission'][0][1] + stats['post_emission'][1][2]) / (stats['post'][0][1] + stats['post'][1][2])\n            self.mu[1,1] = (stats['post_emission'][1][1] + stats['post_emission'][0][2] + stats['post_emission'][0][0] + stats['post_emission'][0][1]) / (stats['post'][1][1] + stats['post'][0][2] + stats['post'][0][0] + stats['post'][0][1])\n            \n            self.mu[0,0] = self.mu[1,1]\n            self.mu[1,2] = self.mu[0,1]\n            self.mu[0,2] = self.mu[1,1]\n            self.mu[1,0] = self.mu[0,0]\n        \n        self.alpha = np.matrix([map(lambda m: self.get_alpha(m), np.asarray(self.mu[i])[0]) for i in range(self.n_features)])\n        self._update_distr(self.mu, self.alpha)\n       \n    def merge_distr(self):\n        f = self.count_s2 / float(self.count_s1 + self.count_s2) #TODO exp_data.\n        \n        for el in [self.mu, self.alpha]:\n            high = min(el[0,1], el[1,2]) + f * fabs(el[0,1] - el[1,2])\n            low = min(el[1,1], el[0,2]) + f * fabs(el[1,1] - el[0,2])\n            med = np.mean([el[0,0], el[1,0]])\n            el[0,1] = high\n            el[1,2] = high\n            el[1,1] = low\n            el[0,2] = low\n            el[0,0] = low #min(med, low)\n            el[1,0] = low #min(med, low)\n        \n        self._update_distr(self.mu, self.alpha)\n\n    \nif __name__ == '__main__':\n    alpha = np.matrix([[0.2, 0.2, 0.2], [0.2, 0.2, 0.2]])\n    mu = np.matrix([[15.,100.,10.], [10.,10.,100.]])\n    f = lambda x: 0.4*x**2 + 1\n    \n    dim_cond_1 = 2\n    dim_cond_2 = 3\n    mean = [0, 0]\n    cov = [[1, 0], [0, 100]]\n    X= np.random.multivariate_normal(mean, cov, size=5)\n\n    m2 = NegBinRepHMM(alpha = alpha, mu = np.matrix([[50.,130.,110.], [60.,100.,120.]]), dim_cond_1 = dim_cond_1, dim_cond_2 = dim_cond_2, func=f)\n    m2.fit([X], three_para=False)\n    \n    posteriors = m2.predict_proba(X)\n    e = m2.predict(X)\n    for i, el in enumerate(X):\n        print(el, e[i], sep='\\t', file=sys.stderr)\n    #print(np.max(posteriors, axis=1))\n    print(m2.mu)\n", "meta": {"hexsha": "c515c6d554bd01281d15c6a4ced444c5b830d20d", "size": 13809, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/rgt/THOR/neg_bin_rep_hmm.py", "max_stars_repo_name": "mguo123/pan_omics", "max_stars_repo_head_hexsha": "e1cacd543635b398fb08c0b31d08fa6b7c389658", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rgt/THOR/neg_bin_rep_hmm.py", "max_issues_repo_name": "mguo123/pan_omics", "max_issues_repo_head_hexsha": "e1cacd543635b398fb08c0b31d08fa6b7c389658", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rgt/THOR/neg_bin_rep_hmm.py", "max_forks_repo_name": "mguo123/pan_omics", "max_forks_repo_head_hexsha": "e1cacd543635b398fb08c0b31d08fa6b7c389658", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2208955224, "max_line_length": 240, "alphanum_fraction": 0.5448620465, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290152, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.18922692980761938}}
{"text": "\"\"\"\nMotif discovery, incorporating position sensitivity and motif degeneracy.\nThe basic model is similar to the original BIRT:  for a given (degenerate) motif,\nfind the window of positions that maximize the significance by the binomial test.\n\nHere, the degeneracy is modeled as one canonical k-mer, and some or all of the 3k+9\n\"neighboring\" k-mers that differ from it by just one base.\nThe intuition is that each substitution carries an increasing cost;  being one mutation\nfrom consensus isn't as bad as being 3 or 4 mutations away from the consensus sequence.\n\nThis machinery is derived from my original \"Vermit\" implementation of the cERMIT algorithm,\nwhich focused on log-odds \"evidence\" for each gene, with the in-group/out-group version\nas a special case.\n\nHowever, in this code I'm using binomial distribution p-values, which come only from in-group/\nout-group count data (evidence = 0 or 1).  So I kept the machinery, but the nominclature is\nnot what I would have done if I started with this approach!\n\"\"\"\nimport copy\nimport numpy as np\nfrom scipy import weave\n\nfrom pygr import util, dnaseq, rmath\n\ndef kmer_matches(kmer, suf, seq_offsets, midgap):\n    \"\"\"\n    locs    0-based start position of matches to `kmer` within the concatenated sequences.\n    matches 0-based index of corresponding sequence for each entry in `locs`.\n    midgap  Number of bases between the first and second half of `kmer`\n    \"\"\"\n    # Caching speeds the single-processor algorithm by ~7%,\n    # but eliminating it frees up a LOT of memory to allow multithreading.\n    if midgap == 0:\n        locs = suf.find_positions(kmer) # offsets from beginning of file\n        matches = np.searchsorted(seq_offsets, locs) # sequence index for each match\n    else:\n        half = len(kmer) // 2\n        locs_left = suf.find_positions(kmer[:half])\n        locs_right = suf.find_positions(kmer[half:]) - (half+midgap)\n        locs = np.intersect1d(locs_left, locs_right, assume_unique=True)\n        matches = np.searchsorted(seq_offsets, locs)\n        matches_right = np.searchsorted(seq_offsets, locs + (half+midgap))\n        same_seq = (matches == matches_right) # only valid when two halves of the match are in the same sequence!\n        locs = locs[same_seq]\n        matches = matches[same_seq]\n    return (locs, matches)\n\ndef kmers_matches(kmers, suf, seq_offsets, midgap):\n    # Gather together all matches/locations for all kmers.\n    # Sort them, first by sequence ID (implicitly), then by position within the sequence.\n    matches = [] # [np.array], will be joined all at once\n    locs = [] # [np.array], will be joined all at once\n    for kmer in kmers:\n        ls, ms = kmer_matches(kmer, suf, seq_offsets, midgap)\n        matches.append(ms)\n        locs.append(ls)\n    matches = np.concatenate(matches)\n    locs = np.concatenate(locs)\n    # There cannot be any duplicates in locs (assuming all kmers are unique, which they should be)\n    # because there is exactly one distinct kmer at each location in the original sequences.\n    o = np.argsort(locs)\n    return locs[o], matches[o]\n\ndef filelocs_to_seqlocs(locs, matches, seq_lens, seq_offsets, align_5p):\n    \"\"\"\n    Converts file-based kmer locations to sequence-based kmer locations.\n    `locs` is altered *IN PLACE*, so there is no return value.\n    \"\"\"\n    max_seq_len = seq_lens.max() - 1 # b/c they're really seq. len. + 1 for the newline\n    # seq_offsets[matches] - locs == distance from right edge, <= 0\n    locs -= seq_offsets[matches]\n    if align_5p:\n        # sequences are left-justified and 0 is the leftmost base:\n        locs += seq_lens[matches]\n        locs -= 1 # b/c they're really seq. len. + 1 for the newline\n    else:\n        # sequences are right-justified and 0 is the leftmost base:\n        #locs = max_seq_len - (seq_offsets[matches] - locs)\n        locs += max_seq_len\n    #if not (locs.max() < max_seq_len):\n    #    import pdb\n    #    pdb.set_trace()\n    assert locs.max() < max_seq_len\n    assert locs.min() >= 0\n    return max_seq_len\n\nclass SeqBins(object):\n    def __init__(self, fasta, evidence, ev_wts, n_bins=1):\n        self.n_bins = n_bins\n        if self.n_bins <= 1:\n            self.bin_ids = np.array([0]*len(evidence))\n        else:\n            self.bin_ids = self._cluster(fasta, n_bins)\n        # The genes are divided into n bins. Let Bi and Ti be the BG and target set genes, respectively,\n        # in the ith bin, and denote by bi the subset of genes from Bi whose sequence contains a hit. The\n        # goal of this score is to account for cases where the fraction of targets is uneven across bins.\n        # Suppose that targets within each bin are selected uniformly. Then, in bin i the probability that\n        # a selected gene will contain a hit (i.e., belong to bi) is |bi|/|Bi|. Since the fraction of\n        # targets in bin i is |Ti|/|T|, it follows that the probability that a selected gene will contain\n        # a hit is p_m = sum_over_i[ (Ti/T) * (bi/Bi) ]\n        Bi = np.array([ev_wts[self.bin_ids == cid].sum() for cid in xrange(self.n_bins)]) # total genes in each bin\n        Ti = np.array([evidence[self.bin_ids == cid].sum() for cid in xrange(self.n_bins)]) # in-group genes in each bin\n        T = evidence.sum() # total in-group genes across all bins\n        Bi[Bi == 0] == 1 # to avoid divide-by-zero errors when Ti == Bi == 0 (no genes in bin)\n        self.multiplier = (Ti / T / Bi)[None,None,:] # to be multiplied by bi, which is called wt_table in improve_window\n    def _get_features(self, seq):\n        features = []\n        features.append(len(seq))\n        bases = util.make_bag(seq)\n        L = float(max(1, len(seq)))\n        features.extend([bases[b]/L for b in 'ACGT'])\n        return features\n    def _cluster(self, fasta, n_bins):\n        print \"Clustering sequences by composition and length...\"\n        # Compute numeric features for each sequence.\n        features = [self._get_features(s) for i,n,s in fasta]\n        # Normalize distances by dividing by std. deviation.\n        features = np.array(features, np.float)\n        stddev = np.apply_along_axis(np.std, 0, features)\n        print \"S.d. of features:\", stddev\n        features /= stddev\n        # For now, we just run the clustering once, even though it may be sub-optimal\n        clusters, cost = util.kmeans(features, n_bins, maxiter=10)\n        return np.asarray(clusters)\n\ndef improve_window(kmers, bins, evidence, ev_wts, G, mu, suf, seq_lens, seq_offsets, options, mask=None):\n    \"\"\"\n    Evaluate the score for a set of k-mers, restricted to various possible sequence windows.\n    Choose the window giving the highest Z score for these k-mers.\n\n    kmers       Iterable of 1+ k-mers to find the optimal cERMIT-score window for\n    bins        a SeqBins object defining how sequences are grouped into bins/clusters\n    evidence    NumPy array of log-odds or log-enrichment scores for each gene in the pool (floats)\n    ev_wts      NumPy array of weights on (0,1] for each piece of evidence, 1/(# gene models)\n    G           total \"number\" of genes, ev_wts.sum() [to avoid recomputing every time]\n    mu          average evidence, evidence.sum()/G [to avoid recomputing every time]\n    suf         the suffix array searcher object\n    seq_lens    length of each sequence in characters, including the newline separator\n    seq_offsets position in the concatenated sequence file at which each sequence ends\n    options     command line options object\n    mask        Numpy array with length >= max location index; counts the number of times each bp is \"used\" in a motif.\n                This is optional, for masking out kmers used in one motif so another motif can't claim them.\n                If present, it will be updated to mask out the evidence used for these kmers.\n    \n    Raw evidence numbers should have been pre-multiplied by the provided weights (for efficiency).\n    Scoring follows M.A.Newton et al, Annals of Applied Statistics 2007, 1:85-106\n    rather than Georgiev et al. because the latter appears to have some typos in the formulae.\n    Higher scores are better.\n    \"\"\"\n    # Hard to find a good word for the SeqBins, where sequences have been grouped/clustered/binned\n    # by sequence composition (percent A/C/G/T).  In this function \"bin\" is already used for\n    # the sequence position windows (typically of ~25bp length).\n    # Elsewhere in POWRS, there is some post-process \"clustering\" that already uses that name.\n    # But within this function, I'll call the SeqBins \"clusters\" to distinguish them from\n    # the positional bins.\n    cluster_ids = bins.bin_ids # for access by Weave\n    n_clust = bins.n_bins\n    # Gather together all matches/locations for all kmers.\n    # Sort them, first by sequence ID (implicitly), then by position within the sequence.\n    # The algorithm below expects that locations occur in sorted order.\n    #T = time.time()\n    locs, matches = kmers_matches(kmers, suf, seq_offsets, options.midgap)\n    # \"Masking\" to reduce the score of alternative motifs that closely match a previously evaluated motif.\n    if mask is not None:\n        motif_len = max(len(kmer) for kmer in kmers) # should all be the same length, but just in case...\n        assert len(mask) >= locs[-1] + motif_len # locs are sorted, so -1 is max element\n        loc_mask = np.zeros(locs.shape, dtype=np.int) # each pos. varies from 0 (totally free) to motif_len (totally masked)\n        mask_limit = options.mask_limit\n        weave.inline(r\"\"\"\n            int n = Nlocs[0]; // see Numpy book; == locs.shape in Python\n            int klen = motif_len;\n            int maskmax = mask_limit;\n            int ii, jj, kk, loc;\n            for(ii = 0; ii < n; ii++) { // for each location...\n                loc = locs[ii];\n                for(jj = 0; jj < klen; jj++) {\n                    if(mask[loc+jj] >= maskmax) loc_mask[ii]++; // if it's already maxed out, we can't use it (maybe)\n                    else mask[loc+jj]++; // otherwise, note that we've used one count worth\n                }\n            }\n        \"\"\", ['locs','mask','motif_len','loc_mask','mask_limit'])\n        loc_mask = (loc_mask <= motif_len//2) # mask out locations that are more than half used by someone else\n        locs = locs[loc_mask]\n        matches = matches[loc_mask]\n    # locs/matches could be empty, possibly due to masking\n    if len(locs) == 0: return 0, 0, -util.Inf, 0\n    # This sort of complicated indexing creates copies (unlike simple slices):\n    # We need a copy (of locs, at least) because we're going to modify it in place, and it's cached. [not true anymore]\n    assert locs.base == matches.base == None\n    # convert file-based offsets into sequence-based offsets\n    max_seq_len = filelocs_to_seqlocs(locs, matches, seq_lens, seq_offsets, options.align_5p) # locs altered in place!\n    #print \"Finding %i matches: %f\" % (len(locs), time.time()-T); T = time.time()\n    # Tally kmer locations in fixed-width bins, then build a table\n    # of start,end windows showing the total (weighted) evidence\n    # of genes with 1+ copies of the kmer located within that window.\n    W = options.window_width\n    max_W = max(1, max_seq_len // W) # in case W > max_seq_len, so we don't get a 0x0 table\n    ev_table = np.zeros((max_W,max_W), dtype=np.float) # sum evidence for selected genes\n    wt_table = np.zeros((max_W,max_W,n_clust), dtype=np.float) # \"number\" of selected genes, a.k.a. \"m\"\n    locs //= W # convert base-pair locations into binned locations\n    # now we'll subtract out evidence for genes that don't have a kmer in that window:\n        ## This loop is by far the slowest part of this algorithm, so...\n        #last_loc, last_seqid = None, None\n        #for locbin, seqid in zip(locs, matches):\n        #    if seqid != last_seqid: # first kmer of a new sequence\n        #        ev_table += evidence[seqid]\n        #        wt_table += ev_wts[seqid]\n        #        if last_seqid is not None: # last kmer of the old sequence\n        #            ev_table[last_loc:max_W,last_loc:max_W] -= evidence[last_seqid]\n        #            wt_table[last_loc:max_W,last_loc:max_W] -= ev_wts[last_seqid]\n        #        ev_table[0:locbin,0:locbin] -= evidence[seqid]\n        #        wt_table[0:locbin,0:locbin] -= ev_wts[seqid]\n        #        last_seqid = seqid\n        #    else: # non-first kmer\n        #        ev_table[last_loc:locbin,last_loc:locbin] -= evidence[seqid]\n        #        wt_table[last_loc:locbin,last_loc:locbin] -= ev_wts[seqid]\n        #    # We add one so that only bins *between* kmers will be penalized,\n        #    # not bins *containing* kmers. In NumPy if start > end, it's just an empty array.\n        #    last_loc = locbin + 1\n        #if last_seqid is not None: # last kmer of the last sequence\n        #    ev_table[last_loc:max_W,last_loc:max_W] -= evidence[last_seqid]\n        #    wt_table[last_loc:max_W,last_loc:max_W] -= ev_wts[last_seqid]\n    ## After re-writing in C++, the time to actually find the k-mers dominates!\n    weave.inline(r\"\"\"\n        int maxw = max_W; // need this to avoid int/float ambiguity error\n        int nclust = n_clust;\n        int last_loc = -1, last_seqid = -1, last_clust = -1;\n        int n = Nlocs[0]; // see Numpy book; == locs.shape in Python\n        int locbin, seqid, clust;\n        float evid, evwt, last_evid, last_evwt;\n        int ii, jj, kk;\n        for(ii = 0; ii < n; ii++) {\n            locbin = locs[ii];\n            seqid = matches[ii];\n            clust = cluster_ids[seqid];\n            evid = evidence[seqid];\n            evwt = ev_wts[seqid];\n            if(seqid != last_seqid) {\n                // Only need to do the diagonal and above...\n                // Finish up last sequence:\n                if(last_seqid != -1) {\n                    for(jj = last_loc; jj < maxw; jj++) { for(kk = jj; kk < maxw; kk++) {\n                        ev_table[jj*maxw + kk] -= last_evid;\n                        wt_table[(jj*maxw + kk)*nclust + last_clust] -= last_evwt;\n                    }}\n                }\n                // Now start this new sequence:\n                // Add in evidence everywhere (happens ONCE per SEQUENCE)\n                for(jj = 0; jj < maxw; jj++) { for(kk = jj; kk < maxw; kk++) {\n                    ev_table[jj*maxw + kk] += evid;\n                    wt_table[(jj*maxw + kk)*nclust + clust] += evwt;\n                }}\n                // Remove evidence between left edge and this occurrence\n                for(jj = 0; jj < locbin; jj++) { for(kk = jj; kk < locbin; kk++) {\n                    ev_table[jj*maxw + kk] -= evid;\n                    wt_table[(jj*maxw + kk)*nclust + clust] -= evwt;\n                }}\n                last_seqid = seqid;\n            } else {\n                // Continuation of previous sequence;  evidence has already been added.\n                // Just remove evidence between last occurrence and this occurrence.\n                for(jj = last_loc; jj < locbin; jj++) { for(kk = jj; kk < locbin; kk++) {\n                    ev_table[jj*maxw + kk] -= evid;\n                    wt_table[(jj*maxw + kk)*nclust + clust] -= evwt;\n                }}\n            }\n            last_loc = locbin + 1;\n            last_clust = clust;\n            last_evid = evid;\n            last_evwt = evwt;\n        }\n        if(last_seqid != -1) {\n            clust = cluster_ids[last_seqid];\n            evid = evidence[last_seqid];\n            evwt = ev_wts[last_seqid];\n            for(jj = last_loc; jj < maxw; jj++) { for(kk = jj; kk < maxw; kk++) {\n                ev_table[jj*maxw + kk] -= evid;\n                wt_table[(jj*maxw + kk)*nclust + clust] -= evwt;\n            }}\n        }\n    \"\"\", ['locs', 'matches', 'cluster_ids', 'evidence', 'ev_wts', 'max_W', 'n_clust', 'ev_table', 'wt_table'])\n    #print \"For loop over %i matches: %f\" % (len(locs), time.time()-T); T = time.time()\n    # Instead of the cERMIT Z-score, we can compute the binomial p-value (using in-group/out-group evidence only):\n    # Trying to use non-integer valued floats in pbinom() produces NaNs\n    score_table = np.around(ev_table)\n    prob_table = (wt_table * bins.multiplier).sum(axis=2) # probability weighted by bin membership\n    wt_table = wt_table.sum(axis=2) # condense clusters, for normal use by later code\n    wt_table = np.around(wt_table)\n    # This code used to compute pbinom(Ak, Nk, A/N)\n    # In Amadeus and historically (tally_all), we use pbinom(Ak, A, Nk/N) instead.\n    # It would be easy to use either one here, really, without changing much (see commented-out lines below).\n    # P-values are quite similar, although pbinom(Ak, A, Nk/N) seems to be a little stronger in each case.\n    # I'm not sure which one is better justified statistically, but top hits are nearly identical empirically.\n    # We use the Amadeus version now so that we can use their binned enrichment correction.\n    weave.inline(r\"\"\"\n        int maxw = max_W; // need this to avoid int/float ambiguity error\n        int ii, jj, kk;\n        double prob = mu;\n        double N = G;\n        double A = (int)(prob * N);\n        for(jj = 0; jj < maxw; jj++) { for(kk = jj; kk < maxw; kk++) {\n            ii = jj*maxw + kk; // linear index into score_table / wt_table\n            // pbinom(Ak, Nk, A/N):\n            //score_table[ii] = -0.4342945 * pbinom(score_table[ii]-1, wt_table[ii], prob, 0, 1); // -log_10(P): bigger is better\n            // pbinom(Ak, A, Nk/N):\n            score_table[ii] = -0.4342945 * pbinom(score_table[ii]-1, A, prob_table[ii], 0, 1); // -log_10(P): bigger is better\n        }}\n    \"\"\", ['mu', 'max_W', 'score_table', 'prob_table', 'G'],\n    **rmath.weave_inline_kwargs)\n    # Disqualify bins with too few / too many hits:\n    min_genes = options.min_genes\n    max_genes = options.max_genes_frac * G\n    score_table[wt_table < min_genes] = -util.Inf\n    score_table[wt_table > max_genes] = -util.Inf\n    # Almost there. Find the highest scoring, longest, rightmost window in which start <= end.\n    # (Start and end are both inclusive when we read them out from the evidence table).\n    olderr = np.seterr(all='ignore') # I think triu() is implemented with a multiplication...\n    score_table = np.triu(score_table, k=0) # zero out everything below the diagonal (ensures start <= end) (except NaNs!)\n    np.seterr(**olderr)\n    max_Z = np.nanmax(score_table)\n    # This was caused originally by non-integer weightings on genes -- leaving it here just in case.\n    if np.isnan(max_Z):\n        print \"Failed with %i locs for %i kmers with -- %s\" % (len(locs), len(kmers), kmers)\n        return 0, 0, -util.Inf, 0\n    peaks = [(end-start, end, start) for start, end in zip(*np.nonzero(score_table == max_Z))]\n    peaks.sort(reverse=True)\n    first_bin, last_bin = peaks[0][2], peaks[0][1]\n    #score_table[~np.isfinite(score_table)] = 0 # to make plotting nicer\n    #print \"Post processing: %f\" % (time.time()-T); T = time.time()\n    # Return [inclusive, exclusive) base pair indices starting from 0 == left edge\n    return first_bin*W, (last_bin+1)*W, max_Z, ev_table[first_bin,last_bin]\n\nclass Motif(object):\n    def __init__(self, kmer, both_strands, data, parent=None):\n        \"\"\"\n        `data` is a dictionary containing the following keys:\n            evidence    NumPy array of 1's and 0's marking in-group and out-group, respectively (floats)\n            ev_wts      NumPy array of weights on (0,1] for each piece of evidence, 1/(# gene models)\n            G           total \"number\" of genes, ev_wts.sum() [to avoid recomputing every time]\n            mu          average evidence, evidence.sum()/G [to avoid recomputing every time]\n            suf         the suffix array searcher object\n            seq_lens    length of each sequence in characters, including the newline separator\n            seq_offsets position in the concatenated sequence file at which each sequence ends\n            options     command line options object\n        \"\"\"\n        if parent:\n            self.center = parent.center # the central kmer\n            self.friends = parent.friends | set([kmer]) # other included neighboring kmers\n            self.other_nbrs = parent.other_nbrs - set([kmer]) # neighboring kmers not yet included\n        else:\n            self.center = kmer\n            self.friends = set()\n            self.other_nbrs = generate_neighbors(kmer)\n        self.both_strands = both_strands\n        # Don't want to save whole data object or pickled Motifs will be huge...\n        self.options_length = data['options'].length\n        self._pattern = None\n        # Scoring\n        self.all_kmers = set([self.center]) | self.friends\n        if self.both_strands: self.all_kmers |= set(dnaseq.reverse_complement(m) for m in self.all_kmers)\n        self.start, self.end, self.score, self.evidence = improve_window(kmers=self.all_kmers, **data)\n        # Using center_score means that the preferred strand version will sort to the top at the end!\n        if parent: self.center_score = parent.center_score\n        else: self.center_score = self.score\n        # When sorting, prefer both-strands version when scores are equal (e.g. palindromic k-mers)\n        self.sortkey = (self.score, self.both_strands, self.center_score, self.end, self.start, self.pattern)\n    @property\n    def start_user(self): return self.start - self.options_length\n    @property\n    def end_user(self): return self.end - self.options_length\n    def __hash__(self): # Motifs are uniquely identified by their string pattern, but may get different scores due to re-scoring\n        return hash(self.sortkey)\n    def __cmp__(self, other):\n        return cmp(self.sortkey, other.sortkey)\n    def __str__(self):\n        return self.as_str()\n    def as_str(self, shift=0, max_shift=0):\n        s1 = \" \"*shift\n        s2 = \" \"*(max_shift - shift)\n        if self.both_strands: rc_seed = dnaseq.reverse_complement(self.center)\n        else: rc_seed = \"-\" * len(self.center)\n        return \"%8.2f    [%6.1f]    %s%s%s / %s%s%s    %6i    %6i    %50s\" % (\n            self.score, self.evidence,\n            s1, self.center, s2, s2, rc_seed, s1, self.start_user, self.end_user, self.pattern)\n    @property\n    def revcomp(self):\n        \"\"\"Returns the reverse complement of this motif (or None if not on both strands).\"\"\"\n        if not self.both_strands: return None\n        elif self.center == dnaseq.reverse_complement(self.center): return self # palindrome\n        elif not hasattr(self, \"_revcomp\"):\n            rc = self._revcomp = copy.copy(self)\n            rc.center = dnaseq.reverse_complement(self.center)\n            rc.friends = set(dnaseq.reverse_complement(f) for f in self.friends)\n            rc.other_nbrs = set(dnaseq.reverse_complement(o) for o in self.other_nbrs)\n            rc._pattern = None\n            rc.sortkey = (rc.score, rc.both_strands, rc.center_score, rc.end, rc.start, rc.pattern)\n        return self._revcomp\n    @property\n    def pattern(self):\n        if self._pattern is None:\n            self._pattern = \"\"\n            for pos, base in enumerate(self.center):\n                alts = set(f[pos] for f in self.friends)\n                alts.discard(base)\n                if not alts:\n                    self._pattern += base\n                else:\n                    self._pattern += \"[\" + base + \"\".join(sorted(a.lower() for a in alts)) + \"]\"\n        return self._pattern\n\ndef generate_neighbors(kmer):\n    nbrs = set()\n    for pos, base in enumerate(kmer):\n        for alt in \"ACGT\":\n            if alt != base:\n                assert base != \"N\"\n                nbrs.add(kmer[:pos] + alt + kmer[pos+1:])\n    return nbrs\n\nclass Cluster(object):\n    \"\"\"A group of similar Motif objects.\"\"\"\n    def __init__(self, motif, data):\n        self.motifs = [motif]\n        self.lost_motifs = [] # used only in reverse complement operations...\n        self.offsets = [0]\n        self.all_kmers = motif.all_kmers\n        self.start = motif.start\n        self.end = motif.end\n        self.score = motif.score\n        self.evidence = motif.evidence\n        # Need to keep `data` for merge scoring and revcomp scoring,\n        # but it could make pickles holding Clusters quite large...\n        self.data = data\n    @property\n    def start_user(self): return self.start - self.data['options'].length\n    @property\n    def end_user(self): return self.end - self.data['options'].length\n    def try_merge(self, other):\n        \"\"\"Returns either a new Cluster or None.\"\"\"\n        if not overlaps(self, other): return None\n        kmers_linked = False\n        # First try exact alignment\n        for m1, o1 in zip(self.motifs, self.offsets):\n            if kmers_linked: break\n            for m2, o2 in zip(other.motifs, other.offsets):\n                # `or` is too permissive; `and` is better\n                if m1.center in m2.friends and m2.center in m1.friends:\n                    kmers_linked = True\n                    offset = (o1 - o2)\n                    break\n        # Second try shifted left and shifted right\n        # Most conservative version:  seeds overlap by N-1 bases\n        # Overlapping seeds with variants turns out to be too permissive.\n        for m1, o1 in zip(self.motifs, self.offsets):\n            if kmers_linked: break\n            for m2, o2 in zip(other.motifs, other.offsets):\n                if m1.center[1:] == m2.center[:-1]:\n                    kmers_linked = True\n                    offset = (o1 - o2) + 1\n                    break\n                elif m2.center[1:] == m1.center[:-1]:\n                    kmers_linked = True\n                    offset = (o1 - o2) - 1\n                    break\n        if not kmers_linked: return None\n        new = copy.copy(self)\n        new.motifs = self.motifs + other.motifs\n        new.offsets = self.offsets + [o+offset for o in other.offsets]\n        offset = min(new.offsets)\n        new.offsets = [o-offset for o in new.offsets] # set min offset to 0\n        new.all_kmers = self.all_kmers | other.all_kmers\n        new.start, new.end, new.score, new.evidence = improve_window(kmers=new.all_kmers, **new.data)\n        if new.score > max(self.score, other.score) and overlaps(self, new) and overlaps(other, new):\n            return new\n        else: return None\n    @property\n    def revcomp(self):\n        if not hasattr(self, \"_revcomp\"):\n            # Motifs that are single stranded will return None.\n            # If all our motifs are single stranded, we'll return None also.\n            rc = self._revcomp = copy.copy(self)\n            rc.motifs = []\n            rc.lost_motifs = [] # single stranded motifs that can't be used in the revcomp\n            rc.offsets = []\n            rc.all_kmers = set()\n            for motif, offset in zip(self.motifs, self.offsets):\n                if motif.revcomp:\n                    rc.motifs.append(motif.revcomp)\n                    rc.offsets.append(offset) # will be reversed shortly\n                    rc.all_kmers.update(motif.revcomp.all_kmers)\n                else:\n                    rc.lost_motifs.append(motif)\n            if rc.motifs:\n                max_off = max(rc.offsets)\n                rc.offsets = [max_off - o for o in rc.offsets] # have to reverse direction of offsets\n                rc.start, rc.end, rc.score, rc.evidence = improve_window(kmers=rc.all_kmers, **rc.data)\n                rc._revcomp = self\n            else:\n                self._revcomp = None\n        return self._revcomp\n    def __cmp__(self, other):\n        return cmp(self.score, other.score)\n    def __len__(self):\n        return len(self.motifs)\n    def __str__(self):\n        return \"<%.2f, %i to %i, %i motifs: %s ...>\" % (self.score, self.start_user, self.end_user, len(self.motifs), self.motifs[0].center)\n\ndef overlaps(mc1, mc2):\n    \"\"\"Compare two motifs and/or clusters to see if their location ranges overlap.\"\"\"\n    return (mc1.start < mc2.end) and (mc1.end > mc2.start)\n\ndef extract_positive_seqs(cluster, evidence, suf, seq_lens, seq_offsets, align_5p, midgap):\n    \"\"\"\n    For the \"positive\" (in-group) sequences, extract all the unique regions\n    that contain 1+ of the kmers in cluster.\n    We do this to avoid the multiple-counting problem of tallying kmers individually.\n    \"\"\"\n    regions = set() # set([(start,end,revcomp)]) within suf.corpus (the concatenated sequences)\n    max_offset = max(cluster.offsets)\n    kmer_len = len(cluster.motifs[0].center) + midgap # k-mer length, including \"gap\" residues in the middle\n    region_len = max_offset + kmer_len\n    for motif, offset in zip(cluster.motifs, cluster.offsets):\n        # First, the positive strand:\n        fwd_kmers = set([motif.center]) | motif.friends\n        locs, matches = kmers_matches(fwd_kmers, suf, seq_offsets, midgap)\n        seq_locs = locs.copy()\n        max_seq_len = filelocs_to_seqlocs(seq_locs, matches, seq_lens, seq_offsets, align_5p)\n        # matches within the positive set of sequences and the allowed region\n        keep = (evidence[matches] > 0) & (cluster.start <= seq_locs) & (seq_locs < cluster.end)\n        starts = locs[keep] - offset\n        regions.update((start, start+region_len, False) for start in starts)\n        # Then, the reverse strand\n        rev_kmers = motif.all_kmers - fwd_kmers # avoid double-counting palindromes\n        if rev_kmers:\n            locs, matches = kmers_matches(rev_kmers, suf, seq_offsets, midgap)\n            seq_locs = locs.copy()\n            max_seq_len = filelocs_to_seqlocs(seq_locs, matches, seq_lens, seq_offsets, align_5p)\n            # matches within the positive set of sequences and the allowed region\n            keep = (evidence[matches] > 0) & (cluster.start <= seq_locs) & (seq_locs < cluster.end)\n            starts = locs[keep] - (max_offset - offset)\n            regions.update((start, start+region_len, True) for start in starts)\n    seqs = []\n    for start, end, revcomp in regions:\n        subseq = suf.corpus[start:end]\n        # Because of the padding at the start and/or end due to max_offset,\n        # subseq may inadvertently span two different genomic sequences!\n        nl = subseq.find(\"\\n\")\n        if nl >= 0:\n            if nl < kmer_len: subseq = subseq[nl+1:].rjust(region_len, \"N\") # left side shorter than k\n            elif nl >= max_offset: subseq = subseq[:nl].ljust(region_len, \"N\") # right side shorter than k\n            else: continue # could have been either side, too much trouble to figure out, skip it\n        if revcomp: seqs.append(dnaseq.reverse_complement(subseq))\n        else: seqs.append(subseq)\n    return seqs\n\n", "meta": {"hexsha": "abe7ddf64328894c48afc56ec033f7294ebdbc01", "size": 30475, "ext": "py", "lang": "Python", "max_stars_repo_path": "pygr/powrs.py", "max_stars_repo_name": "iwd32900/powrs", "max_stars_repo_head_hexsha": "bd4927f0cb6ab1aa6b77b5adc3cc846dbd064045", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-05-02T09:30:23.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-05T22:37:40.000Z", "max_issues_repo_path": "pygr/powrs.py", "max_issues_repo_name": "iwd32900/powrs", "max_issues_repo_head_hexsha": "bd4927f0cb6ab1aa6b77b5adc3cc846dbd064045", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pygr/powrs.py", "max_forks_repo_name": "iwd32900/powrs", "max_forks_repo_head_hexsha": "bd4927f0cb6ab1aa6b77b5adc3cc846dbd064045", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-11-05T22:37:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-03T11:30:48.000Z", "avg_line_length": 54.8111510791, "max_line_length": 140, "alphanum_fraction": 0.6256275636, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.18922692601607072}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: shahab Sotudian\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport math\nimport six\nfrom six.moves import range\nfrom scipy.stats import rankdata\nimport sys\nimport time\nfrom sklearn import preprocessing\nfrom scipy.stats import spearmanr\nimport random\nstart_time = time.time()\n\n\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n# @@@@                         Functions\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n\nWhich_Type='ANTIBODY' # 'ANTIBODY'  'ENZYME'   'OTHERS'\nNum_Features= 30   # Total number of features\n\nif Which_Type == 'ANTIBODY':\n    Test_Proteins= ['3rvw','4dn4','4g6j','3hi6','3l5w','2vxt','2w9e','4g6m','3g6d','3eo1','3v6z','3hmx','3eoa','3mxw']\n    \n    Train_Proteins=['1mlc','1iqd','2jel','1nca','1ahw','1e6j','1kxq','1wej','1dqj','2fd6','2i25','1jps','2hmi','1k4c',\n                    '1i9r','1bj1','1bgx','1qfw','2vis','1nsn','1bvk','1fsk','1vfb']\n    \n    \n    Features_Ordered= ['mincomp_fa_rep','mincomp_score','mincomp_total_score','piper_fa_rep','piper_score','piper_total_score',\n                       'movedcomp_total_score','movedcomp_score','var_mem_Elec','var_mem_Born','kurt_mem_Avdw','SPPS','skew_mem_Rvdw',\n                       'kurt_mem_Born','avg_mem_Elec','mincomp_fa_dun','PREMIN_COMP_Torsions','movedcomp_fa_dun','POSTMIN_COMP_Torsions',\n                       'PREMIN_SING_Torsions','POSTMIN_SING_Torsions','mincomp_rama_prepro','cen_Elec','movedcomp_rama_prepro','size',\n                       'piper_fa_dun','mincomp_fa_atr','cen_Born','avg_mem_Born','piper_rama_prepro','mincomp_fa_sol',\n                       'piper_fa_intra_sol_xover4','mincomp_omega','POSTMIN_SING_Impropers','piper_yhh_planarity','movedcomp_omega',\n                       'movedcomp_fa_intra_rep','mincomp_pro_close','var_mem_Avdw','POSTMIN_SING_Bonded','piper_omega',\n                       'movedcomp_pro_close','PREMIN_COMP_Impropers','mincomp_fa_intra_rep','PREMIN_SING_Impropers','POSTMIN_COMP_Impropers',\n                       'PREMIN_COMP_Bonded','PREMIN_SING_Bonded','POSTMIN_COMP_Bonded','PREMIN_COMP_Angles','piper_pro_close',\n                       'POSTMIN_SING_Angles','movedcomp_fa_intra_sol_xover4','PREMIN_SING_Angles','POSTMIN_COMP_Angles',\n                       'mincomp_fa_intra_sol_xover4','skew_mem_Born','avg_mem_dist','movedcomp_yhh_planarity','cen_Avdw',\n                       'mincomp_yhh_planarity','avg_mem_Avdw','var_mem_dist','movedcomp_ref','mincomp_ref','piper_fa_atr',\n                       'movedcomp_fa_atr','var_mem_DARS','movedcomp_fa_sol','avg_mem_DARS','piper_fa_sol','var_mem_Rvdw','cen_DARS',\n                       'piper_dslf_fa13','piper_ref','SPAR','var_mem_Teng','movedcomp_dslf_fa13','cen_Rvdw','movedcomp_hbond_lr_bb',\n                       'mincomp_hbond_lr_bb','movedcomp_hbond_bb_sc','piper_hbond_bb_sc','movedcomp_hbond_sr_bb','mincomp_hbond_sr_bb',\n                       'avg_mem_Rvdw','mincomp_hbond_bb_sc','piper_hbond_sr_bb','movedcomp_hbond_sc','mincomp_fa_elec','piper_hbond_sc',\n                       'movedcomp_fa_elec','SPAS','mincomp_hbond_sc','cen_Teng','piper_fa_elec','avg_mem_Teng','piper_hbond_lr_bb','piper_time']\n    \n    DATA_ALL = pd.read_csv('/home/Final_DATA_Antibody.csv')\n\nelif Which_Type == 'ENZYME':\n    Test_Proteins= ['2gaf','4hx3','3a4s','2yvj','4fza','3fn1','3pc8','3lvk','3k75','4iz7','3vlb','4h03','3h11','1jtd','4lw4','2a1a']\n    \n    Train_Proteins=['3sgq','1fq1','2o3b','1d6r','2pcc','2mta','1kkl','1oc0','1mah','1m10','1jzd','1cgi','1ijk','1f51','2ayo','7cei',\n                    '1jiw','2uuy','2oul','1us7','1jk9','1tmq','2sni','1avx','1gxd','2oob','1hia','1dfj','2nz8','2j0t','2z0e','1nw9',\n                    '1ay7','1jtg','2oor','2ot3','1jwh','1bvn','1oph','1ezu','1e6e','1acb','1f6m','2abz','1f34','1jmo','1gl1','1udi',\n                    '1r6q','1zm4','1eaw','1ewy','2b42','1buh','1pxv','2sic','2a9k','4cpa','1z5y','1gla','2o8v','1zli','1r0r','1fle',\n                    '1oyv','1ppe','1wdw','1yvb','1clv','2ido']\n    \n    Features_Ordered= ['movedcomp_fa_rep','movedcomp_score','movedcomp_total_score','piper_lk_ball_wtd','POSTMIN_COMP_VWD03',\n                       'POSTMIN_SING_VWD03','mincomp_lk_ball_wtd','var_mem_Born','mincomp_hbond_lr_bb','piper_pro_close',\n                       'movedcomp_hbond_lr_bb','movedcomp_lk_ball_wtd','movedcomp_pro_close','piper_hbond_lr_bb','var_mem_Elec',\n                       'POSTMIN_COMP_Angles','POSTMIN_COMP_Impropers','piper_dslf_fa13','movedcomp_dslf_fa13','mincomp_pro_close',\n                       'POSTMIN_SING_Bonded','movedcomp_omega','piper_fa_rep','size','PREMIN_SING_Bonded','PREMIN_COMP_Bonded',\n                       'POSTMIN_SING_Impropers','POSTMIN_COMP_Bonded','mincomp_fa_rep','mincomp_hbond_sr_bb','piper_hbond_sr_bb',\n                       'piper_total_score','piper_score','piper_omega','POSTMIN_SING_Angles','avg_mem_DARS','cen_DARS',\n                       'movedcomp_hbond_sr_bb','PREMIN_SING_Impropers','PREMIN_COMP_Impropers','PREMIN_SING_Angles','mincomp_omega',\n                       'PREMIN_COMP_Angles','movedcomp_fa_dun','SPPS','mincomp_fa_dun','mincomp_total_score','mincomp_score',\n                       'mincomp_fa_intra_rep','movedcomp_yhh_planarity','piper_rama_prepro','mincomp_rama_prepro',\n                       'movedcomp_rama_prepro','piper_yhh_planarity','kurt_mem_dist','movedcomp_hbond_sc','cen_Elec',\n                       'mincomp_yhh_planarity','mincomp_hbond_sc','mincomp_dslf_fa13','var_mem_dist','movedcomp_fa_intra_rep',\n                       'movedcomp_hbond_bb_sc','mincomp_hbond_bb_sc','kurt_mem_Born','avg_mem_dist','avg_mem_Elec','PREMIN_SING_VWD03',\n                       'PREMIN_COMP_VWD03','SPAR','PREMIN_COMP_Torsions','PREMIN_SING_Torsions','piper_fa_dun','mincomp_p_aa_pp',\n                       'movedcomp_p_aa_pp','POSTMIN_COMP_Torsions','mincomp_fa_elec','piper_hbond_bb_sc','POSTMIN_SING_Torsions',\n                       'var_mem_DARS','movedcomp_fa_sol','movedcomp_fa_elec','piper_fa_atr','piper_fa_elec','mincomp_fa_atr',\n                       'piper_fa_sol','mincomp_fa_sol','movedcomp_fa_atr','SPAS','piper_hbond_sc','piper_fa_intra_sol_xover4',\n                       'movedcomp_time','movedcomp_fa_intra_sol_xover4','mincomp_fa_intra_sol_xover4','piper_fa_intra_rep',\n                       'piper_ref','movedcomp_ref','mincomp_ref','skew_mem_Born','kurt_mem_Teng','skew_mem_Teng','skew_mem_DARS',\n                       'skew_mem_dist','cen_Teng','mincomp_time','cen_Rvdw','var_mem_Teng','var_mem_Rvdw','avg_mem_Avdw','avg_mem_Rvdw']\n    \n    DATA_ALL = pd.read_csv('/home//Final_DATA_Enzyme.csv')    \n\nelif Which_Type == 'OTHERS':\n    Test_Proteins=['3szk','1m27','2x9a','baad','3aad','3s9d','3daw','cp57','3h2v','3bx7',\n                   '3biw','3p57','4m76','3aaa','3f1p','bp57','2gtp','1rke','3r9a','3l89',\n                   '1exb','4jcv']\n    \n    Train_Proteins=['1rv6','1eer','1e4k','2fju','1z0k','1ofu','1a2k','3cph','1ibr','1ib1',\n                    '1k5d','1k74','1syx','3d5s','1i4d','1rlb','1he8','1r8s','1pvh','1fcc',\n                    '3bp8','1azs','2hqs','1gpw','2c0l','2i9b','2hle','1de4','1qa9','1fqj',\n                    '1h1v','1e96','1j2j','1n2c','1t6b','2hrk','1kac','1y64','2b4j','1ghq',\n                    '2g77','1ml0','1gcq','1efn','1ffw','1bkd','1zhi','1klu','1xd3','2j7p',\n                    '2cfh','1hcf','2vdb','1atn','1grn','1lfd','1b6c','1ak4','1wq1','1ira',\n                    '2btf','1sbb','1xqs','1mq8','1xu1','1i2m','1he1','1s1q','2oza','1zhh',\n                    '1ktz','1fak','1fc2','1kxp','1gp2','2ajf','1akj','1h9d','2a5t']\n    \n    Features_Ordered=['mincomp_score','mincomp_total_score','mincomp_fa_rep','piper_total_score',\n                      'piper_score','piper_fa_rep','cen_Avdw','avg_mem_Avdw','var_mem_Teng',\n                      'var_mem_Avdw','avg_mem_Teng','mincomp_lk_ball_wtd','POSTMIN_COMP_Impropers',\n                      'size','POSTMIN_SING_Impropers','piper_p_aa_pp','mincomp_p_aa_pp',\n                      'movedcomp_lk_ball_wtd','mincomp_pro_close','movedcomp_p_aa_pp','piper_rama_prepro',\n                      'mincomp_rama_prepro','movedcomp_rama_prepro','PREMIN_COMP_Angles','PREMIN_SING_Angles',\n                      'piper_yhh_planarity','cen_DARS','movedcomp_hbond_bb_sc','avg_mem_DARS','POSTMIN_COMP_VWD03',\n                      'POSTMIN_COMP_Angles','POSTMIN_SING_Angles','SPPS','mincomp_hbond_bb_sc','piper_hbond_bb_sc',\n                      'movedcomp_hbond_sc','mincomp_yhh_planarity','mincomp_fa_dun','mincomp_hbond_sc','movedcomp_pro_close',\n                      'piper_pro_close','movedcomp_ref','mincomp_ref','piper_ref','movedcomp_yhh_planarity','SPAR',\n                      'movedcomp_fa_dun','piper_fa_elec','movedcomp_fa_elec','piper_hbond_sc','movedcomp_fa_atr',\n                      'piper_fa_intra_sol_xover4','movedcomp_fa_sol','mincomp_fa_elec','movedcomp_omega','piper_fa_atr',\n                      'piper_fa_sol','mincomp_fa_intra_sol_xover4','SPAS','movedcomp_fa_intra_sol_xover4','mincomp_fa_atr',\n                      'mincomp_fa_intra_rep','movedcomp_dslf_fa13','piper_fa_intra_rep','POSTMIN_SING_VWD03','PREMIN_COMP_VWD03',\n                      'mincomp_fa_sol','PREMIN_SING_VWD03','piper_dslf_fa13','POSTMIN_SING_Torsions','PREMIN_SING_Torsions',\n                      'PREMIN_COMP_Torsions','POSTMIN_COMP_Torsions','piper_fa_dun','movedcomp_fa_intra_rep','piper_hbond_sr_bb',\n                      'movedcomp_hbond_sr_bb','mincomp_hbond_sr_bb','mincomp_dslf_fa13','mincomp_omega','PREMIN_COMP_Impropers',\n                      'piper_omega','movedcomp_hbond_lr_bb','PREMIN_SING_Impropers','mincomp_hbond_lr_bb','piper_hbond_lr_bb',\n                      'skew_mem_DARS','cen_Elec','avg_mem_Elec','avg_mem_Born','cen_Born','piper_time','kurt_mem_Teng','skew_mem_Teng',\n                      'mincomp_time','movedcomp_time']\n    \n    DATA_ALL = pd.read_csv('/home/Others_Protein_DATA.csv')\n\n\n\n\nX=DATA_ALL.iloc[:][Features_Ordered[0:Num_Features]]\nY=pd.DataFrame(DATA_ALL.iloc[:]['dockq'])   # ['dockq','fnat','lrms','irms']\n\n\n\n# Normalazation\nNormalization_scaler = preprocessing.MinMaxScaler()#MinMaxScaler  StandardScaler\nNormalized_X=pd.DataFrame(   Normalization_scaler.fit_transform(X.values)    )\nNormalized_X.columns=X.columns\n\n\n\n\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n# @@@@                         Functions\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n\ndef dcg_at_k(r, k):\n    \"\"\"\n    Args:\n        r: Relevance scores (list or numpy) in rank order\n            (first element is the first item)\n        k: Number of results to consider\n\n    Returns:\n        Discounted cumulative gain\n    \"\"\"\n    r = np.asfarray(r)[:k]\n    return np.sum(r / np.log2(np.arange(2, r.size + 2)))\n\n\ndef ndcg_at_k(r, k):\n\n    dcg_max = dcg_at_k(sorted(r, reverse=True), k)\n    if not dcg_max:\n        return 0.\n    return dcg_at_k(r, k) / dcg_max\n\n\ndef Pi_Hat(Big_X_features,x,Theta, Alpha):\n    PI=1\n    PI_Hat=1\n    for i in range(len(Big_X_features)):\n        S_x_y= np.inner( Theta, x ) - np.inner( Theta, Big_X_features[i,:] )\n        # print(S_x_y)\n        if S_x_y != 0:\n            PI_Hat= PI_Hat + np.exp(-Alpha*S_x_y)/(1+np.exp(-Alpha*S_x_y))\n        # if S_x_y<0:\n        #     PI=PI+1\n    return PI_Hat\n       \n\ndef Gradient_Update(Big_X_Relevance,Big_X_features,Theta, Alpha):\n        # Part1  \n    N_n= 1/dcg_at_k(sorted(Big_X_Relevance, reverse=True), len(Big_X_Relevance))\n    if N_n == float('inf'):          # Revise N_n=0\n        N_n=1\n    Eq_41_Sumation= np.zeros(len(Big_X_features[1,:]))\n\n\n\n    for Ind_x in range(len(Big_X_features)):\n        global S_x_y\n        x= Big_X_features[Ind_x,:]\n        rx=Big_X_Relevance[Ind_x]\n\n        # Part2 Eq_42\n        Eq_42= np.zeros(len(Big_X_features[1,:]))\n        for i in range(len(Big_X_features)):\n            S_x_y= np.inner( Theta, x ) - np.inner( Theta, Big_X_features[i,:] )\n            if S_x_y != np.array([0.]):\n               \n                Grad_Diff= x - Big_X_features[i,:]  # This is for linear score functions\n                P1=np.exp(Alpha*S_x_y)/((1+np.exp(Alpha*S_x_y))**2)\n                Eq_42=Eq_42+ (P1*Grad_Diff)\n\n        Eq_42=-Alpha*Eq_42  \n           \n        # Part3 Eq_43        \n        PP1= -(((2**rx)-1)/(math.log2(1+Pi_Hat(Big_X_features,x,Theta, Alpha)))**2)\n        PP2= 1/((1+Pi_Hat(Big_X_features,x,Theta, Alpha))*np.log(2))\n        Eq_43=PP1*PP2\n   \n   \n        # Part 4 Eq_42_43\n\n        Eq_41_Sumation= Eq_41_Sumation + (Eq_43 * Eq_42)\n     \n    # Final gradient\n    return  N_n*Eq_41_Sumation  \n       \n\ndef iter_lines(lines, has_targets=True, one_indexed=True, missing=0.0):\n    \"\"\"Transforms an iterator of lines to an iterator of LETOR rows.\n    Each row is represented by a (x, y, qid, comment) tuple.\n    Parameters\n    ----------\n    lines : iterable of lines\n        Lines to parse.\n    has_targets : bool, optional\n        Whether the file contains targets. If True, will expect the first token\n        of every line to be a real representing the sample's target (i.e.\n        score). If False, will use -1 as a placeholder for all targets.\n    one_indexed : bool, optional\n        Whether feature ids are one-indexed. If True, will subtract 1 from each\n        feature id.\n    missing : float, optional\n        Placeholder to use if a feature value is not provided for a sample.\n    Yields\n    ------\n    x : array of floats\n        Feature vector of the sample.\n    y : float\n        Target value (score) of the sample, or -1 if no target was parsed.\n    qid : object\n        Query id of the sample. This is currently guaranteed to be a string.\n    comment : str\n        Comment accompanying the sample.\n    \"\"\"\n    for line in lines:\n                   \n        data, _, comment = line.rstrip().partition('#')\n        toks = data.split()\n\n        num_features = 0\n        x = np.repeat(missing, 8)\n        y = -1.0\n        if has_targets:\n            # print(toks)\n            # print(\"#########################\")\n            y = float(toks[0])\n            toks = toks[1:]\n\n        qid = _parse_qid_tok(toks[0])\n\n        for tok in toks[1:]:\n            fid, _, val = tok.partition(':')\n            fid = int(fid)\n            val = float(val)\n            if one_indexed:\n                fid -= 1\n            assert fid >= 0\n            while len(x) <= fid:\n                orig = len(x)\n                x.resize(len(x) * 2)\n                x[orig:orig * 2] = missing\n\n            x[fid] = val\n            num_features = max(fid + 1, num_features)\n\n        assert num_features > 0\n        x.resize(num_features)\n\n        yield (x, y, qid, comment)\n\n\n   \ndef read_dataset(source, has_targets=True, one_indexed=True, missing=0.0):\n    \"\"\"Parses a LETOR dataset from `source`.\n    Parameters\n    ----------\n    source : string or iterable of lines\n        String, file, or other file-like object to parse.\n    has_targets : bool, optional\n        See `iter_lines`.\n    one_indexed : bool, optional\n        See `iter_lines`.\n    missing : float, optional\n        See `iter_lines`.\n    Returns\n    -------\n    X : array of arrays of floats\n        Feature matrix (see `iter_lines`).\n    y : array of floats\n        Target vector (see `iter_lines`).\n    qids : array of objects\n        Query id vector (see `iter_lines`).\n    comments : array of strs\n        Comment vector (see `iter_lines`).\n    \"\"\"\n    if isinstance(source, six.string_types):\n        source = source.splitlines()\n\n    max_width = 0\n    xs, ys, qids, comments = [], [], [], []\n    it = iter_lines(source, has_targets=has_targets,\n                    one_indexed=one_indexed, missing=missing)\n    for x, y, qid, comment in it:\n        xs.append(x)\n        ys.append(y)\n        qids.append(qid)\n        comments.append(comment)\n        max_width = max(max_width, len(x))\n\n    assert max_width > 0\n    X = np.ndarray((len(xs), max_width), dtype=np.float64)\n    X.fill(missing)\n    for i, x in enumerate(xs):\n        X[i, :len(x)] = x\n    ys = np.array(ys) if has_targets else None\n    qids = np.array(qids)\n    comments = np.array(comments)\n\n    return (X, ys, qids, comments)\n   \n\ndef _parse_qid_tok(tok):\n    assert tok.startswith('qid:')\n    return tok[4:]\n\ndef Performance_Metrics(S_in):\n    RANKS=S_in[S_in['RANK_True']==1]\n    ACC_All=S_in[S_in['dockq']>0.23]\n    Med_All=S_in[S_in['dockq']>0.49]\n    # Spearman\n    Spearman=spearmanr(S_in['RANK_Pred'], S_in['RANK_True'])[0]\n    Spearman_C=spearmanr(S_in['RANK_ClusPro'], S_in['RANK_True'])[0]\n\n    # Highest Quality\n    T_1_star= int(RANKS['RANK_Pred']<=1)\n    T_5_star= int(RANKS['RANK_Pred']<=5)\n    T_10_star= int(RANKS['RANK_Pred']<=10)\n    \n    CT_1_star= int(RANKS['RANK_ClusPro']<=1)\n    CT_5_star= int(RANKS['RANK_ClusPro']<=5)\n    CT_10_star= int(RANKS['RANK_ClusPro']<=10)\n\n    # ACC\n    if ACC_All.empty:\n        ACCT_1=ACCT_5=ACCT_10=ACCCT_1=ACCCT_5=ACCCT_10=0\n        Have_Acc=0\n    else:\n        Have_Acc=1\n        ACCT_1=int(np.where( sum(x<=1 for x in ACC_All['RANK_Pred'])  > 0.5 , 1, 0))\n        ACCT_5=int(np.where( sum(x<=5 for x in ACC_All['RANK_Pred'])  > 0.5 , 1, 0))\n        ACCT_10= int(np.where( sum(x<=10 for x in ACC_All['RANK_Pred'])  > 0.5 , 1, 0))\n        \n        ACCCT_1=int(np.where( sum(x<=1 for x in ACC_All['RANK_ClusPro'])  > 0.5 , 1, 0))\n        ACCCT_5=int(np.where( sum(x<=5 for x in ACC_All['RANK_ClusPro'])  > 0.5 , 1, 0))\n        ACCCT_10=int(np.where( sum(x<=10 for x in ACC_All['RANK_ClusPro'])  > 0.5 , 1, 0))\n    \n    \n    # Med\n    if Med_All.empty:\n        MedT_1=MedT_5=MedT_10=MedCT_1=MedCT_5=MedCT_10=0\n        Have_Med=0\n    else:\n        Have_Med=1\n        MedT_1=int(np.where( sum(x<=1 for x in Med_All['RANK_Pred'])  > 0.5 , 1, 0))\n        MedT_5=int(np.where( sum(x<=5 for x in Med_All['RANK_Pred'])  > 0.5 , 1, 0))\n        MedT_10=int(np.where( sum(x<=10 for x in Med_All['RANK_Pred'])  > 0.5 , 1, 0))\n        \n        MedCT_1=int(np.where( sum(x<=1 for x in Med_All['RANK_ClusPro'])  > 0.5 , 1, 0))\n        MedCT_5=int(np.where( sum(x<=5 for x in Med_All['RANK_ClusPro'])  > 0.5 , 1, 0))\n        MedCT_10=int(np.where( sum(x<=10 for x in Med_All['RANK_ClusPro'])  > 0.5 , 1, 0))\n\n    return [Spearman,Spearman_C,T_1_star,CT_1_star,T_5_star,CT_5_star,T_10_star,CT_10_star,ACCT_1,ACCCT_1,ACCT_5,ACCCT_5,ACCT_10,ACCCT_10,Have_Acc,MedT_1,MedCT_1,MedT_5,MedCT_5,MedT_10,MedCT_10,Have_Med]\n\n\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n# @@@@                         Main Algorithm ApproxNDCG\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n\n\n# =========-------------------------------------------------------------------\n#  Data Preprocessing  -   Train\n# =========-------------------------------------------------------------------    \n   \n# Load data \n\n# X_Train=Normalized_X[DATA_ALL['pdbid'].isin(Train_Proteins)]\n# Y_Train=Y[DATA_ALL['pdbid'].isin(Train_Proteins)]\n\n# X_Train=X_Train.reset_index(drop=True)\n# Y_Train=Y_Train.reset_index(drop=True)\n\n\n\n\nNum_Queries=len(Train_Proteins)\nNum_Features= Normalized_X.shape[1]\n\n\n\nWeight_Y=1\nY=Y*Weight_Y  \nNum_itr=20\nLearning_Rate = 0.1\nAlpha=10\n\n# Initialize Theta  \nTheta_t_1 = np.zeros([(Num_itr+1),Num_Features])\n#Theta_t_1[0,:]=np.random.random([1,Num_Features])\nTheta_t_1[0,:]=np.ones([1,Num_Features])\n\n\nfor t in range(Num_itr):    \n    print('**** Iteration ', t+1, '  *******************************')\n    THETA= Theta_t_1[t,:]\n    for i in range(Num_Queries):\n        Big_X_features= Normalized_X[DATA_ALL['pdbid'].isin([Train_Proteins[i]])]\n        Big_X_Relevance= Y[DATA_ALL['pdbid'].isin([Train_Proteins[i]])]\n\n        # Compute gradient for i-th query\n        Delta_Theta=  Gradient_Update(np.array(Big_X_Relevance),np.array(Big_X_features),THETA, Alpha)\n      \n        THETA = THETA + (Learning_Rate * Delta_Theta)\n\n    Theta_t_1[(t+1),:]= THETA\n    # Shuffle queries\n    random.seed(t)\n    random.shuffle(Train_Proteins)  \n   \n\n\n\n# =========-------------------------------------------------------------------\n#  Data Preprocessing  -   Validation\n# =========-------------------------------------------------------------------    \n\n# with open(\"/home/vali.txt\") as validationfile:\n#     VX, Vy, Vqids, Vc = read_dataset(validationfile, has_targets=True , one_indexed=True)\n   \n\n\n# =========-------------------------------------------------------------------\n#  Data Preprocessing  -   Test\n# =========-------------------------------------------------------------------  \n   \n# X_Test=Normalized_X[DATA_ALL['pdbid'].isin(Test_Proteins)]\n# Y_Test=Y[DATA_ALL['pdbid'].isin(Test_Proteins)]\n# X_Test=X_Test.reset_index(drop=True)\n# Y_Test=Y_Test.reset_index(drop=True)\n\n\nNum_Test_Queries=len(Test_Proteins)\n\n \nPredicted_NDCGatk = np.array([0,1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\nfor pp in range(Num_itr):    \n    NDCG_all=[0,0,0,0,0,0,0,0,0,0,0]    \n    for tt in range(Num_Test_Queries):\n        Test_X_features= Normalized_X[DATA_ALL['pdbid'].isin([Test_Proteins[tt]])]\n        Pred_Q= np.matmul(np.array(Test_X_features)  , Theta_t_1[pp]  )     # Prediction in iteration pp-th\n        Ground_Q = np.array( Y[DATA_ALL['pdbid'].isin([Test_Proteins[tt]])] )\n        Pred_Ranks=(rankdata(-Pred_Q, method='ordinal'))    # Decreasing order\n        Pred_Ranks = np.expand_dims(Pred_Ranks, axis=1)\n        Concat= np.concatenate((Ground_Q,Pred_Ranks), axis=1)\n        sorted_array = Concat[np.argsort(Concat[:, 1])]\n        RGT= sorted_array[:,0]\n        # NDCG @ k\n        NDCG_all = np.add(NDCG_all, [pp, ndcg_at_k(RGT, 1),ndcg_at_k(RGT, 2),ndcg_at_k(RGT, 3),ndcg_at_k(RGT, 4),ndcg_at_k(RGT, 5),ndcg_at_k(RGT, 6),ndcg_at_k(RGT, 7),ndcg_at_k(RGT, 8),ndcg_at_k(RGT, 9),ndcg_at_k(RGT, 10)])  \n       \n\n    Predicted_NDCG=NDCG_all/Num_Test_Queries\n    print(Predicted_NDCG)\n    Predicted_NDCGatk=np.vstack([Predicted_NDCGatk,Predicted_NDCG])\n\n\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n\n# save numpy array as csv file\nfrom numpy import asarray\nfrom numpy import savetxt\n\n\n# save to csv file\n\n\n\nSAVE_Name_Theta= Which_Type + '_NFeature_' + str(Num_Features) +'_Learned_Thetas_itr'+str(Num_itr)+'_Alpha'+str(Alpha)+'.csv'\n\nSAVE_Name_Results= Which_Type + '_NFeature_' + str(Num_Features) + '_Results_itr'+str(Num_itr)+'_Alpha'+str(Alpha)+'.csv'\n\n# save to csv file\nsavetxt(SAVE_Name_Theta, Theta_t_1, delimiter=',')\n\nsavetxt(SAVE_Name_Results, Predicted_NDCGatk, delimiter=',')\n", "meta": {"hexsha": "c9b002e8402a1c9607f8bf019f9a5899d888d0be", "size": 22457, "ext": "py", "lang": "Python", "max_stars_repo_path": "ApproxNDCG/ApproxNDCG_Model_Protein.py", "max_stars_repo_name": "sotudian/Cluster-Ranking-in-Protein-Protein-Docking", "max_stars_repo_head_hexsha": "8272d4630649e05a06cdbf3bfae7b2fe30da670a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ApproxNDCG/ApproxNDCG_Model_Protein.py", "max_issues_repo_name": "sotudian/Cluster-Ranking-in-Protein-Protein-Docking", "max_issues_repo_head_hexsha": "8272d4630649e05a06cdbf3bfae7b2fe30da670a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ApproxNDCG/ApproxNDCG_Model_Protein.py", "max_forks_repo_name": "sotudian/Cluster-Ranking-in-Protein-Protein-Docking", "max_forks_repo_head_hexsha": "8272d4630649e05a06cdbf3bfae7b2fe30da670a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.4693069307, "max_line_length": 225, "alphanum_fraction": 0.5987442668, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 7057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3276682876897044, "lm_q1q2_score": 0.1892269174591755}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#\n\nimport numpy\nfrom pyscf import lib\nfrom pyscf.ao2mo import _ao2mo\nfrom pyscf.ao2mo.incore import iden_coeffs, _conc_mos\nfrom pyscf.pbc.df.fft_ao2mo import _format_kpts\nfrom pyscf.pbc.df import df_ao2mo\nfrom pyscf.pbc.df import aft_ao2mo\nfrom pyscf.pbc.lib import kpts_helper\nfrom pyscf.pbc.lib.kpts_helper import is_zero, gamma_point, member, unique\nfrom pyscf import __config__\n\n\ndef get_eri(mydf, kpts=None,\n            compact=getattr(__config__, 'pbc_df_ao2mo_get_eri_compact', True)):\n    if mydf._cderi is None:\n        mydf.build()\n\n    kptijkl = _format_kpts(kpts)\n    eri = aft_ao2mo.get_eri(mydf, kptijkl, compact=compact)\n    eri += df_ao2mo.get_eri(mydf, kptijkl, compact=compact)\n    return eri\n\n\ndef general(mydf, mo_coeffs, kpts=None,\n            compact=getattr(__config__, 'pbc_df_ao2mo_general_compact', True)):\n    if mydf._cderi is None:\n        mydf.build()\n\n    kptijkl = _format_kpts(kpts)\n    if isinstance(mo_coeffs, numpy.ndarray) and mo_coeffs.ndim == 2:\n        mo_coeffs = (mo_coeffs,) * 4\n    eri_mo = aft_ao2mo.general(mydf, mo_coeffs, kptijkl, compact=compact)\n    eri_mo += df_ao2mo.general(mydf, mo_coeffs, kptijkl, compact=compact)\n    return eri_mo\n\ndef ao2mo_7d(mydf, mo_coeff_kpts, kpts=None, factor=1, out=None):\n    cell = mydf.cell\n    if kpts is None:\n        kpts = mydf.kpts\n    nkpts = len(kpts)\n\n    if isinstance(mo_coeff_kpts, numpy.ndarray) and mo_coeff_kpts.ndim == 3:\n        mo_coeff_kpts = [mo_coeff_kpts] * 4\n    else:\n        mo_coeff_kpts = list(mo_coeff_kpts)\n\n    # Shape of the orbitals can be different on different k-points. The\n    # orbital coefficients must be formatted (padded by zeros) so that the\n    # shape of the orbital coefficients are the same on all k-points. This can\n    # be achieved by calling pbc.mp.kmp2.padded_mo_coeff function\n    nmoi, nmoj, nmok, nmol = [x.shape[2] for x in mo_coeff_kpts]\n    eri_shape = (nkpts, nkpts, nkpts, nmoi, nmoj, nmok, nmol)\n    if gamma_point(kpts):\n        dtype = numpy.result_type(*mo_coeff_kpts)\n    else:\n        dtype = numpy.complex128\n\n    if out is None:\n        out = numpy.empty(eri_shape, dtype=dtype)\n    else:\n        assert(out.shape == eri_shape)\n\n    kptij_lst = numpy.array([(ki, kj) for ki in kpts for kj in kpts])\n    kptis_lst = kptij_lst[:,0]\n    kptjs_lst = kptij_lst[:,1]\n    kpt_ji = kptjs_lst - kptis_lst\n    uniq_kpts, uniq_index, uniq_inverse = unique(kpt_ji)\n    ngrids = numpy.prod(mydf.mesh)\n    nao = cell.nao_nr()\n    max_memory = max(2000, mydf.max_memory-lib.current_memory()[0]-nao**4*16/1e6) * .5\n\n    fswap = lib.H5TmpFile()\n    tao = []\n    ao_loc = None\n    kconserv = kpts_helper.get_kconserv(cell, kpts)\n    for uniq_id, kpt in enumerate(uniq_kpts):\n        q = uniq_kpts[uniq_id]\n        adapted_ji_idx = numpy.where(uniq_inverse == uniq_id)[0]\n\n        kptjs = kptjs_lst[adapted_ji_idx]\n        coulG = mydf.weighted_coulG(q, False, mydf.mesh)\n        coulG *= factor\n\n        moij_list = []\n        ijslice_list = []\n        for ji, ji_idx in enumerate(adapted_ji_idx):\n            ki = ji_idx // nkpts\n            kj = ji_idx % nkpts\n            moij, ijslice = _conc_mos(mo_coeff_kpts[0][ki], mo_coeff_kpts[1][kj])[2:]\n            moij_list.append(moij)\n            ijslice_list.append(ijslice)\n            fswap.create_dataset('zij/'+str(ji), (ngrids,nmoi*nmoj), 'D')\n\n        for aoaoks, p0, p1 in mydf.ft_loop(mydf.mesh, q, kptjs,\n                                           max_memory=max_memory):\n            for ji, aoao in enumerate(aoaoks):\n                ki = adapted_ji_idx[ji] // nkpts\n                kj = adapted_ji_idx[ji] %  nkpts\n                buf = aoao.transpose(1,2,0).reshape(nao**2,p1-p0)\n                zij = _ao2mo.r_e2(lib.transpose(buf), moij_list[ji],\n                                  ijslice_list[ji], tao, ao_loc)\n                zij *= coulG[p0:p1,None]\n                fswap['zij/'+str(ji)][p0:p1] = zij\n\n        mokl_list = []\n        klslice_list = []\n        for kk in range(nkpts):\n            kl = kconserv[ki, kj, kk]\n            mokl, klslice = _conc_mos(mo_coeff_kpts[2][kk], mo_coeff_kpts[3][kl])[2:]\n            mokl_list.append(mokl)\n            klslice_list.append(klslice)\n            fswap.create_dataset('zkl/'+str(kk), (ngrids,nmok*nmol), 'D')\n\n        ki = adapted_ji_idx[0] // nkpts\n        kj = adapted_ji_idx[0] % nkpts\n        kptls = kpts[kconserv[ki, kj, :]]\n        for aoaoks, p0, p1 in mydf.ft_loop(mydf.mesh, q, -kptls,\n                                           max_memory=max_memory):\n            for kk, aoao in enumerate(aoaoks):\n                buf = aoao.conj().transpose(1,2,0).reshape(nao**2,p1-p0)\n                zkl = _ao2mo.r_e2(lib.transpose(buf), mokl_list[kk],\n                                  klslice_list[kk], tao, ao_loc)\n                fswap['zkl/'+str(kk)][p0:p1] = zkl\n\n        for ji, ji_idx in enumerate(adapted_ji_idx):\n            ki = ji_idx // nkpts\n            kj = ji_idx % nkpts\n\n            moij, ijslice = _conc_mos(mo_coeff_kpts[0][ki], mo_coeff_kpts[1][kj])[2:]\n            zij = []\n            for LpqR, LpqI, sign in mydf.sr_loop(kpts[[ki,kj]], max_memory, False, mydf.blockdim):\n                zij.append(_ao2mo.r_e2(LpqR+LpqI*1j, moij, ijslice, tao, ao_loc))\n\n            for kk in range(nkpts):\n                kl = kconserv[ki, kj, kk]\n                eri_mo = lib.dot(numpy.asarray(fswap['zij/'+str(ji)]).T,\n                                 numpy.asarray(fswap['zkl/'+str(kk)]))\n\n                for i, (LrsR, LrsI, sign) in \\\n                        enumerate(mydf.sr_loop(kpts[[kk,kl]], max_memory, False, mydf.blockdim)):\n                    zkl = _ao2mo.r_e2(LrsR+LrsI*1j, mokl_list[kk],\n                                      klslice_list[kk], tao, ao_loc)\n                    lib.dot(zij[i].T, zkl, sign*factor, eri_mo, 1)\n\n                if dtype == numpy.double:\n                    eri_mo = eri_mo.real\n                out[ki,kj,kk] = eri_mo.reshape(eri_shape[3:])\n        del(fswap['zij'])\n        del(fswap['zkl'])\n\n    return out\n\n", "meta": {"hexsha": "22de3ec123184f3ddcd82e4758cf178ee637c9a2", "size": 6690, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/pbc/df/mdf_ao2mo.py", "max_stars_repo_name": "crisely09/pyscf", "max_stars_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-30T22:33:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-22T18:02:36.000Z", "max_issues_repo_path": "pyscf/pbc/df/mdf_ao2mo.py", "max_issues_repo_name": "crisely09/pyscf", "max_issues_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscf/pbc/df/mdf_ao2mo.py", "max_forks_repo_name": "crisely09/pyscf", "max_forks_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-09-16T23:37:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-14T23:00:39.000Z", "avg_line_length": 39.1228070175, "max_line_length": 98, "alphanum_fraction": 0.6077727952, "include": true, "reason": "import numpy", "num_tokens": 2034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.30735800417608683, "lm_q1q2_score": 0.18905217566436747}}
{"text": "# Copyright 2021 AlQuraishi Laboratory\n# Copyright 2021 DeepMind Technologies Limited\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Constants used in AlphaFold.\"\"\"\n\nimport collections\nimport functools\nfrom typing import Mapping, List, Tuple\n\nimport numpy as np\nimport tree\n\n# Internal import (35fd).\n\n\n# Distance from one CA to next CA [trans configuration: omega = 180].\nca_ca = 3.80209737096\n\n# Format: The list for each AA type contains chi1, chi2, chi3, chi4 in\n# this order (or a relevant subset from chi1 onwards). ALA and GLY don't have\n# chi angles so their chi angle lists are empty.\nchi_angles_atoms = {\n    \"ALA\": [],\n    # Chi5 in arginine is always 0 +- 5 degrees, so ignore it.\n    \"ARG\": [\n        [\"N\", \"CA\", \"CB\", \"CG\"],\n        [\"CA\", \"CB\", \"CG\", \"CD\"],\n        [\"CB\", \"CG\", \"CD\", \"NE\"],\n        [\"CG\", \"CD\", \"NE\", \"CZ\"],\n    ],\n    \"ASN\": [[\"N\", \"CA\", \"CB\", \"CG\"], [\"CA\", \"CB\", \"CG\", \"OD1\"]],\n    \"ASP\": [[\"N\", \"CA\", \"CB\", \"CG\"], [\"CA\", \"CB\", \"CG\", \"OD1\"]],\n    \"CYS\": [[\"N\", \"CA\", \"CB\", \"SG\"]],\n    \"GLN\": [\n        [\"N\", \"CA\", \"CB\", \"CG\"],\n        [\"CA\", \"CB\", \"CG\", \"CD\"],\n        [\"CB\", \"CG\", \"CD\", \"OE1\"],\n    ],\n    \"GLU\": [\n        [\"N\", \"CA\", \"CB\", \"CG\"],\n        [\"CA\", \"CB\", \"CG\", \"CD\"],\n        [\"CB\", \"CG\", \"CD\", \"OE1\"],\n    ],\n    \"GLY\": [],\n    \"HIS\": [[\"N\", \"CA\", \"CB\", \"CG\"], [\"CA\", \"CB\", \"CG\", \"ND1\"]],\n    \"ILE\": [[\"N\", \"CA\", \"CB\", \"CG1\"], [\"CA\", \"CB\", \"CG1\", \"CD1\"]],\n    \"LEU\": [[\"N\", \"CA\", \"CB\", \"CG\"], [\"CA\", \"CB\", \"CG\", \"CD1\"]],\n    \"LYS\": [\n        [\"N\", \"CA\", \"CB\", \"CG\"],\n        [\"CA\", \"CB\", \"CG\", \"CD\"],\n        [\"CB\", \"CG\", \"CD\", \"CE\"],\n        [\"CG\", \"CD\", \"CE\", \"NZ\"],\n    ],\n    \"MET\": [\n        [\"N\", \"CA\", \"CB\", \"CG\"],\n        [\"CA\", \"CB\", \"CG\", \"SD\"],\n        [\"CB\", \"CG\", \"SD\", \"CE\"],\n    ],\n    \"PHE\": [[\"N\", \"CA\", \"CB\", \"CG\"], [\"CA\", \"CB\", \"CG\", \"CD1\"]],\n    \"PRO\": [[\"N\", \"CA\", \"CB\", \"CG\"], [\"CA\", \"CB\", \"CG\", \"CD\"]],\n    \"SER\": [[\"N\", \"CA\", \"CB\", \"OG\"]],\n    \"THR\": [[\"N\", \"CA\", \"CB\", \"OG1\"]],\n    \"TRP\": [[\"N\", \"CA\", \"CB\", \"CG\"], [\"CA\", \"CB\", \"CG\", \"CD1\"]],\n    \"TYR\": [[\"N\", \"CA\", \"CB\", \"CG\"], [\"CA\", \"CB\", \"CG\", \"CD1\"]],\n    \"VAL\": [[\"N\", \"CA\", \"CB\", \"CG1\"]],\n}\n\n# If chi angles given in fixed-length array, this matrix determines how to mask\n# them for each AA type. The order is as per restype_order (see below).\nchi_angles_mask = [\n    [0.0, 0.0, 0.0, 0.0],  # ALA\n    [1.0, 1.0, 1.0, 1.0],  # ARG\n    [1.0, 1.0, 0.0, 0.0],  # ASN\n    [1.0, 1.0, 0.0, 0.0],  # ASP\n    [1.0, 0.0, 0.0, 0.0],  # CYS\n    [1.0, 1.0, 1.0, 0.0],  # GLN\n    [1.0, 1.0, 1.0, 0.0],  # GLU\n    [0.0, 0.0, 0.0, 0.0],  # GLY\n    [1.0, 1.0, 0.0, 0.0],  # HIS\n    [1.0, 1.0, 0.0, 0.0],  # ILE\n    [1.0, 1.0, 0.0, 0.0],  # LEU\n    [1.0, 1.0, 1.0, 1.0],  # LYS\n    [1.0, 1.0, 1.0, 0.0],  # MET\n    [1.0, 1.0, 0.0, 0.0],  # PHE\n    [1.0, 1.0, 0.0, 0.0],  # PRO\n    [1.0, 0.0, 0.0, 0.0],  # SER\n    [1.0, 0.0, 0.0, 0.0],  # THR\n    [1.0, 1.0, 0.0, 0.0],  # TRP\n    [1.0, 1.0, 0.0, 0.0],  # TYR\n    [1.0, 0.0, 0.0, 0.0],  # VAL\n]\n\n# The following chi angles are pi periodic: they can be rotated by a multiple\n# of pi without affecting the structure.\nchi_pi_periodic = [\n    [0.0, 0.0, 0.0, 0.0],  # ALA\n    [0.0, 0.0, 0.0, 0.0],  # ARG\n    [0.0, 0.0, 0.0, 0.0],  # ASN\n    [0.0, 1.0, 0.0, 0.0],  # ASP\n    [0.0, 0.0, 0.0, 0.0],  # CYS\n    [0.0, 0.0, 0.0, 0.0],  # GLN\n    [0.0, 0.0, 1.0, 0.0],  # GLU\n    [0.0, 0.0, 0.0, 0.0],  # GLY\n    [0.0, 0.0, 0.0, 0.0],  # HIS\n    [0.0, 0.0, 0.0, 0.0],  # ILE\n    [0.0, 0.0, 0.0, 0.0],  # LEU\n    [0.0, 0.0, 0.0, 0.0],  # LYS\n    [0.0, 0.0, 0.0, 0.0],  # MET\n    [0.0, 1.0, 0.0, 0.0],  # PHE\n    [0.0, 0.0, 0.0, 0.0],  # PRO\n    [0.0, 0.0, 0.0, 0.0],  # SER\n    [0.0, 0.0, 0.0, 0.0],  # THR\n    [0.0, 0.0, 0.0, 0.0],  # TRP\n    [0.0, 1.0, 0.0, 0.0],  # TYR\n    [0.0, 0.0, 0.0, 0.0],  # VAL\n    [0.0, 0.0, 0.0, 0.0],  # UNK\n]\n\n# Atoms positions relative to the 8 rigid groups, defined by the pre-omega, phi,\n# psi and chi angles:\n# 0: 'backbone group',\n# 1: 'pre-omega-group', (empty)\n# 2: 'phi-group', (currently empty, because it defines only hydrogens)\n# 3: 'psi-group',\n# 4,5,6,7: 'chi1,2,3,4-group'\n# The atom positions are relative to the axis-end-atom of the corresponding\n# rotation axis. The x-axis is in direction of the rotation axis, and the y-axis\n# is defined such that the dihedral-angle-definiting atom (the last entry in\n# chi_angles_atoms above) is in the xy-plane (with a positive y-coordinate).\n# format: [atomname, group_idx, rel_position]\nrigid_group_atom_positions = {\n    \"ALA\": [\n        [\"N\", 0, (-0.525, 1.363, 0.000)],\n        [\"CA\", 0, (0.000, 0.000, 0.000)],\n        [\"C\", 0, (1.526, -0.000, -0.000)],\n        [\"CB\", 0, (-0.529, -0.774, -1.205)],\n        [\"O\", 3, (0.627, 1.062, 0.000)],\n    ],\n    \"ARG\": [\n        [\"N\", 0, (-0.524, 1.362, -0.000)],\n        [\"CA\", 0, (0.000, 0.000, 0.000)],\n        [\"C\", 0, (1.525, -0.000, -0.000)],\n        [\"CB\", 0, (-0.524, -0.778, -1.209)],\n        [\"O\", 3, (0.626, 1.062, 0.000)],\n        [\"CG\", 4, (0.616, 1.390, -0.000)],\n        [\"CD\", 5, (0.564, 1.414, 0.000)],\n        [\"NE\", 6, (0.539, 1.357, -0.000)],\n        [\"NH1\", 7, (0.206, 2.301, 0.000)],\n        [\"NH2\", 7, (2.078, 0.978, -0.000)],\n        [\"CZ\", 7, (0.758, 1.093, -0.000)],\n    ],\n    \"ASN\": [\n        [\"N\", 0, (-0.536, 1.357, 0.000)],\n        [\"CA\", 0, (0.000, 0.000, 0.000)],\n        [\"C\", 0, (1.526, -0.000, -0.000)],\n        [\"CB\", 0, (-0.531, -0.787, -1.200)],\n        [\"O\", 3, (0.625, 1.062, 0.000)],\n        [\"CG\", 4, (0.584, 1.399, 0.000)],\n        [\"ND2\", 5, (0.593, -1.188, 0.001)],\n        [\"OD1\", 5, (0.633, 1.059, 0.000)],\n    ],\n    \"ASP\": [\n        [\"N\", 0, (-0.525, 1.362, -0.000)],\n        [\"CA\", 0, (0.000, 0.000, 0.000)],\n        [\"C\", 0, (1.527, 0.000, -0.000)],\n        [\"CB\", 0, (-0.526, -0.778, -1.208)],\n        [\"O\", 3, (0.626, 1.062, -0.000)],\n        [\"CG\", 4, (0.593, 1.398, -0.000)],\n        [\"OD1\", 5, (0.610, 1.091, 0.000)],\n        [\"OD2\", 5, (0.592, -1.101, -0.003)],\n    ],\n    \"CYS\": [\n        [\"N\", 0, (-0.522, 1.362, -0.000)],\n        [\"CA\", 0, (0.000, 0.000, 0.000)],\n        [\"C\", 0, (1.524, 0.000, 0.000)],\n        [\"CB\", 0, (-0.519, -0.773, -1.212)],\n        [\"O\", 3, (0.625, 1.062, -0.000)],\n        [\"SG\", 4, (0.728, 1.653, 0.000)],\n    ],\n    \"GLN\": [\n        [\"N\", 0, (-0.526, 1.361, -0.000)],\n        [\"CA\", 0, (0.000, 0.000, 0.000)],\n        [\"C\", 0, (1.526, 0.000, 0.000)],\n        [\"CB\", 0, (-0.525, -0.779, -1.207)],\n        [\"O\", 3, (0.626, 1.062, -0.000)],\n        [\"CG\", 4, (0.615, 1.393, 0.000)],\n        [\"CD\", 5, (0.587, 1.399, -0.000)],\n        [\"NE2\", 6, (0.593, -1.189, -0.001)],\n        [\"OE1\", 6, (0.634, 1.060, 0.000)],\n    ],\n    \"GLU\": [\n        [\"N\", 0, (-0.528, 1.361, 0.000)],\n        [\"CA\", 0, (0.000, 0.000, 0.000)],\n        [\"C\", 0, (1.526, -0.000, -0.000)],\n        [\"CB\", 0, (-0.526, -0.781, -1.207)],\n        [\"O\", 3, (0.626, 1.062, 0.000)],\n        [\"CG\", 4, (0.615, 1.392, 0.000)],\n        [\"CD\", 5, (0.600, 1.397, 0.000)],\n        [\"OE1\", 6, (0.607, 1.095, -0.000)],\n        [\"OE2\", 6, (0.589, -1.104, -0.001)],\n    ],\n    \"GLY\": [\n        [\"N\", 0, (-0.572, 1.337, 0.000)],\n        [\"CA\", 0, (0.000, 0.000, 0.000)],\n        [\"C\", 0, (1.517, -0.000, -0.000)],\n        [\"O\", 3, (0.626, 1.062, -0.000)],\n    ],\n    \"HIS\": [\n        [\"N\", 0, (-0.527, 1.360, 0.000)],\n        [\"CA\", 0, (0.000, 0.000, 0.000)],\n        [\"C\", 0, (1.525, 0.000, 0.000)],\n        [\"CB\", 0, (-0.525, -0.778, -1.208)],\n        [\"O\", 3, (0.625, 1.063, 0.000)],\n        [\"CG\", 4, (0.600, 1.370, -0.000)],\n        [\"CD2\", 5, (0.889, -1.021, 0.003)],\n        [\"ND1\", 5, (0.744, 1.160, -0.000)],\n        [\"CE1\", 5, (2.030, 0.851, 0.002)],\n        [\"NE2\", 5, (2.145, -0.466, 0.004)],\n    ],\n    \"ILE\": [\n        [\"N\", 0, (-0.493, 1.373, -0.000)],\n        [\"CA\", 0, (0.000, 0.000, 0.000)],\n        [\"C\", 0, (1.527, -0.000, -0.000)],\n        [\"CB\", 0, (-0.536, -0.793, -1.213)],\n        [\"O\", 3, (0.627, 1.062, -0.000)],\n        [\"CG1\", 4, (0.534, 1.437, -0.000)],\n        [\"CG2\", 4, (0.540, -0.785, -1.199)],\n        [\"CD1\", 5, (0.619, 1.391, 0.000)],\n    ],\n    \"LEU\": [\n        [\"N\", 0, (-0.520, 1.363, 0.000)],\n        [\"CA\", 0, (0.000, 0.000, 0.000)],\n        [\"C\", 0, (1.525, -0.000, -0.000)],\n        [\"CB\", 0, (-0.522, -0.773, -1.214)],\n        [\"O\", 3, (0.625, 1.063, -0.000)],\n        [\"CG\", 4, (0.678, 1.371, 0.000)],\n        [\"CD1\", 5, (0.530, 1.430, -0.000)],\n        [\"CD2\", 5, (0.535, -0.774, 1.200)],\n    ],\n    \"LYS\": [\n        [\"N\", 0, (-0.526, 1.362, -0.000)],\n        [\"CA\", 0, (0.000, 0.000, 0.000)],\n        [\"C\", 0, (1.526, 0.000, 0.000)],\n        [\"CB\", 0, (-0.524, -0.778, -1.208)],\n        [\"O\", 3, (0.626, 1.062, -0.000)],\n        [\"CG\", 4, (0.619, 1.390, 0.000)],\n        [\"CD\", 5, (0.559, 1.417, 0.000)],\n        [\"CE\", 6, (0.560, 1.416, 0.000)],\n        [\"NZ\", 7, (0.554, 1.387, 0.000)],\n    ],\n    \"MET\": [\n        [\"N\", 0, (-0.521, 1.364, -0.000)],\n        [\"CA\", 0, (0.000, 0.000, 0.000)],\n        [\"C\", 0, (1.525, 0.000, 0.000)],\n        [\"CB\", 0, (-0.523, -0.776, -1.210)],\n        [\"O\", 3, (0.625, 1.062, -0.000)],\n        [\"CG\", 4, (0.613, 1.391, -0.000)],\n        [\"SD\", 5, (0.703, 1.695, 0.000)],\n        [\"CE\", 6, (0.320, 1.786, -0.000)],\n    ],\n    \"PHE\": [\n        [\"N\", 0, (-0.518, 1.363, 0.000)],\n        [\"CA\", 0, (0.000, 0.000, 0.000)],\n        [\"C\", 0, (1.524, 0.000, -0.000)],\n        [\"CB\", 0, (-0.525, -0.776, -1.212)],\n        [\"O\", 3, (0.626, 1.062, -0.000)],\n        [\"CG\", 4, (0.607, 1.377, 0.000)],\n        [\"CD1\", 5, (0.709, 1.195, -0.000)],\n        [\"CD2\", 5, (0.706, -1.196, 0.000)],\n        [\"CE1\", 5, (2.102, 1.198, -0.000)],\n        [\"CE2\", 5, (2.098, -1.201, -0.000)],\n        [\"CZ\", 5, (2.794, -0.003, -0.001)],\n    ],\n    \"PRO\": [\n        [\"N\", 0, (-0.566, 1.351, -0.000)],\n        [\"CA\", 0, (0.000, 0.000, 0.000)],\n        [\"C\", 0, (1.527, -0.000, 0.000)],\n        [\"CB\", 0, (-0.546, -0.611, -1.293)],\n        [\"O\", 3, (0.621, 1.066, 0.000)],\n        [\"CG\", 4, (0.382, 1.445, 0.0)],\n        # ['CD', 5, (0.427, 1.440, 0.0)],\n        [\"CD\", 5, (0.477, 1.424, 0.0)],  # manually made angle 2 degrees larger\n    ],\n    \"SER\": [\n        [\"N\", 0, (-0.529, 1.360, -0.000)],\n        [\"CA\", 0, (0.000, 0.000, 0.000)],\n        [\"C\", 0, (1.525, -0.000, -0.000)],\n        [\"CB\", 0, (-0.518, -0.777, -1.211)],\n        [\"O\", 3, (0.626, 1.062, -0.000)],\n        [\"OG\", 4, (0.503, 1.325, 0.000)],\n    ],\n    \"THR\": [\n        [\"N\", 0, (-0.517, 1.364, 0.000)],\n        [\"CA\", 0, (0.000, 0.000, 0.000)],\n        [\"C\", 0, (1.526, 0.000, -0.000)],\n        [\"CB\", 0, (-0.516, -0.793, -1.215)],\n        [\"O\", 3, (0.626, 1.062, 0.000)],\n        [\"CG2\", 4, (0.550, -0.718, -1.228)],\n        [\"OG1\", 4, (0.472, 1.353, 0.000)],\n    ],\n    \"TRP\": [\n        [\"N\", 0, (-0.521, 1.363, 0.000)],\n        [\"CA\", 0, (0.000, 0.000, 0.000)],\n        [\"C\", 0, (1.525, -0.000, 0.000)],\n        [\"CB\", 0, (-0.523, -0.776, -1.212)],\n        [\"O\", 3, (0.627, 1.062, 0.000)],\n        [\"CG\", 4, (0.609, 1.370, -0.000)],\n        [\"CD1\", 5, (0.824, 1.091, 0.000)],\n        [\"CD2\", 5, (0.854, -1.148, -0.005)],\n        [\"CE2\", 5, (2.186, -0.678, -0.007)],\n        [\"CE3\", 5, (0.622, -2.530, -0.007)],\n        [\"NE1\", 5, (2.140, 0.690, -0.004)],\n        [\"CH2\", 5, (3.028, -2.890, -0.013)],\n        [\"CZ2\", 5, (3.283, -1.543, -0.011)],\n        [\"CZ3\", 5, (1.715, -3.389, -0.011)],\n    ],\n    \"TYR\": [\n        [\"N\", 0, (-0.522, 1.362, 0.000)],\n        [\"CA\", 0, (0.000, 0.000, 0.000)],\n        [\"C\", 0, (1.524, -0.000, -0.000)],\n        [\"CB\", 0, (-0.522, -0.776, -1.213)],\n        [\"O\", 3, (0.627, 1.062, -0.000)],\n        [\"CG\", 4, (0.607, 1.382, -0.000)],\n        [\"CD1\", 5, (0.716, 1.195, -0.000)],\n        [\"CD2\", 5, (0.713, -1.194, -0.001)],\n        [\"CE1\", 5, (2.107, 1.200, -0.002)],\n        [\"CE2\", 5, (2.104, -1.201, -0.003)],\n        [\"OH\", 5, (4.168, -0.002, -0.005)],\n        [\"CZ\", 5, (2.791, -0.001, -0.003)],\n    ],\n    \"VAL\": [\n        [\"N\", 0, (-0.494, 1.373, -0.000)],\n        [\"CA\", 0, (0.000, 0.000, 0.000)],\n        [\"C\", 0, (1.527, -0.000, -0.000)],\n        [\"CB\", 0, (-0.533, -0.795, -1.213)],\n        [\"O\", 3, (0.627, 1.062, -0.000)],\n        [\"CG1\", 4, (0.540, 1.429, -0.000)],\n        [\"CG2\", 4, (0.533, -0.776, 1.203)],\n    ],\n}\n\n# A list of atoms (excluding hydrogen) for each AA type. PDB naming convention.\nresidue_atoms = {\n    \"ALA\": [\"C\", \"CA\", \"CB\", \"N\", \"O\"],\n    \"ARG\": [\"C\", \"CA\", \"CB\", \"CG\", \"CD\", \"CZ\", \"N\", \"NE\", \"O\", \"NH1\", \"NH2\"],\n    \"ASP\": [\"C\", \"CA\", \"CB\", \"CG\", \"N\", \"O\", \"OD1\", \"OD2\"],\n    \"ASN\": [\"C\", \"CA\", \"CB\", \"CG\", \"N\", \"ND2\", \"O\", \"OD1\"],\n    \"CYS\": [\"C\", \"CA\", \"CB\", \"N\", \"O\", \"SG\"],\n    \"GLU\": [\"C\", \"CA\", \"CB\", \"CG\", \"CD\", \"N\", \"O\", \"OE1\", \"OE2\"],\n    \"GLN\": [\"C\", \"CA\", \"CB\", \"CG\", \"CD\", \"N\", \"NE2\", \"O\", \"OE1\"],\n    \"GLY\": [\"C\", \"CA\", \"N\", \"O\"],\n    \"HIS\": [\"C\", \"CA\", \"CB\", \"CG\", \"CD2\", \"CE1\", \"N\", \"ND1\", \"NE2\", \"O\"],\n    \"ILE\": [\"C\", \"CA\", \"CB\", \"CG1\", \"CG2\", \"CD1\", \"N\", \"O\"],\n    \"LEU\": [\"C\", \"CA\", \"CB\", \"CG\", \"CD1\", \"CD2\", \"N\", \"O\"],\n    \"LYS\": [\"C\", \"CA\", \"CB\", \"CG\", \"CD\", \"CE\", \"N\", \"NZ\", \"O\"],\n    \"MET\": [\"C\", \"CA\", \"CB\", \"CG\", \"CE\", \"N\", \"O\", \"SD\"],\n    \"PHE\": [\"C\", \"CA\", \"CB\", \"CG\", \"CD1\", \"CD2\", \"CE1\", \"CE2\", \"CZ\", \"N\", \"O\"],\n    \"PRO\": [\"C\", \"CA\", \"CB\", \"CG\", \"CD\", \"N\", \"O\"],\n    \"SER\": [\"C\", \"CA\", \"CB\", \"N\", \"O\", \"OG\"],\n    \"THR\": [\"C\", \"CA\", \"CB\", \"CG2\", \"N\", \"O\", \"OG1\"],\n    \"TRP\": [\n        \"C\",\n        \"CA\",\n        \"CB\",\n        \"CG\",\n        \"CD1\",\n        \"CD2\",\n        \"CE2\",\n        \"CE3\",\n        \"CZ2\",\n        \"CZ3\",\n        \"CH2\",\n        \"N\",\n        \"NE1\",\n        \"O\",\n    ],\n    \"TYR\": [\n        \"C\",\n        \"CA\",\n        \"CB\",\n        \"CG\",\n        \"CD1\",\n        \"CD2\",\n        \"CE1\",\n        \"CE2\",\n        \"CZ\",\n        \"N\",\n        \"O\",\n        \"OH\",\n    ],\n    \"VAL\": [\"C\", \"CA\", \"CB\", \"CG1\", \"CG2\", \"N\", \"O\"],\n}\n\n# Naming swaps for ambiguous atom names.\n# Due to symmetries in the amino acids the naming of atoms is ambiguous in\n# 4 of the 20 amino acids.\n# (The LDDT paper lists 7 amino acids as ambiguous, but the naming ambiguities\n# in LEU, VAL and ARG can be resolved by using the 3d constellations of\n# the 'ambiguous' atoms and their neighbours)\n# TODO: ^ interpret this\nresidue_atom_renaming_swaps = {\n    \"ASP\": {\"OD1\": \"OD2\"},\n    \"GLU\": {\"OE1\": \"OE2\"},\n    \"PHE\": {\"CD1\": \"CD2\", \"CE1\": \"CE2\"},\n    \"TYR\": {\"CD1\": \"CD2\", \"CE1\": \"CE2\"},\n}\n\n# Van der Waals radii [Angstroem] of the atoms (from Wikipedia)\nvan_der_waals_radius = {\n    \"C\": 1.7,\n    \"N\": 1.55,\n    \"O\": 1.52,\n    \"S\": 1.8,\n}\n\nBond = collections.namedtuple(\n    \"Bond\", [\"atom1_name\", \"atom2_name\", \"length\", \"stddev\"]\n)\nBondAngle = collections.namedtuple(\n    \"BondAngle\",\n    [\"atom1_name\", \"atom2_name\", \"atom3name\", \"angle_rad\", \"stddev\"],\n)\n\n\n@functools.lru_cache(maxsize=None)\ndef load_stereo_chemical_props() -> Tuple[\n    Mapping[str, List[Bond]],\n    Mapping[str, List[Bond]],\n    Mapping[str, List[BondAngle]],\n]:\n    \"\"\"Load stereo_chemical_props.txt into a nice structure.\n\n    Load literature values for bond lengths and bond angles and translate\n    bond angles into the length of the opposite edge of the triangle\n    (\"residue_virtual_bonds\").\n\n    Returns:\n      residue_bonds:  dict that maps resname --> list of Bond tuples\n      residue_virtual_bonds: dict that maps resname --> list of Bond tuples\n      residue_bond_angles: dict that maps resname --> list of BondAngle tuples\n    \"\"\"\n    # TODO: this file should be downloaded in a setup script\n    stereo_chemical_props_path = \"openfold/resources/stereo_chemical_props.txt\"\n    with open(stereo_chemical_props_path, \"rt\") as f:\n        stereo_chemical_props = f.read()\n    lines_iter = iter(stereo_chemical_props.splitlines())\n    # Load bond lengths.\n    residue_bonds = {}\n    next(lines_iter)  # Skip header line.\n    for line in lines_iter:\n        if line.strip() == \"-\":\n            break\n        bond, resname, length, stddev = line.split()\n        atom1, atom2 = bond.split(\"-\")\n        if resname not in residue_bonds:\n            residue_bonds[resname] = []\n        residue_bonds[resname].append(\n            Bond(atom1, atom2, float(length), float(stddev))\n        )\n    residue_bonds[\"UNK\"] = []\n\n    # Load bond angles.\n    residue_bond_angles = {}\n    next(lines_iter)  # Skip empty line.\n    next(lines_iter)  # Skip header line.\n    for line in lines_iter:\n        if line.strip() == \"-\":\n            break\n        bond, resname, angle_degree, stddev_degree = line.split()\n        atom1, atom2, atom3 = bond.split(\"-\")\n        if resname not in residue_bond_angles:\n            residue_bond_angles[resname] = []\n        residue_bond_angles[resname].append(\n            BondAngle(\n                atom1,\n                atom2,\n                atom3,\n                float(angle_degree) / 180.0 * np.pi,\n                float(stddev_degree) / 180.0 * np.pi,\n            )\n        )\n    residue_bond_angles[\"UNK\"] = []\n\n    def make_bond_key(atom1_name, atom2_name):\n        \"\"\"Unique key to lookup bonds.\"\"\"\n        return \"-\".join(sorted([atom1_name, atom2_name]))\n\n    # Translate bond angles into distances (\"virtual bonds\").\n    residue_virtual_bonds = {}\n    for resname, bond_angles in residue_bond_angles.items():\n        # Create a fast lookup dict for bond lengths.\n        bond_cache = {}\n        for b in residue_bonds[resname]:\n            bond_cache[make_bond_key(b.atom1_name, b.atom2_name)] = b\n        residue_virtual_bonds[resname] = []\n        for ba in bond_angles:\n            bond1 = bond_cache[make_bond_key(ba.atom1_name, ba.atom2_name)]\n            bond2 = bond_cache[make_bond_key(ba.atom2_name, ba.atom3name)]\n\n            # Compute distance between atom1 and atom3 using the law of cosines\n            # c^2 = a^2 + b^2 - 2ab*cos(gamma).\n            gamma = ba.angle_rad\n            length = np.sqrt(\n                bond1.length ** 2\n                + bond2.length ** 2\n                - 2 * bond1.length * bond2.length * np.cos(gamma)\n            )\n\n            # Propagation of uncertainty assuming uncorrelated errors.\n            dl_outer = 0.5 / length\n            dl_dgamma = (\n                2 * bond1.length * bond2.length * np.sin(gamma)\n            ) * dl_outer\n            dl_db1 = (\n                2 * bond1.length - 2 * bond2.length * np.cos(gamma)\n            ) * dl_outer\n            dl_db2 = (\n                2 * bond2.length - 2 * bond1.length * np.cos(gamma)\n            ) * dl_outer\n            stddev = np.sqrt(\n                (dl_dgamma * ba.stddev) ** 2\n                + (dl_db1 * bond1.stddev) ** 2\n                + (dl_db2 * bond2.stddev) ** 2\n            )\n            residue_virtual_bonds[resname].append(\n                Bond(ba.atom1_name, ba.atom3name, length, stddev)\n            )\n\n    return (residue_bonds, residue_virtual_bonds, residue_bond_angles)\n\n\n# Between-residue bond lengths for general bonds (first element) and for Proline\n# (second element).\nbetween_res_bond_length_c_n = [1.329, 1.341]\nbetween_res_bond_length_stddev_c_n = [0.014, 0.016]\n\n# Between-residue cos_angles.\nbetween_res_cos_angles_c_n_ca = [-0.5203, 0.0353]  # degrees: 121.352 +- 2.315\nbetween_res_cos_angles_ca_c_n = [-0.4473, 0.0311]  # degrees: 116.568 +- 1.995\n\n# This mapping is used when we need to store atom data in a format that requires\n# fixed atom data size for every residue (e.g. a numpy array).\natom_types = [\n    \"N\",\n    \"CA\",\n    \"C\",\n    \"CB\",\n    \"O\",\n    \"CG\",\n    \"CG1\",\n    \"CG2\",\n    \"OG\",\n    \"OG1\",\n    \"SG\",\n    \"CD\",\n    \"CD1\",\n    \"CD2\",\n    \"ND1\",\n    \"ND2\",\n    \"OD1\",\n    \"OD2\",\n    \"SD\",\n    \"CE\",\n    \"CE1\",\n    \"CE2\",\n    \"CE3\",\n    \"NE\",\n    \"NE1\",\n    \"NE2\",\n    \"OE1\",\n    \"OE2\",\n    \"CH2\",\n    \"NH1\",\n    \"NH2\",\n    \"OH\",\n    \"CZ\",\n    \"CZ2\",\n    \"CZ3\",\n    \"NZ\",\n    \"OXT\",\n]\natom_order = {atom_type: i for i, atom_type in enumerate(atom_types)}\natom_type_num = len(atom_types)  # := 37.\n\n# A compact atom encoding with 14 columns\n# pylint: disable=line-too-long\n# pylint: disable=bad-whitespace\nrestype_name_to_atom14_names = {\n    \"ALA\": [\"N\", \"CA\", \"C\", \"O\", \"CB\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"],\n    \"ARG\": [\n        \"N\",\n        \"CA\",\n        \"C\",\n        \"O\",\n        \"CB\",\n        \"CG\",\n        \"CD\",\n        \"NE\",\n        \"CZ\",\n        \"NH1\",\n        \"NH2\",\n        \"\",\n        \"\",\n        \"\",\n    ],\n    \"ASN\": [\n        \"N\",\n        \"CA\",\n        \"C\",\n        \"O\",\n        \"CB\",\n        \"CG\",\n        \"OD1\",\n        \"ND2\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n    ],\n    \"ASP\": [\n        \"N\",\n        \"CA\",\n        \"C\",\n        \"O\",\n        \"CB\",\n        \"CG\",\n        \"OD1\",\n        \"OD2\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n    ],\n    \"CYS\": [\"N\", \"CA\", \"C\", \"O\", \"CB\", \"SG\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"],\n    \"GLN\": [\n        \"N\",\n        \"CA\",\n        \"C\",\n        \"O\",\n        \"CB\",\n        \"CG\",\n        \"CD\",\n        \"OE1\",\n        \"NE2\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n    ],\n    \"GLU\": [\n        \"N\",\n        \"CA\",\n        \"C\",\n        \"O\",\n        \"CB\",\n        \"CG\",\n        \"CD\",\n        \"OE1\",\n        \"OE2\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n    ],\n    \"GLY\": [\"N\", \"CA\", \"C\", \"O\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"],\n    \"HIS\": [\n        \"N\",\n        \"CA\",\n        \"C\",\n        \"O\",\n        \"CB\",\n        \"CG\",\n        \"ND1\",\n        \"CD2\",\n        \"CE1\",\n        \"NE2\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n    ],\n    \"ILE\": [\n        \"N\",\n        \"CA\",\n        \"C\",\n        \"O\",\n        \"CB\",\n        \"CG1\",\n        \"CG2\",\n        \"CD1\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n    ],\n    \"LEU\": [\n        \"N\",\n        \"CA\",\n        \"C\",\n        \"O\",\n        \"CB\",\n        \"CG\",\n        \"CD1\",\n        \"CD2\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n    ],\n    \"LYS\": [\n        \"N\",\n        \"CA\",\n        \"C\",\n        \"O\",\n        \"CB\",\n        \"CG\",\n        \"CD\",\n        \"CE\",\n        \"NZ\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n    ],\n    \"MET\": [\n        \"N\",\n        \"CA\",\n        \"C\",\n        \"O\",\n        \"CB\",\n        \"CG\",\n        \"SD\",\n        \"CE\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n    ],\n    \"PHE\": [\n        \"N\",\n        \"CA\",\n        \"C\",\n        \"O\",\n        \"CB\",\n        \"CG\",\n        \"CD1\",\n        \"CD2\",\n        \"CE1\",\n        \"CE2\",\n        \"CZ\",\n        \"\",\n        \"\",\n        \"\",\n    ],\n    \"PRO\": [\"N\", \"CA\", \"C\", \"O\", \"CB\", \"CG\", \"CD\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"],\n    \"SER\": [\"N\", \"CA\", \"C\", \"O\", \"CB\", \"OG\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"],\n    \"THR\": [\n        \"N\",\n        \"CA\",\n        \"C\",\n        \"O\",\n        \"CB\",\n        \"OG1\",\n        \"CG2\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n    ],\n    \"TRP\": [\n        \"N\",\n        \"CA\",\n        \"C\",\n        \"O\",\n        \"CB\",\n        \"CG\",\n        \"CD1\",\n        \"CD2\",\n        \"NE1\",\n        \"CE2\",\n        \"CE3\",\n        \"CZ2\",\n        \"CZ3\",\n        \"CH2\",\n    ],\n    \"TYR\": [\n        \"N\",\n        \"CA\",\n        \"C\",\n        \"O\",\n        \"CB\",\n        \"CG\",\n        \"CD1\",\n        \"CD2\",\n        \"CE1\",\n        \"CE2\",\n        \"CZ\",\n        \"OH\",\n        \"\",\n        \"\",\n    ],\n    \"VAL\": [\n        \"N\",\n        \"CA\",\n        \"C\",\n        \"O\",\n        \"CB\",\n        \"CG1\",\n        \"CG2\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n        \"\",\n    ],\n    \"UNK\": [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"],\n}\n# pylint: enable=line-too-long\n# pylint: enable=bad-whitespace\n\n\n# This is the standard residue order when coding AA type as a number.\n# Reproduce it by taking 3-letter AA codes and sorting them alphabetically.\nrestypes = [\n    \"A\",\n    \"R\",\n    \"N\",\n    \"D\",\n    \"C\",\n    \"Q\",\n    \"E\",\n    \"G\",\n    \"H\",\n    \"I\",\n    \"L\",\n    \"K\",\n    \"M\",\n    \"F\",\n    \"P\",\n    \"S\",\n    \"T\",\n    \"W\",\n    \"Y\",\n    \"V\",\n]\nrestype_order = {restype: i for i, restype in enumerate(restypes)}\nrestype_num = len(restypes)  # := 20.\nunk_restype_index = restype_num  # Catch-all index for unknown restypes.\n\nrestypes_with_x = restypes + [\"X\"]\nrestype_order_with_x = {restype: i for i, restype in enumerate(restypes_with_x)}\n\n\ndef sequence_to_onehot(\n    sequence: str, mapping: Mapping[str, int], map_unknown_to_x: bool = False\n) -> np.ndarray:\n    \"\"\"Maps the given sequence into a one-hot encoded matrix.\n\n    Args:\n      sequence: An amino acid sequence.\n      mapping: A dictionary mapping amino acids to integers.\n      map_unknown_to_x: If True, any amino acid that is not in the mapping will be\n        mapped to the unknown amino acid 'X'. If the mapping doesn't contain\n        amino acid 'X', an error will be thrown. If False, any amino acid not in\n        the mapping will throw an error.\n\n    Returns:\n      A numpy array of shape (seq_len, num_unique_aas) with one-hot encoding of\n      the sequence.\n\n    Raises:\n      ValueError: If the mapping doesn't contain values from 0 to\n        num_unique_aas - 1 without any gaps.\n    \"\"\"\n    num_entries = max(mapping.values()) + 1\n\n    if sorted(set(mapping.values())) != list(range(num_entries)):\n        raise ValueError(\n            \"The mapping must have values from 0 to num_unique_aas-1 \"\n            \"without any gaps. Got: %s\" % sorted(mapping.values())\n        )\n\n    one_hot_arr = np.zeros((len(sequence), num_entries), dtype=np.int32)\n\n    for aa_index, aa_type in enumerate(sequence):\n        if map_unknown_to_x:\n            if aa_type.isalpha() and aa_type.isupper():\n                aa_id = mapping.get(aa_type, mapping[\"X\"])\n            else:\n                raise ValueError(\n                    f\"Invalid character in the sequence: {aa_type}\"\n                )\n        else:\n            aa_id = mapping[aa_type]\n        one_hot_arr[aa_index, aa_id] = 1\n\n    return one_hot_arr\n\n\nrestype_1to3 = {\n    \"A\": \"ALA\",\n    \"R\": \"ARG\",\n    \"N\": \"ASN\",\n    \"D\": \"ASP\",\n    \"C\": \"CYS\",\n    \"Q\": \"GLN\",\n    \"E\": \"GLU\",\n    \"G\": \"GLY\",\n    \"H\": \"HIS\",\n    \"I\": \"ILE\",\n    \"L\": \"LEU\",\n    \"K\": \"LYS\",\n    \"M\": \"MET\",\n    \"F\": \"PHE\",\n    \"P\": \"PRO\",\n    \"S\": \"SER\",\n    \"T\": \"THR\",\n    \"W\": \"TRP\",\n    \"Y\": \"TYR\",\n    \"V\": \"VAL\",\n}\n\n\n# NB: restype_3to1 differs from Bio.PDB.protein_letters_3to1 by being a simple\n# 1-to-1 mapping of 3 letter names to one letter names. The latter contains\n# many more, and less common, three letter names as keys and maps many of these\n# to the same one letter name (including 'X' and 'U' which we don't use here).\nrestype_3to1 = {v: k for k, v in restype_1to3.items()}\n\n# Define a restype name for all unknown residues.\nunk_restype = \"UNK\"\n\nresnames = [restype_1to3[r] for r in restypes] + [unk_restype]\nresname_to_idx = {resname: i for i, resname in enumerate(resnames)}\n\n\n# The mapping here uses hhblits convention, so that B is mapped to D, J and O\n# are mapped to X, U is mapped to C, and Z is mapped to E. Other than that the\n# remaining 20 amino acids are kept in alphabetical order.\n# There are 2 non-amino acid codes, X (representing any amino acid) and\n# \"-\" representing a missing amino acid in an alignment.  The id for these\n# codes is put at the end (20 and 21) so that they can easily be ignored if\n# desired.\nHHBLITS_AA_TO_ID = {\n    \"A\": 0,\n    \"B\": 2,\n    \"C\": 1,\n    \"D\": 2,\n    \"E\": 3,\n    \"F\": 4,\n    \"G\": 5,\n    \"H\": 6,\n    \"I\": 7,\n    \"J\": 20,\n    \"K\": 8,\n    \"L\": 9,\n    \"M\": 10,\n    \"N\": 11,\n    \"O\": 20,\n    \"P\": 12,\n    \"Q\": 13,\n    \"R\": 14,\n    \"S\": 15,\n    \"T\": 16,\n    \"U\": 1,\n    \"V\": 17,\n    \"W\": 18,\n    \"X\": 20,\n    \"Y\": 19,\n    \"Z\": 3,\n    \"-\": 21,\n}\n\n# Partial inversion of HHBLITS_AA_TO_ID.\nID_TO_HHBLITS_AA = {\n    0: \"A\",\n    1: \"C\",  # Also U.\n    2: \"D\",  # Also B.\n    3: \"E\",  # Also Z.\n    4: \"F\",\n    5: \"G\",\n    6: \"H\",\n    7: \"I\",\n    8: \"K\",\n    9: \"L\",\n    10: \"M\",\n    11: \"N\",\n    12: \"P\",\n    13: \"Q\",\n    14: \"R\",\n    15: \"S\",\n    16: \"T\",\n    17: \"V\",\n    18: \"W\",\n    19: \"Y\",\n    20: \"X\",  # Includes J and O.\n    21: \"-\",\n}\n\nrestypes_with_x_and_gap = restypes + [\"X\", \"-\"]\nMAP_HHBLITS_AATYPE_TO_OUR_AATYPE = tuple(\n    restypes_with_x_and_gap.index(ID_TO_HHBLITS_AA[i])\n    for i in range(len(restypes_with_x_and_gap))\n)\n\n\ndef _make_standard_atom_mask() -> np.ndarray:\n    \"\"\"Returns [num_res_types, num_atom_types] mask array.\"\"\"\n    # +1 to account for unknown (all 0s).\n    mask = np.zeros([restype_num + 1, atom_type_num], dtype=np.int32)\n    for restype, restype_letter in enumerate(restypes):\n        restype_name = restype_1to3[restype_letter]\n        atom_names = residue_atoms[restype_name]\n        for atom_name in atom_names:\n            atom_type = atom_order[atom_name]\n            mask[restype, atom_type] = 1\n    return mask\n\n\nSTANDARD_ATOM_MASK = _make_standard_atom_mask()\n\n\n# A one hot representation for the first and second atoms defining the axis\n# of rotation for each chi-angle in each residue.\ndef chi_angle_atom(atom_index: int) -> np.ndarray:\n    \"\"\"Define chi-angle rigid groups via one-hot representations.\"\"\"\n    chi_angles_index = {}\n    one_hots = []\n\n    for k, v in chi_angles_atoms.items():\n        indices = [atom_types.index(s[atom_index]) for s in v]\n        indices.extend([-1] * (4 - len(indices)))\n        chi_angles_index[k] = indices\n\n    for r in restypes:\n        res3 = restype_1to3[r]\n        one_hot = np.eye(atom_type_num)[chi_angles_index[res3]]\n        one_hots.append(one_hot)\n\n    one_hots.append(np.zeros([4, atom_type_num]))  # Add zeros for residue `X`.\n    one_hot = np.stack(one_hots, axis=0)\n    one_hot = np.transpose(one_hot, [0, 2, 1])\n\n    return one_hot\n\n\nchi_atom_1_one_hot = chi_angle_atom(1)\nchi_atom_2_one_hot = chi_angle_atom(2)\n\n# An array like chi_angles_atoms but using indices rather than names.\nchi_angles_atom_indices = [chi_angles_atoms[restype_1to3[r]] for r in restypes]\nchi_angles_atom_indices = tree.map_structure(\n    lambda atom_name: atom_order[atom_name], chi_angles_atom_indices\n)\nchi_angles_atom_indices = np.array(\n    [\n        chi_atoms + ([[0, 0, 0, 0]] * (4 - len(chi_atoms)))\n        for chi_atoms in chi_angles_atom_indices\n    ]\n)\n\n# Mapping from (res_name, atom_name) pairs to the atom's chi group index\n# and atom index within that group.\nchi_groups_for_atom = collections.defaultdict(list)\nfor res_name, chi_angle_atoms_for_res in chi_angles_atoms.items():\n    for chi_group_i, chi_group in enumerate(chi_angle_atoms_for_res):\n        for atom_i, atom in enumerate(chi_group):\n            chi_groups_for_atom[(res_name, atom)].append((chi_group_i, atom_i))\nchi_groups_for_atom = dict(chi_groups_for_atom)\n\n\ndef _make_rigid_transformation_4x4(ex, ey, translation):\n    \"\"\"Create a rigid 4x4 transformation matrix from two axes and transl.\"\"\"\n    # Normalize ex.\n    ex_normalized = ex / np.linalg.norm(ex)\n\n    # make ey perpendicular to ex\n    ey_normalized = ey - np.dot(ey, ex_normalized) * ex_normalized\n    ey_normalized /= np.linalg.norm(ey_normalized)\n\n    # compute ez as cross product\n    eznorm = np.cross(ex_normalized, ey_normalized)\n    m = np.stack(\n        [ex_normalized, ey_normalized, eznorm, translation]\n    ).transpose()\n    m = np.concatenate([m, [[0.0, 0.0, 0.0, 1.0]]], axis=0)\n    return m\n\n\n# create an array with (restype, atomtype) --> rigid_group_idx\n# and an array with (restype, atomtype, coord) for the atom positions\n# and compute affine transformation matrices (4,4) from one rigid group to the\n# previous group\nrestype_atom37_to_rigid_group = np.zeros([21, 37], dtype=np.int)\nrestype_atom37_mask = np.zeros([21, 37], dtype=np.float32)\nrestype_atom37_rigid_group_positions = np.zeros([21, 37, 3], dtype=np.float32)\nrestype_atom14_to_rigid_group = np.zeros([21, 14], dtype=np.int)\nrestype_atom14_mask = np.zeros([21, 14], dtype=np.float32)\nrestype_atom14_rigid_group_positions = np.zeros([21, 14, 3], dtype=np.float32)\nrestype_rigid_group_default_frame = np.zeros([21, 8, 4, 4], dtype=np.float32)\n\n\ndef _make_rigid_group_constants():\n    \"\"\"Fill the arrays above.\"\"\"\n    for restype, restype_letter in enumerate(restypes):\n        resname = restype_1to3[restype_letter]\n        for atomname, group_idx, atom_position in rigid_group_atom_positions[\n            resname\n        ]:\n            atomtype = atom_order[atomname]\n            restype_atom37_to_rigid_group[restype, atomtype] = group_idx\n            restype_atom37_mask[restype, atomtype] = 1\n            restype_atom37_rigid_group_positions[\n                restype, atomtype, :\n            ] = atom_position\n\n            atom14idx = restype_name_to_atom14_names[resname].index(atomname)\n            restype_atom14_to_rigid_group[restype, atom14idx] = group_idx\n            restype_atom14_mask[restype, atom14idx] = 1\n            restype_atom14_rigid_group_positions[\n                restype, atom14idx, :\n            ] = atom_position\n\n    for restype, restype_letter in enumerate(restypes):\n        resname = restype_1to3[restype_letter]\n        atom_positions = {\n            name: np.array(pos)\n            for name, _, pos in rigid_group_atom_positions[resname]\n        }\n\n        # backbone to backbone is the identity transform\n        restype_rigid_group_default_frame[restype, 0, :, :] = np.eye(4)\n\n        # pre-omega-frame to backbone (currently dummy identity matrix)\n        restype_rigid_group_default_frame[restype, 1, :, :] = np.eye(4)\n\n        # phi-frame to backbone\n        mat = _make_rigid_transformation_4x4(\n            ex=atom_positions[\"N\"] - atom_positions[\"CA\"],\n            ey=np.array([1.0, 0.0, 0.0]),\n            translation=atom_positions[\"N\"],\n        )\n        restype_rigid_group_default_frame[restype, 2, :, :] = mat\n\n        # psi-frame to backbone\n        mat = _make_rigid_transformation_4x4(\n            ex=atom_positions[\"C\"] - atom_positions[\"CA\"],\n            ey=atom_positions[\"CA\"] - atom_positions[\"N\"],\n            translation=atom_positions[\"C\"],\n        )\n        restype_rigid_group_default_frame[restype, 3, :, :] = mat\n\n        # chi1-frame to backbone\n        if chi_angles_mask[restype][0]:\n            base_atom_names = chi_angles_atoms[resname][0]\n            base_atom_positions = [\n                atom_positions[name] for name in base_atom_names\n            ]\n            mat = _make_rigid_transformation_4x4(\n                ex=base_atom_positions[2] - base_atom_positions[1],\n                ey=base_atom_positions[0] - base_atom_positions[1],\n                translation=base_atom_positions[2],\n            )\n            restype_rigid_group_default_frame[restype, 4, :, :] = mat\n\n        # chi2-frame to chi1-frame\n        # chi3-frame to chi2-frame\n        # chi4-frame to chi3-frame\n        # luckily all rotation axes for the next frame start at (0,0,0) of the\n        # previous frame\n        for chi_idx in range(1, 4):\n            if chi_angles_mask[restype][chi_idx]:\n                axis_end_atom_name = chi_angles_atoms[resname][chi_idx][2]\n                axis_end_atom_position = atom_positions[axis_end_atom_name]\n                mat = _make_rigid_transformation_4x4(\n                    ex=axis_end_atom_position,\n                    ey=np.array([-1.0, 0.0, 0.0]),\n                    translation=axis_end_atom_position,\n                )\n                restype_rigid_group_default_frame[\n                    restype, 4 + chi_idx, :, :\n                ] = mat\n\n\n_make_rigid_group_constants()\n\n\ndef make_atom14_dists_bounds(\n    overlap_tolerance=1.5, bond_length_tolerance_factor=15\n):\n    \"\"\"compute upper and lower bounds for bonds to assess violations.\"\"\"\n    restype_atom14_bond_lower_bound = np.zeros([21, 14, 14], np.float32)\n    restype_atom14_bond_upper_bound = np.zeros([21, 14, 14], np.float32)\n    restype_atom14_bond_stddev = np.zeros([21, 14, 14], np.float32)\n    residue_bonds, residue_virtual_bonds, _ = load_stereo_chemical_props()\n    for restype, restype_letter in enumerate(restypes):\n        resname = restype_1to3[restype_letter]\n        atom_list = restype_name_to_atom14_names[resname]\n\n        # create lower and upper bounds for clashes\n        for atom1_idx, atom1_name in enumerate(atom_list):\n            if not atom1_name:\n                continue\n            atom1_radius = van_der_waals_radius[atom1_name[0]]\n            for atom2_idx, atom2_name in enumerate(atom_list):\n                if (not atom2_name) or atom1_idx == atom2_idx:\n                    continue\n                atom2_radius = van_der_waals_radius[atom2_name[0]]\n                lower = atom1_radius + atom2_radius - overlap_tolerance\n                upper = 1e10\n                restype_atom14_bond_lower_bound[\n                    restype, atom1_idx, atom2_idx\n                ] = lower\n                restype_atom14_bond_lower_bound[\n                    restype, atom2_idx, atom1_idx\n                ] = lower\n                restype_atom14_bond_upper_bound[\n                    restype, atom1_idx, atom2_idx\n                ] = upper\n                restype_atom14_bond_upper_bound[\n                    restype, atom2_idx, atom1_idx\n                ] = upper\n\n        # overwrite lower and upper bounds for bonds and angles\n        for b in residue_bonds[resname] + residue_virtual_bonds[resname]:\n            atom1_idx = atom_list.index(b.atom1_name)\n            atom2_idx = atom_list.index(b.atom2_name)\n            lower = b.length - bond_length_tolerance_factor * b.stddev\n            upper = b.length + bond_length_tolerance_factor * b.stddev\n            restype_atom14_bond_lower_bound[\n                restype, atom1_idx, atom2_idx\n            ] = lower\n            restype_atom14_bond_lower_bound[\n                restype, atom2_idx, atom1_idx\n            ] = lower\n            restype_atom14_bond_upper_bound[\n                restype, atom1_idx, atom2_idx\n            ] = upper\n            restype_atom14_bond_upper_bound[\n                restype, atom2_idx, atom1_idx\n            ] = upper\n            restype_atom14_bond_stddev[restype, atom1_idx, atom2_idx] = b.stddev\n            restype_atom14_bond_stddev[restype, atom2_idx, atom1_idx] = b.stddev\n    return {\n        \"lower_bound\": restype_atom14_bond_lower_bound,  # shape (21,14,14)\n        \"upper_bound\": restype_atom14_bond_upper_bound,  # shape (21,14,14)\n        \"stddev\": restype_atom14_bond_stddev,  # shape (21,14,14)\n    }\n\n\nrestype_atom14_ambiguous_atoms = np.zeros((21, 14), dtype=np.float32)\nrestype_atom14_ambiguous_atoms_swap_idx = np.tile(\n    np.arange(14, dtype=np.int), (21, 1)\n)\n\n\ndef _make_atom14_ambiguity_feats():\n    for res, pairs in residue_atom_renaming_swaps.items():\n        res_idx = restype_order[restype_3to1[res]]\n        for atom1, atom2 in pairs.items():\n            atom1_idx = restype_name_to_atom14_names[res].index(atom1)\n            atom2_idx = restype_name_to_atom14_names[res].index(atom2)\n            restype_atom14_ambiguous_atoms[res_idx, atom1_idx] = 1\n            restype_atom14_ambiguous_atoms[res_idx, atom2_idx] = 1\n            restype_atom14_ambiguous_atoms_swap_idx[\n                res_idx, atom1_idx\n            ] = atom2_idx\n            restype_atom14_ambiguous_atoms_swap_idx[\n                res_idx, atom2_idx\n            ] = atom1_idx\n\n\n_make_atom14_ambiguity_feats()\n", "meta": {"hexsha": "0a289d27b6f28daccbed1ba4c791c79462f64218", "size": 39486, "ext": "py", "lang": "Python", "max_stars_repo_path": "openfold/np/residue_constants.py", "max_stars_repo_name": "yuzhiguo07/openfold", "max_stars_repo_head_hexsha": "5fb0f074066387b9969578b8bf68f7e046c778af", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-16T17:02:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T17:02:10.000Z", "max_issues_repo_path": "openfold/np/residue_constants.py", "max_issues_repo_name": "yuzhiguo07/openfold", "max_issues_repo_head_hexsha": "5fb0f074066387b9969578b8bf68f7e046c778af", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openfold/np/residue_constants.py", "max_forks_repo_name": "yuzhiguo07/openfold", "max_forks_repo_head_hexsha": "5fb0f074066387b9969578b8bf68f7e046c778af", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2806748466, "max_line_length": 82, "alphanum_fraction": 0.4883503014, "include": true, "reason": "import numpy", "num_tokens": 13852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.18902097608368895}}
{"text": "\"\"\"\n\n:mod:`meshes` -- Discretization\n===============================\n\nEverything related to meshes appropriate for the multigrid solver.\n\n\"\"\"\n# Copyright 2018-2020 The emg3d Developers.\n#\n# This file is part of emg3d.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License.  You may obtain a copy\n# of the License at\n#\n#     https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the\n# License for the specific language governing permissions and limitations under\n# the License.\n\n\nimport numpy as np\nfrom copy import deepcopy\nfrom scipy import optimize\n\n__all__ = ['TensorMesh', 'get_hx_h0', 'get_cell_numbers', 'get_stretched_h',\n           'get_domain', 'get_hx']\n\n\nclass TensorMesh:\n    \"\"\"Rudimentary mesh for multigrid calculation.\n\n    The tensor-mesh :class:`discretize.TensorMesh` is a powerful tool,\n    including sophisticated mesh-generation possibilities in 1D, 2D, and 3D,\n    plotting routines, and much more. However, in the multigrid solver we have\n    to generate a mesh at each level, many times over and over again, and we\n    only need a very limited set of attributes. This tensor-mesh class provides\n    all required attributes. All attributes here are the same as their\n    counterparts in :class:`discretize.TensorMesh` (both in name and value).\n\n    .. warning::\n        This is a slimmed-down version of :class:`discretize.TensorMesh`, meant\n        principally for internal use by the multigrid modeller. It is highly\n        recommended to use :class:`discretize.TensorMesh` to create the input\n        meshes instead of this class. There are no input-checks carried out\n        here, and there is only one accepted input format for `h` and `x0`.\n\n\n    Parameters\n    ----------\n    h : list of three ndarrays\n        Cell widths in [x, y, z] directions.\n\n    x0 : ndarray of dimension (3, )\n        Origin (x, y, z).\n\n    \"\"\"\n\n    def __init__(self, h, x0):\n        \"\"\"Initialize the mesh.\"\"\"\n        self.x0 = x0\n\n        # Width of cells.\n        self.hx = h[0]\n        self.hy = h[1]\n        self.hz = h[2]\n\n        # Cell related properties.\n        self.nCx = int(self.hx.size)\n        self.nCy = int(self.hy.size)\n        self.nCz = int(self.hz.size)\n        self.vnC = np.array([self.hx.size, self.hy.size, self.hz.size])\n        self.nC = int(self.vnC.prod())\n        self.vectorCCx = np.r_[0, self.hx[:-1].cumsum()]+self.hx*0.5+self.x0[0]\n        self.vectorCCy = np.r_[0, self.hy[:-1].cumsum()]+self.hy*0.5+self.x0[1]\n        self.vectorCCz = np.r_[0, self.hz[:-1].cumsum()]+self.hz*0.5+self.x0[2]\n\n        # Node related properties.\n        self.nNx = self.nCx + 1\n        self.nNy = self.nCy + 1\n        self.nNz = self.nCz + 1\n        self.vnN = np.array([self.nNx, self.nNy, self.nNz], dtype=int)\n        self.nN = int(self.vnN.prod())\n        self.vectorNx = np.r_[0., self.hx.cumsum()] + self.x0[0]\n        self.vectorNy = np.r_[0., self.hy.cumsum()] + self.x0[1]\n        self.vectorNz = np.r_[0., self.hz.cumsum()] + self.x0[2]\n\n        # Edge related properties.\n        self.vnEx = np.array([self.nCx, self.nNy, self.nNz], dtype=int)\n        self.vnEy = np.array([self.nNx, self.nCy, self.nNz], dtype=int)\n        self.vnEz = np.array([self.nNx, self.nNy, self.nCz], dtype=int)\n        self.nEx = int(self.vnEx.prod())\n        self.nEy = int(self.vnEy.prod())\n        self.nEz = int(self.vnEz.prod())\n        self.vnE = np.array([self.nEx, self.nEy, self.nEz], dtype=int)\n        self.nE = int(self.vnE.sum())\n\n    def __repr__(self):\n        \"\"\"Simple representation.\"\"\"\n        return (f\"TensorMesh: {self.nCx} x {self.nCy} x {self.nCz} \"\n                f\"({self.nC:,})\")\n\n    def copy(self):\n        \"\"\"Return a copy of the TensorMesh.\"\"\"\n        return TensorMesh.from_dict(self.to_dict(True))\n\n    def to_dict(self, copy=False):\n        \"\"\"Store the necessary information of the TensorMesh in a dict.\"\"\"\n        out = {'hx': self.hx, 'hy': self.hy, 'hz': self.hz, 'x0': self.x0,\n               '__class__': self.__class__.__name__}\n        if copy:\n            return deepcopy(out)\n        else:\n            return out\n\n    @classmethod\n    def from_dict(cls, inp):\n        \"\"\"Convert dictionary into :class:`TensorMesh` instance.\n\n        Parameters\n        ----------\n        inp : dict\n            Dictionary as obtained from :func:`TensorMesh.to_dict`.\n            The dictionary needs the keys `hx`, `hy`, `hz`, and `x0`.\n\n        Returns\n        -------\n        obj : :class:`TensorMesh` instance\n\n        \"\"\"\n        try:\n            return cls(h=[inp['hx'], inp['hy'], inp['hz']], x0=inp['x0'])\n        except KeyError as e:\n            print(f\"* ERROR   :: Variable {e} missing in `inp`.\")\n            raise\n\n    @property\n    def vol(self):\n        \"\"\"Construct cell volumes of the 3D model as 1D array.\"\"\"\n        if getattr(self, '_vol', None) is None:\n            self._vol = (self.hx[None, None, :]*self.hy[None, :, None] *\n                         self.hz[:, None, None]).ravel()\n        return self._vol\n\n\ndef get_hx_h0(freq, res, domain, fixed=0., possible_nx=None, min_width=None,\n              pps=3, alpha=None, max_domain=100000., raise_error=True, verb=1,\n              return_info=False):\n    r\"\"\"Return cell widths and origin for given parameters.\n\n    Returns cell widths for the provided frequency, resistivity, domain extent,\n    and other parameters using a flexible amount of cells. See input parameters\n    for more details. A maximum of three hard/fixed boundaries can be provided\n    (one of which is the grid center).\n\n    The minimum cell width is calculated through :math:`\\delta/\\rm{pps}`, where\n    the skin depth is given by :math:`\\delta = 503.3 \\sqrt{\\rho/f}`, and the\n    parameter `pps` stands for 'points-per-skindepth'. The minimum cell width\n    can be restricted with the parameter `min_width`.\n\n    The actual calculation domain adds a buffer zone around the (survey)\n    domain. The thickness of the buffer is six times the skin depth. The field\n    is basically zero after two wavelengths. A wavelength is\n    :math:`2\\pi\\delta`, hence roughly 6 times the skin depth. Taking a factor 6\n    gives therefore almost two wavelengths, as the field travels to the\n    boundary and back. The actual buffer thickness can be steered with the\n    `res` parameter.\n\n    One has to take into account that the air is very resistive, which has to\n    be considered not just in the vertical direction, but also in the\n    horizontal directions, as the airwave will bounce back from the sides\n    otherwise. In the marine case this issue reduces with increasing water\n    depth.\n\n\n    See Also\n    --------\n    get_stretched_h : Get `hx` for a fixed number `nx` and within a fixed\n                      domain.\n\n\n    Parameters\n    ----------\n\n    freq : float\n        Frequency (Hz) to calculate the skin depth. The skin depth is a concept\n        defined in the frequency domain. If a negative frequency is provided,\n        it is assumed that the calculation is carried out in the Laplace\n        domain. To calculate the skin depth, the value of `freq` is then\n        multiplied by :math:`-2\\pi`, to simulate the closest\n        frequency-equivalent.\n\n    res : float or list\n        Resistivity (Ohm m) to calculate the skin depth. The skin depth is\n        used to calculate the minimum cell width and the boundary thicknesses.\n        Up to three resistivities can be provided:\n\n        - float: Same resistivity for everything;\n        - [min_width, boundaries];\n        - [min_width, left boundary, right boundary].\n\n    domain : list\n        Contains the survey-domain limits [min, max]. The actual calculation\n        domain consists of this domain plus a buffer zone around it, which\n        depends on frequency and resistivity.\n\n    fixed : list, optional\n        Fixed boundaries, one, two, or maximum three values. The grid is\n        centered around the first value. Hence it is the center location with\n        the smallest cell. Two more fixed boundaries can be added, at most one\n        on each side of the first one.\n        Default is 0.\n\n    possible_nx : list, optional\n        List of possible numbers of cells. See :func:`get_cell_numbers`.\n        Default is ``get_cell_numbers(500, 5, 3)``, which corresponds to\n        [16, 24, 32, 40, 48, 64, 80, 96, 128, 160, 192, 256, 320, 384].\n\n    min_width : float, list or None, optional\n        Minimum cell width restriction:\n\n        - None : No restriction;\n        - float : Fixed to this value, ignoring skin depth and `pps`.\n        - list [min, max] : Lower and upper bounds.\n\n        Default is None.\n\n    pps : int, optional\n        Points per skindepth; minimum cell width is calculated via\n        `dmin = skindepth/pps`.\n        Default = 3.\n\n    alpha : list, optional\n        Maximum alpha and step size to find a good alpha. The first value is\n        the maximum alpha of the survey domain, the second value is the maximum\n        alpha for the buffer zone, and the third value is the step size.\n        Default = [1, 1.5, .01], hence no stretching within the survey domain\n        and a maximum stretching of 1.5 in the buffer zone; step size is 0.01.\n\n    max_domain : float, optional\n        Maximum calculation domain from fixed[0] (usually source position).\n        Default is 100,000.\n\n    raise_error : bool, optional\n        If True, an error is raised if no suitable grid is found. Otherwise it\n        just prints a message and returns None's.\n        Default is True.\n\n    verb : int, optional\n        Verbosity, 0 or 1.\n        Default = 1.\n\n    return_info : bool\n        If True, a dictionary is returned with some grid info (min and max\n        cell width and alpha).\n\n\n    Returns\n    -------\n    hx : ndarray\n        Cell widths of mesh.\n\n    x0 : float\n        Origin of the mesh.\n\n    info : dict\n        Dictionary with mesh info; only if ``return_info=True``.\n\n        Keys:\n\n        - `dmin`: Minimum cell width;\n        - `dmax`: Maximum cell width;\n        - `amin`: Minimum alpha;\n        - `amax`: Maximum alpha.\n\n    \"\"\"\n    # Get variables with default lists:\n    if alpha is None:\n        alpha = [1, 1.5, 0.01]\n    if possible_nx is None:\n        possible_nx = get_cell_numbers(500, 5, 3)\n\n    # Cast resistivity value(s).\n    res = np.array(res, ndmin=1)\n    if res.size == 1:\n        res_arr = np.array([res[0], res[0], res[0]])\n    elif res.size == 2:\n        res_arr = np.array([res[0], res[1], res[1]])\n    else:\n        res_arr = np.array([res[0], res[1], res[2]])\n\n    # Cast and check fixed.\n    fixed = np.array(fixed, ndmin=1)\n    if fixed.size > 2:\n\n        # Check length.\n        if fixed.size > 3:\n            print(\"\\n* ERROR   :: Maximum three fixed boundaries permitted.\\n\"\n                  f\"             Provided: {fixed.size}.\")\n            raise ValueError(\"Wrong input for fixed\")\n\n        # Sort second and third, so it doesn't matter how it was provided.\n        fixed = np.array([fixed[0], max(fixed[1:]), min(fixed[1:])])\n\n        # Check side.\n        if np.sign(np.diff(fixed[:2])) == np.sign(np.diff(fixed[::2])):\n            print(\"\\n* ERROR   :: 2nd and 3rd fixed boundaries have to be \"\n                  \"left and right of the first one.\\n             \"\n                  f\"Provided: [{fixed[0]}, {fixed[1]}, {fixed[2]}]\")\n            raise ValueError(\"Wrong input for fixed\")\n\n    # Calculate skin depth.\n    skind = 503.3*np.sqrt(res_arr/abs(freq))\n    if freq < 0:  # For Laplace-domain calculations.\n        skind /= np.sqrt(2*np.pi)\n\n    # Minimum cell width.\n    dmin = skind[0]/pps\n    if min_width is not None:  # Respect user input.\n        min_width = np.array(min_width, ndmin=1)\n        if min_width.size == 1:\n            dmin = min_width\n        else:\n            dmin = np.clip(dmin, *min_width)\n\n    # Survey domain; contains all sources and receivers.\n    domain = np.array(domain, dtype=float)\n\n    # Calculation domain; big enough to avoid boundary effects.\n    # To avoid boundary effects we want the signal to travel two wavelengths\n    # from the source to the boundary and back to the receiver.\n    # => 2*pi*sd ~ 6.3*sd = one wavelength => signal is ~ 0.2 %.\n    # Two wavelengths we can safely assume it is zero.\n    #\n    # The air does not follow the concept of skin depth, as it is a wave rather\n    # than diffusion. For this is the factor `max_domain`, which restricts\n    # the domain in each direction to this value from the center.\n\n    # (a) Source to edges of domain.\n    dist_in_domain = abs(domain - fixed[0])\n\n    # (b) Two wavelengths.\n    two_lambda = skind[1:]*4*np.pi\n\n    # (c) Required buffer, additional to domain.\n    dist_buff = np.max([np.zeros(2), (two_lambda - dist_in_domain)/2], axis=0)\n\n    # (d) Add buffer to domain.\n    calc_domain = np.array([domain[0]-dist_buff[0], domain[1]+dist_buff[1]])\n\n    # (e) Restrict total domain to max_domain.\n    calc_domain[0] = max(calc_domain[0], fixed[0]-max_domain)\n    calc_domain[1] = min(calc_domain[1], fixed[0]+max_domain)\n\n    # Initiate flag if terminated.\n    finished = False\n\n    # Initiate alpha variables for survey and calculation domains.\n    sa, ca = 1.0, 1.0\n\n    # Loop over possible cell numbers from small to big.\n    for nx in np.unique(possible_nx):\n\n        # Loop over possible alphas for domain.\n        for sa in np.arange(1.0, alpha[0]+alpha[2]/2, alpha[2]):\n\n            # Get current stretched grid cell sizes.\n            thxl = dmin*sa**np.arange(nx)  # Left of origin.\n            thxr = dmin*sa**np.arange(nx)  # Right of origin.\n\n            # 0. Adjust stretching for fixed boundaries.\n            if fixed.size > 1:  # Move mesh to first fixed boundary.\n                t_nx = np.r_[fixed[0], fixed[0]+np.cumsum(thxr)]\n                ii = np.argmin(abs(t_nx-fixed[1]))\n                thxr *= abs(fixed[1]-fixed[0])/np.sum(thxr[:ii])\n\n            if fixed.size > 2:  # Move mesh to second fixed boundary.\n                t_nx = np.r_[fixed[0], fixed[0]-np.cumsum(thxl)]\n                ii = np.argmin(abs(t_nx-fixed[2]))\n                thxl *= abs(fixed[2]-fixed[0])/np.sum(thxl[:ii])\n\n            # 1. Fill from center to left domain.\n            nl = np.sum((fixed[0]-np.cumsum(thxl)) > domain[0])+1\n\n            # 2. Fill from center to right domain.\n            nr = np.sum((fixed[0]+np.cumsum(thxr)) < domain[1])+1\n\n            # 3. Get remaining number of cells and check termination criteria.\n            nsdc = nl+nr  # Number of domain cells.\n            nx_remain = nx-nsdc\n\n            # Not good, try next.\n            if nx_remain <= 0:\n                continue\n\n            # Create the current hx-array.\n            hx = np.r_[thxl[:nl][::-1], thxr[:nr]]\n            hxo = np.r_[thxl[:nl][::-1], thxr[:nr]]\n\n            # Get actual domain:\n            asurv_domain = [fixed[0]-np.sum(thxl[:nl]),\n                            fixed[0]+np.sum(thxr[:nr])]\n            x0 = float(fixed[0]-np.sum(thxl[:nl]))\n\n            # Get actual stretching (differs in case of fixed layers).\n            sa_adj = np.max([hx[1:]/hx[:-1], hx[:-1]/hx[1:]])\n\n            # Loop over possible alphas for calc_domain.\n            for ca in np.arange(sa, alpha[1]+alpha[2]/2, alpha[2]):\n\n                # 4. Fill to left calc_domain.\n                thxl = hx[0]*ca**np.arange(1, nx_remain+1)\n                nl = np.sum((asurv_domain[0]-np.cumsum(thxl)) >\n                            calc_domain[0])+1\n\n                # 5. Fill to right calc_domain.\n                thxr = hx[-1]*ca**np.arange(1, nx_remain+1)\n                nr = np.sum((asurv_domain[1]+np.cumsum(thxr)) <\n                            calc_domain[1])+1\n\n                # 6. Get remaining number of cells and check termination\n                # criteria.\n                ncdc = nl+nr  # Number of calc_domain cells.\n                nx_remain2 = nx-nsdc-ncdc\n\n                if nx_remain2 < 0:  # Not good, try next.\n                    continue\n\n                # Create hx-array.\n                nl += int(np.floor(nx_remain2/2))  # If uneven, add one cell\n                nr += int(np.ceil(nx_remain2/2))   # more on the right.\n                hx = np.r_[thxl[:nl][::-1], hx, thxr[:nr]]\n\n                # Calculate origin.\n                x0 = float(asurv_domain[0]-np.sum(thxl[:nl]))\n\n                # Mark it as finished and break out of the loop.\n                finished = True\n                break\n\n            if finished:\n                break\n\n        if finished:\n            break\n\n    # Check finished and print info about found grid.\n    if not finished:\n        # Throw message if no solution was found.\n        print(\"\\n* ERROR   :: No suitable grid found; relax your criteria.\\n\")\n        if raise_error:\n            raise ArithmeticError(\"No grid found!\")\n        else:\n            hx, x0 = None, None\n\n    elif verb > 0:\n        print(f\"   Skin depth \", end=\"\")\n        if res.size == 1:\n            print(f\"         [m] : {skind[0]:.0f}\")\n        elif res.size == 2:\n            print(f\"(m/l-r)  [m] : {skind[0]:.0f} / {skind[1]:.0f}\")\n        else:\n            print(f\"(m/l/r)  [m] : {skind[0]:.0f} / {skind[1]:.0f} / \"\n                  f\"{skind[2]:.0f}\")\n        print(f\"   Survey domain       [m] : {domain[0]:.0f} - \"\n              f\"{domain[1]:.0f}\")\n        print(f\"   Calculation domain  [m] : {calc_domain[0]:.0f} - \"\n              f\"{calc_domain[1]:.0f}\")\n        print(f\"   Final extent        [m] : {x0:.0f} - \"\n              f\"{x0+np.sum(hx):.0f}\")\n        extstr = f\"   Min/max cell width  [m] : {min(hx):.0f} / \"\n        alstr = f\"   Alpha survey\"\n        nrstr = \"   Number of cells \"\n        if not np.isclose(sa, sa_adj):\n            sastr = f\"{sa:.3f} ({sa_adj:.3f})\"\n        else:\n            sastr = f\"{sa:.3f}\"\n        print(extstr+f\"{max(hxo):.0f} / {max(hx):.0f}\")\n        print(alstr+f\"/calc       : {sastr} / {ca:.3f}\")\n        print(nrstr+f\"(s/c/r) : {nx} ({nsdc}/{ncdc}/{nx_remain2})\")\n        print()\n\n    if return_info:\n        if not fixed.size > 1:\n            sa_adj = sa\n\n        info = {'dmin': dmin,\n                'dmax': np.nanmax(hx),\n                'amin': np.nanmin([ca, sa, sa_adj]),\n                'amax': np.nanmax([ca, sa, sa_adj])}\n\n        return hx, x0, info\n    else:\n        return hx, x0\n\n\ndef get_cell_numbers(max_nr, max_prime=5, min_div=3):\n    r\"\"\"Returns 'good' cell numbers for the multigrid method.\n\n    'Good' cell numbers are numbers which can be divided by 2 as many times as\n    possible. At the end there will be a low prime number.\n\n    The function adds all numbers :math:`p 2^n \\leq M` for :math:`p={2, 3, ...,\n    p_\\text{max}}` and :math:`n={n_\\text{min}, n_\\text{min}+1, ..., \\infty}`;\n    :math:`M, p_\\text{max}, n_\\text{min}` correspond to `max_nr`, `max_prime`,\n    and `min_div`, respectively.\n\n\n    Parameters\n    ----------\n    max_nr : int\n        Maximum number of cells.\n\n    max_prime : int\n        Highest permitted prime number p for p*2^n. {2, 3, 5, 7} are good upper\n        limits in order to avoid too big lowest grids in the multigrid method.\n        Default is 5.\n\n    min_div : int\n        Minimum times the number can be divided by two.\n        Default is 3.\n\n\n    Returns\n    -------\n    numbers : array\n        Array containing all possible cell numbers from lowest to highest.\n\n    \"\"\"\n    # Primes till 20.\n    primes = np.array([2, 3, 5, 7, 11, 13, 17, 19])\n\n    # Sanity check; 19 is already ridiculously high.\n    if max_prime > primes[-1]:\n        print(f\"* ERROR   :: Highest prime is {max_prime}, \"\n              \"please use a value < 20.\")\n        raise ValueError(\"Highest prime too high\")\n\n    # Restrict to max_prime.\n    primes = primes[primes <= max_prime]\n\n    # Get possible values.\n    # Currently restricted to prime*2**30 (for prime=2 => 1,073,741,824 cells).\n    numbers = primes[:, None]*2**np.arange(min_div, 30)\n\n    # Get unique values.\n    numbers = np.unique(numbers)\n\n    # Restrict to max_nr and return.\n    return numbers[numbers <= max_nr]\n\n\ndef get_stretched_h(min_width, domain, nx, x0=0, x1=None, resp_domain=False):\n    \"\"\"Return cell widths for a stretched grid within the domain.\n\n    Returns `nx` cell widths within `domain`, where the minimum cell width is\n    `min_width`. The cells are not stretched within `x0` and `x1`, and outside\n    uses a power-law stretching. The actual stretching factor and the number of\n    cells left and right of `x0` and `x1` are find in a minimization process.\n\n    The domain is not completely respected. The starting point of the domain\n    is, but the endpoint of the domain might slightly shift (this is more\n    likely the case for small `nx`, for big `nx` the shift should be small).\n    The new endpoint can be obtained with ``domain[0]+np.sum(hx)``. If you want\n    the domain to be respected absolutely, set ``resp_domain=True``. However,\n    be aware that this will introduce one stretch-factor which is different\n    from the other stretch factors, to accommodate the restriction. This\n    one-off factor is between the left- and right-side of `x0`, or, if `x1` is\n    provided, just after `x1`.\n\n\n    See Also\n    --------\n    get_hx_x0 : Get `hx` and `x0` for a flexible number of `nx` with\n                given bounds.\n\n\n    Parameters\n    ----------\n\n    min_width : float\n        Minimum cell width. If x1 is provided, the actual minimum cell width\n        might be smaller than min_width.\n\n    domain : list\n        [start, end] of model domain.\n\n    nx : int\n        Number of cells.\n\n    x0 : float\n        Center of the grid. `x0` is restricted to `domain`.\n        Default is 0.\n\n    x1 : float\n        If provided, then no stretching is applied between `x0` and `x1`. The\n        non-stretched part starts at `x0` and stops at the first possible\n        location at or after `x1`. `x1` is restricted to `domain`. This will\n        min_width so that an integer number of cells fit within x0 and x1.\n\n    resp_domain : bool\n        If False (default), then the domain-end might shift slightly to assure\n        that the same stretching factor is applied throughout. If set to True,\n        however, the domain is respected absolutely. This will introduce one\n        stretch-factor which is different from the other stretch factors, to\n        accommodate the restriction. This one-off factor is between the left-\n        and right-side of `x0`, or, if `x1` is provided, just after `x1`.\n\n\n    Returns\n    -------\n    hx : ndarray\n        Cell widths of mesh.\n\n    \"\"\"\n\n    # Cast to arrays\n    domain = np.array(domain, dtype=float)\n    x0 = np.array(x0, dtype=float)\n    x0 = np.clip(x0, *domain)  # Restrict to model domain\n    min_width = np.array(min_width, dtype=float)\n    if x1 is not None:\n        x1 = np.array(x1, dtype=float)\n        x1 = np.clip(x1, *domain)  # Restrict to model domain\n\n    # If x1 is provided (a part is not stretched)\n    if x1 is not None:\n\n        # Store original values\n        xlim_orig = domain.copy()\n        nx_orig = int(nx)\n        x0_orig = x0.copy()\n        h_min_orig = min_width.copy()\n\n        # Get number of non-stretched cells\n        n_nos = int(np.ceil((x1-x0)/min_width))\n\n        # Re-calculate min_width to fit with x0-x1-limits:\n        min_width = (x1-x0)/n_nos\n\n        # Subtract one cell, because the standard scheme provides one\n        # min_width-cell.\n        n_nos -= 1\n\n        # Reset x0, because the first min_width comes from normal scheme\n        x0 += min_width\n\n        # Reset xmax for normal scheme\n        domain[1] -= n_nos*min_width\n\n        # Reset nx for normal scheme\n        nx -= n_nos\n\n        # If there are not enough points reset to standard procedure. The limit\n        # of five is arbitrary. However, nx should be much bigger than five\n        # anyways, otherwise stretched grid doesn't make sense.\n        if nx <= 5:\n            print(\"Warning :: Not enough points for non-stretched part,\"\n                  \"ignoring therefore `x1`.\")\n            domain = xlim_orig\n            nx = nx_orig\n            x0 = x0_orig\n            x1 = None\n            min_width = h_min_orig\n\n    # Get stretching factor (a = 1+alpha).\n    if min_width == 0 or min_width > np.diff(domain)/nx:\n        # If min_width is bigger than the domain-extent divided by nx, no\n        # stretching is required at all.\n        alpha = 0\n    else:\n\n        # Wrap _get_dx into a minimization function to call with fsolve.\n        def find_alpha(alpha, min_width, args):\n            \"\"\"Find alpha such that min(hx) = min_width.\"\"\"\n            return min(get_hx(alpha, *args))/min_width-1\n\n        # Search for best alpha, must be at least 0\n        args = (domain, nx, x0)\n        alpha = max(0, optimize.fsolve(find_alpha, 0.02, (min_width, args)))\n\n    # With alpha get actual cell spacing with `resp_domain` to respect the\n    # users decision.\n    hx = get_hx(alpha, domain, nx, x0, resp_domain)\n\n    # Add the non-stretched center if x1 is provided\n    if x1 is not None:\n        hx = np.r_[hx[: np.argmin(hx)], np.ones(n_nos)*min_width,\n                   hx[np.argmin(hx):]]\n\n    # Print warning min_width could not be respected.\n    if abs(hx.min() - min_width) > 0.1:\n        print(f\"Warning :: Minimum cell width ({np.round(hx.min(), 2)} m) is \"\n              \"below `min_width`, because `nx` is too big for `domain`.\")\n\n    return hx\n\n\ndef get_domain(x0=0, freq=1, res=0.3, limits=None, min_width=None,\n               fact_min=0.2, fact_neg=5, fact_pos=None):\n    r\"\"\"Get domain extent and minimum cell width as a function of skin depth.\n\n    Returns the extent of the calculation domain and the minimum cell width as\n    a multiple of the skin depth, with possible user restrictions on minimum\n    calculation domain and range of possible minimum cell widths.\n\n    .. math::\n\n            \\delta &= 503.3 \\sqrt{\\frac{\\rho}{f}} , \\\\\n            x_\\text{start} &= x_0-k_\\text{neg}\\delta , \\\\\n            x_\\text{end} &= x_0+k_\\text{pos}\\delta , \\\\\n            h_\\text{min} &= k_\\text{min} \\delta .\n\n\n    Parameters\n    ----------\n\n    x0 : float\n        Center of the calculation domain. Normally the source location.\n        Default is 0.\n\n    freq : float\n        Frequency (Hz) to calculate the skin depth. The skin depth is a concept\n        defined in the frequency domain. If a negative frequency is provided,\n        it is assumed that the calculation is carried out in the Laplace\n        domain. To calculate the skin depth, the value of `freq` is then\n        multiplied by :math:`-2\\pi`, to simulate the closest\n        frequency-equivalent.\n\n        Default is 1 Hz.\n\n    res : float, optional\n        Resistivity (Ohm m) to calculate skin depth.\n        Default is 0.3 Ohm m (sea water).\n\n    limits : None or list\n        [start, end] of model domain. This extent represents the minimum extent\n        of the domain. The domain is therefore only adjusted if it has to reach\n        outside of [start, end].\n        Default is None.\n\n    min_width : None, float, or list of two floats\n        Minimum cell width is calculated as a function of skin depth:\n        fact_min*sd. If `min_width` is a float, this is used. If a list of\n        two values [min, max] are provided, they are used to restrain\n        min_width. Default is None.\n\n    fact_min, fact_neg, fact_pos : floats\n        The skin depth is multiplied with these factors to estimate:\n\n            - Minimum cell width (`fact_min`, default 0.2)\n            - Domain-start (`fact_neg`, default 5), and\n            - Domain-end (`fact_pos`, defaults to `fact_neg`).\n\n\n    Returns\n    -------\n\n    h_min : float\n        Minimum cell width.\n\n    domain : list\n        Start- and end-points of calculation domain.\n\n    \"\"\"\n\n    # Set fact_pos to fact_neg if not provided.\n    if fact_pos is None:\n        fact_pos = fact_neg\n\n    # Calculate the skin depth.\n    skind = 503.3*np.sqrt(res/abs(freq))\n    if freq < 0:  # For Laplace-domain calculations.\n        skind /= np.sqrt(2*np.pi)\n\n    # Estimate minimum cell width.\n    h_min = fact_min*skind\n    if min_width is not None:  # Respect user input.\n        if np.array(min_width).size == 1:\n            h_min = min_width\n        else:\n            h_min = np.clip(h_min, *min_width)\n\n    # Estimate calculation domain.\n    domain = [x0-fact_neg*skind, x0+fact_pos*skind]\n    if limits is not None:  # Respect user input.\n        domain = [min(limits[0], domain[0]), max(limits[1], domain[1])]\n\n    return h_min, domain\n\n\ndef get_hx(alpha, domain, nx, x0, resp_domain=True):\n    r\"\"\"Return cell widths for given input.\n\n    Find the number of cells left and right of `x0`, `nl` and `nr`\n    respectively, for the provided alpha. For this, we solve\n\n    .. math::   \\frac{x_\\text{max}-x_0}{x_0-x_\\text{min}} =\n                \\frac{a^{nr}-1}{a^{nl}-1}\n\n    where :math:`a = 1+\\alpha`.\n\n\n    Parameters\n    ----------\n\n    alpha : float\n        Stretching factor `a` is given by ``a=1+alpha``.\n\n    domain : list\n        [start, end] of model domain.\n\n    nx : int\n        Number of cells.\n\n    x0 : float\n        Center of the grid. `x0` is restricted to `domain`.\n\n    resp_domain : bool\n        If False (default), then the domain-end might shift slightly to assure\n        that the same stretching factor is applied throughout. If set to True,\n        however, the domain is respected absolutely. This will introduce one\n        stretch-factor which is different from the other stretch factors, to\n        accommodate the restriction. This one-off factor is between the left-\n        and right-side of `x0`, or, if `x1` is provided, just after `x1`.\n\n\n    Returns\n    -------\n    hx : ndarray\n        Cell widths of mesh.\n\n    \"\"\"\n    if alpha <= 0.:  # If alpha <= 0: equal spacing (no stretching at all)\n        hx = np.ones(nx)*np.diff(np.squeeze(domain))/nx\n\n    else:            # Get stretched hx\n        a = alpha+1\n\n        # Get hx depending if x0 is on the domain boundary or not.\n        if np.isclose(x0, domain[0]) or np.isclose(x0, domain[1]):\n            # Get al a's\n            alr = np.diff(domain)*alpha/(a**nx-1)*a**np.arange(nx)\n            if x0 == domain[1]:\n                alr = alr[::-1]\n\n            # Calculate differences\n            hx = alr*np.diff(domain)/sum(alr)\n\n        else:\n            # Find number of elements left and right by solving:\n            #     (xmax-x0)/(x0-xmin) = a**nr-1/(a**nl-1)\n            nr = np.arange(2, nx+1)\n            er = (domain[1]-x0)/(x0-domain[0]) - (a**nr[::-1]-1)/(a**nr-1)\n            nl = np.argmin(abs(np.floor(er)))+1\n            nr = nx-nl\n\n            # Get all a's\n            al = a**np.arange(nl-1, -1, -1)\n            ar = a**np.arange(1, nr+1)\n\n            # Calculate differences\n            if resp_domain:\n                # This version honours domain[0] and domain[1], but to achieve\n                # this it introduces one stretch-factor which is different from\n                # all the others between al to ar.\n                hx = np.r_[al*(x0-domain[0])/sum(al),\n                           ar*(domain[1]-x0)/sum(ar)]\n            else:\n                # This version moves domain[1], but each stretch-factor is\n                # exactly the same.\n                fact = (x0-domain[0])/sum(al)  # Take distance from al.\n                hx = np.r_[al, ar]*fact\n\n                # Note: this hx is equivalent as providing the following h\n                # to TensorMesh:\n                # h = [(min_width, nl-1, -a), (min_width, n_nos+1),\n                #      (min_width, nr, a)]\n\n    return hx\n", "meta": {"hexsha": "1c850ddd900887b33d213aba43297d734592063b", "size": 31713, "ext": "py", "lang": "Python", "max_stars_repo_path": "geofem/emg3d/meshes.py", "max_stars_repo_name": "iisadoramacedo/geofem-master", "max_stars_repo_head_hexsha": "cc5cf4ae660480dd4dc3d805310f7207fb28230e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "geofem/emg3d/meshes.py", "max_issues_repo_name": "iisadoramacedo/geofem-master", "max_issues_repo_head_hexsha": "cc5cf4ae660480dd4dc3d805310f7207fb28230e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-29T11:42:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-29T11:42:21.000Z", "max_forks_repo_path": "build/lib/geofem/emg3d/meshes.py", "max_forks_repo_name": "iisadoramacedo/geofem-master", "max_forks_repo_head_hexsha": "cc5cf4ae660480dd4dc3d805310f7207fb28230e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-09T18:15:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-09T18:15:10.000Z", "avg_line_length": 35.8338983051, "max_line_length": 79, "alphanum_fraction": 0.5905779964, "include": true, "reason": "import numpy,from scipy", "num_tokens": 8359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.1890209760836889}}
{"text": "from __future__ import absolute_import, division, print_function, unicode_literals\nfrom typing import Optional\n\nimport numpy as np\nimport os\n\nfrom astropy.io import fits\nfrom astropy.table import Table\n\nfrom .. import this_project as P\nfrom .. import utils as ut\n\n__all__ = [\"Planck14Data\", \"Planck14DataAlt\", \"Planck14Model\", \"Maniyar18Model\"]\n\n\nclass CIBxCIB:\n\n    _l = None  # multipole\n    _Cl = None  # angular power\n    _dCl = None  # uncertainty on the angular power\n    _Dl = None  # l(l+1)/2pi * Cl\n    _dDl = None  # uncertainty on the angular power\n    _l3Cl = None  # l**3 * Cl\n\n    _S = None  # shot noise level\n    _dS = None  # uncertainty on the shot noise\n\n    _raw_table = None  # raw table, taken from publications, emails, etc\n\n    def __init__(self, freq1, freq2=None, unit=\"Jy^2/sr\"):\n        if unit not in [\"Jy^2/sr\", \"MJy^2/sr\", \"K^2.sr\", \"uK^2.sr\"]:\n            raise ValueError(\n                'Unit must be either \"Jy^2/sr\", ' '\"MJy^2/sr\", \"uK^2.sr\" or \"K^2.sr\"'\n            )\n        self.unit = unit\n\n        self.freq1 = self.freq2int(freq1)\n        if freq2 is None:\n            self.freq2 = freq1\n        else:\n            self.freq2 = self.freq2int(freq2)\n\n    # Methods\n    #########\n    def freq2int(self, freq):\n        if isinstance(freq, str):\n            return int(freq)\n        else:\n            if isinstance(freq, int):\n                return freq\n            else:\n                raise TypeError(\"freq must be int or str\")\n\n    # Properties\n    ############\n    @property\n    def freqstr(self):\n        self._freqstr = \"x\".join(\n            (\n                str(max([int(self.freq1), int(self.freq2)])),\n                str(min([int(self.freq1), int(self.freq2)])),\n            )\n        )\n        return self._freqstr\n\n    @property\n    def l(self):\n        if self._l is None:\n            self._l = self.raw_table[:, 0]\n        return self._l\n\n    @property\n    def Cl(self):\n        return None\n\n    @property\n    def dCl(self):\n        return None\n\n    @property\n    def Dl(self):\n        if self._Dl is None:\n            self._Dl = self.l * (self.l + 1.0) / 2.0 / np.pi * self.Cl\n        return self._Dl\n\n    @property\n    def l3Cl(self):\n        if self._l3Cl is None:\n            self._l3Cl = self.l ** 3 * self.Cl\n        return self._l3Cl\n\n    @property\n    def Jy2K(self):\n        self._Jy2K = P.Jy2K\n        return self._Jy2K\n\n    @property\n    def K2Jy(self):\n        self._K2Jy = P.K2Jy\n        return self._K2Jy\n\n\nclass Planck14DataAlt(CIBxCIB):\n    def __init__(self, freq1, freq2=None, unit=\"Jy^2/sr\"):\n        super(Planck14Data, self).__init__(freq1, freq2=freq2, unit=unit)\n\n        self.Cl_contains_SN = True\n\n    # Properties\n    ############\n    @property\n    def raw_table(self):\n        if self._raw_table is None:\n            self._raw_table = np.loadtxt(\n                os.path.join(P.PACKAGE_DIR, \"resources/cibxcib/Planck14_data.txt\")\n            )\n        return self._raw_table\n\n    @property\n    def Cl(self):\n        if self._Cl is None:\n            # Native unit is Jy^2/sr\n            self._Cl = self.raw_table[:, self._freq2col(self.freqstr)].copy()\n\n            # We add the shot noise, which is also in Jy^2/sr\n            self._Cl += self.S\n\n            if self.unit in [\"K^2.sr\", \"uK^2.sr\"]:\n                self._Cl *= self.Jy2K[str(self.freq1)] * self.Jy2K[str(self.freq2)]\n\n                if self.unit == \"uK^2.sr\":\n                    self._Cl *= 1.0e12\n\n            if self.unit == \"MJy^2/sr\":\n                self._Cl /= 1.0e12\n\n        return self._Cl\n\n    @property\n    def S(self):\n        \"\"\"\n        Shot noise, units are Jy^2/sr. Taken from\n        Planck (2014 XXX)\n        \"\"\"\n        if self._S is None:\n            self._S = {\n                \"857x857\": 5364,\n                \"545x545\": 1690,\n                \"353x353\": 262,\n                \"217x217\": 21,\n                \"3000x3000\": 9585,\n                \"857x545\": 2702,\n                \"857x353\": 953,\n                \"857x217\": 181,\n                \"545x353\": 626,\n                \"545x217\": 121,\n                \"353x217\": 54,\n                \"3000x857\": 4158,\n                \"3000x545\": 1449,\n                \"3000x353\": 411,\n                \"3000x217\": 95,\n            }\n\n            if self.unit in [\"K^2.sr\", \"uK^2.sr\"]:\n                self._S *= self.Jy2K[str(self.freq1)] * self.Jy2K[str(self.freq2)]\n\n                if self.unit == \"uK^2.sr\":\n                    self._S *= 1.0e12\n\n            if self.unit == \"MJy^2/sr\":\n                self._S /= 1.0e12\n\n        return self._S[self.freqstr]\n\n    @property\n    def dS(self):\n        \"\"\"\n        Shot noise\n        \"\"\"\n        if self._dS is None:\n            self._dS = {\n                \"857x857\": 343,\n                \"545x545\": 45,\n                \"353x353\": 8,\n                \"217x217\": 2,\n                \"3000x3000\": 1090,\n                \"857x545\": 124,\n                \"857x353\": 54,\n                \"857x217\": 6,\n                \"545x353\": 19,\n                \"545x217\": 6,\n                \"353x217\": 3,\n                \"3000x857\": 443,\n                \"3000x545\": 176,\n                \"3000x353\": 48,\n                \"3000x217\": 11,\n            }\n            if self.unit in [\"K^2.sr\", \"uK^2.sr\"]:\n                self._dS *= self.Jy2K[str(self.freq1)] * self.Jy2K[str(self.freq2)]\n                if self.unit == \"uK^2.sr\":\n                    self._dS *= 1.0e12\n\n            if self.unit == \"MJy^2/sr\":\n                self._dS /= 1.0e12\n\n        return self._dS[self.freqstr]\n\n    # Methods\n    #########\n    def _freq2col(self, freqstr):\n        mapping = {\n            \"857x857\": 1,\n            \"545x545\": 2,\n            \"353x353\": 3,\n            \"217x217\": 4,\n            \"3000x3000\": 5,\n            \"857x545\": 6,\n            \"857x353\": 7,\n            \"857x217\": 8,\n            \"545x353\": 9,\n            \"545x217\": 10,\n            \"353x217\": 11,\n            \"3000x857\": 12,\n            \"3000x545\": 13,\n            \"3000x353\": 14,\n            \"3000x217\": 15,\n            \"100x100\": 16,\n            \"857x100\": 17,\n            \"545x100\": 18,\n            \"353x100\": 19,\n            \"217x100\": 20,\n            \"143x143\": 21,\n            \"857x143\": 22,\n            \"545x143\": 23,\n            \"353x143\": 24,\n            \"217x143\": 25,\n            \"143x100\": 26,\n        }\n\n        return mapping[self.freqstr]\n\n\nclass Planck14Model(CIBxCIB):\n    def __init__(self, freq1, freq2=None, unit=\"Jy^2/sr\"):\n        super(Planck14Model, self).__init__(freq1, freq2=freq2, unit=unit)\n\n        self.Cl_contains_SN = True\n\n    # Properties\n    ############\n    @property\n    def raw_table(self):\n        if self._raw_table is None:\n            self._raw_table = np.loadtxt(\n                os.path.join(P.PACKAGE_DIR, \"resources/cibxcib/Planck14_model.txt\")\n            )\n        return self._raw_table\n\n    @property\n    def Cl(self):\n        if self._Cl is None:\n            # native unit is be Jy^2/sr\n            self._Cl = self.raw_table[:, self._freq2col(self.freqstr)].copy()\n\n            # Possibly convert the units\n            if self.unit in [\"K^2.sr\", \"uK^2.sr\"]:\n                self._Cl *= self.Jy2K[str(self.freq1)] * self.Jy2K[str(self.freq2)]\n                if self.unit == \"uK^2.sr\":\n                    self._Cl *= 1.0e12\n\n            if self.unit == \"MJy^2/sr\":\n                self._Cl /= 1.0e12\n\n            # Apply the correction factor to the PR1 calibration\n            # self._Cl /= (\n            #     ut.PLANCK_PR1PR3_CALCORR[str(self.freq1)]\n            #     * ut.PLANCK_PR1PR3_CALCORR[str(self.freq2)]\n            # )\n        return self._Cl\n\n    # Methods\n    #########\n    def _freq2col(self, freqstr):\n        # l, 353x353, 353x545, 353x857, 545x545, 545x857, 857x857\n        mapping = {\n            \"353x353\": 1,\n            \"545x353\": 2,\n            \"857x353\": 3,\n            \"545x545\": 4,\n            \"857x545\": 5,\n            \"857x857\": 6,\n        }\n\n        return mapping[self.freqstr]\n\n\nclass Maniyar18Model(CIBxCIB):\n    def __init__(self, freq1, freq2=None, unit=\"Jy^2/sr\"):\n        super(Maniyar18Model, self).__init__(freq1, freq2=freq2, unit=unit)\n\n        self.Cl_contains_SN = True\n        self.Cl_contains_1halo = True\n\n    # Properties\n    ############\n    @property\n    def raw_table(self):\n        if self._raw_table is None:\n            self._raw_table = fits.open(\n                os.path.join(\n                    P.PACKAGE_DIR, \"resources/cibxcib/Maniyar18_model_crosspowers.dat\"\n                )\n            )\n        return self._raw_table\n\n    @property\n    def l(self):\n        if self._l is None:\n            self._l = self.raw_table[1].data\n        return self._l\n\n    @property\n    def Cl(self):\n        if self._Cl is None:\n            # native unit is Jy^2/sr\n            self._Cl = self.raw_table[0].data[\n                self._freq2col(str(self.freq1)), self._freq2col(str(self.freq2))\n            ]\n\n            # Possibly convert the units\n            if self.unit in [\"K^2.sr\", \"uK^2.sr\"]:\n                self._Cl *= self.Jy2K[str(self.freq1)] * self.Jy2K[str(self.freq2)]\n                if self.unit == \"uK^2.sr\":\n                    self._Cl *= 1.0e12\n\n            if self.unit == \"MJy^2/sr\":\n                self._Cl /= 1.0e12\n\n        return self._Cl\n\n    # Methods\n    #########\n    def _freq2col(self, freq):\n        # 217x217, 353x353, 545x545, 857x857, 3000x3000\n        mapping = {\n            \"100\": 0,\n            \"143\": 1,\n            \"217\": 2,\n            \"353\": 3,\n            \"545\": 4,\n            \"857\": 5,\n            \"3000\": 6,\n        }\n\n        return mapping[freq]\n\n\nclass Planck14Data(CIBxCIB):\n    def __init__(self, freq1, freq2=None, unit=\"Jy^2/sr\"):\n        super(Planck14Data, self).__init__(freq1, freq2=freq2, unit=unit)\n        self.Cl_contains_SN = True\n\n    # Properties\n    ############\n    @property\n    def raw_table(self):\n        if self._raw_table is None:\n            self._raw_table = Table.read(\n                os.path.join(\n                    P.PACKAGE_DIR, \"resources/cibxcib/Planck14_data_frompaper.txt\"\n                ),\n                format=\"csv\",\n                delimiter=\";\",\n            )\n        return self._raw_table\n\n    @property\n    def l(self):\n        if self._l is None:\n            self._l = self.raw_table[\"ell\"].data.data\n\n        return self._l\n\n    @property\n    def Cl(self):\n        if self._Cl is None:\n            # Native unit is Jy^2/sr\n            self._Cl = self.raw_table[f\"{self.freq1}x{self.freq2}\"].data.data\n\n            # We add the shot noise, which is also in Jy^2/sr\n            # self._Cl += self.S\n\n            if self.unit in [\"K^2.sr\", \"uK^2.sr\"]:\n                self._Cl *= self.Jy2K[str(self.freq1)] * self.Jy2K[str(self.freq2)]\n\n                if self.unit == \"uK^2.sr\":\n                    self._Cl *= 1.0e12\n\n            if self.unit == \"MJy^2/sr\":\n                self._Cl /= 1.0e12\n\n            # Apply the correction factor to the PR1 calibration\n            # self._Cl /= (\n            #     ut.PLANCK_PR1PR3_CALCORR[str(self.freq1)]\n            #     * ut.PLANCK_PR1PR3_CALCORR[str(self.freq2)]\n            # )\n\n        return self._Cl\n\n    @property\n    def dCl(self):\n        if self._dCl is None:\n            # Native unit is Jy^2/sr\n            self._dCl = self.raw_table[f\"d{self.freq1}x{self.freq2}\"].data.data\n\n            if self.unit in [\"K^2.sr\", \"uK^2.sr\"]:\n                self._dCl *= self.Jy2K[str(self.freq1)] * self.Jy2K[str(self.freq2)]\n\n                if self.unit == \"uK^2.sr\":\n                    self._dCl *= 1.0e12\n\n            if self.unit == \"MJy^2/sr\":\n                self._dCl /= 1.0e12\n\n            # Apply the correction factor to the PR1 calibration\n            # self._dCl /= (\n            #     ut.PLANCK_PR1PR3_CALCORR[str(self.freq1)]\n            #     * ut.PLANCK_PR1PR3_CALCORR[str(self.freq2)]\n            # )\n\n        return self._dCl\n\n    @property\n    def dDl(self):\n        if self._dDl is None:\n            self._dDl = self.l * (self.l + 1.0) / 2.0 / np.pi * self.dCl\n        return self._dDl\n\n\nclass Mak17Model(CIBxCIB):\n    def __init__(\n        self,\n        freq1: str,\n        freq2: Optional[str] = None,\n        lmax: Optional[int] = None,\n        unit: str = \"uK2.sr\",\n        mask=\"mask40\",\n    ):\n        super().__init__(freq1, freq2=freq2, unit=unit)\n\n        if lmax is None:\n            self.lmax = 3000\n        else:\n            self.lmax = lmax\n\n        #         self.freq1 = freq1\n        #         if freq2 is None:\n        #             self.freq2 = freq1\n        #         else:\n        #             self.freq2 = freq2\n        #\n        self.mask = mask\n\n    @property\n    def l(self):\n        if self._l is None:\n            self._l = np.arange(self.lmax)\n        return self._l\n\n    @staticmethod\n    def model(ells, A_cib, A_ps, gamma):\n        \"\"\"\n        Returns Dl^total = Dl^CIB + Dl^PS\n        The Dl^PS are given as value at ell=2000, hence we need to convert this back to Cls\n        and then apply the appropriate scaling.\n        \"\"\"\n        return (\n            A_cib * np.power(ells / 2000.0, gamma)\n            + A_ps / 2000 / 2001 * ells * ells\n            + 1.0\n        )\n\n    @property\n    def mask(self):\n        return self._mask\n\n    @mask.setter\n    def mask(self, val):\n        if not hasattr(self, \"_mask\"):\n            allowed = [\"mask30\", \"mask40\", \"mask50\"]\n            if val not in allowed:\n                raise ValueError(f\"mask must be in {allowed}\")\n            self._mask = val\n        else:\n            raise RuntimeError(\"mask can only be set once during initialization.\")\n\n    @staticmethod\n    def get_rho_cib(freq1, freq2):\n        d = {\n            \"353x353\": 1.0,\n            \"545x545\": 1.0,\n            \"857x857\": 1.0,\n            \"353x545\": 0.975,\n            \"353x857\": 0.892,\n            \"545x857\": 0.949,\n        }\n\n        return d[f\"{freq1}x{freq2}\"]\n\n    @staticmethod\n    def get_rho_ps(freq1, freq2):\n        d = {\n            \"353x353\": 1.0,\n            \"545x545\": 1.0,\n            \"857x857\": 1.0,\n            \"353x545\": 0.98,\n            \"353x857\": 0.86,\n            \"545x857\": 0.97,\n        }\n\n        return d[f\"{freq1}x{freq2}\"]\n\n    @property\n    def _raw_data(self):\n        # Define mask30\n        mask30 = {\n            \"gamma\": 0.51,\n            \"cib\": {\"353\": 2.5e3, \"545\": 4.5e5, \"857\": 1.09e9},\n            \"ps\": {\"353\": 2.15e3, \"545\": 3.54e5, \"857\": 7.2e8},\n            \"cal\": {\"353\": 1.0, \"545\": 1.05, \"857\": 1.01},\n        }\n\n        # Define mask40\n        mask40 = {\n            \"gamma\": 0.53,\n            \"cib\": {\"353\": 2.56e3, \"545\": 4.47e5, \"857\": 1.09e9},\n            \"ps\": {\"353\": 2.1e3, \"545\": 3.42e5, \"857\": 7.34e8},\n            \"cal\": {\"353\": 1.0, \"545\": 1.03, \"857\": 1.01},\n        }\n\n        d = dict(\n            mask30=mask30,\n            mask40=mask40,\n            #                mask50=mask50,\n        )\n\n        return d\n\n    def calibration(self, freq1: int, freq2: int):\n        raw_data = self._raw_data[self.mask]\n        cal1, cal2 = raw_data[\"cal\"][str(freq1)], raw_data[\"cal\"][str(freq2)]\n\n        return cal1 * cal2\n\n    def get_model_parameters(self):\n        raw_data = self._raw_data[self.mask]\n\n        # Correlation coefficients\n        rho_cib = self.get_rho_cib(self.freq1, self.freq2)\n        rho_ps = self.get_rho_ps(self.freq1, self.freq2)\n\n        # Amplitudes\n        gamma = raw_data[\"gamma\"]\n\n        A_cib = rho_cib * np.sqrt(\n            raw_data[\"cib\"][str(self.freq1)] * raw_data[\"cib\"][str(self.freq2)]\n        )\n\n        A_ps = rho_ps * np.sqrt(\n            raw_data[\"ps\"][str(self.freq1)] * raw_data[\"ps\"][str(self.freq2)]\n        )\n\n        return gamma, A_cib, A_ps\n\n    @property\n    def Cl(self):\n        \"\"\"\n        We copy the dipole for the monopole, because it would naturally be inf due to\n        the division by zero.\n        \"\"\"\n        _Cl = self.Dl / (self.l * (self.l + 1)) * 2.0 * np.pi\n        _Cl = np.concatenate([_Cl[1:2], _Cl[1:]])\n\n        return _Cl\n\n    @property\n    def Dl(self):\n        if self._Dl is None:\n            gamma, A_cib, A_ps = self.get_model_parameters()\n            self._Dl = self.model(self.l, A_cib, A_ps, gamma)\n            self._Dl /= self.calibration(self.freq1, self.freq2)\n\n            if self.unit == \"K^2.sr\":\n                self._Dl /= 1.0e12\n            if self.unit == \"Jy^2/sr\":\n                self._Dl *= 1.0e-12 * (\n                    self.K2Jy[str(self.freq1)] * self.K2Jy[str(self.freq2)]\n                )\n            if self.unit == \"MJy^2/sr\":\n                self._Dl *= self.K2Jy[str(self.freq1)] * self.K2Jy[str(self.freq2)]\n        return self._Dl\n\n\nclass Mak17(Mak17Model):\n    \"\"\"We keep this copy of the Mak17Model to ensure downward compatibility.\"\"\"\n    pass\n", "meta": {"hexsha": "ca66a70f14ae3e1321b532c0950be8ef8f0cbb36", "size": 16713, "ext": "py", "lang": "Python", "max_stars_repo_path": "cibinfo/powerspectra/cibxcib.py", "max_stars_repo_name": "DanielLenz/CIBinfo", "max_stars_repo_head_hexsha": "45f12f3d459c17abedc4e5c75ef1422e99e20f20", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cibinfo/powerspectra/cibxcib.py", "max_issues_repo_name": "DanielLenz/CIBinfo", "max_issues_repo_head_hexsha": "45f12f3d459c17abedc4e5c75ef1422e99e20f20", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cibinfo/powerspectra/cibxcib.py", "max_forks_repo_name": "DanielLenz/CIBinfo", "max_forks_repo_head_hexsha": "45f12f3d459c17abedc4e5c75ef1422e99e20f20", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5337726524, "max_line_length": 91, "alphanum_fraction": 0.4814814815, "include": true, "reason": "import numpy,from astropy", "num_tokens": 4993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.1890209689473546}}
{"text": "#!/bin/python3.6\n\nimport subprocess\nimport os\nimport networkx as nx\nimport random\nfrom typing import Optional, Callable, Dict, List\nimport re\nimport signal\nfrom glob import glob\nfrom time import sleep\n\nfrom utils import filled_in, TreeDecomposition, pairs, stream_bn, get_bn_stats, \\\n    filter_read_bn, compute_complexity_width, read_jkl, write_jkl, get_domain_sizes, \\\n    CWDecomposition\n\nimport matplotlib.pyplot as plt\nfrom networkx.drawing.nx_agraph import pygraphviz_layout\n\nSOLVER_DIR = \"../solvers\"\nSCORE_PATN = re.compile(r\"New improvement! (?P<score>[\\d.-]+) \\(after (?P<time>[\\d.-]+) s.\\)\")\nCHECKPOINT_MINUTES = 30  # in minutes\nCHECKPOINT_INTERVAL = int(CHECKPOINT_MINUTES*60)  # in seconds\nCHECKPOINT_RETRY_INTERVAL = 5  # in seconds\n\n# not that crucial, if you consider the stdout updates of the heuristic as mere\n# triggers for reading new (not necessarily next) bn from .res file\nPARSE_RETRY_INTERVAL = 0.01  # in seconds\n\n\nclass BayesianNetwork(object):\n    def __init__(self, input_file, data=None, parents=None):\n        self.parents = dict() if parents is None else parents\n        self.input_file = input_file\n        self.data = data\n        self.sum_scores, self.best_score, self.offsets = get_bn_stats(self.input_file)\n        self.best_norm_score = self.best_score - sum(self.offsets.values())\n        self._score = None\n        self._dag = None\n\n    def _clear_cached(self):\n        self._score = self._dag = None\n\n    def compute_all_scores(self, subset: set = None) -> Dict[int, float]:\n        if self.data is None:\n            if subset is None:\n                data = stream_bn(self.input_file, normalize=True)\n            else:\n                data = filter_read_bn(self.input_file, subset, normalize=True).items()\n        else:\n            data = self.data.items()  # data is assumed to be normalized\n        scores = dict()\n        for node, psets in data:\n            if node in self.parents:  # could be a bn with a subset of nodes\n                if subset is None or node in subset:\n                    scores[node] = psets[self.parents[node]] + self.offsets[node]\n        return scores\n\n    def compute_score(self, subset: set=None) -> float:\n        \"\"\"recompute score based on parents sets\"\"\"\n        scores = self.compute_all_scores(subset)\n        return sum(scores.values())\n\n    @property\n    def score(self) -> float:\n        if self._score is None:\n            self._score = self.compute_score()\n        return self._score\n\n    def add(self, node, parents):\n        self.parents[node] = frozenset(parents)\n        self._clear_cached()\n\n    def recompute_dag(self):\n        dag = nx.DiGraph()\n        for node in self.parents.keys():\n            dag.add_node(node)\n            for parent in self.parents[node]:\n                assert not dag.has_edge(node, parent), f\"cyclic parent set {node}<->{parent}\"\n                dag.add_edge(parent, node)\n        self._dag = dag\n\n    @property\n    def dag(self) -> nx.DiGraph:\n        if self._dag is None:\n            self.recompute_dag()\n        return self._dag\n\n    def verify(self):\n        assert nx.is_directed_acyclic_graph(self.dag), \"network is not acyclic\"\n\n    def get_moralized(self):\n        moral = self.dag.to_undirected()\n        for node in self.parents.keys():\n            for p1, p2 in pairs(self.parents[node]):\n                moral.add_edge(p1, p2)\n        return moral\n\n    def draw(self, subset=None):\n        if subset is None:\n            dag = self.dag\n        else:\n            dag = self.dag.subgraph(subset)\n        pos = pygraphviz_layout(dag, prog='dot')\n        nx.draw(dag, pos, with_labels=True)\n        plt.show()\n\n    def replace(self, newbn: 'BayesianNetwork'):\n        for node, new_parents in newbn.parents.items():\n            self.parents[node] = new_parents\n        self._clear_cached()\n\n\nclass TWBayesianNetwork(BayesianNetwork):\n    def __init__(self, input_file, tw=0, elim_order=None, td=None, *args, **kwargs):\n        super().__init__(input_file, *args, **kwargs)\n        self.tw = tw\n        self.elim_order: List[int] = elim_order\n        self._td: Optional[TreeDecomposition] = td\n\n    @property\n    def td(self) -> TreeDecomposition:\n        if self._td is None:\n            raise RuntimeError(\"td requested before finalizing (call `.done`)\")\n        return self._td\n\n    def done(self):\n        \"\"\"\n        compute and store tree decomp and width based on\n        elim_order(default: reverse topological order of the dag)\n        \"\"\"\n        if self.elim_order is None:\n            self.elim_order = list(nx.topological_sort(self.dag))[::-1]\n        self._td = TreeDecomposition(self.get_moralized(), self.elim_order, self.tw)\n        if self.tw <= 0:\n            self.tw = self.td.width\n\n    def verify(self, verify_treewidth=True):\n        super().verify()\n        if verify_treewidth:\n            self.td.verify(graph=self.get_moralized())\n\n    def get_triangulated(self, elim_order=None):\n        if elim_order is None: elim_order = self.elim_order\n        assert elim_order is not None, \"elim order not specified\"\n        moral = self.get_moralized().subgraph(elim_order)\n        triangulated, max_degree = filled_in(moral, elim_order)\n        assert max_degree <= self.tw, f\"tw {self.tw} < {max_degree} for elim order {elim_order}\"\n        return triangulated\n\n\nclass CWBayesianNetwork(TWBayesianNetwork):\n    def __init__(self, input_file, cwidth, datfile, elim_order=None, td=None, *args, **kwargs):\n        super().__init__(input_file, *args, **kwargs)\n        self.tw = cwidth\n        self.elim_order: List[int] = elim_order\n        self._td: Optional[TreeDecomposition] = td\n        self.domain_sizes = get_domain_sizes(datfile)\n\n    def done(self):\n        if self.elim_order is None:\n            self.elim_order = list(nx.topological_sort(self.dag))[::-1]\n        self._td = CWDecomposition(self.get_moralized(), self.elim_order, self.tw, self.domain_sizes)\n\n\ndef inject_tuples(basejkl, extra_tuples, destname, strong_injection=False):\n    src = read_jkl(basejkl, normalize=False)\n    inject_count = 0\n    for node, pset in extra_tuples.items():\n        parents, score = pset\n        if strong_injection or parents not in src[node]:\n            src[node][parents] = score\n            inject_count += 1\n    write_jkl(src, destname)\n\n\ndef parse_res(filename: str, treewidth: int, outfile: str, cwidth=-1,\n              add_extra_tuples=False, augfile: str = \"augmented.jkl\",\n              datfile=None, retry=True, debug=False) -> TWBayesianNetwork:\n    \"\"\"\n    Parse a .res file containing a solution BN. Optionally merge the parent set\n    tuples from the jkl file `filename` and the the res file `outfile` and\n    save as a temporary file `augfile` (only when `add_extra_tuples` is True)\n\n    :param filename: input jkl file\n    :param treewidth: treewidth bound\n    :param outfile: res file containing BN\n    :param cwidth: cwidth bound, use -1 to ignore and simply parse a TWBN\n    :param add_extra_tuples: whether to inject tuples from outfile into filename\n    :param augfile: name of temporary file containing merged set of tuples,\n                    (only applicable if add_extra_tuples is True)\n    :param datfile: path to data file (with header rows)\n    :param retry: keep retrying until file is non-empty\n    :param debug: debugging\n    :return: parsed BN as a TWBayesianNetwork\n    \"\"\"\n    elim_order = None\n    tuples = []\n    extra_tuples = dict()\n    score = None\n    # keep retrying until file is non-empty\n    while retry and os.path.getsize(outfile) == 0:\n        sleep(PARSE_RETRY_INTERVAL)\n    with open(outfile) as out:\n        for line in out:\n            if not line.strip():\n                continue\n            elif line.startswith(\"Score:\"):\n                score = float(line.split()[1].strip())\n                break\n            elif line.startswith(\"elim-order:\"):\n                elim_order = line.split()[1].strip(\"()\").split(\",\")\n                elim_order = list(map(int, elim_order))\n                if debug: print(\"elim-order:\", elim_order)\n            else:\n                vertex, rest = line.split(\":\")\n                vertex = int(vertex)\n                rest = rest.strip().split()\n                if len(rest) == 1:\n                    local_score = float(rest[0])\n                    parents = frozenset()\n                else:\n                    local_score, parents = rest\n                    local_score = float(local_score)\n                    parents = frozenset(map(int, parents.strip(\"()\").split(\",\")))\n                # bn.add(int(vertex), map(int, parents))\n                tuples.append((vertex, parents))\n                if add_extra_tuples:\n                    extra_tuples[vertex] = (parents, local_score)\n                if debug: print(f\"v:{vertex}, sc:{local_score}, par:{parents})\")\n    if add_extra_tuples:\n        inject_tuples(filename, extra_tuples, augfile, True)\n        if debug: print(\"temporary merged file saved as\", augfile)\n        input_file = augfile\n    else:\n        input_file = filename\n    if cwidth > 0:\n        assert datfile, \"datfile needed for cwidth\"\n        bn = CWBayesianNetwork(cwidth=cwidth, input_file=input_file, datfile=datfile)\n    else:\n        bn = TWBayesianNetwork(tw=treewidth, input_file=input_file)\n    if elim_order is not None: bn.elim_order = elim_order\n    for node, parents in tuples: bn.add(node, parents)\n    bn.done()\n    if score is not None:\n        bn._score = score\n    else:\n        print(f\"warning: score not found in {outfile}\")\n    return bn\n\n\ndef parse_res_score(outfile: str):\n    with open(outfile) as out:\n        for line in out:\n            if not line.strip():\n                continue\n            elif line.startswith(\"Score:\"):\n                score = float(line.split()[1].strip())\n                return score\n    return None\n\n\ndef write_res(bn: BayesianNetwork, outfile, write_elim_order=False, debug=False):\n    nodes = sorted(bn.dag.nodes())\n    scores = bn.compute_all_scores()\n    with open(outfile, \"w\") as out:\n        if write_elim_order and isinstance(bn, TWBayesianNetwork):\n            elim_order = bn.td.recompute_elim_order()\n            out.write(f\"elim-order: ({','.join(map(str, elim_order))})\\n\")\n        for node in nodes:\n            parents = bn.parents[node]\n            pstr = \"\"\n            if parents:\n                pstr = \" (\" + \",\".join(map(str, parents)) + \")\"\n            out.write(f\"{node}: {scores[node]:.2f} {pstr}\\n\")\n        out.write(f\"\\nScore: {bn.compute_score():.3f}\\n\")\n\n\ndef write_net(bn: BayesianNetwork, datfile, tempprefix=\"lltemp\",\n              use_res=\"\", debug=False):\n    netfile = f\"{tempprefix}.net\"\n    if use_res:\n        resfile = use_res\n    else:\n        resfile = f\"{tempprefix}.res\"\n        write_res(bn, resfile)\n    basecmd = [\"java\", \"-jar\", os.path.join(SOLVER_DIR, \"blip.jar\"), \"parle\"]\n    args = [\"-d\", datfile, \"-r\", resfile, \"-n\", netfile]\n    cmd = basecmd + args\n    if debug: print(\"running parle, cmd:\", cmd)\n    proc = subprocess.run(cmd, stdout=subprocess.PIPE)\n    if proc.returncode == 0:  # success\n        if debug: print(\"file generated:\", netfile)\n    else:  # error\n        print(\"error encountered during 'parle', returncode:\", proc.returncode)\n        return None\n\n\ndef run_blip(filename, treewidth, outfile=\"temp.res\", timeout=10, seed=0,\n             solver=\"kg\", logfile=\"temp.log\", debug=False) -> TWBayesianNetwork:\n    basecmd = [\"java\", \"-jar\", os.path.join(SOLVER_DIR, \"blip.jar\"),\n               f\"solver.{solver}\", \"-v\", \"1\"]\n    args = [\"-j\", filename, \"-w\", str(treewidth), \"-r\", outfile,\n            \"-t\", str(timeout), \"-seed\", str(seed), \"-l\", logfile]\n    cmd = basecmd + args\n    if debug: print(\"running blip, cmd:\", cmd)\n    proc = subprocess.run(cmd, stdout=subprocess.PIPE)\n    if proc.returncode == 0:  # success\n        return parse_res(filename, treewidth, outfile, debug)\n    else:  # error\n        print(\"error encountered, returncode:\", proc.returncode)\n        return None\n\n\ndef activate_checkpoints(bnprovider, save_as):\n    def alarm_handler(signalnum, frame):\n        print(\"alarm triggered\")\n        try:\n            bn = bnprovider()\n        except IndexError:\n            print(\"bn res file invalid (probably got overwritten)\")\n            signal.alarm(CHECKPOINT_RETRY_INTERVAL)  # snooze alarm\n        else:\n            patn = save_as.replace(\".res\", \"*.res\")\n            prefix, ext = os.path.splitext(save_as)\n            prev_checkpoint = 0\n            for check_file in glob(patn):\n                try:\n                    saved_at = int(check_file.replace(prefix, \"\").replace(ext, \"\"))\n                except ValueError:\n                    continue\n                else:\n                    prev_checkpoint = max(prev_checkpoint, saved_at)\n            new_checkpoint = prev_checkpoint + CHECKPOINT_MINUTES\n            fname = save_as.replace(\".res\", f\"{new_checkpoint}.res\")\n            print(\"saving checkpoint to\", fname)\n            write_res(bn, fname, write_elim_order=True)\n            signal.alarm(CHECKPOINT_INTERVAL)  # reset alarm\n    signal.signal(signal.SIGALRM, alarm_handler)  # register handler\n    signal.alarm(CHECKPOINT_INTERVAL)  # set first alarm\n    print(f\"checkpointing for {CHECKPOINT_MINUTES}m activated\")\n\n\ndef monitor_blip(filename, treewidth, logger: Callable, outfile=\"temp.res\",\n                 timeout=10, seed=0, solver=\"kg\", datfile=None,\n                 cwidth=0, onlyfilter=False, save_as=\"\", debug=False):\n    \"\"\"\n    Run BLIP in monitoring mode, where each new score update is logged\n\n    :param filename: path to jkl file\n    :param treewidth: treewidth bound (ignored if in CWIDTH_MODE)\n    :param logger: logging function to be used\n    :param outfile: path to .res file containing learned network (volatile)\n    :param timeout: total time limit on blip computation\n    :param seed: random seed passed on to blip\n    :param solver: blip sub-algo to use (for tw: [kg, ka, kmax], cwidth: [old, greedy, max])\n    :param datfile: path to data file (with header rows, for domain sizes)\n    :param cwidth: cwidth bound (if positive, activates CWIDTH_MODE)\n    :param onlyfilter: only use pset filtering algo (ignored if not in CWIDTH_MODE)\n    :param save_as: filepath prefix to use for saving checkpoint solutions\n    :param debug: enable debug mode\n    \"\"\"\n    CWIDTH_MODE = cwidth > 0\n    if CWIDTH_MODE:\n        assert solver in (\"old\", \"greedy\", \"max\"), \\\n            f\"invalid solver({solver}) for monitor_blip in CWIDTH_MODE\"\n        basecmd = [\"java\", \"-jar\", os.path.join(SOLVER_DIR, \"blip-cw.jar\"),\n                   f\"solver.kg.adv\", \"-v\", \"1\", \"-src\", f\"cwidth-{solver}\"]\n        args = [\"-j\", filename, \"-d\", datfile, \"-w\", \"0\", \"-cw\", str(cwidth),\n                \"-r\", outfile, \"-t\", str(timeout), \"-seed\", str(seed)]\n        if onlyfilter: args.append(\"-filter\")\n    else:\n        basecmd = [\"java\", \"-jar\", os.path.join(SOLVER_DIR, \"blip.jar\"),\n                   f\"solver.{solver}\", \"-v\", \"1\"]\n        args = [\"-j\", filename, \"-w\", str(treewidth), \"-r\", outfile,\n                \"-t\", str(timeout), \"-seed\", str(seed)]\n    cmd = basecmd + args\n    if debug: print(\"monitoring blip, cmd:\", \" \".join(cmd))\n    if save_as:\n        if CWIDTH_MODE:\n            bnprovider = lambda: parse_res(filename, 0, outfile, cwidth=cwidth,\n                                           datfile=datfile)\n        else:\n            bnprovider = lambda: parse_res(filename, treewidth, outfile)\n        activate_checkpoints(bnprovider, save_as)\n    domain_sizes = None if datfile is None else get_domain_sizes(datfile)\n    with subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1,\n                          universal_newlines=True) as proc:\n        for line in proc.stdout:\n            if debug: print(\"got line:\", line, end='')\n            match = SCORE_PATN.match(line)\n            if match:\n                score = float(match['score'])\n                logdata = {\"score\": score}\n                if domain_sizes is not None:\n                    try:\n                        bn = bnprovider()\n                    except IndexError:  # todo: not reached anymore, retries, rethink\n                        print(\"bn res file invalid (probably got overwritten)\")\n                        cw = acw = -1\n                    else:\n                        tw = bn.td.compute_width()\n                        cw = compute_complexity_width(bn.td, domain_sizes)\n                        logdata[\"tw\"] = tw\n                        logdata[\"cw\"] = cw\n                logger(logdata)\n    print(f\"done returncode: {proc.returncode}\")\n\n\ndef start_blip_proc(filename, treewidth, outfile=\"temp.res\",\n                    timeout=10, seed=0, solver=\"kg\", debug=False) -> subprocess.Popen:\n    basecmd = [\"java\", \"-jar\", os.path.join(SOLVER_DIR, \"blip.jar\"),\n               f\"solver.{solver}\", \"-v\", \"1\"]\n    args = [\"-j\", filename, \"-w\", str(treewidth), \"-r\", outfile,\n            \"-t\", str(timeout), \"-seed\", str(seed)]\n    cmd = basecmd + args\n    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1,\n                            universal_newlines=True)\n    os.set_blocking(proc.stdout.fileno(), False)  # set stdout to be non-blocking\n    if debug: print(f\"starting blip proc, pid: {proc.pid}, \\ncmd: {cmd}\")\n    return proc\n\n\ndef start_blip_proc_cw(filename, datfile, cwidth, outfile=\"temp.res\", timeout=10,\n                       seed=0, searcher=\"greedy\", onlyfilter=False, debug=False) -> subprocess.Popen:\n    basecmd = [\"java\", \"-jar\", os.path.join(SOLVER_DIR, \"blip-cw.jar\"),\n               f\"solver.kg.adv\", \"-v\", \"1\", \"-src\", f\"cwidth-{searcher}\"]\n    args = [\"-j\", filename, \"-d\", datfile, \"-w\", \"0\", \"-cw\", str(cwidth),\n            \"-r\", outfile, \"-t\", str(timeout), \"-seed\", str(seed)]\n    if onlyfilter: args.append([\"-filter\"])\n    cmd = basecmd + args\n    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1,\n                            universal_newlines=True)\n    os.set_blocking(proc.stdout.fileno(), False)  # set stdout to be non-blocking\n    if debug: print(f\"starting blip-cw proc, pid: {proc.pid}, \\ncmd: {cmd}\")\n    return proc\n\n\ndef check_blip_proc(proc: subprocess.Popen, debug=False) -> float:\n    score = float(\"-infinity\")\n    rc = proc.poll()\n    if rc is not None:\n        if debug: print(f\"blip proc already terminated with rc:\", rc)\n        return score\n    while True:\n        line = proc.stdout.readline()\n        if line:\n            if debug: print(\"got line:\", line, end='')\n            match = SCORE_PATN.match(line)\n            if match:\n                score = float(match['score'])\n        else:\n            rc = proc.poll()\n            if rc is not None:\n                if debug: print(f\"no output and proc is completed (rc: {rc})\")\n            else:\n                if debug: print(f\"no output and proc is still running\")\n            break\n    return score\n\n\ndef stop_blip_proc(proc: subprocess.Popen):\n    proc.terminate()\n    proc.stdout.close()\n    if proc.stderr is not None: proc.stderr.close()\n    if proc.stdin is not None: proc.stdin.close()\n    proc.wait()\n\n\nif __name__ == '__main__':\n    # res = run_blip(\"../past-work/blip-publish/data/child-5000.jkl\", 10, timeout=2, seed=4)\n    # dag = res.get_dag()\n    # print(\"acyclic\", nx.is_directed_acyclic_graph(dag))\n    # fig, axes = plt.subplots(1, 3)\n    # nx.draw(dag, with_labels=True, ax=axes[0])\n    # moral = res.get_moralized()\n    # nx.draw(moral, with_labels=True, ax=axes[1])\n    # tri = res.get_triangulated()\n    # nx.draw(tri, with_labels=True, ax=axes[2])\n    # fig.show()\n    for seed in range(1,100):\n        print(seed)\n        res = run_blip(\"../past-work/blip-publish/data/child-5000.jkl\", 10, timeout=2, seed=seed, debug=False)\n        tri = res.get_triangulated()\n    print(\"done\")\n\n", "meta": {"hexsha": "8b4d320920ea73c87cc32952829adc8cadeece48", "size": 19757, "ext": "py", "lang": "Python", "max_stars_repo_path": "blip.py", "max_stars_repo_name": "aditya95sriram/bn-slim", "max_stars_repo_head_hexsha": "8661ffcdf4a29f2f6e3601bae1b7c0ee076f62c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-12T19:15:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T19:15:25.000Z", "max_issues_repo_path": "blip.py", "max_issues_repo_name": "aditya95sriram/bn-slim", "max_issues_repo_head_hexsha": "8661ffcdf4a29f2f6e3601bae1b7c0ee076f62c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-12T19:20:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T11:28:45.000Z", "max_forks_repo_path": "blip.py", "max_forks_repo_name": "aditya95sriram/bn-slim", "max_forks_repo_head_hexsha": "8661ffcdf4a29f2f6e3601bae1b7c0ee076f62c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.568788501, "max_line_length": 110, "alphanum_fraction": 0.6022675507, "include": true, "reason": "import networkx,from networkx", "num_tokens": 4823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.1890209689473546}}
{"text": "\"\"\"\nThe :py:mod:`h2_mobility` module contains a class to read the required data and\na class to evaluate the power-to-mobility system.\n\"\"\"\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport pvlib\n\n\nclass ReadData:\n    \"\"\"\n\n    This class enables to read data from the data files.\n\n    Parameters\n    ----------\n    filename_climate : str\n        The directory of the file with information on the\n        solar irradiance.\n\n    \"\"\"\n\n    def __init__(self, filename_climate):\n        self.filename_climate = filename_climate\n        self.path = os.path.dirname(os.path.abspath(__file__))\n\n    def load_climate(self):\n        \"\"\"\n\n        This method loads the hourly solar irradiance data\n        and ambient temperature data,\n        situated in the 'sol_irr' and 'T_amb' columns of the\n        climate data file.\n\n        Returns\n        -------\n        sol_irr : ndarray\n            The hourly solar irradiance data for a Typical\n            Meteorological Year.\n        t_amb : ndarray\n            The hourly ambient temperature data for a Typical\n            Meteorological Year.\n\n        \"\"\"\n        data = pd.read_csv(self.filename_climate)\n        sol_irr = data['sol_irr'].to_numpy()\n        t_amb = data['T_amb'].to_numpy()\n\n        return sol_irr, t_amb\n\n    def load_parameters(self):\n        \"\"\"\n\n        This method loads the deterministic values of the model\n        parameters, defined in the design_space file. This is\n        useful when the deterministic performance of a specific\n        design needs to be evaluated.\n\n        Returns\n        -------\n        param_dict : dict\n            Dictionary with the names of the model parameters\n            and the corresponding deterministic values.\n\n        \"\"\"\n        param_dict = {}\n        design_space = os.path.join(self.path, 'design_space')\n\n        # read the deterministic values for the parameters in `design_space`\n        with open(design_space, 'r') as file:\n            for line in file:\n                tmp = line.split()\n                if tmp[1] == 'par':\n                    param_dict[tmp[0]] = float(tmp[2])\n\n        return param_dict\n\n\nclass Evaluation:\n    \"\"\"\n\n    This class evaluates the power-to-mobility system.\n    For a given design, the solar irradiance, ambient temperature\n    and the characterization of the model parameters,\n    the levelized cost of driving, carbon intensity and the annual\n    grid consumption are quantified.\n\n    Parameters\n    ----------\n    sol_irr : ndarray\n        The hourly solar irradiance for the evaluated year.\n    t_amb : ndarray\n        The hourly ambient temperature for the evaluated year.\n    parameters : dict\n        Dictionary with the model parameters and design variables values.\n\n    \"\"\"\n\n    def __init__(self, sol_irr, t_amb, par):\n        self.par = par\n\n        # the solar irradiance and ambient temperature are scaled with the\n        # corresponding uncertainty\n        self.sol_irr = sol_irr * self.par['u_sol_irr']\n        self.t_amb = t_amb + self.par['u_t_amb']\n\n        self.length = len(self.sol_irr)\n\n        # the result dictionary\n        self.res = {}\n\n        # the system lifetime\n        self.par['life_sys'] = 20.\n\n        # initialize the operating hours of the electrolyzer array\n        self.res['running_hours_pemel'] = 0.\n\n        # initialize the storage tank size and its starting status\n        self.m_h2_max = self.tank()\n        self.m_h2_min = 0.05 * self.m_h2_max\n        self.m_h2 = self.m_h2_min\n\n        # instantiate the profiles for grid electricity price\n        self.demand_profiles()\n\n        # the number of PEM electrolyzer cells, corresponding to the\n        # nominal capacity of the considered PEM cell and the provided\n        # PEM capacity\n        self.n_pemel_array = self.par['n_pemel'] / 0.4\n\n        # the fitted polynomials on the electrolyzer and compressor\n        self.polyfit_pemel()\n        self.polyfit_pemel_compr()\n\n    def demand_profiles(self):\n        \"\"\"\n        Set the grid electricity price for buying and selling electricity.\n        A contract with fixed electricity price is considered, for which the\n        price for buying electricity consists of three segments: the energy\n        price itself (i.e. 'elec cost'), the profit made on this price by the\n        electricity provider (i.e. 'elec_cost_profit') and the fraction of the\n        energy price to the final retail price (i.e. 'elec_cost_ratio', e.g.\n        when this value equal 0.3, then the energy price corresponds to 30% of\n        the final bill, while 70% corresponds to transportation cost,\n        taxes,...). The price for selling electricity back to the grid\n        corresponds to the energy price.\n\n        In addition, the demand profiles from the hydrogen buses and diesel\n        buses is determined, based on the European daily refueling profile [1].\n\n        [1] T. A. Gunawan, I.Williamson, D. Raine, and R. F. Monaghan,\n        “Decarbonising city bus networks in ireland with renewable hydrogen,”\n        International Journal of Hydrogen Energy, 2020.\n\n        \"\"\"\n\n        # electricity cost profile [euro/Wh]\n        self.elec_profile = np.ones(self.length) * (\n            (self.par['elec_cost'] +\n             self.par['elec_cost_profit']) /\n            self.par['elec_cost_ratio']) / 1e6\n\n        # electricity selling profile [euro/Wh]\n        self.elec_profile_sale = np.ones(\n            self.length) * self.par['elec_cost'] / 1e6\n\n        self.diesel_profile = np.ones(self.length) * self.par['diesel_cost']\n\n        # number of km driven per day per bus\n        self.par['n_km_bus'] = 250.\n\n        # number of buses in the fleet\n        self.par['n_bus'] = 40.\n\n        # energy consumed by the diesel buses and hydrogen buses per day\n        # [kWh/day]\n        energy_h2 = (self.par['cons_h2_bus'] * self.par['n_km_bus'] *\n                     self.par['n_h2_bus'])\n        energy_diesel = (self.par['cons_diesel_bus'] * self.par['n_km_bus'] *\n                         (self.par['n_bus'] - self.par['n_h2_bus']))\n\n        h2_required = energy_h2 / 33.33  # kg\n        diesel_required = energy_diesel / 10.  # litre\n\n        # the daily refueling profile of the buses.\n        fill_profile = np.array([0.09, 0.015, 0.005, 0.04, 0.04, 0., 0.01,\n                                 0.01, 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n                                 0.08, 0.08, 0.13, 0.13, 0.13, 0.13, 0.11])\n\n        # daily refueling profile for the hydrogen buses and diesel buses\n        day_h2 = np.ones(24) * fill_profile * h2_required\n        day_diesel = np.ones(24) * fill_profile * diesel_required\n\n        # annual refueling profiles\n        self.load_h2 = list(day_h2) * int(365 * self.length / 8760)\n        self.load_diesel = list(day_diesel) * int(365 * self.length / 8760)\n\n        # dispenser capacity such that the hourly hydrogen demand can be\n        # complied with\n        dispenser_mass_flow_rate = 33.333\n        self.par['n_disp'] = max(self.load_h2) / dispenser_mass_flow_rate\n\n    #############################\n    # photovoltaic array module #\n    #############################\n\n    def quantify_mpp(self, sol_irr, t_amb, pv_system):\n        \"\"\"\n\n        Quantify the maximum power of the photovoltaic array\n        for a given solar irradiance and ambient temperature.\n\n        Parameters\n        ----------\n        sol_irr : float\n            The solar irradiance [W/m2].\n        t_amb : float\n            The ambient temperature [C].\n        pv_system : pandas.core.series.Series\n            The pv system characteristics\n        Returns\n        -------\n        pmp : float\n            The maximum power.\n\n        \"\"\"\n\n        # quantify the parameters for the pv system using De Soto method\n        pv_inputs = pvlib.pvsystem.calcparams_desoto(sol_irr,\n                                                     t_amb,\n                                                     pv_system['alpha_sc'],\n                                                     pv_system['a_ref'],\n                                                     pv_system['I_L_ref'],\n                                                     pv_system['I_o_ref'],\n                                                     pv_system['R_sh_ref'],\n                                                     pv_system['R_s'],\n                                                     EgRef=1.121,\n                                                     dEgdT=-0.0002677,\n                                                     irrad_ref=1000.,\n                                                     temp_ref=25.)\n\n        # determine the maximum power for the given pv system\n        pmp = pvlib.pvsystem.max_power_point(pv_inputs[0],\n                                             pv_inputs[1],\n                                             pv_inputs[2],\n                                             pv_inputs[3],\n                                             pv_inputs[4],\n                                             method='newton')['p_mp']\n\n        return pmp\n\n    def photovoltaic(self):\n        \"\"\"\n\n        The hourly photovoltaic power is quantified via the PVlib package.\n        Using this package, first the characteristics for a typical\n        photovoltaic panel are defined. Based on these characteristics,\n        the maximum power point is quantified for each hour, based on the\n        corresponding solar irradiance and ambient temperature. Finally, the\n        hourly power production is scaled by the considered photovoltaic array\n        capacity.\n\n        \"\"\"\n\n        p_pv = np.zeros(len(self.sol_irr))\n\n        # get the specific photovoltaic panel characteristics\n        pv_database = pvlib.pvsystem.retrieve_sam('CECmod')\n        pv_system = pv_database.SunPower_SPR_X19_240_BLK\n\n        # determine the maximum power point at reference conditions\n        p_mpp_ref = self.quantify_mpp(1000., 25., pv_system)  # W\n\n        # maximum power point determination for each hour in the timeframe\n        for i, irr in enumerate(self.sol_irr):\n            if irr > 0.:\n                p_mpp = self.quantify_mpp(irr, self.t_amb[i], pv_system)\n                p_pv[i] = p_mpp / p_mpp_ref * self.par['n_pv'] * 1e3  # W\n            else:\n                p_pv[i] = 0.\n\n        # store the hourly pv power in the result dictionary\n        self.res['p_pv'] = p_pv\n\n        # the dc-dc converter capacity in kW\n        self.res['n_dcdc_pv'] = max(p_pv) / 1e3\n\n    #############################\n    # electrolyzer array module #\n    #############################\n\n    def pemel(self, i_pemel):\n        \"\"\"\n        The electrolyzer model, based on the work of Saeed et al. [2]. For a\n        given current, the model determines the operating voltage by\n        considering the activation, concentration and ohmic overpotentials.\n        The model quantifies the operating voltage, power, efficiency and\n        hydrogen production.\n\n        [2] Saeed, E. W., & Warkozek, E. G. (2015). Modeling and Analysis of\n            Renewable PEM Fuel Cell System. Energy Procedia, 74, 87–101.\n            https://doi.org/10.1016/j.egypro.2015.07.527\n\n        Parameters\n        ----------\n        i_pemel : float\n            The electrolyzer input current [A].\n\n        Returns\n        -------\n        res : dict\n            Dictionary with the operating conditions of the electrolyzer for a\n            given current. It contains items on the operating voltage, power,\n            efficiency and hydrogen mass flow rate.\n\n        \"\"\"\n        par_pemel = {'T': 353.,\n                     'a': 1.,\n                     'p_o2': 1.,\n                     'p_h2': 1.,\n                     'p_h2o': 1.,\n                     'i_L': 2.,\n                     'A': 100.,\n                     'i_0': 1e-4,\n                     'n': 2.,\n                     't_mem': 50e-4,\n                     'alpha': 0.3,\n                     'R': 8.3143,\n                     'F': 96485.,\n                     'HHV': 141.7e6,\n                     }\n\n        res = {}\n        i = i_pemel / par_pemel['A']\n\n        # minimum operating voltage of electrolyzer\n        e_0 = (1.48 - 0.85e-3 * (par_pemel['T'] - 298.15) + 4.3085e-5 *\n               par_pemel['T'] * np.log(par_pemel['p_h2'] *\n                                       np.sqrt(par_pemel['p_o2']) /\n                                       par_pemel['p_h2o']))\n\n        # activation overpotential\n        v_act = (np.log(i / par_pemel['i_0']) /\n                 (par_pemel['alpha'] * par_pemel['n'] * par_pemel['F']) *\n                 par_pemel['R'] * par_pemel['T'])\n\n        # ohmic overpotential\n        lambda_mem = (0.043 + 17.81 * par_pemel['a'] -\n                      39.85 * par_pemel['a']**2. +\n                      36. * par_pemel['a']**3.)\n        sigma_mem = ((0.005139 * lambda_mem - 0.00326) *\n                     np.exp(1268 * (1. / 303. - 1. / par_pemel['T'])))\n        v_ohm = i * par_pemel['t_mem'] / sigma_mem\n\n        # the concentration overpotential\n        v_con = - (par_pemel['R'] * par_pemel['T'] /\n                   (par_pemel['n'] * par_pemel['F']) *\n                   np.log(1. - i / par_pemel['i_L']))\n\n        # model outputs\n        res['v_pemel'] = (e_0 + v_act + v_ohm + v_con) * self.n_pemel_array\n        res['m_pemel'] = self.current_to_mh2(i_pemel) * self.n_pemel_array\n        res['p_pemel'] = i_pemel * res['v_pemel']\n        res['eff_pemel'] = (res['m_pemel'] * par_pemel['HHV'] /\n                            (res['p_pemel'] * 3600.))\n        return res\n\n    def current_to_mh2(self, current):\n        \"\"\"\n        When current is provided, this function determines the\n        corresponding hydrogen mass flow rate per hour.\n\n        Parameters\n        ----------\n        current : float\n            The electrolyzer input current [A].\n\n        Returns\n        -------\n        m_h2 : float\n            The produced hydrogen mass flow rate [kg/h].\n\n        \"\"\"\n        far_cons = 96485.\n        m_h2 = current / (2. * far_cons) * 2.02e-3 * 3600.\n\n        return m_h2\n\n    def mh2_to_power(self, m_h2):\n        \"\"\"\n        When the hydrogen mass flow rate is provided, this function determines\n        the corresponding required power per hour.\n\n        Parameters\n        ----------\n        m_h2 : float\n            The produced hydrogen mass flow rate [kg/h].\n\n        Returns\n        -------\n        power : float\n            The required power to produce the hydrogen [W].\n\n        \"\"\"\n\n        far_cons = 96485.\n        current = m_h2 * (2. * far_cons) / (2.02e-3 * 3600. *\n                                            self.n_pemel_array)\n        power = self.pemel(current)['p_pemel']\n\n        return power\n\n    def polyfit_pemel(self):\n        \"\"\"\n        The electrolyzer stack is evaluated over a range of input currents.\n        Following these evaluations, a polynomial is fitted on the\n        power - current relation of the electrolyzer. This polynomial enables\n        to rapidly determine the input current when a certain amount of power\n        is available. Since this relation is fairly linear, the polynomial\n        should reach good agreement with the actual power - current relation,\n        while maintaining the level of fidelity of the actual model.\n\n        \"\"\"\n\n        # evaluate the electrolyzer stack for a set of currents\n        i_list = np.arange(start=3, stop=200, step=4)\n        p_pemel = np.zeros(len(i_list))\n        for index, i in enumerate(i_list):\n            res = self.pemel(i)\n            p_pemel[index] = res['p_pemel']\n\n        # generate a polynomial fitted on the power - current points\n        self.p_to_i_pemel = polyfit_func(p_pemel, i_list)\n\n    #####################\n    # compressor module #\n    #####################\n\n    def compressor(self, m_h2):\n        \"\"\"\n        The compressor module defined the required compression power to\n        compress the hydrogen mass flow rate [3].\n\n        [3] Zhao, L., Brouwer, J., & Samuelsen, S. (2014). Dynamic analysis of\n        a self-sustainable renewable hydrogen fueling station. ASME 2014 12th\n        International Conference on Fuel Cell Science, Engineering and\n        Technology, FUELCELL 2014 Collocated with the ASME 2014 8th\n        International Conference on Energy Sustainability.\n        https://doi.org/10.1115/FuelCell2014-6330\n\n        Parameters\n        ----------\n        m_h2 : float\n            Hydrogen mass flow rate [kg/h].\n\n        Returns\n        -------\n        power : float\n            The required compression power [W].\n\n        \"\"\"\n\n        # convert the flow rate into kg/s\n        m_h2 *= 1. / 3600.\n\n        par_c = {\n            'T_in': 353.,\n            'p_in': 1.,\n            'p_out': 350.,\n            'eta_c': 0.85,\n            'R': 4.124,\n            'n': 1.609,\n        }\n\n        power = (m_h2 *\n                 par_c['n'] *\n                 par_c['R'] *\n                 par_c['T_in'] *\n                 ((par_c['p_out'] /\n                   par_c['p_in'])**((par_c['n'] -\n                                     1.) /\n                                    par_c['n']) -\n                     1.) *\n                 1000. /\n                 (par_c['eta_c'] *\n                     (par_c['n'] -\n                      1.)))\n\n        return power\n\n    def polyfit_pemel_compr(self):\n        \"\"\"\n        The power consumption by the electrolyzer stack and compressor are\n        evaluated over a range of hydrogen mass flow rates. Following these\n        evaluations, a polynomial is fitted on the mass flow rate - power\n        relation. This polynomial enables to rapidly determine the input\n        mass flow rate when a certain amount of power is available.\n        Since this relation is fairly linear, the polynomial should reach good\n        agreement with the actual mass flow rate - power relation, while\n        maintaining the level of fidelity of the actual model.\n\n        \"\"\"\n\n        # the electrolyzer array operating limits\n        pemel_lower_lim = self.par['n_pemel'] * 10.\n        pemel_upper_lim = self.par['n_pemel'] * 1e3\n\n        # the operating current at these limits\n        current_ub = self.p_to_i_pemel(pemel_upper_lim)\n        current_lb = self.p_to_i_pemel(pemel_lower_lim)\n\n        # the characteristics of the electrolyzer at the limits\n        pemel_ub = self.pemel(current_ub)\n        pemel_lb = self.pemel(current_lb)\n\n        # the compression power at the hydrogen production limits\n        p_compr_ub = self.compressor(pemel_ub['m_pemel'])\n        p_compr_lb = self.compressor(pemel_lb['m_pemel'])\n\n        # the compression and electrolyzer power at the limits\n        pemel_compr_ub = pemel_ub['p_pemel'] + p_compr_ub\n        pemel_compr_lb = pemel_lb['p_pemel'] + p_compr_lb\n\n        # the operating bounds for the compressor and electrolyzer\n        self.bounds = {'pemel_lb': pemel_lb,\n                       'pemel_ub': pemel_ub,\n                       'pemel_compr_lb': pemel_compr_lb,\n                       'pemel_compr_ub': pemel_compr_ub\n                       }\n\n        # evaluate the electrolyzer and compressor for a set of mass flow rates\n        step = pemel_ub['m_pemel'] / 50.\n        m_h2_list = np.arange(start=step, stop=pemel_ub['m_pemel'] - step,\n                              step=step)\n        p_pemel_compr = np.zeros(len(m_h2_list))\n        for index, m_h2 in enumerate(m_h2_list):\n            p_pemel = self.mh2_to_power(m_h2)\n            p_compr = self.compressor(m_h2)\n            p_pemel_compr[index] = p_pemel + p_compr\n\n        # generate a polynomial fitted on the power - mass flow rate points\n        self.p_to_m_pemel_comp = polyfit_func(p_pemel_compr, m_h2_list)\n\n    #############################\n    # tank and dispenser module #\n    #############################\n\n    def tank(self):\n        \"\"\"\n\n        The maximum storage capacity of the hydrogen tank.\n\n        Returns\n        -------\n        m_max : float\n            The hydrogen storage capacity. [kg]\n\n        \"\"\"\n\n        # conversion from energy (kWh) into mass (kg)\n        m_max = self.par['n_tank'] / 33.33\n\n        return m_max\n\n    def dispenser(self, m_h2):\n        \"\"\"\n        The cooling power is determined before the dispensation of the hydrogen\n        into the bus fuel tank [4].\n\n        [4] A. Elgowainy, K. Reddi, D. Y. Lee, N. Rustagi, and E. Gupta,\n        “Techno-economic and thermodynamic analysis of pre-cooling systems at\n        gaseous hydrogen refueling stations,” Int. J. Hydrogen Energy, vol. 42,\n        no. 49, pp. 29067–29079, Dec. 2017.\n\n        Parameters\n        ----------\n        m_h2 : float\n            Hydrogen mass flow rate [kg/h].\n\n        Returns\n        -------\n        power : float\n            The required cooling power for dispensation [W].\n\n        \"\"\"\n\n        demand_day_h2 = sum(self.load_h2[:24])\n\n        if m_h2 < 1e-6 or demand_day_h2 < 1e-4:\n            power = 0.\n        else:\n            t_amb = 10.4\n            m_h2 *= 1. / 3600.\n            ei_pcu = ((0.3 / (1.6 * np.exp(-0.018 * t_amb))) +\n                      (25. * np.log(t_amb) - 21.) / demand_day_h2)  # kWhe/kgH2\n            power = ei_pcu * m_h2 * 3.6e6  # W\n\n        return power\n\n    ##############################\n    # management strategy module #\n    ##############################\n\n    def p_for_inst_demand(self, m_h2):\n        \"\"\"\n        When a hydrogen demand is provided, this method determines the power\n        to generate the hydrogen in the electrolyzer array and the power to\n        compress the hydrogen in the compressor. The method indicates when the\n        electrolyzer array capacity is not sufficient to produce the desired\n        hydrogen mass flow rate.\n\n        Parameters\n        ----------\n        m_h2 : float\n            Hydrogen mass flow rate [kg/h].\n\n        Returns\n        -------\n        p_pemel : float\n            The required electrolyzer array power [W].\n        p_compr : float\n            The required compressor power [W].\n        bool\n            True when the electrolyzer capacity is insufficient to produce the\n            hydrogen.\n\n        \"\"\"\n\n        # check if the desired hydrogen can be produced by the PEM\n        if m_h2 > self.bounds['pemel_ub']['m_pemel']:\n            return 0., 0., True\n\n        # determine the power needed from electrolyzer and compressor to\n        # deliver the required hydrogen mass flow rate\n        p_pemel = self.mh2_to_power(m_h2)\n        p_compr = self.compressor(m_h2)\n        self.res['running_hours_pemel'] += 1.\n        return p_pemel, p_compr, False\n\n    def prod_mh2(self, p_in):\n        \"\"\"\n        When there is power available to produce hydrogen, this method\n        distributes this power over the electrolyzer array and compressor,\n        such that the hydrogen is produced and compressed with this given\n        power. If the given power will lead to an excess of hydrogen (i.e\n        the storage tank is full before the energy is fully consumed), the\n        power supplied to the electrolyzer array and compressor is recalculated\n        such that no excess hydrogen is produced.\n\n        Parameters\n        ----------\n        p_in : float\n            The power available to produce hydrogen [W].\n\n        Returns\n        -------\n        p_pemel : float\n            The power consumed by the electrolyzer array [W].\n        p_compr : float\n            The power consumed by the compressor [W].\n\n        \"\"\"\n\n        no_run = False\n\n        # produce H2 only if tank is not yet full\n        # nothing happens when the desired power is under the lower limit\n        if self.m_h2 >= self.m_h2_max or p_in < self.bounds['pemel_compr_lb']:\n            p_pemel = 0.\n            p_compr = 0.\n            no_run = True  # the electrolyzer did not run\n\n        # if the power is higher than the upper limit, work at the upper limit\n        elif p_in > self.bounds['pemel_compr_ub']:\n\n            # this is what can be produced at the upper limit for H2\n            m_h2 = self.bounds['pemel_ub']['m_pemel']\n\n            # produced hydrogen is added to the tank\n            self.m_h2 += m_h2\n\n        else:\n\n            # quantify the hydrogen created with the available power\n            m_h2 = self.p_to_m_pemel_comp(p_in)\n\n            # produced hydrogen is added to the tank\n            self.m_h2 += m_h2\n\n        # if the new hydrogen capacity exceeds the maximum storage capacity\n        if self.m_h2 > self.m_h2_max:\n\n            # the hydrogen that is still allowed in the tank\n            m_h2 -= (self.m_h2 - self.m_h2_max)\n\n            # the power for the PEM to generate this hydrogen\n            p_rev = self.mh2_to_power(m_h2)\n\n            # check if this power is higher than the lower limit for the PEM\n            if p_rev > self.bounds['pemel_lb']['p_pemel']:\n                self.m_h2 = self.m_h2_max\n\n            # the space left in the tank is too small\n            else:\n                self.m_h2 -= (m_h2 + self.m_h2 - self.m_h2_max)\n                p_pemel = 0.\n                p_compr = 0.\n                no_run = True\n\n        # if power is applied to the PEM and compessor\n        if not no_run:\n            p_compr = self.compressor(m_h2)\n            p_pemel = self.mh2_to_power(m_h2)\n            self.res['running_hours_pemel'] += 1.\n\n        return p_pemel, p_compr\n\n    def extract_h2_from_tank(self, demand):\n        \"\"\"\n        Extract the hydrogen demand from the storage tank. If more hydrogen is\n        demanded than available in the tank, extract only the available amount\n        of hydrogen.\n\n        Parameters\n        ----------\n        demand : float\n            The hydrogen demand. [kg]\n\n        Returns\n        -------\n        demand_left : float\n            The amount of hydrogen demand that is not covered by the tank. [kg]\n\n        \"\"\"\n\n        # extract the hydrogen from the tank\n        self.m_h2 -= demand\n\n        if self.m_h2 < self.m_h2_min:\n\n            # if the demand was too high, set the tank to its minimum level and\n            # define the demand that was not covered by the tank\n            demand_left = self.m_h2_min - self.m_h2\n            self.m_h2 = self.m_h2_min\n        else:\n\n            # if the tank covers the demand, there is no hydrogen demand left\n            demand_left = 0.\n\n        return demand_left\n\n    ##########################################\n    # model evaluation\n    ##########################################\n\n    def evaluation(self):\n        \"\"\"\n\n        This is the main method of the Evaluation class.\n        For each hour, the power management strategy is applied.\n        The hydrogen demand is extracted from the hydrogen tank, when\n        sufficient hydrogen is available in the tank. When the hydrogen in the\n        tank does not comply with the hydrogen demand, the power to run the\n        electrolyzer array and compressor is calculated to generate and\n        compress the remaining hydrogen. To generate this power and the\n        dispensation power, the photovoltaic power is called upon first. If\n        necessary, the remaining power is covered by the grid.\n        When the hydrogen tank does comply with the hydrogen demand, the\n        photovoltaic power is used to cover the required dispensation power.\n        When excess photovoltaic power is present, this power is used to\n        generate and compress hydrogen in the electrolyzer array and\n        compressor, respectively. Finally, the lifetime, cost and\n        CO2-emission of the system are quantified.\n\n        Returns\n        -------\n        bool\n            True when the capacity of the electrolyzer array is sufficient to\n            cover the instantaneous hydrogen demand during the year.\n\n        \"\"\"\n\n        n_compr = np.zeros(self.length)\n        n_disp = np.zeros(self.length)\n        n_dcdc_pem = np.zeros(self.length)\n        n_dcac = np.zeros(self.length)\n\n        self.res['m_h2_array'] = np.ones(self.length)\n        self.res['grid_e_buy'] = np.ones(self.length)\n        self.res['grid_e_sold'] = np.ones(self.length)\n        self.res['grid_co2'] = 0.\n\n        # get the hourly photovoltaic array power\n        self.photovoltaic()\n\n        for t in range(self.length):\n            e_grid_buy = 0.\n            e_grid_sold = 0.\n\n            # define the power for dispensation\n            p_disp = self.dispenser(self.load_h2[t])\n            n_disp[t] = p_disp\n\n            # define if there is any H2 demand left after assessing the tank\n            demand_left = self.extract_h2_from_tank(self.load_h2[t])\n            if demand_left > 0.:\n\n                # power needed by the PEM and compressor to generate the demand\n                p_pemel, p_compr, check = self.p_for_inst_demand(demand_left)\n                n_dcdc_pem[t] = p_pemel\n                n_compr[t] = p_compr\n\n                if check:\n                    return False\n\n                # positive if the PV energy can comply with the PEM power\n                net_p_1 = self.res['p_pv'][t] - p_pemel\n\n                if net_p_1 > 0.:\n                    # if yes, check if remaining PV power can comply with the\n                    # compressor and dispensation demand\n                    net_p_2 = net_p_1 - (p_compr + p_disp)\n\n                    if net_p_2 > 0.:\n                        # when still excess power available, sell to the grid\n                        e_grid_sold = net_p_2\n                        n_dcac[t] = e_grid_sold\n\n                    else:\n                        # if the compressor and dispensation demand cannot be\n                        # covered, buy remaining demand from the grid\n                        # (compressor and dispensation are AC-powered)\n                        e_grid_buy = abs(net_p_2)\n\n                else:\n                    # if PEM, compressor and dispensation cannot be covered by\n                    # PV energy, buy required electricity from the grid\n                    # only power for PEM has to pass through AC-DC conversion\n                    p_to_buy = abs(net_p_1) + p_compr + p_disp\n                    e_grid_buy = p_to_buy\n                    n_dcac[t] = abs(net_p_1)\n\n            else:  # excess PV energy available to generate hydrogen\n\n                # use solar energy to power the dispensation\n                net_p = self.res['p_pv'][t] - p_disp\n\n                if net_p <= 0.:\n                    # remaining power covered by the grid\n                    e_grid_buy = abs(net_p)\n\n                    # the solar power is all used for dispensation and thus\n                    # sent through the DC-AC converter\n                    n_dcac[t] = self.res['p_pv'][t]\n\n                else:\n\n                    # quantify how much of the remaining PV energy can be used\n                    # by the PEM and compressor to generate hydrogen\n                    p_pemel, p_compr = self.prod_mh2(net_p)\n                    n_compr[t] = p_compr\n\n                    # the remaining excess PV energy can be sold\n                    e_grid_sold = net_p - p_pemel - p_compr\n                    n_dcac[t] = p_disp + e_grid_sold + p_compr\n                    n_dcdc_pem[t] = p_pemel\n\n            # store evolution of storage tank, electricity bought/sold\n            # and the CO2 amount from buying grid electricity\n            self.res['m_h2_array'][t] = ((self.m_h2 - self.m_h2_min) /\n                                         (self.m_h2_max - self.m_h2_min))\n            self.res['grid_e_buy'][t] = e_grid_buy\n            self.res['grid_e_sold'][t] = e_grid_sold\n            self.res['grid_co2'] += e_grid_buy * self.par['co2_elec']\n\n        # define the capacity of the converters, compression and cooling\n        self.res['n_compr'] = max(n_compr) / 1e3\n        self.res['n_cooling'] = max(n_disp) / 1e3\n        self.res['n_dcdc_pemel'] = max(n_dcdc_pem) / 1e3\n        self.res['n_dcac'] = max(n_dcac) / 1e3\n\n        # the cost of annual diesel consumption\n        self.res['diesel_cost'] = self.load_diesel * self.diesel_profile\n\n        # determine the lifetime of the electrolyzer\n        self.lifetime()\n\n        # determine the system cost\n        self.cost()\n\n        # determine the system annual CO2 emission\n        self.lca()\n\n        return True\n\n    def lifetime(self):\n        \"\"\"\n\n        The lifetime method determines the lifetime of\n        the electrolyzer array, based on the number of\n        operating hours during the evaluated year.\n\n        \"\"\"\n\n        # lifetime of the electrolyzer array\n        if self.res['running_hours_pemel'] == 0.:\n            self.res['life_pemel'] = 1e8\n        else:\n            self.res['life_pemel'] = (self.par['life_pemel'] /\n                                      self.res['running_hours_pemel'])\n\n    def cost(self):\n        \"\"\"\n\n        Based on the capital recovery factor, the CAPEX,\n        OPEX and replacement cost of the system components,\n        the levelized cost of mobility [euro/km] is determined. The formula\n        for the annualized system cost is adopted from Coppitters et al. [5].\n\n        [5] Coppitters, D., De Paepe, W., & Contino, F. (2020). Robust design\n            optimization and stochastic performance analysis of a\n            grid-connected photovoltaic system with battery storage and\n            hydrogen storage. Energy, 213, 118798.\n            https://doi.org/10.1016/j.energy.2020.118798\n        \"\"\"\n\n        # the capital recovery factor\n        inv_rate = ((self.par['int_rate'] - self.par['infl_rate']) /\n                    (1. + self.par['infl_rate']))\n        crf = (((1. + inv_rate)**self.par['life_sys'] - 1.) /\n               (inv_rate * (1. + inv_rate)**self.par['life_sys']))**(-1)\n\n        # annual cost of photovoltaic array and DC-DC converter\n        pv_cost = self.par['n_pv'] * (crf * self.par['capex_pv'] +\n                                      self.par['opex_pv'])\n        pv_dcdc_cost = self.res['n_dcdc_pv'] * (self.par['capex_dcdc'] *\n                                                (crf + self.par['opex_dcdc']))\n        components_cost = pv_cost + pv_dcdc_cost\n\n        # annual cost of electrolyzer array and DC-DC converter\n        pemel_cost = self.par['n_pemel'] * (self.par['capex_pemel'] *\n                                            (crf + self.par['opex_pemel']))\n        pemel_dcdc_cost = (self.res['n_dcdc_pemel'] *\n                           (self.par['capex_dcdc'] *\n                            (crf + self.par['opex_dcdc'])))\n        components_cost += pemel_cost + pemel_dcdc_cost\n\n        # annual cost of hydrogen storage tank\n        tank_cost = self.par['n_tank'] * (self.par['capex_tank'] *\n                                          (crf + self.par['opex_tank']))\n        components_cost += tank_cost\n\n        # annual cost of compressor\n        compressor_cost = (self.par['capex_compr'] *\n                           (self.res['n_compr']**0.5861) *\n                           (crf + self.par['opex_compr']))\n        components_cost += compressor_cost\n\n        # annual cost of dispenser\n        dispenser_cost = self.par['n_disp'] * (self.par['capex_disp'] *\n                                               (crf + self.par['opex_disp']))\n        components_cost += dispenser_cost\n\n        # annual cost of dispensation cooling\n        cooling_cost = self.res['n_cooling'] * (self.par['capex_cool'] *\n                                                (crf + self.par['opex_cool']))\n        components_cost += cooling_cost\n\n        # annual cost of DC-AC inverter\n        dcac_cost = self.res['n_dcac'] * (self.par['capex_dcac'] *\n                                          (crf + self.par['opex_dcac']))\n        components_cost += dcac_cost\n\n        # annual cost of buses\n        h2_bus_cost = (self.par['capex_h2_bus'] * crf + self.par['n_km_bus'] *\n                       365. * self.par['opex_h2_bus']) * self.par['n_h2_bus']\n        diesel_bus_cost = (self.par['capex_diesel_bus'] * crf +\n                           self.par['opex_diesel_bus'] * 365. *\n                           self.par['n_km_bus']) * (self.par['n_bus'] -\n                                                    self.par['n_h2_bus'])\n        components_cost += h2_bus_cost + diesel_bus_cost\n\n        # annual replacement cost of the electrolyzer and buses\n        arc = crf * sum([(1. + inv_rate)**(-(i + 1.) *\n                                           self.res['life_pemel']) *\n                         self.par['n_pemel'] *\n                         self.par['repl_pemel'] *\n                         self.par['capex_pemel'] for\n                         i in range(int(self.par['life_sys'] /\n                                        self.res['life_pemel']))])\n        arc += crf * sum([(1. + inv_rate)**(-(i + 1.) * 10.) *\n                          self.par['n_h2_bus'] * self.par['repl_h2_bus']\n                          for i in range(int(self.par['life_sys'] / 10.))])\n        arc += crf * sum([(1. + inv_rate)**(-(i + 1.) * 10.) *\n                          (self.par['n_bus'] - self.par['n_h2_bus']) *\n                          self.par['repl_diesel_bus'] for i in\n                          range(int(self.par['life_sys'] / 10.))])\n\n        grid_e_cost = sum(self.res['grid_e_buy'] * self.elec_profile)\n        grid_e_gain = sum(self.res['grid_e_sold'] * self.elec_profile_sale)\n\n        # total annual cost\n        cost = (arc + components_cost + grid_e_cost - grid_e_gain +\n                sum(self.res['diesel_cost']))\n\n        # levelized cost of mobility in euro/km\n        self.res['lcom'] = cost / (self.par['n_km_bus'] * self.par['n_bus'] *\n                                   365.)\n\n    def lca(self):\n        \"\"\"\n        The life cycle assessment is performed based on the CO2 emissions from\n        constructing the system components and the emissions related to\n        consuming grid electricity and diesel. The annual CO2-equivalent\n        emissions of the system is divided by the annual distance covered by\n        the bus fleet, resulting in the levelized cost of mobility.\n\n        \"\"\"\n\n        # annual CO2 emission of photovoltaic array production\n        pv_co2 = self.par['n_pv'] * self.par['co2_pv']\n        pv_dcdc_co2 = self.res['n_dcdc_pv'] * self.par['co2_dcdc']\n        comp_co2 = pv_co2 + pv_dcdc_co2\n\n        # annual CO2 emission of electrolyzer array production\n        pemel_co2 = (self.par['n_pemel'] * self.par['co2_pemel'] *\n                     (1 + int(self.par['life_sys'] / self.res['life_pemel'])))\n        pemel_dcdc_co2 = self.res['n_dcdc_pemel'] * self.par['co2_dcdc']\n        comp_co2 += pemel_co2 + pemel_dcdc_co2\n\n        # annual CO2 emission of hydrogen storage tank production\n        tank_co2 = self.par['n_tank'] / 33.33 * 16. * self.par['co2_tank']\n        comp_co2 += tank_co2\n\n        # annual CO2 emission of compressor production\n        compressor_co2 = self.res['n_compr'] * self.par['co2_compr']\n        comp_co2 += compressor_co2\n\n        # annual CO2 emission of dispenser production\n        dispenser_co2 = self.par['n_disp'] * self.par['co2_disp']\n        comp_co2 += dispenser_co2\n\n        # annual CO2 emission of cooling unit production\n        cooling_co2 = self.res['n_cooling'] * self.par['co2_cool']\n        comp_co2 += cooling_co2\n\n        # annual CO2 emission of DC-AC inverter production\n        dcac_co2 = self.res['n_dcac'] * self.par['co2_dcac']\n        comp_co2 += dcac_co2\n\n        # annual CO2 emission of diesel and hydrogen engine production\n        diesel_engine_co2 = (self.par['co2_diesel_engine'] * 200. *  # 200 kW\n                             (self.par['n_bus'] - self.par['n_h2_bus']))\n        h2_engine_co2 = self.par['co2_fc_engine'] * 200. * self.par['n_h2_bus']\n        comp_co2 += ((diesel_engine_co2 + h2_engine_co2) *\n                     (1 + int(self.par['life_sys'] / 10.)))  # 10y lifetime\n\n        # annual CO2 emission of diesel consumption\n        diesel_co2 = sum(self.load_diesel) * self.par['co2_diesel']\n\n        # annual CO2 emission of system\n        co2 = (comp_co2 / self.par['life_sys'] + self.res['grid_co2'] +\n               diesel_co2)\n\n        # CO2 emitted per km driven by the fleet\n        self.res['lco2'] = co2 / (self.par['n_km_bus'] * self.par['n_bus'] *\n                                  365. * self.length / 8760.)\n\n    def print_results(self, succes=True):\n        \"\"\"\n\n        This method prints the levelized cost of electricity,\n        the self-sufficiency ratio and the annual energy produced\n        by the photovoltaic array.\n\n        \"\"\"\n        if not succes:\n            print(\"\"\"Evaluation failed: the electrolyzer array capacity\n                     of %f kW was not sufficient to cover the instantaneous\n                     hydrogen demand.\"\"\" % self.par['n_pemel'])\n        else:\n            print('outputs:')\n            print('LCOE:'.ljust(30) + '%.5f euro/km' % self.res['lcom'])\n            print('LCO2:'.ljust(30) + '%.5f kg co2-eq/km' % self.res['lco2'])\n            print(\n                'PV electricity generated:'.ljust(30) +\n                '%.5f MWh' %\n                (sum(self.res['p_pv']) / 1e6))\n            print('grid energy bought:'.ljust(30) + '%.5f MWh' %\n                  (sum(self.res['grid_e_buy']) / 1e6))\n            print('grid energy sold:'.ljust(30) + '%.5f MWh' %\n                  (sum(self.res['grid_e_sold']) / 1e6))\n            print(\n                'compressor capacity:'.ljust(30) +\n                '%.5f kW' %\n                self.res['n_compr'])\n            print(\n                'cooling capacity:'.ljust(30) +\n                '%.5f kW' %\n                self.res['n_cooling'])\n            print('life electrolyzer:'.ljust(30) + '%.5f year' %\n                  self.res['life_pemel'])\n\n            plt.plot(self.res['m_h2_array'])\n            plt.show(block=False)\n\n\ndef polyfit_func(x_in, y_in, threshold=0.99999999):\n    \"\"\"\n    The function fits a polynomial to the points of x_in and y_in. The\n    polynomial starts with order 1. To evaluate its performance, the R-squared\n    performance indicator is quantified. If the value for R-squared does\n    not reach the defined threshold, the polynomial order is increased and\n    the polynomial is fitted again on the points, until the threshold is\n    satisfied. Once satisfied, the function returns the polynomial.\n\n    Parameters\n    ----------\n    x_in : ndarray\n        The x-coordinates for the sample points.\n    y_in : ndarray\n        The y-coordinates for the sample points.\n    threshold : float, optional\n        The threshold for the R-squared parameter. The default is 0.99999.\n\n    Returns\n    -------\n    poly_func : numpy.poly1d\n        A one-dimensional polynomial.\n\n    \"\"\"\n    order = 0\n    r_squared = 0.\n    while r_squared < threshold:\n        order += 1\n\n        # the polynomial\n        poly_coeff = np.polyfit(x_in, y_in, order)\n        poly_func = np.poly1d(poly_coeff)\n\n        # r-squared\n        yhat = poly_func(x_in)\n        ybar = np.sum(y_in) / len(y_in)\n        ssreg = np.sum((yhat - ybar)**2.)\n        sstot = np.sum((y_in - ybar)**2.)\n        r_squared = ssreg / sstot\n\n    return poly_func\n", "meta": {"hexsha": "e06d2e26f85725d583a8d9d09b8c581a75fbc65e", "size": 42956, "ext": "py", "lang": "Python", "max_stars_repo_path": "rheia/CASES/H2_MOBILITY/h2_mobility.py", "max_stars_repo_name": "Tsiri/RHEIA", "max_stars_repo_head_hexsha": "a7bacd72e5515242e78ee413f9e8959ab4f1115d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-29T08:26:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T08:26:49.000Z", "max_issues_repo_path": "rheia/CASES/H2_MOBILITY/h2_mobility.py", "max_issues_repo_name": "Tsiri/RHEIA", "max_issues_repo_head_hexsha": "a7bacd72e5515242e78ee413f9e8959ab4f1115d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rheia/CASES/H2_MOBILITY/h2_mobility.py", "max_forks_repo_name": "Tsiri/RHEIA", "max_forks_repo_head_hexsha": "a7bacd72e5515242e78ee413f9e8959ab4f1115d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-25T18:55:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-25T18:55:10.000Z", "avg_line_length": 37.2881944444, "max_line_length": 79, "alphanum_fraction": 0.5511220784, "include": true, "reason": "import numpy", "num_tokens": 10280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.18902096894735457}}
{"text": "\"\"\"\nThis module contains the class RacosClassification, which provides a classifier for all Racos algorithms.\n\nAuthor:\n    Yu-Ren Liu\n\nUpdated by:\n    Ze-Wen Li\n\"\"\"\n\nfrom zoopt.dimension import Dimension, Dimension2\nfrom zoopt.utils.tool_function import ToolFunction\nimport copy\nimport numpy as np\nfrom zoopt.utils.zoo_global import gl\n\n\nclass RacosClassification:\n    \"\"\"\n    This class implements a classifier used by all Racos algorithms.\n    \"\"\"\n\n    def __init__(self, dim, positive, negative, ub=1):\n        \"\"\"\n        Initialization\n\n        :param dim: a Dimension object\n        :param positive: positive population\n        :param negative: negative population\n        :param ub: uncertain bits, which is a parameter for Racos\n        \"\"\"\n        self.__solution_space = dim\n        self.__sample_region = []\n        self.__label_index = []\n        # Solution\n        self.__positive_solution = positive\n        self.__negative_solution = negative\n        self.__x_positive = None\n        self.__uncertain_bit = ub\n\n        regions = dim.get_regions()\n        for i in range(dim.get_size()):\n            temp = [regions[i][0], regions[i][1]]\n            self.__sample_region.append(temp)\n        return\n\n    def reset_classifier(self):\n        \"\"\"\n        Reset this classifier.\n\n        :return: no return value\n        \"\"\"\n        regions = self.__solution_space.get_regions()\n        for i in range(self.__solution_space.get_size()):\n            self.__sample_region[i][0] = regions[i][0]\n            self.__sample_region[i][1] = regions[i][1]\n            self.__label_index = []\n        self.__x_positive = None\n        return\n\n    # This algos always works, whether discrete or continuous, we always use this function.\n    def mixed_classification(self):\n        \"\"\"\n        The process to train this classifier, which can handle mixed search space(continuous and discrete).\n\n        :return: no return value\n        \"\"\"\n        if type(self.__solution_space) == Dimension:\n            self.__x_positive = self.__positive_solution[np.random.randint(\n                0, len(self.__positive_solution))]\n            len_negative = len(self.__negative_solution)\n            index_set = list(range(self.__solution_space.get_size()))\n            remain_index_set = list(range(self.__solution_space.get_size()))\n            types = self.__solution_space.get_types()\n            order = self.__solution_space.get_order()\n            while len_negative > 0:\n                if len(remain_index_set) == 0:\n                    ToolFunction.log('ERROR: sampled two same solutions, please raise issues on github')\n                k = remain_index_set[np.random.randint(0, len(remain_index_set))]\n                x_pos_k = self.__x_positive.get_x_index(k)\n                # continuous\n                if types[k] is True:\n                    x_negative = self.__negative_solution[\n                        np.random.randint(0, len_negative)]\n                    x_neg_k = x_negative.get_x_index(k)\n                    if x_pos_k < x_neg_k:\n                        r = np.random.uniform(x_pos_k, x_neg_k)\n                        if r < self.__sample_region[k][1]:\n                            self.__sample_region[k][1] = r\n                            i = 0\n                            while i < len_negative:\n                                if self.__negative_solution[i].get_x_index(k) >= r:\n                                    len_negative -= 1\n                                    itemp = self.__negative_solution[i]\n                                    self.__negative_solution[i] = self.__negative_solution[len_negative]\n                                    self.__negative_solution[len_negative] = itemp\n                                else:\n                                    i += 1\n                    else:\n                        r = np.random.uniform(x_neg_k, x_pos_k)\n                        if r > self.__sample_region[k][0]:\n                            self.__sample_region[k][0] = r\n                            i = 0\n                            while i < len_negative:\n                                if self.__negative_solution[i].get_x_index(k) <= r:\n                                    len_negative -= 1\n                                    itemp = self.__negative_solution[i]\n                                    self.__negative_solution[i] = self.__negative_solution[len_negative]\n                                    self.__negative_solution[len_negative] = itemp\n                                else:\n                                    i += 1\n                # discrete\n                else:\n                    if order[k] is True:\n                        x_negative = self.__negative_solution[\n                            np.random.randint(0, len_negative)]\n                        x_neg_k = x_negative.get_x_index(k)\n                        if x_pos_k < x_neg_k:\n                            # different from continuous version\n                            r = np.random.randint(x_pos_k, x_neg_k)\n                            if r < self.__sample_region[k][1]:\n                                self.__sample_region[k][1] = r\n                                i = 0\n                                while i < len_negative:\n                                    if self.__negative_solution[i].get_x_index(k) >= r:\n                                        len_negative -= 1\n                                        itemp = self.__negative_solution[i]\n                                        self.__negative_solution[i] = self.__negative_solution[len_negative]\n                                        self.__negative_solution[len_negative] = itemp\n                                    else:\n                                        i += 1\n                        else:\n                            r = np.random.randint(x_neg_k, x_pos_k + 1)\n                            if r > self.__sample_region[k][0]:\n                                self.__sample_region[k][0] = r\n                                i = 0\n                                while i < len_negative:\n                                    if self.__negative_solution[i].get_x_index(k) <= r:\n                                        len_negative -= 1\n                                        itemp = self.__negative_solution[i]\n                                        self.__negative_solution[i] = self.__negative_solution[len_negative]\n                                        self.__negative_solution[len_negative] = itemp\n                                    else:\n                                        i += 1\n                    else:\n                        delete = 0\n                        i = 0\n                        while i < len_negative:\n                            if self.__negative_solution[i].get_x_index(k) != x_pos_k:\n                                len_negative -= 1\n                                delete += 1\n                                itemp = self.__negative_solution[i]\n                                self.__negative_solution[i] = self.__negative_solution[len_negative]\n                                self.__negative_solution[len_negative] = itemp\n                            else:\n                                i += 1\n                        remain_index_set.remove(k)\n                        if delete != 0:\n                            index_set.remove(k)\n                        if len(index_set) == 0:\n                            index_set.append(k)\n            self.set_uncertain_bit(index_set)\n            return\n        elif type(self.__solution_space) == Dimension2:\n            self.__x_positive = self.__positive_solution[np.random.randint(0, len(self.__positive_solution))]\n            len_negative = len(self.__negative_solution)\n            index_set = list(range(self.__solution_space.get_size()))\n            remain_index_set = list(range(self.__solution_space.get_size()))\n            types = self.__solution_space.get_types()\n            order_or_precision = self.__solution_space.get_order_or_precision()\n            while len_negative > 0:\n                if len(remain_index_set) == 0:\n                    ToolFunction.log('ERROR: sampled two same solutions, please raise issues on github')\n                k = remain_index_set[np.random.randint(0, len(remain_index_set))]\n                x_pos_k = self.__x_positive.get_x_index(k)\n\n                # continuous\n                if types[k]:\n                    x_negative = self.__negative_solution[np.random.randint(0, len_negative)]\n                    x_neg_k = x_negative.get_x_index(k)\n\n                    if x_pos_k < x_neg_k:\n                        r = round(np.random.uniform(x_pos_k, x_neg_k), gl.float_precisions[k])\n                        if r < self.__sample_region[k][1]:\n                            self.__sample_region[k][1] = r\n                            i = 0\n                            while i < len_negative:\n                                if self.__negative_solution[i].get_x_index(k) >= r:\n                                    len_negative -= 1\n                                    itemp = self.__negative_solution[i]\n                                    self.__negative_solution[i] = self.__negative_solution[len_negative]\n                                    self.__negative_solution[len_negative] = itemp\n                                else:\n                                    i += 1\n                    else:\n                        r = round(np.random.uniform(x_neg_k, x_pos_k), gl.float_precisions[k])\n                        if r > self.__sample_region[k][0]:\n                            self.__sample_region[k][0] = r\n                            i = 0\n                            while i < len_negative:\n                                if self.__negative_solution[i].get_x_index(k) <= r:\n                                    len_negative -= 1\n                                    itemp = self.__negative_solution[i]\n                                    self.__negative_solution[i] = self.__negative_solution[len_negative]\n                                    self.__negative_solution[len_negative] = itemp\n                                else:\n                                    i += 1\n                # discrete\n                else:\n                    if order_or_precision[k] is True:\n                        x_negative = self.__negative_solution[np.random.randint(0, len_negative)]\n                        x_neg_k = x_negative.get_x_index(k)\n                        if x_pos_k < x_neg_k:\n                            r = np.random.randint(x_pos_k, x_neg_k)\n                            if r < self.__sample_region[k][1]:\n                                self.__sample_region[k][1] = r\n                                i = 0\n                                while i < len_negative:\n                                    if self.__negative_solution[i].get_x_index(k) >= r:\n                                        len_negative -= 1\n                                        itemp = self.__negative_solution[i]\n                                        self.__negative_solution[i] = self.__negative_solution[len_negative]\n                                        self.__negative_solution[len_negative] = itemp\n                                    else:\n                                        i += 1\n                        else:\n                            r = np.random.randint(x_neg_k, x_pos_k + 1)\n                            if r > self.__sample_region[k][0]:\n                                self.__sample_region[k][0] = r\n                                i = 0\n                                while i < len_negative:\n                                    if self.__negative_solution[i].get_x_index(k) <= r:\n                                        len_negative -= 1\n                                        itemp = self.__negative_solution[i]\n                                        self.__negative_solution[i] = self.__negative_solution[len_negative]\n                                        self.__negative_solution[len_negative] = itemp\n                                    else:\n                                        i += 1\n                    else:\n                        delete = 0\n                        i = 0\n                        while i < len_negative:\n                            if self.__negative_solution[i].get_x_index(k) != x_pos_k:\n                                len_negative -= 1\n                                delete += 1\n                                itemp = self.__negative_solution[i]\n                                self.__negative_solution[i] = self.__negative_solution[len_negative]\n                                self.__negative_solution[len_negative] = itemp\n                            else:\n                                i += 1\n                        remain_index_set.remove(k)\n                        if delete != 0:\n                            index_set.remove(k)\n                        if len(index_set) == 0:\n                            index_set.append(k)\n            self.set_uncertain_bit(index_set)\n            return\n\n    def set_uncertain_bit(self, index_set):\n        \"\"\"\n        Choose uncertain bits from iset.\n\n        :param iset: index set\n        :return: no return value\n        \"\"\"\n        ub = min(self.__uncertain_bit, len(index_set))\n        self.__label_index = np.random.choice(index_set, ub, replace=False)\n        return\n\n    def rand_sample(self):\n        \"\"\"\n        Random sample from self.__solution_space.get_dim().\n\n        :return: sampled x\n        \"\"\"\n        if type(self.__solution_space) == Dimension:\n            x = copy.deepcopy(self.__x_positive.get_x())\n            for index in self.__label_index:\n                if self.__solution_space.get_type(index) is True:\n                    x[index] = np.random.uniform(self.__sample_region[index][0], self.__sample_region[index][1])\n                else:\n                    x[index] = np.random.randint(self.__sample_region[index][0], self.__sample_region[index][1] + 1)\n            return x\n        elif type(self.__solution_space) == Dimension2:\n            x = copy.deepcopy(self.__x_positive.get_x())\n            for index in self.__label_index:\n                # continuous\n                if self.__solution_space.get_type(index):\n                    x[index] = round(np.random.uniform(self.__sample_region[index][0], self.__sample_region[index][1]),\n                                     gl.float_precisions[index])\n                # discrete\n                else:\n                    x[index] = np.random.randint(self.__sample_region[index][0], self.__sample_region[index][1] + 1)\n            return x\n\n    def get_sample_region(self):\n        return self.__sample_region\n\n    def get_sample_space(self):\n        if type(self.__solution_space) == Dimension:\n            size = self.__solution_space.get_size()\n            regions = self.__sample_region\n            types = self.__solution_space.get_types()\n            return Dimension(size, regions, types)\n        elif type(self.__solution_space) == Dimension2:\n            types = self.__solution_space.get_types()\n            regions = self.__sample_region\n            order_or_precision = self.__solution_space.get_order_or_precision()\n            dim_li = []\n            for i in range(len(types)):\n                dim_li.append((types[i], regions[i], order_or_precision[i]))\n            return Dimension2(dim_li)\n        else:\n            ToolFunction.log('get sample space wrong')\n\n    def get_positive_solution(self):\n        return self.__positive_solution\n\n    def get_negative_solution(self):\n        return self.__negative_solution\n\n    def get_x_positive(self):\n        return self.__x_positive\n\n    def get_label_index(self):\n        return self.__label_index\n\n    # for debugging\n    def print_neg(self):\n        \"\"\"\n        Print negative population.\n\n        :return: no return value\n        \"\"\"\n        ToolFunction.log('------print neg------')\n        for x in self.__negative_solution:\n            x.print_solution()\n\n    def print_pos(self):\n        \"\"\"\n        Print positive population.\n\n        :return: no return value\n        \"\"\"\n\n        ToolFunction.log('------print pos------')\n        for x in self.__positive_solution:\n            x.print_solution()\n\n    def print_sample_region(self):\n        \"\"\"\n        Print sample region.\n\n        :return: no return value\n        \"\"\"\n        ToolFunction.log('------print sample region------')\n        ToolFunction.log(self.__sample_region)\n", "meta": {"hexsha": "0ab521b96f9034e2463ac7d87b1ff490f7773693", "size": 16481, "ext": "py", "lang": "Python", "max_stars_repo_path": "zoopt/algos/opt_algorithms/racos/racos_classification.py", "max_stars_repo_name": "vishalbelsare/ZOOpt", "max_stars_repo_head_hexsha": "2ca4a9fcc0a7a2e93a225e6e193712d04c26723c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 403, "max_stars_repo_stars_event_min_datetime": "2017-04-19T03:01:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T04:31:27.000Z", "max_issues_repo_path": "zoopt/algos/opt_algorithms/racos/racos_classification.py", "max_issues_repo_name": "vishalbelsare/ZOOpt", "max_issues_repo_head_hexsha": "2ca4a9fcc0a7a2e93a225e6e193712d04c26723c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2017-05-07T10:09:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-18T11:33:00.000Z", "max_forks_repo_path": "zoopt/algos/opt_algorithms/racos/racos_classification.py", "max_forks_repo_name": "vishalbelsare/ZOOpt", "max_forks_repo_head_hexsha": "2ca4a9fcc0a7a2e93a225e6e193712d04c26723c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 97, "max_forks_repo_forks_event_min_datetime": "2017-04-19T03:52:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T13:05:02.000Z", "avg_line_length": 46.0363128492, "max_line_length": 119, "alphanum_fraction": 0.477519568, "include": true, "reason": "import numpy", "num_tokens": 2931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.18902096894735457}}
{"text": "\nfrom pdfminer.psparser import LIT, PSLiteral, PSStackParser, PSKeyword, PSEOF, keyword_name\nfrom pdfminer.pdftypes import PDFObjRef, resolve1, dict_value, stream_value, list_value, PDFStream\n\nfrom PIL import ImageCms\nfrom io import BytesIO\nimport numpy as np\nfrom itertools import product\n\n\nclass colorSpaces:\n    @property\n    def defaults(self):\n        default_values = [\n            (GrayColorSpace, LIT('DeviceGray'), LIT('G')),\n            (RGBColorSpace, LIT('DeviceRGB'), LIT('RGB')),\n            (CMYKColorSpace, LIT('DeviceCMYK'), LIT('CMYK')),\n            (CalGrayColorSpace, LIT('CalGray')),\n            (CalRGBColorSpace, LIT('CalRGB')),\n            (LabColorSpace, LIT('Lab')),\n            (ICCBasedColorSpace, LIT('ICCBased')),\n            (IndexedColorSpace, LIT('Indexed')),\n            (SeparationColorSpace, LIT('Separation')),\n            # (DeviceNColorSpace, LIT('DeviceN')),\n            (PatternColorSpace, LIT('Pattern')),\n            (NColorSpace, LIT('DeviceN')),\n        ]\n        refs = {}\n        for tpl in default_values:\n            for i, x in enumerate(tpl):\n                if i > 0:\n                    refs[x] = tpl[0]\n        return refs\n\n    def parse(self, obj, args=[]):\n        if isinstance(obj, PDFObjRef):\n            obj = resolve1(obj)\n\n        if isinstance(obj, PSLiteral):\n            cs = self.defaults.get(obj)\n            if not cs:\n                return None\n                # raise TypeError('unknown color space: %s' % obj.name)\n            return cs(*args)\n\n        if isinstance(obj, list):\n            return self.parse(obj[0], args=obj[1:])\n\n\nclass ColorSpace:\n    overprintMask = 0x0f\n    pipe = lambda *val: val\n    getGray = pipe\n    getRGB = pipe\n    getCMYK = pipe\n    mapGray = pipe\n    mapRGB = pipe\n    mapCMYK = pipe\n\n\nclass GrayColorSpace(ColorSpace):\n    mode = 'L'\n    ncomps = 1\n\n    def getRGB(self, gray):\n        # [gray] · [1, 1, 1]\n        r = g = b = gray\n        return r, g, b\n\n    def getCMYK(self, gray):\n        # [gray] · [0, 0, 0, 1]\n        c = m = y = 0\n        k = gray\n        return c, m, y, k\n\n\nclass CalGrayColorSpace(GrayColorSpace):\n    whiteX = whiteY = whiteZ = 1\n    blackX = blackY = blackZ = 0\n    gamma = 1\n\n    def __init__(self, obj):\n        obj = resolve1(obj)\n        params = dict_value(obj)\n        self.whiteX, self.whiteY, self.whiteZ = params['WhitePoint']\n        self.blackX, self.blackY, self.blackZ = params['BlackPoint']\n        self.gamma = params['Gamma']\n\n\nclass RGBColorSpace(ColorSpace):\n    mode = 'RGB'\n    ncomps = 3\n\n    def getGray(self, r, g, b):\n        return 0.299 * r + 0.587 * g + 0.114 * b\n\n    def getCMYK(self, r, g, b):\n        c = 1 - r\n        m = 1 - g\n        y = 1 - b\n        k = min(c, m, y)\n        return c - k, m - k, y - k, k\n\n    def mapGray(self, arr):\n        return self.getGray(arr[..., 0], arr[..., 1], arr[..., 2])\n\n    def mapCMYK(self, arr):\n        k = arr.max(-1)\n        out = np.empty_like(arr)\n        out[..., 0] = k - arr[..., 0]\n        out[..., 1] = k - arr[..., 1]\n        out[..., 2] = k - arr[..., 2]\n        k = k[..., np.newaxis]\n        return np.concatenate((out, 255 - k), axis=-1)\n\n\nclass CalRGBColorSpace(RGBColorSpace):\n    matrix = [\n        1,\t0,\t0,\n        0,\t1,\t0,\n        0,\t0,\t1\n    ]\n\n    def __init__(self, obj):\n        obj = resolve1(obj)\n        params = dict_value(obj)\n        self.whiteX, self.whiteY, self.whiteZ = params.get(\n            'WhitePoint', (1, 1, 1))\n        self.blackX, self.blackY, self.blackZ = params.get(\n            'BlackPoint', (0, 0, 0))\n        self.gammaR, self.gammaG, self.gammaB = params.get('Gamma', (1, 1, 1))\n        self.matrix = params.get('Matrix', self.matrix)\n\n\nclass CMYKColorSpace(ColorSpace):\n    mode = 'CMYK'\n    ncomps = 4\n    factors = [\n        [1,\t\t 1,\t     1],\n        [0.1373, 0.1216, 0.1255],\n        [1,\t\t 0.9490, 0],\n        [0.1098, 0.1020, 0],\n        [0.9255, 0,\t     0.5490],\n        [0.1412, 0,\t     0],\n        [0.9294, 0.1098, 0.1412],\n        [0.1333, 0,\t     0],\n        [0,\t\t 0.6784, 0.9373],\n        [0,\t\t 0.0588, 0.1412],\n        [0,\t\t 0.6510, 0.3137],\n        [0,\t\t 0.0745, 0],\n        [0.1804, 0.1922, 0.5725],\n        [0,\t\t 0,\t\t 0.0078],\n        [0.2118, 0.2119, 0.2235],\n        [0,\t\t 0,\t     0]\n    ]\n\n    def getGray(self, c, m, y, k):\n        return 1 - k - 0.3 * c - 0.59 * m - 0.11 * y\n\n    def getRGB(self, c, m, y, k, r=0, g=0, b=0):\n        c1, m1, y1, k1 = 1-c, 1-m, 1-y, 1-k\n        for i, (b0, b1, b2, b3) in enumerate(product([c1, c], [m1, m], [y1, y], [k1, k])):\n            x = b0 * b1 * b2 * b3\n            r += self.factors[i][0] * x\n            g += self.factors[i][1] * x\n            b += self.factors[i][2] * x\n        return r, g, b\n\n    def mapGray(self, arr):\n        return 255 - arr[..., 3] - 0.3 * arr[..., 0] - 0.59 * arr[..., 1] - 0.11 * arr[..., 2]\n\n    def mapRGB(self, arr):\n        arr = arr.astype('float') / 255\n        out = np.empty_like(arr[..., :-1], dtype='float')\n        self.getRGB(*(arr[..., i] for i in range(4)),\n                    *(out[..., i] for i in range(3)))\n        return (out * 255).astype('uint8')\n\n\nxyzrgb = [\n    [3.240449,\t-1.537136,\t-0.498531],\n    [-0.969265,\t1.876011,\t0.041556],\n    [0.055643,\t-0.204026,\t1.057229]\n]\n\n\nclass LabColorSpace(ColorSpace):\n    mode = 'LAB'\n    ncomps = 3\n\n    def __init__(self, obj):\n        obj = resolve1(obj)\n        params = dict_value(obj)\n        self.whiteX, self.whiteY, self.whiteZ = params.get(\n            'WhitePoint', (1, 1, 1))\n        self.blackX, self.blackY, self.blackZ = params.get(\n            'BlackPoint', (0, 0, 0))\n        self.aMin, self.bMin, self.aMax, self.bMax = params.get(\n            'Range', (-100, -100, 100, 100))\n        self.kr = 1 / (\n            xyzrgb[0][0] * self.whiteX +\n            xyzrgb[0][1] * self.whiteY +\n            xyzrgb[0][2] * self.whiteZ\n        )\n        self.kg = 1 / (\n            xyzrgb[1][0] * self.whiteX +\n            xyzrgb[1][1] * self.whiteY +\n            xyzrgb[1][2] * self.whiteZ\n        )\n        self.kb = 1 / (\n            xyzrgb[2][0] * self.whiteX +\n            xyzrgb[2][1] * self.whiteY +\n            xyzrgb[2][2] * self.whiteZ\n        )\n\n    def getGray(self, l, a, b):\n        r, g, b = self.getRGB(l, a, b)\n        return 0.299 * r + 0.587 * g + 0.114 * b + 0.5\n\n    def getRGB(self, l, a, b):\n        def lab2xyz(t): return t ** 3 if (t >= 6 /\n                                          29) else (108 / 841 * (t - 4 / 29))\n\n        # convert L*a*b* to CIE 1931 XYZ color space\n        t1 = (l + 16) / 116\n        t2 = t1 + a / 500\n        X = lab2xyz(t2)\n        X *= self.whiteX\n        Y = lab2xyz(t1)\n        Y *= self.whiteY\n        t2 = t1 - b / 200\n        Z = lab2xyz(t2)\n        Z *= self.whiteZ\n\n        # convert XYZ to RGB, including gamut mapping and gamma correction\n        r = xyzrgb[0][0] * X + xyzrgb[0][1] * Y + xyzrgb[0][2] * Z\n        g = xyzrgb[1][0] * X + xyzrgb[1][1] * Y + xyzrgb[1][2] * Z\n        b = xyzrgb[2][0] * X + xyzrgb[2][1] * Y + xyzrgb[2][2] * Z\n\n        return r ** 0.5, g ** 0.5, b ** 0.5\n\n    def getCMYK(self, l, a, b):\n        r, g, b = self.getRGB(l, a, b)\n        c = 1 - r\n        m = 1 - g\n        y = 1 - b\n        k = min(c, m, y)\n        return c - k, m - k, y - k, k\n\n\nclass ICCBasedColorSpace(ColorSpace):\n    @property\n    def defaults(self):\n        return {\n            'L': GrayColorSpace,\n            'RGB': RGBColorSpace,\n            'CMYK': CMYKColorSpace,\n            'LAB': LabColorSpace\n        }\n\n    mode = 'RGB'\n\n    def __init__(self, obj):\n        obj = resolve1(obj)\n        fp = BytesIO(obj.get_data())\n        self.profile = ImageCms.ImageCmsProfile(fp)\n        fp.close()\n        self.mode = self.profile.profile.color_space\n        if self.mode == 'LAB':\n            alt = resolve1(obj['Alternate'])\n            if isinstance(alt, list):\n                alt = alt[1]\n            self.base = self.defaults[self.mode](alt)\n        else:\n            self.base = self.defaults[self.mode]()\n        self.ncomps = len(self.mode)\n\n    def getGray(self, *val):\n        return self.base.getGray(*val)\n\n    def getRGB(self, *val):\n        return self.base.getRGB(*val)\n\n    def getCMYK(self, *val):\n        return self.base.getCMYK(*val)\n\n\nclass IndexedColorSpace(ColorSpace):\n    mode = 'P'\n    basemode = 'RGB'\n    palette = list(map(lambda i: (i, i, i), range(256)))\n    ncomps = 1\n\n    def __init__(self, base, hival, obj):\n        cs = colorSpaces()\n        self.base = cs.parse(resolve1(base))\n        self.hival = int(resolve1(hival))\n\n        obj = resolve1(obj)\n        data = b''\n        if isinstance(obj, bytes):\n            data = obj\n        elif isinstance(obj, PDFStream):\n            data = obj.get_data()\n        if data:\n            n = self.base.ncomps\n            self.palette = [[data[i * n + j] for j in range(n)] for i in range(len(data) // n)]\n\n    def lookup(self, index):\n        i = max(0, min(index, len(self.palette) - 1))\n        return self.palette[i]\n\n    def getGray(self, index):\n        return self.base.getGray(*self.lookup(index))\n\n    def getRGB(self, index):\n        return self.base.getRGB(*self.lookup(index))\n\n    def getCMYK(self, index):\n        return self.base.getCMYK(*self.lookup(index))\n\n    def mapPixels(self, arr):\n        palette = np.array(self.palette, dtype='uint8')\n        return palette[arr]\n\n    def mapGray(self, arr):\n        return self.base.mapGray(arr)\n\n    def mapRGB(self, arr):\n        return self.base.mapRGB(arr)\n\n    def mapCMYK(self, arr):\n        return self.base.mapCMYK(arr)\n\n\nclass functionParser:\n    def _min(self, x, num):\n        if isinstance(x, (int, float)):\n            return min(x, num)\n        x[x >= num] = num\n        return x\n\n    def _max(self, x, num):\n        if isinstance(x, (int, float)):\n            return max(x, num)\n        x[x < num] = num\n        return x\n\n\nclass SampledFunctionParser(functionParser):\n    def __init__(self, spec, domain):\n        self.domain = domain\n        self.frange = list_value(spec['Range'])\n        self.nins = len(self.domain) >> 1\n        self.nouts = len(self.frange) >> 1\n\n        self.sizes = list_value(spec['Size'])[:self.nins]\n        self.bits = int(spec['BitsPerSample'])\n\n        if 'Encode' in spec:\n            self.encode = list_value(spec['Encode'])\n        else:\n            self.encode = [0] * (self.nins << 1)\n            self.encode[1::2] = [size-1 for size in self.sizes]\n\n        self.decode = list_value(\n            spec['Decode']) if 'Decode' in spec else self.frange[:]\n\n        # domain = [0 1]\n        # range = [0 1 0 1 0 1 0 1]\n        # bits = 8\n        # sizes = [1024]\n        # encode = [0 1023]\n        # decode = [0 1 0 1 0 1 0 1]\n\n    def interpolate(self, x, xmin, xmax, ymin, ymax):\n        return (ymax - ymin) / (xmax-xmin) * (x-xmin) + ymin\n\n    def parse(self, *args):\n        e = []\n        for i in range(self.nins):\n            x = self._min(\n                self._max(args[i], self.domain[i*2]), self.domain[i*2+1])\n            x = self.interpolate(\n                x, self.domain[i*2], self.domain[i*2+1], self.encode[i*2], self.encode[i*2+1])\n            e.append(self._min(self._max(x, 0), self.sizes[i]-1))\n        return e\n\n\ndef SampledFunction(spec, domain):\n    parser = SampledFunctionParser(spec, domain)\n    return parser.parse\n\n\nclass ExponentialFunctionParser(functionParser):\n    def __init__(self, spec, domain):\n        self.c0, self.c1 = [0], [1]\n        if spec.get('C0'):\n            self.c0 = [float(x) for x in list_value(spec['C0'])]\n        if spec.get('C1'):\n            self.c1 = [float(x) for x in list_value(spec['C1'])]\n        self.n = spec['N']\n        self.frange = None\n        if spec.get('Range'):\n            self.frange = list_value(spec.get('Range'))\n        self.domain = domain\n\n    def parse(self, ipt):\n        ipt /= 255\n        ipt = self._min(self._max(ipt, self.domain[0]), self.domain[1])\n        opt = []\n        for i in range(len(self.c0)):\n            x = self.c0[i] + pow(ipt, self.n) * (self.c1[i] - self.c0[i])\n            if self.frange:\n                x = self._min(self._max(x, self.frange[0]), self.frange[1])\n            opt.append(x * 255)\n        return opt\n\n\ndef ExponentialFunction(spec, domain):\n    parser = ExponentialFunctionParser(spec, domain)\n    return parser.parse\n\n\ndef StitchingFunction(spec, domain):\n    pass\n\n\nclass PSFunctionParser(PSStackParser):\n    def __init__(self, fp):\n        super().__init__(fp)\n        self.run()\n\n    def run(self):\n        try:\n            self.nextobject()\n        except PSEOF:\n            pass\n        _, self.argstack = self.curstack.pop()\n        self.reset()\n\n    def parse(self, *args):\n        argstack = list(args) + self.argstack\n        self.curstack = []\n        while argstack:\n            obj = argstack.pop(0)\n            if isinstance(obj, PSKeyword):\n                name = keyword_name(obj)\n                if not isinstance(name, str):\n                    name = name.decode()\n                result = getattr(self, 'do_'+name)()\n                if result is not None:\n                    if isinstance(result, (list, tuple)):\n                        self.curstack += list(result)\n                    else:\n                        self.curstack.append(result)\n            else:\n                self.curstack.append(obj)\n        return self.curstack\n\n    def do_keyword(self, pos, token):\n        self.push((pos, token))\n\n    def do_roll(self):\n        n, j = self.pop(2)\n        vals = self.pop(n)\n        j %= n\n        if not j:\n            return vals\n        return (vals*2)[n-j:n*2-j]\n\n    def do_dup(self):\n        x = self.pop(1)\n        return x + x\n\n    def do_exch(self):\n        a, b = self.pop(2)\n        return b, a\n\n    def do_sub(self):\n        a, b = self.pop(2)\n        if isinstance(b, (int, float)):\n            return b - a\n        b[b < a] = 0\n        b[b >= a] -= a\n        return b\n\n    def do_pop(self):\n        self.pop(1)\n\n    def do_index(self):\n        i = self.pop(1)[0]\n        return self.curstack[-i-1]\n\n    def do_cvr(self):\n        num = self.pop(1)[0]\n        return float(num)\n\n    def do_mul(self):\n        a, b = self.pop(2)\n        return a * b\n\n\ndef PostScriptFunction(spec, domain):\n    parser = PSFunctionParser(BytesIO(spec.get_data()))\n    return parser.parse\n\n\ndef func_parse(spec):\n    func_type = int(spec.get('FunctionType'))\n    domain = list_value(spec.get('Domain'))\n\n    func_refs = {\n        0: SampledFunction,\n        2: ExponentialFunction,\n        3: StitchingFunction,\n        4: PostScriptFunction\n    }\n\n    func_builder = func_refs[func_type]\n    return func_builder(spec, domain)\n\n\nclass SeparationColorSpace(ColorSpace):\n    mode = 'P'\n\n    def __init__(self, alt, base, func, *args):\n        cs = colorSpaces()\n        self.base = cs.parse(resolve1(base))\n        spec = resolve1(func)\n        self.ncomps = len(spec['Domain']) >> 1\n        self.func = func_parse(spec)\n\n    def transform(self, *val):\n        transformed = self.func(*val)\n        new_val = []\n        for i in range(self.base.ncomps):\n            new_val.append(transformed[i])\n        return new_val\n\n    def mapPixels(self, arr):\n        if not self.func:\n            return arr\n        if len(arr.shape) == 2:\n            arr = arr[..., np.newaxis]\n        w, h, d = arr.shape\n        arr = arr.astype('float')\n        transformed = self.transform(*[arr[..., i] for i in range(d)])\n        result = None\n        for layer in transformed:\n            if isinstance(layer, (int, float)):\n                layer = np.ones((w, h), dtype='float') * layer\n            layer = layer.astype('uint8')\n            if result is None:\n                result = layer\n            else:\n                result = np.dstack([result, layer])\n        return result\n\n    def getGray(self, *val):\n        val = self.transform(*val)\n        return self.base.getGray(*val)\n\n    def getRGB(self, *val):\n        val = self.transform(*val)\n        return self.base.getRGB(*val)\n\n    def getCMYK(self, *val):\n        val = self.transform(*val)\n        return self.base.getCMYK(*val)\n\n    def mapGray(self, arr):\n        return self.base.mapGray(arr)\n\n    def mapRGB(self, arr):\n        return self.base.mapRGB(arr)\n\n    def mapCMYK(self, arr):\n        return self.base.mapCMYK(arr)\n\n\nclass NColorSpace(SeparationColorSpace):\n    mode = 'P'\n\n    def __init__(self, names, alt, func, *attrs):\n        self.names = list_value(names)\n        self.base = colorSpaces().parse(resolve1(alt))\n        spec = resolve1(func)\n        self.ncomps = len(spec['Domain']) >> 1\n        self.func = func_parse(spec)\n\n\nclass PatternColorSpace(ColorSpace):\n    under = None\n    mode = 'P'\n    ncomps = 1\n\n    def __init__(self, *args):\n        if args:\n            cs = colorSpaces()\n            self.under = cs.parse(resolve1(args[0]))\n\n\ndefaults = colorSpaces().defaults\nparse = colorSpaces().parse\n\n\n", "meta": {"hexsha": "7b9d1521003f5cc2a16ec0da9f8c6c2d4b6d2cdf", "size": 16882, "ext": "py", "lang": "Python", "max_stars_repo_path": "minepdf/colorspace.py", "max_stars_repo_name": "jonix6/minepdf", "max_stars_repo_head_hexsha": "6c57427fb16622a1b9960f6e7d514487d9bcd877", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-29T07:59:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-01T06:08:30.000Z", "max_issues_repo_path": "minepdf/colorspace.py", "max_issues_repo_name": "jonix6/minepdf", "max_issues_repo_head_hexsha": "6c57427fb16622a1b9960f6e7d514487d9bcd877", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "minepdf/colorspace.py", "max_forks_repo_name": "jonix6/minepdf", "max_forks_repo_head_hexsha": "6c57427fb16622a1b9960f6e7d514487d9bcd877", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-05T11:14:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-05T11:14:14.000Z", "avg_line_length": 27.7664473684, "max_line_length": 98, "alphanum_fraction": 0.5143347945, "include": true, "reason": "import numpy", "num_tokens": 4977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.18902096894735454}}
{"text": "#!/usr/bin/env python3\nfrom __future__ import print_function\nimport sys\nsys.path.append('../lib/')\nimport os\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport pints\nimport pints.io\nimport pints.plot\n\n# Model etc.\nimport model as m\nimport parameters\nfrom parameters import simvc_fix, get_qc\nfrom parameters import simvc_typical_values\nimport parametertransform\nfrom priors import IKrWithoutConductanceLogPrior\nfrom priors import VoltageOffsetWithConductanceLogPrior\nfrom protocols import leak_staircase as protocol_def\n\n\"\"\"\nRun fit for mutliple cell experiment data with same kinetics:\n\nOptimise a likelihood\n    L(\\theta) = \\prod_i L_{kinetics, i}(\\theta | \\phi^*_i)\nwhere\n    i, measurement index\n    \\theta, the parameters of the kinetics\n    L_{kinetics, i}, the likelihood of the kinetic parameters for measurement i\nand\n    \\phi^*_i = \\argmax_{\\phi_i} L_{individual, i}(\\phi_i | \\theta)\nwhere\n    \\phi_i, the parameters for individual measurement, such as g_{Kr} and\n        voltage artefact parameters\n    L_{individual, i}, the likelihood of \\phi_i given \\theta.\n\nThis returns us \\theta* (= \\argmax_\\theta L(\\theta)) and {\\phi^*_i}.\n\"\"\"\n\ntry:\n    file_name = sys.argv[1]\n    run_id = int(sys.argv[2])\nexcept:\n    print('Usage: python %s [str:file_name]' % os.path.basename(__file__)\n            + '[int:run_id]')\n    sys.exit()\n\ncommon_param = parameters.ikr[1:]\nindependent_param = ['ikr.g',\n    #'voltageclamp.rseries',\n    'voltageclamp.voffset_eff',\n    'voltageclamp.gLeak']\nn_common_param = len(common_param)\nn_independent_param = len(independent_param)\n\n\ndef get_param(common, independent):\n    model_p = np.append(independent[0], common)\n    vclamp_p = independent[1:]\n    return np.append(model_p, vclamp_p)\n\n\ndef get_fix_param(var, val):\n    \"\"\"\n        var: variable name.\n        val: variable value to fix.\n    \"\"\"\n    out = {}\n    for i, j in zip(var, val):\n        out[i] = j\n    return out\n\n\ndef update_logposterior_fix_param(l, p):\n    \"\"\"\n        l: log-posterior.\n        p: dict, fix params.\n\n        NOTE: Only works for specific implementation.\n    \"\"\"\n    l._log_likelihood._problem._model.set_fix_parameters(p)\n\n\nfile_dir = '../data'\nfile_list = [\n        'herg25oc1',\n        'herg27oc1',\n        'herg27oc2',\n        'herg30oc1',\n        'herg30oc2',\n        'herg33oc1',\n        'herg33oc2',\n        'herg37oc3',\n        ]\ntemperatures = [25.0, 27.0, 27.0, 30.0, 30.0, 33.0, 33.0, 37.0]\nuseFilterCap = False\n\nif file_name not in file_list:\n    raise ValueError('Input `file_name` must be in `file_list`')\ntemperature = temperatures[file_list.index(file_name)]\n\nsavedir = './out/' + file_name + '-scheme3-simvclinleak'\nif not os.path.isdir(savedir):\n    os.makedirs(savedir)\n\nprint('Temperature: ', temperature)\n\n# Control fitting seed --> OR DONT\nnp.random.seed(run_id)\nfit_seed = np.random.randint(0, 2**30)\n# fit_seed = 542811797\nprint('Fit seed: ', fit_seed)\nnp.random.seed(fit_seed)\n\n# Leak param\nleakbeforeparam = np.loadtxt('../qc/' + file_name + '-staircaseramp-leak_before.txt')\ncell_id_file = '../qc/%s-staircaseramp-cell_id.txt' % file_name\ncell_ids = []\nwith open(cell_id_file, 'r') as f:\n    for l in f:\n        if not l.startswith('#'):\n            cell_ids.append(l.split()[0])\n\n# Get cells\nselectedfile = '../manualselection/manualv2selected-%s.txt' % (file_name)\nselectedwell = []\nwith open(selectedfile, 'r') as f:\n    for l in f:\n        if not l.startswith('#'):\n            selectedwell.append(l.split()[0])\nselectedwell = selectedwell[:]\nn_cells = len(selectedwell)\nprint(file_name + ' selected ' + str(n_cells) + ' cells')\n\n\n# Set parameter transformation\ntransform_to_ikr = parametertransform.log_transform_to_ikr\ntransform_from_ikr = parametertransform.log_transform_from_ikr\ntransform_to_vc = parametertransform.log_transform_to_vc\ntransform_from_vc = parametertransform.log_transform_from_vc\ntransform_to_leak = parametertransform.donothing\ntransform_from_leak = parametertransform.donothing\n\ntransform_to_common_param = transform_to_ikr\ntransform_from_common_param = transform_from_ikr\n\nn_gvc_parameters = VoltageOffsetWithConductanceLogPrior(None,\n        None).n_parameters()\ntransform_to_gvc = parametertransform.ComposeTransformation(\n        np.exp, transform_to_vc, 1)\ntransform_from_gvc = parametertransform.ComposeTransformation(\n        np.log, transform_from_vc, 1)\ntransform_to_independent_param = parametertransform.ComposeTransformation(\n        transform_to_gvc, transform_to_leak, n_gvc_parameters)\ntransform_from_independent_param = parametertransform.ComposeTransformation(\n        transform_from_gvc, transform_from_leak, n_gvc_parameters)\n\n\n# For individual bit in MwG\n# Model\nmodel_common = m.Model('../mmt-model-files/simplified-voltage-clamp-ikr-linleak.mmt',\n                protocol_def=protocol_def,\n                temperature=273.15 + temperature,  # K\n                transform=transform_to_common_param,\n                useFilterCap=useFilterCap)  # ignore capacitive spike\nmodel_common.set_parameters(common_param)\n\nmodel_independent = m.Model('../mmt-model-files/simplified-voltage-clamp-ikr-linleak.mmt',\n                protocol_def=protocol_def,\n                temperature=273.15 + temperature,  # K\n                transform=transform_to_independent_param,\n                useFilterCap=useFilterCap)  # ignore capacitive spike\nmodel_independent.set_parameters(independent_param)\n\n\n# Load all data\nlog_posteriors_common = []\nlog_posteriors_independent = []\ndata_all = []\ntimes_all = []\nnoise_sigma_all = []\nx0_common_all = []\nx0_independent_all = []\ntransform_x0_common_all = []\ntransform_x0_independent_all = []\nfor cell in selectedwell:\n    # Load data\n    data_file_name = file_name + '-staircaseramp-' + cell + '.csv'\n    time_file_name = file_name + '-staircaseramp-times.csv'\n    print('Fitting to ', data_file_name)\n\n    data = np.loadtxt(file_dir + '/' + data_file_name,\n                      delimiter=',', skiprows=1) # headers\n    times = np.loadtxt(file_dir + '/' + time_file_name,\n                       delimiter=',', skiprows=1) # headers\n    times = times * 1e3  # s -> ms\n    noise_sigma = np.std(data[:500])\n    print('Estimated noise level: ', noise_sigma)\n\n    if useFilterCap:\n        # Apply capacitance filter to data\n        data = data * model_common.cap_filter(times)\n\n    data_all.append(data)\n    times_all.append(times)\n    noise_sigma_all.append(noise_sigma)\n\n    # Get independent CMA-ES results as x0\n    cma_file = './fit-results/%s/%s-staircaseramp-%s-solution-542811797.txt' \\\n            % (file_name, file_name, cell)\n    x0i_param = np.loadtxt(cma_file)\n    # Change unit... (note, conductance unit different to Beattie's ones)\n    x0i_param = x0i_param * 1e-3  # in mV, ms\n    x0_common = x0i_param[1:n_common_param + 1]  # remove conductance\n    # Get 'independent parameters'\n    cma_ip_file = './out/%s-fixkinetics-simvclinleak/%s-staircaseramp-%s-solution-542811797.txt' \\\n            % (file_name, file_name, cell)\n    x0_independent = np.loadtxt(cma_ip_file)\n    # x0_independent = np.array([-1.5, 1e-2])\n    tx0_common = transform_from_common_param(x0_common)\n    # tx0_independent = transform_from_vc(x0i_param[n_common_param + 1:])\n    tx0_independent = transform_from_independent_param(x0_independent)\n\n    x0_common_all.append(x0_common)\n    x0_independent_all.append(x0_independent)\n    transform_x0_common_all.append(tx0_common)\n    transform_x0_independent_all.append(tx0_independent)\n\n    # Get fix parameters' value\n    rseal, cm, rseries = get_qc('../qc', file_name, cell)\n    print('Est. Rseal, Cm, Rseries:', rseal, cm, rseries, '(GOhm, pF, GOhm)')\n    alpha = 0.8  # rseries %compensation\n    cell_idx = cell_ids.index(cell)\n    ga, Ea = leakbeforeparam[cell_idx]\n    simvc_fix_values = [cm, rseries * alpha, rseries] + [ga, Ea]\n    fix_p = get_fix_param(simvc_fix + ['voltageclamp.rseries', 'voltageclamp.gLeak_est', 'voltageclamp.ELeak_est'],\n            simvc_fix_values)\n\n    #\n    # For individual bit in MwG\n    #\n    model_common.set_fix_parameters(fix_p)\n    model_independent.set_fix_parameters(fix_p)\n\n    problem_common = pints.SingleOutputProblem(model_common, times, data)\n    loglikelihood_common = pints.GaussianKnownSigmaLogLikelihood(\n            problem_common, noise_sigma)\n    logprior_common = IKrWithoutConductanceLogPrior(transform_to_common_param,\n            transform_from_common_param)\n    log_posterior_common = pints.LogPosterior(loglikelihood_common,\n            logprior_common)\n    log_posteriors_common.append(log_posterior_common)\n\n    problem_independent = pints.SingleOutputProblem(model_independent, times,\n            data)\n    loglikelihood_independent = pints.GaussianKnownSigmaLogLikelihood(\n            problem_independent, noise_sigma)\n    vc_prior = VoltageOffsetWithConductanceLogPrior(\n            transform_to_gvc, transform_from_gvc)\n    ileak_prior = pints.UniformLogPrior([-1e3], [1e3])\n    prior_independent = pints.ComposedLogPrior(vc_prior, ileak_prior)\n    log_posterior_independent = pints.LogPosterior(loglikelihood_independent,\n            prior_independent)\n    log_posteriors_independent.append(log_posterior_independent)\n\n    print('Score at default parameters: ',\n            log_posterior_common(transform_x0_common_all[-1]))\n\n    fix_p = get_fix_param(independent_param, x0_independent_all[-1])\n    update_logposterior_fix_param(log_posterior_common, fix_p)\n    print('Score at updated parameters: ',\n            log_posterior_common(transform_x0_common_all[-1]))\n\n    print('Score at default parameters: ',\n            log_posterior_independent(transform_x0_independent_all[-1]))\n\n    fix_p = get_fix_param(common_param, x0_common_all[-1])\n    update_logposterior_fix_param(log_posterior_independent, fix_p)\n    print('Score at updated parameters: ',\n            log_posterior_independent(transform_x0_independent_all[-1]))\n\n    for _ in range(5):\n        assert(log_posterior_common(transform_x0_common_all[-1]) ==\\\n                log_posterior_common(transform_x0_common_all[-1]))\n        assert(log_posterior_independent(transform_x0_independent_all[-1]) ==\\\n                log_posterior_independent(transform_x0_independent_all[-1]))\n\ndata_all = np.asarray(data_all).T\ntimes_all = np.asarray(times_all).T\ntimes = times_all[:, 0]\n\ntransform_x0_common_all_mean = np.mean(transform_x0_common_all, axis=0)\nx0_common_all_mean = np.copy(transform_to_common_param(transform_x0_common_all_mean))\ntotal_log_posteriors_common = pints.SumOfIndependentLogPDFs(\n        log_posteriors_common)\n\n# quick sanity checks\nassert(n_cells == len(log_posteriors_independent))\nassert(n_cells == len(log_posteriors_common))\n\n\n#\n# Define the big loglikelihood\n#\ntip0 = np.copy(transform_x0_independent_all)\ntcp0 = np.copy(transform_x0_common_all_mean)\nn_opt_iterations_independent = 200\n\nfinal_posterior = m.ParallelMultiLevelLogLikelihood(\n            total_common_logposterior=total_log_posteriors_common,\n            list_of_independent_logposteriors=log_posteriors_independent,\n            common_param=common_param,\n            independent_param=independent_param,\n            transform_to_common_param=transform_to_common_param,\n            transform_to_independent_param=transform_to_independent_param,\n            transformed_independent_parameters0=tip0,\n            n_opt=n_opt_iterations_independent,\n            restart_fit=True,\n            onlyNelderMead=True,\n            n_workers=None)\n\nprint('Test total_log_posteriors_common:', total_log_posteriors_common(tcp0))\n# This is important to run once...\n# To set what's the prior lp within final_posterior object\nprint('Test final_posterior: ', final_posterior(tcp0))\n\n\n#\n# Run optimisation\n# \nN = 1\n\nlogposteriors = []\nparams_c = []\nparams_i = []\nn_iter = 1000\nepsilon = 0.5  # when to switch from CMA-ES to Nelder-Mead\n\nfor _ in range(N):\n\n    x0 = tcp0\n\n    if epsilon > 0:\n        # Create optimiser part 1\n        opt = pints.OptimisationController(\n                final_posterior, x0,\n                method=pints.CMAES)\n        opt.set_max_iterations(int(epsilon * n_iter))\n        opt.set_max_unchanged_iterations(iterations=50, threshold=1e4)\n        opt.set_parallel(False)\n\n        # Run optimisation\n        try:\n            with np.errstate(all='ignore'):\n                # Tell numpy not to issue warnings\n                p, s = opt.run()\n        except ValueError:\n            import traceback\n            traceback.print_exc()\n\n        del(opt)\n        x0 = np.copy(p)\n\n    if epsilon < 1:\n        # Create optimiser part 2\n        opt = pints.OptimisationController(\n                final_posterior, x0,\n                method=pints.NelderMead)\n        #opt.set_max_iterations(int((1 - epsilon) * n_iter))\n        opt.set_max_unchanged_iterations(iterations=50, threshold=1e3)\n        opt.set_parallel(False)\n\n        # Run optimisation\n        try:\n            with np.errstate(all='ignore'):\n                # Tell numpy not to issue warnings\n                p, s = opt.run()\n        except ValueError:\n            import traceback\n            traceback.print_exc()\n\n        del(opt)\n\n    # Found parameters\n    found_tcp = np.copy(p)\n    found_cp = transform_to_common_param(p)\n    _ = final_posterior(found_tcp)\n    found_ip = final_posterior.get_current_independent_param()\n\n    logposteriors.append(s)\n    params_c.append(found_cp)\n    params_i.append(found_ip)\n\n\n#\n# Done\n#\nobtained_logposterior0 = logposteriors[0]\nobtained_parameters0 = params_c[0]\nobtained_parameters_i0 = params_i[0]\n\n# Show results\nsaveas = file_name\nprint('Found solution:          Prior parameters:' )\n# Store output\nwith open('%s/%s-solution-%s.txt' % (savedir, saveas, fit_seed), 'w') as f:\n    for k, x in enumerate(obtained_parameters0):\n        print(pints.strfloat(x) + '    ' + pints.strfloat(x0_common_all_mean[k]))\n        f.write(pints.strfloat(x) + '\\n')\nnp.savetxt('%s/%s-solution_i-%s.txt' % (savedir, saveas, fit_seed), obtained_parameters_i0)\n\nwith open('%s/%s-cells-%s.txt' % (savedir, saveas, fit_seed), 'w') as f:\n    for c in selectedwell:\n        f.write(c + '\\n')\n\n# Plot results\nmodel_ideal = m.Model('../mmt-model-files/ideal-ikr.mmt',\n                protocol_def=protocol_def,\n                temperature=273.15 + temperature,  # K\n                transform=parametertransform.donothing,\n                useFilterCap=useFilterCap)  # ignore capacitive spike\nvoltage = model_ideal.voltage(times)\noutput0 = final_posterior.problem_evaluate(\n        transform_from_common_param(obtained_parameters0),\n        obtained_parameters_i0)\nif not os.path.isdir(savedir + '/plot-solution-%s' % fit_seed):\n    os.makedirs(savedir + '/plot-solution-%s' % fit_seed)\nfor i in range(n_cells):\n    fig, axes = plt.subplots(2, 1, sharex=True, figsize=(8, 6))\n    axes[0].plot(times, voltage, c='#7f7f7f')\n    axes[0].set_ylabel('Voltage (mV)')\n    axes[1].plot(times, data_all[:, i], alpha=0.5, label='data')\n    ideal = model_ideal.simulate(\n            np.append(obtained_parameters_i0[i][0], obtained_parameters0),\n            times)\n    axes[1].plot(times, ideal, label='same kinetics')\n    axes[1].plot(times, output0[:, i], label='found solution 1')\n    axes[1].legend()\n    axes[1].set_ylabel('Current (pA)')\n    axes[1].set_xlabel('Time (ms)')\n    plt.subplots_adjust(hspace=0)\n    plt.savefig(savedir + '/plot-solution-%s/%s' % (fit_seed, selectedwell[i]))\n    plt.close()\n\nprint('Done.')\n\n## eof\n", "meta": {"hexsha": "f62b62157ad5d137b3ed2ac8658bcdd54341cedf", "size": 15423, "ext": "py", "lang": "Python", "max_stars_repo_path": "herg-real-data/fit-simvclinleak-scheme3-parallel.py", "max_stars_repo_name": "CardiacModelling/VoltageClampModel", "max_stars_repo_head_hexsha": "f30271da75e3c70526e53fb51dc12b317ab3b714", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-12-13T16:51:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T00:26:24.000Z", "max_issues_repo_path": "herg-real-data/fit-simvclinleak-scheme3-parallel.py", "max_issues_repo_name": "CardiacModelling/VoltageClampModel", "max_issues_repo_head_hexsha": "f30271da75e3c70526e53fb51dc12b317ab3b714", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-03T08:13:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T11:04:46.000Z", "max_forks_repo_path": "herg-real-data/fit-simvclinleak-scheme3-parallel.py", "max_forks_repo_name": "CardiacModelling/VoltageClampModel", "max_forks_repo_head_hexsha": "f30271da75e3c70526e53fb51dc12b317ab3b714", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1973392461, "max_line_length": 115, "alphanum_fraction": 0.6970109577, "include": true, "reason": "import numpy", "num_tokens": 3963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.36658972248186006, "lm_q1q2_score": 0.18902096181102035}}
{"text": "# Copyright 2021 The NetKet Authors - All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom functools import partial\nfrom typing import Callable\nimport warnings\n\nimport jax\nfrom jax import numpy as jnp\n\nfrom netket import jax as nkjax\nfrom netket.stats import Stats\nfrom netket.utils.types import PyTree\nfrom netket.utils.dispatch import dispatch\n\nfrom netket.operator import (\n    AbstractOperator,\n    DiscreteOperator,\n    ContinuousOperator,\n    Squared,\n)\n\nfrom netket.vqs import expect\n\nfrom netket.vqs.mc import (\n    kernels,\n    get_local_kernel,\n    get_local_kernel_arguments,\n)\n\nfrom .state import MCState\n\n\n# Dispatches to select what expect-kernel to use\n@dispatch\ndef get_local_kernel(vstate: MCState, Ô: Squared, chunk_size: int):  # noqa: F811\n    return kernels.local_value_squared_kernel_chunked\n\n\n@dispatch\ndef get_local_kernel(  # noqa: F811\n    vstate: MCState, Ô: DiscreteOperator, chunk_size: int\n):\n    return kernels.local_value_kernel_chunked\n\n\ndef _local_continuous_kernel(kernel, logpsi, pars, σ, args, *, chunk_size=None):\n    def _kernel(σ):\n        return kernel(logpsi, pars, σ, args)\n\n    return nkjax.vmap_chunked(_kernel, in_axes=0, chunk_size=chunk_size)(σ)\n\n\n@dispatch\ndef get_local_kernel(  # noqa: F811\n    vstate: MCState, Ô: ContinuousOperator, chunk_size: int\n):\n    return nkjax.HashablePartial(_local_continuous_kernel, Ô._expect_kernel)\n\n\n# If batch_size is None, ignore it and remove it from signature so that we fall back\n# to already implemented methods\n@expect.dispatch\ndef expect_nochunking(vstate: MCState, operator: AbstractOperator, chunk_size: None):\n    return expect(vstate, operator)\n\n\n# if no implementation exists for batched, fall back to unbatched methods.\n@expect.dispatch\ndef expect_fallback(\n    vstate: MCState, operator: AbstractOperator, chunk_size\n):  # noqa: F811\n    warnings.warn(\n        f\"Ignoring chunk_size={chunk_size} for expect_and_grad method with signature \"\n        f\"({type(vstate)}, {type(operator)}) because no implementation supporting \"\n        f\"chunking for this signature exists.\"\n    )\n\n    return expect(vstate, operator)\n\n\n@expect.dispatch\ndef expect_mcstate_operator_chunked(\n    vstate: MCState, Ô: AbstractOperator, chunk_size: int\n) -> Stats:  # noqa: F811\n    σ, args = get_local_kernel_arguments(vstate, Ô)\n\n    local_estimator_fun = get_local_kernel(vstate, Ô, chunk_size)\n\n    return _expect_chunking(\n        chunk_size,\n        local_estimator_fun,\n        vstate._apply_fun,\n        vstate.sampler.machine_pow,\n        vstate.parameters,\n        vstate.model_state,\n        σ,\n        args,\n    )\n\n\n@partial(jax.jit, static_argnums=(0, 1, 2))\ndef _expect_chunking(\n    chunk_size: int,\n    local_value_kernel: Callable,\n    model_apply_fun: Callable,\n    machine_pow: int,\n    parameters: PyTree,\n    model_state: PyTree,\n    σ: jnp.ndarray,\n    args: PyTree,\n) -> Stats:\n    σ_shape = σ.shape\n\n    if jnp.ndim(σ) != 2:\n        σ = σ.reshape((-1, σ_shape[-1]))\n\n    def logpsi(w, σ):\n        return model_apply_fun({\"params\": w, **model_state}, σ)\n\n    def log_pdf(w, σ):\n        return machine_pow * model_apply_fun({\"params\": w, **model_state}, σ).real\n\n    _, Ō_stats = nkjax.expect(\n        log_pdf,\n        partial(local_value_kernel, logpsi, chunk_size=chunk_size),\n        parameters,\n        σ,\n        args,\n        n_chains=σ_shape[0],\n    )\n\n    return Ō_stats\n", "meta": {"hexsha": "68106746a0c842f674fc54188dc3663e26c4d4fe", "size": 3903, "ext": "py", "lang": "Python", "max_stars_repo_path": "netket/vqs/mc/mc_state/expect_chunked.py", "max_stars_repo_name": "NetKet/netket", "max_stars_repo_head_hexsha": "96758e814fc3128e6821564d6cc2852bac40ecf2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 352, "max_stars_repo_stars_event_min_datetime": "2018-04-24T16:45:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:15:34.000Z", "max_issues_repo_path": "netket/vqs/mc/mc_state/expect_chunked.py", "max_issues_repo_name": "NetKet/netket", "max_issues_repo_head_hexsha": "96758e814fc3128e6821564d6cc2852bac40ecf2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 947, "max_issues_repo_issues_event_min_datetime": "2018-04-24T20:16:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T17:33:52.000Z", "max_forks_repo_path": "netket/vqs/mc/mc_state/expect_chunked.py", "max_forks_repo_name": "NetKet/netket", "max_forks_repo_head_hexsha": "96758e814fc3128e6821564d6cc2852bac40ecf2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 148, "max_forks_repo_forks_event_min_datetime": "2018-04-25T02:44:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T11:42:34.000Z", "avg_line_length": 26.9172413793, "max_line_length": 86, "alphanum_fraction": 0.7130412503, "include": true, "reason": "import numpy,import jax,from jax", "num_tokens": 995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.18902096181102032}}
{"text": "# pylint: disable=dangerous-default-value\n\n\"\"\"\n  Various routines for dealing with generating input and processing output\n  for abstracted records of experimental tests.\n\n  These routines do things like:\n    * Convert simplified descriptions of tests into strain/strain time\n      histories that the models can use\n    * Generate random experiments and the corresponding inputs\n\n  The actual deterministic and statistical fitting routines expect data\n  in a common format.  There are a few conditions on the input test data:\n\n  1. You have to sample all tests with the same number of time points (ntime).\n  2. You have to provide the full, correct history of the input conditions.\n     For strain controlled experiments this is the full history of test\n     time, strain, and temperature.  For stress control it is the full\n     history of time, stress, and temperature.\n  3. You do not have to provide the full *results* history.  That is,\n     the fit routines can accommodate some types of abstracted test data,\n     like maximum stress as a function of cycles for strain-controlled cyclic\n     tests.  The convert_results function can then convert a full (simulated)\n     results history to the right abstracted format for comparison to the\n     test data.\n\n  The fitting routines rely on five tensors with the following format:\n\n  * data :code:`(3, ntime, nexp)`: the input experimental conditions.\n    The first\n    index contains the experimental time, temperature, and strain history\n    for strain controlled tests and the experimental time, temperature\n    and stress history for stress controlled tests\n  * results :code:`(ntime, nexp)`: the (potentially abstracted) experimental\n    results.\n    For example, this could be the stress history for a tensile test or\n    the strain history for a creep test.  The specific requirements for\n    certain tests types are described below.\n  * cycles :code:`(ntime, nexp)`: the cycle counts for cyclic  tests or an\n    integer\n    used to indicate features of the experiment for other test types.\n    Specific requirements are given below.\n  * types :code:`(nexp,)`: an integer giving the test type (see list below)\n  * control :code:`(nexp,)`: 0 for strain control, 1 for stress control\n\n  The current test types are:\n\n  0. \"tension\" -- uniaxial, monotonic tension or compression test\n  1. \"relaxation\" -- stress relaxation test\n  2. \"strain_cyclic\" -- strain controlled cyclic (i.e. creep or creep-fatigue)\n  3. \"creep\" -- a creep test\n  4. \"stress_cyclic\" -- a stress controlled cyclic test\n  5. \"abstract_tensile\" -- tension tests where only the yield strength\n     and ultimate tensile strength are known\n  6. \"direct_data\" -- the full results history is known and provided\n\n  The :func:`pyoptmat.experiments.load_results`\n  function provides a way to load data for this type\n  from an xarray format.  The same tensors are stored in the xarray\n  structure, however the descriptive string names for the tests are used\n  and \"strain\" or \"stress\" is used instead of 0 and 1 to indicate the\n  control type.  Additional metadata can be stored in the xarray format with\n  source information, heat ID, etc.\n\"\"\"\n\nimport numpy as np\nimport numpy.random as ra\n\nimport torch\n\n\ndef load_results(xdata, device=torch.device(\"cpu\")):\n    \"\"\"\n    Load experimental data from xarray into torch tensors\n\n    Args:\n      xdata (xarray.DataArray): xarray data structure\n\n    Keyword Args:\n      device (torch.device):   the device to dump the resulting arrays on\n\n    Returns:\n      tuple: see below\n\n    This function returns a tuple of five tensors\n\n      data :code:`(3, ntime, nexperiment)`\n\n        The initial index are the experimental (times, temperatures, idata)\n        For strain controlled tests idata is strain\n        For stress controlled tests idata is stress\n\n      results :code:`(ntime, nexperiment)`\n\n        For strain controlled tests this is stress\n        For stress controlled tests this is strain\n\n      cycles :code:`(ntime, nexperiment)`\n\n        Cycle count for all tests\n\n      types :code:`(nexperiment,)`\n\n        Experiment types, converted to integers per the dicts above\n\n      control :code:`(nexperiment,)`\n\n        Maps the string control type (\"strain\" or \"stress\") to an integer\n        using the dict above\n    \"\"\"\n    time = torch.tensor(xdata[\"time\"].values, device=device)\n    temp = torch.tensor(xdata[\"temperature\"].values, device=device)\n    strain = torch.tensor(xdata[\"strain\"].values, device=device)\n    stress = torch.tensor(xdata[\"stress\"].values, device=device)\n\n    cycle = torch.tensor(xdata[\"cycle\"].values, device=device)\n    types = torch.tensor([exp_map[t] for t in xdata[\"type\"].values], device=device)\n    control = torch.tensor(\n        [control_map[t] for t in xdata[\"control\"].values], device=device\n    )\n\n    data = torch.empty((4,) + time.shape, device=device)\n\n    data[0] = time\n    data[1] = temp\n    data[2, :, control == 0] = strain[:, control == 0]\n    data[2, :, control == 1] = stress[:, control == 1]\n\n    results = torch.empty_like(time)\n    results[:, control == 0] = stress[:, control == 0]\n    results[:, control == 1] = strain[:, control == 1]\n\n    return data, results, cycle, types, control\n\n\ndef convert_results(results, cycles, types):\n    \"\"\"\n    Process a raw results vector to our common format based on test type\n\n    Args:\n      results (torch.tensor):   raw results data :code:`(ntime, nexperiment)`\n      cycles (torch.tensor):    cycle counts :code:`(ntime, nexperiment)`\n      types (torch.tensor):     test types :code:`(nexperiment,)`\n\n    Returns:\n      torch.tensor: tensor of processed results\n    \"\"\"\n    processed = torch.empty_like(results)\n\n    for i, func in exp_fns_num.items():\n        current = types == i\n        if torch.sum(current) > 0:\n            processed[:, current] = func(cycles[:, current], results[:, current])\n\n    return processed\n\n\ndef format_direct_data(cycles, predictions):\n    \"\"\"\n    Format direct stress/strain results\n\n    For this test type cycles just equals 0 for all time steps\n\n    This function does nothing, it just returns :code:`predictions`\n\n    Args:\n      cycles (torch.tensor):        cycle count\n      predictions (torch.tensor):   input to format\n\n    Returns:\n      torch.tensor:                 tensor of processed results\n\n    \"\"\"\n    return predictions\n\n\ndef format_abstract_tensile(cycles, predictions):\n    \"\"\"\n    Format abstracted tensile test data, where only the yield strength\n    and ultimate tensile strength are available.\n\n    This method relies on the input cycles being:\n    * 0: in the elastic regime\n    * 1: for the first 1/2 of the remaining time points outside of the elastic regime\n    * 2: for the second 1/2 of the remaining time points.\n\n    The inputs are the full stress history.  This function:\n\n    * Cycle 0: overwrite with zeros\n    * Cycle 1: overwrite with the first value in cycle 1\n    * Cycle 2: overwrite with the maximum stress\n\n    Args:\n      cycles (torch.tensor):        cycle count\n      predictions (torch.tensor):   input to format\n\n    Returns:\n      torch.tensor:                 tensor of processed results\n    \"\"\"\n    result = torch.zeros_like(predictions)\n\n    # cycles == 0 -> 0\n    result += torch.where(cycles == 0, 0.0, 0.0)\n\n    # cycles == 1 -> first value in that region\n    _, index = torch.max(cycles == 1, 0)\n    result += torch.where(cycles == 1, predictions.gather(0, index.view(1, -1))[0], 0.0)\n\n    # cycles == 2 -> max value overall\n    mvalues, _ = torch.max(predictions, 0)\n    result += torch.where(cycles == 2, mvalues, 0.0)\n\n    return result\n\n\ndef format_tensile(cycles, predictions):\n    \"\"\"\n    Format tension test data to our \"post-processed\" form for comparison\n\n    Input data are stresses for this test type\n\n    Cycles are all 0\n\n    This function doesn't do anything, just returns :code:`predictions`\n\n    Args:\n      cycles (torch.tensor):        cycle count/listing\n      predictions (torch.tensor):   input data\n\n    Returns:\n      torch.tensor:                 processed results\n    \"\"\"\n    return predictions\n\n\ndef format_relaxation(cycles, predictions):\n    \"\"\"\n    Format stress relaxation test data to our \"post-processed\" form for\n    comparison. This works for both creep and stress relaxation tests.\n\n    Input data are stresses for stress relaxation and strains for creep\n\n    Cycle 0 indicates the loading part of the test, cycle 1 is the hold\n\n    Zero out the loading results, replace the relaxation results with the\n    normalized (subtract t=0) curve\n\n    Args:\n      cycles (torch.tensor):        cycle count/listing\n      predictions (torch.tensor):   input data\n\n    Returns:\n      torch.tensor:                 processed results\n    \"\"\"\n    result = torch.zeros_like(predictions)\n    rcurve = cycles[:, 0] == 1  # This is right, but dangerous in the future\n\n    curve = predictions[rcurve]\n    curve = curve - curve[0]\n\n    result[rcurve] = curve\n\n    return result\n\n\ndef format_cyclic(cycles, predictions):\n    \"\"\"\n    Format a generic cyclic test -- works for both stress and strain control\n\n    Input data are stresses for strain control and strains for stress control.\n\n    We format this as a \"block\" -- the values for each cycle are replaced\n    by the maximum value within the cycle\n\n    Args:\n      cycles (torch.tensor):        cycle count/listing\n      predictions (torch.tensor):   input data\n\n    Returns:\n      torch.tensor:                 processed results\n    \"\"\"\n    # If this is slow we can probably remove the for loop\n    result = torch.zeros_like(predictions)\n    uc = cycles[:, 0]  # Correct but dangerous for future expansion\n    for i in range(uc[-1] + 1):\n        curr = uc == i\n        vals, _ = torch.max(predictions[curr], axis=0)\n        result[curr] = vals\n\n    return result\n\n\ndef make_tension_tests(rates, temperatures, elimits, nsteps):\n    \"\"\"\n    Produce tension test (time,strain,temperature) history blocks\n    given tensor inputs for the strain rates, temperatures, and\n    maximum strain of each test\n\n    Args:\n      rates (torch.tensor):         1D tensor giving the strain rate of each test\n      temperaturess (torch.tensor): 1D tensor giving the constant temperature of each test\n      elimits (torch.tensor):       1D tensor giving the maximum strain of each test\n      nsteps (torch.tensor):        integer number of steps\n\n    Returns:\n      tuple:                        tuple of\n                                    :code:`(times, strains, temperatures, cycles)`\n    \"\"\"\n    nbatch = temperatures.shape[0]\n    times = torch.zeros(nsteps, nbatch)\n    strains = torch.zeros_like(times)\n    temps = torch.zeros_like(strains)\n\n    for i in range(nbatch):\n        times[:, i] = torch.linspace(0, elimits[i] / rates[i], nsteps)\n        strains[:, i] = torch.linspace(0, elimits[i], nsteps)\n        temps[:, i] = temperatures[i]\n\n    return times, strains, temps, torch.zeros_like(times, dtype=int)\n\n\ndef make_creep_tests(\n    stress, temperature, rate, hold_times, nsteps_load, nsteps_hold, logspace=False\n):\n    \"\"\"\n    Produce creep test input (time,stress,temperature) given tensor\n    inputs for the target stress, target temperature, loading rate\n\n    Args:\n      stress (torch.tensor):        1D tensor of target stresses\n      temperature (torch.tensor):   1D tensor of target temperature\n      rate (torch.tensor):          1D tensor of target rates\n      hold_times (torch.tensor):    1D tensor of hold times\n      nsteps_load (torch.tensor):   number of time steps to load up the sample\n      nsteps_hold (torch.tensor):   number of time steps to hold the sample\n\n    Keyword Args:\n      logspace (bool):              log-space time increments during holds\n\n    Returns:\n      tuple:                        tuple of\n                                    :code:`(times, strains, temperatures, cycles)`\n    \"\"\"\n    nbatch = stress.shape[0]\n    nsteps = nsteps_load + nsteps_hold\n\n    stresses = torch.zeros(nsteps, nbatch)\n    times = torch.zeros_like(stresses)\n    temperatures = torch.zeros_like(stresses)\n\n    for i, (s, t, lr, T) in enumerate(zip(stress, hold_times, rate, temperature)):\n        stresses[:nsteps_load, i] = torch.linspace(0, s, nsteps_load)\n        stresses[nsteps_load:, i] = s\n\n        times[:nsteps_load, i] = torch.linspace(0, s / lr, nsteps_load)\n        temperatures[:, i] = T\n        if logspace:\n            times[nsteps_load:, i] = torch.logspace(\n                torch.log10(times[nsteps_load - 1, i]), torch.log10(t), nsteps_hold + 1\n            )[1:]\n        else:\n            times[nsteps_load:, i] = torch.linspace(\n                times[nsteps_load - 1, i], t, nsteps_hold + 1\n            )[1:]\n\n    cycles = torch.ones_like(times, dtype=int)\n    cycles[:nsteps_load] = 0\n\n    return times, stresses, temperatures, cycles\n\n\ndef generate_random_tension(strain_rate=[1.0e-6, 1.0e-2], max_strain=0.2):\n    \"\"\"\n    Generate a random tension test condition in the provided ranges\n\n    Keyword Args:\n      strain_rate (list): Range of strain rates\n      max_strain (float): Maximum strain to simulate\n\n    Returns:\n      dict:               dictionary with :code:`\"max_strain\"`\n                          and :code:`\"strain_rate\"`\n    \"\"\"\n    return {\n        \"max_strain\": max_strain,\n        \"strain_rate\": 10.0\n        ** ra.uniform(np.log10(strain_rate[0]), np.log10(strain_rate[1])),\n    }\n\n\ndef sample_tension(test, nsteps=50):\n    \"\"\"\n    Generate the times and strains for a tensile test\n\n    Args:\n      test (dict):    Dictionary defining the test case\n\n    Keyword Args:\n      nsteps (int):   Number of steps to sample\n\n    Returns:\n      tuple:          tuple of :code:`(times, strains)`\n    \"\"\"\n    tmax = test[\"max_strain\"] / test[\"strain_rate\"]\n    times = np.linspace(0, tmax, nsteps)\n    strains = times * test[\"strain_rate\"]\n\n    return times, strains\n\n\ndef generate_random_cycle(\n    max_strain=[0, 0.02],\n    R=[-1, 1],\n    strain_rate=[1.0e-3, 1.0e-5],\n    tension_hold=[0, 1 * 3600.0],\n    compression_hold=[0, 600],\n):\n    \"\"\"\n    Generate a random cycle in the provided ranges\n\n    Keyword Args:\n      max_strain (list):        range of the maximum strains\n      R (list):                 range of R ratios\n      strain_rate (list):       range of loading strain rates\n      tension_hold (list):      range of tension hold times\n      compression_hold (list):  range of compression hold times\n\n    Returns:\n      dict:                     dictionary describing cycle, described below\n\n    * :code:`\"max_strain\"` -- maximum strain value\n    * :code:`\"R\"` -- R ratio :math:`\\\\frac{max}{min}`\n    * :code:`\"strain_rate\"` -- strain rate during load/unload\n    * :code:`\"tension_hold\"` -- hold on the tension end of the cycle\n    * :code:`\"compression_hold\"` -- hold on the compressive end of the cycle\n    \"\"\"\n    return {\n        \"max_strain\": ra.uniform(*max_strain),\n        \"R\": ra.uniform(*R),\n        \"strain_rate\": 10.0\n        ** ra.uniform(np.log10(strain_rate[0]), np.log10(strain_rate[1])),\n        \"tension_hold\": ra.uniform(*tension_hold),\n        \"compression_hold\": ra.uniform(*compression_hold),\n    }\n\n\ndef sample_cycle_normalized_times(cycle, N, nload=10, nhold=10):\n    # pylint: disable=too-many-locals\n    \"\"\"\n    Sample a cyclic test at a normalized series of times\n\n    Take a random cycle dictionary and expand into discrete\n    times, strains samples where times are the actual, physical\n    times, given over the fixed phases\n\n      * :math:`0 \\\\rightarrow  t_{phase}` -- tension load\n      * :math:`t_{phase} \\\\rightarrow 2 t_{phase}` -- tension hold\n      * :math:`2 t_{phase} \\\\rightarrow 3 t_{phase}` --   unload\n      * :math:`3 t_{phase} \\\\rightarrow 4 t_{phase}` -- compression load\n      * :math:`4 t_{phase} \\\\rightarrow 5 t_{phase}` -- compression hold\n      * :math:`5 t_{phase} \\\\rightarrow 6 t_{phase}` -- unload\n\n    This pattern repeats for N cycles\n\n    Args:\n      cycle (dict): dictionary defining the load cycle\n      N (int):      number of repeats to include in the history\n\n    Keyword Args:\n      nload (int):  number of steps to use for the load time\n      nhold (int):  number of steps to use for the hold time\n    \"\"\"\n    emax = cycle[\"max_strain\"]\n    emin = cycle[\"R\"] * cycle[\"max_strain\"]\n    erate = cycle[\"strain_rate\"]\n\n    # Segments:\n    t1 = np.abs(emax) / erate\n    t2 = cycle[\"tension_hold\"]\n    t3 = np.abs(emax - emin) / erate\n    t4 = cycle[\"compression_hold\"]\n    t5 = np.abs(emin) / erate\n    divisions = [t1, t2, t3, t4, t5]\n    timesteps = [nload, nhold, 2 * nload, nhold, nload]\n    cdivisions = np.cumsum(divisions)\n    period = cdivisions[-1]\n\n    Ntotal = nload * 4 + nhold * 2\n\n    times = np.zeros((1 + Ntotal * N,))\n    cycles = np.zeros(times.shape, dtype=int)\n\n    n = 1\n    tc = 0\n    for k in range(N):\n        for ti, ni in zip(divisions, timesteps):\n            times[n : n + ni] = np.linspace(tc, tc + ti, ni + 1)[1:]\n            cycles[n : n + ni] = k\n            n += ni\n            tc += ti\n\n    tp = times % period\n    strains = np.piecewise(\n        tp,\n        [\n            np.logical_and(tp >= 0, tp < cdivisions[0]),\n            np.logical_and(tp >= cdivisions[0], tp < cdivisions[1]),\n            np.logical_and(tp >= cdivisions[1], tp < cdivisions[2]),\n            np.logical_and(tp >= cdivisions[2], tp < cdivisions[3]),\n            np.logical_and(tp >= cdivisions[3], tp < cdivisions[4]),\n        ],\n        [\n            lambda tt: tt / t1 * emax,\n            lambda tt: tt * 0 + emax,\n            lambda tt: emax - (tt - cdivisions[1]) / t3 * (emax - emin),\n            lambda tt: tt * 0 + emin,\n            lambda tt: emin - (tt - cdivisions[3]) / t5 * emin,\n        ],\n    )\n\n    return times, strains, cycles\n\n\n# Numerical codes for each test type\nexp_map = {\n    \"tensile\": 0,\n    \"relaxation\": 1,\n    \"strain_cyclic\": 2,\n    \"creep\": 3,\n    \"stress_cyclic\": 4,\n    \"abstract_tensile\": 5,\n    \"direct_data\": 6,\n}\n# Function to use to process each test type\nexp_fns = {\n    \"tensile\": format_tensile,\n    \"relaxation\": format_relaxation,\n    \"strain_cyclic\": format_cyclic,\n    \"creep\": format_relaxation,\n    \"stress_cyclic\": format_cyclic,\n    \"abstract_tensile\": format_abstract_tensile,\n    \"direct_data\": format_direct_data,\n}\n# Map to numbers instead\nexp_fns_num = {exp_map[k]: v for k, v in exp_fns.items()}\n\n# Map control type to number\ncontrol_map = {\"strain\": 0, \"stress\": 1}\n", "meta": {"hexsha": "08b1e8973a33ac41f7dc660af45f6da550b49765", "size": 18369, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyoptmat/experiments.py", "max_stars_repo_name": "tianjuchen/pyoptmat", "max_stars_repo_head_hexsha": "6f34205f450fd884679f37522ccd0d0b65ecdb71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyoptmat/experiments.py", "max_issues_repo_name": "tianjuchen/pyoptmat", "max_issues_repo_head_hexsha": "6f34205f450fd884679f37522ccd0d0b65ecdb71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyoptmat/experiments.py", "max_forks_repo_name": "tianjuchen/pyoptmat", "max_forks_repo_head_hexsha": "6f34205f450fd884679f37522ccd0d0b65ecdb71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4590163934, "max_line_length": 90, "alphanum_fraction": 0.6441831346, "include": true, "reason": "import numpy", "num_tokens": 4636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.18902096181102032}}
{"text": "\"\"\"Main module.\"\"\"\n\nfrom scipy.interpolate import interp1d\nfrom pathlib import Path\nimport pandas as pd\nimport numpy as np\nfrom typing import Union, Any, Sequence\nimport json\n\nclass QINCM:\n    # Quick Inland Navigation Cost Model\n\n    # Under keel clearance\n    ukc = 0.20\n\n\n    def __init__(self,\n                 route_depth_costs_file: Union[str, Path] = None,\n                 knelpunt_discharge_depth_file: Union[str, Path] = None,\n                 reference: str = None,\n                 ):\n        \"\"\"\n        Initialise\n\n        :param route_depth_costs_file:\n        :param knelpunt_discharge_depth_file:\n        :param reference_point_mode: set True if the discharge in the earlier point links to a single discharge\n        \"\"\"\n\n        # Initialise model\n        self._read_routes_depth_costs(route_depth_costs_file)\n        self._read_knelpunt_discharge_depth(knelpunt_discharge_depth_file, reference=reference)\n\n    def _compute_knelpunt_depth(self, discharges):\n        depths = {}\n        for k in self.knelpunt_names:\n            depths[k] = self.knelpunt_discharge_depth[k](discharges[k])\n        depths = pd.DataFrame(data=depths, index=discharges.index)\n\n        # if isinstance(discharges, pd.DataFrame):\n        #     depths = {}\n        #     for k in self.knelpunt_names:\n        #         depths[k] = self.knelpunt_discharge_depth[k](discharges[k])\n        #     depths = pd.DataFrame(data=depths, index=discharges.index)\n        # else:\n        #     depths = {}\n        #     for k in self.knelpunt_names:\n        #         depths[k] = self.knelpunt_discharge_depth[k](discharges)\n        #     depths = pd.DataFrame(data=depths, index=discharges)\n\n        return depths\n\n\n    def _costs_at_routes_at_discharge(self, discharges: pd.DataFrame) -> pd.DataFrame:\n        \"\"\"\n        Compute costs per route per discharge\n\n        param discharges: list of unique discharges. dim1: unique discharges, dim2: knelpunten\n\n        returns: DataFrame (index: routes, columns: discharges)\n        \"\"\"\n\n        depths = self._compute_knelpunt_depth(discharges)\n\n        # For each r (=FrozenList of knelpunten)\n        r_costs = {}\n        for r in self.routes:\n\n            # Get the limiting depth on the route\n            r_depth = depths.reindex(r, axis=1).min(axis=1).fillna(999999)\n\n            # Depth to draught/draft\n            r_draughts = r_depth - self.ukc\n\n            # Get costs\n            r_costs[r] = self.routes_depth_costs[r](r_draughts)\n\n        costs = pd.DataFrame(r_costs, index=discharges.index)\n\n        return costs\n\n    def _compute_local_discharge(self, discharges):\n        if np.ndim(discharges) == 1:\n            # Only reference discharge is given, compute local discharge from Q-Q-relation\n            Q_ref = discharges\n\n            if isinstance(discharges, pd.Series):\n                Q_local = pd.DataFrame(index=discharges.index)\n            else:\n                Q_local = pd.DataFrame(index=Q_ref)  # The index is only for convenience.\n\n            for k, QQ in self.knelpunt_discharge_distribution.items():\n                Q_local[k] = QQ(Q_ref)\n        else:\n            k_names = self.knelpunt_names\n\n            if isinstance(discharges, pd.DataFrame):\n                Q_local = pd.DataFrame(data=discharges, columns=k_names, index=discharges.index)\n            else:\n                Q_local = pd.DataFrame(data=discharges, columns=k_names)\n\n                Q_local.index = Q_local[self.knelpunt_reference]  # The index is only for convenience.\n        return Q_local\n\n    def costs_per_discharge(self, discharges: Union) -> pd.DataFrame:\n        \"\"\"\n        Compute total costs per discharge\n\n        param discharges: list of unique discharges. ALso supports timeseries\n\n        returns: Series (index=discharges)\n        \"\"\"\n        Q_local = self._compute_local_discharge(discharges)\n\n        costs = self._costs_at_routes_at_discharge(Q_local)\n        return costs\n\n\n    def costs_for_scenario(self, discharges, occurance=None, delta: bool = True):\n        \"\"\"\n        Compute total costs in scenario\n\n        param discharge: list of unique discharges\n        param occurance: float, or list with for each discharge the number of days. If none, it assumes every discharges occured one day\n        \"\"\"\n\n        # TODO: Discharge may also be a pandas\n        if occurance is not None:\n            # Validate input\n            # if isinstance(occurance, float):\n            #     occurance = np.ones(np.shape(discharges)) * occurance\n            # assert len(discharges) == len(occurance), 'Input should have same length'\n\n            # Compute total costs\n            costs = self.costs_per_discharge(discharges)\n\n            # Compute delta costs\n            if delta:\n                costs_no_problems = self.costs_per_discharge([99999999])  #TODO: This way is not good for depths that are included as constants...\n                costs = costs.subtract(costs_no_problems.values, axis=1)\n\n            costs_occurance = costs.multiply(occurance, axis=0)\n\n\n        else:\n            costs = self.costs_per_discharge(discharges)\n\n\n            if delta:\n                costs_no_problems = self.costs_per_discharge([99999999])\n                costs = costs.subtract(costs_no_problems.values, axis=1)\n\n            costs_occurance = costs\n\n\n        total_costs_per_route = costs_occurance.sum(axis=0)\n        # total_costs_per_discharge = costs_occurance.sum(axis=1) # Or per day if that's the index\n        # total_costs = total_costs_per_route.sum()\n\n        return total_costs_per_route\n\n    def _read_routes_depth_costs(self, routes_depth_costs_file: Union[str, Path]):\n        \"\"\"\n        # Set for each route (combination of knelpunten) the function of [draught]-[response].\n\n        Read json file with following format:\n\n        {\n          [list_of_knelpunten_for_route1]: {depth: costs_per_route_at_depth_per_day},\n          [list_of_knelpunten_for_route2]: {depth: costs_per_route_at_depth_per_day},\n          ...\n        }\n\n        e.g. (truncated notation)\n\n        {\n          [A, B]: {0.0: 1000, 1.0: 2000, 2.0: 1500},\n          [B, C]: {0.0: 2000, 1.0: 3000, 2.0: 1800}\n        }\n\n        \"\"\"\n        # Read output\n        routes_depth_costs = pd.read_json(routes_depth_costs_file, convert_dates=False, convert_axes=False)\n        routes_depth_costs.columns = [frozenset(i[1:-1].split(', ')) for i in routes_depth_costs.columns]\n        routes_depth_costs = routes_depth_costs.rename({frozenset({''}): frozenset()}, axis=1)\n        routes_depth_costs.index = [float(c) for c in routes_depth_costs.index]\n\n        self.routes = routes_depth_costs.columns\n\n        # Convert into interpolation function\n        depth_costs_functions = {}\n        for r in self.routes:\n            depth_costs = routes_depth_costs.xs(r, axis=1)\n            # Test this also: depth_costs = routes_depth_costs.xs(r)\n\n            depth_costs_function = interp1d(\n                x=depth_costs.index,\n                y=depth_costs.values,\n                kind='linear',\n                bounds_error=False,\n                fill_value=tuple(depth_costs.values[[0, -1]]),\n            )\n            depth_costs_functions[r] = depth_costs_function\n\n        self.routes_depth_costs = depth_costs_functions\n\n    def _read_knelpunt_discharge_depth(self, knelpunt_discharge_depth_file: Union[str, Path], reference=None):\n        \"\"\"\n        Read json file with for each knelpunt the discharge-depth relation. The discharges for all knelpunten (probably)\n        need to be identical\n\n        {\n               knelpunt1: {discharge: depth}\n               knelpunt2: {discharge: depth}\n        }\n\n        e.g.\n        {\n          'k1': {500: 2.5, 1000: 3, 2000: 4},\n          'k2': {200, 5, 800: 6, 1500: 7}\n        }\n\n        :param knelpunt_discharge_depth_file: path to json file\n\n        \"\"\"\n        if not isinstance(knelpunt_discharge_depth_file, dict):\n            with open(knelpunt_discharge_depth_file) as fin:\n                discharge_depth = json.load(fin)\n        else:\n            discharge_depth = knelpunt_discharge_depth_file\n\n        if reference is None:\n            # If not set, take the first\n            self.knelpunt_reference = list(discharge_depth.keys())[0]\n        else:\n            self.knelpunt_reference = reference\n\n\n        self.knelpunt_names = list(discharge_depth.keys())\n\n        self.knelpunt_discharge_depth = {}\n        knelpunt_discharge = {}\n        for k, QD in discharge_depth.items():\n            Q, D = zip(*QD.items())\n            Q = [float(q) for q in Q]\n            D = [float(d) for d in D]\n\n            # Make this an interpolation function, incl. extrapolation\n            discharge_depth_function = interp1d(\n                x=Q,\n                y=D,\n                kind='linear',\n                bounds_error=False,\n                fill_value='extrapolate',\n            )\n            self.knelpunt_discharge_depth[k] = discharge_depth_function\n            knelpunt_discharge[k] = Q\n\n        # Make lookup function of discharge at reference, to local discharge\n        Q_ref = knelpunt_discharge[self.knelpunt_reference]\n\n        self.knelpunt_discharge_distribution = {}\n        for k in discharge_depth:\n            Q = knelpunt_discharge[k]\n\n            # Make this an interpolation function, extrapolation=constant\n            Qref_Q = interp1d(\n                x=Q_ref,\n                y=Q,\n                kind='linear',\n                bounds_error=False,\n                fill_value='extrapolate',\n            )\n\n            self.knelpunt_discharge_distribution[k] = Qref_Q\n\n\n    def stats_knelpunten(self, Qmin=500, Qmax=2000):\n        \"\"\"\n        for each discharge determine the number of trips that is influenced by the knelpunt (alltrips)\n        for each knelpunt show only the trips that are limited by that specific point\n\n        return alltrips, mintrips\n        \"\"\"\n\n        alltrips = {}\n        mintrips = {}\n        mintrips_increase = {}\n\n        routes = self.routes_depth_costs.keys()\n\n        discharge_series = np.linspace(Qmin, Qmax, 100)\n\n        # Get discharge per knelpunt\n        Q_local = self._compute_local_discharge(discharge_series)\n\n        # Get depth per knelpunt and convert to draught by using ukc\n        QH = self._compute_knelpunt_depth(Q_local) - self.ukc\n\n        for r in routes:\n            # Depth on route\n            r_QH = QH[r]\n\n            # Get total costs on this route\n            depth_for_route = r_QH.min(axis=1).fillna(999)\n            costs_for_route = pd.Series(\n                data = self.routes_depth_costs[r](depth_for_route),\n                index = discharge_series\n            )\n            costs_for_route_increase = costs_for_route - costs_for_route.iloc[-1]\n\n            for k in r:\n\n                depth = r_QH[k].values\n\n                # Get number of affected trips (per waterdepth)\n                costs_for_all_passing_trips = self.routes_depth_costs[r](depth)\n                alltrips[(r, k)] = pd.Series(\n                    data=costs_for_all_passing_trips,\n                    index=discharge_series\n                )\n\n                # Only select those levels where k is the minimum depth on the route\n                k_minimal = r_QH.idxmin(axis=1) == k\n                mintrips[(r, k)] = costs_for_route.multiply(k_minimal, axis=0)\n                mintrips_increase[(r, k)] = costs_for_route_increase.multiply(k_minimal, axis=0)\n\n        alltrips = pd.concat(alltrips)\n        mintrips = pd.concat(mintrips)\n        mintrips_increase = pd.concat(mintrips_increase)\n\n        alltrips_sum = alltrips.unstack(level=1).sum(axis=0, level=1)\n        mintrips_sum = mintrips.unstack(level=1).sum(axis=0, level=1)\n        mintrips_increase_sum = mintrips_increase.unstack(level=1).sum(axis=0, level=1)\n        return alltrips_sum, mintrips_sum, mintrips_increase_sum\n\nif __name__ == '__main__':\n\n    inputdir = Path('../data')\n\n    M = QINCM(inputdir / 'route_depth_costs.json',\n              inputdir / 'knelpunt_discharge_waterdepth.json',\n              reference='WA_Nijmegen'\n              )\n\n    discharges = np.linspace(500, 3000, 26)\n\n    # print('Costs per route per discharge')\n    # a1 = M.costs_per_route_per_discharge(discharges)\n    # print(a1.head())\n\n    print('Costs per discharge')\n    a2 = M.costs_per_discharge(discharges)\n    print(a2.head())\n\n    # Create a random occurance so the total sum is a full year\n    occurance = np.random.rand(*discharges.shape)\n    occurance *= 365 / occurance.sum()\n\n    print('Costs per year')\n    a3 = M.costs_for_scenario(discharges, occurance)\n    print(a3)\n", "meta": {"hexsha": "21ed2475d3ff68473d1e8e5b82e3ce465457096a", "size": 12592, "ext": "py", "lang": "Python", "max_stars_repo_path": "qincm/qincm.py", "max_stars_repo_name": "Deltares/QINCM", "max_stars_repo_head_hexsha": "5d7004859dd171463187e83f090fd9dcce97fb70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "qincm/qincm.py", "max_issues_repo_name": "Deltares/QINCM", "max_issues_repo_head_hexsha": "5d7004859dd171463187e83f090fd9dcce97fb70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qincm/qincm.py", "max_forks_repo_name": "Deltares/QINCM", "max_forks_repo_head_hexsha": "5d7004859dd171463187e83f090fd9dcce97fb70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6887052342, "max_line_length": 146, "alphanum_fraction": 0.6113405337, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.35577490034429643, "lm_q1q2_score": 0.1889909618740043}}
{"text": "# coding: utf-8\n# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\nfrom __future__ import division, unicode_literals\n\n\"\"\"\nThis module contains the class describing the coordination geometries that can exist in a given structure. These\n\"model\" coordination geometries are described in the following articles :\n - Pure Appl. Chem., Vol. 79, No. 10, pp. 1779--1799, 2007.\n - Acta Cryst. A, Vol. 46, No. 1, pp. 1--11, 1990.\nThe module also contains descriptors of part of these geometries (plane of separation, ...) that are used in the\nidentification algorithms.\n\"\"\"\n\n__author__ = \"David Waroquiers\"\n__copyright__ = \"Copyright 2012, The Materials Project\"\n__credits__ = \"Geoffroy Hautier\"\n__version__ = \"2.0\"\n__maintainer__ = \"David Waroquiers\"\n__email__ = \"david.waroquiers@gmail.com\"\n__date__ = \"Feb 20, 2016\"\n\nimport numpy as np\nfrom scipy.misc import factorial\nimport itertools\nimport abc\nfrom monty.json import MSONable, MontyDecoder\nimport json\nimport os\nfrom six import with_metaclass\n\nmodule_dir = os.path.dirname(os.path.abspath(__file__))\n\nUNKNOWN_ENVIRONMENT_SYMBOL = 'UNKNOWN'\nUNCLEAR_ENVIRONMENT_SYMBOL = 'UNCLEAR'\nEXPLICIT_PERMUTATIONS = 'EXPLICIT_PERMUTATIONS'\nSEPARATION_PLANE = 'SEPARATION_PLANE'\n\n\nclass AbstractChemenvAlgorithm(with_metaclass(abc.ABCMeta, MSONable)):\n    \"\"\"\n    Class used to define a Chemenv strategy for the neighbors and coordination environment to be applied to a\n    StructureEnvironments object\n    \"\"\"\n\n    def __init__(self, algorithm_type):\n        self._algorithm_type = algorithm_type\n\n    @abc.abstractmethod\n    def as_dict(self):\n        \"\"\"\n        A JSON serializable dict representation of the algorithm\n        \"\"\"\n        pass\n\n    @property\n    def algorithm_type(self):\n        return self._algorithm_type\n\n    @abc.abstractmethod\n    def __str__(self):\n        return\n\n\nclass ExplicitPermutationsAlgorithm(AbstractChemenvAlgorithm):\n    def __init__(self, permutations):\n        \"\"\"\n            Initializes a separation plane for a given perfect coordination geometry\n        \"\"\"\n        super(ExplicitPermutationsAlgorithm, self).__init__(\n            algorithm_type=EXPLICIT_PERMUTATIONS)\n        self._permutations = permutations\n\n    def __str__(self):\n        return self.algorithm_type\n\n    @property\n    def permutations(self):\n        return self._permutations\n\n    @property\n    def as_dict(self):\n        return {\"@module\": self.__class__.__module__,\n                \"@class\": self.__class__.__name__,\n                \"permutations\": self._permutations}\n\n    @classmethod\n    def from_dict(cls, dd):\n        return cls(dd['permutations'])\n\n\nclass SeparationPlane(AbstractChemenvAlgorithm):\n    def __init__(self, plane_points, mirror_plane=False, ordered_plane=False,\n                 point_groups=None,\n                 ordered_point_groups=None,  # include_inverted_plane=False,\n                 point_groups_permutations=None,\n                 # do_inverse_pt_gp_permutations=False, plane_type='MIRROR',\n                 explicit_permutations=None, minimum_number_of_points=None,\n                 explicit_optimized_permutations=None,\n                 multiplicity=None,\n                 other_plane_points=None):  # , plane_safe_permutations=False):\n        \"\"\"\n            Initializes a separation plane for a given perfect coordination geometry\n\n            :param mirror_plane: True if the separation plane is a mirror plane, in which case there is a correspondence\n            of the points in each point_group (can reduce the number of permutations)\n            :param ordered_plane : True if the order of the points in the plane can be taken into account to reduce the\n            number of permutations\n            :param plane_points: Indices of the points that are in the plane in the perfect structure (and should be\n            found in the defective one as well)\n            :param point_groups: The two groups of points separated by the plane\n            :param plane_type: can be \"MIRROR\", if the plane is a mirror plane going through the central site,\n             'BASAL_THROUGH_CENTER', if the plane is a basal plane (no point on the \"left\" side) going through the central\n             site, 'BASAL', if the is a basal plane not going through the central site, 'UNEQUILIBRATED_THROUGH_CENTER', if\n             the plane cuts the geometry in two groups of points with different numbers of points on each side, and is going\n             through the centre, 'UNEQUILIBRATED', if the plane cuts the geometry in two groups of points with different\n             numbers of points on each side, and is not going through the centre, 'EQUILIBRATED_THROUGH_CENTER', if the\n             plane cuts the geometry in two groups of points of the same size, is going through the centre but is not a\n             mirror plane, 'EQUILIBRATED', if the plane cuts the geometry in two groups of points of the same size, is not\n             going through the centre but is not a mirror plane.\n            \"\"\"\n        super(SeparationPlane, self).__init__(algorithm_type=SEPARATION_PLANE)\n        self.mirror_plane = mirror_plane\n        self.plane_points = plane_points\n        self.point_groups = point_groups\n        if len(point_groups[0]) > len(point_groups[1]):\n            raise RuntimeError(\n                \"The number of points in the first group should be\\n\"\n                \"less than or equal to the number of points in the second group\")\n        self._hash = 10000 * len(plane_points) + 100 * len(\n            point_groups[0]) + len(point_groups[1])\n        self.ordered_plane = ordered_plane\n        self.ordered_point_groups = [False,\n                                     False] if ordered_point_groups is None else ordered_point_groups\n        self._ordered_indices = list(point_groups[0])\n        self._ordered_indices.extend(plane_points)\n        self._ordered_indices.extend(point_groups[1])\n        self._inv_ordered_indices = np.argsort(self._ordered_indices)\n        self._point_groups_permutations = point_groups_permutations\n        self.explicit_permutations = explicit_permutations\n        self.explicit_optimized_permutations = explicit_optimized_permutations\n        self._safe_permutations = None\n        if self.explicit_optimized_permutations is not None:\n            self._permutations = self.explicit_optimized_permutations\n        elif self.explicit_permutations is not None:\n            self._permutations = self.explicit_permutations\n        self.multiplicity = multiplicity\n        self.other_plane_points = other_plane_points\n        self.minimum_number_of_points = minimum_number_of_points\n        self.maximum_number_of_points = len(self.plane_points)\n        self._ref_separation_perm = list(self.point_groups[0])\n        self._ref_separation_perm.extend(list(self.plane_points))\n        self._ref_separation_perm.extend(list(self.point_groups[1]))\n        self._argsorted_ref_separation_perm = list(\n            np.argsort(self._ref_separation_perm))\n\n    @property\n    def ordered_indices(self):\n        return self._ordered_indices\n\n    @property\n    def inv_ordered_indices(self):\n        return self._inv_ordered_indices\n\n    @property\n    def permutations(self):\n        return self._permutations\n\n    @property\n    def ref_separation_perm(self):\n        return self._ref_separation_perm\n\n    @property\n    def argsorted_ref_separation_perm(self):\n        return self._argsorted_ref_separation_perm\n\n    def safe_plane_permutations(self, ordered_plane=False,\n                                ordered_point_groups=None):\n        ordered_point_groups = [False,\n                                False] if ordered_point_groups is None else ordered_point_groups\n        rotate = lambda s, n: s[-n:] + s[:-n]\n        if ordered_plane and self.ordered_plane:\n            plane_perms = [rotate(self.plane_points, ii) for ii in\n                           range(len(self.plane_points))]\n            invplanepoints = self.plane_points[::-1]\n            plane_perms.extend([rotate(invplanepoints, ii) for ii in\n                                range(len(self.plane_points) - 1, -1, -1)])\n        else:\n            plane_perms = list(itertools.permutations(self.plane_points))\n        if ordered_point_groups[0] and self.ordered_point_groups[0]:\n            s0_perms = [rotate(self.point_groups[0], ii) for ii in\n                        range(len(self.point_groups[0]))]\n            invpg0 = self.point_groups[0][::-1]\n            s0_perms.extend([rotate(invpg0, ii) for ii in range(len(invpg0))])\n        else:\n            s0_perms = list(itertools.permutations(self.point_groups[0]))\n        if ordered_point_groups[1] and self.ordered_point_groups[1]:\n            s2_perms = [rotate(self.point_groups[1], ii) for ii in\n                        range(len(self.point_groups[1]))]\n            invpg2 = self.point_groups[1][::-1]\n            s2_perms.extend([rotate(invpg2, ii) for ii in range(len(invpg2))])\n        else:\n            s2_perms = list(itertools.permutations(self.point_groups[1]))\n        add_opposite = False\n        if self._safe_permutations is None:\n            self._safe_permutations = []\n            for perm_side1 in s0_perms:\n                for perm_sep_plane in plane_perms:\n                    for perm_side2 in s2_perms:\n                        perm = list(perm_side1)\n                        perm.extend(list(perm_sep_plane))\n                        perm.extend(list(perm_side2))\n                        self._safe_permutations.append(perm)\n                        if add_opposite:\n                            perm = list(perm_side2)\n                            perm.extend(list(perm_sep_plane))\n                            perm.extend(list(perm_side1))\n                            self._safe_permutations.append(perm)\n        return self._safe_permutations\n\n    def safe_separation_permutations(self, ordered_plane=False,\n                                     ordered_point_groups=None,\n                                     add_opposite=False):\n        s0 = range(len(self.point_groups[0]))\n        plane = range(len(self.point_groups[0]),\n                      len(self.point_groups[0]) + len(self.plane_points))\n        s1 = range(len(self.point_groups[0]) + len(self.plane_points),\n                   len(self.point_groups[0]) + len(self.plane_points) + len(\n                       self.point_groups[1]))\n        ordered_point_groups = [False,\n                                False] if ordered_point_groups is None else ordered_point_groups\n        rotate = lambda s, n: s[-n:] + s[:-n]\n        if ordered_plane and self.ordered_plane:\n            plane_perms = [rotate(plane, ii) for ii in range(len(plane))]\n            inv_plane = plane[::-1]\n            plane_perms.extend(\n                [rotate(inv_plane, ii) for ii in range(len(inv_plane))])\n        else:\n            plane_perms = list(itertools.permutations(plane))\n        if ordered_point_groups[0] and self.ordered_point_groups[0]:\n            s0_perms = [rotate(s0, ii) for ii in range(len(s0))]\n            inv_s0 = s0[::-1]\n            s0_perms.extend([rotate(inv_s0, ii) for ii in range(len(inv_s0))])\n        else:\n            s0_perms = list(itertools.permutations(s0))\n        if ordered_point_groups[1] and self.ordered_point_groups[1]:\n            s1_perms = [rotate(s1, ii) for ii in range(len(s1))]\n            inv_s1 = s1[::-1]\n            s1_perms.extend([rotate(inv_s1, ii) for ii in range(len(inv_s1))])\n        else:\n            s1_perms = list(itertools.permutations(s1))\n        if self._safe_permutations is None:\n            self._safe_permutations = []\n            for perm_side1 in s0_perms:\n                for perm_sep_plane in plane_perms:\n                    for perm_side2 in s1_perms:\n                        perm = list(perm_side1)\n                        perm.extend(list(perm_sep_plane))\n                        perm.extend(list(perm_side2))\n                        self._safe_permutations.append(perm)\n                        if add_opposite:\n                            perm = list(perm_side2)\n                            perm.extend(list(perm_sep_plane))\n                            perm.extend(list(perm_side1))\n                            self._safe_permutations.append(perm)\n        return self._safe_permutations\n\n    @property\n    def as_dict(self):\n        return {\"@module\": self.__class__.__module__,\n                \"@class\": self.__class__.__name__,\n                \"plane_points\": self.plane_points,\n                \"mirror_plane\": self.mirror_plane,\n                \"ordered_plane\": self.ordered_plane,\n                \"point_groups\": self.point_groups,\n                \"ordered_point_groups\": self.ordered_point_groups,\n                \"point_groups_permutations\": self._point_groups_permutations,\n                \"explicit_permutations\": self.explicit_permutations,\n                \"explicit_optimized_permutations\": self.explicit_optimized_permutations,\n                \"multiplicity\": self.multiplicity,\n                \"other_plane_points\": self.other_plane_points,\n                \"minimum_number_of_points\": self.minimum_number_of_points}\n\n    @classmethod\n    def from_dict(cls, dd):\n        eop = dd[\n            'explicit_optimized_permutations'] if 'explicit_optimized_permutations' in dd else None\n        return cls(plane_points=dd['plane_points'],\n                   mirror_plane=dd['mirror_plane'],\n                   ordered_plane=dd['ordered_plane'],\n                   point_groups=dd['point_groups'],\n                   ordered_point_groups=dd['ordered_point_groups'],\n                   point_groups_permutations=dd['point_groups_permutations'],\n                   explicit_permutations=dd['explicit_permutations'],\n                   explicit_optimized_permutations=eop,\n                   multiplicity=dd[\n                       'multiplicity'] if 'multiplicity' in dd else None,\n                   other_plane_points=dd[\n                       'other_plane_points'] if 'other_plane_points' in dd else None,\n                   minimum_number_of_points=dd['minimum_number_of_points'])\n\n    def __str__(self):\n        out = 'Separation plane algorithm with the following reference separation :\\n'\n        out += '[{}] | [{}] | [{}]'.format(\n            '-'.join(str(pp) for pp in [self.point_groups[0]]),\n            '-'.join(str(pp) for pp in [self.plane_points]),\n            '-'.join(str(pp) for pp in [self.point_groups[1]]),\n        )\n        return out\n\n\nclass CoordinationGeometry(object):\n    \"\"\"\n    Class used to store the ideal representation of a chemical environment or \"coordination geometry\"\n    \"\"\"\n\n    class NeighborsSetsHints(object):\n\n        ALLOWED_HINTS_TYPES = ['single_cap', 'double_cap', 'triple_cap']\n\n        def __init__(self, hints_type, options):\n            if hints_type not in self.ALLOWED_HINTS_TYPES:\n                raise ValueError('Type \"{}\" for NeighborsSetsHints is not allowed'.format(type))\n            self.hints_type = hints_type\n            self.options = options\n\n        def hints(self, hints_info):\n            if hints_info['csm'] > self.options['csm_max']:\n                return []\n            return object.__getattribute__(self, '{}_hints'.format(self.hints_type))(hints_info)\n\n        def single_cap_hints(self, hints_info):\n            cap_index_perfect = self.options['cap_index']\n            nb_set = hints_info['nb_set']\n            permutation = hints_info['permutation']\n            nb_set_voronoi_indices_perfect_aligned = nb_set.get_neighb_voronoi_indices(permutation=permutation)\n            cap_voronoi_index = nb_set_voronoi_indices_perfect_aligned[cap_index_perfect]\n            new_site_voronoi_indices = list(nb_set.site_voronoi_indices)\n            new_site_voronoi_indices.remove(cap_voronoi_index)\n            return [new_site_voronoi_indices]\n\n        def double_cap_hints(self, hints_info):\n            first_cap_index_perfect = self.options['first_cap_index']\n            second_cap_index_perfect = self.options['second_cap_index']\n            nb_set = hints_info['nb_set']\n            permutation = hints_info['permutation']\n            nb_set_voronoi_indices_perfect_aligned = nb_set.get_neighb_voronoi_indices(permutation=permutation)\n            first_cap_voronoi_index = nb_set_voronoi_indices_perfect_aligned[first_cap_index_perfect]\n            second_cap_voronoi_index = nb_set_voronoi_indices_perfect_aligned[second_cap_index_perfect]\n            new_site_voronoi_indices1 = list(nb_set.site_voronoi_indices)\n            new_site_voronoi_indices2 = list(nb_set.site_voronoi_indices)\n            new_site_voronoi_indices3 = list(nb_set.site_voronoi_indices)\n            new_site_voronoi_indices1.remove(first_cap_voronoi_index)\n            new_site_voronoi_indices2.remove(second_cap_voronoi_index)\n            new_site_voronoi_indices3.remove(first_cap_voronoi_index)\n            new_site_voronoi_indices3.remove(second_cap_voronoi_index)\n            return [new_site_voronoi_indices1, new_site_voronoi_indices2, new_site_voronoi_indices3]\n\n        def triple_cap_hints(self, hints_info):\n            first_cap_index_perfect = self.options['first_cap_index']\n            second_cap_index_perfect = self.options['second_cap_index']\n            third_cap_index_perfect = self.options['third_cap_index']\n            nb_set = hints_info['nb_set']\n            permutation = hints_info['permutation']\n            nb_set_voronoi_indices_perfect_aligned = nb_set.get_neighb_voronoi_indices(permutation=permutation)\n            first_cap_voronoi_index = nb_set_voronoi_indices_perfect_aligned[first_cap_index_perfect]\n            second_cap_voronoi_index = nb_set_voronoi_indices_perfect_aligned[second_cap_index_perfect]\n            third_cap_voronoi_index = nb_set_voronoi_indices_perfect_aligned[third_cap_index_perfect]\n            new_site_voronoi_indices1 = list(nb_set.site_voronoi_indices)\n            new_site_voronoi_indices2 = list(nb_set.site_voronoi_indices)\n            new_site_voronoi_indices3 = list(nb_set.site_voronoi_indices)\n            new_site_voronoi_indices4 = list(nb_set.site_voronoi_indices)\n            new_site_voronoi_indices5 = list(nb_set.site_voronoi_indices)\n            new_site_voronoi_indices6 = list(nb_set.site_voronoi_indices)\n            new_site_voronoi_indices7 = list(nb_set.site_voronoi_indices)\n            new_site_voronoi_indices1.remove(first_cap_voronoi_index)\n            new_site_voronoi_indices2.remove(second_cap_voronoi_index)\n            new_site_voronoi_indices3.remove(third_cap_voronoi_index)\n            new_site_voronoi_indices4.remove(second_cap_voronoi_index)\n            new_site_voronoi_indices4.remove(third_cap_voronoi_index)\n            new_site_voronoi_indices5.remove(first_cap_voronoi_index)\n            new_site_voronoi_indices5.remove(third_cap_voronoi_index)\n            new_site_voronoi_indices6.remove(first_cap_voronoi_index)\n            new_site_voronoi_indices6.remove(second_cap_voronoi_index)\n            new_site_voronoi_indices7.remove(first_cap_voronoi_index)\n            new_site_voronoi_indices7.remove(second_cap_voronoi_index)\n            new_site_voronoi_indices7.remove(third_cap_voronoi_index)\n            return [new_site_voronoi_indices1, new_site_voronoi_indices2, new_site_voronoi_indices3,\n                    new_site_voronoi_indices4, new_site_voronoi_indices5, new_site_voronoi_indices6,\n                    new_site_voronoi_indices7]\n\n        def as_dict(self):\n            return {'hints_type': self.hints_type,\n                    'options': self.options}\n\n        @classmethod\n        def from_dict(cls, dd):\n            return cls(hints_type=dd['hints_type'],\n                       options=dd['options'])\n\n    def __init__(self, mp_symbol, name, alternative_names=None,\n                 IUPAC_symbol=None, IUCr_symbol=None, coordination=None,\n                 central_site=np.zeros(3), points=None, solid_angles=None,\n                 permutations_safe_override=False,\n                 plane_ordering_override=True, deactivate=False, faces=None,\n                 edges=None,\n                 plane_safe_permutations=False, algorithms=None,\n                 equivalent_indices=None,\n                 neighbors_sets_hints=None):\n        \"\"\"\n        Initializes one \"coordination geometry\" according to [Pure Appl. Chem., Vol. 79, No. 10, pp. 1779--1799, 2007]\n        and [Acta Cryst. A, Vol. 46, No. 1, pp. 1--11, 1990].\n        :param mp_symbol: Symbol used internally for the coordination geometry.\n        :param name: Name of the coordination geometry.\n        :param alternative_names: Alternative names for this coordination geometry.\n        :param IUPAC_symbol: The IUPAC symbol of this coordination geometry.\n        :param IUCr_symbol: The IUCr symbol of this coordination geometry.\n        :param coordination: The coordination number of this coordination geometry (number of neighboring atoms).\n        :param central_site: The coordinates of the central site of this coordination geometry.\n        :param points: The list of the coordinates of all the points of this coordination geometry.\n        :param separation_planes: List of separation facets to help set up the permutations\n        :param permutation_safe_override: Computes all the permutations if set to True (overrides the plane separation\n        algorithms or any other algorithm, for testing purposes)\n        :param plane_ordering_override: Computes all the permutations of the plane separation algorithm if set to False\n        otherwise, uses the anticlockwise ordering of the separation facets (for testing purposes)\n        :param deactivate: deactivates this coordination geometry in the search\n        :param faces : list of the faces with their vertices given in a clockwise or anticlockwise order, for drawing\n        purposes\n        :param : list of edges, for drawing purposes\n        \"\"\"\n        self._mp_symbol = mp_symbol\n        self.name = name\n        self.alternative_names = alternative_names if alternative_names is not None else []\n        self.IUPACsymbol = IUPAC_symbol\n        self.IUCrsymbol = IUCr_symbol\n        self.coordination = coordination\n        self.central_site = np.array(central_site)\n        self.points = points\n        self._solid_angles = solid_angles\n        self.permutations_safe_override = permutations_safe_override\n        self.plane_ordering_override = plane_ordering_override\n        self.plane_safe_permutations = plane_safe_permutations\n        # self.setup_permutations(permutations)\n        self.deactivate = deactivate\n        self._faces = faces\n        self._edges = edges\n        self._algorithms = algorithms\n        if points is not None:\n            self.centroid = np.mean(np.array(points), axis=0)\n        else:\n            self.centroid = None\n        self.equivalent_indices = equivalent_indices\n        self.neighbors_sets_hints = neighbors_sets_hints\n\n    def as_dict(self):\n        return {'mp_symbol': self._mp_symbol,\n                'name': self.name,\n                'alternative_names': self.alternative_names,\n                'IUPAC_symbol': self.IUPACsymbol,\n                'IUCr_symbol': self.IUCrsymbol,\n                'coordination': self.coordination,\n                'central_site': [float(xx) for xx in self.central_site],\n                'points': [[float(xx) for xx in pp] for pp in\n                           self.points] if self.points is not None else None,\n                'solid_angles': [float(ang) for ang in\n                                 self._solid_angles] if self._solid_angles is not None else None,\n                'deactivate': self.deactivate,\n                '_faces': self._faces,\n                '_edges': self._edges,\n                '_algorithms': [algo.as_dict for algo in\n                                self._algorithms] if self._algorithms is not None else None,\n                'equivalent_indices': self.equivalent_indices,\n                'neighbors_sets_hints': [nbsh.as_dict() for nbsh in self.neighbors_sets_hints]\n                if self.neighbors_sets_hints is not None else None}\n\n    @classmethod\n    def from_dict(cls, dd):\n        dec = MontyDecoder()\n        return cls(mp_symbol=dd['mp_symbol'],\n                   name=dd['name'],\n                   alternative_names=dd['alternative_names'],\n                   IUPAC_symbol=dd['IUPAC_symbol'],\n                   IUCr_symbol=dd['IUCr_symbol'],\n                   coordination=dd['coordination'],\n                   central_site=dd['central_site'],\n                   points=dd['points'],\n                   solid_angles=(dd['solid_angles'] if 'solid_angles' in dd\n                                 else [4.0 * np.pi / dd['coordination']] * dd[\n                       'coordination']),\n                   deactivate=dd['deactivate'],\n                   faces=dd['_faces'],\n                   edges=dd['_edges'],\n                   algorithms=[dec.process_decoded(algo_d)\n                               for algo_d in dd['_algorithms']] if dd[\n                                                                       '_algorithms'] is not None else None,\n                   equivalent_indices=dd[\n                       'equivalent_indices'] if 'equivalent_indices' in dd else None,\n                   neighbors_sets_hints=[cls.NeighborsSetsHints.from_dict(nbshd)\n                                         for nbshd in dd['neighbors_sets_hints']]\n                   if 'neighbors_sets_hints' in dd else None)\n\n    def __str__(self):\n        symbol = ''\n        if self.IUPAC_symbol is not None:\n            symbol += ' (IUPAC: {s}'.format(s=self.IUPAC_symbol)\n            if self.IUCr_symbol is not None:\n                symbol += ' || IUCr: {s})'.format(s=self.IUCr_symbol)\n            else:\n                symbol += ')'\n        elif self.IUCr_symbol is not None:\n            symbol += ' (IUCr: {s})'.format(s=self.IUCr_symbol)\n        outs = ['Coordination geometry type : {n}{s}\\n'.format(n=self.name,\n                                                               s=symbol),\n                '  - coordination number : {c}'.format(c=self.coordination)]\n        if self.points is None:\n            outs.append('... not yet implemented')\n        else:\n            outs.append('  - list of points :')\n            for pp in self.points:\n                outs.append('    - {p}'.format(p=pp))\n        outs.append(\n            '------------------------------------------------------------')\n        outs.append('')\n\n        return '\\n'.join(outs)\n\n    def __repr__(self):\n        symbol = ''\n        if self.IUPAC_symbol is not None:\n            symbol += ' (IUPAC: {s}'.format(s=self.IUPAC_symbol)\n            if self.IUCr_symbol is not None:\n                symbol += ' || IUCr: {s})'.format(s=self.IUCr_symbol)\n            else:\n                symbol += ')'\n        elif self.IUCr_symbol is not None:\n            symbol += ' (IUCr: {s})'.format(s=self.IUCr_symbol)\n        outs = ['Coordination geometry type : {n}{s}\\n'.format(n=self.name,\n                                                               s=symbol),\n                '  - coordination number : {c}'.format(c=self.coordination)]\n        outs.append(\n            '------------------------------------------------------------')\n        outs.append('')\n        return '\\n'.join(outs)\n\n    def __len__(self):\n        return self.coordination\n\n    def set_permutations_safe_override(self, permutations_safe_override):\n        self.permutations_safe_override = permutations_safe_override\n        # self.setup_permutations()\n\n    @property\n    def distfactor_max(self):\n        dists = [np.linalg.norm(pp - self.central_site) for pp in self.points]\n        return np.max(dists) / np.min(dists)\n\n    @property\n    def coordination_number(self):\n        \"\"\"\n        Returns the coordination number of this coordination geometry.\n        \"\"\"\n        return self.coordination\n\n    @property\n    def mp_symbol(self):\n        \"\"\"\n        Returns the MP symbol of this coordination geometry.\n        \"\"\"\n        return self._mp_symbol\n\n    @property\n    def ce_symbol(self):\n        \"\"\"\n        Returns the symbol of this coordination geometry.\n        \"\"\"\n        return self._mp_symbol\n\n    def get_coordination_number(self):\n        \"\"\"\n        Returns the coordination number of this coordination geometry.\n        \"\"\"\n        return self.coordination\n\n    def is_implemented(self):\n        \"\"\"\n        Returns True if this coordination geometry is implemented.\n        \"\"\"\n        return bool(self.points)\n\n    def get_name(self):\n        \"\"\"\n        Returns the name of this coordination geometry.\n        \"\"\"\n        return self.name\n\n    @property\n    def IUPAC_symbol(self):\n        \"\"\"\n        Returns the IUPAC symbol of this coordination geometry.\n        \"\"\"\n        return self.IUPACsymbol\n\n    @property\n    def IUPAC_symbol_str(self):\n        \"\"\"\n        Returns a string representation of the IUPAC symbol of this coordination geometry.\n        \"\"\"\n        return str(self.IUPACsymbol)\n\n    @property\n    def IUCr_symbol(self):\n        \"\"\"\n        Returns the IUCr symbol of this coordination geometry.\n        \"\"\"\n        return self.IUCrsymbol\n\n    @property\n    def IUCr_symbol_str(self):\n        \"\"\"\n        Returns a string representation of the IUCr symbol of this coordination geometry.\n        \"\"\"\n        return str(self.IUCrsymbol)\n\n    @property\n    def number_of_permutations(self):\n        \"\"\"\n        Returns the number of permutations of this coordination geometry.\n        \"\"\"\n        if self.permutations_safe_override:\n            return factorial(self.coordination)\n        elif self.permutations is None:\n            return factorial(self.coordination)\n        return len(self.permutations)\n\n    def ref_permutation(self, permutation):\n        perms = []\n        for eqv_indices in self.equivalent_indices:\n            perms.append(tuple([permutation[ii] for ii in eqv_indices]))\n        perms.sort()\n        return perms[0]\n\n    @property\n    def algorithms(self):\n        \"\"\"\n        Returns the list of algorithms that are used to identify this coordination geometry.\n        \"\"\"\n        return self._algorithms\n\n    def get_central_site(self):\n        \"\"\"\n        Returns the central site of this coordination geometry.\n        \"\"\"\n        return self.central_site\n\n    def faces(self, sites, permutation=None):\n        \"\"\"\n        Returns the list of faces of this coordination geometry. Each face is given as a\n        list of its vertices coordinates.\n        \"\"\"\n        if permutation is None:\n            coords = [site.coords for site in sites]\n        else:\n            coords = [sites[ii].coords for ii in permutation]\n        return [[coords[ii] for ii in f] for f in self._faces]\n\n    def edges(self, sites, permutation=None, input='sites'):\n        \"\"\"\n        Returns the list of edges of this coordination geometry. Each edge is given as a\n        list of its end vertices coordinates.\n        \"\"\"\n        if input == 'sites':\n            coords = [site.coords for site in sites]\n        elif input == 'coords':\n            coords = sites\n        # if permutation is None:\n        #     coords = [site.coords for site in sites]\n        # else:\n        #     coords = [sites[ii].coords for ii in permutation]\n        if permutation is not None:\n            coords = [coords[ii] for ii in permutation]\n        return [[coords[ii] for ii in e] for e in self._edges]\n\n    def solid_angles(self, permutation=None):\n        \"\"\"\n        Returns the list of \"perfect\" solid angles Each edge is given as a\n        list of its end vertices coordinates.\n        \"\"\"\n        if permutation is None:\n            return self._solid_angles\n        else:\n            return [self._solid_angles[ii] for ii in permutation]\n\n    def get_pmeshes(self, sites, permutation=None):\n        \"\"\"\n        Returns the pmesh strings used for jmol to show this geometry.\n        \"\"\"\n        pmeshes = []\n        # _vertices = [site.coords for site in sites]\n        if permutation is None:\n            _vertices = [site.coords for site in sites]\n        else:\n            _vertices = [sites[ii].coords for ii in permutation]\n        _face_centers = []\n        number_of_faces = 0\n        for face in self._faces:\n            if len(face) in [3, 4]:\n                number_of_faces += 1\n            else:\n                number_of_faces += len(face)\n\n            _face_centers.append(np.array([np.mean([_vertices[face_vertex][ii]\n                                                    for face_vertex in face])\n                                           for ii in range(3)]))\n\n        out = '{}\\n'.format(len(_vertices) + len(_face_centers))\n        for vv in _vertices:\n            out += '{:15.8f} {:15.8f} {:15.8f}\\n'.format(vv[0], vv[1], vv[2])\n        for fc in _face_centers:\n            out += '{:15.8f} {:15.8f} {:15.8f}\\n'.format(fc[0], fc[1], fc[2])\n        out += '{:d}\\n'.format(number_of_faces)\n        for iface, face in enumerate(self._faces):\n            if len(face) == 3:\n                out += '4\\n'\n            elif len(face) == 4:\n                out += '5\\n'\n            else:\n                for ii in range(len(face)):\n                    out += '4\\n'\n                    out += '{:d}\\n'.format(len(_vertices) + iface)\n                    out += '{:d}\\n'.format(face[ii])\n                    out += '{:d}\\n'.format(face[np.mod(ii + 1, len(face))])\n                    out += '{:d}\\n'.format(len(_vertices) + iface)\n            if len(face) in [3, 4]:\n                for face_vertex in face:\n                    out += '{:d}\\n'.format(face_vertex)\n                out += '{:d}\\n'.format(face[0])\n        pmeshes.append({\"pmesh_string\": out})\n        return pmeshes\n\n    def get_pmeshes_test(self, sites, permutation=None):\n        \"\"\"\n        Returns the pmesh strings used for jmol to show this geometry.\n        \"\"\"\n        pmeshes = []\n        _vertices = [site.coords for site in sites]\n        # if permutation is None:\n        #    _vertices = [site.coords for site in sites]\n        # else:\n        #    _vertices = [sites[ii].coords for ii in permutation]\n        _face_centers = []\n        number_of_faces = 0\n        for face in self._faces:\n            if len(face) in [3, 4]:\n                number_of_faces += 1\n            else:\n                number_of_faces += len(face)\n\n            _face_centers.append(np.array([np.mean([_vertices[face_vertex][ii]\n                                                    for face_vertex in face])\n                                           for ii in range(3)]))\n\n        out = '{}\\n'.format(len(_vertices) + len(_face_centers))\n        for vv in _vertices:\n            out += '{:15.8f} {:15.8f} {:15.8f}\\n'.format(vv[0], vv[1], vv[2])\n        for fc in _face_centers:\n            out += '{:15.8f} {:15.8f} {:15.8f}\\n'.format(fc[0], fc[1], fc[2])\n        out += '{:d}\\n'.format(number_of_faces)\n        for iface, face in enumerate(self._faces):\n            if len(face) == 3:\n                out += '4\\n'\n            elif len(face) == 4:\n                out += '5\\n'\n            else:\n                for ii in range(len(face)):\n                    out += '4\\n'\n                    out += '{:d}\\n'.format(len(_vertices) + iface)\n                    out += '{:d}\\n'.format(permutation[face[ii]])\n                    out += '{:d}\\n'.format(\n                        permutation[face[np.mod(ii + 1, len(face))]])\n                    out += '{:d}\\n'.format(len(_vertices) + iface)\n            if len(face) in [3, 4]:\n                for face_vertex in face:\n                    out += '{:d}\\n'.format(permutation[face_vertex])\n                out += '{:d}\\n'.format(permutation[face[0]])\n        pmeshes.append({\"pmesh_string\": out})\n        return pmeshes\n\n\nclass AllCoordinationGeometries(dict):\n    \"\"\"\n    Class used to store all the reference \"coordination geometries\" (list with instances of the CoordinationGeometry\n    classes)\n    \"\"\"\n\n    def __init__(self, permutations_safe_override=False, only_symbols=None):\n        \"\"\"\n            Initializes the list of Coordination Geometries\n            :param permutations_safe_override:\n            :param only_symbols:\n            \"\"\"\n        dict.__init__(self)\n        self.cg_list = list()\n        if only_symbols is None:\n            f = open(\n                '{}/coordination_geometries_files/allcg.txt'.format(module_dir),\n                'r')\n            data = f.readlines()\n            f.close()\n            for line in data:\n                cg_file = '{}/{}'.format(module_dir, line.strip())\n                f = open(cg_file, 'r')\n                dd = json.load(f)\n                f.close()\n                self.cg_list.append(CoordinationGeometry.from_dict(dd))\n        else:\n            for symbol in only_symbols:\n                fsymbol = symbol.replace(':', '#')\n                cg_file = '{}/coordination_geometries_files/{}.json'.format(\n                    module_dir, fsymbol)\n                f = open(cg_file, 'r')\n                dd = json.load(f)\n                f.close()\n                self.cg_list.append(CoordinationGeometry.from_dict(dd))\n\n        self.cg_list.append(CoordinationGeometry(UNKNOWN_ENVIRONMENT_SYMBOL,\n                                                 \"Unknown environment\",\n                                                 deactivate=True))\n        self.cg_list.append(CoordinationGeometry(UNCLEAR_ENVIRONMENT_SYMBOL,\n                                                 \"Unclear environment\",\n                                                 deactivate=True))\n        if permutations_safe_override:\n            for cg in self.cg_list:\n                cg.set_permutations_safe_override(True)\n\n    def __getitem__(self, key):\n        return self.get_geometry_from_mp_symbol(key)\n\n    def __repr__(self):\n        \"\"\"\n        Returns a string with the list of coordination geometries.\n        \"\"\"\n        outs = ['', '#=================================#',\n                '# List of coordination geometries #',\n                '#=================================#', '']\n        for cg in self.cg_list:\n            outs.append(repr(cg))\n\n        return '\\n'.join(outs)\n\n    def __str__(self):\n        \"\"\"\n        Returns a string with the list of coordination geometries that are implemented.\n        \"\"\"\n        outs = ['', '#=======================================================#',\n                '# List of coordination geometries currently implemented #',\n                '#=======================================================#', '']\n        for cg in self.cg_list:\n            if cg.is_implemented():\n                outs.append(str(cg))\n\n        return '\\n'.join(outs)\n\n    def get_geometries(self, coordination=None, returned='cg'):\n        \"\"\"\n        Returns a list of coordination geometries with the given coordination number.\n        :param coordination: The coordination number of which the list of coordination geometries are returned.\n        \"\"\"\n        geom = list()\n        if coordination is None:\n            for gg in self.cg_list:\n                if returned == 'cg':\n                    geom.append(gg)\n                elif returned == 'mp_symbol':\n                    geom.append(gg.mp_symbol)\n        else:\n            for gg in self.cg_list:\n                if gg.get_coordination_number() == coordination:\n                    if returned == 'cg':\n                        geom.append(gg)\n                    elif returned == 'mp_symbol':\n                        geom.append(gg.mp_symbol)\n        return geom\n\n    def get_symbol_name_mapping(self, coordination=None):\n        geom = {}\n        if coordination is None:\n            for gg in self.cg_list:\n                geom[gg.mp_symbol] = gg.name\n        else:\n            for gg in self.cg_list:\n                if gg.get_coordination_number() == coordination:\n                    geom[gg.mp_symbol] = gg.name\n        return geom\n\n    def get_symbol_cn_mapping(self, coordination=None):\n        geom = {}\n        if coordination is None:\n            for gg in self.cg_list:\n                geom[gg.mp_symbol] = gg.coordination_number\n        else:\n            for gg in self.cg_list:\n                if gg.get_coordination_number() == coordination:\n                    geom[gg.mp_symbol] = gg.coordination_number\n        return geom\n\n    def get_implemented_geometries(self, coordination=None, returned='cg',\n                                   include_deactivated=False):\n        \"\"\"\n        Returns a list of the implemented coordination geometries with the given coordination number.\n        :param coordination: The coordination number of which the list of implemented coordination geometries\n        are returned.\n        \"\"\"\n        geom = list()\n        if coordination is None:\n            for gg in self.cg_list:\n                if gg.points is not None and (\n                            (not gg.deactivate) or include_deactivated):\n                    if returned == 'cg':\n                        geom.append(gg)\n                    elif returned == 'mp_symbol':\n                        geom.append(gg.mp_symbol)\n        else:\n            for gg in self.cg_list:\n                if gg.get_coordination_number() == coordination and gg.points is not None and \\\n                        ((not gg.deactivate) or include_deactivated):\n                    if returned == 'cg':\n                        geom.append(gg)\n                    elif returned == 'mp_symbol':\n                        geom.append(gg.mp_symbol)\n        return geom\n\n    def get_not_implemented_geometries(self, coordination=None,\n                                       returned='mp_symbol'):\n        \"\"\"\n        Returns a list of the implemented coordination geometries with the given coordination number.\n        :param coordination: The coordination number of which the list of implemented coordination geometries\n        are returned.\n        \"\"\"\n        geom = list()\n        if coordination is None:\n            for gg in self.cg_list:\n                if gg.points is None:\n                    if returned == 'cg':\n                        geom.append(gg)\n                    elif returned == 'mp_symbol':\n                        geom.append(gg.mp_symbol)\n        else:\n            for gg in self.cg_list:\n                if gg.get_coordination_number() == coordination and gg.points is None:\n                    if returned == 'cg':\n                        geom.append(gg)\n                    elif returned == 'mp_symbol':\n                        geom.append(gg.mp_symbol)\n        return geom\n\n    def get_geometry_from_name(self, name):\n        \"\"\"\n        Returns the coordination geometry of the given name.\n        :param name: The name of the coordination geometry.\n        \"\"\"\n        for gg in self.cg_list:\n            if gg.name == name or name in gg.alternative_names:\n                return gg\n        raise LookupError(\n            'No coordination geometry found with name \"{name}\"'.format(\n                name=name))\n\n    def get_geometry_from_IUPAC_symbol(self, IUPAC_symbol):\n        \"\"\"\n        Returns the coordination geometry of the given IUPAC symbol.\n        :param IUPAC_symbol: The IUPAC symbol of the coordination geometry.\n        \"\"\"\n        for gg in self.cg_list:\n            if gg.IUPAC_symbol == IUPAC_symbol:\n                return gg\n        raise LookupError(\n            'No coordination geometry found with IUPAC symbol \"{symbol}\"'.format(\n                symbol=IUPAC_symbol))\n\n    def get_geometry_from_IUCr_symbol(self, IUCr_symbol):\n        \"\"\"\n        Returns the coordination geometry of the given IUCr symbol.\n        :param IUCr_symbol: The IUCr symbol of the coordination geometry.\n        \"\"\"\n        for gg in self.cg_list:\n            if gg.IUCr_symbol == IUCr_symbol:\n                return gg\n        raise LookupError(\n            'No coordination geometry found with IUCr symbol \"{symbol}\"'.format(\n                symbol=IUCr_symbol))\n\n    def get_geometry_from_mp_symbol(self, mp_symbol):\n        \"\"\"\n        Returns the coordination geometry of the given mp_symbol.\n        :param mp_symbol: The mp_symbol of the coordination geometry.\n        \"\"\"\n        for gg in self.cg_list:\n            if gg.mp_symbol == mp_symbol:\n                return gg\n        raise LookupError(\n            'No coordination geometry found with mp_symbol \"{symbol}\"'.format(\n                symbol=mp_symbol))\n\n    def is_a_valid_coordination_geometry(self, mp_symbol=None,\n                                         IUPAC_symbol=None, IUCr_symbol=None,\n                                         name=None, cn=None):\n        \"\"\"\n        Checks whether a given coordination geometry is valid (exists) and whether the parameters are coherent with\n        each other.\n        :param IUPAC_symbol:\n        :param IUCr_symbol:\n        :param name:\n        :param cn:\n        :param mp_symbol: The mp_symbol of the coordination geometry.\n        \"\"\"\n        if name is not None:\n            raise NotImplementedError(\n                'is_a_valid_coordination_geometry not implemented for the name')\n        if mp_symbol is None and IUPAC_symbol is None and IUCr_symbol is None:\n            raise SyntaxError(\n                'missing argument for is_a_valid_coordination_geometry : at least one of mp_symbol, '\n                'IUPAC_symbol and IUCr_symbol must be passed to the function')\n        if mp_symbol is not None:\n            try:\n                cg = self.get_geometry_from_mp_symbol(mp_symbol)\n                if IUPAC_symbol is not None:\n                    if IUPAC_symbol != cg.IUPAC_symbol:\n                        return False\n                if IUCr_symbol is not None:\n                    if IUCr_symbol != cg.IUCr_symbol:\n                        return False\n                if cn is not None:\n                    if int(cn) != int(cg.coordination_number):\n                        return False\n                return True\n            except LookupError:\n                return False\n        elif IUPAC_symbol is not None:\n            try:\n                cg = self.get_geometry_from_IUPAC_symbol(IUPAC_symbol)\n                if IUCr_symbol is not None:\n                    if IUCr_symbol != cg.IUCr_symbol:\n                        return False\n                if cn is not None:\n                    if cn != cg.coordination_number:\n                        return False\n                return True\n            except LookupError:\n                return False\n        elif IUCr_symbol is not None:\n            try:\n                cg = self.get_geometry_from_IUCr_symbol(IUCr_symbol)\n                if cn is not None:\n                    if cn != cg.coordination_number:\n                        return False\n                return True\n            except LookupError:\n                return True\n        raise Exception('Should not be here !')\n\n    def pretty_print(self, type='implemented_geometries', maxcn=8, additional_info=None):\n        if type == 'all_geometries_latex_images':\n            mystring = ''\n            for cn in range(1, maxcn + 1):\n                mystring += '\\\\section*{{Coordination {cn}}}\\n\\n'.format(cn=cn)\n                for cg in self.get_implemented_geometries(coordination=cn,\n                                                          returned='cg'):\n                    mystring += '\\\\subsubsection*{{{mp} : {name}}}\\n\\n'.format(\n                        mp=cg.mp_symbol, name=cg.get_name())\n                    mystring += 'IUPAC : {iupac}\\n\\nIUCr : {iucr}\\n\\n'.format(\n                        iupac=cg.IUPAC_symbol, iucr=cg.IUCr_symbol)\n                    mystring += '\\\\begin{center}\\n'\n                    mystring += '\\\\includegraphics[scale=0.15]{{images/{let}_{cif}.png}}\\n'.format(\n                        let=cg.mp_symbol.split(':')[0],\n                        cif=cg.mp_symbol.split(':')[1])\n                    mystring += '\\\\end{center}\\n\\n'\n                for cg in self.get_not_implemented_geometries(cn,\n                                                              returned='cg'):\n                    mystring += '\\\\subsubsection*{{{mp} : {name}}}\\n\\n'.format(\n                        mp=cg.mp_symbol, name=cg.get_name())\n                    mystring += 'IUPAC : {iupac}\\n\\nIUCr : {iucr}\\n\\n'.format(\n                        iupac=cg.IUPAC_symbol, iucr=cg.IUCr_symbol)\n        elif type == 'all_geometries_latex':\n            mystring = ''\n            for cn in range(1, maxcn + 1):\n                mystring += '\\\\subsection*{{Coordination {cn}}}\\n\\n'.format(\n                    cn=cn)\n                mystring += '\\\\begin{itemize}\\n'\n                for cg in self.get_implemented_geometries(coordination=cn,\n                                                          returned='cg'):\n                    mystring += '\\\\item {mp} $\\\\rightarrow$ {name} '.format(\n                        mp=cg.mp_symbol.replace('_',\n                                                '\\\\_'),\n                        name=cg.get_name())\n                    mystring += '(IUPAC : {iupac} - IUCr : {iucr})\\n'.format(\n                        iupac=cg.IUPAC_symbol_str,\n                        iucr=cg.IUCr_symbol_str.replace('[', '$[$').replace(']',\n                                                                            '$]$'))\n                for cg in self.get_not_implemented_geometries(cn,\n                                                              returned='cg'):\n                    mystring += '\\\\item {mp} $\\\\rightarrow$ {name} '.format(\n                        mp=cg.mp_symbol.replace('_',\n                                                '\\\\_'),\n                        name=cg.get_name())\n                    mystring += '(IUPAC : {iupac} - IUCr : {iucr})\\n'.format(\n                        iupac=cg.IUPAC_symbol_str,\n                        iucr=cg.IUCr_symbol_str.replace('[', '$[$').replace(']',\n                                                                            '$]$'))\n                mystring += '\\\\end{itemize}\\n\\n'\n        else:\n            mystring = '+-------------------------+\\n| Coordination geometries |\\n+-------------------------+\\n\\n'\n            for cn in range(1, maxcn + 1):\n                mystring += '==>> CN = {cn} <<==\\n'.format(cn=cn)\n                if type == 'implemented_geometries':\n                    for cg in self.get_implemented_geometries(coordination=cn):\n                        if additional_info is not None:\n                            if 'nb_hints' in additional_info:\n                                if cg.neighbors_sets_hints is not None:\n                                    addinfo = ' *'\n                                else:\n                                    addinfo = ''\n                            else:\n                                addinfo = ''\n                        else:\n                            addinfo = ''\n                        mystring += ' - {mp} : {name}{addinfo}\\n'.format(mp=cg.mp_symbol,\n                                                                  name=cg.get_name(),\n                                                                  addinfo=addinfo)\n                elif type == 'all_geometries':\n                    for cg in self.get_geometries(coordination=cn):\n                        mystring += ' - {mp} : {name}\\n'.format(mp=cg.mp_symbol,\n                                                                name=cg.get_name())\n                mystring += '\\n'\n        return mystring\n", "meta": {"hexsha": "601f59d6275598e17e66ae5d0ce6df5103f7f991", "size": 51388, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py", "max_stars_repo_name": "mailhexu/pymatgen", "max_stars_repo_head_hexsha": "70da55dd860771eb9d38c306dbcd3f6b074b7a54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2019-06-15T18:08:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T05:01:29.000Z", "max_issues_repo_path": "ComRISB/pyextern/pymatgen/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py", "max_issues_repo_name": "comscope/Comsuite", "max_issues_repo_head_hexsha": "b80ca9f34c519757d337487c489fb655f7598cc2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ComRISB/pyextern/pymatgen/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py", "max_forks_repo_name": "comscope/Comsuite", "max_forks_repo_head_hexsha": "b80ca9f34c519757d337487c489fb655f7598cc2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-06-05T02:57:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T02:54:25.000Z", "avg_line_length": 45.235915493, "max_line_length": 124, "alphanum_fraction": 0.5703471628, "include": true, "reason": "import numpy,from scipy", "num_tokens": 10747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3557749003442964, "lm_q1q2_score": 0.18899096187400427}}
{"text": "# occiput\n\n# Stefano Pedemonte\n# Aalto University, School of Science, Helsinki\n# Oct 2013, Helsinki\n# Martinos Center for Biomedical Imaging, Harvard University/MGH, Boston\n# Dec. 2013, Boston\n# Martinos Center for Biomedical Imaging, Harvard University/MGH, Boston\n# Jan. 2015, Boston\n# Feb. 2015, Helsinki\n# Nov. 2015, Boston\n\n# Michele Scipioni\n# Martinos Center for Biomedical Imaging, Harvard University/MGH, Boston\n# Jan. 2017, Boston\n# University of Pisa, Department of Information Engineering, Pisa, Italy\n# Sep. 2017, Pisa\n\n# If you are looking for how PET reconstruction is implemented in Occiput, this is where to start.\n# The objects defined here provide a abstractions for Static and Dynamic PET reconstruction,\n# abstracting the scanner geometries and vendor models and providing an interface for\n# projection, backprojection and tomographic reconstruction.\n\nfrom __future__ import absolute_import, print_function, division\nimport copy\nimport os\n\n# Import interfile data handling module\nfrom ....interfile import Interfile\nfrom numpy import asarray, exp, flipud, fliplr\n# Import other modules\nfrom numpy import isscalar, linspace, int32, ones, zeros, pi, sqrt, float32, where, ndarray, tile\nfrom scipy import ndimage\n\n# Import occiput:\nfrom ...Core import Image3D\nfrom ...Core import Transform_Identity, Transform_Scale\nfrom ...Core.Errors import FileNotFound, UnknownParameter, UnexpectedParameter\nfrom ...Core.Print import array_to_string\nfrom ...Core.Print import millisec_to_min_sec, pretty_print_large_number, print_percentage\nfrom ...DataSources.FileSources.Files import guess_file_type_by_name\nfrom ...DataSources.FileSources.PET_projection import import_PET_Projection\nfrom ...DataSources.FileSources.PET_projection import import_interfile_projection\nfrom ...DataSources.FileSources.PET_volume import import_interfile_volume\nfrom ...DataSources.Synthetic.Shapes import uniform_cylinder\n# Import ilang (inference language; optimisation)\nfrom .PET_ilang import PET_Static_Poisson, PET_Dynamic_Poisson, ProbabilisticGraphicalModel\nfrom .PET_profiler import ReconstructionProfiler\nfrom .PET_projection import PET_Projection, Binning, PET_Projection_Sparsity\nfrom .PET_projection import PET_initialize_compression_structure\nfrom .PET_projection import display_PET_Projection_geometry\nfrom .PET_raytracer import PET_project_compressed, PET_backproject_compressed\nfrom .PET_raytracer import ProjectionParameters, BackprojectionParameters\nfrom .PET_scanners import Generic, get_scanner_by_name\nfrom .PET_subsets import SubsetGenerator\nfrom ...Visualization.Visualization import ipy_table, has_ipy_table, ProgressBar\n# Set verbose level\n# This is a global setting for occiput. There are 3 levels of verbose: high, low, no_printing\nfrom ...global_settings import *\n\n# Import DisplayNode to produce ipython notebook visualisations\n\ntry:\n    import pylab\nexcept:\n    has_pylab = False\nelse:\n    has_pylab = True\n\n__all__ = ['PET_Static_Scan', 'PET_Multi2D_Scan', 'PET_Dynamic_Scan', 'PET_Cyclic_Scan',\n           'Binning', 'PET_Projection_Sparsity', 'PET_Projection', 'RigidTransform']\n\n# set_verbose_high()\n# set_verbose_low()\nset_verbose_no_printing()\n\n# Default parameters\nDEFAULT_SUBSET_SIZE = 24\nDEFAULT_RECON_ITERATIONS = 10\nDEFAULT_N_TIME_BINS = 15\nEPS = 1e-6\n\n\ndef f_continuous(var):\n    \"\"\"Makes an nd_array Fortran-contiguous. \"\"\"\n    if isinstance(var, ndarray):\n        if not var.flags.f_contiguous:\n            var = asarray(var, order='F')\n    else:\n        if hasattr(var, 'data'):\n            if isinstance(var.data, ndarray):\n                if not var.data.flags.f_contiguous:\n                    var.data = asarray(var.data, order='F')\n    return var\n\n\n# FIXME: eliminate the class RigidTransform; use transformation matrices\n# in Image3D instead, for activity and attenuation volumes. # Use\n# Core.Transform_6DOF or Core.Transform_Affine if required, to\n# parameterize the projector and back_projector.\n\nclass RigidTransform:\n    \"\"\"Region of Interest. Legacy! \"\"\"\n\n    def __init__(self, parameters=(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)):\n        if type(parameters) == dict:\n            self.load_from_dictionary(parameters)\n        elif type(parameters) in [list, tuple]:\n            if len(parameters) == 6:\n                self.x = parameters[0]\n                self.y = parameters[1]\n                self.z = parameters[2]\n                self.theta_x = parameters[3]\n                self.theta_y = parameters[4]\n                self.theta_z = parameters[5]\n            else:\n                raise UnknownParameter(\n                    'Parameter %s specified for the construction of RigidTransform is not compatible. ' % str(\n                        parameters))\n        else:\n            raise UnknownParameter(\n                'Parameter %s specified for the construction of RigidTransform is not compatible. ' % str(parameters))\n\n    def load_from_dictionary(self, dictionary):\n        self.x = dictionary['x']  # Translation along x\n        self.y = dictionary['y']  # Translation along y\n        self.z = dictionary['z']  # Translation along z\n        self.theta_x = dictionary['theta_x']  # Rotation around x\n        self.theta_y = dictionary['theta_y']  # Rotation around y\n        self.theta_z = dictionary['theta_z']  # Rotation around z\n\n    def __repr__(self):\n        s = \"PET volume location (RigidTransform): \\n\"\n        s = s + \" - x:             %f \\n\" % self.x\n        s = s + \" - y:             %f \\n\" % self.y\n        s = s + \" - z:             %f \\n\" % self.z\n        s = s + \" - theta_x:       %f \\n\" % self.theta_x\n        s = s + \" - theta_y:       %f \\n\" % self.theta_y\n        s = s + \" - theta_z:       %f \\n\" % self.theta_z\n        return s\n\n    def _repr_html_(self):\n        if not has_ipy_table:\n            return \"Please install ipy_table.\"\n        table_data = [['x', self.x], ['y', self.y], ['z', self.z], ['theta_x',\n                                                                    self.theta_x], ['theta_y', self.theta_y],\n                      ['theta_z', self.theta_z]]\n        table = ipy_table.make_table(table_data)\n        table = ipy_table.apply_theme('basic_left')\n        # table = ipy_table.set_column_style(0, color='lightBlue')\n        table = ipy_table.set_global_style(float_format=\"%3.3f\")\n        return table._repr_html_()\n\n\n#########################################################################\n#########\t\t[CLASS] PET_Static_Scan\t\t\t#########\n#########################################################################\n\n\nclass PET_Static_Scan():\n    \"\"\"PET Static Scan. \"\"\"\n\n    ########### INITIALIZATION FUNCTIONS\n    def __init__(self):\n        self.use_gpu(True)  # by default, use GPU.\n        self.set_scanner(Generic)  # set scanner geometry and load interface\n        self.activity = None  # memoization of activity.\n        self.attenuation = None  # memoization of attenuation.\n        self.attenuation_projection = None  # memoization of attenuation projection.\n        self.sensitivity = None  # sensitivity is a permanent parameter.\n        self.prompts = None  # measurement: prompts. Initialized as empty data structure.\n        self.randoms = None\n        self.scatter = None\n        self._normalization = None  # normalization volume - for all projections - memoize\n        self._need_normalization_update = True  # If True, the normalization volume needs to be recomputed\n        self.use_compression(False)\n        self.set_transform_scanner_to_world(Transform_Identity(map_from='scanner', map_to='world'))\n        self.profiler = ReconstructionProfiler()\n\n    def set_transform_scanner_to_world(self, transform):\n        # FIXME: here raise an error if the transform does not map from 'scanner' to 'world'\n        self.transform_scanner_to_world = transform\n\n    def _make_Image3D_activity(self, data=None):\n        shape = float32(self.activity_shape)\n        size = float32(self.activity_size)\n        T_scanner_to_world = self.transform_scanner_to_world\n        T_pix_to_scanner = Transform_Scale(size / shape, map_from='pixels_PET_Static', map_to='scanner')\n        T_pix_to_world = T_scanner_to_world.left_multiply(T_pix_to_scanner)\n        image = Image3D(data=data, affine=T_pix_to_world, space='world')\n        return image\n\n    def _make_Image3D_attenuation(self, data=None):\n        shape = float32(self.attenuation_shape)\n        size = float32(self.attenuation_size)\n        T_scanner_to_world = self.transform_scanner_to_world\n        T_pix_to_scanner = Transform_Scale(size / shape, map_from='pixels_PET_Static', map_to='scanner')\n        T_pix_to_world = T_scanner_to_world.left_multiply(T_pix_to_scanner)\n        image = Image3D(data=data, affine=T_pix_to_world, space='world')\n        return image\n\n    ########### SET SHAPE PARAMS\n\n    def set_activity_shape(self, activity_shape):\n        if not len(activity_shape) == 3:\n            print(\"Invalid activity shape\")  # FIXME: raise invalid input error\n        else:\n            self.activity_shape = activity_shape\n\n    def set_activity_size(self, activity_size):\n        if not len(activity_size) == 3:\n            print(\"Invalid activity size\")  # FIXME: raise invalid input error\n        else:\n            self.activity_size = activity_size\n        self._adapt_line_step_size_activity()\n\n    def set_attenuation_shape(self, attenuation_shape):\n        if not len(attenuation_shape) == 3:\n            print(\"Invalid attenuation shape\")  # FIXME: raise invalid input error\n        else:\n            self.attenuation_shape = attenuation_shape\n\n    def set_attenuation_size(self, attenuation_size):\n        if not len(attenuation_size) == 3:\n            print(\"Invalid attenuation size\")  # FIXME: raise invalid input error\n        else:\n            self.attenuation_size = attenuation_size\n        self._adapt_line_step_size_attenuation()\n\n    def _get_sparsity(self):\n        # if self.prompts == None:\n        # in this case returns sparsity pattern for uncompressed projection\n        sparsity = PET_Projection_Sparsity(\n            self.binning.N_axial, self.binning.N_azimuthal, self.binning.N_u, self.binning.N_v)\n        # else:\n        #    sparsity = self.prompts.sparsity\n        return sparsity\n\n    def set_scale_activity(self, scale):\n        self.scale_activity = float32(scale)\n\n    def _adapt_line_step_size_activity(self):  # FIXME: move this calculation in the raytracer\n        if not hasattr(self, 'activity_size'):\n            activity_size = float32([0, 0, 0])\n        elif self.activity_size is None:\n            activity_size = float32([0, 0, 0])\n        else:\n            activity_size = float32(self.activity_size)\n        diagonal = sqrt((activity_size ** 2).sum())\n        self.activity_projection_parameters.sample_step = diagonal / self.activity_projection_parameters.N_samples\n        self.activity_backprojection_parameters.sample_step = diagonal / self.activity_backprojection_parameters.N_samples\n\n    def _adapt_line_step_size_attenuation(self):  # FIXME: move this calculation in the raytracer\n        if not hasattr(self, 'attenuation_size'):\n            attenuation_size = float32([0, 0, 0])\n        elif self.attenuation_size is None:\n            attenuation_size = float32([0, 0, 0])\n        else:\n            attenuation_size = float32(self.attenuation_size)\n        diagonal = sqrt((attenuation_size ** 2).sum())\n        self.attenuation_projection_parameters.sample_step = diagonal / self.attenuation_projection_parameters.N_samples\n        self.attenuation_backprojection_parameters.sample_step = diagonal / self.attenuation_backprojection_parameters.N_samples\n\n    def _construct_ilang_model(self):\n        # define the ilang probabilistic model\n        self.ilang_model = PET_Static_Poisson(self)\n        # construct a basic Directed Acyclical Graph\n        self.ilang_graph = ProbabilisticGraphicalModel(['lambda', 'alpha', 'counts'])\n        self.ilang_graph.set_nodes_given(['counts', 'alpha'], True)\n        self.ilang_graph.add_dependence(self.ilang_model, {'lambda': 'lambda', 'alpha': 'alpha', 'counts': 'counts'})\n        # construct a basic sampler object\n        # self.sampler     = Sampler(self.ilang_graph)\n\n    def set_binning(self, binning):\n        if isinstance(binning, Binning):\n            self.binning = binning\n        else:\n            self.binning = Binning(binning)\n        self._subsets_generator = SubsetGenerator(self.binning.N_azimuthal, self.binning.N_axial)\n        return self.binning\n\n    def set_scanner(self, scanner):\n        if type(scanner) is type(\"\"):\n            scanner = get_scanner_by_name(scanner)\n        self.scanner = scanner()\n\n        self.activity_projection_parameters = ProjectionParameters()\n        self.activity_backprojection_parameters = BackprojectionParameters()\n        self.activity_projection_parameters.N_samples = self.scanner.activity_N_samples_projection_DEFAULT\n        self.activity_projection_parameters.sample_step = self.scanner.activity_sample_step_projection_DEFAULT\n        self.activity_backprojection_parameters.N_samples = self.scanner.activity_N_samples_backprojection_DEFAULT\n        self.activity_backprojection_parameters.sample_step = self.scanner.activity_sample_step_backprojection_DEFAULT\n\n        self.set_activity_shape(self.scanner.activity_shape_DEFAULT)\n        self.set_activity_size(self.scanner.activity_size_DEFAULT)\n\n        self.activity_projection_parameters.gpu_acceleration = self._use_gpu\n        self.activity_backprojection_parameters.gpu_acceleration = self._use_gpu\n\n        self.attenuation_projection_parameters = ProjectionParameters()\n        self.attenuation_backprojection_parameters = BackprojectionParameters()\n        self.attenuation_projection_parameters.N_samples = self.scanner.attenuation_N_samples_projection_DEFAULT\n        self.attenuation_projection_parameters.sample_step = self.scanner.attenuation_sample_step_projection_DEFAULT\n        self.attenuation_backprojection_parameters.N_samples = self.scanner.attenuation_N_samples_backprojection_DEFAULT\n        self.attenuation_backprojection_parameters.sample_step = self.scanner.attenuation_sample_step_backprojection_DEFAULT\n\n        self.set_attenuation_shape(self.scanner.attenuation_shape_DEFAULT)\n        self.set_attenuation_size(self.scanner.attenuation_size_DEFAULT)\n\n        self.attenuation_projection_parameters.gpu_acceleration = self._use_gpu\n        self.attenuation_backprojection_parameters.gpu_acceleration = self._use_gpu\n\n        binning = Binning()\n        binning.size_u = self.scanner.size_u\n        binning.size_v = self.scanner.size_v\n        binning.N_u = self.scanner.N_u\n        binning.N_v = self.scanner.N_v\n        binning.N_axial = self.scanner.N_axial\n        binning.N_azimuthal = self.scanner.N_azimuthal\n        binning.angles_axial = self.scanner.angles_axial\n        binning.angles_azimuthal = self.scanner.angles_azimuthal\n        self.binning = binning\n\n        self.set_scale_activity(self.scanner.scale_activity)\n\n        self._subsets_generator = SubsetGenerator(self.binning.N_azimuthal, self.binning.N_axial)\n\n    def use_gpu(self, use_it):\n        self._use_gpu = use_it\n\n    def use_compression(self, use_it):\n        self._use_compression = use_it\n        if not use_it:\n            if self.prompts is not None:\n                if self.prompts.is_compressed():\n                    self.set_prompts(self.prompts.uncompress_self())\n            if self.randoms is not None:\n                if self.randoms.is_compressed():\n                    self.set_randoms(self.randoms.uncompress_self())\n            if self.sensitivity is not None:\n                if self.sensitivity.is_compressed():\n                    self.set_sensitivity(self.sensitivity.uncompress_self())\n            if self.scatter is not None:\n                if self.scatter.is_compressed():\n                    self.set_scatter(self.scatter.uncompress_self())\n        else:\n            if hasattr(self, \"_use_compression\"):\n                if self._use_compression is False and use_it is True:\n                    # FIXME\n                    # print \"Not able to compress once uncompressed. Please implement PET_Projection.uncompress_self() to \"\n                    # print \"enable this functionality. \"\n                    return\n            if self.prompts is not None:\n                if not self.prompts.is_compressed():\n                    self.set_prompts(self.prompts.compress_self())\n            if self.randoms is not None:\n                if not self.randoms.is_compressed():\n                    self.set_randoms(self.randoms.compress_self())\n            if self.sensitivity is not None:\n                if not self.sensitivity.is_compressed():\n                    self.set_sensitivity(self.sensitivity.compress_self())\n            if self.scatter is not None:\n                if not self.scatter.is_compressed():\n                    self.set_scatter(self.scatter.compress_self())\n\n    ########### SET FUNCTIONS\n    def set_prompts(self, prompts):\n        if isinstance(prompts, PET_Projection):\n            self.prompts = prompts\n            self.prompts.data = float32(self.prompts.data)\n            self.sparsity = self.prompts.sparsity  # update self.sparsity (self.sparsity exists to store sparsity\n        # information in case there is no prompts data)\n        # self.set_binning(prompts.get_binning()) #FIXME: check if it is compatible with the scanner\n        elif self.prompts is not None:\n            prompts = PET_Projection(self.prompts.get_binning(), prompts, self.prompts.sparsity.offsets,\n                                     self.prompts.sparsity.locations, self.prompts.get_time_bins())\n            self.prompts = prompts\n            self.prompts.data = float32(self.prompts.data)\n        else:\n            print(\"Prompts data should be an instance of PET_Projection or an array whose dimension\")\n            print(\"matches the sparsity pattern of the current projection data. \")\n            # FIXME: raise input error and to a try-except when creating the instance of PET_Projection\n\n    def set_scatter(self, scatter, duration_ms=None):\n        self.scatter = scatter\n        self.scatter.data = float32(self.scatter.data)\n        if duration_ms is not None:\n            self.scatter.time_bins = int32([0, duration_ms])\n\n    def simulate_scatter(self, activity=None, attenuation=None):\n        can_simulate = True\n        if not hasattr(self.scanner, \"scatter_simulator\"):\n            can_simulate = False\n        elif self.scanner.scatter_simulator is None:\n            can_simulate = False\n        if not can_simulate:\n            print(\"The selected scanner interface does not expose a scatter simultor. \")\n            return None\n        if activity is None:\n            activity = self.activity\n        if attenuation is None:\n            attenuation = self.attenuation\n        scatter_projection = self.scanner.scatter_simulator.simulate(activity, attenuation)\n        return scatter_projection\n\n    def tail_fit_scatter(self, scatter_projection):\n        print(\"Not implemented. Please implement tail fitting. \")\n        return None\n\n    def set_randoms(self, randoms):\n        if isinstance(randoms, PET_Projection):\n            self.randoms = randoms\n            self.randoms.data = float32(self.randoms.data)\n            self.sparsity_delay = self.randoms.sparsity  # update self.sparsity (self.sparsity exists to store\n            # sparsity information in case there is not randoms data)\n            # self.set_binning(randoms.get_binning())   #FIXME: make sure binning is consistent with randoms\n        elif self.randoms is not None:\n            randoms = PET_Projection(self.randoms.get_binning(), randoms, self.randoms.sparsity.offsets,\n                                     self.randoms.sparsity.locations, self.randoms.get_time_bins())\n            self.randoms = randoms\n            self.randoms.data = float32(self.randoms.data)\n        else:\n            print(\"Delay randoms data should be an instance of PET_Projection or an array whose dimension\")\n            print(\"matches the sparsity pattern of the current projection data. \")\n            # FIXME: raise input error and to a try-except when creating the instance of PET_Projection\n\n    def set_sensitivity(self, sensitivity):\n        # FIXME: verify type: PET_projection or nd_array (the latter only in full sampling mode)\n        self.sensitivity = sensitivity\n        self.sensitivity.data = float32(self.sensitivity.data)\n\n    def set_attenuation(self, attenuation):\n        # self.ilang_graph.set_node_value('alpha',attenuation)\n        # FIXME: how about the transformation ?\n        # FIXME: setting activity and attenuation as members here is not in the spirit of iLang - memoization\n        self.attenuation = attenuation\n        self.attenuation.data = float32(self.attenuation.data)\n\n    def set_attenuation_projection(self, attenuation_projection):\n        self.attenuation_projection = attenuation_projection\n        self.attenuation_projection.data = float32(self.attenuation_projection.data)\n\n    def _load_static_measurement(self, time_bin=None):\n        if time_bin is None:\n            Rp = self.scanner.listmode.get_measurement_static_prompt()\n            Rd = self.scanner.listmode.get_measurement_static_delay()\n        else:\n            Rp = self.scanner.listmode.get_measurement_prompt(time_bin)\n            Rd = self.scanner.listmode.get_measurement_delay(time_bin)\n        time_start = Rp['time_start']\n        time_end = Rp['time_end']\n\n        time_bins = int32(linspace(time_start, time_end, 2))\n        prompts = PET_Projection(self.binning, Rp['counts'], Rp['offsets'], Rp['locations'], time_bins)\n        randoms = PET_Projection(self.binning, Rd['counts'], Rd['offsets'], Rd['locations'], time_bins)\n        if self._use_compression:\n            self.set_prompts(prompts)\n            self.set_randoms(randoms)\n        else:\n            # print \"Uncompressing\"\n            self.set_prompts(prompts.uncompress_self())\n            self.set_randoms(randoms.uncompress_self())\n        self._construct_ilang_model()\n\n    #    def set_activity(self,activity):\n    #        self.ilang_graph.set_node_value('lambda',activity)\n    #        print \"PET_Static_Scan.set_activity(): This is for integration with iLang - please implement\"\n    # FIXME: how about the transformation ?\n\n    ########### IMPORT FUNCTIONS\n    # FIXME: when importing, compress if compression is enabled\n    def import_prompts(self, filename, datafile=''):\n        filetype = guess_file_type_by_name(filename)\n        if filetype is \"interfile_projection_header\":\n            projection = import_interfile_projection(\n                filename, self.binning, self.scanner.michelogram, datafile, load_time=True)\n        elif filetype is \"h5\":\n            projection = import_PET_Projection(filename)\n        else:\n            print(\"PET.import_prompts: file type unknown. \")\n            return\n        projection.data = float32(projection.data)\n        if self._use_compression is False:\n            projection = projection.uncompress_self()\n        else:\n            projection = projection.compress_self()\n        self.set_prompts(projection)\n\n    def import_scatter(self, filename, datafile='', duration_ms=None):\n        filetype = guess_file_type_by_name(filename)\n        if filetype is \"interfile_projection_header\":\n            projection = import_interfile_projection(filename, self.binning, self.scanner.michelogram, datafile)\n        elif filetype is \"h5\":\n            projection = import_PET_Projection(filename)\n        else:\n            print(\"PET.import_scatter: file type unknown. \")\n            return\n        projection.data = float32(projection.data)\n        if self._use_compression is False:\n            projection = projection.uncompress_self()\n        self.set_scatter(projection, duration_ms)\n\n    def import_randoms(self, filename, datafile='', duration_ms=None):\n        filetype = guess_file_type_by_name(filename)\n        if filetype is \"interfile_projection_header\":\n            projection = import_interfile_projection(filename, self.binning, self.scanner.michelogram, datafile)\n        elif filetype is \"h5\":\n            projection = import_PET_Projection(filename)\n        else:\n            print(\"PET.import_randoms: file type unknown. \")\n            return\n        projection.data = float32(projection.data)\n        if duration_ms is not None:\n            projection.data = float32(projection.data * self.prompts.get_duration() / (1.0 * duration_ms))\n        if self._use_compression is False:\n            projection = projection.uncompress_self()\n        self.set_randoms(projection)\n\n    def import_sensitivity(self, filename, datafile='', vmin=0.00, vmax=1e10):\n        filetype = guess_file_type_by_name(filename)\n        if filetype is \"h5\":\n            sensitivity = import_PET_Projection(filename)\n        elif filetype is \"interfile_projection_header\":\n            sensitivity = import_interfile_projection(\n                filename, self.binning, self.scanner.michelogram, datafile, True, vmin, vmax)\n            # if self.prompts is not None:  # FIXME: sensitivity loaded from interfile with some manufacturers has non-zero value\n            # where there are no detectors - set to zero where data is zero\n            # (good approx only for long acquisitions). See if there is a better\n            # way to handle this.\n            #    sensitivity.data[self.prompts.data==0]=0\n            # else:\n            #  print \"Warning: If loading real scanner data, please load prompts before loading the sensitivity. Ignore this message if this is a simulation. See the source code for more info. \" # FIXME: see comment two lines up\n        elif filetype is \"mat\":\n            print(\"Sensitivity from Matlab not yet implemented. All is ready, please spend 15 minutes and implement. \")\n            return\n        else:\n            print(\"File type unknown. \")\n            return\n        sensitivity.data = float32(sensitivity.data)\n        if self._use_compression is False:\n            sensitivity = sensitivity.uncompress_self()\n        self.set_sensitivity(sensitivity)\n\n    def import_attenuation(self, filename, datafile='', filename_hardware='', datafile_hardware=''):\n\n        filetype = guess_file_type_by_name(filename)\n        if filetype is \"interfile_volume_header\":\n            volume = import_interfile_volume(filename, datafile)\n        elif filetype is \"nifti\":\n            print(\"Nifti attenuation file not supported. Everything is ready to implement this, please implement it. \")\n            # FIXME: if nifti files are used, sum the hardware image using resampling in the common space\n        elif filetype is \"h5\":\n            print(\"H5 attenuation file not supported. Everything is ready to implement this, please implement it. \")\n            # FIXME: if h5 files are used, sum the hardware image using resampling in the common space\n        elif filetype is \"mat\":\n            print(\"Matlab attenuation file not supported. Everything is ready to implement this, please implement it. \")\n        else:\n            print(\"PET.import_attenuation: file type of %s unknown. Unable to load attenuation tomogram. \" % filename)\n            return\n\n        if filename_hardware is not '':\n            filetype = guess_file_type_by_name(filename_hardware)\n            if filetype is \"interfile_volume_header\":\n                volume_hardware = import_interfile_volume(filename_hardware, datafile_hardware)\n            else:\n                print(\"File type of %s unknown. Unable to load hardware attenuation tomogram. \" % filename_hardware)\n                return\n\n        volume.data = volume.data + volume_hardware.data\n        volume.data = float32(volume.data)\n        self.set_attenuation(volume)\n\n    def import_attenuation_projection(self, filename, datafile=''):\n        filetype = guess_file_type_by_name(filename)\n        if filetype is \"interfile_projection_header\":\n            projection = import_interfile_projection(\n                filename, self.binning, self.scanner.michelogram, datafile, load_time=True)\n        elif filetype is \"h5\":\n            projection = import_PET_Projection(filename)\n        else:\n            print(\"PET.import_attenuation_projection: file type unknown. \")\n            return\n        projection.data = float32(projection.data)\n        if self._use_compression is False:\n            projection = projection.uncompress_self()\n        self.set_attenuation_projection(projection)\n\n    def import_listmode(self, filename, datafile=None, time_range_ms=(0, None), display_progress=True,\n                        print_debug=False):\n        \"\"\"Load measurement data from a listmode file. \"\"\"\n        if print_debug: print(\"- Loading static PET data from listmode file \" + str(filename))\n        hdr = Interfile.load(filename)\n\n        # 2) Guess the path of the listmode data file, if not specified or mis-specified;\n        #  1 - see if the specified listmode data file exists\n        if datafile is not None:\n            datafile = datafile.replace(\"/\", os.path.sep).replace(\"\\\\\",\n                                                                  os.path.sep)  # cross platform compatibility\n            if not os.path.exists(datafile):\n                raise FileNotFound(\"listmode data\", datafile)\n        # 2 - if the listmode data file is not specified, try with the name (and\n        # full path) contained in the listmode header\n        datafile = hdr['name of data file']['value']\n        # cross platform compatibility\n        datafile = datafile.replace(\"/\", os.path.sep).replace(\"\\\\\", os.path.sep)\n        if not os.path.exists(datafile):\n            #  3 - if it doesn't exist, look in the same path as the header file for the listmode\n            #      data file with name specified in the listmode header file\n            datafile = os.path.split(filename)[0] + os.path.sep + os.path.split(datafile)[-1]\n            if not os.path.exists(datafile):\n                #  4 - if it doesn't exist, look in the same path as the header file for the listmode data\n                #      file with same name as the listmode header file, replacing the extension: \".l.hdr -> .l\"\n                if filename.endswith(\".l.hdr\"):\n                    datafile = filename.replace(\".l.hdr\", \".l\")\n                    if not os.path.exists(datafile):\n                        raise FileNotFound(\"listmode data\", datafile)\n                # 5 - if it doesn't exist, look in the same path as the header file for the listmode data\n                #      file with same name as the listmode header file, replacing the extension: \".hdr -> .l\"\n                elif filename.endswith(\".hdr\"):\n                    datafile = filename.replace(\".hdr\", \".l\")\n                    if not os.path.exists(datafile):\n                        raise FileNotFound(\"listmode data\", datafile)\n\n        # 3) Determine duration of the acquisition\n        n_packets = hdr['total listmode word counts']['value']\n        scan_duration = hdr['image duration']['value'] * 1000  # milliseconds\n\n        # 4) determine scanner parameters\n        n_radial_bins = hdr['number of projections']['value']\n        n_angles = hdr['number of views']['value']\n        n_rings = hdr['number of rings']['value']\n        max_ring_diff = hdr['maximum ring difference']['value']\n        n_sinograms = n_rings + 2 * n_rings * max_ring_diff - max_ring_diff ** 2 - max_ring_diff\n\n        # Determine the time binning\n        time_range_0 = time_range_ms[0]\n        if time_range_ms[1] is not None:\n            if time_range_ms[1] > scan_duration:\n                time_range_1 = scan_duration\n            else:\n                time_range_1 = time_range_ms[1]\n        else:\n            time_range_1 = scan_duration\n        time_bins = int32(linspace(time_range_0, time_range_1, 2))\n\n        # Display information\n\n        \"\"\"print_debug(\" - Number of packets:    %d       \" % n_packets)\n        print_debug(\" - Scan duration:        %d [sec] \" % (scan_duration/1000.0))\n        print_debug(\" - Listmode data file:   %s       \" % datafile)\n        print_debug(\" - Listmode header file: %s       \" % filename)\n        print_debug(\" - Number of time bins:  %d       \" % (len(time_bins)-1))\n        print_debug(\" - Time start:           %f [sec] \" % (time_range_0/1000.0))\n        print_debug(\" - Time end:             %f [sec] \" % (time_range_1/1000.0))\n        print_debug(\" - time_bins:            %s       \" % str(time_bins))\n        print_debug(\" - n_radial_bins:        %d       \" % n_radial_bins)\n        print_debug(\" - n_angles:             %d       \" % n_angles)\n        print_debug(\" - n_angles:             %d       \" % n_sinograms)\"\"\"\n\n        if print_debug:\n            print(\" - Number of packets:    %d       \" % n_packets)\n            print(\" - Scan duration:        %d [sec] \" % (scan_duration / 1000.0))\n            print(\" - Listmode data file:   %s       \" % datafile)\n            print(\" - Listmode header file: %s       \" % filename)\n            print(\" - Number of time bins:  %d       \" % (len(time_bins) - 1))\n            print(\" - Time start:           %f [sec] \" % (time_range_0 / 1000.0))\n            print(\" - Time end:             %f [sec] \" % (time_range_1 / 1000.0))\n            print(\" - time_bins:            %s       \" % str(time_bins))\n            print(\" - n_radial_bins:        %d       \" % n_radial_bins)\n            print(\" - n_angles:             %d       \" % n_angles)\n            print(\" - n_angles:             %d       \" % n_sinograms)\n\n        if display_progress:\n            progress_bar = ProgressBar(title=\"Reading listmode source file.\\nPlease wait ...\")\n            progress_callback = progress_bar.set_percentage\n        else:\n            def progress_callback(value):\n                if value == 1.0:\n                    print(value, \"/\", 100)\n                if (int32(value) / 10) * 10 == value:\n                    print(value, \"/\", 100)\n\n        # Load the listmode data\n        M = self.scanner.michelogram\n        R = self.scanner.listmode.load_listmode(datafile, n_packets, time_bins, self.binning, n_radial_bins, n_angles,\n                                                n_sinograms, M.span, M.segments_sizes, M.michelogram_sinogram,\n                                                M.michelogram_plane, progress_callback)\n        print(\"Done!\")\n\n        # Load static measurement data\n        self._load_static_measurement()\n\n        # Free structures listmode data\n        self.scanner.listmode.free_memory()\n\n        # Construct ilang model\n        self._construct_ilang_model()\n\n\n    ########### GET FUNCTIONS\n    def get_prompts(self):\n        return self.prompts\n\n    def get_scatter(self):\n        return self.scatter\n\n    def get_randoms(self):\n        return self.randoms\n\n    def get_sensitivity(self):\n        return self.sensitivity\n\n    def get_attenuation(self):\n        return self.attenuation\n\n    def get_attenuation_projection(self):\n        return self.attenuation_projection\n\n    #    def get_activity(self):\n    #        return self.activity\n\n    ########### EXPORT FUNCTIONS\n    def export_prompts(self, filename):\n        self.get_prompts().save_to_file(filename)\n\n    def export_scatter(self, filename):\n        self.get_randoms().save_to_file(filename)\n\n    def export_randoms(self, filename):\n        self.get_randoms().save_to_file(filename)\n\n    def export_sensitivity(self, filename):\n        if self.sensitivity is None:\n            print(\"Sensitivity has not been loaded\")\n        else:\n            self.get_sensitivity().save_to_file(filename)\n\n    def export_attenuation_projection(self, filename):\n        self.get_attenuation_projection().save_to_file(filename)\n\n    ########### CHECK IMPORTED FILES (QUICK INSPECT)\n    def quick_inspect(self, figshape=None, index_axial=0, index_azimuthal=5, index_bin=60):\n        \"\"\"Plot a slice of the prompts, randoms and scatter, approapriately scaled to\n        verify if the relative scales are correct. \"\"\"\n        if self.randoms is not None and not isscalar(self.randoms):\n            randoms = self.randoms.to_nd_array()[index_axial, index_azimuthal, :, index_bin]\n        else:\n            randoms = 0.0\n        if self.prompts is not None and not isscalar(self.prompts):\n            prompts = self.prompts.to_nd_array()[index_axial, index_azimuthal, :, index_bin]\n        else:\n            prompts = 0.0\n        if self.sensitivity is not None:\n            if not isscalar(self.sensitivity):\n                sensitivity = self.sensitivity.to_nd_array()[index_axial, index_azimuthal, :, index_bin]\n            else:\n                sensitivity = self.sensitivity\n        else:\n            sensitivity = 1.0\n        if self.scatter is not None and not isscalar(self.scatter):\n            scatter = self.scatter.to_nd_array()[index_axial, index_azimuthal, :, index_bin]\n            if self.scatter.get_duration() is not None:\n                if self.scatter.get_duration() > 1e-6:\n                    if self.prompts.get_duration() is not None:\n                        if self.prompts.get_duration() > 1e-6:\n                            scatter = scatter * self.prompts.get_duration() / self.scatter.get_duration()\n        else:\n            scatter = 0.0\n\n        if has_pylab:\n            if figshape is not None:\n                if figshape == \"default\":\n                    figshape = (6, 2.5)\n                pylab.figure(figsize=figshape)\n                pylab.plot(prompts - randoms, label='prompts-randoms')\n                #pylab.hold(1)\n                pylab.plot(sensitivity * scatter, 'g', label='sensitivity*scatter')\n                pylab.legend(fontsize=10)\n                pylab.xlim((0, self.binning.N_u))\n                #pylab.show()\n            else:\n                figshape = (6, 2.5)\n                pylab.figure(figsize=figshape)\n                pylab.plot(prompts - randoms, label='prompts-randoms')\n                #pylab.hold(1)\n                pylab.plot(sensitivity * scatter, 'g', label='sensitivity*scatter')\n                pylab.legend(fontsize=10)\n                pylab.xlim((0, self.binning.N_u))\n                #pylab.show()\n        else:\n            print(\"quick_inspect uses Pylab to display imaging data. Please install Pylab. \")\n\n    ########### PROJECTIONS/BACKPROJECTION ROUTINES\n\n    def project_attenuation(self, attenuation=None, unit='inv_cm', transformation=None, sparsity=None,\n                            subsets_matrix=None, exponentiate=True):\n        self.profiler.tic()\n        if attenuation is None:\n            attenuation = self.attenuation\n        if isinstance(attenuation, ndarray):\n            attenuation_data = f_continuous(float32(attenuation))\n        else:\n            attenuation_data = f_continuous(float32(attenuation.data))\n        self.profiler.rec_project_make_continuous()\n\n        if not list(attenuation_data.shape) == list(self.attenuation_shape):\n            raise UnexpectedParameter(\"Attenuation must have the same shape as self.attenuation_shape\")\n\n        # By default, the center of the imaging volume is at the center of the scanner\n        tx = 0.5 * (self.attenuation_size[0] - self.attenuation_size[0] / self.attenuation_shape[0])\n        ty = 0.5 * (self.attenuation_size[1] - self.attenuation_size[1] / self.attenuation_shape[1])\n        tz = 0.5 * (self.attenuation_size[2] - self.attenuation_size[2] / self.attenuation_shape[2])\n        if transformation is None:\n            transformation = RigidTransform((tx, ty, tz, 0, 0, 0))\n        else:\n            transformation = copy.copy(transformation)\n            transformation.x = transformation.x + tx\n            transformation.y = transformation.y + ty\n            transformation.z = transformation.z + tz\n\n        # Scale according to the unit measure of the specified attenuation. It is assumed that the attenuation map\n        # is constant in a voxel, with the value specified in 'attenuation', of unit measure 'unit'.\n        if unit == 'inv_mm':\n            invert = False\n            scale = 1.0\n        elif unit == 'inv_cm':\n            invert = False\n            scale = 10.0\n        elif unit == 'mm':\n            invert = True\n            scale = 1.0\n        elif unit == 'cm':\n            invert = True\n            scale = 10.0\n        else:\n            print(\"Unit measure unknown. Assuming inv_cm. Keep track of the unit measures! \")\n            invert = False\n            scale = 10.0\n\n        if invert:\n            attenuation_data = 1.0 / (attenuation_data + EPS)\n        step_size_mm = self.attenuation_projection_parameters.sample_step\n        step_size = step_size_mm / scale\n\n        # Optionally project with a sparsity pattern not equal to sparsity associated to the loaded prompts data\n        # Note: if prompts have not been loaded, self._get_sparsity() assumes no compression.\n\n        if sparsity is None:\n            sparsity = self._get_sparsity()\n\n        # Optionally project only to a subset of projection planes\n        if subsets_matrix is None:\n            sparsity_subset = sparsity\n            self.profiler.tic()\n            angles = self.binning.get_angles()\n            self.profiler.rec_project_get_angles()\n        else:\n            self.profiler.tic()\n            sparsity_subset = sparsity.get_subset(subsets_matrix)\n            self.profiler.rec_project_get_subset_sparsity()\n            self.profiler.tic()\n            angles = self.binning.get_angles(subsets_matrix)\n            self.profiler.rec_project_get_angles()\n\n        offsets = sparsity_subset.offsets\n        locations = sparsity_subset.locations\n        activations = ones([angles.shape[1], angles.shape[2]], dtype=\"uint32\")\n\n        # Call the raytracer\n        self.profiler.tic()\n        projection_data, timing = PET_project_compressed(attenuation_data, None, offsets, locations, activations,\n                                                         angles.shape[2], angles.shape[1], angles,\n                                                         self.binning.N_u, self.binning.N_v, self.binning.size_u,\n                                                         self.binning.size_v,\n                                                         self.attenuation_size[0], self.attenuation_size[1],\n                                                         self.attenuation_size[2],\n                                                         0.0, 0.0, 0.0,\n                                                         transformation.x, transformation.y, transformation.z,\n                                                         transformation.theta_x, transformation.theta_y,\n                                                         transformation.theta_z,\n                                                         0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n                                                         self.attenuation_projection_parameters.gpu_acceleration,\n                                                         self.attenuation_projection_parameters.N_samples,\n                                                         self.attenuation_projection_parameters.sample_step,\n                                                         self.attenuation_projection_parameters.background_attenuation,\n                                                         0.0,\n                                                         self.attenuation_projection_parameters.truncate_negative_values,\n                                                         self.attenuation_projection_parameters.direction,\n                                                         self.attenuation_projection_parameters.block_size)\n\n        self.profiler.rec_project_projection()\n        self.profiler.rec_projection(timing)\n\n        # Fix scale and exponentiate\n        if exponentiate:\n            self.profiler.tic()\n            projection_data = exp(-projection_data * step_size)\n            self.profiler.rec_project_exponentiate()\n        else:\n            self.profiler.tic()\n            projection_data = projection_data * step_size\n            self.profiler.rec_project_scale()\n\n        # Create object PET_Projection: it contains the raw projection data and the description of the projection geometry\n        # and sparsity pattern.\n        time_bins = int32([0, 0])  # Projection of the attenuation does not have timing information\n        self.profiler.tic()\n        projection = PET_Projection(self.binning, projection_data, sparsity.offsets, sparsity.locations,\n                                    time_bins, subsets_matrix)\n        self.profiler.rec_project_wrap()\n        self.set_attenuation_projection(projection)\n        return projection\n\n    def backproject_attenuation(self, projection, unit=\"inv_cm\", transformation=None, sparsity=None,\n                                subsets_matrix=None):\n        if isinstance(projection, ndarray):\n            projection_data = float32(projection)\n        else:\n            projection_data = float32(projection.data)\n\n        # By default, the center of the imaging volume is at the center of the scanner\n        tx = 0.5 * (self.attenuation_size[0] - self.attenuation_size[0] / self.attenuation_shape[0])\n        ty = 0.5 * (self.attenuation_size[1] - self.attenuation_size[1] / self.attenuation_shape[1])\n        tz = 0.5 * (self.attenuation_size[2] - self.attenuation_size[2] / self.attenuation_shape[2])\n        if transformation is None:\n            transformation = RigidTransform((tx, ty, tz, 0, 0, 0))\n        else:\n            transformation = copy.copy(transformation)\n            transformation.x = transformation.x + tx\n            transformation.y = transformation.y + ty\n            transformation.z = transformation.z + tz\n\n        # Scale according to the unit measure of the specified attenuation. It is assumed that the attenuation map\n        # is constant in a voxel, with the value specified in 'attenuation', of unit measure 'unit'.\n        if unit == 'inv_mm':\n            invert = False\n            scale = 1.0\n        elif unit == 'inv_cm':\n            invert = False\n            scale = 10.0\n        elif unit == 'mm':\n            invert = True\n            scale = 1.0\n        elif unit == 'cm':\n            invert = True\n            scale = 10.0\n        else:\n            print(\"Unit measure unknown. Assuming inv_cm. Keep track of the unit measures! \")\n            invert = False\n            scale = 10.0\n\n        if invert:\n            projection_data = float32(1.0 / (projection_data + EPS))\n        step_size_mm = self.attenuation_projection_parameters.sample_step\n        step_size = step_size_mm / scale\n\n        if sparsity is None:\n            sparsity = self._get_sparsity()\n\n        if isinstance(projection, ndarray):\n            projection_data = float32(projection)\n            offsets = sparsity.offsets\n            locations = sparsity.locations\n            angles = self.binning.get_angles(subsets_matrix)\n            activations = ones([self.binning.N_azimuthal, self.binning.N_axial], dtype=\"uint32\")\n        else:\n            projection_data = float32(projection.data)\n            offsets = projection.sparsity.offsets\n            locations = projection.sparsity.locations\n            angles = projection.get_angles()\n            activations = ones([projection.sparsity.N_azimuthal, projection.sparsity.N_axial], dtype=\"uint32\")\n\n        # Call ray-tracer\n        backprojection_data, timing = PET_backproject_compressed(projection_data, None, offsets, locations, activations,\n                                                                 angles.shape[2], angles.shape[1], angles,\n                                                                 self.binning.N_u, self.binning.N_v,\n                                                                 self.binning.size_u, self.binning.size_v,\n                                                                 self.attenuation_shape[0], self.attenuation_shape[1],\n                                                                 self.attenuation_shape[2],\n                                                                 self.attenuation_size[0], self.attenuation_size[1],\n                                                                 self.attenuation_size[2],\n                                                                 0.0, 0.0, 0.0,\n                                                                 transformation.x, transformation.y, transformation.z,\n                                                                 transformation.theta_x, transformation.theta_y,\n                                                                 transformation.theta_z,\n                                                                 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n                                                                 self.attenuation_backprojection_parameters.gpu_acceleration,\n                                                                 self.attenuation_backprojection_parameters.N_samples,\n                                                                 self.attenuation_backprojection_parameters.sample_step,\n                                                                 self.attenuation_backprojection_parameters.background_attenuation,\n                                                                 0.0,\n                                                                 self.attenuation_backprojection_parameters.direction,\n                                                                 self.attenuation_backprojection_parameters.block_size)\n\n        self.profiler.rec_backprojection(timing)\n        backprojection_data = backprojection_data * step_size\n\n        # Set the correct scale - unit measure and return Image3D - FIXME: set scale for requested unit measure\n        return self._make_Image3D_attenuation(backprojection_data)\n\n    def project_activity(self, activity, unit=\"Bq/mm3\", transformation=None, sparsity=None, subsets_matrix=None):\n        self.profiler.tic()\n        if isinstance(activity, ndarray):\n            activity_data = f_continuous(float32(activity))\n        else:\n            activity_data = f_continuous(float32(activity.data))\n        self.profiler.rec_project_make_continuous()\n\n        # By default, the center of the imaging volume is at the center of the scanner; no rotation\n        tx = 0.5 * (self.activity_size[0] - self.activity_size[0] / self.activity_shape[0])\n        ty = 0.5 * (self.activity_size[1] - self.activity_size[1] / self.activity_shape[1])\n        tz = 0.5 * (self.activity_size[2] - self.activity_size[2] / self.activity_shape[2])\n        if transformation is None:\n            transformation = RigidTransform((tx, ty, tz, 0, 0, 0))\n        else:\n            transformation = copy.copy(transformation)\n            transformation.x = transformation.x + tx\n            transformation.y = transformation.y + ty\n            transformation.z = transformation.z + tz\n\n        # Optionally project with a sparsity pattern not equal to sparsity associated to the loaded prompts data\n        # Note: if prompts have not been loaded, self._get_sparsity() assumes no compression.\n        if sparsity is None:\n            sparsity = self._get_sparsity()\n\n        # Optionally project only to a subset of projection planes\n        if subsets_matrix is None:\n            self.profiler.tic()\n            sparsity_subset = sparsity\n            angles = self.binning.get_angles()\n            self.profiler.rec_project_get_angles()\n        else:\n            self.profiler.tic()\n            sparsity_subset = sparsity.get_subset(subsets_matrix)\n            self.profiler.rec_project_get_subset_sparsity()\n            self.profiler.tic()\n            angles = self.binning.get_angles(subsets_matrix)\n            self.profiler.rec_project_get_angles()\n\n        scale = 1.0\n        step_size_mm = self.activity_projection_parameters.sample_step\n        step_size = step_size_mm / scale\n\n        offsets = sparsity_subset.offsets\n        locations = sparsity_subset.locations\n        activations = ones([angles.shape[1], angles.shape[2]], dtype=\"uint32\")\n\n        # print locations[:,0:20]\n        # print locations.flags\n        # print sparsity.locations[:,0:20]\n        # print sparsity.locations.flags\n\n        # print \"project activity\"\n        # print \"activity\",activity_data.shape\n        # print \"offsets\",offsets.shape\n        # print \"locations\",locations.shape\n        # print \"activations\",activations.shape\n        # print \"angles.shape\",angles.shape\n\n        # Call the raytracer\n        self.profiler.tic()\n        projection_data, timing = PET_project_compressed(activity_data, None, offsets, locations, activations,\n                                                         angles.shape[2], angles.shape[1], angles,\n                                                         self.binning.N_u, self.binning.N_v, self.binning.size_u,\n                                                         self.binning.size_v,\n                                                         self.activity_size[0], self.activity_size[1],\n                                                         self.activity_size[2],\n                                                         0.0, 0.0, 0.0,\n                                                         transformation.x, transformation.y, transformation.z,\n                                                         transformation.theta_x, transformation.theta_y,\n                                                         transformation.theta_z,\n                                                         0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n                                                         self.activity_projection_parameters.gpu_acceleration,\n                                                         self.activity_projection_parameters.N_samples,\n                                                         self.activity_projection_parameters.sample_step,\n                                                         self.activity_projection_parameters.background_activity,\n                                                         0.0,\n                                                         self.activity_projection_parameters.truncate_negative_values,\n                                                         self.activity_projection_parameters.direction,\n                                                         self.activity_projection_parameters.block_size)\n\n        self.profiler.rec_project_projection()\n        self.profiler.rec_projection(timing)\n        # Create object PET_Projection: it contains the raw projection data and the description of the projection geometry\n        # and sparsity pattern.\n        time_bins = int32([0, 1000.0])  # 1 second - projection returns a rate - by design\n\n        self.profiler.tic()\n        projection_data = projection_data * step_size\n        self.profiler.rec_project_scale()\n\n        self.profiler.tic()\n        projection = PET_Projection(self.binning, projection_data, sparsity.offsets,\n                                    sparsity.locations, time_bins, subsets_matrix)\n        self.profiler.rec_project_wrap()\n        return projection\n\n    def backproject_activity(self, projection, transformation=None, subsets_matrix=None):\n        # By default, the center of the imaging volume is at the center of the scanner\n        tx = 0.5 * (self.activity_size[0] - self.activity_size[0] / self.activity_shape[0])\n        ty = 0.5 * (self.activity_size[1] - self.activity_size[1] / self.activity_shape[1])\n        tz = 0.5 * (self.activity_size[2] - self.activity_size[2] / self.activity_shape[2])\n        if transformation is None:\n            transformation = RigidTransform((tx, ty, tz, 0, 0, 0))\n        else:\n            transformation = copy.copy(transformation)\n            transformation.x = transformation.x + tx\n            transformation.y = transformation.y + ty\n            transformation.z = transformation.z + tz\n\n        if not isinstance(projection, ndarray):\n            if not subsets_matrix is None:\n                self.profiler.tic()\n                projection_subset = projection.get_subset(subsets_matrix)\n                self.profiler.rec_backpro_get_subset()\n                self.profiler.tic()\n                sparsity_subset = projection_subset.sparsity\n                angles = projection_subset.get_angles()\n                self.profiler.rec_backpro_get_angles()\n                projection_data = float32(projection_subset.data)\n            else:\n                self.profiler.tic()\n                projection_subset = projection\n                sparsity_subset = projection.sparsity\n                angles = projection_subset.get_angles()\n                self.profiler.rec_backpro_get_angles()\n                projection_data = float32(projection_subset.data)\n        else:\n            sparsity = self._get_sparsity()\n            if subsets_matrix is not None:\n                self.profiler.tic()\n                indexes = subsets_matrix.flatten() == 1\n                projection_data = float32(projection.swapaxes(0, 1).\n                                          reshape((sparsity.N_axial * sparsity.N_azimuthal,\n                                                   self.binning.N_u, self.binning.N_v))[indexes, :, :])\n                self.profiler.rec_backpro_get_subset_data()\n                self.profiler.tic()\n                sparsity_subset = sparsity.get_subset(subsets_matrix)\n                self.profiler.rec_backpro_get_subset_sparsity()\n                self.profiler.tic()\n                angles = self.binning.get_angles(subsets_matrix)\n                self.profiler.rec_backpro_get_angles()\n            else:\n                self.profiler.tic()\n                sparsity_subset = sparsity\n                angles = self.binning.get_angles()\n                self.profiler.rec_backpro_get_angles()\n                projection_data = float32(projection)\n\n        offsets = sparsity_subset.offsets\n        locations = sparsity_subset.locations\n        activations = ones([sparsity_subset.N_azimuthal, sparsity_subset.N_axial], dtype=\"uint32\")\n\n        scale = 1.0  # FIXME: change this according to the input unit measure - check how this is done in project_attenuation\n        step_size_mm = self.activity_projection_parameters.sample_step\n        step_size = step_size_mm / scale\n\n        # print \"backproject activity\"\n        # print \"projection_data\",projection_data.shape\n        # print \"offsets\",offsets.shape\n        # print \"locations\",locations.shape\n        # print \"activations\",activations.shape\n        # print \"angles\",angles.shape\n        # print angles[:,0,0:5]\n        # print offsets[0:3,0:5]\n        # print locations[:,0:5]\n        # time.sleep(0.2)\n\n        # Call ray-tracer\n        self.profiler.tic()\n        backprojection_data, timing = PET_backproject_compressed(projection_data, None, offsets, locations, activations,\n                                                                 angles.shape[2], angles.shape[1], angles,\n                                                                 self.binning.N_u, self.binning.N_v,\n                                                                 self.binning.size_u, self.binning.size_v,\n                                                                 self.activity_shape[0], self.activity_shape[1],\n                                                                 self.activity_shape[2],\n                                                                 self.activity_size[0], self.activity_size[1],\n                                                                 self.activity_size[2],\n                                                                 0.0, 0.0, 0.0,\n                                                                 transformation.x, transformation.y, transformation.z,\n                                                                 transformation.theta_x, transformation.theta_y,\n                                                                 transformation.theta_z,\n                                                                 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n                                                                 self.activity_backprojection_parameters.gpu_acceleration,\n                                                                 self.activity_backprojection_parameters.N_samples,\n                                                                 self.activity_backprojection_parameters.sample_step,\n                                                                 self.activity_backprojection_parameters.background_activity,\n                                                                 0.0,\n                                                                 self.activity_backprojection_parameters.direction,\n                                                                 self.activity_backprojection_parameters.block_size)\n\n        self.profiler.rec_backpro_backprojection()\n        self.profiler.rec_backprojection(timing)\n\n        self.profiler.tic()\n        backprojection_data = backprojection_data * step_size\n        self.profiler.rec_backpro_scale()\n\n        self.profiler.tic()\n        backprojection = self._make_Image3D_activity(backprojection_data)\n        self.profiler.rec_backpro_wrap()\n        return backprojection\n\n    ########### RECONSTRUCTION ROUTINES\n\n    def get_normalization(self, attenuation_times_sensitivity=None, transformation=None, sparsity=None,\n                          duration_ms=None, subsets_matrix=None, epsilon=None):\n        \"\"\"Compute the terms at denominator of the MLEM/OSEM reconstruction algorithm based on the file loaded/imported before\"\"\"\n        # FIXME: memoization\n        if attenuation_times_sensitivity is None:\n            attenuation_times_sensitivity = self.sensitivity  # FIXME: include attenuation here - memoization mumap proj\n        if isscalar(attenuation_times_sensitivity) or attenuation_times_sensitivity is None:\n            attenuation_times_sensitivity = ones(self.prompts.data.shape)\n        if duration_ms is None:\n            duration_ms = self.prompts.get_duration()\n        duration_sec = duration_ms / 1000.0\n        alpha = self.scale_activity\n        normalization = self.backproject_activity(\n            attenuation_times_sensitivity * duration_sec * alpha, transformation, subsets_matrix)\n        return normalization\n\n    def get_gradient_activity(self, activity, attenuation=None, unit_activity=\"Bq/mm3\", transformation_activity=None,\n                              sparsity=None, duration_ms=None, subset_size=None, subset_mode='random',\n                              subsets_matrix=None,\n                              azimuthal_range=None, separate_additive_terms=False, epsilon=None):\n        # Optionally use only a subset of the projections - use, in order:\n        # subsets_matrix; subset_size, subset_mode and az_range\n        if subsets_matrix is None:\n            if subset_size is not None:\n                if subset_size >= 0:\n                    subsets_matrix = self._subsets_generator.new_subset(subset_mode, subset_size, azimuthal_range)\n\n        # Optionally use the specified value of epsilon (small number added to the denominator is divisions)\n        if epsilon is None:\n            epsilon = EPS\n\n        if attenuation is None:\n            attenuation = 1.0\n\n        if self.prompts is None:\n            print(\"self.prompts is None, please set prompts. \")\n            return\n            # FIXME : throw an error\n\n        # By default use the timing information stored in the prompts, however optionally enable overriding\n        if duration_ms is None:\n            duration_ms = self.prompts.get_duration()\n        duration_sec = duration_ms / 1000.0\n\n        # Precompute attenuation*sensitivity - FIXME: do it only is the subset, same for other calculation in proj space\n        alpha = self.scale_activity\n        prompts = self.prompts\n        randoms = self.randoms\n        scatter = self.scatter\n        sensitivity = self.sensitivity\n        if randoms is None:\n            randoms = 0.0\n        if scatter is None:\n            scatter = 0.0\n        if sensitivity is None or sensitivity is 1.0:\n            att_sens = attenuation\n        else:\n            att_sens = sensitivity * attenuation\n\n        att_sens = att_sens.get_subset(subsets_matrix)\n\n        # Compute the first term of the gradient: backprojection of the sensitivity of the scanner\n        # If it is requested that the gradient is computed using all the projection measurements, use the\n        # memoized normalization. self.get_normalization() takes care of memoization.\n        # gradient_term1 = self.get_normalization(att_sens,\n        # transformation_activity, sparsity, duration_ms, subsets_matrix,\n        # epsilon=epsilon)\n        norm = PET_Projection(self.binning, data=1.0, subsets_matrix=subsets_matrix)\n        gradient_term1 = self.backproject_activity(norm)\n\n        # Compute the second term of the gradient: backprojection of the ratio between the measurement and the projection of\n        # current activity estimate... Ordinary Poisson to include scatter and randoms.\n        projection = self.project_activity(activity, unit=unit_activity, transformation=transformation_activity,\n                                           sparsity=sparsity,\n                                           subsets_matrix=subsets_matrix)\n\n        prompts_subset = prompts.get_subset(subsets_matrix)\n        gradient_term2 = self.backproject_activity(prompts_subset / (\n            projection + randoms / (att_sens * alpha * duration_sec + epsilon) + scatter / (\n                attenuation * alpha * duration_sec + epsilon) + epsilon),\n                                                   transformation=transformation_activity)\n\n        if separate_additive_terms:\n            return (gradient_term1, gradient_term2, subsets_matrix)\n        else:\n            gradient = gradient_term1 + gradient_term2\n            return (gradient, subsets_matrix)\n\n    def get_gradient_attenuation(self, attenuation, activity,\n                                 sparsity=None, duration_ms=None, subset_size=None, subset_mode='random',\n                                 subsets_matrix=None,\n                                 azimuthal_range=None, epsilon=None):\n        # Optionally use only a subset of the projections - use, in order:\n        # subsets_matrix; subset_size, subset_mode and az_range\n        if subsets_matrix is None:\n            if subset_size is not None:\n                if subset_size >= 0:\n                    subsets_matrix = self._subsets_generator.new_subset(subset_mode, subset_size, azimuthal_range)\n\n        # Optionally use the specified value of epsilon (small number added to the denominator is divisions)\n        if epsilon is None:\n            epsilon = EPS\n\n        if attenuation is None:\n            attenuation = 1.0\n\n        if self.prompts is None:\n            print(\"self.prompts is None, please set prompts. \")\n            return\n            # FIXME : throw an error\n\n        # By default use the timing information stored in the prompts, however optionally enable overriding\n        if duration_ms is None:\n            duration_ms = self.prompts.get_duration()\n        duration_sec = duration_ms / 1000.0\n\n        # Precompute attenuation*sensitivity - FIXME: do it only is the subset, same for other calculation in proj space\n        alpha = self.scale_activity\n        prompts = self.prompts\n        randoms = self.randoms\n        scatter = self.scatter\n        sensitivity = self.sensitivity\n        if randoms is None:\n            randoms = 0.0\n        if scatter is None:\n            scatter = 0.0\n        if sensitivity is None:\n            sensitivity = 1.0\n\n        attenuation_projection = self.project_attenuation(\n            attenuation, unit='inv_cm', transformation=None, sparsity=sparsity, subsets_matrix=subsets_matrix,\n            exponentiate=True)\n\n        # FIXME: transformation = None\n        pr_activity = self.project_activity(activity, transformation=None, sparsity=sparsity,\n                                            subsets_matrix=subsets_matrix) * sensitivity * attenuation_projection * duration_sec * alpha\n        gradient = self.backproject_attenuation(pr_activity - prompts / (\n            randoms / (pr_activity + epsilon) + scatter / (pr_activity / (sensitivity + epsilon) + epsilon) + 1),\n                                                unit=\"inv_cm\", transformation=None, sparsity=sparsity,\n                                                subsets_matrix=subsets_matrix)\n        return gradient\n\n    def estimate_activity_and_attenuation(self, activity=None, attenuation=None, iterations=DEFAULT_RECON_ITERATIONS,\n                                          sparsity=None,\n                                          subset_size=DEFAULT_SUBSET_SIZE,\n                                          subset_mode='random', epsilon=None, subsets_matrix=None, azimuthal_range=None,\n                                          show_progressbar=True):\n        # FIXME: save time: don't compute twice the proj of the attenuation\n        activity = self._make_Image3D_activity(ones(self.activity_shape, dtype=float32, order=\"F\"))\n        attenuation = self._make_Image3D_attenuation(zeros(self.attenuation_shape, dtype=float32, order=\"F\"))\n\n        progress_bar = ProgressBar()\n        if show_progressbar:\n            progress_bar.set_percentage(0.1)\n        for iteration in range(iterations):\n            activity = self.estimate_activity(activity, attenuation, 1, sparsity, subset_size,\n                                              subset_mode, epsilon, subsets_matrix, azimuthal_range,\n                                              show_progressbar=False)\n            attenuation = self.estimate_attenuation(\n                activity, attenuation, 1, sparsity, subset_size, subset_mode, epsilon, subsets_matrix, azimuthal_range,\n                show_progressbar=False)\n            if show_progressbar:\n                progress_bar.set_percentage((iteration + 1) * 100.0 / iterations)\n        if show_progressbar:\n            progress_bar.set_percentage(100.0)\n        return (activity, attenuation)\n\n    def estimate_attenuation(self, activity=None, attenuation=None, iterations=DEFAULT_RECON_ITERATIONS, sparsity=None,\n                             subset_size=DEFAULT_SUBSET_SIZE,\n                             subset_mode='random', epsilon=None, subsets_matrix=None,\n                             azimuthal_range=None, show_progressbar=True):\n\n        progress_bar = ProgressBar()\n        if show_progressbar:\n            progress_bar.set_percentage(0.1)\n\n        if attenuation is None:\n            attenuation = self._make_Image3D_attenuation(zeros(self.attenuation_shape, dtype=float32, order=\"F\"))\n        for iteration in range(iterations):\n            attenuation = attenuation + self.get_gradient_attenuation(attenuation, activity,\n                                                                      sparsity, duration_ms=None,\n                                                                      subset_size=subset_size, subset_mode=subset_mode,\n                                                                      subsets_matrix=subsets_matrix,\n                                                                      azimuthal_range=azimuthal_range, epsilon=epsilon)\n            if show_progressbar:\n                progress_bar.set_percentage((iteration + 1) * 100.0 / iterations)\n        if show_progressbar:\n            progress_bar.set_percentage(100.0)\n        return attenuation\n\n    def estimate_activity(self, gradient_prior_func=None, activity__=None, attenuation=None,\n                          iterations=DEFAULT_RECON_ITERATIONS, sparsity=None,\n                          subset_size=DEFAULT_SUBSET_SIZE, subset_mode='random', epsilon=None, subsets_matrix=None,\n                          azimuthal_range=None, show_progressbar=True, gradient_prior_args=()):\n\n        progress_bar = ProgressBar()\n        if show_progressbar:\n            progress_bar.set_percentage(0.1)\n\n        # Optionally use the specified value of epsilon (small number added to the denominator is divisions)\n        if epsilon is None:\n            epsilon = EPS\n\n        if self.prompts is None:\n            print(\"self.prompts is None, please set prompts. \")\n            return\n            # FIXME : throw an error\n\n        duration_ms = self.prompts.get_duration()\n\n        # print \"Projection of the attenuation. \"\n        if attenuation is None:\n            attenuation = self.attenuation\n        if attenuation is not None:\n            self.attenuation_projection = self.project_attenuation(\n                attenuation)  # FIXME: now it's only here that this is defined\n        else:\n            self.attenuation_projection = 1.0\n\n        if activity__ is None:\n            activity__ = self._make_Image3D_activity(ones(self.activity_shape, dtype=float32, order=\"F\"))\n            # FIXME: use transformation - also notice that roi_activity is always set to None here\n\n        for iteration in range(iterations):\n            [gradient1, gradient2, subsets_matrix] = self.get_gradient_activity(activity__, self.attenuation_projection,\n                                                                                sparsity=sparsity,\n                                                                                duration_ms=duration_ms,\n                                                                                subset_size=subset_size,\n                                                                                subset_mode=subset_mode,\n                                                                                subsets_matrix=subsets_matrix,\n                                                                                azimuthal_range=azimuthal_range,\n                                                                                separate_additive_terms=True,\n                                                                                epsilon=epsilon)\n\n            if gradient_prior_func is not None:\n                activity__ = activity__ * gradient2 / \\\n                             (gradient1 + epsilon - gradient_prior_func(activity__, *gradient_prior_args))\n            else:\n                activity__ = activity__ * gradient2 / (gradient1 + epsilon)\n            if show_progressbar:\n                progress_bar.set_percentage((iteration + 1) * 100.0 / iterations)\n        if show_progressbar:\n            progress_bar.set_percentage(100.0)\n        return activity__\n\n    def osem_reconstruction(self, iterations=10, activity=None, attenuation_projection=None, subset_mode=\"random\",\n                            subset_size=64, transformation=None, azimuthal_range=None, show_progressbar=True,\n                            SaveAll=False, KineticPrior=False, SaveDisk=False,\n                            savepath=\"\"):\n\n        if show_progressbar:\n            progress_bar = ProgressBar(title=\"Reconstruction progress ...\")\n            progress_bar.set_percentage(0.0)\n\n        if activity is None:\n            activity = self._make_Image3D_activity(ones(self.activity_shape, dtype=float32, order=\"F\"))\n\n        if self.sensitivity is None:\n            sensitivity = self.prompts.copy()\n            sensitivity.data = 0.0 * sensitivity.data + 1\n            self.set_sensitivity(sensitivity)\n\n        if SaveAll:\n            activity_all = ones((self.activity_shape[0], self.activity_shape[1], self.activity_shape[2], iterations),\n                                dtype=float32)\n\n        subsets_generator = SubsetGenerator(self.binning.N_azimuthal, self.binning.N_axial)\n\n        self.profiler.reset()\n        for i in range(iterations):\n            if not show_progressbar:\n                if iterations >= 15:\n                    if i == iterations - 1:\n                        print(\"iteration \", (i + 1), \"/\", iterations)\n                    elif i + 1 == 1:\n                        print(\"iteration \", (i + 1), \"/\", iterations)\n                    elif (int32(i + 1) / 5) * 5 == i + 1:\n                        print(\"iteration \", (i + 1), \"/\", iterations)\n                else:\n                    print(\"iteration \", (i + 1), \"/\", iterations)\n\n            subsets_matrix = subsets_generator.new_subset(subset_mode, subset_size, azimuthal_range)\n            # TODO : introduce OSL prior into osem_step\n            activity = self.osem_step(activity, subsets_matrix, attenuation_projection, transformation)\n\n            if SaveAll:\n                temp = activity.data\n                temp = flipud(temp)  # U-D\n                temp = fliplr(temp)  # L-R\n                # temp = flip(temp,2)  #Zreverse\n                activity_all[:, :, :, i] = temp\n                del temp\n            if SaveDisk:\n                activity.save_to_file(savepath + 'activity_recon_%d.nii' % i)\n            if KineticPrior:\n                # TODO\n                # call kinetic model fitter module\n                # update activity before next iteration\n                pass\n            if show_progressbar:\n                progress_bar.set_percentage((i + 1) * 100.0 / iterations)\n\n        if SaveAll:\n            return activity, activity_all\n        else:\n            return activity\n\n    def mlem_reconstruction(self, iterations=10, activity=None, attenuation_projection=None, transformation=None):\n        if activity is None:\n            activity = self._make_Image3D_activity(ones(self.activity_shape, dtype=float32, order=\"F\"))\n        if self.sensitivity is None:\n            sensitivity = self.prompts.copy()\n            sensitivity.data = 0.0 * sensitivity.data + 1\n            self.set_sensitivity(sensitivity)\n\n        self.profiler.reset()\n        for i in range(iterations):\n            print(i)\n            subsets_matrix = None\n            activity = self.osem_step(activity, subsets_matrix, attenuation_projection, transformation)\n        return activity\n\n    ################ Gradient prior terms for OSL version of osem_step #####################\n    def kinetic_model_prior(self, activity_, model, sigma, sf):\n        gradient = (\n                       model - sf * activity_.data) / sigma ** 2  # derivative of a gaussian prior that enforces similarity between recon and fitting\n        return gradient\n\n    def smoothness_prior(self, activity_, importance):\n        # kernel = ones((3,3,1))\n        # kernel[1,1] = -8.0\n        kernel = asarray([[[0, 0, 0], [0, 1, 0], [0, 0, 0]], [[0, 1, 0], [1, -6, 1], [0, 1, 0]],\n                          [[0, 0, 0], [0, 1, 0], [0, 0, 0]]])  # 3D laplacian operator\n        gradient = ndimage.convolve(activity_.data, kernel, mode='constant', cval=0.0)\n        return importance * gradient\n\n    def kinetic_plus_smoothing_prior(self, activity_, sources, sigma, sf, importance):\n        return self.kinetic_model_prior(activity_, sources, sigma, sf) + self.smoothness_prior(activity_, importance)\n\n    #######################################################################################\n\n    def osem_step(self, activity, subsets_matrix=None, attenuation_projection=None, transformation=None,\n                  gradient_prior_type=None, gradient_prior_args=()):\n        epsilon = 1e-08\n\n        self.profiler.rec_iteration()\n        self.profiler.tic()\n        prompts = self.prompts\n        if self._use_compression:\n            prompts = prompts.uncompress_self()\n        self.profiler.rec_uncompress()\n\n        duration_ms = prompts.get_duration()\n        if duration_ms is None:\n            print(\"Acquisition duration unknown (self.prompts.time_bins undefined); assuming 60 minutes. \")\n            duration_ms = 1000 * 60 * 60\n        duration = duration_ms / 1000.0\n        alpha = self.scale_activity\n\n        if attenuation_projection is not None:\n            self.profiler.tic()\n            attenuation_projection = attenuation_projection.get_subset(subsets_matrix)\n            self.profiler.rec_get_subset_attenuation()\n        elif self.attenuation_projection is not None:\n            self.profiler.tic()\n            attenuation_projection = self.attenuation_projection.get_subset(subsets_matrix)\n            self.profiler.rec_get_subset_attenuation()\n        elif self.attenuation is not None:\n            print(\"Projecting attenuation\")\n            # self.profiler.tic()\n            self.attenuation_projection = self.project_attenuation(self.attenuation)\n            # self.profiler.rec_project_attenuation()\n            self.profiler.tic()\n            attenuation_projection = self.attenuation_projection.get_subset(subsets_matrix)\n            self.profiler.rec_get_subset_attenuation()\n            print(\"Done\")\n        else:\n            attenuation_projection = 1.0\n\n        if self.sensitivity is not None:\n            self.profiler.tic()\n            sens_x_att = self.sensitivity.get_subset(subsets_matrix)\n            self.profiler.rec_get_subset_sensitivity()\n            self.profiler.tic()\n            sens_x_att = sens_x_att * attenuation_projection\n            self.profiler.rec_compose_various()\n        else:\n            sens_x_att = attenuation_projection\n        if isscalar(sens_x_att):\n            sens_x_att = sens_x_att * ones(prompts.data.shape, dtype=float32)\n\n        if self.randoms is not None:\n            randoms = self.randoms\n            if self._use_compression:\n                self.profiler.tic()\n                randoms = randoms.uncompress_self()\n                self.profiler.rec_uncompress()\n            self.profiler.tic()\n            randoms = randoms.get_subset(subsets_matrix)\n            self.profiler.rec_get_subset_randoms()\n            self.profiler.tic()\n            randoms = (randoms + epsilon) / (sens_x_att * alpha * duration + epsilon)\n            self.profiler.rec_compose_randoms()\n\n        if self.scatter is not None:\n            self.profiler.tic()\n            mscatter = self.scatter.get_subset(subsets_matrix)\n            self.profiler.rec_get_subset_scatter()\n            self.profiler.tic()\n            mscatter = (mscatter + epsilon) / (attenuation_projection * alpha * duration + epsilon)\n            self.profiler.rec_compose_scatter()\n\n            # Scale scatter: this is used in dynamic and kinetic imaging, when scatter is calculated using \n            # the ativity for a time period longer than the current frame: \n            if self.scatter.get_duration() is not None:\n                if self.scatter.get_duration() > 1e-6:\n                    self.profiler.tic()\n                    mscatter = mscatter * duration / self.scatter.get_duration()\n                    self.profiler.rec_compose_scatter()\n\n        if gradient_prior_type is not None:\n            if gradient_prior_type == \"smooth\":\n                gradient_prior_func = self.smoothness_prior\n            elif gradient_prior_type == \"kinetic\":\n                gradient_prior_func = self.kinetic_model_prior\n            elif gradient_prior_type == \"both\":\n                gradient_prior_func = self.kinetic_plus_smoothing_prior\n        else:\n            gradient_prior_func = None\n\n        # print duration, alpha\n        self.profiler.tic()\n        norm = self.backproject_activity(sens_x_att * alpha * duration, transformation=transformation)\n        if gradient_prior_func is not None:\n            update2 = norm + epsilon - gradient_prior_func(activity, *gradient_prior_args)\n        else:\n            update2 = norm + epsilon\n        self.profiler.rec_backprojection_norm_total()\n\n        self.profiler.tic()\n        projection = self.project_activity(activity, subsets_matrix=subsets_matrix, transformation=transformation)\n        self.profiler.rec_projection_activity_total()\n\n        if self.randoms is not None:\n            if self.scatter is not None:\n                self.profiler.tic()\n                p = prompts.get_subset(subsets_matrix)\n                self.profiler.rec_get_subset_prompts()\n                self.profiler.tic()\n                s = (projection + randoms + mscatter + epsilon)\n                self.profiler.rec_compose_various()\n                self.profiler.tic()\n                update1 = self.backproject_activity(p / s, transformation=transformation)\n                self.profiler.rec_backprojection_activity_total()\n            else:\n                self.profiler.tic()\n                p = prompts.get_subset(subsets_matrix)\n                self.profiler.rec_get_subset_prompts()\n                self.profiler.tic()\n                s = (projection + randoms + epsilon)\n                self.profiler.rec_compose_various()\n                self.profiler.tic()\n                update1 = self.backproject_activity(p / s, transformation=transformation)\n                self.profiler.rec_backprojection_activity_total()\n        else:\n            if self.scatter is not None:\n                self.profiler.tic()\n                p = prompts.get_subset(subsets_matrix)\n                self.profiler.rec_get_subset_prompts()\n                self.profiler.tic()\n                s = (projection + mscatter + epsilon)\n                self.profiler.rec_compose_various()\n                self.profiler.tic()\n                update1 = self.backproject_activity(p / s, transformation=transformation)\n                self.profiler.rec_backprojection_activity_total()\n            else:\n                self.profiler.tic()\n                p = prompts.get_subset(subsets_matrix)\n                self.profiler.rec_get_subset_prompts()\n                self.profiler.tic()\n                s = (projection + epsilon)\n                self.profiler.rec_compose_various()\n                self.profiler.tic()\n                update1 = self.backproject_activity(p / s, transformation=transformation)\n                self.profiler.rec_backprojection_activity_total()\n\n        self.profiler.tic()\n        activity = (activity / update2) * update1\n        self.profiler.rec_update()\n\n        return activity\n\n    ########### VISUALIZATION ROUTINES AND VOLUME MANIPULATION\n\n    def brain_crop(self, bin_range=(100, 240)):\n        if self._use_compression is True:\n            print(\"Projection cropping currently only works with uncompressed data. \")\n            print(\"In order to enable cropping, please complete the implementation of PET_Projection.get_subset()\")\n            print(\"Now PET_Projection.get_subset() only works with uncompressed data. \")\n            return\n        if hasattr(self, \"_cropped\"):\n            return\n        A = bin_range[0]\n        B = bin_range[1]\n        self.binning.size_u = (1.0 * self.binning.size_u) / self.binning.N_u * (B - A)\n        self.binning.N_u = B - A\n        if self.prompts is not None:\n            self.prompts = self.prompts.crop((A, B))\n        if self.randoms is not None:\n            self.randoms = self.randoms.crop((A, B))\n        if self.scatter is not None:\n            self.scatter = self.scatter.crop((A, B))\n        if self.sensitivity is not None:\n            self.sensitivity = self.sensitivity.crop((A, B))\n        self._cropped = True\n\n    def volume_render(self, volume, scale=1.0):\n        # FIXME: use the VolumeRender object in occiput.Visualization (improve it), the following is a quick fix:\n        [offsets, locations] = PET_initialize_compression_structure(180, 1, 256, 256)\n        if isinstance(volume, ndarray):\n            volume = float32(volume)\n        else:\n            volume = float32(volume.data)\n        subsets_generator = SubsetGenerator(1, 180)\n        subsets_matrix = subsets_generator.all_active()\n        mask = uniform_cylinder(volume.shape, volume.shape,\n                                [0.5 * volume.shape[0], 0.5 * volume.shape[1], 0.5 * volume.shape[2]],\n                                0.5 * min(volume.shape[0] - 1, volume.shape[1]), volume.shape[2], 2, 1, 0)\n        volume[where(mask.data == 0)] = 0.0\n        direction = 7\n        block_size = 512\n\n        proj, timing = PET_project_compressed(volume, None, offsets, locations, subsets_matrix,\n                                              180, 1, pi / 180,\n                                              256, 256,\n                                              256.0, 256.0,\n                                              256.0, 256.0, 256.0,\n                                              256.0, 256.0, 256.0,\n                                              128.0, 128.0, 128.0,\n                                              0.0, 0.0, 0.0,\n                                              0.0, 0.0, 0.0,\n                                              0.0, 0.0, 0.0,\n                                              1, 256, 1.5,\n                                              0.0, 0.0, 0,\n                                              direction, block_size)\n        proj[where(proj > proj.max() / scale)] = proj.max() / scale\n        binning = Binning()\n        binning.N_axial = 180\n        binning.N_azimuthal = 1\n        binning.angles_axial = float32(linspace(0, pi - pi / 180.0, 180))\n        binning.angles_azimuthal = float32(linspace(0, 0, 1))\n        binning.size_u = 256.0\n        binning.size_v = 256.0\n        binning.N_u = 256\n        binning.N_v = 256\n        projection = PET_Projection(binning, proj, offsets, locations)\n        return projection.uncompress_self()\n\n    def display_geometry(self):\n        return display_PET_Projection_geometry()\n\n    def __repr__(self):\n        s = \"Static PET acquisition:  \\n\"\n        s = s + \" - Time_start:                   %s \\n\" % millisec_to_min_sec(self.prompts.get_time_start())\n        s = s + \" - Time_end:                     %s \\n\" % millisec_to_min_sec(self.prompts.get_time_end())\n        s = s + \" - Duration:                     %s \\n\" % millisec_to_min_sec(self.prompts.get_time_end() -\n                                                                               self.prompts.get_time_start())\n        s = s + \" - N_counts:                     %d \\n\" % self.prompts.get_integral()\n        s = s + \" - N_locations:                  %d \\n\" % self.prompts.sparsity.get_N_locations()\n        s = s + \" - compression_ratio:            %d \\n\" % self.prompts.sparsity.compression_ratio\n        s = s + \" - listmode_loss:                %d \\n\" % self.prompts.sparsity.listmode_loss\n        s = s + \" = Scanner: \\n\"\n        s = s + \"     - Name:                     %s \\n\" % self.scanner.model\n        s = s + \"     - Manufacturer:             %s \\n\" % self.scanner.manufacturer\n        s = s + \"     - Version:                  %s \\n\" % self.scanner.version\n        s = s + \" * Binning: \\n\"\n        s = s + \"     - N_axial bins:             %d \\n\" % self.binning.N_axial\n        s = s + \"     - N_azimuthal bins:         %d \\n\" % self.binning.N_azimuthal\n        s = s + \"     - Angles axial:             %s \\n\" % array_to_string(self.binning.angles_axial)\n        s = s + \"     - Angles azimuthal:         %s \\n\" % array_to_string(self.binning.angles_azimuthal)\n        s = s + \"     - Size_u:                   %f \\n\" % self.binning.size_u\n        s = s + \"     - Size_v:                   %f \\n\" % self.binning.size_v\n        s = s + \"     - N_u:                      %s \\n\" % self.binning.N_u\n        s = s + \"     - N_v:                      %s \\n\" % self.binning.N_v\n        return s\n\n    def _repr_html_(self):\n        if not has_ipy_table:\n            return \"Please install ipy_table.\"\n        if self.scanner is not None:\n            table_data = [\n                ['Time_start', millisec_to_min_sec(self.prompts.get_time_start())],\n                ['Time_end', millisec_to_min_sec(self.prompts.get_time_end())],\n                ['Duration', millisec_to_min_sec(self.prompts.get_time_end() - self.prompts.get_time_start())],\n                ['N_counts', pretty_print_large_number(self.prompts.get_integral())],\n                ['N_locations', pretty_print_large_number(self.prompts.sparsity.get_N_locations)],\n                # ['compression_ratio',print_percentage(self.compression_ratio)],\n                # ['listmode_loss',self.listmode_loss],\n                ['Scanner Name', self.scanner.model], ['Scanner Manufacturer', self.scanner.manufacturer],\n                ['Scanner Version', self.scanner.version], ]\n        else:\n            table_data = [\n                ['Time_start', millisec_to_min_sec(self.prompts.get_time_start())],\n                ['Time_end', millisec_to_min_sec(self.prompts.get_time_end())],\n                ['Duration', millisec_to_min_sec(self.prompts.get_time_end() - self.prompts.get_time_start())],\n                ['N_counts', pretty_print_large_number(self.prompts.get_integral())],\n                ['N_locations', pretty_print_large_number(self.prompts.sparsity.get_N_locations())], ]\n            # ['compression_ratio',print_percentage(self.compression_ratio)],\n            # ['listmode_loss',self.listmode_loss], ]\n        table = ipy_table.make_table(table_data)\n        table = ipy_table.apply_theme('basic_left')\n        # table = ipy_table.set_column_style(0, color='lightBlue')\n        table = ipy_table.set_global_style(float_format=\"%3.3f\")\n        return table._repr_html_()\n\n\n#########################################################################\n#########\t\t[CLASS] PET_Multi2D_Scan\t\t#########\n#########################################################################\n\nclass PET_Multi2D_Scan(PET_Static_Scan):\n    \"\"\"This class has been designed for testing purposes, because it is built on top of PET_Static_Scan\n    so that each one of those, which were 'volume slices' in the static model, now is a 2D time frame.\n    Doing so we have a dynamic volume (i.e. a single slice whose activity changes in time) built as a\n    PET_Static_Scan object, that is able to exploit the fast and parallel reconstruction of a multi-slice\n    volume, without the need of multiple nested for-loop that we need to use on a standard PET_Dynamic_Scan()\"\"\"\n\n    def __init__(self):\n        self.n_slices = 0\n        self.scatter_duration = None\n        self.prompts_duration = None\n        self.attenuation_projection = None\n        PET_Static_Scan.__init__(self)\n\n    def set_activity_size(self, activity_size):\n        self.activity_size = (activity_size[0], activity_size[1], self.n_slices)\n\n    def set_activity_shape(self, activity_shape):\n        self.activity_shape = (activity_shape[0], activity_shape[1], self.n_slices)\n\n    def set_attenuation_projection(self, attenuation_projection):\n        self.attenuation_projection = attenuation_projection\n        self.attenuation_projection.data = float32(self.attenuation_projection.data)\n\n    def set_prompts_duration(self, duration_array):\n        self.prompts_duration = duration_array\n\n    def set_scatter_duration(self, duration_array):\n        self.scatter_duration = duration_array\n\n    def set_number_of_slices(self, n_slices):\n        self.n_slices = n_slices\n        self.binning.N_azimuthal = 1\n        self.binning.angles_azimuthal = int32([0, ])\n        self.binning.N_v = self.n_slices + 1\n        self.binning.size_v = self.n_slices\n        self.set_binning(self.binning)\n        if self.scatter_duration is None:\n            self.scatter_duration = ones([self.n_slices + 1, ])\n        if self.prompts_duration is None:\n            self.prompts_duration = ones([self.n_slices + 1, ])\n\n    def osem_reconstruction(self, iterations=10, activity=None, attenuation_projection=None, subset_mode=\"random\",\n                            subset_size=64, transformation=None, azimuthal_range=None, show_progressbar=True,\n                            SaveAll=False, KineticPrior=False, SaveDisk=False, savepath=\"\"):\n\n        if show_progressbar:\n            progress_bar = ProgressBar(title=\"Reconstruction progress ...\")\n            progress_bar.set_percentage(0.0)\n\n        if activity is None:\n            activity = self._make_Image3D_activity(ones(self.activity_shape, dtype=float32, order=\"F\"))\n\n        if self.sensitivity is None:\n            sensitivity = self.prompts.copy()\n            sensitivity.data = 0.0 * sensitivity.data + 1\n            self.set_sensitivity(sensitivity)\n\n        if SaveAll:\n            activity_all = ones((self.activity_shape[0], self.activity_shape[1], self.activity_shape[2], iterations),\n                                dtype=float32)\n\n        subsets_generator = SubsetGenerator(self.binning.N_azimuthal, self.binning.N_axial)\n\n        self.profiler.reset()\n        for i in range(iterations):\n            if not show_progressbar:\n                if iterations >= 15:\n                    if i == iterations - 1:\n                        print(\"iteration \", (i + 1), \"/\", iterations)\n                    elif i + 1 == 1:\n                        print(\"iteration \", (i + 1), \"/\", iterations)\n                    elif (int32(i + 1) / 5) * 5 == i + 1:\n                        print(\"iteration \", (i + 1), \"/\", iterations)\n                else:\n                    print(\"iteration \", (i + 1), \"/\", iterations)\n\n            subsets_matrix = subsets_generator.new_subset(subset_mode, subset_size, azimuthal_range)\n            # TODO : introduce OSL prior into osem_step\n            activity = self.osem_step(activity, subsets_matrix, attenuation_projection, transformation)\n            if SaveAll:\n                temp = activity.data\n                temp = flipud(temp)  # U-D\n                temp = fliplr(temp)  # L-R\n                # temp = flip(temp,2)  #Zreverse\n                activity_all[:, :, :, i] = temp\n                del temp\n            if SaveDisk:\n                activity.save_to_file(savepath + 'activity_recon_%d.nii' % i)\n            if KineticPrior:\n                # TODO\n                # call kinetic model fitter module\n                # update activity before next iteration\n                pass\n            progress_bar.set_percentage((i + 1) * 100.0 / iterations)\n\n        if SaveAll:\n            return activity, activity_all\n        else:\n            return activity\n\n    def mlem_reconstruction(self, iterations=10, activity=None, attenuation_projection=None, transformation=None):\n        if activity is None:\n            activity = self._make_Image3D_activity(ones(self.activity_shape, dtype=float32, order=\"F\"))\n\n        if self.sensitivity is None:\n            self.set_sensitivity(1.0)\n\n        for i in range(iterations):\n            print(i)\n            subsets_matrix = None\n            activity = self.osem_step(activity, subsets_matrix, transformation)\n        return activity\n\n    # TODO: Gradient prior terms for OSL version of osem_step\n    def kinetic_model_prior(self, activity_, model, sigma, sf):\n        Nx, Ny, frames = activity_.data.shape\n        voxels = Nx * Ny\n        a_vec = activity_.data.reshape([voxels, frames])\n        l = zeros([voxels, frames])\n        for t in range(frames):\n            for v in range(voxels):\n                l[v, t] = (model[v, t] - sf * a_vec[v, t]) / sigma ** 2\n        return l.reshape(Nx, Ny, frames)\n\n    def smoothness_prior(self, activity_, importance):\n        kernel = ones((3, 3, 1))\n        kernel[1, 1] = -8.0\n        gradient = ndimage.convolve(self, activity_.data, kernel, mode='constant', cval=0.0)\n        return importance * gradient\n\n    def kinetic_plus_smoothing_prior(self, activity_, sources, sigma, sf, importance):\n        return self.kinetic_model_prior(activity_, sources, sigma, sf) + self.smoothness_prior(activity_, importance)\n\n    def osem_step(self, activity, subsets_matrix=None, attenuation_projection=None, transformation=None,\n                  gradient_prior_type=None, gradient_prior_args=()):\n\n        epsilon = 1e-08\n\n        self.profiler.rec_iteration()\n        self.profiler.tic()\n\n        prompts = self.prompts\n        if self._use_compression:\n            prompts = prompts.uncompress_self()\n        self.profiler.rec_uncompress()\n\n        duration_ms = prompts.get_duration()\n        if duration_ms is None:\n            print(\"Acquisition duration unknown (self.prompts.time_bins undefined); assuming 60 minutes. \")\n            duration_ms = 1000 * 60 * 60\n        duration = duration_ms / 1000.0\n        alpha = self.scale_activity\n\n        if attenuation_projection is not None:\n            self.profiler.tic()\n            attenuation_projection = attenuation_projection.get_subset(subsets_matrix)\n            self.profiler.rec_get_subset_attenuation()\n        elif self.attenuation_projection is not None:\n            self.profiler.tic()\n            attenuation_projection = self.attenuation_projection.get_subset(subsets_matrix)\n            self.profiler.rec_get_subset_attenuation()\n        elif self.attenuation is not None:\n            print(\"Projecting attenuation\")\n            # self.profiler.tic()\n            self.attenuation_projection = self.project_attenuation(self.attenuation)\n            # self.profiler.rec_project_attenuation()\n            self.profiler.tic()\n            attenuation_projection = self.attenuation_projection.get_subset(subsets_matrix)\n            self.profiler.rec_get_subset_attenuation()\n            print(\"Done\")\n        else:\n            attenuation_projection = 1.0\n\n        if self.sensitivity is not None:\n            self.profiler.tic()\n            sens_x_att = self.sensitivity.get_subset(subsets_matrix)\n            self.profiler.rec_get_subset_sensitivity()\n            self.profiler.tic()\n            sens_x_att = sens_x_att * attenuation_projection\n            self.profiler.rec_compose_various()\n        else:\n            sens_x_att = attenuation_projection\n        if isscalar(sens_x_att):\n            sens_x_att = sens_x_att * ones(prompts.data.shape, dtype=float32)\n\n        if self.randoms is not None:\n            randoms = self.randoms\n            if self._use_compression:\n                self.profiler.tic()\n                randoms = randoms.uncompress_self()\n                self.profiler.rec_uncompress()\n            self.profiler.tic()\n            randoms = randoms.get_subset(subsets_matrix)\n            self.profiler.rec_get_subset_randoms()\n            self.profiler.tic()\n            randoms = (randoms + epsilon) / (sens_x_att * alpha * duration + epsilon)\n            self.profiler.rec_compose_randoms()\n\n        if self.scatter is not None:\n            self.profiler.tic()\n            mscatter = self.scatter.get_subset(subsets_matrix)\n            self.profiler.rec_get_subset_scatter()\n            self.profiler.tic()\n            mscatter = (mscatter + epsilon) / (attenuation_projection * alpha * duration + epsilon)\n            self.profiler.rec_compose_scatter()\n\n            # Scale scatter: this is used in dynamic and kinetic imaging, when scatter is calculated using \n            # the ativity for a time period longer than the current frame: \n            if self.scatter.get_duration() is not None:\n                if self.scatter.get_duration() > 1e-6:\n                    self.profiler.tic()\n                    mscatter = mscatter * duration / self.scatter.get_duration()\n                    self.profiler.rec_compose_scatter()\n\n        if gradient_prior_type is not None:\n            if gradient_prior_type == \"smooth\":\n                gradient_prior_func = self.smoothness_prior\n            elif gradient_prior_type == \"kinetic\":\n                gradient_prior_func = self.kinetic_model_prior\n            elif gradient_prior_type == \"both\":\n                gradient_prior_func = self.kinetic_plus_smoothing_prior\n        else:\n            gradient_prior_func = None\n\n        # print duration, alpha\n        self.profiler.tic()\n        norm = self.backproject_activity(sens_x_att * alpha * duration, transformation=transformation)\n        if gradient_prior_func is not None:\n            update2 = norm + epsilon - gradient_prior_func(activity, *gradient_prior_args)\n        else:\n            update2 = norm + epsilon\n        self.profiler.rec_backprojection_norm_total()\n\n        self.profiler.tic()\n        projection = self.project_activity(activity, subsets_matrix=subsets_matrix, transformation=transformation)\n        self.profiler.rec_projection_activity_total()\n\n        if self.randoms is not None:\n            if self.scatter is not None:\n                self.profiler.tic()\n                p = prompts.get_subset(subsets_matrix)\n                self.profiler.rec_get_subset_prompts()\n                self.profiler.tic()\n                s = (projection + randoms + mscatter + epsilon)\n                self.profiler.rec_compose_various()\n                self.profiler.tic()\n                update1 = self.backproject_activity(p / s, transformation=transformation)\n                self.profiler.rec_backprojection_activity_total()\n            else:\n                self.profiler.tic()\n                p = prompts.get_subset(subsets_matrix)\n                self.profiler.rec_get_subset_prompts()\n                self.profiler.tic()\n                s = (projection + randoms + epsilon)\n                self.profiler.rec_compose_various()\n                self.profiler.tic()\n                update1 = self.backproject_activity(p / s, transformation=transformation)\n                self.profiler.rec_backprojection_activity_total()\n        else:\n            if self.scatter is not None:\n                self.profiler.tic()\n                p = prompts.get_subset(subsets_matrix)\n                self.profiler.rec_get_subset_prompts()\n                self.profiler.tic()\n                s = (projection + mscatter + epsilon)\n                self.profiler.rec_compose_various()\n                self.profiler.tic()\n                update1 = self.backproject_activity(p / s, transformation=transformation)\n                self.profiler.rec_backprojection_activity_total()\n            else:\n                self.profiler.tic()\n                p = prompts.get_subset(subsets_matrix)\n                self.profiler.rec_get_subset_prompts()\n                self.profiler.tic()\n                s = (projection + epsilon)\n                self.profiler.rec_compose_various()\n                self.profiler.tic()\n                update1 = self.backproject_activity(p / s, transformation=transformation)\n                self.profiler.rec_backprojection_activity_total()\n\n        self.profiler.tic()\n        activity = (activity / update2) * update1\n        self.profiler.rec_update()\n\n        return activity\n\n    def osem_step_old(self, activity, subsets_matrix, transformation, gradient_prior_type=None, gradient_prior_args=()):\n        epsilon = 1e-08\n\n        prompts = self.prompts\n        if self._use_compression:\n            prompts = prompts.uncompress_self()\n        prompts = prompts.get_subset(subsets_matrix)\n\n        # make matrices of duration arrays\n        prompts_duration = tile(self.prompts_duration / 1000.0, (prompts.data.shape[0], prompts.data.shape[1],\n                                                                 prompts.data.shape[2], 1))\n        scatter_duration = tile(self.scatter_duration / 1000.0, (prompts.data.shape[0], prompts.data.shape[1],\n                                                                 prompts.data.shape[2], 1))\n        alpha = self.scale_activity\n\n        if self.attenuation_projection is not None:\n            attenuation_projection = self.attenuation_projection.get_subset(subsets_matrix)\n        else:\n            attenuation_projection = 1.0\n\n        if self.sensitivity is not None:\n            if isscalar(self.sensitivity):\n                sens_x_att = self.sensitivity * attenuation_projection\n            else:\n                sens_x_att = self.sensitivity.get_subset(subsets_matrix) * attenuation_projection\n        else:\n            sens_x_att = attenuation_projection\n\n        if self.randoms is not None:\n            randoms = self.randoms\n            if self._use_compression:\n                randoms = randoms.uncompress_self()\n            randoms = (randoms.get_subset(subsets_matrix) + epsilon) / (sens_x_att * alpha * prompts_duration + epsilon)\n\n        if self.scatter is not None:\n            mscatter = (self.scatter.get_subset(subsets_matrix) + epsilon) / (\n                attenuation_projection * alpha * prompts_duration + epsilon)\n            # Scale scatter: this is used in dynamic and kinetic imaging, when scatter is calculated using the ativity for a time period longer than the current frame:\n            mscatter = mscatter * prompts_duration / scatter_duration\n\n        if gradient_prior_type is not None:\n            if gradient_prior_type == \"smooth\":\n                gradient_prior_func = self.smoothness_prior\n            elif gradient_prior_type == \"kinetic\":\n                gradient_prior_func = self.kinetic_model_prior\n            elif gradient_prior_type == \"both\":\n                gradient_prior_func = self.kinetic_plus_smoothing_prior\n        else:\n            gradient_prior_func = None\n\n        norm = self.backproject_activity(sens_x_att * alpha * prompts_duration, transformation=transformation)\n        if gradient_prior_func is not None:\n            update2 = norm + epsilon - gradient_prior_func(activity, *gradient_prior_args)\n        else:\n            update2 = norm + epsilon\n\n        projection = self.project_activity(activity, subsets_matrix=subsets_matrix, transformation=transformation)\n\n        if self.randoms is not None:\n            if self.scatter is not None:\n                update1 = self.backproject_activity(prompts / (projection + randoms + mscatter + epsilon),\n                                                    transformation=transformation)\n            else:\n                update1 = self.backproject_activity(prompts / (projection + randoms + epsilon),\n                                                    transformation=transformation)\n\n        else:\n            if self.scatter is not None:\n                update1 = self.backproject_activity(prompts / (projection + mscatter + epsilon),\n                                                    transformation=transformation)\n            else:\n                update1 = self.backproject_activity(prompts / (projection + epsilon), transformation=transformation)\n\n        # activity = activity - gradient1\n        activity = (activity / update2) * update1\n\n        return activity\n\n    def quick_inspect(self, figshape=None, index_axial=0, index_slice=0):\n        index_azimuthal = 0\n        if self.randoms is not None and not isscalar(self.randoms):\n            randoms = self.randoms.to_nd_array()[index_axial, index_azimuthal, :, index_slice + 1]\n        else:\n            randoms = 0.0\n        if self.prompts is not None and not isscalar(self.prompts):\n            prompts = self.prompts.to_nd_array()[index_axial, index_azimuthal, :, index_slice + 1]\n        else:\n            prompts = 0.0\n        if self.sensitivity is not None:\n            if not isscalar(self.sensitivity):\n                sensitivity = self.sensitivity.to_nd_array()[index_axial, index_azimuthal, :, index_slice + 1]\n            else:\n                sensitivity = self.sensitivity\n        else:\n            sensitivity = 1.0\n        if self.scatter is not None and not isscalar(self.scatter):\n            scatter = self.scatter.to_nd_array()\n            prompts_duration = tile(self.prompts_duration / 1000.0,\n                                    (self.prompts.data.shape[0], self.prompts.data.shape[1], \\\n                                     self.prompts.data.shape[2], 1))\n            scatter_duration = tile(self.scatter_duration / 1000.0,\n                                    (self.prompts.data.shape[0], self.prompts.data.shape[1], \\\n                                     self.prompts.data.shape[2], 1))\n            scatter = scatter * prompts_duration / scatter_duration\n            scatter = scatter[index_axial, index_azimuthal, :, index_slice + 1]\n        else:\n            scatter = 0.0\n\n        if has_pylab:\n            if figshape is not None:\n                if figshape == \"default\":\n                    figshape = (6, 2.5)\n                pylab.figure(figsize=figshape)\n                pylab.plot(prompts - randoms, label='prompts-randoms')\n                pylab.hold(1)\n                pylab.plot(sensitivity * scatter, 'g', label='sensitivity*scatter')\n                pylab.legend(fontsize=10)\n                pylab.xlim((0, self.binning.N_u))\n                pylab.show()\n            else:\n                figshape = (6, 2.5)\n                pylab.figure(figsize=figshape)\n                pylab.plot(prompts - randoms, label='prompts-randoms')\n                pylab.hold(1)\n                pylab.plot(sensitivity * scatter, 'g', label='sensitivity*scatter')\n                pylab.legend(fontsize=10)\n                pylab.xlim((0, self.binning.N_u))\n                pylab.show()\n        else:\n            print(\"quick_inspect uses Pylab to display imaging data. Please install Pylab. \")\n\n        if has_pylab:\n            if figshape is not None:\n                if figshape == \"default\":\n                    figshape = (6, 2.5)\n                pylab.figure(figsize=figshape)\n                pylab.plot(prompts - randoms, label='prompts-randoms')\n                pylab.hold(1)\n                pylab.plot(sensitivity * scatter, 'g', label='sensitivity*scatter')\n                pylab.legend(fontsize=10)\n                pylab.xlim((0, self.binning.N_u))\n                pylab.show()\n            else:\n                figshape = (6, 2.5)\n                pylab.figure(figsize=figshape)\n                pylab.plot(prompts - randoms, label='prompts-randoms')\n                pylab.hold(1)\n                pylab.plot(sensitivity * scatter, 'g', label='sensitivity*scatter')\n                pylab.legend(fontsize=10)\n                pylab.xlim((0, self.binning.N_u))\n                pylab.show()\n        else:\n            print(\"quick_inspect uses Pylab to display imaging data. Please install Pylab. \")\n\n\n#########################################################################\n#########\t\t[CLASS] PET_Dynamic_Scan\t\t#########\n#########################################################################\n\n\nclass PET_Dynamic_Scan(PET_Static_Scan):\n    \"\"\"PET Dynamic Scan. This is useful for motion correction and for kinetic imaging, or both. \n    See how it is built as a colletion of PET_Static_Scan objects and most of the set() and get()\n    methods are just built on top of the ones previously defined. If they work, these should be fine!\"\"\"\n\n    def __init__(self):\n        self._dynamic = []  # Sequence of static scans, one per time bin\n        self.time_bins = []  # Time binning\n        self.static = None\n        PET_Static_Scan.__init__(self)\n\n    ############ SET SHAPE AND SCANNER PARAMETERS\n\n    def set_activity_shape(self, activity_shape):\n        if not len(activity_shape) == 3:\n            print(\"Invalid activity shape\")  # FIXME: raise invalid input error\n        else:\n            self.activity_shape = activity_shape\n            if hasattr(self, \"static\"):\n                if self.static is not None:\n                    self.static.set_activity_shape(activity_shape)\n            for frame in range(len(self)):\n                self[frame].set_activity_shape(activity_shape)\n\n    def set_activity_size(self, activity_size):\n        if not len(activity_size) == 3:\n            raise (\"Invalid activity size\")\n        else:\n            self.activity_size = activity_size\n            if hasattr(self, \"static\"):\n                if self.static is not None:\n                    self.static.set_activity_size(activity_size)\n            for frame in range(len(self)):\n                self[frame].set_activity_size(activity_size)\n\n    def set_attenuation_shape(self, attenuation_shape):\n        if not len(attenuation_shape) == 3:\n            raise (\"Invalid attenuation shape\")\n        else:\n            self.attenuation_shape = attenuation_shape\n            if hasattr(self, \"static\"):\n                if self.static is not None:\n                    self.static.set_attenuation_shape(attenuation_shape)\n            for frame in range(len(self)):\n                self[frame].set_attenuation_shape(attenuation_shape)\n\n    def set_attenuation_size(self, attenuation_size):\n        if not len(attenuation_size) == 3:\n            raise (\"Invalid attenuation size\")\n        else:\n            self.attenuation_size = attenuation_size\n            if hasattr(self, \"static\"):\n                if self.static is not None:\n                    self.static.set_attenuation_size(attenuation_size)\n            for frame in range(len(self)):\n                self[frame].set_attenuation_size(attenuation_size)\n\n    def brain_crop(self, bin_range=(100, 240)):\n        if self._use_compression is True:\n            print(\"Cropping currently only works with uncompressed data. \")\n            return\n        self.static.brain_crop(bin_range)\n        for frame in range(len(self)):\n            self[frame].brain_crop(bin_range)\n\n    ############# IMPORT ROUTINES\n\n    def import_listmode(self, hdr_filename, time_range_ms=(0, None), data_filename=None, motion_files_path=None,\n                        display_progress=False):\n        \"\"\"Load prompts data from a listmode file. \"\"\"\n        print_debug(\"- Loading dynamic PET data from listmode file \" + str(hdr_filename))\n        hdr = Interfile.load(hdr_filename)\n        # Extract information from the listmode header\n\n        # 1) Guess the path of the listmode data file, if not specified or mis-specified;\n        #  1 - see if the specified listmode data file exists\n        if data_filename is not None:\n            data_filename = data_filename.replace(\"/\", os.path.sep).replace(\"\\\\\",\n                                                                            os.path.sep)  # cross platform compatibility\n            if not os.path.exists(data_filename):\n                raise FileNotFound(\"listmode data\", data_filename)\n        # 2 - if the listmode data file is not specified, try with the name (and full path) contained in the listmode header\n        data_filename = hdr['name of data file']['value']\n        data_filename = data_filename.replace(\"/\", os.path.sep).replace(\"\\\\\",\n                                                                        os.path.sep)  # cross platform compatibility\n        if not os.path.exists(data_filename):\n            #  3 - if it doesn't exist, look in the same path as the header file for the listmode data file with name specified in the listmode header file\n            data_filename = os.path.split(hdr_filename)[0] + os.path.sep + os.path.split(data_filename)[-1]\n            if not os.path.exists(data_filename):\n                #  4 - if it doesn't exist, look in the same path as the header file for the listmode data file with same name as the listmode header file, replacing the extension: \".l.hdr -> .l\"\n                if hdr_filename.endswith(\".l.hdr\"):\n                    data_filename = hdr_filename.replace(\".l.hdr\", \".l\")\n                    if not os.path.exists(data_filename):\n                        raise FileNotFound(\"listmode data\", data_filename)\n                # 5 - if it doesn't exist, look in the same path as the header file for the listmode data file with same name as the listmode header file, replacing the extension: \".hdr -> .l\"\n                elif hdr_filename.endswith(\".hdr\"):\n                    data_filename = hdr_filename.replace(\".hdr\", \".l\")\n                    if not os.path.exists(data_filename):\n                        raise FileNotFound(\"listmode data\", data_filename)\n\n        # 2) Determine the duration of the acquisition\n        n_packets = hdr['total listmode word counts']['value']\n        scan_duration = hdr['image duration']['value'] * 1000  # milliseconds\n\n        # 3) determine scanner parameters\n        n_radial_bins = hdr['number of projections']['value']\n        n_angles = hdr['number of views']['value']\n        n_rings = hdr['number of rings']['value']\n        max_ring_diff = hdr['maximum ring difference']['value']\n        n_sinograms = n_rings + 2 * n_rings * max_ring_diff - max_ring_diff ** 2 - max_ring_diff\n\n        # Determine the time binning\n        if time_range_ms[1] is None:\n            time_range_ms = int32(linspace(0, scan_duration, DEFAULT_N_TIME_BINS + 1))\n        elif isscalar(time_range_ms):  # time_bins in this case indicates the number of time bins\n            time_range_ms = int32(linspace(0, scan_duration, time_range_ms + 1))\n\n        # Display information\n        print_debug(\" - Number of packets:    %d       \" % n_packets)\n        print_debug(\" - Scan duration:        %d [sec] \" % (scan_duration / 1000.0))\n        print_debug(\" - Listmode data file:   %s       \" % data_filename)\n        print_debug(\" - Listmode header file: %s       \" % hdr_filename)\n        print_debug(\" - Number of time bins:  %d       \" % (len(time_range_ms) - 1))\n        print_debug(\" - Time start:           %f [sec] \" % (time_range_ms[0] / 1000.0))\n        print_debug(\" - Time end:             %f [sec] \" % (time_range_ms[-1] / 1000.0))\n        print_debug(\" - time_range_ms:        %s       \" % str(time_range_ms))\n        print_debug(\" - n_radial_bins:        %d       \" % n_radial_bins)\n        print_debug(\" - n_angles:             %d       \" % n_angles)\n        print_debug(\" - n_angles:             %d       \" % n_sinograms)\n\n        progress_bar = ProgressBar()\n        if display_progress:\n            progress_callback = progress_bar.set_percentage\n        else:\n            def progress_callback(value):\n                if value == 1.0:\n                    print(value, \"/\", 100)\n                if (int32(value) / 10) * 10 == value:\n                    print(value, \"/\", 100)\n\n        # Load the listmode data\n        M = self.scanner.michelogram\n        R = self.scanner.listmode.load_listmode(data_filename, n_packets, time_range_ms, self.binning, n_radial_bins,\n                                                n_angles, n_sinograms, M.span, M.segments_sizes, M.michelogram_sinogram,\n                                                M.michelogram_plane, progress_callback)\n        if display_progress:\n            progress_bar.set_percentage(100)\n\n        # self.dynamic_inflation = R['dynamic_inflation']\n\n        N_time_bins = R['N_time_bins']\n        time_start = R['time_start']\n        time_end = R['time_end']\n        # self.time_bins = time_bins[time_start:N_time_bins+1]  #the actual time bins are less than the requested time bins, truncate time_bins\n        self.time_bins = time_range_ms\n\n        # Make list of PET_Static_Scan objects, one per bin\n        self._dynamic = []\n        for t in range(N_time_bins):\n            PET_t = PET_Static_Scan()\n            PET_t.use_compression(self._use_compression)\n            PET_t.use_gpu(self._use_gpu)\n            PET_t.set_scanner(self.scanner.__class__)\n            PET_t.set_binning(self.binning)\n            PET_t._load_static_measurement(t)\n            # make list of static scans\n            self._dynamic.append(PET_t)\n            # also make one attribut for each static scan\n            setattr(self, \"frame%d\" % t, self._dynamic[t])\n            # set activity shape and size and attenuation shape and size\n            PET_t.set_activity_size(self.activity_size)\n            PET_t.set_activity_shape(self.activity_shape)\n            PET_t.set_attenuation_size(self.activity_size)\n            PET_t.set_attenuation_shape(self.activity_shape)\n\n        # Make a global PET_Static_Scan object\n        self.static = PET_Static_Scan()\n        self.static.use_compression(self._use_compression)\n        self.static.use_gpu(self._use_gpu)\n        self.static.set_scanner(self.scanner.__class__)\n        self.static.set_binning(self.binning)\n        self.static._load_static_measurement()\n        self.static.set_activity_size(self.activity_size)\n        self.static.set_activity_shape(self.activity_shape)\n        self.static.set_attenuation_size(self.activity_size)\n        self.static.set_attenuation_shape(self.activity_shape)\n\n        # Free structures listmode data\n        self.scanner.listmode.free_memory()\n\n        # Construct ilang model\n        self._construct_ilang_model()\n\n    def import_prompts(self):\n        print(\n            \"Not implemented: should load prompts for multiple time frames and also set self.static.prompts to the integral.\")\n\n    def import_randoms(self):\n        print(\n            \"Not implemented: should load randoms for multiple time frames and also set self.static.randoms to the integral.\")\n\n    ########### EXPORT ROUTINES\n\n    def export_prompts(self):\n        print(\"Not implemented.\")\n\n    def export_randoms(self):\n        print(\"Not implemented.\")\n\n    ########### SET ROUTINES\n\n    def set_prompts(self, prompts_list):\n        N_time_bins = len(prompts_list)\n        if len(self) == N_time_bins:\n            print(\"PET_Dynamic_Scan.set_prompts(): Number of sinograms matches current setup; no re-initialization.\")\n            for t in range(N_time_bins):\n                self[t].set_prompts(prompts_list[t])\n        else:\n            print(\n                \"PET_Dynamic_Scan.set_prompts(): Number of sinograms does not match current setup; re-initialization.\")\n            self._dynamic = []\n            total_prompts = prompts_list[0] * 0\n            if total_prompts.is_compressed():\n                total_prompts = total_prompts.uncompress_self()\n            for t in range(N_time_bins):\n                PET_t = PET_Static_Scan()\n                PET_t.use_compression(self._use_compression)\n                PET_t.use_gpu(self._use_gpu)\n                PET_t.set_scanner(self.scanner.__class__)\n                PET_t.set_binning(self.binning)\n                PET_t.set_prompts(prompts_list[t])\n                self._dynamic.append(PET_t)\n                setattr(self, \"frame%d\" % t, self._dynamic[t])\n                # FIXME: remove excess frames if new N_time_bins is less than previous\n                PET_t.set_activity_size(self.activity_size)\n                PET_t.set_activity_shape(self.activity_shape)\n                PET_t.set_attenuation_size(self.activity_size)\n                PET_t.set_attenuation_shape(self.activity_shape)\n                if prompts_list[t].is_compressed():\n                    total_prompts += prompts_list[t].uncompress_self()\n                else:\n                    total_prompts += prompts_list[t]\n            if self._use_compression:\n                total_prompts = total_prompts.compress_self()\n\n            # Make a global PET_Static_Scan object\n            self.static = PET_Static_Scan()\n            self.static.use_compression(self._use_compression)\n            self.static.use_gpu(self._use_gpu)\n            self.static.set_scanner(self.scanner.__class__)\n            self.static.set_binning(self.binning)\n            self.static.set_prompts(total_prompts)\n            self.static.set_activity_size(self.activity_size)\n            self.static.set_activity_shape(self.activity_shape)\n            self.static.set_attenuation_size(self.activity_size)\n            self.static.set_attenuation_shape(self.activity_shape)\n\n            # Construct ilang model\n            self._construct_ilang_model()\n\n    def set_randoms(self, randoms_list):\n        N_time_bins = len(randoms_list)\n        if len(self) == N_time_bins:\n            print(\"PET_Dynamic_Scan.set_randoms(): Number of sinograms matches current setup; no re-initialization.\")\n            for t in range(N_time_bins):\n                self[t].set_randoms(randoms_list[t])\n        else:\n            print(\n                \"PET_Dynamic_Scan.set_randoms(): Number of sinograms does not match current setup; re-initialization.\")\n            self._dynamic = []\n            total_randoms = randoms_list[0] * 0\n            for t in range(N_time_bins):\n                PET_t = PET_Static_Scan()\n                PET_t.use_compression(self._use_compression)\n                PET_t.use_gpu(self._use_gpu)\n                PET_t.set_scanner(self.scanner.__class__)\n                PET_t.set_binning(self.binning)\n                PET_t.set_randoms(randoms_list[t])\n                self._dynamic.append(PET_t)\n                setattr(self, \"frame%d\" % t, self._dynamic[t])\n                # FIXME: remove excess frames if new N_time_bins is less than previous\n                PET_t.set_activity_size(self.activity_size)\n                PET_t.set_activity_shape(self.activity_shape)\n                PET_t.set_attenuation_size(self.activity_size)\n                PET_t.set_attenuation_shape(self.activity_shape)\n                total_randoms += randoms_list[t]\n\n            # Make a global PET_Static_Scan object\n            self.static = PET_Static_Scan()\n            self.static.use_compression(self._use_compression)\n            self.static.use_gpu(self._use_gpu)\n            self.static.set_scanner(self.scanner.__class__)\n            self.static.set_binning(self.binning)\n            self.static.set_randoms(total_randoms)\n            self.static.set_activity_size(self.activity_size)\n            self.static.set_activity_shape(self.activity_shape)\n            self.static.set_attenuation_size(self.activity_size)\n            self.static.set_attenuation_shape(self.activity_shape)\n\n            # Construct ilang model\n            self._construct_ilang_model()\n\n    def set_scatter(self, scatter, duration_ms=None):\n        self.scatter = float32(scatter)\n        self.static.set_scatter(scatter, duration_ms)\n        for frame in range(len(self)):\n            self[frame].set_scatter(scatter, duration_ms)\n\n    def set_sensitivity(self, sensitivity):\n        # FIXME: verify type: PET_projection or nd_array (the latter only in full sampling mode)\n        self.sensitivity = sensitivity\n        self.sensitivity.data = float32(self.sensitivity.data)\n        self.static.set_sensitivity(sensitivity)\n        for frame in range(len(self)):\n            self[frame].set_sensitivity(sensitivity)\n\n    def set_attenuation(self, attenuation):\n        # FIXME: verify type\n        self.static.set_attenuation(attenuation)\n        for frame in range(len(self)):\n            self[frame].set_attenuation(float32(attenuation))\n\n    def set_attenuation_projection(self, attenuation_projection):\n        # FIXME: verify type\n        self.attenuation_projection = attenuation_projection\n        self.attenuation_projection.data = float32(attenuation_projection.data)\n        self.static.set_attenuation_projection(attenuation_projection)\n        for frame in range(len(self)):\n            self[frame].set_attenuation_projection(attenuation_projection)\n\n    ########## GET ROUTINES\n\n    def get_prompts(self):\n        prompts = []\n        for frame in self:\n            prompts.append(frame.prompts)\n        return prompts\n\n    def get_randoms(self):\n        randoms = []\n        for frame in self:\n            randoms.append(frame.randoms)\n        return randoms\n\n    def get_scatter(self):\n        return self.static.scatter\n\n    def get_sensitivity(self):\n        return self.static.sensitivity\n\n    def get_attenuation(self):\n        return self.static.attenuation\n\n    def get_attenuation_projection(self):\n        return self.static.attenuation_projection\n\n    def use_compression(self, use_it):\n        self._use_compression = use_it\n\n    ########### VARIOUS RECONSTRUCTION FUNCTIONS: OSEM, DIRECT (scheleton), 4D (check what this is with Stefano!)\n    def osem_reconstruction(self, iterations=10, activity=None, attenuation_projection=None, subset_mode=\"random\",\n                            subset_size=64, transformations=None, azimuthal_range=None, show_progressbar=True,\n                            SaveAll=False, KineticPrior=False, SaveDisk=False, savepath=\"\"):\n\n        if show_progressbar:\n            progress_bar_slice = ProgressBar(title=\"Frames stack ...\")\n            progress_bar_slice.set_percentage(0.0)\n\n        \"\"\"Iterates through various time frames and reconstruct each one of them as a PET_Static_Scan object \"\"\"\n        for frame in range(len(self)):\n            if activity is not None:\n                activity_init = activity[frame]\n            else:\n                if hasattr(self[frame], 'activity'):\n                    activity_init = self[frame].activity\n                else:\n                    activity_init = None\n            if transformations is not None:\n                transformation = transformations[frame]\n            else:\n                transformation = None\n            activity_recon = self[frame].osem_reconstruction(iterations=iterations, activity=activity_init,\n                                                             attenuation_projection=attenuation_projection,\n                                                             subset_mode=subset_mode, subset_size=subset_size,\n                                                             transformation=transformation, azimuthal_range=None)\n            self[frame].activity = activity_recon\n            if show_progressbar:\n                progress_bar_slice.set_percentage((frame + 1) * 100.0 / (len(self)))\n            else:\n                print(\"Reconstructing frame %d / %d\" % (frame + 1, len(self)))\n\n    def direct_reconstruction(self, iterations=10, activity=None, attenuation_projection=None, subset_mode=\"random\",\n                              subset_size=64, transformations=None, azimuthal_range=None, gradient_prior_type=None,\n                              gradient_prior_args=()):\n        \"\"\" Scheleton for implementation of direct reconstrucion. Check TODOs for what it's still waiting to be implemented!\n        It's important to keep in mind that PET_Dynamic_Scan is built like a collection of PET_Static_Scan object, so it's\n        of the utmost importance to deal well with this structure when we need to alternate between 1-iteration-osem recon\n        and fitting of the kinetic model for prior computation purpose.\"\"\"\n\n        subsets_generator = SubsetGenerator(self.binning.N_azimuthal, self.binning.N_axial)\n        self.profiler.reset()\n\n        for i in range(iterations):\n            \"\"\"As you can see, the outer for-loop is defined on the direct iterations, while the inner one loops on time frames\n            not calling PET_Static_Scan.osem_reconstruction as a whole, but just one step of PET_Static_Scan.osem_step to be run \n            on the current subset\"\"\"\n            print(\"iteration \", (i + 1), \"/\", iterations)\n\n            # We use the same subset across all the time frames. Check if this makes sense, but it should.\n            subsets_matrix = subsets_generator.new_subset(subset_mode, subset_size, azimuthal_range)\n\n            for frame in range(len(self)):\n                print(\"Frame %d / %d\" % (frame + 1, len(self)))\n\n                if activity is not None:\n                    activity_init = activity[frame]\n                else:\n                    if hasattr(self[frame], 'activity'):\n                        if self[frame].activity is None:\n                            activity_init = self._make_Image3D_activity(\n                                ones(self.activity_shape, dtype=float32, order=\"F\"))\n                        else:\n                            activity_init = self[frame].activity\n                    else:\n                        activity_init = self._make_Image3D_activity(ones(self.activity_shape, dtype=float32, order=\"F\"))\n\n                if self.sensitivity is None:\n                    sensitivity = self.prompts.copy()\n                    sensitivity.data = 0.0 * sensitivity.data + 1\n                    self.set_sensitivity(sensitivity)\n\n                if transformations is not None:\n                    transformation = transformations[frame]\n                else:\n                    transformation = None\n\n                # TODO : introduce OSL prior into osem_step\n                # TODO : pick the current time frame from the fitted volume to use in the OSL prior\n                activity_recon = self[frame].osem_step(activity_init, subsets_matrix, attenuation_projection,\n                                                       transformation, gradient_prior_type=gradient_prior_type,\n                                                       gradient_prior_args=gradient_prior_args)\n                self[frame].activity = activity_recon\n\n                # TODO : here is where you need to fit the volume using kinetic model\n\n    def osem_reconstruction_4D(self, iterations=10, activity=None, subset_mode=\"random\", subset_size=64,\n                               transformations=None, show_progressbar=True, ):\n        if show_progressbar:\n            progress_bar_slice = ProgressBar(title=\"Current iteration ...\")\n            progress_bar_slice.set_percentage(0.0)\n\n        if activity is None:\n            activity = self._make_Image3D_activity(ones(self.activity_shape, dtype=float32, order=\"F\"))\n\n        \"\"\"if self.sensitivity is None:\n            self.set_sensitivity(1.0)\"\"\"\n\n        subsets_generator = SubsetGenerator(self.binning.N_azimuthal, self.binning.N_axial)\n\n        for i in range(iterations):\n            if not show_progressbar:\n                if iterations >= 15:\n                    if i == 1:\n                        print(i, '/', iterations)\n                    elif i == iterations - 1:\n                        print(i, '/', iterations)\n                    elif (int32(i) / 5) * 5 == i:\n                        print(i, '/', iterations)\n                else:\n                    print(i, '/', iterations)\n\n            activity = self.osem_step_4D(activity, subsets_generator, subset_mode, subset_size, transformations)\n            if show_progressbar:\n                progress_bar_slice.set_percentage((i + 1) * 100.0 / iterations)\n        return activity\n\n    def osem_step_4D(self, activity, subsets_generator, subset_mode=\"random\", subset_size=64, transformations=None):\n        epsilon = 1e-08\n        norm = self._make_Image3D_activity(zeros(self.activity_shape, dtype=float32, order=\"F\"))\n        update1 = self._make_Image3D_activity(zeros(self.activity_shape, dtype=float32, order=\"F\"))\n\n        for t in range(len(self)):\n            subsets_matrix = subsets_generator.new_subset(subset_mode, subset_size)\n\n            prompts = self[t].prompts\n            if self[t]._use_compression:\n                prompts = prompts.uncompress_self()\n\n            duration_ms = prompts.get_duration()\n            if duration_ms is None:\n                duration_ms = 1000 * 60 * 60\n            duration = duration_ms / 1000.0\n            alpha = self[t].scale_activity\n\n            # [NOTE]\n            # Compute projections of the attenuation map on the fly; too memory consuming to precompute the\n            # projection for each time frame - precomputing makes PET_Static_Scan more efficient, but in Dynamic, it\n            # requires too much memory in practical applications.\n\n            if self[t].attenuation is not None:\n                attenuation_projection = self[t].project_attenuation(self[t].attenuation)\n                attenuation_projection = attenuation_projection.get_subset(subsets_matrix)\n            else:\n                attenuation_projection = 1.0\n\n            if self[t].sensitivity is not None:\n                if isscalar(self[t].sensitivity):\n                    sens_x_att = self[t].sensitivity * attenuation_projection\n                else:\n                    sens_x_att = self[t].sensitivity.get_subset(subsets_matrix) * attenuation_projection\n            else:\n                sens_x_att = attenuation_projection\n            if isscalar(sens_x_att):\n                sens_x_att = sens_x_att * ones(prompts.data.shape, dtype=float32)\n\n            if self[t].randoms is not None:\n                randoms = self.randoms\n                if self[t]._use_compression:\n                    randoms = randoms.uncompress_self()\n                randoms = (randoms.get_subset(subsets_matrix) + epsilon) / (sens_x_att * alpha * duration + epsilon)\n\n            if self[t].scatter is not None:\n                mscatter = (self.scatter.get_subset(subsets_matrix) + epsilon) / (\n                    attenuation_projection * alpha * duration + epsilon)\n                # Scale scatter: this is used in dynamic and kinetic imaging, when scatter is calculated using the ativity for a time period longer than the current frame:\n                if self[t].scatter.get_duration() is not None:\n                    if self[t].scatter.get_duration() > 1e-6:\n                        mscatter = mscatter * duration / self[t].scatter.get_duration()\n\n            norm += self[t].backproject_activity(sens_x_att * alpha * duration, transformation=transformations[t])\n\n            projection = self[t].project_activity(activity, subsets_matrix=subsets_matrix,\n                                                  transformation=transformations[t])\n\n            if self[t].randoms is not None:\n                if self[t].scatter is not None:\n                    update1 += self[t].backproject_activity(\n                        prompts.get_subset(subsets_matrix) / (projection + randoms + mscatter + epsilon),\n                        transformation=transformations[t])\n                else:\n                    update1 += self[t].backproject_activity(\n                        prompts.get_subset(subsets_matrix) / (projection + randoms + epsilon),\n                        transformation=transformations[t])\n\n            else:\n                if self[t].scatter is not None:\n                    update1 += self[t].backproject_activity(\n                        prompts.get_subset(subsets_matrix) / (projection + mscatter + epsilon),\n                        transformation=transformations[t])\n                else:\n                    update1 += self[t].backproject_activity(prompts.get_subset(subsets_matrix) / (projection + epsilon),\n                                                            transformation=transformations[t])\n\n            activity = (activity / (norm + epsilon)) * update1\n\n        return activity\n\n    ########## SLICING FUNCTIONS TO EXTRACT A SINGLE TIME FRAME FROM A DYNAMIC SERIES \n    ########## OR WHOLE RECONSTRUCTED ACTIVITY AS A 4D ARRAY (USEFUL FOR PRIOR CIOMPUTATION\n    ########## AND KINETIC MODELING)\n\n    def get_activity_as_array(self):\n        activities = []\n        for frame in range(len(self)):\n            activity = self[frame].activity.data\n            activities.append(activity)\n        return asarray(activities)\n\n    def get_2D_slices(self, slices=(62, 63, 64, 65, 66), azimuthal_index=5):\n        N_time_bins = len(self)\n\n        pet = PET_Multi2D_Scan()\n        pet.use_compression(False)\n        pet.set_scanner(self.scanner.__class__)\n        pet.set_number_of_slices(N_time_bins)\n        pet.set_activity_shape((self.activity_shape[0], self.activity_shape[1]))\n        pet.set_activity_size((self.activity_size[0], self.activity_size[1]))\n\n        # extract slice of prompts, scatter, randoms, sensitivity\n        prompts = zeros([pet.binning.N_axial, pet.binning.N_u, N_time_bins + 1], dtype=float32)\n        randoms = zeros([pet.binning.N_axial, pet.binning.N_u, N_time_bins + 1], dtype=float32)\n        scatter = zeros([pet.binning.N_axial, pet.binning.N_u, N_time_bins + 1], dtype=float32)\n        sensitivity = ones([pet.binning.N_axial, pet.binning.N_u, N_time_bins + 1], dtype=float32)\n        attenuation_projection = ones([pet.binning.N_axial, pet.binning.N_u, N_time_bins + 1], dtype=float32)\n        for t in range(N_time_bins):\n            if hasattr(self[t], \"prompts\"):\n                if self[t].prompts is not None:\n                    prompts[:, :, t + 1] = self[t].prompts.to_nd_array()[:, azimuthal_index, :, slices].sum(0).squeeze()\n        for t in range(N_time_bins):\n            if hasattr(self[t], \"randoms\"):\n                if self[t].randoms is not None:\n                    randoms[:, :, t + 1] = self[t].randoms.to_nd_array()[:, azimuthal_index, :, slices].sum(0).squeeze()\n        # FIXME: implement scatter scale in PET_Static_Scan and use it here;\n        # this will reduce memory for scatter by storing scatter projection only once.\n        for t in range(N_time_bins):\n            if hasattr(self[t], \"scatter\"):\n                if self[t].scatter is not None:\n                    scatter[:, :, t + 1] = self[t].scatter.to_nd_array()[:, azimuthal_index, :, slices].sum(0).squeeze()\n        for t in range(N_time_bins):\n            if hasattr(self[t], \"sensitivity\"):\n                if self[t].sensitivity is not None:\n                    sensitivity[:, :, t + 1] = self[t].sensitivity.to_nd_array()[:, azimuthal_index, :, slices].mean(\n                        0).squeeze()\n\n        # project attenuation and extract slice of the projection\n        # FIXME: implement .set_attenuation_projection() in PET_Static_SCAN and use in recon if loaded\n        if hasattr(self, \"attenuation_projection\"):\n            if self.attenuation_projection is not None:\n                att = self.attenuation_projection.to_nd_array()[:, azimuthal_index, :, slices].mean(0).squeeze()\n                for t in range(N_time_bins):\n                    attenuation_projection[:, :, t + 1] = att\n\n        prompts = PET_Projection(pet.binning, prompts)\n        randoms = PET_Projection(pet.binning, randoms)\n        sensitivity = PET_Projection(pet.binning, sensitivity)\n        scatter = PET_Projection(pet.binning, scatter)\n        attenuation_projection = PET_Projection(pet.binning, attenuation_projection)\n\n        pet.set_prompts(prompts)\n        pet.set_scatter(scatter)\n        pet.set_randoms(randoms)\n        pet.set_sensitivity(sensitivity)\n        pet.set_attenuation_projection(attenuation_projection)\n\n        prompts_duration = ones([N_time_bins + 1, ])\n        scatter_duration = ones([N_time_bins + 1, ])\n        for t in range(N_time_bins):\n            prompts_duration[1 + t] = self[t].prompts.get_duration()\n            scatter_duration[1 + t] = self[t].scatter.get_duration()\n        pet.set_prompts_duration(prompts_duration)\n        pet.set_scatter_duration(scatter_duration)\n\n        return pet\n\n    ########## VISUALIZATION AND REPRESENTATION ROUTINES\n\n    def _construct_ilang_model(self):\n        # define the ilang probabilistic model\n        self.ilang_model = PET_Dynamic_Poisson(self)\n        # construct the Directed Acyclical Graph\n        self.ilang_graph = ProbabilisticGraphicalModel(['lambda', 'alpha', 'counts'])\n        # self.ilang_graph.set_nodes_given(['counts','alpha'],True)\n        # self.ilang_graph.add_dependence(self.ilang_model,{'lambda':'lambda','alpha':'alpha','z':'counts'})\n\n    def __repr__(self):\n        \"\"\"Display information about Dynamic_PET_Scan\"\"\"\n        s = \"Dynamic PET acquisition:  \\n\"\n        s = s + \" - N_time_bins:                  %d \\n\" % len(self.time_bins)\n        s = s + \" - Time_start:                   %s \\n\" % millisec_to_min_sec(self.time_bins[0])\n        s = s + \" - Time_end:                     %s \\n\" % millisec_to_min_sec(self.time_bins[-1])\n        s = s + \" - N_counts:                     %d \\n\" % self.static.prompts.get_integral()\n        s = s + \" - N_locations:                  %d \\n\" % self.static.prompts.sparsity.get_N_locations()\n        s = s + \" - compression_ratio:            %d \\n\" % self.static.prompts.get_compression_ratio()\n        #        s = s+\" - dynamic_inflation:            %d \\n\"%self.dynamic_inflation\n        s = s + \" - listmode_loss:                %d \\n\" % self.static.prompts.get_listmode_loss()\n        s = s + \" - Mean time bin duration:       %d [sec] \\n\" % 0  # FIXME\n        if self.scanner is not None:\n            s = s + \" * Scanner: \\n\"\n            s = s + \"     - Name:                     %s \\n\" % self.scanner.model\n            s = s + \"     - Manufacturer:             %s \\n\" % self.scanner.manufacturer\n            s = s + \"     - Version:                  %s \\n\" % self.scanner.version\n        if self.binning is not None:\n            s = s + \" * Binning: \\n\"\n            s = s + \"     - N_axial bins:             %d \\n\" % self.binning.N_axial\n            s = s + \"     - N_azimuthal bins:         %d \\n\" % self.binning.N_azimuthal\n            s = s + \"     - Angles axial step:        %f \\n\" % self.binning.angles_axial\n            s = s + \"     - Angles azimuthal:         %f \\n\" % self.binning.angles_azimuthal\n            s = s + \"     - Size_u:                   %f \\n\" % self.binning.size_u\n            s = s + \"     - Size_v:                   %f \\n\" % self.binning.size_v\n            s = s + \"     - N_u:                      %s \\n\" % self.binning.N_u\n            s = s + \"     - N_v:                      %s \\n\" % self.binning.N_v\n        return s\n\n    def _repr_html_(self):\n        if not has_ipy_table:\n            return \"Please install ipy_table.\"\n        table_data = [['N_time_bins', len(self.time_bins)],\n                      ['Time_start', millisec_to_min_sec(self.time_bins[0])],\n                      ['Time_end', millisec_to_min_sec(self.time_bins[-1])],\n                      ['Duration', millisec_to_min_sec(self.time_bins[-1] - self.time_bins[0])],\n                      ['N_counts', pretty_print_large_number(self.static.prompts.get_integral())],\n                      ['N_locations', pretty_print_large_number(self.static.prompts.sparsity.get_N_locations())],\n                      ['compression_ratio', print_percentage(self.static.prompts.get_compression_ratio())],\n                      #        ['dynamic_inflation',self.dynamic_inflation],\n                      ['listmode_loss', self.static.prompts.get_listmode_loss()], ]\n        if self.scanner:\n            table_data += [['Name', self.scanner.model], ['Manufacturer', self.scanner.manufacturer],\n                           ['Version', self.scanner.version], ]\n        table = ipy_table.make_table(table_data)\n        table = table.apply_theme('basic_left')\n        # table = table.set_column_style(0, color='lightBlue')\n        table = table.set_global_style(float_format=\"%3.3f\")\n        return table._repr_html_()\n\n    ########### UTLITIES\n\n    def __iter__(self):\n        \"\"\"This method makes the object iterable. \"\"\"\n        return iter(self._dynamic)\n\n    def __getitem__(self, i):\n        \"\"\"This method makes the object addressable like a list. \"\"\"\n        return self._dynamic[i]\n\n    def __len__(self):\n        return len(self._dynamic)\n\n\n#########################################################################\n#########\t\t[CLASS] PET_Cyclic_Scan\t\t\t#########\n#########################################################################\n\n\nclass PET_Cyclic_Scan(PET_Dynamic_Scan):\n    \"\"\"PET Cyclic Scan. This is useful for respiratory gated imaging and for cardiac gated imaging (or both).\"\"\"\n\n    def __init__(self):\n        \"\"\"Most attributes and methods are directly inherited from PET_Dynamic_Scan class. This is basically a specialization of PET_Cyclic_Scan to account for specific need of gated acquisitions\"\"\"\n        PET_Dynamic_Scan.__init__(self)\n\n    def import_listmode(self, hdr_filename, time_range_matrix_ms, data_filename=None, display_progress=False):\n        \"\"\"Load cyclic measurement data from a listmode file. \"\"\"\n        print_debug(\"- Loading static PET data from listmode file \" + str(hdr_filename))\n        hdr = Interfile.load(hdr_filename)\n        # Extract information from the listmode header\n\n        # 1) Guess the path of the listmode data file, if not specified or mis-specified;\n        #  1 - see if the specified listmode data file exists\n        if data_filename is not None:\n            data_filename = data_filename.replace(\"/\", os.path.sep).replace(\"\\\\\",\n                                                                            os.path.sep)  # cross platform compatibility\n            if not os.path.exists(data_filename):\n                raise FileNotFound(\"listmode data\", data_filename)\n        # 2 - if the listmode data file is not specified, try with the name (and full path)\n        #      contained in the listmode header\n        data_filename = hdr['name of data file']['value']\n        data_filename = data_filename.replace(\"/\", os.path.sep).replace(\"\\\\\",\n                                                                        os.path.sep)  # cross platform compatibility\n        if not os.path.exists(data_filename):\n            #  3 - if it doesn't exist, look in the same path as the header file for the listmode data\n            #      file with name specified in the listmode header file\n            data_filename = os.path.split(hdr_filename)[0] + os.path.sep + os.path.split(data_filename)[-1]\n            if not os.path.exists(data_filename):\n                #  4 - if it doesn't exist, look in the same path as the header file for the listmode data\n                #      file with same name as the listmode header file, replacing the extension: \".l.hdr -> .l\"\n                if hdr_filename.endswith(\".l.hdr\"):\n                    data_filename = hdr_filename.replace(\".l.hdr\", \".l\")\n                    if not os.path.exists(data_filename):\n                        raise FileNotFound(\"listmode data\", data_filename)\n                # 5 - if it doesn't exist, look in the same path as the header file for the listmode data\n                #      file with same name as the listmode header file, replacing the extension: \".hdr -> .l\"\n                elif hdr_filename.endswith(\".hdr\"):\n                    data_filename = hdr_filename.replace(\".hdr\", \".l\")\n                    if not os.path.exists(data_filename):\n                        raise FileNotFound(\"listmode data\", data_filename)\n\n        # 2) Determine duration of the acquisition\n        n_packets = hdr['total listmode word counts']['value']\n        scan_duration = hdr['image duration']['value'] * 1000  # milliseconds\n\n        # 3) determine scanner parameters\n        n_radial_bins = hdr['number of projections']['value']\n        n_angles = hdr['number of views']['value']\n        n_rings = hdr['number of rings']['value']\n        max_ring_diff = hdr['maximum ring difference']['value']\n        n_sinograms = n_rings + 2 * n_rings * max_ring_diff - max_ring_diff ** 2 - max_ring_diff\n        n_frames = time_range_matrix_ms.shape[0]\n        n_cycles = time_range_matrix_ms.shape[1]\n\n        # 4) Display information\n        print_debug(\" - Number of packets:    %d       \" % n_packets)\n        print_debug(\" - Scan duration:        %d [sec] \" % (scan_duration / 1000.0))\n        print_debug(\" - Listmode data file:   %s       \" % data_filename)\n        print_debug(\" - Listmode header file: %s       \" % hdr_filename)\n        print_debug(\" - n_frames :            %d       \" % n_frames)\n        print_debug(\" - n_cycles :            %d       \" % n_cycles)\n        print_debug(\" - n_radial_bins:        %d       \" % n_radial_bins)\n        print_debug(\" - n_angles:             %d       \" % n_angles)\n        print_debug(\" - n_angles:             %d       \" % n_sinograms)\n\n        if display_progress:\n            progress_bar = ProgressBar()\n            progress_callback = progress_bar.set_percentage\n        else:\n            def progress_callback(value):\n                if value == 1.0:\n                    print(value, \"/\", 100)\n                if (int32(value) / 10) * 10 == value:\n                    print(value, \"/\", 100)\n\n        # Load the listmode data\n        M = self.scanner.michelogram\n        R = self.scanner.listmode.load_listmode_cyclic(data_filename, time_range_matrix_ms, self.binning, n_radial_bins,\n                                                       n_angles, n_sinograms, M.span, M.segments_sizes,\n                                                       M.michelogram_sinogram,\n                                                       M.michelogram_plane, n_packets, progress_callback)\n        progress_callback(100)\n\n        self._dynamic = []\n        for t in range(n_frames):\n            PET_t = PET_Static_Scan()\n            PET_t.use_compression(self._use_compression)\n            PET_t.use_gpu(self._use_gpu)\n            PET_t.set_scanner(self.scanner.__class__)\n            PET_t.set_binning(self.binning)\n            PET_t._load_static_measurement(t)\n            # make list of static scans\n            self._dynamic.append(PET_t)\n            # also make one attribut for each static scan\n            setattr(self, \"frame%d\" % t, self._dynamic[t])\n            # set activity shape and size and attenuation shape and size\n            PET_t.set_activity_size(self.activity_size)\n            PET_t.set_activity_shape(self.activity_shape)\n            PET_t.set_attenuation_size(self.activity_size)\n            PET_t.set_attenuation_shape(self.activity_shape)\n\n        # Make a global PET_Static_Scan object\n        self.static = PET_Static_Scan()\n        self.static.use_compression(self._use_compression)\n        self.static.use_gpu(self._use_gpu)\n        self.static.set_scanner(self.scanner.__class__)\n        self.static.set_binning(self.binning)\n        self.static._load_static_measurement()\n        self.static.set_activity_size(self.activity_size)\n        self.static.set_activity_shape(self.activity_shape)\n        self.static.set_attenuation_size(self.activity_size)\n        self.static.set_attenuation_shape(self.activity_shape)\n\n        # Free structures listmode data\n        self.scanner.listmode.free_memory()\n\n        # Construct ilang model\n        self._construct_ilang_model()\n", "meta": {"hexsha": "2932bbcaf4c6fb5c37e44419c57bca406fcd4681", "size": 156931, "ext": "py", "lang": "Python", "max_stars_repo_path": "occiput_suite/occiput/Reconstruction/PET/PET (1).py", "max_stars_repo_name": "mscipio/occiput-suite", "max_stars_repo_head_hexsha": "9b7dc59ad615d46d811eab965a86ec9efe292a7d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-02-22T13:50:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-16T01:28:22.000Z", "max_issues_repo_path": "occiput_suite/occiput/Reconstruction/PET/PET (1).py", "max_issues_repo_name": "mscipio/occiput-suite", "max_issues_repo_head_hexsha": "9b7dc59ad615d46d811eab965a86ec9efe292a7d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "occiput_suite/occiput/Reconstruction/PET/PET (1).py", "max_forks_repo_name": "mscipio/occiput-suite", "max_forks_repo_head_hexsha": "9b7dc59ad615d46d811eab965a86ec9efe292a7d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-02-22T13:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-14T02:17:32.000Z", "avg_line_length": 50.5251126851, "max_line_length": 228, "alphanum_fraction": 0.5952807285, "include": true, "reason": "from numpy,from scipy", "num_tokens": 32406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.1889909546169766}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Mean filtering as used for simultaneous EEG/fMRI\"\"\"\n\nimport eegpy\nfrom eegpy.misc import FATALERROR\nfrom eegpy.misc import debug\nfrom eegpy.helper import upsample,downsample,find_max_overlap\n#from eegpy.filter.filt_misc import filterRecursively\n#if debug:\n#    import pylab\n\n#################\n# Module-Import #\n#################\n\ntry:\n    import numpy as n\nexcept ImportError:\n    raise FATALERROR('SciPy or NumPy not found!\\nPlease visit www.scipy.org or numeric.scipy.org for more information.')\n\n# Global variables \n_t_before = 50 #Time to reduce triggers by\n\n########################\n# Function definitions #\n########################\n\nclass MeanFilter():\n    \"\"\"Implementation for the filtering by subtracting the mean.\n    Should work with EEG-files and with arrays, first only with arrays.\n    Works in-place!!!\"\"\"\n    \n    _data=None\n    _ts = None\n    _len = None\n    _mean_data = None\n    _filter = None#lambda x:x\n    _corrts = None\n    _t_before = _t_before\n    \n    def __init__(self, x=None, ts=None, len=None, filter=None, t_before=None):\n        if x!=None:\n            self.set_data(x)\n        if t_before != None:\n            self._t_before = t_before\n            #print \"t_before in meanfilt:\"\n        if ts!=None:\n            self.set_timepoints(ts)\n        if len!=None:\n            self.set_length(len)\n        if filter != None:\n            self._filter = filter\n        \n    def get_data(self):\n        return self._data    \n                \n    def set_data(self, x):\n        try:\n            a = x.shape\n        except Exception, e:\n            raise ValueError(\"Only arrays / memmaps can be used as input for MeanFilter\")\n        self._data = x\n    \n    def set_timepoints(self,ts):\n        self._ts = [int(x)-self._t_before for x in ts]\n        self._ts.sort()\n    \n    def get_length(self):\n        return self._len\n    \n    def set_length(self,l):\n        self._len = int(l)\n    \n    def set_timepoints_auto(self,start,end=10e50,step=5500,ch_num=0,width=100):\n        \"\"\"If triggers are not good, one can try to automatically find the timepoints\"\"\"\n        #print \"Setting timepoints automatically\"\n        assert ch_num<self._data.shape[1] and ch_num>=0, \"ch_num is not valid\"\n        ts = []\n        t = int(start)\n        offset=0\n        while t<self._data.shape[0]-step and t<end:\n            if t==int(start):\n                #template = self._data[t-width/2:t+width/2,ch_num]\n                template = self._data[t:t+step,ch_num]\n                ts.append(t)\n            else:\n                #offset = find_max_overlap(template, self._data[t-width/2:t+width/2,ch_num], width/2)\n                offset = find_max_overlap(template, self._data[t:t+step,ch_num], width/2)\n                #print offset\n                ts.append(t+offset)\n            if debug:\n                print ts[-1],\n            t+=step+offset\n        self.set_timepoints(ts)\n        return ts\n                \n            \n    \n    def check_before_filtering(self):\n        if self._data == None:\n            raise RuntimeError(\"No data were set yet.\")\n        if self._ts == None:\n            raise RuntimeError(\"No timepoints were set yet.\")\n        if self._len == None:\n            #Auto calculate _len as the minimal distance between subsequent timepoints\n            self._len = n.diff(n.array(self._ts)).min()\n            if self._len/n.diff(n.array(self._ts)).mean()<0.1:\n                print \"Auto-setting of length might have failed..., self._len = \", self._len\n        #Now all three values needed should be o.k.\n        if debug:\n            print \"self._data.shape:\", self._data.shape\n            print \"self._ts:\", self._ts, n.diff(n.array(self._ts)).mean()\n            print \"self._len:\", self._len\n            \n    def calc_mean(self):\n        #self._corrts = n.zeros((len(self._ts)),\"i\")\n        mean_shape = []\n        mean_shape.append(self._len)\n        for i in range(1,len(self._data.shape)):\n            mean_shape.append(self._data.shape[i])\n        #print \"mean_shape = \", mean_shape\n        #print \"Sollte sein: \",self._data[self._ts[0]:self._ts[0]+self._len,...].shape\n        self._mean_data = n.zeros(mean_shape,\"d\")\n        #print self._mean_data.shape, self._data[self._ts[0]:self._ts[0]+self._len,...].shape\n        for i, t in enumerate(self._ts): #First walk-through, calculating average\n            #self._mean_data += self._filter(self._data[t:t+self._len,...])\n            try:\n                d = self._data[t:t+self._len,...]\n                #d_up = upsample(d)\n                self._mean_data += d\n                #if i==0:\n                    #self._mean_data += d#_up\n                #else:\n                    #self._corrts[i] = find_max_overlap(self._mean_data[:,10],d_up[:,10])\n                    #if self._corrts[i]<0:\n                    #    self._mean_data[:i,...] += d_up[-i:,...]\n                    #elif self._corrts[i]==0:\n                    #    self._mean_data += d_up\n                    #else:\n                    #    self._mean_data[i:,...] += d_up[:-i,...]\n                #print \"maxOverlap:\", self._corrts[i]\n                #pylab.clf()\n                #pylab.ioff()\n                #for i in range(d.shape[1]):\n                #    pylab.subplot(8,d.shape[1]/8,i+1)\n                #    pylab.plot(d[:,i])\n                #pylab.show()\n            except ValueError,e:\n                print self._mean_data.shape, self._data[t:t+self._len,...].shape#, d_up.shape\n                print \"Shape missmatch occured. Seems like the last timepoint isn't completely recorded in the eeg and is therefore ignored for template-creation.\"\n                if debug:\n                     print e\n        self._mean_data /= len(self._ts)\n        #self._mean_data = downsample(self._mean_data)\n        #if debug:\n            #pylab.clf()\n            #pylab.ioff()\n            #for i in range(self._mean_data.shape[1]):\n            #    pylab.subplot(8,self._mean_data.shape[1]/8,i+1)\n            #    pylab.plot(self._mean_data[:,i])\n            #pylab.show()\n                \n    def subtract_mean(self, n_ma=None):\n        \"\"\"Subtract the mean artifact from all artifact occurences\n        n_ma: Number of nearby artifacts to include in average. \n          If None (default), do global subtraction\n        \"\"\"\n        if n_ma==None:\n            assert self._mean_data != None, \"Before subtracting, first calulate the mean!\"\n            for i,t in enumerate(self._ts): #Second walk: Substracting mean\n                try:\n                    #self._data[t:t+self._len,...] -= downsample(self._mean_data,start=self._corrts[i])\n                    self._data[t:t+self._len,...] -= self._mean_data\n                except ValueError,e:\n                    print \"Shape missmatch occured during writing.\", t\n        else:\n            n_ma = int(n_ma)\n            assert n_ma>0 and n_ma<len(self._ts), \"Wrong value for n_ma; need 0<n_ma<=len(timepoints)\"\n            for i,t in enumerate(self._ts): #Second walk: Substracting mean\n                try:\n                    i1 = i-n_ma/2 #Startindex for mean\n                    i2 = i+n_ma/2 #Endindex for mean\n                    #Correct these indices\n                    if i1<0:\n                        i1=0\n                        i2 = n_ma\n                    elif i2>len(self._ts):\n                        i1 = len(self._ts)-n_ma\n                        i2 = len(self._ts)\n                    self._data[t:t+self._len,...] -= self._mean_data\n                except ValueError,e:\n                    print \"Shape missmatch occured during writing.\", t\n        return self._data\n    \n    def frequency_filter(self):\n        \"\"\"Applies the filter that is given to the constructor using the keyword filter.\n        If no filter is given, pass.\n        \"\"\"\n        #TODO: Change behaviour. Filter each channel as a whole and use lowpass by default.\n        if self._filter == None:\n            pass\n        else:\n            for i in range(0,self._data.shape[0],10000):\n                try:\n                    self._data[i:i+10000,:] = self._filter(self._data[i:i+10000,:])\n                except Exception, e:\n                    if debug:\n                        print \"Error in MeanFilter.frequency_filter:\", e \n        \n    \n    def filter(self):\n        \"\"\"Do the filtering\"\"\"\n        self.check_before_filtering()\n        self.calc_mean()\n        self.subtract_mean()\n        #self.frequency_filter()\n        \n    data = property(get_data,set_data)\n    length = property(get_length,set_length)\n            \n\n#########################\n# Convenience-functions #\n#########################        \n_meanfilter = None #Global Instance of MeanFilter for use with methods below\n\ndef filter(x,ts,len=None,filter=None,t_before=None):\n    \"\"\"Do the PCA, with array x.\"\"\"\n    global _meanfilter\n    _meanfilter = MeanFilter(x,ts,len,filter,t_before)\n    return _meanfilter.filter()\n\n\n        \n#######################################\n# If called directly, do some example #\n#######################################    \nif __name__=='__main__':\n\n    #TODO: Make some example use\n    print \"Example code not implemented yet.\"\n    ", "meta": {"hexsha": "0eabe456529009335f1ec774d571bb3bb6bb8e10", "size": 9176, "ext": "py", "lang": "Python", "max_stars_repo_path": "eegpy/filter/meanfilt.py", "max_stars_repo_name": "thorstenkranz/eegpy", "max_stars_repo_head_hexsha": "0f9461456999874abbb774896ca832eb27740a9d", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-05-12T10:42:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-20T02:08:03.000Z", "max_issues_repo_path": "eegpy/filter/meanfilt.py", "max_issues_repo_name": "thorstenkranz/eegpy", "max_issues_repo_head_hexsha": "0f9461456999874abbb774896ca832eb27740a9d", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-11-19T11:36:30.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-21T05:00:09.000Z", "max_forks_repo_path": "eegpy/filter/meanfilt.py", "max_forks_repo_name": "thorstenkranz/eegpy", "max_forks_repo_head_hexsha": "0f9461456999874abbb774896ca832eb27740a9d", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-09-21T22:41:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-28T13:55:19.000Z", "avg_line_length": 37.7613168724, "max_line_length": 163, "alphanum_fraction": 0.5361813426, "include": true, "reason": "import numpy", "num_tokens": 2132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.18899095098846286}}
{"text": "import argparse\nimport base64\nimport json\nimport logging\nimport os\nimport re\nimport subprocess\nimport warnings\nimport zlib\nfrom collections import Counter\nfrom functools import lru_cache\nfrom math import ceil\n\nfrom ScientificTopics.download import default_model_name, _get_default_model\n\ntry:\n    import matplotlib.pyplot as plt\nexcept ImportError:\n    warnings.warn(\"Unable to find matplotlib, plotting is disabled\")\n    plt = None\nimport numpy\nimport pyximport\n\nfrom ScientificTopics.sentence_segmentation import Tokenizer\n\npyximport.install(\n    setup_args={'include_dirs': numpy.get_include()})\nfrom ScientificTopics import lda_infer\n\n\nclass LDAInfer(object):\n    \"\"\"\n    LDAInfer is a class that reads LDA models and infer topics for new documents.\n    To use LDAInfer, four model files are required:\n\n    1. Punkt parameter file, for segmenting paragraphs into sentences.\n    2. SentencePieceModel file, for tokenizing sentences.\n    3. Stopwords file.\n    4. LDA result directory, for collecting LDA doc-topic/topic-word tables.\n\n    Two methods, tokenize_sentences() and tokenize_paragraph() are used to\n    tokenize text into tokens and convert into vocabulary ids.\n\n    Two methods, infer_topic_fast() and infer_topic() are used to infer topics\n    for list of token ids representing a document.\n    \"\"\"\n\n    def __init__(self, lda_result_dir,\n                 punkt_model, stopwords, spm_model,\n                 beta=0.01, alpha=0.1, num_vocab=None):\n        \"\"\"\n        Initialize a LDAInfer class to infer topics for new documents.\n\n        :param lda_result_dir: Directory containing tables of a LDA model.\n        :param punkt_model: Filename of Punkt model.\n        :param stopwords: Filename of stopwords list.\n        :param spm_model: Filename of SentencePiece model.\n        :param beta: Beta of LDA model.\n        :param alpha: Alpha of LDA model.\n        :param num_vocab: Number of vocabularies.\n        \"\"\"\n        self.lda_result_dir = lda_result_dir\n        self.beta = beta\n        self.alpha = alpha\n        self.num_vocab = num_vocab\n        self._ntopics = None\n\n        if self.num_vocab is not None:\n            self._betasum = self.beta * self.num_vocab\n\n        logging.info(\"Loading tokenizer...\")\n        self.tokenizer = Tokenizer(punkt_model, spm_model)\n        self.spm_tokenizer = self.tokenizer.spm_tokenizer\n        logging.info(\"Loading stopwords...\")\n        with open(stopwords, encoding='utf8') as f:\n            self.stopwords = [x.strip().split()[0] for x in f if x.strip()]\n        self.stopwords = set(self.spm_tokenizer.PieceToId(x) for x in self.stopwords)\n\n        self.n_t, self.n_tw = self._read_model_parameters()\n\n    @property\n    def ntopics(self):\n        \"\"\"\n        Return number of topics.\n        \"\"\"\n        return self._ntopics\n\n    @lru_cache(maxsize=1000)\n    def _get_p(self, word_id):\n        p_array = []\n        for i in range(self.ntopics):\n            p = self.n_tw[i, word_id] * 1. * self.beta / (self.n_t[i] + self.beta * self.num_vocab)\n            p_array.append(p)\n\n        p_array = numpy.asarray(p_array)\n\n        summation = numpy.sum(p_array)\n        if summation == 0:\n            return numpy.ones(shape=(self.ntopics,)) / self.ntopics\n        else:\n            return p_array / numpy.sum(p_array)\n\n    def _propose_word(self, word_id, size=None):\n        return numpy.random.choice(self.ntopics, p=self._get_p(word_id), size=size)\n\n    def _propose_doc(self, total_tokens, size=None):\n        \"\"\"-Int for doc_topics[-i]\"\"\"\n        rand_numbers = numpy.random.rand(*size) * (total_tokens + self.alpha * self.ntopics)\n        proposal = numpy.empty(shape=size, dtype=numpy.int)\n\n        cond = rand_numbers < total_tokens\n\n        take_doc_topics = numpy.where(cond)\n        proposal[take_doc_topics] = -(rand_numbers[take_doc_topics]).astype(numpy.int)\n\n        take_random_topics = numpy.where(numpy.logical_not(cond))\n        proposal[take_random_topics] = numpy.random.choice(self.ntopics, size=len(take_random_topics[0]))\n        return proposal\n\n    def tokenize_sentences(self, text, filter_stopwords=True):\n        \"\"\"\n        Tokenize words in a paragraph, and return a list of lists, each list representing\n        a sentence. All words are converted to id in vocabulary.\n\n        :param text: Paragraph to tokenize\n        :param filter_stopwords: Switch to filter out all stopwords\n        :return: a list of lists of token ids.\n        \"\"\"\n        token_ids_all = self.tokenizer.tokenize_ids(text)\n        valid_tokens = []\n        for sentence in token_ids_all:\n            sentence = [x for x in sentence if x not in self.stopwords or not filter_stopwords]\n            valid_tokens.append(sentence)\n        return valid_tokens\n\n    def tokenize_paragraph(self, text, filter_stopwords=True):\n        \"\"\"\n        Tokenize words in a paragraph, and return a list of token ids.\n        See also @tokenize_sentences()\n\n        :param text: Paragraph to tokenize\n        :param filter_stopwords: Switch to filter out all stopwords\n        :return: a list of token ids.\n        \"\"\"\n        token_ids_all = self.tokenize_sentences(text, filter_stopwords)\n        # Collect\n        token_ids_all = sum(token_ids_all, [])\n\n        return token_ids_all\n\n    def generate_html(self, original_tokens, doc_topics, monte_carlo_states, doc_topics_states):\n        html_template_filename = os.path.join(\n            os.path.dirname(os.path.realpath(__file__)),\n            'plot.template.html'\n        )\n        with open(html_template_filename) as f:\n            html_template = f.read()\n\n        top_words = [x[1] for x in sorted(self.get_top_words().items(), key=lambda x: x[0])]\n\n        data_base64 = base64.b64encode(zlib.compress(json.dumps({\n            'top_words': top_words,\n            'states': monte_carlo_states.tolist(),\n            'n_tw': doc_topics_states.tolist(),\n            'tokens': [(x not in self.stopwords, self.spm_tokenizer.IdToPiece(x)) for x in original_tokens]\n        }).encode())).decode()\n        return html_template.replace('{{data_base64}}', data_base64)\n\n    def infer_topic_fast(self, doc, iterations=1000, mh_steps=2, plot_mc_states=False):\n        \"\"\"\n        Infer topics for a new document. This method uses Cython implementation so it is\n        relatively faster than infer_topic().\n\n        Upon finishing, three objects will be returned:\n        1. Topic assignments for each word.\n        2. Topic assignments of each iteration of the entire Monte-Carlo process.\n        3. Number of topic assignments of each iteration.\n\n        :param doc: List of tokens representing a document.\n        :param iterations: Number of Monte-Carlo iterations.\n        :param mh_steps: Number of Metropolis-Hastings steps for each iteration.\n        :param plot_mc_states: Whether to plot the MC states of all iterations.\n        :return:\n        \"\"\"\n        doc_topics, monte_carlo_states, doc_topics_states, doc_probabilities = lda_infer.infer_topic(\n            numpy.asarray(doc, dtype=numpy.uint32),\n            self.n_t, self.n_tw,\n            self.alpha, self.beta, iterations, mh_steps\n        )\n\n        if plot_mc_states:\n            for i in range(self.ntopics):\n                t_arr = doc_topics_states[:, i]\n                if numpy.sum(t_arr) > iterations:\n                    plt.plot(list(range(iterations)), t_arr, linewidth=1, label='Topic %d' % i)\n            plt.legend()\n            plt.show()\n\n        return doc_topics, monte_carlo_states, doc_topics_states, doc_probabilities\n\n    def infer_topic(self, doc, iterations=1000, mh_steps=2, plot_mc_states=False):\n        \"\"\"\n        Infer topics for a new document. This method uses Cython implementation so it is\n        relatively faster than infer_topic().\n\n        Upon finishing, three objects will be returned:\n        1. Topic assignments for each word.\n        2. Topic assignments of each iteration of the entire Monte-Carlo process.\n        3. Number of topic assignments of each iteration.\n\n        :param doc: List of tokens representing a document.\n        :param iterations: Number of Monte-Carlo iterations.\n        :param mh_steps: Number of Metropolis-Hastings steps for each iteration.\n        :param plot_mc_states: Whether to plot the MC states of all iterations.\n        :return:\n        \"\"\"\n        doc_topics = numpy.random.choice(self.ntopics, size=(len(doc),))\n        topic_counter = numpy.zeros((self.ntopics,), dtype=numpy.int)\n        for t, c in Counter(doc_topics).items():\n            topic_counter[t] += c\n\n        monte_carlo_states = numpy.empty((iterations, len(doc)), dtype=numpy.int)\n        doc_topics_states = numpy.empty((iterations, self.ntopics), dtype=numpy.int)\n\n        word_proposals = [self._propose_word(x, size=(iterations, mh_steps)) for x in doc]\n        doc_proposals = [self._propose_doc(len(doc), size=(iterations, mh_steps)) for _ in doc]\n        random_numbers = numpy.random.rand(iterations, len(doc), mh_steps, 2)\n\n        for i in range(iterations):\n            monte_carlo_states[i, :] = doc_topics\n            doc_topics_states[i, :] = topic_counter\n\n            for j, word_id in enumerate(doc):\n                original_topic = doc_topics[j]\n\n                topic = original_topic\n                for k in range(mh_steps):\n                    new_topic = word_proposals[j][i, k]\n\n                    if new_topic != topic:\n                        # Simplified version of cxx::LightDocSampler::Sample()\n                        n_td_alpha = topic_counter[new_topic] + self.alpha\n                        n_sd_alpha = topic_counter[topic] + self.alpha\n\n                        if topic == original_topic:\n                            n_sd_alpha -= 1\n                        if new_topic == original_topic:\n                            n_td_alpha -= 1\n\n                        pi = n_td_alpha / n_sd_alpha\n\n                        if random_numbers[i, j, k, 0] < pi:\n                            topic = new_topic\n\n                    doc_proposal = doc_proposals[j][i, k]\n                    new_topic = doc_topics[-doc_proposal] if doc_proposal < 0 else doc_proposal\n\n                    if new_topic != topic:\n                        if new_topic != original_topic:\n                            n_tw_beta = self.n_tw[new_topic, word_id] + self.beta\n                            n_t_beta_sum = self.n_t[new_topic] + self._betasum\n                            pi_t = n_tw_beta / n_t_beta_sum\n                        else:\n                            n_td_alpha = topic_counter[new_topic] + self.alpha - 1\n                            n_tw_beta = self.n_tw[new_topic, word_id] + self.beta\n                            n_t_beta_sum = self.n_t[new_topic] + self._betasum\n                            proposal_t = topic_counter[new_topic] + self.alpha\n                            pi_t = (n_td_alpha * n_tw_beta) / (n_t_beta_sum * proposal_t)\n\n                        if topic != original_topic:\n                            n_sw_beta = self.n_tw[topic, word_id] + self.beta\n                            n_s_beta_sum = self.n_t[topic] + self._betasum\n                            pi_s = n_sw_beta / n_s_beta_sum\n                        else:\n                            n_sd_alpha = topic_counter[topic] + self.alpha\n                            n_sw_beta = self.n_tw[topic, word_id] + self.beta\n                            n_s_beta_sum = self.n_t[topic] + self._betasum\n                            proposal_s = topic_counter[topic] + self.alpha\n                            pi_s = (n_sd_alpha * n_sw_beta) / (n_s_beta_sum * proposal_s)\n\n                        pi = pi_t / pi_s\n\n                        if random_numbers[i, j, k, 1] < pi:\n                            topic = new_topic\n\n                if topic != original_topic:\n                    topic_counter[original_topic] -= 1\n                    topic_counter[topic] += 1\n\n                doc_topics[j] = topic\n\n        if plot_mc_states:\n            for i in range(self.ntopics):\n                t_arr = doc_topics_states[:, i]\n                if numpy.sum(t_arr) > iterations:\n                    plt.plot(list(range(iterations)), t_arr, linewidth=1, label='Topic %d' % i)\n            plt.legend()\n            plt.show()\n\n        return doc_topics, monte_carlo_states, doc_topics_states\n\n    def get_top_words(self):\n        top_words = {}\n        for topic in range(len(self.n_tw)):\n            sort_index = self.n_tw[topic].argsort()[:-21:-1]\n            top_count = self.n_tw[topic][sort_index]\n            string_builder = []\n            for word_id, count in zip(sort_index, top_count):\n                piece_id = self.spm_tokenizer.IdToPiece(int(word_id)) if self.spm_tokenizer is not None else str(\n                    word_id)\n                string_builder.append(piece_id)\n            top_words[topic] = string_builder\n        return top_words\n\n    def find_possible_stopwords(self):\n        stopwords = Counter()\n        for topic in range(len(self.n_tw)):\n            total_counts = sum(self.n_tw[topic])\n            sort_index = self.n_tw[topic].argsort()[:-21:-1]\n            top_count = self.n_tw[topic][sort_index]\n            string_builder = []\n            for word_id, count in zip(sort_index, top_count):\n                piece_id = self.spm_tokenizer.IdToPiece(int(word_id)) if self.spm_tokenizer is not None else str(\n                    word_id)\n                stopwords[piece_id] += 1\n                string_builder.append('%s (%.4f)' % (piece_id, count / total_counts))\n            logging.info('Topic %d: %s', topic, ', '.join(string_builder))\n\n        for word, count in sorted(stopwords.items(), key=lambda x: x[1], reverse=True):\n            if count > self.ntopics / 10:\n                logging.info('Possible stopword: %s in %d topics', word, count)\n\n    def _read_model_parameters_try_cache(self):\n        \"\"\"\n        Read cached LDA model tables n_tw and n_t.\n        \"\"\"\n        cache_filename = os.path.join(self.lda_result_dir, 'cached_parameters.npz')\n\n        if not os.path.exists(cache_filename):\n            raise FileNotFoundError()\n\n        cache_timestamp = os.path.getmtime(cache_filename)\n        model_parameters = [x for x in os.listdir(self.lda_result_dir) if re.match(r'server_\\d_table_\\d.model', x)]\n        total_nodes = max(int(x.split('_')[1]) for x in model_parameters)\n        for i in range(total_nodes):\n            f_timestamp = os.path.getmtime(os.path.join(self.lda_result_dir, 'server_%d_table_1.model' % i))\n            if f_timestamp > cache_timestamp:\n                raise FileNotFoundError()\n            f_timestamp = os.path.getmtime(os.path.join(self.lda_result_dir, 'server_%d_table_0.model' % i))\n            if f_timestamp > cache_timestamp:\n                raise FileNotFoundError()\n\n        logging.info('Found cached parameters: %s, loading cache...', cache_filename)\n        data = numpy.load(cache_filename)\n        n_t = data['n_t']\n        n_tw = data['n_tw']\n        self._ntopics = n_t.shape[0]\n\n        return n_t, n_tw\n\n    def _read_model_parameters(self):\n        \"\"\"\n        Read LDA model tables n_tw and n_t.\n        \"\"\"\n        try:\n            return self._read_model_parameters_try_cache()\n        except FileNotFoundError:\n            pass\n\n        model_parameters = [x for x in os.listdir(self.lda_result_dir) if re.match(r'server_\\d_table_\\d.model', x)]\n        total_nodes = max(int(x.split('_')[1]) for x in model_parameters)\n\n        # Alphas\n        logging.info('Reading word count by topic...')\n        n_t = {}\n        for i in range(total_nodes):\n            with open(os.path.join(self.lda_result_dir, 'server_%d_table_1.model' % i)) as f:\n                line = f.readline()\n                if not line:\n                    continue\n                for topic, topic_count in re.findall(r'(\\d+):(\\d+)', line):\n                    n_t[int(topic)] = int(topic_count)\n                logging.info('Loaded topic summary table %s', 'server_%d_table_1.model' % i)\n\n        self._ntopics = max(n_t.keys()) + 1\n        logging.info('Found %d topics', self.ntopics)\n        n_t = numpy.asarray([x[1] for x in sorted(n_t.items())], dtype=numpy.uint32)\n        assert len(n_t) == self.ntopics\n        logging.debug('Word count by topics: %r', n_t)\n\n        # Word beta\n        logging.info('Reading word count by topic and word id...')\n        n_tw = numpy.zeros((self.ntopics, self.num_vocab), dtype=numpy.uint32)\n        for i in range(total_nodes):\n            with open(os.path.join(self.lda_result_dir, 'server_%d_table_0.model' % i)) as f:\n                for line in f:\n                    if not line.strip():\n                        break\n\n                    matches = re.findall(r'(\\d+)(?=\\s)|(\\d+):(\\d+)', line)\n                    word_id = int(matches[0][0])\n                    for _, topic, topic_count in matches[1:]:\n                        n_tw[int(topic), word_id] = int(topic_count)\n\n                logging.info('Loaded word topic table %s', 'server_%d_table_0.model' % i)\n\n        numpy.savez(\n            os.path.join(self.lda_result_dir, 'cached_parameters.npz'),\n            n_t=n_t,\n            n_tw=n_tw\n        )\n\n        return n_t, n_tw\n\n\ndef load_model(model_name=default_model_name, topic_model=0):\n    params = _get_default_model(model_name, topic_model)\n    return LDAInfer(**params)\n\n\ndef gen_blocks(input_file, nodes, block_size, dump_binary):\n    logging.info('Scanning input file...')\n\n    total_docs = 0\n    total_tokens = 0\n    with open(input_file + '.libsvm') as f:\n        for line in f:\n            tokens = sum([int(x.split(':')[1]) for x in line.split('\\t')[1].split(' ')])\n            total_tokens += tokens\n            total_docs += 1\n\n    total_block_size = (total_tokens * 2 + total_docs + 2) * 4 / 1024 / 1024\n    logging.info('In total %d documents, %d tokens, estimated total block size: %.2f MB',\n                 total_docs, total_tokens, total_block_size)\n\n    num_blocks = int(ceil(total_block_size / nodes / block_size))\n    tokens_per_block = int(ceil(total_tokens / nodes / num_blocks))\n\n    logging.info('Scheduling %d nodes with %d blocks, each block has %d tokens',\n                 nodes, num_blocks, tokens_per_block)\n\n    dump_binary_results = []\n\n    with open(input_file + '.libsvm') as f:\n        for node in range(nodes):\n            for block in range(num_blocks):\n                tokens_this_block = 0\n                docs_this_block = 0\n\n                block_input = input_file + '.libsvm.%d.%d' % (node, block)\n                with open(block_input, 'w') as f_output:\n                    while tokens_this_block < tokens_per_block:\n                        try:\n                            line = f.readline()\n                            if not line.strip():\n                                raise EOFError('empty of file reached')\n                        except (EOFError, IOError):\n                            break\n\n                        tokens = sum([int(x.split(':')[1]) for x in line.split('\\t')[1].split(' ')])\n                        tokens_this_block += tokens\n                        f_output.write(line)\n                        docs_this_block += 1\n\n                    logging.info('Node %d, block %d has %d docs and %d tokens',\n                                 node, block, docs_this_block, tokens_this_block)\n\n                    if dump_binary is not None:\n                        cmd = [\n                            dump_binary,\n                            block_input, input_file + '.vocab',\n                            os.path.realpath(os.path.dirname(block_input)), str(node), str(block)\n                        ]\n                        logging.info('Executing dump_binary: %r', cmd)\n                        dump_binary_results.append(\n                            subprocess.Popen(cmd))\n\n    logging.info('Waiting for dump_binary to finish.')\n    for i in dump_binary_results:\n        i.wait()\n\n\ndef analyze_results(input_dir, spm_model):\n    inferer = LDAInfer(input_dir, spm_model=spm_model)\n    inferer.find_possible_stopwords()\n\n\ndef infer(input_dir,\n          infer_input, infer_output,\n          params, spm_model, stopwords,\n          alpha, beta, num_vocab, generate_html):\n    logging.info('Loading model...')\n    inferer = LDAInfer(input_dir, punkt_model=params, spm_model=spm_model, stopwords=stopwords,\n                       beta=beta, alpha=alpha, num_vocab=num_vocab)\n\n    # top_words = [x[1] for x in sorted(inferer.get_top_words().items(), key=lambda x: x[0])]\n    # inferer.find_possible_stopwords()\n\n    with open(infer_input, encoding='utf8') as input_file, open(infer_output, 'w') as output_file:\n        logging.info('Starting to infer topics on new documents.')\n        for i, line in enumerate(input_file):\n            if not line.strip():\n                logging.warning('Found an empty line at line %d', i)\n                continue\n\n            logging.info('Tokenizing paragraph.')\n            token_ids_all = inferer.tokenize_paragraph(line, filter_stopwords=False)\n            token_ids_stop = inferer.tokenize_paragraph(line, filter_stopwords=True)\n\n            logging.info('Inferring paragraph.')\n            topics, mc_states, n_tw_states, _ = inferer.infer_topic_fast(token_ids_stop)\n\n            if generate_html:\n                with open('plot.%d.html' % i, 'w', encoding='utf8') as f:\n                    f.write(inferer.generate_html(token_ids_all, topics, mc_states, n_tw_states))\n\n            topic_count = Counter(topics)\n            builder = []\n            for topic in sorted(topic_count):\n                builder.append('%d:%d' % (topic, topic_count[topic]))\n            output_file.write(' '.join(builder))\n            output_file.write('\\n')\n            logging.info('Inferred %d tokens: %s',\n                         len(token_ids_stop), ' '.join('%d:%d' % x for x in Counter(token_ids_stop).items()))\n\n\ndef main():\n    parser = argparse.ArgumentParser(description='LDA tools for sentence segmenter and tokenizer.')\n    parser.add_argument('--verbose', action='store_true', default=False, help='More debugging logging.')\n\n    subparsers = parser.add_subparsers(help='Action to execute.', dest='action')\n\n    download_paragraph = subparsers.add_parser(\"gen-blocks\", help='Generate blocks for LDA use.')\n    download_paragraph.add_argument('--input', action='store', type=str, required=True,\n                                    help='Input corpus, for example corpus.lightlda, '\n                                         'must has *.lightlda.libsvm and *.lightlda.vocab.')\n    download_paragraph.add_argument('--nodes', action='store', type=int, required=True,\n                                    help='How many nodes to use.')\n    download_paragraph.add_argument('--block-size', action='store', type=int, default=500,\n                                    help='The average block size in MB. See lightlda/dump_binary.cpp for block format.')\n    download_paragraph.add_argument('--dump-binary', action='store', type=str, default=None,\n                                    help='If provided the executive path for dump-binary, I will help you execute it.')\n\n    analyze_arguments = subparsers.add_parser(\"analyze\", help='Analyze LDA result.')\n    analyze_arguments.add_argument('--lda-result-dir', action='store', type=str, required=True,\n                                   help='LDA result dir')\n    analyze_arguments.add_argument('--spm', action='store', type=str, required=True,\n                                   help='SPM model file')\n\n    infer_arguments = subparsers.add_parser(\"infer\", help='Infer LDA topics.')\n    default_model = {}\n    try:\n        default_model = _get_default_model()\n    except FileNotFoundError:\n        pass\n    infer_arguments.add_argument('--lda-result-dir', action='store', type=str,\n                                 default=default_model['lda_result_dir'],\n                                 help='LDA result dir')\n    infer_arguments.add_argument('--input', action='store', type=str, required=True,\n                                 help='Paragraphs to infer')\n    infer_arguments.add_argument('--output', action='store', type=str, required=True,\n                                 help='Inference output')\n    infer_arguments.add_argument('--model-dir', action='store', type=str, default=None,\n                                 help='Directory of the model that contains a config.json')\n    infer_arguments.add_argument('--params', action='store', type=str,\n                                 default=default_model['punkt_model'],\n                                 help='Punkt parameters')\n    infer_arguments.add_argument('--spm', action='store', type=str,\n                                 default=default_model['spm_model'],\n                                 help='SPM model file')\n    infer_arguments.add_argument('--stopwords', action='store', type=str,\n                                 default=default_model['stopwords'],\n                                 help='List of stopwords')\n    infer_arguments.add_argument('--num-vocab', action='store', type=int,\n                                 default=default_model['num_vocab'],\n                                 help='Number of vocabulary')\n    infer_arguments.add_argument('--alpha', action='store', type=float,\n                                 default=default_model['alpha'],\n                                 help='Topics prior')\n    infer_arguments.add_argument('--beta', action='store', type=float,\n                                 default=default_model['beta'],\n                                 help='Words prior')\n    infer_arguments.add_argument('--generate-html', action='store_true', default=False,\n                                 help='Generate HTML visualizations')\n\n    args = parser.parse_args()\n\n    if args.verbose:\n        logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',\n                            level=logging.DEBUG)\n    else:\n        logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',\n                            level=logging.INFO)\n\n    if args.action == 'gen-blocks':\n        gen_blocks(args.input, args.nodes, args.block_size, args.dump_binary)\n    elif args.action == 'analyze':\n        analyze_results(args.lda_result_dir, args.spm)\n    elif args.action == 'infer':\n        if args.model_dir is not None:\n            d = os.path.realpath(args.model_dir)\n            with open(os.path.join(d, 'config.json')) as f:\n                config = json.load(f)\n                kwargs = {\n                    'input_dir': d,\n                    'params': os.path.join(d, config['params']),\n                    'spm_model': os.path.join(d, config['spm']),\n                    'stopwords': os.path.join(d, config['stopwords']),\n                    'alpha': config['alpha'],\n                    'beta': config['beta'],\n                    'num_vocab': config['num_vocab'],\n                }\n        else:\n            kwargs = {\n                'input_dir': args.lda_result_dir,\n                'params': args.params,\n                'spm_model': args.spm,\n                'stopwords': args.stopwords,\n                'alpha': args.alpha,\n                'beta': args.beta,\n                'num_vocab': args.num_vocab,\n            }\n        input_dir = kwargs.pop('input_dir')\n        infer(input_dir,\n              args.input, args.output,\n              generate_html=args.generate_html,\n              **kwargs)\n    else:\n        parser.print_usage()\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "9c4f21e76b1c4ad778f159b01713b5c81990250c", "size": 27447, "ext": "py", "lang": "Python", "max_stars_repo_path": "ScientificTopics/lda_tools.py", "max_stars_repo_name": "hhaoyan/ScientificTopics", "max_stars_repo_head_hexsha": "dbbae98e90e39ff205999fbefafb1b097fa9b490", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-09-25T19:49:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-10T20:50:05.000Z", "max_issues_repo_path": "ScientificTopics/lda_tools.py", "max_issues_repo_name": "hhaoyan/ScientificTopics", "max_issues_repo_head_hexsha": "dbbae98e90e39ff205999fbefafb1b097fa9b490", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ScientificTopics/lda_tools.py", "max_forks_repo_name": "hhaoyan/ScientificTopics", "max_forks_repo_head_hexsha": "dbbae98e90e39ff205999fbefafb1b097fa9b490", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.2917981073, "max_line_length": 120, "alphanum_fraction": 0.5837067803, "include": true, "reason": "import numpy", "num_tokens": 5882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.1889281777798115}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n.. wikisection:: overview\n    :title: (6) Alignment-free local similarity detection with Word-Blot\n\n    The :mod:`biseqt.blot` module implements the WordBlot algorithm.\n\n    >>> from biseqt.blot import WordBlot\n    >>> from biseqt.sequence import Sequence, Alphabet\n    >>> from biseqt.stochastics import rand_seq, MutationProcess\n    >>> A = Alphabet('ACGT')\n    >>> S = rand_seq(A, 100)\n    >>> M = MutationProcess(A, go_prob=.1, ge_prob=.1, subst_probs=.2)\n    >>> T, _ = M.mutate(S)\n    >>> WB = WordBlot(S, T, wordlen=5, alphabet=A, g_max=.5, \\\n                            sensitivity=.99)\n    >>> list(WB.similar_segments(50, .7))\n    [(((-28, 7), (0, 99)), 1.1988215486845972, 0.7630903108462143)]\n    >>>\n\"\"\"\nimport sys\nimport warnings\nimport numpy as np\nimport logging\nfrom itertools import groupby, product\nfrom scipy.special import erfcinv\nfrom scipy.spatial import cKDTree\nfrom .seeds import SeedIndex, SeedIndexMultiple\nfrom .kmers import as_kmer_seq\nfrom .util import Logger\n\n\n# so we can catch numpy warnings\nwarnings.filterwarnings('error')\n\n\n# A band (i-r, i+r) is considered of interest if xs[i] >threshold. This\n# function returns a maximal (disjoint) set of bands of interest (i.e if two\n# bands overlap they are reported as one bigger band).\ndef find_peaks(xs, rs, threshold):\n    \"\"\"Finds maximal (disjoint) peak regions in a sequence of real numbers.\n    Each value that is at least as large as the threshold constitutes the\n    center of a peak with radius according to its position. In the output all\n    overlapping peaks are merged into maximal peaks.\n\n    Args:\n        xs: the 1D data sequence of interest\n        rs: the radii for peaks defined at every point exceeding threshold,\n            could be a 1D sequence or a fixed number,\n        threshold: cutoff value to compare with ``xs`` values.\n\n    Returns:\n        list (tuple): A least of \"peaks\", each a tuple of ``(left, right)``\n        coordinates in ``xs``. Returned peaks are guaranteed to be disjoint.\n    \"\"\"\n    peaks = []\n    cur_peak = None\n    for idx, x in enumerate(xs):\n        radius = rs[idx] if isinstance(rs, list) else rs\n        assert isinstance(radius, int)\n        if x < threshold:\n            continue\n        peak_l, peak_r = max(0, idx - 1), min(len(xs) - 1, idx + 1)\n        if cur_peak is None:\n            cur_peak = (peak_l, peak_r)\n            continue\n        if peak_l < cur_peak[1] + radius:  # overlaps with cur_peak\n            assert peak_r >= cur_peak[1]\n            cur_peak = (cur_peak[0], peak_r)\n        else:\n            peaks.append(cur_peak)\n            cur_peak = (peak_l, peak_r)\n    if cur_peak is not None:\n        peaks.append(cur_peak)\n    return [(int(l), int(r)) for (l, r) in peaks]\n\n\ndef wall_to_wall_distance(len0, len1, diag):\n    \"\"\"Wall to wall distance for a diagonal position\n\n    .. math::\n        L = \\\\min(l_0 - d, l_1) + \\\\min(d, 0)\n\n    with :math:`l_0,l_1` being the length of the sequences (i.e ``len0`` and\n    ``len1`` arguments) and :math:`d` the starting diagonal (i.e ``diag``\n    argument).\n    \"\"\"\n    return min(len0 - diag, len1) + min(diag, 0)\n\n\ndef expected_overlap_len(len0, len1, diag, gap_prob):\n    \"\"\"Calculates the expected length of an overlap alignment given its starting\n    coordinates:\n\n    .. math::\n        K = \\\\left(\\\\frac{2}{2 - g}\\\\right) L\n\n    where :math:`L` is the :func:`wall_to_wall_distance`.\n\n    Args:\n        len0 (int): Length of the 1st sequence.\n        len1 (int): Length of the 2nd sequence.\n        diag (int): Starting diagonal of alignments to consider.\n        gap_prob (float): Probability of indels occuring at any position.\n    Returns:\n        int: Expected length of an overlap alignment.\n    \"\"\"\n    L = wall_to_wall_distance(len0, len1, diag)\n    expected_len = (2. / (2 - gap_prob)) * L\n    assert expected_len >= 0\n    return int(np.ceil(expected_len))\n\n\n# band radius for edit path of length K\ndef band_radius(expected_len, gap_prob, sensitivity):\n    \"\"\"Calculates the smallest band radius in the dynamic programming table\n    such that an alignment of given expected length, with the given gap\n    probability, stays entirely within the diagonal band with probability given\n    as sensitivity. This is given by:\n\n    .. math::\n        r = \\\\mathrm{erf}^{-1}\\\\left(1-\\\\epsilon\\\\right)\n            \\\\sqrt{2gK}\n\n    where :math:`g` is the gap probability, :math:`1-\\\\epsilon` is the desired\n    sensitivity, and :math:`K` is the given expected length.\n\n    Args:\n        expected_len (int):\n            minimum expected length of similar region.\n        gap_prob (float): Probability of indels occuring at any position.\n        sensitivity (float): The probability that an alignment with given gap\n            probability remains entirely within the band.\n    Returns:\n        int: The smallest band radius guaranteeing the required sensitivity.\n    \"\"\"\n    assert 0 < gap_prob < 1 and 0 < sensitivity < 1\n    epsilon = 1. - sensitivity\n    C = erfcinv(epsilon) * np.sqrt(2 * gap_prob)\n    radius = C * np.sqrt(expected_len)\n    return max(1, int(np.ceil(radius)))\n\n\ndef band_radii(expected_lens, gap_prob, sensitivity):\n    \"\"\"Same as :func:`band_radius` but for bulk calculations (e.g. finding\n    overlaps).\n\n    Args:\n        expected_lens (list):\n            List of integers for which to calculate band radii.\n        gap_prob (float):\n            As in :func:`band_radius`.\n        sensitivity (float):\n            As in :func:`band_radius`.\n    \"\"\"\n    assert 0 < gap_prob < 1 and 0 < sensitivity < 1\n    epsilon = 1. - sensitivity\n    C = erfcinv(epsilon) * np.sqrt(2 * gap_prob)\n    return np.array([max(1, int(np.ceil(C * np.sqrt(K))))\n                     for K in expected_lens])\n\n\ndef H0_moments(alphabet_len, wordlen, area):\n    \"\"\"The mean and standrad deviation of the limiting normal distribution\n    under the :math:`H_0` (unrelated) model given by:\n\n    .. math::\n        \\\\begin{aligned}\n            \\mu_0 & = Ap^w \\\\\\\\\n            \\sigma_0^2 & =\n                A\\\\left[(1 - p^w)\\left(p^w + \\\\frac{2p^{w+1}}{1 - p}\\\\right)\n                - 2wp^{2w}\\\\right]\n        \\\\end{aligned}\n\n    where :math:`w` is the word length, :math:`A` is the area of the ROI, and\n    :math:`p = \\\\frac{1}{|\\Sigma|}` with :math:`|\\Sigma|` being the alphabet\n    length.\n    \"\"\"\n    p_H0 = 1. / alphabet_len\n    pw_H0 = p_H0 ** wordlen\n\n    mu_H0 = area * pw_H0\n    sd_H0 = np.sqrt(area * (\n        (1 - pw_H0) * (pw_H0 + 2 * p_H0 * pw_H0 / (1 - p_H0)) -\n        2 * wordlen * pw_H0 ** 2\n    ))\n    return mu_H0, sd_H0\n\n\ndef H1_moments(alphabet_len, wordlen, area, seglen, p_match):\n    \"\"\"The mean and standrad deviation of the limiting normal distribution under\n    the :math:`H_1` (related) model given by:\n\n    .. math::\n        \\\\begin{aligned}\n            \\mu_1 & = \\mu_0 + Kp^w \\\\\\\\\n            \\sigma_1^2 & = \\sigma_0^2\n                + 2K\\\\left[(1 - p^w)\\left(p^w + \\\\frac{2p^{w+1}}{1 - p}\\\\right)\n                - 2wp^{2w}\\\\right]\n        \\\\end{aligned}\n\n    where :math:`w` is the word length, :math:`K` is the similarity length, and\n    :math:`p` is the match probability.\n    \"\"\"\n    mu_H0, sd_H0 = H0_moments(alphabet_len, wordlen, area)\n\n    p_H1 = p_match\n    if p_H1 == 1.:\n        # we can't let p_H1 == 1 because we get division by zero below\n        p_H1 = 1 - np.finfo(float).eps\n    pw_H1 = p_H1 ** wordlen\n\n    mu_H1 = mu_H0 + seglen * pw_H1\n    sd_H1 = np.sqrt(sd_H0 ** 2 + seglen * (\n        (1 - pw_H1) * (pw_H1 + 2 * p_H1 * pw_H1 / (1 - p_H1)) -\n        2 * wordlen * pw_H1 ** 2\n    ))\n    return mu_H1, sd_H1\n\n\n# FIXME the fact that we have organized our data as self.S and self.T is the\n# main blocker for merging pairwise and multiple sequence implementations.\n# Also involved: SeedIndexMultiple\nclass WordBlot(SeedIndex):\n    \"\"\"A similarity finder based on m-dependent CLT statistics.\n\n    Attributes:\n        g_max (float):\n            Upper bound for indel probabilities in mutation model.\n        sensitivity (float):\n            Desired sensitivity of bands.\n    \"\"\"\n    def __init__(self, S, T, g_max=None, sensitivity=None, **kw):\n        assert 0 < g_max < 1 and 0 < sensitivity < 1\n        self.g_max = g_max\n        self.sensitivity = sensitivity\n        super(WordBlot, self).__init__(S, T, **kw)\n\n    def score_num_seeds(self, **kw):\n        \"\"\"Calculates our key central statistics based on m-dependent CLT. For\n        a given observation of number of seeds in a region of interest (ROI),\n        calculates the z-core against the :math:`H_0` (unrelated) and\n        :math:`H_1` (related) models. In either case, the distribution of\n        number of seeds, being a sum of m-dependent identically distributed\n        random variables, is asymptotically normal with parameters given by\n        :func:`H0_moments`, :func:`H1_moments`.\n\n        Keyword Args:\n            num_seeds (int):\n                Number of observed seed in the ROI.\n            area (int|float):\n                Area of the ROI.\n            seglen (int):\n                Similar segment length in H1 model.\n            p_match (float):\n                Expected match probability at any given position.\n\n        Returns:\n            tuple (float): z-scores in H0 and H1 models\n        \"\"\"\n        num_seeds = kw['num_seeds']\n        area = kw['area']\n\n        if area == 0:\n            return float('-inf'), float('-inf')\n\n        mu_H0, sd_H0 = H0_moments(len(self.alphabet), self.wordlen, area)\n        mu_H1, sd_H1 = H1_moments(len(self.alphabet), self.wordlen, area,\n                                  kw['seglen'], kw['p_match'])\n\n        z_H0 = (num_seeds - mu_H0) / sd_H0  # score under H0\n        z_H1 = (num_seeds - mu_H1) / sd_H1  # score under H1\n        return z_H0, z_H1\n\n    def band_radius(self, K):\n        \"\"\"Wraps :func:`band_radius` with our mutation parameters and sequence\n        lengths.\n\n        Args:\n            K (int): expected alignment length of interest.\n\n        Returns:\n            int: radius of band for desired :attr:`sensitivity`.\n        \"\"\"\n        return band_radius(K, self.g_max, self.sensitivity)\n\n    def segment_dims(self, d_band=None, a_band=None):\n        \"\"\"Calculate the edit path length :math:`K` and the area of the given\n        diagonal/antiodiagonal segment.\n\n        Keyword Args:\n            d_band (tuple): lower and upper diagonals limiting the segment.\n            a_band (tuple): lower and upper antidiagonal positions limiting the\n                segment.\n\n        Returns:\n            tuple: edit path length and segment area.\n        \"\"\"\n        a_min, a_max = a_band\n        d_min, d_max = d_band\n        K = (a_max - a_min) / 2\n        A = (d_max - d_min) * K\n        return K, A\n\n    def estimate_match_probability(self, num_seeds, d_band=None, a_band=None):\n        \"\"\"Estimate the edit path match probability given the provided observed\n        number of seeds :math:`n` in given sigment:\n\n        .. math::\n            \\hat{p} = \\\\left(\\\\frac{n - Ap_\\circ^w}{K}\\\\right)^{\\\\frac{1}{w}}\n\n        where :math:`n, A, p_\\circ, K, w` are the number of seeds, segment\n        area, null probability of matching nucleotides, segment length, and the\n        word length, respectively.\n\n        Args:\n            num_seeds (int): number of seeds observed in segment.\n\n        Keywords Args:\n            d_band (tuple):\n                lower and upper diagonals limiting the segment.\n            a_band (tuple):\n                lower and upper antidiagonal positions limiting the segment.\n\n        Returns:\n            float: estimated match probability\n        \"\"\"\n        K, area = self.segment_dims(d_band=d_band, a_band=a_band)\n        word_p_null = (1./len(self.alphabet)) ** self.wordlen\n        # NOTE K effectively has become the projected alignment length not the\n        # full length. This is REALLY important in interpretation but I think\n        # must things are currently consistent (TODO full review needed).\n        word_p = (num_seeds - area * word_p_null) / K\n        try:\n            match_p = np.exp(np.log(word_p) / self.wordlen)\n        except Warning:\n            # presumably this happened because word_p was too small for log\n            match_p = 0\n        return min(match_p, 1)\n\n    @classmethod\n    def find_all_neighbors(cls, seeds, d_radius, a_radius):\n        \"\"\"For each seed finds all seeds in its neighborhood defined by:\n\n        .. math::\n\n            U_{(d, a)} = \\\\{(d', a'): |d - d'| < r_d,  |a - a'| < r_a \\\\}\n\n        This is done using a Quad-Tree in :math:`O(m lg m)` time where m is the\n        number of seeds.\n\n        Returns:\n            list: tuples ``((d, a), neighs)`` where ``neighs`` is a list of\n                  neighbor indices.\n        \"\"\"\n        # normalize the two diameters so we can use a standard L∞ neighborhood.\n        # typically a_diam is larger, so scale up d values proportionally\n        d_coeff = 1. * a_radius / d_radius\n        radius = a_radius\n\n        all_seeds = list(cls.to_diagonal_coordinates(i, j) for i, j in seeds)\n        if not all_seeds:\n            return []\n        all_seeds_scaled = np.array([(d * d_coeff, a) for d, a in all_seeds])\n        quad_tree = cKDTree(all_seeds_scaled)\n        all_neighs = quad_tree.query_ball_tree(quad_tree, radius,\n                                               p=float('inf'))\n        # all_neighs[i] is the indices of the neighbors of all_seeds[i]; this\n        # always contains the seed itself (i.e always: i in neighs[i])\n        for idx, _ in enumerate(all_neighs):\n            all_neighs[idx].remove(idx)\n        return zip(all_seeds, all_neighs)\n\n    def score_seeds(self, K):\n        \"\"\"Find the neighbors of each seed in the sense of\n        :func:`find_all_neighbors` and estimates the match probability of the\n        segment centered at the coordinates of each seed.\n\n        Args:\n            K (int): the similarity legnth of interest that dictates\n                neighborhood shapes and estimated match probabilities.\n\n        Returns:\n            list(dict): List of dictionaries with keys: ``seed`` (coordinates\n            of exactly matching kmer in diagonal coordinates), ``neighs`` (list\n            of indices of neighbors of this seed in the appropriate diagonal\n            strip), ``p`` the estimated match probability\n            of a segment centered at the seed.\n        \"\"\"\n        d_radius = int(np.ceil(self.band_radius(K)))\n        a_radius = K\n\n        seeds_with_neighs = self.find_all_neighbors(\n            self.seeds(exclude_trivial=True), d_radius, a_radius\n        )\n\n        # n is the number of seeds in neighborhood excluding the center seed,\n        def _p(d, a, n):\n            d_band = (d - d_radius, d + d_radius)\n            a_band = (a - a_radius, a + a_radius)\n            return self.estimate_match_probability(n + 1, d_band=d_band,\n                                                   a_band=a_band)\n\n        return [{'seed': (d, a), 'neighs': neighs, 'p': _p(d, a, len(neighs))}\n                for (d, a), neighs in seeds_with_neighs]\n\n    def similar_segments(self, K_min, p_min, at_least_one=False):\n        \"\"\"Find all maximal local similarities of given minium length and match\n        probability. Additionally for each segment, the match probability is\n        estimated and H0/H1 scores are calculated.\n\n        Args:\n            K_min (int):\n                minimum required length of similarity.\n            p_min (float):\n                Minimum required match probability at each position.\n            score (bool):\n                Whether to score the segment against H1 by counting seeds\n                inside.\n\n        Yields:\n            dict: dictionary with keys: ``segment`` (coordinates of similar\n            region in diagonal coordinates ``((d_min, d_max), (a_min,\n            a_max))``)), ``p`` the estimated match probability, and ``score``\n            the H1 z-score if keyword argument ``score`` is true.\n        \"\"\"\n        self.log('finding local similarities between %s and %s' %\n                 (self.S.content_id[:8], self.T.content_id[:8]))\n        d_radius = int(np.ceil(self.band_radius(K_min)))\n        a_radius = K_min\n        scored_seeds = self.score_seeds(K_min)\n\n        def _update_seg(seg, seed):\n            d, a = seed\n            if seg is None:\n                d_min, d_max = d - d_radius, d + d_radius\n                a_min, a_max = a - a_radius, a + a_radius\n            else:\n                (d_min, d_max), (a_min, a_max) = seg\n                d_min = min(d - d_radius, d_min)\n                d_max = max(d + d_radius, d_max)\n                a_min = min(a - a_radius, a_min)\n                a_max = max(a + a_radius, a_max)\n            return (d_min, d_max), (a_min, a_max)\n\n        avail = [rec['p'] >= p_min for rec in scored_seeds]\n        if not any(avail) and at_least_one:\n            # we're obliged to return something, let the highest probability\n            # seed go through.\n            assert len(scored_seeds), 'no seeds found while at_least_one=True'\n            avail[np.argmax([rec['p'] for rec in scored_seeds])] = True\n        while True:\n            try:\n                seed_idx = avail.index(True)\n            except ValueError:\n                break\n            stack = [seed_idx]\n            avail[seed_idx] = False\n            ps_in_seg = [scored_seeds[seed_idx]['p']]\n            seg = None\n            while stack:\n                idx = stack.pop()\n                ps_in_seg.append(scored_seeds[idx]['p'])\n                seg = _update_seg(seg, scored_seeds[idx]['seed'])\n                for neigh in scored_seeds[idx]['neighs']:\n                    if avail[neigh]:\n                        stack.append(neigh)\n                        avail[neigh] = False\n            if seg is None:\n                break\n            else:\n                (d_min, d_max), (a_min, a_max) = seg\n                d_min = min(len(self.S), max(d_min, -len(self.T)))\n                d_max = min(len(self.S), max(d_max, -len(self.T)))\n                a_min = max(a_min, 0)\n                a_max = min(a_max, len(self.S) + len(self.T))\n                seg = (d_min, d_max), (a_min, a_max)\n            # NOTE the following is more justifiable but it matches the\n            # average. TODO turn this in into an experiment to justify\n            # p_hat = self.estimate_match_probability(\n            #   n, d_band=seg[0], a_band=seg[1])\n            p_hat = sum(ps_in_seg) / len(ps_in_seg)\n            res = {'segment': seg, 'p': p_hat}\n            n = self.seed_count(d_band=seg[0], a_band=seg[1])\n            K_hat, area_hat = self.segment_dims(d_band=seg[0],\n                                                a_band=seg[1])\n            scores = self.score_num_seeds(num_seeds=n, area=area_hat,\n                                          seglen=K_hat, p_match=p_hat)\n            res['scores'] = scores\n            yield res\n\n\nclass WordBlotOverlap(WordBlot):\n    \"\"\"A specialized version of WordBlot for detecting overlap\n    (suffix-prefix) similarities between sequences (e.g. in a sequencing\n    context).\"\"\"\n    def score_seeds(self):\n        \"\"\"For each seed finds all seeds in its neighborhood defined by:\n\n        .. math::\n\n            U_{(d, a)} = \\\\{(d', a'): |d - d'| < r_d(d),  |a - a'| < r_a(d) \\\\}\n\n        in such a way that each seed's neighborhood is the entire diagonal band\n        containing it. Each seed recieves an estimated match probability for a\n        similarity on its diagonal band and a z-score with respect to the H1\n        model.\n\n        Returns:\n            list: dicts with keys ``seed`` (diagonal coordinates of seed),\n                  ``p`` (estimated match probability of overlap alignment),\n                  ``L`` (the length of an alignment through the seed's band\n                  according to sequence lengths), ``score`` (the z-score with\n                  respect to H1), and ``r`` (band radius at the seed's\n                  coordinates).\n        \"\"\"\n        def _len(d):\n            return expected_overlap_len(\n                len(self.S), len(self.T), d, self.g_max\n            )\n\n        def _rad(d):\n            return np.ceil(self.band_radius(_len(d)))\n\n        all_seeds = list(self.to_diagonal_coordinates(i, j)\n                         for i, j in self.seeds(exclude_trivial=True))\n        if not all_seeds:\n            return []\n        all_seeds_scaled = np.array([(d / _rad(d), ) for d, a in all_seeds])\n        quad_tree = cKDTree(all_seeds_scaled)\n        all_neighs = quad_tree.query_ball_tree(quad_tree, 1, p=float('inf'))\n        # all_neighs[i] is the indices of the neighbors of all_seeds[i]; this\n        # always contains the seed itself (i.e always: i in neighs[i])\n        for idx, _ in enumerate(all_neighs):\n            all_neighs[idx].remove(idx)\n        seeds_with_neighs = zip(all_seeds, all_neighs)\n\n        # n excludes the center seed itself\n        def _p(d, n):\n            L = _len(d)\n            d_radius = int(np.ceil(self.band_radius(L)))\n            area = 2 * d_radius * L\n            word_p_null = (1./len(self.alphabet)) ** self.wordlen\n            word_p = (n + 1 - area * word_p_null) / L\n            try:\n                match_p = np.exp(np.log(word_p) / self.wordlen)\n            except Warning:\n                # presumably this happened because word_p was too small for log\n                match_p = 0\n            return min(match_p, 1)\n\n        return [{'seed': (d, a), 'r': _rad(d), 'L': _len(d),\n                 'p': _p(d, len(neighs))}\n                for (d, a), neighs in seeds_with_neighs]\n\n    def highest_scoring_overlap_band(self):\n        \"\"\"Finds the highest scoring diagonal band according to probabiliy\n        estimations of :func:`score_seeds`.\n\n        Returns:\n            dict: with same keys ``p, score, d_band`` consistent with the\n                  output of :func:`score_seeds` for the highest scoring\n                  diagonal band.\n        \"\"\"\n        scored_seeds = self.score_seeds()\n        if not scored_seeds:\n            return None\n        idx = max(range(len(scored_seeds)), key=lambda i: scored_seeds[i]['p'])\n        seed, rad = scored_seeds[idx]['seed'], scored_seeds[idx]['r']\n        p_hat, overlap_len = scored_seeds[idx]['p'], scored_seeds[idx]['L']\n        d_band = seed[0] - rad, seed[0] + rad\n        res = {'d_band': d_band, 'p': p_hat, 'len': overlap_len}\n        area = 2 * rad * overlap_len\n        mu_H1, sd_H1 = H1_moments(len(self.alphabet), self.wordlen, area,\n                                  overlap_len, p_hat)\n        num_seeds = self.seed_count(d_band=d_band)\n        z_H1 = (num_seeds - mu_H1) / sd_H1\n        res['score'] = z_H1\n        return res\n\n\nclass WordBlotOverlapRef(WordBlotOverlap):\n    \"\"\"An in-memory, SQL-free version of :class:`WordBlotOverlap` for faster\n    comparisons.  Due to implementation details the word length is constrained\n    above by the available memory.\n\n    Attributes:\n        allowed_memory (int|float): allocatable memory in GB for kmers index.\n    \"\"\"\n    def __init__(self, ref, allowed_memory=1, **kw):\n        self.wordlen = kw['wordlen']\n        self.alphabet = kw['alphabet']\n        self.g_max = kw['g_max']\n        self.sensitivity = kw['sensitivity']\n        self.log_level = kw.get('log_level', logging.INFO)\n        self.S = ref\n        num_kmers = len(self.alphabet) ** self.wordlen\n        mem_needed = sys.getsizeof(num_kmers) * num_kmers\n        mem_needed_gb = np.power(2, np.log2(mem_needed) - 30)\n        assert allowed_memory > 0, 'allowed memory must be positive'\n        self.allowed_memory = allowed_memory\n        if mem_needed_gb > self.allowed_memory:\n            msg = 'not enough memory (max = %.2f GB) ' % allowed_memory\n            msg += 'to store %d-mers ' % self.wordlen\n            msg += '(%.2f GB needed)' % mem_needed_gb\n            raise MemoryError(msg)\n        self.kmer_hits = [[] for _ in range(num_kmers)]\n        for pos, kmer in enumerate(as_kmer_seq(ref, self.wordlen)):\n            self.kmer_hits[kmer].append(pos)\n        self.T = None\n        relpath = 'python-object'\n        log_header = '%d-mer cache (%s)' % (self.wordlen, relpath)\n        self._logger = Logger(log_level=self.log_level, header=log_header)\n        self._seeds = {}\n\n    def seeds(self, exclude_trivial=True):\n        assert self.T is not None\n        if self.T.content_id not in self._seeds:\n            self._seeds = {self.T.content_id: []}\n            for pos, kmer in enumerate(as_kmer_seq(self.T, self.wordlen)):\n                for pos_ref in self.kmer_hits[kmer]:\n                    if self.S == self.T and exclude_trivial and pos == pos_ref:\n                        continue\n                    self._seeds[self.T.content_id].append((pos_ref, pos))\n        return self._seeds[self.T.content_id]\n\n    def seed_count(self, d_band=None, a_band=None):\n        assert self.T is not None\n        seeds = self.seeds()\n        cnt = 0\n        if d_band:\n            d_min, d_max = d_band\n        if a_band:\n            a_min, a_max = a_band\n        for i, j in seeds:\n            d, a = self.to_diagonal_coordinates(i, j)\n            if d_band and not d_min <= d <= d_max:\n                continue\n            if a_band and not a_min <= a <= a_max:\n                continue\n            cnt += 1\n        return cnt\n\n    def score_seeds_(self, seq):\n        self.T = seq\n        return super(WordBlotOverlapRef, self).score_seeds()\n\n    def highest_scoring_overlap_band(self, seq):\n        self.T = seq\n        return super(WordBlotOverlapRef, self).highest_scoring_overlap_band()\n\n\nclass WordBlotLocalRef(WordBlot):\n    \"\"\"An in-memory, SQL-free version of :class:`WordBlot` for faster\n    comparisons. Due to implementation details the word length is constrained\n    above by the available memory.\n\n    Attributes:\n        allowed_memory (int|float): allocatable memory in GB for kmers index.\n    \"\"\"\n    def __init__(self, ref, allowed_memory=1, **kw):\n        self.wordlen = kw['wordlen']\n        self.alphabet = kw['alphabet']\n        self.g_max = kw['g_max']\n        self.sensitivity = kw['sensitivity']\n        self.log_level = kw.get('log_level', logging.INFO)\n        self.S = ref\n        num_kmers = len(self.alphabet) ** self.wordlen\n        mem_needed = sys.getsizeof(num_kmers) * num_kmers\n        mem_needed_gb = np.power(2, np.log2(mem_needed) - 30)\n        assert allowed_memory > 0, 'allowed memory must be positive'\n        self.allowed_memory = allowed_memory\n        if mem_needed_gb > self.allowed_memory:\n            msg = 'not enough memory (max = %.2f GB) ' % allowed_memory\n            msg += 'to store %d-mers ' % self.wordlen\n            msg += '(%.2f GB needed)' % mem_needed_gb\n            raise MemoryError(msg)\n        self.kmer_hits = [[] for _ in range(num_kmers)]\n        for pos, kmer in enumerate(as_kmer_seq(ref, self.wordlen)):\n            self.kmer_hits[kmer].append(pos)\n        self.T = None\n        relpath = 'python-object'\n        log_header = '%d-mer cache (%s)' % (self.wordlen, relpath)\n        self._logger = Logger(log_level=self.log_level, header=log_header)\n        self._seeds = {}\n\n    def seeds(self, exclude_trivial=True):\n        assert self.T is not None\n        if self.T.content_id not in self._seeds:\n            self._seeds = {self.T.content_id: []}\n            for pos, kmer in enumerate(as_kmer_seq(self.T, self.wordlen)):\n                for pos_ref in self.kmer_hits[kmer]:\n                    if self.S == self.T and exclude_trivial and pos == pos_ref:\n                        continue\n                    self._seeds[self.T.content_id].append((pos_ref, pos))\n        return self._seeds[self.T.content_id]\n\n    def seed_count(self, d_band=None, a_band=None):\n        assert self.T is not None\n        seeds = self.seeds()\n        cnt = 0\n        if d_band:\n            d_min, d_max = d_band\n        if a_band:\n            a_min, a_max = a_band\n        for i, j in seeds:\n            d, a = self.to_diagonal_coordinates(i, j)\n            if d_band and not d_min <= d <= d_max:\n                continue\n            if a_band and not a_min <= a <= a_max:\n                continue\n            cnt += 1\n        return cnt\n\n    def score_seeds_(self, seq, K):\n        self.T = seq\n        return super(WordBlotLocalRef, self).score_seeds(K)\n\n    def similar_segments(self, seq, K_min, p_min, at_least_one=False):\n        self.T = seq\n        kw = {'at_least_one': at_least_one}\n        for res in super(WordBlotLocalRef, self).similar_segments(K_min, p_min,\n                                                                  **kw):\n            yield res\n\n\n# FIXME lots of code duplication here, can it be cleaned up? (cf. note above\n# WordBlot; the main issue is self.S and self.T being used everywhere there,\n# and presumably lots of hidden pairwise assumptions). The good news is:\n# every function implemented below should in principle work exactly as is for\n# pairwise.\nclass WordBlotMultiple(SeedIndexMultiple):\n    \"\"\"A multiple sequence similarity finder based on m-dependent CLT\n    statistics.\n\n    Attributes:\n        g_max (float):\n            Upper bound for indel probabilities in mutation model.\n        sensitivity (float):\n            Desired sensitivity of bands.\n    \"\"\"\n    def __init__(self, *seqs, **kw):\n        g_max, sensitivity = kw.pop('g_max'), kw.pop('sensitivity')\n        assert 0 < g_max < 1 and 0 < sensitivity < 1\n        self.g_max = g_max\n        self.sensitivity = sensitivity\n        super(WordBlotMultiple, self).__init__(*seqs, **kw)\n\n    def band_radius(self, K):\n        \"\"\"Wraps :func:`band_radius` with our mutation parameters and sequence\n        lengths.\n\n        Args:\n            K (int): expected alignment length of interest.\n\n        Returns:\n            int: radius of band for desired :attr:`sensitivity`.\n        \"\"\"\n        return band_radius(K, self.g_max, self.sensitivity)\n\n    def wall_to_wall_distance(self, ds):\n        \"\"\"Wall to wall distance :math:`L` for a diagonal position :math:`d_1,\n        \\ldots, d_{n-1}`.\n\n        The distance :math:`L` is the largest possible value of the\n        antidiagonal coordinate once all diagonal coordinates are fixed.\n        \"\"\"\n        raise NotImplementedError\n\n    def estimate_match_probability(self, num_seeds, K, volume):\n        \"\"\"Estimate the edit path match probability given the provided observed\n        number of seeds in given sigment.\n\n        .. math::\n            \\hat{p} = \\\\left(\n                            \\\\frac{n - Vp_\\circ^{w(N-1)}}{K}\n                      \\\\right)^{\\\\frac{1}{w(N-1)}}\n\n        where :math:`n, N, V, p_\\circ, w` are the number of seeds, number of\n        sequences, segment n-d volume, null probability of matching\n        nucleotides, and word length, respectively.\n\n        Args:\n            num_seeds (int|float): number of seeds observed in segment.\n            K (int|float): the expected length of the alignment.\n            volume (int|float): the n-d volume of the region of interest.\n\n        Returns:\n            float: estimated match probability\n        \"\"\"\n        power = self.wordlen * (len(self.seqs) - 1)\n        word_p_null = (1. / len(self.alphabet)) ** power\n\n        if num_seeds > 0:\n            word_p = (num_seeds - volume * word_p_null) / K\n            try:\n                match_p = np.exp(np.log(word_p) / self.wordlen)\n            except Warning:\n                # presumably this happened because word_p was too small for log\n                match_p = 0\n        else:\n            match_p = 0\n        return min(match_p, 1)\n\n    def score_seeds(self, K):\n        \"\"\"Find the neighbors of each seed in the sense of\n        :func:`find_all_neighbors` and estimates the match probability of the\n        segment centered at the coordinates of each seed.\n\n        Args:\n            K (int): the similarity legnth of interest that dictates\n                neighborhood shapes and estimated match probabilities.\n\n        Returns:\n            list: list of tuples ``((d, a), neighs, p)`` where ``(d, a)``\n                  is the diagonal coordinates of the seed, ``neighs`` is a list\n                  of integer indices of seeds in its diagonal/antidiagonal\n                  neighborhood, and ``p`` is the estimated match probability of\n                  a segment of length ``K`` centered at the seed.\n        \"\"\"\n        d_radius = int(np.ceil(self.band_radius(K)))\n        a_radius = int(np.ceil(len(self.seqs) * K / 2.))\n        seeds_with_neighs = self.find_all_neighbors(d_radius, a_radius)\n        volume = (2 * d_radius) ** (len(self.seqs) - 1) * K\n\n        # n excludes the center seed itself\n        def _p(n):\n            return self.estimate_match_probability(n + 1, K, volume)\n\n        return [{'seed': (ds, a), 'neighs': neighs, 'p': _p(len(neighs))}\n                for (ds, a), neighs in seeds_with_neighs]\n\n    def find_all_neighbors(self, d_radius, a_radius):\n        \"\"\"For each seed finds all seeds in its neighborhood defined by:\n\n        .. math::\n\n            U_{(d_1,\\ldots,d_{n-1}, a)} =\n                \\\\{(d_1', \\ldots, d_{n-1}', a'):\n                    |d_k - d_k'| < r_d,  |a - a'| < r_a \\\\}\n\n        This is done using a kD-Tree in :math:`O(nm lg m)` time where m is the\n        number of seeds and n is the number of sequences.\n\n        Returns:\n            list: tuples ``((ds, a), neighs)`` where ``neighs`` is a list of\n                  neighbor indices.\n        \"\"\"\n        self.log('finding all neighbors using a kD-tree')\n        # normalize the two diameters so we can use a standard L∞ neighborhood.\n        # typically a_diam is larger, so scale up d values proportionally\n        d_coeff = 1. * a_radius / d_radius\n        radius = a_radius\n\n        all_seeds = list(self.seeds())\n        if not all_seeds:\n            return []\n        all_seeds_scaled = np.array([[d * d_coeff for d in ds] + [a]\n                                     for ds, a in all_seeds])\n        quad_tree = cKDTree(all_seeds_scaled)\n        all_neighs = quad_tree.query_ball_tree(quad_tree, radius,\n                                               p=float('inf'))\n        # all_neighs[i] is the indices of the neighbors of all_seeds[i]; this\n        # always contains the seed itself (i.e always: i in neighs[i])\n        for idx, _ in enumerate(all_neighs):\n            all_neighs[idx].remove(idx)\n        self.log('found all neighbors')\n        return zip(all_seeds, all_neighs)\n\n    def score_num_seeds(self, num_seeds, **kw):\n        \"\"\"The exrtension of :func:`WordBlot.score_num_seeds` to multiple\n        sequence comparisons.\n\n        Keyword Args:\n            num_seeds (int):\n                Number of observed seed in the ROI.\n            volume (int|float):\n                Area of the ROI.\n            seglen (int):\n                Similar segment length in H1 model.\n            p_match (float):\n                Expected match probability at any given position.\n\n        Returns:\n            tuple (float): z-scores in H0 and H1 models\n        \"\"\"\n        p_match = kw['p_match']\n        seglen = kw['seglen']\n        volume = kw['volume']\n        if volume == 0:\n            return float('-inf'), float('-inf')\n        if p_match == 1.:\n            # we can't let p_H1 == 1 because we get division by zero below\n            p_match = 1 - np.finfo(float).eps\n\n        p_H0 = (1. / len(self.alphabet)) ** (len(self.seqs) - 1)\n        pw_H0 = p_H0 ** self.wordlen\n\n        mu_H0 = volume * pw_H0\n        sd_H0 = np.sqrt(volume * (\n            (1 - pw_H0) * (pw_H0 + 2 * p_H0 * pw_H0 / (1 - p_H0)) -\n            2 * self.wordlen * pw_H0 ** 2\n        ))\n\n        p_H1 = p_match\n        pw_H1 = p_H1 ** self.wordlen\n\n        mu_H1 = mu_H0 + seglen * pw_H1\n        sd_H1 = np.sqrt(sd_H0 ** 2 + seglen * (\n            (1 - pw_H1) * (pw_H1 + 2 * p_H1 * pw_H1 / (1 - p_H1)) -\n            2 * self.wordlen * pw_H1 ** 2\n        ))\n\n        z_H0 = (num_seeds - mu_H0) / sd_H0  # score under H0\n        z_H1 = (num_seeds - mu_H1) / sd_H1  # score under H1\n        return z_H0, z_H1\n\n    def similar_segments(self, K_min, p_min, at_least_one=False):\n        \"\"\"Find all maximal local similarities of given minium length and match\n        probability. Additionally for each segment, the match probability is\n        estimated and H0/H1 scores are calculated.\n\n        Args:\n            K_min (int):\n                minimum required length of similarity.\n            p_min (float):\n                Minimum required match probability at each position.\n            score (bool):\n                Whether to score the segment against H1 by counting seeds\n                inside.\n\n        Yields:\n            dict: dictionary with keys: ``segment`` (coordinates of similar\n            region in diagonal coordinates, ``p`` the estimated match\n            probability, and ``score`` the H1 z-score if keyword argument\n            ``score`` is true.\n        \"\"\"\n        d_radius = int(np.ceil(self.band_radius(K_min)))\n        a_radius = int(np.ceil(len(self.seqs) * K_min / 2.))\n        scored_seeds = self.score_seeds(K_min)\n        self.log('finding local similarities between %d sequences' %\n                 len(self.seqs))\n\n        def _update_seg(seg, seed):\n            ds, a = seed\n            if seg is None:\n                d_ranges = [None] * (len(self.seqs) - 1)\n                for i in range(len(self.seqs) - 1):\n                    d_ranges[i] = ds[i] - d_radius, ds[i] + d_radius\n                a_range = a - a_radius, a + a_radius\n            else:\n                d_ranges, a_range = seg\n                assert all(len(r) == 2 for r in d_ranges)  # pairs of min, max\n                for i in range(len(self.seqs) - 1):\n                    d_min, d_max = d_ranges[i]\n                    d_ranges[i] = (min(ds[i], d_min),\n                                   max(ds[i], d_max))\n                a_min, a_max = seg[-1]\n                a_range = (min(a - a_radius, a_min), max(a + a_radius, a_max))\n            return d_ranges, a_range\n\n        avail = [rec['p'] >= p_min for rec in scored_seeds]\n        if not any(avail) and at_least_one:\n            # we're obliged to return something, let the highest probability\n            # seed go through.\n            assert len(scored_seeds), 'no seeds found while at_least_one=True'\n            avail[np.argmax([rec['p'] for rec in scored_seeds])] = True\n        while True:\n            try:\n                # TODO grab the highest probability so we yield in decreasing\n                # order of quality\n                seed_idx = avail.index(True)\n            except ValueError:\n                break\n            stack = [seed_idx]\n            avail[seed_idx] = False\n            ps_in_seg = [scored_seeds[seed_idx]['p']]\n            seg = None\n            while stack:\n                idx = stack.pop()\n                ps_in_seg.append(scored_seeds[idx]['p'])\n                seg = _update_seg(seg, scored_seeds[idx]['seed'])\n                for neigh in scored_seeds[idx]['neighs']:\n                    if avail[neigh]:\n                        stack.append(neigh)\n                        avail[neigh] = False\n            if seg is None:\n                break\n            else:\n                # clip overflowing values so translating back to standard\n                # coordinates gives meaningful numbers.\n                ds_range, a_range = seg\n                for idx in range(len(self.seqs) - 1):\n                    d_min, d_max = ds_range[idx]\n                    d_min = min(\n                        len(self.seqs[0]),\n                        max(d_min, -len(self.seqs[idx + 1]))\n                    )\n                    d_max = min(\n                        len(self.seqs[0]),\n                        max(d_max, -len(self.seqs[idx + 1]))\n                    )\n                    ds_range[idx] = d_min, d_max\n                a_min, a_max = a_range\n                a_min = max(a_min, 0)\n                a_max = min(a_max, sum(len(seq) for seq in self.seqs))\n                seg = ds_range, (a_min, a_max)\n            # NOTE the following is more justifiable but it matches the\n            # average. TODO turn this in into an experiment to justify\n            # p_hat = self.estimate_match_probability(\n            #   n, d_band=seg[0], a_band=seg[1])\n            p_hat = sum(ps_in_seg) / len(ps_in_seg)\n            res = {'segment': seg, 'p': p_hat}\n            ds_band, a_band = seg\n            n = self.seed_count(ds_band=ds_band, a_band=a_band)\n            K_hat = np.ceil((a_band[1] - a_band[0]) / len(self.seqs))\n            volume = a_band[1] - a_band[0]\n            for d_band in ds_band:\n                volume *= d_band[1] - d_band[0]\n            scores = self.score_num_seeds(num_seeds=n, volume=volume,\n                                          seglen=K_hat, p_match=p_hat)\n            res['scores'] = scores\n            yield res\n\n\nclass WordBlotMultipleFast(WordBlotMultiple):\n    \"\"\"An in-memory, SQL-free version of :class:`WordBlotOverlapMultiple` for\n    faster comparisons. Due to implementation details the word length is\n    constrained above by the available memory.\n\n    Attributes:\n        allowed_memory (int|float): allocatable memory in GB for kmers index,\n            default is 1.\n    \"\"\"\n    def __init__(self, *seqs, **kw):\n        name = '_'.join(S.content_id[:8] for S in seqs)\n        self.name = name\n        self.wordlen = kw['wordlen']\n        self.alphabet = kw['alphabet']\n        self.g_max = kw['g_max']\n        self.sensitivity = kw['sensitivity']\n        self.log_level = kw.get('log_level', logging.INFO)\n        self.seqs = seqs\n        self.allowed_memory = kw.get('allowed_memory', 1)\n        assert self.allowed_memory > 0, 'allowed memory must be positive'\n        num_kmers = len(self.alphabet) ** self.wordlen\n        mem_needed = sys.getsizeof(num_kmers) * num_kmers\n        mem_needed_gb = np.power(2, np.log2(mem_needed) - 30)\n        if mem_needed_gb > self.allowed_memory:\n            msg = 'not enough memory (max = %.2f GB) ' % self.allowed_memory\n            msg += 'to store %d-mers ' % self.wordlen\n            msg += '(%.2f GB needed)' % mem_needed_gb\n            raise MemoryError(msg)\n        self.kmer_hits = [[] for _ in range(num_kmers)]\n        for idx, seq in enumerate(self.seqs):\n            for pos, kmer in enumerate(as_kmer_seq(seq, self.wordlen)):\n                self.kmer_hits[kmer].append((idx, pos))\n        log_header = '%d-mer word-blot (python-object)' % self.wordlen\n        self._logger = Logger(log_level=self.log_level, header=log_header)\n\n    def seeds(self):\n        for hits in self.kmer_hits:\n            hits = {seqid: [c[1] for c in seq_hits]\n                    for seqid, seq_hits in groupby(hits,\n                                                   key=lambda c: c[0])}\n            # only consider kmers present in all sequences\n            if len(hits) < len(self.seqs):\n                continue\n            for idxs in product(*hits.values()):\n                ds, a = self.to_diagonal_coordinates(*idxs)\n                yield list(ds), a\n\n    def seed_count(self, ds_band=None, a_band=None):\n        cnt = 0\n        for ds, a in self.seeds():\n            if ds_band:\n                if not all(ds_band[i][0] <= d <= ds_band[i][1]\n                           for i, d in enumerate(ds)):\n                    continue\n            if a_band and not a_band[0] <= a <= a_band[1]:\n                continue\n            cnt += 1\n        return cnt\n", "meta": {"hexsha": "5d18646f99ae6ec367812fab84ec03a6e2cdbcd5", "size": 43386, "ext": "py", "lang": "Python", "max_stars_repo_path": "biseqt/blot.py", "max_stars_repo_name": "amirkdv/oval", "max_stars_repo_head_hexsha": "8acd50bbdc4c96ef25d9680710e0afef455a88f3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-29T11:39:45.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-29T11:39:45.000Z", "max_issues_repo_path": "biseqt/blot.py", "max_issues_repo_name": "amirkdv/oval", "max_issues_repo_head_hexsha": "8acd50bbdc4c96ef25d9680710e0afef455a88f3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "biseqt/blot.py", "max_forks_repo_name": "amirkdv/oval", "max_forks_repo_head_hexsha": "8acd50bbdc4c96ef25d9680710e0afef455a88f3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0239852399, "max_line_length": 80, "alphanum_fraction": 0.5701839303, "include": true, "reason": "import numpy,from scipy", "num_tokens": 10837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.3208212943308302, "lm_q1q2_score": 0.18892817315029337}}
{"text": "#!/usr/bin/env python\n\n\"\"\"This script defines functions to equilibrium simulation of gasification \nprocesses. It uses some predefined functions from Cantera package.\n\n@author = Rodolfo Rodrigues\n@contact = rodolfo@unipampa.edu.br\n@data = April, 2012, rev.: June, 2013 (adapted to use cython Cantera)\n\"\"\"\n#==============================================================================\n# import libraries/files\n#==============================================================================\nimport pp\nimport feedstock\nimport cantera as ct\nimport numpy as np\nimport scipy.optimize as opt\nimport csv\n\n#==============================================================================\n# predefine parameters\n#==============================================================================\nR = ct.gas_constant  # 8314.4621 Pa*m^3/K/kmol\nTn = 273.15  # K\nPn = ct.one_atm  # 101315 Pa\nzero = np.zeros(1)\none = np.ones(1)\n\n#==============================================================================\n# special functions\n#==============================================================================\ndef get_feed(self, moist=0, fuel=1.0, air=0, o2=0, stm=0):\n    \"\"\"\n    This function creates a mixture of phases to denote the fuel.\n    The fuel is composed as a mixture of char, gas, ash, and moisture phases.\n\n    Parameters\n    ----------\n    self : ndarray\n        Mass fraction of fuel compounds, d.b. [kg/kg]\n    moist : float\n        Mass fraction of moisture fuel [kg/kg]\n    fuel : float\n        Mass amount of fuel, d.b. [kg]\n    air : float\n        Mass amount of air [kg]\n    o2 : float\n        Mass amount of pure O2 [kg] (default value is zero)\n    stm : float\n        Mass amount of steam [kg] (default value is zero)\n\n    Returns\n    -------\n    feed : object\n        Feedstock object [mixture of phases]\n    \"\"\"\n    # convert everything to array\n    moist *= one\n    fuel *= one\n    air *= one\n    o2 *= one\n    stm *= one\n    # preallocate variables\n    no = np.zeros(pp.nsp)\n    # mass amount of fuel, w.b.\n    mass = fuel*(1 + moist)*np.append(self*(1 - moist), moist)\n    ## NOTE: It's not possible to estimate the molecular weight of a fuel\n    ## starting from its mass fraction composition. This parameter is taken\n    ## from the whole-number multiple and empirical formula.\n    ## attribute values for species\n    #\n    # mole amount of fuel, w.b.\n    mol = mass/pp.Mw_f\n    ## attribute values for species\n    # mole amount of CHONSCl content\n    no[pp.i_C] = mol[0]\n#    no[pp.i_C_] = 0.3*mol[0]\n    no[pp.i_H] = mol[1]\n    no[pp.i_O] = mol[2]\n    no[pp.i_N] = mol[3]\n    no[pp.i_S] = mol[4]\n    no[pp.i_Cl] = mol[5]\n    # mole amount of ash content \n    no[pp.i_SiO2] = mol[6]\n    no[pp.i_CaO] = mol[7]\n    no[pp.i_Al2O3] = mol[8]\n    no[pp.i_Fe2O3] = mol[9]\n    no[pp.i_Na2O] = mol[10]\n    no[pp.i_K2O] = mol[11]\n    no[pp.i_MgO] = mol[12]\n    no[pp.i_P2O5] = mol[13]\n    no[pp.i_TiO2] = mol[14]\n    no[pp.i_SO3] = mol[15]\n    no[pp.i_Cr2O3] = mol[16]\n    # mole amount of moisture content\n    no[pp.i_H2O] = mol[17]\n    # mole amount of air content \n    # air composition: 23.2%wt O2, 75.47%wt N2, 1.2%wt Ar\n    if (o2.all() == 0 and air.any() != 0):\n        no[pp.i_O2] = 0.23211606*air/pp.Mw[pp.i_O2]\n        no[pp.i_N2] = 0.75507754*air/pp.Mw[pp.i_N2]\n        no[pp.i_Ar] = 0.01280640*air/pp.Mw[pp.i_Ar]\n    elif (o2.any() != 0 and air.all() == 0):\n        no[pp.i_O2] = o2/pp.Mw[pp.i_O2]\n    # mole amount of steam content\n    no[pp.i_H2O] += stm/pp.Mw[pp.i_H2O]\n    ## attribute values for phase\n    # mole amount to each phase\n    no_s = np.sum(no[:pp.s.n_species]) # solid phase\n    no_g = np.sum(no[pp.s.n_species:]) # gas phase\n    # set mole amount to each phase\n    pp.f.set_phase_moles(pp.f.phase_index('solid'), no_s)\n    pp.f.set_phase_moles(pp.f.phase_index('gas'), no_g)\n    # set mole amount to each species\n    pp.f.species_moles = no\n    return pp.f\n\ndef get_water(self, moisture=0, fuel=1.0, steam=0):\n    \"\"\"\n    This function get the mole amount of water as moisture and steam.\n\n    Parameters\n    ----------\n    self : ndarray\n        Mass fraction of fuel compounds, d.b. [kg/kg]\n    moisture : float\n        Mass fraction of moisture fuel [kg/kg]\n    fuel : float\n        Mass amount of fuel, d.b. [kg]\n    steam : float\n        Mass amount of steam [kg] (default value is zero)\n\n    Returns\n    -------\n    mole_moisture : float\n        Mole amount of moisture [kmol]\n    mole_steam : float\n        Mole amount of steam [kmol]\n    \"\"\"\n    # convert everything to array\n    moisture *= one\n    fuel *= one\n    steam *= one\n    # mass amount of fuel, w.b.\n    mass = fuel*(1 + moisture)*np.append(self*(1 - moisture), moisture)\n    # mole amount of fuel, w.b.\n    mol = mass/pp.Mw_f\n    # mole amount of moisture content\n    mole_moisture = mol[17]\n    # mole amount of steam content\n    mole_steam = steam/pp.Mw[pp.i_H2O]\n    return mole_moisture, mole_steam\n\ndef get_enthalpy(self, value='h', duty=0):\n    '''\n    Return enthalpy (h) and specific heat capacity (cp) of a mixture of phases.\n    \n    TODO: Add duty term to enthalpy calculation\n    '''\n    # enthalpy [J] per 1 kg of fuel\n    h = (self.phase_moles(self.phase_index('solid')) \\\n        * self.phase(self.phase_index('solid')).enthalpy_mole \\\n        + self.phase_moles(self.phase_index('gas')) \\\n        * self.phase(self.phase_index('gas')).enthalpy_mole \\\n        )/sum(self.species_moles)\n    if value == 'h': return h\n    # specific heat capacity [J/kmol/K]\n    cp = (self.phase_moles(self.phase_index('solid')) \\\n        * self.phase(self.phase_index('solid')).cp_mole \\\n        + self.phase_moles(self.phase_index('gas')) \\\n        * self.phase(self.phase_index('gas')).cp_mole \\\n        )/sum(self.species_moles)\n    if value == 'cp': return cp\n    return  h, cp\n    \ndef equilibrate_tp(self, moisture, fuel, air, o2=zero, steam=zero,\n                T=1273, P=ct.one_atm):\n    \"\"\"\n    Isothermic multi-phase equilibrium calculation holding temperature and \n    pressure fixed.\n    \n    The enthalpy of feedstocks/reagents (fuel, air, and steam) does not matter \n    for calculation of products in this approach.\n\n    Parameters\n    ----------\n    self : ndarray\n        Mass fraction of fuel compounds in d.b. [kg/kg]\n    moisture : float\n        Mass fraction of moisture fuel [kg/kg]\n    fuel : float\n        Mass amount of fuel in d.b. [kg]\n    air : float\n        Mass amount of air [kg]\n    o2 : float\n        Mass amount of oxygen, O2 [kg] (default value is zero)\n    steam : float\n        Mass amount of steam [kg]\n    T : float\n        Temperature [K]\n    P : float\n        Pressure [Pa] (default = 1 atm)\n\n    Returns\n    -------\n    inlet : float\n        Mole amount of inlet species [kmol]\n    outlet : float\n        Mole amount of outlet species [kmol]\n    \"\"\"\n    f = get_feed(self, moisture, fuel, air, o2, steam)\n    ## save initial composition\n    inlet = f.species_moles\n    # set desired condition\n    f.T = T\n    f.P = P\n    # calculate equilibrium\n    f.equilibrate('TP')#, solver='vcs')#, estimate_equil=1)\n    ## save final composition\n    # mole amount\n    outlet = f.species_moles\n    # FIXME: That is not possible to use labels at phaseMoles function\n    return outlet, inlet#, GasMoles, GasComposition\n\ndef simple_equilibrate_hp(self, moisture, fuel, air=zero, steam=zero, \n                          P=ct.one_atm, duty=0):\n    \"\"\"\n    Adiabatic multi-phase equilibrium calculation holding enthalpy and \n    pressure fixed.\n    \n    Use `equilibrate_hp' function for nonconventional fuels.\n\n    Parameters\n    ----------\n    self : ndarray\n        Mass fraction of fuel compounds in d.b. [kg/kg]\n    moisture : float\n        Mass fraction of moisture fuel [kg/kg]\n    fuel : float\n        Mass amount of fuel in d.b. [kg]\n    air : float\n        Mass amount of air [kg]\n    steam : float\n        Mass amount of steam [kg]\n    P : float\n        Pressure [Pa] (default = 1 atm)\n    duty : float\n        Duty fraction of outlet energy (default = 0)\n        Positive value means lost heat.\n\n    Returns\n    -------\n    content : object\n        Reactor state\n    inlet : float\n        Mole amount of inlet species [kmol]\n    outlet : float\n        Mole amount of outlet species [kmol]\n    T : float\n        Equilibrium temperature [K]\n    \"\"\"\n    f = get_feed(self, moisture, fuel, air, steam)\n    # save initial composition\n    inlet = f.species_moles\n    # get enthalpy\n    H = f.H\n    # set desired condition\n    f.P = P\n    if duty != 0: f.H = (1-duty)*H\n    # calculate equilibrium\n    f.equilibrate('HP') #, solver='vcs', max_iter=200, estimate_equil=-1)\n    # save final composition\n    outlet = f.species_moles\n    T = f.T\n    return {'content':f, 'outlet':outlet, 'T':T, 'inlet':inlet}\n\ndef equilibrate_hp(self, hfo, fuel, mw, moisture=zero, air=zero, steam=zero, \n                   P=ct.one_atm, duty=0, guess=None, solver=0, disp=0):\n    '''\n    Non-isothermic multi-phase equilibrium calculation holding enthalpy and \n    pressure fixed.\n    \n    Use `simple_equilibrate_hp' function for conventional fuels.\n\n    Parameters\n    ----------\n    self : ndarray\n        Mass fraction of fuel compounds in d.b. [kg/kg]\n    moisture : float\n        Mass fraction of moisture fuel [kg/kg]\n    fuel : float\n        Mass amount of fuel in d.b. [kg]\n    mw : float\n        Molecular weight of fuel in d.b. [kg/kmol]\n    air : float\n        Mass amount of air [kg]\n    steam : float\n        Mass amount of steam [kg]\n    P : float\n        Pressure [Pa] (default = 1 atm)\n    duty : float\n        Duty fraction of outlet energy (default = 0)\n        Positive value means lost heat.\n    guess : float\n        Guess value of temperature for equilibrium calculations [K]\n    solver : integer\n        solver = 0, default calculation\n        solver = 1, scipy calculation\n    disp : integer\n        Display status notification of calculation.\n        Default = 0, no notification.\n\n    Returns\n    -------\n    content : objet\n        Reactor state    \n    inlet : float\n        Mole amount of inlet species [kmol]\n    outlet : float\n        Mole amount of outlet species [kmol]\n    T : float\n        Equilibrium temperature [K]\n    '''\n    f = get_feed(self, moisture, fuel, air, steam)\n    mole_moisture, mole_steam = get_water(self, moisture, fuel, steam)\n    # save initial composition\n    inlet = f.species_moles\n    # get moles of fuel\n    mole_fuel = fuel/mw\n    # get moles of air species\n    mole_O2 = inlet[pp.i_O2]\n    mole_N2 = inlet[pp.i_N2]\n    mole_Ar = inlet[pp.i_Ar]    \n    # inlet enthalpy [J/kmol]\n    inlet_h = (mole_fuel*hfo + mole_moisture*(pp.Hfo_H2Ol + pp.H_vap) \\\n                + mole_O2*pp.Hfo_O2 + mole_N2*pp.Hfo_N2 + mole_Ar*pp.Hfo_Ar \\\n                + mole_steam*pp.H_vap)/(mole_fuel + mole_moisture + mole_O2 \\\n                + mole_N2 + mole_Ar + mole_steam)\n    # use default guess value\n    if guess == None: guess = pp.To\n    # equilibrium calculation at T and P constant\n    def equilibrate_tp(self, T, P):\n        self.T = T\n        self.P = P\n        self.equilibrate('TP')\n        return self\n    # set phases\n    f = equilibrate_tp(f, guess, P)\n    # choose solver\n    # 0: own solver (default) (adapted from CATON et al., 2009)\n    # 1: scipy solver (scipy.optimize.minimize_scalar)\n    if solver == 0:\n        # default solver (adapted from CATON et al., 2009)\n        # set parameters to iterative calculation\n        dT = 50 # temperature increment\n        tol = 0.01 # tolerance\n        iters = 0 # initial iteration\n        # first state\n        # enthalpy and specific heat of outlet species\n        outlet_h, outlet_cp  = get_enthalpy(f,'h,cp')\n        # duty\n        outlet_h = (1-duty)*outlet_h\n        outlet_cp = (1-duty)*outlet_cp\n        # define the error\n        T_err0 = (outlet_h - inlet_h)/outlet_cp\n        # iterative calculation\n        # estimate equilibrium temperature and product composition\n        while (abs(T_err0) > tol):\n            guess += dT\n            f = equilibrate_tp(f, guess, P)\n            outlet_h, outlet_cp  = get_enthalpy(f,'h,cp')\n            # duty\n            outlet_h = (1-duty)*outlet_h\n            outlet_cp = (1-duty)*outlet_cp\n            T_err = (outlet_h - inlet_h)/outlet_cp\n            if (cmp(T_err, 0) != cmp(T_err0, 0)): # verify change of sign\n                guess -= dT # go back to previous temperature\n                dT *= 0.5 # decrease increment\n            else:\n                # verify change of curve inclination after highest temperature\n                if (abs(T_err) > abs(T_err0)):\n                    dT *= -1 # change of increment sign\n                T_err0 = T_err # update value!\n            iters += 1 # counter\n            if iters == 200:\n                print 'maximum number of iterations reached'\n                break\n            if disp == 2: \n                print 'T = %4.2f, T_err = %0.4g, iters = %2.0f' %(guess,\n                                                                  T_err,iters)\n        if disp == 1:\n            print 'T = %4.2f, T_err = %0.4g, iters = %2.0f' %(guess,\n                                                              T_err,iters)\n        T = f.T\n        outlet = f.species_moles\n    else:\n        # alternative solver (it uses minimize_scalar method)\n        def residual(x):\n            # set phases\n            f.T = x\n            f.P = P\n            f.equilibrate('TP')\n            # outlet enthalpy [J/kmol] with duty source\n            outlet_h  = (1-duty)*get_enthalpy(f,'h')\n            return (outlet_h - inlet_h)**2\n        # estimate equilibrium temperature\n        res = opt.minimize_scalar(residual,method='bounded',bounds=(200,6000),\n                                  bracket=(residual(1200),residual(3000)))\n        # estimate equilibrium product composition\n        T = res.x[0]\n        f = equilibrate_tp(f, T, P)\n        outlet = f.species_moles\n    return {'content':f, 'outlet':outlet, 'T':T, 'inlet':inlet}\n\ndef get_fuel_db(self):\n#    fuel = get_feed(self, zero, one, zero) # 1 kg of fuel in d.b.\n    fuel = get_feed(self) # 1 kg of fuel in d.b.\n    nsp = fuel.n_species\n    sp = fuel.species_moles\n    # initiate variables\n    mol_of_C = 0\n    mol_of_H = 0\n    mol_of_O = 0\n    mol_of_S = 0\n    mol_of_Cl = 0\n    mol_of_Si = 0\n    mol_of_Ca = 0\n    mol_of_Al = 0\n    mol_of_Fe = 0\n    mol_of_Na = 0\n    mol_of_K = 0\n    mol_of_Mg = 0\n    mol_of_P = 0\n    mol_of_Ti = 0\n    mol_of_Cr = 0\n    mol_of_Ar = 0\n    mol = 0\n    # count moles of C,H,O in fuel species\n    # IMPORTANT: I have to count S, Cl and ash species for precise estimation \n    # of stoichiometric oxygen amount. This is important mainly for high ash\n    # fuels\n    for i in range(nsp):\n        if sp[i] != 0:\n#            if i != fuel.species_index('gas', 'H2O'):\n#                if i != fuel.species_index('gas', 'CO2'):\n#                    mol_of_C += sp[i] * fuel.n_atoms(i, 'C')\n#                    mol_of_H += sp[i] * fuel.n_atoms(i, 'H')\n#                    mol_of_O += sp[i] * fuel.n_atoms(i, 'O')\n            mol_of_C += sp[i] * fuel.n_atoms(i, 'C')\n            mol_of_H += sp[i] * fuel.n_atoms(i, 'H')\n            mol_of_O += sp[i] * fuel.n_atoms(i, 'O')\n            mol_of_S += sp[i] * fuel.n_atoms(i, 'S')\n            mol_of_Cl += sp[i] * fuel.n_atoms(i, 'Cl')\n            mol_of_Si += sp[i] * fuel.n_atoms(i, 'Si')\n            mol_of_Ca += sp[i] * fuel.n_atoms(i, 'Ca')\n            mol_of_Al += sp[i] * fuel.n_atoms(i, 'Al')\n            mol_of_Fe += sp[i] * fuel.n_atoms(i, 'Fe')\n            mol_of_Na += sp[i] * fuel.n_atoms(i, 'Na')\n            mol_of_K += sp[i] * fuel.n_atoms(i, 'K')\n            mol_of_Mg += sp[i] * fuel.n_atoms(i, 'Mg')\n            mol_of_P += sp[i] * fuel.n_atoms(i, 'P')\n            mol_of_Ti += sp[i] * fuel.n_atoms(i, 'Ti')\n            mol_of_Cr += sp[i] * fuel.n_atoms(i, 'Cr')\n            mol_of_Ar += sp[i] * fuel.n_atoms(i, 'Ar')\n            mol += sp[i]\n    # normalise per mole of fuel\n    mol_of_C /= mol\n    mol_of_H /= mol\n    mol_of_O /= mol\n    mol_of_S /= mol\n    mol_of_Cl /= mol\n    mol_of_Si /= mol\n    mol_of_Ca /= mol\n    mol_of_Al /= mol\n    mol_of_Fe /= mol\n    mol_of_Na /= mol\n    mol_of_K /= mol\n    mol_of_Mg /= mol\n    mol_of_P /= mol\n    mol_of_Ti /= mol\n    mol_of_Cr /= mol\n    mol_of_Ar /= mol\n    # stoichiometric moles of oxygen per mole of fuel\n    stoic = mol_of_C + 0.25*mol_of_H - 0.5*mol_of_O + mol_of_S \\\n            - 0.5*mol_of_Cl + mol_of_Si + 0.5*mol_of_Ca + 3/2*mol_of_Al \\\n            + 3/2*mol_of_Fe + 0.25*mol_of_Na + 0.25*mol_of_K + 0.5*mol_of_Mg \\\n            + 2.5*mol_of_P + mol_of_Ti + 3/2*mol_of_Cr\n    if stoic < 0:   # FIXME: Figure out the issue of a negative stoic\n                    # oxygen. This happens when there is a fuel with high\n                    # oxygen content, that is, \n                    # 0.5*mol_of_O > mol_of_C + 0.25*mol_of_H\n        stoic += 0.5*mol_of_O\n    return fuel, stoic\n\ndef enthalpy_of_formation(self, hhv):\n    '''\n    Estimate the standard enthalpy of formation of fuel [J/kg] from higher \n    heating value and species composition.\n    \n    Parameters\n    ----------\n    self : ndarray\n\n    Returns\n    -------\n    hfo : ndarray\n        standard enthalpy of formation of fuel [J/kg]\n    '''\n    f, stoic = get_fuel_db(self)\n    mol = f.species_moles # kmol\n    Mw = sum(mol*pp.Mw)\n    # standard enthalpy of formation [J/kg]\n    return (mol[pp.i_C]*pp.Hfo_CO2 + mol[pp.i_H]/2*pp.Hfo_H2Ol \\\n            + mol[pp.i_N]*pp.Hfo_N2 + mol[pp.i_S]*pp.Hfo_SO2 \\\n            + mol[pp.i_Cl]*pp.Hfo_ClO + mol[pp.i_SiO2]*pp.Hfo_SiO2 \\\n            + mol[pp.i_CaO]*pp.Hfo_CaO + mol[pp.i_Al2O3]*pp.Hfo_Al2O3 \\\n            + mol[pp.i_Fe2O3]*pp.Hfo_Fe2O3 + mol[pp.i_Na2O]*pp.Hfo_Na2O \\\n            + mol[pp.i_K2O]*pp.Hfo_K2O + mol[pp.i_MgO]*pp.Hfo_MgO \\\n            + mol[pp.i_P2O5]*pp.Hfo_P2O5 + mol[pp.i_TiO2]*pp.Hfo_TiO2 \\\n            + mol[pp.i_SO3]*pp.Hfo_SO3 + mol[pp.i_Cr2O3]*pp.Hfo_Cr2O3 \\\n            - stoic*pp.Hfo_O2 + hhv*1e6*Mw)/mol[pp.i_C]\n            \ndef mass_of_air(self, fuel, ER=1.0):\n    fuel_db, stoic = get_fuel_db(self)\n    mol_of_fuel = fuel * np.sum(self/pp.Mw_f[:-1])\n    # mole amount of gasifying agent\n    mol_of_air = ER * stoic * mol_of_fuel/0.21\n    # mass amount of gasifying agent\n    return mol_of_air * pp.Mw_air\n\ndef equivalence_ratio(self, fuel, air, o2=0):\n    fuel_db, stoic = get_fuel_db(self)\n    mol_of_fuel = fuel * np.sum(self/pp.Mw_f[:-1])\n    if air!=0 and o2==0:\n        mol_of_O2 = 0.21 * (air/pp.Mw_air)\n    elif air==0 and o2!=0:\n        mol_of_O2 = o2/pp.Mw[pp.i_O2]\n    else:\n        mol_of_O2 = 0.21 * (air/pp.Mw_air) + o2/pp.Mw[pp.i_O2]\n    return mol_of_O2/(stoic * mol_of_fuel)\n\ndef steam_to_carbon_ratio(self, fuel, steam):\n    mol = chon_moles(self, 0, fuel, 0, 0, 0)\n    mol_of_C = mol[0]\n    mol_of_steam = steam / pp.Mw[pp.i_H2O]\n    return mol_of_steam / mol_of_C\n    \ndef mass_of_steam(self, fuel, SR=0):\n    mol = chon_moles(self, 0, fuel, 0, 0, 0)\n    mol_of_C = mol[0]\n    mol_of_steam = SR * mol_of_C\n    return mol_of_steam * pp.Mw[pp.i_H2O]\n\ndef chon_moles(self, moist, fuel, air, o2, stm):\n    f = get_feed(self, moist, fuel, air, o2, stm)\n    nsp = f.n_species\n    sp = f.species_moles\n    # initiate variables\n    mol_of_C = 0\n    mol_of_H = 0\n    mol_of_O = 0\n    mol_of_N = 0\n    # count moles of C,H,O in fuel species\n    for i in range(nsp):\n        if sp[i] != 0:\n            mol_of_C += sp[i] * f.n_atoms(i, 'C')\n            mol_of_H += sp[i] * f.n_atoms(i, 'H')\n            mol_of_O += sp[i] * f.n_atoms(i, 'O')\n            mol_of_N += sp[i] * f.n_atoms(i, 'N')\n    return mol_of_C, mol_of_H, mol_of_O, mol_of_N\n    \ndef ohc_ratio(self, moist, fuel, air, o2, stm):\n    C, H, O, N = chon_moles(self, moist, fuel, air, o2, stm)\n    return H/C, O/C\n\ndef gas_yield(self, basis='vol', db='y'):\n    \"\"\"\n    Gas yield of reactor outlet.\n\n    Parameters\n    ----------\n    self : ndarray\n        Mole of products [kmol]\n    basis : string\n        Mole amount ('kmol')\n        Mass amount ('kg')\n        Normal volume amount ('Nm3')\n        Normal condition at 273.15K and 1 atm.\n    db : string\n        Dry basis ('y', default) or wet basis ('n')\n    \n\n    Returns\n    -------\n    yield : float\n        Syngas yield [kmol] [kg] [Nm3]\n    \"\"\"\n    # mole of gas species\n    mol = self[pp.s.n_species:]\n    # wet basis\n    if (db == 'n'):        \n        if (basis == 'mole'):\n            return np.sum(mol) - self[pp.i_N2]\n        if (basis == 'mass'):\n            return np.sum(mol*pp.Mw_g) - self[pp.i_N2]*pp.Mw[pp.i_N2]\n        if (basis == 'vol'):\n            return ((np.sum(mol) - self[pp.i_N2])*R*Tn)/Pn\n    # dry basis\n    if (db == 'y'):\n        if (basis == 'mole'):\n            return np.sum(mol) - self[pp.i_H2O] - self[pp.i_N2]\n        if (basis == 'mass'):\n            return np.sum(mol*pp.Mw_g) - self[pp.i_H2O]*pp.Mw[pp.i_H2O] \\\n                - self[pp.i_N2]*pp.Mw[pp.i_N2]\n        if (basis == 'vol'):\n            return ((np.sum(mol) - self[pp.i_H2O] - self[pp.i_N2])*R*Tn)/Pn\n\ndef get_species(self, species=[], eps=1e-6):\n    '''\n    Get a list of species which mole fractions in 'self' are higher than 'eps'.\n    this function is useful to find a minimum number of species to handle out a\n    chemical equilibrium problem.\n    '''\n    i = 1\n    while i < pp.nsp:\n        if self[i] > eps:\n            species_name = pp.f.species_name(i)\n            try:\n                species.index(species_name)\n            except:\n                # exclude liquid species\n                if 'L)' not in species_name:\n                    species.append(species_name)\n        i += 1\n    return species\n    \ndef get_fraction(self, species, normalized='n', db='n', eps=None):\n    '''\n    db : string\n        Dry basis ('y') or wet basis ('n', default)\n    '''\n    ## TODO: Make available for mass fraction calculation\n    idx = len(species)\n    mole = np.zeros(idx, 'd')\n    i = 0\n    while i < idx:\n        # get values\n        try:\n            mole[i] = self[pp.f.species_index('solid', species[i])]#/mole_solid\n        except:\n            mole[i] = self[pp.f.species_index('gas', species[i])]#/mole_gas\n        if eps != None:\n            # make small values as zero\n            if mole[i] < eps:\n                mole[i] = 0\n        i += 1\n    # convert mole amount to mole fraction\n    mole /= sum(self)\n    if db == 'y':\n        mole *= (1 - self[pp.i_H2O])\n    if normalized == 'y':\n        # normalize values\n        mole /= np.sum(mole)\n    return mole\n    \ndef h2co_ratio(self):\n    h2 = self[pp.f.species_index('gas', 'H2')]\n    co = self[pp.f.species_index('gas', 'CO')]\n    return h2/co\n    \ndef carbon_conversion(products, reagents):\n    return (reagents[pp.i_C] - products[pp.i_C]) / reagents[pp.i_C]\n\ndef syngas_hhv(self, fuel_mass=1.0, basis='vol'):\n    \"\"\"\n    Higher heating value of gas-phase products (syngas).\n\n    Parameters\n    ----------\n    self : ndarray\n        Mole of products [kmol]\n    fuel : float\n        Mass of fuel, w.b.\n    basis : string\n        HHV in mass fraction = 'w', mole fraction = 'm', \n        volume fraction = 'v' (default)\n\n    Returns\n    -------\n    HHV : float\n        Higher heating value in the respective basis (mass, mole, or volume), \n        d.b. [MJ/kg] [MJ/kmol] [MJ/Nm3]\n    \"\"\"\n    ns = pp.nsp\n    # preallocate variables\n    sp = []\n    hhv_i = np.zeros(ns) # will be nonzero to 'heating' species\n    # find key species\n    for i in range(ns):\n        if (i == pp.f.species_index('gas','H2') or \\\n            i == pp.f.species_index('gas','CH4') or \\\n            i == pp.f.species_index('gas','CO') #or \\\n#            i == pp.f.species_index('gas','C2H6')\n            ):\n            sp = np.append(sp, pp.f.species_name(i))\n            hhv_i[i] = pp.Hfo[i] + (pp.f.n_atoms(i,'C') \\\n            + 0.25*pp.f.n_atoms(i,'H'))*pp.Hfo[pp.i_O2] \\\n            - (pp.f.n_atoms(i,'C'))*pp.Hfo[pp.i_CO2] \\\n            # FIXME: liquid or gas water?\n            - (0.5*pp.f.n_atoms(i,'H'))*pp.Hfo[pp.i_H2O] # [J/kmol]\n    # higher heating value\n    hhv = np.sum(self*hhv_i)*1e-6 # [MJ]\n    if (basis == 'syngas mole'):\n        return hhv/gas_yield(self, db='y', basis='mole') # d.b. [MJ/kmol]\n    if (basis == 'syngas mass'):\n        return hhv/gas_yield(self, db='y', basis='mass') # d.b. [MJ/kg]\n    if (basis == 'fuel mass'):\n        return hhv/fuel_mass # [MJ/kg]\n    if (basis == 'syngas vol'):\n        return hhv/gas_yield(self, db='y', basis='vol') # d.b. [MJ/Nm3]\n\ndef syngas_lhv(self, fuel_mass=1.0):\n    \"\"\"\n    Lower heating value (LHV) of gas-phase products (syngas).\n\n    Parameters\n    ----------\n    self : ndarray\n        Mole of products [kmol]\n    fuel : float\n        Mass of fuel, w.b.\n    basis : string\n        LHV in mass fraction = 'w', mole fraction = 'm', \n        volume fraction = 'v' (default)\n\n    Returns\n    -------\n    lhv : float\n        Lower heating value [MJ/kg]\n    \"\"\"\n    lhv_CO = 10.160*pp.Mw[pp.i_CO] # MJ/kmol\n    lhv_CH4 = 49.855*pp.Mw[pp.i_CH4] # MJ/kmol\n#    lhv_C2H6 = 47.208*pp.Mw[pp.i_C2H6] # MJ/kmol\n    lhv_H2 = 120.092*pp.Mw[pp.i_H2] # MJ/kmol\n    return (lhv_CO*self[pp.i_CO] + lhv_CH4*self[pp.i_CH4] \\\n#            + lhv_C2H6*self[pp.i_C2H6] \n            + lhv_H2*self[pp.i_H2])*(1 \\\n            - self[pp.i_H2O]/gas_yield(self, db='n', basis='mole'))\n        \ndef gas_hhv(self, basis='vol'):\n    \"\"\"\n    Higher heating value of gas-phase products (fuel gas).\n\n    Parameters\n    ----------\n    self : ndarray\n        Mole of products [kmol]\n    basis : string\n        HHV in mass fraction = 'w', mole fraction = 'm', \n        volume fraction = 'v' (default)\n\n    Returns\n    -------\n    HHV : float\n        Higher heating value in the respective basis (mass, mole, or volume), \n        d.b. [MJ/kg] [MJ/kmol] [MJ/Nm3]\n    \"\"\"\n    ns = pp.nsp\n    # preallocate variables\n    sp = []\n    hhv_i = np.zeros(ns) # will be nonzero to 'heating' species\n    # find 'heating' species\n    for i in range(ns):\n        if (i == pp.f.species_index('gas','H2') or \\\n            i == pp.f.species_index('gas','CO')):\n            # Combustion of hydrogen\n            # H2 + 0.5O2 --> H2O + <<HHV>>\n            # Combustion of carbon monoxide\n            # CO + 0.5O2 --> CO2 + <<HHV>>\n            sp = np.append(sp, pp.f.species_name(i))\n            hhv_i[i] = pp.Hfo[i] + (pp.f.n_atoms(i,'C') \\\n            + 0.25*pp.f.n_atoms(i,'H'))*pp.Hfo[pp.i_O2] \\\n            - (pp.f.n_atoms(i,'C'))*pp.Hfo[pp.i_CO2] \\\n            # FIXME: liquid or gas water?\n            - (0.5*pp.f.n_atoms(i,'H'))*pp.Hfo[pp.i_H2O] # [J/kmol]\n        if (pp.f.n_atoms(i,'C') >= 1 and pp.f.n_atoms(i,'H') >= 1):\n            if (pp.f.n_atoms(i,'N') == 0 and pp.f.n_atoms(i,'O') == 0 and \\\n                pp.f.n_atoms(i,'S') == 0):\n                # Combustion of hydrocarbons\n                # CxHy + (x+0.25y)O2 --> xCO2 + 0.5yH2O + <<HHV>>\n                sp = np.append(sp, pp.f.species_name(i))\n                hhv_i[i] = pp.Hfo[i] + (pp.f.n_atoms(i,'C') \\\n                + 0.25*pp.f.n_atoms(i,'H'))*pp.Hfo[pp.i_O2] \\\n                - (pp.f.n_atoms(i,'C'))*pp.Hfo[pp.i_CO2] \\\n                # FIXME: liquid or gas water?\n                - (0.5*pp.f.n_atoms(i,'H'))*pp.Hfo[pp.i_H2O] # [J/kmol]\n    ## N2 H2 CO CH4 CO2 C2H6\n    # higher heating value\n    hhv = np.sum(self*hhv_i)*1e-6 # [MJ]\n    if (basis == 'mole'):\n        return hhv/gas_yield(self, db='y', basis='mole') # d.b. [MJ/kmol]\n    if (basis == 'mass'):\n        return hhv/gas_yield(self, db='y', basis='mass') # d.b. [MJ/kg]\n    if (basis == 'vol'):\n        return hhv/gas_yield(self, db='y', basis='vol') # d.b. [MJ/Nm3]\n\ndef mass_to_mole_fraction(self, Mw1, Mw2):\n    \"\"\"\n    Convert mass fraction to mole fraction for dual-fuel blends.\n    \n    Parameters\n    ----------\n    self : ndarray\n        Mass fraction of fuel #1 [kg/kg]\n    Mw1 : float\n        Molecular weight of fuel #1 [kg/kmol]\n    Mw2 : float\n        Molecular weight of fuel #2 [kg/kmol]\n    \n    Returns\n    -------\n    mole_fraction : ndarray\n        Mole fraction of fuel #1 [kmol/kmol]\n    \"\"\"\n    idx = len(self)\n    if (self.ndim == 1):\n        mole_fraction = self/Mw1/(self/Mw1 + (1.0 - self)/Mw2)\n    else:\n        mole_fraction = np.zeros(idx,'d')\n        for i in range(idx):\n            mole_fraction[i] = self[i]/Mw1/(self[i]/Mw1 + (1 - self[i])/Mw2)\n    return mole_fraction\n\ndef mole_to_mass_fraction(self, Mw1, Mw2):\n    \"\"\"\n    Convert mole fraction to mass fraction for dual-fuel blends.\n    \n    Parameters\n    ----------\n    self : ndarray\n        Mole fraction of fuel #1 [kmol/kmol]\n    Mw1 : float\n        Molecular weight of fuel #1 [kg/kmol]\n    Mw2 : float\n        Molecular weight of fuel #2 [kg/kmol]\n    \n    Returns\n    -------\n    mass_fraction : ndarray\n        Mass fraction of fuel #1 [kg/kg]\n    \"\"\"\n    idx = len(self)\n    if (self.ndim == 1):\n        mass_fraction = self*Mw1/(Mw2 - self(Mw1 - Mw2))\n    else:\n        mass_fraction = np.zeros(idx,'d')\n        for i in range(idx):\n            mass_fraction[i] = self[i]*Mw1/(Mw2 - self[i]*(Mw1 - Mw2))\n    return mass_fraction\n\ndef mixture(f, prop1, prop2):\n    n1 = np.size(f)\n    if (prop1.ndim <= 0):\n        prop3 = np.zeros((n1))\n        for i in range(n1):\n            prop3[i] = f[i]*prop1 + (1.0 - f[i])*prop2\n    else:\n        n2 = len(prop1)\n        prop3 = np.zeros((n1,n2))\n        for i in range(n1):\n            for j in range(n2):\n                prop3[i,j] = f[i]*prop1[j] + (1.0 - f[i])*prop2[j]\n    return prop3\n\ndef blending(f, coal, biomass):\n    \"\"\"\n    f : float\n        %wt biomass in coal-biomass blend\n    \"\"\"\n    return (1.0 - f)*coal + (f)*biomass\n\ndef avg_error(mes, sim):\n    \"\"\"\n    Return average error\n    sim : ndarray\n        simulated values\n    mes: ndarray\n        mesuared values\n    \"\"\"\n    return np.sum(np.abs(sim-mes)/mes)/len(mes)\n\ndef cold_gas_efficiency(self, fuel_lhv, moisture_fuel):\n    \"\"\"\n    Return cold gas efficiency of gasification.\n    fuel_lhv : ndarray\n        Fuel LHV\n    moisture_fuel : ndarray\n        Fuel moisture\n    \"\"\"\n    return (syngas_lhv(self, 1 + moisture_fuel)/fuel_lhv)    \n\ndef coprocessing(self, fuel_id, blend, moisture, T, P=1.0,\n                 air=0, O2=0, ER=0.4, steam=0, SR=0,\n                 small=None, db='n', normalized='n', format_='%',\n                 species=['C(gr)','N2','O2','H2','CO','CH4','CO2','H2O']):\n    \"\"\"\n    Cogasification calculations for binary blends of fuels.\n    \n    Parameters\n    ----------\n    self : ndarray\n        Mass fraction of fuel #1 [kg/kg]\n    fuel_id : list of strings\n        List of ID fuel\n    blend : float|ndarray\n        Fuel #1 to fuel #2 ratio [kg/kg]\n    moisture : float|ndarray\n        Moisture mass fraction [kg/kg]\n    T : float|ndarray\n        Temperature [degC]\n    P : float|ndarray\n        Pressure [atm] (default is 1.0)\n    air : float|ndarray\n        Air amount [kg] (default is zero)\n    O2 : float|ndarray\n        O2 amount [kg] (default is zero)\n    ER : float|ndarray\n        Equivalence ratio [kmol/kmol]\n    steam : float|ndarray\n        Steam amount [kg] (default is zero)\n    SR : float|ndarray\n        Steam to carbon ratio [kmol/kmol] (default is zero)\n        basis: 1 kg coal-biomass blend, d.b.\n    small : float\n        Smallest number to report as a fraction value (default is None)\n    db : string\n        Dry basis composition ('y') or web basis composition ('n') (default\n        is 'n')\n    normalized : string\n        Normalized compostion ('y') or overall composition ('n') (default\n        is 'n')\n    format_ : string\n        Percentual ('%') or 'ppm' compostion (default is '%')\n    species : list of strings\n        List of chemical species.\n        Default is C(gr), N2, O2, H2, CO, CH4, CO2, H2O\n    \n    Returns\n    -------\n    file : csv\n        Function return a CSV file as following data: %wt biomass ratio \n        (assuming 1st fuel as coal), %wt moisture, T (degC), P (atm), \n        equivalence ratio, steam-to-carbon ratio, O-to-C ratio, H-to-C ratio, \n        species mole fractions, H2-to-CO ratio, % carbon conversion, \n        gas yield (Nm3/kg), HHV (MJ/kg), % cold gas efficiency        \n    \"\"\"\n    # convert all values to array\n    blend *= one\n    moisture *= one\n    T *= one\n    P *= one\n    air *= one\n    O2 *= one\n    ER *= one\n    steam *= one\n    SR *= one\n    # default values\n    steam_ = 0\n    SR_ = 0\n    air_ = 0\n    o2_ = 0\n    ER_ = 0\n    # get number of points\n    n_0 = np.size(fuel_id)\n    n_1 = np.size(blend)\n    n_2 = np.size(moisture)\n    n_3 = np.size(T)\n    n_4 = np.size(P)\n    \n    if np.size(air) > 1:\n        n_5 = np.size(air)\n    elif np.size(O2) > 1:\n        n_5 = np.size(O2)\n    elif np.size(ER) > 1:\n        n_5 = np.size(ER)\n    else:\n        n_5 = 1\n        \n    if np.size(steam) > 1:\n        n_6 = np.size(steam)\n    elif np.size(SR) > 1:\n        n_6 = np.size(SR)\n    else:\n        n_6 = 1\n        \n    if format_ == 'ppm':\n        ft = 1e6\n    else:\n        ft = 1e2\n#    # start count minimum number of species\n#    minimum_species = []\n    # start calculations\n    for i in range(n_0-1): # asssumed 1st fuel as coal\n        csvfile = open(str(fuel_id[0]) + '-' + str(fuel_id[i+1]) + '.csv','w')\n        f = csv.writer(csvfile)\n        f.writerow(['% BR','% MC','T (C)','P (atm)','ER','SR','O/C',\n                    'H/C'] + species + ['H2/CO','% CC','Y (Nm3/kg)',\n                    'HHV (MJ/kg)','% CGE'])\n        for j in range(n_1): # %coal-biomass blend\n            frac = blending(blend[j], self[0,:], self[i+1,:])\n            for k in range(n_2): # moisture\n                # get lhv to each moisture content of fuels\n                fuel_lhv = feedstock.heating_values(fuel_id,moisture[k])['LHV']\n                for l in range(n_3): # temperature\n                    for m in range(n_4): # pressure\n                        for o in range(n_5): # equivalence ratio\n                            if air.any() != 0:\n                                air_ = air[o]\n                                o2_ = 0\n                                ER_ = equivalence_ratio(frac, 1.0, air[o])\n                            elif O2.any() != 0:\n                                air_ = 0\n                                o2_ = O2[o]\n                                ER_ = equivalence_ratio(frac, 1.0, 0, O2[o])\n                            elif ER.any() != 0:\n                                air_ = mass_of_air(frac, 1.0, ER[o])\n                                o2_ = 0\n                                ER_ = ER[o]\n                            for q in range(n_6): # steam-to-carbon ratio\n                                if SR.any() != 0:\n                                    steam_ = mass_of_steam(frac, 1.0, SR[q])\n                                    SR_ = SR[q]\n                                elif steam.any() != 0:\n                                    steam_ = steam[q]\n                                    SR_ = steam_to_carbon_ratio(frac, 1.0, \n                                                                steam[q])\n                                hc,oc = ohc_ratio(frac, moisture[k], 1.0, \n                                                  air_, o2_, steam_)\n                                p,r = equilibrate_tp(frac, moisture[k], 1.0, \n                                                     air_, o2_, steam_, \n                                                     T[l]+273.15,\n                                                     ct.one_atm*P[m])\n                                fuel_lhv_ = blending(blend[j], fuel_lhv[0], \n                                                     fuel_lhv[i+1])\n                                syngas_lhv_ = syngas_lhv(p, 1 + moisture[k])\n                                eff = syngas_lhv_/fuel_lhv_\n                                hhv = syngas_hhv(p, basis='fuel mass', \n                                                 fuel_mass=1+moisture[k])\n                                h2co = h2co_ratio(p)\n                                cc = carbon_conversion(p,r)\n                                y = gas_yield(p, basis='vol', db='y') # per kg\n                                syngas = get_fraction(p, species, eps=small,\n                                                      db=db, \n                                                      normalized=normalized)\n                                f.writerow([100*blend[j], 100*moisture[k],\n                                            T[l], P[m], ER_,\n                                            SR_, oc, hc] + list(ft*syngas) \n                                            + [h2co, 100*cc, y, hhv, 100*eff])\n#                                minimum_species = get_species(p, \n#                                                              minimum_species, \n#                                                              eps=1e-6)\n        csvfile.close()\n#        print minimum_species\n        print 'Blend #' + str(i+1) + ' (' + str(fuel_id[0]) + '-' \\\n              + str(fuel_id[i+1]) + '): DONE'                    \n    return None\n\ndef coprocessing1(self, fuel_id, blend, moisture, T, P=1.0,\n                  air=0, O2=0, ER=0.4,\n                  steam=0, SR=0,\n                  small=None, db='n', normalized='n',\n                  species=['C(gr)','N2','O2','H2','CO','CH4','CO2','H2O']):\n    \"\"\"\n    Cogasification calculations for binary blends of fuels.\n    \n    Parameters\n    ----------\n    self : ndarray\n        Mass fraction of fuel #1 [kg/kg]\n    fuel_id : list of strings\n        List of ID fuel\n    blend : float|ndarray\n        Fuel #1 to fuel #2 ratio [kg/kg]\n    moisture : float|ndarray\n        Moisture mass fraction [kg/kg]\n    T : float|ndarray\n        Temperature [degC]\n    P : float|ndarray\n        Pressure [atm] (default is 1.0)\n    air : float|ndarray\n        Air amount [kg] (default is zero)\n    O2 : float|ndarray\n        O2 amount [kg] (default is zero)\n    ER : float|ndarray\n        Equivalence ratio [kmol/kmol]\n    steam : float|ndarray\n        Steam amount [kg] (default is zero)\n    SR : float|ndarray\n        Steam to carbon ratio [kmol/kmol] (default is zero)\n        basis: 1 kg coal-biomass blend, d.b.\n    small : float\n        Smallest number to report as a fraction value (default is None)\n    db : string\n        Get dry basis composition ('y') or web basis composition ('n') (default\n        is 'y')\n    normalized : string\n        Get normalized compostion ('y') or overall composition ('n') (default\n        is 'y')\n    species : list of strings\n        List of chemical species.\n        Default is N2, O2, H2, CO, CH4, CO2, H2O\n    \n    Returns\n    -------\n    file : csv\n        Function return a CSV file as following data: %wt biomass ratio \n        (assuming 1st fuel as coal), %wt moisture, T (degC), P (atm), \n        equivalence ratio, steam-to-carbon ratio, O-to-C ratio, H-to-C ratio, \n        species mole fractions, H2-to-CO ratio, % carbon conversion, \n        gas yield (Nm3/kg), HHV (MJ/kg), % cold gas efficiency        \n    \"\"\"\n    # convert all values to array\n    blend *= one\n    moisture *= one\n    T *= one\n    air *= one\n    O2 *= one\n    ER *= one\n    steam *= one\n    SR *= one\n    # get number of points\n    n_0 = np.size(fuel_id)\n    n_1 = np.size(blend)    \n    # start calculations\n    for i in range(n_0-1): # asssumed 1st fuel as coal\n        csvfile = open(str(fuel_id[0]) + '-' + str(fuel_id[i+1]) + '.csv','w')\n        f = csv.writer(csvfile)\n        f.writerow(['% BR','% MC','T (C)','P (atm)','ER','SR','O/C',\n                    'H/C'] + species + ['H2/CO','% CC','Y (Nm3/kg)',\n                    'HHV (MJ/kg)','% CGE'])\n        for j in range(n_1): # %coal-biomass blend\n            frac = blending(blend[j], self[0,:], self[i+1,:])\n            # get lhv to each moisture content of fuels\n            fuel_lhv = feedstock.heating_values(fuel_id, moisture[j])['LHV']\n            if air.any() != 0:\n                air_ = air[j]\n                o2_ = 0\n                ER_ = equivalence_ratio(frac, 1.0, air[j])\n            elif O2.any() != 0:\n                air_ = 0\n                o2_ = O2[j]\n                ER_ = equivalence_ratio(frac, 1.0, 0, O2[j])\n            elif ER.any() != 0:\n                air_ = mass_of_air(frac, 1.0, ER[j])\n                o2_ = 0\n                ER_ = ER[j]\n            else:\n                air_ = 0\n                o2_ = 0\n                ER_ = 0\n            if SR.all() != 0:\n                steam_ = mass_of_steam(frac, 1.0, SR[j])\n                SR_ = SR[j]\n            elif steam.all() != 0:\n                steam_ = steam[j]\n                SR_ = steam_to_carbon_ratio(frac, 1.0, steam[j])\n            else:\n                steam_ = 0\n                SR_ = 0\n            hc, oc = ohc_ratio(frac, moisture[j], 1.0, air_, o2_, steam_)\n            p, r = equilibrate_tp(frac, moisture[j], 1.0, air_, o2_, steam_, \n                                  T[j]+273.15, ct.one_atm*P)\n            fuel_lhv_ = blending(blend[j], fuel_lhv[0], fuel_lhv[i+1])\n            syngas_lhv_ = syngas_lhv(p, 1 + moisture[j])\n            eff = 100*syngas_lhv_/fuel_lhv_\n            hhv = syngas_hhv(p, basis='fuel mass', fuel_mass=1+moisture[j])\n            h2co = h2co_ratio(p)\n            cc = 100*carbon_conversion(p, r)\n            y = gas_yield(p, basis='vol', db='y') # per kg\n            syngas = get_fraction(p, species, eps=small, \n                                  db=db, normalized=normalized)\n            f.writerow([100*blend[j], 100*moisture[j], T[j], P, ER_, SR_, \n                        oc, hc] + list(100*syngas) + [h2co, cc, y, hhv, eff])\n        csvfile.close()\n        print 'Blend #' + str(i+1) + ' (' + str(fuel_id[0]) + '-' \\\n              + str(fuel_id[i+1]) + '): DONE'                    \n    return None\n", "meta": {"hexsha": "d14ebf5eef7859cd91fe9bda3df5429d4d5ffa55", "size": 41597, "ext": "py", "lang": "Python", "max_stars_repo_path": "gasifier.py", "max_stars_repo_name": "rodolfo-enq/gasification", "max_stars_repo_head_hexsha": "696cb4cf1d1a27c1b5ab7c328da1c44868a165d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-12-21T13:28:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T16:34:00.000Z", "max_issues_repo_path": "gasifier.py", "max_issues_repo_name": "rodolfo-enq/gasification", "max_issues_repo_head_hexsha": "696cb4cf1d1a27c1b5ab7c328da1c44868a165d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gasifier.py", "max_forks_repo_name": "rodolfo-enq/gasification", "max_forks_repo_head_hexsha": "696cb4cf1d1a27c1b5ab7c328da1c44868a165d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-21T15:24:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T19:15:20.000Z", "avg_line_length": 35.0143097643, "max_line_length": 80, "alphanum_fraction": 0.523523331, "include": true, "reason": "import numpy,import scipy", "num_tokens": 12208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.1887975415103319}}
{"text": "# coding:utf-8\nimport functools\nimport logging\nimport time\nimport copy\nimport json\nimport math\nimport importlib\n\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport numpy as np\nfrom torch.autograd import Variable\n\nfrom .... import extensions as E\nfrom ..utils.pair_helper import cal_iou\nfrom ..utils.bbox_helper import clip_bbox\nfrom ..utils import loss as L\nfrom ..utils import accuracy as A\nfrom ..utils.assigner import map_rois_to_level\nfrom ...initializer import initialize_from_cfg, init_weights_normal\nfrom .pair import compute_proposal_targets, predict_assos\nfrom .matcher import SingleFramePostProcessorFactory\nfrom .position import PositionTransform, PositionEmbedding\nfrom .ibconv import build_ibconv\nfrom unn.models.backbones.resnext_syncbn import ResNeXtBottleneck\nfrom unn.models.attentions.siamese_attention import SiameseAttention\nfrom unn.models.attentions.siamese_attention import SiameseAttentionPlus\nfrom unn.models.functions.embedding import BoxPositionEmbedding\nfrom unn.models.functions.embedding import ImagePositionEmbedding\n\nimport pdb\n\n__all__ = ['GeneralAssociation', 'LowdimAssociation', 'MaskAssociation','AttentionAssociation', 'RelationAttention', 'PosRelationAttention']\n\nlogger = logging.getLogger('global')\n\ndef to_np_array(x):\n    if isinstance(x, Variable): x = x.data\n    return x.cpu().float().numpy() if torch.is_tensor(x) else x\n\n\ndef parse_bbox(file_path):\n    all_bbox = {}\n    for line in open(file_path):\n        content = json.loads(line)\n        if not \"bbox\" in content:\n            continue\n        image_id = content[\"image_id\"]\n        if image_id[-4] != \".\":\n            image_id = image_id + \".jpg\"\n        #content['score'] = 8.4 / (1 + math.exp(12.0 -content['score'] * 10.0))\n        bbox = [0] + content[\"bbox\"] + [content[\"score\"]] + [content[\"label\"]]\n        if not image_id in all_bbox:\n            all_bbox[image_id] = []\n        all_bbox[image_id].append(bbox)\n    for image_id in all_bbox.keys():\n        all_bbox[image_id] = np.array(all_bbox[image_id])\n        return all_bbox\n\n        super(PairWiseNet, self).__init__()\n        self.origin_cfg = copy.deepcopy(cfg)\n        self.cfg = copy.deepcopy(cfg)\n        self.tocaffe = self.cfg.get('tocaffe', False)\n        self.cfg['num_classes'] = num_classes\n        self.num_classes = num_classes\n        if isinstance(inplanes, list):\n            assert len(inplanes) == 1, 'single input is expected, but found:{} '.format(inplanes)\n            inplanes = inplanes[0]\n        assert isinstance(inplanes, int)\n        self.inplanes = inplanes\n        self.roipool = E.build_generic_roipool(cfg['roipooling'])\n        self.pool_size = cfg['roipooling']['pool_size']\n        self.position_score = cfg.get('position_score', False)\n        self.single_mdim = self.pool_size * self.pool_size * inplanes\n        if self.cfg.get('pre_fc', None):\n            self.pre_fc = nn.Linear(self.single_mdim, self.cfg['pre_fc'])\n            self.single_mdim = self.cfg['pre_fc']\n        else:\n            self.pre_fc = None\n        self.mdim = self.single_mdim * 2\n        self.union_box = self.cfg.get('union_box', False)\n        if self.cfg.get('use_precompute_box', None) is not None:\n            self.pre_bbox = parse_bbox(self.cfg[\"use_precompute_box\"])\n        else:\n            self.pre_bbox = None\n        self.important_weight = self.cfg['important_weight']\n        assert(0 <= self.important_weight <= 1)\n        self.hand_bbox = {}\n        for filename in self.cfg[\"important_hands\"]:\n            self.parse_gt_bbox(filename)\n        if not self.cfg.get('position', None) is None:\n            # Only use position transform\n            if self.cfg['position'] == 'naive':\n                self.mdim += 14\n            elif self.cfg['position'] == 'embedding':\n            # Use position embedding, each element will be mapped to high dimension\n                self.mdim += 14 * 256\n            else:\n                self.position_fc1 = nn.Linear(self.pool_size * self.pool_size * inplanes, 1024)\n                self.position_relu = nn.ReLU(inplace=True)\n                self.position_fc2 = nn.Linear(1024, 1024)\n                self.position_fc3 = nn.Linear(1024, 14 * 256)\n                self.mdim += 14 * 256\n        self.predict_kernel = self.cfg.get('predict_kernel', None)\n        if self.predict_kernel is not None:\n            self.ibconv = build_ibconv(self.inplanes, self.pool_size, self.cfg)\n            \n            \n        if self.cfg.get('similarity', False):\n            # Use vector dot operation to assess the similarity\n            self.mdim += self.single_mdim\n        if self.union_box:\n            self.mdim += self.single_mdim\n    \n        if self.cfg.get('use_filter', None):\n            asso_triplet = []\n            filename = cfg.get('use_filter')\n            with open(filename, 'r') as f:\n                lines = f.readlines()\n                for line in lines:\n                    mp = json.loads(line.strip())\n                    asso_triplet.append(mp)\n            self.origin_cfg['asso_triplet'] = asso_triplet\n        if self.cfg.get('pre_filter', None) is not None:\n            self.pre_filter = json.loads(open(self.cfg['pre_filter']).readlines()[0])\n        self.cls_mdim = 0\n        self.keep_origin_feature = False\n        self.use_rpn = False\n        self.output_predict = self.origin_cfg.get('output_predict', False)\n        if self.cfg.get('binary_mask', None) is not None:\n            self.binary_mask = json.loads(open(self.cfg['binary_mask']).readlines()[0])\n            bbox_num = self.cfg['num_bbox_classes']\n            self.binary_scale = [[0 for _ in range(self.num_classes)] for __ in range(bbox_num)]\n            for k in self.binary_mask.keys():\n                v = self.binary_mask[k]\n                for item in v:\n                    self.binary_scale[k][item] = 1\n            self.binary_scale = torch.cuda.FloatTensor(self.binary_scale)\n        else:\n            self.binary_mask = None\n        if self.cfg.get('element_wise_sum', False):\n            self.mdim = self.single_mdim\n\n\n    def parse_gt_bbox(self, file_path):\n        for line in open(file_path):\n            content = json.loads(line)\n            filename = content['filename']\n            assos = content['associations']\n            hand_bbox = []\n            for asso in assos:\n                if asso['label2'] in [3, 4]:\n                    hand_bbox.append(asso['bbox2'])\n            self.hand_bbox[filename] = hand_bbox\n\n    def transform_aug_bbox(self, input, b_ix):\n        bbox = self.hand_bbox.get(input['filename'][b_ix], None)\n        if bbox is None or len(bbox) == 0:\n            return None\n        tmp_bboxes = np.array(bbox)\n        scale_factor = input[\"image_info\"][b_ix][2]\n        flipped = input[\"image_info\"][b_ix][5]\n        image_w = input[\"image_info\"][b_ix][1]\n        scale_factor = to_np_array(scale_factor)\n        image_w = to_np_array(image_w)\n        tmp_bboxes *= scale_factor\n\n        if flipped:\n            x1 = tmp_bboxes[:, 0].copy()\n            x2 = tmp_bboxes[:, 2].copy()\n            tmp_bboxes[:, 0] = image_w - 1 - x2\n            tmp_bboxes[:, 2] = image_w - 1 - x1\n        return tmp_bboxes\n\n\n    def calIoU(self, b1, b2):\n        area1 = (b1[:, 2] - b1[:, 0]) * (b1[:, 3] - b1[:, 1])\n        area2 = (b2[:, 2] - b2[:, 0]) * (b2[:, 3] - b2[:, 1])\n        inter_xmin = np.maximum(b1[:, 0].reshape(-1, 1), b2[:, 0].reshape(1, -1))\n        inter_ymin = np.maximum(b1[:, 1].reshape(-1, 1), b2[:, 1].reshape(1, -1))\n        inter_xmax = np.minimum(b1[:, 2].reshape(-1, 1), b2[:, 2].reshape(1, -1))\n        inter_ymax = np.minimum(b1[:, 3].reshape(-1, 1), b2[:, 3].reshape(1, -1))\n        inter_h = np.maximum(inter_xmax - inter_xmin, 0)\n        inter_w = np.maximum(inter_ymax - inter_ymin, 0)\n        inter_area = inter_h * inter_w\n        union_area1 = area1.reshape(-1, 1) + area2.reshape(1, -1)\n        union_area2 = (union_area1 - inter_area)\n        return inter_area / np.maximum(union_area2, 1)\n\n\n    def check_is_focus_hand(self, cls, bbox, gt_assos):\n        if cls != 3:\n            return True\n        if gt_assos.shape[0] == 0:\n            return False\n        \n        iou = self.calIoU(bbox.reshape(-1, 4), gt_assos[:,8:12]).reshape(-1)\n        return iou.max() > 0.5\n\n\n    def check_is_first(self, cls):\n        if self.cfg.get('pair_method', None) is not None:\n            if not 'first' in self.cfg['pair_method']:\n                return cls > 0\n            else:\n                return cls in self.cfg['pair_method']['first']\n        return cls > 0\n\n    def check_is_second(self, cls):\n        if self.cfg.get('pair_method', None) is not None:\n            if not 'second' in self.cfg['pair_method']:\n                return cls > 0\n            else:\n                return cls in self.cfg['pair_method']['second']\n        return cls > 0\n    \n    def generate_pair(self, rois, input):\n        '''\n        return value pair_rois: [N,K] batch_ix, rois_1 idx, rois_2 idx\n        '''\n        rois = to_np_array(rois)\n        B = max(rois[:, 0].astype(np.int32)) + 1\n        pair_rois = []\n        pair_position = []\n        rois1 = []\n        rois2 = []\n        nrois = np.array(copy.deepcopy(rois))\n        for b_ix in range(B):\n            rois1_ix = []\n            rois2_ix = []\n            b_first_cnt = 0\n            b_second_cnt = 0\n            for i in range(nrois.shape[0]):\n                # All body bbox\n                if int(nrois[i,0]) == b_ix and self.check_is_first(int(rois[i, 6])):\n                    rois1_ix.append(i)\n                    b_first_cnt += 1\n                    if self.cfg.get('pre_top_n', None):\n                        if b_first_cnt > self.cfg['pre_top_n']:\n                            break\n                # All the other bbox\n                if int(nrois[i,0]) == b_ix and self.check_is_second(int(rois[i, 6])):\n                    rois2_ix.append(i)\n                    b_second_cnt += 1\n                    if self.cfg.get('pre_top_n', None):\n                        if b_second_cnt > self.cfg['pre_top_n']:\n                            break\n            # filter no focus on hands\n           # if self.training:  ## training stage\n            #    gt_assos = to_np_array(input['gt_assos'][b_ix])\n            #    gt_assos = gt_assos[gt_assos[:, -1] == 2]\n            #    new_rois2_ix = []\n            #    for i in rois2_ix:\n            #        if self.check_is_focus_hand(int(rois[i, 6]), rois[i, 1:5], gt_assos):\n            #            new_rois2_ix.append(i)\n            #    rois2_ix = new_rois2_ix\n                \n            # For avoiding runtime error\n            if len(rois1_ix) == 0:\n                rois1_ix.append(0)\n            if len(rois2_ix) == 0:\n                rois2_ix.append(0)\n            rois1_ix = np.array(rois1_ix)\n            rois2_ix = np.array(rois2_ix)\n            N = len(rois1_ix)\n            M = len(rois2_ix)\n            batch_pair_rois = np.zeros((N * M, 3))\n            batch_pair_position = np.zeros((N * M, 5))\n            batch_pair_rois[:, 1: 3] = np.stack(np.meshgrid(rois1_ix, rois2_ix), axis=2).reshape(-1,2)\n            batch_pair_rois[:, 0] = b_ix\n            batch_pair_position[:, 0] = b_ix\n            batch_rois1 = nrois[batch_pair_rois[:,1].astype(np.int32)]\n            batch_rois2 = nrois[batch_pair_rois[:,2].astype(np.int32)]\n            batch_pair_position[:, 1] = np.minimum(batch_rois1[:, 1], batch_rois2[:, 1])\n            batch_pair_position[:, 2] = np.minimum(batch_rois1[:, 2], batch_rois2[:, 2])\n            batch_pair_position[:, 3] = np.maximum(batch_rois1[:, 3], batch_rois2[:, 3])\n            batch_pair_position[:, 4] = np.maximum(batch_rois1[:, 4], batch_rois2[:, 4])\n            pair_rois.append(batch_pair_rois)\n            pair_position.append(batch_pair_position)\n            rois1.append(batch_rois1)\n            rois2.append(batch_rois2)\n        pair_rois = np.vstack(pair_rois)\n        pair_position = np.vstack(pair_position)\n        rois1 = np.vstack(rois1)\n        rois2 = np.vstack(rois2)\n        pair_filter = []\n        position_filter = []\n        rois1_filter = []\n        rois2_filter = []\n        # pre-process, suppress the pairs whose object is far away from the body bbox\n        #ratio = 0.2\n        for i, pair in enumerate(pair_rois):\n            idx1 = int(pair[1])\n            idx2 = int(pair[2])\n            '''\n            body_x1, body_y1, body_x2, body_y2 = rois[idx1][1:5]\n            w = body_x2 - body_x1\n            h = body_y2 - body_y1\n            body_x1 = max(body_x1 - w * ratio, 0)\n            body_y1 = max(body_y1 - h * ratio, 0)\n            body_x2 = body_x2 + w * ratio\n            body_y2 = body_y2 + h * ratio\n            '''\n            xmax = max(rois[idx1][1], rois[idx2][1])\n            xmin = min(rois[idx1][3], rois[idx2][3])\n            ymax = max(rois[idx1][2], rois[idx2][2])\n            ymin = min(rois[idx1][4], rois[idx2][4])\n            '''\n            xmax = max(body_x1, rois[idx2][1])\n            xmin = min(body_x2, rois[idx2][3])\n            ymax = max(body_y1, rois[idx2][2])\n            ymin = min(body_y2, rois[idx2][4])\n            '''\n            cross = max(xmin - xmax, 0) * max(ymin - ymax, 0)\n            area = (rois[idx2][3] - rois[idx2][1]) * (rois[idx2][4] - rois[idx2][2])\n            ioa = cross / (area + 0.1)\n            label1 = rois1[i][6].astype(np.int32)\n            label2 = rois2[i][6].astype(np.int32)\n            # IOA filter \n            if ioa > self.cfg.get('ioa_threshold', -1) or i == 0:\n                # Pre filter\n                if self.cfg.get('pre_filter', None) is None or (str(label1) in self.pre_filter and label2 in self.pre_filter[str(label1)]) or i == 0:\n                    pair_filter.append(pair)\n                    position_filter.append(pair_position[i])\n                    rois1_filter.append(rois1[i])\n                    rois2_filter.append(rois2[i])\n        if self.cfg.get('ioa_threshold', None) is not None or self.cfg.get('pre_filter', None) is not None:\n            pair_rois = np.array(pair_filter)\n            pair_position = np.array(position_filter)\n            rois1 = np.array(rois1_filter)\n            rois2 = np.array(rois2_filter)\n        return pair_rois, rois1, rois2, pair_position\n\n    def print_param(self, feature, file_path):\n        '''\n        print param during tocaffe method\n        '''\n        return\n        res_file = open(file_path, 'w')\n        temp_feature = feature.view(-1)\n        res_file.write(str(temp_feature.shape) + '\\n')\n        for i in range(len(temp_feature)):\n            res_file.write(str(temp_feature[i].cpu().detach().numpy().tolist()) + '\\n')\n        res_file.close()\n    \n    def create_table(self, pair_rois):\n        '''\n        map two rois idx to pair idx\n        '''\n        roiTable = {}\n        N = pair_rois.shape[0]\n        for i in range(N):\n            x = int(pair_rois[i][1])\n            y = int(pair_rois[i][2])\n            roiTable[(x,y)] = i\n        return roiTable\n\n    def forward(self, input):\n        prefix = 'PairWiseNet'\n        mode = input.get('runner_mode', 'val')\n        self.cfg = copy.deepcopy(self.origin_cfg)\n        if mode in self.cfg:\n            self.cfg.update(self.cfg[mode])\n        else:\n            self.cfg.update(self.cfg.get('val', {}))\n        output = {}\n        if self.pre_bbox is not None:\n            B = len(input['filename'])\n            dt_bboxes = []\n            for b_ix in range(B):\n                tmp_bboxes = copy.deepcopy(self.pre_bbox[input['filename'][b_ix]])\n                tmp_bboxes = torch.cuda.HalfTensor(tmp_bboxes)\n                scale_factor = input[\"image_info\"][b_ix][2]\n                flipped = input[\"image_info\"][b_ix][5]\n                image_w = input[\"image_info\"][b_ix][1]\n                tmp_bboxes[:, 1: 5] *= scale_factor.half()\n                tmp_bboxes[:, 0] = b_ix\n                if flipped:\n                    x1 = tmp_bboxes[:, 1].clone()\n                    x2 = tmp_bboxes[:, 3].clone()\n                    tmp_bboxes[:, 1] = image_w.half() - 1 - x2\n                    tmp_bboxes[:, 3] = image_w.half() - 1 - x1\n                dt_bboxes.append(tmp_bboxes)\n            input['dt_bboxes'] = torch.cat(dt_bboxes, dim=0)\n        if self.training:\n            if input['gt_assos'][0][0][2] > 0:\n                sv = 1\n            elif self.cfg.get('ignore_false_example', False):\n                sv = 0\n            else:\n                sv = 1\n            if not 'dt_bboxes' in input or input['dt_bboxes'].shape[0] == 0:\n                input['dt_bboxes'] = torch.HalfTensor([[0, 0, 0, 0, 0, 0.0, 1]]).cuda()\n            loss, acc, predict_vector, predict_target = self.get_loss(input)\n            if predict_vector is not None:\n                output[prefix + '.predict_vector'] = predict_vector\n                output[prefix + '.predict_target'] = predict_target\n            for k, v in loss.items():\n                output[prefix + k] = v * sv\n            for k, v in acc.items():\n                output[prefix + k] = v\n        else:\n            if not 'dt_bboxes' in input or input['dt_bboxes'].shape[0] == 0:\n                if self.tocaffe:\n                    input['dt_bboxes'] = torch.FloatTensor([[0, 0, 0, 0, 0, 0.0, 1]])\n                else:\n                    input['dt_bboxes'] = torch.HalfTensor([[0, 0, 0, 0, 0, 0.0, 1]]).cuda()\n            assos, pred_cls = self.get_assos(input)\n            if self.tocaffe:\n                output[prefix + '.blobs.classification'] = pred_cls\n            output['dt_bboxes'] = input['dt_bboxes']\n            output['dt_assos'] = assos\n            if self.cfg.get('post_processor', None) is not None:\n                processor = SingleFramePostProcessorFactory.create(self.cfg['post_processor'])\n                output = processor.process(output)\n        return output\n\n    def roi_pooling(self, rois, x, stride, image_info):\n        #pdb.set_trace()\n        feature = self.roipool(rois[:,0:5], x, stride)\n        if self.keep_origin_feature and self.pre_fc is None:\n            return feature\n        c = feature.numel() // feature.shape[0]\n        feature = feature.view(-1, c).contiguous()\n        if self.pre_fc is not None:\n            feature = self.pre_fc(feature)\n        return feature\n\n    def mlvl_predict(self, x_rois, x_features, x_strides, levels, image_info):\n        #pdb.set_trace()\n        mlvl_pred_feature = []\n        for lvl_idx in levels:\n            #logger.info(str(lvl_idx) + \" \" + str(x_rois[lvl_idx].shape[0]))\n            if x_rois[lvl_idx].shape[0] > 0:\n                rois = x_rois[lvl_idx]\n                feature = x_features[lvl_idx]\n                stride = x_strides[lvl_idx]\n                pred_feature = self.roi_pooling(rois, feature, stride, image_info)\n                mlvl_pred_feature.append(pred_feature)\n        pred_feature = torch.cat(mlvl_pred_feature, dim=0)\n        return pred_feature\n        \n    def extract_feature(self, rois, input, keep_rois=False):\n        '''\n        rois is original rois\n        '''\n        #pdb.set_trace()\n        x_features = input['features']\n        x_strides = input['strides']\n        image_info = input['image_info']\n        for i in range(len(x_features)):\n            feature = x_features[i]\n            if self.tocaffe:\n                self.print_param(feature, 'fpn' +  str(i) + '.txt')\n        if self.cfg.get('fpn', None):\n            fpn = self.cfg['fpn']\n            if self.tocaffe and not self.training:\n                mlvl_rois, recover_inds = [rois] * len(fpn['fpn_levels']), None\n            else:\n                if not keep_rois:\n                    mlvl_rois, recover_inds = map_rois_to_level(fpn['fpn_levels'], fpn['base_scale'], rois, original_inds=True)\n                    rois = to_np_array(rois[recover_inds])\n                else:\n                    mlvl_rois, recover_inds = map_rois_to_level(fpn['fpn_levels'], fpn['base_scale'], rois)\n                    rois = to_np_array(rois)\n            pred_feature = self.mlvl_predict(\n                mlvl_rois, x_features, x_strides, fpn['fpn_levels'], image_info)\n            if keep_rois and not self.tocaffe:\n                pred_feature = pred_feature[recover_inds]\n            \n        else:\n            assert len(x_features) == 1 and len(x_strides) == 1\n            pred_feature  = self.roi_pooling(rois, x_features[0], x_strides[0], image_info)\n        return rois, pred_feature\n    \n    def extract_relation_feature(self, rois, pair_rois, pair_position, input):\n        #pdb.set_trace()\n        rois1 = copy.deepcopy(rois)\n        rois1, pred_rois1_feature = self.extract_feature(rois1, input, keep_rois=True)\n        if self.tocaffe:\n            # use CPU method\n            rois1_feature = pred_rois1_feature.index_select(0, torch.LongTensor(pair_rois[:, 1])).contiguous()\n            rois2_feature = pred_rois1_feature.index_select(0, torch.LongTensor(pair_rois[:, 2])).contiguous()\n        else:\n            rois1_feature = pred_rois1_feature.index_select(0, torch.cuda.LongTensor(pair_rois[:, 1])).contiguous()\n            rois2_feature = pred_rois1_feature.index_select(0, torch.cuda.LongTensor(pair_rois[:, 2])).contiguous()\n        if self.predict_kernel:\n            rois2_feature = self.ibconv(rois1_feature, rois1, pair_rois, input)\n\n        # rois1_feature is body feature\n        # rois2_feature is object feature\n        pred_human_feature = rois1_feature\n        features = [rois1_feature, rois2_feature] \n        if self.union_box:\n            _, union_feature = self.extract_feature(torch.Tensor(pair_position).type_as(rois1_feature), input, keep_rois=True)\n            features.append(union_feature)\n        if not self.cfg.get('position', None) is None:\n            # add position feature\n            position_feature = PositionTransform(rois1[pair_rois[:,1].astype(np.int32)], rois1[pair_rois[:,2].astype(np.int32)], input['image_info'])\n            if self.cfg['position'] == 'embedding' or self.cfg['position'] == 'embedding app':\n                position_feature = PositionEmbedding(position_feature, 256)\n                if self.cfg['position'] == 'embedding app':\n                    app_feature = self.position_relu(self.position_fc1(pred_human_feature))\n                    app_feature = self.position_relu(self.position_fc2(app_feature))\n                    app_feature = self.position_relu(self.position_fc3(app_feature))\n                    position_feature = position_feature * app_feature\n\n            features.append(position_feature)\n        if self.cfg.get('similarity', False):\n            # add similarity feature\n            features.append(rois1_feature * rois2_feature)\n        if self.keep_origin_feature:\n            return features\n        if self.cfg.get('element_wise_sum', False):\n            pred_pair_feature = features[0]\n            for i in range(1, len(features)):\n                pred_pair_feature = pred_pair_feature + features[i]\n        else:\n            pred_pair_feature = torch.cat(features, dim=1)\n        if self.tocaffe:\n            self.print_param(pred_pair_feature, 'concat167.txt')\n        return pred_pair_feature\n\n    def binary_predict(self, x, rois1=None, rois2=None, union_rois=None):\n        raise NotImplementedError\n\n    def predict(self, x, rois1=None, rois2=None, union_rois=None, input=None):\n        raise NotImplementedError\n\n    def load_box(self, path):\n        # load given bbox \n        fin = open(path, \"r\")\n        contents = fin.readlines()\n        rois = []\n        for line in contents:\n            anno = json.loads(line)\n            tmp = [0]\n            box = anno[\"bbox\"]\n            for item in box:\n                #tmp.append(item * 13.0 / 40.0)\n                tmp.append(item)\n            tmp.append(anno[\"score\"])\n            label = anno[\"label\"]\n            # reassign bbox label \n            tmp.append(label)\n            rois.append(tmp)\n        rois = torch.cuda.FloatTensor(rois)\n        return rois\n\n    def get_assos(self, input):\n        image_info = input['image_info']\n        rois = input['dt_bboxes']\n        #rois = input['dt_bboxes'][:self.cfg['pre_top_n']]\n        #rois = self.load_box(\"/mnt/lustre/share/zhangmingyuan/to_ycj/0808/bbox.json\")\n        tmp_rois = copy.deepcopy(rois)\n        pair_rois, rois1, rois2, pair_position = self.generate_pair(tmp_rois, input)\n        if self.cfg.get('forward_batch', None):\n            #pdb.set_trace()\n            cur_idx = 0\n            batch_size = self.cfg['forward_batch']\n            pred_cls = []\n            binary_pred_cls = []\n            while cur_idx < pair_rois.shape[0]:\n                if cur_idx + batch_size >= pair_rois.shape[0]:\n                    inds = np.array([_ for _ in range(cur_idx, pair_rois.shape[0])]).astype(np.int32)\n                else:\n                    inds = np.array([_ for _ in range(cur_idx, cur_idx + batch_size)]).astype(np.int32)\n                pred_pair_feature = self.extract_relation_feature(rois, pair_rois[inds], pair_position[inds], input)\n                pred_cls.append(self.predict(pred_pair_feature, rois1[inds], rois2[inds], pair_position[inds], input))\n                if self.use_rpn:\n                    binary_pred_cls.append(self.binary_predict(pred_pair_feature, rois1[inds], rois2[inds], pair_position[inds]))\n                cur_idx += batch_size\n            pred_cls = torch.cat(pred_cls, dim=0)\n            if self.use_rpn:\n                binary_pred_cls = torch.cat(binary_pred_cls, dim=0)\n        else:\n            pred_pair_feature = self.extract_relation_feature(rois, pair_rois, pair_position, input)\n            pred_cls = self.predict(pred_pair_feature, rois1, rois2, pair_position, input)\n\n            if self.use_rpn:\n                binary_pred_cls = self.binary_predict(pred_pair_feature, rois1, rois2, pair_position)\n        if self.cfg.get('cls_type', 'softmax') == 'softmax':\n            pred_cls = F.softmax(pred_cls, dim=1)\n        else:\n            pred_cls = F.sigmoid(pred_cls)\n        if self.use_rpn:\n            N = binary_pred_cls.shape[0]\n            binary_pred_cls = binary_pred_cls.view(N, 1).contiguous()\n            binary_pred_cls = F.sigmoid(binary_pred_cls)\n            #pred_cls = pred_cls * binary_pred_cls\n        if self.tocaffe:\n            self.print_param(pred_cls, 'softmax.txt')\n        assos = predict_assos(rois, pair_rois, pred_cls, image_info, self.cfg, self.tocaffe)\n        return assos, pred_cls\n\n    def assign(self, rois, gt_bboxes):\n        # when use rpn output for asso prediction, we re-label the bbox cls by calculate the IoU between dt and gt\n        # 1 is body bbox, 2 is object bbox \n        N = rois.shape[0]\n        flag = False\n        for i in range(N):\n            b_ix = int(rois[i][0])\n            gt = to_np_array(gt_bboxes[b_ix]).astype(np.int32)\n            idx = np.where(gt[:, 4] == 1)\n            gt = gt[idx]\n            if gt.shape[0] == 0:\n                if flag:\n                    rois[i][6] = 2\n                flag = True\n                continue\n            iou = cal_iou(to_np_array(rois[i][1:5]), gt)\n            iou = np.max(iou)\n            if iou < 0.5:\n                if flag:\n                    rois[i][6] = 2\n                flag = True\n        return rois\n\n    def append_gt_bboxes(self, rois, gt_bboxes, image_info):\n        B = len(image_info)\n        new_rois = []\n        for b_ix in range(B):\n            gt_bbox = gt_bboxes[b_ix]\n            N = gt_bbox.shape[0]\n            nrois = torch.zeros((N, 7))\n            nrois = nrois.type_as(rois)\n            nrois[:, 0] = b_ix\n            nrois[:, 1: 5] = gt_bbox[:, :4]\n            nrois[:, 5] = 1.0\n            nrois[:, 6] = gt_bbox[:, 4]\n            w = nrois[:, 3] - nrois[:, 1]\n            h = nrois[:, 4] - nrois[:, 2]\n            rand = np.random.rand(N, 4)\n            ratio = self.cfg.get('gt_jitter_ratio', 0.0)\n            nrois[:, 1] = nrois[:, 1] + ((rand[:, 0] - 0.5) * 2 * w * ratio).type_as(nrois)\n            nrois[:, 2] = nrois[:, 2] + ((rand[:, 1] - 0.5) * 2 * h * ratio).type_as(nrois)\n            nrois[:, 3] = nrois[:, 3] + ((rand[:, 2] - 0.5) * 2 * w * ratio).type_as(nrois)\n            nrois[:, 4] = nrois[:, 4] + ((rand[:, 3] - 0.5) * 2 * h * ratio).type_as(nrois)\n            nrois[:, 1:5] = clip_bbox(nrois[:, 1:5], image_info[b_ix])\n            if N > 20 and not self.cfg.get('only_gt_bboxes', False):\n                keep_ix = np.random.choice(N, size=20, replace=True)\n                nrois = nrois.index_select(0, torch.cuda.LongTensor(keep_ix)).contiguous()\n            new_rois.append(nrois)\n        if not self.cfg.get('only_gt_bboxes', False):\n            new_rois.append(rois)\n        rois = torch.cat(new_rois)\n        return rois\n\n    def get_loss(self, input):\n        image_info = input['image_info']\n        rois = input.get('dt_bboxes', None)\n        gt_assos = input['gt_assos']\n        gt_bboxes = input.get('gt_bboxes', None)\n        if self.cfg.get('append_gt_bboxes', False):\n            rois = self.append_gt_bboxes(rois, gt_bboxes, image_info)\n        #rois = self.assign(rois, gt_bboxes)\n        ignore_regions = input.get('gt_ignores', None)\n        tmp_rois = copy.deepcopy(rois)\n        pair_rois, rois1, rois2, pair_position = self.generate_pair(tmp_rois, input)\n        #pdb.set_trace()\n        roiTable = self.create_table(pair_rois)\n        inds, rcnn_gt_cls, normalizer = \\\n            compute_proposal_targets(\n                tmp_rois, pair_rois, self.num_classes, self.cfg, gt_bboxes, gt_assos, roiTable, image_info, 'rcnn', ignore_regions)\n        tmp_pair_rois = pair_rois[inds]\n        tmp_pair_position = pair_position[inds]\n        tmp_rois1 = rois1[inds]\n        tmp_rois2 = rois2[inds]\n        #pdb.set_trace()\n        pred_pair_feature = self.extract_relation_feature(rois, tmp_pair_rois, tmp_pair_position, input)\n        pred_rcnn_cls = self.predict(pred_pair_feature, tmp_rois1, tmp_rois2, tmp_pair_position, input)\n        if isinstance(pred_rcnn_cls, list):\n            loss, acc = {}, {}\n            for i, pred_cls in enumerate(pred_rcnn_cls):\n                cur_loss, cur_acc = self.cal_loss(input, tmp_rois1, tmp_rois2, pred_cls, rcnn_gt_cls, str(i) + '_', self.cfg.get(\"cls_loss_scale\", 1.0), self.binary_mask)\n                loss.update(cur_loss)\n                acc.update(cur_acc)\n        else:\n            loss, acc = self.cal_loss(input, tmp_rois1, tmp_rois2, pred_rcnn_cls, rcnn_gt_cls, \"\", self.cfg.get(\"cls_loss_scale\", 1.0), self.binary_mask)\n        predict_vector = None\n        predict_target = None\n        if self.output_predict:\n            bbox1_score = torch.Tensor(tmp_rois1[:, 5]).cuda()\n            bbox1_score = bbox1_score.type_as(pred_rcnn_cls)\n            bbox2_score = torch.Tensor(tmp_rois2[:, 5]).cuda()\n            bbox2_score = bbox2_score.type_as(pred_rcnn_cls)\n            if self.use_rpn:\n                pred_binary_cls = self.binary_predict(pred_pair_feature, tmp_rois1, tmp_rois2, tmp_pair_position)\n                N = pred_binary_cls.shape[0]\n                pred_binary_cls = pred_binary_cls.view(N, 1).contiguous()\n                bbox1_score = bbox1_score.view(N, 1).contiguous()\n                bbox2_score = bbox2_score.view(N, 1).contiguous()\n                predict_vector = F.sigmoid(pred_rcnn_cls) * F.sigmoid(pred_binary_cls) * bbox1_score * bbox2_score\n            else:\n                predict_vector = F.sigmoid(pred_rcnn_cls) * bbox1_score * bbox2_score\n            predict_target = rcnn_gt_cls\n        elif self.use_rpn:\n            rpn_cfg = copy.deepcopy(self.cfg)\n            rpn_cfg.update(self.cfg['rpn'])\n            inds, rcnn_gt_cls, normalizer = \\\n                compute_proposal_targets(\n                    tmp_rois, pair_rois, 1, rpn_cfg, gt_bboxes, gt_assos, roiTable, image_info, 'rpn', ignore_regions)\n            tmp_pair_rois = pair_rois[inds]\n            tmp_pair_position = pair_position[inds]\n            tmp_rois1 = rois1[inds]\n            tmp_rois2 = rois2[inds]\n            pred_pair_feature = self.extract_relation_feature(rois, tmp_pair_rois, tmp_pair_position, input)\n            pred_rcnn_cls = self.binary_predict(pred_pair_feature, tmp_rois1, tmp_rois2, tmp_pair_position)\n            rpn_loss, rpn_acc = self.cal_loss(input, tmp_rois1, tmp_rois2, pred_rcnn_cls, rcnn_gt_cls, \"rpn_\", rpn_cfg.get(\"cls_loss_scale\", 1.0))\n            loss.update(rpn_loss)\n            acc.update(rpn_acc)\n\n        return loss, acc, predict_vector, predict_target\n\n\n    def cal_sample_weight(self, rois2, input):\n        num = rois2.shape[0]\n        weight = np.ones(shape=(num, ))\n        filenames = input['filename']\n        gt_hand = {}\n        for bz_idx, filename in enumerate(filenames):\n            gt_hand[bz_idx] = self.transform_aug_bbox(input, bz_idx)\n\n        for i in range(len(rois2)):\n            bz_idx = int(rois2[i, 0])\n            bbox = rois2[i, 1: 5]\n            filename = input['filename'][bz_idx]\n            cls = rois2[i, 6]\n            if cls == 3:\n                gt_hands_by_img = gt_hand[bz_idx]\n                if gt_hands_by_img is None:\n                    weight[i] = 1-self.important_weight\n                else:\n                    iou = self.calIoU(bbox.reshape((-1, 4)), gt_hands_by_img).reshape(-1)\n                    weight[i] = self.important_weight if iou.max() > 0.5 else 1-self.important_weight\n            else:\n                weight[i] = 1 - self.important_weight\n\n        return weight\n\n    def cal_loss(self, input, rois1, rois2, pred_rcnn_cls, rcnn_gt_cls, prefix, cls_loss_scale, binary_mask=None):\n        loss = {}\n        def f2(x):\n            return Variable(torch.from_numpy(x)).cuda()\n        rcnn_gt_cls = f2(rcnn_gt_cls).long()\n        rcnn_cls = pred_rcnn_cls.float()\n        if self.cfg.get('cls_type', 'softmax') == 'sigmoid':\n            rcnn_gt_cls = rcnn_gt_cls.float()\n        sigma = self.cfg.get('smooth_l1_sigma', 1.0)\n        if self.cfg.get('ohem', None):\n            rcnn_cls = rcnn_cls.view(-1).contiguous()\n            rcnn_gt_cls = rcnn_gt_cls.view(-1).contiguous()\n            cls_loss, _, idx = L.ohem_loss(\n                self.cfg['ohem']['batch_size'],\n                rcnn_cls,\n                rcnn_gt_cls,\n                None,\n                None,\n                self.cfg.get('cls_type', 'softmax'),\n                smooth_l1_sigma=sigma)\n            rcnn_cls = rcnn_cls[idx]\n            rcnn_gt_cls = rcnn_gt_cls[idx]\n        elif self.cfg.get('cls_type', 'softmax') == 'softmax':\n#（N， 6） rois2 \n            # rcnn_cls\n            sample_weight = self.cal_sample_weight(rois2, input)\n            sample_weight = torch.from_numpy(sample_weight).cuda().float()\n            cls_loss = L.cross_entropy_weight(rcnn_cls, rcnn_gt_cls, sample_weight)  # todo 可能在这里加weight\n            # cls_loss = F.cross_entropy(rcnn_cls, rcnn_gt_cls)\n        else:\n            if self.binary_mask:\n                N, C = rcnn_cls.shape\n                for i in range(N):\n                    scale = self.binary_scale[rois2[i][6]]\n                    scale = scale.type_as(rcnn_cls)\n                    rcnn_cls[i] = rcnn_cls[i] * scale\n            cls_loss = F.binary_cross_entropy_with_logits(rcnn_cls, rcnn_gt_cls)\n        loss.update({'.' + prefix + 'cls_loss': cls_loss * cls_loss_scale})\n        if self.cfg.get('cls_type', 'softmax') == 'softmax':\n            acc = {'.' + prefix + 'accuracy': A.accuracy(rcnn_cls, rcnn_gt_cls)[0]}\n        else:\n            acc = {'.' + prefix + 'accuracy': A.binary_accuracy(rcnn_cls, rcnn_gt_cls)[0]}\n        return loss, acc\n\n\nclass GeneralAssociation(PairWiseNet):\n    def __init__(self,\n                 inplanes,\n                 feat_planes,\n                 num_classes,\n                 cfg,\n                 initializer=None):\n        super(GeneralAssociation, self).__init__(inplanes, num_classes, cfg)\n        inplanes = self.inplanes\n        self.relu = nn.ReLU(inplace=True)\n        self.fc6_ioa = nn.Linear(self.mdim, feat_planes)\n        self.fc7 = nn.Linear(feat_planes, feat_planes)\n        self.fc_rcnn_cls = nn.Linear(feat_planes + self.cls_mdim, num_classes)\n                \n\n    def predict(self, x, rois1=None, rois2=None, union_rois=None, input=None):\n        '''\n            x: feature to pool\n        '''\n        feature = self.relu(self.fc6_ioa(x))\n        feature = self.relu(self.fc7(feature))\n        pred_cls = self.fc_rcnn_cls(feature)\n        if self.tocaffe:\n            self.print_param(x, 'concat_feature.txt')\n            self.print_param(pred_cls, 'pred_feature.txt')\n        return pred_cls\n\nclass LowdimAssociation(PairWiseNet):\n    def __init__(self,\n                 inplanes,\n                 feat_planes,\n                 num_classes,\n                 cfg,\n                 initializer=None):\n        super(LowdimAssociation, self).__init__(inplanes, num_classes, cfg)\n        inplanes = self.inplanes\n        self.relu = nn.ReLU(inplace=True)\n        self.body_fc = nn.Linear(3136, 512)\n        self.face_fc = nn.Linear(3136, 512)\n        self.hand_fc = nn.Linear(3136, 512)\n        self.concat_fc = nn.Linear(feat_planes, feat_planes)\n        self.fc_rcnn_cls = nn.Linear(feat_planes + self.cls_mdim, num_classes)\n                \n\n    def predict(self, x, rois1=None, rois2=None, union_rois=None, input=None):\n        '''\n            x: feature to pool\n        '''\n        #pdb.set_trace()\n        body_feature = x[:, :3136]\n        face_bool = rois2[:, -1] != 3\n        hand_bool = rois2[:, -1] == 3\n        face_index = np.where(face_bool)[0]\n        hand_index = np.where(hand_bool)[0]\n        face_index = torch.from_numpy(face_index).cuda()\n        hand_index = torch.from_numpy(hand_index).cuda()\n        face_feature = torch.index_select(x[:, 3136:3136*2], 0, face_index)\n        #face_feature = torch.index_select(x[:, 3136:3136*2], 0, face_index)\n        hand_feature = torch.index_select(x[:, 3136:3136*2], 0, hand_index)\n        #hand_feature = torch.index_select(x[:, 3136:3136*2], 0, hand_index)\n        body_feature = self.relu(self.body_fc(body_feature))\n        bz = len(body_feature)\n        object_feature = torch.zeros([bz, 512]).cuda().half()\n        if len(face_feature) != 0:\n            face_feature = self.relu(self.face_fc(face_feature))\n            object_feature[face_index, :] = face_feature\n        if len(hand_feature) != 0:\n            hand_feature = self.relu(self.hand_fc(hand_feature))\n            object_feature[hand_index, :] = hand_feature\n        if len(object_feature) != 512:\n            print(object_feature.size)\n            print(face_index.shape)\n            print(hand_index.shape)\n            print(np.where(~(face_bool | hand_bool)))\n            print(rois2[~(face_bool | hand_bool), -1])\n        feature = torch.cat([body_feature, object_feature], dim=1)\n        feature = self.relu(self.concat_fc(feature))\n        pred_cls = self.fc_rcnn_cls(feature)\n        if self.tocaffe:\n            self.print_param(x, 'concat_feature.txt')\n            self.print_param(pred_cls, 'pred_feature.txt')\n        return pred_cls\n\n\ndef generate_union_mask(human_rois, object_rois, union_rois):\n    \"\"\"\n    human_rois: [512, 7]\n    object_rois: [512, 7]\n    union_rois: [512, 5]\n    \"\"\"\n    batch_size = human_rois.shape[0]\n    union_mask = np.zeros((batch_size, 2, 64, 64))\n    pooling_size = 64\n    for i in range(batch_size):\n        union_left_top = np.tile(union_rois[i, 1:3], 2)\n        w, h = union_rois[i, 3:5] - union_rois[i, 1:3]\n        weights_t = pooling_size / np.array([w, h, w, h])\n        human_coord = ((human_rois[i, 1:5] - union_left_top) * weights_t).astype(np.int32)\n        object_coord = ((object_rois[i, 1:5] - union_left_top) * weights_t).astype(np.int32)\n        union_mask[i, 0, human_coord[1]:human_coord[3] + 1, human_coord[0]:human_coord[2] + 1] = 1\n        union_mask[i, 1, object_coord[1]:object_coord[3] + 1, object_coord[0]:object_coord[2] + 1] = 1\n    union_mask = union_mask.astype(np.float32)\n    return union_mask\n\n\nclass MaskAssociation(PairWiseNet):\n    def __init__(self,\n                 inplanes,\n                 feat_planes,\n                 num_classes,\n                 cfg,\n                 initializer=None):\n        super(MaskAssociation, self).__init__(inplanes, num_classes, cfg)\n        inplanes = self.inplanes\n        self.relu = nn.ReLU(inplace=True)\n        self.cnn_fc6 = nn.Linear(self.mdim, feat_planes) # [3136+3136, 1024]\n        self.cnn_fc7 = nn.Linear(feat_planes, feat_planes) # [1024, 1024]\n        self.mask_fc6 = nn.Linear(2*64*64, feat_planes) # [2*64*64, 1024]\n        self.mask_fc7 = nn.Linear(feat_planes, feat_planes) # [1024, 1024]\n        self.fc_rcnn_cls1 = nn.Linear(feat_planes * 2, feat_planes) # [1024+1024, 1024]\n        self.fc_rcnn_cls2 = nn.Linear(feat_planes, num_classes) # [1024, 3]\n                \n    \n    def extract_relation_feature(self, rois, pair_rois, pair_position, input):\n        '''\n        rois: (400, 7)  [0.0000, 620.1332, 264.8327, 690.6124, 340.9308,   0.0024,   1.0000]->[bz_id, x, y, x2, y2, score, class]\n        pair_rois: (512, 3) [  1., 103., 128.] -> [bz_id, body index of rois, object index of rois]\n        pair_position: (512, 4) [  1.,27.40246582, 152.92190552, 329.59094238,710.640625] -> [bz_id, x, y, x2, y2](body)\n        input\n\n        return: (512, 9856)\n        '''\n        rois1 = copy.deepcopy(rois)\n        rois1, pred_rois1_feature = self.extract_feature(rois1, input, keep_rois=True)\n        if self.tocaffe:\n            # use CPU method\n            rois1_feature = pred_rois1_feature.index_select(0, torch.LongTensor(pair_rois[:, 1])).contiguous()\n            rois2_feature = pred_rois1_feature.index_select(0, torch.LongTensor(pair_rois[:, 2])).contiguous()\n        else:\n            rois1_feature = pred_rois1_feature.index_select(0, torch.cuda.LongTensor(pair_rois[:, 1])).contiguous()\n            rois2_feature = pred_rois1_feature.index_select(0, torch.cuda.LongTensor(pair_rois[:, 2])).contiguous()\n        if self.predict_kernel:\n            rois2_feature = self.ibconv(rois1_feature, rois1, pair_rois, input)\n\n        # rois1_feature is body feature\n        # rois2_feature is object feature\n        pred_human_feature = rois1_feature\n        features = [rois1_feature, rois2_feature] \n        if self.union_box:\n            _, union_feature = self.extract_feature(torch.Tensor(pair_position).type_as(rois1_feature), input, keep_rois=True)\n            features.append(union_feature)\n        if not self.cfg.get('position', None) is None:\n            # add position feature\n            position_feature = PositionTransform(rois1[pair_rois[:,1].astype(np.int32)], rois1[pair_rois[:,2].astype(np.int32)], input['image_info'])\n            if self.cfg['position'] == 'embedding' or self.cfg['position'] == 'embedding app':\n                position_feature = PositionEmbedding(position_feature, 256)\n                if self.cfg['position'] == 'embedding app':\n                    app_feature = self.position_relu(self.position_fc1(pred_human_feature))\n                    app_feature = self.position_relu(self.position_fc2(app_feature))\n                    app_feature = self.position_relu(self.position_fc3(app_feature))\n                    position_feature = position_feature * app_feature\n\n            features.append(position_feature)\n        if self.cfg.get('similarity', False):\n            # add similarity feature\n            features.append(rois1_feature * rois2_feature)\n        if self.keep_origin_feature:\n            return features\n        if self.cfg.get('element_wise_sum', False):\n            pred_pair_feature = features[0]\n            for i in range(1, len(features)):\n                pred_pair_feature = pred_pair_feature + features[i]\n        else:\n            pred_pair_feature = torch.cat(features, dim=1)\n        if self.tocaffe:\n            self.print_param(pred_pair_feature, 'concat167.txt')\n        return pred_pair_feature\n\n\n    def predict(self, x, rois1=None, rois2=None, union_rois=None, input=None):\n        '''\n            x: feature to pool\n        '''\n        #pdb.set_trace()\n        pair_mask = generate_union_mask(rois1, rois2, union_rois)   # [batch, 2, 64, 64]\n        pair_mask = torch.from_numpy(pair_mask).cuda().half()\n        N = pair_mask.size()[0]\n        pair_mask = pair_mask.view(N, -1)\n        pair_mask_feature = self.relu(self.mask_fc6(pair_mask))\n        pair_mask_feature = self.relu(self.mask_fc7(pair_mask_feature))\n\n        feature = self.relu(self.cnn_fc6(x))\n        feature = self.relu(self.cnn_fc7(feature))\n\n        feature = torch.cat((feature, pair_mask_feature), dim=1)\n        feature = self.relu(self.fc_rcnn_cls1(feature))\n        pred_cls = self.fc_rcnn_cls2(feature)\n        if self.tocaffe:\n            self.print_param(x, 'concat_feature.txt')\n            self.print_param(pred_cls, 'pred_feature.txt')\n        return pred_cls\n\nclass AttentionAssociation(PairWiseNet):\n    def __init__(self,\n                 inplanes,\n                 feat_planes,\n                 num_classes,\n                 cfg,\n                 initializer=None):\n        super(AttentionAssociation, self).__init__(inplanes, num_classes, cfg)\n        inplanes = self.inplanes * 4\n        self.keep_origin_feature = True\n        self.bpe = self.cfg.get('box_position_embedding', False)\n        if self.cfg.get('new_attention', False):\n            self.attention = SiameseAttentionPlus(self.inplanes, self.cfg['head_count'])\n        else:\n            self.attention = SiameseAttention(self.inplanes, self.cfg['head_count'])\n        self.block1 = ResNeXtBottleneck(inplanes, inplanes, stride=1, cardinality=32, base_width=4, widen_factor=4, normalize=self.cfg['normalize'])\n        self.block2 = ResNeXtBottleneck(inplanes, inplanes, stride=1, cardinality=32, base_width=4, widen_factor=4, normalize=self.cfg['normalize'])\n        self.block3 = ResNeXtBottleneck(inplanes, inplanes, stride=1, cardinality=32, base_width=4, widen_factor=4, normalize=self.cfg['normalize'])\n        self.conv_cls = nn.Conv2d(inplanes, num_classes, 1, bias=False) \n\n    def predict(self, x, rois1=None, rois2=None, union_rois=None, input=None):\n        '''\n            x: feature to pool\n        '''\n        first, second, union = x\n        if self.bpe:\n            first = first + BoxPositionEmbedding(rois1, self.pool_size, self.pool_size, self.inplanes, dtype=first.dtype)\n            second = second + BoxPositionEmbedding(rois2, self.pool_size, self.pool_size, self.inplanes, dtype=second.dtype)\n            union = union + BoxPositionEmbedding(union_rois, self.pool_size, self.pool_size, self.inplanes, dtype=union.dtype)\n\n        correlation = self.attention(first, second)\n        #correlation = first * second\n        feature = torch.cat((first, second, correlation, union), dim=1)\n        feature = self.block1(feature)\n        feature = self.block2(feature)\n        feature = self.block3(feature)\n        feature = self.conv_cls(feature)\n        feature = torch.mean(torch.mean(feature, dim=3), dim=2)\n        return feature\n\n\nclass RelationAttention(PairWiseNet):\n    def __init__(self,\n                 inplanes,\n                 feat_planes,\n                 num_classes,\n                 cfg,\n                 initializer=None):\n        super(RelationAttention, self).__init__(inplanes, num_classes, cfg)\n        self.keep_origin_feature = True\n        module_name, cls_name = cfg['relation_type'].rsplit('.', 1)\n        module = importlib.import_module(module_name)\n        cls = getattr(module, cls_name)\n        self.attention = cls(cfg['multi_relation'])\n        if cfg.get('feature_type', None) is not None:\n            module_name, cls_name = cfg['feature_type'].rsplit('.', 1)\n            module = importlib.import_module(module_name)\n            cls = getattr(module, cls_name)\n            self.extractor = cls(inplanes)\n        else:\n            self.extractor = None\n        self.relu = nn.ReLU()\n        self.fc6 = nn.Linear(self.mdim, feat_planes)\n        self.fc7 = nn.Linear(feat_planes, feat_planes)\n        self.fc_rcnn_cls = nn.Linear(feat_planes, num_classes)\n        \n        initialize_from_cfg(self, initializer)\n        init_weights_normal(self.fc_rcnn_cls, 0.01)\n\n    def extract_feature(self, rois, input, keep_rois=False):\n        rois, pred_feature = super(RelationAttention, self).extract_feature(rois, input, keep_rois)\n        N, C = pred_feature.shape[:2]\n        cfg = {}\n        cfg['rois'] = torch.from_numpy(rois).cuda()\n        cfg['rois_feature'] = pred_feature.view(N, C, -1).contiguous()\n        if self.extractor:\n            cfg['context'] = self.extractor(input['features'])\n        cfg['image_info'] = input['image_info']\n        pred_feature = self.attention(cfg)\n        return rois, pred_feature\n\n    \n    def generate_cls(self, first, second, union):\n        N = first.shape[0]\n        cur_first = first.view(N, -1)\n        cur_second = second.view(N, -1)\n        cur_union = union.view(N, -1)\n        if self.cfg.get('element_wise_sum', False):\n            feature = cur_first + cur_second + cur_union\n        else:\n            feature = torch.cat([cur_first, cur_second, cur_union], dim=1)\n        feature = self.relu(self.fc6(feature))\n        feature = self.relu(self.fc7(feature))\n        pred_cls = self.fc_rcnn_cls(feature)\n        return pred_cls\n\n    def predict(self, x, rois1=None, rois2=None, union_rois=None, input=None):\n        '''\n            x: feature to pool\n        '''\n        first, second, union = x\n        N = first.shape[0]\n        pred_cls1 = self.generate_cls(first, second, union)\n        #if self.training:\n        #    return [pred_cls0, pred_cls1]\n        #else:\n        #    return pred_cls1\n        return pred_cls1\n\n\nclass PosRelationAttention(PairWiseNet):\n    def __init__(self,\n                 inplanes,\n                 feat_planes,\n                 num_classes,\n                 cfg,\n                 initializer=None):\n        super(PosRelationAttention, self).__init__(inplanes, num_classes, cfg)\n        self.keep_origin_feature = True\n        module_name, cls_name = cfg['relation_type'].rsplit('.', 1)\n        module = importlib.import_module(module_name)\n        cls = getattr(module, cls_name)\n        self.attention = cls(cfg['multi_relation'])\n        if cfg.get('feature_type', None) is not None:\n            module_name, cls_name = cfg['feature_type'].rsplit('.', 1)\n            module = importlib.import_module(module_name)\n            cls = getattr(module, cls_name)\n            self.extractor1 = cls(inplanes)\n            self.extractor2 = cls(inplanes)\n        else:\n            self.extractor1 = None\n            self.extractor2 = None\n        self.relu = nn.ReLU()\n        self.fc6 = nn.Linear(self.mdim, feat_planes)\n        self.fc7 = nn.Linear(feat_planes, feat_planes)\n        self.fc_rcnn_cls = nn.Linear(feat_planes, num_classes)\n        initialize_from_cfg(self, initializer)\n        init_weights_normal(self.fc_rcnn_cls, 0.01)\n\n    def extract_feature(self, rois, input, keep_rois=False):\n        embedd = []\n        for i in range(len(input['features'])):\n            b, c, h, w = input['features'][i].shape\n            pos_embedding = ImagePositionEmbedding(b, c, h, w, input['features'][0].dtype) \n            embedd.append(pos_embedding)\n        features = input['features']\n        _, pred_feature = super(PosRelationAttention, self).extract_feature(rois, input, keep_rois)\n        input['features'] = embedd\n        rois, embed_feature = super(PosRelationAttention, self).extract_feature(rois, input, keep_rois)\n        input['features'] = features\n\n        N, C = pred_feature.shape[:2]\n        cfg = {}\n        cfg['rois'] = torch.from_numpy(rois).cuda()\n        cfg['rois_feature'] = pred_feature.view(N, C, -1).contiguous()\n        cfg['rois_embed'] = embed_feature.view(N, C, -1).contiguous()\n        if self.extractor1:\n            cfg['context'] = self.extractor1(features)\n            cfg['embed'] = self.extractor2(embedd)\n        cfg['image_info'] = input['image_info']\n        pred_feature = self.attention(cfg)\n        return rois, pred_feature\n\n    \n    def generate_cls(self, first, second, union):\n        N = first.shape[0]\n        cur_first = first.view(N, -1)\n        cur_second = second.view(N, -1)\n        cur_union = union.view(N, -1)\n        if self.cfg.get('element_wise_sum', False):\n            feature = cur_first + cur_second + cur_union\n        else:\n            feature = torch.cat([cur_first, cur_second, cur_union], dim=1)\n        feature = self.relu(self.fc6(feature))\n        feature = self.relu(self.fc7(feature))\n        pred_cls = self.fc_rcnn_cls(feature)\n        return pred_cls\n\n    def predict(self, x, rois1=None, rois2=None, union_rois=None, input=None):\n        '''\n            x: feature to pool\n        '''\n        first, second, union = x\n        N = first.shape[0]\n        pred_cls1 = self.generate_cls(first, second, union)\n        #if self.training:\n        #    return [pred_cls0, pred_cls1]\n        #else:\n        #    return pred_cls1\n        return pred_cls1\n\n\n", "meta": {"hexsha": "db24a209a478c9da012305bbd8727b7d3515d3f9", "size": 52898, "ext": "py", "lang": "Python", "max_stars_repo_path": "unn/models/heads/pair_head2/pair_head_change.py", "max_stars_repo_name": "zongdaoming/TinyTransformer", "max_stars_repo_head_hexsha": "8e64f8816117048c388b4b20e3a56760ce149fe3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-08T11:23:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T04:05:23.000Z", "max_issues_repo_path": "unn/models/heads/pair_head_clean/pair_head_change.py", "max_issues_repo_name": "zongdaoming/TinyTransformer", "max_issues_repo_head_hexsha": "8e64f8816117048c388b4b20e3a56760ce149fe3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-08T11:25:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-08T11:26:15.000Z", "max_forks_repo_path": "unn/models/heads/pair_head_group/pair_head_change.py", "max_forks_repo_name": "zongdaoming/TinyTransformer", "max_forks_repo_head_hexsha": "8e64f8816117048c388b4b20e3a56760ce149fe3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.7529610829, "max_line_length": 170, "alphanum_fraction": 0.5825362017, "include": true, "reason": "import numpy", "num_tokens": 13481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.18879753763188148}}
{"text": "\"\"\"This module contains the tabular Critic implementation.\"\"\"\nfrom __future__ import annotations\n\nimport math\nfrom typing import Hashable, List, Tuple, Dict, Callable\n\nimport attr\nimport numpy as np\nfrom scipy.special import logsumexp, softmax\nfrom scipy.optimize import brentq\n\nfrom improvisers.game_graph import GameGraph, Node\nfrom improvisers.critic import Critic, Distribution, DistLike\nfrom improvisers.explicit import ExplicitDist as Dist\n\n\noo = float('inf')\n\n\nCacheKey = Tuple[Node, Hashable, float]\n\n\n@attr.s(frozen=True, auto_attribs=True)\nclass Cache:\n    data: Dict[Tuple[Node, Hashable], Tuple[float, float]] = attr.ib(\n        factory=dict\n    )\n\n    def __contains__(self, key: CacheKey) -> bool:\n        node, stat_key, rationality = key\n        if (node, stat_key) not in self.data:\n            return False\n        return self.data[node, stat_key][1] == rationality\n\n    def __getitem__(self, key: CacheKey) -> float:\n        node, stat_key, _ = key\n        if key not in self:\n            raise ValueError(f\"key: {key} not in cache.\")\n        return self.data[node, stat_key][0]\n\n    def __setitem__(self, key: CacheKey, val: float) -> None:\n        node, stat_key, rationality = key\n        self.data[node, stat_key] = (val, rationality)\n\n\ndef cached_stat(func: NodeStatFunc) -> NodeStatFunc:\n    \"\"\"Cache node level statistics. Only once per rationality.\"\"\"\n    def wrap(critic: TabularCritic,\n             node_dist: DistLike,\n             rationality: float) -> float:\n        if isinstance(node_dist, Dist):  # Don't cache distributions.\n            return func(critic, node_dist, rationality)\n        node = node_dist\n        if (node, func, rationality) in critic.cache:\n            return critic.cache[node, func, rationality]\n        val = func(critic, node, rationality)\n        critic.cache[node, func, rationality] = val\n        return val\n    return wrap\n\n\n@attr.s(auto_attribs=True, frozen=True)\nclass TabularCritic:\n    game: GameGraph\n    cache: Cache = attr.ib(factory=Cache)\n    _min_ent_moves: Dict[Node, List[Node]] = attr.ib(factory=dict)\n\n    def min_ent_moves(self, node: Node) -> List[Node]:\n        \"\"\"Return moves which minimizes the *achievable* entropy.\"\"\"\n        if node in self._min_ent_moves:\n            return self._min_ent_moves[node]\n\n        moves, worst = [], oo\n        for node2 in self.game.moves(node):\n            entropy = self.entropy(node2, 0)\n            if entropy < worst:\n                moves, worst = [node2], entropy\n            elif entropy == worst:\n                moves.append(node2)\n        self._min_ent_moves[node] = moves\n        return moves\n\n    def min_ent_move(self, node: Node, rationality: float) -> Node:\n        moves = self.min_ent_moves(node)\n\n        # Optimization. If all values are the same, the resulting\n        # policy will assign same probability to transitioning to this\n        # node. Commonly happens when two subtrees are equivalent.\n        val0 = self.value(moves[0], 0)\n\n        other_vals = (self.value(move, 0) for move in moves[1:])\n        if all(val == val0 for val in other_vals):\n            return moves[0]\n\n        # Break ties with psat.\n        # Note 1: Triggering this is fairly difficult to arrange in\n        #   practice, since entropy and values both sensitive to exact\n        #   model.\n        # Note 2: Unlike in general min psat move case, rationality\n        #   need note be updated since entropy is already matched.\n        # Note 3: This step cannot be cached since psat will, in general,\n        #   depend on the rationality.\n        return min(moves, key=lambda n: self.psat(n, rationality))\n\n    def min_psat_move(\n            self, node: Node, rationality: float) -> Tuple[Node, float]:\n        assert self.game.label(node) == 'p2'\n\n        # Compute entropy of planned move.\n        planned_move = self.min_ent_move(node, rationality)\n        entropy = self.entropy(planned_move, rationality)\n\n        # p1 will increase rationality until target entropy matched.\n        def replanned_psat(move: Node) -> float:\n            replanned_rationality = rationality\n            if rationality < oo:  # Note: can't increase rationality past oo.\n                replanned_rationality = self.match_entropy(move, entropy)\n            return self.psat(move, max(replanned_rationality, 0))\n\n        # p2 will take the minimum psat of the replanned moves.\n        moves = self.game.moves(node)\n        p2_move = min(moves, key=replanned_psat)\n\n        if rationality < oo:\n            rationality = self.match_entropy(p2_move, entropy)\n\n        return p2_move, rationality\n\n    @cached_stat\n    def value(self, node: Node, rationality: float) -> float:\n        label = self.game.label(node)\n\n        if isinstance(label, bool):              # Terminal node.\n            return rationality * label if rationality < oo else float(label)\n\n        moves = list(self.game.moves(node))  # Fix order of moves.\n\n        if label == 'p2':                        # Player 2 case.\n            p2_move = self.min_ent_move(node, rationality)\n            return self.value(p2_move, rationality)\n\n        values = [self.value(move, rationality) for move in moves]\n\n        if label == 'p1':                        # Player 1 case.\n            return logsumexp(values) if rationality < oo else max(values)\n\n        dist = label                             # Environment case.\n        probs = [dist.prob(move) for move in moves]\n        return np.average(values, weights=probs)\n\n    @cached_stat\n    def lsat(self, node_dist: DistLike, rationality: float) -> float:\n        if isinstance(node_dist, Dist):  # Reduce dist to calls over support.\n            dist = node_dist\n            probs = [dist.prob(n) for n in dist.support()]\n            lsats = [self.lsat(n, rationality) for n in dist.support()]\n            return logsumexp(lsats, b=probs)\n        node = node_dist\n\n        label = self.game.label(node)\n        if isinstance(label, bool):\n            return 0 if label else -oo\n        elif label == 'p2':\n            # Plan against optimal deterministic p2 policy.\n            p2_move, rationality = self.min_psat_move(node, rationality)\n\n            return self.lsat(p2_move, rationality)\n\n        node_dist2 = self.move_dist(node, rationality)\n        return self.lsat(node_dist2, rationality)\n\n    def psat(self, node: Node, rationality: float) -> float:\n        sat_prob = math.exp(self.lsat(node, rationality))\n        assert sat_prob < 1.2\n        return min(sat_prob, 1)  # Clip at 1 due to numerics.\n\n    def _rationality(self, node: Node, target: float,\n                     match_entropy: bool = False,\n                     num_iter: int = 100) -> float:\n        \"\"\"Bracketed search for rationality to match either psat or entropy.\"\"\"\n        assert target >= 0, \"Entropy or probabilities must be positive.\"\n        if not match_entropy:  # Matching psat.\n            assert target <= 1, \"Probabilities are less than 1!\"\n\n        stat = self.entropy if match_entropy else self.psat\n\n        def f(coeff: float) -> float:\n            return stat(node, coeff) - target\n\n        # TODO: properly support negative rationality.\n        if f(-100) > 0:\n            return -100   # TODO: support -oo.\n        elif f(oo) < 0:\n            return oo\n\n        top = 1\n        for _ in range(num_iter):\n            try:\n                return brentq(f, -top, top)\n            except ValueError:\n                top *= 2\n\n        return oo  # Effectively infinite.\n\n    @cached_stat\n    def match_entropy(self, node: Node, target: float) -> float:\n        return self._rationality(node, target, match_entropy=True)\n\n    @cached_stat\n    def match_psat(self, node: Node, target: float) -> float:\n        return self._rationality(node, target, match_entropy=False)\n\n    @cached_stat\n    def entropy(self, node_dist: DistLike, rationality: float) -> float:\n        if isinstance(node_dist, Dist):  # Reduce dist to calls over support.\n            dist = node_dist\n            entropy = dist.entropy\n            # Contribution from children. H(A[t+1:T] || S[t+1: T], S[:t]).\n            for node in dist.support():\n                entropy += dist.prob(node) * self.entropy(node, rationality)\n            return entropy\n\n        node = node_dist\n        label = self.game.label(node)\n        if isinstance(label, bool):\n            return 0.0  # Terminal node has no entropy.\n\n        node_dist2 = self.move_dist(node, rationality)\n        return self.entropy(node_dist2, rationality)\n\n    def move_dist(self, state: Node, rationality: float) -> Distribution:\n        label = self.game.label(state)\n        if isinstance(label, bool):\n            return Dist({})\n        elif label == 'p2':\n            p2_move = self.min_ent_move(state, rationality)\n            return Dist({p2_move: 1})  # Assume worst case.\n\n        moves = self.game.moves(state)\n\n        if label == 'p1':\n            vals = [self.value(move, rationality) for move in moves]\n\n            if rationality < oo:\n                probs = softmax(vals)\n                return Dist({move: p for move, p in zip(moves, probs)})\n\n            # If rationality = oo, then we pick uniformly from the best move.\n            optimal = max(vals)\n            support = [a for a, v in zip(moves, vals) if v == optimal]\n            return Dist({node: 1 / len(support) for node in support})\n\n        return label  # Environment Case. label *is* the distribution.\n\n    def state_dist(self, move: Node, rationality: float) -> Distribution:\n        stack = [(0.0, move, rationality)]\n        node2prob = {}\n        while stack:\n            lprob, node, rationality = stack.pop()\n            label = self.game.label(node)\n\n            if isinstance(label, bool) or label == 'p1':\n                node2prob[node] = lprob\n                continue\n            elif label == 'p2':  # Plan against deterministic adversary.\n                p2_move = self.min_ent_move(node, rationality)\n                stack.append((lprob, p2_move, rationality))\n                continue\n            else:\n                dist = label\n                for node2 in dist.support():\n                    lprob2 = lprob + math.log(dist.prob(node2))\n                    stack.append((lprob2, node2, rationality))\n        node2prob = {k: math.exp(v) for k, v in node2prob.items()}\n        return Dist(node2prob)\n\n    @staticmethod\n    def from_game_graph(game_graph: GameGraph) -> Critic:\n        return TabularCritic(game_graph)\n\n\nNodeStatFunc = Callable[[TabularCritic, Node, float], float]\n\n\n__all__ = ['TabularCritic']\n", "meta": {"hexsha": "981651658e3c1b5ee2b70567596d7dfd2446d820", "size": 10554, "ext": "py", "lang": "Python", "max_stars_repo_path": "improvisers/tabular.py", "max_stars_repo_name": "mvcisback/improvisers", "max_stars_repo_head_hexsha": "d7ccc9c560fbe939a24a7ad61f1d12a7c31157ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "improvisers/tabular.py", "max_issues_repo_name": "mvcisback/improvisers", "max_issues_repo_head_hexsha": "d7ccc9c560fbe939a24a7ad61f1d12a7c31157ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "improvisers/tabular.py", "max_forks_repo_name": "mvcisback/improvisers", "max_forks_repo_head_hexsha": "d7ccc9c560fbe939a24a7ad61f1d12a7c31157ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9020979021, "max_line_length": 79, "alphanum_fraction": 0.606120902, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.18879753763188145}}
{"text": "# -*- coding: utf-8 -*-\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n#\n# Copyright (C) 2012-2016 GEM Foundation\n#\n# OpenQuake is free software: you can redistribute it and/or modify it\n# under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# OpenQuake is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"\nModule exports\n:class:`AtkinsonBoore2003SInter`,\n:class:`AtkinsonBoore2003SSlab`,\n:class:`AtkinsonBoore2003SInterNSHMP2008`,\n:class:`AtkinsonBoore2003SSlabNSHMP2008`,\n:class:`AtkinsonBoore2003SSlabCascadia`,\n:class:`AtkinsonBoore2003SSlabCascadiaNSHMP2008`,\n:class:`AtkinsonBoore2003SSlabJapan`\n:class:`AtkinsonBoore2003SSlabJapanNSHMP2008`\n\"\"\"\nfrom __future__ import division\n\nimport numpy as np\n# standard acceleration of gravity in m/s**2\nfrom scipy.constants import g\nimport copy\n\nfrom openquake.hazardlib.gsim.base import GMPE, CoeffsTable\nfrom openquake.hazardlib import const\nfrom openquake.hazardlib.imt import PGA, SA\n\n\nclass AtkinsonBoore2003SInter(GMPE):\n    \"\"\"\n    Implements GMPE developed by G. M  Atkinson and D. Boore and published as\n    \"Empirical Ground-Motion Relations for Subduction-Zone Earthquakes and\n    Their Application to Cascadia and Other Regions\" (Bulletin of the\n    Seismological Society of America, Volume 93, Number 4, pages 1703-1929,\n    2003) and includes correction for subduction interface equations as\n    described in \"Erratum to 'Empirical Ground Motion Relations for\n    Subduction-Zone Earthquakes and their application to Cascadia and other\n    regions'\", Gail M. Atkinson and David M. Boore, Volume 98, Number 5,\n    pp.2567-2569, 2008. The class implements the global model but not the\n    corrections for Japan/Cascadia. SA values at 4 s (not supported by the\n    original equations) are obtained from mean value at 3 s divided by a\n    factor equal to 0.550 (scaling factor computed in the context of the SHARE\n    project and obtained as average ratio between median values at 4 and 3\n    seconds as predicted by SHARE subduction GMPEs). The class implements the\n    equations for 'Subduction Interface' (that's why the class name ends with\n    'SInter').\n    \"\"\"\n    #: Supported tectonic region type is subduction interface\n    DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.SUBDUCTION_INTERFACE\n\n    #: Supported intensity measure types are spectral acceleration,\n    #: and peak ground acceleration, see table 1, page 1715\n    DEFINED_FOR_INTENSITY_MEASURE_TYPES = set([\n        PGA,\n        SA\n    ])\n\n    #: Supported intensity measure component is the random horizontal\n    #component :\n    #attr:`~openquake.hazardlib.const.IMC.RANDOM_HORIZONTAL`, see\n    #paragraph 'Functional : Form', page 1706\n    DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = const.IMC.RANDOM_HORIZONTAL\n\n    #: Supported standard deviation types are inter-event, intra-event\n    #: and total, see table 1, page 1715\n    DEFINED_FOR_STANDARD_DEVIATION_TYPES = set([\n        const.StdDev.TOTAL,\n        const.StdDev.INTER_EVENT,\n        const.StdDev.INTRA_EVENT\n    ])\n\n    #: Required site parameters is Vs30, used to distinguish between NEHRP\n    #: soil classes, see paragraph 'Functional Form', page 1706\n    REQUIRES_SITES_PARAMETERS = set(('vs30', ))\n\n    #: Required rupture parameters are magnitude and focal depth, see equation\n    #: 1, page 1706\n    REQUIRES_RUPTURE_PARAMETERS = set(('mag', 'hypo_depth'))\n\n    #: Required distance measure is closest distance to rupture, see equation\n    #: 1, page 1706\n    REQUIRES_DISTANCES = set(('rrup', ))\n\n    def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):\n        \"\"\"\n        See :meth:`superclass method\n        <.base.GroundShakingIntensityModel.get_mean_and_stddevs>`\n        for spec of input and result values.\n        \"\"\"\n        # extracting dictionary of coefficients specific to required\n        # intensity measure type.\n        C = self.COEFFS_SINTER[imt]\n\n        # cap magnitude values at 8.5, see page 1709\n        mag = rup.mag\n        if mag > 8.5:\n            mag = 8.5\n\n        # compute PGA on rock (needed for site amplification calculation)\n        G = 10 ** (1.2 - 0.18 * mag)\n        pga_rock = self._compute_mean(self.COEFFS_SINTER[PGA()], G, mag,\n                                      rup.hypo_depth, dists.rrup, sites.vs30,\n                                      # by passing pga_rock > 500 the soil\n                                      # amplification is 0\n                                      np.zeros_like(sites.vs30) + 600,\n                                      PGA())\n        pga_rock = 10 ** (pga_rock)\n\n        # periods 0.4 s (2.5 Hz) and 0.2 s (5 Hz) need a special case because\n        # of the erratum. SA for 0.4s and 0.2s is computed and a weighted sum\n        # is returned\n        if isinstance(imt, SA) and imt.period in (0.2, 0.4):\n            C04 = self.COEFFS_SINTER[SA(period=0.4, damping=5.0)]\n            C02 = self.COEFFS_SINTER[SA(period=0.2, damping=5.0)]\n            mean04 = self._compute_mean(C04, G, mag, rup.hypo_depth,\n                                        dists.rrup, sites.vs30, pga_rock, imt)\n            mean02 = self._compute_mean(C02, G, mag, rup.hypo_depth,\n                                        dists.rrup, sites.vs30, pga_rock, imt)\n\n            if imt.period == 0.2:\n                mean = 0.333 * mean02 + 0.667 * mean04\n            else:\n                mean = 0.333 * mean04 + 0.667 * mean02\n        else:\n            mean = self._compute_mean(C, G, mag, rup.hypo_depth, dists.rrup,\n                                      sites.vs30, pga_rock, imt)\n\n        # convert from log10 to ln and units from cm/s**2 to g\n        mean = np.log((10 ** mean) * 1e-2 / g)\n\n        if isinstance(imt, SA) and imt.period == 4.0:\n            mean /= 0.550\n\n        stddevs = self._get_stddevs(C, stddev_types, sites.vs30.shape[0])\n\n        return mean, stddevs\n\n    def _compute_mean(self, C, g, mag, hypo_depth, rrup, vs30, pga_rock, imt):\n        \"\"\"\n        Compute mean according to equation 1, page 1706.\n        \"\"\"\n        if hypo_depth > 100:\n            hypo_depth = 100\n        delta = 0.00724 * 10 ** (0.507 * mag)\n        R = np.sqrt(rrup ** 2 + delta ** 2)\n\n        s_amp = self._compute_soil_amplification(C, vs30, pga_rock, imt)\n\n        mean = (\n            # 1st term\n            C['c1'] + C['c2'] * mag +\n            # 2nd term\n            C['c3'] * hypo_depth +\n            # 3rd term\n            C['c4'] * R -\n            # 4th term\n            g * np.log10(R) +\n            # 5th, 6th and 7th terms\n            s_amp\n        )\n\n        return mean\n\n    @classmethod\n    def _compute_soil_amplification(cls, C, vs30, pga_rock, imt):\n        \"\"\"\n        Compute soil amplification (5th, 6th, and 7th terms in equation 1,\n        page 1706).\n        \"\"\"\n        Sc, Sd, Se = cls._compute_site_class_dummy_variables(vs30)\n        sl = cls._compute_soil_linear_factor(pga_rock, imt)\n\n        return C['c5'] * sl * Sc + C['c6'] * sl * Sd + C['c7'] * sl * Se\n\n    @classmethod\n    def _compute_site_class_dummy_variables(cls, vs30):\n        \"\"\"\n        Compute site class dummy variables as explained in paragraph\n        'Functional Form', page 1706.\n        \"\"\"\n        Sc = np.zeros_like(vs30)\n        Sd = np.zeros_like(vs30)\n        Se = np.zeros_like(vs30)\n\n        Sc[(vs30 > 360) & (vs30 <= 760)] = 1\n        Sd[(vs30 >= 180) & (vs30 <= 360)] = 1\n        Se[vs30 < 180] = 1\n\n        return Sc, Sd, Se\n\n    @classmethod\n    def _compute_soil_linear_factor(cls, pga_rock, imt):\n        \"\"\"\n        Compute soil linear factor as explained in paragraph 'Functional\n        Form', page 1706.\n        \"\"\"\n        if isinstance(imt, SA) and imt.period >= 1:\n            return np.ones_like(pga_rock)\n        else:\n            sl = np.zeros_like(pga_rock)\n\n            pga_between_100_500 = (pga_rock > 100) & (pga_rock < 500)\n            pga_greater_equal_500 = pga_rock >= 500\n\n            is_SA_between_05_1 = isinstance(imt, SA) and 0.5 < imt.period < 1\n\n            is_SA_less_equal_05 = isinstance(imt, SA) and (imt.period <= 0.5)\n\n            if is_SA_between_05_1:\n                sl[pga_between_100_500] = (1 - (1. / imt.period - 1) *\n                                           (pga_rock[pga_between_100_500] -\n                                           100) / 400)\n                sl[pga_greater_equal_500] = 1 - (1. / imt.period - 1)\n\n            if is_SA_less_equal_05 or isinstance(imt, PGA):\n                sl[pga_between_100_500] = (1 - (pga_rock[pga_between_100_500] -\n                                           100) / 400)\n\n            sl[pga_rock <= 100] = 1\n\n            return sl\n\n    def _get_stddevs(self, C, stddev_types, num_sites):\n        \"\"\"\n        Return standard deviations as defined in table 1, pag 1715.\n        \"\"\"\n        stddevs = []\n        for stddev_type in stddev_types:\n            assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES\n            if stddev_type == const.StdDev.TOTAL:\n                stddevs.append(np.log(10 ** C['sigma']) + np.zeros(num_sites))\n            elif stddev_type == const.StdDev.INTRA_EVENT:\n                stddevs.append(np.log(10 ** C['s1']) + np.zeros(num_sites))\n            elif stddev_type == const.StdDev.INTER_EVENT:\n                stddevs.append(np.log(10 ** C['s2']) + np.zeros(num_sites))\n        return stddevs\n\n    COEFFS_SINTER = CoeffsTable(sa_damping=5, table=\"\"\"\\\n    IMT      c1          c2          c3           c4          c5          c6          c7          sigma       s1          s2\n    pga      2.991000    0.035250    0.007590    -0.002060   0.190000    0.240000    0.290000    0.230000    0.200000    0.110000\n    0.0400   2.875300    0.070520    0.010040    -0.002780   0.150000    0.200000    0.200000    0.260000    0.220000    0.140000\n    0.1000   2.778900    0.098410    0.009740    -0.002870   0.150000    0.230000    0.200000    0.270000    0.250000    0.100000\n    0.2000   2.663800    0.123860    0.008840    -0.002800   0.150000    0.270000    0.250000    0.280000    0.250000    0.130000\n    0.4000   2.524900    0.147700    0.007280    -0.002350   0.130000    0.370000    0.380000    0.290000    0.250000    0.150000\n    1.0000   2.144200    0.134500    0.005210    -0.001100   0.100000    0.300000    0.550000    0.340000    0.280000    0.190000\n    2.0000   2.190700    0.071480    0.002240     0.000000   0.100000    0.250000    0.400000    0.340000    0.290000    0.180000\n    3.0000   2.301000    0.022370    0.000120     0.000000   0.100000    0.250000    0.360000    0.360000    0.310000    0.180000\n    4.0000   2.301000    0.022370    0.000120     0.000000   0.100000    0.250000    0.360000    0.360000    0.310000    0.180000\n    \"\"\")\n\n\nclass AtkinsonBoore2003SSlab(AtkinsonBoore2003SInter):\n    \"\"\"\n    Implements GMPE developed by G. M  Atkinson and D. Boore and published as\n    \"Empirical Ground-Motion Relations for Subduction-Zone Earthquakes and\n    Their Application to Cascadia and Other Regions\" (Bulletin of the\n    Seismological Society of America, Volume 93, Number 4, pages 1703-1929,\n    2003). The class implements the global model but not the corrections for\n    Japan/Cascadia. SA values at 4 s (not supported by the original equations)\n    are obtained from mean value at 3 s divided by a factor equal to 0.550\n    (scaling factor computed in the context of the SHARE project and obtained\n    as average ratio between median values at 4 and 3 seconds as predicted by\n    SHARE subduction GMPEs). The class implements the equations for 'Subduction\n    IntraSlab' (that's why the class name ends with 'SSlab').\n    \"\"\"\n    #: Supported tectonic region type is subduction interface\n    DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.SUBDUCTION_INTRASLAB\n\n    def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):\n        \"\"\"\n        See :meth:`superclass method\n        <.base.GroundShakingIntensityModel.get_mean_and_stddevs>`\n        for spec of input and result values.\n        \"\"\"\n        # extracting dictionary of coefficients specific to required\n        # intensity measure type.\n        C = self.COEFFS_SSLAB[imt]\n\n        # cap magnitude values at 8.0, see page 1709\n        mag = rup.mag\n        if mag >= 8.0:\n            mag = 8.0\n\n        # compute PGA on rock (needed for site amplification calculation)\n        G = 10 ** (0.301 - 0.01 * mag)\n        pga_rock = self._compute_mean(self.COEFFS_SSLAB[PGA()], G, mag,\n                                      rup.hypo_depth, dists.rrup, sites.vs30,\n                                      # by passing pga_rock > 500 the soil\n                                      # amplification is 0\n                                      np.zeros_like(sites.vs30) + 600,\n                                      PGA())\n        pga_rock = 10 ** (pga_rock)\n\n        # compute actual mean and convert from log10 to ln and units from\n        # cm/s**2 to g\n        mean = self._compute_mean(C, G, mag, rup.hypo_depth, dists.rrup,\n                                  sites.vs30, pga_rock, imt)\n        mean = np.log((10 ** mean) * 1e-2 / g)\n\n        if isinstance(imt, SA) and imt.period == 4.0:\n            mean /= 0.550\n\n        stddevs = self._get_stddevs(C, stddev_types, sites.vs30.shape[0])\n\n        return mean, stddevs\n\n    COEFFS_SSLAB = CoeffsTable(sa_damping=5, table=\"\"\"\\\n    IMT      c1         c2         c3         c4         c5          c6         c7         sigma      s1        s2\n    pga     -0.04713    0.69090    0.01130    -0.00202    0.19000    0.24000    0.29000    0.27000    0.23000    0.14000\n    0.0400   0.50697    0.63273    0.01275    -0.00234    0.15000    0.20000    0.20000    0.25000    0.24000    0.07000\n    0.1000   0.43928    0.66675    0.01080    -0.00219    0.15000    0.23000    0.20000    0.28000    0.27000    0.07000\n    0.2000   0.51589    0.69186    0.00572    -0.00192    0.15000    0.27000    0.25000    0.28000    0.26000    0.10000\n    0.4000   0.00545    0.77270    0.00173    -0.00178    0.13000    0.37000    0.38000    0.28000    0.26000    0.10000\n    1.0000  -1.02133    0.87890    0.00130    -0.00173    0.10000    0.30000    0.55000    0.29000    0.27000    0.11000\n    2.0000  -2.39234    0.99640    0.00364    -0.00118    0.10000    0.25000    0.40000    0.30000    0.28000    0.11000\n    3.0000  -3.70012    1.11690    0.00615    -0.00045    0.10000    0.25000    0.36000    0.30000    0.29000    0.08000\n    4.0000  -3.70012    1.11690    0.00615    -0.00045    0.10000    0.25000    0.36000    0.30000    0.29000    0.08000\n    \"\"\")\n\n\nclass AtkinsonBoore2003SInterNSHMP2008(AtkinsonBoore2003SInter):\n    \"\"\"\n    Extend :class:`AtkinsonBoore2003SInter` and introduces site amplification\n    for B/C site condition and fixed rupture hypocentral depth (20 km) as\n    defined by the National Seismic Hazard Mapping Project (NSHMP) for the\n    2008 US hazard model\n\n    Site amplification for B/C is triggered when vs30 > 760 and it is\n    computed as site amplification for C soil scaled by a factor equal to 0.5\n\n    The class implements the equation as coded in ``subroutine getABsub``\n    in ``hazSUBXnga.f`` Fortran code available at:\n    http://earthquake.usgs.gov/hazards/products/conterminous/2008/software/\n    \"\"\"\n\n    def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):\n        \"\"\"\n        See :meth:`superclass method\n        <.base.GroundShakingIntensityModel.get_mean_and_stddevs>`\n        for spec of input and result values.\n\n        Call super class method with hypocentral depth fixed at 20 km\n        \"\"\"\n        # fix hypocentral depth to 20 km. Create new rupture context to avoid\n        # changing the original one\n        new_rup = copy.deepcopy(rup)\n        new_rup.hypo_depth = 20.\n\n        mean, stddevs = super(AtkinsonBoore2003SInterNSHMP2008, self). \\\n            get_mean_and_stddevs(sites, new_rup, dists, imt, stddev_types)\n\n        return mean, stddevs\n\n    @classmethod\n    def _compute_soil_amplification(cls, C, vs30, pga_rock, imt):\n        \"\"\"\n        Compute soil amplification (5th, 6th, and 7th terms in equation 1,\n        page 1706) and add the B/C site condition as implemented by NSHMP.\n        \"\"\"\n        Sbc, Sc, Sd, Se = cls._compute_site_class_dummy_variables(vs30)\n        sl = cls._compute_soil_linear_factor(pga_rock, imt)\n\n        return (\n            C['c5'] * sl * Sbc * 0.5 +\n            C['c5'] * sl * Sc +\n            C['c6'] * sl * Sd +\n            C['c7'] * sl * Se\n        )\n\n    @classmethod\n    def _compute_site_class_dummy_variables(cls, vs30):\n        \"\"\"\n        Extend\n        :meth:`AtkinsonBoore2003SInter._compute_site_class_dummy_variables`\n        and includes dummy variable for B/C site conditions (vs30 > 760.)\n        \"\"\"\n        Sbc = np.zeros_like(vs30)\n        Sc = np.zeros_like(vs30)\n        Sd = np.zeros_like(vs30)\n        Se = np.zeros_like(vs30)\n\n        Sbc[vs30 > 760.] = 1\n        Sc[(vs30 > 360) & (vs30 <= 760)] = 1\n        Sd[(vs30 >= 180) & (vs30 <= 360)] = 1\n        Se[vs30 < 180] = 1\n\n        return Sbc, Sc, Sd, Se\n\n\nclass AtkinsonBoore2003SSlabNSHMP2008(AtkinsonBoore2003SSlab):\n    \"\"\"\n    Extend :class:`AtkinsonBoore2003SSlab` and introduces site amplification\n    for B/C site condition as defined by the National Seismic Hazard Mapping\n    Project (NSHMP) for the 2008 US hazard model.\n\n    Site amplification for B/C is triggered when vs30 > 760 and it is\n    computed as site amplification for C soil scaled by a factor equal to 0.5\n\n    The class replicates the equation as coded in ``subroutine getABsub``\n    in ``hazgridXnga2.f`` Fortran code available at:\n    http://earthquake.usgs.gov/hazards/products/conterminous/2008/software/\n    \"\"\"\n    @classmethod\n    def _compute_soil_amplification(cls, C, vs30, pga_rock, imt):\n        \"\"\"\n        Compute soil amplification (5th, 6th, and 7th terms in equation 1,\n        page 1706) and add the B/C site condition as implemented by NSHMP.\n\n        Call\n        :meth:`AtkinsonBoore2003SInterNSHMP2008._compute_soil_amplification`\n        \"\"\"\n        return AtkinsonBoore2003SInterNSHMP2008._compute_soil_amplification(\n            C, vs30, pga_rock, imt)\n\n    @classmethod\n    def _compute_site_class_dummy_variables(cls, vs30):\n        \"\"\"\n        Extend\n        :meth:`AtkinsonBoore2003SInter._compute_site_class_dummy_variables`\n        and includes dummy variable for B/C site conditions (vs30 > 760.)\n\n        Call\n        meth:`AtkinsonBoore2003SInter._compute_site_class_dummy_variables`\n        \"\"\"\n        return AtkinsonBoore2003SInterNSHMP2008. \\\n            _compute_site_class_dummy_variables(vs30)\n\n\nclass AtkinsonBoore2003SSlabCascadia(AtkinsonBoore2003SSlab):\n    \"\"\"\n    Extends :class:`AtkinsonBoore2003SSlab` but uses coefficients for\n    Cascadia region\n\n    The class replicates the equation as coded in ``subroutine getABsub``\n    in ``hazgridXnga2.f`` Fortran code available at:\n    http://earthquake.usgs.gov/hazards/products/conterminous/2008/software/\n    \"\"\"\n    COEFFS_SSLAB = CoeffsTable(sa_damping=5, table=\"\"\"\\\n    IMT      c1      c2         c3         c4         c5          c6         c7         sigma      s1        s2\n    pga     -0.25    0.69090    0.01130    -0.00202    0.19000    0.24000    0.29000    0.27000    0.23000    0.14000\n    0.0400   0.23    0.63273    0.01275    -0.00234    0.15000    0.20000    0.20000    0.25000    0.24000    0.07000\n    0.1000   0.16    0.66675    0.01080    -0.00219    0.15000    0.23000    0.20000    0.28000    0.27000    0.07000\n    0.2000   0.40    0.69186    0.00572    -0.00192    0.15000    0.27000    0.25000    0.28000    0.26000    0.10000\n    0.4000  -0.01    0.77270    0.00173    -0.00178    0.13000    0.37000    0.38000    0.28000    0.26000    0.10000\n    1.0000  -0.98    0.87890    0.00130    -0.00173    0.10000    0.30000    0.55000    0.29000    0.27000    0.11000\n    2.0000  -2.25    0.99640    0.00364    -0.00118    0.10000    0.25000    0.40000    0.30000    0.28000    0.11000\n    3.0000  -3.64    1.11690    0.00615    -0.00045    0.10000    0.25000    0.36000    0.30000    0.29000    0.08000\n    \"\"\")\n\n\nclass AtkinsonBoore2003SSlabCascadiaNSHMP2008(AtkinsonBoore2003SSlabCascadia,\n                                              AtkinsonBoore2003SSlabNSHMP2008):\n    \"\"\"\n    Combines :class:`AtkinsonBoore2003SSlabNSHMP2008` for NSHMP site\n    amplification with :class:`AtkinsonBoore2003SSlabCascadia` for Cascadia.\n    \"\"\"\n    pass\n\n\nclass AtkinsonBoore2003SSlabJapan(AtkinsonBoore2003SSlab):\n    \"\"\"\n    Extends :class:`AtkinsonBoore2003SSlab` but substitutes values for c1 from\n    Table 3 which incorporate correction factors for Japan.\n    \"\"\"\n\n    COEFFS_SSLAB = CoeffsTable(sa_damping=5, table=\"\"\"\\\n    IMT      c1      c2         c3         c4         c5          c6         c7         sigma      s1        s2\n    pga      0.10    0.69090    0.01130    -0.00202    0.19000    0.24000    0.29000    0.27000    0.23000    0.14000\n    0.0400   0.68    0.63273    0.01275    -0.00234    0.15000    0.20000    0.20000    0.25000    0.24000    0.07000\n    0.1000   0.61    0.66675    0.01080    -0.00219    0.15000    0.23000    0.20000    0.28000    0.27000    0.07000\n    0.2000   0.70    0.69186    0.00572    -0.00192    0.15000    0.27000    0.25000    0.28000    0.26000    0.10000\n    0.4000   0.07    0.77270    0.00173    -0.00178    0.13000    0.37000    0.38000    0.28000    0.26000    0.10000\n    1.0000  -0.98    0.87890    0.00130    -0.00173    0.10000    0.30000    0.55000    0.29000    0.27000    0.11000\n    2.0000  -2.44    0.99640    0.00364    -0.00118    0.10000    0.25000    0.40000    0.30000    0.28000    0.11000\n    3.0000  -3.73    1.11690    0.00615    -0.00045    0.10000    0.25000    0.36000    0.30000    0.29000    0.08000\n    \"\"\")\n\n\nclass AtkinsonBoore2003SSlabJapanNSHMP2008(AtkinsonBoore2003SSlabJapan,\n                                           AtkinsonBoore2003SSlabNSHMP2008):\n    \"\"\"\n    Combines :class:`AtkinsonBoore2003SSlabNSHMP2008` for NSHMP site\n    amplification with :class:`AtkinsonBoore2003SSlabJapan` for Japan.\n\n    Validation test vector was generated by applying increments in columns 1\n    and 2 of Table 3 to test vector for\n    AtkinsonBoore2003SSlabCascadiaNSHMP2008.\n    \"\"\"\n    pass\n", "meta": {"hexsha": "34e0740a11cc31a70cc3b9aef5f8c1881b926aa5", "size": 22626, "ext": "py", "lang": "Python", "max_stars_repo_path": "openquake.hazardlib/openquake/hazardlib/gsim/atkinson_boore_2003.py", "max_stars_repo_name": "rainzhop/ConvNetQuake", "max_stars_repo_head_hexsha": "a3e6de3f7992eac72f1b9883fec36b8c7fdefd48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "openquake.hazardlib/openquake/hazardlib/gsim/atkinson_boore_2003.py", "max_issues_repo_name": "rainzhop/ConvNetQuake", "max_issues_repo_head_hexsha": "a3e6de3f7992eac72f1b9883fec36b8c7fdefd48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openquake.hazardlib/openquake/hazardlib/gsim/atkinson_boore_2003.py", "max_forks_repo_name": "rainzhop/ConvNetQuake", "max_forks_repo_head_hexsha": "a3e6de3f7992eac72f1b9883fec36b8c7fdefd48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.9821073559, "max_line_length": 129, "alphanum_fraction": 0.6084150977, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.18875758954940733}}
{"text": "\"\"\" graph functions that depend on resonance structure\n\nBEFORE ADDING ANYTHING, SEE IMPORT HIERARCHY IN __init__.py!!!!\n\"\"\"\nimport itertools\nimport functools\nimport numpy\nfrom automol.util import dict_\nfrom automol.graph.base._algo import atom_groups\nfrom automol.graph.base._algo import isomorphism\nfrom automol.graph.base._algo import connected_components\nfrom automol.graph.base._core import atoms\nfrom automol.graph.base._core import atom_keys\nfrom automol.graph.base._core import bond_keys\nfrom automol.graph.base._core import bond_orders\nfrom automol.graph.base._core import set_bond_orders\nfrom automol.graph.base._core import atom_hybridizations\nfrom automol.graph.base._core import atom_unsaturated_valences\nfrom automol.graph.base._core import remove_atoms\nfrom automol.graph.base._core import remove_bonds\nfrom automol.graph.base._core import without_dummy_atoms\nfrom automol.graph.base._core import without_bond_orders\nfrom automol.graph.base._core import without_dummy_bonds\nfrom automol.graph.base._core import without_fractional_bonds\nfrom automol.graph.base._core import maximum_spin_multiplicity\nfrom automol.graph.base._core import implicit\nfrom automol.graph.base._core import subgraph\nfrom automol.graph.base._core import atoms_bond_keys\nfrom automol.graph.base._core import atoms_neighbor_atom_keys\nfrom automol.graph.base._core import dummy_atoms_neighbor_atom_key\n\n\n# # core functions\ndef dominant_resonance(rgr):\n    \"\"\" *a* dominant (minimum spin/maximum pi) resonance graph\n    \"\"\"\n    return next(iter(dominant_resonances(rgr)))\n\n\ndef dominant_resonances(rgr):\n    \"\"\" all dominant (minimum spin/maximum pi) resonance graphs\n    \"\"\"\n    rgr = without_fractional_bonds(rgr)\n    rgrs = resonances(rgr)\n    mult_min = min(map(maximum_spin_multiplicity, rgrs))\n    dom_rgrs = tuple(\n        rgr for rgr in rgrs if maximum_spin_multiplicity(rgr) == mult_min)\n    return dom_rgrs\n\n\ndef resonances(rgr):\n    \"\"\" all resonance graphs with this connectivity\n    \"\"\"\n    return subresonances(without_bond_orders(rgr))\n\n\ndef subresonances(rgr):\n    \"\"\" this connected graph and its lower-spin (more pi-bonded) resonances\n    \"\"\"\n    rgr = without_fractional_bonds(rgr)\n    # get the bond capacities (room for increasing bond order), filtering out\n    # the negative ones to avoid complications with hypervalent atoms in TSs\n    bnd_cap_dct = dict_.by_value(_bond_capacities(rgr), lambda x: x > 0)\n\n    ret_rgrs = []\n    if bnd_cap_dct:\n        bnd_keys, bnd_caps = zip(*bnd_cap_dct.items())\n        atm_keys = list(functools.reduce(frozenset.union, bnd_keys))\n\n        # Loop over all possible combinations of bond order increments (amounts\n        # by which to increase the bond order), filtering out combinations that\n        # exceed the valences of the atoms involved.\n        # (Note that we are only testing the bonds with available pi electrons,\n        # so this is compatible with having hypervalent atoms elsewhere in the\n        # molecule)\n        bnd_ord_inc_ranges = [range(bnd_cap+1) for bnd_cap in bnd_caps]\n        for bnd_ord_incs in itertools.product(*bnd_ord_inc_ranges):\n            bnd_ord_inc_dct = dict(zip(bnd_keys, bnd_ord_incs))\n            ret_rgr = _add_pi_bonds(rgr, bnd_ord_inc_dct)\n\n            max_bnd_ord = max(bond_orders(ret_rgr).values())\n\n            atm_unsat_vlcs = dict_.values_by_key(\n                atom_unsaturated_valences(ret_rgr), atm_keys)\n\n            if not any(atm_unsat_vlc < 0 for atm_unsat_vlc in atm_unsat_vlcs):\n                if max_bnd_ord < 4:\n                    ret_rgrs.append(ret_rgr)\n\n    if not ret_rgrs:\n        ret_rgrs = (rgr,)\n    else:\n        ret_rgrs = tuple(ret_rgrs)\n\n    return ret_rgrs\n\n\ndef resonance_dominant_bond_orders(rgr):\n    \"\"\" resonance-dominant bond orders, by bond\n    \"\"\"\n    rgr = without_fractional_bonds(rgr)\n    bnd_keys = list(bond_keys(rgr))\n    bnd_ords_by_res = [\n        dict_.values_by_key(bond_orders(dom_rgr), bnd_keys)\n        for dom_rgr in dominant_resonances(rgr)]\n    bnd_ords_lst = list(map(frozenset, zip(*bnd_ords_by_res)))\n    bnd_dom_res_ords_dct = dict(zip(bnd_keys, bnd_ords_lst))\n    return bnd_dom_res_ords_dct\n\n\ndef one_resonance_dominant_bond_orders(rgr):\n    \"\"\" resonance-dominant bond orders, by bond\n    \"\"\"\n    rgr = without_fractional_bonds(rgr)\n    bnd_keys = list(bond_keys(rgr))\n    bnd_ords_by_res = [\n        dict_.values_by_key(bond_orders(dom_rgr), bnd_keys)\n        for dom_rgr in dominant_resonances(rgr)]\n    first_bnd_ords = [bnd_ords_by_res[0]]\n    bnd_ords_lst = list(map(frozenset, zip(*first_bnd_ords)))\n    bnd_dom_res_ords_dct = dict(zip(bnd_keys, bnd_ords_lst))\n    return bnd_dom_res_ords_dct\n\n\ndef resonance_avg_bond_orders(rgr):\n    \"\"\" resonance-dominant bond orders, by bond\n    \"\"\"\n    rgr = without_fractional_bonds(rgr)\n    bnd_keys = list(bond_keys(rgr))\n    bnd_ords_by_res = [\n        dict_.values_by_key(bond_orders(dom_rgr), bnd_keys)\n        for dom_rgr in dominant_resonances(rgr)]\n    nres = len(bnd_ords_by_res)\n    bnd_ords_lst = zip(*bnd_ords_by_res)\n    avg_bnd_ord_lst = [sum(bnd_ords)/nres for bnd_ords in bnd_ords_lst]\n    avg_bnd_ord_dct = dict(zip(bnd_keys, avg_bnd_ord_lst))\n    return avg_bnd_ord_dct\n\n\n# # derived properties\ndef linear_atom_keys(rgr, dummy=True):\n    \"\"\" atoms forming linear bonds, based on their hybridization\n\n    :param rgr: the graph\n    :param dummy: whether or not to consider atoms connected to dummy atoms as\n        linear, if different from what would be predicted based on their\n        hybridization\n    :returns: the linear atom keys\n    :rtype: tuple[int]\n    \"\"\"\n    rgr = without_fractional_bonds(rgr)\n    atm_hyb_dct = resonance_dominant_atom_hybridizations(implicit(rgr))\n    lin_atm_keys = set(dict_.keys_by_value(atm_hyb_dct, lambda x: x == 1))\n\n    if dummy:\n        dum_ngb_key_dct = dummy_atoms_neighbor_atom_key(rgr)\n        lin_atm_keys |= set(dum_ngb_key_dct.values())\n\n    lin_atm_keys = tuple(sorted(lin_atm_keys))\n    return lin_atm_keys\n\n\ndef linear_segments_atom_keys(gra, lin_keys=None):\n    \"\"\" atom keys for linear segments in the graph\n    \"\"\"\n    ngb_keys_dct = atoms_neighbor_atom_keys(without_dummy_atoms(gra))\n\n    lin_keys = (linear_atom_keys(gra, dummy=True)\n                if lin_keys is None else lin_keys)\n\n    lin_keys = [k for k in lin_keys if len(ngb_keys_dct[k]) <= 2]\n\n    lin_segs = connected_components(subgraph(gra, lin_keys))\n\n    lin_keys_lst = []\n    for lin_seg in lin_segs:\n        lin_seg_keys = atom_keys(lin_seg)\n        if len(lin_seg_keys) == 1:\n            key, = lin_seg_keys\n            lin_keys_lst.append([key])\n        else:\n            end_key1, end_key2 = sorted([\n                key for key, ngb_keys in\n                atoms_neighbor_atom_keys(lin_seg).items()\n                if len(ngb_keys) == 1])\n            ngb_keys_dct = atoms_neighbor_atom_keys(lin_seg)\n\n            key = None\n            keys = [end_key1]\n            while key != end_key2:\n                key, = ngb_keys_dct[keys[-1]] - set(keys)\n                keys.append(key)\n            lin_keys_lst.append(keys)\n\n    lin_keys_lst = tuple(map(tuple, lin_keys_lst))\n    return lin_keys_lst\n\n\ndef radical_atom_keys(gra, single_res=False, min_valence=1.):\n    \"\"\" Radical atom keys for this molecular graph\n\n    Radical atoms are based on the lowest-spin resonance structures for this\n    graph. If the `single_res` flag is set, a single low-spin resonance\n    structure will be chosen when there are multiple such structures.\n\n    This function should eventually replace both\n    `resonance_dominant_radical_atom_keys` and\n    `sing_res_dom_radical_atom_keys` for a more user-friendly interface.\n\n    Note that this function ignores the bond orders in `gra`. If you wish to\n    identify radical atom keys based on the bond orders in `gra`, this can be\n    done by using the `atom_unsaturated_valences` function.\n\n    :param gra: the molecular graph\n    :param single_res: only include radical keys for a single (arbitrary)\n        resonance structure, or include all atoms that are radicals in any of\n        the low-spin resonance structures?\n    :type single_res: bool\n    :param min_valence: optionally, specify that only sites with at least a\n        certain number of radical electrons be included\n    :type min_valence: int\n    :returns: the radical atom keys\n    :rtype: frozenset[int]\n\n    \"\"\"\n    gra = without_fractional_bonds(gra)\n    atm_keys = list(atom_keys(gra))\n\n    if single_res:\n        atm_rad_vlcs = dict_.values_by_key(\n            atom_unsaturated_valences(dominant_resonance(gra)), atm_keys)\n    else:\n        atm_rad_vlcs_by_res = [\n            dict_.values_by_key(atom_unsaturated_valences(dom_gra), atm_keys)\n            for dom_gra in dominant_resonances(gra)]\n        atm_rad_vlcs = [\n            max(rad_vlcs) for rad_vlcs in zip(*atm_rad_vlcs_by_res)]\n\n    atm_rad_keys = frozenset(atm_key for atm_key, atm_rad_vlc\n                             in zip(atm_keys, atm_rad_vlcs)\n                             if atm_rad_vlc >= min_valence)\n    return atm_rad_keys\n\n\ndef has_separated_radical_sites(gra):\n    \"\"\" does this radical have two or more separated radical sites?\n\n    The identification is performed based on one of its lowest-spin resonance\n    structures. It shouldn't matter which of the low-spin resonance structures\n    is used -- if one of them has separated radical sites, they all should.\n\n    This identifies polyradical molecules, but excludes things like carbenes.\n\n    :param gra: the graph\n    :returns: True if it has, False if not\n    :rtype: bool\n    \"\"\"\n    rad_atm_keys = radical_atom_keys(gra, single_res=True)\n    return len(rad_atm_keys) > 1\n\n\ndef nonresonant_radical_atom_keys(rgr):\n    \"\"\" keys for radical atoms that are not in resonance\n    \"\"\"\n    rgr = without_fractional_bonds(rgr)\n    atm_keys = list(atom_keys(rgr))\n    atm_rad_vlcs_by_res = [\n        dict_.values_by_key(atom_unsaturated_valences(dom_rgr), atm_keys)\n        for dom_rgr in dominant_resonances(rgr)]\n    atm_rad_vlcs = [min(rad_vlcs) for rad_vlcs in zip(*atm_rad_vlcs_by_res)]\n    atm_rad_keys = frozenset(atm_key for atm_key, atm_rad_vlc\n                             in zip(atm_keys, atm_rad_vlcs) if atm_rad_vlc)\n    return atm_rad_keys\n\n\ndef sigma_radical_atom_keys(rgr):\n    \"\"\" keys for sigma radical atoms\n    \"\"\"\n    rgr = without_fractional_bonds(rgr)\n    atm_rad_keys = nonresonant_radical_atom_keys(rgr)\n    bnd_ords_dct = resonance_dominant_bond_orders(rgr)\n    atm_bnd_keys_dct = atoms_bond_keys(rgr)\n    atm_sig_keys = []\n    for atm_key in atm_rad_keys:\n        for bnd_key in atm_bnd_keys_dct[atm_key]:\n            if 3 in bnd_ords_dct[bnd_key]:\n                atm_sig_keys.append(atm_key)\n                break\n    atm_sig_keys = frozenset(atm_sig_keys)\n    return atm_sig_keys\n\n\ndef resonance_dominant_radical_atom_keys(rgr):\n    \"\"\" resonance-dominant radical atom keys\n\n    TODO: DEPRECATE\n\n    (keys of resonance-dominant radical sites)\n    \"\"\"\n    rgr = without_fractional_bonds(rgr)\n    atm_keys = list(atom_keys(rgr))\n    atm_rad_vlcs_by_res = [\n        dict_.values_by_key(atom_unsaturated_valences(dom_rgr), atm_keys)\n        for dom_rgr in dominant_resonances(rgr)]\n    atm_rad_vlcs = [max(rad_vlcs) for rad_vlcs in zip(*atm_rad_vlcs_by_res)]\n    atm_rad_keys = frozenset(atm_key for atm_key, atm_rad_vlc\n                             in zip(atm_keys, atm_rad_vlcs) if atm_rad_vlc)\n    return atm_rad_keys\n\n\ndef sing_res_dom_radical_atom_keys(rgr):\n    \"\"\" resonance-dominant radical atom keys,for one resonance\n\n    TODO: DEPRECATE\n    \"\"\"\n    rgr = without_fractional_bonds(rgr)\n    atm_keys = list(atom_keys(rgr))\n    atm_rad_vlcs_by_res = [\n        dict_.values_by_key(atom_unsaturated_valences(dom_rgr), atm_keys)\n        for dom_rgr in dominant_resonances(rgr)]\n    first_atm_rad_val = [atm_rad_vlcs_by_res[0]]\n    atm_rad_vlcs = [max(rad_vlcs) for rad_vlcs in zip(*first_atm_rad_val)]\n    atm_rad_keys = frozenset(atm_key for atm_key, atm_rad_vlc\n                             in zip(atm_keys, atm_rad_vlcs) if atm_rad_vlc)\n    return atm_rad_keys\n\n\ndef radical_groups(gra):\n    \"\"\" returns a list of lists of groups attached each radical\n    \"\"\"\n    gra = without_fractional_bonds(gra)\n\n    groups = []\n    rads = sing_res_dom_radical_atom_keys(gra)\n    for rad in rads:\n        groups.append(atom_groups(gra, rad))\n    return groups\n\n\ndef radical_group_dct(gra):\n    \"\"\" return a dictionary of lists of groups attached each radical\n    \"\"\"\n    gra = without_fractional_bonds(gra)\n\n    groups = {}\n    rads = list(sing_res_dom_radical_atom_keys(gra))\n    atms = atoms(gra)\n    for rad in rads:\n        key = atms[rad][0]\n        if key in groups:\n            groups[atms[rad][0]] += atom_groups(gra, rad)\n        else:\n            groups[atms[rad][0]] = atom_groups(gra, rad)\n\n    return groups\n\n\ndef radical_dissociation_prods(gra, pgra1):\n    \"\"\" given a dissociation product, determine the other product\n    \"\"\"\n    gra = without_fractional_bonds(gra)\n\n    pgra2 = None\n    rads = sing_res_dom_radical_atom_keys(gra)\n    adj_atms = atoms_neighbor_atom_keys(gra)\n    # adj_idxs = tuple(adj_atms[rad] for rad in rads)\n    for rad in rads:\n        for adj in adj_atms[rad]:\n            for group in atom_groups(gra, adj, stereo=False):\n                if isomorphism(group, pgra1, backbone_only=True):\n                    pgra2 = remove_atoms(gra, atom_keys(group))\n                    # pgra2 = remove_bonds(pgra2, bond_keys(group))\n                    if bond_keys(group) in pgra2:\n                        pgra2 = remove_bonds(pgra2, bond_keys(group))\n    return (pgra1, pgra2)\n\n\ndef sp2_bond_keys(gra):\n    \"\"\" determine the sp2 bonds in this graph\n    \"\"\"\n    gra = without_bond_orders(gra)\n    bnd_keys = dict_.keys_by_value(\n        resonance_dominant_bond_orders(gra), lambda x: 2 in x)\n\n    # make sure both ends are sp^2 (excludes cumulenes)\n    atm_hyb_dct = resonance_dominant_atom_hybridizations(gra)\n    sp2_atm_keys = dict_.keys_by_value(atm_hyb_dct, lambda x: x == 2)\n    bnd_keys = frozenset({bnd_key for bnd_key in bnd_keys\n                          if bnd_key <= sp2_atm_keys})\n    return bnd_keys\n\n\ndef resonance_dominant_atom_hybridizations(rgr):\n    \"\"\" resonance-dominant atom hybridizations, by atom\n    \"\"\"\n    rgr = without_fractional_bonds(rgr)\n    atm_keys = list(atom_keys(rgr))\n    atm_hybs_by_res = [\n        dict_.values_by_key(atom_hybridizations(dom_rgr), atm_keys)\n        for dom_rgr in dominant_resonances(rgr)]\n    atm_hybs = [min(hybs) for hybs in zip(*atm_hybs_by_res)]\n    atm_hyb_dct = dict(zip(atm_keys, atm_hybs))\n    return atm_hyb_dct\n\n\ndef resonance_dominant_atom_centered_cumulene_keys(rgr):\n    \"\"\" resonance dominant keys for atom-centered cumulenes\n\n    the bond-centered cumulenes are described by\n        (frozenset({end_atm_key1, end_atm_key2}), cent_atm_key)\n    where the first pair contains the sp2 atoms at the cumulene ends and\n    `cent_atm_key` is the key of the central atom\n    \"\"\"\n    rgr = without_fractional_bonds(rgr)\n    cum_chains = _cumulene_chains(rgr)\n    cum_keys = set()\n    for cum_chain in cum_chains:\n        size = len(cum_chain)\n        if size % 2 == 1:\n            cum_keys.add(\n                (frozenset({cum_chain[0], cum_chain[-1]}),\n                 cum_chain[size // 2])\n            )\n    cum_keys = frozenset(cum_keys)\n    return cum_keys\n\n\ndef resonance_dominant_bond_centered_cumulene_keys(rgr):\n    \"\"\" resonance dominant keys for bond-centered cumulenes\n\n    the bond-centered cumulenes are described by\n        (frozenset({end_atm_key1, end_atm_key2}),\n         frozenset({cent_atm_key1, cent_atm_key2}))\n    where the first pair contains the sp2 atoms at the cumulene ends and the\n    second pair is the bond key for the central bond\n    \"\"\"\n    rgr = without_fractional_bonds(rgr)\n    cum_chains = _cumulene_chains(rgr)\n    cum_keys = set()\n    for cum_chain in cum_chains:\n        size = len(cum_chain)\n        if size % 2 == 0:\n            cum_keys.add(\n                (frozenset({cum_chain[0], cum_chain[-1]}),\n                 frozenset({cum_chain[size // 2 - 1], cum_chain[size // 2]}))\n            )\n    cum_keys = frozenset(cum_keys)\n    return cum_keys\n\n\n# # helpers\ndef _bond_capacities(rgr):\n    \"\"\" the number of electron pairs available for further pi-bonding, by bond\n    \"\"\"\n    rgr = without_dummy_bonds(rgr)\n    atm_unsat_vlc_dct = atom_unsaturated_valences(rgr)\n\n    def _pi_capacities(bnd_key):\n        return min(map(atm_unsat_vlc_dct.__getitem__, bnd_key))\n\n    bnd_keys = list(bond_keys(rgr))\n    bnd_caps = tuple(map(_pi_capacities, bnd_keys))\n    bnd_cap_dct = dict(zip(bnd_keys, bnd_caps))\n    return bnd_cap_dct\n\n\ndef _add_pi_bonds(rgr, bnd_ord_inc_dct):\n    \"\"\" add pi bonds to this graph\n    \"\"\"\n    bnd_keys = bond_keys(rgr)\n    assert set(bnd_ord_inc_dct.keys()) <= bnd_keys\n\n    bnd_keys = list(bnd_keys)\n    bnd_ords = dict_.values_by_key(bond_orders(rgr), bnd_keys)\n    bnd_ord_incs = dict_.values_by_key(bnd_ord_inc_dct, bnd_keys, fill_val=0)\n    new_bnd_ords = numpy.add(bnd_ords, bnd_ord_incs)\n    bnd_ord_dct = dict(zip(bnd_keys, new_bnd_ords))\n    rgr = set_bond_orders(rgr, bnd_ord_dct)\n    return rgr\n\n\ndef _cumulene_chains(rgr):\n    atm_hyb_dct = resonance_dominant_atom_hybridizations(rgr)\n    sp1_atm_keys = dict_.keys_by_value(atm_hyb_dct, lambda x: x == 1)\n    sp2_atm_keys = dict_.keys_by_value(atm_hyb_dct, lambda x: x == 2)\n\n    atm_ngb_keys_dct = atoms_neighbor_atom_keys(rgr)\n\n    def _cumulene_chain(chain):\n        ret = None\n        atm_key = chain[-1]\n        next_atm_keys = atm_ngb_keys_dct[atm_key] - {chain[-2]}\n        if next_atm_keys:\n            assert len(next_atm_keys) == 1\n            next_atm_key, = next_atm_keys\n            if next_atm_key in sp1_atm_keys:\n                chain.append(next_atm_key)\n                ret = _cumulene_chain(chain)\n            elif next_atm_key in sp2_atm_keys:\n                chain.append(next_atm_key)\n                ret = chain\n        return ret\n\n    cum_chains = []\n    for atm_key in sp2_atm_keys:\n        sp1_atm_ngb_keys = atm_ngb_keys_dct[atm_key] & sp1_atm_keys\n        chains = [[atm_key, atm_ngb_key] for atm_ngb_key in sp1_atm_ngb_keys]\n        for chain in chains:\n            cum_chain = _cumulene_chain(chain)\n            if cum_chain is not None:\n                cum_chains.append(cum_chain)\n\n    cum_chains = tuple(map(tuple, cum_chains))\n    return cum_chains\n", "meta": {"hexsha": "ac3ce43e16057501b0e21557157d521f6c077ca7", "size": 18384, "ext": "py", "lang": "Python", "max_stars_repo_path": "automol/graph/base/_resonance.py", "max_stars_repo_name": "snelliott/automol", "max_stars_repo_head_hexsha": "d1f7d51c1bbe06ba7569ea7c75304618cebee198", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-01T14:23:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T19:17:08.000Z", "max_issues_repo_path": "automol/graph/base/_resonance.py", "max_issues_repo_name": "snelliott/automol", "max_issues_repo_head_hexsha": "d1f7d51c1bbe06ba7569ea7c75304618cebee198", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-12T21:02:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-12T21:35:33.000Z", "max_forks_repo_path": "automol/graph/base/_resonance.py", "max_forks_repo_name": "snelliott/automol", "max_forks_repo_head_hexsha": "d1f7d51c1bbe06ba7569ea7c75304618cebee198", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-12-12T18:41:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-11T20:12:14.000Z", "avg_line_length": 35.6970873786, "max_line_length": 79, "alphanum_fraction": 0.6916884247, "include": true, "reason": "import numpy", "num_tokens": 5021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.18875758458022002}}
{"text": "import numpy as np\nimport pandas as pd\nimport os\n\nclass HemibrainALSim:\n    def __init__(self, file_folder = 'data/', dfpath = 'adult_hallem06.csv', threshold=5., return_flycircuit=True):\n        \"\"\"Creates the AL with a simple model for Hemibrain and FlyCircuit.\n        \n        # Arguments:\n            file_folder (str): The folder with the matrices to load for presynaptically acting and postsynaptically acting LNs.\n            dfpath (str): The path to the csv file to be used for loading the affinity values.\n        \"\"\"\n        df = pd.read_csv(os.path.join(file_folder, dfpath) )\n        all_odorant_names = list(df.iloc[:,0])\n\n        self.preLN_field = np.load(os.path.join(file_folder, 'preLN_field.npy'))\n        self.postLN_field = np.load(os.path.join(file_folder, 'postLN_field.npy'))\n        self.preLN_field_a = np.load(os.path.join(file_folder, 'preLN_field_a.npy')) # OSN-to-LN\n        self.preLN_field_b = np.load(os.path.join(file_folder, 'preLN_field_b.npy')) # LN-to-PN\n\n        glom_names = ['VP3',\n                      'VC3l',\n                      'VP5',\n                      'DL2v',\n                      'V',\n                      'VL2a',\n                      'VC5',\n                      'DM4',\n                      'DM3',\n                      'DA4m',\n                      'VP2',\n                      'VP1l',\n                      'DL2d',\n                      'VP1m',\n                      'DM5',\n                      'DC4',\n                      'DA1',\n                      'VA3',\n                      'VM2',\n                      'D',\n                      'VL2p',\n                      'VM5d',\n                      'VA1v',\n                      'DL3',\n                      'VA7m',\n                      'DA2',\n                      'VM7d',\n                      'VC3m',\n                      'VM1',\n                      'VM4',\n                      'VA4',\n                      'DL1',\n                      'DC1',\n                      'DA4l',\n                      'DP1m',\n                      'VA2',\n                      'VA1d',\n                      'DM2',\n                      'DP1l',\n                      'VC4',\n                      'VM7v',\n                      'VA5',\n                      'VA6',\n                      'DC2',\n                      'DM1',\n                      'DL4',\n                      'VA7l',\n                      'DM6',\n                      'VM3',\n                      'VM5v',\n                      'VC2',\n                      'DA3',\n                      'DC3',\n                      'DL5',\n                      'VC1',\n                      'VL1']\n\n        GL_to_OR = {\n                'D': {'receptors': ['OR69a','OR69b'], 'name': 'ab9', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'antenna'},\n                'DA1': {'receptors': ['OR67d'], 'name': 'at1A', 'co-receptors': ['Orco'], 'sensillum': 'trichodea', 'sensillum location': 'antenna'},\n                'DA2': {'receptors': ['OR33a','OR56a'], 'name': 'ab4B', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'antenna'},\n                'DA3': {'receptors': ['OR23a'], 'name': 'at2B', 'co-receptors': ['Orco'], 'sensillum': 'trichodea', 'sensillum location': 'antenna'},\n                'DA4l': {'receptors': ['OR43a'], 'name': 'at3', 'co-receptors': ['Orco'], 'sensillum': 'trichodea', 'sensillum location': 'antenna'},\n                'DA4m': {'receptors': ['OR2a'], 'name': 'at3', 'co-receptors': ['Orco'], 'sensillum': 'trichodea', 'sensillum location': 'antenna'},\n                'DC1': {'receptors': ['OR19a','OR19b'], 'name': 'at3A', 'co-receptors': ['Orco'], 'sensillum': 'trichodea', 'sensillum location': 'antenna'},\n                'DC2': {'receptors': ['OR13a'], 'name': 'ab6A', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'antenna'},\n                'DC3': {'receptors': ['OR83c'], 'name': 'at2A', 'co-receptors': ['Orco'], 'sensillum': 'trichodea', 'sensillum location': 'antenna'},\n                'DC4': {'receptors': ['IR64a'], 'name': 'Sac III', 'co-receptors': ['IR8a'], 'sensillum': 'sacculus', 'sensillum location': 'antenna'},\n                'DL1': {'receptors': ['OR10a','GR10a'], 'name': 'ab1D', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'antenna'},\n                'DL2d': {'receptors': ['IR75b'], 'name': 'ac3A', 'co-receptors': ['IR8a'], 'sensillum': 'coeloconica', 'sensillum location': 'antenna'},\n                'DL2v': {'receptors': ['IR75c'], 'name': 'ac3A', 'co-receptors': ['IR8a'], 'sensillum': 'coeloconica', 'sensillum location': 'antenna'},\n                'DL3': {'receptors': ['OR65a','OR65b','OR65c'], 'name': 'at4B', 'co-receptors': ['Orco'], 'sensillum': 'trichodea', 'sensillum location': 'antenna'},\n                'DL4': {'receptors': ['OR49a','OR85f'], 'name': 'ab10B', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'antenna'},\n                'DL5': {'receptors': ['OR7a'], 'name': 'ab4A', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'antenna'},\n                'DM1': {'receptors': ['OR42b'], 'name': 'ab1A', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'antenna'},\n                'DM2': {'receptors': ['OR22a','OR22b'], 'name': 'ab3A', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'antenna'},\n                'DM3': {'receptors': ['OR47a','OR33b'], 'name': 'ab5B', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'antenna'},\n                'DM4': {'receptors': ['OR59b'], 'name': 'ab2A', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'antenna'},\n                'DM5': {'receptors': ['OR33b','OR85a'], 'name': 'ab2B', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'antenna'},\n                'DM6': {'receptors': ['OR67a'], 'name': 'ab10B', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'antenna'},\n                'DP1l': {'receptors': ['IR75a'], 'name': 'ac2', 'co-receptors': ['IR8a'], 'sensillum': 'coeloconica', 'sensillum location': 'antenna'},\n                'DP1m': {'receptors': ['IR64a'], 'name': 'Sac III', 'co-receptors': ['IR8a'], 'sensillum': 'sacculus', 'sensillum location': 'antenna'},\n                'V': {'receptors': ['GR21a','GR63a'], 'name': 'ab1C', 'co-receptors': [], 'sensillum': 'sacculus', 'sensillum location': 'antenna'},\n                'DA4l': {'receptors': ['OR43a'], 'name': 'at3', 'co-receptors': ['Orco'], 'sensillum': 'trichodea', 'sensillum location': 'antenna'},\n                'VA1d': {'receptors': ['OR88a'], 'name': 'at4C', 'co-receptors': ['Orco'], 'sensillum': 'trichodea', 'sensillum location': 'antenna'},\n                'VA1v': {'receptors': ['OR47b'], 'name': 'at4A', 'co-receptors': ['Orco'], 'sensillum': 'trichodea', 'sensillum location': 'antenna'},\n                'VA2': {'receptors': ['OR92a'], 'name': 'ab1B', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'antenna'},\n                'VA3': {'receptors': ['OR67b'], 'name': 'ab9', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'antenna'},\n                'VA4': {'receptors': ['OR85d'], 'name': 'pb3B', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'maxillary pulp'},\n                'VA5': {'receptors': ['OR49b'], 'name': 'ab6B', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'antenna pulp'},\n                'VA6': {'receptors': ['OR82a'], 'name': 'ab5A', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'antenna pulp'},\n                'VA7l': {'receptors': ['OR46a'], 'name': 'pb2B', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'maxillary pulp'},\n                'VA7m': {'receptors': [], 'name': '', 'co-receptors': [], 'sensillum': 'unknown', 'sensillum location': 'unknown'},\n                'VC1': {'receptors': ['OR33c,OR85e'], 'name': 'pb2A', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'maxillary pulp'},\n                'VC2': {'receptors': ['OR71a'], 'name': 'pb1B', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'maxillary pulp'},\n                'VC3l': {'receptors': ['OR35a'], 'name': 'ac1', 'co-receptors': ['Orco'], 'sensillum': 'coeloconica', 'sensillum location': 'antenna'},\n                'VC3m': {'receptors': [], 'name': 'unknown', 'co-receptors': ['Orco'], 'sensillum': 'coeloconica', 'sensillum location': 'antenna'},\n                'VC4': {'receptors': ['OR67c'], 'name': 'ab7B', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'antenna'},\n                'VC5': {'receptors': ['IR41a'], 'name': 'IR25a,IR76b', 'co-receptors': ['Orco'], 'sensillum': 'coeloconica', 'sensillum location': 'antenna'},\n                'VL1': {'receptors': ['IR75d'], 'name': 'ac1', 'co-receptors': ['IR25a'], 'sensillum': 'coeloconica', 'sensillum location': 'antenna'},\n                'VM7d': {'receptors': ['OR42a'], 'name': 'pb1A', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'maxillary pulp'},\n                'VM7v': {'receptors': ['OR59c'], 'name': 'pb3A', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'maxillary pulp'},\n                'VM5v': {'receptors': ['OR98a'], 'name': 'ab7A', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'antenna'},\n                'VM5d': {'receptors': ['OR85b','OR98b'], 'name': 'ab3B', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'antenna'},\n                'VM4': {'receptors': ['IR76a'], 'name': 'ac4', 'co-receptors': ['IR25a','IR76b'], 'sensillum': 'coeloconica', 'sensillum location': 'antenna'},\n                'VM3': {'receptors': ['OR9a'], 'name': 'ab8B', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'antenna'},\n                'VM2': {'receptors': ['OR43b'], 'name': 'ab8A', 'co-receptors': ['Orco'], 'sensillum': 'basiconica', 'sensillum location': 'antenna'},\n                'VM1': {'receptors': ['OR92a'], 'name': 'ac1', 'co-receptors': ['IR25a','IR76b'], 'sensillum': 'coeloconica', 'sensillum location': 'antenna'},\n                'VL2p': {'receptors': ['IR31a'], 'name': 'ac1', 'co-receptors': ['IR8a'], 'sensillum': 'coeloconica', 'sensillum location': 'antenna'},\n                'VL2a': {'receptors': ['IR84a'], 'name': 'ac4', 'co-receptors': ['IR8a'], 'sensillum': 'coeloconica', 'sensillum location': 'antenna'},\n                'VP3': {'receptors': [], 'name': 'ac4', 'co-receptors': ['IR8a'], 'sensillum': 'coeloconica', 'sensillum location': 'antenna'},\n                'VP5': {'receptors': [], 'name': 'ac4', 'co-receptors': ['IR8a'], 'sensillum': 'coeloconica', 'sensillum location': 'antenna'},\n                'VP2': {'receptors': [], 'name': 'ac4', 'co-receptors': ['IR8a'], 'sensillum': 'coeloconica', 'sensillum location': 'antenna'},\n                'VP1l': {'receptors': [], 'name': 'ac4', 'co-receptors': ['IR8a'], 'sensillum': 'coeloconica', 'sensillum location': 'antenna'},\n                'VP1m': {'receptors': [], 'name': 'ac4', 'co-receptors': ['IR8a'], 'sensillum': 'coeloconica', 'sensillum location': 'antenna'},\n            }\n\n        idx_a = all_odorant_names.index('putrescine')\n\n        b_array = np.array(list(df.iloc[idx_a,1:]))\n\n        or_names = [i.lower() for i in list(df.columns[1:])]\n        bj = []\n        or_names_found = []\n        or_inds_found = []\n        for i, val in enumerate(glom_names):\n            receptors = GL_to_OR[val]['receptors']\n            found = False\n            for j in receptors:\n                jreal = j\n                j = j.lower()\n                if j in or_names:\n                    bj.append(b_array[or_names.index(j)])\n                    found = True\n                    or_names_found.append(jreal)\n                    or_inds_found.append(len(bj)-1)\n            if found == False:\n                bj.append(0)\n        self.ngloms = 56\n        self.or_inds_found = or_inds_found\n        self.or_names_found = or_names_found\n        T = 50000\n        dt = 1e-4\n        bj = np.array(bj)\n\n        I = np.zeros((self.ngloms, T))\n        b = bj.reshape((-1,1))\n        b = np.repeat(b, T, axis=1)\n        I[:,10000:30000] = 5 + 0. * np.repeat(5.*np.random.random((1,20000)), self.ngloms, axis=0) # 1.\n        Ib = I*b\n\n        self.OSN = np.diff(np.floor(np.cumsum(Ib,axis=1)/threshold), axis=1)\n        self.Ib = Ib\n        self.threshold = threshold\n\n        self.base_hpf_gain = 10.\n        self.hemi_hpf_gain = 180.\n        self.hemi_preLN_gain = 5e3\n        self.preLN_linear_inhibition_gain = 1e-2\n        self.hemi_amp = 4.\n        self.osnf_filter = 20.\n        self.alpha = 1.\n        self.eps = 1e-1\n        self.dt = dt\n        self.T = T\n                                    \n    def sim(self, return_flycircuit=True):\n        \"\"\"Simulates the AL with a simple model for Hemibrain and FlyCircuit.\n        \n        # Arguments:\n            return_flycircuit (bool): Whether to return the FlyCircuit output or not.\n        \"\"\"\n        dt = self.dt\n        T = self.T\n        OSN = np.diff(np.floor(np.cumsum(self.Ib,axis=1)/self.threshold), axis=1)\n        W_OSNLN = self.preLN_field_a\n        W_PNLN = self.preLN_field_b.T\n        preLN = W_PNLN.dot(W_OSNLN.dot(self.OSN))\n        preLNbaseline = self.OSN\n        OSNf = self.OSN * 0.\n        alpha = 1.\n        for j in range(1,OSNf.shape[1]):\n            OSNf[:,j] = OSNf[:,j-1] + dt * (alpha * self.OSN[:,j]-self.osnf_filter*OSNf[:,j-1])\n        XONE = OSN * 0.\n        alpha = 1.\n        for j in range(1,XONE.shape[1]):\n            XONE[:,j] = XONE[:,j-1] + dt * (alpha * (1-XONE[:,j-1])*OSNf[:,j]-10.*XONE[:,j-1])\n        XONEf = XONE * 0.\n        alpha = 10.\n        for j in range(1,OSNf.shape[1]):\n            XONEf[:,j] = XONEf[:,j-1] + dt * (alpha * XONE[:,j]-10.0*XONEf[:,j-1])\n        OSNh = XONE - XONEf\n        OSNh = np.maximum(0., OSNh)\n        def lpass(X, alpha=10.):\n            Xf = X * 0.\n            for j in range(1,X.shape[1]):\n                Xf[:,j] = Xf[:,j-1] + dt * (alpha * X[:,j]-alpha*Xf[:,j-1])\n            return Xf\n\n        preLN = W_PNLN.dot(W_OSNLN.dot(OSNf))\n        preLNbaseline = OSNf\n        OSNhnew = W_PNLN.dot(W_OSNLN).dot(OSNf)\n        OSNhnew2 = self.postLN_field.dot(OSNh)\n\n        hemimodel = np.maximum(0.,self.hemi_amp * (self.hemi_preLN_gain * OSNf/(self.eps+1.*W_PNLN.dot(W_OSNLN).dot(OSNf))-self.preLN_linear_inhibition_gain*OSNhnew+self.hemi_hpf_gain*OSNhnew2))\n\n        basemodel = preLNbaseline.copy()\n        for j in range(1,basemodel.shape[1]):\n            if np.sqrt(np.sum((basemodel[:,j])**2))>1e-0:\n                basemodel[:,j] = basemodel[:,j] / np.sqrt(np.sum((basemodel[:,j])**2))\n        basemodel = lpass(basemodel) + self.base_hpf_gain * OSNh\n        if return_flycircuit:\n            return hemimodel, basemodel\n        else:\n            return hemimodel", "meta": {"hexsha": "44dc520e2b5f0363b405fa473f1a71edd749e946", "size": 15109, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/Adult Drosophila/al_example.py", "max_stars_repo_name": "FlyBrainLab/EOScircuits", "max_stars_repo_head_hexsha": "2ade33db402997f5001f1707f136370c660dce33", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/Adult Drosophila/al_example.py", "max_issues_repo_name": "FlyBrainLab/EOScircuits", "max_issues_repo_head_hexsha": "2ade33db402997f5001f1707f136370c660dce33", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/Adult Drosophila/al_example.py", "max_forks_repo_name": "FlyBrainLab/EOScircuits", "max_forks_repo_head_hexsha": "2ade33db402997f5001f1707f136370c660dce33", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.2936170213, "max_line_length": 194, "alphanum_fraction": 0.5047984645, "include": true, "reason": "import numpy", "num_tokens": 4678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.18875758085662953}}
{"text": "#!/usr/bin/env python\n\nimport io2, re, os, sys\nimport numpy as np\nfrom io2.gaussian_reader import GaussianReader as GR0\nimport aqml.cheminfo.molecule.molecule as cmm\nfrom aqml.cheminfo.core import *\nimport aqml.cheminfo.rdkit.core as crk\nfrom aqml.cheminfo.rw.ctab import *\nimport scipy.spatial.distance as ssd\n\nh2kc = io2.Units().h2kc\nT, F = True, False\nnp.set_printoptions(formatter={'float': '{: 0.4f}'.format})\n\n\nclass _atoms(object):\n    \"\"\" `atoms object from file formats other than xyz\"\"\"\n    def __init__(self, f):\n        import ase.io as aio\n        m = aio.read(f)\n        self.zs = m.numbers\n        self.coords = m.positions\n        self.na = len(self.zs)\n\nuc = io2.Units() # unit converter\n\ndef get_val(dic, key):\n    assert key in list(dic.keys()), '#ERROR: prop not found!'\n    if key in ['HF','MP2','MP3','MP4','CCSD','CCSD(T)']:\n        return '%.4f'%( dic[key]*uc.h2kc )\n    elif key in ['dipole']:\n        return '%.4f'%dic[key]\n    else:\n        raise '#ERROR: prop not found!'\n\n\nclass CM(object):\n    \"\"\"\n    coulomb matrix object\n    \"\"\"\n    def __init__(self, atoms, param={'M':'cml1','rp':1.,'wz':T,'sort':T}):\n        self.param = param\n        self.atoms = atoms\n        self.cml1 = T if param['M'] in ['cml1'] else F\n\n    def generate_coulomb_matrix(self):\n        \"\"\" Coulomb matrix\n\n        sorted CM has serious limitation when used to identify unique conformers.\n        E.g., for CH3-CH3 molecule, as the L1 norm of all H-containing columns are\n        the same, so shuffling such columns leads to different CM, though the molecule\n        remains unchanged\n\n        The limitation can be alleviated through the use of L1 norm of each column!!\n        \"\"\"\n        atoms = self.atoms\n        na = atoms.na\n        mat = np.zeros((na,na))\n        _ds = ssd.squareform( ssd.pdist(atoms.coords) )\n        dsp = _ds**self.param['rp']\n        np.fill_diagonal(dsp, 1.0)\n        zs = atoms.zs\n        _X, _Y = np.meshgrid(zs,zs)\n        if self.param['wz']:\n            mat = _X*_Y/dsp\n            diag = -np.array(zs)**2.4\n        else:\n            mat = 1/dsp\n            diag = np.zeros(na)\n        np.fill_diagonal(mat,  diag)\n        if self.param['sort']:\n            L1s = np.array([ np.sum(np.abs(mat[i])) for i in range(na) ])\n            ias = np.argsort(L1s)\n            if self.cml1:\n                x = L1s[ias]\n            else:\n                x = np.ravel(mat[ias,:][:,ias])\n        else:\n            x = np.ravel(mat)\n        #print 'x = ', x\n        return x\n\n\ndef cdist(objs, param={}):\n    _param = {'M':'cml1','rp':1.0,'sort':T,'wz':F}\n    for key in list(param.keys()):\n        if key in list(_param.keys()):\n            if param[key] != _param[key]:\n                _param[key] = param[key]\n    _xs = []\n    nc = len(objs)\n    for obj in objs:\n        if _param['M'] in ['cm','cml1']:\n            _xobj = CM(obj,_param)\n            xi = _xobj.generate_coulomb_matrix()#; print '              xi = ', xi\n            _xs.append( xi )\n        else:\n            raise '#ERROR: unknown `M'\n    xs = np.array(_xs)\n    return xs, ssd.squareform( ssd.pdist(xs,'cityblock') )\n\n\ndef get_alternative(s):\n    \"\"\" c1cccc[n]1 --> c1ccccn1 \"\"\"\n    patt = '\\[n\\]'\n    s = re.sub(patt,'n',s)\n    return s\n\n\nclass OptedMols(object):\n\n    \"\"\"\n    postprocess optimized goemetries (by G09)\n    so as to retrieve only the unqiue conformers\n    and then convert to sdf format with properties\n    embedded at the end of the file\n    \"\"\"\n\n    def __init__(self, fs, rsmi, props=['HF'], istart=0):\n        self.nc0 = len(fs)\n        fsc = []\n        cso = [] # mol objects\n        ms = [] # ase mols\n        ys = []\n        #assert '_c' in fs[0]\n        #self.filename = '_'.join( fs[0].split('/')[-1].split('_')[:-1] )\n        self.fs_diss = []\n        self.fs_redundant = []\n        cids = []\n        for i,f in enumerate(fs):\n            fmt = f[-3:]\n            if fmt in ['log','out']: #G09 output file\n                dic = GR0(f, istart=istart)[-1]\n                zs = np.array(dic['Atomic_numbers'],np.int)\n                coords = np.array( dic['Positions'] )\n                m = atoms(zs, coords)\n                try:\n                    co = cmm.Mol(zs, coords, ican=True)\n                    can2 = get_alternative(co.can)\n                    if rsmi not in [co.can,can2]:\n                        print(\"#ERROR: %s has a SMILES %s, differs from %s\"%(f,co.can,rsmi))\n                        self.fs_diss.append(f)\n                        continue\n                    else:\n                        _ys = {}\n                        for key in props:\n                            _ys[key] = get_val(dic,key)\n                        ys.append(_ys)\n                        ms.append(m); cso.append(co); fsc.append(f)\n                except:\n                    print(\"#ERROR: this is a radical!\")\n                    self.fs_diss.append(f)\n                    continue\n            elif fmt in ['mol','sdf']:\n                oo = crk.RDMol(f)\n                m = atoms(oo.zs, oo.coords)\n                ms.append(m)\n                cso.append( oo.prop['smiles_indigo'] )\n                fsc.append(f)\n                ys.append( [ oo.prop[k] for k in props ] )\n        self.cso = cso\n        self.ms = ms\n        self.fsc = fsc\n        self.nc = len(cso)\n        self.ys = ys\n\n    def prune_conformers(self, param={'M':'cml1','wz':F,'thresh':0.01}, KeepPat=None):\n        \"\"\" get unique conformers \"\"\"\n        ccidsr = [0,] # always keep the first conformer!!\n        if self.nc > 1:\n            xs, ds = cdist(self.ms, param=param)\n            #self.ds = ds\n            #seq = np.argsort(self.ys[:,0])\n            for i in range(1,self.nc):\n                #ic = seq[i]\n                if (not np.all(ds[i,ccidsr]>param['thresh'])):\n                    self.fs_redundant.append( self.fsc[i] )\n                    continue\n                ccidsr.append(i)\n        self.ccidsr = ccidsr\n        nc2 = len(ccidsr)\n        if nc2 < self.nc:\n            print('   %d out of %d conformers survived'%(nc2, self.nc))\n\n    def write_conformers(self):\n        \"\"\" write conformers to sdf files \"\"\"\n        #print self.ccidsr\n        #print self.fsc\n        for ic in self.ccidsr:\n            fo = self.fsc[ic][:-4] + '.sdf'\n            ci = self.cso[ic]\n            #zs = [ chemical_symbols[zi] for zi in mi.zs ]\n            #si = '%.4f #HF '%(self.ys[cid]*h2kc)\n            #write_xyz(fo, (zs, mi.coords), comments=si)\n            prop = self.ys[ic]\n            prop['smiles_indigo'] = ci.can\n            zs, coords, chgs, bom = ci.blk\n            write_ctab(zs, chgs, bom, coords, sdf=fo, prop=prop)\n\n\nif __name__ == \"__main__\":\n    \"\"\"\n    generate conformers for a input molecule\n\n    Attention: most frequently, the input are sdf files of AMONs !!!!!!!!!!\n    \"\"\"\n    import stropr as so\n\n    _args = sys.argv[1:]\n    if ('-h' in _args) or (len(_args) < 3):\n        print(\"Usage: \")\n        print(\"   geomprune [-r amons.can] [-thresh 0.01] [-M cml1] [folder]\")\n        sys.exit()\n\n    print(' \\n Now executing ')\n    print('         geomprune ' + ' '.join(sys.argv[1:]) + '\\n')\n\n    idx = 0\n    keys = ['-r','-ref']; hask,fsmi,idx = so.parser(_args,keys,'',idx,F)\n    assert hask, '#ERROR: a reference smi/can file must be provided'\n    assert fsmi[-3:] in ['smi','can'], '#ERROR: ref smiles file format not allowed'\n\n    keys = ['-fmt','-format']; ifmt,ffmt,idx = so.parser(_args,keys,'sdf',idx,F)\n    assert ifmt, '#ERROR: plz specify [-ffmt sdf/out]'\n\n    keys = ['-d','-digits']; has_sl,sl,idx = so.parser(_args,keys,'6',idx,F) # frag_000001.sdf ...\n\n    keys = ['-w','-write']; write,idx = so.haskey(_args,keys,idx) # rename & write unique conformers\n\n    thresh = 0.01\n    rep = 'cml1'\n\n    fd = _args[idx]\n    refs = [ si.strip() for si in file(fsmi).readlines() ]\n    ng = len(refs) # number of (unique molecular) graphs\n\n    if has_sl:\n        sfmt = '%%0%dd'%( int(sl) )\n    else:\n        sfmt = '%%0%dd'%( len(str(ng)) )\n\n    for _ in ['diss','redundant']:\n        if not os.path.exists(fd+'/'+_):\n            os.system('mkdir -p %s/%s'%(fd,_))\n\n    for mid in range(1,ng+1):\n        lb = sfmt%mid\n        fs = io2.cmdout('ls %s/frag_'%fd + lb + '_*%s'%ffmt)\n        print(' ** now processing mid %s'%lb)\n        obj = OptedMols(fs,refs[mid-1])\n        obj.prune_conformers(param={'M':rep,'wz':False,'thresh':thresh})\n        if write:\n            obj.write_conformers()\n        for f in obj.fs_diss:\n            os.system('mv %s.* %s/diss'%(f[:-4],fd))\n        for f in obj.fs_redundant:\n            cmd = 'mv %s.* %s/redundant'%(f[:-4],fd)\n            os.system(cmd)\n\n", "meta": {"hexsha": "92fe19eacbb75791860e6621268cc4ad6105e496", "size": 8606, "ext": "py", "lang": "Python", "max_stars_repo_path": "cheminfo/molecule/geomprune.py", "max_stars_repo_name": "binghuang2018/aqml", "max_stars_repo_head_hexsha": "4901f3bd85db968fb3fc7ab97fd443421909d89d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2020-02-17T11:15:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T18:03:15.000Z", "max_issues_repo_path": "cheminfo/molecule/geomprune.py", "max_issues_repo_name": "binghuang2018/aqml", "max_issues_repo_head_hexsha": "4901f3bd85db968fb3fc7ab97fd443421909d89d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-11T06:49:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-21T07:30:53.000Z", "max_forks_repo_path": "cheminfo/molecule/geomprune.py", "max_forks_repo_name": "binghuang2018/aqml", "max_forks_repo_head_hexsha": "4901f3bd85db968fb3fc7ab97fd443421909d89d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-09T01:37:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-19T13:13:34.000Z", "avg_line_length": 32.9731800766, "max_line_length": 100, "alphanum_fraction": 0.5094120381, "include": true, "reason": "import numpy,import scipy", "num_tokens": 2468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.1887575721638519}}
{"text": "\"\"\"\n#;+\n#; NAME:\n#; utils\n#;    Version 1.0\n#;\n#; PURPOSE:\n#;    Module for spectral utilities\n#;       Primarily overloads of Spectrum1D\n#;   07-Sep-2014 by JXP\n#;-\n#;------------------------------------------------------------------------------\n\"\"\"\nfrom __future__ import print_function, absolute_import, division, unicode_literals\n\nimport numpy as np\nimport os\nimport astropy as apy\n\nfrom astropy import units as u\nfrom astropy import constants as const\nfrom astropy.io import fits\n\nfrom specutils import Spectrum1D\nfrom specutils.wcs import BaseSpectrum1DWCS, Spectrum1DLookupWCS\nfrom specutils.wcs.specwcs import Spectrum1DPolynomialWCS\n\nfrom xastropy.xutils import xdebug as xdb\n\n# Child Class of specutils/Spectrum1D\n#    Generated by JXP to add functionality before it gets ingested in the specutils distribution\nclass XSpectrum1D(Spectrum1D):\n\n    #### ###############################\n    #  Instantiate from Spectrum1D [best to avoid!]\n    @classmethod\n    def from_spec1d(cls, spec1d):\n\n        # Giddy up\n        return cls(flux=spec1d.flux, wcs=spec1d.wcs, unit=spec1d.unit,\n                   uncertainty=spec1d.uncertainty, mask=spec1d.mask, meta=spec1d.meta)\n\n    #### ###############################\n    #  Normalize\n    def normalize(self, conti, verbose=False, no_check=False):\n        \"\"\"\n        Normalize the spectrum with an input continuum\n\n        Parameters\n        ----------\n        conti: numpy array\n          Continuum\n        verbose: bool (False)\n        no_check: bool (False)\n          Check size of array?\n        \"\"\"\n        # Sanity check\n        if (len(conti) != len(self.flux)): \n            if no_check:\n                print('WARNING: Continuum length differs from flux')\n                if len(conti) > len(self.flux):\n                    self.flux = self.flux / conti[0:len(self.flux)]\n                    return\n                else:\n                    raise ValueError('normalize: Continuum needs to be longer!')\n            else:\n                raise ValueError('normalize: Continuum needs to be same length as flux array')\n\n        # Adjust the flux\n        self.flux = self.flux / conti\n        if verbose:\n            print('spec.utils: Normalizing the spectrum')\n\n\n    #### ###############################\n    #  Grabs spectrum pixels in a velocity window\n    def pix_minmax(self, *args):\n        \"\"\"Pixels in velocity range\n\n        Parameters\n        ----------\n        Option 1: wvmnx\n          wvmnx: Tuple of 2 floats\n            wvmin, wvmax in spectral units\n\n        Option 2: zabs, wrest, vmnx  [not as a tuple or list!]\n          zabs: Absorption redshift\n          wrest: Rest wavelength  (with Units!)\n          vmnx: Tuple of 2 floats\n            vmin, vmax in km/s\n\n        Returns:\n        pix: array\n          Integer list of pixels\n        \"\"\"\n        if len(args) == 1: # Option 1\n            wvmnx = args[0]\n        elif len(args) == 3: # Option 2\n            from astropy import constants as const\n            # args = zabs, wrest, vmnx\n            wvmnx = (args[0]+1) * (args[1] + (args[1] * args[2] / const.c.to('km/s')) )\n            wvmnx.to(u.AA)\n\n        # Locate the values\n        pixmin = np.argmin( np.fabs( self.dispersion-wvmnx[0] ) )\n        pixmax = np.argmin( np.fabs( self.dispersion-wvmnx[1] ) )\n\n        gdpix = np.arange(pixmin,pixmax+1)\n\n        # Fill + Return\n        self.sub_pix = gdpix\n        return gdpix, wvmnx, (pixmin, pixmax)\n\n    #### ###############################\n    #  Box car smooth\n    def box_smooth(self, nbox, preserve=False):\n        \"\"\" Box car smooth spectrum and return a new one\n        Is a simple wrapper to the rebin routine\n\n        Parameters\n        ----------\n        nbox: integer\n          Number of pixels to smooth over\n        preserve: bool (False) \n          Keep the new spectrum at the same number of pixels as original\n        Returns:\n          XSpectrum1D of the smoothed spectrum\n        \"\"\"\n        from xastropy.xutils import arrays as xxa\n        if preserve:\n            from astropy.convolution import convolve, Box1DKernel\n            new_fx = convolve(self.flux, Box1DKernel(nbox))\n            new_sig = convolve(self.sig, Box1DKernel(nbox))\n            new_wv = self.dispersion\n        else:\n            # Truncate arrays as need be\n            npix = len(self.flux)\n            try:\n                new_npix = npix // nbox # New division\n            except ZeroDivisionError:\n                xdb.set_trace()\n            orig_pix = np.arange( new_npix * nbox )\n\n            # Rebin (mean)\n            new_wv = xxa.scipy_rebin( self.dispersion[orig_pix], new_npix )\n            new_fx = xxa.scipy_rebin( self.flux[orig_pix], new_npix )\n            new_sig = xxa.scipy_rebin( self.sig[orig_pix], new_npix ) / np.sqrt(nbox)\n\n        # Return\n        return XSpectrum1D.from_array(new_wv, new_fx,\n                                      uncertainty=apy.nddata.StdDevUncertainty(new_sig))\n\n    #### ###############################\n    #  Rebin\n    def rebin(self, new_wv):\n        \"\"\" Rebin the existing spectrum to a new wavelength array\n        Uses simple linear interpolation.  The default (and only) option \n        conserves counts (and flambda).\n        \n        WARNING: Do not trust either edge pixel of the new array\n\n        Parameters\n        ----------\n        new_wv: Quantity array\n          New wavelength array\n\n        Returns:\n        ----------\n          XSpectrum1D of the rebinned spectrum\n        \"\"\"\n        from scipy.interpolate import interp1d\n\n        # Endpoints of original pixels\n        npix = len(self.dispersion)\n        wvh = (self.dispersion + np.roll(self.dispersion, -1))/2.\n        wvh[npix-1] = self.dispersion[npix-1] + (self.dispersion[npix-1] - self.dispersion[npix-2])/2.\n        dwv = wvh - np.roll(wvh,1)\n        dwv[0] = 2*(wvh[0]-self.dispersion[0])\n\n        # Cumulative Sum\n        cumsum = np.cumsum(self.flux * dwv)\n\n        # Interpolate\n        fcum = interp1d(wvh, cumsum, fill_value=0., bounds_error=False)\n\n        # Endpoints of new pixels\n        nnew = len(new_wv)\n        nwvh = (new_wv + np.roll(new_wv, -1))/2.\n        nwvh[nnew-1] = new_wv[nnew-1] + (new_wv[nnew-1] - new_wv[nnew-2])/2.\n        # Pad starting point\n        bwv = np.zeros(nnew+1) * new_wv.unit\n        #xdb.set_trace()\n        bwv[0] = new_wv[0] - (new_wv[1] - new_wv[0])/2.\n        bwv[1:] = nwvh\n\n        # Evaluate\n        newcum = fcum(bwv)\n        # Endpoint\n        if (bwv[-1] > wvh[-1]):\n            newcum[-1] = cumsum[-1]\n\n        # Rebinned flux\n        new_fx = (np.roll(newcum,-1)-newcum)[:-1]\n\n        # Normalize (preserve counts and flambda)\n        new_dwv = bwv - np.roll(bwv,1)\n        new_fx = new_fx / new_dwv[1:]\n\n        # Return new spectrum\n        return XSpectrum1D.from_array(new_wv, new_fx)\n\n    # Quick plot\n    def plot(self):\n        ''' Plot the spectrum\n        Parameters\n        ----------\n        '''\n        if self.sig is not None:\n            xdb.xplot(self.dispersion, self.flux, self.sig)\n        else:\n            xdb.xplot(self.dispersion, self.flux)\n\n    # Velo array\n    def relative_vel(self, wv_obs):\n        ''' Return a velocity array relative to an input wavelength\n        Should consider adding a velocity array to this Class, \n        i.e. self.velo\n\n        Parameters\n        ----------\n        wv_obs : float\n          Wavelength to set the zero of the velocity array.\n          Often (1+z)*wrest\n\n        Returns:\n        ---------\n        velo: Quantity array (km/s)\n        '''\n        return  (self.dispersion-wv_obs) * const.c.to('km/s')/wv_obs\n\n    # Write to fits\n    def write_to_fits(self, outfil, clobber=True, add_wave=False):\n        ''' Write to a FITS file\n        Should generate a separate code to make a Binary FITS table format\n\n        Parameters\n        ----------\n        outfil: String\n          Name of the FITS file\n        clobber: bool (True)\n          Clobber existing file?\n        add_wave: bool (False)\n          Force writing of wavelength array\n        '''\n        # TODO\n        #  1. Add unit support for wavelength arrays\n\n        from specutils.io import write_fits as sui_wf\n        prihdu = sui_wf._make_hdu(self.data)  # Not for binary table format\n        prihdu.name = 'FLUX'\n        multi = 0 #  Multi-extension?\n\n        # Type\n        if type(self.wcs) is Spectrum1DPolynomialWCS:  # CRVAL1, etc. WCS\n            # WCS\n            wcs = self.wcs\n            wcs.write_fits_header(prihdu.header)\n            # Error array?\n            if self.sig is not None:\n                sighdu = fits.ImageHDU(self.sig)\n                sighdu.name='ERROR'\n                # \n                if add_wave:\n                    wvhdu = fits.ImageHDU(self.dispersion.value)\n                    wvhdu.name = 'WAVELENGTH'\n                    hdu = fits.HDUList([prihdu, sighdu, wvhdu])\n                else:\n                    hdu = fits.HDUList([prihdu, sighdu])\n                multi=1\n            else:\n                hdu = prihdu\n\n        elif type(self.wcs) is Spectrum1DLookupWCS: # Wavelengths as an array (without units for now)\n            # Add sig, wavelength to HDU\n            sighdu = fits.ImageHDU(self.sig)\n            sighdu.name='ERROR'\n            wvhdu = fits.ImageHDU(self.dispersion.value)\n            wvhdu.name = 'WAVELENGTH'\n            hdu = fits.HDUList([prihdu, sighdu, wvhdu])\n            multi=1\n        else:\n            raise ValueError('write_to_fits: Not ready for this type of spectrum wavelengths')\n\n        # Deal with header\n        if hasattr(self,'head'):\n            hdukeys = prihdu.header.keys()\n            # Append ones to avoid\n            hdukeys = hdukeys +ZZ ['BUNIT','COMMENT','', 'NAXIS2', 'HISTORY']\n            for key in self.head.keys():\n                # Use new ones\n                if key in hdukeys:\n                    continue\n                # Update unused ones\n                try:\n                    prihdu.header[key] = self.head[key]\n                except ValueError:\n                    xdb.set_trace()\n            # History\n            if 'HISTORY' in self.head.keys():\n                prihdu.header.add_history(str(self.head['HISTORY']))\n\n        # Write\n        hdu.writeto(outfil, clobber=clobber)\n        print('Wrote spectrum to {:s}'.format(outfil))\n\n\n# Quick plot\ndef bspline_stack(spectra):\n    ''' \"Stack\" a set of spectra with a bspline algorithm\n    Might be useful for coadding\n\n    Parameters:\n    -----------\n    spectra: List of Spectrum1D\n\n    Returns:\n    -------\n    bspline\n    '''\n\n# ################\nif __name__ == \"__main__\":\n\n    flg_test = 0\n    #flg_test += 2**0  # Test write (simple)\n    #flg_test += 2**1  # Test write with 3 arrays\n    #flg_test += 2**2  # Test boxcar\n    flg_test += 2**3  # Test rebin\n\n    from xastropy.spec import readwrite as xsr\n\n    if (flg_test % 2**1) >= 2**0:\n        # Standard log-linear read + write (MagE)\n        fil = '~/PROGETTI/LLSZ3/data/normalize/UM669_nF.fits'\n        myspec = xsr.readspec(fil)\n        # Write\n        myspec.write_to_fits('tmp.fits')\n\n    if (flg_test % 2**2) >= 2**1:\n        # Now 2D\n        fil = '/Users/xavier/Dropbox/QSOPairs/data/LRIS_redux/SDSSJ231254.65-025403.1_b400_F.fits.gz'\n        myspec = xsr.readspec(fil)\n        myspec.write_to_fits('tmp.fits')\n\n    if (flg_test % 2**3) >= 2**2: # Boxcar\n        fil = '~/PROGETTI/LLSZ3/data/normalize/UM669_nF.fits'\n        myspec = xsr.readspec(fil)\n        newspec = myspec.box_smooth(3)\n        # \n        newspec2 = myspec.box_smooth(3, preserve=True)\n        xdb.xplot(myspec.dispersion, myspec.flux, newspec2.flux)\n    \n    if (flg_test % 2**4) >= 2**3: # Rebin array\n        fil = '~/PROGETTI/LLSZ3/data/normalize/UM669_nF.fits'\n        myspec = xsr.readspec(fil)\n\n        new_wv = np.arange(3000., 9000., 5) * u.AA\n        newspec = myspec.rebin(new_wv)\n        #xdb.xplot(myspec.dispersion, myspec.flux,\n        #    xtwo=new_wv, ytwo=newspec.flux)\n        # Test EW\n        wvmnx = np.array((4859., 4961.))*u.AA\n        gd1 = np.where( (myspec.dispersion > wvmnx[0]) & \n            (myspec.dispersion < wvmnx[1]))[0]\n        dwv1 = myspec.dispersion - np.roll(myspec.dispersion,1)\n        EW1 = np.sum(dwv1[gd1]*(1.-myspec.flux[gd1].value))\n        gd2 = np.where( (newspec.dispersion > wvmnx[0]) & \n            (newspec.dispersion < wvmnx[1]))[0]\n        dwv2 = newspec.dispersion - np.roll(newspec.dispersion,1)\n        EW2 = np.sum(dwv2[gd2]*(1.-newspec.flux[gd2].value))\n        print('EW1={:g} and EW2={:g} for wvmnx={:g},{:g}'.format(\n            EW1,EW2,wvmnx[0],wvmnx[1]))\n        print('Percent diff = {:0.2f}%'.format(100*(EW2-EW1)/EW1))\n\n", "meta": {"hexsha": "a2cef8a9f1497739924ca0c080202a3b3e3281ff", "size": 12627, "ext": "py", "lang": "Python", "max_stars_repo_path": "xastropy/spec/utils.py", "max_stars_repo_name": "mneeleman/xastropy", "max_stars_repo_head_hexsha": "790aebfbc5cd26d43281bb70dec6bc63007dbb87", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "xastropy/spec/utils.py", "max_issues_repo_name": "mneeleman/xastropy", "max_issues_repo_head_hexsha": "790aebfbc5cd26d43281bb70dec6bc63007dbb87", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xastropy/spec/utils.py", "max_forks_repo_name": "mneeleman/xastropy", "max_forks_repo_head_hexsha": "790aebfbc5cd26d43281bb70dec6bc63007dbb87", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7974025974, "max_line_length": 102, "alphanum_fraction": 0.5474776273, "include": true, "reason": "import numpy,from scipy,import astropy,from astropy", "num_tokens": 3437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.18868945887817223}}
{"text": "# -*- coding: utf-8 -*-\n# Licensed under a 3-clause BSD style license - see LICNSE.rst\n\n# This module includes files automatically generated from ply (these end in\n# _lextab.py and _parsetab.py). To generate these files, remove them from this\n# folder, then build astropy and run the tests in-place:\n#\n#   python setup.py build_ext --inplace\n#   pytest astropy/units\n#\n# You can then commit the changes to the re-generated _lextab.py and\n# _parsetab.py files.\n\n\"\"\"\nHandles units in `Office of Guest Investigator Programs (OGIP)\nFITS files\n<https://heasarc.gsfc.nasa.gov/docs/heasarc/ofwg/docs/general/ogip_93_001/>`__.\n\"\"\"\n\nimport copy\nimport keyword\nimport math\nimport os\nimport warnings\nfrom fractions import Fraction\n\nfrom astropy.utils import parsing\n\nfrom . import core, generic, utils\n\n\nclass OGIP(generic.Generic):\n    \"\"\"\n    Support the units in `Office of Guest Investigator Programs (OGIP)\n    FITS files\n    <https://heasarc.gsfc.nasa.gov/docs/heasarc/ofwg/docs/general/ogip_93_001/>`__.\n    \"\"\"\n\n    _tokens = (\n        'DIVISION',\n        'OPEN_PAREN',\n        'CLOSE_PAREN',\n        'WHITESPACE',\n        'STARSTAR',\n        'STAR',\n        'SIGN',\n        'UFLOAT',\n        'LIT10',\n        'UINT',\n        'UNKNOWN',\n        'UNIT'\n    )\n\n    @staticmethod\n    def _generate_unit_names():\n\n        from astropy import units as u\n        names = {}\n        deprecated_names = set()\n\n        bases = [\n            'A', 'C', 'cd', 'eV', 'F', 'g', 'H', 'Hz', 'J',\n            'Jy', 'K', 'lm', 'lx', 'm', 'mol', 'N', 'ohm', 'Pa',\n            'pc', 'rad', 's', 'S', 'sr', 'T', 'V', 'W', 'Wb'\n        ]\n        deprecated_bases = []\n        prefixes = [\n            'y', 'z', 'a', 'f', 'p', 'n', 'u', 'm', 'c', 'd',\n            '', 'da', 'h', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'\n        ]\n\n        for base in bases + deprecated_bases:\n            for prefix in prefixes:\n                key = prefix + base\n                if keyword.iskeyword(key):\n                    continue\n                names[key] = getattr(u, key)\n        for base in deprecated_bases:\n            for prefix in prefixes:\n                deprecated_names.add(prefix + base)\n\n        simple_units = [\n            'angstrom', 'arcmin', 'arcsec', 'AU', 'barn', 'bin',\n            'byte', 'chan', 'count', 'day', 'deg', 'erg', 'G',\n            'h', 'lyr', 'mag', 'min', 'photon', 'pixel',\n            'voxel', 'yr'\n        ]\n        for unit in simple_units:\n            names[unit] = getattr(u, unit)\n\n        # Create a separate, disconnected unit for the special case of\n        # Crab and mCrab, since OGIP doesn't define their quantities.\n        Crab = u.def_unit(['Crab'], prefixes=False, doc='Crab (X-ray flux)')\n        mCrab = u.Unit(10 ** -3 * Crab)\n        names['Crab'] = Crab\n        names['mCrab'] = mCrab\n\n        deprecated_units = ['Crab', 'mCrab']\n        for unit in deprecated_units:\n            deprecated_names.add(unit)\n\n        # Define the function names, so we can parse them, even though\n        # we can't use any of them (other than sqrt) meaningfully for\n        # now.\n        functions = [\n            'log', 'ln', 'exp', 'sqrt', 'sin', 'cos', 'tan', 'asin',\n            'acos', 'atan', 'sinh', 'cosh', 'tanh'\n        ]\n        for name in functions:\n            names[name] = name\n\n        return names, deprecated_names, functions\n\n    @classmethod\n    def _make_lexer(cls):\n        tokens = cls._tokens\n\n        t_DIVISION = r'/'\n        t_OPEN_PAREN = r'\\('\n        t_CLOSE_PAREN = r'\\)'\n        t_WHITESPACE = '[ \\t]+'\n        t_STARSTAR = r'\\*\\*'\n        t_STAR = r'\\*'\n\n        # NOTE THE ORDERING OF THESE RULES IS IMPORTANT!!\n        # Regular expression rules for simple tokens\n        def t_UFLOAT(t):\n            r'(((\\d+\\.?\\d*)|(\\.\\d+))([eE][+-]?\\d+))|(((\\d+\\.\\d*)|(\\.\\d+))([eE][+-]?\\d+)?)'\n            t.value = float(t.value)\n            return t\n\n        def t_UINT(t):\n            r'\\d+'\n            t.value = int(t.value)\n            return t\n\n        def t_SIGN(t):\n            r'[+-](?=\\d)'\n            t.value = float(t.value + '1')\n            return t\n\n        def t_X(t):  # multiplication for factor in front of unit\n            r'[x×]'\n            return t\n\n        def t_LIT10(t):\n            r'10'\n            return 10\n\n        def t_UNKNOWN(t):\n            r'[Uu][Nn][Kk][Nn][Oo][Ww][Nn]'\n            return None\n\n        def t_UNIT(t):\n            r'[a-zA-Z][a-zA-Z_]*'\n            t.value = cls._get_unit(t)\n            return t\n\n        # Don't ignore whitespace\n        t_ignore = ''\n\n        # Error handling rule\n        def t_error(t):\n            raise ValueError(\n                f\"Invalid character at col {t.lexpos}\")\n\n        return parsing.lex(lextab='ogip_lextab', package='astropy/units')\n\n    @classmethod\n    def _make_parser(cls):\n        \"\"\"\n        The grammar here is based on the description in the\n        `Specification of Physical Units within OGIP FITS files\n        <https://heasarc.gsfc.nasa.gov/docs/heasarc/ofwg/docs/general/ogip_93_001/>`__,\n        which is not terribly precise.  The exact grammar is here is\n        based on the YACC grammar in the `unity library\n        <https://bitbucket.org/nxg/unity/>`_.\n        \"\"\"\n\n        tokens = cls._tokens\n\n        def p_main(p):\n            '''\n            main : UNKNOWN\n                 | complete_expression\n                 | scale_factor complete_expression\n                 | scale_factor WHITESPACE complete_expression\n            '''\n            if len(p) == 4:\n                p[0] = p[1] * p[3]\n            elif len(p) == 3:\n                p[0] = p[1] * p[2]\n            else:\n                p[0] = p[1]\n\n        def p_complete_expression(p):\n            '''\n            complete_expression : product_of_units\n            '''\n            p[0] = p[1]\n\n        def p_product_of_units(p):\n            '''\n            product_of_units : unit_expression\n                             | division unit_expression\n                             | product_of_units product unit_expression\n                             | product_of_units division unit_expression\n            '''\n            if len(p) == 4:\n                if p[2] == 'DIVISION':\n                    p[0] = p[1] / p[3]\n                else:\n                    p[0] = p[1] * p[3]\n            elif len(p) == 3:\n                p[0] = p[2] ** -1\n            else:\n                p[0] = p[1]\n\n        def p_unit_expression(p):\n            '''\n            unit_expression : unit\n                            | UNIT OPEN_PAREN complete_expression CLOSE_PAREN\n                            | OPEN_PAREN complete_expression CLOSE_PAREN\n                            | UNIT OPEN_PAREN complete_expression CLOSE_PAREN power numeric_power\n                            | OPEN_PAREN complete_expression CLOSE_PAREN power numeric_power\n            '''\n\n            # If we run p[1] in cls._functions, it will try and parse each\n            # item in the list into a unit, which is slow. Since we know that\n            # all the items in the list are strings, we can simply convert\n            # p[1] to a string instead.\n            p1_str = str(p[1])\n\n            if p1_str in cls._functions and p1_str != 'sqrt':\n                raise ValueError(\n                    \"The function '{}' is valid in OGIP, but not understood \"\n                    \"by astropy.units.\".format(\n                        p[1]))\n\n            if len(p) == 7:\n                if p1_str == 'sqrt':\n                    p[0] = p[1] * p[3] ** (0.5 * p[6])\n                else:\n                    p[0] = p[1] * p[3] ** p[6]\n            elif len(p) == 6:\n                p[0] = p[2] ** p[5]\n            elif len(p) == 5:\n                if p1_str == 'sqrt':\n                    p[0] = p[3] ** 0.5\n                else:\n                    p[0] = p[1] * p[3]\n            elif len(p) == 4:\n                p[0] = p[2]\n            else:\n                p[0] = p[1]\n\n        def p_scale_factor(p):\n            '''\n            scale_factor : LIT10 power numeric_power\n                         | LIT10\n                         | signed_float\n                         | signed_float power numeric_power\n                         | signed_int power numeric_power\n            '''\n            if len(p) == 4:\n                p[0] = 10 ** p[3]\n            else:\n                p[0] = p[1]\n            # Can't use np.log10 here, because p[0] may be a Python long.\n            if math.log10(p[0]) % 1.0 != 0.0:\n                from astropy.units.core import UnitsWarning\n                warnings.warn(\n                    \"'{}' scale should be a power of 10 in \"\n                    \"OGIP format\".format(p[0]), UnitsWarning)\n\n        def p_division(p):\n            '''\n            division : DIVISION\n                     | WHITESPACE DIVISION\n                     | WHITESPACE DIVISION WHITESPACE\n                     | DIVISION WHITESPACE\n            '''\n            p[0] = 'DIVISION'\n\n        def p_product(p):\n            '''\n            product : WHITESPACE\n                    | STAR\n                    | WHITESPACE STAR\n                    | WHITESPACE STAR WHITESPACE\n                    | STAR WHITESPACE\n            '''\n            p[0] = 'PRODUCT'\n\n        def p_power(p):\n            '''\n            power : STARSTAR\n            '''\n            p[0] = 'POWER'\n\n        def p_unit(p):\n            '''\n            unit : UNIT\n                 | UNIT power numeric_power\n            '''\n            if len(p) == 4:\n                p[0] = p[1] ** p[3]\n            else:\n                p[0] = p[1]\n\n        def p_numeric_power(p):\n            '''\n            numeric_power : UINT\n                          | signed_float\n                          | OPEN_PAREN signed_int CLOSE_PAREN\n                          | OPEN_PAREN signed_float CLOSE_PAREN\n                          | OPEN_PAREN signed_float division UINT CLOSE_PAREN\n            '''\n            if len(p) == 6:\n                p[0] = Fraction(int(p[2]), int(p[4]))\n            elif len(p) == 4:\n                p[0] = p[2]\n            else:\n                p[0] = p[1]\n\n        def p_sign(p):\n            '''\n            sign : SIGN\n                 |\n            '''\n            if len(p) == 2:\n                p[0] = p[1]\n            else:\n                p[0] = 1.0\n\n        def p_signed_int(p):\n            '''\n            signed_int : SIGN UINT\n            '''\n            p[0] = p[1] * p[2]\n\n        def p_signed_float(p):\n            '''\n            signed_float : sign UINT\n                         | sign UFLOAT\n            '''\n            p[0] = p[1] * p[2]\n\n        def p_error(p):\n            raise ValueError()\n\n        return parsing.yacc(tabmodule='ogip_parsetab', package='astropy/units')\n\n    @classmethod\n    def _validate_unit(cls, unit, detailed_exception=True):\n        if unit not in cls._units:\n            if detailed_exception:\n                raise ValueError(\n                    \"Unit '{}' not supported by the OGIP \"\n                    \"standard. {}\".format(\n                        unit, utils.did_you_mean_units(\n                            unit, cls._units, cls._deprecated_units,\n                            cls._to_decomposed_alternative)))\n            else:\n                raise ValueError()\n\n        if unit in cls._deprecated_units:\n            utils.unit_deprecation_warning(\n                unit, cls._units[unit], 'OGIP',\n                cls._to_decomposed_alternative)\n\n    @classmethod\n    def _parse_unit(cls, unit, detailed_exception=True):\n        cls._validate_unit(unit, detailed_exception=detailed_exception)\n        return cls._units[unit]\n\n    @classmethod\n    def parse(cls, s, debug=False):\n        s = s.strip()\n        try:\n            # This is a short circuit for the case where the string is\n            # just a single unit name\n            return cls._parse_unit(s, detailed_exception=False)\n        except ValueError:\n            try:\n                return core.Unit(\n                    cls._parser.parse(s, lexer=cls._lexer, debug=debug))\n            except ValueError as e:\n                if str(e):\n                    raise\n                else:\n                    raise ValueError(\n                        f\"Syntax error parsing unit '{s}'\")\n\n    @classmethod\n    def _get_unit_name(cls, unit):\n        name = unit.get_format_name('ogip')\n        cls._validate_unit(name)\n        return name\n\n    @classmethod\n    def _format_unit_list(cls, units):\n        out = []\n        units.sort(key=lambda x: cls._get_unit_name(x[0]).lower())\n\n        for base, power in units:\n            if power == 1:\n                out.append(cls._get_unit_name(base))\n            else:\n                power = utils.format_power(power)\n                if '/' in power:\n                    out.append(f'{cls._get_unit_name(base)}**({power})')\n                else:\n                    out.append(f'{cls._get_unit_name(base)}**{power}')\n        return ' '.join(out)\n\n    @classmethod\n    def to_string(cls, unit):\n        # Remove units that aren't known to the format\n        unit = utils.decompose_to_known_units(unit, cls._get_unit_name)\n\n        if isinstance(unit, core.CompositeUnit):\n            # Can't use np.log10 here, because p[0] may be a Python long.\n            if math.log10(unit.scale) % 1.0 != 0.0:\n                warnings.warn(\n                    f\"'{unit.scale}' scale should be a power of 10 in OGIP format\",\n                    core.UnitsWarning)\n\n        return generic._to_string(cls, unit)\n\n    @classmethod\n    def _to_decomposed_alternative(cls, unit):\n        # Remove units that aren't known to the format\n        unit = utils.decompose_to_known_units(unit, cls._get_unit_name)\n\n        if isinstance(unit, core.CompositeUnit):\n            # Can't use np.log10 here, because p[0] may be a Python long.\n            if math.log10(unit.scale) % 1.0 != 0.0:\n                scale = unit.scale\n                unit = copy.copy(unit)\n                unit._scale = 1.0\n                return '{} (with data multiplied by {})'.format(\n                    generic._to_string(cls, unit), scale)\n\n        return generic._to_string(unit)\n", "meta": {"hexsha": "0ee7be1f2c6e034f480955b0b1e2de3acd4b1b6d", "size": 14108, "ext": "py", "lang": "Python", "max_stars_repo_path": "astropy/units/format/ogip.py", "max_stars_repo_name": "zabop/astropy", "max_stars_repo_head_hexsha": "11b3214f18b74aea5e3f8349e50ae1b09c39d30e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-11T12:26:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-11T12:26:49.000Z", "max_issues_repo_path": "astropy/units/format/ogip.py", "max_issues_repo_name": "nabobalis/astropy", "max_issues_repo_head_hexsha": "9f77b9a0ffe18e4c767e36f00e2e8728135c0e11", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-10-09T18:54:27.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T18:54:27.000Z", "max_forks_repo_path": "astropy/units/format/ogip.py", "max_forks_repo_name": "nabobalis/astropy", "max_forks_repo_head_hexsha": "9f77b9a0ffe18e4c767e36f00e2e8728135c0e11", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6322869955, "max_line_length": 97, "alphanum_fraction": 0.4727814006, "include": true, "reason": "from astropy", "num_tokens": 3411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.18868945780177548}}
{"text": "\"\"\"\nExample models\n==============\n\nPlease note that none of the models are tuned much for performance, they are included for demonstration purposes only.\n\"\"\"\n\nfrom abc import ABC, abstractmethod\n\nimport numpy as np\n\n\n\nclass CompositeTrajectory(list):\n  \"\"\"\n  Class used by the EvolutionOperator implementation to store multiple individual\n  model trajectories. Derives from list and is meant to just be a collection of\n  trajectory instances.\n  \"\"\"\n  pass\n\n\n\nclass EvolutionOperator(ABC):\n  \"\"\"\n  Abstract base class for generic evolution operators.\n\n  This class represents evolution operators that only implement forward\n  propagation in time and do not support any form of linearization.\n  \"\"\"\n\n  @property\n  @abstractmethod\n  def ndim(self):\n    \"\"\"\n    The number of dimensions of the model state\n    \"\"\"\n    pass\n\n\n  @abstractmethod\n  def __call__(self, x, dt, trajectoryout=None):\n    \"\"\"\n    Propagates model from the current state to a new state at `t+dt`.\n\n    The current model state `x` is assumed to be at the time `t` and is\n    propagated to the time `t+dt`. The state is to be updated in-place, replacing\n    the contents of `x` with the updated state vector.\n    For linear operators or nonlinear operators that do not implement linearization, the\n    method will usually return ``None``. For linearized operators (see\n    :class:`LinearizedEvolutionOperator`), the method must return trajectory data for\n    the tangent linear and adjoint operators. The trajectory data is specific to the\n    operator implementation.\n\n    Args:\n      x  (NxM array) : One or more state vectors stored in columns. Outside of ensemble\n                       filtering methods, M is likely to be 1 (only a single state vector\n                       to be propagated).\n      dt (float)     : Propagation time step.\n\n    Returns:\n      Model trajectory at `t+dt` or ``None``.\n\n\n    Subclasses must implement this method at least for M = 1.\n    The default implementation handles the case of M > 1 by calling this method for each\n    column of `x` individually and can therefore be used form the subclass as a convenience.\n    The individual (sub)model trajectories are then joined together and returned as a\n    CompositeTrajectory instance.\n    \"\"\"\n\n    N, M = x.shape\n\n    # Fallback implementation of ensemble state propagation via simple loop.\n    # Subclasses may (should) do better than this\n    if M > 1:\n\n      T = CompositeTrajectory() if isinstance(self, LinearizedEvolutionOperator) else None\n      for m in range(M):\n        trj = self(x[:,m], dt)\n        if T: T.append(trj)\n\n      return T\n    else:\n      raise Exception(\"EvolutionOperator.__call__() not implemented for M=1\")\n\n\n\n\nclass LinearizedEvolutionOperator(EvolutionOperator):\n  \"\"\"\n  Abstract base class for evolution operators that implement both the tangent linear\n  and adjoint. The class is an extension of the EvolutionOperator abstract base.\n  \"\"\"\n\n  @abstractmethod\n  def dot(self, trajectory, x, out=None):\n    \"\"\"\n    Implements tangent-linear operator for the evolution model.\n\n    Args:\n      trajectory    : Trajectory at which the linearization occurs. This is the instance\n                      returned from :func:`da.EvolutionOperator.__call__()`.\n      x (NxM array) : Vector on which the tangent-linear operates.\n\n    Returns:\n      NxM array     : The product :math:`\\mathbf{A}x`, where :math:`\\mathbf{A}` is the tangent-linear operator.\n\n\n    Subclasses must implement this method at least for M=1 (M is the number of columns in `x`).\n    The default implementation handles the case of M > 1 by calling this method for each\n    column of `x` individually and can therefore be used form the subclass as a convenience.\n\n    \"\"\"\n\n    N, M = x.shape\n\n    if M > 1:\n      haveCompositeTrj = isinstance(trajectory, CompositeTrajectory)\n      if haveCompositeTrj: assert M == len(trajectory)\n\n      for m in range(M):\n        x[:,m] = self.dot(trajectory[m] if haveCompositeTrj else trajectory, x[:,m])\n\n      return x\n    else:\n      raise Exception(\"LinearizedEvolutionOperator.tl() not implemented\")\n\n\n\n  @abstractmethod\n  def adjdot(self, trajectory, x, out=None):\n    \"\"\"\n    Implements adjoint operator for the evolution model.\n\n    Args:\n      trajectory    : Trajectory at which the linearization occurs. This is the instance\n                      returned from :func:`da.EvolutionOperator.__call__()`.\n      x (NxM array) : Vector on which the adjoint operates.\n\n    Returns:\n      NxM array     : The product :math:`\\mathbf{A}^\\mathsf{T} x` where :math:`\\mathbf{A}^\\mathsf{T}` is the adjoint operator.\n\n    Subclasses must implement this method at least for M=1 (M is the number of columns in `x`).\n    The default implementation handles the case of M > 1 by calling this method for each\n    column of `x` individually and can therefore be used form the subclass as a convenience.\n    \"\"\"\n\n    N, M = x.shape\n\n    if M > 1:\n      haveCompositeTrj = isinstance(trajectory, CompositeTrajectory)\n      if haveCompositeTrj: assert M == len(trajectory)\n\n      for m in range(M):\n        x[:,m] = self.adjdot(trajectory[m] if haveCompositeTrj else trajectory, x[:,m])\n\n      return x\n    else:\n      raise Exception(\"LinearizedEvolutionOperator.ad() not implemented\")\n\n\n\n", "meta": {"hexsha": "fecaad8b18557680355f2dae93d277a5d7b9ca03", "size": 5259, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/models/__init__.py", "max_stars_repo_name": "martingu11/endas", "max_stars_repo_head_hexsha": "e58be74e844efa14cbd86aba5e76dbc44fe690de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-13T13:14:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-13T13:14:09.000Z", "max_issues_repo_path": "examples/models/__init__.py", "max_issues_repo_name": "martingu11/endas", "max_issues_repo_head_hexsha": "e58be74e844efa14cbd86aba5e76dbc44fe690de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2020-07-13T14:51:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-14T08:59:16.000Z", "max_forks_repo_path": "examples/models/__init__.py", "max_forks_repo_name": "martingu11/endas", "max_forks_repo_head_hexsha": "e58be74e844efa14cbd86aba5e76dbc44fe690de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-18T10:37:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T10:37:45.000Z", "avg_line_length": 32.0670731707, "max_line_length": 126, "alphanum_fraction": 0.688724092, "include": true, "reason": "import numpy", "num_tokens": 1213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.18868945404040488}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"Chemical Engineering Design Library (ChEDL). Utilities for process modeling.\nCopyright (C) 2016, 2017, 2018, 2019 Caleb Bell <Caleb.Andrew.Bell@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\nThis module contains various surface tension estimation routines, dataframes\nof fit coefficients, fitting model equations, mixing rules, and\nwater-hydrocarbon interfacial tension estimation routines.\n\nFor reporting bugs, adding feature requests, or submitting pull requests,\nplease use the `GitHub issue tracker <https://github.com/CalebBell/chemicals/>`_.\n\n.. contents:: :local:\n\nPure Component Correlations\n---------------------------\n.. autofunction:: chemicals.interface.Brock_Bird\n.. autofunction:: chemicals.interface.Pitzer_sigma\n.. autofunction:: chemicals.interface.Sastri_Rao\n.. autofunction:: chemicals.interface.Zuo_Stenby\n.. autofunction:: chemicals.interface.Hakim_Steinberg_Stiel\n.. autofunction:: chemicals.interface.Miqueu\n.. autofunction:: chemicals.interface.Aleem\n.. autofunction:: chemicals.interface.Mersmann_Kind_sigma\n\nMixing Rules\n------------\n.. autofunction:: chemicals.interface.Winterfeld_Scriven_Davis\n.. autofunction:: chemicals.interface.Weinaug_Katz\n.. autofunction:: chemicals.interface.Diguilio_Teja\n\nCorrelations for Specific Substances\n------------------------------------\n.. autofunction:: chemicals.interface.sigma_IAPWS\n\nPetroleum Correlations\n----------------------\n.. autofunction:: chemicals.interface.API10A32\n\nOil-Water Interfacial Tension Correlations\n------------------------------------------\n.. autofunction:: chemicals.interface.Meybodi_Daryasafar_Karimi\n\nFit Correlations\n----------------\n.. autofunction:: chemicals.interface.REFPROP_sigma\n.. autofunction:: chemicals.interface.Somayajulu\n.. autofunction:: chemicals.interface.Jasper\n.. autofunction:: chemicals.interface.PPDS14\n.. autofunction:: chemicals.interface.Watson_sigma\n.. autofunction:: chemicals.interface.ISTExpansion\n\nFit Coefficients\n----------------\nAll of these coefficients are lazy-loaded, so they must be accessed as an\nattribute of this module.\n\n.. data:: sigma_data_Mulero_Cachadina\n\n    Data from [5]_ with :obj:`REFPROP_sigma` coefficients.\n\n.. data:: sigma_data_Jasper_Lange\n\n    Data as shown in [4]_ but originally in [3]_ with :obj:`Jasper` coefficients.\n\n.. data:: sigma_data_Somayajulu\n\n    Data from [1]_ with :obj:`Somayajulu` coefficients.\n\n.. data:: sigma_data_Somayajulu2\n\n    Data from [2]_ with :obj:`Somayajulu` coefficients. These should be\n    preferred over the original coefficients.\n\n.. data:: sigma_data_VDI_PPDS_11\n\n    Data from [6]_ with :obj:`chemicals.dippr.EQ106` coefficients.\n\n.. [1] Somayajulu, G. R. \"A Generalized Equation for Surface Tension from\n   the Triple Point to the Critical Point.\" International Journal of\n   Thermophysics 9, no. 4 (July 1988): 559-66. doi:10.1007/BF00503154.\n.. [2] Mulero, A., M. I. Parra, and I. Cachadina. \"The Somayajulu\n   Correlation for the Surface Tension Revisited.\" Fluid Phase\n   Equilibria 339 (February 15, 2013): 81-88.\n   doi:10.1016/j.fluid.2012.11.038.\n.. [3] Jasper, Joseph J. \"The Surface Tension of Pure Liquid Compounds.\"\n   Journal of Physical and Chemical Reference Data 1, no. 4\n   (October 1, 1972): 841-1010. doi:10.1063/1.3253106.\n.. [4] Speight, James. Lange's Handbook of Chemistry. 16 edition.\n   McGraw-Hill Professional, 2005.\n.. [5] Mulero, A., I. Cachadiña, and M. I. Parra. “Recommended\n   Correlations for the Surface Tension of Common Fluids.” Journal of\n   Physical and Chemical Reference Data 41, no. 4 (December 1, 2012):\n   043105. doi:10.1063/1.4768782.\n.. [6] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.\n   Berlin; New York:: Springer, 2010.\n\nThe structure of each dataframe is shown below:\n\n\n.. ipython::\n\n    In [1]: import chemicals\n\n    In [2]: chemicals.interface.sigma_data_Mulero_Cachadina\n\n    In [3]: chemicals.interface.sigma_data_Jasper_Lange\n\n    In [4]: chemicals.interface.sigma_data_Somayajulu\n\n    In [5]: chemicals.interface.sigma_data_Somayajulu2\n\n    In [6]: chemicals.interface.sigma_data_VDI_PPDS_11\n\"\"\"\n\n\nfrom __future__ import division\n\n__all__ = ['REFPROP_sigma', 'Somayajulu', 'Jasper',\n           'Brock_Bird', 'Pitzer_sigma', 'Sastri_Rao', 'Zuo_Stenby',\n           'sigma_IAPWS', 'PPDS14', 'Watson_sigma',\n           'Mersmann_Kind_sigma', 'API10A32',\n           'Hakim_Steinberg_Stiel', 'Miqueu', 'Aleem',\n           'Winterfeld_Scriven_Davis', 'Diguilio_Teja', 'Weinaug_Katz',\n           'Meybodi_Daryasafar_Karimi', 'ISTExpansion']\n\nimport os\nfrom fluids.numerics import numpy as np\nfrom fluids.constants import N_A, k, root_two\nfrom chemicals.utils import log, exp, sqrt\nfrom chemicals.utils import mixing_simple, PY37, source_path, os_path_join, can_load_data, mark_numba_incompatible\nfrom chemicals.data_reader import register_df_source, data_source\n\nfolder = os_path_join(source_path, 'Interface')\n\n\nregister_df_source(folder, 'MuleroCachadinaParameters.tsv')\nregister_df_source(folder, 'Jasper-Lange.tsv')\nregister_df_source(folder, 'Somayajulu.tsv')\nregister_df_source(folder, 'SomayajuluRevised.tsv')\nregister_df_source(folder, 'VDI PPDS surface tensions.tsv')\n\n_interface_dfs_loaded = False\n@mark_numba_incompatible\ndef load_interface_dfs():\n    global _interface_dfs_loaded, sigma_data_Mulero_Cachadina, sigma_values_Mulero_Cachadina\n    global sigma_data_Jasper_Lange, sigma_values_Jasper_Lange\n    global sigma_data_Somayajulu, sigma_values_Somayajulu, sigma_data_Somayajulu2\n    global sigma_values_Somayajulu2, sigma_data_VDI_PPDS_11, sigma_values_VDI_PPDS_11\n\n    sigma_data_Mulero_Cachadina = data_source('MuleroCachadinaParameters.tsv')\n    sigma_values_Mulero_Cachadina = np.array(sigma_data_Mulero_Cachadina.values[:, 1:], dtype=float)\n\n    sigma_data_Jasper_Lange = data_source('Jasper-Lange.tsv')\n    sigma_values_Jasper_Lange = np.array(sigma_data_Jasper_Lange.values[:, 1:], dtype=float)\n\n    sigma_data_Somayajulu = data_source('Somayajulu.tsv')\n    sigma_values_Somayajulu = np.array(sigma_data_Somayajulu.values[:, 1:], dtype=float)\n\n    sigma_data_Somayajulu2 = data_source('SomayajuluRevised.tsv')\n    sigma_values_Somayajulu2 = np.array(sigma_data_Somayajulu2.values[:, 1:], dtype=float)\n\n    sigma_data_VDI_PPDS_11 = data_source('VDI PPDS surface tensions.tsv')\n    sigma_values_VDI_PPDS_11 = np.array(sigma_data_VDI_PPDS_11.values[:, 1:], dtype=float)\n\nif PY37:\n    def __getattr__(name):\n        if name in ('sigma_data_Mulero_Cachadina', 'sigma_values_Mulero_Cachadina',\n                    'sigma_data_Jasper_Lange', 'sigma_values_Jasper_Lange',\n                    'sigma_data_Somayajulu', 'sigma_values_Somayajulu', 'sigma_data_Somayajulu2',\n                    'sigma_values_Somayajulu2', 'sigma_data_VDI_PPDS_11', 'sigma_values_VDI_PPDS_11'\n                    ):\n            load_interface_dfs()\n            return globals()[name]\n        raise AttributeError(\"module %s has no attribute %s\" %(__name__, name))\nelse:\n    if can_load_data:\n        load_interface_dfs()\n\n\n\ndef sigma_IAPWS(T):\n    r'''Calculate the surface tension of pure water as a function of .\n    temperature. Assumes the 2011 IAPWS [1]_ formulation.\n\n    .. math::\n        \\sigma = B\\tau^\\mu(1+b\\tau)\\\\\n\n    .. math::\n        \\tau = 1-T/T_c\\\\\n\n    .. math::\n        B = 0.2358 \\text{N/m}\\\\\n\n    .. math::\n        b = -0.625\\\\\n\n    .. math::\n        \\mu = 1.256\n\n    Parameters\n    ----------\n    T : float\n        Temperature of liquid [K]\n\n    Returns\n    -------\n    sigma : float\n        Air-water surface tension, [N/m]\n\n    Notes\n    -----\n    This function is valid from the triple temperature to the critical\n    temperature. No effects for pressure are included in the formulation.\n    Test values are from IAPWS 2010 book.\n\n    Examples\n    --------\n    >>> sigma_IAPWS(300.)\n    0.0716859625271\n    >>> sigma_IAPWS(450.)\n    0.0428914991565\n    >>> sigma_IAPWS(600.)\n    0.0083756108728\n\n    References\n    ----------\n    .. [1] IAPWS. 2014. Revised Release on Surface Tension of Ordinary Water\n       Substance\n    '''\n    tau = 1. - T*(1.0/647.096)\n    return 0.2358*tau**1.256*(1.0 - 0.625*tau)\n\n### Regressed coefficient-based functions\n\ndef REFPROP_sigma(T, Tc, sigma0, n0, sigma1=0.0, n1=0.0, sigma2=0.0, n2=0.0):\n    r'''Calculates air-liquid surface tension  using the REFPROP_sigma [1]_\n    regression-based method. Relatively recent, and most accurate.\n\n    .. math::\n        \\sigma(T)=\\sigma_0\\left(1-\\frac{T}{T_c}\\right)^{n_0}+\n        \\sigma_1\\left(1-\\frac{T}{T_c}\\right)^{n_1}+\n        \\sigma_2\\left(1-\\frac{T}{T_c}\\right)^{n_2}\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    sigma0 : float\n        First emperical coefficient of a fluid\n    n0 : float\n        First emperical exponent of a fluid\n    sigma1 : float, optional\n        Second emperical coefficient of a fluid.\n    n1 : float, optional\n        Second emperical exponent of a fluid.\n    sigma1 : float, optional\n        Third emperical coefficient of a fluid.\n    n2 : float, optional\n        Third emperical exponent of a fluid.\n\n    Returns\n    -------\n    sigma : float\n        Liquid surface tension, [N/m]\n\n    Notes\n    -----\n    Function as implemented in [1]_. No example necessary; results match\n    literature values perfectly.\n    Form of function returns imaginary results when T > Tc; None is returned\n    if this is the case.\n\n\n    Examples\n    --------\n    Parameters for water at 298.15 K\n\n    >>> REFPROP_sigma(298.15, 647.096, -0.1306, 2.471, 0.2151, 1.233)\n    0.07205503890847453\n\n    References\n    ----------\n    .. [1] Diky, Vladimir, Robert D. Chirico, Chris D. Muzny, Andrei F.\n       Kazakov, Kenneth Kroenlein, Joseph W. Magee, Ilmutdin Abdulagatov, and\n       Michael Frenkel. \"ThermoData Engine (TDE): Software Implementation of\n       the Dynamic Data Evaluation Concept.\" Journal of Chemical Information\n       and Modeling 53, no. 12 (2013): 3418-30. doi:10.1021/ci4005699.\n    '''\n    Tr = T/Tc\n    one_minus_Tr = 1.0 - Tr\n    sigma = sigma0*(one_minus_Tr)**n0 + sigma1*(one_minus_Tr)**n1 + sigma2*(one_minus_Tr)**n2\n    return sigma\n\n\ndef PPDS14(T, Tc, a0, a1, a2):\n    r'''Calculates air-water surface tension  using the [1]_\n    emperical (parameter-regressed) method, called the PPDS 14 equation for\n    surface tension.\n    \n    .. math::\n        \\sigma = a_0 \\tau^{a_1}(1 + a_2 \\tau)\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    a0 : float\n        Regression parameter, [N/m]\n    a1 : float\n        Regression parameter, [-]\n    a2 : float\n        Regression parameter, [-]\n\n    Returns\n    -------\n    sigma : float\n        Liquid surface tension, [N/m]\n\n    Notes\n    -----\n\n    Examples\n    --------\n    Benzene at 280 K from [1]_\n\n    >>> PPDS14(T=280, Tc=562.05, a0=0.0786269, a1=1.28646, a2=-0.112304)\n    0.030559764256249854\n\n    References\n    ----------\n    .. [1] \"ThermoData Engine (TDE103b V10.1) User’s Guide.\" \n       https://trc.nist.gov/TDE/Help/TDE103b/Eqns-Pure-SurfaceTension/PPDS14.htm.\n    .. [2] Frenkel, Michael, Robert D. Chirico, Vladimir Diky, Xinjian Yan, \n       Qian Dong, and Chris Muzny. \"ThermoData Engine (TDE):  Software\n       Implementation of the Dynamic Data Evaluation Concept.\" Journal of \n       Chemical Information and Modeling 45, no. 4 (July 1, 2005): 816-38. \n       https://doi.org/10.1021/ci050067b.\n    '''\n    tau = 1.0 - T/Tc\n    return a0*tau**a1*(1.0 + a2*tau)\n\ndef Watson_sigma(T, Tc, a1, a2, a3=0.0, a4=0.0, a5=0.0):\n    r'''Calculates air-water surface tension using the Watson [1]_\n    emperical (parameter-regressed) method developed by NIST.\n    \n    .. math::\n        \\sigma = \\exp\\left[a_{1} + \\ln(1 - T_r)\\left(\n        a_2 + a_3T_r + a_4T_r^2 + a_5T_r^3 \\right)\\right]\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    a1 : float\n        Regression parameter, [-]\n    a2 : float\n        Regression parameter, [-]\n    a3 : float\n        Regression parameter, [-]\n    a4 : float\n        Regression parameter, [-]\n    a5 : float\n        Regression parameter, [-]\n\n    Returns\n    -------\n    sigma : float\n        Liquid surface tension, [N/m]\n\n    Notes\n    -----\n    This expression is also used for enthalpy of vaporization in [1]_.\n    The coefficients from NIST TDE for enthalpy of vaporization are kJ/mol.\n\n    Examples\n    --------\n    Isooctane at 350 K from [1]_:\n\n    >>> Watson_sigma(T=350.0, Tc=543.836, a1=-3.02417, a2=1.21792, a3=-5.26877e-9, a4=5.62659e-9, a5=-2.27553e-9)\n    0.0138340926605649\n\n    References\n    ----------\n    .. [1] \"ThermoData Engine (TDE103b V10.1) User’s Guide.\" \n       https://trc.nist.gov/TDE/Help/TDE103b/Eqns-Pure-SurfaceTension/HVPExpansion-SurfaceTension.htm\n    '''\n    Tr = T/Tc\n    l = log(1.0 - Tr)\n    return exp(a1 + l*(a2 + Tr*(a3 + Tr*(a4 + a5*Tr))))\n\ndef ISTExpansion(T, Tc, a1, a2, a3=0.0, a4=0.0, a5=0.0):\n    r'''Calculates air-water surface tension using the IST expansion [1]_\n    emperical (parameter-regressed) method developed by NIST.\n    \n    .. math::\n        \\sigma = \\sum_i a_i\\left(1 - \\frac{T}{T_c} \\right)^i\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    a1 : float\n        Regression parameter, [-]\n    a2 : float\n        Regression parameter, [-]\n    a3 : float\n        Regression parameter, [-]\n    a4 : float\n        Regression parameter, [-]\n    a5 : float\n        Regression parameter, [-]\n\n    Returns\n    -------\n    sigma : float\n        Liquid surface tension, [N/m]\n\n    Notes\n    -----\n\n    Examples\n    --------\n    Diethyl phthalate at 400 K from [1]_:\n\n    >>> ISTExpansion(T=400.0, Tc=776.0, a1=0.037545, a2=0.0363288)\n    0.02672100905515996\n\n    References\n    ----------\n    .. [1] \"ThermoData Engine (TDE103b V10.1) User’s Guide.\" \n       https://trc.nist.gov/TDE/Help/TDE103b/Eqns-Pure-SurfaceTension/ISTExpansion-SurfaceTension.htm\n    '''\n    tau = 1.0 - T/Tc\n    return tau*(a1 + tau*(a2 + tau*(a3 + tau*(a4 + a5*tau))))\n\ndef Somayajulu(T, Tc, A, B, C):\n    r'''Calculates air-water surface tension  using the [1]_\n    emperical (parameter-regressed) method. Well regressed, no recent data.\n\n    .. math::\n        \\sigma=aX^{5/4}+bX^{9/4}+cX^{13/4}\n\n    .. math::\n        X=(T_c-T)/T_c\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    A : float\n        Regression parameter\n    B : float\n        Regression parameter\n    C : float\n        Regression parameter\n\n    Returns\n    -------\n    sigma : float\n        Liquid surface tension, N/m\n\n    Notes\n    -----\n    Presently untested, but matches expected values. Internal units are mN/m.\n    Form of function returns imaginary results when T > Tc; None is returned\n    if this is the case. Function is claimed valid from the triple to the\n    critical point. Results can be evaluated beneath the triple point.\n\n    Examples\n    --------\n    Water at 300 K\n\n    >>> Somayajulu(300, 647.126, 232.713514, -140.18645, -4.890098)\n    0.07166386387996758\n\n    References\n    ----------\n    .. [1] Somayajulu, G. R. \"A Generalized Equation for Surface Tension from\n       the Triple Point to the Critical Point.\" International Journal of\n       Thermophysics 9, no. 4 (July 1988): 559-66. doi:10.1007/BF00503154.\n    '''\n    X = (Tc-T)/Tc\n    return X*sqrt(sqrt(X))*(A + X*(B + C*X))*1e-3\n\n\ndef Jasper(T, a, b):\n    r'''Calculates surface tension of a fluid given two parameters, a linear\n    fit in Celcius from [1]_ with data reprinted in [2]_.\n\n    .. math::\n        \\sigma = a - bT\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid, [K]\n    a : float\n        Parameter for equation. Chemical specific.\n    b : float\n        Parameter for equation. Chemical specific.\n\n    Returns\n    -------\n    sigma : float\n        Surface tension [N/m]\n\n    Notes\n    -----\n    Internal units are mN/m, and degrees Celcius.\n    This function has been checked against several references.\n\n    Examples\n    --------\n    >>> Jasper(298.15, 24, 0.0773)\n    0.0220675\n\n    References\n    ----------\n    .. [1] Jasper, Joseph J. \"The Surface Tension of Pure Liquid Compounds.\"\n       Journal of Physical and Chemical Reference Data 1, no. 4\n       (October 1, 1972): 841-1010. doi:10.1063/1.3253106.\n    .. [2] Speight, James. Lange's Handbook of Chemistry. 16 edition.\n       McGraw-Hill Professional, 2005.\n    '''\n    sigma = (a - b*(T-273.15))*1e-3\n    return sigma\n\n\n### CSP methods\n\n\ndef Brock_Bird(T, Tb, Tc, Pc):\n    r'''Calculates air-water surface tension  using the [1]_\n    emperical method. Old and tested.\n\n    .. math::\n        \\sigma = P_c^{2/3}T_c^{1/3}Q(1-T_r)^{11/9}\n\n    .. math::\n        Q = 0.1196 \\left[ 1 + \\frac{T_{br}\\ln (P_c/1.01325)}{1-T_{br}}\\right]-0.279\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tb : float\n        Boiling temperature of the fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    Pc : float\n        Critical pressure of fluid [Pa]\n\n    Returns\n    -------\n    sigma : float\n        Liquid surface tension, N/m\n\n    Notes\n    -----\n    Numerous arrangements of this equation are available.\n    This is DIPPR Procedure 7A: Method for the Surface Tension of Pure,\n    Nonpolar, Nonhydrocarbon Liquids\n    The exact equation is not in the original paper.\n    If the equation yields a negative result, return None.\n\n    Examples\n    --------\n    p-dichloribenzene at 412.15 K, from DIPPR; value differs due to a slight\n    difference in method.\n\n    >>> Brock_Bird(412.15, 447.3, 685, 3.952E6)\n    0.02208448325192495\n\n    Chlorobenzene from Poling, as compared with a % error value at 293 K.\n\n    >>> Brock_Bird(293.15, 404.75, 633.0, 4530000.0)\n    0.032985686413713036\n\n    References\n    ----------\n    .. [1] Brock, James R., and R. Byron Bird. \"Surface Tension and the\n       Principle of Corresponding States.\" AIChE Journal 1, no. 2\n       (June 1, 1955): 174-77. doi:10.1002/aic.690010208\n    '''\n    Tc_inv = 1.0/Tc\n    Tbr = Tb*Tc_inv\n    Tr = T*Tc_inv\n    Pc = Pc*1e-5  # Convert to bar\n    Q = 0.1196*(1.0 + Tbr*log(Pc*(1.0/1.01325))/(1.0 - Tbr)) - 0.279\n    sigma = (Pc)**(2.0/3.0)*Tc**(1.0/3.0)*Q*(1.0 - Tr)**(11.0/9.0)\n    sigma = sigma*1e-3  # convert to N/m\n    return sigma\n\n\ndef Pitzer_sigma(T, Tc, Pc, omega):\n    r'''Calculates air-water surface tension using the correlation derived\n    by [1]_ from the works of [2]_ and [3]_. Based on critical property CSP\n    methods.\n\n    .. math::\n        \\sigma = P_c^{2/3}T_c^{1/3}\\frac{1.86 + 1.18\\omega}{19.05}\n        \\left[ \\frac{3.75 + 0.91 \\omega}{0.291 - 0.08 \\omega}\\right]^{2/3} (1-T_r)^{11/9}\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    Pc : float\n        Critical pressure of fluid [Pa]\n    omega : float\n        Acentric factor for fluid, [-]\n\n    Returns\n    -------\n    sigma : float\n        Liquid surface tension, N/m\n\n    Notes\n    -----\n    The source of this equation has not been reviewed.\n    Internal units of presure are bar, surface tension of mN/m.\n\n    Examples\n    --------\n    Chlorobenzene from Poling, as compared with a % error value at 293 K.\n\n    >>> Pitzer_sigma(293., 633.0, 4530000.0, 0.249)\n    0.03458453513446388\n\n    References\n    ----------\n    .. [1] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n       New York: McGraw-Hill Professional, 2000.\n    .. [2] Curl, R. F., and Kenneth Pitzer. \"Volumetric and Thermodynamic\n       Properties of Fluids-Enthalpy, Free Energy, and Entropy.\" Industrial &\n       Engineering Chemistry 50, no. 2 (February 1, 1958): 265-74.\n       doi:10.1021/ie50578a047\n    .. [3] Pitzer, K. S.: Thermodynamics, 3d ed., New York, McGraw-Hill,\n       1995, p. 521.\n    '''\n    Tr = T/Tc\n    Pc = Pc*1e-5  # Convert to bar\n    sigma = Pc**(2.0/3.0)*Tc**(1.0/3.0)*(1.86 + 1.18*omega)*(1.0/19.05)*(\n        (3.75 + 0.91*omega)/(0.291 - 0.08*omega))**(2.0/3.0)*(1.0 - Tr)**(11.0/9.0)\n    return sigma*1e-3  # N/m, please\n\n\ndef Sastri_Rao(T, Tb, Tc, Pc, chemicaltype=None):\n    r'''Calculates air-water surface tension using the correlation derived by\n    [1]_ based on critical property CSP methods and chemical classes.\n\n    .. math::\n        \\sigma = K P_c^xT_b^y T_c^z\\left[\\frac{1-T_r}{1-T_{br}}\\right]^m\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tb : float\n        Boiling temperature of the fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    Pc : float\n        Critical pressure of fluid [Pa]\n\n    Returns\n    -------\n    sigma : float\n        Liquid surface tension, N/m\n\n    Notes\n    -----\n    The source of this equation has not been reviewed.\n    Internal units of presure are bar, surface tension of mN/m.\n\n    Examples\n    --------\n    Chlorobenzene from Poling, as compared with a % error value at 293 K.\n\n    >>> Sastri_Rao(293.15, 404.75, 633.0, 4530000.0)\n    0.03234567739694441\n\n    References\n    ----------\n    .. [1] Sastri, S. R. S., and K. K. Rao. \"A Simple Method to Predict\n       Surface Tension of Organic Liquids.\" The Chemical Engineering Journal\n       and the Biochemical Engineering Journal 59, no. 2 (October 1995): 181-86.\n       doi:10.1016/0923-0467(94)02946-6.\n    '''\n    if chemicaltype == 'alcohol':\n        k, x, y, z, m = 2.28, 0.25, 0.175, 0, 0.8\n    elif chemicaltype == 'acid':\n        k, x, y, z, m = 0.125, 0.50, -1.5, 1.85, 11.0/9.0\n    else:\n        k, x, y, z, m = 0.158, 0.50, -1.5, 1.85, 11.0/9.0\n    Tr = T/Tc\n    Tbr = Tb/Tc\n    Pc = Pc*1E-5  # Convert to bar\n    sigma = k*Pc**x*Tb**y*Tc**z*((1.0 - Tr)/(1.0 - Tbr))**m\n    sigma = sigma*1e-3  # N/m\n    return sigma\n\n\ndef Zuo_Stenby(T, Tc, Pc, omega):\n    r'''Calculates air-water surface tension using the reference fluids\n    methods of [1]_.\n\n    .. math::\n        \\sigma^{(1)} = 40.520(1-T_r)^{1.287}\n\n    .. math::\n        \\sigma^{(2)} = 52.095(1-T_r)^{1.21548}\n\n    .. math::\n        \\sigma_r = \\sigma_r^{(1)}+ \\frac{\\omega - \\omega^{(1)}}\n        {\\omega^{(2)}-\\omega^{(1)}} (\\sigma_r^{(2)}-\\sigma_r^{(1)})\n\n    .. math::\n        \\sigma = T_c^{1/3}P_c^{2/3}[\\exp{(\\sigma_r)} -1]\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    Pc : float\n        Critical pressure of fluid [Pa]\n    omega : float\n        Acentric factor for fluid, [-]\n\n    Returns\n    -------\n    sigma : float\n        Liquid surface tension, N/m\n\n    Notes\n    -----\n    Presently untested. Have not personally checked the sources.\n    I strongly believe it is broken.\n    The reference values for methane and n-octane are from the DIPPR database.\n\n    Examples\n    --------\n    Chlorobenzene\n\n    >>> Zuo_Stenby(293., 633.0, 4530000.0, 0.249)\n    0.03345569011871088\n\n    References\n    ----------\n    .. [1] Zuo, You-Xiang, and Erling H. Stenby. \"Corresponding-States and\n       Parachor Models for the Calculation of Interfacial Tensions.\" The\n       Canadian Journal of Chemical Engineering 75, no. 6 (December 1, 1997):\n       1130-37. doi:10.1002/cjce.5450750617\n    '''\n    Tc_1, Pc_1, omega_1 = 190.56, 4599000.0*1e-5, 0.012\n    Tc_2, Pc_2, omega_2 = 568.7, 2490000.0*1e-5, 0.4\n    Pc = Pc*1e-5\n    Tr = T/Tc\n\n    ST_1 = 40.520*(1.0 - Tr)**1.287  # Methane\n    ST_2 = 52.095*(1.0 - Tr)**1.21548  # n-octane\n\n    ST_r_1 = log(1.0 + 0.013537770442486932*ST_1) # Constant from 1/(Tc_1**(1.0/3.0)*Pc_1**(2.0/3.0))\n#    ST_r_1 = log(1.0 + ST_1/(Tc_1**(1.0/3.0)*Pc_1**(2.0/3.0)))\n    ST_r_2 = log(1.0 + 0.014154874587259097*ST_2) # Constant from /(Tc_2**(1.0/3.0)*Pc_2**(2.0/3.0))\n    sigma_r = ST_r_1 + (omega-omega_1)*(ST_r_2-ST_r_1)*2.5773195876288657\n#    sigma_r = ST_r_1 + (omega-omega_1)/(omega_2 - omega_1)*(ST_r_2-ST_r_1)\n    sigma = Tc**(1.0/3.0)*Pc**(2.0/3.0)*(exp(sigma_r) - 1.0)\n    sigma = sigma*1e-3  # N/m, please\n    return sigma\n\n\ndef Hakim_Steinberg_Stiel(T, Tc, Pc, omega, StielPolar=0.0):\n    r'''Calculates air-water surface tension using the reference fluids methods\n    of [1]_.\n\n    .. math::\n        \\sigma = 4.60104\\times 10^{-7} P_c^{2/3}T_c^{1/3}Q_p \\left(\\frac{1-T_r}{0.4}\\right)^m\n\n    .. math::\n        Q_p = 0.1574+0.359\\omega-1.769\\chi-13.69\\chi^2-0.51\\omega^2+1.298\\omega\\chi\n\n    .. math::\n        m = 1.21+0.5385\\omega-14.61\\chi-32.07\\chi^2-1.65\\omega^2+22.03\\omega\\chi\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    Pc : float\n        Critical pressure of fluid [Pa]\n    omega : float\n        Acentric factor for fluid, [-]\n    StielPolar : float, optional\n        Stiel Polar Factor, [-]\n\n    Returns\n    -------\n    sigma : float\n        Liquid surface tension, N/m\n\n    Notes\n    -----\n    Original equation for m and Q are used. Internal units are atm and mN/m.\n\n    Examples\n    --------\n    1-butanol, as compared to value in CRC Handbook of 0.02493.\n\n    >>> Hakim_Steinberg_Stiel(298.15, 563.0, 4414000.0, 0.59, StielPolar=-0.07872)\n    0.02190790257519\n\n    References\n    ----------\n    .. [1] Hakim, D. I., David Steinberg, and L. I. Stiel. \"Generalized\n       Relationship for the Surface Tension of Polar Fluids.\" Industrial &\n       Engineering Chemistry Fundamentals 10, no. 1 (February 1, 1971): 174-75.\n       doi:10.1021/i160037a032.\n    '''\n    omega2 = omega*omega\n    StielPolar2 = StielPolar*StielPolar\n    Q = (0.1574 + 0.359*omega - 1.769*StielPolar - 13.69*StielPolar2\n        - 0.510*omega2 + 1.298*StielPolar*omega)\n    m = (1.210 + 0.5385*omega - 14.61*StielPolar - 32.07*StielPolar2\n        - 1.656*omega2 + 22.03*StielPolar*omega)\n    Tr = T/Tc\n    Pc = Pc*(1.0/101325.0)\n    sigma = Pc**(2.0/3.)*Tc**(1.0/3.0)*Q*(2.5*(1.0 - Tr))**m\n    sigma = sigma*1e-3  # convert to N/m\n    return sigma\n\n\ndef Miqueu(T, Tc, Vc, omega):\n    r'''Calculates air-water surface tension using the methods of [1]_.\n\n    .. math::\n        \\sigma = k T_c \\left( \\frac{N_a}{V_c}\\right)^{2/3}\n        (4.35 + 4.14 \\omega)t^{1.26}(1+0.19t^{0.5} - 0.487t)\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    Tc : float\n        Critical temperature of fluid [K]\n    Vc : float\n        Critical volume of fluid [m^3/mol]\n    omega : float\n        Acentric factor for fluid, [-]\n\n    Returns\n    -------\n    sigma : float\n        Liquid surface tension, N/m\n\n    Notes\n    -----\n    Uses Avogadro's constant and the Boltsman constant.\n    Internal units of volume are mL/mol and mN/m. However, either a typo\n    is in the article or author's work, or my value of k is off by 10; this is\n    corrected nonetheless.\n    Created with 31 normal fluids, none polar or hydrogen bonded. Has an\n    AARD of 3.5%.\n\n    Examples\n    --------\n    Bromotrifluoromethane, 2.45 mN/m\n\n    >>> Miqueu(300., 340.1, 0.000199, 0.1687)\n    0.003474100774091376\n\n    References\n    ----------\n    .. [1] Miqueu, C, D Broseta, J Satherley, B Mendiboure, J Lachaise, and\n       A Graciaa. \"An Extended Scaled Equation for the Temperature Dependence\n       of the Surface Tension of Pure Compounds Inferred from an Analysis of\n       Experimental Data.\" Fluid Phase Equilibria 172, no. 2 (July 5, 2000):\n       169-82. doi:10.1016/S0378-3812(00)00384-8.\n    '''\n    Vc = Vc*1E6\n    t = 1. - T/Tc\n    sigma = k*Tc*(N_A/Vc)**(2.0/3.0)*(4.35 + 4.14*omega)*t**1.26*(1.0 + 0.19*sqrt(t) - 0.25*t)*10000.0\n    return sigma\n\n\ndef Aleem(T, MW, Tb, rhol, Hvap_Tb, Cpl):\n    r'''Calculates vapor-liquid surface tension using the correlation derived by\n    [1]_ based on critical property CSP methods.\n\n    .. math::\n        \\sigma = \\phi \\frac{MW^{1/3}} {6N_A^{1/3}}\\rho_l^{2/3}\\left[H_{vap}\n        + C_{p,l}(T_b-T)\\right]\n\n    .. math::\n        \\phi = 1 - 0.0047MW + 6.8\\times 10^{-6} MW^2\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    MW : float\n        Molecular weight [g/mol]\n    Tb : float\n        Boiling temperature of the fluid [K]\n    rhol : float\n        Liquid density at T and P [kg/m^3]\n    Hvap_Tb : float\n        Mass enthalpy of vaporization at the normal boiling point [kg/m^3]\n    Cpl : float\n        Liquid heat capacity of the chemical at T [J/kg/K]\n\n    Returns\n    -------\n    sigma : float\n        Liquid-vapor surface tension [N/m]\n\n    Notes\n    -----\n    Internal units of molecuar weight are kg/mol. This model is dimensionally\n    consistent.\n\n    This model does not use the critical temperature. After it predicts a\n    surface tension of 0 at a sufficiently high temperature, it returns\n    negative results. The temperature at which this occurs (the \"predicted\"\n    critical temperature) can be calculated as follows:\n\n    .. math::\n        \\sigma = 0 \\to T_{c,predicted} \\text{ at } T_b + \\frac{H_{vap}}{Cp_l}\n\n    Because of its dependence on density, it has the potential to model the\n    effect of pressure on surface tension.\n\n    Claims AAD of 4.3%. Developed for normal alkanes. Total of 472 data points.\n    Behaves worse for higher alkanes. Behaves very poorly overall.\n\n    Examples\n    --------\n    Methane at 90 K\n\n    >>> Aleem(T=90, MW=16.04246, Tb=111.6, rhol=458.7, Hvap_Tb=510870.,\n    ... Cpl=2465.)\n    0.01669970230131523\n\n    References\n    ----------\n    .. [1] Aleem, W., N. Mellon, S. Sufian, M. I. A. Mutalib, and D. Subbarao.\n       \"A Model for the Estimation of Surface Tension of Pure Hydrocarbon\n       Liquids.\" Petroleum Science and Technology 33, no. 23-24 (December 17,\n       2015): 1908-15. doi:10.1080/10916466.2015.1110593.\n    '''\n    MW = MW*1e-3 # Use kg/mol for consistency with the other units\n    sphericity = 1. - MW*(0.0047 - 6.8E-6*MW)\n    return sphericity*MW**(1.0/3.0)/(6.*N_A**(1.0/3.0))*rhol**(2.0/3.)*(Hvap_Tb + Cpl*(Tb-T))\n\n\ndef Mersmann_Kind_sigma(T, Tm, Tb, Tc, Pc, n_associated=1):\n    r'''Estimates the surface tension of organic liquid substances\n    according to the method of [1]_.\n\n    .. math::\n        \\sigma^* = \\frac{\\sigma n_{ass}^{1/3}} {(kT_c)^{1/3} T_{rm}P_c^{2/3}}\n\n    .. math::\n        \\sigma^* = \\left(\\frac{T_b - T_m}{T_m}\\right)^{1/3}\n        \\left[6.25(1-T_r) + 31.3(1-T_r)^{4/3}\\right]\n\n    Parameters\n    ----------\n    T : float\n        Temperature of the fluid [K]\n    Tm : float\n        Melting temperature [K]\n    Tb : float\n        Boiling temperature of the fluid [K]\n    Tc : float\n        Critical temperature of the fluid [K]\n    Pc : float\n        Critical pressure of the fluid [Pa]\n    n_associated : float\n        Number of associated molecules in a cluster (2 for alcohols, 1\n        otherwise), [-]\n\n    Returns\n    -------\n    sigma : float\n        Liquid-vapor surface tension [N/m]\n\n    Notes\n    -----\n    In the equation, all quantities must be in SI units. `k` is the boltzman\n    constant.\n\n    Examples\n    --------\n    MTBE at STP (the actual value is 0.0181):\n\n    >>> Mersmann_Kind_sigma(298.15, 164.15, 328.25, 497.1, 3430000.0)\n    0.016744311449290426\n\n    References\n    ----------\n    .. [1] Mersmann, Alfons, and Matthias Kind. \"Prediction of Mechanical and\n       Thermal Properties of Pure Liquids, of Critical Data, and of Vapor\n       Pressure.\" Industrial & Engineering Chemistry Research, January 31,\n       2017. https://doi.org/10.1021/acs.iecr.6b04323.\n    '''\n    Tr = T/Tc\n    sigma_star = ((Tb - Tm)/Tm)**(1.0/3.)*(6.25*(1. - Tr) + 31.3*(1. - Tr)**(4.0/3.))\n    sigma = sigma_star*(k*Tc)**(1.0/3.0)*(Tm/Tc)*Pc**(2.0/3.0)*n_associated**(-1.0/3.0)\n    return sigma\n\n\ndef API10A32(T, Tc, K_W):\n    r'''Calculates the interfacial tension between\n    a liquid petroleum fraction and air, using the oil's pseudocritical\n    temperature and Watson K Characterization factor.\n\n    .. math::\n        \\sigma = \\frac{673.7\\left[\\frac{\\left(T_c - T\\right)}{T_c}\\right]^{1.232}}{K_W}\n\n    Parameters\n    ----------\n    T : float\n        Liquid temperature, [K]\n    Tc : float\n        Pseudocritical temperature (or critical temperature if using\n        the equation with a pure component), [K]\n    K_W : float\n        Watson characterization factor\n\n    Returns\n    -------\n    sigma : float\n        Air-water surface tension, [N/m]\n\n    Notes\n    -----\n    [1]_ cautions that this should not be applied to coal liquids,\n    and that it will give higher errors at pressures above 500 psi.\n    [1]_ claims this has an average error of 10.7%.\n\n    This function converges to zero at `Tc`; do not use it above that\n    temperature!\n\n    Examples\n    --------\n    Sample problem in Comments on Procedure 10A3.2.1 of [1]_;\n\n    >>> from fluids.core import F2K, R2K\n    >>> API10A32(T=F2K(60), Tc=R2K(1334), K_W=12.4)\n    29.577333312096968\n\n    References\n    ----------\n    .. [1] API Technical Data Book: General Properties & Characterization.\n       American Petroleum Institute, 7E, 2005.\n    '''\n    return 673.7*((Tc-T)/Tc)**1.232/K_W\n\n### Surface Tension Mixtures\n\ndef Winterfeld_Scriven_Davis(xs, sigmas, rhoms):\n    r'''Calculates surface tension of a liquid mixture according to\n    mixing rules in [1]_ and also in [2]_.\n\n    .. math::\n        \\sigma_M = \\sum_i \\sum_j \\frac{1}{V_L^{L2}}\\left(x_i V_i \\right)\n        \\left( x_jV_j\\right)\\sqrt{\\sigma_i\\cdot \\sigma_j}\n\n    Parameters\n    ----------\n    xs : array-like\n        Mole fractions of all components, [-]\n    sigmas : array-like\n        Surface tensions of all components, [N/m]\n    rhoms : array-like\n        Molar densities of all components, [mol/m^3]\n\n    Returns\n    -------\n    sigma : float\n        Air-liquid surface tension of mixture, [N/m]\n\n    Notes\n    -----\n    DIPPR Procedure 7C: Method for the Surface Tension of Nonaqueous Liquid\n    Mixtures\n\n    Becomes less accurate as liquid-liquid critical solution temperature is\n    approached. DIPPR Evaluation:  3-4% AARD, from 107 nonaqueous binary\n    systems, 1284 points. Internally, densities are converted to kmol/m^3. The\n    Amgat function is used to obtain liquid mixture density in this equation.\n\n    Raises a ZeroDivisionError if either molar volume are zero, and a\n    ValueError if a surface tensions of a pure component is negative.\n\n    Examples\n    --------\n    >>> Winterfeld_Scriven_Davis([0.1606, 0.8394], [0.01547, 0.02877],\n    ... [8610., 15530.])\n    0.02496738845043982\n\n    References\n    ----------\n    .. [1] Winterfeld, P. H., L. E. Scriven, and H. T. Davis. \"An Approximate\n       Theory of Interfacial Tensions of Multicomponent Systems: Applications\n       to Binary Liquid-Vapor Tensions.\" AIChE Journal 24, no. 6\n       (November 1, 1978): 1010-14. doi:10.1002/aic.690240610.\n    .. [2] Danner, Ronald P, and Design Institute for Physical Property Data.\n       Manual for Predicting Chemical Process Design Data. New York, N.Y, 1982.\n    '''\n    N = len(xs)\n    Vms = [0.0]*N\n    rho = 0.0\n    for i in range(N):\n        Vms[i] = 1e3/rhoms[i]\n        rho += xs[i]*Vms[i]\n#    rho = 1./rho\n    rho = root_two/rho # factor out rt2\n    # For speed, transform the Vms array to contain\n#    xs[i]*Vms[i]*sigmas_05[i]*rho\n    tot = 0.0\n    for i in range(N):\n        val = sqrt(sigmas[i])*xs[i]*rho*Vms[i]\n        Vms[i] = val\n        tot += val*val\n    tot *= 0.5\n    for i in range(N):\n        # Symmetric - can be slightly optimized\n        temp = 0.0\n        for j in range(i):\n            temp += Vms[j]\n        tot += Vms[i]*temp\n\n    return tot\n\n\ndef Diguilio_Teja(T, xs, sigmas_Tb, Tbs, Tcs):\n    r'''Calculates surface tension of a liquid mixture according to\n    mixing rules in [1]_.\n\n    .. math::\n        \\sigma = 1.002855(T^*)^{1.118091} \\frac{T}{T_b} \\sigma_r\n\n    .. math::\n        T^* = \\frac{(T_c/T)-1}{(T_c/T_b)-1}\n\n    .. math::\n        \\sigma_r = \\sum x_i \\sigma_i\n\n    .. math::\n        T_b = \\sum x_i T_{b,i}\n\n    .. math::\n        T_c = \\sum x_i T_{c,i}\n\n    Parameters\n    ----------\n    T : float\n        Temperature of fluid [K]\n    xs : array-like\n        Mole fractions of all components\n    sigmas_Tb : array-like\n        Surface tensions of all components at the boiling point, [N/m]\n    Tbs : array-like\n        Boiling temperatures of all components, [K]\n    Tcs : array-like\n        Critical temperatures of all components, [K]\n\n    Returns\n    -------\n    sigma : float\n        Air-liquid surface tension of mixture, [N/m]\n\n    Notes\n    -----\n    Simple model, however it has 0 citations. Gives similar results to the\n    `Winterfeld_Scriven_Davis` model.\n\n    Raises a ValueError if temperature is greater than the mixture's critical\n    temperature or if the given temperature is negative, or if the mixture's\n    boiling temperature is higher than its critical temperature.\n\n    [1]_ claims a 4.63 percent average absolute error on 21 binary and 4\n    ternary non-aqueous systems. [1]_ also considered Van der Waals mixing\n    rules for `Tc`, but found it provided a higher error of 5.58%\n\n    Examples\n    --------\n    >>> Diguilio_Teja(T=298.15, xs=[0.1606, 0.8394],\n    ... sigmas_Tb=[0.01424, 0.02530], Tbs=[309.21, 312.95], Tcs=[469.7, 508.0])\n    0.025716823875045505\n\n    References\n    ----------\n    .. [1] Diguilio, Ralph, and Amyn S. Teja. \"Correlation and Prediction of\n       the Surface Tensions of Mixtures.\" The Chemical Engineering Journal 38,\n       no. 3 (July 1988): 205-8. doi:10.1016/0300-9467(88)80079-0.\n    '''\n    Tc, Tb, sigmar = 0.0, 0.0, 0.0\n    for i in range(len(xs)):\n        Tc += Tcs[i]*xs[i]\n        Tb += Tbs[i]*xs[i]\n        sigmar += sigmas_Tb[i]*xs[i]\n    if T > Tc:\n        raise ValueError('T > Tc according to Kays rule - model is not valid in this range.')\n    Tst = (Tc/T - 1.)/(Tc/Tb - 1.0)\n    return 1.002855*Tst**1.118091*(T/Tb)*sigmar\n\n\ndef Weinaug_Katz(parachors, Vml, Vmg, xs, ys):\n    r'''Calculates surface tension of a liquid mixture according to\n    mixing rules in [1]_ and also in [2]_. This is based on the\n    Parachor concept. This is called the Macleod-Sugden model in some places.\n\n    .. math::\n        \\sigma_M = \\left[\\sum_i P_i\\left( \\frac{x_i}{V_{m,l}}\n         - \\frac{y_i}{V_{m,g}}\\right) \\right]^4\n\n    Parameters\n    ----------\n    parachors : list[float]\n        Parachors of each component, [N^0.25*m^2.75/mol]\n    Vml : float\n        Liquid mixture molar volume, [m^3/mol]\n    Vmg : float\n        Gas mixture molar volume; this can be set to zero at\n        low pressures, [m^3/mol]\n    xs : list[float]\n        Mole fractions of all components in liquid phase, [-]\n    xs : list[float]\n        Mole fractions of all components in gas phase, [-]\n\n    Returns\n    -------\n    sigma : float\n        Air-liquid surface tension of mixture, [N/m]\n\n    Notes\n    -----\n    This expression is efficient and does not require pure component\n    surface tensions. Its accuracy is dubious.\n\n    Examples\n    --------\n    >>> Weinaug_Katz([5.1e-5, 7.2e-5], Vml=0.000125, Vmg=0.02011, xs=[.4, .6], ys=[.6, .4])\n    0.06547479150776776\n\n    Neglect the vapor phase density by setting `Vmg` to a high value:\n\n    >>> Weinaug_Katz([5.1e-5, 7.2e-5], Vml=0.000125, Vmg=1e100, xs=[.4, .6], ys=[.6, .4])\n    0.06701752894095361\n\n    References\n    ----------\n    .. [1] Weinaug, Charles F., and Donald L. Katz. \"Surface Tensions of\n       Methane-Propane Mixtures.\" Industrial & Engineering Chemistry 35,\n       no. 2 (February 1, 1943): 239-246. https://doi.org/10.1021/ie50398a028.\n    .. [2] Pedersen, Karen Schou, Aage Fredenslund, and Per Thomassen.\n       Properties of Oils and Natural Gases. Vol. 5. Gulf Pub Co, 1989.\n    '''\n    tot = 0.0\n    rhoml = 1.0/Vml\n    rhomg = 1.0/Vmg\n    for i in range(len(parachors)):\n        tot += parachors[i]*(xs[i]*rhoml - ys[i]*rhomg)\n    tot *= tot\n    tot *= tot # fourth power it\n    return tot\n\n### Water-hydrocarbon interfacial tensions\n\n\ndef Meybodi_Daryasafar_Karimi(rho_water, rho_oil, T, Tc):\n    r'''Calculates the interfacial tension between water and a hydrocabon\n    liquid according to the correlation of [1]_.\n\n    .. math::\n        \\gamma_{hw} = \\left(\\frac{A_1 + A_2 \\Delta \\rho + A_3\\Delta\\rho^2\n        + A_4\\Delta\\rho^3} {A_5 + A_6\\frac{T^{A_7}}{T_{c,h}} + A_8T^{A_9}}\n        \\right)^{A_{10}}\n\n    Parameters\n    ----------\n    rho_water : float\n        The density of the aqueous phase, [kg/m^3]\n    rho_oil : float\n        The density of the hydrocarbon phase, [kg/m^3]\n    T : float\n        Temperature of the fluid, [K]\n    Tc : float\n        Critical temperature of the hydrocarbon mixture, [K]\n\n    Returns\n    -------\n    sigma : float\n        Hydrocarbon-water surface tension [N/m]\n\n    Notes\n    -----\n    Internal units of the equation are g/mL and mN/m.\n\n    Examples\n    --------\n    >>> Meybodi_Daryasafar_Karimi(980, 760, 580, 914)\n    0.02893598143089256\n\n    References\n    ----------\n    .. [1] Kalantari Meybodi, Mahdi, Amin Daryasafar, and Masoud Karimi.\n       \"Determination of Hydrocarbon-Water Interfacial Tension Using a New\n       Empirical Correlation.\"  Fluid Phase Equilibria 415 (May 15, 2016):\n       42-50. doi:10.1016/j.fluid.2016.01.037.\n    '''\n    A1 = -1.3687340042E-1\n    A2 = -3.0391828884E-1\n    A3 = 5.6225871072E-1\n    A4 = -3.3074367079E-1\n    A5 = -3.0050179309E0\n    A6 = 5.8914210205E-5\n    A7 = -4.1388901263E0\n    A8 = 3.0084299030E0\n    A9 = -3.8203072876E-3\n#    A10 = 3.5000000000E0\n    drho = abs(rho_water - rho_oil)*1e-3 # Correlation in units of g/mL\n    sigma = ((A1 + drho*(A2 + drho*(A3 + A4*drho)))\n             /(A5 + A6*T**A7/Tc + A8*T**A9))\n    return sigma*sigma*sigma*sqrt(sigma)*1e-3 # mN/m to N/m\n", "meta": {"hexsha": "67fb9b57a4b6c4cc5510ebaab566754178b1fea2", "size": 42539, "ext": "py", "lang": "Python", "max_stars_repo_path": "chemicals/interface.py", "max_stars_repo_name": "CalebBell/chemicals", "max_stars_repo_head_hexsha": "e3920ae917bf1944946aa95f5461a41bcdba6c63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2020-08-29T07:47:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:16:46.000Z", "max_issues_repo_path": "chemicals/interface.py", "max_issues_repo_name": "CalebBell/chemicals", "max_issues_repo_head_hexsha": "e3920ae917bf1944946aa95f5461a41bcdba6c63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2020-08-31T04:44:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T05:40:07.000Z", "max_forks_repo_path": "chemicals/interface.py", "max_forks_repo_name": "CalebBell/chemicals", "max_forks_repo_head_hexsha": "e3920ae917bf1944946aa95f5461a41bcdba6c63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2020-09-01T04:57:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:36:58.000Z", "avg_line_length": 31.2098312546, "max_line_length": 114, "alphanum_fraction": 0.624626813, "include": true, "reason": "import numpy", "num_tokens": 13469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.18868221808365662}}
{"text": "\"\"\"\nCalculations of overlap (similarity) between annotation sets.\n\"\"\"\nimport abc\nimport math\nimport time\nfrom collections import defaultdict\nfrom pathlib import Path\nfrom typing import Collection, Mapping, Optional, Sequence, Type, Union\n\nimport decorateme\nimport numpy as np\nfrom pocketutils.core.chars import Chars\nfrom pocketutils.core.enums import CleverEnum\nfrom pocketutils.core.exceptions import XValueError\nfrom pocketutils.tools.unit_tools import UnitTools\nfrom typeddfs.df_errors import HashFileMissingError\n\nfrom mandos.analysis import AnalysisUtils as Au\nfrom mandos.analysis.io_defns import SimilarityDfLongForm, SimilarityDfShortForm\nfrom mandos.model.hit_dfs import HitDf\nfrom mandos.model.hits import AbstractHit\nfrom mandos.model.utils import unlink\n\n# note that most of these math functions are much faster than their numpy counterparts\n# if we're not broadcasting, it's almost always better to use them\n# some are more accurate, too\n# e.g. we're using fsum rather than sum\nfrom mandos.model.utils.setup import logger\n\n\nclass _Inf:\n    def __init__(self, n: int):\n        self.n = n\n        self.used, self.t0, self.nonzeros = set(), time.monotonic(), 0\n\n    def is_used(self, c1: str, c2: str) -> bool:\n        return (c1, c2) in self.used or (c2, c1) in self.used\n\n    def got(self, c1: str, c2: str, z: float) -> None:\n        self.used.add((c1, c2))\n        self.nonzeros += int(c1 != c2 and not np.isnan(z) and 0 < z < 1)\n        if self.i % 1000 == 0:\n            self.log(\"info\")\n\n    @property\n    def i(self) -> int:\n        return len(self.used)\n\n    def log(self, level: str) -> None:\n        delta = UnitTools.delta_time_to_str(time.monotonic() - self.t0, space=Chars.narrownbsp)\n        logger.log(\n            level.upper(),\n            f\"Processed {self.i:,}/{self.n:,} pairs in {delta};\"\n            + f\" {self.nonzeros:,} ({self.nonzeros / self.i * 100:.1f}%) are nonzero\",\n        )\n\n    def __repr__(self):\n        return f\"{self.__class__.__name__}({self.i}/{self.n})\"\n\n    def __str__(self):\n        return repr(self)\n\n\n@decorateme.auto_repr_str()\nclass MatrixCalculator(metaclass=abc.ABCMeta):\n    def __init__(\n        self,\n        *,\n        min_compounds: int,\n        min_nonzero: int,\n        min_hits: int,\n        exclude: Optional[Collection[str]] = None,\n    ):\n        self.min_compounds = min_compounds\n        self.min_nonzero = min_nonzero\n        self.min_hits = min_hits\n        self.exclude = set() if exclude is None else exclude\n\n    def calc_all(self, hits: Path, to: Path, *, keep_temp: bool = False) -> SimilarityDfLongForm:\n        raise NotImplemented()\n\n\nclass JPrimeMatrixCalculator(MatrixCalculator):\n    def calc_all(self, path: Path, to: Path, *, keep_temp: bool = False) -> SimilarityDfLongForm:\n        hits = self._read_hits(path)\n        key_to_hit = Au.hit_multidict(hits, \"search_key\")\n        logger.notice(f\"Calculating J on {len(key_to_hit):,} keys from {len(hits):,} hits\")\n        good_keys = {}\n        for key, key_hits in key_to_hit.items():\n            key_hits: Sequence[AbstractHit] = key_hits\n            n_compounds_0 = len({k.origin_inchikey for k in key_hits})\n            part_path = self._part_path(to, key)\n            df = None\n            if part_path.exists():\n                df = self._read_part(key, part_path)\n            if df is None and n_compounds_0 >= self.min_compounds:\n                df = self._calc_partial(key, key_hits)\n                df.write_file(part_path, attrs=True, file_hash=True, mkdirs=True)\n                logger.debug(f\"Wrote results for {key} to {part_path}\")\n            if df is not None and self._should_include(df):\n                good_keys[key] = part_path\n            if df is not None:\n                del df\n        big_df = self._concat_parts(good_keys)\n        big_df.write_file(to, attrs=True, file_hash=True, mkdirs=True)\n        logger.notice(f\"Wrote {len(big_df):,} rows to {to}\")\n        attrs_path = to.parent / (to.name + \".attrs.json\")\n        logger.sucess(f\"Finished -- see {attrs_path} for statistics\")\n        if not keep_temp:\n            for k in good_keys:\n                unlink(self._part_path(to, k))\n\n    def _read_hits(self, path: Path) -> Sequence[AbstractHit]:\n        hits = HitDf.read_file(path)\n        keys = hits[\"search_key\"].unique()\n        bad_excludes = [e for e in self.exclude if e not in keys]\n        if len(bad_excludes) > 0:\n            logger.error(f\"Keys to exclude are not in the input file: {', '.join(bad_excludes)}\")\n        for key in keys:\n            if key not in self.exclude:\n                dfx = hits[hits[\"search_key\"] == key]\n                negatives = dfx[dfx[\"weight\"] <= 0]\n                if len(negatives) > 0:\n                    logger.error(f\"{len(negatives)} / {len(dfx):,} hits for {key} are nonpositive\")\n        return [h for h in hits.to_hits() if h.search_key not in self.exclude and h.weight > 0]\n\n    def _calc_partial(self, key: str, key_hits: HitDf) -> SimilarityDfLongForm:\n        df = self.calc_one(key, key_hits).to_long_form(kind=\"psi\", key=key)\n        return df.set_attrs(\n            key=key,\n            quartiles=[float(df[\"value\"].quantile(x)) for x in [0, 0.25, 0.5, 0.75, 1]],\n            n_hits=len(key_hits),\n            n_values=len(df[\"value\"].unique()),\n            n_compounds=len(df[\"inchikey_1\"].unique()),\n            n_real=len(df[(df[\"value\"].notna()) & (df[\"value\"] > 0) & (df[\"value\"] < 1)]),\n        )\n\n    def _should_include(self, df: SimilarityDfLongForm) -> bool:\n        key = df.attrs[\"key\"]\n        reqs = dict(n_compounds=self.min_compounds, n_hits=self.min_hits, n_real=self.min_nonzero)\n        for a, mn in reqs.items():\n            v = df.attrs[a]\n            if v < mn:\n                logger.warning(f\"Key {key}: {a} = {v:,} < {mn:,}\")\n                return False\n        return True\n\n    def _read_part(self, key: str, part_path: Path) -> Optional[SimilarityDfLongForm]:\n        try:\n            df = SimilarityDfLongForm.read_file(part_path, file_hash=True, attrs=True)\n            logger.warning(f\"Results for key {key} already exist ({len(df):,} rows)\")\n            return df\n        except HashFileMissingError:\n            logger.error(f\"Extant results for key {key} appear incomplete; restarting\")\n            logger.opt(exception=True).debug(f\"Hash error for {key}\")\n            unlink(part_path)\n        return None  #  calculate from scratch\n\n    def _concat_parts(self, keys: Mapping[str, Path]):\n        logger.notice(f\"Included {len(keys):,} keys: {', '.join(keys)}\")\n        dfs = []\n        for key, pp in keys.items():\n            df = SimilarityDfLongForm.read_file(pp, attrs=True)\n            dfs.append(df)\n        return SimilarityDfLongForm.of(dfs, keys=keys)\n\n    def calc_one(self, key: str, hits: Sequence[AbstractHit]) -> SimilarityDfShortForm:\n        ik2hits = Au.hit_multidict(hits, \"origin_inchikey\")\n        logger.info(f\"Calculating J on {key} for {len(ik2hits):,} compounds and {len(hits):,} hits\")\n        data = defaultdict(dict)\n        inf = _Inf(n=int(len(ik2hits) * (len(ik2hits) - 1) / 2))\n        for (c1, hits1) in ik2hits.items():\n            for (c2, hits2) in ik2hits.items():\n                if inf.is_used(c1, c2):\n                    continue\n                z = 1 if c1 == c2 else self._j_prime(key, hits1, hits2)\n                data[c1][c2] = z\n                inf.got(c1, c2, z)\n        inf.log(\"success\")\n        return SimilarityDfShortForm.from_dict(data)\n\n    def _part_path(self, path: Path, key: str):\n        return path.parent / f\".{path.name}-{key}.tmp.feather\"\n\n    def _j_prime(\n        self, key: str, hits1: Collection[AbstractHit], hits2: Collection[AbstractHit]\n    ) -> float:\n        if len(hits1) == len(hits2) == 0:\n            return float(\"NaN\")  # TODO: Can this even happen?\n        if len(hits1) == 0 or len(hits2) == 0:\n            return 0\n        sources = {h.data_source for h in hits1}.intersection({h.data_source for h in hits2})\n        if len(sources) == 0:\n            return float(\"NaN\")\n        values = [\n            self._jx(\n                key,\n                [h for h in hits1 if h.data_source == source],\n                [h for h in hits2 if h.data_source == source],\n            )\n            for source in sources\n        ]\n        return float(math.fsum(values) / len(values))\n\n    def _jx(\n        self, key: str, hits1: Collection[AbstractHit], hits2: Collection[AbstractHit]\n    ) -> float:\n        if len(hits1) == len(hits2) == 0:\n            return float(\"NaN\")  # TODO: impossible, right?\n        if len(hits1) == 0 or len(hits2) == 0:\n            return 0\n        pair_to_weights = Au.weights_of_pairs(hits1, hits2)\n        values = []\n        for ca, cb in pair_to_weights.values():\n            wedge = self._wedge(ca, cb)\n            vee = self._vee(ca, cb)\n            if vee > 0:\n                values.append(wedge / vee)\n        return float(math.fsum(values) / len(values))\n\n    def _wedge(self, ca: float, cb: float) -> float:\n        return math.sqrt(Au.elle(ca) * Au.elle(cb))\n\n    def _vee(self, ca: float, cb: float) -> float:\n        return Au.elle(ca) + Au.elle(cb) - math.sqrt(Au.elle(ca) * Au.elle(cb))\n\n\nclass MatrixAlg(CleverEnum):\n    j = ()\n\n    @property\n    def clazz(self) -> Type[MatrixCalculator]:\n        return {MatrixAlg.j: JPrimeMatrixCalculator}[self]\n\n\n@decorateme.auto_utils()\nclass MatrixCalculation:\n    @classmethod\n    def create(\n        cls,\n        algorithm: Union[str, MatrixAlg],\n        *,\n        min_compounds: int,\n        min_nonzero: int,\n        min_hits: int,\n        exclude: Optional[Collection[str]] = None,\n    ) -> MatrixCalculator:\n        return MatrixAlg.of(algorithm).clazz(\n            min_compounds=min_compounds,\n            min_nonzero=min_nonzero,\n            min_hits=min_hits,\n            exclude=exclude,\n        )\n\n\n__all__ = [\"JPrimeMatrixCalculator\", \"MatrixAlg\", \"MatrixCalculation\", \"MatrixCalculator\"]\n", "meta": {"hexsha": "8d1520d18be88bb6376a9b8858cfbdad7b679726", "size": 9931, "ext": "py", "lang": "Python", "max_stars_repo_path": "mandos/analysis/distances.py", "max_stars_repo_name": "dmyersturnbull/chembler", "max_stars_repo_head_hexsha": "b1b54a5f4fe7939e012c0cc8b227fcea60d6e744", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mandos/analysis/distances.py", "max_issues_repo_name": "dmyersturnbull/chembler", "max_issues_repo_head_hexsha": "b1b54a5f4fe7939e012c0cc8b227fcea60d6e744", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mandos/analysis/distances.py", "max_forks_repo_name": "dmyersturnbull/chembler", "max_forks_repo_head_hexsha": "b1b54a5f4fe7939e012c0cc8b227fcea60d6e744", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.492248062, "max_line_length": 100, "alphanum_fraction": 0.5998388883, "include": true, "reason": "import numpy", "num_tokens": 2620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.1886822180836566}}
{"text": "# Copyright 2019 Huawei Technologies Co., Ltd\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\nimport numpy as np\r\nfrom akg.utils import kernel_exec as utils\r\nfrom test_op import resize_bilinear\r\nfrom tensorio import compare_tensor\r\nfrom gen_random import random_gaussian\r\n\r\ndef resize_bilinear_run(in_shape, out_shape, dtype, kernel_name, attrs):\r\n    kernel_name = utils.gen_name_kernel(kernel_name, dtype, in_shape)\r\n\r\n    if 'tuning' in attrs.keys():\r\n        t = attrs.get(\"tuning\", False)\r\n        kernel_name = attrs.get(\"kernel_name\", False)\r\n        mod = utils.op_build_test(resize_bilinear.resize_bilinear,\r\n                                  input_shapes=[in_shape], input_types=[dtype],\r\n                                  op_attrs=[out_shape], kernel_name=kernel_name, attrs=attrs, tuning=t)\r\n        if t:\r\n            expect, input, output = gen_data(dtype, in_shape, out_shape)\r\n            return mod, expect, (input, output)\r\n        else:\r\n            return mod\r\n    else:\r\n        # Create op\r\n        mod = utils.op_build_test(resize_bilinear.resize_bilinear,\r\n                                  input_shapes=[in_shape], input_types=[dtype],\r\n                                  op_attrs=[out_shape], kernel_name=kernel_name, attrs=attrs)\r\n\r\n        expect, input, output = gen_data(dtype, in_shape, out_shape)\r\n        output = utils.mod_launch(mod, (input, output), expect=expect)\r\n        return input, output, expect, compare_tensor(output, expect, atol=5e-01, rtol=5e-03, equal_nan=True)\r\n\r\n\r\ndef gen_data(dtype, in_shape, out_shape):\r\n    # Generate data for testing the op\r\n    input = random_gaussian(in_shape, miu=1, sigma=4).astype(dtype)\r\n    # Generate expected output using numpy implementation of resize bilinear\r\n    expect = bilinear_expect(input, out_shape)\r\n    # Predict output\r\n    output = np.full(expect.shape, np.nan, dtype)\r\n    return expect, input, output\r\n\r\n\r\ndef bilinear_expect(input_data, out_shape):\r\n    # Get N,W,H,C from input data\r\n    batch_size, in_height, in_width, channels = input_data.shape\r\n    out_height, out_width = out_shape[0], out_shape[1]\r\n    out_shape = [batch_size, out_height, out_width, channels]\r\n\r\n    # scale value is required to map from input space to output space\r\n    # align_corner version:\r\n    height_scale = (in_height - 1.0) / (out_height - 1.0)\r\n    width_scale = (in_width - 1.0) / (out_width - 1.0)\r\n\r\n    # compute_interpolation_weights calculates lower, upper and lerp for each index of ys and xs\r\n    def compute_interpolation_weights(index, scale):\r\n        temp = CachedInterpolation(0, 0, 0)\r\n        temp.lower = np.floor(index * scale).astype(\"int32\")\r\n        temp.upper = np.ceil(index * scale).astype(\"int32\")\r\n        temp.lerp = index * scale - temp.lower\r\n        return temp\r\n\r\n    # ys and xs will ensure which row(top,bottom) and column(left,right) index from input matrix will be responsible for the wighted calculation for each position of output matrix\r\n    # ys will provide row information and xs will provide column information for output matrix\r\n    # so ys size will be same as output height and xs size will be same as output width\r\n    # they will also contain interpolation weight(lerp)\r\n    ys = [compute_interpolation_weights(i, height_scale) for i in range(out_height)]\r\n    xs = [compute_interpolation_weights(i, width_scale) for i in range(out_width)]\r\n\r\n    return resize_image(input_data, out_shape, xs, ys)\r\n\r\n# each position of row and column index of output matrix will contain lower, upper and lerp\r\n\r\n\r\nclass CachedInterpolation:\r\n    def __init__(self, lower, upper, lerp):\r\n        self.lower = lower\r\n        self.upper = upper\r\n        self.lerp = lerp\r\n\r\n\r\ndef resize_image(input_data, out_shape, xs, ys):\r\n    def compute_lerp(top_left, top_right, bottom_left, bottom_right, x_lerp, y_lerp):\r\n        top = top_left + (top_right - top_left) * x_lerp\r\n        bottom = bottom_left + (bottom_right - bottom_left) * x_lerp\r\n        return top + (bottom - top) * y_lerp\r\n\r\n    output = np.zeros(out_shape).astype(input_data.dtype)\r\n    batch_size, out_height, out_width, channels = out_shape\r\n    for b in range(batch_size):\r\n        for y in range(out_height):\r\n            for x in range(out_width):\r\n                for c in range(channels):\r\n                    left_x_index = xs[x].lower\r\n                    right_x_index = xs[x].upper\r\n                    xs_lerp = xs[x].lerp\r\n\r\n                    top_y_index = ys[y].lower\r\n                    bottom_y_index = ys[y].upper\r\n                    ys_lerp = ys[y].lerp\r\n\r\n                    top_left = input_data[b][top_y_index][left_x_index][c]\r\n                    top_right = input_data[b][top_y_index][right_x_index][c]\r\n                    bottom_left = input_data[b][bottom_y_index][left_x_index][c]\r\n                    bottom_right = input_data[b][bottom_y_index][right_x_index][c]\r\n\r\n                    output[b][y][x][c] = compute_lerp(top_left, top_right, bottom_left, bottom_right, xs_lerp, ys_lerp)\r\n    return output\r\n", "meta": {"hexsha": "dc5f8f0a81bbfdd3a05b8cbbeaba3cbb960f5158", "size": 5527, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/common/test_run/resize_bilinear_run.py", "max_stars_repo_name": "laekov/akg", "max_stars_repo_head_hexsha": "5316b8cb2340bbf71bdc724dc9d81513a67b3104", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-31T02:43:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T02:43:43.000Z", "max_issues_repo_path": "tests/common/test_run/resize_bilinear_run.py", "max_issues_repo_name": "laekov/akg", "max_issues_repo_head_hexsha": "5316b8cb2340bbf71bdc724dc9d81513a67b3104", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/common/test_run/resize_bilinear_run.py", "max_forks_repo_name": "laekov/akg", "max_forks_repo_head_hexsha": "5316b8cb2340bbf71bdc724dc9d81513a67b3104", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.6776859504, "max_line_length": 180, "alphanum_fraction": 0.6560521078, "include": true, "reason": "import numpy", "num_tokens": 1281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.18857024863946328}}
{"text": "import os\nimport csv\nfrom scipy import integrate\nimport matplotlib.pyplot as plt\n\nDEPTHS = [-1.0 * i for i in [0, 6, 19.7, 28.9, 36.4, 43.88, 51.34, 58.81, 66.36, 73.94, 81.5, 88.97, 96.45, 103.93, 111.41,\n          118.92, 126.47, 134.01, 141.55, 149.09, 156.64, 164.18, 171.72, 179.27, 186.79, 194.27, 201.75,\n          209.23, 216.71, 224.09, 231.4, 238.7, 246.01, 253.31, 260.62, 267.9, 275.16, 282.42, 289.68,\n          296.94, 304.19, 311.41, 318.44, 325.47, 332.5, 339.53, 346.56, 353.59, 360.62, 367.66, 374.69,\n          381.72, 388.75, 395.78, 402.78, 409.72, 416.67, 423.61, 430.56, 437.5, 444.44, 451.32, 457.89,\n          464.47, 471.05, 477.63, 484.21, 490.79, 497.37, 503.75, 510, 516.25, 522.5, 528.75, 535, 541.25,\n          547.5, 553.95, 560.53, 567.11, 573.68]]\n\n\nclass Inspect:\n\n    def __init__(self, reg_path, depleted_path):\n        super().__init__()\n        self.reg_path = reg_path\n        self.depleted_path = depleted_path\n        self.adibekyan_bsp_1200 = None\n        self.adibekyan_bsp_1400 = None\n        self.adibekyan_bsp_1600 = None\n        self.adibekyan_depleted_bsp_f1200_1200 = None\n        self.adibekyan_depleted_bsp_f1400_1200 = None\n        self.adibekyan_depleted_bsp_f1400_1400 = None\n        self.adibekyan_depleted_bsp_f1600_1200 = None\n        self.adibekyan_depleted_bsp_f1600_1400 = None\n        self.adibekyan_depleted_bsp_f1600_1600 = None\n        self.adibekyan_morb_f1200_1200 = None\n        self.adibekyan_morb_f1400_1200 = None\n        self.adibekyan_morb_f1400_1400 = None\n        self.adibekyan_morb_f1600_1200 = None\n        self.adibekyan_morb_f1600_1400 = None\n        self.adibekyan_morb_f1600_1600 = None\n        self.kepler_bsp_1200 = None\n        self.kepler_bsp_1400 = None\n        self.kepler_bsp_1600 = None\n        self.kepler_depleted_bsp_f1200_1200 = None\n        self.kepler_depleted_bsp_f1400_1200 = None\n        self.kepler_depleted_bsp_f1400_1400 = None\n        self.kepler_depleted_bsp_f1600_1200 = None\n        self.kepler_depleted_bsp_f1600_1400 = None\n        self.kepler_depleted_bsp_f1600_1600 = None\n        self.kepler_morb_f1200_1200 = None\n        self.kepler_morb_f1400_1200 = None\n        self.kepler_morb_f1400_1400 = None\n        self.kepler_morb_f1600_1200 = None\n        self.kepler_morb_f1600_1400 = None\n        self.kepler_morb_f1600_1600 = None\n\n        self.__getfiles()\n\n    def __return_df(self, f):\n        return list(csv.reader(open(f, 'r'), delimiter=\",\"))\n\n    def __getfiles(self):\n        files = []\n        fnames = []\n        for dirname, dirnames, f in os.walk(self.reg_path):\n            for i in f:\n                files.append(dirname + \"/\" + i)\n                fnames.append(i)\n        for index, i in enumerate(fnames):\n            f = files[index]\n            if \"Adibekyan\" in i and \"BSP\" in i and \"1200\" in i:\n                self.adibekyan_bsp_1200 = self.__return_df(f=f)\n            elif \"Adibekyan\" in i and \"BSP\" in i and \"1400\" in i:\n                self.adibekyan_bsp_1400 = self.__return_df(f=f)\n            elif \"Adibekyan\" in i and \"BSP\" in i and \"1600\" in i:\n                self.adibekyan_bsp_1600 = self.__return_df(f=f)\n            elif \"Adibekyan\" in i and \"MORB\" in i and \"_F1200\" in i and \"_1200\" in i:\n                self.adibekyan_morb_f1200_1200 = self.__return_df(f=f)\n            elif \"Adibekyan\" in i and \"MORB\" in i and \"_F1400\" in i and \"_1200\" in i:\n                self.adibekyan_morb_f1400_1200 = self.__return_df(f=f)\n            elif \"Adibekyan\" in i and \"MORB\" in i and \"_F1400\" in i and \"_1400\" in i:\n                self.adibekyan_morb_f1400_1400 = self.__return_df(f=f)\n            elif \"Adibekyan\" in i and \"MORB\" in i and \"_F1600\" in i and \"_1200\" in i:\n                self.adibekyan_morb_f1600_1200 = self.__return_df(f=f)\n            elif \"Adibekyan\" in i and \"MORB\" in i and \"_F1600\" in i and \"_1400\" in i:\n                self.adibekyan_morb_f1600_1400 = self.__return_df(f=f)\n            elif \"Adibekyan\" in i and \"MORB\" in i and \"_F1600\" in i and \"_1600\" in i:\n                self.adibekyan_morb_f1600_1600 = self.__return_df(f=f)\n            elif \"Kepler\" in i and \"BSP\" in i and \"1200\" in i:\n                self.kepler_bsp_1200 = self.__return_df(f=f)\n            elif \"Kepler\" in i and \"BSP\" in i and \"1400\" in i:\n                self.kepler_bsp_1400 = self.__return_df(f=f)\n            elif \"Kepler\" in i and \"BSP\" in i and \"1600\" in i:\n                self.kepler_bsp_1600 = self.__return_df(f=f)\n            elif \"Kepler\" in i and \"MORB\" in i and \"_F1200\" in i and \"_1200\" in i:\n                self.kepler_morb_f1200_1200 = self.__return_df(f=f)\n            elif \"Kepler\" in i and \"MORB\" in i and \"_F1400\" in i and \"_1200\" in i:\n                self.kepler_morb_f1400_1200 = self.__return_df(f=f)\n            elif \"Kepler\" in i and \"MORB\" in i and \"_F1400\" in i and \"_1400\" in i:\n                self.kepler_morb_f1400_1400 = self.__return_df(f=f)\n            elif \"Kepler\" in i and \"MORB\" in i and \"_F1600\" in i and \"_1200\" in i:\n                self.kepler_morb_f1600_1200 = self.__return_df(f=f)\n            elif \"Kepler\" in i and \"MORB\" in i and \"_F1600\" in i and \"_1400\" in i:\n                self.kepler_morb_f1600_1400 = self.__return_df(f=f)\n            elif \"Kepler\" in i and \"MORB\" in i and \"_F1600\" in i and \"_1600\" in i:\n                self.kepler_morb_f1600_1600 = self.__return_df(f=f)\n\n        files = []\n        fnames = []\n        for dirname, dirnames, f in os.walk(self.depleted_path):\n            for i in f:\n                files.append(dirname + \"/\" + i)\n                fnames.append(i)\n        for index, i in enumerate(fnames):\n            f = files[index]\n            if \"Adibekyan\" in i and \"F1200\" in i and \"_1200\" in i:\n                self.adibekyan_depleted_bsp_f1200_1200 = self.__return_df(f=f)\n            elif \"Adibekyan\" in i and \"F1400\" in i and \"_1200\" in i:\n                self.adibekyan_depleted_bsp_f1400_1200 = self.__return_df(f=f)\n            elif \"Adibekyan\" in i and \"F1400\" in i and \"_1400\" in i:\n                self.adibekyan_depleted_bsp_f1400_1400 = self.__return_df(f=f)\n            elif \"Adibekyan\" in i and \"F1600\" in i and \"_1200\" in i:\n                self.adibekyan_depleted_bsp_f1600_1200 = self.__return_df(f=f)\n            elif \"Adibekyan\" in i and \"F1600\" in i and \"_1400\" in i:\n                self.adibekyan_depleted_bsp_f1600_1400 = self.__return_df(f=f)\n            elif \"Adibekyan\" in i and \"F1600\" in i and \"_1600\" in i:\n                self.adibekyan_depleted_bsp_f1600_1600 = self.__return_df(f=f)\n            elif \"Kepler\" in i and \"F1200\" in i and \"_1200\" in i:\n                self.kepler_depleted_bsp_f1200_1200 = self.__return_df(f=f)\n            elif \"Kepler\" in i and \"F1400\" in i and \"_1200\" in i:\n                self.kepler_depleted_bsp_f1400_1200 = self.__return_df(f=f)\n            elif \"Kepler\" in i and \"F1400\" in i and \"_1400\" in i:\n                self.kepler_depleted_bsp_f1400_1400 = self.__return_df(f=f)\n            elif \"Kepler\" in i and \"F1600\" in i and \"_1200\" in i:\n                self.kepler_depleted_bsp_f1600_1200 = self.__return_df(f=f)\n            elif \"Kepler\" in i and \"F1600\" in i and \"_1400\" in i:\n                self.kepler_depleted_bsp_f1600_1400 = self.__return_df(f=f)\n            elif \"Kepler\" in i and \"F1600\" in i and \"_1600\" in i:\n                self.kepler_depleted_bsp_f1600_1600 = self.__return_df(f=f)\n\n    def __get_morb_row(self, star, morb_file):\n        for row in morb_file:\n            if row[0] == star:\n                return row\n        return []\n\n    def __get_earth_row(self, file):\n        for row in file:\n            if row[0].lower() == \"sun\":\n                return row\n\n    def __compute_buoyancy_at_depth(self, density_differentials, plate_thickness=10 * 1000, gravity=9.8):\n        buoyancies = []\n        for index, i in enumerate(density_differentials):\n            if index < len(density_differentials) - 1:\n                sublist_density_diffs = density_differentials[0:index + 1]\n                d = DEPTHS[0:index + 1]\n                buoyancy_force = integrate.simps(sublist_density_diffs, d) * 1000 * 1000 * plate_thickness * gravity\n                buoyancies.append(buoyancy_force)\n            else:\n                buoyancy_force = integrate.simps(density_differentials,\n                                                 DEPTHS) * 1000 * 1000 * plate_thickness * gravity\n                buoyancies.append(buoyancy_force)\n        return buoyancies\n\n\n    def get_buoyancy(self, bsp_file, morb_file):\n        buoyancies = {}\n\n        for bsp_row in bsp_file:\n            star = bsp_row[0]\n            morb_row = self.__get_morb_row(star=star, morb_file=morb_file)\n            if len(bsp_row[1:]) == len(morb_row[1:]) == len(DEPTHS):\n                densitity_differnces = [float(x) - float(y) for x, y in zip(morb_row[1:], bsp_row[1:])]\n                buoyancy_force = self.__compute_buoyancy_at_depth(density_differentials=densitity_differnces)\n                buoyancies.update({star: buoyancy_force})\n\n        return buoyancies", "meta": {"hexsha": "fe0f88146208bd1e002ed44bd6154bf5ad9208bc", "size": 9047, "ext": "py", "lang": "Python", "max_stars_repo_path": "analysis/buoyancy.py", "max_stars_repo_name": "ScottHull/Exoplanet-Pocketknife", "max_stars_repo_head_hexsha": "15b49ff3612adc3b31a78c27379fb8b2f47c6c8f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analysis/buoyancy.py", "max_issues_repo_name": "ScottHull/Exoplanet-Pocketknife", "max_issues_repo_head_hexsha": "15b49ff3612adc3b31a78c27379fb8b2f47c6c8f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analysis/buoyancy.py", "max_forks_repo_name": "ScottHull/Exoplanet-Pocketknife", "max_forks_repo_head_hexsha": "15b49ff3612adc3b31a78c27379fb8b2f47c6c8f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.2947976879, "max_line_length": 123, "alphanum_fraction": 0.60473085, "include": true, "reason": "from scipy", "num_tokens": 2998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.18857024147945226}}
{"text": "from random import randint, randrange, choice, shuffle, uniform\nimport time\nimport keyboard\nimport numpy as np\n\n#======CONSTANTS======#\n\nWHOLESALE_PRICE = 70    #Price corps pay for replenishing their product inventory\nMAX_INVSPACE = 50       #Max inventory storage a corp has\nMARKET_FEE = 50         #Daily cost corps need to pay to say in the market\n\n#=====================#\n\nclass Market():\n    def __init__(self, consumers = [], corps = [], vacantConsumerIDs = [], vacantCorpIDs = []):\n        self.consumers = consumers;\n        self.corps = corps;\n        self.vacantConsumerIDs = vacantConsumerIDs; #When a consumer exits the market, its ID gets stored here for a new consumer to come and take\n        self.vacantCorpIDs = vacantCorpIDs;         #Same as above but for corps\n    \n\n    #Populates the market at the begining of the simulation\n    def populate(self):\n        #Populate consumers\n        for i in range(1, 1001):\n            self.consumers.append(Consumer(ID = str(i)))\n\n        #Populate corps\n        for i in range(1, 101):\n            self.corps.append(Corp(ID = 'Cx' + str(i), price = randint(190, 210)))\n\n\n    #Repopulates the market\n    def repopulate(self):\n        #Try to repopulate consumers (60% chance of replenishing per vacant)\n        for i in self.vacantConsumerIDs:\n            if randint(1, 100) <= 60: self.consumers.append(Consumer(ID = i))\n\n        #Try to repopulate corps (30% chance of replenishing per vacant)\n        for i in self.vacantCorpsIDs:\n            if randint(1, 100) <= 30: self.corps.append(Corp(ID = i))\n\n\n    #Checks for broke corps and unsatisfied consumers. Called in self.newDay()\n    def update(self):\n        #Remove leaving consumers from the market and store their IDs for future costumers\n        for consumer in self.consumers: \n            consumer.update();\n            if not consumer.inMarket: \n                self.vacantConsumerIDs.append(consumer.ID);\n                self.consumers.remove(consumer);\n\n        #Remove broke corps from the market and store their IDs for future corps\n        for corp in self.corps:\n            corp.update();\n            if not corp.inBusiness: \n                self.vacantCorpIDs.append(corp.ID);\n                self.corps.remove(corp);\n\n\n    #Simulates a full day in the market\n    def newDay(self):\n        #The new day's parameters get set\n        shuffle(self.consumers);    #Shuffle the customer list for changing buying order each day\n\n        #Today's simulation begins\n        for consumer in self.consumers:\n            shuffle(self.corps);            #Shuffle the corps list for changing access for each customer\n            for corp in self.corps:\n                consumer.searchProduct(corp.price, corp.inventory, corp.ID) #[consumer] searches for a product in [corp]\n                if consumer.hasBought:\n                    corp.inventory -= 1;    #Consumer has bought, the product gets removed from [corp]'s inventory\n                    corp.demand += 1;\n                    corp.money += corp.price;\n                    break;                  #Consumer ends the day\n        self.update()\n\n\nclass Consumer():\n    def __init__(self, lastBoughtID = None, ID = 0, hasBought = False, inMarket = True):\n        self.ID = ID;                              #Consumer's IDs are numeric\n        self.lastBoughtID = lastBoughtID;          #Saves the last corp's ID from which the customer has bought\n        self.buyingPrice = randint(5000, 10000);   #Maximum price the consumer will pay for a product\n        self.hasBought = hasBought;                #Bool, indicates if the consumer was able to buy something\n        self.inMarket = inMarket;                  #Bool, flag var for deleting consumers when they leave the market\n    \n\n    #Iterates through corps in the market searching for a product to buy with a valid price\n    def searchProduct(self, price, products, cID):\n        if products > 0 and price <= self.buyingPrice:\n            self.hasBought = True;\n            self.buyingPrice = price;\n            self.lastBoughtID = cID;\n        else: self.hasBought = False;\n\n\n    #Checks if consumer has bought, if he hasnt it sets inMarket bool to False for him to exit\n    def update(self):   \n        if not self.hasBought: self.inMarket = False;\n\n\nclass Corp():\n    def __init__(self, demand = 0, willInvest = False, money = randint(100000, 200000), ID = 'Cx', price = 0, inventory = MAX_INVSPACE, inBusiness = True, history = []):\n        self.ID = ID;               #Corp's IDs are in the form of Cx plus numeric id\n        self.money = money;\n        self.demand = demand;               #Daily sold products\n        self.price = price;                 #Initial price always between (190, 210)\n        self.inventory = inventory;         #Products in the corp's storage waiting to be sold (MAX len == 50)\n        self.willInvest = willInvest;       #Random var that decides if the corp replenishes inv each day\n        self.inBusiness = inBusiness;       #Bool, indicates if the corp is alive marketwise\n        self.history = [str(hex(id(self)))] #List with (price, demand) historic pairs, [0] = object hex mem adress, this is to avoid all Corp.history arrays to have the same mem adress\n\n\n    #Replenishes corp's inventory with new products\n    def replenishInv(self):\n        if len(self.inventory) <= 5 or self.willInvest:\n            self.willInvest = False;\n            while self.inventory <= MAX_INVSPACE and self.money >= WHOLESALE_PRICE:\n                inventory += 1;\n                self.money -= WHOLESALE_PRICE;\n\n\n    #Sets the random bool that determines random inventory replenishing     \n    def setInvestment(self): \n        if randint(1, 100) <= 25: self.willInvest = True;\n\n\n    #Algorythm for price adjustment simulation, only called if we have 2 data tuples to start working with\n    def setPrice(self):\n        '''\n        try:\n            #1st: Find q(p) by solving a system of linear equations, this is done by understanding q(p) function as matrixes in the form of AX=B\n            A = np.array([[1, self.history[-2][0]], [1, self.history[-1][0]]]);\n            B = np.array([self.history[-2][1], self.history[-1][1]]);\n            X = np.linalg.solve(A, B);                   #RETURNS -> (n, m) of q(p) = m*p + n so: q(p) = X[1]*p + X[0]\n        \n            #2nd: Calculate price flexibility epsilon (e)\n            try:\n                q = int(X[1])*self.history[-1][0]+int(X[0])\n                q_prime = int(X[1])\n                e = (self.history[-1][0]/q)*q_prime\n            except ZeroDivisionError:\n                print(f\"ID: {self.ID}\")\n                print(f\"Last 2 historic pairs: {self.history[-1]}{self.history[-2]}\")\n                e = uniform(0.5, 1.5);\n\n        except np.linalg.LinAlgError:   e = uniform(0.5, 1.5);\n\n        #3rd: Compare abs(e) with one to determine what to do with the price\n        if abs(e) < 1:      self.price += int(20 * (1-e))\n        elif abs(e) > 1:    self.price -= int(20 * (e-1))\n        else:               pass    \n        '''\n\n    #Pays market fee, checks if corp has gone bankrupt and records day's (pi, qi) pairs\n    #Called in Market.update()\n    def update(self):\n        #print(f\"BONKED corp.update(), history memdir = {hex(id(self.history))} !!!: ID: {self.ID}\")\n        if type(self.history[0]) is str: self.history.pop(0);  #Delete mem.access hex\n        if len(self.history) >= 2: self.setPrice();            #Adjust price when enough historic data is available\n        self.history.append((self.price, self.demand))\n        self.money -= MARKET_FEE;                              #Corp pays the daily market fee\n        if self.money < 0: self.inBusiness = False;            #Checks if corp went bankrupt, if so its kicked out\n\n\n\n#===============SIMULATION {MAIN} CONTROL PROCESS================#\n\nmarket = Market();\nmarket.populate();\nisRunning = True;\nday = 0\n\ndebugTags =['Cx1', 'Cx2', 'Cx3', '1', '2', '3']\n\nwhile isRunning:\n    #check escape input\n    try:\n        pass;\n        #if keyboard.is_pressed(\"q\"): isRunning = False;\n    except: pass;\n    #Simulate new day is called\n    market.newDay();\n    day += 1\n    #newDay not simulated until space is pressed for debbuging purposes\n    print(f\"=========DAY {day}=========\")\n    print(\"\")\n    print(\"CORPS (only 3 first by id): \")\n    print(\"\")\n    for i in range(0, len(market.corps)):\n        if market.corps[i].ID in debugTags:\n            print(f\"ID: {market.corps[i].ID}\")\n            print(f\"Money: {market.corps[i].money}\")\n            print(f\"Price: {market.corps[i].price}\")\n            print(f\"Demand: {market.corps[i].demand}\")\n            print(f\"Stock: {market.corps[i].inventory}/{MAX_INVSPACE}\")\n            print(f\"Historic price/demand: {market.corps[i].history}\")\n            print(f\"Number of corps: {len(market.corps)}\")\n            print(\"\")\n    \n    print(\"CONSUMERS (only 3 first by id): \")\n    print(\"\")\n    for i in range(0, len(market.consumers)):\n        if market.consumers[i].ID in debugTags:\n            print(f\"ID: {market.consumers[i].ID}\")\n            print(f\"MaxPrice: {market.consumers[i].buyingPrice}\")\n            print(f\"HasBought?: {market.consumers[i].hasBought}\")\n            print(f\"LastBoughtAt: Corp {market.consumers[i].lastBoughtID}\")\n            print(f\"TotConsumers: {len(market.consumers)}\")\n            print(\"\")\n    while True:\n        debugFlag = input(\"Input any key to continue: \");\n        if debugFlag == 'q': raise ValueError(\"Ending simulation...\");\n        if debugFlag or not debugFlag: break;\n    #time.sleep(3)       #Wait 3 seconds between simulated days for reviewing and debugging purpose\n\n\n\n#================TO - DO================#\n\n#Algorythm for corp price adjustment in response to products sold More products == Higher prices and vicev.\n#ALGORYHM FORMULA: R(p) = p * q(p)   ||| p = price | q(p) = demand function | R(p) = Revenue |||[Maximize R]\n#d(p) estimated from historical sales data composed by pairs of the type (pi, qi) \n#   ||| pi = i(th) day's price | qi = i(th) day's demand|||\n#WE NEED AT LEAST 2 PAIRS (pi, qi) FOR THE ALGORYTHM TO WORK WITH\n#\n#Determine the price profitability with PRICE ELASTICITY OF DEMAND: e = (p/q)*(dq/dp) || e = p/q(p) * q'(p) \n#|e| > 1, the price is ELASTIC      (%∆Q > %∆P)     => DECREASE PRICE\n#|e| < 1, the price is INELASTIC    (%∆Q < %∆P)     => INCREASE PRICE\n#|e| = 1, the price is UNIT ELASTIC (%∆Q = %∆P)     => MANTAIN PRICE  (price is optimal)\n\n#\n\n#LINKS:\n#\n#https://math.ucr.edu/~joselg/teachingS13/elasticity.pdf\n#https://stackabuse.com/solving-systems-of-linear-equations-with-pythons-numpy/\n#https://www.geeksforgeeks.org/scipy-curve-fitting/ !!! -> IMPORTANT, q(p) IS NOT A LINE, ITS A CURVE, OBTAIN IT WITH THIS AND USING ALL HISTORIC PAIR DATA AVAILABLE", "meta": {"hexsha": "caf90bb8a2c745e093292e2fc1ed7ca18e639306", "size": 10761, "ext": "py", "lang": "Python", "max_stars_repo_path": "PythonCode/MarketSimulation/main.py", "max_stars_repo_name": "sansy98/sansy_repo", "max_stars_repo_head_hexsha": "bf67dfc9770223b9c87b328c92992095a660d36f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-11T06:51:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-06T18:57:02.000Z", "max_issues_repo_path": "PythonCode/MarketSimulation/main.py", "max_issues_repo_name": "sansy98/sansy_repo", "max_issues_repo_head_hexsha": "bf67dfc9770223b9c87b328c92992095a660d36f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PythonCode/MarketSimulation/main.py", "max_forks_repo_name": "sansy98/sansy_repo", "max_forks_repo_head_hexsha": "bf67dfc9770223b9c87b328c92992095a660d36f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.2142857143, "max_line_length": 184, "alphanum_fraction": 0.6004088839, "include": true, "reason": "import numpy", "num_tokens": 2766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883592602051, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.18848948132340612}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nfrom __future__ import absolute_import, division, print_function\nimport glob\nimport re\nimport numpy as np\nfrom scipy.interpolate import RegularGridInterpolator\nfrom scipy.interpolate import UnivariateSpline\nimport healpy as hp\nfrom astropy.io import fits\n\nimport pyIrfLoader\n\npyIrfLoader.Loader_go()\n\nfrom fermipy import utils\nfrom fermipy import spectrum\nfrom fermipy.utils import edge_to_center\nfrom fermipy.utils import edge_to_width\nfrom fermipy.utils import sum_bins\nfrom fermipy.skymap import HpxMap\nfrom fermipy.hpx_utils import HPX\nfrom fermipy.ltcube import LTCube\n\nevtype_string = {\n    1: 'FRONT',\n    2: 'BACK',\n    4: 'PSF0',\n    8: 'PSF1',\n    16: 'PSF2',\n    32: 'PSF3',\n    64: 'EDISP0',\n    128: 'EDISP1',\n    256: 'EDISP2',\n    512: 'EDISP3',\n}\n\n\ndef loglog_quad(x, y, dim):\n\n    ys0 = [slice(None)] * y.ndim\n    ys1 = [slice(None)] * y.ndim\n\n    xs0 = [None] * y.ndim\n    xs1 = [None] * y.ndim\n\n    ys0[dim] = slice(None, -1)\n    ys1[dim] = slice(1, None)\n\n    xs0[dim] = slice(None, -1)\n    xs1[dim] = slice(1, None)\n    log_ratio = np.log(x[xs1] / x[xs0])\n    return 0.5 * (y[ys0] * x[xs0] + y[ys1] * x[xs1]) * log_ratio\n\n\ndef bins_per_dec(edges):\n    return (len(edges) - 1) / np.log10(edges[-1] / edges[0])\n\n\ndef bitmask_to_bits(mask):\n\n    bits = []\n    for i in range(32):\n        if mask & (2**i):\n            bits += [2**i]\n\n    return bits\n\n\ndef poisson_log_like(c, m):\n    return c * np.log(m) - m\n\n\ndef poisson_ts(sig, bkg, bkg_fit=None):\n\n    if bkg_fit is None:\n        return 2 * (poisson_log_like(sig + bkg, sig + bkg) -\n                    poisson_log_like(sig + bkg, bkg))\n    else:\n        return 2 * (poisson_log_like(sig + bkg, sig + bkg_fit) -\n                    poisson_log_like(sig + bkg, bkg_fit))\n\n\ndef poisson_ts_fast(sig, bkg, bkg_fit=None):\n\n    if bkg_fit is None:\n        return 2 * ((sig + bkg) * np.log((sig + bkg) / bkg) - sig)\n    else:\n        return 2 * ((sig + bkg) * np.log((sig + bkg_fit) / bkg_fit) - sig)\n\n\ndef compute_ext_flux(egy, flux):\n    pass\n\n\ndef compute_ps_loc(egy, flux):\n    \"\"\"Solve for the localization precision of a point source with a given flux.\"\"\"\n    pass\n\n\ndef compute_ps_counts(ebins, exp, psf, bkg, fn, egy_dim=0, spatial_model='PointSource',\n                      spatial_size=1E-3):\n    \"\"\"Calculate the observed signal and background counts given models\n    for the exposure, background intensity, PSF, and source flux.\n\n    Parameters\n    ----------\n    ebins : `~numpy.ndarray`\n        Array of energy bin edges.\n\n    exp : `~numpy.ndarray`\n        Model for exposure.\n\n    psf : `~fermipy.irfs.PSFModel`\n        Model for average PSF.\n\n    bkg : `~numpy.ndarray`\n        Array of background intensities.\n\n    fn : `~fermipy.spectrum.SpectralFunction`\n\n    egy_dim : int\n        Index of energy dimension in ``bkg`` and ``exp`` arrays.\n\n    \"\"\"\n    ewidth = utils.edge_to_width(ebins)\n    ectr = np.exp(utils.edge_to_center(np.log(ebins)))\n\n    r68 = psf.containment_angle(ectr, fraction=0.68)\n    if spatial_model != 'PointSource':\n        r68[r68 < spatial_size] = spatial_size\n\n    # * np.ones((len(ectr), 31))\n    theta_edges = np.linspace(0.0, 3.0, 31)[np.newaxis, :]\n    theta_edges = theta_edges * r68[:, np.newaxis]\n    theta = 0.5 * (theta_edges[:, :-1] + theta_edges[:, 1:])\n    domega = np.pi * (theta_edges[:, 1:]**2 - theta_edges[:, :-1]**2)\n\n    if spatial_model == 'PointSource':\n        sig_pdf = domega * psf.interp(ectr[:, np.newaxis], theta)\n    elif spatial_model == 'RadialGaussian':\n        sig_pdf = domega * utils.convolve2d_gauss(lambda t: psf.interp(ectr[:, np.newaxis, np.newaxis], t),\n                                                  theta, spatial_size / 1.5095921854516636, nstep=2000)\n    elif spatial_model == 'RadialDisk':\n        sig_pdf = domega * utils.convolve2d_disk(lambda t: psf.interp(ectr[:, np.newaxis, np.newaxis], t),\n                                                 theta, spatial_size / 0.8246211251235321)\n    else:\n        raise ValueError('Invalid spatial model: {}'.format(spatial_model))\n\n    sig_pdf *= (np.pi / 180.)**2\n    sig_flux = fn.flux(ebins[:-1], ebins[1:])\n\n    # Background and signal counts\n    bkgc = bkg[..., np.newaxis] * domega * exp[..., np.newaxis] * \\\n        ewidth[..., np.newaxis] * (np.pi / 180.)**2\n    sigc = sig_pdf * sig_flux[..., np.newaxis] * exp[..., np.newaxis]\n\n    return sigc, bkgc\n\n\ndef compute_norm(sig, bkg, ts_thresh, min_counts, sum_axes=None, bkg_fit=None,\n                 rebin_axes=None):\n    \"\"\"Solve for the normalization of the signal distribution at which the\n    detection test statistic (twice delta-loglikelihood ratio) is >=\n    ``ts_thresh`` AND the number of signal counts >= ``min_counts``.\n    This function uses the Asimov method to calculate the median\n    expected TS when the model for the background is fixed (no\n    uncertainty on the background amplitude).\n\n    Parameters\n    ----------\n    sig : `~numpy.ndarray`\n        Array of signal amplitudes in counts.\n\n    bkg : `~numpy.ndarray`\n        Array of background amplitudes in counts.\n\n    ts_thresh : float\n        Test statistic threshold.\n\n    min_counts : float\n        Counts threshold.\n\n    sum_axes : list\n        Axes over which the source test statistic should be summed.\n        By default the summation will be performed over all\n        dimensions.\n\n    bkg_fit : `~numpy.ndarray`\n        Array of background amplitudes in counts for the fitting\n        model.  If None then the fit model will be equal to the data\n        model.\n\n    \"\"\"\n\n    if sum_axes is None:\n        sum_axes = np.arange(sig.ndim)\n\n    sig = np.expand_dims(sig, -1)\n    bkg = np.expand_dims(bkg, -1)\n    sig_sum = np.apply_over_axes(np.sum, sig, sum_axes)\n    bkg_sum = np.apply_over_axes(np.sum, bkg, sum_axes)\n    bkg_fit_sum = None\n\n    if bkg_fit is not None:\n        bkg_fit = np.expand_dims(bkg_fit, -1)\n        bkg_fit_sum = np.apply_over_axes(np.sum, bkg_fit, sum_axes)\n\n    sig_rebin = sig\n    bkg_rebin = bkg\n    bkg_fit_rebin = bkg_fit\n\n    if rebin_axes:\n        sig_rebin = sig.copy()\n        bkg_rebin = bkg.copy()\n        if bkg_fit is not None:\n            bkg_fit_rebin = bkg_fit.copy()\n\n        for dim, rebin in zip(sum_axes, rebin_axes):\n            sig_rebin = sum_bins(sig_rebin, dim, rebin)\n            bkg_rebin = sum_bins(bkg_rebin, dim, rebin)\n            if bkg_fit is not None:\n                bkg_fit_rebin = sum_bins(bkg_fit_rebin, dim, rebin)\n\n    # Find approx solution using coarse binning and summed arrays\n    sig_scale = 10**np.linspace(0.0, 10.0, 51) * (min_counts / sig_sum)\n    vals_approx = _solve_norm(sig_rebin, bkg_rebin, ts_thresh, min_counts,\n                              sig_scale, sum_axes, bkg_fit_rebin)\n\n    # Refine solution using an interval (0.1,10) around approx\n    # solution\n    sig_scale = (10**np.linspace(0.0, 1.0, 21) *\n                 np.fmax(0.333 * vals_approx[..., None],\n                         min_counts / sig_sum))\n\n    vals = _solve_norm(sig, bkg, ts_thresh, min_counts, sig_scale,\n                       sum_axes, bkg_fit)\n\n    #sig_scale = 10**np.linspace(0.0, 10.0, 101)*(min_counts / sig_sum)\n    # vals = _solve_norm(sig, bkg, ts_thresh, min_counts, sig_scale2,\n    #                   sum_axes, bkg_fit)\n\n    return vals\n\n\ndef _solve_norm(sig, bkg, ts_thresh, min_counts, sig_scale, sum_axes,\n                bkg_fit=None):\n\n    ts = np.apply_over_axes(np.sum, poisson_ts_fast(sig * sig_scale,\n                                                    bkg, bkg_fit),\n                            sum_axes)\n\n    vals = np.ones(ts.shape[:-1])\n    for idx, v in np.ndenumerate(ts[..., 0]):\n\n        if ts[idx][0] >= ts_thresh:\n            vals[idx] = sig_scale[idx][0]\n            continue\n\n        m = slice(np.argmin(ts[idx]), None)\n        vals[idx] = np.interp(ts_thresh, ts[idx][m], sig_scale[idx][m])\n        #fn = UnivariateSpline(ts[idx][m], sig_scale[idx][m], k=2, s=0)\n        #vals[idx] = fn(ts_thresh)\n\n    return vals\n\n\nclass ExposureMap(HpxMap):\n\n    def __init__(self, data, hpx):\n        HpxMap.__init__(self, data, hpx)\n\n    @classmethod\n    def create(cls, ltc, event_class, event_types, ebins):\n        \"\"\"Create an exposure map from a livetime cube.  This method will\n        generate an exposure map with the same geometry as the\n        livetime cube (nside, etc.).\n\n        Parameters\n        ----------\n        ltc : `~fermipy.irfs.LTCube`\n            Livetime cube object.\n\n        event_class : str\n            Event class string.\n\n        event_types : list\n            List of event type strings, e.g. ['FRONT','BACK'].\n\n        ebins :  `~numpy.ndarray`\n            Energy bin edges in MeV.\n\n        \"\"\"\n\n        evals = np.sqrt(ebins[1:] * ebins[:-1])\n        exp = np.zeros((len(evals), ltc.hpx.npix))\n        for et in event_types:\n            aeff = create_aeff(event_class, et, evals, ltc.costh_center)\n            exp += np.sum(aeff.T[:, :, np.newaxis] *\n                          ltc.data[:, np.newaxis, :], axis=0)\n\n        hpx = HPX(ltc.hpx.nside, ltc.hpx.nest,\n                  ltc.hpx.coordsys, ebins=ebins)\n        return cls(exp, hpx)\n\n\nclass PSFModel(object):\n    \"\"\"Class that stores a pre-computed model of the PSF versus energy.  \n\n    \"\"\"\n\n    def __init__(self, dtheta, energies, cth_bins, exp, psf, wts):\n        \"\"\"Create a PSFModel.\n\n        Parameters\n        ----------\n        dtheta : `~numpy.ndarray`\n            Array of angular offsets in degrees at which the PSF is\n            evaluated.\n\n        energies : `~numpy.ndarray`\n            Array of energies in MeV at which the PSF is evaluated.\n\n        cth_bins : `~numpy.ndarray`\n            Interval in cosine of the incidence angle for which this\n            model of the PSF was generated.\n\n        exp : `~numpy.ndarray`\n            Array of exposure vs. energy in cm^2 s.\n\n        psf : `~numpy.ndarray`\n            2D array of PSF values evaluated on an NxM grid of N\n            offset angles and M energies (defined by ``dtheta`` and\n            ``energies``).\n\n        wts : `~numpy.ndarray`\n            Array of weights vs. energy.  These are used to evaluate\n            the bin-averaged PSF model.\n\n        \"\"\"\n\n        self._dtheta = dtheta\n        self._log_energies = np.log10(energies)\n        self._energies = energies\n        self._cth_bins = cth_bins\n        self._cth = utils.edge_to_center(cth_bins)\n        self._scale_fn = None\n        self._exp = exp\n        self._psf = psf\n        self._wts = wts\n        self._psf_fn = RegularGridInterpolator((self._dtheta, self._log_energies),\n                                               np.log(self._psf),\n                                               bounds_error=False,\n                                               fill_value=None)\n        self._wts_fn = RegularGridInterpolator((self._log_energies,),\n                                               np.log(self._wts),\n                                               bounds_error=False,\n                                               fill_value=None)\n\n    def eval(self, ebin, dtheta, scale_fn=None):\n        \"\"\"Evaluate the PSF at the given energy bin index.\n\n        Parameters\n        ----------\n        ebin : int\n            Index of energy bin.\n\n        dtheta : array_like\n            Array of angular separations in degrees.\n\n        scale_fn : callable        \n            Function that evaluates the PSF scaling function.\n            Argument is energy in MeV.\n        \"\"\"\n\n        if scale_fn is None and self.scale_fn is not None:\n            scale_fn = self.scale_fn\n\n        if scale_fn is None:\n            scale_factor = 1.0\n        else:\n            dtheta = dtheta / scale_fn(self.energies[ebin])\n            scale_factor = 1. / scale_fn(self.energies[ebin])**2\n\n        vals = 10**np.interp(dtheta, self.dtheta, np.log10(self.val[:, ebin]))\n        return vals * scale_factor\n\n    def interp(self, energies, dtheta, scale_fn=None):\n        \"\"\"Evaluate the PSF model at an array of energies and angular\n        separations.\n\n        Parameters\n        ----------\n        energies : array_like\n            Array of energies in MeV.\n\n        dtheta : array_like\n            Array of angular separations in degrees.\n\n        scale_fn : callable        \n            Function that evaluates the PSF scaling function.\n            Argument is energy in MeV.\n        \"\"\"\n\n        if scale_fn is None and self.scale_fn:\n            scale_fn = self.scale_fn\n\n        log_energies = np.log10(energies)\n\n        shape = (energies * dtheta).shape\n        scale_factor = np.ones(shape)\n\n        if scale_fn is not None:\n            dtheta = dtheta / scale_fn(energies)\n            scale_factor = 1. / scale_fn(energies)**2\n\n        vals = np.exp(self._psf_fn((dtheta, log_energies)))\n        return vals * scale_factor\n\n    def interp_bin(self, egy_bins, dtheta, scale_fn=None):\n        \"\"\"Evaluate the bin-averaged PSF model over the energy bins ``egy_bins``.\n\n        Parameters\n        ----------\n        egy_bins : array_like\n            Energy bin edges in MeV.\n\n        dtheta : array_like\n            Array of angular separations in degrees.\n\n        scale_fn : callable        \n            Function that evaluates the PSF scaling function.\n            Argument is energy in MeV.\n        \"\"\"\n\n        npts = 4\n        egy_bins = np.exp(utils.split_bin_edges(np.log(egy_bins), npts))\n        egy = np.exp(utils.edge_to_center(np.log(egy_bins)))\n        log_energies = np.log10(egy)\n\n        vals = self.interp(egy[None, :], dtheta[:, None],\n                           scale_fn=scale_fn)\n        wts = np.exp(self._wts_fn((log_energies,)))\n        wts = wts.reshape((1,) + wts.shape)\n        vals = np.sum(\n            (vals * wts).reshape((vals.shape[0], int(vals.shape[1] / npts), npts)), axis=2)\n        vals /= np.sum(wts.reshape(wts.shape[0],\n                                   int(wts.shape[1] / npts), npts), axis=2)\n        return vals\n\n    def containment_angle(self, energies=None, fraction=0.68, scale_fn=None):\n        \"\"\"Evaluate the PSF containment angle at a sequence of energies.\"\"\"\n\n        if energies is None:\n            energies = self.energies\n\n        vals = self.interp(energies[np.newaxis, :], self.dtheta[:, np.newaxis],\n                           scale_fn=scale_fn)\n        dtheta = np.radians(self.dtheta[:, np.newaxis] * np.ones(vals.shape))\n        return self._calc_containment(dtheta, vals, fraction)\n\n    def containment_angle_bin(self, egy_bins, fraction=0.68, scale_fn=None):\n        \"\"\"Evaluate the PSF containment angle averaged over energy bins.\"\"\"\n\n        vals = self.interp_bin(egy_bins, self.dtheta, scale_fn=scale_fn)\n        dtheta = np.radians(self.dtheta[:, np.newaxis] * np.ones(vals.shape))\n        return self._calc_containment(dtheta, vals, fraction)\n\n    def _calc_containment(self, dtheta, vals, fraction=0.68):\n\n        delta = dtheta[1:] - dtheta[:-1]\n        ctr = 0.5 * (dtheta[1:] + dtheta[:-1])\n\n        avg_val = 0.5 * (vals[1:, :] * np.sin(dtheta[1:, :]) +\n                         vals[:-1, :] * np.sin(dtheta[:-1, :]))\n\n        csum = delta * avg_val * 2 * np.pi\n        csum = np.cumsum(csum, axis=0)\n        theta = np.zeros(csum.shape[1])\n\n        for i in range(csum.shape[1]):\n            theta[i] = np.degrees(np.interp(fraction, csum[:, i],\n                                            dtheta[1:, i]))\n\n        return theta\n\n    def set_scale_fn(self, scale_fn):\n        self._scale_fn = scale_fn\n\n    @property\n    def scale_fn(self):\n        return self._scale_fn\n\n    @property\n    def dtheta(self):\n        return self._dtheta\n\n    @property\n    def log_energies(self):\n        return self._log_energies\n\n    @property\n    def energies(self):\n        return self._energies\n\n    @property\n    def val(self):\n        return self._psf\n\n    @property\n    def exp(self):\n        return self._exp\n\n    @classmethod\n    def create(cls, skydir, ltc, event_class, event_types, energies, cth_bins=None,\n               ndtheta=500, use_edisp=False, fn=None, nbin=64):\n        \"\"\"Create a PSFModel object.  This class can be used to evaluate the\n        exposure-weighted PSF for a source with a given observing\n        profile and energy distribution.\n\n        Parameters\n        ----------\n        skydir : `~astropy.coordinates.SkyCoord`\n\n        ltc : `~fermipy.irfs.LTCube`\n\n        energies : `~numpy.ndarray`\n            Grid of energies at which the PSF will be pre-computed.\n\n        cth_bins : `~numpy.ndarray`\n            Bin edges in cosine of the inclination angle.\n\n        use_edisp : bool\n            Generate the PSF model accounting for the influence of\n            energy dispersion.\n\n        fn : `~fermipy.spectrum.SpectralFunction`\n            Model for the spectral energy distribution of the source.\n\n        \"\"\"\n\n        if isinstance(event_types, int):\n            event_types = bitmask_to_bits(event_types)\n\n        if fn is None:\n            fn = spectrum.PowerLaw([1E-13, -2.0])\n\n        dtheta = np.logspace(-4, 1.75, ndtheta)\n        dtheta = np.insert(dtheta, 0, [0])\n        log_energies = np.log10(energies)\n        egy_bins = 10**utils.center_to_edge(log_energies)\n\n        if cth_bins is None:\n            cth_bins = np.array([0.2, 1.0])\n\n        if use_edisp:\n            psf = create_wtd_psf(skydir, ltc, event_class, event_types,\n                                 dtheta, egy_bins, cth_bins, fn, nbin=nbin)\n            wts = calc_counts_edisp(skydir, ltc, event_class, event_types,\n                                    egy_bins, cth_bins, fn, nbin=nbin)\n        else:\n            psf = create_avg_psf(skydir, ltc, event_class, event_types,\n                                 dtheta, energies, cth_bins)\n            wts = calc_counts(skydir, ltc, event_class, event_types,\n                              egy_bins, cth_bins, fn)\n\n        exp = calc_exp(skydir, ltc, event_class, event_types,\n                       energies, cth_bins)\n\n        return cls(dtheta, energies, cth_bins, np.squeeze(exp), np.squeeze(psf),\n                   np.squeeze(wts))\n\n\ndef create_irf(event_class, event_type):\n    if isinstance(event_type, int):\n        event_type = evtype_string[event_type]\n\n    irf_factory = pyIrfLoader.IrfsFactory.instance()\n    irfname = '%s::%s' % (event_class, event_type)\n    irf = irf_factory.create(irfname)\n    return irf\n\n\ndef create_psf(event_class, event_type, dtheta, egy, cth):\n    \"\"\"Create an array of PSF response values versus energy and\n    inclination angle.\n\n    Parameters\n    ----------\n    egy : `~numpy.ndarray`\n        Energy in MeV.\n\n    cth : `~numpy.ndarray`\n        Cosine of the incidence angle.\n\n    \"\"\"\n    irf = create_irf(event_class, event_type)\n    theta = np.degrees(np.arccos(cth))\n    m = np.zeros((len(dtheta), len(egy), len(cth)))\n\n    for i, x in enumerate(egy):\n        for j, y in enumerate(theta):\n            m[:, i, j] = irf.psf().value(dtheta, x, y, 0.0)\n\n    return m\n\n\ndef create_edisp(event_class, event_type, erec, egy, cth):\n    \"\"\"Create an array of energy response values versus energy and\n    inclination angle.\n\n    Parameters\n    ----------\n    egy : `~numpy.ndarray`\n        Energy in MeV.\n\n    cth : `~numpy.ndarray`\n        Cosine of the incidence angle.\n\n    \"\"\"\n    irf = create_irf(event_class, event_type)\n    theta = np.degrees(np.arccos(cth))\n    v = np.zeros((len(erec), len(egy), len(cth)))\n    m = (erec[:,None] / egy[None,:] < 3.0) & (erec[:,None] / egy[None,:] > 0.33333)\n    #    m |= ((erec[:,None] / egy[None,:] < 3.0) &\n    #          (erec[:,None] / egy[None,:] > 0.5) & (egy[None,:] < 10**2.5))    \n    m = np.broadcast_to(m[:,:,None], v.shape)\n\n    try:    \n        x = np.ones(v.shape)*erec[:,None,None]\n        y = np.ones(v.shape)*egy[None,:,None]\n        z = np.ones(v.shape)*theta[None,None,:]\n        v[m] = irf.edisp().value(np.ravel(x[m]), np.ravel(y[m]), np.ravel(z[m]), 0.0)\n    except:\n        for i, x in enumerate(egy):\n            for j, y in enumerate(theta):\n                m = (erec / x < 3.0) & (erec / x > 0.333)\n                v[m, i, j] = irf.edisp().value(erec[m], x, y, 0.0)\n        \n    return v\n\n\ndef create_aeff(event_class, event_type, egy, cth):\n    \"\"\"Create an array of effective areas versus energy and incidence\n    angle.  Binning in energy and incidence angle is controlled with\n    the egy and cth input parameters.\n\n    Parameters\n    ----------\n    event_class : str\n        Event class string (e.g. P8R2_SOURCE_V6).\n\n    event_type : list\n\n    egy : array_like\n        Evaluation points in energy (MeV).\n\n    cth : array_like\n        Evaluation points in cosine of the incidence angle.\n\n    \"\"\"\n    irf = create_irf(event_class, event_type)\n    irf.aeff().setPhiDependence(False)\n    theta = np.degrees(np.arccos(cth))\n\n    # Exposure Matrix\n    # Dimensions are Etrue and incidence angle\n    m = np.zeros((len(egy), len(cth)))\n\n    for i, x in enumerate(egy):\n        for j, y in enumerate(theta):\n            m[i, j] = irf.aeff().value(x, y, 0.0)\n\n    return m\n\n\ndef calc_exp(skydir, ltc, event_class, event_types,\n             egy, cth_bins, npts=None):\n    \"\"\"Calculate the exposure on a 2D grid of energy and incidence angle.\n\n    Parameters\n    ----------\n    npts : int    \n        Number of points by which to sample the response in each\n        incidence angle bin.  If None then npts will be automatically\n        set such that incidence angle is sampled on intervals of <\n        0.05 in Cos(Theta).\n\n    Returns\n    -------\n    exp : `~numpy.ndarray`\n        2D Array of exposures vs. energy and incidence angle.\n\n    \"\"\"\n\n    if npts is None:\n        npts = int(np.ceil(np.max(cth_bins[1:] - cth_bins[:-1]) / 0.025))\n\n    exp = np.zeros((len(egy), len(cth_bins) - 1))\n    cth_bins = utils.split_bin_edges(cth_bins, npts)\n    cth = edge_to_center(cth_bins)\n    ltw = ltc.get_skydir_lthist(skydir, cth_bins).reshape(-1, npts)\n    for et in event_types:\n        aeff = create_aeff(event_class, et, egy, cth)\n        aeff = aeff.reshape(exp.shape + (npts,))\n        exp += np.sum(aeff * ltw[np.newaxis, :, :], axis=-1)\n\n    return exp\n\n\ndef create_avg_rsp(rsp_fn, skydir, ltc, event_class, event_types, x,\n                   egy, cth_bins, npts=None):\n    \"\"\"Calculate the weighted response function.\n    \"\"\"\n    if npts is None:\n        npts = int(np.ceil(np.max(cth_bins[1:] - cth_bins[:-1]) / 0.05))\n\n    wrsp = np.zeros((len(x), len(egy), len(cth_bins) - 1))\n    exps = np.zeros((len(egy), len(cth_bins) - 1))\n\n    cth_bins = utils.split_bin_edges(cth_bins, npts)\n    cth = edge_to_center(cth_bins)\n    ltw = ltc.get_skydir_lthist(skydir, cth_bins)\n    ltw = ltw.reshape(-1, npts)\n\n    for et in event_types:\n        rsp = rsp_fn(event_class, et, x, egy, cth)\n        aeff = create_aeff(event_class, et, egy, cth)\n        rsp = rsp.reshape(wrsp.shape + (npts,))\n        aeff = aeff.reshape(exps.shape + (npts,))\n        wrsp += np.sum(rsp * aeff[np.newaxis, :, :, :] *\n                       ltw[np.newaxis, np.newaxis, :, :], axis=-1)\n        exps += np.sum(aeff * ltw[np.newaxis, :, :], axis=-1)\n\n    exps_inv = np.zeros_like(exps)\n    exps_inv[exps > 0] = 1./exps[exps>0]        \n    wrsp *= exps_inv[np.newaxis, :, :]\n    return wrsp\n\n\ndef create_avg_psf(skydir, ltc, event_class, event_types, dtheta,\n                   egy, cth_bins, npts=None):\n    \"\"\"Generate model for exposure-weighted PSF averaged over incidence\n    angle.\n\n    Parameters\n    ----------\n    egy : `~numpy.ndarray`\n        Energies in MeV.\n\n    cth_bins : `~numpy.ndarray`\n        Bin edges in cosine of the incidence angle.\n    \"\"\"\n\n    return create_avg_rsp(create_psf, skydir, ltc,\n                          event_class, event_types,\n                          dtheta, egy,  cth_bins, npts)\n\n\ndef create_avg_edisp(skydir, ltc, event_class, event_types, erec,\n                     egy, cth_bins, npts=None):\n    \"\"\"Generate model for exposure-weighted DRM averaged over incidence\n    angle.\n\n    Parameters\n    ----------\n    egy : `~numpy.ndarray`\n        True energies in MeV.\n\n    cth_bins : `~numpy.ndarray`\n        Bin edges in cosine of the incidence angle.\n    \"\"\"\n    return create_avg_rsp(create_edisp, skydir, ltc,\n                          event_class, event_types,\n                          erec, egy,  cth_bins, npts)\n\n\ndef create_wtd_psf(skydir, ltc, event_class, event_types, dtheta,\n                   egy_bins, cth_bins, fn, nbin=64, npts=1):\n    \"\"\"Create an exposure- and dispersion-weighted PSF model for a source\n    with spectral parameterization ``fn``.  The calculation performed\n    by this method accounts for the influence of energy dispersion on\n    the PSF.\n\n    Parameters\n    ----------\n    dtheta : `~numpy.ndarray`\n\n    egy_bins : `~numpy.ndarray`\n        Bin edges in observed energy.\n\n    cth_bins : `~numpy.ndarray`\n        Bin edges in cosine of the true incidence angle.\n\n    nbin : int\n        Number of bins per decade in true energy.\n\n    npts : int\n        Number of points by which to oversample each energy bin.\n\n    \"\"\"\n    #npts = int(np.ceil(32. / bins_per_dec(egy_bins)))\n    egy_bins = np.exp(utils.split_bin_edges(np.log(egy_bins), npts))\n    etrue_bins = 10**np.linspace(1.0, 6.5, nbin * 5.5 + 1)\n    etrue = 10**utils.edge_to_center(np.log10(etrue_bins))\n\n    psf = create_avg_psf(skydir, ltc, event_class, event_types, dtheta,\n                         etrue, cth_bins)\n    drm = calc_drm(skydir, ltc, event_class, event_types,\n                   egy_bins, cth_bins, nbin=nbin)\n    cnts = calc_counts(skydir, ltc, event_class, event_types,\n                       etrue_bins, cth_bins, fn)\n\n    wts = drm * cnts[None, :, :]\n    wts_norm = np.sum(wts, axis=1)\n    wts_norm[wts_norm == 0] = 1.0\n    wts = wts / wts_norm[:, None, :]\n    wpsf = np.sum(wts[None, :, :, :] * psf[:, None, :, :], axis=2)\n    wts = np.sum(wts[None, :, :, :], axis=2)\n\n    if npts > 1:\n        shape = (wpsf.shape[0], int(wpsf.shape[1] / npts), npts, wpsf.shape[2])\n        wpsf = np.sum((wpsf * wts).reshape(shape), axis=2)\n        shape = (wts.shape[0], int(wts.shape[1] / npts), npts, wts.shape[2])\n        wpsf = wpsf / np.sum(wts.reshape(shape), axis=2)\n\n    return wpsf\n\n\ndef calc_drm(skydir, ltc, event_class, event_types,\n             egy_bins, cth_bins, nbin=64):\n    \"\"\"Calculate the detector response matrix.\"\"\"\n    npts = int(np.ceil(128. / bins_per_dec(egy_bins)))\n    egy_bins = np.exp(utils.split_bin_edges(np.log(egy_bins), npts))\n\n    etrue_bins = 10**np.linspace(1.0, 6.5, nbin * 5.5 + 1)\n    egy = 10**utils.edge_to_center(np.log10(egy_bins))\n    egy_width = utils.edge_to_width(egy_bins)\n    etrue = 10**utils.edge_to_center(np.log10(etrue_bins))\n    edisp = create_avg_edisp(skydir, ltc, event_class, event_types,\n                             egy, etrue, cth_bins)\n    edisp = edisp * egy_width[:, None, None]\n    edisp = sum_bins(edisp, 0, npts)\n    return edisp\n\n\ndef calc_counts(skydir, ltc, event_class, event_types,\n                egy_bins, cth_bins, fn, npts=1):\n    \"\"\"Calculate the expected counts vs. true energy and incidence angle\n    for a source with spectral parameterization ``fn``.\n\n    Parameters\n    ----------\n    skydir : `~astropy.coordinate.SkyCoord`\n\n    ltc : `~fermipy.irfs.LTCube`\n\n    egy_bins : `~numpy.ndarray`\n        Bin edges in observed energy in MeV.\n\n    cth_bins : `~numpy.ndarray`\n        Bin edges in cosine of the true incidence angle.\n\n    npts : int\n        Number of points by which to oversample each energy bin.\n    \"\"\"\n    #npts = int(np.ceil(32. / bins_per_dec(egy_bins)))\n    egy_bins = np.exp(utils.split_bin_edges(np.log(egy_bins), npts))\n    exp = calc_exp(skydir, ltc, event_class, event_types,\n                   egy_bins, cth_bins)\n    dnde = fn.dnde(egy_bins)\n    cnts = loglog_quad(egy_bins, exp * dnde[:, None], 0)\n    cnts = sum_bins(cnts, 0, npts)\n    return cnts\n\n\ndef calc_counts_edisp(skydir, ltc, event_class, event_types,\n                      egy_bins, cth_bins, fn, nbin=16, npts=1):\n    \"\"\"Calculate the expected counts vs. observed energy and true\n    incidence angle for a source with spectral parameterization ``fn``.\n\n    Parameters\n    ----------\n    skydir : `~astropy.coordinate.SkyCoord`\n\n    ltc : `~fermipy.irfs.LTCube`\n\n    egy_bins : `~numpy.ndarray`\n        Bin edges in observed energy in MeV.\n\n    cth_bins : `~numpy.ndarray`\n        Bin edges in cosine of the true incidence angle.\n\n    nbin : int    \n        Number of points per decade with which to sample true energy.\n        \n    npts : int\n        Number of points by which to oversample each reconstructed energy bin.\n\n    \"\"\"\n    #npts = int(np.ceil(32. / bins_per_dec(egy_bins)))\n\n    # Split energy bins\n    egy_bins = np.exp(utils.split_bin_edges(np.log(egy_bins), npts))\n    etrue_bins = 10**np.linspace(1.0, 6.5, nbin * 5.5 + 1)\n    drm = calc_drm(skydir, ltc, event_class, event_types,\n                   egy_bins, cth_bins, nbin=nbin)\n    cnts_etrue = calc_counts(skydir, ltc, event_class, event_types,\n                             etrue_bins, cth_bins, fn)\n\n    cnts = np.sum(cnts_etrue[None, :, :] * drm[:, :, :], axis=1)\n    cnts = sum_bins(cnts, 0, npts)\n    return cnts\n\n\ndef calc_wtd_exp(skydir, ltc, event_class, event_types,\n                 egy_bins, cth_bins, fn, nbin=16):\n    \"\"\"Calculate the effective exposure.\n\n    Parameters\n    ----------\n    skydir : `~astropy.coordinates.SkyCoord`\n\n    ltc : `~fermipy.irfs.LTCube`\n\n    nbin : int    \n        Number of points per decade with which to sample true energy.\n\n    \"\"\"\n    cnts = calc_counts_edisp(skydir, ltc, event_class, event_types,\n                             egy_bins, cth_bins, fn, nbin=nbin)\n    flux = fn.flux(egy_bins[:-1], egy_bins[1:])\n    return cnts / flux[:, None]\n\n\ndef plot_hpxmap(hpxmap, **kwargs):\n\n    import matplotlib as mpl\n    import matplotlib.pyplot as plt\n    from matplotlib.colors import PowerNorm, Normalize, LogNorm\n\n    zidx = kwargs.pop('zidx', None)\n\n    kwargs_imshow = {'norm': None,\n                     'vmin': None, 'vmax': None}\n\n    gamma = kwargs.get('gamma', 2.0)\n    zscale = kwargs.get('zscale', None)\n    cbar = kwargs.get('cbar', None)\n    cbar_label = kwargs.get('cbar_label', '')\n    title = kwargs.get('title', '')\n    levels = kwargs.get('levels', None)\n    rot = kwargs.get('rot', None)\n\n    kwargs_imshow['vmin'] = kwargs.get('vmin', None)\n    kwargs_imshow['vmax'] = kwargs.get('vmax', None)\n\n    cmap = mpl.cm.get_cmap(kwargs.get('cmap', 'jet'))\n    cmap.set_under('white')\n    kwargs_imshow['cmap'] = cmap\n\n    if zscale == 'pow':\n        vmed = np.median(hpxmap.counts)\n        vmax = max(hpxmap.counts)\n        vmin = min(1.1 * hpxmap.counts[hpxmap.counts > 0])\n        kwargs_imshow['norm'] = PowerNorm(gamma=gamma, clip=True)\n    elif zscale == 'log':\n        kwargs_imshow['norm'] = LogNorm()\n    else:\n        kwargs_imshow['norm'] = Normalize(clip=True)\n\n    from healpy import projaxes as PA\n\n    fig = plt.gcf()\n    if 'sub' in kwargs:\n        sub = kwargs['sub']\n        nrows, ncols, idx = sub / 100, (sub % 100) / 10, (sub % 10)\n        c, r = (idx - 1) % ncols, (idx - 1) / ncols\n        margins = (0.01, 0.0, 0.0, 0.02)\n        extent = (c * 1. / ncols + margins[0],\n                  1. - (r + 1) * 1. / nrows + margins[1],\n                  1. / ncols - margins[2] - margins[0],\n                  1. / nrows - margins[3] - margins[1])\n        extent = (extent[0] + margins[0],\n                  extent[1] + margins[1],\n                  extent[2] - margins[2] - margins[0],\n                  extent[3] - margins[3] - margins[1])\n    else:\n        extent = (0.02, 0.05, 0.96, 0.9)\n\n    ax = hp.projaxes.HpxMollweideAxes(fig, extent, coord=None, rot=rot,\n                                      format='%g', flipconv='astro')\n\n    ax.set_title(title)\n    fig.add_axes(ax)\n\n    if zidx is not None:\n        data = hpxmap.data[zidx]\n    elif hpxmap.data.ndim == 2:\n        data = np.sum(hpxmap.data, axis=0)\n    else:\n        data = hpxmap.data\n\n    img0 = ax.projmap(data, nest=hpxmap.hpx.nest, xsize=1600, coord='C',\n                      **kwargs_imshow)\n\n    if levels:\n        cs = ax.contour(img0, extent=ax.proj.get_extent(),\n                        levels=levels, colors=['k'],\n                        interpolation='nearest')\n\n    hp.visufunc.graticule(verbose=False, lw=0.5, color='k')\n\n    if cbar is not None:\n\n        im = ax.get_images()[0]\n        cb_kw = dict(orientation='vertical',\n                     shrink=.6, pad=0.05)\n        cb_kw.update(cbar)\n        cb = fig.colorbar(im, **cb_kw)  # ,format='%.3g')\n        cb.set_label(cbar_label)\n        #, ticks=[min, max])\n#            cb.ax.xaxis.set_label_text(cbar_label)\n", "meta": {"hexsha": "f41f17e699e225d58a3c6a529f84548935f58153", "size": 32592, "ext": "py", "lang": "Python", "max_stars_repo_path": "fermipy/irfs.py", "max_stars_repo_name": "damgreen/fermipy", "max_stars_repo_head_hexsha": "92b693a9272453bc6eb5c21e9bbac912408122fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fermipy/irfs.py", "max_issues_repo_name": "damgreen/fermipy", "max_issues_repo_head_hexsha": "92b693a9272453bc6eb5c21e9bbac912408122fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fermipy/irfs.py", "max_forks_repo_name": "damgreen/fermipy", "max_forks_repo_head_hexsha": "92b693a9272453bc6eb5c21e9bbac912408122fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8592375367, "max_line_length": 107, "alphanum_fraction": 0.5840083456, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 8976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.1884846601256271}}
{"text": "'''\nthis is not the original prox fitting, but a modified version just for post-processing\nour generated results. The input is the smplx body parameters, and the optimization \nis based on the scene sdf and the contact loss\n'''\n\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport pickle\nimport sys, os, glob\nimport pdb\nimport json\nimport argparse\nimport numpy as np\nimport open3d as o3d\n\nsys.path.append('/home/yzhang/workspaces/smpl-env-gen-3d-internal')\n\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn import init\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nfrom torch.autograd import Variable\n\n\nimport smplx\nfrom human_body_prior.tools.model_loader import load_vposer\nimport chamfer_pytorch.dist_chamfer as ext\n\nfrom cvae import BodyParamParser, GeometryTransformer\n\n\n\n\n\n\n\nclass FittingOP:\n    def __init__(self, fittingconfig, lossconfig):\n\n\n        for key, val in fittingconfig.items():\n            setattr(self, key, val)\n\n\n        for key, val in lossconfig.items():\n            setattr(self, key, val)\n\n\n        self.vposer, _ = load_vposer(self.vposer_ckpt_path, vp_model='snapshot')\n        self.body_mesh_model = smplx.create(self.human_model_path, model_type='smplx',\n                                       gender='neutral', ext='npz',\n                                       num_pca_comps=12,\n                                       create_global_orient=True,\n                                       create_body_pose=True,\n                                       create_betas=True,\n                                       create_left_hand_pose=True,\n                                       create_right_hand_pose=True,\n                                       create_expression=True,\n                                       create_jaw_pose=True,\n                                       create_leye_pose=True,\n                                       create_reye_pose=True,\n                                       create_transl=True,\n                                       batch_size=self.batch_size\n                                       )\n        self.vposer.to(self.device)\n        self.body_mesh_model.to(self.device)\n\n        self.xhr_rec = Variable(torch.randn(1,75).to(self.device), requires_grad=True)\n        self.optimizer = optim.Adam([self.xhr_rec], lr=self.init_lr_h)\n\n\n\n\n        ## read scene sdf\n        with open(self.scene_sdf_path+'.json') as f:\n                sdf_data = json.load(f)\n                grid_min = np.array(sdf_data['min'])\n                grid_max = np.array(sdf_data['max'])\n                grid_dim = sdf_data['dim']\n        sdf = np.load(self.scene_sdf_path + '_sdf.npy').reshape(grid_dim, grid_dim, grid_dim)\n\n        self.s_grid_min_batch = torch.tensor(grid_min, dtype=torch.float32, device=self.device).unsqueeze(0)\n        self.s_grid_max_batch = torch.tensor(grid_max, dtype=torch.float32, device=self.device).unsqueeze(0)\n        self.s_sdf_batch = torch.tensor(sdf, dtype=torch.float32, device=self.device).unsqueeze(0)\n\n\n        ## read scene vertices\n        scene_o3d = o3d.io.read_triangle_mesh(self.scene_verts_path)\n        scene_verts = np.asarray(scene_o3d.vertices)\n        self.s_verts_batch = torch.tensor(scene_verts, dtype=torch.float32, device=self.device).unsqueeze(0)\n\n\n\n\n\n    def cal_loss(self, xhr, cam_ext):\n        \n        ### reconstruction loss\n        loss_rec = self.weight_loss_rec*F.l1_loss(xhr, self.xhr_rec)\n        xh_rec = GeometryTransformer.convert_to_3D_rot(self.xhr_rec)\n\n        ### vposer loss\n        vposer_pose = xh_rec[:,16:48]\n        loss_vposer = self.weight_loss_vposer * torch.mean(vposer_pose**2)\n\n\n        ### contact loss\n        body_param_rec = BodyParamParser.body_params_encapsulate_batch(xh_rec)\n        joint_rot_batch = self.vposer.decode(body_param_rec['body_pose_vp'], \n                                           output_type='aa').view(self.batch_size, -1)\n \n        body_param_ = {}\n        for key in body_param_rec.keys():\n            if key in ['body_pose_vp']:\n                continue\n            else:\n                body_param_[key] = body_param_rec[key]\n\n        smplx_output = self.body_mesh_model(return_verts=True, \n                                              body_pose=joint_rot_batch,\n                                              **body_param_)\n        body_verts_batch = smplx_output.vertices #[b, 10475,3]\n        body_verts_batch = GeometryTransformer.verts_transform(body_verts_batch, cam_ext)\n\n        vid, fid = GeometryTransformer.get_contact_id(\n                                body_segments_folder=self.contact_id_folder,\n                                contact_body_parts=self.contact_part)\n        body_verts_contact_batch = body_verts_batch[:, vid, :]\n\n        dist_chamfer_contact = ext.chamferDist()\n        contact_dist, _ = dist_chamfer_contact(body_verts_contact_batch.contiguous(), \n                                                self.s_verts_batch.contiguous())\n\n        loss_contact = self.weight_contact * torch.mean(torch.sqrt(contact_dist+1e-4)/(torch.sqrt(contact_dist+1e-4)+1.0))  \n\n\n        ### sdf collision loss\n        s_grid_min_batch = self.s_grid_min_batch.unsqueeze(1)\n        s_grid_max_batch = self.s_grid_max_batch.unsqueeze(1)\n\n        norm_verts_batch = (body_verts_batch - s_grid_min_batch) / (s_grid_max_batch - s_grid_min_batch) *2 -1\n        n_verts = norm_verts_batch.shape[1]\n        body_sdf_batch = F.grid_sample(self.s_sdf_batch.unsqueeze(1), \n                                        norm_verts_batch[:,:,[2,1,0]].view(-1, n_verts,1,1,3),\n                                        padding_mode='border')\n\n\n        # if there are no penetrating vertices then set sdf_penetration_loss = 0\n        if body_sdf_batch.lt(0).sum().item() < 1:\n            loss_sdf_pene = torch.tensor(0.0, dtype=torch.float32, device=self.device)\n        else:\n            loss_sdf_pene = body_sdf_batch[body_sdf_batch < 0].abs().mean()\n\n        loss_collision = self.weight_collision*loss_sdf_pene\n\n\n        return loss_rec, loss_vposer, loss_contact, loss_collision\n\n\n\n\n    def fitting(self, input_data_file):\n\n\n        with open(input_data_file, 'rb') as f:\n            body_param_input = pickle.load(f)\n\n        xh, self.cam_ext, self.cam_int= BodyParamParser.body_params_parse_fitting(body_param_input)\n        xhr = GeometryTransformer.convert_to_6D_rot(xh)\n        self.xhr_rec.data = xhr.clone()\n\n        T_mat = np.eye(4)\n        T_mat[1,:] = np.array([0,-1,0,0])\n        T_mat[2,:] = np.array([0,0,-1,0])\n        T_mat = torch.tensor(T_mat, dtype=torch.float32, device=self.device)\n        T_mat = T_mat.unsqueeze(0)\n        trans = torch.matmul(self.cam_ext[:1],T_mat)\n        \n\n\n        for ii in range(self.num_iter):\n\n            self.optimizer.zero_grad()\n\n            loss_rec, loss_vposer, loss_contact, loss_collision = self.cal_loss(xhr, trans)\n            loss = loss_rec + loss_vposer + loss_contact + loss_collision\n            if self.verbose:\n                print('[INFO][fitting] iter={:d}, l_rec={:f}, l_vposer={:f}, l_contact={:f}, l_collision={:f}'.format(\n                                        ii, loss_rec.item(), loss_vposer.item(), \n                                        loss_contact.item(), loss_collision.item()) )\n\n            loss.backward(retain_graph=True)\n            self.optimizer.step()\n\n\n        print('[INFO][fitting] fitting finish, returning optimal value')\n\n\n        xh_rec =  GeometryTransformer.convert_to_3D_rot(self.xhr_rec)\n\n        return xh_rec\n\n\n\n    def save_result(self, xh_rec, output_data_file):\n\n        dirname = os.path.dirname(output_data_file)\n        \n        if not os.path.exists(dirname):\n            os.makedirs(dirname)\n\n        body_param_list = BodyParamParser.body_params_encapsulate(xh_rec)\n        print('[INFO] save results to: '+output_data_file)\n        for ii, body_param in enumerate(body_param_list):\n            # print(body_param['transl'])\n            # print(body_param['global_orient'])\n            # print()\n            body_param['cam_ext'] = self.cam_ext.detach().cpu().numpy()\n            body_param['cam_int'] = self.cam_int.detach().cpu().numpy()\n            outfile = open(output_data_file, 'wb')\n            pickle.dump(body_param, outfile)\n            outfile.close()\n\n\nif __name__=='__main__':\n\n\n    gen_path = sys.argv[1]\n    fit_path = sys.argv[2]\n\n    scene_test_list = ['17DRP5sb8fy-bedroom', '17DRP5sb8fy-familyroomlounge', \n                        '17DRP5sb8fy-livingroom', 'sKLMLpTHeUy-familyname_0_1', \n                        'X7HyMhZNoso-livingroom_0_16', 'zsNo4HB9uLZ-bedroom0_0', \n                        'zsNo4HB9uLZ-livingroom0_13']\n    \n    mp3dr_path = '/is/cluster/yzhang/mp3d-rooms'\n\n    for scenename in scene_test_list:\n\n        fittingconfig={\n            'scene_verts_path': os.path.join(mp3dr_path, scenename+'.ply'),\n            'scene_sdf_path': os.path.join(mp3dr_path, 'sdf/'+scenename),\n            'human_model_path': '/is/ps2/yzhang/body_models/VPoser',\n            'vposer_ckpt_path': '/is/ps2/yzhang/body_models/VPoser/vposer_v1_0',\n            'init_lr_h': 0.1,\n            'num_iter': 50,\n            'batch_size': 1, \n            'device': torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\"),\n            'contact_id_folder': '/is/cluster/work/yzhang/PROX/body_segments',\n            'contact_part': ['back','butt','L_Hand','R_Hand','L_Leg','R_Leg','thighs'],\n            'verbose': False\n        }\n\n        lossconfig={\n            'weight_loss_rec': 1,\n            'weight_loss_vposer':0.01,\n            'weight_contact': 0.1,\n            'weight_collision' : 0.5\n        }\n\n\n        fop = FittingOP(fittingconfig, lossconfig)\n\n\n\n        for ii in range(10000):\n            input_data_file = os.path.join(gen_path,scenename+'/body_gen_{:06d}.pkl'.format(ii))\n\n            if not os.path.exists(input_data_file):\n                continue\n\n            output_data_file = os.path.join(fit_path,scenename+'/body_gen_{:06d}.pkl'.format(ii))\n            if os.path.exists(output_data_file):\n                continue\n\n            \n            xh_rec = fop.fitting(input_data_file)\n\n            if xh_rec is None:\n                continue\n            fop.save_result(xh_rec, output_data_file)\n\n", "meta": {"hexsha": "4c227f6fce49ce619e4c4a61691bf0dce2b3c604", "size": 10299, "ext": "py", "lang": "Python", "max_stars_repo_path": "source/fitting_habitat.py", "max_stars_repo_name": "jiyeonkim127/PSI", "max_stars_repo_head_hexsha": "5c525d5304fb756c9314ea3e225bbb180e521b9a", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": 138, "max_stars_repo_stars_event_min_datetime": "2020-04-18T19:32:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:58:33.000Z", "max_issues_repo_path": "source/fitting_habitat.py", "max_issues_repo_name": "jiyeonkim127/PSI", "max_issues_repo_head_hexsha": "5c525d5304fb756c9314ea3e225bbb180e521b9a", "max_issues_repo_licenses": ["Xnet", "X11"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2020-04-21T18:24:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:25:11.000Z", "max_forks_repo_path": "source/fitting_habitat.py", "max_forks_repo_name": "jiyeonkim127/PSI", "max_forks_repo_head_hexsha": "5c525d5304fb756c9314ea3e225bbb180e521b9a", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2020-04-22T01:32:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T02:52:01.000Z", "avg_line_length": 35.5137931034, "max_line_length": 124, "alphanum_fraction": 0.5974366443, "include": true, "reason": "import numpy", "num_tokens": 2345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.18847904331976592}}
{"text": "class fpoutClass:\n  pass\n\ndef readout(outfile,atmfile,fpout):\n  import h5py\n  import numpy as np\n  with h5py.File(outfile, 'r') as h5f:\n     fpout.inputparams = dict(h5f['inputparams'].attrs)\n     fpout.atm = dict(h5f['atm'].attrs)\n     fpout.atm['zin'] = np.array(h5f['atm/zin'])\n     fpout.atm['tg'] = np.array(h5f['atm/tg'])\n     fpout.atm['bfield'] = np.array(h5f['atm/bfield'])\n     fpout.atm['dni'] = np.array(h5f['atm/dni'])\n     fpout.atm['dnn'] = np.array(h5f['atm/dnn'])\n     fpout.atm['mion'] = np.array(h5f['atm/mion'])\n     fpout.atm['Zion'] = np.array(h5f['atm/Zion'])\n     fpout.atm['Zn'] = np.array(h5f['atm/Zn'])\n     fpout.atm['Enion'] = np.array(h5f['atm/Enion'])\n     fpout.E = np.array(h5f['E'])\n     fpout.mu = np.array(h5f['mu'])\n     fpout.z = np.array(h5f['z'])\n     fpout.esvol = np.array(h5f['esvol'])\n     fpout.heatrate = np.array(h5f['heatrate'])\n     fpout.momrate =  np.array(h5f['momrate'])\n     fpout.f = np.array(h5f['f'])\n  makefpoutstr(fpout,atmfile)\n\ndef makefpoutstr(fpout,atmfile):\n  import numpy as np\n  import const as c\n  fpout.atmfile = atmfile\n  fpout.nE = fpout.inputparams['nE']\n  fpout.nmu = fpout.inputparams['nmu']\n  fpout.nz = fpout.inputparams['nz']\n  nE = fpout.nE\n  nmu = fpout.nmu\n  nz = fpout.nz\n  fpout.Em = .5*(fpout.E[1:]+fpout.E[0:nE])\n  mbeam = fpout.inputparams['mbeam']\n  if (fpout.inputparams['inc_relativity']):\n    fpout.gma = fpout.E/(mbeam/1e3) + 1e0\n    fpout.bta = np.sqrt(1e0 - pow(fpout.gma,-2))\n    fpout.gmam = fpout.Em/(mbeam/1e3) + 1e0\n    fpout.btam = np.sqrt(1e0 - pow(fpout.gmam,-2))\n  else:\n    fpout.gma = np.ones(nE+1)\n    fpout.bta = np.sqrt(2*fpout.E*1e3/mbeam)\n    fpout.gmam = np.ones(nE)\n    fpout.btam = np.sqrt(2*fpout.Em*1e3/mbeam)\n\n  fpout.theta = np.arccos(fpout.mu)\n  fpout.thetam = fpout.theta[0] if fpout.inputparams['oneD'] else .5*(fpout.theta[1:]+fpout.theta[0:nmu])\n  fpout.mum = np.cos(fpout.thetam)\n\n  fpout.zm = .5*(fpout.z[1:]+fpout.z[0:nz])\n  #Calculate useful fluxes\n  vz = c.clight *np.outer(fpout.mum, fpout.btam)\n  vx = c.clight * np.outer(np.sin(fpout.thetam), fpout.btam)\n  domega = fpout.esvol/(fpout.E[1:] - fpout.E[0:nE]) # solid angle part of esvol\n\n  fpout.eflux = np.einsum('ijk,jk,k',fpout.f,vz*fpout.esvol,fpout.Em)*1e3*c.ergperev # Energy flux in z direction (erg cm^-2 s^-1)\n  fpout.efluxx = np.einsum('ijk,jk,k',fpout.f,vx*fpout.esvol,fpout.Em)*1e3*c.ergperev # Energy flux in x direction (erg cm^-2 s^-1)\n  fpout.nflux = np.einsum('ijk,jk',fpout.f,vz*fpout.esvol)# number flux in z direction (particles cm^-2 s^-1)\n  fpout.flux = np.einsum('ijk,jk->ik',fpout.f,vz*domega) # number flux distribution in z direction (particles cm^-2 s^-1 keV^-1)\n  fpout.flx = np.einsum('ijk,jk,k->ik',fpout.f,domega,fpout.btam)*c.clight # number flux speed distribution. (particles cm^-2 s^-1 keV^-1)\n\n  if (abs(mbeam-c.me) < 1e3): #electron beam\n    import fpbrem\n    fpout.Eph = fpout.Em\n    fpout.brem = fpbrem.fpbrem(fpout.Em,fpout.flx,fpout.Eph,fpout.atm)\n    fpout.totbrem = np.einsum('ij,j',fpout.brem,np.diff(fpout.z))\n  else:\n  # Not electron beam so do not calculate bremsstrahlung\n    fpout.brem = 0e0\n    fpout.totbrem = 0e0\n    fpout.Eph = 0e0\n\ndef writefpout(fpout,outfile = 'out.h5'):\n  import h5py\n  with h5py.File(outfile,'w') as fle:\n    ipg = fle.create_group('inputparams')\n    ipg.attrs.update(fpout.inputparams)\n    atmattrs = {k:fpout.atm[k] for k in ('nIon','nNeutral') if k in fpout.atm}\n    atmg = fle.create_group('atm')\n    atmg.attrs.update(atmattrs)\n    atmg.create_dataset('zin',data=fpout.atm['zin']); atmg.create_dataset('tg',data=fpout.atm['tg']); atmg.create_dataset('bfield',data=fpout.atm['bfield'])\n    atmg.create_dataset('dni',data=fpout.atm['dni']); atmg.create_dataset('dnn',data=fpout.atm['dnn']); atmg.create_dataset('mion',data=fpout.atm['mion'])\n    atmg.create_dataset('Zion',data=fpout.atm['Zion']); atmg.create_dataset('Zn',data=fpout.atm['Zn']); atmg.create_dataset('Enion',data=fpout.atm['Enion'])\n    fle.create_dataset('E',data = fpout.E); fle.create_dataset('mu',data = fpout.mu); fle.create_dataset('z',data = fpout.z)\n    fle.create_dataset('esvol',data = fpout.esvol); fle.create_dataset('heatrate',data = fpout.heatrate); fle.create_dataset('momrate',data = fpout.momrate)\n    fle.create_dataset('f',data = fpout.f)\n\ndef writeparam(fle,outfile,nE,nmu,atmfile,inc_relativity,inc_cc, inc_synchro, inc_magmirror, inc_rc, oneD, reflecttop, reflectbottom, maxiter, tolres, toldiff,\n               implicit_theta, mbeam, Zbeam, Ecut, dlt, Eflux, patype, pasigma, resist_fact, Emin, Emax, restart):\n\n  truestr = \".true.\"\n  falsestr = \".false.\"\n\n  with open(fle,'w') as pfle:\n    pfle.write(\"&control\\n\")\n    pfle.write(\"nE = \"+str(nE) + \",\\n\")\n    pfle.write(\"nmu = \"+str(nmu) + \",\\n\")\n    pfle.write(\"Emin = \"+  \"%.17e\" % Emin + \",\\n\")\n    pfle.write(\"Emax = \"+ \"%.17e\" % Emax + \",\\n\")\n    pfle.write(\"inc_relativity = \" + (truestr if inc_relativity else falsestr)  + \",\\n\")\n    pfle.write(\"inc_CC = \" + (truestr if inc_cc else falsestr) + \",\\n\")\n    pfle.write(\"inc_synchro = \" + (truestr if inc_synchro else falsestr) + \",\\n\")\n    pfle.write(\"inc_magmirror = \" + (truestr if inc_magmirror else falsestr) + \",\\n\")\n    pfle.write(\"inc_RC = \"+ (truestr if inc_rc else falsestr) + \",\\n\")\n    pfle.write(\"oneD = \"+ (truestr if oneD else falsestr) + \",\\n\")\n    pfle.write(\"reflecttop = \" +  (truestr if reflecttop else falsestr) + \",\\n\")\n    pfle.write(\"reflectbottom = \"+ (truestr if reflectbottom else falsestr) + \",\\n\")\n    pfle.write(\"maxiter = \"+str(maxiter)+\",\\n\")\n    pfle.write(\"writeoutput = .true.,\\n\")\n    pfle.write(\"tolres = \"+ \"%.4e\" % tolres +\",\\n\")\n    pfle.write(\"toldiff = \" +\"%.4e\" % toldiff +\",\\n\")\n    pfle.write(\"implicit_theta = \"+\"%.17e\" % implicit_theta+\",\\n\")\n    pfle.write(\"atmfile = '\"+atmfile+\"',\\n\")\n    pfle.write(\"outfile = '\"+outfile+\"',\\n\")\n    pfle.write(\"mbeam =  \"+ \"%.17e\" % mbeam+\",\\n\")\n    pfle.write(\"Zbeam = \"+\"%.17e\" % Zbeam+\",\\n\")\n    pfle.write(\"Ecut = \"+\"%.17e\" % Ecut +\",\\n\")\n    pfle.write(\"dlt = \"+\"%.17e\" % dlt+\",\\n\")\n    pfle.write(\"eflux= \"+\"%.17e\" % Eflux+\",\\n\")\n    pfle.write(\"patype = \"+str(patype)+\",\\n\")\n    pfle.write(\"pasigma = \"+\"%.17e\" % pasigma+\",\\n\")\n    pfle.write(\"resist_fact = \"+\"%.17e\" % resist_fact +\",\\n\")\n    pfle.write(\"restart = \"+ (truestr if restart else falsestr) +\"\\n\")\n    pfle.write(\"/\\n\")\n\ndef solver(nE = 100, nmu=60, atmfile='atm.dat', inc_relativity = True, inc_cc = True, inc_synchro=True, inc_magmirror = False, inc_rc = True,\n           oneD = False, reflecttop = False, reflectbottom = False, maxiter=100, tolres=1e-3, toldiff = 1e-4, implicit_theta = 1.0, mbeam = 0e0, Zbeam=-1.0,\n           Ecut=20.0, dlt=5.0, Eflux=1e11, patype=2, pasigma=.05, resist_fact=1e0, Emin = 1e0, Emax = 0, restart= False, writeout = True, outfile = '',\n           nthreads = 0, mpiexec = 'mpiexec'):\n   import inspect\n   import os\n   import numpy as np\n   import const as c\n   import subprocess\n   from random import random\n\n   if (nthreads == 0):\n     nthreads = os.cpu_count()\n   if (mbeam == 0e0):\n     mbeam = c.me\n   if (Emax == 0):\n     Emax = 3e3*Ecut\n\n   iid = int(random()*1e6) # pick some random label to keep track of which param.cnt and out.dat go together\n   paramfile = 'param.'+str(iid)+'.cnt'\n   if (outfile == ''):\n     outfile = 'out.'+str(iid)+'.h5'\n     keepout = False\n   else:\n     outfile = str(outfile)\n     keepout = True\n\n   if (restart != False):\n     if (isinstance(restart,fpoutClass)):\n#       writefpout(restart,outfile=outfile)\n       dorestart = True\n       #Setup input parameters using values from restart\n       nE = restart.inputparams['nE']; nmu = restart.inputparams['nmu']; atmfile = restart.atmfile; inc_relativity = restart.inputparams['inc_relativity']\n       inc_CC = restart.inputparams['inc_CC']; inc_synchro = restart.inputparams['inc_synchro']; inc_magmirror = restart.inputparams['inc_magmirror']\n       oneD = restart.inputparams['oneD']; reflecttop = restart.inputparams['reflecttop']; reflectbottom = restart.inputparams['reflectbottom']\n       mbeam = restart.inputparams['mbeam']; Zbeam = restart.inputparams['zbeam']; Ecut = restart.inputparams['Ecut']; dlt = restart.inputparams['dlt']\n       Eflux = restart.inputparams['eflux']; patype = restart.inputparams['patype']; pasigma = restart.inputparams['pasigma']\n       resist_fact = restart.inputparams['resist_fact']; Emin = restart.inputparams['Emin']; Emax = restart.inputparams['Emax']\n       if (maxiter is solver.__defaults__[0]): maxiter = restart.inputparams['maxiter']\n       if (tolres == 1e-3): tolres = restart.inputparams['tolres']\n       if (toldiff == 1e-4): todiff = restart.inputparams['toldiff']\n       if (implicit_theta == 1.0): implicit_theta = restart.inputparams['implicit_theta']\n       writefpout(restart,outfile)\n     else:\n       print('Cannot restart from ' + str(type(restart)))\n       return\n   else:\n     dorestart = False\n\n   import readatm\n   atm = readatm.readatm(fle = atmfile)\n   if (atm == None): return\n\n   writeparam(paramfile,outfile,nE,nmu,atmfile,inc_relativity,inc_cc, inc_synchro, inc_magmirror, inc_rc, oneD, reflecttop, reflectbottom, maxiter, tolres, toldiff,\n              implicit_theta, mbeam, Zbeam, Ecut, dlt, Eflux, patype, pasigma, resist_fact, Emin, Emax, dorestart)\n\n   nz = atm['zin'].size\n   nthreads = min(nthreads, int(nz/5))\n\n   thisdir = os.path.dirname(inspect.getfile(writeparam))\n   mpiexec = str(mpiexec)\n   try:\n     out = subprocess.run([mpiexec,'-n',str(nthreads),thisdir+'/fp',paramfile],stderr=subprocess.STDOUT)\n   except OSError as err:\n     print(\"OS error: {0}\".format(err))\n     if (os.path.exists(paramfile)): os.remove(paramfile)\n     if (os.path.exists(outfile) and not keepout): os.remove(outfile)\n     return None\n   fpout = fpoutClass()\n   readout(outfile,atmfile,fpout)\n   os.remove(paramfile)\n   if (not keepout): os.remove(outfile)\n   return fpout\n\n", "meta": {"hexsha": "7930d624490a62a33f852dd596916be393bf0413", "size": 9862, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/fp.py", "max_stars_repo_name": "solarFP/FP", "max_stars_repo_head_hexsha": "a7c7f318ce162e2ab54d37f2f2231efd051e3280", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-09-30T18:51:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-09T20:09:06.000Z", "max_issues_repo_path": "python/fp.py", "max_issues_repo_name": "solarFP/FP", "max_issues_repo_head_hexsha": "a7c7f318ce162e2ab54d37f2f2231efd051e3280", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/fp.py", "max_forks_repo_name": "solarFP/FP", "max_forks_repo_head_hexsha": "a7c7f318ce162e2ab54d37f2f2231efd051e3280", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.1073170732, "max_line_length": 164, "alphanum_fraction": 0.6483471912, "include": true, "reason": "import numpy", "num_tokens": 3389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.32423540551084407, "lm_q1q2_score": 0.1884790433197659}}
{"text": "import sys\nimport sysconfig\nimport warnings\nimport numpy as nu\nimport ctypes\nimport ctypes.util\nfrom numpy.ctypeslib import ndpointer\nimport os\nfrom galpy import potential\nfrom galpy.util import galpyWarning\nfrom galpy.orbit_src.integratePlanarOrbit import _parse_integrator, _parse_tol\n#Find and load the library\n_lib= None\nouterr= None\nPY3= sys.version > '3'\nif PY3: #pragma: no cover\n    _ext_suffix= sysconfig.get_config_var('EXT_SUFFIX')\nelse:\n    _ext_suffix= '.so'\nfor path in sys.path:\n    try:\n        _lib = ctypes.CDLL(os.path.join(path,'galpy_integrate_c%s' % _ext_suffix))\n    except OSError as e:\n        if os.path.exists(os.path.join(path,'galpy_integrate_c%s' % _ext_suffix)): #pragma: no cover\n            outerr= e\n        _lib = None\n    else:\n        break\nif _lib is None: #pragma: no cover\n    if not outerr is None:\n        warnings.warn(\"integrateFullOrbit_c extension module not loaded, because of error '%s' \" % outerr,\n                      galpyWarning)\n    else:\n        warnings.warn(\"integrateFullOrbit_c extension module not loaded, because galpy_integrate_c%s image was not found\" % _ext_suffix,\n                      galpyWarning)\n    _ext_loaded= False\nelse:\n    _ext_loaded= True\n\ndef _parse_pot(pot,potforactions=False):\n    \"\"\"Parse the potential so it can be fed to C\"\"\"\n    #Figure out what's in pot\n    if not isinstance(pot,list):\n        pot= [pot]\n    #Initialize everything\n    pot_type= []\n    pot_args= []\n    npot= len(pot)\n    for p in pot:\n        if isinstance(p,potential.LogarithmicHaloPotential):\n            pot_type.append(0)\n            pot_args.extend([p._amp,p._q,p._core2])\n        elif isinstance(p,potential.MiyamotoNagaiPotential):\n            pot_type.append(5)\n            pot_args.extend([p._amp,p._a,p._b])\n        elif isinstance(p,potential.PowerSphericalPotential):\n            pot_type.append(7)\n            pot_args.extend([p._amp,p.alpha])\n        elif isinstance(p,potential.HernquistPotential):\n            pot_type.append(8)\n            pot_args.extend([p._amp,p.a])\n        elif isinstance(p,potential.FlattenedNFWPotential):\n            pot_type.append(91)\n            pot_args.extend([p._amp,p.a,p.q])\n        elif isinstance(p,potential.NFWPotential):\n            pot_type.append(9)\n            pot_args.extend([p._amp,p.a])\n        elif isinstance(p,potential.JaffePotential):\n            pot_type.append(10)\n            pot_args.extend([p._amp,p.a])\n        elif isinstance(p,potential.DoubleExponentialDiskPotential):\n            pot_type.append(11)\n            pot_args.extend([p._amp,p._alpha,p._beta,p._kmaxFac,\n                             p._nzeros,p._glorder])\n            pot_args.extend([p._glx[ii] for ii in range(p._glorder)])\n            pot_args.extend([p._glw[ii] for ii in range(p._glorder)])\n            pot_args.extend([p._j0zeros[ii] for ii in range(p._nzeros+1)])\n            pot_args.extend([p._dj0zeros[ii] for ii in range(p._nzeros+1)])\n            pot_args.extend([p._j1zeros[ii] for ii in range(p._nzeros+1)])\n            pot_args.extend([p._dj1zeros[ii] for ii in range(p._nzeros+1)])\n            pot_args.extend([p._kp._amp,p._kp.alpha])\n        elif isinstance(p,potential.FlattenedPowerPotential):\n            pot_type.append(12)\n            pot_args.extend([p._amp,p.alpha,p.q2,p.core2])\n        elif isinstance(p,potential.interpRZPotential):\n            pot_type.append(13)\n            pot_args.extend([len(p._rgrid),len(p._zgrid)])\n            if p._logR:\n                pot_args.extend([p._logrgrid[ii] for ii in range(len(p._rgrid))])\n            else:\n                pot_args.extend([p._rgrid[ii] for ii in range(len(p._rgrid))])\n            pot_args.extend([p._zgrid[ii] for ii in range(len(p._zgrid))])\n            if potforactions:\n                pot_args.extend([x for x in p._potGrid_splinecoeffs.flatten(order='C')])\n            else:\n                pot_args.extend([x for x in p._rforceGrid_splinecoeffs.flatten(order='C')])\n                pot_args.extend([x for x in p._zforceGrid_splinecoeffs.flatten(order='C')])\n            pot_args.extend([p._amp,int(p._logR)])\n        elif isinstance(p,potential.IsochronePotential):\n            pot_type.append(14)\n            pot_args.extend([p._amp,p.b])\n        elif isinstance(p,potential.PowerSphericalPotentialwCutoff):\n            pot_type.append(15)\n            pot_args.extend([p._amp,p.alpha,p.rc])\n        elif isinstance(p,potential.MN3ExponentialDiskPotential):\n            # Three Miyamoto-Nagai disks\n            npot+= 2\n            pot_type.extend([5,5,5])\n            pot_args.extend([p._amp*p._mn3[0]._amp,\n                             p._mn3[0]._a,p._mn3[0]._b,\n                             p._amp*p._mn3[1]._amp,\n                             p._mn3[1]._a,p._mn3[1]._b,\n                             p._amp*p._mn3[2]._amp,\n                             p._mn3[2]._a,p._mn3[2]._b])\n        elif isinstance(p,potential.KuzminKutuzovStaeckelPotential):\n            pot_type.append(16)\n            pot_args.extend([p._amp,p._ac,p._Delta])\n        elif isinstance(p,potential.PlummerPotential):\n            pot_type.append(17)\n            pot_args.extend([p._amp,p._b])\n        elif isinstance(p,potential.PseudoIsothermalPotential):\n            pot_type.append(18)\n            pot_args.extend([p._amp,p._a])\n    pot_type= nu.array(pot_type,dtype=nu.int32,order='C')\n    pot_args= nu.array(pot_args,dtype=nu.float64,order='C')\n    return (npot,pot_type,pot_args)\n\ndef integrateFullOrbit_c(pot,yo,t,int_method,rtol=None,atol=None,dt=None):\n    \"\"\"\n    NAME:\n       integrateFullOrbit_c\n    PURPOSE:\n       C integrate an ode for a FullOrbit\n    INPUT:\n       pot - Potential or list of such instances\n       yo - initial condition [q,p]\n       t - set of times at which one wants the result\n       int_method= 'leapfrog_c', 'rk4_c', 'rk6_c', 'symplec4_c'\n       rtol, atol\n       dt= (None) force integrator to use this stepsize (default is to automatically determine one))\n    OUTPUT:\n       (y,err)\n       y : array, shape (len(y0), len(t))\n       Array containing the value of y for each desired time in t, \\\n       with the initial value y0 in the first row.\n       err: error message, if not zero: 1 means maximum step reduction happened for adaptive integrators\n    HISTORY:\n       2011-11-13 - Written - Bovy (IAS)\n    \"\"\"\n    rtol, atol= _parse_tol(rtol,atol)\n    npot, pot_type, pot_args= _parse_pot(pot)\n    int_method_c= _parse_integrator(int_method)\n    if dt is None: \n        dt= -9999.99\n\n    #Set up result array\n    result= nu.empty((len(t),6))\n    err= ctypes.c_int(0)\n\n    #Set up the C code\n    ndarrayFlags= ('C_CONTIGUOUS','WRITEABLE')\n    integrationFunc= _lib.integrateFullOrbit\n    integrationFunc.argtypes= [ndpointer(dtype=nu.float64,flags=ndarrayFlags),\n                               ctypes.c_int,                             \n                               ndpointer(dtype=nu.float64,flags=ndarrayFlags),\n                               ctypes.c_int,\n                               ndpointer(dtype=nu.int32,flags=ndarrayFlags),\n                               ndpointer(dtype=nu.float64,flags=ndarrayFlags),\n                               ctypes.c_double,\n                               ctypes.c_double,\n                               ctypes.c_double,\n                               ndpointer(dtype=nu.float64,flags=ndarrayFlags),\n                               ctypes.POINTER(ctypes.c_int),\n                               ctypes.c_int]\n\n    #Array requirements, first store old order\n    f_cont= [yo.flags['F_CONTIGUOUS'],\n             t.flags['F_CONTIGUOUS']]\n    yo= nu.require(yo,dtype=nu.float64,requirements=['C','W'])\n    t= nu.require(t,dtype=nu.float64,requirements=['C','W'])\n    result= nu.require(result,dtype=nu.float64,requirements=['C','W'])\n\n    #Run the C code\n    integrationFunc(yo,\n                    ctypes.c_int(len(t)),\n                    t,\n                    ctypes.c_int(npot),\n                    pot_type,\n                    pot_args,\n                    ctypes.c_double(dt),\n                    ctypes.c_double(rtol),ctypes.c_double(atol),\n                    result,\n                    ctypes.byref(err),\n                    ctypes.c_int(int_method_c))\n\n    #Reset input arrays\n    if f_cont[0]: yo= nu.asfortranarray(yo)\n    if f_cont[1]: t= nu.asfortranarray(t)\n\n    return (result,err.value)\n\ndef integrateFullOrbit_dxdv_c(pot,yo,dyo,t,int_method,rtol=None,atol=None): #pragma: no cover because not included in v1, uncover when included\n    \"\"\"\n    NAME:\n       integrateFullOrbit_dxdv_c\n    PURPOSE:\n       C integrate an ode for a planarOrbit+phase space volume dxdv\n    INPUT:\n       pot - Potential or list of such instances\n       yo - initial condition [q,p]\n       dyo - initial condition [dq,dp]\n       t - set of times at which one wants the result\n       int_method= 'leapfrog_c', 'rk4_c', 'rk6_c', 'symplec4_c'\n       rtol, atol\n    OUTPUT:\n       (y,err)\n       y : array, shape (len(y0), len(t))\n       Array containing the value of y for each desired time in t, \\\n       with the initial value y0 in the first row.\n       err: error message if not zero, 1: maximum step reduction happened for adaptive integrators\n    HISTORY:\n       2011-11-13 - Written - Bovy (IAS)\n    \"\"\"\n    rtol, atol= _parse_tol(rtol,atol)\n    npot, pot_type, pot_args= _parse_pot(pot)\n    int_method_c= _parse_integrator(int_method)\n    yo= nu.concatenate((yo,dyo))\n\n    #Set up result array\n    result= nu.empty((len(t),12))\n    err= ctypes.c_int(0)\n\n    #Set up the C code\n    ndarrayFlags= ('C_CONTIGUOUS','WRITEABLE')\n    integrationFunc= _lib.integrateFullOrbit_dxdv\n    integrationFunc.argtypes= [ndpointer(dtype=nu.float64,flags=ndarrayFlags),\n                               ctypes.c_int,                             \n                               ndpointer(dtype=nu.float64,flags=ndarrayFlags),\n                               ctypes.c_int,\n                               ndpointer(dtype=nu.int32,flags=ndarrayFlags),\n                               ndpointer(dtype=nu.float64,flags=ndarrayFlags),\n                               ctypes.c_double,\n                               ctypes.c_double,\n                               ndpointer(dtype=nu.float64,flags=ndarrayFlags),\n                               ctypes.POINTER(ctypes.c_int),\n                               ctypes.c_int]\n\n    #Array requirements, first store old order\n    f_cont= [yo.flags['F_CONTIGUOUS'],\n             t.flags['F_CONTIGUOUS']]\n    yo= nu.require(yo,dtype=nu.float64,requirements=['C','W'])\n    t= nu.require(t,dtype=nu.float64,requirements=['C','W'])\n    result= nu.require(result,dtype=nu.float64,requirements=['C','W'])\n\n    #Run the C code\n    integrationFunc(yo,\n                    ctypes.c_int(len(t)),\n                    t,\n                    ctypes.c_int(npot),\n                    pot_type,\n                    pot_args,\n                    ctypes.c_double(rtol),ctypes.c_double(atol),\n                    result,\n                    ctypes.byref(err),\n                    ctypes.c_int(int_method_c))\n\n    #Reset input arrays\n    if f_cont[0]: yo= nu.asfortranarray(yo)\n    if f_cont[1]: t= nu.asfortranarray(t)\n\n    return (result,err.value)\n", "meta": {"hexsha": "f7d1d5b98ba1fbf3489b7cbc0a87f0dc935b5a7b", "size": 11176, "ext": "py", "lang": "Python", "max_stars_repo_path": "galpy/orbit_src/integrateFullOrbit.py", "max_stars_repo_name": "fardal/galpy", "max_stars_repo_head_hexsha": "93a1b6fc8d138899922127086cc66184919c8cba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "galpy/orbit_src/integrateFullOrbit.py", "max_issues_repo_name": "fardal/galpy", "max_issues_repo_head_hexsha": "93a1b6fc8d138899922127086cc66184919c8cba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "galpy/orbit_src/integrateFullOrbit.py", "max_forks_repo_name": "fardal/galpy", "max_forks_repo_head_hexsha": "93a1b6fc8d138899922127086cc66184919c8cba", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0882352941, "max_line_length": 143, "alphanum_fraction": 0.5841088046, "include": true, "reason": "import numpy,from numpy", "num_tokens": 2805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.35220179564702847, "lm_q1q2_score": 0.18846262741019587}}
{"text": "# Copyright (c) 2021 Horizon Robotics. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom enum import Enum\nimport functools\nimport numpy as np\nfrom typing import Callable\n\nimport torch\nimport torch.nn as nn\nimport torch.distributions as td\n\nimport alf\nfrom alf.algorithms.config import TrainerConfig\nfrom alf.algorithms.off_policy_algorithm import OffPolicyAlgorithm\nfrom alf.algorithms.sac_algorithm import _set_target_entropy\nfrom alf.data_structures import LossInfo, namedtuple, TimeStep\nfrom alf.data_structures import AlgStep, StepType\nfrom alf.nest import nest\nimport alf.nest.utils as nest_utils\nfrom alf.networks import ActorDistributionNetwork, CriticNetwork\nfrom alf.networks.preprocessors import EmbeddingPreprocessor\nfrom alf.tensor_specs import TensorSpec, BoundedTensorSpec\nfrom alf.utils import common, dist_utils, losses, math_ops, tensor_utils\nfrom alf.utils.conditional_ops import conditional_update\nfrom alf.utils.summary_utils import safe_mean_hist_summary\n\nTau = namedtuple(\n    \"Tau\",\n    [\n        \"a\",  # The current action value\n        \"v\",  # The current first derivative of action (not used by action repetition)\n        \"u\"  # The current second derivative of action (not used by action repetition)\n    ],\n    default_value=())\n\nTaacState = namedtuple(\"TaacState\", [\"tau\", \"repeats\"], default_value=())\n\nTaacCriticInfo = namedtuple(\n    \"TaacCriticInfo\", [\"critics\", \"target_critic\", \"value_loss\"],\n    default_value=())\n\nTaacActorInfo = namedtuple(\n    \"TaacActorInfo\",\n    [\"actor_loss\", \"b1_a_entropy\", \"beta_entropy\", \"adv\", \"value_loss\"],\n    default_value=())\n\nTaacInfo = namedtuple(\n    \"TaacInfo\", [\n        \"reward\", \"step_type\", \"tau\", \"prev_tau\", \"discount\",\n        \"action_distribution\", \"rollout_b\", \"b\", \"actor\", \"critic\", \"alpha\",\n        \"repeats\"\n    ],\n    default_value=())\n\nTaacLossInfo = namedtuple('TaacLossInfo', ('actor', 'critic', 'alpha'))\n\nDistributions = namedtuple(\"Distributions\", [\"beta_dist\", \"b1_a_dist\"])\n\nActPredOutput = namedtuple(\n    \"ActPredOutput\", [\"dists\", \"b\", \"actor_a\", \"taus\", \"q_values2\"],\n    default_value=())\n\nMode = Enum('AlgorithmMode', ('predict', 'rollout', 'train'))\n\n\ndef _discounted_return(rewards, values, is_lasts, discounts):\n    \"\"\"Computes discounted return for the first T-1 steps.\n\n    Same with ``tf_agents.utils.value_ops``, this function returns accumulated\n    discounted reward for steps that are StepType.LAST.\n\n    Args:\n        rewards (Tensor): shape is ``[T,B]`` (or ``[T]``) representing rewards.\n        values (Tensor): shape is ``[T,B]`` (or ``[T]``) representing values.\n        is_lasts (Tensor): shape is ``[T,B]`` (or ``[T]``) representing last steps.\n        discounts (Tensor): shape is ``[T,B]`` (or ``[T]``) representing discounts.\n\n    Returns:\n        Tensor: A tensor with shape ``[T-1,B]`` (or ``[T-1]``) representing the\n        discounted returns.\n    \"\"\"\n    assert values.shape[0] >= 2, (\"The sequence length needs to be \"\n                                  \"at least 2. Got {s}\".format(\n                                      s=values.shape[0]))\n\n    is_lasts = is_lasts.to(dtype=torch.float32)\n    is_lasts = common.expand_dims_as(is_lasts, values)\n    discounts = common.expand_dims_as(discounts, values)\n\n    rets = torch.zeros_like(values)\n    rets[-1] = values[-1]\n    acc_values = rets.clone()\n\n    with torch.no_grad():\n        for t in reversed(range(rewards.shape[0] - 1)):\n            rets[t] = acc_values[t + 1] * discounts[t + 1] + rewards[t + 1]\n            acc_values[t] = is_lasts[t] * values[t] + (\n                1 - is_lasts[t]) * rets[t]\n\n    rets = rets[:-1]\n    return rets.detach()\n\n\n@alf.configurable\nclass TAACTDLoss(nn.Module):\n    r\"\"\"This TD loss implements the compare-through multi-step Q operator\n    :math:`\\mathcal{T}^{\\pi^{\\text{ta}}}` proposed in the TAAC paper. For a sampled\n    trajectory, it compares the beta action :math:`\\tilde{b}_n` sampled from the\n    current policy with the historical rollout beta action :math:`b_n` step by step,\n    and uses the minimum :math:`n` that has :math:`\\tilde{b}_n\\lor b_n=1` as the\n    target step for boostrapping.\n    \"\"\"\n\n    def __init__(self,\n                 gamma=0.99,\n                 td_error_loss_fn=losses.element_wise_squared_loss,\n                 debug_summaries=False,\n                 name=\"TAACTDLoss\"):\n        \"\"\"\n        Args:\n            gamma (float|list[float]): A discount factor for future rewards. For\n                multi-dim reward, this can also be a list of discounts, each\n                discount applies to a reward dim.\n            td_errors_loss_fn (Callable): A function for computing the TD errors\n                loss. This function takes as input the target and the estimated\n                Q values and returns the loss for each element of the batch.\n            debug_summaries (bool): True if debug summaries should be created.\n            name (str): The name of this loss.\n        \"\"\"\n        super().__init__()\n        self._name = name\n        self._gamma = torch.tensor(gamma)\n        self._debug_summaries = debug_summaries\n        self._td_error_loss_fn = td_error_loss_fn\n\n    @property\n    def gamma(self):\n        \"\"\"Return the :math:`\\gamma` value for discounting future rewards.\n\n        Returns:\n            Tensor: a rank-0 or rank-1 (multi-dim reward) floating tensor.\n        \"\"\"\n        return self._gamma.clone()\n\n    def forward(self, info, value, target_value):\n        r\"\"\"Calculate the TD loss. The first dimension of all the tensors is the\n        time dimension and the second dimesion is the batch dimension.\n\n        Args:\n            info (TaacInfo): TaacInfo collected from train_step().\n            value (torch.Tensor): the tensor for the value at each time\n                step. The loss is between this and the calculated return.\n            target_value (torch.Tensor): the tensor for the value at each time\n                step. This is used to calculate return.\n\n        Returns:\n            LossInfo: TD loss with the ``extra`` field same as the loss.\n        \"\"\"\n        train_b = info.b\n        if info.reward.ndim == 3:\n            # [T, B, D] or [T, B, 1]\n            discounts = info.discount.unsqueeze(-1) * self._gamma\n        else:\n            # [T, B]\n            discounts = info.discount * self._gamma\n\n        rollout_b = info.rollout_b\n        # td return till the first action switching\n        b = (rollout_b | train_b).to(torch.bool)\n        # b at step 0 doesn't affect the bootstrapping of any step\n        b[0, :] = False\n\n        # combine is_last and b\n        is_lasts = (info.step_type == StepType.LAST)\n        is_lasts |= b\n\n        returns = _discounted_return(\n            rewards=info.reward,\n            values=target_value,\n            is_lasts=is_lasts,\n            discounts=discounts)\n\n        value = value[:-1]\n        loss = self._td_error_loss_fn(returns.detach(), value)\n        loss = tensor_utils.tensor_extend_zero(loss)\n\n        if loss.ndim == 3:\n            # Multidimensional reward. Average over the critic loss for all\n            # dimensions.\n            loss = loss.mean(dim=-1)\n\n        if self._debug_summaries and alf.summary.should_record_summaries():\n            mask = info.step_type[:-1] != StepType.LAST\n            with alf.summary.scope(self._name):\n\n                def _summarize(v, r, td, suffix):\n                    alf.summary.scalar(\n                        \"explained_variance_of_return_by_value\" + suffix,\n                        tensor_utils.explained_variance(v, r, mask))\n                    safe_mean_hist_summary('values' + suffix, v, mask)\n                    safe_mean_hist_summary('returns' + suffix, r, mask)\n                    safe_mean_hist_summary(\"td_error\" + suffix, td, mask)\n\n                td = returns - value\n                if value.ndim == 2:\n                    _summarize(value, returns, td, '')\n                else:\n                    for i in range(value.shape[-1]):\n                        suffix = '/' + str(i)\n                        _summarize(value[..., i], returns[..., i], td[..., i],\n                                   suffix)\n\n        return LossInfo(loss=loss, extra=loss)\n\n\n@alf.configurable\nclass TaacAlgorithmBase(OffPolicyAlgorithm):\n    r\"\"\"Temporally abstract actor-critic algorithm.\n\n    In a nutsell, for inference TAAC adds a second stage that chooses between a\n    candidate trajectory :math:`\\hat{\\tau}` output by an SAC actor and the previous\n    trajectory :math:`\\tau^-`. For policy evaluation, TAAC uses a compare-through Q\n    operator for TD backup by re-using state-action sequences that have shared\n    actions between rollout and training. For policy improvement, the\n    new actor gradient is approximated by multiplying a scaling factor to the\n    :math:`\\frac{\\partial Q}{\\partial a}` term in the original SAC’s actor\n    gradient, where the scaling factor is the optimal probability of choosing\n    the :math:`\\hat{\\tau}` in the second stage.\n\n    Different sub-algorithms implement different forms of the 'trajectory' concept,\n    for example, it can be a constant function representing the same action, or\n    a quadratic function.\n    \"\"\"\n\n    def __init__(self,\n                 observation_spec,\n                 action_spec: BoundedTensorSpec,\n                 reward_spec=TensorSpec(()),\n                 actor_network_cls=ActorDistributionNetwork,\n                 critic_network_cls=CriticNetwork,\n                 reward_weights=None,\n                 num_critic_replicas=2,\n                 epsilon_greedy=None,\n                 env=None,\n                 config: TrainerConfig = None,\n                 target_update_tau=0.05,\n                 target_update_period=1,\n                 critic_loss_ctor=None,\n                 actor_optimizer=None,\n                 critic_optimizer=None,\n                 alpha_optimizer=None,\n                 debug_summaries=False,\n                 randomize_first_state_tau=False,\n                 b1_advantage_clipping=None,\n                 max_repeat_steps=None,\n                 target_entropy=None,\n                 name=\"TaacAlgorithmBase\"):\n        r\"\"\"\n        Args:\n            observation_spec (nested TensorSpec): representing the observations.\n            action_spec (BoundedTensorSpec): representing the continuous action.\n            reward_spec (TensorSpec): a rank-1 or rank-0 tensor spec representing\n                the reward(s).\n            actor_network_cls (Callable): is used to construct the actor network.\n                The constructed actor network will be called to sample continuous\n                actions.\n            critic_network_cls (Callable): is used to construct critic network.\n                for estimating ``Q(s,a)`` given that the action is continuous.\n            reward_weights (None|list[float]): this is only used when the reward is\n                multidimensional. In that case, the weighted sum of the q values\n                is used for training the actor if reward_weights is not None.\n                Otherwise, the sum of the q values is used.\n            num_critic_replicas (int): number of critics to be used. Default is 2.\n            epsilon_greedy (float): a floating value in [0,1], representing the\n                chance of action sampling instead of taking argmax. This can\n                help prevent a dead loop in some deterministic environment like\n                Breakout. Only used for evaluation. If None, its value is taken\n                from ``alf.get_config_value(TrainerConfig.epsilon_greedy)``\n            env (Environment): The environment to interact with. ``env`` is a\n                batched environment, which means that it runs multiple simulations\n                simultateously. ``env` only needs to be provided to the root\n                algorithm.\n            config (TrainerConfig): config for training. It only needs to be\n                provided to the algorithm which performs ``train_iter()`` by\n                itself.\n            target_update_tau (float): Factor for soft update of the target\n                networks.\n            target_update_period (int): Period for soft update of the target\n                networks.\n            critic_loss_ctor (None|OneStepTDLoss|MultiStepLoss): a critic loss\n                constructor. If ``None``, a default ``TAACTDLoss`` will be used.\n            actor_optimizer (torch.optim.optimizer): The optimizer for actor.\n            critic_optimizer (torch.optim.optimizer): The optimizer for critic.\n            alpha_optimizer (torch.optim.optimizer): The optimizer for alpha.\n            debug_summaries (bool): True if debug summaries should be created.\n            randomize_first_state_tau (bool): whether to randomize ``state.tau``\n                at the beginning of an episode during rollout and training.\n                Potentially this helps exploration. This was turned off in\n                Yu et al. 2021.\n            b1_advantage_clipping (None|tuple[float]): option for clipping the\n                advantage (defined as :math:`Q(s,\\hat{\\tau}) - Q(s,\\tau^-)`) when\n                computing :math:`\\beta_1`. If not ``None``, it should be a pair\n                of numbers ``[min_adv, max_adv]``.\n            max_repeat_steps (None|int): the max number of steps to repeat during\n                rollout and evaluation. This value doesn't impact the switch\n                during training.\n            target_entropy (Callable|tuple[Callable]|None): If a\n                callable function, then it will be called on the action spec to\n                calculate a target entropy. If ``None``, a default entropy will\n                be calculated. To set separate entropy targets for the two\n                stage policies, this argument can be a tuple of two callables.\n            name (str): name of the algorithm\n        \"\"\"\n        assert len(\n            nest.flatten(action_spec)) == 1 and action_spec.is_continuous, (\n                \"Only support a single continuous action!\")\n\n        self._num_critic_replicas = num_critic_replicas\n        if epsilon_greedy is None:\n            epsilon_greedy = alf.get_config_value(\n                'TrainerConfig.epsilon_greedy')\n        self._epsilon_greedy = epsilon_greedy\n\n        self._tau_spec, critic_networks, actor_network = self._make_networks(\n            observation_spec, action_spec, reward_spec, actor_network_cls,\n            critic_network_cls)\n\n        log_alpha = (nn.Parameter(torch.zeros(())),\n                     nn.Parameter(torch.zeros(())))\n\n        train_state_spec = TaacState(\n            tau=self._tau_spec,\n            repeats=TensorSpec(shape=(), dtype=torch.int64))\n        super().__init__(\n            observation_spec,\n            action_spec,\n            reward_spec=reward_spec,\n            train_state_spec=train_state_spec,\n            reward_weights=reward_weights,\n            env=env,\n            config=config,\n            debug_summaries=debug_summaries,\n            name=name)\n\n        if actor_optimizer is not None:\n            self.add_optimizer(actor_optimizer, [actor_network])\n        if critic_optimizer is not None:\n            self.add_optimizer(critic_optimizer, [critic_networks])\n        if alpha_optimizer is not None:\n            self.add_optimizer(alpha_optimizer, list(log_alpha))\n\n        self._log_alpha = log_alpha\n        self._log_alpha_paralist = nn.ParameterList(list(log_alpha))\n        self._actor_network = actor_network\n        self._critic_networks = critic_networks\n        self._target_critic_networks = self._critic_networks.copy(\n            name='target_critic_networks')\n\n        if critic_loss_ctor is None:\n            critic_loss_ctor = TAACTDLoss\n        critic_loss_ctor = functools.partial(\n            critic_loss_ctor, debug_summaries=debug_summaries)\n        # Have different names to separate their summary curves\n        self._critic_losses = []\n        for i in range(num_critic_replicas):\n            self._critic_losses.append(\n                critic_loss_ctor(name=\"critic_loss%d\" % (i + 1)))\n        self._gamma = self._critic_losses[0]._gamma\n\n        self._b_spec = BoundedTensorSpec(shape=(), dtype='int64', maximum=1)\n\n        # separate target entropies for discrete and continuous actions\n        if not isinstance(target_entropy, tuple):\n            target_entropy = (target_entropy, ) * 2\n        self._target_entropy = nest.map_structure(\n            lambda spec, t: _set_target_entropy(self.name, t, [spec]),\n            (self._b_spec, action_spec), target_entropy)\n\n        self._b1_advantage_clipping = b1_advantage_clipping\n        self._max_repeat_steps = max_repeat_steps\n        self._randomize_first_state_tau = randomize_first_state_tau\n\n        # Create as a buffer so that training from a checkpoint will have\n        # the correct flag.\n        self.register_buffer(\"_training_started\",\n                             torch.zeros((), dtype=torch.bool))\n\n        self._update_target = common.get_target_updater(\n            models=[self._critic_networks],\n            target_models=[self._target_critic_networks],\n            tau=target_update_tau,\n            period=target_update_period)\n\n    def _make_networks(self, observation_spec, action_spec, reward_spec,\n                       actor_network_cls, critic_network_cls):\n        raise NotImplementedError()\n\n    def _update_tau(self, tau):\n        \"\"\"Update the current trajectory ``tau`` by moving one step ahead.\"\"\"\n        raise NotImplementedError()\n\n    def _action2tau(self, a, tau):\n        \"\"\"Compute a new trajectory given a new action and the current trajectory\n        ``tau``.\"\"\"\n        raise NotImplementedError()\n\n    def _make_networks_impl(self, observation_spec, action_spec, reward_spec,\n                            actor_network_cls, critic_network_cls, tau_mask):\n        def _make_parallel(net):\n            return net.make_parallel(\n                self._num_critic_replicas * reward_spec.numel)\n\n        tau_spec = nest.map_structure(lambda m: action_spec if m else (),\n                                      tau_mask)\n        tau_embedding = nest.map_structure(\n            lambda _: torch.nn.Sequential(\n                alf.layers.FC(action_spec.numel, observation_spec.numel)),\n            tau_spec)\n\n        actor_network = actor_network_cls(\n            input_tensor_spec=(observation_spec, tau_spec),\n            input_preprocessors=(alf.layers.Detach(), tau_embedding),\n            preprocessing_combiner=nest_utils.NestConcat(),\n            action_spec=action_spec)\n        critic_network = critic_network_cls(\n            input_tensor_spec=(observation_spec, tau_spec),\n            action_preprocessing_combiner=nest_utils.NestConcat())\n        critic_networks = _make_parallel(critic_network)\n\n        return tau_spec, critic_networks, actor_network\n\n    def _randomize_first_tau(self, time_step_or_exp, state, rollout_tau=None):\n        \"\"\"Randomize the first ``tau`` (by default always 0) for better\n        exploration if ``b=0`` is selected.\n\n        If a ``rollout_tau`` is already provided, then directly use it (during\n        training).\n        \"\"\"\n\n        def _randomize(tau):\n            return alf.nest.map_structure(\n                lambda spec: spec.sample(outer_dims=tau.a.shape[:1]),\n                self._tau_spec)\n\n        if rollout_tau is None:\n            kwargs = dict(tau=state.tau)\n            randomize = _randomize\n        else:\n            kwargs = dict(r_tau=rollout_tau)\n            randomize = lambda r_tau: r_tau\n\n        tau = conditional_update(\n            target=state.tau,\n            cond=(time_step_or_exp.step_type == StepType.FIRST),\n            func=randomize,\n            **kwargs)\n        return state._replace(tau=tau)\n\n    def _predict_action(self,\n                        time_step,\n                        state,\n                        epsilon_greedy=None,\n                        mode=Mode.rollout):\n\n        observation = time_step.observation\n\n        ap_out = self._compute_beta_and_tau(observation, state, epsilon_greedy,\n                                            mode)\n\n        if not common.is_eval() and not self._training_started:\n            b = self._b_spec.sample(observation.shape[:1])\n            b1_a = self._action_spec.sample(observation.shape[:1])\n            b1_tau = self._action2tau(b1_a, state.tau)\n            ap_out = ap_out._replace(b=b, taus=(ap_out.taus[0], b1_tau))\n\n        b0_tau, b1_tau = ap_out.taus\n        new_state = state._replace(tau=b0_tau)\n\n        def _b1_action(b1_tau, new_state):\n            new_state = new_state._replace(\n                repeats=torch.zeros_like(new_state.repeats), tau=b1_tau)\n            return new_state\n\n        condition = ap_out.b.to(torch.bool)\n        if self._max_repeat_steps is not None and mode != Mode.train:\n            condition |= (state.repeats >= self._max_repeat_steps)\n\n        # selectively update with new actions\n        new_state = conditional_update(\n            target=new_state,\n            cond=condition,\n            func=_b1_action,\n            b1_tau=b1_tau,\n            new_state=new_state)\n\n        new_state = new_state._replace(repeats=new_state.repeats + 1)\n        return ap_out, new_state\n\n    def _compute_critics(self,\n                         critic_net,\n                         observation,\n                         tau,\n                         replica_min=True,\n                         apply_reward_weights=True):\n        \"\"\"Compute Q(s,a)\"\"\"\n        observation = (observation, tau)\n        critics, _ = critic_net(observation)  # [B, replicas * reward_dim]\n        critics = critics.reshape(  # [B, replicas, reward_dim]\n            -1, self._num_critic_replicas, *self._reward_spec.shape)\n        if replica_min:\n            if self.has_multidim_reward():\n                sign = self.reward_weights.sign()\n                critics = (critics * sign).min(dim=1)[0] * sign\n            else:\n                critics = critics.min(dim=1)[0]\n\n        if apply_reward_weights and self.has_multidim_reward():\n            critics = critics * self.reward_weights\n            critics = critics.sum(dim=-1)\n        return critics\n\n    def _alpha_train_step(self, beta_entropy, action_entropy):\n        alpha_loss = (self._log_alpha[1] *\n                      (action_entropy - self._target_entropy[1]).detach())\n        alpha_loss += (self._log_alpha[0] *\n                       (beta_entropy - self._target_entropy[0]).detach())\n        return alpha_loss\n\n    def _calc_critic_loss(self, info: TaacInfo):\n        critic_info = info.critic\n        critic_losses = []\n        for i, l in enumerate(self._critic_losses):\n            kwargs = dict(\n                info=info,\n                value=critic_info.critics[:, :, i, ...],\n                target_value=critic_info.target_critic)\n            critic_losses.append(l(**kwargs).loss)\n\n        critic_loss = math_ops.add_n(critic_losses)\n        return LossInfo(\n            loss=critic_loss,\n            extra=critic_loss / float(self._num_critic_replicas))\n\n    def _trainable_attributes_to_ignore(self):\n        return ['_target_critic_networks']\n\n    def _build_beta_dist(self, q_values2):\n        def _safe_categorical(logits, alpha):\n            r\"\"\"A numerically stable implementation of categorical distribution\n            :math:`exp(\\frac{Q}{\\alpha})`.\n            \"\"\"\n            logits = logits / torch.clamp(alpha, min=1e-10)\n            # logits are equivalent after subtracting a common number\n            logits = logits - torch.max(logits, dim=-1, keepdim=True)[0]\n            return td.Categorical(logits=logits)\n\n        # compute beta dist *conditioned* on ``action``\n        with torch.no_grad():\n            beta_alpha = self._log_alpha[0].exp().detach()\n            if self._b1_advantage_clipping is None:\n                beta_dist = _safe_categorical(q_values2, beta_alpha)\n            else:\n                clip_min, clip_max = self._b1_advantage_clipping\n                # The first dim [..., 0] is always 0\n                q_values2 = q_values2 - q_values2[..., :1]\n                q_values2[..., 1] = q_values2[..., 1].clamp(\n                    min=clip_min, max=clip_max)\n                beta_dist = _safe_categorical(q_values2, beta_alpha)\n\n        return beta_dist\n\n    def _compute_beta_and_tau(self, observation, state, epsilon_greedy, mode):\n        # compute resampling action dist\n        b1_a_dist, _ = self._actor_network((observation, state.tau))\n        # resample a new attempting action\n        if mode == Mode.predict:\n            b1_a = dist_utils.epsilon_greedy_sample(b1_a_dist, epsilon_greedy)\n        else:\n            b1_a = dist_utils.rsample_action_distribution(b1_a_dist)\n\n        b0_tau = self._update_tau(state.tau)\n        # This should be a deterministic function converting b1_a to b1_tau\n        b1_tau = self._action2tau(b1_a, state.tau)\n\n        # compute Q(s, tau^-) and Q(s, \\hat{tau})\n        with torch.no_grad():\n            q_0 = self._compute_critics(self._critic_networks, observation,\n                                        b0_tau)\n        q_1 = self._compute_critics(self._critic_networks, observation, b1_tau)\n\n        q_values2 = torch.stack([q_0, q_1], dim=-1)\n        beta_dist = self._build_beta_dist(q_values2)\n\n        if mode == Mode.predict:\n            b = dist_utils.epsilon_greedy_sample(beta_dist, epsilon_greedy)\n        else:\n            b = dist_utils.sample_action_distribution(beta_dist)\n\n        dists = Distributions(beta_dist=beta_dist, b1_a_dist=b1_a_dist)\n        return ActPredOutput(\n            dists=dists,\n            b=b,\n            actor_a=b1_a,\n            taus=(b0_tau, b1_tau),\n            q_values2=q_values2)\n\n    def _actor_train_step(self, a, b1_a_entropy, beta_dist, beta_entropy,\n                          q_values2):\n        alpha = self._log_alpha[1].exp().detach()\n        q_a = beta_dist.probs[:, 1].detach() * q_values2[:, 1]\n\n        dqda = nest_utils.grad(a, q_a.sum())\n\n        def actor_loss_fn(dqda, action):\n            loss = 0.5 * losses.element_wise_squared_loss(\n                (dqda + action).detach(), action)\n            return loss.sum(list(range(1, loss.ndim)))\n\n        actor_loss = nest.map_structure(actor_loss_fn, dqda, a)\n        actor_loss = math_ops.add_n(nest.flatten(actor_loss))\n        actor_loss -= alpha * b1_a_entropy\n\n        return LossInfo(\n            loss=actor_loss,\n            extra=TaacActorInfo(\n                actor_loss=actor_loss,\n                adv=q_values2[:, 1] - q_values2[:, 0],\n                b1_a_entropy=b1_a_entropy,\n                beta_entropy=beta_entropy))\n\n    def _critic_train_step(self, inputs: TimeStep, rollout_tau, b0_tau, b1_tau,\n                           beta_dist):\n\n        with torch.no_grad():\n            target_q_0 = self._compute_critics(\n                self._target_critic_networks,\n                inputs.observation,\n                b0_tau,\n                apply_reward_weights=False)\n            target_q_1 = self._compute_critics(\n                self._target_critic_networks,\n                inputs.observation,\n                b1_tau,\n                apply_reward_weights=False)\n\n            beta_probs = beta_dist.probs\n            if self.has_multidim_reward():\n                beta_probs = beta_probs.unsqueeze(1)\n\n            target_critic = (beta_probs[..., 0] * target_q_0 +\n                             beta_probs[..., 1] * target_q_1)\n\n        critics = self._compute_critics(\n            self._critic_networks,\n            inputs.observation,\n            rollout_tau,\n            replica_min=False,\n            apply_reward_weights=False)\n        return TaacCriticInfo(critics=critics, target_critic=target_critic)\n\n    def predict_step(self, inputs: TimeStep, state):\n        ap_out, new_state = self._predict_action(\n            inputs,\n            state,\n            epsilon_greedy=self._epsilon_greedy,\n            mode=Mode.predict)\n        return AlgStep(\n            output=new_state.tau.a,\n            state=new_state,\n            info=TaacInfo(action_distribution=ap_out.dists, b=ap_out.b))\n\n    def rollout_step(self, inputs: TimeStep, state):\n        if self._randomize_first_state_tau:\n            state = self._randomize_first_tau(inputs, state)\n        ap_out, new_state = self._predict_action(\n            inputs, state, mode=Mode.rollout)\n        return AlgStep(\n            output=new_state.tau.a,\n            state=new_state,\n            info=TaacInfo(\n                action_distribution=ap_out.dists,\n                prev_tau=state.tau,  # for getting randomized tau in training\n                tau=new_state.tau,  # for critic training\n                b=ap_out.b,\n                repeats=state.repeats))\n\n    def summarize_rollout(self, experience):\n        repeats = experience.rollout_info.repeats.reshape(-1)\n        if self._debug_summaries:\n            with alf.summary.scope(self._name):\n                # if rollout batch size=1, hist won't show\n                alf.summary.histogram(\"rollout_repeats/value\", repeats)\n                alf.summary.scalar(\"rollout_repeats/mean\",\n                                   torch.mean(repeats.to(torch.float32)))\n\n    def train_step(self, inputs: TimeStep, state, rollout_info: TaacInfo):\n        self._training_started.fill_(True)\n\n        if self._randomize_first_state_tau:\n            # Because we called ``self._randomize_first_tau`` in rollout_step()\n            # while the random ``tau`` was not stored in the replay buffer, the\n            # first step's ``tau`` here is not accurate. So we need to use the\n            # rollout ``tau``.\n            state = self._randomize_first_tau(inputs, state,\n                                              rollout_info.prev_tau)\n\n        ap_out, new_state = self._predict_action(\n            inputs, state=state, mode=Mode.train)\n\n        beta_dist = ap_out.dists.beta_dist\n        b1_a_dist = ap_out.dists.b1_a_dist\n        b0_tau, b1_tau = ap_out.taus\n        q_values2 = ap_out.q_values2\n\n        b1_a_entropy = -dist_utils.compute_log_probability(\n            b1_a_dist, ap_out.actor_a)\n        beta_entropy = beta_dist.entropy()\n\n        actor_loss = self._actor_train_step(ap_out.actor_a, b1_a_entropy,\n                                            beta_dist, beta_entropy, q_values2)\n        critic_info = self._critic_train_step(inputs, rollout_info.tau, b0_tau,\n                                              b1_tau, beta_dist)\n        alpha_loss = self._alpha_train_step(beta_entropy, b1_a_entropy)\n\n        info = TaacInfo(\n            reward=inputs.reward,\n            step_type=inputs.step_type,\n            discount=inputs.discount,\n            rollout_b=rollout_info.b,\n            action_distribution=ap_out.dists,\n            actor=actor_loss,\n            critic=critic_info,\n            b=ap_out.b,\n            alpha=alpha_loss,\n            repeats=state.repeats)\n        return AlgStep(output=new_state.tau.a, state=new_state, info=info)\n\n    def after_update(self, root_inputs, info: TaacInfo):\n        self._update_target()\n\n    def calc_loss(self, info: TaacInfo):\n        critic_loss = self._calc_critic_loss(info)\n        alpha_loss = info.alpha\n        actor_loss = info.actor\n        if self._debug_summaries:\n            with alf.summary.scope(self._name):\n                alf.summary.scalar(\"alpha/beta\", self._log_alpha[0].exp())\n                alf.summary.scalar(\"alpha/action\", self._log_alpha[1].exp())\n                alf.summary.scalar(\"resample_advantage\",\n                                   torch.mean(actor_loss.extra.adv))\n                p_beta0 = info.action_distribution[0].probs[..., 0]\n                alf.summary.histogram(\"P_beta_0/value\", p_beta0)\n                alf.summary.scalar(\"P_beta_0/mean\", p_beta0.mean())\n                alf.summary.scalar(\"P_beta_0/std\", p_beta0.std())\n                repeats = info.repeats\n                alf.summary.scalar(\"train_repeats/mean\",\n                                   torch.mean(repeats.to(torch.float32)))\n                alf.summary.histogram(\"train_repeats/value\",\n                                      repeats.to(torch.float32))\n\n        return LossInfo(\n            loss=actor_loss.loss + alpha_loss + critic_loss.loss,\n            extra=TaacLossInfo(\n                actor=actor_loss.extra,\n                critic=critic_loss.extra,\n                alpha=alpha_loss))\n\n\n@alf.configurable\nclass TaacAlgorithm(TaacAlgorithmBase):\n    r\"\"\"Model temporal abstraction by action repetition. See\n\n        \"TAAC: Temporally Abstract Actor-Critic for Continuous Control\",\n        Yu et al., arXiv 2021.\n\n    for algorithm details.\n    \"\"\"\n\n    def __init__(self, name=\"TaacAlgorithm\", *args, **kwargs):\n        \"\"\"See ``TaacAlgorithmBase`` for argument description.\n        \"\"\"\n        super().__init__(*args, name=name, **kwargs)\n\n    def _make_networks(self, *args):\n        tau_mask = Tau(a=True, v=False, u=False)\n        args = args + (tau_mask, )\n        return self._make_networks_impl(*args)\n\n    def _update_tau(self, tau):\n        \"\"\"Return a constant trajectory.\"\"\"\n        return tau\n\n    def _action2tau(self, a, tau):\n        \"\"\"Return a constant trajectory.\"\"\"\n        return Tau(a=a)\n\n\n@alf.configurable\nclass TaacLAlgorithm(TaacAlgorithmBase):\n    r\"\"\"TaacL: Piecewise linear trajectory policy for continuous control.\n\n    For a linear trajectory, let :math:`a` be the action and :math:`v` the\n    first derivative. Its dynamics is:\n\n    .. math::\n\n        \\begin{array}{ll}\n            v_{t+1} &\\leftarrow v_t\\\\\n            a_{t+1} &\\leftarrow v_{t+1} + a_t\\\\\n        \\end{array}\n\n    TaacL's trajectory is piece-wise linear. Each time the policy decides whether\n    to repeat the previous linear traj or generate a new one. Importantly,\n    to generate a new one the policy doesn't directly generate the entire set of\n    two parameters :math:`(a,v)` because this will result in bad exploration\n    in the action space. Instead,\n\n    .. math::\n\n        \\begin{array}{ll}\n            a_{t+1} &\\sim \\pi\\\\\n            v_{t+1} &\\leftarrow a_{t+1} - a_t\\\\\n        \\end{array}\n\n    For :math:`a\\in[0,1]` and :math:`v\\in[0,1]`, the actual dynamics is\n    :math:`a_{t+1}\\leftarrow \\max(\\min(a_t+2v_{t+1},1),-1)`.\n    \"\"\"\n\n    def __init__(self,\n                 name=\"TaacLAlgorithm\",\n                 inverse_mode=True,\n                 *args,\n                 **kwargs):\n        \"\"\"See ``TaacAlgorithmBase`` for other argument description.\n\n        Args:\n            inverse_mode (bool): this argument decides how the new traj is computed when\n                ``b=1``. If it's False, then the new action is treated as the\n                new first derivative ``v``; otherwise the new action is treated\n                as the new action ``a``, and ``v`` is inversely inferred.\n        \"\"\"\n        super().__init__(*args, name=name, **kwargs)\n\n        assert (\n            np.all(self._action_spec.minimum == -1)\n            and np.all(self._action_spec.maximum == 1)\n        ), (\"Only support actions in [-1, 1]! Consider using env wrappers to \"\n            \"scale your action space first.\")\n\n        self._inverse_mode = inverse_mode\n\n    def _make_networks(self, *args):\n        tau_mask = Tau(a=True, v=True, u=False)\n        args = args + (tau_mask, )\n        return self._make_networks_impl(*args)\n\n    def _update_tau(self, tau):\n        \"\"\"Compute next action on a linear trajectory specified by a pair of\n        ('action', 'action derivative').\n        \"\"\"\n        a = torch.clamp(tau.a + 2. * tau.v, min=-1., max=1.)\n        return tau._replace(a=a)\n\n    def _action2tau(self, a, tau):\n        if self._inverse_mode:\n            # Given a new action at the next step and the current traj ``tau``,\n            # infer the new traj's first derivative.\n            v = (a - tau.a) / 2.\n            return Tau(a=a, v=v)\n        else:\n            # Given a new first derivative and the current traj ``tau``, compute\n            # the new traj's action\n            tau = Tau(a=tau.a, v=a)\n            return self._update_tau(tau)\n\n\n@alf.configurable\nclass TaacQAlgorithm(TaacLAlgorithm):\n    r\"\"\"TaacQ: Piecewise quadratic trajectory policy for continuous control.\n\n    For a quadratic trajectory, let :math:`a` be the action, :math:`u` be the\n    second derivative, and :math:`v` be the first derivative. Its dynamics is:\n\n    .. math::\n\n        \\begin{array}{ll}\n            u_{t+1} &\\leftarrow u_t\\\\\n            v_{t+1} &\\leftarrow u_{t+1} + v_t\\\\\n            a_{t+1} &\\leftarrow v_{t+1} + a_t\\\\\n        \\end{array}\n\n    TaacQ's trajectory is piece-wise quadratic. Each time the policy decides whether\n    to repeat the previous quadratic traj or generate a new one. Importantly,\n    to generate a new one the policy doesn't directly generate the entire set of\n    three parameters :math:`(a,v,u)` because this will result in bad exploration\n    in the action space. Instead,\n\n    .. math::\n\n        \\begin{array}{ll}\n            a_{t+1} &\\sim \\pi\\\\\n            v_{t+1} &\\leftarrow a_{t+1} - a_t\\\\\n            u_{t+1} &\\leftarrow v_{t+1}\\\\\n        \\end{array}\n\n    where the last two steps assume resetting :math:`v_t` to zero.\n\n    For :math:`a\\in[0,1]`, :math:`v\\in[0,1]`, and :math:`u\\in[0,1]`, the actual\n    dynamics is :math:`v_{t+1}\\leftarrow \\max(\\min(v_t+2u_{t+1},1),-1)` and\n    :math:`a_{t+1}\\leftarrow \\max(\\min(a_t+2v_{t+1},1),-1)`.\n    \"\"\"\n\n    def __init__(self,\n                 name=\"TaacQAlgorithm\",\n                 inverse_mode=True,\n                 *args,\n                 **kwargs):\n        \"\"\"See ``TaacAlgorithmBase`` for other argument description.\n\n        Args:\n            inverse_mode (bool): this argument decides how the new traj is computed\n                when ``b=1``. If it's False, then the new action is treated as the\n                new second derivative ``u``; otherwise the new action is treated\n                as the new action ``a``, and ``u`` is inversely inferred. In either\n                case, the current ``v`` is first set to 0, and then a new ``v`` is\n                computed.\n        \"\"\"\n        super().__init__(*args, name=name, inverse_mode=inverse_mode, **kwargs)\n\n    def _make_networks(self, *args):\n        tau_mask = Tau(a=True, v=True, u=True)\n        args = args + (tau_mask, )\n        return self._make_networks_impl(*args)\n\n    def _update_tau(self, tau):\n        \"\"\"Compute next action on a quadratic trajectory specified by a triplet\n        of ('action', 'action derivative', and 'action second derivative').\n        \"\"\"\n        v = torch.clamp(tau.v + tau.u * 2., min=-1., max=1.)\n        a = torch.clamp(tau.a + v * 2., min=-1., max=1.)\n        return Tau(a=a, v=v, u=tau.u)\n\n    def _action2tau(self, a, tau):\n        if self._inverse_mode:\n            # Given a new action at the next step and the current traj ``tau``,\n            # infer the new traj, assuming resetting ``tau.v`` to 0 first.\n            v = (a - tau.a) / 2.\n            u = v / 2.\n            return Tau(a=a, v=v, u=u)\n        else:\n            # Given a new second derivative at the next step and the current traj\n            # ``tau``, compute the new traj, assuming resetting ``tau.v`` to 0 first.\n            tau = Tau(a=tau.a, v=0, u=a)\n            return self._update_tau(tau)\n", "meta": {"hexsha": "92be01cb6c0d57321c8effa8ff0455baf35ce54b", "size": 39746, "ext": "py", "lang": "Python", "max_stars_repo_path": "alf/algorithms/taac_algorithm.py", "max_stars_repo_name": "hnyu/alf", "max_stars_repo_head_hexsha": "7548f034e4abbd49a52fed27a01861ee5bfcc1d7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 175, "max_stars_repo_stars_event_min_datetime": "2019-04-29T17:43:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:05:00.000Z", "max_issues_repo_path": "alf/algorithms/taac_algorithm.py", "max_issues_repo_name": "Aminullah6264/gpvi_plus_updated_adv", "max_issues_repo_head_hexsha": "449cb2594a1a9ee158af19984c4caaf7d86f1e7f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 518, "max_issues_repo_issues_event_min_datetime": "2019-03-30T00:24:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T03:14:14.000Z", "max_forks_repo_path": "alf/algorithms/taac_algorithm.py", "max_forks_repo_name": "Aminullah6264/gpvi_plus_updated_adv", "max_forks_repo_head_hexsha": "449cb2594a1a9ee158af19984c4caaf7d86f1e7f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 45, "max_forks_repo_forks_event_min_datetime": "2019-05-31T22:26:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T09:30:32.000Z", "avg_line_length": 41.1023784902, "max_line_length": 88, "alphanum_fraction": 0.6040356262, "include": true, "reason": "import numpy", "num_tokens": 9035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.35220178884745906, "lm_q1q2_score": 0.18846262377175702}}
{"text": "# The batman package: fast computation of exoplanet transit light curves\n# Copyright (C) 2015 Laura Kreidberg\t \n# \n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nimport numpy as np\nfrom . import _nonlinear_ld\nfrom . import _quadratic_ld\nfrom . import _uniform_ld\nfrom . import _logarithmic_ld\nfrom . import _exponential_ld\nfrom . import _power2_ld\nfrom . import _custom_ld\nfrom . import _rsky\nfrom . import _eclipse\nfrom math import pi\nimport multiprocessing\nfrom . import openmp\n\n__all__ = ['TransitModel', 'TransitParams']\n\ndef wrapper(func, *args, **kwargs):\n    def wrapped():\n        return func(*args, **kwargs)\n    return wrapped\n\nclass TransitModel(object):\n\t\"\"\"\n\tClass for generating model transit light curves.\t\n\n\t:param params: A :attr:`TransitParams` object containing the physical parameters of the transit\n\t:type params: a `TransitParams` instance\n\n\t:param t: Array of times at which to calculate the model.\n\t:type t: ndarray \n\n\t:param max_err: Error tolerance (in parts per million) for the model.\n\t:type max_err: float, optional\n\n\t:param nthreads: Number of threads to use for parallelization. \n\t:type nthreads: int, optional\n\n\t:param fac: Scale factor for integration step size\n\t:type fac: float, optional\n\n\t:param transittype: Type of transit (\"primary\" or \"secondary\")\n\t:type transittype: string, optional\n\n\t:param supersample_factor:\tNumber of points subdividing exposure\n\t:type supersample_factor: integer, optional\n\n\t:param exp_time: Exposure time (in same units as `t`)\n\t:type exp_time: double, optional\n\n\t:Example:\n\t\n\t>>> m = batman.TransitModel(params, max_err = 0.5, nthreads=4)\n\t\"\"\"\n\n\tdef __init__(self, params, t, max_err=1.0, nthreads = 1, fac = None, transittype = \"primary\", supersample_factor = 1, exp_time = 0.):\n\t\t#checking for invalid input\n\t\tif  (params.limb_dark == \"uniform\" and len(params.u) != 0) or (params.limb_dark == \"linear\" and len(params.u) != 1) or \\\n\t\t    (params.limb_dark == \"quadratic\" and len(params.u) != 2) or (params.limb_dark == \"logarithmic\" and len(params.u) != 2) or \\\n\t\t    (params.limb_dark == \"exponential\" and len(params.u) != 2) or (params.limb_dark == \"squareroot\" and len(params.u) != 2) or \\\n\t\t    (params.limb_dark == \"power2\" and len(params.u) != 2) or \\\n\t\t    (params.limb_dark == \"nonlinear\" and len(params.u) != 4):\n\t\t\traise Exception(\"Incorrect number of coefficients for \" +params.limb_dark + \" limb darkening; u should have the form:\\n \\\n\t\t\t u = [] for uniform LD\\n \\\n\t\t\t u = [u1] for linear LD\\n \\\n  \t\t\t u = [u1, u2] for quadratic, logarithmic, exponential, squareroot, and power2 LD\\n \\\n\t\t\t u = [u1, u2, u3, u4] for nonlinear LD, or\\n \\\n\t\t         u = [u1, ..., un] for custom LD\") \n\t\tif params.limb_dark not in [\"uniform\", \"linear\", \"quadratic\", \"logarithmic\", \"exponential\", \"squareroot\", \"nonlinear\", \"power2\", \"custom\"]: \n\t\t\traise Exception(\"\\\"\"+params.limb_dark+\"\\\"\"+\" limb darkening not supported; allowed options are:\\n \\\n\t\t\t\tuniform, linear, quadratic, logarithmic, exponential, squareroot, nonlinear, power2, custom\")\n\t\tif max_err < 0.001: raise Exception(\"The lowest allowed value for max_err is 0.001. For more accurate calculation, set the integration step size explicitly with the fac parameter.\")\n\t\tif transittype not in [\"primary\", \"secondary\"]: raise Exception(\"Allowed transit types are \\\"primary\\\" and \\\"secondary\\\".\")\n\t\tif (supersample_factor > 1 and exp_time <= 0.): raise Exception(\"Please enter a valid exposure time (exp_time must be greater than 0 to calculate super-sampled light curves).\")\n\t\tif (not isinstance(t, np.ndarray)): raise Exception(\"Times t must be a numpy array (not a list).\")\n\n\t\t#initializes model parameters\n\t\tself.t = t\n\t\tself.t0 = params.t0\n\t\tself.per = params.per\n\t\tself.rp = params.rp\n\t\tself.a = params.a\n\t\tself.inc = params.inc\n\t\tself.ecc = params.ecc\n\t\tself.w = params.w\n\t\tself.u = params.u\n\t\tself.limb_dark = params.limb_dark\n\t\tself.fp = params.fp\n\t\tself.t_secondary = params.t_secondary\n\t\tself.max_err = max_err\n\t\tself.supersample_factor = supersample_factor\n\t\tself.exp_time = exp_time\n\t\tself.inverse = False\n\n\t\t#handles the case of inverse transits (rp < 0)\n\t\tif self.rp < 0.: \n\t\t\tself.rp = -1.*self.rp\n\t\t\tparams.rp = -1.*params.rp\n\t\t\tself.inverse = True\n\n\t\tif self.supersample_factor > 1:  # IJMC: now do it quicker, with no loops:\n\t\t\tt_offsets = np.linspace(-self.exp_time/2., self.exp_time/2., self.supersample_factor)\n\t\t\tself.t_supersample = (t_offsets + self.t.reshape(self.t.size, 1)).flatten()\n\t\telse: self.t_supersample = self.t\n\t\t\n\t\tif transittype == \"primary\": self.transittype = 1\n\t\telse: \n\t\t\tself.transittype = 2\n\t\t\tparams.t0 = self.get_t_conjunction(params)\t\t\n\t\t\n\t\tif fac != None: self.fac = fac\n\t\telse: self.fac = self._get_fac()\n\t\t\n\t\tif nthreads==None or nthreads == 1: self.nthreads=1\n\t\telse:\n\t\t\tif nthreads <= multiprocessing.cpu_count()and nthreads >1 and openmp.detect(): self.nthreads = nthreads\n\t\t\telse: \n\t\t\t\tif nthreads > multiprocessing.cpu_count(): raise Exception(\"Maximum number of threads is \"+'{0:d}'.format(multiprocessing.cpu_count()))\n\t\t\t\telif nthreads <= 1: raise Exception(\"Number of threads must be between 2 and {0:d}\".format(multiprocessing.cpu_count()))\n\t\t\t\telse: raise Exception(\"OpenMP not enabled: do not set the nthreads parameter\")\n\t\tself.ds = _rsky._rsky(self.t_supersample, params.t0, params.per, params.a, params.inc*pi/180., params.ecc, params.w*pi/180., self.transittype, self.nthreads)\n\n\tdef calc_err(self, plot = False):\n\t\t\"\"\"\n\n\t\tCalculate maximum error for transit light curve calculation.\n\t\t\t\n\t\t:param plot: If ``True``, plots the error in the light curve model as a function of separation of centers.\n\t\t:type plot: bool\n\n\t\t:return: Truncation error (parts per million)\n\t\t:rtype: float\n\n\t\t\"\"\"\n\t\tif self.limb_dark in [\"logarithmic\", \"exponential\", \"nonlinear\", \"squareroot\", \"power2\", \"custom\"]:\n\t\t\tds = np.linspace(0., 1.1, 500)\n\t\t\tfac_lo = 5.0e-4\n\t\t\tif self.limb_dark == \"nonlinear\":\n\t\t\t\tf0 = _nonlinear_ld._nonlinear_ld(ds, self.rp, self.u[0], self.u[1], self.u[2], self.u[3], fac_lo, self.nthreads)\n\t\t\t\tf = _nonlinear_ld._nonlinear_ld(ds, self.rp, self.u[0], self.u[1], self.u[2], self.u[3], self.fac, self.nthreads)\n\t\t\telif self.limb_dark == \"squareroot\":\n\t\t\t\tf0 = _nonlinear_ld._nonlinear_ld(ds, self.rp, self.u[1], self.u[0], 0., 0., fac_lo, self.nthreads)\n\t\t\t\tf = _nonlinear_ld._nonlinear_ld(ds, self.rp, self.u[1], self.u[0], 0., 0., self.fac, self.nthreads)\n\t\t\telif self.limb_dark == \"exponential\":\n\t\t\t\tf0 = _exponential_ld._exponential_ld(ds, self.rp, self.u[0], self.u[1], fac_lo, self.nthreads)\n\t\t\t\tf = _exponential_ld._exponential_ld(ds, self.rp, self.u[0], self.u[1], self.fac, self.nthreads)\n\t\t\telif self.limb_dark == \"logarithmic\":\n\t\t\t\tf0 = _logarithmic_ld._logarithmic_ld(ds, self.rp, self.u[0], self.u[1], fac_lo, self.nthreads)\n\t\t\t\tf = _logarithmic_ld._logarithmic_ld(ds, self.rp, self.u[0], self.u[1], self.fac, self.nthreads)\n\t\t\telif self.limb_dark == \"power2\":\n\t\t\t\tf0 = _power2_ld._power2_ld(ds, self.rp, self.u[0], self.u[1], fac_lo, self.nthreads)\n\t\t\t\tf = _power2_ld._power2_ld(ds, self.rp, self.u[0], self.u[1], self.fac, self.nthreads)\n\t\t\telse:\n\t\t\t\tf0 = _custom_ld._custom_ld(ds, self.rp, self.u[0], self.u[1], self.u[2], self.u[3], self.u[4], self.u[5], fac_lo, self.nthreads)\n\t\t\t\tf =  _custom_ld._custom_ld(ds, self.rp, self.u[0], self.u[1], self.u[2], self.u[3], self.u[4], self.u[5], self.fac, self.nthreads)\n\t\n\t\t\terr = np.max(np.abs(f-f0))*1.0e6\n\t\t\tif plot == True:\n\t\t\t\timport matplotlib.pyplot as plt\n\t\t\t\tplt.plot(ds, 1.0e6*(f-f0), color='k')\n\t\t\t\tplt.xlabel(\"d (separation of centers)\")\n\t\t\t\tplt.ylabel(\"Error (ppm)\") \n\t\t\t\tplt.show()\n\n\t\t\treturn err\n\t\telse: raise Exception(\"Function calc_err not valid for \" + self.limb_dark + \" limb darkening\")\n\n\tdef _get_fac(self):\n\t\tif self.limb_dark in [\"logarithmic\", \"exponential\", \"squareroot\", \"nonlinear\", \"power2\", \"custom\"]:\n\t\t\tnthreads = 1\n\t\t\tfac_lo, fac_hi = 5.0e-4, 1.\n\t\t\tds = np.linspace(0., 1.+self.rp, 1000)\n\t\t\tif self.limb_dark == \"nonlinear\": f0 = _nonlinear_ld._nonlinear_ld(ds, self.rp, self.u[0], self.u[1], self.u[2], self.u[3], fac_lo, nthreads)\n\t\t\telif self.limb_dark == \"squareroot\": f0 = _nonlinear_ld._nonlinear_ld(ds, self.rp, self.u[1], self.u[0], 0., 0., fac_lo, nthreads)\n\t\t\telif self.limb_dark == \"exponential\": f0 = _exponential_ld._exponential_ld(ds, self.rp, self.u[0], self.u[1], fac_lo, nthreads)\n\t\t\telif self.limb_dark == \"logarithmic\": f0 = _logarithmic_ld._logarithmic_ld(ds, self.rp, self.u[0], self.u[1], fac_lo, nthreads)\n\t\t\telif self.limb_dark == \"power2\": f0 = _power2_ld._power2_ld(ds, self.rp, self.u[0], self.u[1], fac_lo, nthreads)\n\t\t\telse: f0 = _custom_ld._custom_ld(ds, self.rp, self.u[0], self.u[1], self.u[2], self.u[3], self.u[4], self.u[5], fac_lo, nthreads)\n\n\t\t\tn = 0\n\t\t\terr = 0.\n\t\t\twhile(err > self.max_err or err < 0.99*self.max_err):\n\t\t\t\tfac = (fac_lo + fac_hi)/2.\n\t\t\t\tif self.limb_dark == \"nonlinear\": f = _nonlinear_ld._nonlinear_ld(ds, self.rp, self.u[0], self.u[1], self.u[2], self.u[3], fac, nthreads)\n\t\t\t\telif self.limb_dark == \"squareroot\": f = _nonlinear_ld._nonlinear_ld(ds, self.rp, self.u[1], self.u[0], 0., 0., fac, nthreads)\n\t\t\t\telif self.limb_dark == \"exponential\": f = _exponential_ld._exponential_ld(ds, self.rp, self.u[0], self.u[1], fac, nthreads)\n\t\t\t\telif self.limb_dark == \"logarithmic\": f = _logarithmic_ld._logarithmic_ld(ds, self.rp, self.u[0], self.u[1], fac, nthreads)\n\t\t\t\telif self.limb_dark == \"power2\": f = _power2_ld._power2_ld(ds, self.rp, self.u[0], self.u[1], fac, nthreads)\n\t\t\t\telse: f = _custom_ld._custom_ld(ds, self.rp, self.u[0], self.u[1], self.u[2], self.u[3], self.u[4], self.u[5], fac, nthreads)\n\n\t\t\t\terr = np.max(np.abs(f-f0))*1.0e6\n\n\t\t\t\tif err > self.max_err: fac_hi = fac\t\n\t\t\t\telse: fac_lo = fac\n\t\t\t\tn += 1\n\t\t\t\tif n > 1e3: raise Exception(\"Convergence failure in calculation of scale factor for integration step size\")\n\t\t\treturn fac\n\t\telse: return None\n\t\n\tdef light_curve(self, params):\n\t\t\"\"\"\n\t\tCalculate a model light curve.\n\n\t\t:param params: Transit parameters\n\t\t:type params: A `TransitParams` instance\n\n\t\t:return: Relative flux \n\t\t:rtype: ndarray\n\n\t\t:Example:\n\n\t\t>>> flux = m.light_curve(params)\n\t\t\"\"\"\n\t\t#recalculates rsky and fac if necessary\n\t\tif params.t0 != self.t0 or params.per != self.per or params.a != self.a or params.inc != self.inc or params.ecc != self.ecc or params.w != self.w or params.t_secondary != self.t_secondary:\n\t\t\tif self.transittype == 2 and params.t_secondary != self.t_secondary:\n\t\t\t\tparams.t0 = self.get_t_conjunction(params)\n\t\t\tself.ds= _rsky._rsky(self.t_supersample, params.t0, params.per, params.a, params.inc*pi/180., params.ecc, params.w*pi/180., self.transittype, self.nthreads)\n\t\tif params.limb_dark != self.limb_dark: self.fac = self._get_fac()\n\n\t\t#updates transit params\n\t\tself.t0 = params.t0\n\t\tself.per = params.per\n\t\tself.rp = params.rp\n\t\tself.a = params.a\n\t\tself.inc = params.inc\n\t\tself.ecc = params.ecc\n\t\tself.w = params.w\n\t\tself.u = params.u\n\t\tself.limb_dark = params.limb_dark\n\t\tself.fp = params.fp\n\t\tself.t_secondary = params.t_secondary\n\t\tself.inverse = False\n\n\t\t#handles the case of inverse transits (rp < 0)\n\t\tif self.rp < 0.: \n\t\t\tself.rp = -1.*self.rp\n\t\t\tparams.rp = -1.*params.rp\n\t\t\tself.inverse = True\n\t\t\n\t\tif self.transittype == 1:\n\t\t\tif params.limb_dark != self.limb_dark: raise Exception(\"Need to reinitialize model in order to change limb darkening option\")\n\t\t\tif self.limb_dark == \"quadratic\": lc = _quadratic_ld._quadratic_ld(self.ds, params.rp, params.u[0], params.u[1], self.nthreads)\n\t\t\telif self.limb_dark == \"linear\": lc = _quadratic_ld._quadratic_ld(self.ds, params.rp, params.u[0], 0., self.nthreads)\n\t\t\telif self.limb_dark == \"nonlinear\": lc = _nonlinear_ld._nonlinear_ld(self.ds, params.rp, params.u[0], params.u[1], params.u[2], params.u[3], self.fac, self.nthreads)\n\t\t\telif self.limb_dark == \"squareroot\": lc = _nonlinear_ld._nonlinear_ld(self.ds, params.rp, params.u[1], params.u[0], 0., 0., self.fac, self.nthreads)\n\t\t\telif self.limb_dark == \"uniform\": lc = _uniform_ld._uniform_ld(self.ds, params.rp, self.nthreads)\n\t\t\telif self.limb_dark == \"logarithmic\": lc = _logarithmic_ld._logarithmic_ld(self.ds, params.rp, params.u[0], params.u[1], self.fac, self.nthreads)\n\t\t\telif self.limb_dark == \"exponential\": lc = _exponential_ld._exponential_ld(self.ds, params.rp, params.u[0], params.u[1], self.fac, self.nthreads)\n\t\t\telif self.limb_dark == \"power2\": lc = _power2_ld._power2_ld(self.ds, params.rp, params.u[0], params.u[1], self.fac, self.nthreads)\n\t\t\telif self.limb_dark == \"custom\": lc = _custom_ld._custom_ld(self.ds, params.rp, params.u[0], params.u[1], params.u[2], params.u[3], params.u[4], params.u[5], self.fac, self.nthreads)\n\t\t\telse: raise Exception(\"Invalid limb darkening option\")\n\n\t\t\tif self.inverse == True: lc = 2. - lc\n\n\t\telse: lc = _eclipse._eclipse(self.ds, params.rp, params.fp, self.nthreads)\t\t\t\n\t\tif self.supersample_factor == 1: return lc\n\t\telse: return np.mean(lc.reshape(-1, self.supersample_factor), axis=1)\n\n\tdef _get_phase(self, params, position):\n\t\tif position == \"periastron\": TA = 0.\n\t\telif position == \"primary\": TA = pi/2. - params.w*pi/180.\n\t\telif position == \"secondary\": TA = 3.*pi/2. - params.w*pi/180.\n\t\t\n\t\tE = 2.*np.arctan(np.sqrt((1. - params.ecc)/(1. + params.ecc))*np.tan(TA/2.))\n\t\tM = E - params.ecc*np.sin(E)\n\t\treturn M/2./pi\n\t\n\tdef get_t_periastron(self, params):\n\t\t\"\"\"\n\t\tReturn the time of periastron passage (calculated using `params.t0`).\n\t\t\"\"\"\n\t\tphase = self._get_phase(params, \"primary\")\n\t\treturn params.t0 - params.per*phase\n\n\tdef get_t_secondary(self, params):\n\t\t\"\"\"\n\t\tReturn the time of secondary eclipse center (calculated using `params.t0`).\n\t\t\"\"\"\n\t\tphase = self._get_phase(params, \"primary\")\n\t\tphase2 = self._get_phase(params, \"secondary\")\n\t\treturn params.t0 + params.per*(phase2-phase)\n\n\tdef get_t_conjunction(self, params):\n\t\t\"\"\"\n\t\tReturn the time of primary transit center (calculated using `params.t_secondary`).\n\t\t\"\"\"\n\t\tphase = self._get_phase(params, \"primary\")\n\t\tphase2 = self._get_phase(params, \"secondary\")\n\t\treturn params.t_secondary + params.per*(phase-phase2)\n\n\tdef get_true_anomaly(self):\n\t\t\"\"\"\n\t\tReturn the true anomaly at each time\n\t\t\"\"\"\n\t\tself.f = _rsky._getf(self.t_supersample, self.t0, self.per, self.a,\n\t\t\t\t\t\t\t  self.inc*pi/180., self.ecc, self.w*pi/180.,\n\t\t\t\t\t\t\t  self.transittype, self.nthreads)\n\t\treturn self.f\n\nclass TransitParams(object):\n\t\"\"\"\n\tObject to store the physical parameters of the transit.\n\n\t:param t0: Time of inferior conjunction. \n\t:type t0: float, optional \n\n\t:param t_secondary: Time of secondary eclipse center.\n\t:type t_secondary: float, optional \n\n\t:param per: Orbital period.\n\t:type per: float\n\n\t:param rp: Planet radius [in stellar radii].\n\t:type rp: float\n\n\t:param a: Semi-major axis [in stellar radii].\n\t:type a: float\n\n\t:param inc: Orbital inclination [in degrees].\n\t:type inc: float\n\n\t:param ecc: Orbital eccentricity.\n\t:type ecc: float\n\n\t:param w: Argument of periapse [in degrees]\n\t:type w: float\n\n\t:param u: List of limb darkening coefficients.\n\t:type u: array_like \n\n\t:param limb_dark: Limb darkening model (choice of \"nonlinear\", \"quadratic\", \"exponential\", \"logarithmic\", \"squareroot\", \"linear\", \"uniform\", \"power2\", or \"custom\").\n\t:type limb_dark: str\n\n\t:param fp: Planet-to-star flux ratio (for secondary eclipse models).\n\t:type fp: float, optional\n\n\t.. note::  \n\t\t- Units for the orbital period and ephemeris can be anything as long as they are consistent (e.g. both in days). \n\t\t- The orbital path is calculated based on `t0` for primary transits and `t_secondary` for secondary eclipses.\n\n\t:Example:\n\t\n\t>>> import batman\n\t>>> params = batman.TransitParams()\n\t>>> params.t0 = 0. \t\t\t\t#time of inferior conjunction\n\t>>> params.per = 1.\t\t\t\t#orbital period\t\n\t>>> params.rp = 0.1\t\t\t\t#planet radius (in units of stellar radii)\n\t>>> params.a = 15.\t\t\t\t#semi-major axis (in units of stellar radii)\n\t>>> params.inc = 87.\t\t\t\t#orbital inclination (in degrees)\t\n\t>>> params.ecc = 0.\t\t\t\t#eccentricity\t\n\t>>> params.w = 90.\t\t\t\t#longitude of periastron (in degrees) \n\t>>> params.u = [0.1, 0.3] \t      \t        #limb darkening coefficients\n\t>>> params.limb_dark = \"quadratic\"          \t#limb darkening model\n\t\"\"\"\n\tdef __init__(self):\n\t\tself.t0 = None\n\t\tself.per = None\n\t\tself.rp = None\n\t\tself.a = None\n\t\tself.inc = None\n\t\tself.ecc = None\n\t\tself.w = None\n\t\tself.u = None\n\t\tself.limb_dark = None\n\t\tself.fp = None\n\t\tself.t_secondary = None\n\n", "meta": {"hexsha": "cb1f6cf5504c6c56b3125a110547870ca2e57e95", "size": 16848, "ext": "py", "lang": "Python", "max_stars_repo_path": "source/batman-package-2.4.6/batman/transitmodel.py", "max_stars_repo_name": "Simske/exostriker", "max_stars_repo_head_hexsha": "587b0af4c9cadb46637a4ac61a5392a596e966b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/batman-package-2.4.6/batman/transitmodel.py", "max_issues_repo_name": "Simske/exostriker", "max_issues_repo_head_hexsha": "587b0af4c9cadb46637a4ac61a5392a596e966b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/batman-package-2.4.6/batman/transitmodel.py", "max_forks_repo_name": "Simske/exostriker", "max_forks_repo_head_hexsha": "587b0af4c9cadb46637a4ac61a5392a596e966b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.875, "max_line_length": 190, "alphanum_fraction": 0.6890432099, "include": true, "reason": "import numpy", "num_tokens": 5161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.18846262377175693}}
{"text": "#!/usr/bin/env python -u \n'''\npDMET: Density Matrix Embedding theory for Periodic Systems\nCopyright (C) 2018 Hung Q. Pham. All Rights Reserved.\nA few functions in pDMET are modifed from QC-DMET Copyright (C) 2015 Sebastian Wouters\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nEmail: Hung Q. Pham <pqh3.14@gmail.com>\n'''\n\nimport os, datetime\nimport numpy as np\n                   \n            \n            \nBOHR = 0.52917721092\ndef make_imp_orbs(cell, w90, impCluster, threshold=0.5, rm_list=None, add_list=None):\n    '''Attribute:\n            cell            : PySCF cell object\n            w90             : the w90 object for MLWFs\n            impCluster      : a list of the atom labels starting from 1\n       Return:\n            impOrbs         : list of the MWLFs that belong to the impCluster\n         \n    '''\n    impCluster = np.asarray(impCluster)\n    \n    def put_atoms_in_unitcell(frac_coors):\n        coors = frac_coors.flatten()\n        coors[coors < 0.0] = coors[coors < 0.0] + 1.0\n        coors[coors > 1.0] = coors[coors > 1.0] - 1.0        \n        return coors.reshape(-1,3)\n    \n    assert impCluster.max() <= cell.natm, \\\n            \"Check the impCluster. There are {0} atoms in the unit cell\".format(cell.natm)\n    \n    # Make sure all the atoms inside the unit cell\n    lattice = cell.lattice_vectors() * BOHR\n    inv_lattice = np.linalg.inv(lattice) \n    abs_coors = cell.atom_coords() * BOHR\n    frac_coors = abs_coors @ inv_lattice\n    abs_coors = put_atoms_in_unitcell(frac_coors) @ lattice\n    impAtoms = abs_coors[impCluster - 1]\n    \n    # Make sure all the MLWFs inside the unit cell\n    num_wann = w90.wann_centres.shape[0]\n    MLWFs_coors = w90.wann_centres\n    MLWFs_frac_coors = MLWFs_coors @ inv_lattice\n    MLWFs_coors = put_atoms_in_unitcell(MLWFs_frac_coors) @ lattice\n    \n    # Check the distance between MLWFs and the imp atoms\n    tmp = np.repeat(MLWFs_coors[:,np.newaxis,:], impAtoms.shape[0], axis=1)\n    distance = np.sqrt(np.sum((tmp - impAtoms)**2, axis=2))\n    min_distance = distance.min(axis=1)\n    min_distance_idx = np.argmin(distance, axis=1)  \n\n    # Set the minimum distance of the undesired orbitals to 100.0, hence they get removed\n    if rm_list is not None:\n        min_distance[rm_list] = 100.0\n    if add_list is not None:\n        min_distance[add_list] = 0.01\n        \n    # Label by 1 only the impurity orbitals\n    impOrbs = np.zeros(num_wann, dtype=int)\n    impOrbs[min_distance < threshold] = 1\n    \n\n    # Group the impurity orbitals by their corresponding atoms\n    Norbs = MLWFs_coors.shape[0]\n    impOrbs_idx = np.arange(Norbs)[impOrbs == 1]\n    atom_idx = min_distance_idx[min_distance < threshold]\n    impAtms = []\n    for i, atm in enumerate(impCluster):\n        impAtms.append(impOrbs_idx[atom_idx == i])\n    \n    return impOrbs, impAtms\n    ", "meta": {"hexsha": "ee62df066d98517d0f1daff1c3bedc507565a6b5", "size": 3298, "ext": "py", "lang": "Python", "max_stars_repo_path": "pdmet/tools/misc.py", "max_stars_repo_name": "hungpham2017/pdmet", "max_stars_repo_head_hexsha": "50848c9f22879f8154e86af783d8036f304bac54", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pdmet/tools/misc.py", "max_issues_repo_name": "hungpham2017/pdmet", "max_issues_repo_head_hexsha": "50848c9f22879f8154e86af783d8036f304bac54", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pdmet/tools/misc.py", "max_forks_repo_name": "hungpham2017/pdmet", "max_forks_repo_head_hexsha": "50848c9f22879f8154e86af783d8036f304bac54", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4772727273, "max_line_length": 90, "alphanum_fraction": 0.6688902365, "include": true, "reason": "import numpy", "num_tokens": 923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.18846262013331805}}
{"text": "import os\nimport time\nimport torch\nimport imageio\nimport numpy as np\nimport torch.nn.functional as F\n\nfrom run_nerf_helpers import *\nfrom utils.flow_utils import flow_to_image\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\ndef batchify_rays(t, chain_5frames,\n                rays_flat, chunk=1024*16, **kwargs):\n    \"\"\"Render rays in smaller minibatches to avoid OOM.\n    \"\"\"\n    all_ret = {}\n    for i in range(0, rays_flat.shape[0], chunk):\n        ret = render_rays(t, chain_5frames, rays_flat[i:i+chunk], **kwargs)\n        for k in ret:\n            if k not in all_ret:\n                all_ret[k] = []\n            all_ret[k].append(ret[k])\n\n    all_ret = {k: torch.cat(all_ret[k], 0) for k in all_ret}\n    return all_ret\n\n\ndef render(t, chain_5frames,\n           H, W, focal, focal_render=None,\n           chunk=1024*16, rays=None, c2w=None, ndc=True,\n           near=0., far=1.,\n           use_viewdirs=False, c2w_staticcam=None,\n           **kwargs):\n    \"\"\"Render rays\n    Args:\n      H: int. Height of image in pixels.\n      W: int. Width of image in pixels.\n      focal: float. Focal length of pinhole camera.\n      chunk: int. Maximum number of rays to process simultaneously. Used to\n        control maximum memory usage. Does not affect final results.\n      rays: array of shape [2, batch_size, 3]. Ray origin and direction for\n        each example in batch.\n      c2w: array of shape [3, 4]. Camera-to-world transformation matrix.\n      ndc: bool. If True, represent ray origin, direction in NDC coordinates.\n      near: float or array of shape [batch_size]. Nearest distance for a ray.\n      far: float or array of shape [batch_size]. Farthest distance for a ray.\n      use_viewdirs: bool. If True, use viewing direction of a point in space in model.\n      c2w_staticcam: array of shape [3, 4]. If not None, use this transformation matrix for\n       camera while using other c2w argument for viewing directions.\n    Returns:\n      rgb_map: [batch_size, 3]. Predicted RGB values for rays.\n      disp_map: [batch_size]. Disparity map. Inverse of depth.\n      acc_map: [batch_size]. Accumulated opacity (alpha) along a ray.\n      extras: dict with everything returned by render_rays().\n    \"\"\"\n\n    if c2w is not None:\n        # special case to render full image\n        if focal_render is not None:\n            # Render full image using different focal length for dolly zoom. Inference only.\n            rays_o, rays_d = get_rays(H, W, focal_render, c2w)\n        else:\n            rays_o, rays_d = get_rays(H, W, focal, c2w)\n    else:\n        # use provided ray batch\n        rays_o, rays_d = rays\n\n    if use_viewdirs:\n        # provide ray directions as input\n        viewdirs = rays_d\n        if c2w_staticcam is not None:\n            raise NotImplementedError\n        # Make all directions unit magnitude.\n        # shape: [batch_size, 3]\n        viewdirs = viewdirs / torch.norm(viewdirs, dim=-1, keepdim=True)\n        viewdirs = torch.reshape(viewdirs, [-1, 3]).float()\n\n    sh = rays_d.shape # [..., 3]\n    if ndc:\n        # for forward facing scenes\n        rays_o, rays_d = ndc_rays(H, W, focal, 1., rays_o, rays_d)\n\n    # Create ray batch\n    rays_o = torch.reshape(rays_o, [-1, 3]).float()\n    rays_d = torch.reshape(rays_d, [-1, 3]).float()\n    near, far = near * \\\n        torch.ones_like(rays_d[..., :1]), far * torch.ones_like(rays_d[..., :1])\n\n    # (ray origin, ray direction, min dist, max dist) for each ray\n    rays = torch.cat([rays_o, rays_d, near, far], -1)\n    if use_viewdirs:\n        rays = torch.cat([rays, viewdirs], -1)\n\n    # Render and reshape\n    all_ret = batchify_rays(t, chain_5frames,\n                        rays, chunk, **kwargs)\n    for k in all_ret:\n        k_sh = list(sh[:-1]) + list(all_ret[k].shape[1:])\n        all_ret[k] = torch.reshape(all_ret[k], k_sh)\n\n    return all_ret\n\n\ndef render_path_batch(render_poses, time2render,\n                    hwf, chunk, render_kwargs, savedir=None, focal2render=None):\n    \"\"\"Render frames using batch.\n\n    Args:\n      render_poses: array of shape [num_frame, 3, 4]. Camera-to-world transformation matrix of each frame.\n      time2render: array of shape [num_frame]. Time of each frame.\n      hwf: list. [Height of image in pixels, Width of image in pixels, Focal length of pinhole camera]\n      chunk: int. Maximum number of rays to process simultaneously. Used to\n        control maximum memory usage. Does not affect final results.\n      render_kwargs: dictionary. args for the render function.\n      savedir: string. Directory to save results.\n      focal2render: list. Only used to perform dolly-zoom.\n    Returns:\n      ret_dict: dictionary. Final and intermediate results.\n    \"\"\"\n    H, W, focal = hwf\n\n    ret_dict = {}\n    rgbs = []\n    rgbs_d = []\n    rgbs_s = []\n    dynamicnesses = []\n\n    time_curr = time.time()\n    for i, c2w in enumerate(render_poses):\n\n        print(i, time.time() - time_curr)\n        time_curr = time.time()\n\n        t = time2render[i]\n\n        if focal2render is not None:\n            # Render full image using different focal length\n            rays_o, rays_d = get_rays(H, W, focal2render[i], c2w)\n        else:\n            rays_o, rays_d = get_rays(H, W, focal, c2w)\n        rays_o = torch.reshape(rays_o, (-1, 3))\n        rays_d = torch.reshape(rays_d, (-1, 3))\n        batch_rays = torch.stack([rays_o, rays_d], 0)\n        rgb = []\n        rgb_d = []\n        rgb_s = []\n        dynamicness = []\n        for j in range(0, batch_rays.shape[1], chunk):\n            # print(j, '/', batch_rays.shape[1])\n            ret = render(t, False,\n                         H, W, focal,\n                         chunk=chunk, rays=batch_rays[:, j:j+chunk, :],\n                         **render_kwargs)\n            rgb.append(ret['rgb_map_full'].cpu())\n            rgb_d.append(ret['rgb_map_d'].cpu())\n            rgb_s.append(ret['rgb_map_s'].cpu())\n            dynamicness.append(ret['dynamicness_map'].cpu())\n        rgb = torch.reshape(torch.cat(rgb, 0), (H, W, 3)).numpy()\n        rgb_d = torch.reshape(torch.cat(rgb_d, 0), (H, W, 3)).numpy()\n        rgb_s = torch.reshape(torch.cat(rgb_s, 0), (H, W, 3)).numpy()\n        dynamicness = torch.reshape(torch.cat(dynamicness, 0), (H, W)).numpy()\n\n        # Not a good solution. Should take care of this when preparing the data.\n        if W%2 == 1:\n            # rgb = cv2.resize(rgb, (W - 1, H))\n            rgb = rgb[:, :-1, :]\n            rgb_d = rgb_d[:, :-1, :]\n            rgb_s = rgb_s[:, :-1, :]\n            dynamicness = dynamicness[:, :-1]\n        rgbs.append(rgb)\n        rgbs_d.append(rgb_d)\n        rgbs_s.append(rgb_s)\n        dynamicnesses.append(dynamicness)\n\n        if savedir is not None:\n            rgb8 = to8b(rgbs[-1])\n            filename = os.path.join(savedir, '{:03d}.png'.format(i))\n            imageio.imwrite(filename, rgb8)\n\n    ret_dict['rgbs'] = np.stack(rgbs, 0)\n    ret_dict['rgbs_d'] = np.stack(rgbs_d, 0)\n    ret_dict['rgbs_s'] = np.stack(rgbs_s, 0)\n    ret_dict['dynamicnesses'] = np.stack(dynamicnesses, 0)\n\n    return ret_dict\n\n\ndef render_path(render_poses,\n                time2render,\n                hwf,\n                chunk,\n                render_kwargs,\n                savedir=None,\n                flows_gt_f=None,\n                flows_gt_b=None,\n                focal2render=None):\n    \"\"\"Render frames.\n\n    Args:\n      render_poses: array of shape [num_frame, 3, 4]. Camera-to-world transformation matrix of each frame.\n      time2render: array of shape [num_frame]. Time of each frame.\n      hwf: list. [Height of image in pixels, Width of image in pixels, Focal length of pinhole camera]\n      chunk: int. Maximum number of rays to process simultaneously. Used to\n        control maximum memory usage. Does not affect final results.\n      render_kwargs: dictionary. args for the render function.\n      savedir: string. Directory to save results.\n      focal2render: list. Only used to perform dolly-zoom.\n    Returns:\n      ret_dict: dictionary. Final and intermediate results.\n    \"\"\"\n    H, W, focal = hwf\n\n    ret_dict = {}\n    rgbs = []\n    rgbs_d = []\n    rgbs_s = []\n    depths = []\n    depths_d = []\n    depths_s = []\n    flows_f = []\n    flows_b = []\n    dynamicness = []\n    blending = []\n\n    grid = np.stack(np.meshgrid(np.arange(W, dtype=np.float32),\n                       np.arange(H, dtype=np.float32), indexing='xy'), -1)\n    grid = torch.Tensor(grid)\n    time_curr = time.time()\n    for i, c2w in enumerate(render_poses):\n        t = time2render[i]\n        pose = c2w[:3, :4]\n        print(i, time.time() - time_curr)\n        time_curr = time.time()\n\n        if focal2render is None:\n            # Normal rendering.\n            ret = render(t, False,\n                         H, W, focal,\n                         chunk=1024*32, c2w=pose,\n                         **render_kwargs)\n        else:\n            # Render image using different focal length.\n            ret = render(t, False,\n                         H, W, focal, focal_render=focal2render[i],\n                         chunk=1024*32, c2w=pose,\n                         **render_kwargs)\n\n        rgbs.append(ret['rgb_map_full'].cpu().numpy())\n        rgbs_d.append(ret['rgb_map_d'].cpu().numpy())\n        rgbs_s.append(ret['rgb_map_s'].cpu().numpy())\n\n        depths.append(ret['depth_map_full'].cpu().numpy())\n        depths_d.append(ret['depth_map_d'].cpu().numpy())\n        depths_s.append(ret['depth_map_s'].cpu().numpy())\n\n        dynamicness.append(ret['dynamicness_map'].cpu().numpy())\n\n        if flows_gt_f is not None:\n            # Reconstruction. Flow is caused by both changing camera and changing time.\n            pose_f = render_poses[min(i + 1, int(len(render_poses)) - 1), :3, :4]\n            pose_b = render_poses[max(i - 1, 0), :3, :4]\n        else:\n            # Non training view-time. Flow is caused by changing time (just for visualization).\n            pose_f = render_poses[i, :3, :4]\n            pose_b = render_poses[i, :3, :4]\n\n        # Sceneflow induced optical flow\n        induced_flow_f_ = induce_flow(H, W, focal, pose_f, ret['weights_d'], ret['raw_pts_f'], grid[..., :2])\n        induced_flow_b_ = induce_flow(H, W, focal, pose_b, ret['weights_d'], ret['raw_pts_b'], grid[..., :2])\n\n        if (i + 1) >= len(render_poses):\n            induced_flow_f = np.zeros((H, W, 2))\n        else:\n            induced_flow_f = induced_flow_f_.cpu().numpy()\n        if flows_gt_f is not None:\n            flow_gt_f = flows_gt_f[i].cpu().numpy()\n            induced_flow_f = np.concatenate((induced_flow_f, flow_gt_f), 0)\n        induced_flow_f_img = flow_to_image(induced_flow_f)\n        flows_f.append(induced_flow_f_img)\n\n        if (i - 1) < 0:\n            induced_flow_b = np.zeros((H, W, 2))\n        else:\n            induced_flow_b = induced_flow_b_.cpu().numpy()\n        if flows_gt_b is not None:\n            flow_gt_b = flows_gt_b[i].cpu().numpy()\n            induced_flow_b = np.concatenate((induced_flow_b, flow_gt_b), 0)\n        induced_flow_b_img = flow_to_image(induced_flow_b)\n        flows_b.append(induced_flow_b_img)\n\n        if i == 0:\n            ret_dict['sceneflow_f_NDC'] = ret['sceneflow_f'].cpu().numpy()\n            ret_dict['sceneflow_b_NDC'] = ret['sceneflow_b'].cpu().numpy()\n            ret_dict['blending'] = ret['blending'].cpu().numpy()\n\n            weights = np.concatenate((ret['weights_d'][..., None].cpu().numpy(),\n                                      ret['weights_s'][..., None].cpu().numpy(),\n                                      ret['blending'][..., None].cpu().numpy(),\n                                      ret['weights_full'][..., None].cpu().numpy()))\n            ret_dict['weights'] = np.moveaxis(weights, [0, 1, 2, 3], [1, 2, 0, 3])\n\n        if savedir is not None:\n            rgb8 = to8b(rgbs[-1])\n            filename = os.path.join(savedir, '{:03d}.png'.format(i))\n            imageio.imwrite(filename, rgb8)\n\n    ret_dict['rgbs'] = np.stack(rgbs, 0)\n    ret_dict['rgbs_d'] = np.stack(rgbs_d, 0)\n    ret_dict['rgbs_s'] = np.stack(rgbs_s, 0)\n    ret_dict['depths'] = np.stack(depths, 0)\n    ret_dict['depths_d'] = np.stack(depths_d, 0)\n    ret_dict['depths_s'] = np.stack(depths_s, 0)\n    ret_dict['dynamicness'] = np.stack(dynamicness, 0)\n    ret_dict['flows_f'] = np.stack(flows_f, 0)\n    ret_dict['flows_b'] = np.stack(flows_b, 0)\n\n    return ret_dict\n\n\ndef raw2outputs(raw_s,\n                raw_d,\n                blending,\n                z_vals,\n                rays_d,\n                raw_noise_std):\n    \"\"\"Transforms model's predictions to semantically meaningful values.\n\n    Args:\n      raw_d: [num_rays, num_samples along ray, 4]. Prediction from Dynamic model.\n      raw_s: [num_rays, num_samples along ray, 4]. Prediction from Static model.\n      z_vals: [num_rays, num_samples along ray]. Integration time.\n      rays_d: [num_rays, 3]. Direction of each ray.\n\n    Returns:\n      rgb_map: [num_rays, 3]. Estimated RGB color of a ray.\n      disp_map: [num_rays]. Disparity map. Inverse of depth map.\n      acc_map: [num_rays]. Sum of weights along each ray.\n      weights: [num_rays, num_samples]. Weights assigned to each sampled color.\n      depth_map: [num_rays]. Estimated distance to object.\n    \"\"\"\n    # Function for computing density from model prediction. This value is\n    # strictly between [0, 1].\n    def raw2alpha(raw, dists, act_fn=F.relu): return 1.0 - \\\n        torch.exp(-act_fn(raw) * dists)\n\n    # Compute 'distance' (in time) between each integration time along a ray.\n    dists = z_vals[..., 1:] - z_vals[..., :-1]\n\n    # The 'distance' from the last integration time is infinity.\n    dists = torch.cat(\n        [dists, torch.Tensor([1e10]).expand(dists[..., :1].shape)],\n         -1) # [N_rays, N_samples]\n\n    # Multiply each distance by the norm of its corresponding direction ray\n    # to convert to real world distance (accounts for non-unit directions).\n    dists = dists * torch.norm(rays_d[..., None, :], dim=-1)\n\n    # Extract RGB of each sample position along each ray.\n    rgb_d = torch.sigmoid(raw_d[..., :3])  # [N_rays, N_samples, 3]\n    rgb_s = torch.sigmoid(raw_s[..., :3])  # [N_rays, N_samples, 3]\n\n    # Add noise to model's predictions for density. Can be used to\n    # regularize network during training (prevents floater artifacts).\n    noise = 0.\n    if raw_noise_std > 0.:\n        noise = torch.randn(raw_d[..., 3].shape) * raw_noise_std\n\n    # Predict density of each sample along each ray. Higher values imply\n    # higher likelihood of being absorbed at this point.\n    alpha_d = raw2alpha(raw_d[..., 3] + noise, dists) # [N_rays, N_samples]\n    alpha_s = raw2alpha(raw_s[..., 3] + noise, dists) # [N_rays, N_samples]\n    alphas  = 1. - (1. - alpha_s) * (1. - alpha_d) # [N_rays, N_samples]\n\n    T_d    = torch.cumprod(torch.cat([torch.ones((alpha_d.shape[0], 1)), 1. - alpha_d + 1e-10], -1), -1)[:, :-1]\n    T_s    = torch.cumprod(torch.cat([torch.ones((alpha_s.shape[0], 1)), 1. - alpha_s + 1e-10], -1), -1)[:, :-1]\n    T_full = torch.cumprod(torch.cat([torch.ones((alpha_d.shape[0], 1)), (1. - alpha_d * blending) * (1. - alpha_s * (1. - blending)) + 1e-10], -1), -1)[:, :-1]\n    # T_full = torch.cumprod(torch.cat([torch.ones((alpha_d.shape[0], 1)), torch.pow(1. - alpha_d + 1e-10, blending) * torch.pow(1. - alpha_s + 1e-10, 1. - blending)], -1), -1)[:, :-1]\n    # T_full = torch.cumprod(torch.cat([torch.ones((alpha_d.shape[0], 1)), (1. - alpha_d) * (1. - alpha_s) + 1e-10], -1), -1)[:, :-1]\n\n    # Compute weight for RGB of each sample along each ray.  A cumprod() is\n    # used to express the idea of the ray not having reflected up to this\n    # sample yet.\n    weights_d = alpha_d * T_d\n    weights_s = alpha_s * T_s\n    weights_full = (alpha_d * blending + alpha_s * (1. - blending)) * T_full\n    # weights_full = alphas * T_full\n\n    # Computed weighted color of each sample along each ray.\n    rgb_map_d = torch.sum(weights_d[..., None] * rgb_d, -2)\n    rgb_map_s = torch.sum(weights_s[..., None] * rgb_s, -2)\n    rgb_map_full = torch.sum(\n        (T_full * alpha_d * blending)[..., None] * rgb_d + \\\n        (T_full * alpha_s * (1. - blending))[..., None] * rgb_s, -2)\n\n    # Estimated depth map is expected distance.\n    depth_map_d = torch.sum(weights_d * z_vals, -1)\n    depth_map_s = torch.sum(weights_s * z_vals, -1)\n    depth_map_full = torch.sum(weights_full * z_vals, -1)\n\n    # Sum of weights along each ray. This value is in [0, 1] up to numerical error.\n    acc_map_d = torch.sum(weights_d, -1)\n    acc_map_s = torch.sum(weights_s, -1)\n    acc_map_full = torch.sum(weights_full, -1)\n\n    # Computed dynamicness\n    dynamicness_map = torch.sum(weights_full * blending, -1)\n    # dynamicness_map = 1 - T_d[..., -1]\n\n    return rgb_map_full, depth_map_full, acc_map_full, weights_full, \\\n           rgb_map_s, depth_map_s, acc_map_s, weights_s, \\\n           rgb_map_d, depth_map_d, acc_map_d, weights_d, dynamicness_map\n\n\ndef raw2outputs_d(raw_d,\n                  z_vals,\n                  rays_d,\n                  raw_noise_std):\n\n    # Function for computing density from model prediction. This value is\n    # strictly between [0, 1].\n    def raw2alpha(raw, dists, act_fn=F.relu): return 1.0 - \\\n        torch.exp(-act_fn(raw) * dists)\n\n    # Compute 'distance' (in time) between each integration time along a ray.\n    dists = z_vals[..., 1:] - z_vals[..., :-1]\n\n    # The 'distance' from the last integration time is infinity.\n    dists = torch.cat(\n        [dists, torch.Tensor([1e10]).expand(dists[..., :1].shape)],\n        -1)  # [N_rays, N_samples]\n\n    # Multiply each distance by the norm of its corresponding direction ray\n    # to convert to real world distance (accounts for non-unit directions).\n    dists = dists * torch.norm(rays_d[..., None, :], dim=-1)\n\n    # Extract RGB of each sample position along each ray.\n    rgb_d = torch.sigmoid(raw_d[..., :3])  # [N_rays, N_samples, 3]\n\n    # Add noise to model's predictions for density. Can be used to\n    # regularize network during training (prevents floater artifacts).\n    noise = 0.\n    if raw_noise_std > 0.:\n        noise = torch.randn(raw_d[..., 3].shape) * raw_noise_std\n\n    # Predict density of each sample along each ray. Higher values imply\n    # higher likelihood of being absorbed at this point.\n    alpha_d = raw2alpha(raw_d[..., 3] + noise, dists)  # [N_rays, N_samples]\n\n    T_d = torch.cumprod(torch.cat([torch.ones((alpha_d.shape[0], 1)), 1. - alpha_d + 1e-10], -1), -1)[:, :-1]\n    # Compute weight for RGB of each sample along each ray.  A cumprod() is\n    # used to express the idea of the ray not having reflected up to this\n    # sample yet.\n    weights_d = alpha_d * T_d\n\n    # Computed weighted color of each sample along each ray.\n    rgb_map_d = torch.sum(weights_d[..., None] * rgb_d, -2)\n\n    return rgb_map_d, weights_d\n\n\ndef render_rays(t,\n                chain_5frames,\n                ray_batch,\n                network_fn_d,\n                network_fn_s,\n                network_query_fn_d,\n                network_query_fn_s,\n                N_samples,\n                num_img,\n                DyNeRF_blending,\n                pretrain=False,\n                lindisp=False,\n                perturb=0.,\n                N_importance=0,\n                raw_noise_std=0.,\n                inference=False):\n\n    \"\"\"Volumetric rendering.\n    Args:\n      ray_batch: array of shape [batch_size, ...]. All information necessary\n        for sampling along a ray, including: ray origin, ray direction, min\n        dist, max dist, and unit-magnitude viewing direction.\n      network_fn_d: function. Model for predicting RGB and density at each point\n        in space.\n      network_query_fn_d: function used for passing queries to network_fn_d.\n      N_samples: int. Number of different times to sample along each ray.\n      lindisp: bool. If True, sample linearly in inverse depth rather than in depth.\n      perturb: float, 0 or 1. If non-zero, each ray is sampled at stratified\n        random points in time.\n      N_importance: int. Number of additional times to sample along each ray.\n        These samples are only passed to network_fine.\n      network_fine: \"fine\" network with same spec as network_fn.\n      raw_noise_std: ...\n    Returns:\n      rgb_map: [num_rays, 3]. Estimated RGB color of a ray. Comes from fine model.\n      disp_map: [num_rays]. Disparity map. 1 / depth.\n      acc_map: [num_rays]. Accumulated opacity along each ray. Comes from fine model.\n      raw: [num_rays, num_samples, 4]. Raw predictions from model.\n      rgb0: See rgb_map. Output for coarse model.\n      disp0: See disp_map. Output for coarse model.\n      acc0: See acc_map. Output for coarse model.\n      z_std: [num_rays]. Standard deviation of distances along ray for each\n        sample.\n    \"\"\"\n\n    # batch size\n    N_rays = ray_batch.shape[0]\n\n    # ray_batch: [N_rays, 11]\n    # rays_o:    [N_rays, 0:3]\n    # rays_d:    [N_rays, 3:6]\n    # near:      [N_rays, 6:7]\n    # far:       [N_rays, 7:8]\n    # viewdirs:  [N_rays, 8:11]\n\n    # Extract ray origin, direction.\n    rays_o, rays_d = ray_batch[:, 0:3], ray_batch[:, 3:6] # [N_rays, 3] each\n\n    # Extract unit-normalized viewing direction.\n    viewdirs = ray_batch[:, -3:] if ray_batch.shape[-1] > 8 else None\n\n    # Extract lower, upper bound for ray distance.\n    bounds = torch.reshape(ray_batch[..., 6:8], [-1, 1, 2])\n    near, far = bounds[..., 0], bounds[..., 1]\n\n    # Decide where to sample along each ray. Under the logic, all rays will be sampled at\n    # the same times.\n    t_vals = torch.linspace(0., 1., steps=N_samples)\n    if not lindisp:\n        # Space integration times linearly between 'near' and 'far'. Same\n        # integration points will be used for all rays.\n        z_vals = near * (1.-t_vals) + far * (t_vals)\n    else:\n        # Sample linearly in inverse depth (disparity).\n        z_vals = 1./(1./near * (1.-t_vals) + 1./far * (t_vals))\n    z_vals = z_vals.expand([N_rays, N_samples])\n\n    # Perturb sampling time along each ray.\n    if perturb > 0.:\n        # get intervals between samples\n        mids = .5 * (z_vals[..., 1:] + z_vals[..., :-1])\n        upper = torch.cat([mids, z_vals[..., -1:]], -1)\n        lower = torch.cat([z_vals[..., :1], mids], -1)\n        # stratified samples in those intervals\n        t_rand = torch.rand(z_vals.shape)\n        z_vals = lower + (upper - lower) * t_rand\n\n    # Points in space to evaluate model at.\n    pts = rays_o[..., None, :] + rays_d[..., None, :] * \\\n        z_vals[..., :, None] # [N_rays, N_samples, 3]\n\n    # Add the time dimension to xyz.\n    pts_ref = torch.cat([pts, torch.ones_like(pts[..., 0:1]) * t], -1)\n\n    # First pass: we have the staticNeRF results\n    raw_s = network_query_fn_s(pts_ref[..., :3], viewdirs, network_fn_s)\n    # raw_s:          [N_rays, N_samples, 5]\n    # raw_s_rgb:      [N_rays, N_samples, 0:3]\n    # raw_s_a:        [N_rays, N_samples, 3:4]\n    # raw_s_blending: [N_rays, N_samples, 4:5]\n\n    # Second pass: we have the DyanmicNeRF results and the blending weight\n    raw_d = network_query_fn_d(pts_ref, viewdirs, network_fn_d)\n    # raw_d:          [N_rays, N_samples, 11]\n    # raw_d_rgb:      [N_rays, N_samples, 0:3]\n    # raw_d_a:        [N_rays, N_samples, 3:4]\n    # sceneflow_b:    [N_rays, N_samples, 4:7]\n    # sceneflow_f:    [N_rays, N_samples, 7:10]\n    # raw_d_blending: [N_rays, N_samples, 10:11]\n\n    if pretrain:\n        rgb_map_s, _ = raw2outputs_d(raw_s[..., :4],\n                                     z_vals,\n                                     rays_d,\n                                     raw_noise_std)\n        ret = {'rgb_map_s': rgb_map_s}\n        return ret\n\n    raw_s_rgba = raw_s[..., :4]\n    raw_d_rgba = raw_d[..., :4]\n\n    # We need the sceneflow from the dynamicNeRF.\n    sceneflow_b = raw_d[..., 4:7]\n    sceneflow_f = raw_d[..., 7:10]\n\n    if DyNeRF_blending:\n        blending = raw_d[..., 10]\n    else:\n        blending = raw_s[..., 4]\n\n    # if sfmask:\n    #     sceneflow_f = sceneflow_f * blending.detach()[..., None]\n    #     sceneflow_b = sceneflow_b * blending.detach()[..., None]\n\n    # Rerndering.\n    rgb_map_full, depth_map_full, acc_map_full, weights_full, \\\n    rgb_map_s, depth_map_s, acc_map_s, weights_s, \\\n    rgb_map_d, depth_map_d, acc_map_d, weights_d, \\\n    dynamicness_map = raw2outputs(raw_s_rgba,\n                                  raw_d_rgba,\n                                  blending,\n                                  z_vals,\n                                  rays_d,\n                                  raw_noise_std)\n\n    ret = {'rgb_map_full': rgb_map_full, 'depth_map_full': depth_map_full, 'acc_map_full': acc_map_full, 'weights_full': weights_full,\n           'rgb_map_s': rgb_map_s, 'depth_map_s': depth_map_s, 'acc_map_s': acc_map_s, 'weights_s': weights_s,\n           'rgb_map_d': rgb_map_d, 'depth_map_d': depth_map_d, 'acc_map_d': acc_map_d, 'weights_d': weights_d,\n           'dynamicness_map': dynamicness_map}\n\n    t_interval = 1. / num_img * 2.\n    pts_f = torch.cat([pts + sceneflow_f, torch.ones_like(pts[..., 0:1]) * (t + t_interval)], -1)\n    pts_b = torch.cat([pts + sceneflow_b, torch.ones_like(pts[..., 0:1]) * (t - t_interval)], -1)\n\n    ret['sceneflow_b'] = sceneflow_b\n    ret['sceneflow_f'] = sceneflow_f\n    ret['raw_pts'] = pts_ref[..., :3]\n    ret['raw_pts_f'] = pts_f[..., :3]\n    ret['raw_pts_b'] = pts_b[..., :3]\n    ret['blending'] = blending\n\n    # Third pass: we have the DyanmicNeRF results at time t - 1\n    raw_d_b = network_query_fn_d(pts_b, viewdirs, network_fn_d)\n    raw_d_b_rgba = raw_d_b[..., :4]\n    sceneflow_b_b = raw_d_b[..., 4:7]\n    sceneflow_b_f = raw_d_b[..., 7:10]\n\n    # Rerndering t - 1\n    rgb_map_d_b, weights_d_b = raw2outputs_d(raw_d_b_rgba,\n                                             z_vals,\n                                             rays_d,\n                                             raw_noise_std)\n\n    ret['sceneflow_b_f'] = sceneflow_b_f\n    ret['rgb_map_d_b'] = rgb_map_d_b\n    ret['acc_map_d_b'] = torch.abs(torch.sum(weights_d_b - weights_d, -1))\n\n    # Fourth pass: we have the DyanmicNeRF results at time t + 1\n    raw_d_f = network_query_fn_d(pts_f, viewdirs, network_fn_d)\n    raw_d_f_rgba = raw_d_f[..., :4]\n    sceneflow_f_b = raw_d_f[..., 4:7]\n    sceneflow_f_f = raw_d_f[..., 7:10]\n\n    rgb_map_d_f, weights_d_f = raw2outputs_d(raw_d_f_rgba,\n                                             z_vals,\n                                             rays_d,\n                                             raw_noise_std)\n\n    ret['sceneflow_f_b'] = sceneflow_f_b\n    ret['rgb_map_d_f'] = rgb_map_d_f\n    ret['acc_map_d_f'] = torch.abs(torch.sum(weights_d_f - weights_d, -1))\n\n    if inference:\n        return ret\n\n    # Also consider time t - 2 and t + 2 (Learn from NSFF)\n\n    # Fifth pass: we have the DyanmicNeRF results at time t - 2\n    pts_b_b = torch.cat([pts_b[..., :3] + sceneflow_b_b, torch.ones_like(pts[..., 0:1]) * (t - t_interval * 2)], -1)\n    ret['raw_pts_b_b'] = pts_b_b[..., :3]\n\n    if chain_5frames:\n        raw_d_b_b = network_query_fn_d(pts_b_b, viewdirs, network_fn_d)\n        raw_d_b_b_rgba = raw_d_b_b[..., :4]\n        rgb_map_d_b_b, _ = raw2outputs_d(raw_d_b_b_rgba,\n                                      z_vals,\n                                      rays_d,\n                                      raw_noise_std)\n\n        ret['rgb_map_d_b_b'] = rgb_map_d_b_b\n\n    # Sixth pass: we have the DyanmicNeRF results at time t + 2\n    pts_f_f = torch.cat([pts_f[..., :3] + sceneflow_f_f, torch.ones_like(pts[..., 0:1]) * (t + t_interval * 2)], -1)\n    ret['raw_pts_f_f'] = pts_f_f[..., :3]\n\n    if chain_5frames:\n        raw_d_f_f = network_query_fn_d(pts_f_f, viewdirs, network_fn_d)\n        raw_d_f_f_rgba = raw_d_f_f[..., :4]\n        rgb_map_d_f_f, _ = raw2outputs_d(raw_d_f_f_rgba,\n                                      z_vals,\n                                      rays_d,\n                                      raw_noise_std)\n\n        ret['rgb_map_d_f_f'] = rgb_map_d_f_f\n\n    for k in ret:\n        if torch.isnan(ret[k]).any() or torch.isinf(ret[k]).any():\n            print(f\"! [Numerical Error] {k} contains nan or inf.\")\n            import ipdb; ipdb.set_trace()\n\n    return ret\n", "meta": {"hexsha": "d1eaae1a5477891d42279624c0ed426052b9fb6c", "size": 28187, "ext": "py", "lang": "Python", "max_stars_repo_path": "render_utils.py", "max_stars_repo_name": "McMvMc/DVS_compare", "max_stars_repo_head_hexsha": "9e0408bfe2a3217f75f3349d505498c76eac3400", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 122, "max_stars_repo_stars_event_min_datetime": "2021-12-14T03:46:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:10:13.000Z", "max_issues_repo_path": "render_utils.py", "max_issues_repo_name": "McMvMc/DVS_compare", "max_issues_repo_head_hexsha": "9e0408bfe2a3217f75f3349d505498c76eac3400", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2022-01-17T16:00:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T02:57:19.000Z", "max_forks_repo_path": "render_utils.py", "max_forks_repo_name": "McMvMc/DVS_compare", "max_forks_repo_head_hexsha": "9e0408bfe2a3217f75f3349d505498c76eac3400", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-12-17T14:08:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T09:08:43.000Z", "avg_line_length": 40.6152737752, "max_line_length": 184, "alphanum_fraction": 0.5896689963, "include": true, "reason": "import numpy", "num_tokens": 7737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3522017820478896, "lm_q1q2_score": 0.18846262013331802}}
{"text": "# Copyright (C) 2015 Atsushi Togo\n# All rights reserved.\n#\n# This file is part of spglib.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n#   notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n#   notice, this list of conditions and the following disclaimer in\n#   the documentation and/or other materials provided with the\n#   distribution.\n#\n# * Neither the name of the spglib project nor the names of its\n#   contributors may be used to endorse or promote products derived\n#   from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nfrom phonopy import _spglib as spg\nimport numpy as np\n\n\nclass SpglibError(object):\n    message = \"no error\"\n\n\nspglib_error = SpglibError()\n\n\ndef get_version():\n    _set_no_error()\n    return tuple(spg.version())\n\n\ndef get_symmetry(cell, symprec=1e-5, angle_tolerance=-1.0):\n    \"\"\"This gives crystal symmetry operations from a crystal structure.\n\n    Args:\n        cell: Crystal structrue given either in Atoms object or tuple.\n            In the case given by a tuple, it has to follow the form below,\n            (Lattice parameters in a 3x3 array (see the detail below),\n             Fractional atomic positions in an Nx3 array,\n             Integer numbers to distinguish species in a length N array,\n             (optional) Collinear magnetic moments in a length N array),\n            where N is the number of atoms.\n            Lattice parameters are given in the form:\n                [[a_x, a_y, a_z],\n                 [b_x, b_y, b_z],\n                 [c_x, c_y, c_z]]\n        symprec:\n            float: Symmetry search tolerance in the unit of length.\n        angle_tolerance:\n            float: Symmetry search tolerance in the unit of angle deg.\n                If the value is negative, an internally optimized routine\n                is used to judge symmetry.\n\n    Return:\n        A dictionary: Rotation parts and translation parts. Dictionary keys:\n            'rotations': Gives the numpy 'intc' array of the rotation matrices.\n            'translations': Gives the numpy 'double' array of fractional\n                translations with respect to a, b, c axes.\n\n    \"\"\"\n    _set_no_error()\n\n    lattice, positions, numbers, magmoms = _expand_cell(cell)\n    if lattice is None:\n        return None\n\n    multi = 48 * len(positions)\n    rotation = np.zeros((multi, 3, 3), dtype='intc')\n    translation = np.zeros((multi, 3), dtype='double')\n\n    # Get symmetry operations\n    if magmoms is None:\n        dataset = get_symmetry_dataset(cell,\n                                       symprec=symprec,\n                                       angle_tolerance=angle_tolerance)\n        if dataset is None:\n            return None\n        else:\n            return {'rotations': dataset['rotations'],\n                    'translations': dataset['translations'],\n                    'equivalent_atoms': dataset['equivalent_atoms']}\n    else:\n        equivalent_atoms = np.zeros(len(magmoms), dtype='intc')\n        num_sym = spg.symmetry_with_collinear_spin(rotation,\n                                                   translation,\n                                                   equivalent_atoms,\n                                                   lattice,\n                                                   positions,\n                                                   numbers,\n                                                   magmoms,\n                                                   symprec,\n                                                   angle_tolerance)\n        _set_error_message()\n        if num_sym == 0:\n            return None\n        else:\n            return {'rotations': np.array(rotation[:num_sym],\n                                          dtype='intc', order='C'),\n                    'translations': np.array(translation[:num_sym],\n                                             dtype='double', order='C'),\n                    'equivalent_atoms': equivalent_atoms}\n\n\ndef get_symmetry_dataset(cell,\n                         symprec=1e-5,\n                         angle_tolerance=-1.0,\n                         hall_number=0):\n    \"\"\"Search symmetry dataset from an input cell.\n\n    Args:\n        cell, symprec, angle_tolerance:\n            See the docstring of get_symmetry.\n        hall_number: If a serial number of Hall symbol (>0) is given,\n                     the database corresponding to the Hall symbol is made.\n\n    Return:\n        A dictionary is returned. Dictionary keys:\n            number (int): International space group number\n            international (str): International symbol\n            hall (str): Hall symbol\n            choice (str): Centring, origin, basis vector setting\n            transformation_matrix (3x3 float):\n                Transformation matrix from input lattice to standardized\n                lattice:\n                    L^original = L^standardized * Tmat\n            origin shift (3 float):\n                Origin shift from standardized to input origin\n            rotations (3x3 int), translations (float vector):\n                Rotation matrices and translation vectors. Space group\n                operations are obtained by\n                [(r,t) for r, t in zip(rotations, translations)]\n            wyckoffs (n char): Wyckoff letters\n            equivalent_atoms (n int): Symmetrically equivalent atoms\n            mapping_to_primitive (n int):\n                Original cell atom index mapping to primivie cell atom index\n            Idealized standardized unit cell:\n                std_lattice (3x3 float, row vectors),\n                std_positions (Nx3 float), std_types (N int)\n            std_rotation_matrix:\n                Rigid rotation matrix to rotate from standardized basis\n                vectors to idealized standardized basis vectors\n                    L^idealized = R * L^standardized\n            std_mapping_to_primitive (m int):\n                std_positions index mapping to those of primivie cell atoms\n            pointgroup (str): Pointgroup symbol\n\n        If it fails, None is returned.\n\n    \"\"\"\n    _set_no_error()\n\n    lattice, positions, numbers, _ = _expand_cell(cell)\n    if lattice is None:\n        return None\n\n    spg_ds = spg.dataset(lattice, positions, numbers, hall_number,\n                         symprec, angle_tolerance)\n    if spg_ds is None:\n        _set_error_message()\n        return None\n\n    keys = ('number',\n            'hall_number',\n            'international',\n            'hall',\n            'choice',\n            'transformation_matrix',\n            'origin_shift',\n            'rotations',\n            'translations',\n            'wyckoffs',\n            'site_symmetry_symbols',\n            'equivalent_atoms',\n            'mapping_to_primitive',\n            'std_lattice',\n            'std_types',\n            'std_positions',\n            'std_rotation_matrix',\n            'std_mapping_to_primitive',\n            # 'pointgroup_number',\n            'pointgroup')\n    dataset = {}\n    for key, data in zip(keys, spg_ds):\n        dataset[key] = data\n\n    dataset['international'] = dataset['international'].strip()\n    dataset['hall'] = dataset['hall'].strip()\n    dataset['choice'] = dataset['choice'].strip()\n    dataset['transformation_matrix'] = np.array(\n        dataset['transformation_matrix'], dtype='double', order='C')\n    dataset['origin_shift'] = np.array(dataset['origin_shift'], dtype='double')\n    dataset['rotations'] = np.array(dataset['rotations'],\n                                    dtype='intc', order='C')\n    dataset['translations'] = np.array(dataset['translations'],\n                                       dtype='double', order='C')\n    letters = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    dataset['wyckoffs'] = [letters[x] for x in dataset['wyckoffs']]\n    dataset['site_symmetry_symbols'] = [\n        s.strip() for s in dataset['site_symmetry_symbols']]\n    dataset['equivalent_atoms'] = np.array(dataset['equivalent_atoms'],\n                                           dtype='intc')\n    dataset['mapping_to_primitive'] = np.array(dataset['mapping_to_primitive'],\n                                               dtype='intc')\n    dataset['std_lattice'] = np.array(np.transpose(dataset['std_lattice']),\n                                      dtype='double', order='C')\n    dataset['std_types'] = np.array(dataset['std_types'], dtype='intc')\n    dataset['std_positions'] = np.array(dataset['std_positions'],\n                                        dtype='double', order='C')\n    dataset['std_rotation_matrix'] = np.array(dataset['std_rotation_matrix'],\n                                              dtype='double', order='C')\n    dataset['std_mapping_to_primitive'] = np.array(\n        dataset['std_mapping_to_primitive'], dtype='intc')\n    dataset['pointgroup'] = dataset['pointgroup'].strip()\n\n    _set_error_message()\n    return dataset\n\n\ndef get_spacegroup(cell, symprec=1e-5, angle_tolerance=-1.0, symbol_type=0):\n    \"\"\"Return space group in international table symbol and number as a string.\n\n    If it fails, None is returned.\n    \"\"\"\n    _set_no_error()\n\n    dataset = get_symmetry_dataset(cell,\n                                   symprec=symprec,\n                                   angle_tolerance=angle_tolerance)\n    if dataset is None:\n        return None\n\n    spg_type = get_spacegroup_type(dataset['hall_number'])\n    if symbol_type == 1:\n        return \"%s (%d)\" % (spg_type['schoenflies'], dataset['number'])\n    else:\n        return \"%s (%d)\" % (spg_type['international_short'], dataset['number'])\n\n\ndef get_hall_number_from_symmetry(rotations, translations, symprec=1e-5):\n    \"\"\"Hall number is obtained from a set of symmetry operations.\n\n    If it fails, None is returned.\n    \"\"\"\n\n    r = np.array(rotations, dtype='intc', order='C')\n    t = np.array(translations, dtype='double', order='C')\n    hall_number = spg.hall_number_from_symmetry(r, t, symprec)\n    return hall_number\n\n\ndef get_spacegroup_type(hall_number):\n    \"\"\"Translate Hall number to space group type information.\n\n    If it fails, None is returned.\n    \"\"\"\n    _set_no_error()\n\n    keys = ('number',\n            'international_short',\n            'international_full',\n            'international',\n            'schoenflies',\n            'hall_symbol',\n            'choice',\n            'pointgroup_schoenflies',\n            'pointgroup_international',\n            'arithmetic_crystal_class_number',\n            'arithmetic_crystal_class_symbol')\n    spg_type_list = spg.spacegroup_type(hall_number)\n    _set_error_message()\n\n    if spg_type_list is not None:\n        spg_type = dict(zip(keys, spg_type_list))\n        for key in spg_type:\n            if key != 'number' and key != 'arithmetic_crystal_class_number':\n                spg_type[key] = spg_type[key].strip()\n        return spg_type\n    else:\n        return None\n\n\ndef get_pointgroup(rotations):\n    \"\"\"Return point group in international table symbol and number.\n\n    The symbols are mapped to the numbers as follows:\n    1   \"1    \"\n    2   \"-1   \"\n    3   \"2    \"\n    4   \"m    \"\n    5   \"2/m  \"\n    6   \"222  \"\n    7   \"mm2  \"\n    8   \"mmm  \"\n    9   \"4    \"\n    10  \"-4   \"\n    11  \"4/m  \"\n    12  \"422  \"\n    13  \"4mm  \"\n    14  \"-42m \"\n    15  \"4/mmm\"\n    16  \"3    \"\n    17  \"-3   \"\n    18  \"32   \"\n    19  \"3m   \"\n    20  \"-3m  \"\n    21  \"6    \"\n    22  \"-6   \"\n    23  \"6/m  \"\n    24  \"622  \"\n    25  \"6mm  \"\n    26  \"-62m \"\n    27  \"6/mmm\"\n    28  \"23   \"\n    29  \"m-3  \"\n    30  \"432  \"\n    31  \"-43m \"\n    32  \"m-3m \"\n    \"\"\"\n    _set_no_error()\n\n    # (symbol, pointgroup_number, transformation_matrix)\n    pointgroup = spg.pointgroup(np.array(rotations, dtype='intc', order='C'))\n    _set_error_message()\n    return pointgroup\n\n\ndef standardize_cell(cell,\n                     to_primitive=False,\n                     no_idealize=False,\n                     symprec=1e-5,\n                     angle_tolerance=-1.0):\n    \"\"\"Return standardized cell.\n\n    Args:\n        cell, symprec, angle_tolerance:\n            See the docstring of get_symmetry.\n        to_primitive:\n            bool: If True, the standardized primitive cell is created.\n        no_idealize:\n            bool: If True,  it is disabled to idealize lengths and angles of\n                  basis vectors and positions of atoms according to crystal\n                  symmetry.\n    Return:\n        The standardized unit cell or primitive cell is returned by a tuple of\n        (lattice, positions, numbers).\n        If it fails, None is returned.\n    \"\"\"\n    _set_no_error()\n\n    lattice, _positions, _numbers, _ = _expand_cell(cell)\n    if lattice is None:\n        return None\n\n    # Atomic positions have to be specified by scaled positions for spglib.\n    num_atom = len(_positions)\n    positions = np.zeros((num_atom * 4, 3), dtype='double', order='C')\n    positions[:num_atom] = _positions\n    numbers = np.zeros(num_atom * 4, dtype='intc')\n    numbers[:num_atom] = _numbers\n    num_atom_std = spg.standardize_cell(lattice,\n                                        positions,\n                                        numbers,\n                                        num_atom,\n                                        to_primitive * 1,\n                                        no_idealize * 1,\n                                        symprec,\n                                        angle_tolerance)\n    _set_error_message()\n\n    if num_atom_std > 0:\n        return (np.array(lattice.T, dtype='double', order='C'),\n                np.array(positions[:num_atom_std], dtype='double', order='C'),\n                np.array(numbers[:num_atom_std], dtype='intc'))\n    else:\n        return None\n\n\ndef refine_cell(cell, symprec=1e-5, angle_tolerance=-1.0):\n    \"\"\"Return refined cell.\n\n    The standardized unit cell is returned by a tuple of\n    (lattice, positions, numbers).\n    If it fails, None is returned.\n    \"\"\"\n    _set_no_error()\n\n    lattice, _positions, _numbers, _ = _expand_cell(cell)\n    if lattice is None:\n        return None\n\n    # Atomic positions have to be specified by scaled positions for spglib.\n    num_atom = len(_positions)\n    positions = np.zeros((num_atom * 4, 3), dtype='double', order='C')\n    positions[:num_atom] = _positions\n    numbers = np.zeros(num_atom * 4, dtype='intc')\n    numbers[:num_atom] = _numbers\n    num_atom_std = spg.refine_cell(lattice,\n                                   positions,\n                                   numbers,\n                                   num_atom,\n                                   symprec,\n                                   angle_tolerance)\n    _set_error_message()\n\n    if num_atom_std > 0:\n        return (np.array(lattice.T, dtype='double', order='C'),\n                np.array(positions[:num_atom_std], dtype='double', order='C'),\n                np.array(numbers[:num_atom_std], dtype='intc'))\n    else:\n        return None\n\n\ndef find_primitive(cell, symprec=1e-5, angle_tolerance=-1.0):\n    \"\"\"Primitive cell is searched in the input cell.\n\n    The primitive cell is returned by a tuple of (lattice, positions, numbers).\n    If it fails, None is returned.\n    \"\"\"\n    _set_no_error()\n\n    lattice, positions, numbers, _ = _expand_cell(cell)\n    if lattice is None:\n        return None\n\n    num_atom_prim = spg.primitive(lattice,\n                                  positions,\n                                  numbers,\n                                  symprec,\n                                  angle_tolerance)\n    _set_error_message()\n\n    if num_atom_prim > 0:\n        return (np.array(lattice.T, dtype='double', order='C'),\n                np.array(positions[:num_atom_prim], dtype='double', order='C'),\n                np.array(numbers[:num_atom_prim], dtype='intc'))\n    else:\n        return None\n\n\ndef get_symmetry_from_database(hall_number):\n    \"\"\"Return symmetry operations corresponding to a Hall symbol.\n\n    The Hall symbol is given by the serial number in between 1 and 530.\n    The symmetry operations are given by a dictionary whose keys are\n    'rotations' and 'translations'.\n    If it fails, None is returned.\n    \"\"\"\n    _set_no_error()\n\n    rotations = np.zeros((192, 3, 3), dtype='intc')\n    translations = np.zeros((192, 3), dtype='double')\n    num_sym = spg.symmetry_from_database(rotations, translations, hall_number)\n    _set_error_message()\n\n    if num_sym is None:\n        return None\n    else:\n        return {'rotations':\n                np.array(rotations[:num_sym], dtype='intc', order='C'),\n                'translations':\n                np.array(translations[:num_sym], dtype='double', order='C')}\n\n\n############\n# k-points #\n############\ndef get_grid_point_from_address(grid_address, mesh):\n    \"\"\"Return grid point index by tranlating grid address\"\"\"\n    _set_no_error()\n\n    return spg.grid_point_from_address(np.array(grid_address, dtype='intc'),\n                                       np.array(mesh, dtype='intc'))\n\n\ndef get_ir_reciprocal_mesh(mesh,\n                           cell,\n                           is_shift=None,\n                           is_time_reversal=True,\n                           symprec=1e-5,\n                           is_dense=False):\n    \"\"\"Return k-points mesh and k-point map to the irreducible k-points.\n\n    The symmetry is serched from the input cell.\n\n    Parameters\n    ----------\n    mesh : array_like\n        Uniform sampling mesh numbers.\n        dtype='intc', shape=(3,)\n    cell : spglib cell tuple\n        Crystal structure.\n    is_shift : array_like, optional\n        [0, 0, 0] gives Gamma center mesh and value 1 gives half mesh shift.\n        Default is None which equals to [0, 0, 0].\n        dtype='intc', shape=(3,)\n    is_time_reversal : bool, optional\n        Whether time reversal symmetry is included or not. Default is True.\n    symprec : float, optional\n        Symmetry tolerance in distance. Default is 1e-5.\n    is_dense : bool, optional\n        grid_mapping_table is returned with dtype='uintp' if True. Otherwise\n        its dtype='intc'. Default is False.\n\n    Returns\n    -------\n    grid_mapping_table : ndarray\n        Grid point mapping table to ir-gird-points.\n        dtype='intc' or 'uintp', shape=(prod(mesh),)\n    grid_address : ndarray\n        Address of all grid points.\n        dtype='intc', shspe=(prod(mesh), 3)\n\n    \"\"\"\n    _set_no_error()\n\n    lattice, positions, numbers, _ = _expand_cell(cell)\n    if lattice is None:\n        return None\n\n    if is_dense:\n        dtype = 'uintp'\n    else:\n        dtype = 'intc'\n    grid_mapping_table = np.zeros(np.prod(mesh), dtype=dtype)\n    grid_address = np.zeros((np.prod(mesh), 3), dtype='intc')\n    if is_shift is None:\n        is_shift = [0, 0, 0]\n    if spg.ir_reciprocal_mesh(\n            grid_address,\n            grid_mapping_table,\n            np.array(mesh, dtype='intc'),\n            np.array(is_shift, dtype='intc'),\n            is_time_reversal * 1,\n            lattice,\n            positions,\n            numbers,\n            symprec) > 0:\n        return grid_mapping_table, grid_address\n    else:\n        return None\n\n\ndef get_stabilized_reciprocal_mesh(mesh,\n                                   rotations,\n                                   is_shift=None,\n                                   is_time_reversal=True,\n                                   qpoints=None,\n                                   is_dense=False):\n    \"\"\"Return k-point map to the irreducible k-points and k-point grid points.\n\n    The symmetry is searched from the input rotation matrices in real space.\n\n    Parameters\n    ----------\n    mesh : array_like\n        Uniform sampling mesh numbers.\n        dtype='intc', shape=(3,)\n    rotations : array_like\n        Rotation matrices with respect to real space basis vectors.\n        dtype='intc', shape=(rotations, 3)\n    is_shift : array_like\n        [0, 0, 0] gives Gamma center mesh and value 1 gives  half mesh shift.\n        dtype='intc', shape=(3,)\n    is_time_reversal : bool\n        Time reversal symmetry is included or not.\n    qpoints : array_like\n        q-points used as stabilizer(s) given in reciprocal space with respect\n        to reciprocal basis vectors.\n        dtype='double', shape=(qpoints ,3) or (3,)\n    is_dense : bool, optional\n        grid_mapping_table is returned with dtype='uintp' if True. Otherwise\n        its dtype='intc'. Default is False.\n\n    Returns\n    -------\n    grid_mapping_table : ndarray\n        Grid point mapping table to ir-gird-points.\n        dtype='intc', shape=(prod(mesh),)\n    grid_address : ndarray\n        Address of all grid points. Each address is given by three unsigned\n        integers.\n        dtype='intc', shape=(prod(mesh), 3)\n\n    \"\"\"\n    _set_no_error()\n\n    if is_dense:\n        dtype = 'uintp'\n    else:\n        dtype = 'intc'\n    mapping_table = np.zeros(np.prod(mesh), dtype=dtype)\n    grid_address = np.zeros((np.prod(mesh), 3), dtype='intc')\n    if is_shift is None:\n        is_shift = [0, 0, 0]\n    if qpoints is None:\n        qpoints = np.array([[0, 0, 0]], dtype='double', order='C')\n    else:\n        qpoints = np.array(qpoints, dtype='double', order='C')\n        if qpoints.shape == (3,):\n            qpoints = np.array([qpoints], dtype='double', order='C')\n\n    if spg.stabilized_reciprocal_mesh(\n            grid_address,\n            mapping_table,\n            np.array(mesh, dtype='intc'),\n            np.array(is_shift, dtype='intc'),\n            is_time_reversal * 1,\n            np.array(rotations, dtype='intc', order='C'),\n            qpoints) > 0:\n        return mapping_table, grid_address\n    else:\n        return None\n\n\ndef get_grid_points_by_rotations(address_orig,\n                                 reciprocal_rotations,\n                                 mesh,\n                                 is_shift=None,\n                                 is_dense=False):\n    \"\"\"Returns grid points obtained after rotating input grid address\n\n    Parameters\n    ----------\n    address_orig : array_like\n        Grid point address to be rotated.\n        dtype='intc', shape=(3,)\n    reciprocal_rotations : array_like\n        Rotation matrices {R} with respect to reciprocal basis vectors.\n        Defined by q'=Rq.\n        dtype='intc', shape=(rotations, 3, 3)\n    mesh : array_like\n        dtype='intc', shape=(3,)\n    is_shift : array_like, optional\n        With (1) or without (0) half grid shifts with respect to grid intervals\n        sampled along reciprocal basis vectors. Default is None, which\n        gives [0, 0, 0].\n    is_dense : bool, optional\n        rot_grid_points is returned with dtype='uintp' if True. Otherwise\n        its dtype='intc'. Default is False.\n\n    Returns\n    -------\n    rot_grid_points : ndarray\n        Grid points obtained after rotating input grid address\n        dtype='intc' or 'uintp', shape=(rotations,)\n\n    \"\"\"\n\n    _set_no_error()\n\n    if is_shift is None:\n        _is_shift = np.zeros(3, dtype='intc')\n    else:\n        _is_shift = np.array(is_shift, dtype='intc')\n\n    rot_grid_points = np.zeros(len(reciprocal_rotations), dtype='uintp')\n    spg.grid_points_by_rotations(\n        rot_grid_points,\n        np.array(address_orig, dtype='intc'),\n        np.array(reciprocal_rotations, dtype='intc', order='C'),\n        np.array(mesh, dtype='intc'),\n        _is_shift)\n\n    if is_dense:\n        return rot_grid_points\n    else:\n        return np.array(rot_grid_points, dtype='intc')\n\n\ndef get_BZ_grid_points_by_rotations(address_orig,\n                                    reciprocal_rotations,\n                                    mesh,\n                                    bz_map,\n                                    is_shift=None,\n                                    is_dense=False):\n    \"\"\"Returns grid points obtained after rotating input grid address\n\n    Parameters\n    ----------\n    address_orig : array_like\n        Grid point address to be rotated.\n        dtype='intc', shape=(3,)\n    reciprocal_rotations : array_like\n        Rotation matrices {R} with respect to reciprocal basis vectors.\n        Defined by q'=Rq.\n        dtype='intc', shape=(rotations, 3, 3)\n    mesh : array_like\n        dtype='intc', shape=(3,)\n    is_shift : array_like, optional\n        With (1) or without (0) half grid shifts with respect to grid intervals\n        sampled along reciprocal basis vectors. Default is None, which\n        gives [0, 0, 0].\n    is_dense : bool, optional\n        rot_grid_points is returned with dtype='uintp' if True. Otherwise\n        its dtype='intc'. Default is False.\n\n    Returns\n    -------\n    rot_grid_points : ndarray\n        Grid points obtained after rotating input grid address\n        dtype='intc' or 'uintp', shape=(rotations,)\n\n    \"\"\"\n\n    _set_no_error()\n\n    if is_shift is None:\n        _is_shift = np.zeros(3, dtype='intc')\n    else:\n        _is_shift = np.array(is_shift, dtype='intc')\n\n    if bz_map.dtype == 'uintp' and bz_map.flags.c_contiguous:\n        _bz_map = bz_map\n    else:\n        _bz_map = np.array(bz_map, dtype='uintp')\n\n    rot_grid_points = np.zeros(len(reciprocal_rotations), dtype='uintp')\n    spg.BZ_grid_points_by_rotations(\n        rot_grid_points,\n        np.array(address_orig, dtype='intc'),\n        np.array(reciprocal_rotations, dtype='intc', order='C'),\n        np.array(mesh, dtype='intc'),\n        _is_shift,\n        _bz_map)\n\n    if is_dense:\n        return rot_grid_points\n    else:\n        return np.array(rot_grid_points, dtype='intc')\n\n\ndef relocate_BZ_grid_address(grid_address,\n                             mesh,\n                             reciprocal_lattice,  # column vectors\n                             is_shift=None,\n                             is_dense=False):\n    \"\"\"Grid addresses are relocated to be inside first Brillouin zone.\n\n    Number of ir-grid-points inside Brillouin zone is returned.\n    It is assumed that the following arrays have the shapes of\n        bz_grid_address : (num_grid_points_in_FBZ, 3)\n        bz_map (prod(mesh * 2), )\n\n    Note that the shape of grid_address is (prod(mesh), 3) and the\n    addresses in grid_address are arranged to be in parallelepiped\n    made of reciprocal basis vectors. The addresses in bz_grid_address\n    are inside the first Brillouin zone or on its surface. Each\n    address in grid_address is mapped to one of those in\n    bz_grid_address by a reciprocal lattice vector (including zero\n    vector) with keeping element order. For those inside first\n    Brillouin zone, the mapping is one-to-one. For those on the first\n    Brillouin zone surface, more than one addresses in bz_grid_address\n    that are equivalent by the reciprocal lattice translations are\n    mapped to one address in grid_address. In this case, those grid\n    points except for one of them are appended to the tail of this array,\n    for which bz_grid_address has the following data storing:\n\n    |------------------array size of bz_grid_address-------------------------|\n    |--those equivalent to grid_address--|--those on surface except for one--|\n    |-----array size of grid_address-----|\n\n    Number of grid points stored in bz_grid_address is returned.\n    bz_map is used to recover grid point index expanded to include BZ\n    surface from grid address. The grid point indices are mapped to\n    (mesh[0] * 2) x (mesh[1] * 2) x (mesh[2] * 2) space (bz_map).\n\n    \"\"\"\n    _set_no_error()\n\n    if is_shift is None:\n        _is_shift = np.zeros(3, dtype='intc')\n    else:\n        _is_shift = np.array(is_shift, dtype='intc')\n    bz_grid_address = np.zeros((np.prod(np.add(mesh, 1)), 3), dtype='intc')\n    bz_map = np.zeros(np.prod(np.multiply(mesh, 2)), dtype='uintp')\n    num_bz_ir = spg.BZ_grid_address(\n        bz_grid_address,\n        bz_map,\n        grid_address,\n        np.array(mesh, dtype='intc'),\n        np.array(reciprocal_lattice, dtype='double', order='C'),\n        _is_shift)\n\n    if is_dense:\n        return bz_grid_address[:num_bz_ir], bz_map\n    else:\n        return bz_grid_address[:num_bz_ir], np.array(bz_map, dtype='intc')\n\n\ndef delaunay_reduce(lattice, eps=1e-5):\n    \"\"\"Run Delaunay reduction\n\n    Args:\n        lattice: Lattice parameters in the form of\n            [[a_x, a_y, a_z],\n             [b_x, b_y, b_z],\n             [c_x, c_y, c_z]]\n        symprec:\n            float: Tolerance to check if volume is close to zero or not and\n                   if two basis vectors are orthogonal by the value of dot\n                   product being close to zero or not.\n\n    Returns:\n        if the Delaunay reduction succeeded:\n            Reduced lattice parameters are given as a numpy 'double' array:\n            [[a_x, a_y, a_z],\n             [b_x, b_y, b_z],\n             [c_x, c_y, c_z]]\n        otherwise None is returned.\n    \"\"\"\n    _set_no_error()\n\n    delaunay_lattice = np.array(np.transpose(lattice),\n                                dtype='double', order='C')\n    result = spg.delaunay_reduce(delaunay_lattice, float(eps))\n    _set_error_message()\n\n    if result == 0:\n        return None\n    else:\n        return np.array(np.transpose(delaunay_lattice),\n                        dtype='double', order='C')\n\n\ndef niggli_reduce(lattice, eps=1e-5):\n    \"\"\"Run Niggli reduction\n\n    Args:\n        lattice: Lattice parameters in the form of\n            [[a_x, a_y, a_z],\n             [b_x, b_y, b_z],\n             [c_x, c_y, c_z]]\n        eps:\n            float: Tolerance to check if difference of norms of two basis\n                   vectors is close to zero or not and if two basis vectors are\n                   orthogonal by the value of dot product being close to zero or\n                   not. The detail is shown at\n                   https://atztogo.github.io/niggli/.\n\n    Returns:\n        if the Niggli reduction succeeded:\n            Reduced lattice parameters are given as a numpy 'double' array:\n            [[a_x, a_y, a_z],\n             [b_x, b_y, b_z],\n             [c_x, c_y, c_z]]\n        otherwise None is returned.\n    \"\"\"\n    _set_no_error()\n\n    niggli_lattice = np.array(np.transpose(lattice), dtype='double', order='C')\n    result = spg.niggli_reduce(niggli_lattice, float(eps))\n    _set_error_message()\n\n    if result == 0:\n        return None\n    else:\n        return np.array(np.transpose(niggli_lattice),\n                        dtype='double', order='C')\n\n\ndef get_error_message():\n    return spglib_error.message\n\n\ndef _expand_cell(cell):\n    if isinstance(cell, tuple):\n        lattice = np.array(np.transpose(cell[0]), dtype='double', order='C')\n        positions = np.array(cell[1], dtype='double', order='C')\n        numbers = np.array(cell[2], dtype='intc')\n        if len(cell) > 3:\n            magmoms = np.array(cell[3], dtype='double')\n        else:\n            magmoms = None\n    else:\n        import warnings\n        warnings.warn(\"ASE Atoms-like input is deprecated.\",\n                      DeprecationWarning)\n        lattice = np.array(cell.get_cell().T, dtype='double', order='C')\n        positions = np.array(cell.get_scaled_positions(),\n                             dtype='double', order='C')\n        numbers = np.array(cell.get_atomic_numbers(), dtype='intc')\n        magmoms = None\n\n    if _check(lattice, positions, numbers, magmoms):\n        return (lattice, positions, numbers, magmoms)\n    else:\n        return (None, None, None, None)\n\n\ndef _check(lattice, positions, numbers, magmoms):\n    if lattice.shape != (3, 3):\n        return False\n    if positions.ndim != 2:\n        return False\n    if positions.shape[1] != 3:\n        return False\n    if numbers.ndim != 1:\n        return False\n    if len(numbers) != positions.shape[0]:\n        return False\n    if magmoms is not None:\n        if magmoms.ndim != 1:\n            return False\n        if len(magmoms) != len(numbers):\n            return False\n    return True\n\n\ndef _set_error_message():\n    spglib_error.message = spg.error_message()\n\n\ndef _set_no_error():\n    spglib_error.message = \"no error\"\n", "meta": {"hexsha": "0205455e16882ab5bb830548351e5fbc26adefcf", "size": 32815, "ext": "py", "lang": "Python", "max_stars_repo_path": "phonopy/structure/spglib.py", "max_stars_repo_name": "flokno/phonopy", "max_stars_repo_head_hexsha": "02e31d5998de0a9b664b67968bb511e21c400574", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "phonopy/structure/spglib.py", "max_issues_repo_name": "flokno/phonopy", "max_issues_repo_head_hexsha": "02e31d5998de0a9b664b67968bb511e21c400574", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-09-18T08:12:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-20T23:37:28.000Z", "max_forks_repo_path": "phonopy/structure/spglib.py", "max_forks_repo_name": "flokno/phonopy", "max_forks_repo_head_hexsha": "02e31d5998de0a9b664b67968bb511e21c400574", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-09-13T09:32:01.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-13T09:32:01.000Z", "avg_line_length": 35.1338329764, "max_line_length": 80, "alphanum_fraction": 0.5823251562, "include": true, "reason": "import numpy", "num_tokens": 7432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3522017820478896, "lm_q1q2_score": 0.18846262013331802}}
{"text": "from numbers import Integral, Real\nfrom itertools import chain\nimport string\n\nfrom six import string_types\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport openmc.checkvalue as cv\nimport openmc.data\n\n# Supported keywords for continuous-energy cross section plotting\nPLOT_TYPES = ['total', 'scatter', 'elastic', 'inelastic', 'fission',\n              'absorption', 'capture', 'nu-fission', 'nu-scatter', 'unity',\n              'slowing-down power', 'damage']\n\n# Supported keywoards for multi-group cross section plotting\nPLOT_TYPES_MGXS = ['total', 'absorption', 'scatter', 'fission',\n                   'kappa-fission', 'nu-fission', 'prompt-nu-fission',\n                   'deleyed-nu-fission', 'chi', 'chi-prompt', 'chi-delayed',\n                   'inverse-velocity', 'beta', 'decay rate', 'unity']\n# Create a dictionary which can be used to convert PLOT_TYPES_MGXS to the\n# openmc.XSdata attribute name needed to access the data\n_PLOT_MGXS_ATTR = {line: line.replace(' ', '_').replace('-', '_')\n                   for line in PLOT_TYPES_MGXS}\n_PLOT_MGXS_ATTR['scatter'] = 'scatter_matrix'\n\n# Special MT values\nUNITY_MT = -1\nXI_MT = -2\n\n# MTs to combine to generate associated plot_types\n_INELASTIC = [mt for mt in openmc.data.SUM_RULES[3] if mt != 27]\nPLOT_TYPES_MT = {'total': openmc.data.SUM_RULES[1],\n                 'scatter': [2] + _INELASTIC,\n                 'elastic': [2],\n                 'inelastic': _INELASTIC,\n                 'fission': [18],\n                 'absorption': [27], 'capture': [101],\n                 'nu-fission': [18],\n                 'nu-scatter': [2] + _INELASTIC,\n                 'unity': [UNITY_MT],\n                 'slowing-down power': [2] + _INELASTIC + [XI_MT],\n                 'damage': [444]}\n# Operations to use when combining MTs the first np.add is used in reference\n# to zero\nPLOT_TYPES_OP = {'total': (np.add,),\n                 'scatter': (np.add,) * (len(PLOT_TYPES_MT['scatter']) - 1),\n                 'elastic': (),\n                 'inelastic': (np.add,) * (len(PLOT_TYPES_MT['inelastic']) - 1),\n                 'fission': (), 'absorption': (),\n                 'capture': (), 'nu-fission': (),\n                 'nu-scatter': (np.add,) * (len(PLOT_TYPES_MT['nu-scatter']) - 1),\n                 'unity': (),\n                 'slowing-down power':\n                    (np.add,) * (len(PLOT_TYPES_MT['slowing-down power']) - 2) + (np.multiply,),\n                 'damage': ()}\n\n# Types of plots to plot linearly in y\nPLOT_TYPES_LINEAR = {'nu-fission / fission', 'nu-scatter / scatter',\n                     'nu-fission / absorption', 'fission / absorption'}\n\n# Minimum and maximum energies for plotting (units of eV)\n_MIN_E = 1.e-5\n_MAX_E = 20.e6\n\n\ndef plot_xs(this, types, divisor_types=None, temperature=294., data_type=None,\n            axis=None, sab_name=None, ce_cross_sections=None,\n            mg_cross_sections=None, enrichment=None, plot_CE=True, orders=None,\n            divisor_orders=None, **kwargs):\n    \"\"\"Creates a figure of continuous-energy cross sections for this item.\n\n    Parameters\n    ----------\n    this : str or openmc.Material\n        Object to source data from\n    types : Iterable of values of PLOT_TYPES\n        The type of cross sections to include in the plot.\n    divisor_types : Iterable of values of PLOT_TYPES, optional\n        Cross section types which will divide those produced by types\n        before plotting. A type of 'unity' can be used to effectively not\n        divide some types.\n    temperature : float, optional\n        Temperature in Kelvin to plot. If not specified, a default\n        temperature of 294K will be plotted. Note that the nearest\n        temperature in the library for each nuclide will be used as opposed\n        to using any interpolation.\n    data_type : {'nuclide', 'element', 'material', 'macroscopic'}, optional\n        Type of object to plot. If not specified, a guess is made based on the\n        `this` argument.\n    axis : matplotlib.axes, optional\n        A previously generated axis to use for plotting. If not specified,\n        a new axis and figure will be generated.\n    sab_name : str, optional\n        Name of S(a,b) library to apply to MT=2 data when applicable; only used\n        for items which are instances of openmc.Element or openmc.Nuclide\n    ce_cross_sections : str, optional\n        Location of cross_sections.xml file. Default is None.\n    mg_cross_sections : str, optional\n        Location of MGXS HDF5 Library file. Default is None.\n    enrichment : float, optional\n        Enrichment for U235 in weight percent. For example, input 4.95 for\n        4.95 weight percent enriched U. Default is None. This is only used for\n        items which are instances of openmc.Element\n    plot_CE : bool, optional\n        Denotes whether or not continuous-energy will be plotted. Defaults to\n        plotting the continuous-energy data.\n    orders : Iterable of Integral, optional\n        The scattering order or delayed group index to use for the\n        corresponding entry in types. Defaults to the 0th order for scattering\n        and the total delayed neutron data. This only applies to plots of\n        multi-group data.\n    divisor_orders : Iterable of Integral, optional\n        Same as orders, but for divisor_types\n    **kwargs\n        All keyword arguments are passed to\n        :func:`matplotlib.pyplot.figure`.\n\n    Returns\n    -------\n    fig : matplotlib.figure.Figure\n        If axis is None, then a Matplotlib Figure of the generated\n        cross section will be returned. Otherwise, a value of\n        None will be returned as the figure and axes have already been\n        generated.\n\n    \"\"\"\n    cv.check_type(\"plot_CE\", plot_CE, bool)\n\n    if data_type is None:\n        if isinstance(this, openmc.Nuclide):\n            data_type = 'nuclide'\n        elif isinstance(this, openmc.Element):\n            data_type = 'element'\n        elif isinstance(this, openmc.Material):\n            data_type = 'material'\n        elif isinstance(this, openmc.Macroscopic):\n            data_type = 'macroscopic'\n        elif isinstance(this, string_types):\n            if this[-1] in string.digits:\n                data_type = 'nuclide'\n            else:\n                data_type = 'element'\n        else:\n            raise TypeError(\"Invalid type for plotting\")\n\n    if plot_CE:\n        # Calculate for the CE cross sections\n        E, data = calculate_cexs(this, data_type, types, temperature, sab_name,\n                                 ce_cross_sections, enrichment)\n        if divisor_types:\n            cv.check_length('divisor types', divisor_types, len(types))\n            Ediv, data_div = calculate_cexs(this, divisor_types, temperature,\n                                            sab_name, ce_cross_sections,\n                                            enrichment)\n\n            # Create a new union grid, interpolate data and data_div on to that\n            # grid, and then do the actual division\n            Enum = E[:]\n            E = np.union1d(Enum, Ediv)\n            data_new = np.zeros((len(types), len(E)))\n\n            for line in range(len(types)):\n                data_new[line, :] = \\\n                    np.divide(np.interp(E, Enum, data[line, :]),\n                              np.interp(E, Ediv, data_div[line, :]))\n                if divisor_types[line] != 'unity':\n                    types[line] = types[line] + ' / ' + divisor_types[line]\n            data = data_new\n    else:\n        # Calculate for MG cross sections\n        E, data = calculate_mgxs(this, types, orders, temperature,\n                                 mg_cross_sections, ce_cross_sections,\n                                 enrichment)\n\n        if divisor_types:\n            cv.check_length('divisor types', divisor_types, len(types))\n            Ediv, data_div = calculate_mgxs(this, divisor_types,\n                                            divisor_orders, temperature,\n                                            mg_cross_sections,\n                                            ce_cross_sections, enrichment)\n\n            # Perform the division\n            for line in range(len(types)):\n                data[line, :] /= data_div[line, :]\n                if divisor_types[line] != 'unity':\n                    types[line] += ' / ' + divisor_types[line]\n\n    # Generate the plot\n    if axis is None:\n        fig = plt.figure(**kwargs)\n        ax = fig.add_subplot(111)\n    else:\n        fig = None\n        ax = axis\n    # Set to loglog or semilogx depending on if we are plotting a data\n    # type which we expect to vary linearly\n    if set(types).issubset(PLOT_TYPES_LINEAR):\n        plot_func = ax.semilogx\n    else:\n        plot_func = ax.loglog\n\n    # Plot the data\n    for i in range(len(data)):\n        data[i, :] = np.nan_to_num(data[i, :])\n        if np.sum(data[i, :]) > 0.:\n            plot_func(E, data[i, :], label=types[i])\n\n    ax.set_xlabel('Energy [eV]')\n    if plot_CE:\n        ax.set_xlim(_MIN_E, _MAX_E)\n    else:\n        ax.set_xlim(E[-1], E[0])\n    if divisor_types:\n        if data_type == 'nuclide':\n            ylabel = 'Nuclidic Microscopic Data'\n        elif data_type == 'element':\n            ylabel = 'Elemental Microscopic Data'\n        elif data_type == 'material' or data_type == 'macroscopic':\n            ylabel = 'Macroscopic Data'\n    else:\n        if data_type == 'nuclide':\n            ylabel = 'Microscopic Cross Section [b]'\n        elif data_type == 'element':\n            ylabel = 'Elemental Cross Section [b]'\n        elif data_type == 'material' or data_type == 'macroscopic':\n            ylabel = 'Macroscopic Cross Section [1/cm]'\n    ax.set_ylabel(ylabel)\n    ax.legend(loc='best')\n    name = this.name if data_type == 'material' else this\n    if len(types) > 1:\n        ax.set_title('Cross Sections for ' + name)\n    else:\n        ax.set_title('Cross Section for ' + name)\n\n    return fig\n\n\ndef calculate_cexs(this, data_type, types, temperature=294., sab_name=None,\n                   cross_sections=None, enrichment=None):\n    \"\"\"Calculates continuous-energy cross sections of a requested type.\n\n    Parameters\n    ----------\n    this : str or openmc.Material\n        Object to source data from\n    data_type : {'nuclide', 'element', material'}\n        Type of object to plot\n    types : Iterable of values of PLOT_TYPES\n        The type of cross sections to calculate\n    temperature : float, optional\n        Temperature in Kelvin to plot. If not specified, a default\n        temperature of 294K will be plotted. Note that the nearest\n        temperature in the library for each nuclide will be used as opposed\n        to using any interpolation.\n    sab_name : str, optional\n        Name of S(a,b) library to apply to MT=2 data when applicable.\n    cross_sections : str, optional\n        Location of cross_sections.xml file. Default is None.\n    enrichment : float, optional\n        Enrichment for U235 in weight percent. For example, input 4.95 for\n        4.95 weight percent enriched U. Default is None\n        (natural composition).\n\n    Returns\n    -------\n    energy_grid : numpy.ndarray\n        Energies at which cross sections are calculated, in units of eV\n    data : numpy.ndarray\n        Cross sections calculated at the energy grid described by energy_grid\n\n    \"\"\"\n\n    # Check types\n    cv.check_type('temperature', temperature, Real)\n    if sab_name:\n        cv.check_type('sab_name', sab_name, string_types)\n    if enrichment:\n        cv.check_type('enrichment', enrichment, Real)\n\n    if data_type == 'nuclide':\n        energy_grid, xs = _calculate_cexs_nuclide(this, types, temperature,\n                                                  sab_name, cross_sections)\n        # Convert xs (Iterable of Callable) to a grid of cross section values\n        # calculated on @ the points in energy_grid for consistency with the\n        # element and material functions.\n        data = np.zeros((len(types), len(energy_grid)))\n        for line in range(len(types)):\n            data[line, :] = xs[line](energy_grid)\n    elif data_type == 'element':\n        energy_grid, data = _calculate_cexs_elem_mat(this, types, temperature,\n                                                     cross_sections, sab_name,\n                                                     enrichment)\n    elif data_type == 'material':\n        energy_grid, data = _calculate_cexs_elem_mat(this, types, temperature,\n                                                     cross_sections)\n    else:\n        raise TypeError(\"Invalid type\")\n\n    return energy_grid, data\n\n\ndef _calculate_cexs_nuclide(this, types, temperature=294., sab_name=None,\n                            cross_sections=None):\n    \"\"\"Calculates continuous-energy cross sections of a requested type.\n\n    Parameters\n    ----------\n    this : openmc.Nuclide\n        Nuclide object to source data from\n    types : Iterable of str or Integral\n        The type of cross sections to calculate; values can either be those\n        in openmc.PLOT_TYPES or integers which correspond to reaction\n        channel (MT) numbers.\n    temperature : float, optional\n        Temperature in Kelvin to plot. If not specified, a default\n        temperature of 294K will be plotted. Note that the nearest\n        temperature in the library for each nuclide will be used as opposed\n        to using any interpolation.\n    sab_name : str, optional\n        Name of S(a,b) library to apply to MT=2 data when applicable.\n    cross_sections : str, optional\n        Location of cross_sections.xml file. Default is None.\n\n    Returns\n    -------\n    energy_grid : numpy.ndarray\n        Energies at which cross sections are calculated, in units of eV\n    data : Iterable of Callable\n        Requested cross section functions\n\n    \"\"\"\n\n    # Parse the types\n    mts = []\n    ops = []\n    yields = []\n    for line in types:\n        if line in PLOT_TYPES:\n            mts.append(PLOT_TYPES_MT[line])\n            if line.startswith('nu'):\n                yields.append(True)\n            else:\n                yields.append(False)\n            ops.append(PLOT_TYPES_OP[line])\n        else:\n            # Not a built-in type, we have to parse it ourselves\n            cv.check_type('MT in types', line, Integral)\n            cv.check_greater_than('MT in types', line, 0)\n            mts.append((line,))\n            ops.append(())\n            yields.append(False)\n\n    # Load the library\n    library = openmc.data.DataLibrary.from_xml(cross_sections)\n\n    # Convert temperature to format needed for access in the library\n    strT = \"{}K\".format(int(round(temperature)))\n    T = temperature\n\n    # Now we can create the data sets to be plotted\n    energy_grid = []\n    xs = []\n    lib = library.get_by_material(this)\n    if lib is not None:\n        nuc = openmc.data.IncidentNeutron.from_hdf5(lib['path'])\n        # Obtain the nearest temperature\n        if strT in nuc.temperatures:\n            nucT = strT\n        else:\n            delta_T = np.array(nuc.kTs) - T * openmc.data.K_BOLTZMANN\n            closest_index = np.argmin(np.abs(delta_T))\n            nucT = nuc.temperatures[closest_index]\n\n        # Prep S(a,b) data if needed\n        if sab_name:\n            sab = openmc.data.ThermalScattering.from_hdf5(sab_name)\n            # Obtain the nearest temperature\n            if strT in sab.temperatures:\n                sabT = strT\n            else:\n                delta_T = np.array(sab.kTs) - T * openmc.data.K_BOLTZMANN\n                closest_index = np.argmin(np.abs(delta_T))\n                sabT = sab.temperatures[closest_index]\n\n            # Create an energy grid composed the S(a,b) and the nuclide's grid\n            grid = nuc.energy[nucT]\n            sab_Emax = 0.\n            sab_funcs = []\n            if sab.elastic_xs:\n                elastic = sab.elastic_xs[sabT]\n                if isinstance(elastic, openmc.data.CoherentElastic):\n                    grid = np.union1d(grid, elastic.bragg_edges)\n                    if elastic.bragg_edges[-1] > sab_Emax:\n                        sab_Emax = elastic.bragg_edges[-1]\n                elif isinstance(elastic, openmc.data.Tabulated1D):\n                    grid = np.union1d(grid, elastic.x)\n                    if elastic.x[-1] > sab_Emax:\n                        sab_Emax = elastic.x[-1]\n                sab_funcs.append(elastic)\n            if sab.inelastic_xs:\n                inelastic = sab.inelastic_xs[sabT]\n                grid = np.union1d(grid, inelastic.x)\n                if inelastic.x[-1] > sab_Emax:\n                        sab_Emax = inelastic.x[-1]\n                sab_funcs.append(inelastic)\n            energy_grid = grid\n        else:\n            energy_grid = nuc.energy[nucT]\n\n        for i, mt_set in enumerate(mts):\n            # Get the reaction xs data from the nuclide\n            funcs = []\n            op = ops[i]\n            for mt in mt_set:\n                if mt == 2:\n                    if sab_name:\n                        # Then we need to do a piece-wise function of\n                        # The S(a,b) and non-thermal data\n                        sab_sum = openmc.data.Sum(sab_funcs)\n                        pw_funcs = openmc.data.Regions1D(\n                            [sab_sum, nuc[mt].xs[nucT]],\n                            [sab_Emax])\n                        funcs.append(pw_funcs)\n                    else:\n                        funcs.append(nuc[mt].xs[nucT])\n                elif mt in nuc:\n                    if yields[i]:\n                        # Get the total yield first if available. This will be\n                        # used primarily for fission.\n                        for prod in chain(nuc[mt].products,\n                                          nuc[mt].derived_products):\n                            if prod.particle == 'neutron' and \\\n                                prod.emission_mode == 'total':\n                                func = openmc.data.Combination(\n                                    [nuc[mt].xs[nucT], prod.yield_],\n                                    [np.multiply])\n                                funcs.append(func)\n                                break\n                        else:\n                            # Total doesn't exist so we have to create from\n                            # prompt and delayed. This is used for scatter\n                            # multiplication.\n                            func = None\n                            for prod in chain(nuc[mt].products,\n                                              nuc[mt].derived_products):\n                                if prod.particle == 'neutron' and \\\n                                    prod.emission_mode != 'total':\n                                    if func:\n                                        func = openmc.data.Combination(\n                                            [prod.yield_, func], [np.add])\n                                    else:\n                                        func = prod.yield_\n                            if func:\n                                funcs.append(openmc.data.Combination(\n                                    [func, nuc[mt].xs[nucT]], [np.multiply]))\n                            else:\n                                # If func is still None, then there were no\n                                # products. In that case, assume the yield is\n                                # one as its not provided for some summed\n                                # reactions like MT=4\n                                funcs.append(nuc[mt].xs[nucT])\n                    else:\n                        funcs.append(nuc[mt].xs[nucT])\n                elif mt == UNITY_MT:\n                    funcs.append(lambda x: 1.)\n                elif mt == XI_MT:\n                    awr = nuc.atomic_weight_ratio\n                    alpha = ((awr - 1.) / (awr + 1.))**2\n                    xi = 1. + alpha * np.log(alpha) / (1. - alpha)\n                    funcs.append(lambda x: xi)\n                else:\n                    funcs.append(lambda x: 0.)\n            xs.append(openmc.data.Combination(funcs, op))\n    else:\n        raise ValueError(this + \" not in library\")\n\n    return energy_grid, xs\n\n\ndef _calculate_cexs_elem_mat(this, types, temperature=294.,\n                             cross_sections=None, sab_name=None,\n                             enrichment=None):\n    \"\"\"Calculates continuous-energy cross sections of a requested type.\n\n    Parameters\n    ----------\n    this : openmc.Material or openmc.Element\n        Object to source data from\n    types : Iterable of values of PLOT_TYPES\n        The type of cross sections to calculate\n    temperature : float, optional\n        Temperature in Kelvin to plot. If not specified, a default\n        temperature of 294K will be plotted. Note that the nearest\n        temperature in the library for each nuclide will be used as opposed\n        to using any interpolation.\n    cross_sections : str, optional\n        Location of cross_sections.xml file. Default is None.\n    sab_name : str, optional\n        Name of S(a,b) library to apply to MT=2 data when applicable.\n    enrichment : float, optional\n        Enrichment for U235 in weight percent. For example, input 4.95 for\n        4.95 weight percent enriched U. Default is None\n        (natural composition).\n\n    Returns\n    -------\n    energy_grid : numpy.ndarray\n        Energies at which cross sections are calculated, in units of eV\n    data : numpy.ndarray\n        Cross sections calculated at the energy grid described by energy_grid\n\n    \"\"\"\n\n    if isinstance(this, openmc.Material):\n        if this.temperature is not None:\n            T = this.temperature\n        else:\n            T = temperature\n        data_type = 'material'\n    else:\n        T = temperature\n        data_type = 'element'\n\n    # Load the library\n    library = openmc.data.DataLibrary.from_xml(cross_sections)\n\n    if isinstance(this, openmc.Material):\n        # Expand elements in to nuclides with atomic densities\n        nuclides = this.get_nuclide_atom_densities()\n        # For ease of processing split out the nuclide and its fraction\n        nuc_fractions = {nuclide[1][0]: nuclide[1][1]\n                         for nuclide in nuclides.items()}\n        # Create a dict of [nuclide name] = nuclide object to carry forward\n        # with a common nuclides format between openmc.Material and\n        # openmc.Element objects\n        nuclides = {nuclide[1][0]: nuclide[1][0]\n                    for nuclide in nuclides.items()}\n    else:\n        # Expand elements in to nuclides with atomic densities\n        nuclides = this.expand(1., 'ao', enrichment=enrichment,\n                               cross_sections=cross_sections)\n        # For ease of processing split out the nuclide and its fraction\n        nuc_fractions = {nuclide[0]: nuclide[1] for nuclide in nuclides}\n        # Create a dict of [nuclide name] = nuclide object to carry forward\n        # with a common nuclides format between openmc.Material and\n        # openmc.Element objects\n        nuclides = {nuclide[0]: nuclide[0] for nuclide in nuclides}\n\n    # Identify the nuclides which have S(a,b) data\n    sabs = {}\n    for nuclide in nuclides.items():\n        sabs[nuclide[0]] = None\n    if isinstance(this, openmc.Material):\n        for sab_name in this._sab:\n            sab = openmc.data.ThermalScattering.from_hdf5(\n                library.get_by_material(sab_name)['path'])\n            for nuc in sab.nuclides:\n                sabs[nuc] = library.get_by_material(sab_name)['path']\n    else:\n        if sab_name:\n            sab = openmc.data.ThermalScattering.from_hdf5(sab_name)\n            for nuc in sab.nuclides:\n                sabs[nuc] = library.get_by_material(sab_name)['path']\n\n    # Now we can create the data sets to be plotted\n    xs = {}\n    E = []\n    for nuclide in nuclides.items():\n        name = nuclide[0]\n        nuc = nuclide[1]\n        sab_tab = sabs[name]\n        temp_E, temp_xs = calculate_cexs(nuc, data_type, types, T, sab_tab,\n                                         cross_sections)\n        E.append(temp_E)\n        # Since the energy grids are different, store the cross sections as\n        # a tabulated function so they can be calculated on any grid needed.\n        xs[name] = [openmc.data.Tabulated1D(temp_E, temp_xs[line])\n                    for line in range(len(types))]\n\n    # Condense the data for every nuclide\n    # First create a union energy grid\n    energy_grid = E[0]\n    for grid in E[1:]:\n        energy_grid = np.union1d(energy_grid, grid)\n\n    # Now we can combine all the nuclidic data\n    data = np.zeros((len(types), len(energy_grid)))\n    for line in range(len(types)):\n        if types[line] == 'unity':\n            data[line, :] = 1.\n        else:\n            for nuclide in nuclides.items():\n                name = nuclide[0]\n                data[line, :] += (nuc_fractions[name] *\n                                  xs[name][line](energy_grid))\n\n    return energy_grid, data\n\n\ndef calculate_mgxs(this, data_type, types, orders=None, temperature=294.,\n                   cross_sections=None, ce_cross_sections=None,\n                   enrichment=None):\n    \"\"\"Calculates multi-group cross sections of a requested type.\n\n    If the data for the nuclide or macroscopic object in the library is\n    represented as angle-dependent data then this method will return the\n    geometric average cross section over all angles.\n\n    Parameters\n    ----------\n    this : str or openmc.Material\n        Object to source data from\n    data_type : {'nuclide', 'element', material', 'macroscopic'}\n        Type of object to plot\n    types : Iterable of values of PLOT_TYPES_MGXS\n        The type of cross sections to calculate\n    orders : Iterable of Integral, optional\n        The scattering order or delayed group index to use for the\n        corresponding entry in types. Defaults to the 0th order for scattering\n        and the total delayed neutron data.\n    temperature : float, optional\n        Temperature in Kelvin to plot. If not specified, a default\n        temperature of 294K will be plotted. Note that the nearest\n        temperature in the library for each nuclide will be used as opposed\n        to using any interpolation.\n    cross_sections : str, optional\n        Location of MGXS HDF5 Library file. Default is None.\n    ce_cross_sections : str, optional\n        Location of continuous-energy cross_sections.xml file. Default is None.\n        This is used only for expanding an openmc.Element object passed as this\n    enrichment : float, optional\n        Enrichment for U235 in weight percent. For example, input 4.95 for\n        4.95 weight percent enriched U. Default is None\n        (natural composition).\n\n    Returns\n    -------\n    energy_grid : numpy.ndarray\n        Energies at which cross sections are calculated, in units of eV\n    data : numpy.ndarray\n        Cross sections calculated at the energy grid described by energy_grid\n\n    \"\"\"\n\n    # Check types\n    cv.check_type('temperature', temperature, Real)\n    if enrichment:\n        cv.check_type('enrichment', enrichment, Real)\n    cv.check_iterable_type('types', types, string_types)\n\n    cv.check_type(\"cross_sections\", cross_sections, str)\n    library = openmc.MGXSLibrary.from_hdf5(cross_sections)\n\n    if data_type in ('nuclide', 'macroscopic'):\n        mgxs = _calculate_mgxs_nuc_macro(this, types, library, orders,\n                                         temperature)\n    elif data_type in ('element', 'material'):\n        mgxs = _calculate_mgxs_elem_mat(this, types, library, orders,\n                                        temperature, ce_cross_sections,\n                                        enrichment)\n    else:\n        raise TypeError(\"Invalid type\")\n\n    # Convert the data to the format needed\n    data = np.zeros((len(types), 2 * library.energy_groups.num_groups))\n    energy_grid = np.zeros(2 * library.energy_groups.num_groups)\n    for g in range(library.energy_groups.num_groups):\n        energy_grid[g * 2: g * 2 + 2] = \\\n            library.energy_groups.group_edges[g: g + 2]\n    # Ensure the energy will show on a log-axis by replacing 0s with a\n    # sufficiently small number\n    energy_grid[0] = max(energy_grid[0], _MIN_E)\n\n    for line in range(len(types)):\n        for g in range(library.energy_groups.num_groups):\n            data[line, g * 2: g * 2 + 2] = mgxs[line, g]\n\n    return energy_grid[::-1], data\n\n\ndef _calculate_mgxs_nuc_macro(this, types, library, orders=None,\n                              temperature=294.):\n    \"\"\"Determines the multi-group cross sections of a nuclide or macroscopic\n    object.\n\n    If the data for the nuclide or macroscopic object in the library is\n    represented as angle-dependent data then this method will return the\n    geometric average cross section over all angles.\n\n    Parameters\n    ----------\n    this : openmc.Nuclide or openmc.Macroscopic\n        Object to source data from\n    types : Iterable of str\n        The type of cross sections to calculate; values can either be those\n        in openmc.PLOT_TYPES_MGXS\n    library : openmc.MGXSLibrary\n        MGXS Library containing the data of interest\n    orders : Iterable of Integral, optional\n        The scattering order or delayed group index to use for the\n        corresponding entry in types. Defaults to the 0th order for scattering\n        and the total delayed neutron data.\n    temperature : float, optional\n        Temperature in Kelvin to plot. If not specified, a default\n        temperature of 294K will be plotted. Note that the nearest\n        temperature in the library for each nuclide will be used as opposed\n        to using any interpolation.\n\n    Returns\n    -------\n    data : numpy.ndarray\n        Cross sections calculated at the energy grid described by energy_grid\n\n    \"\"\"\n\n    # Check the parameters and grab order/delayed groups\n    if orders:\n        cv.check_iterable_type('orders', orders, Integral,\n                               min_depth=len(types), max_depth=len(types))\n    else:\n        orders = [None] * len(types)\n    for i, line in enumerate(types):\n        cv.check_type(\"line\", line, str)\n        cv.check_value(\"line\", line, PLOT_TYPES_MGXS)\n        if orders[i]:\n            cv.check_greater_than(\"order value\", orders[i], 0, equality=True)\n\n    xsdata = library.get_by_name(this)\n\n    if xsdata is not None:\n        # Obtain the nearest temperature\n        t = np.abs(xsdata.temperatures - temperature).argmin()\n\n        # Get the data\n        data = np.zeros((len(types), library.energy_groups.num_groups))\n        for i, line in enumerate(types):\n            if 'fission' in line and not xsdata.fissionable:\n                continue\n            elif line == 'unity':\n                data[i, :] = 1.\n            else:\n                # Now we have to get the cross section data and properly\n                # treat it depending on the requested type.\n                # First get the data in a generic fashion\n                temp_data = getattr(xsdata, _PLOT_MGXS_ATTR[line])[t]\n                shape = temp_data.shape[:]\n                # If we have angular data, then want the geometric\n                # average over all provided angles.  Since the angles are\n                # equi-distant, un-weighted averaging will suffice\n                if xsdata.representation == 'angle':\n                    temp_data = np.mean(temp_data, axis=(0, 1))\n\n                # Now we can look at the shape of the data to identify how\n                # it should be modified to produce an array of values\n                # with groups.\n                if shape in (xsdata.xs_shapes[\"[G']\"],\n                             xsdata.xs_shapes[\"[G]\"]):\n                    # Then the data is already an array vs groups so copy\n                    # and move along\n                    data[i, :] = temp_data\n                elif shape == xsdata.xs_shapes[\"[G][G']\"]:\n                    # Sum the data over outgoing groups to create our array vs\n                    # groups\n                    data[i, :] = np.sum(temp_data, axis=1)\n                elif shape == xsdata.xs_shapes[\"[DG]\"]:\n                    # Then we have a constant vs groups with a value for each\n                    # delayed group. The user-provided value of orders tells us\n                    # which delayed group we want. If none are provided, then\n                    # we sum all the delayed groups together.\n                    if orders[i]:\n                        if orders[i] < len(shape[0]):\n                            data[i, :] = temp_data[orders[i]]\n                    else:\n                        data[i, :] = np.sum(temp_data[:])\n                elif shape in (xsdata.xs_shapes[\"[DG][G']\"],\n                               xsdata.xs_shapes[\"[DG][G]\"]):\n                    # Then we have an array vs groups with values for each\n                    # delayed group. The user-provided value of orders tells us\n                    # which delayed group we want. If none are provided, then\n                    # we sum all the delayed groups together.\n                    if orders[i]:\n                        if orders[i] < len(shape[0]):\n                            data[i, :] = temp_data[orders[i], :]\n                    else:\n                        data[i, :] = np.sum(temp_data[:, :], axis=0)\n                elif shape == xsdata.xs_shapes[\"[DG][G][G']\"]:\n                    # Then we have a delayed group matrix. We will first\n                    # remove the outgoing group dependency\n                    temp_data = np.sum(temp_data, axis=-1)\n                    # And then proceed in exactly the same manner as the\n                    # \"[DG][G']\" or \"[DG][G]\" shapes in the previous block.\n                    if orders[i]:\n                        if orders[i] < len(shape[0]):\n                            data[i, :] = temp_data[orders[i], :]\n                    else:\n                        data[i, :] = np.sum(temp_data[:, :], axis=0)\n                elif shape == xsdata.xs_shapes[\"[G][G'][Order]\"]:\n                    # This is a scattering matrix with angular data\n                    # First remove the outgoing group dependence\n                    temp_data = np.sum(temp_data, axis=1)\n                    # The user either provided a specific order or we resort\n                    # to the default 0th order\n                    if orders[i]:\n                        order = orders[i]\n                    else:\n                        order = 0\n                    # If the order is available, store the data for that order\n                    # if it is not available, then the expansion coefficient\n                    # is zero and thus we already have the correct value.\n                    if order < shape[1]:\n                        data[i, :] = temp_data[:, order]\n    else:\n        raise ValueError(\"{} not present in provided MGXS \"\n                         \"library\".format(this))\n\n    return data\n\n\ndef _calculate_mgxs_elem_mat(this, types, library, orders=None,\n                             temperature=294., ce_cross_sections=None,\n                             enrichment=None):\n    \"\"\"Determines the multi-group cross sections of an element or material\n    object.\n\n    If the data for the nuclide or macroscopic object in the library is\n    represented as angle-dependent data then this method will return the\n    geometric average cross section over all angles.\n\n    Parameters\n    ----------\n    this : openmc.Element or openmc.Material\n        Object to source data from\n    types : Iterable of str\n        The type of cross sections to calculate; values can either be those\n        in openmc.PLOT_TYPES_MGXS\n    library : openmc.MGXSLibrary\n        MGXS Library containing the data of interest\n    orders : Iterable of Integral, optional\n        The scattering order or delayed group index to use for the\n        corresponding entry in types. Defaults to the 0th order for scattering\n        and the total delayed neutron data.\n    temperature : float, optional\n        Temperature in Kelvin to plot. If not specified, a default\n        temperature of 294K will be plotted. Note that the nearest\n        temperature in the library for each nuclide will be used as opposed\n        to using any interpolation.\n    ce_cross_sections : str, optional\n        Location of continuous-energy cross_sections.xml file. Default is None.\n        This is used only for expanding the elements\n    enrichment : float, optional\n        Enrichment for U235 in weight percent. For example, input 4.95 for\n        4.95 weight percent enriched U. Default is None\n        (natural composition).\n\n    Returns\n    -------\n    data : numpy.ndarray\n        Cross sections calculated at the energy grid described by energy_grid\n\n    \"\"\"\n\n    if isinstance(this, openmc.Material):\n        if this.temperature is not None:\n            T = this.temperature\n        else:\n            T = temperature\n\n        # Check to see if we have nuclides/elements or a macrocopic object\n        if this._macroscopic is not None:\n            # We have macroscopics\n            nuclides = {this._macroscopic: (this._macroscopic, this.density)}\n        else:\n            # Expand elements in to nuclides with atomic densities\n            nuclides = this.get_nuclide_atom_densities()\n\n        # For ease of processing split out nuc and nuc_density\n        nuc_fraction = [nuclide[1][1] for nuclide in nuclides.items()]\n    else:\n        T = temperature\n        # Expand elements in to nuclides with atomic densities\n        nuclides = this.expand(100., 'ao', enrichment=enrichment,\n                               cross_sections=ce_cross_sections)\n\n        # For ease of processing split out nuc and nuc_fractions\n        nuc_fraction = [nuclide[1] for nuclide in nuclides]\n\n    nuc_data = []\n    for nuclide in nuclides.items():\n        nuc_data.append(_calculate_mgxs_nuc_macro(nuclide[0], types, library,\n                                                  orders, T))\n\n    # Combine across the nuclides\n    data = np.zeros((len(types), library.energy_groups.num_groups))\n    for line in range(len(types)):\n        if types[line] == 'unity':\n            data[line, :] = 1.\n        else:\n            for n in range(len(nuclides)):\n                data[line, :] += nuc_fraction[n] * nuc_data[n][line, :]\n\n    return data\n", "meta": {"hexsha": "810ee5d27cca06a88984d6185e28d4d0d779e906", "size": 38310, "ext": "py", "lang": "Python", "max_stars_repo_path": "openmc/plotter.py", "max_stars_repo_name": "cchaugen/temp_openmc_for_Sterling", "max_stars_repo_head_hexsha": "9f346c9c7ab3128fa40548e936290b97610a2235", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "openmc/plotter.py", "max_issues_repo_name": "cchaugen/temp_openmc_for_Sterling", "max_issues_repo_head_hexsha": "9f346c9c7ab3128fa40548e936290b97610a2235", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openmc/plotter.py", "max_forks_repo_name": "cchaugen/temp_openmc_for_Sterling", "max_forks_repo_head_hexsha": "9f346c9c7ab3128fa40548e936290b97610a2235", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.3783185841, "max_line_length": 96, "alphanum_fraction": 0.5745497259, "include": true, "reason": "import numpy", "num_tokens": 8350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.18846261649487922}}
{"text": "\"\"\"\nThis is a Python implementation of the Denoising Autoencoder approach that we proposed for\nthe first Multi-target speaker detection and identification Challenge Evaluation (MCE 2018, http://www.mce2018.org)\n\nThe basic idea is to train a Denoising Autoencoder to map each individual input ivector\nto the mean of all ivectors from that speaker.\nThe aim of this DAE is to compensate for inter-session variability and increase the discriminative power of the ivectors.\n\nYou can find our system description for the MCE 2018 challenge here: http://mce.csail.mit.edu/pdfs/BiometricVox_description.pdf\n\nPart of the code has been adapted from the baseline system at: https://github.com/swshon/multi-speakerID.\n\n Copyright 2018 Roberto Font\n\t\t\t\tBiometric Vox S.L.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nfrom __future__ import print_function\nimport numpy as np\n\nfrom mce_utils import load_ivector, length_norm, make_spkvec, calculate_EER, get_trials_label_with_confusion, calculate_EER_with_confusion\n\nimport pandas as pd\nfrom keras.models import Model\nfrom keras.layers import Input, Dense, Activation\nfrom keras import metrics\nfrom keras import optimizers\n\n# Neural network definition: a single hidden layer with 'tanh' activation and a linear output layer \ndef get_DAE(nu=2000):\n  iv_dim = 600\n  inputs = Input(shape=(iv_dim,))\n  x = Dense(nu)(inputs)\n  x = Activation('tanh')(x)\n  x = Dense(iv_dim)(x)\n  out = Activation('linear')(x)\n  model = Model(inputs=inputs, outputs=out)\n  \n  return model\n\n# Making dictionary to find blacklist pair between train and test dataset\nbl_match = np.loadtxt('data/bl_matching.csv',dtype='str')\ndev2train={}\ndev2id={}\ntrain2dev={}\ntrain2id={}\ntest2train={}\ntrain2test={}\nfor iter, line in enumerate(bl_match):\n    line_s = line.split(',')\n    dev2train[line_s[1].split('_')[-1]]= line_s[3].split('_')[-1]\n    dev2id[line_s[1].split('_')[-1]]= line_s[0].split('_')[-1]\n    train2dev[line_s[3].split('_')[-1]]= line_s[1].split('_')[-1]\n    train2id[line_s[3].split('_')[-1]]= line_s[0].split('_')[-1]\n    test2train[line_s[2].split('_')[-1]]= line_s[3].split('_')[-1]\n    train2test[line_s[3].split('_')[-1]]= line_s[2].split('_')[-1]\n    \n    \n# load test set information\nfilename = 'data/tst_evaluation_keys.csv'\ntst_info = np.loadtxt(filename,dtype='str',delimiter=',',skiprows=1,usecols=range(0,3))\ntst_trials = []\ntst_trials_label = []\ntst_ground_truth =[]\nfor iter in range(len(tst_info)):\n    tst_trials_label.extend([tst_info[iter,0]])\n    if tst_info[iter,1]=='background':\n        tst_trials = np.append(tst_trials,0)\n        \n    else:\n        tst_trials = np.append(tst_trials,1)\n    \n\n# Set random seed to make results reproducible\nseed = 134\nnp.random.seed(seed)\n\n# Loading i-vector\ntrn_bl_id, trn_bl_utt, trn_bl_ivector = load_ivector('data/trn_blacklist.csv')\ntrn_bg_id, trn_bg_utt, trn_bg_ivector = load_ivector('data/trn_background.csv')\ndev_bl_id, dev_bl_utt, dev_bl_ivector = load_ivector('data/dev_blacklist.csv')\ndev_bg_id, dev_bg_utt, dev_bg_ivector = load_ivector('data/dev_background.csv')\ntst_id, test_utt, tst_ivector = load_ivector('data/tst_evaluation.csv')\n\n# length normalization\ntrn_bl_ivector = length_norm(trn_bl_ivector)\ntrn_bg_ivector = length_norm(trn_bg_ivector)\ndev_bl_ivector = length_norm(dev_bl_ivector)\ndev_bg_ivector = length_norm(dev_bg_ivector)\ntst_ivector = length_norm(tst_ivector)\n\n# Inputs to DAE are ivectors and targets are the speaker-level mean ivectors\ntrain_spk_ids = pd.DataFrame({'spk_ids': trn_bg_id})\ntrain_ivs = pd.DataFrame(trn_bg_ivector)\n\nX_train = train_ivs.values\nY_train = (train_ivs.groupby(train_spk_ids['spk_ids']).transform('mean')).values\n\n# DAE training\nmodel = get_DAE()\n\nmodel.compile(loss='cosine_proximity',\n              optimizer = optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=1e-06),\n              metrics=[metrics.mean_squared_error])\n\nnum_examples = X_train.shape[0]\nnum_epochs = 5\nbatch_size = 512\nnum_batch_per_epoch = num_examples / batch_size\n\nmodel.fit(x=X_train,y=Y_train,batch_size=batch_size,epochs=num_epochs)\n\n# Compute DAE-transformed embeddings from ivectors\ntrn_bl_embeddings = model.predict(trn_bl_ivector,batch_size=batch_size)\ntrn_bg_embeddings = model.predict(trn_bg_ivector,batch_size=batch_size)\ndev_bl_embeddings = model.predict(dev_bl_ivector,batch_size=batch_size)\ndev_bg_embeddings = model.predict(dev_bg_ivector,batch_size=batch_size)\ntst_embeddings = model.predict(tst_ivector,batch_size=batch_size)\n\n# Calculating speaker mean vector\nspk_mean, spk_mean_label = make_spkvec(trn_bl_embeddings,trn_bl_id)\n\n# length normalization\ntrn_bl_embeddings = length_norm(trn_bl_embeddings)\ntrn_bg_embeddings = length_norm(trn_bg_embeddings)\ndev_bl_embeddings = length_norm(dev_bl_embeddings)\ndev_bg_embeddings = length_norm(dev_bg_embeddings)\ntst_embeddings = length_norm(tst_embeddings)\n        \nprint('Dev set score using train set :')\n\n# making trials of Dev set\ndev_embeddings = np.append(dev_bl_embeddings, dev_bg_embeddings,axis=0)\ndev_trials = np.append( np.ones([len(dev_bl_id), 1]), np.zeros([len(dev_bg_id), 1]))\n\n# Cosine distance scoring\nscores = spk_mean.dot(dev_embeddings.transpose())\ndev_scores = np.max(scores,axis=0)\n\n# Top-S detector EER\ndev_EER = calculate_EER(dev_trials, dev_scores)\n\n#divide trial label into target and non-target, plus confusion error(blacklist, fail at blacklist detector)\ndev_identified_label = spk_mean_label[np.argmax(scores,axis=0)]\ndev_trials_label = np.append( dev_bl_id,dev_bg_id)\n\n# Top-1 detector EER\ndev_trials_confusion = get_trials_label_with_confusion(dev_identified_label, dev_trials_label, dev2train, dev_trials )\ndev_EER_confusion = calculate_EER_with_confusion(dev_scores,dev_trials_confusion)\n\nprint('Test set score using train set:')\n\n#Cosine distance scoring on Test set\nscores = spk_mean.dot(tst_embeddings.transpose())\ntst_scores = np.max(scores,axis=0)\n\n# top-S detector EER\ntst_EER = calculate_EER(tst_trials, tst_scores)\n\n#divide trial label into target and non-target, plus confusion error(blacklist, fail at blacklist detector)\ntst_identified_label = spk_mean_label[np.argmax(scores,axis=0)]\n\n# Top-1 detector EER\ntst_trials_confusion = get_trials_label_with_confusion(tst_identified_label, tst_trials_label, test2train, tst_trials )\ntst_EER_confusion = calculate_EER_with_confusion(tst_scores,tst_trials_confusion)\n\n\nprint('Test set score using train + dev set:')\n\n# get dev set id consistent with Train set\ndev_bl_id_along_trnset = []\nfor iter in range(len(dev_bl_id)):\n    dev_bl_id_along_trnset.extend([dev2train[dev_bl_id[iter]]])\n\n# Calculating speaker mean vector\nspk_mean, spk_mean_label = make_spkvec(np.append(trn_bl_embeddings,dev_bl_embeddings,0),np.append(trn_bl_id,dev_bl_id_along_trnset))\n\n#Cosine distance scoring on Test set\nscores = spk_mean.dot(tst_embeddings.transpose())\ntst_scores = np.max(scores,axis=0)\n\n# top-S detector EER\ntst_EER = calculate_EER(tst_trials, tst_scores)\n\n#divide trial label into target and non-target, plus confusion error(blacklist, fail at blacklist detector)\ntst_identified_label = spk_mean_label[np.argmax(scores,axis=0)]\n\n# Top-1 detector EER\ntst_trials_confusion = get_trials_label_with_confusion(tst_identified_label, tst_trials_label, test2train,tst_trials )\ntst_EER_confusion = calculate_EER_with_confusion(tst_scores,tst_trials_confusion)\n", "meta": {"hexsha": "b4a79165f1beaf278dced02ae67c497c5dc2b4a7", "size": 7804, "ext": "py", "lang": "Python", "max_stars_repo_path": "mce2018_dae_tst.py", "max_stars_repo_name": "BiometricVox/DAE_SpeakerID", "max_stars_repo_head_hexsha": "b4c572e0dd258593517fe96764bf687c109b24e5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2019-02-24T10:03:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T00:15:15.000Z", "max_issues_repo_path": "mce2018_dae_tst.py", "max_issues_repo_name": "BiometricVox/DAE_SpeakerID", "max_issues_repo_head_hexsha": "b4c572e0dd258593517fe96764bf687c109b24e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mce2018_dae_tst.py", "max_forks_repo_name": "BiometricVox/DAE_SpeakerID", "max_forks_repo_head_hexsha": "b4c572e0dd258593517fe96764bf687c109b24e5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:57:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-14T16:24:31.000Z", "avg_line_length": 38.6336633663, "max_line_length": 138, "alphanum_fraction": 0.7817785751, "include": true, "reason": "import numpy", "num_tokens": 2051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.18846261649487922}}
{"text": "\"Scripts for generating, solving and sweeping programs\"\nfrom __future__ import unicode_literals, print_function\nfrom time import time\nimport numpy as np\nfrom ..nomials import parse_subs\nfrom ..solution_array import SolutionArray\nfrom ..keydict import KeyDict\nfrom ..small_scripts import maybe_flatten\n\ntry:\n    from ad import adnumber\nexcept ImportError:\n    adnumber = None\n    print(\"Couldn't import ad; automatic differentiation of linked variables\"\n          \" is disabled.\")\n\n\ndef evaluate_linked(constants, linked):\n    \"Evaluates the values and gradients of linked variables.\"\n    if adnumber:\n        kdc = KeyDict({k: adnumber(maybe_flatten(v))\n                       for k, v in constants.items()})\n        kdc.log_gets = True\n    kdc_plain = None\n    array_calulated, logged_array_gets = {}, {}\n    for v, f in linked.items():\n        try:\n            assert adnumber  # trigger exit if ad not found\n            if v.veckey and v.veckey.original_fn:\n                if v.veckey not in array_calulated:\n                    ofn = v.veckey.original_fn\n                    array_calulated[v.veckey] = np.array(ofn(kdc))\n                    logged_array_gets[v.veckey] = kdc.logged_gets\n                logged_gets = logged_array_gets[v.veckey]\n                out = array_calulated[v.veckey][v.idx]\n            else:\n                logged_gets = kdc.logged_gets\n                out = f(kdc)\n            constants[v] = out.x\n            v.descr[\"gradients\"] = {}\n            for key in logged_gets:\n                if key.shape:\n                    grad = out.gradient(kdc[key])\n                    v.gradients[key] = np.array(grad)\n                else:\n                    v.gradients[key] = out.d(kdc[key])\n        except Exception:  # pylint: disable=broad-except\n            from .. import settings\n            if settings.get(\"ad_errors_raise\", None):\n                raise\n            if adnumber:\n                print(\"Couldn't auto-differentiate linked variable %s\\n  \"\n                      \"(to raise the error directly for debugging purposes,\"\n                      \" set gpkit.settings[\\\"ad_errors_raise\\\"] to True)\" % v)\n            if kdc_plain is None:\n                kdc_plain = KeyDict(constants)\n            constants[v] = f(kdc_plain)\n            v.descr.pop(\"gradients\", None)\n        finally:\n            if adnumber:\n                kdc.logged_gets = set()\n\n\ndef _progify_fctry(program, return_attr=None):\n    \"\"\"Generates function that returns a program() and optionally an attribute.\n\n    Arguments\n    ---------\n    program: NomialData\n        Class to return, e.g. GeometricProgram or SequentialGeometricProgram\n    return_attr: string\n        attribute to return in addition to the program\n    \"\"\"\n    def programify(self, constants=None, **kwargs):\n        \"Return program version of self\"\n        if not constants:\n            constants, _, linked = parse_subs(self.varkeys, self.substitutions)\n            if linked:\n                evaluate_linked(constants, linked)\n        prog = program(self.cost, self, constants, **kwargs)\n        if return_attr:\n            return prog, getattr(prog, return_attr)\n        return prog\n    return programify\n\n\ndef _solve_fctry(genfunction):\n    \"Returns function for making/solving/sweeping a program.\"\n    def solvefn(self, solver=None, verbosity=1, skipsweepfailures=False,\n                **kwargs):\n        \"\"\"Forms a mathematical program and attempts to solve it.\n\n         Arguments\n         ---------\n         solver : string or function (default None)\n             If None, uses the default solver found in installation.\n         verbosity : int (default 1)\n             If greater than 0 prints runtime messages.\n             Is decremented by one and then passed to programs.\n         skipsweepfailures : bool (default False)\n             If True, when a solve errors during a sweep, skip it.\n         **kwargs : Passed to solver\n\n         Returns\n         -------\n         sol : SolutionArray\n             See the SolutionArray documentation for details.\n\n         Raises\n         ------\n         ValueError if the program is invalid.\n         RuntimeWarning if an error occurs in solving or parsing the solution.\n         \"\"\"\n        constants, sweep, linked = parse_subs(self.varkeys, self.substitutions)\n        solution = SolutionArray()\n\n        # NOTE SIDE EFFECTS: self.program is set below\n        if sweep:\n            run_sweep(genfunction, self, solution, skipsweepfailures,\n                      constants, sweep, linked,\n                      solver, verbosity, **kwargs)\n        else:\n            self.program, progsolve = genfunction(self)\n            result = progsolve(solver, verbosity, **kwargs)\n            solution.append(result)\n        solution.program = self.program\n        solution.model = self\n        solution.to_arrays()\n        if self.cost.units:\n            solution[\"cost\"] = solution[\"cost\"] * self.cost.units\n        self.solution = solution  # NOTE: SIDE EFFECTS\n        return solution\n    return solvefn\n\n\n# pylint: disable=too-many-locals,too-many-arguments\ndef run_sweep(genfunction, self, solution, skipsweepfailures,\n              constants, sweep, linked,\n              solver, verbosity, **kwargs):\n    \"Runs through a sweep.\"\n    # sort sweeps by the eqstr of their varkey\n    sweepvars, sweepvals = zip(*sorted(list(sweep.items()),\n                                       key=lambda vkval: vkval[0].eqstr))\n    if len(sweep) == 1:\n        sweep_grids = np.array(list(sweepvals))\n    else:\n        sweep_grids = np.meshgrid(*list(sweepvals))\n\n    N_passes = sweep_grids[0].size\n    sweep_vects = {var: grid.reshape(N_passes)\n                   for (var, grid) in zip(sweepvars, sweep_grids)}\n\n    if verbosity > 0:\n        print(\"Solving over %i passes.\" % N_passes)\n        tic = time()\n\n    self.program = []\n    for i in range(N_passes):\n        constants.update({var: sweep_vect[i]\n                          for (var, sweep_vect) in sweep_vects.items()})\n        if linked:\n            kdc = KeyDict(constants)\n            constants.update({v: f(kdc) for v, f in linked.items()})\n        program, solvefn = genfunction(self, constants)\n        self.program.append(program)  # NOTE: SIDE EFFECTS\n        try:\n            solution.append(solvefn(solver, verbosity-1, **kwargs))\n        except (RuntimeWarning, ValueError):\n            if not skipsweepfailures:\n                raise RuntimeWarning(\"solve failed during sweep; program\"\n                                     \" has been saved to m.program[-1].\"\n                                     \" To ignore such failures, solve with\"\n                                     \" skipsweepfailures=True.\")\n    if not solution:\n        raise RuntimeWarning(\"no sweeps solved successfully.\")\n\n    solution[\"sweepvariables\"] = KeyDict()\n    ksweep = KeyDict(sweep)\n    for var, val in list(solution[\"constants\"].items()):\n        if var in ksweep:\n            solution[\"sweepvariables\"][var] = val\n            del solution[\"constants\"][var]\n        elif var not in linked:\n            solution[\"constants\"][var] = [val[0]]\n\n    if verbosity > 0:\n        soltime = time() - tic\n        print(\"Sweeping took %.3g seconds.\" % (soltime,))\n", "meta": {"hexsha": "31467a90c52a138988111db8beafe3d8287984cd", "size": 7211, "ext": "py", "lang": "Python", "max_stars_repo_path": "gpkit/constraints/prog_factories.py", "max_stars_repo_name": "giserh/gpkit", "max_stars_repo_head_hexsha": "71b953fcac8f67f148b67b54b6e8cd4182dc0b3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gpkit/constraints/prog_factories.py", "max_issues_repo_name": "giserh/gpkit", "max_issues_repo_head_hexsha": "71b953fcac8f67f148b67b54b6e8cd4182dc0b3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gpkit/constraints/prog_factories.py", "max_forks_repo_name": "giserh/gpkit", "max_forks_repo_head_hexsha": "71b953fcac8f67f148b67b54b6e8cd4182dc0b3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1534391534, "max_line_length": 79, "alphanum_fraction": 0.5848009985, "include": true, "reason": "import numpy", "num_tokens": 1577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.18846260763408618}}
{"text": "\"\"\"\nModified from PointConv: https://github.com/DylanWusee/pointconv\nAuthor: Jiachen Xu and Jingyu Gong\nDate: June 2020\n\"\"\"\n\nimport os\nimport sys\nBASE_DIR = os.path.dirname(__file__)\nsys.path.append(BASE_DIR)\nsys.path.append(os.path.join(BASE_DIR, '../'))\nsys.path.append(os.path.join(BASE_DIR, '../utils'))\nimport tensorflow as tf\nimport numpy as np\nimport tf_util\nfrom PointConv import feature_encoding_layer, feature_decoding_layer, feature_encoding_layer_extra\n\ndef placeholder_scene_inputs(batch_size, num_point, num_classes):\n    pointclouds_pl = tf.placeholder(tf.float32, shape=(batch_size, num_point, 6))\n    labels_pl = tf.placeholder(tf.int32, shape=(batch_size, num_point))\n    labels_onehot_pl = tf.placeholder(tf.float32, shape=(batch_size, num_point,num_classes))\n    smpws_pl = tf.placeholder(tf.float32, shape=(batch_size, num_point))\n    external_scene_encode_pl = tf.placeholder(tf.int32,shape=(batch_size,num_classes))\n\n    cos_loss_weight = tf.placeholder(tf.float32, shape=None)\n    return pointclouds_pl, labels_pl, labels_onehot_pl, smpws_pl, external_scene_encode_pl, cos_loss_weight\n\ndef get_scene_model(point_cloud, is_training, num_class, sigma, bn_decay=None, weight_decay = None):\n    \"\"\" Semantic segmentation PointNet, input is BxNx3, output Bxnum_class \"\"\"\n\n    batch_size = point_cloud.get_shape()[0].value\n    num_point = point_cloud.get_shape()[1].value\n    end_points = {}\n    l0_xyz = point_cloud[:,:,:3]\n    l0_points = point_cloud\n    l0_points_xyz = point_cloud[:,:,:3]\n    l0_points_rgb = point_cloud[:,:,3:]\n\n    # Feature encoding layers\n    l1_xyz, l1_points_xyz = feature_encoding_layer(l0_xyz, l0_points_xyz, npoint=2048, radius = 0.1, sigma = sigma, K=8, mlp=[32,32,32], akc_channel = 3, is_training=is_training, bn_decay=bn_decay, weight_decay = weight_decay, scope='layer1_xyz')\n    _, l1_points_rgb = feature_encoding_layer_extra(l0_xyz, l1_xyz, l0_points_rgb, npoint=2048, radius = 0.1, sigma = sigma, K=8, mlp=[32,32,32], akc_channel = 3, is_training=is_training, bn_decay=bn_decay, weight_decay = weight_decay, scope='layer1_rgb')\n    l1_points = tf.concat([l1_points_xyz, l1_points_rgb], -1)\n    l1_xyz_1024, l1_points_1024 = feature_encoding_layer(l1_xyz, l1_points, npoint=1024, radius = 0.1, sigma = sigma, K=8, mlp=[32,32,64], akc_channel=16, is_training=is_training, bn_decay=bn_decay, weight_decay = weight_decay, scope='layer1_1024')\n    l1_xyz_512, l1_points_512 = feature_encoding_layer(l1_xyz_1024, l1_points_1024, npoint=512, radius = 0.1, sigma = sigma, K=8, mlp=[64,64,64], akc_channel=32, is_training=is_training, bn_decay=bn_decay, weight_decay = weight_decay, scope='layer1_512')\n    l2_xyz, l2_points = feature_encoding_layer(l1_xyz_512, l1_points_512, npoint=256, radius = 0.2, sigma = 2 * sigma, K=8, mlp=[64,64,128], akc_channel=32, is_training=is_training, bn_decay=bn_decay, weight_decay = weight_decay, scope='layer2')\n    l2_xyz_128, l2_points_128 = feature_encoding_layer(l2_xyz, l2_points, npoint=128, radius = 0.2, sigma = 2 * sigma, K=8, mlp=[128,128,128], akc_channel=None, is_training=is_training, bn_decay=bn_decay, weight_decay = weight_decay, scope='layer2_128')\n    l3_xyz, l3_points = feature_encoding_layer(l2_xyz_128, l2_points_128, npoint=64, radius = 0.4, sigma = 4 * sigma, K=8, mlp=[128,128,256], akc_channel=None, is_training=is_training, bn_decay=bn_decay, weight_decay = weight_decay, scope='layer3')\n    l4_xyz, l4_points = feature_encoding_layer(l3_xyz, l3_points, npoint=36, radius = 0.8, sigma = 8 * sigma, K=8, mlp=[256,256,512], akc_channel=None, is_training=is_training, bn_decay=bn_decay, weight_decay = weight_decay, scope='layer4')\n\n    external_l5_xyz,external_l5_points = feature_encoding_layer(l4_xyz, l4_points, npoint=8, radius = 1.6, sigma = 8 * sigma, K=8, mlp=[512,512,512], akc_channel=None, is_training=is_training, bn_decay=bn_decay, weight_decay = weight_decay, scope='external_layer5')\n    external_l6_scene_feature = tf.reduce_mean(external_l5_points,axis=1,keepdims=True)\n    external_scene_feature = tf_util.dropout(external_l6_scene_feature, keep_prob=0.5, is_training=is_training, scope='external_dp')\n    external_scene_feature = tf_util.conv1d(external_scene_feature, num_class, 1, padding='VALID', activation_fn=None, weight_decay=weight_decay, scope='external_fc')\n\n\n    # Feature decoding layers\n    l3_points = feature_decoding_layer(l3_xyz, l4_xyz, l3_points, l4_points, 0.8, 8 * sigma, 8, [512,512], is_training, bn_decay, weight_decay, scope='fa_layer1')\n    l2_points_128 = feature_decoding_layer(l2_xyz_128, l3_xyz, l2_points_128, l3_points, 0.4, 4 * sigma, 8, [256,256], is_training, bn_decay, weight_decay, scope='fa_layer2_128')\n    l2_points = feature_decoding_layer(l2_xyz, l2_xyz_128, l2_points, l2_points_128, 0.4, 4 * sigma, 8, [256,256], is_training, bn_decay, weight_decay, scope='fa_layer2')\n    l1_points_512 = feature_decoding_layer(l1_xyz_512, l2_xyz, l1_points_512, l2_points, 0.2, 2 * sigma, 8, [256,256], is_training, bn_decay, weight_decay, scope='fa_layer3_512') \n    l1_points_1024 = feature_decoding_layer(l1_xyz_1024, l1_xyz_512, l1_points_1024, l1_points_512, 0.2, 2 * sigma, 8, [256,256], is_training, bn_decay, weight_decay, scope='fa_layer3_1024')\n    l1_points = feature_decoding_layer(l1_xyz, l1_xyz_1024, l1_points, l1_points_1024, 0.2, 2 * sigma, 8, [256,128], is_training, bn_decay, weight_decay, scope='fa_layer3')\n    l0_points = feature_decoding_layer(l0_xyz, l1_xyz, l0_points, l1_points, 0.1, sigma, 8, [128,128,128], is_training, bn_decay, weight_decay, scope='fa_layer4')\n\n    # FC layers\n    net = tf_util.conv1d(l0_points, 128, 1, padding='VALID', bn=True, is_training=is_training, scope='fc1', bn_decay=bn_decay, weight_decay=weight_decay)\n    end_points['feats'] = net\n    net = tf_util.dropout(net, keep_prob=0.5, is_training=is_training, scope='dp1')\n    net = tf_util.conv1d(net, num_class, 1, padding='VALID', activation_fn=None, weight_decay=weight_decay, scope='fc2')\n\n    return net, end_points, external_scene_feature\n\ndef get_mask(label1, label2):\n    num_points1 = label1.get_shape().as_list()[1]\n    num_points2 = label2.get_shape().as_list()[1]\n\n    label1 = tf.expand_dims(label1, axis=-1)\n    label2 = tf.expand_dims(label2, axis=-1)\n    label2_transpose = tf.transpose(label2, perm=[0, 2, 1])\n\n    label1 = tf.tile(label1, [1, 1, num_points2])\n    label2_transpose = tf.tile(label2_transpose, [1, num_points1, 1])\n\n    # if they have same label, the make value is -1\n    mask = (tf.cast(tf.equal(label1, label2_transpose), tf.float32) - 1) * 255\n\n    return mask\n\n\ndef knn1(xyz1, xyz2, k=4, label1=None, label2=None):\n    xyz1 = tf.squeeze(xyz1)\n    xyz2 = tf.squeeze(xyz2)\n\n    xyz2_transpose = tf.transpose(xyz2, perm=[0, 2, 1])\n    point_cloud_inner = tf.matmul(xyz1, xyz2_transpose)\n\n    point_cloud_inner = -2 * point_cloud_inner\n    xyz1_square = tf.reduce_sum(tf.square(xyz1), axis=-1, keep_dims=True)\n\n    xyz2_square = tf.reduce_sum(tf.square(xyz2), axis=-1, keep_dims=True)\n\n    xyz2_square_trans = tf.transpose(xyz2_square, perm=[0, 2, 1])\n\n\n    adj_matrix = xyz1_square + point_cloud_inner + xyz2_square_trans\n\n    neg_adj = -adj_matrix\n\n    if label1 is not None:\n        mask = get_mask(label1, label2)\n        neg_adj += mask\n\n    _, nn_idx = tf.nn.top_k(neg_adj, k=k)\n    return nn_idx\n\ndef get_scene_loss(cos_loss_weight, pred, label, label_onehot, smpw, external_scene_feature,external_scene_encode, point_features=None, xyz=None):\n    \"\"\" pred: BxNxC,\n        label: BxN,\n\tsmpw: BxN \"\"\"\n    if point_features is not None:\n        pred_possibility = tf.reduce_max(tf.nn.softmax(pred, axis=-1), axis=-1)\n        pred_class = tf.cast(tf.argmax(pred, axis=-1), tf.int32)\n\n        batch_size, num_point, num_dims = point_features.get_shape()[:3]\n        xyz_lst, feature_lst, label_lst = [], [], []\n\n        def f1(correct_index1, i, possibility, correct_num):\n            choice = tf.cond(tf.less(correct_num, 2048), lambda: f4(possibility, correct_num), lambda: f3(possibility))\n\n            choice.set_shape([2048])\n\n            correct_index = tf.squeeze(tf.gather(correct_index1, choice))\n\n            xyz_lst.append(tf.expand_dims(tf.gather(xyz[i], correct_index), axis=0))\n            feature_lst.append(tf.expand_dims(tf.gather(point_features[i], correct_index), axis=0))\n            label_lst.append(tf.expand_dims(tf.gather(label[i], correct_index), axis=0))\n\n            return tf.constant(False)\n\n        def f2():\n            loss_xyz = tf.concat(xyz_lst, axis=0)\n            loss_feature = tf.concat(feature_lst, axis=0)\n            loss_label = tf.concat(label_lst, axis=0)\n\n\n            idx = knn1(loss_xyz, xyz, 8, loss_label, label)\n            idx_ = tf.range(batch_size) * num_point\n            idx_ = tf.reshape(idx_, [batch_size, 1, 1])\n\n            point_features_flat = tf.reshape(point_features, [-1, num_dims])\n            point_features_neighbors = tf.gather(point_features_flat, idx+idx_)\n            point_features_central = tf.tile(tf.expand_dims(loss_feature, 2), [1, 1, 8, 1])\n\n            point_features_central = tf.stop_gradient(point_features_central)\n\n            norm1 = tf.sqrt(tf.reduce_sum(tf.square(point_features_neighbors), axis=-1))\n            norm2 = tf.sqrt(tf.reduce_sum(tf.square(point_features_central), axis=-1))\n            product = tf.reduce_sum(point_features_neighbors * point_features_central, axis=-1)\n            cos_loss = tf.reduce_mean(product / (norm1 * norm2 + 1e-5))\n\n            return 1 - cos_loss\n\n        def f3(possibility):\n            _, choice = tf.nn.top_k(possibility, k=2048)\n\n            return choice\n\n        def f4(possibility, correct_num):\n            possibility_max = tf.argmax(possibility, output_type=tf.int32)\n\n            _, choice = tf.nn.top_k(possibility, k=correct_num * 2 // 3)\n\n            choice = tf.pad(choice, [[0, 2048 - correct_num * 2 // 3]], mode=\"CONSTANT\", constant_values=possibility_max)\n\n            return choice\n\n        judge_lst = []\n        for i in range(batch_size):\n            index = tf.equal(pred_class[i], label[i])\n            correct_num = tf.reduce_sum(tf.cast(index, tf.int32))\n            correct_index1 = tf.reshape(tf.where(index), [-1])\n            possibility = tf.gather(pred_possibility[i], correct_index1)\n\n            judge_lst.append(tf.cond(tf.equal(correct_num, tf.constant(0)),\n                                    lambda: tf.constant(True),\n                                    lambda: f1(correct_index1, i, possibility, correct_num)))\n\n        cos_loss = tf.cond(tf.equal(tf.reduce_sum(tf.cast(judge_lst, tf.int32)), tf.constant(0)), lambda: f2(), lambda: tf.constant(1.0))\n\n    else:\n        cos_loss = tf.constant(0.0)\n\n    external_scene_feature_2d = tf.squeeze(external_scene_feature,[1])\n    external_scene_loss = tf.losses.sigmoid_cross_entropy(external_scene_encode,external_scene_feature_2d)\n    external_scene_probability = tf.sigmoid(external_scene_feature)\n    external_scene_probability = tf.tile(external_scene_probability,[1,pred.get_shape()[1],1])\n    external_scene_probability = tf.stop_gradient(external_scene_probability)\n    pred = tf.nn.softmax(pred)\n    pred = tf.multiply(pred,external_scene_probability)\n    softmax_probability_sum = tf.reduce_sum(pred,axis=2,keepdims=True)\n    softmax_probability_sum = tf.tile(softmax_probability_sum,[1,1,pred.get_shape()[2]])\n    pred = tf.div(pred,softmax_probability_sum+1e-5)\n    classify_loss = tf.keras.backend.categorical_crossentropy(label_onehot,pred)\n    classify_loss = classify_loss * smpw\n    print('add smpw')\n\n    weight_reg = tf.add_n(tf.get_collection('losses'))\n    classify_loss_mean = tf.reduce_mean(classify_loss, name='classify_loss_mean')\n    total_loss = classify_loss_mean + weight_reg + cos_loss * cos_loss_weight + external_scene_loss\n    tf.summary.scalar('classify loss', classify_loss_mean)\n    tf.summary.scalar('total loss', total_loss)\n\n    return total_loss, pred\n\nif __name__=='__main__':\n    import pdb\n    pdb.set_trace()\n\n    with tf.Graph().as_default():\n        inputs = tf.zeros((32,2048,3))\n        net, _ = get_model(inputs, tf.constant(True), 10, 1.0)\n        print(net)\n", "meta": {"hexsha": "bc60549eb641e40893cae3592977649543a38545", "size": 12122, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/scene_encoder_rsl.py", "max_stars_repo_name": "azuki-miho/GeoSceneEncoder", "max_stars_repo_head_hexsha": "a7645d048bbb532e5116bad0ccb7883926357241", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-11T06:46:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T06:46:16.000Z", "max_issues_repo_path": "models/scene_encoder_rsl.py", "max_issues_repo_name": "azuki-miho/GeoSceneEncoder", "max_issues_repo_head_hexsha": "a7645d048bbb532e5116bad0ccb7883926357241", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/scene_encoder_rsl.py", "max_forks_repo_name": "azuki-miho/GeoSceneEncoder", "max_forks_repo_head_hexsha": "a7645d048bbb532e5116bad0ccb7883926357241", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.3587443946, "max_line_length": 265, "alphanum_fraction": 0.7122587032, "include": true, "reason": "import numpy", "num_tokens": 3419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.18846260763408618}}
{"text": "from __future__ import print_function\nimport numpy as np\nimport os\nimport warnings\nfrom collections import defaultdict\nfrom astropy import constants\nfrom astropy import log\nfrom .. import base_class\nfrom ..utils import ImmutableDict,unitless,lower_keys\nfrom .. import utils\n\nimport astropy.units as u\n_quantity = u.Quantity\n\nclass Fjdu(base_class.RadiativeTransferApproximator):\n    def __init__(self, datapath=None, species='co',\n                 density=None,\n                 collider_densities=None,\n                 temperature=None,\n                 tbg=2.73,\n                 column=None,\n                 abundance=None,\n                 escapeProbGeom='lvg',\n                 **kwargs):\n\n        if os.getenv('RADEX_DATAPATH') and datapath is None:\n            datapath = os.getenv('RADEX_DATAPATH')\n\n        self.datapath = os.path.dirname(datapath)\n        self.species = species\n\n        self._is_locked = False\n        self._locked_parameter = None\n        self.set_default_params()\n        self.set_params(temperature=temperature, density=density,\n                        collider_densities=collider_densities,\n                        column=column, geotype=escapeProbGeom, **kwargs)\n        self.tbg = tbg\n        from pyradex.fjdu import wrapper_my_radex\n        myradex_wrapper = wrapper_my_radex.myradex_wrapper\n        self._myradex = myradex_wrapper\n        self._is_locked = False\n        self._locked_parameter = None\n\n        if abundance is not None:\n            if density is not None or collider_densities is not None:\n                self._locked_parameter = 'density'\n            elif column is not None:\n                self._locked_parameter = 'column'\n            else:\n                raise ValueError(\"At least two of column, density, and \"\n                                 \"abundance must be specified\")\n            self.abundance = abundance\n\n    def __call__(self, return_table=True, **kwargs):\n\n        niter = self.run_radex(**kwargs)\n\n        if return_table:\n            return self.get_table()\n        else:\n            return niter\n\n    def load_datafile(self, filename=None, verbose=False):\n        filename = filename or self.molpath\n        self.datapath = (os.path.dirname(filename) or self.datapath)+\"/\"\n        self.fname = os.path.basename(filename)\n\n        nlevels, nitems, ntrans = self._myradex.config_basic(self.datapath,\n                                                             self.fname,\n                                                             unitless(self.tbg),\n                                                             verbose)\n        self.set_params(**{'n_levels': nlevels,\n                           'n_item': nitems,\n                           'n_transitions': ntrans})\n\n    def run_radex(self, **kwargs):\n\n        # drop kwargs kept for compatibility with Radex\n        ignore_kwargs = ['reuse_last', 'reload_molfile']\n        for ik in ignore_kwargs:\n            if ik in kwargs:\n                kwargs.pop(ik)\n\n        self.set_params(**kwargs)\n        self.load_datafile()\n        energies, f_occupations, data_transitions, cooling_rate = \\\n                self._myradex.run_one_params(**self.params)\n        self._energies = u.Quantity(energies, u.K) # excitation temperature\n        self._data_dict = cast_into_dic(self._myradex.column_names.tostring().decode(),\n                                        data_transitions)\n        self._level_population = f_occupations\n\n\n    _default_params = (('tkin', 0.0),\n                       ('dv_CGS', 1e5),\n                       ('dens_X_CGS', 0.0),\n                       ('Ncol_X_CGS', 0.0),\n                       ('H2_density_CGS', 0.0),\n                       ('HI_density_CGS', 0.0),\n                       ('oH2_density_CGS', 0.0),\n                       ('pH2_density_CGS', 0.0),\n                       ('HII_density_CGS', 0.0),\n                       ('Electron_density_CGS', 0.0),\n                       ('n_levels', 0),\n                       ('n_item', 0),\n                       ('n_transitions', 0),\n                       ('geotype', 'lvg'),\n                      )\n\n    _keyword_map = {#'temperature': 'tkin',\n                    'deltav': 'dv_cgs',\n                    #'column': 'ncol_x_cgs',\n                   }\n\n    _density_keyword_map = {'h2': 'h2_density_cgs',\n                            'h': 'hi_density_cgs',\n                            'oh2': 'oh2_density_cgs',\n                            'ph2': 'ph2_density_cgs',\n                            'hii': 'hii_density_cgs',\n                            'e': 'electron_density_cgs',\n                           }\n\n    def set_default_params(self):\n        self._params = lower_keys(dict(self._default_params))\n\n    def set_params(self, **kwargs):\n        default = lower_keys(dict(self._default_params))\n        for k in kwargs:\n            if kwargs[k] is None:\n                continue\n            if k == 'deltav':\n                # deltav requires unit conversion\n                self.deltav = kwargs[k]\n            elif k.lower() in self._keyword_map:\n                self._params[self._keyword_map[k]] = kwargs[k]\n            elif k.lower() in ('density','collider_densities'):\n                self.density = kwargs[k]\n            elif k.lower() == 'column':\n                self.column = kwargs[k]\n            elif k.lower() == 'temperature':\n                # temperature _cannot_ be set until density is\n                if not hasattr(self, '_use_thermal_opr'):\n                    try:\n                        self.density = kwargs['density']\n                    except KeyError:\n                        self.density = kwargs['collider_densities']\n                self.temperature = kwargs[k]\n            elif k == 'tbg':\n                self.tbg = kwargs[k]\n            elif k == 'species':\n                self.species = kwargs[k]\n            elif k.lower() not in default:\n                raise ValueError(\"{0} is not a valid key.\".format(k))\n            else:\n                self._params[k] = kwargs[k]\n\n\n    @property\n    def params(self):\n        return lower_keys(self._params)\n\n    @params.setter\n    def params(self, value):\n        if not isinstance(value, dict):\n            raise TypeError('Parameters must be a dictionary.')\n        self.set_params(**value)\n\n    @property\n    def density(self):\n\n        dd = {'H2': u.Quantity(self.params['h2_density_cgs'], self._u_cc),\n              'OH2': u.Quantity(self.params['oh2_density_cgs'], self._u_cc),\n              'PH2': u.Quantity(self.params['ph2_density_cgs'], self._u_cc),\n              'E': u.Quantity(self.params['electron_density_cgs'], self._u_cc),\n              'H+': u.Quantity(self.params['hii_density_cgs'], self._u_cc),\n              'H': u.Quantity(self.params['hi_density_cgs'], self._u_cc),\n              'He': u.Quantity(0, self._u_cc),}\n        return ImmutableDict(dd)\n\n    @density.setter\n    def density(self, collider_density):\n\n        self._use_thermal_opr = False\n\n        if isinstance(collider_density, (float,int,_quantity,np.ndarray)):\n            log.warn(\"Assuming the density is n(H_2).\")\n            collider_density = {'H2': collider_density}\n\n        collider_densities = defaultdict(lambda: 0)\n        for k in collider_density:\n            collider_densities[k.upper()] = unitless(u.Quantity(collider_density[k],\n                                                                self._u_cc))\n            if k.upper() not in self._all_valid_colliders:\n                raise ValueError('Collider %s is not one of the valid colliders: %s' %\n                                 (k,self._all_valid_colliders))\n\n        if (('OH2' in collider_densities and collider_densities['OH2'] !=0) or\n            ('PH2' in collider_densities and collider_densities['PH2'] !=0)):\n            if not 'PH2' in collider_densities or not 'OH2' in collider_densities:\n                raise ValueError(\"If o-H2 density is specified, p-H2 must also be.\")\n            # dictionary of collider densities\n            for k in collider_densities:\n                if k.lower() in self._density_keyword_map:\n                    key = self._density_keyword_map[k.lower()]\n                    self._params[key.lower()] = collider_densities[k]\n                elif k.lower() in self._density_keyword_map.values():\n                    self._params[k.lower()] = collider_densities[k]\n                else:\n                    raise KeyError(\"Collider {0} not recognized.\".format(k))\n            self._params['dens_x_cgs'] = self.total_density.value\n            self._use_thermal_opr = False\n        elif 'H2' in collider_densities and 'H2' in self._valid_colliders:\n            # H2 is a collider in the file: use it.\n            self._params['dens_x_cgs'] = collider_density['H2']\n            for k in self._density_keyword_map.values():\n                self._params[k] = 0.0\n            self._params['h2_density_cgs'] = collider_density['H2']\n        elif 'H2' in collider_densities:\n            # Only oH2 and pH2 are in the file.  Must assume.\n            warnings.warn(\"Using a default ortho-to-para ratio (which \"\n                          \"will only affect species for which independent \"\n                          \"ortho & para collision rates are given)\")\n            self._use_thermal_opr = True\n            #self.radex.cphys.density[0] = collider_densities['H2']\n\n            T = unitless(self.temperature)\n            if T > 0:\n                # From Faure, private communication\n                opr = min(3.0,9.0*np.exp(-170.6/T))\n            else:\n                opr = 3.0\n            fortho = opr/(1+opr)\n            log.debug(\"Set OPR to {0} and fortho to {1}\".format(opr,fortho))\n            self._params['oh2_density_cgs'] = collider_density['H2']*(fortho)\n            self._params['ph2_density_cgs'] = collider_density['H2']*(1-fortho)\n            self._params['dens_x_cgs'] = self.total_density.value\n\n\n    @property\n    def temperature(self):\n        return u.Quantity(self.params['tkin'], u.K)\n\n    @temperature.setter\n    def temperature(self, tkin):\n        if hasattr(tkin,'to'):\n            tkin = unitless(u.Quantity(tkin, u.K))\n        if tkin <= 0 or tkin > 1e4:\n            raise ValueError('Must have kinetic temperature > 0 and < 10^4 K')\n        self.set_params(tkin=tkin)\n\n        if self._use_thermal_opr:\n            # Reset the density to a thermal value\n            lp = self._locked_parameter\n            self.density = (unitless(self.density['H2']) or\n                            unitless(self.density['OH2']+self.density['PH2']))\n            self._locked_parameter = lp\n\n    @property\n    def column_per_bin(self):\n        return u.Quantity(self.params['ncol_x_cgs'], self._u_sc)\n\n    @column_per_bin.setter\n    def column_per_bin(self, col):\n        if hasattr(col,'to'):\n            col = unitless(u.Quantity(col, self._u_sc))\n        if col < 1e5 or col > 1e25:\n            raise ValueError(\"Extremely low or extremely high column.\")\n        self.set_params(ncol_x_cgs=col)\n\n        col = u.Quantity(col, self._u_sc)\n        if not self._is_locked:\n            self._is_locked = True\n            if self.locked_parameter == 'density':\n                ab = (col/(self.total_density * self.length))\n                if hasattr(ab, 'decompose'):\n                    self.abundance = ab.decompose().value\n                else:\n                    self.abundance = ab / (self._u_cc*u.pc).to(self._u_sc)\n            elif self.locked_parameter == 'abundance':\n                self.density = col / self.length / self.abundance\n            self._lock_param('column')\n            self._is_locked = False\n\n    @property\n    def abundance(self):\n        return self._abundance\n\n    @abundance.setter\n    def abundance(self, abund):\n        self._abundance = abund\n        if not self._is_locked:\n            self._is_locked = True\n            if self.locked_parameter == 'column':\n                dens = self.column_per_bin / self.length / abund\n                self.density = dens\n            elif self.locked_parameter == 'density':\n                col = self.total_density*self.length*abund\n                self.column_per_bin = u.Quantity(col, u.cm**-2)\n            self._lock_param('abundance')\n            self._is_locked=False\n\n    @property\n    def tbg(self):\n        return u.Quantity(self._tbg, u.K)\n\n    @tbg.setter\n    def tbg(self, tbg):\n        if hasattr(tbg, 'value'):\n            self._tbg = unitless(u.Quantity(tbg, u.K))\n        else:\n            self._tbg = tbg\n\n    @property\n    def deltav(self):\n        return u.Quantity(self.params['dv_cgs']*self._kms_to_cms, self._u_kms)\n\n    _kms_to_cms = 1e-5\n    _u_cms = u.cm/u.s\n\n    @deltav.setter\n    def deltav(self, dv):\n        if hasattr(dv, 'unit'):\n            self._params['dv_cgs'] = unitless(dv.to(self._u_cms))\n        else:\n            self._params['dv_cgs'] = unitless(u.Quantity(dv/self._kms_to_cms,\n                                                         self._u_cms))\n\n    @property\n    def molpath(self):\n        if hasattr(self,'_molpath'):\n            return self._molpath\n\n    @molpath.setter\n    def molpath(self, molfile):\n        if \"~\" in molfile:\n            molfile = os.path.expanduser(molfile)\n        utils.verify_collisionratefile(molfile)\n        self._molpath = molfile\n\n    @property\n    def datapath(self):\n        return self._datapath\n\n    @datapath.setter\n    def datapath(self, datapath):\n        self._datapath = datapath\n\n    @property\n    def escapeprobProbGeom(self):\n        return self._params['geotype']\n\n    @escapeprobProbGeom.setter\n    def escapeprobProbGeom(self, value):\n        if value in ('lvg','spherical','slab'):\n            self._params['geotype'] = value\n        else:\n            raise ValueError(\"Geometry must be spherical, slab, or lvg\")\n\n    _um_to_ghz = u.um.to(u.GHz, equivalencies=u.spectral())\n\n    @property\n    def frequency(self):\n        return u.Quantity(self._um_to_ghz/self._data_dict['lam'], unit=u.GHz)\n\n    @property\n    def level_population(self):\n        return self._level_population\n\n    @property\n    def tex(self):\n        return u.Quantity(self._data_dict['Tex'], u.K)\n\n    Tex = tex\n\n    @property\n    def tau(self):\n        return self._data_dict['tau']\n\n    @property\n    def upperstateenergy(self):\n        return u.Quantity(self._data_dict['Eup'], u.K)\n\n    @property\n    def upperlevelnumber(self):\n        return self._data_dict['iup']\n\n    @property\n    def lowerlevelnumber(self):\n        return self._data_dict['ilow']\n\n    @property\n    def upperlevelpop(self):\n        return self._data_dict['fup']\n\n    @property\n    def lowerlevelpop(self):\n        return self._data_dict['flow']\n\n    @property\n    def source_line_brightness_temperature(self):\n        return u.Quantity(self._data_dict['Tr'], u.K)\n\n    #@property\n    #def source_line_surfbrightness(self):\n    #    return u.Quantity(self._data_dict['flux'], self._u_brightness)\n\n    @property\n    def source_brightness(self):\n        return u.Quantity(self._data_dict['flux_dens'], self._u_brightness)\n\n    @property\n    def background_brightness(self):\n        return u.Quantity(self._data_dict['Jback'], self._u_brightness)\n    #    return self.tbg.to(self._u_brightness)\n\n    @property\n    def beta(self):\n        return self._data_dict['beta']\n\n    @property\n    def statistical_weight(self):\n        return self._data_dict['gup']\n\n\ndef cast_into_dic(col_names, arr):\n    '''col_names is column_info, and arr is data_transitions'''\n    names = col_names.split()\n    return {names[i]: arr[i,:] for i in range(len(names))}\n", "meta": {"hexsha": "1750fe7df3f28a518b52d7cda4a395dd57d9687b", "size": 15540, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyradex/fjdu/core.py", "max_stars_repo_name": "SpacialTree/pyradex", "max_stars_repo_head_hexsha": "722f9fdc45ff080cdcb151e37aa7075fab548f68", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2016-01-26T13:39:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-01T07:38:04.000Z", "max_issues_repo_path": "pyradex/fjdu/core.py", "max_issues_repo_name": "SpacialTree/pyradex", "max_issues_repo_head_hexsha": "722f9fdc45ff080cdcb151e37aa7075fab548f68", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2015-05-29T16:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T23:41:36.000Z", "max_forks_repo_path": "pyradex/fjdu/core.py", "max_forks_repo_name": "SpacialTree/pyradex", "max_forks_repo_head_hexsha": "722f9fdc45ff080cdcb151e37aa7075fab548f68", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2015-01-13T10:40:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T22:24:46.000Z", "avg_line_length": 36.1395348837, "max_line_length": 87, "alphanum_fraction": 0.5577220077, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 3595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.28776782186926264, "lm_q1q2_score": 0.18845762585356365}}
{"text": "import os, sys, glob, copy\nimport argparse\nfrom pathlib import Path\nfrom typing import Dict, List, Optional, Union, Tuple, TypeVar\nfrom importlib import import_module\n\nimport pandas as pd\nimport numpy as np\nimport numba as nb\nfrom skimage import transform\n\nfrom joblib import Parallel, delayed\nfrom multiprocessing import cpu_count\n\nimport astropy\nfrom astropy.constants import sigma_T, m_p, c\nfrom astropy.io import fits\nfrom astropy import units as un\nimport lenstools\nfrom lenstools import ConvergenceMap\n#import pymaster as nmt\n\nfrom astrild.rays.utils import Filters\nfrom astrild.rays.skys.sky_utils import SkyUtils, SkyNumbaUtils\nfrom astrild.rays.skyio import SkyIO\nfrom astrild.io import IO\n\ndir_src = Path(__file__).parent.parent.absolute()\ndefault_config_file_ray = dir_src / \"configs/ray_snapshot_info.h5\"\n\nsigma_T = sigma_T.to(un.Mpc**2).value #[Mpc^2]\nm_p = m_p.to(un.M_sun).value #[M_sun]\nc_light = c.to(\"km/s\").value\nT_cmb = 2.7251 #[K]\nGcm2 = 4.785E-20 # G/c^2 (Mpc/M_sun)\n\n# store available nr. of cpus for parallel computation\nncpus_available = cpu_count()\n\nclass SkyArrayWarning(BaseException):\n    pass\n\n\nclass SkyArray:\n    \"\"\"\n    The sky-map contains either:\n        - results of ray-tracing simulations run with RayRamses\n        - results of analytical dT and deflection angle results for NFW halos\n\n    This class analyzes the 2D map that contains the summes pertrurbations\n    of each ray. It can prepare the data for the search of voids and peaks.\n\n    Attributes:\n        skymap:\n        opening_angle: [deg]\n        quantity:\n        dirs:\n        map_file:\n\n    Methods:\n        from_file:\n        from_dataframe:\n        from_array:\n        from_halo_series:\n        from_halo_dataframe:\n        pdf:\n        wl_peak_counts:\n        add_galaxy_shape_noise:\n        create_galaxy_shape_noise:\n        create_cmb:\n        create_mask:\n        convolution:\n        zoom:\n        division:\n        merge:\n        convert_convergence_to_deflection:\n    \"\"\"\n\n    def __init__(\n        self,\n        skymap: np.ndarray,\n        opening_angle: float,\n        quantity: str,\n        dirs: Dict[str, str],\n        map_file: Optional[str] = None,\n    ):\n        self.data = {\"orig\": skymap}\n        self._npix = skymap.shape[0]\n        self._opening_angle = opening_angle\n        self.quantity = quantity\n        self.dirs = dirs\n        self.map_file = map_file\n\n    @classmethod\n    def from_file(\n        cls,\n        map_file: str,\n        opening_angle: float,\n        quantity: str,\n        dir_in: str,\n        npix: Optional[int] = None,\n        convert_unit: bool = True,\n    ) -> \"SkyArray\":\n        \"\"\"\n        Initialize class by reading the skymap data from pandas hdf5 file\n        or numpy array.\n        The file can be pointed at via map_filename or file_dsc.\n\n        Args:\n            map_filename:\n                File path with which skymap pd.DataFrame can be loaded.\n            opening_angle: [deg]\n        \"\"\"\n        assert map_file, \"There is no file being pointed at\"\n\n        file_extension = map_file.split(\".\")[-1]\n        if file_extension == \"h5\":\n            map_df = pd.read_hdf(map_file, key=\"df\")\n            return cls.from_dataframe(\n                map_df,\n                opening_angle,\n                quantity,\n                dir_in,\n                map_file,\n                npix,\n                convert_unit,\n            )\n        elif file_extension in [\"npy\", \"fits\"]:\n            if file_extension == \"npy\":\n                map_array = np.load(map_file)\n            elif file_extension == \"fits\":\n                map_array = ConvergenceMap.load(map_file, format=\"fits\").data\n            return cls.from_array(\n                map_array, opening_angle, quantity, dir_in, map_file\n            )\n\n\n    @classmethod\n    def from_dataframe(\n        cls,\n        map_df: pd.DataFrame,\n        opening_angle: float,\n        quantity: str,\n        dir_in: str,\n        map_file: str,\n        npix: Optional[int] = None,\n        convert_unit: bool = True,\n    ) -> \"SkyArray\":\n        \"\"\"\n        Initialize class by reading the skymap data from pandas DataFrame. \n\n        Args:\n            map_filename:\n                File path with which skymap pd.DataFrame can be loaded.\n            opening_angle: [deg]\n        \"\"\"\n        if convert_unit:\n            map_df = SkyUtils.convert_code_to_phy_units(quantity, map_df)\n        map_array = SkyIO.transform_RayRamsesOutput_to_NumpyNdarray(\n            map_df[quantity].values\n        )\n        return cls.from_array(\n            map_array, opening_angle, quantity, dir_in, map_file\n        )\n\n\n    @classmethod\n    def from_array(\n        cls,\n        map_array: np.array,\n        opening_angle: float,\n        quantity: str,\n        dir_in: str,\n        map_file: Optional[str] = None,\n    ) -> \"SkyArray\":\n        \"\"\"\n        Initialize class by reading the skymap data from np.ndarray.\n\n        Args:\n            map_filename:\n                File path with which skymap pd.DataFrame can be loaded.\n            opening_angle: [deg]\n        \"\"\"\n        assert map_array.shape[0] == map_array.shape[1]\n        dirs = {\"sim\": dir_in}\n        return cls(map_array, opening_angle, quantity, dirs, map_file)\n    \n\n    @classmethod\n    def from_halo_series(\n        cls,\n        halo: pd.Series,\n        npix: int = 100,\n        extent: float = 1,\n        direction: List[int] = [0, 1],\n        suppress: bool = False,\n        suppression_R: float = 1,\n        to: str = \"dT\",\n    ) -> \"SkyArray\":\n        \"\"\"\n        Calculate the deflection angle of Rees-Sciama / Birkinshaw-Gull / \n        moving cluster of galaxies effect of a halo with NFW profile using method\n        in described Sec. 3.2 in Baxter et al 2015 (1412.7521).\n\n        Note:\n            In this application it can be assumed that s_{SL}/s_{S}=1. Furthermore,\n            we can deglect vec{theta}/norm{theta} as it will be multiplied by the\n            same in the integral of Eq. 9 in Yasini et a. 2018 (1812.04241).\n        \n        Args:\n            theta_200c: radius, [deg]\n            M_200c: mass, [Msun]\n            c_200c: concentration, [-]\n            extent: The size of the map from which the trans-vel is calculated\n                in units of R200 of the associated halo.\n            suppress:\n            suppression_R:\n            angu_diam_dist: angular diameter distance, [Mpc]\n            direction: 0=(along x-axis), 1=(along y-axis), if 0 and 1 are given\n                the sum of both maps is returned.\n            to: Indicates whether 2nd order temperature perturbation of Ree-Sciama\n                effect or deflection angle map will be created, [dT, alpha]\n        \"\"\"\n        halo_dict = {\n            \"theta_200c\": halo.r200_deg,\n            \"M_200c\": halo.m200,\n            \"c_200c\": halo.c_NFW,\n            \"angu_diam_dist\": halo.Dc,\n        }\n\n        # set quantity label of SkyArray and method variable\n        if to == \"dT\":\n            quantity = \"rs\"\n            get_analytical_map = SkyUtils.NFW_temperature_perturbation_map\n            halo_dict[\"vel\"] = [halo.theta1_tv, halo.theta2_tv]\n        elif to == \"alpha\":\n            quantity = \"alpha\"\n            get_analytical_map = SkyUtils.NFW_deflection_angle_map\n        else:\n            SkyArrayWarning(\"The routine for this quantity is not implemented\")\n        \n        # place directional indicator in SkyArray quantity label\n        if 1 in direction and 0 in direction:\n            pass\n        elif 0 in direction:\n            quantity += \"_x\"\n        else:\n            quantity += \"_y\"\n        \n        map_array = get_analytical_map(\n            **halo_dict,\n            npix=npix,\n            extent=extent,\n            direction=direction,\n            suppress=suppress,\n            suppression_R=suppression_R,\n        )\n        opening_angle = 2 * halo.r200_deg * extent\n        return cls(map_array, opening_angle, quantity, dirs=None, map_file=None)\n    \n\n    @classmethod\n    def from_halo_dataframe(\n        cls,\n        halo_cat: Union[pd.DataFrame, pd.Series],\n        npix: int = 8192,\n        extent: float = 1,\n        direction: List[int] = [0, 1],\n        suppress: bool = False,\n        suppression_R: float = 1,\n        opening_angle: float = 20.,\n        ncpus: int = 1,\n        to: str = \"dT\",\n    ) -> \"SkyArray\":\n        \"\"\"\n        Identical to SkyArray.from_halo_series() but for a pd.DataFrame.\n        \"\"\"\n        halo_dict = halo_cat[[\n            \"r200_deg\",\n            \"r200_pix\",\n            \"m200\",\n            \"c_NFW\",\n            \"Dc\",\n            \"theta1_pix\",\n            \"theta2_pix\",\n        ]].to_dict(orient='list')\n        halo_idx = np.arange(len(halo_dict[\"m200\"]))\n        \n        # set quantity label of SkyArray and method variable\n        if to == \"dT\":\n            quantity = \"rs\"\n            halo_dict[\"theta1_tv\"] = halo_cat[\"theta1_tv\"].values\n            halo_dict[\"theta2_tv\"] = halo_cat[\"theta2_tv\"].values\n        elif to == \"alpha\":\n            quantity = \"alpha\"\n        else:\n            SkyArrayWarning(\"The routine for this quantity is not implemented\")\n        \n        # place directional indicator in SkyArray quantity label\n        if 1 in direction and 0 in direction:\n            pass\n        elif 0 in direction:\n            quantity += \"_x\"\n        else:\n            quantity += \"_y\"\n        \n        if ncpus == 1:\n            map_array = SkyUtils.analytic_Halo_signal_to_SkyArray(\n                halo_idx,\n                halo_dict,\n                extent,\n                direction,\n                suppress,\n                suppression_R,\n                npix,\n                to,\n            )\n        else:\n            halo_idx_batches = np.array_split(halo_idx, ncpus)\n            map_sub_arrays = Parallel(n_jobs=ncpus)(\n                delayed(SkyUtils.analytic_Halo_signal_to_SkyArray)(\n                    halo_idx_batch,\n                    halo_dict,\n                    extent,\n                    direction,\n                    suppress,\n                    suppression_R,\n                    npix,\n                    to,\n                ) for halo_idx_batch in halo_idx_batches\n            )\n            map_array = sum(map_sub_arrays)\n        map_array = np.nan_to_num(\n            map_array, copy=False, nan=0.0, posinf=0.0, neginf=0.0,\n        )\n\n        return cls(map_array, opening_angle, quantity, dirs=None, map_file=None)\n    \n\n    @classmethod\n    def from_halo_catalogue_to_temperature_perturbation_map(\n        cls,\n        halo_cat: pd.DataFrame,\n        extent: float = 1,\n        direction: List[int] = [0, 1],\n        suppress: bool = False,\n        suppression_R: float = 1,\n        npix: int = 8192,\n        opening_angle: float = 20.,\n        ncpus: int = 1,\n    ) -> \"SkyArray\":\n        \"\"\"\n        The Rees-Sciama / Birkinshaw-Gull / moving cluster of galaxies effect.\n\n        Args:\n            vel: transverse to the line-of-sight velocity, [km/sec]\n\n        Returns:\n            Temperature perturbation map, \\Delta T / T_CMB\n        \"\"\"\n        halo_dict = halo_cat[[\n            \"r200_deg\",\n            \"r200_pix\",\n            \"m200\",\n            \"c_NFW\",\n            \"Dc\",\n            \"theta1_pix\",\n            \"theta2_pix\",\n            \"theta1_tv\",\n            \"theta2_tv\",\n        ]].to_dict(orient='list')\n        halo_idx = range(len(halo_dict[\"m200\"]))\n        \n        if ncpus == 1:\n            map_array = SkyUtils.analytic_Halo_signal_to_SkyArray(\n                halo_idx, halo_dict, extent, direction, suppress, suppression_R, npix\n            )\n        else:\n            halo_idx_batches = np.array_split(halo_idx, ncpus)\n            map_sub_arrays = Parallel(n_jobs=ncpus)(\n                delayed(SkyUtils.analytic_Halo_signal_to_SkyArray)(\n                    halo_idx_batch,\n                    halo_dict,\n                    extent,\n                    direction,\n                    suppress,\n                    suppression_R,\n                    npix,\n                ) for halo_idx_batch in halo_idx_batches\n            )\n            map_array = sum(map_sub_arrays)\n        map_array[np.isinf(map_array)] = 0.\n\n        if 1 in direction and 0 in direction:\n            quantity = \"isw_rs\"\n        elif 0 in direction:\n            quantity = \"isw_rs_x\"\n        else:\n            quantity = \"isw_rs_y\"\n        return cls(map_array, opening_angle, quantity, dirs=None, map_file=None)\n  \n    \n    @property\n    def ncpus(self):\n        return self._ncpus\n\n\n    @ncpus.setter\n    def ncpus(self, val: int):\n        if (ncpus == 0) or (ncpus < -1):\n            raise ValueError(\n                f\"ncpus={ncpus} is not valid. Please enter a value \" +\\\n                \">0 for ncpus or -1 to use all available cores.\"\n            )\n        elif ncpus == -1: self._ncpus = ncpus_available\n        else: self._ncpus = val\n\n\n    @property\n    def npix(self) -> int:\n        return self._npix\n\n    @property\n    def opening_angle(self) -> float:\n        return self._opening_angle\n\n\n    def pdf(self, nbins: int, of: str = \"orig\") -> dict:\n        _pdf = {}\n        _pdf[\"values\"], _pdf[\"bins\"] = np.histogram(\n            self.data[of], bins=nbins, density=True\n        )\n        return _pdf\n\n    def wl_peak_counts(\n        self,\n        nbins: int,\n        field_conversion: str,\n        of: str = \"orig\",\n        limits: Optional[tuple] = None,\n    ) -> pd.DataFrame:\n        \"\"\"\n        Signal peak counts. This is used commonly used in weak-lensing,\n        but it doesn't need to stop there...\n        \"\"\"\n        if field_conversion == \"normalize\":\n            _map = self.data[of] - np.mean(self.skymap.data[of])\n        else:\n            _map = self.data[of]\n\n        if limits is None:\n            lower_bound = np.percentile(\n                self.data[of], 5\n            )  # np.min(self.data[of])\n            upper_bound = np.percentile(\n                self.data[of], 95\n            )  # np.max(self.data[of])\n        else:\n            lower_bound = min(limits)\n            upper_bound = max(limits)\n\n        map_bins = np.arange(\n            lower_bound, upper_bound, (upper_bound - lower_bound) / nbins\n        )\n        _map = ConvergenceMap(data=_map, angle=self._opening_angle * un.deg)\n        _kappa, _pos = _map.locatePeaks(map_bins)\n\n        _hist, _kappa = np.histogram(_kappa, bins=nbins, density=False)\n        _kappa = (_kappa[1:] + _kappa[:-1]) / 2\n        peak_counts_dic = {\"kappa\": _kappa, \"counts\": _hist}\n        peak_counts_df = pd.DataFrame(data=peak_counts_dic)\n        return peak_counts_df\n\n\n    def resize(\n        self,\n        npix,\n        of: Optional[str] = None,\n        img: Optional[np.ndarray] = None,\n        rtn: bool = False,\n        orig_data: str = None,\n    ) -> Union[np.ndarray, None]:\n        \"\"\"\n        Lower the nr. of pixels of image. Useful for tests.\n        \n        Args:\n            npix: the new pixel nr. per edge of the image\n            of: skymap image identifier.\n            orig_data: What to do with data of the image to be processed:\n                e.g. no, shallow, or deep copy\n        \"\"\"\n        img = self._manage_img_data(img, orig_data)\n        img = transform.resize(img, (npix, npix), anti_aliasing=True)\n        if rtn: return img\n        else: self.data[of] = img\n\n    \n    def crop(\n        self,\n        xlimit: Union[Tuple, List, np.array],\n        ylimit: Union[Tuple, List, np.array],\n        of: Optional[str] = None,\n        img: Optional[np.ndarray] = None,\n        rtn: bool = False,\n        orig_data: str = None,\n    ) -> Union[np.ndarray, None]:\n        \"\"\"\n        Zoom into sky_array map.\n\n        Args:\n            x,ylimit: Boundaries of zoom. If given in ints units are pixels,\n                if floats percentages are used.\n            of: skymap image identifier.\n            orig_data: What to do with data of the image to be processed:\n                e.g. no, shallow, or deep copy\n        \"\"\"\n        if of:\n            assert of in list(self.data.keys()), \"Map does not exist.\"\n            img = self.data[of]\n        \n        img = self._manage_img_data(img, orig_data)\n        xlimit = np.asarray(xlimit)\n        ylimit = np.asarray(ylimit)\n        assert np.diff(xlimit) == np.diff(ylimit), SkyArrayWarning(\"The whole class is currently designed for square images.\")\n        if isinstance(xlimit[0], float):\n            _npix = img.shape[0]\n            xlimit = (_npix * xlimit / 100).astype(int)\n            ylimit = (_npix * ylimit / 100).astype(int)\n        zoom = img[xlimit[0] : xlimit[1], ylimit[0] : ylimit[1]]\n        if rtn:\n            return zoom\n        else:\n            print(f\"Image crop to x={xlimit} and y={ylimit}.\")\n            self.data[of] = zoom\n            self._opening_angle = (\n                self._opening_angle * abs(np.diff(xlimit)) / self._npix\n            )\n            self._npix = zoom.shape[0]\n\n\n    def division(\n        self,\n        ntiles: int,\n        of: Optional[str] = None,\n        img: Optional[np.ndarray] = None,\n        rtn: bool = False,\n        orig_data: str = None,\n    ) -> Union[List[np.ndarray], None]:\n        \"\"\"\n        Divide image into tiles.\n        Should use sklearn.feature_extraction.image.extract_patches_2d\n\n        Args:\n            ntiles: Nr. of tiles per edge (as to be in 2^n).\n            orig_data: What to do with data of the image to be processed:\n                e.g. no, shallow, or deep copy\n        \"\"\"\n        img = self._manage_img_data(img, orig_data)\n        npix = img.shape[0]\n        edges = list(np.arange(0, npix, npix / ntiles)) + [npix]\n        edges = np.array(\n            [edges[idx : idx + 2] for idx in range(len(edges) - 1)]\n        ).astype(int)\n        tiles = []\n        for xlim in edges:\n            for ylim in edges:\n                tiles.append(self.crop(xlim, ylim, img=img, rtn=True))\n        print(\n            f\"The image is divided into {len(tiles)} tiles, \" +\\\n            f\"each with {tiles[0].shape[0]}^2 pixels.\"\n        )\n        tiles = np.asarray(tiles)\n        if rtn:\n            return tiles\n        else:\n            self.tiles = tiles\n            self._tile_npix = tiles[0].shape[0]\n            self._tile_opening_angle = self._opening_angle * self._tile_npix / self._npix\n\n\n    def merge(\n        self, tiles: np.ndarray, rtn: bool = False\n    ) -> Union[np.ndarray, None]:\n        \"\"\"\n        Merge tiles created with self.division.\n\n        Args:\n            tiles: 3D\n        \"\"\"\n        ntiles = len(tiles)\n        nrows = int(np.sqrt(ntiles))\n        _parts = np.arange(0, ntiles + nrows, nrows)\n        row_tile_idx = [(_parts[ii], _parts[ii + 1]) for ii in range(nrows)]\n        row_tiles = []\n        for idx in range(nrows):\n            start = row_tile_idx[idx][0]\n            end = row_tile_idx[idx][1]\n            row_tiles.append(np.hstack((tiles[start:end])))\n        row_tiles = np.asarray(row_tiles)\n        img = np.vstack((row_tiles))\n        if rtn: return img\n\n    \n    def substract_mean(\n        self,\n        of: Optional[str] = None,\n        img: Optional[np.ndarray] = None,\n        rtn: bool = False,\n        orig_data: str = None,\n    ) -> Union[np.ndarray, None]:\n        \"\"\"\n        Centre values of map on it's mean value.\n        \"\"\"\n        if of:\n            assert of in list(self.data.keys()), \"Map does not exist.\"\n            img = self.data[of]\n        img = self._manage_img_data(img, orig_data)\n        img -= np.mean(img)\n        if rtn: return img\n        else: self.data[of] = img\n\n\n    def filter(\n        self,\n        filter_dsc: dict,\n        on: Optional[str] = None,\n        img: Optional[np.ndarray] = None,\n        rtn: bool = False,\n        orig_data: str = None,\n    ) -> Union[np.ndarray, None]:\n        \"\"\"\n        Apply kernel (filter_dsc) over skymap image (on).\n        \n        Args:\n            filter_dsc: Kernel description.\n                Note that theta_i should be given in astropy.units!\n            on: skymap image identifier.\n            orig_data: What to do with data of the image to be processed:\n                e.g. no, shallow, or deep copy\n        \"\"\"\n        if on:\n            assert on in list(self.data.keys()), \"Map does not exist.\"\n            img = self.data[on]\n            map_name = [on]\n        else:\n            map_name = [\"\"]\n        \n        # load rays/utils/filters.py package for dynamic function call\n        module = import_module(\"astrild.rays.utils\")\n        img = self._manage_img_data(img, orig_data)\n\n        for filter_name, args in filter_dsc.items():\n            if rtn is False:\n                abbrev = args[\"abbrev\"]\n                del args[\"abbrev\"]\n                map_name.append(abbrev)\n\n            clas = getattr(module, \"Filters\")\n            fct = getattr(clas, filter_name)\n            img = fct(img, self._opening_angle * un.deg, **args)\n        if rtn: return img\n        else: self.data[(\"_\").join(map_name)] = img\n\n\n    def create_galaxy_shape_noise(\n        self, std: float, ngal: float, rnd_seed: Optional[int] = None\n    ) -> None:\n        \"\"\"\n        Galaxy Shape Noise (GSN), e.g.: arxiv:1907.06657\n\n        Args:\n            std: dispersion of source galaxy intrinsic ellipticity, 0.4 for LSST\n            ngal: Nr. density of galaxies, 40 for LSST; [arcmin^2]\n            rnd_seed: Fix random seed, for reproducability.\n        Returns:\n            gsn_map:\n                self.npix x self.npix np.array containing the GSN\n        \"\"\"\n        theta_pix = 60 * self._opening_angle / self._npix\n        std_pix = 0.007  # np.sqrt(std ** 2 / (2*theta_pix*ngal))\n        if rnd_seed is None:\n            self.data[\"gsn\"] = np.random.normal(\n                loc=0, scale=std_pix, size=[self._npix, self._npix]\n            )\n        else:\n            rg = np.random.Generator(np.random.PCG64(rnd_seed))\n            self.data[\"gsn\"] = rg.normal(\n                loc=0, scale=std_pix, size=[self._npix, self._npix]\n            )\n        print(f\"The GSN map sigma is {np.std(self.data['gsn'])}\", std_pix)\n\n\n    def add_galaxy_shape_noise(self, on: str = \"orig\") -> np.ndarray:\n        \"\"\"\n        Add GSN on top of skymap.\n        \n        Args:\n            std: dispersion of source galaxy intrinsic ellipticity, 0.4 for LSST\n            ngal: Nr. density of galaxies, 40 for LSST; [arcmin^2]\n            rnd_seed: Fix random seed, for reproducability.\n        \"\"\"\n        if \"kappa\" in self.quantity:\n            self.data[\"orig_gsn\"] = self.data[\"orig\"] + self.data[\"gsn\"]\n            return self.data[\"orig_gsn\"]\n        else:\n            raise SkyArrayWarning(f\"GSN should not be added to {self.quantity}\")\n\n\n    def create_cmb(\n        self,\n        filepath_cl: str,\n        lmax: int = 3e3,\n        rnd_seed: Optional[int] = None,\n        rtn: bool = False,\n    ) -> np.ndarray:\n        \"\"\"\n        Cosmig Microwave Background (CMB) on partial-sky map,\n        for which the flat-sky approximation holds (ell > 10).\n\n        Args:\n            filepath_cl: angular power spectrum of CMB\n            theta: Edge length of the square field-of-view [deg]\n            nside: Nr. of pixels per edge of the output full-sky map\n            rnd_seed: Fix random seed, for reproducability.\n\n        Returns:\n            cmb_map:\n        \"\"\"\n        if rnd_seed:\n            np.random.seed(rnd_seed)\n        Nx = Ny = self._npix\n        Lx = Ly = self._opening_angle * np.pi / 180.0\n\n        cl_tt_cmb = np.load(filepath_cl)[1]\n        #cmb = nmt.synfast_flat(\n        #    Nx, Ny, Lx, Ly, cls=np.array([cl_tt_cmb]), spin_arr=np.array([0])\n        #)[0]\n        if rtn: return cmb\n        else: self.data[\"cmb\"] = cmb\n\n\n    def add_cmb(\n        self,\n        filepath_cl: Optional[str] = None,\n        filepath_cmb: Optional[str] = None,\n        on: str = \"orig\",\n        lmax: Optional[float] = None,\n        rnd_seed: Optional[int] = None,\n        rtn: bool = False,\n        overwrite: bool = True,\n    ) -> np.ndarray:\n        \"\"\"\n        Args:\n            filepath_cl:\n            on:\n            lmax:\n            rnd_seed:\n            rtn:\n            overwrite:\n        \n        Returns:\n        \"\"\"\n        if \"isw\" in self.quantity:\n            if \"cmb\" not in self.data.keys():\n                try: self.create_cmb(filepath_cl, lmax, rnd_seed)\n                except: \n                    self.data[\"cmb\"] = np.load(filepath_cmb)\n            _map = self.data[on] + self.data[\"cmb\"]\n            if rtn:\n                return _map\n            else:\n                if overwrite:\n                    self.data[on] = _map\n                else:\n                    self.data[f\"{on}_cmb\"] = _map\n        else:\n            raise SkyArrayWarning(f\"CMB should not be added to {self.quantity}\")\n\n\n    def convert_convergence_to_deflection(\n        self,\n        on: Optional[str] = None,\n        img: Optional[np.ndarray] = None,\n        npix: Optional[int] = None,\n        opening_angle: Optional[float] = None,\n        rtn: bool = True,\n        orig_data: str = None,\n    ) -> Tuple[np.ndarray, np.ndarray]:\n        \"\"\"\n        Args:\n            on: String to indicate which map in self.data should be used.\n            img: 2D convergence map.\n            rtn: Bool to indicate whether to attach result to class object or return.\n            orig_data: What to do with data of the image to be processed:\n                e.g. no, shallow, or deep copy\n\n        Returns:\n            alpha_1,2: 2D deflection angle map [rad]\n        \"\"\"\n        #TODO handle tiles/multiple images\n        assert self.quantity in [\n            \"kappa_1\",\n            \"kappa_2\",\n        ], \"Deflection angle can only be calculated from the kappa map\"\n        img = self._manage_img_data(img, orig_data)\n\n        if npix is None: npix = self._npix\n        if opening_angle is None: opening_angle = self._opening_angle\n\n        alpha_1, alpha_2 = SkyUtils.convert_convergence_to_deflection_ctypes(\n            img, npix, opening_angle * un.deg\n        )\n        if rtn:\n            return alpha_2, alpha_1\n        else:\n            self.data[\"defltx\"] = alpha_2\n            self.data[\"deflty\"] = alpha_1\n\n\n    def convert_deflection_to_shear(\n        self,\n        on: Optional[str] = None,\n        img: Optional[np.ndarray] = None,\n        rtn: bool = False,\n        orig_data: str = None,\n    ) -> Tuple[np.ndarray, np.ndarray]:\n        \"\"\"\n        Args:\n            on: String to indicate which map in self.data should be used.\n            img: 2D convergence map.\n            rtn: Bool to indicate whether to attach result to class object or return.\n            orig_data: What to do with data of the image to be processed:\n                e.g. no, shallow, or deep copy\n\n        Returns:\n            gamma_1,2: 2D shear map [-]\n        \"\"\"\n        assert self.quantity in [\n            \"alpha\"\n        ], \"Shear can only be calculated from the deflection angle map\"\n        img = self._manage_img_data(img, orig_data)\n        gamma_1, gamma_2 = SkyUtils.convert_deflection_to_shear(\n            img, self._npix, self._opening_angle * un.deg\n        )\n        if rtn:\n            return gamma_2, gamma_1\n        else:\n            self.data[\"gammax\"] = gamma_2\n            self.data[\"gammay\"] = gamma_1\n    \n\n    @staticmethod\n    def _manage_img_data(\n        img: np.ndarray,\n        orig_data: str = None,\n    ) -> np.ndarray:\n        \"\"\"\n        Handle the memory location of the image to be processed.\n\n        Args:\n            img: memory pointer of the image data.\n            orig_data: action key word.\n\n        Returns:\n            cimg: pointer to (new) memory location.\n        \"\"\"\n        if orig_data == \"shallow\": cimg = copy.copy(img)\n        elif orig_data == \"deep\": cimg = copy.deepcopy(img)\n        else: cimg = img\n        return cimg\n", "meta": {"hexsha": "448fdae0d60984e5e695ec60ec796c6de50ed838", "size": 27702, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/astrild/rays/skys/sky_array.py", "max_stars_repo_name": "Christovis/wys-ars", "max_stars_repo_head_hexsha": "bb15f2d392842f9b32de12b5db5c86079bc97105", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-27T14:45:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T21:09:46.000Z", "max_issues_repo_path": "src/astrild/rays/skys/sky_array.py", "max_issues_repo_name": "Christovis/wys-ars", "max_issues_repo_head_hexsha": "bb15f2d392842f9b32de12b5db5c86079bc97105", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-03T10:47:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-03T10:47:45.000Z", "max_forks_repo_path": "src/astrild/rays/skys/sky_array.py", "max_forks_repo_name": "Christovis/wys-ars", "max_forks_repo_head_hexsha": "bb15f2d392842f9b32de12b5db5c86079bc97105", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-03T10:17:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T10:17:34.000Z", "avg_line_length": 31.8048220436, "max_line_length": 126, "alphanum_fraction": 0.543318172, "include": true, "reason": "import numpy,import numba,import astropy,from astropy", "num_tokens": 6693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.18845762560619567}}
{"text": "from __future__ import absolute_import, division, print_function\n\nfrom ..compatibility import Sequence\nimport inspect\n\nimport numpy as np\n\ntry:\n    import scipy\n    import scipy.fftpack\nexcept ImportError:\n    scipy = None\n\nfrom .core import concatenate as _concatenate\nfrom .creation import arange as _arange\nfrom ..utils import derived_from\n\n\nchunk_error = (\"Dask array only supports taking an FFT along an axis that \\n\"\n               \"has a single chunk. An FFT operation was tried on axis %s \\n\"\n               \"which has chunks %s. To change the array's chunks use \"\n               \"dask.Array.rechunk.\")\n\nfft_preamble = \"\"\"\n    Wrapping of %s\n\n    The axis along which the FFT is applied must have a one chunk. To change\n    the array's chunking use dask.Array.rechunk.\n\n    The %s docstring follows below:\n\n    \"\"\"\n\n\ndef _fft_out_chunks(a, s, axes):\n    \"\"\" For computing the output chunks of [i]fft*\"\"\"\n    if s is None:\n        return a.chunks\n    chunks = list(a.chunks)\n    for i, axis in enumerate(axes):\n        chunks[axis] = (s[i],)\n    return chunks\n\n\ndef _rfft_out_chunks(a, s, axes):\n    \"\"\" For computing the output chunks of rfft*\"\"\"\n    if s is None:\n        s = [a.chunks[axis][0] for axis in axes]\n    s = list(s)\n    s[-1] = s[-1] // 2 + 1\n    chunks = list(a.chunks)\n    for i, axis in enumerate(axes):\n        chunks[axis] = (s[i],)\n    return chunks\n\n\ndef _irfft_out_chunks(a, s, axes):\n    \"\"\" For computing the output chunks of irfft*\"\"\"\n    if s is None:\n        s = [a.chunks[axis][0] for axis in axes]\n        s[-1] = 2 * (s[-1] - 1)\n    chunks = list(a.chunks)\n    for i, axis in enumerate(axes):\n        chunks[axis] = (s[i],)\n    return chunks\n\n\ndef _hfft_out_chunks(a, s, axes):\n    assert len(axes) == 1\n\n    axis = axes[0]\n\n    if s is None:\n        s = [2 * (a.chunks[axis][0] - 1)]\n\n    n = s[0]\n\n    chunks = list(a.chunks)\n    chunks[axis] = (n,)\n    return chunks\n\n\ndef _ihfft_out_chunks(a, s, axes):\n    assert len(axes) == 1\n\n    axis = axes[0]\n\n    if s is None:\n        s = [a.chunks[axis][0]]\n    else:\n        assert len(s) == 1\n\n    n = s[0]\n\n    chunks = list(a.chunks)\n    if n % 2 == 0:\n        m = (n // 2) + 1\n    else:\n        m = (n + 1) // 2\n    chunks[axis] = (m,)\n    return chunks\n\n\n_out_chunk_fns = {'fft': _fft_out_chunks,\n                  'ifft': _fft_out_chunks,\n                  'rfft': _rfft_out_chunks,\n                  'irfft': _irfft_out_chunks,\n                  'hfft': _hfft_out_chunks,\n                  'ihfft': _ihfft_out_chunks}\n\n\ndef fft_wrap(fft_func, kind=None, dtype=None):\n    \"\"\" Wrap 1D, 2D, and ND real and complex FFT functions\n\n    Takes a function that behaves like ``numpy.fft`` functions and\n    a specified kind to match it to that are named after the functions\n    in the ``numpy.fft`` API.\n\n    Supported kinds include:\n\n        * fft\n        * fft2\n        * fftn\n        * ifft\n        * ifft2\n        * ifftn\n        * rfft\n        * rfft2\n        * rfftn\n        * irfft\n        * irfft2\n        * irfftn\n        * hfft\n        * ihfft\n\n    Examples\n    --------\n    >>> parallel_fft = fft_wrap(np.fft.fft)\n    >>> parallel_ifft = fft_wrap(np.fft.ifft)\n    \"\"\"\n    if scipy is not None:\n        if fft_func is scipy.fftpack.rfft:\n            raise ValueError(\"SciPy's `rfft` doesn't match the NumPy API.\")\n        elif fft_func is scipy.fftpack.irfft:\n            raise ValueError(\"SciPy's `irfft` doesn't match the NumPy API.\")\n\n    if kind is None:\n        kind = fft_func.__name__\n    try:\n        out_chunk_fn = _out_chunk_fns[kind.rstrip(\"2n\")]\n    except KeyError:\n        raise ValueError(\"Given unknown `kind` %s.\" % kind)\n\n    def func(a, s=None, axes=None):\n        if axes is None:\n            if kind.endswith('2'):\n                axes = (-2, -1)\n            elif kind.endswith('n'):\n                if s is None:\n                    axes = tuple(range(a.ndim))\n                else:\n                    axes = tuple(range(len(s)))\n            else:\n                axes = (-1,)\n        else:\n            if len(set(axes)) < len(axes):\n                raise ValueError(\"Duplicate axes not allowed.\")\n\n        _dtype = dtype\n        if _dtype is None:\n            sample = np.ones(a.ndim * (8,), dtype=a.dtype)\n            try:\n                _dtype = fft_func(sample, axes=axes).dtype\n            except TypeError:\n                _dtype = fft_func(sample).dtype\n\n        for each_axis in axes:\n            if len(a.chunks[each_axis]) != 1:\n                raise ValueError(chunk_error % (each_axis, a.chunks[each_axis]))\n\n        chunks = out_chunk_fn(a, s, axes)\n\n        args = (s, axes)\n        if kind.endswith('fft'):\n            axis = None if axes is None else axes[0]\n            n = None if s is None else s[0]\n            args = (n, axis)\n\n        return a.map_blocks(fft_func, *args, dtype=_dtype,\n                            chunks=chunks)\n\n    if kind.endswith('fft'):\n        _func = func\n\n        def func(a, n=None, axis=None):\n            s = None\n            if n is not None:\n                s = (n,)\n\n            axes = None\n            if axis is not None:\n                axes = (axis,)\n\n            return _func(a, s, axes)\n\n    func_mod = inspect.getmodule(fft_func)\n    func_name = fft_func.__name__\n    func_fullname = func_mod.__name__ + \".\" + func_name\n    if fft_func.__doc__ is not None:\n        func.__doc__ = (fft_preamble % (2 * (func_fullname,)))\n        func.__doc__ += fft_func.__doc__\n    func.__name__ = func_name\n    return func\n\n\nfft = fft_wrap(np.fft.fft)\nfft2 = fft_wrap(np.fft.fft2)\nfftn = fft_wrap(np.fft.fftn)\nifft = fft_wrap(np.fft.ifft)\nifft2 = fft_wrap(np.fft.ifft2)\nifftn = fft_wrap(np.fft.ifftn)\nrfft = fft_wrap(np.fft.rfft)\nrfft2 = fft_wrap(np.fft.rfft2)\nrfftn = fft_wrap(np.fft.rfftn)\nirfft = fft_wrap(np.fft.irfft)\nirfft2 = fft_wrap(np.fft.irfft2)\nirfftn = fft_wrap(np.fft.irfftn)\nhfft = fft_wrap(np.fft.hfft)\nihfft = fft_wrap(np.fft.ihfft)\n\n\ndef _fftfreq_block(i, n, d):\n    r = i.copy()\n    r[i >= (n + 1) // 2] -= n\n    r /= n * d\n    return r\n\n\n@derived_from(np.fft)\ndef fftfreq(n, d=1.0, chunks='auto'):\n    n = int(n)\n    d = float(d)\n\n    r = _arange(n, dtype=float, chunks=chunks)\n\n    return r.map_blocks(_fftfreq_block, dtype=float, n=n, d=d)\n\n\n@derived_from(np.fft)\ndef rfftfreq(n, d=1.0, chunks='auto'):\n    n = int(n)\n    d = float(d)\n\n    r = _arange(n // 2 + 1, dtype=float, chunks=chunks)\n    r /= n * d\n\n    return r\n\n\ndef _fftshift_helper(x, axes=None, inverse=False):\n    if axes is None:\n        axes = list(range(x.ndim))\n    elif not isinstance(axes, Sequence):\n        axes = (axes,)\n\n    y = x\n    for i in axes:\n        n = y.shape[i]\n        n_2 = (n + int(inverse is False)) // 2\n\n        l = y.ndim * [slice(None)]\n        l[i] = slice(None, n_2)\n        l = tuple(l)\n\n        r = y.ndim * [slice(None)]\n        r[i] = slice(n_2, None)\n        r = tuple(r)\n\n        y = _concatenate([y[r], y[l]], axis=i)\n\n        if len(x.chunks[i]) == 1:\n            y = y.rechunk({i: x.chunks[i]})\n\n    return y\n\n\n@derived_from(np.fft)\ndef fftshift(x, axes=None):\n    return _fftshift_helper(x, axes=axes, inverse=False)\n\n\n@derived_from(np.fft)\ndef ifftshift(x, axes=None):\n    return _fftshift_helper(x, axes=axes, inverse=True)\n", "meta": {"hexsha": "53c80fb73b071d1bc3c7c9f4cc591bb5e3fbcb10", "size": 7213, "ext": "py", "lang": "Python", "max_stars_repo_path": "dask/array/fft.py", "max_stars_repo_name": "mikiec84/dask", "max_stars_repo_head_hexsha": "c4ee834c1f7a71c3c85e80d1aea04a071db51ba4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-02T01:24:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-02T01:24:25.000Z", "max_issues_repo_path": "dask/array/fft.py", "max_issues_repo_name": "mikiec84/dask", "max_issues_repo_head_hexsha": "c4ee834c1f7a71c3c85e80d1aea04a071db51ba4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dask/array/fft.py", "max_forks_repo_name": "mikiec84/dask", "max_forks_repo_head_hexsha": "c4ee834c1f7a71c3c85e80d1aea04a071db51ba4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-05T23:36:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-05T23:36:44.000Z", "avg_line_length": 24.4508474576, "max_line_length": 80, "alphanum_fraction": 0.5559406627, "include": true, "reason": "import numpy,import scipy", "num_tokens": 2047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3738758297482025, "lm_q1q2_score": 0.1883983376217992}}
{"text": "from typing import Optional, List, Union\n\nimport numpy as np\nfrom GPy.kern import Kern\nfrom GPy.kern.src.kern import CombinationKernel\nfrom graphviz import Source\nfrom scipy.spatial.distance import cdist, pdist\nfrom sympy import pprint, latex, mathml, dotprint\n\nfrom src.autoks.backend.kernel import RawKernelType, kernel_to_infix_tokens, tokens_to_str, sort_kernel, additive_form, \\\n    is_base_kernel, subkernel_expression, kernels_to_kernel_vecs, is_prod_kernel, is_sum_kernel, compute_kernel, \\\n    KERNEL_DICT, set_priors\nfrom src.autoks.core.hyperprior import HyperpriorMap\nfrom src.autoks.core.kernel_encoding import kernel_to_tree, KernelTree\nfrom src.autoks.symbolic.kernel_symbol import KernelSymbol\nfrom src.autoks.symbolic.util import postfix_tokens_to_symbol\nfrom src.autoks.util import remove_duplicates\nfrom src.evalg.encoding import infix_tokens_to_postfix_tokens\nfrom src.evalg.serialization import Serializable\n\n\nclass Covariance(Serializable):\n    \"\"\"A wrapper for a GPy Kern\"\"\"\n\n    def __init__(self, kernel: RawKernelType):\n        self.raw_kernel = kernel\n\n    @property\n    def raw_kernel(self) -> RawKernelType:\n        return self._raw_kernel\n\n    @raw_kernel.setter\n    def raw_kernel(self, new_kernel: RawKernelType) -> None:\n        if not isinstance(new_kernel, RawKernelType):\n            raise TypeError(f'kernel must be {RawKernelType.__name__}. Found type {new_kernel.__class__.__name__}.')\n        self._raw_kernel = new_kernel\n        # Set other raw_kernel parameters\n        self.infix_tokens = kernel_to_infix_tokens(self.raw_kernel)\n        self.postfix_tokens = infix_tokens_to_postfix_tokens(self.infix_tokens)\n        self.infix = tokens_to_str(self.infix_tokens, show_params=False)\n        self.infix_full = tokens_to_str(self.infix_tokens, show_params=True)\n        self.postfix = tokens_to_str(self.postfix_tokens, show_params=False)\n        postfix_token_symbols = tokens_to_kernel_symbols(self.postfix_tokens)\n        self.symbolic_expr = postfix_tokens_to_symbol(postfix_token_symbols)\n        self.symbolic_expr_expanded = self.symbolic_expr.expand()\n\n    def to_dict(self) -> dict:\n        input_dict = super().to_dict()\n        input_dict[\"kernel\"] = self.raw_kernel.to_dict()\n        return input_dict\n\n    @classmethod\n    def _format_input_dict(cls, input_dict: dict) -> dict:\n        input_dict = super()._format_input_dict(input_dict)\n        input_dict[\"kernel\"] = Kern.from_dict(input_dict[\"kernel\"])\n        return input_dict\n\n    def to_binary_tree(self) -> KernelTree:\n        \"\"\"Get the binary tree representation of the kernel\n\n        :return:\n        \"\"\"\n        return kernel_to_tree(self.raw_kernel)\n\n    def canonical(self) -> RawKernelType:\n        \"\"\"Get canonical form of backend kernel.\n\n        :return:\n        \"\"\"\n        return sort_kernel(self.raw_kernel)\n\n    def to_additive_form(self) -> RawKernelType:\n        \"\"\"Convert the kernel to additive form.\n\n        :return:\n        \"\"\"\n        return additive_form(self.raw_kernel)\n\n    def pretty_print(self) -> None:\n        \"\"\"Pretty print the kernel.\n\n        :return:\n        \"\"\"\n        pprint(self.symbolic_expr)\n\n    def print_full(self) -> None:\n        \"\"\"Print the verbose version of the kernel.\n\n        :return:\n        \"\"\"\n        print(self.infix_full)\n\n    def is_base(self) -> bool:\n        \"\"\"Determine whether backend kernel is a 1-d base kernel.\"\"\"\n        return is_base_kernel(self.raw_kernel)\n\n    def is_sum(self) -> bool:\n        \"\"\"Determine whether backend kernel is a sum kernel.\"\"\"\n        return is_sum_kernel(self.raw_kernel)\n\n    def is_prod(self) -> bool:\n        \"\"\"Determine whether backend kernel is a product kernel.\"\"\"\n        return is_prod_kernel(self.raw_kernel)\n\n    def priors(self) -> Optional:\n        \"\"\"Get the priors of the kernel.\"\"\"\n        raise NotImplementedError('This will be implemented soon')\n\n    def set_hyperpriors(self, hyperpriors: HyperpriorMap) -> None:\n        inv_KERNEL_DICT = {v: k for k, v in KERNEL_DICT.items()}\n\n        def set_kern_prior(x):\n            if not isinstance(x, CombinationKernel) and isinstance(x, Kern):\n                cls_name = inv_KERNEL_DICT[x.__class__]\n                set_priors(x, hyperpriors[cls_name], in_place=True)\n\n        for part in self.infix_tokens:\n            set_kern_prior(part)\n\n    def symbolically_equals(self, other) -> bool:\n        \"\"\"Determine whether this covariance's kernel expression is the same as another's kernel expression.\"\"\"\n        return self.symbolic_expr == other.symbolic_expr\n\n    def symbolic_expanded_equals(self, other) -> bool:\n        \"\"\"Determine whether this covariance's expanded kernel expression is the same as another's expanded kernel\n        expression.\"\"\"\n        return self.symbolic_expr_expanded == other.symbolic_expr_expanded\n\n    def infix_equals(self, other) -> bool:\n        \"\"\"Determine whether this covariance's kernel infix expression is the same as another's infix kernel\n        expression.\"\"\"\n        # naively compare based on infix\n        return isinstance(other, Covariance) and other.infix == self.infix\n\n    def as_latex(self) -> str:\n        \"\"\"Get a LaTeX representation of this covariance.\"\"\"\n        return latex(self.symbolic_expr)\n\n    def as_mathml(self) -> str:\n        \"\"\"Get a MathML representation of this covariance.\"\"\"\n        return mathml(self.symbolic_expr)\n\n    def as_dot(self) -> str:\n        \"\"\"Get a DOT representation of this covariance.\"\"\"\n        return dotprint(self.symbolic_expr)\n\n    def as_graph(self) -> Source:\n        \"\"\"Get a GraphViz Source representation of this covariance.\"\"\"\n        return Source(self.as_dot())\n\n    def __add__(self, other):\n        return Covariance(self.raw_kernel + other.raw_kernel)\n\n    def __mul__(self, other):\n        return Covariance(self.raw_kernel * other.raw_kernel)\n\n    def __str__(self):\n        return str(self.symbolic_expr)\n\n    def __repr__(self):\n        return f'{self.__class__.__name__}('f'kernel={self.infix_full !r})'\n\n\ndef pretty_print_covariances(covariances: List[Covariance],\n                             kernel_type_label: Optional[str] = None):\n    \"\"\"Pretty print a list of covariances.\"\"\"\n    n_kernels = len(covariances)\n\n    plural_suffix = 's' if n_kernels > 1 else ''\n    ending = f'kernel{plural_suffix}:'\n    if kernel_type_label is not None:\n        message = f'{n_kernels} {kernel_type_label} {ending}'\n    else:\n        message = f'{n_kernels} {ending}'\n    message = message.capitalize()\n    print(message)\n    for cov in covariances:\n        cov.pretty_print()\n    print('')\n\n\n# Symbolic interface\ndef tokens_to_kernel_symbols(tokens: List[Union[str, RawKernelType]]) -> List[Union[str, KernelSymbol]]:\n    symbols = []\n    for token in tokens:\n        if isinstance(token, str):\n            symbols.append(token)\n        elif isinstance(token, RawKernelType):\n            name = subkernel_expression(token)\n            symbols.append(KernelSymbol(name, token))\n    return symbols\n\n\ndef euclidean_distance(x: np.ndarray,\n                       y: np.ndarray) -> float:\n    return np.linalg.norm(x - y)\n\n\ndef kernel_l2_dist(kernel_1: RawKernelType,\n                   kernel_2: RawKernelType,\n                   x: np.ndarray) -> float:\n    \"\"\"Euclidean distance between two kernel matrices.\n\n    :param kernel_1:\n    :param kernel_2:\n    :param x:\n    :return:\n    \"\"\"\n\n    return euclidean_distance(compute_kernel(kernel_1, x), compute_kernel(kernel_2, x))\n\n\ndef covariance_distance(covariances: List[Covariance],\n                        x: np.ndarray) -> np.ndarray:\n    \"\"\"Euclidean distance of all pairs gp_models.\n\n    :param covariances:\n    :param x:\n    :return:\n    \"\"\"\n    # For each pair of kernel matrices, compute Euclidean distance\n    n_kernels = len(covariances)\n    dists = np.zeros((n_kernels, n_kernels))\n    for i in range(n_kernels):\n        for j in range(i + 1, n_kernels):\n            dists[i, j] = kernel_l2_dist(covariances[i].raw_kernel, covariances[j].raw_kernel, x)\n    # Make symmetric\n    dists = (dists + dists.T) / 2.\n    return dists\n\n\ndef remove_duplicate_kernels(covariances: List[Covariance]) -> List[Covariance]:\n    \"\"\"Remove duplicate gp_models.\n\n    :param covariances:\n    :return:\n    \"\"\"\n    return remove_duplicates([cov.symbolic_expr for cov in covariances], covariances)\n\n\ndef kernel_vec_avg_dist(kvecs1: np.ndarray,\n                        kvecs2: np.ndarray) -> float:\n    \"\"\"Average Euclidean distance between two lists of vectors.\n\n    :param kvecs1: n_1 x d array encoding of an additive kernel part\n    :param kvecs2: n_2 x d array encoding of an additive kernel part\n    :return:\n    \"\"\"\n    dists = cdist(kvecs1, kvecs2, metric='euclidean')\n    return float(np.mean(dists))\n\n\ndef all_pairs_avg_dist(covariances: List[Covariance],\n                       base_kernels: List[str],\n                       n_dims: int) -> float:\n    \"\"\"Mean distance between all pairs of gp_models.\n\n    Can be thought of as a diversity score of a population of gp_models\n    :param covariances:\n    :param base_kernels:\n    :param n_dims:\n    :return:\n    \"\"\"\n    if len(covariances) < 2:\n        return 0.\n\n    raw_kernels = [cov.raw_kernel for cov in covariances]\n    kernel_vecs = kernels_to_kernel_vecs(raw_kernels, base_kernels, n_dims)\n\n    # compute average Euclidean distance for all pairs of gp_models\n    data = np.empty((len(kernel_vecs), 1), dtype=np.object)\n    for i, kvec in enumerate(kernel_vecs):\n        data[i, 0] = kvec\n    pairwise_dist = pdist(data, metric=lambda u, v: kernel_vec_avg_dist(u[0], v[0]))\n    return float(np.mean(pairwise_dist))\n\n\ndef inner_frob(m, n):\n    \"\"\"Frobenius inner product\"\"\"\n    return np.trace(m.T.conjugate() @ n)\n\n\ndef alignment(k1: np.ndarray, k2: np.ndarray) -> float:\n    \"\"\"Alignment A(k1, k2) between two kernel matrices\n\n    It can be viewed as the cosine of the angle between the matrices viewed as 2-d vectors\n\n    0 <= A(k1, k2) <= 1\n\n        Alignment $A$ between two kernel matrices $K_1$ and $K_2$:\n\n    $$A(K_1, K_2) = \\frac{\\langle K_1, K_2 \\rangle_F}{\\sqrt{\\langle K_1, K_1 \\rangle_F \\langle K_2, K_2 \\rangle_F}}$$\n    \"\"\"\n    k1_dot_k2 = inner_frob(k1, k2)\n    k1_dot_k1 = inner_frob(k1, k1)\n    k2_dot_k2 = inner_frob(k2, k2)\n\n    return k1_dot_k2 / np.sqrt(k1_dot_k1 * k2_dot_k2)\n\n\ndef centered_alignment(k1: np.ndarray, k2: np.ndarray) -> float:\n    \"\"\"Centered kernel alignment\n\n    Cortes et al. (2012)\n    \"\"\"\n    k1_centered = center_kernel(k1)\n    k2_centered = center_kernel(k2)\n    return alignment(k1_centered, k2_centered)\n\n\ndef center_kernel(k: np.ndarray) -> np.ndarray:\n    \"\"\"Center a kernel matrix\"\"\"\n    m = k.shape[0]\n    identity = np.eye(m)\n    ones = np.ones((m, 1))\n    centering = (identity - (ones @ ones.T) / m)\n    return centering @ k @ centering\n\n\ndef pairwise_centered_alignments(covariances: List[Covariance],\n                                 x: np.ndarray) -> np.ndarray:\n    \"\"\"Alignment of all pairs of covariances.\n\n    :param covariances:\n    :param x:\n    :return:\n    \"\"\"\n    # For each pair of kernel matrices, compute alignment\n    n_kernels = len(covariances)\n    dists = np.zeros((n_kernels, n_kernels))\n    for i in range(n_kernels):\n        for j in range(i + 1, n_kernels):\n            k1 = compute_kernel(covariances[i].raw_kernel, x)\n            k2 = compute_kernel(covariances[j].raw_kernel, x)\n            dists[i, j] = centered_alignment(k1, k2)\n    # Make symmetric\n    dists = (dists + dists.T) / 2.\n    return dists\n", "meta": {"hexsha": "453283c15eb0e6a4d786142c313dc680a5338ff2", "size": 11465, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/autoks/core/covariance.py", "max_stars_repo_name": "lschlessinger1/MS-project", "max_stars_repo_head_hexsha": "e1c02d1d1a7a2480ff6f14f30625dc42ee3417e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-29T15:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-13T18:58:40.000Z", "max_issues_repo_path": "src/autoks/core/covariance.py", "max_issues_repo_name": "lschlessinger1/MS-project", "max_issues_repo_head_hexsha": "e1c02d1d1a7a2480ff6f14f30625dc42ee3417e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 275, "max_issues_repo_issues_event_min_datetime": "2019-02-19T22:59:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-03T08:56:08.000Z", "max_forks_repo_path": "src/autoks/core/covariance.py", "max_forks_repo_name": "lschlessinger1/MS-project", "max_forks_repo_head_hexsha": "e1c02d1d1a7a2480ff6f14f30625dc42ee3417e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8200589971, "max_line_length": 121, "alphanum_fraction": 0.6672481465, "include": true, "reason": "import numpy,from scipy,from sympy", "num_tokens": 2810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.18839833410629483}}
{"text": "# Copyright 2018 Timo Nolle\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n# ==============================================================================\n\nimport numpy as np\n\nfrom april.anomalydetection.utils import label_collapse\nfrom april.anomalydetection.utils import max_collapse\nfrom april.anomalydetection.utils.heuristic import best_heuristic\nfrom april.anomalydetection.utils.heuristic import elbow_heuristic\nfrom april.anomalydetection.utils.heuristic import ratio_heuristic\nfrom april.anomalydetection.utils.heuristic import lowest_plateau_heuristic\nfrom april.enums import Base\nfrom april.enums import Class\nfrom april.enums import Heuristic\nfrom april.enums import Strategy\n\n\nclass Binarizer(object):\n    def __init__(self, result, mask, features, targets=None):\n        self.result = result\n        self._mask = mask\n        self.mask_ = mask\n        self.features = features\n        self._targets = targets\n\n        #Try to fix dimensions\n        if self.mask_.shape != self.result.scores.shape:\n            if len(self.mask_) != len(self.result.scores.shape):\n                self.mask_ = np.expand_dims(self.mask_, axis=-1)\n            self.mask_ = np.repeat(self.mask_, self.result.scores.shape[-1], axis=-1)\n\n        self.targets = None\n        if self._targets is not None:\n            if self.result.scores.shape[2] == 1:\n                self._targets = np.delete(self._targets,1, axis=2) # 删除第二列\n            elif self.result.scores.shape[2] == 2:\n                pass\n            self.targets = dict((a, self.mask(label_collapse(self._targets, axis=a))) for a in [0, 1,2])\n\n    def mask(self, a):\n        print('**************a.shape=', a.shape)\n        if len(a.shape) == 1:\n            print('1 len(a.shape)=', len(a.shape))\n            m = self.mask_[:, 0, 0]\n        elif len(a.shape) == 2:\n            print('2 len(a.shape)=', len(a.shape))\n            m = self.mask_[:, :, 0]\n        else:\n            print('? len(a.shape)=', len(a.shape))\n            m = self.mask_\n        print('type(a)=', type(a), ',type(m)=', type(m))\n        print('a.shape=', a.shape, ', m.shape=', m.shape)\n#         print('a[0]=', a[0], ', m[0]=', m[0])\n        return np.ma.array(a, mask=m)\n\n    def get_targets(self, axis=2):\n        return self.targets.get(axis)\n\n    def correct_shape(self, tau, strategy):\n        tau = np.asarray(tau)\n        if strategy == Strategy.POSITION:\n            tau = tau[:, None]\n        if strategy == Strategy.POSITION_ATTRIBUTE:\n            tau = tau.reshape(*self.result.scores.shape[1:])\n        return tau\n\n    def split_by_strategy(self, a, strategy):\n        if strategy == Strategy.SINGLE:\n            return [a]\n        elif isinstance(a, list):\n            if strategy == Strategy.POSITION:\n                return [[_a[:, i:i + 1] for _a in a] for i in range(len(a[0][0]))]\n            elif strategy == Strategy.ATTRIBUTE:\n                return [[_a] for _a in a]\n            elif strategy == Strategy.POSITION_ATTRIBUTE:\n                return [[_a[:, i:i + 1]] for i in range(len(a[0][0])) for _a in a]\n        else:\n            if strategy == Strategy.POSITION:\n                return [a[:, i:i + 1, :] for i in range(a.shape[1])]\n            elif strategy == Strategy.ATTRIBUTE:\n                return [a[:, :, i:i + 1] for i in range(a.shape[2])]\n            elif strategy == Strategy.POSITION_ATTRIBUTE:\n                return [a[:, i:i + 1, j:j + 1] for i in range(a.shape[1]) for j in range(a.shape[2])]\n\n    def get_grid_candidate_taus(self, a, steps=20, axis=0):\n        \"\"\"G in the paper.\"\"\"\n        return np.linspace(max_collapse(a, axis=axis).min() - .001, a.max(), steps)\n\n    def get_candidate_taus(self, a, axis=0):\n        a = max_collapse(a, axis=axis).compressed()\n        a_min = a.min()\n        a_max = a.max()\n        if a_max > a_min:\n            a = (a_max - a) / (a_max - a_min)\n        a = 2 * (a / 2).round(2)\n        if a_max > a_min:\n            a = a_max - a * (a_max - a_min)\n        a = np.sort(np.unique(a))\n        a[0] -= .001\n        if len(a) < 5:\n            a = np.linspace(a_min - .001, a_max, 5)\n        return a\n\n    def get_legacy_tau(self, scores, heuristic=Heuristic.DEFAULT, strategy=Strategy.SINGLE, axis=0):\n        if heuristic == Heuristic.DEFAULT:\n            return np.array([0.5])\n\n        if not isinstance(scores, np.ma.MaskedArray):\n            scores = self.mask(scores)\n\n        alpha = None\n        if strategy == Strategy.SINGLE:\n            alpha = np.array([scores.mean()])\n        elif strategy == Strategy.ATTRIBUTE:\n            alpha = scores.mean(axis=1).mean(axis=0).data\n        elif strategy == Strategy.POSITION:\n            alpha = scores.mean(axis=2).mean(axis=0).data[:, None]\n        elif strategy == Strategy.POSITION_ATTRIBUTE:\n            alpha = scores.mean(axis=0).data\n\n        taus = self.get_grid_candidate_taus(scores / alpha, axis=axis)\n        tau = None\n        if heuristic == Heuristic.BEST:\n            y_true = self.get_targets(axis=axis)\n            tau = best_heuristic(taus=taus, theta=self.legacy_binarize, y_true=y_true, alpha=alpha, scores=scores,\n                                 axis=axis)\n\n        if heuristic == Heuristic.RATIO:\n            tau = ratio_heuristic(taus=taus, theta=self.legacy_binarize, scores=scores, axis=axis, alpha=alpha)\n\n        if heuristic in [Heuristic.ELBOW_DOWN, Heuristic.ELBOW_UP]:\n            tau = elbow_heuristic(taus=taus, theta=self.legacy_binarize, scores=scores, axis=axis,\n                                  alpha=alpha)[heuristic]\n\n        if heuristic in [Heuristic.LP_LEFT, Heuristic.LP_MEAN, Heuristic.LP_RIGHT]:\n            tau = lowest_plateau_heuristic(taus=taus, theta=self.legacy_binarize, scores=scores, axis=axis,\n                                           alpha=alpha)[heuristic]\n\n        return tau * alpha\n\n    def get_tau(self, scores, heuristic=Heuristic.DEFAULT, strategy=Strategy.SINGLE, axis=0, taus=None):\n        if heuristic == Heuristic.DEFAULT:\n            return np.array([0.5])\n\n        if not isinstance(scores, np.ma.MaskedArray):\n            scores = self.mask(scores)\n\n        scores = self.split_by_strategy(scores, strategy)\n\n        if heuristic in [Heuristic.MEAN, Heuristic.MEDIAN]:\n            scores = [max_collapse(s, axis=axis) for s in scores]\n            if heuristic == Heuristic.MEAN:\n                return self.correct_shape([np.mean(s[np.round(s, 1) > 0]) for s in scores], strategy)\n            elif heuristic == Heuristic.MEDIAN:\n                return self.correct_shape([np.median(s[np.round(s, 1) > 0]) for s in scores], strategy)\n\n        if taus is None:\n            taus = [self.get_candidate_taus(s, axis=axis) for s in scores]\n        else:\n            taus = [taus] * len(scores)\n\n        tau = None\n        if heuristic == Heuristic.BEST:\n            y_trues = self.split_by_strategy(self.get_targets(axis=2), strategy)\n            y_trues = [label_collapse(y, axis=axis) for y in y_trues]\n            tau = [best_heuristic(taus=t, theta=self.threshold_binarize, y_true=y, scores=s, axis=axis)\n                   for s, t, y in zip(scores, taus, y_trues)]\n\n        if heuristic == Heuristic.RATIO:\n            tau = [ratio_heuristic(taus=t, scores=s, theta=self.threshold_binarize, axis=axis)\n                   for s, t in zip(scores, taus)]\n\n        if heuristic in [Heuristic.ELBOW_DOWN, Heuristic.ELBOW_UP]:\n            tau = [elbow_heuristic(taus=t, scores=s, theta=self.threshold_binarize, axis=axis)[heuristic]\n                   for s, t in zip(scores, taus)]\n\n        if heuristic in [Heuristic.LP_LEFT, Heuristic.LP_MEAN, Heuristic.LP_RIGHT]:\n            tau = [lowest_plateau_heuristic(taus=t, scores=s, theta=self.threshold_binarize, axis=axis)[heuristic]\n                   for s, t in zip(scores, taus)]\n\n        return self.correct_shape(tau, strategy)\n\n    def legacy_binarize(self, scores, tau, alpha, axis=0):\n        # Apply the threshold function (Theta in the paper) using alpha as a scaling factor\n        return self.threshold_binarize(tau=tau * alpha, scores=scores, axis=axis)\n\n    def threshold_binarize(self, tau, scores, axis=0):\n        # Apply the threshold function (Theta in the paper)\n        predictions = np.array(scores.data > tau, dtype=int)\n\n        # Apply mask\n        predictions = np.ma.array(predictions, mask=scores.mask)\n\n        # Positive axis flatten predictions\n        if axis in [0, 1]:\n            predictions = label_collapse(predictions, axis=axis)\n\n        return predictions\n\n    def binarize(self, scores=None, tau=None, base=None, heuristic=None, strategy=None, go_backwards=False,\n                 return_parameters=False, axis=2, heuristic_axis=None):\n\n        if heuristic_axis is None:\n            heuristic_axis = axis\n\n        if scores is None:\n            if go_backwards:\n                scores = self.result.scores_backward\n            else:\n                scores = self.result.scores\n\n        if not isinstance(scores, np.ma.MaskedArray):\n            scores = self.mask(scores)\n\n        # Get baseline threshold (tau in the paper)\n        if tau is None or heuristic != Heuristic.MANUAL:\n            if base == Base.LEGACY:\n                tau = self.get_legacy_tau(scores=scores, heuristic=heuristic, strategy=strategy, axis=heuristic_axis)\n            else:\n                tau = self.get_tau(scores=scores, heuristic=heuristic, strategy=strategy, axis=heuristic_axis)\n\n        # Apply the threshold function (Theta in the paper)\n        predictions = self.threshold_binarize(scores=scores, tau=tau, axis=axis)\n\n        if return_parameters:\n            return predictions, tau\n\n        return predictions\n\n    @staticmethod\n    def get_scores(probabilities):\n        scores = np.zeros_like(probabilities)\n        for i in range(scores.shape[2]):\n            p = probabilities[:, :, i:i + 1]\n            _p = np.copy(probabilities)\n            _p[_p <= p] = 0\n            scores[:, :, i] = _p.sum(axis=2)\n        return scores\n\n    def classify(self, tau, features, predictions):\n        def mask(a, mask):\n            b = np.copy(a)\n            b[mask == 1] = 0\n            c = np.copy(a)\n            c[mask == 0] = 0\n            return b, c\n\n        classification = np.zeros_like(predictions)\n        c_cf = classification[:, :, 0]\n        c_data = classification[:, :, 1:]\n        predictions_cf = predictions[:, :, 0]\n        predictions_data = predictions[:, :, 1:]\n\n        # Attribute heuristic\n        c_data[predictions_data == 1] = Class.ATTRIBUTE\n        c_data[predictions_data == 0] = Class.NORMAL_ATTRIBUTE\n\n        # Insert and Skip heuristics\n        if self.result.predictions is not None:\n            f = features[0]\n\n            # Top-1 predictions\n            # p = np.argmax(self.result.predictions[0], axis=2) + 1\n\n            # Top-n predictions according to threshold (tau)\n            _p = self.get_scores(self.result.predictions[0])\n            p = np.zeros_like(_p) + np.arange(_p.shape[-1]) + 1\n            p[_p > tau[0]] = -1\n\n            # Mask padding\n            p[self._mask] = -1\n\n            # Helper objects\n            pfht = np.zeros_like(predictions_cf)\n            pfhf = np.zeros_like(predictions_cf)\n            pftt = np.zeros_like(predictions_cf)\n            pftf = np.zeros_like(predictions_cf)\n            ppht = np.zeros_like(predictions_cf)\n            pphf = np.zeros_like(predictions_cf)\n            pptt = np.zeros_like(predictions_cf)\n            pptf = np.zeros_like(predictions_cf)\n            ffht = np.zeros_like(predictions_cf)\n            ffhf = np.zeros_like(predictions_cf)\n            fftt = np.zeros_like(predictions_cf)\n            fftf = np.zeros_like(predictions_cf)\n            fpht = np.zeros_like(predictions_cf)\n            fphf = np.zeros_like(predictions_cf)\n            fptt = np.zeros_like(predictions_cf)\n            fptf = np.zeros_like(predictions_cf)\n\n            for j in np.arange(f.shape[1]):\n                # Current prediction and feature\n                _p = p[:, j:j + 1]\n                _f = f[:, j:j + 1]\n\n                # Top-1 Predictions\n                ph = p[:, :j]\n                phf, pht = mask(ph, predictions_cf[:, :j])\n                pt = p[:, j + 1:]\n                ptf, ptt = mask(pt, predictions_cf[:, j + 1:])\n\n                # Actual case features\n                fh = f[:, :j]\n                fhf, fht = mask(fh, predictions_cf[:, :j])\n                ft = f[:, j + 1:]\n                ftf, ftt = mask(ft, predictions_cf[:, j + 1:])\n\n                # Prediction appears elsewhere in case\n                pfht[:, j] = np.any(np.any(_p == fht[:, :, np.newaxis], axis=-1), axis=-1)\n                pfhf[:, j] = np.any(np.any(_p == fhf[:, :, np.newaxis], axis=-1), axis=-1)\n                pftt[:, j] = np.any(np.any(_p == ftt[:, :, np.newaxis], axis=-1), axis=-1)\n                pftf[:, j] = np.any(np.any(_p == ftf[:, :, np.newaxis], axis=-1), axis=-1)\n\n                # Prediction appears elsewhere in predictions\n                ppht[:, j] = np.any(np.any(_p == pht, axis=-1), axis=-1)\n                pphf[:, j] = np.any(np.any(_p == phf, axis=-1), axis=-1)\n                pptt[:, j] = np.any(np.any(_p == ptt, axis=-1), axis=-1)\n                pptf[:, j] = np.any(np.any(_p == ptf, axis=-1), axis=-1)\n\n                # Event appears elsewhere in case\n                ffht[:, j] = np.any(_f == fht, axis=-1)\n                ffhf[:, j] = np.any(_f == fhf, axis=-1)\n                fftt[:, j] = np.any(_f == ftt, axis=-1)\n                fftf[:, j] = np.any(_f == ftf, axis=-1)\n\n                # Event appears elsewhere in predictions\n                fpht[:, j] = np.any(np.any(_f[:, :, np.newaxis] == pht, axis=-1), axis=-1)\n                fphf[:, j] = np.any(np.any(_f[:, :, np.newaxis] == phf, axis=-1), axis=-1)\n                fptt[:, j] = np.any(np.any(_f[:, :, np.newaxis] == ptt, axis=-1), axis=-1)\n                fptf[:, j] = np.any(np.any(_f[:, :, np.newaxis] == ptf, axis=-1), axis=-1)\n\n            # Classification rules\n            skips = np.logical_and(predictions_cf == 1, ~np.logical_or(pfhf, pftf))\n            inserts = np.logical_and(predictions_cf == 1, np.logical_or(pfhf, pftf))\n            reworks = np.logical_and(predictions_cf == 1, ffhf)\n\n            shifts = np.logical_and(predictions_cf == 1, np.logical_xor(pfht, pftt))\n            lates = np.logical_and(predictions_cf == 1, fpht)\n            earlies = np.logical_and(predictions_cf == 1, fptt)\n\n            # Set the labels\n            c_cf[inserts] = Class.INSERT\n            c_cf[skips] = Class.SKIP\n            c_cf[shifts] = Class.SHIFT\n            c_cf[lates] = Class.LATE\n            c_cf[earlies] = Class.EARLY\n            c_cf[reworks] = Class.REWORK\n\n        return self.mask(classification)\n", "meta": {"hexsha": "f115ace0e53fc85a17484119bf24536eb25792a0", "size": 15311, "ext": "py", "lang": "Python", "max_stars_repo_path": "experiments/1_Sampling_Naive_Likelihood_OC-SVM_DAE_BINet/april/anomalydetection/utils/binarizer.py", "max_stars_repo_name": "Business-Process-Analytics/AnomalyDetection", "max_stars_repo_head_hexsha": "9476ff2d674d3a98fa61805a6d29c4d8a7ddc5f0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experiments/1_Sampling_Naive_Likelihood_OC-SVM_DAE_BINet/april/anomalydetection/utils/binarizer.py", "max_issues_repo_name": "Business-Process-Analytics/AnomalyDetection", "max_issues_repo_head_hexsha": "9476ff2d674d3a98fa61805a6d29c4d8a7ddc5f0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "experiments/1_Sampling_Naive_Likelihood_OC-SVM_DAE_BINet/april/anomalydetection/utils/binarizer.py", "max_forks_repo_name": "Business-Process-Analytics/AnomalyDetection", "max_forks_repo_head_hexsha": "9476ff2d674d3a98fa61805a6d29c4d8a7ddc5f0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.1790633609, "max_line_length": 117, "alphanum_fraction": 0.5698517406, "include": true, "reason": "import numpy", "num_tokens": 3831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.18839833410629483}}
{"text": "\"\"\"\n\nFilename: utils.py\n\nPurpose: Set of utility functions\n\nAuthor: John Weaver\nDate created: 28.11.2018\nPossible problems:\n1.\n\n\"\"\"\nimport os\nimport numpy as np\nfrom tractor.galaxy import ExpGalaxy\nfrom tractor import EllipseE\nfrom tractor.galaxy import ExpGalaxy\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm, SymLogNorm\nfrom matplotlib.patches import Ellipse\nfrom matplotlib.patches import Rectangle\nfrom skimage.segmentation import find_boundaries\n\nimport config as conf\nimport matplotlib.cm as cm\nimport random\nfrom time import time\nfrom astropy.io import fits\n\nimport logging\nlogger = logging.getLogger('farmer.utils')\n\ndef header_from_dict(params):\n    \"\"\" Take in dictionary and churn out a header. Never forget configs again. \"\"\"\n    hdr = fits.Header()\n    total_public_entries = np.sum([ not k.startswith('__') for k in params.keys()])\n    logger.debug(f'header_from_dict :: Dictionary has {total_public_entries} entires')\n    tstart = time()\n    for i, attr in enumerate(params.keys()):\n        if not attr.startswith('__'):\n            logger.debug(f'header_from_dict ::   {attr}')\n            value = params[attr]\n            if type(value) == str:\n                # store normally\n                hdr.set(f'CONF{i+1}', value, attr)\n            if type(value) in (float, int):\n                # store normally\n                hdr.set(f'CONF{i+1}', value, attr)\n            if type(value) in (list, tuple):\n                # freak out.\n                for j, val in enumerate(value):\n                    hdr.set(f'CONF{i+1}_{j+1}', str(val), f'{attr}_{j+1}')\n            \n    logger.debug(f'header_from_dict :: Completed writing header ({time() - tstart:2.3f}s)')\n    return hdr\n\ndef create_circular_mask(h, w, center=None, radius=None):\n\n    if center is None: # use the middle of the image\n        center = [int(w/2), int(h/2)]\n    if radius is None: # use the smallest distance between the center and image walls\n        radius = min(center[0], center[1], w-center[0], h-center[1])\n\n    Y, X = np.ogrid[:h, :w]\n    dist_from_center = np.sqrt((X - center[0])**2 + (Y-center[1])**2)\n\n    mask = np.zeros((h, w), dtype=int)\n    mask[dist_from_center <= radius] = 1\n    return mask\n    \nclass SimpleGalaxy(ExpGalaxy):\n    '''This defines the 'SIMP' galaxy profile -- an exponential profile\n    with a fixed shape of a 0.45 arcsec effective radius and spherical\n    shape.  It is used to detect marginally-resolved galaxies.\n    '''\n    shape = EllipseE(0.45 / conf.PIXEL_SCALE, 0., 0.)\n\n    def __init__(self, *args):\n        super(SimpleGalaxy, self).__init__(*args)\n\n    def __str__(self):\n        return (self.name + ' at ' + str(self.pos)\n                + ' with ' + str(self.brightness))\n\n    def __repr__(self):\n        return (self.name + '(pos=' + repr(self.pos) +\n                ', brightness=' + repr(self.brightness) + ')')\n\n    @staticmethod\n    def getNamedParams():\n        return dict(pos=0, brightness=1)\n\n    def getName(self):\n        return 'SimpleGalaxy'\n\n    ### HACK -- for Galaxy.getParamDerivatives()\n    def isParamFrozen(self, pname):\n        if pname == 'shape':\n            return True\n        return super(SimpleGalaxy, self).isParamFrozen(pname)   \n\n\ndef make_weights(fn):\n\n    # Grab an image, estimate rms, make weight map fits file\n\n    import sys\n    from astropy.stats import sigma_clipped_stats\n\n\n    hdul = fits.open(fn)\n\n    print(hdul.info())\n\n    __, __, rms = sigma_clipped_stats(hdul[0].data)\n\n    wgt = np.zeros_like(hdul[0].data)\n    wgt[rms>0] = 1/rms**2\n\n    hdul[0].data = wgt\n\n    p = fn.split('.fits')\n    fout = p[0]+conf.WEIGHT_EXT+'.fits'\n    print('Writing weight map to ', fout)\n    hdul.writeto(fout)\n\n", "meta": {"hexsha": "d673471a02db7c77adee9bb7e6a00f53afae2e96", "size": 3694, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/core/utils.py", "max_stars_repo_name": "astroweaver/dev-tractor-pipeline", "max_stars_repo_head_hexsha": "5535380cf0c1838a282aa872da010767fbb65e73", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-26T06:50:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T08:55:40.000Z", "max_issues_repo_path": "src/core/utils.py", "max_issues_repo_name": "astroweaver/the_farmer", "max_issues_repo_head_hexsha": "5535380cf0c1838a282aa872da010767fbb65e73", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/utils.py", "max_forks_repo_name": "astroweaver/the_farmer", "max_forks_repo_head_hexsha": "5535380cf0c1838a282aa872da010767fbb65e73", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0866141732, "max_line_length": 91, "alphanum_fraction": 0.631023281, "include": true, "reason": "import numpy,from astropy", "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.18839833410629483}}
{"text": "# AUTOGENERATED! DO NOT EDIT! File to edit: data_vis.ipynb (unless otherwise specified).\n\n__all__ = ['get_settings', 'cross_section_helper']\n\n# Cell\nimport numpy as np\nimport scipy.interpolate\nimport matplotlib.pyplot as plt\n\n# Cell\ndef get_settings():\n    \"\"\"\n    Returns some nice default settings for matplotlib to be used with `matplotlib.pyplot.rc_context`.\n    \"\"\"\n    return {'axes.labelsize': 32,\n            'xtick.major.size': 10,\n            'xtick.major.width': 1.5,\n            'xtick.labelsize': 24,\n            'ytick.major.size': 10,\n            'ytick.major.width': 1.5,\n            'ytick.labelsize': 24,\n            'legend.fontsize': 18,\n            'lines.linewidth': 4,\n            'lines.markersize': 10,\n            'figure.figsize': (12,8)}\n\n# Cell\nclass cross_section_helper:\n    \"\"\"\n    Class enabling computations and visualizations relating to signal and background cross sections\n    \"\"\"\n\n    def __init__(self, masses, sig_css, bg_css, mass_units='GeV'):\n        self.masses = masses\n        self.sig_css = sig_css\n        self.bg_css = bg_css\n        self.mass_units = mass_units\n        self.log_sig_css = np.log10(self.sig_css)\n        self.m2logcsF = scipy.interpolate.interp1d(self.masses, self.log_sig_css, kind='cubic')\n        self.logcs2mF = scipy.interpolate.interp1d(self.m2logcsF(self.masses), self.masses, kind='cubic')\n        # WHERE TO PUT THIS VARIABLE?\n        self.conv = 10**15 / 10**12 # cross sec (pb) * lumi (fb^{-1}) * self.conv = number of events\n\n    def sig_cs(self, masses, who='E'):\n        r\"\"\"\n        Given a mass, returns the signal cross section (in pb) through interpolation\n        \"\"\"\n        return np.power(10, self.m2logcsF(masses))\n\n    def mass(self, css, who='E'):\n        r\"\"\"\n        Given a cross section, returns the particle mass value yielding that signal cross section\n        \"\"\"\n        return self.logcs2mF(np.log10(css))\n\n    def absolute_max_mass_sens(self, lumi=3000, sig=5):\n        \"\"\"\n        Given a luminosity and desired signal significance, returns the best-case scenario highest probeable mass\n        (i.e., TPR = 1, FPR = 0)\n        \"\"\"\n        return self.mass(sig**2 / (lumi * self.conv))\n\n    def max_mass_sens_versus_tpr_fpr(self, plot=True, sig=5, lumi=3000, tpr_bounds=(0.1,1), fpr_bounds=(10**-7, 0.5), res=1000,\n                                     cvalues=None, clabels=None, manual=None):\n        \"\"\"\n        For fixed luminosity and desired signal significance, plot the maximum mass sensitivity as a function of a\n        binary classifier's true positive rate and false positive rate.\n        \"\"\"\n        tprs = np.linspace(tpr_bounds[0], tpr_bounds[1], 100)\n        fprs = np.sort(np.logspace(np.log10(fpr_bounds[0]), np.log10(fpr_bounds[1]), num=100, base=10))\n        bg_yield = self.conv * np.sum(self.bg_css) * lumi\n        coefsss = [\n            [[-(self.conv * tpr * lumi)**2, sig**2 * self.conv * tpr * lumi, sig**2 * fpr * bg_yield] for fpr in fprs] for tpr in tprs]\n        sig_csss = [[np.amax(np.roots(coefs)) for coefs in coefss] for coefss in coefsss]\n        max_mass_senss = self.mass(sig_csss)\n\n        # have found this plot works best when plotting log(fpr) on y-axis\n        log_fprs = np.log10(fprs)\n        ext = [tprs[0], tprs[-1], log_fprs[0], log_fprs[-1]]\n        pts = np.array([[tpr,log_fpr] for tpr in tprs for log_fpr in log_fprs])\n        data = max_mass_senss.flatten()\n        grid = np.array(\n                [[[x,y] for x in np.linspace(ext[0], ext[1], res)]\n                for y in np.linspace(ext[2], ext[3], res)])\n        interp = scipy.interpolate.griddata(pts, data, grid)\n\n        if plot:\n            with plt.rc_context(get_settings()):\n                plt.imshow(interp, origin='lower', aspect='auto', extent=ext, cmap='winter')\n                cbar = plt.colorbar()\n                plt.xlabel(r'{}'.format('True Positive Rate'))\n                plt.ylabel(r'{}'.format('False Postive Rate'))\n                cbar.set_label(r'{}'.format(f\"Mass Sensitivity ({self.mass_units})\"), rotation=90)\n                if None not in [cvalues, clabels]:\n                    result = plt.contour(grid[:,:,0], grid[:,:,1], interp, cvalues, colors='white',\n                                                 linewidths=3, linestyles='dashed')\n                    fmt = {lev:lab for lev, lab in zip(result.levels, clabels)}\n                    plt.clabel(result, result.levels, inline=True, fmt=fmt, fontsize=32, manual=manual)\n                minytick, maxytick = [int(log_fprs[0]) + 1, int(log_fprs[-1]) - 1]\n                plt.yticks(\n                    [i for i in range(minytick, maxytick+1)], [r'$10^{' + f'{i}' + r'}$' for i in range(minytick, maxytick+1)])\n\n        return [grid, interp]", "meta": {"hexsha": "a63a34c58876f602180ea7a7823f25b921265992", "size": 4737, "ext": "py", "lang": "Python", "max_stars_repo_path": "bcml4pheno/data_vis.py", "max_stars_repo_name": "sheride/bcml4pheno", "max_stars_repo_head_hexsha": "c9629dafcdbee0a4c28ceb7b28c9862de8479a24", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bcml4pheno/data_vis.py", "max_issues_repo_name": "sheride/bcml4pheno", "max_issues_repo_head_hexsha": "c9629dafcdbee0a4c28ceb7b28c9862de8479a24", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bcml4pheno/data_vis.py", "max_forks_repo_name": "sheride/bcml4pheno", "max_forks_repo_head_hexsha": "c9629dafcdbee0a4c28ceb7b28c9862de8479a24", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.9902912621, "max_line_length": 135, "alphanum_fraction": 0.5896136795, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.18839832707528617}}
{"text": "#!/usr/bin/env python\n\n\n\"\"\"\nCreated on 2015\n\n@author: jakobg\n\n\n This script is about extracting (NVSS)-relics when giving it an properly formated .csv file of galaxy clusters. It expects for every galaxy cluster\n - one .fits file in the 'Images_NVSS' folder\n - one .region file in the 'Regions' folder which contouns at least one DS9 region called polygon with text describing the regions name (e.g. drection), relic type and spectral index\n [optionally] one .slist file in the 'Sources' folder for source subtraction before extracting relics\n output is an .csv file of all extracted relics\n \n\"\"\"\n\n\nfrom __future__ import division,print_function\n\nimport os\nimport math\nimport numpy  as np\nimport pandas as pd\nimport argparse\n\n    \nprint( '###==== Step 0a: Executing self written .py subroutines ====###' )\nimport clusterbuster.surveyclasses    as cbclass\nimport clusterbuster.sourceextraction as relex\nimport clusterbuster.dbclasses        as cdb\nimport clusterbuster.iout.misc        as iom\nimport clusterbuster.iout.surveyplots as ioclass\nimport clusterbuster.maput            as maput\nimport clusterbuster.fitsut           as fitsut\n\n\nfrom astropy.io import fits\nfrom astropy.convolution import convolve\nfrom astropy.convolution import Gaussian2DKernel\nfrom astropy.wcs import WCS\nfrom reproject import reproject_interp\nfrom copy import copy, deepcopy\n                \ndef updateClusters_missingRegions(ClList, AddList):\n    \"\"\" This adds relic regions based on a .csv file to the cluster List \n    It is a workaround to have a fast update of the already existing datafiles with the soon to be standard file system,\n    in this case  only for clusters without NVSS detections are updated via the identifiers.\n    \n    Later on this might be incorporated in the CB suite\n    \"\"\"\n\n    regions = pd.read_csv(AddList, comment='#')\n    \"\"\" FIX the classification by mapping\"\"\"    \n    mapping = {'PHOENIX'          : 0, \n               'RELIC'            : 1,\n               'SHOCKLET'         : 3,\n               'AGN'              : -1,\n               'AGN_relic'        : -1,  \n               'AGN_RELIC/PHOENIX': 0,\n               'HALO'             : -2,\n               'SHOCKLET'         : 3}\n    \n    regions[\"CLASS_int\"] = regions[\"FLAGS_CLASS\"].map(mapping)\n    regions[\"CLASS_int\"] = regions[\"CLASS_int\"].fillna(-1)\n    regions.loc[regions['FLAGS_CLASS'] == 1 & regions['Counter'], 'FLAGS_CLASS'] = 2      # Double Relic\n    regions.loc[regions['FLAGS_CLASS'] == 3 & regions['Counter'], 'FLAGS_CLASS'] = 2      # Double Relic\n     \n\n    for index, row in regions.iterrows():\n        \"\"\" Just append the cluster if its status is not True and add the missing relic regions \"\"\"\n        for GCl in ClList:\n            if GCl.status not in ['TRUE'] and GCl.name == row['Cluster']:  \n\n                if int(row['CLASS_int']) == -2:\n                    continue  # For now exclude halos, just because they are currently a seperate entry in the clusters file\n                rtype = int(row['CLASS_int'])\n                alpha = -1  #row['Alpha']\n                alpha_err = 0  #row['Alpha_error']\n                alphaFLAG = False\n                candidate = (row['FLAG_conf'] == False)\n                region = cbclass.RelicRegion(name=row['Identifier'], cnt=[], rtype=rtype, alpha=alpha, alpha_err=alpha_err,\n                                             alphaFLAG=alphaFLAG, candidate=candidate)\n                GCl.add_regions([region])\n                \n    return ClList\n\n\ndef survey_run(surveys, infolder='', outfoldertop='/data/ClusterBuster-Output/', plot=True):\n    \"\"\" Extracts survey relics from an real world survey\n    \"\"\"\n    \n    for survey in surveys:\n        print('###==== Step 0b: Initialize internal variables/objects for survey: %s ====###' % survey)\n        smt = iom.SmartTiming()\n        \n        ClList = []\n        Excluded = []\n        subtract = ['slist', 'fits']  # im, fits, slist\n\n        Jy_SI    = 1e-26    # W/Hz/m^2\n        outfolder = '%s%s' % (outfoldertop, survey)\n        topfolder = os.getcwd() # '/home/jakobg/lib/ClusterBuster/Relics_Surveys/'\n        iom.check_mkdir(outfolder)  # create folder if necesairy\n\n        print( '###==== Step 1: Load data and anaylise it   ====###' )\n        # np.genfromtxt('Analysis_RORRS/ClusterRelics.csv'', delimiter=';')\n        ClusterFile = infolder + 'ClusterList/ClusterAfterNuza2017_clusters.csv' \n        RegionFile  = infolder + 'ClusterList/ClusterAfterNuza2017_regions.csv' \n\n        Clusters = pd.read_csv(ClusterFile, comment='#', delimiter=',', quotechar='\"')\n        Clusters.where(Clusters.notnull(), 0)\n        \n        \"\"\" Part of development: rpelace nan values with values that can be handled by clustebruster \"\"\"\n        \n        for strings in ['REF_LX', 'REF_M200', 'REF_M500', 'REF_F']:\n            Clusters[strings] = Clusters[strings].replace(np.nan, '', regex=True)\n\n        for values in ['M200', 'M500', 'LX_500_0.1-2.4']:\n            Clusters[values] = Clusters[values].replace(np.nan, 0, regex=True)\n\n        n = 0\n        for index, CL in Clusters.iterrows():\n            if CL['Cluster'] and CL['Cluster'] not in [o.name for o in ClList] and CL['Cluster'] not in ['']:\n                \"\"\"I did this to remove unfinished, but recent additions to the relic database\"\"\"\n                #print(type(CL['Discovery']))\n                #if math.isnan(CL['Discovery']):\n                #    pass\n                #elif int(CL['Discovery']) >= 2018:\n                #    continue\n\n                try:\n                    \"\"\"I did this to remove unfinished, but recent additions to the relic database\"\"\"\n                    if CL['Cluster'] == '#':\n                        continue\n                    if int(CL['Discovery']) >= 2018:\n                        continue\n                except:\n                    pass\n\n\n                n += 1\n#                if n > 5:\n#                     continue\n                Cl_name = CL['Cluster']\n                status  = CL['FLAG_INCLUDED']\n                \n\n                print(CL)\n\n                RA_host  = float(CL['RA'])    #float(CL[2])  \n                Dec_host = float(CL['Dec'])\n                \n                diff = np.sqrt((float(CL['RA_Xmax'])-RA_host)**2+(float(CL['Dec_Xmax'])-Dec_host)**2)*3600\n                if not math.isnan(diff) :           \n                    print('Two different centre positions given for cluster %s. The offset was %.1f arcsec' % (Cl_name, diff) )\n                    RA_host  = float(CL['RA_Xmax'])\n                    Dec_host = float(CL['Dec_Xmax'])\n  \n                z    = float(CL['z'])\n                M200 = float(CL['M200'])*1e14\n                M500 = float(CL['M500'])*1e14\n                Lx   = float(CL['LX_500_0.1-2.4'])*1e44\n                flux_lit = float(CL['F_lit'])\n                  \n                halo = CL['FLAG_Halo'] \n              \n                try:\n                  ClassFlag = ('true' in CL['Type_Flag'].lower())\n                except :\n                  ClassFlag = False    \n                  \n                #create Class object\n                GCl = cbclass.Galaxycluster(name=Cl_name, RA=RA_host, Dec=Dec_host, z=z, M200=M200, M500=M500, Lx=Lx, \n                                            Lx_lit=Lx, flux_lit=flux_lit, ClassFlag=ClassFlag, halo=halo, status=status)\n\n                # add further references\n                GCl.Lx      .ref = cdb.reference(CL['REF_LX'  ], rtype='text', page=None              , nr=None)\n                GCl.M200    .ref = cdb.reference(CL['REF_M200'], rtype='text', page=CL['REFPAGE_M200'], nr=None)\n                GCl.M500    .ref = cdb.reference(CL['REF_M500'], rtype='text', page=CL['REFPAGE_M500'], nr=None)\n                GCl.flux_lit.ref = cdb.reference(CL['REF_F'   ], rtype='text', page=CL['REFPAGE_F']   , nr=None)\n\n\n                #============= Load  survey (NVSS) image  =============#\n                if GCl.status not in ['TRUE']: \n                    ClList.append(GCl)\n                    continue\n                fitsimage = infolder + 'Images_%s/%s-%s.fits' % (survey, survey, Cl_name)\n                image, center, spixel = fitsut.fits2numpy(fitsimage)\n                \n                \n                if survey == 'NVSS':\n                        s_pixel   = [spixel[1]*GCl.cosmoPS*3600, spixel[1]*3600]\n                        NVSSbeam  = [45., 45./s_pixel[1]]\n                        NVSS_rms  = 4.5e-4     # in Jy/beam\n                        NVSSlimit = 2*NVSS_rms\n                        NVSSnu    = 1.4\n                        telescope = 'VLA-D'\n                        GCl.dinfo = cbclass.DetInfo(beam=[NVSSbeam[0], NVSSbeam[0], 0],\n                                                     spixel=s_pixel[1], rms=NVSS_rms,\n                                                     limit=NVSSlimit, telescope=telescope,\n                                                     nucen=NVSSnu, center=center[0], pcenter=center[1])\n                if survey == 'TGSS':\n                        s_pixel   = [spixel[1]*GCl.cosmoPS*3600, spixel[1]*3600]\n                        TGSSbeam  = [25., 25./s_pixel[1]]\n                        TGSS_rms  = 3.0e-3     # in Jy/beam\n                        TGSSlimit = 2*TGSS_rms\n                        beamrec   = 1. if GCl.Dec > 19 else 1. / np.cos(np.radians(GCl.Dec - 19))\n                        TGSSnu    = 0.1475\n                        telescope = 'GMRT'\n                        GCl.dinfo = cbclass.DetInfo(beam=[TGSSbeam[0]*beamrec, TGSSbeam[0], 0],\n                                                     spixel=s_pixel[1], rms=TGSS_rms,\n                                                     limit=TGSSlimit, telescope=telescope,\n                                                     nucen=TGSSnu, center=center[0], pcenter=center[1])\n                dinfo_survey = GCl.dinfo\n                #============= Load relic search region  =============#\n                # Make in np.image\n                regfile     = infolder + 'Regions/RR_%s.reg' % (Cl_name) \n                GCl.regions = ioclass.readDS9relics(regfile, spixel, center[0], center[1])\n\n                #============= Subtract Sources  =============#\n                # in Sources folder\n                #try load folder:\n                    #img = bdsm.process_image(args.file+args.ft, thresh_isl=args.tIs, thresh_pix=args.tPi, mean_map = 'zero', beam = (0.0125,0.0125,0), rms_map = False, rms_value = 0.00045, thresh = 'hard') \n                #except:\n\n                #pybdsm.catalog_type\n                #--< create .fits image ut of that, which you subtract from your image ....\n                smt(task='subtraction')\n                model      = np.zeros(image.shape)\n                model_conv = np.zeros(image.shape)\n                use_list, use_im = (False, False)\n                if 'slist' in subtract:\n                    slist = infolder + 'Sources/slist/%s.slist' % Cl_name\n                    if os.path.isfile(slist):\n                        scL = iom.read_para_list(slist)\n\n                        for sc in scL:\n\n                            if sc['shape'] == 'Gaussian':\n                                g_size = [float(sc['majoraxis'])/s_pixel[1]*60, float(sc['minoraxis'])/s_pixel[1]*60]\n                            else:\n                                g_size = [GCl.dinfo.beam[0]/GCl.dinfo.spixel, GCl.dinfo.beam[1]/GCl.dinfo.spixel]\n                            freq_factor = (GCl.dinfo.nucen/1.4)**(-0.7)\n                            COOp = iom.CoordinateToPixel(iom.J2000ToCoordinate(sc['dir']), spixel, center[0], center[1])\n\n                            GCl.compacts.append(sc)\n                            #This is not good --> better create an unconcolved model and convolve it with the desired beam\n                            model += maput.ImageGaussian_inv(model.shape, sc['flux']*1e-3*freq_factor, g_size, [COOp[0]-1, COOp[1]-1], theta=sc['theta'], FWHM=True)  #*gaussian_area\n                            #model_conv += maput.ImageGaussian_inv(model_conv.shape, sc['flux']*1e-3*freq_factor, g_size, [COOp[0]-1.,COOp[1]-1], theta = sc['theta'], FWHM=True)  #*gaussian_area\n                        model_conv = model\n                        use_list = True\n\n                if 'fits' in subtract:\n                    highres_image_path = infolder + 'Images_%s/%s-%s.fits' % (\"FIRST\", \"FIRST\", Cl_name)\n                    if os.path.isfile(highres_image_path):\n    \n                        # regridd\n       \n                        # http://reproject.readthedocs.io/en/stable/  --> works on fits files\n                        hdu_raw = fits.open(fitsimage)[0]\n                        image_HR, center_HR, spixel_HR = fitsut.fits2numpy(highres_image_path)\n                        s_pixel_HR = [spixel_HR[1]*GCl.cosmoPS*3600, spixel_HR[1]*3600]\n                        fitsut.numpy2fits(image_HR,  infolder + 'Images_%s/%s-%s_test.fits' % (\"FIRST\", \"FIRST\", Cl_name), s_pixel_HR[1], center_HR[0], center_HR[1])\n                        hdu_HR = fits.open(infolder + 'Images_%s/%s-%s_test.fits' % (\"FIRST\", \"FIRST\", Cl_name))[0]\n                        hdu_HR.data = hdu_HR.data.squeeze()\n                        hdu_HR.data[np.isnan(hdu_HR.data)] = 0.     # For contour masked  NVSS images I encountered the issue that some values where nan\n                        hdu_HR.data[np.where(hdu_HR.data < 6e-4)] = 0.\n                                  \n                        pad = 50\n                        hdu_HR.data = np.lib.pad(hdu_HR.data, pad, maput.padwithtens)\n                        \n                        FWHM2sigma = 1/2.354\n                        FWHM_FIRST = 5.4\n                        FWHM_conv  = np.sqrt(GCl.dinfo.beam[0]**2-FWHM_FIRST**2)\n                        gaussian_2D_kernel = Gaussian2DKernel(FWHM_conv/s_pixel_HR[1]*FWHM2sigma)\n                        A_beam_old = 1.133*((FWHM_FIRST/s_pixel_HR[1])**2)  # FIRST-beam\n                        A_beam     = 1.133*((GCl.dinfo.beam[0]/s_pixel_HR[1])**2)\n\n                        \"\"\"\n                        The copy action is very dangerous, because the corresponding .header object is cloned, so that\n                        any change in hdu_HR_conv.header also influences hdu_HR.header\n                        deepcopy() is not possible. Because of the we remove hdu_HR_conv from any changes in the header\n                        \"\"\"\n                        hdu_HR_conv = copy(hdu_HR)\n                        hdu_HR_conv.data = A_beam/A_beam_old*convolve(hdu_HR.data, gaussian_2D_kernel, normalize_kernel=True)\n                        for hdu in [hdu_HR]:\n#                            hdu.data = np.expand_dims(hdu.data, axis=0)\n#                            hdu.data = np.expand_dims(hdu.data, axis=0)\n                            hdu.header['CRPIX1'] = hdu.header['CRPIX1'] + pad\n                            hdu.header['CRPIX2'] = hdu.header['CRPIX2'] + pad\n                            hdu.header['NAXIS1'] = hdu.header['NAXIS1'] + pad*2\n                            hdu.header['NAXIS2'] = hdu.header['NAXIS2'] + pad*2\n#\n#                        from astropy.io import fits\n#                        from astropy.utils.data import get_pkg_data_filename\n#                        hdu_raw = fits.open(get_pkg_data_filename('galactic_center/gc_2mass_k.fits'))[0]\n#                        hdu2 = fits.open(get_pkg_data_filename('galactic_center/gc_msx_e.fits'))[0]\n###                      \n                        for hdu in [hdu_raw, hdu_HR]:\n                            try:\n                                hdu.data = hdu_raw.data[0,0,:,:]\n                            except:\n                                print('Test ... data dimensions are matching')\n                            hdu.header['NAXIS'] = 2\n\n                            keylist = ['PC01_01', 'PC02_01', 'PC03_01', 'PC04_01',\n                                       'PC01_02', 'PC02_02', 'PC03_02', 'PC04_02',\n                                       'PC01_03', 'PC02_03', 'PC03_03', 'PC04_03',\n                                       'PC01_04', 'PC02_04', 'PC03_04', 'PC04_04',\n                                       'NAXIS3', 'NAXIS4',\n                                       'CTYPE3', 'CRVAL3', 'CDELT3', 'CRPIX3', 'CUNIT3', 'CROTA3',\n                                       'CTYPE4', 'CRVAL4', 'CDELT4', 'CRPIX4', 'CUNIT4', 'CROTA4']\n                            for key in keylist:     \n                                try: \n                                    del hdu.header[key]\n                                    print('[%s] removed from the .fits header' % (key))\n                                except:\n                                    print('[%s] not found, so we cannot delete it from the .fits header' % (key))\n                                    \n                            hdu.header['EPOCH'] = 2e3\n                            hdu.header['EQUINOX'] = 2e3\n                            print('====================')\n\n\n                        hdu_HR_conv.writeto(infolder + 'Images_%s/%s-%s_test2b.fits' % (\"FIRST\", \"FIRST\", Cl_name), overwrite=True)\n                        fitsut.numpy2fits(hdu_HR_conv.data.squeeze(),  infolder + 'Images_%s/%s-%s_test2.fits' % (\"FIRST\", \"FIRST\", Cl_name), s_pixel_HR[1], center_HR[0], [c+pad for c in center_HR[1]])\n\n\n                        print( 'WCS(hdu_raw.header).wcs.naxis, WCS(hdu2.header).wcs.naxis', WCS(hdu_raw.header).wcs.naxis, WCS(hdu_HR_conv.header).wcs.naxis )\n                        array, footprint = reproject_interp(hdu_HR_conv, hdu_raw.header) #hdu 2 image and systm, hdu1--> just the system\n\n                        print('_______', np.sum(array), footprint)\n                        print('_______________________________', array.shape, image.shape)\n                        array = array.squeeze() #could be removed\n                        array[np.isnan(array)] = 0.\n\n                        fitsut.map2fits(array, GCl.dinfo, infolder + 'Images_%s/%s-%s_test3.fits' % (\"FIRST\", \"FIRST\", Cl_name))\n\n                        model_conv = array.squeeze()  # add up  OR replace!\n                        print('fits_subtraction: np.sum(model_conv):', np.sum(model_conv))\n                        use_im = True\n\n                residuum = image-model_conv\n\n                \"\"\" Development: Only get the flux within the search region \"\"\"       \n                extreme_res = True\n                residuum = maput.ContourMasking(residuum, [region.cnt[0] for region in GCl.regions])\n                \n                print('%30s source subtraction;  list: %5r; image: %5r'   % (Cl_name , use_list, use_im) )\n                GCl.maps_update(residuum, 'Diffuse', infolder + '%s/Images_%s/diffuse/%s-%s.fits' % (topfolder, survey, survey, Cl_name))\n                if np.sum(model_conv) != 0 or extreme_res:      \n                    GCl.maps_update(image     , 'Raw'       , infolder + '%s/Images_%s/raw/%s-%s_res.fits' % (topfolder, survey, survey, Cl_name))\n                    GCl.maps_update(model     , 'Modell'    , infolder + '%s/Images_%s/subtracted/%s-%s.fits' % (topfolder, survey, survey, Cl_name))\n                    GCl.maps_update(model_conv, 'Subtracted', infolder + '%s/Images_%s/subtracted/%s-%s_conv.fits' % (topfolder, survey, survey, Cl_name))\n                smt()\n                \n                #============= impose relic.search  =============#\n                for ii, region in enumerate(GCl.regions):\n                    smt(task='RelicExtr')\n                    relics = relex.RelicExtraction(residuum, z, GCl=GCl, dinfo=GCl.dinfo, rinfo=region, Imcenter=center,\n                                                   subtracted=model)[0:2]  # faintexcl=3.6\n                    smt()\n                    relics = sorted(relics, key=lambda x: x.flux, reverse=True)\n\n                    for relic in relics:\n                        relic.alpha.value = region.alpha\n                        print(region.alpha_err)\n                        if region.alpha_err is None:\n                            relic.alpha.set_std(0)\n                        else:\n                            relic.alpha.set_std(region.alpha_err)\n\n                    GCl.add_relics(relics)\n\n                # Add galaxy cluster to the list\n                ClList.append(GCl)\n          \n            #============= Report why certain clusters are excluded  =============#\n            else:\n                RL_name = CL['Cluster']\n                if CL['Identifier']:\n                    RL_name += '_' + CL['Identifier']\n\n                if CL['FLAG_INCLUDED'] in ['noMAP']:\n                    string = RL_name + ' excluded because the corresponding region is not mapped by the survey.'\n                else:\n                    string = RL_name + ' excluded because of: ' + CL['FLAG_INCLUDED']\n\n                Excluded.append(string)\n\n            mf = open(\"%s/Excluded.dat\" % outfolder, \"w\")\n            for ex in Excluded:\n                mf.write(ex + '\\n')\n                 \n        ClList = sorted(ClList, key=iom.Object_natural_keys)\n\n    \n        print('#=====  Last Step: Output is produced ====#'); smt(task='output') \n        \n        \"\"\" This is an intervening step: Update and ... the missing clusters, in the future this might done at the beginning at an first step \"\"\"\n        ClList = updateClusters_missingRegions(ClList, RegionFile)  # topfolder+RegionFile\n        \n\n        print('#=====  A: Pickle Objects ====#' )\n        iom.pickleObject(ClList, outfolder+'pickled/', 'ClList')\n        \n        print('#=====  B: Create the Survey and pickle it ====#')\n        cnt_levels = [9e-4, 1.8e-3, 3.6e-3, 7.2e-3, 1.44e-2]\n\n        synonyms = [('1RXS J060313.4+421231', '1RXS J06+42'),\n                    ('ACT-CLJ0102-4915', 'ACT-CLJ01-49'),\n                    ('CIZA J0649.3+1801', 'CIZA J0649'),  # CIZA J0649+18\n                    ('CIZA J0107.7+5408', 'CIZA J0107'),\n                    ('CIZA J2242.8+5301', 'CIZA J2243'),  # CIZA J2243+53\n                    ('MACS J0025-1222', 'MACS J0025'),\n                    ('MACS J0152.5-2852', 'MACS J0152'),  # MCS J0717+37\n                    ('MACS J0717.5+3745', 'MACS J0717'),  # MCS J0717+37\n                    ('MACS J1149.5+2223', 'MACS J1149'),  # J1149+22\n                    ('MACS J1752.0+4440', 'MACS J1752'),  # MCS J1752+44\n                    ('MACS J2243.3-0935', 'MACS J2243'),  # MCS J1752+44\n                    ('MaxBCG 138.91895+25.19876', 'MaxBCG 138+25'),\n                    ('MaxBCG 217.95869+13.53470', 'MaxBCG 217+13'),\n                    ('PSZ1 G004.5-19.5', 'PSZ1 G004'),  # PSZ1 G004-19\n                    ('PSZ1 G096.89+24.17', 'PSZ1 G097'),  # PSZ1 G097+24\n                    ('PSZ1 G108.18-11.53', 'PSZ1 G108'),  # PSZ1 G108-12\n                    ('PLCK G200.9-28.2', 'PLCK G200'),  # PSZ1 G108-12\n                    ('PLCK G287.0+32.9', 'PLCK G287'),  # PLCK G287+33\n                    ('RXC J0225.1-2928', 'RXC J0225'),\n                    ('RXC J1053.7+5452', 'RXC J1054'),  # RXC J1054+55\n                    ('RXC J1053.7+5452 ', 'RXC J1053'),  # RXC J1054+55\n                    ('RXC J1234.2+0947', 'RXC J1234'),  # RXC J1054+55\n                    ('RXC J1314.4-2515', 'RXC J1314'),  # RXC J1314-25\n                    ('ZwCl 0008+5215', 'ZwCl 0008'),  # ZwCl 0008+52\n                    ('ZwCl 1447.2+2619', 'ZwCl 1447'),  # ZwCl 0008+52\n                    ('ZwCl 2341+0000', 'ZwCl 2341'),  # ZwCl 2341+00\n                    ('[KMA2007] 217.95869+13.53470', 'KMA2007'),  # ZwCl 2341+00\n                    ]\n\n#        synonyms_lit = [('2017A&A...597A..15D', '2017A+A_deGasperin+Intema+'),\n#                        ('2017arXiv170801718K', '2017arXiv_Kale+Wik+')]\n        for GCl in ClList:\n\n            for syn in synonyms:\n                if GCl.name.replace('_', ' ') == syn[0] or GCl.name == syn[0]:\n                    print( '! Name replacement:', syn)\n                    GCl.name = syn[1]\n            GCl.name = GCl.name.replace('_', ' ')\n            GCl.updateInformation()\n\n        norm = cdb.norm('R200', Nexp=1)\n        Histo = cdb.Histogram2D(nbins=(64, 46), fromto=[[0, 2.*np.pi], [0, 1.5]], norm=norm)     # angle_projected(rad), D_proj(R200)\n\n        Survey = cbclass.Survey(ClList, survey, cnt_levels=cnt_levels, synonyms=synonyms, dinfo=dinfo_survey, hist_main=Histo, surshort=survey)  # 'NVSS' should be replaced with a real survey class\n        Survey.emi_max = 2e-2\n        Survey.scatterkwargs = {\"alpha\": 0.7, \"fmt\": \"o\", \"markersize\": 10}\n        Survey.histkwargs = {\"alpha\": 0.4}\n        Survey.relic_filter_kwargs = {\"Filter\": True, \"shape\": False, \"minrms\": 8}\n        iom.pickleObject(Survey, outfolder+'/pickled/', 'Survey')\n\n        for GCl in Survey.GCls:\n            print(GCl.name, GCl.status)\n\n    smt(forced=True)\n    return True\n\n\nif __name__ == \"__main__\":\n    \n    parser = argparse.ArgumentParser(description='Extracts survey relics from an real world survey')\n    parser.add_argument('-surveys', dest='surveys', nargs='+', action='store', default=['NVSS'],  type=str, help='Survey names that are to be used')\n    parser.add_argument('-infolder', dest='infolder', action='store', default='', type=str, help='filepath for data arrays to be loaded (folder of NVSS paths etc.)')\n    parser.add_argument('-outputfolder', dest='outputfolder', action='store', default='/data/ClusterBuster-Output/', type=str, help='filepath for data arrays to store')\n    args = parser.parse_args()\n\n    survey_run(surveys=args.surveys, infolder=args.infolder, outfoldertop=args.outputfolder, plot=False)\n", "meta": {"hexsha": "23b0d43238213dd3bd68fe03304616a2d1773629", "size": 25435, "ext": "py", "lang": "Python", "max_stars_repo_path": "surveyreal/runsurvey.py", "max_stars_repo_name": "jakgel/clusterbuster", "max_stars_repo_head_hexsha": "d79400a0faf43dece457d99b024b955aef544fc2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-09-10T14:06:45.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-10T14:06:45.000Z", "max_issues_repo_path": "surveyreal/runsurvey.py", "max_issues_repo_name": "jakgel/clusterbuster", "max_issues_repo_head_hexsha": "d79400a0faf43dece457d99b024b955aef544fc2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "surveyreal/runsurvey.py", "max_forks_repo_name": "jakgel/clusterbuster", "max_forks_repo_head_hexsha": "d79400a0faf43dece457d99b024b955aef544fc2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.322851153, "max_line_length": 207, "alphanum_fraction": 0.5045803027, "include": true, "reason": "import numpy,from astropy", "num_tokens": 6528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.37387580881868493, "lm_q1q2_score": 0.18839832707528614}}
{"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nfrom math import sqrt\nfrom random import randint\nfrom scipy.optimize import minimize\nfrom pyswarm import pso\n\n\nclass hidr(object):\n\n    # Dados de cadastro das usinas hidreletricas (presentes no HIDR.DAT)\n    Codigo = None           # Codigo da UHE\n    Nome = None             # Nome da UHE\n    Posto = None            # Numero do Posto\n    Bdh = None              # Desvio - Nao sei qual e esta informacao ??????\n    Sist = None             # Submercado\n    Empr = None             # Codigo da empresa\n    Jusante = None          # Codigo de Jusante\n    Desvio = None           # Desvio - Nao sei qual e esta informacao ??????\n    VolMin = None           # Volume Minimo\n    VolMax = None           # Volume Maximo\n    VolVert = None          # Volume Vertimento\n    VolMinDesv = None       # Volume Minimo para Desvio\n    CotaMin = None          # Cota Minima\n    CotaMax = None          # Cota Maxima\n    PolCotaVol = None       # Polinomio Cota-Volume\n    PolCotaArea = None      # Polinomio Cata-Area\n    CoefEvap = None         # Coeficientes de Evaporacao\n    NumConjMaq = None       # Numero de Conjuntos de Maquinas\n    MaqporConj = None       # Numero de Maquinas por Conjunto\n    PEfporConj = None       # POtencia Efetiva por Maquina do Conjunto\n\n    CF_HBQT = None          # Nao sei qual e esta informacao ??????\n    CF_HBQG = None          # Nao sei qual e esta informacao ??????\n    CF_HBPT = None          # Nao sei qual e esta informacao ??????\n\n    AltEfetConj = None      # Altura de Queda Efetiva do Conjunto\n    VazEfetConj = None      # Vazao Efetiva do Conjunto\n    ProdEsp = None          # Produtibilidade Especifica\n    PerdaHid = None         # Perda Hidraulica\n    NumPolVNJ = None        # Numero de Polinomios Vazao Nivel Jusante\n\n    PolVazNivJus = None     # Polinomios Vazao Nivel Jusante\n\n    CotaRefNivelJus = None  # Cota Referencia Nivel de Jusante\n    CFMed = None            # Cota Media do Canal de Fuga\n    InfCanalFuga = None     # Informacao Canal de Fuga - Nao sei qual e esta informacao ??????\n    FatorCargaMax = None    # Fator de Caga Maximo - Nao sei qual e esta informacao ?????????\n    FatorCargaMin = None    # Fator de Caga Minimo - Nao sei qual e esta informacao ?????????\n    VazMin = None           # Vazao Minima Obrigatoria\n    UnidBase = None         # Numero de Unidades de Base\n    TipoTurb = None         # Tipo de Turbina Hidraulica\n    Repres_Conj = None      # Representacao Conjunto de Maquina - Nao sei qual e esta informacao ?????\n    TEIFH = None            # Taxa Equivalente de Indisponibilidade Forcada Hidraulica\n    IP = None               # Indisponibilidade Programada\n    TipoPerda = None        # Tipo Perda Hidraulica\n    Data = None             # Nao sei qual e esta informacao ??????\n    Observ = None           # Observacao\n    VolRef = None           # Volume de Referencia\n    TipoReg = None          # Tipo de Regulacao\n\n    # Dados Adicionais Especificados no arquivo de configuracao hidraulica (CONFHD)\n    Ree = None\n    Status = None\n    VolIni = None\n    Modif = None\n    AnoI = None\n    AnoF = None\n\n    # Dados Adicinais Calculados para as Usinas pertecentes a configuracao hidraulica (CONFHD)\n    VolUtil = None\n    VazEfet = None\n    PotEfet = None\n    Ro65 = None             # PDTMED (NEWAVE) - PROD. ASSOCIADA A ALTURA CORRESPONDENTE A 65% DO V.U.\n    Ro50 = None\n    RoMax = None            # PDTMAX (NEWAVE) - PROD. ASSOCIADA A ALTURA MAXIMA\n    RoMin = None            # PDTMIN (NEWAVE) - PROD. ASSOCIADA A ALTURA MINIMA\n    RoEquiv = None          # PRODT (NEWAVE) - PROD. EQUIVALENTE ( DO VOL. MINIMO AO VOL. MAXIMO )\n    RoEquiv65 = None        # PRODTM (NEWAVE) - PROD. EQUIVALENTE ( DO VOL. MINIMO A 65% DO V.U. )\n    Engolimento = None\n    RoAcum = None           # PDTARM (NEWAVE) - PROD. ACUM. PARA CALCULO DA ENERGIA ARMAZENADA\n    RoAcum65 = None         # PDAMED (NEWAVE) - PROD. ACUM. PARA CALCULO DA ENERGIA ARMAZENADA CORRESPONDENTE A 65% DO V.U.\n    RoAcumMax = None        # PDCMAX e PDVMAX (NEWAVE) - PROD. ACUM.\n    RoAcumMed = None        # PDTCON, PDCMED e PDVMED (NEWAVE) - PROD. ACUM.\n    RoAcumMin = None        # PDCMIN e PDVMIN (NEWAVE) - PROD. ACUM.\n\n    RoAcum_A_Ree = None\n    RoAcum_B_Ree = None\n    RoAcum_C_Ree = None\n    RoAcum_A_Sist = None\n    RoAcum_B_Sist = None\n    RoAcum_C_Sist = None\n\n    RoAcumEntreResRee = None\n    RoAcumEntreResSist = None\n\n    # Vazoes Naturais, Incrementais e Par(p)\n    Vazoes = None       # Historico de Vazoes naturais (imes, ilag)\n    FAC = None          # Funcao de Autocorrelacao (imes, ilag)\n    FACP = None         # Funcao de Autocorrelacao Parcial (imes, ilag)\n    CoefParp = None     # Coeficientes do Modelo par(p) (imes,ilag)\n    CoefIndParp  = None     # Coeficientes independentes do Modelo par(p) (imes) - Aditivo = 0 - Multiplicativo > 0\n    Ordem = None        # Ordem do modelo par(p) para todos os meses (mes)\n\n    # Parametros da usina Dependentes do Tempo - Especificados (MODIF.DAT)\n    VolMinT = None     # Volume Mínimo Operativo (pode variar mes a mes)\n    VolMaxT = None     # Volume Maximo Operativo (pode variar mes a mes)\n    VolMinP = None     # Volume Mínimo com adocao de penalidade (pode variar mes a mes)\n    VazMinT = None     # Vazao Minima pode variar mes a mes\n    CFugaT  = None     # Cota do Canal de Fuga (pode varia mes a mes)\n\n    # Parametros relativos a expansao hidrica que variam no tempo para usinas 'EE' e 'NE' (EXPH)\n    StatusVolMorto = None       # Status do Volume Morto - 0: Nao Comecou Encher - 1: Enchendo - 2: Cheio\n    VolMortoTempo = None        # Evolucao do Volume Minimo da Usina\n    StatusMotoriz  = None       # Status da Motorizacao  - 0: Nao Comecou Motorizar - 1: Motorizando - 3: Motorizada\n    UnidadesTempo = None        # Numero de Unidades em cada mes\n    EngolTempo = None           # Evolucao do Engolimento Maximo da Usina\n    PotenciaTempo = None        # Evolucao da Potencia Instalada da Usina\n\n    ##########################################################################################################\n    # Graficos Diversos\n    ##########################################################################################################\n\n    # Plota Polinomio Cota-Volume\n    def PlotaPCV(self):\n        if self.VolMin == 0:\n            return\n\n        if (self.VolMin == self.VolMax):\n            volumes = np.linspace(self.VolMin - 1,self.VolMax + 1, 100)\n        else:\n            volumes = np.linspace(self.VolMin,self.VolMax,100)\n        a = self.PolCotaVol[0]\n        b = self.PolCotaVol[1]\n        c = self.PolCotaVol[2]\n        d = self.PolCotaVol[3]\n        e = self.PolCotaVol[4]\n        cota = a + b*volumes + c*volumes**2 + d*volumes**3 + e*volumes**4\n        cota.shape = volumes.shape\n        plt.plot(volumes, cota, 'b-', lw=3)\n\n        plt.xlabel('Volume do Reservatorio (hm^3)', fontsize=16)\n        titulo = 'Polinomio Cota-Volume da Usina ' + self.Nome\n        plt.title(titulo, fontsize=16)\n        plt.ylabel('Cota em Metros', fontsize=16)\n        plt.xlim(volumes[0], volumes[99])\n        if ( cota[0] == cota[99]):\n            plt.ylim(cota[0]-1, cota[99]+1)\n        else:\n            plt.ylim(cota[0], cota[99])\n        plt.show()\n\n    # Plota Polinomio Cota-Area\n    def PlotaPCA(self):\n        if self.VolMin == 0:\n            return\n\n        if (self.CotaMax == self.CotaMin):\n            cotas = np.linspace(self.CotaMin - 1,self.CotaMax + 1, 100)\n        else:\n            cotas = np.linspace(self.CotaMin,self.CotaMax,100)\n        a = self.PolCotaArea[0]\n        b = self.PolCotaArea[1]\n        c = self.PolCotaArea[2]\n        d = self.PolCotaArea[3]\n        e = self.PolCotaArea[4]\n        areas = a + b*cotas + c*cotas**2 + d*cotas**3 + e*cotas**4\n        areas.shape = cotas.shape\n        plt.plot(cotas, areas, 'b-', lw=3)\n\n        plt.xlabel('Cota do Reservatorio (em metros)', fontsize=16)\n        titulo = 'Polinomio Cota-Area da Usina ' + self.Nome\n        plt.title(titulo, fontsize=16)\n        plt.ylabel('Area Superficia em km^2', fontsize=16)\n        plt.xlim(cotas[0], cotas[99])\n        if ( areas[0] == areas[99]):\n            plt.ylim(areas[0]-1, areas[99]+1)\n        else:\n            plt.ylim(areas[0], areas[99])\n        plt.show()\n\n    # Plota Curva Colina\n    def PlotaColina(self):\n        if self.VolMin == 0:\n            return\n\n        if (self.VolMin == self.VolMax):\n            volumes = np.linspace(self.VolMin - 1,self.VolMax + 1, 100)\n        else:\n            volumes = np.linspace(self.VolMin,self.VolMax,100)\n\n        a = self.PolCotaVol[0]\n        b = self.PolCotaVol[1]\n        c = self.PolCotaVol[2]\n        d = self.PolCotaVol[3]\n        e = self.PolCotaVol[4]\n\n        cotamont = a + b*volumes + c*volumes**2 + d*volumes**3 + e*volumes**4\n        cotamont.shape = volumes.shape\n\n        qdef = np.linspace(self.VazMin, 5*self.Engolimento, 100)\n\n        a = self.PolVazNivJus[0][0]\n        b = self.PolVazNivJus[0][1]\n        c = self.PolVazNivJus[0][2]\n        d = self.PolVazNivJus[0][3]\n        e = self.PolVazNivJus[0][4]\n\n        cotajus = a + b*qdef + c*qdef**2 + d*qdef**3 + e*qdef**4\n        cotajus.shape = qdef.shape\n\n        xGrid, yGrid = np.meshgrid(cotamont, cotajus)\n\n        z = self.ProdEsp * ( xGrid - yGrid )\n\n        fig = plt.figure()\n        ax = fig.gca(projection='3d')\n\n        surf = ax.plot_surface(qdef, volumes,z, rcount=100, ccount = 100, cmap=plt.cm.coolwarm,\n                       linewidth=0, antialiased=False)\n\n        plt.xlabel('Vazão Defluente em m^3/s', fontsize=12)\n        titulo = 'Produtibilidade da Usina ' + self.Nome\n        plt.title(titulo, fontsize=16)\n        plt.ylabel('Volume Armazenado em hm^3', fontsize=12)\n        fig.colorbar(surf, shrink=0.5, aspect=5)\n\n        plt.show()\n\n\n    def PlotaProdutibs(self, iano, imes):\n        x_axis = np.arange(1,6)\n        y_axis = [ self.RoEquiv[iano][imes], self.RoMin[iano][imes], self.Ro50[iano][imes], self.Ro65[iano][imes], self.RoMax[iano][imes] ]\n        fig, ax = plt.subplots()\n        a, b, c, d, e = plt.bar(x_axis, y_axis)\n        a.set_facecolor('r')\n        b.set_facecolor('g')\n        c.set_facecolor('b')\n        d.set_facecolor('y')\n        e.set_facecolor('m')\n        ax.set_xticks(x_axis)\n        ax.set_xticklabels(['Equiv', 'Min', '50%', '65%', 'Max'])\n        titulo = 'Produtibilidades da Usina ' + self.Nome\n        plt.title(titulo, fontsize=16)\n        plt.xlabel('Tipo de Produtibilidade', fontsize=16)\n        plt.ylabel('Produtibilidade', fontsize=16)\n        plt.show()\n\n    def PlotaVazoes(self):\n        x_axis = np.arange(1,13)\n        plt.plot(x_axis,self.Vazoes.transpose(),'c-')\n        media = np.mean(self.Vazoes, axis=0)\n        plt.plot(x_axis,media,'r-',lw=3)\n        desvio = np.nanstd(self.Vazoes, axis=0)\n        plt.plot(x_axis,media+desvio,'r-.',lw=2)\n        plt.plot(x_axis,media-desvio,'r-.',lw=2)\n        ultimo = len(self.Vazoes)-1\n        plt.plot(x_axis,self.Vazoes[:][ultimo],'b-')\n        titulo = 'Historico de Vazoes da Usina ' + self.Nome\n        plt.title(titulo, fontsize=16)\n        plt.xlabel('Mes do Ano', fontsize=16)\n        plt.ylabel('Vazao', fontsize=16)\n        plt.show()\n\n    def PlotaVolume(self):\n        nanos = len(self.VolMinT)\n\n        fig = plt.figure()\n        ax = plt.subplot(111)\n\n\n        x_axis = np.arange(1,nanos*12+1)\n        ax.plot(x_axis,self.VolMinT.reshape(nanos*12),'g-.',lw=2, label = 'Vol.Min.Operat.')\n        ax.plot(x_axis,self.VolMaxT.reshape(nanos*12),'g-.',lw=2, label = 'Vol.Max.Operat.')\n        ax.plot(x_axis,self.VolMax*np.ones(nanos*12),'b-',lw=3,   label = 'Vol.Minimo Real')\n        ax.plot(x_axis,self.VolMin*np.ones(nanos*12),'b-',lw=3,   label = 'Vol.Maximo Real')\n        ax.plot(x_axis,self.VolMinP.reshape(nanos*12),'b-.',lw=2, label = 'Vol.Min.com Pen.')\n\n        plt.fill_between(x_axis,self.VolMinT.reshape(nanos*12), self.VolMaxT.reshape(nanos*12), facecolor='g', alpha=0.1)\n\n        titulo = 'Evolucao dos Volumes da Usina \\n' + self.Nome\n        plt.title(titulo, fontsize=16)\n        plt.xlabel('Mes de Estudo', fontsize=16)\n        plt.ylabel('Volume em hm^3', fontsize=16)\n\n        box = ax.get_position()\n\n        ax.set_position([ box.x0, box.y0, box.width*0.7, box.height] )\n\n        ax.legend(loc='center left', shadow=True, fontsize=12, bbox_to_anchor=(1, 0.5))\n\n        plt.show()\n\n    def PlotaVazMin(self):\n        nanos = len(self.VazMinT)\n\n        fig = plt.figure()\n        ax = plt.subplot(111)\n\n        x_axis = np.arange(1,nanos*12+1)\n        ax.plot(x_axis,self.VazMinT.reshape(nanos*12),'g-.',lw=2, label='Vaz.Min.Operat.')\n        ax.plot(x_axis,self.VazMin*np.ones(nanos*12),'b-',lw=3,   label='Vaz.Min.Cadastro')\n\n        titulo = 'Evolucao da Vazao Minima da Usina \\n' + self.Nome\n        plt.title(titulo, fontsize=16)\n        plt.xlabel('Mes de Estudo', fontsize=16)\n        plt.ylabel('Vazao Minima em m^3', fontsize=16)\n\n        box = ax.get_position()\n\n        ax.set_position([ box.x0, box.y0, box.width*0.7, box.height] )\n\n        ax.legend(loc='center left', shadow=True, fontsize=12, bbox_to_anchor=(1, 0.5))\n\n        plt.show()\n\n    def PlotaVolMorto(self):\n\n        if self.Status == 'EX':\n            print('Grafico de Volume Morto nao impresso, pois ', self.Nome, 'e uma usina existente')\n            return\n\n        nanos = len(self.VolMortoTempo)\n\n        nmeses = np.count_nonzero(self.VolMortoTempo)\n\n        legenda = str(nmeses) + ' Meses'\n\n        ax = plt.subplot(111)\n\n        x_axis = np.arange(1,nanos*12+1)\n        p1 = ax.plot(x_axis,self.VolMortoTempo.reshape(nanos*12),'g-.',lw=2, label = legenda )\n\n        titulo = 'Enchimento do Volume Morto da Usina \\n' + self.Nome\n        plt.title(titulo, fontsize=16)\n        plt.xlabel('Mes de Estudo', fontsize=16)\n        plt.ylabel('Volume Morto em hm^3', fontsize=16)\n\n        plt.legend(fontsize=12)\n\n        np.count_nonzero(self.VolMortoTempo)\n\n        plt.show()\n\n    def PlotaPotencia(self):\n\n        nanos = len(self.PotenciaTempo)\n\n        ax = plt.subplot(111)\n\n        x_axis = np.arange(1, nanos * 12 + 1)\n        p1 = ax.plot(x_axis, self.PotenciaTempo.reshape(nanos * 12), 'g-.', lw=2)\n\n        titulo = 'Evolucao da Potencia Efetiva da Usina \\n' + self.Nome\n        plt.title(titulo, fontsize=16)\n        plt.xlabel('Mes de Estudo', fontsize=16)\n        plt.ylabel('Potencia Efetiva em MW', fontsize=16)\n\n        plt.show()\n\n    def PlotaParp(self, mes):\n\n        ordmax = len(self.CoefParp[0])\n        nanos = len(self.Vazoes) - 1\n\n        if mes == 0:\n            str_mes = 'January'\n        elif mes == 1:\n            str_mes = 'Fevereiro'\n        elif mes == 2:\n            str_mes = 'Marco'\n        elif mes == 3:\n            str_mes = 'Abril'\n        elif mes == 4:\n            str_mes = 'Maio'\n        elif mes == 5:\n            str_mes = 'Junho'\n        elif mes == 6:\n            str_mes = 'Julho'\n        elif mes == 7:\n            str_mes = 'Agosto'\n        elif mes == 8:\n            str_mes = 'Setembro'\n        elif mes == 9:\n            str_mes = 'Outubro'\n        elif mes == 10:\n            str_mes = 'Novembro'\n        else:\n            str_mes = 'Dezembro'\n\n        IC = 1.96/sqrt(nanos-1)\n\n        cores = []\n        limitesup = []\n        limiteinf = []\n        for elemento in self.FACP[mes][1:ordmax+1]:\n            limitesup.append(IC)\n            limiteinf.append(-IC)\n            if elemento > IC or elemento < -IC:\n                cores.append('r')\n            else:\n                cores.append('b')\n\n        f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\n        barWidth = 0.40\n\n\n        titulo = 'FAC e FACP of ' + str_mes + ' - UHE ' + self.Nome\n        f.canvas.set_window_title(titulo)\n\n        ax1.bar(np.arange(1,ordmax+1), self.FAC[mes][1:ordmax+1], barWidth, align='center')\n        ax2.bar(np.arange(1,ordmax+1), self.FACP[mes][1:ordmax+1], barWidth, align='center', color = cores)\n        ax2.plot(np.arange(1,ordmax+1), limitesup, 'm--', lw=1)\n        ax2.plot(np.arange(1,ordmax+1), limiteinf, 'm--', lw=1)\n\n        ax1.set_xticks(np.arange(1,ordmax+1))\n        ax2.set_xticks(np.arange(1,ordmax+1))\n        tituloFAC =  'FAC - Month: ' + str_mes + '\\n of UHE ' + self.Nome\n        tituloFACP = 'FACP - Month ' + str_mes +  '\\n of UHE ' + self.Nome\n        ax1.set_title(tituloFAC,  fontsize = 13)\n        ax2.set_title(tituloFACP, fontsize =13)\n        #ax1.xlabel('Lag')\n        #ax2.xlabel('Lag')\n        #ax1.ylabel('Autocorrelacao e Autocorrelacao Parcial')\n\n        plt.show()\n\n\n    ##########################################################################################################\n    # Calcula Parametros das Usinas\n    ##########################################################################################################\n\n    def CalcVolUtil(self):     # Calcula Volume Util da Usina\n        if self.TipoReg == b'M':\n            self.VolUtil = self.VolMax - self.VolMin\n        else:\n            self.VolUtil = float(0)\n            self.VolMin = self.VolMax\n\n    def CalcPotEfetiva(self):     # Calcula Potencia Efetiva da Usina\n        a = np.array(self.MaqporConj)\n        b = np.array(self.PEfporConj)\n        self.PotEfet = np.vdot(a, b)\n\n    def CalcVazEfetiva(self):      # Calcula Vazao Efetiva da Usina\n        a = np.array(self.MaqporConj)\n        b = np.array(self.VazEfetConj)\n        self.VazEfet = np.vdot(a, b)\n\n    def CalcEngolMaximo(self):    # Estima Engolimento Maximo da Usina\n\n        def CalcEngol(self, ql):\n            engol = 0.\n            for i in range(5):   # Varre Conjuntos de Maquinas\n                if self.MaqporConj[i] > 0:\n                    if ql < self.AltEfetConj[i]:\n                        if self.TipoTurb == 1 or self.TipoTurb == 3:\n                            alpha = 0.5\n                        else:\n                            alpha = 0.2\n                    else:\n                        alpha = -1\n                    if self.AltEfetConj[i] != 0:\n                        engol = engol + self.MaqporConj[i]*self.VazEfetConj[i]*((ql/self.AltEfetConj[i])**alpha)\n            return engol\n\n        a = self.PolCotaVol[0]\n        b = self.PolCotaVol[1]\n        c = self.PolCotaVol[2]\n        d = self.PolCotaVol[3]\n        e = self.PolCotaVol[4]\n\n        # Calcula Engolimento a 65% do Volume Util\n        volume = self.VolMin + 0.65*self.VolUtil\n        cota = a + b*volume + c*volume**2 + d*volume**3 + e*volume**4\n        queda65 = cota - self.CFMed\n        engol65 = CalcEngol(self, queda65)\n\n        # Calcula Engolimento a 50% do Volume Util\n        volume = self.VolMin + 0.50*self.VolUtil\n        cota = a + b*volume + c*volume**2 + d*volume**3 + e*volume**4\n        queda50 = cota - self.CFMed\n        engol50 = CalcEngol(self, queda50)\n\n        # Calcula Engolimento Associada ao Volume Maximo\n        volume = self.VolMax\n        cota = a + b*volume + c*volume**2 + d*volume**3 + e*volume**4\n        quedaMax = cota - self.CFMed\n        engolMax = CalcEngol(self, quedaMax)\n\n        # Calcula Engolimento Associada ao Volume Minimo\n        volume = self.VolMin\n        cota = a + b*volume + c*volume**2 + d*volume**3 + e*volume**4\n        quedaMin = cota - self.CFMed\n        engolMin = CalcEngol(self, quedaMin)\n\n        # Calcula Engolimento Associado a Altura Equivalente\n        if ( self.VolUtil > 0):\n            cota = 0\n            for i in range(5):\n                cota = cota + self.PolCotaVol[i] * (self.VolMax**(i+1)) / (i+1)\n                cota = cota - self.PolCotaVol[i] * (self.VolMin**(i+1)) / (i+1)\n            cota = cota / self.VolUtil\n        quedaEquiv = cota - self.CFMed\n        engolEquiv = CalcEngol(self, quedaEquiv)\n\n        self.Engolimento = (engol50+engol65+engolEquiv+engolMax+engolMin)/5\n\n        return\n\n    def CalcProdutibs(self, nanos):       # Calcula Produtibilidades Associadas aa diversos volumes\n\n        self.Ro65       = np.zeros( (nanos,12), 'd' )\n        self.Ro50       = np.zeros( (nanos,12), 'd' )\n        self.RoEquiv    = np.zeros( (nanos,12), 'd' )\n        self.RoEquiv65  = np.zeros( (nanos,12), 'd' )\n        self.RoMin      = np.zeros( (nanos,12), 'd' )\n        self.RoMax      = np.zeros( (nanos,12), 'd' )\n\n        a = self.PolCotaVol[0]\n        b = self.PolCotaVol[1]\n        c = self.PolCotaVol[2]\n        d = self.PolCotaVol[3]\n        e = self.PolCotaVol[4]\n\n        # Calcula Produtibilidade Associada a 65% do Volume Util\n        volume = self.VolMin + 0.65*self.VolUtil\n        cota = a + b*volume + c*volume**2 + d*volume**3 + e*volume**4\n        for iano in range(nanos):\n            for imes in range(12):\n                cfuga = self.CFugaT[iano][imes]\n                if self.TipoPerda == 2:\n                    self.Ro65[iano][imes] = self.ProdEsp * (cota - cfuga - self.PerdaHid)\n                else:\n                    self.Ro65[iano][imes] = self.ProdEsp * (cota - cfuga)*(1. - self.PerdaHid/100)\n\n        # Calcula Produtibilidade Associada a 50% do Volume Util\n        volume = self.VolMin + 0.50*self.VolUtil\n        cota = a + b*volume + c*volume**2 + d*volume**3 + e*volume**4\n        for iano in range(nanos):\n            for imes in range(12):\n                cfuga = self.CFugaT[iano][imes]\n                if self.TipoPerda == 2:\n                    self.Ro50[iano][imes] = self.ProdEsp * (cota - cfuga - self.PerdaHid)\n                else:\n                    self.Ro50[iano][imes] = self.ProdEsp * (cota - cfuga)*(1. - self.PerdaHid/100)\n\n        # Calcula Produtibilidade Associada ao Volume Maximo\n        volume = self.VolMax\n        cota = a + b*volume + c*volume**2 + d*volume**3 + e*volume**4\n        for iano in range(nanos):\n            for imes in range(12):\n                cfuga = self.CFugaT[iano][imes]\n                if self.TipoPerda == 2:\n                    self.RoMax[iano][imes] = self.ProdEsp * (cota - cfuga - self.PerdaHid)\n                else:\n                    self.RoMax[iano][imes] = self.ProdEsp * (cota - cfuga)*(1. - self.PerdaHid/100)\n\n        # Calcula Produtibilidade Associada ao Volume Minimo\n        volume = self.VolMin\n        cota = a + b*volume + c*volume**2 + d*volume**3 + e*volume**4\n        for iano in range(nanos):\n            for imes in range(12):\n                cfuga = self.CFugaT[iano][imes]\n                if self.TipoPerda == 2:\n                    self.RoMin[iano][imes] = self.ProdEsp * (cota - cfuga - self.PerdaHid)\n                else:\n                    self.RoMin[iano][imes] = self.ProdEsp * (cota - cfuga)*(1. - self.PerdaHid/100)\n\n        # Calcula Produtibilidade Equivalente\n        if ( self.VolUtil > 0):\n            cota = 0\n            cota65 = 0\n            Vol65 = self.VolMin + 0.65*self.VolUtil\n            for i in range(5):\n                cota = cota + self.PolCotaVol[i] * (self.VolMax**(i+1)) / (i+1)\n                cota = cota - self.PolCotaVol[i] * (self.VolMin**(i+1)) / (i+1)\n                cota65 = cota65 + self.PolCotaVol[i] * (Vol65**(i+1)) / (i+1)\n                cota65 = cota65 - self.PolCotaVol[i] * (self.VolMin**(i+1)) / (i+1)\n            cota = cota / self.VolUtil\n            cota65 = cota65 / (Vol65 - self.VolMin)\n        else:\n            cota65 = cota\n        for iano in range(nanos):\n            for imes in range(12):\n                cfuga = self.CFugaT[iano][imes]\n                if self.TipoPerda == 2:\n                    self.RoEquiv[iano][imes]   = self.ProdEsp * (cota   - cfuga - self.PerdaHid)\n                    self.RoEquiv65[iano][imes] = self.ProdEsp * (cota65 - cfuga - self.PerdaHid)\n                else:\n                    self.RoEquiv[iano][imes]   = self.ProdEsp * (cota   - cfuga)*(1. - self.PerdaHid/100)\n                    self.RoEquiv65[iano][imes] = self.ProdEsp * (cota65 - cfuga)*(1. - self.PerdaHid/100)\n        return\n\n    # Calcula Vazao Incremental\n    def QInc(self, usinas, iano, imes):\n\n        nanos_hist = len(self.Vazoes)\n\n        def Montante(usinas, usina, iano, imes):\n            for iusi in usinas:\n                if iusi.Jusante == usina.Codigo:\n                    if iusi.StatusVolMorto[iano][imes] == 2:\n                        yield iusi\n                    else:\n                        yield from Montante(usinas, iusi, iano, imes)\n\n        if self.StatusVolMorto[iano][imes] != 2:\n            print ('Erro: Tentativa de calculo de Incremental para usina (', self.Nome, ') fora de operacao no mes ', imes, ' e ano ', iano)\n            return 0\n        else:\n            Incremental = self.Vazoes[0:nanos_hist,imes]\n            for iusina in Montante(usinas, self, iano, imes):\n                Incremental = Incremental - iusina.Vazoes[0:nanos_hist,imes]\n\n        if np.min(Incremental) < 0:\n            contador = 0\n            for i in range(nanos_hist):\n                if Incremental[i] < 0:\n                    Incremental[i] = 0\n                    contador = contador + 1\n            return Incremental\n        else:\n            return Incremental\n\n    # Calcula vazao incremental entre a usina e todos os reservatorios a montante\n    def QIncEntreRes(self, usinas, ianoconf, imesconf):\n\n        nanos_hist = len(self.Vazoes)\n\n        def Montante(usinas, usina, iano, imes):\n            for iusi in usinas:\n                if iusi.Jusante == usina.Codigo:\n                    if iusi.StatusVolMorto[iano][imes] == 2:\n                        if iusi.VolUtil > 0:\n                            yield iusi\n                        else:\n                            yield from Montante(usinas, iusi, iano, imes)\n                    else:\n                        yield from Montante(usinas, iusi, iano, imes)\n\n        if self.StatusVolMorto[ianoconf][imesconf] != 2:\n            print ('Erro: Tentativa de calculo de Incremental para usina (', self.Nome, ') fora de operacao no mes ', imesconf, ' e ano ', ianoconf)\n            return 0\n        else:\n            Incremental = np.zeros( (nanos_hist,1) , 'd')\n            Incremental = self.Vazoes[0:nanos_hist,imesconf]\n            for iusina in Montante(usinas, self, ianoconf, imesconf):\n                Incremental = Incremental - iusina.Vazoes[0:nanos_hist,imesconf]\n\n        if np.min(Incremental) < 0:\n            contador = 0\n            for i in range(nanos_hist):\n                if Incremental[i] < 0:\n                    #Incremental[i] = 0\n                    contador = contador + 1\n            #print ('Vazao Incremental da Usina ', self.Nome, 'menor que zero no mes ', imesconf, ' e ano ', ianoconf, 'Quantidade:', contador )\n            return Incremental\n        else:\n            return Incremental\n\n    def ProdAcum(self, usinas):\n\n        def Cascata(usinas,iano,imes):\n            current = self\n            if current.StatusVolMorto[iano][imes] == 2:\n                yield current\n            while current.Jusante != 0:\n                for iusi in usinas:\n                    if iusi.Codigo == current.Jusante:\n                        if iusi.StatusVolMorto[iano][imes] == 2:\n                            yield iusi\n                        current = iusi\n                        break\n\n        nanos = len(self.StatusVolMorto)\n\n        self.RoAcum_A_Ree = np.zeros( (nanos,12), 'd')\n        self.RoAcum_B_Ree = np.zeros( (nanos,12), 'd')\n        self.RoAcum_C_Ree = np.zeros( (nanos,12), 'd')\n\n        self.RoAcum_A_Sist = np.zeros( (nanos,12), 'd')\n        self.RoAcum_B_Sist = np.zeros( (nanos,12), 'd')\n        self.RoAcum_C_Sist = np.zeros( (nanos,12), 'd')\n\n        self.RoAcum    = np.zeros( (nanos,12), 'd')\n        self.RoAcum65  = np.zeros( (nanos,12), 'd' )\n        self.RoAcumMax = np.zeros( (nanos,12), 'd' )\n        self.RoAcumMed = np.zeros( (nanos,12), 'd' )\n        self.RoAcumMin = np.zeros( (nanos,12), 'd' )\n\n        for iano in range(nanos):\n            for imes in range(12):\n                trocouRee = 0\n                trocouSist = 0\n                FioRee = True\n                FioSist = True\n\n                for iusina in Cascata(usinas, iano, imes):\n                    produtib    = iusina.RoEquiv[iano][imes]\n                    produtib65  = iusina.RoEquiv65[iano][imes]\n                    produtibMax = iusina.RoMax[iano][imes]\n                    produtibMed = iusina.Ro65[iano][imes]\n                    produtibMin = iusina.RoMin[iano][imes]\n                    if iusina.StatusMotoriz[iano][imes] == 2:\n                        self.RoAcum[iano][imes]    = self.RoAcum[iano][imes]    + produtib\n                        self.RoAcum65[iano][imes]  = self.RoAcum65[iano][imes]  + produtib65\n                        self.RoAcumMax[iano][imes] = self.RoAcumMax[iano][imes] + produtibMax\n                        self.RoAcumMed[iano][imes] = self.RoAcumMed[iano][imes] + produtibMed\n                        self.RoAcumMin[iano][imes] = self.RoAcumMin[iano][imes] + produtibMin\n                    if iusina.Sist != self.Sist:\n                        trocouSist = trocouSist+ 1\n                    if iusina.Ree != self.Ree:\n                        trocouRee = trocouRee + 1\n\n                    if trocouRee == 0:\n                        if iusina.StatusMotoriz[iano][imes] == 2:\n                            self.RoAcum_A_Ree[iano][imes] = self.RoAcum_A_Ree[iano][imes] + produtib\n                    else:\n                        if iusina.VolUtil > 0:\n                            FioRee = False\n                        if FioRee:\n                            if iusina.StatusMotoriz[iano][imes] == 2:\n                                self.RoAcum_B_Ree[iano][imes] = self.RoAcum_B_Ree[iano][imes] + produtib\n                        else:\n                            if iusina.StatusMotoriz[iano][imes] == 2:\n                                self.RoAcum_C_Ree[iano][imes] = self.RoAcum_C_Ree[iano][imes] + produtib\n\n                    if trocouSist == 0:\n                        if iusina.StatusMotoriz[iano][imes] == 2:\n                            self.RoAcum_A_Sist[iano][imes] = self.RoAcum_A_Sist[iano][imes] + produtib\n                    else:\n                        if iusina.VolUtil > 0:\n                            FioSist = False\n                        if FioSist:\n                            if iusina.StatusMotoriz[iano][imes] == 2:\n                                self.RoAcum_B_Sist[iano][imes] = self.RoAcum_B_Sist[iano][imes] + produtib\n                        else:\n                            if iusina.StatusMotoriz[iano][imes] == 2:\n                                self.RoAcum_C_Sist[iano][imes] = self.RoAcum_C_Sist[iano][imes] + produtib\n\n    def ProdAcumEntreResRee(self, iano, imes, usinas):\n         if self.Jusante == 0:\n             return 0\n         for iusina in usinas:\n             if iusina.Codigo == self.Jusante:\n                 if iusina.VolUtil != 0:\n                     return 0.\n                 elif self.Ree != iusina.Ree:\n                     return 0.\n                 elif iusina.StatusMotoriz[iano][imes] == 2:\n                     return iusina.RoEquiv[iano][imes] + iusina.ProdAcumEntreResRee(iano, imes, usinas)\n                 else:\n                     return iusina.ProdAcumEntreResRee(iano, imes, usinas)\n                 break\n    #\n    # def ProdAcumEntreResSist(self, iano, imes, usinas):\n    #     if self.Jusante == 0:\n    #         return 0\n    #     for iusina in usinas:\n    #         if iusina.Codigo == self.Jusante:\n    #             if iusina.VolUtil != 0:\n    #                 return 0.\n    #             elif self.Sist != iusina.Sist:\n    #                 return 0.\n    #             elif iusina.StatusMotoriz[iano][imes] == 2:\n    #                 return iusina.RoEquiv + iusina.ProdAcumEntreResSist(iano, imes, usinas)\n    #             else:\n    #                 return iusina.ProdAcumEntreResSist(iano, imes, usinas)\n    #             break\n\n\n\n    #########################################################\n    # Calcula Modelo PAR(p)\n    #########################################################\n\n    def parp(self, ord_max):\n\n        nanos = len(self.Vazoes)  # A serie historica do ultimo ano geralmente nao vem completa (despreze-a)\n\n        media = np.mean(self.Vazoes[1:nanos], 0)    # A primeira serie historica eh utilizada como tendencia (despreze-a)\n        desvio = np.std(self.Vazoes[1:nanos], 0)    # A primeira serie historica eh utilizada como tendencia (despreze-a)\n\n        # Calcula vazao normalizada (nao precisa)\n        #vaznorm = np.zeros((nanos,12),'d')\n        #for iano in range(nanos):\n        #    for imes in range(12):\n        #        vaznorm[iano][imes] = (self.Vazoes[iano][imes] - media[imes])/desvio[imes]\n\n        # Calcula funcao de auto-correlacao (uma para cada mes)\n        self.FAC = np.zeros( (12, ord_max+1), 'd')\n        for ilag in range(ord_max+1):\n            for imes in range(12):\n                for iano in np.arange(1,nanos):\n                     ano_ant = iano\n                     mes_ant = imes - ilag\n                     if mes_ant < 0:\n                         ano_ant -= 1\n                         mes_ant += 12\n                     self.FAC[imes][ilag] += (self.Vazoes[iano][imes] - media[imes])* (self.Vazoes[ano_ant][mes_ant] - media[mes_ant])\n                self.FAC[imes][ilag] /= (nanos-1)\n                self.FAC[imes][ilag] /= (desvio[imes]*desvio[mes_ant])\n\n        # Calcula funcao de auto-correlacao parcial (uma para cada mes)\n        self.FACP = np.zeros((12, ord_max+1), 'd')\n        for ilag in np.arange(1,ord_max+1):\n            for imes in range(12):\n                A = np.eye(ilag)\n                B = np.zeros(ilag)\n                # Preenche matriz triangular superior\n                for ilin in range(len(A)):\n                    for icol in range( len(A) ):           # TODO: Aqui poderia ser np.arange(ilin+1,len(A)): Testar depois\n                        if icol > ilin:\n                            mes = imes - ilin - 1\n                            if mes < 0:\n                               mes = mes + 12\n                            A[ilin][icol] = self.FAC[mes][icol-ilin]\n                    B[ilin] = self.FAC[imes][ilin+1]\n                # Preenche matriz triangular inferior\n                for ilin in range(len(A)):\n                    for icol in range( len(A) ):          # TODO: Aqui poderia ser np.arange(0, ilin): Testar depois\n                        if icol < ilin:\n                            A[ilin][icol] = A[icol][ilin]\n                phi = np.linalg.solve(A,B)\n                self.FACP[imes][ilag] = phi[ len(phi)-1 ]\n\n        # Identificacao da ordem\n        IC = 1.96/sqrt(nanos-1)\n        self.Ordem = np.zeros(12, 'i')\n        for imes in range(12):\n            self.Ordem[imes] = 0\n            for ilag in range(ord_max+1):\n                if self.FACP[imes][ilag] > IC or self.FACP[imes][ilag] < -IC:\n                    self.Ordem[imes] = ilag\n\n        # Calculo dos coeficientes\n        self.CoefParp = np.zeros( (12,ord_max), 'd')\n        for imes in range(12):\n            ilag = self.Ordem[imes]\n            A = np.eye(ilag)\n            B = np.zeros(ilag)\n            # Preenche matriz triangular superior\n            for ilin in range(len(A)):\n                for icol in range( len(A) ):             # TODO: Aqui poderia ser np.arange(ilin+1,len(A)): Testar depois\n                    if icol > ilin:\n                        mes = imes - ilin - 1\n                        if mes < 0:\n                           mes = mes + 12\n                        A[ilin][icol] = self.FAC[mes][icol-ilin]\n                B[ilin] = self.FAC[imes][ilin+1]\n            # Preenche matriz triangular inferior\n            for ilin in range(len(A)):\n                for icol in range( len(A) ):             # TODO: Aqui poderia ser np.arange(0, ilin): Testar depois\n                    if icol < ilin:\n                        A[ilin][icol] = A[icol][ilin]\n            phi = np.linalg.solve(A,B)\n            for iord in range ( len(phi) ):\n                self.CoefParp[imes][iord ] = phi[ iord ]\n\n    def gera_series_aditivo(self):\n\n        nanos = len(self.Vazoes) - 1\n        ord_max = len(self.CoefParp[0])\n\n        media = np.mean(self.Vazoes[1:nanos], 0)\n        desvio = np.std(self.Vazoes[1:nanos], 0)\n\n        # Calculo dos residuos\n        residuos = np.zeros( (nanos, 12) )\n        for iano in np.arange(1,nanos):\n            for imes in range(12):\n                residuos[iano][imes]= ( self.Vazoes[iano][imes]-media[imes] ) / desvio[imes]\n                for ilag in range(ord_max):\n                    ano_ant = iano\n                    mes_ant = imes - ilag - 1\n                    if mes_ant < 0:\n                        ano_ant -= 1\n                        mes_ant += 12\n                    residuos[iano][imes] -= self.CoefParp[imes][ilag]*( self.Vazoes[ano_ant][mes_ant]-media[mes_ant] ) / desvio[mes_ant]\n\n        # Gera series sinteticas\n        sintetica_adit = np.zeros((1000,60),'d')\n        for iser in range(1000):\n            contador = -1\n            for iano in range(5):\n                for imes in range(12):\n                    contador += 1\n                    serie = randint(1,nanos-1)\n                    valor = media[imes] + desvio[imes]*residuos[serie][imes]\n                    for ilag in range(ord_max):\n                        mes_ant = imes - ilag - 1\n                        ano_ant = iano\n                        if mes_ant < 0:\n                            mes_ant += 12\n                            ano_ant -= 1\n                        if ano_ant < 0:\n                            vazant = media[mes_ant]\n                        else:\n                            vazant = sintetica_adit[iser][contador-1-ilag]\n                        valor += desvio[imes]*self.CoefParp[imes][ilag]*(vazant-media[mes_ant])/desvio[mes_ant]\n                    sintetica_adit[iser][contador] = valor\n\n        x_axis = np.arange(1, 61)\n        plt.plot(x_axis, sintetica_adit.transpose(), 'c-')\n        plt.plot(x_axis, np.mean(sintetica_adit,0), 'r-', lw=3, label='Mean - Synthetic Series')\n        plt.plot(x_axis, np.mean(sintetica_adit,0) + np.nanstd(sintetica_adit, axis=0), 'r-.', lw=2, label='Std Synthetic Series')\n        plt.plot(x_axis, np.mean(sintetica_adit,0) - np.nanstd(sintetica_adit, axis=0), 'r-.', lw=2)\n        m = np.concatenate([ media, media, media, media, media])\n        d = np.concatenate([ desvio, desvio, desvio, desvio, desvio])\n        plt.plot(x_axis, m, 'mo', lw=3, label='Mean - Hystorical Series')\n        plt.plot(x_axis, m + d, 'bo', lw=2, label='Std - Hystorical Series')\n        plt.plot(x_axis, m - d, 'bo', lw=2)\n        titulo = self.Nome.strip() + \"'s Synthetic Series of Natural \\n\" \" Inflows - Aditive Noise \"\n        plt.title(titulo, fontsize=16)\n        plt.xlabel('Month', fontsize=16)\n        plt.ylabel('Inflow (m^3/s', fontsize=16)\n        plt.legend(fontsize=12)\n        plt.show()\n\n\n    def gera_series_multiplicativo(self):\n\n        nanos = len(self.Vazoes) - 1\n        ord_max = len(self.CoefParp[0])\n\n        media = np.mean(self.Vazoes[1:nanos], 0)\n        desvio = np.std(self.Vazoes[1:nanos], 0)\n\n        # Calculo dos residuos\n        residuosmult = np.zeros( (nanos, 12) )\n        termoind = np.zeros(12, 'd')\n        for iano in np.arange(1,nanos):\n            for imes in range(12):\n                residuosmult[iano][imes]= self.Vazoes[iano][imes]\n                somatorio = 0\n                termoind[imes] = media[imes]  # Versao centrada: ver pagina 20 dissertacao Filipe Goulart Cabral (COPPE 2016)\n                                              # O ideal portanto, seria utilizar este metodo com formulacao de otimzicao ao\n                                              # inves de yule-walker. Restringindo que o termo-ind e os phis sejam todos positivos\n                for ilag in range(ord_max):\n                    ano_ant = iano\n                    mes_ant = imes - ilag - 1\n                    if mes_ant < 0:\n                        ano_ant -= 1\n                        mes_ant += 12\n                    somatorio += self.CoefParp[imes][ilag]*self.Vazoes[ano_ant][mes_ant]\n                    termoind[imes] -= self.CoefParp[imes][ilag]*media[mes_ant]\n                residuosmult[iano][imes] = residuosmult[iano][imes]/(termoind[imes]+somatorio)\n\n        # Gera series sinteticas\n        sintetica_mult = np.zeros((1000,60),'d')\n        for iser in range(1000):\n            contador = -1\n            for iano in range(5):\n                for imes in range(12):\n                    contador += 1\n                    serie = randint(1,nanos-1)\n                    valor = termoind[imes]\n                    for ilag in range(ord_max):\n                        mes_ant = imes - ilag - 1\n                        ano_ant = iano\n                        if mes_ant < 0:\n                            mes_ant += 12\n                            ano_ant -= 1\n                        if ano_ant < 0:\n                            vazant = media[mes_ant]\n                        else:\n                            vazant = sintetica_mult[iser][contador-1-ilag]\n                        valor += self.CoefParp[imes][ilag]*vazant\n                    sintetica_mult[iser][contador] = valor*residuosmult[serie][imes]\n\n        x_axis = np.arange(1, 61)\n        plt.plot(x_axis, sintetica_mult.transpose(), 'c-')\n        plt.plot(x_axis, np.mean(sintetica_mult,0), 'r-', lw=3, label='Mean - Synthetic Series')\n        plt.plot(x_axis, np.mean(sintetica_mult,0) + np.std(sintetica_mult, axis=0), 'r-.', lw=2, label='Std Synthetic Series')\n        plt.plot(x_axis, np.mean(sintetica_mult,0) - np.std(sintetica_mult, axis=0), 'r-.', lw=2)\n        m = np.concatenate([ media, media, media, media, media])\n        d = np.concatenate([ desvio, desvio, desvio, desvio, desvio])\n        plt.plot(x_axis, m, 'mo', lw=3, label='Mean - Hystorical Series')\n        plt.plot(x_axis, m + d, 'bo', lw=2, label='Std - Hystorical Series')\n        plt.plot(x_axis, m - d, 'bo', lw=2)\n        titulo = self.Nome.strip() + \"'s Synthetic Series of Natural \\n\" \" Inflows - Multiplicative Noise \"\n        plt.title(titulo, fontsize=16)\n        plt.xlabel('Month', fontsize=16)\n        plt.ylabel('Inflows (m3/s)', fontsize=16)\n        #plt.ylim(-100, 30000)\n        plt.legend(fontsize=12)\n        plt.show()\n\n        vasco = 1000\n\n    def pso(self, ord_max):\n\n        def objetivo(x, ord_max, imes):\n\n            nanos = len(self.Vazoes) - 1  # A serie historica do ultimo ano geralmente nao vem completa (despreze-a)\n\n            coef = np.zeros( ord_max+1, 'd')\n            for icoef in range(ord_max+1):\n                coef[icoef] = x[icoef]\n\n            objetivo = 0.\n            residuos = np.zeros(nanos-1)\n\n            for iano in np.arange(1,nanos):\n                somatorio = coef[0]\n                for ilag in range(ord_max):\n                    mes_ant = imes - 1 - ilag\n                    ano_ant = iano\n                    if mes_ant < 0:\n                        mes_ant += 12\n                        ano_ant -= 1\n                    somatorio += coef[ilag + 1] * self.Vazoes[ano_ant][mes_ant]\n                residuos[iano-1]=(self.Vazoes[iano][imes] / somatorio)\n                objetivo += ((self.Vazoes[iano][imes] / somatorio) ** 2)\n\n            total = np.sum(residuos) - nanos + 1\n            total = total ** 2\n            total = 10000*total\n\n            return ( objetivo/(nanos-1) + total )\n\n        self.CoefParp = np.zeros((12, ord_max), 'd')\n        self.CoefIndParp = np.zeros(12, 'd')\n        self.Ordem = np.zeros(12,'d')\n        for imes in range(12):\n            print( '*******', imes+1)\n\n            best = 999999\n            best_ordem = 0\n            for iord in np.arange(1,(ord_max+1)):\n                # Define limites e condicao inicial\n                lb = np.zeros(iord + 1)\n                ub = np.zeros(iord + 1)\n                for i in range(iord + 1):\n                    lb[i] = 0.00001\n                    ub[i] = 10000\n\n                print('**', iord)\n                solution, fopt = pso(objetivo, lb, ub, args=(iord, imes), maxiter = 500)\n\n                #solution = minimize(objetivo, x0, method= 'SLSQP', bounds=limites, constraints=cons, args=( iord, imes), options={ 'disp': False, 'maxiter': 10000 }  )\n                if fopt < best:\n                    best = fopt\n                    best_ordem = iord\n\n            self.Ordem[imes] = best_ordem\n\n            solution, fopt = pso(objetivo, lb, ub, args=(iord, imes), maxiter=5000)\n\n            for icoef in range(ord_max):\n                self.CoefParp[imes][icoef] = solution[icoef+1]\n            self.CoefIndParp[imes] = solution[0]\n\n\n    def parp_otimo(self, ord_max):\n\n\n        # Funcao objetivo minimizar erro quatratico medio (o residuo eh o erro)\n        def objetivo(x, ord_max, imes):\n\n            nanos = len(self.Vazoes) - 1  # A serie historica do ultimo ano geralmente nao vem completa (despreze-a)\n\n            coef = np.zeros( ord_max+1, 'd')\n            for icoef in range(ord_max+1):\n                coef[icoef] = x[icoef]\n\n            objetivo = 0.\n            for iano in np.arange(1,nanos):\n                somatorio = coef[0]\n                for ilag in range(ord_max):\n                    mes_ant = imes - 1 - ilag\n                    ano_ant = iano\n                    if mes_ant < 0:\n                        mes_ant += 12\n                        ano_ant -= 1\n                    somatorio += coef[ilag + 1] * self.Vazoes[ano_ant][mes_ant]\n                objetivo += ((self.Vazoes[iano][imes] / somatorio) ** 2)\n\n            return objetivo/(nanos-1)\n\n        # Restricoes a media dos residuos devem ser igual a unidade ou somatorio dos residuos devem ser igual a nanos\n        def restricao(x, ord_max, imes):\n\n            nanos = len(self.Vazoes) - 1  # A serie historica do ultimo ano geralmente nao vem completa (despreze-a)\n\n            coef = np.zeros( ord_max+1, 'd')\n            for icoef in range(ord_max+1):\n                coef[icoef] = x[icoef]\n\n            objetivo = 0.\n            residuos = np.zeros(nanos-1)\n            for iano in np.arange(1,nanos):\n                somatorio = coef[0]\n                for ilag in range(ord_max):\n                    mes_ant = imes - 1 - ilag\n                    ano_ant = iano\n                    if mes_ant < 0:\n                        mes_ant += 12\n                        ano_ant -= 1\n                    somatorio += coef[ilag + 1] * self.Vazoes[ano_ant][mes_ant]\n                objetivo += (self.Vazoes[iano][imes] / somatorio)\n                residuos[iano-1]=(self.Vazoes[iano][imes] / somatorio)\n                desvio = np.std(residuos)\n                #curtose = kurtosis(residuos) - 3\n            # return ([ objetivo - nanos + 1 , desvio - 0.2])\n            return ([ objetivo - nanos + 1 ])\n\n        # Define limites e condicao inicial\n        x0 = np.zeros(ord_max+1)\n        limites = []\n        for i in range(ord_max + 1):\n            x0[i] = 0.1\n            limites.append((0, 10000))\n\n        self.CoefParp = np.zeros((12, ord_max), 'd')\n        self.CoefIndParp = np.zeros(12, 'd')\n        self.Ordem = np.zeros(12,'d')\n        for imes in range(12):\n            print( '*******', imes+1)\n            conl = {'type': 'eq', 'fun': restricao, 'args': (ord_max, imes)}\n            cons = ([conl])\n            best = 999999\n            best_ordem = 0\n            #for iord in np.arange(1,(ord_max+1)):\n            for iord in np.arange(6, 7):\n                solution = minimize(objetivo, x0, method= 'SLSQP', bounds=limites, constraints=cons, args=( iord, imes), options={ 'disp': False, 'maxiter': 10000 }  )\n                if solution.fun < best:\n                    best = solution.fun\n                    best_ordem = iord\n\n            self.Ordem[imes] = best_ordem\n            solution = minimize(objetivo, x0, method= 'SLSQP', bounds=limites, constraints=cons, args=( best_ordem, imes), options={ 'disp': True, 'maxiter': 10000 }  )\n\n\n            for icoef in range(ord_max):\n                self.CoefParp[imes][icoef] = solution.x[icoef+1]\n            self.CoefIndParp[imes] = solution.x[0]\n\n\n    def gera_series_multiplicativo_parp_otimo(self):\n\n        nanos = len(self.Vazoes) - 1\n        ord_max = len(self.CoefParp[0])\n\n        media = np.mean(self.Vazoes[1:nanos], 0)\n        desvio = np.std(self.Vazoes[1:nanos], 0)\n\n        # Calculo dos residuos\n        residuosmult = np.zeros( (nanos, 12) )\n        for iano in np.arange(1,nanos):\n            for imes in range(12):\n                residuosmult[iano][imes]= self.Vazoes[iano][imes]\n                somatorio = 0\n                for ilag in range(ord_max):\n                    ano_ant = iano\n                    mes_ant = imes - ilag - 1\n                    if mes_ant < 0:\n                        ano_ant -= 1\n                        mes_ant += 12\n                    somatorio += self.CoefParp[imes][ilag]*self.Vazoes[ano_ant][mes_ant]\n                residuosmult[iano][imes] = residuosmult[iano][imes]/(self.CoefIndParp[imes]+somatorio)\n\n        # Gera series sinteticas\n        sintetica_mult = np.zeros((1000,60),'d')\n        for iser in range(1000):\n            contador = -1\n            for iano in range(5):\n                for imes in range(12):\n                    contador += 1\n                    serie = randint(1,nanos-1)\n                    valor = self.CoefIndParp[imes]\n                    for ilag in range(ord_max):\n                        mes_ant = imes - ilag - 1\n                        ano_ant = iano\n                        if mes_ant < 0:\n                            mes_ant += 12\n                            ano_ant -= 1\n                        if ano_ant < 0:\n                            vazant = media[mes_ant]\n                        else:\n                            vazant = sintetica_mult[iser][contador-1-ilag]\n                        valor += self.CoefParp[imes][ilag]*vazant\n                    sintetica_mult[iser][contador] = valor*residuosmult[serie][imes]\n\n        x_axis = np.arange(1, 61)\n        plt.plot(x_axis, sintetica_mult.transpose(), 'c-')\n        plt.plot(x_axis, np.mean(sintetica_mult,0), 'r-', lw=3, label='Mean - Synthetic Series')\n        plt.plot(x_axis, np.mean(sintetica_mult,0) + np.std(sintetica_mult, axis=0), 'r-.', lw=2, label='Std Synthetic Series')\n        plt.plot(x_axis, np.mean(sintetica_mult,0) - np.std(sintetica_mult, axis=0), 'r-.', lw=2)\n        m = np.concatenate([ media, media, media, media, media])\n        d = np.concatenate([ desvio, desvio, desvio, desvio, desvio])\n        plt.plot(x_axis, m, 'mo', lw=3, label='Mean - Hystorical Series')\n        plt.plot(x_axis, m + d, 'bo', lw=2, label='Std - Hystorical Series')\n        plt.plot(x_axis, m - d, 'bo', lw=2)\n        titulo = self.Nome.strip() + \"'s Synthetic Series of Natural \\n\" \" Inflows - Multiplicative Noise \"\n        plt.title(titulo, fontsize=16)\n        plt.xlabel('Month', fontsize=16)\n        plt.ylabel('Inflows (m3/s)', fontsize=16)\n        #plt.ylim(-100, 30000)\n        plt.legend(fontsize=12)\n        plt.show()", "meta": {"hexsha": "aef54d083d502f5b97d4abab33cf1d1d163694d7", "size": 50844, "ext": "py", "lang": "Python", "max_stars_repo_path": "PySDDP/hidr.py", "max_stars_repo_name": "tscher/PySDDP", "max_stars_repo_head_hexsha": "ece69b77c951cbb1f046ac184f6fe4fc025ad690", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-01-07T13:35:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T14:30:33.000Z", "max_issues_repo_path": "PySDDP/hidr.py", "max_issues_repo_name": "AndreMarcato/PySDDP", "max_issues_repo_head_hexsha": "e6b1e60df6a5598c30552be61b07ed642e46399c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PySDDP/hidr.py", "max_forks_repo_name": "AndreMarcato/PySDDP", "max_forks_repo_head_hexsha": "e6b1e60df6a5598c30552be61b07ed642e46399c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-01-08T11:37:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-19T15:07:26.000Z", "avg_line_length": 42.2995008319, "max_line_length": 168, "alphanum_fraction": 0.5228345527, "include": true, "reason": "import numpy,from scipy", "num_tokens": 14799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.18812794556196538}}
{"text": "#!/usr/bin/env python\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#\n\nimport time\nimport ctypes\nimport tempfile\nfrom functools import reduce\nimport numpy\nimport h5py\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf import ao2mo\nfrom pyscf.cc import ccsd\nfrom pyscf.cc import _ccsd\n\n# t2,l2 as ijab\n\ndef kernel(mycc, eris, t1=None, t2=None, l1=None, l2=None,\n           max_cycle=50, tol=1e-8, verbose=logger.INFO):\n    cput0 = (time.clock(), time.time())\n    if isinstance(verbose, logger.Logger):\n        log = verbose\n    else:\n        log = logger.Logger(mycc.stdout, verbose)\n\n    if t1 is None: t1 = mycc.t1\n    if t2 is None: t2 = mycc.t2\n    if l1 is None: l1 = t1\n    if l2 is None: l2 = t2\n\n    nocc, nvir = t1.shape\n    saved = make_intermediates(mycc, t1, t2, eris)\n\n    if mycc.diis:\n        adiis = lib.diis.DIIS(mycc, mycc.diis_file)\n        adiis.space = mycc.diis_space\n    else:\n        adiis = lambda t1,t2,*args: (t1, t2)\n    cput0 = log.timer('CCSD lambda initialization', *cput0)\n\n    conv = False\n    for istep in range(max_cycle):\n        l1new, l2new = update_amps(mycc, t1, t2, l1, l2, eris, saved)\n        normt = numpy.linalg.norm(l1new-l1) + numpy.linalg.norm(l2new-l2)\n        l1, l2 = l1new, l2new\n        l1new = l2new = None\n        if mycc.diis:\n            l1, l2 = mycc.diis(l1, l2, istep, normt, 0, adiis)\n        log.info('cycle = %d  norm(lambda1,lambda2) = %.6g', istep+1, normt)\n        cput0 = log.timer('CCSD iter', *cput0)\n        if normt < tol:\n            conv = True\n            break\n    return conv, l1, l2\n\n\n# l2, t2 as ijab\ndef make_intermediates(mycc, t1, t2, eris):\n    log = logger.Logger(mycc.stdout, mycc.verbose)\n    nocc, nvir = t1.shape\n    nov = nocc * nvir\n    foo = eris.fock[:nocc,:nocc]\n    fov = eris.fock[:nocc,nocc:]\n    fvv = eris.fock[nocc:,nocc:]\n\n    class _Saved:\n        pass\n    saved = _Saved()\n    saved.ftmp = lib.H5TmpFile()\n    saved.woooo = saved.ftmp.create_dataset('woooo', (nocc,nocc,nocc,nocc), 'f8')\n    saved.wooov = saved.ftmp.create_dataset('wooov', (nocc,nocc,nocc,nvir), 'f8')\n    saved.wOVov = saved.ftmp.create_dataset('wOVov', (nocc,nvir,nocc,nvir), 'f8')\n    saved.wOvOv = saved.ftmp.create_dataset('wOvOv', (nocc,nvir,nocc,nvir), 'f8')\n    saved.wovvv = saved.ftmp.create_dataset('wovvv', (nocc,nvir,nvir,nvir), 'f8')\n\n# As we don't have l2 in memory, hold tau temporarily in memory\n    w1 = fvv - numpy.einsum('ja,jb->ba', fov, t1)\n    w2 = foo + numpy.einsum('ib,jb->ij', fov, t1)\n    w3 = numpy.einsum('kc,jkbc->bj', fov, t2) * 2 + fov.T\n    w3 -= numpy.einsum('kc,kjbc->bj', fov, t2)\n    w3 += reduce(numpy.dot, (t1.T, fov, t1.T))\n    w4 = fov.copy()\n\n    _tmpfile = tempfile.NamedTemporaryFile(dir=lib.param.TMPDIR)\n    fswap = h5py.File(_tmpfile.name)\n\n    time1 = time.clock(), time.time()\n    unit = max(nocc*nvir**2*4 + nvir**3*2,\n               nvir**3*3 + nocc*nvir**2,\n               nocc*nvir**2*6 + nocc**2*nvir + nocc**3 + nocc**2*nvir)\n    max_memory = mycc.max_memory - lib.current_memory()[0]\n    blksize = max(ccsd.BLKMIN, int(max_memory*.95e6/8/unit))\n    log.debug1('ccsd lambda make_intermediates: block size = %d, nocc = %d in %d blocks',\n               blksize, nocc, int((nocc+blksize-1)//blksize))\n    for istep, (p0, p1) in enumerate(prange(0, nocc, blksize)):\n        eris_ovvv = _cp(eris.ovvv[p0:p1])\n        eris_ovvv = lib.unpack_tril(eris_ovvv.reshape((p1-p0)*nvir,-1))\n        eris_ovvv = eris_ovvv.reshape(p1-p0,nvir,nvir,nvir)\n        w1 += numpy.einsum('jcba,jc->ba', eris_ovvv, t1[p0:p1]*2)\n        w1 -= numpy.einsum('jabc,jc->ba', eris_ovvv, t1[p0:p1])\n        #:w3 += numpy.einsum('kdcb,kjdc->bj', eris_ovvv, theta)\n        for i in range(p1-p0):\n            theta = t2[p0+i] * 2\n            theta -= t2[p0+i].transpose(0,2,1)\n            w3 += lib.dot(eris_ovvv[i].reshape(-1,nvir).T,\n                          _cp(theta.reshape(nocc,-1)).T)\n        theta = None\n        #:wOVov = numpy.einsum('jbcd,kd->jbkc', eris_ovvv, t1)\n        #:wOvOv = numpy.einsum('jdcb,kd->jbkc', eris_ovvv, -t1)\n        wOVov = lib.dot(eris_ovvv.reshape(-1,nvir),\n                        t1.T).reshape(-1,nvir,nvir,nocc).transpose(0,1,3,2).copy()\n        g2ovvv = _cp(eris_ovvv.transpose(0,2,3,1))\n        wOvOv = lib.dot(g2ovvv.reshape(-1,nvir),\n                        -t1.T).reshape(-1,nvir,nvir,nocc).transpose(0,1,3,2).copy()\n        for i in range(p1-p0):\n            g2ovvv[i] *= 2\n            g2ovvv[i] -= eris_ovvv[i].transpose(1,0,2)\n        wooov = numpy.empty((p1-p0,nocc,nocc,nvir))\n        woooo = numpy.empty((p1-p0,nocc,nocc,nocc))\n        eris_ovov = _cp(_cp(eris.ovov[p0:p1]).transpose(0,2,1,3))\n        for j0, j1 in prange(0, nocc, blksize):\n            tau = _ccsd.make_tau(t2[j0:j1], t1[j0:j1], t1)\n            #:wooov[:,j0:j1] = numpy.einsum('icbd,jkbd->ijkc', g2ovvv, tau)\n            #:woooo[:,:,j0:j1] = numpy.einsum('icjd,klcd->ijkl', eris_ovov, tau)\n            tmp = lib.dot(g2ovvv.reshape(-1,nvir**2), tau.reshape(-1,nvir**2).T)\n            wooov[:,j0:j1] = tmp.reshape(-1,nvir,j1-j0,nocc).transpose(0,2,3,1)\n            woooo[:,:,j0:j1] = lib.dot(eris_ovov.reshape(-1,nvir**2),\n                                       tau.reshape(-1,nvir**2).T).reshape(-1,nocc,j1-j0,nocc)\n        eris_ovov = eris_ovvv = g2ovvv = tau = tmp = None\n#==== mem usage nocc*nvir**2*2 + nocc**2*nvir + nocc**3 + nvir**3*2 + nocc*nvir**2*2\n\n        eris_ooov = _cp(eris.ooov[p0:p1])\n        w2[p0:p1] += numpy.einsum('ijkb,kb->ij', eris_ooov, t1) * 2\n        w2 -= numpy.einsum('kjib,kb->ij', eris_ooov, t1[p0:p1])\n        #:w3 -= numpy.einsum('kjlc,klbc->bj', eris_ooov, theta)\n        for i in range(p1-p0):\n            theta = t2[p0+i].transpose(0,2,1) * 2\n            theta -= t2[p0+i]\n            w3 -= lib.dot(theta.reshape(-1,nvir).T, eris_ooov[i].reshape(nocc,-1).T)\n        theta = None\n        #:woooo += numpy.einsum('ikjc,lc->ijkl', eris_ooov, t1)\n        #:wOvOv += numpy.einsum('jklb,lc->jbkc', eris_ooov, t1)\n        woooo += lib.dot(eris_ooov.reshape(-1,nvir),\n                         t1.T).reshape((-1,nocc,nocc,nocc)).transpose(0,2,1,3)\n        for i in range(p1-p0):\n            lib.dot(_cp(eris_ooov[i].transpose(2,0,1)).reshape(-1,nocc),\n                    t1, 1, wOvOv[i].reshape(-1,nvir), 1)\n            wooov[i] += eris_ooov[i].transpose(1,0,2)*2\n            wooov[i] -= eris_ooov[i]\n\n        eris_ovoo = _cp(eris.ovoo[p0:p1])\n        #:woooo += numpy.einsum('icjl,kc->ijkl', eris_ovoo, t1)\n        #:wOVov += numpy.einsum('jbkl,lc->jbkc', eris_ovoo, -t1)\n        for i in range(p1-p0):\n            woooo[i] += lib.dot(t1, eris_ovoo[i].reshape(nvir,-1)).reshape((nocc,)*3).transpose(1,0,2)\n        lib.dot(eris_ovoo.reshape(-1,nocc), t1, -1, wOVov.reshape(-1,nvir), 1)\n        #:wooov -= numpy.einsum('iblj,klbc->ijkc', eris_ovoo*1.5, t2)\n        tmp_ovoo = _cp(-eris_ovoo.transpose(0,2,3,1)).reshape(-1,nov)\n        for j in range(nocc):\n            wooov[:,:,j] += lib.dot(tmp_ovoo, t2[j].reshape(-1,nvir),\n                                    1.5).reshape(-1,nocc,nvir)\n        #:g2ooov = eris_ooov * 2 - eris_ovoo.transpose(0,3,2,1)\n        g2ooov, tmp_ovoo = tmp_ovoo.reshape(p1-p0,nocc,nocc,nvir), None\n        g2ooov += eris_ooov * 2\n        thetabuf = numpy.empty((blksize,nvir,nocc,nvir))\n        vikjc = numpy.empty((p1-p0,nocc,blksize,nvir))\n        for j0, j1 in prange(0, nocc, blksize):\n            theta = thetabuf[:j1-j0]\n            for i in range(j1-j0):\n                theta[i] = t2[j0+i].transpose(1,0,2)*2 - t2[j0+i].transpose(2,0,1)\n            #:vikjc = numpy.einsum('iklb,jlcb->ikjc', g2ooov, theta)\n            if j1 == j0 + blksize:\n                lib.dot(g2ooov.reshape(-1,nov), _cp(theta.reshape(-1,nov)).T,\n                        1, vikjc.reshape((p1-p0)*nocc,-1), 0)\n            else:\n                vikjc = lib.dot(g2ooov.reshape(-1,nov),\n                                _cp(theta.reshape(-1,nov)).T)\n                vikjc = vikjc.reshape(p1-p0,nocc,j1-j0,nvir)\n            wooov[:,j0:j1,:] += vikjc.transpose(0,2,1,3)\n            wooov[:,:,j0:j1] -= vikjc*.5\n        eris_ooov = eris_ovoo = g2ooov = vikjc = theta = thetabuf = None\n#==== mem usage nocc*nvir**2*3 + nocc**2*nvir + nocc**3 + nocc*nvir**2 + nocc**2*nvir*3\n\n        eris_ovov = _cp(eris.ovov[p0:p1])\n        g2ovov = eris_ovov*2\n        g2ovov -= eris_ovov.transpose(0,3,2,1)\n        tmpw4 = numpy.einsum('kcld,ld->kc', g2ovov, t1)\n        #:w1 -= numpy.einsum('kcja,kjcb->ba', g2ovov, t2[p0:p1])\n        w1 -= lib.dot(t2[p0:p1].reshape(-1,nvir).T,\n                      _cp(g2ovov.transpose(0,2,1,3).reshape(-1,nvir)))\n        w1 -= numpy.einsum('ja,jb->ba', tmpw4, t1[p0:p1])\n        #:w2[p0:p1] += numpy.einsum('ibkc,jkbc->ij', g2ovov, t2)\n        w2[p0:p1] += lib.dot(_cp(g2ovov.transpose(0,2,1,3)).reshape(p1-p0,-1),\n                             t2.reshape(nocc,-1).T)\n        w2[p0:p1] += numpy.einsum('ib,jb->ij', tmpw4, t1)\n        w3 += reduce(numpy.dot, (t1[p0:p1].T, tmpw4, t1.T))\n        w4[p0:p1] += tmpw4\n        vOVov = numpy.empty((nocc,nvir,p1-p0,nvir))\n        #:vOVov += numpy.einsum('jbld,klcd->kcjb', g2ovov, t2)\n        #:vOVov -= numpy.einsum('jbld,kldc->kcjb', eris_ovov, t2)\n        for j in range(nocc):\n            lib.dot(_cp(t2[j].transpose(1,0,2)).reshape(-1,nov),\n                    g2ovov.reshape(-1,nov).T, 1, vOVov[j].reshape(nvir,-1))\n            lib.dot(t2[j].reshape(nov,-1).T, eris_ovov.reshape(-1,nov).T,\n                    -1, vOVov[j].reshape(nvir,-1), 1)\n        vOVov = lib.transpose(vOVov.reshape(nov,-1)).reshape(p1-p0,nvir,nocc,nvir)\n        vOVov += eris_ovov\n        g2ovov = tmp = tmpw4 = None\n#==== mem usage nocc*nvir**2*4 + nocc**2*nvir + nocc**3 + nocc*nvir**2\n\n        #:tmp = numpy.einsum('jbld,kd->jlbk', eris_ovov, t1)\n        #:wOVov -= numpy.einsum('jlbk,lc->jbkc', tmp, t1)\n        #:tmp = numpy.einsum('jdlb,kd->jlbk', eris_ovov, t1)\n        #:wOvOv += numpy.einsum('jlbk,lc->jbkc', tmp, t1)\n        tmp = numpy.empty((nocc,nvir,nocc))\n        for j in range(p1-p0):\n            lib.dot(_cp(eris_ovov[j].transpose(1,0,2)).reshape(-1,nvir),\n                    t1.T, 1, tmp.reshape(-1,nocc))\n            lib.dot(tmp.reshape(nocc,-1).T, t1, -1, wOVov[j].reshape(-1,nvir), 1)\n            lib.dot(eris_ovov[j].reshape(nvir,-1).T, t1.T, 1,\n                    tmp.reshape(-1,nocc))\n            lib.dot(tmp.reshape(nocc,-1).T, t1, 1, wOvOv[j].reshape(-1,nvir), 1)\n        tmp = None\n\n        #:vOvOv = numpy.einsum('jdlb,kldc->kcjb', eris_ovov, t2)\n        ovovtmp = _cp(eris_ovov.transpose(0,3,2,1)).reshape(-1,nov)\n        vOvOv = numpy.empty((nocc,nvir,p1-p0,nvir))\n        for j in range(nocc):\n            lib.dot(t2[j].reshape(-1,nvir).T, ovovtmp.T, 1,\n                    vOvOv[j].reshape(nvir,-1))\n        ovovtmp = eris_ovov = None\n        vOvOv = lib.transpose(vOvOv.reshape(nov,-1)).reshape(p1-p0,nvir,nocc,nvir)\n        vOvOv -= _cp(eris.oovv[p0:p1]).transpose(0,3,1,2)\n        wOVov += vOVov\n        wOvOv += vOvOv\n        saved.wOVov[p0:p1] = wOVov\n        saved.wOvOv[p0:p1] = wOvOv\n        wOVov = wOvOv = None\n#==== mem usage nocc*nvir**2*6 + nocc**2*nvir + nocc**3 + nocc**2*nvir\n\n        ov1 = vOvOv*2 + vOVov\n        #:wooov -= numpy.einsum('ibkc,jb->ijkc', ov1, t1)\n        for i in range(p1-p0):\n            lib.dot(t1, ov1[i].reshape(nvir,-1), -1, wooov[i].reshape(nocc,-1), 1)\n        ov1 = lib.transpose(ov1.reshape(-1,nov))\n        fswap['2vOvOv/%d'%istep] = ov1.reshape(nocc,nvir,-1,nvir)\n        ov1 = None\n        ov2 = vOVov*2 + vOvOv\n        w3 += numpy.einsum('kcjb,kc->bj', ov2, t1[p0:p1])\n        #:wooov += numpy.einsum('ibjc,kb->ijkc', ov2, t1)\n        for i in range(p1-p0):\n            wooov[i] += lib.dot(t1, ov2[i].reshape(nvir,-1)).reshape(nocc,nocc,nvir).transpose(1,0,2)\n        ov2 = lib.transpose(ov2.reshape(-1,nov))\n        fswap['2vovOV/%d'%istep] = ov2.reshape(nocc,nvir,-1,nvir)\n        vOVov = vOvOv = None\n        ov2 = None\n#==== mem usage nocc*nvir**2*5 + nocc**2*nvir + nocc**3\n\n        woooo += _cp(eris.oooo[p0:p1]).transpose(0,2,1,3)\n        saved.woooo[p0:p1] = woooo\n        saved.wooov[p0:p1] = wooov\n        woooo = wooov = None\n        time1 = log.timer_debug1('pass1 [%d:%d]'%(p0, p1), *time1)\n\n    w3 += numpy.einsum('bc,jc->bj', w1, t1)\n    w3 -= numpy.einsum('kj,kb->bj', w2, t1)\n\n    for p0, p1 in prange(0, nocc, blksize):\n        eris_ooov = _cp(eris.ooov[p0:p1])\n        g2ooov = eris_ooov * 2\n        g2ooov -= eris_ooov.transpose(0,2,1,3)\n        #:tmp = numpy.einsum('kjla,jb->kabl', g2ooov, t1)\n        #:wovvv = numpy.einsum('kabl,lc->kabc', tmp, t1)\n        #:wovvv += numpy.einsum('kjla,jlbc->kabc', g2ooov, t2)\n        tmp = lib.dot(_cp(g2ooov.transpose(1,0,2,3).reshape(nocc,-1)).T,\n                      t1).reshape(-1,nocc,nvir,nvir).transpose(0,2,3,1)\n        wovvv = lib.dot(_cp(tmp.reshape(-1,nocc)), t1).reshape(-1,nvir,nvir,nvir)\n        wovvv += lib.dot(_cp(g2ooov.transpose(0,3,1,2).reshape(-1,nocc**2)),\n                         t2.reshape(nocc**2,-1)).reshape(-1,nvir,nvir,nvir)\n        tmp = g2ooov = None\n        ov1 = numpy.empty((p1-p0,nvir,nocc,nvir))\n        ov2 = numpy.empty((p1-p0,nvir,nocc,nvir))\n        for istep, (j0, j1) in enumerate(prange(0, nocc, blksize)):\n            ov1[:,:,j0:j1] = fswap['2vOvOv/%d'%istep][p0:p1]\n            ov2[:,:,j0:j1] = fswap['2vovOV/%d'%istep][p0:p1]\n        #:wovvv += numpy.einsum('kcja,jb->kabc', ov1, t1)\n        #:wovvv -= numpy.einsum('kbja,jc->kabc', ov2, t1)\n        wovvv += lib.dot(_cp(ov1.transpose(0,1,3,2).reshape(-1,nocc)),\n                         t1).reshape(-1,nvir,nvir,nvir).transpose(0,2,3,1)\n        wovvv -= lib.dot(_cp(ov2.transpose(0,1,3,2).reshape(-1,nocc)),\n                         t1).reshape(-1,nvir,nvir,nvir).transpose(0,2,1,3)\n#==== mem usage nvir**3 + nocc*nvir**2*2\n        eris_ooov = ov1 = ov2 = None\n\n        for j0, j1 in prange(0, nocc, blksize):\n            eris_ovvv = _cp(eris.ovvv[j0:j1])\n            eris_ovvv = lib.unpack_tril(eris_ovvv.reshape((j1-j0)*nvir,-1))\n            eris_ovvv = eris_ovvv.reshape(j1-j0,nvir,nvir,nvir)\n            #:wovvv += numpy.einsum('jabd,kjdc->kabc', eris_ovvv, t2[p0:p1,j0:j1]) * -1.5\n            tmp_ovvv = numpy.empty((j1-j0,nvir,nvir,nvir))\n            for i in range(j1-j0):\n                tmp_ovvv[i] = eris_ovvv[i].transpose(1,0,2)*2\n            tmp = lib.dot(_cp(t2[p0:p1,j0:j1].transpose(0,3,1,2).reshape((p1-p0)*nvir,-1)),\n                          tmp_ovvv.reshape(-1,nvir**2), -1.5/2).reshape(-1,nvir,nvir,nvir)\n            wovvv += tmp.transpose(0,2,3,1)\n            if p0 == j0:\n                for i in range(p1-p0):\n                    tmp_ovvv[i] -= eris_ovvv[i].transpose(1,2,0)\n                    wovvv[i] += tmp_ovvv[i]\n            tmp = tmp_ovvv = None\n            g2ovvv = numpy.empty((j1-j0,nvir,nvir,nvir))\n            for i in range(j1-j0):\n                g2ovvv[i] = eris_ovvv[i] * 2\n                g2ovvv[i] -= eris_ovvv[i].transpose(1,2,0)\n#==== mem usage nvir**3*3\n            eris_ovvv = None\n            theta = _cp(t2[p0:p1,j0:j1].transpose(0,2,1,3)*2)\n            for i in range(p1-p0):\n                theta[i] -= t2[p0+i,j0:j1].transpose(2,0,1)\n            #:vkbca = numpy.einsum('jdca,kbjd->kbca', g2ovvv, theta)\n            vkbca = lib.dot(theta.reshape((p1-p0)*nvir,-1),\n                            g2ovvv.reshape(-1,nvir*nvir)).reshape(-1,nvir,nvir,nvir)\n            wovvv += vkbca.transpose(0,3,1,2)\n            wovvv -= vkbca.transpose(0,3,2,1) * .5\n#==== mem usage nvir**3*3 + nocc*nvir**2\n            g2ovvv = theta = vkabc = None\n        saved.wovvv[p0:p1] = wovvv\n        time1 = log.timer_debug1('pass2 [%d:%d]'%(p0, p1), *time1)\n\n    fswap.close()\n\n    saved.w1 = w1\n    saved.w2 = w2\n    saved.w3 = w3\n    saved.w4 = w4\n    saved.ftmp.flush()\n    return saved\n\n\n# update L1, L2\ndef update_amps(mycc, t1, t2, l1, l2, eris=None, saved=None):\n    if saved is None:\n        saved = make_intermediates(mycc, t1, t2, eris)\n    time1 = time0 = time.clock(), time.time()\n    log = logger.Logger(mycc.stdout, mycc.verbose)\n    nocc, nvir = t1.shape\n    nov = nocc * nvir\n    fov = eris.fock[:nocc,nocc:]\n\n    #:mba = numpy.einsum('klca,klcb->ba', l2, t2*2-t2.transpose(0,1,3,2))\n    #:mij = numpy.einsum('ikcd,jkcd->ij', l2, t2*2-t2.transpose(0,1,3,2))\n    #:theta = t2*2 - t2.transpose(0,1,3,2)\n    theta = _ccsd.make_0132(t2, t2, 2, -1)\n    mba = lib.dot(theta.reshape(-1,nvir).T, l2.reshape(-1,nvir))\n    mij = lib.dot(l2.reshape(nocc,-1), theta.reshape(nocc,-1).T)\n    theta = None\n    mba1 = numpy.einsum('jc,jb->bc', l1, t1) + mba\n    mij1 = numpy.einsum('kb,jb->kj', l1, t1) + mij\n    mia1 =(t1 + numpy.einsum('kc,jkbc->jb', l1, t2) * 2\n         - numpy.einsum('kc,jkcb->jb', l1, t2)\n         - reduce(numpy.dot, (t1, l1.T, t1))\n         - numpy.einsum('bd,jd->jb', mba, t1)\n         - numpy.einsum('lj,lb->jb', mij, t1))\n\n    tmp = mycc.add_wvvVV(numpy.zeros_like(l1), l2, eris)\n    l2new = numpy.empty((nocc,nocc,nvir,nvir))\n    ij = 0\n    for i in range(nocc):\n        for j in range(i):\n            tmp1 = tmp[ij] * .5  # *.5 because of l2+l2.transpose(1,0,3,2) later\n            l2new[i,j] = tmp1\n            l2new[j,i] = tmp1.T\n            ij += 1\n        l2new[i,i] = tmp[ij] * .5\n        ij += 1\n    l1new =(numpy.einsum('ijab,jb->ia', l2new, t1) * 4\n          - numpy.einsum('jiab,jb->ia', l2new, t1) * 2)\n    tmp = tmp1 = None\n\n    l1new += fov\n    l1new += numpy.einsum('ib,ba->ia', l1, saved.w1)\n    l1new -= numpy.einsum('ja,ij->ia', l1, saved.w2)\n    l1new -= numpy.einsum('ik,ka->ia', mij, saved.w4)\n    l1new -= numpy.einsum('ca,ic->ia', mba, saved.w4)\n    l1new += numpy.einsum('ijab,bj->ia', l2, saved.w3) * 2\n    l1new -= numpy.einsum('ijba,bj->ia', l2, saved.w3)\n\n    l2new += numpy.einsum('ia,jb->ijab', l1, saved.w4)\n    #:l2new += numpy.einsum('jibc,ca->jiba', l2, saved.w1)\n    #:l2new -= numpy.einsum('kiba,jk->jiba', l2, saved.w2)\n    lib.dot(l2.reshape(-1,nvir), saved.w1, 1, l2new.reshape(-1,nvir), 1)\n    lib.dot(saved.w2, l2.reshape(nocc,-1),-1, l2new.reshape(nocc,-1), 1)\n\n    eris_ooov = _cp(eris.ooov)\n    l1new -= numpy.einsum('jkia,kj->ia', eris_ooov, mij1) * 2\n    l1new += numpy.einsum('ikja,kj->ia', eris_ooov, mij1)\n    #:l2new -= numpy.einsum('ka,kijb->jiba', l1, eris_ooov)\n    lib.dot(_cp(eris_ooov.transpose(0,2,1,3).reshape(nocc,-1)).T,\n            l1, -1, l2new.reshape(-1,nvir), 1)\n    eris_ooov = None\n\n    tau = _ccsd.make_tau(t2, t1, t1)\n    #:l2tau = numpy.einsum('ijcd,klcd->ijkl', l2, tau)\n    l2tau = lib.dot(l2.reshape(nocc**2,-1),\n                    tau.reshape(nocc**2,-1).T).reshape((nocc,)*4)\n    tau = None\n    #:l2t1 = numpy.einsum('jidc,kc->ijkd', l2, t1)\n    l2t1 = lib.dot(l2.reshape(-1,nvir), t1.T).reshape(nocc,nocc,nvir,nocc)\n    l2t1 = _cp(l2t1.transpose(1,0,3,2))\n\n    max_memory = mycc.max_memory - lib.current_memory()[0]\n    unit = max(nvir**3*2+nocc*nvir**2, nocc*nvir**2*5)\n    blksize = min(nocc, max(ccsd.BLKMIN, int(max_memory*.95e6/8/unit)))\n    log.debug1('block size = %d, nocc = %d is divided into %d blocks',\n               blksize, nocc, int((nocc+blksize-1)/blksize))\n    for p0, p1 in prange(0, nocc, blksize):\n        eris_ovvv = _cp(eris.ovvv[p0:p1])\n        eris_ovvv = lib.unpack_tril(eris_ovvv.reshape((p1-p0)*nvir,-1))\n        eris_ovvv = eris_ovvv.reshape(p1-p0,nvir,nvir,nvir)\n\n        l1new[p0:p1] += numpy.einsum('iabc,bc->ia', eris_ovvv, mba1) * 2\n        l1new[p0:p1] -= numpy.einsum('ibca,bc->ia', eris_ovvv, mba1)\n        #:l2new[p0:p1] += numpy.einsum('ic,jbac->jiba', l1, eris_ovvv)\n        tmp = lib.dot(l1, eris_ovvv.reshape(-1,nvir).T)\n        l2new[p0:p1] += tmp.reshape(nocc,-1,nvir,nvir).transpose(1,0,2,3)\n        tmp = None\n        m4buf = numpy.empty((blksize,nocc,nvir,nvir))\n        eris_ovvv = _cp(eris_ovvv.transpose(0,2,1,3).reshape(-1,nvir**2))\n        for j0, j1 in prange(0, nocc, blksize):\n            #:m4 = numpy.einsum('ijkd,kadb->ijab', l2t1[j0:j1,:,p0:p1], eris_ovvv)\n            m4 = m4buf[:j1-j0]\n            lib.dot(_cp(l2t1[j0:j1,:,p0:p1].reshape((j1-j0)*nocc,-1)),\n                    eris_ovvv, 1, m4.reshape(-1,nvir**2))\n            l2new[j0:j1] -= m4\n            l1new[j0:j1] -= numpy.einsum('ijab,jb->ia', m4, t1) * 2\n            l1new -= numpy.einsum('ijab,ia->jb', m4, t1[j0:j1]) * 2\n            l1new += numpy.einsum('jiab,jb->ia', m4, t1[j0:j1])\n            l1new[j0:j1] += numpy.einsum('jiab,ia->jb', m4, t1)\n        eris_ovvv = m4buf = m4 = None\n#==== mem usage nvir**3*2 + nocc*nvir**2\n\n        eris_ovov = _cp(eris.ovov[p0:p1])\n        l1new[p0:p1] += numpy.einsum('jb,iajb->ia', l1, eris_ovov) * 2\n        for i in range(p1-p0):\n            l2new[p0+i] += eris_ovov[i].transpose(1,0,2) * .5\n        #:l2new[p0:p1] -= numpy.einsum('icjb,ca->ijab', eris_ovov, mba1)\n        #:l2new[p0:p1] -= numpy.einsum('jbka,ik->jiba', eris_ovov, mij1)\n        tmp = numpy.empty((nocc,nvir,nvir))\n        for j in range(p0,p1):\n            lib.dot(eris_ovov[j-p0].reshape(nvir,-1).T, mba1, 1,\n                    tmp.reshape(-1,nvir))\n            l2new[j] -= tmp.transpose(0,2,1)\n            lib.dot(mij1, _cp(eris_ovov[j-p0].transpose(1,0,2).reshape(nocc,-1)),\n                    -1, l2new[j].reshape(nocc,-1), 1)\n        tmp = None\n        l1new[p0:p1] += numpy.einsum('iajb,jb->ia', eris_ovov, mia1) * 2\n        l1new[p0:p1] -= numpy.einsum('ibja,jb->ia', eris_ovov, mia1)\n        m4buf = numpy.empty((blksize,nocc,nvir,nvir))\n        for j0, j1 in prange(0, nocc, blksize):\n            #:m4 = numpy.einsum('kalb,ijkl->ijab', eris_ovov, l2tau[j0:j1,:,p0:p1])\n            m4 = m4buf[:j1-j0]\n            lib.dot(l2tau[j0:j1,:,p0:p1].reshape((j1-j0)*nocc,-1).copy(),\n                    _cp(eris_ovov.transpose(0,2,1,3).reshape(-1,nvir**2)),\n                    .5, m4.reshape(-1,nvir**2))\n            l2new[j0:j1] += m4\n            l1new[j0:j1] += numpy.einsum('ijab,jb->ia', m4, t1) * 4\n            l1new[j0:j1] -= numpy.einsum('ijba,jb->ia', m4, t1) * 2\n        eris_ovov = m4buf = m4 = None\n#==== mem usage nocc*nvir**2 * 3\n\n        eris_oovv = _cp(eris.oovv[p0:p1])\n        l1new[p0:p1] -= numpy.einsum('jb,ijba->ia', l1, eris_oovv)\n        eris_oovv = None\n\n        saved_wooov = _cp(saved.wooov[p0:p1])\n        #:l1new[p0:p1] -= numpy.einsum('jkca,ijkc->ia', l2, saved_wooov)\n        l1new[p0:p1] -= lib.dot(saved_wooov.reshape(p1-p0,-1),\n                                l2.reshape(-1,nvir))\n        saved_wovvv = _cp(saved.wovvv[p0:p1])\n        #:l1new += numpy.einsum('kibc,kabc->ia', l2[p0:p1], saved_wovvv)\n        for j in range(p1-p0):\n            lib.dot(l2[p0+j].reshape(nocc,-1),\n                    saved_wovvv[j].reshape(nvir,-1).T, 1, l1new, 1)\n        saved_wooov = saved_wovvv = None\n#==== mem usage nvir**3 + nocc**2*nvir\n\n        saved_wOvOv = _cp(saved.wOvOv[p0:p1])\n        tmp_ovov = _cp(saved.wOVov[p0:p1]) * 2\n        tmp_ovov += saved_wOvOv\n        tmp_ovov = lib.transpose(tmp_ovov.reshape(-1,nov)).reshape(nocc,nvir,-1,nvir)\n        tmp1 = numpy.empty((p1-p0,nvir,nocc,nvir))\n        tmp = numpy.empty((blksize,nvir,nocc,nvir))\n        for j0, j1 in prange(0, nocc, blksize):\n            #:tmp = l2[j0:j1].transpose(0,2,1,3) - l2[j0:j1].transpose(0,3,1,2)*.5\n            #:l2new[p0:p1] += numpy.einsum('kcia,kcjb->jiba', tmp, tmp_ovov[j0:j1])\n            for i in range(j1-j0):\n                tmp[i] = -.5 * l2[j0+i].transpose(2,0,1)\n                tmp[i] += l2[j0+i].transpose(1,0,2)\n            lib.dot(tmp_ovov[j0:j1].reshape((j1-j0)*nvir,-1).T,\n                    tmp[:j1-j0].reshape((j1-j0)*nvir,-1), 1, tmp1.reshape(-1,nov))\n            l2new[p0:p1] += tmp1.transpose(0,2,1,3)\n        tmp = tmp1 = tmp_ovov = None\n#==== mem usage nocc*nvir**2 * 5\n\n        #:tmp = numpy.einsum('jkca,ibkc->ijab', l2, saved_wOvOv)\n        tmp = numpy.empty((p1-p0,nvir,nvir))\n        for j in range(nocc):\n            lib.dot(saved_wOvOv.reshape(-1,nov), l2[j].reshape(nov,-1), 1,\n                    tmp.reshape(-1,nvir))\n            l2new[p0:p1,j] += tmp.transpose(0,2,1)\n            l2new[p0:p1,j] += tmp * .5\n        saved_wOvOv = tmp = None\n\n        saved_woooo = _cp(saved.woooo[p0:p1])\n        #:m3 = numpy.einsum('klab,ijkl->ijab', l2, saved_woooo)\n        m3 = lib.dot(saved_woooo.reshape(-1,nocc**2),\n                     l2.reshape(nocc**2,-1), .5).reshape(-1,nocc,nvir,nvir)\n        l2new[p0:p1] += m3\n        l1new[p0:p1] += numpy.einsum('ijab,jb->ia', m3, t1) * 4\n        l1new[p0:p1] -= numpy.einsum('ijba,jb->ia', m3, t1) * 2\n        saved_woooo = m3 = None\n        time1 = log.timer_debug1('lambda pass [%d:%d]'%(p0, p1), *time1)\n\n    mo_e = eris.fock.diagonal()\n    eia = lib.direct_sum('i-a->ia', mo_e[:nocc], mo_e[nocc:])\n    l1new /= eia\n    l1new += l1\n\n#    l2new = l2new + l2new.transpose(1,0,3,2)\n#    l2new /= lib.direct_sum('ia+jb->ijab', eia, eia)\n#    l2new += l2\n    ij = 0\n    for i in range(nocc):\n        for j in range(i):\n            dab = lib.direct_sum('a+b->ab', eia[i], eia[j])\n            tmp = (l2new[i,j]+l2new[j,i].T) / dab + l2[i,j]\n            l2new[i,j] = tmp\n            l2new[j,i] = tmp.T\n            ij += 1\n        dab = lib.direct_sum('a+b->ab', eia[i], eia[i])\n        l2new[i,i] = (l2new[i,i]+l2new[i,i].T)/dab + l2[i,i]\n        ij += 1\n\n    time0 = log.timer_debug1('update l1 l2', *time0)\n    return l1new, l2new\n\ndef prange(start, end, step):\n    for i in range(start, end, step):\n        yield i, min(i+step, end)\n\ndef _cp(a):\n    return numpy.array(a, copy=False, order='C')\n\n\nif __name__ == '__main__':\n    from pyscf import gto\n    from pyscf import scf\n    from pyscf.cc import ccsd\n\n    mol = gto.M()\n    mf = scf.RHF(mol)\n\n    mcc = ccsd.CCSD(mf)\n\n    numpy.random.seed(12)\n    nocc = 5\n    nmo = 12\n    nvir = nmo - nocc\n    eri0 = numpy.random.random((nmo,nmo,nmo,nmo))\n    eri0 = ao2mo.restore(1, ao2mo.restore(8, eri0, nmo), nmo)\n    fock0 = numpy.random.random((nmo,nmo))\n    fock0 = fock0 + fock0.T + numpy.diag(range(nmo))*2\n    t1 = numpy.random.random((nocc,nvir))\n    t2 = numpy.random.random((nocc,nocc,nvir,nvir))\n    t2 = t2 + t2.transpose(1,0,3,2)\n    l1 = numpy.random.random((nocc,nvir))\n    l2 = numpy.random.random((nocc,nocc,nvir,nvir))\n    l2 = l2 + l2.transpose(1,0,3,2)\n\n    eris = lambda:None\n    eris.oooo = eri0[:nocc,:nocc,:nocc,:nocc].copy()\n    eris.ooov = eri0[:nocc,:nocc,:nocc,nocc:].copy()\n    eris.ovoo = eri0[:nocc,nocc:,:nocc,:nocc].copy()\n    eris.oovv = eri0[:nocc,:nocc,nocc:,nocc:].copy()\n    eris.ovov = eri0[:nocc,nocc:,:nocc,nocc:].copy()\n    idx = numpy.tril_indices(nvir)\n    eris.ovvv = eri0[:nocc,nocc:,nocc:,nocc:][:,:,idx[0],idx[1]].copy()\n    eris.vvvv = ao2mo.restore(4,eri0[nocc:,nocc:,nocc:,nocc:],nvir)\n    eris.fock = fock0\n\n    saved = make_intermediates(mcc, t1, t2, eris)\n    l1new, l2new = update_amps(mcc, t1, t2, l1, l2, eris, saved)\n    print(abs(l1new).sum()-38172.7896467303)\n    print(numpy.dot(l1new.flatten(), numpy.arange(35)) - 739312.005491083)\n    print(numpy.dot(l1new.flatten(), numpy.sin(numpy.arange(35)))-7019.50937051188)\n    print(numpy.dot(numpy.sin(l1new.flatten()), numpy.arange(35))-69.6652346635955)\n\n    print(abs(l2new).sum()-72035.4931071527)\n    print(abs(l2new-l2new.transpose(1,0,3,2)).sum())\n    print(numpy.dot(l2new.flatten(), numpy.arange(35**2)) - 48427109.5409886)\n    print(numpy.dot(l2new.flatten(), numpy.sin(numpy.arange(35**2)))-137.758016736487)\n    print(numpy.dot(numpy.sin(l2new.flatten()), numpy.arange(35**2))-507.656936701192)\n\n\n    mol = gto.Mole()\n    mol.verbose = 0\n    mol.atom = [\n        [8 , (0. , 0.     , 0.)],\n        [1 , (0. , -0.757 , 0.587)],\n        [1 , (0. , 0.757  , 0.587)]]\n\n    mol.basis = 'cc-pvdz'\n    mol.build()\n    rhf = scf.RHF(mol)\n    rhf.conv_tol = 1e-16\n    rhf.scf()\n\n    mcc = ccsd.CCSD(rhf)\n    mcc.conv_tol = 1e-12\n    ecc, t1, t2 = mcc.kernel()\n\n    nmo = rhf.mo_energy.size\n    fock0 = numpy.diag(rhf.mo_energy)\n    nocc = mol.nelectron // 2\n    nvir = nmo - nocc\n\n    eris = mcc.ao2mo()\n    conv, l1, l2 = kernel(mcc, eris, t1, t2, tol=1e-8)\n    print(numpy.linalg.norm(l1)-0.0132626841292)\n    print(numpy.linalg.norm(l2)-0.212575609057)\n\n    from pyscf.cc import ccsd_rdm\n    dm1 = ccsd_rdm.make_rdm1(mcc, t1, t2, l1, l2)\n    dm2 = ccsd_rdm.make_rdm2(mcc, t1, t2, l1, l2)\n    h1 = reduce(numpy.dot, (rhf.mo_coeff.T, rhf.get_hcore(), rhf.mo_coeff))\n    eri = ao2mo.full(rhf._eri, rhf.mo_coeff)\n    eri = ao2mo.restore(1, eri, nmo).reshape((nmo,)*4)\n    e1 = numpy.einsum('pq,pq', h1, dm1)\n    e2 = numpy.einsum('pqrs,pqrs', eri, dm2) * .5\n    print(e1+e2+mol.energy_nuc() - rhf.e_tot - ecc)\n", "meta": {"hexsha": "2dc4b236ee47c72232f9d9a960767c12b2ae84d2", "size": 28427, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/cc/ccsd_lambda.py", "max_stars_repo_name": "nmardirossian/pyscf", "max_stars_repo_head_hexsha": "57c8912dcfcc1157a822feede63df54ed1067115", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-05-02T19:55:30.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-02T19:55:30.000Z", "max_issues_repo_path": "pyscf/cc/ccsd_lambda.py", "max_issues_repo_name": "nmardirossian/pyscf", "max_issues_repo_head_hexsha": "57c8912dcfcc1157a822feede63df54ed1067115", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscf/cc/ccsd_lambda.py", "max_forks_repo_name": "nmardirossian/pyscf", "max_forks_repo_head_hexsha": "57c8912dcfcc1157a822feede63df54ed1067115", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-12-06T03:10:50.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-06T03:10:50.000Z", "avg_line_length": 44.2099533437, "max_line_length": 102, "alphanum_fraction": 0.5555633728, "include": true, "reason": "import numpy", "num_tokens": 10969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.18812794099441402}}
{"text": "import torch\r\nfrom torch.nn import functional as F\r\nfrom torch.utils.data import Dataset, DataLoader\r\n\r\nimport argparse\r\nimport os\r\n\r\nfrom tqdm import tqdm\r\nimport numpy as np\r\nfrom scipy import linalg\r\nfrom PIL import Image\r\nfrom torchvision import datasets, transforms, utils\r\nfrom torchvision.datasets.folder import find_classes\r\nfrom torchvision.models import inception_v3, Inception3\r\n\r\nparser = argparse.ArgumentParser(description='FID score calculator')\r\nparser.add_argument('--img', required=True, help='path to image directory')\r\nparser.add_argument('--batch', default=64, type=int, help='batch size')\r\nparser.add_argument('--sample', default=5000, type=int,\r\n                    help='number of samples generated for evaluation')\r\nparser.add_argument('--code', default=128, type=int,\r\n                    help='code size for generator')\r\nparser.add_argument('--model', default='dcgan', choices=['dcgan', 'resnet'],\r\n                    help='choice model class')\r\nparser.add_argument('checkpoint', metavar='CHECKPOINT',\r\n                    help='checkpoint of generator model')\r\n\r\n\r\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\r\n\r\n\r\ndef forward(self, x):\r\n    x = F.interpolate(x, size=(299, 299), mode='bilinear', align_corners=True)\r\n    F.interpolate()\r\n    \r\n    x = self.Conv2d_1a_3x3(x)  # 299 x 299 x 3\r\n    x = self.Conv2d_2a_3x3(x)  # 149 x 149 x 32\r\n    x = self.Conv2d_2b_3x3(x)  # 147 x 147 x 32\r\n    x = F.max_pool2d(x, kernel_size=3, stride=2)  # 147 x 147 x 64\r\n\r\n    x = self.Conv2d_3b_1x1(x)  # 73 x 73 x 64\r\n    x = self.Conv2d_4a_3x3(x)  # 73 x 73 x 80\r\n    x = F.max_pool2d(x, kernel_size=3, stride=2)  # 71 x 71 x 192\r\n\r\n    x = self.Mixed_5b(x)  # 35 x 35 x 192\r\n    x = self.Mixed_5c(x)  # 35 x 35 x 256\r\n    x = self.Mixed_5d(x)  # 35 x 35 x 288\r\n\r\n    x = self.Mixed_6a(x)  # 35 x 35 x 288\r\n    x = self.Mixed_6b(x)  # 17 x 17 x 768\r\n    x = self.Mixed_6c(x)  # 17 x 17 x 768\r\n    x = self.Mixed_6d(x)  # 17 x 17 x 768\r\n    x = self.Mixed_6e(x)  # 17 x 17 x 768\r\n\r\n    x = self.Mixed_7a(x)  # 17 x 17 x 768\r\n    x = self.Mixed_7b(x)  # 8 x 8 x 1280\r\n    x = self.Mixed_7c(x)  # 8 x 8 x 2048\r\n\r\n    x = F.avg_pool2d(x, kernel_size=8)  # 8 x 8 x 2048\r\n\r\n    return x.squeeze()  # 1 x 1 x 2048\r\n\r\n\r\ndef load_patched_inception_v3():\r\n    inception = inception_v3(pretrained=True)\r\n    inception.eval()\r\n    inception.forward = forward.__get__(inception, Inception3)\r\n\r\n    return inception.to(device)\r\n\r\n\r\ntransform = transforms.Compose([\r\n    transforms.Resize(128),\r\n    transforms.CenterCrop(128),\r\n    transforms.ToTensor(),\r\n    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\r\n\r\n\r\nclass ImageData(Dataset):\r\n    def __init__(self, root, transform=transform):\r\n        self.root = root\r\n        self.transform = transform\r\n        self.images = os.listdir(root)\r\n\r\n    def __getitem__(self, index):\r\n        img = os.path.join(self.root, self.images[index])\r\n        img = Image.open(img).convert('RGB')\r\n\r\n        if self.transform is not None:\r\n            img = transform(img)\r\n\r\n        return img\r\n\r\n    def __len__(self):\r\n        return len(self.images)\r\n\r\n\r\nif __name__ == '__main__':\r\n    args = parser.parse_args()\r\n    print(args)\r\n\r\n    eps = 1e-6\r\n\r\n    inception = load_patched_inception_v3()\r\n    _, class2id = find_classes(args.img)\r\n    total_class = len(class2id)\r\n\r\n    if args.model == 'dcgan':\r\n        from model import Generator\r\n\r\n    elif args.model == 'resnet':\r\n        from model_resnet import Generator\r\n\r\n    generator = Generator(args.code, total_class).to(device)\r\n    generator.load_state_dict(torch.load(args.checkpoint))\r\n    generator.eval()\r\n\r\n    fids = []\r\n\r\n    for class_name, id in class2id.items():\r\n        dataloader = DataLoader(ImageData(os.path.join(args.img, class_name)),\r\n                                batch_size=args.batch, num_workers=4)\r\n        real_feature = []\r\n        with torch.no_grad():\r\n            for image in tqdm(dataloader,\r\n                              desc='Extract features of real images'):\r\n                image = image.to(device)\r\n                features = inception(image).detach().cpu().numpy()\r\n                real_feature.append(features)\r\n\r\n        real_feature = np.concatenate(real_feature)\r\n        real_mean = np.mean(real_feature, 0)\r\n        real_cov = np.cov(real_feature, rowvar=False)\r\n        del real_feature\r\n\r\n        sample_feature = []\r\n        with torch.no_grad():\r\n            n_iter = args.sample // args.batch\r\n            resid = args.sample - n_iter * args.batch\r\n            n_samples = [args.batch] * n_iter\r\n            if resid != 0:\r\n                n_samples += [resid]\r\n            for i in tqdm(n_samples,\r\n                          desc='Extract features of fake images'):\r\n                input_class = torch.full([i], id, dtype=torch.long) \\\r\n                    .to(device)\r\n                code = torch.randn(i, args.code).to(device)\r\n                sample = generator(code, input_class)\r\n                features = inception(sample).detach().cpu().numpy()\r\n                sample_feature.append(features)\r\n\r\n        sample_feature = np.concatenate(sample_feature)\r\n        sample_mean = np.mean(sample_feature, 0)\r\n        sample_cov = np.cov(sample_feature, rowvar=False)\r\n        del sample_feature\r\n\r\n        # Came from https://github.com/bioinf-jku/TTUR\r\n\r\n        cov_sqrt, _ = linalg.sqrtm(sample_cov @ real_cov, disp=False)\r\n        if not np.isfinite(cov_sqrt).all():\r\n            print('Product of cov matrices is singular')\r\n            offset = np.eye(sample_cov.shape[0]) * eps\r\n            cov_sqrt = linalg.sqrtm((sample_cov + offset)\r\n                                    @ (real_cov + offset))\r\n\r\n        if np.iscomplexobj(cov_sqrt):\r\n            if not np.allclose(np.diagonal(cov_sqrt).imag, 0, atol=1e-3):\r\n                m = np.max(np.abs(cov_sqrt.imag))\r\n                raise ValueError(f'Imaginary component {m}')\r\n\r\n            cov_sqrt = cov_sqrt.real\r\n\r\n        mean_diff = sample_mean - real_mean\r\n        mean_norm = mean_diff @ mean_diff\r\n\r\n        trace = np.trace(sample_cov) + np.trace(real_cov) \\\r\n            - 2 * np.trace(cov_sqrt)\r\n\r\n        fid = mean_norm + trace\r\n\r\n        print(f'FID score of class {id} ({class_name}):', fid)\r\n        fids.append(fid)\r\n\r\n    print(f'Mean FID is: {sum(fids) / len(fids)}')", "meta": {"hexsha": "6f21503a7d85e21713acec5f275de53f7dfbca45", "size": 6343, "ext": "py", "lang": "Python", "max_stars_repo_path": "fid.py", "max_stars_repo_name": "pjuangph/sagan-pytorch", "max_stars_repo_head_hexsha": "b766f0c53184cfc02b4220329585a4d59bbfb2c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fid.py", "max_issues_repo_name": "pjuangph/sagan-pytorch", "max_issues_repo_head_hexsha": "b766f0c53184cfc02b4220329585a4d59bbfb2c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fid.py", "max_forks_repo_name": "pjuangph/sagan-pytorch", "max_forks_repo_head_hexsha": "b766f0c53184cfc02b4220329585a4d59bbfb2c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.472826087, "max_line_length": 79, "alphanum_fraction": 0.5940406748, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.18812793790806182}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nA submodule with classes used for supernova model files stored on disk. It\r\nassumes models are available in a format usable by the AstroPy unified table\r\nreader; see https://docs.astropy.org/en/stable/index.html for details.\r\n\r\nBased on the ASTERIA (https://github.com/IceCubeOpenSource/ASTERIA) models\r\ndeveloped by Navya Uberoi and Spencer Griswold.\r\n\r\nUpdated summer 2020 by Jim Kneller & Arkin Worlikar.\r\n\"\"\"\r\n\r\nfrom abc import abstractmethod, ABC\r\nfrom enum import IntEnum\r\n\r\nimport astropy\r\nfrom astropy.io import ascii\r\nfrom astropy.table import Table, join\r\nfrom astropy.units.quantity import Quantity\r\n\r\nimport matplotlib as mpl\r\nimport matplotlib.pyplot as plt\r\n\r\nimport numpy as np\r\nfrom scipy.interpolate import interp1d\r\nfrom scipy.special import loggamma\r\n\r\nimport os\r\nimport logging\r\nimport re\r\n\r\nimport tarfile\r\nimport h5py\r\n\r\nfrom .neutrino import Flavor\r\nfrom .flavor_transformation import *\r\n\r\n\r\ndef get_value(x):\r\n    \"\"\"If quantity x has is an astropy Quantity with units, return just the\r\n    value.\r\n\r\n    Parameters\r\n    ----------\r\n    x : Quantity, float, or ndarray\r\n        Input quantity.\r\n\r\n    Returns\r\n    -------\r\n    value : float or ndarray\r\n    \"\"\"\r\n    if type(x) == Quantity:\r\n        return x.value\r\n    return x\r\n\r\n\r\ndef get_closest(arr, x):\r\n    \"\"\"Get index of closest element in an array to input value.\r\n\r\n    Parameters\r\n    ----------\r\n    arr : list or ndarray\r\n        Array of values.\r\n    x : float or int or str\r\n        Value to search.\r\n\r\n    Returns\r\n    -------\r\n    idx : int\r\n        Index of closest element in the array.\r\n    \"\"\"\r\n    return np.abs(np.asarray(arr) - x).argmin()\r\n\r\n\r\nclass SupernovaModel(ABC):\r\n    \"\"\"Base class defining an interface to a supernova model.\"\"\"\r\n    \r\n    def __init__(self):\r\n        pass\r\n    \r\n    @abstractmethod\r\n    def get_time(self):\r\n        \"\"\"Returns\r\n        -------\r\n            returns array of snapshot times from the simulation\r\n        \"\"\"\r\n        pass\r\n\r\n    @abstractmethod\r\n    def get_initialspectra(self, t, E):\r\n        \"\"\"Get neutrino spectra at the source.\r\n\r\n        Parameters\r\n        ----------\r\n        t : float\r\n            Time to evaluate spectra.\r\n        E : float or ndarray\r\n            Energies to evaluate spectra.\r\n\r\n        Returns\r\n        -------\r\n        initialspectra : dict\r\n            Dictionary of neutrino spectra, keyed by neutrino flavor.\r\n        \"\"\"\r\n        pass\r\n\r\n    def get_oscillatedspectra(self, t, E, flavor_xform):\r\n        \"\"\"Get neutrino spectra after applying oscillation.\r\n\r\n        Parameters\r\n        ----------\r\n        t : astropy.Quantity\r\n            Time to evaluate initial and oscillated spectra.\r\n        E : astropy.Quantity or ndarray\r\n            Energies to evaluate the initial and oscillated spectra.\r\n        flavor_xform : FlavorTransformation\r\n            An instance from the flavor_transformation module.\r\n\r\n        Returns\r\n        -------\r\n        oscillatedspectra : dict\r\n            Dictionary of oscillated spectra, keyed by neutrino flavor.\r\n        \"\"\"\r\n        initialspectra = self.get_initialspectra(t, E)\r\n        oscillatedspectra = {}\r\n\r\n        oscillatedspectra[Flavor.NU_E] = \\\r\n            flavor_xform.prob_ee(t, E) * initialspectra[Flavor.NU_E] + \\\r\n            flavor_xform.prob_ex(t, E) * initialspectra[Flavor.NU_X]\r\n\r\n        oscillatedspectra[Flavor.NU_X] = \\\r\n            flavor_xform.prob_xe(t, E) * initialspectra[Flavor.NU_E] + \\\r\n            flavor_xform.prob_xx(t, E) * initialspectra[Flavor.NU_X] \r\n\r\n        oscillatedspectra[Flavor.NU_E_BAR] = \\\r\n            flavor_xform.prob_eebar(t, E) * initialspectra[Flavor.NU_E_BAR] + \\\r\n            flavor_xform.prob_exbar(t, E) * initialspectra[Flavor.NU_X_BAR]\r\n\r\n        oscillatedspectra[Flavor.NU_X_BAR] = \\\r\n            flavor_xform.prob_xebar(t, E) * initialspectra[Flavor.NU_E_BAR] + \\\r\n            flavor_xform.prob_xxbar(t, E) * initialspectra[Flavor.NU_X_BAR] \r\n\r\n        return oscillatedspectra    \r\n\r\n\r\nclass Nakazato_2013(SupernovaModel):\r\n    \"\"\"Set up a model based on simulations from Nakazato et al., ApJ S 205:2,\r\n    2013 and ApJ 804:75, 2015. See also http://asphwww.ph.noda.tus.ac.jp/snn/.\r\n    \"\"\"\r\n\r\n    def __init__(self, filename):\r\n        \"\"\"Initialize model.\r\n\r\n        Parameters\r\n        ----------\r\n        filename : str\r\n            Absolute or relative path to FITS file with model data.\r\n        \"\"\"\r\n        # Store model metadata.\r\n        if 't_rev' in filename:\r\n            self.progenitor_mass = float(filename.split('-')[-1].strip('s%.fits')) * u.Msun\r\n            self.revival_time = float(filename.split('-')[-2].strip('t_rev%ms')) * u.ms\r\n            self.metallicity = float(filename.split('-')[-3].strip('z%'))\r\n            self.EOS = filename.split('-')[-4].upper()\r\n        # No revival time because the explosion \"failed\" (BH formation).\r\n        else:\r\n            self.progenitor_mass = float(filename.split('-')[-1].strip('s%.fits')) * u.Msun\r\n            self.metallicity = float(filename.split('-')[-2].strip('z%'))\r\n            self.revival_time = 0 * u.ms\r\n            self.EOS = filename.split('-')[-4].upper()\r\n\r\n        # Read FITS table using the astropy reader.\r\n        simtab = Table.read(filename)\r\n        self.filename = os.path.basename(filename)\r\n\r\n        # Get grid of model times.\r\n        self.time = simtab['TIME'].to('s')\r\n\r\n        # Set up dictionary of luminosity, mean energy and shape parameter\r\n        # alpha, keyed by neutrino flavor (NU_E, NU_X, NU_E_BAR, NU_X_BAR).\r\n        self.luminosity = {}\r\n        self.meanE = {}\r\n        self.pinch = {}\r\n\r\n        for flavor in Flavor:\r\n            # Note: file only contains NU_E, NU_E_BAR, and NU_X, so double up\r\n            # the use of NU_X for NU_X_BAR.\r\n            _flav = Flavor.NU_X if flavor == Flavor.NU_X_BAR else flavor\r\n\r\n            self.luminosity[flavor] = simtab['L_{}'.format(_flav.name)].to('erg/s')\r\n            self.meanE[flavor] = simtab['E_{}'.format(_flav.name)].to('MeV')\r\n            self.pinch[flavor] = simtab['ALPHA_{}'.format(_flav.name)]\r\n\r\n    def get_time(self):\r\n        \"\"\"Get grid of model times.\r\n\r\n        Returns\r\n        -------\r\n        time : ndarray\r\n            Grid of times used in the model.\r\n        \"\"\"\r\n        return self.time\r\n    \r\n    def get_initialspectra(self, t, E):\r\n        \"\"\"Get neutrino spectra/luminosity at the source.\r\n\r\n        Parameters\r\n        ----------\r\n        t : float or astropy.Quantity\r\n            Time to evaluate initial spectra.\r\n        E : float or ndarray of astropy.Quantity\r\n            Energies to evaluate the initial spectra.\r\n\r\n        Returns\r\n        -------\r\n        initialspectra : dict\r\n            Dictionary of model spectra, keyed by neutrino flavor.\r\n        \"\"\"\r\n        initialspectra = {}\r\n\r\n        # Avoid division by zero in energy PDF below.\r\n        E[E==0] = np.finfo(float).eps * E.unit\r\n\r\n        # Estimate L(t), <E_nu(t)> and alpha(t). Express all energies in erg.\r\n        E = E.to('erg').value\r\n\r\n        # Make sure input time uses the same units as the model time grid, or\r\n        # the interpolation will not work correctly.\r\n        t = t.to(self.time.unit)\r\n\r\n        for flavor in Flavor:\r\n            # Use np.interp rather than scipy.interpolate.interp1d because it\r\n            # can handle dimensional units (astropy.Quantity).\r\n            L  = get_value(np.interp(t, self.time, self.luminosity[flavor].to('erg/s')))\r\n            Ea = get_value(np.interp(t, self.time, self.meanE[flavor].to('erg')))\r\n            a  = np.interp(t, self.time, self.pinch[flavor])\r\n\r\n            # For numerical stability, evaluate log PDF and then exponentiate.\r\n            initialspectra[flavor] = \\\r\n                np.exp(np.log(L) - (2+a)*np.log(Ea) + (1+a)*np.log(1+a) \r\n                       - loggamma(1+a) + a*np.log(E) - (1+a)*(E/Ea)) / (u.erg * u.s)\r\n\r\n        return initialspectra\r\n\r\n    def __repr__(self):\r\n        \"\"\"Default representation of the model.\r\n        \"\"\"\r\n        mod = 'Nakazato_2013 Model: {}\\n'.format(self.filename)\r\n        s = ['Progenitor mass : {}'.format(self.progenitor_mass),\r\n             'Metallicity     : {}'.format(self.metallicity),\r\n             'Revival time    : {}'.format(self.revival_time),\r\n             'Eq. of state    : {}'.format(self.EOS)\r\n             ]\r\n        return mod + '\\n'.join(s)\r\n        \r\n    def _repr_markdown_(self):\r\n        \"\"\"Markdown representation of the model, for Jupyter notebooks.\r\n        \"\"\"\r\n        mod = '**Nakazato_2013 Model**: {}\\n\\n'.format(self.filename)\r\n        s = ['|Parameter|Value|',\r\n             '|:---------|:-----:|',\r\n             '|Progenitor mass | ${0.value:g}$ {0.unit:latex}|'.format(self.progenitor_mass),\r\n             '|Metallicity | ${:g}$|'.format(self.metallicity),\r\n             '|Revival time | ${0.value:g}$ {0.unit:latex}|'.format(self.revival_time),\r\n             '|EOS | {}|'.format(self.EOS)\r\n             ]\r\n        return mod + '\\n'.join(s)\r\n\r\n\r\nclass Sukhbold_2015(SupernovaModel):\r\n    \"\"\"Set up a model based on simulations from Sukhbold et al., ApJ 821:38,2016. Models were shared privately by email.\r\n    \"\"\"\r\n\r\n    def __init__(self, filename):\r\n        \"\"\"Initialize model.\r\n\r\n        Parameters\r\n        ----------\r\n        filename : str\r\n            Absolute or relative path to FITS file with model data.\r\n        \"\"\"\r\n        # Store model metadata.\r\n        self.progenitor_mass = float(filename.split('-')[-1].strip('z%.fits')) * u.Msun\r\n        self.EOS = filename.split('-')[-2]\r\n\r\n        # Read FITS table using the astropy unified Table reader.\r\n        simtab = Table.read(filename)\r\n        self.filename = os.path.basename(filename)\r\n\r\n        # Get grid of model times.\r\n        self.time = simtab['TIME'].to('s')\r\n\r\n        # Set up dictionary of luminosity, mean energy, and shape parameter,\r\n        # keyed by neutrino flavor (NU_E, NU_X, NU_E_BAR, NU_X_BAR).\r\n        self.luminosity = {}\r\n        self.meanE = {}\r\n        self.pinch = {}\r\n\r\n        for flavor in Flavor:\r\n            self.luminosity[flavor] = simtab['L_{}'.format(flavor.name)].to('erg/s')\r\n            self.meanE[flavor] = simtab['E_{}'.format(flavor.name)].to('MeV')\r\n            self.pinch[flavor] = simtab['ALPHA_{}'.format(flavor.name)]\r\n            \r\n    def get_time(self):\r\n        \"\"\"Get grid of model times.\r\n\r\n        Returns\r\n        -------\r\n        time : ndarray\r\n            Grid of times used in the model.\r\n        \"\"\"\r\n        return self.time\r\n    \r\n    def get_initialspectra(self,t,E):\r\n        \"\"\"Get neutrino spectra/luminosity curves after oscillation.\r\n\r\n        Parameters\r\n        ----------\r\n        t : astropy.Quantity\r\n            Time to evaluate initial spectra.\r\n        E : astropy.Quantity or ndarray\r\n            Energies to evaluate the initial spectra.\r\n\r\n        Returns\r\n        -------\r\n        initialspectra : dict\r\n            Dictionary of model spectra, keyed by neutrino flavor.\r\n        \"\"\"\r\n        initialspectra = {}\r\n\r\n        # Avoid division by zero in energy PDF below.\r\n        E[E==0] = np.finfo(float).eps * E.unit\r\n\r\n        # Estimate L(t), <E_nu(t)>, and alpha(t). Express all energies in erg.\r\n        E = E.to('erg').value\r\n\r\n        # Make sure input time uses the same units as the global time grid or\r\n        # the interpolation will not work properly.\r\n        t = t.to(self.time.unit)\r\n\r\n        for flavor in Flavor:\r\n            L  = get_value(np.interp(t, self.time, self.luminosity[flavor].to('erg/s')))\r\n            Ea = get_value(np.interp(t, self.time, self.meanE[flavor].to('erg')))\r\n            a  = np.interp(t, self.time, self.pinch[flavor])\r\n\r\n            # For numerical stability, evaluate log PDF then exponentiate.\r\n            initialspectra[flavor] = \\\r\n                np.exp(np.log(L) - (2+a)*np.log(Ea) + (1+a)*np.log(1+a) \r\n                       - loggamma(1+a) + a*np.log(E) - (1+a)*(E/Ea)) / (u.erg * u.s)\r\n\r\n        return initialspectra\r\n\r\n    def __repr__(self):\r\n        \"\"\"Default representation of the model.\r\n        \"\"\"\r\n        mod = 'Sukhbold_2015 Model: {}\\n'.format(self.filename)\r\n        s = ['Progenitor mass : {}'.format(self.progenitor_mass),\r\n             'Eq. of state    : {}'.format(self.EOS)\r\n             ]\r\n        return mod + '\\n'.join(s)\r\n\r\n    def _repr_markdown_(self):\r\n        \"\"\"Markdown representation of the model, for Jupyter notebooks.\r\n        \"\"\"\r\n        mod = '**Sukhbold_2015 Model**: {}\\n\\n'.format(self.filename)\r\n        s = ['|Parameter|Value|',\r\n             '|:---------|:-----:|',\r\n             '|Progenitor mass | ${0.value:g}$ {0.unit:latex}|'.format(self.progenitor_mass),\r\n             '|EOS | {}|'.format(self.EOS)\r\n             ]\r\n        return mod + '\\n'.join(s)\r\n\r\n\r\nclass Bollig_2016(SupernovaModel):\r\n    \"\"\"Set up a model based on simulations from Bollig et al. (2016). Models were taken, with permission, from the Garching Supernova Archive.\r\n    \"\"\"\r\n    def __init__(self, filename, eos='LS220'):\r\n        \"\"\"Initialize model.\r\n\r\n        Parameters\r\n        ----------\r\n        filename : str\r\n            Absolute or relative path to file prefix, we add nue/nuebar/nux.\r\n        eos : string\r\n            Equation of state used in simulation.\r\n        \"\"\"\r\n        self.time = {}\r\n        self.luminosity = {}\r\n        self.meanE = {}\r\n        self.pinch = {}\r\n\r\n        # Store model metadata.\r\n        self.filename = os.path.basename(filename)\r\n        self.EOS = eos\r\n        self.progenitor_mass = float(self.filename.strip('s%c')) * u.Msun\r\n\r\n        # Read through the several ASCII files for the chosen simulation and\r\n        # merge the data into one giant table.\r\n        mergtab = None\r\n        for flavor in Flavor:\r\n            _flav = Flavor.NU_X if flavor == Flavor.NU_X_BAR else flavor\r\n            _sfx = _flav.name.replace('_', '').lower()\r\n            _filename = '{}_{}_{}'.format(filename, eos, _sfx)\r\n            _lname  = 'L_{}'.format(flavor.name)\r\n            _ename  = 'E_{}'.format(flavor.name)\r\n            _e2name = 'E2_{}'.format(flavor.name)\r\n            _aname  = 'ALPHA_{}'.format(flavor.name)\r\n\r\n            simtab = Table.read(_filename,\r\n                                names=['TIME', _lname, _ename, _e2name],\r\n                                format='ascii')\r\n            simtab['TIME'].unit = 's'\r\n            simtab[_lname].unit = '1e51 erg/s'\r\n            simtab[_aname] = (2*simtab[_ename]**2 - simtab[_e2name]) / (simtab[_e2name] - simtab[_ename]**2)\r\n            simtab[_ename].unit = 'MeV'\r\n            del simtab[_e2name]\r\n\r\n            if mergtab is None:\r\n                mergtab = simtab\r\n            else:\r\n                mergtab = join(mergtab, simtab, keys='TIME', join_type='left')\r\n                mergtab[_lname].fill_value = 0.\r\n                mergtab[_ename].fill_value = 0.\r\n                mergtab[_aname].fill_value = 0.\r\n        simtab = mergtab.filled()\r\n\r\n        self.time = simtab['TIME'].to('s')\r\n\r\n        for flavor in Flavor:\r\n            # Set the dictionary of luminosity, mean energy, and shape\r\n            # parameter keyed by NU_E, NU_X, NU_E_BAR, NU_X_BAR.\r\n            _lname  = 'L_{}'.format(flavor.name)\r\n            self.luminosity[flavor] = simtab[_lname].to('erg/s')\r\n\r\n            _ename  = 'E_{}'.format(flavor.name)\r\n            self.meanE[flavor] = simtab[_ename].to('MeV')\r\n\r\n            _aname  = 'ALPHA_{}'.format(flavor.name)\r\n            self.pinch[flavor] = simtab[_aname]\r\n\r\n    def get_time(self):\r\n        \"\"\"Get grid of model times.\r\n\r\n        Returns\r\n        -------\r\n        time : ndarray\r\n            Grid of times used in the model.\r\n        \"\"\"\r\n        return self.time\r\n\r\n    def get_initialspectra(self,t,E):\r\n        \"\"\"Get neutrino spectra/luminosity curves before oscillation.\r\n\r\n        Parameters\r\n        ----------\r\n        t : float\r\n            Time to evaluate initial spectra.\r\n        E : float or ndarray\r\n            Energies to evaluate the initial spectra.\r\n\r\n        Returns\r\n        -------\r\n        initialspectra : dict\r\n            Dictionary of model spectra, keyed by neutrino flavor.\r\n        \"\"\"\r\n        initialspectra = {}\r\n\r\n        # Avoid division by zero in energy PDF below.\r\n        E[E==0] = np.finfo(float).eps * E.unit\r\n\r\n        # Estimate L(t), <E_nu(t)> and alpha(t). Express all energies in erg.\r\n        E = E.to('erg').value\r\n\r\n        # Make sure input time uses the same units as the model time grid, or\r\n        # the interpolation will not work correctly.\r\n        t = t.to(self.time.unit)\r\n\r\n        for flavor in Flavor:\r\n            # Use np.interp rather than scipy.interpolate.interp1d because it\r\n            # can handle dimensional units (astropy.Quantity).\r\n            L  = get_value(np.interp(t, self.time, self.luminosity[flavor].to('erg/s')))\r\n            Ea = get_value(np.interp(t, self.time, self.meanE[flavor].to('erg')))\r\n            a  = np.interp(t, self.time, self.pinch[flavor])\r\n\r\n            # For numerical stability, evaluate log PDF and then exponentiate.\r\n            initialspectra[flavor] = \\\r\n                np.exp(np.log(L) - (2+a)*np.log(Ea) + (1+a)*np.log(1+a)\r\n                       - loggamma(1+a) + a*np.log(E) - (1+a)*(E/Ea)) / (u.erg * u.s)\r\n\r\n        return initialspectra\r\n\r\n    def __repr__(self):\r\n        \"\"\"Default representation of the model.\r\n        \"\"\"\r\n        mod = 'Bollig_2016 Model: {}\\n'.format(self.filename)\r\n        s = ['Progenitor mass : {}'.format(self.progenitor_mass),\r\n             'Eq. of state    : {}'.format(self.EOS)\r\n             ]\r\n        return mod + '\\n'.join(s)\r\n\r\n    def _repr_markdown_(self):\r\n        \"\"\"Markdown representation of the model, for Jupyter notebooks.\r\n        \"\"\"\r\n        mod = '**Bollig_2016 Model**: {}\\n\\n'.format(self.filename)\r\n        s = ['|Parameter|Value|',\r\n             '|:---------|:-----:|',\r\n             '|Progenitor mass | ${0.value:g}$ {0.unit:latex}|'.format(self.progenitor_mass),\r\n             '|EOS | {}|'.format(self.EOS)\r\n             ]\r\n        return mod + '\\n'.join(s)\r\n\r\n\r\nclass OConnor_2015(SupernovaModel):\r\n    \"\"\"Set up a model based on the black hole formation simulation in O'Connor (2015). \r\n    \"\"\"\r\n    def __init__(self, filename, eos='LS220'):\r\n        \"\"\"Initialize model.\r\n\r\n        Parameters\r\n        ----------\r\n        filename : str\r\n            Absolute or relative path to file prefix, we add nue/nuebar/nux\r\n        eos : string\r\n            Equation of state used in simulation\r\n        \"\"\"\r\n        simtab = Table.read(filename, \r\n                     names= ['TIME','L_NU_E','L_NU_E_BAR','L_NU_X',\r\n                                    'E_NU_E','E_NU_E_BAR','E_NU_X',\r\n                                    'RMS_NU_E','RMS_NU_E_BAR','RMS_NU_X'],\r\n                     format='ascii')\r\n\r\n        simtab['ALPHA_NU_E'] = (2.0*simtab['E_NU_E']**2 - simtab['RMS_NU_E']**2)/(simtab['RMS_NU_E']**2 - simtab['E_NU_E']**2)\r\n        simtab['ALPHA_NU_E_BAR'] = (2.0*simtab['E_NU_E_BAR']**2 - simtab['RMS_NU_E_BAR']**2)/(simtab['RMS_NU_E_BAR']**2 - simtab['E_NU_E_BAR']**2)\r\n        simtab['ALPHA_NU_X'] = (2.0*simtab['E_NU_X']**2 - simtab['RMS_NU_X']**2)/(simtab['RMS_NU_X']**2 - simtab['E_NU_X']**2)\r\n\r\n        # SYB: double-check on this factor of 4. Should be factor of 2?\r\n        simtab['L_NU_X'] /= 4.0\r\n\r\n        self.filename = 'OConnor2015_s40WH07_LS220'\r\n        self.EOS = eos\r\n        self.progenitor_mass = 40 * u.Msun\r\n\r\n        # Get grid of model times.\r\n        self.time = simtab['TIME'] * u.s\r\n\r\n        # Set up dictionary of luminosity, mean energy and shape parameter\r\n        # alpha, keyed by neutrino flavor (NU_E, NU_X, NU_E_BAR, NU_X_BAR).\r\n        self.luminosity = {}\r\n        self.meanE = {}\r\n        self.pinch = {}\r\n\r\n        for flavor in Flavor:\r\n            # Note: file only contains NU_E, NU_E_BAR, and NU_X, so double up\r\n            # the use of NU_X for NU_X_BAR.\r\n            _flav = Flavor.NU_X if flavor == Flavor.NU_X_BAR else flavor\r\n\r\n            self.luminosity[flavor] = simtab['L_{}'.format(_flav.name)] * u.erg/u.s\r\n            self.meanE[flavor] = simtab['E_{}'.format(_flav.name)] * u.MeV\r\n            self.pinch[flavor] = simtab['ALPHA_{}'.format(_flav.name)]\r\n\r\n    def get_time(self):\r\n        \"\"\"Get grid of model times.\r\n\r\n        Returns\r\n        -------\r\n        time : ndarray\r\n            Grid of times used in the model.\r\n        \"\"\"\r\n        return self.time\r\n\r\n    def get_initialspectra(self,t,E):\r\n        \"\"\"Get neutrino spectra/luminosity curves before oscillation.\r\n\r\n        Parameters\r\n        ----------\r\n        t : float\r\n            Time to evaluate initial and oscillated spectra.\r\n        E : float or ndarray\r\n            Energies to evaluate the initial and oscillated spectra.\r\n\r\n        Returns\r\n        -------\r\n        initialspectra : dict\r\n            Dictionary of model spectra, keyed by neutrino flavor.\r\n        \"\"\"\r\n        initialspectra = {}\r\n\r\n        # Avoid division by zero in energy PDF below.\r\n        E[E==0] = np.finfo(float).eps * E.unit\r\n\r\n        # Estimate L(t), <E_nu(t)> and alpha(t). Express all energies in erg.\r\n        E = E.to('erg').value\r\n\r\n        # Make sure input time uses the same units as the model time grid, or\r\n        # the interpolation will not work correctly.\r\n        t = t.to(self.time.unit)\r\n\r\n        for flavor in Flavor:\r\n            # Use np.interp rather than scipy.interpolate.interp1d because it\r\n            # can handle dimensional units (astropy.Quantity).\r\n            L  = get_value(np.interp(t, self.time, self.luminosity[flavor].to('erg/s')))\r\n            Ea = get_value(np.interp(t, self.time, self.meanE[flavor].to('erg')))\r\n            a  = np.interp(t, self.time, self.pinch[flavor])\r\n\r\n            # For numerical stability, evaluate log PDF and then exponentiate.\r\n            initialspectra[flavor] = \\\r\n                np.exp(np.log(L) - (2+a)*np.log(Ea) + (1+a)*np.log(1+a)\r\n                       - loggamma(1+a) + a*np.log(E) - (1+a)*(E/Ea)) / (u.erg * u.s)\r\n\r\n        return initialspectra\r\n\r\n    def __repr__(self):\r\n        \"\"\"Default representation of the model.\r\n        \"\"\"\r\n        mod = 'OConnor_2015 Model: {}\\n'.format(self.filename)\r\n        s = ['Progenitor mass : {}'.format(self.progenitor_mass),\r\n             'Eq. of state    : {}'.format(self.EOS)\r\n             ]\r\n        return mod + '\\n'.join(s)\r\n\r\n    def _repr_markdown_(self):\r\n        \"\"\"Markdown representation of the model, for Jupyter notebooks.\r\n        \"\"\"\r\n        mod = '**OConnor_2015 Model**: {}\\n\\n'.format(self.filename)\r\n        s = ['|Parameter|Value|',\r\n             '|:---------|:-----:|',\r\n             '|Progenitor mass | ${0.value:g}$ {0.unit:latex}|'.format(self.progenitor_mass),\r\n             '|EOS | {}|'.format(self.EOS)\r\n             ]\r\n        return mod + '\\n'.join(s)\r\n\r\n\r\nclass Warren_2020(SupernovaModel):\r\n    \"\"\"Set up a model based on simulations from Warren et al. (2020).\"\"\"\r\n\r\n    def __init__(self, filename, eos='LS220'):\r\n        \"\"\"Initialize model.\r\n\r\n        Parameters\r\n        ----------\r\n        filename : str\r\n            Absolute or relative path to file prefix, we add nue/nuebar/nux\r\n        eos : string\r\n            Equation of state used in simulation\r\n        \"\"\"\r\n        # Read data from HDF5 files, then store.\r\n        f = h5py.File(filename, 'r')\r\n        simtab = Table()\r\n\r\n        for i in range(len(f['nue_data']['lum'])):\r\n            if f['sim_data']['shock_radius'][i][1] > 0.00001:\r\n                bounce = f['sim_data']['shock_radius'][i][0]\r\n                break\r\n\r\n        simtab['TIME'] = f['nue_data']['lum'][:, 0] - bounce\r\n        simtab['L_NU_E'] = f['nue_data']['lum'][:, 1] * 1e51\r\n        simtab['L_NU_E_BAR'] = f['nuae_data']['lum'][:, 1] * 1e51\r\n        simtab['L_NU_X'] = f['nux_data']['lum'][:, 1] * 1e51 / 4.0\r\n        simtab['E_NU_E'] = f['nue_data']['avg_energy'][:, 1]\r\n        simtab['E_NU_E_BAR'] = f['nuae_data']['avg_energy'][:, 1]\r\n        simtab['E_NU_X'] = f['nux_data']['avg_energy'][:, 1]\r\n        simtab['RMS_NU_E'] = f['nue_data']['rms_energy'][:, 1]\r\n        simtab['RMS_NU_E_BAR'] = f['nuae_data']['rms_energy'][:, 1]\r\n        simtab['RMS_NU_X'] = f['nux_data']['rms_energy'][:, 1]\r\n\r\n        simtab['ALPHA_NU_E'] = (2.0 * simtab['E_NU_E'] ** 2 - simtab['RMS_NU_E'] ** 2) / (simtab['RMS_NU_E'] ** 2 - simtab['E_NU_E'] ** 2)\r\n        simtab['ALPHA_NU_E_BAR'] = (2.0 * simtab['E_NU_E_BAR'] ** 2 - simtab['RMS_NU_E_BAR'] ** 2) / (simtab['RMS_NU_E_BAR'] ** 2 - simtab['E_NU_E_BAR'] ** 2)\r\n        simtab['ALPHA_NU_X'] = (2.0 * simtab['E_NU_X'] ** 2 - simtab['RMS_NU_X'] ** 2) / (simtab['RMS_NU_X'] ** 2 - simtab['E_NU_X'] ** 2)\r\n\r\n        # Set model metadata.\r\n        self.filename = os.path.basename(filename)\r\n        self.EOS = eos\r\n        self.progenitor_mass = float(filename.split('_')[-1].strip('m%.h5')) * u.Msun\r\n        self.turbmixing_param = float(filename.split('_')[-2].strip('a%'))\r\n\r\n        # Get grid of model times.\r\n        self.time = simtab['TIME'] * u.s\r\n\r\n        # Set up dictionary of luminosity, mean energy and shape parameter\r\n        # alpha, keyed by neutrino flavor (NU_E, NU_X, NU_E_BAR, NU_X_BAR).\r\n        self.luminosity = {}\r\n        self.meanE = {}\r\n        self.pinch = {}\r\n\r\n        for flavor in Flavor:\r\n            # Note: file only contains NU_E, NU_E_BAR, and NU_X, so double up\r\n            # the use of NU_X for NU_X_BAR.\r\n            _flav = Flavor.NU_X if flavor == Flavor.NU_X_BAR else flavor\r\n\r\n            self.luminosity[flavor] = simtab['L_{}'.format(_flav.name)] * u.erg/u.s\r\n            self.meanE[flavor] = simtab['E_{}'.format(_flav.name)] * u.MeV\r\n            self.pinch[flavor] = simtab['ALPHA_{}'.format(_flav.name)]\r\n\r\n    def get_time(self):\r\n        \"\"\"Get grid of model times.\r\n\r\n        Returns\r\n        -------\r\n        time : ndarray\r\n            Grid of times used in the model.\r\n        \"\"\"\r\n        return self.time\r\n\r\n    def get_initialspectra(self, t, E):\r\n        \"\"\"Get neutrino spectra/luminosity curves before oscillation.\r\n\r\n        Parameters\r\n        ----------\r\n        t : float\r\n            Time to evaluate initial and oscillated spectra.\r\n        E : float or ndarray\r\n            Energies to evaluate the initial and oscillated spectra.\r\n\r\n        Returns\r\n        -------\r\n        initialspectra : dict\r\n            Dictionary of model spectra, keyed by neutrino flavor.\r\n        \"\"\"\r\n        initialspectra = {}\r\n\r\n        # Avoid division by zero in energy PDF below.\r\n        E[E==0] = np.finfo(float).eps * E.unit\r\n\r\n        # Estimate L(t), <E_nu(t)> and alpha(t). Express all energies in erg.\r\n        E = E.to('erg').value\r\n\r\n        # Make sure input time uses the same units as the model time grid, or\r\n        # the interpolation will not work correctly.\r\n        t = t.to(self.time.unit)\r\n\r\n        for flavor in Flavor:\r\n            # Use np.interp rather than scipy.interpolate.interp1d because it\r\n            # can handle dimensional units (astropy.Quantity).\r\n            L  = get_value(np.interp(t, self.time, self.luminosity[flavor].to('erg/s')))\r\n            Ea = get_value(np.interp(t, self.time, self.meanE[flavor].to('erg')))\r\n            a  = np.interp(t, self.time, self.pinch[flavor])\r\n\r\n            # For numerical stability, evaluate log PDF and then exponentiate.\r\n            initialspectra[flavor] = \\\r\n                np.exp(np.log(L) - (2+a)*np.log(Ea) + (1+a)*np.log(1+a)\r\n                       - loggamma(1+a) + a*np.log(E) - (1+a)*(E/Ea)) / (u.erg * u.s)\r\n\r\n        return initialspectra\r\n\r\n    def __repr__(self):\r\n        \"\"\"Default representation of the model.\r\n        \"\"\"\r\n        mod = 'Warren_2020 Model: {}\\n'.format(self.filename)\r\n        s = ['Progenitor mass : {}'.format(self.progenitor_mass),\r\n             'Turb. mix param : {}'.format(self.turbmixing_param),\r\n             'Eq. of state    : {}'.format(self.EOS)\r\n             ]\r\n        return mod + '\\n'.join(s)\r\n\r\n    def _repr_markdown_(self):\r\n        \"\"\"Markdown representation of the model, for Jupyter notebooks.\r\n        \"\"\"\r\n        mod = '**Warren_2020 Model**: {}\\n\\n'.format(self.filename)\r\n        s = ['|Parameter|Value|',\r\n             '|:---------|:-----:|',\r\n             '|Progenitor mass | ${0.value:g}$ {0.unit:latex}|'.format(self.progenitor_mass),\r\n             '|Turb. mixing param. | {}|'.format(self.turbmixing_param),\r\n             '|EOS | {}|'.format(self.EOS)\r\n             ]\r\n        return mod + '\\n'.join(s)\r\n\r\n\r\nclass Kuroda_2020(SupernovaModel):\r\n    \"\"\"Set up a model based on simulations from Kuroda et al. (2020).\"\"\"\r\n\r\n    def __init__(self, filename, eos='LS220'):\r\n        \"\"\"Initialize model.\r\n\r\n        Parameters\r\n        ----------\r\n        filename : str\r\n            Absolute or relative path to file prefix, we add nue/nuebar/nux\r\n        eos : string\r\n            Equation of state used in simulation\r\n        \"\"\"\r\n        # Load up model metadata.\r\n        self.filename = filename\r\n        self.EOS = eos\r\n\r\n        # Read ASCII data.\r\n        simtab = Table.read(filename, format='ascii')\r\n\r\n        # Get grid of model times.\r\n        self.time = (simtab['Tpb[ms]'] * u.ms).to('s')\r\n\r\n        # Set up dictionary of luminosity, mean energy and shape parameter\r\n        # alpha, keyed by neutrino flavor (NU_E, NU_X, NU_E_BAR, NU_X_BAR).\r\n        self.luminosity = {}\r\n        self.meanE = {}\r\n        self.pinch = {}\r\n\r\n        for flavor in Flavor:\r\n            # Note: file only contains NU_E, NU_E_BAR, and NU_X, so double up\r\n            # the use of NU_X for NU_X_BAR.\r\n            _flav = Flavor.NU_X if flavor == Flavor.NU_X_BAR else flavor\r\n            if _flav.is_neutrino:\r\n                _fkey = _flav.name.lower()\r\n            else:\r\n                _fkey = _flav.name.strip('%_BAR').lower().replace('_', '_a')\r\n\r\n            self.luminosity[flavor] = simtab['<L{}>'.format(_fkey)] * 1e51 * u.erg/u.s\r\n            self.meanE[flavor] = simtab['<E{}>'.format(_fkey)] * u.MeV\r\n\r\n            # There is no pinch parameter so use alpha=2.0.\r\n            self.pinch[flavor] = np.full_like(self.meanE[flavor].value, 2.)\r\n\r\n    def get_time(self):\r\n        \"\"\"Get grid of model times.\r\n\r\n        Returns\r\n        -------\r\n        time : ndarray\r\n            Grid of times used in the model.\r\n        \"\"\"\r\n        return self.time\r\n\r\n    def get_initialspectra(self, t, E):\r\n        \"\"\"Get neutrino spectra/luminosity curves before oscillation.\r\n\r\n        Parameters\r\n        ----------\r\n        t : float\r\n            Time to evaluate initial and oscillated spectra.\r\n        E : float or ndarray\r\n            Energies to evaluate the initial and oscillated spectra.\r\n\r\n        Returns\r\n        -------\r\n        initialspectra : dict\r\n            Dictionary of model spectra, keyed by neutrino flavor.\r\n        \"\"\"\r\n        initialspectra = {}\r\n\r\n        # Avoid division by zero in energy PDF below.\r\n        E[E==0] = np.finfo(float).eps * E.unit\r\n\r\n        # Estimate L(t), <E_nu(t)> and alpha(t). Express all energies in erg.\r\n        E = E.to('erg').value\r\n\r\n        # Make sure input time uses the same units as the model time grid, or\r\n        # the interpolation will not work correctly.\r\n        t = t.to(self.time.unit)\r\n\r\n        for flavor in Flavor:\r\n            # Use np.interp rather than scipy.interpolate.interp1d because it\r\n            # can handle dimensional units (astropy.Quantity).\r\n            L  = get_value(np.interp(t, self.time, self.luminosity[flavor].to('erg/s')))\r\n            Ea = get_value(np.interp(t, self.time, self.meanE[flavor].to('erg')))\r\n            a  = np.interp(t, self.time, self.pinch[flavor])\r\n\r\n            # For numerical stability, evaluate log PDF and then exponentiate.\r\n            initialspectra[flavor] = \\\r\n                np.exp(np.log(L) - (2+a)*np.log(Ea) + (1+a)*np.log(1+a)\r\n                       - loggamma(1+a) + a*np.log(E) - (1+a)*(E/Ea)) / (u.erg * u.s)\r\n\r\n        return initialspectra\r\n\r\n    def __repr__(self):\r\n        \"\"\"Default representation of the model.\r\n        \"\"\"\r\n        mod = 'Kuroda_2020 Model: {}\\n'.format(self.filename)\r\n        s = ['Eq. of state    : {}'.format(self.EOS)\r\n             ]\r\n        return mod + '\\n'.join(s)\r\n\r\n    def _repr_markdown_(self):\r\n        \"\"\"Markdown representation of the model, for Jupyter notebooks.\r\n        \"\"\"\r\n        mod = '**Kuroda_2020 Model**: {}\\n\\n'.format(self.filename)\r\n        s = ['|Parameter|Value|',\r\n             '|:---------|:-----:|',\r\n             '|EOS | {}|'.format(self.EOS)\r\n             ]\r\n        return mod + '\\n'.join(s)\r\n\r\n\r\nclass Janka(SupernovaModel):\r\n    \"\"\"Set up a model based on simulations from Janka, I'll have to update this descriptioin later because I dont know where this is from\r\n    \"\"\"\r\n\r\n    def __init__(self, filename):\r\n        \"\"\"Initialize model.\r\n\r\n        Parameters\r\n        ----------\r\n        filename : str\r\n            Absolute or relative path to FITS file with model data.\r\n        \"\"\"\r\n        self.file = Table.read(filename)\r\n        self.filename = filename\r\n        self.luminosity = {}\r\n        self.meanE = {}\r\n        self.pinch = {}\r\n        for flavor in Flavor:\r\n            self.luminosity[flavor] = interp1d(self.get_time(), self.get_luminosity(flavor))\r\n            self.meanE[flavor] = interp1d(self.get_time(), self.get_mean_energy(flavor))\r\n            self.pinch[flavor] = interp1d(self.get_time(), self.get_pinch_param(flavor))\r\n            \r\n    def get_time(self):\r\n        \"\"\"Get grid of model times.\r\n\r\n        Returns\r\n        -------\r\n        time : ndarray\r\n            Grid of times used in the model.\r\n        \"\"\"\r\n        return self.file['TIME']\r\n    \r\n    def get_luminosity(self, flavor):\r\n        \"\"\"Get model luminosity L_nu.\r\n\r\n        Parameters\r\n        ----------\r\n        flavor : Flavor\r\n            Neutrino flavor type.\r\n\r\n        Returns\r\n        -------\r\n        luminosity : ndarray\r\n            Grid of luminosity values (erg/s) for this flavor.\r\n        \"\"\"\r\n        if flavor == Flavor.NU_X_BAR:\r\n            flavor = Flavor.NU_X\r\n        return self.file['L_{}'.format(flavor.name.upper())]\r\n        \r\n    def get_mean_energy(self, flavor):\r\n        \"\"\"Get model mean energy <E_nu>.\r\n\r\n        Parameters\r\n        ----------\r\n        flavor : Flavor\r\n            Neutrino flavor type.\r\n\r\n        Returns\r\n        -------\r\n        energy : ndarray\r\n            Grid of mean energy versus time.\r\n        \"\"\"\r\n        if flavor == Flavor.NU_X_BAR:\r\n            flavor = Flavor.NU_X\r\n        return self.file['E_{}'.format(flavor.name.upper())]\r\n    \r\n    def get_pinch_param(self, flavor):\r\n        \"\"\"Get spectral pinch parameter alpha(t).\r\n\r\n        Parameters\r\n        ----------\r\n        flavor : Flavor\r\n            Neutrino flavor type.\r\n\r\n        Returns\r\n        -------\r\n        alpha : ndarray\r\n            Grid of alpha versus time.\r\n        \"\"\"\r\n        if (flavor == Flavor.NU_X_BAR):\r\n            flavor = Flavor.NU_X\r\n        return self.file['ALPHA_{}'.format(flavor.name.upper())]\r\n    \r\n    def get_EOS(self):\r\n        \"\"\"Model equation of state.\r\n\r\n        Returns\r\n        -------\r\n        eos : str\r\n            Model equation of state.\r\n        \"\"\"\r\n        return self.filename.split('-')[1]\r\n    \r\n    def get_progenitor_mass(self):\r\n        \"\"\"Progenitor mass.\r\n\r\n        Returns\r\n        -------\r\n        mass : float\r\n            Progenitor mass, in units of solar mass.\r\n        \"\"\"\r\n        return float(self.split('-')[-1].split('.')[0].strip('s'))\r\n\r\n    def get_initialspectra(self,t,E):\r\n        \"\"\"Get neutrino spectra/luminosity curves after oscillation.\r\n\r\n        Parameters\r\n        ----------\r\n        t : float\r\n            Time to evaluate initial and oscillated spectra.\r\n        E : float or ndarray\r\n            Energies to evaluate the initial and oscillated spectra.\r\n\r\n        Returns\r\n        -------\r\n        initialspectra : dict\r\n            Dictionary of model spectra, keyed by neutrino flavor.\"\"\"\r\n    \r\n        initialspectra = {}\r\n        for flavor in Flavor:\r\n            L = self.luminosity[flavor](t)\r\n            Ea = self.meanE[flavor](t)          # <E_nu(t)>\r\n            Ea = Ea*1e6 * 1.60218e-12\r\n            a = self.pinch[flavor](t)           # alpha_nu(t)\r\n            E[E==0] = np.finfo(float).eps       # Avoid division by zero.\r\n\r\n            # For numerical stability, evaluate log PDF then exponentiate.\r\n            initialspectra[flavor] = \\\r\n                np.exp(np.log(L) - (2+a)*np.log(Ea) + (1+a)*np.log(1+a) \r\n                       - loggamma(1+a) + a*np.log(E) - (1+a)*(E/Ea)) / (u.erg * u.s)\r\n\r\n        return initialspectra\r\n\r\n\r\n# class Fornax2019(SupernovaModel):\r\n#     \r\n#     def __init__(self, filename):\r\n#         self.file = Table.read(filename)\r\n#         self.filename = filename\r\n#         \r\n#     def get_time(self):\r\n#         return self.file['TIME']\r\n#     \r\n#     def get_luminosity(self, flavor):\r\n#         if flavor == Flavor.NU_X_BAR:\r\n#             flavor = Flavor.NU_X\r\n#         return self.file['L_{}'.format(flavor.name.upper())]\r\n#         \r\n#     def get_mean_energy(self, flavor):\r\n#         if flavor == Flavor.NU_X_BAR:\r\n#             flavor = Flavor.NU_X\r\n#         return self.file['E_{}'.format(flavor.name.upper())]\r\n#     \r\n#     def get_pinch_param(self, flavor):\r\n#         if (flavor == Flavor.NU_X_BAR):\r\n#             flavor = Flavor.NU_X\r\n#         return self.file['ALPHA_{}'.format(flavor.name.upper())]\r\n#     \r\n#     def get_EOS(self):\r\n#         return self.filename.split('-')[1]\r\n#     \r\n#     def get_progenitor_mass(self):\r\n#         return float(self.split('-')[-1].split('.')[0].strip('s'))\r\n# \r\n# class OConnor_2013(SupernovaModel):\r\n#        \r\n#     eos = 'LS220'\r\n#     mass = 30\r\n#     def __init__(self, filename, FlavorTransformation):\r\n#         spectra_tuple = get_spectra(mass, eos)\r\n#         self.eos = eos\r\n#         self.luminosity = get_luminosity\r\n#         self.meanE = spectra_list(2)\r\n#         self.luminosity = get_luminosity(mass, eos)\r\n#         self.\r\n#     \r\n#     def get_luminosity(mass, eos):\r\n#         # Open luminosity file.\r\n#         tf = tarfile.open('{}_timeseries.tar.gz'.format(eos))\r\n#     \r\n#         # Extract luminosity data.\r\n#         dataname = 's{:d}_{}_timeseries.dat'.format(mass, eos)\r\n#         datafile = tf.extractfile(dataname)\r\n#         lumdata = ascii.read(datafile, names=['t', 'Le', 'Lae', 'Lx',\r\n#                                               'Ee_avg', 'Eae_avg', 'Ex_avg',\r\n#                                               'Ee_rms', 'Eae_rms', 'Ex_rms'])\r\n#         return lumdata\r\n#     \r\n#     \r\n#     def get_spectra(mass, eos):\r\n#         # Open spectra file.\r\n#         tf = tarfile.open('{}_timeseries_spectra.tar.gz'.format(eos))\r\n#     \r\n#         # Extract luminosity data.\r\n#         dataname = 's{:d}_{}_timeseries_spectra.dat'.format(mass, eos)\r\n#         datafile = tf.extractfile(dataname)\r\n#     \r\n#         t = []\r\n#         E = []\r\n#         spectra = []\r\n#     \r\n#         for line in datafile:\r\n#             tokens = [float(x) for x in line.strip().split()]\r\n#             if len(tokens) == 1:\r\n#                 if t:\r\n#                     E = _E\r\n#                     spectra.append(Table([_Fe, _Fae, _Fx],\r\n#                                          names=['Fe', 'Fae', 'Fx'],\r\n#                                          meta={'t' : t[-1]}))\r\n#                 t.append(tokens[0])\r\n#                 _E, _Fe, _Fae, _Fx = [[] for _ in range(4)]\r\n#             elif len(tokens) == 4:\r\n#                 _E.append(tokens[0])\r\n#                 _Fe.append(tokens[1])\r\n#                 _Fae.append(tokens[2])\r\n#                 _Fx.append(tokens[3])\r\n#     \r\n#         spectra.append(Table([_Fe, _Fae, _Fx],\r\n#                              names=['Fe', 'Fae', 'Fx'],\r\n#                              meta={'t' : t[-1]}))\r\n#     \r\n#         return t, E, spectra\r\n\r\n\r\nclass SNOwGLoBES:\r\n    \"\"\"A model that does not inherit from SupernovaModel (yet) and imports a group of SNOwGLoBES files.\"\"\"\r\n\r\n    def __init__(self, tarfilename):\r\n        \"\"\"Initialize model from a tar archive.\r\n\r\n        Parameters\r\n        ----------\r\n        tarfilename: str\r\n            Absolute or relative path to tar archive with SNOwGLoBES files.\r\n        \"\"\"\r\n        self.tfname = tarfilename\r\n        tf = tarfile.open(self.tfname)\r\n\r\n        # For now just pull out the \"NoOsc\" files.\r\n        datafiles = sorted([f.name for f in tf if '.dat' in f.name])\r\n        noosc = [df for df in datafiles if 'NoOsc' in df]\r\n        noosc.sort(key=len)\r\n\r\n        # Loop through the noosc files and pull out the number fluxes.\r\n        self.time = []\r\n        self.energy = None\r\n        self.flux = {}\r\n        self.fmin = 1e99\r\n        self.fmax = -1e99\r\n\r\n        for nooscfile in noosc:\r\n            with tf.extractfile(nooscfile) as f:\r\n                logging.debug('Reading {}'.format(nooscfile))\r\n                meta = f.readline()\r\n                metatext = meta.decode('utf-8')\r\n                t = float(metatext.split('TBinMid=')[-1].split('sec')[0])\r\n                dt = float(metatext.split('tBinWidth=')[-1].split('s')[0])\r\n                dE = float(metatext.split('eBinWidth=')[-1].split('MeV')[0])\r\n\r\n                data = Table.read(f, format='ascii.commented_header', header_start=-1)\r\n                data.meta['t'] = t\r\n                data.meta['dt'] = dt\r\n                data.meta['dE'] = dE\r\n\r\n                self.time.append(t)\r\n                if self.energy is None:\r\n                    self.energy = (data['E(GeV)'].data*1000).tolist()\r\n\r\n            for flavor in ['NuE', 'NuMu', 'NuTau', 'aNuE', 'aNuMu', 'aNuTau']:\r\n                if flavor in self.flux:\r\n                    self.flux[flavor].append(data[flavor].data.tolist())\r\n                else:\r\n                    self.flux[flavor] = [data[flavor].data.tolist()]\r\n\r\n        # We now have a table with rows=times and columns=energies. Transpose\r\n        # so that rows=energy and cols=time.\r\n        for k, v in self.flux.items():\r\n            self.flux[k] = np.transpose(self.flux[k])\r\n            self.fmin = np.minimum(self.fmin, np.min(self.flux[k]))\r\n            self.fmax = np.maximum(self.fmax, np.max(self.flux[k]))\r\n\r\n    def get_fluence(self, t):\r\n        \"\"\"Return the fluence at a given time t.\r\n\r\n        Parameters\r\n        ----------\r\n        t : float\r\n            Time in seconds.\r\n\r\n        Returns\r\n        -------\r\n        fluence : dict\r\n            A dictionary giving fluence at time t, keyed by flavor.\r\n        \"\"\"\r\n        idx = get_closest(self.time, t)\r\n\r\n        fluence = {}\r\n        for k, fl in self.flux.items():\r\n            fluence[k] = fl[:,idx]\r\n\r\n        return fluence\r\n", "meta": {"hexsha": "73be27ee32cbc344940018448d90d593861f18a2", "size": 42693, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/snewpy/models.py", "max_stars_repo_name": "joshuashzha/snewpy", "max_stars_repo_head_hexsha": "5ecefc2b46dfb6f9867e6fe476dc78503077b6e2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/snewpy/models.py", "max_issues_repo_name": "joshuashzha/snewpy", "max_issues_repo_head_hexsha": "5ecefc2b46dfb6f9867e6fe476dc78503077b6e2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/snewpy/models.py", "max_forks_repo_name": "joshuashzha/snewpy", "max_forks_repo_head_hexsha": "5ecefc2b46dfb6f9867e6fe476dc78503077b6e2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0887573964, "max_line_length": 159, "alphanum_fraction": 0.5299463612, "include": true, "reason": "import numpy,from scipy,import astropy,from astropy", "num_tokens": 10738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.1880985098461631}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 13 11:18:50 2020\n\n@author: dberke\n\nA script to read in data on transition offsets vs. several stellar parameters\nfrom a database, and perform multi-component fitting to it.\n\"\"\"\n\nimport argparse\nimport csv\nfrom inspect import signature\nimport os\nfrom pathlib import Path\nimport pickle\nfrom pprint import pprint\nfrom time import sleep, time\nimport sys\n\nfrom adjustText import adjust_text\nimport h5py\nimport hickle\nfrom matplotlib.gridspec import GridSpec\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nimport numpy as np\nimport numpy.ma as ma\nfrom scipy.optimize import curve_fit\nfrom tqdm import tqdm\nimport unyt as u\n\nimport varconlib as vcl\nimport varconlib.fitting.fitting as fit\n\n# Define style parameters to use for stellar parameter plots.\nstyle_pre = {'color': 'Chocolate',\n             'ecolor_thick': 'DarkOrange',\n             'ecolor_thin': 'BurlyWood'}\nstyle_post = {'color': 'DodgerBlue',\n              'ecolor_thick': 'CornFlowerBlue',\n              'ecolor_thin': 'LightSkyBlue'}\nstyle_ref = {'color': 'DarkGreen',\n             'ecolor_thick': 'ForestGreen',\n             'ecolor_thin': 'DarkSeaGreen'}\nstyle_markers = {'markeredgecolor': 'Black',\n                 'markeredgewidth': 1,\n                 'alpha': 0.7,\n                 'markersize': 4}\nstyle_caps = {'capsize_thin': 4,\n              'capsize_thick': 7,\n              'linewidth_thin': 2,\n              'linewidth_thick': 3,\n              'cap_thin': 1.5,\n              'cap_thick': 2.5}\n\n\ndef create_comparison_figure(ylims=None, fit_target='transitions',\n                             temp_lims=(5300 * u.K, 6200 * u.K),\n                             mtl_lims=(-0.75, 0.4),\n                             mag_lims=(4, 5.8),\n                             logg_lims=(4.1, 4.6)):\n    \"\"\"Create and returns a figure with pre-set subplots.\n\n    This function creates the background figure and subplots for use with the\n    --compare-stellar-parameter-* flags.\n\n    Optional\n    ----------\n    ylims : 2-tuple of floats or ints\n        A tuple of length 2 containing the upper and lower limits of the\n        subplots in the figure.\n    fit_target : str, ['transitions', 'pairs']\n        A string denoting whether these plots are for transitions or pairs.\n    temp_lims : 2-tuple of floats or ints (optional dimensions of temperature)\n        A tuple of length containing upper and lower limits for the x-axis of\n        the temperature subplot.\n    mtl_lims : 2-tuple of floats or ints\n        A tuple of length containing upper and lower limits for the x-axis of\n        the metallicity subplot.\n    mag_lims : 2-tuple of floats or ints\n        A tuple of length containing upper and lower limits for the x-axis of\n        the absolute magnitude subplot.\n    logg_lims : 2-tuple of floats or ints\n        A tuple of length containing upper and lower limits for the x-axis of\n        the log(g) subplot.\n\n    Returns\n    -------\n    tuple\n        A tuple containing the figure itself and the various axes of the\n        subplots within it.\n\n    \"\"\"\n\n    comp_fig = plt.figure(figsize=(12, 8), tight_layout=True)\n    gs = GridSpec(ncols=4, nrows=2, figure=comp_fig,\n                  width_ratios=(5, 5, 5, 3))\n\n    temp_ax_pre = comp_fig.add_subplot(gs[0, 0])\n    temp_ax_post = comp_fig.add_subplot(gs[1, 0],\n                                        sharex=temp_ax_pre,\n                                        sharey=temp_ax_pre)\n    mtl_ax_pre = comp_fig.add_subplot(gs[0, 1],\n                                      sharey=temp_ax_pre)\n    mtl_ax_post = comp_fig.add_subplot(gs[1, 1],\n                                       sharex=mtl_ax_pre,\n                                       sharey=mtl_ax_pre)\n    logg_ax_pre = comp_fig.add_subplot(gs[0, 2],\n                                       sharey=temp_ax_pre)\n    logg_ax_post = comp_fig.add_subplot(gs[1, 2],\n                                        sharex=logg_ax_pre,\n                                        sharey=logg_ax_pre)\n    hist_ax_pre = comp_fig.add_subplot(gs[0, 3],\n                                       sharey=temp_ax_pre)\n    hist_ax_post = comp_fig.add_subplot(gs[1, 3],\n                                        sharex=hist_ax_pre,\n                                        sharey=hist_ax_pre)\n\n    all_axes = (temp_ax_pre, temp_ax_post, mtl_ax_pre, mtl_ax_post,\n                logg_ax_pre, logg_ax_post, hist_ax_pre, hist_ax_post)\n    # Set the plot limits here. The y-limits for temp_ax1 are\n    # used for all subplots.\n    if ylims is not None:\n        temp_ax_pre.set_ylim(bottom=ylims[0],\n                             top=ylims[1])\n    temp_ax_pre.set_xlim(left=temp_lims[0],\n                         right=temp_lims[1])\n    mtl_ax_pre.set_xlim(left=mtl_lims[0],\n                        right=mtl_lims[1])\n    logg_ax_pre.set_xlim(left=logg_lims[0],\n                         right=logg_lims[1])\n\n    # Axis styles for all subplots.\n    for ax in all_axes:\n        if not args.full_range:\n            ax.yaxis.set_major_locator(ticker.MultipleLocator(\n                                      base=100))\n            ax.yaxis.set_minor_locator(ticker.MultipleLocator(\n                                      base=50))\n        else:\n            ax.yaxis.set_major_locator(ticker.AutoLocator())\n            ax.yaxis.set_minor_locator(ticker.AutoMinorLocator())\n        ax.axhline(y=0, color='Black', linestyle='--')\n        ax.yaxis.grid(which='major', color='Gray',\n                      linestyle='--', alpha=0.5)\n        ax.yaxis.grid(which='minor', color='Gray',\n                      linestyle=':', alpha=0.5)\n        if ax not in (hist_ax_pre, hist_ax_post):\n            ax.xaxis.grid(which='major', color='Gray',\n                          linestyle='--', alpha=0.65)\n        ax.tick_params(labelsize=14)\n\n    for ax in (temp_ax_pre, temp_ax_post):\n        ax.set_xlabel('Temperature (K)', size=15)\n        ax.xaxis.set_major_locator(ticker.MultipleLocator(base=200))\n        ax.xaxis.set_minor_locator(ticker.MultipleLocator(base=100))\n    for ax in (mtl_ax_pre, mtl_ax_post):\n        ax.set_xlabel('Metallicity [Fe/H]', size=15)\n        ax.xaxis.set_major_locator(ticker.MultipleLocator(base=0.2))\n        ax.xaxis.set_minor_locator(ticker.MultipleLocator(base=0.1))\n    for ax in (logg_ax_pre, logg_ax_post):\n        ax.set_xlabel(r'log $g$ $(\\mathrm{cm}/\\mathrm{s}^2)$', size=15)\n        ax.xaxis.set_major_locator(ticker.MultipleLocator(base=0.1))\n        ax.xaxis.set_minor_locator(ticker.MultipleLocator(base=0.05))\n\n    # Just label the left-most two subplots' y-axes.\n    for ax, era in zip((temp_ax_pre, temp_ax_post),\n                       ('Pre', 'Post')):\n        if fit_target == 'transitions':\n            ax.set_ylabel(f'{era}-fiber change offset (m/s)')\n        elif fit_target == 'pairs':\n            ax.set_ylabel(f'{era}-fiber change separation (m/s)')\n        else:\n            raise RuntimeError(f'Unallowed value for fit_target: {fit_target}')\n\n    axes_dict = {'temp_pre': temp_ax_pre, 'temp_post': temp_ax_post,\n                 'mtl_pre': mtl_ax_pre, 'mtl_post': mtl_ax_post,\n                 'logg_pre': logg_ax_pre, 'logg_post': logg_ax_post,\n                 'hist_pre': hist_ax_pre, 'hist_post': hist_ax_post}\n\n    return comp_fig, axes_dict\n\n\ndef plot_data_points(axis, x_pos, y_pos, thick_err, thin_err, era=None,\n                     ref=False):\n    \"\"\"Plot a data point for a star.\n\n    Parameters\n    ----------\n    axis : `matplotlib.axes.Axes`\n        An axes to plot the data on.\n    x_pos : iterable of floats or `unyt.unyt_quantity`\n        The x-positions of the points to plot.\n    y_pos : iterable of floats or `unyt.unyt_quantity`\n        The y-positions of the points to plot. The length must match the length\n        of `x_pos`.\n    thick_err : iterable of floats or `unyt.unyt_quantity` or None\n        The values of the thick error bars to plot. The length must match the\n        length of `x_pos`.\n    thin_err : iterable of floats or `unyt.unyt_quantity` or None\n        The values of the thin error bars to plot. The length must match the\n        length of `x_pos`.\n    era : string, ['pre', 'post'], or None, Default : None\n        Whether the time period of the plot is pre- or post-fiber\n        change. The only allowed string values are 'pre' and 'post'. Controls\n        color of the points. If `ref` is *True*, the value of `era` is\n        ignored, and can be left unspecified, otherwise it needs a\n        value to be given.\n    ref : bool, Default : False\n        Whether this data point is for the reference star. If *True*,\n        will use a special separate color scheme.\n\n    Returns\n    -------\n    None.\n\n    \"\"\"\n\n    if ref:\n        params = style_ref\n    elif era == 'pre':\n        params = style_pre\n    elif era == 'post':\n        params = style_post\n    else:\n        raise ValueError(\"Keyword 'era' received an unknown value\"\n                         f\" (valid values are 'pre' & 'post'): {era}\")\n\n    if thin_err is not None:\n        axis.errorbar(x=x_pos, y=y_pos,\n                      yerr=thin_err, linestyle='',\n                      marker='', capsize=style_caps['capsize_thin'],\n                      color=params['color'],\n                      ecolor=params['ecolor_thin'],\n                      elinewidth=style_caps['linewidth_thin'],\n                      capthick=style_caps['cap_thin'])\n    if thick_err is not None:\n        axis.errorbar(x=x_pos, y=y_pos,\n                      yerr=thick_err, linestyle='',\n                      marker='o', markersize=style_markers['markersize'],\n                      markeredgewidth=style_markers['markeredgewidth'],\n                      markeredgecolor=style_markers['markeredgecolor'],\n                      alpha=style_markers['alpha'],\n                      capsize=style_caps['capsize_thick'],\n                      color=params['color'],\n                      ecolor=params['ecolor_thick'],\n                      elinewidth=style_caps['linewidth_thick'],\n                      capthick=style_caps['cap_thick'])\n\n\ndef find_star(star_params, stellar_params, star_names):\n    \"\"\"Return the name of the star which matches the given parameters.\n\n    Parameters\n    ----------\n    star_params : iterable\n        An iterable (in practice, an array slice of length 3) which contains\n        values of stellar parameters, temperature in position 0, metallicity in\n        position 1, and magnitude in position 2.\n    stellar_params : array-like\n        A 3xN array of stellar parameters, with the same order as `star_params`.\n    star_names : `bidict.bidict`\n        A `bidict` containing star names in strings as keys, and index numbers\n        as ints for the values.\n\n    Returns\n    -------\n    str\n        The name of the star associated with the given parameters.\n\n    \"\"\"\n\n    for i in range(len(stellar_params[0])):\n        if np.all(np.isclose(star_params, stellar_params[:, i])):\n            return star_names[i]\n\n\ndef main():\n    \"\"\"Run the main routine of the script.\"\"\"\n\n    # Define the limits to plot in the various stellar parameters.\n    temp_lims = (5400, 6300) * u.K\n    mtl_lims = (-0.75, 0.45)\n    # mag_lims = (4, 5.8)\n    logg_lims = (4.1, 4.6)\n\n    # Define the model to use:\n    if args.constant:\n        model_func = fit.constant_model\n    elif args.linear:\n        model_func = fit.linear_model\n    elif args.quadratic:\n        model_func = fit.quadratic_model\n    elif args.cubic:\n        model_func = fit.cubic_model\n    elif args.cross_term:\n        model_func = fit.cross_term_model\n    elif args.quadratic_cross_term:\n        model_func = fit.quad_cross_term_model\n    elif args.quad_cross_term:\n        model_func = fit.quad_cross_term_model\n\n    model_name = '_'.join(model_func.__name__.split('_')[:-1])\n\n    if args.transitions:\n        tqdm.write('Unpickling transitions list.')\n        with open(vcl.final_selection_file, 'r+b') as f:\n            transitions_list = pickle.load(f)\n        vprint(f'Found {len(transitions_list)} transitions.')\n    elif args.pairs:\n        tqdm.write('Unpickling pairs list.')\n        with open(vcl.final_pair_selection_file, 'r+b') as f:\n            pairs_list = pickle.load(f)\n        vprint(f'Found {len(pairs_list)} pairs in the list.')\n\n    db_file = vcl.databases_dir / 'stellar_db_uncorrected.hdf5'\n    if not db_file.exists():\n        raise FileNotFoundError('The given stellar database does not exist:'\n                                f' {db_file}')\n\n    # Load data from HDF5 database file.\n    tqdm.write('Reading data from stellar database file...')\n    if args.transitions:\n        star_transition_offsets = u.unyt_array.from_hdf5(\n                db_file, dataset_name='star_transition_offsets')\n        star_transition_offsets_EotWM = u.unyt_array.from_hdf5(\n                db_file, dataset_name='star_transition_offsets_EotWM')\n        star_transition_offsets_EotM = u.unyt_array.from_hdf5(\n                db_file, dataset_name='star_transition_offsets_EotM')\n        # star_transition_offsets_stds = u.unyt_array.from_hdf5(\n        #         db_file, dataset_name='star_standard_deviations')\n    elif args.pairs:\n        star_pair_separations = u.unyt_array.from_hdf5(\n               db_file, dataset_name='star_pair_separations')\n        star_pair_separations_EotWM = u.unyt_array.from_hdf5(\n                db_file, dataset_name='star_pair_separations_EotWM')\n        star_pair_separations_EotM = u.unyt_array.from_hdf5(\n                db_file, dataset_name='star_pair_separations_EotM')\n    star_temperatures = u.unyt_array.from_hdf5(\n            db_file, dataset_name='star_temperatures')\n\n    with h5py.File(db_file, mode='r') as f:\n\n        star_metallicities = hickle.load(f, path='/star_metallicities')\n        # star_magnitudes = hickle.load(f, path='/star_magnitudes')\n        star_gravities = hickle.load(f, path='/star_gravities')\n        transition_column_dict = hickle.load(f, path='/transition_column_index')\n        pair_column_dict = hickle.load(f, path='/pair_column_index')\n\n        star_names = hickle.load(f, path='/star_row_index')\n\n    # Handle various fitting and plotting setup:\n    eras = {'pre': 0, 'post': 1}\n    param_dict = {'temp': 0, 'mtl': 1, 'logg': 2}\n\n    # Create lists to store information about each fit in:\n    index_nums = []\n    chi_squareds_pre, sigmas_pre, sigma_sys_pre = [], [], []\n    chi_squareds_post, sigmas_post, sigma_sys_post = [], [], []\n    index_num = 0\n\n    # Figure out how many parameters the model function takes, so we know how\n    # many to dynamically give it later. Subtract 1 for the parameter which\n    # takes the stellar parameters.\n    params_list = [0 for i in range(len(signature(model_func).parameters)-1)]\n\n    # Define the folder to put plots in.\n    output_dir = vcl.output_dir\n    if args.transitions:\n        fit_target = 'transitions'\n    elif args.pairs:\n        fit_target = 'pairs'\n    plots_folder = output_dir /\\\n        f'stellar_parameter_fits_{fit_target}_{args.sigma}sigma/{model_name}'\n    vprint(f'Creating plots in {plots_folder}')\n    if not plots_folder.exists():\n        os.makedirs(plots_folder)\n\n    # Create a dictionary of fit coefficients assigned to each transition's\n    # label\n    coefficients_dict = {}\n    covariance_dict = {}\n    sigmas_dict = {}\n    sigma_sys_dict = {}\n\n    if args.transitions:\n        tqdm.write('Creating plots for each transition...')\n        for transition in tqdm(transitions_list):\n            for order_num in transition.ordersToFitIn:\n                index_nums.append(index_num)\n                index_num += 1\n                label = '_'.join([transition.label, str(order_num)])\n                vprint(20 * '-')\n                vprint(f'Analyzing {label}...')\n\n                # The column number to use for this transition:\n                col = transition_column_dict[label]\n                ylimits = (-300 * u.m / u.s,\n                           300 * u.m / u.s) if not args.full_range else None\n\n                comp_fig, axes_dict = create_comparison_figure(\n                                ylims=ylimits,\n                                fit_target='transitions',\n                                temp_lims=temp_lims,\n                                mtl_lims=mtl_lims,\n                                logg_lims=logg_lims)\n\n                for time in eras.keys():\n\n                    vprint(20 * '=')\n                    vprint(f'Working on {time}-change era.')\n                    mean = np.nanmean(star_transition_offsets[eras[time],\n                                      :, col])\n\n                    # First, create a masked version to catch any missing\n                    # entries:\n                    m_offsets = ma.masked_invalid(star_transition_offsets[\n                                eras[time], :, col])\n                    total_stars = ma.count(m_offsets)\n                    vprint(f'Found {total_stars} stars with data.')\n                    m_offsets = m_offsets.reshape([len(m_offsets), 1])\n                    # Then create a new array from the non-masked data:\n                    offsets = u.unyt_array(m_offsets[~m_offsets.mask],\n                                           units=u.m/u.s)\n                    vprint(f'Median of offsets is {np.nanmedian(offsets)}')\n\n    #                m_stds = ma.masked_invalid(star_transition_offsets_stds[\n    #                            eras[time], :, col])\n    #                m_stds = m_stds.reshape([len(m_stds), 1])\n    #                stds = u.unyt_array(m_stds[~m_stds.mask],\n    #                                    units=u.m/u.s)\n\n                    m_eotwms = ma.masked_invalid(star_transition_offsets_EotWM[\n                            eras[time], :, col])\n                    m_eotwms = m_eotwms.reshape([len(m_eotwms), 1])\n                    eotwms = u.unyt_array(m_eotwms[~m_offsets.mask],\n                                          units=u.m/u.s)\n\n                    m_eotms = ma.masked_invalid(star_transition_offsets_EotM[\n                            eras[time], :, col])\n                    m_eotms = m_eotms.reshape([len(m_eotms), 1])\n                    # Use the same mask as for the offsets.\n                    eotms = u.unyt_array(m_eotms[~m_offsets.mask],\n                                         units=u.m/u.s)\n                    # Create an error array which uses the greater of the error\n                    # on the mean or the error on the weighted mean.\n                    err_array = ma.array(np.maximum(eotwms, eotms).value)\n\n                    vprint(f'Mean is {np.mean(offsets)}')\n                    weighted_mean = np.average(offsets, weights=err_array**-2)\n                    vprint(f'Weighted mean is {weighted_mean}')\n\n                    # Mask the various stellar parameter arrays with the same\n                    # mask so that everything stays in sync.\n                    temperatures = ma.masked_array(star_temperatures)\n                    temps = temperatures[~m_offsets.mask]\n                    metallicities = ma.masked_array(star_metallicities)\n                    metals = metallicities[~m_offsets.mask]\n                    # magnitudes = ma.masked_array(star_magnitudes)\n                    # mags = magnitudes[~m_offsets.mask]\n                    gravities = ma.masked_array(star_gravities)\n                    loggs = gravities[~m_offsets.mask]\n\n                    stars = ma.masked_array([key for key in\n                                             star_names.keys()]).reshape(\n                                                 len(star_names.keys()), 1)\n                    names = stars[~m_offsets.mask]\n\n                    # Stack the stellar parameters into vertical slices\n                    # for passing to model functions.\n                    x_data = ma.array(np.stack((temps, metals, loggs), axis=0))\n\n                    # Create the parameter list for this run of fitting.\n                    params_list[0] = float(mean)\n\n                    beta0 = tuple(params_list)\n                    vprint(beta0)\n\n                    results = fit.find_sys_scatter(model_func,\n                                                   x_data,\n                                                   ma.array(offsets.value),\n                                                   err_array, beta0,\n                                                   n_sigma=args.sigma,\n                                                   tolerance=0.001,\n                                                   verbose=args.verbose)\n\n                    mask = results['mask_list'][-1]\n                    residuals = ma.array(results['residuals'], mask=mask)\n                    x_data.mask = mask\n                    err_array.mask = mask\n\n                    # for item1, item2 in zip(residuals, ma.getdata(residuals)):\n                    #     print(f'{item1:10.3f}   {item2:10.3f}')\n\n                    chi_squared_nu = results['chi_squared_list'][-1]\n                    sys_err = results['sys_err_list'][-1] * u.m / u.s\n\n                    vprint(f'Terminated with sys_err = {sys_err}')\n                    vprint(f'Finished {label}_{time} in'\n                           f' {len(results[\"sys_err_list\"])} steps.')\n                    # Add the optimized parameters and covariances to the\n                    # dictionary. Make sure we separate them by time period.\n                    coefficients_dict[label + '_' + time] = results['popt']\n                    covariance_dict[label + '_' + time] = results['pcov']\n\n                    sigma = np.nanstd(residuals) * u.m/u.s\n\n                    sigmas_dict[label + '_' + time] = sigma\n                    sigma_sys_dict[label + '_' + time] = sys_err\n\n                    if time == 'pre':\n                        chi_squareds_pre.append(chi_squared_nu)\n                        sigmas_pre.append(sigma.value)\n                        sigma_sys_pre.append(sys_err.value)\n                    else:\n                        chi_squareds_post.append(chi_squared_nu)\n                        sigmas_post.append(sigma.value)\n                        sigma_sys_post.append(sys_err.value)\n\n                    for plot_type, lims in zip(('temp', 'mtl', 'logg'),\n                                               (temp_lims, mtl_lims,\n                                                logg_lims)):\n                        ax = axes_dict[f'{plot_type}_{time}']\n                        plot_data_points(ax,\n                                         ma.compressed(x_data[\n                                             param_dict[plot_type]]),\n                                         ma.compressed(residuals),\n                                         thick_err=ma.compressed(err_array),\n                                         # thin_err=iter_err_array,\n                                         thin_err=None,\n                                         era=time)\n                        if args.label_outliers:\n                            # Find outliers more than 3 sigma away from zero so\n                            # we can label them.\n                            labels = []\n                            for x, y, e in zip(range(len(\n                                    x_data[param_dict[plot_type]])), residuals,\n                                    err_array):\n                                sig_lim = args.sigma * e\n                                if abs(y) > sig_lim:\n                                    star_name = find_star(x_data[:, x],\n                                                          x_data, names)\n\n                                    labels.append(ax.text(\n                                        x_data[param_dict[plot_type], x],\n                                        y, star_name,\n                                        horizontalalignment='left',\n                                        verticalalignment='top',\n                                        size=8, weight='bold', color='Red'))\n                            # print(labels)\n                            adjust_text(labels,\n                                        ax=ax,\n                                        only_move={'points': 'y',\n                                                   'text': 'xy',\n                                                   'objects': 'xy'},\n                                        arrowprops=dict(arrowstyle='-',\n                                                        color='OliveDrab'),\n                                        autoalign=True,\n                                        lim=1000, fontsize=9)\n\n                        points = residuals.count()\n                        outliers = total_stars - points\n                        ax.annotate(f'Blendedness: {transition.blendedness}\\n'\n                                    f'Stars: {points}\\n'\n                                    f'Outliers: {outliers}',\n                                    (0.01, 0.99),\n                                    xycoords='axes fraction',\n                                    verticalalignment='top')\n                        ax.annotate(fr'$\\chi^2_\\nu$: {chi_squared_nu:.4f}'\n                                    '\\n'\n                                    fr'$\\sigma$: {sigma:.2f}'\n                                    '\\n'\n                                    r'$\\sigma_\\mathrm{sys}$:'\n                                    f' {sys_err:.2f}',\n                                    (0.99, 0.99),\n                                    xycoords='axes fraction',\n                                    horizontalalignment='right',\n                                    verticalalignment='top')\n                        data = np.array(ma.masked_invalid(\n                            residuals).compressed())\n                        axes_dict[f'hist_{time}'].hist(data,\n                                                       bins='fd',\n                                                       color='Black',\n                                                       histtype='step',\n                                                       orientation='horizontal')\n\n                file_name = plots_folder / f'{label}_{model_name}.png'\n                vprint(f'Saving file {label}.png')\n                vprint('\\n')\n\n                comp_fig.savefig(str(file_name))\n                plt.close('all')\n\n    elif args.pairs:\n        tqdm.write('Creating plots for each pair...')\n        for pair in tqdm(pairs_list):\n            for order_num in pair.ordersToMeasureIn:\n                index_nums.append(index_num)\n                index_num += 1\n                label = '_'.join([pair.label, str(order_num)])\n                vprint(20 * '-')\n                vprint(f'Analyzing {label}...')\n\n                # The column number to use for this transition:\n                col = pair_column_dict[label]\n                ylimits = (-300 * u.m / u.s,\n                           300 * u.m / u.s) if not args.full_range else None\n\n                comp_fig, axes_dict = create_comparison_figure(\n                                ylims=ylimits,\n                                fit_target='pairs',\n                                temp_lims=temp_lims,\n                                mtl_lims=mtl_lims,\n                                logg_lims=logg_lims)\n\n                for time in eras.keys():\n\n                    vprint(20 * '=')\n                    vprint(f'Working on {time}-change era.')\n                    mean = np.nanmean(star_pair_separations[eras[time],\n                                      :, col])\n\n                    # First, create a masked version to catch any missing\n                    # entries:\n                    m_seps = ma.masked_invalid(star_pair_separations[\n                                eras[time], :, col])\n                    total_stars = ma.count(m_seps)\n                    vprint(f'Found {total_stars} stars with data.')\n                    m_seps = m_seps.reshape([len(m_seps), 1])\n                    # Then create a new array from the non-masked data:\n                    separations = u.unyt_array(m_seps[~m_seps.mask],\n                                               units=u.m/u.s)\n                    vprint('Median of separations is'\n                           f' {np.nanmedian(separations)}')\n\n                    m_eotwms = ma.masked_invalid(star_pair_separations_EotWM[\n                            eras[time], :, col])\n                    m_eotwms = m_eotwms.reshape([len(m_eotwms), 1])\n                    eotwms = u.unyt_array(m_eotwms[~m_seps.mask],\n                                          units=u.m/u.s)\n\n                    m_eotms = ma.masked_invalid(star_pair_separations_EotM[\n                            eras[time], :, col])\n                    m_eotms = m_eotms.reshape([len(m_eotms), 1])\n                    # Use the same mask as for the offsets.\n                    eotms = u.unyt_array(m_eotms[~m_seps.mask],\n                                         units=u.m/u.s)\n                    # Create an error array which uses the greater of the error\n                    # on the mean or the error on the weighted mean.\n                    err_array = ma.array(np.maximum(eotwms, eotms).value)\n\n                    vprint(f'Mean is {np.mean(separations)}')\n                    weighted_mean = np.average(separations,\n                                               weights=err_array**-2)\n                    vprint(f'Weighted mean is {weighted_mean}')\n\n                    # Mask the various stellar parameter arrays with the same\n                    # mask so that everything stays in sync.\n                    temperatures = ma.masked_array(star_temperatures)\n                    temps = temperatures[~m_seps.mask]\n                    metallicities = ma.masked_array(star_metallicities)\n                    metals = metallicities[~m_seps.mask]\n                    gravities = ma.masked_array(star_gravities)\n                    loggs = gravities[~m_seps.mask]\n\n                    stars = ma.masked_array([key for key in\n                                             star_names.keys()]).reshape(\n                                                 len(star_names.keys()), 1)\n                    names = stars[~m_seps.mask]\n\n                    # Stack the stellar parameters into vertical slices\n                    # for passing to model functions.\n                    x_data = ma.array(np.stack((temps, metals, loggs), axis=0))\n\n                    # Create the parameter list for this run of fitting.\n                    params_list[0] = float(mean)\n\n                    beta0 = tuple(params_list)\n                    vprint(beta0)\n\n                    results = fit.find_sys_scatter(model_func,\n                                                   x_data,\n                                                   ma.array(separations.value),\n                                                   err_array, beta0,\n                                                   n_sigma=args.sigma,\n                                                   tolerance=0.001,\n                                                   verbose=args.verbose)\n\n                    mask = results['mask_list'][-1]\n                    residuals = ma.array(results['residuals'], mask=mask)\n                    x_data.mask = mask\n                    err_array.mask = mask\n\n                    chi_squared_nu = results['chi_squared_list'][-1]\n                    sys_err = results['sys_err_list'][-1] * u.m / u.s\n\n                    vprint(f'Terminated with sys_err = {sys_err}')\n                    vprint(f'Finished {label}_{time} in'\n                           f' {len(results[\"sys_err_list\"])} steps.')\n                    # Add the optimized parameters and covariances to the\n                    # dictionary. Make sure we separate them by time period.\n                    coefficients_dict[label + '_' + time] = results['popt']\n                    covariance_dict[label + '_' + time] = results['pcov']\n\n                    sigma = np.nanstd(residuals) * u.m/u.s\n\n                    sigmas_dict[label + '_' + time] = sigma\n                    sigma_sys_dict[label + '_' + time] = sys_err\n\n                    if time == 'pre':\n                        chi_squareds_pre.append(chi_squared_nu)\n                        sigmas_pre.append(sigma.value)\n                        sigma_sys_pre.append(sys_err.value)\n                    else:\n                        chi_squareds_post.append(chi_squared_nu)\n                        sigmas_post.append(sigma.value)\n                        sigma_sys_post.append(sys_err.value)\n\n                    for plot_type, lims in zip(('temp', 'mtl', 'logg'),\n                                               (temp_lims, mtl_lims,\n                                                logg_lims)):\n                        ax = axes_dict[f'{plot_type}_{time}']\n                        ax.tick_params(labelsize=14)\n                        plot_data_points(\n                            ax,\n                            ma.compressed(x_data[param_dict[plot_type]]),\n                            ma.compressed(residuals),\n                            thick_err=ma.compressed(err_array),\n                            # thin_err=None,\n                            thin_err=np.sqrt(ma.compressed(err_array) ** 2 +\n                                             sys_err.value ** 2),\n                            era=time)\n                        if args.label_outliers:\n                            # Find outliers more than 3 sigma away from zero so\n                            # we can label them.\n                            labels = []\n                            for x, y, e in zip(range(len(\n                                    x_data[param_dict[plot_type]])), residuals,\n                                    err_array):\n                                sig_lim = args.sigma * e\n                                if abs(y) > sig_lim:\n                                    star_name = find_star(x_data[:, x],\n                                                          x_data, names)\n\n                                    labels.append(ax.text(\n                                        x_data[param_dict[plot_type], x],\n                                        y, star_name,\n                                        horizontalalignment='left',\n                                        verticalalignment='top',\n                                        size=8, weight='bold', color='Red'))\n                            # print(labels)\n                            adjust_text(labels,\n                                        ax=ax,\n                                        only_move={'points': 'y',\n                                                   'text': 'xy',\n                                                   'objects': 'xy'},\n                                        arrowprops=dict(arrowstyle='-',\n                                                        color='OliveDrab'),\n                                        autoalign=True,\n                                        lim=1000, fontsize=9)\n\n                        points = residuals.count()\n                        outliers = total_stars - points\n                        ax.annotate(f'Blend tuple: {pair.blendTuple}\\n'\n                                    f'Stars: {points}\\n'\n                                    f'Outliers: {outliers}',\n                                    (0.01, 0.99),\n                                    xycoords='axes fraction',\n                                    verticalalignment='top')\n                        ax.annotate(fr'$\\chi^2_\\nu$: {chi_squared_nu:.4f}'\n                                    '\\n'\n                                    fr'$\\sigma$: {sigma:.2f}'\n                                    '\\n'\n                                    r'$\\sigma_\\mathrm{sys}$:'\n                                    f' {sys_err:.2f}',\n                                    (0.99, 0.99),\n                                    xycoords='axes fraction',\n                                    horizontalalignment='right',\n                                    verticalalignment='top')\n                        data = np.array(ma.masked_invalid(\n                            residuals).compressed())\n                        axes_dict[f'hist_{time}'].hist(data,\n                                                       bins='fd',\n                                                       color='Black',\n                                                       histtype='step',\n                                                       orientation='horizontal')\n\n                file_name = plots_folder / f'{label}_{model_name}.png'\n                vprint(f'Saving file {label}.png')\n                vprint('\\n')\n\n                comp_fig.savefig(str(file_name))\n                plt.close('all')\n\n    # Save metadata from this run's fits to CSV:\n    csv_file = plots_folder / f'{model_name}_{fit_target}_fit_results.csv'\n\n    with open(csv_file, 'w', newline='') as f:\n        datawriter = csv.writer(f)\n        header = ('#index', 'chi_squared_pre', 'sigma_pre', 'sigma_sys_pre',\n                  'chi_squared_post', 'sigma_post', 'sigma_sys_post')\n        datawriter.writerow(header)\n        for row in zip(index_nums, chi_squareds_pre, sigmas_pre, sigma_sys_pre,\n                       chi_squareds_post, sigmas_post, sigma_sys_post):\n            datawriter.writerow(row)\n\n    # Save the function used and the parameters found for each transition/pair\n    # to an HDF5 file for use in other scripts.\n    output_dir = output_dir / 'fit_params'\n    hdf5_file = output_dir /\\\n        f'{model_name}_{fit_target}_{args.sigma:.1f}sigma_params.hdf5'\n    if not hdf5_file.parent.exists():\n        os.mkdir(hdf5_file.parent)\n\n    vprint(f'Writing HDF5 file with fit parameters at {hdf5_file}')\n    if hdf5_file.exists():\n        os.unlink(hdf5_file)\n    with h5py.File(hdf5_file, mode='a') as f:\n        f.attrs['type'] = 'A file containing a fitting function and the' +\\\n                          ' parameters for it for each transition or pair' +\\\n                          'in /coeffs_dict'\n        hickle.dump(model_func, f, path='/fitting_function')\n        hickle.dump(coefficients_dict, f, path='/coeffs_dict')\n        hickle.dump(covariance_dict, f, path='/covariance_dict')\n        hickle.dump(sigmas_dict, f, path='/sigmas_dict')\n        hickle.dump(sigma_sys_dict, f, path='/sigma_sys_dict')\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(description='Use stored data from stars'\n                                     ' to fit transition offsets to stellar'\n                                     ' parameters.')\n    parser.add_argument('--full-range', action='store_true',\n                        help='Plot the full range of values instead of'\n                        ' restricting to a  fixed range.')\n    parser.add_argument('--label-outliers', action='store_true',\n                        help='Label the points which are more than'\n                        ' 3 sigma away from the mean.')\n    parser.add_argument('-v', '--verbose', action='store_true',\n                        help='Print out more information about the script.')\n\n    parser.add_argument('--sigma', action='store', type=float, default=2.5,\n                        help='The number to use (in standard deviations)'\n                        ' beyond which to consider a data point an outlier.')\n\n    func = parser.add_mutually_exclusive_group(required=True)\n    func.add_argument('--constant', action='store_true',\n                      help='Use a constant function.')\n    func.add_argument('--linear', action='store_true',\n                      help='Use a function linear in all three variables.')\n    func.add_argument('--quadratic', action='store_true',\n                      help='Use a function quadratic in all three variables.')\n    func.add_argument('--cubic', action='store_true',\n                      help='Use a cubic function for all three variables.')\n    func.add_argument('--quartic', action='store_true',\n                      help='Use a quartic function for all three variables.')\n    func.add_argument('--quintic', action='store_true',\n                      help='Use a quintic function for all three variables.')\n    func.add_argument('--cross-term', action='store_true',\n                      help='Use a linear model with cross term ([Fe/H]/Teff).')\n    func.add_argument('--quadratic-cross-term', action='store_true',\n                      help='Use a quadratic model with cross terms between'\n                      ' metallicity and temperature.')\n    func.add_argument('--quadratic-magnitude', action='store_true',\n                      help='Use a cross term with quadratic magnitude.')\n    func.add_argument('--quad-cross-terms', action='store_true',\n                      help='Use a quadratic model with full cross terms.')\n\n    fit_target = parser.add_mutually_exclusive_group(required=True)\n    fit_target.add_argument('-T', '--transitions', action='store_true',\n                            help='Fit individual transitions.')\n    fit_target.add_argument('-P', '--pairs', action='store_true',\n                            help='Fit pairs.')\n\n    args = parser.parse_args()\n\n    vprint = vcl.verbose_print(args.verbose)\n\n    start_time = time()\n\n    main()\n\n    duration = time() - start_time\n    print(f'Finished in {duration:.2f} seconds.')\n", "meta": {"hexsha": "b2970559e3d7685f581547d0a7346f86ea98efba", "size": 41286, "ext": "py", "lang": "Python", "max_stars_repo_path": "varconlib/scripts/multi_fit_stars.py", "max_stars_repo_name": "DBerke/varconlib", "max_stars_repo_head_hexsha": "4771cf315c8fa76e1982612f3ac520c0cec098d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "varconlib/scripts/multi_fit_stars.py", "max_issues_repo_name": "DBerke/varconlib", "max_issues_repo_head_hexsha": "4771cf315c8fa76e1982612f3ac520c0cec098d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "varconlib/scripts/multi_fit_stars.py", "max_forks_repo_name": "DBerke/varconlib", "max_forks_repo_head_hexsha": "4771cf315c8fa76e1982612f3ac520c0cec098d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.5456595265, "max_line_length": 80, "alphanum_fraction": 0.4992491401, "include": true, "reason": "import numpy,from scipy", "num_tokens": 8353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.18809850625490437}}
{"text": "\"\"\"\n##################################################################################################\n# Copyright Info :    Copyright (c) Davar Lab @ Hikvision Research Institute. All rights reserved.\n# Filename       :    affine_transformation.py\n# Abstract       :    Implementations of the affine transformation\n\n# Current Version:    1.0.0\n# Date           :    2021-03-07\n##################################################################################################\n\"\"\"\nimport logging\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom mmcv.runner import load_checkpoint\n\nfrom ..builder import TRANSFORMATIONS\n\n\n@TRANSFORMATIONS.register_module()\nclass Affine_SpatialTransformer(nn.Module):\n    \"\"\" Rectification Network of RARE, namely Affine-based STN [1]\n\n    Ref: [1] Spatial Transformer Network. NIPS-2016\n\n    Usage:\n    transformation=dict(\n         type='Affine_SpatialTransformer',\n         I_size=(32, 100),\n         I_r_size=(32, 100),\n         I_channel_num=1),\n\n    \"\"\"\n\n    def __init__(self,\n                 I_size,\n                 I_r_size,\n                 I_channel_num=1,\n                 fix_transformation=False):\n        \"\"\"\n        Spatial Transformation Network based on Affine\n\n        Args:\n            I_size (tuple): size of input images\n            I_r_size (tuple): size of rectified images\n            I_channel_num (int): the number of channels of the input image I\n            fix_transformation (bool): if fix the parameters of the transformation during training\n\n        \"\"\"\n        super(Affine_SpatialTransformer, self).__init__()\n        self.I_size = I_size\n        self.I_r_size = I_r_size\n        self.I_channel_num = I_channel_num\n        self.LocalizationNetwork = AffineLocalizationNetwork(self.I_channel_num, self.I_size)\n\n        # if set STN parameters fixed, the weights and bias of all layers are set to False\n        if fix_transformation:\n            for p in self.LocalizationNetwork.parameters():\n                p.requires_grad = False\n\n    def init_weights(self, pretrained=None):\n        \"\"\"\n\n        Args:\n            pretrained (str): save path of pretrained model\n\n\n        \"\"\"\n        if isinstance(pretrained, str):\n            logger = logging.getLogger()\n            logger.info(\"Affine_SpatialTransformer:\")\n            load_checkpoint(self, pretrained,\n                            strict=False, logger=logger)\n\n    def forward(self, batch_I):\n        \"\"\"\n\n        Args:\n            batch_I (tensor): batch of input images[batch_size x I_channel_num x I_r_height x I_r_width]\n\n        Returns:\n            torch.Tensor: rectified image [batch_size x I_channel_num x I_r_height x I_r_width]\n\n        \"\"\"\n        xy_batch_C_prime = self.LocalizationNetwork(batch_I).view(-1, 2, 3)\n\n        row_rev = torch.cat([xy_batch_C_prime[:, 1], xy_batch_C_prime[:, 0]], 1).view(-1, 2, 3).permute(0, 2, 1)\n        colomn_rev = torch.cat([row_rev[:, 1], row_rev[:, 0]], 1)\n        colomn_rev = torch.cat([colomn_rev, row_rev[:, 2]], 1).view(-1, 3, 2).permute(0, 2, 1)\n        batch_C_prime = colomn_rev\n\n        build_P_prime = F.affine_grid(batch_C_prime, torch.Size((batch_C_prime.size(0),\n                                                                 self.I_channel_num,\n                                                                 self.I_r_size[0],\n                                                                 self.I_r_size[1])))\n\n        batch_I_r = F.grid_sample(batch_I, build_P_prime, padding_mode='border')\n\n        return batch_I_r\n\n\nclass AffineLocalizationNetwork(nn.Module):\n    \"\"\"\n    Localization Network of STN,\n    which predicts 6 params of Affine Transformation\n\n    \"\"\"\n\n    def __init__(self, I_channel_num, I_size):\n        \"\"\"\n        Args:\n            I_channel_num (int): channel number of input\n            I_size (tuple): input image size\n        \"\"\"\n        super(AffineLocalizationNetwork, self).__init__()\n        self.I_channel_num = I_channel_num\n        self.I_size = I_size\n        self.loc_conv1_channel = nn.Conv2d(in_channels=self.I_channel_num,\n                                           out_channels=48, kernel_size=3,\n                                           stride=1, padding=1)\n        self.loc_relu1 = nn.ReLU(inplace=True)\n        self.loc_pool1 = nn.MaxPool2d(2, 2)\n        self.loc_conv2_channel = nn.Conv2d(48, 48,\n                                           3, 1, 1)\n        self.loc_relu2_new = nn.ReLU(inplace=True)\n        self.loc_pool2_new = nn.MaxPool2d(2, 2)\n        self.loc_conv3_channel = nn.Conv2d(48, 64,\n                                           3, 1, 1)\n        self.loc_relu3_new = nn.ReLU(inplace=True)\n        self.loc_pool3_new = nn.MaxPool2d(2, 2)\n        self.loc_conv4_channel_64 = nn.Conv2d(64, 64,\n                                              3, 1, 1)\n        self.loc_relu4 = nn.ReLU(inplace=True)\n        self.loc_pool4 = nn.MaxPool2d(2, 2)\n\n        self.loc_relu5 = nn.ReLU(inplace=True)\n        self.loc_reg = nn.Linear(768, 6)\n\n        # Init fc2 in LocalizationNetwork\n        self.loc_reg.weight.data.fill_(0)\n        initial_bias = np.array([1, 0, 0, 0, 1, 0])\n        self.loc_reg.bias.data = torch.from_numpy(initial_bias).float().view(-1)\n\n        # for item in self.no_update:\n        #    item.weight.requires_grad = False\n        #    item.bias.requires_grad = False\n\n    def forward(self, x):\n        \"\"\"\n        Args:\n            x (tensor): input image feature maps [batch_size x I_channel_num x I_height x I_width]\n\n        Returns:\n            torch.Tensor: Predicted coordinates of fiducial points for input batch [batch_size x F x 2]\n        \"\"\"\n        batch_size = x.size(0)\n        x = self.loc_conv1_channel(x)\n        x = self.loc_relu1(x)\n        x = self.loc_pool1(x)\n        x = self.loc_conv2_channel(x)\n        x = self.loc_relu2_new(x)\n        x = self.loc_pool2_new(x)\n        x = self.loc_conv3_channel(x)\n        x = self.loc_relu3_new(x)\n        x = self.loc_pool3_new(x)\n        x = self.loc_conv4_channel_64(x)\n        x = self.loc_relu4(x)\n        x = self.loc_pool4(x)\n\n        y = x.view(batch_size, -1)\n        y = self.loc_relu5(y)\n        batch_C_prime = self.loc_reg(y)\n\n        return batch_C_prime\n", "meta": {"hexsha": "8e750da3ec21de0ed30a53b13ecee4cd4eb83c11", "size": 6236, "ext": "py", "lang": "Python", "max_stars_repo_path": "davarocr/davarocr/davar_rcg/models/transformations/affine_transformation.py", "max_stars_repo_name": "icedream2/DAVAR-Lab-OCR", "max_stars_repo_head_hexsha": "c8b82f45516850eeadcab2739fb2a4292f2fdca1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 387, "max_stars_repo_stars_event_min_datetime": "2021-01-02T07:50:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:30:03.000Z", "max_issues_repo_path": "davarocr/davarocr/davar_rcg/models/transformations/affine_transformation.py", "max_issues_repo_name": "icedream2/DAVAR-Lab-OCR", "max_issues_repo_head_hexsha": "c8b82f45516850eeadcab2739fb2a4292f2fdca1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 70, "max_issues_repo_issues_event_min_datetime": "2021-05-04T18:28:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:14:52.000Z", "max_forks_repo_path": "davarocr/davarocr/davar_rcg/models/transformations/affine_transformation.py", "max_forks_repo_name": "icedream2/DAVAR-Lab-OCR", "max_forks_repo_head_hexsha": "c8b82f45516850eeadcab2739fb2a4292f2fdca1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2021-01-05T08:28:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:14:03.000Z", "avg_line_length": 35.0337078652, "max_line_length": 112, "alphanum_fraction": 0.5601347017, "include": true, "reason": "import numpy", "num_tokens": 1452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.18809849907238693}}
{"text": "\"\"\"\nCalculate driving_force due to ZPF tielines.\n\nThe general approach is similar to the PanOptimizer rough search method.\n\n1. With all phases active, calculate the chemical potentials of the tieline\n   endpoints via ``equilibrium`` calls. Done in ``estimate_hyperplane``.\n2. Calculate the target chemical potentials, which are the average chemical\n   potentials of all of the current chemical potentials at the tieline endpoints.\n3. Calculate the current chemical potentials of the desired single phases\n4. The error is the difference between these chemical potentials\n\nThere's some special handling for tieline endpoints where we do not know the\ncomposition conditions to calculate chemical potentials at.\n\"\"\"\n\nimport logging\nfrom dataclasses import dataclass\nfrom collections import OrderedDict\nfrom typing import Sequence, Dict, Any, Union, List, Tuple, Type, Optional\n\nimport numpy as np\nfrom numpy.typing import ArrayLike\nfrom scipy.stats import norm\nimport tinydb\n\nfrom pycalphad import Database, Model, variables as v\nfrom pycalphad.codegen.callables import build_phase_records\nfrom pycalphad.core.utils import instantiate_models, filter_phases, unpack_components\nfrom pycalphad.core.phase_rec import PhaseRecord\nfrom espei.utils import PickleableTinyDB\nfrom espei.shadow_functions import equilibrium_, calculate_, no_op_equilibrium_, update_phase_record_parameters, constrained_equilibrium\nfrom pycalphad.core.calculate import _sample_phase_constitution\nfrom pycalphad.core.utils import point_sample\n\n_log = logging.getLogger(__name__)\n\n\n@dataclass\nclass RegionVertex:\n    phase_name: str\n    composition: ArrayLike  # 1D of size (number nonvacant pure elements)\n    comp_conds: Dict[v.X, float]\n    points: ArrayLike\n    phase_records: Dict[str, PhaseRecord]\n    is_disordered: bool\n    has_missing_comp_cond: bool\n\n@dataclass\nclass PhaseRegion:\n    vertices: Sequence[RegionVertex]\n    potential_conds: Dict[v.StateVariable, float]\n    species: Sequence[v.Species]\n    phases: Sequence[str]\n    models: Dict[str, Model]\n\n    def eq_str(self):\n        phase_compositions = ', '.join(f'{vtx.phase_name}: {vtx.comp_conds}' for vtx in self.vertices)\n        return f\"conds: ({self.potential_conds}), comps: ({phase_compositions})\"\n\n\ndef _extract_pot_conds(all_conditions: Dict[v.StateVariable, np.ndarray], idx: int) -> Dict[v.StateVariable, float]:\n    \"\"\"Conditions are either scalar or 1d arrays for the conditions in the entire dataset.\n    This function extracts the condition corresponding to the current region,\n    based on the index in the 1d condition array.\n    \"\"\"\n    pot_conds = {}  # e.g. v.P, v.T\n    for cond_key, cond_val in all_conditions.items():\n        cond_val = np.atleast_1d(np.asarray(cond_val))\n        # If the conditions is an array, we want the corresponding value\n        # Otherwise treat it as a scalar\n        if len(cond_val) > 1:\n            cond_val = cond_val[idx]\n        pot_conds[getattr(v, cond_key)] = float(cond_val)\n    return pot_conds\n\n\ndef _extract_phases_comps(vertex):\n    \"\"\"Extract the phase name, phase compositions and disordered flag from a vertex\n    \"\"\"\n    if len(vertex) == 4:  # phase_flag within\n        phase_name, components, compositions, flag = vertex\n        if flag == \"disordered\":\n            disordered_flag = True\n        else:\n            disordered_flag = False\n    elif len(vertex) == 3:  # no phase_flag within\n        phase_name, components, compositions = vertex\n        disordered_flag = False\n    else:\n        raise ValueError(\"Wrong number of data in tie-line point\")\n    comp_conds = dict(zip(map(v.X, map(str.upper, components)), compositions))\n    return phase_name, comp_conds, disordered_flag\n\n\ndef _phase_is_stoichiometric(mod):\n    return all(len(subl) == 1 for subl in mod.constituents)\n\n\ndef _compute_vertex_composition(comps: Sequence[str], comp_conds: Dict[str, float]):\n    \"\"\"Compute the overall composition in a vertex assuming an N=1 normalization condition\"\"\"\n    pure_elements = sorted(c for c in comps if c != 'VA')\n    vertex_composition = np.empty(len(pure_elements), dtype=np.float_)\n    unknown_indices = []\n    for idx, el in enumerate(pure_elements):\n        amt = comp_conds.get(v.X(el), None)\n        if amt is None:\n            unknown_indices.append(idx)\n            vertex_composition[idx] = np.nan\n        else:\n            vertex_composition[idx] = amt\n    if len(unknown_indices) == 1:\n        # Determine the dependent component by mass balance\n        vertex_composition[unknown_indices[0]] = 1 - np.nansum(vertex_composition)\n    return vertex_composition\n\n\ndef _subsample_phase_points(phase_record, phase_points, target_composition, avg_mass_residual_tol=0.02):\n    # Compute the mole fractions of each point\n    phase_compositions = np.zeros((phase_points.shape[0], target_composition.size), order='F')\n    # TODO: potential bug here if the composition has dependence (even piecewise\n    #   dependence) in the state variables. The compositions may be nan in this case.\n    statevar_placeholder = np.ones((phase_points.shape[0], phase_record.num_statevars))\n    dof = np.hstack((statevar_placeholder, phase_points))\n    for el_idx in range(target_composition.size):\n        phase_record.mass_obj_2d(phase_compositions[:, el_idx], dof, el_idx)\n\n    # Find the points indicdes where the mass is within the average mass residual tolerance\n    idxs = np.nonzero(np.mean(np.abs(phase_compositions - target_composition), axis=1) < avg_mass_residual_tol)[0]\n\n    # Return the sub-space of points where this condition holds valid\n    return phase_points[idxs]\n\n\ndef get_zpf_data(dbf: Database, comps: Sequence[str], phases: Sequence[str], datasets: PickleableTinyDB, parameters: Dict[str, float], model: Optional[Dict[str, Type[Model]]] = None):\n    \"\"\"\n    Return the ZPF data used in the calculation of ZPF error\n\n    Parameters\n    ----------\n    comps : list\n        List of active component names\n    phases : list\n        List of phases to consider\n    datasets : espei.utils.PickleableTinyDB\n        Datasets that contain single phase data\n    parameters : dict\n        Dictionary mapping symbols to optimize to their initial values\n    model : Optional[Dict[str, Type[Model]]]\n        Dictionary phase names to pycalphad Model classes.\n\n    Returns\n    -------\n    list\n        List of data dictionaries with keys ``weight``, ``phase_regions`` and ``dataset_references``.\n    \"\"\"\n    desired_data = datasets.search((tinydb.where('output') == 'ZPF') &\n                                   (tinydb.where('components').test(lambda x: set(x).issubset(comps))) &\n                                   (tinydb.where('phases').test(lambda x: len(set(phases).intersection(x)) > 0)))\n\n    zpf_data = []  # 1:1 correspondence with each dataset\n    for data in desired_data:\n        data_comps = list(set(data['components']).union({'VA'}))\n        species = sorted(unpack_components(dbf, data_comps), key=str)\n        data_phases = filter_phases(dbf, species, candidate_phases=phases)\n        models = instantiate_models(dbf, species, data_phases, model=model, parameters=parameters)\n        all_phase_points = {phase_name: _sample_phase_constitution(models[phase_name], point_sample, True, 50) for phase_name in data_phases}\n        all_regions = data['values']\n        conditions = data['conditions']\n        phase_regions = []\n        # Each phase_region is one set of phases in equilibrium (on a tie-line),\n        # e.g. [[\"ALPHA\", [\"B\"], [0.25]], [\"BETA\", [\"B\"], [0.5]]]\n        for idx, phase_region in enumerate(all_regions):\n            # Extract the conditions for entire phase region\n            pot_conds = _extract_pot_conds(conditions, idx)\n            pot_conds.setdefault(v.N, 1.0) # Add v.N condition, if missing\n            # Extract all the phases and compositions from the tie-line points\n            vertices = []\n            for vertex in phase_region:\n                phase_name, comp_conds, disordered_flag = _extract_phases_comps(vertex)\n                phase_recs = build_phase_records(dbf, species, data_phases, {**pot_conds, **comp_conds}, models, parameters=parameters, build_gradients=True, build_hessians=True)\n                # Construct single-phase points satisfying the conditions for each phase in the region\n                mod = models[phase_name]\n                composition = _compute_vertex_composition(data_comps, comp_conds)\n                if np.any(np.isnan(composition)):\n                    # We can't construct points because we don't have a known composition\n                    has_missing_comp_cond = True\n                    phase_points = None\n                elif _phase_is_stoichiometric(mod):\n                    has_missing_comp_cond = False\n                    phase_points = None\n                else:\n                    has_missing_comp_cond = False\n                    # Only sample points that have an average mass residual within tol\n                    tol = 0.05\n                    phase_points = _subsample_phase_points(phase_recs[phase_name], all_phase_points[phase_name], composition, tol)\n                    assert phase_points.shape[0] > 0, \"at least one set of points is within the target tolerance\"\n                vtx = RegionVertex(phase_name, composition, comp_conds, phase_points, phase_recs, disordered_flag, has_missing_comp_cond)\n                vertices.append(vtx)\n            region = PhaseRegion(vertices, pot_conds, species, data_phases, models)\n            phase_regions.append(region)\n\n        data_dict = {\n            'weight': data.get('weight', 1.0),\n            'phase_regions': phase_regions,\n            'dataset_reference': data['reference']\n        }\n        zpf_data.append(data_dict)\n    return zpf_data\n\n\ndef estimate_hyperplane(phase_region: PhaseRegion, parameters: np.ndarray, approximate_equilibrium: bool = False) -> np.ndarray:\n    \"\"\"\n    Calculate the chemical potentials for the target hyperplane, one vertex at a time\n\n    Notes\n    -----\n    This takes just *one* set of phase equilibria, a phase region, e.g. a dataset point of\n    [['FCC_A1', ['CU'], [0.1]], ['LAVES_C15', ['CU'], [0.3]]]\n    and calculates the chemical potentials given all the phases possible at the\n    given compositions. Then the average chemical potentials of each end point\n    are taken as the target hyperplane for the given equilibria.\n\n    \"\"\"\n    if approximate_equilibrium:\n        _equilibrium = no_op_equilibrium_\n    else:\n        _equilibrium = equilibrium_\n    target_hyperplane_chempots = []\n    target_hyperplane_phases = []\n    species = phase_region.species\n    phases = phase_region.phases\n    models = phase_region.models\n    for vertex in phase_region.vertices:\n        phase_records = vertex.phase_records\n        update_phase_record_parameters(phase_records, parameters)\n        cond_dict = {**vertex.comp_conds, **phase_region.potential_conds}\n        if vertex.has_missing_comp_cond:\n            # This composition is unknown -- it doesn't contribute to hyperplane estimation\n            pass\n        else:\n            # Extract chemical potential hyperplane from multi-phase calculation\n            # Note that we consider all phases in the system, not just ones in this tie region\n            str_statevar_dict = OrderedDict([(str(key), cond_dict[key]) for key in sorted(phase_region.potential_conds.keys(), key=str)])\n            grid = calculate_(species, phases, str_statevar_dict, models, phase_records, pdens=50, fake_points=True)\n            multi_eqdata = _equilibrium(phase_records, cond_dict, grid)\n            target_hyperplane_phases.append(multi_eqdata.Phase.squeeze())\n            # Does there exist only a single phase in the result with zero internal degrees of freedom?\n            # We should exclude those chemical potentials from the average because they are meaningless.\n            num_phases = np.sum(multi_eqdata.Phase.squeeze() != '')\n            Y_values = multi_eqdata.Y.squeeze()\n            no_internal_dof = np.all((np.isclose(Y_values, 1.)) | np.isnan(Y_values))\n            MU_values = multi_eqdata.MU.squeeze()\n            if (num_phases == 1) and no_internal_dof:\n                target_hyperplane_chempots.append(np.full_like(MU_values, np.nan))\n            else:\n                target_hyperplane_chempots.append(MU_values)\n    target_hyperplane_mean_chempots = np.nanmean(target_hyperplane_chempots, axis=0, dtype=np.float_)\n    return target_hyperplane_mean_chempots\n\n\ndef driving_force_to_hyperplane(target_hyperplane_chempots: np.ndarray,\n                                phase_region: PhaseRegion, vertex: RegionVertex,\n                                parameters: np.ndarray, approximate_equilibrium: bool = False) -> float:\n    \"\"\"Calculate the integrated driving force between the current hyperplane and target hyperplane.\n    \"\"\"\n    species = phase_region.species\n    models = phase_region.models\n    current_phase = vertex.phase_name\n    cond_dict = {**phase_region.potential_conds, **vertex.comp_conds}\n    str_statevar_dict = OrderedDict([(str(key),cond_dict[key]) for key in sorted(phase_region.potential_conds.keys(), key=str)])\n    phase_points = vertex.points\n    phase_records = vertex.phase_records\n    update_phase_record_parameters(phase_records, parameters)\n    if phase_points is None:\n        # We don't have the phase composition here, so we estimate the driving force.\n        # Can happen if one of the composition conditions is unknown or if the phase is\n        # stoichiometric and the user did not specify a valid phase composition.\n        single_eqdata = calculate_(species, [current_phase], str_statevar_dict, models, phase_records, pdens=50)\n        df = np.multiply(target_hyperplane_chempots, single_eqdata.X).sum(axis=-1) - single_eqdata.GM\n        driving_force = float(df.max())\n    elif vertex.is_disordered:\n        # Construct disordered sublattice configuration from composition dict\n        # Compute energy\n        # Compute residual driving force\n        # TODO: Check that it actually makes sense to declare this phase 'disordered'\n        num_dof = sum([len(subl) for subl in models[current_phase].constituents])\n        desired_sitefracs = np.ones(num_dof, dtype=np.float_)\n        dof_idx = 0\n        for subl in models[current_phase].constituents:\n            dof = sorted(subl, key=str)\n            num_subl_dof = len(subl)\n            if v.Species(\"VA\") in dof:\n                if num_subl_dof == 1:\n                    _log.debug('Cannot predict the site fraction of vacancies in the disordered configuration %s of %s. Returning driving force of zero.', subl, current_phase)\n                    return 0\n                else:\n                    sitefracs_to_add = [1.0]\n            else:\n                sitefracs_to_add = np.array([cond_dict.get(v.X(d)) for d in dof], dtype=np.float_)\n                # Fix composition of dependent component\n                sitefracs_to_add[np.isnan(sitefracs_to_add)] = 1 - np.nansum(sitefracs_to_add)\n            desired_sitefracs[dof_idx:dof_idx + num_subl_dof] = sitefracs_to_add\n            dof_idx += num_subl_dof\n        single_eqdata = calculate_(species, [current_phase], str_statevar_dict, models, phase_records, points=np.asarray([desired_sitefracs]))\n        driving_force = np.multiply(target_hyperplane_chempots, single_eqdata.X).sum(axis=-1) - single_eqdata.GM\n        driving_force = float(np.squeeze(driving_force))\n    else:\n        # Extract energies from single-phase calculations\n        grid = calculate_(species, [current_phase], str_statevar_dict, models, phase_records, points=phase_points, pdens=50, fake_points=True)\n        # TODO: consider enabling approximate for this?\n        converged, energy = constrained_equilibrium(phase_records, cond_dict, grid)\n        if not converged:\n            _log.debug('Calculation failure: constrained equilibrium not converged for %s, conditions: %s, parameters %s', current_phase, cond_dict, parameters)\n            return np.inf\n        driving_force = float(np.dot(target_hyperplane_chempots, vertex.composition) - float(energy))\n    return driving_force\n\n\ndef calculate_zpf_driving_forces(zpf_data: Sequence[Dict[str, Any]],\n                                 parameters: ArrayLike = None,\n                                 approximate_equilibrium: bool = False,\n                                 short_circuit: bool = False\n                                 ) -> Tuple[List[List[float]], List[List[float]]]:\n    \"\"\"\n    Calculate error due to phase equilibria data\n\n    zpf_data : Sequence[Dict[str, Any]]\n        Datasets that contain single phase data\n    parameters : ArrayLike\n        Array of parameters to calculate the error with.\n    approximate_equilibrium : bool\n        Whether or not to use an approximate version of equilibrium that does\n        not refine the solution and uses ``starting_point`` instead.\n    short_circuit: bool\n        If True, immediately return a size 1 array with a driving force of\n        ``np.nan`` (failed hyperplane) or ``np.inf`` (failed driving force).\n        Can save computational time if the caller will aggregate driving forces.\n\n    Returns\n    -------\n    Tuple[List[List[float]], List[List[float]]]\n        Driving forces and weights as ragged 2D arrays with shape\n        ``(len(zpf_data), len(vertices in each zpf_data))``\n\n    Notes\n    -----\n    The physical picture of the standard deviation is that we've measured a ZPF\n    line. That line corresponds to some equilibrium chemical potentials. The\n    standard deviation is the standard deviation of those 'measured' chemical\n    potentials.\n\n    \"\"\"\n    if parameters is None:\n        parameters = np.array([])\n    driving_forces = []\n    weights = []\n    for data in zpf_data:\n        data_driving_forces = []\n        data_weights = []\n        weight = data['weight']\n        dataset_ref = data['dataset_reference']\n        # for the set of phases and corresponding tie-line verticies in equilibrium\n        for phase_region in data['phase_regions']:\n            # 1. Calculate the average multiphase hyperplane\n            eq_str = phase_region.eq_str()\n            target_hyperplane = estimate_hyperplane(phase_region, parameters, approximate_equilibrium=approximate_equilibrium)\n            if np.any(np.isnan(target_hyperplane)):\n                _log.debug('NaN target hyperplane. Equilibria: (%s), driving force: 0.0, reference: %s.', eq_str, dataset_ref)\n                data_driving_forces.extend([0]*len(phase_region.vertices))\n                data_weights.extend([weight]*len(phase_region.vertices))\n                continue\n            # 2. Calculate the driving force to that hyperplane for each vertex\n            for vertex in phase_region.vertices:\n                driving_force = driving_force_to_hyperplane(target_hyperplane, phase_region, vertex, parameters,\n                                                            approximate_equilibrium=approximate_equilibrium,\n                                                            )\n                if np.isinf(driving_force) and short_circuit:\n                    _log.debug('Equilibria: (%s), current phase: %s, hyperplane: %s, driving force: %s, reference: %s. Short circuiting.', eq_str, vertex.phase_name, target_hyperplane, driving_force, dataset_ref)\n                    return [[np.inf]], [[np.inf]]\n                data_driving_forces.append(driving_force)\n                data_weights.append(weight)\n                _log.debug('Equilibria: (%s), current phase: %s, hyperplane: %s, driving force: %s, reference: %s', eq_str, vertex.phase_name, target_hyperplane, driving_force, dataset_ref)\n        driving_forces.append(data_driving_forces)\n        weights.append(data_weights)\n    return driving_forces, weights\n\n\ndef calculate_zpf_error(zpf_data: Sequence[Dict[str, Any]],\n                        parameters: np.ndarray = None,\n                        data_weight: int = 1.0,\n                        approximate_equilibrium: bool = False) -> float:\n    \"\"\"\n    Calculate the likelihood due to phase equilibria data.\n\n    For detailed documentation, see ``calculate_zpf_driving_forces``\n\n    Returns\n    -------\n    float\n        Log probability of ZPF driving forces\n\n    \"\"\"\n    if len(zpf_data) == 0:\n        return 0.0\n    driving_forces, weights = calculate_zpf_driving_forces(zpf_data, parameters, approximate_equilibrium, short_circuit=True)\n    # Driving forces and weights are 2D ragged arrays with the shape (len(zpf_data), len(zpf_data['values']))\n    driving_forces = np.concatenate(driving_forces)\n    weights = np.concatenate(weights)\n    if np.any(np.logical_or(np.isinf(driving_forces), np.isnan(driving_forces))):\n        return -np.inf\n    log_probabilites = norm.logpdf(driving_forces, loc=0, scale=1000/data_weight/weights)\n    _log.debug('Data weight: %s, driving forces: %s, weights: %s, probabilities: %s', data_weight, driving_forces, weights, log_probabilites)\n    return np.sum(log_probabilites)\n", "meta": {"hexsha": "be531507201a7b47accc067e0fbd5b89bd70cd46", "size": 20917, "ext": "py", "lang": "Python", "max_stars_repo_path": "espei/error_functions/zpf_error.py", "max_stars_repo_name": "semikk/ESPEI", "max_stars_repo_head_hexsha": "81f28a0a28307217b527890db254f31f07d76440", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "espei/error_functions/zpf_error.py", "max_issues_repo_name": "semikk/ESPEI", "max_issues_repo_head_hexsha": "81f28a0a28307217b527890db254f31f07d76440", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "espei/error_functions/zpf_error.py", "max_forks_repo_name": "semikk/ESPEI", "max_forks_repo_head_hexsha": "81f28a0a28307217b527890db254f31f07d76440", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.4024096386, "max_line_length": 212, "alphanum_fraction": 0.6785389874, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 4644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.33458945452352534, "lm_q1q2_score": 0.18809832877732338}}
{"text": "\"\"\"\nhalo finding\n\n\n\n\"\"\"\n\n#-----------------------------------------------------------------------------\n# Copyright (c) yt Development Team. All rights reserved.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n#-----------------------------------------------------------------------------\n\nimport gc\nimport numpy as np\n\nfrom yt.config import ytcfg\nfrom yt.funcs import mylog\nfrom yt.utilities.math_utils import \\\n    get_rotation_matrix, \\\n    periodic_dist\nfrom yt.utilities.physical_constants import \\\n    mass_sun_cgs\nfrom yt.utilities.physical_ratios import \\\n    rho_crit_g_cm3_h2, \\\n    TINY\nfrom yt.utilities.parallel_tools.parallel_analysis_interface import \\\n    ParallelAnalysisInterface\n\nfrom yt_astro_analysis.halo_analysis.halo_finding.hop.EnzoHop import RunHOP\nfrom yt_astro_analysis.halo_analysis.halo_finding.fof.EnzoFOF import RunFOF\n\nclass Halo(object):\n    \"\"\"\n    A data source that returns particle information about the members of a\n    HOP-identified halo.\n    \"\"\"\n    _distributed = False\n    _processing = False\n    _owner = 0\n    indices = None\n    extra_wrap = [\"__getitem__\"]\n\n    def __init__(self, halo_list, id, indices=None, size=None, CoM=None,\n        max_dens_point=None, group_total_mass=None, max_radius=None,\n        bulk_vel=None, tasks=None, rms_vel=None, supp=None, ptype='all'):\n        self.ptype = ptype\n        self.halo_list = halo_list\n        self._max_dens = halo_list._max_dens\n        self.id = id\n        self.data = halo_list._data_source\n        self.ds = self.data.ds\n        self.gridsize = (self.ds.domain_right_edge - \\\n                 self.ds.domain_left_edge)\n        if indices is not None:\n            self.indices = halo_list._base_indices[indices]\n        else:\n            self.indices = None\n        # We assume that if indices = None, the instantiator has OTHER plans\n        # for us -- i.e., setting it somehow else\n        self.size = size\n        self.CoM = CoM\n        self.max_dens_point = max_dens_point\n        self.group_total_mass = group_total_mass\n        self.max_radius = max_radius\n        self.bulk_vel = bulk_vel\n        self.tasks = tasks\n        self.rms_vel = rms_vel\n        self.bin_count = None\n        self.overdensity = None\n        # A supplementary data dict.\n        if supp is None:\n            self.supp = {}\n        else:\n            self.supp = supp\n        self._saved_fields = {}\n        self._ds_sort = None\n        self._particle_mask = None\n\n    @property\n    def particle_mask(self):\n        # Dynamically create the masking array for particles, and get\n        # the data using standard yt methods.\n        if self._particle_mask is not None:\n            return self._particle_mask\n        # This is from disk.\n        pid = self.__getitem__('particle_index')\n        # This is from the sphere.\n        if self._name == \"RockstarHalo\":\n            ds = self.ds.sphere(self.CoM, self._radjust * self.max_radius)\n        elif self._name == \"LoadedHalo\":\n            ds = self.ds.sphere(self.CoM, np.maximum(self._radjust * \\\n            self.ds.quan(self.max_radius, 'code_length'), \\\n            self.ds.index.get_smallest_dx()))\n        sp_pid = ds['particle_index']\n        self._ds_sort = sp_pid.argsort()\n        sp_pid = sp_pid[self._ds_sort]\n        # This matches them up.\n        self._particle_mask = np.in1d(sp_pid, pid)\n        return self._particle_mask\n\n    def center_of_mass(self):\n        r\"\"\"Calculate and return the center of mass.\n\n        The center of mass of the halo is directly calculated and returned.\n\n        Examples\n        --------\n        >>> com = halos[0].center_of_mass()\n        \"\"\"\n        if self.CoM is not None:\n            return self.CoM\n        pm = self[\"particle_mass\"].in_units('Msun')\n        c = {}\n        # We shift into a box where the origin is the left edge\n        c[0] = self[\"particle_position_x\"] - self.ds.domain_left_edge[0]\n        c[1] = self[\"particle_position_y\"] - self.ds.domain_left_edge[1]\n        c[2] = self[\"particle_position_z\"] - self.ds.domain_left_edge[2]\n        com = []\n        for i in range(3):\n            # A halo is likely periodic around a boundary if the distance\n            # between the max and min particle\n            # positions are larger than half the box.\n            # So skip the rest if the converse is true.\n            # Note we might make a change here when periodicity-handling is\n            # fully implemented.\n            if (c[i].max() - c[i].min()) < (self.ds.domain_width[i] / 2.):\n                com.append(c[i])\n                continue\n            # Now we want to flip around only those close to the left boundary.\n            sel = (c[i] <= (self.ds.domain_width[i]/2))\n            c[i][sel] += self.ds.domain_width[i]\n            com.append(c[i])\n\n        c = (com * pm).sum(axis=1) / pm.sum()\n        c = self.ds.arr(c, 'code_length')\n\n        return c%self.ds.domain_width + self.ds.domain_left_edge\n\n    def maximum_density(self):\n        r\"\"\"Return the HOP-identified maximum density. Not applicable to\n        FOF halos.\n\n        Return the HOP-identified maximum density. Not applicable to FOF halos.\n\n        Examples\n        --------\n        >>> max_dens = halos[0].maximum_density()\n        \"\"\"\n        if self.max_dens_point is not None:\n            return self.max_dens_point[0]\n        return self._max_dens[self.id][0]\n\n    def maximum_density_location(self):\n        r\"\"\"Return the location HOP identified as maximally dense. Not\n        applicable to FOF halos.\n\n        Return the location HOP identified as maximally dense.\n\n        Examples\n        --------\n        >>> max_dens_loc = halos[0].maximum_density_location()\n        \"\"\"\n        if self.max_dens_point is not None:\n            return self.max_dens_point[1:]\n        return np.array([\n                self._max_dens[self.id][1],\n                self._max_dens[self.id][2],\n                self._max_dens[self.id][3]])\n\n    def total_mass(self):\n        r\"\"\"Returns the total mass in solar masses of the halo.\n\n        Returns the total mass in solar masses of just the particles in the\n        halo.\n\n        Examples\n        --------\n        >>> halos[0].total_mass()\n        \"\"\"\n        if self.group_total_mass is not None:\n            return self.group_total_mass\n        return self[\"particle_mass\"].in_units('Msun').sum()\n\n    def bulk_velocity(self):\n        r\"\"\"Returns the mass-weighted average velocity in cm/s.\n\n        This calculates and returns the mass-weighted average velocity of just\n        the particles in the halo in cm/s.\n\n        Examples\n        --------\n        >>> bv = halos[0].bulk_velocity()\n        \"\"\"\n        if self.bulk_vel is not None:\n            return self.bulk_vel\n        pm = self[\"particle_mass\"].in_units('Msun')\n        vx = (self[\"particle_velocity_x\"] * pm).sum()\n        vy = (self[\"particle_velocity_y\"] * pm).sum()\n        vz = (self[\"particle_velocity_z\"] * pm).sum()\n        return self.ds.arr([vx, vy, vz], vx.units) / pm.sum()\n\n    def rms_velocity(self):\n        r\"\"\"Returns the mass-weighted RMS velocity for the halo\n        particles in cgs units.\n\n        Calculate and return the mass-weighted RMS velocity for just the\n        particles in the halo.  The bulk velocity of the halo is subtracted\n        before computation.\n\n        Examples\n        --------\n        >>> rms_vel = halos[0].rms_velocity()\n        \"\"\"\n        if self.rms_vel is not None:\n            return self.rms_vel\n        bv = self.bulk_velocity()\n        pm = self[\"particle_mass\"].in_units('Msun')\n        sm = pm.sum()\n        vx = (self[\"particle_velocity_x\"] - bv[0]) * pm / sm\n        vy = (self[\"particle_velocity_y\"] - bv[1]) * pm / sm\n        vz = (self[\"particle_velocity_z\"] - bv[2]) * pm / sm\n        s = vx ** 2. + vy ** 2. + vz ** 2.\n        ms = np.mean(s)\n        return np.sqrt(ms) * pm.size\n\n    def maximum_radius(self, center_of_mass=True):\n        r\"\"\"Returns the maximum radius in the halo for all particles,\n        either from the point of maximum density or from the\n        center of mass.\n\n        The maximum radius from the most dense point is calculated.  This\n        accounts for periodicity.\n\n        Parameters\n        ----------\n        center_of_mass : bool\n            True chooses the center of mass when\n            calculating the maximum radius.\n            False chooses from the maximum density location for HOP halos\n            (it has no effect for FOF halos).\n            Default = True.\n\n        Examples\n        --------\n        >>> radius = halos[0].maximum_radius()\n        \"\"\"\n        if self.max_radius is not None:\n            return self.max_radius\n        if center_of_mass:\n            center = self.center_of_mass()\n        else:\n            center = self.maximum_density_location()\n        rx = np.abs(self[\"particle_position_x\"] - center[0])\n        ry = np.abs(self[\"particle_position_y\"] - center[1])\n        rz = np.abs(self[\"particle_position_z\"] - center[2])\n        DW = self.data.ds.domain_right_edge - self.data.ds.domain_left_edge\n        r = np.sqrt(np.minimum(rx, DW[0] - rx) ** 2.0\n                + np.minimum(ry, DW[1] - ry) ** 2.0\n                + np.minimum(rz, DW[2] - rz) ** 2.0)\n        return r.max()\n\n    def __getitem__(self, key):\n        return self.data[(self.ptype, key)][self.indices]\n\n    def get_sphere(self, center_of_mass=True):\n        r\"\"\"Returns a sphere source.\n\n        This will generate a new, empty sphere source centered on this halo,\n        with the maximum radius of the halo. This can be used like any other\n        data container in yt.\n\n        Parameters\n        ----------\n        center_of_mass : bool, optional\n            True chooses the center of mass when\n            calculating the maximum radius.\n            False chooses from the maximum density location for HOP halos\n            (it has no effect for FOF halos).\n            Default = True.\n\n        Returns\n        -------\n        sphere : `yt.data_objects.api.YTSphere`\n            The empty data source.\n\n        Examples\n        --------\n        >>> sp = halos[0].get_sphere()\n        \"\"\"\n        if center_of_mass:\n            center = self.center_of_mass()\n        else:\n            center = self.maximum_density_location()\n        radius = self.maximum_radius()\n        # A bit of a long-reach here...\n        sphere = self.data.ds.sphere(center, radius=radius)\n        return sphere\n\n    def get_size(self):\n        if self.size is not None:\n            return self.size\n        return self.indices.size\n\n    def virial_mass(self, virial_overdensity=200., bins=300):\n        r\"\"\"Return the virial mass of the halo in Msun,\n        using only the particles\n        in the halo (no baryonic information used).\n\n        The virial mass is calculated, using the built in `Halo.virial_info`\n        functionality.  The mass is then returned.\n\n        Parameters\n        ----------\n        virial_overdensity : float\n            The overdensity threshold compared to the universal average when\n            calculating the virial mass. Default = 200.\n        bins : int\n            The number of spherical bins used to calculate overdensities.\n            Default = 300.\n\n        Returns\n        -------\n        mass : float\n            The virial mass in solar masses of the particles in the halo.  -1\n            if not virialized.\n\n        Examples\n        --------\n        >>> vm = halos[0].virial_mass()\n        \"\"\"\n        self.virial_info(bins=bins)\n        vir_bin = self.virial_bin(virial_overdensity=virial_overdensity,\n            bins=bins)\n        if vir_bin != -1:\n            return self.mass_bins[vir_bin]\n        else:\n            return -1\n\n    def virial_radius(self, virial_overdensity=200., bins=300):\n        r\"\"\"Return the virial radius of the halo in code units.\n\n        The virial radius of the halo is calculated, using only the particles\n        in the halo (no baryonic information used). Returns -1 if the halo is\n        not virialized.\n\n        Parameters\n        ----------\n        virial_overdensity : float\n            The overdensity threshold compared to the universal average when\n            calculating the virial radius. Default = 200.\n        bins : integer\n            The number of spherical bins used to calculate overdensities.\n            Default = 300.\n\n        Returns\n        -------\n        radius : float\n            The virial radius in code units of the particles in the halo.  -1\n            if not virialized.\n\n        Examples\n        --------\n        >>> vr = halos[0].virial_radius()\n        \"\"\"\n        self.virial_info(bins=bins)\n        vir_bin = self.virial_bin(virial_overdensity=virial_overdensity,\n            bins=bins)\n        if vir_bin != -1:\n            return self.radial_bins[vir_bin]\n        else:\n            return -1\n\n    def virial_bin(self, virial_overdensity=200., bins=300):\n        r\"\"\"Returns the bin index of the virial radius of the halo. Generally,\n        it is better to call virial_radius instead, which calls this function\n        automatically.\n        \"\"\"\n        self.virial_info(bins=bins)\n        over = (self.overdensity > virial_overdensity)\n        if over.any():\n            vir_bin = max(np.arange(bins + 1)[over])\n            return vir_bin\n        else:\n            return -1\n\n    def virial_info(self, bins=300):\n        r\"\"\"Calculates the virial information for the halo. Generally, it is\n        better to call virial_radius or virial_mass instead, which calls this\n        function automatically.\n        \"\"\"\n        # Skip if we've already calculated for this number of bins.\n        if self.bin_count == bins and self.overdensity is not None:\n            return None\n        self.bin_count = bins\n        # Cosmology\n        h = self.ds.hubble_constant\n        Om_matter = self.ds.omega_matter\n        z = self.ds.current_redshift\n        period = self.ds.domain_right_edge - \\\n            self.ds.domain_left_edge\n        thissize = self.get_size()\n        rho_crit = rho_crit_g_cm3_h2 * h ** 2.0 * Om_matter  # g cm^-3\n        Msun2g = mass_sun_cgs\n        rho_crit = rho_crit * ((1.0 + z) ** 3.0)\n        # Get some pertinent information about the halo.\n        self.mass_bins = self.ds.arr(np.zeros(self.bin_count + 1,\n                                              dtype='float64'),'Msun')\n        dist = np.empty(thissize, dtype='float64')\n        cen = self.center_of_mass()\n        mark = 0\n        # Find the distances to the particles. I don't like this much, but I\n        # can't see a way to eliminate a loop like this, either here or in yt.\n        for pos in zip(self[\"particle_position_x\"],\n                self[\"particle_position_y\"], self[\"particle_position_z\"]):\n            dist[mark] = periodic_dist(cen, pos, period)\n            mark += 1\n        # Set up the radial bins.\n        # Multiply min and max to prevent issues with digitize below.\n        self.radial_bins = np.logspace(np.log10(min(dist) * .99 + TINY),\n            np.log10(max(dist) * 1.01 + 2 * TINY), num=self.bin_count + 1)\n        self.radial_bins = self.ds.arr(self.radial_bins,'code_length')\n        # Find out which bin each particle goes into, and add the particle\n        # mass to that bin.\n        inds = np.digitize(dist, self.radial_bins) - 1\n        if self[\"particle_position_x\"].size > 1:\n            for index in np.unique(inds):\n                self.mass_bins[index] += \\\n                np.sum(self[\"particle_mass\"][inds == index]).in_units('Msun')\n        # Now forward sum the masses in the bins.\n        for i in range(self.bin_count):\n            self.mass_bins[i + 1] += self.mass_bins[i]\n        # Calculate the over densities in the bins.\n        self.overdensity = self.mass_bins * Msun2g / \\\n            (4./3. * np.pi * rho_crit * \\\n            (self.radial_bins )**3.0)\n\n    def _get_ellipsoid_parameters_basic(self):\n        np.seterr(all='ignore')\n        # check if there are 4 particles to form an ellipsoid\n        # neglecting to check if the 4 particles in the same plane,\n        # that is almost certainly never to occur,\n        # will deal with it later if it ever comes up\n        if np.size(self[\"particle_position_x\"]) < 4:\n            mylog.warning(\"Too few particles for ellipsoid parameters.\")\n            return (0, 0, 0, 0, 0, 0, 0)\n        # Calculate the parameters that describe the ellipsoid of\n        # the particles that constitute the halo. This function returns\n        # all the parameters except for the center of mass.\n        com = self.center_of_mass()\n        position = [self[\"particle_position_x\"],\n                    self[\"particle_position_y\"],\n                    self[\"particle_position_z\"]]\n        # Locate the furthest particle from com, its vector length and index\n        DW = np.array([self.gridsize[0],self.gridsize[1],self.gridsize[2]])\n        position = [position[0] - com[0],\n                    position[1] - com[1],\n                    position[2] - com[2]]\n        # different cases of particles being on other side of boundary\n        for axis in range(np.size(DW)):\n            cases = np.array([position[axis],\n                                position[axis] + DW[axis],\n                              position[axis] - DW[axis]])\n            # pick out the smallest absolute distance from com\n            position[axis] = np.choose(np.abs(cases).argmin(axis=0), cases)\n        # find the furthest particle's index\n        r = np.sqrt(position[0]**2 +\n                    position[1]**2 +\n                    position[2]**2)\n        A_index = r.argmax()\n        mag_A = r.max()\n        # designate the A vector\n        A_vector = (position[0][A_index],\n                    position[1][A_index],\n                    position[2][A_index])\n        # designate the e0 unit vector\n        e0_vector = A_vector / mag_A\n        # locate the tB particle position by finding the max B\n        e0_vector_copy = np.empty((np.size(position[0]), 3), dtype='float64')\n        for i in range(3):\n            e0_vector_copy[:, i] = e0_vector[i]\n        rr = np.array([position[0],\n                       position[1],\n                       position[2]]).T # Similar to tB_vector in old code.\n        tC_vector = np.cross(e0_vector_copy, rr)\n        te2 = tC_vector.copy()\n        for dim in range(3):\n            te2[:,dim] *= np.sum(tC_vector**2., axis = 1)**(-0.5)\n        te1 = np.cross(te2, e0_vector_copy)\n        length = np.abs(-np.sum(rr * te1, axis = 1) * \\\n            (1. - np.sum(rr * e0_vector_copy, axis = 1)**2. * \\\n            mag_A**-2.)**(-0.5))\n        # This problem apparently happens sometimes, that the NaNs are turned\n        # into infs, which messes up the nanargmax below.\n        length[length == np.inf] = 0.\n        tB_index = np.nanargmax(length) # ignores NaNs created above.\n        mag_B = length[tB_index]\n        e1_vector = te1[tB_index]\n        e2_vector = te2[tB_index]\n        temp_e0 = rr.copy()\n        temp_e1 = rr.copy()\n        temp_e2 = rr.copy()\n        for dim in range(3):\n            temp_e0[:,dim] = e0_vector[dim]\n            temp_e1[:,dim] = e1_vector[dim]\n            temp_e2[:,dim] = e2_vector[dim]\n        length = np.abs(np.sum(rr * temp_e2, axis = 1) * (1 - \\\n            np.sum(rr * temp_e0, axis = 1)**2. * mag_A**-2. - \\\n            np.sum(rr * temp_e1, axis = 1)**2. * mag_B**-2.)**(-0.5))\n        length[length == np.inf] = 0.\n        tC_index = np.nanargmax(length)\n        mag_C = length[tC_index]\n        # tilt is calculated from the rotation about x axis\n        # needed to align e1 vector with the y axis\n        # after e0 is aligned with x axis\n        # find the t1 angle needed to rotate about z axis to align e0 onto x-z plane\n        t1 = np.arctan(-e0_vector[1] / e0_vector[0])\n        RZ = get_rotation_matrix(t1, (0, 0, 1))\n        r1 = np.dot(RZ, e0_vector)\n        # find the t2 angle needed to rotate about y axis to align e0 to x\n        t2 = np.arctan(r1[2] / r1[0])\n        RY = get_rotation_matrix(t2, (0, 1, 0))\n        r2 = np.dot(RY, np.dot(RZ, e1_vector))\n        # find the tilt angle needed to rotate about x axis to align e1 to y and e2 to z\n        tilt = np.arctan(-r2[2] / r2[1])\n        return (mag_A, mag_B, mag_C, e0_vector[0], e0_vector[1],\n            e0_vector[2], tilt)\n\nclass HOPHalo(Halo):\n    _name = \"HOPHalo\"\n    pass\n\nclass FOFHalo(Halo):\n\n    def maximum_density(self):\n        r\"\"\"Not implemented.\"\"\"\n        return -1\n\n    def maximum_density_location(self):\n        r\"\"\"Not implemented.\"\"\"\n        return self.center_of_mass()\n\nclass HaloList(object):\n\n    _fields = [\"particle_position_%s\" % ax for ax in 'xyz']\n\n    def __init__(self, data_source, redshift=-1, ptype='all'):\n        \"\"\"\n        Run hop on *data_source* with a given density *threshold*.\n        Returns an iterable collection of\n        *HopGroup* items.\n        \"\"\"\n        self._data_source = data_source\n        self.ptype = ptype\n        self._groups = []\n        self._max_dens = {}\n        self.__obtain_particles()\n        self._run_finder()\n        mylog.info(\"Parsing outputs\")\n        self._parse_output()\n        mylog.debug(\"Finished. (%s)\", len(self))\n        self.redshift = redshift\n\n    def __obtain_particles(self):\n        ii = slice(None)\n        self.particle_fields = {}\n        for field in self._fields:\n            tot_part = self._data_source[(self.ptype, field)].size\n            if field == \"particle_index\":\n                self.particle_fields[field] = \\\n                    self._data_source[(self.ptype, field)][ii].astype('int64')\n            else:\n                self.particle_fields[field] = \\\n                    self._data_source[(self.ptype, field)][ii].astype('float64')\n            del self._data_source[(self.ptype, field)]\n        self._base_indices = np.arange(tot_part)[ii]\n        gc.collect()\n\n    def _parse_output(self):\n        unique_ids = np.unique(self.tags)\n        counts = np.bincount(self.tags + 1)\n        sort_indices = np.argsort(self.tags)\n        grab_indices = np.indices(self.tags.shape).ravel()[sort_indices]\n        dens = self.densities[sort_indices]\n        cp = 0\n        for i in unique_ids:\n            cp_c = cp + counts[i + 1]\n            if i == -1:\n                cp += counts[i + 1]\n                continue\n            group_indices = grab_indices[cp:cp_c]\n            self._groups.append(self._halo_class(self, i, group_indices,\n                                                 ptype=self.ptype))\n            md_i = np.argmax(dens[cp:cp_c])\n            px, py, pz = \\\n                [self.particle_fields['particle_position_%s' % ax][group_indices]\n                 for ax in 'xyz']\n            self._max_dens[i] = (dens[cp:cp_c][md_i], px[md_i],\n                py[md_i], pz[md_i])\n            cp += counts[i + 1]\n\n    def __len__(self):\n        return len(self._groups)\n\n    def __iter__(self):\n        for i in self._groups:\n            yield i\n\n    def __getitem__(self, key):\n        return self._groups[key]\n\nclass HOPHaloList(HaloList):\n    \"\"\"\n    Run hop on *data_source* with a given density *threshold*.\n    Returns an iterable collection of *HopGroup* items.\n    \"\"\"\n    _name = \"HOP\"\n    _halo_class = HOPHalo\n    _fields = [\"particle_position_%s\" % ax for ax in 'xyz'] + \\\n              [\"particle_mass\"]\n\n    def __init__(self, data_source, threshold=160.0, ptype='all'):\n        self.threshold = threshold\n        mylog.info(\"Initializing HOP\")\n        HaloList.__init__(self, data_source, ptype=ptype)\n\n    def _run_finder(self):\n        self.densities, self.tags = \\\n            RunHOP(self.particle_fields[\"particle_position_x\"] / self.period[0],\n                self.particle_fields[\"particle_position_y\"] / self.period[1],\n                self.particle_fields[\"particle_position_z\"] / self.period[2],\n                self.particle_fields[\"particle_mass\"].in_units('Msun'),\n                self.threshold)\n        self.particle_fields[\"densities\"] = self.densities\n        self.particle_fields[\"tags\"] = self.tags\n\nclass FOFHaloList(HaloList):\n    _name = \"FOF\"\n    _halo_class = FOFHalo\n\n    def __init__(self, data_source, link=0.2, redshift=-1, ptype='all'):\n        self.link = link\n        mylog.info(\"Initializing FOF\")\n        HaloList.__init__(self, data_source, redshift=redshift, ptype=ptype)\n\n    def _run_finder(self):\n        self.tags = \\\n        RunFOF(self.particle_fields[\"particle_position_x\"] / self.period[0],\n               self.particle_fields[\"particle_position_y\"] / self.period[1],\n               self.particle_fields[\"particle_position_z\"] / self.period[2],\n               self.link)\n        self.densities = np.ones(self.tags.size, dtype='float64') * -1\n        self.particle_fields[\"densities\"] = self.densities\n        self.particle_fields[\"tags\"] = self.tags\n\nclass GenericHaloFinder(HaloList, ParallelAnalysisInterface):\n    def __init__(self, ds, data_source, padding=0.0, ptype='all'):\n        ParallelAnalysisInterface.__init__(self)\n        self.ds = ds\n        self.index = ds.index\n        self.center = (np.array(data_source.right_edge) +\n                       np.array(data_source.left_edge)) / 2.0\n        self.ptype = ptype\n\n    def _parse_halolist(self, threshold_adjustment):\n        groups = []\n        max_dens = {}\n        hi = 0\n        LE, RE = self.bounds\n        for halo in self._groups:\n            this_max_dens = halo.maximum_density_location()\n            # if the most dense particle is in the box, keep it\n            if np.all((this_max_dens >= LE) & (this_max_dens <= RE)):\n                # Now we add the halo information to OURSELVES, taken from the\n                # self.hop_list\n                # We need to mock up the HOPHaloList thingie, so we need to\n                #     set self._max_dens\n                max_dens_temp = list(self._max_dens[halo.id])[0] / \\\n                    threshold_adjustment\n                max_dens[hi] = [max_dens_temp] + \\\n                    list(self._max_dens[halo.id])[1:4]\n                groups.append(self._halo_class(self, hi, ptype=self.ptype))\n                groups[-1].indices = halo.indices\n                self.comm.claim_object(groups[-1])\n                hi += 1\n        del self._groups, self._max_dens  # explicit >> implicit\n        self._groups = groups\n        self._max_dens = max_dens\n\n    def _join_halolists(self):\n        groups = {self.comm.rank: len(self)}\n        groups = self.comm.par_combine_object(\n            groups, datatype='dict', op='join')\n\n        ngroups = np.array([groups[rank] for rank in sorted(groups)])\n        offsets = ngroups.cumsum() - ngroups\n        my_offset = offsets[self.comm.rank]\n        for halo in self:\n            halo.id += my_offset\n\n    def _reposition_particles(self, bounds):\n        # This only does periodicity.  We do NOT want to deal with anything\n        # else.  The only reason we even do periodicity is the\n        LE, RE = bounds\n        dw = self.ds.domain_right_edge - self.ds.domain_left_edge\n        for i, ax in enumerate('xyz'):\n            arr = self._data_source[self.ptype, \"particle_position_%s\" % ax]\n            arr[arr < LE[i] - self.padding] += dw[i]\n            arr[arr > RE[i] + self.padding] -= dw[i]\n\nclass HOPHaloFinder(GenericHaloFinder, HOPHaloList):\n    r\"\"\"HOP halo finder.\n\n    Halos are built by:\n    1. Calculating a density for each particle based on a smoothing kernel.\n    2. Recursively linking particles to other particles from lower density\n    particles to higher.\n    3. Geometrically proximate chains are identified and\n    4. merged into final halos following merging rules.\n\n    Lower thresholds generally produce more halos, and the largest halos\n    become larger. Also, halos become more filamentary and over-connected.\n\n    Eisenstein and Hut. \"HOP: A New Group-Finding Algorithm for N-Body\n    Simulations.\" ApJ (1998) vol. 498 pp. 137-142\n\n    Parameters\n    ----------\n    ds : `Dataset`\n        The dataset on which halo finding will be conducted.\n    subvolume : `yt.data_objects.data_containers.YTSelectionContainer`, optional\n        A region over which HOP will be run, which can be used to run HOP\n        on a subvolume of the full volume. Default = None, which defaults\n        to the full volume automatically.\n    threshold : float\n        The density threshold used when building halos. Default = 160.0.\n    ptype : string\n        The particle type to be used for halo finding.\n        Default: 'all'.\n    padding : float\n        When run in parallel, the finder needs to surround each subvolume\n        with duplicated particles for halo finidng to work. This number\n        must be no smaller than the radius of the largest halo in the box\n        in code units. Default = 0.02.\n    total_mass : float\n        If HOP is run on the same dataset mulitple times, the total mass\n        of particles in Msun units in the full volume can be supplied here\n        to save time.\n        This must correspond to the particles being operated on, meaning\n        if stars are included in the halo finding, they must be included\n        in this mass as well, and visa-versa.\n        If halo finding on a subvolume, this still corresponds with the\n        mass in the entire volume.\n        Default = None, which means the total mass is automatically\n        calculated.\n    save_particles : bool\n        If True, output member particles for each halo.\n        Default: True.\n\n    Examples\n    --------\n    >>> import yt\n    >>> from yt.extensions.astro_analysis.halo_analysis import HaloCatalog\n    >>> data_ds = yt.load('Enzo_64/RD0006/RedshiftOutput0006')\n    >>> hc = HaloCatalog(data_ds=data_ds, finder_method='hop',\n    ...                  finder_kwargs={\"threshold\": 160})\n    >>> hc.create()\n    \"\"\"\n    def __init__(self, ds, subvolume=None, threshold=160, dm_only=False,\n                 ptype='all', padding=0.02, total_mass=None,\n                 save_particles=True):\n        if subvolume is not None:\n            ds_LE = np.array(subvolume.left_edge)\n            ds_RE = np.array(subvolume.right_edge)\n        self.period = ds.domain_right_edge - ds.domain_left_edge\n        self.save_particles = save_particles\n        self._data_source = ds.all_data()\n        GenericHaloFinder.__init__(self, ds, self._data_source, padding,\n                                   ptype=ptype)\n        # do it once with no padding so the total_mass is correct\n        # (no duplicated particles), and on the entire volume, even if only\n        # a small part is actually going to be used.\n        self.padding = 0.0\n        padded, LE, RE, self._data_source = \\\n            self.partition_index_3d(ds=self._data_source,\n                padding=self.padding)\n\n        if dm_only:\n            raise RuntimeError(\n                \"dm_only has been removed. \" +\n                \"Use ptype to specify a particle type, instead.\")\n\n        self.ptype = ptype\n\n        # For scaling the threshold, note that it's a passthrough\n        if total_mass is None:\n            total_mass = self.comm.mpi_allreduce(\n                self._data_source.quantities.total_quantity(\n                    (self.ptype, \"particle_mass\")).in_units('Msun'), op='sum')\n        # MJT: Note that instead of this, if we are assuming that the particles\n        # are all on different processors, we should instead construct an\n        # object representing the entire domain and sum it \"lazily\" with\n        # Derived Quantities.\n        if subvolume is not None:\n            self._data_source = ds.region([0.] * 3, ds_LE, ds_RE)\n        else:\n            self._data_source = ds.all_data()\n        self.padding = padding  # * ds[\"unitary\"] # This should be clevererer\n        padded, LE, RE, self._data_source = \\\n            self.partition_index_3d(ds=self._data_source,\n            padding=self.padding)\n        self.bounds = (LE, RE)\n        # sub_mass can be skipped if subvolume is not used and this is not\n        # parallel.\n        if subvolume is None and \\\n                ytcfg.get(\"yt\", \"internals\", \"topcomm_parallel_size\") == 1:\n            sub_mass = total_mass\n        else:\n            sub_mass = \\\n                self._data_source.quantities.total_quantity(\n                    (self.ptype, \"particle_mass\")).in_units('Msun')\n        HOPHaloList.__init__(self, self._data_source,\n            threshold * total_mass / sub_mass, ptype=self.ptype)\n        self._parse_halolist(total_mass / sub_mass)\n        self._join_halolists()\n\nclass FOFHaloFinder(GenericHaloFinder, FOFHaloList):\n    r\"\"\"Friends-of-friends halo finder.\n\n    Halos are found by linking together all pairs of particles closer than\n    some distance from each other. Particles may have multiple links,\n    and halos are found by recursively linking together all such pairs.\n\n    Larger linking lengths produce more halos, and the largest halos\n    become larger. Also, halos become more filamentary and over-connected.\n\n    Davis et al. \"The evolution of large-scale structure in a universe\n    dominated by cold dark matter.\" ApJ (1985) vol. 292 pp. 371-394\n\n    Parameters\n    ----------\n    ds : `Dataset`\n        The dataset on which halo finding will be conducted.\n    subvolume : `yt.data_objects.data_containers.YTSelectionContainer`, optional\n        A region over which HOP will be run, which can be used to run HOP\n        on a subvolume of the full volume. Default = None, which defaults\n        to the full volume automatically.\n    link : float\n        If positive, the interparticle distance (compared to the overall\n        average) used to build the halos. If negative, this is taken to be\n        the *actual* linking length, and no other calculations will be\n        applied.  Default = 0.2.\n    ptype : string\n        The type of particle to be used for halo finding.\n        Default: 'all'.\n    padding : float\n        When run in parallel, the finder needs to surround each subvolume\n        with duplicated particles for halo finidng to work. This number\n        must be no smaller than the radius of the largest halo in the box\n        in code units. Default = 0.02.\n    save_particles : bool\n        If True, output member particles for each halo.\n        Default: True.\n\n    Examples\n    --------\n    >>> import yt\n    >>> from yt.extensions.astro_analysis.halo_analysis import HaloCatalog\n    >>> data_ds = yt.load('Enzo_64/RD0006/RedshiftOutput0006')\n    >>> hc = HaloCatalog(data_ds=data_ds, finder_method='fof',\n    ...                  finder_kwargs={\"link\": 0.2})\n    >>> hc.create()\n    \"\"\"\n    def __init__(self, ds, subvolume=None, link=0.2, dm_only=False,\n                 ptype='all', padding=0.02, save_particles=True):\n        if subvolume is not None:\n            ds_LE = np.array(subvolume.left_edge)\n            ds_RE = np.array(subvolume.right_edge)\n        self.period = ds.domain_right_edge - ds.domain_left_edge\n        self.ds = ds\n        self.index = ds.index\n        self.redshift = ds.current_redshift\n        self.save_particles = save_particles\n        self._data_source = ds.all_data()\n        GenericHaloFinder.__init__(self, ds, self._data_source, padding)\n        self.padding = 0.0  # * ds[\"unitary\"] # This should be clevererer\n        # get the total number of particles across all procs, with no padding\n        padded, LE, RE, self._data_source = \\\n            self.partition_index_3d(ds=self._data_source,\n            padding=self.padding)\n\n        if dm_only:\n            raise RuntimeError(\n                \"dm_only has been removed. \" +\n                \"Use ptype to specify a particle type, instead.\")\n\n        self.ptype = ptype\n\n        if link > 0.0:\n            n_parts = self.comm.mpi_allreduce(\n                self._data_source[\"particle_position_x\"].size, op='sum')\n            # get the average spacing between particles\n            #l = ds.domain_right_edge - ds.domain_left_edge\n            #vol = l[0] * l[1] * l[2]\n            # Because we are now allowing for datasets with non 1-periodicity,\n            # but symmetric, vol is always 1.\n            vol = 1.\n            avg_spacing = (float(vol) / n_parts) ** (1. / 3.)\n            linking_length = link * avg_spacing\n        else:\n            linking_length = np.abs(link)\n        self.padding = padding\n        if subvolume is not None:\n            self._data_source = ds.region([0.] * 3, ds_LE,\n                ds_RE)\n        else:\n            self._data_source = ds.all_data()\n        padded, LE, RE, self._data_source = \\\n            self.partition_index_3d(ds=self._data_source,\n            padding=self.padding)\n        self.bounds = (LE, RE)\n        # reflect particles around the periodic boundary\n        #self._reposition_particles((LE, RE))\n        # here is where the FOF halo finder is run\n        mylog.info(\"Using a linking length of %0.3e\", linking_length)\n        FOFHaloList.__init__(self, self._data_source, linking_length,\n                             redshift=self.redshift, ptype=self.ptype)\n        self._parse_halolist(1.)\n        self._join_halolists()\n", "meta": {"hexsha": "7d9d5612b2befec6d2c6334e9b650e67939319e7", "size": 37022, "ext": "py", "lang": "Python", "max_stars_repo_path": "yt_astro_analysis/halo_analysis/halo_finding/halo_objects.py", "max_stars_repo_name": "brittonsmith/yt_astro_analysis", "max_stars_repo_head_hexsha": "f5d255a89dc1e882866cbfabcc627c3af3ee6d62", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "yt_astro_analysis/halo_analysis/halo_finding/halo_objects.py", "max_issues_repo_name": "brittonsmith/yt_astro_analysis", "max_issues_repo_head_hexsha": "f5d255a89dc1e882866cbfabcc627c3af3ee6d62", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "yt_astro_analysis/halo_analysis/halo_finding/halo_objects.py", "max_forks_repo_name": "brittonsmith/yt_astro_analysis", "max_forks_repo_head_hexsha": "f5d255a89dc1e882866cbfabcc627c3af3ee6d62", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7231759657, "max_line_length": 88, "alphanum_fraction": 0.5938360975, "include": true, "reason": "import numpy", "num_tokens": 8878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.18809832622572326}}
{"text": "import numpy as np\nimport xarray as xr\nimport multiprocessing\nfrom scipy.sparse import csr_matrix\nfrom pathlib import Path\nfrom apexpy import Apex\nfrom datetime import datetime, timedelta\nimport logging\nimport warnings\ntry:\n    import cvxpy as cp\n    import bottleneck as bn\n    import pandas\n    from skimage import measure, morphology\n    from sklearn.metrics.pairwise import rbf_kernel\nexcept ImportError as imp_err:\n    warnings.warn(f\"Packages required for recreating dataset not installed: {imp_err}\")\n\nfrom trough import config, utils, _tec, _arb\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_model(tec_data, hemisphere, omni_file):\n    \"\"\"Get magnetic latitudes of the trough according to the model in Deminov 2017\n    for a specific time and set of magnetic local times.\n    \"\"\"\n    logger.info(\"getting model\")\n    omni_data = xr.open_dataset(omni_file)\n    logger.info(f\"{omni_data.time.values[0]=} {omni_data.time.values[-1]=}\")\n    kp = _get_weighted_kp(tec_data.time, omni_data)\n    logger.info(f\"{kp.shape=}\")\n    apex = Apex(date=utils.datetime64_to_datetime(tec_data.time.values[0]))\n    mlat = 65.5 * np.ones((tec_data.time.shape[0], tec_data.mlt.shape[0]))\n    for i in range(10):\n        glat, glon = apex.convert(mlat, tec_data.mlt.values[None, :], 'mlt', 'geo', 350, tec_data.time.values[:, None])\n        mlat = _model_subroutine_lat(tec_data.mlt.values[None, :], glon, kp[:, None], hemisphere)\n    if hemisphere == 'south':\n        mlat = mlat * -1\n    tec_data['model'] = xr.DataArray(\n        mlat,\n        coords={'time': tec_data.time, 'mlt': tec_data.mlt},\n        dims=['time', 'mlt']\n    )\n\n\ndef _model_subroutine_lat(mlt, glon, kp, hemisphere):\n    \"\"\"Get's model output mlat given MLT, geographic lon and weighted kp\n\n    Parameters\n    ----------\n    mlt: numpy.ndarray (n_mlt, )\n    glon: numpy.ndarray (n_mlt, )\n    kp: float\n\n    Returns\n    -------\n    mlat: numpy.ndarray (n_t, n_mlt)\n    \"\"\"\n    phi_t = 3.16 - 5.6 * np.cos(np.deg2rad(15 * (mlt - 2.4))) + 1.4 * np.cos(np.deg2rad(15 * (2 * mlt - .8)))\n    if hemisphere == 'north':\n        phi_lon = .85 * np.cos(np.deg2rad(glon + 63)) - .52 * np.cos(np.deg2rad(2 * glon + 5))\n    elif hemisphere == 'south':\n        phi_lon = 1.5 * np.cos(np.deg2rad(glon - 119))\n    else:\n        raise ValueError(f\"Invalid hemisphere: {hemisphere}, valid = ['north', 'south']\")\n    return 65.5 - 2.4 * kp + phi_t + phi_lon * np.exp(-.3 * kp)\n\n\ndef _get_weighted_kp(times, omni_data, tau=.6, T=10):\n    \"\"\"Get a weighed sum of kp values over time. See paper for details.\n    \"\"\"\n    logger.info(f\"_get_weighted_kp {times[0]=} {times[-1]=}\")\n    ap = omni_data.sel(time=slice(times[0] - np.timedelta64(T, 'h'), times[-1]))['ap'].values\n    prehistory = np.column_stack([ap[T - i:ap.shape[0] - i] for i in range(T)])\n    weight_factors = tau ** np.arange(T)\n    ap_tau = np.sum((1 - tau) * prehistory * weight_factors, axis=1)\n    return 2.1 * np.log(.2 * ap_tau + 1)\n\n\ndef estimate_background(tec, patch_shape):\n    \"\"\"Use a moving average filter to estimate the background TEC value. `patch_shape` must contain odd numbers\n\n    Parameters\n    ----------\n    tec: numpy.ndarray[float]\n    patch_shape: tuple\n\n    Returns\n    -------\n    numpy.ndarray[float]\n    \"\"\"\n    assert all([2 * (p // 2) + 1 == p for p in patch_shape]), \"patch_shape must be all odd numbers\"\n    patches = utils.extract_patches(tec, patch_shape)\n    return bn.nanmean(patches.reshape((tec.shape[0] - patch_shape[0] + 1,) + tec.shape[1:] + (-1,)), axis=-1)\n\n\ndef preprocess_interval(data, min_val=0, max_val=100, bg_est_shape=(1, 15, 15)):\n    logger.info(\"preprocessing interval\")\n    tec = data['tec'].values\n    # throw away outlier values\n    tec[tec > max_val] = np.nan\n    tec[tec < min_val] = np.nan\n    # change to log\n    log_tec = np.log10(tec + .001)\n    # estimate background\n    bg = estimate_background(log_tec, bg_est_shape)\n    # subtract background\n    x = log_tec - bg\n    coords = {'time': data.time, 'mlat': data.mlat, 'mlt': data.mlt}\n    data['x'] = xr.DataArray(x, coords=coords, dims=['time', 'mlat', 'mlt'])\n    data['tec'] = xr.DataArray(tec, coords=coords, dims=['time', 'mlat', 'mlt'])\n\n\ndef fix_boundaries(labels):\n    fixed = labels.copy()\n    while True:\n        boundary_pairs = np.unique(fixed[:, [0, -1]], axis=0)\n        if np.all((boundary_pairs[:, 0] == boundary_pairs[:, 1]) | np.any(boundary_pairs == 0, axis=1)):\n            break\n        for i in range(boundary_pairs.shape[0]):\n            if np.any(boundary_pairs[i] == 0) or boundary_pairs[i, 0] == boundary_pairs[i, 1]:\n                continue\n            fixed[fixed == boundary_pairs[i, 1]] = boundary_pairs[i, 0]\n            break\n    return fixed\n\n\ndef remove_auroral(data, hemisphere, offset=3):\n    if hemisphere == 'north':\n        data['labels'] *= data.mlat < (data['arb'] + offset)\n    elif hemisphere == 'south':\n        data['labels'] *= data.mlat > (data['arb'] - offset)\n    else:\n        raise ValueError(f\"Invalid hemisphere: {hemisphere}, valid = ['north', 'south']\")\n\n\ndef postprocess(data, hemisphere, perimeter_th=50, area_th=1, closing_r=0):\n    if closing_r > 0:\n        selem = morphology.disk(closing_r, dtype=bool)[:, :, None]\n        data['labels'] = np.pad(data['labels'], ((0, 0), (0, 0), (closing_r, closing_r)), 'wrap')\n        data['labels'] = morphology.binary_closing(data['labels'], selem)[:, :, closing_r:-closing_r]\n    remove_auroral(data, hemisphere)\n    for t in range(data.time.shape[0]):\n        tmap = data['labels'][t].values\n        labeled = measure.label(tmap, connectivity=2)\n        labeled = fix_boundaries(labeled)\n        props = pandas.DataFrame(measure.regionprops_table(labeled, properties=('label', 'area', 'perimeter')))\n        error_mask = (props['perimeter'] < perimeter_th) | (props['area'] < area_th)\n        for i, r in props[error_mask].iterrows():\n            tmap[labeled == r['label']] = 0\n        data['labels'][t] = tmap\n\n\ndef get_rbf_matrix(shape, bandwidth=1):\n    X, Y = np.meshgrid(np.arange(shape[1]), np.arange(shape[0]))\n    xy = np.column_stack((X.ravel(), Y.ravel()))\n    gamma = np.log(2) / bandwidth ** 2\n    basis = rbf_kernel(xy, gamma=gamma)\n    basis[basis < .01] = 0\n    return csr_matrix(basis)\n\n\ndef get_tv_matrix(im_shape, hw=1, vw=1):\n    size = im_shape[0] * im_shape[1]\n\n    right = np.eye(size)\n    cols = im_shape[1] * (np.arange(size) // im_shape[1]) + (np.arange(size) + 1) % im_shape[1]\n    right[np.arange(size), cols] = -1\n\n    left = np.eye(size)\n    cols = im_shape[1] * (np.arange(size) // im_shape[1]) + (np.arange(size) - 1) % im_shape[1]\n    left[np.arange(size), cols] = -1\n\n    up = np.eye(size)\n    cols = np.arange(size) + im_shape[1]\n    mask = cols < size\n    cols = cols[mask]\n    up[np.arange(size)[mask], cols] = -1\n\n    down = np.eye(size)\n    cols = np.arange(size) - im_shape[1]\n    mask = cols >= 0\n    cols = cols[mask]\n    down[np.arange(size)[mask], cols] = -1\n    return csr_matrix(hw * (right + left) + vw * (up + down))\n\n\ndef get_optimization_args(data, model_weight_max, rbf_bw, tv_hw, tv_vw, l2_weight, tv_weight):\n    all_args = []\n    # get rbf basis matrix\n    basis = get_rbf_matrix((data.mlat.shape[0], data.mlt.shape[0]), rbf_bw)\n    # get tv matrix\n    tv = get_tv_matrix((data.mlat.shape[0], data.mlt.shape[0]), tv_hw, tv_vw) * tv_weight\n    for i in range(data.time.shape[0]):\n        # l2 norm cost away from model\n        l2 = abs(data.mlat - data['model']).isel(time=i)\n        l2 -= l2.min()\n        l2 = (model_weight_max - 1) * l2 / l2.max() + 1\n        l2 *= l2_weight\n        fin_mask = np.isfinite(np.ravel(data['x'].isel(time=i)))\n        if not fin_mask.any():\n            raise Exception(\"WHY ALL NAN??\")\n        args = (cp.Variable(data.mlat.shape[0] * data.mlt.shape[0]), basis[fin_mask, :],\n                np.ravel(data['x'].isel(time=i))[fin_mask], tv, np.ravel(l2))\n        all_args.append(args)\n    return all_args\n\n\ndef run_single(u, basis, x, tv, l2):\n    main_cost = u.T @ basis.T @ x\n    tv_cost = cp.norm1(tv @ u)\n    l2_cost = l2 @ (u ** 2)\n    total_cost = main_cost + tv_cost + l2_cost\n    prob = cp.Problem(cp.Minimize(total_cost))\n    try:\n        prob.solve(solver=cp.GUROBI)\n    except Exception as e:\n        logger.info(f\"FAILED, USING ECOS: {e}\")\n        prob.solve(solver=cp.ECOS)\n    return u.value\n\n\ndef run_multiple(args, parallel=True):\n    if parallel:\n        with multiprocessing.Pool(processes=4) as p:\n            results = p.starmap(run_single, args)\n    else:\n        results = []\n        for arg in args:\n            results.append(run_single(*arg))\n    return np.stack(results, axis=0)\n\n\ndef label_trough_interval(start_date, end_date, params, hemisphere, tec_dir, arb_dir, omni_file):\n    logger.info(f\"labeling trough interval: {start_date=} {end_date=}\")\n    data = _tec.get_tec_data(start_date, end_date, hemisphere, tec_dir).to_dataset(name='tec')\n    preprocess_interval(data, bg_est_shape=params.bg_est_shape)\n\n    data['arb'] = _arb.get_arb_data(start_date, end_date, hemisphere, arb_dir)\n    get_model(data, hemisphere, omni_file)\n    args = get_optimization_args(data, params.model_weight_max, params.rbf_bw, params.tv_hw, params.tv_vw,\n                                 params.l2_weight, params.tv_weight)\n    logger.info(\"Running inversion optimization\")\n    data['score'] = xr.DataArray(\n        run_multiple(args).reshape((data.time.shape[0], data.mlat.shape[0], data.mlt.shape[0])),\n        coords={\n            'time': data.time,\n            'mlat': data.mlat,\n            'mlt': data.mlt\n        },\n        dims=['time', 'mlat', 'mlt']\n    )\n    # threshold\n    data['labels'] = data['score'] >= params.threshold\n    # postprocess\n    logger.info(\"Postprocessing inversion results\")\n    postprocess(data, hemisphere, params.perimeter_th, params.area_th, params.closing_rad)\n    return data\n\n\ndef label_trough_dataset(start_date, end_date, params=None, tec_dir=None, arb_dir=None, omni_file=None,\n                         output_dir=None):\n    if params is None:\n        params = config.trough_id_params\n    if tec_dir is None:\n        tec_dir = config.processed_tec_dir\n    if arb_dir is None:\n        arb_dir = config.processed_arb_dir\n    if omni_file is None:\n        omni_file = config.processed_omni_file\n    if output_dir is None:\n        output_dir = config.processed_labels_dir\n\n    Path(output_dir).mkdir(exist_ok=True, parents=True)\n    for year in range(start_date.year, end_date.year + 1):\n        for hemisphere in ['north', 'south']:\n            labels = []\n            scores = []\n            start = datetime(year, 1, 1, 0, 0)\n            while start.year < year + 1:\n                end = start + timedelta(days=1)\n                if start >= end_date or end <= start_date:\n                    start += timedelta(days=1)\n                    continue\n                start = max(start_date, start)\n                end = min(end_date, end)\n                data = label_trough_interval(start, end, params, hemisphere, tec_dir, arb_dir, omni_file)\n                if end.year == start.year + 1:\n                    data = data.isel(time=slice(0, -1))\n                labels.append(data['labels'])\n                scores.append(data['score'])\n                start += timedelta(days=1)\n            labels = xr.concat(labels, 'time')\n            scores = xr.concat(scores, 'time')\n            labels.to_netcdf(Path(output_dir) / f\"labels_{hemisphere}_{year:04d}.nc\")\n            scores.to_netcdf(Path(output_dir) / f\"scores_{hemisphere}_{year:04d}.nc\")\n\n\ndef get_label_paths(start_date, end_date, hemisphere, processed_dir):\n    file_dates = np.arange(\n        np.datetime64(start_date, 'Y'),\n        (np.datetime64(end_date, 's')).astype('datetime64[Y]') + 1,\n        np.timedelta64(1, 'Y')\n    )\n    file_dates = utils.decompose_datetime64(file_dates)\n    return [Path(processed_dir) / f\"labels_{hemisphere}_{d[0]:04d}.nc\" for d in file_dates]\n\n\ndef get_trough_labels(start_date, end_date, hemisphere, labels_dir=None):\n    if labels_dir is None:\n        labels_dir = config.processed_labels_dir\n    data = utils.read_netcdfs(get_label_paths(start_date, end_date, hemisphere, labels_dir), 'time')\n    return data.sel(time=slice(start_date, end_date))\n\n\ndef get_data(start_date, end_date, hemisphere, tec_dir=None, omni_file=None, labels_dir=None):\n    if tec_dir is None:\n        tec_dir = config.processed_tec_dir\n    if omni_file is None:\n        omni_file = config.processed_omni_file\n    if labels_dir is None:\n        labels_dir = config.processed_labels_dir\n    data = xr.open_dataset(omni_file).sel(time=slice(start_date, end_date))\n    data['tec'] = _tec.get_tec_data(start_date, end_date, hemisphere, tec_dir)\n    data['labels'] = get_trough_labels(start_date, end_date, hemisphere, labels_dir)\n    return data\n", "meta": {"hexsha": "71c0245241e226a01deb20d5295698773ab7478d", "size": 12776, "ext": "py", "lang": "Python", "max_stars_repo_path": "trough/_trough.py", "max_stars_repo_name": "gregstarr/trough", "max_stars_repo_head_hexsha": "5ec89cf342b3fc63fb13223bd4d3a9f20cb5d4eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-31T00:48:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:48:33.000Z", "max_issues_repo_path": "trough/_trough.py", "max_issues_repo_name": "gregstarr/trough", "max_issues_repo_head_hexsha": "5ec89cf342b3fc63fb13223bd4d3a9f20cb5d4eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2022-03-08T10:44:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:14:36.000Z", "max_forks_repo_path": "trough/_trough.py", "max_forks_repo_name": "gregstarr/trough", "max_forks_repo_head_hexsha": "5ec89cf342b3fc63fb13223bd4d3a9f20cb5d4eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8328267477, "max_line_length": 119, "alphanum_fraction": 0.6286787727, "include": true, "reason": "import numpy,from scipy,import cvxpy", "num_tokens": 3532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.33458944788835565, "lm_q1q2_score": 0.18809832504718685}}
{"text": "import argparse\nimport h5sparse as h5py\nfrom h5py import SoftLink\nimport os\nimport numpy as np\nimport blockmodel\nfrom math import sqrt\nfrom read_matrix import body_matrix, surface_matrix, revert_h_weighting, revert_c_weighting\nfrom scipy.sparse import csr_matrix, diags, vstack\nfrom scipy.sparse.linalg import svds\nimport pandas as pd\nfrom time import time\nfrom datetime import date\n\n# kernel object\nclass Kernel():\n    ## initialized with filegroup name & k value\n    def __init__(self, params):\n        self.filegroup = params.f\n        self.num_of_vectors = params.k\n        self.epsilon = params.epsilon\n        self.regularization = params.regular\n        self.is_coverage_to_weight = params.c\n        self.is_thickness_to_weight = params.z\n        self.is_smoother_to_apply = params.smooth\n        self.is_loaded = False\n        self.smoother = False\n\n    ## load kernel results\n    def load_kernel(self, db):\n        if f\"/{self.filegroup}\" in db:\n            for item in db[f\"/{self.filegroup}\"]:\n                if f\"/{self.filegroup}/{item}/kernel\" in db:\n                    attrs = db[f\"/{self.filegroup}/{item}/kernel\"].attrs\n                    if attrs['thickness_weighted'] == self.is_thickness_to_weight:\n                        if (not self.is_coverage_to_weight and attrs['coverage_weighted'] == -1) or (self.is_coverage_to_weight and attrs['coverage_weighted'] == self.regularization):\n                            if not 'smoother_added' in attrs: attrs['smoother_added'] = False\n                            if attrs['smoother_added'] == self.is_smoother_to_apply:\n                                self.csr = db[f\"/{self.filegroup}/{item}/kernel\"][()]\n                                self.d = db[f\"/{self.filegroup}/{item}/residual\"]\n                                self.smoother = attrs['smoother_added']\n                                if self.is_coverage_to_weight: self.c = db[f\"/{self.filegroup}/{item}/weight\"]\n                                if not item == self.num_of_vectors:\n                                    if not f\"/{self.filegroup}/{self.num_of_vectors}/kernel\" in db: db[f\"/{self.filegroup}/{self.num_of_vectors}/kernel\"] = SoftLink(f\"/{self.filegroup}/{item}/kernel\")\n                                    if not f\"/{self.filegroup}/{self.num_of_vectors}/residual\" in db: db[f\"/{self.filegroup}/{self.num_of_vectors}/residual\"] = SoftLink(f\"/{self.filegroup}/{item}/residual\")\n                                    if not f\"/{self.filegroup}/{self.num_of_vectors}/weight\" in db and self.is_coverage_to_weight: db[f\"/{self.filegroup}/{self.num_of_vectors}/weight\"] = SoftLink(f\"/{self.filegroup}/{item}/weight\")\n                                self.is_loaded = True\n                                break\n    \n    ## save kernel results\n    def save_kernel(self, db):\n        if not f\"/{self.filegroup}\" in db: db.create_group(f\"/{self.filegroup}\")\n        if not f\"/{self.filegroup}/{self.num_of_vectors}\" in db: db.create_group(f\"/{self.filegroup}/{self.num_of_vectors}\")\n\n        kernel_data = overwrite_data(db, f\"/{self.filegroup}/{self.num_of_vectors}/kernel\", self.csr)\n        kernel_data.attrs['created'] = date.today().strftime('%Y-%m-%d')\n        kernel_data.attrs['error_weighted'] = True\n        kernel_data.attrs['smoother_added'] = self.smoother\n        kernel_data.attrs['thickness_weighted'] = self.is_thickness_to_weight\n        kernel_data.attrs['coverage_weighted'] = self.regularization if self.is_coverage_to_weight else -1\n\n        if self.is_coverage_to_weight:\n            weight_data = overwrite_data(db, f\"/{self.filegroup}/{self.num_of_vectors}/weight\", self.c)\n            weight_data.attrs['created'] = date.today().strftime('%Y-%m-%d')\n            weight_data.attrs['smoother_added'] = self.smoother\n\n        residual_data = overwrite_data(db, f\"/{self.filegroup}/{self.num_of_vectors}/residual\", self.d)\n        residual_data.attrs['created'] = date.today().strftime('%Y-%m-%d')\n        residual_data.attrs['error_weighted'] = True\n        residual_data.attrs['smoother_added'] = self.smoother\n\n    ## Load existing data matrix\n    def readmatrix(self):\n        if self.filegroup == 'Sfast':\n            filenames = ['ScS-S.4.05', 'SS-S.4']\n            is_surface_to_add = True\n        elif self.filegroup == 'Surf':\n            filenames = []\n            is_surface_to_add = True\n        elif self.filegroup == 'Scomb':\n            filenames = ['Scomb.4']\n            is_surface_to_add = False\n        elif self.filegroup == 'ScombSurf':\n            filenames = ['Scomb.4']\n            is_surface_to_add = True\n        elif self.filegroup == 'Sonly':\n            filenames = ['Scomb.4', 'SS.95-05.4', 'ScS-S.4.05', 'SS-S.4']\n            is_surface_to_add = False\n        elif self.filegroup == 'S':\n            filenames = ['Scomb.4', 'SS.95-05.4', 'ScS-S.4.05', 'SS-S.4']\n            is_surface_to_add = True\n        elif self.filegroup == 'P':\n            filenames = ['Pcomb.4', 'PP.95-05.4',  'PP-P.4']\n            is_surface_to_add = False\n        else:\n            raise ValueError('unknown file combination %s' % self.filegroup)\n\n        data = ()\n        kernels = ()\n        for filename in filenames:\n            (d, K) = body_matrix(filename)\n            data = data + (d,)\n            kernels = kernels + (K,)\n        if is_surface_to_add:\n            fns = ['mat4.nd.r'+str(i)+'.swp' for i in range(4,15+1)]\n            fns += ['mat4.nd.l'+str(i)+'.swp' for i in range(4,15+1)]\n            (d, K) = surface_matrix(fns)\n            data = data + (d,)\n            kernels = kernels + (K,)\n\n        return np.vstack(data), np.vstack(kernels)\n\n    ## collect and weight kernel matrices\n    def get_kernel(self):\n        from config import H\n        if not self.is_thickness_to_weight:\n            H = np.ones(len(H))\n        (self.d, K) = self.readmatrix()\n\n        # Apply coverage weighting column by column (save memory)\n        c = np.zeros(K.shape[1])\n        for i in range(len(c)):\n            c[i] = H[i//2578]\n        if self.is_coverage_to_weight:\n            for i in range(len(c)):\n                if self.regularization == 0:\n                    c[i] *= max(1, np.sum(K[:,i]!=0))\n                elif self.regularization == 1:\n                    c[i] *= max(1, np.sum(np.abs(K[:,i]), axis=0))\n                elif self.regularization == 2:\n                    c[i] *= max(1, np.sqrt(np.sum(K[:,i]**self.regularization, axis=0)))\n                elif self.regularization > 2:\n                    c[i] *= max(1, np.sqrt(np.sum(np.abs(K[:,i])**self.regularization, axis=0)))\n                else:\n                    raise ValueError('incorrect regularization norm: L-%s' % self.regularization)\n                K[:,i] = K[:,i]/c[i]\n        self.c = c\n\n        # Compress K into scipy sparse matrix (csr format)\n        self.csr = csr_matrix(K,dtype=np.float32)\n        self.is_loaded = True\n\n    ## Apply first differnce smoother\n    def first_diffence(self, db, radial_lambda=5., lateral_lambda=5.):\n        if self.smoother: return\n        m = blockmodel.Model()\n        dwt = self.c[...] ** 2\n\n        # Insert extra rows to sensitivity matrix\n        data = []\n        row = []\n        col = []\n\n        # Insert extra elements to traveltime residual\n        (mshell, nshell) = (2578, 18)\n\n        # Radical smoother\n        for i in range(mshell):\n            for j in range(nshell-1):\n                lower_block_num = i + j * mshell\n                upper_block_num = lower_block_num + mshell\n\n                # insert flam for lower block and -flam for upper to matrix\n                newrow = row[-1] + 1 if len(row) > 0 else 0\n                row.append(newrow)\n                col.append(lower_block_num)\n                data.append(radial_lambda / self.c[lower_block_num])\n                dwt[lower_block_num] += (radial_lambda / self.c[lower_block_num]) ** 2\n\n                row.append(newrow)\n                col.append(upper_block_num)\n                data.append(-radial_lambda / self.c[upper_block_num])\n                dwt[upper_block_num] += (radial_lambda / self.c[upper_block_num]) ** 2\n\n                # insert 0 residual to self.d\n                self.d = np.append(self.d, 0)\n                \n        # Lateral smoother\n        for this_block in range(nshell*mshell):\n            # get surrounding blocks\n            west_neigbor = m[this_block].neighbor('W').id\n            east_neigbor = m[this_block].neighbor('E').id\n            south_neighbor = m[this_block].neighbor('S').id\n            north_neighbor = m[this_block].neighbor('N').id\n\n            # insert 4*glam for center block and -glam for ambient to matrix\n            newrow = row[-1] + 1 if len(row) > 0 else 0\n            row.append(newrow)\n            col.append(this_block)\n            data.append(4 * lateral_lambda / self.c[this_block])\n            dwt[this_block] += (4 * lateral_lambda / self.c[this_block]) ** 2\n\n            row.append(newrow)\n            col.append(north_neighbor)\n            data.append(-lateral_lambda / self.c[north_neighbor])\n            dwt[north_neighbor] += (lateral_lambda / self.c[north_neighbor]) ** 2\n\n            row.append(newrow)\n            col.append(south_neighbor)\n            data.append(-lateral_lambda / self.c[south_neighbor])\n            dwt[south_neighbor] += (lateral_lambda / self.c[south_neighbor]) ** 2\n\n            row.append(newrow)\n            col.append(east_neigbor)\n            data.append(-lateral_lambda / self.c[east_neigbor])\n            dwt[east_neigbor] += (lateral_lambda / self.c[east_neigbor]) ** 2\n\n            row.append(newrow)\n            col.append(west_neigbor)\n            data.append(-lateral_lambda / self.c[west_neigbor])\n            dwt[west_neigbor] += (lateral_lambda / self.c[west_neigbor]) ** 2\n\n            # insert 0 residual to self.d\n            self.d = np.append(self.d, 0)\n\n        # compile smoother matrix and stack with csr\n        print(f\"inserting {len(row)} elements smoother in {row[-1]+1} rows...\")\n        smoother = csr_matrix((data, (row, col)), shape=(row[-1]+1, mshell*nshell))\n        self.csr = vstack([self.csr, smoother])\n        self.c = np.sqrt(dwt)\n\n        # toggle on smoother status\n        self.smoother = True\n\n    ## decompose and reconstruct\n    def svd(self, db):\n        t = time()\n        U, W, VT = svds(self.csr, k=self.num_of_vectors) if self.num_of_vectors < 46404 else svds(self.csr, k=46403)\n        print('SVD with %s vectors finished in %.2f s' % (str(self.num_of_vectors) if self.num_of_vectors < 46404 else 'All', time()-t))\n\n        ### Reshape and save SVD results with timing\n        t = time()\n        thres = self.epsilon * max(W)\n        z_array = []\n        for i in range(W.shape[0]):\n            if W[i] < thres:\n                break\n            z_array.append(1/W[i])\n        Z = diags(z_array)\n        rank = len(z_array)\n\n        V = np.transpose(VT[0:rank, :])\n        UT = np.transpose(U[:, 0:rank])\n\n        ### write to database\n        svd_v_data = overwrite_data(db, f\"/{self.filegroup}/{self.num_of_vectors}/svd_v\", V)\n        svd_z_data = overwrite_data(db, f\"/{self.filegroup}/{self.num_of_vectors}/svd_z\", z_array)\n        svd_ut_data = overwrite_data(db, f\"/{self.filegroup}/{self.num_of_vectors}/svd_ut\", UT)\n        svd_z_data.attrs['epsilon'] = self.epsilon\n\n        t = time()\n        m = V @ (Z @ (UT @ self.d))\n        if self.is_thickness_to_weight: m = revert_h_weighting(m)\n        if self.is_coverage_to_weight: m = revert_c_weighting(m, self.c)\n        s = pd.Series(m.reshape(len(m)))\n        model = overwrite_data(db, f\"/{self.filegroup}/{self.num_of_vectors}/model\", m)\n        print(s.describe())\n        print('inversion model calculated from SVD in %.2f s' % (time()-t))\n\n\n# parse input parameters\ndef create_parser():\n    parser = argparse.ArgumentParser(prog=\"Tomography Inversion Tools\")\n    parser.add_argument(\"f\", help=\"filegroup\")\n    parser.add_argument(\"-k\", help=\"truncated size\", type=int, default=6000)\n    parser.add_argument(\"--epsilon\", \"-e\", help=\"neglecting threshold\", type=float, default=1e-4)\n    parser.add_argument(\"--regular\", \"-l\", help=\"power magnitude for regularization\", type=int, default=2)\n    parser.add_argument(\"-c\", help=\"coverage weighting\", action='store_true')\n    parser.add_argument(\"-z\", help=\"thickness weighting\", action='store_true')\n    parser.add_argument(\"--smooth\", help=\"apply smoother\", action='store_true')\n    parser.add_argument(\"--overwrite\", \"-o\", help=\"overwrite kernel\", action='store_true')\n    parser.add_argument(\"--dispose\", \"-d\", help=\"not to save kernel\", action='store_true')\n    return parser\n\ndef create_params(f, **kwargs):\n    parser = create_parser()\n    args = []\n    args.append(f)\n    for key in kwargs.keys():\n        if not kwargs[key] is False:\n            args.append(f\"--{key}\" if len(key) > 1 else f\"-{key}\") # note this is only compatible with Python >= 3.6\n            if not type(kwargs[key]) is bool:args.append(str(kwargs[key]))\n    return parser.parse_args(args)\n\n# main program\ndef inversion(params, output_dir='.'):\n    ## prepare kernel data\n    db = open_hdf5(f\"{output_dir}/database.hdf\")\n    data = Kernel(params)\n\n    if not params.overwrite:\n        print(\"try to load sensitivity matrix if possible...\")\n        data.load_kernel(db)\n\n    if not data.is_loaded:\n        if not params.overwrite: print(\"no sensitivity matrix availible\")\n        print(\"generating sensitivity matrix from data...\")\n        data.get_kernel()\n        ## add smoother to kernel matrix\n        if params.smooth: data.first_diffence(db, radial_lambda=5, lateral_lambda=5)\n        if not params.dispose:\n            data.save_kernel(db)\n            print(\"sensitivity matrix saved.\")\n    else:\n        print(\"sensitivity matrix loaded.\")\n\n    print(f\"sensitivity matrix shape: {data.csr.shape}\")\n    ## implement svd\n    data.svd(db)\n    db.close()\n    \n# open database\ndef open_hdf5(filename):\n    os.environ['HDF5_USE_FILE_LOCKING'] = 'FALSE'\n    try:\n        db = h5py.File(filename, mode='a')\n    except:\n        db = h5py.File(filename, mode='w')\n    return db\n\n# handle database write\ndef overwrite_data(db, path, newdata):\n    if path in db: del db[path]\n    data = db.create_dataset(path, data=newdata)\n    return data\n\n\n# run as main\nif __name__ == '__main__':\n    parser = create_parser()\n    params = parser.parse_args()\n    inversion(params)\n", "meta": {"hexsha": "7fff71e17e2bc9c3892d7b2b9cab50910de6d3c9", "size": 14367, "ext": "py", "lang": "Python", "max_stars_repo_path": "inversion.py", "max_stars_repo_name": "Jun1453/tomofilter", "max_stars_repo_head_hexsha": "efd8db983c92386ae93a4544e057d61b2d38b89c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inversion.py", "max_issues_repo_name": "Jun1453/tomofilter", "max_issues_repo_head_hexsha": "efd8db983c92386ae93a4544e057d61b2d38b89c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inversion.py", "max_forks_repo_name": "Jun1453/tomofilter", "max_forks_repo_head_hexsha": "efd8db983c92386ae93a4544e057d61b2d38b89c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.1441441441, "max_line_length": 231, "alphanum_fraction": 0.5901023178, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.1880983138567776}}
{"text": "# This file is part of PSL-Python.\n# Copyright (c) 2021, Eijiro Shibusawa <phd_kimberlite@yahoo.co.jp>\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n#    list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n#    this list of conditions and the following disclaimer in the documentation\n#    and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport numpy as np\nimport cv2\n\nfrom colormap import colormap as jet\nfrom pixel_cost import absolute_difference as ad_cost\nfrom pixel_cost import zero_mean_normalized_cross_correlation as zncc_cost\nfrom pixel_cost import zero_mean_absolute_difference as zsad_cost\nfrom pixel_cost import normalized_cross_correlation as ncc_cost\n\ndef depth_to_colormap(depth, min_z, max_z):\n    mask = depth > 0\n    delta = 1/min_z - 1/max_z\n    index = np.round(np.maximum(0, np.minimum(1/(depth + 1E-6) - 1/max_z, delta) / delta) * 255).astype(np.int)\n    img = (jet[index] * 255).astype(np.uint8)\n    img[~mask] = (0,0,0)\n    return img\n\nclass plane_sweep():\n    def __init__(self):\n        self.scale = 1.0\n        self.near_z = 0.4\n        self.far_z = 5000\n        self.match_window_width = 7\n        self.match_window_height = 7\n        self.num_planes = 256\n        self.near_y = 0.4\n        self.far_y = 1.5\n        self.num_ground = 16\n        self.plane_generation_mode_ = {'uniform_depth':0, 'uniform_disparity':1}\n        self.plane_generation_mode = self.plane_generation_mode_['uniform_disparity']\n        self.matching_costs_ = {'sad':0, 'zncc':1, 'zsad':2, 'ncc':3}\n        self.matching_costs = self.matching_costs_['sad']\n        self.matching_gpu_batch_enabled = False\n        self.sub_pixel_interpolation_mode_ = {'direct':0, 'inverse':1}\n        self.sub_pixel_interpolation_mode = self.sub_pixel_interpolation_mode_['inverse']\n        self.ouput_cost_volume_enabled = False\n        self.sub_pixel_enabled = True\n        self.box_filer_ad_enabled = True\n        self.write_debug_warping_enabled = False\n        self.ground_plane_enabled = False\n        self.use_gpu = False\n        self.clear_images()\n        self.CV = None\n        self.rays = None\n\n    @staticmethod\n    def generate_depth(near, far, num, mode):\n        if mode == 1:\n            minD = 1/far\n            maxD = 1/near\n            dstep = (maxD - minD)/(num - 1)\n            depth = 1 / (np.arange(maxD, minD - dstep, -dstep))\n        else:\n            step = (far - near)/(num - 1)\n            depth  = np.arange(near, far + step, step)\n        return np.flip(depth)[:num]\n\n    def generate_planes(self):\n        # front parallel\n        fp_planes = np.zeros((4, self.num_planes), dtype=np.float)\n        fp_planes[2, :] = -1\n        fp_planes_has_neighbor = np.full(self.num_planes, True, dtype=np.bool)\n        fp_planes_has_neighbor[0] = fp_planes_has_neighbor[-1] = False\n        fp_planes[3, :] = plane_sweep.generate_depth(self.near_z, self.far_z, self.num_planes, self.plane_generation_mode)\n        self.planes = fp_planes\n        self.planes_has_neighbor = fp_planes_has_neighbor\n\n        # ground\n        if self.ground_plane_enabled:\n            g_planes = np.zeros((4, self.num_ground), dtype=np.float)\n            g_planes[1, :] = -1\n            g_planes[3, :] = plane_sweep.generate_depth(self.near_y, self.far_y, self.num_ground, self.plane_generation_mode)\n            g_planes_has_neighbor = np.full(self.num_ground, True, dtype=np.bool)\n            g_planes_has_neighbor[0] = g_planes_has_neighbor[-1] = False\n            self.planes = np.hstack((self.planes, g_planes))\n            self.planes_has_neighbor = np.hstack((self.planes_has_neighbor, g_planes_has_neighbor))\n\n    def transform_planes(self, R, t):\n        self.Hs = np.empty((self.planes.shape[1], 3, 3), dtype=self.planes.dtype)\n        for k in range(0, self.Hs.shape[0]):\n            p = self.planes[:,k]\n            n = (p[0:3][:,np.newaxis])\n            self.Hs[k] = R + np.dot(t, n.T)/p[3]\n\n    def add_image(self, cam, R, t, img):\n        # Xc = Rc*X - Tc\n        self.cams.append(cam)\n        self.Rs.append(R)\n        self.Ts.append(t)\n        self.imgs.append(img)\n\n    def clear_images(self):\n        self.imgs = list()\n        self.cams = list()\n        self.Rs = list()\n        self.Ts = list()\n\n    def get_cost_volume(self, ref):\n        self.generate_planes()\n\n        n_planes = self.planes.shape[1]\n        n_imgs = len(self.imgs)\n        sz_img = self.imgs[ref].shape\n\n        accumlation_scale = 1.0 / (n_imgs - 1)\n        if self.matching_costs == 1:\n            cost_function = zncc_cost(self.imgs[ref], n_planes, (self.match_window_width, self.match_window_height), scale=accumlation_scale)\n        elif self.matching_costs == 2:\n            cost_function = zsad_cost(self.imgs[ref], n_planes, (self.match_window_width, self.match_window_height), self.box_filer_before_occlusion_enabled, scale=accumlation_scale)\n        elif self.matching_costs == 3:\n            cost_function = ncc_cost(self.imgs[ref], n_planes, (self.match_window_width, self.match_window_height), scale=accumlation_scale)\n        else:\n            cost_function = ad_cost(self.imgs[ref], n_planes, (self.match_window_width, self.match_window_height), self.box_filer_ad_enabled, scale=accumlation_scale)\n\n        if n_imgs == 2: # stereo case\n            self.mask = np.zeros((sz_img[0], sz_img[1], n_planes), np.bool)\n\n        rays = self.cams[ref].unproject_rays(sz_img)\n        for k in range(0, n_imgs):\n            if k == ref:\n                continue\n            # relative pose\n            R = np.dot(self.Rs[k], self.Rs[ref].T)\n            t = np.dot(R, self.Ts[ref]) - self.Ts[k]\n            self.transform_planes(R, t)\n            img_other = self.imgs[k]\n            cam_other = self.cams[k]\n            for l in range(0, n_planes):\n                xyz = np.dot(self.Hs[l], rays)\n                xy = cam_other.project(xyz).astype(np.float32)\n                warp = cv2.remap(img_other, xy[0].reshape(sz_img), xy[1].reshape(sz_img), cv2.INTER_LINEAR, None, cv2.BORDER_WRAP, 255)\n                cost_function.accumulate(warp, l)\n                if n_imgs == 2: # stereo case\n                    mask = (xy[0,:] >= 0) & (xy[1,:] >= 0) & (xy[0,:] < sz_img[1]) & (xy[1,:] < sz_img[0])\n                    mask = mask.reshape(sz_img)\n                    self.mask[:,:,l] = mask\n\n                if self.write_debug_warping_enabled:\n                    cv2.imwrite('debug_warping_{:04d}_{:04d}.png'.format(k, l), warp)\n\n        self.CV = cost_function.get_cost_volume()\n        self.rays = rays\n\n    def get_depth_from_planes(self, indices):\n        if (self.planes is None) or (self.rays is None):\n            return None\n\n        xy = np.empty((2, self.rays.shape[1]), dtype=np.float)\n        xy[0] = self.rays[0,:] / self.rays[2,:]\n        xy[1] = self.rays[1,:] / self.rays[2,:]\n\n        indices_0 = indices.reshape(-1)\n        plane_depth = self.planes[3,indices_0]\n        plane_dot = xy[0] * self.planes[0, indices_0] + xy[1] * self.planes[1, indices_0] + self.planes[2, indices_0]\n\n        if self.sub_pixel_enabled:\n            indices_mask = self.planes_has_neighbor[indices]\n            indices_m = np.copy(indices)\n            indices_m[indices_mask] += 1\n            indices_p = np.copy(indices)\n            indices_p[indices_mask] -= 1\n            cost_0 = np.take_along_axis(self.CV, indices[:,:,np.newaxis], 2).reshape(-1)\n            cost_p = np.take_along_axis(self.CV, indices_p[:,:,np.newaxis], 2).reshape(-1)\n            cost_m = np.take_along_axis(self.CV, indices_m[:,:,np.newaxis], 2).reshape(-1)\n            offset_denom = cost_p + cost_m - (cost_0 * 2)\n            offset_denom_mask = np.abs(offset_denom) < 1E-5\n            offset_denom[offset_denom_mask] = 1\n            offset = (cost_m - cost_p)/(2 * offset_denom)\n            offset[offset_denom_mask] = 0\n\n            if self.sub_pixel_interpolation_mode == 0:\n                step_p = self.planes[3, indices_p.reshape(-1)] - self.planes[3, indices_0]\n                step_m = self.planes[3, indices_0] - self.planes[3, indices_m.reshape(-1)]\n                depth_sub = np.copy(offset)\n                depth_sub[offset < 0] = (offset*step_m)[offset < 0]\n                depth_sub[offset > 0] = (offset*step_p)[offset > 0]\n                D = -(plane_depth + depth_sub) / plane_dot\n            else:\n                step_p = 1/(self.planes[3, indices_0]) - 1/(self.planes[3, indices_p.reshape(-1)])\n                step_m = 1/(self.planes[3, indices_m.reshape(-1)]) - 1/(self.planes[3, indices_0])\n\n                depth_sub = np.copy(offset)\n                depth_sub[offset < 0] = (offset*step_m)[offset < 0]\n                depth_sub[offset > 0] = (offset*step_p)[offset > 0]\n                D = -1/(1/plane_depth - depth_sub) / plane_dot\n        else:\n            D = -plane_depth / plane_dot\n\n        D = D.reshape(indices.shape)\n        return D\n\n    def get_depth(self, ref = 0):\n        try:\n            import torch\n            import psl_cuda as py_psl_cuda\n        except ImportError:\n            self.use_gpu = False\n\n        if not self.use_gpu:\n            if self.CV is None:\n                self.get_cost_volume(ref)\n            best_plane_indices = np.argmin(self.CV, axis=2)\n            D = self.get_depth_from_planes(best_plane_indices)\n        else:\n            D = self.get_depth_gpu(ref)\n\n        return D\n\n    def get_depth_gpu(self, ref = 0):\n        if self.sub_pixel_enabled:\n            raise ValueError(\"Subpixel estimation is not supported!\")\n\n        try:\n            import torch\n            import psl_cuda as py_psl_cuda\n            from pixel_cost_cuda import absolute_difference as ad_cost_cuda\n            from pixel_cost_cuda import zero_mean_normalized_cross_correlation as zncc_cost_cuda\n            from pixel_cost_cuda import zero_mean_absolute_difference as zsad_cost_cuda\n            from pixel_cost_cuda import normalized_cross_correlation as ncc_cost_cuda\n        except ImportError:\n            return None\n\n        self.generate_planes()\n        n_imgs = len(self.imgs)\n\n        # upload tensor\n        if str(self.cams[ref].__class__.__name__) == 'unified_camera':\n            # unified camera model has xi parameters\n            Ks = [np.array([C.K[0, 0], C.K[1, 1], C.K[0, 2], C.K[1, 2], C.xi])  for C in self.cams]\n            t_Ks = torch.tensor(np.array(Ks), dtype=torch.float32, device=torch.device('cpu'))\n\n        t_imgs = torch.tensor(np.array(self.imgs), device=torch.device('cuda'))\n        t_Ps = torch.tensor(self.planes.T, dtype=torch.float32, device=torch.device('cuda'))\n        t_Rs = torch.tensor(np.array(self.Rs), dtype=torch.float32, device=torch.device('cpu'))\n        t_Ts = torch.tensor(np.array(self.Ts), dtype=torch.float32, device=torch.device('cpu'))\n\n        # cost function\n        if self.matching_costs == 1:\n            cost_function = zncc_cost_cuda(t_imgs[ref], (self.match_window_width, self.match_window_height),\n                                self.matching_gpu_batch_enabled)\n        elif self.matching_costs == 2:\n            cost_function = zsad_cost_cuda(t_imgs[ref], (self.match_window_width, self.match_window_height),\n                                self.box_filer_before_occlusion_enabled, self.matching_gpu_batch_enabled)\n        elif self.matching_costs == 3:\n            cost_function = ncc_cost_cuda(t_imgs[ref], (self.match_window_width, self.match_window_height),\n                                self.matching_gpu_batch_enabled)\n        else:\n            cost_function = ad_cost_cuda(t_imgs[ref], (self.match_window_width, self.match_window_height),\n                                self.box_filer_ad_enabled, self.matching_gpu_batch_enabled)\n\n        # compute warped images\n        rays_gpu = py_psl_cuda.get_ray_tensor(ref, t_imgs, t_Ks)\n        warped_images_gpu = py_psl_cuda.get_warped_image_tensor(ref, t_imgs, t_Ks, t_Rs, t_Ts, rays_gpu, t_Ps)\n        if self.write_debug_warping_enabled:\n            warped_images = warped_images_gpu.to('cpu').numpy()\n            for k in range(0, n_imgs - 1):\n                for l in range(0, self.planes.shape[1]):\n                    cv2.imwrite('debug_warping_{:04d}_{:04d}.png'.format(k, l), warped_images[k, l])\n\n        # compute cost volume\n        CV = cost_function.get_cost_volume(warped_images_gpu)\n        del warped_images_gpu\n        torch.cuda.empty_cache()\n\n        # WTA\n        indices_gpu = torch.argmin(CV, dim = 0)\n        D_gpu = py_psl_cuda.get_depth_tensor(rays_gpu, indices_gpu, t_Ps)\n        D = D_gpu.to('cpu').numpy()\n\n        if self.ouput_cost_volume_enabled:\n            self.CV = CV.to('cpu').numpy().transpose(1, 2, 0)\n\n        del CV, rays_gpu, indices_gpu, D_gpu\n        del t_imgs, t_Ps\n        torch.cuda.empty_cache()\n\n        return D\n", "meta": {"hexsha": "fa8a1f8d3d6470768b5054bab58ecc2679dd43b3", "size": 13761, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/psl.py", "max_stars_repo_name": "eshibusawa/PSL-Python", "max_stars_repo_head_hexsha": "e2223f1b24666148b5f20353a961901221539a5f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python/psl.py", "max_issues_repo_name": "eshibusawa/PSL-Python", "max_issues_repo_head_hexsha": "e2223f1b24666148b5f20353a961901221539a5f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/psl.py", "max_forks_repo_name": "eshibusawa/PSL-Python", "max_forks_repo_head_hexsha": "e2223f1b24666148b5f20353a961901221539a5f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.5662251656, "max_line_length": 182, "alphanum_fraction": 0.6258266114, "include": true, "reason": "import numpy", "num_tokens": 3523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.18807784012867443}}
{"text": "from core.macid_base import MACIDBase\nfrom core.macid import MACID\nimport networkx as nx\nfrom typing import Any, List, Dict, Union\nfrom core.get_paths import directed_decision_free_path, find_all_dir_paths, find_all_undir_paths, get_motif, \\\n    is_active_indirect_frontdoor_trail, is_active_path\nimport copy\n\n\ndef _get_key_node(mb: MACIDBase, path: List[str]) -> str:\n    \"\"\"\n    Returns the key node of a path (ie the first \"fork\" node in the path)\n    \"\"\"\n    for _, b, _ in zip(path[:-2], path[1:-1], path[2:]):\n        structure = get_motif(mb, path, path.index(b))\n        if structure == \"fork\":\n            return b\n    return \"\"  # shouldn't happen\n\n\ndef _effective_dir_path_exists(mb: MACIDBase, start: str, finish: str, effective_set: List[str]) -> bool:\n    \"\"\"\n    checks whether an effective directed path exists\n\n    \"\"\"\n    start_finish_paths = find_all_dir_paths(mb, start, finish)\n    for path in start_finish_paths:\n        if _path_is_effective(mb, path, effective_set):\n            return True\n    else:\n        return False\n\n\ndef _effective_undir_path_exists(mb: MACIDBase, start: str, finish: str, effective_set: List[str]) -> bool:\n    \"\"\"\n    checks whether an effective undirected path exists\n    \"\"\"\n    start_finish_paths = find_all_undir_paths(mb, start, finish)\n    for path in start_finish_paths:\n        if _path_is_effective(mb, path, effective_set):\n            return True\n    else:\n        return False\n\n\ndef _path_is_effective(mb: MACIDBase, path: List[str], effective_set: List[str]) -> bool:\n    \"\"\"\n    checks whether a path is effective\n    \"\"\"\n    dec_nodes_in_path = set(mb.all_decision_nodes).intersection(set(path[1:]))  # exclude first node of the path\n    all_dec_nodes_effective = all(dec_node in effective_set for dec_node in dec_nodes_in_path)\n    # all([]) evaluates to true => this covers case where path has no decision nodes\n    if all_dec_nodes_effective:\n        return True\n    else:\n        return False\n\n\ndef _directed_effective_path_not_through_set_y(mb: MACIDBase, start: str, finish: str,\n                                               effective_set: List[str], y: List[str] = []) -> bool:\n    \"\"\"\n    checks whether a directed effective path exists that doesn't pass through any of the nodes in the set y.\n    \"\"\"\n    start_finish_paths = find_all_dir_paths(mb, start, finish)\n    for path in start_finish_paths:\n        path_not_through_y = set(y).isdisjoint(set(path))\n        if _path_is_effective(mb, path, effective_set) and path_not_through_y:\n            return True\n    else:\n        return False\n\n\ndef _effective_backdoor_path_not_blocked_by_set_w(mb: MACIDBase, start: str, finish: str, effective_set: List[str],\n                                                  w: List[str] = []) -> List[str]:\n    \"\"\"\n    Returns the effective backdoor path not blocked if we condition on nodes in set w.\n    If no such path exists, this returns None.\n    \"\"\"\n    start_finish_paths: List[List[str]] = find_all_undir_paths(mb, start, finish)\n    for path in start_finish_paths:\n        is_backdoor_path = path[1] in mb.get_parents(path[0])\n        not_blocked_by_w = is_active_path(mb, path, w)\n        if is_backdoor_path and _path_is_effective(mb, path, effective_set) and not_blocked_by_w:\n            return path\n    return []\n\n\ndef _effective_undir_path_not_blocked_by_set_w(mb: MACIDBase, start: str, finish: str,\n                                               effective_set: List[str], w: List[str] = []) -> Union[List[str], None]:\n    \"\"\"\n    Returns an effective undirected path not blocked if we condition on nodes in set w.\n    If no such path exists, this returns None.\n    \"\"\"\n    start_finish_paths: List[List[str]] = find_all_undir_paths(mb, start, finish)\n    for path in start_finish_paths:\n        not_blocked_by_w = is_active_path(mb, path, w)\n        if _path_is_effective(mb, path, effective_set) and not_blocked_by_w:\n            return path\n    else:\n        return None\n\n\ndef direct_effect(macid: MACID, decision: str) -> bool:\n    \"\"\"checks to see whether this decision is motivated by a direct effect reasoning patter.\n    Graphical Criterion:\n    1) There is a directed decision free path from D_A to a utility node U_A\n    \"\"\"\n    if decision not in macid.nodes:\n        raise Exception(f\"{decision} is not present in the macid\")\n\n    agent = macid.whose_node[decision]\n    agent_utils = macid.utility_nodes_agent[agent]\n    for u in agent_utils:\n        if directed_decision_free_path(macid, decision, u):\n            return True\n    else:\n        return False\n\n\ndef manipulation(macid: MACID, decision: str, effective_set: List[str]) -> bool:\n    \"\"\"checks to see whether this decision is motivated by an incentive for manipulation\n    Graphical Criterion:\n    1) There is a directed decision-free path from D_A to an effective decision node D_B.\n    2) There is a directed, effective path from D_B to U_A (an effective path is a path in which all\n    decision nodes, except possibly the initial node, and except fork nodes, are effective)\n    3) There is a directed, effective path from D_A to U_B that does not pass through D_B.\n    \"\"\"\n    if decision not in macid.nodes:\n        raise Exception(f\"{decision} is not present in the macid\")\n\n    if not all([node in macid.nodes for node in effective_set]):\n        raise Exception(\"One or many of the nodes in the effective_set are not present in the macid.\")\n\n    agent = macid.whose_node[decision]\n    agent_utils = macid.utility_nodes_agent[agent]\n    reachable_decisions = []    # set of possible D_B\n    list_decs = copy.deepcopy(macid.all_decision_nodes)\n    list_decs.remove(decision)\n    for dec_reach in list_decs:\n        if dec_reach in effective_set:\n            if directed_decision_free_path(macid, decision, dec_reach):\n                reachable_decisions.append(dec_reach)\n\n    for decision_b in reachable_decisions:\n        agent_b = macid.whose_node[decision_b]\n        agent_b_utils = macid.utility_nodes_agent[agent_b]\n\n        for u in agent_utils:\n            if _effective_dir_path_exists(macid, decision_b, u, effective_set):\n\n                for u_b in agent_b_utils:\n                    if _directed_effective_path_not_through_set_y(macid, decision, u_b, effective_set, [decision_b]):\n                        return True\n    else:\n        return False\n\n\ndef signaling(macid: MACID, decision: str, effective_set: List[str]) -> bool:\n    \"\"\"checks to see whether this decision is motivated by an incentive for signaling\n\n    Graphical Criterion:\n    1) There is a directed decision-free path from D_A to an effective decision node D_B.\n    2) There is a directed, effective path from D_B to U_A.\n    3) There is an effective back-door path π from D_A to U_B that is not blocked by D_B U W^{D_A}_{D_B}.\n    4) If C is the key node in π, there is an effective path from C to U_A that is not blocked by D_A U W^{C}_{D_A}\n\n    \"\"\"\n    if decision not in macid.nodes:\n        raise Exception(f\"{decision} is not present in the macid\")\n\n    if not all([node in macid.nodes for node in effective_set]):\n        raise Exception(\"One or many of the nodes in the effective_set are not present in the macid.\")\n\n    agent = macid.whose_node[decision]\n    agent_utils = macid.utility_nodes_agent[agent]\n    reachable_decisions = []    # set of possible D_B\n    list_decs = copy.deepcopy(macid.all_decision_nodes)\n    list_decs.remove(decision)\n    for dec_reach in list_decs:\n        if dec_reach in effective_set:\n            if directed_decision_free_path(macid, decision, dec_reach):\n                reachable_decisions.append(dec_reach)\n\n    for decision_b in reachable_decisions:\n        agent_b = macid.whose_node[decision_b]\n        agent_b_utils = macid.utility_nodes_agent[agent_b]\n        for u in agent_utils:\n            if _effective_dir_path_exists(macid, decision_b, u, effective_set):\n                for u_b in agent_b_utils:\n\n                    decision_b_parents_not_desc_decision = [node for node in macid.get_parents(decision_b)\n                                                            if node not in set(nx.descendants(macid, decision))]\n                    cond_nodes = [decision_b] + decision_b_parents_not_desc_decision\n\n                    if _effective_backdoor_path_not_blocked_by_set_w(macid, decision, u_b, effective_set, cond_nodes):\n                        path = _effective_backdoor_path_not_blocked_by_set_w(macid, decision, u_b, effective_set,\n                                                                             cond_nodes)\n                        if _get_key_node(macid, path):\n                            key_node = _get_key_node(macid, path)\n                        else:\n                            return False\n                        decision_parents_not_desc_key_node = [node for node in macid.get_parents(decision)\n                                                              if node not in set(nx.descendants(macid, key_node))]\n                        cond_nodes2 = [decision] + decision_parents_not_desc_key_node\n\n                        if _effective_undir_path_not_blocked_by_set_w(macid, key_node, u, effective_set, cond_nodes2):\n                            return True\n    else:\n        return False\n\n\ndef revealing_or_denying(macid: MACID, decision: str, effective_set: List[str]) -> bool:\n    \"\"\"checks to see whether this decision is motivated by an incentive for revealing or denying\n\n    Graphical Criterion:\n    1) There is a directed decision-free path from D_A to an effective decision node D_B.\n    2) There is a direced, effective path from D_B to U_A.\n    3) There is an effective indirect front-door path π from D_A to U_B that is not blocked by D_B U W^{D_A}_{D_B}.\n    \"\"\"\n    if decision not in macid.nodes:\n        raise Exception(f\"{decision} is not present in the macid\")\n\n    if not all([node in macid.nodes for node in effective_set]):\n        raise Exception(\"One or many of the nodes in the effective_set are not present in the macid.\")\n\n    agent = macid.whose_node[decision]\n    agent_utils = macid.utility_nodes_agent[agent]\n    reachable_decisions = []    # set of possible D_B\n    list_decs = copy.deepcopy(macid.all_decision_nodes)\n    list_decs.remove(decision)\n    for dec_reach in list_decs:\n        if dec_reach in effective_set:\n            if directed_decision_free_path(macid, decision, dec_reach):\n                reachable_decisions.append(dec_reach)\n\n    for decision_b in reachable_decisions:\n        agent_b = macid.whose_node[decision_b]\n        agent_b_utils = macid.utility_nodes_agent[agent_b]\n\n        for u in agent_utils:\n            if _effective_dir_path_exists(macid, decision_b, u, effective_set):\n\n                for u_b in agent_b_utils:\n                    decision_b_parents_not_desc_decision = [node for node in macid.get_parents(decision_b)\n                                                            if node not in set(nx.descendants(macid, decision))]\n                    cond_nodes = [decision_b] + decision_b_parents_not_desc_decision\n                    if is_active_indirect_frontdoor_trail(macid, decision, u_b, cond_nodes):\n                        return True\n    else:\n        return False\n\n\ndef get_reasoning_patterns(mb: MACID) -> Dict[str, List[Any]]:\n    \"\"\" Return a dictionary matching each reasoning pattern with the decision nodes in the MAID which admit it.\n    This finds all of the circumstances under which an agent in a MAID has a reason to prefer one strategy over\n    another, when all other agents are playing WD strategies.\n    (Pfeffer and Gal, 2007: On the Reasoning patterns of Agents in Games).\n    \"\"\"\n    motivations: Dict[str, List[str]] = {'dir_effect': [], 'sig': [], 'manip': [], 'rev_den': []}\n    effective_set = list(mb.all_decision_nodes)\n    while True:\n        new_set = [dec for dec in effective_set if direct_effect(mb, dec) or manipulation(mb, dec, effective_set)\n                   or signaling(mb, dec, effective_set) or revealing_or_denying(mb, dec, effective_set)]\n\n        if len(new_set) == len(effective_set):\n            break\n        effective_set = new_set\n\n    for decision in effective_set:\n        if direct_effect(mb, decision):\n            motivations['dir_effect'].append(decision)\n        elif signaling(mb, decision, effective_set):\n            motivations['sig'].append(decision)\n        elif manipulation(mb, decision, effective_set):\n            motivations['manip'].append(decision)\n        elif revealing_or_denying(mb, decision, effective_set):\n            motivations['rev_den'].append(decision)\n\n    return motivations\n", "meta": {"hexsha": "242f9649db6183da88c4572518cf00af9e003420", "size": 12562, "ext": "py", "lang": "Python", "max_stars_repo_path": "analyze/reasoning_patterns.py", "max_stars_repo_name": "edlanglois/pycid", "max_stars_repo_head_hexsha": "eb88f504a21018d7be847eeff50f7642a5a90f50", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analyze/reasoning_patterns.py", "max_issues_repo_name": "edlanglois/pycid", "max_issues_repo_head_hexsha": "eb88f504a21018d7be847eeff50f7642a5a90f50", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analyze/reasoning_patterns.py", "max_forks_repo_name": "edlanglois/pycid", "max_forks_repo_head_hexsha": "eb88f504a21018d7be847eeff50f7642a5a90f50", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8642857143, "max_line_length": 118, "alphanum_fraction": 0.6624741283, "include": true, "reason": "import networkx", "num_tokens": 2861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.18807784012867443}}
{"text": "#!/usr/bin/env python\n\n# Author: Dogacan S. Ozturk\n\ndef merge_pfisr_with_gitm_potentials(PhiX, PhiY, XadaptGrids, YadaptGrids, pfisrTimes, weimerSimulationList, gridRes, mergeParameter, plotPotentials, savePotentials):\n    \n    '''\n    This function merges the potentials calculated from PFISR estimates with the\n    global potential patterns obtained from Weimer driven GITM simulations.\n    \n    To merge potentials, the user is required to provide a global potential pattern.\n    These potentials can be obtained by directly using the Global Ionosphere\n    Thermosphere Model (GITM) output driven with Weimer Potentials. This code can work\n    with 3DALL, 3DION, 3DUSR, or 3DHME output from GITM, as long as the output\n    files have the potential and grid values. If the output doesn't have the\n    PotentialY, we suggest creating a dictionary item called 'PotentialY'\n    which is a copy of the 'Potential' values, such as:\n    gitmSimulationResults['PotentialY'] = gitmSimulationResults['Potential']\n    \n    User passes a mergeParameter that is the scalar value of the standard\n    deviation for Gaussian kernel, between 0.1 to 1.0, 0.1 indicating maximum\n    and 1.0 indicating minimum smoothing during merging of the local and global\n    parameters.\n    \n    Parameters:\n    ===========\n    PhiX:                   A numpy array of calculated potential differences in\n                            longitudinal direction, provided in Volts.\n    PhiY:                   A numpy array of calculated potential differences in\n                            latitudinal direction, provided in Volts.\n    XadaptGrids:            A numpy array containing the longitude coordinates\n                            of the downsampled grid points in degrees.\n    YadaptGrids:            A numpy array containing the latitude coordinates of\n                            the downsampled grid points in degrees.\n    PfisrTimes:             An array of datetime objects storing the values of\n                            averaged PFISR experiments.\n    weimerSimulationsList:  String for full path of the simulation results. The\n                            files can be 3DALL, 3DUSR, 3DION, or 3DHME as long\n                            as the results containt 'Potential' and 'PotentialY'\n    gridRes:                A float value of the new uniform grid spacing.\n    mergeParameter:         A float value between 0.1 to 1.0 that in summary,\n                            defines the degree of smoothing 0.1 being maximum,\n                            while 1.0 is the minimum smoothing applied to\n                            estimated potentials.\n    plotPotentials:         Logical, if True will save plots of the potentials.\n    savePotentials:         Logical, if True will save the output files in a\n                            format similar to AMIE procedure.\n    \n    Returns:\n    ========\n    phiXhime:  Numpy array of merged potentials in longitudinal direction. [V]\n    phiYhime:  Numpy array of merged potentials in latitudinal direction. [V]\n    himeEx:    Numpy array of electric field values in longitudinal direction\n               calculated from the new HIME potentials. [mV/m]\n    himeEy:    Numpy array of electric field values in latitudinal direction\n               calculated from the new HIME potentials. [mV/m]\n    xHimeMesh: Numpy array of longitudinal values of the new global grid. [deg]\n    yHimeMesh: Numpy array of latitudinal values of the new global grid. [deg]\n    himeTimes: Datetime array of merged potentials.\n    \n    Example:\n    ========\n    >> from merge_potentials import merge_pfisr_with_gitm_potentials\n    >> weimerSimulationList = glob('../Examples/Files/Simulations/3D*.bin')\n    >> mergeParameter = 0.6\n    >> plotPotentials = True\n    >> savePotentials = True\n    >> phiXhime, phiYhime, himeEx, himeEy, xHimeMesh, yHimeMesh, himeTimes =\n       merge_pfisr_with_gitm_potentials(PhiX, PhiY, XnewGrids, YnewGrids,\n       experimentTimes, weimerSimulationList, gridRes, mergeParameter,\n       plotPotentials, savePotentials)\n        \n    '''\n    \n    # Import default python libraries.\n    import numpy as np\n    import datetime as dt\n    from apexpy import Apex\n    from scipy.ndimage.filters import gaussian_filter\n    from scipy.interpolate import griddata\n    \n    # Import custom python libraries.\n    from spacepy.pybats import gitm\n    from hime_helper_functions import calc_distance\n    from hime_processing_functions import plot_hime_output\n    from hime_processing_functions import write_hime_output\n    \n    # Sort the simulation files.\n    weimerSimulationList.sort()\n    nFiles = len(weimerSimulationList)\n    \n    # Define adapted grids.\n    naX = np.shape(XadaptGrids)[0]\n    naY = np.shape(YadaptGrids)[0]\n    \n    # Allocate arrays for the new values of electric fields.\n    ExMerged = np.zeros((nFiles, naX, naY))\n    EyMerged = np.zeros((nFiles, naX, naY))\n    \n    # Create a big mesh and a median mesh in magnetic local time.\n    nres2deg = gridRes*24./360.\n    xBigMeshPts = np.arange(0.0, 24.0 + nres2deg, nres2deg)\n    xMedMeshPts = np.arange(0.0, 30.0 + nres2deg, nres2deg)\n    yBigMeshPts = np.arange(0.0, 90., gridRes)\n    \n    nxBigMesh = len(xBigMeshPts)\n    nyBigMesh = len(yBigMeshPts)\n    \n    nxMedMesh = len(xMedMeshPts)\n    nyMedMesh = len(yBigMeshPts)\n    \n    yBigMesh, xBigMesh = np.meshgrid(yBigMeshPts, xBigMeshPts)\n    yMedMesh, xMedMesh = np.meshgrid(yBigMeshPts, xMedMeshPts)\n    \n    # Allocate arrays for the HIME potentials and times.\n    himePotX = np.zeros((nFiles, nxBigMesh, nyBigMesh))\n    himePotY = np.zeros((nFiles, nxBigMesh, nyBigMesh))\n    himeTimes = np.zeros(nFiles, dtype=object)\n    \n    for file in range(nFiles):\n        gitmOutput = gitm.GitmBin(weimerSimulationList[file]) # Read the HME output.\n        gitmTime = gitmOutput['time'] # Set time.\n        himeTimes[file] = gitmTime\n        \n        # Find matching PFISR experiment time.\n        pfisrTimeInd = np.where(np.abs(gitmTime-pfisrTimes)==np.abs(gitmTime-pfisrTimes).min())[0][0]\n        \n        # Read in simulation mesh.\n        gitmLats = np.rad2deg(gitmOutput['Latitude'][:,:,-1])\n        gitmLons = np.rad2deg(gitmOutput['Longitude'][:,:,-1])\n        \n        # Get the dimensions of the simulation mesh.\n        nGitmLons = np.shape(gitmLats)[0]\n        nGitmLats = np.shape(gitmLats)[1]\n        \n        # Calculate number of points in simulation grids.\n        nPoints = nGitmLats*nGitmLons\n        \n        # Obtain the magnetic local time coordinates of the grid points.\n        dmlon = np.reshape(gitmOutput['Magnetic Longitude'][:,:,-1], [nPoints,1])\n        mlt_time = Apex(date=gitmTime)\n        dmlon = mlt_time.mlon2mlt(dmlon,gitmTime)\n        dmlon[np.where(dmlon<=6.)] = dmlon[np.where(dmlon<=6.)]+24.\n        dmlat = np.reshape(gitmOutput['Magnetic Latitude'][:,:,-1], [nPoints,1])\n        \n        mltPoints = np.zeros([nPoints,2])\n        for n in range(nPoints):\n            mltPoints[n,0] = dmlon[n]\n            mltPoints[n,1] = dmlat[n]\n            \n        # Obtain values in geographic coordinates.\n        geopotx = np.reshape(gitmOutput['Potential'][:,:,-1], [nPoints, 1])\n        geopoty = np.reshape(gitmOutput['PotentialY'][:,:,-1], [nPoints, 1])\n            \n        # Interpolate the new data on the median mesh.\n        gitmXonMedMesh = griddata(mltPoints,geopotx,(xMedMesh,yMedMesh), method='linear')[:,:,0]\n        gitmYonMedMesh = griddata(mltPoints,geopoty,(xMedMesh,yMedMesh), method='linear')[:,:,0]\n        \n        # Create a new mesh to store values of the interpolated potentials.\n        gitmXonBigMesh = np.zeros([nxBigMesh,nyBigMesh])\n        gitmYonBigMesh = np.zeros([nxBigMesh,nyBigMesh])\n        \n        for lon in range(nxMedMesh):\n            for lat in range(nyMedMesh):\n                if(xMedMesh[lon,lat]>=24.):\n                    xActual = xMedMesh[lon,lat]-24.0\n                else:\n                    xActual = xMedMesh[lon,lat]\n                    \n                indX = np.where(np.abs(xActual - xBigMeshPts) == np.abs(xActual - xBigMeshPts).min())\n                gitmXonBigMesh[indX,lat] = gitmXonMedMesh[lon,lat]\n                gitmYonBigMesh[indX,lat] = gitmYonMedMesh[lon,lat]\n        \n        # Place the potentials estimated from PFISR measurements on the\n        # global simulation mesh.\n        \n        pfisrXonBigMesh = np.zeros([nxBigMesh, nyBigMesh])\n        pfisrYonBigMesh = np.zeros([nxBigMesh, nyBigMesh])\n        \n        for lon in range(naX):\n            for lat in range(naY):\n                pointLat = YadaptGrids[lat]\n                pointLon = mlt_time.mlon2mlt(XadaptGrids[lon], gitmTime)\n                \n                indLat = np.where(np.abs(pointLat - yBigMeshPts) == np.abs(pointLat - yBigMeshPts).min())[0]\n                \n                indLon = np.where(np.abs(pointLon - xBigMeshPts) == np.abs(pointLon - xBigMeshPts).min())[0]\n                \n                pfisrXonBigMesh[indLon, indLat] = PhiX[pfisrTimeInd, lon, lat]\n                pfisrYonBigMesh[indLon, indLat] = PhiY[pfisrTimeInd, lon, lat]\n        \n        # Merge the calculated potentials with simulated potentials, both\n        # on the simulation mesh.\n        mergedPotX = gaussian_filter(gitmXonBigMesh+pfisrXonBigMesh,mergeParameter)\n        mergedPotY = gaussian_filter(gitmYonBigMesh+pfisrYonBigMesh,mergeParameter)\n        \n        # Clean the nan values that arise from interpolation.\n        mergedPotX[np.isnan(mergedPotX)] = 0.0\n        mergedPotY[np.isnan(mergedPotY)] = 0.0\n        \n        # Plot potentials if user set plotPotentials to true.\n        if(plotPotentials):\n            plot_hime_output(xBigMesh, yBigMesh, mergedPotX, mergedPotY, gitmTime)\n        \n        # Save potentials if user set savePotentials to true.\n        if(savePotentials):\n            write_hime_output(xBigMesh, yBigMesh, mergedPotX, mergedPotY, gitmTime)\n        \n        # Store the values of the merged potentials.\n        himePotX[file] = mergedPotX\n        himePotY[file] = mergedPotY\n        \n        # Calculate the electric fields using central differencing at this step\n        # again for inspecting the results.\n        for i in range(1,naX-1):\n            for j in range(1,naY-1):\n                pointLat = YadaptGrids[j]\n                pointLon = mlt_time.mlon2mlt(XadaptGrids[i], gitmTime)\n\n                indLat = np.where(np.abs(pointLat - yBigMeshPts) == np.abs(pointLat - yBigMeshPts).min())[0]\n            \n                indLon = np.where(np.abs(pointLon - xBigMeshPts) == np.abs(pointLon - xBigMeshPts).min())[0]\n                \n                dx = calc_distance(YadaptGrids[j],YadaptGrids[j],XadaptGrids[i+1],XadaptGrids[i-1])\n                dy = calc_distance(YadaptGrids[j+1],YadaptGrids[j-1],XadaptGrids[i],XadaptGrids[i])\n            \n                if (indLon >= (nxBigMesh-1)):\n                    ExMerged[file, i, j] = -(mergedPotX[indLon, indLat] - mergedPotX[indLon-1, indLat])/(dx/2.)\n                elif (indLat >= (nyBigMesh-1)):\n                    EyMerged[pfisrTimeInd, i, j] = -(mergedPotY[indLon, indLat+1] - mergedPotY[indLon, indLat-1])/(dy/2.)\n                else:\n                    ExMerged[file, i, j] = -(mergedPotX[indLon+1, indLat] - mergedPotX[indLon-1, indLat])/dx\n                    EyMerged[file, i, j] = -(mergedPotY[indLon, indLat+1] - mergedPotY[indLon, indLat-1])/dy\n                    \n    return(himePotX, himePotY, ExMerged, EyMerged, xBigMesh, yBigMesh, himeTimes)\n    \n", "meta": {"hexsha": "2cd6a7e9040db325221ed733148a409049530abf", "size": 11465, "ext": "py", "lang": "Python", "max_stars_repo_path": "Code/merge_potentials.py", "max_stars_repo_name": "dcsozturk/hime", "max_stars_repo_head_hexsha": "07c056e48258d8e3de7c99cde9a9b1c8d073285e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-02T05:21:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-19T06:28:18.000Z", "max_issues_repo_path": "Code/merge_potentials.py", "max_issues_repo_name": "dcsozturk/hime", "max_issues_repo_head_hexsha": "07c056e48258d8e3de7c99cde9a9b1c8d073285e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/merge_potentials.py", "max_forks_repo_name": "dcsozturk/hime", "max_forks_repo_head_hexsha": "07c056e48258d8e3de7c99cde9a9b1c8d073285e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.3755274262, "max_line_length": 166, "alphanum_fraction": 0.6297426952, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.18807783643814138}}
{"text": "# NiftyRec - Ray-tracing tools\n# Stefano Pedemonte\n# Center for Medical Image Computing (CMIC), University College Lonson (UCL)\n# 2009-2012, London\n# Aalto University, School of Science\n# Summer 2013, Helsinki\n# Martinos Center for Biomedical Imaging, Harvard University/MGH\n# Jan. 2014, Boston\n\nfrom simplewrap import *\nimport numpy\nimport os, platform\n\n__all__ = ['test_library_niftyrec_c', 'gpu_set', 'gpu_reset', 'gpu_list', 'gpu_exists',\n           'PET_project', 'PET_backproject', 'PET_project_compressed', 'PET_backproject_compressed',\n           'SPECT_project_parallelholes', 'SPECT_backproject_parallelholes',\n           'CT_project_conebeam', 'CT_backproject_conebeam', 'CT_project_parallelbeam', 'CT_backproject_parallelbeam',\n           'ET_spherical_phantom', 'ET_cylindrical_phantom', 'ET_spheres_ring_phantom',\n           'TR_grid_from_box_and_affine', 'TR_resample_grid', 'TR_resample_box', 'TR_gradient_grid', 'TR_gradient_box',\n           'TR_transform_grid',\n           'INTERPOLATION_LINEAR', 'INTERPOLATION_POINT']\n\nlibrary_name = \"_et_array_interface\"\nniftyrec_lib_paths = [localpath(), filepath(__file__), './', '/usr/local/niftyrec/lib/',\n                      'C:/Prorgam Files/NiftyRec/lib/']\n\nINTERPOLATION_LINEAR = 0\nINTERPOLATION_POINT = 1\n\n\n####################################### Error handling: ########################################\n\nclass ErrorInCFunction(Exception):\n    def __init__(self, msg, status, function_name):\n        self.msg = str(msg)\n        self.status = status\n        self.function_name = function_name\n        if self.status == status_io_error():\n            self.status_msg = \"IO Error\"\n        elif self.status == status_initialisation_error():\n            self.status_msg = \"Error with the initialisation of the C library\"\n        elif self.status == status_parameter_error():\n            self.status_msg = \"One or more of the specified parameters are not right\"\n        elif self.status == status_unhandled_error():\n            self.status_msg = \"Unhandled error, likely a bug. \"\n        else:\n            self.status_msg = \"Unspecified Error\"\n\n    def __str__(self):\n        return \"'%s' returned by the C Function '%s' (error code %d). %s\" % (\n        self.status_msg, self.function_name, self.status, self.msg)\n\n\ndef status_success():\n    \"\"\"Returns the value returned by the function calls to the library in case of success. \"\"\"\n    r = call_c_function(niftyrec_c.status_success, [{'name': 'return_value', 'type': 'uint', 'value': None}])\n    return r.return_value\n\n\ndef status_io_error():\n    \"\"\"Returns the integer value returned by the function calls to the library in case of IO error. \"\"\"\n    r = call_c_function(niftyrec_c.status_io_error, [{'name': 'return_value', 'type': 'uint', 'value': None}])\n    return r.return_value\n\n\ndef status_initialisation_error():\n    \"\"\"Returns the value returned by the function calls to the library in case of initialisation error. \"\"\"\n    r = call_c_function(niftyrec_c.status_initialisation_error,\n                        [{'name': 'return_value', 'type': 'uint', 'value': None}])\n    return r.return_value\n\n\ndef status_parameter_error():\n    \"\"\"Returns the value returned by the function calls to the library in case of parameter error. \"\"\"\n    r = call_c_function(niftyrec_c.status_parameter_error, [{'name': 'return_value', 'type': 'uint', 'value': None}])\n    return r.return_value\n\n\ndef status_unhandled_error():\n    \"\"\"Returns the value returned by the function calls to the library in case of unhandled error. \"\"\"\n    r = call_c_function(niftyrec_c.status_unhandled_error, [{'name': 'return_value', 'type': 'uint', 'value': None}])\n    return r.return_value\n\n\nclass LibraryNotFound(Exception):\n    def __init__(self, msg):\n        self.msg = msg\n\n    def __str__(self):\n        return \"Library cannot be found: %s\" % str(self.msg)\n\n    ####################################### Load library: ########################################\n\n\ndef test_library_niftyrec_c():\n    \"\"\"Test whether the C library niftyrec_c responds. \"\"\"\n    number = 101  # just a number\n    descriptor = [{'name': 'input', 'type': 'int', 'value': number},\n                  {'name': 'output', 'type': 'int', 'value': None}, ]\n    r = call_c_function(niftyrec_c.echo, descriptor)\n    return r.output == number\n\n\n# search for the library in the list of locations 'niftyrec_lib_paths' \n# and in the locations in the environment variables \"LD_LIBRARY_PATH\", \"DYLD_LIBRARY_PATH\" and \"PATH\"\n\nif platform.system() == 'Linux':\n    sep = \":\"\nelif platform.system() == 'Darwin':\n    sep = \":\"\nelif platform.system() == 'Windows':\n    sep = \";\"\nif os.environ.has_key('LD_LIBRARY_PATH'):\n    niftyrec_lib_paths = niftyrec_lib_paths + os.environ['LD_LIBRARY_PATH'].split(sep)\nif os.environ.has_key('DYLD_LIBRARY_PATH'):\n    niftyrec_lib_paths = niftyrec_lib_paths + os.environ['DYLD_LIBRARY_PATH'].split(sep)\nif os.environ.has_key('PATH'):\n    niftyrec_lib_paths = niftyrec_lib_paths + os.environ['PATH'].split(sep)\n\n(found, fullpath, path) = find_c_library(library_name, niftyrec_lib_paths)\nif found == NOT_FOUND:\n    print \"The library %s cannot be FOUND, please make sure that the path to the NiftyRec libraries has been exported. \" % fullpath\n    print \"1) Before launching Python, type the following in the terminal (the same terminal): \"\n    path = \"'path to the niftyrec libraries'\"\n    if platform.system() == 'Linux':\n        print \"export LD_LIBRARY_PATH=%s\" % path\n    elif platform.system() == 'Darwin':\n        print \"export DYLD_LIBRARY_PATH=%s\" % path\n    elif platform.system() == 'Windows':\n        print \"Add %s to the system PATH using Control Panel -> Advanced Settings -> System -> ..\" % path\n    raise LibraryNotFound(\"NiftyRec\" + \" (\" + str(library_name) + \") \")\nelif found == FOUND_NOT_LOADABLE:\n    print \"The library %s cannot be LOADED, please make sure that the path to the NiftyRec libraries has been exported. \" % fullpath\n    print \"1) Before launching Python, type the following in the terminal (the same terminal): \"\n    if platform.system() == 'Linux':\n        print \"export LD_LIBRARY_PATH=%s\" % path\n    elif platform.system() == 'Darwin':\n        print \"export DYLD_LIBRARY_PATH=%s\" % path\n    elif platform.system() == 'Windows':\n        print \"Add %s to the system PATH using Control Panel -> Advanced Settings -> System -> ..\" % path\n    raise LibraryNotFound(\"NiftyRec\" + \" (\" + str(library_name) + \") \")\nelse:\n    niftyrec_c = load_c_library(fullpath)\n\n\n#################################### Create interface to the C functions: ####################################\n\ndef gpu_list():\n    \"\"\"List GPUs and get information. \"\"\"\n    MAX_GPUs = 1000\n    INFO_SIZE = 5\n    description = [{'name': 'N', 'type': 'array', 'value': None, 'dtype': int32, 'size': (1,)},\n                   {'name': 'info', 'type': 'array', 'value': None, 'dtype': int32, 'size': (MAX_GPUs, INFO_SIZE)}, ]\n    r = call_c_function(niftyrec_c.et_array_list_gpus, descriptor)\n    if not r.status == status_success():\n        raise ErrorInCFunction(\"The execution of 'list_gpus' was unsuccessful.\", r.status,\n                               'niftyrec_c.et_array_list_gpus')\n    N = r.dictionary['N']\n    info = r.dictionary['info']\n    gpus = []\n    for i in range(N):\n        gpus.append({'id': info[i, 0], 'gflops': info[i, 1], 'multiprocessors': info[i, 2], 'clock': info[i, 3],\n                     'globalmemory': info[i, 4]})\n    return gpus\n\n\ndef gpu_exists(id):\n    \"\"\"Check if GPU with given id exists. \"\"\"\n    for gpu in gpu_list():\n        if gpu['id'] == id:\n            return True\n    return False\n\n\ndef gpu_set(id):\n    \"\"\"Set GPU (when multiple GPUs are installed in the system). \"\"\"\n    description = [{'name': 'id', 'type': 'int', 'value': int32(id)}, ]\n    r = call_c_function(niftyrec_c.et_array_set_gpu, descriptor)\n    if not r.status == status_success():\n        raise ErrorInCFunction(\"The execution of 'set_gpu' was unsuccessful.\", r.status, 'niftyrec_c.et_array_set_gpu')\n\n\ndef gpu_reset():\n    \"\"\"Reset the currently selected GPU. \"\"\"\n    r = call_c_function(niftyrec_c.et_array_reset_gpu, [])\n    if not r.status == status_success():\n        raise ErrorInCFunction(\"The execution of 'reset_gpu' was unsuccessful.\", r.status,\n                               'niftyrec_c.et_array_reset_gpu')\n\n\ndef PET_project(activity, attenuation, binning,\n                use_gpu=0):  # FIXME: in this and all other functions, replace 'binning' object with (only the required) raw variables\n    \"\"\"PET projection; output projection data is compressed. \"\"\"\n    descriptor = [{'name': 'activity', 'type': 'array', 'value': activity},\n                  {'name': 'activity_size_x', 'type': 'int', 'value': activity.shape[0]},\n                  {'name': 'activity_size_y', 'type': 'int', 'value': activity.shape[1]},\n                  {'name': 'activity_size_z', 'type': 'int', 'value': activity.shape[2]},\n\n                  {'name': 'attenuation', 'type': 'array', 'value': attenuation},\n                  {'name': 'attenuation_size_x', 'type': 'int', 'value': attenuation.shape[0]},\n                  {'name': 'attenuation_size_y', 'type': 'int', 'value': attenuation.shape[1]},\n                  {'name': 'attenuation_size_z', 'type': 'int', 'value': attenuation.shape[2]},\n\n                  {'name': 'use_gpu', 'type': 'int', 'value': use_gpu}, ]\n    r = call_c_function(niftyrec_c.PET_project, descriptor)\n    if not r.status == status_success():\n        raise ErrorInCFunction(\"The execution of 'PET_project' was unsuccessful.\", r.status, 'niftyrec_c.PET_project')\n    return r.dictionary['projection']\n\n\ndef PET_backproject(projection_data, attenuation, binning, use_gpu=0):\n    \"\"\"PET back-projection; input projection data is compressed. \"\"\"\n    descriptor = []\n    r = call_c_function(niftyrec_c.PET_backproject, descriptor)\n    if not r.status == status_success():\n        raise ErrorInCFunction(\"The execution of 'PET_backproject' was unsuccessful.\", r.status,\n                               'niftyrec_c.PET_backproject')\n    return r.dictionary\n\n\ndef PET_project_compressed(activity, attenuation, offsets, locations, active,\n                           N_axial, N_azimuthal, angles_axial, angles_azimuthal, N_u, N_v, size_u, size_v,\n                           activity_size_x, activity_size_y, activity_size_z, attenuation_size_x, attenuation_size_y,\n                           attenuation_size_z,\n                           T_activity_x, T_activity_y, T_activity_z, R_activity_x, R_activity_y, R_activity_z,\n                           T_attenuation_x, T_attenuation_y, T_attenuation_z, R_attenuation_x, R_attenuation_y,\n                           R_attenuation_z,\n                           use_gpu, N_samples, sample_step, background, background_attenuation,\n                           truncate_negative_values, direction, block_size):\n    \"\"\"PET projection; output projection data is compressed. \"\"\"\n    N_locations = locations.shape[1]\n    # accept attenuation=None:\n    if attenuation is None:\n        attenuation = numpy.zeros((0, 0, 0))\n    descriptor = [{'name': 'projection', 'type': 'array', 'value': None, 'dtype': float32, 'size': (N_locations)},\n                  {'name': 'activity', 'type': 'array', 'value': activity},\n                  {'name': 'N_activity_x', 'type': 'uint', 'value': activity.shape[0]},\n                  {'name': 'N_activity_y', 'type': 'uint', 'value': activity.shape[1]},\n                  {'name': 'N_activity_z', 'type': 'uint', 'value': activity.shape[2]},\n                  {'name': 'activity_size_x', 'type': 'float', 'value': activity_size_x},\n                  {'name': 'activity_size_y', 'type': 'float', 'value': activity_size_y},\n                  {'name': 'activity_size_z', 'type': 'float', 'value': activity_size_z},\n\n                  {'name': 'T_activity_x', 'type': 'float', 'value': T_activity_x},\n                  {'name': 'T_activity_y', 'type': 'float', 'value': T_activity_y},\n                  {'name': 'T_activity_z', 'type': 'float', 'value': T_activity_z},\n                  {'name': 'R_activity_x', 'type': 'float', 'value': R_activity_x},\n                  {'name': 'R_activity_y', 'type': 'float', 'value': R_activity_y},\n                  {'name': 'R_activity_z', 'type': 'float', 'value': R_activity_z},\n\n                  {'name': 'attenuation', 'type': 'array', 'value': attenuation},\n                  {'name': 'N_attenuation_x', 'type': 'uint', 'value': attenuation.shape[0]},\n                  {'name': 'N_attenuation_y', 'type': 'uint', 'value': attenuation.shape[1]},\n                  {'name': 'N_attenuation_z', 'type': 'uint', 'value': attenuation.shape[2]},\n                  {'name': 'attenuation_size_x', 'type': 'float', 'value': attenuation_size_x},\n                  {'name': 'attenuation_size_y', 'type': 'float', 'value': attenuation_size_y},\n                  {'name': 'attenuation_size_z', 'type': 'float', 'value': attenuation_size_z},\n\n                  {'name': 'T_attenuation_x', 'type': 'float', 'value': T_attenuation_x},\n                  {'name': 'T_attenuation_y', 'type': 'float', 'value': T_attenuation_y},\n                  {'name': 'T_attenuation_z', 'type': 'float', 'value': T_attenuation_z},\n                  {'name': 'R_attenuation_x', 'type': 'float', 'value': R_attenuation_x},\n                  {'name': 'R_attenuation_y', 'type': 'float', 'value': R_attenuation_y},\n                  {'name': 'R_attenuation_z', 'type': 'float', 'value': R_attenuation_z},\n\n                  {'name': 'N_axial', 'type': 'uint', 'value': N_axial},\n                  {'name': 'N_azimuthal', 'type': 'uint', 'value': N_azimuthal},\n                  {'name': 'angles_axial', 'type': 'array', 'value': angles_axial},\n                  {'name': 'angles_azimuthal', 'type': 'array', 'value': angles_azimuthal},\n                  {'name': 'N_u', 'type': 'uint', 'value': N_u},\n                  {'name': 'N_v', 'type': 'uint', 'value': N_v},\n                  {'name': 'size_u', 'type': 'float', 'value': size_u},\n                  {'name': 'size_v', 'type': 'float', 'value': size_v},\n\n                  {'name': 'N_locations', 'type': 'uint', 'value': N_locations},\n\n                  {'name': 'offsets', 'type': 'array', 'value': offsets},\n                  {'name': 'locations', 'type': 'array', 'value': locations},\n                  {'name': 'active', 'type': 'array', 'value': active},\n\n                  {'name': 'N_samples', 'type': 'uint', 'value': N_samples},\n                  {'name': 'sample_step', 'type': 'float', 'value': sample_step},\n                  {'name': 'background', 'type': 'float', 'value': background},\n                  {'name': 'background_attenuation', 'type': 'float', 'value': background_attenuation},\n                  {'name': 'truncate_negative_values', 'type': 'uint', 'value': truncate_negative_values},\n\n                  {'name': 'use_gpu', 'type': 'uint', 'value': use_gpu},\n                  {'name': 'direction', 'type': 'uint', 'value': direction},\n                  {'name': 'block_size', 'type': 'uint', 'value': block_size},\n                  ]\n    r = call_c_function(niftyrec_c.PET_project_compressed, descriptor)\n    if not r.status == status_success():\n        raise ErrorInCFunction(\"The execution of 'PET_project_compressed' was unsuccessful.\", r.status,\n                               'niftyrec_c.PET_project_compressed')\n    return r.dictionary[\"projection\"]\n\n\ndef PET_project_compressed_test(activity, attenuation, N_axial, N_azimuthal, offsets, locations, active):\n    N_locations = locations.shape[1]\n    # accept attenuation=None:\n    if attenuation is None:\n        attenuation = numpy.zeros((0, 0, 0))\n    descriptor = [{'name': 'projection', 'type': 'array', 'value': None, 'dtype': float32, 'size': (N_locations), },\n                  {'name': 'activity', 'type': 'array', 'value': activity},\n                  {'name': 'N_activity_x', 'type': 'uint', 'value': activity.shape[0]},\n                  {'name': 'N_activity_y', 'type': 'uint', 'value': activity.shape[1]},\n                  {'name': 'N_activity_z', 'type': 'uint', 'value': activity.shape[2]},\n\n                  {'name': 'attenuation', 'type': 'array', 'value': attenuation},\n                  {'name': 'N_attenuation_x', 'type': 'uint', 'value': attenuation.shape[0]},\n                  {'name': 'N_attenuation_y', 'type': 'uint', 'value': attenuation.shape[1]},\n                  {'name': 'N_attenuation_z', 'type': 'uint', 'value': attenuation.shape[2]},\n\n                  {'name': 'N_axial', 'type': 'uint', 'value': N_axial},\n                  {'name': 'N_azimuthal', 'type': 'uint', 'value': N_azimuthal},\n                  {'name': 'N_locations', 'type': 'uint', 'value': N_locations},\n\n                  {'name': 'offsets', 'type': 'array', 'value': offsets},\n                  {'name': 'locations', 'type': 'array', 'value': locations},\n                  {'name': 'active', 'type': 'array', 'value': active}, ]\n    r = call_c_function(niftyrec_c.PET_project_compressed_test, descriptor)\n    if not r.status == status_success():\n        raise ErrorInCFunction(\"The execution of 'PET_project_compressed_test' was unsuccessful.\", r.status,\n                               'niftyrec_c.PET_project_compressed_test')\n    return r.dictionary[\"projection\"]\n\n\ndef PET_backproject_compressed(projection_data, attenuation, offsets, locations, active,\n                               N_axial, N_azimuthal, angles_axial, angles_azimuthal, N_u, N_v, size_u, size_v,\n                               N_activity_x, N_activity_y, N_activity_z,\n                               activity_size_x, activity_size_y, activity_size_z,\n                               attenuation_size_x, attenuation_size_y, attenuation_size_z,\n                               T_activity_x, T_activity_y, T_activity_z, R_activity_x, R_activity_y, R_activity_z,\n                               T_attenuation_x, T_attenuation_y, T_attenuation_z, R_attenuation_x, R_attenuation_y,\n                               R_attenuation_z,\n                               use_gpu, N_samples, sample_step, background, background_attenuation, direction,\n                               block_size):\n    \"\"\"PET back-projection; input projection data is compressed. \"\"\"\n    N_locations = locations.shape[1]\n    # accept attenuation=None:\n    if attenuation is None:\n        attenuation = numpy.zeros((0, 0, 0))\n    descriptor = [{'name': 'back_projection', 'type': 'array', 'value': None, 'dtype': float32,\n                   'size': (N_activity_x, N_activity_y, N_activity_z), 'order': \"F\"},\n                  {'name': 'N_activity_x', 'type': 'uint', 'value': N_activity_x},\n                  {'name': 'N_activity_y', 'type': 'uint', 'value': N_activity_y},\n                  {'name': 'N_activity_z', 'type': 'uint', 'value': N_activity_z},\n                  {'name': 'activity_size_x', 'type': 'float', 'value': activity_size_x},\n                  {'name': 'activity_size_y', 'type': 'float', 'value': activity_size_y},\n                  {'name': 'activity_size_z', 'type': 'float', 'value': activity_size_z},\n\n                  {'name': 'T_activity_x', 'type': 'float', 'value': T_activity_x},\n                  {'name': 'T_activity_y', 'type': 'float', 'value': T_activity_y},\n                  {'name': 'T_activity_z', 'type': 'float', 'value': T_activity_z},\n                  {'name': 'R_activity_x', 'type': 'float', 'value': R_activity_x},\n                  {'name': 'R_activity_y', 'type': 'float', 'value': R_activity_y},\n                  {'name': 'R_activity_z', 'type': 'float', 'value': R_activity_z},\n\n                  {'name': 'attenuation', 'type': 'array', 'value': attenuation},\n                  {'name': 'N_attenuation_x', 'type': 'uint', 'value': attenuation.shape[0]},\n                  {'name': 'N_attenuation_y', 'type': 'uint', 'value': attenuation.shape[1]},\n                  {'name': 'N_attenuation_z', 'type': 'uint', 'value': attenuation.shape[2]},\n                  {'name': 'attenuation_size_x', 'type': 'float', 'value': attenuation_size_x},\n                  {'name': 'attenuation_size_y', 'type': 'float', 'value': attenuation_size_y},\n                  {'name': 'attenuation_size_z', 'type': 'float', 'value': attenuation_size_z},\n\n                  {'name': 'T_attenuation_x', 'type': 'float', 'value': T_attenuation_x},\n                  {'name': 'T_attenuation_y', 'type': 'float', 'value': T_attenuation_y},\n                  {'name': 'T_attenuation_z', 'type': 'float', 'value': T_attenuation_z},\n                  {'name': 'R_attenuation_x', 'type': 'float', 'value': R_attenuation_x},\n                  {'name': 'R_attenuation_y', 'type': 'float', 'value': R_attenuation_y},\n                  {'name': 'R_attenuation_z', 'type': 'float', 'value': R_attenuation_z},\n\n                  {'name': 'N_axial', 'type': 'uint', 'value': N_axial},\n                  {'name': 'N_azimuthal', 'type': 'uint', 'value': N_azimuthal},\n                  {'name': 'angles_axial', 'type': 'array', 'value': angles_axial},\n                  {'name': 'angles_azimuthal', 'type': 'array', 'value': angles_azimuthal},\n                  {'name': 'N_u', 'type': 'uint', 'value': N_u},\n                  {'name': 'N_v', 'type': 'uint', 'value': N_v},\n                  {'name': 'size_u', 'type': 'float', 'value': size_u},\n                  {'name': 'size_v', 'type': 'float', 'value': size_v},\n\n                  {'name': 'N_locations', 'type': 'uint', 'value': N_locations},\n\n                  {'name': 'offsets', 'type': 'array', 'value': offsets},\n                  {'name': 'locations', 'type': 'array', 'value': locations},\n                  {'name': 'active', 'type': 'array', 'value': active},\n                  {'name': 'projection_data', 'type': 'array', 'value': projection_data},\n\n                  {'name': 'use_gpu', 'type': 'uint', 'value': use_gpu},\n                  {'name': 'N_samples', 'type': 'uint', 'value': N_samples},\n                  {'name': 'sample_step', 'type': 'float', 'value': sample_step},\n                  {'name': 'background_activity', 'type': 'float', 'value': background},\n                  {'name': 'background_attenuation', 'type': 'float', 'value': background_attenuation},\n                  {'name': 'direction', 'type': 'uint', 'value': direction},\n                  {'name': 'block_size', 'type': 'uint', 'value': block_size}, ]\n    r = call_c_function(niftyrec_c.PET_backproject_compressed, descriptor)\n    if not r.status == status_success():\n        raise ErrorInCFunction(\"The execution of 'PET_backproject_compressed' was unsuccessful.\", r.status,\n                               'niftyrec_c.PET_backproject_compressed')\n    return r.dictionary['back_projection']\n\n\ndef ET_spherical_phantom(voxels, size, center, radius, inner_value, outer_value):\n    \"\"\"Create a spherical phantom. \"\"\"\n    descriptor = [\n        {'name': 'image', 'type': 'array', 'value': None, 'dtype': float32, 'size': (voxels[0], voxels[1], voxels[2]),\n         'order': \"F\"},\n        {'name': 'Nx', 'type': 'uint', 'value': voxels[0]},\n        {'name': 'Ny', 'type': 'uint', 'value': voxels[1]},\n        {'name': 'Nz', 'type': 'uint', 'value': voxels[2]},\n        {'name': 'sizex', 'type': 'float', 'value': size[0]},\n        {'name': 'sizey', 'type': 'float', 'value': size[1]},\n        {'name': 'sizez', 'type': 'float', 'value': size[2]},\n        {'name': 'centerx', 'type': 'float', 'value': center[0]},\n        {'name': 'centery', 'type': 'float', 'value': center[1]},\n        {'name': 'centerz', 'type': 'float', 'value': center[2]},\n        {'name': 'radius', 'type': 'float', 'value': radius},\n        {'name': 'inner_value', 'type': 'float', 'value': inner_value},\n        {'name': 'outer_value', 'type': 'float', 'value': outer_value}, ]\n    r = call_c_function(niftyrec_c.ET_spherical_phantom, descriptor)\n    if not r.status == status_success():\n        raise ErrorInCFunction(\"The execution of 'ET_spherical_phantom' was unsuccessful.\", r.status,\n                               'niftyrec_c.ET_spherical_phantom')\n    return r.dictionary['image']\n\n\ndef ET_cylindrical_phantom(voxels, size, center, radius, length, axis, inner_value, outer_value):\n    \"\"\"Create a cylindrical phantom. \"\"\"\n    descriptor = [\n        {'name': 'image', 'type': 'array', 'value': None, 'dtype': float32, 'size': (voxels[0], voxels[1], voxels[2]),\n         'order': \"F\"},\n        {'name': 'Nx', 'type': 'uint', 'value': voxels[0]},\n        {'name': 'Ny', 'type': 'uint', 'value': voxels[1]},\n        {'name': 'Nz', 'type': 'uint', 'value': voxels[2]},\n        {'name': 'sizex', 'type': 'float', 'value': size[0]},\n        {'name': 'sizey', 'type': 'float', 'value': size[1]},\n        {'name': 'sizez', 'type': 'float', 'value': size[2]},\n        {'name': 'centerx', 'type': 'float', 'value': center[0]},\n        {'name': 'centery', 'type': 'float', 'value': center[1]},\n        {'name': 'centerz', 'type': 'float', 'value': center[2]},\n        {'name': 'radius', 'type': 'float', 'value': radius},\n        {'name': 'length', 'type': 'float', 'value': length},\n        {'name': 'axis', 'type': 'uint', 'value': axis},\n        {'name': 'inner_value', 'type': 'float', 'value': inner_value},\n        {'name': 'outer_value', 'type': 'float', 'value': outer_value}, ]\n    r = call_c_function(niftyrec_c.ET_cylindrical_phantom, descriptor)\n    if not r.status == status_success():\n        raise ErrorInCFunction(\"The execution of 'ET_cylindrical_phantom' was unsuccessful.\", r.status,\n                               'niftyrec_c.ET_cylindrical_phantom')\n    return r.dictionary['image']\n\n\ndef ET_spheres_ring_phantom(voxels, size, center, ring_radius, min_sphere_radius, max_sphere_radius, N_spheres=6,\n                            inner_value=1.0, outer_value=0.0, taper=0, axis=0):\n    \"\"\"Create a phantom with a ring of spheres of variable radius. \"\"\"\n    descriptor = [\n        {'name': 'image', 'type': 'array', 'value': None, 'dtype': float32, 'size': (voxels[0], voxels[1], voxels[2]),\n         'order': \"F\"},\n        {'name': 'Nx', 'type': 'uint', 'value': voxels[0]},\n        {'name': 'Ny', 'type': 'uint', 'value': voxels[1]},\n        {'name': 'Nz', 'type': 'uint', 'value': voxels[2]},\n        {'name': 'sizex', 'type': 'float', 'value': size[0]},\n        {'name': 'sizey', 'type': 'float', 'value': size[1]},\n        {'name': 'sizez', 'type': 'float', 'value': size[2]},\n        {'name': 'centerx', 'type': 'float', 'value': center[0]},\n        {'name': 'centery', 'type': 'float', 'value': center[1]},\n        {'name': 'centerz', 'type': 'float', 'value': center[2]},\n        {'name': 'ring_radius', 'type': 'float', 'value': ring_radius},\n        {'name': 'min_sphere_radius', 'type': 'float', 'value': min_sphere_radius},\n        {'name': 'max_sphere_radius', 'type': 'float', 'value': max_sphere_radius},\n        {'name': 'N_spheres', 'type': 'uint', 'value': N_spheres},\n        {'name': 'inner_value', 'type': 'float', 'value': inner_value},\n        {'name': 'outer_value', 'type': 'float', 'value': outer_value},\n        {'name': 'taper', 'type': 'float', 'value': taper},\n        {'name': 'ring_axis', 'type': 'uint', 'value': axis}, ]\n    r = call_c_function(niftyrec_c.ET_spheres_ring_phantom, descriptor)\n    if not r.status == status_success():\n        raise ErrorInCFunction(\"The execution of 'ET_spheres_ring_phantom' was unsuccessful.\", r.status,\n                               'niftyrec_c.ET_spheres_ring_phantom')\n    return r.dictionary['image']\n\n\ndef SPECT_project_parallelholes(activity, cameras, attenuation=None, psf=None, background=0.0,\n                                background_attenuation=0.0, use_gpu=1, truncate_negative_values=0):\n    \"\"\"SPECT projection; parallel-holes geometry. \"\"\"\n    # accept attenuation=None and psf=None:\n    if attenuation is None:\n        attenuation = numpy.zeros((0, 0, 0))\n    if psf is None:\n        psf = numpy.zeros((0, 0, 0))\n    N_projections = cameras.shape[0]\n    descriptor = [{'name': 'activity', 'type': 'array', 'value': activity},\n                  {'name': 'activity_size', 'type': 'array', 'value': int32(activity.shape)},\n                  {'name': 'projection', 'type': 'array', 'value': None, 'dtype': float32,\n                   'size': (activity.shape[0], activity.shape[1], N_projections), 'order': \"F\"},\n                  {'name': 'projection_size', 'type': 'array',\n                   'value': int32([N_projections, activity.shape[0], activity.shape[1]])},\n                  {'name': 'cameras', 'type': 'array', 'value': cameras, 'order': \"F\"},\n                  {'name': 'cameras_size', 'type': 'array', 'value': int32(cameras.shape)},\n                  {'name': 'psf', 'type': 'array', 'value': psf, 'order': \"F\"},\n                  {'name': 'psf_size', 'type': 'array', 'value': int32(psf.shape)},\n                  {'name': 'attenuation', 'type': 'array', 'value': attenuation},\n                  {'name': 'attenuation_size', 'type': 'array', 'value': int32(attenuation.shape)},\n                  {'name': 'background', 'type': 'float', 'value': background},\n                  {'name': 'background_attenuation', 'type': 'float', 'value': background_attenuation},\n                  {'name': 'use_gpu', 'type': 'int', 'value': use_gpu},\n                  {'name': 'truncate_negative_values', 'type': 'int', 'value': truncate_negative_values}, ]\n\n    r = call_c_function(niftyrec_c.SPECT_project_parallelholes, descriptor)\n    if not r.status == status_success():\n        raise ErrorInCFunction(\"The execution of 'SPECT_project_parallelholes' was unsuccessful.\", r.status,\n                               'niftyrec_c.SPECT_project_parallelholes')\n    return r.dictionary['projection']\n\n\ndef SPECT_backproject_parallelholes(projection, cameras, attenuation=None, psf=None, background=0.0,\n                                    background_attenuation=0.0, use_gpu=1, truncate_negative_values=0):\n    \"\"\"SPECT backprojection; parallel-holes geometry. \"\"\"\n    # accept attenuation=None and psf=None:\n    if attenuation is None:\n        attenuation = numpy.zeros((0, 0, 0))\n    if psf is None:\n        psf = numpy.zeros((0, 0, 0))\n    N_projections = cameras.shape[0]\n    descriptor = [{'name': 'projection', 'type': 'array', 'value': projection},\n                  {'name': 'projection_size', 'type': 'array', 'value': int32(projection.shape)},\n                  {'name': 'backprojection', 'type': 'array', 'value': None, 'dtype': float32,\n                   'size': (projection.shape[0], projection.shape[1], projection.shape[0]), 'order': \"F\"},\n                  {'name': 'backprojection_size', 'type': 'array',\n                   'value': int32([projection.shape[0], projection.shape[1], projection.shape[0]])},\n                  {'name': 'cameras', 'type': 'array', 'value': cameras, 'order': \"F\"},\n                  {'name': 'cameras_size', 'type': 'array', 'value': int32(cameras.shape)},\n                  {'name': 'psf', 'type': 'array', 'value': psf, 'order': \"F\"},\n                  {'name': 'psf_size', 'type': 'array', 'value': int32(psf.shape)},\n                  {'name': 'attenuation', 'type': 'array', 'value': attenuation},\n                  {'name': 'attenuation_size', 'type': 'array', 'value': int32(attenuation.shape)},\n                  {'name': 'background', 'type': 'float', 'value': background},\n                  {'name': 'background_attenuation', 'type': 'float', 'value': background_attenuation},\n                  {'name': 'use_gpu', 'type': 'int', 'value': use_gpu},\n                  {'name': 'truncate_negative_values', 'type': 'int', 'value': truncate_negative_values}, ]\n\n    r = call_c_function(niftyrec_c.SPECT_backproject_parallelholes, descriptor)\n    if not r.status == status_success():\n        raise ErrorInCFunction(\"The execution of 'SPECT_backproject_parallelholes' was unsuccessful.\", r.status,\n                               'niftyrec_c.SPECT_backproject_parallelholes')\n    return r.dictionary['backprojection']\n\n\ndef CT_project_conebeam(attenuation, camera_trajectory, source_trajectory, use_gpu=0):\n    \"\"\"Transmission imaging projection; cone-beam geometry. \"\"\"\n    descriptor = []\n    r = call_c_function(niftyrec_c.CT_project_conebeam, descriptor)\n    if not r.status == status_success():\n        raise ErrorInCFunction(\"The execution of 'CT_project_conebeam' was unsuccessful.\", r.status,\n                               'niftyrec_c.CT_project_conebeam')\n    return r.dictionary\n\n\ndef CT_backproject_conebeam(projection_data, camera_trajectory, source_trajectory, use_gpu=0):\n    \"\"\"Transmission imaging back-projection; cone-beam geometry. \"\"\"\n    descriptor = []\n    r = call_c_function(niftyrec_c.CT_backproject_conebeam, descriptor)\n    if not r.status == status_success():\n        raise ErrorInCFunction(\"The execution of 'CT_backproject_conebeam' was unsuccessful.\", r.status,\n                               'niftyrec_c.CT_backproject_conebeam')\n    return r.dictionary\n\n\ndef CT_project_parallelbeam(attenuation, camera_trajectory, source_trajectory, use_gpu=0):\n    \"\"\"Transmission imaging projection; parallel-beam geometry. \"\"\"\n    descriptor = []\n    r = call_c_function(niftyrec_c.CT_project_parallelbeam, descriptor)\n    if not r.status == status_success():\n        raise ErrorInCFunction(\"The execution of 'CT_project_parallelbeam' was unsuccessful.\", r.status,\n                               'niftyrec_c.CT_project_parallelbeam')\n    return r.dictionary\n\n\ndef CT_backproject_parallelbeam(attenuation, camera_trajectory, source_trajectory, use_gpu=0):\n    \"\"\"Transmission imaging back-projection; parallel-beam geometry. \"\"\"\n    descriptor = []\n    r = call_c_function(niftyrec_c.CT_backproject_parallelbeam, descriptor)\n    if not r.status == status_success():\n        raise ErrorInCFunction(\"The execution of 'CT_backproject_parallelbeam' was unsuccessful.\", r.status,\n                               'niftyrec_c.CT_backproject_parallelbeam')\n    return r.dictionary\n\n\ndef TR_grid_from_box_and_affine(box_min, box_max, box_n, affine_box2grid=None):\n    \"\"\"Create 3D grid from box and affine transformation. \"\"\"\n    if affine_box2grid is None:\n        affine_box2grid = numpy.eye(4, dtype=float32)\n    descriptor = [\n        {'name': 'grid', 'type': 'array', 'value': None, 'dtype': float32, 'size': (box_n[0], box_n[1], box_n[2], 3),\n         'order': \"F\"},\n        {'name': 'affine_box2grid', 'type': 'array', 'value': affine_box2grid, },\n        {'name': 'box_min_x', 'type': 'float', 'value': box_min[0], },\n        {'name': 'box_min_y', 'type': 'float', 'value': box_min[1], },\n        {'name': 'box_min_z', 'type': 'float', 'value': box_min[2], },\n        {'name': 'box_max_x', 'type': 'float', 'value': box_max[0], },\n        {'name': 'box_max_y', 'type': 'float', 'value': box_max[1], },\n        {'name': 'box_max_z', 'type': 'float', 'value': box_max[2], },\n        {'name': 'box_n_x', 'type': 'uint', 'value': box_n[0], },\n        {'name': 'box_n_y', 'type': 'uint', 'value': box_n[1], },\n        {'name': 'box_n_z', 'type': 'uint', 'value': box_n[2], }, ]\n    r = call_c_function(niftyrec_c.TR_grid_from_box_and_affine, descriptor)\n    if not r.status == status_success():\n        raise ErrorInCFunction(\"The execution of 'TR_grid_from_box_and_affine' was unsuccessful.\", r.status,\n                               'niftyrec_c.TR_grid_from_box_and_affine')\n    return r.dictionary['grid']\n\n\ndef TR_resample_grid(image_array, grid_array, affine_index2grid=None, background=0.0, use_gpu=1,\n                     interpolation_mode=INTERPOLATION_LINEAR):\n    \"\"\"Resample the image at locations specified by grid_array (array of 3D locations) and given the affine transformation that maps \n    image array indexes to grid coordinates.  \"\"\"\n    if affine_index2grid is None:\n        affine_index2grid = numpy.eye(4, dtype=float32)\n    resampled_shape = numpy.asarray([grid_array.shape[0], grid_array.shape[1], grid_array.shape[2]])\n    descriptor = [{'name': 'resampled_array', 'type': 'array', 'value': None, 'dtype': float32,\n                   'size': (resampled_shape[0], resampled_shape[1], resampled_shape[2]), 'order': \"F\"},\n                  {'name': 'image_array', 'type': 'array', 'value': image_array, 'dtype': float32},\n                  {'name': 'affine', 'type': 'array', 'value': affine_index2grid, 'dtype': float32},\n                  {'name': 'grid_array', 'type': 'array', 'value': grid_array, 'dtype': float32},\n                  {'name': 'Nx', 'type': 'uint', 'value': image_array.shape[0]},\n                  {'name': 'Ny', 'type': 'uint', 'value': image_array.shape[1]},\n                  {'name': 'Nz', 'type': 'uint', 'value': image_array.shape[2]},\n                  {'name': 'Nx_grid', 'type': 'uint', 'value': resampled_shape[0]},\n                  {'name': 'Ny_grid', 'type': 'uint', 'value': resampled_shape[1]},\n                  {'name': 'Nz_grid', 'type': 'uint', 'value': resampled_shape[2]},\n                  {'name': 'background', 'type': 'float', 'value': background},\n                  {'name': 'use_gpu', 'type': 'uint', 'value': numpy.uint32(use_gpu)},\n                  {'name': 'interpolation_mode', 'type': 'uint', 'value': numpy.uint32(interpolation_mode)},\n                  ]\n    r = call_c_function(niftyrec_c.TR_resample_grid, descriptor)\n    if not r.status == status_success():\n        raise ErrorInCFunction(\"The execution of 'TR_resample_grid' was unsuccessful.\", r.status,\n                               'niftyrec_c.TR_resample_grid')\n    return r.dictionary['resampled_array']\n\n\ndef TR_resample_box(image_array, box_min, box_max, box_n, affine_index2grid=None, background=0, use_gpu=1,\n                    interpolation_mode=INTERPOLATION_LINEAR):\n    pass\n\n\ndef TR_gradient_grid(image_array, grid_array, affine_index2grid=None, background=0, use_gpu=1,\n                     interpolation_mode=INTERPOLATION_LINEAR):\n    pass\n\n\ndef TR_gradient_box(image_array, box_min, box_max, box_n, affine_index2grid=None, background=0, use_gpu=1,\n                    interpolation_mode=INTERPOLATION_LINEAR):\n    pass\n\n\ndef TR_transform_grid(grid_array, affine_from_grid, use_gpu=1):\n    \"\"\"Transform 3D grid according to affine transformation. \"\"\"\n    if affine_from_grid is None:\n        affine_from_grid = numpy.eye(4, dtype=float32)\n    descriptor = [{'name': 'transformed_array', 'type': 'array', 'value': None, 'dtype': float32,\n                   'size': (grid_array.shape[0], grid_array.shape[1], grid_array.shape[2], 3), 'order': \"F\"},\n                  {'name': 'grid_array', 'type': 'array', 'value': grid_array, 'dtype': float32},\n                  {'name': 'Nx', 'type': 'uint', 'value': grid_array.shape[0]},\n                  {'name': 'Ny', 'type': 'uint', 'value': grid_array.shape[1]},\n                  {'name': 'Nz', 'type': 'uint', 'value': grid_array.shape[2]},\n                  {'name': 'affine', 'type': 'array', 'value': affine_from_grid, 'dtype': float32},\n                  {'name': 'use_gpu', 'type': 'uint', 'value': numpy.uint32(use_gpu)}, ]\n    r = call_c_function(niftyrec_c.TR_transform_grid, descriptor)\n    if not r.status == status_success():\n        raise ErrorInCFunction(\"The execution of 'TR_transform_grid' was unsuccessful.\", r.status,\n                               'niftyrec_c.TR_transform_grid')\n    return r.dictionary['transformed_array']\n", "meta": {"hexsha": "432475399847e75524bc06c0b2bacb30b9417829", "size": 39262, "ext": "py", "lang": "Python", "max_stars_repo_path": "occiput_suite/NiftyPy/__bkp/NiftyRec_bk_old.py", "max_stars_repo_name": "mscipio/occiput-suite", "max_stars_repo_head_hexsha": "9b7dc59ad615d46d811eab965a86ec9efe292a7d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-02-22T13:50:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-16T01:28:22.000Z", "max_issues_repo_path": "occiput_suite/NiftyPy/__bkp/NiftyRec_bk_old.py", "max_issues_repo_name": "mscipio/occiput-suite", "max_issues_repo_head_hexsha": "9b7dc59ad615d46d811eab965a86ec9efe292a7d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "occiput_suite/NiftyPy/__bkp/NiftyRec_bk_old.py", "max_forks_repo_name": "mscipio/occiput-suite", "max_forks_repo_head_hexsha": "9b7dc59ad615d46d811eab965a86ec9efe292a7d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-02-22T13:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-14T02:17:32.000Z", "avg_line_length": 58.1659259259, "max_line_length": 134, "alphanum_fraction": 0.5870561866, "include": true, "reason": "import numpy", "num_tokens": 9932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3702253925955867, "lm_q1q2_score": 0.18800484681746524}}
{"text": "#!/usr/bin/env python\nimport unittools as ut\nimport patools as pa\nimport qctools as qc\nimport obtools as ob\nimport iotools as io\nimport argparse\nimport datetime\nimport time\nimport subprocess\nimport os\nfrom os.path import isfile\nimport logging\nimport math\nimport numpy as np\nimport sys\n\"\"\"\nThermochemistry tools.\nRequires:\nQuantum chemistry code, NWChem, MOPAC, ...\nMESS partition function code\nPAC99\nthermp\n\"\"\"\n__updated__ = \"2017-12-15\"\n\n\ndef get_stoichometry(formula, element):\n    \"\"\"\n    Returns the stoichometry (count) of an element in a given formula\n    Note: Case insensitive\n    >>> [get_stoichometry(f,'H') for f in ['C2H4', 'O2', 'CH', 'H2O', 'HO', 'CH3OH']]\n    [4, 0, 1, 2, 1, 4]\n    >>> [get_stoichometry('H2SO4',e) for e in ['N', 'O', 'S', 'H']]\n    [0, 4, 1, 2]\n    \"\"\"\n    formula = formula.upper()\n    element = element.upper()\n    assert len(element) == 1, 'TODO'\n    n = 0\n    pos = formula.find(element)\n    for pos, char in enumerate(formula):\n        if(char == element):\n            if len(formula) > pos+1:\n                if formula[pos+1].isdigit():\n                    n += int(formula[pos+1])\n                else:\n                    n += 1\n            else:\n                n += 1\n    return n\n\n\ndef parse_line16(s):\n    \"\"\"\n    Return a list of numbers parsed from a\n    string of numbers located in every 16 chars.\n    Note: Numbers may not have a space in between.\n    >>> parse_line16(' 2.807326142D-08-7.923286750D-12 0.000000000D+00 3.329428940D+04 3.816278870D+01')\n    [2.807326142e-08, -7.92328675e-12, 0.0, 33294.2894, 38.1627887]\n    \"\"\"\n    assert len(\n        s) % 16 == 0, 'Given string for parse_line should have 16n chararacters, n={1,2,...}'\n    assert len(\n        s) > 0, 'Given string for parse_line should have 16n chararacters, n={1,2,...}'\n\n    n = int(len(s) / 16)\n    # replace fortran exponent D to E\n    tmp = s.replace('D', 'E')\n    nums = [0] * n\n    for i in range(n):\n        nums[i] = float(tmp[i*16:(i+1)*16])\n    return nums\n\n\ndef get_comment_lines(tag, deltaH):\n    \"\"\"\n    Returns 3 line string that includes the comment based on tag, deltaH and date.\n    Based on Franklin Goldsmith's NASA_CKIN.py\n    e.g.:\n    line 1:!\n    line 2:!DHf(0K) =    25.00 [kcal/mol], taken from SJK ANL0\n    line 3:!Q(T) from CI+QC/cc-pVTZ by SJK on  18Apr2017\n\n    TODO: To simplify, instead of a tag, comments could be given directly or\n    it could be read from a database of tags, which can be accessed outside\n    the code.\n    \"\"\"\n    import datetime\n    date = datetime.datetime.now().strftime(\"%d%b%Y\")\n    line1 = '!\\n'\n    if tag == 'SJKB0':\n        line2 = \"!DHf(0K) = %8.2F [kcal/mol], taken from SJK ANL0\\n\" % (deltaH)\n        line3 = '!Q(T) from B3LYP/6-311++G(d,p) by CFG on  ' + date + '\\n'\n    elif tag == 'SJKB20':\n        line2 = \"!DHf(0K) = %8.2F [kcal/mol], taken from SJK ANL0\\n\" % (deltaH)\n        line3 = '!Q(T) from B2PLYPD3/cc-pVTZ by SJK on  ' + date + '\\n'\n    elif tag == 'SJKT0':\n        line2 = \"!DHf(0K) = %8.2F [kcal/mol], taken from SJK ANL0\\n\" % (deltaH)\n        line3 = '!Q(T) from CCSD(T)/cc-pVTZ by SJK on  ' + date + '\\n'\n    elif tag == 'SJKQ0':\n        line2 = \"!DHf(0K) = %8.2F [kcal/mol], taken from SJK ANL0\\n\" % (deltaH)\n        line3 = '!Q(T) from CCSD(T)/cc-pVQZ by SJK on  ' + date + '\\n'\n    elif tag == 'SJKCBS0':\n        line2 = \"!DHf(0K) = %8.2F [kcal/mol], taken from SJK ANL0\\n\" % (deltaH)\n        line3 = '!Q(T) from CCSD(T)/CBSby SJK on  ' + date + '\\n'\n    elif tag == 'SJKCIT0':\n        line2 = \"!DHf(0K) = %8.2F [kcal/mol], taken from SJK ANL0\\n\" % (deltaH)\n        line3 = '!Q(T) from CI+QC/cc-pVTZ by SJK on  ' + date + '\\n'\n    elif tag == 'SJKCIQ0':\n        line2 = \"!DHf(0K) = %8.2F [kcal/mol], taken from SJK ANL0\\n\" % (deltaH)\n        line3 = '!Q(T) from CI+QC/cc-pVQZ by SJK on  ' + date + '\\n'\n    elif tag == 'SJKCICBS0':\n        line2 = \"!DHf(0K) = %8.2F [kcal/mol], taken from SJK ANL0\\n\" % (deltaH)\n        line3 = '!Q(T) from CI+QC/cc-pVQZ by SJK on  ' + date + '\\n'\n    elif tag == 'SJKPT2T0':\n        line2 = \"!DHf(0K) = %8.2F [kcal/mol], taken from SJK ANL0\\n\" % (deltaH)\n        line3 = '!Q(T) from CASPT2/cc-pVTZ by SJK on  ' + date + '\\n'\n    elif tag == 'SJKPT2Q0':\n        line2 = \"!DHf(0K) = %8.2F [kcal/mol], taken from SJK ANL0\\n\" % (deltaH)\n        line3 = '!Q(T) from CASPT2/cc-pVQZ by SJK on  ' + date + '\\n'\n    elif tag == 'SJKB1':\n        line2 = \"!DHf(0K) = %8.2F [kcal/mol], taken from SJK ANL1\\n\" % (deltaH)\n        line3 = '!Q(T) from B3LYP/6-311++G(d,p) by CFG on  ' + date + '\\n'\n    elif tag == 'SJKT1':\n        line2 = \"!DHf(0K) = %8.2F [kcal/mol], taken from SJK ANL1\\n\" % (deltaH)\n        line3 = '!Q(T) from CCSD(T)/cc-pVTZ by SJK on  ' + date + '\\n'\n    elif tag == 'SJKQ1':\n        line2 = \"!DHf(0K) = %8.2F [kcal/mol], taken from SJK ANL1\\n\" % (deltaH)\n        line3 = '!Q(T) from CCSD(T)/cc-pVQZ by SJK on  ' + date + '\\n'\n    elif tag == 'SJKCBS1':\n        line2 = \"!DHf(0K) = %8.2F [kcal/mol], taken from SJK ANL1\\n\" % (deltaH)\n        line3 = '!Q(T) from CCSD(T)/CBS by SJK on  ' + date + '\\n'\n    elif tag == 'SJKCBSA1':\n        line2 = \"!DHf(0K) = %8.2F [kcal/mol], taken from SJK ANL1\\n\" % (deltaH)\n        line3 = '!Q(T) from CCSD(T)/CBS + anh by SJK on  ' + date + '\\n'\n    elif tag == 'SJKCIT1':\n        line2 = \"!DHf(0K) = %8.2F [kcal/mol], taken from SJK ANL1\\n\" % (deltaH)\n        line3 = '!Q(T) from CI+QC/cc-pVTZ by SJK on  ' + date + '\\n'\n    elif tag == 'SJKCIQ1':\n        line2 = \"!DHf(0K) = %8.2F [kcal/mol], taken from SJK ANL1\\n\" % (deltaH)\n        line3 = '!Q(T) from CI+QC/cc-pVQZ by SJK on  ' + date + '\\n'\n    elif tag == 'SJKPT2T1':\n        line2 = \"!DHf(0K) = %8.2F [kcal/mol], taken from SJK ANL1\\n\" % (deltaH)\n        line3 = '!Q(T) from CASPT2/cc-pVTZ by SJK on  ' + date + '\\n'\n    elif tag == 'SJKPT2Q1':\n        line2 = \"!DHf(0K) = %8.2F [kcal/mol], taken from SJK ANL1\\n\" % (deltaH)\n        line3 = '!Q(T) from CASPT2/cc-pVQZ by SJK on  ' + date + '\\n'\n    else:\n        line2 = '!{0}.\\n'.format(date)\n        line3 = '!{0}.\\n'.format(tag)\n    return line1 + line2 + line3\n\n\ndef get_coefficients(c97text):\n    \"\"\"\n    Returns a string of 3 lines containing NASA polynomial\n    coefficients in chemkin format\n    *.c97 file:\n    C2H3\n    3 201704 C   2.00H   3.00    0.00    0.00    0.00 0   27.0452200     296391.000\n    100.000   200.000 2  0.0  1.0  0.0  0.0  0.0  0.0  0.0  0.0        10698.000\n    3.587567650D+00 3.894470300D-03 0.000000000D+00 0.000000000D+00 0.000000000D+00\n    0.000000000D+00 0.000000000D+00 0.000000000D+00 3.437879620D+04 6.439970150D+00\n    200.000  1000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        10698.000\n    2.881119522D+00 4.825191250D-03 1.818030931D-05-2.828286454D-08 1.209654946D-11\n    0.000000000D+00 0.000000000D+00 0.000000000D+00 3.446352960D+04 9.703788500D+00\n    1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        10698.000\n    2.984627599D+00 1.078391826D-02-5.158601830D-06 1.200731137D-09-1.103701620D-13\n    0.000000000D+00 0.000000000D+00 0.000000000D+00 3.423078010D+04 7.923373280D+00\n\n        coefficients in chemkin format:\n     2.98462760E+00 1.07839183E-02-5.15860183E-06 1.20073114E-09-1.10370162E-13    2\n     3.42307801E+04 7.92337328E+00 2.88111952E+00 4.82519125E-03 1.81803093E-05    3\n    -2.82828645E-08 1.20965495E-11 3.44635296E+04 9.70378850E+00                   4\n    \"\"\"\n    lines = c97text.splitlines()\n    las = [0.] * 7\n    has = [0.] * 7\n    msg = None\n    if len(lines) > 1:\n        las[0:5] = parse_line16(lines[6][0:80])\n        las[5:7] = parse_line16(lines[7][48:80])\n        has[0:5] = parse_line16(lines[9][0:80])\n        has[5:7] = parse_line16(lines[10][48:80])\n    else:\n        msg = 'pacc has failed'\n    return las, has, msg\n\n\ndef get_coefficients_str(las, has):\n    \"\"\"\n    Returns a string of 3 lines containing NASA polynomial\n    coefficients in chemkin format\n    *.c97 file:\n    C2H3\n    3 201704 C   2.00H   3.00    0.00    0.00    0.00 0   27.0452200     296391.000\n    100.000   200.000 2  0.0  1.0  0.0  0.0  0.0  0.0  0.0  0.0        10698.000\n    3.587567650D+00 3.894470300D-03 0.000000000D+00 0.000000000D+00 0.000000000D+00\n    0.000000000D+00 0.000000000D+00 0.000000000D+00 3.437879620D+04 6.439970150D+00\n    200.000  1000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        10698.000\n    2.881119522D+00 4.825191250D-03 1.818030931D-05-2.828286454D-08 1.209654946D-11\n    0.000000000D+00 0.000000000D+00 0.000000000D+00 3.446352960D+04 9.703788500D+00\n    1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        10698.000\n    2.984627599D+00 1.078391826D-02-5.158601830D-06 1.200731137D-09-1.103701620D-13\n    0.000000000D+00 0.000000000D+00 0.000000000D+00 3.423078010D+04 7.923373280D+00\n\n        coefficients in chemkin format:\n     2.98462760E+00 1.07839183E-02-5.15860183E-06 1.20073114E-09-1.10370162E-13    2\n     3.42307801E+04 7.92337328E+00 2.88111952E+00 4.82519125E-03 1.81803093E-05    3\n    -2.82828645E-08 1.20965495E-11 3.44635296E+04 9.70378850E+00                   4\n    \"\"\"\n    line2 = \"% 15.8E% 15.8E% 15.8E% 15.8E% 15.8E    2\\n\" % (\n        has[0], has[1], has[2], has[3], has[4])\n    line3 = \"% 15.8E% 15.8E% 15.8E% 15.8E% 15.8E    3\\n\" % (\n        has[5], has[6], las[0], las[1], las[2])\n    line4 = \"% 15.8E% 15.8E% 15.8E% 15.8E                   4\\n\" % (\n        las[3], las[4], las[5], las[6])\n    return line2+line3+line4\n\n\ndef convert_chemkin2rmg(ckin):\n    \"\"\"\n! OOCCC(O[O])C_m2      torsscan/m062x/cc-pvtz/gaussian\n! deltaH(0) -32.7035898546 kcal/mol\n! deltaH(298) -39.3632755502 kcal/mol\nC4H9O4                  H   9C   4O   4N   0G   200.00   3000.00  1000.00      1\n 1.57361381E+01 3.29113185E-02-1.59602886E-05 3.77476959E-09-3.52930905E-13    2\n-2.63226479E+04-4.77325306E+01 4.60561015E-01 9.96060317E-02-1.28949962E-04    3\n 9.08860280E-08-2.58936516E-11-2.34008733E+04 2.49356355E+01                   4\n\n     line2 = \"% 15.8E% 15.8E% 15.8E% 15.8E% 15.8E    2\\n\"%(has[0], has[1], has[2], has[3], has[4])\n    line3 = \"% 15.8E% 15.8E% 15.8E% 15.8E% 15.8E    3\\n\"%(has[5], has[6], las[0], las[1], las[2])\n    line4 = \"% 15.8E% 15.8E% 15.8E% 15.8E                   4\\n\"%(las[3], las[4], las[5], las[6])\n    \"\"\"\n    lines = ckin.splitlines()\n    nline = len(lines)\n    has = [0]*7\n    las = [0]*7\n    if nline < 4:\n        logging.error('Bad format for chemkin file at convert_chemkin2rmg')\n    else:\n        lines = lines[-4:]\n        tlow, thigh, tmed = lines[0].split()[6:9]\n        tlow = float(tlow)\n        tmed = float(tmed)\n        thigh = float(thigh)\n        has[0] = float(lines[1][0:15])\n        has[1] = float(lines[1][15:30])\n        has[2] = float(lines[1][30:45])\n        has[3] = float(lines[1][45:60])\n        has[4] = float(lines[1][60:75])\n        has[5] = float(lines[2][0:15])\n        has[6] = float(lines[2][15:30])\n        las[0] = float(lines[2][30:45])\n        las[1] = float(lines[2][45:60])\n        las[2] = float(lines[2][60:75])\n        las[3] = float(lines[2][60:75])\n        las[3] = float(lines[3][0:15])\n        las[4] = float(lines[3][15:30])\n        las[5] = float(lines[3][30:45])\n        las[6] = float(lines[3][45:60])\n    return get_rmg_polynomial(las, has, temps=[tlow, tmed, tmed, thigh])\n\n\ndef get_rmg_polynomial(las, has, temps=[200., 1000., 1000., 3000.]):\n    \"\"\"\n    Return NASA polynomial as a dictionary in RMG format:\n\n    NASA Polynomial, seven or nine coefficients, Tmax and Tmin = valid temperature range\n    polynomials = [{'coeffs':[2.3443,0.00798042,-1.94779e-05,2.0157e-08,-7.37603e-12,-917.924,0.683002], 'Tmin':(200,'K'), 'Tmax':(1000,'K')},\n                      {'coeffs':[2.93283,0.000826598,-1.46401e-07,1.54099e-11,-6.88796e-16,-813.056,-1.02432], 'Tmin':(1000,'K'), 'Tmax':(6000,'K')}]\n                      Tmin = (200,'K')\n                      Tmax = (6000,'K')\n                      NASAPolynomial = {'polynomials':polynomials,'Tmin':Tmin,'Tmax':Tmax}\n    \"\"\"\n    p = [{'coeffs': las, 'Tmin': (temps[0], 'K'), 'Tmax':(temps[1], 'K')},\n         {'coeffs': has, 'Tmin': (temps[2], 'K'), 'Tmax':(temps[3], 'K')}]\n\n    return {'polynomials': p, 'Tmin': (min(temps), 'K'), 'Tmax': (max(temps), 'K')}\n\n\ndef get_name_from_messpf(inputfile='pf.inp'):\n    \"\"\"\n    Returns species formula by parsing messpf input file.\n    input file:\n    Temperature(step[K],size)        100.   30\n    RelativeTemperatureIncrement            0.001\n    Species   C2H3\n    !      RRHO\n    Geometry[angstrom]     5   ! CCSD(T)/cc-pVQZ\n    C          0.0000000000        0.0229607853       -0.6194779279\n    C          0.0000000000       -0.0846208019        0.6897727967\n    H          0.0000000000        0.9977802761       -1.1068370147\n    H          0.0000000000       -0.8465433753       -1.2673164024\n    H          0.0000000000        0.5835275291        1.5364927734\n    Core     RigidRotor\n    SymmetryFactor       1\n    End\n    Frequencies[1/cm]      9   ! CCSD(T)/CBS; anh\n    692    796    894    1019    1353    1580    2895    3023    3114\n    ZeroEnergy[kcal/mol]            -34.41  ! ANL1\n    ElectronicLevels[1/cm]        1\n    0   2\n    End\n    \"\"\"\n    with open(inputfile, 'r') as f:\n        lines = f.readlines()\n    for line in lines:\n        if 'Species' in line:\n            name = line.split()[-1]\n    return name\n\n\ndef get_chemkin_str(deltaH, tag, formula, filename):\n    \"\"\"\n    Given formula string, tag string, deltaH float and a filename string,\n    returns a string for NASA polynomials in chemkin format:\n    !\n    !DHf(0K) =    25.00 [kcal/mol], taken from SJK ANL0\n    !Q(T) from CI+QC/cc-pVTZ by SJK on  18Apr2017\n    C2H3                    H   3C   2O   0N   0G   200.00   3000.00  1000.00      1\n     2.98462760E+00 1.07839183E-02-5.15860183E-06 1.20073114E-09-1.10370162E-13    2\n     3.42307801E+04 7.92337328E+00 2.88111952E+00 4.82519125E-03 1.81803093E-05    3\n    -2.82828645E-08 1.20965495E-11 3.44635296E+04 9.70378850E+00                   4\n    \"\"\"\n    lines1to3 = get_comment_lines(tag, deltaH)\n    nH = get_stoichometry(formula, 'H')\n    nC = get_stoichometry(formula, 'C')\n    nN = get_stoichometry(formula, 'N')\n    nO = get_stoichometry(formula, 'O')\n    line4 = \"%s        H%4dC%4dO%4dN%4dG%9.2F%10.2F%9.2F      1\\n\" % (\n        formula.ljust(16)[0:16], nH, nC, nO, nN, 200.0, 3000.0, 1000.0)\n    lines5to7 = get_coefficients_str(formula+'.c97')\n\n    return lines1to3 + line4 + lines5to7\n\n\ndef write_chemkin_file(slabel, qlabel, hof, hof298, formula, mid, las, has, filename):\n    \"\"\"\n    Given formula string, tag string, deltaH float and a filename string,\n    writes a file containing NASA polynomials in chemkin format:\n    !\n    !DHf(0K) =    25.00 [kcal/mol], taken from SJK ANL0\n    !Q(T) from CI+QC/cc-pVTZ by SJK on  18Apr2017\n    C2H3                    H   3C   2O   0N   0G   200.00   3000.00  1000.00      1\n     2.98462760E+00 1.07839183E-02-5.15860183E-06 1.20073114E-09-1.10370162E-13    2\n     3.42307801E+04 7.92337328E+00 2.88111952E+00 4.82519125E-03 1.81803093E-05    3\n    -2.82828645E-08 1.20965495E-11 3.44635296E+04 9.70378850E+00                   4\n    \"\"\"\n    comments = '! {} \\t {}\\n'.format(slabel, qlabel)\n    comments += '! deltaH(0) {:.2f} kcal/mol\\n'.format(hof)\n    comments += '! deltaH(298) {:.2f} kcal/mol\\n'.format(hof298)\n    nH = get_stoichometry(formula, 'H')\n    nC = get_stoichometry(formula, 'C')\n    nN = get_stoichometry(formula, 'N')\n    nO = get_stoichometry(formula, 'O')\n    cformula = '{}_{}'.format(formula, str(mid))\n    line4 = \"%s        H%4dC%4dO%4dN%4dG%9.2F%10.2F%9.2F      1\\n\" % (\n        cformula.ljust(16)[0:16], nH, nC, nO, nN, 200.0, 3000.0, 1000.0)\n    lines5to7 = get_coefficients_str(las, has)\n    s = comments + line4 + lines5to7\n    io.write_file(s, filename)\n    return s\n\n\ndef get_thermp_input(formula, deltaH, enthalpyT=0., breakT=1000.):\n    \"\"\"\n    Returns thermp input text as a string for a given formula string and deltaH (float)\n    e.g.\n    1, 0\n    Nwell, Nprod\n    30\n    nt\n    71.82    0.                          //enthalpy at specified T (in kcal/mol), with T = 0 or 298 K\n    C2H3                                    //name of species\n    C  2                                    //composition in terms of\n    H  3                                    //element_name  element_count\n    **\n    1000.                                   //temperature to break the fit\n    \"\"\"\n    nH = get_stoichometry(formula, 'H')\n    nC = get_stoichometry(formula, 'C')\n    nN = get_stoichometry(formula, 'N')\n    nO = get_stoichometry(formula, 'O')\n    tmp = '1, 0\\n'\n    tmp += 'Nwell, Nprod\\n'\n    tmp += '30\\n'\n    tmp += 'nt\\n'\n    tmp += '{0} {1}\\n'.format(deltaH, enthalpyT)\n    tmp += '{0}\\n'.format(formula)\n    if nC > 0:\n        tmp += 'C {0}\\n'.format(nC)\n    if nH > 0:\n        tmp += 'H {0}\\n'.format(nH)\n    if nO > 0:\n        tmp += 'O {0}\\n'.format(nO)\n    if nN > 0:\n        tmp += 'N {0}\\n'.format(nN)\n    tmp += '**\\n'\n    tmp += '{0}'.format(breakT)\n    return tmp\n\n\ndef write_thermp_input(formula, deltaH, enthalpyT=0., breakT=1000., filename='thermp.dat'):\n    \"\"\"\n    Write thermp input file with given formula string, deltaH float\n    e.g.\n    1, 0\n    Nwell, Nprod\n    30\n    nt\n    71.82    0.                          //enthalpy at specified T (in kcal/mol), with T = 0 or 298 K\n    C2H3                                    //name of species\n    C  2                                    //composition in terms of\n    H  3                                    //element_name  element_count\n    **\n    1000.                                   //temperature to break the fit\n    \"\"\"\n    nH = get_stoichometry(formula, 'H')\n    nC = get_stoichometry(formula, 'C')\n    nN = get_stoichometry(formula, 'N')\n    nO = get_stoichometry(formula, 'O')\n    with open(filename, 'w') as f:\n        f.write('1, 0\\n')\n        f.write('Nwell, Nprod\\n')\n        f.write('30\\n')\n        f.write('nt\\n')\n        f.write('{0} {1}\\n'.format(deltaH, enthalpyT))\n        f.write('{0}\\n'.format(formula))\n        if nC > 0:\n            f.write('C {0}\\n'.format(nC))\n        if nH > 0:\n            f.write('H {0}\\n'.format(nH))\n        if nO > 0:\n            f.write('O {0}\\n'.format(nO))\n        if nN > 0:\n            f.write('N {0}\\n'.format(nN))\n        f.write('**\\n')\n        f.write('{0}'.format(breakT))\n    if io.check_file(filename, 1):\n        msg = 'Thermp input file \"{0}\" written.\\n'.format(filename)\n    else:\n        msg = 'Failed writing thermp input file \"{0}\".\\n'.format(filename)\n    return msg\n\n\n# def get_pf_input(mol,method,xyz,freqs,zpe=0., xmat=[], hindered=None):\n#     \"\"\"\n#     Write input file for mess partition function program\n#     Temperature(step[K],size)        100.   30\n#     RelativeTemperatureIncrement            0.001\n#     Species CH4\n#     RRHO\n#     Geometry[angstrom] 5 !pm3\n#     C -0.0000 0.0000 0.0000\n#     H 1.0870 0.0000 0.0000\n#     H -0.3623 1.0249 0.0000\n#     H -0.3623 -0.5124 0.8876\n#     H -0.3623 -0.5124 -0.8876\n#     Core RigidRotor\n#     SymmetryFactor 1\n#     End\n#     Frequencies[1/cm] 9 !pm3\n#     1362.16 1362.39 1362.48 1451.03 1451.06 3207.47 3207.48 3207.50 3311.01\n#     ZeroEnergy[kcal/mol] 28.481 ! pm3\n#     ElectronicLevels[1/cm]  1\n#     0 1\n#     End\n#     \"\"\"\n#     optmethod  = method\n#     freqmethod = method\n#     tagmethod  = method\n#     sym = 1\n#     natom = len(mol.atoms)\n#     formula = mol.formula\n#     multiplicity = mol.spin\n#     inp  = 'Temperature(step[K],size)        100.   30\\n'\n#     inp += 'RelativeTemperatureIncrement            0.001\\n'\n#     inp += 'Species {0}\\n'.format(formula)\n#     inp += 'RRHO\\n'\n#     inp += 'Geometry[angstrom] {0} !{1}\\n'.format(natom,optmethod)\n#     inp += ''.join(xyz.splitlines(True)[2:])\n#     inp += '\\nCore RigidRotor\\n'\n#     inp += 'SymmetryFactor {0}\\n'.format(sym)\n#     inp += 'End\\n'\n#     if hindered:\n#         inp += hindered\n#     inp += 'Frequencies[1/cm] {0} !{1}\\n'.format(len(freqs),freqmethod)\n#     inp += ' '.join(freqs) + '\\n'\n#     if len(xmat) > 0:\n#         inp += ' Anharmonicities[1/cm]\\n'\n#         for i in range( len(xmat)):\n#             for j in range(i+1):\n#                 inp += '  ' + str(i) + ' ' + str(j) + ' ' + str(xmat[i,j]) + '\\n'\n#         inp += ' End\\n'\n#     inp += 'ZeroEnergy[kcal/mol] {0} ! {1}\\n'.format(zpe,tagmethod)\n#     inp += 'ElectronicLevels[1/cm]  1\\n'\n#     inp += '0 {0}\\n'.format(multiplicity)\n#     inp += 'End\\n'\n#     return inp\n\n\ndef get_messpf_input(mol, parameters):\n    \"\"\"\n    TODO: Anharmonic frequencies\n    Write input file for mess partition function program\n    AtomDistanceMin[angstrom] 0.6\n    Temperature(step[K],size)        100.   30\n    RelativeTemperatureIncrement            0.001\n    Species CH4\n    RRHO\n    Geometry[angstrom] 5 !pm3\n    C -0.0000 0.0000 0.0000\n    H 1.0870 0.0000 0.0000\n    H -0.3623 1.0249 0.0000\n    H -0.3623 -0.5124 0.8876\n    H -0.3623 -0.5124 -0.8876\n    Core RigidRotor\n    SymmetryFactor 1\n    End\n    Frequencies[1/cm] 9 !pm3\n    1362.16 1362.39 1362.48 1451.03 1451.06 3207.47 3207.48 3207.50 3311.01\n    ZeroEnergy[kcal/mol] 28.481 ! pm3\n    ElectronicLevels[1/cm]  1\n    0 1\n    End\n\n    For a single atom:\n\n    AtomDistanceMin[angstrom] 0.6\n    Temperature(step[K],size)        100.   30\n    RelativeTemperatureIncrement            0.001\n    Species H\n      Atom\n         Mass[amu]     1\n\n         ElectronicLevels[1/cm]     1\n            0    2\n       End\n    \"\"\"\n    from . import unittools as ut\n    from . import anharm\n    natom = parameters['natom']\n    label = parameters['qlabel']\n    results = parameters['results']\n    multiplicity = parameters['mult']\n    xyz = results['xyz']\n    sym = results['sym']\n    natom = len(mol.atoms)\n    formula = mol.formula\n    #multiplicity = mol.spin\n    freqs = []\n    xmat = []\n    rotconsts = []\n    posfreqs = []\n    zpe = 0\n    rotdists = ''\n    scale = 0\n    scaletype = None\n    vibrots = None\n    emax = 500  # kcal/mol, not sure\n    if 'azpve' in results:\n        zpve = results['azpve']\n    elif 'zpve' in results:\n        zpve = results['zpve']\n    else:\n        zpve = 0.\n    if 'pfreqs' in results:\n        freqs = results['pfreqs']\n    elif 'freqs' in results:\n        freqs = results['freqs']\n        if len(freqs) > 0:\n            for freq in freqs:\n                if float(freq) > 0:\n                    posfreqs.append(freq)\n            if len(posfreqs) < len(freqs):\n                logging.warning('Imaginary frequencies are ignored')\n            results['freqs'] = posfreqs\n            freqs = posfreqs\n    if 'rotconsts' in results:\n        rotconsts = results['rotconsts']\n    if 'vibrots' in results:\n        vibrots = results['vibrots']\n    else:\n        vibrots = None\n    if 'rotdists' in results:\n        rotdists = results['rotdists']\n    if 'xmat' in results:\n        xmat = np.asarray(results['xmat'])\n        if 'pfreqs' in results:\n            freqs, fill, xmat, fill2, fill3, vibrots = anharm.main(\n                results, vibrots)\n        elif 'afreqs' in results:\n            freqs = results['afreqs']\n        #xmat = anharm.mess_x(xmat)\n    if 'scale' in parameters:\n        scale = parameters['scale']\n    if 'scaletype' in parameters:\n        scaletype = parameters['scaletype']\n\n    coreIsMd = False\n    if 'hindered potential' in results:\n        if 'Core' in results['hindered potential']:\n            coreIsMd = True\n\n    # HEADER\n    inp = 'AtomDistanceMin[angstrom] 0.6\\n'\n    inp += 'Temperature(step[K],size)        100.   30\\n'\n    inp += 'RelativeTemperatureIncrement            0.001\\n'\n    # BEGIN INPUT\n    inp += 'Species {0}\\n'.format(formula)\n    if natom == 1:\n        inp += 'Atom\\n'\n        inp += 'Mass[amu] {}\\n'.format(ut.atommasses[formula])\n        inp += 'End\\n'\n    else:\n        # BEGIN RRHO\n        inp += 'RRHO\\n'\n        inp += '  Geometry[angstrom] {0} !{1}\\n\\t  '.format(natom, label)\n        inp += '\\t  '.join(xyz.splitlines(True)[2:])\n        inp += '\\n  ZeroEnergy[kcal/mol] {0} ! {1}\\n'.format(zpve, label)\n        inp += '  ElectronicLevels[1/cm]  1\\n'\n        inp += '     0 {0}\\n'.format(multiplicity)\n\n        # BEGIN CORE\n        coreline = '   Core RigidRotor\\n'\n        coreline += '      ZeroPointEnergy[1/cm] {}\\n'.format(zpe)\n        hindlines = ''\n        if 'hindered potential' in results:\n            if coreIsMd:\n                coreline = '  Core MultiRotor\\n'\n                hindlines = '     {}'.format('     '.join(\n                    results['hindered potential'].splitlines(True)[3:]))\n            else:\n                hindlines = '   End\\n'\n                hindpot = results['hindered potential']\n                if scale and scaletype:\n                    if scaletype.startswith('h'):\n                        hindpot = hindpot.split('Potential[kcal/mol]')\n                        if len(hindpot) > 1:\n                            for h, pot in enumerate(hindpot[1:]):\n                                pot, end = pot.split('End')\n                                num = pot.split()[0]\n                                pot = pot.split()[1:]\n                                newpot = ' {}\\n    '.format(num)\n                                for val in pot:\n                                    newpot += '   {:.3f}'.format(\n                                        float(scale) * float(val))\n                                hindpot[h+1] = newpot + '\\n End' + end\n                        hindpot = 'Potential[kcal/mol]'.join(hindpot)\n                hindlines += '  {}'.format('  '.join(hindpot.splitlines(True)))\n        inp += coreline\n        inp += '      InterpolationEnergyMax[kcal/mol] {}\\n'.format(emax)\n        inp += '      SymmetryFactor {0}\\n'.format(sym)\n        if coreIsMd:\n            inp += hindlines  # END RRHO\n        # freqs\n        if len(freqs) > 0:\n            inp += '      Frequencies[1/cm] {0} !{1}\\n'.format(\n                len(freqs), label)\n            inp += '      ' + ' '.join([str(x) for x in freqs]) + '\\n'\n        if scaletype and scale:\n            if 'f' in scaletype:\n                inp += '      FrequencyScalingFactor {:.4f}\\n'.format(scale)\n        # anharmonics\n        if len(xmat) > 0:\n            inp += '      Anharmonicities[1/cm]\\n'\n            for i in range(len(xmat)):\n                inp += '\\t\\t' + ' '.join([str(xmat[i][j])\n                                         for j in range(i+1)]) + '\\n'\n        if not coreIsMd:\n            if 'norot' in parameters:\n                if not parameters['norot']:\n                    # if len(rotconsts) > 0:\n                    #    inp += '      RotationalConstants[1/cm] '\n                    #    inp += ' '.join(rotconsts) + '\\n'\n                    if vibrots:\n                        vibrots = vibrots.splitlines(True)\n                        if len(freqs) == len(vibrots):\n                            inp += '      RovibrationalCouplings[1/cm]\\n'\n                            inp += '\\t   ' + '\\t   '.join(vibrots) + '\\n'\n                        else:\n                            logging.warning(\n                                \"Rotational Couplings length does not match freqs -- removed from pf.inp\")\n                    if len(rotdists) > 0:\n                        inp += '      RotationalDistortion[1/cm]\\n'\n                        inp += '\\t   ' + \\\n                            '\\t   '.join(rotdists.splitlines(True)) + '\\n'\n                        inp += '      End\\n'  # END CORE\n            inp += hindlines  # END RRHO\n        if not 'hindered potential' in results:\n            inp += '   End\\n'\n        inp += 'End\\n'  # END CORE\n    return inp\n\n\ndef run_pf(messpf='messpf', inputfile='pf.inp'):\n    \"\"\"\n    Runs mess to generate partition function\n    Requires an input file,i.e. pf.inp.\n    '/tcghome/ygeorgi/fock/crossrate/bin/partition_function'\n    Output is input_prefix + \".log\"\n    e.g.\n    Temperature(step[K],size)        100.   30\n    RelativeTemperatureIncrement            0.001\n    Species   C2H3\n    RRHO\n    Geometry[angstrom]     5   ! CCSD(T)/cc-pVQZ\n    C          0.0000000000        0.0229607853       -0.6194779279\n    C          0.0000000000       -0.0846208019        0.6897727967\n    H          0.0000000000        0.9977802761       -1.1068370147\n    H          0.0000000000       -0.8465433753       -1.2673164024\n    H          0.0000000000        0.5835275291        1.5364927734\n    Core     RigidRotor\n    SymmetryFactor       1\n    End\n    Frequencies[1/cm]      9   ! CCSD(T)/CBS; anh\n    692    796    894    1019    1353    1580    2895    3023    3114\n    ZeroEnergy[kcal/mol]            -34.41  ! ANL1\n    ElectronicLevels[1/cm]        1\n    0   2\n    End\n    \"\"\"\n    import subprocess\n    from . import iotools as io\n    msg = ''\n    if io.check_exe(messpf):\n        if io.check_file(inputfile, 1):\n            if io.check_exe(messpf):\n                subprocess.call([messpf, inputfile])\n                if io.check_file('pf.log', 1):\n                    msg += '{0} generated by mess.\\n'.format(inputfile)\n            else:\n                msg += 'Mess executable not found {0}\\n'.format(messpf)\n                return msg\n        else:\n            msg += \"{0} input file does not exist.\\n\".format(inputfile)\n\n    else:\n        msg += \"{0} mess partitition function executable does not exist.\\n\".format(\n            messpf)\n    return msg\n\n\ndef run_thermp(thermpinput, thermpfile='thermp.dat', pffile='pf.out', thermpexe='thermp'):\n    \"\"\"\n    Runs thermp.exe\n    Requires pffile and thermpfile to be present\n    linus\n    /tcghome/sjk/gen/aux_me/therm/thermp.exe\n    \"\"\"\n    from . import iotools as io\n    msg = ''\n    io.write_file(thermpinput, thermpfile)\n    if not io.check_file(thermpfile, 1):\n        return \"{0} file not found.\\n\".format(thermpfile)\n    pfdat = pffile.replace('out', 'dat')\n    if io.check_file(pffile):\n        io.mv(pffile, pfdat)\n    if io.check_file(pfdat, 1):\n        msg += io.execute(thermpexe)\n    else:\n        msg += \"{0} file not found.\\n\".format(pffile)\n    return msg\n\n\ndef run_pac99(formula, pac99='pac99'):\n    \"\"\"\n    Run pac99 for a given species name (formula)\n    https://www.grc.nasa.gov/WWW/CEAWeb/readme_pac99.htm\n    requires formula+'i97' and new.groups files\n    TODO: Maybe add delete empty files\n    linus\n    pac99='/tcghome/sjk/gen/aux_me/therm/pac99.x'\n    \"\"\"\n    from subprocess import Popen, PIPE\n    from . import iotools as io\n    msg = ''\n    c97file = formula + '.c97'\n    i97file = formula + '.i97'\n    o97file = formula + '.o97'\n    if io.check_exe(pac99):\n        if io.check_file(i97file):\n            if io.check_file('new.groups'):\n                if io.check_exe(pac99):\n                    p = Popen(pac99, stdin=PIPE)\n                    p.communicate(formula)\n                else:\n                    msg += 'pac99 not found.\\n'\n                    return msg\n            else:\n                msg += 'new.groups file is required to run pac99.\\n'\n        else:\n            msg += '{0} file not found.\\n'.format(i97file)\n\n    else:\n        msg += '{0} file not found.\\n'.format(pac99)\n    if io.check_file(c97file) and io.check_file(o97file):\n        msg += \"{0} {1} files are written.\\n\".format(c97file, o97file)\n    return msg\n\n\n# def write_chemkin_polynomial(mol, xyz, freqs, deltaH,parameters, xmat=[], zpe=0.):\n#     \"\"\"\n#     A driver to perform all operations to write NASA polynomial in\n#     chemkin format. Assumes quantum chemistry calculation is performed.\n#     \"\"\"\n#     messpfinput = 'pf.inp'\n#     messpfoutput = 'pf.log'\n#     name = mol.formula\n#     tag = parameters['qcmethod']\n#     inp = get_pf_input(mol, tag, xyz, freqs, xmat=xmat, zpe=0.)\n#     io.write_file(inp, messpfinput)\n#     msg = 'Running {0} to generate partition function.\\n'.format(parameters['messpf'])\n#     msg += io.execute([parameters['messpf'],messpfinput])\n#     msg += 'Running thermp .\\n'\n#     inp = get_thermp_input(mol.formula, deltaH)\n#     msg = run_thermp(inp, 'thermp.dat', messpfoutput, parameters['thermp'])\n#     msg += 'Running pac99.\\n'\n#     msg += run_pac99(name)\n#     msg += 'Converting to chemkin format.\\n'\n#     chemkinfile = name + '.ckin'\n#     msg += 'Writing chemkin file {0}.\\n'.format(chemkinfile)\n#     try:\n#         msg += write_chemkin_file(deltaH, tag, name, chemkinfile)\n#     except:\n#         \"Failed to write polynomials\"\n#     return msg\n\n\ndef write_chemkin_polynomial(mol, parameters):\n    \"\"\"\n    A driver to perform all operations to write NASA polynomial in\n    chemkin format. Assumes quantum chemistry calculation is performed.\n    \"\"\"\n    messpfinput = 'pf.inp'\n#   messpfoutput = 'pf.log'\n#    messpfoutput = 'pf.out'\n    messpfoutput = 'pf.out'\n    formula = mol.formula\n    qlabel = parameters['qlabel']\n    slabel = parameters['slabel']\n    mid = parameters['mol_index']\n    hof = parameters['results']['deltaH0']\n    if parameters['skippf']:\n        logging.debug('Skipping pf generation...')\n    else:\n        inp = get_messpf_input(mol, parameters)\n        io.write_file(inp, messpfinput)\n        logging.debug('Running {0} to generate partition function...'.format(\n            parameters['messpf']))\n        msg = io.execute([parameters['messpf'], messpfinput])\n        logging.debug(msg)\n    logging.debug('Running thermp...')\n    inp = get_thermp_input(mol.formula, hof)\n    msg = run_thermp(inp, 'thermp.dat', messpfoutput, parameters['thermp'])\n    logging.debug(msg)\n    logging.debug('Running pac99...')\n    msg = run_pac99(formula)\n    hof298 = 0\n    chemkininput = ''\n    rmgpoly = {}\n    logging.debug(msg)\n    if io.check_file('thermp.out'):\n        lines = io.read_file('thermp.out')\n        hof298 = pa.get_298(lines)\n        logging.info('delHf(298) = {0} kcal/mol'.format(hof298))\n    else:\n        logging.error('Failed to create thermp.out')\n    c97file = formula + '.c97'\n    if io.check_file(c97file):\n        c97text = io.read_file(c97file)\n        las, has, msg = get_coefficients(c97text)\n        if msg:\n            logging.info(msg)\n        logging.debug('Converting to chemkin format.')\n        chemkinfile = formula + '.ckin'\n        logging.debug('Writing chemkin file {0}.\\n'.format(chemkinfile))\n        try:\n            chemkininput = write_chemkin_file(\n                slabel, qlabel, hof, hof298, formula, mid, las, has, chemkinfile)\n            rmgpoly = get_rmg_polynomial(las, has)\n        except:\n            logging.error(\"Failed to write chemkin polynomials\")\n    else:\n        logging.error('Cannot find {}.'.format(c97file))\n    return hof298, chemkininput, rmgpoly\n\n\ndef get_heat_capacity(rmgpoly, T):\n    \"\"\"\n    rmgpoly is a dictionary in the following format\n    {u'Tmax': [3000.0, u'K'],\n     u'Tmin': [200.0, u'K'],\n     u'polynomials': [{u'Tmax': [1000.0, u'K'],\n                       u'Tmin': [200.0, u'K'],\n                       u'coeffs': [3.47200416,\n                               0.0002877246707,\n                               -1.014581759e-06,\n                               1.344086535e-09,\n                               -4.50222436e-13,\n                               2548.182033,\n                               1.600701434]},\n                  {u'Tmax': [3000.0, u'K'],\n                   u'Tmin': [1000.0, u'K'],\n                   u'coeffs': [3.25257139,\n                               0.000111709217,\n                               4.54124982e-07,\n                               -2.061316072e-10,\n                               2.673718745e-14,\n                               2658.216226,\n                               2.95565086]}]}\n\n    Formulas for calculation:\n    Cp/R = a1 + a2 T + a3 T^2 + a4 T^3 + a5 T^4\n    H/RT = a1 + a2 T /2 + a3 T^2 /3 + a4 T^3 /4 + a5 T^4 /5 + a6/T\n    S/R  = a1 lnT + a2 T + a3 T^2 /2 + a4 T^3 /3 + a5 T^4 /4 + a7\n    where a1, a2, a3, a4, a5, a6, and a7 are the numerical coefficients\n    supplied in NASA thermodynamic files.\n    The first 7 numbers starting on the second line of each species entry\n    (five of the second line and the first two of the third line) are the\n    seven coefficients (a1 through a7, respectively) for the high-temperature\n    range (above 1000 K, the upper boundary is specified on the first line of\n    the species entry). The following seven numbers are the coefficients\n    (a1 through a7, respectively) for the low-temperature range\n    (below 1000 K, the lower boundary is specified on the first line of the species entry).\n    H in the above equation is defined as\n    H(T) = Delta Hf(298) + [ H(T) - H(298) ]\n    so that, in general, H(T) is not equal to\n    Delta Hf(T) and one needs to have the data for the reference elements to calculate Delta Hf(T).\n    \"\"\"\n    alist = []\n    cp = 0.\n    for poly in rmgpoly['polynomials']:\n        Tmax = poly['Tmax'][0]\n        Tmin = poly['Tmin'][0]\n        if T >= Tmin and T <= Tmax:\n            alist = poly['coeffs']\n    if len(alist) > 4:\n        cp = alist[0] + alist[1]*T + alist[2] * \\\n            T**2 + alist[3]*T**3 + alist[4]*T**4\n        cp = cp * ut.Rinkcal\n    else:\n        logging.error['{} K is outside the temperature range of the given NASA polynomials [{},{}]'.format\n                      (T, rmgpoly['Tmin'][0], rmgpoly['Tmax'][0])]\n    return cp\n\n\ndef get_entropy(rmgpoly, T):\n    \"\"\"\n    rmgpoly is a dictionary in the following format\n    {u'Tmax': [3000.0, u'K'],\n     u'Tmin': [200.0, u'K'],\n     u'polynomials': [{u'Tmax': [1000.0, u'K'],\n                       u'Tmin': [200.0, u'K'],\n                       u'coeffs': [3.47200416,\n                               0.0002877246707,\n                               -1.014581759e-06,\n                               1.344086535e-09,\n                               -4.50222436e-13,\n                               2548.182033,\n                               1.600701434]},\n                  {u'Tmax': [3000.0, u'K'],\n                   u'Tmin': [1000.0, u'K'],\n                   u'coeffs': [3.25257139,\n                               0.000111709217,\n                               4.54124982e-07,\n                               -2.061316072e-10,\n                               2.673718745e-14,\n                               2658.216226,\n                               2.95565086]}]}\n\n    Formulas for calculation:\n    Cp/R = a1 + a2 T + a3 T^2 + a4 T^3 + a5 T^4\n    H/RT = a1 + a2 T /2 + a3 T^2 /3 + a4 T^3 /4 + a5 T^4 /5 + a6/T\n    S/R  = a1 lnT + a2 T + a3 T^2 /2 + a4 T^3 /3 + a5 T^4 /4 + a7\n    where a1, a2, a3, a4, a5, a6, and a7 are the numerical coefficients\n    supplied in NASA thermodynamic files.\n    The first 7 numbers starting on the second line of each species entry\n    (five of the second line and the first two of the third line) are the\n    seven coefficients (a1 through a7, respectively) for the high-temperature\n    range (above 1000 K, the upper boundary is specified on the first line of\n    the species entry). The following seven numbers are the coefficients\n    (a1 through a7, respectively) for the low-temperature range\n    (below 1000 K, the lower boundary is specified on the first line of the species entry).\n    H in the above equation is defined as\n    H(T) = Delta Hf(298) + [ H(T) - H(298) ]\n    so that, in general, H(T) is not equal to\n    Delta Hf(T) and one needs to have the data for the reference elements to calculate Delta Hf(T).\n    \"\"\"\n    alist = []\n    S = 0.\n    for poly in rmgpoly['polynomials']:\n        Tmax = poly['Tmax'][0]\n        Tmin = poly['Tmin'][0]\n        if T >= Tmin and T <= Tmax:\n            alist = poly['coeffs']\n    if len(alist) > 6:\n        S = alist[0] * math.log(T) + alist[1]*T + alist[2] * \\\n            T**2/2. + alist[3]*T**3/3. + alist[4]*T**4/4 + alist[6]\n        S = S * ut.Rinkcal\n    else:\n        logging.error['{} K is outside the temperature range of the given NASA polynomials [{},{}]'.format\n                      (T, rmgpoly['Tmin'][0], rmgpoly['Tmax'][0])]\n    return S\n\n\ndef get_enthalpy(rmgpoly, T):\n    \"\"\"\n    rmgpoly is a dictionary in the following format\n    {u'Tmax': [3000.0, u'K'],\n     u'Tmin': [200.0, u'K'],\n     u'polynomials': [{u'Tmax': [1000.0, u'K'],\n                       u'Tmin': [200.0, u'K'],\n                       u'coeffs': [3.47200416,\n                               0.0002877246707,\n                               -1.014581759e-06,\n                               1.344086535e-09,\n                               -4.50222436e-13,\n                               2548.182033,\n                               1.600701434]},\n                  {u'Tmax': [3000.0, u'K'],\n                   u'Tmin': [1000.0, u'K'],\n                   u'coeffs': [3.25257139,\n                               0.000111709217,\n                               4.54124982e-07,\n                               -2.061316072e-10,\n                               2.673718745e-14,\n                               2658.216226,\n                               2.95565086]}]}\n\n    Formulas for calculation:\n    H/RT = a1 + a2 T /2 + a3 T^2 /3 + a4 T^3 /4 + a5 T^4 /5 + a6/T\n    where a1, a2, a3, a4, a5, a6, and a7 are the numerical coefficients\n    supplied in NASA thermodynamic files.\n    H in the above equation is defined as\n    H(T) = Delta Hf(298) + [ H(T) - H(298) ]\n    so that, in general, H(T) is not equal to\n    Delta Hf(T) and one needs to have the data for the reference elements to calculate Delta Hf(T).\n    \"\"\"\n    alist = []\n    H = 0.\n    for poly in rmgpoly['polynomials']:\n        Tmax = poly['Tmax'][0]\n        Tmin = poly['Tmin'][0]\n        if T >= Tmin and T <= Tmax:\n            alist = poly['coeffs']\n    if len(alist) > 6:\n        H = alist[0] + alist[1]*T/2 + alist[2]*T**2/3. + \\\n            alist[3]*T**3/4. + alist[4]*T**4/5 + alist[5]/T\n        H = H * ut.Rinkcal * T / 1000.\n    else:\n        logging.error['{} K is outside the temperature range of the given NASA polynomials [{},{}]'.format\n                      (T, rmgpoly['Tmin'][0], rmgpoly['Tmax'][0])]\n    return H\n\n\ndef get_hindered_potential(s, report=False):\n    \"\"\"\n Rotor                             Hindered\n Group    4   5   6   7   8   9  10  11  12  13  14  15  16  17\n Axis             2           1\n Symmetry            1\n Potential[kcal/mol]           12\n    0.00    1.52    2.20    2.14    1.83    1.58    2.03    3.78    6.35    7.46    5.81    1.99\n End\n Rotor                             Hindered\n Group    5   6   7   8   9  10  11  12  13  14  15  16  17\n Axis             4           2\n Symmetry            1\n Potential[kcal/mol]           12\n    0.00    3.72    8.34    7.05    3.27    2.22    4.05    3.24    1.90    3.35    5.10    3.42\n    \"\"\"\n    s = s.lower()\n    lines = s.splitlines()\n    pot = []\n    for line in lines:\n        if line.islower():  # Check if line has any letter\n            pass\n        elif line.strip():\n            items = line.split()\n            newpot = [float(x) for x in items]\n            pot.append(newpot)\n            if report:\n                logging.info(line)\n            if any(p < 0. for p in newpot):\n                logging.error('Negative hindered potential detected')\n                if not report:\n                    break\n    return pot\n\n\ndef get_new_groups():\n    s = \"\"\"\nH2SO4\n 2 J 9/77 H   2.00S   1.00O   4.00    0.00    0.00 0     98.07948    -735148.376\n    300.000  1000.000 5  0.0  1.0  2.0  3.0  4.0  5.0  0.0  0.0\n  1.07256800D+00  4.37692260D-02 -5.53332430D-05  3.55182530D-08 -9.06773580D-12\n                                                 -9.02597580D+04  1.89395820D+01\n   1000.000  5000.000 5  0.0  1.0  2.0  3.0  4.0  5.0  0.0  0.0\n  1.08895320D+01  7.50041780D-03 -2.92104780D-06  5.25955130D-10 -3.57894150D-14\n                                                 -9.24713640D+04 -2.94047820D+01\nH2S\n 2 J 6/77 H   2.00S   1.00    0.00    0.00    0.00 0     34.08188     -20502.254\n    300.000  1000.000 5  0.0  1.0  2.0  3.0  4.0  5.0  0.0  0.0\n  3.93234760D+00 -5.02609050D-04  4.59284730D-06 -3.18072140D-09  6.64975610D-13\n                                                 -3.65053590D+03  2.31579050D+00\n   1000.000  5000.000 5  0.0  1.0  2.0  3.0  4.0  5.0  0.0  0.0\n  2.74521990D+00  4.04346070D-03 -1.53845100D-06  2.75202490D-10 -1.85920950D-14\n                                                 -3.41994440D+03  8.05467450D+00\nSH\n 2 J 6/77 S   1.00H   1.00    0.00    0.00    0.00 0     33.07394     139332.329\n    300.000  1000.000 5  0.0  1.0  2.0  3.0  4.0  5.0  0.0  0.0\n  4.44203220D+00 -2.43591970D-03  1.90645760D-06  9.91666300D-10 -9.57407620D-13\n                                                  1.55232580D+04 -1.14449035D+00\n   1000.000  5000.000 5  0.0  1.0  2.0  3.0  4.0  5.0  0.0  0.0\n  3.00145370D+00  1.33949570D-03 -4.67896630D-07  7.88040150D-11 -5.02804530D-15\n                                                  1.59053200D+04  6.28462715D+00\nSO3\n 2 J 9/65 S   1.00O   3.00    0.00    0.00    0.00 0     80.06420    -395752.673\n    300.000  1000.000 5  0.0  1.0  2.0  3.0  4.0  5.0  0.0  0.0\n  2.57803850D+00  1.45563350D-02 -9.17641730D-06 -7.92030220D-10  1.97094730D-12\n                                                 -4.89317530D+04  1.22651384D+01\n   1000.000  5000.000 5  0.0  1.0  2.0  3.0  4.0  5.0  0.0  0.0\n  7.07573760D+00  3.17633870D-03 -1.35357600D-06  2.56309120D-10 -1.79360440D-14\n                                                 -5.02113760D+04 -1.11875176D+01\nSO2\n 2 J 6/61 S   1.00O   2.00    0.00    0.00    0.00 0     64.06480    -296834.548\n    300.000  1000.000 5  0.0  1.0  2.0  3.0  4.0  5.0  0.0  0.0\n  3.26653380D+00  5.32379020D-03  6.84375520D-07 -5.28100470D-09  2.55904540D-12\n                                                 -3.69081480D+04  9.66465108D+00\n   1000.000  5000.000 5  0.0  1.0  2.0  3.0  4.0  5.0  0.0  0.0\n  5.24513640D+00  1.97042040D-03 -8.03757690D-07  1.51499690D-10 -1.05580040D-14\n                                                 -3.75582270D+04 -1.07404892D+00\nAR                Argon. NSRDS-NBS 35, vl, 1971. Temperature cutoff.\n 2 L 6/88 AR  1.00    0.00    0.00    0.00    0.00 0     39.94800          0.000\n    200.000  1000.000 1  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0         6197.428\n 2.500000000D+00 0.000000000D+00 0.000000000D+00 0.000000000D+00 0.000000000D+00\n 0.000000000D+00 0.000000000D+00 0.000000000D+00-7.453750000D+02 4.379674910D+00\n   1000.000  6000.000 1  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0         6197.428\n 2.500000000D+00 0.000000000D+00 0.000000000D+00 0.000000000D+00 0.000000000D+00\n 0.000000000D+00 0.000000000D+00 0.000000000D+00-7.453750000D+02 4.379674910D+00\nN2                Nitrogen. GLUSHKO ET.AL. v1, pt2, p207, 1978.\n 2 TPIS78 N   2.00    0.00    0.00    0.00    0.00 0     28.01348          0.000\n    200.000  1000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0         8670.104\n 3.531005280D+00-1.236609870D-04-5.029994360D-07 2.435306118D-09-1.408812347D-12\n 0.000000000D+00 0.000000000D+00 0.000000000D+00-1.046976280D+03 2.967474680D+00\n   1000.000  6000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0         8670.104\n 2.952576373D+00 1.396900385D-03-4.926315980D-07 7.860101870D-11-4.607551990D-15\n 0.000000000D+00 0.000000000D+00 0.000000000D+00-9.239486900D+02 5.871891890D+00\nO2                Oxygen. Gurvich et al. v1, pt 2, p9, 1989.\n 2 TPIS89 O   2.00    0.00    0.00    0.00    0.00 0     31.99880          0.000\n    200.000  1000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0         8680.104\n 3.782456360D+00-2.996734156D-03 9.847302010D-06-9.681295090D-09 3.243728370D-12\n 0.000000000D+00 0.000000000D+00 0.000000000D+00-1.063943564D+03 3.657675730D+00\n   1000.000  6000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0         8680.104\n 3.660960650D+00 6.563658110D-04-1.411496268D-07 2.057979356D-11-1.299134362D-15\n 0.000000000D+00 0.000000000D+00 0.000000000D+00-1.215977179D+03 3.415362790D+00\nCO2               Props & Hf298: TPIS v2,pt1,1991,p27.\n 2 L 7/88 C   1.00O   2.00    0.00    0.00    0.00 0     44.00980    -393510.000\n    200.000  1000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0         9365.469\n 2.356773524D+00 8.984596770D-03-7.123562690D-06 2.459190224D-09-1.436995477D-13\n 0.000000000D+00 0.000000000D+00 0.000000000D+00-4.837196970D+04 9.901052220D+00\n   1000.000  6000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0         9365.469\n 4.636594930D+00 2.741319907D-03-9.958285310D-07 1.603730114D-10-9.161034680D-15\n 0.000000000D+00 0.000000000D+00 0.000000000D+00-4.902493410D+04-1.935348550D+00\nCA\n 2 BEN76  C   1.00    0.00    0.00    0.00    0.00 0     12.01100      17210.010\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n  6.20131064d-01  6.55685438d-03 -8.40971939d-06  5.34237173d-09 -1.34221334d-12\n                                                  1.67980617d+04 -2.13964424d+00\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  1.70014134d+00  2.13036557d-03 -1.46491180d-06  4.57867726d-10 -5.30959813d-14\n                                                  1.65796625d+04 -7.34011722d+00\nCBC\n 2 BEN76  C   1.00    0.00    0.00    0.00    0.00 0     12.01100       2772.724\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n  1.10379898d+00 -1.40207754d-03  1.01721889d-05 -1.04915786d-08  3.35530569d-12\n                                                  2.43522265d+03 -1.01067689d+01\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  1.18859776d+00  2.62679100d-03 -1.40397450d-06  3.62315999d-10 -3.62315999d-14\n                                                  2.15954456d+03 -1.17034055d+01\nCBCB\n 2 S&F85  C   1.00H   0.00    0.00    0.00    0.00 0     12.01100          0.000\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n -9.07225320d-01  1.21274570d-02 -1.59921140d-05  1.06772290d-08 -2.88771260d-12\n                                                  2.34891290d+03 -2.17231890d+00\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  1.64937250d+00  2.43505820d-03 -1.40110120d-06  3.74624350d-10 -3.82283850d-14\n                                                  1.78059830d+03 -1.47139470d+01\nCBCD\n 2 S&F85  C   1.00H   0.00    0.00    0.00    0.00 0     12.01100          0.000\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n  1.89361290d+00 -3.63320180d-03  1.33476670d-05 -1.32062840d-08  4.38875210d-12\n                                                  2.36121080d+03 -1.41160640d+01\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  6.57951850d-01  3.79153180d-03 -2.18052300d-06  5.80353650d-10 -5.87829120d-14\n                                                  2.50341600d+03 -8.72472110d+00\nCBCT\n 2 S&F85  C   1.00H   0.00    0.00    0.00    0.00 0     12.01100          0.000\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n  1.89361290d+00 -3.63320180d-03  1.33476670d-05 -1.32062840d-08  4.38875210d-12\n                                                  2.36121080d+03 -1.58018030d+01\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  6.57951850d-01  3.79153180d-03 -2.18052300d-06  5.80353650d-10 -5.87829120d-14\n                                                  2.50341600d+03 -1.04104590d+01\nCBH\n 2 S&F85  C   1.00H   1.00    0.00    0.00    0.00 0     13.01894          0.000\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n -8.59079180d-01  1.01575080d-02 -6.05790130d-06  1.11817290d-10  8.76799660d-13\n                                                  1.51812920d+03  7.93471810d+00\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  8.12920500d-01  5.70326930d-03 -2.94688640d-06  7.32625720d-10 -7.11722860d-14\n                                                  1.07063610d+03 -6.86258470d-01\nCDC2\n 2 BEN76  C   1.00    0.00    0.00    0.00    0.00 0     12.01100       5203.260\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n  1.57567141d-02  1.20990725d-02 -2.39398157d-05  2.39017773d-08 -9.01711547d-12\n                                                  4.82932602d+03 -9.21726687d+00\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  2.25642353d+00  1.36203978d-03 -7.27986777d-07  1.87867555d-10 -1.87867555d-14\n                                                  4.34871092d+03 -1.99090723d+01\nCDCBC\n 2 BEN76  C   1.00    0.00    0.00    0.00    0.00 0     12.01100       4347.792\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n -2.15050677d+00  2.56218701d-02 -4.82075840d-05  4.17875044d-08 -1.37198166d-11\n                                                  4.19996194d+03 -9.32804085d-01\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  3.04446083d+00  4.86442777d-04 -2.59995277d-07  6.70955554d-11 -6.70955554d-15\n                                                  3.27765919d+03 -2.51782099d+01\nCDCDC\n 2 BEN76  C   1.00    0.00    0.00    0.00    0.00 0     12.01100       4468.564\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n -2.15050677d+00  2.56218701d-02 -4.82075840d-05  4.17875044d-08 -1.37198166d-11\n                                                  4.32073394d+03 -9.32804085d-01\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  3.04446083d+00  4.86442777d-04 -2.59995277d-07  6.70955554d-11 -6.70955554d-15\n                                                  3.39843119d+03 -2.51782099d+01\nCDHC\n 2 BEN76  C   1.00H   1.00    0.00    0.00    0.00 0     13.01894       4322.631\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n  3.87658435d-01  6.91462635d-03 -4.92473068d-06  3.06564147d-09 -1.19103098d-12\n                                                  3.93773106d+03 -6.55229555d-02\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  1.76953318d+00  3.63735034d-03 -1.32392850d-06  1.71399542d-10 -2.18997389d-15\n                                                  3.48001920d+03 -7.46676354d+00\nCDHCB\n 2 S&F85  C   1.00H   1.00    0.00    0.00    0.00 0     13.01894          0.000\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n -1.77479380d+00  2.03672900d-02 -2.92063140d-05  2.13900470d-08 -6.19476560d-12\n                                                  3.25431500d+03  8.37139370d+00\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  2.16078460d+00  3.89973620d-03 -1.87505280d-06  4.40575310d-10 -4.10819930d-14\n                                                  2.44872450d+03 -1.05679580d+01\nCDHCD\n 2 S&F85  C   1.00H   1.00    0.00    0.00    0.00 0     13.01894          0.000\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n -1.77479380d+00  2.03672900d-02 -2.92063140d-05  2.13900470d-08 -6.19476560d-12\n                                                  3.25431500d+03  8.37139370d+00\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  2.16078460d+00  3.89973620d-03 -1.87505280d-06  4.40575310d-10 -4.10819930d-14\n                                                  2.44872440d+03 -1.05679580d+01\nCDHCT\n 2 S&F85  C   1.00H   1.00    0.00    0.00    0.00 0     13.01894          0.000\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n -1.77479380d+00  2.03672900d-02 -2.92063140d-05  2.13900470d-08 -6.19476560d-12\n                                                  3.25431500d+03  9.20168260d+00\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  2.16078460d+00  3.89973620d-03 -1.87505280d-06  4.40575310d-10 -4.10819930d-14\n                                                  2.44872450d+03 -9.73766950d+00\nCDH2\n 2 S&F85  C   1.00H   2.00    0.00    0.00    0.00 0     14.02688          0.000\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n  7.08636360d-01  5.71738370d-03  3.97432860d-06 -8.14882140d-09  3.39759220d-12\n                                                  2.66405290d+03  8.03997270d+00\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  7.62035270d-01  7.90072810d-03 -3.83366760d-06  9.04921890d-10 -8.42780610d-14\n                                                  2.55458540d+03  7.24431290d+00\nCHC3\n 2 BEN76  C   1.00H   1.00    0.00    0.00    0.00 0     13.01894       -956.112\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n -1.21199942d+00  1.57135839d-02 -1.58129928d-05  8.16308832d-09 -1.79427286d-12\n                                                 -1.16875169d+03 -3.21908314d+00\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  4.21180248d+00  8.18242540d-05  1.33950798d-06 -6.69862359d-10  9.41347774d-14\n                                                 -2.66361789d+03 -3.11576551d+01\nCHCBC2\n 2 BEN76  C   1.00H   1.00    0.00    0.00    0.00 0     13.01894       -493.152\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n -2.70626696d+00  2.55442809d-02 -3.35585641d-05  2.09055818d-08 -5.02705367d-12\n                                                 -5.64094599d+02  3.00591586d+00\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  3.92458678d+00  2.09170394d-03 -1.11797969d-06  2.88510888d-10 -2.88510888d-14\n                                                 -2.12756082d+03 -2.99433080d+01\nCHCDC2\n 2 BEN76  C   1.00H   1.00    0.00    0.00    0.00 0     13.01894       -744.761\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n -2.69178809d+00  2.27174202d-02 -2.67597650d-05  1.50516772d-08 -3.18914467d-12\n                                                 -7.43740880d+02  3.74363064d+00\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  2.00129268d+00  5.30222627d-03 -2.83394852d-06  7.31341554d-10 -7.31341554d-14\n                                                 -1.74761503d+03 -1.92282945d+01\nCHCTC2\n 2 BEN76  C   1.00H   1.00    0.00    0.00    0.00 0     13.01894       -865.533\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n -2.29967144d+00  2.07315703d-02 -2.60278088d-05  1.75696487d-08 -4.99182528d-12\n                                                 -9.03749304d+02  2.30198068d+00\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  1.48247630d+00  5.93460188d-03 -3.17194238d-06  8.18565776d-10 -8.18565777d-14\n                                                 -1.70025797d+03 -1.60989330d+01\nCH2C2\n 2 BEN76  C   1.00H   2.00    0.00    0.00    0.00 0     14.02688      -2480.858\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n  2.95576901d-01  8.26548665d-03  2.02730929d-06 -8.22251499d-09  3.84394234d-12\n                                                 -2.93983603d+03  5.66809199d-01\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  8.95359335d-01  8.82630650d-03 -4.51610338d-06  1.11218836d-09 -1.07950628d-13\n                                                 -3.18218807d+03 -2.98904913d+00\nCH2CBC\n 2 BEN76  C   1.00H   2.00    0.00    0.00    0.00 0     14.02688      -2445.633\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n -1.61079486d+00  2.13020824d-02 -2.44229173d-05  1.42423100d-08 -3.20026830d-12\n                                                 -2.72304502d+03  8.49250374d+00\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  2.81096829d+00  5.93460188d-03 -3.17194238d-06  8.18565777d-10 -8.18565777d-14\n                                                 -3.81247249d+03 -1.36149824d+01\nCH2CBD\n 2 BEN76  C   1.00H   2.00    0.00    0.00    0.00 0     14.02688      -2158.799\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n -2.99489148d+00  2.49586869d-02 -2.77613624d-05  1.47398773d-08 -2.60172081d-12\n                                                 -2.15783856d+03  1.58638825d+01\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  1.17752700d+00  8.75596999d-03 -4.67991499d-06  1.20772000d-09 -1.20772000d-13\n                                                 -3.03586486d+03 -4.40568818d+00\nCH2CD2\n 2 BEN76  C   1.00H   2.00    0.00    0.00    0.00 0     14.02688      -2158.799\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n -2.99489148d+00  2.49586869d-02 -2.77613624d-05  1.47398773d-08 -2.60172081d-12\n                                                 -2.15783856d+03  1.58638825d+01\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  1.17752700d+00  8.75596999d-03 -4.67991499d-06  1.20772000d-09 -1.20772000d-13\n                                                 -3.03586486d+03 -4.40568818d+00\nCH2CDC\n 2 BEN76  C   1.00H   2.00    0.00    0.00    0.00 0     14.02688      -2395.311\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n -9.84166104d-01  1.41467063d-02 -7.15413971d-06 -2.15080256d-09  2.42261065d-12\n                                                 -2.66434595d+03  6.65325780d+00\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  8.87674198d-01  9.14512421d-03 -4.88791121d-06  1.26139644d-09 -1.26139644d-13\n                                                 -3.13410437d+03 -2.90870113d+00\nCH2CTC\n 2 BEN76  C   1.00H   2.00    0.00    0.00    0.00 0     14.02688      -2380.215\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n -7.61851269d-01  1.30343429d-02 -7.51763250d-06  4.44629802d-10  9.34733367d-13\n                                                 -2.66730666d+03  5.96602298d+00\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  3.68857816d-01  9.77749982d-03 -5.22590507d-06  1.34862066d-09 -1.34862066d-13\n                                                 -2.94558197d+03  2.32409280d-01\nCH3C\n 2 BEN76  C   1.00H   3.00    0.00    0.00    0.00 0     15.03482      -5132.810\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n  9.67091211d-01  4.54272496d-03  1.40931220d-05 -2.03529587d-08  8.18255263d-12\n                                                 -5.71121159d+03  7.97556073d+00\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n -6.27511183d-01  1.36690420d-02 -7.30586729d-06  1.88538511d-09 -1.88538511d-13\n                                                 -5.43213903d+03  1.52438529d+01\nCTC\n 2 BEN76  C   1.00    0.00    0.00    0.00    0.00 0     12.01100      13863.619\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n  8.02437417d-01  3.49837285d-03 -4.15397270d-06  4.07988802d-09 -1.75083632d-12\n                                                  1.34983448d+04 -2.26753348d+00\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  1.24244195d+00  2.09170394d-03 -1.11797969d-06  2.88510888d-10 -2.88510888d-14\n                                                  1.33531243d+04 -4.58500863d+00\nCTCB\n 2 S&F85  C   1.00H   0.00    0.00    0.00    0.00 0     12.01100          0.000\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n -3.49384520d+00  2.72321320d-02 -4.76891040d-05  3.86559630d-08 -1.19225380d-11\n                                                  1.33155360d+04  1.68245410d+01\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  2.28560130d+00  8.22574900d-04 -4.14361390d-07  1.03588260d-10 -1.03983680d-14\n                                                  1.22382860d+04 -1.04535180d+01\nCTCD\n 2 S&F85  C   1.00H   0.00    0.00    0.00    0.00 0     12.01100          0.000\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n  7.72587840d-01  1.44159610d-03  2.24535910d-06 -3.27337130d-09  1.18176800d-12\n                                                  1.38820450d+04 -1.66930970d+00\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  4.49136330d-01  3.36057940d-03 -1.88820530d-06  4.95862840d-10 -4.98295890d-14\n                                                  1.39278700d+04 -2.35699140d-01\nCTCT\n 2 S&F85  C   1.00H   0.00    0.00    0.00    0.00 0     12.01100          0.000\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n  9.09050340d-03  9.68282400d-03 -1.61930660d-05  1.34477210d-08 -4.31250880d-12\n                                                  1.25675030d+04  6.29563560d-01\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  1.61375010d+00  1.75286410d-03 -9.50741270d-07  2.44108940d-10 -2.42282270d-14\n                                                  1.22902950d+04 -6.81710090d+00\nCTH\n 2 S&F85  C   1.00H   1.00    0.00    0.00    0.00 0     13.01894          0.000\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0\n  3.22062990d-01  1.23444940d-02 -1.94881630d-05  1.58382730d-08 -4.95581450d-12\n                                                  1.30498420d+04  7.64972930d+00\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0\n  2.08408360d+00  3.00946820d-03 -1.27530500d-06  2.64569910d-10 -2.18420530d-14\n                                                  1.27910130d+04 -3.35539540d-01\nHVIN              C2H4 - C2H3\n 2 L 2/91 H   1.00    0.00    0.00    0.00    0.00 0      1.00794    -625071.953\n    200.000  1000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0            0.000\n  7.46735360d-01 -9.08531026d-03  3.11780593d-05 -3.33930685d-08  1.22733472d-11\n  0.00000000d+00  0.00000000d+00  0.00000000d+00 -7.52125326d+04 -2.33376993d+00\n   1000.000  6000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0            0.000\n -3.59257940d-01  2.99014152d-03 -1.07409461d-06  1.73348003d-10 -1.03738147d-14\n  0.00000000d+00  0.00000000d+00  0.00000000d+00 -7.53284072d+04  1.23891111d+00\nHVINS             C2H4 - C2H3 + 8 kcal correction on H.\n 2 L 2/91 H   1.00    0.00    0.00    0.00    0.00 0      1.00794    -591599.953\n    200.000  1000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0            0.000\n  7.46735360d-01 -9.08531026d-03  3.11780593d-05 -3.33930685d-08  1.22733472d-11\n  0.00000000d+00  0.00000000d+00  0.00000000d+00 -7.11867993d+04 -2.33376993d+00\n   1000.000  6000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0            0.000\n -3.59257940d-01  2.99014152d-03 -1.07409461d-06  1.73348003d-10 -1.03738147d-14\n  0.00000000d+00  0.00000000d+00  0.00000000d+00 -7.13026738d+04  1.23891111d+00\nHPHEN             C6H6 - C6H5\n 2 L 1/91 H   1.00    0.00    0.00    0.00    0.00 0      1.00794    -254320.000\n    200.000  1000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0            0.000\n -2.06302352d-01 -8.15243200d-04  1.43769315d-05 -1.95955059d-08  8.17474280d-12\n  0.00000000d+00  0.00000000d+00  0.00000000d+00 -3.05819013d+04  1.10333770d+00\n   1000.000  6000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0            0.000\n  3.06920100d-01  2.32195120d-03 -8.16396860d-07  1.29838420d-10 -7.68981960d-15\n  0.00000000d+00  0.00000000d+00  0.00000000d+00 -3.08941277d+04 -2.51191430d+00\nHC2H              C2H2 - C2H1\n 2 L 3/91 H   1.00    0.00    0.00    0.00    0.00 0      1.00794    -331613.472\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0            0.000\n -3.22796852d+00  1.87214852d-02 -3.02272137d-05  2.39352994d-08 -7.26880375d-12\n  0.00000000d+00  0.00000000d+00  0.00000000d+00 -3.95302119d+04  1.38493147d+01\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0            0.000\n -5.51834000d-02  3.11952519d-03 -1.41953706d-06  3.15909714d-10 -2.79158072d-14\n  0.00000000d+00  0.00000000d+00  0.00000000d+00 -4.00479060d+04 -8.06478801d-01\nC6H5              PHENYL RADICAL. NASA TM 83800, 1985. TRC 10/89.\n 2 L 1/91 C   6.00H   5.00    0.00    0.00    0.00 0     77.10570     337200.000\n    200.000  1000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        14004.789\n  7.09733118d-01  1.93298588d-02  5.94082169d-05 -9.85091151d-08  4.25428989d-11\n  0.00000000d+00  0.00000000d+00  0.00000000d+00  3.91345677d+04  2.30298910d+01\n   1000.000  6000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        14004.789\n  1.07700130d+01  1.83851527d-02 -6.70001899d-06  1.09228975d-09 -6.58438624d-14\n  0.00000000d+00  0.00000000d+00  0.00000000d+00  3.52041168d+04 -3.50135190d+01\nC6H6              Benzene. NASA TM 83800, 1985. TRC 10/86.\n 2 L 1/91 C   6.00H   6.00    0.00    0.00    0.00 0     78.11364      82880.000\n    200.000  1000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        14194.792\n  5.03430766d-01  1.85146156d-02  7.37851484d-05 -1.18104621d-07  5.07176417d-11\n  0.00000000d+00  0.00000000d+00  0.00000000d+00  8.55266640d+03  2.41332287d+01\n   1000.000  6000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        14194.792\n  1.10769331d+01  2.07071039d-02 -7.51641585d-06  1.22212817d-09 -7.35336820d-14\n  0.00000000d+00  0.00000000d+00  0.00000000d+00  4.30998914d+03 -3.75254333d+01\nC2H3              VINYL RAD.  Ervin, JACS 1990, v112, p5750. Taylor;Ames.\n 2 L 2/91 C   2.00H   3.00    0.00    0.00    0.00 0     27.04582     677571.953\n    200.000  1000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        10575.049\n  3.21246076d+00  1.51485596d-03  2.59207153d-05 -3.57655130d-08  1.47149755d-11\n  0.00000000d+00  0.00000000d+00  0.00000000d+00  8.03023088d+04  7.81741050d+00\n   1000.000  6000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        10575.049\n  4.35099402d+00  7.49338358d-03 -2.64318675d-06  4.21293814d-10 -2.49901527d-14\n  0.00000000d+00  0.00000000d+00  0.00000000d+00  7.95971039d+04 -1.21152748d-01\nC2H4              ETHYLENE.  VARIOUS REFS.\n 2 L 1/07 C   2.00H   4.00    0.00    0.00    0.00 0     28.05376      52500.000\n    200.000  1000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        10518.688\n  3.95919612d+00 -7.57045430d-03  5.70987746d-05 -6.91585815d-08  2.69883227d-11\n  0.00000000d+00  0.00000000d+00  0.00000000d+00  5.08977621d+03  5.48364057d+00\n   1000.000  6000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        10518.688\n  3.99173608d+00  1.04835251d-02 -3.71728136d-06  5.94641817d-10 -3.53639674d-14\n  0.00000000d+00  0.00000000d+00  0.00000000d+00  4.26869674d+03  1.11775836d+00\nC2H2              GLUSHKO CONSTANTS,1978. DelH TRC tables, 10/31/88.\n 2 L 1/91 C   2.00H   2.00    0.00    0.00    0.00 0     26.03788     228200.000\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        10012.261\n  5.72658274d-01  2.51337936d-02 -4.00165415d-05  3.27263088d-08 -1.02964640d-11\n  0.00000000d+00  0.00000000d+00  0.00000000d+00  2.64518701d+04  1.56116943d+01\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        10012.261\n  4.12608035d+00  6.10531164d-03 -2.61558836d-06  5.50068670d-10 -4.61171092d-14\n  0.00000000d+00  0.00000000d+00  0.00000000d+00  2.59396953d+04 -4.43643704d-01\nC2H               ETHYNYL. Delh: Ervin,JACS v112,1990. Jacox, 1988.\n 2 L 1/91 C   2.00H   1.00    0.00    0.00    0.00 0     25.02994     559813.472\n    298.150  1000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        10454.472\n  3.80062679d+00  6.41230844d-03 -9.78932779d-06  8.79100936d-09 -3.02766025d-12\n  0.00000000d+00  0.00000000d+00  0.00000000d+00  6.59820820d+04  1.76237958d+00\n   1000.000  3000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        10454.472\n  4.18126375d+00  2.98578645d-03 -1.19605130d-06  2.34158956d-10 -1.82013020d-14\n  0.00000000d+00  0.00000000d+00  0.00000000d+00  6.59876013d+04  3.62835097d-01\nCRESOL            EQL MIXTURE. KUDCHADKER ET AL JPCRD,V7,N2,P417,1978.\n 2 L 6/87 C   7.00H   8.00O   1.00    0.00    0.00 0    108.13992    -132298.000\n    200.000  1000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        21109.369\n  4.22633160d-01  4.55511152d-02  3.20141892d-05 -8.11240449d-08  3.76665388d-11\n  0.00000000d+00  0.00000000d+00  0.00000000d+00 -1.82026239d+04  2.60327123d+01\n   1000.000  6000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        21109.369\n  1.59327193d+01  2.70116915d-02 -9.94520997d-06  1.62975034d-09 -9.85197125d-14\n  0.00000000d+00  0.00000000d+00  0.00000000d+00 -2.35919689d+04 -5.97313776d+01\nC6H5OH            PHENOL. NASA TM 83800, JAN 1985.\n 2 L 6/90 C   6.00H   6.00O   1.00    0.00    0.00 0     94.11304     -96399.000\n    200.000  1000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        17496.655\n -2.91043722d-01  4.08566827d-02  2.42825579d-05 -7.14481301d-08  3.46006031d-11\n  0.00000000d+00  0.00000000d+00  0.00000000d+00 -1.34129213d+04  2.68748641d+01\n   1000.000  6000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        17496.655\n  1.41556495d+01  1.99344395d-02 -7.18195552d-06  1.16224855d-09 -6.97121653d-14\n  0.00000000d+00  0.00000000d+00  0.00000000d+00 -1.81288534d+04 -5.18007382d+01\nC6H5O             PHENOXY RADICAL. NASA TM-83800, 1985.\n 2 L 6/90 C   6.00H   5.00O   1.00    0.00    0.00 0     93.10510      47697.600\n    200.000  1000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        16208.083\n  7.75754295d-02  3.30579420d-02  3.60341330d-05 -7.93148251d-08  3.64321927d-11\n  0.00000000d+00  0.00000000d+00  0.00000000d+00  4.06540008d+03  2.57601045d+01\n   1000.000  6000.000 5  0.0  1.0  2.0  3.0  4.0  0.0  0.0  0.0        16208.083\n  1.31516170d+01  1.90163347d-02 -6.94688180d-06  1.13441103d-09 -6.84628699d-14\n  0.00000000d+00  0.00000000d+00  0.00000000d+00 -4.73010834d+02 -4.67113087d+01\n\"\"\"\n    return s\n\n\nif __name__ == \"__main__\":\n    import doctest\n    doctest.testmod(verbose=True)\n", "meta": {"hexsha": "f3f9cb0e936aaf53dde59b747a8c10195bd0da8e", "size": 71575, "ext": "py", "lang": "Python", "max_stars_repo_path": "qtc/tctools.py", "max_stars_repo_name": "keceli/qtc", "max_stars_repo_head_hexsha": "334fae9cd0eea493437e95c9aeb5a3088cbac343", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "qtc/tctools.py", "max_issues_repo_name": "keceli/qtc", "max_issues_repo_head_hexsha": "334fae9cd0eea493437e95c9aeb5a3088cbac343", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qtc/tctools.py", "max_forks_repo_name": "keceli/qtc", "max_forks_repo_head_hexsha": "334fae9cd0eea493437e95c9aeb5a3088cbac343", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1198156682, "max_line_length": 149, "alphanum_fraction": 0.5397275585, "include": true, "reason": "import numpy", "num_tokens": 30835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.1880048468174652}}
{"text": "#!/usr/bin/env python2.7\n\nfrom pymongo import MongoClient\nimport pymongo.errors\nimport bson\nimport cPickle as pickle\nimport solver\nimport numpy as np\n\n# Connexion a la base de donnees mongoDB\nusername, password, host, dbname = 'user', 'user123', '127.0.0.1', 'dinghao'\nclient = MongoClient('mongodb://%s:%s@%s/%s' % (username, password, host, dbname))\ndb = client.dinghao\n\n# Recuperer l'id des inputs pour l'initialisation du calcul\ninit_id = raw_input(\"Entrer l'id de l'init : \") or \"5b1085116e955233e756b33d\"\nprint init_id\n\n# Recuperer les donnees necessaires au calcul\ndata = db['init'].find_one({'_id': bson.objectid.ObjectId(init_id)})\n\ndt = data[\"dt\"]\ndx = data[\"dx\"]\ndy = data[\"dy\"]\nNt = data[\"Nt\"]\ntf = data[\"tf\"]\nNt_0 = data['num_run']\nsolver_type = str(data[\"solver_algo\"])\nV = np.array( pickle.loads(data[\"V\"]) , order=\"F\" )\nt = np.linspace(0, tf, Nt, dtype=np.float32)\n\nrun = db['run'].find_one({'init_id': bson.objectid.ObjectId(init_id)}, sort= [('t', -1)])\n\npsi0 =  np.array( pickle.loads(run[\"psi\"]) , order=\"F\", dtype=\"complex128\")\nnorm = np.linalg.norm(psi0, ord=1)\n\n# Initialisation du solver\nsol = solver.Solver(str(solver_type), psi0, V, 6.582119514, 939.5654133, dt, dx, dy)\n\n# Calcul de la solution de schrodinger 2D dependant du temps\ntry:\n    for it in range(Nt_0,Nt):\n        for i in range (2000):\n            if (solver_type == \"ftcs\"):\n                psi = sol.ftcs()\n            elif (solver_type == \"btcs\"):\n                psi = sol.btcs(50)\n            else:\n                psi = sol.ctcs(50)\n            psi = np.array( sol.ftcs(), order=\"F\", dtype=\"complex128\" ) \n            N = np.abs(psi)/ norm\n        bindat = bson.binary.Binary(pickle.dumps(psi, protocol = 2))\n        psi_id = db['run'].insert_one({\n            'psi': bindat\n        }).inserted_id\n        db['run'].update_one({'_id': psi_id}, {'$set': {'t': 0, 'init_id': bson.objectid.ObjectId(init_id), 'norm': np.linalg.norm(psi, ord=1)}})\n        result = db['init'].update_one({'_id': bson.objectid.ObjectId(init_id)}, {'$inc': {'num_run': 1}})\n        print(\"Iter %s / %s, t = %s\" % (str(it + 1), str(Nt), str(t[it])))\n        \nexcept pymongo.errors.OperationFailure as e:\n  print(\"ERROR: %s\" % (e))", "meta": {"hexsha": "06c94a53123fc4673444e9f885df1d9a7728a09a", "size": 2201, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/solver_mongo.py", "max_stars_repo_name": "DinghaoLI/Schrodinger_equation_3D", "max_stars_repo_head_hexsha": "d987fd8a711d4f3b13727b576caacf399c3fb10b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/solver_mongo.py", "max_issues_repo_name": "DinghaoLI/Schrodinger_equation_3D", "max_issues_repo_head_hexsha": "d987fd8a711d4f3b13727b576caacf399c3fb10b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solver_mongo.py", "max_forks_repo_name": "DinghaoLI/Schrodinger_equation_3D", "max_forks_repo_head_hexsha": "d987fd8a711d4f3b13727b576caacf399c3fb10b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0819672131, "max_line_length": 145, "alphanum_fraction": 0.6165379373, "include": true, "reason": "import numpy", "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.18800483976023485}}
{"text": "###############################################\n##Dmitry Sutormin, 2020##\n##N-to-C-terminus assymetry in protein domain secondary structure elements composition##\n\n#Pareses DSSP output generated for representative structures with Run_DSSP.py\n#Get statistics of secondary structure elements at N- and C-termini of protein domains.\n###############################################\n\n#######\n#Packages to be imported.\n#######\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.stats as st\n\n#######\n#Variables to be defined.\n#######\n\n#Path to DSSP data file.\nDSSP_data_inpath=\"C:\\\\Users\\sutor\\OneDrive\\ThinkPad_working\\Sutor\\Documents\\Skoltech_PhD\\Structural_bioinformatics\\Project\\DSSP\\DSSP\\DSSP_Representative_pdb_domains.txt\"\n\n\n#Path to output file.\nDSSP_data_outpath=\"C:\\\\Users\\sutor\\OneDrive\\ThinkPad_working\\Sutor\\Documents\\Skoltech_PhD\\Structural_bioinformatics\\Project\\DSSP\\\\\"\n\n\n#######\n#Read DSSP output.\n#######\n\ndef read_dssp_data(DSSP_inpath):\n    \n    #Read DSSP data keep in dictionary.\n    DSSP_data_dict={}\n    filein=open(DSSP_inpath, 'r')\n    for line in filein:\n        line=line.rstrip().split('\\t')  \n        if line[0] not in ['PFAM_id']:\n            PFAM_id=line[0]\n            PDB_id=line[1]\n            Chain_id=line[2]\n            Start=int(line[3])\n            End=int(line[4])\n            Resolution=float(line[5])\n            SSE_string=line[6]\n            Phi_list=[float(x) for x in line[7].lstrip('[').rstrip(']').split(', ')]\n            Psi_list=[float(x) for x in line[8].lstrip('[').rstrip(']').split(', ')]\n            DSSP_data_dict[PFAM_id]=[PDB_id, Chain_id, Start, End, Resolution, SSE_string, Phi_list, Psi_list]\n    \n    filein.close()\n    return DSSP_data_dict\n\n\n#######\n#Filter data, split data by domain length.\n#######\n\ndef define_length_groups(DSSP_data_dict, min_len, thr_len):\n    \n    Domain_length_ar=[]\n    Discarded_short_structures={}\n    Short_structures={}\n    Long_structures={}\n    for pfam_id, dssp_data in DSSP_data_dict.items():\n        domain_len=len(dssp_data[5])\n        Domain_length_ar.append(domain_len)\n        \n        #Classify domains by length.\n        if domain_len<min_len:\n            Discarded_short_structures[pfam_id]=dssp_data\n        elif min_len<=domain_len<thr_len:\n            Short_structures[pfam_id]=dssp_data\n        elif domain_len>=thr_len:\n            Long_structures[pfam_id]=dssp_data    \n    \n    #Plot domain length distribution.\n    fig, plot=plt.subplots(1,1,figsize=(3,3), dpi=100)\n    plot.hist(Domain_length_ar, bins=50, rwidth=0.85, color='#94fff1', edgecolor='black', linewidth=0.1)\n    plot.axvline(x=min_len, ls='--', linewidth=0.7, color='black')\n    plot.axvline(x=thr_len, ls='--', linewidth=0.7)\n    plot.set_xlabel('Domain length, aa')\n    plot.set_ylabel('Number of structures') \n    plot.set_yscale('log')\n    plot.set_title('Representative structures\\nafter DSSP')\n    plot.annotate(f'Number of\\nstructures\\n{len(Domain_length_ar)}', (0.5,0.7), xycoords='axes fraction') \n    plot.annotate(f'x<{min_len} : {len(Discarded_short_structures)}', (0.5,0.6), xycoords='axes fraction', size=7)\n    plot.annotate(f'{min_len}<=x<{thr_len} : {len(Short_structures)}', (0.5,0.5), xycoords='axes fraction', size=7)\n    plot.annotate(f'x>={thr_len} : {len(Long_structures)}', (0.5,0.4), xycoords='axes fraction', size=7) \n    \n    plt.tight_layout()\n    plt.show()\n    \n    return Short_structures, Long_structures\n\n\n#######\n#Take phi, psi angles for N- and C-termini.\n#######\n\ndef phi_psi_N_to_C(structures_dict, window_width):\n        \n    phi_N=[]\n    phi_C=[]\n    psi_N=[]\n    psi_C=[] \n    phi=[]\n    psi=[]\n    for pfam_id, dssp_data in structures_dict.items():\n        phi_list=dssp_data[6]\n        psi_list=dssp_data[7]\n        phi_N+=phi_list[:window_width]\n        phi_C+=phi_list[-window_width:]\n        psi_N+=psi_list[:window_width]\n        psi_C+=psi_list[-window_width:] \n        phi+=phi_list\n        psi+=psi_list\n        \n    return phi_N, phi_C, psi_N, psi_C, phi, psi\n\n\n#######\n#Create secondary structure element frequency matrix.\n#######\n\ndef ss_element_frequency_matrix(structures_dict, window_width):\n    \n    #Create positioned matrix of secondary structure elements.\n    ss_matrix_N=[]\n    ss_matrix_C=[]\n    for i in range(window_width):\n        column_N=[]\n        column_C=[]\n        for pfam_id, dssp_data in structures_dict.items():\n            SSE_string=dssp_data[5]\n            column_N.append(SSE_string[i])\n            column_C.append(SSE_string[-window_width+i])\n        ss_matrix_N.append(column_N)\n        ss_matrix_C.append(column_C)\n            \n    #Create position frequency matrix of secondary structure elements.\n    DSSP_alphabet=['H', 'B', 'E', 'G', 'I', 'T', 'S', '-']\n    ss_pfm_N={}\n    ss_pfm_C={}\n    ss_pfm_conf_N={}\n    ss_pfm_conf_C={}\n    for letter_code in DSSP_alphabet:\n        #Keep frequences of ss elements.\n        frequency_row_N=[]\n        frequency_row_C=[]\n        #Keep boundaries of confident interval.\n        conf_upper_N=[]\n        conf_upper_C=[]\n        conf_lower_N=[]\n        conf_lower_C=[]        \n        for i in range(len(ss_matrix_N)):\n            column_letter_freq_N=ss_matrix_N[i].count(letter_code)/float(len(ss_matrix_N[i]))\n            confident_interval_N=st.binom.interval(0.95, len(ss_matrix_N[i]), column_letter_freq_N, loc=0)\n            lower_N=confident_interval_N[0]/len(ss_matrix_N[i])\n            upper_N=confident_interval_N[1]/len(ss_matrix_N[i])\n            conf_lower_N.append(lower_N)\n            conf_upper_N.append(upper_N)\n            frequency_row_N.append(column_letter_freq_N)\n            \n            column_letter_freq_C=ss_matrix_C[i].count(letter_code)/float(len(ss_matrix_C[i]))\n            confident_interval_C=st.binom.interval(0.95, len(ss_matrix_C[i]), column_letter_freq_C, loc=0)\n            lower_C=confident_interval_C[0]/len(ss_matrix_C[i])\n            upper_C=confident_interval_C[1]/len(ss_matrix_C[i])\n            conf_lower_C.append(lower_C)\n            conf_upper_C.append(upper_C)\n            frequency_row_C.append(column_letter_freq_C)  \n          \n        ss_pfm_N[letter_code]=frequency_row_N\n        ss_pfm_C[letter_code]=frequency_row_C\n        \n        ss_pfm_conf_N[letter_code+'_upper']=conf_upper_N\n        ss_pfm_conf_N[letter_code+'_lower']=conf_lower_N\n        ss_pfm_conf_C[letter_code+'_upper']=conf_upper_C\n        ss_pfm_conf_C[letter_code+'_lower']=conf_lower_C        \n       \n    print(ss_pfm_N) \n    print(ss_pfm_C)   \n    return ss_matrix_N, ss_matrix_C, ss_pfm_N, ss_pfm_C, ss_pfm_conf_N, ss_pfm_conf_C\n\n\n#######\n#Enrichment of secondary structure elements N- over C-terminus.\n#######\n\ndef ss_ele_enrichment(ss_pfm_N, ss_pfm_C):\n    \n    enrichment_N_to_C_dict={}\n    for letter_code, frequency_row_N in ss_pfm_N.items():\n        frequency_N=np.array(frequency_row_N)\n        frequency_C=np.array(ss_pfm_C[letter_code][::-1])\n        enrichment_N_to_C=frequency_N/frequency_C\n        enrichment_N_to_C_dict[letter_code]=enrichment_N_to_C\n    \n    return enrichment_N_to_C_dict\n\n\n#######\n#Terminal beta-strands relations: simultaneous occurence or independant?.\n#######\n\ndef termini_dependance(ss_matrix_N, ss_matrix_C, ss_pfm_N, ss_pfm_C, local_window_width):\n    \n    DSSP_alphabet=['H', 'B', 'E', 'G', 'I', 'T', 'S', '-']\n    \n    #Calculate observed frequences of elements co-occurence coordinate-wise.\n    Observed_matrices_dict={}\n    for letter_code_1 in DSSP_alphabet:\n        for letter_code_2 in DSSP_alphabet:\n            Ni_Cj_freq_2d_ar=[]\n            for Ni in range(local_window_width):\n                Cj_freq_1d_ar=[]\n                for Cj in range(local_window_width):\n                    N_column_i=ss_matrix_N[Ni]\n                    C_column_j=ss_matrix_C[-Cj-1]\n                    Ni_Cj_counts=0\n                    for structure_k in range(len(N_column_i)):\n                        if (N_column_i[structure_k]==letter_code_1) and (C_column_j[structure_k]==letter_code_2):\n                            Ni_Cj_counts+=1\n                    Ni_Cj_frequency=Ni_Cj_counts/float(len(N_column_i))\n                    Cj_freq_1d_ar.append(Ni_Cj_frequency)\n            \n                Ni_Cj_freq_2d_ar.append(Cj_freq_1d_ar)\n            \n            Ni_Cj_freq_2d_ar_np=np.array(Ni_Cj_freq_2d_ar)\n            Observed_matrices_dict[letter_code_1+letter_code_2]=Ni_Cj_freq_2d_ar_np\n        \n    #Calculate expected frequences of elements co-occurence coordinate-wise.\n    Expected_matrices_dict={}\n    for letter_code_1 in DSSP_alphabet:\n        for letter_code_2 in DSSP_alphabet:\n            Expected_Ni_Cj_freq_2d_ar=[]\n            for Ni in range(local_window_width):\n                Expected_Cj_freq_1d_ar=[]\n                for Cj in range(local_window_width):  \n                    Ni_frequency=ss_pfm_N[letter_code_1][Ni]\n                    Cj_frequency=ss_pfm_C[letter_code_2][-Cj-1]\n                    Expected_Ni_Cj_frequency=Ni_frequency*Cj_frequency\n                    Expected_Cj_freq_1d_ar.append(Expected_Ni_Cj_frequency)\n                Expected_Ni_Cj_freq_2d_ar.append(Expected_Cj_freq_1d_ar)\n                \n            Expected_Ni_Cj_freq_2d_ar_np=np.array(Expected_Ni_Cj_freq_2d_ar)\n            Expected_matrices_dict[letter_code_1+letter_code_2]=Expected_Ni_Cj_freq_2d_ar_np\n\n    #Calculate observed over expected ratio of frequences of elements co-occurence coordinate-wise.\n    Obs_over_exp_matrices_dict={}\n    for letter_code_1 in DSSP_alphabet:\n        for letter_code_2 in DSSP_alphabet:\n            Obs_over_exp_freq_matrix=np.divide(Observed_matrices_dict[letter_code_1+letter_code_2], Expected_matrices_dict[letter_code_1+letter_code_2])\n            Obs_over_exp_matrices_dict[letter_code_1+letter_code_2]=Obs_over_exp_freq_matrix\n            \n            print(letter_code_1, letter_code_2, Obs_over_exp_freq_matrix)\n    \n    return Obs_over_exp_matrices_dict\n\n\n#######\n#Analyse N-to-C asymmetry in secondary structure elements frequency.\n#######\n\ndef distribution_of_frequences(ss_pfm_N, ss_pfm_C):\n    ss_pfm=ss_pfm_N+ss_pfm_C\n    print(len(ss_pfm))\n    \n    fig, plot=plt.subplots(1,1,figsize=(4,4), dpi=100)\n    weights=np.ones_like(ss_pfm)/(len(ss_pfm)) #Taken from https://stackoverflow.com/questions/42481698/probability-density-histogram-with-matplotlib-doesnt-make-sense     \n    plot.hist(ss_pfm, bins=10, weights=weights)\n    plot.set_xlabel('Frequency of ss element')\n    plot.set_ylabel('Fraction of positions')\n    plt.show()\n\n    return\n\n\n#######\n#Analyse N-to-C asymmetry in secondary structure elements frequency.\n#######\n\ndef N_to_C_asymmetry(ss_pfm_N_short, ss_pfm_C_short, ss_pfm_conf_N_short, ss_pfm_conf_C_short, ss_pfm_N_long, ss_pfm_C_long, ss_pfm_conf_N_long, ss_pfm_conf_C_long, window_width):\n    \n    ##Plot distribution of frequences, get confidential interval.\n    ##Distribution are far from being normal, estimation is not good -> depricated.\n    #distribution_of_frequences(ss_pfm_N_short['H'], ss_pfm_C_short['H'])\n    #distribution_of_frequences(ss_pfm_N_long['H'], ss_pfm_C_long['H'])\n    \n    #Plot frequency of ss elements as a function of distance from N- and C-termini.\n    X_N=range(window_width)\n    X_C=range(60, 60+window_width)\n    xticks_ar=list(range(0,111,10))\n    xticklabels_ar=[0,10,20,30,40,50,-50,-40,-30,-20,-10,0]\n    xticks_spec=[-4, 114]\n    xticklabels_spec=['N-', '-C']\n    fig, plot=plt.subplots(2,2,figsize=(12,6), dpi=100)\n    plot[0,0].plot(X_N, ss_pfm_N_short['H'], color='#94fff1', linewidth=2, label=r'$\\alpha$-helix short domains')\n    plot[0,0].fill_between(X_N, ss_pfm_conf_N_short['H_lower'], ss_pfm_conf_N_short['H_upper'], color='#94fff1', alpha=0.3, linewidth=0)\n    plot[0,0].plot(X_C, ss_pfm_C_short['H'], color='#94fff1', linewidth=2)\n    plot[0,0].fill_between(X_C, ss_pfm_conf_C_short['H_lower'], ss_pfm_conf_C_short['H_upper'], color='#94fff1', alpha=0.3, linewidth=0)\n    \n    plot[0,0].plot(X_N, ss_pfm_N_long['H'], color='#ab658c', linewidth=2, label=r'$\\alpha$-helix long domains')\n    plot[0,0].fill_between(X_N, ss_pfm_conf_N_long['H_lower'], ss_pfm_conf_N_long['H_upper'], color='#ab658c', alpha=0.3, linewidth=0)\n    plot[0,0].plot(X_C, ss_pfm_C_long['H'], color='#ab658c', linewidth=2) \n    plot[0,0].fill_between(X_C, ss_pfm_conf_C_long['H_lower'], ss_pfm_conf_C_long['H_upper'], color='#ab658c', alpha=0.3, linewidth=0)\n    \n    plot[0,0].plot(X_N, ss_pfm_N_short['E'], color='#59acff', linewidth=2, label=r'$\\beta$-strand short domains')\n    plot[0,0].fill_between(X_N, ss_pfm_conf_N_short['E_lower'], ss_pfm_conf_N_short['E_upper'], color='#59acff', alpha=0.3, linewidth=0)\n    plot[0,0].plot(X_C, ss_pfm_C_short['E'], color='#59acff', linewidth=2)\n    plot[0,0].fill_between(X_C, ss_pfm_conf_C_short['E_lower'], ss_pfm_conf_C_short['E_upper'], color='#59acff', alpha=0.3, linewidth=0)\n    \n    plot[0,0].plot(X_N, ss_pfm_N_long['E'], color='#ffec59', linewidth=2, label=r'$\\beta$-strand long domains')\n    plot[0,0].fill_between(X_N, ss_pfm_conf_N_long['E_lower'], ss_pfm_conf_N_long['E_upper'], color='#ffec59', alpha=0.3, linewidth=0)\n    plot[0,0].plot(X_C, ss_pfm_C_long['E'], color='#ffec59', linewidth=2)    \n    plot[0,0].fill_between(X_C, ss_pfm_conf_C_long['E_lower'], ss_pfm_conf_C_long['E_upper'], color='#ffec59', alpha=0.3, linewidth=0)\n    \n    plot[0,0].set_xticks(xticks_ar)\n    plot[0,0].set_xticklabels(xticklabels_ar)\n    plot[0,0].set_xticks(xticks_spec, minor=True)\n    plot[0,0].set_xticklabels(xticklabels_spec, minor=True)\n    plot[0,0].tick_params(axis='x', which='minor', length=0)\n    plot[0,0].set_xlabel('Distance, aa')\n    plot[0,0].set_ylabel('Frequency') \n    plot[0,0].legend(fontsize=8.5, ncol=2, handlelength=0.7, frameon=False, columnspacing=0.7, loc='upper center')\n    \n    plot[0,1].plot(X_N, ss_pfm_N_short['B'], color='#94fff1', linewidth=2, label=r'$\\beta$-bridge short domains')\n    plot[0,1].fill_between(X_N, ss_pfm_conf_N_short['B_lower'], ss_pfm_conf_N_short['B_upper'], color='#94fff1', alpha=0.3, linewidth=0)\n    plot[0,1].plot(X_C, ss_pfm_C_short['B'], color='#94fff1', linewidth=2)\n    plot[0,1].fill_between(X_C, ss_pfm_conf_C_short['B_lower'], ss_pfm_conf_C_short['B_upper'], color='#94fff1', alpha=0.3, linewidth=0)\n    \n    plot[0,1].plot(X_N, ss_pfm_N_long['B'], color='#ab658c', linewidth=2, label=r'$\\beta$-bridge long domains')\n    plot[0,1].fill_between(X_N, ss_pfm_conf_N_long['B_lower'], ss_pfm_conf_N_long['B_upper'], color='#ab658c', alpha=0.3, linewidth=0)\n    plot[0,1].plot(X_C, ss_pfm_C_long['B'], color='#ab658c', linewidth=2) \n    plot[0,1].fill_between(X_C, ss_pfm_conf_C_long['B_lower'], ss_pfm_conf_C_long['B_upper'], color='#ab658c', alpha=0.3, linewidth=0)\n    \n    plot[0,1].plot(X_N, ss_pfm_N_short['G'], color='#59acff', linewidth=2, label=r'3-10-helix short domains')\n    plot[0,1].fill_between(X_N, ss_pfm_conf_N_short['G_lower'], ss_pfm_conf_N_short['G_upper'], color='#59acff', alpha=0.3, linewidth=0)\n    plot[0,1].plot(X_C, ss_pfm_C_short['G'], color='#59acff', linewidth=2)\n    plot[0,1].fill_between(X_C, ss_pfm_conf_C_short['G_lower'], ss_pfm_conf_C_short['G_upper'], color='#59acff', alpha=0.3, linewidth=0)\n    \n    plot[0,1].plot(X_N, ss_pfm_N_long['G'], color='#ffec59', linewidth=2, label=r'3-10-helix long domains')\n    plot[0,1].fill_between(X_N, ss_pfm_conf_N_long['G_lower'], ss_pfm_conf_N_long['G_upper'], color='#ffec59', alpha=0.3, linewidth=0)\n    plot[0,1].plot(X_C, ss_pfm_C_long['G'], color='#ffec59', linewidth=2)    \n    plot[0,1].fill_between(X_C, ss_pfm_conf_C_long['G_lower'], ss_pfm_conf_C_long['G_upper'], color='#ffec59', alpha=0.3, linewidth=0)\n    \n    plot[0,1].set_xticks(xticks_ar)\n    plot[0,1].set_xticklabels(xticklabels_ar)\n    plot[0,1].set_xticks(xticks_spec, minor=True)\n    plot[0,1].set_xticklabels(xticklabels_spec, minor=True)\n    plot[0,1].tick_params(axis='x', which='minor', length=0)\n    plot[0,1].set_xlabel('Distance, aa')\n    plot[0,1].set_ylabel('Frequency')  \n    plot[0,1].legend(fontsize=8.5, ncol=2, handlelength=0.7, frameon=False, columnspacing=0.7, loc='center')\n    \n    plot[1,0].plot(X_N, ss_pfm_N_short['I'], color='#94fff1', linewidth=2, label=r'$\\pi$-helix short domains')\n    plot[1,0].fill_between(X_N, ss_pfm_conf_N_short['I_lower'], ss_pfm_conf_N_short['I_upper'], color='#94fff1', alpha=0.3, linewidth=0)\n    plot[1,0].plot(X_C, ss_pfm_C_short['I'], color='#94fff1', linewidth=2)\n    plot[1,0].fill_between(X_C, ss_pfm_conf_C_short['I_lower'], ss_pfm_conf_C_short['I_upper'], color='#94fff1', alpha=0.3, linewidth=0)\n\n    plot[1,0].plot(X_N, ss_pfm_N_long['I'], color='#ab658c', linewidth=2, label=r'$\\pi$-helix long domains')\n    plot[1,0].fill_between(X_N, ss_pfm_conf_N_long['I_lower'], ss_pfm_conf_N_long['I_upper'], color='#ab658c', alpha=0.3, linewidth=0)\n    plot[1,0].plot(X_C, ss_pfm_C_long['I'], color='#ab658c', linewidth=2) \n    plot[1,0].fill_between(X_C, ss_pfm_conf_C_long['I_lower'], ss_pfm_conf_C_long['I_upper'], color='#ab658c', alpha=0.3, linewidth=0)\n\n    plot[1,0].plot(X_N, ss_pfm_N_short['T'], color='#59acff', linewidth=2, label=r'turn short domains')\n    plot[1,0].fill_between(X_N, ss_pfm_conf_N_short['T_lower'], ss_pfm_conf_N_short['T_upper'], color='#59acff', alpha=0.3, linewidth=0)\n    plot[1,0].plot(X_C, ss_pfm_C_short['T'], color='#59acff', linewidth=2)\n    plot[1,0].fill_between(X_C, ss_pfm_conf_C_short['T_lower'], ss_pfm_conf_C_short['T_upper'], color='#59acff', alpha=0.3, linewidth=0)\n\n    plot[1,0].plot(X_N, ss_pfm_N_long['T'], color='#ffec59', linewidth=2, label=r'turn long domains')\n    plot[1,0].fill_between(X_N, ss_pfm_conf_N_long['T_lower'], ss_pfm_conf_N_long['T_upper'], color='#ffec59', alpha=0.3, linewidth=0)\n    plot[1,0].plot(X_C, ss_pfm_C_long['T'], color='#ffec59', linewidth=2)  \n    plot[1,0].fill_between(X_C, ss_pfm_conf_C_long['T_lower'], ss_pfm_conf_C_long['T_upper'], color='#ffec59', alpha=0.3, linewidth=0)\n    \n    plot[1,0].set_xticks(xticks_ar)\n    plot[1,0].set_xticklabels(xticklabels_ar)\n    plot[1,0].set_xticks(xticks_spec, minor=True)\n    plot[1,0].set_xticklabels(xticklabels_spec, minor=True)\n    plot[1,0].tick_params(axis='x', which='minor', length=0)\n    plot[1,0].set_xlabel('Distance, aa')\n    plot[1,0].set_ylabel('Frequency')  \n    plot[1,0].legend(fontsize=8.5, ncol=2, handlelength=0.7, frameon=False, columnspacing=0.7, loc='center')\n    \n    plot[1,1].plot(X_N, ss_pfm_N_short['S'], color='#94fff1', linewidth=2, label=r'bend short domains')\n    plot[1,1].fill_between(X_N, ss_pfm_conf_N_short['S_lower'], ss_pfm_conf_N_short['S_upper'], color='#94fff1', alpha=0.3, linewidth=0)\n    plot[1,1].plot(X_C, ss_pfm_C_short['S'], color='#94fff1', linewidth=2)\n    plot[1,1].fill_between(X_C, ss_pfm_conf_C_short['S_lower'], ss_pfm_conf_C_short['S_upper'], color='#94fff1', alpha=0.3, linewidth=0)\n    \n    plot[1,1].plot(X_N, ss_pfm_N_long['S'], color='#ab658c', linewidth=2, label=r'bend long domains')\n    plot[1,1].fill_between(X_N, ss_pfm_conf_N_long['S_lower'], ss_pfm_conf_N_long['S_upper'], color='#ab658c', alpha=0.3, linewidth=0)\n    plot[1,1].plot(X_C, ss_pfm_C_long['S'], color='#ab658c', linewidth=2) \n    plot[1,1].fill_between(X_C, ss_pfm_conf_C_long['S_lower'], ss_pfm_conf_C_long['S_upper'], color='#ab658c', alpha=0.3, linewidth=0)\n    \n    plot[1,1].plot(X_N, ss_pfm_N_short['-'], color='#59acff', linewidth=2, label=r'unstructured short domains')\n    plot[1,1].fill_between(X_N, ss_pfm_conf_N_short['-_lower'], ss_pfm_conf_N_short['-_upper'], color='#59acff', alpha=0.3, linewidth=0)\n    plot[1,1].plot(X_C, ss_pfm_C_short['-'], color='#59acff', linewidth=2)\n    plot[1,1].fill_between(X_C, ss_pfm_conf_C_short['-_lower'], ss_pfm_conf_C_short['-_upper'], color='#59acff', alpha=0.3, linewidth=0)\n        \n    plot[1,1].plot(X_N, ss_pfm_N_long['-'], color='#ffec59', linewidth=2, label=r'unstructured long domains')\n    plot[1,1].fill_between(X_N, ss_pfm_conf_N_long['-_lower'], ss_pfm_conf_N_long['-_upper'], color='#ffec59', alpha=0.3, linewidth=0)\n    plot[1,1].plot(X_C, ss_pfm_C_long['-'], color='#ffec59', linewidth=2)  \n    plot[1,1].fill_between(X_C, ss_pfm_conf_C_long['-_lower'], ss_pfm_conf_C_long['-_upper'], color='#ffec59', alpha=0.3, linewidth=0)\n    \n    plot[1,1].set_xticks(xticks_ar)\n    plot[1,1].set_xticklabels(xticklabels_ar)\n    plot[1,1].set_xticks(xticks_spec, minor=True)\n    plot[1,1].set_xticklabels(xticklabels_spec, minor=True)\n    plot[1,1].tick_params(axis='x', which='minor', length=0)\n    plot[1,1].set_xlabel('Distance, aa')\n    plot[1,1].set_ylabel('Frequency')  \n    plot[1,1].legend(fontsize=8.5, ncol=2, handlelength=0.7, frameon=False, columnspacing=0.7, loc='center')    \n    \n    \n    plt.tight_layout()\n    plt.show()    \n    \n    return\n\n\n#######\n#Enrichment of ss elements at N-terminus over the elements at C-terminus.\n#######\n\ndef N_to_C_enrichment(enrichment_N_to_C_dict_short, enrichment_N_to_C_dict_long, window_width):\n    \n    #Plot enrichment of ss elements as a function of distance from termini.\n    X=range(window_width)\n    xticks_ar=list(range(0,51,10))\n    xticklabels_ar=[0,10,20,30,40,50]\n    xticks_spec=[-4]\n    xticklabels_spec=['N-\\nC-', ]\n    fig, plot=plt.subplots(2,2,figsize=(12,6), dpi=100)\n    plot[0,0].plot(X, enrichment_N_to_C_dict_short['H'], color='#94fff1', linewidth=2, label=r'$\\alpha$-helix short domains')\n    plot[0,0].plot(X, enrichment_N_to_C_dict_long['H'], color='#ab658c', linewidth=2, label=r'$\\alpha$-helix long domains')\n    plot[0,0].plot(X, enrichment_N_to_C_dict_short['E'], color='#59acff', linewidth=2, label=r'$\\beta$-strand short domains')\n    plot[0,0].plot(X, enrichment_N_to_C_dict_long['E'], color='#ffec59', linewidth=2, label=r'$\\beta$-strand long domains')   \n    plot[0,0].set_xticks(xticks_ar)\n    plot[0,0].set_xticklabels(xticklabels_ar)\n    plot[0,0].set_xticks(xticks_spec, minor=True)\n    plot[0,0].set_xticklabels(xticklabels_spec, minor=True)\n    plot[0,0].tick_params(axis='x', which='minor', length=0)\n    plot[0,0].set_xlabel('Distance, aa')\n    plot[0,0].set_ylabel('Enrichment p(N)/p(C)') \n    plot[0,0].legend(fontsize=8.5, ncol=2, handlelength=0.7, frameon=False, columnspacing=0.7, loc='upper center')\n    \n    plot[0,1].plot(X, enrichment_N_to_C_dict_short['B'], color='#94fff1', linewidth=2, label=r'$\\beta$-bridge short domains')\n    plot[0,1].plot(X, enrichment_N_to_C_dict_long['B'], color='#ab658c', linewidth=2, label=r'$\\beta$-bridge long domains')\n    plot[0,1].plot(X, enrichment_N_to_C_dict_short['G'], color='#59acff', linewidth=2, label=r'3-10-helix short domains')\n    plot[0,1].plot(X, enrichment_N_to_C_dict_long['G'], color='#ffec59', linewidth=2, label=r'3-10-helix long domains')   \n    plot[0,1].set_xticks(xticks_ar)\n    plot[0,1].set_xticklabels(xticklabels_ar)\n    plot[0,1].set_xticks(xticks_spec, minor=True)\n    plot[0,1].set_xticklabels(xticklabels_spec, minor=True)\n    plot[0,1].tick_params(axis='x', which='minor', length=0)\n    plot[0,1].set_xlabel('Distance, aa')\n    plot[0,1].set_ylabel('Enrichment p(N)/p(C)')  \n    plot[0,1].legend(fontsize=8.5, ncol=2, handlelength=0.7, frameon=False, columnspacing=0.7, loc='upper center')\n    \n    plot[1,0].plot(X, enrichment_N_to_C_dict_short['I'], color='#94fff1', linewidth=2, label=r'$\\pi$-helix short domains')\n    plot[1,0].plot(X, enrichment_N_to_C_dict_long['I'], color='#ab658c', linewidth=2, label=r'$\\pi$-helix long domains')\n    plot[1,0].plot(X, enrichment_N_to_C_dict_short['T'], color='#59acff', linewidth=2, label=r'turn short domains')\n    plot[1,0].plot(X, enrichment_N_to_C_dict_long['T'], color='#ffec59', linewidth=2, label=r'turn long domains')   \n    plot[1,0].set_xticks(xticks_ar)\n    plot[1,0].set_xticklabels(xticklabels_ar)\n    plot[1,0].set_xticks(xticks_spec, minor=True)\n    plot[1,0].set_xticklabels(xticklabels_spec, minor=True)\n    plot[1,0].tick_params(axis='x', which='minor', length=0)\n    plot[1,0].set_xlabel('Distance, aa')\n    plot[1,0].set_ylabel('Enrichment p(N)/p(C)')  \n    plot[1,0].legend(fontsize=8.5, ncol=2, handlelength=0.7, frameon=False, columnspacing=0.7, loc='upper center')\n    \n    plot[1,1].plot(X, enrichment_N_to_C_dict_short['S'], color='#94fff1', linewidth=2, label=r'bend short domains')\n    plot[1,1].plot(X, enrichment_N_to_C_dict_long['S'], color='#ab658c', linewidth=2, label=r'bend long domains') \n    plot[1,1].plot(X, enrichment_N_to_C_dict_short['-'], color='#59acff', linewidth=2, label=r'unstructured short domains')\n    plot[1,1].plot(X, enrichment_N_to_C_dict_long['-'], color='#ffec59', linewidth=2, label=r'unstructured long domains')  \n    plot[1,1].set_xticks(xticks_ar)\n    plot[1,1].set_xticklabels(xticklabels_ar)\n    plot[1,1].set_xticks(xticks_spec, minor=True)\n    plot[1,1].set_xticklabels(xticklabels_spec, minor=True)\n    plot[1,1].tick_params(axis='x', which='minor', length=0)\n    plot[1,1].set_xlabel('Distance, aa')\n    plot[1,1].set_ylabel('Enrichment p(N)/p(C)')  \n    plot[1,1].legend(fontsize=8.5, ncol=2, handlelength=0.7, frameon=False, columnspacing=0.7, loc='upper center')    \n    \n    \n    plt.tight_layout()\n    plt.show()        \n    \n    return\n\n#######\n#Plot co-occurence of ss elements at termini.\n#######\n\ndef plot_co_occurence(Obs_over_exp_matrices_short, Obs_over_exp_matrices_long, local_window_width):\n    \n    fig, plot=plt.subplots(2,2,figsize=(7,7), dpi=100)\n    ticks_ar=list(range(-1, local_window_width, int(local_window_width/10)))\n    ticks_ar[0]=0\n    print(list(ticks_ar))\n    ticklabels_ar=np.array(list(ticks_ar))+1\n    plot00=plot[0,0].imshow(Obs_over_exp_matrices_short['EH'], cmap='gnuplot', vmin=0.3, vmax=2.1, interpolation='nearest')\n    plot[0,0].set_title(r'$\\beta-\\alpha$ short domains')\n    plo00_cbar=plot[0,0].figure.colorbar(plot00, ax=plot[0,0], shrink=0.7)\n    plot[0,0].set_xticks(ticks_ar)\n    plot[0,0].set_xticklabels(ticklabels_ar) \n    plot[0,0].set_yticks(ticks_ar)\n    plot[0,0].set_yticklabels(ticklabels_ar)    \n    plot[0,0].set_xlabel(r'Distance from C-terminus, aa ($\\alpha$)')\n    plot[0,0].set_ylabel(r'Distance from N-terminus, aa ($\\beta$)')     \n    plo00_cbar.ax.set_ylabel('p(Obs)/p(Exp)', rotation=-90, va=\"bottom\")\n    \n    plot01=plot[0,1].imshow(Obs_over_exp_matrices_long['EH'], cmap='gnuplot', vmin=0.3, vmax=2.1, interpolation='nearest')\n    plot[0,1].set_title(r'$\\beta-\\alpha$-helix long domains')\n    plo01_cbar=plot[0,1].figure.colorbar(plot01, ax=plot[0,1], shrink=0.7)  \n    plot[0,1].set_xticks(ticks_ar)\n    plot[0,1].set_xticklabels(ticklabels_ar) \n    plot[0,1].set_yticks(ticks_ar)\n    plot[0,1].set_yticklabels(ticklabels_ar)    \n    plot[0,1].set_xlabel(r'Distance from C-terminus, aa ($\\alpha$)')\n    plot[0,1].set_ylabel(r'Distance from N-terminus, aa ($\\beta$)')     \n    plo01_cbar.ax.set_ylabel('p(Obs)/p(Exp)', rotation=-90, va=\"bottom\")\n    \n    plot10=plot[1,0].imshow(Obs_over_exp_matrices_short['HE'], cmap='gnuplot', vmin=0.3, vmax=2.1, interpolation='nearest')\n    plot[1,0].set_title(r'$\\alpha-\\beta$-strand short domains')\n    plo10_cbar=plot[0,0].figure.colorbar(plot10, ax=plot[1,0], shrink=0.7)\n    plot[1,0].set_xticks(ticks_ar)\n    plot[1,0].set_xticklabels(ticklabels_ar) \n    plot[1,0].set_yticks(ticks_ar)\n    plot[1,0].set_yticklabels(ticklabels_ar)    \n    plot[1,0].set_xlabel(r'Distance from C-terminus, aa ($\\beta$)')\n    plot[1,0].set_ylabel(r'Distance from N-terminus, aa ($\\alpha$)')     \n    plo10_cbar.ax.set_ylabel('p(Obs)/p(Exp)', rotation=-90, va=\"bottom\")\n    \n    plot11=plot[1,1].imshow(Obs_over_exp_matrices_long['HE'], cmap='gnuplot', vmin=0.3, vmax=2.1, interpolation='nearest')\n    plot[1,1].set_title(r'$\\alpha-\\beta$-strand long domains')\n    plo11_cbar=plot[1,1].figure.colorbar(plot11, ax=plot[1,1], shrink=0.7)  \n    plot[1,1].set_xticks(ticks_ar)\n    plot[1,1].set_xticklabels(ticklabels_ar) \n    plot[1,1].set_yticks(ticks_ar)\n    plot[1,1].set_yticklabels(ticklabels_ar)    \n    plot[1,1].set_xlabel(r'Distance from C-terminus, aa ($\\beta$)')\n    plot[1,1].set_ylabel(r'Distance from N-terminus, aa ($\\alpha$)')     \n    plo11_cbar.ax.set_ylabel('p(Obs)/p(Exp)', rotation=-90, va=\"bottom\")    \n    \n    plt.tight_layout()\n    plt.show()    \n    return\n    \n\n#######\n#Wrapper function.\n#######\n\ndef wrapper(DSSP_inpath):\n    #Define domain length trhresholds.\n    min_len=50\n    thr_len=130\n    \n    #Define distance from termini to analyse.\n    window_width=50\n    local_window_width=50\n    \n    #Read DSSP data.\n    DSSP_data_dict=read_dssp_data(DSSP_inpath)\n    #Classify domains by length.\n    Short_structures, Long_structures=define_length_groups(DSSP_data_dict, min_len, thr_len)\n    \n    #Get phi, psi angles for N- and C-termini.\n    sphi_N, sphi_C, spsi_N, spsi_C, sphi, spsi=phi_psi_N_to_C(Short_structures, window_width)\n    lphi_N, lphi_C, lpsi_N, lpsi_C, lphi, lpsi=phi_psi_N_to_C(Long_structures, window_width)\n    \n    #Compute position frequency matrices.\n    ss_matrix_N_short, ss_matrix_C_short, ss_pfm_N_short, ss_pfm_C_short, ss_pfm_conf_N_short, ss_pfm_conf_C_short=ss_element_frequency_matrix(Short_structures, window_width)\n    ss_matrix_N_long, ss_matrix_C_long, ss_pfm_N_long, ss_pfm_C_long, ss_pfm_conf_N_long, ss_pfm_conf_C_long=ss_element_frequency_matrix(Long_structures, window_width)\n    \n    #Plot frequency of ss elements as a function of a distance from termini.\n    N_to_C_asymmetry(ss_pfm_N_short, ss_pfm_C_short, ss_pfm_conf_N_short, ss_pfm_conf_C_short, ss_pfm_N_long, ss_pfm_C_long, ss_pfm_conf_N_long, ss_pfm_conf_C_long, window_width)\n    \n    #Enrichment of ss elements N- over C-terminus.\n    enrichment_N_to_C_dict_short=ss_ele_enrichment(ss_pfm_N_short, ss_pfm_C_short)\n    enrichment_N_to_C_dict_long=ss_ele_enrichment(ss_pfm_N_long, ss_pfm_C_long)\n    \n    #Plot enrichment of frequency of ss elements at N-terminus over C-terminus.\n    N_to_C_enrichment(enrichment_N_to_C_dict_short, enrichment_N_to_C_dict_long, window_width)\n    \n    #Analyse co-occurence of secondary structure elements at protein termini.\n    Obs_over_exp_matrices_short=termini_dependance(ss_matrix_N_short, ss_matrix_C_short, ss_pfm_N_short, ss_pfm_C_short, local_window_width)\n    Obs_over_exp_matrices_long=termini_dependance(ss_matrix_N_long, ss_matrix_C_long, ss_pfm_N_long, ss_pfm_C_long, local_window_width)\n    \n    #Plot co-occurence of secondary structure elements at protein termini.\n    plot_co_occurence(Obs_over_exp_matrices_short, Obs_over_exp_matrices_long, local_window_width)\n    \n    return\n\nwrapper(DSSP_data_inpath)", "meta": {"hexsha": "794436220fbc8c74dfbc3f5d5e20d2ec9df6f070", "size": 30337, "ext": "py", "lang": "Python", "max_stars_repo_path": "DSSP_statistics.py", "max_stars_repo_name": "sutormin94/N-to-C_asymmetry", "max_stars_repo_head_hexsha": "ed4f9d6ed6c202a46d619d9ebec097134ee04985", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DSSP_statistics.py", "max_issues_repo_name": "sutormin94/N-to-C_asymmetry", "max_issues_repo_head_hexsha": "ed4f9d6ed6c202a46d619d9ebec097134ee04985", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DSSP_statistics.py", "max_forks_repo_name": "sutormin94/N-to-C_asymmetry", "max_forks_repo_head_hexsha": "ed4f9d6ed6c202a46d619d9ebec097134ee04985", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.7307692308, "max_line_length": 179, "alphanum_fraction": 0.687576227, "include": true, "reason": "import numpy,import scipy", "num_tokens": 9440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.18800483976023485}}
{"text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# EFOSC2 polarisation photometry script v1.0\n# Created by Adam Higgins\n# Email: abh13@le.ac.uk\n\n__doc__ = \"\"\" Script runs photometry for the polarisation images from EFOSC2\nand outputs flux information for ordinary and extraordinary beams.\nFor usage please go to https://github.com/abh13/EFOSC2_Scripts.\n\nFile names for each half-wave plate angle should be:\n0ang.fits,\n225ang.fits,\n45ang.fits,\n675ang.fits\n\"\"\"\n\nfrom astropy.io import fits\nfrom astropy.table import vstack\nfrom astropy.stats import sigma_clip\nfrom astropy.stats import sigma_clipped_stats\nfrom astropy.visualization import SqrtStretch\nfrom astropy.visualization import ZScaleInterval\nfrom astropy.visualization.mpl_normalize import ImageNormalize\nfrom photutils import DAOStarFinder\nfrom photutils import CircularAperture\nfrom photutils import aperture_photometry\nfrom photutils import RectangularAnnulus\nfrom photutils.utils import calc_total_error\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport os\nimport sys\nimport argparse\n\n\ndef get_args():\n\t\"\"\" Parse command line arguments \"\"\"\n\tparser = argparse.ArgumentParser(description=__doc__)\n\tparser.add_argument(\"Directory\",metavar=\"DIR\",type=str,action=\"store\",\n\t\thelp=\"Required directory\")\n\tparser.add_argument(\"--ap\",type=float,default=2.0,dest='aperture',\n\t\thelp=\"Source aperture diameter X*FWHM (default = 2.0)\")\n\tparser.add_argument(\"--fwhm\",type=float,default=0,dest='fwhm',\n\t\thelp=\"Manually set the FWHM (default = AUTO)\")\n\t\t\n\targs = parser.parse_args()\n\tfolder_path = args.__dict__['Directory']\n\tapermul = args.aperture\n\tfwhm = args.fwhm\n\treturn folder_path,apermul,fwhm\n\n\ndef efosc2_pol_phot(folder_path,apermul,fwhm):\n\t\"\"\" Script runs photometry for EFOSC2 polarimetry images \"\"\"\n\n\t# Read in four wave plate angle files and set up arrays for later\n\tfile_ang0 = os.path.join(folder_path,'0ang.fits')\n\tfile_ang225 = os.path.join(folder_path,'225ang.fits')\n\tfile_ang45 = os.path.join(folder_path,'45ang.fits')\n\tfile_ang675 = os.path.join(folder_path,'675ang.fits')\n\n\tfiles = [file_ang0,file_ang225,file_ang45,file_ang675]\n\tangle = ['0','225','45','675']\n\tang_dec = ['0','22.5','45','67.5']\n\tlabel = ['$0^{\\circ}$ image','$22.5^{\\circ}$ image',\n\t\t'$45^{\\circ}$ image','$67.5^{\\circ}$ image']\n\t\t\n\t# Set up array to store the number of sources per half-wave plate\n\tnumsource = []\n\t\n\t# Loop over files for the four wave plate files\n\tfor k in range(0,len(angle),1):\n\n\t\t# Open fits file, extract pixel flux data and remove saturated pixels\n\t\ttry:\n\t\t\thdulist = fits.open(files[k])\n\t\t\timage_data = hdulist[0].data\n\t\t\t\n\t\texcept FileNotFoundError:\n\t\t\traise FileNotFoundError(\"Cannot find the input fits file(s).\")\n\t\t\n\t\t# Remove bad pixels and mask edges\n\t\timage_data[image_data > 60000] = 0\n\t\timage_data[image_data < 0] = 0    \n\t\trows = len(image_data[:,0])\n\t\tcols = len(image_data[0,:])\n\t\thdulist.close()\n\n\t\t# Calculate estimate of background using sigma-clipping and calculate\n\t\t# number of pixels used in the background region that were not\n\t\t# clipped! This is done in a small area near the optical axis.\n\t\tgo_bmean, go_bmedian, go_bstd = sigma_clipped_stats(image_data\n\t\t\t[510:568,520:580],sigma=3.0,maxiters=5)\n\t\tge_bmean, ge_bmedian, ge_bstd = sigma_clipped_stats(image_data\n\t\t\t[446:504,520:580],sigma=3.0,maxiters=5)\n\t\tmask_o = sigma_clip(image_data[510:568,520:580],sigma=3.0,maxiters=5,\n\t\t\tmasked=True)\n\t\tmask_e = sigma_clip(image_data[446:504,520:580],sigma=3.0,maxiters=5,\n\t\t\tmasked=True)\n\t\tann_area_o = np.ma.MaskedArray.count(mask_o)\n\t\tann_area_e = np.ma.MaskedArray.count(mask_e)\n\t\t\n\t\t# Detect sources using DAO star finder\n\t\tdaofind_o = DAOStarFinder(fwhm=5,threshold=5*go_bstd,\n\t\t\texclude_border=True)\n\t\tdaofind_e = DAOStarFinder(fwhm=5,threshold=5*ge_bstd,\n\t\t\texclude_border=True)\n\t\tsources_o = daofind_o(image_data[522:552,535:565])\n\t\tsources_e = daofind_e(image_data[462:492,535:565])\n\t\t\n\t\tif (sources_o is None or sources_e is None):\n\t\t\traise ValueError(\"No source detected in image\")\n\t\t\t\n\t\tif len(sources_o) != len(sources_e):\n\t\t\traise ValueError(\"Unequal number of sources in o and e images!\")\n\t\t\n\t\tglob_bgm = [go_bmean,ge_bmean]\n\t\tglob_bgerr = [go_bstd,ge_bstd]\n\t\t\n\t\t# Convert the source centroids back into detector pixels\n\t\tsources_o['xcentroid'] = sources_o['xcentroid'] + 535\n\t\tsources_o['ycentroid'] = sources_o['ycentroid'] + 522\n\t\tsources_e['xcentroid'] = sources_e['xcentroid'] + 535\n\t\tsources_e['ycentroid'] = sources_e['ycentroid'] + 462\n\n\t\t# Estimate the FWHM of the source by simulating a 2D Gaussian\n\t\t# This is only done on the 0 angle image ensuring aperture sizes\n\t\t# are equal for all half-wave plate angles. If a user specified\n\t\t# FWHM is given, then the estimation is not used.\n\t\tif fwhm == 0.0:\n\t\t\txpeaks_o = []\n\t\t\txpeaks_e = []\n\t\t\typeaks_o = []\n\t\t\typeaks_e = []\n\t\t\tfwhm = []\n\t\t\t\n\t\t\tfor i in range(0,len(sources_o),1):\t\t\t\n\t\t\t\tdata_o = image_data[525:550,535:565]\n\t\t\t\txpeaks_o.append(int(sources_o[i]['xcentroid']) - 535)\n\t\t\t\typeaks_o.append(int(sources_o[i]['ycentroid']) - 525)\n\t\t\t\t\t\n\t\t\t\tdata_e = image_data[465:490,535:560]\n\t\t\t\txpeaks_e.append(int(sources_e[i]['xcentroid']) - 535)\n\t\t\t\typeaks_e.append(int(sources_e[i]['ycentroid']) - 465)\n\t\t\t\t\n\t\t\t\tmin_count_o = np.min(data_o)\n\t\t\t\tmin_count_e = np.min(data_e)\n\t\t\t\tmax_count_o = data_o[ypeaks_o[i],xpeaks_e[i]]\n\t\t\t\tmax_count_e = data_e[ypeaks_o[i],xpeaks_e[i]]\n\t\t\t\thalf_max_o = (max_count_o + min_count_o)/2\n\t\t\t\thalf_max_e = (max_count_e + min_count_e)/2\n\t\t\t\t\n\t\t\t\t# Crude calculation for each source\n\t\t\t\tnearest_above_x_o = ((np.abs(data_o[ypeaks_o[i],\n\t\t\t\t\txpeaks_o[i]:-1] - half_max_o)).argmin())\n\t\t\t\tnearest_below_x_o = ((np.abs(data_o[ypeaks_o[i],0:\n\t\t\t\t\txpeaks_o[i]] - half_max_o)).argmin())\n\t\t\t\tnearest_above_x_e = ((np.abs(data_e[ypeaks_e[i],\n\t\t\t\t\txpeaks_e[i]:-1] - half_max_e)).argmin())\n\t\t\t\tnearest_below_x_e = ((np.abs(data_e[ypeaks_e[i],0:\n\t\t\t\t\txpeaks_e[i]] - half_max_e)).argmin())\n\t\t\t\tnearest_above_y_o = ((np.abs(data_o[ypeaks_o[i]:-1,\n\t\t\t\t\txpeaks_o[i]] - half_max_o)).argmin())\n\t\t\t\tnearest_below_y_o = ((np.abs(data_o[0:ypeaks_o[i],\n\t\t\t\t\txpeaks_o[i]] - half_max_o)).argmin())\n\t\t\t\tnearest_above_y_e = ((np.abs(data_e[ypeaks_e[i]:-1,\n\t\t\t\t\txpeaks_e[i]] - half_max_e)).argmin())\n\t\t\t\tnearest_below_y_e = ((np.abs(data_e[0:ypeaks_e[i],\n\t\t\t\t\txpeaks_e[i]] - half_max_e)).argmin())\n\t\t\t\tfwhm.append((nearest_above_x_o + (xpeaks_o[i] -\n\t\t\t\t\tnearest_below_x_o)))\n\t\t\t\tfwhm.append((nearest_above_y_o + (ypeaks_o[i] -\n\t\t\t\t\tnearest_below_y_o)))\n\t\t\t\tfwhm.append((nearest_above_x_e + (xpeaks_e[i] -\n\t\t\t\t\tnearest_below_x_e)))\n\t\t\t\tfwhm.append((nearest_above_y_e + (ypeaks_e[i] -\n\t\t\t\t\tnearest_below_y_e)))\n\t\t\t\n\t\t\tfwhm = np.mean(fwhm)\n\t\t\n\t\t# Stack both ord and exord sources together\n\t\ttot_sources = vstack([sources_o,sources_e])\n\t\t\t\t\n\t\t# Store the ordinary and extraordinary beam source images and\n\t\t# create apertures for aperture photometry \n\t\tpositions = np.swapaxes(np.array((tot_sources['xcentroid'],\n\t\t\ttot_sources['ycentroid']),dtype='float'),0,1)\n\t\taperture = CircularAperture(positions, r=0.5*apermul*fwhm)\n\t\tphot_table = aperture_photometry(image_data,aperture)   \n\t\t\t\t\t  \n\t\t# Set up arrays of ord and exord source parameters\n\t\ts_id = np.zeros([len(np.array(phot_table['id']))])\n\t\txp = np.zeros([len(s_id)])\n\t\typ = np.zeros([len(s_id)])\n\t\tfluxbgs = np.zeros([len(s_id)])\n\t\tmean_bg = np.zeros([len(s_id)])\n\t\tbg_err = np.zeros([len(s_id)])\n\t\ts_area = []\n\t\t\n\t\tfor i in range(0,len(np.array(phot_table['id'])),1):\n\t\t\ts_id[i] = np.array(phot_table['id'][i])\n\t\t\txpos = np.array(phot_table['xcenter'][i])\n\t\t\typos = np.array(phot_table['ycenter'][i])\n\t\t\txp[i] = xpos\n\t\t\typ[i] = ypos\n\t\t\ts_area.append(np.pi*(0.5*apermul*fwhm)**2)\n\t\t\tj = i%2\t\t\t\t\n\t\t\tfluxbgs[i] = (phot_table['aperture_sum'][i] -\n\t\t\t\taperture.area*glob_bgm[j])\n\t\t\tmean_bg[i] = glob_bgm[j]\n\t\t\tbg_err[i] = glob_bgerr[j]\t\t\t\n\t\t\n\t\t# Create and save the image in z scale and overplot the ordinary and\n\t\t# extraordinary apertures and local background annuli if applicable\n\t\tfig = plt.figure()\n\t\tzscale = ZScaleInterval(image_data)\n\t\tnorm = ImageNormalize(stretch=SqrtStretch(),interval=zscale)\n\t\timage = plt.imshow(image_data,cmap='gray',origin='lower',norm=norm)\n\t\tbg_annulus_o = RectangularAnnulus((550,539),w_in=0.1,w_out=60,h_out=58,\n\t\t\ttheta=0)\n\t\tbg_annulus_e = RectangularAnnulus((550,475),w_in=0.1,w_out=60,h_out=58,\n\t\t\ttheta=0)\n\t\tbg_annulus_o.plot(color='skyblue',lw=1.5,alpha=0.5)\n\t\tbg_annulus_e.plot(color='lightgreen',lw=1.5,alpha=0.5)\n\t\t\n\t\tfor i in range(0,len(np.array(phot_table['id'])),1):\n\t\t\taperture = CircularAperture((xp[i],yp[i]),r=0.5*apermul*fwhm)\n\t\t\t\n\t\t\tif i < int(len(np.array(phot_table['id']))/2):\n\t\t\t\taperture.plot(color='blue',lw=1.5,alpha=0.5)\n\t\t\n\t\t\telse:\n\t\t\t\taperture.plot(color='green',lw=1.5,alpha=0.5)\n\t\t\t\n\t\tplt.xlim(500,600)\n\t\tplt.ylim(425,575)\n\t\tplt.title(label[k])\n\t\timage_fn = folder_path + angle[k] + '_image.png'\n\t\tfig.savefig(image_fn)\n\n\t\t# Create dataframes for photometry results\n\t\tcols = ['xpix','ypix','fluxbgs','sourcearea','meanbg','bgerr',\n\t\t\t'bgarea']\n\t\tdf_o = pd.DataFrame(columns=cols)\n\t\tdf_e = pd.DataFrame(columns=cols)\n\t\t\n\t\tfor i in range(0,len(np.array(phot_table['id'])),1):\n\t\t\tif 0 <= i < int(len(np.array(phot_table['id']))/2):\n\t\t\t\tdf_o = df_o.append({cols[0]:xp[i],cols[1]:yp[i],\n\t\t\t\t\tcols[2]:fluxbgs[i],cols[3]:s_area[i],cols[4]:mean_bg[i],\n\t\t\t\t\tcols[5]:bg_err[i],cols[6]:ann_area_o},ignore_index=True)\n\t\t\t\t\t\n\t\t\telse:\n\t\t\t\tdf_e = df_e.append({cols[0]:xp[i],cols[1]:yp[i],\n\t\t\t\t\tcols[2]:fluxbgs[i],cols[3]:s_area[i],cols[4]:mean_bg[i],\n\t\t\t\t\tcols[5]:bg_err[i],cols[6]:ann_area_e},ignore_index=True)\n\t\t\n\t\t# Save dataframes to text files\n\t\tdf_o.to_string(folder_path+'angle'+angle[k]+'_ord.txt',\n\t\t\tindex=False,justify='left')\n\t\t\n\t\tdf_e.to_string(folder_path+'angle'+angle[k]+'_exord.txt',\n\t\t\tindex=False,justify='left')\n\t\t\n\t\t# Save the number of sources in each beam to a list\n\t\tnumsource.append(int(len(np.array(phot_table['id']))/2))\n\t\n\t# Print number of sources per half-wave plate image and FWHM\n\tprint(\"FWHM =\",fwhm,\"pixels\")\n\tfor i in range(0,len(numsource),1):\n\t\tprint(\"No of sources detected at\",ang_dec[i],\"degrees:\",numsource[i])\n\t\n\treturn 0\n\n\t\ndef main():\n\t\"\"\" Run script from command line \"\"\"\n\tfolder_path,apermul,fwhm = get_args()\n\treturn efosc2_pol_phot(folder_path,apermul,fwhm)\n\n\t\nif __name__ == '__main__':\n    sys.exit(main())", "meta": {"hexsha": "6eb51a8ac2cad1cac31968a083755ddd789451ad", "size": 10231, "ext": "py", "lang": "Python", "max_stars_repo_path": "EFOSC2_Pol_Phot.py", "max_stars_repo_name": "abh13/EFOSC2_Scripts", "max_stars_repo_head_hexsha": "aec90a61abe670a83d296aadcdd6dbf1669fa64c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EFOSC2_Pol_Phot.py", "max_issues_repo_name": "abh13/EFOSC2_Scripts", "max_issues_repo_head_hexsha": "aec90a61abe670a83d296aadcdd6dbf1669fa64c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EFOSC2_Pol_Phot.py", "max_forks_repo_name": "abh13/EFOSC2_Scripts", "max_forks_repo_head_hexsha": "aec90a61abe670a83d296aadcdd6dbf1669fa64c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.898245614, "max_line_length": 76, "alphanum_fraction": 0.6981722217, "include": true, "reason": "import numpy,from astropy", "num_tokens": 3207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.32766831395172374, "lm_q1q2_score": 0.18797623652047382}}
{"text": "import csv, json, argparse, copy, re, os, urllib2\n\nimport numpy as np\nfrom scipy.spatial import distance\nfrom sklearn import manifold, metrics, decomposition, preprocessing\n\nimport igraph\n\nimport jsmin\n\nimport rdkit\nfrom rdkit import Chem, DataStructs, Geometry\nfrom rdkit.DataStructs import cDataStructs\nfrom rdkit.Chem import Draw, AllChem, Scaffolds, Lipinski, Crippen, rdMolDescriptors, TemplateAlign\nfrom rdkit.Chem.Scaffolds import MurckoScaffold\n\nPROPS_ORDER = [\"mw\", \"hba\", \"hbd\", \"rb\", \"rc\", \"arc\", \"logp\", \"tpsa\"]\n        \nPROP2FNC = {\n    \"mw\": rdMolDescriptors.CalcExactMolWt,\n    \"hba\": Lipinski.NumHAcceptors,\n    \"hbd\": Lipinski.NumHDonors,\n    \"rb\": Lipinski.NumRotatableBonds,\n    \"rc\": Lipinski.RingCount,\n    \"arc\": Lipinski.NumAromaticRings,\n    \"logp\": Crippen.MolLogP, \n    \"tpsa\": rdMolDescriptors.CalcTPSA,\n}\n\nPROP2LABEL = {\n    \"mw\": \"Molecular weight\",\n    \"hba\": \"H-bond acceptors\",\n    \"hbd\": \"H-bond donors\",\n    \"rb\": \"Rotatable bonds\",\n    \"rc\": \"Rings\",\n    \"arc\": \"Aromatic rings\",\n    \"logp\": \"cLogP\",\n    \"tpsa\": \"TPSA\"\n}\n\nFP2FNC = {\n    \"ecfp4\": lambda rdmol: AllChem.GetMorganFingerprintAsBitVect(rdmol, radius=2, nBits=1024),\n    \"ecfp6\": lambda rdmol: AllChem.GetMorganFingerprintAsBitVect(rdmol, radius=3, nBits=1024),\n    \"apfp\": lambda rdmol: AllChem.GetHashedAtomPairFingerprintAsBitVect(rdmol, nBits=1024),\n    \"ttfp\": lambda rdmol: AllChem.GetHashedTopologicalTorsionFingerprintAsBitVect(rdmol, nBits=1024),\n    \"maccs\": lambda rdmol: AllChem.GetMACCSKeysFingerprint(rdmol),\n}\n\nAVAILABLE_METRICS = [\"Tanimoto\", \"Dice\", \"Cosine\", \"Sokal\", \"Russel\", \"RogotGoldberg\", \"AllBit\", \"Kulczynski\", \"McConnaughey\", \"Asymmetric\", \"BraunBlanquet\"]\n\nclass ChemSpace():\n\n    def __init__(self):\n        self.category_field = False\n        self.category_field_delimiter = False\n        self.label_field = False\n        self.compound_structure_field = False\n        self.sdf = False\n        self.write_structures = True\n        self.fp = \"ecfp4\"\n        self.fingerprint_field = False\n        self.metric = \"Tanimoto\"\n\n        if self.metric not in AVAILABLE_METRICS:\n            raise Exception(\"Metric '{}' not found in available similarity metrics: {}\".format(self.metric, AVAILABLE_METRICS))\n\n        self.index2rdmol = {}\n        self.index2fpobj = {}\n\n    def read_csv(self, filename, delimiter=\",\", header=False, missing_value=False, remove_columns=False):\n        \"\"\"Reads data from the CSV file\"\"\"\n        print(\"Reading file: {}\".format(filename))\n\n        self.filename = filename\n        with open(self.filename, \"r\") as input_file:\n            reader = csv.reader(input_file, delimiter=delimiter)\n            rows = [row for row in reader]\n        \n        self.read_data(rows, header, missing_value, remove_columns)\n\n    def read_sdf(self, filename):\n        \"\"\"Reads data from a sdf file\"\"\"\n        print(\"Reading file: {}\".format(filename))\n        self.sdf = True\n        self.header = False\n        self.data = []\n        self.filename = filename\n        self.index2rdmol = {}\n        self.index2fpobj = {}\n        self.index2props = {}\n        self.index2category = {}\n        self.index2label = {}\n        self.index2id = {}\n\n        molsupplier = Chem.SDMolSupplier(str(filename))\n        not_parsed = []\n\n        for index, m in enumerate(molsupplier):\n            try:\n                Chem.SanitizeMol(m)\n                self.index2rdmol[index] = m\n                self.index2fpobj[index] = FP2FNC[self.fp](m)\n                self.index2props[index] = m.GetPropsAsDict()\n                self.index2id[index] = index\n\n            except Exception, e:\n                print(e)\n                not_parsed.append(index)\n\n        self.index_order = self.index2rdmol.keys()\n        self.index_order.sort()\n        self.index2row = {i: [] for i in self.index_order}\n        self.data = self.index2row.values()\n\n        if self.label_field is not False and self.label_field in self.index2props[self.index_order[0]]:\n            self.index2label = {i: self.index2props[i].get(self.label_field) for i in self.index_order}\n\n        if self.category_field is not False and self.category_field in self.index2props[self.index_order[0]]:\n            self.index2category = {i: self.index2props[i].get(self.category_field) for i in self.index_order}\n\n        self.__create_chemspace_format__()\n\n    def add_compounds_from_file(self, filename, delimiter=\",\"):\n        print(\"Reading compounds: {}\".format(filename))\n        self.filename = filename\n\n        with open(self.filename, \"r\") as input_file:\n            reader = csv.reader(input_file, delimiter=delimiter)\n            rows = [row for row in reader]\n\n        self.add_compounds(rows)\n\n    def add_category(self, category):\n        if not \"categories\" in self.chemical_space:\n            self.chemical_space[\"categories\"] = []\n\n        self.chemical_space[\"categories\"].append(category)\n\n\n    def add_compounds(self, rows):\n        \"\"\"Reads data in a form of list of lists (tuples)\"\"\"\n        self.compounds = {r[0]: r[1] for r in rows}\n        self.chemical_space[\"compounds\"] = {}\n        self.__parse_compounds__()\n\n        for key in self.chemical_space[\"points\"]:\n            if key in self.id2rdmol:\n                self.chemical_space[\"compounds\"][key] = {\"structure\": self.__get_compound__(key)}\n\n    def read_data(self, rows, header=False, missing_value=False, remove_columns=False):\n        \"\"\"Reads data in a form of list of lists (tuples)\"\"\"\n        self.header = header\n        self.missing_value = missing_value\n        data_start = 0\n\n        self.data = rows\n        self.index2id = {}\n        self.index2row = {}\n        self.index2compound = {}\n        self.index2label = {}\n        self.index2category = {}\n\n        if self.header:\n            self.header = self.data[0]\n            self.data = self.data[1:]\n\n        if self.header:\n            if remove_columns is not False and len(remove_columns) > 0:\n                for col in remove_columns:\n                    self.__remove_field__(col)\n\n            if self.compound_structure_field and self.compound_structure_field in self.header:\n                self.index2compound = self.__extract_field__(self.compound_structure_field)\n                self.__read_compounds__()\n\n            if self.label_field and self.label_field in self.header:\n                self.index2label = self.__extract_field__(self.label_field)\n\n            if self.category_field and self.category_field in self.header:\n                self.index2category = self.__extract_field__(self.category_field)\n\n            if self.fingerprint_field and self.fingerprint_field in self.header:\n                self.index2fp = self.__extract_field__(self.fingerprint_field)\n                self.index2fpobj = {}\n\n                for index, fp in self.index2fp.items():\n                    self.index2fpobj[index] = self.__get_bitvect_for_fp__(fp)\n\n            # remove ID field\n            self.header.pop(0)\n\n        self.index2id = {i: row[0] for i, row in enumerate(self.data)}\n        self.index2row = {i: [round(float(v), 2) if v not in [\"\", None, \"None\", self.missing_value] else None for v in row[1:]] for i, row in enumerate(self.data)}\n        self.index_order = [i for i, row in enumerate(self.data)]\n        self.data = [self.index2row[i] for i in self.index_order]\n        \n        if self.missing_value is not False:\n            self.data, self.missing_values_indexes = self.__impute_missing_values__(self.data)\n            # self.original_data = self.__return_missing_values__(copy.deepcopy(self.data), self.missing_values_indexes)\n\n        # self.original_data = copy.deepcopy(self.index2row)        \n        self.__create_chemspace_format__()\n\n    def __read_compounds__(self):\n        for i, smi in self.index2compound.items():\n            try:\n                self.index2rdmol[i] = Chem.MolFromSmiles(smi)\n                self.index2fpobj[i] = FP2FNC[self.fp](self.index2rdmol[i])\n\n            except Exception, e:\n                print(e)\n                self.index2rdmol[i] = None\n                self.index2fpobj[i] = None\n\n    def __remove_field__(self, field):\n        if field in self.header:\n            index = self.header.index(field)\n\n            if index is not False:\n                self.header.pop(index)\n\n                for i, row in enumerate(self.data):\n                    self.data[i].pop(index)\n\n    def __extract_field__(self, field):\n        index2value = {}\n\n        if field in self.header:\n            index = self.header.index(field)\n\n            if index is not False:\n                self.header.pop(index)\n\n                for i, row in enumerate(self.data):\n                    index2value[i] = row[index]\n                    self.data[i].pop(index)\n\n        return index2value\n\n    def __impute_missing_values__(self, data):\n        datatype2impute = {\"numeric\": {\"strategy\":\"mean\", \n                                        \"value\": lambda x: round(float(value), 3)}, \n                           \"binary\": {\"strategy\":\"most_frequent\", \n                                      \"value\": lambda x: int(value)}\n                           }\n\n        missing_values_indexes = []\n        \n        for i, row in enumerate(self.data):\n            missing_values_indexes.append([j for j, v in enumerate(row) if v == self.missing_value])\n\n            for j, value in enumerate(row):\n                if value == self.missing_value:\n                    data[i][j] = np.nan\n        imputer = preprocessing.Imputer(missing_values=\"NaN\", strategy=datatype2impute[\"numeric\"][\"strategy\"])\n        #error when using median strategy - minus one dimension in imputed data... omg\n        imputed_data = [list(row) for row in imputer.fit_transform(self.data)]\n        imputed_data = [[datatype2impute[\"numeric\"][\"value\"](value) for value in row] for row in imputed_data]\n        return imputed_data, missing_values_indexes\n\n    def __return_missing_values__(self, data, missing_values_indexes):\n        for i, indexes in enumerate(missing_values_indexes):\n            if indexes:\n                for index in indexes:\n                    data[i][index] = None\n        return data\n\n    def __create_chemspace_format__(self):\n        self.chemical_space = {\"points\": {}}\n\n        for index in self.index_order:\n            self.chemical_space[\"points\"][index] = {\"object_ids\": [self.index2id[index]]}\n\n        if len(self.index2category):\n            self.__parse_categories__()\n\n        if len(self.index2label):\n            for index, label in self.index2label.items():\n                self.chemical_space[\"points\"][index][\"label\"] = label\n        \n        for index, row in self.index2row.items():\n            self.chemical_space[\"points\"][index][\"features\"] = copy.copy(row)\n\n        if self.header:\n            current_header = self.chemical_space.get(\"feature_names\", [])\n            current_header.extend(self.header)\n            self.chemical_space[\"feature_names\"] = current_header\n\n        if len(self.index2rdmol) and self.write_structures:\n            self.chemical_space[\"compounds\"] = {}\n\n            for index, rdmol in self.index2rdmol.items():\n                # self.chemical_space[\"compounds\"][index] = {\"structure\": self.__get_compound__(rdmol), \"smiles\": Chem.MolToSmiles(rdmol, True)}\n\n                self.chemical_space[\"compounds\"][index] = {\"smiles\": Chem.MolToSmiles(rdmol, True)}\n\n    def __parse_categories__(self):\n        category2ids = {}\n        \n        for index, category in self.index2category.items():\n            categories = [category] if self.category_field_delimiter is False else [c.strip() for c in category.split(self.category_field_delimiter)]\n\n            for c in categories:\n                if c in category2ids:\n                    category2ids[c].add(index)\n                else:\n                    category2ids[c] = {index}\n        \n        if not \"categories\" in self.chemical_space:\n            self.chemical_space[\"categories\"] = []\n\n        for c, ids in category2ids.items():\n            self.chemical_space[\"categories\"].append({\"label\": c, \"points\": list(ids)})\n\n    def add_paths(self, paths):\n        if not self.chemical_space.get(\"paths\", False):\n            self.chemical_space[\"paths\"] = []\n\n        self.chemical_space[\"paths\"].extend(paths)\n\n    def add_paths_from_file(self):\n        pass\n\n    def add_physico_chemical_properties(self):\n        print(\"Calculating physico-chemical properties: {} compounds\".format(len(self.index2rdmol)))\n        self.pcp = True\n        if len(self.index2rdmol):\n            count = len(self.index2rdmol)\n            i = 0\n\n            id2pcp = {}\n            for index, rdmol in self.index2rdmol.items():\n                if i%100 == 0 or i == count:\n                    print(\"{}/{}\".format(i, count))\n\n                id2pcp[index] = self.__get_pcp_for_rdmol__(rdmol)\n                i+=1\n\n            empty = [None for x in PROP2LABEL]\n            for i, index in enumerate(self.index_order):\n                \n                if id2pcp.get(index, False):\n                    pcps = id2pcp[index]\n                else:\n                    pcps = empty\n                \n                self.chemical_space[\"points\"][index][\"features\"].extend(pcps)\n                self.data[i].extend(pcps)                \n\n            current_header = self.chemical_space.get(\"feature_names\", [])\n            current_header.extend([PROP2LABEL[prop] for prop in PROPS_ORDER])\n            self.chemical_space[\"feature_names\"] = current_header\n            self.original_data = copy.deepcopy(self.data)\n\n    def __get_pcp_for_rdmol__(self, rdmol):\n        return [round(PROP2FNC[prop](rdmol), 2) for prop in PROPS_ORDER]\n\n    def __get_compound__(self, rdmol):\n        if rdmol is not None:\n            Chem.Kekulize(rdmol)\n            AllChem.Compute2DCoords(rdmol)\n            compound = {\"atoms\": {}}\n            atoms = [a for a in rdmol.GetAtoms()]\n            bond_types = []\n            for i, a in enumerate(atoms, 1):\n                number = a.GetIdx()\n                position = rdmol.GetConformer().GetAtomPosition(number)\n\n                compound[\"atoms\"][number] = {\n                    \"bonds\": {b.GetEndAtomIdx():b.GetBondTypeAsDouble() for b in a.GetBonds() if b.GetEndAtomIdx() != number},\n                    \"symbol\": a.GetSymbol(),\n                    \"charge\": a.GetFormalCharge(),\n                    \"coordinates\": [round(position.x, 3), round(position.y, 3)]\n                }\n\n                bond_types.extend(compound[\"atoms\"][number][\"bonds\"].values())\n        else:\n            compound = None\n\n        return compound\n\n    def normalize_data(self, feature_range=(0,1)):\n        \"\"\"Normalizes data to a scale from 0 to 1.\"\"\"\n        print(\"Data normalization (scale): {}\".format(feature_range))\n\n        min_max_scaler = preprocessing.MinMaxScaler(feature_range)\n        self.data = min_max_scaler.fit_transform(self.data)\n        self.data = [[round(v, 3) for v in row] for row in self.data]\n\n    def __calculate_distance_matrix__(self, similarity_threshold):\n        print(\"\\nCalculating distance matrix: {} compounds\".format(len(self.index2fpobj)))\n\n        self.dist_matrix = {x:[] for x in self.index_order}\n        self.edges = []\n        self.index2edges = {}\n\n        fps_count = len(self.index_order)\n        \n        for i, index_1 in enumerate(self.index_order):\n            self.index2edges[index_1] = []\n\n            if i%100 == 0 or i == fps_count:\n                print(\"{}/{}\".format(i, fps_count))\n            \n            for j, index_2 in enumerate(self.index_order[i:], i):\n                sim = DataStructs.FingerprintSimilarity(self.index2fpobj[index_1], self.index2fpobj[index_2], metric=getattr(DataStructs, \"{}Similarity\".format(self.metric)))\n                self.dist_matrix[index_1].append(1-sim)\n                \n                if index_1 != index_2:\n                    self.dist_matrix[index_2].append(1-sim)\n\n                    if sim >= similarity_threshold:\n                        self.edges.append((index_1, index_2))\n                        self.index2edges[index_1].append([index_2])\n\n    def __get_edges__(self, similarity_threshold=0.7, k=2):\n        print(\"\\nCalculating edges [similarity threshold={}]: {} compounds\".format(similarity_threshold, len(self.index2fpobj)))\n        self.edges = []\n        self.index2edges = {}\n        count = len(self.index_order)\n\n        for i, index in enumerate(self.index_order):\n            if (i+1)%100 == 0:\n                print(\"{}/{}\".format(i, count))\n\n            values = [[idx, v] for idx, v in zip(self.index_order, self.dist_matrix[index]) if idx != index]\n            values.sort(key=lambda x: x[1])\n\n            if 1-values[1][1] >= similarity_threshold: \n                self.index2edges[index] = []\n\n                for v in values:\n                    if 1-v[1] >= similarity_threshold:\n                        self.edges.append((index, v[0]))\n                        self.index2edges[index].append([v[0]])\n\n                        if len(self.index2edges[index]) == k:\n                            break\n                    else:\n                        break\n\n        print(\"EDGES: {}\".format(len(self.edges)))\n        \n    def __convert_fps_to_bitvects__(self, fps):\n        converted = []\n\n        for fp in fps:\n            row = [fp[0], self.__get_bitvect_for_fp__(fp[1:])]\n            converted.append(row)\n\n        return converted\n\n    def __get_bitvect_for_fp__(self, fp):\n        if type(fp) is list and len(fp) == 1:\n            fp = fp[0]\n        bitvect = cDataStructs.ExplicitBitVect(len(fp))\n        on_indexes = [i for i, b in enumerate(fp) if int(b) == 1]\n        bitvect.SetBitsFromList(on_indexes)\n        return bitvect\n\n    def arrange(self, by=\"fps\", fps=[], method=\"pca\", similarity_threshold=0.7, add_edges=False, k=None):\n        self.index2edges = False\n        self.edges = False\n        self.dist_matrix = False\n        bitvects = False\n\n        if type(method) is not list:\n            methods = [method]\n        else:\n            methods = method\n\n        for method in methods:\n            if by == \"scaffolds\":\n                self.__arrange_by_scaffolds__()\n\n                g = igraph.Graph(len(self.index_order))\n                print(\"\\nCalculating Chemical Space Network...\")\n                feature_names = [\"CSN1\", \"CSN2\"]\n\n                g.add_edges(self.edges)\n                layout = g.layout_fruchterman_reingold()\n                coords = layout.coords\n\n            elif by == \"dm\" or method == \"sas\":\n                if len(fps) == 0:\n                    for index in self.index_order:\n                        fps.append(self.index2fpobj[index])\n                    bitvects = True\n                        \n                elif type(fps[0][1]) in [unicode, int] and not bitvects:\n                    fps = self.__convert_fps_to_bitvects__(fps)\n                    bitvects = True\n\n                if not self.dist_matrix:\n                    self.__calculate_distance_matrix__(similarity_threshold)\n\n                dist_matrix = np.matrix([np.array(self.dist_matrix[index]) for index in self.index_order])\n                g = igraph.Graph(len(self.index_order))\n\n                if method == \"csn\":\n                    print(\"\\nCalculating Chemical Space Network...\")\n                    feature_names = [\"CSN1\", \"CSN2\"]\n                    if k is not None:\n                        # k = len(self.index_order)\n                        self.__get_edges__(similarity_threshold=similarity_threshold, k=k)\n\n                    print(\"Fruchterman-Reingold Layout calculation...\")\n                    g.add_edges(self.edges)\n                    layout = g.layout_fruchterman_reingold()\n                    coords = layout.coords\n\n                elif method == \"mds\":\n                    print(\"\\nCalculating MDS...\")\n                    feature_names = [\"MDS1\", \"MDS2\"]\n                    # sklearn implementation\n                    mds = manifold.MDS(n_components=2, dissimilarity='precomputed')\n                    coords = mds.fit_transform(dist_matrix)\n\n                    # igraph implementation\n                    # layout = g.layout_mds(dist_matrix, 2, arpack_options=igraph.ARPACKOptions(iter=1000))\n                    # coords = layout.coords\n\n                elif method == \"pca\":\n                    print(\"\\nCalculating PCA...\")\n                    feature_names = [\"PC1\", \"PC2\"]\n                    pca = decomposition.PCA(n_components=2)\n                    coords = pca.fit_transform(dist_matrix)\n\n                elif method == \"fa\":\n                    print(\"\\nCalculating Factor Analysis...\")\n                    feature_names = [\"FA1\", \"FA2\"]\n                    fa = decomposition.FactorAnalysis(n_components=2)\n                    coords = fa.fit_transform(dist_matrix)\n\n                elif method == \"isomap\":\n                    print(\"\\nCalculating Isomap...\")\n                    feature_names = [\"Isomap1\", \"Isomap2\"]\n                    isomap = manifold.Isomap(n_neighbors=200, n_components=2)\n                    coords = isomap.fit_transform(dist_matrix)\n\n                elif method == \"tsne\":\n                    print(\"\\nCalculating t-SNE...\")\n                    feature_names = [\"t-SNE1\", \"t-SNE2\"]\n                    tsne = manifold.TSNE(n_components=2, metric='precomputed')\n                    coords = tsne.fit_transform(dist_matrix)\n\n                elif method == \"sas\":\n                    print(\"\\nCalculating SAS...\")\n                    feature_names = [\"Similarity\", \"Activity difference\"]\n                    self.chemical_space = {\"points\": {}, \"feature_names\": [\"SALI\"]}\n                    ai = self.header.index(self.activity_field)\n                    ids = []\n                    coords = []\n                    \n                    for i, index_1 in enumerate(self.index_order[:-1]):\n                        for j, index_2 in enumerate(self.index_order[i:], i):\n                            if i != j:\n                                activity_diff = round(abs(float(self.data[i][ai]) - float(self.data[j][ai])), 2)\n                                distance = self.dist_matrix[i][j]\n                                distance = distance if distance > 0 else 0.01\n\n                                sali = round(activity_diff/distance, 2)\n                                coord = [round(1 - self.dist_matrix[i][j], 2), activity_diff]\n                                self.chemical_space[\"points\"][\"{}_{}\".format(index_1, index_2)] = {\"features\": [sali]}\n                                ids.append(\"{}_{}\".format(index_1, index_2))\n                                coords.append(coord)\n\n                    self.index_order = ids\n\n            elif by in [\"data\", \"fps\"]:\n                if by == \"fps\":\n                    if len(fps) == 0 and len(self.index2fpobj):\n                        for index in self.index_order:\n                            fps.append(self.index2fpobj[index])\n                    \n                    data = [[int(b) for b in fp] for fp in fps]\n                else:\n                    data = self.data\n\n                if method == \"pca\":\n                    print(\"\\nCalculating PCA...\")\n                    feature_names = [\"PC1\", \"PC2\"]\n                    pca = decomposition.PCA(n_components=2)\n                    coords = pca.fit_transform(data)\n\n                elif method == \"fa\":\n                    print(\"\\nCalculating Factor Analysis...\")\n                    feature_names = [\"FA1\", \"FA2\"]\n                    fa = decomposition.FactorAnalysis(n_components=2)\n                    coords = fa.fit_transform(data)\n\n            if method in [\"csn\", \"nn\"] or add_edges or by == \"scaffolds\":\n                if self.dist_matrix is False and self.edges is False:\n                    self.__calculate_distance_matrix__()\n\n                if self.edges is False:\n                    if k is None:\n                        k = len(self.index_order)\n                    self.__get_edges__(similarity_threshold=similarity_threshold, k=k)\n\n                if by != \"scaffolds\":\n                    for cid, es in self.index2edges.items():\n                        if not self.chemical_space[\"points\"][cid].get(\"links\", False):\n                            self.chemical_space[\"points\"][cid][\"links\"] = []\n\n                        for e in es:\n                            self.chemical_space[\"points\"][cid][\"links\"].extend(e)\n\n            index2coords = {index:coords[i] for i, index in enumerate(self.index_order)}\n\n            for index, values in self.chemical_space[\"points\"].items():\n                if index in index2coords:\n                    point_features = self.chemical_space[\"points\"][index][\"features\"]\n                    features = [round(index2coords[index][0], 3), round(index2coords[index][1], 3)]\n                    features.extend(point_features)\n                    self.chemical_space[\"points\"][index][\"features\"] = features\n\n                else:\n                    self.chemical_space[\"points\"].pop(index, None)\n\n            feature_names.extend(self.chemical_space.get(\"feature_names\", []))\n            self.chemical_space[\"feature_names\"] = feature_names\n\n    def __arrange_by_scaffolds__(self, align_by_scaffold=True):\n        self.scaffold2indexes = {}\n        self.scaffold2rdmol = {}\n        self.index2scaffold = {}\n\n        for index, rdmol in self.index2rdmol.items():\n            AllChem.Compute2DCoords(rdmol)\n\n            if align_by_scaffold:\n                scaffold = Scaffolds.MurckoScaffold.GetScaffoldForMol(rdmol)\n                AllChem.Compute2DCoords(scaffold)\n                scaffold_smiles = Chem.MolToSmiles(scaffold)\n                self.scaffold2rdmol[scaffold_smiles] = scaffold\n                \n                matched = rdmol.GetSubstructMatch(scaffold)\n                coords = [rdmol.GetConformer().GetAtomPosition(x) for x in matched]\n                coords2D = [Geometry.Point2D(pt.x,pt.y) for pt in coords]\n\n                coordDict = {}\n                for i,coord in enumerate(coords2D):\n                    coordDict[matched[i]] = coord\n\n                AllChem.Compute2DCoords(rdmol, coordMap=coordDict)\n\n                if scaffold_smiles in self.scaffold2indexes:\n                    self.scaffold2indexes[scaffold_smiles].append(index)\n                else:\n                    self.scaffold2indexes[scaffold_smiles] = [index]\n\n        self.scaffold2indexes = {scaffold: indexes for scaffold, indexes in self.scaffold2indexes.items() if len(indexes) > 1}\n\n        for index, scaffold in enumerate(self.scaffold2indexes.keys(), len(self.index_order)):\n                self.index2scaffold[index] = scaffold\n                self.index2rdmol[index] = self.scaffold2rdmol[scaffold]\n                self.index_order.append(index)\n\n        self.edges = []\n        self.index2edges = {}\n\n        for index_1, scaffold in self.index2scaffold.items():\n            self.index2edges[index_1] = []\n\n            for index_2 in self.scaffold2indexes[scaffold]:\n                self.edges.append((index_1, index_2))\n                self.index2edges[index_1].append(index_2)\n\n        self.__add_scaffolds_to_chemical_space__()\n\n    def __add_scaffolds_to_chemical_space__(self):\n        for index, scaffold in self.index2scaffold.items():\n            self.chemical_space[\"points\"][index] = {\n                # \"features\": self.__get_pcp_for_rdmol__(self.scaffold2rdmol[scaffold]),\n                \"object_ids\": self.scaffold2indexes[scaffold],\n                \"links\": self.scaffold2indexes[scaffold],\n            }\n            if self.pcp:\n                self.chemical_space[\"points\"][index][\"features\"] = [None for i in range(len(self.chemical_space[\"feature_names\"]) - len(PROPS_ORDER))]\n                self.chemical_space[\"points\"][index][\"features\"].extend(self.__get_pcp_for_rdmol__(self.scaffold2rdmol[scaffold]))\n            self.chemical_space[\"compounds\"][index] = {\"smiles\": scaffold, \"color\": \"red\"}\n\n    def get_chemspace_compound_from_smiles(self, smi):\n        mol_obj = Chem.MolFromSmiles(smi)\n        if mol_obj is not None:\n            AllChem.Compute2DCoords(mol_obj)\n            mol = self.__get_compound__(mol=mol_obj)\n        else:\n            mol = False\n        return mol\n\n    def export_chemical_space_as_html(self, htmldir=\".\", ):\n        \"\"\"Export a simple HTML page with embedded chemical space and dependencies into a given directory.\"\"\"\n        if not os.path.exists(htmldir):\n            os.makedirs(htmldir)\n\n        chemspace_json = self.export_chemical_space_as_json(minify=True, dump=True)\n        \n        libs = [\n            (\"chemspace-0.2.0.min.js\", \"https://openscreen.cz/software/chemspace/static/js/chemspace-0.2.0.min.js\"),\n            (\"jquery-3.3.1.min.js\", \"https://code.jquery.com/jquery-3.3.1.min.js\"),\n            (\"konva.min.js\", \"https://cdn.rawgit.com/konvajs/konva/1.7.6/konva.min.js\")\n        ]\n        \n        js_html = []\n        for l in libs:\n            js_html.append(\"<script src='{}'></script>\".format(l[0]))\n\n        settings = {\n            \"target\": \"chemspace\"\n        }\n\n        template = \"\"\"<html>\n        <head>\n            {}\n            <script>\n                $(document).ready(function() {{\n                    var data = {};\n                    var chemspace = new ChemSpace({});\n                    chemspace.read_data(data);\n                    chemspace.draw();\n                }});\n            </script>\n        </head>\n\n        <body>\n            <div id=\"chemspace\"></div>\n        </body>\n        </html>\"\"\".format('\\n'.join(js_html), chemspace_json, json.dumps(settings))\n\n        \n        for l in libs:\n            lib, url = l\n            try:\n                source = urllib2.urlopen(url)\n                source_html = source.read()\n\n                with open(os.path.join(htmldir, lib), \"w\") as output:\n                    output.write(source_html)\n            except urllib2.URLError, e:\n                raise Exception(\"\"\"\n                        \\nCan't download file {}.\\nPlease check your internet connection and try again.\\nIf the error persists there can be something wrong with the InCHlib server.\\n\"\"\".format(url)\n                    )\n\n        with open(os.path.join(htmldir, \"chemspace.html\"), \"w\") as output:\n            output.write(template)\n\n    def export_chemical_space_as_json(self, filename=None, minify=False, dump=True):\n        \"\"\"Returns space in a JSON format or exports it to the file specified by the filename parameter.\"\"\"\n        space_json = self.chemical_space\n\n        if minify:\n            space_json = json.dumps(space_json)\n            space_json = self.__minify_data(space_json)\n        elif dump:\n            space_json = json.dumps(space_json, indent=4)\n\n        if filename:\n            output = open(filename, \"w\")\n            output.write(space_json)\n        \n        return space_json\n\n    def __minify_data(self, data):\n        return jsmin.jsmin(data)\n\ndef _process_(arguments):\n    s = ChemSpace()\n    s.sdf_file = False\n    s.write_structures = False if arguments.dont_write_structures else True\n    s.fp = arguments.fingerprint\n    s.category_field = arguments.category_field\n    s.category_field_delimiter = arguments.category_field_delimiter\n    s.label_field = arguments.label_field\n    s.activity_field = arguments.activity_field\n    s.compound_structure_field = arguments.compound_structure_field\n    s.fingerprint_field = arguments.fingerprint_field\n    s.metric = arguments.similarity_metric\n\n    if arguments.data_file.split(\".\")[-1].lower() == \"sdf\":\n        s.read_sdf(arguments.data_file)\n    else:\n        s.read_csv(arguments.data_file, arguments.data_delimiter, arguments.data_header, arguments.missing_values, arguments.remove_columns)\n\n    if s.compound_structure_field is not False or s.sdf == True:\n        if arguments.physico_chemical_properties:\n            s.add_physico_chemical_properties()\n\n    if arguments.normalize:\n        s.normalize_data()\n\n    if arguments.arrange_by:\n        s.arrange(\n            method=arguments.dimensional_reduction_method,\n            similarity_threshold=float(arguments.compound_similarity_threshold),\n            add_edges=arguments.add_edges,\n            by=arguments.arrange_by,\n            k=arguments.knn\n        )\n    \n    if arguments.html_dir:\n        s.export_chemical_space_as_html(arguments.html_dir)\n    elif arguments.output_file:\n        s.export_chemical_space_as_json(arguments.output_file, minify=arguments.minify_output)\n    else:\n        print(s.export_chemical_space_as_json(minify=arguments.minify_output))\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n    parser.add_argument(\"data_file\", type=str, help=\"csv(text) data file with delimited values or a sdf file\")\n    parser.add_argument(\"-dh\", \"--data_header\", default=False, help=\"whether the first row of data file is a header\", action=\"store_true\")\n    parser.add_argument(\"-dd\", \"--data_delimiter\", type=str, default=\",\", help=\"delimiter of values in data file\")\n    parser.add_argument(\"-o\", \"--output_file\", type=str, help=\"the name of output file\")\n    parser.add_argument(\"-fpf\", \"--fingerprint_field\", type=str, default=False, help=\"set a fingerprint field name in case it is in the data file\")\n    parser.add_argument(\"-cf\", \"--category_field\", type=str, default=False, help=\"set a category field name in case it is in the data file\")\n    parser.add_argument(\"-cfd\", \"--category_field_delimiter\", type=str, default=False, help=\"a category field delimiter\")\n    parser.add_argument(\"-lf\", \"--label_field\", type=str, default=False, help=\"set a label field name in case it is in the data file\")\n    parser.add_argument(\"-af\", \"--activity_field\", type=str, default=False, help=\"set an activity field name in case it is in the data file\")\n    parser.add_argument(\"-csf\", \"--compound_structure_field\", type=str, default=False, help=\"the name of a column with a compound structure\")\n    parser.add_argument(\"-fp\", \"--fingerprint\", type=str, default=\"ecfp4\", help=\"fingerprint used for a compound representation (ecfp4, ecfp6, maccs, topological, atom_pairs)\")\n    parser.add_argument(\"-arr\", \"--arrange_by\", default=False, help=\"arrange data by compound structures (distance matrix) or by input data (data/fps)\", type=str)\n    parser.add_argument(\"-cst\", \"--compound_similarity_threshold\", default=0.7, help=\"compound similarity threshold\")\n    parser.add_argument(\"-drm\", \"--dimensional_reduction_method\", nargs='+', type=str, default=\"pca\", help=\"which method use for dimensional reduction (pca/isomap/csn)\")\n    parser.add_argument(\"-dws\", \"--dont_write_structures\", default=False, help=\"dont write structures to output file\", action=\"store_true\")\n    parser.add_argument(\"-min\", \"--minify_output\", default=False, help=\"minify the JSON output format\", action=\"store_true\")\n    parser.add_argument(\"-html\", \"--html_dir\", type=str, default=False, help=\"the directory to store HTML page with dependencies\")\n    parser.add_argument(\"-pcp\", \"--physico_chemical_properties\", default=False, help=\"calculate basic phyisico-chemical properties and add them ass features\", action='store_true')\n    parser.add_argument(\"-edges\", \"--add_edges\", default=False, help=\"add edges based on compound similarity to the graph\", action='store_true')\n    parser.add_argument(\"-n\", \"--normalize\", default=False, help=\"normalize data to [0, 1] range\", action=\"store_true\")\n    parser.add_argument(\"-mv\", \"--missing_values\", type=str, default=False, help=\"define the string representating missing values in the data\")\n    parser.add_argument(\"-k\", \"--knn\", type=int, default=None, help=\"the number of neighbours (k) used for the construction of csn using the nn method\")\n    parser.add_argument(\"-sm\", \"--similarity_metric\", type=str, default=\"Tanimoto\", help=\"similarity metric\")\n    parser.add_argument('-rmc','--remove_columns', nargs='+', default=False, help='columns in data that should not be used')\n    \n    args = parser.parse_args()\n    _process_(args)\n", "meta": {"hexsha": "0e6098d75c435b2e63f057cc82ca3783d0b87859", "size": 36025, "ext": "py", "lang": "Python", "max_stars_repo_path": "chemspace/chemspace.py", "max_stars_repo_name": "skutac/ChemSpace.js", "max_stars_repo_head_hexsha": "92a20c9853259a2c43b0c0dcee25f89cfb70b786", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-03T08:13:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-03T08:13:24.000Z", "max_issues_repo_path": "chemspace/chemspace.py", "max_issues_repo_name": "skutac/ChemSpace.js", "max_issues_repo_head_hexsha": "92a20c9853259a2c43b0c0dcee25f89cfb70b786", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chemspace/chemspace.py", "max_forks_repo_name": "skutac/ChemSpace.js", "max_forks_repo_head_hexsha": "92a20c9853259a2c43b0c0dcee25f89cfb70b786", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9380214541, "max_line_length": 197, "alphanum_fraction": 0.586315059, "include": true, "reason": "import numpy,from scipy", "num_tokens": 8071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.32766829425520916, "lm_q1q2_score": 0.18797622522100874}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Python Crash Course\n\n# Hello! This is a quick intro to programming in Python to help you hit the ground running with the _12 Steps to Navier–Stokes_.  \n# \n# There are two ways to enjoy these lessons with Python:\n# \n# 1. You can download and install a Python distribution on your computer. One option is the free [Anaconda Scientific Python](https://store.continuum.io/cshop/anaconda/) distribution. Another is [Canopy](https://www.enthought.com/products/canopy/academic/), which is free for academic use.  Our recommendation is Anaconda.\n# \n# 2. You can run Python in the cloud using [Wakari](https://wakari.io/) web-based data analysis, for which you need to create a free account. (No software installation required!)\n# \n# In either case, you will probably want to download a copy of this notebook, or the whole AeroPython collection. We recommend that you then follow along each lesson, experimenting with the code in the notebooks, or typing the code into a separate Python interactive session.\n# \n# If you decided to work on your local Python installation, you will have to navigate in the terminal to the folder that contains the .ipynb files. Then, to launch the notebook server, just type:\n# ipython notebook\n# \n# You will get a new browser window or tab with a list of the notebooks available in that folder. Click on one and start working!\n\n# ## Libraries\n\n# Python is a high-level open-source language.  But the _Python world_ is inhabited by many packages or libraries that provide useful things like array operations, plotting functions, and much more. We can import libraries of functions to expand the capabilities of Python in our programs.  \n# \n# OK! We'll start by importing a few libraries to help us out. First: our favorite library is **NumPy**, providing a bunch of useful array operations (similar to MATLAB). We will use it a lot! The second library we need is **Matplotlib**, a 2D plotting library which we will use to plot our results.\n# The following code will be at the top of most of your programs, so execute this cell first:\n\n# In[1]:\n\n\n# <-- comments in python are denoted by the pound sign, like this one\n\nimport numpy as np                # we import the array library\nfrom matplotlib import pyplot    # import plotting library\n\n\n# We are importing one library named `numpy` and we are importing a module called `pyplot` of a big library called `matplotlib`.\n# To use a function belonging to one of these libraries, we have to tell Python where to look for it. For that, each function name is written following the library name, with a dot in between.\n# So if we want to use the NumPy function [linspace()](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html), which creates an array with equally spaced numbers between a start and end, we call it by writing:\n\n# In[2]:\n\n\nmyarray = np.linspace(0, 5, 10)\nmyarray\n\n\n# If we don't preface the `linspace()` function with `numpy`, Python will throw an error.\n\n# In[4]:\n\n\nmyarray = np.linspace(0, 5, 10)\n\n\n# The function `linspace()` is very useful. Try it changing the input parameters!\n# \n# **Import style:**\n# \n# You will often see code snippets that use the following lines\n# ```Python\n# import numpy as np\n# import matplotlib.pyplot as plt\n# ```\n# What's all of this import-as business? It's a way of creating a 'shortcut' to the NumPy library and the pyplot module. You will see it frequently as it is in common usage, but we prefer to keep out imports explicit. We think it helps with code readability.\n# \n# **Pro tip:**\n# \n# Sometimes, you'll see people importing a whole library without assigning a shortcut for it (like `from numpy import *`). This saves typing but is sloppy and can get you in trouble. Best to get into good habits from the beginning!\n# \n# \n# To learn new functions available to you, visit the [NumPy Reference](http://docs.scipy.org/doc/numpy/reference/) page. If you are a proficient `Matlab` user, there is a wiki page that should prove helpful to you: [NumPy for Matlab Users](http://wiki.scipy.org/NumPy_for_Matlab_Users)\n\n# ## Variables\n\n# Python doesn't require explicitly declared variable types like C and other languages.  \n\n# In[5]:\n\n\na = 5        #a is an integer 5\nb = 'five'   #b is a string of the word 'five'\nc = 5.0      #c is a floating point 5  \n\n\n# In[6]:\n\n\ntype(a)\n\n\n# In[7]:\n\n\ntype(b)\n\n\n# In[8]:\n\n\ntype(c)\n\n\n# Note that if you divide an integer by an integer that yields a remainder, the result will be converted to a float.  (This is *different* from the behavior in Python 2.7, beware!)\n\n# ## Whitespace in Python\n\n# Python uses indents and whitespace to group statements together.  To write a short loop in C, you might use:\n# \n#     for (i = 0, i < 5, i++){\n#        printf(\"Hi! \\n\");\n#     }\n\n# Python does not use curly braces like C, so the same program as above is written in Python as follows:\n\n# In[9]:\n\n\nfor i in range(5):\n    print(\"Hi \\n\")\n\n\n# If you have nested for-loops, there is a further indent for the inner loop.\n\n# In[10]:\n\n\nfor i in range(3):\n    for j in range(3):\n        print(i, j)\n    \n    print(\"This statement is within the i-loop, but not the j-loop\")\n\n\n# ## Slicing Arrays\n\n# In NumPy, you can look at portions of arrays in the same way as in `Matlab`, with a few extra tricks thrown in.  Let's take an array of values from 1 to 5.\n\n# In[11]:\n\n\nmyvals = np.array([1, 2, 3, 4, 5])\nprint(myvals)\n\n\n# Python uses a **zero-based index**, so let's look at the first and last element in the array `myvals`\n\n# In[12]:\n\n\nprint(myvals[0], myvals[4])\n\n\n# There are 5 elements in the array `myvals`, but if we try to look at `myvals[5]`, Python will be unhappy, as `myvals[5]` is actually calling the non-existant 6th element of that array.\n\n# In[13]:\n\n\nprint(myvals[5])\n\n\n# Arrays can also be 'sliced', grabbing a range of values.  Let's look at the first three elements\n\n# In[14]:\n\n\nprint(myvals[0:3])\n\n\n# Note here, the slice is inclusive on the front end and exclusive on the back, so the above command gives us the values of `myvals[0]`, `myvals[1]` and `myvals[2]`, but not `myvals[3]`.\n\n# ## Assigning Array Variables\n\n# One of the strange little quirks/features in Python that often confuses people comes up when assigning and comparing arrays of values.  Here is a quick example.  Let's start by defining a 1-D array called $a$:\n\n# In[15]:\n\n\na = np.linspace(1,5,5)\n\n\n# In[16]:\n\n\na\n\n\n# OK, so we have an array $a$, with the values 1 through 5.  I want to make a copy of that array, called $b$, so I'll try the following:\n\n# In[17]:\n\n\nb = a\n\n\n# In[18]:\n\n\nb\n\n\n# Great.  So $a$ has the values 1 through 5 and now so does $b$.  Now that I have a backup of $a$, I can change its values without worrying about losing data (or so I may think!).\n\n# In[19]:\n\n\na[2] = 17\n\n\n# In[20]:\n\n\na\n\n\n# Here, the 3rd element of $a$ has been changed to 17.  Now let's check on $b$.\n\n# In[21]:\n\n\nb\n\n\n# And that's how things go wrong!  When you use a statement like $a = b$, rather than copying all the values of $a$ into a new array called $b$, Python just creates an alias (or a pointer) called $b$ and tells it to route us to $a$.  So if we change a value in $a$ then $b$ will reflect that change (technically, this is called *assignment by reference*).  If you want to make a true copy of the array, you have to tell Python to copy every element of $a$ into a new array.  Let's call it $c$.  \n\n# In[22]:\n\n\nc = a.copy()\n\n\n# Now, we can try again to change a value in $a$ and see if the changes are also seen in $c$.  \n\n# In[23]:\n\n\na[2] = 3\n\n\n# In[24]:\n\n\na\n\n\n# In[25]:\n\n\nc\n\n\n# OK, it worked!  If the difference between `a = b` and `a = b.copy()` is unclear, you should read through this again.  This issue will come back to haunt you otherwise.\n\n# ## Learn More\n\n# There are a lot of resources online to learn more about using NumPy and other libraries. Just for kicks, here we use Jupyter's feature for embedding videos to point you to a short video on YouTube on using NumPy arrays.\n\n# In[26]:\n\n\nfrom IPython.display import YouTubeVideo\n# a short video about using NumPy arrays, from Enthought\nYouTubeVideo('vWkb7VahaXQ')\n\n\n# In[27]:\n\n\nfrom IPython.core.display import HTML\ndef css_styling():\n    styles = open(\"../styles/custom.css\", \"r\").read()\n    return HTML(styles)\ncss_styling()\n\n", "meta": {"hexsha": "f93b857a8d6200c2defe480d87183cce052b0c90", "size": 8284, "ext": "py", "lang": "Python", "max_stars_repo_path": "lessons_src/00_Quick_Python_Intro.py", "max_stars_repo_name": "tnakaicode/python-cfd", "max_stars_repo_head_hexsha": "174176bdcb1c31e021fefd8fd54e2b3dd898dc62", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lessons_src/00_Quick_Python_Intro.py", "max_issues_repo_name": "tnakaicode/python-cfd", "max_issues_repo_head_hexsha": "174176bdcb1c31e021fefd8fd54e2b3dd898dc62", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lessons_src/00_Quick_Python_Intro.py", "max_forks_repo_name": "tnakaicode/python-cfd", "max_forks_repo_head_hexsha": "174176bdcb1c31e021fefd8fd54e2b3dd898dc62", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1236363636, "max_line_length": 495, "alphanum_fraction": 0.7085948817, "include": true, "reason": "import numpy,from numpy", "num_tokens": 2177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713670203584295, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.18793386693188197}}
{"text": "from __future__ import print_function\nimport numpy as np\nimport random\nimport datetime\nimport os\nfrom scipy.ndimage.interpolation import zoom\nimport matplotlib.pyplot as plt\n\n\ndef write_time_and_date():\n    os.environ['TZ'] = 'CST6CDT'\n    return \"Time\" + datetime.datetime.now().strftime(\"_%H_%M_%S_\") + \\\n           \"Date\" + datetime.datetime.now().strftime(\"_%Y_%m_%d\")\n\n\ndef results2(res, number_isotopes_displayed):\n\n    index = [i[0] for i in sorted(enumerate(res), key=lambda x:x[1])]\n    index = list(reversed(index))\n    for i in range(number_isotopes_displayed):\n        print((isotopes[index[i]], round(res[index[i]], 3)))\n\n\ndef load_template_spectra_from_folder(parent_folder,\n                                      spectrum_identifier,\n                                      LLD=10):\n    '''\n    inputs: partent_folder, spectrum_identifier\n    output: dictionary containing all template spectra from a folder.\n\n    Load template spectrum data into a dictionary. This allows templates from\n    different folders to be loaded into different dictionaries.\n\n    '''\n\n    temp_dict = {}\n\n    def normalize_spectrum(ID):\n        temp_spectrum = read_spectrum(parent_folder + ID + spectrum_identifier)\n        temp_spectrum[0:LLD] = 0\n        return temp_spectrum / np.max(temp_spectrum)\n\n    for i in range(len(isotopes)):\n        # Fixes background spectra name issue\n        if i >= len(isotopes) - 3:\n            spectrum_identifier = ''\n\n        temp_dict[isotopes[i]] = normalize_spectrum(isotopes_GADRAS_ID[i])\n\n    return temp_dict\n\n\ndef zoom_spectrum(spectrum, zoom_strength):\n    spectrum = np.abs(zoom(spectrum, zoom_strength))\n    if zoom_strength < 1.0:\n        spectrum = np.lib.pad(spectrum,\n                              (0, 1024 - spectrum.shape[0]),\n                              'constant',\n                              constant_values=0)\n    if zoom_strength > 1.0:\n        spectrum = spectrum[0:1024]\n\n    return spectrum\n\n\ndef read_spectrum(filename):\n    '''\n    Reads spectrum from .spe files.\n    Works with silver detector and GADRAS formatted spectra.\n    '''\n    spectrum = np.empty(1024)\n\n    with open(filename, 'rb') as f:\n\n        content = f.readlines()\n\n        if RepresentsInt(content[8]):\n            for i in range(1024):\n                # spectra begins at index 8\n                spectrum[i] = int(content[8 + i])\n        else:\n            for i in range(1024):\n                # spectra begins at index 12\n                spectrum[i] = int(content[12 + i])\n\n    return spectrum\n\n\ndef create_simplex(number_samples, number_categories):\n    # make an empty array\n    k = np.zeros([number_samples, number_categories + 1])\n    # Make a sorted array of random variables\n    a = np.sort(np.random.uniform(0,\n                                  1,\n                                  [number_samples, number_categories - 1]),\n                axis=1)\n    # Zero pad left side\n    k[:, 0] = 0\n    # Put sorted array in new array\n    k[:, 1:number_categories] = a\n    # One pad right side\n    k[:, number_categories] = 1\n    # Take the difference of adjacent elements\n    temp_simplex = np.diff(k)\n    return temp_simplex\n\n\ndef shuffle_simplex(simplex):\n    # last term from simpex is always background, by convention\n    temp = random.sample(simplex[:-1], len(simplex) - 1)\n\n    # 29 here because 29 isotopes plus one background super-isotope\n    shuffled_array = np.pad(temp, [0, 29 - len(temp)], 'constant')\n\n    np.random.shuffle(shuffled_array)\n\n    # Add background\n    shuffled_array = np.append(shuffled_array, simplex[-1])\n\n    return shuffled_array\n\n\ndef visualize_simplex(key, index1, index2):\n    new_list = []\n\n    for i in range(len(key)):\n        if key[i][index1] > 0 and key[i][index2] > 0:\n            new_list.append([key[i][index1], key[i][index2]])\n\n    plt.scatter(np.array(new_list)[:, 0], np.array(new_list)[:, 1])\n    return new_list\n\n\ndef RepresentsInt(s):\n    '''\n    Helper funtion to see if a string represents an integer\n    '''\n    try:\n        int(s)\n        return True\n    except ValueError:\n        return False\n\n\nisotopes = [\n    'Am241',\n    'Ba133',\n    'Co57',\n    'Co60',\n    'Cs137',\n    'Cr51',\n    'Eu152',\n    'Ga67',\n    'I123',\n    'I125',\n    'I131',\n    'In111',\n    'Ir192',\n    'U238',\n    'Lu177m',\n    'Mo99',\n    'Np237',\n    'Pd103',\n    'Pu239',\n    'Pu240',\n    'Ra226',\n    'Se75',\n    'Sm153',\n    'Tc99m',\n    'Xe133',\n    'Tl201',\n    'Tl204',\n    'U233',\n    'U235',\n    'Back_Th',\n    'Back_U',\n    'Back_K',\n]\n\n\nisotopes_GADRAS_ID = [\n    '241AM',\n    '133BA',\n    '57CO',\n    '60CO',\n    '137CS',\n    '51CR',\n    '152EU',\n    '67GA',\n    '123I',\n    '125I',\n    '131I',\n    '111IN',\n    '192IR',\n    '238U',\n    '177MLU',\n    '99MO',\n    '237NP',\n    '103PD',\n    '239PU',\n    '240PU',\n    '226RA',\n    '75SE',\n    '153SM',\n    '99TCM',\n    '133XE',\n    '201TL',\n    '204TL',\n    '233U',\n    '235U',\n    'ThoriumInSoil.spe',\n    'UraniumInSoil.spe',\n    'PotassiumInSoil.spe',\n]\n\n\nisotopes_sources_GADRAS_ID = [\n    '241AM',\n    '133BA',\n    '57CO',\n    '60CO',\n    '137CS',\n    '51CR',\n    '152EU',\n    '67GA',\n    '123I',\n    '125I',\n    '131I',\n    '111IN',\n    '192IR',\n    '238U',\n    '177MLU',\n    '99MO',\n    '237NP',\n    '103PD',\n    '239PU',\n    '240PU',\n    '226RA',\n    '75SE',\n    '153SM',\n    '99TCM',\n    '133XE',\n    '201TL',\n    '204TL',\n    '233U',\n    '235U'\n]\n\n\ndef sample_spectrum(iso_DRF, ncounts):\n    '''\n    Input:\n    isoDRF: the 1024x1 vector containing the spectrum to be sampled.\n            Does not need to be normalized.\n    Output:\n    ncounts: the 1024x1 vector containing the sampled spectrum.\n\n    Method:\n    Normalize isoDRF, and it is effectively a probability density function\n    Calculate the cumulative distribution function\n    Generate uniform random numbers to sample the cdf\n    '''\n\n    pdf = iso_DRF / sum(iso_DRF)\n    cdf = np.cumsum(pdf)\n\n    # take random samples and generate spectrum\n    t_all = np.random.rand(np.int(ncounts))\n    spec = pdf * 0\n    for t in t_all:\n        pos = np.argmax(cdf > t)\n        spec[pos] = spec[pos] + 1\n    return spec\n", "meta": {"hexsha": "4cad41ab5e61c07c7921068f740d221de086136c", "size": 6099, "ext": "py", "lang": "Python", "max_stars_repo_path": "annsa/annsa.py", "max_stars_repo_name": "samgdotson/annsa", "max_stars_repo_head_hexsha": "b8e3622c5866e7cfd4595da8565f713be9618a59", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "annsa/annsa.py", "max_issues_repo_name": "samgdotson/annsa", "max_issues_repo_head_hexsha": "b8e3622c5866e7cfd4595da8565f713be9618a59", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "annsa/annsa.py", "max_forks_repo_name": "samgdotson/annsa", "max_forks_repo_head_hexsha": "b8e3622c5866e7cfd4595da8565f713be9618a59", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2591240876, "max_line_length": 79, "alphanum_fraction": 0.5753402197, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.1879138903785469}}
{"text": "#!/usr/bin/env python3\n\"\"\"Calculates the Frechet Inception Distance (FID) to evalulate GANs\n\nThe FID metric calculates the distance between two distributions of images.\nTypically, we have summary statistics (mean & covariance matrix) of one\nof these distributions, while the 2nd distribution is given by a GAN.\n\nWhen run as a stand-alone program, it compares the distribution of\nimages that are stored as PNG/JPEG at a specified location with a\ndistribution given by summary statistics (in pickle format).\n\nThe FID is calculated by assuming that X_1 and X_2 are the activations of\nthe pool_3 layer of the inception net for generated samples and real world\nsamples respectively.\n\nSee --help to see further details.\n\nCode apapted from https://github.com/bioinf-jku/TTUR to use PyTorch instead\nof Tensorflow\n\nCopyright 2018 Institute of Bioinformatics, JKU Linz\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n   http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport os\nimport pathlib\nfrom argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\n\nimport numpy as np\nimport torch\nfrom scipy import linalg\nfrom scipy.misc import imread\nfrom torch.nn.functional import adaptive_avg_pool2d, adaptive_max_pool2d\nfrom scipy import misc\nimport random\nimport re\nfrom scipy.special import softmax\nfrom shutil import copyfile\nfrom domain_gap.sskmean.clustering.equal_groups import EqualGroupsKMeans\nimport glob\nimport os.path as osp\n\nimport numpy as np\nfrom sklearn.cluster import KMeans\nimport time\n\ntry:\n    from tqdm import tqdm\nexcept ImportError:\n    # If not tqdm is not available, provide a mock version of it\n    def tqdm(x): return x\n\nfrom domain_gap.models.inception import InceptionV3\n\nparser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)\nparser.add_argument('path', type=str, nargs=2,\n                    help=('Path to the generated images or '\n                          'to .npz statistic files'))\nparser.add_argument('--batch-size', type=int, default=50,\n                    help='Batch size to use')\nparser.add_argument('--dims', type=int, default=2048,\n                    choices=list(InceptionV3.BLOCK_INDEX_BY_DIM),\n                    help=('Dimensionality of Inception features to use. '\n                          'By default, uses pool3 features'))\nparser.add_argument('-c', '--gpu', default='3', type=str,\n                    help='GPU to use (leave blank for CPU only)')\n\n\ndef make_square(image, max_dim = 512):\n    max_dim = max(np.shape(image)[0], np.shape(image)[1])\n    h, w = image.shape[:2]\n    top_pad = (max_dim - h) // 2\n    bottom_pad = max_dim - h - top_pad\n    left_pad = (max_dim - w) // 2\n    right_pad = max_dim - w - left_pad\n    padding = [(top_pad, bottom_pad), (left_pad, right_pad), (0, 0)]\n    image = np.pad(image, padding, mode='constant', constant_values=0)\n    window = (top_pad, left_pad, h + top_pad, w + left_pad)\n    return image\n\ndef get_activations(opt, files, model, batch_size=50, dims=8192,\n                    cuda=False, verbose=False):\n    \"\"\"Calculates the activations of the pool_3 layer for all images.\n\n    Params:\n    -- files       : List of image files paths\n    -- model       : Instance of inception model\n    -- batch_size  : Batch size of images for the model to process at once.\n                     Make sure that the number of samples is a multiple of\n                     the batch size, otherwise some samples are ignored. This\n                     behavior is retained to match the original FID score\n                     implementation.\n    -- dims        : Dimensionality of features returned by Inception\n    -- cuda        : If set to True, use GPU\n    -- verbose     : If set to True and parameter out_step is given, the number\n                     of calculated batches is reported.\n    Returns:\n    -- A numpy array of dimension (num images, dims) that contains the\n       activations of the given tensor when feeding inception with the\n       query tensor.\n    \"\"\"\n    model.eval()\n\n    # if len(files) % batch_size != 0:\n    #     print(('Warning: number of images is not a multiple of the '\n    #            'batch size. Some samples are going to be ignored.'))\n    if batch_size > len(files):\n        print(('Warning: batch size is bigger than the data size. '\n               'Setting batch size to data size'))\n        batch_size = len(files)\n\n    n_batches = len(files) // batch_size\n    n_remainder=  len(files) % batch_size\n\n    print('\\rnumber of batches is %d' % n_batches),\n    n_used_imgs = n_batches * batch_size\n\n    pred_arr = np.empty((n_used_imgs+n_remainder, dims))\n    if n_remainder!=0:\n        n_batches=n_batches+1\n    for i in range(n_batches):\n        if verbose:\n            print('\\rPropagating batch %d/%d' % (i + 1, n_batches),\n                  end='', flush=True)\n        start = i * batch_size\n        if n_remainder!=0 and i==n_batches-1:\n          end = start + n_remainder\n        else:\n          end = start + batch_size\n\n        images = np.array([misc.imresize( imread(str(f)).astype(np.float32), size=[64, 64]).astype(np.float32)\n                           for f in files[start:end]])\n\n        images = images.transpose((0, 3, 1, 2))\n        images /= 255\n\n        batch = torch.from_numpy(images).type(torch.FloatTensor)\n        if cuda:\n            batch = batch.cuda()\n        \n        if opt.FD_model == 'inception':\n            pred = model(batch)[0]\n            # If model output is not scalar, apply global spatial average pooling.\n            # This happens if you choose a dimensionality not equal 2048.\n            if pred.shape[2] != 1 or pred.shape[3] != 1:\n                pred = adaptive_avg_pool2d(pred, output_size=(1, 1))\n        if opt.FD_model == 'posenet':\n            pred = model(batch)\n            # print (np.shape (pred))\n            pred = adaptive_max_pool2d(pred, output_size=(1, 1))\n        pred_arr[start:end] = pred.cpu().data.numpy().reshape(end - start, -1)\n        print('\\rPropagating batch %d/%d' % (i + 1, n_batches))\n\n    if verbose:\n        print(' done')\n\n    return pred_arr\n\n\ndef calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):\n    \"\"\"Numpy implementation of the Frechet Distance.\n    The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)\n    and X_2 ~ N(mu_2, C_2) is\n            d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).\n\n    Stable version by Dougal J. Sutherland.\n\n    Params:\n    -- mu1   : Numpy array containing the activations of a layer of the\n               inception net (like returned by the function 'get_predictions')\n               for generated samples.\n    -- mu2   : The sample mean over activations, precalculated on an\n               representative data set.\n    -- sigma1: The covariance matrix over activations for generated samples.\n    -- sigma2: The covariance matrix over activations, precalculated on an\n               representative data set.\n\n    Returns:\n    --   : The Frechet Distance.\n    \"\"\"\n\n    mu1 = np.atleast_1d(mu1)\n    mu2 = np.atleast_1d(mu2)\n\n    sigma1 = np.atleast_2d(sigma1)\n    sigma2 = np.atleast_2d(sigma2)\n\n    assert mu1.shape == mu2.shape, \\\n        'Training and test mean vectors have different lengths'\n    assert sigma1.shape == sigma2.shape, \\\n        'Training and test covariances have different dimensions'\n\n    diff = mu1 - mu2\n\n    # Product might be almost singular\n    covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)\n    if not np.isfinite(covmean).all():\n        msg = ('fid calculation produces singular product; '\n               'adding %s to diagonal of cov estimates') % eps\n        print(msg)\n        offset = np.eye(sigma1.shape[0]) * eps\n        covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))\n\n    # Numerical error might give slight imaginary component\n    if np.iscomplexobj(covmean):\n        if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):\n            m = np.max(np.abs(covmean.imag))\n            raise ValueError('Imaginary component {}'.format(m))\n        covmean = covmean.real\n\n    tr_covmean = np.trace(covmean)\n\n    return (diff.dot(diff) + np.trace(sigma1) +\n            np.trace(sigma2) - 2 * tr_covmean)\n\n\ndef calculate_activation_statistics(opt, files, model, batch_size=50,\n                                    dims=8192, cuda=False, verbose=False):\n    \"\"\"Calculation of the statistics used by the FID.\n    Params:\n    -- files       : List of image files paths\n    -- model       : Instance of inception model\n    -- batch_size  : The images numpy array is split into batches with\n                     batch size batch_size. A reasonable batch size\n                     depends on the hardware.\n    -- dims        : Dimensionality of features returned by Inception\n    -- cuda        : If set to True, use GPU\n    -- verbose     : If set to True and parameter out_step is given, the\n                     number of calculated batches is reported.\n    Returns:\n    -- mu    : The mean over samples of the activations of the pool_3 layer of\n               the inception model.\n    -- sigma : The covariance matrix of the activations of the pool_3 layer of\n               the inception model.\n    \"\"\"\n    act = get_activations(opt, files, model, batch_size, dims, cuda, verbose)\n    mu = np.mean(act, axis=0)\n    sigma = np.cov(act, rowvar=False)\n    #eigen_vals, eigen_vecs= np.linalg.eig(sigma)\n    #sum_eigen_val=eigen_vals.sum().real\n    sum_eigen_val = (sigma.diagonal()).sum()\n    return mu, sigma, sum_eigen_val\n\n\ndef _compute_statistics_of_path(opt, path, model, batch_size, dims, cuda):\n    if path.endswith('.npz'):\n        f = np.load(path)\n        m, s = f['mu'][:], f['sigma'][:]\n        f.close()\n    else:\n        path = pathlib.Path(path)\n        files = list(path.glob('*.jpg')) + list(path.glob('*.png'))\n        #random.shuffle(files)\n        #files = files[:2000]\n        m, s, sum_eigen_val = calculate_activation_statistics(opt, files, model, batch_size,\n                                               dims, cuda) \n    return m, s, sum_eigen_val\n\n\ndef get_id_path_of_data (dataset_id, paths):\n    img_paths = []\n    dataset_ids = []\n    person_ids = []\n    pattern = re.compile(r'([-\\d]+)_c([-\\d]+)')\n    did = 0\n    for sub_path in paths:\n        sub_path = pathlib.Path(sub_path)\n        files = list(sub_path.glob('*.jpg')) + list(sub_path.glob('*.png'))\n        # files=glob.glob(osp.join(sub_path, '*.png'))+glob.glob(osp.join(sub_path, '*.jpg'))\n        dataset_id_list = [dataset_id[did] for n in range(len(files))]\n        dataset_ids.extend(dataset_id_list)\n        img_paths.extend(files)\n        did += 1\n    dataset = []\n    ii = 0\n    for img_path in img_paths:\n        pid, camid = map(int, pattern.search(str(img_path)).groups())\n        # if pid == -1: continue  # junk images are just ignored\n        camid -= 1  # index starts from 0\n        dataid = dataset_ids[ii]\n        person_ids.append(pid)\n        dataset.append((img_path, pid, dataid))\n        ii = ii + 1\n\n    return img_paths, person_ids, dataset_ids, dataset\n\ndef clustering_sample(tpaths, dict, dataset_id, opt, result_dir, c_num, score_name, weight, n_num):\n    \"\"\"clustering the ids from different datasets and sampleing\"\"\"\n\n    # preparing dataset\n    paths = [dict[i]+'bounding_box_test' for i in dataset_id]\n    img_paths,  person_ids,  dataset_ids, _  = get_id_path_of_data(dataset_id, paths)\n\n    cuda = True\n    for p in paths:\n        if not os.path.exists(p):\n            raise RuntimeError('Invalid path: %s' % p)\n\n    if opt.FD_model == 'inception':\n        dims = 2048\n        block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims]\n        model = InceptionV3([block_idx])\n\n    if cuda:\n        model.cuda()\n    batch_size=256\n\n    # caculate the various, mu sigma of target ste\n    print('=========== extracting feature of target traning set ===========')\n    target_path = pathlib.Path(tpaths)\n    files = list(target_path.glob('*.jpg')) + list(target_path.glob('*.png'))\n    # random.shuffle(files)\n    # files = files[:2000]\n    target_feature = get_activations(opt, files, model, batch_size, dims, cuda, verbose=False)\n    m1 = np.mean(target_feature, axis=0)\n    s1 = np.cov(target_feature, rowvar=False)\n    sum_eigen_val1 = (s1.diagonal()).sum()\n\n\n    # extracter feature for data pool\n    if not os.path.exists(result_dir + '/feature.npy'):\n        print('=========== extracting feature of data pool ===========')\n        feature = get_activations(opt, img_paths, model, batch_size, dims, cuda, verbose=False)\n        if not os.path.isdir(result_dir):\n            os.mkdir(result_dir)\n        np.save(result_dir + '/feature.npy', feature)\n    else:\n        feature = np.load(result_dir + '/feature.npy')\n\n    person_ids_array=np.array(person_ids)\n    mean_feature_per_id=[]\n    pid_per_id=[]\n    did_per_id=[]\n\n    # get mean fature of perid and the fid, various of per_id with the target\n    if not os.path.exists(result_dir + '/mean_feature_per_id.npy'):\n        for did in dataset_id:\n           ind_of_set = np.argwhere(np.array(dataset_ids) == did).squeeze()\n           dataset_feature = feature[ind_of_set]\n           dataset_pid = person_ids_array[ind_of_set]\n           pid_of_dataset=set(dataset_pid)\n           for pid in pid_of_dataset:\n              ind_of_pid = np.argwhere(np.array(dataset_pid) == pid).squeeze()\n              feature_per_id = dataset_feature[ind_of_pid]\n              id_ave_feature=feature_per_id.mean(0)\n              mean_feature_per_id.append(id_ave_feature)\n              pid_per_id.append(pid)\n              did_per_id.append(did)\n        np.save(result_dir+ '/mean_feature_per_id.npy',mean_feature_per_id)\n        pid_did_fid_var = np.c_[np.array(pid_per_id), np.array(did_per_id)]\n        np.save(result_dir+ '/pid_did_fid_var.npy', pid_did_fid_var)\n    else:\n       mean_feature_per_id=np.load(result_dir + '/mean_feature_per_id.npy')\n       pid_did_fid_var = np.load(result_dir + '/pid_did_fid_var.npy')\n\n    #remove 0 and -1\n    ori_pid_per_id = pid_did_fid_var[:, 0]\n    remove_ind=np.r_[np.argwhere(ori_pid_per_id == -1), np.argwhere(ori_pid_per_id == 0)].squeeze()\n\n    new_pid_did_fid_var = np.delete(pid_did_fid_var, remove_ind, 0)\n    new_mean_feature_per_id = np.delete(mean_feature_per_id, remove_ind, 0)\n\n\n    print('\\r=========== clustering the data pool ===========')\n    pid_per_id = new_pid_did_fid_var[:,0]\n    did_per_id = new_pid_did_fid_var[:,1]\n    # clustering ids based on ids' mean feature\n    if not os.path.exists(result_dir + '/label_cluster_'+str(c_num)+'.npy'):\n        estimator = KMeans(n_clusters=c_num)\n        estimator.fit(new_mean_feature_per_id)\n        label_pred = estimator.labels_\n        np.save(result_dir + '/label_cluster_'+str(c_num)+'.npy',label_pred)\n    else:\n        label_pred = np.load('sample_data/' + '/label_cluster_'+str(c_num)+'.npy')\n\n    print('\\r=========== caculating the fid and v_gap between T and C_k ===========')\n    if not os.path.exists(result_dir + '/cluster_fid_var.npy'):\n        cluster_feature=[]\n        cluster_fid=[]\n        cluster_mmd=[]\n        cluster_var_gap=[]\n        for k in tqdm(range(c_num)):\n            # initializatn of the first seed cluster 0\n            initial_pid=pid_per_id[label_pred==k]\n            initial_did=did_per_id[label_pred==k]\n            initial_feature = feature[(dataset_ids == initial_did[0]) & (person_ids_array == initial_pid[0])]\n            for j in range(1,len(initial_pid)):\n                current_feature=feature[(dataset_ids == initial_did[j]) & (person_ids_array == initial_pid[j])]\n                initial_feature=np.r_[initial_feature, current_feature]\n            cluster_feature.append(initial_feature)\n            mu = np.mean(initial_feature, axis=0)\n            sigma = np.cov(initial_feature, rowvar=False)\n            # caculating various\n            current_var_gap = np.abs((sigma.diagonal()).sum() - sum_eigen_val1)\n            current_fid = calculate_frechet_distance(m1, s1, mu, sigma)\n            # mmd_value = polynomial_mmd_averages(torch.from_numpy(initial_feature), torch.from_numpy(target_feature))\n            # current_mmd=mmd_value[0].mean()\n            cluster_fid.append(current_fid)\n            # cluster_mmd.append(current_mmd)\n            cluster_var_gap.append(current_var_gap)\n        np.save(result_dir + '/cluster_fid_var.npy', np.c_[np.array(cluster_fid), np.array(cluster_var_gap)])\n        #np.save(result_dir+'/cluster_fid_var.npy', np.c_[np.array(cluster_fid),np.array(cluster_var_gap)])\n    else:\n        cluster_fid_var=np.load(result_dir + '/cluster_fid_var.npy')\n        cluster_fid=cluster_fid_var[:,0]\n        cluster_var_gap=cluster_fid_var[:,1]\n\n#    cluster_fid=cluster_mmd\n#    calculatting softmax score\n    cluster_fida=np.array(cluster_fid)\n    cluster_var_gapa=np.array(cluster_var_gap)\n    score_fid = softmax(-cluster_fida)\n    score_var_gap = softmax(-cluster_var_gapa)\n    if score_name == 'fid':\n        sample_rate=score_fid\n    elif score_name == 'var':\n        sample_rate=score_var_gap\n    else:\n        sample_rate = score_fid* weight + score_var_gap * (1-weight)\n\n    c_num_len = []\n    id_score = []\n    for kk in range(c_num):\n        initial_pid = pid_per_id[label_pred == kk]\n        c_num_len.append(len(initial_pid))\n    for jj in range(len(label_pred)):\n        id_score.append(sample_rate[label_pred[jj]] / c_num_len[label_pred[jj]])\n\n    selected_data_ind = np.sort(np.random.choice(range(len(id_score)), n_num, p=id_score))\n    sdid = did_per_id[selected_data_ind]\n    spid = pid_per_id[selected_data_ind]\n    data_dir = result_dir + '/proxy_set'\n    if not os.path.isdir(data_dir):\n        os.mkdir(data_dir)\n    print('\\r=========== building proxy set ===========')\n    sampled_data=np.c_[sdid,spid]\n    ii = dataset_build(dict, dataset_id, sampled_data, data_dir)\n    print('finished')\n    return sampled_data\n\n\ndef dataset_build(dict, dataset_id, sampled_data,result_dir):\n    pattern = re.compile(r'([-\\d]+)_c([-\\d]+)')\n    pid=sampled_data[:, 1]\n    new_pid=np.arange(len(pid))+1\n    did=sampled_data[:, 0]\n\n    for ii in range(len(pid)):\n        id= pid[ii]\n        id_set=did[ii]\n        new_id=new_pid[ii]\n        # sample images\n        gallery_data_path = dict[id_set]+ 'bounding_box_test'\n        for root, dirs, files in os.walk(gallery_data_path, topdown=True):\n            for name in files:\n                current_id, _ = map(int, pattern.search(str(name)).groups())\n                if not (name[-3:] == 'png' or name[-3:] == 'jpg'):\n                    continue\n                if int(current_id)!= id:\n                    continue\n                src_path = gallery_data_path + '/' + name\n                dst_path = result_dir+ '/bounding_box_test'\n                dstr_path = result_dir + '/bounding_box_train'\n                if not os.path.isdir(dst_path):\n                    os.mkdir(dst_path)\n                    os.mkdir(dstr_path)\n                    # one picture in train\n                    copyfile(src_path, dstr_path + '/' + '{:04}'.format(new_id) + name[4:-3] + 'jpg')\n                copyfile(src_path, dst_path + '/' + '{:04}'.format(new_id) + name[4:-3]+'jpg')\n        query_data_path = gallery_data_path[0:-18]+ '/query'\n        for root, dirs, files in os.walk(query_data_path, topdown=True):\n            for name in files:\n                if not (name[-3:] == 'png' or name[-3:] == 'jpg'):\n                    continue\n                if int(name[0:4]) != id:\n                    continue\n                src_path = query_data_path + '/' + name\n                dst_path = result_dir+'/query'\n                if not os.path.isdir(dst_path):\n                    os.mkdir(dst_path)\n                copyfile(src_path, dst_path + '/' + '{:04}'.format(new_id) + name[4:-3]+'jpg')\n\n\n\ndef calculate_fd_given_paths(paths, opt):\n    \"\"\"Calculates the FID of two paths\"\"\"\n\n    cuda = True\n    for p in paths:\n        if not os.path.exists(p):\n            raise RuntimeError('Invalid path: %s' % p)\n\n    if opt.FD_model == 'inception':\n        dims = 2048\n        block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims]\n        model = InceptionV3([block_idx])\n\n    if cuda:\n        model.cuda()\n\n    m1, s1, sum_eigen_val1 = _compute_statistics_of_path(opt, paths[0], model, 256,\n                                         dims, cuda)\n\n    npz_path = None\n    if not paths[0].endswith(\".npz\"):\n        if not paths[0].endswith('/'):\n            npz_path = paths[0] + \".npz\"\n        else:\n            npz_path = paths[0][:-1] + \".npz\"\n        np.savez(npz_path, mu = m1, sigma = s1)\n    m2, s2, sum_eigen_val2 = _compute_statistics_of_path(opt, paths[1], model, 256,\n                                         dims, cuda)\n\n\n    fd_value = calculate_frechet_distance(m1, s1, m2, s2)\n\n    return fd_value, npz_path, sum_eigen_val1, sum_eigen_val2\n\n\n\nif __name__ == '__main__':\n    args = parser.parse_args()\n    os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu\n\n    fid_value,_, sum_eigen_val1, sum_eigen_val2 = calculate_fd_given_paths(args.path,\n                                          args.batch_size,\n                                          args.gpu != '',\n                                          8192)\n    #print (fid_value)\n", "meta": {"hexsha": "b0f5a07a58eb6afd0a15bbc9aef9891d8cbaded7", "size": 21585, "ext": "py", "lang": "Python", "max_stars_repo_path": "domain_gap/fd_score.py", "max_stars_repo_name": "sxzrt/Ranking-Models-Unlabeled", "max_stars_repo_head_hexsha": "68249fa5f11c3e0e0a6ac76c69073ad5f9758095", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2021-08-22T11:34:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T17:36:10.000Z", "max_issues_repo_path": "domain_gap/fd_score.py", "max_issues_repo_name": "sxzrt/Ranking-Models-Unlabeled", "max_issues_repo_head_hexsha": "68249fa5f11c3e0e0a6ac76c69073ad5f9758095", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "domain_gap/fd_score.py", "max_forks_repo_name": "sxzrt/Ranking-Models-Unlabeled", "max_forks_repo_head_hexsha": "68249fa5f11c3e0e0a6ac76c69073ad5f9758095", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-04T03:10:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-04T03:10:34.000Z", "avg_line_length": 39.9722222222, "max_line_length": 118, "alphanum_fraction": 0.6266388696, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.1879138852149098}}
{"text": "\"\"\" This file defines utility classes and functions for algorithms. \"\"\"\nimport numpy as np\n\nfrom gps.utility.general_utils import BundleType\nfrom gps.algorithm.policy.lin_gauss_policy import LinearGaussianPolicy\n\n\nclass IterationData(BundleType):\n    \"\"\" Collection of iteration variables. \"\"\"\n    def __init__(self):\n        variables = {\n            'sample_list': None,  # List of samples for the current iteration.\n            'traj_info': None,  # Current TrajectoryInfo object.\n            'pol_info': None,  # Current PolicyInfo object.\n            'traj_distr': None,  # Initial trajectory distribution.\n            'new_traj_distr': None, # Updated trajectory distribution.\n            'cs': None,  # Sample costs of the current iteration.\n            'step_mult': 1.0,  # KL step multiplier for the current iteration.\n            'eta': 1.0,  # Dual variable used in LQR backward pass.\n        }\n        BundleType.__init__(self, variables)\n\n\nclass TrajectoryInfo(BundleType):\n    \"\"\" Collection of trajectory-related variables. \"\"\"\n    def __init__(self):\n        variables = {\n            'dynamics': None,  # Dynamics object for the current iteration.\n            'x0mu': None,  # Mean for the initial state, used by the dynamics.\n            'x0sigma': None,  # Covariance for the initial state distribution.\n            'cc': None,  # Cost estimate constant term.\n            'cv': None,  # Cost estimate vector term.\n            'Cm': None,  # Cost estimate matrix term.\n            'last_kl_step': float('inf'),  # KL step of the previous iteration.\n        }\n        BundleType.__init__(self, variables)\n\n\nclass PolicyInfo(BundleType):\n    \"\"\" Collection of policy-related variables. \"\"\"\n    def __init__(self, hyperparams):\n        T, dU, dX = hyperparams['T'], hyperparams['dU'], hyperparams['dX']\n        variables = {\n            'lambda_k': np.zeros((T, dU)),  # Dual variables.\n            'lambda_K': np.zeros((T, dU, dX)),  # Dual variables.\n            'pol_wt': hyperparams['init_pol_wt'] * np.ones(T),  # Policy weight.\n            'pol_mu': None,  # Mean of the current policy output.\n            'pol_sig': None,  # Covariance of the current policy output.\n            'pol_K': np.zeros((T, dU, dX)),  # Policy linearization.\n            'pol_k': np.zeros((T, dU)),  # Policy linearization.\n            'pol_S': np.zeros((T, dU, dU)),  # Policy linearization covariance.\n            'chol_pol_S': np.zeros((T, dU, dU)),  # Cholesky decomp of covar.\n            'prev_kl': None,  # Previous KL divergence.\n            'init_kl': None,  # The initial KL divergence, before the iteration.\n            'policy_samples': [],  # List of current policy samples.\n            'policy_prior': None,  # Current prior for policy linearization.\n        }\n        BundleType.__init__(self, variables)\n\n    def traj_distr(self):\n        \"\"\" Create a trajectory distribution object from policy info. \"\"\"\n        T, dU, dX = self.pol_K.shape\n        # Compute inverse policy covariances.\n        inv_pol_S = np.empty_like(self.chol_pol_S)\n        for t in range(T):\n            inv_pol_S[t, :, :] = np.linalg.solve(\n                self.chol_pol_S[t, :, :],\n                np.linalg.solve(self.chol_pol_S[t, :, :].T, np.eye(dU))\n            )\n        return LinearGaussianPolicy(self.pol_K, self.pol_k, self.pol_S,\n                self.chol_pol_S, inv_pol_S)\n\n\ndef estimate_moments(X, mu, covar):\n    \"\"\" Estimate the moments for a given linearized policy. \"\"\"\n    N, T, dX = X.shape\n    dU = mu.shape[-1]\n    if len(covar.shape) == 3:\n        covar = np.tile(covar, [N, 1, 1, 1])\n    Xmu = np.concatenate([X, mu], axis=2)\n    ev = np.mean(Xmu, axis=0)\n    em = np.zeros((N, T, dX+dU, dX+dU))\n    pad1 = np.zeros((dX, dX+dU))\n    pad2 = np.zeros((dU, dX))\n    for n in range(N):\n        for t in range(T):\n            covar_pad = np.vstack([pad1, np.hstack([pad2, covar[n, t, :, :]])])\n            em[n, t, :, :] = np.outer(Xmu[n, t, :], Xmu[n, t, :]) + covar_pad\n    return ev, em\n\n\ndef gauss_fit_joint_prior(pts, mu0, Phi, m, n0, dwts, dX, dU, sig_reg):\n    \"\"\" Perform Gaussian fit to data with a prior. \"\"\"\n    # Build weights matrix.\n    D = np.diag(dwts)\n    # Compute empirical mean and covariance.\n    mun = np.sum((pts.T * dwts).T, axis=0)\n    diff = pts - mun\n    empsig = diff.T.dot(D).dot(diff)\n    empsig = 0.5 * (empsig + empsig.T)\n    # MAP estimate of joint distribution.\n    N = dwts.shape[0]\n    mu = mun\n    sigma = (N * empsig + Phi + (N * m) / (N + m) *\n             np.outer(mun - mu0, mun - mu0)) / (N + n0)\n    sigma = 0.5 * (sigma + sigma.T)\n    # Add sigma regularization.\n    sigma += sig_reg\n    # Conditioning to get dynamics.\n    fd = np.linalg.solve(sigma[:dX, :dX], sigma[:dX, dX:dX+dU]).T\n    fc = mu[dX:dX+dU] - fd.dot(mu[:dX])\n    dynsig = sigma[dX:dX+dU, dX:dX+dU] - fd.dot(sigma[:dX, :dX]).dot(fd.T)\n    dynsig = 0.5 * (dynsig + dynsig.T)\n    return fd, fc, dynsig\n", "meta": {"hexsha": "fa3d465615bff69b6e621912ef5a9349d5e3130b", "size": 4917, "ext": "py", "lang": "Python", "max_stars_repo_path": "GPS_Berkley/GpsTestFolder/algorithm_utils.py", "max_stars_repo_name": "bvsk35/Hopping_Bot", "max_stars_repo_head_hexsha": "5a8c7d4fdb4ae0a5ddf96002deb3c9ba1116c216", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GPS_Berkley/GpsTestFolder/algorithm_utils.py", "max_issues_repo_name": "bvsk35/Hopping_Bot", "max_issues_repo_head_hexsha": "5a8c7d4fdb4ae0a5ddf96002deb3c9ba1116c216", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GPS_Berkley/GpsTestFolder/algorithm_utils.py", "max_forks_repo_name": "bvsk35/Hopping_Bot", "max_forks_repo_head_hexsha": "5a8c7d4fdb4ae0a5ddf96002deb3c9ba1116c216", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-02T07:27:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-02T07:27:04.000Z", "avg_line_length": 42.7565217391, "max_line_length": 80, "alphanum_fraction": 0.5859263779, "include": true, "reason": "import numpy", "num_tokens": 1383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3486451353339458, "lm_q1q2_score": 0.1879138779193836}}
{"text": "\"\"\"\nAgentpy Output Module\nContent: DataDict class for output data\n\"\"\"\n\nimport pandas as pd\nimport os\nfrom os import listdir, makedirs\nfrom os.path import getmtime, join\nfrom SALib.analyze import sobol\nfrom .tools import AttrDict, make_list, AgentpyError\nimport json\nimport numpy as np\n\n\nclass NpEncoder(json.JSONEncoder):\n    \"\"\" Adds support for numpy number formats to json. \"\"\"\n    # By Jie Yang https://stackoverflow.com/a/57915246\n    def default(self, obj):\n        if isinstance(obj, np.integer):\n            return int(obj)\n        elif isinstance(obj, np.floating):\n            return float(obj)\n        elif isinstance(obj, np.ndarray):\n            return obj.tolist()\n        else:\n            return super(NpEncoder, self).default(obj)\n\n\ndef _last_exp_id(name, path):\n    \"\"\" Identifies existing experiment data and return highest id. \"\"\"\n\n    exp_id = 0\n    output_dirs = listdir(path)\n    exp_dirs = [s for s in output_dirs if name in s]\n    if exp_dirs:\n        ids = [int(s.split('_')[-1]) for s in exp_dirs]\n        exp_id = max(ids)\n    return exp_id\n\n\n# TODO Create DataSubDict without methods\nclass DataDict(AttrDict):\n    \"\"\" Nested dictionary for output data of simulations.\n    Items can be accessed like attributes.\n    Attributes can differ from the standard ones listed below.\n\n    Attributes:\n        info (dict):\n            Metadata of the simulation.\n        parameters (DataDict):\n            Simulation parameters.\n        variables (DataDict):\n            Recorded variables, separatedper object type.\n        reporters (pandas.DataFrame):\n            Reported outcomes of the simulation.\n        sensitivity (DataDict):\n            Sensitivity data, if calculated.\n    \"\"\"\n\n    def __repr__(self, indent=False):\n        rep = \"\"\n        if not indent:\n            rep += \"DataDict {\"\n        i = '    ' if indent else ''\n        for k, v in self.items():\n            rep += f\"\\n{i}'{k}': \"\n            if isinstance(v, (int, float, np.integer, np.floating)):\n                rep += f\"{v} {type(v)}\"\n            elif isinstance(v, str):\n                x0 = f\"(length {len(v)})\"\n                x = f\"...' {x0}\" if len(v) > 20 else \"'\"\n                rep += f\"'{v[:30]}{x} {type(v)}\"\n            elif isinstance(v, pd.DataFrame):\n                lv = len(list(v.columns))\n                rv = len(list(v.index))\n                rep += f\"DataFrame with {lv} \" \\\n                       f\"variable{'s' if lv != 1 else ''} \" \\\n                       f\"and {rv} row{'s' if rv != 1 else ''}\"\n            elif isinstance(v, DataDict):\n                rep += f\"{v.__repr__(indent=True)}\"\n            elif isinstance(v, dict):\n                lv = len(list(v.keys()))\n                rep += f\"Dictionary with {lv} key{'s' if lv != 1 else ''}\"\n            elif isinstance(v, list):\n                lv = len(v)\n                rep += f\"List with {lv} entr{'ies' if lv != 1 else 'y'}\"\n            else:\n                rep += f\"Object of type {type(v)}\"\n        if not indent:\n            rep += \"\\n}\"\n        return rep\n\n    def _short_repr(self):\n        len_ = len(self.keys())\n        return f\"DataDict {{{len_} entr{'y' if len_ == 1 else 'ies'}}}\"\n\n    def __eq__(self, other):\n        \"\"\" Check equivalence of two DataDicts.\"\"\"\n        if not isinstance(other, DataDict):\n            return False\n        for key, item in self.items():\n            if key not in other:\n                return False\n            if isinstance(item, pd.DataFrame):\n                if not self[key].equals(other[key]):\n                    return False\n            elif not self[key] == other[key]:\n                return False\n        return True\n\n    def __ne__(self, other):\n        return not self.__eq__(other)\n\n    # Data analysis --------------------------------------------------------- #\n\n    @staticmethod\n    def _sobol_set_df_index(df, p_keys, reporter):\n        df['parameter'] = p_keys\n        df['reporter'] = reporter\n        df.set_index(['reporter', 'parameter'], inplace=True)\n\n    def calc_sobol(self, reporters=None, **kwargs):\n        \"\"\" Calculates Sobol Sensitivity Indices\n        using :func:`SALib.analyze.sobol.analyze`.\n        Data must be from an :class:`Experiment` with a :class:`Sample`\n        that was generated with the method 'saltelli'.\n        If the experiment had more than one iteration,\n        the mean value between iterations will be taken.\n\n        Arguments:\n            reporters (str or list of str, optional): The reporters that should\n                be used for the analysis. If none are passed, all are used.\n            **kwargs: Will be forwarded to :func:`SALib.analyze.sobol.analyze`.\n\n        Returns:\n            DataDict: The DataDict itself with an added category 'sensitivity'.\n        \"\"\"\n\n        if not self.parameters.log['type'] == 'saltelli':\n            raise AgentpyError(\"Sampling method must be 'saltelli'.\")\n        if self.info['iterations'] == 1:\n            reporters_df = self.reporters\n        else:\n            reporters_df = self.reporters.groupby('sample_id').mean()\n\n        # STEP 1 - Load salib problem from parameter log\n        param_ranges_salib = self.parameters.log['salib_problem']\n        calc_second_order = self.parameters.log['calc_second_order']\n\n        # STEP 2 - Calculate Sobol Sensitivity Indices\n        if reporters is None:\n            reporters = reporters_df.columns\n        if isinstance(reporters, str):\n            reporters = [reporters]\n        p_keys = self._combine_pars(sample=True, constants=False).keys()\n        dfs_list = [[] for _ in range(4 if calc_second_order else 2)]\n\n        for reporter in reporters:\n            y = np.array(reporters_df[reporter])\n            si = sobol.analyze(param_ranges_salib, y, calc_second_order, **kwargs)\n\n            # Make dataframes out of S1 and ST sensitivities\n            keyss = [['S1', 'ST'], ['S1_conf', 'ST_conf']]\n            for keys, dfs in zip(keyss, dfs_list[0:2]):\n                s = {k[0:2]: v for k, v in si.items() if k in keys}\n                df = pd.DataFrame(s)\n                self._sobol_set_df_index(df, p_keys, reporter)\n                dfs.append(df)\n\n            # Make dataframes out S2 sensitivities\n            if calc_second_order:\n                for key, dfs in zip(['S2', 'S2_conf'], dfs_list[2:4]):\n                    df = pd.DataFrame(si[key])\n                    self._sobol_set_df_index(df, p_keys, reporter)\n                    dfs.append(df)\n\n        # Combine dataframes for each reporter\n        self['sensitivity'] = sdict = DataDict()\n        sdict['sobol'] = pd.concat(dfs_list[0])\n        sdict['sobol_conf'] = pd.concat(dfs_list[1])\n\n        if calc_second_order:\n            # Add Second-Order to self\n            dfs_si = [sdict['sobol'], pd.concat(dfs_list[2])]\n            dfs_si_conf = [sdict['sobol_conf'], pd.concat(dfs_list[3])]\n            sdict['sobol'] = pd.concat(dfs_si, axis=1)\n            sdict['sobol_conf'] = pd.concat(dfs_si_conf, axis=1)\n\n            # Create Multi-Index for Columns\n            arrays = [[\"S1\", \"ST\"] + [\"S2\"] * len(p_keys), [\"\"] * 2 + list(p_keys)]\n            tuples = list(zip(*arrays))\n            index = pd.MultiIndex.from_tuples(tuples, names=[\"order\", \"parameter\"])\n            sdict['sobol'].columns = index\n            sdict['sobol_conf'].columns = index.copy()\n\n        return self\n\n    # Data arrangement ------------------------------------------------------ #\n\n    def _combine_vars(self, obj_types=True, var_keys=True):\n        \"\"\" Returns pandas dataframe with combined variables \"\"\"\n\n        # Retrieve variables\n        if 'variables' in self:\n            vs = self['variables']\n        else:\n            return None\n\n        if len(vs.keys()) == 1:\n            return list(vs.values())[0]  # Return df if vs has only one entry\n        elif isinstance(vs, DataDict):\n            df_dict = dict(vs)  # Convert to dict if vs is DataDict\n\n        # Remove dataframes that don't include any of the selected var_keys\n        if var_keys is not True:\n            df_dict = {k: v for k, v in df_dict.items()\n                       if any(x in v.columns for x in make_list(var_keys))}\n\n        # Select object types\n        if obj_types is not True:\n            df_dict = {k: v for k, v in df_dict.items()\n                       if k in make_list(obj_types)}\n\n        # Add 'obj_id' before 't' for model df\n        model_type = self.info['model_type']\n        if model_type in list(df_dict.keys()):\n            df = df_dict[model_type]\n            df['obj_id'] = 0\n            indexes = list(df.index.names)\n            indexes.insert(-1, 'obj_id')\n            df = df.reset_index()\n            df = df.set_index(indexes)\n            df_dict[model_type] = df\n\n        # Return none if empty\n        if df_dict == {}:\n            return None\n\n        # Create dataframe\n        df = pd.concat(df_dict)  # Dict keys (obj_type) will be added to index\n        df.index = df.index.set_names('obj_type', level=0)  # Rename new index\n\n        # Select var_keys\n        if var_keys is not True:\n            # make_list prevents conversion to pd.Series for single value\n            df = df[make_list(var_keys)]\n\n        return df\n\n    def _dict_pars_to_df(self, dict_pars):\n        n = self.info['sample_size'] if 'sample_size' in self.info else 1\n        d = {k: [v] * n for k, v in dict_pars.items()}\n        i = pd.Index(list(range(n)), name='sample_id')\n        return pd.DataFrame(d, index=i)\n\n    def _combine_pars(self, sample=True, constants=True):\n        \"\"\" Returns pandas dataframe with parameters and sample_id \"\"\"\n        # Cancel if there are no parameters\n        if 'parameters' not in self:\n            return None\n        dfp = pd.DataFrame()\n        if sample and 'sample' in self.parameters:\n            dfp = self.parameters.sample.copy()\n            if constants and 'constants' in self.parameters:\n                for k, v in self.parameters.constants.items():\n                    dfp[k] = v\n        elif constants and 'constants' in self.parameters:\n            dfp = self._dict_pars_to_df(self.parameters.constants)\n        # Cancel if no parameters have been selected\n        if dfp is None or dfp.empty is True:\n            return None\n        return dfp\n\n    def arrange(self, variables=False, reporters=False, parameters=False,\n                constants=False, obj_types=True, index=False):\n        \"\"\" Combines and/or filters data based on passed arguments.\n\n        Arguments:\n            variables (bool or str or list of str, optional):\n                Key or list of keys of variables to include in the dataframe.\n                If True, all available variables are selected.\n                If False (default), no variables are selected.\n            reporters (bool or str or list of str, optional):\n                Key or list of keys of reporters to include in the dataframe.\n                If True, all available reporters are selected.\n                If False (default), no reporters are selected.\n            parameters (bool or str or list of str, optional):\n                Key or list of keys of parameters to include in the dataframe.\n                If True, all non-constant parameters are selected.\n                If False (default), no parameters are selected.\n            constants (bool, optional):\n                Include constants if 'parameters' is True (default False).\n            obj_types (str or list of str, optional):\n                Agent and/or environment types to include in the dataframe.\n                If True (default), all objects are selected.\n                If False, no objects are selected.\n            index (bool, optional):\n                Whether to keep original multi-index structure (default False).\n\n        Returns:\n            pandas.DataFrame: The newly arranged dataframe.\n        \"\"\"\n\n        dfv = dfm = dfp = df = None\n\n        # Step 1: Variables\n        if variables is not False:\n            dfv = self._combine_vars(obj_types, variables)\n\n        # Step 2: Measures\n        if reporters is not False:\n            dfm = self.reporters\n            if reporters is not True:  # Select reporter keys\n                # make_list prevents conversion to pd.Series for single value\n                dfm = dfm[make_list(reporters)]\n\n        # Step 3: Parameters\n        if parameters is True:\n            dfp = self._combine_pars(constants=constants)\n        elif parameters is not False:\n            dfp = self._combine_pars()\n            dfp = dfp[make_list(parameters)]\n\n        # Step 4: Combine dataframes\n        if dfv is not None and dfm is not None:\n            # Combine variables & measures\n            index_keys = dfv.index.names\n            dfm = dfm.reset_index()\n            dfv = dfv.reset_index()\n            df = pd.concat([dfm, dfv])\n            df = df.set_index(index_keys)\n        elif dfv is not None:\n            df = dfv\n        elif dfm is not None:\n            df = dfm\n        if dfp is not None:\n            if df is None:\n                df = dfp\n            else:  # Combine df with parameters\n                if df is not None and isinstance(df.index, pd.MultiIndex):\n                    dfp = dfp.reindex(df.index, level='sample_id')\n                df = pd.concat([df, dfp], axis=1)\n\n        if df is None:\n            return pd.DataFrame()\n\n        # Step 6: Reset index\n        if not index:\n            df = df.reset_index()\n\n        return df\n\n    def arrange_reporters(self):\n        \"\"\" Common use case of :obj:`DataDict.arrange`\n        with `reporters=True` and `parameters=True`. \"\"\"\n        return self.arrange(variables=False, reporters=True, parameters=True)\n\n    def arrange_variables(self):\n        \"\"\" Common use case of :obj:`DataDict.arrange`\n        with `variables=True` and `parameters=True`. \"\"\"\n        return self.arrange(variables=True, reporters=False, parameters=True)\n\n    # Saving and loading data ----------------------------------------------- #\n\n    def save(self, exp_name=None, exp_id=None, path='ap_output', display=True):\n        \"\"\" Writes data to directory `{path}/{exp_name}_{exp_id}/`.\n\n        Works only for entries that are of type :class:`DataDict`,\n        :class:`pandas.DataFrame`, or serializable with JSON\n        (int, float, str, dict, list). Numpy objects will be converted\n        to standard objects, if possible.\n\n        Arguments:\n            exp_name (str, optional): Name of the experiment to be saved.\n                If none is passed, `self.info['model_type']` is used.\n            exp_id (int, optional): Number of the experiment.\n                Note that passing an existing id can overwrite existing data.\n                If none is passed, a new id is generated.\n            path (str, optional): Target directory (default 'ap_output').\n            display (bool, optional): Display saving progress (default True).\n        \"\"\"\n\n        # Create output directory if it doesn't exist\n        if path not in listdir():\n            makedirs(path)\n\n        # Set exp_name\n        if exp_name is None:\n            if 'info' in self and 'model_type' in self.info:\n                exp_name = self.info['model_type']\n            else:\n                exp_name = 'Unnamed'\n\n        exp_name = exp_name.replace(\" \", \"_\")\n\n        # Set exp_id\n        if exp_id is None:\n            exp_id = _last_exp_id(exp_name, path) + 1\n\n        # Create new directory for output\n        path = f'{path}/{exp_name}_{exp_id}'\n        makedirs(path)\n\n        # Save experiment data\n        for key, output in self.items():\n\n            if isinstance(output, pd.DataFrame):\n                output.to_csv(f'{path}/{key}.csv')\n\n            elif isinstance(output, DataDict):\n                for k, o in output.items():\n\n                    if isinstance(o, pd.DataFrame):\n                        o.to_csv(f'{path}/{key}_{k}.csv')\n                    elif isinstance(o, dict):\n                        with open(f'{path}/{key}_{k}.json', 'w') as fp:\n                            json.dump(o, fp, cls=NpEncoder)\n\n            else:  # Use JSON for other object types\n                try:\n                    with open(f'{path}/{key}.json', 'w') as fp:\n                        json.dump(output, fp, cls=NpEncoder)\n                except TypeError as e:\n                    print(f\"Warning: Object '{key}' could not be saved. \"\n                          f\"(Reason: {e})\")\n                    os.remove(f'{path}/{key}.json')\n\n            # TODO Support grids & graphs\n            # elif t == nx.Graph:\n            #    nx.write_graphml(output, f'{path}/{key}.graphml')\n\n        if display:\n            print(f\"Data saved to {path}\")\n\n    def _load(self, exp_name=None, exp_id=None,\n              path='ap_output', display=True):\n\n        def load_file(path, file, display):\n            if display:\n                print(f'Loading {file} - ', end='')\n            i_cols = ['sample_id', 'iteration', 'obj_id', 't']\n            ext = file.split(\".\")[-1]\n            path = path + file\n            try:\n                if ext == 'csv':\n                    obj = pd.read_csv(path) # Convert .csv into DataFrane\n                    index = [i for i in i_cols if i in obj.columns]\n                    if index:  # Set potential index columns\n                        obj = obj.set_index(index)\n                elif ext == 'json':\n                    # Convert .json with json decoder\n                    with open(path, 'r') as fp:\n                        obj = json.load(fp)\n                    # Convert dict to AttrDict\n                    if isinstance(obj, dict):\n                        obj = AttrDict(obj)\n                # TODO Support grids & graphs\n                # elif ext == 'graphml':\n                #    self[key] = nx.read_graphml(path)\n                else:\n                    raise ValueError(f\"File type '{ext}' not supported\")\n                if display:\n                    print('Successful')\n                return obj\n            except Exception as e:\n                print(f'Error: {e}')\n\n        # Prepare for loading\n        if exp_name is None:\n            # Choose latest modified experiment\n            exp_names = listdir(path)\n            paths = [join(path, d) for d in exp_names]\n            latest_exp = exp_names[paths.index(max(paths, key=getmtime))]\n            exp_name = latest_exp.rsplit('_', 1)[0]\n\n        exp_name = exp_name.replace(\" \", \"_\")\n        if not exp_id:\n            exp_id = _last_exp_id(exp_name, path)\n            if exp_id == 0:\n                raise FileNotFoundError(f\"No experiment found with \"\n                                        f\"name '{exp_name}' in path '{path}'\")\n        path = f'{path}/{exp_name}_{exp_id}/'\n        if display:\n            print(f'Loading from directory {path}')\n\n        # Loading data\n        for file in listdir(path):\n            if 'variables_' in file:\n                if 'variables' not in self:\n                    self['variables'] = DataDict()\n                ext = file.split(\".\")[-1]\n                key = file[:-(len(ext) + 1)].replace('variables_', '')\n                self['variables'][key] = load_file(path, file, display)\n            elif 'parameters_' in file:\n                ext = file.split(\".\")[-1]\n                key = file[:-(len(ext) + 1)].replace('parameters_', '')\n                if 'parameters' not in self:\n                    self['parameters'] = DataDict()\n                self['parameters'][key] = load_file(path, file, display)\n            else:\n                ext = file.split(\".\")[-1]\n                key = file[:-(len(ext) + 1)]\n                self[key] = load_file(path, file, display)\n        return self\n\n    @classmethod\n    def load(cls, exp_name=None, exp_id=None, path='ap_output', display=True):\n        \"\"\" Reads data from directory `{path}/{exp_name}_{exp_id}/`.\n\n            Arguments:\n                exp_name (str, optional): Experiment name.\n                    If none is passed, the most recent experiment is chosen.\n                exp_id (int, optional): Id number of the experiment.\n                    If none is passed, the highest available id used.\n                path (str, optional): Target directory (default 'ap_output').\n                display (bool, optional): Display loading progress (default True).\n\n            Returns:\n                DataDict: The loaded data from the chosen experiment.\n        \"\"\"\n        return cls()._load(exp_name, exp_id, path, display)\n", "meta": {"hexsha": "980e216886e69e265797f264d31dfde2914dbe46", "size": 20428, "ext": "py", "lang": "Python", "max_stars_repo_path": "agentpy/datadict.py", "max_stars_repo_name": "isabeaups/agentpy", "max_stars_repo_head_hexsha": "47d6554495218581cdd2c211366ee6c1f81a304d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-01T17:04:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-01T17:04:26.000Z", "max_issues_repo_path": "agentpy/datadict.py", "max_issues_repo_name": "isabeaups/agentpy", "max_issues_repo_head_hexsha": "47d6554495218581cdd2c211366ee6c1f81a304d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "agentpy/datadict.py", "max_forks_repo_name": "isabeaups/agentpy", "max_forks_repo_head_hexsha": "47d6554495218581cdd2c211366ee6c1f81a304d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0592734226, "max_line_length": 83, "alphanum_fraction": 0.5418053652, "include": true, "reason": "import numpy", "num_tokens": 4510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.34864512179822554, "lm_q1q2_score": 0.1879138706238575}}
{"text": "import os\nimport sys\nimport numpy as np\n\nfrom . import constants as cc\n#from . import camera as cam\nfrom . import preliminary_computations as precomp\nfrom .local_conditions import sky_countrate\n#from . import set_object as obj\nfrom . import optics as opt\nfrom . import photometry as phot\n#from .InfoStore import add\nfrom . import utils\n#######################################\n\ndef etc_computation(info_dict):\n    \"\"\" Compute either the SNR, the total exposure time or the magnitude in function of the 2 others\n\n    Parameters\n    ----------\n    info_dict: dictionary\n               contains all relevant information\n    \n    wavelength : array\n             wavelengths in angstrom\n\n    Returns\n    ---------\n    SNR: float\n         Signal to noise ratio\n\n    mag: float\n         magnitude reached \n\n    tot_exp_time: float\n                  total exposure time in seconds    \n\n    \"\"\"\n    # display result\n    verbose = info_dict['verbose']\n\n    etc_type = info_dict['etc_type']\n    SNR = info_dict['SNR']\n    tot_exp_time = info_dict['Nexp']*info_dict['exptime']\n    info_dict['total_exposure_time']=tot_exp_time\n    Nexp = info_dict['Nexp']\n    # Detector Integration Time in seconds\n    if etc_type == 'snr' or etc_type == 'mag':\n         DIT = info_dict['exptime'] - info_dict['T_dithering']\n  \n    #Display \n    if verbose == True:\n         print ('\\nInformation about Passband:')\n         print ('----------------------------')\n         print ('Cut_on: %.f angstroms' % info_dict['Passband_cuton'])\n         print ('Effective wavelength: %.f angstroms' % info_dict['effWavelength'])\n         print ('Cut_off: %.f angstroms' % info_dict['Passband_cutoff'])\n\n         print ('\\nAirmass: %.2f' % info_dict['airmass'])\n         print ('\\nSeeing: %.2f' % info_dict['seeing_los_arcsec'])\n\n    if info_dict['detailed_trans']==1:\n         # Computes mean transmission of each components for the given passband\n         mean_trans_tel = utils.mean_efficiency_passband(info_dict,opt.telescope_efficiency(info_dict))\n         mean_trans_inst = utils.mean_efficiency_passband(info_dict,opt.instrument_channel_efficiency(info_dict)*info_dict['Trans_filter']*info_dict['camera_efficiency'])\n         #mean_trans_optics = mean_trans_tel*mean_trans_inst\n         mean_trans_filter = utils.mean_efficiency_passband(info_dict,info_dict['Trans_filter'])\n         mean_eta_cam = utils.mean_efficiency_passband(info_dict,info_dict['camera_efficiency'])\n         mean_trans_optics = mean_trans_tel*mean_trans_inst\n         mean_trans_atm = utils.mean_efficiency_passband(info_dict,info_dict['Trans_atmosphere'])\n         #mean_trans_system = mean_trans_optics*mean_trans_filter*mean_trans_atm*mean_eta_cam\n         #mean_trans_system = mean_trans_optics*mean_eta_cam\n         mean_trans_system = mean_trans_optics\n         info_dict['trans_mean_tel']=mean_trans_tel\n         info_dict['trans_mean_inst']=mean_trans_inst\n         info_dict['trans_mean_optics']=mean_trans_optics\n         info_dict['trans_mean_filter']=mean_trans_filter\n         info_dict['trans_mean_atm']=mean_trans_atm\n         info_dict['trans_mean_cam']=mean_eta_cam\n         info_dict['trans_mean_system']=mean_trans_system\n       \n\n         if verbose == True:\n              print ('\\nMEAN EFFICENCIES:')\n              print ('------------------')\n              print ('Obscuration: %.3f' % (1.-info_dict['obstruction']))\n              print ('Telescope: %.3f (+obs: %.3f)' % (mean_trans_tel,mean_trans_tel*(1.-info_dict['obstruction'])))\n              print ('Instrument: %.3f' % mean_trans_inst)\n              print ('Optics (tel+inst): %.3f  (+obs: %.3f)' % (mean_trans_optics,mean_trans_optics*(1.-info_dict['obstruction'])))\n              print ('Filter: %.3f' % mean_trans_filter)\n              print ('Atmosphere: %.3f' % mean_trans_atm)\n              print ('Camera: %.3f' % mean_eta_cam)\n              print ('System: %.3f (+obs: %.3f)\\n' % (mean_trans_system,mean_trans_system*(1-info_dict['obstruction'])))\n\n              #print ('Telescope alan: %.3f' % utils.mean_efficiency_passband(info_dict,opt.telescope_efficiency_alan(info_dict)))\n              #print ('Instrument alan: %.3f' % utils.mean_efficiency_passband(info_dict,opt.instrument_channel_efficiency_alan(info_dict)*info_dict['Trans_filter']*info_dict['camera_efficiency']))\n              #print ('System alan (+atm) (+obs+atm): %.3f (%.3f) (%.3f)' % (utils.mean_efficiency_passband(info_dict,opt.telescope_efficiency_alan(info_dict)*opt.instrument_channel_efficiency_alan(info_dict)*info_dict['Trans_filter']*info_dict['camera_efficiency']),utils.mean_efficiency_passband(info_dict,opt.telescope_efficiency_alan(info_dict)*opt.instrument_channel_efficiency_alan(info_dict)*info_dict['Trans_filter']*info_dict['camera_efficiency']*info_dict['Trans_atmosphere']),utils.mean_efficiency_passband(info_dict,opt.telescope_efficiency_alan(info_dict)*opt.instrument_channel_efficiency_alan(info_dict)*info_dict['Trans_filter']*info_dict['camera_efficiency']*info_dict['Trans_atmosphere'])*(1.-info_dict['obstruction'])))\n\n \n    elif info_dict['detailed_trans'] == 0:\n         mean_eta_cam = utils.mean_efficiency_passband(info_dict,info_dict['camera_efficiency'])\n         mean_eta_optics=utils.mean_efficiency_passband(info_dict,phot.set_filter(info_dict))\n         mean_trans_system =  mean_eta_cam * mean_eta_optics\n         info_dict['trans_mean_system']=mean_trans_system\n         if verbose == True:\n              print ('\\nMEAN EFFICENCIES:')\n              print ('------------------')\n              print ('Obscuration: %.3f' % (1.-info_dict['obstruction']))\n              print ('System: %.2f (+obs: %.3f)\\n' % (mean_trans_system,mean_trans_system*(1-info_dict['obstruction'])))\n\n    \n\n\n    # Number of pixels covering 1.35*FWHM of the PSF\n    npix = info_dict['npix']\n    # Factor when estimating the Noise from other images\n    factor_ima = precomp.factor_images_averaged(info_dict)\n    # Fraction of light in the brightest pixel\n    f_pix = precomp.Normalisation_factor(info_dict,True)\n    # Fraction of light in the PSF\n    f_PSF = precomp.Normalisation_factor(info_dict,False)\n\n    info_dict['factor_ima']=factor_ima\n    info_dict['f_pix']=f_pix\n    info_dict['f_PSF']=f_PSF\n    #----------------------------------------------------------------------------------------\n\n    # Background Noise countrate in e-/s/px\n    #---------------------------------------\n    info_dict = sky_countrate(info_dict)# e-/s/px\n    BN = info_dict['Sky_CountRate']\n    #print ('Sky countrate: %.2f (e-/px/s)' % BN)    \n    # Thermic signal (electrons/s/pixel)  <--> Dark current\n    #------------------------------------------------------\n    DC = info_dict['cameras'][info_dict['channel']]['DC']\n    # Digitization noise   (e-/pixel)\n    #----------------------------------\n    # Converter analog to digital noise of 1/2 ADU (electrons/pixel) \n    DigN = info_dict['dig_noise']\n\n    # Readout noise (e-/pixel)\n    #--------------------------\n    RN = info_dict['cameras'][info_dict['channel']]['RN']\n \n    # Instrument background (e-/s/pix)\n    inst_bg=info_dict['Instrument_bg']\n\n    # Object\n    #---------\n    # Count rate of the object in e-/s\n    if etc_type == 'snr' or etc_type == 'time':\n         CR, fph = info_dict['Object_fes'],info_dict['Object_fph']  # e-/s\n\n    # Zeropoint\n    #-----------\n    ZP = info_dict['zeropoint']\n\n    #Add some info in info_cit\n    if verbose == True:\n         print ('Zeropoint: %.2f (%s mag)' % (ZP,info_dict['photometry_system']))\n    #-----------------------------------------------------------------------------------------\n\n    # Compute the SNR\n    #------------------\n    if etc_type == 'snr':\n         # In the case of a given magnitude to reach, the fraction of flux\n         # we kept should be included so that the given mag corresponds to the \n         # measured count rate.\n         if info_dict['object_type'] == 'magnitude': \n              CR = CR #/ f_PSF\n              CR_pix = CR #/ f_pix\n         else: CR_pix=CR\n\n         # Peak SNR (Object signal/noise at the brightest pixel)\n         SNR_pix = np.sqrt(Nexp) * CR_pix * f_pix * DIT / np.sqrt(CR_pix * f_pix * DIT + factor_ima * ((RN**2. + DigN**2.) + DIT * ( DC + BN + inst_bg)))\n\n         # Total integrated noise over npix (electrons/area)\n         SNR = np.sqrt(Nexp) * CR * f_PSF * DIT / np.sqrt(CR * f_PSF * DIT + factor_ima * npix*((RN**2. + DigN**2.) + DIT * ( DC + BN + inst_bg)))\n\n         if info_dict['object_type'] == 'magnitude': \n              #mag = ZP - 2.5*np.log10(CR*f_PSF)\n              mag = info_dict['object_magnitude']\n              mag_pix = ZP - 2.5*np.log10(CR_pix*f_pix)\n              mag_pix = info_dict['object_magnitude']\n         else: \n              mag = ZP - 2.5*np.log10(CR)\n              mag_pix = ZP - 2.5*np.log10(CR_pix)\n\n         Ftot_el=CR*f_PSF*DIT#*np.sqrt(Nexp)\n         Ftot_el_pix=CR_pix*f_pix*DIT#*np.sqrt(Nexp)\n         DIT_pix=DIT\n\n         info_dict['SNR']=SNR\n         info_dict['SNR_pix']=SNR_pix\n         info_dict['mag_pix']=mag_pix\n         info_dict['Ftot_el_pix']=Ftot_el_pix\n         info_dict['Ftot_el']=Ftot_el\n         info_dict['DIT_pix']=DIT_pix\n\n         if verbose == True:\n              print ('\\n\\nA magnitude (%s system) of %.2f in %s band within a total exposure time of %.2f seconds splited in %d exposure(s), implies a total SNR of :\\n' %(info_dict['photometry_system'],mag,info_dict['filter_band'],DIT*Nexp,Nexp))\n              #print ('\\t - Peak SNR at the brightest pixel: %.2f \\n' % SNR_pix)\n              print ('\\t - Integrated SNR over %d pixels: %.2f' % (npix, SNR))\n              print ('\\n\\nA magnitude (%s system) of %.2f in %s band within a total exposure time of %.2f seconds splited in %d exposure(s), implies a SNR for the central pixel of of :\\n\\n' %(info_dict['photometry_system'],mag_pix,info_dict['filter_band'],DIT_pix*Nexp,Nexp))\n              print ('\\t - SNR of the central pixel: %.2f \\n\\n' %  SNR_pix)\n    #------------------------------------------------------------------------------------------\n\n    # Compute the total exposure time\n    #--------------------------------\n    elif etc_type == 'time':\n\n         # In the case of a given magnitude to reach, the fraction of flux\n         # we kept should be included so that the given mag corresponds to the \n         # measured count rate.\n         if info_dict['object_type'] == 'magnitude': CR = CR #/ f_PSF\n\n         # Integrated over Npixels     (solve 2nd degree equation)\n         if Nexp > 1:\n              SNR_1 = SNR / np.sqrt(Nexp) \n         else:\n              SNR_1 = SNR \n         A_sys = -(CR * f_PSF)**2.\n         B_sys = SNR_1**2.*(CR * f_PSF + factor_ima * npix*(DC + BN + inst_bg))\n         C_sys = SNR_1**2.*factor_ima * npix*(RN**2. + DigN**2.)\n\n         delta = B_sys*B_sys - 4.*A_sys*C_sys\n\n         DIT = (-B_sys -np.sqrt(delta)) / (2.*A_sys)\n         #mag = -2.5*np.log10(obj_janskys/3631)\n\n         if info_dict['object_type'] == 'magnitude': mag = ZP - 2.5*np.log10(CR)#*f_PSF)\n         else: mag = ZP - 2.5*np.log10(CR)\n\n         Ftot_el=CR*f_PSF*DIT#*np.sqrt(Nexp)\n\n         #Brightest pixel\n         if info_dict['object_type'] == 'magnitude': CR_pix = CR #/ f_pix\n         else: CR_pix=CR\n\n         A_sys = -(CR_pix * f_pix)**2.\n         B_sys = SNR_1**2.*(CR_pix * f_pix + factor_ima *(DC + BN + inst_bg))\n         C_sys = SNR_1**2.*factor_ima *(RN**2. + DigN**2.)\n\n         delta = B_sys*B_sys - 4.*A_sys*C_sys\n\n         DIT_pix = (-B_sys -np.sqrt(delta)) / (2.*A_sys)\n\n         if info_dict['object_type'] == 'magnitude': mag_pix = ZP - 2.5*np.log10(CR_pix)#*f_pix)\n         else: mag_pix = ZP - 2.5*np.log10(CR)\n\n         Ftot_el_pix=CR_pix*f_pix*DIT_pix#*np.sqrt(Nexp)\n\n         info_dict['DIT']=DIT\n         info_dict['DIT_pix']=DIT_pix\n         info_dict['Ftot_el_pix']=Ftot_el_pix\n         info_dict['Ftot_el']=Ftot_el\n         info_dict['mag_pix']=mag_pix\n\n         if verbose == True:        \n              print ('\\n\\nReaching a magnitude (%s system) of %.2f in %s band with a SNR of %.2f requires:\\n' %(info_dict['photometry_system'],mag,info_dict['filter_band'],SNR))\n              print ('\\t - a Total exposure time of : %.2f s\\n' % (DIT * Nexp)) \n              print ('\\n\\nReaching a magnitude (%s system) of %.2f in %s band with a SNR of %.2f for the central pixel requires:\\n\\n' %(info_dict['photometry_system'],mag_pix,info_dict['filter_band'],SNR))\n              print ('\\t - a Total exposure time of : %.2f s\\n\\n' % (DIT_pix * Nexp))\n\n    #-------------------------------------------------------------------------------------\n    \n    # Compute the magnitude \n    #------------------------\n    elif etc_type == 'mag':\n         #f_PSF=1\n         #f_pix=1\n         # Integrated over Npixels    (solve 2nd degree equation)\n         A_sys = -( f_PSF * DIT * np.sqrt(Nexp) )**2.\n         B_sys = SNR**2.* f_PSF * DIT \n         C_sys = SNR**2. * (factor_ima * npix * (RN**2. + DigN**2. + DIT * (DC + BN + inst_bg)))\n\n         delta = B_sys*B_sys - 4.*A_sys*C_sys \n\n         CR = (-B_sys - np.sqrt(delta)) / (2.*A_sys)\n         Ftot_el=CR*f_PSF*DIT#*np.sqrt(Nexp)\n\n         mag = ZP -2.5*np.log10(CR)\n\n         # Central pixel\n         A_sys = -( f_pix * DIT * np.sqrt(Nexp) )**2.\n         B_sys = SNR**2.* f_pix * DIT\n         C_sys = SNR**2. * (factor_ima * (RN**2. + DigN**2. + DIT * (DC + BN + inst_bg)))\n\n         delta = B_sys*B_sys - 4.*A_sys*C_sys\n\n         CR_pix = (-B_sys - np.sqrt(delta)) / (2.*A_sys)\n         Ftot_el_pix=CR_pix*f_pix*DIT#*np.sqrt(Nexp)\n         mag_pix = ZP -2.5*np.log10(CR_pix)\n         DIT_pix=DIT\n\n         object_mag = mag*np.ones(len(info_dict['wavelength_ang']))\n         fJy = phot.mag2Jy(info_dict, object_mag)  # Jy\n         flam = utils.fJy_to_flambda(info_dict['wavelength_ang'], fJy)        # erg/s/cm2/A\n         fph = utils.flambda_to_fph(info_dict['wavelength_ang'], flam)        # ph/s/cm2/A      \n         \n         info_dict['Object_mag']=object_mag\n         info_dict['object_magnitude']=mag\n         info_dict['mag_pix']=mag_pix\n         info_dict['DIT_pix']=DIT\n         info_dict['Ftot_el_pix']=Ftot_el_pix\n         info_dict['Ftot_el']=Ftot_el\n \n         if verbose == True:\n              print ('\\n\\nFor a total SNR=%.2f in a total exposure time of %.2f (sec) in %d exposure(s) we reach:\\n' %(SNR, DIT*Nexp, Nexp))\n              print ('\\t - a magnitude (%s system) of: %.2f in %s band\\n' % (info_dict['photometry_system'],mag,info_dict['filter_band']))\n              print ('\\n\\nFor the central pixel a SNR=%.2f in a total exposure time of %.2f (sec) in %d exposure(s) we reach:\\n\\n' %(SNR, DIT_pix*Nexp, Nexp))\n              print ('\\t - a magnitude (%s system) of: %.2f in %s band\\n\\n' % (info_dict['photometry_system'],mag_pix,info_dict['filter_band']))\n\n\n    info_dict['DIT']=DIT\n\n    sigma_shot_noise = np.sqrt(Ftot_el * DIT)\n    sigma_dark_current = np.sqrt(DC * npix * DIT)\n    sigma_sky = np.sqrt(BN * npix * DIT)\n    sigma_digitization = np.sqrt( npix*DigN**2.)\n    sigma_readout_noise = np.sqrt(npix*RN**2.) \n    \n    # Total number of electrons in the brightest pixel for 1 exposure\n    N_el_tot_pix1 = Ftot_el_pix + (BN + DC + inst_bg)*DIT_pix + RN + DigN\n    N_el_tot_pix2 = Ftot_el*f_pix/f_PSF + (BN + DC + inst_bg)*DIT + RN + DigN\n\n    info_dict['N_el_tot_pix1']=N_el_tot_pix1\n    info_dict['N_el_tot_pix2']=N_el_tot_pix2\n\n    if N_el_tot_pix1 > info_dict['cameras'][info_dict['channel']]['FWC']:\n        info_dict['saturation']='Yes'\n    else: info_dict['saturation']='No'\n        \n    if verbose == True:\n\n         #print ('\\nFull well capacity of 1 pixel: %.2f (electrons)\\nInverse gain of %.2f e/ADU and %d bits implies a maximum number of electrons to be digitized of  %.2f (electrons)' % (info_dict['cameras'][info_dict['channel']]['FWC'],info_dict['cameras'][info_dict['channel']]['gain'],info_dict['cameras'][info_dict['channel']]['bits'],info_dict['cameras'][info_dict['channel']]['gain']*(2.**(info_dict['cameras'][info_dict['channel']]['bits'])-1)))\n         print ('\\nFull well capacity of 1 pixel: %.2f (electrons)' % (info_dict['cameras'][info_dict['channel']]['FWC']))\n         print ('\\n\\n--------- One pixel only------------------')\n         print ('\\nPhoto-electrons created: central pix for %d exposure(s) of %.2f sec ' % (Nexp,DIT_pix))\n         print ('\\tby:')\n         print ('\\t- Object:         %10.2f   (electrons)' % Ftot_el_pix)\n         print ('\\t- Sky:            %10.2f   (electrons)' % (BN*DIT_pix))\n         print ('\\t- Readout:        %10.2f   (electrons)' % RN)\n         print ('\\t- Dark current:   %10.2f   (electrons)' % (DC*DIT_pix))\n         print ('\\t- Digitization:   %10.2f   (electrons)' % DigN)\n         print ('\\t- Instrument bg:  %10.2f   (electrons)' % (inst_bg*DIT_pix))\n\n         print ('\\nSNR: -central pixel: %.2f' % (np.sqrt(Nexp)*Ftot_el_pix/np.sqrt(Ftot_el_pix + factor_ima * ((RN**2. + DigN**2.) + DIT_pix * ( DC + BN  + inst_bg)))))\n\n         print ('\\nTotal of electrons collected in the central pixel during an exposure time of %d seconds: %.2f ' % (DIT_pix, N_el_tot_pix1))\n         if N_el_tot_pix1 > info_dict['cameras'][info_dict['channel']]['FWC']:\n              print ('--> Central pixel saturated: number of electrons > Full well Capacity')\n         elif N_el_tot_pix1 > info_dict['cameras'][info_dict['channel']]['gain']*(2.**(info_dict['cameras'][info_dict['channel']]['bits'])-1):\n              print ('--> Central pixel saturated: number of electrons > number of digitizations')\n         elif N_el_tot_pix1 > 1./2*info_dict['cameras'][info_dict['channel']]['FWC']:\n              print ('--> Number of electrons in central pixel > 1/2 of Full well Capacity. Risk of non-linear response.')\n\n         else:\n              print ('--> No saturation')\n\n         print ('\\n\\n\\n--------- Integrated over %d pixels------------------' % npix)\n         print ('\\nPhoto-electrons created: brightest pix |  total of %d pixels, %d exposure(s) of %.2f sec ' % (npix,Nexp,DIT))\n         print ('\\tby:')\n         print ('\\t- Object:         %10.2f   |   %10.2f   (electrons)' % (Ftot_el*f_pix/f_PSF, Ftot_el))\n         print ('\\t- Sky:            %10.2f   |   %10.2f   (electrons)' % (BN*DIT,(BN * npix* DIT * Nexp)))\n         print ('\\t- Readout:        %10.2f   |   %10.2f   (electrons)' % (RN,(RN * npix * Nexp)))\n         print ('\\t- Dark current:   %10.2f   |   %10.2f   (electrons)' % (DC*DIT,(DC * DIT * npix * Nexp)))\n         print ('\\t- Digitization:   %10.2f   |   %10.2f   (electrons)' % (DigN, (DigN * npix * Nexp)))\n         print ('\\t- Instrument bg:  %10.2f   |   %10.2f   (electrons)' % (inst_bg*DIT, (inst_bg *DIT * npix * Nexp)))\n\n         #print ('\\nTotal noise: %.2f ' % (np.sqrt(Ftot_el * f_PSF * DIT *Nexp + Nexp*factor_ima * npix*((RN**2. + DigN**2.) + DIT * ( DC + BN )))))\n\n         print ('\\nSNR: -Brightest pixel: %.2f' % (np.sqrt(Nexp)*Ftot_el*f_pix/f_PSF/np.sqrt(Ftot_el*f_pix/f_PSF + factor_ima * ((RN**2. + DigN**2.) + DIT * ( DC + BN + inst_bg)))))\n         print ('     -integrated over %d pixels: %.2f' % (npix,np.sqrt(Nexp)*Ftot_el / np.sqrt(Ftot_el + factor_ima * npix*((RN**2. + DigN**2.) + DIT * ( DC + BN + inst_bg)))))     \n         print ('\\nTotal of electrons collected in the brightest pixel during an exposure time of %d seconds: %.2f ' % (DIT_pix, N_el_tot_pix2))\n         if N_el_tot_pix2 > info_dict['cameras'][info_dict['channel']]['FWC']:\n              print ('--> Brightest pixel saturated: number of electrons > Full well Capacity')\n         elif N_el_tot_pix2 > info_dict['cameras'][info_dict['channel']]['gain']*(2.**(info_dict['cameras'][info_dict['channel']]['bits'])-1):\n              print ('--> Brightest pixel saturated: number of electrons > number of digitizations')\n         elif N_el_tot_pix2 > 1./2*info_dict['cameras'][info_dict['channel']]['FWC']:\n              print ('--> Number of electrons in brightest pixel > 1/2 of Full well Capacity. Risk of non-linear response.')\n\n         else:\n              print ('--> No saturation')\n\n\n         print ('\\nDead time: %.2f sec \\n(%.2f sec for dithering, the %.2f sec for the readout are not taken into account)' % (info_dict['deadtime_tot'],info_dict['T_dithering'],info_dict['cameras'][info_dict['channel']]['ReadoutTime']))\n    info_dict['SNR']=SNR\n    info_dict['mag']=mag\n    info_dict['total_exposure_time']=DIT*Nexp\n    info_dict['fph']=fph\n\n    return info_dict \n", "meta": {"hexsha": "53e7b28600e133aee596f09fbde58ca57b53d5ca", "size": 20330, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyETC/solver.py", "max_stars_repo_name": "mtourneur/pyETC", "max_stars_repo_head_hexsha": "ea97f22d949d01e5191a1895493aa08ca32db1bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-14T18:21:56.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-14T18:21:56.000Z", "max_issues_repo_path": "pyETC/solver.py", "max_issues_repo_name": "mtourneur/pyETC", "max_issues_repo_head_hexsha": "ea97f22d949d01e5191a1895493aa08ca32db1bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyETC/solver.py", "max_forks_repo_name": "mtourneur/pyETC", "max_forks_repo_head_hexsha": "ea97f22d949d01e5191a1895493aa08ca32db1bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.5989847716, "max_line_length": 738, "alphanum_fraction": 0.5909985243, "include": true, "reason": "import numpy", "num_tokens": 5702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.18791314697989492}}
{"text": "# We implemented our method on top of AB3DMOT's KITTI tracking open-source code\n\nfrom __future__ import print_function\nimport os.path, copy, numpy as np, time, sys\nfrom numba import jit\nfrom sklearn.utils.linear_assignment_ import linear_assignment\nfrom filterpy.kalman import KalmanFilter\nfrom utils import load_list_from_folder, fileparts, mkdir_if_missing\nfrom scipy.spatial import ConvexHull\nfrom covariance import Covariance\nimport json\nfrom nuscenes import NuScenes\nfrom nuscenes.eval.common.data_classes import EvalBoxes\nfrom nuscenes.eval.tracking.data_classes import TrackingBox \nfrom nuscenes.eval.detection.data_classes import DetectionBox \nfrom pyquaternion import Quaternion\nfrom tqdm import tqdm\n\nfrom KalmanBoxTracker import KalmanBoxTracker\nfrom AB3DMOT import AB3DMOT\n\n@jit    \ndef poly_area(x,y):\n    return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))\n\n@jit        \ndef box3d_vol(corners):\n    ''' corners: (8,3) no assumption on axis direction '''\n    a = np.sqrt(np.sum((corners[0,:] - corners[1,:])**2))\n    b = np.sqrt(np.sum((corners[1,:] - corners[2,:])**2))\n    c = np.sqrt(np.sum((corners[0,:] - corners[4,:])**2))\n    return a*b*c\n\n@jit       \ndef convex_hull_intersection(p1, p2):\n    \"\"\" Compute area of two convex hull's intersection area.\n        p1,p2 are a list of (x,y) tuples of hull vertices.\n        return a list of (x,y) for the intersection and its volume\n    \"\"\"\n    inter_p = polygon_clip(p1,p2)\n    if inter_p is not None:\n        hull_inter = ConvexHull(inter_p)\n        return inter_p, hull_inter.volume\n    else:\n        return None, 0.0  \n\ndef polygon_clip(subjectPolygon, clipPolygon):\n   \"\"\" Clip a polygon with another polygon.\n   Args:\n     subjectPolygon: a list of (x,y) 2d points, any polygon.\n     clipPolygon: a list of (x,y) 2d points, has to be *convex*\n   Note:\n     **points have to be counter-clockwise ordered**\n\n   Return:\n     a list of (x,y) vertex point for the intersection polygon.\n   \"\"\"\n   def inside(p):\n      return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])\n \n   def computeIntersection():\n      dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]\n      dp = [ s[0] - e[0], s[1] - e[1] ]\n      n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]\n      n2 = s[0] * e[1] - s[1] * e[0] \n      n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])\n      return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]\n \n   outputList = subjectPolygon\n   cp1 = clipPolygon[-1]\n \n   for clipVertex in clipPolygon:\n      cp2 = clipVertex\n      inputList = outputList\n      outputList = []\n      s = inputList[-1]\n \n      for subjectVertex in inputList:\n         e = subjectVertex\n         if inside(e):\n            if not inside(s):\n               outputList.append(computeIntersection())\n            outputList.append(e)\n         elif inside(s):\n            outputList.append(computeIntersection())\n         s = e\n      cp1 = cp2\n      if len(outputList) == 0:\n          return None\n   return(outputList)\n\ndef iou3d(corners1, corners2):\n    ''' Compute 3D bounding box IoU.\n\n    Input:\n        corners1: numpy array (8,3), assume up direction is negative Y\n        corners2: numpy array (8,3), assume up direction is negative Y\n    Output:\n        iou: 3D bounding box IoU\n        iou_2d: bird's eye view 2D bounding box IoU\n\n    '''\n    # corner points are in counter clockwise order\n    rect1 = [(corners1[i,0], corners1[i,2]) for i in range(3,-1,-1)]\n    rect2 = [(corners2[i,0], corners2[i,2]) for i in range(3,-1,-1)] \n    area1 = poly_area(np.array(rect1)[:,0], np.array(rect1)[:,1])\n    area2 = poly_area(np.array(rect2)[:,0], np.array(rect2)[:,1])\n    inter, inter_area = convex_hull_intersection(rect1, rect2)\n    iou_2d = inter_area/(area1+area2-inter_area)\n    ymax = min(corners1[0,1], corners2[0,1])\n    ymin = max(corners1[4,1], corners2[4,1])\n    inter_vol = inter_area * max(0.0, ymax-ymin)\n    vol1 = box3d_vol(corners1)\n    vol2 = box3d_vol(corners2)\n    iou = inter_vol / (vol1 + vol2 - inter_vol)\n    return iou, iou_2d\n\n@jit       \ndef roty(t):\n    ''' Rotation about the y-axis. '''\n    c = np.cos(t)\n    s = np.sin(t)\n    return np.array([[c,  0,  s],\n                     [0,  1,  0],\n                     [-s, 0,  c]])\n\n@jit       \ndef rotz(t):\n    ''' Rotation about the z-axis. '''\n    c = np.cos(t)\n    s = np.sin(t)\n    return np.array([[c, -s,  0],\n                     [s,  c,  0],\n                     [0,  0,  1]])\n\n\ndef convert_3dbox_to_8corner(bbox3d_input, nuscenes_to_kitti=False):\n    ''' Takes an object and a projection matrix (P) and projects the 3d\n        bounding box into the image plane.\n        Returns:\n            corners_2d: (8,2) array in left image coord.\n            corners_3d: (8,3) array in in rect camera coord.\n        Note: the output of this function will be passed to the funciton iou3d\n            for calculating the 3D-IOU. But the function iou3d was written for \n            kitti, so the caller needs to set nuscenes_to_kitti to True if \n            the input bbox3d_input is in nuscenes format.\n    '''\n    # compute rotational matrix around yaw axis\n    bbox3d = copy.copy(bbox3d_input)\n\n    if nuscenes_to_kitti:\n      # transform to kitti format first\n      bbox3d_nuscenes = copy.copy(bbox3d)\n      # kitti:    [x,  y,  z,  a, l, w, h]\n      # nuscenes: [y, -z, -x, -a, w, l, h]\n      bbox3d[0] =  bbox3d_nuscenes[1]\n      bbox3d[1] = -bbox3d_nuscenes[2]\n      bbox3d[2] = -bbox3d_nuscenes[0]\n      bbox3d[3] = -bbox3d_nuscenes[3]\n      bbox3d[4] =  bbox3d_nuscenes[5]\n      bbox3d[5] =  bbox3d_nuscenes[4]\n   \n\n    R = roty(bbox3d[3])    \n\n    # 3d bounding box dimensions\n    l = bbox3d[4]\n    w = bbox3d[5]\n    h = bbox3d[6]\n    \n    # 3d bounding box corners\n    x_corners = [l/2,l/2,-l/2,-l/2,l/2,l/2,-l/2,-l/2];\n    y_corners = [0,0,0,0,-h,-h,-h,-h];\n    z_corners = [w/2,-w/2,-w/2,w/2,w/2,-w/2,-w/2,w/2];\n    \n    # rotate and translate 3d bounding box\n    corners_3d = np.dot(R, np.vstack([x_corners,y_corners,z_corners]))\n    corners_3d[0,:] = corners_3d[0,:] + bbox3d[0]\n    corners_3d[1,:] = corners_3d[1,:] + bbox3d[1]\n    corners_3d[2,:] = corners_3d[2,:] + bbox3d[2]\n \n    return np.transpose(corners_3d)\n\n\ndef angle_in_range(angle):\n  '''\n  Input angle: -2pi ~ 2pi\n  Output angle: -pi ~ pi\n  '''\n  if angle > np.pi:\n    angle -= 2 * np.pi\n  if angle < -np.pi:\n    angle += 2 * np.pi\n  return angle\n\ndef diff_orientation_correction(det, trk):\n  '''\n  return the angle diff = det - trk\n  if angle diff > 90 or < -90, rotate trk and update the angle diff\n  '''\n  diff = det - trk\n  diff = angle_in_range(diff)\n  if diff > np.pi / 2:\n    diff -= np.pi\n  if diff < -np.pi / 2:\n    diff += np.pi\n  diff = angle_in_range(diff)\n  return diff\n\ndef greedy_match(distance_matrix):\n  '''\n  Find the one-to-one matching using greedy allgorithm choosing small distance\n  distance_matrix: (num_detections, num_tracks)\n  '''\n  matched_indices = []\n\n  num_detections, num_tracks = distance_matrix.shape\n  distance_1d = distance_matrix.reshape(-1)\n  index_1d = np.argsort(distance_1d)\n  index_2d = np.stack([index_1d // num_tracks, index_1d % num_tracks], axis=1)\n  detection_id_matches_to_tracking_id = [-1] * num_detections\n  tracking_id_matches_to_detection_id = [-1] * num_tracks\n  for sort_i in range(index_2d.shape[0]):\n    detection_id = int(index_2d[sort_i][0])\n    tracking_id = int(index_2d[sort_i][1])\n    if tracking_id_matches_to_detection_id[tracking_id] == -1 and detection_id_matches_to_tracking_id[detection_id] == -1:\n      tracking_id_matches_to_detection_id[tracking_id] = detection_id\n      detection_id_matches_to_tracking_id[detection_id] = tracking_id\n      matched_indices.append([detection_id, tracking_id])\n\n  matched_indices = np.array(matched_indices)\n  return matched_indices\n \n\ndef associate_detections_to_trackers(detections,trackers,iou_threshold=0.1, \n  use_mahalanobis=False, dets=None, trks=None, trks_S=None, mahalanobis_threshold=0.1, print_debug=False, match_algorithm='greedy'):\n  \"\"\"\n  Assigns detections to tracked object (both represented as bounding boxes)\n\n  detections:  N x 8 x 3\n  trackers:    M x 8 x 3\n\n  dets: N x 7\n  trks: M x 7\n  trks_S: N x 7 x 7\n\n  Returns 3 lists of matches, unmatched_detections and unmatched_trackers\n  \"\"\"\n  if(len(trackers)==0):\n    return np.empty((0,2),dtype=int), np.arange(len(detections)), np.empty((0,8,3),dtype=int)    \n  iou_matrix = np.zeros((len(detections),len(trackers)),dtype=np.float32)\n  distance_matrix = np.zeros((len(detections),len(trackers)),dtype=np.float32)\n\n  if use_mahalanobis:\n    assert(dets is not None)\n    assert(trks is not None)\n    assert(trks_S is not None)\n\n  if use_mahalanobis and print_debug:\n    print('dets.shape: ', dets.shape)\n    print('dets: ', dets)\n    print('trks.shape: ', trks.shape)\n    print('trks: ', trks)\n    print('trks_S.shape: ', trks_S.shape)\n    print('trks_S: ', trks_S)\n    S_inv = [np.linalg.inv(S_tmp) for S_tmp in trks_S]  # 7 x 7\n    S_inv_diag = [S_inv_tmp.diagonal() for S_inv_tmp in S_inv]# 7\n    print('S_inv_diag: ', S_inv_diag)\n\n  for d,det in enumerate(detections):\n    for t,trk in enumerate(trackers):\n      if use_mahalanobis:\n        S_inv = np.linalg.inv(trks_S[t]) # 7 x 7\n        diff = np.expand_dims(dets[d] - trks[t], axis=1) # 7 x 1\n        # manual reversed angle by 180 when diff > 90 or < -90 degree\n        corrected_angle_diff = diff_orientation_correction(dets[d][3], trks[t][3])\n        diff[3] = corrected_angle_diff\n        distance_matrix[d, t] = np.sqrt(np.matmul(np.matmul(diff.T, S_inv), diff)[0][0])\n      else:\n        iou_matrix[d,t] = iou3d(det,trk)[0]             # det: 8 x 3, trk: 8 x 3\n        distance_matrix = -iou_matrix\n\n  if match_algorithm == 'greedy':\n    matched_indices = greedy_match(distance_matrix)\n  elif match_algorithm == 'pre_threshold':\n    if use_mahalanobis:\n      to_max_mask = distance_matrix > mahalanobis_threshold\n      distance_matrix[to_max_mask] = mahalanobis_threshold + 1\n    else:\n      to_max_mask = iou_matrix < iou_threshold\n      distance_matrix[to_max_mask] = 0\n      iou_matrix[to_max_mask] = 0\n    matched_indices = linear_assignment(distance_matrix)      # houngarian algorithm\n  else:\n    matched_indices = linear_assignment(distance_matrix)      # houngarian algorithm\n\n  if print_debug:\n    print('distance_matrix.shape: ', distance_matrix.shape)\n    print('distance_matrix: ', distance_matrix)\n    print('matched_indices: ', matched_indices)\n\n  unmatched_detections = []\n  for d,det in enumerate(detections):\n    if(d not in matched_indices[:,0]):\n      unmatched_detections.append(d)\n  unmatched_trackers = []\n  for t,trk in enumerate(trackers):\n    if len(matched_indices) == 0 or (t not in matched_indices[:,1]):\n      unmatched_trackers.append(t)\n\n  #filter out matched with low IOU\n  matches = []\n  for m in matched_indices:\n    match = True\n    if use_mahalanobis:\n      if distance_matrix[m[0],m[1]] > mahalanobis_threshold:\n        match = False\n    else:\n      if(iou_matrix[m[0],m[1]]<iou_threshold):\n        match = False\n    if not match:\n      unmatched_detections.append(m[0])\n      unmatched_trackers.append(m[1])\n    else:\n      matches.append(m.reshape(1,2))\n  if(len(matches)==0):\n    matches = np.empty((0,2),dtype=int)\n  else:\n    matches = np.concatenate(matches,axis=0)\n\n  if print_debug:\n    print('matches: ', matches)\n    print('unmatched_detections: ', unmatched_detections)\n    print('unmatched_trackers: ', unmatched_trackers)\n\n  return matches, np.array(unmatched_detections), np.array(unmatched_trackers)\n\nNUSCENES_TRACKING_NAMES = [\n  'bicycle',\n  'bus',\n  'car',\n  'motorcycle',\n  'pedestrian',\n  'trailer',\n  'truck'\n]\n\ndef format_sample_result(sample_token, tracking_name, tracker):\n  '''\n  Input:\n    tracker: (9): [h, w, l, x, y, z, rot_y], tracking_id, tracking_score\n  Output:\n  sample_result {\n    \"sample_token\":   <str>         -- Foreign key. Identifies the sample/keyframe for which objects are detected.\n    \"translation\":    <float> [3]   -- Estimated bounding box location in meters in the global frame: center_x, center_y, center_z.\n    \"size\":           <float> [3]   -- Estimated bounding box size in meters: width, length, height.\n    \"rotation\":       <float> [4]   -- Estimated bounding box orientation as quaternion in the global frame: w, x, y, z.\n    \"velocity\":       <float> [2]   -- Estimated bounding box velocity in m/s in the global frame: vx, vy.\n    \"tracking_id\":    <str>         -- Unique object id that is used to identify an object track across samples.\n    \"tracking_name\":  <str>         -- The predicted class for this sample_result, e.g. car, pedestrian.\n                                       Note that the tracking_name cannot change throughout a track.\n    \"tracking_score\": <float>       -- Object prediction score between 0 and 1 for the class identified by tracking_name.\n                                       We average over frame level scores to compute the track level score.\n                                       The score is used to determine positive and negative tracks via thresholding.\n  }\n  '''\n  rotation = Quaternion(axis=[0, 0, 1], angle=tracker[6]).elements\n  sample_result = {\n    'sample_token': sample_token,\n    'translation': [tracker[3], tracker[4], tracker[5]],\n    'size': [tracker[1], tracker[2], tracker[0]],\n    'rotation': [rotation[0], rotation[1], rotation[2], rotation[3]],\n    'velocity': [0, 0],\n    'tracking_id': str(int(tracker[7])),\n    'tracking_name': tracking_name,\n    'tracking_score': tracker[8]\n  }\n\n  return sample_result\n\ndef track_nuscenes(data_split, covariance_id, match_distance, match_threshold, match_algorithm, save_root, use_angular_velocity):\n  '''\n  submission {\n    \"meta\": {\n        \"use_camera\":   <bool>  -- Whether this submission uses camera data as an input.\n        \"use_lidar\":    <bool>  -- Whether this submission uses lidar data as an input.\n        \"use_radar\":    <bool>  -- Whether this submission uses radar data as an input.\n        \"use_map\":      <bool>  -- Whether this submission uses map data as an input.\n        \"use_external\": <bool>  -- Whether this submission uses external data as an input.\n    },\n    \"results\": {\n        sample_token <str>: List[sample_result] -- Maps each sample_token to a list of sample_results.\n    }\n  }\n  \n  '''\n  save_dir = os.path.join(save_root, data_split); mkdir_if_missing(save_dir)\n  if 'train' in data_split:\n    detection_file = '/juno/u/hkchiu/dataset/nuscenes_new/megvii_train.json'\n    data_root = '/juno/u/hkchiu/dataset/nuscenes/trainval'\n    version='v1.0-trainval'\n    output_path = os.path.join(save_dir, 'results_train_probabilistic_tracking.json')\n  elif 'val' in data_split:\n    detection_file = '/juno/u/hkchiu/dataset/nuscenes_new/megvii_val.json'\n    data_root = '/juno/u/hkchiu/dataset/nuscenes/trainval'\n    version='v1.0-trainval'\n    output_path = os.path.join(save_dir, 'results_val_probabilistic_tracking.json')\n  elif 'test' in data_split:\n    detection_file = '/juno/u/hkchiu/dataset/nuscenes_new/megvii_test.json'\n    data_root = '/juno/u/hkchiu/dataset/nuscenes/test'\n    version='v1.0-test'\n    output_path = os.path.join(save_dir, 'results_test_probabilistic_tracking.json')\n\n  nusc = NuScenes(version=version, dataroot=data_root, verbose=True)\n\n  results = {}\n\n  total_time = 0.0\n  total_frames = 0\n\n  with open(detection_file) as f:\n    data = json.load(f)\n  assert 'results' in data, 'Error: No field `results` in result file. Please note that the result format changed.' \\\n    'See https://www.nuscenes.org/object-detection for more information.'\n\n  all_results = EvalBoxes.deserialize(data['results'], DetectionBox)\n  meta = data['meta']\n  print('meta: ', meta)\n  print(\"Loaded results from {}. Found detections for {} samples.\"\n    .format(detection_file, len(all_results.sample_tokens)))\n\n  processed_scene_tokens = set()\n  for sample_token_idx in tqdm(range(len(all_results.sample_tokens))):\n    sample_token = all_results.sample_tokens[sample_token_idx]\n    scene_token = nusc.get('sample', sample_token)['scene_token']\n    if scene_token in processed_scene_tokens:\n      continue\n    first_sample_token = nusc.get('scene', scene_token)['first_sample_token']\n    current_sample_token = first_sample_token\n\n    mot_trackers = {tracking_name: AB3DMOT(covariance_id, tracking_name=tracking_name, use_angular_velocity=use_angular_velocity, tracking_nuscenes=True) for tracking_name in NUSCENES_TRACKING_NAMES}\n\n    while current_sample_token != '':\n      results[current_sample_token] = []\n      dets = {tracking_name: [] for tracking_name in NUSCENES_TRACKING_NAMES}\n      info = {tracking_name: [] for tracking_name in NUSCENES_TRACKING_NAMES}\n      for box in all_results.boxes[current_sample_token]:\n        if box.detection_name not in NUSCENES_TRACKING_NAMES:\n          continue\n        q = Quaternion(box.rotation)\n        angle = q.angle if q.axis[2] > 0 else -q.angle\n        #print('box.rotation,  angle, axis: ', box.rotation, q.angle, q.axis)\n        #print('box.rotation,  angle, axis: ', q.angle, q.axis)\n        #[h, w, l, x, y, z, rot_y]\n        detection = np.array([\n          box.size[2], box.size[0], box.size[1], \n          box.translation[0],  box.translation[1], box.translation[2],\n          angle])\n        #print('detection: ', detection)\n        information = np.array([box.detection_score])\n        dets[box.detection_name].append(detection)\n        info[box.detection_name].append(information)\n        \n      dets_all = {tracking_name: {'dets': np.array(dets[tracking_name]), 'info': np.array(info[tracking_name])}\n        for tracking_name in NUSCENES_TRACKING_NAMES}\n\n      total_frames += 1\n      start_time = time.time()\n      for tracking_name in NUSCENES_TRACKING_NAMES:\n        if dets_all[tracking_name]['dets'].shape[0] > 0:\n          trackers = mot_trackers[tracking_name].update(dets_all[tracking_name], match_distance, match_threshold, match_algorithm, scene_token)\n          # (N, 9)\n          # (h, w, l, x, y, z, rot_y), tracking_id, tracking_score \n          # print('trackers: ', trackers)\n          for i in range(trackers.shape[0]):\n            sample_result = format_sample_result(current_sample_token, tracking_name, trackers[i])\n            results[current_sample_token].append(sample_result)\n      cycle_time = time.time() - start_time\n      total_time += cycle_time\n\n      # get next frame and continue the while loop\n      current_sample_token = nusc.get('sample', current_sample_token)['next']\n\n    # left while loop and mark this scene as processed\n    processed_scene_tokens.add(scene_token)\n\n  # finished tracking all scenes, write output data\n  output_data = {'meta': meta, 'results': results}\n  with open(output_path, 'w') as outfile:\n    json.dump(output_data, outfile)\n\n  print(\"Total Tracking took: %.3f for %d frames or %.1f FPS\"%(total_time,total_frames,total_frames/total_time))\n\n\nif __name__ == '__main__':\n  if len(sys.argv)!=9:\n    print(\"Usage: python main.py data_split(train, val, test) covariance_id(0, 1, 2) match_distance(iou or m) match_threshold match_algorithm(greedy or h) use_angular_velocity(true or false) dataset save_root\")\n    sys.exit(1)\n\n  data_split = sys.argv[1]\n  covariance_id = int(sys.argv[2])\n  match_distance = sys.argv[3]\n  match_threshold = float(sys.argv[4])\n  match_algorithm = sys.argv[5]\n  use_angular_velocity = sys.argv[6] == 'True' or sys.argv[6] == 'true'\n  dataset = sys.argv[7]\n  save_root = os.path.join('./' + sys.argv[8])\n\n  if dataset == 'kitti':\n    print('track kitti not supported')\n  elif dataset == 'nuscenes':\n    print('track nuscenes')\n    track_nuscenes(data_split, covariance_id, match_distance, match_threshold, match_algorithm, save_root, use_angular_velocity)\n\n", "meta": {"hexsha": "4a94603cbd37f2e9bc428e2c5214bf9e979a3f01", "size": 19668, "ext": "py", "lang": "Python", "max_stars_repo_path": "Probabilistic_Tracker/main.py", "max_stars_repo_name": "YoushaaMurhij/3d-tracking-approaches", "max_stars_repo_head_hexsha": "0fcb9d6d1ff9cc9bb637e8e988f510a80c04f695", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-12-19T03:19:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T17:25:47.000Z", "max_issues_repo_path": "Probabilistic_Tracker/main.py", "max_issues_repo_name": "YoushaaMurhij/3d-tracking-approaches", "max_issues_repo_head_hexsha": "0fcb9d6d1ff9cc9bb637e8e988f510a80c04f695", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Probabilistic_Tracker/main.py", "max_forks_repo_name": "YoushaaMurhij/3d-tracking-approaches", "max_forks_repo_head_hexsha": "0fcb9d6d1ff9cc9bb637e8e988f510a80c04f695", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-12-01T14:42:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T02:54:59.000Z", "avg_line_length": 38.1902912621, "max_line_length": 210, "alphanum_fraction": 0.6611246695, "include": true, "reason": "from scipy,from numba", "num_tokens": 5625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.18763823629239107}}
{"text": "import logging, math, os, shutil\nfrom datetime import datetime\nfrom itertools import chain\nfrom time import time\nfrom typing import List, Callable\nimport pickle\nfrom copy import copy\n\nimport yaml\nimport numpy as np\nimport pandas as pd\nfrom scipy import special, stats\nfrom summer import CompartmentalModel\n\nfrom autumn import settings\nfrom autumn.core import db, plots\nfrom autumn.core.utils.git import get_git_branch, get_git_hash\nfrom autumn.core.utils.timer import Timer\nfrom autumn.calibration.priors import BasePrior\nfrom autumn.calibration.targets import BaseTarget\nfrom autumn.calibration.proposal_tuning import tune_jumping_stdev\nfrom autumn.core.project.params import read_param_value_from_string\nfrom autumn.core.project import Project, get_project, Params\n\nfrom .constants import ADAPTIVE_METROPOLIS\nfrom .transformations import (\n    make_transform_func_with_lower_bound,\n    make_transform_func_with_two_bounds,\n    make_transform_func_with_upper_bound,\n)\nfrom .utils import (\n    calculate_prior,\n    raise_error_unsupported_prior,\n    sample_starting_params_from_lhs,\n    specify_missing_prior_params,\n    draw_independent_samples,\n)\nfrom .targets import truncnormal_logpdf\n\nModelBuilder = Callable[[dict,dict], CompartmentalModel]\n\nlogger = logging.getLogger(__name__)\n\n\nclass CalibrationMode:\n    \"\"\"Different ways to run the calibration.\"\"\"\n\n    AUTUMN_MCMC = \"autumn_mcmc\"\n    MODES = [AUTUMN_MCMC]\n\n\nclass MetroInit:\n    \"\"\"Different ways to set the intial point for the MCMC.\"\"\"\n\n    LHS = \"lhs\"\n    CURRENT_PARAMS = \"current_params\"\n\n\n# Multiplier scaling the covariance matrix in the Haario Metropolis. 2.4 is the value recommended by Haario.\n# Greater values increase jumping step size and reduce the acceptance ratio\nDEFAULT_HAARIO_SCALING_FACTOR = 2.4\n\nDEFAULT_METRO_INIT = MetroInit.CURRENT_PARAMS\nDEFAULT_METRO_STEP = 0.1\n\nDEFAULT_STEPS = 50\n\n\nclass Calibration:\n    \"\"\"\n    Handles model calibration.\n\n    If sampling from the posterior distribution is required, uses a Bayesian algorithm.\n    If only one calibrated parameter set is required, uses maximum likelihood estimation.\n\n    A Metropolis Hastings algorithm is used with or without adaptive proposal function.\n    The adaptive approach employed was published by Haario et al.\n\n        'An  adaptive  Metropolis  algorithm', Bernoulli 7(2), 2001, 223-242\n\n    \"\"\"\n\n    def __init__(\n        self,\n        priors: List[BasePrior],\n        targets: List[BaseTarget],\n        haario_scaling_factor: float = DEFAULT_HAARIO_SCALING_FACTOR,\n        adaptive_proposal: bool = True,\n        metropolis_init: str = DEFAULT_METRO_INIT,\n        metropolis_init_rel_step_size: float = DEFAULT_METRO_STEP,\n        fixed_proposal_steps: int = DEFAULT_STEPS,\n        seed: int = None,\n        initial_jumping_stdev_ratio: float = 0.25,\n        jumping_stdev_adjustment: float = 0.5,\n        random_process=None,\n        hierarchical_priors: list = []\n    ):\n        \"\"\"\n        Defines a new calibration.\n        \"\"\"\n        check_hierarchical_priors(hierarchical_priors, priors)\n        self.hierarchical_priors = hierarchical_priors\n        self.all_priors = [p.to_dict() for p in priors] + [h_p.to_dict() for h_p in hierarchical_priors]\n\n        self.includes_random_process = False\n        if random_process is not None:\n            self.random_process = random_process\n            self.set_up_random_process()\n        \n        #self.targets = [t.to_dict() for t in targets]\n        self.targets = remove_early_points_to_prevent_crash(targets, self.all_priors)\n\n        self.haario_scaling_factor = haario_scaling_factor\n        self.adaptive_proposal = adaptive_proposal\n        self.initialisation_type = metropolis_init\n        self.metropolis_init_rel_step_size = metropolis_init_rel_step_size\n        self.n_steps_fixed_proposal = fixed_proposal_steps\n        self.initial_jumping_stdev_ratio = initial_jumping_stdev_ratio\n        self.jumping_stdev_adjustment = jumping_stdev_adjustment\n\n        self.split_priors_by_type()\n\n        if seed is None:\n            seed = int(time())\n        self.seed = seed\n\n        # Set this to True for mock tests that have trouble with pickling\n        self._no_pickle = False\n\n    @staticmethod\n    def from_existing(pkl_file, output_dir):\n        obj = pickle.load(open(pkl_file, 'rb'))\n        obj.output = CalibrationOutputs.from_existing(obj.chain_idx, output_dir)\n        return obj\n\n    def __getstate__(self):\n        state = self.__dict__.copy()\n        del state['transform']\n        del state['project']\n        del state['output']\n\n        # Probably can't pickle models...\n        state['latest_model'] = None\n\n        # These are items that are not members of the class/object dictionary,\n        # but are still required for restoring state\n        state['_extra'] = {}\n        state['_extra']['project'] = {'model_name': self.project.model_name, 'project_name': self.project.region_name}\n        state['_extra']['rng'] = np.random.get_state()\n\n        return state\n\n    def __setstate__(self, state):\n\n        # These are items that are not members of the class/object dictionary,\n        # but are still required for restoring state\n        _extra = state.pop('_extra')\n\n        self.__dict__.update(state)\n        self.project = get_project(**_extra['project'])\n        self.build_transformations(update_jumping_stdev=False)\n        np.random.set_state(_extra['rng'])\n\n        #self.output = CalibrationOutputs.open_existing(self.chain_idx, state[])\n\n    \n\n    def set_up_random_process(self):\n        self.includes_random_process = True\n\n        # add priors for coefficients, using 80% weight for the first order, splitting remaining 20% between remaining orders\n        order = self.random_process.order\n        if order == 1:\n            coeff_means = [1.]\n        else:\n            coeff_means = [.8] + [.2 / (order - 1)] * (order - 1)\n        for i, coeff_mean in enumerate(coeff_means):\n            self.all_priors.append({\n                \"param_name\":  f\"random_process.coefficients({i})\",\n                \"distribution\": \"trunc_normal\",\n                \"distri_params\": [coeff_mean, 0.05],\n                \"trunc_range\": [0., 1.],\n            })\n\n        # add prior for noise sd\n        self.all_priors.append({\n            \"param_name\": \"random_process.noise_sd\",\n            \"distribution\": \"uniform\",\n            \"distri_params\": [0.49, 0.51],\n        })\n\n        # add priors for rp values\n        n_values = len(self.random_process.values)\n        self.all_priors += [\n            {\n                \"param_name\": f\"random_process.values({i_val})\",\n                \"distribution\": \"uniform\",\n                \"distri_params\": [-2., 2.],\n                \"skip_evaluation\": True\n            } for i_val in range(1, n_values)  # the very first value will be fixed to 0.\n        ]\n\n    def split_priors_by_type(self):\n        # Distinguish independent sampling parameters from standard (iteratively sampled) calibration parameters\n        independent_sample_idxs = [\n            idx for idx in range(len(self.all_priors)) if self.all_priors[idx].get(\"sampling\") == \"lhs\"\n        ]\n\n        self.iterative_sampling_priors = [\n            param_dict\n            for i_param, param_dict in enumerate(self.all_priors)\n            if i_param not in independent_sample_idxs\n        ]\n        self.independent_sampling_priors = [\n            param_dict\n            for i_param, param_dict in enumerate(self.all_priors)\n            if i_param in independent_sample_idxs\n        ]\n        self.iterative_sampling_param_names = [\n            self.iterative_sampling_priors[i][\"param_name\"]\n            for i in range(len(self.iterative_sampling_priors))\n        ]\n        self.independent_sampling_param_names = [\n            self.independent_sampling_priors[i][\"param_name\"]\n            for i in range(len(self.independent_sampling_priors))\n        ]\n\n    def tune_proposal(self, param_name, project: Project, n_points=100, relative_likelihood_reduction=0.5):\n        assert param_name in self.iterative_sampling_param_names, f\"{param_name} is not an iteratively sampled parameter\"\n        assert n_points > 1, \"A minimum of two points is required to perform proposal tuning\"\n\n        self._is_first_run = True\n\n        # We must perform a few initialisation tasks (needs refactoring)\n        # work out missing distribution params for priors\n        specify_missing_prior_params(self.iterative_sampling_priors)\n        specify_missing_prior_params(self.independent_sampling_priors)\n\n        # rebuild self.all_priors, following changes to the two sets of priors\n        self.all_priors = self.iterative_sampling_priors + self.independent_sampling_priors\n\n        self.project = project\n        self.model_parameters = project.param_set.baseline\n        self.end_time = 2 + max([max(t.data.index) for t in self.targets])\n        target_names = [t.data.name for t in self.targets]\n        self.derived_outputs_whitelist = list(set(target_names))\n        self.run_mode = CalibrationMode.AUTUMN_MCMC\n        self.workout_unspecified_target_sds()  # for likelihood definition\n        self.workout_unspecified_time_weights()  # for likelihood weighting\n\n        prior_dict = [p_dict for p_dict in self.all_priors if p_dict[\"param_name\"] == param_name][0]\n        lower_bound, upper_bound = get_parameter_finite_range_from_prior(prior_dict)\n\n        starting_point = read_current_parameter_values(self.all_priors, self.model_parameters.to_dict())\n\n        eval_points = list(np.linspace(start=lower_bound, stop=upper_bound, num=n_points, endpoint=True))\n        eval_log_postertiors = []\n        for i_run, eval_point in enumerate(eval_points):\n            self.run_num = i_run\n            update = {param_name: eval_point}\n            updated_params = {**starting_point, **update}\n            log_likelihood = self.loglikelihood(updated_params)\n            log_prior = self.logprior(updated_params)\n            eval_log_postertiors.append(log_likelihood + log_prior)\n        return tune_jumping_stdev(eval_points, eval_log_postertiors, relative_likelihood_reduction)\n\n    def run(\n        self,\n        project: Project,\n        max_seconds: float,\n        chain_idx: int,\n        num_chains: int,\n        derived_outputs_to_plot: List[str] = None,\n    ):\n        self.project = project\n        self.model_parameters = project.param_set.baseline\n        self.chain_idx = chain_idx\n        model_parameters_data = self.model_parameters.to_dict()\n\n        # \n\n        # Figure out which derived outputs we have to calculate.\n        derived_outputs_to_plot = derived_outputs_to_plot or []\n        target_names = [t.data.name for t in self.targets]\n        self.derived_outputs_whitelist = list(set(target_names + derived_outputs_to_plot))\n\n        # Validate target output start time.\n        self.validate_target_start_time(model_parameters_data)\n\n        # Set a custom end time for all model runs - there is no point running\n        # the models after the last calibration targets.\n        self.end_time = 2 + max([max(t.data.index) for t in self.targets])\n\n        # work out missing distribution params for priors\n        specify_missing_prior_params(self.iterative_sampling_priors)\n        specify_missing_prior_params(self.independent_sampling_priors)\n\n        # rebuild self.all_priors, following changes to the two sets of priors\n        self.all_priors = self.iterative_sampling_priors + self.independent_sampling_priors\n\n        # initialise hierarchical priors' parameters\n        self.update_hierarchical_prior_params(self.model_parameters)\n\n        # Select starting params\n        # Random seed is reset in here; make sure any other seeding happens after this\n        self.starting_point = set_initial_point(\n            self.all_priors, model_parameters_data, chain_idx, num_chains, self.initialisation_type\n        )\n\n        # Set chain specific seed\n        # Chain 0 will have seed equal to that set in the calibration initialisation\n        self.seed_chain = chain_idx * 1000 + self.seed\n\n        # initialise output and save metadata\n        self.output = CalibrationOutputs(chain_idx, project.model_name, project.region_name)\n        self.save_metadata(chain_idx, project, model_parameters_data)\n\n        self.workout_unspecified_target_sds()  # for likelihood definition\n        self.workout_unspecified_time_weights()  # for likelihood weighting\n        self.workout_unspecified_jumping_stdevs()  # for proposal function definition\n        self.param_bounds = self.get_parameter_bounds()\n\n        self.build_transformations()\n\n        self.latest_model = None\n        self.mcmc_trace_matrix = None  # will store the results of the MCMC model calibration\n\n        if self.chain_idx == 0:\n            plots.calibration.plot_pre_calibration(self.all_priors, self.output.output_dir)\n\n        self.is_vic_super_model = False\n        if \"victorian_clusters\" in model_parameters_data:\n            if model_parameters_data[\"victorian_clusters\"]:\n                self.is_vic_super_model = True\n\n        # Set up a flag so that we run a full model validation the first iteration,\n        # but disable for subsequent iterations\n        self._is_first_run = True\n\n        # Actually run the calibration\n        self.run_fitting_algorithm(\n            run_mode=CalibrationMode.AUTUMN_MCMC,\n            n_chains=num_chains,\n            available_time=max_seconds,\n        )\n\n    def update_hierarchical_prior_params(self, current_params=None):\n        for h_p in self.hierarchical_priors:\n            # work out hyper-parameter values\n            distri_params = copy(h_p.hyper_parameters)\n            for i, p in enumerate(distri_params):\n                if isinstance(p, str):\n                    if isinstance(current_params, Params):\n                        distri_params[i] = current_params[p]\n                    else:\n                        param_index = [par['param_name'] for par in self.all_priors].index(p)\n                        distri_params[i] = current_params[param_index]\n            \n            # update prior lists\n            for prior in self.all_priors:\n                if prior[\"param_name\"] == h_p.name:\n                    prior[\"distri_params\"] = distri_params\n                    break    \n\n            for prior in self.iterative_sampling_priors:\n                if prior[\"param_name\"] == h_p.name:\n                    prior[\"distri_params\"] = distri_params\n                    break   \n\n    def validate_target_start_time(self, model_parameters_data):\n        model_start = model_parameters_data[\"time\"][\"start\"]\n        max_prior_start = None\n        for p in self.all_priors:\n            if p[\"param_name\"] == \"time.start\":\n                max_prior_start = max(p[\"distri_params\"])\n\n        for t in self.targets:\n            t_name = t.data.name\n            min_t = min(t.data.index)\n            msg = f\"Target {t_name} has time {min_t} before model start {model_start}.\"\n            assert min_t >= model_start, msg\n            if max_prior_start:\n                msg = f\"Target {t_name} has time {min_t} before prior start {max_prior_start}.\"\n                assert min_t >= max_prior_start, msg\n\n    def save_metadata(self, chain_idx, project, model_parameters_data):\n        metadata = {\n            \"app_name\": project.model_name,\n            \"region_name\": project.region_name,\n            \"start_time\": datetime.now().strftime(\"%Y-%m-%d--%H-%M-%S\"),\n            \"git_branch\": get_git_branch(),\n            \"git_commit\": get_git_hash(),\n            \"seed_chain\": self.seed_chain,\n            \"seed\": self.seed\n        }\n        self.output.write_metadata(f\"meta-{chain_idx}.yml\", metadata)\n        self.output.write_metadata(f\"params-{chain_idx}.yml\", model_parameters_data)\n        self.output.write_metadata(f\"priors-{chain_idx}.yml\", self.all_priors)\n        self.output.write_metadata(f\"targets-{chain_idx}.yml\", self.targets)\n\n    def run_model_with_params(self, proposed_params: dict):\n        \"\"\"\n        Run the model with a set of params.\n        \"\"\"\n        logger.info(f\"Running iteration {self.run_num}...\")\n        # Update default parameters to use calibration params.\n        param_updates = {\"time.end\": self.end_time}\n        for param_name, value in proposed_params.items():\n            param_updates[param_name] = value\n        iter_params = self.model_parameters.update(param_updates, calibration_format=True)\n\n        # Update the random_process attribute with the current rp config for later likelihood evaluation\n        if self.includes_random_process:\n            self.random_process.coefficients = [proposed_params[f\"random_process.coefficients({i})\"] for i in range(self.random_process.order)]\n            self.random_process.noise_sd = proposed_params[\"random_process.noise_sd\"]\n            self.random_process.values = [0.] + [proposed_params[f\"random_process.values({k})\"] for k in range(1, len(self.random_process.values))]\n\n        if self._is_first_run:\n            self.build_options = dict(enable_validation = True)\n\n        self.latest_model = self.project.run_baseline_model(\n            iter_params, derived_outputs_whitelist=self.derived_outputs_whitelist,\n            build_options = self.build_options\n        )\n        \n        if self._is_first_run:\n            self._is_first_run = False\n            self.build_options['enable_validation'] = False\n            self.build_options['derived_outputs_idx_cache'] = self.latest_model._derived_outputs_idx_cache\n\n        return self.latest_model\n\n    def loglikelihood(self, all_params_dict):\n        \"\"\"\n        Calculate the loglikelihood for a set of parameters\n        \"\"\"\n        model = self.run_model_with_params(all_params_dict)\n\n        ll = 0  # loglikelihood if using bayesian approach.\n        for target in self.targets:\n            key = target.data.name\n            data = target.data.to_numpy()\n            time_weights = target.time_weights\n            indices = []\n            for t in target.data.index:\n                time_idxs = np.where(model.times == t)[0]\n                time_idx = time_idxs[0]\n                indices.append(time_idx)\n\n            model_output = model.derived_outputs[key][indices]\n            if self.run_mode == CalibrationMode.AUTUMN_MCMC:\n                if target.loglikelihood_distri in [\"normal\", \"trunc_normal\"]:\n                    # Retrieve the value of the standard deviation\n                    if key + \"_dispersion_param\" in all_params_dict:\n                        normal_sd = all_params_dict[key + \"_dispersion_param\"]\n                    elif \"target_output_ratio\" in all_params_dict:\n                        normal_sd = all_params_dict[\"target_output_ratio\"] * max(target.data)\n                    else:\n                        normal_sd = target.stdev\n\n                    if target.loglikelihood_distri == \"normal\":\n                        squared_distance = (data - model_output) ** 2\n                        ll += -(0.5 / normal_sd ** 2) * np.sum(\n                            [w * d for (w, d) in zip(time_weights, squared_distance)]\n                        )\n                    else:  # this is a truncated normal likelihood\n                        logpdf_arr =  truncnormal_logpdf(data, model_output, target.trunc_range, normal_sd)\n                        ll += (logpdf_arr * time_weights).sum()\n                elif target.loglikelihood_distri == \"poisson\":\n                    for i in range(len(data)):\n                        ll += (\n                            round(data[i]) * math.log(abs(model_output[i]))\n                            - model_output[i]\n                            - math.log(math.factorial(round(data[i])))\n                        ) * time_weights[i]\n                elif target.loglikelihood_distri == \"negative_binomial\":\n                    if key + \"_dispersion_param\" in all_params_dict:\n                        # the dispersion parameter varies during the MCMC. We need to retrieve its value\n                        n = all_params_dict[key + \"_dispersion_param\"]\n                    elif target.dispersion_param is not None:\n                        n = target.dispersion_param\n                    else:\n                        raise ValueError(f\"A dispersion_param is required for target {key}\")\n\n                    for i in range(len(data)):\n                        # We use the parameterisation based on mean and variance and assume define var=mean**delta\n                        mu = model_output[i]\n                        # work out parameter p to match the distribution mean with the model output\n                        p = mu / (mu + n)\n                        ll += stats.nbinom.logpmf(round(data[i]), n, 1.0 - p) * time_weights[i]\n                else:\n                    raise ValueError(\"Distribution not supported in loglikelihood_distri\")\n\n        return ll\n\n    def workout_unspecified_target_sds(self):\n        \"\"\"\n        If the sd parameter of the targeted output is not specified, it will be calculated automatically such that the\n        95% CI of the associated normal distribution covers a width equivalent to 25% of the maximum value of the target.\n        :return:\n        \"\"\"\n        for i, target in enumerate(self.targets):\n            if target.stdev is None:\n                if (\n                    # Do we ever use this?  Doesn't show up anywhere in the codebase..\n                    target.cis is not None\n                ):  # match normal likelihood 95% width with data 95% CI with\n                # +++ This will crash, but we should rewrite it when it does (Romain to explain), since this is very opaque right now...\n                    target.stdev = (\n                        target[\"cis\"][0][1] - target[\"cis\"][0][0]\n                    ) / 4.0\n                else:\n                    target.stdev = 0.25 / 4.0 * max(target.data)\n\n    def workout_unspecified_time_weights(self):\n        \"\"\"\n        Will assign a weight to each time point of each calibration target. If no weights were requested, we will use\n        1/n for each time point, where n is the number of time points.\n        If a list of weights was specified, it will be rescaled so the weights sum to 1.\n        \"\"\"\n        for i, target in enumerate(self.targets):\n            if target.time_weights is None:\n                target.time_weights = np.ones(len(target.data)) / len(target.data)\n            else:\n                assert len(target.time_weights) == len(target.data)\n                s = sum(target.time_weights)\n                target.time_weights = target.time_weights / s\n\n    def workout_unspecified_jumping_stdevs(self):\n        for i, prior_dict in enumerate(self.iterative_sampling_priors):\n            if \"jumping_stdev\" not in prior_dict.keys():\n                prior_low, prior_high = get_parameter_finite_range_from_prior(prior_dict)\n                prior_width = prior_high - prior_low\n\n                #  95% of the sampled values within [mu - 2*sd, mu + 2*sd], i.e. interval of witdth 4*sd\n                relative_prior_width = (\n                    self.metropolis_init_rel_step_size  # fraction of prior_width in which 95% of samples should fall\n                )\n                self.iterative_sampling_priors[i][\"jumping_stdev\"] = (\n                    relative_prior_width * prior_width * self.initial_jumping_stdev_ratio\n                )\n\n    def run_fitting_algorithm(\n        self,\n        run_mode: str,\n        n_chains=1,\n        available_time=None,\n    ):\n        \"\"\"\n        master method to run model calibration.\n\n        :param run_mode: string\n            only 'autumn_mcmc' is currently supported\n        :param n_chains: number of chains to be run\n        :param available_time: maximal simulation time allowed (in seconds)\n        \"\"\"\n        self.run_mode = run_mode\n        if run_mode not in CalibrationMode.MODES:\n            msg = f\"Requested run mode is not supported. Must be one of {CalibrationMode.MODES}\"\n            raise ValueError(msg)\n\n        # Initialise random seed differently for different chains\n        np.random.seed(self.seed_chain)\n\n        try:\n            # Run the selected fitting algorithm.\n            if run_mode == CalibrationMode.AUTUMN_MCMC:\n                self.run_autumn_mcmc(available_time)\n\n        finally:\n            self.write_outputs()\n\n    def write_outputs(self):\n        \"\"\"Ensure output data from run is written to disk, including model state for resume\n        \"\"\"\n        self.output.write_data_to_disk()\n        if not self._no_pickle:\n            state_pkl_filename = os.path.join(self.output.output_dir, f\"calstate-{self.chain_idx}.pkl\")\n            pickle.dump(self, open(state_pkl_filename, 'wb'))\n\n    def test_in_prior_support(self, iterative_params):\n        in_support = True\n        for i, prior_dict in enumerate(self.iterative_sampling_priors):\n            param_name = prior_dict[\"param_name\"]\n            # Work out bounds for acceptable values, using the support of the prior distribution\n            lower_bound = self.param_bounds[param_name][0]\n            upper_bound = self.param_bounds[param_name][1]\n            if iterative_params[i] < lower_bound or iterative_params[i] > upper_bound:\n                in_support = False\n                break\n\n        return in_support\n\n    def run_autumn_mcmc(\n        self,\n        available_time\n    ):\n        \"\"\"\n        Run our hand-rolled MCMC algorithm to calibrate model parameters.\n        \"\"\"\n\n        self.mcmc_trace_matrix = None  # will store param trace and loglikelihood evolution\n\n        self.last_accepted_iterative_params_trans = None\n        self.last_acceptance_quantity = None  # acceptance quantity is defined as loglike + logprior\n        self.n_accepted = 0\n        self.n_iters_real = 0  # Actual number of iterations completed, as opposed to run_num.\n        self.run_num = 0  # Canonical id of the MCMC run, will be the same as iters until reset by adaptive algo.\n    \n        self.enter_mcmc_loop(available_time)\n\n    def resume_autumn_mcmc(self, available_time: int = None, max_iters: int = None, finalise=True):\n        try:\n            self.enter_mcmc_loop(available_time, max_iters)\n        finally:\n            if finalise:\n                self.write_outputs()\n            \n    def enter_mcmc_loop(self, available_time: int = None, max_iters: int = None):\n        start_time = time()\n\n        if max_iters:\n            if self.n_iters_real >= max_iters:\n                msg = f\"Not resuming run. Existing run already has {self.n_iters_real} iterations; max_iters = {max_iters}\"\n                logger.info(msg)\n                return\n\n        while True:\n            logging.info(\"Running MCMC iteration %s, run %s\", self.n_iters_real, self.run_num)\n\n            # Not actually LHS sampling - just sampling directly from prior.\n            independent_samples = draw_independent_samples(self.independent_sampling_priors)\n\n            # Propose new parameter set.\n            proposed_iterative_params_trans = self.propose_new_iterative_params_trans(\n                self.last_accepted_iterative_params_trans, self.haario_scaling_factor\n            )\n            proposed_iterative_params = self.get_original_params(proposed_iterative_params_trans)\n\n            self.update_hierarchical_prior_params(proposed_iterative_params)\n\n            is_within_prior_support = self.test_in_prior_support(\n                proposed_iterative_params\n            )  # should always be true but this is a good safety check\n\n            # combine all sampled params into a single dictionary\n            iterative_samples_dict = {\n                self.iterative_sampling_param_names[i]: proposed_iterative_params[i]\n                for i in range(len(proposed_iterative_params))\n            }\n            all_params_dict = {**iterative_samples_dict, **independent_samples}\n\n            if is_within_prior_support:\n                # Evaluate log-likelihood.\n                proposed_loglike = self.loglikelihood(all_params_dict)\n\n                # Evaluate log-prior.\n                proposed_logprior = self.logprior(all_params_dict)\n\n                # Evaluate the log-likelihood of the random process if applicable\n                if self.includes_random_process:\n                    proposed_logprior += self.random_process.evaluate_rp_loglikelihood()\n\n                # posterior distribution\n                proposed_log_posterior = proposed_loglike + proposed_logprior\n\n                # transform the density\n                proposed_acceptance_quantity = proposed_log_posterior\n                for i, prior_dict in enumerate(\n                    self.iterative_sampling_priors\n                ):  # multiply the density with the determinant of the Jacobian\n                    inv_derivative = self.transform[prior_dict[\"param_name\"]][\"inverse_derivative\"](\n                        proposed_iterative_params_trans[i]\n                    )\n                    if inv_derivative > 0:\n                        proposed_acceptance_quantity += math.log(inv_derivative)\n                    else:\n                        proposed_acceptance_quantity += math.log(1.0e-100)\n\n                is_auto_accept = (\n                    self.last_acceptance_quantity is None\n                    or proposed_acceptance_quantity >= self.last_acceptance_quantity\n                )\n                if is_auto_accept:\n                    accept = True\n                else:\n                    accept_prob = np.exp(proposed_acceptance_quantity - self.last_acceptance_quantity)\n                    accept = (np.random.binomial(n=1, p=accept_prob, size=1) > 0)[0]\n            else:\n                accept = False\n                proposed_loglike = None\n                proposed_acceptance_quantity = None\n\n            # Update stored quantities.\n            if accept:\n                self.last_accepted_iterative_params_trans = proposed_iterative_params_trans\n                self.last_acceptance_quantity = proposed_acceptance_quantity\n                self.n_accepted += 1\n\n            self.update_mcmc_trace(self.last_accepted_iterative_params_trans)\n\n            # Store model outputs\n            self.output.store_mcmc_iteration(\n                all_params_dict,\n                proposed_loglike,\n                proposed_log_posterior,\n                accept,\n                self.run_num,\n            )\n            if accept:\n                self.output.store_model_outputs(self.latest_model, self.run_num)\n\n            logging.info(\"Finished MCMC iteration %s, run %s\", self.n_iters_real, self.run_num)\n            self.run_num += 1\n            self.n_iters_real += 1\n            if available_time:\n                # Stop iterating if we have run out of time.\n                elapsed_time = time() - start_time\n                if elapsed_time > available_time:\n                    msg = f\"Stopping MCMC simulation after {self.n_iters_real} iterations because of {available_time}s time limit\"\n                    logger.info(msg)\n                    break\n            if max_iters:\n                # Stop running if we have performed enough iterations\n                if self.n_iters_real >= max_iters:\n                    msg = f\"Stopping MCMC simulation after {self.n_iters_real} iterations, maximum iterations hit\"\n                    logger.info(msg)\n                    break\n\n            # Check that the pre-adaptive phase ended with a decent acceptance ratio\n            if self.adaptive_proposal and self.run_num == self.n_steps_fixed_proposal:\n                acceptance_ratio = self.n_accepted / self.run_num\n                logger.info(\n                    \"Pre-adaptive phase completed at %s iterations after %s runs with an acceptance ratio of %s.\",\n                    self.n_iters_real,\n                    self.run_num,\n                    acceptance_ratio,\n                )\n                if acceptance_ratio < ADAPTIVE_METROPOLIS[\"MIN_ACCEPTANCE_RATIO\"]:\n                    logger.info(\"Acceptance ratio too low, restart sampling from scratch.\")\n                    (\n                        self.run_num,\n                        self.n_accepted,\n                        self.last_accepted_params_trans,\n                        self.last_acceptance_quantity,\n                    ) = (0, 0, None, None)\n                    self.reduce_proposal_step_size()\n                    self.output.delete_stored_iterations()\n                else:\n                    logger.info(\"Acceptance ratio acceptable, continue sampling.\")\n\n    def reduce_proposal_step_size(self):\n        \"\"\"\n        Reduce the \"jumping_stdev\" associated with each parameter during the pre-adaptive phase\n        \"\"\"\n        for i in range(len(self.iterative_sampling_priors)):\n            self.iterative_sampling_priors[i][\"jumping_stdev\"] *= self.jumping_stdev_adjustment\n\n    def build_adaptive_covariance_matrix(self, haario_scaling_factor):\n        scaling_factor = haario_scaling_factor ** 2 / len(\n            self.iterative_sampling_priors\n        )  # from Haario et al. 2001\n        cov_matrix = np.cov(self.mcmc_trace_matrix, rowvar=False)\n        adaptive_cov_matrix = scaling_factor * cov_matrix + scaling_factor * ADAPTIVE_METROPOLIS[\n            \"EPSILON\"\n        ] * np.eye(len(self.iterative_sampling_priors))\n        return adaptive_cov_matrix\n\n    def get_parameter_bounds(self):\n        param_bounds = {}\n        for i, prior_dict in enumerate(\n            self.iterative_sampling_priors + self.independent_sampling_priors\n        ):\n            # Work out bounds for acceptable values, using the support of the prior distribution\n            lower_bound, upper_bound = get_parameter_bounds_from_priors(prior_dict)\n            param_bounds[prior_dict[\"param_name\"]] = [lower_bound, upper_bound]\n\n        return param_bounds\n\n    def build_transformations(self, update_jumping_stdev=True):\n        \"\"\"\n        Build transformation functions between the parameter space and R^n.\n        \"\"\"\n        self.transform = {}\n        for i, prior_dict in enumerate(self.iterative_sampling_priors):\n            param_name = prior_dict[\"param_name\"]\n            self.transform[param_name] = {\n                \"direct\": None,  # param support to R\n                \"inverse\": None,  # R to param space\n                \"inverse_derivative\": None,  # R to R\n            }\n            lower_bound = self.param_bounds[param_name][0]\n            upper_bound = self.param_bounds[param_name][1]\n\n            original_sd = self.iterative_sampling_priors[i][\n                \"jumping_stdev\"\n            ]  # we will need to transform the jumping step\n\n            # trivial case of an unbounded parameter\n            if lower_bound == -float(\"inf\") and upper_bound == float(\"inf\"):\n                self.transform[param_name][\"direct\"] = lambda x: x\n                self.transform[param_name][\"inverse\"] = lambda x: x\n                self.transform[param_name][\"inverse_derivative\"] = lambda x: 1.0\n\n                representative_point = None\n            # case of a lower-bounded parameter with infinite support\n            elif upper_bound == float(\"inf\"):\n                for func_type in [\"direct\", \"inverse\", \"inverse_derivative\"]:\n                    self.transform[param_name][func_type] = make_transform_func_with_lower_bound(\n                        lower_bound, func_type\n                    )\n                representative_point = lower_bound + 10 * original_sd\n                if self.starting_point[param_name] <= lower_bound:\n                    self.starting_point[param_name] = lower_bound + original_sd / 10\n\n            # case of an upper-bounded parameter with infinite support\n            elif lower_bound == -float(\"inf\"):\n                for func_type in [\"direct\", \"inverse\", \"inverse_derivative\"]:\n                    self.transform[param_name][func_type] = make_transform_func_with_upper_bound(\n                        upper_bound, func_type\n                    )\n\n                representative_point = upper_bound - 10 * original_sd\n                if self.starting_point[param_name] >= upper_bound:\n                    self.starting_point[param_name] = upper_bound - original_sd / 10\n            # case of a lower- and upper-bounded parameter\n            else:\n                for func_type in [\"direct\", \"inverse\", \"inverse_derivative\"]:\n                    self.transform[param_name][func_type] = make_transform_func_with_two_bounds(\n                        lower_bound, upper_bound, func_type\n                    )\n\n                representative_point = 0.5 * (lower_bound + upper_bound)\n                if self.starting_point[param_name] <= lower_bound:\n                    self.starting_point[param_name] = lower_bound + original_sd / 10\n                elif self.starting_point[param_name] >= upper_bound:\n                    self.starting_point[param_name] = upper_bound - original_sd / 10\n\n            # Don't update jumping if we are resuming (this has already been calculated)\n            # FIXME:  We should probably refactor this to update on copies rather than in place\n            if representative_point is not None and update_jumping_stdev:\n                transformed_low = self.transform[param_name][\"direct\"](\n                    representative_point - original_sd / 4\n                )\n                transformed_up = self.transform[param_name][\"direct\"](\n                    representative_point + original_sd / 4\n                )\n                self.iterative_sampling_priors[i][\"jumping_stdev\"] = abs(\n                    transformed_up - transformed_low\n                )\n\n    def get_original_params(self, transformed_iterative_params):\n        original_iterative_params = []\n        for i, prior_dict in enumerate(self.iterative_sampling_priors):\n            original_iterative_params.append(\n                self.transform[prior_dict[\"param_name\"]][\"inverse\"](transformed_iterative_params[i])\n            )\n        return original_iterative_params\n\n    def propose_new_iterative_params_trans(\n        self, prev_iterative_params_trans, haario_scaling_factor=2.4\n    ):\n        \"\"\"\n        calculated the joint log prior\n        :param prev_iterative_params_trans: last accepted parameter values as a list ordered using the order of\n         self.iterative_sampling_priors\n        :return: a new list of parameter values\n        \"\"\"\n        new_iterative_params_trans = []\n        # if this is the initial step\n        if prev_iterative_params_trans is None:\n            for prior_dict in self.iterative_sampling_priors:\n                start_point = self.starting_point[prior_dict[\"param_name\"]]\n                new_iterative_params_trans.append(\n                    self.transform[prior_dict[\"param_name\"]][\"direct\"](start_point)\n                )\n            return new_iterative_params_trans\n\n        use_adaptive_proposal = (\n            self.adaptive_proposal and self.run_num > self.n_steps_fixed_proposal\n        )\n\n        if use_adaptive_proposal:\n            adaptive_cov_matrix = self.build_adaptive_covariance_matrix(haario_scaling_factor)\n            if np.all((adaptive_cov_matrix == 0)):\n                use_adaptive_proposal = (\n                    False  # we can't use the adaptive method for this step as the covariance is 0.\n                )\n            else:\n                new_iterative_params_trans = sample_from_adaptive_gaussian(\n                    prev_iterative_params_trans, adaptive_cov_matrix\n                )\n\n        if not use_adaptive_proposal:\n            for i, prior_dict in enumerate(self.iterative_sampling_priors):\n                sample = np.random.normal(\n                    loc=prev_iterative_params_trans[i], scale=prior_dict[\"jumping_stdev\"], size=1\n                )[0]\n                new_iterative_params_trans.append(sample)\n\n        return new_iterative_params_trans\n\n    def logprior(self, all_params_dict):\n        \"\"\"\n        calculated the joint log prior\n        :param all_params_dict: model parameters as a dictionary\n        :return: the natural log of the joint prior\n        \"\"\"\n        logp = 0.0\n        for param_name, value in all_params_dict.items():\n            prior_dict = [d for d in self.all_priors if d[\"param_name\"] == param_name][0]\n            if \"skip_evaluation\" in prior_dict:\n                if prior_dict[\"skip_evaluation\"]:\n                    continue\n            logp += calculate_prior(prior_dict, value, log=True)\n\n        return logp\n\n    def update_mcmc_trace(self, params_to_store):\n        \"\"\"\n        store mcmc iteration into param_trace\n        :param params_to_store: model parameters as a list of values ordered using the order of self.iterative_sampling_priors\n        :param loglike_to_store: current loglikelihood value\n        \"\"\"\n        if self.mcmc_trace_matrix is None:\n            self.mcmc_trace_matrix = np.array([params_to_store])\n        else:\n            self.mcmc_trace_matrix = np.concatenate(\n                (self.mcmc_trace_matrix, np.array([params_to_store]))\n            )\n\n\nclass CalibrationOutputs:\n    \"\"\"\n    Handles writing outputs for the calibration process\n    \"\"\"\n\n    def __init__(self, chain_id: int, app_name: str, region_name: str):\n        self.chain_id = chain_id\n        # List of dicts for tracking MCMC progress.\n        self.mcmc_runs = []\n        self.mcmc_params = []\n\n        # Setup output directory\n        project_dir = os.path.join(settings.OUTPUT_DATA_PATH, \"calibrate\", app_name, region_name)\n        timestamp = datetime.now().strftime(\"%Y-%m-%d\")\n        # A bit of a hack to write to a different directory when running jobs in AWS.\n        self.output_dir = os.environ.get(\n            \"AUTUMN_CALIBRATE_DIR\", os.path.join(project_dir, timestamp)\n        )\n        db_name = f\"chain-{chain_id}\"\n        self.output_db_path = os.path.join(self.output_dir, db_name)\n        if os.path.exists(self.output_db_path):\n            # Delete existing data.\n            logger.info(\"File found at %s, recreating %s\", self.output_db_path, self.output_dir)\n            shutil.rmtree(self.output_dir)\n\n        logger.info(\"Created data directory at %s\", self.output_dir)\n        os.makedirs(self.output_dir, exist_ok=True)\n        self.db = db.ParquetDatabase(self.output_db_path)\n\n    @classmethod\n    def from_existing(cls, chain_id, output_dir):\n        obj = cls.__new__(cls)\n        obj.output_dir = output_dir\n\n        db_name = f\"chain-{chain_id}\"\n\n        obj.output_db_path = os.path.join(obj.output_dir, db_name)\n        obj.db = db.ParquetDatabase(obj.output_db_path)\n\n        obj.chain_id = chain_id\n\n        # List of dicts for tracking MCMC progress.\n        #obj.mcmc_runs = []\n        #obj.mcmc_params = []\n        obj.load_mcmc()\n\n        return obj\n\n    def load_mcmc(self):\n        \"\"\"Read MCMC calibration data from disk (for resuming an existing run)\n        \"\"\"\n        self.mcmc_runs = self.db.query('mcmc_run').to_dict('records')\n        self.mcmc_params = self.db.query('mcmc_params').to_dict('records')\n\n    def write_metadata(self, filename, data):\n        file_path = os.path.join(self.output_dir, filename)\n        with open(file_path, \"w\") as f:\n            yaml.dump(data, f)\n\n    def delete_stored_iterations(self):\n        self.db.close()\n        self.db.delete_everything()\n        self.mcmc_runs = []\n        self.mcmc_params = []\n\n    def store_model_outputs(self, model, iter_num: int):\n        \"\"\"\n        Record the model outputs for this iteration\n        \"\"\"\n        assert model and model.outputs is not None, \"No model has been run\"\n        #outputs_df = db.store.build_outputs_table([model], run_id=iter_num, chain_id=self.chain_id)\n        derived_outputs_df = db.store.build_derived_outputs_table(\n            [model], run_id=iter_num, chain_id=self.chain_id\n        )\n        #self.db.append_df(db.store.Table.OUTPUTS, outputs_df)\n        self.db.append_df(db.store.Table.DERIVED, derived_outputs_df)\n\n    def store_mcmc_iteration(\n        self,\n        all_params_dict: dict,\n        proposed_loglike: float,\n        proposed_acceptance_quantity: float,\n        accept: bool,\n        i_run: int,\n    ):\n        \"\"\"\n        Records the MCMC iteration details\n        :param proposed_params: the current parameter values\n        :param proposed_loglike: the current loglikelihood\n        :param accept: whether the iteration was accepted or not\n        :param i_run: the iteration number\n        \"\"\"\n        mcmc_run = {\n            \"chain\": self.chain_id,\n            \"run\": i_run,\n            \"loglikelihood\": proposed_loglike,\n            \"ap_loglikelihood\": proposed_acceptance_quantity,\n            \"accept\": 1 if accept else 0,\n            \"weight\": 0,  # Default to zero, re-calculate this later.\n        }\n        self.mcmc_runs.append(mcmc_run)\n        if accept:\n            # Write run parameters.\n            for param_name, value in all_params_dict.items():\n                mcmc_params = {\n                    \"chain\": self.chain_id,\n                    \"run\": i_run,\n                    \"name\": param_name,\n                    \"value\": value,\n                }\n                self.mcmc_params.append(mcmc_params)\n\n    def write_data_to_disk(self):\n        \"\"\"\n        Write in-memory calibration data to disk\n        \"\"\"\n        if not self.mcmc_runs:\n            logger.info(\"No data to write to disk\")\n            return\n\n        # Close Parquet writer used to write data for outputs / derived outputs.\n        self.db.close()\n\n        with Timer(\"Writing calibration data to disk.\"):\n            # Write parameters\n            mcmc_params_df = pd.DataFrame.from_dict(self.mcmc_params)\n            self.db.dump_df(db.store.Table.PARAMS, mcmc_params_df, append=False)\n            # Calculate iterations weights, then write to disk\n            weight = 0\n            for mcmc_run in reversed(self.mcmc_runs):\n                weight += 1\n                if mcmc_run[\"accept\"]:\n                    mcmc_run[\"weight\"] = weight\n                    weight = 0\n\n            mcmc_runs_df = pd.DataFrame.from_dict(self.mcmc_runs)\n            self.db.dump_df(db.store.Table.MCMC, mcmc_runs_df, append=False)\n\n\ndef check_hierarchical_priors(hierarchical_priors, priors):\n    prior_names = [p.name for p in priors]\n    for h_p in hierarchical_priors:\n        variable_hyper_parameters = h_p.list_variable_hyper_parameters()\n        for p_name in variable_hyper_parameters:\n            msg = f\"{p_name} is defined as a hyper-parameter but is not associated with a prior\"\n            assert p_name in prior_names, msg\n\ndef get_parameter_bounds_from_priors(prior_dict):\n    \"\"\"\n    Determine lower and upper bounds of a parameter by analysing its assigned prior distribution\n    :param prior_dict: dictionary defining a parameter's prior distribution\n    :return: lower_bound, upper_bound\n    \"\"\"\n    if prior_dict[\"distribution\"] == \"uniform\":\n        lower_bound = prior_dict[\"distri_params\"][0]\n        upper_bound = prior_dict[\"distri_params\"][1]\n    elif prior_dict[\"distribution\"] in [\"lognormal\", \"gamma\", \"weibull\", \"exponential\"]:\n        lower_bound = 0.0\n        upper_bound = float(\"inf\")\n    elif prior_dict[\"distribution\"] == \"normal\":\n        lower_bound = - float(\"inf\")\n        upper_bound = float(\"inf\")\n    elif prior_dict[\"distribution\"] == \"trunc_normal\":\n        lower_bound = prior_dict[\"trunc_range\"][0]\n        upper_bound = prior_dict[\"trunc_range\"][1]\n    elif prior_dict[\"distribution\"] == \"beta\":\n        lower_bound = 0.0\n        upper_bound = 1.0\n    else:\n        raise ValueError(\"prior distribution bounds detection currently not handled.\")\n\n    return lower_bound, upper_bound\n\n\ndef get_parameter_finite_range_from_prior(prior_dict):\n    if prior_dict[\"distribution\"] == \"uniform\":\n        prior_low = prior_dict[\"distri_params\"][0]\n        prior_high = prior_dict[\"distri_params\"][1]\n    elif prior_dict[\"distribution\"] == \"lognormal\":\n        mu = prior_dict[\"distri_params\"][0]\n        sd = prior_dict[\"distri_params\"][1]\n        prior_low = math.exp(mu + math.sqrt(2) * sd * special.erfinv(2 * 0.025 - 1))\n        prior_high = math.exp(mu + math.sqrt(2) * sd * special.erfinv(2 * 0.975 - 1))\n    elif prior_dict[\"distribution\"] == \"trunc_normal\":\n        mu = prior_dict[\"distri_params\"][0]\n        sd = prior_dict[\"distri_params\"][1]\n        bounds = prior_dict[\"trunc_range\"]\n        prior_low = stats.truncnorm.ppf(\n            0.025, (bounds[0] - mu) / sd, (bounds[1] - mu) / sd, loc=mu, scale=sd\n        )\n        prior_high = stats.truncnorm.ppf(\n            0.975, (bounds[0] - mu) / sd, (bounds[1] - mu) / sd, loc=mu, scale=sd\n        )\n    elif prior_dict[\"distribution\"] == \"normal\":\n        mu = prior_dict[\"distri_params\"][0]\n        sd = prior_dict[\"distri_params\"][1]\n        prior_low = stats.norm.ppf(\n            0.025, loc=mu, scale=sd\n        )\n        prior_high = stats.norm.ppf(\n            0.975, loc=mu, scale=sd\n        )\n    elif prior_dict[\"distribution\"] == \"beta\":\n        prior_low = stats.beta.ppf(\n            0.025,\n            prior_dict[\"distri_params\"][0],\n            prior_dict[\"distri_params\"][1],\n        )\n        prior_high = stats.beta.ppf(\n            0.975,\n            prior_dict[\"distri_params\"][0],\n            prior_dict[\"distri_params\"][1],\n        )\n    elif prior_dict[\"distribution\"] == \"gamma\":\n        prior_low = stats.gamma.ppf(\n            0.025,\n            prior_dict[\"distri_params\"][0],\n            0.0,\n            prior_dict[\"distri_params\"][1],\n        )\n        prior_high = stats.gamma.ppf(\n            0.975,\n            prior_dict[\"distri_params\"][0],\n            0.0,\n            prior_dict[\"distri_params\"][1],\n        )\n    else:\n        raise_error_unsupported_prior(prior_dict[\"distribution\"])\n\n    return prior_low, prior_high\n\n\ndef sample_from_adaptive_gaussian(prev_params, adaptive_cov_matrix):\n    return np.random.multivariate_normal(prev_params, adaptive_cov_matrix)\n\n\ndef remove_early_points_to_prevent_crash(target_outputs, priors):\n    \"\"\"\n    Trim the beginning of the time series when model start time is varied during the MCMC\n    \"\"\"\n    idx = None\n    for i, p in enumerate(priors):\n        if p[\"param_name\"] == \"time.start\":\n            idx = i\n            break\n\n    if idx is not None:\n        latest_start_time = priors[idx][\"distri_params\"][1]\n        for target in target_outputs:\n            first_idx_to_keep = next(\n                t_idx for t_idx, t_val in enumerate(target.data.index) if t_val > latest_start_time\n            )\n            target.data = target.data.iloc[first_idx_to_keep:]\n            #target[\"values\"] = target[\"values\"][first_idx_to_keep:]\n\n    return target_outputs\n\n\ndef set_initial_point(\n    priors, model_parameters: dict, chain_idx, total_nb_chains, initialisation_type\n):\n    \"\"\"\n    Determine the starting point of the MCMC.\n    \"\"\"\n    if initialisation_type == MetroInit.LHS:\n        # draw samples using LHS based on the prior distributions\n        np.random.seed(0)  # Set deterministic random seed for Latin Hypercube Sampling\n        starting_points = sample_starting_params_from_lhs(priors, total_nb_chains)\n\n        return starting_points[chain_idx - 1]\n    elif initialisation_type == MetroInit.CURRENT_PARAMS:\n        # use the current parameter values from the yaml files\n        starting_points = read_current_parameter_values(priors, model_parameters)\n        return starting_points\n    else:\n        raise ValueError(f\"{initialisation_type} is not a supported Initialisation Type\")\n\n\ndef read_current_parameter_values(priors, model_parameters):\n    starting_points = {}\n    for param_dict in priors:\n        if param_dict[\"param_name\"].endswith(\"dispersion_param\"):\n            assert param_dict[\"distribution\"] == \"uniform\"\n            starting_points[param_dict[\"param_name\"]] = np.mean(param_dict[\"distri_params\"])\n        else:\n            starting_points[param_dict[\"param_name\"]] = read_param_value_from_string(\n                model_parameters, param_dict[\"param_name\"]\n            )\n\n    return starting_points\n", "meta": {"hexsha": "72b27a21538163000b7ba4a14e31b1731c4cd606", "size": 51969, "ext": "py", "lang": "Python", "max_stars_repo_path": "autumn/calibration/calibration.py", "max_stars_repo_name": "emmamcbryde/AuTuMN-1", "max_stars_repo_head_hexsha": "b1e7de15ac6ef6bed95a80efab17f0780ec9ff6f", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "autumn/calibration/calibration.py", "max_issues_repo_name": "emmamcbryde/AuTuMN-1", "max_issues_repo_head_hexsha": "b1e7de15ac6ef6bed95a80efab17f0780ec9ff6f", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "autumn/calibration/calibration.py", "max_forks_repo_name": "emmamcbryde/AuTuMN-1", "max_forks_repo_head_hexsha": "b1e7de15ac6ef6bed95a80efab17f0780ec9ff6f", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4930498774, "max_line_length": 147, "alphanum_fraction": 0.626142508, "include": true, "reason": "import numpy,from scipy", "num_tokens": 10862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.1876382324377561}}
{"text": "import numpy as np\nimport astropy.units as u\n\nfrom dust_extinction.shapes import _curve_F99_method\n\nfrom measure_extinction.stardata import StarData, BandData, SpecData\n\n__all__ = [\"ModelData\"]\n\n\nclass ModelData(object):\n    \"\"\"\n    Provide stellar atmosphere model \"observed\" data given input stellar, gas,\n    and dust extinction parameters.\n\n    Parameters\n    ----------\n    modelfiles: string array\n        set of model files to use\n\n    path : string, optional\n        path for model files\n\n    band_names : string array, optional\n        bands to use\n        default = ['U', 'B', 'V', 'J', 'H', 'K']\n\n    spectra_names : string array, optional\n        origin of the spectra to use\n        default = ['STIS']\n\n    Attributes\n    ----------\n    n_models : int\n        number of stellar atmosphere models\n    model_files : string array\n        filenames for the models\n\n    temps : float array\n        log10(effective temperatures)\n    gravs : float array\n        log10(surface gravities)\n    mets : float array\n        log10(metallicities)\n    vturbs : float array\n        microturbulance values [km/s]\n\n    n_bands : int\n        number of photometric bands\n    band_names : string array\n        names of the photometric bands\n\n    n_spectra : int\n        number of different types of spectra\n    spectra_names : string array\n        identifications for the spectra data (includes band data)\n    waves : n_spectra dict\n        wavelengths for the spectra\n    fluxes : n_spectra dict\n        fluxes in the bands\n    flux_uncs : n_spectra list\n        flux uncertainties in the bands\n    \"\"\"\n\n    def __init__(\n        self,\n        modelfiles,\n        path=\"./\",\n        band_names=[\"U\", \"B\", \"V\", \"J\", \"H\", \"K\"],\n        spectra_names=[\"BAND\", \"STIS\"],\n    ):\n\n        self.n_models = len(modelfiles)\n        self.model_files = np.array(modelfiles)\n\n        # physical parameters of models\n        self.temps = np.zeros(self.n_models)\n        self.gravs = np.zeros(self.n_models)\n        self.mets = np.zeros(self.n_models)\n        self.vturb = np.zeros(self.n_models)\n\n        # photometric band data\n        self.n_bands = len(band_names)\n        self.band_names = band_names\n\n        # photometric and spectroscopic data\n        self.n_spectra = len(spectra_names) + 1\n        self.spectra_names = spectra_names\n        self.waves = {}\n        self.fluxes = {}\n        self.flux_uncs = {}\n\n        for cspec in self.spectra_names:\n            self.fluxes[cspec] = None\n            self.flux_uncs[cspec] = None\n\n        # initialize the BAND dictonary entry as the number of elements\n        # is set by the desired bands, not the bands in the files\n        self.waves[\"BAND\"] = np.zeros((self.n_bands))\n        self.fluxes[\"BAND\"] = np.zeros((self.n_models, self.n_bands))\n        self.flux_uncs[\"BAND\"] = np.zeros((self.n_models, self.n_bands))\n\n        # read and store the model data\n        for k, cfile in enumerate(modelfiles):\n            moddata = StarData(cfile, path=path)\n\n            # model parameters\n            self.temps[k] = np.log10(float(moddata.model_params[\"Teff\"]))\n            self.gravs[k] = float(moddata.model_params[\"logg\"])\n            self.mets[k] = np.log10(float(moddata.model_params[\"Z\"]))\n            self.vturb[k] = float(moddata.model_params[\"vturb\"])\n\n            # spectra\n            for cspec in self.spectra_names:\n                # initialize the spectra vectors\n                if self.fluxes[cspec] is None:\n                    self.waves[cspec] = moddata.data[cspec].waves\n                    self.fluxes[cspec] = np.zeros(\n                        (self.n_models, len(moddata.data[cspec].fluxes))\n                    )\n                    self.flux_uncs[cspec] = np.zeros(\n                        (self.n_models, len(moddata.data[cspec].fluxes))\n                    )\n\n                # photometric bands\n                if cspec == \"BAND\":\n                    for i, cband in enumerate(self.band_names):\n                        band_flux = moddata.data[\"BAND\"].get_band_flux(cband)\n                        self.waves[cspec][i] = band_flux[2]\n                        self.fluxes[cspec][k, i] = band_flux[0]\n                        self.flux_uncs[cspec][k, i] = band_flux[1]\n                else:\n                    # get the spectral data\n                    self.fluxes[cspec][k, :] = moddata.data[cspec].fluxes\n                    self.flux_uncs[cspec][k, :] = moddata.data[cspec].uncs\n\n        # add units\n        self.waves[\"BAND\"] = self.waves[\"BAND\"] * u.micron\n\n        # provide the width in model space for each parameter\n        #   used in calculating the nearest neighbors\n        self.n_nearest = 11\n\n        self.temps_min = min(self.temps)\n        self.temps_max = max(self.temps)\n        self.temps_width2 = (self.temps_max - self.temps_min) ** 2\n        # self.temp_width2 = 1.0\n\n        self.gravs_min = min(self.gravs)\n        self.gravs_max = max(self.gravs)\n        self.gravs_width2 = (self.gravs_max - self.gravs_min) ** 2\n\n        self.mets_min = min(self.mets)\n        self.mets_max = max(self.mets)\n        self.mets_width2 = (self.mets_max - self.mets_min) ** 2\n        # self.mets_width2 *= 4.0\n\n    def stellar_sed(self, params, velocity=None):\n        \"\"\"\n        Compute the stellar SED given model parameters\n\n        Parameters\n        ----------\n        params : float array\n            stellar atmosphere parameters [logT, logg, logZ]\n\n        velocity : float\n            stellar velocity in km/s\n\n        Returns\n        -------\n        sed : dict\n            SED with {'bands': band_sed, 'spec': spec_sed, ...}\n        \"\"\"\n        # compute the distance between model params and grid points\n        #    probably a better way using a kdtree\n        dist2 = (\n            (params[0] - self.temps) ** 2 / self.temps_width2\n            + (params[1] - self.gravs) ** 2 / self.gravs_width2\n            + (params[2] - self.mets) ** 2 / self.mets_width2\n        )\n        sindxs = np.argsort(dist2)\n        gsindxs = sindxs[0 : self.n_nearest]\n\n        # generate model SED form nearest neighbors\n        #   should handle the case where dist2 has an element that is zero\n        #   i.e., one of the precomputed models exactly matches the request\n        weights = 1.0 / np.sqrt(dist2[gsindxs])\n        weights /= np.sum(weights)\n\n        # print(params)\n        # print(self.model_files[gsindxs])\n        # exit()\n\n        sed = {}\n        for cspec in self.fluxes.keys():\n            # dot product does the multiplication and sum\n            sed[cspec] = np.dot(weights, self.fluxes[cspec][gsindxs, :])\n            # shift spectrum if velocity given\n            if velocity is not None:\n                cwaves = self.waves[cspec]\n                sed[cspec] = np.interp(\n                    cwaves, (1.0 + velocity / 2.998e5) * cwaves, sed[cspec]\n                )\n\n        return sed\n\n    def dust_extinguished_sed(self, params, sed, velocity=0.0):\n        \"\"\"\n        Dust extinguished sed given the extinction parameters\n\n        Parameters\n        ----------\n        params : float array\n            dust extinction parameters [Av, Rv, c2, c3, c4, gamma, x0]\n\n        sed : dict\n            fluxes for each spectral piece\n\n        velocity : float, optional\n            velocity of dust\n\n        Returns\n        -------\n        extinguished sed : dict\n            SED with {'bands': band_sed, 'spec': spec_sed, ...}\n        \"\"\"\n        Rv = params[1]\n\n        # updated F04 C1-C2 correlation\n        C1 = 2.18 - 2.91 * params[2]\n\n        # spline points\n        opt_axav_x = 10000.0 / np.array([6000.0, 5470.0, 4670.0, 4110.0])\n        # **Use NIR spline x values in FM07, clipped to K band for now\n        nir_axav_x = np.array([0.50, 0.75, 1.0])\n        optnir_axav_x = np.concatenate([nir_axav_x, opt_axav_x])\n\n        # **Keep optical spline points from F99:\n        #    Final optical spline point has a leading \"-1.208\" in Table 4\n        #    of F99, but that does not reproduce Table 3.\n        #    Additional indication that this is not correct is from\n        #    fm_unred.pro\n        #    which is based on FMRCURVE.pro distributed by Fitzpatrick.\n        opt_axebv_y = np.array(\n            [\n                -0.426 + 1.0044 * Rv,\n                -0.050 + 1.0016 * Rv,\n                0.701 + 1.0016 * Rv,\n                1.208 + 1.0032 * Rv - 0.00033 * (Rv ** 2),\n            ]\n        )\n        # updated NIR curve from F04, note R dependence\n        nir_axebv_y = (0.63 * Rv - 0.84) * nir_axav_x ** 1.84\n\n        optnir_axebv_y = np.concatenate([nir_axebv_y, opt_axebv_y])\n\n        # create the extinguished sed\n        ext_sed = {}\n        for cspec in self.fluxes.keys():\n            # get the dust extinguished SED (account for the\n            #  systemic velocity of the galaxy [opposite regular sense])\n            shifted_waves = (1.0 - velocity / 2.998e5) * self.waves[cspec]\n            axav = _curve_F99_method(\n                shifted_waves,\n                Rv,\n                C1,\n                params[2],\n                params[3],\n                params[4],\n                params[5],\n                params[6],\n                optnir_axav_x,\n                optnir_axebv_y / Rv,\n                [0.3, 10.0],\n                \"F04_measure_extinction\",\n            )\n            ext_sed[cspec] = sed[cspec] * (10 ** (-0.4 * axav * params[0]))\n\n        return ext_sed\n\n    def hi_abs_sed(self, params, hi_velocities, sed):\n        \"\"\"\n        HI abs sed given the HI columns\n\n        Parameters\n        ----------\n        params : float array\n            hi columns [log(HI_MW), log(HI_gal)]\n\n        hi_velocities : float array\n            hi velocities in km/sec [vel_MW, vel_gal]\n\n        sed : dict\n            fluxes for each spectral piece\n\n        Returns\n        -------\n        hi absorbed sed : dict\n            SED with {'bands': band_sed, 'spec': spec_sed, ...}\n        \"\"\"\n        # wavelengths of HI lines\n        #     only use Ly-alpha right now - others useful later\n        h_lines = (\n            np.array(\n                [\n                    1215.0,\n                    1025.0,\n                    972.0,\n                    949.0,\n                    937.0,\n                    930.0,\n                    926.0,\n                    923.0,\n                    920,\n                    919.0,\n                    918.0,\n                ]\n            )\n            * u.angstrom\n        )\n        # width overwhich to compute the HI abs\n        h_width = 100.0 * u.angstrom\n\n        hi_sed = {}\n        for cspec in self.fluxes.keys():\n            hi_sed[cspec] = np.copy(sed[cspec])\n            indxs, = np.where(np.absolute((self.waves[cspec] - h_lines[0]) <= h_width))\n            if len(indxs) > 0:\n                for i, cvel in enumerate(hi_velocities):\n                    # compute the Ly-alpha abs: from Bohlin et al. (197?)\n                    abs_wave = (1.0 + (cvel / 3e5)) * h_lines[0].to(u.micron).value\n                    phi = 4.26e-20 / (\n                        (1e4 * (self.waves[cspec][indxs].to(u.micron).value - abs_wave))\n                        ** 2\n                        + 6.04e-10\n                    )\n\n                    nhi = 10 ** params[i]\n                    hi_sed[cspec][indxs] = hi_sed[cspec][indxs] * np.exp(\n                        -1.0 * nhi * phi\n                    )\n\n        return hi_sed\n\n    def SED_to_StarData(self, sed):\n        \"\"\"\n        Convert the model created SED into a StarData object.\n        Needed to plug into generating an ExtData object.\n\n        Parameters\n        ----------\n        sed : object\n            SED of each component\n        \"\"\"\n        sd = StarData(None)\n\n        for cspec in sed.keys():\n            if cspec == \"BAND\":\n                # populate the BAND info\n                sd.data[\"BAND\"] = BandData(\"BAND\")\n                for k, cband in enumerate(self.band_names):\n                    sd.data[\"BAND\"].band_fluxes[cband] = (sed[\"BAND\"][k], 0.0)\n                sd.data[\"BAND\"].get_band_mags_from_fluxes()\n            else:\n                # populate the spectral info\n                sd.data[cspec] = SpecData(cspec)\n                sd.data[cspec].waves = self.waves[cspec]\n                sd.data[cspec].n_waves = len(sd.data[cspec].waves)\n                sd.data[cspec].fluxes = sed[cspec] * (\n                    u.erg / ((u.cm ** 2) * u.s * u.angstrom)\n                )\n                sd.data[cspec].uncs = 0.0 * sd.data[cspec].fluxes\n                sd.data[cspec].npts = np.full((sd.data[cspec].n_waves), 1.0)\n                print(sd.data[cspec].fluxes)\n\n        return sd\n", "meta": {"hexsha": "9eacda5f7c72e313fd666c963af71c5333ccf38f", "size": 12611, "ext": "py", "lang": "Python", "max_stars_repo_path": "measure_extinction/modeldata.py", "max_stars_repo_name": "mdcleir/measure_extinction", "max_stars_repo_head_hexsha": "d13198cac9b870f07c8da36b095910f3cb2d23ab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-04T19:09:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-04T19:09:51.000Z", "max_issues_repo_path": "measure_extinction/modeldata.py", "max_issues_repo_name": "mdcleir/measure_extinction", "max_issues_repo_head_hexsha": "d13198cac9b870f07c8da36b095910f3cb2d23ab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 92, "max_issues_repo_issues_event_min_datetime": "2018-01-08T22:05:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T16:47:26.000Z", "max_forks_repo_path": "measure_extinction/modeldata.py", "max_forks_repo_name": "mdcleir/measure_extinction", "max_forks_repo_head_hexsha": "d13198cac9b870f07c8da36b095910f3cb2d23ab", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-02-28T11:05:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-15T20:47:02.000Z", "avg_line_length": 33.3624338624, "max_line_length": 88, "alphanum_fraction": 0.5211323448, "include": true, "reason": "import numpy,import astropy", "num_tokens": 3277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.18763822415345122}}
{"text": "#!/usr/bin/env python \n\nimport numpy as np\nimport copy\nimport os\nimport sys\nimport re\n\n'''VARIABLES-VARIABLES-VARIABLES-VARIABLES-VARIABLES-VARIABLES-VARIABLES-VARIABLES-VARIABLES-VARIABLES-VARIABLES-VARIABLES\nuseful Variables\n'''\t\n\n#Periodic table\nperiodic_table = [\"\",\"H\",\"He\",\"Li\",\"Be\",\"B\",\"C\",\"N\",\"O\",\"F\",\"Ne\",\"Na\",\"Mg\",\"Al\",\"Si\",\"P\",\"S\",\"Cl\",\"Ar\",\"K\",\"Ca\",\"Sc\",\"Ti\",\"V\",\"Cr\",\"Mn\",\"Fe\",\"Co\",\"Ni\",\"Cu\",\"Zn\",\"Ga\",\"Ge\",\"As\",\"Se\",\"Br\",\"Kr\",\"Rb\",\"Sr\",\"Y\",\"Zr\",\n    \"Nb\",\"Mo\",\"Tc\",\"Ru\",\"Rh\",\"Pd\",\"Ag\",\"Cd\",\"In\",\"Sn\",\"Sb\",\"Te\",\"I\",\"Xe\",\"Cs\",\"Ba\",\"La\",\"Ce\",\"Pr\",\"Nd\",\"Pm\",\"Sm\",\"Eu\",\"Gd\",\"Tb\",\"Dy\",\"Ho\",\"Er\",\"Tm\",\"Yb\",\"Lu\",\"Hf\",\"Ta\",\"W\",\"Re\",\"Os\",\"Ir\",\"Pt\",\"Au\",\"Hg\",\"Tl\",\n    \"Pb\",\"Bi\",\"Po\",\"At\",\"Rn\",\"Fr\",\"Ra\",\"Ac\",\"Th\",\"Pa\",\"U\",\"Np\",\"Pu\",\"Am\",\"Cm\",\"Bk\",\"Cf\",\"Es\",\"Fm\",\"Md\",\"No\",\"Lr\",\"Rf\",\"Db\",\"Sg\",\"Bh\",\"Hs\",\"Mt\",\"Ds\",\"Rg\",\"Uub\",\"Uut\",\"Uuq\",\"Uup\",\"Uuh\",\"Uus\",\"Uuo\"]\n\n'''USEFUL-USEFUL-USEFUL-USEFUL-USEFUL-USEFUL-USEFUL-USEFUL-USEFUL-USEFUL-USEFUL-USEFUL-USEFUL-USEFUL-USEFUL-USEFUL-USEFUL\nOther useful functions\n'''\t\t\n#checks if a string contains only an integer\ndef isInt(s):\n    try: \n        int(s)\n        return True\n    except ValueError:\n        return False\t\n\t\n'''PARSING-PARSING-PARSING-PARSING-PARSING-PARSING-PARSING-PARSING-PARSING-PARSING-PARSING-PARSING-PARSING-PARSING-PARSING\nFunctions for parsing comp chem input\n'''\t\n\n#gets xyz structures from xyz file and provides a list of numpy arrays with xyz data of each structure, number of atoms and an atom list \ndef xyz_from_xyz(file):\n\tn_atoms = 0\n\tatoms = []\n\tstructures = []\n\ttitle = []\n\tfile_object = open(file, 'r')\n\tinput = (line for line in file_object) #make generator\n\t#search for number of atoms\n\tfor line in input:\n\t\tif isInt(line.strip()):\n\t\t\tn_atoms=int(line)\n\t\t\tbreak\t\n\telse: #exits if no line with number of atoms was found\n\t\tsys.exit('Error: No xyz coordinates found in file: ' + file)\n\t\t\t\n\t#skip one line\n\ttitle.append(next(input).strip())\n\t\n\t# now there should be n_atoms lines of coordinates WHAT IF NOT???\n\tfor i in range(n_atoms):\n\t\tl=next(input).split()\n\t\t\n\t\tif l[0] in periodic_table:\n\t\t\tatoms.append(l[0]) #get atom symbol and append to atom list\n\t\telse:\n\t\t\tsys.exit('Error: something is wrong with the first structure in file: '+file)\n\t\tcoords=[float(x) for x in l[1:]] #convert line to list of floats\n\t\tcoords=np.array([coords]) #create array with coords\n\t\ttry: #try append, doesn't work if XYZ doesn't exist yet\n\t\t\tXYZ=np.concatenate((XYZ,coords), axis=0)\n\t\texcept NameError:\n\t\t\tXYZ=coords\n\t\t\t\t\n\tstructures.append(XYZ) #append first structure to structures list\n\tdel XYZ #get rid of that for the next structure\n\t\t\n\t#now search for more structures\n\t\n\tfor line in input:\n\t\t#start extracting if atom number line is found\n\t\ttry:\n\t\t\tif int(line.strip()) == n_atoms:\n\t\t\t\t#read one line to skip title\n\t\t\t\ttitle.append(next(input).strip())\n\t\t\t\t\n\t\t\t\t# now there should be n_atoms lines of coordinates WHAT IF NOT???\n\t\t\t\tfor i in range(n_atoms):\n\t\t\t\t\tl=next(input).split()\n\t\t\t\t\tcoords=[float(x) for x in l[1:]]\n\t\t\t\t\tcoords=np.array([coords])\n\t\t\t\t\ttry: #try append, doesn't work if XYZ doesn't exist yet\n\t\t\t\t\t\tXYZ=np.concatenate((XYZ,coords), axis=0)\n\t\t\t\t\texcept NameError:\n\t\t\t\t\t\tXYZ=coords\n\t\t\t\tstructures.append(XYZ)\n\t\t\t\tdel XYZ\n\t\texcept ValueError:\n\t\t\tpass\n\t\t\t\t\n\treturn structures, n_atoms, atoms, title\n\n\n'''OUTPUT-OUTPUT-OUTPUT-OUTPUT-OUTPUT-OUTPUT-OUTPUT-OUTPUT-OUTPUT-OUTPUT-OUTPUT-OUTPUT-OUTPUT-OUTPUT-OUTPUT-OUTPUT-OUTPUT-OUTPUT\nFunctions for output\n'''\t\t\n#appends xyz structure to file, takes numpy array for A, atoms list, opened file and title for structure\ndef print_xyz(A, atoms, file, title):\n\t\n\tfile.write(str(len(atoms))+ \"\\n\"+ title + \"\\n\")\n\tfor i in range(len(A)):\n\t\tfile.write(\"{0:2s} {1:15.12f} {2:15.12f} {3:15.12f}\\n\".format(atoms[i], A[i, 0], A[i, 1], A[i, 2]))\n\treturn", "meta": {"hexsha": "27294250b3dc80d26538299ac7d0de4643d7f230", "size": 3768, "ext": "py", "lang": "Python", "max_stars_repo_path": "DIA_collection.py", "max_stars_repo_name": "dsvatunek/sort_xyz", "max_stars_repo_head_hexsha": "24b108eb7d0e3f9a79250077dd9b99245f0300b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-24T14:58:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T14:58:56.000Z", "max_issues_repo_path": "DIA_collection.py", "max_issues_repo_name": "dsvatunek/sort_xyz", "max_issues_repo_head_hexsha": "24b108eb7d0e3f9a79250077dd9b99245f0300b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DIA_collection.py", "max_forks_repo_name": "dsvatunek/sort_xyz", "max_forks_repo_head_hexsha": "24b108eb7d0e3f9a79250077dd9b99245f0300b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8857142857, "max_line_length": 210, "alphanum_fraction": 0.6541932059, "include": true, "reason": "import numpy", "num_tokens": 1187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.18760599244282505}}
{"text": "\"\"\"\nColorimetry Plotting\n====================\n\nDefines the colorimetry plotting objects:\n\n-   :func:`colour.plotting.plot_single_sd`\n-   :func:`colour.plotting.plot_multi_sds`\n-   :func:`colour.plotting.plot_single_cmfs`\n-   :func:`colour.plotting.plot_multi_cmfs`\n-   :func:`colour.plotting.plot_single_illuminant_sd`\n-   :func:`colour.plotting.plot_multi_illuminant_sds`\n-   :func:`colour.plotting.plot_visible_spectrum`\n-   :func:`colour.plotting.plot_single_lightness_function`\n-   :func:`colour.plotting.plot_multi_lightness_functions`\n-   :func:`colour.plotting.plot_single_luminance_function`\n-   :func:`colour.plotting.plot_multi_luminance_functions`\n-   :func:`colour.plotting.plot_blackbody_spectral_radiance`\n-   :func:`colour.plotting.plot_blackbody_colours`\n\nReferences\n----------\n-   :cite:`Spiker2015a` : Borer, T. (2017). Private Discussion with Mansencal,\n    T. and Shaw, N.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom functools import reduce\nfrom matplotlib.patches import Polygon\n\nfrom colour.algebra import (\n    LinearInterpolator,\n    normalise_maximum,\n    sdiv,\n    sdiv_mode,\n)\nfrom colour.colorimetry import (\n    CCS_ILLUMINANTS,\n    SDS_ILLUMINANTS,\n    LIGHTNESS_METHODS,\n    LUMINANCE_METHODS,\n    MultiSpectralDistributions,\n    SpectralDistribution,\n    SpectralShape,\n    sd_blackbody,\n    sd_ones,\n    sd_to_XYZ,\n    sds_and_msds_to_sds,\n    wavelength_to_XYZ,\n)\nfrom colour.hints import (\n    Any,\n    Boolean,\n    Callable,\n    Dict,\n    Floating,\n    List,\n    NDArray,\n    Optional,\n    Sequence,\n    Tuple,\n    Union,\n    cast,\n)\nfrom colour.plotting import (\n    CONSTANTS_COLOUR_STYLE,\n    XYZ_to_plotting_colourspace,\n    artist,\n    filter_passthrough,\n    filter_cmfs,\n    filter_illuminants,\n    override_style,\n    render,\n    plot_single_colour_swatch,\n    plot_multi_functions,\n    update_settings_collection,\n)\nfrom colour.utilities import (\n    as_float_array,\n    domain_range_scale,\n    first_item,\n    ones,\n    tstack,\n)\n\n__author__ = \"Colour Developers\"\n__copyright__ = \"Copyright 2013 Colour Developers\"\n__license__ = \"New BSD License - https://opensource.org/licenses/BSD-3-Clause\"\n__maintainer__ = \"Colour Developers\"\n__email__ = \"colour-developers@colour-science.org\"\n__status__ = \"Production\"\n\n__all__ = [\n    \"plot_single_sd\",\n    \"plot_multi_sds\",\n    \"plot_single_cmfs\",\n    \"plot_multi_cmfs\",\n    \"plot_single_illuminant_sd\",\n    \"plot_multi_illuminant_sds\",\n    \"plot_visible_spectrum\",\n    \"plot_single_lightness_function\",\n    \"plot_multi_lightness_functions\",\n    \"plot_single_luminance_function\",\n    \"plot_multi_luminance_functions\",\n    \"plot_blackbody_spectral_radiance\",\n    \"plot_blackbody_colours\",\n]\n\n\n@override_style()\ndef plot_single_sd(\n    sd: SpectralDistribution,\n    cmfs: Union[\n        MultiSpectralDistributions,\n        str,\n        Sequence[Union[MultiSpectralDistributions, str]],\n    ] = \"CIE 1931 2 Degree Standard Observer\",\n    out_of_gamut_clipping: Boolean = True,\n    modulate_colours_with_sd_amplitude: Boolean = False,\n    equalize_sd_amplitude: Boolean = False,\n    **kwargs: Any,\n) -> Tuple[plt.Figure, plt.Axes]:\n    \"\"\"\n    Plot given spectral distribution.\n\n    Parameters\n    ----------\n    sd\n        Spectral distribution to plot.\n    cmfs\n        Standard observer colour matching functions used for computing the\n        spectrum domain and colours. ``cmfs`` can be of any type or form\n        supported by the :func:`colour.plotting.filter_cmfs` definition.\n    out_of_gamut_clipping\n        Whether to clip out of gamut colours otherwise, the colours will be\n        offset by the absolute minimal colour leading to a rendering on\n        gray background, less saturated and smoother.\n    modulate_colours_with_sd_amplitude\n        Whether to modulate the colours with the spectral distribution\n        amplitude.\n    equalize_sd_amplitude\n        Whether to equalize the spectral distribution amplitude.\n        Equalization occurs after the colours modulation thus setting both\n        arguments to *True* will generate a spectrum strip where each\n        wavelength colour is modulated by the spectral distribution amplitude.\n        The usual 5% margin above the spectral distribution is also omitted.\n\n    Other Parameters\n    ----------------\n    kwargs\n        {:func:`colour.plotting.artist`, :func:`colour.plotting.render`},\n        See the documentation of the previously listed definitions.\n\n    Returns\n    -------\n    :class:`tuple`\n        Current figure and axes.\n\n    References\n    ----------\n    :cite:`Spiker2015a`\n\n    Examples\n    --------\n    >>> from colour import SpectralDistribution\n    >>> data = {\n    ...     500: 0.0651,\n    ...     520: 0.0705,\n    ...     540: 0.0772,\n    ...     560: 0.0870,\n    ...     580: 0.1128,\n    ...     600: 0.1360\n    ... }\n    >>> sd = SpectralDistribution(data, name='Custom')\n    >>> plot_single_sd(sd)  # doctest: +ELLIPSIS\n    (<Figure size ... with 1 Axes>, <...AxesSubplot...>)\n\n    .. image:: ../_static/Plotting_Plot_Single_SD.png\n        :align: center\n        :alt: plot_single_sd\n    \"\"\"\n\n    _figure, axes = artist(**kwargs)\n\n    cmfs = cast(\n        MultiSpectralDistributions, first_item(filter_cmfs(cmfs).values())\n    )\n\n    sd = cast(SpectralDistribution, sd.copy())\n    sd.interpolator = LinearInterpolator\n    wavelengths = cmfs.wavelengths[\n        np.logical_and(\n            cmfs.wavelengths\n            >= max(min(cmfs.wavelengths), min(sd.wavelengths)),\n            cmfs.wavelengths\n            <= min(max(cmfs.wavelengths), max(sd.wavelengths)),\n        )\n    ]\n    values = as_float_array(sd[wavelengths])\n\n    RGB = XYZ_to_plotting_colourspace(\n        wavelength_to_XYZ(wavelengths, cmfs),\n        CCS_ILLUMINANTS[\"CIE 1931 2 Degree Standard Observer\"][\"E\"],\n        apply_cctf_encoding=False,\n    )\n\n    if not out_of_gamut_clipping:\n        RGB += np.abs(np.min(RGB))\n\n    RGB = normalise_maximum(RGB)\n\n    if modulate_colours_with_sd_amplitude:\n        with sdiv_mode():\n            RGB *= cast(NDArray, sdiv(values, np.max(values)))[..., np.newaxis]\n\n    RGB = CONSTANTS_COLOUR_STYLE.colour.colourspace.cctf_encoding(RGB)\n\n    if equalize_sd_amplitude:\n        values = ones(values.shape)\n\n    margin = 0 if equalize_sd_amplitude else 0.05\n\n    x_min, x_max = min(wavelengths), max(wavelengths)\n    y_min, y_max = 0, max(values) + max(values) * margin\n\n    polygon = Polygon(\n        np.vstack(\n            [\n                (x_min, 0),\n                tstack([wavelengths, values]),\n                (x_max, 0),\n            ]\n        ),\n        facecolor=\"none\",\n        edgecolor=\"none\",\n        zorder=CONSTANTS_COLOUR_STYLE.zorder.background_polygon,\n    )\n    axes.add_patch(polygon)\n\n    padding = 0.1\n    axes.bar(\n        x=wavelengths - padding,\n        height=max(values),\n        width=1 + padding,\n        color=RGB,\n        align=\"edge\",\n        clip_path=polygon,\n        zorder=CONSTANTS_COLOUR_STYLE.zorder.background_polygon,\n    )\n\n    axes.plot(\n        wavelengths,\n        values,\n        color=CONSTANTS_COLOUR_STYLE.colour.dark,\n        zorder=CONSTANTS_COLOUR_STYLE.zorder.midground_line,\n    )\n\n    settings: Dict[str, Any] = {\n        \"axes\": axes,\n        \"bounding_box\": (x_min, x_max, y_min, y_max),\n        \"title\": f\"{sd.strict_name} - {cmfs.strict_name}\",\n        \"x_label\": \"Wavelength $\\\\lambda$ (nm)\",\n        \"y_label\": \"Spectral Distribution\",\n    }\n    settings.update(kwargs)\n\n    return render(**settings)\n\n\n@override_style()\ndef plot_multi_sds(\n    sds: Union[\n        Sequence[Union[SpectralDistribution, MultiSpectralDistributions]],\n        MultiSpectralDistributions,\n    ],\n    plot_kwargs: Optional[Union[Dict, List[Dict]]] = None,\n    **kwargs: Any,\n) -> Tuple[plt.Figure, plt.Axes]:\n    \"\"\"\n    Plot given spectral distributions.\n\n    Parameters\n    ----------\n    sds\n        Spectral distributions or multi-spectral distributions to\n        plot. `sds` can be a single\n        :class:`colour.MultiSpectralDistributions` class instance, a list\n        of :class:`colour.MultiSpectralDistributions` class instances or a\n        list of :class:`colour.SpectralDistribution` class instances.\n    plot_kwargs\n        Keyword arguments for the :func:`matplotlib.pyplot.plot` definition,\n        used to control the style of the plotted spectral distributions.\n        `plot_kwargs`` can be either a single dictionary applied to all the\n        plotted spectral distributions with the same settings or a sequence of\n        dictionaries with different settings for each plotted spectral\n        distributions. The following special keyword arguments can also be\n        used:\n\n        -   ``illuminant`` : The illuminant used to compute the spectral\n            distributions colours. The default is the illuminant associated\n            with the whitepoint of the default plotting colourspace.\n            ``illuminant`` can be of any type or form supported by the\n            :func:`colour.plotting.filter_cmfs` definition.\n        -   ``cmfs`` : The standard observer colour matching functions used for\n            computing the spectral distributions colours. ``cmfs`` can be of\n            any type or form supported by the\n            :func:`colour.plotting.filter_cmfs` definition.\n        -   ``normalise_sd_colours`` : Whether to normalise the computed\n            spectral distributions colours. The default is *True*.\n        -   ``use_sd_colours`` : Whether to use the computed spectral\n            distributions colours under the plotting colourspace illuminant.\n            Alternatively, it is possible to use the\n            :func:`matplotlib.pyplot.plot` definition ``color`` argument with\n            pre-computed values. The default is *True*.\n\n    Other Parameters\n    ----------------\n    kwargs\n        {:func:`colour.plotting.artist`, :func:`colour.plotting.render`},\n        See the documentation of the previously listed definitions.\n\n    Returns\n    -------\n    :class:`tuple`\n        Current figure and axes.\n\n    Examples\n    --------\n    >>> from colour import SpectralDistribution\n    >>> data_1 = {\n    ...     500: 0.004900,\n    ...     510: 0.009300,\n    ...     520: 0.063270,\n    ...     530: 0.165500,\n    ...     540: 0.290400,\n    ...     550: 0.433450,\n    ...     560: 0.594500\n    ... }\n    >>> data_2 = {\n    ...     500: 0.323000,\n    ...     510: 0.503000,\n    ...     520: 0.710000,\n    ...     530: 0.862000,\n    ...     540: 0.954000,\n    ...     550: 0.994950,\n    ...     560: 0.995000\n    ... }\n    >>> sd_1 = SpectralDistribution(data_1, name='Custom 1')\n    >>> sd_2 = SpectralDistribution(data_2, name='Custom 2')\n    >>> plot_kwargs = [\n    ...     {'use_sd_colours': True},\n    ...     {'use_sd_colours': True, 'linestyle': 'dashed'},\n    ... ]\n    >>> plot_multi_sds([sd_1, sd_2], plot_kwargs=plot_kwargs)\n    ... # doctest: +ELLIPSIS\n    (<Figure size ... with 1 Axes>, <...AxesSubplot...>)\n\n    .. image:: ../_static/Plotting_Plot_Multi_SDS.png\n        :align: center\n        :alt: plot_multi_sds\n    \"\"\"\n\n    _figure, axes = artist(**kwargs)\n\n    sds_converted = sds_and_msds_to_sds(sds)\n\n    plot_settings_collection = [\n        {\n            \"label\": f\"{sd.strict_name}\",\n            \"zorder\": CONSTANTS_COLOUR_STYLE.zorder.midground_line,\n            \"cmfs\": \"CIE 1931 2 Degree Standard Observer\",\n            \"illuminant\": SDS_ILLUMINANTS[\n                CONSTANTS_COLOUR_STYLE.colour.colourspace.whitepoint_name\n            ],\n            \"use_sd_colours\": False,\n            \"normalise_sd_colours\": False,\n        }\n        for sd in sds_converted\n    ]\n\n    if plot_kwargs is not None:\n        update_settings_collection(\n            plot_settings_collection, plot_kwargs, len(sds_converted)\n        )\n\n    x_limit_min, x_limit_max, y_limit_min, y_limit_max = [], [], [], []\n    for i, sd in enumerate(sds_converted):\n        plot_settings = plot_settings_collection[i]\n\n        cmfs = cast(\n            MultiSpectralDistributions,\n            first_item(filter_cmfs(plot_settings.pop(\"cmfs\")).values()),\n        )\n        illuminant = cast(\n            SpectralDistribution,\n            first_item(\n                filter_illuminants(plot_settings.pop(\"illuminant\")).values()\n            ),\n        )\n        normalise_sd_colours = plot_settings.pop(\"normalise_sd_colours\")\n        use_sd_colours = plot_settings.pop(\"use_sd_colours\")\n\n        wavelengths, values = sd.wavelengths, sd.values\n\n        shape = sd.shape\n        x_limit_min.append(shape.start)\n        x_limit_max.append(shape.end)\n        y_limit_min.append(min(values))\n        y_limit_max.append(max(values))\n\n        if use_sd_colours:\n            with domain_range_scale(\"1\"):\n                XYZ = sd_to_XYZ(sd, cmfs, illuminant)\n\n            if normalise_sd_colours:\n                XYZ /= XYZ[..., 1]\n\n            plot_settings[\"color\"] = np.clip(\n                XYZ_to_plotting_colourspace(XYZ), 0, 1\n            )\n\n        axes.plot(wavelengths, values, **plot_settings)\n\n    bounding_box = (\n        min(x_limit_min),\n        max(x_limit_max),\n        min(y_limit_min),\n        max(y_limit_max) + np.max(y_limit_max) * 0.05,\n    )\n    settings: Dict[str, Any] = {\n        \"axes\": axes,\n        \"bounding_box\": bounding_box,\n        \"legend\": True,\n        \"x_label\": \"Wavelength $\\\\lambda$ (nm)\",\n        \"y_label\": \"Spectral Distribution\",\n    }\n    settings.update(kwargs)\n\n    return render(**settings)\n\n\n@override_style()\ndef plot_single_cmfs(\n    cmfs: Union[\n        MultiSpectralDistributions,\n        str,\n        Sequence[Union[MultiSpectralDistributions, str]],\n    ] = \"CIE 1931 2 Degree Standard Observer\",\n    **kwargs: Any,\n) -> Tuple[plt.Figure, plt.Axes]:\n    \"\"\"\n    Plot given colour matching functions.\n\n    Parameters\n    ----------\n    cmfs\n        Colour matching functions to plot. ``cmfs`` can be of any type or form\n        supported by the :func:`colour.plotting.filter_cmfs` definition.\n\n    Other Parameters\n    ----------------\n    kwargs\n        {:func:`colour.plotting.artist`,\n        :func:`colour.plotting.plot_multi_cmfs`,\n        :func:`colour.plotting.render`},\n        See the documentation of the previously listed definitions.\n\n    Returns\n    -------\n    :class:`tuple`\n        Current figure and axes.\n\n    Examples\n    --------\n    >>> plot_single_cmfs('CIE 1931 2 Degree Standard Observer')\n    ... # doctest: +ELLIPSIS\n    (<Figure size ... with 1 Axes>, <...AxesSubplot...>)\n\n    .. image:: ../_static/Plotting_Plot_Single_CMFS.png\n        :align: center\n        :alt: plot_single_cmfs\n    \"\"\"\n\n    cmfs = cast(\n        MultiSpectralDistributions, first_item(filter_cmfs(cmfs).values())\n    )\n\n    settings: Dict[str, Any] = {\n        \"title\": f\"{cmfs.strict_name} - Colour Matching Functions\"\n    }\n    settings.update(kwargs)\n\n    return plot_multi_cmfs((cmfs,), **settings)\n\n\n@override_style()\ndef plot_multi_cmfs(\n    cmfs: Union[\n        MultiSpectralDistributions,\n        str,\n        Sequence[Union[MultiSpectralDistributions, str]],\n    ],\n    **kwargs: Any,\n) -> Tuple[plt.Figure, plt.Axes]:\n    \"\"\"\n    Plot given colour matching functions.\n\n    Parameters\n    ----------\n    cmfs\n        Colour matching functions to plot. ``cmfs`` elements can be of any\n        type or form supported by the :func:`colour.plotting.filter_cmfs`\n        definition.\n\n    Other Parameters\n    ----------------\n    kwargs\n        {:func:`colour.plotting.artist`, :func:`colour.plotting.render`},\n        See the documentation of the previously listed definitions.\n\n    Returns\n    -------\n    :class:`tuple`\n        Current figure and axes.\n\n    Examples\n    --------\n    >>> cmfs = [\n    ...     'CIE 1931 2 Degree Standard Observer',\n    ...     'CIE 1964 10 Degree Standard Observer',\n    ... ]\n    >>> plot_multi_cmfs(cmfs)  # doctest: +ELLIPSIS\n    (<Figure size ... with 1 Axes>, <...AxesSubplot...>)\n\n    .. image:: ../_static/Plotting_Plot_Multi_CMFS.png\n        :align: center\n        :alt: plot_multi_cmfs\n    \"\"\"\n\n    cmfs = cast(\n        List[MultiSpectralDistributions], list(filter_cmfs(cmfs).values())\n    )\n\n    _figure, axes = artist(**kwargs)\n\n    axes.axhline(\n        color=CONSTANTS_COLOUR_STYLE.colour.dark,\n        linestyle=\"--\",\n        zorder=CONSTANTS_COLOUR_STYLE.zorder.foreground_line,\n    )\n\n    x_limit_min, x_limit_max, y_limit_min, y_limit_max = [], [], [], []\n    for i, cmfs_i in enumerate(cmfs):\n        for j, RGB in enumerate(\n            as_float_array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n        ):\n            RGB = [reduce(lambda y, _: y * 0.5, range(i), x) for x in RGB]\n            values = cmfs_i.values[:, j]\n\n            shape = cmfs_i.shape\n            x_limit_min.append(shape.start)\n            x_limit_max.append(shape.end)\n            y_limit_min.append(np.min(values))\n            y_limit_max.append(np.max(values))\n\n            axes.plot(\n                cmfs_i.wavelengths,\n                values,\n                color=RGB,\n                label=f\"{cmfs_i.strict_labels[j]} - {cmfs_i.strict_name}\",\n                zorder=CONSTANTS_COLOUR_STYLE.zorder.midground_line,\n            )\n\n    bounding_box = (\n        min(x_limit_min),\n        max(x_limit_max),\n        min(y_limit_min) - np.abs(np.min(y_limit_min)) * 0.05,\n        max(y_limit_max) + np.abs(np.max(y_limit_max)) * 0.05,\n    )\n    cmfs_strict_names = \", \".join([cmfs_i.strict_name for cmfs_i in cmfs])\n    title = f\"{cmfs_strict_names} - Colour Matching Functions\"\n\n    settings: Dict[str, Any] = {\n        \"axes\": axes,\n        \"bounding_box\": bounding_box,\n        \"legend\": True,\n        \"title\": title,\n        \"x_label\": \"Wavelength $\\\\lambda$ (nm)\",\n        \"y_label\": \"Tristimulus Values\",\n    }\n    settings.update(kwargs)\n\n    return render(**settings)\n\n\n@override_style()\ndef plot_single_illuminant_sd(\n    illuminant: Union[SpectralDistribution, str],\n    cmfs: Union[\n        MultiSpectralDistributions,\n        str,\n        Sequence[Union[MultiSpectralDistributions, str]],\n    ] = \"CIE 1931 2 Degree Standard Observer\",\n    **kwargs: Any,\n) -> Tuple[plt.Figure, plt.Axes]:\n    \"\"\"\n    Plot given single illuminant spectral distribution.\n\n    Parameters\n    ----------\n    illuminant\n        Illuminant to plot. ``illuminant`` can be of any type or form supported\n        by the :func:`colour.plotting.filter_illuminants` definition.\n    cmfs\n        Standard observer colour matching functions used for computing the\n        spectrum domain and colours. ``cmfs`` can be of any type or form\n        supported by the :func:`colour.plotting.filter_cmfs` definition.\n\n    Other Parameters\n    ----------------\n    kwargs\n        {:func:`colour.plotting.artist`,\n        :func:`colour.plotting.plot_single_sd`,\n        :func:`colour.plotting.render`},\n        See the documentation of the previously listed definitions.\n\n    Returns\n    -------\n    :class:`tuple`\n        Current figure and axes.\n\n    References\n    ----------\n    :cite:`Spiker2015a`\n\n    Examples\n    --------\n    >>> plot_single_illuminant_sd('A')  # doctest: +ELLIPSIS\n    (<Figure size ... with 1 Axes>, <...AxesSubplot...>)\n\n    .. image:: ../_static/Plotting_Plot_Single_Illuminant_SD.png\n        :align: center\n        :alt: plot_single_illuminant_sd\n    \"\"\"\n\n    cmfs = cast(\n        MultiSpectralDistributions, first_item(filter_cmfs(cmfs).values())\n    )\n\n    title = f\"Illuminant {illuminant} - {cmfs.strict_name}\"\n\n    illuminant = first_item(filter_illuminants(illuminant).values())\n\n    settings: Dict[str, Any] = {\"title\": title, \"y_label\": \"Relative Power\"}\n    settings.update(kwargs)\n\n    return plot_single_sd(illuminant, **settings)\n\n\n@override_style()\ndef plot_multi_illuminant_sds(\n    illuminants: Union[\n        SpectralDistribution, str, Sequence[Union[SpectralDistribution, str]]\n    ],\n    **kwargs: Any,\n) -> Tuple[plt.Figure, plt.Axes]:\n    \"\"\"\n    Plot given illuminants spectral distributions.\n\n    Parameters\n    ----------\n    illuminants\n        Illuminants to plot. ``illuminants`` elements can be of any type or\n        form supported by the :func:`colour.plotting.filter_illuminants`\n        definition.\n\n    Other Parameters\n    ----------------\n    kwargs\n        {:func:`colour.plotting.artist`,\n        :func:`colour.plotting.plot_multi_sds`,\n        :func:`colour.plotting.render`},\n        See the documentation of the previously listed definitions.\n\n    Returns\n    -------\n    :class:`tuple`\n        Current figure and axes.\n\n    Examples\n    --------\n    >>> plot_multi_illuminant_sds(['A', 'B', 'C'])  # doctest: +ELLIPSIS\n    (<Figure size ... with 1 Axes>, <...AxesSubplot...>)\n\n    .. image:: ../_static/Plotting_Plot_Multi_Illuminant_SDS.png\n        :align: center\n        :alt: plot_multi_illuminant_sds\n    \"\"\"\n\n    if \"plot_kwargs\" not in kwargs:\n        kwargs[\"plot_kwargs\"] = {}\n\n    SD_E = SDS_ILLUMINANTS[\"E\"]\n    if isinstance(kwargs[\"plot_kwargs\"], dict):\n        kwargs[\"plot_kwargs\"][\"illuminant\"] = SD_E\n    else:\n        for i in range(len(kwargs[\"plot_kwargs\"])):\n            kwargs[\"plot_kwargs\"][i][\"illuminant\"] = SD_E\n\n    illuminants = cast(\n        List[SpectralDistribution],\n        list(filter_illuminants(illuminants).values()),\n    )\n\n    illuminant_strict_names = \", \".join(\n        [illuminant.strict_name for illuminant in illuminants]\n    )\n    title = f\"{illuminant_strict_names} - Illuminants Spectral Distributions\"\n\n    settings: Dict[str, Any] = {\"title\": title, \"y_label\": \"Relative Power\"}\n    settings.update(kwargs)\n\n    return plot_multi_sds(illuminants, **settings)\n\n\n@override_style(\n    **{\n        \"ytick.left\": False,\n        \"ytick.labelleft\": False,\n    }\n)\ndef plot_visible_spectrum(\n    cmfs: Union[\n        MultiSpectralDistributions,\n        str,\n        Sequence[Union[MultiSpectralDistributions, str]],\n    ] = \"CIE 1931 2 Degree Standard Observer\",\n    out_of_gamut_clipping: Boolean = True,\n    **kwargs: Any,\n) -> Tuple[plt.Figure, plt.Axes]:\n    \"\"\"\n    Plot the visible colours spectrum using given standard observer *CIE XYZ*\n    colour matching functions.\n\n    Parameters\n    ----------\n    cmfs\n        Standard observer colour matching functions used for computing the\n        spectrum domain and colours. ``cmfs`` can be of any type or form\n        supported by the :func:`colour.plotting.filter_cmfs` definition.\n    out_of_gamut_clipping\n        Whether to clip out of gamut colours otherwise, the colours will be\n        offset by the absolute minimal colour leading to a rendering on\n        gray background, less saturated and smoother.\n\n    Other Parameters\n    ----------------\n    kwargs\n        {:func:`colour.plotting.artist`,\n        :func:`colour.plotting.plot_single_sd`,\n        :func:`colour.plotting.render`},\n        See the documentation of the previously listed definitions.\n\n    Returns\n    -------\n    :class:`tuple`\n        Current figure and axes.\n\n    References\n    ----------\n    :cite:`Spiker2015a`\n\n    Examples\n    --------\n    >>> plot_visible_spectrum()  # doctest: +ELLIPSIS\n    (<Figure size ... with 1 Axes>, <...AxesSubplot...>)\n\n    .. image:: ../_static/Plotting_Plot_Visible_Spectrum.png\n        :align: center\n        :alt: plot_visible_spectrum\n    \"\"\"\n\n    cmfs = cast(\n        MultiSpectralDistributions, first_item(filter_cmfs(cmfs).values())\n    )\n\n    bounding_box = (min(cmfs.wavelengths), max(cmfs.wavelengths), 0, 1)\n\n    settings: Dict[str, Any] = {\"bounding_box\": bounding_box, \"y_label\": None}\n    settings.update(kwargs)\n    settings[\"standalone\"] = False\n\n    _figure, axes = plot_single_sd(\n        sd_ones(cmfs.shape),\n        cmfs=cmfs,\n        out_of_gamut_clipping=out_of_gamut_clipping,\n        **settings,\n    )\n\n    # Removing wavelength line as it doubles with the axes spine.\n    axes.lines.pop(0)\n\n    settings = {\n        \"axes\": axes,\n        \"standalone\": True,\n        \"title\": f\"The Visible Spectrum - {cmfs.strict_name}\",\n        \"x_label\": \"Wavelength $\\\\lambda$ (nm)\",\n    }\n    settings.update(kwargs)\n\n    return render(**settings)\n\n\n@override_style()\ndef plot_single_lightness_function(\n    function: Union[Callable, str], **kwargs: Any\n) -> Tuple[plt.Figure, plt.Axes]:\n    \"\"\"\n    Plot given *Lightness* function.\n\n    Parameters\n    ----------\n    function\n        *Lightness* function to plot. ``function`` can be of any type or form\n        supported by the :func:`colour.plotting.filter_passthrough` definition.\n\n    Other Parameters\n    ----------------\n    kwargs\n        {:func:`colour.plotting.artist`,\n        :func:`colour.plotting.plot_multi_functions`,\n        :func:`colour.plotting.render`},\n        See the documentation of the previously listed definitions.\n\n    Returns\n    -------\n    :class:`tuple`\n        Current figure and axes.\n\n    Examples\n    --------\n    >>> plot_single_lightness_function('CIE 1976')  # doctest: +ELLIPSIS\n    (<Figure size ... with 1 Axes>, <...AxesSubplot...>)\n\n    .. image:: ../_static/Plotting_Plot_Single_Lightness_Function.png\n        :align: center\n        :alt: plot_single_lightness_function\n    \"\"\"\n\n    settings: Dict[str, Any] = {\"title\": f\"{function} - Lightness Function\"}\n    settings.update(kwargs)\n\n    return plot_multi_lightness_functions((function,), **settings)\n\n\n@override_style()\ndef plot_multi_lightness_functions(\n    functions: Union[Callable, str, Sequence[Union[Callable, str]]],\n    **kwargs: Any,\n) -> Tuple[plt.Figure, plt.Axes]:\n    \"\"\"\n    Plot given *Lightness* functions.\n\n    Parameters\n    ----------\n    functions\n        *Lightness* functions to plot. ``functions`` elements can be of any\n        type or form supported by the\n        :func:`colour.plotting.filter_passthrough` definition.\n\n    Other Parameters\n    ----------------\n    kwargs\n        {:func:`colour.plotting.artist`,\n        :func:`colour.plotting.plot_multi_functions`,\n        :func:`colour.plotting.render`},\n        See the documentation of the previously listed definitions.\n\n    Returns\n    -------\n    :class:`tuple`\n        Current figure and axes.\n\n    Examples\n    --------\n    >>> plot_multi_lightness_functions(['CIE 1976', 'Wyszecki 1963'])\n    ... # doctest: +ELLIPSIS\n    (<Figure size ... with 1 Axes>, <...AxesSubplot...>)\n\n    .. image:: ../_static/Plotting_Plot_Multi_Lightness_Functions.png\n        :align: center\n        :alt: plot_multi_lightness_functions\n    \"\"\"\n\n    functions_filtered = filter_passthrough(LIGHTNESS_METHODS, functions)\n\n    settings: Dict[str, Any] = {\n        \"bounding_box\": (0, 1, 0, 1),\n        \"legend\": True,\n        \"title\": f\"{', '.join(functions_filtered)} - Lightness Functions\",\n        \"x_label\": \"Normalised Relative Luminance Y\",\n        \"y_label\": \"Normalised Lightness\",\n    }\n    settings.update(kwargs)\n\n    with domain_range_scale(\"1\"):\n        return plot_multi_functions(functions_filtered, **settings)\n\n\n@override_style()\ndef plot_single_luminance_function(\n    function: Union[Callable, str], **kwargs: Any\n) -> Tuple[plt.Figure, plt.Axes]:\n    \"\"\"\n    Plot given *Luminance* function.\n\n    Parameters\n    ----------\n    function\n        *Luminance* function to plot.\n\n    Other Parameters\n    ----------------\n    kwargs\n        {:func:`colour.plotting.artist`,\n        :func:`colour.plotting.plot_multi_functions`,\n        :func:`colour.plotting.render`},\n        See the documentation of the previously listed definitions.\n\n    Returns\n    -------\n    :class:`tuple`\n        Current figure and axes.\n\n    Examples\n    --------\n    >>> plot_single_luminance_function('CIE 1976')  # doctest: +ELLIPSIS\n    (<Figure size ... with 1 Axes>, <...AxesSubplot...>)\n\n    .. image:: ../_static/Plotting_Plot_Single_Luminance_Function.png\n        :align: center\n        :alt: plot_single_luminance_function\n    \"\"\"\n\n    settings: Dict[str, Any] = {\"title\": f\"{function} - Luminance Function\"}\n    settings.update(kwargs)\n\n    return plot_multi_luminance_functions((function,), **settings)\n\n\n@override_style()\ndef plot_multi_luminance_functions(\n    functions: Union[Callable, str, Sequence[Union[Callable, str]]],\n    **kwargs: Any,\n) -> Tuple[plt.Figure, plt.Axes]:\n    \"\"\"\n    Plot given *Luminance* functions.\n\n    Parameters\n    ----------\n    functions\n        *Luminance* functions to plot. ``functions`` elements can be of any\n        type or form supported by the\n        :func:`colour.plotting.filter_passthrough` definition.\n\n    Other Parameters\n    ----------------\n    kwargs\n        {:func:`colour.plotting.artist`,\n        :func:`colour.plotting.plot_multi_functions`,\n        :func:`colour.plotting.render`},\n        See the documentation of the previously listed definitions.\n\n    Returns\n    -------\n    :class:`tuple`\n        Current figure and axes.\n\n    Examples\n    --------\n    >>> plot_multi_luminance_functions(['CIE 1976', 'Newhall 1943'])\n    ... # doctest: +ELLIPSIS\n    (<Figure size ... with 1 Axes>, <...AxesSubplot...>)\n\n    .. image:: ../_static/Plotting_Plot_Multi_Luminance_Functions.png\n        :align: center\n        :alt: plot_multi_luminance_functions\n    \"\"\"\n\n    functions_filtered = filter_passthrough(LUMINANCE_METHODS, functions)\n\n    settings: Dict[str, Any] = {\n        \"bounding_box\": (0, 1, 0, 1),\n        \"legend\": True,\n        \"title\": f\"{', '.join(functions_filtered)} - Luminance Functions\",\n        \"x_label\": \"Normalised Munsell Value / Lightness\",\n        \"y_label\": \"Normalised Relative Luminance Y\",\n    }\n    settings.update(kwargs)\n\n    with domain_range_scale(\"1\"):\n        return plot_multi_functions(functions_filtered, **settings)\n\n\n@override_style()\ndef plot_blackbody_spectral_radiance(\n    temperature: Floating = 3500,\n    cmfs: Union[\n        MultiSpectralDistributions,\n        str,\n        Sequence[Union[MultiSpectralDistributions, str]],\n    ] = \"CIE 1931 2 Degree Standard Observer\",\n    blackbody: str = \"VY Canis Major\",\n    **kwargs: Any,\n) -> Tuple[plt.Figure, plt.Axes]:\n    \"\"\"\n    Plot given blackbody spectral radiance.\n\n    Parameters\n    ----------\n    temperature\n        Blackbody temperature.\n    cmfs\n        Standard observer colour matching functions used for computing the\n        spectrum domain and colours. ``cmfs`` can be of any type or form\n        supported by the :func:`colour.plotting.filter_cmfs` definition.\n    blackbody\n        Blackbody name.\n\n    Other Parameters\n    ----------------\n    kwargs\n        {:func:`colour.plotting.artist`,\n        :func:`colour.plotting.plot_single_sd`,\n        :func:`colour.plotting.render`},\n        See the documentation of the previously listed definitions.\n\n    Returns\n    -------\n    :class:`tuple`\n        Current figure and axes.\n\n    Examples\n    --------\n    >>> plot_blackbody_spectral_radiance(3500, blackbody='VY Canis Major')\n    ... # doctest: +ELLIPSIS\n    (<Figure size ... with 2 Axes>, <...AxesSubplot...>)\n\n    .. image:: ../_static/Plotting_Plot_Blackbody_Spectral_Radiance.png\n        :align: center\n        :alt: plot_blackbody_spectral_radiance\n    \"\"\"\n\n    figure = plt.figure()\n\n    figure.subplots_adjust(hspace=CONSTANTS_COLOUR_STYLE.geometry.short / 2)\n\n    cmfs = cast(\n        MultiSpectralDistributions, first_item(filter_cmfs(cmfs).values())\n    )\n\n    sd = sd_blackbody(temperature, cmfs.shape)\n\n    axes = figure.add_subplot(211)\n    settings: Dict[str, Any] = {\n        \"axes\": axes,\n        \"title\": f\"{blackbody} - Spectral Radiance\",\n        \"y_label\": \"W / (sr m$^2$) / m\",\n    }\n    settings.update(kwargs)\n    settings[\"standalone\"] = False\n\n    plot_single_sd(sd, cmfs.name, **settings)\n\n    axes = figure.add_subplot(212)\n\n    with domain_range_scale(\"1\"):\n        XYZ = sd_to_XYZ(sd, cmfs)\n\n    RGB = normalise_maximum(XYZ_to_plotting_colourspace(XYZ))\n\n    settings = {\n        \"axes\": axes,\n        \"aspect\": None,\n        \"title\": f\"{blackbody} - Colour\",\n        \"x_label\": f\"{temperature}K\",\n        \"y_label\": \"\",\n        \"x_ticker\": False,\n        \"y_ticker\": False,\n    }\n    settings.update(kwargs)\n    settings[\"standalone\"] = False\n\n    figure, axes = plot_single_colour_swatch(RGB, **settings)\n\n    settings = {\"axes\": axes, \"standalone\": True}\n    settings.update(kwargs)\n\n    return render(**settings)\n\n\n@override_style(\n    **{\n        \"ytick.left\": False,\n        \"ytick.labelleft\": False,\n    }\n)\ndef plot_blackbody_colours(\n    shape: SpectralShape = SpectralShape(150, 12500, 50),\n    cmfs: Union[\n        MultiSpectralDistributions,\n        str,\n        Sequence[Union[MultiSpectralDistributions, str]],\n    ] = \"CIE 1931 2 Degree Standard Observer\",\n    **kwargs: Any,\n) -> Tuple[plt.Figure, plt.Axes]:\n    \"\"\"\n    Plot blackbody colours.\n\n    Parameters\n    ----------\n    shape\n        Spectral shape to use as plot boundaries.\n    cmfs\n        Standard observer colour matching functions used for computing the\n        blackbody colours. ``cmfs`` can be of any type or form supported by the\n        :func:`colour.plotting.filter_cmfs` definition.\n\n    Other Parameters\n    ----------------\n    kwargs\n        {:func:`colour.plotting.artist`, :func:`colour.plotting.render`},\n        See the documentation of the previously listed definitions.\n\n    Returns\n    -------\n    :class:`tuple`\n        Current figure and axes.\n\n    Examples\n    --------\n    >>> plot_blackbody_colours(SpectralShape(150, 12500, 50))\n    ... # doctest: +ELLIPSIS\n    (<Figure size ... with 1 Axes>, <...AxesSubplot...>)\n\n    .. image:: ../_static/Plotting_Plot_Blackbody_Colours.png\n        :align: center\n        :alt: plot_blackbody_colours\n    \"\"\"\n\n    _figure, axes = artist(**kwargs)\n\n    cmfs = cast(\n        MultiSpectralDistributions, first_item(filter_cmfs(cmfs).values())\n    )\n\n    RGB = []\n    temperatures = []\n\n    for temperature in shape:\n        sd = sd_blackbody(temperature, cmfs.shape)\n\n        with domain_range_scale(\"1\"):\n            XYZ = sd_to_XYZ(sd, cmfs)\n\n        RGB.append(normalise_maximum(XYZ_to_plotting_colourspace(XYZ)))\n        temperatures.append(temperature)\n\n    x_min, x_max = min(temperatures), max(temperatures)\n    y_min, y_max = 0, 1\n\n    padding = 0.1\n    axes.bar(\n        x=np.array(temperatures) - padding,\n        height=1,\n        width=shape.interval + (padding * shape.interval),\n        color=RGB,\n        align=\"edge\",\n        zorder=CONSTANTS_COLOUR_STYLE.zorder.background_polygon,\n    )\n\n    settings: Dict[str, Any] = {\n        \"axes\": axes,\n        \"bounding_box\": (x_min, x_max, y_min, y_max),\n        \"title\": \"Blackbody Colours\",\n        \"x_label\": \"Temperature K\",\n        \"y_label\": None,\n    }\n    settings.update(kwargs)\n\n    return render(**settings)\n", "meta": {"hexsha": "6f60d53313aa28ccf85d5b935e53d878c673f48c", "size": 34481, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/plotting/colorimetry.py", "max_stars_repo_name": "tjdcs/colour", "max_stars_repo_head_hexsha": "09413da71b5da57408eb812797c5db1300d4791a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "colour/plotting/colorimetry.py", "max_issues_repo_name": "tjdcs/colour", "max_issues_repo_head_hexsha": "09413da71b5da57408eb812797c5db1300d4791a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/plotting/colorimetry.py", "max_forks_repo_name": "tjdcs/colour", "max_forks_repo_head_hexsha": "09413da71b5da57408eb812797c5db1300d4791a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8543933054, "max_line_length": 79, "alphanum_fraction": 0.6235608016, "include": true, "reason": "import numpy", "num_tokens": 8565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.18760598715718949}}
{"text": "# This file is part of LayerModel_lib\n#\n#     A tool to compute the transmission behaviour of plane electromagnetic waves\n#     through human tissue.\n#\n# Copyright (C) 2018 Jan-Christoph Brumm\n#\n# Licensed under MIT license.\n#\nimport numpy as np\nimport os\n\nfrom LayerModel_lib.voxelmodel import VoxelModel\nfrom LayerModel_lib.voxelmodel_importer import VoxelModelImporter\nfrom LayerModel_lib.coordinate import Coordinate\n\ncurrent_directory = os.path.dirname(__file__)\nbase_path = os.path.join(current_directory, '..', '..', '..', 'Numerical Human Phantoms', 'Donna')\n\n# path to the AVW File of this model\nfilename = os.path.join(base_path, 'segm_donna')\n# path to the tissue_mapping file\ntissue_file = os.path.join('ImportDonna_tissues.txt')\n\nAVW_Data = VoxelModelImporter(filename, tissue_file, 'AVW')\nmodel_orig = AVW_Data.data['image']\ntissue_name_orig = AVW_Data.tissue_names\ntissue_mapping = AVW_Data.tissue_mapping\n\nDonna = VoxelModel()\nDonna.show_progress_bar = True\n\n# needs to be set manually from README.txt\nDonna.set_scale(1.875, 1.875, 10)\n\nDonna.name = 'Donna'\nDonna.description = 'Donna model from the Helmholtz Zentrum München. ' \\\n                    'Resolution %.2fmm x %.2fmm x %.2fmm' % (Donna.scaling.x,\n                                                             Donna.scaling.y, Donna.scaling.z)\n\n#  Calculate the outer_shape of the original and the complete model\nouter_shape = AVW_Data.calculate_outer_shape(model_orig, tissue_mapping)\n\nDonna.add_voxel_data(short_name='original',\n                     name='Original data from AVW file',\n                     model=model_orig,\n                     outer_shape=outer_shape,\n                     tissue_names=tissue_name_orig)\n\nDonna.add_voxel_data(short_name='complete',\n                     name='The \\'original\\' model converted to our TissueProperties.',\n                     model=Donna.models['original'].data,\n                     outer_shape=outer_shape,\n                     tissue_mapping=tissue_mapping)\n\n# Calculate the trunk model\nstart_slice = int(96)\nend_slice = int(141)\n\n(model_trunk, trunk_mask) = AVW_Data.calculate_trunk_model(Donna, 'complete', z_start=start_slice, z_end=end_slice)\nouter_shape_trunk = AVW_Data.calculate_outer_shape(model_trunk)\n\nDonna.add_voxel_data(short_name='trunk',\n                     name=\"The trunk of the 'complete' model. Arms have been removed using \"\n                          \"VoxelModel.remove_arms().\",\n                     outer_shape=outer_shape_trunk,\n                     model=model_trunk,\n                     mask=trunk_mask,\n                     tissue_mapping=None)\n\n# Calculate the 3D surface of Donna\nsurface = Donna.create_3d_model(model_type='trunk', patch_size=(30, 30))\nDonna.models['trunk'].surface_3d = surface\n\nDonna.models['trunk'].endpoints = []\nfor (i, s) in enumerate(surface):\n   Donna.models['trunk'].endpoints.append(Coordinate(np.array(s['centroid'])))#\n\nDonna.save_model()\n", "meta": {"hexsha": "d81934b9f63eafb6d72925ecfd063bd006890c48", "size": 2929, "ext": "py", "lang": "Python", "max_stars_repo_path": "phantom_import/ImportDonna.py", "max_stars_repo_name": "janbrumm/layermodel_lib", "max_stars_repo_head_hexsha": "0d5e0c9ac77d302910823ebc757a4ec99541f3ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "phantom_import/ImportDonna.py", "max_issues_repo_name": "janbrumm/layermodel_lib", "max_issues_repo_head_hexsha": "0d5e0c9ac77d302910823ebc757a4ec99541f3ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phantom_import/ImportDonna.py", "max_forks_repo_name": "janbrumm/layermodel_lib", "max_forks_repo_head_hexsha": "0d5e0c9ac77d302910823ebc757a4ec99541f3ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6125, "max_line_length": 115, "alphanum_fraction": 0.6800955958, "include": true, "reason": "import numpy", "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18760597995334327}}
{"text": "import numpy as np\nimport torch\n\nclass coord_utils:\n    @staticmethod\n    def location_to_probability_map(size, loc):\n        # loc is not normalized location\n        promap_vec = torch.zeros([size, size], dtype=torch.float32)\n        try:\n            conf = loc[4]\n        except IndexError:\n            conf = 1.0\n\n        cx = loc[0]*size\n        cy = loc[1]*size\n        w = loc[2]*size\n        h = loc[3]*size\n\n        [x1, y1, x2, y2] = [(cx - w/2.).int(), (cy - h/2.).int(), (cx + w/2.).int(), (cy + h/2.).int()]\n        if x1 == x2: x2 += 1\n        if y1 == y2: y2 += 1\n        \n        x1 = x1.clamp(0, size)\n        y1 = y1.clamp(0, size)\n        x2 = x2.clamp(0, size)\n        y2 = y2.clamp(0, size)\n\n        for y in range(y1, y2): \n            for x in range(x1, x2):                       \n                promap_vec[y][x] = conf \n        return promap_vec\n\n    @staticmethod\n    def locations_to_probability_maps(size, locs):\n        pms = []\n        for loc in locs:\n            pm = coord_utils.location_to_probability_map(size, loc)\n            pms.append(pm.view(-1))\n        \n        return torch.stack(pms, dim=0)\n\n    @staticmethod\n    def probability_map_to_location(size, pmap):\n        # probability map to location (cx, cy, w, h)\n        pmap = pmap.view(size, size)\n\n        xlist = []\n        ylist = []\n        for y in range(size):\n            for x in range(size):\n                if(pmap[y][x] >= 0.5):\n                    xlist.append(x+0.5)\n                    ylist.append(y+0.5)\n\n        if len(xlist) == 0 or len(ylist) == 0:\n            return torch.zeros(4, dtype=torch.float32)\n\n        ax = np.array(xlist)\n        ay = np.array(ylist)\n        x1 = ax.mean()\n        y1 = ay.mean()\n\n        k = 3.5 #np.sqrt(2)\n        w = ax.std() * k + 0.5\n        h = ay.std() * k + 0.5\n\n        loc = torch.tensor([x1/size, y1/size, w/size, h/size], dtype=torch.float32)\n        return loc\n\n    @staticmethod\n    def normal_to_location(wid, ht, location):\n        # Normalized location to coordinate\n        wid *= 1.0\n        ht *= 1.0\n        location[0] *= wid\n        location[1] *= ht\n        location[2] *= wid\n        location[3] *= ht\n        return location\n\n    @staticmethod\n    def location_to_normal(wid, ht, location):\n        # Coordinates to normalized location\n        wid *= 1.0\n        ht *= 1.0\n        location[0] /= wid\n        location[1] /= ht\n        location[2] /= wid\n        location[3] /= ht\n        return location\n\n    @staticmethod\n    def bbox_iou(box1, box2, x1y1x2y2=True):\n        \"\"\"\n        Returns the IoU of two bounding boxes\n        \"\"\"\n        if not x1y1x2y2: # (cx, cy, w, h)\n            # Transform from center and width to exact coordinates\n            b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2\n            b1_y1, b1_y2 = box1[:, 1] - box1[:, 3] / 2, box1[:, 1] + box1[:, 3] / 2\n            b2_x1, b2_x2 = box2[:, 0] - box2[:, 2] / 2, box2[:, 0] + box2[:, 2] / 2\n            b2_y1, b2_y2 = box2[:, 1] - box2[:, 3] / 2, box2[:, 1] + box2[:, 3] / 2\n        else:\n            # Get the coordinates of bounding boxes\n            b1_x1, b1_y1, b1_x2, b1_y2 = box1[:, 0], box1[:, 1], box1[:, 2], box1[:, 3]\n            b2_x1, b2_y1, b2_x2, b2_y2 = box2[:, 0], box2[:, 1], box2[:, 2], box2[:, 3]\n\n        # get the corrdinates of the intersection rectangle\n        inter_rect_x1 = torch.max(b1_x1, b2_x1)\n        inter_rect_y1 = torch.max(b1_y1, b2_y1)\n        inter_rect_x2 = torch.min(b1_x2, b2_x2)\n        inter_rect_y2 = torch.min(b1_y2, b2_y2)\n        # Intersection area\n        inter_area = torch.clamp(inter_rect_x2 - inter_rect_x1 + 1, min=0) * torch.clamp(\n            inter_rect_y2 - inter_rect_y1 + 1, min=0\n        )\n        # Union Area\n        b1_area = (b1_x2 - b1_x1 + 1) * (b1_y2 - b1_y1 + 1)\n        b2_area = (b2_x2 - b2_x1 + 1) * (b2_y2 - b2_y1 + 1)\n\n        iou = inter_area / (b1_area + b2_area - inter_area + 1e-16)\n\n        return iou", "meta": {"hexsha": "6d3f9e56cdce852aeb7534f93a3184020e6ad210", "size": 3957, "ext": "py", "lang": "Python", "max_stars_repo_path": "coord_utils.py", "max_stars_repo_name": "JunwookHeo/YOLO-OT", "max_stars_repo_head_hexsha": "7004f25ce858acb7253bfcbc6fabeb915d8747a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "coord_utils.py", "max_issues_repo_name": "JunwookHeo/YOLO-OT", "max_issues_repo_head_hexsha": "7004f25ce858acb7253bfcbc6fabeb915d8747a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coord_utils.py", "max_forks_repo_name": "JunwookHeo/YOLO-OT", "max_forks_repo_head_hexsha": "7004f25ce858acb7253bfcbc6fabeb915d8747a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1707317073, "max_line_length": 103, "alphanum_fraction": 0.5031589588, "include": true, "reason": "import numpy", "num_tokens": 1321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.1875900622724822}}
{"text": "import math\n\nfrom typing import Optional, List, Tuple, Sequence, Union, cast, TypeVar\nfrom typing import Iterator, overload\nimport numpy\nimport itertools\n\nfrom ..types import Xp, Shape, DTypes, DTypesInt, DTypesFloat, List2d, ArrayXd\nfrom ..types import Floats1d, Floats2d, Floats3d, Floats4d\nfrom ..types import Array1d, Array2d, Array3d, Array4d, ListXd\nfrom ..types import FloatsXd, Ints1d, Ints2d, Ints3d, Ints4d, IntsXd, _Floats\nfrom ..types import DeviceTypes, Generator, Padded, Batchable, SizedGenerator\nfrom ..util import get_array_module, is_xp_array, to_numpy\n\n\nArrayT = TypeVar(\"ArrayT\", bound=ArrayXd)\nFloatsT = TypeVar(\"FloatsT\", bound=_Floats)\nFloatsType = TypeVar(\"FloatsType\", bound=FloatsXd)\nSQRT2PI = math.sqrt(2.0 / math.pi)\nINV_SQRT2 = 1.0 / math.sqrt(2.0)\nINV_SQRT_2PI = 1.0 / math.sqrt(2.0 * math.pi)\n\n\nclass Ops:\n    name: str = \"base\"\n    xp: Xp = numpy\n\n    def __init__(\n        self, device_type: DeviceTypes = \"cpu\", device_id: int = -1, **kwargs\n    ) -> None:\n        self.device_type = device_type\n        self.device_id = device_id\n\n    def to_numpy(self, data, *, byte_order=None):  # pragma: no cover\n        if isinstance(data, numpy.ndarray):\n            if byte_order:\n                dtype = data.dtype.newbyteorder(byte_order)\n                data = numpy.asarray(data, dtype=dtype)\n            return data\n        else:\n            raise ValueError(\"Cannot convert non-numpy from base Ops class\")\n\n    def minibatch(\n        self,\n        size: Union[int, Generator],\n        sequence: Batchable,\n        *,\n        shuffle: bool = False,\n        buffer: int = 1,\n    ) -> SizedGenerator:\n        \"\"\"Iterate slices from a sequence, optionally shuffled. Slices\n        may be either views or copies of the underlying data.\n\n        The `size` argument may be either an integer, or a sequence of integers.\n        If a sequence, a new size is drawn before every output.\n\n        If shuffle is True, shuffled batches are produced by first generating\n        an index array, shuffling it, and then using it to slice into the\n        sequence.\n\n        An internal queue of `buffer` items is accumulated before being each\n        output. Buffering is useful for some devices, to allow the\n        network to run asynchronously without blocking on every batch.\n        \"\"\"\n        if not hasattr(sequence, \"__len__\"):\n            err = f\"Can't minibatch data. Expected sequence, got {type(sequence)}\"\n            raise ValueError(err)\n        sizes = self._get_batch_sizes(\n            len(sequence), itertools.repeat(size) if isinstance(size, int) else size\n        )\n        indices = numpy.arange(len(sequence))\n\n        # This is a bit convoluted, but it's a time where convenience makes\n        # trickery worthwhile: instead of being an actual generator, we\n        # return our SizedGenerator object, which provides a __len__.\n        def _iter_items():\n            if shuffle:\n                numpy.random.shuffle(indices)\n            queue = []\n            i = 0\n            for size in sizes:\n                size = int(size)\n                queue.append(self._get_batch(sequence, indices[i : i + size]))\n                if len(queue) >= buffer:\n                    yield from queue\n                    queue = []\n                i += size\n            yield from queue\n\n        return SizedGenerator(_iter_items, len(sizes))\n\n    def multibatch(\n        self,\n        size: Union[int, Generator],\n        sequence: Batchable,\n        *others: Batchable,\n        shuffle: bool = False,\n        buffer: int = 1,\n    ) -> SizedGenerator:\n        \"\"\"Minibatch one or more sequences of data, and yield\n        lists with one batch per sequence. See ops.minibatch.\n        \"\"\"\n        # You'd think we could just do this by calling into minibatch and zip...\n        # But the shuffling makes it really hard.\n        sequences = (sequence,) + tuple(others)\n        if not all(hasattr(seq, \"__len__\") for seq in sequences):\n            values = \", \".join([f\"{type(seq)}\" for seq in sequences])\n            err = f\"Can't multibatch data. Expected sequences, got {values}\"\n            raise ValueError(err)\n        sizes = self._get_batch_sizes(\n            len(sequence), itertools.repeat(size) if isinstance(size, int) else size\n        )\n        indices = numpy.arange(len(sequence))\n\n        def _iter_items():\n            if shuffle:\n                numpy.random.shuffle(indices)\n            queue = []\n            i = 0\n            for size in sizes:\n                size = int(size)\n                idx_batch = indices[i : i + size]\n                queue.append([])\n                for sequence in sequences:\n                    queue[-1].append(self._get_batch(sequence, idx_batch))\n                if len(queue) >= buffer:\n                    yield from queue\n                    queue = []\n                i += size\n            yield from queue\n\n        return SizedGenerator(_iter_items, len(sizes))\n\n    def _get_batch(self, sequence, indices):\n        if isinstance(sequence, list):\n            subseq = [sequence[i] for i in indices]\n        elif isinstance(sequence, tuple):\n            subseq = tuple(sequence[i] for i in indices)\n        else:\n            subseq = sequence[indices]\n        if is_xp_array(subseq):\n            subseq = self.as_contig(self.xp.asarray(subseq))\n        return subseq\n\n    def _get_batch_sizes(self, length: int, sizes: Iterator[int]):\n        output = []\n        i = 0\n        while i < length:\n            output.append(next(sizes))\n            i += output[-1]\n        return output\n\n    def seq2col(\n        self, seq: Floats2d, nW: int, *, lengths: Optional[Ints1d] = None\n    ) -> Floats2d:\n        \"\"\"Given an (M, N) sequence of vectors, return an (M, N*(nW*2+1))\n        sequence. The new sequence is constructed by concatenating nW preceding\n        and succeeding vectors onto each column in the sequence, to extract a\n        window of features.\n        \"\"\"\n        # This is a test implementation that only supports nW=1 and lengths=None\n        assert nW == 1\n        assert lengths == None\n        B = seq.shape[0]\n        I = seq.shape[1]\n        cols = self.alloc3f(B, (nW * 2 + 1), I)\n        # Copy left contexts. The last words aren't the left-context for anything.\n        cols[nW:, :nW] = self.reshape3f(seq[:-nW], -1, nW, I)\n        cols[:, nW] = seq\n        cols[:-nW, nW + 1 :] = self.reshape3f(seq[nW:], -1, nW, I)\n        return self.reshape2f(cols, B, I * (2 * nW + 1))\n\n    def backprop_seq2col(\n        self, dY: Floats2d, nW: int, *, lengths: Optional[Ints1d] = None\n    ) -> Floats2d:\n        \"\"\"The reverse/backward operation of the `seq2col` function: calculate\n        the gradient of the original `(M, N)` sequence, as a function of the\n        gradient of the output `(M, N*(nW*2+1))` sequence.\n        \"\"\"\n        # This is a test implementation that only supports nW=1 and lengths=None\n        assert nW == 1\n        assert lengths == None\n        nF = nW * 2 + 1\n        B = dY.shape[0]\n        I = dY.shape[1] // nF\n        # Having trouble getting the kernel to work...\n        dX = self.alloc2f(B, I)\n        dY3d = self.reshape3f(dY, B, nF, I)\n        dX[:-nW] += self.reshape2f(dY3d[nW:, :nW], -1, I)\n        dX += dY3d[:, nW]\n        dX[nW:] += self.reshape2f(dY3d[:-nW, nW + 1 :], -1, I)\n        return dX\n\n    def gemm(\n        self,\n        x: Floats2d,\n        y: Floats2d,\n        out: Optional[Floats2d] = None,\n        trans1: bool = False,\n        trans2: bool = False,\n    ) -> Floats2d:\n        \"\"\"Perform General Matrix Multiplication (GeMM) and optionally store\n        the result in the specified output variable.\n        \"\"\"\n        if trans1:\n            x = x.T\n        if trans2:\n            y = y.T\n        if out is None:\n            return self.xp.dot(x, y)\n        else:\n            self.xp.dot(x, y, out=out)\n            return out\n\n    def tile(self, X: Floats2d, reps: int) -> Floats2d:\n        return self.xp.tile(X, reps)\n\n    def affine(self, X: Floats2d, W: Floats2d, b: Floats1d) -> Floats2d:\n        \"\"\"Apply a weights layer and a bias to some inputs, i.e.\n        Y = X @ W.T + b\n        \"\"\"\n        Y = self.gemm(X, W, trans2=True)\n        Y += b\n        return Y\n\n    @overload \n    def flatten(\n        self,\n        X: List[Floats2d],\n        dtype: Optional[DTypes] = None,\n        pad: int = 0,\n        ndim_if_empty: int = 2,\n     ) -> Floats2d:\n        ...\n\n    @overload \n    def flatten(\n        self,\n        X: List[Ints1d],\n        dtype: Optional[DTypes] = None,\n        pad: int = 0,\n        ndim_if_empty: int = 2,\n     ) -> Ints1d:\n        ...\n\n    @overload \n    def flatten(\n        self,\n        X: List2d,\n        dtype: Optional[DTypes] = None,\n        pad: int = 0,\n        ndim_if_empty: int = 2,\n     ) -> Array2d:\n        ...\n\n    # further specific typed signatures can be added as necessary\n\n    @overload \n    def flatten(\n        self,\n        X: ListXd,\n        dtype: Optional[DTypes] = None,\n        pad: int = 0,\n        ndim_if_empty: int = 2,\n     ) -> ArrayXd:\n        ...\n\n    @overload \n    def flatten(\n        self,\n        X: Sequence[ArrayXd],\n        dtype: Optional[DTypes] = None,\n        pad: int = 0,\n        ndim_if_empty: int = 2,\n     ) -> ArrayXd:\n        ...\n\n    def flatten(\n        self,\n        X: Sequence[ArrayXd],\n        dtype: Optional[DTypes] = None,\n        pad: int = 0,\n        ndim_if_empty: int = 2,\n    ) -> ArrayXd:\n        \"\"\"Flatten a list of arrays into one large array.\"\"\"\n        if X is None or len(X) == 0:\n            return self.alloc((0,) * ndim_if_empty, dtype=dtype or \"f\")\n        xp = get_array_module(X[0])\n        shape_if_empty = X[0].shape\n        X = [x for x in X if x.size != 0]\n        if len(X) == 0:\n            return self.alloc(shape_if_empty, dtype=dtype or \"f\")\n        if int(pad) >= 1:\n            padded = []\n            for x in X:\n                padded.append(xp.zeros((pad,) + x.shape[1:], dtype=x.dtype))\n                padded.append(x)\n            padded.append(xp.zeros((pad,) + x.shape[1:], dtype=x.dtype))\n            X = padded\n        result = xp.concatenate(X)\n        if dtype is not None:\n            result = xp.asarray(result, dtype=dtype)\n        return result\n\n    @overload\n    def unflatten(self, X: Floats2d, lengths: Ints1d, pad: int = 0) -> List[Floats2d]:\n        ...\n\n    @overload\n    def unflatten(self, X: Ints1d, lengths: Ints1d, pad: int = 0) -> List[Ints1d]:\n        ...\n\n    @overload\n    def unflatten(self, X: Array2d, lengths: Ints1d, pad: int = 0) -> List2d:\n        ...\n\n    # further specific typed signatures can be added as necessary\n\n    @overload\n    def unflatten(self, X: ArrayXd, lengths: Ints1d, pad: int = 0) -> ListXd:\n        ...\n\n    def unflatten(self, X: ArrayXd, lengths: Ints1d, pad: int = 0) -> ListXd:\n        \"\"\"The reverse/backward operation of the `flatten` function: unflatten\n        a large array into a list of arrays according to the given lengths.\n        \"\"\"\n        # cupy.split requires lengths to be in CPU memory.\n        lengths = to_numpy(lengths)\n\n        if pad > 0:\n            lengths = numpy.where(lengths > 0, lengths + pad, 0)  # type: ignore\n        unflat = self.xp.split(X, numpy.cumsum(lengths))[:-1]  # type: ignore\n        if pad > 0:\n            unflat = [a[pad:] for a in unflat]\n\n        assert len(unflat) == len(lengths)\n\n        return unflat\n\n    @overload\n    def pad(self, seqs: List[Ints2d], round_to=1) -> Ints3d:\n        ...\n\n    @overload  # noqa: F811\n    def pad(self, seqs: List[Floats2d], round_to=1) -> Floats3d:\n        ...\n\n    def pad(  # noqa: F811\n        self, seqs: Union[List[Ints2d], List[Floats2d]], round_to=1\n    ) -> Array3d:\n        \"\"\"Perform padding on a list of arrays so that they each have the same\n        length, by taking the maximum dimension across each axis. This only\n        works on non-empty sequences with the same `ndim` and `dtype`.\n        \"\"\"\n        # TODO: This should be generalized to handle different ranks\n        if not seqs:\n            raise ValueError(\"Cannot pad empty sequence\")\n        if len(set(seq.ndim for seq in seqs)) != 1:\n            raise ValueError(\"Cannot pad sequences with different ndims\")\n        if len(set(seq.dtype for seq in seqs)) != 1:\n            raise ValueError(\"Cannot pad sequences with different dtypes\")\n        if len(set(seq.shape[1:] for seq in seqs)) != 1:\n            raise ValueError(\"Cannot pad sequences that differ on other dimensions\")\n        # Find the maximum dimension along each axis. That's what we'll pad to.\n        length = max(len(seq) for seq in seqs)\n        # Round the length to nearest bucket -- helps on GPU, to make similar\n        # array sizes.\n        length = (length + (round_to - 1)) // round_to * round_to\n        final_shape = (len(seqs), length) + seqs[0].shape[1:]\n        output: Array3d = self.alloc(final_shape, dtype=seqs[0].dtype)\n        for i, arr in enumerate(seqs):\n            # It's difficult to convince this that the dtypes will match.\n            output[i, : arr.shape[0]] = arr  # type: ignore[assignment, call-overload]\n        return output\n\n    def unpad(self, padded: Array3d, lengths: List[int]) -> List2d:\n        \"\"\"The reverse/backward operation of the `pad` function: transform an\n        array back into a list of arrays, each with their original length.\n        \"\"\"\n        output = []\n        for i, length in enumerate(lengths):\n            output.append(padded[i, :length])\n        return cast(List2d, output)\n\n    def list2padded(self, seqs: List2d) -> Padded:\n        \"\"\"Pack a sequence of 2d arrays into a Padded datatype.\"\"\"\n        if not seqs:\n            return Padded(\n                self.alloc3f(0, 0, 0), self.alloc1i(0), self.alloc1i(0), self.alloc1i(0)\n            )\n        elif len(seqs) == 1:\n            data = self.reshape3(seqs[0], seqs[0].shape[0], 1, seqs[0].shape[1])\n            size_at_t = self.asarray1i([1] * data.shape[0])\n            lengths = self.asarray1i([data.shape[0]])\n            indices = self.asarray1i([0])\n            return Padded(data, size_at_t, lengths, indices)\n        lengths_indices = [(len(seq), i) for i, seq in enumerate(seqs)]\n        lengths_indices.sort(reverse=True)\n        indices_ = [i for length, i in lengths_indices]\n        lengths_ = [length for length, i in lengths_indices]\n        nS = max([seq.shape[0] for seq in seqs])\n        nB = len(seqs)\n        nO = seqs[0].shape[1]\n        # Reorder the sequences, by length. This looks the same in either\n        # direction: you're swapping elements between their original and sorted\n        # position.\n        seqs = cast(List2d, [seqs[i] for i in indices_])\n        arr: Array3d = self.pad(seqs)\n        assert arr.shape == (nB, nS, nO), (nB, nS, nO)\n        arr = self.as_contig(arr.transpose((1, 0, 2)))\n        assert arr.shape == (nS, nB, nO)\n        # Build a lookup table so we can find how big the batch is at point t.\n        batch_size_at_t_ = [0 for _ in range(nS)]\n        current_size = len(lengths_)\n        for t in range(nS):\n            while current_size and t >= lengths_[current_size - 1]:\n                current_size -= 1\n            batch_size_at_t_[t] = current_size\n        assert sum(lengths_) == sum(batch_size_at_t_)\n        return Padded(\n            arr,\n            self.asarray1i(batch_size_at_t_),\n            self.asarray1i(lengths_),\n            self.asarray1i(indices_),\n        )\n\n    def padded2list(self, padded: Padded) -> List2d:\n        \"\"\"Unpack a Padded datatype to a list of 2-dimensional arrays.\"\"\"\n        data = padded.data\n        indices = to_numpy(padded.indices)\n        lengths = to_numpy(padded.lengths)\n        unpadded: List[Optional[Array2d]] = [None] * len(lengths)\n        # Transpose from (length, batch, data) to (batch, length, data)\n        data = self.as_contig(data.transpose((1, 0, 2)))\n        for i in range(data.shape[0]):\n            unpadded[indices[i]] = data[i, : int(lengths[i])]\n        return cast(List2d, unpadded)\n\n    def get_dropout_mask(self, shape: Shape, drop: Optional[float]) -> FloatsXd:\n        \"\"\"Create a random mask for applying dropout, with a certain percent of\n        the mask (defined by `drop`) will contain zeros. The neurons at those\n        positions will be deactivated during training, resulting in a more\n        robust network and less overfitting.\n        \"\"\"\n        if drop is None or drop <= 0:\n            return self.xp.ones(shape, dtype=\"f\")\n        elif drop >= 1.0:\n            return self.alloc(shape)\n        coinflips = self.xp.random.uniform(0.0, 1.0, shape)\n        mask = (coinflips >= drop) / (1.0 - drop)\n        return cast(FloatsXd, self.asarray(mask, dtype=\"float32\"))\n\n    def alloc1f(\n        self,\n        d0: int,\n        *,\n        dtype: Optional[DTypesFloat] = \"float32\",\n        zeros: bool = True,\n    ) -> Floats1d:\n        return self.alloc((d0,), dtype=dtype, zeros=zeros)\n\n    def alloc2f(\n        self,\n        d0: int,\n        d1: int,\n        *,\n        dtype: Optional[DTypesFloat] = \"float32\",\n        zeros: bool = True,\n    ) -> Floats2d:\n        return self.alloc((d0, d1), dtype=dtype, zeros=zeros)\n\n    def alloc3f(\n        self,\n        d0: int,\n        d1: int,\n        d2: int,\n        *,\n        dtype: Optional[DTypesFloat] = \"float32\",\n        zeros: bool = True,\n    ) -> Floats3d:\n        return self.alloc((d0, d1, d2), dtype=dtype, zeros=zeros)\n\n    def alloc4f(\n        self,\n        d0: int,\n        d1: int,\n        d2: int,\n        d3: int,\n        *,\n        dtype: Optional[DTypesFloat] = \"float32\",\n        zeros: bool = True,\n    ) -> Floats4d:\n        return self.alloc((d0, d1, d2, d3), dtype=dtype, zeros=zeros)\n\n    def alloc_f(\n        self,\n        shape: Shape,\n        *,\n        dtype: Optional[DTypesFloat] = \"float32\",\n        zeros: bool = True,\n    ) -> FloatsXd:\n        return self.alloc(shape, dtype=dtype, zeros=zeros)\n\n    def alloc1i(\n        self,\n        d0: int,\n        *,\n        dtype: Optional[DTypesInt] = \"int32\",\n        zeros: bool = True,\n    ) -> Ints1d:\n        return self.alloc((d0,), dtype=dtype, zeros=zeros)\n\n    def alloc2i(\n        self,\n        d0: int,\n        d1: int,\n        *,\n        dtype: Optional[DTypesInt] = \"int32\",\n        zeros: bool = True,\n    ) -> Ints2d:\n        return self.alloc((d0, d1), dtype=dtype, zeros=zeros)\n\n    def alloc3i(\n        self,\n        d0: int,\n        d1: int,\n        d2: int,\n        *,\n        dtype: Optional[DTypesInt] = \"int32\",\n        zeros: bool = True,\n    ) -> Ints3d:\n        return self.alloc((d0, d1, d2), dtype=dtype, zeros=zeros)\n\n    def alloc4i(\n        self,\n        d0: int,\n        d1: int,\n        d2: int,\n        d3: int,\n        *,\n        dtype: Optional[DTypesInt] = \"int32\",\n        zeros: bool = True,\n    ) -> Ints4d:\n        return self.alloc((d0, d1, d2, d3), dtype=dtype, zeros=zeros)\n\n    def alloc_i(\n        self,\n        shape: Shape,\n        *,\n        dtype: Optional[DTypesInt] = \"int32\",\n        zeros: bool = True,\n    ) -> IntsXd:\n        return self.alloc(shape, dtype=dtype, zeros=zeros)\n\n    def alloc(\n        self,\n        shape: Shape,\n        *,\n        dtype: Optional[DTypes] = \"float32\",\n        zeros: bool = True,\n    ) -> ArrayT:\n        \"\"\"Allocate an array of a certain shape.\"\"\"\n        if isinstance(shape, int):\n            shape = (shape,)\n\n        if zeros:\n            return self.xp.zeros(shape, dtype=dtype)\n        else:\n            return self.xp.empty(shape, dtype=dtype)\n\n    def reshape1(self, array: ArrayXd, d0: int) -> Array1d:\n        return cast(Array1d, self.reshape(array, (d0,)))\n\n    def reshape2(self, array: ArrayXd, d0: int, d1: int) -> Array2d:\n        return cast(Array2d, self.reshape(array, (d0, d1)))\n\n    def reshape3(self, array: ArrayXd, d0: int, d1: int, d2: int) -> Array3d:\n        return cast(Array3d, self.reshape(array, (d0, d1, d2)))\n\n    def reshape4(self, array: ArrayXd, d0: int, d1: int, d2: int, d3: int) -> Array4d:\n        return cast(Array4d, self.reshape(array, (d0, d1, d2, d3)))\n\n    def reshape1f(self, array: FloatsXd, d0: int) -> Floats1d:\n        return cast(Floats1d, self.reshape(array, (d0,)))\n\n    def reshape2f(self, array: FloatsXd, d0: int, d1: int) -> Floats2d:\n        return cast(Floats2d, self.reshape(array, (d0, d1)))\n\n    def reshape3f(self, array: FloatsXd, d0: int, d1: int, d2: int) -> Floats3d:\n        return cast(Floats3d, self.reshape(array, (d0, d1, d2)))\n\n    def reshape4f(\n        self, array: FloatsXd, d0: int, d1: int, d2: int, d3: int\n    ) -> Floats4d:\n        return cast(Floats4d, self.reshape(array, (d0, d1, d2, d3)))\n\n    def reshape_f(self, array: FloatsXd, shape: Shape) -> FloatsXd:\n        return self.reshape(array, shape)\n\n    def reshape1i(self, array: IntsXd, d0: int) -> Ints1d:\n        return cast(Ints1d, self.reshape(array, (d0,)))\n\n    def reshape2i(self, array: IntsXd, d0: int, d1: int) -> Ints2d:\n        return cast(Ints2d, self.reshape(array, (d0, d1)))\n\n    def reshape3i(self, array: IntsXd, d0: int, d1: int, d2: int) -> Ints3d:\n        return cast(Ints3d, self.reshape(array, (d0, d1, d2)))\n\n    def reshape4i(self, array: IntsXd, d0: int, d1: int, d2: int, d3: int) -> Ints4d:\n        return cast(Ints4d, self.reshape(array, (d0, d1, d2, d3)))\n\n    def reshape_i(self, array: IntsXd, shape: Shape) -> IntsXd:\n        return self.reshape(array, shape)\n\n    def reshape(self, array: ArrayT, shape: Shape) -> ArrayT:\n        \"\"\"Reshape an array.\"\"\"\n        if isinstance(shape, int):\n            shape = (shape,)\n        return cast(ArrayT, array.reshape(shape))\n\n    def asarray4f(\n        self,\n        data: Union[Floats4d, Sequence[int]],\n        *,\n        dtype: Optional[DTypes] = \"float32\",\n    ) -> Floats4d:\n        return cast(Floats4d, self.asarray(data, dtype=dtype))\n\n    def asarray3f(\n        self,\n        data: Union[Floats3d, Sequence[int]],\n        *,\n        dtype: Optional[DTypes] = \"float32\",\n    ) -> Floats3d:\n        return cast(Floats3d, self.asarray(data, dtype=dtype))\n\n    def asarray2f(\n        self,\n        data: Union[Floats2d, Sequence[int]],\n        *,\n        dtype: Optional[DTypes] = \"float32\",\n    ) -> Floats2d:\n        return cast(Floats2d, self.asarray(data, dtype=dtype))\n\n    def asarray1f(\n        self,\n        data: Union[Floats1d, Sequence[int]],\n        *,\n        dtype: Optional[DTypes] = \"float32\",\n    ) -> Floats1d:\n        return cast(Floats1d, self.asarray(data, dtype=dtype))\n\n    def asarray_f(\n        self,\n        data: Union[FloatsXd, Sequence[float]],\n        *,\n        dtype: Optional[DTypes] = \"float32\",\n    ) -> FloatsXd:\n        return cast(FloatsXd, self.asarray(data, dtype=dtype))\n\n    def asarray1i(\n        self, data: Union[Ints1d, Sequence[int]], *, dtype: Optional[DTypes] = \"int32\"\n    ) -> Ints1d:\n        return cast(Ints1d, self.asarray(data, dtype=dtype))\n\n    def asarray2i(\n        self, data: Union[Ints2d, Sequence[int]], *, dtype: Optional[DTypes] = \"int32\"\n    ) -> Ints2d:\n        return cast(Ints2d, self.asarray(data, dtype=dtype))\n\n    def asarray3i(\n        self, data: Union[Ints3d, Sequence[int]], *, dtype: Optional[DTypes] = \"int32\"\n    ) -> Ints3d:\n        return cast(Ints3d, self.asarray(data, dtype=dtype))\n\n    def asarray4i(\n        self, data: Union[Ints4d, Sequence[int]], *, dtype: Optional[DTypes] = \"int32\"\n    ) -> Ints4d:\n        return cast(Ints4d, self.asarray(data, dtype=dtype))\n\n    def asarray_i(\n        self, data: Union[IntsXd, Sequence[int]], *, dtype: Optional[DTypes] = \"int32\"\n    ) -> IntsXd:\n        return cast(IntsXd, self.asarray(data, dtype=dtype))\n\n    def asarray(\n        self,\n        data: Union[ArrayXd, Sequence[ArrayXd], Sequence[float], Sequence[int]],\n        *,\n        dtype: Optional[DTypes] = None,\n    ) -> ArrayXd:\n        \"\"\"Ensure a given array is of the correct type.\"\"\"\n        if isinstance(data, self.xp.ndarray):\n            if dtype is None:\n                return data\n            elif data.dtype == dtype:\n                return data\n            else:\n                return self.xp.asarray(data, dtype=dtype)\n        elif hasattr(data, \"numpy\"):\n            # Handles PyTorch Tensor\n            return data.numpy()  # type: ignore[union-attr]\n        elif dtype is not None:\n            return self.xp.array(data, dtype=dtype)\n        else:\n            return self.xp.array(data)\n\n    def as_contig(self, data: ArrayT, dtype: Optional[DTypes] = None) -> ArrayT:\n        \"\"\"Allow the backend to make a contiguous copy of an array.\n        Implementations of `Ops` do not have to make a copy or make it\n        contiguous if that would not improve efficiency for the execution engine.\n        \"\"\"\n        if data.flags[\"C_CONTIGUOUS\"] and dtype in (None, data.dtype):\n            return data\n        kwargs = {\"dtype\": dtype} if dtype is not None else {}\n        return self.xp.ascontiguousarray(data, **kwargs)\n\n    def sigmoid(self, X: FloatsType, *, inplace: bool = False) -> FloatsType:\n        # To prevent overflows and help with regularization/numerical stability\n        X = self.xp.clip(X, -20.0, 20.0)\n\n        if inplace:\n            self.xp.exp(-X, out=X)\n            X += 1.0  # type: ignore[assignment]\n            X **= -1.0  # type: ignore[assignment]\n            return cast(FloatsType, X)\n        else:\n            return cast(FloatsType, 1.0 / (1.0 + self.xp.exp(-X)))\n\n    def backprop_sigmoid(\n        self, dY: FloatsType, Y: FloatsType, *, inplace: bool = False\n    ) -> FloatsType:\n        if inplace:\n            self.dsigmoid(Y, inplace=True)\n            Y *= dY  # type: ignore\n            return Y\n        else:\n            return dY * self.dsigmoid(Y, inplace=inplace)  # type: ignore\n\n    def dsigmoid(self, Y: FloatsType, *, inplace: bool = False) -> FloatsType:\n        if inplace:\n            Y *= 1 - Y\n            return Y\n        else:\n            return Y * (1.0 - Y)\n\n    def dtanh(self, Y: FloatsT, *, inplace: bool = False) -> FloatsT:\n        if inplace:\n            Y **= 2\n            Y *= -1.0\n            Y += 1.0\n            return Y\n        else:\n            return 1 - Y**2\n\n    def softmax(\n        self,\n        x: FloatsT,\n        *,\n        inplace: bool = False,\n        axis: int = -1,\n        temperature: float = 1.0,\n    ) -> FloatsT:\n        if temperature != 1.0:\n            x = x / temperature\n        maxes = self.xp.max(x, axis=axis, keepdims=True)\n        shifted = x - maxes\n        new_x = self.xp.exp(shifted)\n        new_x /= new_x.sum(axis=axis, keepdims=True)\n        return new_x\n\n    def softmax_sequences(\n        self, Xs: Floats2d, lengths: Ints1d, *, inplace: bool = False, axis: int = -1\n    ) -> Floats2d:\n        if Xs.ndim >= 3:\n            err = f\"Softmax currently only supports 2d. Got: {Xs.ndim}\"\n            raise NotImplementedError(err)\n        # This loses almost no fidelity, and helps the numerical stability.\n        Xs = self.xp.clip(Xs, -20.0, 20.0)\n        new_x = self.xp.exp(Xs)\n        summed = self.backprop_reduce_sum(self.reduce_sum(new_x, lengths), lengths)\n        new_x /= summed\n        return new_x\n\n    def backprop_softmax(\n        self, Y: FloatsT, dY: FloatsT, *, axis: int = -1, temperature: float = 1.0\n    ) -> FloatsT:\n        if temperature != 1.0:\n            dY = dY / temperature\n\n        dX = Y * dY\n        dX -= Y * dX.sum(axis=axis, keepdims=True)\n        return dX\n\n    def backprop_softmax_sequences(\n        self, dY: Floats2d, Y: Floats2d, lengths: Ints1d\n    ) -> Floats2d:\n        dX = Y * dY\n        sum_dX = self.backprop_reduce_sum(self.reduce_sum(dX, lengths), lengths)\n        dX -= Y * sum_dX\n        return dX\n\n    def lstm_forward_training(\n        self,\n        params: Floats1d,\n        H0: Floats3d,\n        C0: Floats3d,\n        X: Floats2d,\n        size_at_t: Ints1d,\n    ) -> Tuple[Floats2d, Tuple]:\n        assert H0.shape == C0.shape\n        assert H0.shape[1] == C0.shape[1]\n        Y, fwd_state = lstm_forward_training(params, H0, C0, X, size_at_t)\n        return Y, fwd_state\n\n    def lstm_forward_inference(\n        self,\n        params: Floats1d,\n        H0: Floats3d,\n        C0: Floats3d,\n        X: Floats2d,\n        size_at_t: Ints1d,\n    ) -> Floats2d:\n        Y, _ = lstm_forward_training(params, H0, C0, X, size_at_t)\n        return Y\n\n    def backprop_lstm(\n        self, dY: Floats2d, lengths: Ints1d, params: Floats1d, fwd_state: Tuple\n    ) -> Tuple[Floats2d, Floats1d]:\n        dX, d_params = backprop_lstm(dY, lengths, params, fwd_state)\n        return dX, d_params\n\n    def maxout(self, X: Floats3d) -> Tuple[Floats2d, Ints2d]:\n        which = X.argmax(axis=-1)\n        return X.max(axis=-1), which\n\n    def backprop_maxout(self, dY: Floats2d, which: Ints2d, P: int) -> Floats3d:\n        dX = self.alloc3f(dY.shape[0], dY.shape[1], P, dtype=dY.dtype)\n        for b in range(dY.shape[0]):\n            for o in range(dY.shape[1]):\n                dX[b, o, which[b, o]] = dY[b, o]\n        return dX\n\n    def relu(self, X: Floats2d, inplace: bool = False) -> Floats2d:\n        if not inplace:\n            return X * (X > 0)\n        else:\n            X *= X > 0\n            return X\n\n    def backprop_relu(\n        self, dY: Floats2d, Y: Floats2d, inplace: bool = False\n    ) -> Floats2d:\n        if not inplace:\n            return dY * (Y > 0)\n        dY *= Y > 0\n        return dY\n\n    def clipped_linear(\n        self,\n        X: FloatsType,\n        slope: float = 1.0,\n        offset: float = 0.0,\n        min_val: float = 0.0,\n        max_val: float = 1.0,\n        inplace: bool = False,\n    ) -> FloatsType:\n        if inplace:\n            X *= slope  # type: ignore[assignment]\n            X += offset  # type: ignore[assignment]\n            return cast(FloatsType, self.xp.clip(X, min_val, max_val, out=X))\n        out = X * slope + offset  # type: ignore[assignment]\n        return cast(FloatsType, self.xp.clip(out, min_val, max_val))\n\n    def backprop_clipped_linear(\n        self,\n        dY: FloatsType,\n        X: FloatsType,\n        slope: float = 1.0,\n        offset: float = 0.0,\n        min_val: float = 0.0,\n        max_val: float = 1.0,\n        inplace: bool = False,\n    ) -> FloatsType:\n        low = (min_val - offset) / slope\n        high = (max_val - offset) / slope\n        slope = self.xp.float64(slope).astype(X.dtype)\n        zero = self.xp.float64(0.0).astype(X.dtype)\n        dX = self.xp.where((low < X) & (X < high), slope, zero)\n        if inplace:\n            dY *= dX\n            return dY\n        return dY * dX\n\n    def relu_k(\n        self, X: FloatsType, n: float = 6.0, inplace: bool = False\n    ) -> FloatsType:\n        return self.clipped_linear(X, max_val=n, inplace=inplace)\n\n    def backprop_relu_k(\n        self, dY: FloatsType, X: FloatsType, n: float = 6.0, inplace: bool = False\n    ) -> FloatsType:\n        return self.backprop_clipped_linear(dY, X, max_val=n, inplace=inplace)\n\n    def hard_sigmoid(self, X: FloatsType, inplace: bool = False) -> FloatsType:\n        return self.clipped_linear(X, slope=0.2, offset=0.5)\n\n    def backprop_hard_sigmoid(\n        self, dY: FloatsType, X: FloatsType, inplace: bool = False\n    ) -> FloatsType:\n        return self.backprop_clipped_linear(dY, X, slope=0.2, offset=0.5)\n\n    def hard_tanh(self, X: FloatsType, inplace: bool = False) -> FloatsType:\n        return self.clipped_linear(X, min_val=-1.0, max_val=1.0)\n\n    def backprop_hard_tanh(\n        self, dY: FloatsType, X: FloatsType, inplace: bool = False\n    ) -> FloatsType:\n        return self.backprop_clipped_linear(dY, X, min_val=-1.0, max_val=1.0)\n\n    def swish(self, X: FloatsType, inplace: bool = False) -> FloatsType:\n        if inplace:\n            X *= self.sigmoid(X)  # type: ignore[operator, assignment]\n            return cast(FloatsType, X)\n        out = X * self.sigmoid(X)  # type: ignore[operator]\n        return cast(FloatsType, out)\n\n    def backprop_swish(\n        self, dY: FloatsType, X: FloatsType, Y: FloatsType, inplace: bool = False\n    ) -> FloatsType:\n        Y = Y + self.sigmoid(X) * (1 - Y)  # type: ignore[operator]\n        if inplace:\n            dY *= Y  # type: ignore[operator, assignment]\n            return cast(FloatsType, dY)\n        out = dY * Y  # type: ignore[operator]\n        return cast(FloatsType, out)\n\n    # Following https://www.scitepress.org/Papers/2019/74696/74696.pdf\n    def hard_swish(self, X: FloatsType, inplace: bool = False) -> FloatsType:\n        if inplace:\n            X *= self.hard_sigmoid(X)  # type: ignore[operator, assignment]\n            return cast(FloatsType, X)\n        out = X * self.hard_sigmoid(X)  # type: ignore[operator]\n        return cast(FloatsType, out)\n\n    def backprop_hard_swish(\n        self, dY: FloatsType, X: FloatsType, inplace: bool = False\n    ) -> FloatsType:\n        dX = X * 0.4 + 0.5\n        dX[X > 2.5] = 1.0\n        dX[X < -2.5] = 0\n        if inplace:\n            dY *= dX\n            return dY\n        return dY * dX\n\n    # From https://arxiv.org/pdf/1905.02244v5.pdf\n    def hard_swish_mobilenet(self, X: FloatsType, inplace: bool = False) -> FloatsType:\n        if inplace:\n            X *= self.relu_k(X + 3) / 6\n            return X\n        return X * (self.relu_k(X + 3) / 6)\n\n    def backprop_hard_swish_mobilenet(\n        self, dY: FloatsType, X: FloatsType, inplace: bool = False\n    ) -> FloatsType:\n        dX = (1 / 6) * (X * 2.0 + 3.0)\n        dX[X > 3.0] = 1.0\n        dX[X < -3.0] = 0\n        if inplace:\n            dY *= dX\n            return dY\n        return dX * dY\n\n    # Code snippet taken from:\n    # https://www.johndcook.com/blog/2009/01/19/stand-alone-error-function-erf/\n    def erf(self, X: FloatsType) -> FloatsType:\n        # save the sign of x\n        sign = self.xp.sign(X)\n        X = self.xp.abs(X)\n\n        a1 = 0.254829592\n        a2 = -0.284496736\n        a3 = 1.421413741\n        a4 = -1.453152027\n        a5 = 1.061405429\n        p = 0.3275911\n\n        t = 1.0 / (1.0 + p * X)\n        y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * self.xp.exp(\n            -X * X\n        )\n        out = sign * y\n        out = out.astype(X.dtype)\n        return out\n\n    def sechsq(self, X: FloatsType) -> FloatsType:\n        return (1 / self.xp.cosh(X)) ** 2\n\n    def gelu_approx(self, X: FloatsType, inplace: bool = False) -> FloatsType:\n        tmp = 1.0 + self.xp.tanh(SQRT2PI * (X + 0.044715 * self.xp.power(X, 3)))\n        tmp *= 0.5\n        tmp = tmp.astype(X.dtype)\n        if inplace:\n            X *= tmp\n            return X\n        else:\n            Y = self.xp.array(X)\n            Y *= tmp\n            return Y\n\n    def backprop_gelu_approx(\n        self, dY: FloatsType, X: FloatsType, inplace: bool = False\n    ) -> FloatsType:\n        dX = self.alloc_f(X.shape)\n        Xp3 = self.xp.power(X, 3)\n        tmp = 0.5 * self.xp.tanh(0.0356774 * Xp3 + 0.797885 * X)\n        tmp += (0.0535161 * Xp3 + 0.398942 * X) * self.sechsq(\n            0.0356774 * Xp3 + 0.797885 * X\n        )\n        tmp += 0.5\n        dX += tmp\n        if inplace:\n            dY *= dX\n            return dY\n        return dY * dX\n\n    def gelu(self, X: FloatsType, inplace: bool = False) -> FloatsType:\n        # GELU(x) = x · Φ(x)\n        cdf = gaussian_cdf(self, X)\n        if inplace:\n            X *= cdf  # type: ignore[operator, assignment]\n            return X\n        return X * cdf  # type: ignore[operator, return-value]\n\n    def backprop_gelu(\n        self, dY: FloatsType, X: FloatsType, inplace: bool = False\n    ) -> FloatsType:\n        # GELU'(x) = Φ(x) + x · PDF(x)\n        dX = gaussian_cdf(self, X) + X * gaussian_pdf(self, X)  # type: ignore[operator]\n        if inplace:\n            dY *= dX\n            return dY\n        return dY * dX\n\n    def mish(\n        self, X: FloatsType, threshold: float = 20.0, inplace: bool = False\n    ) -> FloatsType:\n        tmp = X * self.xp.tanh(self.xp.log(1.0 + self.xp.exp(X)))\n        Y = self.xp.where(X >= threshold, X, tmp)\n        if inplace:\n            X[:] = Y\n            return X\n        else:\n            return Y\n\n    def backprop_mish(\n        self,\n        dY: FloatsType,\n        X: Floats2d,\n        threshold: float = 20.0,\n        inplace: bool = False,\n    ) -> FloatsType:\n        if dY.shape != X.shape:\n            msg = f\"arrays have incompatible shapes: {dY.shape} and {X.shape}\"\n            raise ValueError(msg)\n\n        xp = get_array_module(X)\n        indices = X < threshold\n        Xsub = X[indices]\n        dYsub = dY[indices]\n        omega = 4.0 * (Xsub + 1.0)\n        omega += 4.0 * xp.exp(2.0 * Xsub)\n        omega += xp.exp(3.0 * Xsub)\n        omega += xp.exp(Xsub) * ((4.0 * Xsub) + 6.0)\n        delta = xp.exp(Xsub) + 1.0\n        delta *= delta\n        delta += 1.0\n        dXsub = dYsub * ((xp.exp(Xsub) * omega) / (delta**2))\n        # Gradient when above threshold will ignore softplus.\n        if inplace:\n            out = dY\n        else:\n            out = xp.copy(dY)\n        out[indices] = dXsub\n        return out\n\n    def update_averages(\n        self, ema: FloatsT, weights: FloatsT, t: int, max_decay: float = 0.9999\n    ) -> None:\n        # Internals for optimizer\n        decay = (1.0 + t) / (10.0 + t)\n        if decay > max_decay:\n            decay = max_decay\n        ema -= (1 - decay) * (ema - weights)\n\n    def adam(\n        self,\n        weights: Floats1d,\n        gradient: Floats1d,\n        mom1: Floats1d,\n        mom2: Floats1d,\n        beta1: float,\n        beta2: float,\n        eps: float,\n        learn_rate: float,\n        mod_rate: float = 1.0,\n    ) -> Tuple[Floats1d, Floats1d, Floats1d, Floats1d]:\n        # Internals for optimizer\n        mom1 *= beta1\n        mom2 *= beta2\n        mom1 += gradient * (1.0 - beta1)\n        mom2 += gradient * gradient * (1.0 - beta2)\n        # Here we assume learn rate is calculated by the caller.\n        # cdef weight_t a_t = learn_rate * sqrt(1-beta2**hp.t) / (1-beta1**hp.t);\n        weights -= learn_rate * (mom1 / (mod_rate * self.xp.sqrt(mom2) + eps))\n        return weights, gradient, mom1, mom2\n\n    def clip_gradient(self, gradient: FloatsT, threshold: float) -> FloatsT:\n        # Internals for optimizer\n        xp = get_array_module(gradient)\n        grad_norm = xp.linalg.norm(gradient)\n        if grad_norm >= threshold:\n            gradient *= threshold / grad_norm\n        return gradient\n\n    def logloss(self, y_true: FloatsT, y_pred: FloatsT) -> float:\n        # Currently not used\n        log_yp = self.xp.log(y_pred + 1e-8)\n        loss = (y_true * log_yp) + (1 - y_true) * self.xp.log((1 - y_pred) + 1e-8)\n        return -loss\n\n    def reduce_sum(self, X: Floats2d, lengths: Ints1d) -> Floats2d:\n        Y = self.alloc2f(lengths.shape[0], X.shape[1], zeros=False)\n        start = 0\n        for i, length in enumerate(lengths):\n            if length < 0:\n                raise ValueError(f\"all sequence lengths must be >= 0, got {length}\")\n            elif start + length > X.shape[0]:\n                raise IndexError(\"lengths must sum up to the number of rows\")\n            elif length:\n                Y[i] = X[start : start + length].sum(axis=0)\n                start += length\n            else:\n                Y[i] = 0.0\n        return Y\n\n    def reduce_mean(self, X: Floats2d, lengths: Ints1d) -> Floats2d:\n        Y = self.alloc2f(lengths.shape[0], X.shape[1], zeros=False)\n        start = 0\n        for i, length in enumerate(lengths):\n            if length < 0:\n                raise ValueError(f\"all sequence lengths must be >= 0, got {length}\")\n            elif start + length > X.shape[0]:\n                raise IndexError(\"lengths must sum up to the number of rows\")\n            elif length:\n                Y[i] = X[start : start + length].mean(axis=0)\n            else:\n                Y[i] = 0.0\n            start += length\n        return Y\n\n    def reduce_max(self, X: Floats2d, lengths: Ints1d) -> Tuple[Floats2d, Ints2d]:\n        Y = self.alloc2f(lengths.shape[0], X.shape[1], dtype=X.dtype, zeros=False)\n        which = self.alloc2i(lengths.shape[0], X.shape[1], zeros=False)\n        start = 0\n        for i, length in enumerate(lengths):\n            if length <= 0:\n                raise ValueError(f\"all sequence lengths must be > 0, got {length}\")\n            elif start + length > X.shape[0]:\n                raise IndexError(\"lengths must sum up to the number of rows\")\n            elif length:\n                which[i] = X[start : start + length].argmax(axis=0)\n                Y[i] = X[start : start + length].max(axis=0)\n            start += length\n        return Y, which\n\n    def backprop_reduce_sum(self, d_sums: Floats2d, lengths: Ints1d) -> Floats2d:\n        dX = self.alloc2f(\n            lengths.sum(), d_sums.shape[1], dtype=d_sums.dtype, zeros=False\n        )\n        start = 0\n        for i, length in enumerate(lengths):\n            if length < 0:\n                raise ValueError(f\"all sequence lengths must be >= 0, got {length}\")\n            dX[start : start + length] = d_sums[i]\n            start += length\n        return dX\n\n    def backprop_reduce_mean(self, d_means: Floats2d, lengths: Ints1d) -> Floats2d:\n        dX = self.alloc2f(\n            lengths.sum(), d_means.shape[1], dtype=d_means.dtype, zeros=False\n        )\n        start = 0\n        for i, length in enumerate(lengths):\n            if length < 0:\n                raise ValueError(f\"all sequence lengths must be >= 0, got {length}\")\n            dX[start : start + length] = d_means[i] / length\n            start += length\n        return dX\n\n    def backprop_reduce_max(\n        self, d_maxes: Floats2d, which: Ints2d, lengths: Ints1d\n    ) -> Floats2d:\n        dX = self.alloc2f(lengths.sum(), d_maxes.shape[1], dtype=d_maxes.dtype)\n        start = 0\n        for i, length in enumerate(lengths):\n            if length <= 0:\n                raise ValueError(f\"all sequence lengths must be > 0, got {length}\")\n\n            self.xp.put_along_axis(\n                dX[start : start + length], which[i].reshape((1, -1)), d_maxes[i], 0\n            )\n            start += length\n        return dX\n\n    def hash(self, ids: Ints1d, seed: int) -> Ints2d:\n        \"\"\"Hash a sequence of 64-bit keys into a table with 4 32-bit keys, using\n        murmurhash3.\n        \"\"\"\n        from .numpy_ops import NumpyOps\n\n        numpy_ops = NumpyOps()\n        return self.asarray2i(\n            numpy_ops.hash(numpy_ops.asarray(ids, dtype=\"uint64\"), seed)\n        )\n\n    def ngrams(self, n: int, keys: Ints1d) -> Ints1d:\n        from .numpy_ops import NumpyOps\n\n        numpy_ops = NumpyOps()\n        return self.asarray1i(\n            numpy_ops.ngrams(n, numpy_ops.asarray(keys, dtype=\"uint64\"))\n        )\n\n    def position_encode(\n        self, N: int, D: int, period: int = 10000, out: Optional[Floats2d] = None\n    ) -> Floats2d:\n        # Currently internals only\n        from .numpy_ops import NumpyOps\n\n        numpy_ops = NumpyOps()\n        return self.asarray2f(numpy_ops.position_encode(N, D, period, out))\n\n    def scatter_add(\n        self, table: FloatsXd, indices: IntsXd, values: FloatsXd\n    ) -> FloatsXd:\n        return self.xp.add.at(table, indices, values)\n\n    def insert_into(self, shape, Xs):\n        \"\"\"Maybe don't need this? Just a quicky to get Jax working.\"\"\"\n        output = self.alloc(shape, dtype=Xs[0].dtype)\n        for i, x in enumerate(Xs):\n            output[i, : x.shape[0]] = x\n        return output\n\n\n\"\"\"\nLSTM Notation (kind of involved, but made it a lot easier to write)\n\nX: Inputs\nY: Outputs (aka hiddens)\nC: Cells\nG: Gates (Output of non-linearity, i.e. lstm_gates(X @ W.T)\nA: Activations (X @ W.T, before non-linearity)\n\nImagine we have the input:\nbatch = [\n    [\"apple\", \"banana\", \"cantaloupe\", \"date\", \"elderberry\"],\n    [\"aardvark\", \"bat\", \"capybara\", \"dingo\", \"elephant\"]\n]\n\nThe input variable X will have one vector per word, so X[0, 1] will be banana's\nvector, X[0, 1, 0] will be a float, the first element of that vector.\n\nWe're computing an output variable Y of shape (nL, nB, nO), so that Y[0, 1] is\nthe output variable of banana.\n\nA problem with variables for RNNs is keeping the timesteps straight. It's hard\nto distinguish the current, previous, and next timesteps. To solve this problem,\nwe follow the convention that **we are at timestep 3**.\n\nAdditionally, the variables for Y and C are offset by one, as the 0th elements\nhave the initial hiddens and initial cells. So:\n\n    t=3\n    Xt3: The input vectors for 'dingo' and 'date', i.e. X[t]\n    Yt3: The output vectors for 'dingo' and 'date', i.e. Y[t+1] (Y is offset.)\n    Ct2: The cells calculated at 'c...', that are the input for 'd...'\n    Ct3: The cells calculated at 'd...', that are the input for 'e...'\n    At3: The activations at 'd...'\n    Gt3: The gates at 'd...'\n\"\"\"\n\n\ndef lstm_forward_training(\n    params: Floats1d, c_init: Floats3d, h_init: Floats3d, X: Floats2d, lengths: Ints1d\n) -> Tuple[Floats2d, Tuple]:\n    xp = get_array_module(params)\n    depth, dirs, nO = c_init.shape\n    N, nI = X.shape\n    batch_size = lengths[0]\n    # Preallocate these so we can pass them through for loop.\n    G = cast(Floats4d, xp.zeros((depth, dirs, X.shape[0], nO * 4), dtype=\"f\"))\n    Y = cast(Floats4d, xp.zeros((depth, dirs, X.shape[0], nO), dtype=\"f\"))\n    C = cast(Floats4d, xp.zeros((depth, dirs, X.shape[0], nO), dtype=\"f\"))\n    Yt2 = cast(Floats2d, xp.zeros((batch_size, nO), dtype=\"f\"))\n    Ct2 = cast(Floats2d, xp.zeros((batch_size, nO), dtype=\"f\"))\n    # Compute the start and end indices first.\n    indices = []\n    start = 0\n    for batch_size in lengths:\n        indices.append((start, start + batch_size))\n        start += batch_size\n    params_i = 0\n    orig_X = X\n    for i in range(depth):\n        nI = X.shape[1]\n        for d in range(dirs):\n            # The inits are shaped (depth, dirs, nO). We add the internal dimension\n            # to make them set correctly.\n            Yt2 = h_init[i, d].reshape((1, nO))  # type: ignore[assignment]\n            Ct2 = c_init[i, d].reshape((1, nO))  # type: ignore[assignment]\n            layer_params, params_i = _split_weights(params, i, nO, nI, params_i)\n            Wx, Wh, bias = _transpose_weights(layer_params)\n            G[i, d] += xp.dot(X, Wx.T)\n            G[i, d] += bias\n            for start, end in indices if d == 0 else reversed(indices):\n                # When we iterate left-to-right, t2 might be longer than t3.\n                Yt2 = Yt2[: end - start]\n                Ct2 = Ct2[: end - start]\n                # But in right-to-left, it's the opposite: t3 can be longer.\n                Gt3 = G[i, d, start:end]\n                Gt3 = Gt3[: Yt2.shape[0]]\n                Gt3 += xp.dot(Yt2, Wh.T)\n                Gt3_ = cast(Floats3d, Gt3.reshape((-1, nO, 4)))\n                hf = sigmoid(Gt3_[:, :, 0])\n                hi = sigmoid(Gt3_[:, :, 1])\n                ho = sigmoid(Gt3_[:, :, 2])\n                hc = xp.tanh(Gt3_[:, :, 3])\n                Ct3 = hf * Ct2\n                Ct3 += hi * hc\n                # Store results\n                Gt3 = (\n                    xp.hstack((hf, hi, ho, hc))\n                    .reshape((-1, 4, nO))\n                    .transpose((0, 2, 1))\n                    .reshape((-1, nO * 4))\n                )\n                # Fix the endpoint to account for shorter slices when iterating\n                # reversed. Not 100% sure this is right. If there's a bug, look\n                # here?\n                end = min(end, start + ho.shape[0])\n                Y[i, d, start:end] = xp.tanh(Ct3) * ho\n                G[i, d, start:end] = Gt3\n                C[i, d, start:end] = Ct3\n                # Set the t2 variables to the current t3 variables.\n                Ct2 = Ct3\n                Yt2 = Y[i, d, start:end]\n        H = cast(Floats2d, Y[i].transpose((1, 0, 2)).reshape((N, -1)))\n        if dirs == 2:\n            H = xp.ascontiguousarray(H)\n        X = H\n    return H, (Y, G, C, orig_X)\n\n\ndef backprop_lstm(dY: Floats2d, lengths: Ints1d, params: Floats1d, fwd_state: Tuple):\n    xp = get_array_module(params)\n\n    Y: Floats4d\n    G: Floats4d\n    C: Floats4d\n    X: Floats2d\n    Wx: Floats2d\n    Wh: Floats2d\n    bias: Floats1d\n    dWx: Floats2d\n    dWh: Floats2d\n    d_bias: Floats1d\n    Y, G, C, X = fwd_state\n    depth, dirs, N, nO = C.shape\n    nI = X.shape[1]\n    batch_size = lengths[0]\n    # We don't need to store all the cells for all the layers.\n    dC = cast(Floats2d, xp.zeros((N, nO), dtype=C.dtype))\n    dG = cast(Floats2d, xp.zeros((N, nO * 4), dtype=C.dtype))\n    d_params = cast(Floats1d, xp.zeros((params.shape[0],), dtype=params.dtype))\n    # Collect the params and slices. It makes it a bit easier to get the indexing\n    # right, when we're iterating backwards.\n    params_i = 0\n    all_layer_params: List[List[Tuple[Tuple[Floats2d, Floats2d, Floats1d], int]]] = []\n    for i in range(depth):\n        all_layer_params.append([])\n        n_inputs = nI if i == 0 else (nO * dirs)\n        for d in range(dirs):\n            layer_params, params_i = _split_weights(params, i, nO, n_inputs, params_i)\n            layer_params = _transpose_weights(layer_params)\n            all_layer_params[-1].append((layer_params, params_i))\n    params_i = 0\n    all_layer_grads: List[List[Tuple[Tuple[Floats2d, Floats2d, Floats1d], int]]] = []\n    for i in range(depth):\n        all_layer_grads.append([])\n        n_inputs = nI if i == 0 else (nO * dirs)\n        for d in range(dirs):\n            layer_grads, params_i = _split_weights(d_params, i, nO, n_inputs, params_i)\n            layer_grads = _transpose_weights(layer_grads)\n            all_layer_grads[-1].append((layer_grads, params_i))\n    # Similarly, we want to compute the indices first\n    indices = []\n    start = 0\n    for batch_size in lengths:\n        indices.append((start, start + batch_size))\n        start += batch_size\n\n    Xs = [X] + [\n        cast(Floats2d, Y[i].transpose((1, 0, 2)).reshape((N, -1)))\n        for i in range(depth - 1)\n    ]\n    dXs = [xp.zeros((X.shape[0], X.shape[1]), dtype=X.dtype) for X in Xs]\n    # Okay, now do the actual looping\n    for i in reversed(range(depth)):\n        dY3d = cast(Floats3d, dY.reshape((N, dirs, nO)).transpose((1, 0, 2)))\n        dX = dXs[i]\n        X = Xs[i]\n        if dirs >= 2:\n            dY3d = xp.ascontiguousarray(dY3d)\n        for d in range(dirs):\n            Wx, Wh, bias = all_layer_params[i][d][0]\n            dWx, dWh, d_bias = all_layer_grads[i][d][0]\n            if d == 0:\n                start_t3, end_t3 = indices[-1]\n                layer_indices = indices[:-1]\n                layer_indices.reverse()\n            else:\n                start_t3, end_t3 = indices[0]\n                layer_indices = indices[1:]\n            for start_t2, end_t2 in layer_indices:\n                size = min(end_t2 - start_t2, end_t3 - start_t3)\n                dGt3, dCt2 = backprop_lstm_gates(\n                    dY3d[d, start_t3 : start_t3 + size],\n                    dC[start_t3 : start_t3 + size],\n                    G[i, d, start_t3 : start_t3 + size],\n                    C[i, d, start_t3 : start_t3 + size],\n                    C[i, d, start_t2 : start_t2 + size],\n                )\n                # Backprop hidden-to-hidden w.r.t. hidden.\n                dY3d[d, start_t2 : start_t2 + size] += dGt3 @ Wh\n                # Update iteration variables\n                dC[start_t2 : start_t2 + size] = dCt2\n                start_t3 = start_t2\n                end_t3 = end_t2\n            # Backprop input-to-hidden w.r.t. weights.\n            dWx += dG.T @ X\n            # Backprop hidden-to-hidden w.r.t. weights.\n            dWh += dG.T @ Y[i, d]\n            # Backprop bias\n            d_bias += dG.sum(axis=0)\n            # Backprop input-to-hidden w.r.t. input\n            dX += dG @ Wx\n        dY = dX\n    assert dX.shape[1] == X.shape[1]\n    grad_parts = []\n    for layer_grads in all_layer_grads:\n        for dir_grads, _ in layer_grads:\n            grad_parts.append(_untranspose_unsplit_weights(dir_grads))\n    return dX, xp.concatenate(grad_parts)\n\n\ndef _split_weights(params: Floats1d, i: int, nO: int, nI: int, params_i: int):\n    Wx_size = 4 * nO * nI\n    bx_size = 4 * nO\n    Wh_size = 4 * nO * nO\n    bh_size = 4 * nO\n    Wx = params[params_i : params_i + Wx_size].reshape((4 * nO, nI))\n    params_i += Wx_size\n    bx = params[params_i : params_i + bx_size].reshape((4 * nO,))\n    params_i += bx_size\n    Wh = params[params_i : params_i + Wh_size].reshape((4 * nO, nO))\n    params_i += Wh_size\n    bh = params[params_i : params_i + bh_size].reshape((4 * nO,))\n    params_i += bh_size\n    return ((Wx, bx), (Wh, bh)), params_i\n\n\ndef _transpose_weights(params):\n    # Transpose the parameters so that the gates are the last dimension. This\n    # makes it easier to fuse.\n    (Wx, bx), (Wh, bh) = params\n    xp = get_array_module(Wx)\n    Wx = Wx.reshape((4, -1, Wx.shape[-1]))\n    Wx = Wx.transpose((1, 0, 2)).reshape((-1, Wx.shape[-1]))\n    bx = bx.reshape((4, -1)).transpose((1, 0)).reshape((-1,))\n    Wh = Wh.reshape((4, -1, Wh.shape[-1]))\n    Wh = Wh.transpose((1, 0, 2)).reshape((-1, Wh.shape[-1]))\n    bh = bh.reshape((4, -1)).transpose((1, 0)).reshape((-1,))\n    ascontig = xp.ascontiguousarray\n    Wx = ascontig(Wx)\n    Wh = ascontig(Wh)\n    bias = ascontig(bx) + bh\n    return Wx, Wh, bias\n\n\ndef _untranspose_unsplit_weights(params):\n    Wx, Wh, bias = params\n    xp = get_array_module(Wx)\n    nO = Wh.shape[1]\n    nI = Wx.shape[1]\n    Wx = Wx.reshape((-1, 4, nI)).transpose((1, 0, 2)).reshape((-1, nI))\n    Wh = Wh.reshape((-1, 4, nO)).transpose((1, 0, 2)).reshape((-1, nO))\n    bias = bias.reshape((-1, 4)).transpose((1, 0)).reshape((-1,))\n    zeros = xp.zeros(bias.shape, dtype=\"f\")\n    return xp.concatenate((Wx.ravel(), bias, Wh.ravel(), zeros))\n\n\ndef backprop_lstm_gates(\n    dYt3: Floats2d, dCt3: Floats2d, Gt3: Floats2d, Ct3: Floats2d, Ct2: Floats2d\n) -> Tuple[Floats2d, Floats2d]:\n    # See above for notation. Step numbering refers to forward_lstm_gates\n    xp = get_array_module(dYt3)\n    hf, hi, ho, hc = xp.split(Gt3, 4, axis=-1)\n    assert hf.shape[0] == hi.shape[0] == ho.shape[0] == hc.shape[0]\n    assert hf.shape[0] == dYt3.shape[0] == dCt3.shape[0] == Ct3.shape[0] == Ct2.shape[0]\n    tanhCt3 = xp.tanh(Ct3)\n    # 3b: Yt3 = tanhCt3 * ho\n    d_ho = dYt3 * tanhCt3\n    d_tanhCt3 = dYt3 * ho\n    # 3a: tanhCt3 = tanh(Ct3)\n    dCt3 += d_tanhCt3 * dtanh(tanhCt3)\n    # 2b: Ct3 += hi * hc\n    d_hi = dCt3 * hc\n    d_hc = dCt3 * hi\n    # 2a: Ct3 = hf * Ct2\n    d_hf = dCt3 * Ct2\n    dCt2 = dCt3 * hf\n    d_At3_hc = d_hc * dtanh(hc)  # 1d\n    d_At3_ho = d_ho * dsigmoid(ho)  # 1c\n    d_At3_hi = d_hi * dsigmoid(hi)  # 1b\n    d_At3_hf = d_hf * dsigmoid(hf)  # 1a\n    dAt3 = xp.concatenate((d_At3_hf, d_At3_hi, d_At3_ho, d_At3_hc), axis=-1)\n    return dAt3, dCt2\n\n\ndef sigmoid(X, out=None):\n    xp = get_array_module(X)\n\n    # To prevent overflows and help with regularization/numerical stability\n    X = xp.clip(X, -20.0, 20.0)\n    return 1.0 / (1.0 + xp.exp(-X))\n\n\ndef dsigmoid(Y: ArrayT) -> ArrayT:\n    return Y * (1.0 - Y)\n\n\ndef dtanh(Y: ArrayT) -> ArrayT:\n    return 1 - Y**2\n\n\ndef gaussian_cdf(ops: Ops, X: FloatsType) -> FloatsType:\n    \"\"\"Gaussian CDF for distribution with mean 0 and stdev 1.\"\"\"\n    return 0.5 * (1.0 + ops.erf(INV_SQRT2 * X))\n\n\ndef gaussian_pdf(ops: Ops, X: FloatsType) -> FloatsType:\n    \"\"\"Gaussian PDF for distribution with mean 0 and stdev 1.\"\"\"\n    return INV_SQRT_2PI * ops.xp.exp(-0.5 * X * X)\n", "meta": {"hexsha": "315b0b0bf58466933a5af3053d77ede1f8e75c78", "size": 55329, "ext": "py", "lang": "Python", "max_stars_repo_path": "thinc/backends/ops.py", "max_stars_repo_name": "richardpaulhudson/thinc", "max_stars_repo_head_hexsha": "a9b047121e1ddca30fd9fc6c78cb853084ea6e78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thinc/backends/ops.py", "max_issues_repo_name": "richardpaulhudson/thinc", "max_issues_repo_head_hexsha": "a9b047121e1ddca30fd9fc6c78cb853084ea6e78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thinc/backends/ops.py", "max_forks_repo_name": "richardpaulhudson/thinc", "max_forks_repo_head_hexsha": "a9b047121e1ddca30fd9fc6c78cb853084ea6e78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3088704531, "max_line_length": 88, "alphanum_fraction": 0.5585859134, "include": true, "reason": "import numpy", "num_tokens": 16254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.1875900622724822}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov  1 14:27:54 2018\n\n@author: dkorff\n\"\"\"\n\nimport numpy as np\nimport cantera as ct\n\nclass Inputs():\n    # These flags specify whether to include each element (anode, separator,\n    #   cathode) in the simulation:\n    flag_anode = 1\n    flag_sep = 1\n    flag_cathode = 0\n\n    # The C-rate is the rate of charge/discharge - how many charges/discharges\n    #   can be carried out in 1 hour? This sets the current density:\n    C_rate = 1\n\n    # Simulation temperature (or initial temperature)\n    T = 300  # [K]\n\n    # Set initial SOC to generalize both electrode initial lithiation\n    # Fully charged = anode fully lithiated, cathode fully de-lithiated.\n    SOC_0 = 0.98\n\n    # Number of discretized volumes in the y-direction:\n    npoints_anode = 5\n    npoints_cathode = 5\n    npoints_elyte = 2\n\n    # Number of \"shells\" in anode particle:\n    nshells_anode = 5\n    n_shells_cathode = 5\n\n    \"Cantera and CTI file info:\"\n    ctifile = 'lithium_ion_battery.cti'\n    anode_phase = 'anode'\n    cathode_phase = 'cathode'\n    metal_phase = 'electron'\n    elyte_phase = 'electrolyte'\n    anode_surf_phase = 'edge_anode_electrolyte'\n    cathode_surf_phase = 'edge_cathode_electrolyte'\n\n    Li_species_anode = 'Li[anode]'\n    Vac_species_anode = 'V[anode]'\n    Li_species_cathode = 'Li[cathode]'\n    Vac_species_cathode = 'V[cathode]'\n\n    Phi_anode_init = 0.0\n    Phi_elyte_init = 4.0\n    Delta_Phi_init = 4.0\n\n    # Cutoff Values for lithiation and delithiation of anode:\n    SOC_max = 1 - 1e-2\n    SOC_min = 1 - SOC_max\n\n    \"Anode geometry and transport\"\n    # Microstructure\n    eps_solid_an = 0.6        # Graphite volume fraction [-]\n    tau_an = 1.6        # Tortuosity - assume equal values for carbon and elyte [-]\n    r_p_an = 5e-6       # Average pore radius [m]\n    d_part_an = 5e-6    # Average particle diameter for graphite [m]\n    overlap_an = 0.4    # Percentage of anode particle overlapping with other\n                        #   anode particles.  Reduces total anode/elyte\n                        #   surface area.\n    H_an = 50e-6        # Anode thickness [m]\n\n    # Other Parameters\n    C_dl_an = 1.5e-2    # Double-layer capacitance [F/m^2]\n    sigma_an = 75.0     # Bulk anode electrical conductivity [S/m]\n\n    D_Li_an = 7.5e-16   # Bulk diffusion coefficient for Li in graphite [m^2/s]\n\n    \"Electrolyte geometry and transport\"\n    # Separator thickness [m]\n    H_elyte = 100e-6\n    # Elyte species bulk diffusion coefficients [m^2/s]\n    D_Li_elyte = np.array([1e-12, 1e-12, 1e-10, 3e-11])\n    z_k_elyte = np.array([0., 0., 1., -1.])\n\n    eps_elyte_sep = 0.85      # Separator electrolyte volume fraction\n    tau_sep = 1.6  # Tortuosity of separator\n    sigma_sep = 50.0  # Bulk ionic conductivity of separator [S/m]\n\n    \"Cathode geometry and transport\"\n    # Microstructure:\n    eps_solid_ca = 0.5  # LiCoO2 volume fraction [-]\n    tau_ca = 1.6  # Tortuosity - assume equal values for LiCoO2 and elyte [-]\n    r_p_ca = 5e-6     # Average pore radius [m]\n    d_part_ca = 30e-6  # Average particle diameter for LiCoO2 [m]\n    overlap_ca = 0.4    # Percentage of anode particle overlapping with other\n                        #   anode particles.  Reduces total anode/elyte\n                        #   surface area.\n    H_ca = 30e-6      # Cathode thickness [m]\n\n    # Other parameters:\n    C_dl_ca = 1.5       # Double-layer capacitance [F/m^2]\n    sigma_ca = 7.50    # Bulk cathode electrical conductivity [S/m]\n    D_Li_ca = 7.5e-16  # Bulk diffusion coefficient for Li in LiCoO2 [m^2/s]\n", "meta": {"hexsha": "c9d185198a25236d4b6e791c86ba3a3a94d25607", "size": 3551, "ext": "py", "lang": "Python", "max_stars_repo_path": "li_ion_battery_p2d_inputs.py", "max_stars_repo_name": "coresresearch/p2d_li_ion_battery", "max_stars_repo_head_hexsha": "7ea1a2332eb885bea65e47e82ea231f80d28ca18", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-02-05T04:53:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T01:50:51.000Z", "max_issues_repo_path": "li_ion_battery_p2d_inputs.py", "max_issues_repo_name": "coresresearch/p2d_li_ion_battery", "max_issues_repo_head_hexsha": "7ea1a2332eb885bea65e47e82ea231f80d28ca18", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "li_ion_battery_p2d_inputs.py", "max_forks_repo_name": "coresresearch/p2d_li_ion_battery", "max_forks_repo_head_hexsha": "7ea1a2332eb885bea65e47e82ea231f80d28ca18", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-03-21T21:06:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-05T09:06:15.000Z", "avg_line_length": 34.4757281553, "max_line_length": 83, "alphanum_fraction": 0.6437623205, "include": true, "reason": "import numpy", "num_tokens": 1117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.36658974324230986, "lm_q1q2_score": 0.18759005873132656}}
{"text": "# Taku Ito\n# 3/18/2019\n# General object to run empirical sr actflow process\n# For group-level/cross-subject analyses\n\nimport numpy as np\nimport os\nimport multiprocessing as mp\nimport scipy.stats as stats\nimport nibabel as nib\nimport os\nos.environ['OMP_NUM_THREADS'] = str(1)\nimport sklearn\nfrom scipy import signal\nimport h5py\nimport sys\nsys.path.append('glmScripts/')\nimport glmScripts.taskGLMPipeline_v2 as tgp\nimport sys\nimport pandas as pd\nimport pathlib\nimport calculateFC as fc\nimport tools\n\n# Using final partition\nnetworkdef = np.loadtxt('/home/ti61/f_mc1689_1/NetworkDiversity/data/network_partition.txt')\nnetworkorder = np.asarray(sorted(range(len(networkdef)), key=lambda k: networkdef[k]))\nnetworkorder.shape = (len(networkorder),1)\n# network mappings for final partition set\nnetworkmappings = {'fpn':7, 'vis1':1, 'vis2':2, 'smn':3, 'aud':8, 'lan':6, 'dan':5, 'con':4, 'dmn':9, \n                           'pmulti':10, 'none1':11, 'none2':12}\nnetworks = networkmappings.keys()\n\n## General parameters/variables\nnParcels = 360\n\n\n\nclass Model():\n    \"\"\"\n    Class to perform empirical actflow for a given subject (stimulus-to-response)\n    \"\"\"\n    def __init__(self,projectdir='/home/ti61/f_mc1689_1/SRActFlow/',ruletype='12',n_hiddenregions=10,randomize=False,scratchfcdir=None):\n        \"\"\"\n        instantiate:\n            indices for condition types\n            indices for specific condition instances\n            betas\n        \"\"\"\n        #### Set up basic model parameters\n        self.projectdir = projectdir\n        # Excluding 084\n        self.subjNums = ['013','014','016','017','018','021','023','024','026','027','028','030','031','032','033',\n                         '034','035','037','038','039','040','041','042','043','045','046','047','048','049','050',\n                         '053','055','056','057','058','062','063','066','067','068','069','070','072','074','075',\n                         '076','077','081','085','086','087','088','090','092','093','094','095','097','098','099',\n                         '101','102','103','104','105','106','108','109','110','111','112','114','115','117','119',\n                         '120','121','122','123','124','125','126','127','128','129','130','131','132','134','135',\n                         '136','137','138','139','140','141']\n\n        self.inputtypes = ['RED','VERTICAL','CONSTANT','HIGH']\n        self.ruletype = ruletype\n        #### Load in atlas\n        glasserfile2 = projectdir + 'data/Q1-Q6_RelatedParcellation210.LR.CorticalAreas_dil_Colors.32k_fs_RL.dlabel.nii'\n        glasser2 = nib.load(glasserfile2).get_data()\n        glasser2 = np.squeeze(glasser2)\n        self.glasser2 = glasser2\n\n\n        #### \n        # Define hidden units\n        if n_hiddenregions!=None:\n            #######################################\n            #### Select hidden layer regions\n            hiddendir = projectdir + 'data/results/MAIN/RSA/'\n            hiddenregions = np.loadtxt(hiddendir + 'RSA_Similarity_SortedRegions2.txt',delimiter=',')\n\n            #######################################\n            #### Output directory\n            if randomize:\n                print(\"Constructing model with\", n_hiddenregions, \"randomly selected hidden regions\")\n                fcdir = scratchfcdir \n                #### Necessary to optimize amarel\n                pathlib.Path(fcdir).mkdir(parents=True, exist_ok=True) # Make sure directory exists\n                hiddenregions = np.random.choice(hiddenregions,size=n_hiddenregions,replace=False)\n            else:\n                print(\"Constructing model with\", n_hiddenregions, \"hidden regions\")\n                fcdir = projectdir + 'data/results/MAIN/fc/LayerToLayerFC_' + str(n_hiddenregions) + 'Hidden/'\n                pathlib.Path(fcdir).mkdir(parents=True, exist_ok=True) # Make sure directory exists\n                # Select hidden layer\n                if n_hiddenregions < 0:\n                    hiddenregions = hiddenregions[n_hiddenregions:]\n                else:\n                    hiddenregions = hiddenregions[:n_hiddenregions]\n\n            ## Set object attributes\n            self.n_hiddenregions = n_hiddenregions\n            self.hiddenregions = np.squeeze(hiddenregions)\n            self.fcdir = fcdir\n            self.hidden = True # Set this variable to true - indicates to run sr simulations with a hidden layer\n\n            #### identify hidden region vertex indices\n            hidden_ind = []\n            for roi in hiddenregions:\n                hidden_ind.extend(np.where(self.glasser2==roi+1)[0])\n            self.hidden_ind = hidden_ind\n        else:\n            print(\"Constructing model with NO hidden layers\")\n            fcdir = projectdir + 'data/results/MAIN/fc/LayerToLayerFC_NoHidden/'\n            pathlib.Path(fcdir).mkdir(parents=True, exist_ok=True) # Make sure directory exists\n            self.hidden = False # Set this variable to true - indicates to run sr simulations with a hidden layer\n            self.fcdir = fcdir\n            self.hiddenregions = None\n            self.n_hiddenregions = n_hiddenregions\n\n        ####\n        # Define task rule (input) layer\n        ruledir = self.projectdir + 'data/results/MAIN/RuleDecoding/'\n        if ruletype=='12':\n            rule_regions = np.loadtxt(ruledir + self.ruletype + 'Rule_Regions.csv',delimiter=',')\n        elif ruletype=='fpn':\n            rule_regions = []\n            rule_regions.extend(np.where(networkdef==networkmappings['fpn'])[0])\n            rule_regions = np.asarray(rule_regions)\n        elif ruletype=='nounimodal':\n            allrule_regions = np.loadtxt(ruledir + '12Rule_Regions.csv',delimiter=',')\n            unimodal_nets = ['vis1','aud']\n            unimodal_regions = []\n            for net in unimodal_nets:\n                unimodal_regions.extend(np.where(networkdef==networkmappings[net])[0])\n            # only include regions that are in allrule_regions but also NOT in unimodal_regions\n            rule_regions = []\n            for roi in allrule_regions:\n                if roi in unimodal_regions:\n                    continue\n                else:\n                    rule_regions.append(roi)\n            rule_regions = np.asarray(rule_regions)\n\n\n        rule_ind = []\n        for roi in rule_regions:\n            rule_ind.extend(np.where(self.glasser2==roi+1)[0])\n        self.rule_ind = rule_ind\n\n        #### \n        # Define motor regions\n        # Set indices for layer-by-layer vertices\n        targetdir = projectdir + 'data/results/MAIN/MotorResponseDecoding/'\n        motor_resp_regions_LH = np.loadtxt(targetdir + 'MotorResponseRegions_LH.csv',delimiter=',')\n        motor_resp_regions_RH = np.loadtxt(targetdir + 'MotorResponseRegions_RH.csv',delimiter=',')\n        targetROIs = np.hstack((motor_resp_regions_LH,motor_resp_regions_RH))\n\n        # Define all motor_ind\n        motor_ind = []\n        for roi in targetROIs:\n            roi_ind = np.where(glasser2==roi+1)[0]\n            motor_ind.extend(roi_ind)\n\n        motor_ind = np.asarray(motor_ind).copy()\n        self.motor_ind = motor_ind\n\n        #### override -- only pick the motor parcel with the greatest response decoding\n        \n        motor_ind_lh = []\n        for roi in motor_resp_regions_LH:\n            # only include left hand responses in the right hemisphere\n            if roi>=180:\n                roi_ind = np.where(glasser2==roi+1)[0]\n                motor_ind_lh.extend(roi_ind)\n\n        motor_ind_rh = []\n        for roi in motor_resp_regions_RH:\n            # only include left hand responses in the right hemisphere\n            if roi<180:\n                roi_ind = np.where(glasser2==roi+1)[0]\n                motor_ind_rh.extend(roi_ind)\n\n        # \n        motor_ind_rh = np.asarray(motor_ind_rh).copy()\n        motor_ind_lh = np.asarray(motor_ind_lh).copy()\n        self.motor_ind_rh = motor_ind_rh\n        self.motor_ind_lh = motor_ind_lh\n\n        #### Load model task set\n        filename= projectdir + 'data/results/MAIN/EmpiricalSRActFlow_AllTrialKeys_15stims_v3.csv' # Great\n        self.trial_metadata = pd.read_csv(filename)\n\n    def computeGroupFC(self,n_components=500,nproc='max'):\n        \"\"\"\n        Function that wraps _computeSubjFC() to compute FC for all subjs, and computes averaged groupFC\n        \"\"\" \n        if nproc=='max':\n            nproc=mp.cpu_count()\n\n        inputs = []\n        for subj in self.subjNums:\n            inputs.append((subj,n_components))\n\n        pool = mp.Pool(processes=nproc)\n        if self.hidden:\n            pool.starmap_async(self._computeSubjFC,inputs)\n        else:\n            pool.starmap_async(self._computeSubjFC_NoHidden,inputs)\n        pool.close()\n        pool.join()\n\n        #### Compute group FC\n        for inputtype in self.inputtypes:\n            if self.hidden:\n                fc.computeGroupFC(inputtype,self.fcdir)\n            else:\n                fc.computeGroupFC_NoHidden(inputtype,self.fcdir)\n        if self.hidden:\n            fc.computeGroupFC(self.ruletype,self.fcdir)\n        else:\n            fc.computeGroupFC_NoHidden(self.ruletype,self.fcdir)\n\n    def loadRealMotorResponseActivations(self,vertexmasks=True):\n        #### Load motor response activations localized in output vertices only (for faster loading)\n        if vertexmasks:\n            print('Load real motor responses in output vertices')\n            self.data_task_rh, self.data_task_lh = tools.loadMotorResponsesOutputMask()\n        else:\n            print('Load real motor responses in output parcels -- inefficient since need to load all vertices first')\n            data_task_rh = []\n            data_task_lh = []\n            for subj in self.subjNums:\n                tmp_rh = tools.loadMotorResponses(subj,hand='Right')\n                tmp_lh = tools.loadMotorResponses(subj,hand='Left')\n                data_task_rh.append(tmp_rh[self.motor_ind_rh,:].copy().T)\n                data_task_lh.append(tmp_lh[self.motor_ind_lh,:].copy().T)\n            self.data_task_rh = np.asarray(data_task_rh).T\n            self.data_task_lh = np.asarray(data_task_lh).T\n\n    def loadModelFC(self):\n        if self.hidden:\n            print('Load Model FC weights')\n            fcdir = self.fcdir\n\n            self.fc_input2hidden = {}\n            self.eig_input2hidden = {}\n            for inputtype in ['VERTICAL','RED','HIGH','CONSTANT']:\n                self.fc_input2hidden[inputtype], self.eig_input2hidden[inputtype] = tools.loadGroupActFlowFC(inputtype,fcdir)\n\n            # Load rule to hidden\n            self.fc_12rule2hidden, self.eig_12rule2hidden = tools.loadGroupActFlowFC(self.ruletype,fcdir)\n            # Load hidden to motor resp mappings\n            self.fc_hidden2motorresp, self.eig_hidden2motorresp = tools.loadGroupActFlowFC('hidden2out',fcdir)\n        else:\n            print('Load Model FC weights -- No hidden layer')\n            fcdir = self.fcdir\n\n            self.fc_input2output = {}\n            self.eig_input2output = {}\n            for inputtype in ['VERTICAL','RED','HIGH','CONSTANT']:\n                self.fc_input2output[inputtype], self.eig_input2output[inputtype] = tools.loadGroupActFlowFC_NoHidden(inputtype,fcdir)\n\n            # Load rule to hidden\n            self.fc_12rule2output, self.eig_12rule2output = tools.loadGroupActFlowFC_NoHidden('12',fcdir)\n\n    def simulateGroupActFlow(self,thresh=0,nproc='max',vertexmasks=True):\n        \"\"\"\n        Simulate group level actflow (all subject simulations)\n        \"\"\"\n        \n        if nproc=='max':\n            nproc=mp.cpu_count()\n\n        inputs = []\n        for subj in self.subjNums:\n            inputs.append((subj,thresh))\n        \n        if nproc == 1:\n            results = []\n            for input1 in inputs:\n                results.append(self._simulateSubjActFlow(input1[0],input1[1]))\n        else:\n            pool = mp.Pool(processes=nproc)\n            results = pool.starmap_async(self._simulateSubjActFlow,inputs).get()\n            pool.close()\n            pool.join()\n\n        actflow_predictions = np.zeros((len(self.subjNums),len(self.motor_ind),4))\n        #actflow_predictions_noReLU = np.zeros((len(self.subjNums),len(self.motor_ind),4))\n        scount = 0\n        for result in results:\n        #    actflow_predictions[scount,:,:] = result[0]\n        #    actflow_predictions_noReLU[scount,:,:] = result[1]\n            actflow_predictions[scount,:,:] = result\n            scount += 1\n\n        ## Reformat to fit shape of actual data array\n        actflow_rh = np.zeros((len(self.glasser2),2,len(self.subjNums)))\n        actflow_lh = np.zeros((len(self.glasser2),2,len(self.subjNums)))\n        for scount in range(len(self.subjNums)):\n            # RMID\n            actflow_rh[self.motor_ind,0,scount] = actflow_predictions[scount,:,2]\n            # RIND\n            actflow_rh[self.motor_ind,1,scount] = actflow_predictions[scount,:,3]\n            # LMID\n            actflow_lh[self.motor_ind,0,scount] = actflow_predictions[scount,:,0]\n            # LIND\n            actflow_lh[self.motor_ind,1,scount] = actflow_predictions[scount,:,1]\n\n        #### Now save out only relevant output mask vertices\n        if vertexmasks:\n            tmp = np.squeeze(nib.load(self.projectdir + 'data/results/MAIN/MotorRegionsMasksPerSubj/sractflow_smn_outputRH_mask.dscalar.nii').get_data())\n            rh_ind = np.where(tmp==True)[0]\n            actflow_rh = actflow_rh[rh_ind,:,:]\n\n            tmp = np.squeeze(nib.load(self.projectdir + 'data/results/MAIN/MotorRegionsMasksPerSubj/sractflow_smn_outputLH_mask.dscalar.nii').get_data())\n            lh_ind = np.where(tmp==True)[0]\n            actflow_lh = actflow_lh[lh_ind,:,:].copy()\n        else:\n            actflow_rh = actflow_rh[self.motor_ind_rh,:,:].copy()\n            actflow_lh = actflow_lh[self.motor_ind_lh,:,:].copy()\n\n        return actflow_rh, actflow_lh\n\n    def actflowDecoding(self,trainset,testset,outputfile,\n                        nbootstraps=1000,featsel=False,nproc='max',null=False,verbose=True):\n        if nproc=='max':\n            nproc=mp.cpu_count()\n\n        # Decoding\n        for i in range(nbootstraps):\n            distances_baseline = np.zeros((1,len(self.subjNums)*2)) # subjs * nlabels\n            distances_baseline[0,:],rmatch,rmismatch, confusion_mats = tools.actflowDecodings(testset,trainset,\n                                                                                              effects=True, featsel=featsel,confusion=True,permutation=null,\n                                                                                              ncvs=1, nproc=nproc)\n\n            ##### Save out and append file\n            # Open/create file\n            filetxt = open(outputfile,\"a+\")\n            # Write out to file\n            print(np.mean(distances_baseline),file=filetxt)\n            # Close file\n            filetxt.close()\n            \n            if i%100==0 and verbose==True:\n                print('Permutation', i)\n                print('\\tDecoding accuracy:', np.mean(distances_baseline), '| R-match:', np.mean(rmatch), '| R-mismatch:', np.mean(rmismatch))\n\n    def extractSubjActivations(self, subj, df_trials):\n        \"\"\"\n        extract activations for a sample subject, including motor response\n        \"\"\"\n\n        ## Set up data parameters\n        X = tgp.loadTaskTiming(subj,'ALL')\n        self.stimIndex = np.asarray(X['stimIndex'])\n        self.stimCond = np.asarray(X['stimCond'])\n\n        datadir = self.projectdir + 'data/postProcessing/hcpPostProcCiric/'\n        h5f = h5py.File(datadir + subj + '_glmOutput_data.h5','r')\n        self.betas = h5f['taskRegression/ALL_24pXaCompCorXVolterra_taskReg_betas_canonical'][:].copy()\n        h5f.close()\n\n        ## Set up task parameters\n        self.logicRules = ['BOTH', 'NOTBOTH', 'EITHER', 'NEITHER']\n        self.sensoryRules = ['RED', 'VERTICAL', 'HIGH', 'CONSTANT']\n        self.motorRules = ['LMID', 'LIND', 'RMID', 'RIND']\n        self.colorStim = ['RED', 'BLUE']\n        self.oriStim = ['VERTICAL', 'HORIZONTAL']\n        self.pitchStim = ['HIGH', 'LOW']\n        self.constantStim = ['CONSTANT','ALARM']\n\n\n        # Begin extraction for specific trials\n        n_trials = len(df_trials)\n        \n        stimData = np.zeros((n_trials,self.betas.shape[0]))\n        logicRuleData = np.zeros((n_trials,self.betas.shape[0]))\n        sensoryRuleData = np.zeros((n_trials,self.betas.shape[0]))\n        motorRuleData = np.zeros((n_trials,self.betas.shape[0]))\n        respData = np.zeros((n_trials,self.betas.shape[0]))\n        sensoryRuleIndices = []\n        motorRespAll = []\n        \n        for trial in range(n_trials):\n            logicRule = df_trials.iloc[trial].logicRule\n            sensoryRule = df_trials.iloc[trial].sensoryRule\n            motorRule = df_trials.iloc[trial].motorRule\n            motorResp = df_trials.iloc[trial].motorResp\n            stim1 = df_trials.iloc[trial].stim1\n            stim2 = df_trials.iloc[trial].stim2\n\n#                        if verbose:\n#                            print 'Running actflow predictions for:', logicRule, sensoryRule, motorRule, 'task'\n\n            logicKey = 'RuleLogic_' + logicRule\n            sensoryKey = 'RuleSensory_' + sensoryRule\n            motorKey = 'RuleMotor_' + motorRule\n            stimKey = 'Stim_' + stim1 + stim2\n            motorResp = solveInputs(logicRule, sensoryRule, motorRule, stim1, stim2, printTask=False)\n            respKey = 'Response_' + motorResp\n\n\n            stimKey_ind = np.where(self.stimCond==stimKey)[0]\n            logicRule_ind = np.where(self.stimCond==logicKey)[0]\n            sensoryRule_ind = np.where(self.stimCond==sensoryKey)[0]\n            motorRule_ind = np.where(self.stimCond==motorKey)[0]\n            respKey_ind = np.where(self.stimCond==respKey)[0]\n\n\n            stimData[trial,:] = np.real(self.betas[:,stimKey_ind].copy()[:,0])\n            logicRuleData[trial,:] = np.real(self.betas[:,logicRule_ind].copy()[:,0])\n            sensoryRuleData[trial,:] = np.real(self.betas[:,sensoryRule_ind].copy()[:,0])\n            motorRuleData[trial,:] = np.real(self.betas[:,motorRule_ind].copy()[:,0])\n            respData[trial,:] = np.real(self.betas[:,respKey_ind].copy()[:,0])\n                        \n            motorRespAll.append(motorResp)\n            sensoryRuleIndices.append(sensoryRule)\n\n        self.motorRespAll = motorRespAll\n        self.stimData = stimData\n        self.logicRuleData = logicRuleData\n        self.sensoryRuleData = sensoryRuleData\n        self.motorRuleData = motorRuleData\n        self.respData = respData\n        self.sensoryRuleIndices = sensoryRuleIndices\n\n    def extractSubjHiddenRSMActivations(self, subj):\n        \"\"\"\n        extract activations for a sample subject, including motor response\n        \"\"\"\n\n        ## Set up data parameters\n        X = tgp.loadTaskTiming(subj,'ALL')\n        self.stimIndex = np.asarray(X['stimIndex'])\n        self.stimCond = np.asarray(X['stimCond'])\n\n        datadir = self.projectdir + 'data/postProcessing/hcpPostProcCiric/'\n        h5f = h5py.File(datadir + subj + '_glmOutput_data.h5','r')\n        self.betas = h5f['taskRegression/ALL_24pXaCompCorXVolterra_taskReg_betas_canonical'][:].copy()\n        h5f.close()\n\n        ## Set up task parameters\n        self.logicRules = ['BOTH', 'NOTBOTH', 'EITHER', 'NEITHER']\n        self.sensoryRules = ['RED', 'VERTICAL', 'HIGH', 'CONSTANT']\n        self.motorRules = ['LMID', 'LIND', 'RMID', 'RIND']\n        self.colorStim = ['RED', 'BLUE']\n        self.oriStim = ['VERTICAL', 'HORIZONTAL']\n        self.pitchStim = ['HIGH', 'LOW']\n        self.constantStim = ['CONSTANT','ALARM']\n\n        total_conds = 28 # 12 rules + 16 stimulus pairings\n        rsm_activations = np.zeros((28,self.betas.shape[0]))\n        labels = []\n        condcount = 0\n        ## \n        # START\n        for cond in self.logicRules:\n            labels.append(cond)\n            key = 'RuleLogic_' + cond\n            ind = np.where(self.stimCond==key)[0]\n            rsm_activations[condcount,:] = np.real(self.betas[:,ind].copy()[:,0])\n            condcount += 1 # go to next condition\n\n        for cond in self.sensoryRules:\n            labels.append(cond)\n            key = 'RuleSensory_' + cond\n            ind = np.where(self.stimCond==key)[0]\n            rsm_activations[condcount,:] = np.real(self.betas[:,ind].copy()[:,0])\n            condcount += 1 # go to next condition\n\n        for cond in self.motorRules:\n            labels.append(cond)\n            key = 'RuleMotor_' + cond\n            ind = np.where(self.stimCond==key)[0]\n            rsm_activations[condcount,:] = np.real(self.betas[:,ind].copy()[:,0])\n            condcount += 1 # go to next condition\n\n\n        # This is nested for loop since stimuli come in pairs\n        for cond1 in self.colorStim:\n            for cond2 in self.colorStim:\n                labels.append(cond1 + cond2)\n                key = 'Stim_' + cond1 + cond2\n                ind = np.where(self.stimCond==key)[0]\n                rsm_activations[condcount,:] = np.real(self.betas[:,ind].copy()[:,0])\n                condcount += 1 # go to next condition\n\n        for cond1 in self.oriStim:\n            for cond2 in self.oriStim:\n                labels.append(cond1 + cond2)\n                key = 'Stim_' + cond1 + cond2\n                ind = np.where(self.stimCond==key)[0]\n                rsm_activations[condcount,:] = np.real(self.betas[:,ind].copy()[:,0])\n                condcount += 1 # go to next condition\n\n        for cond1 in self.pitchStim:\n            for cond2 in self.pitchStim:\n                labels.append(cond1 + cond2)\n                key = 'Stim_' + cond1 + cond2\n                ind = np.where(self.stimCond==key)[0]\n                rsm_activations[condcount,:] = np.real(self.betas[:,ind].copy()[:,0])\n                condcount += 1 # go to next condition\n\n        for cond1 in self.constantStim:\n            for cond2 in self.constantStim:\n                labels.append(cond1 + cond2)\n                key = 'Stim_' + cond1 + cond2\n                ind = np.where(self.stimCond==key)[0]\n                rsm_activations[condcount,:] = np.real(self.betas[:,ind].copy()[:,0])\n                condcount += 1 # go to next condition\n\n        return rsm_activations, labels\n\n    def generateHiddenUnitRSMPredictions(self,thresh=0,n_hiddenregions=10,filename='',verbose=False):\n        \"\"\"\n        Run all predictions for all 64 tasks\n        \"\"\"\n        hidden_ind = self.hidden_ind\n        rule_ind = self.rule_ind\n\n        all_actflow_unthresh = []\n        all_actflow_thresh = []\n        all_true_activity = []\n        for subj in self.subjNums:\n            print('Predicting hidden layer activations for subject', subj)\n            rsm_activations, labels = self.extractSubjHiddenRSMActivations(subj)\n            \n            tmp_actflow_unthresh = []\n            tmp_actflow_thresh = []\n            tmp_true_activity = []\n            labelcount = 0\n            for label in labels:\n                # Dissociate sensory rules from sensory stimuli since stimuli have two stimulus words (e.g., 'REDRED')\n                if label in ['BOTH', 'NOTBOTH', 'EITHER', 'NEITHER', 'RED', 'VERTICAL', 'HIGH', 'CONSTANT', 'LMID', 'LIND', 'RMID', 'RIND']:\n                    input_units = 'rule'\n                if label in ['REDRED', 'REDBLUE', 'BLUERED', 'BLUEBLUE']:\n                    input_units = 'RED' # specify sensory rules for sensory activations\n                if label in ['VERTICALVERTICAL', 'VERTICALHORIZONTAL', 'HORIZONTALVERTICAL', 'HORIZONTALHORIZONTAL']:\n                    input_units = 'VERTICAL' # this is the sensory rule\n                if label in ['HIGHHIGH', 'HIGHLOW', 'LOWHIGH', 'LOWLOW']:\n                    input_units = 'HIGH'\n                if label in ['CONSTANTCONSTANT', 'CONSTANTALARM', 'ALARMCONSTANT', 'ALARMALARM']:\n                    input_units = 'CONSTANT'\n\n                if input_units!='rule':\n                    input_ind = self._getStimIndices(input_units) # Identify the vertices for stimulus layer of the ANN \n                    unique_input_ind = np.where(np.in1d(input_ind,hidden_ind)==False)[0]\n\n                    fc = self.fc_input2hidden[input_units]\n                    pc_act = np.matmul(rsm_activations[labelcount,:][unique_input_ind],self.eig_input2hidden[input_units].T)\n                    # Unthresholded actflow\n                    actflow_unthresh = np.matmul(pc_act,fc) \n                    # Thresholded actflow\n                    actflow_thresh = np.multiply(actflow_unthresh,actflow_unthresh>thresh)\n\n                if input_units=='rule':\n                    unique_input_ind = np.where(np.in1d(rule_ind,hidden_ind)==False)[0]\n                    fc = self.fc_12rule2hidden\n                    pc_act = np.matmul(rsm_activations[labelcount,:][unique_input_ind],self.eig_12rule2hidden.T)\n                    # Unthresholded actflow\n                    actflow_unthresh = np.matmul(pc_act,fc) \n                    # Thresholded actflow\n                    actflow_thresh = np.multiply(actflow_unthresh,actflow_unthresh>thresh)\n\n                tmp_actflow_unthresh.append(actflow_unthresh)\n                tmp_actflow_thresh.append(actflow_thresh)\n                tmp_true_activity.append(np.squeeze(rsm_activations[labelcount,hidden_ind]))\n\n                labelcount += 1\n\n            # Compute subject-specific predicted activations for each condition\n            all_actflow_unthresh.append(np.asarray(tmp_actflow_unthresh))\n            all_actflow_thresh.append(np.asarray(tmp_actflow_thresh))\n            all_true_activity.append(np.asarray(tmp_true_activity))\n\n\n\n        np.savetxt(filename + '.txt', labels, fmt='%s')\n\n        h5f = h5py.File(filename + '.h5','a')\n        try:\n            h5f.create_dataset('actflow_unthresh',data=all_actflow_unthresh)\n            h5f.create_dataset('actflow_thresh',data=all_actflow_thresh)\n            h5f.create_dataset('true_activity',data=all_true_activity)\n        except:\n            del h5f['actflow_unthresh'], h5f['actflow_thresh'], h5f['true_activity']\n            h5f.create_dataset('actflow_unthresh',data=all_actflow_unthresh)\n            h5f.create_dataset('actflow_thresh',data=all_actflow_thresh)\n            h5f.create_dataset('true_activity',data=all_true_activity)\n        h5f.close()\n\n\n    def generateInputControlDecoding(self,n_hiddenregions=10,verbose=False):\n        \"\"\"\n        Run all predictions for all 64 tasks\n        \"\"\"\n        hidden_ind = self.hidden_ind\n        rule_ind = self.rule_ind\n\n        \n        # Also exclude smn indices\n        smn_rois = np.where(networkdef==networkmappings['smn'])[0]\n        smn_ind = []\n        for roi in smn_rois:\n            smn_ind.extend(np.where(self.glasser2==roi+1)[0])\n        smn_ind = np.asarray(smn_ind)\n\n        target_vertices = self.fc_hidden2motorresp.shape[1]\n        actflow = np.zeros((target_vertices,4)) #LMID, LIND, RMID, rIND -- 4 cols in 3rd dim for each sensory rule\n        input_activations_lmid = []\n        input_activations_lind = []\n        input_activations_rmid = []\n        input_activations_rind = []\n        all_input_ind = []\n        for sensoryRule in self.sensoryRules:\n            input_ind = self._getStimIndices(sensoryRule) # Identify the vertices for the stimulus layer of the ANN \n            all_input_ind.extend(input_ind)\n\n        all_input_ind = np.asarray(all_input_ind)\n\n        #### Input activations\n        unique_input_ind = np.where(np.in1d(all_input_ind,hidden_ind)==False)[0]\n        unique_input_ind = np.where(np.in1d(unique_input_ind,smn_ind)==False)[0]\n        input_act = self.stimData[:,:][:,unique_input_ind]\n        \n        #### 12 rule activations\n        unique_input_ind = np.where(np.in1d(rule_ind,hidden_ind)==False)[0]\n        unique_input_ind = np.where(np.in1d(unique_input_ind,smn_ind)==False)[0]\n        rule_composition = self.logicRuleData[:,unique_input_ind] + self.sensoryRuleData[:,unique_input_ind] + self.motorRuleData[:,unique_input_ind]\n        #rule_act = self.logicRuleData[:,:][:,unique_input_ind]\n\n        ##### Concatenate input activations\n        input_activations = np.hstack((input_act,rule_composition))\n        ## Apply threshold\n        input_activations = np.multiply(input_act,input_act>0)\n\n\n        #### Average into 4 different responses\n        respIndex = np.asarray(self.motorRespAll)\n        # LMID\n        ind = np.where(respIndex=='LMID')[0]\n        if len(ind)!=0:\n            input_activations_lmid.append(np.sum(input_activations[ind,:],axis=0))\n        # LIND\n        ind = np.where(respIndex=='LIND')[0]\n        if len(ind)!=0:\n            input_activations_lind.append(np.sum(input_activations[ind,:],axis=0))\n        # RMID\n        ind = np.where(respIndex=='RMID')[0]\n        if len(ind)!=0:\n            input_activations_rmid.append(np.sum(input_activations[ind,:],axis=0))\n        # RIND\n        ind = np.where(respIndex=='RIND')[0]\n        if len(ind)!=0:\n            input_activations_rind.append(np.sum(input_activations[ind,:],axis=0))\n\n        return input_activations_lmid, input_activations_lind, input_activations_rmid, input_activations_rind\n\n    def generateActFlowPredictions_12Rule_PCFC(self,thresh=0,n_hiddenregions=10,verbose=False):\n        \"\"\"\n        Run all predictions for all 64 tasks\n        \"\"\"\n        hidden_ind = self.hidden_ind\n        rule_ind = self.rule_ind\n\n        target_vertices = self.fc_hidden2motorresp.shape[1]\n        actflow = np.zeros((target_vertices,4)) #LMID, LIND, RMID, rIND -- 4 cols in 3rd dim for each sensory rule\n        sensecount = 0\n        for sensoryRule in self.sensoryRules:\n            sensoryIndices = np.where(np.asarray(self.sensoryRuleIndices)==sensoryRule)[0]\n\n            input_ind = self._getStimIndices(sensoryRule) # Identify the vertices for stimulus layer of the ANN \n\n            # Run activity flow\n\n            #### Input to hidden regions\n            # first identify non-overlapping indices\n            unique_input_ind = np.where(np.in1d(input_ind,hidden_ind)==False)[0]\n            fc = self.fc_input2hidden[sensoryRule]\n            pc_act = np.matmul(self.stimData[sensoryIndices,:][:,unique_input_ind],self.eig_input2hidden[sensoryRule].T)\n            actflow_stim = np.matmul(pc_act,fc) \n            \n            #### Rule compositions\n            ####  (12rule) to hidden regions\n            unique_input_ind = np.where(np.in1d(rule_ind,hidden_ind)==False)[0]\n            rule_composition = self.logicRuleData[sensoryIndices,:][:,unique_input_ind] + self.sensoryRuleData[sensoryIndices,:][:,unique_input_ind] + self.motorRuleData[sensoryIndices,:][:,unique_input_ind]\n            # first identify non-overlapping indices\n            fc = self.fc_12rule2hidden\n            pc_act = np.matmul(rule_composition,self.eig_12rule2hidden.T)\n            actflow_taskrules = np.matmul(pc_act,fc) \n\n            hiddenlayer_composition = actflow_taskrules + actflow_stim\n\n            # Apply a threshold if there is one\n            if thresh==None:\n                pass\n            else:\n                hiddenlayer_composition = np.multiply(hiddenlayer_composition,hiddenlayer_composition>thresh)\n                #t, p = stats.ttest_1samp(hiddenlayer_composition,0,axis=0) # Trials x Vertices\n                #p[t>0] = p[t>0]/2.0\n                #p[t<0] = 1.0 - p[t<0]/2.0\n                #h0 = mc.fdrcorrection0(p)[0] # Effectively a threshold linear func\n                #h0 = p<0.05\n                #hiddenlayer_composition = np.multiply(hiddenlayer_composition,h0)\n\n            ## multiplicative gating\n            ##hiddenlayer_composition = np.multiply(np.multiply(np.multiply(actflow_stim, actflow_logicrule), actflow_sensoryrule), actflow_motorrule)\n\n            #### Hidden to output regions \n            unique_ind = np.where(np.in1d(hidden_ind,self.motor_ind)==False)[0]\n            fc = self.fc_hidden2motorresp\n            pc_act = np.matmul(hiddenlayer_composition[:,unique_ind],self.eig_hidden2motorresp.T)\n            actflow_predictions = np.real(np.matmul(pc_act,fc))\n\n\n            ## Apply a threshold if there is one\n            #if thresh==None:\n            #    pass\n            #else:\n            #    actflow_predictions = np.multiply(actflow_predictions,actflow_predictions>thresh)\n\n\n            respIndex = np.asarray(self.motorRespAll)[sensoryIndices]\n            # LMID\n            ind = np.where(respIndex=='LMID')[0]\n            if len(ind)!=0:\n                actflow[:,0] = actflow[:,0] + np.sum(actflow_predictions[ind,:],axis=0)\n            # LIND\n            ind = np.where(respIndex=='LIND')[0]\n            if len(ind)!=0:\n                actflow[:,1] = actflow[:,1] + np.sum(actflow_predictions[ind,:],axis=0)\n            # RMID\n            ind = np.where(respIndex=='RMID')[0]\n            if len(ind)!=0:\n                actflow[:,2] = actflow[:,2] + np.sum(actflow_predictions[ind,:],axis=0)\n            # RIND\n            ind = np.where(respIndex=='RIND')[0]\n            if len(ind)!=0:\n                actflow[:,3] = actflow[:,3] + np.sum(actflow_predictions[ind,:],axis=0)\n            \n            #\n            #respIndex = np.asarray(self.motorRespAll)[sensoryIndices]\n            ## LMID\n            #ind = np.where(respIndex=='LMID')[0]\n            #print ind\n            #actflow[:,0,sensecount] = np.mean(actflow_predictions[ind,:],axis=0)\n            ## LIND\n            #ind = np.where(respIndex=='LIND')[0]\n            #print ind\n            #actflow[:,1,sensecount] = np.mean(actflow_predictions[ind,:],axis=0)\n            ## RMID\n            #ind = np.where(respIndex=='RMID')[0]\n            #print ind\n            #actflow[:,2,sensecount] = np.mean(actflow_predictions[ind,:],axis=0)\n            ## RIND\n            #ind = np.where(respIndex=='RIND')[0]\n            #print ind\n            #actflow[:,3,sensecount] = np.mean(actflow_predictions[ind,:],axis=0)\n\n            sensecount += 1\n\n        #actflow = np.mean(actflow,axis=2)\n        #actflow = np.divide(actflow,4.0)\n\n        return actflow\n\n    def generateActFlowPredictions_12Rule_NoHidden(self,thresh=0,verbose=False):\n        \"\"\"\n        Run all predictions for all 64 tasks\n        \"\"\"\n        rule_ind = self.rule_ind\n\n        target_vertices = self.fc_12rule2output.shape[1]\n        actflow = np.zeros((target_vertices,4)) #LMID, LIND, RMID, rIND -- 4 cols in 3rd dim for each sensory rule\n        sensecount = 0\n        for sensoryRule in self.sensoryRules:\n            sensoryIndices = np.where(np.asarray(self.sensoryRuleIndices)==sensoryRule)[0]\n\n            input_ind = self._getStimIndices(sensoryRule) # Identify the vertices for stimulus layer of the ANN \n\n            # Run activity flow\n\n            #### Input to hidden regions\n            # first identify non-overlapping indices\n            unique_input_ind = np.where(np.in1d(input_ind,self.motor_ind)==False)[0]\n            fc = self.fc_input2output[sensoryRule]\n            pc_act = np.matmul(self.stimData[sensoryIndices,:][:,unique_input_ind],self.eig_input2output[sensoryRule].T)\n            actflow_stim = np.matmul(pc_act,fc) \n            \n            #### Rule compositions\n            ####  (12rule) to hidden regions\n            unique_input_ind = np.where(np.in1d(rule_ind,self.motor_ind)==False)[0]\n            rule_composition = self.logicRuleData[sensoryIndices,:][:,unique_input_ind] + self.sensoryRuleData[sensoryIndices,:][:,unique_input_ind] + self.motorRuleData[sensoryIndices,:][:,unique_input_ind]\n            # first identify non-overlapping indices\n            fc = self.fc_12rule2output\n            pc_act = np.matmul(rule_composition,self.eig_12rule2output.T)\n            actflow_taskrules = np.matmul(pc_act,fc) \n\n            actflow_predictions = actflow_taskrules + actflow_stim\n\n#            # Apply a threshold if there is one\n#            if thresh==None:\n#                pass\n#            else:\n#                actflow_predictions = np.multiply(actflow_predictions,actflow_predictions>thresh)\n                #t, p = stats.ttest_1samp(hiddenlayer_composition,0,axis=0) # Trials x Vertices\n                #p[t>0] = p[t>0]/2.0\n                #p[t<0] = 1.0 - p[t<0]/2.0\n                #h0 = mc.fdrcorrection0(p)[0] # Effectively a threshold linear func\n                #h0 = p<0.05\n                #hiddenlayer_composition = np.multiply(hiddenlayer_composition,h0)\n\n            respIndex = np.asarray(self.motorRespAll)[sensoryIndices]\n            # LMID\n            ind = np.where(respIndex=='LMID')[0]\n            if len(ind)!=0:\n                actflow[:,0] = actflow[:,0] + np.sum(actflow_predictions[ind,:],axis=0)\n            # LIND\n            ind = np.where(respIndex=='LIND')[0]\n            if len(ind)!=0:\n                actflow[:,1] = actflow[:,1] + np.sum(actflow_predictions[ind,:],axis=0)\n            # RMID\n            ind = np.where(respIndex=='RMID')[0]\n            if len(ind)!=0:\n                actflow[:,2] = actflow[:,2] + np.sum(actflow_predictions[ind,:],axis=0)\n            # RIND\n            ind = np.where(respIndex=='RIND')[0]\n            if len(ind)!=0:\n                actflow[:,3] = actflow[:,3] + np.sum(actflow_predictions[ind,:],axis=0)\n            \n            #\n            #respIndex = np.asarray(self.motorRespAll)[sensoryIndices]\n            ## LMID\n            #ind = np.where(respIndex=='LMID')[0]\n            #print ind\n            #actflow[:,0,sensecount] = np.mean(actflow_predictions[ind,:],axis=0)\n            ## LIND\n            #ind = np.where(respIndex=='LIND')[0]\n            #print ind\n            #actflow[:,1,sensecount] = np.mean(actflow_predictions[ind,:],axis=0)\n            ## RMID\n            #ind = np.where(respIndex=='RMID')[0]\n            #print ind\n            #actflow[:,2,sensecount] = np.mean(actflow_predictions[ind,:],axis=0)\n            ## RIND\n            #ind = np.where(respIndex=='RIND')[0]\n            #print ind\n            #actflow[:,3,sensecount] = np.mean(actflow_predictions[ind,:],axis=0)\n\n            sensecount += 1\n\n        #actflow = np.mean(actflow,axis=2)\n        #actflow = np.divide(actflow,4.0)\n\n        return actflow\n\n    def _simulateSubjActFlow(self,subj,thresh=0):\n        print('Subject ' + subj + '... Simulating ' + str(len(self.trial_metadata)) + ' Trials')\n        self.extractSubjActivations(subj,self.trial_metadata)\n        if self.hidden:\n            actflow = self.generateActFlowPredictions_12Rule_PCFC(thresh=thresh,verbose=False)\n        else:\n            actflow = self.generateActFlowPredictions_12Rule_NoHidden(thresh=thresh,verbose=False)\n        return actflow\n\n    def _getStimIndices(self,sensoryRule):\n        if sensoryRule=='RED': \n            inputkey = 'COLOR'\n        if sensoryRule=='VERTICAL':\n            inputkey = 'ORI'\n        if sensoryRule=='HIGH':\n            inputkey = 'PITCH'\n        if sensoryRule=='CONSTANT': \n            inputkey = 'CONSTANT'\n        \n        inputdir = self.projectdir + 'data/results/MAIN/InputStimuliDecoding/'\n        input_regions = np.loadtxt(inputdir + 'InputStimuliRegions_' + inputkey + '.csv',delimiter=',')\n\n        input_ind = []\n        for roi in input_regions:\n            input_ind.extend(np.where(self.glasser2==roi+1)[0])\n\n        return input_ind\n\n    def _computeSubjFC(self,subj,n_components=500):\n        \"\"\"\n        Compute FC\n        \"\"\"\n        # Set some useful local parameters\n        fcdir = self.fcdir\n        n_hiddenregions = self.n_hiddenregions\n        hiddenregions = self.hiddenregions\n\n        print('Computing FC for subject', subj, '| num hidden =', n_hiddenregions, '| num components =', n_components)\n\n        #######################################\n        #### Load data\n        data = tools.loadRestActivity(subj,model='24pXaCompCorXVolterra',zscore=False)\n        # Demean\n        data = signal.detrend(data,axis=1,type='constant')\n\n        #######################################\n        #### Compute input 2 hidden layer FC\n        print('Computing input to hidden FC | subj', subj)\n        # Re-map inputtypes to sensory features\n        inputmap = {'RED':'COLOR','VERTICAL':'ORI','CONSTANT':'CONSTANT','HIGH':'PITCH'}\n        for inputtype in self.inputtypes:\n            outputfilename = fcdir + '/' + inputtype + 'To' + 'HiddenLayer_FC_subj' + subj + '.h5'\n            sourcedir = self.projectdir + 'data/results/MAIN/InputStimuliDecoding/'\n            input_regions = np.loadtxt(sourcedir + 'InputStimuliRegions_' + inputmap[inputtype] + '.csv',delimiter=',')\n            # Compute FC\n            fc.layerToLayerFC(data,input_regions,hiddenregions,outputfilename,n_components=n_components)\n\n        #######################################\n        #### Compute rule 2 hidden layer FC\n        print('Computing rule to hidden FC | subj', subj)\n        outputfilename = fcdir + '/' + self.ruletype + 'RuleToHiddenLayer_FC_subj' + subj + '.h5'\n        sourcedir = self.projectdir + 'data/results/MAIN/RuleDecoding/'\n        if self.ruletype == 'fpn':\n            rule_regions = []\n            rule_regions.extend(np.where(networkdef==networkmappings['fpn'])[0])\n            rule_regions = np.asarray(rule_regions)\n        elif self.ruletype=='nounimodal':\n            allrule_regions = np.loadtxt(sourcedir + '12Rule_Regions.csv',delimiter=',')\n            unimodal_nets = ['vis1','aud']\n            unimodal_regions = []\n            for net in unimodal_nets:\n                unimodal_regions.extend(np.where(networkdef==networkmappings[net])[0])\n            # only include regions that are in allrule_regions but also NOT in unimodal_regions\n            rule_regions = []\n            for roi in allrule_regions:\n                if roi in unimodal_regions:\n                    continue\n                else:\n                    rule_regions.append(roi)\n            rule_regions = np.asarray(rule_regions)\n        else:\n            rule_regions = np.loadtxt(sourcedir + self.ruletype + 'Rule_Regions.csv',delimiter=',')\n\n        # Compute FC\n        fc.layerToLayerFC(data,rule_regions,hiddenregions,outputfilename,n_components=n_components)\n\n        #######################################\n        #### Compute hidden to output layer \n        outputfilename = fcdir + '/HiddenLayerToOutput_FC_subj' + subj + '.h5'\n        targetdir = self.projectdir + 'data/results/MAIN/MotorResponseDecoding/'\n        motor_resp_regions_LH = np.loadtxt(targetdir + 'MotorResponseRegions_LH.csv',delimiter=',')\n        motor_resp_regions_RH = np.loadtxt(targetdir + 'MotorResponseRegions_RH.csv',delimiter=',')\n        motor_resp_regions = np.hstack((motor_resp_regions_LH,motor_resp_regions_RH))\n        # Compute FC\n        print('Computing hidden to output FC | subj', subj)\n        fc.layerToLayerFC(data,hiddenregions,motor_resp_regions,outputfilename,n_components=n_components)\n\n    def _computeSubjFC_NoHidden(self,subj,n_components=500):\n        \"\"\"\n        Compute FC\n        \"\"\"\n        # Set some useful local parameters\n        fcdir = self.fcdir\n        n_hiddenregions = self.n_hiddenregions\n        hiddenregions = self.hiddenregions\n\n        print('Computing FC for subject', subj, '| num hidden =', n_hiddenregions, '| num components =', n_components)\n\n        #######################################\n        #### Load data\n        data = tools.loadRestActivity(subj,model='24pXaCompCorXVolterra',zscore=False)\n        # Demean\n        data = signal.detrend(data,axis=1,type='constant')\n\n        #######################################\n        #### Compute input 2 output layer FC\n        print('Computing input to output (NoHidden) FC | subj', subj)\n        targetdir = self.projectdir + 'data/results/MAIN/MotorResponseDecoding/'\n        motor_resp_regions_LH = np.loadtxt(targetdir + 'MotorResponseRegions_LH.csv',delimiter=',')\n        motor_resp_regions_RH = np.loadtxt(targetdir + 'MotorResponseRegions_RH.csv',delimiter=',')\n        motor_resp_regions = np.hstack((motor_resp_regions_LH,motor_resp_regions_RH))\n\n        # Re-map inputtypes to sensory features\n        inputmap = {'RED':'COLOR','VERTICAL':'ORI','CONSTANT':'CONSTANT','HIGH':'PITCH'}\n        for inputtype in self.inputtypes:\n            outputfilename = fcdir + '/' + inputtype + 'To' + 'OutputLayer_FC_subj' + subj + '.h5'\n            sourcedir = self.projectdir + 'data/results/MAIN/InputStimuliDecoding/'\n            input_regions = np.loadtxt(sourcedir + 'InputStimuliRegions_' + inputmap[inputtype] + '.csv',delimiter=',')\n            # Compute FC\n            fc.layerToLayerFC(data,input_regions,motor_resp_regions,outputfilename,n_components=n_components)\n\n        #######################################\n        #### Compute rule 2 output layer FC\n        print('Computing rule to output (NoHidden) FC | subj', subj)\n        outputfilename = fcdir + '/' + self.ruletype + 'RuleToHiddenLayer_FC_subj' + subj + '.h5'\n        sourcedir = self.projectdir + 'data/results/MAIN/RuleDecoding/'\n        if self.ruletype == 'fpn':\n            rule_regions = []\n            rule_regions.extend(np.where(networkdef==networkmappings['fpn'])[0])\n            rule_regions = np.asarray(rule_regions)\n        elif self.ruletype=='nounimodal':\n            allrule_regions = np.loadtxt(sourcedir + '12Rule_Regions.csv',delimiter=',')\n            unimodal_nets = ['vis1','aud']\n            unimodal_regions = []\n            for net in unimodal_nets:\n                unimodal_regions.extend(np.where(networkdef==networkmappings[net])[0])\n            # only include regions that are in allrule_regions but also NOT in unimodal_regions\n            rule_regions = []\n            for roi in allrule_regions:\n                if roi in unimodal_regions:\n                    continue\n                else:\n                    rule_regions.append(roi)\n            rule_regions = np.asarray(rule_regions)\n        else:\n            rule_regions = np.loadtxt(sourcedir + self.ruletype + 'Rule_Regions.csv',delimiter=',')\n\n        # Compute FC\n        fc.layerToLayerFC(data,rule_regions,motor_resp_regions,outputfilename,n_components=n_components)\n\ndef solveInputs(logicRule, sensoryRule, motorRule, stim1, stim2, printTask=False):\n    \"\"\"\n    Solves CPRO task given a set of inputs and a task rule\n    logicRule = [BOTH, NOTBOTH, EITHER, NEITHER]\n    sensoryRule = [RED, VERTICAL, HIGH, CONSTANT]\n    motorRule = [LMID, LIND, RMID, RIND]\n    stim1 = [RED,BLUE] # for example\n    stim2 = [RED,BLUE] # for example\n    \"\"\"\n\n    # Run through logic rule gates\n    if logicRule == 'BOTH':\n        if stim1==sensoryRule and stim2==sensoryRule:\n            gate = True\n        else:\n            gate = False\n\n    if logicRule == 'NOTBOTH':\n        if stim1!=sensoryRule or stim2!=sensoryRule:\n            gate = True\n        else:\n            gate = False\n\n    if logicRule == 'EITHER':\n        if stim1==sensoryRule or stim2==sensoryRule:\n            gate = True\n        else:\n            gate = False\n\n    if logicRule == 'NEITHER':\n        if stim1!=sensoryRule and stim2!=sensoryRule:\n            gate = True\n        else:\n            gate = False\n\n\n    # Apply logic gating to motor rules\n    if motorRule=='LMID':\n        if gate==True:\n            motorOutput = 'LMID'\n        else:\n            motorOutput = 'LIND'\n\n    if motorRule=='LIND':\n        if gate==True:\n            motorOutput = 'LIND'\n        else:\n            motorOutput = 'LMID'\n\n    if motorRule=='RMID':\n        if gate==True:\n            motorOutput = 'RMID'\n        else:\n            motorOutput = 'RIND'\n\n    if motorRule=='RIND':\n        if gate==True:\n            motorOutput = 'RIND'\n        else:\n            motorOutput = 'RMID'\n\n    ## Print task first\n    if printTask:\n        print('Logic rule:', logicRule)\n        print('Sensory rule:', sensoryRule)\n        print('Motor rule:', motorRule)\n        print('**Stimuli**')\n        print(stim1, stim2)\n        print('Motor response:', motorOutput)\n\n    return motorOutput\n\ndef constructTasks(n_stims=1,filename='./EmpiricalSRActFlow_AllTrialKeys1.h5'):\n    \"\"\"\n    Construct and save a dictionary of tasks to simulate/generate data for\n   \n    \"\"\"\n    logicRules = ['BOTH', 'NOTBOTH', 'EITHER', 'NEITHER']\n    sensoryRules = ['RED', 'VERTICAL', 'HIGH', 'CONSTANT']\n    motorRules = ['LMID', 'LIND', 'RMID', 'RIND']\n    colorStim = ['RED', 'BLUE']\n    oriStim = ['VERTICAL', 'HORIZONTAL']\n    pitchStim = ['HIGH', 'LOW']\n    constantStim = ['CONSTANT','ALARM']\n\n    trial_dict = {}\n    trial_dict['logicRule'] = []\n    trial_dict['sensoryRule'] = []\n    trial_dict['motorRule'] = []\n    trial_dict['stim1'] =  []\n    trial_dict['stim2'] = []\n    trial_dict['motorResp'] = []\n    for sensoryRule in sensoryRules:\n\n        for nstim in range(n_stims):\n            respIndex = []\n            # Randomly sample two stimulus patterns depending on the sensory rule\n            if sensoryRule=='RED': stims = np.random.choice(colorStim,2,replace=True)\n            if sensoryRule=='VERTICAL': stims = np.random.choice(oriStim,2,replace=True)\n            if sensoryRule=='HIGH': stims = np.random.choice(pitchStim,2,replace=True)\n            if sensoryRule=='PITCH': stims = np.random.choice(constantStim,2,replace=True)\n            stim1, stim2 = stims\n\n            \n            for logicRule in logicRules:\n\n                for motorRule in motorRules:\n\n#                        if verbose:\n#                            print 'Running actflow predictions for:', logicRule, sensoryRule, motorRule, 'task'\n\n                    logicKey = 'RuleLogic_' + logicRule\n                    sensoryKey = 'RuleSensory_' + sensoryRule\n                    motorKey = 'RuleMotor_' + motorRule\n                    stimKey = 'Stim_' + stim1 + stim2\n                    motorResp = solveInputs(logicRule, sensoryRule, motorRule, stim1, stim2, printTask=False)\n                    respKey = 'Response_' + motorResp\n                    \n                    # Instantiate empty dictionary for this trial\n                    trial_dict['logicRule'].append(logicRule)\n                    trial_dict['sensoryRule'].append(sensoryRule)\n                    trial_dict['motorRule'].append(motorRule)\n                    trial_dict['stim1'].append(stim1)\n                    trial_dict['stim2'].append(stim2)\n                    trial_dict['motorResp'].append(motorResp)\n\n    df = pd.DataFrame(trial_dict)\n    df.to_csv(filename)\n\ndef constructTasksForRITLGeneralization(n_stims=1,filename_training='./GroupfMRI14a_EmpiricalSRActFlow_TrainingTasks.csv',\n                                        filename_testing='./GroupfMRI14a_EmpiricalSRActFlow_TestTasks.csv'):\n    \"\"\"\n    Construct and save a dictionary of tasks to simulate/generate data for\n   \n    \"\"\"\n    logicRules = ['BOTH', 'NOTBOTH', 'EITHER', 'NEITHER']\n    sensoryRules = ['RED', 'VERTICAL', 'HIGH', 'CONSTANT']\n    motorRules = ['LMID', 'LIND', 'RMID', 'RIND']\n    colorStim = ['RED', 'BLUE']\n    oriStim = ['VERTICAL', 'HORIZONTAL']\n    pitchStim = ['HIGH', 'LOW']\n    constantStim = ['CONSTANT','ALARM']\n\n    #testset_tasks = ['BOTH-RED-LIND', 'NEITHER-VERTICAL-LMID', 'NOTBOTH-HIGH-RIND', 'EITHER-CONSTANT-RMID']\n    #testset_tasks = ['BOTH-RED-LMID', 'NEITHER-VERTICAL-LIND', 'NOTBOTH-HIGH-RMID', 'EITHER-CONSTANT-RIND',\n    #                 'NOTBOTH-RED-LMID', 'EITHER-VERTICAL-LIND', 'BOTH-HIGH-RMID', 'NEITHER-CONSTANT-RIND']\n    testset_tasks = ['BOTH-RED-LMID', 'NEITHER-VERTICAL-LIND', 'NOTBOTH-HIGH-RMID', 'EITHER-CONSTANT-RIND',\n                     'NOTBOTH-RED-LMID', 'EITHER-VERTICAL-LIND', 'BOTH-HIGH-RMID', 'NEITHER-CONSTANT-RIND',\n                     'BOTH-VERTICAL-LMID', 'NEITHER-RED-LIND', 'NOTBOTH-CONSTANT-RMID', 'EITHER-HIGH-RIND',\n                     'NOTBOTH-VERTICAL-LMID', 'EITHER-RED-LIND', 'BOTH-CONSTANT-RMID', 'NEITHER-HIGH-RIND',\n                     'BOTH-CONSTANT-LMID', 'NEITHER-HIGH-LIND', 'NOTBOTH-VERTICAL-RMID', 'EITHER-RED-RIND',\n                     'NOTBOTH-CONSTANT-LMID', 'EITHER-HIGH-LIND', 'BOTH-VERTICAL-RMID', 'NEITHER-RED-RIND',\n                     'BOTH-HIGH-LMID', 'NEITHER-CONSTANT-LIND', 'NOTBOTH-RED-RMID', 'EITHER-VERTICAL-RIND',\n                     'NOTBOTH-HIGH-LMID', 'EITHER-CONSTANT-LIND', 'BOTH-RED-RMID', 'NEITHER-VERTICAL-RIND']\n#    testset_tasks = ['BOTH-RED-LMID', 'NEITHER-VERTICAL-LIND', 'NOTBOTH-HIGH-RMID', 'EITHER-CONSTANT-RIND',\n#                     'NOTBOTH-RED-LMID', 'EITHER-VERTICAL-LIND', 'BOTH-HIGH-RMID', 'NEITHER-CONSTANT-RIND',\n#                     'BOTH-VERTICAL-LMID', 'NEITHER-RED-LIND', 'NOTBOTH-CONSTANT-RMID', 'EITHER-HIGH-RIND',\n#                     'NOTBOTH-VERTICAL-LMID', 'EITHER-RED-LIND', 'BOTH-CONSTANT-RMID', 'NEITHER-HIGH-RIND',\n#                     'BOTH-CONSTANT-LMID', 'NEITHER-HIGH-LIND', 'NOTBOTH-VERTICAL-RMID', 'EITHER-RED-RIND',\n#                     'NOTBOTH-CONSTANT-LMID', 'EITHER-HIGH-LIND', 'BOTH-VERTICAL-RMID', 'NEITHER-RED-RIND']\n\n    # Training set dictionary\n    trial_dict = {}\n    trial_dict['logicRule'] = []\n    trial_dict['sensoryRule'] = []\n    trial_dict['motorRule'] = []\n    trial_dict['stim1'] =  []\n    trial_dict['stim2'] = []\n    trial_dict['motorResp'] = []\n    # Test set dictionary\n    test_dict = {}\n    test_dict['logicRule'] = []\n    test_dict['sensoryRule'] = []\n    test_dict['motorRule'] = []\n    test_dict['stim1'] =  []\n    test_dict['stim2'] = []\n    test_dict['motorResp'] = []\n    for sensoryRule in sensoryRules:\n\n        for nstim in range(n_stims):\n            # Randomly sample two stimulus patterns depending on the sensory rule\n            if sensoryRule=='RED': stims = np.random.choice(colorStim,2,replace=True)\n            if sensoryRule=='VERTICAL': stims = np.random.choice(oriStim,2,replace=True)\n            if sensoryRule=='HIGH': stims = np.random.choice(pitchStim,2,replace=True)\n            if sensoryRule=='PITCH': stims = np.random.choice(constantStim,2,replace=True)\n            stim1, stim2 = stims\n\n            \n            for logicRule in logicRules:\n\n                for motorRule in motorRules:\n\n#                        if verbose:\n#                            print 'Running actflow predictions for:', logicRule, sensoryRule, motorRule, 'task'\n\n                    logicKey = 'RuleLogic_' + logicRule\n                    sensoryKey = 'RuleSensory_' + sensoryRule\n                    motorKey = 'RuleMotor_' + motorRule\n                    stimKey = 'Stim_' + stim1 + stim2\n                    motorResp = solveInputs(logicRule, sensoryRule, motorRule, stim1, stim2, printTask=False)\n                    respKey = 'Response_' + motorResp\n                    \n                    task_str = logicRule + '-' + sensoryRule + '-' + motorRule\n                    if task_str in testset_tasks:\n                        test_dict['logicRule'].append(logicRule)\n                        test_dict['sensoryRule'].append(sensoryRule)\n                        test_dict['motorRule'].append(motorRule)\n                        test_dict['stim1'].append(stim1)\n                        test_dict['stim2'].append(stim2)\n                        test_dict['motorResp'].append(motorResp)\n                    else:\n                        # Instantiate empty dictionary for this trial\n                        trial_dict['logicRule'].append(logicRule)\n                        trial_dict['sensoryRule'].append(sensoryRule)\n                        trial_dict['motorRule'].append(motorRule)\n                        trial_dict['stim1'].append(stim1)\n                        trial_dict['stim2'].append(stim2)\n                        trial_dict['motorResp'].append(motorResp)\n\n    df = pd.DataFrame(trial_dict)\n    df.to_csv(filename_training)\n    df = pd.DataFrame(test_dict)\n    df.to_csv(filename_testing)\n\n\n", "meta": {"hexsha": "ca5d3a649865140ebd66941b5ebce10230b3cb0a", "size": 55492, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/SRModels.py", "max_stars_repo_name": "ito-takuya/sr_enn", "max_stars_repo_head_hexsha": "85e105779dc9d4a0c4ddf8b7ff9f3f751b05bfdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-02-24T20:30:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T06:45:58.000Z", "max_issues_repo_path": "code/SRModels.py", "max_issues_repo_name": "ito-takuya/sr_enn", "max_issues_repo_head_hexsha": "85e105779dc9d4a0c4ddf8b7ff9f3f751b05bfdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/SRModels.py", "max_forks_repo_name": "ito-takuya/sr_enn", "max_forks_repo_head_hexsha": "85e105779dc9d4a0c4ddf8b7ff9f3f751b05bfdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-17T03:39:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T03:39:44.000Z", "avg_line_length": 44.787732042, "max_line_length": 207, "alphanum_fraction": 0.5904815108, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 13613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.18759005519017088}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nPlot the evolution of TRAPPIST-1 with initial conditions sampled from the\nposterior distributions.\n\n@author: David P. Fleming, 2019\n@email: dflemin3 (at) uw (dot) edu\n\nScript output:\n\nLuminosity [Lsun] = 5.220000e-04 + 1.900000e-05 - 1.900000e-05\nLXUV [Lsun] = 3.866823e-07 + 4.876776e-08 - 4.998834e-08\nRadius [Rsun] = 0.111608 + 0.000750 - 0.000760\n\n\"\"\"\n\nimport numpy as np\nimport os\nimport sys\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\nfrom trappist import mcmcUtils, trappist1 as t1\n\n#Typical plot parameters that make for pretty plots\nmpl.rcParams['figure.figsize'] = (9,8)\nmpl.rcParams['font.size'] = 22.0\n\n## for Palatino and other serif fonts use:\nmpl.rc('font',**{'family':'serif'})\nmpl.rc('text', usetex=True)\n\n# Read in evolutionary tracks\ndata = np.load(\"../../Data/trappist1StarEvol.npz\")\nnsamples = len(data[\"Luminosity\"])\n\nchains, blobs = mcmcUtils.extractMCMCResults(\"../../Data/trappist1Fiducial.h5\",\n                                             verbose=True, burn=500,\n                                             thinChains=True, blobsExist=True)\n\n### Plot Lum, LumXUV, radius evolution and compare to observations ###\n\nfig, axes = plt.subplots(ncols=3, figsize=(21,6))\n\nfor ii in range(nsamples):\n\n    # Left: lum\n    axes[0].plot(data[\"time\"][ii], data[\"Luminosity\"][ii], alpha=0.1, color=\"k\",\n                 lw=2, zorder=1)\n\n    # Middle: lumLUX\n    axes[1].plot(data[\"time\"][ii], data[\"LXUVStellar\"][ii], alpha=0.3, color=\"k\",\n                 lw=2)\n\n    # Middle: lumLUX\n    axes[2].plot(data[\"time\"][ii], data[\"Radius\"][ii], alpha=0.1, color=\"k\",\n                 lw=2)\n\n# Plot constraints, format\n\n# Output constraints\nlum = np.median(blobs[:,0])\nlumPlus = np.percentile(blobs[:,0], 84) - lum\nlumMinus = lum - np.percentile(blobs[:,0], 16)\nprint(\"Luminosity [Lsun] = %e + %e - %e\" % (lum, lumPlus, lumMinus))\n\nlxuv = np.median(blobs[:,1])\nlxuvPlus = np.percentile(blobs[:,1], 84) - lxuv\nlxuvMinus = lxuv - np.percentile(blobs[:,1], 16)\nprint(\"LXUV [Lsun] = %e + %e - %e\" % (lxuv, lxuvPlus, lxuvMinus))\n\nrad = np.median(blobs[:,2])\nradPlus = np.percentile(blobs[:,2], 84) - rad\nradMinus = rad - np.percentile(blobs[:,2], 16)\nprint(\"Radius [Rsun] = %lf + %lf - %lf\" % (rad, radPlus, radMinus))\n\n# Luminosity from Grootel+2018\nx = np.linspace(0, 1.2e10, 100)\n\n# Plot 1-3 sigmas\nfor ii in range(1,4):\n    axes[0].fill_between(x, 0.000522-(ii*0.000019), 0.000522+(ii*0.000019), color=\"C0\",\n                         alpha=0.22, zorder=0)\naxes[0].axhline(0.000522, color=\"C0\", lw=2, ls=\"--\", zorder=2)\n\naxes[0].set_ylabel(r\"Luminosity [L$_{\\odot}$]\", fontsize=25)\naxes[0].set_xlabel(\"Time [yr]\", fontsize=25)\naxes[0].set_ylim(4.0e-4, 1.5e-2)\naxes[0].set_yscale(\"log\")\naxes[0].set_xscale(\"log\")\n\n# Luminosity inset\naxLum = fig.add_axes([0.225, 0.55, 0.085, 0.3])\naxLum.hist(blobs[:,0], bins=20, orientation=\"horizontal\", color=\"gray\",\n           range=[0.00046, 0.000584], alpha=0.5);\naxLum.hist(blobs[:,0], bins=20, orientation=\"horizontal\", color=\"k\",\n          range=[0.00046, 0.000584], lw=2, histtype=\"step\");\naxLum.axhline(0.000522, lw=3, ls=\"--\", color=\"C0\")\naxLum.axhline(0.000522+0.000019, lw=3, ls=\"--\", color=\"C0\")\naxLum.axhline(0.000522-0.000019, lw=3, ls=\"--\", color=\"C0\")\n\n# Format inset\naxLum.set_xlabel(\"\")\naxLum.set_ylabel(\"\")\naxLum.set_title(r\"Luminosity [L$_{\\odot}$]\", fontsize=18)\n\ny2 = [0.000462, 0.00052, 0.000582]\ny2_labels = [\"0.00050\", \"0.00052\", \"0.00054\"]\naxLum.set_yticks(y2)\naxLum.set_yticklabels(y2_labels, minor=False, fontsize=18)\naxLum.set_xticklabels([])\n\n# XUV Luminosity from Wheatley+2017 1-3 Sigmas\n\nfor ii in range(1,4):\n    axes[1].fill_between(x, 3.9e-7-(ii*0.5e-7), 3.9e-7+(ii*0.5e-7), color=\"C0\",\n                         alpha=0.22, zorder=0)\naxes[1].axhline(10**-6.4, color=\"C0\", lw=2, ls=\"--\", zorder=2)\n\naxes[1].set_ylabel(r\"XUV Luminosity [L$_{\\odot}$]\", fontsize=25)\naxes[1].set_xlabel(\"Time [yr]\", fontsize=25)\naxes[1].set_ylim(1.5e-7, 5.0e-5)\naxes[1].set_yscale(\"log\")\naxes[1].set_xscale(\"log\")\n\n# LXUV inset\naxLXUV = fig.add_axes([0.555, 0.55, 0.085, 0.3])\naxLXUV.hist(blobs[:,1], bins=20, orientation=\"horizontal\", color=\"gray\",\n           range=[2.3e-7, 5.5e-7], alpha=0.5);\naxLXUV.hist(blobs[:,1], bins=20, orientation=\"horizontal\", color=\"k\",\n           range=[2.3e-7, 5.5e-7], lw=2, histtype=\"step\");\naxLXUV.axhline(3.4e-7, lw=3, ls=\"--\", color=\"C0\")\naxLXUV.axhline(3.9e-7, lw=3, ls=\"--\", color=\"C0\")\naxLXUV.axhline(4.4e-7, lw=3, ls=\"--\", color=\"C0\")\n\n# Format inset\naxLXUV.set_xlabel(\"\")\naxLXUV.set_ylabel(\"\")\naxLXUV.set_title(r\"$L_{XUV}$ [$10^{-7} L_{\\odot}$]\", fontsize=18)\n\ny2 = [2.4e-7, 3.9e-7, 5.4e-7]\ny2_labels = [\"2.4\", \"3.9 \" ,\"5.4\"]\naxLXUV.set_yticks(y2)\naxLXUV.set_yticklabels(y2_labels, minor=False, fontsize=18)\naxLXUV.set_xticklabels([])\n\n# Radius from Grootel+2018 1-3 sigmas\nfor ii in range(1,4):\n    axes[2].fill_between(x, 0.121-(ii*0.003), 0.121+(ii*0.003), color=\"C0\",\n                         alpha=0.22, zorder=0)\naxes[2].axhline(0.121, color=\"C0\", lw=2, ls=\"--\", zorder=2)\n\naxes[2].set_ylabel(r\"Radius [R$_{\\odot}$]\", fontsize=25)\naxes[2].set_xlabel(\"Time [yr]\", fontsize=25)\naxes[2].set_xscale(\"log\")\naxes[2].set_ylim(0.09, 0.40)\n\n# Radius inset\naxRad = fig.add_axes([0.885, 0.55, 0.085, 0.3])\naxRad.hist(blobs[:,2], bins=20, orientation=\"horizontal\", color=\"gray\",\n           alpha=0.5);\naxRad.hist(blobs[:,2], bins=20, orientation=\"horizontal\", color=\"k\", lw=2,\n           histtype=\"step\");\naxRad.axhline(0.118, lw=3, ls=\"--\", color=\"C0\")\naxRad.axhline(0.121, lw=3, ls=\"--\", color=\"C0\")\naxRad.axhline(0.124, lw=3, ls=\"--\", color=\"C0\")\n\n# Format inset\naxRad.set_xlabel(\"\")\naxRad.set_ylabel(\"\")\naxRad.set_title(r\"Radius [R$_{\\odot}$]\", fontsize=18)\n\nradMed = np.mean(blobs[:,2])\ny2 = [radMed, 0.121]\ny2_labels = [\"%.3lf\" % radMed, \"0.121\"]\naxRad.set_yticks(y2)\naxRad.set_yticklabels(y2_labels, minor=False, fontsize=18)\naxRad.set_xticklabels([])\n\nfig.tight_layout()\nplt.subplots_adjust(wspace=0.225)\n\n# Save!\nif (sys.argv[1] == 'pdf'):\n    fig.savefig(\"trappist1Evol.pdf\", bbox_inches=\"tight\",\n                dpi=200)\nif (sys.argv[1] == 'png'):\n    fig.savefig(\"trappist1Evol.png\", bbox_inches=\"tight\",\n                dpi=200)\n# Done!\n", "meta": {"hexsha": "f422704e05e1429c16987255a09c4ca681aef95e", "size": 6245, "ext": "py", "lang": "Python", "max_stars_repo_path": "Analysis/Evol/plotEvolTrappist1.py", "max_stars_repo_name": "dflemin3/trappist", "max_stars_repo_head_hexsha": "1aeb273f49678d685addc540cd4444ff045bc601", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-12T18:51:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-12T18:51:46.000Z", "max_issues_repo_path": "Analysis/Evol/plotEvolTrappist1.py", "max_issues_repo_name": "dflemin3/trappist", "max_issues_repo_head_hexsha": "1aeb273f49678d685addc540cd4444ff045bc601", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Analysis/Evol/plotEvolTrappist1.py", "max_forks_repo_name": "dflemin3/trappist", "max_forks_repo_head_hexsha": "1aeb273f49678d685addc540cd4444ff045bc601", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-08T18:49:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T18:49:03.000Z", "avg_line_length": 32.5260416667, "max_line_length": 87, "alphanum_fraction": 0.6315452362, "include": true, "reason": "import numpy", "num_tokens": 2333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.18759005519017086}}
{"text": "\"\"\"\nPNT implementation on taxi_domain trees\ncreated on January 8, 2020 by Rohan Paleja\n\"\"\"\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom low_dim.prolonet import ProLoNet\nfrom torch.autograd import Variable\nimport os\nimport pickle\nfrom AndrewSilva.tree_nets.utils.fuzzy_to_crispy import convert_to_crisp\n\n# noinspection PyUnresolvedReferences\ntorch.backends.cudnn.deterministic = True\n# noinspection PyUnresolvedReferences\ntorch.backends.cudnn.benchmark = False\ntorch.manual_seed(50)  # ensures repeatability\nnp.random.seed(50)\n\n\n# noinspection PyArgumentList,PyUnresolvedReferences,PyTypeChecker\nclass PNT_pairwise:\n    \"\"\"\n    PNT_pairwise for taxi domain\n    \"\"\"\n\n    def __init__(self):\n        self.action_embeddings = [1, 0, 0], [0, 1, 0], [0, 0, 1]\n        self.action_embedding_dim = len(self.action_embeddings[0])\n        self.num_actions = len(self.action_embeddings)\n        self.state_dim = 5 + self.num_actions\n        self.output_dim = 1\n        self.embedding_dim = 3\n        self.use_gpu = False\n        if not self.use_gpu:\n            device = 'cpu'\n        else:\n            device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n        self.model = ProLoNet(input_dim=self.state_dim,\n                              output_dim=self.output_dim,\n                              weights=None,\n                              comparators=None,\n                              leaves=256,\n                              is_value=True,\n                              bayesian_embedding_dim=self.embedding_dim,\n                              alpha=1.5,\n                              use_gpu=self.use_gpu,\n                              vectorized=True,\n                              selectors=None).to(device)\n\n        self.sig = torch.nn.Sigmoid()\n        self.criterion = torch.nn.BCELoss()\n\n        self.opt = torch.optim.RMSprop(\n            [{'params': list(self.model.parameters())[:-1]}, {'params': self.model.bayesian_embedding.parameters(), 'lr': .1}], lr=.01)\n        self.person_specific_embeddings = [torch.ones(self.embedding_dim) * 1 / 3 for _ in range(600)]\n\n        self.states, self.actions, self.failed_list, self.mturkcodes, self.indices_of_failed = self.load_in_data()\n        self.test_states, self.test_actions, self.test_failed_list, self.test_mturkcodes, self.test_indices_of_failed = self.load_in_test_data()\n\n        print('Leaves is ', 64)\n        print('Optimizer: RMSprop, lr_e=.001 lr=.0001')\n\n\n        self.training_accuracies = []\n        self.testing_accuracies = []\n        self.testing_stds = []\n        # for producing embeddings, cut this if you want to train\n        # checkpoint = torch.load(\n        #     '/home/Anonymous/PycharmProjects/bayesian_prolo/taxi_domain/models/PNT_pairwise_643999.pkl')\n        # self.model.load_state_dict(checkpoint['state_dict'])\n\n\n    @staticmethod\n    def load_in_data():\n        \"\"\"\n        loads in train data\n        :return:\n        \"\"\"\n        states, actions, failed_list, mturkcodes = pickle.load(open(os.path.join('../datasets/', 'testing_data_from_all_users_2.pkl'), 'rb'))\n\n        indices_of_failed = []\n        for i in failed_list:\n            if i[0] not in indices_of_failed:\n                indices_of_failed.append(i[0])\n\n        return states, actions, failed_list, mturkcodes, indices_of_failed\n\n    @staticmethod\n    def load_in_test_data():\n        \"\"\"\n        loads in test data\n        :return:\n        \"\"\"\n        states, actions, failed_list, mturkcodes = pickle.load(open(os.path.join('../datasets/', 'training_data_from_all_users_2.pkl'), 'rb'))\n\n        indices_of_failed = []\n        for i in failed_list:\n            if i[0] not in indices_of_failed:\n                indices_of_failed.append(i[0])\n\n        return states, actions, failed_list, mturkcodes, indices_of_failed\n\n    def train_model(self):\n        \"\"\"\n        trains a model\n        :return:\n        \"\"\"\n        # variables to keep track of loss and number of tasks trained over\n        for i in range(30000):\n\n            print('epoch: ', i)\n            # sample a timestep before the cutoff for cross_validation\n            which_user = np.random.choice(range(len(self.states)))\n            if which_user in self.indices_of_failed:\n                continue\n\n            states = self.states[which_user]\n            actions = self.actions[which_user]\n            length_of_current_game = len(states)\n\n            # set player specific embedding into network\n            self.model.set_bayesian_embedding(self.person_specific_embeddings[which_user].clone())\n\n            # pick ten timesteps within game\n            for j in range(50):\n\n                timestep = np.random.choice(range(len(self.states[which_user])))\n\n                # input\n\n                state_t = states[timestep]\n                action_t = actions[timestep]\n\n                if self.use_gpu:\n                    network_input = torch.tensor(state_t).reshape(1, 5).cuda()\n                    action_t = torch.tensor(action_t).cuda()\n                else:\n                    network_input = torch.tensor(state_t).reshape(1, 5)\n                    action_t = torch.tensor(action_t)\n\n                phi_i = np.asarray(self.action_embeddings[action_t])\n\n                # positive counterfactuals\n                for counter in range(self.num_actions):\n                    if counter == action_t:  # if counter == phi_i_num:\n                        continue\n                    else:\n                        phi_j = np.asarray(self.action_embeddings[counter])\n                        feature_input = phi_i - phi_j\n\n                        if self.use_gpu:\n                            feature_input = Variable(torch.Tensor(feature_input.reshape(1, 3)).cuda())\n                            label = Variable(torch.Tensor(torch.ones((1, 1))).cuda())\n                            feature_input = torch.cat([feature_input, network_input.float()], dim=1)\n                        else:\n                            feature_input = Variable(torch.Tensor(feature_input.reshape(1, 3)))\n                            label = Variable(torch.Tensor(torch.ones((1, 1))))\n                            feature_input = torch.cat([feature_input, network_input.float()], dim=1)\n\n                        output = self.model.forward(feature_input)\n                        output = self.sig(output)\n\n                        self.opt.zero_grad()\n                        loss = self.criterion(output, label)\n                        loss.backward()\n                        torch.nn.utils.clip_grad_norm_(self.model.parameters(), 0.5)\n                        self.opt.step()\n\n                for counter in range(self.num_actions):\n                    if counter == action_t:  # if counter == phi_i_num:\n                        continue\n                    else:\n                        phi_j = np.asarray(self.action_embeddings[counter])\n                        feature_input = phi_j - phi_i\n\n                        if self.use_gpu:\n                            feature_input = Variable(torch.Tensor(feature_input.reshape(1, 3)).cuda())\n                            label = Variable(torch.Tensor(torch.zeros((1, 1))).cuda())\n                            feature_input = torch.cat([feature_input, network_input.float()], dim=1)\n                        else:\n                            feature_input = Variable(torch.Tensor(feature_input.reshape(1, 3)))\n                            label = Variable(torch.Tensor(torch.zeros((1, 1))))\n                            feature_input = torch.cat([feature_input, network_input.float()], dim=1)\n\n                        output = self.model.forward(feature_input)\n                        output = self.sig(output)\n\n                        self.opt.zero_grad()\n                        loss = self.criterion(output, label)\n                        loss.backward()\n                        torch.nn.utils.clip_grad_norm_(self.model.parameters(), 0.5)\n                        self.opt.step()\n\n            self.person_specific_embeddings[which_user] = torch.Tensor(self.model.get_bayesian_embedding().detach().cpu().numpy())\n\n            if i % 100 == 99:\n                # print('loss is: ', np.mean(self.loss_array[-500]), 'for epoch: ', i)\n                # assert not os.path.exists(log_path) or \"test\" in log_path, \"log path already exist! \"f\n\n                self.evaluate_on_data(True)\n                person_specific_embeddings = self.evaluate_on_data(False)\n                print(i)\n                print('training accuracies: ', self.training_accuracies)\n                print('testing accuracies: ', self.testing_accuracies)\n                torch.save({'state_dict': self.model.state_dict(),\n                            'person_embeddings': person_specific_embeddings},\n                           '/home/Anonymous/PycharmProjects/bayesian_prolo/taxi_domain/models/PNT_pairwise_32' + str(i) + '.pkl')\n                # if self.testing_accuracies[-1] > 0.87:\n                #\n                #\n                #     self.retest_with_crisp_model()\n            # if i > 6000 and i % 1000 == 999:\n            #     self.retest_with_crisp_model()\n\n    def evaluate_on_data(self, train=True):\n        \"\"\"\n        evaluate on a subset of training data\n        :param train: if train is false, means we are in test\n        \"\"\"\n        embedding_optimizer = torch.optim.RMSprop([{'params': self.model.bayesian_embedding.parameters()}], lr=.1)\n\n        accuracies = []\n        person_specific_embeddings = [torch.ones(self.embedding_dim) * 1 / 3 for _ in range(600)]\n        if train:\n            states = self.states\n            actions = self.actions\n            indices_of_failed = self.indices_of_failed\n        else:\n            states = self.test_states\n            actions = self.test_actions\n            indices_of_failed = self.test_indices_of_failed\n\n\n        for i in range(len(states)):\n            if i in indices_of_failed:\n                continue\n            accuracy = 0\n\n            length_of_current_game = len(states[i])\n\n            # set player specific embedding into network\n            self.model.set_bayesian_embedding(person_specific_embeddings[i].clone())\n\n            for j in range(length_of_current_game):\n\n                # input\n                state_t = states[i][j]\n                action_t = actions[i][j]\n\n                probability_matrix = np.zeros((self.num_actions, self.num_actions))\n\n                # begin counterfactual reasoning\n                for each_action in range(self.num_actions):\n                    phi_i = self.action_embeddings[each_action]\n                    phi_i_numpy = np.asarray(phi_i)\n\n                    for each_other_action in range(self.num_actions):\n                        if each_action == each_other_action:\n                            continue\n\n                        phi_j = self.action_embeddings[each_other_action]\n                        phi_j_numpy = np.asarray(phi_j)\n                        action_embedding_counterfactual = phi_i_numpy - phi_j_numpy\n\n                        if self.use_gpu:\n                            network_input = torch.cat(\n                                [torch.Tensor(action_embedding_counterfactual).reshape(self.action_embedding_dim), torch.Tensor(state_t)],\n                                dim=0).reshape(1, self.state_dim).cuda()\n\n                        else:\n                            network_input = torch.cat(\n                                [torch.Tensor(action_embedding_counterfactual).reshape(self.action_embedding_dim), torch.Tensor(state_t)],\n                                dim=0).reshape(1, self.state_dim)\n\n                        # forward\n                        preference_prob = self.sig(self.model.forward(network_input))\n                        probability_matrix[each_action][each_other_action] = preference_prob.data.detach()[0].item()\n\n                # embedding update\n                phi_i = self.action_embeddings[action_t]\n                phi_i_numpy = np.asarray(phi_i)\n                for each_action in range(self.num_actions):\n                    if each_action == action_t:\n                        continue\n                    else:\n                        phi_j = self.action_embeddings[each_action]\n                        phi_j_numpy = np.asarray(phi_j)\n                        action_embedding_counterfactual = phi_i_numpy - phi_j_numpy\n\n                        if self.use_gpu:\n                            network_input = torch.cat(\n                                [torch.Tensor(action_embedding_counterfactual).reshape(self.action_embedding_dim), torch.Tensor(state_t)],\n                                dim=0).reshape(1, self.state_dim).cuda()\n\n                            label = Variable(torch.Tensor(torch.ones((1, 1))).cuda())\n                        else:\n                            network_input = torch.cat(\n                                [torch.Tensor(action_embedding_counterfactual).reshape(self.action_embedding_dim), torch.Tensor(state_t)],\n                                dim=0).reshape(1, self.state_dim)\n                            label = Variable(torch.Tensor(torch.ones((1, 1))))\n\n                        embedding_optimizer.zero_grad()\n                        output = self.sig(self.model.forward(network_input))\n                        loss = self.criterion(output, label)\n\n                        loss.backward()\n                        torch.nn.utils.clip_grad_norm_(self.model.parameters(), 0.5)\n                        embedding_optimizer.step()\n\n                        phi_j = self.action_embeddings[each_action]\n                        phi_j_numpy = np.asarray(phi_j)\n                        action_embedding_counterfactual = phi_j_numpy - phi_i_numpy\n\n                        if self.use_gpu:\n                            network_input = torch.cat(\n                                [torch.Tensor(action_embedding_counterfactual).reshape(self.action_embedding_dim), torch.Tensor(state_t)],\n                                dim=0).reshape(1, self.state_dim).cuda()\n\n                            label = Variable(torch.Tensor(torch.zeros((1, 1))).cuda())\n                        else:\n                            network_input = torch.cat(\n                                [torch.Tensor(action_embedding_counterfactual).reshape(self.action_embedding_dim), torch.Tensor(state_t)],\n                                dim=0).reshape(1, self.state_dim)\n                            label = Variable(torch.Tensor(torch.zeros((1, 1))))\n\n                        embedding_optimizer.zero_grad()\n                        output = self.sig(self.model.forward(network_input))\n                        loss = self.criterion(output, label)\n\n                        loss.backward()\n                        torch.nn.utils.clip_grad_norm_(self.model.parameters(), 0.5)\n                        embedding_optimizer.step()\n\n                # Finished all counterfactuals\n                column_vec = np.sum(probability_matrix, axis=1)\n\n                # print('preference of each action (highest number is the one you should take)', column_vec)\n                highest_val = max(column_vec)\n\n                # account for ties, if there is a tie pick a random one of the two\n                all_indexes_that_have_highest_val = [i for i, e in enumerate(list(column_vec)) if e == highest_val]\n                if len(all_indexes_that_have_highest_val) > 1:\n                    print('actions that are candidates: ', all_indexes_that_have_highest_val)\n\n                # top choice\n                index = np.random.choice(all_indexes_that_have_highest_val)\n                if index == action_t:\n                    accuracy += 1\n\n            person_specific_embeddings[i] = torch.Tensor(self.model.get_bayesian_embedding().detach().cpu().numpy())  # very ugly\n\n            # print('accuracy: ', accuracy / length_of_current_game)\n            accuracies.append(accuracy / length_of_current_game)\n        if train:\n            self.training_accuracies.append(np.mean(accuracies))\n        else:\n            self.testing_accuracies.append(np.mean(accuracies))\n            self.testing_stds.append(np.std(accuracies)/len(accuracies))\n            return person_specific_embeddings\n\n    def retest_with_crisp_model(self, load_in=False):\n        embedding_optimizer = torch.optim.RMSprop([{'params': self.model.bayesian_embedding.parameters()}], lr=.1)\n\n        accuracies = []\n        if load_in:\n            # checkpoint = torch.load(\n            #     '/home/Anonymous/PycharmProjects/bayesian_prolo/taxi_domain/models/PNT_pairwise_642999.pkl') good models\n            checkpoint = torch.load(\n                '/home/Anonymous/PycharmProjects/bayesian_prolo/taxi_domain/models/PNT_pairwise_25611299.pkl')\n            self.model.load_state_dict(checkpoint['state_dict'])\n            # person_specific_embeddings = checkpoint['person_embeddings']\n            person_specific_embeddings = [torch.ones(self.embedding_dim) * 1 / 3 for _ in range(600)]\n\n        else:\n            person_specific_embeddings = [torch.ones(self.embedding_dim) * 1 / 3 for _ in range(600)]\n\n        states = self.test_states\n        actions = self.test_actions\n        indices_of_failed = self.test_indices_of_failed\n\n        if load_in == False:\n            for i in range(len(states)):\n                if i in indices_of_failed:\n                    continue\n                accuracy = 0\n\n                length_of_current_game = len(states[i])\n\n                # set player specific embedding into network\n                self.model.set_bayesian_embedding(person_specific_embeddings[i].clone())\n\n                for j in range(length_of_current_game):\n\n                    # input\n                    state_t = states[i][j]\n                    action_t = actions[i][j]\n\n                    probability_matrix = np.zeros((self.num_actions, self.num_actions))\n\n                    # begin counterfactual reasoning\n                    for each_action in range(self.num_actions):\n                        phi_i = self.action_embeddings[each_action]\n                        phi_i_numpy = np.asarray(phi_i)\n\n                        for each_other_action in range(self.num_actions):\n                            if each_action == each_other_action:\n                                continue\n\n                            phi_j = self.action_embeddings[each_other_action]\n                            phi_j_numpy = np.asarray(phi_j)\n                            action_embedding_counterfactual = phi_i_numpy - phi_j_numpy\n\n                            if self.use_gpu:\n                                network_input = torch.cat(\n                                    [torch.Tensor(action_embedding_counterfactual).reshape(self.action_embedding_dim), torch.Tensor(state_t)],\n                                    dim=0).reshape(1, self.state_dim).cuda()\n\n                            else:\n                                network_input = torch.cat(\n                                    [torch.Tensor(action_embedding_counterfactual).reshape(self.action_embedding_dim), torch.Tensor(state_t)],\n                                    dim=0).reshape(1, self.state_dim)\n\n                            # forward\n                            preference_prob = self.sig(self.model.forward(network_input))\n                            probability_matrix[each_action][each_other_action] = preference_prob.data.detach()[0].item()\n\n                    # embedding update\n                    phi_i = self.action_embeddings[action_t]\n                    phi_i_numpy = np.asarray(phi_i)\n                    for each_action in range(self.num_actions):\n                        if each_action == action_t:\n                            continue\n                        else:\n                            phi_j = self.action_embeddings[each_action]\n                            phi_j_numpy = np.asarray(phi_j)\n                            action_embedding_counterfactual = phi_i_numpy - phi_j_numpy\n\n                            if self.use_gpu:\n                                network_input = torch.cat(\n                                    [torch.Tensor(action_embedding_counterfactual).reshape(self.action_embedding_dim), torch.Tensor(state_t)],\n                                    dim=0).reshape(1, self.state_dim).cuda()\n\n                                label = Variable(torch.Tensor(torch.ones((1, 1))).cuda())\n                            else:\n                                network_input = torch.cat(\n                                    [torch.Tensor(action_embedding_counterfactual).reshape(self.action_embedding_dim), torch.Tensor(state_t)],\n                                    dim=0).reshape(1, self.state_dim)\n                                label = Variable(torch.Tensor(torch.ones((1, 1))))\n\n                            embedding_optimizer.zero_grad()\n                            output = self.sig(self.model.forward(network_input))\n                            loss = self.criterion(output, label)\n\n                            loss.backward()\n                            torch.nn.utils.clip_grad_norm_(self.model.parameters(), 0.5)\n                            embedding_optimizer.step()\n\n                            phi_j = self.action_embeddings[each_action]\n                            phi_j_numpy = np.asarray(phi_j)\n                            action_embedding_counterfactual = phi_j_numpy - phi_i_numpy\n\n                            if self.use_gpu:\n                                network_input = torch.cat(\n                                    [torch.Tensor(action_embedding_counterfactual).reshape(self.action_embedding_dim), torch.Tensor(state_t)],\n                                    dim=0).reshape(1, self.state_dim).cuda()\n\n                                label = Variable(torch.Tensor(torch.zeros((1, 1))).cuda())\n                            else:\n                                network_input = torch.cat(\n                                    [torch.Tensor(action_embedding_counterfactual).reshape(self.action_embedding_dim), torch.Tensor(state_t)],\n                                    dim=0).reshape(1, self.state_dim)\n                                label = Variable(torch.Tensor(torch.zeros((1, 1))))\n\n                            embedding_optimizer.zero_grad()\n                            output = self.sig(self.model.forward(network_input))\n                            loss = self.criterion(output, label)\n\n                            loss.backward()\n                            torch.nn.utils.clip_grad_norm_(self.model.parameters(), 0.5)\n                            embedding_optimizer.step()\n\n                    # Finished all counterfactuals\n                    column_vec = np.sum(probability_matrix, axis=1)\n\n                    # print('preference of each action (highest number is the one you should take)', column_vec)\n                    highest_val = max(column_vec)\n\n                    # account for ties, if there is a tie pick a random one of the two\n                    all_indexes_that_have_highest_val = [i for i, e in enumerate(list(column_vec)) if e == highest_val]\n                    if len(all_indexes_that_have_highest_val) > 1:\n                        print('actions that are candidates: ', all_indexes_that_have_highest_val)\n\n                    # top choice\n                    index = np.random.choice(all_indexes_that_have_highest_val)\n                    if index == action_t:\n                        accuracy += 1\n\n                person_specific_embeddings[i] = torch.Tensor(self.model.get_bayesian_embedding().detach().cpu().numpy())  # very ugly\n\n                # print('accuracy: ', accuracy / length_of_current_game)\n                accuracies.append(accuracy / length_of_current_game)\n\n\n        # CRISPY\n        model = convert_to_crisp(self.model, None)\n        accuracies = []\n\n        for i in range(len(states)):\n            if i in indices_of_failed:\n                continue\n            accuracy = 0\n\n            length_of_current_game = len(states[i])\n\n            # set player specific embedding into network\n            self.model.set_bayesian_embedding(person_specific_embeddings[i].clone())\n\n            for j in range(length_of_current_game):\n\n                # input\n                state_t = states[i][j]\n                action_t = actions[i][j]\n\n                probability_matrix = np.zeros((self.num_actions, self.num_actions))\n\n                # begin counterfactual reasoning\n                for each_action in range(self.num_actions):\n                    phi_i = self.action_embeddings[each_action]\n                    phi_i_numpy = np.asarray(phi_i)\n\n                    for each_other_action in range(self.num_actions):\n                        if each_action == each_other_action:\n                            continue\n\n                        phi_j = self.action_embeddings[each_other_action]\n                        phi_j_numpy = np.asarray(phi_j)\n                        action_embedding_counterfactual = phi_i_numpy - phi_j_numpy\n\n                        network_input = torch.cat(\n                            [torch.Tensor(action_embedding_counterfactual).reshape(self.action_embedding_dim), torch.Tensor(state_t)],\n                            dim=0).reshape(1, self.state_dim)\n\n                        # forward\n                        preference_prob = self.sig(model.forward(network_input))\n                        probability_matrix[each_action][each_other_action] = preference_prob.data.detach()[0].item()\n\n\n                # Finished all counterfactuals\n                column_vec = np.sum(probability_matrix, axis=1)\n\n                # print('preference of each action (highest number is the one you should take)', column_vec)\n                highest_val = max(column_vec)\n\n                # account for ties, if there is a tie pick a random one of the two\n                all_indexes_that_have_highest_val = [i for i, e in enumerate(list(column_vec)) if e == highest_val]\n                if len(all_indexes_that_have_highest_val) > 1:\n                    print('actions that are candidates: ', all_indexes_that_have_highest_val)\n\n                # top choice\n                index = np.random.choice(all_indexes_that_have_highest_val)\n                if index == action_t:\n                    accuracy += 1\n\n            person_specific_embeddings[i] = torch.Tensor(self.model.get_bayesian_embedding().detach().cpu().numpy())  # very ugly\n\n            print('accuracy: ', accuracy / length_of_current_game)\n            accuracies.append(accuracy / length_of_current_game)\n\n        print('crisp acc', np.mean(accuracies))\n        print(np.std(accuracies) / len(accuracies))\n\n\ndef main():\n    \"\"\"\n    entry point for file\n    :return:\n    \"\"\"\n\n    trainer = PNT_pairwise()\n    # trainer.evaluate_on_data(train=True)\n    # trainer.evaluate_on_data(train=False)\n    # trainer.train_model()\n    trainer.retest_with_crisp_model(load_in=True)\n    print('Training accuracy', trainer.training_accuracies)\n    print('Testing accuracies', trainer.testing_accuracies)\n    print(np.max(trainer.training_accuracies))\n    print(np.max(trainer.testing_accuracies))\n    print('max val: ', np.max(trainer.testing_accuracies), ' std', trainer.testing_stds[int(np.argmax(trainer.testing_accuracies))])\n\n    print('This is testing on all players games and testing on holdout set of each player \\n embedding size is 12')\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "e834065b9ca05769674d9f3dd11aa28c281989fb", "size": 27375, "ext": "py", "lang": "Python", "max_stars_repo_path": "taxi_domain/methods/PNT_pairwise.py", "max_stars_repo_name": "CORE-Robotics-Lab/Personalized_Neural_Trees", "max_stars_repo_head_hexsha": "3e8dd12fe4fc850be65c96c847eb143ef3bcdc2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-05-22T19:25:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T07:59:56.000Z", "max_issues_repo_path": "taxi_domain/methods/PNT_pairwise.py", "max_issues_repo_name": "CORE-Robotics-Lab/Personalized_Neural_Trees", "max_issues_repo_head_hexsha": "3e8dd12fe4fc850be65c96c847eb143ef3bcdc2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "taxi_domain/methods/PNT_pairwise.py", "max_forks_repo_name": "CORE-Robotics-Lab/Personalized_Neural_Trees", "max_forks_repo_head_hexsha": "3e8dd12fe4fc850be65c96c847eb143ef3bcdc2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.7775919732, "max_line_length": 144, "alphanum_fraction": 0.5482009132, "include": true, "reason": "import numpy", "num_tokens": 5057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.18759005519017083}}
{"text": "#!/usr/bin/env python3\n\nimport numpy as np\nimport tensorflow.keras as keras\n\nfrom tensorflow.keras.layers import Input\n\n## Basic blocks ##\n\ndef skip_connection(x, xskip):\n    \"\"\"\n    A long skip connection that concatenates output from an encoding layer to a\n    layer in the decoder along the channel dimension.\n\n    Parameters\n    ----------\n    x :\n        Input tensor from the decoder phase.\n    xskip :\n        Tensor from the encoder phase.\n    \"\"\"\n\n    con = keras.layers.Concatenate(axis=3)([x, xskip])\n    return con\n\ndef convolution_block(x, filters, kernel_size, padding, strides, act, dropval, name=None, first_block=False, upsample=False):\n    \"\"\"\n    Fundamental convolution block.\n\n    This block has three possible configurations.\n    1) conv -> activation -> batchnorm\n    2) dropout -> conv -> activation -> batchnorm\n    3) upsample -> dropout -> conv -> activation -> batchnorm\n\n    This convolution block is used in both the encoder and decoder of the network.\n    Upsampling in the decoder is done with a dedicated layer. Downsampling is done\n    with a convolutional layer.\n\n    Parameters\n    ----------\n    x :\n        Input tensor.\n    filters : int\n        Number of activation maps in the convolutiional layer.\n    kernel_size : int\n        Dimension of filter in convolutional layer. Only a single integer is accepted.\n    padding : str\n        Convolutional layer padding.\n    strides : int\n        Stride number for convolutional layer.\n    act :\n        Activation function\n    dropval :\n        Drop rate for droupout layer.\n    name : str\n        Name that will be applied to only the batch normalization layer.\n    first_block : boolean\n        If True, dropout layer will be omitted from the block.\n    upsample : boolean\n        If True, a 2D upsampling layer will be placed before the dropout layer.\n        This enables configuration (3).\n\n    Returns\n    -------\n    con :\n        Output tensor.\n    \"\"\"\n\n    if first_block:\n        con = keras.layers.Conv2D(filters, kernel_size=kernel_size, padding=padding, strides=strides)(x)\n    elif upsample:\n        con = keras.layers.UpSampling2D(strides)(x)\n        con = keras.layers.Dropout(dropval)(con)\n        con = keras.layers.Conv2D(filters, kernel_size=kernel_size, padding=padding, strides=1)(con)\n    else:\n        con = keras.layers.Dropout(dropval)(x)\n        con = keras.layers.Conv2D(filters, kernel_size=kernel_size, padding=padding, strides=strides)(con)\n    con = keras.layers.Activation(act)(con)\n    con = keras.layers.BatchNormalization(name=name)(con)\n    return con\n\ndef residual_block(x, filters, kernel_size, padding, strides, act, dropval, name=[None, None], first_block=False, upsample=[False, False, False], filters_changed=False, mid_skip=None):\n    \"\"\"\n    Parameters\n    ----------\n    x :\n        Input tensor.\n    filters : list\n        A list with two elements. The items in the list, filters[0] and filters[1],\n        are the number of filters in the first and second convolution block,\n        respectively.\n    kernel_size : int\n        Dimension of filter in convolutional layer. Only a single integer is accepted.\n        The kernel_size provided is applied to both convolutional blocks.\n    padding : str\n        Convolutional layer padding. Given string is applied to both convolution\n        blocks.\n    strides : list\n        A list with three elements. Two items in the list, strides[0] and strides[1],\n        are the stride values for the first and second convolutional block, respectively.\n        The third item, stride[2], is the stride that will be applied to the convolutional\n        layer or upsampling layer in the residual connection.\n    act : list\n        A list with two elements. The items in the list, act[0] and act[1], are the\n        activation functions for the first and second convolutional block, respectively.\n    dropval :\n        Drop rate for droupout layer. Given value is applied to both convolution\n        blocks.\n    name : list\n        A list with two elements. The items in the list, name[0] and name[1], are the\n        names that will be applied to only the batch normalization layer of the first\n        and second convolution block, respectively.\n    first_block : boolean\n        If True, dropout layer will be omitted from the first convolution block.\n    upsample : list\n        A list with three elements. Two items in the list, upsample[0] and upsample[1],\n        indicate if an 2D upsampling layer should be added before the dropout layer in\n        the first and second convolution block, respectively. The third item, upsample[2],\n        indicates if a 2D upsampling layer should be used. All elements in the list\n        must be boolean.\n    filters_changed : boolean\n        Set to True if the input to the residual block and the output have a different\n        number of channels (filters). If True, a convolutional layer, if not already present\n        due to automatic triggers, will be placed in the residual connection to fix the channel\n        dimension.\n    mid_skip :\n        A keras tensor. This keras tensor will be concatenated with the output of the\n        first convolution block.\n\n    Returns\n    -------\n    con0 :\n        Output tensor of the first convolution block.\n    con1 :\n        Output tensor of the second convolution block. This is before the residual\n        connection is applied.\n    resoutput :\n        Output tensor from running the entire residual block. Residual connection is applied.\n    \"\"\"\n\n    con0 = convolution_block(x, filters[0], kernel_size, padding, strides[0], act[0], dropval, name=name[0], first_block=first_block, upsample=upsample[0])\n    if mid_skip is not None:\n        con0 = skip_connection(con0, mid_skip)\n    con1 = convolution_block(con0, filters[1], kernel_size, padding, strides[1], act[1], dropval, name=name[1], upsample=upsample[1])\n\n    if strides[2] != 1 and upsample[2] == True:\n        x = keras.layers.UpSampling2D(strides[2])(x)\n        if filters_changed == True:\n            x = keras.layers.Conv2D(filters[1], kernel_size=1, padding=padding, strides=1)(x)\n    elif (strides[2] != 1 and upsample[2] == False):\n        x = keras.layers.Conv2D(filters[1], kernel_size=1, padding=padding, strides=strides[2])(x)\n    elif filters_changed == True:\n        x = keras.layers.Conv2D(filters[1], kernel_size=1, padding=padding, strides=1)(x)\n    rescon = keras.layers.BatchNormalization()(x)\n\n    resoutput = keras.layers.Add()([rescon, con1])\n    return con0, con1, resoutput\n\ndef ResUNet_CMB(params):\n    \"\"\"\n    ResUNet-CMB Network\n\n    Network used in \"Reconstructing Patchy Reionization with Deep Learning.\"\n\n    Parameters\n    ----------\n    params:\n        params is a container for the variables defined in the configuration file.\n        An instance of class resunet.utils.Params.\n\n    Returns\n    -------\n    model :\n        model object.\n    \"\"\"\n\n    input_img1 = Input(shape=(params.imagesize, params.imagesize, 1), dtype=np.float32, name=\"qlen\")\n    input_img2 = Input(shape=(params.imagesize, params.imagesize, 1), dtype=np.float32, name=\"ulen\")\n\n    # encoder\n    enc_0 = keras.layers.Concatenate(axis=3)([input_img1, input_img2])\n    enc_1 = residual_block(enc_0, [64,64], 5, \"same\", [1,1,1], [\"selu\",\"selu\"], params.dropval, first_block=True, filters_changed=True)[2]\n    enc_2 = residual_block(enc_1, [64,128], 5, \"same\", [1,2,2], [\"selu\",\"selu\"], params.dropval, filters_changed=True)\n    enc_3 = residual_block(enc_2[2], [128,128], 5, \"same\", [1,1,1], [\"selu\",\"selu\"], params.dropval)[2]\n\n    # bridge between encoder and decoder\n    enc_dec = residual_block(enc_3, [256,128], 5, \"same\", [2,2,1], [\"selu\",\"selu\"], params.dropval, upsample=[False, True, False])[2]\n\n    lskip1 = skip_connection(enc_dec, enc_3)\n    dec_1 = residual_block(lskip1, [128,128], 5, \"same\", [1,1,1], [\"selu\",\"selu\"], params.dropval, filters_changed=True)[2]\n    dec_2 = residual_block(dec_1, [64, 64], 5, \"same\", [2,1,2], [\"selu\",\"selu\"], params.dropval, upsample=[True, False, True], mid_skip=enc_2[0], filters_changed=True)[2]\n\n    # Block all branches use for final residual connection\n    dec_3 = convolution_block(dec_2, 64, 5, \"same\", 1, \"selu\", params.dropval)\n\n    # kappa branch\n    kappa_1 = convolution_block(dec_3, 64, 5, \"same\", 1, \"selu\", params.dropval)\n    kappa_res_1 = keras.layers.BatchNormalization()(dec_2)\n    kappa_1 = keras.layers.Add()([kappa_res_1, kappa_1])\n    kappa_2 = convolution_block(kappa_1, 64, 5, \"same\", 1, \"selu\", params.dropval)\n    kappa_3 = convolution_block(kappa_2, 1, 5, \"same\", 1, \"linear\", params.dropval, name=\"kappa\")\n\n    # primordial E branch\n    unle_1 = convolution_block(dec_3, 64, 5, \"same\", 1, \"selu\", params.dropval)\n    unle_res_1 = keras.layers.BatchNormalization()(dec_2)\n    unle_1 = keras.layers.Add()([unle_res_1, unle_1])\n    unle_2 = convolution_block(unle_1, 64, 5, \"same\", 1, \"selu\", params.dropval)\n    unle_3 = convolution_block(unle_2, 1, 5, \"same\", 1, \"linear\", params.dropval, name=\"unle\")\n\n    # tau branch\n    tau_1 = convolution_block(dec_3, 64, 5, \"same\", 1, \"selu\", params.dropval)\n    tau_res_1 = keras.layers.BatchNormalization()(dec_2)\n    tau_1 = keras.layers.Add()([tau_res_1, tau_1])\n    tau_2 = convolution_block(tau_1, 64, 5, \"same\", 1, \"selu\", params.dropval)\n    tau_3 = convolution_block(tau_2, 1, 5, \"same\", 1, \"linear\", params.dropval, name=\"tau\")\n\n    model = keras.models.Model(inputs=[input_img1, input_img2], outputs=[tau_3, unle_3, kappa_3])\n    return model\n    \ndef ResUNet_CMB_4out(params):\n    \"\"\"\n    ResUNet-CMB 4-output Network\n\n    Network used in \"Reconstructing Cosmic Polarization Rotation with ResUNet-CMB\"\n\n    Parameters\n    ----------\n    params:\n        params is a container for the variables defined in the configuration file.\n        An instance of class resunet.utils.Params.\n\n    Returns\n    -------\n    model :\n        model object.\n    \"\"\"\n\n    input_img1 = Input(shape=(params.imagesize, params.imagesize, 1), dtype=np.float32, name=\"qlen\")\n    input_img2 = Input(shape=(params.imagesize, params.imagesize, 1), dtype=np.float32, name=\"ulen\")\n\n    # encoder\n    enc_0 = keras.layers.Concatenate(axis=3)([input_img1, input_img2])\n    enc_1 = residual_block(enc_0, [64,64], 5, \"same\", [1,1,1], [\"selu\",\"selu\"], params.dropval, first_block=True, filters_changed=True)[2]\n    enc_2 = residual_block(enc_1, [64,128], 5, \"same\", [1,2,2], [\"selu\",\"selu\"], params.dropval, filters_changed=True)\n    enc_3 = residual_block(enc_2[2], [128,128], 5, \"same\", [1,1,1], [\"selu\",\"selu\"], params.dropval)[2]\n\n    # bridge between encoder and decoder\n    enc_dec = residual_block(enc_3, [256,128], 5, \"same\", [2,2,1], [\"selu\",\"selu\"], params.dropval, upsample=[False, True, False])[2]\n\n    lskip1 = skip_connection(enc_dec, enc_3)\n    dec_1 = residual_block(lskip1, [128,128], 5, \"same\", [1,1,1], [\"selu\",\"selu\"], params.dropval, filters_changed=True)[2]\n    dec_2 = residual_block(dec_1, [64, 64], 5, \"same\", [2,1,2], [\"selu\",\"selu\"], params.dropval, upsample=[True, False, True], mid_skip=enc_2[0], filters_changed=True)[2]\n\n    # Block all branches use for final residual connection\n    dec_3 = convolution_block(dec_2, 64, 5, \"same\", 1, \"selu\", params.dropval)\n\n    # kappa branch\n    kappa_1 = convolution_block(dec_3, 64, 5, \"same\", 1, \"selu\", params.dropval)\n    kappa_res_1 = keras.layers.BatchNormalization()(dec_2)\n    kappa_1 = keras.layers.Add()([kappa_res_1, kappa_1])\n    kappa_2 = convolution_block(kappa_1, 64, 5, \"same\", 1, \"selu\", params.dropval)\n    kappa_3 = convolution_block(kappa_2, 1, 5, \"same\", 1, \"linear\", params.dropval, name=\"kappa\")\n\n    # primordial E branch\n    unle_1 = convolution_block(dec_3, 64, 5, \"same\", 1, \"selu\", params.dropval)\n    unle_res_1 = keras.layers.BatchNormalization()(dec_2)\n    unle_1 = keras.layers.Add()([unle_res_1, unle_1])\n    unle_2 = convolution_block(unle_1, 64, 5, \"same\", 1, \"selu\", params.dropval)\n    unle_3 = convolution_block(unle_2, 1, 5, \"same\", 1, \"linear\", params.dropval, name=\"unle\")\n\n    # tau branch\n    tau_1 = convolution_block(dec_3, 64, 5, \"same\", 1, \"selu\", params.dropval)\n    tau_res_1 = keras.layers.BatchNormalization()(dec_2)\n    tau_1 = keras.layers.Add()([tau_res_1, tau_1])\n    tau_2 = convolution_block(tau_1, 64, 5, \"same\", 1, \"selu\", params.dropval)\n    tau_3 = convolution_block(tau_2, 1, 5, \"same\", 1, \"linear\", params.dropval, name=\"tau\")\n\n    # alpha branch\n    cbf_1 = convolution_block(dec_3, 64, 5, \"same\", 1, \"selu\", params.dropval)\n    cbf_res_1 = keras.layers.BatchNormalization()(dec_2)\n    cbf_1 = keras.layers.Add()([cbf_res_1, cbf_1])\n    cbf_2 = convolution_block(cbf_1, 64, 5, \"same\", 1, \"selu\", params.dropval)\n    cbf_3 = convolution_block(cbf_2, 1, 5, \"same\", 1, \"linear\", params.dropval, name=\"cbf\")\n\n    model = keras.models.Model(inputs=[input_img1, input_img2], outputs=[tau_3, unle_3, kappa_3, cbf_3])\n    return model\n\n", "meta": {"hexsha": "ed9b4aac77063e460ad7b8531cc9cf69ec9a042c", "size": 12872, "ext": "py", "lang": "Python", "max_stars_repo_path": "resunet/resunet.py", "max_stars_repo_name": "EEmGuzman/resunet-cmb", "max_stars_repo_head_hexsha": "e21626ddfc226689501e8d143e2fb0875ca912d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-01-13T19:07:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T16:15:25.000Z", "max_issues_repo_path": "resunet/resunet.py", "max_issues_repo_name": "EEmGuzman/resunet-cmb", "max_issues_repo_head_hexsha": "e21626ddfc226689501e8d143e2fb0875ca912d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "resunet/resunet.py", "max_forks_repo_name": "EEmGuzman/resunet-cmb", "max_forks_repo_head_hexsha": "e21626ddfc226689501e8d143e2fb0875ca912d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-03-12T14:44:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T11:16:45.000Z", "avg_line_length": 44.6944444444, "max_line_length": 184, "alphanum_fraction": 0.671923555, "include": true, "reason": "import numpy", "num_tokens": 3618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.18759004810785965}}
{"text": "#   ZEROPOINT CALCULATION\n#   19.03.09    MERRY CHRISTMAS!\n#   MADE BY GREGORY S.H. PAEK\n#\tUPDATE : 20.01.16\n#=========================================================================#\n# import os, glob, subprocess\nimport numpy as np\nfrom imsng import tool_tbd\n# from astropy.table import Table\nfrom astropy.table import vstack\nimport matplotlib.pyplot as plt\n# from numba import jit\ndef which_obs(obs, path_and_file):\n\t\"\"\"\n\t=====================================================================\n\tGIVE CCD INFORMATION\n\t---------------------------------------------------------------------\n\tINPUT   :   observatory name, and path+table_name(ascii format)\n\t\t\t\ti.e.) path_and_file='/home/sonic/Research/table/obs.txt'\n\tOUTPUT  :   GAIN        []\n\t\t\t\tPixel Scale [\"/pix]\n\t---------------------------------------------------------------------\n\tobs         ccd         gain    RDnoise     dark    pixelscale\n\tSOAO        FLI         1.43    13.60       0.0     0.44540\n\tLOAO        E2V         2.68    4.84        0.0     0.794\n\tLOAO_FLI    FLI         3       15.0        0.0     1.28\n\tDOAO_sophia PIsophia    0.928   7.63        0.0     0.3855\n\tDOAO        FLI         1.27    14.0        0.005   0.464\n\toldBOAO     UNKNOWN     8.9     20.0        0.0     1.7\n\tBOAO        UNKNOWN     5.0     2.0         0.0     0.2145\n\tBOAO        UNKNOWN     5.0     5.0         0.0     0.2145    \n\tSAO         SBIG        1.35    9.0         0.0     0.31\n\t30inch      UNKNOWN     1.60    5.87        0.0     1.3553\n\tCCA250      MLI16803    1.46    10.35       0.0     2.06\n\tMAIDANAK    SNU4kCAM    1.45    4.7         0.0     0.266\n\tMAIDANAK    UNKNOWN     5.40    9.0         0.0     0.266\n\tLSGT        SNUCAMII    1.15    6.0         0.2     0.92\n\tUKIRT       WFCAM       99.0    0.0         0.0     0.4\n\t=====================================================================\n\t\"\"\"\n\timport numpy as np\n\tfrom astropy.io import ascii\n\tobsinfo     = ascii.read(path_and_file)\n\tindx_obs    = np.where( obs == obsinfo['obs'] )\n\tgain        = obsinfo['gain'][indx_obs]\n\tpixscale    = obsinfo['pixelscale'][indx_obs]\n\treturn gain, pixscale\n\n#-------------------------------------------------------------------------#\ndef image_list(imlist):\n\t\"\"\"\n\tINPUT   :   imlist = glob.glob('Calib-*.fits')\n\tOUTPUT  :   observatory list\n\t\t\t\tobject list\n\t\t\t\tfillter list\n\t\"\"\"\n\tobslist = []\n\tobjlist = []\n\tfillist = []\n\tfor img in imlist:\n\t\tsp  = img.split('-')\n\t\tobslist.append(sp[1])\n\t\tobjlist.append(sp[2])\n\t\tfillist.append(sp[5])\n\tobslist = list(set(obslist))\n\tobjlist = list(set(objlist))\n\tfillist = list(set(fillist))\n\treturn obslist, objlist, fillist\n\n\n#-------------------------------------------------------------------------#\ndef secom(inim, gain, pixscale, zp=0, seeing=3, det_sigma=3, backsize=str(64), backfiltersize=str(3), psf=False, dual=False, detect='detection.fits', check=False):\n\t\"\"\"\n\tSourceEXtractor\n\tAPERTURE    3\", 5\", 7\",\n\t\t\t\t1.0seeing, 1.2seeing ,1.5seeing ,1.7seeing ,2.0seeeing\n\tINPUT   :   (image).fits\n\t\t\t\taperture    []\n\t\t\t\tseeing_fwhm [pixel]\n\tOUTPUT  :   no return\n\t\t\t\t.cat\n\t\"\"\"\n\timport numpy as np\n\timport os\n\tfrom astropy.io import ascii\n\t#   FILE CHECK\n\t#\tCONFIG FILES (USER BASE PATH)\n\tconfigfile      = '/home/sonic/Research/yourpy/config/targetphot.sex'\n\tparamfile       = '/home/sonic/Research/yourpy/config/targetphot.param'\n\tnnwfile\t\t    = '/home/sonic/Research/yourpy/config/targetphot.nnw'\n\tconvfile\t    = '/home/sonic/Research/yourpy/config/targetphot.conv'\n\ttry:\n\t\tcomment = 'SourceEXtractor START\\n' \\\n\t\t\t\t+ 'IMAGE\\t\\t: '+inim+'\\n' \\\n\t\t\t\t+ 'GAIN\\t\\t: '+str(gain)+'\\n' \\\n\t\t\t\t+ 'PIXSCALE\\t: '+str(pixscale)+'\\n' \\\n\t\t\t\t+ 'DETECTION SIGMA\\t: '+str(det_sigma)+'\\n' \\\n\t\t\t\t+ 'PARAM\\t\\t: '+paramfile+'\\n' \\\n\t\t\t\t+ 'BACKSIZE\\t: '+backsize+'\\n' \\\n\t\t\t\t+ 'BACKFILTER\\t: '+backfiltersize+'\\n' \\\n\t\t\t\t+ 'CONFIG\\t\\t: '+configfile+'\\n' \\\n\t\t\t\t+ 'NNW\\t\\t: '+nnwfile+'\\n' \\\n\t\t\t\t+ 'CONVOLVE\\t: '+convfile\n\t\tprint(comment)\n\texcept:\n\t\tcomment = 'CHECK configfile/paramfile/nnewfile/convfile or others.'\n\t\tprint(comment)\n\t#   FILE NAME\n\tcat     = inim[:-5]+'.cat'\n\tseg     = inim[:-5]+'.seg.fits'\n\tbkg     = inim[:-5]+'.bkg.fits'\n\tsub     = inim[:-5]+'.sub.fits'\n\timpsf   = inim[:-5]+'.psf'\n\taper    = inim[:-5]+'.aper.fits'\n\n\t#   BASIC INFO.\n\tdet_area        = 5\n\tdet_thresh      = det_sigma/np.sqrt(det_area)\n\tdetecminarea    = str(det_area)\n\tdetectthresh    = str(det_thresh)\n\t#   OPTION\n\taperture        = '%.2f'%(3./pixscale)+','+'%.2f'%(5./pixscale)+','+'%.2f'%(7./pixscale)+','+'%.2f'%(seeing)+','+'%.2f'%(1.2*seeing)+','+'%.2f'%(1.5*seeing)+','+'%.2f'%(1.7*seeing)+','+'%.2f'%(2.0*seeing)\n\toption0\t= ' -MAG_ZEROPOINT {} '.format(zp)\n\toption1 = ' -CATALOG_NAME '+cat+' -PARAMETERS_NAME '+paramfile\n\toption2 = ' -DETECT_MINAREA '+detecminarea+' -DETECT_THRESH '+detectthresh \\\n\t\t\t+' -FILTER Y '+'-FILTER_NAME '+convfile\n\toption3 = ' -PHOT_APERTURES '+aperture \\\n\t\t\t+' -GAIN '+'%.1f'%(gain)+' -PIXEL_SCALE '+'%.1f'%(pixscale)\n\t#option4 = ' -SEEING_FWHM '+'%.3f'%(seeing)+' -STARNNW_NAME '+nnwfile\n\toption4 = ' -SEEING_FWHM '+'%.3f'%(seeing)+' -STARNNW_NAME '+nnwfile\n\toption5 = ' -BACK_SIZE '+ backsize \\\n\t\t\t+ ' -BACK_FILTERSIZE '+ backfiltersize+' -BACKPHOTO_TYPE LOCAL'\n\toption6 = ' -CHECKIMAGE_TYPE SEGMENTATION,APERTURES,BACKGROUND,-BACKGROUND'\n\toption7 = ' -CHECKIMAGE_NAME '+seg+','+aper+','+','+bkg+','+sub\n\tif psf\t!= False:\n\t\toption8 = ' -PSF_NAME '+impsf\n\telse:\n\t\toption8 = ''\n\t#   COMMAND\n\t#   detect = detection.fits is fine image show target significantly and have good seeing and many stars i\n\tdualcom ='sex -c '+configfile+' '+detect+' , '+inim+' -CATALOG_NAME dual'+cat+' -PARAMETERS_NAME '+paramfile+ ' '+option0+' '+option2+' '+option3+' '+option4+' '+option5+' '+option6+' '+option7+' '+option8\n\tsglcom  ='sex -c '+configfile+' '+inim+' '+option0+' '+option1+' '+option2+' '+option3+' '+option4+' '+option5+' '+option6+' '+option7+' '+option8\n\tclearcom='sex -c '+configfile+' '+inim+' '+option0+' '+option1+' '+option2+' '+option3+' '+option4+' '+option5+' '+option8\n\tif dual == False    :\n\t\tif check == False:\n\t\t\tos.system(clearcom)\n\t\telse:\n\t\t\tos.system(sglcom)\n\telse                : os.system(dualcom)\n\t\t\n\tsecat   = ascii.read(cat)\n\treturn secat, cat\n#-------------------------------------------------------------------------#\ndef psfex(inim, pixscale):\n\t\"\"\"\n\tPSfextractor\n\tINPUT   :   (image).fits\n\tOUTPUT  :   FWHM    [pixel]\n\t\t\t\tFWHM    [arcsec]\n\t\"\"\"\n\timport os\n   \n\t#   FILE CHECK\n\t#\tCONFIG FILES (USER BASE PATH)\n\tpsfexconf_prese_conf    = '/home/sonic/Research/yourpy/config/prepsfex.sex'\n\tpsfexconf_prese_param   = '/home/sonic/Research/yourpy/config/prepsfex.param'\n\tpsfexconf_psfex_conf    = '/home/sonic/Research/yourpy/config/default.psfex'\n\tpsfexconf_psfex_conv    = '/home/sonic/Research/yourpy/config/default.conv'\n\ttry:\n\t\tcomment = '\\nPSFex START\\n' \\\n\t\t\t\t+ 'IMAGE\\t\\t: '+inim+'\\n' \\\n\t\t\t\t+ 'PRE_CONFIG\\t: '+psfexconf_prese_conf+'\\n' \\\n\t\t\t\t+ 'PRE_PARAM\\t: '+psfexconf_prese_param+'\\n' \\\n\t\t\t\t+ 'CONFIG\\t\\t: '+psfexconf_psfex_conf+'\\n' \\\n\t\t\t\t+ 'CONV\\t\\t: '+psfexconf_psfex_conv\n\t\tprint(comment)\n\texcept:\n\t\tcomment = 'CHECK psfexconf_prese/psfexconf_prese_param/psfexconf_psfex_conf/psfexconf_psfex_conv OR OTHERS.'\n\t\tprint(comment)\n\n\t#   FILE NAME\n\tcat     = inim[:-5]+'.cat'\n\txml     = inim[:-5]+'.xml'\n\tsnap    = 'snap_'+inim+'[100:125,100:125]'\n\tpsf     = 'psf-'+inim\n\t#   OPTION\n\tpresecom1   = psfexconf_prese_conf+\" \"+inim\n\tpresecom2   = \" -CATALOG_NAME \"+cat\n\tpresecom3   = \" -FILTER_NAME \" + psfexconf_psfex_conv + \" -PARAMETERS_NAME \" + psfexconf_prese_param\n\t#   COMMAND\n\tpresecom    = \"sex -c \"+presecom1+presecom2+presecom3\n\tpsfexcom    = \"psfex -c \"+psfexconf_psfex_conf+\" \"+cat\n\tos.system(presecom)\n\tos.system(psfexcom) \n\tos.system('cp psfex.xml '+xml)\n\t#   SNAP IMAGE\n\timcopycom   = 'imcopy '+snap+' '+psf\n\tprint(imcopycom);   os.system(imcopycom)\n\t#   FWHM [pixel], FWHM [arcsec]\n\tfwhm_pix    = psfexxml(xml)\n\tfwhm_arcsec = round(fwhm_pix*pixscale, 3)\n\tcomment     = '\\n' \\\n\t\t\t\t+ 'FILE NAME'+'\\t'+': '+inim+'\\n' \\\n\t\t\t\t+ 'FWHM value'+'\\t'+': '+str(fwhm_pix)+'\\t'+'[pixel]'+'\\n' \\\n\t\t\t\t+ '\\t'+'\\t'+': '+str(fwhm_arcsec)+'\\t'+'[arcsec]'+'\\n'\n\tprint(comment)\n\treturn fwhm_pix, fwhm_arcsec\n#------------------------------------------------------------\ndef sexcom(inim, param_insex, dualmode=False):\n\t'''\n\t\n\t'''\n\tparam_sex = dict(\tCONF_NAME = 'default.sex',\n\t\t\t\t\t\t#------------------------------\n\t\t\t\t\t\t#\tCATALOG\n\t\t\t\t\t\t#------------------------------\n\t\t\t\t\t\tCATALOG_NAME = 'test.cat',\n\t\t\t\t\t\tCATALOG_TYPE = 'ASCII_HEAD',\n\t\t\t\t\t\tPARAMETERS_NAME = 'default.param',\n\t\t\t\t\t\t#------------------------------\n\t\t\t\t\t\t#\tEXTRACTION\n\t\t\t\t\t\t#------------------------------\n\t\t\t\t\t\tDETECT_TYPE = 'CCD',\n\t\t\t\t\t\tDETECT_MINAREA = '5',\n\t\t\t\t\t\tDETECT_MAXAREA = '0',\n\t\t\t\t\t\tDETECT_THRESH = '1.5',\n\t\t\t\t\t\t# ANALYSIS_THRESH = 'RELATIVE',\n\t\t\t\t\t\tANALYSIS_THRESH = '1.5',\t\t\t\t\t\t\n\t\t\t\t\t\tFILTER = 'Y',\n\t\t\t\t\t\tFILTER_NAME = 'default.conv',\n\t\t\t\t\t\tDEBLEND_NTHRESH = '64',\n\t\t\t\t\t\tDEBLEND_MINCONT = '0.0001',\n\t\t\t\t\t\tCLEAN = 'Y',\n\t\t\t\t\t\tCLEAN_PARAM = '1.0',\n\t\t\t\t\t\tMASK_TYPE = 'CORRECT',\n\t\t\t\t\t\t#------------------------------\n\t\t\t\t\t\t#\tPHOTOMETRY\n\t\t\t\t\t\t#------------------------------\n\t\t\t\t\t\t# PHOT_APERTURES = '3',\n\t\t\t\t\t\tPHOT_AUTOPARAMS = '2.5,3.5',\n\t\t\t\t\t\tPHOT_PETROPARAMS = '2.0,3.5',\n\t\t\t\t\t\tSATUR_LEVEL  = '50000.0',\n\t\t\t\t\t\tSATUR_KEY = 'SQTURATE',\n\t\t\t\t\t\tMAG_ZEROPOINT = '0.0',\n\t\t\t\t\t\tMAG_GAMMA = '4.0',\n\t\t\t\t\t\tGAIN = '1.0',\n\t\t\t\t\t\tGAIN_KEY = 'GAIN',   \n\t\t\t\t\t\tPIXEL_SCALE = '1.0',\n\t\t\t\t\t\t#------------------------------\n\t\t\t\t\t\t#\tSTAR/GALAXY SEPARATION\n\t\t\t\t\t\t#------------------------------\n\t\t\t\t\t\tSEEING_FWHM = '3.0',\n\t\t\t\t\t\tSTARNNW_NAME = 'default.nnw',\n\t\t\t\t\t\t#------------------------------\n\t\t\t\t\t\t#\tBACKGROUND\n\t\t\t\t\t\t#------------------------------\n\t\t\t\t\t\tBACK_SIZE = '128',\n\t\t\t\t\t\tBACK_FILTERSIZE = '10',\n\t\t\t\t\t\tBACKPHOTO_TYPE = 'LOCAL',\n\t\t\t\t\t\t#------------------------------\n\t\t\t\t\t\t#\tCHECK IMAGE\n\t\t\t\t\t\t#------------------------------\n\t\t\t\t\t\tCHECKIMAGE_TYPE = 'NONE',\n\t\t\t\t\t\tCHECKIMAGE_NAME = 'check.fits',\n\t\t\t\t\t\t#==============================\n\t\t\t\t\t\t#\tMEMORY & MISCELLANEOUS\n\t\t\t\t\t\t#==============================\n\t\t\t\t\t\tMEMORY_OBJSTACK = '3000',\n\t\t\t\t\t\tMEMORY_PIXSTACK = '300000',\n\t\t\t\t\t\tMEMORY_BUFSIZE = '1024',\n\t\t\t\t\t\tVERBOSE_TYPE = 'NORMAL',\n\t\t\t\t\t\tHEADER_SUFFIX = '.head',\n\t\t\t\t\t\tWRITE_XML = 'N',\n\t\t\t\t\t\tXML_NAME = 'sex.xml')\n\n\tfor key in param_insex.keys():\n\t\tparam_sex[key] = param_insex[key]\n\n\t\n\tsexcom_normal = 'sex -c {} {} '.format(param_sex['CONF_NAME'], inim)\n\tsexcom_dual = 'sex -c {} {} '.format(param_sex['CONF_NAME'], inim)\n\tfor key in param_sex.keys():\n\t\tif key != 'CONF_NAME':\n\t\t\tsexcom_normal += '-{} {} '.format(key, param_sex[key])\n\n\t# print(sexcom_normal)\n\t# os.system(sexcom_normal)\n\treturn sexcom_normal\n\ndef psfexxml(xmlfile):\n\t\"\"\"\n\tINPUT   :   .xml\n\tOUTPUT  :   FWHM    [pixel]\n\t\"\"\"\n\tfrom astropy.io.votable import parse\n\tfrom astropy.table import Table, Column, MaskedColumn\n\tvotable     = parse(xmlfile)\n\ttable       = votable.get_first_table()\n\tdata        = table.array\n\t#   EXTRACT FWHM [pixel]\n\tfwhm        = data['FWHM_Mean'][0]\n\tfwhm        = round(fwhm, 3)\n\treturn fwhm\n#-------------------------------------------------------------------------#\n#def matching(incat, refcat, sep=2.0):\ndef matching(intbl, reftbl, inra, indec, refra, refdec, sep=2.0):\n\t\"\"\"\n\tMATCHING TWO CATALOG WITH RA, Dec COORD. WITH python\n\tINPUT   :   SE catalog, SDSS catalog file name, sepertation [arcsec]\n\tOUTPUT  :   MATCED CATALOG FILE & TABLE\n\t\"\"\"\n\timport numpy as np\n\timport astropy.units as u\n\t# from astropy.table import Table, Column\n\tfrom astropy.coordinates import SkyCoord\n\tfrom astropy.io import ascii\n\n\tincoord\t\t= SkyCoord(inra, indec, unit=(u.deg, u.deg))\n\trefcoord\t= SkyCoord(refra, refdec, unit=(u.deg, u.deg))\n\n\t#   INDEX FOR REF.TABLE\n\tindx, d2d, d3d  = incoord.match_to_catalog_sky(refcoord)\n\tmreftbl\t\t\t= reftbl[indx]\n\tmreftbl['sep']\t= d2d\n\tmergetbl\t\t= intbl\n\tfor col in mreftbl.colnames:\n\t\tmergetbl[col]\t= mreftbl[col]\n\tindx_sep\t\t= np.where(mergetbl['sep']*3600.<sep)\n\tmtbl\t\t\t= mergetbl[indx_sep]\n\t#mtbl.write(mergename, format='ascii', overwrite=True)\n\treturn mtbl\n#-------------------------------------------------------------------------#\ndef star4zp(intbl, inmagerkey, refmagkey, refmagerkey, \n\trefmaglower=14., refmagupper=17., refmagerupper=0.05,\n\tinmagerupper=0.1, flagcut=0, verbose=False, plot=False, plotout='zphist.png'):\n\t\"\"\"\n\tSELECT STARS FOR USING ZEROPOINT CALCULATION\n\tINPUT   :   TABLE, IMAGE MAG.ERR KEYWORD, REF.MAG. KEYWORD, REF.MAG.ERR KEYWORD\n\tOUTPUT  :   NEW TABLE\n\t\"\"\"\n\t# import numpy as np\n\n\tindx_flag = np.where( intbl['FLAGS'] <= flagcut )\n\tindx_refmag = np.where(\t(intbl[refmagkey] <= refmagupper) &\n\t\t\t\t\t\t\t(intbl[refmagkey] >= refmaglower))\n\tindx_refmager = np.where( intbl[refmagerkey] <= refmagerupper )\n\tindx_mager = np.where( intbl[inmagerkey] <= inmagerupper )\n\n\tindx_all = np.where((intbl['FLAGS'] <= flagcut) & \n\t\t\t\t\t\t(intbl[refmagkey] < refmagupper) & \n\t\t\t\t\t\t(intbl[refmagkey] > refmaglower) & \n\t\t\t\t\t\t(intbl[refmagerkey] < refmagerupper) &\n\t\t\t\t\t\t(intbl[inmagerkey] < inmagerupper) )\n\n\tnewtbl  = intbl[indx_all]\n\tcomment = '-'*50+'\\n' \\\n\t\t\t+ 'ALL\\t\\t\\t\\t\\t: {}\\n'.format(len(intbl)) \\\n\t\t\t+ '-'*50+'\\n' \\\n\t\t\t+ 'FLAG(<={})\\t\\t\\t\\t: {}\\n'.format(flagcut, len(indx_flag[0])) \\\n\t\t\t+ '{} REF. MAGCUT ({}-{})\\t\\t: {}\\n'.format(refmagkey, refmaglower, refmagupper, len(indx_refmag[0])) \\\n\t\t\t+ '{} REF. MAGERR CUT < {}\\t\\t: {}\\n'.format(refmagerkey, refmagerupper, len(indx_refmager[0])) \\\n\t\t\t+ '{} CUT < {}\\t\\t: {}\\n'.format(inmagerkey, inmagerupper, len(indx_mager[0])) \\\n\t\t\t+ '='*50+'\\n' \\\n\t\t\t+ 'TOTAL #\\t\\t\\t\\t\\t: {}\\n'.format(len(newtbl)) \\\n\t\t\t+ '='*50\n\tif verbose != False:\n\t\tprint(comment)\n\t'''\n\tif plot!=False:\n\t\t# import matplotlib.pyplot as plt\n\t\tplt.close('all')\n\t\tplt.rc('font', family='serif')\n\t\tfig = plt.figure()\n\t\tx = 1080 / fig.dpi\n\t\ty = 1080 / fig.dpi\n\t\tfig.set_figwidth(x)\n\t\tfig.set_figheight(y)\n\t\t#-------------------------------------------------------------\n\t\tplt.subplot(221)\n\t\tplt.title('FLAGS')\n\n\t\tbins = np.arange(np.min(intbl['FLAGS']), np.max(intbl['FLAGS'])+0.2, 0.2)\n\t\tplt.hist(intbl['FLAGS'], bins=bins, color='tomato', alpha=0.5,)\n\t\t\t\t# label='{}/{}'.format(len(intbl[indx_flag]), len(intbl)))\n\t\tplt.hist(intbl['FLAGS'][indx_flag], bins=bins, color='dodgerblue', alpha=0.75,\n\t\t\t\tlabel='{}/{}'.format(len(intbl[indx_flag]), len(intbl)))\n\t\tplt.minorticks_on()\n\t\tplt.grid(color='grey', alpha=0.5, linestyle='--')\n\t\tplt.legend()\n\t\t#-------------------------------------------------------------\n\t\tplt.subplot(222)\n\t\tplt.title('{} MAG'.format(refmagkey))\n\t\tbins = np.arange(np.min(intbl[refmagkey]), np.max(intbl[refmagkey])+0.1, 0.1)\n\t\tplt.hist(intbl[refmagkey], bins=bins, color='tomato', alpha=0.5)\n\n\t\tplt.hist(intbl[refmagkey][indx_refmag], bins=bins, color='dodgerblue', alpha=0.75,\n\t\t\t\tlabel='{}/{}'.format(len(intbl[indx_refmag]), len(intbl)))\n\t\tplt.axvline(x=refmaglower, linestyle='--', color='k',)\n\t\tplt.axvline(x=refmagupper, linestyle='--', color='k',)\n\n\t\tplt.minorticks_on()\n\t\tplt.grid(color='grey', alpha=0.5, linestyle='--')\n\t\tplt.legend()\n\t\t#-------------------------------------------------------------\n\t\tplt.subplot(223)\n\t\tplt.title('{}'.format(refmagerkey))\n\t\tbins = np.arange(np.min(intbl[refmagerkey]), np.max(intbl[refmagerkey])+0.001, 0.001)\n\t\tplt.hist(intbl[refmagerkey], bins=bins, color='tomato', alpha=0.5)\n\n\t\tplt.hist(intbl[refmagerkey][indx_refmager], bins=bins, color='dodgerblue', alpha=0.75,\n\t\t\t\tlabel='{}/{}'.format(len(intbl[indx_refmager]), len(intbl)))\n\t\tplt.axvline(x=refmagerupper, linestyle='--', color='k',)\n\t\tplt.minorticks_on()\n\t\tplt.grid(color='grey', alpha=0.5, linestyle='--')\n\t\tplt.legend()\n\t\t#-------------------------------------------------------------\n\t\tplt.subplot(224)\n\t\tplt.title('{}'.format(inmagerkey))\n\t\tbins = np.arange(np.min(intbl[inmagerkey]), np.max(intbl[inmagerkey])+0.01, 0.01)\n\t\tplt.hist(intbl[inmagerkey], bins=bins, color='tomato', alpha=0.5)\n\t\tplt.hist(intbl[inmagerkey][indx_mager], bins=bins, color='dodgerblue', alpha=0.75,\n\t\t\t\tlabel='{}/{}'.format(len(intbl[indx_mager]), len(intbl)))\n\t\tplt.axvline(x=inmagerupper, linestyle='--', color='k',)\n\t\t# plt.xlim([0.0, 1.0])\n\t\tplt.minorticks_on()\n\t\tplt.grid(color='grey', alpha=0.5, linestyle='--')\n\t\tplt.legend()\n\t\t#-------------------------------------------------------------\n\t\tplt.tight_layout()\n\t\t# plt.savefig(plotout, dpi=300)\n\t\tplt.savefig(plotout)\n\t'''\n\treturn newtbl\n#-------------------------------------------------------------------------#\n# @jit\ndef zpcal(intbl, inmagkey, inmagerkey, refmagkey, refmagerkey, sigma=2.0, method='default'):\n\t\"\"\"\n\tZERO POINT CALCULATION\n\t3 SIGMA CLIPPING (MEDIAN)\n\n\timport matplotlib.pyplot as plt\n\tfrom numpy import median\n\timport numpy as np\n\t\"\"\"\n\tfrom astropy.stats import sigma_clip\n\t#\tREMOVE BLANK ROW (=99)\t\n\tindx_avail      = np.where( (intbl[inmagkey] != 99) & (intbl[refmagkey] != 99) )\n\tintbl           = intbl[indx_avail]\n\tzplist          = np.copy(intbl[refmagkey] - intbl[inmagkey])\n\tintbl['zp']\t\t= zplist\n\t#\tSIGMA CLIPPING\n\tzplist_clip     = sigma_clip(zplist, sigma=sigma, maxiters=None, cenfunc=np.median, copy=False)\n\tindx_alive      = np.where( zplist_clip.mask == False )\n\tindx_exile      = np.where( zplist_clip.mask == True )\n\t#\tRE-DEF. ZP LIST AND INDEXING CLIPPED & NON-CLIPPED\n\tintbl_alive     = intbl[indx_alive]\n\tintbl_exile     = intbl[indx_exile]\n\t#\tZP & ZP ERR. CALC.\n\tif method == 'default':\n\t\tzp              = np.median(np.copy(intbl_alive['zp']))\n\t\tzper\t\t\t= np.std(np.copy(intbl_alive['zp']))\n\telif method == 'weightedmean':\n\t\tprint(method)\n\t\tmager = sqsum(intbl_alive[inmagerkey], intbl_alive[refmagerkey])\n\t\tw0 = 1/mager\n\t\tw = w0/np.sum(w0)\n\t\tzp = np.sum(w*intbl_alive['zp'])/np.sum(w)\n\t\tzper = 1/np.sqrt(np.sum(w))\n\treturn zp, zper, intbl_alive, intbl_exile\n#-------------------------------------------------------------------------#\n# def zpplot(outname, alltbl, otbl, xtbl, inmagkey, inmagerkey, refmagkey, refmagerkey, zp, zper, refmaglower, refmagupper):\ndef zpplot(outname, otbl, xtbl, inmagkey, inmagerkey, refmagkey, refmagerkey, zp, zper, refmaglower, refmagupper):\n\t# import numpy as np\n\t# import matplotlib.pyplot as plt\n\t#   FILE NAME\n\tplt.close('all')\n\tplt.rc('font', family='serif')\n\tfig = plt.figure()\n\tx = 1920 / 2 / fig.dpi\n\ty = 1080 / 2 / fig.dpi\n\t# x = 1920 / 4 / fig.dpi\n\t# y = 1080 / 4 / fig.dpi\n\tfig.set_figwidth(x)\n\tfig.set_figheight(y)\n\n\talltbl = vstack([otbl, xtbl])\n\t# plt.rcParams.update({'font.size': 16})\n\tplt.axhline(\n\t\t\t\tzp,\n\t\t\t\tlinewidth=2, linestyle='-', color='gray',\n\t\t\t\tlabel= r'ZP={}$\\pm${}'.format(round(zp, 3), round(zper, 3))\n\t\t\t\t)\n\tplt.fill_between(\n\t\t\t\t\t\t# [np.min(otbl[refmagkey])-0.05, np.max(otbl[refmagkey])+0.05],\n\t\t\t\t\t\t[np.min(alltbl[refmagkey]), np.max(alltbl[refmagkey])],\n\t\t\t\t\t\tzp-zper, zp+zper,\n\t\t\t\t\t\tcolor='silver', alpha=0.3\n\t\t\t\t\t)\n\t# plt.errorbar(\t\n\t# \t\t\t\talltbl[refmagkey], alltbl['zp'],\n\t# \t\t\t\tyerr=tool_tbd.sqsum(alltbl[inmagerkey], alltbl[refmagerkey]),\n\t# \t\t\t\tc='silver', ms=6, marker='.', ls='',\n\t# \t\t\t\tcapsize=2.5, capthick=1,\n\t# \t\t\t\tlabel='All stars ({})'.format(len(alltbl)), alpha=0.25,\n\t# \t\t\t)\n\tplt.errorbar(\t\n\t\t\t\t\totbl[refmagkey], otbl['zp'],\n\t\t\t\t\tyerr=tool_tbd.sqsum(otbl[inmagerkey], otbl[refmagerkey]),\n\t\t\t\t\tc='dodgerblue', ms=6, marker='o', ls='',\n\t\t\t\t\tcapsize=5, capthick=1,\n\t\t\t\t\tlabel='Used stars ({})'.format(len(otbl)), alpha=0.5,\n\t\t\t\t)\n\t# plt.scatter( xtbl[refmagkey], xtbl['zp'], color='tomato', s=50, marker='x', linewidth=1, alpha=1.0, label='CLIPPED ({})'.format(len(xtbl)) )\n\tplt.errorbar(\t\n\t\t\t\t\txtbl[refmagkey], xtbl['zp'],\n\t\t\t\t\tyerr=tool_tbd.sqsum(xtbl[inmagerkey], xtbl[refmagerkey]),\n\t\t\t\t\tc='tomato', ms=6, marker='x', ls='',\n\t\t\t\t\tcapsize=5, capthick=1,\n\t\t\t\t\tlabel='Clipped stars ({})'.format(len(xtbl)), alpha=0.5,\n\t\t\t\t)\n\tplt.axhline(\n\t\t\t\tzp+zper,\n\t\t\t\tlinewidth=2, linestyle='-.', color='gray', alpha=0.5,\n\t\t\t\tlabel='Clip upper ({})'.format(len(xtbl[xtbl['zp']>zp+zper])),\n\t\t\t\t)\n\tplt.axhline(\n\t\t\t\tzp-zper,\n\t\t\t\tlinewidth=2, linestyle='--', color='gray', alpha=0.5,\n\t\t\t\tlabel='Clip lower ({})'.format(len(xtbl[xtbl['zp']<zp-zper])),\n\t\t\t\t)\n\tplt.axvline(x=refmaglower, linestyle='--', color='k', alpha=0.5)\n\tplt.axvline(x=refmagupper, linestyle='--', color='k', alpha=0.5)\n\t# plt.xlim(np.min(otbl[refmagkey])-0.05, np.max(otbl[refmagkey])+0.05)\n\t# plt.ylim(zp-0.5, zp+0.5)\n\t#\tSETTING\n\tplt.title(outname, {'fontsize': 12})\n\tplt.gca().invert_yaxis()\n\tplt.xlabel('REF.MAG.', {'color': 'black', 'fontsize': 20})\n\tplt.ylabel('ZP [AB]', {'color': 'black', 'fontsize': 20})\n\tplt.legend(loc='best', prop={'size': 14}, edgecolor=None)\n\tplt.tight_layout()\n\tplt.minorticks_on()\n\tplt.savefig(outname)\n\t#\tPRINT\n\tprint('MAG TYP     : '+inmagkey)\n\tprint('ZP          = '+str(round(zp, 3)))\n\tprint('ZP ERR      = '+str(round(zper, 3)))\n\tprint('STD.NUMB    = '+str(int(len(otbl))))\n\tprint('REJ.NUMB    = '+str(int(len(xtbl))))\n\tprint('CLIP UPPER  = {}'.format(len(xtbl[xtbl['zp']>zp+zper])))\n\tprint('CTIP LOWER  = {}'.format(len(xtbl[xtbl['zp']<zp-zper])))\n#-------------------------------------------------------------------------#\ndef bkgest_mask(inim):\n\t'''\n\t'''\n\timport numpy as np\n\tfrom astropy.io import fits\n\tfrom photutils import make_source_mask\n\tfrom numpy import mean,median\n\tfrom astropy.stats import sigma_clipped_stats\n\t\n\tdata    =fits.getdata(inim)\n\t# mask    = make_source_mask(data, snr=3, npixels=5, dilate_size=11)\n\tmask    = make_source_mask(data, nsigma=3, npixels=5, dilate_size=11)\n\tmean, median, std = sigma_clipped_stats(data, sigma=3.0, mask=mask)\n\treturn mean, median, std\n#-------------------------------------------------------------------------#\ndef limitmag(N, zp, aper, skysigma):\t\t\t# 3? 5?, zp, diameter [pixel], skysigma\n\timport numpy as np\n\tR           = float(aper)/2.\t\t\t\t# to radius\n\tbraket      = N*skysigma*np.sqrt(np.pi*(R**2))\n\tupperlimit  = float(zp)-2.5*np.log10(braket)\n\treturn round(upperlimit, 3)\n#-------------------------------------------------------------------------#\n'''\ndef targetfind(ra1, de1, ra2, de2, sep):\n\n\timport numpy as np\n\tdist\t= np.sqrt( (ra1-ra2)**2. + (de1-de2)**2. )\n\tindx\t= np.where( (dist == np.min(dist)) &\n\t\t\t\t\t\t(dist < sep/3600.) )\n\treturn indx\n'''\n#-------------------------------------------------------------------------#\ndef plotshow(inim, numb_list, xim_list, yim_list, outname='default', add=None, numb_addlist=None, xim_addlist=None, yim_addlist=None, invert=False):\n\t'''\n\tPLOT IMAGE AND SHOW DESINATED OBJECTS\n\t'''\n\timport numpy as np\n\timport matplotlib.pyplot as plt\n\tfrom astropy.io import fits\n\tfrom matplotlib.colors import LogNorm\n\tfrom matplotlib.patches import Circle\n\tfrom astropy.visualization import (MinMaxInterval, SqrtStretch, ImageNormalize)\n\tfrom astropy.visualization import ZScaleInterval, LinearStretch\n\tfrom astropy.wcs import WCS\n\tif outname == 'default':\n\t\toutname\t\t= inim[:-5]+'.png'\n\telse:\n\t\tpass\n\tdata, hdr\t= fits.getdata(inim, header=True)\n\tif invert == True:\n\t\tdata = -1*data\n\t#fig, ax\t\t= plt.subplots(1)\n\n\tplt.close('all')\n\tplt.rc('font', family='serif')\n\tfig = plt.figure()\n\tx = 1080 / 2 / fig.dpi\n\ty = 1080 / 2 / fig.dpi\n\tfig.set_figwidth(x)\n\tfig.set_figheight(y)\n\n\twcs\t\t\t= WCS(hdr)\n\tnorm_zscale\t= ImageNormalize(data, interval=ZScaleInterval(), stretch=LinearStretch())\n\t# fig\t\t\t= plt.figure() \n\tax\t\t\t= plt.subplot(projection=wcs)\n\tim\t\t\t= ax.imshow(data, cmap='gray', origin='lower', norm=norm_zscale) \n\n\tfor xx, yy in zip(xim_list, yim_list):\n\t\tcirc = Circle((xx, yy), 15, color='gold', fill=None, linewidth='0.3')\n\t\tax.add_patch(circ)\n\tfor i, txt in enumerate(numb_list):\n\t\txim\t\t= xim_list[i]\n\t\tyim\t\t= yim_list[i]\n\t\tax.text(xim+7.5, yim+7.5, str(txt), color='gold', fontsize=5)\n\tif add != None:\n\t\tfor xx, yy in zip(xim_addlist, yim_addlist):\n\t\t\t'''\n\t\t\tcirc = Circle((xx, yy), 15, color='tomato', fill=None, linewidth='0.5')\n\t\t\tax.add_patch(circ)\n\t\t\t'''\n\t\t\tax.scatter(xx, yy, color='tomato', marker='o', alpha=0.1, s=10)\n\t\tfor i, txt in enumerate(numb_addlist):\n\t\t\txim\t\t= xim_addlist[i]\n\t\t\tyim\t\t= yim_addlist[i]\n\t\t\tax.text(xim+7.5, yim+7.5, str(txt), color='tomato', fontsize=5)\n\telse:\n\t\tpass\n\tax.grid('both', linestyle='--', color='silver', alpha=0.5)\n\tax.set_xlabel('R.A.', fontsize=20)\n\tax.set_ylabel('Dec.', fontsize=20)\n\t# plt.tight_layout()\n\t# plt.minorticks_on()\n\tfig.savefig(outname, facecolor='w', edgecolor='w',\n\t\torientation='portrait', papertype=None, format=None,\n\t\ttransparent=False, bbox_inches=None, pad_inches=0.1,\n\t\tmetadata=None)\n#-------------------------------------------------------------------------#\ndef sedualcom(inim, gain, pixscale, seeing, det_sigma=1.5, backsize=str(64), backfiltersize=str(3), detect='detection.fits'):\n\t\"\"\"\n\tSourceEXtractor\n\tAPERTURE    3\", 5\", 7\",\n\t\t\t\t1.0seeing, 1.2seeing ,1.5seeing ,1.7seeing ,2.0seeeing\n\tINPUT   :   (image).fits\n\t\t\t\taperture    []\n\t\t\t\tseeing_fwhm [pixel]\n\tOUTPUT  :   no return\n\t\t\t\t.cat\n\t\"\"\"\n\timport numpy as np\n\timport os\n\tfrom astropy.io import ascii\n\t#   FILE CHECK\n\t#\tCONFIG FILES (USER BASE PATH)\n\tsharepath       = '/home/sonic/Research/yourpy/config'\n\tconfigfile      = sharepath+'/targetphot.sex'\n\tparamfile       = sharepath+'/targetphot.param'\n\tnnwfile\t\t    = sharepath+'/targetphot.nnw'\n\tconvfile\t    = sharepath+'/targetphot.conv'\n\ttry:\n\t\tcomment = '\\nSourceEXtractor (DUAL MODE) START\\n' \\\n\t\t\t\t+ 'IMAGE\\t\\t: '+inim+'\\n' \\\n\t\t\t\t+ 'GAIN\\t\\t: '+str(gain)+'\\n' \\\n\t\t\t\t+ 'PIXSCALE\\t: '+str(pixscale)+'\\n' \\\n\t\t\t\t+ 'DETECTION SIGMA\\t: '+str(det_sigma)+'\\n' \\\n\t\t\t\t+ 'PARAM\\t\\t: '+paramfile+'\\n' \\\n\t\t\t\t+ 'BACKSIZE\\t: '+backsize+'\\n' \\\n\t\t\t\t+ 'BACKFILTER\\t: '+backfiltersize+'\\n' \\\n\t\t\t\t+ 'CONFIG\\t\\t: '+configfile+'\\n' \\\n\t\t\t\t+ 'NNW\\t\\t: '+nnwfile+'\\n' \\\n\t\t\t\t+ 'CONVOLVE\\t: '+convfile\n\t\tprint(comment)\n\texcept:\n\t\tcomment = 'CHECK configfile/paramfile/nnewfile/convfile or others.'\n\t\tprint(comment)\n\t#   FILE NAME\n\toriim   = inim[2:]\n\tcat     = inim[:-5]+'.dual.cat'\n\tseg     = inim[:-5]+'.seg.fits'\n\tbkg     = inim[:-5]+'.bkg.fits'\n\tsub     = inim[:-5]+'.sub.fits'\n\t# psf     = inim[2:-5]+'.psf'\n\tpsf\t\t= inim[:-5]+'.psf'\n\taper    = inim[:-5]+'.aper.fits'\n\n\t#   BASIC INFO.\n\tdet_area        = 5\n\t#det_thresh      = det_sigma/np.sqrt(det_area)\n\tdet_thresh      = det_sigma\n\tdetecminarea    = str(det_area)\n\tdetectthresh    = str(det_thresh)\n\t# seeing, fwhm_arcsec = psfex(oriim, pixscale)\n\t# seeing, fwhm_arcsec = psfex(inim, pixscale)\n\t#pixscale        = pixscalecalc(inim)\n\t#   OPTION\n\taperture        = '%.2f'%(3./pixscale)+','+'%.2f'%(5./pixscale)+','+'%.2f'%(7./pixscale)+','+'%.2f'%(seeing)+','+'%.2f'%(1.2*seeing)+','+'%.2f'%(1.5*seeing)+','+'%.2f'%(1.7*seeing)+','+'%.2f'%(2.0*seeing)\n\n\toption1 = ' -CATALOG_NAME '+cat+' -PARAMETERS_NAME '+paramfile\n\toption2 = ' -DETECT_MINAREA '+detecminarea+' -DETECT_THRESH '+detectthresh \\\n\t\t\t+' -FILTER Y '+'-FILTER_NAME '+convfile\n\toption3 = ' -PHOT_APERTURES '+aperture \\\n\t\t\t+' -GAIN '+'%.1f'%(gain)+' -PIXEL_SCALE '+'%.1f'%(pixscale)\n\toption4 = ' -SEEING_FWHM '+'%.3f'%(seeing)+' -STARNNW_NAME '+nnwfile\n\toption5 = ' -BACK_SIZE '+ backsize \\\n\t\t\t+ ' -BACK_FILTERSIZE '+ backfiltersize+' -BACKPHOTO_TYPE LOCAL'\n\toption6 = ' -CHECKIMAGE_TYPE SEGMENTATION,APERTURES,BACKGROUND,-BACKGROUND'\n\toption7 = ' -CHECKIMAGE_NAME '+seg+','+aper+','+','+bkg+','+sub\n\toption8 = ' -PSF_NAME '+psf\n\t#   COMMAND\n\t#   detect = detection.fits is fine image show target significantly and have good seeing and many stars i\n\tdualcom ='sex -c '+configfile+' '+detect+' , '+inim+' -CATALOG_NAME '+cat+' -PARAMETERS_NAME '+paramfile+ ' '+option2+' '+option3+' '+option4+' '+option5+' '+option6+' '+option7+' '+option8\n\n\tos.system(dualcom)\n\tsecat   = ascii.read(cat)\n\t# return secat, cat, seeing, fwhm_arcsec\n\treturn secat, cat\n#-------------------------------------------------------------------------#\ndef targetfind(tra, tdec, refra, refdec, sep):\n\timport astropy.units as u\n\tfrom astropy.coordinates import SkyCoord\n\ttarg_coord\t= SkyCoord(tra, tdec, unit=(u.deg, u.deg))\n\tphot_coord\t= SkyCoord(refra, refdec, unit=(u.deg, u.deg))\n\tindx, d2d, d3d\t= targ_coord.match_to_catalog_sky(phot_coord)\n\treturn indx, d2d, d3d\n#-------------------------------------------------------------------------#\ndef apass2med(incat, outcat, sedcat='/home/paek/table/stellar_sed_template_phot4med.dat'):\n\tfrom astropy.modeling import models, fitting\n\tfrom astropy.io import ascii\n\t#============================================================\n\t#\tFunction\n\t#------------------------------------------------------------\n\tdef chi_sq(obs, exp):\n\t\t'''\n\t\tobs : observation value\n\t\texp : expectation value\n\t\t'''\n\t\treturn np.sum( ((obs-exp)**2)/exp )\n\t#------------------------------------------------------------\n\t#\tPath\n\t#------------------------------------------------------------\n\t# path_plot = f'{path_base}/plot'\n\t#------------------------------------------------------------\n\t#\tTable\n\t#------------------------------------------------------------\n\treftbl = ascii.read(incat)\n\tsedtbl = ascii.read(sedcat)\n\t#------------------------------------------------------------\n\t#\tAdvance Preparation\n\t#------------------------------------------------------------\n\t#\tmed\n\t# filterlist_med = ['m575', 'm625', 'm675', 'm725', 'm775']\n\tfilterlist_med = ['m425', 'm475', 'm525', 'm575', 'm625', 'm675', 'm725', 'm775', 'm825', 'm875', 'm925', 'm975', 'm1025', 'n6780', 'n6830',]\n\t#\tAPASS\n\tfilterlist_apass = ['B', 'V', 'g', 'r', 'i']\n\t#\tVega --> AB\n\treftbl['Bmag'] = reftbl['Bmag']+(-0.09)\n\treftbl['Vmag'] = reftbl['Vmag']+(-0.02)\n\t#\tGenerate table space on the reference catalog\n\tfor filte in filterlist_med:\n\t\treftbl[f'{filte}mag'] = 0.0\n\t\treftbl[f'e_{filte}mag'] = 0.0\n\treftbl['n_sed'] = 0\n\treftbl['mktype'] = ' '*10\n\t#\tDummy column\n\tsedtbl['chisq'] = 0.0\n\tsedtbl['const'] = 0.0\n\t#------------------------------------------------------------\n\t#\tMain body\n\t#------------------------------------------------------------\n\t# i = 2\n\tprint('-'*60)\n\tprint(f'#\\tConvert APASS catalog (stars:{len(reftbl)})')\n\tprint('-'*60)\n\tfor i in range(len(reftbl)):\n\t\tn_apass = reftbl['NUMBER'][i]\n\t\tms_apass = np.array([reftbl[f'{filte}mag'][i] for filte in filterlist_apass])\n\t\te_ms_apass = np.array([reftbl[f'e_{filte}mag'][i] for filte in filterlist_apass])\n\t\t#\tVariable for fitting\n\t\ty = ms_apass\n\t\tyerr = e_ms_apass\n\t\t# j = 60\n\t\tfor j in range(len(sedtbl)):\n\t\t\tms_sed = np.array([sedtbl[f'{filte}'][j].item() for filte in filterlist_apass])\n\t\t\t#\tVariable for fitting\n\t\t\tx = ms_sed\n\t\t\t#\tInitial parameter\n\t\t\tm_dif = np.median(y-x)\n\t\t\t#------------------------------------------------------------\n\t\t\t#\tFitting\n\t\t\t#------------------------------------------------------------\n\t\t\t# initialize a linear fitter\n\t\t\tfit = fitting.LinearLSQFitter()\n\t\t\t# initialize a linear model\n\t\t\tline_init = models.Linear1D()\n\t\t\tline_init.slope.fixed = True\n\t\t\t# fit the data with the fitter\n\t\t\t# fitted_line = fit(line_init, x, y, weights=e_ms_apass)\n\t\t\tfitted_line = fit(line_init, x, y, )\n\t\t\t#------------------------------------------------------------\n\t\t\t#\tFitting results\n\t\t\t#------------------------------------------------------------\n\t\t\tchisq = chi_sq(ms_apass, fitted_line(x))\n\t\t\tsedtbl['chisq'][j] = chisq\n\t\t\tsedtbl['const'][j] = fitted_line.intercept.value\n\t\t#------------------------------------------------------------\n\t\t#\tPick optimized index\n\t\t#------------------------------------------------------------\n\t\tindx_opt = np.where(sedtbl['chisq']==np.min(sedtbl['chisq']))\n\t\t#------------------------------------------------------------\n\t\t#\tOptimized values\n\t\t#------------------------------------------------------------\n\t\tchisq_opt = sedtbl['chisq'][indx_opt].item()\n\t\tconst_opt = sedtbl['const'][indx_opt].item()\n\t\tms_sed = np.array([sedtbl[f'{filte}'][indx_opt].item() for filte in filterlist_apass])\n\t\tx = ms_sed\n\t\t'''\n\t\t#------------------------------------------------------------\n\t\t# \tPlot\n\t\t#------------------------------------------------------------\n\t\tplt.close()\n\t\tfig, (ax1, ax2) = plt.subplots(2, 1)\n\t\t#\taxis 1\n\t\tax1.plot(x, y, 'ko', label='APASS')\n\t\tax1.plot(x, x+const_opt, 'r-', label=f'Fitted Model, chisq={round(chisq_opt, 3)}')\n\t\tax1.legend()\n\t\tax1.set_title(f'APASS : {i}')\n\n\t\tax1.set_ylabel(r'$\\rm m_{APASS}$ [mag]')\n\t\t#\taxis 2\n\t\tax2.plot(x, y - (x+const_opt), 'ko')\n\t\tax2.axhline(y=0, ls='--', color='grey')\n\t\tax2.set_xlabel(r'$\\rm m_{spec}$ [mag]')\n\t\tax2.set_ylabel('Residual')\n\t\tax2.set_ylim([-0.5, +0.5])\n\n\t\tplt.savefig(f'{path_plot}/plot_{i}.png')#, overwrite=True)\n\n\t\t#\tPut med-band photometries on the APASS catalog\n\t\tfor filte in filterlist_med:\n\t\t\treftbl[f'{filte}mag'][i] = sedtbl[f'{filte}'][indx_opt].item()+const_opt\n\t\treftbl['n_sed'][i] = sedtbl['number'][indx_opt].item()\n\t\treftbl['mktype'][i] = sedtbl['mktype'][indx_opt].item()\n\t\t'''\n\t\t#\tPut med-band photometries on the APASS catalog\n\t\tfor filte in filterlist_med:\n\t\t\treftbl[f'{filte}mag'][i] = sedtbl[f'{filte}'][indx_opt].item()+const_opt\n\t\treftbl['n_sed'][i] = sedtbl['number'][indx_opt].item()\n\t\treftbl['mktype'][i] = sedtbl['mktype'][indx_opt].item()\n\t\n\treftbl.write(f'{outcat}', format='ascii.tab', overwrite=True)\n\treturn reftbl\n\n", "meta": {"hexsha": "9faeb86353e375c1b15f2b6d11c606605ae6da93", "size": 32673, "ext": "py", "lang": "Python", "max_stars_repo_path": "phot_before.py", "max_stars_repo_name": "SilverRon/imsngpy", "max_stars_repo_head_hexsha": "e9e55a73403bef4c73dcc242735efc28d79a3066", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-22T08:58:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T08:58:47.000Z", "max_issues_repo_path": "phot_before.py", "max_issues_repo_name": "SilverRon/imsngpy", "max_issues_repo_head_hexsha": "e9e55a73403bef4c73dcc242735efc28d79a3066", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phot_before.py", "max_forks_repo_name": "SilverRon/imsngpy", "max_forks_repo_head_hexsha": "e9e55a73403bef4c73dcc242735efc28d79a3066", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8159722222, "max_line_length": 206, "alphanum_fraction": 0.5612891378, "include": true, "reason": "import numpy,from numpy,from numba,import astropy,from astropy", "num_tokens": 10558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.18741990999931624}}
{"text": "import os, sys, glob\nimport argparse\nfrom struct import *\nfrom pathlib import Path\nfrom typing import List, Dict, Optional, Union, Type\n\nimport numpy as np\nimport pandas as pd\n\nimport astropy\nfrom astropy import units as un\nfrom astropy import constants as const\nfrom astropy.cosmology import z_at_value, LambdaCDM\n\nfrom astrild.simulation import Simulation\nfrom astrild.particles.ecosmog import Ecosmog\nfrom astrild.particles.halo import Halos\nfrom astrild.utils.geometrical_transforms import (\n    transform_box_to_lc_cart_coords,\n    radial_coordinate_in_lc,\n    angular_coordinate_in_lc,\n)\nfrom astrild.io import IO\n\ndir_src = Path(__file__).parent.absolute()\ndefault_config_file_df = dir_src / \"configs/ray_snapshot_info.h5\"\n\n\nclass RayRamsesWarning(BaseException):\n    pass\n\n\nclass RayRamses(Simulation):\n    \"\"\"\n    Attributes:\n        dir_sim: directory of simulation\n        dir_out: directory for results/returns\n        file_dsc: file describtion for identification\n        dir_root:\n        opening_angle: light-cone opening angle; [deg^2]\n        npix: nr. of cells along the four light-cone edges\n        config: contains snapshot infos (e.g. redshifts, comov. dist, ...)\n\n    Methods:\n        compress_snapshot:\n        sum_snapshots:\n        find_halos_in_raytracing_box:\n        find_halos_in_raytracing_snapshot:\n    \"\"\"\n\n    def __init__(\n        self,\n        config: Union[None, pd.DataFrame],\n        dir_sim: str,\n        dir_out: str,\n        file_dsc: dict = {\"root\": \"Ray_maps\", \"extension\": \"dat\"},\n        dir_root: str = None,\n        opening_angle: float = 20.0,\n        npix: int = 8192,\n        cosmo: astropy.cosmology = LambdaCDM,\n    ):\n        super().__init__(dir_sim, dir_out, file_dsc, dir_root)\n        self.opening_angle = opening_angle\n        self.npix = npix\n        self.config = config\n        self.cosmo = cosmo\n\n\n    def compress_snapshot(\n        self,\n        fields: list,\n        dir_out: str = None,\n        convert: bool = False,\n        cosmo: astropy.cosmology = LambdaCDM,\n        save: bool = True,\n    ) -> None:\n        \"\"\"\n        Combines the ray-tracing outputs of individual CPUs at a given snapshot\n        into one pandas .h5 file.\n\n        Args:\n        Returns:\n        \"\"\"\n        self.cosmology = cosmo\n\n        self.file_nrs = self.get_file_nrs(\n            self.file_dsc, self.dirs[\"sim\"], \"min\", True\n        )\n        self.files = {\n            self.file_dsc[\"root\"]: self.get_file_paths(\n                self.file_dsc, self.dirs[\"sim\"], uniques=\"min\"\n            )\n        }\n        # run through ray-ramses snapshots\n        for ray_nr in np.unique(self.file_nrs):\n            print(\"Ray-Nr %d\" % ray_nr)\n            idx = (np.where(self.file_nrs == ray_nr)[0]).astype(int)\n            cpu_files = [\n                self.files[self.file_dsc[\"root\"]][idx]\n                for idx, rnr in enumerate(self.file_nrs)\n                if rnr == ray_nr\n            ]\n            first = True\n\n            # run through cpu-files for snapshot\n            for cpu_file in cpu_files:\n                print(\"    %s\" % cpu_file.split(\"/\")[-1])\n\n                ray_df = pd.read_csv(\n                    cpu_file,\n                    delim_whitespace=True,\n                    skipinitialspace=True,\n                    names=fields,\n                    header=None,\n                    lineterminator=\"\\n\",\n                )\n\n                if convert is True:\n                    # convert comoving distance to [Gpc/h]\n                    ray_df[\"chi_co\"] /= self.cosmology.H0.value / 100\n\n                    # Correct gamma_1 and gamma_2 to put in the form\n                    # that normally appears in the literature\n                    ray_df[\"shear_y\"] *= 2.0 * sin(ray_df[\"the_co\"])\n                    gamm1_corr = -ray_df[\"shear_x\"] * cos(\n                        2.0 * ray_df[\"phi_co\"]\n                    ) - ray_df[\"shear_y\"] * sin(2.0 * ray_df[\"phi_co\"])\n                    gamm2_corr = -ray_df[\"shear_x\"] * sin(\n                        2.0 * ray_df[\"phi_co\"]\n                    ) + ray_df[\"shear_y\"] * sin(2.0 * ray_df[\"phi_co\"])\n                    ray_df[\"shear_x\"] = gamm1_corr\n                    ray_df[\"shear_y\"] = gamm2_corr\n\n                if first:\n                    ray_collect_df = ray_df\n                    first = False\n                else:\n                    ray_collect_df = ray_collect_df.append(ray_df)\n\n            ray_collect_df = ray_collect_df.sort_values(\n                by=[\"rayid\"], axis=0, ascending=True\n            )\n            ray_collect_df = ray_collect_df.set_index(\"rayid\")\n            file_out = self.dirs[\"sim\"] + \"%s_output%05d.h5\" % (\n                self.file_dsc[\"root\"],\n                ray_nr,\n            )\n            ray_collect_df.to_hdf(file_out, key=\"df\", mode=\"w\")\n\n\n    def sum_snapshots(\n        self,\n        dir_out: str,\n        columns: list,\n        columns_z_shift: list,\n        integration_range: dict,\n        ray_file_root: str = \"Ray_maps_output%05d.h5\",\n        sim_folder_root: str = \"box%d\",\n        z_src: float = None,\n        z_src_shift: float = None,\n    ) -> None:\n        \"\"\"\n        Adds different ray-tracing outputs together. This can give you the\n        integrated ray-tracing quantities between arbitrary redshifts along\n        the ligh-cone. The ray-tracing outputs must either have the format of\n        RayRamses outputs in pd.DataFrames or np.ndarray images.\n\n        Args:\n            dir_out:\n            columns:\n            columns_z_shift:\n            integration_range:\n            ray_file_root:\n            sim_folder_root:\n            z_src:\n            z_src_shift:\n        \"\"\"\n        file_name = self.dirs[\"lc\"] + \"ray_snapshot_info.h5\"\n        if not os.path.isfile(file_name):\n            raise RayRamsesWarning(\n                \"The file 'ray_snapshot_info.h5' does note exist\"\n            )\n        self.ray_info_df = pd.read_hdf(file_name, key=\"s\")\n        sim_folder_root = self.dirs[\"lc\"] + sim_folder_root\n\n        box_ray_nrs = _get_box_and_ray_nrs(integration_range)\n\n        first = True\n        for box_nr, ray_nr in box_ray_nrs:\n            sim_info_df = self.ray_info_df.loc[(box_nr, ray_nr)]\n            self.dirs[\"sim\"] = sim_folder_root % box_nr + \"/\"\n            ray_file = self.dirs[\"sim\"] + ray_file_root % ray_nr\n            ray_map_df = pd.read_hdf(ray_file)\n\n            print(\n                \"Box Nr. %d; %s; Redshift %.3f\"\n                % (box_nr, os.path.basename(ray_file), sim_info_df[\"redshift\"]),\n                len(ray_map_df.index.values),\n            )\n\n            if (\n                z_src_shift is not None\n                and sim_info_df[\"redshift\"] <= z_src_shift\n            ):\n                raise RayRamsesWarning(\n                    \"Redshift shift has not correct data structure\"\n                )\n                # what snapshot to use if end of lightcone-box is reached\n                if (ray_box_info_df.name[1] == ray_nrs.min()) and (box_nr < 4):\n                    z_next = self.ray_info_df.loc[(box_nr + 1, 1)][\"redshift\"]\n                else:\n                    z_next = ray_box_info_df.iloc[ii + 1][\"redshift\"]\n\n                # Shift redshift of light source\n                # only of kappa but not of iswrs !!!\n                ray_map_df[\"kappa_2\"] = self._translate_redshift(\n                    ray_map_df[\"kappa_2\"],\n                    sim_info_df[\"redshift\"],\n                    z_next,\n                    z_src,\n                    z_src_shift,\n                )\n\n            if first is True:\n                ray_df_sum = ray_map_df\n                first = False\n\n            else:\n                for column in columns:\n                    ray_df_sum[column] = (\n                        ray_df_sum[column].values + ray_map_df[column].values\n                    )\n\n        self._merged_snapshots_to_file(ray_df_sum, dir_out, integration_range)\n\n\n    def _get_box_and_ray_nrs(self, integration_range: dict) -> np.ndarray:\n        \"\"\"\n        Get all box and ray-snapshot numbers for selected range.\n        \n        Args:\n        Returns:\n        \"\"\"\n        if not integration_range[\"z\"]:\n            if integration_range[\"box\"][0] == 0:\n                print(\"Integrate over whole light-cone\")\n                self.complete_lc = True\n            elif integration_range[\"ray\"][0] == 0:\n                print(\"Integrate over box\", integration_range[\"box\"])\n                self.ray_info_df = ray_info_df[\n                    ray_info_df.index.get_level_values(0).isin(\n                        integration_range[\"box\"]\n                    )\n                ]\n                self.complete_lc = False\n        else:\n            print(\"Integrate over redshift-range\", integration_range[\"z\"])\n            # if merging based on redshift\n            z_range = np.asarray(integration_range[\"z\"])\n            self.ray_info_df = self.ray_info_df[\n                (z_range.min() < self.ray_info_df[\"redshift\"])\n                & (self.ray_info_df[\"redshift\"] < z_range.max())\n            ]\n            self.complete_lc = False\n\n        return self.ray_info_df.index.values\n\n\n    def _translate_redshift(\n        self,\n        quantity: str,\n        z_near: float,\n        z_far: float,\n        z_src: float,\n        z_src_shift: float,\n    ) -> float:\n        \"\"\"\n        Args:\n            quantity pandas.DataSeries:\n                ray-ramses output quantity\n            x_near np.float:\n                comoving distance closer to observer\n            x_far np.float:\n                comoving distance further from observer\n            x_src np.float:\n                source redshift used in ray-ramses simulation\n\n        Returns:\n        \"\"\"\n        x_far = self.cosmology.comoving_distance(z_far).to_value(\"Mpc\")\n        x_near = self.cosmology.comoving_distance(z_near).to_value(\"Mpc\")\n        x_src = self.cosmology.comoving_distance(z_src).to_value(\"Mpc\")\n\n        if z_far > z_src_shift:\n            # if z of next snapshot larger than new source z, set the new source\n            # equal to it, so that a distance of 150[Mpc/h] is maintained\n            x_src_shift = self.cosmology.comoving_distance(z_far).to_value(\n                \"Mpc\"\n            )\n        else:\n            x_src_shift = self.cosmology.comoving_distance(\n                z_src_shift\n            ).to_value(\"Mpc\")\n\n        x_mid = 0.5 * (x_far + x_near)\n\n        quantity_shift = (\n            quantity\n            * self._kernel_function(x_mid, x_src_shift)\n            / self._kernel_function(x_mid, x_src)\n        )\n        return quantity_shift\n\n\n    def _kernel_function(self, x: float, x_s: float) -> float:\n        \"\"\"\n        Args:\n            x np.float:\n                comoving distance\n            x_s np.float:\n                comoving distance to source\n\n        Returns:\n        \"\"\"\n        g = (x_s - x) * x / x_s\n        return g\n\n\n    def _merged_snapshots_to_file(\n        self, ray_df_sum: pd.DataFrame, dir_out: str, integration_range: dict\n    ) -> None:\n        \"\"\"\n        Write merged ray-tracing pd.DataFrame to .h5 file\n\n        Args:\n        \"\"\"\n        if not integration_range[\"z\"]:\n            if integration_range[\"box\"][0] == 0:\n                fout = dir_out + \"Ray_maps_lc.h5\"\n                print(\"Save in %s\" % fout)\n                ray_df_sum.to_hdf(fout, key=\"df\", mode=\"w\")\n            elif integration_range[\"ray\"][0] == 0:\n                fout = dir_out + \"Ray_maps_box%d.h5\" % box_nr\n                print(\"Save in %s\" % fout)\n                ray_df_sum.to_hdf(fout, key=\"df\", mode=\"w\")\n        else:\n            fout = dir_out + \"Ray_maps_zrange_%.2f_%.2f.h5\" % (\n                self.ray_info_df[\"redshift\"].values.min(),\n                self.ray_info_df[\"redshift\"].values.max(),\n            )\n            print(\"Save in %s\" % fout)\n            ray_df_sum.to_hdf(fout, key=\"df\", mode=\"w\")\n\n    @staticmethod\n    def find_subfind_halos_in_raytracing_snapshot(\n        ecosmog: Type[Ecosmog],\n        box_nr: int,\n        snap_nr: int,\n        ray_nr: int,\n        boxdist: float,\n        boxsize: float,\n        opening_angle: float,\n        snaplimit: tuple,\n        hubble: float,\n    ) -> Union[None, pd.DataFrame]:\n        coeff = hubble / 1e3\n        halos = Halos.from_subfind(snap_nr, ecosmog)\n        \n        if halos.data is None:\n            return None\n        else:\n            halocat = halos.filter_nonzero_subfind_halos_size(halos.data).cat\n        \n        halocatindex = np.arange(len(halocat[\"Group_M_Crit200\"][:]))\n        print(f\"There are {len(halocatindex)} halos in box {box_nr} snapshot {snap_nr}\")\n\n        # cartesian coord. in light-cone [Mpc/h]\n        pos = halocat[\"GroupPos\"][:, :] * coeff\n        pos[:, 0] = pos[:, 0] - boxsize / 2\n        pos[:, 1] = pos[:, 1] - boxsize / 2\n        pos[:, 2] = pos[:, 2] + boxdist\n        # radial distance from observer [Mpc/h]\n        rad_dist = np.sqrt(pos[:, 0]**2 + pos[:, 1]**2 + pos[:, 2]**2)\n        # angular coord [deg]\n        theta1_deg = np.arctan(pos[:, 0] / pos[:, 2]) * 180/np.pi\n        theta2_deg = np.arctan(pos[:, 1] / pos[:, 2]) * 180/np.pi\n\n        # index of halos in light-cone\n        indx = np.where(\n            (rad_dist >= np.min(snaplimit))\n            & (rad_dist <= np.max(snaplimit))\n            & (np.abs(theta1_deg) <= opening_angle / 2)\n            & (np.abs(theta2_deg) <= opening_angle / 2)\n        )[0]\n        print(f\"There are {len(indx)} halos in light-cone in box {box_nr} snapshot {snap_nr}\")\n\n        # project 3D velocity along line-of-sight in cart. coord.\n        pos_norm = np.linalg.norm(pos[indx, :], axis=1)\n        vr = (\n            (\n                halocat[\"GroupVel\"][indx, :] * pos[indx, :] # element-wise dot-product\n            ).sum(axis=1) / (pos_norm**2)\n        )[:, np.newaxis] * pos[indx, :]\n        # project 3D velocity along transverse to line-of-sight direction\n        # in cart. coord.\n        vt = halocat[\"GroupVel\"][indx, :] - vr\n        # small angle approximation\n        # -> TODO improve by projecting on spher. coord. unit vectors e_theta and e_phi\n        vel_x = vt[:, 0]\n        vel_y = vt[:, 1]\n\n        r200_deg = (\n            np.arctan(halocat[\"Group_R_Crit200\"][indx] * coeff / rad_dist[indx])\n            * 180 / np.pi\n        )\n\n        halo_id = [\n            int(f\"{box_nr}{snap_nr}{ii}\")\n            for ii in halocatindex[indx].astype(int)\n        ]\n        halos_dict = {\n            \"id\": halo_id,\n            \"x\": pos[indx, 0],\n            \"y\": pos[indx, 1],\n            \"z\": pos[indx, 2],\n            \"rad_dist\": rad_dist[indx],\n            \"theta1_deg\": theta1_deg[indx] + opening_angle / 2,\n            \"theta1_pix\": _degree_to_pixel(\n                theta1_deg[indx] + opening_angle / 2\n            ),\n            \"theta2_deg\": theta2_deg[indx] + opening_angle / 2,\n            \"theta2_pix\": _degree_to_pixel(\n                theta2_deg[indx] + opening_angle / 2\n            ),\n            \"x_vel\": halocat[\"GroupVel\"][indx, 0],\n            \"y_vel\": halocat[\"GroupVel\"][indx, 1],\n            \"z_vel\": halocat[\"GroupVel\"][indx, 2],\n            \"theta1_tv\": vel_x,\n            \"theta2_tv\": vel_y,\n            \"m200\": halocat[\"Group_M_Crit200\"][indx],\n            \"r200_deg\": r200_deg,\n            \"r200_pix\": _degree_to_pixel(r200_deg),\n            \"ray_nr\": [ray_nr + 1] * len(indx),\n            \"snap_nr\": [snap_nr] * len(indx),\n        }\n        halos_df = pd.DataFrame(data=halos_dict)\n        return halos_df\n\n\n    def find_halos_in_raytracing_box(\n        self,\n        ecosmog: Type[Ecosmog],\n        snapdist: float,\n        box_nr: int,\n        boxsize: float,\n        hubble: float,\n    ) -> Union[None, pd.DataFrame]:\n        \"\"\"\n        Args:\n\n        Returns:\n        \"\"\"\n        boxdist = snapdist[-1]\n        first = True\n        # run through ray-ramses snapshots\n        for ray_nr in np.unique(self.file_nrs)[:-1]:\n            snap_nr = (\n                ray_nr + len(ecosmog.config.index) - len(self.config.index)\n            )\n            snaplimit = (snapdist[ray_nr - 1], snapdist[ray_nr])\n            \n            if \"fof\" in list(ecosmog.files.keys()):\n                halos_df = self.find_subfind_halos_in_raytracing_snapshot(\n                    ecosmog,\n                    box_nr,\n                    snap_nr,\n                    ray_nr,\n                    boxdist,\n                    boxsize,\n                    self.opening_angle,\n                    self.npix,\n                    snaplimit,\n                    hubble,\n                )\n            elif \"halos\" in list(ecosmog.files.keys()):\n                halos_df = self.find_rockstar_halos_in_raytracing_snapshot(\n                    ecosmog,\n                    box_nr,\n                    snap_nr,\n                    ray_nr,\n                    boxdist,\n                    boxsize,\n                    self.opening_angle,\n                    self.npix,\n                    snaplimit,\n                )\n\n            if (first is True) and (halos_df is not None):\n                halos_df_sum = halos_df\n                first = False\n            elif first is False:\n                halos_df_sum = halos_df_sum.append(halos_df, ignore_index=True)\n        return halos_df_sum\n    \n\n    @staticmethod\n    def find_subfind_halos_in_raytracing_snapshot(\n        ecosmog: Type[Ecosmog],\n        box_nr: int,\n        snap_nr: int,\n        ray_nr: int,\n        boxdist: float,\n        boxsize: float,\n        opening_angle: float,\n        npix: int,\n        snaplimit: tuple,\n        hubble: float,\n    ) -> Union[None, pd.DataFrame]:\n        coeff = hubble / 1e3\n        halos = Halos.from_subfind(snap_nr, ecosmog)\n        \n        if halos.data is None:\n            return None\n        else:\n            halocat = halos.filter_nonzero_subfind_halos_size(halos.data).cat\n        \n        halocatindex = np.arange(len(halocat[\"Group_M_Crit200\"][:]))\n        print(f\"There are {len(halocatindex)} halos in box {box_nr} snapshot {snap_nr}\")\n\n        # cartesian coord. in light-cone [Mpc/h]\n        pos = halocat[\"GroupPos\"][:, :] * coeff\n        pos = transform_box_to_lc_cart_coords(pos, boxsize, boxdist)\n        rad_dist = radial_coordinate_in_lc(pos)\n        theta1_deg, theta2_deg = angular_coordinate_in_lc(pos, unit=\"deg\")\n\n        # index of halos in light-cone\n        indx = np.where(\n            (rad_dist >= np.min(snaplimit))\n            & (rad_dist <= np.max(snaplimit))\n            & (np.abs(theta1_deg) <= opening_angle / 2)\n            & (np.abs(theta2_deg) <= opening_angle / 2)\n        )[0]\n        print(f\"There are {len(indx)} halos in light-cone in box {box_nr} snapshot {snap_nr}\")\n\n        # project 3D velocity along line-of-sight in cart. coord.\n        pos_norm = np.linalg.norm(pos[indx, :], axis=1)\n        vr = (\n            (\n                halocat[\"GroupVel\"][indx, :] * pos[indx, :] # element-wise dot-product\n            ).sum(axis=1) / (pos_norm**2)\n        )[:, np.newaxis] * pos[indx, :]\n        # project 3D velocity along transverse to line-of-sight direction\n        # in cart. coord.\n        vt = halocat[\"GroupVel\"][indx, :] - vr\n        # small angle approximation\n        # -> TODO improve by projecting on spher. coord. unit vectors e_theta and e_phi\n        vel_x = vt[:, 0]\n        vel_y = vt[:, 1]\n\n        r200_deg = (\n            np.arctan(halocat[\"Group_R_Crit200\"][indx] * coeff / rad_dist[indx])\n            * 180 / np.pi\n        )\n\n        halo_id = [\n            int(f\"{box_nr}{snap_nr}{ii}\")\n            for ii in halocatindex[indx].astype(int)\n        ]\n        halos_dict = {\n            \"id\": halo_id,\n            \"x\": pos[indx, 0],\n            \"y\": pos[indx, 1],\n            \"z\": pos[indx, 2],\n            \"rad_dist\": rad_dist[indx],\n            \"theta1_deg\": theta1_deg[indx] + opening_angle / 2,\n            \"theta1_pix\": _degree_to_pixel(\n                theta1_deg[indx] + opening_angle / 2, opening_angle, npix\n            ),\n            \"theta2_deg\": theta2_deg[indx] + opening_angle / 2,\n            \"theta2_pix\": _degree_to_pixel(\n                theta2_deg[indx] + opening_angle / 2, opening_angle, npix\n            ),\n            \"x_vel\": halocat[\"GroupVel\"][indx, 0],\n            \"y_vel\": halocat[\"GroupVel\"][indx, 1],\n            \"z_vel\": halocat[\"GroupVel\"][indx, 2],\n            \"theta1_tv\": vel_x,\n            \"theta2_tv\": vel_y,\n            \"m200\": halocat[\"Group_M_Crit200\"][indx],\n            \"r200_deg\": r200_deg,\n            \"r200_pix\": _degree_to_pixel(r200_deg, opening_angle, npix),\n            \"ray_nr\": [ray_nr + 1] * len(indx),\n            \"snap_nr\": [snap_nr] * len(indx),\n        }\n        halos_df = pd.DataFrame(data=halos_dict)\n        return halos_df\n\n\n    @staticmethod\n    def find_rockstar_halos_in_raytracing_snapshot(\n        ecosmog: Type[Ecosmog],\n        box_nr: int,\n        snap_nr: int,\n        ray_nr: int,\n        boxdist: float,\n        boxsize: float,\n        opening_angle: float,\n        npix: int,\n        snaplimit: tuple,\n    ) -> Union[None, pd.DataFrame]:\n        halos = Halos.from_rockstar(snap_nr, ecosmog)\n        \n        if halos.data is None:\n            return None\n        else:\n            halocat = halos.data\n        \n        halocatindex = np.arange(len(halocat[\"m200c\"].values))\n        print(f\"There are {len(halocatindex)} halos in box {box_nr} snapshot {snap_nr}\")\n\n        # cartesian coord. in light-cone [Mpc/h]\n        pos = halocat[[\"x\", \"y\", \"z\"]].values\n        pos = transform_box_to_lc_cart_coords(pos, boxsize, boxdist)\n        rad_dist = radial_coordinate_in_lc(pos)\n        theta1_deg, theta2_deg = angular_coordinate_in_lc(pos, unit=\"deg\")\n\n        # index of halos in light-cone\n        indx = np.where(\n            (rad_dist >= np.min(snaplimit))\n            & (rad_dist <= np.max(snaplimit))\n            & (np.abs(theta1_deg) <= opening_angle / 2)\n            & (np.abs(theta2_deg) <= opening_angle / 2)\n        )[0]\n        halocat = halocat.iloc[halocatindex[indx]]\n        if len(indx) == 0: return None\n\n        pos = pos[halocatindex[indx], :]\n        rad_dist = rad_dist[halocatindex[indx]]\n        theta1_deg = theta1_deg[halocatindex[indx]]\n        theta2_deg = theta2_deg[halocatindex[indx]]\n        print(f\"There are {len(halocat.index.values)} halos in light-cone in box {box_nr} snapshot {snap_nr}\")\n\n        # get redshift\n        redshift = Dc_to_redshift(ecosmog.cosmo, rad_dist * un.Mpc)\n\n        # get angular distance\n\n        # project 3D velocity along line-of-sight in cart. coord.\n        pos_norm = np.linalg.norm(pos, axis=1)\n        vr = (\n            (\n                halocat[[\"vx\", \"vy\", \"vz\"]].values * pos # element-wise dot-product\n            ).sum(axis=1) / (pos_norm**2)\n        )[:, np.newaxis] * pos\n        # project 3D velocity along transverse to line-of-sight direction\n        # in cart. coord.\n        vt = halocat[[\"vx\", \"vy\", \"vz\"]].values - vr\n        # small angle approximation\n        # -> TODO improve by projecting on spher. coord. unit vectors e_theta and e_phi\n\n        r200_deg = (\n            np.arctan(halocat[\"r200c\"].values / (rad_dist * 1e3))\n            * 180 / np.pi\n        )\n\n        halo_id = [\n            int(f\"{box_nr}{snap_nr}{ii}\")\n            for ii in halocatindex[indx].astype(int)\n        ]\n        halos_dict = {\n            \"id\": halo_id,\n            \"x\": pos[:, 0],\n            \"y\": pos[:, 1],\n            \"z\": pos[:, 2],\n            \"Dc\": rad_dist,\n            \"Da\": rad_dist / (1 + redshift),\n            \"redshift\": redshift,\n            \"theta1_deg\": theta1_deg + opening_angle / 2,\n            \"theta1_pix\": _degree_to_pixel(theta1_deg + opening_angle/2, opening_angle, npix),\n            \"theta2_deg\": theta2_deg + opening_angle / 2,\n            \"theta2_pix\": _degree_to_pixel(theta2_deg + opening_angle/2, opening_angle, npix),\n            \"x_vel\": halocat[\"vx\"].values,\n            \"y_vel\": halocat[\"vy\"].values,\n            \"z_vel\": halocat[\"vz\"].values,\n            \"theta1_tv\": vt[:, 0],\n            \"theta2_tv\": vt[:, 1],\n            \"m200\": halocat[\"m200c\"].values,\n            \"c_NFW\": halocat[\"r200c\"].values / halocat[\"Rs\"].values,\n            \"r200_deg\": r200_deg,\n            \"r200_pix\": _degree_to_pixel(r200_deg, opening_angle, npix),\n            \"ray_nr\": [ray_nr + 1] * len(pos),\n            \"snap_nr\": [snap_nr] * len(pos),\n        }\n        halos_df = pd.DataFrame(data=halos_dict)\n        return halos_df\n        \n\ndef _degree_to_pixel(deg: np.ndarray, opening_angle, npix) -> np.ndarray:\n    \"\"\" Convert degree to pixel position \"\"\"\n    return np.ceil(deg * npix / opening_angle).astype(int)\n\n\ndef Dc_to_redshift(cosmo: astropy.cosmology, Dc: un.quantity.Quantity,) -> np.array:\n    \"\"\" Return redshift at comoving distance [Mpc] \"\"\"\n    return np.array([z_at_value(cosmo.comoving_distance, dist) for dist in Dc])\n\n", "meta": {"hexsha": "c33a1f9a9ba200792df71a2d323ca8571b709d31", "size": 24790, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/astrild/rays/rayramses.py", "max_stars_repo_name": "Christovis/wys-ars", "max_stars_repo_head_hexsha": "bb15f2d392842f9b32de12b5db5c86079bc97105", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-27T14:45:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T21:09:46.000Z", "max_issues_repo_path": "src/astrild/rays/rayramses.py", "max_issues_repo_name": "Christovis/wys-ars", "max_issues_repo_head_hexsha": "bb15f2d392842f9b32de12b5db5c86079bc97105", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-03T10:47:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-03T10:47:45.000Z", "max_forks_repo_path": "src/astrild/rays/rayramses.py", "max_forks_repo_name": "Christovis/wys-ars", "max_forks_repo_head_hexsha": "bb15f2d392842f9b32de12b5db5c86079bc97105", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-03T10:17:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T10:17:34.000Z", "avg_line_length": 35.1133144476, "max_line_length": 110, "alphanum_fraction": 0.532029044, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 6295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.18741990252718996}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nNTSC RGB Colourspace\n====================\n\nDefines the *NTSC RGB* colourspace:\n\n-   :attr:`NTSC_RGB_COLOURSPACE`.\n\nSee Also\n--------\n`RGB Colourspaces IPython Notebook\n<http://nbviewer.ipython.org/github/colour-science/colour-ipython/blob/master/notebooks/models/rgb.ipynb>`_  # noqa\n\nReferences\n----------\n.. [1]  `Recommendation ITU-R BT.470-6 - Conventional Television Systems\n        <http://www.itu.int/dms_pubrec/itu-r/rec/bt/R-REC-BT.470-6-199811-S!!PDF-E.pdf>`_  # noqa\n        (Last accessed 13 April 2014)\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\n\nfrom colour.colorimetry import ILLUMINANTS\nfrom colour.models import RGB_Colourspace, normalised_primary_matrix\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013 - 2014 - Colour Developers'\n__license__ = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-science@googlegroups.com'\n__status__ = 'Production'\n\n__all__ = ['NTSC_RGB_PRIMARIES',\n           'NTSC_RGB_WHITEPOINT',\n           'NTSC_RGB_TO_XYZ_MATRIX',\n           'XYZ_TO_NTSC_RGB_MATRIX',\n           'NTSC_RGB_TRANSFER_FUNCTION',\n           'NTSC_RGB_INVERSE_TRANSFER_FUNCTION',\n           'NTSC_RGB_COLOURSPACE']\n\nNTSC_RGB_PRIMARIES = np.array(\n    [[0.67, 0.33],\n     [0.21, 0.71],\n     [0.14, 0.08]])\n\"\"\"\n*NTSC RGB* colourspace primaries.\n\nNTSC_RGB_PRIMARIES : ndarray, (3, 2)\n\"\"\"\n\nNTSC_RGB_WHITEPOINT = ILLUMINANTS.get(\n    'CIE 1931 2 Degree Standard Observer').get('C')\n\"\"\"\n*NTSC RGB* colourspace whitepoint.\n\nNTSC_RGB_WHITEPOINT : tuple\n\"\"\"\n\nNTSC_RGB_TO_XYZ_MATRIX = normalised_primary_matrix(NTSC_RGB_PRIMARIES,\n                                                   NTSC_RGB_WHITEPOINT)\n\"\"\"\n*NTSC RGB* colourspace to *CIE XYZ* colourspace matrix.\n\nNTSC_RGB_TO_XYZ_MATRIX : array_like, (3, 3)\n\"\"\"\n\nXYZ_TO_NTSC_RGB_MATRIX = np.linalg.inv(NTSC_RGB_TO_XYZ_MATRIX)\n\"\"\"\n*CIE XYZ* colourspace to *NTSC RGB* colourspace matrix.\n\nXYZ_TO_NTSC_RGB_MATRIX : array_like, (3, 3)\n\"\"\"\n\nNTSC_RGB_TRANSFER_FUNCTION = lambda x: x ** (1 / 2.2)\n\"\"\"\nTransfer function from linear to *NTSC RGB* colourspace.\n\nNTSC_RGB_TRANSFER_FUNCTION : object\n\"\"\"\n\nNTSC_RGB_INVERSE_TRANSFER_FUNCTION = lambda x: x ** 2.2\n\"\"\"\nInverse transfer function from *NTSC RGB* colourspace to linear.\n\nNTSC_RGB_INVERSE_TRANSFER_FUNCTION : object\n\"\"\"\n\nNTSC_RGB_COLOURSPACE = RGB_Colourspace(\n    'NTSC RGB',\n    NTSC_RGB_PRIMARIES,\n    NTSC_RGB_WHITEPOINT,\n    NTSC_RGB_TO_XYZ_MATRIX,\n    XYZ_TO_NTSC_RGB_MATRIX,\n    NTSC_RGB_TRANSFER_FUNCTION,\n    NTSC_RGB_INVERSE_TRANSFER_FUNCTION)\n\"\"\"\n*NTSC RGB* colourspace.\n\nNTSC_RGB_COLOURSPACE : RGB_Colourspace\n\"\"\"\n", "meta": {"hexsha": "fc73487840c6224862fbace628f37e8e7fa6c276", "size": 2705, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/models/dataset/ntsc_rgb.py", "max_stars_repo_name": "canavandl/colour", "max_stars_repo_head_hexsha": "a453cd37b6135a9092d5ea5b2aafb8d19134bdff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-27T11:32:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-27T11:32:48.000Z", "max_issues_repo_path": "colour/models/dataset/ntsc_rgb.py", "max_issues_repo_name": "canavandl/colour", "max_issues_repo_head_hexsha": "a453cd37b6135a9092d5ea5b2aafb8d19134bdff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/models/dataset/ntsc_rgb.py", "max_forks_repo_name": "canavandl/colour", "max_forks_repo_head_hexsha": "a453cd37b6135a9092d5ea5b2aafb8d19134bdff", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5188679245, "max_line_length": 115, "alphanum_fraction": 0.707948244, "include": true, "reason": "import numpy", "num_tokens": 775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.1873698214160765}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nThis module contains legacy code for the cellulosic ethanol biorefinery\nbased on the 2011 NREL report [1]_.\n\nReferences\n----------\n.. [1] Humbird, D., Davis, R., Tao, L., Kinchin, C., Hsu, D., Aden, A.,\n    Dudgeon, D. (2011). Process Design and Economics for Biochemical \n    Conversion of Lignocellulosic Biomass to Ethanol: Dilute-Acid \n    Pretreatment and Enzymatic Hydrolysis of Corn Stover\n    (No. NREL/TP-5100-47764, 1013269). https://doi.org/10.2172/1013269\n\n\"\"\"\n\n# %% Legacy code\n\n### DO NOT DELELTE:\n### This code is used to generate splits for unit operations in wastewater \n### treatment of a cellulosic ethanol biorefinery.\nimport thermosteam as tmo\nimport numpy as np\nfrom biorefineries.cornstover import chemicals\ntmo.settings.set_thermo(chemicals)\nchemical_groups = dict(\n        OtherSugars = ('Arabinose',\n                        'Mannose',\n                        'Galactose',\n                        'Cellobiose',\n                        'Sucrose'),\n        SugarOligomers = ('GlucoseOligomer',\n                          'XyloseOligomer',\n                          'GalactoseOligomer',\n                          'ArabinoseOligomer',\n                          'MannoseOligomer'),\n        OrganicSolubleSolids = ('AmmoniumAcetate',\n                                'SolubleLignin',\n                                'Extract', \n                                'LacticAcid', \n                                'Cellulase'),\n        InorganicSolubleSolids = ('AmmoniumSulfate',\n                                  'DAP',\n                                  'NaOH',\n                                  'HNO3',\n                                  'NaNO3'),\n        Furfurals = ('Furfural',\n                      'HMF'),\n        OtherOrganics = ('Glycerol',\n                          'Denaturant',\n                          'Oil',\n                          'SuccinicAcid',\n                          'Xylitol'),\n        COxSOxNOxH2S = ('NO',\n                        'NO2',\n                        'SO2',\n                        'CO',\n                        'H2S'),\n        Protein = ('Protein',\n                    'Enzyme',\n                    'DenaturedEnzyme'),\n        CellMass = ('WWTsludge',\n                    'Z_mobilis',\n                    'T_reesei'),\n        OtherInsolubleSolids = ('Tar',\n                                'Ash',\n                                'Lime'),\n        OtherStructuralCarbohydrates = ('Arabinan', \n                                        'Mannan', \n                                        'Galactan')\n)\n\ndef find_split(IDs, flow0, flow1):\n    flow0 = np.asarray(flow0)\n    splits = flow0/(flow0 + np.asarray(flow1))\n    chemicals = tmo.settings.get_chemicals()\n    array = np.zeros(chemicals.size)\n    for ID, split in zip(IDs, splits):\n        if ID in chemical_groups:\n            array[chemicals.get_index(chemical_groups[ID])] = split\n        else:\n            array[chemicals.index(ID)] = split\n    return array\n\nsplits = [\n    ('Ethanol', 1, 15),\n    ('Water', 27158, 356069),\n    ('Glucose', 3, 42),\n    ('Xylose', 7, 85),\n    ('OtherSugars', 13, 175),\n    ('SugarOligomers', 10, 130),\n    ('OrganicSolubleSolids', 182, 2387),\n    ('InorganicSolubleSolids', 8, 110),\n    ('Ammonia', 48, 633),\n    ('AceticAcid', 0, 5),\n    ('Furfurals', 5, 70),\n    ('OtherOrganics', 9, 113),\n    ('Cellulose', 19, 6),\n    ('Xylan', 6, 2),\n    ('OtherStructuralCarbohydrates', 1, 0),\n    ('Lignin', 186, 64),\n    ('Protein', 51, 18),\n    ('CellMass', 813, 280),\n    ('OtherInsolubleSolids', 68, 23)\n]\n\nanaerobic_bioreactor_sludge_splits = find_split(*zip(*splits))\n\nsplits = [\n    ('Glucose', 19, 502),\n    ('Xylose', 40, 1022),\n    ('OtherSugars', 81, 2175),\n    ('SugarOligomers', 60, 1552),\n    ('OrganicSolubleSolids', 612, 15808),\n    ('InorganicSolubleSolids', 97, 2513),\n    ('Furfurals', 19, 513),\n    ('OtherOrganics', 52, 1348),\n    ('Glucan', 1230, 25),\n    ('Xylan', 415, 8),\n    ('OtherStructuralCarbohydrates', 94, 2),\n    ('Lignin', 12226, 250),\n    ('Protein', 3376, 69),\n    ('CellMass', 925, 19),\n    ('OtherInsolubleSolids', 4489, 92)\n]\n\npressure_filter_splits = find_split(*zip(*splits))\n\nsplits = [\n    ('Ethanol', 0, 1),\n    ('Water', 381300, 2241169),\n    ('Glucose', 0, 2),\n    ('Xylose', 1, 3),\n    ('OtherSugars', 1, 7),\n    ('SugarOligomers', 1, 6),\n    ('OrganicSolubleSolids', 79, 466),\n    ('InorganicSolubleSolids', 4828, 28378),\n    ('Ammonia', 3, 16),\n    ('Furfurals', 0, 3),\n    ('OtherOrganics', 1, 7),\n    ('CarbonDioxide', 6, 38),\n    ('O2', 3, 17),\n    ('N2', 5, 32),\n    ('Cellulose', 0, 194),\n    ('Xylan', 0, 65),\n    ('OtherStructuralCarbohydrates', 0, 15),\n    ('Lignin', 0, 1925),\n    ('Protein', 0, 90),\n    ('CellMass', 0, 19778),\n    ('OtherInsolubleSolids', 0, 707)\n]\n\nmembrane_bioreactor_splits = find_split(*zip(*splits))\n\ncentrifuge_species = ('Water', 'Glucose', 'Xylose', 'OtherSugars',\n                      'SugarOligomers', 'OrganicSolubleSolids',\n                      'InorganicSolubleSolids', 'Ammonia', 'Furfurals', \n                      'OtherOrganics', 'CO2', 'COxSOxNOxH2S', 'Cellulose',\n                      'Xylan', 'OtherStructuralCarbohydrates', 'Lignin',\n                      'Protein', 'CellMass', 'OtherInsolubleSolids')\nS623_flow = np.array([7708, 0, 0, 1, 1, 13, 75, 3, 0, 1, 1, 2, 25, 8, 2, 250, 52, 1523, 92])\nS616_flow = np.array([109098, 3, 6, 13, 9, 187, 1068, 46, 5, 8, 14, 31, 1, 0, 0, 13, 3, 80, 5])\n\nsludge_centrifuge_splits = find_split(centrifuge_species, S616_flow, S623_flow)", "meta": {"hexsha": "b69d09ff2d4ad62c2388ae4576aed06a994a4de4", "size": 5522, "ext": "py", "lang": "Python", "max_stars_repo_path": "BioSTEAM 2.x.x/biorefineries/cornstover/_legacy_code.py", "max_stars_repo_name": "blsymens/Bioindustrial-Park", "max_stars_repo_head_hexsha": "c1173646185d52f4b8d595ad088ade8e5216614d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2020-05-12T21:46:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T00:35:35.000Z", "max_issues_repo_path": "BioSTEAM 2.x.x/biorefineries/cornstover/_legacy_code.py", "max_issues_repo_name": "yalinli2/Bioindustrial-Park", "max_issues_repo_head_hexsha": "196e2d60ec9bf0466ef804d036c995b89bc72f72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2020-03-05T14:39:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T22:24:50.000Z", "max_forks_repo_path": "BioSTEAM 2.x.x/biorefineries/cornstover/_legacy_code.py", "max_forks_repo_name": "yalinli2/Bioindustrial-Park", "max_forks_repo_head_hexsha": "196e2d60ec9bf0466ef804d036c995b89bc72f72", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2020-05-14T13:02:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T19:41:07.000Z", "avg_line_length": 33.8773006135, "max_line_length": 95, "alphanum_fraction": 0.5061571894, "include": true, "reason": "import numpy", "num_tokens": 1733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.1873449731193599}}
{"text": "\"\"\"\ntoy_engine.py\n\n\n\"\"\"\n\nbd_results_string = \\\n\"\"\"<rates>\n  <solvent>\n    <kT> 1 </kT>\n    <debye_length> 1.0 </debye_length>\n    <dielectric> 78 </dielectric>\n    <vacuum_permittivity> 0.000142 </vacuum_permittivity>\n    <water_viscosity> 0.243 </water_viscosity>\n    <relative_viscosity> 1 </relative_viscosity>\n  </solvent>\n    <hydrodynamic_interactions> 0 </hydrodynamic_interactions>\n  <time_step_tolerances>\n    <minimum_core_dt> 0.2 </minimum_core_dt>\n    <minimum_core_rxn_dt> 0.05 </minimum_core_rxn_dt>\n    <minimum_chain_dt> 0 </minimum_chain_dt>\n    <minimum_chain_rxn_dt> 0 </minimum_chain_rxn_dt>\n  </time_step_tolerances>\n  <molecule_info>\n    <b_radius> {b_radius} </b_radius>\n    <b_reaction_rate> {b_reaction_rate} </b_reaction_rate>\n    <n_reactions> 1 </n_reactions>\n  </molecule_info>\n  <reactions>\n    <n_trajectories> {n_trajectories} </n_trajectories>\n    <stuck> 0 </stuck>\n    <escaped> {escaped} </escaped>\n    <completed>\n      <name> {name1} </name>\n      <n> {n1} </n>\n    </completed>\n    <completed>\n      <name> {name2} </name>\n      <n> {n2} </n>\n    </completed>\n  </reactions>\n  <n_bd_steps> 0 </n_bd_steps>\n</rates>\n\"\"\"\n\nimport numpy as np\n\ndef write_b_surface_output_file(output_file_name, k_on_src, b_transition_probs,\n                                milestone_transition_probs):\n    CONV_FACTOR = 602000000.0\n    b_reaction_rate = k_on_src / CONV_FACTOR\n    N_TRAJS = 1000000000\n    for key in b_transition_probs:\n        if key == \"escaped\":\n            escaped = int(b_transition_probs[\"escaped\"] * N_TRAJS)\n        else:\n            key1 = key\n            name1 = \"b_%s\" % key\n            n1 = int(b_transition_probs[key] * N_TRAJS)\n            \n    for key in milestone_transition_probs:\n        if key == \"escaped\":\n            escaped2 = int(milestone_transition_probs[\"escaped\"] * n1)\n            pass\n        else:\n            name2 = \"%s_%s\" % (key1, key)\n            n2 = int(milestone_transition_probs[key] * n1)\n    \n    new_result = bd_results_string.format(\n        b_radius=0.0, b_reaction_rate=b_reaction_rate, n_trajectories=N_TRAJS,\n        escaped=escaped+escaped2, name1=name1, n1=n1, name2=name2, n2=n2)\n    #print(\"new_result:\", new_result)\n    with open(output_file_name, \"w\") as f:\n        f.write(new_result)\n    \n    return\n\nclass BrownianParticle():\n    def __init__(self, mass, dimensions, position, velocity, diffusion,\n                 potential_energy_function):\n        self.mass = mass\n        self.dimensions = dimensions\n        assert len(position.shape) == dimensions\n        self.position = position\n        self.velocity = velocity\n        self.diffusion = diffusion\n        self.potential_energy_function = potential_energy_function\n        return\n\n\n\nclass ToyIntegrator():\n    \"\"\"\n    Base class for toy integrators.\n    \"\"\"\n    def __init__(self):\n        pass\n\nclass SmoluchowskiSphericalMMVTIntegrator(ToyIntegrator):\n    \"\"\"\n    An integrator that generates MMVT output files based on a Smoluchowski\n    region.\n    \"\"\"\n    def __init__(self, calc, index, output_file_name, style=\"openmm\"):\n        self.calc = calc\n        self.index = index\n        self.style = style.lower()\n        self.output_file_name = output_file_name\n        self._generate_output_file_header()\n        self.in_state = 1\n        self.time = 0.0\n        self.bounce_counter = 0\n        self.timestep = 0.002\n        self.N_i_j_alpha_dict, self.R_i_alpha_dict, self.N_alpha_beta_dict, self.T_alpha \\\n            = self.calc.regions[self.index].produce_mmvt_statistics(self.index)\n        return\n        \n    def _generate_output_file_header(self):\n        if self.style==\"openmm\":\n            header = \"#\\\"Bounced boundary ID\\\",\\\"bounce index\\\",\\\"total time (ps)\\n\"\n        elif self.style==\"namd\":\n            header = \"# NAMD TEST OUTPUT\\n\"\n        else:\n            header = \"UNKNOWN OUTPUT STYLE\"\n        with open(self.output_file_name, \"w\") as f:\n            f.write(header)\n        return\n    \n    def _write_bounce_to_output_file(self, line):\n        with open(self.output_file_name, \"a\") as f:\n            f.write(line)\n        return\n    \"\"\" # TODO: remove if the other version is good enough\n    def _write_random_transition(self, starting_step, num_steps):\n        # TODO: perhaps this algorithm can be improved by not sampling times\n        #  for both transitions and bounces, but rather using the number\n        #  of transitions per bounce to decide when a bounce becomes a \n        #  transition?\n        MAX_ITER = 1e9\n        step_time = 0.0\n        N_i_j_alpha_dict, R_i_alpha_dict, N_alpha_beta_dict, T_alpha \\\n            = self.calc.regions[self.index].produce_mmvt_statistics(self.index)\n        available_transition_dict = {}\n        available_transitions = []\n        transition_probabilities = []\n        total_transitions_out_of_state = 0\n        for key in N_i_j_alpha_dict:\n            if key[0] == self.in_state:\n                available_transition_dict[key[1]] = N_i_j_alpha_dict[key]\n                total_transitions_out_of_state += N_i_j_alpha_dict[key]\n        \n        probability_sum = sum(available_transition_dict.values())\n        for key in available_transition_dict:\n            available_transitions.append(key)\n            transition_probabilities.append(available_transition_dict[key]/probability_sum)\n        \n        if len(available_transitions) == 0:\n            time_in_this_transition = 1e9\n            avg_time_between_self_bounces = T_alpha / N_alpha_beta_dict[self.in_state]\n        else:\n            next_state = np.random.choice(a=np.array(available_transitions), \n                                          p=np.array(transition_probabilities))\n            avg_transition_time = R_i_alpha_dict[self.in_state] / total_transitions_out_of_state\n            time_in_this_transition = np.random.exponential(avg_transition_time)\n            avg_time_between_self_bounces = R_i_alpha_dict[self.in_state] / N_alpha_beta_dict[self.in_state]\n            \n        # sample times in while loop until time_between_transitions is exceeded\n        counter = 0\n        while True:\n            time_in_this_self_bounce = np.random.exponential(avg_time_between_self_bounces)\n            step_time += time_in_this_self_bounce\n            if step_time > time_in_this_transition:\n                break\n            if self.style==\"openmm\":\n                bounce_str = \"{},{},{}\\n\".format(self.in_state, self.bounce_counter, self.time+step_time)\n                \n            #print(bounce_str)\n            self._write_bounce_to_output_file(bounce_str)\n            self.bounce_counter += 1\n            if self.bounce_counter >= starting_step + num_steps:\n                return\n            if counter > MAX_ITER: \n                raise Exception(\"Max iterations reached.\")\n            counter += 1\n        \n        self.time += time_in_this_transition   \n        self.in_state = next_state \n        if self.style==\"openmm\":\n            bounce_str = \"{},{},{}\\n\".format(self.in_state, self.bounce_counter, self.time)\n        #print(bounce_str)\n        self._write_bounce_to_output_file(bounce_str)\n        self.bounce_counter += 1\n        return\n    \"\"\"\n    \n    def _write_random_transition(self, starting_step, num_steps):\n        # TODO: perhaps this algorithm can be improved by not sampling times\n        #  for both transitions and bounces, but rather using the number\n        #  of transitions per bounce to decide when a bounce becomes a \n        #  transition?\n        MAX_ITER = 1e9\n        step_time = 0.0\n        \n        available_transition_dict = {}\n        available_transitions = []\n        transition_probabilities = []\n        total_transitions_out_of_state = 0\n        for key in self.N_i_j_alpha_dict:\n            if key[0] == self.in_state:\n                available_transition_dict[key[1]] = self.N_i_j_alpha_dict[key]\n                total_transitions_out_of_state += self.N_i_j_alpha_dict[key]\n        \n        probability_sum = sum(available_transition_dict.values())\n        for key in available_transition_dict:\n            available_transitions.append(key)\n            transition_probabilities.append(available_transition_dict[key]/probability_sum)\n        \n        if len(available_transitions) == 0:\n            time_in_this_transition = 1e9\n            avg_time_between_self_bounces = self.T_alpha / self.N_alpha_beta_dict[self.in_state]\n            bounces_per_transition = 1e9\n        else:\n            next_state = np.random.choice(a=np.array(available_transitions), \n                                          p=np.array(transition_probabilities))\n            avg_transition_time = self.R_i_alpha_dict[self.in_state] / total_transitions_out_of_state\n            time_in_this_transition = np.random.exponential(avg_transition_time)\n            avg_time_between_self_bounces = self.R_i_alpha_dict[self.in_state] / self.N_alpha_beta_dict[self.in_state]\n            avg_bounces_per_transition = self.N_alpha_beta_dict[self.in_state] / total_transitions_out_of_state\n            bounces_per_transition = np.random.exponential(avg_bounces_per_transition)\n            \n        # sample times in while loop until time_between_transitions is exceeded\n        counter = 1\n        while True:\n            if counter > bounces_per_transition:\n                break\n            time_in_this_self_bounce = np.random.exponential(avg_time_between_self_bounces)\n            step_time += time_in_this_self_bounce\n            \n            if self.style==\"openmm\":\n                bounce_str = \"{},{},{}\\n\".format(self.in_state, self.bounce_counter, self.time+step_time)\n            elif self.style==\"namd\":\n                if self.in_state == 1:\n                    new_anchor = self.index - 1\n                    new_milestone = self.index - 1\n                elif self.in_state == 2:\n                    new_anchor = self.index + 1\n                    new_milestone = self.index\n                    \n                if new_anchor == -1:\n                    new_anchor = 1\n                    new_milestone = self.index\n                    \n                template=\"SEEKR: Cell Collision: current: {}, new: {}, stepnum: {}\\n\"\n                bounce_str = template.format(self.index, new_anchor, int((self.time+step_time)/self.timestep))\n                if self.bounce_counter == 0:\n                    template=\"SEEKR: Milestone Transition: anchor: {}, source: {}, destination: {}, stepnum: {}, incubation steps: {}\\n\"\n                    bounce_str += template.format(\n                        self.index, \"none\", new_milestone, \n                        int((self.time+step_time)/self.timestep), \n                        int(step_time/self.timestep))\n            \n            self._write_bounce_to_output_file(bounce_str)\n            self.bounce_counter += 1\n            \n            if self.bounce_counter >= starting_step + num_steps:\n                return\n            \n            if counter > MAX_ITER:\n                raise Exception(\"Max iterations exceeded.\")\n            counter += 1\n        \n        self.time += step_time   \n        prev_state = self.in_state\n        self.in_state = next_state \n        if self.style==\"openmm\":\n            bounce_str = \"{},{},{}\\n\".format(self.in_state, self.bounce_counter, self.time)\n        elif self.style==\"namd\":\n            if self.in_state == 1:\n                new_anchor = self.index - 1\n                old_milestone = self.index\n                new_milestone = self.index - 1\n            elif self.in_state == 2:\n                new_anchor = self.index + 1\n                old_milestone = self.index - 1\n                new_milestone = self.index\n            if self.bounce_counter == 0:\n                old_milestone = \"none\"\n            template=\"SEEKR: Cell Collision: current: {}, new: {}, stepnum: {}\\n\"\\\n                     +\"SEEKR: Milestone Transition: anchor: {}, source: {}, destination: {}, stepnum: {}, incubation steps: {}\\n\"\n            bounce_str = template.format(self.index, new_anchor, int((self.time)/self.timestep),\n                                         self.index, old_milestone, new_milestone, int((self.time)/self.timestep), int(step_time/self.timestep))\n        self._write_bounce_to_output_file(bounce_str)\n        #print(\"bounce_str:\", bounce_str)\n        self.bounce_counter += 1\n        return\n        \n    def step(self, number):\n        starting_step = self.bounce_counter\n        while self.bounce_counter < number:\n            self._write_random_transition(starting_step, number)\n            \n        return\n    \nclass SmoluchowskiSphericalElberIntegrator(ToyIntegrator):\n    \"\"\"\n    An integrator that generates MMVT output files based on a Smoluchowski\n    region.\n    \"\"\"\n    def __init__(self, calc, index, output_file_name, style=\"openmm\"):\n        self.calc = calc\n        self.index = index\n        self.style = style.lower()\n        self.output_file_name = output_file_name\n        self._generate_output_file_header()\n        self.in_state = index\n        self.time = 0.0\n        self.bounce_counter = 0\n        self.timestep = 1.0\n        self.elberN_ij, self.elberR_i = self.calc.produce_elber_statistics()\n        return\n        \n    def _generate_output_file_header(self):\n        if self.style==\"openmm\":\n            header = \"#\\\"Bounced boundary ID\\\",\\\"bounce index\\\",\\\"total time (ps)\\n\"\n        else:\n            header = \"UNKNOWN OUTPUT STYLE\"\n        with open(self.output_file_name, \"w\") as f:\n            f.write(header)\n        return\n    \n    def _write_bounce_to_output_file(self, line):\n        with open(self.output_file_name, \"a\") as f:\n            f.write(line)\n        return\n    \n    def _write_random_transition(self, starting_step, num_steps):\n        # TODO: perhaps this algorithm can be improved by not sampling times\n        #  for both transitions and bounces, but rather using the number\n        #  of transitions per bounce to decide when a bounce becomes a \n        #  transition?\n        \n        available_transition_dict = {}\n        available_transitions = []\n        transition_probabilities = []\n        total_transitions_out_of_state = 0\n        for key in self.elberN_ij:\n            if key[0] == self.in_state:\n                available_transition_dict[key[1]] = self.elberN_ij[key]\n                total_transitions_out_of_state += self.elberN_ij[key]\n        \n        probability_sum = sum(available_transition_dict.values())\n        for key in available_transition_dict:\n            available_transitions.append(key)\n            transition_probabilities.append(available_transition_dict[key]/probability_sum)\n        \n        next_state = np.random.choice(a=np.array(available_transitions), \n                                        p=np.array(transition_probabilities))\n        avg_transition_time = self.elberR_i[self.in_state]\n        step_time = np.random.exponential(avg_transition_time)\n        \n        transition_alias = next_state - self.in_state + 2\n        self.time += step_time   \n        \n        if self.style==\"openmm\":\n            bounce_str = \"{},{},{}\\n\".format(transition_alias, self.bounce_counter, step_time)\n        #print(bounce_str)\n        self._write_bounce_to_output_file(bounce_str)\n        self.bounce_counter += 1\n        return\n        \n    def step(self, number):\n        starting_step = self.bounce_counter\n        while self.bounce_counter < number:\n            self._write_random_transition(starting_step, number)\n            \n        return\n    \n", "meta": {"hexsha": "c7391d10c81af60302482bff90922369f50ea838", "size": 15439, "ext": "py", "lang": "Python", "max_stars_repo_path": "seekr2/toy/toy_engine.py", "max_stars_repo_name": "seekrcentral/seekr2", "max_stars_repo_head_hexsha": "45154d477147f9278b97491a6270ff31435c837b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-14T16:13:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T16:13:17.000Z", "max_issues_repo_path": "seekr2/toy/toy_engine.py", "max_issues_repo_name": "seekrcentral/seekr2", "max_issues_repo_head_hexsha": "45154d477147f9278b97491a6270ff31435c837b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2021-05-26T15:29:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T18:23:20.000Z", "max_forks_repo_path": "seekr2/toy/toy_engine.py", "max_forks_repo_name": "seekrcentral/seekr2", "max_forks_repo_head_hexsha": "45154d477147f9278b97491a6270ff31435c837b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-22T01:15:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T01:15:46.000Z", "avg_line_length": 40.8439153439, "max_line_length": 144, "alphanum_fraction": 0.6119567329, "include": true, "reason": "import numpy", "num_tokens": 3459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.18734497167116682}}
{"text": "from corvus.structures import Handler, Exchange, Loop, Update\nimport corvutils.pyparsing as pp\nimport os, sys, subprocess, shutil #, resource\nimport re\nfrom scipy.interpolate import CubicSpline\nfrom scipy.integrate import quad\nfrom scipy.signal import convolve\nimport numpy as np\n# Debug: FDV\nimport pprint\n\npp_debug = pprint.PrettyPrinter(indent=4)\n\n\n# Define dictionary of implemented calculations\nimplemented = {}\nstrlistkey = lambda L:','.join(sorted(L))\nsubs = lambda L:[{L[j] for j in range(len(L)) if 1<<j&k} for k in range(1,1<<len(L))]\n#for s in subs(['cell_vectors', 'cell_struct_xyz_red', 'cell_scaling_iso', 'cell_scaling_abc', 'number_density']):\n#    key = strlistkey(s)\n#    autodesc = 'Get ' + ', '.join(s) + ' using cif2cell'\n#    cost = 10\n#    implemented[key] = {'type':'Exchange','out':list(s),'req':['cif_input'],\n#                        'desc':autodesc,'cost':cost}\n\nimplemented['mbxanes'] = {'type':'Exchange','out':['mbxanes'],'cost':0,\n                        'req':['xanes_cfavg','spectralFunction'],'desc':'Calculate many-body xanes from xanes and spectral function.'}\n#'req':['xanes','spectal_function'],'desc':'Calculate supercell from cif input.'}\n\n\n\nclass mbconv(Handler):\n    def __str__(self):\n        return 'mbconv Handler'\n\n    @staticmethod\n    def canProduce(output):\n        if isinstance(output, list) and output and isinstance(output[0], str):\n            return strlistkey(output) in implemented\n        elif isinstance(output, str):\n            return output in implemented\n        else:\n            raise TypeError('Output should be token or list of tokens')\n\n    @staticmethod\n    def requiredInputFor(output):\n        if isinstance(output, list) and output and isinstance(output[0], str):\n            unresolved = {o for o in output if not mbconv.canProduce(o)}\n            canProduce = (o for o in output if mbconv.canProduce(o))\n            additionalInput = (set(implemented[o]['req']) for o in canProduce)\n            return list(set.union(unresolved,*additionalInput))\n        elif isinstance(output, str):\n            if output in implemented:\n                return implemented[output]['req']\n            else:\n                return [output]\n        else:\n            raise TypeError('Output should be token or list of tokens')\n\n    @staticmethod\n    def cost(output):\n        if isinstance(output, list) and output and isinstance(output[0], str):\n            key = strlistkey(output)\n        elif isinstance(output, str):\n            key = output\n        else:\n            raise TypeError('Output should be token or list of tokens')\n        if key not in implemented:\n            raise LookupError('Corvus cannot currently produce ' + key + ' using FEFF')\n        return implemented[key]['cost']\n\n    @staticmethod\n    def sequenceFor(output,inp=None):\n        if isinstance(output, list) and output and isinstance(output[0], str):\n            key = strlistkey(output)\n        elif isinstance(output, str):\n            key = output\n        else:\n            raise TypeError('Output should be token of list of tokens')\n        if key not in implemented:\n            raise LookupError('Corvus cannot currently produce ' + key + ' using FEFF')\n        f = lambda subkey : implemented[key][subkey]\n        required = f('req')\n        # JJK - Need to add requirements of internal workflow here.\n        if 'mbconv' in list(inp.keys()):\n            required.extend()\n\n        if f('type') is 'Exchange':\n            return Exchange(mbconv, f('req'), f('out'), cost=f('cost'), desc=f('desc'))\n\n    @staticmethod\n    def prep(config):\n        subdir = config['pathprefix'] + str(config['xcIndex']) + '_MBXANES'\n        xcDir = os.path.join(config['cwd'], subdir)\n        # Make new output directory if if doesn't exist\n        if not os.path.exists(xcDir):\n            os.mkdir(xcDir)\n        # Store current Exchange directory in configuration\n        config['xcDir'] = xcDir\n\n    #@staticmethod\n    #def setDefaults(input,target):\n\n    @staticmethod\n    def run(config, input, output):\n\n\n          \n        # Loop over targets in output.\n        if 'mbxanes' in output:\n            # In future use file_reader handler to read in XANES and spectral function if already calculated.\n            w  = np.array(input.get('xanes_cfavg')[0])\n            mu0= np.array(input.get('xanes_cfavg')[1])\n            wsf= np.flip(-1.0*np.array(input.get('spectralFunction')[0]))\n            sf = np.flip(np.array(input.get('spectralFunction')[1]))\n            # Interpolate both XANES and spectral function onto an even grid\n            #w, mu0 = np.loadtxt('xanes.dat',usecols = (0,1)).T\n            #wsf,sf = np.loadtxt('spfcn.dat',usecols = (0,1)).T\n            min_diff = np.amin(np.ediff1d(w))\n            min_diff = min(min_diff,np.amin(np.ediff1d(wsf)))\n        \n            mu0_cs = CubicSpline(w,mu0)\n            spfcn_cs = CubicSpline(wsf,sf)\n            # Use larger of two ranges to specify range\n            w_terp = np.arange(w[0],w[-1],min_diff)\n            wsf_terp = np.arange(wsf[0],wsf[-1],min_diff)\n            mu0_terp = mu0_cs(w_terp)\n            spfcn_terp = spfcn_cs(wsf_terp)\n \n            mu_mb = convolve(mu0_terp,spfcn_terp,mode='full')*min_diff\n\n            # If extra broadening is requested, perform a convolution of that as well.\n            if 'mbconv.extra_broadening' in input:\n                gam = input['mbconv.extra_broadening'][0][0]\n                A_br = gam/np.pi*1.0/(wsf_terp**2 + gam**2)\n                mu_mb = np.convolve(mu_mb,A_br,mode='same')*min_diff\n              \n            scale=w_terp[-1] - w_terp[0] + wsf_terp[-1] - wsf_terp[0]\n            first = w_terp[0] + wsf_terp[0]\n            w_terp = np.linspace(0.0,scale,mu_mb.size) \n            w_terp = w_terp + first\n            mu0_terp = mu0_cs(w_terp)\n            output['mbxanes'] = [w_terp,mu_mb]\n            np.savetxt('mbxanes.dat',np.array([w_terp, mu_mb, mu0_terp]).transpose())\n\n\n\n    @staticmethod\n    def cleanup(config):\n        pass\n\n\n\n\n\n", "meta": {"hexsha": "7918413da980e8dfc885d519b72673f012268055", "size": 5995, "ext": "py", "lang": "Python", "max_stars_repo_path": "corvus/mbconv.py", "max_stars_repo_name": "times-software/Corvus", "max_stars_repo_head_hexsha": "d220e2db28743ecb6748e2a245eb3992daa554c1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-09-16T21:07:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T17:08:38.000Z", "max_issues_repo_path": "corvus/mbconv.py", "max_issues_repo_name": "times-software/Corvus", "max_issues_repo_head_hexsha": "d220e2db28743ecb6748e2a245eb3992daa554c1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "corvus/mbconv.py", "max_forks_repo_name": "times-software/Corvus", "max_forks_repo_head_hexsha": "d220e2db28743ecb6748e2a245eb3992daa554c1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4294871795, "max_line_length": 134, "alphanum_fraction": 0.6040033361, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.3140505578320071, "lm_q1q2_score": 0.18731016229390468}}
{"text": "import os\nimport numpy as np\nimport matplotlib.pyplot as pyplot\nfrom simtk import unit\nfrom foldamers.cg_model.cgmodel import CGModel\nfrom foldamers.parameters.reweight import *\nfrom foldamers.thermo.calc import calculate_heat_capacity\nfrom foldamers.utilities.util import random_positions\nfrom cg_openmm.build.cg_build import build_topology\nfrom cg_openmm.simulation.rep_exch import *\nfrom foldamers.ensembles.ens_build import *\nfrom foldamers.thermo.calc import *\n\n# Job settings\ntop_directory = \"output\"\nif not os.path.exists(top_directory):\n    os.mkdir(top_directory)\n\n# OpenMM simulation settings\nprint_frequency = 5  # Number of steps to skip when printing output\ntotal_simulation_time = 5.0 * unit.nanosecond  # Units = picoseconds\nsimulation_time_step = 5.0 * unit.femtosecond\ntotal_steps = round(total_simulation_time.__div__(simulation_time_step))\n\n# Yank (replica exchange) simulation settings\noutput_data = str(str(top_directory) + \"/output.nc\")\nnumber_replicas = 30\nmin_temp = 5.0 * unit.kelvin\nmax_temp = 100.0 * unit.kelvin\ntemperature_list = get_temperature_list(min_temp, max_temp, number_replicas)\nprint(\"Using \" + str(len(temperature_list)) + \" replicas.\")\nif total_steps > 10000:\n    exchange_attempts = round(total_steps / 1000)\nelse:\n    exchange_attempts = 10\n\n###\n#\n# Global coarse grained model definitions\n#\n###\nbackbone_length = 1\nsidechain_length = 1\nsidechain_positions = 0\ninclude_bond_forces = False\ninclude_bond_angle_forces = True\ninclude_nonbonded_forces = True\ninclude_torsion_forces = True\nconstrain_bonds = True\n\n# Particle properties\nmass = 100.0 * unit.amu\nmasses = {\"backbone_bead_masses\": mass, \"sidechain_bead_masses\": mass}\n\n# Bonded interaction properties\nbond_length = 7.5 * unit.angstrom\nbond_lengths = {\n    \"bb_bb_bond_length\": bond_length,\n    \"bb_sc_bond_length\": bond_length,\n    \"sc_sc_bond_length\": bond_length,\n}\nbond_force_constant = 1250 * unit.kilojoule_per_mole / unit.nanometer / unit.nanometer\nbond_force_constants = {\n    \"bb_bb_bond_k\": bond_force_constant,\n    \"bb_sc_bond_k\": bond_force_constant,\n    \"sc_sc_bond_k\": bond_force_constant,\n}\n\n# Bond angle properties\nbond_angle_force_constant = 0.0002 * unit.kilojoule_per_mole / unit.radian / unit.radian\nbond_angle_force_constants = {\n    \"bb_bb_bb_angle_k\": bond_angle_force_constant,\n    \"bb_bb_sc_angle_k\": bond_angle_force_constant,\n    \"bb_sc_sc_angle_k\": bond_angle_force_constant,\n    \"sc_sc_sc_angle_k\": bond_angle_force_constant,\n    \"sc_bb_sc_angle_k\": bond_angle_force_constant,\n    \"sc_sc_bb_angle_k\": bond_angle_force_constant,\n}\nequil_bond_angle = 92\nequil_bond_angles = {\n    \"bb_bb_bb_angle_0\": equil_bond_angle,\n    \"bb_bb_sc_angle_0\": equil_bond_angle,\n    \"bb_sc_sc_angle_0\": equil_bond_angle,\n    \"sc_sc_sc_angle_0\": equil_bond_angle,\n    \"sc_bb_sc_angle_0\": equil_bond_angle,\n    \"sc_sc_bb_angle_0\": equil_bond_angle,\n}\n\n# Torsion properties\ntorsion_force_constant = 0.0002\ntorsion_force_constants = {\n    \"bb_bb_bb_bb_torsion_k\": torsion_force_constant,\n    \"bb_bb_bb_sc_torsion_k\": torsion_force_constant,\n    \"bb_bb_sc_sc_torsion_k\": torsion_force_constant,\n    \"bb_sc_sc_sc_torsion_k\": torsion_force_constant,\n    \"sc_bb_bb_sc_torsion_k\": torsion_force_constant,\n    \"bb_sc_sc_bb_torsion_k\": torsion_force_constant,\n    \"sc_sc_sc_sc_torsion_k\": torsion_force_constant,\n    \"sc_bb_bb_bb_torsion_k\": torsion_force_constant,\n}\nequil_torsion_angle = 52\nequil_torsion_angles = {\n    \"bb_bb_bb_bb_torsion_0\": equil_torsion_angle,\n    \"bb_bb_bb_sc_torsion_0\": equil_torsion_angle,\n    \"bb_bb_sc_sc_torsion_0\": equil_torsion_angle,\n    \"bb_sc_sc_sc_torsion_0\": equil_torsion_angle,\n    \"sc_bb_bb_sc_torsion_0\": equil_torsion_angle,\n    \"bb_sc_sc_bb_torsion_0\": equil_torsion_angle,\n    \"sc_sc_sc_sc_torsion_0\": equil_torsion_angle,\n    \"sc_bb_bb_bb_torsion_0\": equil_torsion_angle,\n}\n\nsigma = 2.0 * bond_length\nsigmas = {\"bb_bb_sigma\": sigma, \"sc_sc_sigma\": sigma}\nepsilon = 0.2 * unit.kilocalorie_per_mole\nepsilons = {\"bb_bb_eps\": epsilon, \"bb_sc_eps\": epsilon, \"sc_sc_eps\": epsilon}\n\n# Heteropolymer definitions\nheteropolymer = True\n\n# Define individual monomer properties\nmonomer_name = \"A\"\nnum_beads = backbone_length + sidechain_length\nsigmas = {\"bb_bb_sigma\": sigma, \"bb_sc_sigma\": sigma, \"sc_sc_sigma\": 2.0 * sigma}\nA = {\n    \"monomer_name\": monomer_name,\n    \"backbone_length\": backbone_length,\n    \"sidechain_length\": sidechain_length,\n    \"sidechain_positions\": sidechain_positions,\n    \"num_beads\": num_beads,\n    \"bond_lengths\": bond_lengths,\n    \"epsilons\": epsilons,\n    \"sigmas\": sigmas,\n}\n\nmonomer_name = \"B\"\nnum_beads = backbone_length + sidechain_length\nsigmas = {\"bb_bb_sigma\": sigma, \"bb_sc_sigma\": sigma, \"sc_sc_sigma\": 0.8 * sigma}\nB = {\n    \"monomer_name\": monomer_name,\n    \"backbone_length\": backbone_length,\n    \"sidechain_length\": sidechain_length,\n    \"sidechain_positions\": sidechain_positions,\n    \"num_beads\": num_beads,\n    \"bond_lengths\": bond_lengths,\n    \"epsilons\": epsilons,\n    \"sigmas\": sigmas,\n}\n\nmonomer_types = [A, B]\n\nsequence = [A, A, A, B, A, A, A, B, A, A, A, B]\npolymer_length = len(sequence)\n\ncgmodel = CGModel(\n    polymer_length=polymer_length,\n    bond_force_constants=bond_force_constants,\n    bond_angle_force_constants=bond_angle_force_constants,\n    torsion_force_constants=torsion_force_constants,\n    equil_bond_angles=equil_bond_angles,\n    equil_torsion_angles=equil_torsion_angles,\n    include_nonbonded_forces=include_nonbonded_forces,\n    include_bond_forces=include_bond_forces,\n    include_bond_angle_forces=include_bond_angle_forces,\n    include_torsion_forces=include_torsion_forces,\n    constrain_bonds=constrain_bonds,\n    heteropolymer=True,\n    monomer_types=monomer_types,\n    sequence=sequence,\n)\n\nif not os.path.exists(output_data):\n    replica_energies, replica_positions, replica_states = run_replica_exchange(\n        cgmodel.topology,\n        cgmodel.system,\n        cgmodel.positions,\n        temperature_list=temperature_list,\n        simulation_time_step=simulation_time_step,\n        total_simulation_time=total_simulation_time,\n        print_frequency=print_frequency,\n        output_data=output_data,\n    )\n    make_replica_pdb_files(cgmodel.topology, replica_positions)\nelse:\n    replica_energies, replica_positions, replica_states = read_replica_exchange_data(\n        system=cgmodel.system,\n        topology=cgmodel.topology,\n        temperature_list=temperature_list,\n        output_data=output_data,\n        print_frequency=print_frequency,\n    )\n\nC_v, dC_v, new_temperature_list = get_heat_capacity(\n    replica_energies, temperature_list, num_intermediate_states=1\n)\n\nexit()\n", "meta": {"hexsha": "7df2984170e716d08955bd8b8ad7e6c9b59322c8", "size": 6597, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/evaluating_heat_capacity/heteropolymer_heat_capacity/heteropolymer.py", "max_stars_repo_name": "shirtsgroup/foldamers", "max_stars_repo_head_hexsha": "b67c164aff31cf7b6ff64d7b121059b75eaaf14c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-30T19:02:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-30T19:02:50.000Z", "max_issues_repo_path": "examples/evaluating_heat_capacity/heteropolymer_heat_capacity/heteropolymer.py", "max_issues_repo_name": "shirtsgroup/foldamers", "max_issues_repo_head_hexsha": "b67c164aff31cf7b6ff64d7b121059b75eaaf14c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 40, "max_issues_repo_issues_event_min_datetime": "2020-01-16T00:42:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-07T19:34:45.000Z", "max_forks_repo_path": "examples/evaluating_heat_capacity/heteropolymer_heat_capacity/heteropolymer.py", "max_forks_repo_name": "shirtsgroup/foldamers", "max_forks_repo_head_hexsha": "b67c164aff31cf7b6ff64d7b121059b75eaaf14c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-04T14:24:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-13T16:04:46.000Z", "avg_line_length": 33.3181818182, "max_line_length": 88, "alphanum_fraction": 0.7732302562, "include": true, "reason": "import numpy", "num_tokens": 1848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.18724444485609393}}
{"text": "\"\"\"\nDescription:\nAuthor: Jiaqi Gu (jqgu@utexas.edu)\nDate: 2021-12-27 02:35:47\nLastEditors: Jiaqi Gu (jqgu@utexas.edu)\nLastEditTime: 2021-12-27 02:45:29\n\"\"\"\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom pyutils.quantize import input_quantize_fn, weight_quantize_fn\nfrom torch import nn\nfrom torch.nn import Parameter, init\nfrom torch.types import Device\n\n__all__ = [\"MLGConv2d\"]\n\n\nclass MLGConv2d(nn.Module):\n    \"\"\"\n    description: Conv2d layer with memory-efficient multi-level generation (MLG)\n    \"\"\"\n\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        kernel_size: int = 3,\n        stride: int = 1,\n        padding: int = 1,\n        bias: bool = False,\n        w_bit: int = 16,\n        in_bit: int = 16,\n        device: Device = torch.device(\"cuda\"),\n    ):\n        super().__init__()\n        self.in_channels = in_channels\n        self.out_channels = out_channels\n        self.kernel_size = kernel_size\n        self.stride = stride\n        self.padding = padding\n\n        self.w_bit = w_bit\n        self.qb = w_bit\n        self.qu = w_bit\n        self.qv = w_bit\n        self.in_bit = in_bit\n        self.device = device\n\n        ### allocate parameters\n        self.weight = None\n        ### build trainable parameters\n        self.build_parameters()\n\n        ### quantization tool\n        self.input_quantizer = input_quantize_fn(self.in_bit, alg=\"normal\", device=self.device)\n\n        self.weight_quantizer = weight_quantize_fn(self.w_bit, alg=\"dorefa_sym\")\n        self.basis_quantizer = weight_quantize_fn(self.qb, alg=\"dorefa_sym\")\n        self.coeff_in_quantizer = weight_quantize_fn(self.qu, alg=\"dorefa_sym\")\n        self.coeff_out_quantizer = weight_quantize_fn(self.qv, alg=\"dorefa_sym\")\n\n        ### default set to slow forward\n        self.disable_fast_forward()\n        ### default disable dynamic weight generation\n        self.disable_dynamic_weight()\n        self.eye_b = None\n        self.eye_v = None\n\n        if bias:\n            self.bias = Parameter(torch.Tensor(out_channels).to(self.device))\n        else:\n            self.register_parameter(\"bias\", None)\n\n    def build_parameters(self):\n        self.weight = Parameter(\n            torch.Tensor(self.out_channels, self.in_channels, self.kernel_size, self.kernel_size)\n            .to(self.device)\n            .float()\n        )\n\n    def reset_parameters(self):\n        init.kaiming_normal_(self.weight.data, mode=\"fan_out\", nonlinearity=\"relu\")\n\n        if self.bias is not None:\n            fan_in = self.in_channels * self.kernel_size ** 2\n            bound = 1 / np.sqrt(fan_in)\n            init.uniform_(self.bias, -bound, bound)\n\n    def build_weight(self):\n        if self.w_bit < 16:\n            if self.dynamic_weight_flag:\n                if self.coeff_in is not None:\n                    coeff_in = self.coeff_in_quantizer(self.coeff_in)\n                    self.basis = self.weight[\n                        : self.base_out, : self.base_in, ...\n                    ]  # [base_out, base_in, k, k]\n                else:\n                    coeff_in = None\n                    self.basis = self.weight[: self.base_out, ...]  # [base_out, inc, k, k]\n                basis = self.basis_quantizer(self.basis)\n                if self.coeff_out is not None:\n                    coeff_out = self.coeff_out_quantizer(self.coeff_out)\n                else:\n                    coeff_out = None\n                weight = self.weight_generation(basis, coeff_in, coeff_out)\n            else:\n                weight = self.weight_quantizer(self.weight)\n        else:\n            weight = self.weight\n            if self.dynamic_weight_flag:\n                if self.coeff_in is not None:\n                    self.basis = weight[: self.base_out, : self.base_in, ...]  # [base_out, base_in, k, k]\n                else:\n                    self.basis = weight[: self.base_out, ...]  # [base_out, inc, k, k]\n\n                weight = self.weight_generation(self.basis, self.coeff_in, self.coeff_out)\n\n        return weight\n\n    def enable_fast_forward(self):\n        self.fast_forward_flag = True\n\n    def disable_fast_forward(self):\n        self.fast_forward_flag = False\n\n    def load_parameters(self, param_dict):\n        \"\"\"\n        description: update parameters based on this parameter dictionary\\\\\n        param param_dict {dict of dict} {layer_name: {param_name: param_tensor, ...}, ...}\n        \"\"\"\n        for name, param in param_dict.items():\n            getattr(self, name).data.copy_(param)\n\n    def enable_dynamic_weight(self, base_in, base_out):\n        ### multi-level weight generation\n        self.base_in = base_in  # input channel base\n        self.base_out = base_out  # output channel base\n\n        if base_out == 0:  ## disable cross-kernel generation\n            self.base_out = self.out_channels  ## maximum\n        elif min(self.out_channels, self.in_channels * self.kernel_size ** 2) > self.base_out > 0:\n            ### enable generation\n            self.base_out = base_out\n        else:\n            ### base_out is too large, cannot save param, then disable it\n            self.base_out = self.out_channels\n\n        ### only when base_in < min(in_channel, kernel_size**2), will intra-kernel generation save #params.\n        if min(self.in_channels, self.kernel_size ** 2) > self.base_in > 0:\n            self.coeff_in = Parameter(\n                torch.Tensor(self.base_out, self.in_channels, self.base_in).to(self.device)\n            )\n            # init.xavier_normal_(self.coeff_in)\n            init.kaiming_normal_(self.coeff_in, mode=\"fan_out\", nonlinearity=\"relu\")\n        else:\n            ### base_in >= min(in_channel, kernel_size**2), will use the original weight\n            self.coeff_in = None\n        ### onlt when base_out < min(out_channel, in_channel*kernel_size**2), will cross-kernel generation save #params.\n        if min(self.out_channels, self.in_channels * self.kernel_size ** 2) > self.base_out > 0:\n            self.coeff_out = Parameter(torch.Tensor(self.out_channels, self.base_out).to(self.device))\n            init.kaiming_normal_(self.coeff_out, mode=\"fan_out\", nonlinearity=\"relu\")\n        else:\n            self.coeff_out = None\n\n        self.dynamic_weight_flag = True if self.coeff_in is not None or self.coeff_out is not None else False\n        if self.dynamic_weight_flag:\n            if self.coeff_in is not None:\n                self.basis = self.weight[: self.base_out, : self.base_in, ...]\n            else:\n                self.basis = self.weight[: self.base_out, ...]\n        else:\n            self.basis = None\n\n    def disable_dynamic_weight(self):\n        self.dynamic_weight_flag = False\n\n    def weight_generation(self, basis, coeff_in, coeff_out):\n        ### Level 1\n        if coeff_in is not None:\n            # weight_1 [base_out, inc, k^2]\n            # coeff_in x basis = [bo, inc, bi] x [bo, bi, k^2]\n            basis = basis.view(basis.size(0), basis.size(1), -1)\n            weight_1 = torch.matmul(coeff_in, basis)\n        else:\n            weight_1 = basis\n\n        ### Level 2\n        if coeff_out is not None:\n            # weight_2 [outc, inc*k*k]\n            weight_1 = weight_1.view(weight_1.size(0), -1)\n            weight_2 = torch.matmul(coeff_out, weight_1)\n            weight_2 = weight_2.view(self.out_channels, self.in_channels, self.kernel_size, self.kernel_size)\n        else:\n            ## do not use self.out_channel, since for dwconv, we should set out_channel to 1 here.\n            weight_2 = weight_1.view(\n                self.weight.size(0), self.in_channels, self.kernel_size, self.kernel_size\n            )\n        return weight_2\n\n    def get_output_dim(self, img_height, img_width):\n        h_out = (img_height - self.kernel_size + 2 * self.padding) / self.stride + 1\n        w_out = (img_width - self.kernel_size + 2 * self.padding) / self.stride + 1\n        return (int(h_out), int(w_out))\n\n    def get_num_params(self, fullrank=False):\n        if (self.dynamic_weight_flag == True) and (fullrank == False):\n            total = self.basis.numel()\n            if self.coeff_in is not None:\n                total += self.coeff_in.numel()\n            if self.coeff_out is not None:\n                total += self.coeff_out.numel()\n        else:\n            total = self.weight.numel()\n        if self.bias is not None:\n            total += self.bias.numel()\n\n        return total\n\n    def get_param_size(self, fullrank=False):\n        total = 0\n        if (self.dynamic_weight_flag == True) and (fullrank == False):\n            total += self.basis.numel() * self.qb / 8\n            if self.coeff_in is not None:\n                total += self.coeff_in.numel() * self.qu / 8\n            if self.coeff_out is not None:\n                total += self.coeff_out.numel() * self.qv / 8\n        else:\n            total += self.weight.numel() * 4\n        if self.bias is not None:\n            total += self.bias.numel() * 4\n        return total\n\n    def get_ortho_loss(self):\n        ### we want row vectors in the basis to be orthonormal\n        if self.dynamic_weight_flag:  ### at least one-level generation\n            ## basis ortho loss always exists !\n            if self.coeff_in is not None and self.coeff_in.size(2) > 1:\n                if self.basis.size(1) > 1:\n                    ### only penalize when there are at least two row/column vectors\n                    basis = self.basis.view(self.basis.size(0), self.basis.size(1), -1)  # [bo, bi, k^2]\n                    dot_b = torch.matmul(\n                        basis, basis.permute([0, 2, 1])\n                    )  # [bo, bi, k^2] x [bo, k^2, bi] = [bo, bi, bi]\n                else:\n                    dot_b = None\n                ## U\n                coeff_in = self.coeff_in / (\n                    self.coeff_in.data.norm(p=2, dim=1, keepdim=True) + 1e-8\n                )  # normalization\n                dot_u = torch.matmul(\n                    coeff_in.permute(0, 2, 1), coeff_in\n                )  # [bo, bi, ci-bi] x [bo, ci-bi, bi] = [bo, bi, bi]\n            else:\n                dot_u = None\n\n            if self.coeff_out is not None:\n                if self.coeff_in is None:\n                    ### if there is no intra-kernel generation, only cross-kernel generation, e.g., conv1x1, we have to treat basis as a matrix [bo, cin*k*k] and encourage it to have bo orthogonal rows\n                    basis = self.basis.view(self.basis.size(0), -1)  # [bo, ci*k^2]\n                    dot_b = torch.matmul(\n                        basis, basis.permute([1, 0])\n                    )  # [bo, ci*k^2] x [ci*k^2, bo] = [bo, bo]\n                # V\n                coeff_out = self.coeff_out / (\n                    self.coeff_out.data.norm(p=2, dim=0, keepdim=True) + 1e-8\n                )  # normalization\n                dot_v = torch.matmul(coeff_out.t(), coeff_out)  # [bo, co-bo] x [co-bo, bo] = [bo, bo]\n            else:\n                dot_v = None\n            if self.basis is not None and self.eye_b is None:\n                self.eye_b = torch.eye(dot_b.size(-1), dtype=dot_b.dtype, device=dot_b.device)\n                if dot_b.ndim > 2:\n                    self.eye_b = self.eye_b.unsqueeze(0).repeat(basis.size(0), 1, 1)\n            if self.coeff_out is not None and self.eye_v is None:\n                self.eye_v = torch.eye(dot_v.size(-1), dtype=dot_v.dtype, device=dot_v.device)\n            loss = 0\n            if dot_b is not None:\n                loss = loss + F.mse_loss(dot_b, self.eye_b)\n            if dot_u is not None:\n                loss = loss + F.mse_loss(dot_u, self.eye_b)\n            if dot_v is not None:\n                loss = loss + F.mse_loss(dot_v, self.eye_v)\n        else:\n            loss = 0\n\n        return loss\n\n    def assign_separate_weight_bit(self, qb, qu, qv, quant_ratio_b=1, quant_ratio_u=1, quant_ratio_v=1):\n        qb, qu, qv = min(qb, 32), min(qu, 32), min(qv, 32)\n        self.qb, self.qu, self.qv = qb, qu, qv\n        self.basis_quantizer = weight_quantize_fn(qb, alg=\"dorefa_sym\")\n        self.coeff_in_quantizer = weight_quantize_fn(qu, alg=\"dorefa_sym\")\n        self.coeff_out_quantizer = weight_quantize_fn(qv, alg=\"dorefa_sym\")\n        self.basis_quantizer.set_quant_ratio(quant_ratio_b)\n        self.coeff_in_quantizer.set_quant_ratio(quant_ratio_u)\n        self.coeff_out_quantizer.set_quant_ratio(quant_ratio_v)\n\n    def set_quant_ratio(self, quant_ratio_b=1, quant_ratio_u=1, quant_ratio_v=1, quant_ratio_in=1):\n        if hasattr(self, \"basis_quantizer\"):\n            self.basis_quantizer.set_quant_ratio(quant_ratio_b)\n        if hasattr(self, \"coeff_in_quantizer\"):\n            self.coeff_in_quantizer.set_quant_ratio(quant_ratio_u)\n        if hasattr(self, \"coeff_out_quantizer\"):\n            self.coeff_out_quantizer.set_quant_ratio(quant_ratio_v)\n        self.input_quantizer.set_quant_ratio(quant_ratio_in)\n\n    def forward(self, x):\n        if self.in_bit < 16:\n            x = self.input_quantizer(x)\n        if not self.fast_forward_flag or self.weight is None:\n            weight = self.build_weight()\n        else:\n            weight = self.weight\n        #### record weight_2\n        self.weight_2 = weight\n\n        out = F.conv2d(x, weight, bias=self.bias, stride=self.stride, padding=self.padding)\n\n        return out\n\n    def extra_repr(self):\n        s = (\n            \"{in_channels}, {out_channels}, kernel_size={kernel_size}\"\n            \", stride={stride}, padding={padding}, wb={w_bit}, ib={in_bit}\"\n        )\n        if self.bias is None:\n            s += \", bias=False\"\n        if self.dynamic_weight_flag:\n            s += \"base_in={base_in}, base_out={base_out}\"\n        return s.format(**self.__dict__)\n", "meta": {"hexsha": "9593c3faec6175e749a0123a6d27cdcc2762b874", "size": 13717, "ext": "py", "lang": "Python", "max_stars_repo_path": "core/models/layers/mlg_conv2d.py", "max_stars_repo_name": "JeremieMelo/Memory-Efficient-Multi-Level-Generation", "max_stars_repo_head_hexsha": "a490ec32dda08f169d8db946bc8fa70c5fbb7714", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-12-27T22:52:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T06:47:54.000Z", "max_issues_repo_path": "core/models/layers/mlg_conv2d.py", "max_issues_repo_name": "JeremieMelo/Memory-Efficient-Multi-Level-Generation", "max_issues_repo_head_hexsha": "a490ec32dda08f169d8db946bc8fa70c5fbb7714", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core/models/layers/mlg_conv2d.py", "max_forks_repo_name": "JeremieMelo/Memory-Efficient-Multi-Level-Generation", "max_forks_repo_head_hexsha": "a490ec32dda08f169d8db946bc8fa70c5fbb7714", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-01T03:16:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-01T03:16:37.000Z", "avg_line_length": 41.3162650602, "max_line_length": 201, "alphanum_fraction": 0.5785521616, "include": true, "reason": "import numpy", "num_tokens": 3330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.18724444014067249}}
{"text": "# -*- coding: utf-8 -*-\n# Author: XuMing <xuming624@qq.com>\n# Brief: 字符到字符的基本seq2seq模型\n# input:hello; output:ehllo\n\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.layers.core import Dense\n\n# params\nepochs = 60\nbatch_size = 128\nrnn_size = 50\nnum_layers = 2\nencoding_embedding_size = 15\ndecoding_embedding_size = 15\nlearning_rate = 0.001\ncheckpoint = 'model.ckpt'\ndisplay_step = 50\nsource_data_path = '../data/letters_source.txt'\ntarget_data_path = '../data/letters_target.txt'\n\n\ndef get_corpus(data_path):\n    with open(data_path, 'r', encoding='utf-8') as f:\n        text = f.read().lower()\n    return text\n\n\ndef extract_char_vocab(data):\n    \"\"\"\n    mapping dict\n    :param data:\n    :return:\n    \"\"\"\n    special_words = ['<PAD>', '<UNK>', '<BEGIN>', '<END>']\n    set_chars = list(set([char for line in data.split() for char in line]))\n    # add four special words to mapping dict\n    indices_char = {i: c for i, c in enumerate(special_words + set_chars)}\n    char_indices = {c: i for i, c in indices_char.items()}\n    return indices_char, char_indices\n\n\ndef get_input():\n    \"\"\"\n    input tensor\n    :return:\n    \"\"\"\n    inputs = tf.placeholder(tf.int32, [None, None], name='inputs')\n    targets = tf.placeholder(tf.int32, [None, None], name='targets')\n    learning_rate = tf.placeholder(tf.float32, name='learning_rate')\n\n    # get target sequence maxlen\n    target_sequence_len = tf.placeholder(tf.int32, (None,), name='target_sequence_len')\n    target_sequence_maxlen = tf.reduce_max(target_sequence_len, name='target_sequence_maxlen')\n    source_sequence_len = tf.placeholder(tf.int32, (None,), name='source_sequence_len')\n\n    return inputs, targets, learning_rate, target_sequence_len, target_sequence_maxlen, source_sequence_len\n\n\ndef get_encoder_layer(input_data, rnn_size, num_layers,\n                      source_sequence_len, source_vocab_size,\n                      encoding_embedding_size):\n    \"\"\"\n    encoder layer\n    :param intput_data:\n    :param rnn_size:\n    :param num_layers:\n    :param source_sequence_len:\n    :param source_vocab_size:\n    :param encodeing_embedding_size:\n    :return:\n    \"\"\"\n    # encoder embedding\n    encoder_embed_input = tf.contrib.layers.embed_sequence(input_data,\n                                                           source_vocab_size,\n                                                           encoding_embedding_size)\n\n    # RNN cell\n    def get_lstm_cell(rnn_size):\n        lstm_cell = tf.contrib.rnn.LSTMCell(rnn_size,\n                                            initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=2))\n        return lstm_cell\n\n    cell = tf.contrib.rnn.MultiRNNCell([get_lstm_cell(rnn_size) for i in range(num_layers)])\n    encoder_output, encoder_state = tf.nn.dynamic_rnn(cell,\n                                                      encoder_embed_input,\n                                                      sequence_length=source_sequence_len,\n                                                      dtype=tf.float32)\n    return encoder_output, encoder_state\n\n\ndef process_deocder_input(data, vocab_indices, batch_size):\n    \"\"\"\n    target sequence process: add <BEGIN>, and del last <END>\n    :param data:\n    :param vocab_indices:\n    :param batch_size:\n    :return:\n    \"\"\"\n    # cut last char\n    ending = tf.strided_slice(data, [0, 0], [batch_size, -1], [1, 1])\n    decoder_input = tf.concat([tf.fill([batch_size, 1], vocab_indices['<BEGIN>']), ending], 1)\n    return decoder_input\n\n\ndef decoding_layer(target_char_indices, decoding_embedding_size, num_layers, rnn_size,\n                   target_sequence_len, target_sequence_maxlen, encoder_state, decoder_input,\n                   batch_size=128):\n    \"\"\"\n    decode layer\n    :param target_char_indices:\n    :param decoding_embedding_size:\n    :param num_layers:\n    :param rnn_size:\n    :param target_sequence_len:\n    :param target_sequence_maxlen:\n    :param encoder_state:\n    :param decoder_input:\n    :return:\n    \"\"\"\n    # embedding\n    target_vocab_size = len(target_char_indices)\n    decoder_embeddings = tf.Variable(tf.random_uniform([target_vocab_size, decoding_embedding_size]))\n    decoder_embed_input = tf.nn.embedding_lookup(decoder_embeddings, decoder_input)\n\n    # build decoder RNN cell\n    def get_decoder_cell(rnn_size):\n        decoder_cell = tf.contrib.rnn.LSTMCell(rnn_size, initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=2))\n        return decoder_cell\n\n    cell = tf.contrib.rnn.MultiRNNCell([get_decoder_cell(rnn_size) for i in range(num_layers)])\n\n    # output fc layer\n    output_layer = Dense(target_vocab_size, kernel_initializer=tf.truncated_normal_initializer(mean=0.0, stddev=0.1))\n\n    # training decoder\n    with tf.variable_scope('decode'):\n        training_helper = tf.contrib.seq2seq.TrainingHelper(inputs=decoder_embed_input,\n                                                            sequence_length=target_sequence_len,\n                                                            time_major=False)\n        training_decoder = tf.contrib.seq2seq.BasicDecoder(cell,\n                                                           training_helper,\n                                                           encoder_state,\n                                                           output_layer)\n        training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(training_decoder,\n                                                                          impute_finished=True,\n                                                                          maximum_iterations=target_sequence_maxlen)\n    # predict decoder, share params with training decoder\n    with tf.variable_scope('decode', reuse=True):\n        start_tokens = tf.tile(tf.constant([target_char_indices['<BEGIN>']], dtype=tf.int32), [batch_size],\n                               name='start_tokens')\n        predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(decoder_embeddings, start_tokens,\n                                                                     target_char_indices['<END>'])\n        predicting_decoder = tf.contrib.seq2seq.BasicDecoder(cell,\n                                                             predicting_helper,\n                                                             encoder_state,\n                                                             output_layer)\n        predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(predicting_decoder,\n                                                                            impute_finished=True,\n                                                                            maximum_iterations=target_sequence_maxlen)\n    return training_decoder_output, predicting_decoder_output\n\n\ndef seq2seq(input_data, targets, lr, target_sequence_len,\n            target_sequence_maxlen, source_sequence_len,\n            source_vocab_size, target_vocab_size,\n            encoder_embedding_size, decoder_embedding_size,\n            rnn_size, num_layers, target_char_indices, batch_size=128):\n    \"\"\"\n    seq2seq model\n    :param input_data:\n    :param targets:\n    :param lr:\n    :param target_sequence_len:\n    :param target_sequence_maxlen:\n    :param source_sequence_len:\n    :param source_vocab_size:\n    :param target_vocab_size:\n    :param encoder_embedding_size:\n    :param decoder_embedding_size:\n    :param rnn_size:\n    :param num_layers:\n    :return:\n    \"\"\"\n    print('build model...')\n    # get state output of encoder\n    _, encoder_state = get_encoder_layer(input_data,\n                                         rnn_size, num_layers,\n                                         source_sequence_len, source_vocab_size,\n                                         encoder_embedding_size)\n    # input of decoder\n    decoder_input = process_deocder_input(targets, target_char_indices, batch_size=batch_size)\n    # decoder\n    training_decoder_output, predicting_decoder_output = decoding_layer(target_char_indices,\n                                                                        decoder_embedding_size,\n                                                                        num_layers,\n                                                                        rnn_size,\n                                                                        target_sequence_len,\n                                                                        target_sequence_maxlen,\n                                                                        encoder_state,\n                                                                        decoder_input)\n    return training_decoder_output, predicting_decoder_output\n\n\ndef pad_sentence_batch(sentence_batch, pad_int):\n    \"\"\"\n    pad the batch sequence, make sure every batch has same sequence_length\n    :param sentence_batch:\n    :param pad_int:\n    :return:\n    \"\"\"\n    max_sentence = max([len(sentence) for sentence in sentence_batch])\n    return [sentence + [pad_int] * (max_sentence - len(sentence)) for sentence in sentence_batch]\n\n\ndef get_batches(targets, sources, batch_size, source_pad_int, target_pad_int):\n    \"\"\"\n    get batch by generator\n    :param targets:\n    :param sources:\n    :param batch_size:\n    :param source_pad_int:\n    :param target_pad_int:\n    :return:\n    \"\"\"\n    for batch_i in range(0, len(sources) // batch_size):\n        start_i = batch_i * batch_size\n        sources_batch = sources[start_i:start_i + batch_size]\n        targets_batch = targets[start_i:start_i + batch_size]\n        # pad sequence\n        pad_sources_batch = np.array(pad_sentence_batch(sources_batch, source_pad_int))\n        pad_targets_batch = np.array(pad_sentence_batch(targets_batch, target_pad_int))\n\n        # get sentence length\n        targets_lengths = []\n        for target in targets_batch:\n            targets_lengths.append(len(target))\n\n        sources_lengths = []\n        for source in sources_batch:\n            sources_lengths.append(len(source))\n\n        yield pad_targets_batch, pad_sources_batch, targets_lengths, sources_lengths\n\n\ndef train():\n    source_data = get_corpus(source_data_path)\n    target_data = get_corpus(target_data_path)\n    print('corpus length:', len(source_data))\n\n    # see sample data\n    print(source_data.split('\\n')[:10])\n    print(target_data.split('\\n')[:10])\n\n    # get mapping dict\n    source_indices_char, source_char_indices = extract_char_vocab(source_data)\n    target_indices_char, target_char_indices = extract_char_vocab(target_data)\n\n    # chars index\n    source_indices = [[source_char_indices.get(c, source_char_indices['<UNK>']) for c in line]\n                      for line in source_data.split('\\n')]\n    target_indices = [\n        [target_char_indices.get(c, target_char_indices['<UNK>']) for c in line] + [target_char_indices['<END>']]\n        for line in target_data.split('\\n')]\n\n    # see sample source indices data\n    print(source_indices[:10])\n    print(target_indices[:10])\n\n    # split data to train and validation\n    train_source, valid_source = source_indices[batch_size:], source_indices[:batch_size]\n    train_target, valid_target = target_indices[batch_size:], target_indices[:batch_size]\n\n    (valid_targets_batch, valid_sources_batch,\n     valid_targets_lengths, valid_sources_lengths) = next(get_batches(valid_target,\n                                                                      valid_source,\n                                                                      batch_size,\n                                                                      source_char_indices['<PAD>'],\n                                                                      target_char_indices['<PAD>']))\n    train_graph = tf.Graph()\n    with train_graph.as_default():\n        # get inputs\n        input_data, targets, learning_rate, target_sequence_len, target_sequence_maxlen, source_sequence_len = get_input()\n        training_decoder_output, predicting_decoder_output = seq2seq(input_data, targets,\n                                                                     learning_rate, target_sequence_len,\n                                                                     target_sequence_maxlen, source_sequence_len,\n                                                                     len(source_char_indices), len(target_char_indices),\n                                                                     encoding_embedding_size, decoding_embedding_size,\n                                                                     rnn_size, num_layers,\n                                                                     target_char_indices, batch_size)\n        training_logits = tf.identity(training_decoder_output.rnn_output, 'logits')\n        predicting_logits = tf.identity(predicting_decoder_output.sample_id, name='predictions')\n\n        masks = tf.sequence_mask(target_sequence_len, target_sequence_maxlen, dtype=tf.float32, name='masks')\n        with tf.name_scope('optimization'):\n            # loss\n            cost = tf.contrib.seq2seq.sequence_loss(training_logits, targets, masks)\n            # optimizer\n            optimizer = tf.train.AdamOptimizer(learning_rate)\n            # gradient clipping\n            gradients = optimizer.compute_gradients(cost)\n            capped_gradients = [(tf.clip_by_value(grad, -5., 5.), var) for grad, var in gradients if grad is not None]\n            train_op = optimizer.apply_gradients(capped_gradients)\n\n    with tf.Session(graph=train_graph) as sess:\n        sess.run(tf.global_variables_initializer())\n        for epoch_i in range(1, epochs + 1):\n            batches = get_batches(train_target, train_source, batch_size,\n                                  source_char_indices['<PAD>'], target_char_indices['<PAD>'])\n            for batch_i, (targets_batch, sources_batch, targets_length, sources_lengths) in enumerate(batches):\n                _, loss = sess.run([train_op, cost],\n                                   {input_data: sources_batch,\n                                    targets: targets_batch,\n                                    learning_rate: learning_rate,\n                                    target_sequence_len: targets_length,\n                                    source_sequence_len: sources_lengths})\n                if batch_i % display_step == 0:\n                    validation_loss = sess.run([cost],\n                                               {input_data: valid_sources_batch,\n                                                targets: valid_targets_batch,\n                                                learning_rate: learning_rate,\n                                                target_sequence_len: valid_targets_lengths,\n                                                source_sequence_len: valid_sources_lengths})\n                    print('Epoch {:>3}/{} Batch {:>4}/{} - Training Loss: {:>6.3f} - Validation Loss: {:>6.3f}'.format(\n                        epoch_i,\n                        epochs,\n                        batch_i,\n                        len(train_source) // batch_size,\n                        loss,\n                        validation_loss[0]\n                    ))\n        # save model\n        saver = tf.train.Saver()\n        saver.save(sess, checkpoint)\n        print('Model trained and saved %s' % checkpoint)\n\n\ndef source_2_seq(text, source_char_indices):\n    \"\"\"\n    change source data to sequence\n    :param text:\n    :param source_char_indices:\n    :return:\n    \"\"\"\n    sequence_len = 7\n    return [source_char_indices.get(char, source_char_indices['<UNK>']) for char in text] + \\\n           [source_char_indices['<PAD>']] * (sequence_len - len(text))\n\n\ndef infer():\n    source_data = get_corpus(source_data_path)\n    target_data = get_corpus(target_data_path)\n\n    # get mapping dict\n    source_indices_char, source_char_indices = extract_char_vocab(source_data)\n    target_indices_char, target_char_indices = extract_char_vocab(target_data)\n\n    input_word = 'hello'\n    text = source_2_seq(input_word, source_char_indices)\n    loaded_graph = tf.Graph()\n    with tf.Session(graph=loaded_graph) as sess:\n        loader = tf.train.import_meta_graph(checkpoint + '.meta')\n        loader.restore(sess, checkpoint)\n\n        input_data = loaded_graph.get_tensor_by_name('inputs:0')\n        logits = loaded_graph.get_tensor_by_name('predictions:0')\n        source_sequence_len = loaded_graph.get_tensor_by_name('source_sequence_len:0')\n        target_sequence_len = loaded_graph.get_tensor_by_name('target_sequence_len:0')\n        answer_logits = sess.run(logits, {input_data: [text] * batch_size,\n                                          target_sequence_len: [len(input_word)] * batch_size,\n                                          source_sequence_len: [len(input_word)] * batch_size})[0]\n    pad = source_char_indices['<PAD>']\n    print('raw input:', input_word)\n    print('\\nSource')\n    print(' Word 编号:    {}'.format([i for i in text]))\n    print(' Input Words:    {}'.format(' '.join([source_indices_char[i] for i in text])))\n\n    print('\\nTarget')\n    print(' Word 编号:    {}'.format([i for i in answer_logits if i != pad]))\n    print(' Response Words: {}'.format(' '.join([target_indices_char[i] for i in answer_logits if i != pad])))\n\n\nif __name__ == '__main__':\n    # train()\n    infer()\n", "meta": {"hexsha": "dba6afdd8a6d1901770039294b5e70af51ccb621", "size": 17270, "ext": "py", "lang": "Python", "max_stars_repo_path": "17tensorflow/2_network/basic_seq2seq.py", "max_stars_repo_name": "KEVINYZY/python-tutorial", "max_stars_repo_head_hexsha": "ae43536908eb8af56c34865f52a6e8644edc4fa3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-04T10:44:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T07:53:41.000Z", "max_issues_repo_path": "17tensorflow/2_network/basic_seq2seq.py", "max_issues_repo_name": "zm79287/python-tutorial", "max_issues_repo_head_hexsha": "d0f7348e1da4ff954e3add66e1aae55d599283ee", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "17tensorflow/2_network/basic_seq2seq.py", "max_forks_repo_name": "zm79287/python-tutorial", "max_forks_repo_head_hexsha": "d0f7348e1da4ff954e3add66e1aae55d599283ee", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-02-28T07:53:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-28T07:11:20.000Z", "avg_line_length": 44.5103092784, "max_line_length": 122, "alphanum_fraction": 0.581239143, "include": true, "reason": "import numpy", "num_tokens": 3247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.32423539245106076, "lm_q1q2_score": 0.1872444363696903}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#\n\n'''\nRestricted CCSD implementation for real integrals.  Permutation symmetry for\nthe 4-index integrals (ij|kl) = (ij|lk) = (ji|kl) are assumed.\n\nNote MO integrals are treated in chemist's notation\n'''\n\nimport time\nfrom functools import reduce\nimport numpy\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf.cc import ccsd\nfrom pyscf.cc import _ccsd\n\n# t2,l2 as ijab\ndef kernel(mycc, eris=None, t1=None, t2=None, l1=None, l2=None,\n           max_cycle=50, tol=1e-8, verbose=logger.INFO,\n           fintermediates=None, fupdate=None):\n    if eris is None: eris = mycc.ao2mo()\n    cput0 = (time.clock(), time.time())\n    log = logger.new_logger(mycc, verbose)\n\n    if t1 is None: t1 = mycc.t1\n    if t2 is None: t2 = mycc.t2\n    if l1 is None: l1 = t1\n    if l2 is None: l2 = t2\n    if fintermediates is None:\n        fintermediates = make_intermediates\n    if fupdate is None:\n        fupdate = update_lambda\n\n    imds = fintermediates(mycc, t1, t2, eris)\n\n    if isinstance(mycc.diis, lib.diis.DIIS):\n        adiis = mycc.diis\n    elif mycc.diis:\n        adiis = lib.diis.DIIS(mycc, mycc.diis_file, incore=mycc.incore_complete)\n        adiis.space = mycc.diis_space\n    else:\n        adiis = None\n    cput0 = log.timer('CCSD lambda initialization', *cput0)\n\n    conv = False\n    for istep in range(max_cycle):\n        l1new, l2new = fupdate(mycc, t1, t2, l1, l2, eris, imds)\n        normt = numpy.linalg.norm(mycc.amplitudes_to_vector(l1new, l2new) -\n                                  mycc.amplitudes_to_vector(l1, l2))\n        l1, l2 = l1new, l2new\n        l1new = l2new = None\n        l1, l2 = mycc.run_diis(l1, l2, istep, normt, 0, adiis)\n        log.info('cycle = %d  norm(lambda1,lambda2) = %.6g', istep+1, normt)\n        cput0 = log.timer('CCSD iter', *cput0)\n        if normt < tol:\n            conv = True\n            break\n    return conv, l1, l2\n\n\n# l2, t2 as ijab\ndef make_intermediates(mycc, t1, t2, eris):\n    log = logger.Logger(mycc.stdout, mycc.verbose)\n    nocc, nvir = t1.shape\n    nov = nocc * nvir\n    nvir_pair = nvir*(nvir+1)//2\n    foo = eris.fock[:nocc,:nocc]\n    fov = eris.fock[:nocc,nocc:]\n    fvo = eris.fock[nocc:,:nocc]\n    fvv = eris.fock[nocc:,nocc:]\n\n    class _IMDS: pass\n    imds = _IMDS()\n    #TODO: mycc.incore_complete\n    imds.ftmp = lib.H5TmpFile()\n    imds.woooo = imds.ftmp.create_dataset('woooo', (nocc,nocc,nocc,nocc), 'f8')\n    imds.wvooo = imds.ftmp.create_dataset('wvooo', (nvir,nocc,nocc,nocc), 'f8')\n    imds.wVOov = imds.ftmp.create_dataset('wVOov', (nvir,nocc,nocc,nvir), 'f8')\n    imds.wvOOv = imds.ftmp.create_dataset('wvOOv', (nvir,nocc,nocc,nvir), 'f8')\n    imds.wvvov = imds.ftmp.create_dataset('wvvov', (nvir,nvir,nocc,nvir), 'f8')\n\n    w1 = fvv - numpy.einsum('ja,jb->ba', fov, t1)\n    w2 = foo + numpy.einsum('ib,jb->ij', fov, t1)\n    w3 = numpy.einsum('kc,jkbc->bj', fov, t2) * 2 + fov.T\n    w3 -= numpy.einsum('kc,kjbc->bj', fov, t2)\n    w3 += lib.einsum('kc,kb,jc->bj', fov, t1, t1)\n    w4 = fov.copy()\n\n    time1 = time.clock(), time.time()\n    unit = nocc*nvir**2*6\n    max_memory = max(0, mycc.max_memory - lib.current_memory()[0])\n    blksize = min(nvir, max(ccsd.BLKMIN, int((max_memory*.95e6/8-nocc**4-nvir*nocc**3)/unit)))\n    log.debug1('ccsd lambda make_intermediates: block size = %d, nvir = %d in %d blocks',\n               blksize, nvir, int((nvir+blksize-1)//blksize))\n\n    fswap = lib.H5TmpFile()\n    for istep, (p0, p1) in enumerate(lib.prange(0, nvir, blksize)):\n        eris_ovvv = eris.get_ovvv(slice(None), slice(p0,p1))\n        fswap['vvov/%d'%istep] = eris_ovvv.transpose(2,3,0,1)\n\n    woooo = 0\n    wvooo = numpy.zeros((nvir,nocc,nocc,nocc))\n    for p0, p1 in lib.prange(0, nvir, blksize):\n        eris_ovvv = eris.get_ovvv(slice(None), slice(p0,p1))\n        eris_vvov = numpy.empty(((p1-p0),nvir,nocc,nvir))\n        for istep, (q0, q1) in enumerate(lib.prange(0, nvir, blksize)):\n            eris_vvov[:,:,:,q0:q1] = fswap['vvov/%d'%istep][p0:p1]\n\n        w1 += numpy.einsum('jcba,jc->ba', eris_ovvv, t1[:,p0:p1]*2)\n        w1[:,p0:p1] -= numpy.einsum('jabc,jc->ba', eris_ovvv, t1)\n        theta = t2[:,:,:,p0:p1] * 2 - t2[:,:,:,p0:p1].transpose(1,0,2,3)\n        w3 += lib.einsum('jkcd,kdcb->bj', theta, eris_ovvv)\n        theta = None\n        wVOov = lib.einsum('jbcd,kd->bjkc', eris_ovvv, t1)\n        wvOOv = lib.einsum('cbjd,kd->cjkb', eris_vvov,-t1)\n        g2vovv = eris_vvov.transpose(0,2,1,3) * 2 - eris_vvov.transpose(0,2,3,1)\n        for i0, i1 in lib.prange(0, nocc, blksize):\n            tau = t2[:,i0:i1] + numpy.einsum('ia,jb->ijab', t1, t1[i0:i1])\n            wvooo[p0:p1,i0:i1] += lib.einsum('cibd,jkbd->ckij', g2vovv, tau)\n        g2vovv = tau = None\n\n        # Watch out memory usage here, due to the t2 transpose\n        wvvov  = lib.einsum('jabd,jkcd->abkc', eris_ovvv, t2) * -1.5\n        wvvov += eris_vvov.transpose(0,3,2,1) * 2\n        wvvov -= eris_vvov\n\n        g2vvov = eris_vvov * 2 - eris_ovvv.transpose(1,2,0,3)\n        for i0, i1 in lib.prange(0, nocc, blksize):\n            theta = t2[i0:i1] * 2 - t2[i0:i1].transpose(0,1,3,2)\n            vackb = lib.einsum('acjd,kjbd->ackb', g2vvov, theta)\n            wvvov[:,:,i0:i1] += vackb.transpose(0,3,2,1)\n            wvvov[:,:,i0:i1] -= vackb * .5\n        g2vvov = eris_ovvv = eris_vvov = theta = None\n\n        eris_ovoo = _cp(eris.ovoo[:,p0:p1])\n        w2 += numpy.einsum('kbij,kb->ij', eris_ovoo, t1[:,p0:p1]) * 2\n        w2 -= numpy.einsum('ibkj,kb->ij', eris_ovoo, t1[:,p0:p1])\n        theta = t2[:,:,p0:p1].transpose(1,0,2,3) * 2 - t2[:,:,p0:p1]\n        w3 -= lib.einsum('lckj,klcb->bj', eris_ovoo, theta)\n\n        tmp = lib.einsum('lc,jcik->ijkl', t1[:,p0:p1], eris_ovoo)\n        woooo += tmp\n        woooo += tmp.transpose(1,0,3,2)\n        theta = tmp = None\n\n        wvOOv += lib.einsum('lbjk,lc->bjkc', eris_ovoo, t1)\n        wVOov -= lib.einsum('jbkl,lc->bjkc', eris_ovoo, t1)\n        wvooo[p0:p1] += eris_ovoo.transpose(1,3,2,0) * 2\n        wvooo[p0:p1] -= eris_ovoo.transpose(1,0,2,3)\n        wvooo -= lib.einsum('klbc,iblj->ckij', t2[:,:,p0:p1], eris_ovoo*1.5)\n\n        g2ovoo = eris_ovoo * 2 - eris_ovoo.transpose(2,1,0,3)\n        theta = t2[:,:,:,p0:p1]*2 - t2[:,:,:,p0:p1].transpose(1,0,2,3)\n        vcjik = lib.einsum('jlcb,lbki->cjki', theta, g2ovoo)\n        wvooo += vcjik.transpose(0,3,2,1)\n        wvooo -= vcjik*.5\n        theta = g2ovoo = None\n\n        eris_voov = _cp(eris.ovvo[:,p0:p1]).transpose(1,0,3,2)\n        tau = t2[:,:,p0:p1] + numpy.einsum('ia,jb->ijab', t1[:,p0:p1], t1)\n        woooo += lib.einsum('cijd,klcd->ijkl', eris_voov, tau)\n        tau = None\n\n        g2voov = eris_voov*2 - eris_voov.transpose(0,2,1,3)\n        tmpw4 = numpy.einsum('ckld,ld->kc', g2voov, t1)\n        w1 -= lib.einsum('ckja,kjcb->ba', g2voov, t2[:,:,p0:p1])\n        w1[:,p0:p1] -= numpy.einsum('ja,jb->ba', tmpw4, t1)\n        w2 += lib.einsum('jkbc,bikc->ij', t2[:,:,p0:p1], g2voov)\n        w2 += numpy.einsum('ib,jb->ij', tmpw4, t1[:,p0:p1])\n        w3 += reduce(numpy.dot, (t1.T, tmpw4, t1[:,p0:p1].T))\n        w4[:,p0:p1] += tmpw4\n\n        wvOOv += lib.einsum('bljd,kd,lc->bjkc', eris_voov, t1, t1)\n        wVOov -= lib.einsum('bjld,kd,lc->bjkc', eris_voov, t1, t1)\n\n        VOov  = lib.einsum('bjld,klcd->bjkc', g2voov, t2)\n        VOov -= lib.einsum('bjld,kldc->bjkc', eris_voov, t2)\n        VOov += eris_voov\n        vOOv = lib.einsum('bljd,kldc->bjkc', eris_voov, t2)\n        vOOv -= _cp(eris.oovv[:,:,p0:p1]).transpose(2,1,0,3)\n        wVOov += VOov\n        wvOOv += vOOv\n        imds.wVOov[p0:p1] = wVOov\n        imds.wvOOv[p0:p1] = wvOOv\n        wOVov = wOvOv = None\n\n        ov1 = vOOv*2 + VOov\n        ov2 = VOov*2 + vOOv\n        vOOv = VOov = None\n        wvooo -= lib.einsum('jb,bikc->ckij', t1[:,p0:p1], ov1)\n        wvooo += lib.einsum('kb,bijc->ckij', t1[:,p0:p1], ov2)\n        w3 += numpy.einsum('ckjb,kc->bj', ov2, t1[:,p0:p1])\n\n        wvvov += lib.einsum('ajkc,jb->abkc', ov1, t1)\n        wvvov -= lib.einsum('ajkb,jc->abkc', ov2, t1)\n\n        eris_ovoo = _cp(eris.ovoo[:,p0:p1])\n        g2ovoo = eris_ovoo * 2 - eris_ovoo.transpose(2,1,0,3)\n        tau = t2 + numpy.einsum('ia,jb->ijab', t1, t1)\n        wvvov += lib.einsum('laki,klbc->abic', g2ovoo, tau)\n        imds.wvvov[p0:p1] = wvvov\n        wvvov = ov1 = ov2 = g2ovoo = None\n\n    woooo += _cp(eris.oooo).transpose(0,2,1,3)\n    imds.woooo[:] = woooo\n    imds.wvooo[:] = wvooo\n    woooo = wvooo = None\n\n    w3 += numpy.einsum('bc,jc->bj', w1, t1)\n    w3 -= numpy.einsum('kj,kb->bj', w2, t1)\n\n    fswap = None\n\n    imds.w1 = w1\n    imds.w2 = w2\n    imds.w3 = w3\n    imds.w4 = w4\n    imds.ftmp.flush()\n    return imds\n\n\n# update L1, L2\ndef update_lambda(mycc, t1, t2, l1, l2, eris=None, imds=None):\n    if imds is None: imds = make_intermediates(mycc, t1, t2, eris)\n    time1 = time0 = time.clock(), time.time()\n    log = logger.Logger(mycc.stdout, mycc.verbose)\n    nocc, nvir = t1.shape\n    nov = nocc * nvir\n    fov = eris.fock[:nocc,nocc:]\n\n    theta = t2*2 - t2.transpose(0,1,3,2)\n    mba = lib.einsum('klca,klcb->ba', l2, theta)\n    mij = lib.einsum('ikcd,jkcd->ij', l2, theta)\n    theta = None\n    mba1 = numpy.einsum('jc,jb->bc', l1, t1) + mba\n    mij1 = numpy.einsum('kb,jb->kj', l1, t1) + mij\n    mia1 = t1 + numpy.einsum('kc,jkbc->jb', l1, t2) * 2\n    mia1 -= numpy.einsum('kc,jkcb->jb', l1, t2)\n    mia1 -= reduce(numpy.dot, (t1, l1.T, t1))\n    mia1 -= numpy.einsum('bd,jd->jb', mba, t1)\n    mia1 -= numpy.einsum('lj,lb->jb', mij, t1)\n\n    l2new = mycc._add_vvvv(None, l2, eris, with_ovvv=False, t2sym='jiba')\n    l1new  = numpy.einsum('ijab,jb->ia', l2new, t1) * 2\n    l1new -= numpy.einsum('jiab,jb->ia', l2new, t1)\n    l2new *= .5  # *.5 because of l2+l2.transpose(1,0,3,2) in the end\n    tmp = tmp1 = None\n\n    l1new += fov\n    l1new += numpy.einsum('ib,ba->ia', l1, imds.w1)\n    l1new -= numpy.einsum('ja,ij->ia', l1, imds.w2)\n    l1new -= numpy.einsum('ik,ka->ia', mij, imds.w4)\n    l1new -= numpy.einsum('ca,ic->ia', mba, imds.w4)\n    l1new += numpy.einsum('ijab,bj->ia', l2, imds.w3) * 2\n    l1new -= numpy.einsum('ijba,bj->ia', l2, imds.w3)\n\n    l2new += numpy.einsum('ia,jb->ijab', l1, imds.w4)\n    l2new += lib.einsum('jibc,ca->jiba', l2, imds.w1)\n    l2new -= lib.einsum('jk,kiba->jiba', imds.w2, l2)\n\n    eris_ovoo = _cp(eris.ovoo)\n    l1new -= numpy.einsum('iajk,kj->ia', eris_ovoo, mij1) * 2\n    l1new += numpy.einsum('jaik,kj->ia', eris_ovoo, mij1)\n    l2new -= lib.einsum('jbki,ka->jiba', eris_ovoo, l1)\n    eris_ovoo = None\n\n    tau = _ccsd.make_tau(t2, t1, t1)\n    l2tau = lib.einsum('ijcd,klcd->ijkl', l2, tau)\n    tau = None\n    l2t1 = lib.einsum('jidc,kc->ijkd', l2, t1)\n\n    max_memory = max(0, mycc.max_memory - lib.current_memory()[0])\n    unit = nocc*nvir**2*5\n    blksize = min(nocc, max(ccsd.BLKMIN, int(max_memory*.95e6/8/unit)))\n    log.debug1('block size = %d, nocc = %d is divided into %d blocks',\n               blksize, nocc, int((nocc+blksize-1)/blksize))\n\n    l1new -= numpy.einsum('jb,jiab->ia', l1, _cp(eris.oovv))\n    for p0, p1 in lib.prange(0, nvir, blksize):\n        eris_ovvv = eris.get_ovvv(slice(None), slice(p0,p1))\n        l1new[:,p0:p1] += numpy.einsum('iabc,bc->ia', eris_ovvv, mba1) * 2\n        l1new -= numpy.einsum('ibca,bc->ia', eris_ovvv, mba1[p0:p1])\n        l2new[:,:,p0:p1] += lib.einsum('jbac,ic->jiba', eris_ovvv, l1)\n        m4 = lib.einsum('ijkd,kadb->ijab', l2t1, eris_ovvv)\n        l2new[:,:,p0:p1] -= m4\n        l1new[:,p0:p1] -= numpy.einsum('ijab,jb->ia', m4, t1) * 2\n        l1new -= numpy.einsum('ijab,ia->jb', m4, t1[:,p0:p1]) * 2\n        l1new[:,p0:p1] += numpy.einsum('jiab,jb->ia', m4, t1)\n        l1new += numpy.einsum('jiab,ia->jb', m4, t1[:,p0:p1])\n        eris_ovvv = m4buf = m4 = None\n\n        eris_voov = _cp(eris.ovvo[:,p0:p1].transpose(1,0,3,2))\n        l1new[:,p0:p1] += numpy.einsum('jb,aijb->ia', l1, eris_voov) * 2\n        l2new[:,:,p0:p1] += eris_voov.transpose(1,2,0,3) * .5\n        l2new[:,:,p0:p1] -= lib.einsum('bjic,ca->jiba', eris_voov, mba1)\n        l2new[:,:,p0:p1] -= lib.einsum('bjka,ik->jiba', eris_voov, mij1)\n        l1new[:,p0:p1] += numpy.einsum('aijb,jb->ia', eris_voov, mia1) * 2\n        l1new -= numpy.einsum('bija,jb->ia', eris_voov, mia1[:,p0:p1])\n        m4 = lib.einsum('ijkl,aklb->ijab', l2tau, eris_voov)\n        l2new[:,:,p0:p1] += m4 * .5\n        l1new[:,p0:p1] += numpy.einsum('ijab,jb->ia', m4, t1) * 2\n        l1new -= numpy.einsum('ijba,jb->ia', m4, t1[:,p0:p1])\n\n        saved_wvooo = _cp(imds.wvooo[p0:p1])\n        l1new -= lib.einsum('ckij,jkca->ia', saved_wvooo, l2[:,:,p0:p1])\n        saved_wvovv = _cp(imds.wvvov[p0:p1])\n        # Watch out memory usage here, due to the l2 transpose\n        l1new[:,p0:p1] += lib.einsum('abkc,kibc->ia', saved_wvovv, l2)\n        saved_wvooo = saved_wvovv = None\n\n        saved_wvOOv = _cp(imds.wvOOv[p0:p1])\n        tmp_voov = _cp(imds.wVOov[p0:p1]) * 2\n        tmp_voov += saved_wvOOv\n        tmp = l2.transpose(0,2,1,3) - l2.transpose(0,3,1,2)*.5\n        l2new[:,:,p0:p1] += lib.einsum('iakc,bjkc->jiba', tmp, tmp_voov)\n        tmp = tmp1 = tmp_ovov = None\n\n        tmp = lib.einsum('jkca,bikc->jiba', l2, saved_wvOOv)\n        l2new[:,:,p0:p1] += tmp\n        l2new[:,:,p0:p1] += tmp.transpose(1,0,2,3) * .5\n        saved_wvOOv = tmp = None\n\n    saved_woooo = _cp(imds.woooo)\n    m3 = lib.einsum('ijkl,klab->ijab', saved_woooo, l2)\n    l2new += m3 * .5\n    l1new += numpy.einsum('ijab,jb->ia', m3, t1) * 2\n    l1new -= numpy.einsum('ijba,jb->ia', m3, t1)\n    saved_woooo = m3 = None\n    #time1 = log.timer_debug1('lambda pass [%d:%d]'%(p0, p1), *time1)\n\n    mo_e = eris.fock.diagonal()\n    eia = lib.direct_sum('i-a->ia', mo_e[:nocc], mo_e[nocc:])\n    l1new /= eia\n    l1new += l1\n\n#    l2new = l2new + l2new.transpose(1,0,3,2)\n#    l2new /= lib.direct_sum('ia+jb->ijab', eia, eia)\n#    l2new += l2\n    ij = 0\n    for i in range(nocc):\n        if i > 0:\n            l2new[i,:i] += l2new[:i,i].transpose(0,2,1)\n            l2new[i,:i] /= lib.direct_sum('a,jb->jab', eia[i], eia[:i])\n            l2new[:i,i] = l2new[i,:i].transpose(0,2,1)\n        l2new[i,i] = l2new[i,i] + l2new[i,i].T\n        l2new[i,i] /= lib.direct_sum('a,b->ab', eia[i], eia[i])\n    l2new += l2\n\n    time0 = log.timer_debug1('update l1 l2', *time0)\n    return l1new, l2new\n\ndef _cp(a):\n    return numpy.array(a, copy=False, order='C')\n\n\nif __name__ == '__main__':\n    from pyscf import gto\n    from pyscf import scf\n    from pyscf import ao2mo\n    from pyscf.cc import ccsd\n\n    mol = gto.M()\n    mf = scf.RHF(mol)\n\n    mcc = ccsd.CCSD(mf)\n\n    numpy.random.seed(12)\n    nocc = 5\n    nmo = 12\n    nvir = nmo - nocc\n    eri0 = numpy.random.random((nmo,nmo,nmo,nmo))\n    eri0 = ao2mo.restore(1, ao2mo.restore(8, eri0, nmo), nmo)\n    fock0 = numpy.random.random((nmo,nmo))\n    fock0 = fock0 + fock0.T + numpy.diag(range(nmo))*2\n    t1 = numpy.random.random((nocc,nvir))\n    t2 = numpy.random.random((nocc,nocc,nvir,nvir))\n    t2 = t2 + t2.transpose(1,0,3,2)\n    l1 = numpy.random.random((nocc,nvir))\n    l2 = numpy.random.random((nocc,nocc,nvir,nvir))\n    l2 = l2 + l2.transpose(1,0,3,2)\n\n    eris = ccsd._ChemistsERIs()\n    eris.oooo = eri0[:nocc,:nocc,:nocc,:nocc].copy()\n    eris.ovoo = eri0[:nocc,nocc:,:nocc,:nocc].copy()\n    eris.oovv = eri0[:nocc,:nocc,nocc:,nocc:].copy()\n    eris.ovvo = eri0[:nocc,nocc:,nocc:,:nocc].copy()\n    idx = numpy.tril_indices(nvir)\n    eris.ovvv = eri0[:nocc,nocc:,nocc:,nocc:][:,:,idx[0],idx[1]].copy()\n    eris.vvvv = ao2mo.restore(4,eri0[nocc:,nocc:,nocc:,nocc:],nvir)\n    eris.fock = fock0\n\n    imds = make_intermediates(mcc, t1, t2, eris)\n    l1new, l2new = update_lambda(mcc, t1, t2, l1, l2, eris, imds)\n    print(lib.finger(l1new) - -6699.5335665027187)\n    print(lib.finger(l2new) - -514.7001243502192 )\n    print(abs(l2new-l2new.transpose(1,0,3,2)).sum())\n\n    mcc.max_memory = 0\n    imds = make_intermediates(mcc, t1, t2, eris)\n    l1new, l2new = update_lambda(mcc, t1, t2, l1, l2, eris, imds)\n    print(lib.finger(l1new) - -6699.5335665027187)\n    print(lib.finger(l2new) - -514.7001243502192 )\n    print(abs(l2new-l2new.transpose(1,0,3,2)).sum())\n\n    mol = gto.Mole()\n    mol.verbose = 0\n    mol.atom = [\n        [8 , (0. , 0.     , 0.)],\n        [1 , (0. , -0.757 , 0.587)],\n        [1 , (0. , 0.757  , 0.587)]]\n\n    mol.basis = 'cc-pvdz'\n    mol.build()\n    rhf = scf.RHF(mol)\n    rhf.conv_tol = 1e-16\n    rhf.scf()\n\n    mcc = ccsd.CCSD(rhf)\n    mcc.conv_tol = 1e-12\n    ecc, t1, t2 = mcc.kernel()\n\n    nmo = rhf.mo_energy.size\n    fock0 = numpy.diag(rhf.mo_energy)\n    nocc = mol.nelectron // 2\n    nvir = nmo - nocc\n\n    eris = mcc.ao2mo()\n    conv, l1, l2 = kernel(mcc, eris, t1, t2, tol=1e-8)\n    print(numpy.linalg.norm(l1)-0.0132626841292)\n    print(numpy.linalg.norm(l2)-0.212575609057)\n\n    from pyscf.cc import ccsd_rdm\n    dm1 = ccsd_rdm.make_rdm1(mcc, t1, t2, l1, l2)\n    dm2 = ccsd_rdm.make_rdm2(mcc, t1, t2, l1, l2)\n    h1 = reduce(numpy.dot, (rhf.mo_coeff.T, rhf.get_hcore(), rhf.mo_coeff))\n    eri = ao2mo.full(rhf._eri, rhf.mo_coeff)\n    eri = ao2mo.restore(1, eri, nmo).reshape((nmo,)*4)\n    e1 = numpy.einsum('pq,pq', h1, dm1)\n    e2 = numpy.einsum('pqrs,pqrs', eri, dm2) * .5\n    print(e1+e2+mol.energy_nuc() - rhf.e_tot - ecc)\n", "meta": {"hexsha": "7c909ba30bd6dc2efc10d83faa9cffa437cee889", "size": 17771, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/cc/ccsd_lambda.py", "max_stars_repo_name": "fdmalone/pyscf", "max_stars_repo_head_hexsha": "021b17ac721e292b277d2b740e2ff8ab38bb6a4a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-01T12:39:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-01T12:39:45.000Z", "max_issues_repo_path": "pyscf/cc/ccsd_lambda.py", "max_issues_repo_name": "fdmalone/pyscf", "max_issues_repo_head_hexsha": "021b17ac721e292b277d2b740e2ff8ab38bb6a4a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscf/cc/ccsd_lambda.py", "max_forks_repo_name": "fdmalone/pyscf", "max_forks_repo_head_hexsha": "021b17ac721e292b277d2b740e2ff8ab38bb6a4a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8013100437, "max_line_length": 94, "alphanum_fraction": 0.5847729447, "include": true, "reason": "import numpy", "num_tokens": 7245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.3242353859211693, "lm_q1q2_score": 0.18724443259870824}}
{"text": "\"\"\"Implements self supervised semantic shift functions\nIt uses poisoning attacks to learn landmarks in a self-supervised way\nAt each iteration, generate perturbation on the data, generating positive\nand negative samples\nLearn the separation between them (using any classifier)\nApply the classifier to the original (non-perturbated) data\nNegatives -> landmarks\nPositives -> semantically changed\nWe can begin by aligning on all words, and then learn better landmarks from\nthere. Alternatively, one can start from random landmarks.\"\"\"\n\n\n# Third party modules\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.metrics import accuracy_score, log_loss\nfrom scipy.spatial.distance import cosine, euclidean\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Local modules\nfrom WordVectors import WordVectors, intersection\nfrom alignment import align\n\n\n# Initialize random seeds\nnp.random.seed(1)\ntf.random.set_seed(1)\n\ndef negative_samples(words, size, p=None):\n    \"\"\"\n    Returns negative samples of semantic change\n    May use distribution of cosine distance as sampling distribution\n    \"\"\"\n    neg_samples = np.random.choice(words, size, p=p)\n\n    return neg_samples\n\ndef inject_change_single(wv, w, words, v_a, alpha, replace=False,\n                         max_tries=50):\n    \"\"\"\n    Injects change to word w in wv by randomly selecting a word t in wv\n    and injecting the sense of t in to w.\n    The modified vector of w must have a higher cosine distance to v_a\n    than its original version. This is done by sampling t while the cosine of\n    w is not greater than that of v_a and wv(w) or until a max_tries.\n    v_a is the vector of word w in the parallel corpus (not wv).\n\n    Arguments:\n            wv      -   WordVectors of the corpus to be modified\n            w       -   (str) Word to be modified\n            words   -   (list) Pool of words to sample from, injecting sense\n            v_a     -   (np.ndarray) word vector of w in the source parallel to wv\n            alpha   -   (float) Rate of injected change\n            replace -   (bool) Whether to replace w with t instead of 'moving' w towards t\n    Returns:\n            x       -   (np.ndarray) modified vector of w\n    \"\"\"\n    cos_t = cosine(v_a, wv[w])  # cosine distance threshold we want to surpass\n\n    c = 0\n    tries = 0\n    w_id = wv.word_id[w]\n    v_b = np.copy(wv.vectors[w_id])\n    while c < cos_t and tries < max_tries:\n        tries += 1\n        selected = np.random.choice(words)  # select word with new sense\n        if not replace:\n            b = wv[w] + alpha*wv[selected]\n            v_b = b\n        else:\n            v_b = wv[selected]\n\n        c = cosine(v_a, v_b)\n\n    return v_b\n\n\ndef inject_change_batch(wv, changes, alpha, replace=True):\n    \"\"\"\n    Given a WordVectors object and a list of words, perform fast injection\n    of semantic change by using the update rule from Word2Vec\n    wv - WordVectors (input)\n    changes - list of n tuples (a, b) that drives the change such that b->a\n          i.e.: simulates using b in the contexts of a\n    alpha - degree in which to inject the change\n              if scalar: apply same alpha to every pair\n              if array-like: requires size n, specifies individual alpha values\n                              for each pair\n    replace  - (bool) if True, words are replaced instead of moved\n                e.g.: if pair is (dog, car), then v_car <- v_dog\n    Returns a WordVectors object with the change\n    \"\"\"\n    wv_new = WordVectors(words=wv.words, vectors=np.copy(wv.vectors))\n    for i, pair in enumerate(changes):\n        t, w = pair\n        t_i = wv.word_id[t]  # target word\n        w_i = wv.word_id[w]  # modified word\n        # Update vector with alpha and score\n        # Higher score means vectors are already close, thus apply less change\n        # Alpha controls the rate of change\n        if not replace:\n            b = wv_new[w] + alpha*(1)*wv[t]\n            wv_new.vectors[w_i] = b\n        else:\n            wv_new.vectors[w_i] = wv[t]\n        # print(\"norm b\", np.linalg.norm(b))\n    return wv_new\n\n\ndef get_features(x, names=[\"cos\"]):\n    \"\"\"\n    Compute features given input training data (concatenated vectors)\n    Default features is cosine. Accepted features: cosine (cos).\n    Attributes:\n            x   - size n input training data as concatenated word vectors\n            names - size d list of features to compute\n    Returns:\n            n x d feature matrix (floats)\n    \"\"\"\n    x_out = np.zeros((len(x), len(names)), dtype=float)\n    for i, p in enumerate(x):\n        for j, feat in enumerate(names):\n            if feat == \"cos\":\n                x_ = cosine(p[:len(p)//2], p[len(p)//2:])\n                x_out[i][j] = x_\n    return x_out\n\n\ndef build_sklearn_model():\n    \"\"\"\n    Build SVM using sklearn model\n    The model uses an RBF kernel and the features are given by difference\n    between input vectors u-v.\n    Return: sklearn SVC\n    \"\"\"\n    model = SVC(random_state=0, probability=True)\n    return model\n\n\ndef build_keras_model(dim):\n    \"\"\"\n    Builds the keras model to be used in self-supervision.\n    Return: Keras-Tensorflow2 model\n    \"\"\"\n    h1_dim = 100\n    h2_dim = 100\n    model = keras.Sequential([\n                             keras.layers.Input(shape=(dim)),\n                             keras.layers.Dense(h1_dim, activation=\"relu\",\n                                                activity_regularizer=keras.regularizers.l2(1e-2)),\n                             # keras.layers.Dense(h2_dim, activation=\"relu\",\n                             #                    activity_regularizer=keras.regularizers.l2(1e-2)),\n                             keras.layers.Dense(1, activation=\"sigmoid\")\n                            ])\n    model.compile(optimizer=\"rmsprop\",\n                  loss=\"binary_crossentropy\",\n                  metrics=[\"accuracy\"])\n    return model\n\n\ndef threshold_crossvalidation(wv1, wv2, iters=100,\n                                        n_fold=1,\n                                        n_targets=100,\n                                        n_negatives=100,\n                                        fast=True,\n                                        rate=0.5,\n                                        t=0.5,\n                                        landmarks=None,\n                                        t_overlap=1,\n                                        debug=False):\n    \"\"\"\n    Runs crossvalidation over self-supervised samples, carrying out a model\n    selection to determine the best cosine threshold to use in the final\n    prediction.\n\n    Arguments:\n        wv1, wv2    - input WordVectors - required to be intersected and ALIGNED before call\n        plot        - 1: plot functions in the end 0: do not plot\n        iters       - max no. of iterations\n        n_fold      - n-fold crossvalidation (1 - leave one out, 10 - 10-fold cv, etc.)\n        n_targets   - number of positive samples to generate\n        n_negatives - number of negative samples\n        fast        - use fast semantic change simulation\n        rate        - rate of semantic change injection\n        t           - classificaiton threshold (0.5)\n        t_overlap   - overlap threshold for (stop criterion)\n        landmarks   - list of words to use as landmarks (classification only)\n        debug       - toggles debugging mode on/off. Provides reports on several metrics. Slower.\n    Returns:\n        t - selected cosine threshold t\n    \"\"\"\n\n    wv2_original = WordVectors(words=wv2.words, vectors=wv2.vectors.copy())\n    landmark_set = set(landmarks)\n    non_landmarks = [w for w in wv1.words if w not in landmark_set]\n\n    for iter in range(iters):\n\n        replace = dict()  # replacement dictionary\n        pos_samples = list()\n        pos_vectors = dict()\n\n        # Randomly sample words to inject change to\n        # If no word is flagged as non_landmarks, sample from all words\n        # In practice, this should never occur when selecting landmarks\n        # but only for classification when aligning on all words\n        if len(non_landmarks) > 0:\n            targets = np.random.choice(non_landmarks, n_targets)\n            # Make targets deterministic\n            #targets = non_landmarks\n        else:\n            targets = np.random.choice(wv1.words, n_targets)\n\n        for target in targets:\n\n            # Simulate semantic change in target word\n            v = inject_change_single(wv2_original, target, wv1.words,\n                                     wv1[target], rate)\n\n            pos_vectors[target] = v\n\n            pos_samples.append(target)\n        # Convert to numpy array\n        pos_samples = np.array(pos_samples)\n        # Get negative samples from landmarks\n        neg_samples = negative_samples(landmarks, n_negatives, p=None)\n        neg_vectors = {w: wv2_original[w] for w in neg_samples}\n        # Create dictionary of supervision samples (positive and negative)\n        # Mapping word -> vector\n        sup_vectors = {**neg_vectors, **pos_vectors}\n\n        # Prepare training data\n        words_train = np.concatenate((pos_samples, neg_samples))\n        # assign labels to positive and negative samples\n        y_train = [1] * len(pos_samples) + [0] * len(neg_samples)\n\n        # Stack columns to shuffle data and labels together\n        train = np.column_stack((words_train, y_train))\n        # Shuffle batch\n        np.random.shuffle(train)\n        # Detach data and labels\n        words_train = train[:, 0]\n        y_train = train[:, -1].astype(int)\n\n        # Calculate cosine distance of training samples\n        x_train = np.array([cosine(wv1[w], sup_vectors[w]) for w in words_train])\n\n        # t_pool = [0.2, 0.7]\n        t_pool = np.arange(0.2, 1, 0.1)\n\n        best_acc = 0\n        best_t = 0\n        for t_ in t_pool:\n            acc = 0\n            for i in range(0, len(x_train), n_fold):\n                x_cv = x_train[i:i+n_fold]\n                y_true = y_train[i:i+n_fold]\n                y_hat = x_cv > t_\n                acc += sum(y_hat == y_true)/len(x_cv)\n            acc = acc/(len(x_train)//n_fold)\n            if acc > best_acc:\n                best_acc = acc\n                best_t = t_\n                print(\"- New best t\", t_, acc)\n\n    return best_t\n\n\n\n\n\ndef s4(wv1, wv2, verbose=0, plot=0, cls_model=\"nn\",\n                              iters=100,\n                              n_targets=10,\n                              n_negatives=10,\n                              fast=True,\n                              rate=0,\n                              t=0.5,\n                              t_overlap=1,\n                              landmarks=None,\n                              update_landmarks=True,\n                              return_model=False,\n                              debug=False):\n    \"\"\"\n    Performs self-supervised learning of semantic change.\n    Generates negative samples by sampling from landmarks.\n    Generates positive samples via simulation of semantic change on random non-landmark words.\n    Trains a classifier, fine-tune it across multiple iterations.\n    If update_landmarks is True, then it learns landmarks from that step. In this case,\n    the returned values are landmarks, non_landmarks, Q (transform matrix)\n    Otherwise, landmarks are fixed from a starting set and the returned value\n    is the learned classifier - landmarks must be passed.\n    Arguments:\n        wv1, wv2    - input WordVectors - required to be intersected before call\n        verbose     - 1: display log, 0: quiet\n        plot        - 1: plot functions in the end 0: do not plot\n        cls_model   - classification model to use {\"nn\", \"svm_auto\", \"svm_features\"}\n        iters       - max no. of iterations\n        n_targets   - number of positive samples to generate\n        n_negatives - number of negative samples\n        fast        - use fast semantic change simulation\n        rate        - rate of semantic change injection\n        t           - classificaiton threshold (0.5)\n        t_overlap   - overlap threshold for (stop criterion)\n        landmarks   - list of words to use as landmarks (classification only)\n        update_landmarks - if True, learns landmarks. Otherwise, learns classification model.\n        debug       - toggles debugging mode on/off. Provides reports on several metrics. Slower.\n    Returns:\n        if update_landmarks is True:\n            landmarks - list of landmark words\n            non_landmarks - list of non_landmark words\n            Q           - transformation matrix for procrustes alignment\n        if update_landmarks is False:\n            model       - binary classifier\n    \"\"\"\n\n    # Define verbose prints\n    if verbose==1:\n        def verbose_print(*s, end=\"\\n\"):\n            print(*s, end=end)\n    elif verbose==0:\n        def verbose_print(*s, end=\"\\n\"):\n            return None\n\n    wv2_original = WordVectors(words=wv2.words, vectors=wv2.vectors.copy())\n\n\n    avg_window = 0  # number of iterations to use in running average\n\n    # Begin alignment\n    if update_landmarks:\n        # Check if landmarks is initialized\n        if landmarks == None:\n            wv1, wv2, Q = align(wv1, wv2)  # start form global alignment\n            landmark_dists = [euclidean(u, v) for u, v in zip(wv1.vectors, wv2.vectors)]\n            landmark_args = np.argsort(landmark_dists)\n            landmarks = [wv1.words[i] for i in landmark_args[:int(len(wv1.words)*0.5)]]\n            # landmarks = np.random.choice(wv1.words, int(len(wv1)*0.5))\n        landmark_set = set(landmarks)\n        non_landmarks = np.array([w for w in wv1.words if w not in landmark_set])\n    else:\n        landmark_set = set(landmarks)\n        non_landmarks = [w for w in wv1.words if w not in landmark_set]\n\n    wv1, wv2, Q = align(wv1, wv2, anchor_words=landmarks)\n\n    if cls_model == \"nn\":\n        model = build_keras_model(wv1.dimension*2)\n    elif cls_model == \"svm_auto\" or cls_model == \"svm_features\":\n        model = build_sklearn_model()  # get SVC\n\n    landmark_hist = list()  # store no. of landmark history\n    loss_hist = list()  # store self-supervision loss history\n    alignment_loss_hist = list()  # store landmark alignment loss\n    alignment_out_hist = list()  # store alignment loss outside of lm\n    alignment_all_hist = list()\n\n    cumulative_out_hist = list()\n    cumulative_alignment_hist = list()  # store cumulative loss alignment\n    overlap_hist = list()  # store landmark overlap history\n    cumulative_overlap_hist = list()  # mean overlap history\n    cumulative_loss = 0\n\n    # History of cosines\n    cos_loss_in_hist = list()\n    cos_loss_out_hist = list()\n    cumulative_cos_in = list()\n    cumulative_cos_out = list()\n\n    prev_landmarks = set(landmarks)\n    for iter in range(iters):\n\n        replace = dict()  # replacement dictionary\n        pos_samples = list()\n        pos_vectors = dict()\n\n        # Randomly sample words to inject change to\n        # If no word is flagged as non_landmarks, sample from all words\n        # In practice, this should never occur when selecting landmarks\n        # but only for classification when aligning on all words\n        if len(non_landmarks) > 0:\n            targets = np.random.choice(non_landmarks, n_targets)\n            # Make targets deterministic\n            #targets = non_landmarks\n        else:\n            targets = np.random.choice(wv1.words, n_targets)\n\n        for target in targets:\n\n            # Simulate semantic change in target word\n            v = inject_change_single(wv2_original, target, wv1.words,\n                                     wv1[target], rate)\n\n            pos_vectors[target] = v\n\n            pos_samples.append(target)\n        # Convert to numpy array\n        pos_samples = np.array(pos_samples)\n        # Get negative samples from landmarks\n        neg_samples = negative_samples(landmarks, n_negatives, p=None)\n        neg_vectors = {w: wv2_original[w] for w in neg_samples}\n        # Create dictionary of supervision samples (positive and negative)\n        # Mapping word -> vector\n        sup_vectors = {**neg_vectors, **pos_vectors}\n\n        # Prepare training data\n        words_train = np.concatenate((pos_samples, neg_samples))\n        # assign labels to positive and negative samples\n        y_train = [1] * len(pos_samples) + [0] * len(neg_samples)\n\n        # Stack columns to shuffle data and labels together\n        train = np.column_stack((words_train, y_train))\n        # Shuffle batch\n        np.random.shuffle(train)\n        # Detach data and labels\n        words_train = train[:, 0]\n        y_train = train[:, -1].astype(int)\n\n        x_train = np.array([np.append(wv1[w], sup_vectors[w]) for w in words_train])\n\n        # Append history\n        landmark_hist.append(len(landmarks))\n        v1_land = np.array([wv1[w] for w in landmarks])\n        v2_land = np.array([wv2_original[w] for w in landmarks])\n        v1_out = np.array([wv1[w] for w in non_landmarks])\n        v2_out = np.array([wv2_original[w] for w in non_landmarks])\n\n        alignment_loss = np.linalg.norm(v1_land-v2_land)**2/len(v1_land)\n        alignment_loss_hist.append(alignment_loss)\n        cumulative_alignment_hist.append(np.mean(alignment_loss_hist[-avg_window:]))\n\n        # out loss\n        alignment_out_loss = np.linalg.norm(v1_out-v2_out)**2/len(v1_out)\n        alignment_out_hist.append(alignment_out_loss)\n        cumulative_out_hist.append(np.mean(alignment_out_hist[-avg_window:]))\n\n        # all loss\n        alignment_all_loss = np.linalg.norm(wv1.vectors-wv2_original.vectors)**2/len(wv1.words)\n        alignment_all_hist.append(alignment_all_loss)\n\n        if debug:\n        # cosine loss\n            cos_in = np.mean([cosine(u, v) for u, v in zip (v1_land, v2_land)])\n            cos_out = np.mean([cosine(u, v) for u, v in zip(v1_out, v2_out)])\n            cos_loss_in_hist.append(cos_in)\n            cos_loss_out_hist.append(cos_out)\n            cumulative_cos_in.append(np.mean(cos_loss_in_hist))\n            cumulative_cos_out.append(np.mean(cos_loss_out_hist))\n\n        # Begin training of neural network\n        if cls_model == \"nn\":\n            history = model.train_on_batch(x_train, y_train, reset_metrics=False)\n            # history = model.fit(x_train, y_train, epochs=5, verbose=0)\n            # history = [history.history[\"loss\"][0]]\n        elif cls_model == \"svm_auto\":\n            model.fit(x_train, y_train)\n            pred_train = model.predict_proba(x_train)\n            history = [log_loss(y_train, pred_train)]\n        elif cls_model == \"svm_features\":\n            x_train_ = get_features(x_train)  # retrieve manual features\n            model.fit(x_train_, y_train)\n            pred_train = model.predict_proba(x_train_)\n            y_hat_t = (pred_train[:, 0] > 0.5)\n            acc_t = accuracy_score(y_train, y_hat_t)\n            history = [log_loss(y_train, pred_train), acc_t]\n\n        loss_hist.append(history[0])\n\n        # Apply model on original data to select landmarks\n        x_real = np.array([np.append(u, v) for u, v\n                            in zip(wv1.vectors, wv2_original.vectors)])\n        if cls_model == \"nn\":\n            predict_real = model.predict(x_real)\n        elif cls_model == \"svm_auto\":\n            predict_real = model.predict_proba(x_real)\n            predict_real = predict_real[:, 1]\n        elif cls_model == \"svm_features\":\n            x_real_ = get_features(x_real)\n            predict_real = model.predict_proba(x_real_)\n            predict_real = predict_real[:, 1]\n\n        y_predict = (predict_real>t)\n\n        if update_landmarks:\n            landmarks = [wv1.words[i] for i in range(len(wv1.words)) if predict_real[i]<t]\n            non_landmarks = [wv1.words[i] for i in range(len(wv1.words)) if predict_real[i]>t]\n\n        # Update landmark overlap using Jaccard Index\n        isect_ab = set.intersection(prev_landmarks, set(landmarks))\n        union_ab = set.union(prev_landmarks, set(landmarks))\n        j_index = len(isect_ab)/len(union_ab)\n        overlap_hist.append(j_index)\n\n\n\n        cumulative_overlap_hist.append(np.mean(overlap_hist[-avg_window:]))  # store mean\n\n        prev_landmarks = set(landmarks)\n\n        verbose_print(\"> %3d | L %4d | l(in): %.2f | l(out): %.2f | loss: %.2f | overlap %.2f | acc: %.2f\" %\n                        (iter, len(landmarks), cumulative_alignment_hist[-1],\n                         cumulative_out_hist[-1], history[0], cumulative_overlap_hist[-1], history[1]),\n                         end=\"\\r\")\n\n        wv1, wv2_original, Q = align(wv1, wv2_original, anchor_words=landmarks)\n\n\n        # Check if overlap difference is below threhsold\n        if np.mean(overlap_hist) > t_overlap:\n            break\n\n\n\n    # Print new line\n    verbose_print()\n\n    if plot == 1:\n        iter += 1  # add one to iter for plotting\n        plt.plot(range(iter), landmark_hist, label=\"landmarks\")\n        plt.hlines(len(wv1.words), 0, iter, colors=\"red\")\n        plt.ylabel(\"No. of landmarks\")\n        plt.xlabel(\"Iteration\")\n        plt.show()\n        plt.plot(range(iter), loss_hist, c=\"red\", label=\"loss\")\n        plt.ylabel(\"Loss (binary crossentropy)\")\n        plt.xlabel(\"Iteration\")\n        plt.legend()\n        plt.show()\n        plt.plot(range(iter), cumulative_alignment_hist, label=\"in (landmarks)\")\n        plt.plot(range(iter), cumulative_out_hist, label=\"out\")\n        plt.plot(range(iter), alignment_all_hist, label=\"all\")\n        plt.ylabel(\"Alignment loss (MSE)\")\n        plt.xlabel(\"Iteration\")\n        plt.legend()\n        plt.show()\n\n        if debug:\n            plt.plot(range(iter), cumulative_cos_in, label=\"cos in\")\n            plt.plot(range(iter), cumulative_cos_out, label=\"cos out\")\n            plt.legend()\n            plt.show()\n\n        plt.plot(range(iter), cumulative_overlap_hist, label=\"overlap\")\n\n        plt.ylabel(\"Jaccard Index\", fontsize=16)\n        plt.xlabel(\"Iteration\", fontsize=16)\n        plt.xticks(fontsize=16)\n        plt.yticks(fontsize=16)\n        # plt.legend()\n        plt.tight_layout()\n        plt.savefig(\"overlap.pdf\", format=\"pdf\")\n        #plt.show()\n\n    if update_landmarks:\n        if not return_model:\n            return landmarks, non_landmarks, Q\n        else:\n            return landmarks, non_landmarks, Q, model\n    else:\n        return model\n\n\ndef main():\n    \"\"\"\n    Runs main experiments using self supervised alignment.\n    \"\"\"\n    # wv_source = \"wordvectors/latin/corpus1/0.vec\"\n    # wv_target = \"wordvectors/latin/corpus2/0.vec\"\n    # wv_source = \"wordvectors/source/theguardianuk.vec\"\n    # wv_target = \"wordvectors/source/thenewyorktimes_1.vec\"\n    wv_source = \"wordvectors/semeval/latin-corpus1.vec\"\n    wv_target = \"wordvectors/semeval/latin-corpus2.vec\"\n    # wv_source = \"wordvectors/usuk/bnc.vec\"\n    # wv_target = \"wordvectors/usuk/coca_mag.vec\"\n    # wv_source = \"wordvectors/artificial/NYT-0.vec\"\n    # wv_target = \"wordvectors/artificial/NYT-500_random.vec\"\n    plt.style.use(\"seaborn\")\n\n    # Read WordVectors\n    normalized = False\n    wv1 = WordVectors(input_file=wv_source, normalized=normalized)\n    wv2 = WordVectors(input_file=wv_target, normalized=normalized)\n\n    wv1, wv2 = intersection(wv1, wv2)\n\n    landmarks, non_landmarks, Q = s4(wv1, wv2,\n                                                            cls_model=\"nn\",\n                                                            n_targets=100,\n                                                            n_negatives=100,\n                                                            rate=1,\n                                                            t=0.5,\n                                                            iters=100,\n                                                            verbose=1,\n                                                            plot=1)\n    wv1, wv2, Q = align(wv1, wv2, anchor_words=landmarks)\n    d_l = [cosine(wv1[w], wv2[w]) for w in landmarks]\n    d_n = [cosine(wv1[w], wv2[w]) for w in non_landmarks]\n    sns.distplot(d_l, color=\"blue\")\n    sns.distplot(d_n, color=\"red\")\n    plt.legend()\n    plt.show()\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "ecbe52c74e5ecb8650ccf94ee701fb8799558887", "size": 24116, "ext": "py", "lang": "Python", "max_stars_repo_path": "s4.py", "max_stars_repo_name": "IBM/S4_semantic_shift", "max_stars_repo_head_hexsha": "6905899fdf7a3526e5ab958127c6388c7d64ac0a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-18T21:38:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-18T21:38:01.000Z", "max_issues_repo_path": "s4.py", "max_issues_repo_name": "IBM/S4_semantic_shift", "max_issues_repo_head_hexsha": "6905899fdf7a3526e5ab958127c6388c7d64ac0a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "s4.py", "max_forks_repo_name": "IBM/S4_semantic_shift", "max_forks_repo_head_hexsha": "6905899fdf7a3526e5ab958127c6388c7d64ac0a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5993431856, "max_line_length": 108, "alphanum_fraction": 0.5968236855, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3629692193015555, "lm_q1q2_score": 0.18715415826631684}}
{"text": "# STUMPY\n# Copyright 2019 TD Ameritrade. Released under the terms of the 3-Clause BSD license.  # noqa: E501\n# STUMPY is a trademark of TD Ameritrade IP Company, Inc. All rights reserved.\n\nimport numpy as np\nimport scipy.signal\n\ntry:\n    from numba.cuda.cudadrv.driver import _raise_driver_not_found\nexcept ImportError:\n    pass\n\n\ndef driver_not_found():  # pragma: no cover\n    \"\"\"\n    Helper function to raise CudaSupportError driver not found error\n    \"\"\"\n\n    _raise_driver_not_found()\n\n\ndef get_pkg_name():  # pragma: no cover\n    \"\"\"\n    Return package name\n    \"\"\"\n\n    return __name__.split(\".\")[0]\n\n\ndef rolling_window(a, window):\n    \"\"\"\n    Use strides to generate rolling/sliding windows for a numpy array\n\n    Parameters\n    ----------\n    a : ndarray\n        numpy array\n\n    window : int\n        Size of the rolling window\n\n    Returns\n    -------\n    output : ndarray\n        This will be a new view of the original input array.\n    \"\"\"\n\n    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)\n    strides = a.strides + (a.strides[-1],)\n\n    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)\n\n\ndef z_norm(a, axis=0):\n    \"\"\"\n    Calculate the z-normalized input array `a` by subtracting the mean and\n    dividing by the standard deviation along a given axis.\n\n    Parameters\n    ----------\n    a : ndarray\n        numpy array\n\n    axis : int\n        numpy axis\n\n    Returns\n    -------\n    output : ndarray\n        An ndarray with z-normalized values computed along a specified axis.\n    \"\"\"\n\n    return (a - np.mean(a, axis, keepdims=True)) / np.std(a, axis, keepdims=True)\n\n\ndef check_dtype(a, dtype=np.floating):  # pragma: no cover\n    \"\"\"\n    Check if the array type of `a` is of type specified by `dtype` parameter.\n\n    Raises\n    ------\n    TypeError\n        If the array type does not match `dtype`\n    \"\"\"\n\n    if not np.issubdtype(a.dtype, dtype):\n        msg = f\"{dtype} type expected but found {a.dtype}\"\n        raise TypeError(msg)\n\n    return True\n\n\ndef transpose_dataframe(a):  # pragma: no cover\n    \"\"\"\n    Check if the input is a column-wise Pandas `DataFrame`. If `True`, return a\n    transpose dataframe since stumpy assumes that each row represents data from a\n    different dimension while each column represents data from the same dimension.\n    If `False`, return `a` unchanged. Pandas `Series` do not need to be transposed.\n\n    Note that this function has zero dependency on Pandas (not even a soft dependency).\n\n    Parameters\n    ----------\n    a : ndarray\n        First argument.\n\n    Returns\n    -------\n    output : a\n        If a is a Pandas `DataFrame` then return `a.T`. Otherwise, return `a`\n    \"\"\"\n\n    if type(a).__name__ == \"DataFrame\":\n        return a.T\n\n    return a\n\n\ndef are_arrays_equal(a, b):  # pragma: no cover\n    \"\"\"\n    Check if two arrays are equal; first by comparing memory addresses,\n    and secondly by their values.\n\n    Parameters\n    ----------\n    a : ndarray\n        First argument.\n\n    b : ndarray\n        Second argument.\n\n    Returns\n    -------\n    output : bool\n        Returns `True` if the arrays are equal and `False` otherwise.\n    \"\"\"\n\n    if id(a) == id(b):\n        return True\n\n    return np.array_equal(a, b)\n\n\ndef are_distances_too_small(a, threshold=10e-6):  # pragma: no cover\n    \"\"\"\n    Check the distance values from a matrix profile.\n\n    If the values are smaller than the threshold (i.e., less than 10e-6) then\n    it could suggest that this is a self-join.\n\n    Parameters\n    ----------\n    a : ndarray\n        First argument.\n\n    threshold : float\n        Minimum value in which to compare the matrix profile to\n\n    Returns\n    -------\n    output : bool\n        Returns `True` if the matrix profile distances are all below the\n        threshold and `False` if they are all above the threshold.\n    \"\"\"\n\n    if a.mean() < threshold or np.all(a < threshold):\n        return True\n\n    return False\n\n\ndef check_window_size(m):\n    if m <= 2:\n        raise ValueError(\n            \"All window sizes must be greater than or equal to three\",\n            \"\"\"A window size that is less than or equal to two is meaningless when\n            it comes to computing the z-normalized Euclidean distance. In the case of\n            `m=1` produces a standard deviation of zero. In the case of `m=2`, both\n            the mean and standard deviation for any given subsequence are identical\n            and so the z-normalization for any sequence will either be [-1., 1.] or\n            [1., -1.]. Thus, the z-normalized Euclidean distance will be (very likely)\n            zero between any subsequence and its nearest neighbor (assuming that the\n            time series is large enough to contain both scenarios).\n            \"\"\",\n        )\n\n\ndef sliding_dot_product(Q, T):\n    \"\"\"\n    Use FFT convolution to calculate the sliding window dot product.\n\n    Parameters\n    ----------\n    Q : ndarray\n        Query array or subsequence\n\n    T : ndarray\n        Time series or sequence\n\n    Returns\n    -------\n    output : ndarray\n        Sliding dot product between `Q` and `T`.\n\n    Notes\n    -----\n    Calculate the sliding dot product\n\n    `DOI: 10.1109/ICDM.2016.0179 \\\n    <https://www.cs.ucr.edu/~eamonn/PID4481997_extend_Matrix%20Profile_I.pdf>`__\n\n    See Table I, Figure 4\n\n    Following the inverse FFT, Fig. 4 states that only cells [m-1:n]\n    contain valid dot products\n\n    Padding is done automatically in fftconvolve step\n    \"\"\"\n\n    n = T.shape[0]\n    m = Q.shape[0]\n    Qr = np.flipud(Q)  # Reverse/flip Q\n    QT = convolution(Qr, T)\n\n    return QT.real[m - 1 : n]\n\n\ndef compute_mean_std(T, m):\n    \"\"\"\n    Compute the sliding mean and standard deviation for the array `T` with\n    a window size of `m`\n\n    Parameters\n    ----------\n    T : ndarray\n        Time series or sequence\n\n    m : int\n        Window size\n\n    Returns\n    -------\n    M_T : ndarray\n        Sliding mean\n\n    Σ_T : ndarray\n        Sliding standard deviation\n\n    Notes\n    -----\n    `DOI: 10.1109/ICDM.2016.0179 \\\n    <https://www.cs.ucr.edu/~eamonn/PID4481997_extend_Matrix%20Profile_I.pdf>`__\n\n    See Table II\n\n    DOI: 10.1145/2020408.2020587\n\n    See Page 2 and Equations 1, 2\n\n    DOI: 10.1145/2339530.2339576\n\n    See Page 4\n\n    http://www.cs.unm.edu/~mueen/FastestSimilaritySearch.html\n\n    Note that Mueen's algorithm has an off-by-one bug where the\n    sum for the first subsequence is omitted and we fixed that!\n    \"\"\"\n    n = T.shape[0]\n\n    cumsum_T = np.empty(len(T) + 1)\n    np.cumsum(T, out=cumsum_T[1:])  # store output in cumsum_T[1:]\n    cumsum_T[0] = 0\n\n    cumsum_T_squared = np.empty(len(T) + 1)\n    np.cumsum(np.square(T), out=cumsum_T_squared[1:])\n    cumsum_T_squared[0] = 0\n\n    subseq_sum_T = cumsum_T[m:] - cumsum_T[: n - m + 1]\n    subseq_sum_T_squared = cumsum_T_squared[m:] - cumsum_T_squared[: n - m + 1]\n    M_T = subseq_sum_T / m\n    Σ_T = np.abs((subseq_sum_T_squared / m) - np.square(M_T))\n    Σ_T = np.sqrt(Σ_T)\n\n    return M_T, Σ_T\n\n\ndef calculate_distance_profile(m, QT, μ_Q, σ_Q, M_T, Σ_T):\n    \"\"\"\n    Compute the distance profile\n\n    Parameters\n    ----------\n    m : int\n        Window size\n\n    QT : ndarray\n        Dot product between `Q` and `T`\n\n    μ_Q : ndarray\n        Mean of `Q`\n\n    σ_Q : ndarray\n        Standard deviation of `Q`\n\n    M_T : ndarray\n        Sliding mean of `T`\n\n    Σ_T : ndarray\n        Sliding standard deviation of `T`\n\n    Returns\n    -------\n    output : ndarray\n        Distance profile\n\n    Notes\n    -----\n    `DOI: 10.1109/ICDM.2016.0179 \\\n    <https://www.cs.ucr.edu/~eamonn/PID4481997_extend_Matrix%20Profile_I.pdf>`__\n\n    See Equation on Page 4\n    \"\"\"\n\n    denom = m * σ_Q * Σ_T\n    denom[denom == 0] = 1e-10  # Avoid divide by zero\n    D_squared = np.abs(2 * m * (1.0 - (QT - m * μ_Q * M_T) / denom))\n    return np.sqrt(D_squared)\n\n\ndef mueen_calculate_distance_profile(Q, T):\n    \"\"\"\n    Compute the mueen distance profile\n\n    Parameters\n    ----------\n    Q : ndarray\n        Query array or subsequence\n\n    T : ndarray\n        Time series or sequence\n\n    Returns\n    -------\n    output : ndarray\n        Distance profile\n\n    Notes\n    -----\n    `DOI: 10.1109/ICDM.2016.0179 \\\n    <https://www.cs.ucr.edu/~eamonn/PID4481997_extend_Matrix%20Profile_I.pdf>`__\n\n    See Table II\n\n    DOI: 10.1145/2020408.2020587\n\n    See Page 2 and Equations 1, 2\n\n    DOI: 10.1145/2339530.2339576\n\n    See Page 4\n\n    http://www.cs.unm.edu/~mueen/FastestSimilaritySearch.html\n\n    Note that Mueen's algorithm has an off-by-one bug where the\n    sum for the first subsequence is omitted and we fixed that!\n    \"\"\"\n    n = T.shape[0]\n    m = Q.shape[0]\n\n    μ_Q = np.mean(Q, keepdims=True)\n    σ_Q = np.std(Q, keepdims=True)\n    Q_norm = (Q - μ_Q) / σ_Q\n    QT = sliding_dot_product(Q_norm, T)\n\n    cumsum_T = np.empty(len(T) + 1)  # Add one element, fix off-by-one\n    np.cumsum(T, out=cumsum_T[1:])  # store output in cumsum_T[1:]\n    cumsum_T[0] = 0\n\n    cumsum_T_squared = np.empty(len(T) + 1)\n    np.cumsum(np.square(T), out=cumsum_T_squared[1:])\n    cumsum_T_squared[0] = 0\n\n    subseq_sum_T = cumsum_T[m:] - cumsum_T[: n - m + 1]\n    subseq_sum_T_squared = cumsum_T_squared[m:] - cumsum_T_squared[: n - m + 1]\n    M_T = subseq_sum_T / m\n    Σ_T_squared = np.abs(subseq_sum_T_squared / m - np.square(M_T))\n    Σ_T = np.sqrt(Σ_T_squared)\n\n    D = np.abs(\n        (subseq_sum_T_squared - 2 * subseq_sum_T * M_T + m * np.square(M_T))\n        / Σ_T_squared\n        - 2 * QT / Σ_T\n        + m\n    )\n    return np.sqrt(D)\n\n\ndef mass(Q, T, M_T=None, Σ_T=None):\n    \"\"\"\n    Compute the distance profile using the MASS algorithm\n\n    Parameters\n    ----------\n    Q : ndarray\n        Query array or subsequence\n\n    T : ndarray\n        Time series or sequence\n\n    M_T : ndarray (optional)\n        Sliding mean of `T`\n\n    Σ_T : ndarray (optional)\n        Sliding standard deviation of `T`\n\n    Returns\n    -------\n    output : ndarray\n        Distance profile\n\n    Notes\n    -----\n    `DOI: 10.1109/ICDM.2016.0179 \\\n    <https://www.cs.ucr.edu/~eamonn/PID4481997_extend_Matrix%20Profile_I.pdf>`__\n\n    See Table II\n\n    Note that Q, T are not directly required to calculate D\n\n    Note: Unlike the Matrix Profile I paper, here, M_T, Σ_T can be calculated\n    once for all subsequences of T and passed in so the redundancy is removed\n    \"\"\"\n\n    QT = sliding_dot_product(Q, T)\n    m = Q.shape[0]\n    μ_Q, σ_Q = compute_mean_std(Q, m)\n    if M_T is None or Σ_T is None:\n        M_T, Σ_T = compute_mean_std(T, m)\n\n    return calculate_distance_profile(m, QT, μ_Q, σ_Q, M_T, Σ_T)\n\n\nconvolution = scipy.signal.fftconvolve  # Swap for other convolution function\n", "meta": {"hexsha": "76d6e108e206d012101bed569dbee7d2fad6cc4a", "size": 10638, "ext": "py", "lang": "Python", "max_stars_repo_path": "stumpy/core.py", "max_stars_repo_name": "Deepakgthomas/stumpy", "max_stars_repo_head_hexsha": "217b6fcc34f501ca580e4700d4881be050c0d94a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-18T04:54:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-18T04:54:04.000Z", "max_issues_repo_path": "stumpy/core.py", "max_issues_repo_name": "stanleyjacob/stumpy", "max_issues_repo_head_hexsha": "d40afb3c3fff5900e4c850aa2dfd8e09edebfeda", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stumpy/core.py", "max_forks_repo_name": "stanleyjacob/stumpy", "max_forks_repo_head_hexsha": "d40afb3c3fff5900e4c850aa2dfd8e09edebfeda", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9056179775, "max_line_length": 99, "alphanum_fraction": 0.6171272796, "include": true, "reason": "import numpy,import scipy,from numba", "num_tokens": 2932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.18715415116007475}}
{"text": "# Copyright (c) 2009-2022 The Regents of the University of Michigan.\n# Part of HOOMD-blue, released under the BSD 3-Clause License.\n\n\"\"\"Compute properties of hard particle configurations.\n\nThe HPMC compute classes analyze the system configuration and provide results\nas loggable quantities for use with `hoomd.logging.Logger` or by direct access\nvia the Python API. `FreeVolume` computes the free volume available to small\nparticles, such as depletants, and `SDF` computes the pressure in system of\nconvex particles with a fixed box size.\n\"\"\"\n\nfrom __future__ import print_function\n\nfrom hoomd import _hoomd\nfrom hoomd.operation import Compute\nfrom hoomd.hpmc import _hpmc\nfrom hoomd.hpmc import integrate\nfrom hoomd.data.parameterdicts import ParameterDict\nfrom hoomd.logging import log\nimport hoomd\nimport numpy\n\n\nclass FreeVolume(Compute):\n    r\"\"\"Compute the free volume available to a test particle.\n\n    Args:\n        test_particle_type (str): Test particle type.\n        num_samples (int): Number of samples to evaluate.\n\n    `FreeVolume` computes the free volume in the simulation state available to a\n    given test particle shape using Monte Carlo integration. Use it in\n    combination with `hoomd.hpmc.integrate.HPMCIntegrator`, which defines the\n    particle shape parameters. Particles of ``test_particle_type`` may or may\n    not be present in the simulation state.\n\n    `FreeVolume` generates `num_samples` (:math:`n_\\mathrm{samples}`) trial\n    particle configurations with positions :math:`\\vec{r}^t_j` uniformly\n    distributed in the simulation box, and orientations :math:`\\mathbf{q}^t_j`\n    uniformly distributed among rotations matching the box dimensionality.\n    `FreeVolume` counts the number of successful samples that do not overlap\n    particles in the simulation state:\n\n    .. math::\n\n        n_\\mathrm{success} = \\sum_{j=1}^{n_\\mathrm{samples}}\n            \\prod_{i=0}^{N_\\mathrm{particles}-1}\n            \\prod_{\\vec{A} \\in B_\\mathrm{images}}\n            \\left[\n            \\mathrm{overlap}\\left(\n            S_i(\\mathbf{q}_i),\n            S_t(\\mathbf{q}^t_j, \\vec{r}^t_j - (\\vec{r}_i + \\vec{A}))\n            \\right) = \\emptyset\n            \\right]\n\n    where :math:`\\mathrm{overlap}` is the shape overlap function defined in\n    `hoomd.hpmc.integrate`, :math:`S_i` is the shape of particle :math:`i`,\n    :math:`S_t` is the shape of the test particle, :math:`\\vec{A} = h\\vec{a}_1 +\n    k\\vec{a}_2 + l\\vec{a}_3` is a vector that translates by periodic box images,\n    the set of box images includes all image vectors necessary to find overlaps\n    between particles in the primary image with particles in periodic images,\n    and the square brackets denote the Iverson bracket.\n\n    The free volume :math:`V_\\mathrm{free}` is given by:\n\n    .. math::\n        V_\\mathrm{free} = \\frac{n_\\mathrm{success}}\n                               {n_\\mathrm{samples}} V_\\mathrm{box}\n\n    where :math:`V_\\mathrm{box}` is the volume of the simulation box (or area in\n    2D).\n\n    Note:\n\n        `FreeVolume` respects the HPMC integrator's ``interaction_matrix``.\n\n    .. rubric:: Mixed precision\n\n    `FreeVolume` uses reduced precision floating point arithmetic when checking\n    for particle overlaps in the local particle reference frame.\n\n    .. rubric:: Box images\n\n    On CPU devices, `FreeVolume` does not apply the minimum image convention. It\n    supports small boxes where particles may overlap with non-primary images of\n    other particles, including self overlap. On GPU devices, `FreeVolume`\n    applies the minimum image convention.\n\n    Examples::\n\n        fv = hoomd.hpmc.compute.FreeVolume(test_particle_type='B',\n                                           num_samples=1000)\n\n\n    Attributes:\n        test_particle_type (str): Test particle type.\n\n        num_samples (int): Number of samples to evaluate.\n\n    \"\"\"\n\n    def __init__(self, test_particle_type, num_samples):\n        # store metadata\n        param_dict = ParameterDict(test_particle_type=str, num_samples=int)\n        param_dict.update(\n            dict(test_particle_type=test_particle_type,\n                 num_samples=num_samples))\n        self._param_dict.update(param_dict)\n\n    def _attach(self):\n        integrator = self._simulation.operations.integrator\n        if not isinstance(integrator, integrate.HPMCIntegrator):\n            raise RuntimeError(\"The integrator must be an HPMC integrator.\")\n\n        # Extract 'Shape' from '<hoomd.hpmc.integrate.Shape object>'\n        integrator_name = integrator.__class__.__name__\n        try:\n            if isinstance(self._simulation.device, hoomd.device.CPU):\n                cpp_cls = getattr(_hpmc, 'ComputeFreeVolume' + integrator_name)\n            else:\n                cpp_cls = getattr(_hpmc,\n                                  'ComputeFreeVolume' + integrator_name + 'GPU')\n        except AttributeError:\n            raise RuntimeError(\"Unsupported integrator.\")\n\n        cl = _hoomd.CellList(self._simulation.state._cpp_sys_def)\n        self._cpp_obj = cpp_cls(self._simulation.state._cpp_sys_def,\n                                integrator._cpp_obj, cl)\n\n        super()._attach()\n\n    @log(requires_run=True)\n    def free_volume(self):\n        \"\"\"Free volume available to the test particle \\\n        :math:`[\\\\mathrm{length}^{2}]` in 2D and \\\n        :math:`[\\\\mathrm{length}^{3}]` in 3D.\"\"\"\n        self._cpp_obj.compute(self._simulation.timestep)\n        return self._cpp_obj.free_volume\n\n\nclass SDF(Compute):\n    r\"\"\"Compute the scale distribution function.\n\n    Args:\n        xmax (float): Maximum *x* value at the right hand side of the rightmost\n            bin :math:`[\\mathrm{length}]`.\n        dx (float): Bin width :math:`[\\mathrm{length}]`.\n\n    `SDF` computes the proability distribution :math:`s(x)` of particles\n    overlapping as a function of separation. It estimates :math:`s(x)`\n    numerically by computing a histogram with\n    :math:`\\lfloor x_\\mathrm{max}/ \\delta x \\rfloor` bins of width `dx`\n    (:math:`\\delta x`).\n\n    See Also:\n         `Anderson 2016 <https://dx.doi.org/10.1016/j.cpc.2016.02.024>`_\n         describes the theory relating `SDF` to the system pressure.\n\n    .. rubric:: Implementation\n\n    For each pair of particles :math:`i` and :math:`j` `SDF` scales the particle\n    separation vector by the factor :math:`(1-x)` and finds the smallest\n    positive value of :math:`x` leading to an overlap of the particle shapes:\n\n    .. math::\n\n        x_{ij}(\\vec{A}) = \\min \\{ x \\in \\mathbb{R}_{> 0} :\n            \\mathrm{overlap}\\left(\n                S_i(\\mathbf{q}_i),\n                S_j(\\mathbf{q}_j, (1-x)(\\vec{r}^t_j - (\\vec{r}_i + \\vec{A})))\n            \\right) \\ne \\emptyset \\}\n\n    where :math:`\\mathrm{overlap}` is the shape overlap function defined in\n    `hoomd.hpmc.integrate`, :math:`S_i` is the shape of particle\n    :math:`i`, and :math:`\\vec{A} = h\\vec{a}_1 + k\\vec{a}_2 + l\\vec{a}_3` is a\n    vector that translates by periodic box images.\n\n    :math:`x_i` is the minimum value of :math:`x_{ij}` for a single particle:\n\n    .. math::\n\n        x_i = \\min \\{ x_{ij} : \\vec{A} \\in B_\\mathrm{images},\n                     j \\in [0,N_\\mathrm{particles}) \\}\n\n    where the set of box images includes all image vectors necessary to find\n    overlaps between particles in the primary image with particles in periodic\n    images.\n\n    `SDF` adds a single count to the histogram for each particle :math:`i`:\n\n    .. math::\n\n        s(x + \\delta x/2) = \\frac{1}{N_\\mathrm{particles} \\cdot \\delta x}\n            \\sum_{i=0}^{N_\\mathrm{particles}-1}\n            [x \\le x_i < x + \\delta x]\n\n    where the square brackets denote the Iverson bracket, and :math:`s(x +\n    \\delta x/2)` is evaluated for :math:`\\{ x \\in \\mathbb{R}, 0 \\le x <\n    x_\\mathrm{max}, x = k \\cdot \\delta x, k \\in \\mathbb{Z}^* \\}`.\n\n    .. rubric:: Pressure\n\n    The extrapolation of :math:`s(x)` to :math:`x = 0`, :math:`s(0+)` is related\n    to the pressure :math:`P`:\n\n    .. math::\n        \\beta P = \\rho \\left(1 + \\frac{s(0+)}{2d} \\right)\n\n    where :math:`d` is the dimensionality of the system, :math:`\\rho` is the\n    number density, and :math:`\\beta = \\frac{1}{kT}`. This measurement of the\n    pressure is inherently noisy due to the nature of the sampling. Average\n    `betaP` over many timesteps to obtain accurate results.\n\n    Assuming particle diameters are ~1, these paramater values typically\n    achieve good results:\n\n      * ``xmax = 0.02``\n      * ``dx = 1e-4``\n\n    In systems near densest packings, ``dx=1e-5`` may be needed along with\n    smaller ``xmax``. Check that :math:`\\sum_k s(x_k) \\cdot dx \\approx 0.5`.\n\n    Warning:\n        `SDF` does not compute correct pressures for simulations with\n        concave particles or enthalpic interactions.\n\n    Note:\n        `SDF` always runs on the CPU.\n\n    .. rubric:: Mixed precision\n\n    `SDF` uses reduced precision floating point arithmetic when checking\n    for particle overlaps in the local particle reference frame.\n\n    .. rubric:: Box images\n\n    `SDF` does not apply the minimum image convention. It supports small boxes\n    where particles may overlap with non-primary images of other particles,\n    including self overlap.\n\n    Attributes:\n        xmax (float): Maximum *x* value at the right hand side of the rightmost\n            bin :math:`[\\mathrm{length}]`.\n\n        dx (float): Bin width :math:`[\\mathrm{length}]`.\n    \"\"\"\n\n    def __init__(self, xmax, dx):\n        # store metadata\n        param_dict = ParameterDict(xmax=float(xmax), dx=float(dx))\n        self._param_dict.update(param_dict)\n\n    def _attach(self):\n        integrator = self._simulation.operations.integrator\n        if not isinstance(integrator, integrate.HPMCIntegrator):\n            raise RuntimeError(\"The integrator must be an HPMC integrator.\")\n\n        # Extract 'Shape' from '<hoomd.hpmc.integrate.Shape object>'\n        integrator_name = integrator.__class__.__name__\n\n        cpp_cls = getattr(_hpmc, 'ComputeSDF' + integrator_name)\n\n        self._cpp_obj = cpp_cls(self._simulation.state._cpp_sys_def,\n                                integrator._cpp_obj, self.xmax, self.dx)\n\n        super()._attach()\n\n    @log(category='sequence', requires_run=True)\n    def sdf(self):\n        \"\"\"(*N_bins*,) `numpy.ndarray` of `float`): :math:`s[k]` - The scale \\\n        distribution function :math:`[\\\\mathrm{probability\\\\ density}]`.\n\n        The :math:`x` at the center of bin :math:`k` is:\n        :math:`x = k \\\\cdot \\\\delta x + \\\\delta x/2`.\n\n        Attention:\n            In MPI parallel execution, the array is available on rank 0 only.\n            `sdf` is `None` on ranks >= 1.\n        \"\"\"\n        self._cpp_obj.compute(self._simulation.timestep)\n        return self._cpp_obj.sdf\n\n    @log(requires_run=True)\n    def betaP(self):  # noqa: N802 - allow function name\n        \"\"\"float: Beta times pressure in NVT simulations \\\n        :math:`\\\\left[ \\\\mathrm{length}^{-d} \\\\right]`.\n\n        Uses a polynomial curve fit of degree 5 to estimate :math:`s(0+)` and\n        computes the pressure via:\n\n        .. math::\n            \\\\beta P = \\\\rho \\\\left(1 + \\\\frac{s(0+)}{2d} \\\\right)\n\n        where :math:`d` is the dimensionality of the system, :math:`\\\\rho` is\n        the number density, and :math:`\\\\beta = \\\\frac{1}{kT}`.\n\n        Attention:\n            In MPI parallel execution, `betaP` is available on rank 0 only.\n            `betaP` is `None` on ranks >= 1.\n        \"\"\"\n        if not numpy.isnan(self.sdf).all():\n            # get the values to fit\n            n_fit = int(numpy.ceil(self.xmax / self.dx))\n            sdf_fit = self.sdf[0:n_fit]\n            # construct the x coordinates\n            x_fit = numpy.arange(0, self.xmax, self.dx)\n            x_fit += self.dx / 2\n            # perform the fit and extrapolation\n            p = numpy.polyfit(x_fit, sdf_fit, 5)\n\n            box = self._simulation.state.box\n            N = self._simulation.state.N_particles\n            rho = N / box.volume\n            return rho * (1 + numpy.polyval(p, 0.0) / (2 * box.dimensions))\n        else:\n            return None\n", "meta": {"hexsha": "2eacc6c3843b4efffd74ed363e3e68e8563d4639", "size": 12069, "ext": "py", "lang": "Python", "max_stars_repo_path": "hoomd/hpmc/compute.py", "max_stars_repo_name": "USF-GT-Molecular-Modeling/hoomd-blue", "max_stars_repo_head_hexsha": "2ba2f9e60b0320746d21aa8219bfc9df119c053f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hoomd/hpmc/compute.py", "max_issues_repo_name": "USF-GT-Molecular-Modeling/hoomd-blue", "max_issues_repo_head_hexsha": "2ba2f9e60b0320746d21aa8219bfc9df119c053f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hoomd/hpmc/compute.py", "max_forks_repo_name": "USF-GT-Molecular-Modeling/hoomd-blue", "max_forks_repo_head_hexsha": "2ba2f9e60b0320746d21aa8219bfc9df119c053f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9528301887, "max_line_length": 80, "alphanum_fraction": 0.6362581821, "include": true, "reason": "import numpy", "num_tokens": 3109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.18715414760695373}}
{"text": "import numpy as np\n\nfrom bayes_implicit_solvent.continuous_parameter_experiments.elemental_types_mh import log_prior, mols, ll, data_path, \\\n    smiles\n\nsmiles_list = smiles\nfrom bayes_implicit_solvent.typers import RADIUS_UNIT\n\nfrom bayes_implicit_solvent.freesolv import smiles_list\nfrom bayes_implicit_solvent.typers import AtomSpecificationProposal\n\nnp.random.seed(0)\n\nfrom bayes_implicit_solvent.gb_models.obc2_parameters import mbondi_model\n\ninitial_tree = mbondi_model\ninitial_tree.remove_node('[#14]') # otherwise everything is -inf, because this type will be empty\ninitial_tree.proposal_sigmas['radius'] = 1e-2 * RADIUS_UNIT\ninitial_tree.proposal_sigmas['scale_factor'] = 1e-2\n\n# add one more parameter per element appearing in FreeSolv but not specified in obc2 parameter set to initial tree\nfor i in [17, 35, 53]:\n    smirks = '[#{}]'.format(i)\n    initial_tree.add_child(smirks, '*')\n    initial_tree.un_delete_able_types.add(smirks)\n\n#specifiers = ['X1', 'X2', 'X3', 'X4', 'a', 'A']\n#atom_specification_proposal = AtomSpecificationProposal(atomic_specifiers=specifiers)\n#smirks_elaboration_proposal = atom_specification_proposal\n\n\n\nall_bond_specifiers = ['@', '-', '#', '=', ':']\nfrom bayes_implicit_solvent.smarts import atomic_number_dict\n\nall_bondable_types = list(atomic_number_dict.keys())\n\n# atomic_decorators list:\nring_specifiers = ['r0', 'r3', 'r4', 'r5', 'r6', 'r7', 'a', 'A']\ncharge_specifiers = ['-1', '+0', '+1', '+2']\nhydrogen_count_specifiers = ['H0', 'H1', 'H2', 'H3', 'H4']\nconnectivity_specifiers = ['X1', 'X2', 'X3', 'X4']\n\nall_specifier_lists = [\n    ring_specifiers,\n    charge_specifiers,\n    hydrogen_count_specifiers,\n    connectivity_specifiers,\n]\n\nfrom itertools import chain\n\n\nall_atomic_specifiers = list(chain(*all_specifier_lists))\n#all_bondable_types += ['[{}]'.format(s) for s in all_atomic_specifiers]\n#all_decorators = all_bondable_types + all_atomic_specifiers + all_bond_specifiers\n\n\nfrom bayes_implicit_solvent.typers import BondProposal, BondSpecificationProposal, AtomSpecificationProposal, SMIRKSElaborationProposal\n#bond_proposal = BondProposal(bondable_types=all_bondable_types)\natom_specification_proposal = AtomSpecificationProposal(atomic_specifiers=all_atomic_specifiers)\n#bond_specification_proposal = BondSpecificationProposal(bond_specifiers=all_bond_specifiers)\n\nsmirks_elaborators = [\n    #bond_proposal,\n    atom_specification_proposal,\n    #bond_specification_proposal,\n]\nsmirks_elaboration_proposal = SMIRKSElaborationProposal(smirks_elaborators=smirks_elaborators)\n\nprint('initial tree:')\nprint(initial_tree)\n\nn_configuration_samples = 5\n\nimport os\n\nname = 'tree_rjmc_n_config={}_{}_ll'.format(n_configuration_samples, ll)\nsmiles_subset_fname = os.path.join(data_path,\n                                   'smiles_subset_{}.txt'.format(name))\nwith open(smiles_subset_fname, 'w') as f:\n    f.writelines(['{}\\n'.format(s) for s in smiles_list])\n\nfrom bayes_implicit_solvent.prior_checking import check_no_empty_types\n\nerror_y_trees = []\n\nfor mol in mols:\n    thinning = int(len(mol.vacuum_traj) / n_configuration_samples)\n    mol.vacuum_traj = mol.vacuum_traj[::thinning]\n\n\ndef log_prob(tree):\n    log_prior_value = check_no_empty_types(tree)\n\n    theta = np.hstack([tree.get_radii(), tree.get_scale_factors()])\n\n    log_prior_value += log_prior(theta)\n\n    if log_prior_value > -np.inf:\n        try:\n            # TODO: Parallelize. Note that multiprocessing.Pool won't work here because it doesn't play nice with SwigPy objects\n            # TODO: update to allow scale factors to be variable also\n            log_likelihood_value = 0\n            for mol in mols:\n                radii = tree.assign_radii(mol.mol) / RADIUS_UNIT\n                scale_factors = tree.assign_scale_factors(mol.mol)\n\n                log_likelihood_value += mol.log_prob(radii, scale_factors)\n        except:\n            global error_y_trees\n            error_y_trees.append(tree)\n            print('Warning! Encountered un-anticipated exception!')\n            return - np.inf\n        return log_prior_value + log_likelihood_value\n    else:\n        return log_prior_value\n\n\nfrom bayes_implicit_solvent.samplers import tree_rjmc\nfrom pickle import dump\n\nn_iterations = 10000\n\nresult = tree_rjmc(initial_tree, log_prob, smirks_elaboration_proposal, n_iterations=n_iterations,\n                   fraction_cross_model_proposals=0.1)\nwith open('elaborate_tree_rjmc_run_n_compounds={}_n_iter={}_gaussian_ll.pkl'.format(len(mols), n_iterations),\n          'wb') as f:\n    dump(result, f)\n\nwith open('error_y_trees.pkl', 'wb') as f:\n    dump(error_y_trees, f)\n", "meta": {"hexsha": "3d13e250cc3d97f87b400dfbe70254d0356e26a0", "size": 4597, "ext": "py", "lang": "Python", "max_stars_repo_path": "bayes_implicit_solvent/rjmc_experiments/tree_rjmc.py", "max_stars_repo_name": "openforcefield/bayes-implicit-solvent", "max_stars_repo_head_hexsha": "067239fcbb8af28eb6310d702804887662692ec2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-11-12T16:23:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:37:37.000Z", "max_issues_repo_path": "bayes_implicit_solvent/rjmc_experiments/tree_rjmc.py", "max_issues_repo_name": "openforcefield/bayes-implicit-solvent", "max_issues_repo_head_hexsha": "067239fcbb8af28eb6310d702804887662692ec2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-01-18T22:05:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-12T18:37:31.000Z", "max_forks_repo_path": "bayes_implicit_solvent/rjmc_experiments/tree_rjmc.py", "max_forks_repo_name": "openforcefield/bayes-implicit-solvent", "max_forks_repo_head_hexsha": "067239fcbb8af28eb6310d702804887662692ec2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-12-02T20:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-25T23:28:36.000Z", "avg_line_length": 34.5639097744, "max_line_length": 135, "alphanum_fraction": 0.7428757886, "include": true, "reason": "import numpy", "num_tokens": 1193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.18715414220356966}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n'''\n--------------------------------------------------------------------------------\nVaccines Manufacturing Model\n--------------------------------------------------------------------------------\nBryden Wood\nLicense: MIT, see full license in LICENSE.txt\n--------------------------------------------------------------------------------\nDate: 2020-11-20\nAuthors:\n    Jiabin Li\n    Wynne Lim\n    Stamatios Stamatiadis\n    David Reader\n--------------------------------------------------------------------------------\nThe purpose of the manufacturing model is to identify plausible scenarios\nfor how long it will take to manufacture vaccines to treat the populations\nin need, and is split into two parts: Manufacturing Preparation, predicting\nwhen primary (drug substance) and secondary (drug product) manufacturing\ncould start; and Manufacturing Capacity, predicting when enough doses are\nmade to meet the needs of the target populations. The model uses output from\nthe Research and Development model, expert input and interviews, literature\nand manufacturing capacity survey data as inputs. The model uses Monte Carlo\ntechniques to derive the dates at which the vaccine production targets will\nbe met and should therefore be run many times to smooth statistical\nfluctuations.\n--------------------------------------------------------------------------------\nDeveloped for compatibility with Python 3.7.\n\nThis model functions as an importable module to R&D Vaccine Predictions model\n('R&D model').\n\nThe model uses the following libraries from the default Python installation:\n    random\n    datetime\n    json\n    copy\n\nThe model uses the following additional libraries:\n    numpy\n    scipy\n    pandas\n--------------------------------------------------------------------------------\n'''\n\n# Module imports\nimport pandas as pd\nimport numpy as np\nimport random\nimport datetime\nimport json\nimport copy\n\n\n# --------------------------------------------------------------------------------\n\ndef initialise(params, vaccines, manufacturing):\n    '''\n    This function creates and populates a set of global dataframes which can\n    then be accessed from other functions. External data is loaded from JSON\n    files.\n\n    Parameters\n    ----------\n    None\n\n    Returns\n    ----------\n    None\n    '''\n\n    # manufacturing model initialisation.\n\n    global primary_cap\n    global ratio_pri_v\n    global ratio_pri_d\n    global plants_categories\n\n    global secondary_cap\n    global ratio_sec\n    global sec_plants_available\n\n    global df_Categories\n    global df_product\n\n    global default\n    global m_params\n\n    global funding\n    global demand\n    global targetDoses\n\n    global output_summary\n    global cumulative_summary\n    global df_schedule\n\n    global ramp_up\n\n    # load offline default data and online parameters\n    default = jread(manufacturing)\n    m_params = params\n    ramp_up = params['ramp_up']\n\n    primary_cap, ratio_pri_v, ratio_pri_d = getPrimaryInput()\n\n    # initialise the product info\n    df_Categories = default['Capacity Category']\n    df_product = getProduct(vaccines)\n\n    # get the number of primary plants available for each category\n    plants_categories = [6, 9, 6, 0, 6]\n\n    # initialise the schedule input\n    df_schedule, funding = getScheduleInput()\n\n    # initialise the secondary input\n    secondary_cap, ratio_sec, sec_plants_available = getSecondaryInput()\n\n    # initialise the demand data\n    demand = m_params['Doses needed']\n    targets = [\"Group 1\", \"Group 2\", \"Group 3\", \"Group 4\"]\n    wastage = demand['Percentage of drug wastage']\n    dose_perVx = demand['Number of doses per vaccine']\n    # set the target numbers\n    targetDoses = [(demand[x] / (1 - wastage / 100)) * dose_perVx for x in targets]\n    targetDoses = np.cumsum(targetDoses)\n\n    # define global variables\n    output_summary = pd.DataFrame()\n    cumulative_summary = pd.DataFrame()\n\n\n# --------------------------------------------------------------------------------\n\ndef getSecondaryInput():\n    '''\n    This function extracts the relevant information pertaining to 'secondary'\n    from the dictionaries: 'default' and 'm_params' and\n    stores them as a separate dictionary 'secDefaultCap' and 'parameter' respectively\n\n    Parameters\n    ----------\n    None\n\n    Returns\n    ----------\n    secDefaultCap: a dictionary that stores the default secondary capacity of each country.\n\n    ratio_sec: an array of ratio for low, most likely, high.\n\n    sec_plants_available: a value for the number of secondary plants available for each category\n    '''\n\n    # secDefaultCap refers to the offline input table with the default (highest available) capacity for each country\n    secDefaultCap = default['Sec Capacity']\n    parameter = m_params['Sec Input']\n\n    # get the ratio for low, most likely, high\n    parameter_default = 4268.328666666668  # this is the value that is the original value we calculated\n\n    cols = [name + ' Available Capacity (million doses/month)' for name in ['Lowest', 'Most Likely', 'Highest']]\n    ratio_sec = [parameter[col] / parameter_default for col in cols]\n\n    # get the number of secondary plants available for each category\n    sec_plants_available = 0\n    for key, value in secDefaultCap.items():\n        if (value > 0): sec_plants_available += 1\n\n    return secDefaultCap, ratio_sec, sec_plants_available\n\n\n# --------------------------------------------------------------------------------\n\ndef getIteration(df_rnd):\n    '''\n    Takes the output from the R&D model and creates the iteration data required\n    for the manufacturing functions. This includes joining with vaccine data in\n    the database and restricting the number of successful vaccines in each\n    category based on the model assumptions.\n\n    Parameters\n    ----------\n    df_rnd: a dataframe of successful vaccines from the R&D model for the\n        current iteration\n\n    Returns\n    ----------\n    df_iteration: a dataframe of the successful vaccines with data processed\n        for use in the manufacturing model\n    '''\n    global mfg_at_risk\n\n    # generate iteration table\n    tryID = df_rnd['try']\n    v = df_rnd['vaccines']\n    df = pd.DataFrame(v, columns=['Vaccine', 'phase1_start', 'phase1_end', 'phase2_start', 'phase2_end', 'Phase III',\n                                  'phase3_end', 'approval_start', 'Approval (month)'])\n    df['try'] = tryID\n\n    # filter the vaccines being approved\n    df_rnd = df[df['Approval (month)'] != '']\n    df_rnd.reset_index(drop=True, inplace=True)\n\n    # find platform and category\n    df_iteration = df_rnd\n    df_iteration = pd.merge(df_iteration, df_product, on='Vaccine', how='left')\n\n    # get product manufacturing at risk info\n    df_iteration_copy = df_iteration.copy()\n    df_iteration_copy['Mfg before approval'] = df_iteration_copy['Funding'].apply(\n        lambda x: funding[x]['Manufacturing start before approval?'])\n    mfg_at_risk = df_iteration_copy[['Phase III', 'Mfg before approval', 'Approval (month)']].to_dict('records')\n    mfg_at_risk = dict(zip(df_rnd['Vaccine'], mfg_at_risk))\n\n    df_iteration.drop(\n        ['phase1_start', 'phase1_end', 'phase2_start', 'phase2_end', 'Phase III', 'phase3_end', 'approval_start'],\n        axis=1, inplace=True)\n\n    platforms = np.array(df_iteration['Platform'])\n    categories = []\n\n    # get capacity category info\n    for i in df_iteration.index.values:\n        categories.append(df_Categories[platforms[i]])\n\n    df_iteration['Category'] = categories\n\n    # Keep the first 3 of vaccine in the same category\n    df_iteration = df_iteration.sort_values(by=['Approval (month)'])\n    df_iteration = df_iteration.groupby('Category').head(3)\n    df_iteration.reset_index(drop=True, inplace=True)\n\n    # rearrange the table\n    # df_iteration = df_iteration[['try',]]\n\n    return df_iteration\n\n\n# --------------------------------------------------------------------------------\n\ndef getProduct(vaccines):\n    '''\n    This function loads the vaccine database, selects the columns that are\n    required (number, name and platform) and stores them in a dataframe.\n\n    Parameters\n    ----------\n    None\n\n    Returns\n    ----------\n    df_product: filtered vaccine table containing only essential columns\n    '''\n\n    # filter the vaccine data\n    data = vaccines\n    df_product = pd.DataFrame(columns=['Vaccine', 'Platform', 'Funding'])\n\n    vaccines = []\n    platforms = []\n    funding = []\n\n    for i in range(len(data)):\n        vaccines.append(data[i]['number'])\n        platforms.append(data[i]['platform'])\n        funding.append(data[i]['funding_category'])\n\n    df_product['Vaccine'] = vaccines\n    df_product['Vaccine'] = df_product['Vaccine'].astype(int)\n    df_product['Platform'] = platforms\n    df_product['Funding'] = funding\n\n    return df_product\n\n\n# --------------------------------------------------------------------------------\n\ndef getManufacturingStartTime(df_iteration):\n    '''\n    Gets the manufacturing start time based on the current iteration parameters\n    and the required manufacturing preparation timeline using the getSchedule\n    function.\n\n    Parameters\n    ----------\n    df_iteration: a dataframe of the successful vaccines with data processed\n        for use in the manufacturing model\n\n    Returns\n    ----------\n    None\n    '''\n\n    platforms = np.array(df_iteration['Platform'])\n    approval_months = np.array(df_iteration['Approval (month)'])\n    funding = np.array(df_iteration['Funding'])\n    pri_starts = np.zeros(len(df_iteration))\n    sec_starts = np.zeros(len(df_iteration))\n\n    # get primary and secondary start time from scheduling (getSchedule) function\n    for i in df_iteration.index.values:\n        t = getSchedule(platforms[i], approval_months[i], funding[i])\n        pri_starts[i] = t[0]\n        sec_starts[i] = t[1]\n\n    df_iteration['Primary Start'] = pri_starts\n    df_iteration['Secondary Start'] = sec_starts\n    df_iteration['Primary available'] = 0\n    df_iteration['Primary assigned'] = 0\n\n    df_iteration.drop(['Funding'], axis=1, inplace=True)\n\n\n# --------------------------------------------------------------------------------\ndef getPrimaryInput():\n    '''\n    This function extracts the relevant information pertaining to 'primary'\n    from the dictionaries: 'default' and 'm_params' and\n    stores them as a separate dictionary 'primary_Cap' and 'parameter' respectively\n\n    Parameters\n    ----------\n    None\n\n    Returns\n    ----------\n    primary_cap: a dictionary that stores the default primary capacity of each country\n                for each of the platform\n\n    ratio_pri_v: a dictionary containing the ratios for the lowest, most likely and highest volume\n                that is used to convert default value to online value\n\n    ratio_pri_d: a dictionary containing the ratio for the number of doses (million doses per month)\n                that is used to convert default value to online value\n\n    '''\n\n    # primary_cap refers to the offline input table with the default primary capacity for each country\n    primary_cap = default['Pri Capacity']\n\n    # parameter is the input table for primary capacity - from online platform\n    parameter = m_params['Pri Input']\n\n    # dfPrimary['1'], dfPrimary['2'], dfPrimary['3'], dfPrimary['4'], dfPrimary['5'] = 0, 0, 0, 0, 0\n\n    platforms = ['DNA', 'Inactivated', 'Live-attenuated', 'Non-replicating viral vector', 'Replicating viral vector',\n                 'Protein subunit', 'Other', 'RNA']\n    platform_cat = ['DNA', 'Protein subunit', 'Inactivated', 'RNA']\n\n    # dv -> default volume  dd -> default doses\n    parameter_dv = [268, 1113, 779, 167728]\n    parameter_dd = [112, 6488, 6488, 11596, 11596, 5798, 6355, 280]\n\n    # ratio -> used to convert default value to online value\n    ratio_pri_v = {}\n    ratio_pri_d = {}\n    cols = [name + ' Volume V (m3)' for name in ['Lowest', 'Most Likely', 'Highest']]\n\n    for p in platform_cat:\n        ratio_pri_v[p] = [parameter[p][col] / parameter_dv[platform_cat.index(p)] for col in cols]\n\n    for p in platforms:\n        ratio_pri_d[p] = parameter[p]['Doses for most likely volume (Million Doses per month) N_v'] / parameter_dd[\n            platforms.index(p)]\n\n    return primary_cap, ratio_pri_v, ratio_pri_d\n\n\n# --------------------------------------------------------------------------------\ndef primary(df_iteration):\n    '''\n    Takes the current iteration data and allocates primary production capacity\n    to each vaccine candidate based on the model assumptions.\n\n    Parameters\n    ----------\n    df_iteration: a dataframe of the successful vaccines with data processed\n        for use in the manufacturing model\n\n    Returns\n    ----------\n    df_priAllocation: a dataframe of primary capacity allocations for the\n        successful vaccines\n    '''\n\n    # sort the iteration table based on the primary start time\n    df_iteration = df_iteration.sort_values(by=['Primary Start']).reset_index()\n\n    # get capacity available for each category\n    platform_cat = ['DNA', 'Protein subunit', 'Inactivated', 'RNA']\n    category_list = [1, 2, 3, 5]\n\n    platforms_bycat = {\n        '1': ['DNA'],\n        '2': ['Non-replicating viral vector', 'Replicating viral vector', 'Protein subunit', 'Other'],\n        '3': ['Inactivated', 'Live-attenuated'],\n        '5': ['RNA']\n    }\n    sorted_cap = {}\n\n    primary_cap_copy = copy.deepcopy(primary_cap)\n\n    for i in category_list:\n        category_cap = primary_cap_copy[str(i)]\n        example_p = platform_cat[category_list.index(i)]\n        for p in platforms_bycat[str(i)]:\n            ratio_cat = random.triangular(ratio_pri_v[example_p][0], ratio_pri_v[example_p][2],\n                                          ratio_pri_v[example_p][1])\n            for key, value in category_cap.items():\n                category_cap[key][p] = category_cap[key][p] * ratio_cat\n\n        platform_r = platforms_bycat[str(i)][0]\n\n        sorted_temp = sorted(category_cap.items(), key=lambda x: x[1][platform_r], reverse=True)\n\n        sorted_cap[str(i)] = sorted_temp\n\n    # primary info initialisation\n\n    # calculate the number of plants available per vaccine\n    vx_categories = [df_iteration[df_iteration['Category'] == i].index.size for i in range(1, 6)]\n\n    # assign no. of plants available to each vaccine product\n    pri_plants_available = plants_categories[:]\n\n    # Initialise arrays\n    iter_categories = np.array(df_iteration['Category'])\n    iter_pri_avail = np.array(df_iteration['Primary available'])\n    iter_try = np.array(df_iteration['try'])\n    iter_vaccines = np.array(df_iteration['Vaccine'])\n    iter_platforms = np.array(df_iteration['Platform'])\n    iter_pri_starts = np.array(df_iteration['Primary Start'])\n    iter_pri_assigned = np.array(df_iteration['Primary assigned'])\n\n    for i in range(len(df_iteration)):\n        category = iter_categories[i] - 1\n\n        if vx_categories[category] > 1:\n            p = round(pri_plants_available[category] / vx_categories[category])\n            iter_pri_avail[i] = p if p <= 3 else 3  # one vaccine can be assigned to maximum 3 plants\n        else:\n            p = pri_plants_available[category]\n            iter_pri_avail[i] = p if p <= 3 else 3\n        pri_plants_available[category] -= p if p <= 3 else 3\n        vx_categories[category] -= 1\n\n    df_iteration['Primary available'] = iter_pri_avail\n\n    ### Primary product allocation\n    df_priAllocation = pd.DataFrame(columns=['try', 'Country', 'Vaccine', 'Platform', 'Primary Start', 'Capacity'])\n\n    prialloc_try = []\n    prialloc_countries = []\n    prialloc_vaccines = []\n    prialloc_platforms = []\n    prialloc_pri_starts = []\n    prialloc_capacities = []\n\n    for i in range(len(df_iteration)):\n        while iter_pri_assigned[i] < iter_pri_avail[i]:\n            iter_pri_assigned[i] += 1\n            category = str(iter_categories[i])\n            platform = iter_platforms[i]\n            sorted_primary = sorted_cap[category]\n            for country in sorted_primary:\n                if country[1][platform] > 0:\n                    prialloc_try.append(iter_try[i])\n                    prialloc_countries.append(country[0])\n                    prialloc_vaccines.append(iter_vaccines[i])\n                    prialloc_platforms.append(iter_platforms[i])\n                    prialloc_pri_starts.append(iter_pri_starts[i])\n                    prialloc_capacities.append(country[1][platform] / 1000 * ratio_pri_d[platform])\n                    sorted_primary.remove(country)\n                    break\n\n    df_priAllocation['try'] = prialloc_try\n    df_priAllocation['Country'] = prialloc_countries\n    df_priAllocation['Vaccine'] = prialloc_vaccines\n    df_priAllocation['Platform'] = prialloc_platforms\n    df_priAllocation['Primary Start'] = prialloc_pri_starts\n    df_priAllocation['Capacity'] = prialloc_capacities\n\n    return df_priAllocation\n\n\n# --------------------------------------------------------------------------------\n\ndef secondary(df_iteration, df_priAllocation):\n    '''\n    Takes the current iteration data and allocates secondary production capacity\n    to each vaccine candidate based on the model assumptions.\n\n    Parameters\n    ----------\n    df_iteration: a dataframe of the successful vaccines with data processed\n        for use in the manufacturing model\n    df_priAllocation: a dataframe of primary capacity allocations for the\n        successful vaccines\n\n    Returns\n    ----------\n    df_secCumProduction: a dataframe of secondary capacity allocations for the\n        successful vaccines, and cumulative dose count each month\n    '''\n\n    # sort the iteration table based on the secondary start time\n    df_iteration = df_iteration.sort_values(by=['Secondary Start']).reset_index(drop=True)\n\n    # get the number of plants available\n    sec_plantsC = sec_plants_available\n    secondary_copy = copy.deepcopy(secondary_cap)\n\n    # get random secondary capacity for each country based on a triangular distribution based on low,most likely,high value\n    ratios = random.triangular(ratio_sec[0], ratio_sec[2], ratio_sec[1])\n    for key, value in secondary_copy.items():\n        secondary_copy[key] = secondary_copy[key] * ratios\n\n    # sort the secondary plants by capacity\n    sort_secondary = sorted(secondary_copy.items(), key=lambda x: x[1], reverse=True)\n\n    # get the no. of plants available for each vaccine\n    v_count = df_iteration.index.size\n    df_iteration['Secondary available'] = 0\n    df_iteration['Secondary assigned'] = 0\n\n    # Initialise arrays\n    iter_sec_avail = np.zeros(len(df_iteration))\n    iter_sec_assigned = np.zeros(len(df_iteration))\n    iter_try = np.array(df_iteration['try'])\n    iter_vaccines = np.array(df_iteration['Vaccine'])\n    iter_platforms = np.array(df_iteration['Platform'])\n    iter_sec_starts = np.array(df_iteration['Secondary Start'])\n\n    for i in range(len(df_iteration)):\n        if v_count > 1:\n            p = round(sec_plantsC / v_count)\n            iter_sec_avail[i] = p if p <= 3 else 3  # one vaccine can be assigned to maximum 3 plants\n        else:\n            p = sec_plantsC\n            iter_sec_avail[i] = p if p <= 3 else 3  # one vaccine can be assigned to maximum 3 plants\n        v_count -= 1\n        sec_plantsC -= p\n\n    df_iteration['Secondary available'] = iter_sec_avail\n\n    ### secondary product allocation\n\n    # initialisation\n    df_secAllocation = pd.DataFrame(columns=['try', 'Country', 'Vaccine', 'Platform', 'Secondary Start', 'Capacity'])\n    df_iteration['Secondary assigned'] = 0\n\n    iter_sec_assigned = np.array(df_iteration['Secondary assigned'])\n\n    secalloc_try = []\n    secalloc_countries = []\n    secalloc_vaccines = []\n    secalloc_platforms = []\n    secalloc_sec_starts = []\n    secalloc_capacities = []\n\n    # assign plants to vaccines\n    for i in range(len(df_iteration)):\n        while iter_sec_assigned[i] < iter_sec_avail[i]:\n            iter_sec_assigned[i] += 1\n            for country in sort_secondary:\n                if country[1] > 0:\n                    secalloc_try.append(iter_try[i])\n                    secalloc_countries.append(country[0])\n                    secalloc_vaccines.append(iter_vaccines[i])\n                    secalloc_platforms.append(iter_platforms[i])\n                    secalloc_sec_starts.append(iter_sec_starts[i])\n                    secalloc_capacities.append(country[1] / 1000)\n                    sort_secondary.remove(country)\n                    break\n\n    df_secAllocation['try'] = secalloc_try\n    df_secAllocation['Country'] = secalloc_countries\n    df_secAllocation['Vaccine'] = secalloc_vaccines\n    df_secAllocation['Platform'] = secalloc_platforms\n    df_secAllocation['Secondary Start'] = secalloc_sec_starts\n    df_secAllocation['Capacity'] = secalloc_capacities\n\n    # check whether primary or secondary is the bottle neck\n    df_priThroughput = df_priAllocation.groupby('Vaccine')['Capacity'].sum()\n    df_secThroughput = df_secAllocation.groupby('Vaccine')['Capacity'].sum()\n\n    for i in range(len(df_secAllocation)):\n        vx_ID = secalloc_vaccines[i]\n        if df_secThroughput[vx_ID] > df_priThroughput[vx_ID]:\n            df_secAllocation.loc[i, 'Capacity'] *= (df_priThroughput[vx_ID] / df_secThroughput[vx_ID])\n\n    # get secondary throughput table\n    df_secThroughput = df_secAllocation.copy()\n    capacity_arr = np.array(df_secThroughput['Capacity'])\n    start_arr = np.array(df_secThroughput['Secondary Start'])\n\n    duration = ramp_up['duration']\n    pre_approval = ramp_up['pre_approval']\n\n    cum_arr = np.cumsum(np.linspace(0, 1, duration + 1))\n\n    monthly_throughput = {}\n    for j in range(1, 101):\n        col_month = []\n        for i in range(len(df_secThroughput)):\n            vx_ID = secalloc_vaccines[i]\n            phase3 = mfg_at_risk[vx_ID]['Phase III']\n            mfg_before_approval = mfg_at_risk[vx_ID]['Mfg before approval']\n            approv_month = mfg_at_risk[vx_ID]['Approval (month)']\n\n            if phase3 > start_arr[i]:  # secondary -> phase 3 -> approval\n                # calculate the cumulative initial dose\n                if mfg_before_approval == 1 and j > phase3:\n                    if j >= approv_month:\n                        initial_doses = pre_approval * (approv_month - phase3)\n                    else:\n                        initial_doses = 0\n                else:\n                    initial_doses = 0\n\n                # calculate the cumulative ramp up doses\n                if j > approv_month:  # after ramp up\n                    if j - approv_month >= duration:\n                        cum_factor = (j - (approv_month + duration - 1)) + cum_arr[duration - 1] + initial_doses\n                    else:  # in the ramp up period\n                        cum_factor = cum_arr[int(j - approv_month)] + initial_doses\n                    capacity_month = cum_factor * capacity_arr[i]\n\n                else:\n                    capacity_month = initial_doses * capacity_arr[i]\n\n            else:\n                if approv_month > start_arr[i]:  # phase 3 - > secondary - > approval\n                    # calculate the cumulative initial dose\n                    if mfg_before_approval == 1 and j > start_arr[i]:\n                        if j >= approv_month:\n                            initial_doses = pre_approval * (approv_month - start_arr[i])\n                        else:\n                            initial_doses = 0\n                    else:\n                        initial_doses = 0\n\n                    # calculate the cumulative ramp up doses\n                    if j > approv_month:  # after ramp up\n                        if j - approv_month >= duration:\n                            cum_factor = (j - (approv_month + duration - 1)) + cum_arr[duration - 1] + initial_doses\n                        else:  # in the ramp up period\n                            cum_factor = cum_arr[int(j - approv_month)] + initial_doses\n                        capacity_month = cum_factor * capacity_arr[i]\n\n                    else:\n                        capacity_month = initial_doses * capacity_arr[i]\n\n                else:  # phase 3 - > approval - > secondary\n                    # calculate the cumulative initial dose\n                    initial_doses = 0\n\n                    # calculate the cumulative ramp up doses\n                    if j > start_arr[i]:  # after ramp up\n                        if j - start_arr[i] >= duration:\n                            cum_factor = (j - (start_arr[i] + duration - 1)) + cum_arr[duration - 1] + initial_doses\n                        else:  # in the ramp up period\n                            cum_factor = cum_arr[int(j - start_arr[i])] + initial_doses\n                        capacity_month = cum_factor * capacity_arr[i]\n\n                    else:\n                        capacity_month = initial_doses * capacity_arr[i]\n\n            col_month.append(capacity_month)\n\n        monthly_throughput[j] = col_month\n\n    df_monthly = pd.DataFrame(monthly_throughput)\n    df_secThroughput = pd.concat([df_secThroughput, df_monthly], axis=1)\n\n    # get cumulative production for secondary\n    df_secCumProduction = df_secThroughput.copy()\n\n    return df_secCumProduction\n\n\n# --------------------------------------------------------------------------------\n\ndef getSchedule(platform, approval_month, funding_cat):\n    '''\n    Calculates the critical path for a vaccine's manufacturing preparation\n    schedule, and returns the months that primary and secondary manufacturing\n    can start.\n\n    Parameters\n    ----------\n    platform: the vaccine's platform\n    approval_month: the month that the vaccine reached approval from R&D\n\n    Returns\n    ----------\n    m_month: the months that primary and secondary manufacturing can start\n    '''\n\n    # get the gantt table\n    df_gantt = df_schedule[platform].copy()\n\n    funding_ratio = funding[funding_cat]['Gantt duration factor*']\n    # update the dependencies based on the funding category\n\n    if funding[funding_cat]['Simultaneous tech transfer?'] == 1:  # Simultaneous Tech Transfer\n        df_gantt.loc['12', 'Predecessor'] = '0'\n        df_gantt.loc['22', 'Predecessor'] = '21'\n    else:\n        pass\n\n    if funding[funding_cat]['Manufacturing start before approval?'] == 1:  # Manufacturing before approval\n        df_gantt.loc['17', 'Predecessor'] = '17'\n        df_gantt.loc['27', 'Predecessor'] = '25,27'\n    else:\n        pass\n\n    # Remove rows not in use\n    df_gantt['Predecessor'] = df_gantt['Predecessor'].astype(str)\n\n    # get time for each activity\n    df_gantt['Time (days)'] = df_gantt[['Type', 'Value', 'Low', 'Most Likely', 'High']].apply(getValue, axis=1)\n\n    # apply gantt duration factor\n    df_gantt['Time (days)'] = df_gantt['Time (days)'] * funding_ratio\n\n    # Initialise columns\n    df_gantt['end_date'] = datetime.date(2020, 3, 1)\n    df_gantt['start_date'] = datetime.date(2020, 3, 1)\n\n    # Calculate end time\n\n    predecessors = np.array(df_gantt['Predecessor'])\n    start_dates = np.array(df_gantt['start_date'])\n    end_dates = np.array(df_gantt['end_date'])\n    time_days = np.array(df_gantt['Time (days)'])\n\n    df_gantt = df_gantt[df_gantt['Predecessor'] != '-1']\n\n    for i in df_gantt.index.values.astype(int):\n        # assign start date\n        if predecessors[i] != '0':\n\n            if str(predecessors[i]).find(',') == -1:\n\n                pTask_index = int(df_gantt.index[df_gantt['Task ID'] == int(predecessors[i])][0])\n                start_dates[i] = end_dates[pTask_index]\n\n            else:\n                temp_list = []\n                for p in predecessors[i].split(','):\n                    pTask_index = int(df_gantt.index[df_gantt['Task ID'] == int(p)][0])\n                    temp_list.append(end_dates[pTask_index])\n                start_dates[i] = max(temp_list)\n\n            # assign end date\n            if i == 5:  ## assign vaccine approval time\n\n                date_today = datetime.date.today()\n                mon = (date_today.month + approval_month) % 12\n\n                # Assign the year and month\n                if mon != 0:  # not the month of Dec\n                    year = date_today.year + int((date_today.month + approval_month) / 12)\n                    newmon = mon\n                    nodaysinapprmonth = (datetime.date(year, newmon + 1, 1) - datetime.date(year, newmon, 1)).days\n\n                else:  # mon=0 means that the approved month is 12\n                    year = (date_today.year + int((date_today.month + approval_month) / 12)) - 1\n                    newmon = 12\n                    nodaysinapprmonth = (datetime.date(year + 1, 1, 1) - datetime.date(year, 12, 1)).days\n\n                # Assign the date\n                if date_today.day <= nodaysinapprmonth:\n                    target_date = datetime.date(year, newmon, date_today.day)\n\n                else:\n                    target_date = datetime.date(year, newmon, nodaysinapprmonth)\n\n                end_dates[i] = target_date\n            else:\n                end_dates[i] = start_dates[i] + datetime.timedelta(days=time_days[i])\n\n        else:\n            end_dates[i] = start_dates[i] + datetime.timedelta(days=time_days[i])\n\n    m_month = []\n\n    date_today = datetime.date.today()\n\n    comm_prod_index = int(df_gantt[df_gantt['Activities'] == 'Start commercial production'].index.values[0])\n    dp_prod_index = int(df_gantt[df_gantt['Activities'] == 'Start DP production'].index.values[0])\n\n    m_time = [end_dates[i] for i in [comm_prod_index, dp_prod_index]]\n\n    for t in m_time:\n        m_month.append((t.year - date_today.year) * 12 + t.month - date_today.month)\n\n    # apply a minimum 3 months' gap\n    if m_month[0] + 3 > m_month[1]: m_month[1] = m_month[0] + 3\n\n    return m_month\n\n\n# --------------------------------------------------------------------------------\n\n\n# --------------------------------------------------------------------------------\n\ndef jread(filename):\n    '''\n    Reads JSON files and returns the values.\n\n    Parameters\n    ----------\n    filename: filename of JSON file to load\n\n    Returns\n    ----------\n    values: data from the JSON file\n    '''\n\n    f = open(filename)\n    values = json.load(f)\n    f.close()\n\n    return values\n\n\n# --------------------------------------------------------------------------------\n\ndef getValue(values):\n    '''\n    Returns a single time value for an activity of the schedule based on the\n    type of distribution specified.\n\n    Parameters\n    ----------\n    df_schedule: dataframe of the schedule activity data\n    i: row index\n    x: value or distribution type\n\n    Returns\n    ----------\n    computed value in days\n    '''\n    #### Get distribution\n    return {\n        'Static': values[1],\n        'Triangular': random.triangular(values[2], values[4], values[3])\n    }[values[0]]\n\n\n# --------------------------------------------------------------------------------\n\ndef getTarget(df_iteration, df_secCumProduction):\n    '''\n    Finds the months at which the vaccine dose targets are hit.\n\n    Parameters\n    ----------\n    df_iteration: a dataframe of the successful vaccines with data processed\n        for use in the manufacturing model\n    df_secCumProduction: text\n\n    Returns\n    ----------\n    targetMonth: array of months when each dose target was hit\n    df: vaccines for the current iteration, months the target was hit,\n    '''\n    targetDoses_copy = targetDoses.copy()\n    targetMonth = [0, 0, 0, 0]\n    # find the target month\n    for i in range(1, 101):\n        total = df_secCumProduction[i].sum()\n        for t in range(4):\n            if total > targetDoses_copy[t] and targetMonth[t] == 0:\n                targetMonth[t] = i\n                targetDoses_copy[t] = total\n    df = df_iteration.iloc[:, :7]\n    df['Target1 (month)'] = targetMonth[0]\n    df['Target2 (month)'] = targetMonth[1]\n    df['Target3 (month)'] = targetMonth[2]\n    df['Target4 (month)'] = targetMonth[3]\n\n    vaccine_list = df['Vaccine']\n    target_dose = {}\n    for k in range(4):\n        t = []\n        for j in range(len(df)):\n            if targetMonth[k] > 0:\n                t.append(\n                    df_secCumProduction.loc[df_secCumProduction['Vaccine'] == vaccine_list[j], targetMonth[k]].sum())\n            else:\n                t.append(0)\n        target_dose['Target' + str(k + 1) + ' (bn doses)'] = t\n\n    df_target = pd.DataFrame(target_dose)\n    df_target = pd.concat([df, df_target], axis=1)\n\n    return targetMonth, df_target\n\n\n# --------------------------------------------------------------------------------\n\ndef timeline(df):\n    '''\n    Creates the data required for the timeline bar chart.\n\n    Parameters\n    ----------\n    df: dataframe of output summary data from the manufacturing model\n\n    Returns\n    ----------\n    df: dataframe containing data for the timeline chart\n    '''\n    if df.empty:\n        df = pd.DataFrame(index=['None'],\n                          columns=['Approval (month)', 'Platform', 'Primary start time', 'Secondary start time'],\n                          data=0)\n    else:\n        df = df.copy()\n        df = df.iloc[:, 0:7]  # pull out columns A to F from dataframe\n        df['Primary start time'] = df['Primary Start'].sub(df['Approval (month)']).astype(int)\n        df['Secondary start time'] = df['Secondary Start'].sub(df['Primary Start']).astype(int)\n        df['Approval (month)'] = df['Approval (month)'].astype(int)\n\n        df = df.drop(columns=['try', 'Vaccine', 'Category', 'Primary Start', 'Secondary Start'])\n\n        df = df.groupby(['Platform']).mean().apply(np.ceil).astype(int)\n\n    return df\n\n\n# --------------------------------------------------------------------------------\n\ndef doseBreakdown(df):\n    '''\n    Creates the data for the dose breakdown pie charts.\n\n    Parameters\n    ----------\n    df: dataframe of output summary data from the manufacturing model\n\n    Returns\n    ----------\n    target1_pie: table of data to create the pie chart for dose target 1\n    target2_pie: table of data to create the pie chart for dose target 2\n    target3_pie: table of data to create the pie chart for dose target 3\n    target4_pie: table of data to create the pie chart for dose target 4\n    '''\n    #### Get dose breakdown\n    if df.empty:\n        target1_pie = pd.DataFrame(index=['None'], columns=['Target1 (bn doses)', 'Target 1 %'], data=0)\n        target2_pie = pd.DataFrame(index=['None'], columns=['Target2 (bn doses)', 'Target 2 %'], data=0)\n        target3_pie = pd.DataFrame(index=['None'], columns=['Target3 (bn doses)', 'Target 3 %'], data=0)\n        target4_pie = pd.DataFrame(index=['None'], columns=['Target4 (bn doses)', 'Target 4 %'], data=0)\n    else:\n        df_copy = df.copy()\n\n        # Create a dataframe for each Target where 0 values have been filtered out\n        df_doses = [df_copy[df_copy['Target' + str(i) + ' (bn doses)'] != 0][\n                        ['try', 'Platform', 'Target' + str(i) + ' (bn doses)']].reset_index(drop=True) for i in\n                    range(1, 5)]\n\n        # Calculate number of tries for each Target above\n        tries = [i['try'].nunique() for i in df_doses]\n\n        # Calculate average\n        df_grouped = [(df_doses[k].groupby(['Platform'])['Target' + str(k + 1) + ' (bn doses)'].sum()) / tries[k] for k\n                      in range(len(df_doses))]\n\n        target1, target2, target3, target4 = [i for i in df_grouped]\n\n        # Calculate the % of each Target\n        target1_percent, target2_percent, target3_percent, target4_percent = [df_grouped[i] / df_grouped[i].sum() * 100\n                                                                              for i in range(len(df_grouped))]\n\n        df = df.groupby(['Platform'])[\n                 ['Target1 (bn doses)', 'Target2 (bn doses)', 'Target3 (bn doses)', 'Target4 (bn doses)']].sum() / df[\n                 'try'].nunique()\n\n        target1_pie = pd.DataFrame(data={'Target1 (bn doses)': target1, 'Target 1 %': target1_percent})\n        target2_pie = pd.DataFrame(data={'Target2 (bn doses)': target2, 'Target 2 %': target2_percent})\n        target3_pie = pd.DataFrame(data={'Target3 (bn doses)': target3, 'Target 3 %': target3_percent})\n        target4_pie = pd.DataFrame(data={'Target4 (bn doses)': target4, 'Target 4 %': target4_percent})\n\n    return target1_pie, target2_pie, target3_pie, target4_pie\n\n\n# --------------------------------------------------------------------------------\n\ndef getHistogram(target_no, df):\n    '''\n    Creates the data for the histogram chart.\n\n    Parameters\n    ----------\n    target_no: vaccine dose target to generate the histogram for\n    df: dataframe of output summary data from the manufacturing model\n\n    Returns\n    ----------\n    return1: text\n    '''\n    #### Get histogram\n    if df.empty:\n        target = pd.DataFrame(np.array([[0, 0, 0.9, 0.75, 0.5]]), index=['None'],\n                              columns=['Number of Runs', 'Cumulative %', '90%', '75%', '50%'])\n    else:\n        df = df.copy()\n        # count the number of tries reach target n on a particular month\n        target = pd.DataFrame(df.groupby('Target' + str(target_no) + ' (month)')['try'].nunique())\n\n        # remove failed tries (month 0)\n        if target.index[0] == 0:\n            target.drop(0, inplace=True)\n\n        # calculate the cumulative sum\n        target['Cumulative %'] = np.cumsum(target.loc[:, 'try'] / sum(target['try']))\n\n        # add referening line\n        target['90%'], target['75%'], target['50%'] = (0.9, 0.75, 0.5)\n\n        # rename the column\n        target.rename(index=str, columns={\"try\": \"Number of Runs\"}, inplace=True)\n\n    return target\n\n\n# --------------------------------------------------------------------------------\n\ndef cumulativeProduction(target4_hist, cumulative_summary):\n    '''\n    Creates the data required for the cumulative production chart.\n\n    Parameters\n    ----------\n    target4_hist: histogram data for the fourth vaccine dose target\n    cumulative_summary: cumulative summary of the dose production\n\n    Returns\n    ----------\n    df_cumulative: dataframe containing data for the cumulative chart\n    '''\n    #### Get cumulative production\n    if cumulative_summary.empty:\n        df_cumulative = pd.DataFrame(index=['None'], columns=['Month', '10%', '25%', '50%', '75%', '90%', 'Target 4'],\n                                     data=0)\n        df_cumulative['Target 4'] = targetDoses[3]\n    else:\n        df_hist = target4_hist.copy()\n\n        percentage = (0.1, 0.25, 0.5, 0.75, 0.9)\n        month = []\n\n        for i in percentage:\n            df = df_hist[df_hist['Cumulative %'] > i]\n            month.append(int(df.index[0]))\n\n        target4 = targetDoses[3]\n        df = cumulative_summary.copy()\n\n        # Define list with column names to sum()\n        lst = [i for i in range(1, 101)]\n\n        df = df.groupby(['try'])[lst].sum()\n\n        df_cumulative = pd.DataFrame()  # reset the dataframe\n\n        for i in month:\n            if i > 0:\n                df1 = df[(df[i - 1] < target4) & (df[i] > target4)].head(1).T\n            else:\n                df1 = df[df[100] == 0].head(1).T\n            df_cumulative = pd.concat([df_cumulative, df1], axis=1)\n\n        df_cumulative['Target 4'] = targetDoses[3]\n        df_cumulative.reset_index(inplace=True)\n\n        df_cumulative.columns = ['Month', '10%', '25%', '50%', '75%', '90%', 'Target 4']\n\n    return df_cumulative\n\n\n# --------------------------------------------------------------------------------\n\ndef getOutput():\n    '''\n    Processes the output data from the manufacturing model by calling\n    functions for each individual charts required.\n\n    Parameters\n    ----------\n    None\n\n    Returns:\n    ----------\n    timeline_bar: table of data to create the timeline bar chart\n\n    target1_pie: table of data to create the pie chart for dose target 1\n    target2_pie: table of data to create the pie chart for dose target 2\n    target3_pie: table of data to create the pie chart for dose target 3\n    target4_pie: table of data to create the pie chart for dose target 4\n\n    target1_hist: table of data to create the histogram for dose target 1\n    target2_hist: table of data to create the histogram for dose target 2\n    target3_hist: table of data to create the histogram for dose target 3\n    target4_hist: table of data to create the histogram for dose target 4\n\n    cum_line: table of data to create the cumulative % line chart.\n    '''\n\n    # get the timeline table\n    timeline_bar = timeline(output_summary)\n\n    # get the pie chart tables\n    target1_pie, target2_pie, target3_pie, target4_pie = doseBreakdown(output_summary)\n\n    # get the histogram tables\n    target1_hist = getHistogram(1, output_summary)\n    target2_hist = getHistogram(2, output_summary)\n    target3_hist = getHistogram(3, output_summary)\n    target4_hist = getHistogram(4, output_summary)\n\n    # get the trendline table and highlights if targets have been met\n    if target1_hist.index[0] == 'None':\n        cum_line = {'Month': {'None': 0}, '10%': {'None': 0}, '25%': {'None': 0}, '50%': {'None': 0},\n                    '75%': {'None': 0}, '90%': {'None': 0}}\n        highlights = [0, 0, 0, 0]\n    else:\n        cum_line = cumulativeProduction(target4_hist, cumulative_summary).to_dict()\n        targets_list = [target1_hist, target2_hist, target3_hist, target4_hist]\n        highlights = [int(i.index[i['Cumulative %'] >= 0.5][0]) for i in targets_list]\n\n    return timeline_bar.to_dict(), target1_pie.to_dict(), target2_pie.to_dict(), target3_pie.to_dict(), target4_pie.to_dict() \\\n        , target1_hist.to_dict(), target2_hist.to_dict(), target3_hist.to_dict(), target4_hist.to_dict(), cum_line, highlights\n\n\n# --------------------------------------------------------------------------------\n\ndef runTrial(trialData):\n    '''\n    This function takes the trial output from the R&D model and runs the main\n    functions of the manufacturing model.\n\n    Parameters\n    ----------\n    trialData: iteration trial data from the R&D model\n\n    Returns\n    ----------\n    None\n    '''\n\n    global output_summary\n    global cumulative_summary\n\n    if bool(trialData):\n        ## get the iteration table for this try\n        df_iteration = getIteration(trialData)\n        ## append the primary and secondary manufacturing start time to the iteration table\n        getManufacturingStartTime(df_iteration)\n\n        ## get the primary allocation and throughput\n        df_priAllocation = primary(df_iteration)\n\n        ## get the secondary allocation and throughput, as well as cumulative total\n        df_secCumProduction = secondary(df_iteration, df_priAllocation, )\n\n        ## get the output for this try\n        targetMonth, output_mfg = getTarget(df_iteration, df_secCumProduction)\n\n        # merge the output table\n        output_summary = output_summary.append(output_mfg, ignore_index=True)\n        cumulative_summary = cumulative_summary.append(df_secCumProduction, ignore_index=True)\n\n\n# --------------------------------------------------------------------------------\ndef getScheduleInput():\n    '''\n    Modifies the default Gantt chart to create a Gantt chart for each platform.\n\n    Parameters\n    ----------\n    None\n\n    Returns:\n    ----------\n    df_schedule:\n\n    funding: a dictionary containing relevant information for each funding type\n    '''\n\n    # the tables below are used for value updating (static, low, most likely, high)\n    gantt = pd.DataFrame(default.get('Generic Gantt')).transpose()\n    parameter_v = default.get('Gantt Timelines (default)')\n    parameter = m_params.get('Gantt Timelines')\n\n    # the dictionary below is based on funding category\n    funding = m_params.get('Timelines by funding criteria')\n\n    ##############################################################################\n    # Update the values of other activities to the default gantt, once only\n    ranges = ['Low', 'Most Likely', 'High']\n\n    # apply changes to all platforms\n    low_d, most_likely_d, high_d = [parameter_v['All Platform'][x] for x in ranges]\n    low, most_likely, high = [parameter['All Platform'][x] for x in ranges]\n\n    low_r = low / low_d\n    most_likely_r = most_likely / most_likely_d\n    high_r = high / high_d\n\n    # Convert numerical values into integers\n    gantt[['Value', 'Low', 'Most Likely', 'High']] = gantt[['Value', 'Low', 'Most Likely', 'High']].astype(int)\n\n    mask = (gantt['Activities'] != 'Scale up and and process development') & (\n            gantt['Activities'] != 'Technology transfer') & (\n                   gantt['Activities'] != 'DP technology transfer')\n\n    gantt.loc[mask, 'Value'] = round(most_likely_r * gantt.loc[mask, 'Value'], 0).astype(int)\n    gantt.loc[mask, 'Low'] = round(low_r * gantt.loc[mask, 'Low'], 0).astype(int)\n    gantt.loc[mask, 'Most Likely'] = round(most_likely_r * gantt.loc[mask, 'Most Likely'], 0).astype(int)\n    gantt.loc[mask, 'High'] = round(high_r * gantt.loc[mask, 'High'], 0).astype(int)\n\n    gantt_updated = gantt\n\n    del parameter['All Platform']\n    ##############################################################################\n\n    # get the iteration table for different platforms\n    platforms = parameter.keys()\n\n    # gerenate the gantt for different platform\n    df_schedule = {}\n\n    for i in platforms:\n        gantt_updated_copy = gantt_updated.copy()\n        low_d, most_likely_d, high_d = [parameter_v[i][x] for x in ranges]\n        low, most_likely, high = [parameter[i][x] for x in ranges]\n\n        low_r = low / low_d\n        most_likely_r = most_likely / most_likely_d\n        high_r = high / high_d\n\n        mask = (gantt_updated_copy['Activities'] == 'Scale up and and process development') | (\n                gantt_updated_copy['Activities'] == 'Technology transfer') | (\n                       gantt_updated_copy['Activities'] == 'DP technology transfer')\n\n        gantt_updated_copy.loc[mask, 'Low'] = round(low_r * gantt_updated_copy.loc[mask, 'Low'], 0).astype(int)\n        gantt_updated_copy.loc[mask, 'Most Likely'] = round(most_likely_r * gantt_updated_copy.loc[mask, 'Most Likely'],\n                                                            0).astype(int)\n        gantt_updated_copy.loc[mask, 'High'] = round(high_r * gantt_updated_copy.loc[mask, 'High'], 0).astype(int)\n\n        df_schedule[i] = gantt_updated_copy\n\n    return df_schedule, funding\n\n############################################################################## \n", "meta": {"hexsha": "fe982ab6291779a96664cc717f58e9afe9de5748", "size": 46332, "ext": "py", "lang": "Python", "max_stars_repo_path": "manufacturing.py", "max_stars_repo_name": "sllloyd/vaccine_predictions", "max_stars_repo_head_hexsha": "502877cf3ab78f6c3d4bbd7e5af57423bb06e9da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-15T06:40:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-21T17:15:16.000Z", "max_issues_repo_path": "manufacturing.py", "max_issues_repo_name": "sllloyd/vaccine_predictions", "max_issues_repo_head_hexsha": "502877cf3ab78f6c3d4bbd7e5af57423bb06e9da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-20T09:59:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-20T14:14:28.000Z", "max_forks_repo_path": "manufacturing.py", "max_forks_repo_name": "sllloyd/vaccine_predictions", "max_forks_repo_head_hexsha": "502877cf3ab78f6c3d4bbd7e5af57423bb06e9da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-01-07T13:48:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T17:15:26.000Z", "avg_line_length": 36.6840855107, "max_line_length": 127, "alphanum_fraction": 0.602046102, "include": true, "reason": "import numpy", "num_tokens": 10461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.18709288071878988}}
{"text": "# Copyright (C) 2021 Sarah Roggendorf and Jørgen S. Dokken\n#\n# SPDX-License-Identifier:    MIT\n\nfrom typing import Dict, Tuple\n\nimport basix\nimport dolfinx_cuas\nimport numpy as np\nimport ufl\nfrom dolfinx import common as _common\nfrom dolfinx import fem as _fem\nfrom dolfinx import log as _log\nfrom dolfinx import mesh as dmesh\nfrom dolfinx.graph import create_adjacencylist\nfrom petsc4py import PETSc as _PETSc\nfrom dolfinx.cpp.mesh import MeshTags_int32\nimport dolfinx_contact\nimport dolfinx_contact.cpp\nfrom dolfinx_contact.helpers import (epsilon, lame_parameters,\n                                     rigid_motions_nullspace, sigma_func)\n\n__all__ = [\"nitsche_custom\"]\n\n\ndef nitsche_custom(mesh: dmesh.Mesh, mesh_data: Tuple[MeshTags_int32, int, int],\n                   physical_parameters: dict = {}, nitsche_parameters: Dict[str, float] = {},\n                   plane_loc: float = 0.0, vertical_displacement: float = -0.1,\n                   nitsche_bc: bool = True, quadrature_degree: int = 5, form_compiler_params: Dict = {},\n                   jit_params: Dict = {}, petsc_options: Dict = {}, newton_options: Dict = {}) -> _fem.Function:\n    \"\"\"\n    Use custom kernel to compute the one sided contact problem with a mesh coming into contact\n    with a rigid surface (not meshed).\n\n    Parameters\n    ==========\n    mesh\n        The input mesh\n    mesh_data\n        A triplet with a mesh tag for facets and values v0, v1. v0 should be the value in the mesh tags\n        for facets to apply a Dirichlet condition on. v1 is the value for facets which should have applied\n        a contact condition on\n    physical_parameters\n        Optional dictionary with information about the linear elasticity problem.\n        Valid (key, value) tuples are: ('E': float), ('nu', float), ('strain', bool)\n    nitsche_parameters\n        Optional dictionary with information about the Nitsche configuration.\n        Valid (keu, value) tuples are: ('gamma', float), ('theta', float) where theta can be -1, 0 or 1 for\n        skew-symmetric, penalty like or symmetric enforcement of Nitsche conditions\n    plane_loc\n        The location of the plane in y-coordinate (2D) and z-coordinate (3D)\n    vertical_displacement\n        The amount of verticial displacment enforced on Dirichlet boundary\n    nitsche_bc\n        Use Nitche's method to enforce Dirichlet boundary conditions\n    quadrature_degree\n        The quadrature degree to use for the custom contact kernels\n    form_compiler_params\n        Parameters used in FFCX compilation of this form. Run `ffcx --help` at\n        the commandline to see all available options. Takes priority over all\n        other parameter values, except for `scalar_type` which is determined by\n        DOLFINX.\n    jit_params\n        Parameters used in CFFI JIT compilation of C code generated by FFCX.\n        See https://github.com/FEniCS/dolfinx/blob/main/python/dolfinx/jit.py\n        for all available parameters. Takes priority over all other parameter values.\n    petsc_options\n        Parameters that is passed to the linear algebra backend\n        PETSc. For available choices for the 'petsc_options' kwarg,\n        see the `PETSc-documentation\n        <https://petsc4py.readthedocs.io/en/stable/manual/ksp/>`\n    newton_options\n        Dictionary with Newton-solver options. Valid (key, item) tuples are:\n        (\"atol\", float), (\"rtol\", float), (\"convergence_criterion\", \"str\"),\n        (\"max_it\", int), (\"error_on_nonconvergence\", bool), (\"relaxation_parameter\", float)\n    \"\"\"\n    # Compute lame parameters\n    plane_strain = physical_parameters.get(\"strain\", False)\n    E = physical_parameters.get(\"E\", 1e3)\n    nu = physical_parameters.get(\"nu\", 0.1)\n    mu_func, lambda_func = lame_parameters(plane_strain)\n    mu = mu_func(E, nu)\n    lmbda = lambda_func(E, nu)\n    sigma = sigma_func(mu, lmbda)\n\n    # Nitche parameters and variables\n    theta = nitsche_parameters.get(\"theta\", 1)\n    gamma = nitsche_parameters.get(\"gamma\", 1)\n\n    # Unpack mesh data\n    (facet_marker, dirichlet_value, contact_value) = mesh_data\n    assert(facet_marker.dim == mesh.topology.dim - 1)\n\n    # Outward unit normal of plane\n    n_vec = np.zeros(mesh.geometry.dim)\n    n_vec[mesh.geometry.dim - 1] = 1\n\n    # Setup function space and functions used in Jacobian and residual formulation\n    V = _fem.VectorFunctionSpace(mesh, (\"CG\", 1))\n    u = _fem.Function(V)\n    v = ufl.TestFunction(V)\n    du = ufl.TrialFunction(V)\n    u = _fem.Function(V)\n    v = ufl.TestFunction(V)\n\n    # Compute classical (volume) contributions of the equations of linear elasticity\n    dx = ufl.Measure(\"dx\", domain=mesh)\n    J = ufl.inner(sigma(du), epsilon(v)) * dx\n    F = ufl.inner(sigma(u), epsilon(v)) * dx\n\n    # Nitsche for Dirichlet\n    # https://doi.org/10.1016/j.cma.2018.05.024\n    if nitsche_bc:\n        ds = ufl.Measure(\"ds\", domain=mesh, subdomain_data=facet_marker)\n        h = ufl.Circumradius(mesh)\n        n = ufl.FacetNormal(mesh)\n        disp_vec = np.zeros(mesh.geometry.dim)\n        disp_vec[mesh.geometry.dim - 1] = vertical_displacement\n        u_D = ufl.as_vector(disp_vec)\n        F += - ufl.inner(sigma(u) * n, v) * ds(dirichlet_value)\\\n             - theta * ufl.inner(sigma(v) * n, u - u_D) * \\\n            ds(dirichlet_value) + E * gamma / h * ufl.inner(u - u_D, v) * ds(dirichlet_value)\n        J += - ufl.inner(sigma(du) * n, v) * ds(dirichlet_value)\\\n            - theta * ufl.inner(sigma(v) * n, du) * \\\n            ds(dirichlet_value) + E * gamma / h * ufl.inner(du, v) * ds(dirichlet_value)\n    else:\n        raise RuntimeError(\"Dirichlet bc not implemented in custom assemblers yet.\")\n\n    # Custom assembly of contact boundary condition\n    q_rule = dolfinx_contact.QuadratureRule(mesh.topology.cell_type, quadrature_degree,\n                                            mesh.topology.dim - 1, basix.QuadratureType.Default)\n    consts = np.array([E * gamma, theta])\n    consts = np.hstack((consts, n_vec))\n\n    # Compute coefficients for mu and lambda as DG-0 functions\n    V2 = _fem.FunctionSpace(mesh, (\"DG\", 0))\n    lmbda2 = _fem.Function(V2)\n    lmbda2.interpolate(lambda x: np.full((1, x.shape[1]), lmbda))\n    mu2 = _fem.Function(V2)\n    mu2.interpolate(lambda x: np.full((1, x.shape[1]), mu))\n\n    # Compute integral entities on exterior facets (cell_index, local_index)\n    bottom_facets = facet_marker.indices[facet_marker.values == contact_value]\n    integral = _fem.IntegralType.exterior_facet\n    integral_entities = dolfinx_contact.compute_active_entities(mesh, bottom_facets, integral)\n    # Pack mu and lambda on facets\n    coeffs = dolfinx_cuas.pack_coefficients([mu2, lmbda2], integral_entities)\n    # Pack circumradius of facets\n    h_facets = dolfinx_contact.pack_circumradius(mesh, integral_entities)\n\n    # Create contact class\n    data = np.array([contact_value, dirichlet_value], dtype=np.int32)\n    offsets = np.array([0, 2], dtype=np.int32)\n    surfaces = create_adjacencylist(data, offsets)\n    contact = dolfinx_contact.cpp.Contact([facet_marker], surfaces, [(0, 1)],\n                                          V._cpp_object, quadrature_degree=quadrature_degree)\n    # Compute gap from contact boundary\n    g_vec = contact.pack_gap_plane(0, -plane_loc)\n\n    # Concatenate coefficients\n    coeffs = np.hstack([coeffs, h_facets, g_vec])\n\n    # Create RHS kernels\n    L_custom = _fem.form(F, jit_params=jit_params, form_compiler_params=form_compiler_params)\n    kernel_rhs = dolfinx_contact.cpp.generate_contact_kernel(V._cpp_object, dolfinx_contact.Kernel.Rhs, q_rule,\n                                                             [u._cpp_object, mu2._cpp_object, lmbda2._cpp_object])\n\n    def create_b():\n        return _fem.petsc.create_vector(L_custom)\n\n    def assemble_residual(x, b):\n        u.vector[:] = x.array\n        u_packed = dolfinx_cuas.pack_coefficients([u._cpp_object], integral_entities)\n        c = np.hstack([u_packed, coeffs])\n        contact.assemble_vector(b, 0, kernel_rhs, c, consts)\n        _fem.petsc.assemble_vector(b, L_custom)\n\n    # Create Jacobian kernels\n    a_custom = _fem.form(J, jit_params=jit_params, form_compiler_params=form_compiler_params)\n    kernel_J = dolfinx_contact.cpp.generate_contact_kernel(\n        V._cpp_object, dolfinx_contact.Kernel.Jac, q_rule, [u._cpp_object, mu2._cpp_object, lmbda2._cpp_object])\n\n    def create_A():\n        return _fem.petsc.create_matrix(a_custom)\n\n    def assemble_jacobian(x, A):\n        u.vector[:] = x.array\n        u_packed = dolfinx_cuas.pack_coefficients([u._cpp_object], integral_entities)\n        c = np.hstack([u_packed, coeffs])\n        contact.assemble_matrix(A, [], 0, kernel_J, c, consts)\n        _fem.petsc.assemble_matrix(A, a_custom)\n\n    # Setup non-linear problem and Newton-solver\n    problem = dolfinx_cuas.NonlinearProblemCUAS(assemble_residual, assemble_jacobian, create_b, create_A)\n    solver = dolfinx_cuas.NewtonSolver(mesh.comm, problem)\n\n    # Create rigid motion null-space\n    null_space = rigid_motions_nullspace(V)\n    solver.A.setNearNullSpace(null_space)\n\n    # Set Newton solver options\n    solver.atol = newton_options.get(\"atol\", 1e-9)\n    solver.rtol = newton_options.get(\"rtol\", 1e-9)\n    solver.convergence_criterion = newton_options.get(\"convergence_criterion\", \"incremental\")\n    solver.max_it = newton_options.get(\"max_it\", 50)\n    solver.error_on_nonconvergence = newton_options.get(\"error_on_nonconvergence\", True)\n    solver.relaxation_parameter = newton_options.get(\"relaxation_parameter\", 1.0)\n\n    def _u_initial(x):\n        values = np.zeros((mesh.geometry.dim, x.shape[1]))\n        values[-1] = -0.01 - plane_loc\n        return values\n\n    # Set initial_condition:\n    u.interpolate(_u_initial)\n\n    # Define solver and options\n    ksp = solver.krylov_solver\n    option_prefix = ksp.getOptionsPrefix()\n\n    # Set PETSc options\n    opts = _PETSc.Options()\n    opts.prefixPush(option_prefix)\n    for k, v in petsc_options.items():\n        opts[k] = v\n    opts.prefixPop()\n    ksp.setFromOptions()\n\n    dofs_global = V.dofmap.index_map_bs * V.dofmap.index_map.size_global\n    _log.set_log_level(_log.LogLevel.INFO)\n\n    # Solve non-linear problem\n    with _common.Timer(f\"{dofs_global} Solve Nitsche\"):\n        n, converged = solver.solve(u)\n    u.x.scatter_forward()\n\n    if solver.error_on_nonconvergence:\n        assert(converged)\n    print(f\"{dofs_global}, Number of interations: {n:d}\")\n\n    return u\n", "meta": {"hexsha": "e17477fdda257af4c243a0624892f6418af01c93", "size": 10393, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/dolfinx_contact/one_sided/nitsche_custom.py", "max_stars_repo_name": "jorgensd/asimov-contact", "max_stars_repo_head_hexsha": "08704ade6343c346bc54dfd38186983cc7ab4485", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/dolfinx_contact/one_sided/nitsche_custom.py", "max_issues_repo_name": "jorgensd/asimov-contact", "max_issues_repo_head_hexsha": "08704ade6343c346bc54dfd38186983cc7ab4485", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/dolfinx_contact/one_sided/nitsche_custom.py", "max_forks_repo_name": "jorgensd/asimov-contact", "max_forks_repo_head_hexsha": "08704ade6343c346bc54dfd38186983cc7ab4485", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9462809917, "max_line_length": 114, "alphanum_fraction": 0.6837294333, "include": true, "reason": "import numpy", "num_tokens": 2707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3040416875789103, "lm_q1q2_score": 0.1870123496003978}}
{"text": "\"\"\"\nThe classes in this file do preprocessing on data and monte carlo to be used\nto do a point source analysis.\n\"\"\"\n\n__author__ = 'John Evans'\n__copyright__ = 'Copyright 2020 John Evans'\n__credits__ = ['John Evans', 'Jason Fan', 'Michael Larson']\n__license__ = 'Apache License 2.0'\n__version__ = '0.0.1'\n__maintainer__ = 'John Evans'\n__email__ = 'john.evans@icecube.wisc.edu'\n__status__ = 'Development'\n\nfrom typing import Optional, Tuple, Union\nimport numpy as np\nimport numpy.lib.recfunctions as rf\nfrom scipy.interpolate import UnivariateSpline as Spline\n\nfrom dataclasses import dataclass\nfrom dataclasses import field\nfrom dataclasses import InitVar\n\nfrom .. import sources\nfrom .. import _models\nfrom . import spectral\n\n\n@dataclass\nclass _ThreeMLEventModelBase(_models.EventModelBase):\n    \"\"\"Docstring\"\"\"\n    _sin_dec_bins: np.array = field(init=False)\n    _log_energy_bins: np.array = field(init=False)\n    _edge_point: Tuple[float, float] = field(init=False)\n    _background_sob_map: np.ndarray = field(init=False)\n    _ratio: np.ndarray = field(init=False)\n    _reduced_sim_reconstructed: np.ndarray = field(init=False)\n\n\n@dataclass\nclass _ThreeMLEventModelDefaultsBase(_models.TdEventModelDefaultsBase):\n    \"\"\"Docstring\"\"\"\n    signal_sin_dec_bins: InitVar[Union[np.array, int]] = field(default=50)\n    log_energy_bins: InitVar[Union[np.array, int]] = field(default=50)\n    _spectrum: spectral.BaseSpectrum = field(\n        default=spectral.PowerLaw(1e3, 1e-14, -2))\n\n\n@dataclass\nclass ThreeMLEventModel(\n    _models.TdEventModel,\n    _ThreeMLEventModelDefaultsBase,\n    _ThreeMLEventModelBase,\n):\n    \"\"\"Docstring\"\"\"\n    def __post_init__(\n        self,\n        source: sources.Source,\n        data: np.ndarray,\n        sim: np.ndarray,\n        grl: np.ndarray,\n        gamma: float,\n        sampling_width: Optional[float],\n        background_sin_dec_bins: Union[np.array, int],\n        background_window: float,\n        withinwindow: bool,\n        signal_sin_dec_bins: Union[np.array, int],\n        log_energy_bins: Union[np.array, int],\n    ) -> None:\n        \"\"\"\n        Args:\n            source:\n            grl:\n            background_sin_dec_bins: If an int, then the number of bins\n                spanning -1 -> 1, otherwise, a numpy array of bin edges.\n            background_window:\n            withinwindow:\n        \"\"\"\n        super().__post_init__(\n            source,\n            data,\n            sim,\n            grl,\n            gamma,\n            sampling_width,\n            background_sin_dec_bins,\n            background_window,\n            withinwindow,\n        )\n        if isinstance(signal_sin_dec_bins, int):\n            signal_sin_dec_bins = np.linspace(-1, 1, 1 + signal_sin_dec_bins)\n        self._sin_dec_bins = signal_sin_dec_bins\n\n        if isinstance(log_energy_bins, int):\n            log_energy_bins = np.linspace(1, 8, 1 + log_energy_bins)\n\n        self._log_energy_bins = log_energy_bins\n        self._background_sob_map = self._init_background_sob_map()\n        self._init_reduced_sim_reconstructed(source)\n        self._ratio = self._init_sob_ratio()\n\n    def _init_background_sob_map(self) -> None:\n        \"\"\"Create the backgroub SOB map\n        \"\"\"\n        # background\n        bins = np.array([self._sin_dec_bins, self._log_energy_bins])\n        bg_h, _, _ = np.histogram2d(self._data['sindec'], self._data['logE'],\n                                    bins=bins, density=True)\n        with np.errstate(divide='ignore', invalid='ignore'):\n            bg_h /= np.sum(bg_h, axis=1)[:, None]\n        return bg_h\n\n    def _init_sob_ratio(self, *args, **kwargs) -> None:\n        \"\"\"Create the SOB map with a spectrum\n        \"\"\"\n        bins = np.array([self._sin_dec_bins, self._log_energy_bins])\n        bin_centers = bins[1, :-1] + np.diff(bins[1]) / 2\n        sig_w = self._reduced_sim_reconstructed['ow'] * self._spectrum(\n            self._reduced_sim_reconstructed['trueE'])\n        sig_h, _, _ = np.histogram2d(self._reduced_sim_reconstructed['sindec'],\n                                     self._reduced_sim_reconstructed['logE'],\n                                     bins=bins, weights=sig_w, density=True)\n\n        # Normalize histograms by dec band\n        with np.errstate(divide='ignore', invalid='ignore'):  # divide warnings\n            sig_h /= np.sum(sig_h, axis=1)[:, None]\n\n        if 'k' not in kwargs:\n            kwargs['k'] = 1\n        if 's' not in kwargs:\n            kwargs['s'] = 0\n        if 'ext' not in kwargs:\n            kwargs['ext'] = 3\n\n        with np.errstate(divide='ignore', invalid='ignore'):  # divide warnings\n            ratio = sig_h / self._background_sob_map\n\n        with np.errstate(divide='ignore', invalid='ignore'):  # divide warnings\n            for i in range(ratio.shape[0]):\n                # Pick out the values we want to use.\n                # We explicitly want to avoid NaNs and infinities\n                values = ratio[i]\n                good = np.isfinite(values) & (values > 0)\n                x_good, y_good = bin_centers[good], values[good]\n\n                # Do a linear interpolation across the energy range\n                if len(x_good) > 1:\n                    spline = Spline(x_good, y_good, *args, **kwargs)\n                    ratio[i] = spline(bin_centers)\n                elif len(x_good) == 1:\n                    ratio[i] = y_good\n                else:\n                    ratio[i] = 0\n        return ratio\n\n    def _init_reduced_sim_reconstructed(self, source: sources.Source) -> None:\n        \"\"\"Gets a small simulation dataset to use for injecting signal.\n\n        Prunes the simulation set to only events close to a given source and\n        calculate the weight for each event. Adds the weights as a new column\n        to the simulation set.\n\n        Args:\n            source:\n\n        Returns:\n            A reweighted simulation set around the source declination.\n        \"\"\"\n        if self._sampling_width is not None:\n            self._cut_sim_reconstructed(source)\n        else:\n            self._reduced_sim_reconstructed = self._sim\n\n    def _cut_sim_reconstructed(self, source: sources.Source) -> np.ndarray:\n        \"\"\"Select simulation events in a reconstruction dec band\n\n        Args:\n            source:\n        \"\"\"\n        if self._sampling_width is not None:\n            self._edge_point = (np.searchsorted(\n                                self._sin_dec_bins,\n                                np.sin(source.dec - self._sampling_width)) - 1,\n                                np.searchsorted(\n                                self._sin_dec_bins,\n                                np.sin(source.dec + self._sampling_width)) - 1)\n        else:\n            self._edge_point = (self._sin_dec_bins[0], self._sin_dec_bins[-1])\n        sindec_dist = np.abs(source.dec - self._sim['dec'])\n        close = sindec_dist < self._sampling_width\n        self._reduced_sim_reconstructed = self._sim[close].copy()\n\n    def _weight_reduced_sim(self, reduced_sim: np.ndarray) -> np.ndarray:\n        \"\"\"Docstring\"\"\"\n        try:\n            reduced_sim = rf.append_fields(reduced_sim, 'weight',\n                                           np.zeros(len(reduced_sim)),\n                                           dtypes=np.float32)\n\n        except ValueError:  # weight already exist\n            pass\n\n        # Assign the weights using the newly defined \"time profile\"\n        # classes above. If you want to make this a more complicated\n        # shape, talk to me and we can work it out.\n        reduced_sim['weight'] = reduced_sim['ow'] * self._spectrum(\n            reduced_sim['trueE'])\n        return reduced_sim\n\n    def reweight_reduced_sim(self, spectrum: spectral.BaseSpectrum):\n        \"\"\"Docstring\"\"\"\n        self._reduced_sim['weight'] = self._reduced_sim['ow'] * spectrum(\n            self._reduced_sim['trueE'])\n\n    def prepro_index(self, events: np.ndarray) -> np.ndarray:\n        \"\"\"Find the sindec index and energy index for events\n\n        More function info...\n\n        Args:\n            events: An array of events including their positional data.\n\n        Returns:\n            A list of index\n        \"\"\"\n        # Get the bin that each event belongs to\n        try:\n            sin_dec_idx = np.searchsorted(self._sin_dec_bins[:-1],\n                                          events['sindec']) - 1\n        except ValueError:\n            sin_dec_idx = np.searchsorted(self._sin_dec_bins[:-1],\n                                          np.sin(events['dec'])) - 1\n\n        log_energy_idx = np.searchsorted(self._log_energy_bins[:-1],\n                                         events['logE']) - 1\n\n        sin_dec_idx[sin_dec_idx < self._edge_point[0]] = self._edge_point[0]\n        # If events fall outside the sampling width, just gonna approxiamte the\n        # weight using the nearest non-zero sinDec bin.\n        sin_dec_idx[sin_dec_idx > self._edge_point[1]] = self._edge_point[1]\n        return sin_dec_idx, log_energy_idx\n\n    def _energy_sob(\n        self,\n        sin_dec_idx: np.ndarray,\n        log_energy_idx: np.ndarray\n    ) -> np.ndarray:\n        \"\"\"Gets the sob vs. gamma required for each event and specific .\n\n        More function info...\n\n        Args:\n            sin_dec_idx: An array of sin dec index of events\n            log_energy_idx: An array of log energy index of events\n\n        Returns:\n            signal-over-background for each event.\n        \"\"\"\n        return self._ratio[sin_dec_idx, log_energy_idx]\n\n    def get_ns(self, livetime: float) -> float:\n        \"\"\"Gets expected number of neutrino\n\n        More function info...\n\n        Args:\n            livetime: livetime\n\n        Returns:\n            expected number of neutrino\n        \"\"\"\n        ns = (\n            self._spectrum(self._reduced_sim['trueE'])\n            * self._reduced_sim['ow']\n            * livetime\n        ).sum()\n        return ns\n\n    def get_sob_energy(\n        self,\n        sin_dec_idx: np.ndarray,\n        log_energy_idx: np.ndarray,\n    ) -> np.ndarray:\n        \"\"\"Docstring\"\"\"\n        return self._energy_sob(sin_dec_idx, log_energy_idx)\n\n    @property\n    def edge_point(self) -> Tuple[float, float]:\n        \"\"\"Docstring\"\"\"\n        return self._edge_point\n\n    @property\n    def spectrum(self) -> spectral.BaseSpectrum:\n        \"\"\"Docstring\"\"\"\n        return self._spectrum\n\n    @spectrum.setter\n    def spectrum(self, spectrum: spectral.BaseSpectrum):\n        \"\"\"Docstring\"\"\"\n        self._spectrum = spectrum\n", "meta": {"hexsha": "68fda742060a5292bbb82ca61c2fdea23168c949", "size": 10471, "ext": "py", "lang": "Python", "max_stars_repo_path": "mla/threeml/models.py", "max_stars_repo_name": "thejevans/mla", "max_stars_repo_head_hexsha": "0c583741cfc7626b0653bf58f4efaa1e7681424c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-20T15:47:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-20T15:47:00.000Z", "max_issues_repo_path": "mla/threeml/models.py", "max_issues_repo_name": "thejevans/mla", "max_issues_repo_head_hexsha": "0c583741cfc7626b0653bf58f4efaa1e7681424c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-27T02:23:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T20:14:24.000Z", "max_forks_repo_path": "mla/threeml/models.py", "max_forks_repo_name": "thejevans/mla", "max_forks_repo_head_hexsha": "0c583741cfc7626b0653bf58f4efaa1e7681424c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7873754153, "max_line_length": 79, "alphanum_fraction": 0.5905835164, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3040416686603661, "lm_q1q2_score": 0.18701233796383102}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2019 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#\n\n'''\nCISD analytical nuclear gradients\n'''\n\nimport numpy\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf.ci import cisd\nfrom pyscf.grad import rhf as rhf_grad\nfrom pyscf.grad import ccsd as ccsd_grad\n\n\ndef grad_elec(cigrad, civec=None, eris=None, atmlst=None, verbose=logger.INFO):\n    myci = cigrad.base\n    if civec is None: civec = myci.ci\n    assert(not isinstance(civec, (list, tuple)))\n    nocc = myci.nocc\n    nmo = myci.nmo\n    d1 = cisd._gamma1_intermediates(myci, civec, nmo, nocc)\n    fd2intermediate = lib.H5TmpFile()\n    d2 = cisd._gamma2_outcore(myci, civec, nmo, nocc, fd2intermediate, True)\n    t1 = t2 = l1 = l2 = civec\n    return ccsd_grad.grad_elec(cigrad, t1, t2, l1, l2, eris, atmlst, d1, d2, verbose)\n\n\ndef as_scanner(grad_ci, state=0):\n    '''Generating a nuclear gradients scanner/solver (for geometry optimizer).\n\n    The returned solver is a function. This function requires one argument\n    \"mol\" as input and returns total CISD energy.\n\n    The solver will automatically use the results of last calculation as the\n    initial guess of the new calculation.  All parameters assigned in the\n    CISD and the underlying SCF objects (conv_tol, max_memory etc) are\n    automatically applied in the solver.\n\n    Note scanner has side effects.  It may change many underlying objects\n    (_scf, with_df, with_x2c, ...) during calculation.\n\n    Examples::\n\n    >>> from pyscf import gto, scf, ci\n    >>> mol = gto.M(atom='H 0 0 0; F 0 0 1')\n    >>> ci_scanner = ci.CISD(scf.RHF(mol)).nuc_grad_method().as_scanner()\n    >>> e_tot, grad = ci_scanner(gto.M(atom='H 0 0 0; F 0 0 1.1'))\n    >>> e_tot, grad = ci_scanner(gto.M(atom='H 0 0 0; F 0 0 1.5'))\n    '''\n    from pyscf import gto\n    if isinstance(grad_ci, lib.GradScanner):\n        return grad_ci\n\n    logger.info(grad_ci, 'Create scanner for %s', grad_ci.__class__)\n\n    class CISD_GradScanner(grad_ci.__class__, lib.GradScanner):\n        def __init__(self, g):\n            lib.GradScanner.__init__(self, g)\n\n        def __call__(self, mol_or_geom, state=state, **kwargs):\n            if isinstance(mol_or_geom, gto.Mole):\n                mol = mol_or_geom\n            else:\n                mol = self.mol.set_geom_(mol_or_geom, inplace=False)\n\n            ci_scanner = self.base\n            if ci_scanner.nroots > 1 and state >= ci_scanner.nroots:\n                raise ValueError('State ID greater than the number of CISD roots')\n\n            mf_scanner = ci_scanner._scf\n            mf_scanner(mol)\n            ci_scanner.mo_coeff = mf_scanner.mo_coeff\n            ci_scanner.mo_occ = mf_scanner.mo_occ\n\n            if getattr(ci_scanner.ci, 'size', 0) != ci_scanner.vector_size():\n                ci_scanner.ci = None\n            eris = ci_scanner.ao2mo(ci_scanner.mo_coeff)\n            ci_scanner.kernel(ci0=ci_scanner.ci, eris=eris)\n\n# TODO: Check root flip\n            if ci_scanner.nroots > 1:\n                e_tot = ci_scanner.e_tot[state]\n                civec = ci_scanner.ci[state]\n            else:\n                e_tot = ci_scanner.e_tot\n                civec = ci_scanner.ci\n\n            self.mol = mol\n            de = self.kernel(civec, eris=eris, **kwargs)\n            return e_tot, de\n        @property\n        def converged(self):\n            ci_scanner = self.base\n            if ci_scanner.nroots > 1:\n                ci_conv = ci_scanner.converged[state]\n            else:\n                ci_conv = ci_scanner.converged\n            return all((ci_scanner._scf.converged, ci_conv))\n\n    # cache eris object in CCSD base class. eris object is used many times\n    # when calculating gradients\n    g_ao2mo = grad_ci.base.__class__.ao2mo\n    def _save_eris(self, *args, **kwargs):\n        self._eris = g_ao2mo(self, *args, **kwargs)\n        return self._eris\n    grad_ci.base.__class__.ao2mo = _save_eris\n\n    return CISD_GradScanner(grad_ci)\n\nclass Gradients(rhf_grad.GradientsBasics):\n    def __init__(self, myci):\n        self.state = 0  # of which the gradients to be computed.\n        rhf_grad.GradientsBasics.__init__(self, myci)\n\n    def dump_flags(self, verbose=None):\n        log = logger.new_logger(self, verbose)\n        log.info('\\n')\n        if not self.base.converged:\n            log.warn('Ground state %s not converged',\n                     self.base.__class__.__name__)\n        log.info('******** %s for %s ********',\n                 self.__class__, self.base.__class__)\n        if self.state != 0 and self.base.nroots > 1:\n            log.info('State ID = %d', self.state)\n        return self\n\n    grad_elec = grad_elec\n\n    def kernel(self, civec=None, eris=None, atmlst=None, state=None,\n               verbose=None):\n        log = logger.new_logger(self, verbose)\n        myci = self.base\n        if civec is None: civec = myci.ci\n        if civec is None: civec = myci.kernel(eris=eris)\n        if (isinstance(civec, (list, tuple)) or\n            (isinstance(civec, numpy.ndarray) and civec.ndim > 1)):\n            if state is None:\n                state = self.state\n            else:\n                self.state = state\n\n            civec = civec[state]\n            logger.info(self, 'Multiple roots are found in CISD solver. '\n                        'Nuclear gradients of root %d are computed.', state)\n\n        if atmlst is None:\n            atmlst = self.atmlst\n        else:\n            self.atmlst = atmlst\n\n        if self.verbose >= logger.WARN:\n            self.check_sanity()\n        if self.verbose >= logger.INFO:\n            self.dump_flags()\n\n        de = self.grad_elec(civec, eris, atmlst, verbose=log)\n        self.de = de + self.grad_nuc(atmlst=atmlst)\n        if self.mol.symmetry:\n            self.de = self.symmetrize(self.de, atmlst)\n        self._finalize()\n        return self.de\n\n    # Calling the underlying SCF nuclear gradients because it may be modified\n    # by external modules (e.g. QM/MM, solvent)\n    def grad_nuc(self, mol=None, atmlst=None):\n        mf_grad = self.base._scf.nuc_grad_method()\n        return mf_grad.grad_nuc(mol, atmlst)\n\n    def _finalize(self):\n        if self.verbose >= logger.NOTE:\n            logger.note(self, '--------- %s gradients for state %d ----------',\n                        self.base.__class__.__name__, self.state)\n            self._write(self.mol, self.de, self.atmlst)\n            logger.note(self, '----------------------------------------------')\n\n    as_scanner = as_scanner\n\nGrad = Gradients\n\ncisd.CISD.Gradients = lib.class_as_method(Gradients)\n\n\nif __name__ == '__main__':\n    from pyscf import gto\n    from pyscf import scf\n\n    mol = gto.M(\n        atom = [\n            [\"O\" , (0. , 0.     , 0.)],\n            [1   , (0. ,-0.757  , 0.587)],\n            [1   , (0. , 0.757  , 0.587)]],\n        basis = '631g'\n    )\n    mf = scf.RHF(mol)\n    ehf = mf.scf()\n\n    myci = cisd.CISD(mf)\n    myci.kernel()\n    g1 = myci.Gradients().kernel()\n# O     0.0000000000    -0.0000000000     0.0065498854\n# H    -0.0000000000     0.0208760610    -0.0032749427\n# H    -0.0000000000    -0.0208760610    -0.0032749427\n    print(lib.finger(g1) - -0.032562200777204092)\n\n    mcs = myci.as_scanner()\n    mol.set_geom_([\n            [\"O\" , (0. , 0.     , 0.001)],\n            [1   , (0. ,-0.757  , 0.587)],\n            [1   , (0. , 0.757  , 0.587)]])\n    e1 = mcs(mol)\n    mol.set_geom_([\n            [\"O\" , (0. , 0.     ,-0.001)],\n            [1   , (0. ,-0.757  , 0.587)],\n            [1   , (0. , 0.757  , 0.587)]])\n    e2 = mcs(mol)\n    print(g1[0,2] - (e1-e2)/0.002*lib.param.BOHR)\n\n    print('-----------------------------------')\n    mol = gto.M(\n        atom = [\n            [\"O\" , (0. , 0.     , 0.)],\n            [1   , (0. ,-0.757  , 0.587)],\n            [1   , (0. , 0.757  , 0.587)]],\n        basis = '631g'\n    )\n    mf = scf.RHF(mol)\n    ehf = mf.scf()\n\n    myci = cisd.CISD(mf)\n    myci.frozen = [0,1,10,11,12]\n    myci.max_memory = 1\n    myci.kernel()\n    g1 = Gradients(myci).kernel()\n# O    -0.0000000000     0.0000000000     0.0106763547\n# H     0.0000000000    -0.0763194988    -0.0053381773\n# H     0.0000000000     0.0763194988    -0.0053381773\n    print(lib.finger(g1) - 0.1022427304650084)\n\n    mcs = myci.as_scanner()\n    mol.set_geom_([\n            [\"O\" , (0. , 0.     , 0.001)],\n            [1   , (0. ,-0.757  , 0.587)],\n            [1   , (0. , 0.757  , 0.587)]])\n    e1 = mcs(mol)\n    mol.set_geom_([\n            [\"O\" , (0. , 0.     ,-0.001)],\n            [1   , (0. ,-0.757  , 0.587)],\n            [1   , (0. , 0.757  , 0.587)]])\n    e2 = mcs(mol)\n    print(g1[0,2] - (e1-e2)/0.002*lib.param.BOHR)\n\n    mol = gto.M(\n        atom = 'H 0 0 0; H 0 0 1.76',\n        basis = '631g',\n        unit='Bohr')\n    mf = scf.RHF(mol).run(conv_tol=1e-14)\n    myci = cisd.CISD(mf)\n    myci.conv_tol = 1e-10\n    myci.kernel()\n    g1 = Gradients(myci).kernel()\n#[[ 0.          0.         -0.07080036]\n# [ 0.          0.          0.07080036]]\n", "meta": {"hexsha": "1cc96196d27d99e9c80f634e2664143d3feb5d5a", "size": 9528, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/grad/cisd.py", "max_stars_repo_name": "shufay/pyscf", "max_stars_repo_head_hexsha": "c7ea840b012a59fce5fa4114ef3274a7cf00165e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-12T11:55:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T11:55:25.000Z", "max_issues_repo_path": "pyscf/grad/cisd.py", "max_issues_repo_name": "shufay/pyscf", "max_issues_repo_head_hexsha": "c7ea840b012a59fce5fa4114ef3274a7cf00165e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2018-08-22T19:44:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-09T10:02:36.000Z", "max_forks_repo_path": "pyscf/grad/cisd.py", "max_forks_repo_name": "shufay/pyscf", "max_forks_repo_head_hexsha": "c7ea840b012a59fce5fa4114ef3274a7cf00165e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-02-14T16:28:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-12T16:40:30.000Z", "avg_line_length": 34.1505376344, "max_line_length": 85, "alphanum_fraction": 0.5715785055, "include": true, "reason": "import numpy", "num_tokens": 2901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.31742627850202554, "lm_q1q2_score": 0.1869288898104529}}
{"text": "from copy import copy\nfrom .nmf import NMF\nfrom .make_template import TEMPLATE_PATH, HOP_SIZE, SR\nfrom .make_template import BASIS, FRAME_SIZE, ATTACK, BINS\nfrom .utils import make_pianoroll, find_start_stop, midipath2mat\nfrom .utils import stretch_pianoroll, mat2midipath\nimport pickle\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\nimport numpy as np\nimport sys\nimport random\nfrom tqdm import tqdm\n\nMINI_SPEC_SIZE = 14\nDEVICE = 'cuda'\nALIGNED_MINI_SPEC_PATH = 'aligned_mini_specs.pkl'\nVIENNA_MINI_SPEC_PATH = 'vienna_mini_specs.pkl'\nALIGNED_VELOCITY_MODEL_PATH = 'aligned_velocity_model.pkl'\nVIENNA_VELOCITY_MODEL_PATH = 'vienna_velocity_model.pkl'\nCOST_FUNC = 'EucDist'\nNJOBS = 5\nEPS_ACTIVATIONS = 1e-4\nNUM_SONGS_FOR_TRAINING = 100\nEPOCHS = 500\nBATCH_SIZE = 400\nEARLY_STOP = 10\nBRANCHES = 16\nDATASET_LEN = 1  # use this for debugging\nEPS_RANGE = 0.1\n\n\ndef spectrogram(audio, frames=FRAME_SIZE, hop=HOP_SIZE):\n\n    import essentia.standard as esst\n    import essentia as es\n    spectrogram = []\n    spec = esst.SpectrumCQ(numberBins=BINS, sampleRate=SR, windowType='hann')\n    for frame in esst.FrameGenerator(audio, frameSize=frames, hopSize=hop):\n        spectrogram.append(spec(frame))\n\n    return es.array(spectrogram).T\n\n\ndef get_default_predict_func(vienna_based):\n    \"\"\"\n    Return the default  predict function based on PyTorch.  If `vienna_based`\n    is True, it will be the model trained with vienna transcription method,\n    otherwise it will be the model based on magenta aligned score\n    \"\"\"\n    velocity_model = VelocityEstimation().to(DEVICE)\n    if vienna_based:\n        parameters = pickle.load(open(VIENNA_VELOCITY_MODEL_PATH, 'rb'))\n    else:\n        parameters = pickle.load(open(ALIGNED_VELOCITY_MODEL_PATH, 'rb'))\n    velocity_model.load_state_dict(parameters)\n    velocity_model.eval()\n    return velocity_model.predict\n\n\ndef transcribe(audio,\n               data,\n               score=None,\n               res=0.001,\n               sr=SR,\n               return_mini_specs=False):\n    \"\"\"\n    Takes an audio mono file and the non-aligned score mat format as in asmd.\n    Align them and perform NMF with default templates.\n    Returns new score with velocities and timings updated\n\n    `res` is only used for alignment\n    \"\"\"\n    if not return_mini_specs:\n        velocity_model = get_default_predict_func(score is None)\n\n    initW, minpitch, maxpitch = data\n    initW = copy(initW)\n    if score is not None:\n        from .alignment.align_with_amt import audio_to_score_alignment\n        score = copy(score)\n        # align score\n        new_ons, new_offs = audio_to_score_alignment(score, audio, sr, res=res)\n        score[:, 1] = new_ons\n        score[:, 2] = new_offs\n    else:\n        from .vienna_transcription import transcribe\n        score = transcribe(audio, sr)\n\n    # prepare initial matrices\n\n    # remove stoping and starting silence in audio\n    start, stop = find_start_stop(audio, sample_rate=sr)\n    audio = audio[start:stop]\n    V = spectrogram(audio)\n\n    # compute the needed resolution for pianoroll\n    res = len(audio) / sr / V.shape[1]\n    pr = make_pianoroll(score,\n                        res=res,\n                        basis=BASIS,\n                        velocities=False,\n                        attack=ATTACK,\n                        eps=EPS_ACTIVATIONS,\n                        eps_range=EPS_RANGE)\n\n    # remove trailing zeros in initH\n    nonzero_cols = pr.any(axis=0).nonzero()[0]\n    start = nonzero_cols[0]\n    stop = nonzero_cols[-1]\n    pr = pr[:, start:stop + 1]\n\n    # stretch pianoroll\n    initH = stretch_pianoroll(pr, V.shape[1])\n\n    # check shapes\n    assert V.shape == (initW.shape[0], initH.shape[1]),\\\n        \"V, W, H shapes are not comparable\"\n    assert initH.shape[0] == initW.shape[1],\\\n        \"W, H have different ranks\"\n\n    initW = initW[:, minpitch * BASIS:(maxpitch + 1) * BASIS]\n    initH = initH[minpitch * BASIS:(maxpitch + 1) * BASIS, :]\n    initH[initH == 0] = EPS_ACTIVATIONS\n\n    # perform nfm\n    NMF(V, initW, initH, B=BASIS, num_iter=5, cost_func=COST_FUNC)\n\n    NMF(V, initW, initH, B=BASIS, num_iter=5, cost_func=COST_FUNC, fixW=True)\n\n    # use the updated H and W for computing mini-spectrograms\n    # and predict velocities\n    mini_specs = []\n    npitch = maxpitch - minpitch + 1\n    initH = initH.reshape(npitch, BASIS, -1)\n    initW = initW.reshape((-1, npitch, BASIS), order='C')\n    # removing existing velocities\n    score[:, 3] = -255\n    for note in score:\n        # extract mini-spectrogram\n\n        # look for the maximum value in initH in the note\n        start = max(0, int(note[1] / res))\n        end = min(initH.shape[2], int(note[2] / res))\n\n        if end - start < 1:\n            note[3] = 63\n            mini_specs.append(None)\n            continue\n\n        m = np.argmax(\n            np.max(initH[int(note[0] - minpitch), :, start:end],\n                   axis=0)) + start\n\n        # select the sorrounding space in initH\n        start = max(0, m - MINI_SPEC_SIZE // 2)\n        end = min(start + MINI_SPEC_SIZE, initH.shape[2])\n\n        if end - start < MINI_SPEC_SIZE:\n            note[3] = 63\n            mini_specs.append(None)\n            continue\n\n        # compute the mini_spec\n        mini_spec = initW[:, int(note[0] - minpitch), :] @\\\n            initH[int(note[0] - minpitch), :, start:end]\n\n        # normalizing with rms\n        # mini_spec /= (mini_spec**2).mean()**0.5\n        # normalizing to the sum\n        mini_spec /= mini_spec.sum()\n\n        mini_specs.append(mini_spec)\n\n    if return_mini_specs:\n        return mini_specs\n    else:\n        # remove nans...\n        mini_specs = [i for i in mini_specs if i is not None]\n        # numpy to torch and add channel dimensions\n        mini_specs = torch.tensor(mini_specs).to(DEVICE).to(\n            torch.float).unsqueeze(1)\n        with torch.no_grad():\n            vels = velocity_model(mini_specs)\n        score[score[:, 3] != 63, 3] = vels.cpu().numpy()\n        return score, V, initW, initH\n\n\ndef transcribe_from_paths(audio_path,\n                          data,\n                          velocity_model,\n                          midi_score_path=None,\n                          tofile='out.mid'):\n    \"\"\"\n    Load a midi and an audio file and call `transcribe`. If `tofile` is not\n    empty, it will also write a new MIDI file with the provided path.\n    The output midi file will contain only one track with piano (program 0)\n    \"\"\"\n    import essentia.standard as esst\n    audio = esst.EasyLoader(filename=audio_path, sampleRate=SR)()\n    if midi_score_path:\n        score = midipath2mat(midi_score_path)\n    else:\n        score = None\n    new_score, _, _, _ = transcribe(audio,\n                                    data,\n                                    score=score,\n                                    velocity_model=velocity_model)\n\n    # writing to midi\n    mat2midipath(new_score, tofile)\n    return new_score\n\n\ndef processing(i, dataset, data):\n    audio, sr = dataset.get_mix(i, sr=SR)\n    score = dataset.get_score(i, score_type=['non_aligned'])\n    velocities = dataset.get_score(i, score_type=['precise_alignment'])[:, 3]\n    return transcribe(audio, data, score=score,\n                      return_mini_specs=True), velocities.tolist()\n\n\ndef create_mini_specs(data, mini_spec_path):\n    \"\"\"\n    Perform alignment and NMF but not velocity estimation; instead, saves all\n    the mini_specs of each note in the Maestro dataset for successive training\n    \"\"\"\n    from asmd.asmd import audioscoredataset\n    from .maestro_split_indices import maestro_splits\n    train, validation, test = maestro_splits()\n    dataset = audioscoredataset.Dataset().filter(datasets=[\"Maestro\"])\n    random.seed(1750)\n    train = random.sample(train, NUM_SONGS_FOR_TRAINING)\n    dataset.paths = np.array(dataset.paths)[train].tolist()\n\n    data = dataset.parallel(processing, data, n_jobs=NJOBS)\n\n    mini_specs, velocities = [], []\n    for d in data:\n        specs, vels = d\n        # removing nones\n        for i in range(len(specs)):\n            spec = specs[i]\n            vel = vels[i]\n            if spec is not None and vel is not None:\n                mini_specs.append(spec)\n                velocities.append(vel)\n\n    pickle.dump((mini_specs, velocities), open(mini_spec_path, 'wb'))\n    print(\n        f\"number of (inputs, targets) in training set: {len(mini_specs)}, {len(velocities)}\"\n    )\n\n\nclass VelocityEstimation(nn.Module):\n    def __init__(self,\n                 in_numel=MINI_SPEC_SIZE * 100,\n                 branches=BRANCHES,\n                 k=128 // BRANCHES + 1):\n        super().__init__()\n\n        self.preprocess = nn.Sequential(nn.BatchNorm2d(1), nn.Dropout(0.3))\n\n        self.in_numel = in_numel\n        self.branches = branches\n        self.k = k\n\n        self.process = nn.ModuleList()\n\n        for i in range(branches):\n            self.process.append(\n                nn.Sequential(nn.Linear(in_numel, k, bias=True), nn.SELU()))\n\n        self.finalize = nn.Sequential(\n            nn.Linear(branches * k, branches * k, bias=False), nn.SELU(),\n            nn.Linear(branches * k, branches * k, bias=False), nn.SELU(),\n            nn.Linear(branches * k, branches * k, bias=False), nn.SELU(),\n            nn.Linear(branches * k, branches * k, bias=False), nn.SELU(),\n            nn.Linear(branches * k, branches * k, bias=False), nn.SELU(),\n            nn.Linear(branches * k, 1, bias=False), nn.Sigmoid())\n\n        # self.apply(lambda x: init_weights(x, nn.init.kaiming_uniform_))\n\n    def forward(self, x):\n\n        # preprocess\n        x = self.preprocess(x).reshape(x.shape[0], -1)\n\n        # process each velocity range\n        y = torch.zeros(x.shape[0], self.branches,\n                        self.k).to(x.dtype).to(x.device)\n        for i in range(self.branches):\n            y[:, i, :] = self.process[i](x)\n\n        # apply softmax so that only the first output is a probability (classification)\n        middle_out = F.softmax(y[:, :, 0], dim=1)\n\n        # finalize takes as input the concatenation of all the features of previous layers\n        if self.k > 1:\n            x = torch.cat([y[..., i] for i in range(1, self.k)], dim=1)\n            x = torch.cat([middle_out, x], dim=1)\n        else:\n            x = middle_out\n        x = self.finalize(x)[:, 0] * 127\n\n        return x, middle_out\n\n    def predict(self, x):\n        x = self.forward(x)[0]\n        return x\n        # return torch.argmax(x, dim=1)\n\n\ndef init_weights(m, initializer):\n    if hasattr(m, \"weight\"):\n        if m.weight is not None:\n\n            w = m.weight.data\n            if w.dim() < 2:\n                w = w.unsqueeze(0)\n            initializer(w)\n\n\nclass Dataset(torch.utils.data.Dataset):\n    def __init__(self, inputs, targets, branches=BRANCHES):\n        super().__init__()\n        self.inputs = torch.tensor(inputs).to(torch.float).to(DEVICE)\n        self.targets = torch.tensor(targets).to(torch.float).to(DEVICE)\n        self.targets_middle = torch.zeros(len(targets),\n                                          branches).to(torch.float).to(DEVICE)\n        self.targets_middle[torch.arange(len(targets)), targets % branches] = 1\n        assert len(self.inputs) == len(self.targets),\\\n            \"inputs and targets must have the same length!\"\n        del inputs, targets\n\n    def __getitem__(self, i):\n        return self.inputs[i], self.targets[i], self.targets_middle[i]\n\n    def __len__(self):\n        return len(self.inputs)\n\n\ndef train(data, model_path, mini_spec_path):\n\n    print(\"Loading dataset...\")\n    mini_spec = open(mini_spec_path, 'rb')\n    inputs, targets = pickle.load(mini_spec)\n    mini_spec.close()\n\n    print(\"Building model...\")\n    model = VelocityEstimation().to(DEVICE)\n    print(model)\n\n    # shuffle and split\n    indices = list(range(len(inputs) // DATASET_LEN))\n    random.seed(1998)\n    random.shuffle(indices)\n    inputs = np.array(inputs)\n    targets = np.array(targets)\n    train_size = int(len(indices) * 0.7)\n    test_size = valid_size = int(len(indices) * 0.15)\n    train_x = inputs[indices[:train_size]]\n    valid_x = inputs[indices[train_size:train_size + valid_size]]\n    test_x = inputs[indices[-test_size:]]\n    train_y = targets[indices[:train_size]]\n    valid_y = targets[indices[train_size:train_size + valid_size]]\n    test_y = targets[indices[-test_size:]]\n\n    # creating loaders\n    trainloader = torch.utils.data.DataLoader(Dataset(train_x, train_y,\n                                                      BRANCHES),\n                                              batch_size=BATCH_SIZE)\n    validloader = torch.utils.data.DataLoader(Dataset(valid_x, valid_y,\n                                                      BRANCHES),\n                                              batch_size=BATCH_SIZE)\n    testloader = torch.utils.data.DataLoader(Dataset(test_x, test_y, BRANCHES),\n                                             batch_size=BATCH_SIZE)\n    del train_x, train_y, valid_x, valid_y, test_x, test_y, inputs, targets\n\n    optim = torch.optim.Adadelta(model.parameters(), lr=1e-3)\n\n    best_epoch = 0\n    best_params = None\n    best_loss = 9999\n    for epoch in range(EPOCHS):\n        print(f\"-- Epoch {epoch} --\")\n        trainloss, validloss = [], []\n        print(\"-> Training\")\n        model.train()\n        for inputs, targets, targets_middle in tqdm(trainloader):\n            inputs = inputs.to(DEVICE).unsqueeze(1)\n            targets = targets.to(DEVICE)\n            targets_middle = targets_middle.to(DEVICE)\n\n            optim.zero_grad()\n            out, middle_out = model(inputs)\n            bce_loss = F.binary_cross_entropy(middle_out, targets_middle)\n            l1_loss = F.l1_loss(out, targets)\n            # loss = l1_loss\n            loss = bce_loss + l1_loss\n            loss.backward()\n            optim.step()\n            trainloss.append(l1_loss.detach().cpu().numpy())\n\n        print(f\"training loss : {np.mean(trainloss)}\")\n\n        print(\"-> Validating\")\n        with torch.no_grad():\n            model.eval()\n            for inputs, targets, _ in tqdm(validloader):\n                inputs = inputs.unsqueeze(1)\n                targets = targets.to(DEVICE)\n                # targets = torch.argmax(targets, dim=1).to(torch.float)\n\n                out = model.predict(inputs).to(torch.float)\n                loss = torch.abs(targets - out)\n                validloss += loss.tolist()\n\n        validloss = np.mean(validloss)\n        print(f\"validation loss : {validloss}\")\n        if validloss < best_loss:\n            best_loss = validloss\n            best_epoch = epoch\n            best_params = model.state_dict()\n        elif epoch - best_epoch > EARLY_STOP:\n            print(\"-- Early stop! --\")\n            break\n\n    # saving params\n    model.load_state_dict(best_params)\n    pickle.dump(model.to('cpu').state_dict(), open(model_path, 'wb'))\n    model.to(DEVICE)\n\n    # testing\n    print(\"-> Testing\")\n    testloss = []\n    with torch.no_grad():\n        model.eval()\n        for inputs, targets, _ in tqdm(testloader):\n            inputs = inputs.unsqueeze(1)\n            targets = targets.to(DEVICE)\n            # targets = torch.argmax(targets, dim=1).to(torch.float)\n\n            out = model.predict(inputs).to(torch.float)\n            loss = torch.abs(targets - out)\n            testloss += loss.tolist()\n\n        print(\n            f\"testing absolute error (mean, std): {np.mean(testloss)}, {np.std(testloss)}\"\n        )\n\n\ndef show_usage():\n    print(\n        f\"Usage: {sys.argv[0]} [audio_path midi_output_path [midi_score_path] [--cpu]]\"\n    )\n    print(f\"Usage: {sys.argv[0]} create_mini_specs, [--vienna]\")\n    print(f\"Usage: {sys.argv[0]} train [--vienna]\")\n\n\nif __name__ == '__main__':\n    if len(sys.argv) < 2:\n        show_usage()\n    elif sys.argv[1] == 'create_mini_specs':\n\n        data = pickle.load(open(TEMPLATE_PATH, 'rb'))\n        mini_spec_path = ALIGNED_MINI_SPEC_PATH\n        if '--vienna' in sys.argv:\n            mini_spec_path = VIENNA_MINI_SPEC_PATH\n        create_mini_specs(data, mini_spec_path)\n\n    elif sys.argv[1] == 'train':\n\n        data = pickle.load(open(TEMPLATE_PATH, 'rb'))\n        mini_spec_path = ALIGNED_MINI_SPEC_PATH\n        model_path = ALIGNED_VELOCITY_MODEL_PATH\n        if '--vienna' in sys.argv:\n            model_path = VIENNA_VELOCITY_MODEL_PATH\n            mini_spec_path = VIENNA_MINI_SPEC_PATH\n        train(data, model_path, mini_spec_path)\n\n    elif len(sys.argv) < 3:\n        show_usage()\n    else:\n\n        data = pickle.load(open(TEMPLATE_PATH, 'rb'))\n\n        if len(sys.argv) > 3:\n            if '--cpu' in sys.argv:\n                DEVICE = 'cpu'\n            else:\n                score = sys.argv[3]\n        else:\n            score = None\n        transcribe_from_paths(sys.argv[1],\n                              data,\n                              midi_score_path=score,\n                              tofile=sys.argv[2])\n", "meta": {"hexsha": "d65f09abc02666d201a2420e5ec35bf0c8549df0", "size": 16902, "ext": "py", "lang": "Python", "max_stars_repo_path": "perceptual/proposed.py", "max_stars_repo_name": "LIMUNIMI/PerceptualEvaluation", "max_stars_repo_head_hexsha": "6e1fcdf65ae5cb86997443607bb2050163b64720", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "perceptual/proposed.py", "max_issues_repo_name": "LIMUNIMI/PerceptualEvaluation", "max_issues_repo_head_hexsha": "6e1fcdf65ae5cb86997443607bb2050163b64720", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "perceptual/proposed.py", "max_forks_repo_name": "LIMUNIMI/PerceptualEvaluation", "max_forks_repo_head_hexsha": "6e1fcdf65ae5cb86997443607bb2050163b64720", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.804, "max_line_length": 92, "alphanum_fraction": 0.5981540646, "include": true, "reason": "import numpy", "num_tokens": 4108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.1869288776248054}}
{"text": "import numpy\nimport conf\ndef PRINTER():\n\t# IMPLICIT #real*8 (A-H,O-Z) \n\t# IMPLICIT #integer*8 (I-N)   \n\t#integer*4 NSEED                                     \n\t#COMMON/INPT/\n\tglobal NGAS,NSTEP,NANISO,EFINAL,ESTEP,AKT,ARY,TEMPC,TORR,IPEN\n\t#COMMON/INPT2/\n\tglobal KGAS,LGAS,DETEFF,EXCWGHT\n\t#COMMON/INPT1/\n\tglobal NDVEC\n\t#COMMON/COMP/\n\tglobal LCMP,LCFLG,LRAY,LRFLG,LPAP,LPFLG,LBRM,LBFLG,LPEFLG \n\t#COMMON/RATIO/\n\tglobal AN1,AN2,AN3,AN4,AN5,AN6,AN\n\tglobal FRAC#(6)              \n\t#COMMON/SETP/\n\tglobal TMAX,SMALL,API,ESTART,THETA,PHI\n\tglobal TCFMAX#(10),\n\tglobal TCFMAX1,RSTART,EFIELD,ETHRM,ECUT,NEVENT,IMIP,IWRITE                      \n\t#COMMON/BFLD/\n\tglobal EOVB,WB,BTHETA,BMAG  \n\t#COMMON/IONC/\n\tglobal DOUBLE#(6,20000),\n\tglobal CMINIXSC#(6),\n\tglobal CMINEXSC#(6),\n\tglobal ECLOSS#(6),\n\tglobal WPLN#(6),\n\tglobal ICOUNT,AVPFRAC#(3,6)\n\t#COMMON/LARGE/\n\tglobal CF#(20000,512),\n\tglobal EIN#(512),\n\tglobal TCF#(20000),\n\tglobal IARRY#(512),\n\tglobal RGAS#(512),\n\tglobal IPN#(512),\n\tglobal WPL#(512),\n\tglobal IZBR#(512),\n\tglobal IPLAST,PENFRA#(3,512)   \n\t#COMMON/NAMES/\n\tglobal NAMEG#(6)  \n\t#COMMON/KSEED/\n\tglobal NSEED \n\t#COMMON/ECASC/\n\tglobal NEGAS#(512),\n\tglobal LEGAS#(512),\n\tglobal IESHELL#(512),\n\tglobal IECASC  \n\tNGAS=conf.NGAS\n\tNSTEP=conf.NSTEP\n\tNANISO=conf.NANISO\n\tEFINAL=conf.EFINAL\n\tESTEP=conf.ESTEP\n\tAKT=conf.AKT\n\tARY=conf.ARY\n\tTEMPC=conf.TEMPC\n\tTORR=conf.TORR\n\tIPEN=conf.IPEN\n\tKGAS=conf.KGAS\n\tLGAS=conf.LGAS\n\tDETEFF=conf.DETEFF\n\tEXCWGHT=conf.EXCWGHT\n\tNDVEC=conf.NDVEC\n\tLCMP=conf.LCMP\n\tLCFLG=conf.LCFLG\n\tLRAY=conf.LRAY\n\tLRFLG=conf.LRFLG\n\tLPAP=conf.LPAP\n\tLPFLG=conf.LPFLG\n\tLBRM=conf.LBRM\n\tLBFLG=conf.LBFLG\n\tLPEFLG =conf.LPEFLG \n\tAN1=conf.AN1\n\tAN2=conf.AN2\n\tAN3=conf.AN3\n\tAN4=conf.AN4\n\tAN5=conf.AN5\n\tAN6=conf.AN6\n\tAN=conf.AN\n\tFRAC=conf.FRAC\n\tTMAX=conf.TMAX\n\tSMALL=conf.SMALL\n\tAPI=conf.API\n\tESTART=conf.ESTART\n\tTHETA=conf.THETA\n\tPHI=conf.PHI\n\tTCFMAX=conf.TCFMAX\n\n\tTCFMAX1=conf.TCFMAX1\n\tRSTART=conf.RSTART\n\tEFIELD=conf.EFIELD\n\tETHRM=conf.ETHRM\n\tECUT=conf.ECUT\n\tNEVENT=conf.NEVENT\n\tIMIP=conf.IMIP\n\tIWRITE=conf.IWRITE\n\tEOVB=conf.EOVB\n\tWB=conf.WB\n\tBTHETA=conf.BTHETA\n\tBMAG  =conf.BMAG  \n\tDOUBLE=conf.DOUBLE\n\n\tCMINIXSC=conf.CMINIXSC\n\n\tCMINEXSC=conf.CMINEXSC\n\n\tECLOSS=conf.ECLOSS\n\n\tWPLN=conf.WPLN\n\n\tICOUNT=conf.ICOUNT\n\tAVPFRAC=conf.AVPFRAC\n\tCF=conf.CF\n\n\tEIN=conf.EIN\n\n\tTCF=conf.TCF\n\n\tIARRY=conf.IARRY\n\n\tRGAS=conf.RGAS\n\n\tIPN=conf.IPN\n\n\tWPL=conf.WPL\n\n\tIZBR=conf.IZBR\n\n\tIPLAST=conf.IPLAST\n\tPENFRA=conf.PENFRA\n\tNAMEG=conf.NAMEG\n\tNSEED =conf.NSEED \n\tNEGAS=conf.NEGAS\n\n\tLEGAS=conf.LEGAS\n\n\tIESHELL=conf.IESHELL\n\n\tIECASC  =conf.IECASC  \n\t# NAMEG=numpy.zeros(25+1,dtype=str)\n\t# WRITE(6,1)     \n\tprint('\\n           DEGRAD VERSION 3.3  \\n','      -----------------------------\\n\\n')      \n\tif(IMIP == 1):\n\t\tprint('   MIP AND DE/DX SIMULATION')\t#2\n\tif(IMIP == 2):\n\t\tprint('   ELECTRON BEAM SIMULATION')    \n\tif(IMIP == 3):\n\t\tprint('   X-RAY SIMULATION')\t#4\n\tif(IMIP == 4):\n\t\tprint('   BETA DECAY SIMULATION')\t#5\n\tif(IMIP == 5):\n\t\tprint('   DOUBLE BETA DECAY SIMULATION')\t#6\n\tprint('----------------------------------\\n\\n')\n\tif(LCMP == 0):\n\t\tprint('   SIMULATION WITHOUT COMPTON SCATTERING')  \t#7\n\tif(LCMP == 1):\n\t\tprint('   SIMULATION WITH COMPTON SCATTERING')\t#8\n\tif(LRAY == 0):\n\t\tprint('   SIMULATION WITHOUT RAYLEIGH SCATTERING')\t#9\n\tif(LRAY == 1):\n\t\tprint('   SIMULATION WITH RAYLEIGH SCATTERING')\t#11 \n\tif(LPAP == 0):\n\t\tprint('   SIMULATION WITHOUT PAIR PRODUCTION')\t#12 \n\tif(LPAP == 1):\n\t\tprint('   SIMULATION WITH PAIR PRODUCTION')\t#13 \n\tif(LBRM == 0):\n\t\tprint('   SIMULATION WITHOUT BREMSSTRAHLUNG')\t#14 \n\tif(LBRM == 1):\t\n\t\tprint('   SIMULATION WITH BREMSSTRAHLUNG')\t#15 \n\tif(IECASC == 0):\n\t\tprint('   SIMULATION WITH PARAMETERISED SHELL CASCADE')\t#16 \n\tif(IECASC == 1):\n\t\tprint('   SIMULATION WITH COMPLETE SHELL CASCADE')\t#17 \n\tprint('----------------------------------\\n\\n')\n\tprint('   MONTE CARLO SOLUTION FOR MIXTURE OF ',NGAS,' GASES.\\n   DEGRADATION CALCULATION ALL TIMES IN PICOSECS, DISTANCE IN MICRONS\\n   -----------------------------------------------------------------')\n\t# WRITE(6,30) (NAMEG[J],FRAC[J], J=1,NGAS)     \n\tfor J in range(1,NGAS+1):\n\t\tprint('\\n',5*' ','  GASES  USED ',15*' ',' PERCENTAGE USED ',2*'\\n',6*' ',NAMEG[J],5*' ','%.4f' % FRAC[J],'\\n')\n\tprint('\\n','  ','GAS TEMPERATURE =','%.1f' % TEMPC,' DEGREES CENTIGRADE.','\\n','  ','GAS PRESSURE = ','%.1f' % TORR,' TORR.')\n\tif(NSEED != 0):\n\t\t# WRITE(6,51) NSEED\n\t\tprint(2*'\\n',' RANDOM NUMBER SEED =',NSEED)\n\tif(NSEED == 0):\n\t\t# WRITE(6,52) \n\t\tprint(2*'\\n',' STANDARD RANDOM NUMBER SEED = 54217137')\n\tif(IPEN == 0):\n\t\t# WRITE(6,55)\n\t\tprint(2*'\\n','  ',' PENNING IONISATION NOT ALLOWED')\n\tif(IPEN == 1):\n\t\t# WRITE(6,56)                              \n\t\tprint(2*'\\n','  ',' PENNING IONISATION ALLOWED')\n\t# WRITE(6,60) EFINAL,NSTEP                                          \n\tprint(1*'\\n','  ','INTEGRATION FROM 0.0 TO ','%.1f' % EFINAL,' EV.  IN ',NSTEP,' STEPS. ') \n\t# WRITE(6,90) EFIELD,BMAG,BTHETA,WB                                 \n\tprint(1*'\\n','  ELECTRIC FIELD =','%.4f' % EFIELD,' VOLTS/CM.','\\n''  MAGNETIC FIELD =','%.4f' % BMAG,' KILOGAUSS.','\\n','  ANGLE BETWEEN ELECTRIC AND MAGNETIC FIELD =','%.3f' % BTHETA,' DEGREES.','\\n','  CYCLOTRON FREQ. =','%.3f' % WB,' RADIANS/PICOSECOND')\n\t# WRITE(6,43)\n\tprint('\\n',' USED ANISOTROPIC X-SECTIONS (OKHRIMOVSKYY ET AL) ')\n\tif(ICOUNT == 1):\n\t\t# WRITE(6,34) \n\t\tprint(' USED COUNTING IONISATION X-SECTIONS')\n\telse:\n\t\t# WRITE(6,35)\n\t\tprint(' USE GROSS IONISATION X-SECTIONS')\n\t# endif\n\t# WRITE(6,91) ESTART,NEVENT,ETHRM \n\t# print(NEVENT,conf.NEVENT)\n\tprint(1*'\\n','  INITIAL ELECTRON OR X-RAY ENERGY =','%.1f' % ESTART,' EV.','\\n',9*' ','NUMBER OF EVENTS =',NEVENT,'\\n',4*' ','THERMALISATION ENERGY =','%.2f' % ETHRM,' EV.','\\n')\n\t# WRITE(6,911) DETEFF,EXCWGHT\n\tprint(' PHOTON DETECTION EFFICIENCY USED IN FANO CALCULATION =','%.3f' % DETEFF,' %','\\n',7*' ','WEIGHT GIVEN TO EXCITATION IN FANO CALCULATION =','%.3f' % EXCWGHT,'\\n') \n\t# print(IMIP)\n\tif(IMIP == 4 or IMIP == 5):\n\t\tif(KGAS <= 0 or KGAS > NGAS):\n\t\t\t# WRITE(6,990) KGAS\n\t\t\tprint(' ERROR IN INPUT: BETA DECAY IDENTifIER KGAS=',KGAS,'  PROGRAM STOPPED:')\n\t\t\tsys.exit()\n\t\t# endif\n\t\tif(LGAS <= 0 or LGAS > 3):\n\t\t\t# WRITE(6,991) LGAS\n\t\t\tprint(' ERROR IN INPUT: BETA DECAY IDENTIFIER LGAS=',LGAS,'  PROGRAM STOPPED:')\n\t\t\tsys.exit() \n\t\t# endif\n\t\t# WRITE(6,88) KGAS,LGAS\n\t\tprint('\\n  BETA DECAY IN GAS NO =',KGAS,'\\n  IF MOLECULE : BETA DECAY IN ATOMIC COMPONENT =',LGAS,'\\n')\n\t# endif\n\tif(NDVEC == 2):\n\t\t# WRITE(6,915)\n\t\tprint('  BETA OR X-RAY IN RANDOM DIRECTION TO E-FIELD')\n\t\tpass\n\telse:\n\t\t# endif\n\t\tif(abs(numpy.cos(THETA)) < 1.e-9 and IMIP > 2):\n\t\t\t# WRITE(6,92)\n\t\t\tprint('  BETA OR X-RAY PERP# endICULAR TO E-FIELD IN X-Y PLANE')  \n\t\tif(abs(numpy.cos(THETA)) < 1.e-9 and IMIP == 2):\n\t\t\t# WRITE(6,922)\n\t\t\tprint('  ELECTRON BEAM ALONG X DIRECTION')\n\t\tif(numpy.cos(THETA)== 1.0):\n\t\t\t# WRITE(6,93)\n\t\t\tprint('  E-BEAM,BETA OR X-RAY ALONG Z-AXIS IN E-FIELD DIRECTION')\n\t\tif(numpy.cos(THETA)== -1.0):\n\t\t\t# WRITE(6,94)\n\t\t\tprint('  E-BEAM,BETA OR X-RAY ALONG Z-AXIS OPPOSITE TO E-FIELD DIRECTION')     \n\t# 95  WRITE(6,96) TCFMAX1 \n\n\tprint(\"TCFMAX1\",TCFMAX1,type(TCFMAX1))\n\tprint('\\n NULL COLLISION FREQUENCY = %.4f *(10**12/SEC)\\n'%(TCFMAX1))\n\t# WRITE(6,111)  (TCF(L),L=500,9500,1000)\n\tprint('  ','REAL COLLISION FREQUENCY AT 10 EQUALLY SPACED ENERGY INTERVALS (*10**12/SEC)','\\n')\n\tfor L in range(500,9500+1,1000):\n\t\tprint(3*' ','%.3f' % TCF[L],'\\t', end='')\n\t\tif L==4500:\n\t\t\tprint('\\n')\n\tprint('\\n')\n\n\tconf.NGAS=NGAS\n\tconf.NSTEP=NSTEP\n\tconf.NANISO=NANISO\n\tconf.EFINAL=EFINAL\n\tconf.ESTEP=ESTEP\n\tconf.AKT=AKT\n\tconf.ARY=ARY\n\tconf.TEMPC=TEMPC\n\tconf.TORR=TORR\n\tconf.IPEN=IPEN\n\tconf.KGAS=KGAS\n\tconf.LGAS=LGAS\n\tconf.DETEFF=DETEFF\n\tconf.EXCWGHT=EXCWGHT\n\tconf.NDVEC=NDVEC\n\tconf.LCMP=LCMP\n\tconf.LCFLG=LCFLG\n\tconf.LRAY=LRAY\n\tconf.LRFLG=LRFLG\n\tconf.LPAP=LPAP\n\tconf.LPFLG=LPFLG\n\tconf.LBRM=LBRM\n\tconf.LBFLG=LBFLG\n\tconf.LPEFLG =LPEFLG \n\tconf.AN1=AN1\n\tconf.AN2=AN2\n\tconf.AN3=AN3\n\tconf.AN4=AN4\n\tconf.AN5=AN5\n\tconf.AN6=AN6\n\tconf.AN=AN\n\tconf.FRAC=FRAC\n\tconf.TMAX=TMAX\n\tconf.SMALL=SMALL\n\tconf.API=API\n\tconf.ESTART=ESTART\n\tconf.THETA=THETA\n\tconf.PHI=PHI\n\tconf.TCFMAX=TCFMAX\n\n\tconf.TCFMAX1=TCFMAX1\n\tconf.RSTART=RSTART\n\tconf.EFIELD=EFIELD\n\tconf.ETHRM=ETHRM\n\tconf.ECUT=ECUT\n\tconf.NEVENT=NEVENT\n\tconf.IMIP=IMIP\n\tconf.IWRITE=IWRITE                      \n\tconf.EOVB=EOVB\n\tconf.WB=WB\n\tconf.BTHETA=BTHETA\n\tconf.BMAG  =BMAG  \n\tconf.DOUBLE=DOUBLE\n\n\tconf.CMINIXSC=CMINIXSC\n\n\tconf.CMINEXSC=CMINEXSC\n\n\tconf.ECLOSS=ECLOSS\n\n\tconf.WPLN=WPLN\n\n\tconf.ICOUNT=ICOUNT\n\tconf.AVPFRAC=AVPFRAC\n\tconf.CF=CF\n\n\tconf.EIN=EIN\n\n\tconf.TCF=TCF\n\n\tconf.IARRY=IARRY\n\n\tconf.RGAS=RGAS\n\n\tconf.IPN=IPN\n\n\tconf.WPL=WPL\n\n\tconf.IZBR=IZBR\n\n\tconf.IPLAST=IPLAST\n\tconf.PENFRA=PENFRA\n\tconf.NSEED =NSEED \n\tconf.NEGAS=NEGAS\n\n\tconf.LEGAS=LEGAS\n\n\tconf.IESHELL=IESHELL\n\n\tconf.IECASC  =IECASC  \n\treturn                                                            \n\t# end                                                               ", "meta": {"hexsha": "9e102cf7f4ea8d0e32badf5da38c7c35dda0b2e0", "size": 8820, "ext": "py", "lang": "Python", "max_stars_repo_path": "Printer.py", "max_stars_repo_name": "fireballpoint1/fortranTOpy", "max_stars_repo_head_hexsha": "55843a62c6f0a2f8e2a777ef70193940d3d2d141", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-26T05:10:56.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-26T05:10:56.000Z", "max_issues_repo_path": "Printer.py", "max_issues_repo_name": "fireballpoint1/fortranTOpy", "max_issues_repo_head_hexsha": "55843a62c6f0a2f8e2a777ef70193940d3d2d141", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Printer.py", "max_forks_repo_name": "fireballpoint1/fortranTOpy", "max_forks_repo_head_hexsha": "55843a62c6f0a2f8e2a777ef70193940d3d2d141", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-06-26T18:06:44.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-26T18:06:44.000Z", "avg_line_length": 25.4178674352, "max_line_length": 259, "alphanum_fraction": 0.626984127, "include": true, "reason": "import numpy", "num_tokens": 3527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.18692887382224538}}
{"text": "# Copyright 2020 Pulser Development Team\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"All built-in types of waveforms and their Waveform parent class.\"\"\"\n\nfrom __future__ import annotations\n\nfrom abc import ABC, abstractmethod\nimport functools\nimport inspect\nimport itertools\nimport sys\nfrom sys import version_info\nfrom types import FunctionType\nfrom typing import Any, cast, Optional, Tuple, Union\nimport warnings\n\nfrom matplotlib.axes import Axes\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy.typing import ArrayLike\nimport scipy.interpolate as interpolate\n\n# from pulser.parametrized import Parametrized, ParamObj\n# from pulser.parametrized.decorators import parametrize\n# from pulser.json.utils import obj_to_dict\n\nif version_info[:2] >= (3, 8):  # pragma: no cover\n    from functools import cached_property\nelse:  # pragma: no cover\n    try:\n        from backports.cached_property import cached_property  # type: ignore\n    except ImportError:\n        raise ImportError(\n            \"Using pulser with Python version 3.7 requires the\"\n            \" `backports.cached-property` module. Install it by running\"\n            \" `pip install backports.cached-property`.\"\n        )\n\n\nclass Waveform(ABC):\n    \"\"\"The abstract class for a pulse's waveform.\"\"\"\n\n    # def __new__(cls, *args, **kwargs):  # type: ignore\n    #     \"\"\"Creates a Waveform instance or a ParamObj depending on the input.\"\"\"\n    #     for x in itertools.chain(args, kwargs.values()):\n    #         if isinstance(x, Parametrized):\n    #             return ParamObj(cls, *args, **kwargs)\n    #     else:\n    #         return object.__new__(cls)\n\n    def __init__(self, duration: int): # (self, duration: Union[int, Parametrized]):\n        \"\"\"Initializes a waveform with a given duration.\n\n        Args:\n            duration (int): The waveforms duration (in ns).\n        \"\"\"\n        duration = cast(int, duration)\n        try:\n            _duration = int(duration)\n        except (TypeError, ValueError):\n            raise TypeError(\n                \"duration needs to be castable to an int but \"\n                f\"type {type(duration)} was provided.\"\n            )\n        if _duration <= 0:\n            raise ValueError(\n                \"A waveform must have a positive duration, \"\n                + f\"not {duration}.\"\n            )\n        elif duration - _duration != 0:\n            warnings.warn(\n                f\"A waveform duration of {duration} ns is below the\"\n                \" supported precision of 1 ns. It was rounded down \"\n                + f\"to {_duration} ns.\",\n                stacklevel=3,\n            )\n\n        self._duration = _duration\n\n    @property\n    @abstractmethod\n    def duration(self) -> int:\n        \"\"\"The duration of the pulse (in ns).\"\"\"\n        pass\n\n    @cached_property\n    @abstractmethod\n    def _samples(self) -> np.ndarray:\n        pass\n\n    @property\n    def samples(self) -> np.ndarray:\n        \"\"\"The value at each time step that describes the waveform.\n\n        Returns:\n            np.ndarray: A numpy array with a value for each time step.\n        \"\"\"\n        return self._samples.copy()\n\n    @property\n    def first_value(self) -> float:\n        \"\"\"The first value in the waveform.\"\"\"\n        return float(self[0])\n\n    @property\n    def last_value(self) -> float:\n        \"\"\"The last value in the waveform.\"\"\"\n        return float(self[-1])\n\n    @property\n    def integral(self) -> float:\n        \"\"\"Integral of the waveform (time in ns, value in rad/µs).\"\"\"\n        return float(np.sum(self.samples)) * 1e-3  # ns * rad/µs = 1e-3\n\n    def draw(self) -> None:\n        \"\"\"Draws the waveform.\"\"\"\n        fig, ax = plt.subplots()\n        self._plot(ax, \"rad/µs\")\n\n        plt.show()\n\n    def change_duration(self, new_duration: int) -> Waveform:\n        \"\"\"Returns a new waveform with modified duration.\n\n        Args:\n            new_duration(int): The duration of the new waveform.\n        \"\"\"\n        raise NotImplementedError(\n            f\"{self.__class__.__name__} does not support\"\n            \" modifications to its duration.\"\n        )\n\n    # @abstractmethod\n    # def _to_dict(self) -> dict[str, Any]:\n    #     pass\n\n    @abstractmethod\n    def __str__(self) -> str:\n        pass\n\n    @abstractmethod\n    def __repr__(self) -> str:\n        pass\n\n    def __getitem__(\n        self, index_or_slice: Union[int, slice]\n    ) -> Union[float, np.ndarray]:\n        if isinstance(index_or_slice, slice):\n            s: slice = self._check_slice(index_or_slice)\n            return cast(np.ndarray, self._samples[s])\n        else:\n            index: int = self._check_index(index_or_slice)\n            return cast(float, self._samples[index])\n\n    def _check_index(self, i: int) -> int:\n        if i < -self.duration or i >= self.duration:\n            raise IndexError(\n                \"Index ('index_or_slice' = \"\n                f\"{i}) must be in the range \"\n                f\"0~{self.duration-1}, or \"\n                f\"{-self.duration}~-1 from the end.\"\n            )\n        return i if i >= 0 else self.duration + i\n\n    def _check_slice(self, s: slice) -> slice:\n        if s.step is not None and s.step != 1:\n            raise IndexError(\"The step of the slice must be None or 1.\")\n\n        # Transform start and stop indexes into positive or null values\n        # since they can be omitted (None) or negative (end-indexing)\n        start = (\n            0\n            if s.start is None\n            else (s.start if s.start >= 0 else self.duration + s.start)\n        )\n        stop = (\n            self.duration\n            if s.stop is None\n            else (s.stop if s.stop >= 0 else self.duration + s.stop)\n        )\n\n        # Correct out of bounds ranges\n        if start < 0:\n            start = 0\n        if stop < 0:\n            stop = 0\n        if start > self.duration:\n            start = self.duration\n        if stop > self.duration:\n            stop = self.duration\n        if stop < start:\n            stop = start\n\n        return slice(start, stop)\n\n    @abstractmethod\n    def __mul__(self, other: float) -> Waveform:\n        pass\n\n    def __neg__(self) -> Waveform:\n        return self.__mul__(-1.0)\n\n    def __truediv__(self, other: float) -> Waveform:\n        if other == 0:\n            raise ZeroDivisionError(\"Can't divide a waveform by zero.\")\n        else:\n            return self.__mul__(1 / other)\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, Waveform):\n            return False\n        elif self.duration != other.duration:\n            return False\n        else:\n            return bool(np.all(np.isclose(self.samples, other.samples)))\n\n    def __hash__(self) -> int:\n        return hash(tuple(self.samples))\n\n    def _plot(\n        self, ax: Axes, ylabel: str, color: Optional[str] = None\n    ) -> None:\n        ax.set_xlabel(\"t (ns)\")\n        ts = np.arange(self.duration)\n        if color:\n            ax.set_ylabel(ylabel, color=color, fontsize=14)\n            ax.plot(ts, self.samples, color=color)\n            ax.tick_params(axis=\"y\", labelcolor=color)\n            ax.axhline(0, color=color, linestyle=\":\", linewidth=0.5)\n        else:\n            ax.set_ylabel(ylabel, fontsize=14)\n            ax.plot(ts, self.samples, 'o-')\n            ax.axhline(0, color=\"black\", linestyle=\":\", linewidth=0.5)\n\n\nclass LinearWaveform(Waveform):\n    \"\"\"A linear ramp waveform.\n\n    Args:\n        duration (int): The waveform duration (in ns).\n        start (float): The initial value (in rad/µs).\n        stop (float): The final value (in rad/µs).\n    \"\"\"\n\n    def __init__(\n        self,\n        duration: int, # Union[int, Parametrized],\n        start: float, # Union[float, Parametrized],\n        stop: float, # Union[float, Parametrized],\n    ):\n        \"\"\"Initializes a linear waveform.\"\"\"\n        super().__init__(duration)\n        start = cast(float, start)\n        self._start: float = float(start)\n        stop = cast(float, stop)\n        self._stop: float = float(stop)\n\n    @property\n    def duration(self) -> int:\n        \"\"\"The duration of the pulse (in ns).\"\"\"\n        return self._duration\n\n    @cached_property\n    def _samples(self) -> np.ndarray:\n        \"\"\"The value at each time step that describes the waveform.\n\n        Returns:\n            numpy.ndarray: A numpy array with a value for each time step.\n        \"\"\"\n        return np.linspace(self._start, self._stop, num=self._duration)\n\n    @property\n    def slope(self) -> float:\n        r\"\"\"Slope of the ramp, in :math:`s^{-15}`.\"\"\"\n        return (self._stop - self._start) / self._duration\n\n    def change_duration(self, new_duration: int) -> LinearWaveform:\n        \"\"\"Returns a new waveform with modified duration.\n\n        Args:\n            new_duration(int): The duration of the new waveform.\n\n        Returns:\n            LinearWaveform: The new waveform with the given duration.\n        \"\"\"\n        return LinearWaveform(new_duration, self._start, self._stop)\n\n    # def _to_dict(self) -> dict[str, Any]:\n    #     return obj_to_dict(self, self._duration, self._start, self._stop)\n\n    def __str__(self) -> str:\n        return f\"LinearWaveform({self._start:.3g}->{self._stop:.3g} rad/µs)\"\n\n    def __repr__(self) -> str:\n        return (\n            f\"LinearWaveform({self._duration} ns, \"\n            + f\"{self._start:.3g}->{self._stop:.3g} rad/µs)\"\n        )\n\n    def __mul__(self, other: float) -> LinearWaveform:\n        k = float(other)\n        return LinearWaveform(self._duration, self._start * k, self._stop * k)\n\n\n\nclass ConstantWaveform(Waveform):\n    \"\"\"A waveform of constant value.\n\n    Args:\n        duration (int): The waveform duration (in ns).\n        value (float): The modulation value (in rad/µs).\n    \"\"\"\n\n    def __init__(\n        self,\n        duration: int, # Union[int, Parametrized],\n        value: float, # Union[float, Parametrized],\n    ):\n        \"\"\"Initializes a constant waveform.\"\"\"\n        super().__init__(duration)\n        value = cast(float, value)\n        self._value = float(value)\n\n    @property\n    def duration(self) -> int:\n        \"\"\"The duration of the pulse (in ns).\"\"\"\n        return self._duration\n\n    @cached_property\n    def _samples(self) -> np.ndarray:\n        \"\"\"The value at each time step that describes the waveform.\n\n        Returns:\n            numpy.ndarray: A numpy array with a value for each time step.\n        \"\"\"\n        return np.full(self.duration, self._value)\n\n    def change_duration(self, new_duration: int) -> ConstantWaveform:\n        \"\"\"Returns a new waveform with modified duration.\n\n        Args:\n            new_duration(int): The duration of the new waveform.\n\n        Returns:\n            ConstantWaveform: The new waveform with the given duration.\n        \"\"\"\n        return ConstantWaveform(new_duration, self._value)\n\n    # def _to_dict(self) -> dict[str, Any]:\n    #     return obj_to_dict(self, self._duration, self._value)\n\n    def __str__(self) -> str:\n        return (\n            f\"ConstantWaveform({self._duration} ns, \"\n            + f\"{self._value:.3g} rad/µs)\"\n        )\n\n    def __repr__(self) -> str:\n        return (\n            f\"ConstantWaveform({self._duration} ns, \"\n            + f\"{self._value:.3g} rad/µs)\"\n        )\n\n    def __mul__(self, other: float) -> ConstantWaveform:\n        return ConstantWaveform(self._duration, self._value * float(other))\n\n\nclass CompositeWaveform(Waveform):\n    \"\"\"A waveform combining multiple smaller waveforms.\n\n    Args:\n        waveforms(Waveform): Two or more waveforms to combine.\n    \"\"\"\n\n    def __init__(self, *waveforms: Waveform):\n        \"\"\"Initializes a waveform from multiple waveforms.\"\"\"\n        if len(waveforms) < 2:\n            raise ValueError(\n                \"Needs at least two waveforms to form a \" \"CompositeWaveform.\"\n            )\n        waveforms = cast(Tuple[Waveform], waveforms)\n        for wf in waveforms:\n            self._validate(wf)\n\n        self._waveforms = list(waveforms)\n\n    @property\n    def duration(self) -> int:\n        \"\"\"The duration of the pulse (in ns).\"\"\"\n        duration = 0\n        for wf in self._waveforms:\n            duration += wf.duration\n        return duration\n\n    @cached_property\n    def _samples(self) -> np.ndarray:\n        \"\"\"The value at each time step that describes the waveform.\n\n        Returns:\n            numpy.ndarray: A numpy array with a value for each time step.\n        \"\"\"\n        return cast(\n            np.ndarray, np.concatenate([wf.samples for wf in self._waveforms])\n        )\n\n    @property\n    def waveforms(self) -> list[Waveform]:\n        \"\"\"The waveforms encapsulated in the composite waveform.\"\"\"\n        return list(self._waveforms)\n\n    def _validate(self, waveform: Waveform) -> None:\n        if not isinstance(waveform, Waveform):\n            raise TypeError(\n                f\"{waveform!r} is not a valid waveform. \"\n                \"Please provide a valid Waveform.\"\n            )\n\n    # def _to_dict(self) -> dict[str, Any]:\n    #     return obj_to_dict(self, *self._waveforms)\n\n    def __str__(self) -> str:\n        contents_list = [\"{!r}\"] * len(self._waveforms)\n        contents = \", \".join(contents_list)\n        contents = contents.format(*self._waveforms)\n        return f\"Composite({contents})\"\n\n    def __repr__(self) -> str:\n        return f\"CompositeWaveform({self.duration} ns, {self._waveforms!r})\"\n\n    def __mul__(self, other: float) -> CompositeWaveform:\n        return CompositeWaveform(*(wf * other for wf in self._waveforms))\n\n\nclass CustomWaveform(Waveform):\n    \"\"\"A custom waveform.\n\n    Args:\n        samples (array_like): The modulation values at each time step\n            (in rad/µs). The number of samples dictates the duration, in ns.\n    \"\"\"\n\n    def __init__(self, samples: ArrayLike):\n        \"\"\"Initializes a custom waveform.\"\"\"\n        samples_arr = np.array(samples, dtype=float)\n        self._samples: np.ndarray = samples_arr\n        super().__init__(len(samples_arr))\n\n    @property\n    def duration(self) -> int:\n        \"\"\"The duration of the pulse (in ns).\"\"\"\n        return self._duration\n\n    @cached_property\n    def _samples(self) -> np.ndarray:\n        \"\"\"The value at each time step that describes the waveform.\n\n        Returns:\n            numpy.ndarray: A numpy array with a value for each time step.\n        \"\"\"\n        # self._samples is already cached when initialized in __init__\n        pass\n\n    # def _to_dict(self) -> dict[str, Any]:\n    #     return obj_to_dict(self, self._samples)\n\n    def __str__(self) -> str:\n        return \"Custom\"\n\n    def __repr__(self) -> str:\n        return f\"CustomWaveform({self.duration} ns, {self.samples!r})\"\n\n    def __mul__(self, other: float) -> CustomWaveform:\n        return CustomWaveform(self._samples * float(other))\n\n\nclass InterpolatedWaveform(Waveform):\n    \"\"\"Creates a waveform from interpolation of a set of data points.\n\n    Args:\n        duration (int): The waveform duration (in ns).\n        values (ArrayLike): Values of the interpolation points (in rad/µs).\n        times (Optional[ArrayLike]): Fractions of the total duration (between 0\n            and 1), indicating where to place each value on the time axis. If\n            not given, the values are spread evenly throughout the full\n            duration of the waveform.\n        interpolator (str = \"PchipInterpolator\"): The SciPy interpolation class\n            to use. Supports \"PchipInterpolator\" and \"interp1d\".\n        **interpolator_kwargs: Extra parameters to give to the chosen\n            interpolator class.\n    \"\"\"\n\n    def __init__(\n        self,\n        duration: int, # Union[int, Parametrized],\n        values: ArrayLike, # Union[ArrayLike, Parametrized],\n        times: Optional[ArrayLike] = None, # Optional[Union[ArrayLike, Parametrized]] = None,\n        interpolator: str = \"PchipInterpolator\",\n        **interpolator_kwargs: Any,\n    ):\n        \"\"\"Initializes a new InterpolatedWaveform.\"\"\"\n        super().__init__(duration)\n        self._values = np.array(values, dtype=float)\n        if times is not None:\n            times_ = np.array(times, dtype=float)\n            if len(times_) != len(self._values):\n                raise ValueError(\n                    \"When specified, the number of time coordinates in `times`\"\n                    f\" ({len(times_)}) must match the number of `values` \"\n                    f\"({len(self._values)}).\"\n                )\n            if np.any(times_ < 0):\n                raise ValueError(\n                    \"All values in `times` must be greater than or equal to 0.\"\n                )\n            if np.any(times_ > 1):\n                raise ValueError(\n                    \"All values in `times` must be less than or equal to 1.\"\n                )\n            unique_times = np.unique(times)  # Sorted array of unique values\n            if len(times_) != len(unique_times):\n                raise ValueError(\n                    \"`times` must be an array of non-repeating values.\"\n                )\n            self._times = times_\n        else:\n            self._times = np.linspace(0, 1, num=len(self._values))\n\n        valid_interpolators = (\"PchipInterpolator\", \"interp1d\")\n        if interpolator not in valid_interpolators:\n            raise ValueError(\n                f\"Invalid interpolator '{interpolator}', only \"\n                \"accepts: \" + \", \".join(valid_interpolators)\n            )\n        interp_cls = getattr(interpolate, interpolator)\n        self._data_pts = np.array(\n            [\n                (round(t), v)\n                for t, v in zip(\n                    self._times * (self._duration - 1), self._values\n                )\n            ]\n        )\n        self._interp_func = interp_cls(\n            self._data_pts[:, 0], self._data_pts[:, 1], **interpolator_kwargs\n        )\n        self._kwargs: dict[str, Any] = {\n            \"times\": times,\n            \"interpolator\": interpolator,\n            **interpolator_kwargs,\n        }\n\n    @property\n    def duration(self) -> int:\n        \"\"\"The duration of the pulse (in ns).\"\"\"\n        return self._duration\n\n    @cached_property\n    def _samples(self) -> np.ndarray:\n        \"\"\"The value at each time step that describes the waveform.\"\"\"\n        return cast(\n            np.ndarray,\n            np.round(\n                self._interp_func(np.arange(self._duration)), decimals=9\n            ),  # Rounds to the order of Hz\n        )\n\n    @property\n    def interp_function(\n        self,\n    ) -> Union[interpolate.PchipInterpolator, interpolate.interp1d]:\n        \"\"\"The interpolating function.\"\"\"\n        return self._interp_func\n\n    @property\n    def data_points(self) -> np.ndarray:\n        \"\"\"Points (t[ns], value[rad/µs]) that define the interpolation.\"\"\"\n        return self._data_pts.copy()\n\n    def change_duration(self, new_duration: int) -> InterpolatedWaveform:\n        \"\"\"Returns a new waveform with modified duration.\n\n        Args:\n            new_duration(int): The duration of the new waveform.\n\n        Returns:\n            InterpolatedWaveform: The new waveform with the same coordinates\n            for interpolation but a new duration.\n        \"\"\"\n        return InterpolatedWaveform(new_duration, self._values, **self._kwargs)\n\n    def _plot(\n        self, ax: Axes, ylabel: str, color: Optional[str] = None\n    ) -> None:\n        super()._plot(ax, ylabel, color=color)\n        ax.scatter(self._data_pts[:, 0], self._data_pts[:, 1], c=color)\n\n    # def _to_dict(self) -> dict[str, Any]:\n    #     return obj_to_dict(self, self._duration, self._values, **self._kwargs)\n\n    def __str__(self) -> str:\n        coords = [f\"({int(x)}, {y:.4g})\" for x, y in self.data_points]\n        return f\"InterpolatedWaveform(Points: {', '.join(coords)})\"\n\n    def __repr__(self) -> str:\n        interp_str = f\", Interpolator={self._kwargs['interpolator']})\"\n        return self.__str__()[:-1] + interp_str\n\n    def __mul__(self, other: float) -> InterpolatedWaveform:\n        return InterpolatedWaveform(\n            self._duration, self._values * other, **self._kwargs\n        )\n\n\n# # To replicate __init__'s signature in __new__ for every Waveform subclass\n# def _copy_func(f: FunctionType) -> FunctionType:\n#     return FunctionType(\n#         f.__code__,\n#         f.__globals__,\n#         name=f.__name__,\n#         argdefs=f.__defaults__,\n#         closure=f.__closure__,\n#     )\n\n\n# for m in inspect.getmembers(sys.modules[__name__], inspect.isclass):\n#     if m[1].__module__ == __name__:\n#         _new = _copy_func(m[1].__new__)\n#         m[1].__new__ = functools.update_wrapper(_new, m[1].__init__)\n", "meta": {"hexsha": "62bea84deb38052e6930b751f3f3e2bc611aa775", "size": 21041, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/braket/analog/quera/waveforms.py", "max_stars_repo_name": "maolinml/amazon-braket-sdk-python", "max_stars_repo_head_hexsha": "48431815c75be592ec1ee1c5952d90e777df0a13", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/braket/analog/quera/waveforms.py", "max_issues_repo_name": "maolinml/amazon-braket-sdk-python", "max_issues_repo_head_hexsha": "48431815c75be592ec1ee1c5952d90e777df0a13", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/braket/analog/quera/waveforms.py", "max_forks_repo_name": "maolinml/amazon-braket-sdk-python", "max_forks_repo_head_hexsha": "48431815c75be592ec1ee1c5952d90e777df0a13", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8765625, "max_line_length": 93, "alphanum_fraction": 0.5913217052, "include": true, "reason": "import numpy,from numpy,import scipy", "num_tokens": 4922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.18681032198916772}}
{"text": "\"\"\"\n# @Time    : 2021/7/2 5:22 下午\n# @Author  : hezhiqiang01\n# @Email   : hezhiqiang01@baidu.com\n# @File    : env.py\n\"\"\"\n#只需要编写这一部分的代码，就可以无缝衔接MAPPO。\nimport numpy as np\n\nimport math\nimport gym\nfrom gym import spaces, logger\nfrom gym.utils import seeding\n\nclass Env(object):\n    \"\"\"\n    # 环境中的智能体\n    \"\"\"\n    def __init__(self, i):\n        # self.agent_num = 3  # 设置智能体(小飞机)的个数，这里设置为两个\n        # self.obs_dim = 4  # 设置智能体的观测纬度14\n        # self.action_dim = 2  # 设置智能体的动作纬度，这里假定为一个五个纬度的\n\n\n\n       #CartPoleEnv\n\n        # # Angle limit set to 2 * theta_threshold_radians so failing observation\n        self.agent_num = 1  # 设置智能体的个数，这里设置为两个\n        self.obs_dim = 4  # 设置智能体的观测纬度\n        self.action_dim = 2  # 设置智能体的动作纬度，这里假定为一个五个纬度的\n\n        self.gravity = 9.8\n        self.masscart = 1.0\n        self.masspole = 0.1\n        self.total_mass = (self.masspole + self.masscart)\n        self.length = 0.5  # actually half the pole's length\n        self.polemass_length = (self.masspole * self.length)\n        self.force_mag = 10.0\n        self.tau = 0.02  # seconds between state updates\n        self.kinematics_integrator = 'euler'  # 运动学积分仪\n\n        # Angle at which to fail the episode\n        self.theta_threshold_radians = 12 * 2 * math.pi / 360\n        self.x_threshold = 2.4\n        # is still within bounds.\n        high = np.array([self.x_threshold * 2,\n                         np.finfo(np.float32).max,\n                         self.theta_threshold_radians * 2,\n                         np.finfo(np.float32).max],\n                        dtype=np.float32)\n\n        self.action_space = spaces.Discrete(2)  # env.step(0) ：小车向左，env.step(1) ：小车向右.定义了一个变量空间范围为[0,2) 之间的整数\n        self.observation_space = spaces.Box(-high, high, dtype=np.float32)  # ,义了一个取值范围在（-10，10）的变量 维度为1\n\n        self.seed()\n        self.viewer = None\n        self.state = None\n\n        self.steps_beyond_done = None\n\n\n\n    def seed(self, seed=None):\n        self.np_random, seed = seeding.np_random(seed)\n        return [seed]\n\n    def reset(self):\n        \"\"\"\n        # self.agent_num设定为2个智能体时，返回值为一个list，每个list里面为一个shape = (self.obs_dim, )的观测数据\n        \"\"\"\n        ##new\n        self.state = self.np_random.uniform(low=-0.05, high=0.05, size=(4,))\n        self.steps_beyond_done = None\n        return np.array(self.state)\n\n\n        sub_agent_obs = []\n        for i in range(self.agent_num):\n            sub_obs = np.random.random(size=(self.obs_dim, ))#14，obs_dim\n            sub_agent_obs.append(sub_obs)\n        return sub_agent_obs\n\n\n\n\n        #new\n        # sub_agent_obs = []\n        # for i in range(self.agent_num):\n        #     self.state = self.np_random.uniform(low=-0.05, high=0.05, size=(4,))\n        #     sub_agent_obs.append(self.state)\n        # return sub_agent_obs\n\n\n# # if true, action is a number 0...N, otherwise action is a one-hot N-dimensional vector\n        #self.discrete_action_input = False\n    def step(self, actions):\n        \"\"\"\n        # self.agent_num设定为2个智能体时，actions的输入为一个2纬的list，每个list里面为一个shape = (self.action_dim, )的动作数据\n        # 默认参数情况下，输入为一个list，里面含有两个元素，因为动作纬度为5，所里每个元素shape = (5, )\n        \"\"\"\n        # sub_agent_obs = []\n        # sub_agent_reward = []\n        # sub_agent_done = []\n        # sub_agent_info = []\n        # for i in range(self.agent_num):\n        #     sub_agent_obs.append(np.random.random(size=(15,)))\n        #     sub_agent_reward.append([np.random.rand()])\n        #     sub_agent_done.append(False)\n        #     sub_agent_info.append({})\n        #\n        # #print('sub_agent_obs',sub_agent_obs, 'sub_agent_reward', sub_agent_reward, 'sub_agent_done', sub_agent_done, 'sub_agent_info',sub_agent_info)\n        # return [sub_agent_obs, sub_agent_reward, sub_agent_done, sub_agent_info]\n\n\n    #new\n        #err_msg = \"%r (%s) invalid\" % (actions, type(actions))\n        #assert self.action_space.contains(actions), err_msg\n        sub_agent_obs = []\n        sub_agent_reward = []\n        sub_agent_done = []\n        sub_agent_info = []\n        for i in range(self.agent_num):\n            x, x_dot, theta, theta_dot = self.state\n            #print(\"actions[i]\",actions)\n            force = self.force_mag if actions[i][0] == 1 else -self.force_mag\n            # if action == 1:\n            #     force = self.force_mag\n            # elif action == 0:\n            #     force = -self.force_mag\n            # else:\n            #     force = 0\n            costheta = math.cos(theta)\n            sintheta = math.sin(theta)\n\n            # For the interested reader:\n            # https://coneural.org/florian/papers/05_cart_pole.pdf\n            temp = (force + self.polemass_length * theta_dot ** 2 * sintheta) / self.total_mass\n            thetaacc = (self.gravity * sintheta - costheta * temp) / (\n                        self.length * (4.0 / 3.0 - self.masspole * costheta ** 2 / self.total_mass))\n            xacc = temp - self.polemass_length * thetaacc * costheta / self.total_mass\n\n            if self.kinematics_integrator == 'euler':\n                x = x + self.tau * x_dot\n                x_dot = x_dot + self.tau * xacc\n                theta = theta + self.tau * theta_dot\n                theta_dot = theta_dot + self.tau * thetaacc\n            else:  # semi-implicit euler\n                x_dot = x_dot + self.tau * xacc\n                x = x + self.tau * x_dot\n                theta_dot = theta_dot + self.tau * thetaacc\n                theta = theta + self.tau * theta_dot\n\n            self.state = (x, x_dot, theta, theta_dot)  # (位置x，x加速度, 偏移角度theta, 角加速度)\n            # 小车的世界，就一条x轴，\n            # 变量env.x_threshold里存放着小车坐标的最大值（=2.4），\n            # 超过这个数值，世界结束，每step()一次，就会奖励 1，直到上次done为True。\n            done = bool(\n                x < -self.x_threshold\n                or x > self.x_threshold\n                or theta < -self.theta_threshold_radians\n                or theta > self.theta_threshold_radians\n            )\n\n            if not done:\n                reward = 1.0\n            elif self.steps_beyond_done is None:\n                # Pole just fell!\n                self.steps_beyond_done = 0\n                reward = 1.0\n            else:\n                if self.steps_beyond_done == 0:\n                    logger.warn(\n                        \"You are calling 'step()' even though this \"\n                        \"environment has already returned done = True. You \"\n                        \"should always call 'reset()' once you receive 'done = \"\n                        \"True' -- any further steps are undefined behavior.\"\n                    )\n                self.steps_beyond_done += 1\n                reward = 0.0\n            sub_agent_obs.append(np.array(self.state))\n            sub_agent_reward.append(reward)\n            sub_agent_done.append(done)\n            sub_agent_info.append({})\n\n        return [sub_agent_obs, sub_agent_reward, sub_agent_done, sub_agent_info]\n", "meta": {"hexsha": "bfa3c17c3a677e2d8e76167298b52fa86a55d295", "size": 6842, "ext": "py", "lang": "Python", "max_stars_repo_path": "light_mappo-main/envs/env.py", "max_stars_repo_name": "daixiangxiang/Reinforcement_learning", "max_stars_repo_head_hexsha": "90aabba61c609c5afd445205b94ebd87a309ff7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "light_mappo-main/envs/env.py", "max_issues_repo_name": "daixiangxiang/Reinforcement_learning", "max_issues_repo_head_hexsha": "90aabba61c609c5afd445205b94ebd87a309ff7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "light_mappo-main/envs/env.py", "max_forks_repo_name": "daixiangxiang/Reinforcement_learning", "max_forks_repo_head_hexsha": "90aabba61c609c5afd445205b94ebd87a309ff7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5882352941, "max_line_length": 152, "alphanum_fraction": 0.5593393745, "include": true, "reason": "import numpy", "num_tokens": 1986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.18677015065727048}}
{"text": "# --*-- coding:utf-8 --*--\nimport numpy as np\nimport cv2\nfrom scipy import signal\n\n'''\nhelper function\n'''\ndef filterItChopOff(f, r, sp):\n    f[np.isnan(f)] = 0\n    H, W, d = f.shape\n    B = np.ones([2 * r + 1, 2 * r + 1])     # 2r+1 * 2r+1 neighbourhood\n\n    minSP = cv2.erode(sp, B, iterations=1)\n    maxSP = cv2.dilate(sp, B, iterations=1)\n\n    ind = np.where(np.logical_or(minSP != sp, maxSP != sp))\n\n    spInd = np.reshape(range(np.size(sp)), sp.shape,'F')\n\n    delta = np.zeros(f.shape)\n    delta = np.reshape(delta, (H * W, d), 'F')\n    f = np.reshape(f, (H * W, d),'F')\n\n    # calculate delta\n\n    I, J = np.unravel_index(ind, [H, W], 'C')\n    for i in range(np.size(ind)):\n        x = I[i]\n        y = J[i]\n        clipInd = spInd[max(0, x - r):min(H-1, x + r), max(0, y - r):min(W-1, y + r)]\n        diffInd = clipInd[sp[clipInd] != sp[x, y]]\n        delta[ind[i], :] = np.sum(f[diffInd, :], 1)\n    delta = np.reshape(delta, (H, W, d), 'F')\n    f = np.reshape(f, (H, W, d), 'F')\n    fFilt = np.zeros([H, W, d])\n\n    for i in range(f.shape[2]):\n        #  fFilt(:,:,i) = filter2(B, f(:,:,i));\n        tmp = signal.convolve2d(np.rot90(f[:, :, i], 2), np.rot90(np.rot90(B, 2), 2), mode=\"same\")\n        fFilt[:, :, i] = np.rot90(tmp, 2)\n    fFilt = fFilt - delta\n    return fFilt\n\n'''\nhelper function\n'''\ndef mutiplyIt(AtA_1, Atb):\n    result = np.zeros([Atb.shape[0], Atb.shape[1], 3])\n    result[:, :, 0] = np.multiply(AtA_1[:, :, 0], Atb[:, :, 0]) + np.multiply(AtA_1[:, :, 1],\n                                                                              Atb[:, :, 1]) + np.multiply(\n        AtA_1[:, :, 2], Atb[:, :, 2])\n    result[:, :, 1] = np.multiply(AtA_1[:, :, 1], Atb[:, :, 0]) + np.multiply(AtA_1[:, :, 3],\n                                                                              Atb[:, :, 1]) + np.multiply(\n        AtA_1[:, :, 4], Atb[:, :, 2])\n    result[:, :, 2] = np.multiply(AtA_1[:, :, 2], Atb[:, :, 0]) + np.multiply(AtA_1[:, :, 4],\n                                                                              Atb[:, :, 1]) + np.multiply(\n        AtA_1[:, :, 5], Atb[:, :, 2])\n    return result\n\n'''\nhelper function\n'''\ndef invertIt(AtA):\n    AtA_1 = np.zeros([AtA.shape[0], AtA.shape[1], 6])\n    AtA_1[:, :, 0] = np.multiply(AtA[:, :, 3], AtA[:, :, 5]) - np.multiply(AtA[:, :, 4], AtA[:, :, 4])\n    AtA_1[:, :, 1] = -np.multiply(AtA[:, :, 1], AtA[:, :, 5]) + np.multiply(AtA[:, :, 2], AtA[:, :, 4])\n    AtA_1[:, :, 2] = np.multiply(AtA[:, :, 1], AtA[:, :, 4]) - np.multiply(AtA[:, :, 2], AtA[:, :, 3])\n    AtA_1[:, :, 3] = np.multiply(AtA[:, :, 0], AtA[:, :, 5]) - np.multiply(AtA[:, :, 2], AtA[:, :, 2])\n    AtA_1[:, :, 4] = -np.multiply(AtA[:, :, 0], AtA[:, :, 4]) + np.multiply(AtA[:, :, 1], AtA[:, :, 2])\n    AtA_1[:, :, 5] = np.multiply(AtA[:, :, 0], AtA[:, :, 3]) - np.multiply(AtA[:, :, 1], AtA[:, :, 1])\n\n    x1 = np.multiply(AtA[:, :, 0], AtA_1[:, :, 0])\n    x2 = np.multiply(AtA[:, :, 1], AtA_1[:, :, 1])\n    x3 = np.multiply(AtA[:, :, 2], AtA_1[:, :, 2])\n\n    detAta = x1 + x2 + x3\n    return AtA_1, detAta\n\n'''\nCompute the direction of gravity\nN: normal field\niter: number of 'big' iterations\n'''\ndef getYDir(N, angleThresh, iter, y0):\n    y = y0\n    for i in range(len(angleThresh)):\n        thresh = np.pi * angleThresh[i] / 180   # convert it to radian measure\n        y = getYDirHelper(N, y, thresh, iter[i])\n    return y\n\n'''\nN: HxWx3 matrix with normal at each pixel.\ny0: the initial gravity direction\nthresh: in degrees the threshold for mapping to parallel to gravity and perpendicular to gravity\niter: number of iterations to perform\n'''\ndef getYDirHelper(N, y0, thresh, num_iter):\n    dim = N.shape[0] * N.shape[1]\n\n    # change the third dimension to the first-order. (480, 680, 3) => (3, 480, 680)\n    nn = np.swapaxes(np.swapaxes(N,0,2),1,2)\n    nn = np.reshape(nn, (3, dim), 'F')\n\n    # remove these whose number is NAN\n    idx = np.where(np.invert(np.isnan(nn[0,:])))[0]\n    nn = nn[:,idx]\n\n    # Set it up as a optimization problem\n    yDir = y0;\n    for i in range(num_iter):\n        sim0 = np.dot(yDir.T, nn)\n        indF = abs(sim0) > np.cos(thresh)       # calculate 'floor' set.    |sin(theta)| < sin(thresh) ==> |cos(theta)| > cos(thresh)\n        indW = abs(sim0) < np.sin(thresh)       # calculate 'wall' set.\n        if(len(indF.shape) == 2):\n            NF = nn[:, indF[0,:]]\n            NW = nn[:, indW[0,:]]\n        else:\n            NF = nn[:, indF]\n            NW = nn[:, indW]\n        A = np.dot(NW, NW.T) - np.dot(NF, NF.T)\n        b = np.zeros([3,1])\n        c = NF.shape[1]\n        w,v = np.linalg.eig(A)      # w:eigenvalues; v:eigenvectors\n        min_ind = np.argmin(w)      # min index\n        newYDir = v[:,min_ind]\n        yDir = newYDir * np.sign(np.dot(yDir.T, newYDir))\n    return yDir\n\n'''\ngetRMatrix: Generate a rotation matrix that\n            if yf is a scalar, rotates about axis yi by yf degrees\n            if yf is an axis, rotates yi to yf in the direction given by yi x yf\nInput: yi is an axis 3x1 vector\n       yf could be a scalar of axis\n\n'''\ndef getRMatrix(yi, yf):\n    if (np.isscalar(yf)):\n        ax = yi / np.linalg.norm(yi)        # norm(A) = max(svd(A))\n        phi = yf\n    else:\n        yi = yi / np.linalg.norm(yi)\n        yf = yf / np.linalg.norm(yf)\n        ax = np.cross(yi.T, yf.T).T\n        ax = ax / np.linalg.norm(ax)\n        # find angle of rotation\n        phi = np.degrees(np.arccos(np.dot(yi.T, yf)))\n\n    if (abs(phi) > 0.1):\n        phi = phi * (np.pi / 180)\n\n        s_hat = np.array([[0, -ax[2], ax[1]],\n                          [ax[2], 0, -ax[0]],\n                          [-ax[1], ax[0], 0]])\n        R = np.eye(3) + np.sin(phi) * s_hat + (1 - np.cos(phi)) * np.dot(s_hat, s_hat)      # dot???\n    else:\n        R = np.eye(3)\n    return R\n\n'''\nCalibration of gravity direction \n'''\ndef rotatePC(pc, R):\n    if(np.array_equal(R, np.eye(3))):\n        return pc\n    else:\n        dim = pc.shape[0] * pc.shape[1]\n        pc = np.swapaxes(np.swapaxes(pc, 0, 2), 1, 2)\n        res = np.reshape(pc, (3, dim), 'F')\n        res = np.dot(R, res)\n        res = np.reshape(res, pc.shape, 'F')\n        res = np.swapaxes(np.swapaxes(res, 0, 1), 1, 2)\n        return res", "meta": {"hexsha": "ce3390491913d8fb6eaf8c753c8070fb2ae4936b", "size": 6185, "ext": "py", "lang": "Python", "max_stars_repo_path": "samples/elevator/data_generation/depth2hha/utils/util.py", "max_stars_repo_name": "reithmeier/Mask_RCNN", "max_stars_repo_head_hexsha": "4e7d93adf8c244dc541c7fcc959d5e994c8dd9b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-08-20T19:02:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:55.000Z", "max_issues_repo_path": "samples/elevator/data_generation/depth2hha/utils/util.py", "max_issues_repo_name": "reithmeier/Mask_RCNN", "max_issues_repo_head_hexsha": "4e7d93adf8c244dc541c7fcc959d5e994c8dd9b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-03-19T00:34:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T23:47:16.000Z", "max_forks_repo_path": "samples/elevator/data_generation/depth2hha/utils/util.py", "max_forks_repo_name": "reithmeier/Mask_RCNN", "max_forks_repo_head_hexsha": "4e7d93adf8c244dc541c7fcc959d5e994c8dd9b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-09T02:20:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T09:45:03.000Z", "avg_line_length": 35.5459770115, "max_line_length": 133, "alphanum_fraction": 0.489894907, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.3415825128436339, "lm_q1q2_score": 0.18675619686788977}}
{"text": "# -*- coding: utf-8 -*-\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n#\n# Copyright (C) 2014-2018 GEM Foundation\n#\n# OpenQuake is free software: you can redistribute it and/or modify it\n# under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# OpenQuake is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"\nModule exports :class:'GarciaEtAl2005SSlab',\n:class:'GarciaEtAl2005SSlabVert'\n\n\"\"\"\nimport numpy as np\n# standard acceleration of gravity in m/s**2\nfrom scipy.constants import g\n\nfrom openquake.hazardlib.gsim.base import GMPE, CoeffsTable\nfrom openquake.hazardlib import const\nfrom openquake.hazardlib.imt import SA, PGA, PGV\n\n\nclass GarciaEtAl2005SSlab(GMPE):\n    \"\"\"\n    Implements GMPE developed by Garcia, D., Singh, S. K., Harraiz, M,\n    Ordaz, M., and Pacheco, J. F. and published in BSSA as:\n\n    \"Inslab earthquakes of Central Mexico: Peak ground-motion parameters and\n    response spectra\", vol. 95, No. 6, pp. 2272-2282.\"\n\n    The original formulation predict peak ground acceleration (PGA), in\n    cm/s*s, peak ground velocity PGV (cm/s) and 5% damped pseudo-acceleration\n    response spectra (PSA) in cm/s*s for the geometric average of the\n    maximum component of the two horizontal component of ground motion (see\n    last paragraph of Summary in pag. 2272\n\n    The GMPE predicted values for Mexican inslab events and NEHRP B site\n    condition\n\n    \"\"\"\n\n    #: Supported tectonic region type is subduction intraslab,\n    #: given that the equations have been derived using Mexican inslab\n    #: events\n    DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.SUBDUCTION_INTRASLAB\n\n    #: Supported intensity measure types are spectral acceleration,\n    #: and peak ground acceleration. See Table 2 in page 1865\n    DEFINED_FOR_INTENSITY_MEASURE_TYPES = set([\n        SA,\n        PGA,\n        PGV,\n    ])\n\n    #: Supported intensity measure component is the geometric average of\n    #  the maximum of the two horizontal components\n    #: :attr:`openquake.hazardlib.const.IMC.AVERAGE_HORIZONTAL`,\n    #: see Data processing in page 2274.\n    DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = const.IMC.AVERAGE_HORIZONTAL\n\n    #: Supported standard deviation types are inter-event, intra-event\n    #: and total\n    #: See Tables 2 and 3, page 2275.\n    DEFINED_FOR_STANDARD_DEVIATION_TYPES = set([\n        const.StdDev.TOTAL,\n        const.StdDev.INTER_EVENT,\n        const.StdDev.INTRA_EVENT\n    ])\n\n    #: No site parameters required\n    #: All data from 51 hard (NEHRP B) sites.\n    REQUIRES_SITES_PARAMETERS = set(('vs30', ))\n\n    #: Required rupture parameters are magnitude and focal depth\n    #: See equation (1) in pag 2274\n    REQUIRES_RUPTURE_PARAMETERS = set(('mag', 'hypo_depth'))\n\n    #: Required distance measure is Rrup (closest distance to fault surface for\n    #: the larger events, Mw > 6.5) or Rhypo (hypocentral distance for the\n    #: rest (both in kilometers) as explained in page 2274\n    REQUIRES_DISTANCES = set(('rrup', 'rhypo', ))\n\n    def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):\n        \"\"\"\n        See :meth:`superclass method\n        <.base.GroundShakingIntensityModel.get_mean_and_stddevs>`\n        for spec of input and result values.\n        \"\"\"\n        # Extracting dictionary of coefficients specific to required\n        # intensity measure type.\n\n        C = self.COEFFS[imt]\n        mag = rup.mag\n        hypo_depth = rup.hypo_depth\n\n        mean = self._compute_mean(C, g, mag, hypo_depth, dists, imt)\n        stddevs = self._get_stddevs(C, stddev_types, sites.vs30.shape[0])\n\n        return mean, stddevs\n\n    def _compute_mean(self, C, g, mag, hypo_depth, dists, imt):\n        \"\"\"\n        Compute mean according to equation on Table 2, page 2275.\n        \"\"\"\n\n        delta = 0.00750 * 10 ** (0.507 * mag)\n\n        # computing R for different values of mag\n        if mag < 6.5:\n            R = np.sqrt(dists.rhypo ** 2 + delta ** 2)\n        else:\n            R = np.sqrt(dists.rrup ** 2 + delta ** 2)\n\n        mean = (\n            # 1st term\n            C['c1'] + C['c2'] * mag +\n            # 2nd term\n            C['c3'] * R -\n            # 3rd term\n            C['c4'] * np.log10(R) +\n            # 4th term\n            C['c5'] * hypo_depth\n        )\n        # convert from base 10 to base e\n        if imt == PGV():\n            mean = np.log(10 ** mean)\n        else:\n            # convert from cm/s**2 to g\n            mean = np.log((10 ** mean) * 1e-2 / g)\n        return mean\n\n    def _get_stddevs(self, C, stddev_types, num_sites):\n        \"\"\"\n        Return standard deviations as defined in table 2, pag 2275.\n        \"\"\"\n\n        assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES\n                   for stddev_type in stddev_types)\n\n        # the standard deviation values are converted from base 10 to base e\n\n        stddevs = []\n        for stddev_type in stddev_types:\n            assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES\n            if stddev_type == const.StdDev.TOTAL:\n                stddevs.append(np.log(10 ** C['s_t']) + np.zeros(num_sites))\n            elif stddev_type == const.StdDev.INTRA_EVENT:\n                stddevs.append(np.log(10 ** C['s_r']) + np.zeros(num_sites))\n            elif stddev_type == const.StdDev.INTER_EVENT:\n                stddevs.append(np.log(10 ** C['s_e']) + np.zeros(num_sites))\n        return stddevs\n\n    #: Equation coefficients for geometric average of the maximum of the two\n    #: horizontal components, as described in Table 2 on pp. 2275, but\n    #: generated from a Fortran implementation code provided by Daniel Garcia\n    #: (higher precision than in the paper).\n    #: The original IMT values are defined as frequencies values.\n    COEFFS = CoeffsTable(sa_damping=5, table=\"\"\"\\\n    IMT   c1       c2        c3       c4   c5       s_t      s_r      s_e\n    0.04  0.02645  0.58792  -0.00430  1.0  0.00700  0.31829  0.30777  0.08115\n    0.05  0.10949  0.58046  -0.00433  1.0  0.00753  0.33560  0.32329  0.09005\n    0.07  0.22907  0.56961  -0.00429  1.0  0.00826  0.33640  0.32126  0.09979\n    0.10  0.40746  0.54939  -0.00414  1.0  0.00774  0.33431  0.31785  0.10358\n    0.20  0.05215  0.58676  -0.00369  1.0  0.00689  0.27971  0.24464  0.13559\n    0.30 -0.26507  0.62932  -0.00331  1.0  0.00485  0.27649  0.22833  0.15592\n    0.40 -0.55235  0.64414  -0.00280  1.0  0.00483  0.27187  0.23607  0.13484\n    0.50 -0.81731  0.67453  -0.00243  1.0  0.00351  0.26432  0.24081  0.10898\n    0.75 -1.31580  0.70924  -0.00198  1.0  0.00371  0.27422  0.25957  0.08843\n    1.00 -1.75050  0.75555  -0.00168  1.0  0.00296  0.27728  0.26232  0.08985\n    1.50 -2.30120  0.80760  -0.00144  1.0  0.00167  0.28030  0.26085  0.10261\n    2.00 -2.75190  0.84564  -0.00123  1.0  0.00137  0.26353  0.24282  0.10240\n    3.00 -3.34700  0.89255  -0.00092  1.0  0.00085  0.26279  0.22360  0.13806\n    4.00 -3.87460  0.93748  -0.00079  1.0  0.00093  0.25328  0.22226  0.12147\n    5.00 -4.26750  0.96929  -0.00074  1.0  0.00104  0.24643  0.21638  0.11793\n    pga  -0.23170  0.58726  -0.00394  1.0  0.00767  0.28520  0.26662  0.10123\n    pgv  -2.35950  0.70759  -0.00235  1.0  0.00436  0.25745  0.23917  0.09529\n    \"\"\")\n\n\nclass GarciaEtAl2005SSlabVert(GarciaEtAl2005SSlab):\n    \"\"\"\n    Extend :class:`GarciaEtAl2005SSlab`\n\n    Implements GMPE developed by Garcia, D., Singh, S. K., Harraiz, M,\n    Ordaz, M., and Pacheco, J. F. and published in BSSA as:\n\n    \"Inslab earthquakes of Central Mexico: Peak ground-motion parameters and r\n    esponse spectra\", vol. 95, No. 6, pp. 2272-2282.\"\n\n    The original formulation predict peak ground acceleration (PGA), in\n    cm/s*s, peak ground velocity PGV (cm/s) and 5% damped pseudo-acceleration\n    response spectra (PSA) in cm/s*s for the vertical component of ground\n    motion (see last paragraph of Summary in pag. 2272\n\n    The GMPE predicted values for Mexican inslab events and NEHRP B site\n\n    \"\"\"\n\n    #: Equation coefficients for Vertical Component, as described in Table 3\n    #: on pp 2275.\n    #: The original imt values are defined as frequencies values\n    COEFFS = CoeffsTable(sa_damping=5, table=\"\"\"\\\n     IMT    c1     c2      c3      c4     c5      s_t   s_r   s_e\n     0.04  -0.300  0.620  -0.0041  1.00   0.0060  0.31  0.30  0.07\n     0.05  -0.200  0.620  -0.0043  1.00   0.0070  0.32  0.31  0.08\n     0.07  -0.060  0.600  -0.0041  1.00   0.0070  0.32  0.31  0.09\n     0.10  -0.040  0.590  -0.0039  1.00   0.0070  0.31  0.29  0.11\n     0.20  -0.070  0.590  -0.0033  1.00   0.0040  0.26  0.22  0.14\n     0.30  -0.200  0.600  -0.0029  1.00   0.0030  0.26  0.22  0.15\n     0.40  -0.700  0.640  -0.0022  1.00   0.0030  0.26  0.23  0.13\n     0.50  -0.900  0.660  -0.0018  1.00   0.0020  0.26  0.23  0.11\n     0.75  -1.300  0.690  -0.0014  1.00   0.0020  0.25  0.22  0.11\n     1.00  -1.800  0.750  -0.0010  1.00   0.0010  0.27  0.24  0.12\n     1.50  -2.400  0.800  -0.0008  1.00   0.0004  0.26  0.23  0.12\n     2.00  -2.800  0.830  -0.0006  1.00  -0.0005  0.27  0.24  0.14\n     3.00  -3.300  0.880  -0.0005  1.00  -0.0004  0.28  0.23  0.17\n     4.00  -4.000  0.950  -0.0004  1.00  -0.0003  0.27  0.23  0.15\n     5.00  -4.400  0.980  -0.0003  1.00  -0.0002  0.26  0.22  0.14\n     pga   -0.400  0.600  -0.0036  1.00   0.0060  0.27  0.25  0.11\n     pgv   -2.400  0.700  -0.0018  1.00   0.0020  0.24  0.21  0.11\n    \"\"\")\n", "meta": {"hexsha": "2a7343f11a053408fca09bab3517b7d4acd2b159", "size": 9779, "ext": "py", "lang": "Python", "max_stars_repo_path": "openquake/hazardlib/gsim/garcia_2005.py", "max_stars_repo_name": "gfzriesgos/shakyground-lfs", "max_stars_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-01T00:28:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-01T00:28:24.000Z", "max_issues_repo_path": "openquake/hazardlib/gsim/garcia_2005.py", "max_issues_repo_name": "gfzriesgos/shakyground-lfs", "max_issues_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-08-31T14:14:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-11T12:53:13.000Z", "max_forks_repo_path": "openquake/hazardlib/gsim/garcia_2005.py", "max_forks_repo_name": "gfzriesgos/shakyground-lfs", "max_forks_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-08-31T14:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-17T10:06:02.000Z", "avg_line_length": 42.150862069, "max_line_length": 79, "alphanum_fraction": 0.6283873607, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.32766829425520916, "lm_q1q2_score": 0.1867226462656852}}
{"text": "# -*- coding: utf-8 -*-\nimport time\nimport numpy as np\nfrom pyodesys import ODESys as _ODESys\nfrom pyodesys.results import Result\nfrom chempy.units import get_derived_unit, unitless_in_registry, uniform, patched_numpy as pnp\nfrom .integrate import run\nfrom ._chemreac import cvode_predefined_durations_fields\n\n\nclass ODESys(_ODESys):\n\n    def __init__(self, rd, k_from_params=None, variables_from_params=None):\n        if rd.N > 1:\n            raise NotImplementedError(\"ODESys expects single bin for now\")\n        self.rd = rd\n        self.k_from_params = k_from_params\n        self.variables_from_params = variables_from_params\n\n    ny = property(lambda self: self.rd.n*self.rd.N)\n    names = property(lambda self: self.rd.substance_names)\n    latex_names = property(lambda self: self.rd.substance_latex_names)\n    param_names = property(lambda self: self.rd.param_names)\n    autonomous_interface = property(lambda self: not self.rd.logt)\n    numpy = pnp\n    # dep_by_name = True\n    # par_by_name = True\n\n    def _get_units_util(self):\n        if self.rd.unit_registry is None:\n            _dedim = lambda x: np.array(x)\n            time_u = 1\n            conc_u = 1\n            dr_u = 1\n        else:\n            _dedim = lambda x: unitless_in_registry(x, self.rd.unit_registry)\n            time_u = get_derived_unit(self.rd.unit_registry, 'time')\n            conc_u = get_derived_unit(self.rd.unit_registry, 'concentration')\n            dr_u = get_derived_unit(self.rd.unit_registry, 'doserate')\n        return locals()\n\n    def integrate(self, x, y0, params=None, integrator='cvode', **kwargs):\n        if params is not None and self.k_from_params is not None:\n            self.rd.k = self.k_from_params(self, params)\n        if 'doserate' in (params or {}):\n            self.rd.set_with_units(\n                'fields', [[self.variables_from_params['density'](self, params)*params['doserate']]])\n        if 'atol' in kwargs and isinstance(kwargs['atol'], dict):\n            kwargs['atol'] = [kwargs['atol'][k] for k in self.names]\n        integr = run(self.rd, [y0[k] for k in self.names] if isinstance(y0, dict) else y0,\n                     x, integrator=integrator, **kwargs)\n        pout = [params[k] for k in self.param_names] if self.param_names else None\n        return Result(integr.with_units('tout'), integr.with_units('Cout')[:, 0, :],\n                      pout, integr.info, self)\n\n    def chained_parameter_variation(self, durations, y0, varied_params, default_params=None,\n                                    integrate_kwargs=None, x0=None, npoints=1, numpy=None):\n        if list(varied_params) != ['doserate']:\n            raise NotImplementedError(\"For now only varied doserate is supported\")\n        if self.param_names != ['doserate']:\n            raise NotImplementedError(\"We expect doserate to be varied for now\")\n        uutil = self._get_units_util()\n        _dedim, time_u, conc_u, dr_u = [uutil[k] for k in '_dedim time_u conc_u dr_u'.split()]\n        density = _dedim(self.variables_from_params['density'](self, default_params))\n        if default_params:\n            self.rd.k = _dedim(self.k_from_params(self, default_params))\n\n        if x0 is not None:\n            assert x0 == 0*time_u\n        integrate_kwargs = integrate_kwargs or {}\n        atol = integrate_kwargs.pop('atol', 1e-8)\n        if isinstance(atol, float):\n            atol = [atol]\n        elif isinstance(atol, dict):\n            atol = [atol[k] for k in self.names]\n        rtol = integrate_kwargs.pop('rtol', 1e-8)\n        method = integrate_kwargs.pop('method', 'bdf')\n        integrator = integrate_kwargs.pop('integrator', 'cvode')\n        if integrator != 'cvode':\n            raise NotImplementedError(\"chained_parameter_variation requires cvode for now\")\n        drate = uniform(varied_params['doserate'])\n        time_cpu = time.process_time()\n        time_wall = time.time()\n        tout, yout = cvode_predefined_durations_fields(\n            self.rd, _dedim([y0[k] for k in self.names]),\n            _dedim(durations),\n            _dedim(drate*density),\n            atol=atol, rtol=rtol, method=method, npoints=npoints, **integrate_kwargs)\n        info = dict(\n            nsteps=-1,\n            nfev=self.rd.nfev,\n            njev=self.rd.njev,\n            time_wall=time.time() - time_wall,\n            time_cpu=time.process_time() - time_cpu,\n            success=True,\n            integrator=[integrator],\n            t0_set=False,\n            linear_solver=0,  # pyodesys.results.Result work-around for now (not important)\n        )\n        info.update(self.rd.last_integration_info)\n        dr_out = np.concatenate((np.repeat(drate, npoints), drate[-1:]))\n        return Result(tout*time_u, yout[:, 0, :]*conc_u, dr_out.reshape((-1, 1))*dr_u, info, self)\n", "meta": {"hexsha": "1a5e2c5d301c18fce5079eebff26031619479bf3", "size": 4778, "ext": "py", "lang": "Python", "max_stars_repo_path": "chemreac/_odesys.py", "max_stars_repo_name": "bjodah/chemreac", "max_stars_repo_head_hexsha": "dbe38a10cf6b88e66192bcc998721b61aabbd9dc", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2015-03-11T21:46:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-06T16:01:38.000Z", "max_issues_repo_path": "chemreac/_odesys.py", "max_issues_repo_name": "bjodah/chemreac", "max_issues_repo_head_hexsha": "dbe38a10cf6b88e66192bcc998721b61aabbd9dc", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2015-01-21T16:11:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-06T10:30:46.000Z", "max_forks_repo_path": "chemreac/_odesys.py", "max_forks_repo_name": "chemreac/chemreac", "max_forks_repo_head_hexsha": "dbe38a10cf6b88e66192bcc998721b61aabbd9dc", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-08-13T12:06:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T01:12:20.000Z", "avg_line_length": 46.3883495146, "max_line_length": 101, "alphanum_fraction": 0.6303892842, "include": true, "reason": "import numpy", "num_tokens": 1176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038302, "lm_q2_score": 0.3276682876897044, "lm_q1q2_score": 0.1867226377369741}}
{"text": "from datetime import datetime\nimport numpy as np\n\n# equatorial, polar radii\nlightning_ellipse_rev = {\n    # Values at launch\n    0: (6.394140e6, 6.362755e6),\n    \n    # DO.07, late 2018. First Virts revision.\n    # The GRS80 altitude + 6 km differs by about 3 m from the value above\n    # which is the exact that was provided at the time of launch. Use the\n    # original value instead of doing the math.\n    # 6.35675231414e6+6.0e3\n    1: (6.378137e6 + 14.0e3, 6.362755e6),\n}\n\ndef ltg_ellpse_rev(date):\n    \"\"\"\n    Given a date, return the lightning ellipsoid revision. The ellipsoid was\n    tuned after launch based on comparison of the GLM flash centroids to ground\n    strike locations.\n    \n    The date here refers to the operational GLM feed, and this is really\n    a convenience function for inferring the lightning ellipsoid revision. An\n    operational use of glmtools that expects data from a certain source should\n    treat the lightning ellipse revision as a configuration parameter that is\n    passed directly to the GLMDataset object (or the gridder class, which passes\n    the ellipse version along to GLMDataset). For future revisions of the\n    lightning ellipse, this allows for the processing code to be upgraded as\n    soon as the new ellipse parameter is known, and the new ellipse to be\n    chosen in a live environment as a less-surgery-requiring parameter change.\n    \n    date: datetime object for the date and time of observation\n    \n    Returns:\n    ellps_rev (int): integer used to index the lightning_ellipse_rev dict.\n    \n    \"\"\"\n    if date < datetime(2018,10,15):\n        return 0\n    else:\n        return 1\n    \ndef ltg_ellps_radii(date):\n    \"\"\"\n    Given a date, return the equatorial and polar radii of the lightning\n    ellipsoid. The ellipsoid was tuned after launch based on comparison of the\n    GLM flash centroids to ground strike locations.\n    \n    The date here refers to the operational GLM feed, and this is really\n    a convenience function for inferring the lightning ellipsoid revision. An\n    operational use of glmtools that expects data from a certain source should\n    treat the lightning ellipse revision as a configuration parameter that is\n    passed directly to the GLMDataset object (or the gridder class, which passes\n    the ellipse version along to GLMDataset). For future revisions of the\n    lightning ellipse, this allows for the processing code to be upgraded as\n    soon as the new ellipse parameter is known, and the new ellipse to be\n    chosen in a live environment as a less-surgery-requiring parameter change.\n    \n    date: datetime object for the date and time of observation\n    \n    Returns: re_ltg_ellps, rp_ltg_ellps (meters): equatorial and polar radii\n        of the lightning ellipsoid, respectively.\n    \"\"\"\n    re_ltg_ellps, rp_ltg_ellps = lightning_ellipse_rev[ltg_ellps_rev(date)]\n    return re_ltg_ellps, rp_ltg_ellps\n\ndef ltg_ellps_lon_lat_to_fixed_grid(lon, lat, sat_lon, ellipse_rev,\n        re_grs80 = 6.378137e6, rp_grs80 = 6.35675231414e6,\n        sat_grs80_height=35.786023e6 ):\n    \"\"\" \n    lon, lat (degrees): from GLM L2 file, fixed grid coords x, y as \n    defined in the L1b PUG. x,y corresponds to beta, alpha.\n        \n    sat_lon (degrees): nominal nadir longitude of the satellite\n\n    re_ltg_ellps, rp_ltg_ellps (meters): equatorial and polar radii \n        for the lightning ellipse. Defaults to values set at launch\n        of GOES-16 GLM (good at least through early Jan 2018).\n\n    sat_grs80_height (meters): height of the satellite above the GRS80 \n        ellipsoid. This is 'perspective_point_height' in the GOES-R L1b PUG, \n        and the attribute of the same name in the goes_imager_projection \n        variable.\n\n    re_grs80, rp_grs80 (meters): equatorial and polar radii \n        for GRS80 lightning ellipse used by GOES-R, as defined in the\n        GOES-R L1b PUG, and the semi_major_axis and semi_minor_axis\n        attributes of the goes_imager_projection variable.\n\n    This function undoes the lightning ellipsoid height assumption,\n    such that the final fixed grid position matches the ABI fixed\n    grid definition and therefore the ABI L1b products.\n\n    Reference:\n    Bezooijen, R. W. H., H. Demroff, G. Burton, D. Chu, and S. Yang, 2016: \n        Image navigation and registration for the geostationary lightning \n        mapper (GLM). Proc. SPIE 10004, 100041N, doi: 10.1117/12.2242141.\n    \"\"\"\n    re_ltg_ellps, rp_ltg_ellps = lightning_ellipse_rev[ellipse_rev]\n\n    ff_ltg_ellps = (re_ltg_ellps - rp_ltg_ellps)/re_ltg_ellps\n    ff_grs80 = (re_grs80 - rp_grs80)/re_grs80 # 0.003352810704800 \n    sat_H = sat_grs80_height + re_grs80 # 42.164e6 \n    \n    # center longitudes on satellite, and ensure between +/- 180\n    lon = np.atleast_1d(lon)\n    lat = np.atleast_1d(lat)\n    dlon = lon-sat_lon\n    dlon[dlon < -180] += 360\n    dlon[dlon > 180] -= 360\n    lon_rad = np.radians(dlon)\n    lat_rad = np.radians(lat)\n\n    lat_geocent = np.arctan( (1.0 - ff_grs80)**2.0 * np.tan(lat_rad))\n    \n    # We assume geocentric latitude\n    cos_factor = np.cos(lat_geocent)\n    sin_factor = np.sin(lat_geocent)\n\n    R = re_ltg_ellps*(1-ff_ltg_ellps) / np.sqrt(1.0-ff_ltg_ellps*(2.0-ff_ltg_ellps)*cos_factor*cos_factor)\n    vx = R * cos_factor * np.cos(lon_rad) - sat_H\n    vy = R * cos_factor * np.sin(lon_rad)\n    vz = R * sin_factor\n    vmag = np.sqrt(vx*vx + vy*vy + vz*vz)\n    vx /= -vmag # minus signs flip so x points to earth, z up, y left\n    vy /= -vmag\n    vz /= vmag\n    \n    # Microradians\n    alpha = np.arctan(vz/vx) #* 1e6\n    beta = -np.arcsin(vy) #* 1e6\n    return beta, alpha\n", "meta": {"hexsha": "fa0a46973615e22dc27ab2022870cd6b3f28b219", "size": 5617, "ext": "py", "lang": "Python", "max_stars_repo_path": "glmtools/io/lightning_ellipse.py", "max_stars_repo_name": "jeremym-cfd/glmtools", "max_stars_repo_head_hexsha": "b70484c79f12a3fdfcc8f5077ad7f37bf4caa594", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-07T02:38:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-07T02:38:35.000Z", "max_issues_repo_path": "glmtools/io/lightning_ellipse.py", "max_issues_repo_name": "tjlang/glmtools", "max_issues_repo_head_hexsha": "0fa419d156da5965301412ccb8b5960109357d77", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "glmtools/io/lightning_ellipse.py", "max_forks_repo_name": "tjlang/glmtools", "max_forks_repo_head_hexsha": "0fa419d156da5965301412ccb8b5960109357d77", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-11T16:21:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-11T16:21:25.000Z", "avg_line_length": 41.9179104478, "max_line_length": 106, "alphanum_fraction": 0.7062488873, "include": true, "reason": "import numpy", "num_tokens": 1602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.18669734288477405}}
{"text": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\n\n\"\"\"\n.. note::\n         These are the empirical relations functions for SPLAT \n\"\"\"\n\n# imports: internal\nimport copy\nimport sys\n\n# imports - external\nimport numpy\n#from astropy import units as u            # standard units\n#from astropy import constants as const        # physical constants in SI units\nfrom scipy.interpolate import interp1d\nimport matplotlib.pyplot as plt\n\n# splat functions\nfrom splat.initialize import *\nfrom splat.utilities import *\nfrom splat.photometry import filterMag\nfrom splat.core import classifyByIndex, Spectrum\nfrom splat.citations import shortRef\n\n# Python 2->3 fix for input\ntry: input=raw_input\nexcept NameError: pass\n\n\n#Constants.SPLAT_URL = 'http://pono.ucsd.edu/~adam/splat/'\n#DATA_FOLDER = '/reference/Spectra/'\n\n#Constants.DB_SOURCES = fetchDatabase(Constants.DB_SOURCES_FILE)\n#print(Constants.DB_SOURCES)\n#Constants.DB_SPECTRA = fetchDatabase(Constants.DB_SPECTRA_FILE)\n\n# change the command prompt\n#sys.ps1 = 'splat empirical> '\n\n\n\n#####################################################\n##############   DISTANCE ESTIMATION   ##############\n#####################################################\n\ndef estimateDistance(*args, **kwargs):\n    '''\n    :Purpose: Takes the apparent magnitude and either takes or determines the absolute\n                magnitude, then uses the magnitude/distance relation to estimate the\n                distance to the object in parsecs. Returns estimated distance and\n                uncertainty in parsecs\n\n    :param sp: Spectrum class object, which should be flux calibrated to its empirical apparent magnitude\n    :param mag: apparent magnitude of ``sp``\n    :type mag: optional, default = False\n    :param mag_unc: uncertainty of the apparent magnitude\n    :type mag_unc: optional, default = 0\n    :param absmag: absolute magnitude of ``sp``\n    :type absmag: optional, default = False\n    :param absmag_unc: uncertainty of the absolute magnitude\n    :type absmag_unc: optional, default = 0\n    :param spt: spectral type of ``sp``\n    :type spt: optional, default = False\n    :param spt_e: uncertainty of the spectral type\n    :type spt_e: optional, default = 0\n    :param nsamples: number of samples to use in Monte Carlo error estimation\n    :type nsamples: optional, default = 100\n    :param filter: Name of filter, must be one of the following:\n\n                    - '2MASS J', '2MASS H', '2MASS Ks'\n                    - 'MKO J', 'MKO H', 'MKO K', MKO Kp', 'MKO Ks'\n                    - 'NICMOS F090M', 'NICMOS F095N', 'NICMOS F097N', 'NICMOS F108N'\n                    - 'NICMOS F110M', 'NICMOS F110W', 'NICMOS F113N', 'NICMOS F140W'\n                    - 'NICMOS F145M', 'NICMOS F160W', 'NICMOS F164N', 'NICMOS F165M'\n                    - 'NICMOS F166N', 'NICMOS F170M', 'NICMOS F187N', 'NICMOS F190N'\n                    - 'NIRC2 J', 'NIRC2 H', 'NIRC2 Kp', 'NIRC2 Ks'\n                    - 'WIRC J', 'WIRC H', 'WIRC K', 'WIRC CH4S', 'WIRC CH4L'\n                    - 'WIRC CO', 'WIRC PaBeta', 'WIRC BrGamma', 'WIRC Fe2'\n                    - 'WISE W1', 'WISE W2'\n\n    :type filter: optional, default = False\n    :Example:\n    >>> import splat\n    >>> sp = splat.getSpectrum(shortname='1555+0954')[0]\n    >>> print splat.estimateDistance(sp)\n        Please specify the filter used to determine the apparent magnitude\n        (nan, nan)\n    >>> print splat.estimateDistance(sp, mag = 12.521, mag_unc = 0.022, absmag = 7.24, absmag_unc = 0.50, spt = 'M3')\n        (116.36999172188771, 33.124820555524224)\n    '''\n\n    mag = kwargs.get('mag', False)\n    mag_unc = kwargs.get('mag_unc', 0.)\n    mag_unc = kwargs.get('mag_e', mag_unc)\n    absmag = kwargs.get('absmag', False)\n    absmag_unc = kwargs.get('absmag_unc', 0.)\n    absmag_unc = kwargs.get('absmag_e', absmag_unc)\n    spt = kwargs.get('spt', False)\n    spt_unc = kwargs.get('spt_unc', 0.)\n    spt_unc = kwargs.get('spt_e', spt_unc)\n    nsamples = kwargs.get('nsamples', 100)\n    filt = kwargs.get('filter', False)\n\n# require spectum object if filter, magnitude and spt not all provided\n    if mag == False or filt == False or spt == False:\n        if len(args) == 0:\n            sys.stderr.write('\\nYou must include the Spectrum object if you do not specify filter, magnitude and spt\\n')\n            return numpy.nan, numpy.nan\n        else:\n            sp = args[0]\n\n# if no apparent magnitude then calculate from spectrum\n    if (mag == False):\n        if (filt == False):\n            sys.stderr.write('\\nPlease specify the filter used to determine the apparent magnitude\\n')\n            return numpy.nan, numpy.nan\n        mag, mag_unc = filterMag(sp,filt)\n\n# if no spt then calculate from spectrum\n    if spt == False:\n        spt, spt_unc = classifyByIndex(sp)\n\n\n# if no absolute magnitude then estimate from spectral type\n    if absmag == False:\n        if filt == False:\n            sys.stderr.write('\\nPlease specify the filter used to determine the absolute magnitude\\n')\n            return numpy.nan, numpy.nan\n        absmag, absmag_unc = typeToMag(spt,filt,unc=spt_unc)\n#        print(absmag, absmag_unc)\n\n# create Monte Carlo sets\n    if mag_unc > 0.:\n        mags = numpy.random.normal(mag, mag_unc, nsamples)\n    else:\n        mags = nsamples*[mag]\n\n    if absmag_unc > 0.:\n        absmags = numpy.random.normal(absmag, absmag_unc, nsamples)\n    else:\n        absmags = nsamples*[absmag]\n\n# calculate\n    distances = 10.**(numpy.subtract(mags,absmags)/5. + 1.)\n    d = numpy.mean(distances)\n    unc = numpy.std(distances)\n\n    return d, unc\n\n\n\n#####################################################\n###############   SPT -> PARAMETER   ################\n#####################################################\n\n\n\ndef typeToColor(spt,color,reference='skrzypek2015',uncertainty=0.,nsamples=100,verbose=False,**kwargs):\n    \"\"\"\n    :Purpose: Takes a spectral type and optionally a color (string) and returns the typical color of the source. \n    :param spt: string or integer of the spectral type\n    :param color: string indicating color; e.g., color='i-z' (note that case does not matter)\n    :type color: optional, default = 'J-K'\n    :param ref: Abs Mag/SpT relation used to compute the absolute magnitude. Options are:\n\n        - *skrzypek* (default): Color trends from `Skryzpek et al. (2015) <http://adsabs.harvard.edu/abs/2015A%26A...574A..78S>`_.\n          Spectral type range is M5 to T8\n          Colors include i-z, z-Y, Y-J, J-H, H-K, K-W1, W1-W2, and combinations therein.\n\n\n    :type ref: optional, default = 'dupuy'\n    :param nsamples: number of Monte Carlo samples for error computation\n    :type nsamples: optional, default = 100\n    :param unc: uncertainty of ``spt``; if included, returns a tuple with color and uncertainty\n    :type unc: optional, default = 0.\n    :param verbose: Give feedback while in operation\n    :type verbose: optional, default = False\n    :Example:\n        >>> import splat\n        >>> print splat.typeToColor('L3', 'J-K')\n            (1.46, nan)\n        >>> print splat.typeToColor('M5', 'i-z', ref = 'skrzypek', unc=0.5)\n            (0.91, 0.57797809947624645)\n        >>> print splat.typeToColor('M0', 'i-z', ref = 'skrzypek')\n            Spectral type M0.0 is outside the range for reference set Skrzypek et al. (2015)\n            (nan, nan)\n    \"\"\"\n\n# Keywords alternatives\n    for f in ['unc','spt_e','error']:\n        if f in list(kwargs.keys()):\n            uncertainty = kwargs.get(f,uncertainty)\n    for f in ['ref','set','method','model','relation']:\n        if f in list(kwargs.keys()):\n            reference = kwargs.get(f,reference)\n    ref = checkEmpiricalRelation(reference.lower().replace(' ',''),splat.SPT_COLORS_RELATIONS)\n    if ref == False:\n        print('\\nColor set from {} has not be integrated into SPLAT\\n\\n'.format(reference))\n        return numpy.nan, numpy.nan\n    if verbose==True: print('\\nUsing the SpT/color trends from {}\\n'.format(ref))\n\n# Convert spectral type string to number\n    if isinstance(spt,str): sptn = typeToNum(spt)\n    else: sptn = copy.deepcopy(spt)\n\n    col = color.lower().replace(' ','').replace('2mass','').replace('sdss','').replace('wise','').replace('denis','')\n\n# check spt is in range\n    if not (splat.SPT_COLORS_RELATIONS[ref]['range'][0] <= sptn <= splat.SPT_COLORS_RELATIONS[ref]['range'][1]):\n        print('\\n Spectral type {} is outside the range for reference set {}: {} to {}\\n\\n'.format(spt,ref,splat.SPT_COLORS_RELATIONS[ref]['range'][0],splat.SPT_COLORS_RELATIONS[ref]['range'][1]))\n        return numpy.nan, numpy.nan\n\n# fill in extra colors - a little inefficient right now  \n    if col not in list(splat.SPT_COLORS_RELATIONS[ref]['values'].keys()):\n# base color \n        c1 = (col.split('-'))[0]\n        refcol = ''\n        for x in list(splat.SPT_COLORS_RELATIONS[ref]['values'].keys()):\n            if x.split('-')[0] == c1: refcol = x\n        if refcol == '': \n            print('\\nUnable to constuct color {} for reference set {} which has colors {}\\n'.format(color,ref,list(splat.SPT_COLORS_RELATIONS[ref]['values'].keys())))\n            return numpy.nan, numpy.nan\n        refcolors = numpy.array(splat.SPT_COLORS_RELATIONS[ref]['values'][refcol])\n# now run through colors until you create the correct match\n        cntr = 0\n        maxcntr = len(list(splat.SPT_COLORS_RELATIONS[ref]['values'].keys()))\n        while refcol != col and cntr < maxcntr:\n            refadd = ''\n            for x in list(splat.SPT_COLORS_RELATIONS[ref]['values'].keys()):\n                if x.split('-')[0] == (refcol.split('-'))[-1]: refadd = x\n            if refadd == '': \n                print('\\nUnable to constuct color {} for reference set {} which has colors {}\\n'.format(color,ref,list(splat.SPT_COLORS_RELATIONS[ref]['values'].keys())))\n                return numpy.nan, numpy.nan\n            refcol='{}-{}'.format((refcol.split('-'))[0],(refadd.split('-'))[-1])\n            refcolors = refcolors+numpy.array(splat.SPT_COLORS_RELATIONS[ref]['values'][refadd])\n            splat.SPT_COLORS_RELATIONS[ref]['values'][refcol] = refcolors\n            cntr=cntr+1\n        if cntr >= maxcntr:\n            print('\\nUnable to constuct color {} for reference set {} which has colors {}\\n'.format(color,ref,list(splat.SPT_COLORS_RELATIONS[ref]['values'].keys())))\n            return numpy.nan, numpy.nan\n\n    if col in list(splat.SPT_COLORS_RELATIONS[ref]['values'].keys()):\n        f = interp1d(numpy.arange(splat.SPT_COLORS_RELATIONS[ref]['range'][0],splat.SPT_COLORS_RELATIONS[ref]['range'][1]+1),splat.SPT_COLORS_RELATIONS[ref]['values'][col],bounds_error=False,fill_value=0.)\n        if uncertainty > 0.:\n            vals = f(numpy.random.normal(sptn, uncertainty, nsamples))\n            return float(f(sptn)), (numpy.nanstd(vals)**2+splat.SPT_COLORS_RELATIONS[ref]['scatter']**2)**0.5\n        else:\n            return float(f(sptn)), splat.SPT_COLORS_RELATIONS[ref]['scatter']\n    else:\n        print('\\nUnable to constuct color {} for reference set {} which has colors {}\\n'.format(color,ref,list(splat.SPT_COLORS_RELATIONS[ref]['values'].keys())))\n        return numpy.nan, numpy.nan\n\n\n\n\ndef typeToMag_old(spt, filt, **kwargs):\n    \"\"\"\n    :Purpose: Takes a spectral type and a filter, and returns absolute magnitude\n    :param spt: string or integer of the spectral type\n    :param filter: filter of the absolute magnitude. Options are MKO K, MKO H, MKO J, MKO Y, MKO LP, 2MASS J, 2MASS K, or 2MASS H\n    :param nsamples: number of Monte Carlo samples for error computation\n    :type nsamples: optional, default = 100\n    :param unc: uncertainty of ``spt``\n    :type unc: optional, default = 0.\n    :param ref: Abs Mag/SpT relation used to compute the absolute magnitude. Options are:\n\n        - *burgasser*: Abs Mag/SpT relation from `Burgasser (2007) <http://adsabs.harvard.edu/abs/2007ApJ...659..655B>`_.\n          Allowed spectral type range is L0 to T8, and allowed filters are MKO K.\n        - *faherty*: Abs Mag/SpT relation from `Faherty et al. (2012) <http://adsabs.harvard.edu/abs/2012ApJ...752...56F>`_.\n          Allowed spectral type range is L0 to T8, and allowed filters are MKO J, MKO H and MKO K.\n        - *dupuy*: Abs Mag/SpT relation from `Dupuy & Liu (2012) <http://adsabs.harvard.edu/abs/2012ApJS..201...19D>`_.\n          Allowed spectral type range is M6 to T9, and allowed filters are MKO J, MKO Y, MKO H, MKO K, MKO LP, 2MASS J, 2MASS H, and 2MASS K.\n        - *filippazzo*: Abs Mag/SpT relation from Filippazzo et al. (2015). Allowed spectral type range is M6 to T9, and allowed filters are 2MASS J and WISE W2.\n\n\n    :type ref: optional, default = 'dupuy'\n    :Example:\n        >>> import splat\n        >>> print splat.typeToMag('L3', '2MASS J')\n            (12.730064813273996, 0.4)\n        >>> print splat.typeToMag(21, 'MKO K', ref = 'burgasser')\n            (10.705292820099999, 0.26)\n        >>> print splat.typeToMag(24, '2MASS J', ref = 'faherty')\n            Invalid filter given for Abs Mag/SpT relation from Faherty et al. (2012)\n            (nan, nan)\n        >>> print splat.typeToMag('M0', '2MASS H', ref = 'dupuy')\n            Spectral Type is out of range for Abs Mag/SpT relation from Dupuy & Liu (2012) Abs Mag/SpT relation\n            (nan, nan)\n    \"\"\"\n\n#Keywords\n    verbose = kwargs.get('verbose',False)\n    nsamples = kwargs.get('nsamples', 100)\n    ref = kwargs.get('ref', 'dupuy')\n    ref = kwargs.get('set', ref)\n    unc = kwargs.get('unc', 0.)\n\n#Convert spectral type string to number\n    if isinstance(spt,str):\n        spt = typeToNum(spt, uncertainty=unc)\n    else:\n        spt = copy.deepcopy(spt)\n\n#Faherty\n    if (ref.lower() == 'faherty'):\n        sptoffset = 10.\n        reference = 'Abs Mag/SpT relation from Faherty et al. (2012)'\n        coeffs = { \\\n            'MKO J': {'fitunc' : 0.30, 'range' : [20., 38.],  \\\n                'coeff': [.000203252, -.0129143, .275734, -1.99967, 14.8948]}, \\\n            'MKO H': {'fitunc' : 0.27, 'range' : [20., 38.], \\\n                'coeff' : [.000175368, -.0108205, .227363, -1.60036, 13.2372]}, \\\n            'MKO K': {'fitunc' : 0.28, 'range' : [20., 38.], \\\n                'coeff' : [.0000816516, -.00469032, .0940816, -.485519, 9.76100]}}\n\n# Burgasser\n    elif (ref.lower() == 'burgasser'):\n        sptoffset = 20.\n        reference = 'Abs Mag/SpT relation from Burgasser (2007)'\n        coeffs = { \\\n            'MKO K': {'fitunc' : 0.26, 'range' : [20., 38.], \\\n                'coeff': [.0000001051, -.000006985, .0001807, -.002271, .01414, -.04024, .05129, .2322, 10.45]}}\n\n# Dupuy & Liu, default reference\n    elif (ref.lower() == 'dupuy'):\n        reference = 'Abs Mag/SpT relation from Dupuy & Liu (2012)'\n        sptoffset = 10.\n        coeffs = { \\\n            'MKO J': {'fitunc' : 0.39, 'range' : [16., 39.], \\\n                'coeff' : [-.00000194920, .000227641, -.0103332, .232771, -2.74405, 16.3986, -28.3129]}, \\\n            'MKO Y': {'fitunc': 0.40, 'range' : [16., 39.], \\\n                'coeff': [-.00000252638, .000285027, -.0126151, .279438, -3.26895, 19.5444, -35.1560]}, \\\n            'MKO H': {'fitunc': 0.38, 'range' : [16., 39.], \\\n                'coeff': [-.00000224083, .000251601, -.0110960, .245209, -2.85705, 16.9138, -29.7306]}, \\\n            'MKO K': {'fitunc': 0.40, 'range' : [16., 39.], \\\n                'coeff': [-.00000104935, .000125731, -.00584342, .135177, -1.63930, 10.1248, -15.2200]}, \\\n            'MKO LP': {'fitunc': 0.28, 'range': [16., 39.], \\\n                'coeff': [0.00000, 0.00000, .0000546366, -.00293191, .0530581,  -.196584, 8.89928]}, \\\n            '2MASS J': {'fitunc': 0.40, 'range': [16., 39.], \\\n                'coeff': [-.000000784614, .000100820, -.00482973, .111715, -1.33053, 8.16362, -9.67994]}, \\\n            '2MASS H': {'fitunc': 0.40, 'range': [16., 39.], \\\n                'coeff': [-.00000111499, .000129363, -.00580847, .129202, -1.50370, 9.00279, -11.7526]}, \\\n            '2MASS KS': {'fitunc': 0.43, 'range':[16., 39.], \\\n                'coeff': [1.06693e-4, -6.42118e-3, 1.34163e-1, -8.67471e-1, 1.10114e1]}, \\\n            'WISE W1': {'fitunc': 0.39, 'range':[16., 39.], \\\n                'coeff': [1.58040e-5, -3.33944e-4, -4.38105e-3, 3.55395e-1, 7.14765]}, \\\n            'WISE W2': {'fitunc': 0.35, 'range':[16., 39.], \\\n                'coeff': [1.78555e-5, -8.81973e-4, 1.14325e-2, 1.92354e-1, 7.46564]}}\n\n    elif (ref.lower() == 'filippazzo'):\n        reference = 'Abs Mag/SpT relation from Filippazzo et al. (2015)'\n        sptoffset = 10.\n        coeffs = { \\\n            '2MASS J': {'fitunc': 0.40, 'range': [16., 39.], \\\n                'coeff': [3.478e-5, -2.684e-3, 7.771e-2, -1.058e0, 7.157e0, -8.350e0]}, \\\n            'WISE W2': {'fitunc': 0.40, 'range': [16., 39.], \\\n                'coeff': [8.190e-6, -6.938e-4, 2.283e-2, -3.655e-1, 3.032e0, -5.043e-1]}}\n\n    else:\n        sys.stderr.write('\\nInvalid Abs Mag/SpT relation given: %s\\n' % ref)\n        return numpy.nan, numpy.nan\n\n    if (filt.upper() in coeffs.keys()) == 1:\n        for f in coeffs.keys():\n            if filt.upper() == f:\n                coeff = coeffs[f]['coeff']\n                fitunc = coeffs[f]['fitunc']\n                rng = coeffs[f]['range']\n    else:\n        sys.stderr.write('\\n Invalid filter {} given for {}\\n'.format(filt,reference))\n        return numpy.nan, numpy.nan\n\n# compute magnitude if its in the right spectral type range\n    if (rng[0] <= spt <= rng[1]):\n        abs_mag = numpy.polyval(coeff, spt-sptoffset)\n        abs_mag_error = fitunc\n        if (unc > 0.):\n            vals = numpy.polyval(coeff, numpy.random.normal(spt - sptoffset, unc, nsamples))\n#            abs_mag = numpy.nanmean(vals)\n            abs_mag_error = (numpy.nanstd(vals)**2+fitunc**2)**0.5\n        return abs_mag, abs_mag_error\n    else:\n        if verbose: sys.stderr.write('\\nSpectral Type {} is out of range for {}\\n'.format(typeToNum(spt),reference))\n        return numpy.nan, numpy.nan\n\n\ndef typeToMag_old2(spt, filt, unc=0.,ref='filippazzo2015',verbose=False,nsamples=100,**kwargs):\n    \"\"\"\n    :Purpose: \n\n    Takes a spectral type and a filter, and returns the expected absolute magnitude based on empirical relations\n\n    :Required Inputs: \n\n        :param spt: string or integer of the spectral type\n        :param filter: filter for which to retrieve absolute magnitude, which must be defined for the given reference set.\n        You can check what filters are available by printing splat.SPT_ABSMAG_RELATIONS[reference]['filters'].keys(), where reference is, e.g., 'filippazzo2015'\n\n    :Optional Inputs: \n\n        :param reference: Abs Mag/SpT relation used to compute the absolute magnitude (also 'ref' and 'set'). These are defined in splat.SPT_ABSMAG_RELATIONS and are currently as follows:\n\n            - *dahn2002*: Abs Mag/SpT relation from `Dahn et al. (2002) <http://adsabs.harvard.edu/abs/2002AJ....124.1170D>`_\n              Allowed spectral type range is M7 to L8, and allowed filters are 2MASS J\n            - *cruz2003*: Abs Mag/SpT relation from `Cruz et al. (2003) <http://adsabs.harvard.edu/abs/2003AJ....126.2421C>`_\n              Allowed spectral type range is M6 to L8, and allowed filters are 2MASS J\n            - *tinney2003*: Abs Mag/SpT relation from `Tinney et al. (2003) <http://adsabs.harvard.edu/abs/2003AJ....126..975T>`_.\n              Allowed spectral type range is L0 to T7.5, and allowed filters are Cousins I, UKIRT Z, J, K and 2MASS J, Ks\n            - *burgasser2007*: Abs Mag/SpT relation from `Burgasser (2007) <http://adsabs.harvard.edu/abs/2007ApJ...659..655B>`_.\n              Allowed spectral type range is L0 to T8, and allowed filters are MKO K.\n            - *looper2008*: Abs Mag/SpT relation from `Looper et al. (2008) <http://adsabs.harvard.edu/abs/2008ApJ...685.1183L>`_.\n              Allowed spectral type range is L0 to T8, and allowed filters are 2MASS J, H, Ks.\n            - *dupuy2012*: Abs Mag/SpT relation from `Dupuy & Liu (2012) <http://adsabs.harvard.edu/abs/2012ApJS..201...19D>`_.\n              Allowed spectral type range is M6 to T9, and allowed filters are MKO Y, J, H,K, LP, 2MASS J, H, Ks, and WISE W1, W2.\n            - *faherty2012*: Abs Mag/SpT relation from `Faherty et al. (2012) <http://adsabs.harvard.edu/abs/2012ApJ...752...56F>`_.\n              Allowed spectral type range is L0 to T8, and allowed filters are MKO J, H, K.\n            - *tinney2014*: Abs Mag/SpT relation from `Tinney et al. (2014) <http://adsabs.harvard.edu/abs/2014ApJ...796...39T>`_.\n              Allowed spectral type range is T6.5 to Y2, and allowed filters are MKO J, WISE W2\n            - *filippazzo2015* (default): Abs Mag/SpT relation from Filippazzo et al. (2015). \n              Allowed spectral type range is M6 to T9, and allowed filters are 2MASS J and WISE W2.\n            - *faherty2016*: Abs Mag/SpT relation for field dwarfs from `Faherty et al. (2016) <http://adsabs.harvard.edu/abs/2016ApJS..225...10F>`_.\n              Allowed spectral type range is M6 to T9, and allowed filters are 2MASS J, H, Ks and WISE W1, W2, W3\n            - *faherty2016-group*: Abs Mag/SpT relation for \"group\" dwarfs from `Faherty et al. (2016) <http://adsabs.harvard.edu/abs/2016ApJS..225...10F>`_.\n              Allowed spectral type range is M7 to L7, and allowed filters are 2MASS J, H, Ks and WISE W1, W2, W3\n            - *faherty2016-young*: Abs Mag/SpT relation for \"young\" dwarfs from `Faherty et al. (2016) <http://adsabs.harvard.edu/abs/2016ApJS..225...10F>`_.\n              Allowed spectral type range is M7 to L7, and allowed filters are 2MASS J, H, Ks and WISE W1, W2, W3\n\n        :param unc: uncertainty of ``spt`` (default = 0)\n        :param nsamples: number of Monte Carlo samples for error computation (default = 100)\n\n    :Output: \n    \n        2 element tuple providing the absolute magnitude and its uncertainty\n\n    :Example:\n        >>> import splat\n        >>> print splat.typeToMag('L3', '2MASS J')\n            (12.730064813273996, 0.4)\n        >>> print splat.typeToMag(21, 'MKO K', ref = 'burgasser')\n            (10.705292820099999, 0.26)\n        >>> print splat.typeToMag(24, '2MASS J', ref = 'faherty')\n            Invalid filter given for Abs Mag/SpT relation from Faherty et al. (2012)\n            (nan, nan)\n        >>> print splat.typeToMag('M0', '2MASS H', ref = 'dupuy')\n            Spectral Type is out of range for Abs Mag/SpT relation from Dupuy & Liu (2012) Abs Mag/SpT relation\n            (nan, nan)\n    \"\"\"\n\n#Keywords alternatives\n    ref = kwargs.get('reference', ref)\n    ref = kwargs.get('set', ref)\n    unc = kwargs.get('uncertainty', unc)\n    unc = kwargs.get('error', unc)\n\n#Convert spectral type string to number\n    if isinstance(spt,str):\n        sptn = typeToNum(spt, uncertainty=unc)\n    elif isinstance(spt,int) or isinstance(spt,float):\n        sptn = copy.deepcopy(spt)\n    else:\n        raise ValueError('\\nInput spectral type {} must be a string, float or int'.format(spt))\n\n# check that you can use the proscribed relation and filter\n    filtcheck = checkFilterName(filt,verbose=verbose)\n    if filtcheck == False: return numpy.nan,numpy.nan\n    else: filt=filtcheck\n\n    refcheck = checkAbsMag(ref,filt=filt,verbose=verbose)\n    if refcheck == False: return numpy.nan,numpy.nan\n    else: ref=refcheck\n\n    sptoffset = SPT_ABSMAG_RELATIONS[ref]['sptoffset']\n    coeff = SPT_ABSMAG_RELATIONS[ref]['filters'][filt]['coeff']\n    rng = SPT_ABSMAG_RELATIONS[ref]['filters'][filt]['range']\n    fitunc = SPT_ABSMAG_RELATIONS[ref]['filters'][filt]['fitunc']\n    refstring = 'Absolute {}/SpT relation from {}'.format(filt,shortRef(SPT_ABSMAG_RELATIONS[ref]['bibcode']))\n    if verbose: print('\\nUsing {}'.format(refstring))\n\n# compute magnitude if its in the right spectral type range\n    if (rng[0] <= sptn <= rng[1]):\n        abs_mag = numpy.polyval(coeff, sptn-sptoffset)\n        abs_mag_error = fitunc\n        if unc > 0.:\n            vals = numpy.polyval(coeff, numpy.random.normal(sptn - sptoffset, unc, nsamples))\n#            abs_mag = numpy.nanmean(vals)\n            abs_mag_error = (numpy.nanstd(vals)**2+fitunc**2)**0.5\n        return abs_mag, abs_mag_error\n    else:\n        if verbose: sys.stderr.write('\\nSpectral Type {} is out of range for {}\\n'.format(typeToNum(sptn),refstring))\n        return numpy.nan, numpy.nan\n\n\ndef typeToMag(spt, filt, uncertainty=0.,reference='filippazzo2015',verbose=False,nsamples=100,mask=True,mask_value=numpy.nan,**kwargs):\n    \"\"\"\n    :Purpose: \n\n    Takes a spectral type and a filter, and returns the expected absolute magnitude based on empirical relations\n\n    :Required Inputs: \n\n        :param spt: string or integer of the spectral type\n        :param filter: filter for which to retrieve absolute magnitude, which must be defined for the given reference set.\n        You can check what filters are available by printing splat.SPT_ABSMAG_RELATIONS[reference]['filters'].keys(), where reference is, e.g., 'filippazzo2015'\n\n    :Optional Inputs: \n\n        :param reference: Abs Mag/SpT relation used to compute the absolute magnitude (also 'ref' and 'set'). These are defined in splat.SPT_ABSMAG_RELATIONS and are currently as follows:\n\n            - *dahn2002*: Abs Mag/SpT relation from `Dahn et al. (2002) <http://adsabs.harvard.edu/abs/2002AJ....124.1170D>`_\n              Allowed spectral type range is M7 to L8, and allowed filters are 2MASS J\n            - *cruz2003*: Abs Mag/SpT relation from `Cruz et al. (2003) <http://adsabs.harvard.edu/abs/2003AJ....126.2421C>`_\n              Allowed spectral type range is M6 to L8, and allowed filters are 2MASS J\n            - *tinney2003*: Abs Mag/SpT relation from `Tinney et al. (2003) <http://adsabs.harvard.edu/abs/2003AJ....126..975T>`_.\n              Allowed spectral type range is L0 to T7.5, and allowed filters are Cousins I, UKIRT Z, J, K and 2MASS J, Ks\n            - *burgasser2007*: Abs Mag/SpT relation from `Burgasser (2007) <http://adsabs.harvard.edu/abs/2007ApJ...659..655B>`_.\n              Allowed spectral type range is L0 to T8, and allowed filters are MKO K.\n            - *looper2008*: Abs Mag/SpT relation from `Looper et al. (2008) <http://adsabs.harvard.edu/abs/2008ApJ...685.1183L>`_.\n              Allowed spectral type range is L0 to T8, and allowed filters are 2MASS J, H, Ks.\n            - *dupuy2012*: Abs Mag/SpT relation from `Dupuy & Liu (2012) <http://adsabs.harvard.edu/abs/2012ApJS..201...19D>`_.\n              Allowed spectral type range is M6 to T9, and allowed filters are MKO Y, J, H,K, LP, 2MASS J, H, Ks, and WISE W1, W2.\n            - *faherty2012*: Abs Mag/SpT relation from `Faherty et al. (2012) <http://adsabs.harvard.edu/abs/2012ApJ...752...56F>`_.\n              Allowed spectral type range is L0 to T8, and allowed filters are MKO J, H, K.\n            - *tinney2014*: Abs Mag/SpT relation from `Tinney et al. (2014) <http://adsabs.harvard.edu/abs/2014ApJ...796...39T>`_.\n              Allowed spectral type range is T6.5 to Y2, and allowed filters are MKO J, WISE W2\n            - *filippazzo2015* (default): Abs Mag/SpT relation from Filippazzo et al. (2015). \n              Allowed spectral type range is M6 to T9, and allowed filters are 2MASS J and WISE W2.\n            - *faherty2016*: Abs Mag/SpT relation for field dwarfs from `Faherty et al. (2016) <http://adsabs.harvard.edu/abs/2016ApJS..225...10F>`_.\n              Allowed spectral type range is M6 to T9, and allowed filters are 2MASS J, H, Ks and WISE W1, W2, W3\n            - *faherty2016-group*: Abs Mag/SpT relation for \"group\" dwarfs from `Faherty et al. (2016) <http://adsabs.harvard.edu/abs/2016ApJS..225...10F>`_.\n              Allowed spectral type range is M7 to L7, and allowed filters are 2MASS J, H, Ks and WISE W1, W2, W3\n            - *faherty2016-young*: Abs Mag/SpT relation for \"young\" dwarfs from `Faherty et al. (2016) <http://adsabs.harvard.edu/abs/2016ApJS..225...10F>`_.\n              Allowed spectral type range is M7 to L7, and allowed filters are 2MASS J, H, Ks and WISE W1, W2, W3\n\n        :param uncertainty: uncertainty of ``spt`` (default = 0)\n        :param nsamples: number of Monte Carlo samples for error computation (default = 100)\n\n    :Output: \n    \n        2 element tuple providing the absolute magnitude and its uncertainty\n\n    :Example:\n        >>> import splat\n        >>> print splat.typeToMag('L3', '2MASS J')\n            (12.730064813273996, 0.4)\n        >>> print splat.typeToMag(21, 'MKO K', ref = 'burgasser')\n            (10.705292820099999, 0.26)\n        >>> print splat.typeToMag(24, '2MASS J', ref = 'faherty')\n            Invalid filter given for Abs Mag/SpT relation from Faherty et al. (2012)\n            (nan, nan)\n        >>> print splat.typeToMag('M0', '2MASS H', ref = 'dupuy')\n            Spectral Type is out of range for Abs Mag/SpT relation from Dupuy & Liu (2012) Abs Mag/SpT relation\n            (nan, nan)\n    \"\"\"\n\n# Keywords alternatives\n    for f in ['unc','spt_e','error']:\n        if f in list(kwargs.keys()):\n            uncertainty = kwargs.get(f,uncertainty)\n    unc = copy.deepcopy(uncertainty)\n    for f in ['ref','set','method','model','relation']:\n        if f in list(kwargs.keys()):\n            reference = kwargs.get(f,reference)\n    ref = copy.deepcopy(reference)\n\n# Check and convert spectral type variable\n#    spt_type = type(spt)\n    sptn = copy.deepcopy(spt)\n    if isinstance(sptn,str): sptn = [sptn]\n    try:\n        sptn = list(sptn)\n    except:\n        sptn = [sptn]\n    if isinstance(sptn[0],str):\n        sptn = [typeToNum(s) for s in sptn]\n\n    try:\n        sptn = numpy.array(sptn)\n    except:\n        raise ValueError('\\nInput spectral type {} must be a string, float, int, list or numpy array'.format(spt))\n\n# Check uncertainties\n    uncn = copy.deepcopy(unc)\n    if not isinstance(uncn,list) and not isinstance(uncn,numpy.ndarray): uncn = [uncn]\n    if len(uncn) == 1:\n        uncn = numpy.zeros(len(sptn))+float(uncn[0])\n\n    try:\n        uncn = numpy.array(uncn)\n    except:\n        raise ValueError('\\nInput spectral type uncertainty {} must be a float, int, list or numpy array'.format(unc))\n    uncn = numpy.abs(uncn)\n\n# check that you can use the proscribed relation and filter\n    filtcheck = checkFilterName(filt,verbose=verbose)\n    if filtcheck == False: \n        if verbose: print('\\nDid not recognize filter {}'.format(filt))\n        return numpy.nan,numpy.nan\n    else: filt=filtcheck\n\n    refcheck = checkAbsMag(ref,filt=filt,verbose=verbose)\n    if refcheck == False: \n        if verbose: print('\\nDid not recognize relation {} or filter {} not in this relation'.format(ref,filt))\n        return numpy.nan,numpy.nan\n    else: ref=refcheck\n\n# read in relevant information\n    sptoffset = SPT_ABSMAG_RELATIONS[ref]['sptoffset']\n    coeff = SPT_ABSMAG_RELATIONS[ref]['filters'][filt]['coeff']\n    rng = SPT_ABSMAG_RELATIONS[ref]['filters'][filt]['range']\n    fitunc = SPT_ABSMAG_RELATIONS[ref]['filters'][filt]['fitunc']\n    refstring = 'Absolute {}/SpT relation from {}'.format(filt,shortRef(SPT_ABSMAG_RELATIONS[ref]['bibcode']))\n    if verbose: print('\\nUsing {}'.format(refstring))\n\n# compute absolute magnitudes\n    abs_mag = numpy.polyval(coeff, sptn-sptoffset)\n    abs_mag_error = numpy.zeros(len(sptn))+fitunc\n\n# mask out absolute magnitudes if they are outside spectral type range\n    if mask == True:\n        abs_mag[numpy.logical_or(sptn<rng[0],sptn>rng[1])] = mask_value\n        abs_mag_error[numpy.logical_or(sptn<rng[0],sptn>rng[1])] = mask_value\n        if verbose: print('{} values are outside relation range'.format(len(abs_mag[numpy.logical_or(sptn<rng[0],sptn>rng[1])])))\n\n# perform monte carlo error estimate (slow)\n    if numpy.nanmin(uncn) > 0.:\n        for i,u in enumerate(uncn):\n            if absmag[i] != mask_value and absmag[i] != numpy.nan:\n                vals = numpy.polyval(coeff, numpy.random.normal(sptn[i] - sptoffset, uncn, nsamples))\n#            abs_mag = numpy.nanmean(vals)\n                abs_mag_error[i] = (numpy.nanstd(vals)**2+fitunc**2)**0.5\n\n# return values in same dimension as input\n    if len(sptn) == 1: return float(abs_mag[0]),float(abs_mag_error[0])\n    else: return abs_mag, abs_mag_error\n\n\ndef typeToTeff(var, uncertainty=[0.001], reference='stephens09', nsamples=100, reverse=False, string=False,verbose=False, **kwargs):\n    '''\n    :Purpose: \n\n    Returns an effective temperature (Teff) and its uncertainty for a given spectral type (or vice versa) based on an empirical relation\n\n    :Required Inputs:\n\n        :param inp: A single or array of either spectral types or effective temperatures (reverse). \n        If spectral types, these can be ints, floats or strings from 0 (K0) and 49.0 (Y9).\n        If temperatures, these can be ints or floats and assumed to be in units of Kelvin.\n        Note: you must set reverse=True to convert temperature to spectral type.\n\n    :Optional Inputs:\n\n        :param uncertainty: uncertainty of spectral type/temperature (default = 0.001; also 'unc', 'spt_e')\n        :param reference: Teff/SpT relation used to compute the effective temperature (also 'set'). Options are:\n\n        - *stephens* (default): Teff/SpT relation from `Stephens et al. (2009) <http://adsabs.harvard.edu/abs/2009ApJ...702..154S>`_.\n          Allowed spectral type range is M6 to T8 and uses alternate coefficients for L3 to T8.\n        - *golimowski*: Teff/SpT relation from `Golimowski et al. (2004) <http://adsabs.harvard.edu/abs/2004AJ....127.3516G>`_.\n          Allowed spectral type range is M6 to T8.\n        - *looper*: Teff/SpT relation from `Looper et al. (2008) <http://adsabs.harvard.edu/abs/2008ApJ...685.1183L>`_.\n          Allowed spectral type range is L0 to T8.\n        - *marocco*: Teff/SpT relation from `Marocco et al. (2013) <http://adsabs.harvard.edu/abs/2013AJ....146..161M>`_.\n          Allowed spectral type range is M7 to T8.\n        - *filippazzo*: Teff/SpT relation from Filippazzo et al. (2015) <http://adsabs.harvard.edu/abs/2015ApJ...810..158F>`_. Allowed spectral type range is M6 to T9.\n        - *faherty*: Teff/SpT relation from Faherty et al. (2016) <http://adsabs.harvard.edu/abs/2016ApJS..225...10F>`_. \n        This relation is defined for normal dwarfs (M7 < SpT < T8), young dwarfs (``-young`` and ``-young2``, M7 < SpT < L7),\n        and young dwarfs in groups (``-group``, M7 < SpT < L7)\n        - *dupuy*: Teff/SpT relation from Dupuy et al. (2017).  \n        This relation is defined for Saumon & Marley (2008) models (``-saumon``, L1.5 < SpT < T5) and Lyon models (``-lyon``, M7 < SpT < T5)\n\n        :param reverse: set to True to convert effective temperature to spectral type (default=False)\n        :param nsamples: number of samples to use in Monte Carlo error estimation (default=100)\n\n    :Output:\n\n        A 2-element tuple containing the Teff/SpT and its uncertainty\n\n    :Example:\n        >>> import splat\n        >>> print splat.typeToTeff(20)\n            (2233.4796740905499, 100.00007874571999)\n        >>> print splat.typeToTeff(20, unc = 0.3, ref = 'golimowski')\n            (2305.7500497902788, 127.62548366132124)\n    '''\n# Keywords alternatives\n    for f in ['unc','spt_e','error']:\n        if f in list(kwargs.keys()):\n            uncertainty = kwargs.get(f,uncertainty)\n    unc = copy.deepcopy(uncertainty)\n    for f in ['ref','set','method','model','relation']:\n        if f in list(kwargs.keys()):\n            reference = kwargs.get(f,reference)\n    ref = checkEmpiricalRelation(reference.lower().replace(' ',''),splat.SPT_TEFF_RELATIONS)\n    if ref == False:\n        print('\\nSpT/Teff relation from {} has not be integrated into SPLAT\\n\\n'.format(reference))\n        return numpy.nan, numpy.nan\n    if verbose==True: print('\\nUsing the SpT/Teff relation from {}\\n'.format(ref))\n\n# Check and convert input variable\n    inp = copy.deepcopy(var)\n    if isUnit(inp): inp = inp.value\n    if type(inp) in [int,float,str,numpy.float64]: inp = [inp]\n    try:\n        inp = list(inp)\n    except:\n        raise ValueError('\\nInput variable {} must be a string, float, int, list, or numpy array'.format(inp))\n\n# Convert spectral type string to number\n    if isinstance(inp[0],str):\n        inp = [typeToNum(i) for i in inp]\n\n# Check and convert uncertainty variable\n    if type(unc) in [int,float]: unc = [unc]\n    try:\n        unc = list(unc)\n    except:\n        if verbose==True: print('\\nInput uncertainty {} must be a string, float, int, list, or numpy array; ignoring'.format(unc))\n        unc = list(numpy.zeros(len(inp)))\n    while len(unc) < len(inp): unc.append(unc[-1])\n\n# some special relations\n    if 'stephens' in ref.lower() and 'alt' in ref.lower(): ref = 'stephens-alt'\n    if 'faherty' in ref.lower() and 'young2' in ref.lower(): ref = 'faherty-young2'\n    elif 'faherty' in ref.lower() and 'young' in ref.lower(): ref = 'faherty-young'\n    elif 'faherty' in ref.lower() and 'group' in ref.lower(): ref = 'faherty-group'\n    else: pass\n    if 'dupuy' in ref.lower() and 'saumon' in ref.lower(): ref = 'dupuy-saumon'\n    elif 'dupuy' in ref.lower() and 'lyon' in ref.lower(): ref = 'dupuy-lyon'\n    else: pass\n\n# check that you can use the proscribed relation and filter\n    refcheck = checkDict(ref,SPT_TEFF_RELATIONS,verbose=verbose)\n    if refcheck == False: \n        raise ValueError(print('\\nDid not recognize relation reference {}; try {}'.format(reference,list(SPT_TEFF_RELATIONS.keys()))))\n#        raise ValueError: print('\\nDid not recognize relation reference {}'.format(reference))\n    else: ref=refcheck\n\n# read in relevant information\n    sptoffset = SPT_TEFF_RELATIONS[ref]['sptoffset']\n    coeff = numpy.array(SPT_TEFF_RELATIONS[ref]['coeff'])\n    sptrange = SPT_TEFF_RELATIONS[ref]['range']\n    fitunc = SPT_TEFF_RELATIONS[ref]['fitunc']\n    refstr = shortRef(SPT_TEFF_RELATIONS[ref]['bibcode'])\n    if refstr == '': refstr = SPT_TEFF_RELATIONS[ref]['reference']\n    refstring = 'Teff/SpT relation from {}'.format(refstr)\n    if verbose: print('\\nUsing {}'.format(refstring))\n\n# convert teff into spt\n    if reverse == True:\n#        if numpy.min(numpy.polyval(coeff,[r-sptoffset for r in sptrange])) <= teff <= numpy.max(numpy.polyval(coeff,[r-sptoffset for r in sptrange])):\n        x = numpy.linspace(sptrange[1]-sptoffset,sptrange[0]-sptoffset,nsamples)\n        f = interp1d(numpy.polyval(coeff,x),x,bounds_error=False)\n        spto = f(inp)+sptoffset\n# estimate a relation uncertainty from average scatter for all measures\n        sys_unc = 0.5*numpy.absolute(numpy.nanmedian(f(numpy.array(inp)+fitunc)-f(numpy.array(inp)-fitunc)))\n# FAIL: estimate a single relation uncertainty from first measure (for single temperature)\n        if not numpy.isfinite(sys_unc):\n            sys_unc = 0.5*numpy.absolute(f(inp[0]+fitunc)-f(inp[0]-fitunc))\n            if verbose==True: print('using sysunc from first measure')\n# FAIL: estimate a single relation uncertainty from middle of relation (for many temperatues)\n        if not numpy.isfinite(sys_unc):\n            mid_temp = numpy.nanmedian(numpy.polyval(coeff,x))\n            sys_unc = 0.5*numpy.absolute(f(mid_temp+fitunc)-f(mid_temp-fitunc))      \n            if verbose==True: print('using sysunc from middle')\n# FAIL: just use a 0.5 subtype error\n        if not numpy.isfinite(sys_unc): \n            sys_unc = 0.5\n            if verbose==True: print('using fixed sysunc')\n        spto_e = numpy.zeros(len(spto))+sys_unc\n# fold in uncertainty of measurement along with relation error\n        if unc[0] > 0.:\n            for i,t in enumerate(inp):\n                x = numpy.random.normal(t,unc[i],nsamples)+numpy.random.normal(0.,fitunc,nsamples)\n                vals = f(x)+sptoffset\n                spto_e[i] = numpy.nanstd(vals)\n\n# convert to strings if desired\n        if string == True: spto = [typeToNum(s) for s in spto]\n\n# return values\n        if len(inp) == 1: return spto[0],spto_e[0]\n        else: return list(spto),list(spto_e)\n\n        \n#         vals = f(x)+sptoffset\n#             if 'stephens' in ref.lower():\n#                 if numpy.min(numpy.polyval(coeff_alt,[r-sptoffset for r in range_alt])) <= teff <= numpy.max(numpy.polyval(coeff_alt,[r-sptoffset for r in range_alt])):\n#                     x = numpy.linspace(range_alt[1]-sptoffset,range_alt[0]-sptoffset,nsamples)\n#                     f = interp1d(numpy.polyval(coeff_alt,x),x,bounds_error=False)\n#                     spto = float(f(teff))+sptoffset\n#                     if kwargs.get('string',False) == True: spto = splat.typeToNum(spto)\n#                     x = numpy.random.normal(teff,teff_e,nsamples)+sptoffset\n#                     vals = f(x)\n# # assuming an at least 0.5 spectral type uncertainty\n#             spto_e = (numpy.nanstd(vals)**2+0.5**2)**0.5\n#             return spto, spto_e\n#         else:\n#             if verbose: sys.stderr.write('\\nTeff is out of range for {:s} Teff/SpT relation\\n'.format(reference))\n#             return numpy.nan, numpy.nan\n\n# convert spt into teff\n    else:\n\n        teff = numpy.polyval(coeff,numpy.array(inp)-sptoffset)\n        teff_e = numpy.zeros(len(teff))+fitunc\n# add in measurement uncertainties\n        if unc[0] > 0.:\n            for i,s in enumerate(inp):\n                x = numpy.random.normal(s,unc[i],nsamples)\n                vals = numpy.polyval(coeff,x-sptoffset)\n                teff_e[i] = (numpy.nanstd(vals)**2+fitunc**2)**0.5\n# return values\n        if len(inp) == 1: return teff[0]*u.K,teff_e[0]*u.K\n        else: return teff*u.K,teff_e*u.K\n\n\ndef redden(sp, **kwargs):\n    '''\n    Description:\n      Redden a spectrum based on an either Mie theory or a standard interstellar profile\n      using Cardelli, Clayton, and Mathis (1989 ApJ. 345, 245)\n\n    **Usage**\n\n       >>> import splat\n       >>> sp = splat.Spectrum(10001)                   # read in a source\n       >>> spr = splat.redden(sp,av=5.,rv=3.2)          # redden to equivalent of AV=5\n\n    **Note**\n      This routine is still in beta form; only the CCM89 currently works\n\n    '''\n    w = sp.wave.value                           # assuming in microns!\n    av = kwargs.get('av',0.0)\n\n\n    if kwargs.get('mie',False):                 # NOT CURRENTLY FUNCTIONING\n        a = kwargs.get('a',10.)                 # grain size\n        n = kwargs.get('n',1.33)                # complex index of refraction\n        x = 2*numpy.pi*a/w\n        x0 = 2.*numpy.pi*a/0.55                 # for V-band\n        qabs = -4.*x*((n**2-1)/(n**2+2)).imag\n        qsca = (8./3.)*(x**4)*(((n**2-1)/(n**2+2))**2).real\n#        tau = numpy.pi*(a**2)*(qabs+qsca)\n        tau = 1.5*(qabs+qsca)/a    # for constant mass\n        qabs0 = -4.*x0*((n**2-1)/(n**2+2)).imag\n        qsca0 = (8./3.)*(x0**4)*(((n**2-1)/(n**2+2))**2).real\n#        tau0 = numpy.pi*(a**2)*(qabs0+qsca0)\n        tau0 = 1.5*(qabs0+qsca0)/a    # for constant mass\n        scale = (10.**(-0.4*av))\n        absfrac = scale*numpy.exp(numpy.max(tau)-tau)\n    else:\n        x = 1./w\n        a = 0.574*(x**1.61)\n        b = -0.527*(x**1.61)\n        rv = kwargs.get('rv',3.1)\n        absfrac = 10.**(-0.4*av*(a+b/rv))\n\n    if kwargs.get('normalize',False):\n        absfrac = absfrac/numpy.median(absfrac)\n\n#    print(tau0, min(tau), max(tau), max(absfrac), min(absfrac))\n    spabs = Spectrum(wave=w,flux=absfrac)\n    return sp*spabs\n\n\ndef typeToLbol(*args,**kwargs):\n    return typeToLuminosity(*args,**kwargs)\n\ndef typeToLuminosity(spt, uncertainty=0.,reference='filippazzo2015',verbose=False,nsamples=100,reverse=False,**kwargs):\n    \"\"\"\n    :Purpose: \n\n    Takes a spectral type and returns the expected scaled log luminosity (log Lbol/Lsun) based on empirical relations\n\n    :Required Inputs: \n\n        :param spt: string or integer of the spectral type\n\n    :Optional Inputs: \n\n        :param reference: log Lbol/SpT relation reference (also 'ref' and 'set'). These are defined in splat.SPT_LBOL_RELATIONS and are currently as follows:\n\n            - *filippazzo2015* (default): Lbol/SpT relation from `Filippazzo et al. (2015) <http://adsabs.harvard.edu/abs/2013Sci...341.1492D>`_\n              Allowed spectral type range is M6 to T9\n\n        :param uncertainty: uncertainty of ``spt`` (default = 0)\n        :param reverse: apply reverse approach: given BC, infer spectral type\n        :param nsamples: number of Monte Carlo samples for error computation (default = 100)\n\n    :Output: \n    \n        2 element tuple providing the absolute magnitude and its uncertainty\n\n    :Example:\n        >>> import splat\n        >>> print splat.typeToLuminosity('L3')\n    \"\"\"\n\n# Keywords alternatives\n    for f in ['unc','spt_e','error']:\n        if f in list(kwargs.keys()):\n            uncertainty = kwargs.get(f,uncertainty)\n    unc = copy.deepcopy(uncertainty)\n    for f in ['ref','set','method','model','relation']:\n        if f in list(kwargs.keys()):\n            reference = kwargs.get(f,reference)\n    ref = checkEmpiricalRelation(reference.lower().replace(' ',''),splat.SPT_LBOL_RELATIONS)\n    if ref == False:\n        print('\\nSpT/Lbol relation from {} has not be integrated into SPLAT\\n\\n'.format(reference))\n        return numpy.nan, numpy.nan\n    refstring = 'Luminosity/SpT relation for from {}'.format(shortRef(SPT_LBOL_RELATIONS[ref]['bibcode']))\n    if verbose: print('\\nUsing {}'.format(refstring))\n\n# normal approach: SpT -> Lbol\n    if reverse == False:\n\n#Convert spectral type string to number\n        if isinstance(spt,str):\n            sptn = typeToNum(spt, uncertainty=unc)\n        elif isinstance(spt,int) or isinstance(spt,float):\n            sptn = copy.deepcopy(spt)\n        else:\n            raise ValueError('\\nInput spectral type {} must be a string, float or int'.format(spt))\n\n# polynomial method\n        if SPT_LBOL_RELATIONS[ref]['method'] == 'polynomial':\n            rng = SPT_LBOL_RELATIONS[ref]['range']\n            if (rng[0] <= sptn <= rng[1]):\n                lbol = numpy.polyval(SPT_LBOL_RELATIONS[ref]['coeff'], sptn-SPT_LBOL_RELATIONS[ref]['sptoffset'])\n                lbol_error = SPT_LBOL_RELATIONS[ref]['fitunc']\n                if unc > 0.:\n                    vals = numpy.polyval(SPT_LBOL_RELATIONS[ref]['coeff'], numpy.random.normal(sptn - SPT_LBOL_RELATIONS[ref]['sptoffset'], unc, nsamples))\n                    lbol_error = (numpy.nanstd(vals)**2+lbol_error**2)**0.5\n                return lbol, lbol_error\n            else:\n                if verbose: sys.stderr.write('\\nSpectral type {} is out of range for {}'.format(typeToNum(sptn),refstring))\n                return numpy.nan, numpy.nan\n\n# interpolation method\n        elif SPT_LBOL_RELATIONS[ref]['method'] == 'interpolate':\n            rng = [numpy.nanmin(SPT_LBOL_RELATIONS[ref]['spt']),numpy.nanmax(SPT_LBOL_RELATIONS[ref]['spt'])]\n            if (rng[0] <= sptn <= rng[1]):\n                f = interp1d(SPT_LBOL_RELATIONS[ref]['spt'],SPT_LBOL_RELATIONS[ref]['bc'])\n                fe = interp1d(SPT_LBOL_RELATIONS[ref]['spt'],SPT_LBOL_RELATIONS[ref]['rms'])\n                lbol = float(f(sptn))\n                lbol_error = float(fe(sptn))\n                if unc > 0.:\n                    vals = f(numpy.random.normal(sptn, unc, nsamples))\n                    lbol_error = (numpy.nanstd(vals)**2+bc_error**2)**0.5\n                return lbol, lbol_error\n            else:\n                if verbose: sys.stderr.write('\\nSpectral type {} is out of range for {}'.format(typeToNum(sptn),refstring))\n                return numpy.nan, numpy.nan\n        else:\n            raise ValueError('Unknown method {} for {}'.format(SPT_LBOL_RELATIONS[ref]['method'],refstring))\n\n# reverse approach: Lbol -> SpT\n    else:\n        if not isinstance(spt,float): raise ValueError('Running this in reverse you need to provide a log luminosity value instead of {}'.format(spt))\n        if SPT_LBOL_RELATIONS[ref]['method'] == 'polynomial':\n            rng = SPT_LBOL_RELATIONS[ref]['range']\n            x = numpy.linspace(rng[0],rng[1],nsamples)\n            y = numpy.polyval(SPT_LBOL_RELATIONS[ref]['coeff'], x-SPT_LBOL_RELATIONS[ref]['sptoffset'])\n            f = interp1d(y,x)\n            try:\n                lbol = float(f(spt))\n            except:\n                if verbose: print('\\nlog luminosity value {} is outside the range expected for {}'.format(spt,refstring))\n                return numpy.nan, numpy.nan\n            vals = []\n            for i in range(nsamples):\n                ye = y+numpy.random.normal(0,SPT_LBOL_RELATIONS[ref]['fitunc'])\n                f = interp1d(ye,x)\n                try:\n                    vals.append(f(numpy.random.normal(spt,unc)))\n                except:\n                    pass\n            lbol_error = numpy.nanstd(vals)\n            return lbol, lbol_error\n        elif SPT_LBOL_RELATIONS[ref]['method'] == 'interpolate':\n            f = interp1d(SPT_LBOL_RELATIONS[ref]['bc'],SPT_LBOL_RELATIONS[ref]['spt'])\n            try:\n                lbol = f(spt)\n            except:\n                if verbose: print('\\nlog luminosity value {} is outside the range expected for {}'.format(spt,refstring))\n                return numpy.nan, numpy.nan\n            vals = []\n            for i in range(nsamples):\n                y = numpy.random.normal(SPT_LBOL_RELATIONS[ref]['bc'],SPT_LBOL_RELATIONS[ref]['rms'])\n                f = interp1d(y,SPT_LBOL_RELATIONS[ref]['spt'])\n                try:\n                    vals.append(f(numpy.random.normal(spt,unc)))\n                except:\n                    pass\n            lbol_error = numpy.nanstd(vals)\n            return lbol, lbol_error\n        else:\n            raise ValueError('Unknown method {} for {}'.format(SPT_LBOL_RELATIONS[ref]['method'],refstring))\n\n\n\ndef typeToBC(spt, filt, uncertainty=0.,reference='filippazzo2015',verbose=False,nsamples=100,reverse=False,**kwargs):\n    \"\"\"\n    :Purpose: \n\n    Takes a spectral type and a filter, and returns the expected bolometric correction BC = M_bol - M_filter\n\n    :Required Inputs: \n\n        :param spt: string or integer of the spectral type\n        :param filter: filter for which to retrieve absolute magnitude, which must be defined for the given reference set.\n        You can check what filters are available by printing splat.SPT_BC_RELATIONS[reference]['filters'].keys(), where reference is, e.g., 'filippazzo2015'\n\n    :Optional Inputs: \n\n        :param reference: Abs Mag/SpT relation used to compute the absolute magnitude (also 'ref' and 'set'). These are defined in splat.SPT_BC_RELATIONS and are currently as follows:\n\n            - *liu2010*: BC/SpT relation from `Liu et al. (2010) <http://adsabs.harvard.edu/abs/2010ApJ...722..311L>`_\n              Allowed spectral type range is M6 to T8.5, and allowed filters are MKO J, H, K\n            - *dupuy2013*: BC/SpT relation from `Dupuy & Kraus (2013) <http://adsabs.harvard.edu/abs/2013Sci...341.1492D>`_\n              Allowed spectral type range is T8 to Y0.5, and allowed filters are MKO Y, J, H\n            - *filippazzo2015* (default): BC/SpT relation from `Filippazzo et al. (2015) <http://adsabs.harvard.edu/abs/2013Sci...341.1492D>`_\n              Allowed spectral type range is M6 to T8/9, and allowed filters are 2MASS J, Ks\n            - *filippazzo2015-young*: BC/SpT relation for young sources from `Filippazzo et al. (2015) <http://adsabs.harvard.edu/abs/2013Sci...341.1492D>`_\n              Allowed spectral type range is M7 to T8, and allowed filters are 2MASS J, Ks\n\n        :param uncertainty: uncertainty of ``spt`` (default = 0)\n        :param reverse: apply reverse approach: given BC, infer spectral type\n        :param nsamples: number of Monte Carlo samples for error computation (default = 100)\n\n    :Output: \n    \n        2 element tuple providing the absolute magnitude and its uncertainty\n\n    :Example:\n        >>> import splat\n        >>> print splat.typeToBC('L3', '2MASS J')\n    \"\"\"\n\n# Keywords alternatives\n    for f in ['unc','spt_e','error']:\n        if f in list(kwargs.keys()):\n            uncertainty = kwargs.get(f,uncertainty)\n    unc = copy.deepcopy(uncertainty)\n    for f in ['ref','set','method','model','relation']:\n        if f in list(kwargs.keys()):\n            reference = kwargs.get(f,reference)\n    ref = copy.deepcopy(reference)\n\n\n# check that you can use the proscribed relation and filter\n    filtcheck = checkFilterName(filt,verbose=verbose)\n    if filtcheck == False: return numpy.nan,numpy.nan\n    else: filt=filtcheck\n\n    refcheck = checkBC(ref,filt=filt,verbose=verbose)\n    if refcheck == False: return numpy.nan,numpy.nan\n    else: ref=refcheck\n\n    refstring = 'BC/SpT relation for filter {} from {}'.format(filt,shortRef(SPT_BC_RELATIONS[ref]['bibcode']))\n    if verbose: print('\\nUsing {}'.format(refstring))\n\n# normal approach: SpT -> BC\n    if reverse == False:\n\n#Convert spectral type string to number\n        if isinstance(spt,str):\n            sptn = typeToNum(spt, uncertainty=unc)\n        elif isinstance(spt,int) or isinstance(spt,float):\n            sptn = copy.deepcopy(spt)\n        else:\n            raise ValueError('\\nInput spectral type {} must be a string, float or int'.format(spt))\n\n# polynomial method\n        if SPT_BC_RELATIONS[ref]['method'] == 'polynomial':\n            rng = SPT_BC_RELATIONS[ref]['filters'][filt]['range']\n            if (rng[0] <= sptn <= rng[1]):\n                bc = numpy.polyval(SPT_BC_RELATIONS[ref]['filters'][filt]['coeff'], sptn-SPT_BC_RELATIONS[ref]['sptoffset'])\n                bc_error = SPT_BC_RELATIONS[ref]['filters'][filt]['fitunc']\n                if unc > 0.:\n                    vals = numpy.polyval(SPT_BC_RELATIONS[ref]['filters'][filt]['coeff'], numpy.random.normal(sptn - SPT_BC_RELATIONS[ref]['sptoffset'], unc, nsamples))\n                    bc_error = (numpy.nanstd(vals)**2+SPT_BC_RELATIONS[ref]['filters'][filt]['fitunc']**2)**0.5\n                return bc, bc_error\n            else:\n                if verbose: sys.stderr.write('\\nSpectral type {} is out of range for {}'.format(typeToNum(sptn),refstring))\n                return numpy.nan, numpy.nan\n\n# interpolation method\n        elif SPT_BC_RELATIONS[ref]['method'] == 'interpolate':\n            rng = [numpy.nanmin(SPT_BC_RELATIONS[ref]['filters'][filt]['spt']),numpy.nanmax(SPT_BC_RELATIONS[ref]['filters'][filt]['spt'])]\n            if (rng[0] <= sptn <= rng[1]):\n                f = interp1d(SPT_BC_RELATIONS[ref]['filters'][filt]['spt'],SPT_BC_RELATIONS[ref]['filters'][filt]['bc'])\n                fe = interp1d(SPT_BC_RELATIONS[ref]['filters'][filt]['spt'],SPT_BC_RELATIONS[ref]['filters'][filt]['rms'])\n                bc = float(f(sptn))\n                bc_error = float(fe(sptn))\n                if unc > 0.:\n                    vals = f(numpy.random.normal(sptn, unc, nsamples))\n                    bc_error = (numpy.nanstd(vals)**2+bc_error**2)**0.5\n                return bc, bc_error\n            else:\n                if verbose: sys.stderr.write('\\nSpectral type {} is out of range for {}'.format(typeToNum(sptn),refstring))\n                return numpy.nan, numpy.nan\n        else:\n            raise ValueError('Unknown method {} for {}'.format(SPT_BC_RELATIONS[ref]['method'],refstring))\n\n# reverse approach: BC -> SpT\n    else:\n        if not isinstance(spt,float): raise ValueError('Running this in reverse you need to provide a BC value instead of {}'.format(spt))\n        if SPT_BC_RELATIONS[ref]['method'] == 'polynomial':\n            rng = SPT_BC_RELATIONS[ref]['filters'][filt]['range']\n            x = numpy.linspace(rng[0],rng[1],nsamples)\n            y = numpy.polyval(SPT_BC_RELATIONS[ref]['filters'][filt]['coeff'], x-SPT_BC_RELATIONS[ref]['sptoffset'])\n            f = interp1d(y,x)\n            try:\n                bc = float(f(spt))\n            except:\n                if verbose: print('\\nBC value {} is outside the range expected for {}'.format(spt,refstring))\n                return numpy.nan, numpy.nan\n            vals = []\n            for i in range(nsamples):\n                ye = y+numpy.random.normal(0,SPT_BC_RELATIONS[ref]['filters'][filt]['fitunc'])\n                f = interp1d(ye,x)\n                try:\n                    vals.append(f(numpy.random.normal(spt,unc)))\n                except:\n                    pass\n            bc_error = numpy.nanstd(vals)\n            return bc, bc_error\n        elif SPT_BC_RELATIONS[ref]['method'] == 'interpolate':\n            f = interp1d(SPT_BC_RELATIONS[ref]['filters'][filt]['bc'],SPT_BC_RELATIONS[ref]['filters'][filt]['spt'])\n            try:\n                bc = f(spt)\n            except:\n                if verbose: print('\\nBC value {} is outside the range expected for {}'.format(spt,refstring))\n                return numpy.nan, numpy.nan\n            vals = []\n            for i in range(nsamples):\n                y = numpy.random.normal(SPT_BC_RELATIONS[ref]['filters'][filt]['bc'],SPT_BC_RELATIONS[ref]['filters'][filt]['rms'])\n                f = interp1d(y,SPT_BC_RELATIONS[ref]['filters'][filt]['spt'])\n                try:\n                    vals.append(f(numpy.random.normal(spt,unc)))\n                except:\n                    pass\n            bc_error = numpy.nanstd(vals)\n            return bc, bc_error\n        else:\n            raise ValueError('Unknown method {} for {}'.format(SPT_BC_RELATIONS[ref]['method'],refstring))\n\n\n\n\n\n", "meta": {"hexsha": "0c61c572cfc70e16dd6d9d17cc2b9591f8dadc22", "size": 57063, "ext": "py", "lang": "Python", "max_stars_repo_path": "splat/empirical.py", "max_stars_repo_name": "MRickardUK/splat", "max_stars_repo_head_hexsha": "a4e48856a95be3a4f90d1abb01bb6f31c6459274", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "splat/empirical.py", "max_issues_repo_name": "MRickardUK/splat", "max_issues_repo_head_hexsha": "a4e48856a95be3a4f90d1abb01bb6f31c6459274", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "splat/empirical.py", "max_forks_repo_name": "MRickardUK/splat", "max_forks_repo_head_hexsha": "a4e48856a95be3a4f90d1abb01bb6f31c6459274", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.4051948052, "max_line_length": 205, "alphanum_fraction": 0.6143385381, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 16284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3593641588823761, "lm_q1q2_score": 0.18669734288477402}}
{"text": "from netCDF4 import Dataset\nimport numpy as np\nfrom .OBSstruct import OBSstruct\nfrom .utils import setDimensions\ndef adjust_survey(S, dt):\n    '''\n    This function spaces the survey_times evenely,\n    and assigns observations to the closest survey.\n\n    Input:\n\n    OBS - OBSstruct object or observation netcdf file\n    dt - interval between each survey_time in hours\n    Output:\n\n    OBS  - observation object\n    '''\n\n    if not isinstance(S,OBSstruct):\n        fid = Dataset(S)\n        OBS = OBSstruct(fid)\n    else:\n        OBS=OBSstruct(S)\n    # let's assume survey_time/obs_time are given in decimal days.\n    # Now define a new set of survey_times, based on the value given for dt\n\n    survey_time=np.round(np.arange(np.floor(np.min(OBS.time)),np.ceil(np.max(OBS.time))+dt/24.,dt/24.),4)\n    # The next step should allocate a given observation to the survey_time closest in time to the actual observation time.\n    trydt=list(zip(*[abs(OBS.time - stamp) for stamp in survey_time]))\n    uniquelength=np.array([len(np.unique(sample)) for sample in trydt])\n    # If no observations are taken exactly 1/2 dt away from a survey_time\n    # it is straight forward to assign observations to surveys. In this case\n    # all elements of uniquelength will be equal, and hence np.unique(uniquelength)\n    # will contain only one element.\n\n    if not (len(np.unique(uniquelength)) > 1):\n        otime=[survey_time[np.argmin(item[1])] for item in enumerate(trydt)]\n    else:\n        otime=np.ones_like(OBS.time)*float('nan')\n\n        # Locate unproblematic observations and assign observation time\n        ind = np.array(np.argwhere(uniquelength==len(survey_time))).squeeze()\n        otime[ind]=[survey_time[np.argmin(item[1])] for item in enumerate(np.take(trydt,ind,axis=0))]\n\n        # Now, locate problematic observations.\n        ind = np.array(np.argwhere(uniquelength!=len(survey_time))).squeeze()\n        # If a observation is taken exactly at the survey_time, there might be\n        # timedeltas that are symmetric around 0, but containing zero. No need\n        # to treat them any way special.\n\n        check=[item[1] for item in enumerate(np.take(trydt,ind,axis=0))]\n        popindex=[]\n        trydt=np.array(trydt)\n        # Check if the elements in check are array:\n        if type(check[0]) == np.float64:\n            # If check[0] is a floating point number, there's only one observation to fix.\n            otime[ind] = survey_time[np.argmin(trydt[ind])]\n            popindex.append(0)\n            ind = [ind]\n        else:\n            for n in range(0,len(check)):\n                print(n)\n                if (0 in check[n]):\n                    print('here')\n                    popindex.append(n)\n                    otime[ind[n]] = survey_time[np.argmin(trydt[ind[n]])]\n\n        # Now get rid of indicies that we assigned values for:\n        newind = np.array([i for j, i in enumerate(ind) if j not in popindex]).squeeze()\n        # Only continue if there are any observations left to handle:\n        if (newind.size != 0):\n            # Loop over unique observation times\n            probtimes = np.array(np.unique(np.take(OBS.time,newind))).squeeze()\n            if probtimes.size == 1:\n                n = probtimes\n                # Locate variables with coinciding observation time\n\n                tmpind = newind[np.array(OBS.time)[newind]== n]\n                if (tmpind.size == 1):\n                    otime[tmpind]=survey_time[np.argmin(trydt[tmpind])]\n                else:\n                    # For each observation type, assign half of values to lower\n                    # survey_time, other half to higher survey_time\n                    # If only one observation of given type, assign it to the lower.\n                    ntypes=np.array(np.unique(np.take(OBS.type,tmpind))).squeeze()\n                    if not (ntypes.size>1):\n                        # First half gets first mintime\n                        np.put(otime,tmpind[0:int(np.floor(len(tmpind)/2.))],[survey_time[np.argmin(item[1])] for item in enumerate(np.take(trydt,tmpind[0:int(np.floor(len(tmpind)/2.))]))])\n                        # Second half gets last mintime\n                        np.put(otime,tmpind[int(np.floor(len(tmpind)/2.)):],[survey_time[np.argmin(item[1])+1] for item in enumerate(np.take(trydt,tmpind[int(np.floor(len(tmpind)/2.)):]))])\n                    else:\n\n                        for t in range(0,ntypes.size):\n                            typeind=tmpind[np.take(OBS.type,tmpind)==ntypes[t]]\n                            if (typeind.size == 1):\n                                otime[typeind]=survey_time[np.argmin(trydt[typeind])]\n                            else:\n                                # First half gets first mintime\n                                np.put(otime,typeind[0:int(np.floor(len(typeind)/2.))],[survey_time[np.argmin(item[1])] for item in enumerate(np.take(trydt,typeind[0:int(np.floor(len(typeind)/2.))]))])\n                                # Second half gets last mintime\n                                np.put(otime,typeind[int(np.floor(len(typeind)/2.)):],[survey_time[np.argmin(item[1])+1] for item in enumerate(np.take(trydt,typeind[int(np.floor(len(typeind)/2.)):]))])\n\n            else:\n                for n in probtimes:\n\n                    # Locate variables with coinciding observation time\n                    #tmpind=newind[np.take(OBS.time,newind)==probtimes[n]]\n                    #tmpind=newind[np.array(OBS.time)[newind]==probtimes[n]]\n\n                    tmpind=newind[np.array(OBS.time)[newind]== n]\n                    if (tmpind.size==1):\n                        otime[tmpind]=survey_time[np.argmin(trydt[tmpind])]\n                    else:\n                        # For each observation type, assign half of values to lower\n                        # survey_time, other half to higher survey_time\n                        # If only one observation of given type, assign it to the lower.\n                        ntypes=np.array(np.unique(np.take(OBS.type,tmpind))).squeeze()\n                        if not (ntypes.size>1):\n                            # First half gets first mintime\n                            np.put(otime,tmpind[0:int(np.floor(len(tmpind)/2.))],[survey_time[np.argmin(item[1])] for item in enumerate(np.take(trydt,tmpind[0:int(np.floor(len(tmpind)/2.))]))])\n                            # Second half gets last mintime\n                            np.put(otime,tmpind[int(np.floor(len(tmpind)/2.)):],[survey_time[np.argmin(item[1])+1] for item in enumerate(np.take(trydt,tmpind[int(np.floor(len(tmpind)/2.)):]))])\n                        else:\n\n                            for t in range(0,ntypes.size):\n                                typeind=tmpind[np.take(OBS.type,tmpind)==ntypes[t]]\n                                if (typeind.size == 1):\n                                    otime[typeind]=survey_time[np.argmin(trydt[typeind])]\n                                else:\n                                    # First half gets first mintime\n                                    np.put(otime,typeind[0:int(np.floor(len(typeind)/2.))],[survey_time[np.argmin(item[1])] for item in enumerate(np.take(trydt,typeind[0:int(np.floor(len(typeind)/2.))]))])\n                                    # Second half gets last mintime\n                                    np.put(otime,typeind[int(np.floor(len(typeind)/2.)):],[survey_time[np.argmin(item[1])+1] for item in enumerate(np.take(trydt,typeind[int(np.floor(len(typeind)/2.)):]))])\n\n    # OK, that should have done the job!\n    # Now we need to find number of observations within each survey_time,\n    # and delete surveys that does not contain  observations\n    OBS.time=otime\n    OBS=setDimensions(OBS)\n\n    OBS.toarray()\n    return OBS\n", "meta": {"hexsha": "679fdc5092942d41f87073522deba54fa80d8054", "size": 7759, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyromsobs/adjust_survey.py", "max_stars_repo_name": "metno/pyromsobs", "max_stars_repo_head_hexsha": "8479a13908797a5e7370f272a3462b7c6d59e45e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyromsobs/adjust_survey.py", "max_issues_repo_name": "metno/pyromsobs", "max_issues_repo_head_hexsha": "8479a13908797a5e7370f272a3462b7c6d59e45e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyromsobs/adjust_survey.py", "max_forks_repo_name": "metno/pyromsobs", "max_forks_repo_head_hexsha": "8479a13908797a5e7370f272a3462b7c6d59e45e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-05-24T08:53:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-24T08:53:28.000Z", "avg_line_length": 54.2587412587, "max_line_length": 205, "alphanum_fraction": 0.5694032736, "include": true, "reason": "import numpy", "num_tokens": 1753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.186697342884774}}
{"text": "# Copyright 2014-2021 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n'''\nThere are two options to call wannier90 in PySCF.  One is the pyWannier90.py\ninterface as implemented in this file.\n\n(1)\npyWannier90: Wannier90 for PySCF (https://github.com/hungpham2017/pyWannier90)\nHung Q. Pham\nemail: pqh3.14@gmail.com\n\n(2)\nAnother wannier90 python interface is available on the repo:\n    https://github.com/zhcui/wannier90\nContact its author \"Zhihao Cui\" <zcui@caltech.edu> for more details of\ninstallation and implementations.\n'''\n\nimport os, time\nimport numpy as np\nfrom scipy.io import FortranFile\nimport pyscf.data.nist as param\nfrom pyscf import lib\nfrom pyscf.pbc import df\nfrom pyscf.pbc.dft import gen_grid, numint\n\ntry:\n    import libwannier90\nexcept ImportError:\n    print('WARNING: Check the installation of libwannier90 and its path in pyscf/pbc/tools/pywannier90.py')\n    print('libwannier90 can be found at: https://github.com/hungpham2017/pyWannier90')\n    raise\n\n\ndef save_kmf(kmf, chkfile):\n    ''' Save a wavefunction'''\n    from pyscf.lib.chkfile import save\n    kpts = kmf.kpts\n    mo_energy_kpts = kmf.mo_energy_kpts\n    mo_coeff_kpts = kmf.mo_coeff_kpts\n\n    scf_dic = {'kpts'          : kpts,\n               'mo_energy_kpts': mo_energy_kpts,\n               'mo_coeff_kpts' : mo_coeff_kpts}\n    save(chkfile, 'scf', scf_dic)\n\ndef load_kmf(chkfile):\n    ''' Load a wavefunction'''\n    from pyscf.lib.chkfile import load\n    kmf = load(chkfile, 'scf')\n    class fake_kmf:\n        def __init__(self, kmf):\n            self.kpts = kmf['kpts']\n            self.mo_energy_kpts = kmf['mo_energy_kpts']\n            self.mo_coeff_kpts = kmf['mo_coeff_kpts']\n    kmf = fake_kmf(kmf)\n    return kmf\n\ndef angle(v1, v2):\n    '''\n    Return the angle (in radiant between v1 and v2)\n    '''\n\n    v1 = np.asarray(v1)\n    v2 = np.asarray(v2)\n    cosa = v1.dot(v2)/ np.linalg.norm(v1) / np.linalg.norm(v2)\n    return np.arccos(cosa)\n\ndef transform(x_vec, z_vec):\n    '''\n    Construct a transformation matrix to transform r_vec to the new coordinate system defined by x_vec and z_vec\n    '''\n\n    x_vec = x_vec/np.linalg.norm(np.asarray(x_vec))\n    z_vec = z_vec/np.linalg.norm(np.asarray(z_vec))\n    assert x_vec.dot(z_vec) == 0    # x and z have to be orthogonal to one another\n    y_vec = -np.cross(x_vec,z_vec)\n    new = np.asarray([x_vec, y_vec, z_vec])\n    original = np.asarray([[1,0,0],[0,1,0],[0,0,1]])\n\n    tran_matrix = np.empty([3,3])\n    for row in range(3):\n        for col in range(3):\n            tran_matrix[row,col] = np.cos(angle(original[row],new[col]))\n\n    return tran_matrix.T\n\ndef cartesian_prod(arrays, out=None, order='C'):\n    '''\n    This function is similar to lib.cartesian_prod of PySCF, except the output can be in Fortran or in C order\n    '''\n    arrays = [np.asarray(x) for x in arrays]\n    dtype = np.result_type(*arrays)\n    nd = len(arrays)\n    dims = [nd] + [len(x) for x in arrays]\n\n    if out is None:\n        out = np.empty(dims, dtype)\n    else:\n        out = np.ndarray(dims, dtype, buffer=out)\n    tout = out.reshape(dims)\n\n    shape = [-1] + [1] * nd\n    for i, arr in enumerate(arrays):\n        tout[i] = arr.reshape(shape[:nd-i])\n\n    return tout.reshape((nd,-1),order=order).T\n\ndef periodic_grid(cell, grid=[50,50,50], supercell=[1,1,1], order='C'):\n    '''\n    Generate a periodic grid for the unit/computational cell in F/C order\n    '''\n    ngrid = np.asarray(grid)\n    qv = cartesian_prod([np.arange(-ngrid[i]*(supercell[i]//2),ngrid[i]*((supercell[i]+1)//2)) for i in range(3)], order=order)\n    a_frac = lib.einsum('i,ij->ij', 1./ngrid, cell.lattice_vectors())\n    coords = np.dot(qv, a_frac)\n\n    # Compute weight\n    ngrids = np.prod(grid)\n    ncells = np.prod(supercell)\n    weights = np.empty(ngrids*ncells)\n    weights[:] = cell.vol / ngrids / ncells\n    return coords, weights\n\ndef R_r(r_norm, r=1, zona=1):\n    r'''\n    Radial functions used to compute \\Theta_{l,m_r}(\\theta,\\phi)\n    '''\n\n    if r == 1:\n        R_r = 2 * zona**(3/2) * np.exp(-zona*r_norm)\n    elif r == 2:\n        R_r = 1 / 2 / np.sqrt(2) * zona**(3/2) * (2 - zona*r_norm) * np.exp(-zona*r_norm/2)\n    else:\n        R_r = np.sqrt(4/27) * zona**(3/2) * (1 - 2*zona*r_norm/3 + 2*(zona**2)*(r_norm**2)/27) * np.exp(-zona*r_norm/3)\n\n    return R_r\n\ndef theta(func, cost, phi):\n    r'''\n    Basic angular functions (s,p,d,f) used to compute \\Theta_{l,m_r}(\\theta,\\phi)\n    ref: Table 3.1 of the Wannier90 User guide\n        Link: https://github.com/wannier-developers/wannier90/raw/v3.1.0/doc/compiled_docs/user_guide.pdf\n    '''\n    sint = np.sqrt(1 - cost**2)\n    if func == 's':\n        theta = 1 / np.sqrt(4 * np.pi) * np.ones([cost.shape[0]])\n    elif func == 'pz':\n        theta = np.sqrt(3 / 4 / np.pi) * cost\n    elif func == 'px':\n        theta = np.sqrt(3 / 4 / np.pi) * sint * np.cos(phi)\n    elif func == 'py':\n        theta = np.sqrt(3 / 4 / np.pi) * sint * np.sin(phi)\n    elif func == 'dz2':\n        theta = np.sqrt(5 / 16 / np.pi) * (3*cost**2 - 1)\n    elif func == 'dxz':\n        theta = np.sqrt(15 / 4 / np.pi) * sint * cost * np.cos(phi)\n    elif func == 'dyz':\n        theta = np.sqrt(15 / 4 / np.pi) * sint * cost * np.sin(phi)\n    elif func == 'dx2-y2':\n        theta = np.sqrt(15 / 16 / np.pi) * (sint**2) * np.cos(2*phi)\n    elif func == 'dxy':\n        theta = np.sqrt(15 / 16 / np.pi) * (sint**2) * np.sin(2*phi)\n    elif func == 'fz3':\n        theta = np.sqrt(7) / 4 / np.sqrt(np.pi) * (5*cost**3 - 3*cost)\n    elif func == 'fxz2':\n        theta = np.sqrt(21) / 4 / np.sqrt(2*np.pi) * (5*cost**2 - 1) * sint * np.cos(phi)\n    elif func == 'fyz2':\n        theta = np.sqrt(21) / 4 / np.sqrt(2*np.pi) * (5*cost**2 - 1) * sint * np.sin(phi)\n    elif func == 'fz(x2-y2)':\n        theta = np.sqrt(105) / 4 / np.sqrt(np.pi) * sint**2 * cost * np.cos(2*phi)\n    elif func == 'fxyz':\n        theta = np.sqrt(105) / 4 / np.sqrt(np.pi) * sint**2 * cost * np.sin(2*phi)\n    elif func == 'fx(x2-3y2)':\n        theta = np.sqrt(35) / 4 / np.sqrt(2*np.pi) * sint**3 * (np.cos(phi)**2 - 3*np.sin(phi)**2) * np.cos(phi)\n    elif func == 'fy(3x2-y2)':\n        theta = np.sqrt(35) / 4 / np.sqrt(2*np.pi) * sint**3 * (3*np.cos(phi)**2 - np.sin(phi)**2) * np.sin(phi)\n\n    return theta\n\ndef theta_lmr(l, mr, cost, phi):\n    r'''\n    Compute the value of \\Theta_{l,m_r}(\\theta,\\phi)\n    ref: Table 3.1 and 3.2 of the Wannier90 User guide\n        Link: https://github.com/wannier-developers/wannier90/raw/v3.1.0/doc/compiled_docs/user_guide.pdf\n    '''\n    assert l in [0,1,2,3,-1,-2,-3,-4,-5]\n    assert mr in [1,2,3,4,5,6,7]\n\n    if l == 0:                           # s\n        theta_lmr = theta('s', cost, phi)\n    elif (l == 1) and (mr == 1):         # pz\n        theta_lmr = theta('pz', cost, phi)\n    elif (l == 1) and (mr == 2):         # px\n        theta_lmr = theta('px', cost, phi)\n    elif (l == 1) and (mr == 3):         # py\n        theta_lmr = theta('py', cost, phi)\n    elif (l == 2) and (mr == 1):         # dz2\n        theta_lmr = theta('dz2', cost, phi)\n    elif (l == 2) and (mr == 2):         # dxz\n        theta_lmr = theta('dxz', cost, phi)\n    elif (l == 2) and (mr == 3):         # dyz\n        theta_lmr = theta('dyz', cost, phi)\n    elif (l == 2) and (mr == 4):         # dx2-y2\n        theta_lmr = theta('dx2-y2', cost, phi)\n    elif (l == 2) and (mr == 5):         # dxy\n        theta_lmr = theta('dxy', cost, phi)\n    elif (l == 3) and (mr == 1):         # fz3\n        theta_lmr = theta('fz3', cost, phi)\n    elif (l == 3) and (mr == 2):         # fxz2\n        theta_lmr = theta('fxz2', cost, phi)\n    elif (l == 3) and (mr == 3):         # fyz2\n        theta_lmr = theta('fyz2', cost, phi)\n    elif (l == 3) and (mr == 4):         # fz(x2-y2)\n        theta_lmr = theta('fz(x2-y2)', cost, phi)\n    elif (l == 3) and (mr == 5):         # fxyz\n        theta_lmr = theta('fxyz', cost, phi)\n    elif (l == 3) and (mr == 6):         # fx(x2-3y2)\n        theta_lmr = theta('fx(x2-3y2)', cost, phi)\n    elif (l == 3) and (mr == 7):         # fy(3x2-y2)\n        theta_lmr = theta('fy(3x2-y2)', cost, phi)\n    elif (l == -1) and (mr == 1):         # sp-1\n        theta_lmr = 1/np.sqrt(2) * (theta('s', cost, phi) + theta('px', cost, phi))\n    elif (l == -1) and (mr == 2):         # sp-2\n        theta_lmr = 1/np.sqrt(2) * (theta('s', cost, phi) - theta('px', cost, phi))\n    elif (l == -2) and (mr == 1):         # sp2-1\n        theta_lmr = 1/np.sqrt(3) * theta('s', cost, phi) - 1/np.sqrt(6) *theta('px', cost, phi) + 1/np.sqrt(2) * theta('py', cost, phi)\n    elif (l == -2) and (mr == 2):         # sp2-2\n        theta_lmr = 1/np.sqrt(3) * theta('s', cost, phi) - 1/np.sqrt(6) *theta('px', cost, phi) - 1/np.sqrt(2) * theta('py', cost, phi)\n    elif (l == -2) and (mr == 3):         # sp2-3\n        theta_lmr = 1/np.sqrt(3) * theta('s', cost, phi) + 2/np.sqrt(6) *theta('px', cost, phi)\n    elif (l == -3) and (mr == 1):         # sp3-1\n        theta_lmr = 1/2 * (theta('s', cost, phi) + theta('px', cost, phi) + theta('py', cost, phi) + theta('pz', cost, phi))\n    elif (l == -3) and (mr == 2):         # sp3-2\n        theta_lmr = 1/2 * (theta('s', cost, phi) + theta('px', cost, phi) - theta('py', cost, phi) - theta('pz', cost, phi))\n    elif (l == -3) and (mr == 3):         # sp3-3\n        theta_lmr = 1/2 * (theta('s', cost, phi) - theta('px', cost, phi) + theta('py', cost, phi) - theta('pz', cost, phi))\n    elif (l == -3) and (mr == 4):         # sp3-4\n        theta_lmr = 1/2 * (theta('s', cost, phi) - theta('px', cost, phi) - theta('py', cost, phi) + theta('pz', cost, phi))\n    elif (l == -4) and (mr == 1):         # sp3d-1\n        theta_lmr = 1/np.sqrt(3) * theta('s', cost, phi) - 1/np.sqrt(6) *theta('px', cost, phi) + 1/np.sqrt(2) * theta('py', cost, phi)\n    elif (l == -4) and (mr == 2):         # sp3d-2\n        theta_lmr = 1/np.sqrt(3) * theta('s', cost, phi) - 1/np.sqrt(6) *theta('px', cost, phi) - 1/np.sqrt(2) * theta('py', cost, phi)\n    elif (l == -4) and (mr == 3):         # sp3d-3\n        theta_lmr = 1/np.sqrt(3) * theta('s', cost, phi) + 2/np.sqrt(6) * theta('px', cost, phi)\n    elif (l == -4) and (mr == 4):         # sp3d-4\n        theta_lmr = 1/np.sqrt(2) * (theta('pz', cost, phi) + theta('dz2', cost, phi))\n    elif (l == -4) and (mr == 5):         # sp3d-5\n        theta_lmr = 1/np.sqrt(2) * (-theta('pz', cost, phi) + theta('dz2', cost, phi))\n    elif (l == -5) and (mr == 1):         # sp3d2-1\n        theta_lmr = 1/np.sqrt(6) * theta('s', cost, phi) - 1/np.sqrt(2) *theta('px', cost, phi) - 1/np.sqrt(12) *theta('dz2', cost, phi) \\\n                    + 1/2 *theta('dx2-y2', cost, phi)\n    elif (l == -5) and (mr == 2):         # sp3d2-2\n        theta_lmr = 1/np.sqrt(6) * theta('s', cost, phi) + 1/np.sqrt(2) *theta('px', cost, phi) - 1/np.sqrt(12) *theta('dz2', cost, phi) \\\n                    + 1/2 *theta('dx2-y2', cost, phi)\n    elif (l == -5) and (mr == 3):         # sp3d2-3\n        theta_lmr = 1/np.sqrt(6) * theta('s', cost, phi) - 1/np.sqrt(2) *theta('py', cost, phi) - 1/np.sqrt(12) *theta('dz2', cost, phi) \\\n                    - 1/2 *theta('dx2-y2', cost, phi)\n    elif (l == -5) and (mr == 4):         # sp3d2-4\n        theta_lmr = 1/np.sqrt(6) * theta('s', cost, phi) + 1/np.sqrt(2) *theta('py', cost, phi) - 1/np.sqrt(12) *theta('dz2', cost, phi) \\\n                    - 1/2 *theta('dx2-y2', cost, phi)\n    elif (l == -5) and (mr == 5):         # sp3d2-5\n        theta_lmr = 1/np.sqrt(6) * theta('s', cost, phi) - 1/np.sqrt(2) *theta('pz', cost, phi) + 1/np.sqrt(3) *theta('dz2', cost, phi)\n    elif (l == -5) and (mr == 6):         # sp3d2-6\n        theta_lmr = 1/np.sqrt(6) * theta('s', cost, phi) + 1/np.sqrt(2) *theta('pz', cost, phi) + 1/np.sqrt(3) *theta('dz2', cost, phi)\n\n    return theta_lmr\n\ndef g_r(grids_coor, site, l, mr, r, zona, x_axis=[1,0,0], z_axis=[0,0,1], unit='B'):\n    r'''\n    Evaluate the projection function g(r) or \\Theta_{l,m_r}(\\theta,\\phi) on a grid\n    ref: Chapter 3, wannier90 User Guide\n    Attributes:\n        grids_coor : a grids for the cell of interest\n        site       : absolute coordinate (in Borh/Angstrom) of the g(r) in the cell\n        l, mr      : l and mr value in the Table 3.1 and 3.2 of the ref\n    Return:\n        theta_lmr  : an array (ngrid, value) of g(r)\n\n    '''\n\n    unit_conv = 1\n    if unit == 'A': unit_conv = param.BOHR\n\n    r_vec = (grids_coor - site)\n    r_vec = lib.einsum('iv,uv ->iu', r_vec, transform(x_axis, z_axis))\n    r_norm = np.linalg.norm(r_vec,axis=1)\n    if (r_norm < 1e-8).any():\n        r_vec = (grids_coor - site - 1e-5)\n        r_vec = lib.einsum('iv,uv ->iu', r_vec, transform(x_axis, z_axis))\n        r_norm = np.linalg.norm(r_vec,axis=1)\n    cost = r_vec[:,2]/r_norm\n\n    phi = np.empty_like(r_norm)\n    larger_idx = r_vec[:, 0] > 1e-8\n    smaller_idx = r_vec[:, 0] < -1e-8\n    neither_idx = not larger_idx and not smaller_idx\n    phi[larger_idx] = np.arctan(r_vec[larger_idx,1]/r_vec[larger_idx,0])\n    phi[smaller_idx] = np.arctan(r_vec[smaller_idx,1]/r_vec[smaller_idx,0])  + np.pi\n    phi[neither_idx] = np.sign(r_vec[neither_idx,1]) * 0.5 * np.pi\n\n    return theta_lmr(l, mr, cost, phi) * R_r(r_norm * unit_conv, r = r, zona = zona)\n\ndef get_wigner_seitz_supercell(w90, ws_search_size=[2,2,2], ws_distance_tol=1e-6):\n    '''\n    Return a grid that contains all the lattice within the Wigner-Seitz supercell\n    Ref: the hamiltonian_wigner_seitz(count_pts) in wannier90/src/hamittonian.F90\n    '''\n\n    real_metric = w90.real_lattice_loc.T.dot(w90.real_lattice_loc)\n    dist_dim = np.prod(2 * (np.asarray(ws_search_size) + 1) + 1)\n    ndegen = []\n    irvec = []\n    mp_grid = np.asarray(w90.mp_grid_loc)\n    n1_range =  np.arange(-ws_search_size[0] * mp_grid[0], ws_search_size[0]*mp_grid[0] + 1)\n    n2_range =  np.arange(-ws_search_size[1] * mp_grid[1], ws_search_size[1]*mp_grid[1] + 1)\n    n3_range =  np.arange(-ws_search_size[2] * mp_grid[2], ws_search_size[2]*mp_grid[2] + 1)\n    x, y, z = np.meshgrid(n1_range, n2_range, n3_range)\n    n_list = np.vstack([z.flatten('F'), x.flatten('F'), y.flatten('F')]).T\n    i1 = np.arange(- ws_search_size[0] - 1, ws_search_size[0] + 2)\n    i2 = np.arange(- ws_search_size[1] - 1, ws_search_size[1] + 2)\n    i3 = np.arange(- ws_search_size[2] - 1, ws_search_size[2] + 2)\n    x, y, z = np.meshgrid(i1, i2, i3)\n    i_list = np.vstack([z.flatten('F'), x.flatten('F'), y.flatten('F')]).T\n\n    nrpts = 0\n    for n in n_list:\n        # Calculate |r-R|^2\n        ndiff = n - i_list * mp_grid\n        dist = (ndiff.dot(real_metric).dot(ndiff.T)).diagonal()\n\n        dist_min = dist.min()\n        if abs(dist[(dist_dim + 1)//2 -1] - dist_min) < ws_distance_tol**2:\n            temp = 0\n            for i in range(0, dist_dim):\n                if (abs(dist[i] - dist_min) < ws_distance_tol**2):\n                    temp = temp + 1\n            ndegen.append(temp)\n            irvec.append(n.tolist())\n            if (n**2).sum() < 1.e-10: rpt_origin = nrpts\n            nrpts = nrpts + 1\n\n    irvec = np.asarray(irvec)\n    ndegen = np.asarray(ndegen)\n\n    # Check the \"sum rule\"\n    tot = np.sum(1/np.asarray(ndegen))\n    assert tot - np.prod(mp_grid) < 1e-8, \"Error in finding Wigner-Seitz points!!!\"\n\n    return ndegen, irvec, rpt_origin\n\ndef R_wz_sc(w90, R_in, R0, ws_search_size=[2,2,2], ws_distance_tol=1e-6):\n    '''\n    TODO: document it\n    Ref: This is the replication of the R_wz_sc function of ws_distance.F90\n    '''\n    ndegenx = 8 #max number of unit cells that can touch in a single point (i.e.  vertex of cube)\n    R_bz = np.asarray(R_in).reshape(-1, 3)\n    nR = R_bz.shape[0]\n    R0 = np.asarray(R0)\n    ndeg = np.zeros([nR], dtype=np.int32)\n    ndeg_ = np.zeros([nR, ndegenx])\n    shifts = np.zeros([nR, ndegenx, 3])\n    R_out = np.zeros([nR, ndegenx, 3])\n\n    mod2_R_bz = np.sum((R_bz - R0)**2, axis=1)\n    R_in_f = R_bz.dot(w90.recip_lattice_loc.T / 2 / np.pi)\n    n1_range =  np.arange(-ws_search_size[0] - 1, ws_search_size[0] + 2)\n    n2_range =  np.arange(-ws_search_size[1] - 1, ws_search_size[1] + 2)\n    n3_range =  np.arange(-ws_search_size[2] - 1, ws_search_size[2] + 2)\n    x, y, z = np.meshgrid(n1_range, n2_range, n3_range)\n    n_list = np.vstack([z.flatten('F'), x.flatten('F'), y.flatten('F')]).T\n    trans_vecs = n_list * w90.mp_grid_loc\n\n    # First loop:\n    R_f = np.repeat(R_in_f[:,np.newaxis,:], trans_vecs.shape[0], axis=1) + trans_vecs\n    R = R_f.dot(w90.real_lattice_loc)\n    mod2_R = np.sum((R - R0)**2, axis=2)\n    mod2_R_min = mod2_R.min(axis=1)\n    mod2_R_min_idx = np.argmin(mod2_R, axis=1)\n    idx = mod2_R_min < mod2_R_bz\n    R_bz[idx] = R[idx, mod2_R_min_idx[idx]]\n    mod2_R_bz[idx] = mod2_R_min[idx]\n    shifts_data = np.repeat(trans_vecs[np.newaxis,:,:], nR, axis=0)[idx, mod2_R_min_idx[idx]]\n    shifts[idx] = np.repeat(shifts_data[:,np.newaxis,:], ndegenx, axis=1)\n\n    idx = mod2_R_bz < ws_distance_tol**2\n    ndeg[idx] = 1\n    R_out[idx, 0] = R0\n\n    # Second loop:\n    R_in_f = R_bz.dot(w90.recip_lattice_loc.T / 2 / np.pi)\n    R_f = np.repeat(R_in_f[:,np.newaxis,:], trans_vecs.shape[0], axis=1) + trans_vecs\n    R = R_f.dot(w90.real_lattice_loc)\n    mod2_R = np.sum((R - R0)**2, axis=2)\n    mod2_R_bz = np.repeat(mod2_R_bz[:,np.newaxis], trans_vecs.shape[0], axis=1)\n    abs_diff = abs(np.sqrt(mod2_R) - np.sqrt(mod2_R_bz))\n    idx = abs_diff < ws_distance_tol\n    ndeg = idx.sum(axis=1)\n    assert (ndeg <= 8).all(), \"The degeneracy cannot be larger than 8\"\n    for i in range(nR):\n        R_out[i, :ndeg[i]] = R[i, idx[i]]\n        shifts[i, :ndeg[i]] = shifts[i, :ndeg[i]] + trans_vecs[idx[i]]\n        ndeg_[i, :ndeg[i]] = 1.0\n\n    return ndeg_, ndeg, R_out, shifts\n\ndef ws_translate_dist(w90, irvec, ws_search_size=[2,2,2], ws_distance_tol=1e-6):\n    '''\n    TODO: document it\n    Ref: This is the replication of the ws_translate_dist function of ws_distance.F90\n    '''\n    nrpts = irvec.shape[0]\n    ndegenx = 8 #max number of unit cells that can touch in a single point (i.e.  vertex of cube)\n    num_wann = w90.num_wann\n    assert ndegenx*num_wann*nrpts > 0, \"Unexpected dimensions in ws_translate_dist\"\n\n    irvec_ = []\n    wann_centres_i = []\n    wann_centres_j = []\n    for i in range(3):\n        x, y, z = np.meshgrid(irvec[:,i], np.zeros(num_wann), np.zeros(num_wann), indexing='ij')\n        irvec_.append(x.flatten())\n        x, y, z = np.meshgrid(np.zeros(nrpts), np.zeros(num_wann), w90.wann_centres[:,i], indexing='ij')\n        wann_centres_i.append(z.flatten())\n        x, y, z = np.meshgrid(np.zeros(nrpts), w90.wann_centres[:,i], np.zeros(num_wann), indexing='ij')\n        wann_centres_j.append(y.flatten())\n\n\n    irvec_list = np.vstack(irvec_).T\n    irvec_cart_list = irvec_list.dot(w90.real_lattice_loc)\n    wann_centres_i_list = np.vstack(wann_centres_i).T\n    wann_centres_j_list = np.vstack(wann_centres_j).T\n    R_in = irvec_cart_list - wann_centres_i_list + wann_centres_j_list\n    wdist_ndeg_, wdist_ndeg, R_out, shifts = w90.R_wz_sc(R_in, [0,0,0], ws_search_size, ws_distance_tol)\n    ndegenx = wdist_ndeg_.shape[1]\n    irdist_ws = np.repeat(irvec_list[:,np.newaxis,:], ndegenx, axis=1) + shifts\n    crdist_ws = irdist_ws.dot(w90.real_lattice_loc)\n\n    # Reformat the matrices for the computational convenience in lib.einsum\n    wdist_ndeg = wdist_ndeg.reshape(nrpts, num_wann, num_wann)\n    wdist_ndeg_ = wdist_ndeg_.reshape(nrpts, num_wann, num_wann, ndegenx).transpose(3,0,1,2)\n    irdist_ws = irdist_ws.reshape(nrpts, num_wann, num_wann, ndegenx, 3).transpose(3,0,1,2,4)\n    crdist_ws = crdist_ws.reshape(nrpts, num_wann, num_wann, ndegenx, 3).transpose(3,0,1,2,4)\n\n    return wdist_ndeg, wdist_ndeg_, irdist_ws, crdist_ws\n\n\n'''Main class of pyWannier90'''\nclass W90:\n    def __init__(self, kmf, cell, mp_grid, num_wann, gamma=False, spinors=False, spin_up=None, other_keywords=None):\n\n        if isinstance(kmf, str):\n            self.kmf = load_kmf(kmf)\n        else:\n            self.kmf = kmf\n        self.cell = cell\n        self.num_wann = num_wann\n        self.keywords = other_keywords\n\n        # Collect the pyscf calculation info\n        nao_kpts = []\n        for mo_energy in kmf.mo_energy_kpts:\n            nao_kpts.append(mo_energy.shape[0])\n\n        self.num_bands_tot = np.min(nao_kpts)\n        if self.num_bands_tot < cell.nao_nr():\n            print(('The number of bands at different k-point are not the same. '\n                   'The first %d bands are used.') % (self.num_bands_tot) )\n\n        self.num_kpts_loc = self.kmf.kpts.shape[0]\n        self.mp_grid_loc = mp_grid\n        assert self.num_kpts_loc == np.asarray(self.mp_grid_loc).prod()\n        self.real_lattice_loc = self.cell.lattice_vectors() * param.BOHR\n        self.recip_lattice_loc = self.cell.reciprocal_vectors() / param.BOHR\n        self.kpt_latt_loc = self.cell.get_scaled_kpts(self.kmf.kpts)\n        self.num_atoms_loc = self.cell.natm\n        self.atom_symbols_loc = [atom[0] for atom in self.cell._atom]\n        self.atom_atomic_loc = [int(self.cell._atm[atom][0] + self.cell.atom_nelec_core(atom))\n                                for atom in range(self.num_atoms_loc)]\n        self.atoms_cart_loc = np.asarray([(np.asarray(atom[1])* param.BOHR).tolist()\n                                          for atom in self.cell._atom])\n        self.gamma_only, self.spinors = (0 , 0)\n        if gamma: self.gamma_only = 1\n        if spinors: self.spinors = 1\n\n        # Wannier90_setup outputs\n        self.num_bands_loc = None\n        self.num_wann_loc = None\n        self.nntot_loc = None\n        self.nn_list = None\n        self.proj_site = None\n        self.proj_l = None\n        self.proj_m = None\n        self.proj_radial = None\n        self.proj_z = None\n        self.proj_x = None\n        self.proj_zona = None\n        self.exclude_bands = None\n        self.proj_s = None\n        self.proj_s_qaxis = None\n\n        # Input for Wannier90_run\n        self.band_included_list = None\n        self.A_matrix_loc = None\n        self.M_matrix_loc = None\n        self.eigenvalues_loc = None\n\n        # Wannier90_run outputs\n        self.U_matrix = None\n        self.U_matrix_opt = None\n        self.lwindow = None\n        self.wann_centres = None\n        self.wann_spreads = None\n        self.spread = None\n\n        # Others\n        self.use_bloch_phases = False\n        self.spin_up = spin_up\n        self.mo_energy_kpts = []\n        self.mo_coeff_kpts = []\n        if np.mod(self.cell.nelectron,2) !=0:\n            if spin_up:\n                for kpt in range(self.num_kpts_loc):\n                    self.mo_energy_kpts.append(self.kmf.mo_energy_kpts[0][kpt][:self.num_bands_tot])\n                    self.mo_coeff_kpts.append(self.kmf.mo_coeff_kpts[0][kpt][:,:self.num_bands_tot])\n            else:\n                for kpt in range(self.num_kpts_loc):\n                    self.mo_energy_kpts.append(self.kmf.mo_energy_kpts[1][kpt][:self.num_bands_tot])\n                    self.mo_coeff_kpts.append(self.kmf.mo_coeff_kpts[1][kpt][:,:self.num_bands_tot])\n        else:\n\n            for kpt in range(self.num_kpts_loc):\n                self.mo_energy_kpts.append(self.kmf.mo_energy_kpts[kpt][:self.num_bands_tot])\n                self.mo_coeff_kpts.append(self.kmf.mo_coeff_kpts[kpt][:,:self.num_bands_tot])\n\n    def kernel(self, external_AME=None):\n        '''\n        Main kernel for pyWannier90\n        '''\n        self.make_win()\n        self.setup()\n        if external_AME is not None:\n            self.M_matrix_loc = self.read_M_mat(external_AME + '.mmn')\n            self.A_matrix_loc = self.read_A_mat(external_AME + '.amn')\n            self.eigenvalues_loc = self.read_epsilon_mat(external_AME + '.eig')\n        else:\n            self.M_matrix_loc = self.get_M_mat()\n            self.A_matrix_loc = self.get_A_mat()\n            self.eigenvalues_loc = self.get_epsilon_mat()\n        self.run()\n\n    def make_win(self):\n        '''\n        Make a basic *.win file for wannier90\n        '''\n\n        win_file = open('wannier90.win', \"w\")\n        win_file.write('! Basic input generated by the pyWannier90. Date: %s\\n' % (time.ctime()))\n        win_file.write('\\n')\n        win_file.write('num_bands       = %d\\n' % (self.num_bands_tot))\n        win_file.write('num_wann       = %d\\n' % (self.num_wann))\n        win_file.write('\\n')\n        win_file.write('Begin Unit_Cell_Cart\\n')\n        for row in range(3):\n            win_file.write('%10.7f  %10.7f  %10.7f\\n' %\n                           (self.real_lattice_loc[0, row], self.real_lattice_loc[1, row],\n                            self.real_lattice_loc[2, row]))\n        win_file.write('End Unit_Cell_Cart\\n')\n        win_file.write('\\n')\n        win_file.write('Begin atoms_cart\\n')\n        for atom in range(len(self.atom_symbols_loc)):\n            win_file.write('%s  %7.7f  %7.7f  %7.7f\\n' %\n                           (self.atom_symbols_loc[atom], self.atoms_cart_loc[atom,0],\n                            self.atoms_cart_loc[atom,1], self.atoms_cart_loc[atom,2]))\n        win_file.write('End atoms_cart\\n')\n        win_file.write('\\n')\n        if self.use_bloch_phases: win_file.write('use_bloch_phases = T\\n\\n')\n        if self.keywords is not None:\n            win_file.write('!Additional keywords\\n')\n            win_file.write(self.keywords)\n        win_file.write('\\n\\n\\n')\n        win_file.write('mp_grid        = %d %d %d\\n' %\n                       (self.mp_grid_loc[0], self.mp_grid_loc[1], self.mp_grid_loc[2]))\n        if self.gamma_only == 1: win_file.write('gamma_only : true\\n')\n        win_file.write('begin kpoints\\n')\n        for kpt in range(self.num_kpts_loc):\n            win_file.write('%7.7f  %7.7f  %7.7f\\n' %\n                           (self.kpt_latt_loc[kpt][0], self.kpt_latt_loc[kpt][1], self.kpt_latt_loc[kpt][2]))\n        win_file.write('End Kpoints\\n')\n        win_file.close()\n\n    def get_M_mat(self):\n        r'''\n        Construct the ovelap matrix: M_{m,n}^{(\\mathbf{k,b})}\n        Equation (25) in MV, Phys. Rev. B 56, 12847\n        '''\n\n        M_matrix_loc = np.empty([self.num_kpts_loc, self.nntot_loc,\n                                 self.num_bands_loc, self.num_bands_loc],\n                                dtype = np.complex128)\n\n        for k_id in range(self.num_kpts_loc):\n            for nn in range(self.nntot_loc):\n                k1 = self.cell.get_abs_kpts(self.kpt_latt_loc[k_id])\n                k_id2 = self.nn_list[nn, k_id, 0] - 1\n                k2_ = self.kpt_latt_loc[k_id2]\n                k2_scaled = k2_ + self.nn_list[nn, k_id, 1:4]\n                k2 = self.cell.get_abs_kpts(k2_scaled)\n                s_AO = df.ft_ao.ft_aopair(self.cell, -k2+k1, kpti_kptj=[k2,k1], q = np.zeros(3))[0]\n                Cm = self.mo_coeff_kpts[k_id][:,self.band_included_list]\n                Cn = self.mo_coeff_kpts[k_id2][:,self.band_included_list]\n                M_matrix_loc[k_id, nn,:,:] = lib.einsum('nu,vm,uv->nm', Cn.T.conj(), Cm, s_AO).conj()\n\n        return M_matrix_loc\n\n    def read_M_mat(self, filename=None):\n        r'''\n        Read the ovelap matrix: M_{m,n}^{(\\mathbf{k,b})} from seedname.mnn\n        '''\n        if filename is None: filename = 'wannier90.mmn'\n        assert os.path.exists(filename), \"Cannot find \" + filename\n\n        with open(filename, 'r') as f:\n            data = f.readlines()\n            num_bands_loc, num_kpts_loc, nntot_loc = np.int64(data[1].split())\n            data = data[2:]\n            nn_list = []\n            nline = num_bands_loc**2 + 1\n            M_matrix_loc = np.empty([num_kpts_loc, nntot_loc, num_bands_loc, num_bands_loc], dtype = np.complex128)\n            jump = 0\n            for kpt in range(num_kpts_loc):\n                for nn in range(nntot_loc):\n                    temp = data[jump : jump + nline]\n                    nn_list.append(np.int64(temp[0].split()))\n                    val_in_float = np.float64(\" \".join(temp[1:]).split()).reshape(-1,2)\n                    val_in_complex = val_in_float[:,0] + 1j * val_in_float[:,1]\n                    M_matrix_loc[kpt, nn] = val_in_complex.reshape(num_bands_loc, num_bands_loc)\n                    jump += nline\n\n        return M_matrix_loc\n\n    def get_A_mat(self):\n        r'''\n        Construct the projection matrix: A_{m,n}^{\\mathbf{k}}\n        Equation (62) in MV, Phys. Rev. B 56, 12847 or equation (22) in SMV, Phys. Rev. B 65, 035109\n        '''\n\n        A_matrix_loc = np.empty([self.num_kpts_loc, self.num_wann_loc, self.num_bands_loc], dtype = np.complex128)\n\n        if self.use_bloch_phases:\n            Amn = np.zeros([self.num_wann_loc, self.num_bands_loc])\n            np.fill_diagonal(Amn, 1)\n            A_matrix_loc[:,:,:] = Amn\n        else:\n            from pyscf.dft import numint as mol_numint\n            from pyscf.dft import gen_grid as mol_gen_grid\n            grids = mol_gen_grid.Grids(self.cell).build()\n            coords = grids.coords\n            weights = grids.weights\n            for ith_wann in range(self.num_wann_loc):\n                frac_site = self.proj_site[ith_wann]\n                abs_site = frac_site.dot(self.real_lattice_loc) / param.BOHR\n                l = self.proj_l[ith_wann]\n                mr = self.proj_m[ith_wann]\n                r = self.proj_radial[ith_wann]\n                zona = self.proj_zona[ith_wann]\n                x_axis = self.proj_x[ith_wann]\n                z_axis = self.proj_z[ith_wann]\n                gr = g_r(coords, abs_site, l, mr, r, zona, x_axis, z_axis, unit = 'B')\n                ao_L0 = mol_numint.eval_ao(self.cell, coords)\n                s_aoL0_g = lib.einsum('i,i,iv->v', weights, gr, ao_L0)\n                for k_id in range(self.num_kpts_loc):\n                    kpt = self.cell.get_abs_kpts(self.kpt_latt_loc[k_id])\n                    mo_included = self.mo_coeff_kpts[k_id][:,self.band_included_list]\n                    s_kpt = self.cell.pbc_intor('int1e_ovlp', hermi=1, kpts=kpt, pbcopt=lib.c_null_ptr())\n                    A_matrix_loc[k_id,ith_wann,:] = lib.einsum('v,vu,um->m', s_aoL0_g, s_kpt, mo_included,\n                                                               optimize=True).conj()\n\n        return A_matrix_loc\n\n    def read_A_mat(self, filename=None):\n        r'''\n        Read the ovelap matrix: M_{m,n}^{(\\mathbf{k,b})} from seedname.mnn\n        '''\n        if filename is None: filename = 'wannier90.amn'\n        assert os.path.exists(filename), \"Cannot find \" + filename\n\n        with open(filename, 'r') as f:\n            data = f.readlines()\n            num_bands_loc, num_kpts_loc, num_wann_loc = np.int64(data[1].split())\n            data = data[2:]\n            A_matrix_loc = np.empty([num_kpts_loc, num_wann_loc, num_bands_loc], dtype = np.complex128)\n            val_in_float = np.float64(\" \".join(data).split()).reshape(-1,5)\n            A_matrix_loc = (val_in_float[:,3] + 1j * val_in_float[:,4]).reshape(num_kpts_loc, num_wann_loc, num_bands_loc)\n\n        return A_matrix_loc\n\n    def get_epsilon_mat(self):\n        r'''\n        Construct the eigenvalues matrix: \\epsilon_{n}^(\\mathbf{k})\n        '''\n\n        return np.asarray(self.mo_energy_kpts, dtype=np.float64)[:,self.band_included_list] * param.HARTREE2EV\n\n    def read_epsilon_mat(self, filename=None):\n        r'''\n        Read the eigenvalues matrix: \\epsilon_{n}^(\\mathbf{k})\n        '''\n        if filename is None: filename = 'wannier90.eig'\n        assert os.path.exists(filename), \"Cannot find \" + filename\n        with open(filename, 'r') as f:\n            data = f.read()\n            temp = np.float64(data.split()).reshape(-1, 3)\n            nbands = int(temp[:,0].max())\n            nkpts = int(temp[:,1].max())\n            eigenvals = temp[:,2].reshape(nkpts, nbands)\n\n        return eigenvals\n\n    def setup(self):\n        '''\n        Execute the Wannier90_setup\n        '''\n\n        real_lattice_loc = self.real_lattice_loc.T.flatten()\n        recip_lattice_loc = self.recip_lattice_loc.T.flatten()\n        kpt_latt_loc = self.kpt_latt_loc.flatten()\n        atoms_cart_loc = self.atoms_cart_loc.flatten()\n\n        (bands_wann_nntot, nn_list, proj_site, proj_l, proj_m, proj_radial,\n         proj_z, proj_x, proj_zona, exclude_bands, proj_s, proj_s_qaxis) = \\\n                libwannier90.setup(self.mp_grid_loc, self.num_kpts_loc, real_lattice_loc,\n                                   recip_lattice_loc, kpt_latt_loc,\n                                   self.num_bands_tot, self.num_atoms_loc,\n                                   self.atom_atomic_loc, atoms_cart_loc, self.gamma_only, self.spinors)\n\n        # Convert outputs to the correct data type\n        self.num_bands_loc, self.num_wann_loc, self.nntot_loc = np.int32(bands_wann_nntot)\n        self.nn_list = np.int32(nn_list)\n        self.proj_site = proj_site\n        self.proj_l = np.int32(proj_l)\n        self.proj_m = np.int32(proj_m)\n        self.proj_radial = np.int32(proj_radial)\n        self.proj_z = proj_z\n        self.proj_x = proj_x\n        self.proj_zona = proj_zona\n        self.exclude_bands = np.int32(exclude_bands)\n        self.band_included_list = [i for i in range(self.num_bands_tot) if (i + 1) not in self.exclude_bands]\n        self.proj_s = np.int32(proj_s)\n        self.proj_s_qaxis = proj_s_qaxis\n\n    def run(self):\n        '''\n        Execute the Wannier90_run\n        '''\n\n        assert self.num_wann_loc is not None\n        assert isinstance(self.M_matrix_loc, np.ndarray)\n        assert isinstance(self.A_matrix_loc, np.ndarray)\n        assert isinstance(self.eigenvalues_loc, np.ndarray)\n\n        real_lattice_loc = self.real_lattice_loc.T.flatten()\n        recip_lattice_loc = self.recip_lattice_loc.T.flatten()\n        kpt_latt_loc = self.kpt_latt_loc.flatten()\n        atoms_cart_loc = self.atoms_cart_loc.flatten()\n        M_matrix_loc = self.M_matrix_loc.flatten()\n        A_matrix_loc = self.A_matrix_loc.flatten()\n        eigenvalues_loc = self.eigenvalues_loc.flatten()\n\n        U_matrix, U_matrix_opt, lwindow, wann_centres, wann_spreads, spread = \\\n                libwannier90.run(self.mp_grid_loc, self.num_kpts_loc, real_lattice_loc,\n                                 recip_lattice_loc, kpt_latt_loc, self.num_bands_loc,\n                                 self.num_wann_loc, self.nntot_loc, self.num_atoms_loc,\n                                 self.atom_atomic_loc, atoms_cart_loc, self.gamma_only,\n                                 M_matrix_loc, A_matrix_loc, eigenvalues_loc)\n\n        # Convert outputs to the correct data typ\n        self.U_matrix = U_matrix\n        self.U_matrix_opt = U_matrix_opt\n        lwindow = np.int32(np.abs(lwindow.real))\n        self.lwindow = (lwindow == 1)\n        self.wann_centres = wann_centres.real\n        self.wann_spreads = wann_spreads.real\n        self.spread = spread.real\n\n    get_wigner_seitz_supercell = get_wigner_seitz_supercell\n    R_wz_sc = R_wz_sc\n    ws_translate_dist = ws_translate_dist\n\n    def get_hamiltonian_kpts(self):\n        '''Get the Hamiltonian in k-space, this should be identical to Fock matrix from PySCF'''\n\n        assert self.U_matrix is not None, \"You must wannierize first, then you can run this function\"\n        eigenvals_in_window = []\n        for k_id in range(self.num_kpts_loc):\n            mo_included = self.mo_energy_kpts[k_id][self.band_included_list]\n            orbs_in_win = self.lwindow[k_id]\n            mo_in_window = mo_included[orbs_in_win]\n            U_matrix_opt = self.U_matrix_opt[k_id][ :, orbs_in_win].T\n            eigenvals = lib.einsum('m,mo,mo->o', mo_in_window, U_matrix_opt.conj(), U_matrix_opt)\n            eigenvals_in_window.append(eigenvals)\n\n        hamiltonian_kpts = lib.einsum('kso,ko,kto->kst', self.U_matrix.conj(), eigenvals_in_window, self.U_matrix)\n        return hamiltonian_kpts\n\n    def get_hamiltonian_Rs(self, Rs, ham_kpts=None):\n        '''Get the R-space Hamiltonian H(R0, R) centered at R0 or the first R in Rs list\n        '''\n\n        assert self.U_matrix is not None, \"You must wannierize first, then you can run this function\"\n        nkpts = self.kpt_latt_loc.shape[0]\n        if ham_kpts is not None:\n            hamiltonian_kpts = ham_kpts\n        else:\n            hamiltonian_kpts = self.get_hamiltonian_kpts()\n\n        # Find the center either R(0,0,0) or the first R in the Rs list\n        ngrid = len(Rs)\n        center = np.arange(ngrid)[(np.asarray(Rs)**2).sum(axis=1) < 1e-10]\n        if center.shape[0] == 1:\n            center = center[0]\n        else:\n            center = 0\n\n        # The phase factor is computed using the exp(1j*R.dot(k)) rather than exp(-1j*R.dot(k)) in wannier90\n        phase = 1/np.sqrt(nkpts) * np.exp(1j* 2*np.pi * np.dot(Rs, self.kpt_latt_loc.T))\n        hamiltonian_R0 = lib.einsum('k,kst,Rk->Rst', phase[center], hamiltonian_kpts, phase.conj())\n\n        return hamiltonian_R0\n\n    def interpolate_ham_kpts(self, frac_kpts, ham_kpts=None,\n                             use_ws_distance=True, ws_search_size=[2,2,2],\n                             ws_distance_tol=1e-6):\n        ''' Interpolate the band structure using the Slater-Koster scheme\n            Return:\n                eigenvalues and eigenvectors at the desired kpts\n        '''\n\n        assert self.U_matrix is not None, \"You must wannierize first, then you can run this function\"\n        ndegen, Rs, center = self.get_wigner_seitz_supercell(ws_search_size, ws_distance_tol)\n        hamiltonian_R0 = self.get_hamiltonian_Rs(Rs, ham_kpts)\n\n        # Interpolate H(kpts) at the desired k-pts\n        if use_ws_distance:\n            wdist_ndeg, wdist_ndeg_, irdist_ws, crdist_ws = self.ws_translate_dist(Rs)\n            temp = lib.einsum('iRstx,kx->iRstk', irdist_ws, frac_kpts)\n            phase = lib.einsum('iRstk,iRst->Rstk', np.exp(1j* 2*np.pi * temp), wdist_ndeg_)\n            inter_hamiltonian_kpts = \\\n                    lib.einsum('R,Rst,Rts,Rstk->kst', 1/ndegen, 1/wdist_ndeg, hamiltonian_R0, phase)\n        else:\n            phase = np.exp(1j* 2*np.pi * np.dot(Rs, frac_kpts.T))\n            inter_hamiltonian_kpts = \\\n                    lib.einsum('R,Rst,Rk->kst', 1/ndegen, hamiltonian_R0, phase)\n\n        return inter_hamiltonian_kpts\n\n    def interpolate_band(self, frac_kpts, ham_kpts=None, use_ws_distance=True,\n                         ws_search_size=[2,2,2], ws_distance_tol=1e-6):\n        ''' Interpolate the band structure using the Slater-Koster scheme\n            Return:\n                eigenvalues and eigenvectors at the desired kpts\n        '''\n\n        assert self.U_matrix is not None, (\n            \"You must wannierize first, then you can run this function\")\n        inter_hamiltonian_kpts = self.interpolate_ham_kpts(\n            frac_kpts, ham_kpts, use_ws_distance, ws_search_size, ws_distance_tol)\n        # Diagonalize H(kpts) to get eigenvalues and eigenvector\n        nkpts = frac_kpts.shape[0]\n        eigvals, eigvecs = np.linalg.eigh(inter_hamiltonian_kpts)\n        idx_kpts = eigvals.argsort()\n        eigvals = np.asarray([eigvals[kpt][idx_kpts[kpt]] for kpt in range(nkpts)])\n        eigvecs = np.asarray([eigvecs[kpt][:,idx_kpts[kpt]] for kpt in range(nkpts)])\n\n        return eigvals, eigvecs\n\n    def is_real(self, threshold=1.e-6):\n        '''\n        Fourier transform the mo coefficients to real space and check if it is real\n        '''\n\n        assert self.U_matrix is not None, \"You must wannierize first, then you can run this function\"\n        eigenvecs_in_window = []\n        for k_id in range(self.num_kpts_loc):\n            mo_included = self.mo_coeff_kpts[k_id][:,self.band_included_list]\n            orbs_in_win = self.lwindow[k_id]\n            mo_in_window = mo_included[:, orbs_in_win].dot(self.U_matrix_opt[k_id][ :, orbs_in_win].T)\n            eigenvecs_in_window.append(mo_in_window)\n\n        # Rotate the mo(kpts) into localized basis\n        rotated_mo_coeff_kpts = lib.einsum('kum,ksm->kus', eigenvecs_in_window, self.U_matrix)\n\n        # Fourier transform the localized mo\n        nkx, nky, nkz = self.mp_grid_loc\n        Ts = lib.cartesian_prod((np.arange(nkx), np.arange(nky), np.arange(nkz)))\n        nkpts = self.kpt_latt_loc.shape[0]\n        phase = 1/np.sqrt(nkpts) * np.exp(1j* 2*np.pi * np.dot(Ts, self.kpt_latt_loc.T))\n        mo_coeff_Rs = lib.einsum('k,kus,Rk->Rus', phase[0], rotated_mo_coeff_kpts, phase.conj())\n\n        return mo_coeff_Rs.imag.max() < threshold\n\n    def export_unk(self, grid=[50,50,50]):\n        '''\n        Export the periodic part of BF in a real space grid for plotting with wannier90\n        '''\n\n        grids_coor, weights = periodic_grid(self.cell, grid, order = 'F')\n\n        for k_id in range(self.num_kpts_loc):\n            if self.spin_up:\n                spin = '.1'\n            else:\n                spin = '.2'\n            kpt = self.cell.get_abs_kpts(self.kpt_latt_loc[k_id])\n            ao = numint.eval_ao(self.cell, grids_coor, kpt = kpt)\n            u_ao = lib.einsum('x,xi->xi', np.exp(-1j*np.dot(grids_coor, kpt)), ao)\n            unk_file = FortranFile('UNK' + \"%05d\" % (k_id + 1) + spin, 'w')\n            unk_file.write_record(np.asarray([grid[0], grid[1], grid[2], k_id + 1, self.num_bands_loc], dtype = np.int32))\n            mo_included = self.mo_coeff_kpts[k_id][:,self.band_included_list]\n            u_mo = lib.einsum('xi,in->xn', u_ao, mo_included)\n            for band in range(len(self.band_included_list)):\n                unk_file.write_record(np.asarray(u_mo[:,band], dtype = np.complex128))\n            unk_file.close()\n\n    def export_AME(self, grid=[50,50,50]):\n        r'''\n        Export A_{m,n}^{\\mathbf{k}} and M_{m,n}^{(\\mathbf{k,b})} and \\epsilon_{n}^(\\mathbf{k})\n        '''\n\n        if self.A_matrix_loc is None:\n            self.make_win()\n            self.setup()\n            self.M_matrix_loc = self.get_M_mat()\n            self.A_matrix_loc = self.get_A_mat()\n            self.eigenvalues_loc = self.get_epsilon_mat()\n            self.export_unk(self, grid = grid)\n\n        with open('wannier90.mmn', 'w') as f:\n            f.write('Generated by the pyWannier90. Date: %s\\n' % (time.ctime()))\n            f.write('    %d    %d    %d\\n' % (self.num_bands_loc, self.num_kpts_loc, self.nntot_loc))\n\n            for k_id in range(self.num_kpts_loc):\n                for nn in range(self.nntot_loc):\n                    k_id1 = k_id + 1\n                    k_id2 = self.nn_list[nn, k_id, 0]\n                    nnn, nnm, nnl = self.nn_list[nn, k_id, 1:4]\n                    f.write('    %d  %d    %d  %d  %d\\n' % (k_id1, k_id2, nnn, nnm, nnl))\n                    for m in range(self.num_bands_loc):\n                        for n in range(self.num_bands_loc):\n                            f.write('    %22.18e  %22.18e\\n' % (self.M_matrix_loc[k_id, nn,m,n].real,\n                                                                self.M_matrix_loc[k_id, nn,m,n].imag))\n\n        with open('wannier90.amn', 'w') as f:\n            f.write('Generated by the pyWannier90. Date: %s\\n' % (time.ctime()))\n            f.write('    %d    %d    %d\\n' % (self.num_bands_loc, self.num_kpts_loc, self.num_wann_loc))\n\n            for k_id in range(self.num_kpts_loc):\n                for ith_wann in range(self.num_wann_loc):\n                    for band in range(self.num_bands_loc):\n                        f.write('    %d    %d    %d    %22.18e    %22.18e\\n' %\n                                (band+1, ith_wann+1, k_id+1,\n                                 self.A_matrix_loc[k_id,ith_wann,band].real,\n                                 self.A_matrix_loc[k_id,ith_wann,band].imag))\n\n        with open('wannier90.eig', 'w') as f:\n            for k_id in range(self.num_kpts_loc):\n                for band in range(self.num_bands_loc):\n                    f.write('    %d    %d    %22.18e\\n' % (band+1, k_id+1, self.eigenvalues_loc[k_id,band]))\n\n    def get_wannier(self, supercell=[1,1,1], grid=[50,50,50]):\n        '''\n        Evaluate the MLWF using a periodic grid\n        '''\n\n        grids_coor, weights = periodic_grid(self.cell, grid, supercell = [1,1,1], order = 'C')\n        kpts = self.cell.get_abs_kpts(self.kpt_latt_loc)\n\n        u_mo  = []\n        for k_id in range(self.num_kpts_loc):\n            mo_included = self.mo_coeff_kpts[k_id][:,self.band_included_list]\n            mo_in_window = self.lwindow[k_id]\n            C_opt = mo_included[:,mo_in_window].dot(self.U_matrix_opt[k_id][ :, mo_in_window].T)\n            C_tildle = C_opt.dot(self.U_matrix[k_id].T)\n            kpt = kpts[k_id]\n            ao = numint.eval_ao(self.cell, grids_coor, kpt = kpt)\n            u_ao = lib.einsum('x,xi->xi', np.exp(-1j*np.dot(grids_coor, kpt)), ao)\n            u_mo.append(lib.einsum('xi,in->xn', u_ao, C_tildle))\n\n        u_mo = np.asarray(u_mo)\n        WF0 = libwannier90.get_WF0s(self.kpt_latt_loc.shape[0],self.kpt_latt_loc, supercell, grid, u_mo)\n\n        # Fix the global phase following the pw2wannier90 procedure\n        max_index = (WF0*WF0.conj()).real.argmax(axis=0)\n        norm_wfs = np.diag(WF0[max_index,:])\n        norm_wfs = norm_wfs/np.absolute(norm_wfs)\n        WF0 = WF0/norm_wfs/self.num_kpts_loc\n\n        # Check the 'reality' following the pw2wannier90 procedure\n        for WF_id in range(self.num_wann_loc):\n            ratio_max = np.abs(WF0[np.abs(WF0[:,WF_id].real) >= 0.01,WF_id].imag /\n                               WF0[np.abs(WF0[:,WF_id].real) >= 0.01,WF_id].real).max(axis=0)\n            print('The maximum imag/real for wannier function ', WF_id,' : ', ratio_max)\n        return WF0\n\n    def get_guess_orb(self, frac_site=[0,0,0], l=0, mr=1, r=1,\n                      zona=1.0, x_axis=[1,0,0], z_axis=[0,0,1],\n                      supercell=[1,1,1], grid=[50,50,50]):\n        '''\n        Evaluate a guess orbital using a periodic uniform grid\n        '''\n        grids_coor, weights = periodic_grid(self.cell, grid, supercell = supercell, order = 'C')\n        frac_site = np.asarray(frac_site)\n        abs_site = frac_site.dot(self.real_lattice_loc) / param.BOHR\n        gr = g_r(grids_coor, abs_site, l, mr, r, zona, x_axis, z_axis, unit = 'B')\n        return gr\n\n    def plot_wf(self, outfile='MLWF', wf_list=None, supercell=[1,1,1], grid=[50,50,50]):\n        '''\n        Export Wannier function at cell R\n        xsf format: http://web.mit.edu/xcrysden_v1.5.60/www/XCRYSDEN/doc/XSF.html\n        Attributes:\n            wf_list        : a list of MLWFs to plot\n            supercell    : a supercell used for plotting\n        '''\n\n        if wf_list is None:\n            wf_list = list(range(self.num_wann_loc))\n\n        grid = np.asarray(grid)\n        origin = np.asarray([-(grid[i]*(supercell[i]//2) + 1)/grid[i] for i in range(3)]).dot(\n            self.cell.lattice_vectors().T)* param.BOHR\n        real_lattice_loc = (grid*supercell-1)/grid * self.cell.lattice_vectors() * param.BOHR\n        nx, ny, nz = grid*supercell\n        WF0 = self.get_wannier(supercell = supercell, grid = grid)\n\n\n        for wf_id in wf_list:\n            assert wf_id in list(range(self.num_wann_loc))\n            WF = WF0[:,wf_id].reshape(nx,ny,nz).real\n\n            with open(outfile + '-' + str(wf_id) + '.xsf', 'w') as f:\n                f.write('Generated by the pyWannier90. Date: %s\\n\\n' % (time.ctime()))\n                f.write('CRYSTAL\\n')\n                f.write('PRIMVEC\\n')\n                for row in range(3):\n                    f.write('%10.7f  %10.7f  %10.7f\\n' %\n                            (self.real_lattice_loc[row,0], self.real_lattice_loc[row,1],\n                             self.real_lattice_loc[row,2]))\n                f.write('CONVVEC\\n')\n                for row in range(3):\n                    f.write('%10.7f  %10.7f  %10.7f\\n' %\n                            (self.real_lattice_loc[row,0], self.real_lattice_loc[row,1],\n                             self.real_lattice_loc[row,2]))\n                f.write('PRIMCOORD\\n')\n                f.write('%3d %3d\\n' % (self.num_atoms_loc, 1))\n                for atom in range(len(self.atom_symbols_loc)):\n                    f.write('%s  %7.7f  %7.7f  %7.7f\\n' %\n                            (self.atom_symbols_loc[atom], self.atoms_cart_loc[atom][0],\n                             self.atoms_cart_loc[atom][1], self.atoms_cart_loc[atom][2]))\n                f.write('\\n\\n')\n                f.write('BEGIN_BLOCK_DATAGRID_3D\\n3D_field\\nBEGIN_DATAGRID_3D_UNKNOWN\\n')\n                f.write('   %5d     %5d  %5d\\n' % (nx, ny, nz))\n                f.write('   %10.7f  %10.7f  %10.7f\\n' % (origin[0],origin[1],origin[2]))\n                for row in range(3):\n                    f.write('   %10.7f  %10.7f  %10.7f\\n' %\n                            (real_lattice_loc[row,0], real_lattice_loc[row,1], real_lattice_loc[row,2]))\n\n                fmt = ' %13.5e' * nx + '\\n'\n                for iz in range(nz):\n                    for iy in range(ny):\n                        f.write(fmt % tuple(WF[:,iy,iz].tolist()))\n                f.write('END_DATAGRID_3D\\nEND_BLOCK_DATAGRID_3D')\n\n    def plot_guess_orbs(self, outfile='guess_orb', frac_site=[0,0,0], l=0, mr=1, r=1,\n                        zona=1.0, x_axis=[1,0,0], z_axis=[0,0,1],\n                        supercell=[1,1,1], grid=[50,50,50]):\n        '''\n        Export Wannier function at cell R\n        xsf format: http://web.mit.edu/xcrysden_v1.5.60/www/XCRYSDEN/doc/XSF.html\n        Attributes:\n            wf_list        : a list of MLWFs to plot\n            supercell    : a supercell used for plotting\n        '''\n\n        grid = np.asarray(grid)\n        origin = np.asarray([-grid[i]*(supercell[i]//2)/grid[i] for i in range(3)]).dot(\n            self.cell.lattice_vectors().T) * param.BOHR\n        real_lattice_loc = (grid*supercell-1)/grid * self.cell.lattice_vectors() * param.BOHR\n        nx, ny, nz = grid*supercell\n        guess_orb = self.get_guess_orb(frac_site=frac_site, l=l, mr=mr, r=r,\n                                       zona=zona, x_axis=x_axis, z_axis=z_axis,\n                                       supercell=supercell, grid=grid)\n        guess_orb = guess_orb.reshape(nx,ny,nz).real\n\n        with open(outfile + '.xsf', 'w') as f:\n            f.write('Generated by the pyWannier90\\n\\n')\n            f.write('CRYSTAL\\n')\n            f.write('PRIMVEC\\n')\n            for row in range(3):\n                f.write('%10.7f  %10.7f  %10.7f\\n' % (self.real_lattice_loc[row,0], self.real_lattice_loc[row,1],\n                                                      self.real_lattice_loc[row,2]))\n            f.write('CONVVEC\\n')\n            for row in range(3):\n                f.write('%10.7f  %10.7f  %10.7f\\n' % (self.real_lattice_loc[row,0], self.real_lattice_loc[row,1],\n                                                      self.real_lattice_loc[row,2]))\n            f.write('PRIMCOORD\\n')\n            f.write('%3d %3d\\n' % (self.num_atoms_loc, 1))\n            for atom in range(len(self.atom_symbols_loc)):\n                f.write('%s  %7.7f  %7.7f  %7.7f\\n' % (self.atom_symbols_loc[atom], self.atoms_cart_loc[atom][0],\n                                                       self.atoms_cart_loc[atom][1], self.atoms_cart_loc[atom][2]))\n            f.write('\\n\\n')\n            f.write('BEGIN_BLOCK_DATAGRID_3D\\n3D_field\\nBEGIN_DATAGRID_3D_UNKNOWN\\n')\n            f.write('   %5d     %5d  %5d\\n' % (nx, ny, nz))\n            f.write('   %10.7f  %10.7f  %10.7f\\n' % (origin[0],origin[1],origin[2]))\n            for row in range(3):\n                f.write('   %10.7f  %10.7f  %10.7f\\n' % (real_lattice_loc[row,0], real_lattice_loc[row,1],\n                                                         real_lattice_loc[row,2]))\n\n            fmt = ' %13.5e' * nx + '\\n'\n            for iz in range(nz):\n                for iy in range(ny):\n                    f.write(fmt % tuple(guess_orb[:,iy,iz].tolist()))\n            f.write('END_DATAGRID_3D\\nEND_BLOCK_DATAGRID_3D')\n\nif __name__ == '__main__':\n    from pyscf.pbc import gto as pgto\n    from pyscf.pbc import scf as pscf\n    import pywannier90\n\n    # build cell object\n    cell = pgto.Cell()\n    cell.a = [[0.0, 2.7155, 2.7155], [2.7155, 0.0, 2.7155], [2.7155, 2.7155, 0.0]]\n    cell.atom = [['Si',[0.0,0.0,0.0]], ['Si',[1.35775, 1.35775, 1.35775]]]\n    cell.basis = 'gth-dzv'\n    cell.pseudo = 'gth-pade'\n    cell.exp_to_discard = 0.1\n    cell.build()\n\n    # build and run scf object\n    kmesh = [3, 1, 1]\n    kpts = cell.make_kpts(kmesh)\n    kmf = pscf.KKS(cell, kpts)\n    kmf.xc = 'pbe'\n    kmf.run()\n\n    # build and run w90 object\n    num_wann = 8\n    keywords = '''\n    begin projections\n    Si:sp3\n    end projections\n    '''\n    w90 = pywannier90.W90(kmf, cell, kmesh, num_wann, other_keywords=keywords)\n    w90.kernel()\n", "meta": {"hexsha": "070b624a0376106074bfb26e7e1bf9325c25b4bd", "size": 52868, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/pbc/tools/pywannier90.py", "max_stars_repo_name": "QuESt-Calculator/pyscf", "max_stars_repo_head_hexsha": "0ed03633b699505c7278f1eb501342667d0aa910", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 501, "max_stars_repo_stars_event_min_datetime": "2018-12-06T23:48:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:53:18.000Z", "max_issues_repo_path": "pyscf/pbc/tools/pywannier90.py", "max_issues_repo_name": "QuESt-Calculator/pyscf", "max_issues_repo_head_hexsha": "0ed03633b699505c7278f1eb501342667d0aa910", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 710, "max_issues_repo_issues_event_min_datetime": "2018-11-26T22:04:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:53:12.000Z", "max_forks_repo_path": "pyscf/pbc/tools/pywannier90.py", "max_forks_repo_name": "QuESt-Calculator/pyscf", "max_forks_repo_head_hexsha": "0ed03633b699505c7278f1eb501342667d0aa910", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 273, "max_forks_repo_forks_event_min_datetime": "2018-11-26T10:10:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:25:28.000Z", "avg_line_length": 45.2636986301, "max_line_length": 138, "alphanum_fraction": 0.5767950367, "include": true, "reason": "import numpy,from scipy", "num_tokens": 16143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.186697342884774}}
{"text": "# -*- coding: utf-8 -*-\n##########################################################################\n# NSAp - Copyright (C) CEA, 2016\n# Distributed under the terms of the CeCILL-B license, as published by\n# the CEA-CNRS-INRIA. Refer to the LICENSE file or to\n# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html\n# for details.\n##########################################################################\n\n\"\"\"\nCompute the connectome of a given parcellation, like the FreeSurfer aparc+aseg\nsegmentation, using MRtrix, FSL Probtrackx2 or MITK Gibbs Tracking.\n\"\"\"\n\n# Standard\nimport os\nimport subprocess\n\n# Package\nfrom pyconnectome import DEFAULT_FSL_PATH\nfrom pyconnectome.tractography.probabilist import probtrackx2\nfrom pyconnectome.utils.segtools import fix_freesurfer_subcortical_parcellation\nfrom pyconnectome.utils.filetools import convert_mitk_vtk_fibers_to_tck\nfrom pyconnectome.utils.filetools import convert_trk_fibers_to_tck\nfrom pyconnectome.utils.filetools import convert_probtrackx2_saved_paths_to_tck\nfrom pyconnectome.utils.regtools import freesurfer_bbregister_t1todif\n\n# Third-party\nimport numpy\nimport nibabel\nfrom pyfreesurfer import DEFAULT_FREESURFER_PATH\nfrom pyfreesurfer.wrapper import FSWrapper\nfrom pyfreesurfer.utils.filetools import (get_or_check_freesurfer_subjects_dir,\n                                          load_look_up_table)\n\n\ndef connectome_snapshot(connectome, snapshot, labels=None, transform=None,\n                        colorbar_title=\"\", dpi=200, labels_size=4,\n                        vmin=None, vmax=None):\n    \"\"\"\n    Create a PNG snapshot of the connectome (i.e. connectivity matrix).\n\n    Parameters\n    ----------\n    connectome: str\n        Path to txt file storing the connectivity matrix.\n    snapshot: str\n        Path to the output snapshot.\n    labels: str, default None\n        Path to txt file listing the label names. By default no labels.\n        Should be ordered like the rows/cols of the connectivity matrix.\n    transform: callable, default None\n        A Callable function to apply on the matrix (e.g. numpy.log1p).\n        By default no transformation is applied.\n    colorbar_title: str, default \"\"\n        How to interpret the values of the connectivity,\n        e.g. \"Log(# of tracks)\" or \"% of tracks\"\n    dpi: int, default 200\n        \"Dot Per Inch\", set higher for better resolution.\n    labels_size: int, default 4\n        The label font size.\n    vmin, vmax: float, default None\n        The display range.\n\n    Returns\n    -------\n    snapshot: str\n        Path to the output connectome snapshot.\n    \"\"\"\n    # Import in function, so that the rest of the module can be used even\n    # if matplotlib is not available\n    import matplotlib.pyplot as plt\n    # Load the connectivity matrix\n    matrix = numpy.loadtxt(connectome)\n\n    # Check connectivity matrix dimensions\n    if matrix.ndim != 2 or matrix.shape[0] != matrix.shape[1]:\n        raise ValueError(\"Connectivity matrix should be a square matrix.\"\n                         \"Shape of matrix: {}\".format(matrix.shape))\n\n    # Apply transformation if requested\n    if transform is not None:\n        matrix = transform(matrix)\n\n    # -------------------------------------------------------------------------\n    # Create the figure with matplotlib\n    fig, ax = plt.subplots()\n    ax.invert_yaxis()\n    ax.xaxis.tick_top()\n\n    ax.set_xticks(numpy.arange(0.5, matrix.shape[0]))\n    ax.set_yticks(numpy.arange(0.5, matrix.shape[1]))\n\n    ax.tick_params(which=\"both\", axis=\"both\", width=0, length=0)\n\n    # Add the labels if passed\n    if labels is not None:\n        labels_array = numpy.loadtxt(labels, dtype=str)\n\n        if len(labels_array) != matrix.shape[0]:\n            raise ValueError(\n                \"Wrong number of labels: {}. Should be {}.\".format(\n                    len(labels_array), matrix.shape[0]))\n\n        ax.set_xticklabels(labels_array, size=labels_size, rotation=90)\n        ax.set_yticklabels(labels_array, size=labels_size)\n\n    ax.set_aspect(\"equal\")\n    kwargs = {}\n    if vmin is not None:\n        kwargs[\"vmin\"] = vmin\n    if vmax is not None:\n        kwargs[\"vmax\"] = vmax\n    heatmap = ax.pcolor(matrix, cmap=plt.cm.Reds, **kwargs)\n    colorbar = fig.colorbar(heatmap)\n    colorbar.set_label(colorbar_title, rotation=270, labelpad=20)\n\n    fig.tight_layout()\n    # -------------------------------------------------------------------------\n\n    # Save to PNG file\n    if not snapshot.endswith(\".png\"):\n        snapshot += \".png\"\n    fig.savefig(snapshot, dpi=dpi)\n\n    # Release memory\n    fig.clear()\n    plt.close()\n\n    return snapshot\n\n\ndef voxel_to_node_connectivity(probtrackx2_dir, nodes, connectome_lut, outdir,\n                               basename=\"connectome\"):\n    \"\"\"\n    When using the --omatrix3 option in Probtrackx2, the result is a\n    VOXELxVOXEL connectivity matrix. This function creates the NODExNODE\n    (i.e. ROIxROI) connectivity matrix for the given parcellation.\n\n    Parameters\n    ----------\n    probtrackx2_dir: str\n        Path to dir where to find the files created by probtrackx2 when using\n        --omatrix3 option, i.e \"fdt_matrix3.dot\" and \"coords_for_fdt_matrix3\"\n    nodes: str\n        Path to parcellation defining the nodes of the connectome,\n        e.g. FreeSurfer aparc+aseg parcellation with only the regions\n        (i.e. labels) to keep in the connectome.\n    connectome_lut: str\n        Path to the Look Up Table of the given parcellation in the\n        FreeSurfer LUT format.\n    outdir: str\n        Path to directory where output.\n    basename: str, default \"connectome\"\n        Basename of output files (<outdir>/<basename>.[mat|labels]).\n\n    Returns\n    -------\n    out_connectome: str\n        The generated connectome.\n    out_labels: str\n        The coonectome associated labels.\n    \"\"\"\n    # Check input and output dirs\n    for directory in (probtrackx2_dir, outdir):\n        if not os.path.isdir(directory):\n            raise ValueError(\"Directory does not exist: %s\" % directory)\n\n    # Coords: map x,y,z coordinates to voxel index\n    # <x> <y> <z> <voxel index>\n    path_coords = os.path.join(probtrackx2_dir, \"coords_for_fdt_matrix3\")\n    coords = numpy.loadtxt(path_coords, dtype=int, usecols=[0, 1, 2, 4])\n\n    # Load parcellation volume with node labels\n    nodes_vol = nibabel.load(nodes).get_data().astype(dtype=int)\n\n    # Load LUT to get the node names and set of int labels\n    node_labels, node_names, _ = load_look_up_table(connectome_lut)\n    set_labels = set(node_labels)\n\n    # Connectivity matrix\n    nb_nodes = len(node_names)\n    connectome = numpy.zeros((nb_nodes, nb_nodes), dtype=int)\n\n    # fdt_matrix3.dot: voxel to voxel connectivity\n    # <index voxel 1> <index voxel 2> <nb connections>\n    path_fdt_matrix3 = os.path.join(probtrackx2_dir, \"fdt_matrix3.dot\")\n\n    # Since the fdt_matrix3.dot file can be very large, we parse it line by\n    # line without loading it completely in memory\n    with open(path_fdt_matrix3) as f:\n        for line in f:\n\n            # Get indexes of connected voxels and nb of connections\n            v1_idx, v2_idx, nb_connections = map(int, line.strip().split())\n            if nb_connections == 0:\n                continue\n\n            # Volume coordinates of connected voxels\n            x1, y1, z1, _v1_idx = coords[v1_idx - 1, :]\n            x2, y2, z2, _v2_idx = coords[v2_idx - 1, :]\n\n            # Checking assumption that a voxel's info is stored at row=index-1\n            assert v1_idx == _v1_idx, \"%i %i\" % (v1_idx, _v1_idx)\n            assert v2_idx == _v2_idx, \"%i %i\" % (v2_idx, _v2_idx)\n\n            # Labels of the 2 connected voxels\n            label1, label2 = nodes_vol[x1, y1, z1], nodes_vol[x2, y2, z2]\n\n            # Ignore pairs of voxels which labels are not in the connectome\n            if not {label1, label2}.issubset(set_labels):\n                continue\n\n            # Update counts\n            i, j = label1 - 1, label2 - 1  # 0-indexed in python\n            connectome[i, j] += nb_connections\n            connectome[j, i] += nb_connections\n\n    # Write output connectome\n    out_connectome = os.path.join(outdir, basename + \".mat\")\n    numpy.savetxt(out_connectome, connectome, fmt=\"%i\")\n\n    # Write nodes names\n    out_labels = os.path.join(outdir, basename + \".labels\")\n    numpy.savetxt(out_labels, node_names, fmt=\"%s\")\n\n    return out_connectome, out_labels\n\n\ndef probtrackx2_connectome(\n        outdir,\n        tempdir,\n        subject_id,\n        t1_parc,\n        t1_parc_lut,\n        connectome_lut,\n        nodif_brain,\n        nodif_brain_mask,\n        bedpostx_dir,\n        nsamples,\n        nsteps,\n        steplength,\n        fix_freesurfer_subcortical=False,\n        subjects_dir=None,\n        loopcheck=True,\n        cthr=0.2,\n        fibthresh=0.01,\n        distthresh=0.0,\n        sampvox=0.0,\n        snapshots=True,\n        fs_sh=DEFAULT_FREESURFER_PATH,\n        fsl_sh=DEFAULT_FSL_PATH):\n    \"\"\"\n    Compute the connectome of a given parcellation, like the FreeSurfer\n    aparc+aseg segmentation, using ProbTrackx2.\n\n    Requirements:\n        - brain masks for the preprocessed DWI: nodif_brain and\n          nodif_brain_mask.\n        - FreeSurfer: result of recon-all on the T1.\n        - FSL Bedpostx: computed for the preprocessed DWI.\n        - a T1 parcellation that defines the nodes of the connectome, it has\n          to be in the FreeSurfer space (i.e. aligned with\n          <subjects dir>/<subject>/mri/brain.mgz), e.g. aparc+aseg from\n          FreeSurfer.\n\n    Connectome construction strategy:\n        - Pathways are constructed from 'constitutive points' and not from\n          endpoints. A pathway is the result of 2 samples propagating in\n          opposite directions from a seed point. It is done using the\n          --omatrix3 option of Probtrackx2.\n        - The seed mask is the mask of WM voxels that are neighbors\n          (12-connexity) of nodes.\n        - The stop mask is the inverse of white matter, i.e. a sample stops\n          propagating as soon as it leaves the white matter.\n\n    Parameters\n    ----------\n    outdir: str\n        Directory where to output.\n    tempdir: str\n        Path to the directory where temporary directories should be written.\n        It should be a partition with 5+ GB available.\n    subject_id: str\n        Subject id used with FreeSurfer 'recon-all' command.\n    t1_parc: str\n        Path to the parcellation that defines the nodes of the connectome, e.g.\n        aparc+aseg.mgz from FreeSurfer.\n    t1_parc_lut: str\n        Path to the Look Up Table for the passed parcellation in the\n        FreeSurfer LUT format. If you T1 parcellation is from FreeSurfer, this\n        will most likely be <$FREESURFER_HOME>/FreeSurferColorLUT.txt.\n    connectome_lut: str\n        Path to a Look Up Table in the FreeSurfer LUT format, listing the\n        regions from the parcellation to use as nodes in the connectome. The\n        region names should match the ones used in the <t1_parc_lut> LUT and\n        the integer labels should be the row/col positions in the connectome.\n        Alternatively it can be set to 'Lausanne2008' to use the predefined\n        LUT for the Lausanne 2008 atlas, which is based on the FreeSurfer\n        aparc+aseg parcellation.\n    nodif_brain: str\n        Path to the preprocessed brain-only DWI volume.\n    nodif_brain_mask: str\n        Path to the brain binary mask.\n    bedpostx_dir: str\n        Bedpostx output directory.\n    nsamples: int\n        Number of samples per voxel to initiate in the seed mask.\n    nsteps: int\n        Maximum number of steps for a given sample.\n    steplength: int\n        Step size in mm.\n    fix_freesurfer_subcortical: bool, default False\n        If the <t1_parc> is aparc+aseg or aparc.a2009s+aseg from FreeSurfer,\n        set this option to True, to recompute the subcortical segmentations\n        of the 5 structures that are uncorrectly segmented by FreeSurfer,\n        using FSL FIRST.\n    subjects_dir: str or None, default None\n        Path to the FreeSurfer subjects directory. Required if the FreeSurfer\n        environment variable (i.e. $SUBJECTS_DIR) is not set.\n    cthr: float, optional\n        Probtrackx2 option.\n    fibthresh, distthresh, sampvox: float, optional\n        Probtrackx2 options.\n    loopcheck: bool, optional\n        Probtrackx2 option.\n    snapshots: bool, default True\n        If True, create PNG snapshots for QC.\n    fs_sh: str, default NeuroSpin path\n        Path to the Bash script setting the FreeSurfer environment\n    fsl_sh: str, default NeuroSpin path\n        Path to the Bash script setting the FSL environment.\n\n    Returns\n    -------\n    connectome_file: str\n        The generated connectome.\n    labels_file: str\n        The coonectome associated labels.\n    connectome_snap_file: str\n        A grphical representation of the connectome.\n    \"\"\"\n    # -------------------------------------------------------------------------\n    # STEP 0 - Check arguments\n\n    # FreeSurfer subjects_dir\n    subjects_dir = get_or_check_freesurfer_subjects_dir(subjects_dir)\n\n    if connectome_lut.lower() == \"lausanne2008\":\n        module_dir = os.path.dirname(os.path.abspath(__file__))\n        connectome_lut = os.path.join(module_dir, \"Lausanne2008LUT.txt\")\n\n    # Check input paths\n    paths_to_check = [t1_parc, t1_parc_lut, connectome_lut, nodif_brain,\n                      nodif_brain_mask, bedpostx_dir, fs_sh, fsl_sh]\n    for p in paths_to_check:\n        if not os.path.exists(p):\n            raise ValueError(\"File or directory does not exist: %s\" % p)\n\n    # Create <outdir> and/or <tempdir> if not existing\n    for directory in [outdir, tempdir]:\n        if not os.path.isdir(directory):\n            os.makedirs(directory)\n\n    # -------------------------------------------------------------------------\n    # STEP 1 - Compute T1 <-> DWI rigid transformation\n\n    # FreeSurfer T1 to Nifti\n    fs_t1_brain = os.path.join(subjects_dir, subject_id, \"mri\", \"brain.mgz\")\n    t1_brain = os.path.join(outdir, \"t1_brain.nii.gz\")\n    cmd_1a = [\"mri_convert\", fs_t1_brain, t1_brain]\n    FSWrapper(cmd_1a, shfile=fs_sh)()\n\n    # Register diffusion to T1\n    _, dif2anat_dat, dif2anat_mat = freesurfer_bbregister_t1todif(\n            outdir=outdir,\n            subject_id=subject_id,\n            nodif_brain=nodif_brain,\n            subjects_dir=subjects_dir,\n            fs_sh=fs_sh,\n            fsl_sh=fsl_sh)\n\n    # Invert dif2anat transform\n    m = numpy.loadtxt(dif2anat_mat)\n    m_inv = numpy.linalg.inv(m)\n    anat2dif_mat = os.path.join(outdir, \"anat2dif.mat\")\n    numpy.savetxt(anat2dif_mat, m_inv)\n\n    # -------------------------------------------------------------------------\n    # STEP 2 - Convert LUT\n    # Change integer labels in the LUT so that the each label corresponds\n    # to the row/col position in the connectome\n    nodes = os.path.join(outdir, \"nodes.nii.gz\")\n    cmd_2 = [\"labelconvert\", t1_parc, t1_parc_lut, connectome_lut, nodes,\n             \"-nthreads\", \"0\", \"-failonwarn\"]\n    subprocess.check_call(cmd_2)\n\n    # -------------------------------------------------------------------------\n    # STEP 3 - If the T1 parcellation is aparc+aseg or aparc.a2009s+aseg\n    # from FreeSurfer, this option allows the recompute the subcortical\n    # segmentations of 5 structures that are uncorrectly segmented by\n    # FreeSurfer, using FSL FIRST\n    if fix_freesurfer_subcortical:\n        fixed_nodes = os.path.join(outdir, \"nodes_fixSGM.nii.gz\")\n        nodes = fix_freesurfer_subcortical_parcellation(parc=nodes,\n                                                        t1_brain=t1_brain,\n                                                        lut=connectome_lut,\n                                                        output=fixed_nodes,\n                                                        tempdir=tempdir,\n                                                        nb_threads=0,\n                                                        fsl_sh=fsl_sh)\n\n    # -------------------------------------------------------------------------\n    # STEP 4 - Create the masks for Probtrackx2\n\n    # White matter mask\n    aparc_aseg = os.path.join(subjects_dir, subject_id, \"mri\",\n                              \"aparc+aseg.mgz\")\n    wm_mask = os.path.join(outdir, \"wm_mask.nii.gz\")\n    cmd_4a = [\"mri_binarize\",\n              \"--i\", aparc_aseg,\n              \"--o\", wm_mask,\n              \"--wm\"]\n    FSWrapper(cmd_4a, shfile=fs_sh)()\n\n    # Stop mask is inverse of white matter mask\n    stop_mask = os.path.join(outdir, \"inv_wm_mask.nii.gz\")\n    cmd_4b = [\"mri_binarize\",\n              \"--i\", aparc_aseg,\n              \"--o\", stop_mask,\n              \"--wm\", \"--inv\"]\n    FSWrapper(cmd_4b, shfile=fs_sh)()\n\n    # Create target mask: a mask of all nodes\n    target_mask = os.path.join(outdir, \"target_mask.nii.gz\")\n    cmd_4c = [\"mri_binarize\",\n              \"--i\",   nodes,\n              \"--o\",   target_mask,\n              \"--min\", \"1\"]\n    FSWrapper(cmd_4c, shfile=fs_sh)()\n\n    # Dilate target mask by one voxel (12-connexity)\n    target_mask_dil = os.path.join(outdir, \"target_mask_dilated.nii.gz\")\n    cmd_4d = [\"mri_morphology\", target_mask, \"dilate\", \"1\", target_mask_dil]\n    FSWrapper(cmd_4d, shfile=fs_sh)()\n\n    # Create seed mask: white matter voxels near nodes (target regions)\n    # Intersect dilated target mask and white matter mask\n    # -> white matter voxels neighbor (12-connectivity) to node voxels\n    seed_mask = os.path.join(outdir, \"wm_nodes_interface_mask.nii.gz\")\n    cmd_4e = [\"mri_and\", wm_mask, target_mask_dil, seed_mask]\n    FSWrapper(cmd_4e, shfile=fs_sh)()\n\n    # -------------------------------------------------------------------------\n    # STEP 7 - Run Probtrackx2\n    probtrackx2_dir = os.path.join(outdir, \"probtrackx2\")\n    probtrackx2(dir=probtrackx2_dir,\n                forcedir=True,\n                seedref=t1_brain,\n                xfm=anat2dif_mat,\n                invxfm=dif2anat_mat,\n                samples=os.path.join(bedpostx_dir, \"merged\"),\n                mask=nodif_brain_mask,\n                seed=seed_mask,\n                omatrix3=True,\n                target3=nodes,\n                stop=stop_mask,\n                nsamples=nsamples,\n                nsteps=nsteps,\n                steplength=steplength,\n                loopcheck=loopcheck,\n                cthr=cthr,\n                fibthresh=fibthresh,\n                distthresh=distthresh,\n                sampvox=sampvox,\n                shfile=fsl_sh)\n\n    # ------------------------------------------------------------------------\n    # STEP 8 - Create NODExNODE connectivity matrix for nodes from <t1_parc>\n    connectome_file, labels_file = voxel_to_node_connectivity(\n        probtrackx2_dir=probtrackx2_dir,\n        nodes=nodes,\n        connectome_lut=connectome_lut,\n        outdir=outdir)\n\n    # ------------------------------------------------------------------------\n    # STEP 9 - Create a connectome snapshot if requested\n    if snapshots:\n        connectome_snap_file = os.path.join(outdir, \"connectome.png\")\n        connectome_snapshot(connectome_file, connectome_snap_file,\n                            labels=labels_file, transform=numpy.log1p, dpi=300,\n                            labels_size=4, colorbar_title=\"log(# of tracks)\")\n\n    return connectome_file, labels_file, connectome_snap_file\n\n\ndef mrtrix_connectomes(\n        outdir,\n        tempdir,\n        tractogram,\n        t1_brain,\n        nodif_brain,\n        t1_parc,\n        t1_parc_lut,\n        connectome_lut,\n        tractogram_weights=None,\n        tractogram_type=\"mrtrix\",\n        dif2anat_dat=None,\n        dif2anat_mat=None,\n        fix_freesurfer_subcortical=False,\n        radial_search_dist=2.,\n        forward_search_dist=5.,\n        snapshots=True,\n        fs_sh=DEFAULT_FREESURFER_PATH,\n        fsl_sh=DEFAULT_FSL_PATH):\n    \"\"\" Compute the reduced connectome from a parcellation using MRtrix.\n\n    Parameters\n    ----------\n    outdir: str\n        Directory where to output.\n    tempdir: str\n        Path to the directory where temporary directories should be written.\n        It should be a partition with 5+ GB available.\n    tractogram: str or list of str\n        The tractogram to be used in VTK, TRK, TXT or TRK format. It is\n        possible to provide a list of tractograms only for Connectomist and\n        Tracula.\n    t1_brain: str\n        The anatomical image.\n    nodif_brain: str, default None\n        Diffusion brain-only Nifti volume with bvalue ~ 0. If not passed, it is\n        generated automatically by averaging all the b0 volumes of the DWI.\n    t1_parc: str\n        Path to the parcellation that defines the nodes of the connectome, e.g.\n        aparc+aseg.mgz from FreeSurfer in the 't1_brain' space.\n    t1_parc_lut: str\n        Path to the Look Up Table for the passed parcellation in the\n        FreeSurfer LUT format. If you T1 parcellation is from FreeSurfer, this\n        will most likely be <$FREESURFER_HOME>/FreeSurferColorLUT.txt.\n    connectome_lut: str\n        Path to a Look Up Table in the FreeSurfer LUT format, listing the\n        regions from the parcellation to use as nodes in the connectome. The\n        region names should match the ones used in the <t1_parc_lut> LUT and\n        the integer labels should be the row/col positions in the connectome.\n        Alternatively it can be set to 'Lausanne2008' to use the predefined\n        LUT for the Lausanne 2008 atlas, which is based on the FreeSurfer\n        aparc+aseg parcellation.\n    tractogram_weights: str, default None\n        The weight associated to each fiber: one weight per line.\n    tractogram_type: str, default 'mrtrix'\n        The software used to generate the tractogram. This parameter is used\n        for format conversion purposes.\n    dif2anat_dat: str, default None\n        The diffusion to T1 FreeSurfer registration '.dat' file.\n    dif2anat_mat: str\n        The diffusion to T1 FSL registration '.mat' file.\n    fix_freesurfer_subcortical: bool, default False\n        If the <t1_parc> is aparc+aseg or aparc.a2009s+aseg from FreeSurfer,\n        set this option to True, to recompute the subcortical segmentations\n        of the 5 structures that are uncorrectly segmented by FreeSurfer,\n        using FSL FIRST.\n    radial_search_dist: float, default 2.0\n        Multiple connectomes are generated depending on the streamline-node\n        association strategy. The radial search assigns the nearest\n        node from the streamline endpoint within this radius (in mm).\n    forward_search_dist: float, default 5.0\n        Multiple connectomes are generated depending on the streamline-node\n        association strategy. The forward assignment projects the\n        streamline forward from the endpoint to find a node, within this\n        distance (in mm).\n    snapshots: bool, default True\n        If True, create PNG snapshots for QC.\n    fs_sh: str, default NeuroSpin path\n        Path to the Bash script setting the FreeSurfer environment\n    fsl_sh: str, default NeuroSpin path\n        Path to the Bash script setting the FSL environment.\n\n    Returns\n    -------\n    connectome_endvox, connectome_radial, connectome_forward: str\n        The generated reduced connectomes.\n    \"\"\"\n    # -------------------------------------------------------------------------\n    # STEP 0 - Check arguments\n\n    # Get the default module LUT if parameter not provided\n    if connectome_lut.lower() == \"lausanne2008\":\n        module_dir = os.path.dirname(os.path.abspath(__file__))\n        connectome_lut = os.path.join(module_dir, \"Lausanne2008LUT.txt\")\n\n    # Check input paths\n    paths_to_check = [t1_parc, t1_parc_lut, connectome_lut, t1_brain,\n                      nodif_brain]\n    paths_to_check.extend(tractogram)\n    for p in paths_to_check:\n        if not os.path.exists(p):\n            raise ValueError(\"File or directory does not exist: %s\" % p)\n\n    # Check supported tractogram\n    if tractogram_type not in [\"mrtrix\", \"mitk\", \"connectomist\", \"fsl\",\n                               \"tracula\"]:\n        raise ValueError(\"Unsupported tractogram: {0}\".format(tractogram_type))\n\n    # Create <outdir> and/or <tempdir> if not existing\n    for directory in [outdir, tempdir]:\n        if not os.path.isdir(directory):\n            os.makedirs(directory)\n\n    # -------------------------------------------------------------------------\n    # STEP 1 - Align T1 parcellation to diffusion without downsampling\n    parc_name = os.path.basename(t1_parc).split(\".nii\")[0].split(\".mgz\")[0]\n    t1_parc_to_dif = os.path.join(outdir, parc_name + \"_to_dif.nii.gz\")\n    if dif2anat_dat is not None:\n        cmd_1c = [\"mri_vol2vol\",\n                  \"--mov\",  nodif_brain,\n                  \"--targ\", t1_parc,\n                  \"--inv\",\n                  \"--no-resample\",\n                  \"--interp\", \"nearest\",\n                  \"--o\",   t1_parc_to_dif,\n                  \"--reg\", dif2anat_dat,\n                  \"--no-save-reg\"]\n        FSWrapper(cmd_1c, shfile=fs_sh)()\n    elif dif2anat_mat is not None:\n        raise NotImplementedError(\n            \"This code only supports 'dif2anat_dat' parameter.\")\n    else:\n        raise ValueError(\"One transformation matrix is mandatory.\")\n\n    # -------------------------------------------------------------------------\n    # STEP 2 - Convert LUT\n    # Change integer labels in the LUT so that the each label corresponds\n    # to the row/col position in the connectome\n    nodes = os.path.join(outdir, \"nodes.nii.gz\")\n    cmd_2 = [\"labelconvert\", t1_parc_to_dif, t1_parc_lut, connectome_lut,\n             nodes, \"-nthreads\", \"0\", \"-failonwarn\"]\n    subprocess.check_call(cmd_2)\n\n    # -------------------------------------------------------------------------\n    # STEP 3 - If the T1 parcellation is aparc+aseg or aparc.a2009s+aseg\n    # from FreeSurfer, this option allows the recompute the subcortical\n    # segmentations of 5 structures that are uncorrectly segmented by\n    # FreeSurfer, using FSL FIRST\n    if fix_freesurfer_subcortical:\n        fixed_nodes = os.path.join(outdir, \"nodes_fixSGM.nii.gz\")\n        nodes = fix_freesurfer_subcortical_parcellation(\n            parc=nodes,\n            t1_brain=t1_brain,\n            lut=connectome_lut,\n            output=fixed_nodes,\n            tempdir=tempdir,\n            nb_threads=0,\n            fsl_sh=fsl_sh)\n\n    # -------------------------------------------------------------------------\n    # STEP 4 - Create connectomes with labels by combining fibers and nodes\n\n    # Convert streamlines so that they can be used in MRtrix\n    tck_tractogram = os.path.join(outdir, \"fibers.tck\")\n    if tractogram_type == \"mitk\":\n        if len(tractogram) != 1:\n            raise ValueError(\"A one-file tractogram is expected.\")\n        convert_mitk_vtk_fibers_to_tck(tractogram[0], tck_tractogram)\n    elif tractogram_type in (\"connectomist\", \"tracula\"):\n        convert_trk_fibers_to_tck(\n            nodif_brain, tractogram, tck_tractogram, tempdir)\n    elif tractogram_type == \"fsl\":\n        convert_probtrackx2_saved_paths_to_tck(\n            nodif_brain, tractogram, tck_tractogram, tempdir)\n    else:\n        if len(tractogram) != 1:\n            raise ValueError(\"A one-file tractogram is expected.\")\n        tck_tractogram = tractogram[0]\n\n    # Read labels from LUT and create a list of labels: labels.txt\n    labels_array = numpy.loadtxt(connectome_lut, dtype=str, usecols=[1])\n    path_labels = os.path.join(outdir, \"labels.txt\")\n    numpy.savetxt(path_labels, labels_array, fmt=\"%s\")\n\n    # Create connectome with end-voxel assignment\n    connectome_endvox = os.path.join(outdir, \"connectome_endvox.txt\")\n    cmd_8a = [\"tck2connectome\", tck_tractogram, nodes, connectome_endvox,\n              \"-keep_unassigned\",  # Keep 'Unknown' label\n              \"-assignment_end_voxels\"]\n    if tractogram_weights is not None:\n        cmd_8a += [\"-tck_weights_in\", tractogram_weights]\n    subprocess.check_call(cmd_8a)\n\n    # Create connectome with radial search assignment\n    connectome_radial = os.path.join(\n        outdir, \"connectome_radial_{:.2f}mm.txt\".format(radial_search_dist))\n    cmd_8b = [\"tck2connectome\", tck_tractogram, nodes, connectome_radial,\n              \"-keep_unassigned\",  # Keep 'Unknown' label\n              \"-assignment_radial_search\", \"{0}\".format(radial_search_dist)]\n    if tractogram_weights is not None:\n        cmd_8b += [\"-tck_weights_in\", tractogram_weights]\n    subprocess.check_call(cmd_8b)\n\n    # Create connectome assigning the streamline to all nodes it intersects\n    connectome_forward = os.path.join(\n        outdir, \"connectome_forward_{:.2f}mm.txt\".format(forward_search_dist))\n    cmd_8c = [\"tck2connectome\", tck_tractogram, nodes, connectome_forward,\n              \"-keep_unassigned\",  # Keep 'Unknown' label\n              \"-assignment_forward_search\", \"{0}\".format(forward_search_dist)]\n    if tractogram_weights is not None:\n        cmd_8c += [\"-tck_weights_in\", tractogram_weights]\n    subprocess.check_call(cmd_8c)\n\n    # If snapshots are requested\n    if snapshots:\n        snapshot_endvox = os.path.join(outdir, \"connectome_endvox.png\")\n        connectome_snapshot(connectome_endvox, snapshot_endvox,\n                            labels=path_labels, transform=numpy.log1p, dpi=300,\n                            labels_size=4, colorbar_title=\"log(# of tracks)\")\n\n        snapshot_radial = os.path.join(\n            outdir, \"connectome_radial_{:.2f}mm.png\".format(\n                radial_search_dist))\n        connectome_snapshot(connectome_radial, snapshot_radial,\n                            labels=path_labels, transform=numpy.log1p, dpi=300,\n                            labels_size=4, colorbar_title=\"log(# of tracks)\")\n\n        snapshot_forward = os.path.join(\n            outdir, \"connectome_forward_{:.2f}mm.png\".format(\n                forward_search_dist))\n        connectome_snapshot(connectome_forward, snapshot_forward,\n                            labels=path_labels, transform=numpy.log1p, dpi=300,\n                            labels_size=4, colorbar_title=\"log(# of tracks)\")\n\n    return connectome_endvox, connectome_radial, connectome_forward\n", "meta": {"hexsha": "eeeea44cad32f9b7e4cbed101b92bf88999ddb71", "size": 30117, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyconnectome/connectomes/reduced.py", "max_stars_repo_name": "neurospin/pyconnectome", "max_stars_repo_head_hexsha": "971dfaf58895b61f4610934bd5434fb5a7062bfe", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-06-29T20:01:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-18T13:41:45.000Z", "max_issues_repo_path": "pyconnectome/connectomes/reduced.py", "max_issues_repo_name": "neurospin/pyconnectome", "max_issues_repo_head_hexsha": "971dfaf58895b61f4610934bd5434fb5a7062bfe", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2017-07-11T15:49:33.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-16T09:04:03.000Z", "max_forks_repo_path": "pyconnectome/connectomes/reduced.py", "max_forks_repo_name": "neurospin/pyconnectome", "max_forks_repo_head_hexsha": "971dfaf58895b61f4610934bd5434fb5a7062bfe", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2017-04-28T11:04:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-11T10:47:07.000Z", "avg_line_length": 41.143442623, "max_line_length": 79, "alphanum_fraction": 0.6210445928, "include": true, "reason": "import numpy", "num_tokens": 7397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305398, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.18669734110254033}}
{"text": "from typing import Any, Tuple\nimport pkgutil\nimport importlib\n\nimport numpy as np\nimport pandas as pd\nimport scipy\nimport scipy.stats as stats\nfrom scipy.special import gamma, gammaln\n\nfrom pvrpm.core.enums import ConfigKeys as ck\n\n\n# override to getattr to get modules case insensitve\ndef getattr_override(obj: Any, attr: str) -> Any:\n    for a in dir(obj):\n        if a.lower() == attr.lower():\n            return getattr(obj, a)\n\n\n# TODO: there has to be a better way to do this...\ndef load_pysam_modules():\n    \"\"\"\n    Loads ALL of PySAM's modules manually and globalizes them\n\n    This is needed because PySAM is a wrapper for the ssc and sdk of SAM, which includes dynamic modules that are not properly defined for pybind, so using pkgutil's walk_packages function does not work (import error). Since the modules need to be loaded in order for getattr to find it, this must be done once when the program starts\n    \"\"\"\n    global pysam\n    import PySAM as pysam\n\n    for loader, module_name, is_pkg in pkgutil.walk_packages(pysam.__path__):\n        try:\n            importlib.import_module(f\"{pysam.__name__}.{module_name}\")\n        except:\n            pass\n\n\ndef filename_to_module(filename: str) -> object:\n    \"\"\"\n    Takes the filename of an exported json file from SAM, extracts the module name, and returns a callback to that module that can be used to create an object\n\n    Args:\n        filename (str): Filename of the exported case\n\n    Returns:\n        :obj:`PySAM`: PySAM object the file represents\n    \"\"\"\n    # for certain modules the name from SAM doesnt match up with the module name (extra spaces in module name)\n    broken_modules = [\"host_developer\"]\n    for mod in broken_modules:\n        if mod in filename:\n            module_str = filename.strip().split(\"_\")[-2:]\n            module_str = \"\".join(module_str).split(\".\")[0].strip()\n            return getattr_override(pysam, module_str)\n\n    # if not a broken module:\n    # SAM case file exporting should be underscores, with the last word being the module type\n    module_str = filename.strip().split(\"_\")[-1].split(\".\")[0].strip()\n    return getattr_override(pysam, module_str)\n\n\ndef summarize_dc_energy(dc_power_output: tuple, split: int) -> np.array:\n    \"\"\"\n    Calculates the DC energy (kWh) based on an input array of timeseries DC power (kW) for the system lifetime (likely the 'dc_net' output from SAM)\n\n    Can be used to summarize similar hourly, daily data to yearly\n\n    Args:\n        dc_power_output (:obj:`tuple`): Tuple output from SAM simulation\n        split (int): The frequency to split the data too, typically this is the number of years the system was simulated for (system_lifetime_yrs)\n\n    Returns:\n        :obj:`np.array`: Numpy array of length system_lifetime_yrs containing the yearly energy in kWh\n    \"\"\"\n    data = np.array(dc_power_output)\n    data = np.reshape(data, (int(split), int(len(dc_power_output) / split)))\n    return np.sum(data, axis=1)\n\n\ndef component_degradation(percent_per_day: float, t: int) -> float:\n    \"\"\"\n    Calculate the degradation of a component given the time since last replacement\n\n    Args:\n        percent_per_day (float): The percent degradation per day of the module\n        t (int): Time since the module was last replaced, or if its a new module, installed\n\n    Returns:\n        float: The performance of the module, between 0 and 1\n\n    Note:\n        This gives the overall module performance based on degradation, so if the module has degraded 2 percent so far, this function returns 0.98\n    \"\"\"\n\n    return 1 / np.power((1 + percent_per_day / 100), t)\n\n\ndef sample(distribution: str, parameters: dict, num_samples: int) -> np.array:\n    \"\"\"\n    Sample data from a distribution. If distribution is a supported distribution, parameters should be a dictionary with keys \"mean\" and \"std\". Otherwise, distribution should be a scipy stats function and parameters be the kwargs for the distribution.\n\n    Supported Distributions (only requires mean and std):\n        - lognormal\n        - normal\n        - uniform (one std around mean)\n        - weibull\n        - exponential\n\n    Args:\n        distribution (str): Name of the distribution function\n        parameters (:obj:`dict`): Kwargs for the distribution (for a supported distribution should only be the mean and std)\n        num_samples (int): Number of samples to return from distribution\n\n    Returns:\n        :obj:(list): List of floats containing samples from the distribution\n    \"\"\"\n    distribution = distribution.lower().strip()\n\n    if distribution == \"lognormal\":\n        # lognormal uses the mean and std of the underlying normal distribution of log(X)\n        # so they must be normalized first\n        mu, sigma = parameters[ck.MEAN], parameters[ck.STD]\n        normalized_std = np.sqrt(np.log(1 + (sigma / mu) ** 2))\n        normalized_mean = np.log(mu) - normalized_std ** 2 / 2\n        dist = stats.lognorm(s=normalized_std, scale=np.exp(normalized_mean))\n    elif distribution == \"normal\":\n        dist = stats.norm(loc=parameters[ck.MEAN], scale=parameters[ck.STD])\n    elif distribution == \"uniform\":\n        a = parameters[ck.MEAN] - parameters[ck.STD]\n        b = parameters[ck.STD] * 2\n        dist = stats.uniform(loc=a, scale=b)\n    elif distribution == \"weibull\":\n        # for weibull, we have to solve for c and the scale parameter\n        # this fails for certain parameter ranges, raising a runtime error\n        # see https://github.com/scipy/scipy/issues/12134 for reference\n        def _h(c):\n            r = np.exp(gammaln(2 / c) - 2 * gammaln(1 / c))\n            return np.sqrt(1 / (2 * c * r - 1))\n\n        if ck.STD in parameters:\n            mean, std = parameters[ck.MEAN], parameters[ck.STD]\n            c0 = 1.27 * np.sqrt(mean / std)\n            c, info, ier, msg = scipy.optimize.fsolve(lambda t: _h(t) - (mean / std), c0, xtol=1e-10, full_output=True,)\n\n            # Test residual rather than error code.\n            if np.abs(info[\"fvec\"][0]) > 1e-8:\n                raise RuntimeError(f\"with mean={mean} and std={std}, solve failed: {msg}\")\n\n            c = c[0]\n        else:\n            mean, c = parameters[ck.MEAN], parameters[ck.SHAPE]\n\n        scale = mean / gamma(1 + 1 / c)\n        dist = stats.weibull_min(c=c, scale=scale)\n    elif distribution == \"exponential\":\n        dist = stats.expon(scale=parameters[ck.MEAN])\n    else:\n        # else, we don't know this distribution, pass the distribution directly to scipy\n        dist = getattr(stats, distribution)\n        if not dist:\n            raise AttributeError(f\"Scipy stats doesn't have a distribution '{distribution}'\")\n        dist = dist(**parameters)\n\n    # scipy rvs uses rou sampling method\n    return dist.rvs(size=num_samples)\n\n\ndef get_higher_components(\n    top_level: str, start_level: str, case, start_level_df: pd.DataFrame = None,\n) -> Tuple[np.array, np.array, int]:\n    \"\"\"\n    Calculates the indicies of the top level that correspond to the given level df indicies and returns the given level indicies count per top level component and the total number of start_level components per top_level component\n\n    Args:\n        top_level (str): The string name of the component level to calculate indicies for\n        start_level (str): The string name of the component level to start at\n        case (SamCase): The case object for this simulation\n        start_level_df (:obj:`pd.DataFrame`, Optional): The dataframe of the component level for which to find the corresponding top level indicies for\n\n    Returns:\n        tuple(:obj:`np.array`, :obj:`np.array`, int): If start_level_df is given, returns the top level indicies, the number of start_level components in start_level_df per top level index, and the total number of start_level components per top_level component. If start_level_df is None this only returns the total number of start_level components per top_level component.\n    \"\"\"\n    # the number of disconnects equals the number of inverters, if this every changes this would need to be changed\n    # otherwise, the inverter per trans is the same for disconnects\n    # dictionaries to make is easier transitioning between levels\n    component_per = {\n        ck.TRANSFORMER: case.config[ck.INVERTER_PER_TRANS],\n        ck.DISCONNECT: 1,\n        ck.INVERTER: case.config[ck.COMBINER_PER_INVERTER],\n        ck.COMBINER: case.config[ck.STR_PER_COMBINER],\n        ck.STRING: case.config[ck.MODULES_PER_STR],\n        ck.MODULE: 1,\n    }\n\n    # hierarchy of component levels:\n    component_hier = {\n        ck.MODULE: 0,\n        ck.STRING: 1,\n        ck.COMBINER: 2,\n        ck.INVERTER: 3,\n        ck.DISCONNECT: 4,\n        ck.TRANSFORMER: 5,\n    }\n\n    above_levels = [\n        c\n        for c in component_hier.keys()\n        if component_hier[c] > component_hier[start_level] and component_hier[c] <= component_hier[top_level]\n    ]\n\n    total_comp = 1\n    # above levels is ordered ascending\n    for level in above_levels:\n        total_comp *= component_per[level]\n\n    if start_level_df is not None:\n        indicies = start_level_df.index.copy()\n        indicies = np.floor(indicies / total_comp)\n        # sum up the number of occurences for each index and return with total number of components at start level per top level\n        indicies, counts = np.unique(indicies, return_counts=True)\n        return indicies.astype(np.int64), counts.astype(np.int64), int(total_comp)\n    else:\n        return int(total_comp)\n", "meta": {"hexsha": "268751332d9612c6b24a1f45b432d49bc535602a", "size": 9455, "ext": "py", "lang": "Python", "max_stars_repo_path": "pvrpm/core/utils.py", "max_stars_repo_name": "FSEC-Photovoltaics/pvrpm-lcoe", "max_stars_repo_head_hexsha": "dbe0bb30ffa1041ec004f84c57aac44f47bdf6d2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-29T16:03:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:03:26.000Z", "max_issues_repo_path": "pvrpm/core/utils.py", "max_issues_repo_name": "FSEC-Photovoltaics/pvrpm-lcoe", "max_issues_repo_head_hexsha": "dbe0bb30ffa1041ec004f84c57aac44f47bdf6d2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2022-02-05T17:27:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T23:53:50.000Z", "max_forks_repo_path": "pvrpm/core/utils.py", "max_forks_repo_name": "FSEC-Photovoltaics/pvrpm-lcoe", "max_forks_repo_head_hexsha": "dbe0bb30ffa1041ec004f84c57aac44f47bdf6d2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-01-13T23:35:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T15:46:05.000Z", "avg_line_length": 42.2098214286, "max_line_length": 373, "alphanum_fraction": 0.6748810153, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 2243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.18669733575575995}}
{"text": "#!/usr/bin/env python\nimport argparse\nimport os\nfrom tqdm import tqdm \nimport pprint as pp\nimport numpy as np\nimport h5py\nimport json\nimport torch\nimport torch.optim as optim\nimport torch.autograd as autograd\nfrom torch.optim import lr_scheduler\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom tensorboard_logger import configure, log_value\n\nfrom neural_combinatorial_rl.neural_combinatorial_rl import NeuralCombOptRL\nfrom neural_combinatorial_rl.matching_nco import MatchingNeuralCombOptRL, MatchingNoDecoder\nfrom envs import dataset\n\ndef str2bool(v):\n      return v.lower() in ('true', '1')\n\nparser = argparse.ArgumentParser(description=\"Neural Combinatorial Optimization with RL\")\n\n# Data\nparser.add_argument('--task', default='sort_10-20', help=\"The task to solve, in the form {COP}_{size}, e.g., tsp_20\")\nparser.add_argument('--parallel_envs', type=int, default=128, help='')\nparser.add_argument('--batch_size', type=int, default=128, help='')\nparser.add_argument('--train_size', type=int, default=1000000, help='')\nparser.add_argument('--val_size', type=int, default=10000, help='')\n# Network\nparser.add_argument('--embedding_dim', type=int, default=128, help='Dimension of input embedding')\nparser.add_argument('--hidden_dim', type=int, default=128, help='Dimension of hidden layers in Enc/Dec')\nparser.add_argument('--input_size', type=int, default=10)\nparser.add_argument('--n_features', type=int, default=1)\nparser.add_argument('--n_process_blocks', type=int, default=3, help='Number of process block iters to run in the Critic network')\nparser.add_argument('--n_glimpses', type=int, default=2, help='No. of glimpses to use in the pointer network')\nparser.add_argument('--use_tanh', type=str2bool, default=True)\nparser.add_argument('--tanh_exploration', type=int, default=10, help='Hyperparam controlling exploration in the pointer net by scaling the tanh in the softmax')\nparser.add_argument('--dropout', default=0., help='')\nparser.add_argument('--terminating_symbol', default='<0>', help='')\nparser.add_argument('--beam_size', default=1, help='Beam width for beam search')\n# Training\nparser.add_argument('--use_decoder', type=str2bool, default=False)\nparser.add_argument('--actor_net_lr', default=1e-4, help=\"Set the learning rate for the actor network\")\nparser.add_argument('--critic_net_lr', default=1e-4, help=\"Set the learning rate for the critic network\")\nparser.add_argument('--actor_lr_decay_step', default=5000, help='')\nparser.add_argument('--critic_lr_decay_step', default=5000, help='')\nparser.add_argument('--actor_lr_decay_rate', default=0.96, help='')\nparser.add_argument('--critic_lr_decay_rate', default=0.96, help='')\nparser.add_argument('--reward_scale', default=2, type=float,  help='')\nparser.add_argument('--is_train', type=str2bool, default=True, help='')\nparser.add_argument('--n_epochs', default=1, help='')\nparser.add_argument('--random_seed', type=int, default=24601, help='')\nparser.add_argument('--max_grad_norm', default=1.0, help='Gradient clipping')\nparser.add_argument('--use_cuda', type=str2bool, default=True, help='')\nparser.add_argument('--critic_beta', type=float, default=0.9, help='Exp mvg average decay')\nparser.add_argument('--use_KT', type=str2bool, default=True)\n# Misc\nparser.add_argument('--log_step', default=50, help='Log info every log_step steps')\nparser.add_argument('--log_dir', type=str, default='results/logs')\nparser.add_argument('--run_name', type=str, default='0')\nparser.add_argument('--base_dir', type=str, default='/data/pemami/spg/')\nparser.add_argument('--output_dir', type=str, default='outputs')\nparser.add_argument('--epoch_start', type=int, default=0, help='Restart at epoch #')\nparser.add_argument('--load_path', type=str, default='')\nparser.add_argument('--disable_tensorboard', type=str2bool, default=True)\nparser.add_argument('--plot_attention', type=str2bool, default=False)\nparser.add_argument('--disable_progress_bar', type=str2bool, default=False)\nparser.add_argument('--save_stats', type=str2bool, default=False)\nparser.add_argument('--save_model', type=str2bool, default=False)\nparser.add_argument('--_id', type=str, default='1234567')\nparser.add_argument('--sl', type=str2bool, default=False)\nparser.add_argument('--use_graph', type=str2bool, default=False)\nparser.add_argument('--make_only', type=int, default=3)\nparser.add_argument('--num_workers', type=int, default=0)\nparser.add_argument('--cuda_device', type=int, default=0)\n\nargs = vars(parser.parse_args())\nargs['model'] = 'nco'\n# Pretty print the run args\npp.pprint(args)\n# hack\nargs['n_nodes'] = args['input_size']\n# Set the random seed\ntorch.manual_seed(int(args['random_seed']))\n\ntorch.cuda.set_device(args['cuda_device'])\n\n# Optionally configure tensorboard\nargs['run_name'] = args['_id'][-6:] + '-' + args['run_name']    \nif not args['disable_tensorboard']:\n    configure(os.path.join(args['base_dir'], args['log_dir'], args['task'], args['run_name']))\n\nargs['test_size'] = args['val_size']\n# Task specific configuration - generate dataset if needed\ntask = args['task'].split('_')\nargs['COP'] = task[0]  # the combinatorial optimization problem\nargs, env, training_dataloader, test_dataloader = dataset.build(args, args['epoch_start'])\nif args['COP'] == 'mwm2D':\n    mwm2D_opt = test_dataloader.dataset.get_average_optimal_weight()\n\n# Open files for writing results\nif args['save_stats']:\n    fglab_results_dir = os.path.join(args['base_dir'], 'results', 'fglab', args['model'], args['COP'], args['_id'])\n    raw_results_dir = os.path.join(args['base_dir'], 'results', 'raw', args['model'], args['COP'], args['_id'])\n    try:\n        os.makedirs(fglab_results_dir)\n        os.makedirs(raw_results_dir)\n    except:\n        pass\n    fglab_results = open(os.path.join(fglab_results_dir, 'scores.json'), 'w')\n    raw_results = h5py.File(os.path.join(raw_results_dir, 'raw.hdf5'), 'w')\n\n# Load the model parameters from a saved state\nif os.path.exists(args['load_path']):\n    print('  [*] Loading model from {}'.format(args['load_path']))\n\n    model = torch.load(\n        os.path.join(\n            os.getcwd(),\n            args['load_path']\n        ))\n    #model.actor_net.decoder.max_length = args['input_size']\n    model.is_train = args['is_train']\nelse:\n    if args['COP'] == 'mwm2D':\n        if args['use_decoder']:\n            model = MatchingNeuralCombOptRL(\n                args['input_size'],\n                args['n_features'],\n                int(args['embedding_dim']),\n                int(args['hidden_dim']),\n                args['input_size'], # decoder len\n                args['terminating_symbol'],\n                int(args['n_glimpses']),\n                int(args['n_process_blocks']), \n                float(args['tanh_exploration']),\n                args['use_tanh'],\n                int(args['beam_size']),\n                args['is_train'],\n                args['use_cuda'])\n        else:\n            model = MatchingNoDecoder(\n                    args['input_size'],\n                    args['n_features'],\n                    args['embedding_dim'],\n                    args['hidden_dim'],\n                    args['use_cuda'])\n            model.mask_logits = True\n    else:\n        # Instantiate the Neural Combinatorial Opt with RL module\n        model = NeuralCombOptRL(\n            args['n_features'],\n            int(args['embedding_dim']),\n            int(args['hidden_dim']),\n            args['input_size'], # decoder len\n            args['terminating_symbol'],\n            int(args['n_glimpses']),\n            int(args['n_process_blocks']), \n            float(args['tanh_exploration']),\n            args['use_tanh'],\n            int(args['beam_size']),\n            args['is_train'],\n            args['use_cuda'])\n\nargs['save_dir'] = os.path.join(args['base_dir'], 'results', 'models', args['model'], args['COP'], args['_id'])    \ntry:\n    os.makedirs(args['save_dir'])\nexcept:\n    pass\n\n#critic_mse = torch.nn.MSELoss()\n#critic_optim = optim.Adam(model.critic_net.parameters(), lr=float(args['critic_net_lr']))\nactor_optim = optim.Adam(model.parameters(), lr=float(args['actor_net_lr']))\nactor_scheduler = lr_scheduler.MultiStepLR(actor_optim,\n        range(int(args['actor_lr_decay_step']), int(args['actor_lr_decay_step']) * 1000,\n            int(args['actor_lr_decay_step'])), gamma=float(args['actor_lr_decay_rate']))\n\n#critic_scheduler = lr_scheduler.MultiStepLR(critic_optim,\n#        range(int(args['critic_lr_decay_step']), int(args['critic_lr_decay_step']) * 1000,\n#            int(args['critic_lr_decay_step'])), gamma=float(args['critic_lr_decay_rate']))\n\ncritic_exp_mvg_avg = torch.zeros(1)\nbeta = args['critic_beta']\n\nif args['use_cuda']:\n    model = model.cuda()\n    #critic_mse = critic_mse.cuda()\n    critic_exp_mvg_avg = critic_exp_mvg_avg.cuda()\nstep = 0\nval_step = 0\ntot_R = []\nscores = {'_scores': {}}\nif not args['is_train']:\n    args['n_epochs'] = '1'\nepoch = int(args['epoch_start'])\n\ndef eval(val_step, final=False):\n    # Use (greedy) beam search decoding for validation\n    #model.actor_net.decoder.decode_type = \"greedy\"\n    model.decode_type(\"greedy\")\n    print('\\nstarting eval\\n')\n    example_input = []\n    example_output = []\n    eval_R = []\n    ratios = []\n    optimal = []\n    # put in test mode!\n    model.eval()\n    for batch_id, obs in enumerate(tqdm(test_dataloader,\n            disable=args['disable_progress_bar'])):\n        obs = Variable(obs, requires_grad=False)\n        if args['use_cuda']:\n            obs = obs.cuda()\n        obs = torch.transpose(obs, 2, 1)\n        probs, actions, action_idxs, _ = model(obs)\n        if args['COP'] == 'sort':\n            R = env(actions, args['use_KT'], args['use_cuda'])\n        elif args['COP'] == 'mwm2D':\n            # actions is list of len N of (batch_size, n_features)\n            x1 = obs[:, :, 0:args['input_size']]\n            x2 = torch.stack(actions, 2)\n            a = torch.cat([x1, x2], dim=2)\n            R = env(torch.transpose(a, 2, 1), args['use_cuda'])\n        else:\n            R = env(actions, args['use_cuda'])\n        eval_R.append(R.data.cpu().numpy())\n        val_step += 1\n        if val_step % int(args['log_step']) == 0:\n            # example_output = []\n            # example_input = []\n            # for idx, action in enumerate(actions):\n            #     if task[0] == 'tsp':\n            #         example_output.append(action_idxs[idx][0].data[0])\n            #     else:\n            #         example_output.append(action[0].data[0])\n            #     example_input.append(bat[0, :, idx].data[0])\n            #print('Example test input: {}'.format(example_input))\n            #print('Example test output: {}'.format(example_output))\n            print('step: {}, example reward: {}'.format(val_step, R[0].data[0]))\n            # if args['plot_attention']:\n            #     probs = torch.cat(probs, 0)\n            #     plot_attention(example_input,\n            #             example_output, probs.data.cpu().numpy())\n        if args['COP'] == 'mwm2D':\n            ratios.append(R.data.cpu().numpy() / mwm2D_opt)\n    eval_R = np.array(eval_R).ravel()\n    #if args['COP'] == 'sort':\n    #    # Count how many 1's in eval_R\n    #    per_incorrectly_sorted = (len(eval_R) - sum(eval_R == -1.))/(len(eval_R)) * 100.\n    #    print('percent incorrectly sorted: {}'.format(per_incorrectly_sorted))\n    #    scores['_scores']['percent_incorrectly_sorted_{}'.format(step * args['batch_size'])] = float(per_incorrectly_sorted)        \n    mean_eval_R = np.mean(eval_R)\n    std_eval_R = np.std(eval_R)\n    print('Validation overall avg_reward: {}'.format(mean_eval_R))\n    print('Validation overall reward std: {}'.format(std_eval_R))\n    if not args['disable_tensorboard']:\n        log_value('eval_avg_reward', mean_eval_R, val_step)\n        log_value('eval_std_reward', std_eval_R, val_step)\n    scores['_scores']['eval_avg_reward_{}'.format(step * args['batch_size'])] = float(mean_eval_R)\n    #scores['_scores']['eval_std_reward_{}'.format(step * args['batch_size'])] = float(std_eval_R)\n    if args['COP'] == 'mwm2D':\n        print('Average optimal MWM: {}'.format(mwm2D_opt))\n        print('Average optimality ratio: {}'.format(np.mean(ratios)))\n        scores['_scores']['optimality_ratio_{}'.format(step * args['batch_size'])] = float(np.mean(ratios))\n    model.decode_type(\"stochastic\")\n    return val_step \n\nfor i in range(epoch, epoch + int(args['n_epochs'])):\n    if args['is_train']:\n        # eval at 0 \n        val_step = eval(val_step)\n        # put in train mode!\n        model.train()\n        # sample_batch is [batch_size x input_dim x sourceL]\n        for batch_id, obs in enumerate(tqdm(training_dataloader,\n                disable=args['disable_progress_bar'])):\n            obs = Variable(obs, requires_grad=False)\n            if args['use_cuda']:\n                obs = obs.cuda()\n            obs = torch.transpose(obs, 2, 1)\n            probs, actions, actions_idxs, _ = model(obs)\n            if args['COP'] == 'sort':\n                R = env(actions, args['use_KT'], args['use_cuda'])\n            elif args['COP'] == 'mwm2D':\n                # actions is list of len N of (batch_size, n_features)\n                x1 = obs[:, :, 0:args['input_size']]\n                x2 = torch.stack(actions, 2)\n                a = torch.cat([x1, x2], dim=2)\n                R = env(torch.transpose(a, 2, 1), args['use_cuda'])\n            else:\n                R = env(actions, args['use_cuda'])\n            tot_R.append(R.data.cpu().numpy())            \n            if batch_id == 0:\n                critic_exp_mvg_avg = R.mean()\n            else:\n                critic_exp_mvg_avg = (critic_exp_mvg_avg * beta) + ((1. - beta) * R.mean())\n            advantage = R - critic_exp_mvg_avg\n            if not args['use_decoder']:\n                logprobs = torch.stack(probs).sum(dim=0)\n                nll = -logprobs.detach()\n            else:\n                logprobs = 0\n                nll = 0\n                for prob in probs: \n                    # compute the sum of the log probs\n                    # for each tour in the batch\n                    logprob = torch.log(prob)\n                    nll += -logprob.detach()\n                    logprobs = logprobs + logprob\n                # guard against nan\n                #nll[nll != nll] = 0.\n                # clamp any -inf's to 0 to throw away this tour\n                #logprobs[logprobs < -1000] = 0.\n                # multiply each time step by the advanrate\n            reinforce = advantage.detach() * logprobs\n            actor_loss = reinforce.mean()\n            actor_optim.zero_grad()\n            actor_loss.backward()\n            # clip gradient norms\n            torch.nn.utils.clip_grad_norm(model.parameters(),\n                    float(args['max_grad_norm']), norm_type=2)\n            actor_optim.step()\n            actor_scheduler.step()\n            critic_exp_mvg_avg = critic_exp_mvg_avg.detach()\n            #critic_scheduler.step()\n            #R = R.detach()\n            #critic_loss = critic_mse(v.squeeze(1), R)\n            #critic_optim.zero_grad()\n            #critic_loss.backward()\n            #torch.nn.utils.clip_grad_norm(model.critic_net.parameters(),\n            #        float(args['max_grad_norm']), norm_type=2)\n            #critic_optim.step()\n            step += 1\n            if not args['disable_tensorboard']:\n                log_value('Running_avg_reward', -1 * R.mean().data[0], step)\n                log_value('actor_loss', actor_loss.data[0], step)\n                #log_value('critic_loss', critic_loss.data[0], step)\n                log_value('critic_exp_mvg_avg', critic_exp_mvg_avg.data[0], step)\n                log_value('nll', nll.mean().data[0], step)\n            if step % int(args['log_step']) == 0:\n                print('epoch: {}, train_batch_id: {}, avg_reward: {}'.format(\n                    i, batch_id, R.mean().data[0]))\n                example_output = []\n                #example_input = []\n                if args['COP'] == 'sort':\n                    for idx, action in enumerate(actions):\n                        example_output.append(round(action[0].data[0]))  # <-- ?? \n                    #if task[0] == 'tsp':\n                    #    example_output.append(actions_idxs[idx][0].data[0])\n                    #else:\n                    #example_input.append(sample_batch[0, :, idx][0])\n                    #print('Example train input: {}'.format(example_input))\n                    print('Example train output: {}'.format(example_output))\n        if args['save_model']:\n            print(' [*] saving model...')\n            torch.save(model, os.path.join(args['save_dir'], 'nco-COP-{}-N-{}-epoch-{}.pt'.format(args['COP'], args['input_size'], i)))   \n# Eval one last time\nval_step = eval(val_step, True)\n\nif args['save_stats']:\n    # write training stats to file\n    json.dump(scores, fglab_results)\n    tot_R = np.array(tot_R).ravel()\n    raw_results.create_dataset('training_rewards', data=tot_R)\n    # close files\n    fglab_results.close()\n    raw_results.close()\n", "meta": {"hexsha": "0719bc3d1672661d4e41077e1068724cebc9d9ac", "size": 17022, "ext": "py", "lang": "Python", "max_stars_repo_path": "train_nco.py", "max_stars_repo_name": "sylph520/sinkhorn-policy-gradient.pytorch", "max_stars_repo_head_hexsha": "0a96ffe6c8c78d466c8b6e959dd74dc25e11914e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2018-05-22T15:36:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T01:14:58.000Z", "max_issues_repo_path": "train_nco.py", "max_issues_repo_name": "sylph520/sinkhorn-policy-gradient.pytorch", "max_issues_repo_head_hexsha": "0a96ffe6c8c78d466c8b6e959dd74dc25e11914e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "train_nco.py", "max_forks_repo_name": "sylph520/sinkhorn-policy-gradient.pytorch", "max_forks_repo_head_hexsha": "0a96ffe6c8c78d466c8b6e959dd74dc25e11914e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-05-22T15:46:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-30T15:48:46.000Z", "avg_line_length": 45.8814016173, "max_line_length": 160, "alphanum_fraction": 0.6166725414, "include": true, "reason": "import numpy", "num_tokens": 4109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.359364131437828, "lm_q1q2_score": 0.18669732862674612}}
{"text": "import numpy as np\nfrom scipy import interpolate\nimport scipy\nimport astropy\nimport matplotlib\nfrom datetime import datetime\nfrom scipy.stats.mstats import mquantiles\nimport os\nfrom astropy.io import fits\nimport glob\nfrom parameters import *\nimport sys\nimport argparse\nfrom astropy.table import Table\n#import datetime\n##sys.path.insert(0, 'python')\n# matplotlib.rc('text', usetex=True)\n# matplotlib.rcParams['text.latex.preamble'] = [r\"\\usepackage{amsmath}\",\n#                                    r\"\\usepackage{color}\"]\n# matplotlib.use('Agg')\nfrom ptemcee import Sampler as PTSampler\nimport matplotlib.pyplot as plt\nimport matplotlib\n##import corner\nstartTime = datetime.now()\n\nparser = argparse.ArgumentParser(description=\"Calculate radial velocities and stellar parameters of WEAVE target spectra.\")\n\nparser.add_argument(\"--infiles\", type=str, required=True, help=\"input file\", nargs=1)\nparser.add_argument(\"--outdir\", type=str, required=True, help=\"output directory\", nargs=1)\nparser.add_argument(\"--targlist\", type=str, required=True, help=\"path to list of FIBREIDs or TARGIDs to be analysed. To analyse all BA stars, enter 'all'.\", nargs=1)\nparser.add_argument(\"--params\", type=str, required=False, default='parameters.py', help=\"path to parameter file\", nargs=1)\nparser.add_argument(\"--apsclass\", type=bool, required=False, default=False, help=\"to read APS classification\", nargs=1)\nparser.add_argument(\"--override\", type=bool, required=False, default=False, help=\"remove existing files and start from scratch\", nargs=1)\n#parser.add_argument(\"--setups\", type=str, default=None, required=True, help=\"input setups\", nargs='*')\n\n\nargs = parser.parse_args()\nwrite_directory = args.outdir[0]\ntarget_list = args.targlist[0]\ndata_file = args.infiles[0]\napsclassification=args.apsclass#[0]\noverride=args.override#[0]\n\nif apsclassification==True:\n\tprint('WARNING: Code still not ready for reading L2 and check APS classification')\n\tprint('\t\tPlease, set --apsclass False')\n\tsys.exit()\t\n\n\n\n# processing (cropping, smoothing, rebinning, rotational broadening) templates if required \n\nif process_templates==True:\n\tprint('Beginning processing of templates')\n\tfrom PyAstronomy import pyasl\n\timport scipy.stats\n\ttemplatelist = np.genfromtxt(template_list_file, dtype=None, encoding=None)\n\n\t# Ensuring the number of templates to be processed matches the number of points on the grid. \n\tnotemps = len(templatelist)\n\td_size = len(Teff) * len(logg) * len(vsini)\n\tif notemps < d_size:\n\t\tprint('ERROR: The amount of templates to be processed is less than the amount of points in the grid. Add more templates to the list or reduce the grid as necessary (see PARAMETER BOUNDARIES in parameters file).')\n\t\tsys.exit()\n\tif notemps > d_size: \n\t\tprint('ERROR: The amount of templates to be processed is greater than the amount of points in the grid. Remove templates from the list or expand the grid as necessary (see PARAMETER BOUNDARIES in parameters file).')\n\t\tsys.exit()\n\n\tdef restrict_range(w, f):\t\t# to crop the templates\n\t\tour_range = (w > template_crop_min_wav) & (w < template_crop_max_wav)\n\t\tw, f = w[our_range], f[our_range]\n\t\treturn w, f\n\n\tdef smooth(w, f, sig):\t\t# to smooth/broaden templates to match resolution of observed spectrum\n\t\tf = pyasl.broadGaussFast(w, f, sig)\n\t\treturn f\n\n\tdef rotbroad(w, f, vsini):\t\t# to rotationally broaden the templates\n\t\tf = pyasl.rotBroad(w, f, 0.6, float(vsini))\n\t\treturn f\n\n\tdef rebin(w, f, samp):\t\t# to rebin the templates to match the sampling of the observed spectrum\n\t\tf, bin_edges, binnumber = scipy.stats.binned_statistic(w, f, statistic = 'mean', bins = (w[-1] - w[0]) / samp)\n\t\tbin_width = bin_edges[1] - bin_edges[0]\n\t\tw = bin_edges[1:] - bin_width/2\n\t\treturn w, f\n\n\tdef process_template(w, f, sig=sigma, samp=sampling):\n\t\tif sigma != None:\n\t\t\tf = smooth(w, f, sig)\n\t\tif sampling != None:\n\t\t\tw, f = rebin(w, f, samp)\n\t\tfile = open(template_write_directory + '/'+ os.path.splitext(os.path.basename(i))[0] + '_processed', \"w\")\n\t\tfor index in range(len(w)):\n\t\t\tfile.write(str(w[index]) + \" \" + str(f[index]) + \"\\n\")\n\t\tfile.close()\n\t\treturn w, f\n\n\tdef process_template_vsini(w, f, vsini, sig=sigma, samp=sampling):\n\t\tf = rotbroad(w, f, vsini)\n\t\tif sigma != None:\n\t\t\tf = smooth(w, f, sig)\n\t\tif sampling != None:\n\t\t\tw, f = rebin(w, f, samp)\n\t\tfile = open(template_write_directory + '/' + os.path.splitext(os.path.basename(i))[0] + '_processed_vsini' + str(int(vsini)), \"w\")\n\t\tfor index in range(len(w)):\n\t\t\tfile.write(str(w[index]) + \" \" + str(f[index]) + \"\\n\")\n\t\tfile.close()\n\t\treturn w, f\n\n\tdef write_to_grid(templatename, f, t_ind=temp_ind, l_ind=logg_ind, v_ind=vsini_ind, vsini0=None):\n\t\t# finding the teff and logg information from the template name, to write to corresponding grid point\n\t\tt1 = float(templatename[temp_ind[0]:temp_ind[1]])\n\t\tl1 = float(templatename[logg_ind[0]:logg_ind[1]])\n\t\tif vsini0==None:\n\t\t\tv1 = float(templatename[vsini_ind[0]:vsini_ind[1]])\n\t\telse: \n\t\t\tv1 = float(vsini0)\n\n\t\tprint('Teff: ' + str(t1) + ', logg: ' + str(l1) + ', vsini: ' + str(v1))\n\n\t\td[np.where(Teff == t1)[0][0], np.where(logg == l1)[0][0], np.where(vsini == v1)[0][0]] = f\n\n\tt_wavelength_0, t_flux_0 = np.genfromtxt(templatelist[0], unpack=True, usecols=(wav_ind, flux_ind), dtype=None, encoding=None)\n\tt_wavelength_0, t_flux_0 = restrict_range(t_wavelength_0, t_flux_0)\n\tif sampling != None:\n\t\tt_wavelength_0, t_flux_0 = rebin(t_wavelength_0, t_flux_0, sampling)\n\n\td = np.zeros((len(Teff), len(logg), len(vsini), len(t_wavelength_0)))\n\td_filled = 0\n\n\tfor i in templatelist:\n\t\tprint('Processing: ' + i)\n\t\tt_wavelength, t_flux = np.genfromtxt(i, unpack=True, usecols=(wav_ind, flux_ind), dtype=None, encoding=None)\n\t\tt_wavelength, t_flux = restrict_range(t_wavelength, t_flux)\n\t\tif rotbroads == None:\n\t\t\t_, t_flux = process_template(t_wavelength, t_flux, sigma, sampling)\n\t\t\tprint('template processed, writing to grid at:')\n\t\t\twrite_to_grid(i, t_flux)\n\t\t\td_filled += 1\n\t\t\tprint('grid is ' + str(\"{0:.1f}\".format(float(d_filled)/float(d_size) * 100.)) + ' percent full')\n\n\n\n\t\telse:\n\t\t\tprint('processing for vsini: 0')\n\t\t\t_, t_flux_v0 = process_template(t_wavelength, t_flux, sig=sigma, samp=sampling)\n\t\t\tprint('template processed, writing to grid at:')\n\t\t\twrite_to_grid(i, t_flux_v0, vsini0=0.)\n\t\t\td_filled += 1\n\t\t\tprint('grid is ' + str(\"{0:.1f}\".format(float(d_filled)/float(d_size) * 100.)) + ' percent full')\n\n\t\t\tfor j in rotbroads:\n\t\t\t\tif j == 0:\n\t\t\t\t\tcontinue\n\t\t\t\tprint('processing for vsini: ' + str(j))\n\t\t\t\t_, t_flux_vj = process_template_vsini(t_wavelength, t_flux, j, sig=sigma, samp=sampling)\n\t\t\t\tprint('template processed, writing to grid at:')\n\t\t\t\twrite_to_grid(i, t_flux_vj, vsini0=j)\n\t\t\t\td_filled += 1\n\t\t\t\tprint('grid is ' + str(\"{0:.1f}\".format(float(d_filled)/float(d_size) * 100.)) + ' percent full')\n\n\n\tnp.save(template_write_directory + 'template_grid.npy', d)\n\n\n# creating /plots and /results folders in write_directory if they dont already exist \nif not os.path.exists(write_directory + '/plots'):\n    os.mkdir(write_directory + '/plots')\n    print(write_directory + 'plots folder created')\nif not os.path.exists(write_directory + '/results'):\n    os.mkdir(write_directory + '/results')\n    print(write_directory + 'results folder created')\n\nif process_templates==False:\n\t# location of folder containing this script\n\ttemplatedirectory = os.path.dirname(os.path.abspath(__file__)) + '/templates/'\n\t# loading the template flux grid\n\tflux_data_all = np.load(templatedirectory + 'template_grid.npy')\n\t#loading the wavelength data\n\ttemplatewavelength = np.loadtxt(templatedirectory + 'wavelength_data.dat')\nelse:\n\t# the first template for the template wavelength data\n\tflux_data_all = np.load(template_write_directory + 'template_grid.npy')\n\ttemplatewavelength = t_wavelength_0\n\ntemplate_min_wav = min_wav*(1.0 + (min(drv)/299792.458)) - 10.\ntemplate_max_wav = max_wav*(1.0 + (max(drv)/299792.458)) + 10.\n\ntemplatemask = (templatewavelength > template_min_wav) & (templatewavelength < template_max_wav)\nflux_data = np.zeros((len(Teff), len(logg), len(vsini), len(templatewavelength[templatemask])))\ntemplatewavelength = templatewavelength[templatemask]\n\nfor ii in range(len(Teff)):\n\tfor jj in range(len(logg)):\n\t\tfor kk in range(len(vsini)):\n\t\t\tflux_data[ii,jj,kk] = flux_data_all[ii,jj,kk][templatemask]\n\n\nipo = interpolate.RegularGridInterpolator((Teff, logg, vsini), flux_data, method='linear')\n\n# grid of parameters for walker initial positions\nini_grid = [Teff, logg, vsini, drv, slopes, intercepts]\nndim=6\n\n# define edges of parameter space\nteffmin, teffmax, loggmin, loggmax, vsinimin, vsinimax, rvmin, rvmax, slopemin, slopemax, interceptmin, interceptmax = min(Teff), max(Teff), min(logg), max(logg), min(vsini), max(vsini), min(drv), max(drv), min(slopes), max(slopes), min(intercepts), max(intercepts)\n\ndef model(X, wavelength):\n\ti, j, k, l, m, n = X \n\t# interpolating template grid with teff (i), logg (j), vsini (k) trial parameter\n\ttemplateflux = ipo([i, j, k])[0]\n\t# interpolating on wavelength axis for trial RV (l)\n\tfi = interpolate.interp1d(templatewavelength*(1.0 + l/299792.458), templateflux)\n\treturn fi(wavelength)\n\ndef lnprior(X):\n\ti, j, k, l, m, n = X\n\t# flat prior, edges should corespond to template grid\n\tif (teffmin <= i <= teffmax) & (loggmin <= j <= loggmax) & (vsinimin <= k <= vsinimax) & (rvmin <= l <= rvmax) & (slopemin <= m <= slopemax) & (interceptmin <= n <= interceptmax):\n\t\treturn 0.0\n\telse:\n\t\treturn -np.inf\n\ndef lnlike(X, wavelength, flux, noisespec, mask):\n\ti, j, k, l, m, n = X\n\tz = m, n \n\tf = np.poly1d(z)\n\tif exclude_region == False:\n\t\treturn -(np.sum((flux - (model(X, wavelength)*f(wavelength)))**2/(2*PPRE*noisespec**2)))\n\telse:\n\t\treturn -(np.sum((flux[mask] - (model(X, wavelength)*f(wavelength))[mask])**2/(2*PPRE*noisespec[mask]**2)))\n\ndef mcmc_one(t):\n\n\tprint(\"Processing: \" + t)  \n\ttarg_start = datetime.now()\n\n\t# checking if spectrum file exists, and if result already written\n\tif os.path.exists(write_directory + '/results/' + os.path.splitext(os.path.basename(t))[0] + '_results'):\n\t\tif override:\n\t\t\tos.remove(write_directory + '/results/' + os.path.splitext(os.path.basename(t))[0] + '_results')\n\t\t\tos.remove(write_directory + '/results/' + os.path.splitext(os.path.basename(t))[0] + '_spec')\n\t\telse:\n\t\t\tprint('WARNING: result for '+t+' already exists, skipping')\n\t\t\treturn\n\n\t# specify unnormalised calibrated flux\n\twith fits.open(data_file) as ALLDATA:\n\t\tfinal_spectra = ALLDATA['RED_DATA'].data[info['TARGID'] == t][0]\n\t\tspectra_before_sky_subtraction = ALLDATA['RED_DATA_NOSS'].data[info['TARGID'] == t][0]\n\t\tCalibration_function = ALLDATA['RED_SENSFUNC'].data[info['TARGID'] == t][0]\n\t\ttry: \n\t\t\tidx=list(ALLDATA['FIBTABLE'].data['FIBREID']).index(t)\n\t\texcept:\n\t\t\tidx=list(ALLDATA['FIBTABLE'].data['TARGID']).index(t)\n\t\tNSPEC = ALLDATA['FIBTABLE'].data['Nspec'][idx]\n\t\tFIBREID = ALLDATA['FIBTABLE'].data['FIBREID'][idx]\n\t\tCNAME = ALLDATA['FIBTABLE'].data['CNAME'][idx]\n\tflux = final_spectra * Calibration_function * 1.0e18\n\n\t# restrict to desired wavelength range\n\tflux = flux[targetmask]\n\n\t# create corresponsing noise spectrum\n\tnoisespec = np.sqrt((2.*spectra_before_sky_subtraction - final_spectra)*Calibration_function*1.0e18)\n\tnoisespec = noisespec[targetmask]\n\n\t# mask for excluding a wavelength region\n\tif exclude_region == True:\n\t\tmask = np.zeros(len(wavelength), dtype=bool)\n\t\tfor line in lines:\n\t\t\tmask |= (wavelength >= line[0]) & (wavelength <= line[1])\n\telse:\n\t\tmask = np.ones(len(wavelength), dtype=bool)\n\n\t# choose initial walker positions\n\tpos = [[[np.random.choice(i) for i in ini_grid] for i in range(nwalkers)] for i in range(ntemps)]\n\n\t# initialise MCMC sampler\n\tsampler = PTSampler(ntemps=ntemps, nwalkers=nwalkers, dim=ndim, logl=lnlike, logp=lnprior, Tmax=np.inf, loglargs=[wavelength, flux, noisespec, mask])\n\n\t# run MCMC sampler for burn period\n\tif progress_bar==True:\n\t\tprint(\"running burn\")\n\tpos, prob, state = sampler.run_mcmc(pos, burn, adapt=True, progress_bar=progress_bar)\n\t# reset sampler, run MCMC sampler for run period with walkers starting at their positions at the end of burn\n\tsampler.reset()\n\tif progress_bar==True:\n\t\tprint(\"running runs\")\n\tsampler.run_mcmc(pos, runs, adapt=True, progress_bar=progress_bar)\n\tsamples=sampler.chain[0, :, :, :].reshape((-1, ndim))\n\n#\t# plot walker paths\n#\tylabels = ['Teff', 'logg', 'vsini', 'RV', 'slope', 'intercept']\n#\tfor m in range(ndim):\n#\t\tplt.subplot(ndim,1,m+1)\n#\t\tplt.plot(sampler.chain[0,:,:,m].transpose(), alpha=0.2)\n#\t\tplt.ylabel(ylabels[m])\n#\tplt.xlabel('Step')\n#\tplt.savefig(write_directory + '/plots/' + t + '_walkers.png', bbox_inches='tight')\n#\tplt.close()\n\n\t# calculate 16th, 50th, 84th quantiles of the parameter samples\n\tquantiles = mquantiles(samples, prob=[0.16, 0.50, 0.84], axis=0)\n\n\ttargetname = os.path.splitext(os.path.basename(t))[0]\n\tacceptance_r = np.mean(sampler.acceptance_fraction)\n\n\t# print acceptance fraction, should be between 0.2-0.5 for efficient sampling\n\tprint(\"Mean acceptance fraction: {0:.3f}\"\n                .format(acceptance_r))\n\n\t# The parameter results\n\tTeff_r = quantiles[1][0]\n\tTeffminus_r = quantiles[1][0] - quantiles[0][0]\n\tTeffplus_r = quantiles[2][0] - quantiles[1][0]\n\tlogg_r = quantiles[1][1]\n\tloggminus_r = quantiles[1][1] - quantiles[0][1]\n\tloggplus_r = quantiles[2][1] - quantiles[1][1]\n\tvsini_r = quantiles[1][2]\n\tvsiniminus_r = quantiles[1][2] - quantiles[0][2]\n\tvsiniplus_r = quantiles[2][2] - quantiles[1][2]\n\tRV_r = quantiles[1][3]\n\tRVminus_r = quantiles[1][3] - quantiles[0][3]\n\tRVplus_r = quantiles[2][3] - quantiles[1][3]\n\tslope_r = quantiles[1][4]\n\tslopeminus_r = quantiles[1][4] - quantiles[0][4]\n\tslopeplus_r = quantiles[2][4] - quantiles[1][4]\n\tintercept_r = quantiles[1][5]\n\tinterceptminus_r = quantiles[1][5] - quantiles[0][5]\n\tinterceptplus_r = quantiles[2][5] - quantiles[1][5]\n\n\t#fig = corner.corner(samples, quantiles=[0.16, 0.50, 0.84], labels=['Teff', 'log(g)', 'vsini', 'RV', 'slope', 'intercept'], show_titles=True, title_kwargs={\"fontsize\": 10}, plot_datapoints=True, plot_contours=True, auto_bars=True, data_kwargs={\"alpha\": 0.005})\n\t# fig.savefig(write_directory + t + '_cornerplot.png', bbox_inches='tight')\n\t# plt.close()\n\n\t# parameters of best fit (for plotting)\n\tXp = Teff_r, logg_r, vsini_r, RV_r, slope_r, intercept_r\n\tfp = np.poly1d(Xp[-2:])\n\tfitp = fp(wavelength)\n\n#\t# plot spectrum and best-fit\n#\tplt.plot(wavelength, flux, wavelength, model(Xp, wavelength) * fitp)\n#\tif exclude_region == True:\n#\t\tfor n,line in enumerate(lines):\n#\t\t\tif n == 0:\n#\t\t\t\tplt.vlines([line[1]], flux.min()*0.8, flux.max()*1.2, colors='r', linestyles='dashed')\n#\t\t\telif n == (len(lines)-1):\n#\t\t\t\tplt.vlines([line[0]], flux.min()*0.8, flux.max()*1.2, colors='r', linestyles='dashed')\n#\t\t\telse:\n#\t\t\t\tplt.vlines([line[0], line[1]], flux.min()*0.8, flux.max()*1.2, colors='r', linestyles='dashed')\n\n#\tplt.xlim(min_wav, max_wav)\n#\tplt.ylim(flux.min()*0.8, flux.max()*1.2)\n#\tplt.xlabel(r'Wavelength ($\\AA$)')\n#\tplt.ylabel('Calibrated counts')\n#\tplt.savefig(write_directory + '/plots/' + t + '_spectrum.png', bbox_inches='tight')\n#\tplt.close()\n\n#\t# plot mapping function\n#\tplt.plot(wavelength, fitp, wavelength, flux / model(Xp, wavelength))\n#\tplt.xlim(min_wav, max_wav)\n#\tplt.xlabel(r'Wavelength ($\\AA$)')\n#\tplt.ylabel('Calibrated counts')\n#\tplt.savefig(write_directory + '/plots/' + t + '_mapping_function.png', bbox_inches='tight')\n#\tplt.close()\n\n\t# write results\n\ttab = open(write_directory + '/results/' + t +  '_results', \"w\")\n\ttab.write(np.str(NSPEC) + \" \" + np.str(FIBREID) + \" \" + np.str(CNAME) + \" \" + t + \" \" + np.str(acceptance_r) + \" \" + np.str(Teff_r) + \" \" + np.str(Teffminus_r) + \" \" + np.str(Teffplus_r) + \" \" + np.str(logg_r) + \" \" + np.str(loggminus_r) + \" \" + np.str(loggplus_r) + \" \" + np.str(vsini_r) + \" \" + np.str(vsiniminus_r) + \" \" + np.str(vsiniplus_r) + \" \" + np.str(RV_r) + \" \" + np.str(RVminus_r) + \" \" + np.str(RVplus_r) + \" \" + np.str(slope_r) + \" \" + np.str(slopeminus_r) + \" \" + np.str(slopeplus_r) + \" \" + np.str(intercept_r) + \" \" + np.str(interceptminus_r) + \" \" + np.str(interceptplus_r) + \"\\n\")\n\ttab.close()\n\n\ttab = open(write_directory + '/results/' + t +  '_spec', \"w\")\n\ttab.write(\"{0} ; {1} ; {2}; {3} ; {4} ; {5}\\n\".format(NSPEC,FIBREID,CNAME,t,list(flux),list(model(Xp, wavelength) * fitp)))\n\ttab.close()\n\n\ttarg_end = datetime.now() - targ_start\n\tprint(targ_end)\n\ndef modheader(hdul):\n\thdul[1].header.comments['TTYPE1']='The number of the spectrum'\n\thdul[1].header.comments['TTYPE2']='Fibre id'\n\thdul[1].header.comments['TTYPE3']='WEAVE object name from coordinates'\n\thdul[1].header.comments['TTYPE4']='Identifier of the target assigned by survey'\n\thdul[1].header.comments['TTYPE5']='Mean fraction of proposed walker jumps'\n\thdul[1].header.comments['TTYPE6']='Effective temperature'\n\thdul[1].header.comments['TTYPE7']='1-sigma negative uncertainty on Teff'\n\thdul[1].header.comments['TTYPE8']='1-sigma positive uncertainty on Teff'\n\thdul[1].header.comments['TTYPE9']='Surface gravity log(g)'\n\thdul[1].header.comments['TTYPE10']='1-sigma negative uncertainty on logg'\n\thdul[1].header.comments['TTYPE11']='1-sigma positive uncertainty on logg'\n\thdul[1].header.comments['TTYPE12']='Projected rotational velocity'\n\thdul[1].header.comments['TTYPE13']='1-sigma negative uncertainty on vsini'\n\thdul[1].header.comments['TTYPE14']='1-sigma positive uncertainty on vsini'\n\thdul[1].header.comments['TTYPE15']='Radial/line-of-sight velocity'\n\thdul[1].header.comments['TTYPE16']='1-sigma negative uncertainty on RV'\n\thdul[1].header.comments['TTYPE17']='1-sigma positive uncertainty on RV'\n\thdul[1].header.comments['TTYPE18']='Slope of mapping function '\n\thdul[1].header.comments['TTYPE19']='1-sigma negative uncertainty on slope'\n\thdul[1].header.comments['TTYPE20']='1-sigma positive uncertainty on slope'\n\thdul[1].header.comments['TTYPE21']='Intercept of mapping function'\n\thdul[1].header.comments['TTYPE22']='1-sigma negative uncertainty on intercept'\n\thdul[1].header.comments['TTYPE23']='1-sigma positive uncertainty on intercept'\n\n\n\thdul[1].header.comments['TFORM1']='data format of field: integer'\n\thdul[1].header.comments['TFORM2']='data format of field: integer'\n\thdul[1].header.comments['TFORM3']='data format of field: ASCII Character'\n\thdul[1].header.comments['TFORM4']='data format of field: ASCII Character'\n\thdul[1].header.comments['TFORM5']='data format of field: 4-byte REAL'\n\thdul[1].header.comments['TFORM6']='data format of field: 4-byte REAL'\n\thdul[1].header.comments['TFORM7']='data format of field: 4-byte REAL'\n\thdul[1].header.comments['TFORM8']='data format of field: 4-byte REAL'\n\thdul[1].header.comments['TFORM9']='data format of field: 4-byte REAL'\n\thdul[1].header.comments['TFORM10']='data format of field: 4-byte REAL'\n\thdul[1].header.comments['TFORM11']='data format of field: 4-byte REAL'\n\thdul[1].header.comments['TFORM12']='data format of field: 4-byte REAL'\n\thdul[1].header.comments['TFORM13']='data format of field: 4-byte REAL'\n\thdul[1].header.comments['TFORM14']='data format of field: 4-byte REAL'\n\thdul[1].header.comments['TFORM15']='data format of field: 4-byte REAL'\n\thdul[1].header.comments['TFORM16']='data format of field: 4-byte REAL'\n\thdul[1].header.comments['TFORM17']='data format of field: 4-byte REAL'\n\thdul[1].header.comments['TFORM18']='data format of field: 4-byte REAL'\n\thdul[1].header.comments['TFORM19']='data format of field: 4-byte REAL'\n\thdul[1].header.comments['TFORM20']='data format of field: 4-byte REAL'\n\thdul[1].header.comments['TFORM21']='data format of field: 4-byte REAL'\n\thdul[1].header.comments['TFORM22']='data format of field: 4-byte REAL'\n\thdul[1].header.comments['TFORM23']='data format of field: 4-byte REAL'\n\n\thdul[1].header.set('TDISP1','I4',after='TFORM1')\n\thdul[1].header.set('TDISP2','I4',after='TFORM2')\n\thdul[1].header.set('TDISP3','A20',after='TFORM3')\n\thdul[1].header.set('TDISP4','A30',after='TFORM4')\n\thdul[1].header.set('TDISP5','F7.3',after='TFORM5')\n\thdul[1].header.set('TDISP6','F7.3',after='TFORM6')\n\thdul[1].header.set('TDISP7','F7.3',after='TFORM7')\n\thdul[1].header.set('TDISP8','F7.3',after='TFORM8')\n\thdul[1].header.set('TDISP9','F7.3',after='TFORM9')\n\thdul[1].header.set('TDISP10','F7.3',after='TFORM10')\n\thdul[1].header.set('TDISP11','F7.3',after='TFORM11')\n\thdul[1].header.set('TDISP12','F7.3',after='TFORM12')\n\thdul[1].header.set('TDISP13','F7.3',after='TFORM13')\n\thdul[1].header.set('TDISP14','F7.3',after='TFORM14')\n\thdul[1].header.set('TDISP15','F7.3',after='TFORM15')\n\thdul[1].header.set('TDISP16','F7.3',after='TFORM16')\n\thdul[1].header.set('TDISP17','F7.3',after='TFORM17')\n\thdul[1].header.set('TDISP18','F7.3',after='TFORM18')\n\thdul[1].header.set('TDISP19','F7.3',after='TFORM19')\n\thdul[1].header.set('TDISP20','F7.3',after='TFORM20')\n\thdul[1].header.set('TDISP21','F7.3',after='TFORM21')\n\thdul[1].header.set('TDISP22','F7.3',after='TFORM22')\n\thdul[1].header.set('TDISP23','F7.3',after='TFORM23')\n\n\n\thdul[1].header.set('TUCD1','meta.id',after='TDISP1')\n\thdul[1].header.set('TUCD2','meta.id',after='TDISP2')\n\thdul[1].header.set('TUCD3','meta.id;meta.main',after='TDISP3')\n\thdul[1].header.set('TUCD4','meta.id',after='TDISP4')\n\thdul[1].header.set('TUCD5','obs.param',after='TDISP5')\n\thdul[1].header.set('TUCD6','phys.temperature.effective',after='TDISP6')\n\thdul[1].header.set('TUCD7','stat.error;phys.temperature.effective',after='TDISP7')\n\thdul[1].header.set('TUCD8','stat.error;phys.temperature.effective',after='TDISP8')\n\thdul[1].header.set('TUCD9','phys.gravity',after='TDISP9')\n\thdul[1].header.set('TUCD10','stat.error;phys.gravity',after='TDISP10')\n\thdul[1].header.set('TUCD11','stat.error;phys.gravity',after='TDISP11')\n\thdul[1].header.set('TUCD12','phys.veloc.rotat',after='TDISP12')\n\thdul[1].header.set('TUCD13','stat.error;phys.veloc.rotat',after='TDISP13')\n\thdul[1].header.set('TUCD14','stat.error;phys.veloc.rotat',after='TDISP14')\n\thdul[1].header.set('TUCD15','spect.dopplerVeloc',after='TDISP15')\n\thdul[1].header.set('TUCD16','stat.error;spect.dopplerVeloc',after='TDISP16')\n\thdul[1].header.set('TUCD17','stat.error;spect.dopplerVeloc',after='TDISP17')\n\thdul[1].header.set('TUCD18','obs.param',after='TDISP18')\n\thdul[1].header.set('TUCD19','stat.error;obs.param',after='TDISP19')\n\thdul[1].header.set('TUCD20','stat.error;obs.param',after='TDISP20')\n\thdul[1].header.set('TUCD21','obs.param',after='TDISP21')\n\thdul[1].header.set('TUCD22','stat.error;obs.param',after='TDISP22')\n\thdul[1].header.set('TUCD23','stat.error;obs.param',after='TDISP23')\n\n\n\thdul[1].header.set('TUNIT6','K',after='TUCD6')\n\thdul[1].header.set('TUNIT7','K',after='TUCD7')\n\thdul[1].header.set('TUNIT8','K',after='TUCD8')\n\thdul[1].header.set('TUNIT12','km/s',after='TUCD12')\n\thdul[1].header.set('TUNIT13','km/s',after='TUCD13')\n\thdul[1].header.set('TUNIT14','km/s',after='TUCD14')\n\thdul[1].header.set('TUNIT15','km/s',after='TUCD15')\n\thdul[1].header.set('TUNIT16','km/s',after='TUCD16')\n\thdul[1].header.set('TUNIT17','km/s',after='TUCD17')\n\n\thdul[1].header.comments['TDISP1']='Display format for column'\n\thdul[1].header.comments['TDISP2']='Display format for column'\n\thdul[1].header.comments['TDISP3']='Display format for column'\n\thdul[1].header.comments['TDISP4']='Display format for column'\n\thdul[1].header.comments['TDISP5']='Display format for column'\n\thdul[1].header.comments['TDISP6']='Display format for column'\n\thdul[1].header.comments['TDISP7']='Display format for column'\n\thdul[1].header.comments['TDISP8']='Display format for column'\n\thdul[1].header.comments['TDISP9']='Display format for column'\n\thdul[1].header.comments['TDISP10']='Display format for column'\n\thdul[1].header.comments['TDISP11']='Display format for column'\n\thdul[1].header.comments['TDISP12']='Display format for column'\n\thdul[1].header.comments['TDISP13']='Display format for column'\n\thdul[1].header.comments['TDISP14']='Display format for column'\n\thdul[1].header.comments['TDISP15']='Display format for column'\n\thdul[1].header.comments['TDISP16']='Display format for column'\n\thdul[1].header.comments['TDISP17']='Display format for column'\n\thdul[1].header.comments['TDISP18']='Display format for column'\n\thdul[1].header.comments['TDISP19']='Display format for column'\n\thdul[1].header.comments['TDISP20']='Display format for column'\n\thdul[1].header.comments['TDISP21']='Display format for column'\n\thdul[1].header.comments['TDISP22']='Display format for column'\n\thdul[1].header.comments['TDISP23']='Display format for column'\n\n\thdul[1].header.comments['TUCD1']='UCD for column'\n\thdul[1].header.comments['TUCD2']='UCD for column'\n\thdul[1].header.comments['TUCD3']='UCD for column'\n\thdul[1].header.comments['TUCD4']='UCD for column'\n\thdul[1].header.comments['TUCD5']='UCD for column'\n\thdul[1].header.comments['TUCD6']='UCD for column'\n\thdul[1].header.comments['TUCD7']='UCD for column'\n\thdul[1].header.comments['TUCD8']='UCD for column'\n\thdul[1].header.comments['TUCD9']='UCD for column'\n\thdul[1].header.comments['TUCD10']='UCD for column'\n\thdul[1].header.comments['TUCD11']='UCD for column'\n\thdul[1].header.comments['TUCD12']='UCD for column'\n\thdul[1].header.comments['TUCD13']='UCD for column'\n\thdul[1].header.comments['TUCD14']='UCD for column'\n\thdul[1].header.comments['TUCD15']='UCD for column'\n\thdul[1].header.comments['TUCD16']='UCD for column'\n\thdul[1].header.comments['TUCD17']='UCD for column'\n\thdul[1].header.comments['TUCD18']='UCD for column'\n\thdul[1].header.comments['TUCD19']='UCD for column'\n\thdul[1].header.comments['TUCD20']='UCD for column'\n\thdul[1].header.comments['TUCD21']='UCD for column'\n\thdul[1].header.comments['TUCD22']='UCD for column'\n\thdul[1].header.comments['TUCD23']='UCD for column'\n\n\thdul[1].header.comments['TUNIT6']='physical unit of field'\n\thdul[1].header.comments['TUNIT7']='physical unit of field'\n\thdul[1].header.comments['TUNIT8']='physical unit of field'\n\thdul[1].header.comments['TUNIT12']='physical unit of field'\n\thdul[1].header.comments['TUNIT13']='physical unit of field'\n\thdul[1].header.comments['TUNIT14']='physical unit of field'\n\thdul[1].header.comments['TUNIT15']='physical unit of field'\n\thdul[1].header.comments['TUNIT16']='physical unit of field'\n\thdul[1].header.comments['TUNIT17']='physical unit of field'\n\n\n\thdul[1].header.set('TPROP1',0,after='TUCD1')\n\thdul[1].header.set('TPROP2',0,after='TUCD2')\n\thdul[1].header.set('TPROP3',0,after='TUCD3')\n\thdul[1].header.set('TPROP4',0,after='TUCD4')\n\thdul[1].header.set('TPROP5',0,after='TUCD5')\n\thdul[1].header.set('TPROP6',0,after='TUCD6')\n\thdul[1].header.set('TPROP7',0,after='TUCD7')\n\thdul[1].header.set('TPROP8',0,after='TUCD8')\n\thdul[1].header.set('TPROP9',0,after='TUCD9')\n\thdul[1].header.set('TPROP10',0,after='TUCD10')\n\thdul[1].header.set('TPROP11',0,after='TUCD11')\n\thdul[1].header.set('TPROP12',0,after='TUCD12')\n\thdul[1].header.set('TPROP13',0,after='TUCD13')\n\thdul[1].header.set('TPROP14',0,after='TUCD14')\n\thdul[1].header.set('TPROP15',0,after='TUCD15')\n\thdul[1].header.set('TPROP16',0,after='TUCD16')\n\thdul[1].header.set('TPROP17',0,after='TUCD17')\n\thdul[1].header.set('TPROP18',0,after='TUCD18')\n\thdul[1].header.set('TPROP19',0,after='TUCD19')\n\thdul[1].header.set('TPROP20',0,after='TUCD20')\n\thdul[1].header.set('TPROP21',0,after='TUCD21')\n\thdul[1].header.set('TPROP22',0,after='TUCD22')\n\thdul[1].header.set('TPROP23',0,after='TUCD23')\n\n\n\thdul[1].header.comments['TPROP1']='Public column'\n\thdul[1].header.comments['TPROP2']='Public column'\n\thdul[1].header.comments['TPROP3']='Public column'\n\thdul[1].header.comments['TPROP4']='Public column'\n\thdul[1].header.comments['TPROP5']='Public column'\n\thdul[1].header.comments['TPROP6']='Public column'\n\thdul[1].header.comments['TPROP7']='Public column'\n\thdul[1].header.comments['TPROP8']='Public column'\n\thdul[1].header.comments['TPROP9']='Public column'\n\thdul[1].header.comments['TPROP10']='Public column'\n\thdul[1].header.comments['TPROP11']='Public column'\n\thdul[1].header.comments['TPROP12']='Public column'\n\thdul[1].header.comments['TPROP13']='Public column'\n\thdul[1].header.comments['TPROP14']='Public column'\n\thdul[1].header.comments['TPROP15']='Public column'\n\thdul[1].header.comments['TPROP16']='Public column'\n\thdul[1].header.comments['TPROP17']='Public column'\n\thdul[1].header.comments['TPROP18']='Public column'\n\thdul[1].header.comments['TPROP19']='Public column'\n\thdul[1].header.comments['TPROP20']='Public column'\n\thdul[1].header.comments['TPROP21']='Public column'\n\thdul[1].header.comments['TPROP22']='Public column'\n\thdul[1].header.comments['TPROP23']='Public column'\n\n\n\thdul[1].header.set('TDMIN1',1,after='TUCD1')\n\thdul[1].header.set('TDMIN2',1,after='TUCD2')\n\thdul[1].header.set('TDMIN5',0,after='TUCD5')\n\thdul[1].header.set('TDMIN6',0,after='TUCD6')\n\thdul[1].header.set('TDMIN7',0,after='TUCD7')\n\thdul[1].header.set('TDMIN8',0,after='TUCD8')\n\thdul[1].header.set('TDMIN9',0,after='TUCD9')\n\thdul[1].header.set('TDMIN10',0,after='TUCD10')\n\thdul[1].header.set('TDMIN11',0,after='TUCD11')\n\thdul[1].header.set('TDMIN12',0,after='TUCD12')\n\thdul[1].header.set('TDMIN13',0,after='TUCD13')\n\thdul[1].header.set('TDMIN14',0,after='TUCD14')\n\thdul[1].header.set('TDMIN16',0,after='TUCD16')\n\thdul[1].header.set('TDMIN17',0,after='TUCD17')\n\thdul[1].header.set('TDMIN18',-1,after='TUCD18')\n\thdul[1].header.set('TDMIN19',0,after='TUCD19')\n\thdul[1].header.set('TDMIN20',0,after='TUCD20')\n\thdul[1].header.set('TDMIN22',0,after='TUCD22')\n\thdul[1].header.set('TDMIN23',0,after='TUCD23')\n\n\thdul[1].header.comments['TDMIN1']='Minimum value expected for field'\n\thdul[1].header.comments['TDMIN2']='Minimum value expected for field'\n\thdul[1].header.comments['TDMIN5']='Minimum value expected for field'\n\thdul[1].header.comments['TDMIN6']='Minimum value expected for field'\n\thdul[1].header.comments['TDMIN7']='Minimum value expected for field'\n\thdul[1].header.comments['TDMIN8']='Minimum value expected for field'\n\thdul[1].header.comments['TDMIN9']='Minimum value expected for field'\n\thdul[1].header.comments['TDMIN10']='Minimum value expected for field'\n\thdul[1].header.comments['TDMIN11']='Minimum value expected for field'\n\thdul[1].header.comments['TDMIN12']='Minimum value expected for field'\n\thdul[1].header.comments['TDMIN13']='Minimum value expected for field'\n\thdul[1].header.comments['TDMIN14']='Minimum value expected for field'\n\thdul[1].header.comments['TDMIN16']='Minimum value expected for field'\n\thdul[1].header.comments['TDMIN17']='Minimum value expected for field'\n\thdul[1].header.comments['TDMIN18']='Minimum value expected for field'\n\thdul[1].header.comments['TDMIN19']='Minimum value expected for field'\n\thdul[1].header.comments['TDMIN20']='Minimum value expected for field'\n\thdul[1].header.comments['TDMIN22']='Minimum value expected for field'\n\thdul[1].header.comments['TDMIN23']='Minimum value expected for field'\n\n\n\thdul[1].header.set('TDMAX1',960,after='TDMIN1')\n\thdul[1].header.set('TDMAX2',1100,after='TDMIN2')\n\thdul[1].header.set('TDMAX5',1,after='TDMIN5')\n\thdul[1].header.set('TDMAX18',1,after='TDMIN18')\n\n\thdul[1].header.comments['TDMAX1']='Maximum value expected for field'\n\thdul[1].header.comments['TDMAX2']='Maximum value expected for field'\n\thdul[1].header.comments['TDMAX5']='Maximum value expected for field'\n\thdul[1].header.comments['TDMAX18']='Maximum value expected for field'\n\n\n\n\thdul[2].header.comments['TTYPE1']='The number of the spectrum'\n\thdul[2].header.comments['TTYPE2']='Fibre id'\n\thdul[2].header.comments['TTYPE3']='WEAVE object name from coordinates'\n\thdul[2].header.comments['TTYPE4']='Identifier of the target assigned by survey'\n\thdul[2].header.comments['TTYPE5']='Input Spectrum normalised'\n\thdul[2].header.comments['TTYPE6']='Fit Spectrum normalised'\n\n\thdul[2].header.comments['TFORM1']='data format of field: integer'\n\thdul[2].header.comments['TFORM2']='data format of field: integer'\n\thdul[2].header.comments['TFORM3']='data format of field: ASCII Character'\n\thdul[2].header.comments['TFORM4']='data format of field: ASCII Character'\n\thdul[2].header.comments['TFORM5']='data format of field: 4-byte REAL'\n\thdul[2].header.comments['TFORM6']='data format of field: 4-byte REAL'\n\n\thdul[2].header.set('TDISP1','I4',after='TFORM1')\n\thdul[2].header.set('TDISP2','I4',after='TFORM2')\n\thdul[2].header.set('TDISP3','A20',after='TFORM3')\n\thdul[2].header.set('TDISP4','A30',after='TFORM4')\n\n\thdul[2].header.comments['TDISP1']='Display format for column'\n\thdul[2].header.comments['TDISP2']='Display format for column'\n\thdul[2].header.comments['TDISP3']='Display format for column'\n\thdul[2].header.comments['TDISP4']='Display format for column'\n\n\thdul[2].header.set('TUCD1','meta.id',after='TDISP1')\n\thdul[2].header.set('TUCD2','meta.id',after='TDISP2')\n\thdul[2].header.set('TUCD3','meta.id;meta.main',after='TDISP3')\n\thdul[2].header.set('TUCD4','meta.id',after='TDISP4')\n\thdul[2].header.set('TUCD5','phot.count',after='TFORM5')\n\thdul[2].header.set('TUCD6','phot.count',after='TFORM6')\n\thdul[2].header.comments['TUCD1']='UCD for column'\n\thdul[2].header.comments['TUCD2']='UCD for column'\n\thdul[2].header.comments['TUCD3']='UCD for column'\n\thdul[2].header.comments['TUCD4']='UCD for column'\n\thdul[2].header.comments['TUCD5']='UCD for column'\n\thdul[2].header.comments['TUCD6']='UCD for column'\n\n\thdul[2].header.set('TUNIT5','counts','physical unit of field',after='TUCD5')\n\thdul[2].header.set('TUNIT6','counts','physical unit of field',after='TUCD6')\n\n\thdul[2].header.set('TDMIN1',1,after='TUCD1')\n\thdul[2].header.set('TDMIN2',1,after='TUCD2')\n\thdul[2].header.comments['TDMIN1']='Minimum value expected for field'\n\thdul[2].header.comments['TDMIN2']='Minimum value expected for field'\n\thdul[2].header.set('TDMAX1',960,after='TUCD1')\n\thdul[2].header.set('TDMAX2',1100,after='TUCD2')\n\thdul[2].header.comments['TDMAX1']='Maximum value expected for field'\n\thdul[2].header.comments['TDMAX2']='Maximum value expected for field'\n\thdul[2].header.set('TPROP1',0,after='TUCD1')\n\thdul[2].header.set('TPROP2',0,after='TUCD2')\n\thdul[2].header.set('TPROP3',0,after='TUCD3')\n\thdul[2].header.set('TPROP4',0,after='TUCD4')\n\thdul[2].header.set('TPROP5',0,after='TUCD5')\n\thdul[2].header.set('TPROP6',0,after='TUCD6')\n\thdul[2].header.comments['TPROP1']='Public column'\n\thdul[2].header.comments['TPROP2']='Public column'\n\thdul[2].header.comments['TPROP3']='Public column'\n\thdul[2].header.comments['TPROP4']='Public column'\n\thdul[2].header.comments['TPROP5']='Public column'\n\thdul[2].header.comments['TPROP6']='Public column'\n\n\thdul[2].header.set('TCTYP5','AWAV','Coordinate type',after='TPROP5')\n\thdul[2].header.set('TCTYP6','AWAV','Coordinate type',after='TPROP6')\n\thdul[2].header.set('TCUNI5','Angstrom','Coordinate unit',after='TCTYP5')\n\thdul[2].header.set('TCUNI6','Angstrom','Coordinate unit',after='TCTYP6')\n\thdul[2].header.set('TCRPX5',1,'Pixel coordinate of the reference point',after='TCUNI5')\n\thdul[2].header.set('TCRPX6',1,'Pixel coordinate of the reference point',after='TCUNI6')\n\thdul[2].header.set('TCRVL5',8470.25,'Coordinate value at reference point',after='TCRPX5')\n\thdul[2].header.set('TCRVL6',8470.25,'Coordinate value at reference point',after='TCRPX6')\n\thdul[2].header.set('TCDLT5',0.25,'Coordinate increment at reference point',after='TCRVL5')\n\thdul[2].header.set('TCDLT6',0.25,'Coordinate increment at reference point',after='TCRVL6')\n\n#\thdul[2].header['XTENSION']='BINSPEC'\n\treturn hdul\n\ndef createDAT():\n\ttab = open(write_directory+'results/'+ os.path.splitext(os.path.basename(args.infiles[0]))[0]+'_AMY.dat', \"w\")\n\ttab.write(\"Date of creation: {}\\n\".format(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')))\n\ttab.write(\"\\n\")\n\ttab.write(\"######## OB info and inputs ###########\\n\")\n\ttab.write(\"OB: {}\\n\".format(os.path.splitext(os.path.basename(args.infiles[0]))[0].split('_')[1]))\n\ttab.write(\"input file: {}\\n\".format(data_file))\n\ttab.write(\"output directory: {}\\n\".format(write_directory))\n\ttab.write(\"output file: {}\\n\".format(os.path.splitext(os.path.basename(args.infiles[0]))[0]+'_AMY.fits'))\n\ttab.write(\"targlist: {}\\n\".format(target_list))\n\ttab.write(\"apsclassification: {}\\n\".format(apsclassification))\n\ttab.write(\"override: {}\\n\".format(override))\n\n\ttab.write(\"\\n\")\n\ttab.write(\"######## libraries version ###########\\n\")\n\n\ttab.write(\"numpy version: {}\\n\".format(np.version.version))\n\ttab.write(\"astropy version: {}\\n\".format(astropy.version.version))\n\ttab.write(\"scipy version: {}\\n\".format(scipy.version.version))\n\ttab.write(\"matplotlib version: {}\\n\".format(matplotlib.__version__))\n#\ttab.write(\": {}\\n\".format())\n\ttab.write(\"\\n\")\n\ttab.write(\"######## parameters.py file: ###############\\n\")\n\ttab.close()\n\tos.system('more parameters.py >>{}'.format(write_directory+'results/'+ os.path.splitext(os.path.basename(args.infiles[0]))[0]+'_AMY.dat'))\n\n\n\ndef make_output_fits():\n\n\t#PHU\n\thdr = fits.Header()\n\thdr['COMMENT'] = \"WEAVE Contributed Software: AMY\"\n\thdr['DATAMVER'] = 7.60\n\thdr.comments['DATAMVER']='WEAVE Data Model Version'\n\thdr['CS_CODE'] = 'AMY'\n\thdr.comments['CS_CODE']='CS code name'\n\thdr['CS_VER'] = 'May20'\n\thdr.comments['CS_VER']='CS version '\n\thdr['CS_NME1'] = 'Amy, Maria'\n\thdr.comments['CS_NME1']='CS author forename'\n\thdr['CS_NME2'] = 'Harris, Monguio'\n\thdr.comments['CS_NME2']='CS author surname(s)'\n\thdr['CS_MAIL'] = 'm.monguio@icc.ub.edu'\n\thdr.comments['CS_MAIL']='CS author email'\n\thdr['PROV1001'] = os.path.splitext(os.path.basename(args.infiles[0]))[0]+'.fit'\n\thdr.comments['PROV1001']='L1 file used'\n\thdr['PROV2001'] = ''\n\thdr.comments['PROV2001']='L2 file used'\n\thdr['DATETIME'] = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')\n\thdr.comments['DATETIME']='Datetime file created'\n\tprint(hdr['PROV1001'],hdr['DATETIME'])\n\tempty_primary = fits.PrimaryHDU(header=hdr)\n\n\n\t#bin,PARAM\n\toutput_files = glob.glob(write_directory + 'results/*_results')\n\tall_res = []\n\tfor i in output_files:\n\t\twith open(i) as outf:\n\t\t\tall_res.append(outf.read().split())\n\tt = Table(rows=all_res, names=('Nspec', 'FIBREID', 'CNAME', 'TARGID', 'AMY_ACCEPTANCE', 'AMY_TEFF', 'AMY_TEFF_minus', 'AMY_TEFF_plus', 'AMY_LOGG', 'AMY_LOGG_minus', 'AMY_LOGG_plus', 'AMY_VSINI', 'vsini_minus', 'AMY_VSINI_plus', 'AMY_RV', 'AMY_RV_minus', 'AMY_RV_plus', 'AMY_SLOPE', 'AMY_SLOPE_minus', 'AMY_SLOPE_plus', 'AMY_INTERCEPT', 'AMY_INTERCEPT_minus', 'INTERCEPT_plus'))\n\n\tcols=['Nspec', 'FIBREID', 'CNAME', 'TARGID', 'AMY_ACCEPTANCE', 'AMY_TEFF', 'AMY_TEFF_minus','AMY_TEFF_plus', 'AMY_LOGG', 'AMY_LOGG_minus', 'AMY_LOGG_plus', 'AMY_VSINI','vsini_minus', 'AMY_VSINI_plus', 'AMY_RV', 'AMY_RV_minus', 'AMY_RV_plus', 'AMY_SLOPE','AMY_SLOPE_minus', 'AMY_SLOPE_plus', 'AMY_INTERCEPT', 'AMY_INTERCEPT_minus', 'INTERCEPT_plus']\n\tformats=['I','I','20A','30A','E','E','E','E','E','E','E', 'E','E','E','E','E','E','E','E','E','E','E','E']\n\n\tcolumns=[]\n\tfor i in range(len(cols)):\n\t\tcolumns.append(fits.Column(name=cols[i], array=t[cols[i]],format=formats[i]))\n\n\tbintable = fits.BinTableHDU.from_columns(columns)\n\t\n\n\n\t#binspec\n\toutput_files = glob.glob(write_directory + 'results/*_spec')\n\tall_spec = []\n\tcol0=[]\n\tcol1=[]\n\tcol2=[]\n\tcol3=[]\n\tcol4=[]\n\tcol5=[]\n\tfor i in output_files:\n\t\twith open(i) as outf:\n\t\t\tline=outf.read().split(';')\n\t\t\tcol0.append(line[0])\n\t\t\tcol1.append(line[1])\n\t\t\tcol2.append(line[2])\n\t\t\tcol3.append(line[3])\n\t\t\tcol4.append(np.array(np.matrix(line[4])).ravel())\n\t\t\tcol5.append(np.array(np.matrix(line[5])).ravel())\n\tt=[col0,col1,col2,col3,col4,col5]\n\n\n\tcols=['Nspec', 'FIBREID', 'CNAME', 'TARGID','AMY_SPECTRAIN','AMY_SPECTRAFIT']\n\tformats=['I','I','20A','30A','1879E','1879E']\n\n\tcolumns=[]\n\tfor i in range(len(cols)):\n\t\tcolumns.append(fits.Column(name=cols[i], array=t[i],format=formats[i]))\n\n\tspectable = fits.BinTableHDU.from_columns(columns)\n\t\n\thdul = fits.HDUList([empty_primary,bintable,spectable])\n\thdul = modheader(hdul)\n\n\thdul.writeto(write_directory+'results/'+os.path.splitext(os.path.basename(args.infiles[0]))[0]+'_AMY.fits', overwrite=False, checksum=True)\n\n#ascii file with info for reproducibility:\n\tcreateDAT()\n\n\n\nif __name__ ==  '__main__':\n\t# checking if results table already exists\n\tif os.path.exists(write_directory+'results/'+os.path.splitext(os.path.basename(args.infiles[0]))[0]+'_AMY.fits'):\n\t\tif override:\n\t\t\tos.remove(write_directory+'results/'+ os.path.splitext(os.path.basename(args.infiles[0]))[0]+'_AMY.fits')\n\t\telse:\n\t\t\tprint('WARNING: result table already exists, ending process.')\n\t\t\tsys.exit()\n\tif target_list == 'all':\n\t\tprint(\"Processing all BA stars in fits file\")\n\t\tBA = []\n\t\twith fits.open(data_file) as ALLDATA:\n\t\t\tfor n,i in enumerate(ALLDATA['FIBTABLE'].data['TARGID']):\n\t\t\t\tif 'LR-BA' in i:\n#\t\t\tfor n,i in enumerate(ALLDATA['FIBTABLE'].data['TARGCLASS']):\n#\t\t\t\tif 'STAR_BA' in i:\n\t\t\t\t\tif ALLDATA['FIBTABLE'].data['STATUS'][n]=='A':\n\t\t\t\t\t\tBA.append(i)\n\telse:\n\t\tprint(\"Processing BA stars specified in target list\")\n\t\ttarglist = np.genfromtxt(target_list, dtype=None, encoding=None)\n\t\tBA = []\n\t\twith fits.open(data_file) as ALLDATA:\n\t\t\tfor targ in targlist:\n\t\t\t\ttry: \n\t\t\t\t\tidx=list(ALLDATA['FIBTABLE'].data['FIBREID']).index(targ)\n\t\t\t\t\tif ALLDATA['FIBTABLE'].data['STATUS'][idx]=='A':\n\t\t\t\t\t\tBA.append(ALLDATA['FIBTABLE'].data['TARGID'][idx])\n\t\t\t\texcept:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tidx=list(ALLDATA['FIBTABLE'].data['TARGID']).index(targ)\n\t\t\t\t\t\tif ALLDATA['FIBTABLE'].data['STATUS'][idx]=='A':\n\t\t\t\t\t\t\tBA.append(ALLDATA['FIBTABLE'].data['TARGID'][idx])\n\t\t\t\t\texcept:\t\n\t\t\t\t\t\tprint(str(targ)+\": Cant find either FIBREID or TARGID in input table.\")\n\nALLDATA = None\ninfo = None\nwavelength = None\ntargetmask = None\n\ndef set_globals():\n    global ALLDATA\n    global info \n    global wavelength\n    global targetmask\n\n    with fits.open(data_file) as ALLDATA:\n\t    head0 = ALLDATA[0].header\n\t    info = ALLDATA['FIBTABLE'].data\n\t    data1 = ALLDATA['RED_DATA'].data\n\t    head1 = ALLDATA['RED_DATA'].header\n\t    wave0 = head1['CRVAL1']  \n\t    increm = head1['CD1_1']\n\t    wavelength = np.array([wave0+increm*a for a in range(len(data1[1]))])\n\t    targetmask = (wavelength > min_wav) & (wavelength < max_wav)\n\t    wavelength = wavelength[targetmask]\n\nif multiprocess==True:\n\tfrom multiprocessing import Pool\n\tif __name__ ==  '__main__':\n\t\tpool = Pool(processes=process_no, initializer=set_globals)\n\t\tit = pool.imap_unordered(mcmc_one, BA)\n\t\tfor nn,i in enumerate(range(len(BA))):\n\t\t\tit.next()\n\t\tmake_output_fits()\n\t\tprint(datetime.now() - startTime)\n\nelse:\n\tset_globals()\n\tfor nn,i in enumerate(BA):\n\t\tmcmc_one(i)\n\tmake_output_fits()\n\tprint(datetime.now() - startTime)\n", "meta": {"hexsha": "ab57fe7376859b3f8b3a46d75f105f67197f2c10", "size": 42020, "ext": "py", "lang": "Python", "max_stars_repo_path": "ptmcmc.py", "max_stars_repo_name": "mmonguio/AMY", "max_stars_repo_head_hexsha": "3a78cfa70e32c1f9e9c524ef683fb9c062c2f5f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ptmcmc.py", "max_issues_repo_name": "mmonguio/AMY", "max_issues_repo_head_hexsha": "3a78cfa70e32c1f9e9c524ef683fb9c062c2f5f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ptmcmc.py", "max_forks_repo_name": "mmonguio/AMY", "max_forks_repo_head_hexsha": "3a78cfa70e32c1f9e9c524ef683fb9c062c2f5f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.8233369684, "max_line_length": 600, "alphanum_fraction": 0.7010947168, "include": true, "reason": "import numpy,import scipy,from scipy,import astropy,from astropy", "num_tokens": 13601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.18669732862674604}}
{"text": "from det3d.datasets.utils.eval import box3d_overlap\nfrom det3d.core.bbox.box_np_ops import center_to_corner_box3d\nimport numpy as np\n\ndef lvx_track(annos):\n    \"\"\" 将上一帧的next预测与当前帧对比，将当前帧的prev预测与上一帧对比 \"\"\"\n    new_id = 0\n    reserve_id = []\n    threshold = -0.125\n    threshold_1 = -0.325\n    threshold_2 = -0.5\n\n    birth_min = 3\n    death_min = 6\n\n    # 上一帧没有匹配的检测框，进入death\n    vir_annos = {'track_id':np.array([-2]).reshape(1),\n                 'location':np.array([[9999,9999,-2]]).reshape(1,3),\n                 'dimensions':np.array([[0,0,0]]).reshape(1,3),\n                 'rotation_y':np.array([0]).reshape(1),\n                 'location_1':np.array([[9999,9999,-2]]).reshape(1,3),\n                 'dimensions_1':np.array([[0,0,0]]).reshape(1,3),\n                 'rotation_y_1':np.array([0]).reshape(1),\n                 'location_2':np.array([[9999,9999,-2]]).reshape(1,3),\n                 'dimensions_2':np.array([[0,0,0]]).reshape(1,3),\n                 'rotation_y_2':np.array([0]).reshape(1),\n                 'age':np.array([-10000]).reshape(1) # 寿命暂定为6帧\n                 }\n    \n    # 新生track的id池，连续3帧才算为正式的\n    birth_annos = {'track_id':np.array([-2]).reshape(1),\n                 'age':np.array([-10000]).reshape(1) # 寿命暂定为6帧\n                }\n\n    \n    for i,anno in enumerate(annos):\n        if i == 0:\n            anno[\"track_id\"] = np.arange(0,anno[\"name\"].shape[0])\n            new_id+=anno[\"name\"].shape[0]\n        else:\n            boxes = anno_to_boxes(anno,'')\n            boxes_1 = anno_to_boxes(annos[i-1],'_2')\n\n            boxes_2 = anno_to_boxes(anno,'_1')\n            boxes_3 = anno_to_boxes(annos[i-1],'')\n            flag = []\n\n            # 先判断是否多个人交汇成一个人\n            past_predict = get_track_scores(boxes_2,boxes_3)\n            predict_pre = get_track_scores(boxes,boxes_1)\n\n            for age,new_track in zip(birth_annos['age'],birth_annos['track_id']):\n                ind = np.where(annos[i-1]['track_id'] == new_track)\n                # 假阳性的不进行分裂\n                predict_pre[:,ind] = -1\n            split = []\n            det_match = (predict_pre>threshold_1).sum(1).reshape(-1)\n            track_match = (predict_pre>threshold_1).sum(0).reshape(-1)\n            for det in range(det_match.shape[0]):\n                indices = np.where(predict_pre[det]>threshold_1)[0]\n                if det_match[det]>1 and (track_match[indices]<=1).all():\n                    # 当前的detect与多个track匹配，说明多个人汇合一起，需要将detect分割 \n                    # TODO: virtual box应该也算进来\n\n                    # 如果汇合处的detect和其中一个track匹配度非常高，而一些很低，则说明只是个别没有检测到\n                    stay = []\n                    if predict_pre[det].max()>0.6:\n                        for ind in range(len(indices)):\n                            if predict_pre[det,indices[ind]] < predict_pre[det].max():\n                                stay.append(ind)\n                    indices = np.delete(indices,stay)\n\n                    split.append(det)\n                    detect = boxes[det].copy()\n                    tracks = boxes_1[indices].copy()\n                    loc_err = detect-tracks.mean(0)\n                    new_detect = tracks.copy()\n                    new_detect[:,:3] = tracks[:,:3] + loc_err[:3]\n                    new_detect[:,6] = tracks[:,6] + loc_err[6]\n                    new_detect_1 = boxes_3[indices].copy()\n                    new_detect_2 = new_detect.copy()\n                    new_detect_2[:,:3] = new_detect[:,:3]+tracks[:,:3]-new_detect_1[:,:3]\n                    boxes = np.concatenate([boxes,new_detect],axis=0)\n                    boxes_2 = np.concatenate([boxes_2,new_detect_1],axis=0)\n                    anno['location'] = np.concatenate([anno['location'],new_detect[:,:3]],axis=0)\n                    anno['dimensions'] = np.concatenate([anno['dimensions'],new_detect[:,3:6]],axis=0)\n                    anno['rotation_y'] = np.concatenate([anno['rotation_y'],new_detect[:,6]],axis=0)\n                    anno['location_1'] = np.concatenate([anno['location_1'],new_detect_1[:,:3]],axis=0)\n                    anno['dimensions_1'] = np.concatenate([anno['dimensions_1'],new_detect_1[:,3:6]],axis=0)\n                    anno['rotation_y_1'] = np.concatenate([anno['rotation_y_1'],new_detect_1[:,6]],axis=0)\n                    anno['location_2'] = np.concatenate([anno['location_2'],new_detect_2[:,:3]],axis=0)\n                    anno['dimensions_2'] = np.concatenate([anno['dimensions_2'],new_detect_2[:,3:6]],axis=0)\n                    anno['rotation_y_2'] = np.concatenate([anno['rotation_y_2'],new_detect_2[:,6]],axis=0)\n                    anno['name'] = np.concatenate([anno['name'],annos[i-1]['name'][indices]],axis=0)\n                    anno['alpha'] = np.concatenate([anno['alpha'],annos[i-1]['alpha'][indices]],axis=0)\n                    anno['bbox'] = np.concatenate([anno['bbox'],annos[i-1]['bbox'][indices]],axis=0)\n                    anno['score'] = np.concatenate([anno['score'],anno['score'][det:det+1].repeat(indices.shape[0],axis=0)],axis=0)\n\n            boxes = np.delete(boxes,split,axis=0)\n            boxes_2 = np.delete(boxes_2,split,axis=0)\n            track_ids = -1*np.ones(boxes.shape[0])\n            scores = -1*np.ones(boxes.shape[0])\n\n            # 将detect分割后同时修改anno\n            anno = del_dict(anno,split)\n\n            assert annos[i]['name'].shape[0] == boxes.shape[0]\n\n            # 基准帧为过去一帧的当前检测\n            past_predict = get_track_scores(boxes_2,boxes_3)\n            # get_track(past_predict,threshold,track_ids,scores, annos[i-1],flag)\n            \n            predict_pre = get_track_scores(boxes,boxes_1)\n\n            # T,T-1的可信度更高，T+1的可信度更低\n            predict_pre = 0.6*past_predict+0.4*predict_pre\n            for age,new_track in zip(birth_annos['age'],birth_annos['track_id']):\n                ind = np.where(annos[i-1]['track_id'] == new_track)\n                # new track不确定是否为假阳性，所以权重调低\n                predict_pre[:,ind] = (predict_pre[:,ind]-threshold)*(1+age)/(birth_min+1) + threshold\n            get_track(predict_pre,threshold,track_ids,scores,annos[i-1],flag)\n\n            # 前一帧没有被匹配的加入到vir中，并且是已经确定为非假阳性的，不在birth里面\n            for j in range(len(annos[i-1]['track_id'])):\n                if j not in flag and annos[i-1]['track_id'][j] not in birth_annos['track_id']:\n                    # 否则，则将其添加到vir_annos里\n                    vir_annos['track_id']=np.concatenate([vir_annos['track_id'],[annos[i-1]['track_id'][j]]],axis=-1)\n                    vir_annos['location']=np.concatenate([vir_annos['location'],[annos[i-1]['location'][j]]],axis=0)\n                    vir_annos['dimensions']=np.concatenate([vir_annos['dimensions'],[annos[i-1]['dimensions'][j]]],axis=0)\n                    vir_annos['rotation_y']=np.concatenate([vir_annos['rotation_y'],[annos[i-1]['rotation_y'][j]]],axis=-1)\n                    vir_annos['location_1']=np.concatenate([vir_annos['location_1'],[annos[i-1]['location_1'][j]]],axis=0)\n                    vir_annos['dimensions_1']=np.concatenate([vir_annos['dimensions_1'],[annos[i-1]['dimensions_1'][j]]],axis=0)\n                    vir_annos['rotation_y_1']=np.concatenate([vir_annos['rotation_y_1'],[annos[i-1]['rotation_y_1'][j]]],axis=-1)\n                    vir_annos['location_2']=np.concatenate([vir_annos['location_2'],[annos[i-1]['location_2'][j]]],axis=0)\n                    vir_annos['dimensions_2']=np.concatenate([vir_annos['dimensions_2'],[annos[i-1]['dimensions_2'][j]]],axis=0)\n                    vir_annos['rotation_y_2']=np.concatenate([vir_annos['rotation_y_2'],[annos[i-1]['rotation_y_2'][j]]],axis=-1)\n                    vir_annos['age']=np.concatenate([vir_annos['age'],[0]],axis=-1)\n            \n            vir_boxes = anno_to_boxes(vir_annos,'')\n            flag_vir = []\n            # 与virtual框进行阈值更低的匹配\n            # if anno['metadata']['token'] == '642':\n            #     print(boxes_2,vir_boxes)\n            #     import pdb; pdb.set_trace()\n            virtual = get_track_scores(boxes_2,vir_boxes)\n            get_track(virtual,threshold_2,track_ids,scores,vir_annos,flag_vir)\n\n            # 删除virtual中被成功匹配的框,被具现化了\n            vir_annos = del_dict(vir_annos,flag_vir)\n\n            # 向下一帧移动   \n            vir_annos['location_1'][:,:2]= vir_annos['location'][:,:2].copy()\n            vir_annos['location'][:,:2] = vir_annos['location_2'][:,:2].copy()\n            flag_vir = []\n            for j in range((len(vir_annos['track_id']))):\n                vir_annos['location_2'][j,:2] = 2*vir_annos['location'][j,:2]-vir_annos['location_1'][j,:2]\n                vir_annos['age'][j] += 1\n                if vir_annos['location'][j,0]<-40 or vir_annos['location'][j,0]>40 or vir_annos['location'][j,1]<-40 or vir_annos['location'][j,1]>40:\n                    # 如果出了边界，去掉这个人\n                    flag_vir.append(j)\n                if vir_annos['age'][j] > death_min and j not in flag_vir:\n                    # age>6 去掉\n                    flag_vir.append(j)\n            \n            vir_annos = del_dict(vir_annos,flag_vir)\n\n            #处理新生id\n            flag_birth = []\n            for j,new_track in enumerate(birth_annos['track_id']):\n                ind = np.where(annos[i-1]['track_id'][flag] == new_track)[0]\n                if ind.size>0 and birth_annos['age'][j]<birth_min-1:\n                    birth_annos['age'][j] += 1\n                elif new_track>=0:\n                    # 若达到成年寿命，或者中途夭折，去掉\n                    flag_birth.append(j)\n                    if birth_annos['age'][j] < birth_min-1:\n                        reserve_id.append(new_track)\n            birth_annos['age'] = np.delete(birth_annos['age'],flag_birth)\n            birth_annos['track_id'] = np.delete(birth_annos['track_id'],flag_birth)\n\n            for index in range(track_ids.shape[0]):\n                if track_ids[index] == -1:\n                    print(anno['metadata']['token'],index,new_id,anno['location'][index])\n                    if len(reserve_id) == 0:\n                        # 假阳性的id再次使用\n                        track_ids[index] = new_id\n                        new_id += 1\n                    else:\n                        track_ids[index] = reserve_id[-1]\n                        del reserve_id[-1]\n                    birth_annos['track_id'] = np.concatenate([birth_annos['track_id'],[track_ids[index]]],axis=0)\n                    birth_annos['age'] = np.concatenate([birth_annos['age'],[0]],axis=0)\n            anno[\"track_id\"] = track_ids\n    \n    return annos\n\ndef get_track_scores(boxes,boxes_1):\n    ''' DIoU'''\n    predict_pre = box3d_overlap(boxes,boxes_1,z_axis=2,z_center=0.5)\n\n    corners = center_to_corner_box3d(boxes[:,:3],boxes[:,3:6],boxes[:,6])\n    corners_1 = center_to_corner_box3d(boxes_1[:,:3],boxes_1[:,3:6],boxes_1[:,6])\n    for i in range(boxes.shape[0]):\n        for j in range(boxes_1.shape[0]):\n            c = ((boxes[i,:3]-boxes_1[j,:3])**2).sum()\n            d = get_farest(corners[i],corners_1[j])\n            predict_pre[i,j] -= c/d\n    return predict_pre\n\n\ndef get_farest(corners,corners_1):\n    max_d = 0\n    for i in range(8):\n        for j in range(8):\n            dist = ((corners[i]-corners_1[j])**2).sum()\n            if dist > max_d:\n                max_d = dist\n    return max_d\n    \ndef anno_to_boxes(anno,flag):\n    boxes = np.concatenate([anno[f'location{flag}'],anno[f'dimensions{flag}'],anno[f'rotation_y{flag}'][...,np.newaxis]],axis=1)\n    return boxes\n\ndef get_track(iou, threshold, track, scores, anno, flag):\n    num1 = 0\n    num2 = 0\n    while(num1<iou.shape[0] and num2<iou.shape[1]):\n        loc_max = iou.argmax()\n        max_iou = [loc_max//iou.shape[1],loc_max%iou.shape[1]]\n        score = iou[max_iou[0],max_iou[1]]\n        if score <threshold:\n            break\n        # track_ids 需要没有被占用过,并且前一帧的flag没被用过\n        if track[max_iou[0]] != -1:\n            iou[max_iou[0],:] = -1\n            num1+=1\n        elif max_iou[1] in flag:\n            iou[:,max_iou[1]] = -1\n            num2+=1\n        else:\n            track[max_iou[0]] = anno['track_id'][max_iou[1]]\n            scores[max_iou[0]] = score\n            flag.append(max_iou[1])\n            iou[max_iou[0],:] = -1\n            iou[:,max_iou[1]] = -1\n            num1+=1\n            num2+=1\n\ndef del_dict(anno,flag):\n    anno['location'] = np.delete(anno['location'],flag,axis=0)\n    anno['dimensions'] = np.delete(anno['dimensions'],flag,axis=0)\n    anno['rotation_y'] = np.delete(anno['rotation_y'],flag,axis=0)\n    anno['location_1'] = np.delete(anno['location_1'],flag,axis=0)\n    anno['dimensions_1'] = np.delete(anno['dimensions_1'],flag,axis=0)\n    anno['rotation_y_1'] = np.delete(anno['rotation_y_1'],flag,axis=0)\n    anno['location_2'] = np.delete(anno['location_2'],flag,axis=0)\n    anno['dimensions_2'] = np.delete(anno['dimensions_2'],flag,axis=0)\n    anno['rotation_y_2'] = np.delete(anno['rotation_y_2'],flag,axis=0)\n\n    if 'name' in anno.keys():\n        anno['name'] = np.delete(anno['name'],flag,axis=0)\n        anno['alpha'] = np.delete(anno['alpha'],flag,axis=0)\n        anno['score'] = np.delete(anno['score'],flag,axis=0)\n        anno['bbox'] = np.delete(anno['bbox'],flag,axis=0)\n    \n    if 'age' in anno.keys():\n        anno['track_id'] = np.delete(anno['track_id'],flag,axis=0)\n        anno['age'] = np.delete(anno['age'],flag,axis=0)\n    \n    return anno", "meta": {"hexsha": "856d9c3ccdd7f07ec84c724dc5a1acdd5f0dc4a3", "size": 13242, "ext": "py", "lang": "Python", "max_stars_repo_path": "det3d/datasets/lvx/lvx_track.py", "max_stars_repo_name": "meng-zha/Det3D", "max_stars_repo_head_hexsha": "0cabfec8cb243e407506fad0bd57675f4410b0fb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "det3d/datasets/lvx/lvx_track.py", "max_issues_repo_name": "meng-zha/Det3D", "max_issues_repo_head_hexsha": "0cabfec8cb243e407506fad0bd57675f4410b0fb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "det3d/datasets/lvx/lvx_track.py", "max_forks_repo_name": "meng-zha/Det3D", "max_forks_repo_head_hexsha": "0cabfec8cb243e407506fad0bd57675f4410b0fb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.0444444444, "max_line_length": 150, "alphanum_fraction": 0.5441020994, "include": true, "reason": "import numpy", "num_tokens": 3930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.18669732862674604}}
{"text": "import numpy as np\nimport pandas as pd\nimport pymc3 as pm\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass\nfrom .constants import *\nfrom .utils import *\n\n__all__ = ['Damuta', 'DataSet', 'SignatureSet']\n\n_opt_methods = {\"ADVI\": pm.ADVI, \"FullRankADVI\": pm.FullRankADVI}\n_init_strats = ['kmeans', 'uniform']\n\n@dataclass\nclass DataSet:\n    \"\"\"Container for tabular data, allowing simple access to a mutation data set and corresponding annotation for each sample.\n    \n    :class:`DataSet` is instatiated from a pandas dataframe of mutation counts, and (optionally) a pandas dataframe of the\n    same size of sample annotations. The dataframe index is taken as sample ids. All samples that appear in counts should \n    also appear in annotation, and vice versa. Mutation types are expect to be in COSMIC format (ex. A[C>A]A). \n    \n    Parameters\n    ----------\n    counts: pd.DataFrame\n        Nx96 dataframe of mutation counts, one sample per row. Index is assumed to be sample ids.\n    annotation: pd.DataFrame\n        NxF dataframe of meta-data features to annotate samples with. Index is assumed to be sample ids.\n\n    Examples\n    --------\n    >>> import pandas as pd\n    >>> counts = pd.read_csv('tests/test_data/pcawg_counts.csv', index_col = 0, header = 0)\n    >>> annotation = pd.read_csv('tests/test_data/pcawg_cancer_types.csv', index_col = 0, header = 0)\n    >>> pcawg = DataSet(counts, annotation)\n    >>> pcawg.nsamples\n    2778\n    \"\"\"\n\n    counts: pd.DataFrame\n    annotation: pd.DataFrame = None\n\n    def __post_init__(self):\n        if self.counts is not None:\n            assert self.counts.ndim == 2, f'Expected counts.ndim==2. Got {self.counts.ndim}'\n            assert self.counts.shape[1] == 96, f'Expected 96 mutation types, got {self.counts.shape[1]}'\n            assert all(self.counts.columns.isin(mut96)), 'Unexpected mutation type. Check the counts.columns are in COSMIC mutation type format (ex. A[C>A]A). See COSMIC database for more.'\n            # reorder columns if necessary\n            self.counts = self.counts[mut96]\n            \n        if self.annotation is not None:\n            # check the counts and annotation match\n            assert self.annotation.shape[0] == self.counts.shape[0], f\"Shape mismatch. Expected self.annotation.shape[0] == self.counts.shape[0], got {self.annotation.shape[0]}, {self.counts.shape[0]}\"\n            assert self.annotation.index.isin(self.counts.index).all() and self.counts.index.isin(self.annotation.index).all(), \"Counts and annotation indices must match\"\n\n    @property\n    def n_samples(self) -> int:\n        \"\"\"Number of samples in dataset\"\"\"\n        return self.counts.shape[0]\n    \n    @property\n    def ids(self) -> list:\n        \"\"\"List sample ids in dataset\"\"\"\n        return self.counts.index.to_list()\n    \n    def annotate_tissue_types(self, type_col) -> np.array:\n        \"\"\"Set a specified column of annotation as the sample tissue type\n        \n        Tissue type information is used by hirearchical models to create tissue-type prior.\n        See class:`HierarchicalTendemLda` for more details. \n        \"\"\"\n        if self.annotation is None:\n            raise ValueError('Dataset annotation must be provided.')\n        assert type_col in self.annotation.columns, f\"{type_col} not found in annotation columns. Check spelling?\"\n        self.tissue_types = pd.Categorical(self.annotation[type_col])\n        self.type_codes = self.tissue_types.codes\n\n    \n@dataclass\nclass SignatureSet:\n    \"\"\"Container for tabular data, allowing simple access to a set of mutational signature definitions. \n    \n    Parameters\n    ----------\n    signatures: pd.DataFrame\n        Nx96 dataframe of signautre definitions, one signature per row. Rows must sum to 1.\n        \n    Examples\n    ----------\n    \"\"\"\n    \n    signatures: pd.DataFrame\n    \n    def __post_init__(self):\n        # check for shape, valid signautre definitions\n        assert self.signatures.shape[1] == 96, f\"Expected 96 mutation types, got {self.signatures.shape[1]}\"\n        assert np.allclose(self.signatures.sum(1),1), \"All signature definitions must sum to 1\"\n        \n    @property\n    def n_sigs(self) -> int:\n        \"\"\"Number of signatures in dataset\"\"\"\n        return self.signatures.shape[0]\n    \n    @property\n    def damage_signatures(self) -> pd.DataFrame:\n        \"\"\"Damage signatures \n        \n        Damage signatures represent the distribution of mutations over 32 trinucleotide contexts. \n        They are computed by marginalizing over substitution classes. \n        \"\"\"\n        phi = get_phi(self.signatures.to_numpy())\n        return pd.DataFrame(phi, index = self.signatures.index, columns=mut32)\n        \n                \n    @property\n    def misrepair_signatures(self) -> pd.DataFrame:\n        \"\"\"Misrepair signatures \n        \n        Misrepair signatures represent the distribution of mutations over 6 substitution types. \n        They are computed by marginalizing over trinucleotide context classes. \n        \"\"\"\n        eta = get_eta(self.signatures.to_numpy())\n        return pd.DataFrame(eta, index = self.signatures.index, columns=mut6)\n    \n    def summarize_separation(self) -> pd.DataFrame:\n        \"\"\"Summary statistics of pair-wise cosine distances for signautres, \n        damage signatures, and misrepair signatures.\n        \n        \"\"\"\n        \n        seps = {'Signature separation': cosine_similarity(self.signatures)[np.triu_indices(self.n_sigs, k=1)],\n                'Damage signature separation': cosine_similarity(self.damage_signatures)[np.triu_indices(self.n_sigs, k=1)],\n                'Misrepair signature separation': cosine_similarity(self.misrepair_signatures)[np.triu_indices(self.n_sigs, k=1)]\n               }\n        \n        return pd.DataFrame.from_dict(seps).describe()\n    \nclass Model(ABC):\n    \"\"\"\n    Bayesian inference of mutational signautres and their activities.\n    \n    The Damuta class acts as a central interface for several types of latent models. Each subclass defines at least `build_model`, \n    `fit`, `predict_activities`, `model_to_gv` and metrics such as `LAP`, `ALP`, and `BOR` in addition to subclass-specific methods.\n    \n    Parameters\n    ----------\n    dataset : DataSet\n        Data for fitting.\n    opt_method: str \n        one of \"ADVI\" for mean field inference, or \"FullRankADVI\" for full rank inference.\n    seed : int\n        Random seed\n    \n    Attributes\n    ----------\n    model: pymc3.model.Model object\n        pymc3 model instance\n    approx: pymc3.variational.approximations object\n        pymc3 approximation object. Created via self.fit()\n     \"\"\"\n\n    def __init__(self, dataset: DataSet, opt_method: str, init_strategy: str, seed: int):\n        \n        if not isinstance(dataset, DataSet):\n            raise TypeError('Learner instance must be initialized with a DataSet object')\n\n        if not opt_method in _opt_methods.keys():\n            raise TypeError(f'Optimization method should be one of {list(_opt_methods.keys())}')\n        assert init_strategy in _init_strats, f'self.init_strategy should be one of {_init_strats}'\n        \n        self.dataset = dataset\n        self.opt_method = opt_method\n        self.init_strategy = init_strategy\n        self.seed = seed\n        self.model = None\n        self.approx = None\n        \n        # hidden attributes\n        self._model_kwargs = None\n        self._opt = _opt_methods[self.opt_method]\n        self._trace = None\n        self._hat = None\n        self._rng = np.random.default_rng(self.seed)\n        \n        # set seed\n        np.random.seed(self.seed)\n        pm.set_tt_rng(self.seed)\n\n    ################################################################################\n    # Model building and fitting\n    ################################################################################\n\n    @abstractmethod\n    def _build_model(self, *args, **kwargs):\n        \"\"\"Build the pymc3 model \n        \"\"\"\n        pass\n    \n    @abstractmethod\n    def _init_kmeans(self):\n        \"\"\"Defined by subclass\n        \"\"\"\n        pass\n    \n    @abstractmethod\n    def _initialize_signatures(self):\n        \"\"\"Defined by subclass.\n        \"\"\"\n        pass\n        \n\n    def fit(self, n, **pymc3_kwargs):\n        \"\"\"Fit model to the dataset specified by self.dataset\n        \n        Parameters \n        ----------\n        n: int\n            Number of iterations \n        **pymc3_kwargs:\n            More parameters to pass to pymc3.fit() (ex. callbacks)\n            \n        Returns\n        -------\n        self: :class:`Lda`\n        \"\"\"\n        \n        self._initialize_signatures()\n        self._build_model(**self._model_kwargs)\n        \n        with self.model:\n            self._trace = self._opt(random_seed = self.seed)\n            self._trace.fit(n=n, **pymc3_kwargs)\n        \n        self.approx = self._trace.approx\n        \n        return self\n    \n    #@abstractmethod\n    #def predict_activites(self, new_data, *args, **kwargs):\n    #    \"\"\"Defined by subclass\n    #    \"\"\"\n    #    pass\n    \n\n    #def model_to_gv(self, *args, **kwargs):\n    #    \"\"\"Defined by subclass\n    #    \"\"\"\n    #    pass\n\n    \n    ################################################################################\n    # Metrics\n    ################################################################################\n\n    @abstractmethod\n    def BOR(self, *args, **kwargs):\n        \"\"\"Defined by subclass\n        \"\"\"\n        pass\n    \n    def ALP(self, n_samples = 20):\n        \"\"\"Average log probability per mutation \n        \"\"\"\n        if self.approx is None:\n            warnings.warn(\"self.approx is None... Fit the model first!\", ValueError)\n        \n        B = self.approx.sample(n_samples).B.mean(0)\n        return alp_B(self.dataset.counts.to_numpy(), B)\n\n    \n    def LAP(self, n_samples = 20):\n        \"\"\"Log average data likelihood (bayesian version of reconstruction error)\n        \"\"\"\n        if self.approx is None:\n            warnings.warn(\"self.trace is None... Fit the model first!\", ValueError)\n        \n        B = self.approx.sample(n_samples).B.mean(0)\n        return alp_B(self.dataset.counts.to_numpy(), B)\n    \n    def reconstruction_err(self, *args, **kwargs):\n        \"\"\"Defined by subclass\n        \"\"\"\n        pass\n    \n\n", "meta": {"hexsha": "6bc90d13a4264148cfccf8365f6ccf5d9c2df50a", "size": 10262, "ext": "py", "lang": "Python", "max_stars_repo_path": "damuta/base.py", "max_stars_repo_name": "morrislab/damuta", "max_stars_repo_head_hexsha": "48e3146b610397e1c3020b26f0d010b38901452b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-02T19:56:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T19:15:48.000Z", "max_issues_repo_path": "damuta/base.py", "max_issues_repo_name": "morrislab/damuta", "max_issues_repo_head_hexsha": "48e3146b610397e1c3020b26f0d010b38901452b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "damuta/base.py", "max_forks_repo_name": "morrislab/damuta", "max_forks_repo_head_hexsha": "48e3146b610397e1c3020b26f0d010b38901452b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-29T01:13:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T01:13:51.000Z", "avg_line_length": 36.0070175439, "max_line_length": 201, "alphanum_fraction": 0.6066068992, "include": true, "reason": "import numpy,import pymc3", "num_tokens": 2243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3593641314378279, "lm_q1q2_score": 0.186697328626746}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n__author__ = \"Christian Heider Nielsen\"\n__doc__ = r\"\"\"\n\n           Created on 22/03/2020\n           \"\"\"\n\nimport itertools\nimport logging\nimport os\nfrom collections import defaultdict\nfrom datetime import datetime\nfrom typing import Tuple\n\nimport numpy\nimport six\n\n__all__ = [\n    \"bbox_iou\",\n    \"eval_detection_voc\",\n    \"calc_detection_voc_ap\",\n    \"calc_detection_voc_prec_rec\",\n    \"voc_evaluation\",\n]\n\n\ndef bbox_iou(bbox_a: numpy.ndarray, bbox_b: numpy.ndarray) -> numpy.ndarray:\n    \"\"\"Calculate the Intersection of Unions (IoUs) between bounding boxes.\nIoU is calculated as a ratio of area of the intersection\nand area of the union.\nThis function accepts both :obj:`numpy.ndarray` and :obj:`cupy.ndarray` as\ninputs. Please note that both :obj:`bbox_a` and :obj:`bbox_b` need to be\nsame type.\nThe output is same type as the type of the inputs.\nArgs:\nbbox_a (array): An array whose shape is :math:`(N, 4)`.\n  :math:`N` is the number of bounding boxes.\n  The dtype should be :obj:`numpy.float32`.\nbbox_b (array): An array similar to :obj:`bbox_a`,\n  whose shape is :math:`(K, 4)`.\n  The dtype should be :obj:`numpy.float32`.\nReturns:\narray:\nAn array whose shape is :math:`(N, K)`. \\\nAn element at index :math:`(n, k)` contains IoUs between \\\n:math:`n` th bounding box in :obj:`bbox_a` and :math:`k` th bounding \\\nbox in :obj:`bbox_b`.\n\"\"\"\n    if bbox_a.shape[1] != 4 or bbox_b.shape[1] != 4:\n        raise IndexError\n\n    # top left\n    tl = numpy.maximum(bbox_a[:, None, :2], bbox_b[:, :2])\n    # bottom right\n    br = numpy.minimum(bbox_a[:, None, 2:], bbox_b[:, 2:])\n\n    area_i = numpy.prod(br - tl, axis=2) * (tl < br).all(axis=2)\n    area_a = numpy.prod(bbox_a[:, 2:] - bbox_a[:, :2], axis=1)\n    area_b = numpy.prod(bbox_b[:, 2:] - bbox_b[:, :2], axis=1)\n    return area_i / (area_a[:, None] + area_b - area_i)\n\n\ndef eval_detection_voc(\n    pred_bboxes,\n    pred_labels,\n    pred_scores,\n    gt_bboxes,\n    gt_labels,\n    gt_difficults=None,\n    iou_thresh=0.5,\n    use_07_metric=False,\n) -> Tuple:\n    \"\"\"Calculate average precisions based on evaluation code of PASCAL VOC.\n\nThis function evaluates predicted bounding boxes obtained from a dataset\nwhich has :math:`N` images by using average precision for each class.\nThe code is based on the evaluation code used in PASCAL VOC Challenge.\n\nArgs:\npred_bboxes (iterable of numpy.ndarray): An iterable of :math:`N`\n  sets of bounding boxes.\n  Its index corresponds to an index for the base dataset.\n  Each element of :obj:`pred_bboxes` is a set of coordinates\n  of bounding boxes. This is an array whose shape is :math:`(R, 4)`,\n  where :math:`R` corresponds\n  to the number of bounding boxes, which may vary among boxes.\n  The second axis corresponds to\n  :math:`y_{min}, x_{min}, y_{max}, x_{max}` of a bounding box.\npred_labels (iterable of numpy.ndarray): An iterable of labels.\n  Similar to :obj:`pred_bboxes`, its index corresponds to an\n  index for the base dataset. Its length is :math:`N`.\npred_scores (iterable of numpy.ndarray): An iterable of confidence\n  scores for predicted bounding boxes. Similar to :obj:`pred_bboxes`,\n  its index corresponds to an index for the base dataset.\n  Its length is :math:`N`.\ngt_bboxes (iterable of numpy.ndarray): An iterable of ground truth\n  bounding boxes\n  whose length is :math:`N`. An element of :obj:`gt_bboxes` is a\n  bounding box whose shape is :math:`(R, 4)`. Note that the number of\n  bounding boxes in each image does not need to be same as the number\n  of corresponding predicted boxes.\ngt_labels (iterable of numpy.ndarray): An iterable of ground truth\n  labels which are organized similarly to :obj:`gt_bboxes`.\ngt_difficults (iterable of numpy.ndarray): An iterable of boolean\n  arrays which is organized similarly to :obj:`gt_bboxes`.\n  This tells whether the\n  corresponding ground truth bounding box is difficult or not.\n  By default, this is :obj:`None`. In that case, this function\n  considers all bounding boxes to be not difficult.\niou_thresh (float): A prediction is correct if its Intersection over\n  Union with the ground truth is above this value.\nuse_07_metric (bool): Whether to use PASCAL VOC 2007 evaluation metric\n  for calculating average precision. The default value is\n  :obj:`False`.\n\nReturns:\ndict:\n\nThe keys, value-types and the description of the values are listed\nbelow.\n\n* **ap** (*numpy.ndarray*): An array of average precisions. \\\n  The :math:`l`-th value corresponds to the average precision \\\n  for class :math:`l`. If class :math:`l` does not exist in \\\n  either :obj:`pred_labels` or :obj:`gt_labels`, the corresponding \\\n  value is set to :obj:`numpy.nan`.\n* **map** (*float*): The mean of Average Precisions over classes.\n\n\"\"\"\n\n    prec, rec = calc_detection_voc_prec_rec(\n        pred_bboxes,\n        pred_labels,\n        pred_scores,\n        gt_bboxes,\n        gt_labels,\n        gt_difficults,\n        iou_thresh=iou_thresh,\n    )\n\n    ap = calc_detection_voc_ap(prec, rec, use_07_metric=use_07_metric)\n\n    return ap, numpy.nanmean(ap)  # Mean Average Precision\n\n\ndef calc_detection_voc_prec_rec(\n    pred_bboxes,\n    pred_labels,\n    pred_scores,\n    gt_bboxes,\n    gt_labels,\n    gt_difficults=None,\n    iou_thresh: float = 0.5,\n) -> Tuple:\n    \"\"\"Calculate precision and recall based on evaluation code of PASCAL VOC.\n\nThis function calculates precision and recall of\npredicted bounding boxes obtained from a dataset which has :math:`N`\nimages.\nThe code is based on the evaluation code used in PASCAL VOC Challenge.\n\nArgs:\npred_bboxes (iterable of numpy.ndarray): An iterable of :math:`N`\n  sets of bounding boxes.\n  Its index corresponds to an index for the base dataset.\n  Each element of :obj:`pred_bboxes` is a set of coordinates\n  of bounding boxes. This is an array whose shape is :math:`(R, 4)`,\n  where :math:`R` corresponds\n  to the number of bounding boxes, which may vary among boxes.\n  The second axis corresponds to\n  :math:`y_{min}, x_{min}, y_{max}, x_{max}` of a bounding box.\npred_labels (iterable of numpy.ndarray): An iterable of labels.\n  Similar to :obj:`pred_bboxes`, its index corresponds to an\n  index for the base dataset. Its length is :math:`N`.\npred_scores (iterable of numpy.ndarray): An iterable of confidence\n  scores for predicted bounding boxes. Similar to :obj:`pred_bboxes`,\n  its index corresponds to an index for the base dataset.\n  Its length is :math:`N`.\ngt_bboxes (iterable of numpy.ndarray): An iterable of ground truth\n  bounding boxes\n  whose length is :math:`N`. An element of :obj:`gt_bboxes` is a\n  bounding box whose shape is :math:`(R, 4)`. Note that the number of\n  bounding boxes in each image does not need to be same as the number\n  of corresponding predicted boxes.\ngt_labels (iterable of numpy.ndarray): An iterable of ground truth\n  labels which are organized similarly to :obj:`gt_bboxes`.\ngt_difficults (iterable of numpy.ndarray): An iterable of boolean\n  arrays which is organized similarly to :obj:`gt_bboxes`.\n  This tells whether the\n  corresponding ground truth bounding box is difficult or not.\n  By default, this is :obj:`None`. In that case, this function\n  considers all bounding boxes to be not difficult.\niou_thresh (float): A prediction is correct if its Intersection over\n  Union with the ground truth is above this value..\n\nReturns:\ntuple of two lists:\nThis function returns two lists: :obj:`prec` and :obj:`rec`.\n\n* :obj:`prec`: A list of arrays. :obj:`prec[l]` is precision \\\n  for class :math:`l`. If class :math:`l` does not exist in \\\n  either :obj:`pred_labels` or :obj:`gt_labels`, :obj:`prec[l]` is \\\n  set to :obj:`None`.\n* :obj:`rec`: A list of arrays. :obj:`rec[l]` is recall \\\n  for class :math:`l`. If class :math:`l` that is not marked as \\\n  difficult does not exist in \\\n  :obj:`gt_labels`, :obj:`rec[l]` is \\\n  set to :obj:`None`.\n\n\"\"\"\n\n    pred_bboxes = iter(pred_bboxes)\n    pred_labels = iter(pred_labels)\n    pred_scores = iter(pred_scores)\n    gt_bboxes = iter(gt_bboxes)\n    gt_labels = iter(gt_labels)\n    if gt_difficults is None:\n        gt_difficults = itertools.repeat(None)\n    else:\n        gt_difficults = iter(gt_difficults)\n\n    n_pos = defaultdict(int)\n    score = defaultdict(list)\n    match = defaultdict(list)\n\n    for (\n        pred_bbox,\n        pred_label,\n        pred_score,\n        gt_bbox,\n        gt_label,\n        gt_difficult,\n    ) in six.moves.zip(\n        pred_bboxes, pred_labels, pred_scores, gt_bboxes, gt_labels, gt_difficults\n    ):\n\n        if gt_difficult is None:\n            gt_difficult = numpy.zeros(gt_bbox.shape[0], dtype=bool)\n\n        for l in numpy.unique(numpy.concatenate((pred_label, gt_label)).astype(int)):\n            pred_mask_l = pred_label == l\n            pred_bbox_l = pred_bbox[pred_mask_l]\n            pred_score_l = pred_score[pred_mask_l]\n            # sort by score\n            order = pred_score_l.argsort()[::-1]\n            pred_bbox_l = pred_bbox_l[order]\n            pred_score_l = pred_score_l[order]\n\n            gt_mask_l = gt_label == l\n            gt_bbox_l = gt_bbox[gt_mask_l]\n            gt_difficult_l = gt_difficult[gt_mask_l]\n\n            n_pos[l] += numpy.logical_not(gt_difficult_l).sum()\n            score[l].extend(pred_score_l)\n\n            if len(pred_bbox_l) == 0:\n                continue\n            if len(gt_bbox_l) == 0:\n                match[l].extend((0,) * pred_bbox_l.shape[0])\n                continue\n\n            # VOC evaluation follows integer typed bounding boxes.\n            pred_bbox_l = pred_bbox_l.copy()\n            pred_bbox_l[:, 2:] += 1\n            gt_bbox_l = gt_bbox_l.copy()\n            gt_bbox_l[:, 2:] += 1\n\n            iou = bbox_iou(pred_bbox_l, gt_bbox_l)\n            gt_index = iou.argmax(axis=1)\n            # set -1 if there is no matching ground truth\n            gt_index[iou.max(axis=1) < iou_thresh] = -1\n            del iou\n\n            selec = numpy.zeros(gt_bbox_l.shape[0], dtype=bool)\n            for gt_idx in gt_index:\n                if gt_idx >= 0:\n                    if gt_difficult_l[gt_idx]:\n                        match[l].append(-1)\n                    else:\n                        if not selec[gt_idx]:\n                            match[l].append(1)\n                        else:\n                            match[l].append(0)\n                    selec[gt_idx] = True\n                else:\n                    match[l].append(0)\n\n    for iter_ in (\n        pred_bboxes,\n        pred_labels,\n        pred_scores,\n        gt_bboxes,\n        gt_labels,\n        gt_difficults,\n    ):\n        if next(iter_, None) is not None:\n            raise ValueError(\"Length of input iterables need to be same.\")\n\n    n_fg_class = max(n_pos.keys()) + 1\n    prec = [None] * n_fg_class\n    rec = [None] * n_fg_class\n\n    for l in n_pos.keys():\n        score_l = numpy.array(score[l])\n        match_l = numpy.array(match[l], dtype=numpy.int8)\n\n        order = score_l.argsort()[::-1]\n        match_l = match_l[order]\n\n        tp = numpy.cumsum(match_l == 1)\n        fp = numpy.cumsum(match_l == 0)\n\n        # If an element of fp + tp is 0,\n        # the corresponding element of prec[l] is nan.\n        prec[l] = tp / (fp + tp)\n        # If n_pos[l] is 0, rec[l] is None.\n        if n_pos[l] > 0:\n            rec[l] = tp / n_pos[l]\n\n    return prec, rec\n\n\ndef calc_detection_voc_ap(prec, rec, use_07_metric=False):\n    \"\"\"Calculate average precisions based on evaluation code of PASCAL VOC.\n\nThis function calculates average precisions\nfrom given precisions and recalls.\nThe code is based on the evaluation code used in PASCAL VOC Challenge.\n\nArgs:\nprec (list of numpy.array): A list of arrays.\n  :obj:`prec[l]` indicates precision for class :math:`l`.\n  If :obj:`prec[l]` is :obj:`None`, this function returns\n  :obj:`numpy.nan` for class :math:`l`.\nrec (list of numpy.array): A list of arrays.\n  :obj:`rec[l]` indicates recall for class :math:`l`.\n  If :obj:`rec[l]` is :obj:`None`, this function returns\n  :obj:`numpy.nan` for class :math:`l`.\nuse_07_metric (bool): Whether to use PASCAL VOC 2007 evaluation metric\n  for calculating average precision. The default value is\n  :obj:`False`.\n\nReturns:\n~numpy.ndarray:\nThis function returns an array of average precisions.\nThe :math:`l`-th value corresponds to the average precision\nfor class :math:`l`. If :obj:`prec[l]` or :obj:`rec[l]` is\n:obj:`None`, the corresponding value is set to :obj:`numpy.nan`.\n\n\"\"\"\n\n    n_fg_class = len(prec)\n    ap = numpy.empty(n_fg_class)\n    for l in six.moves.range(n_fg_class):\n        if prec[l] is None or rec[l] is None:\n            ap[l] = numpy.nan\n            continue\n\n        if use_07_metric:\n            # 11 point metric\n            ap[l] = 0\n            for t in numpy.arange(0.0, 1.1, 0.1):\n                if numpy.sum(rec[l] >= t) == 0:\n                    p = 0\n                else:\n                    p = numpy.max(numpy.nan_to_num(prec[l])[rec[l] >= t])\n                ap[l] += p / 11\n        else:\n            # correct AP calculation\n            # first append sentinel values at the end\n            mpre = numpy.concatenate(([0], numpy.nan_to_num(prec[l]), [0]))\n            mrec = numpy.concatenate(([0], rec[l], [1]))\n\n            mpre = numpy.maximum.accumulate(mpre[::-1])[::-1]\n\n            # to calculate area under PR curve, look for points\n            # where X axis (recall) changes value\n            i = numpy.where(mrec[1:] != mrec[:-1])[0]\n\n            # and sum (\\Delta recall) * prec\n            ap[l] = numpy.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n\n    return ap\n\n\ndef voc_evaluation(dataset, predictions, output_dir, iteration=None):\n    class_names = dataset.class_names\n\n    pred_boxes_list = []\n    pred_labels_list = []\n    pred_scores_list = []\n    gt_boxes_list = []\n    gt_labels_list = []\n    gt_difficults = []\n\n    for i in range(len(dataset)):\n        image_id, annotation = dataset.get_annotation(i)\n        gt_boxes, gt_labels, is_difficult = annotation\n        gt_boxes_list.append(gt_boxes)\n        gt_labels_list.append(gt_labels)\n        gt_difficults.append(is_difficult.astype(numpy.bool))\n\n        img_info = dataset.get_img_info(i)\n        prediction = predictions[i]\n        prediction = prediction.resize((img_info[\"width\"], img_info[\"height\"])).numpy()\n        boxes, labels, scores = (\n            prediction[\"boxes\"],\n            prediction[\"labels\"],\n            prediction[\"scores\"],\n        )\n\n        pred_boxes_list.append(boxes)\n        pred_labels_list.append(labels)\n        pred_scores_list.append(scores)\n    ap, map = eval_detection_voc(\n        pred_bboxes=pred_boxes_list,\n        pred_labels=pred_labels_list,\n        pred_scores=pred_scores_list,\n        gt_bboxes=gt_boxes_list,\n        gt_labels=gt_labels_list,\n        gt_difficults=gt_difficults,\n        iou_thresh=0.5,\n        use_07_metric=True,\n    )\n    logger = logging.getLogger(\"SSD.inference\")\n    result_str = f\"mAP: {map:.4f}\\n\"\n    metrics = {\"mAP\": map}\n    for i, ap in enumerate(ap):\n        if i == 0:  # skip background\n            continue\n        metrics[class_names[i]] = ap\n        result_str += f\"{class_names[i]:<16}: {ap:.4f}\\n\"\n    logger.info(result_str)\n\n    if iteration is not None:\n        result_path = os.path.join(output_dir, f\"result_{iteration:07d}.txt\")\n    else:\n        result_path = os.path.join(\n            output_dir, f'result_{datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")}.txt'\n        )\n    with open(result_path, \"w\") as f:\n        f.write(result_str)\n\n    return dict(metrics=metrics)\n", "meta": {"hexsha": "5db8943d0b49ee74f4881d2b1f178a94354d3825", "size": 15481, "ext": "py", "lang": "Python", "max_stars_repo_path": "neodroidvision/data/detection/voc/voc_evaluation.py", "max_stars_repo_name": "sintefneodroid/vision", "max_stars_repo_head_hexsha": "a4e66251ead99f15f4697bfe2abd00e2f388e743", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "neodroidvision/data/detection/voc/voc_evaluation.py", "max_issues_repo_name": "sintefneodroid/vision", "max_issues_repo_head_hexsha": "a4e66251ead99f15f4697bfe2abd00e2f388e743", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-12T01:08:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T01:08:08.000Z", "max_forks_repo_path": "neodroidvision/data/detection/voc/voc_evaluation.py", "max_forks_repo_name": "sintefneodroid/vision", "max_forks_repo_head_hexsha": "a4e66251ead99f15f4697bfe2abd00e2f388e743", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6331096197, "max_line_length": 87, "alphanum_fraction": 0.6444674117, "include": true, "reason": "import numpy", "num_tokens": 4002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.18655947130844946}}
{"text": "# *******************************************************************************\n# Copyright (C) 2020 INAF\n#\n# This software is distributed under the terms of the BSD-3-Clause license\n#\n# Authors:\n# Ambra Di Piano <ambra.dipiano@inaf.it>\n# *******************************************************************************\n\nimport time\nimport sys\nimport os\ntexp = sys.argv[1]\nfirst = sys.argv[2]\n\n# start timing\nt = time.time()\nclock0 = time.time()\n#from astropy.coordinates import SkyCoord\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\nfrom gammapy.analysis import Analysis, AnalysisConfig\nfrom gammapy.data import EventList, GTI, Observation, Observations\nfrom gammapy.irf import load_cta_irfs\nfrom gammapy.modeling import Fit\nfrom gammapy.modeling.models import PowerLawSpectralModel, SkyModel, PointSpatialModel\ntimport = time.time() - t\nprint(f'Imports : {timport} s\\n')\n\nt = time.time()\nrootpath = str(os.path.dirname(os.path.abspath(__file__))).replace('cta-sag-sci/RTAscience/timing', '')\ncaldb = f'{rootpath}/caldb/data/cta/prod3b-v2/bcf/South_z20_0.5h/irf_file.fits'\nirfs = load_cta_irfs(caldb)\nfilename = f'{rootpath}/DATA/obs/crab/crab_offax_texp{texp}s_n01.fits'\nobs_id = 1\nprint(f'Fits: {filename.replace(rootpath, \"\")}\\n')\ntsetup = time.time() - t\nprint(f'Setup : {tsetup} s\\n')\n\n# read phlist\nt = time.time()\nevents = EventList.read(filename, hdu='EVENTS')\n# get GTI\ngti = GTI.read(filename, hdu='GTI')\n# get pointing\npointing = events.pointing_radec\n# create observation\nobservation = Observation.create(\n    pointing=pointing, obs_id=f'{obs_id:02d}', tstart=gti.table['START'] * u.s, \n    tstop=gti.table['STOP'] * u.s, irfs=irfs, reference_time=gti.time_ref)\nobservation._events = events\n#print(observation.gti)\nobservations = Observations() \nobservations.append(observation)\n# fix pointing info\nobservation.fixed_pointing_info\n# target\n#target = SkyCoord(pointing.ra, pointing.dec - 0.5 * u.deg, unit='deg', frame='icrs')\ntarget = {'ra': 83.6331, 'dec': 22.0145}\ntobs = time.time() - t\nprint(f'Create observation : {tobs} s\\n')\n\n# configure a 1d analysis\nt = time.time()\nconfig_1d = AnalysisConfig()\nconfig_1d.general.log = {'level': 'warning'}\nconfig_1d.datasets.type = \"1d\"\nconfig_1d.datasets.stack = False\n# define the ON region and make sure that PSF leakage is corrected\nconfig_1d.datasets.on_region = dict(frame=\"icrs\", lon='%s deg' %target['ra'], lat='%s deg' %target['dec'], radius='0.1 deg')\nconfig_1d.datasets.containment_correction = True\n# background\nconfig_1d.datasets.background=dict(method=\"reflected\", exclusion=None)\n#config_1d.datasets.safe_mask.methods = [\"edisp-bias\"]\n# define the energy binning for the spectra\nconfig_1d.datasets.geom.axes.energy = dict(min='0.05 TeV', max='20 TeV', nbins=30)\nconfig_1d.datasets.geom.axes.energy_true = dict(min='0.03 TeV', max='30 TeV', nbins=40)\nconfig_1d.datasets.geom.selection.offset_max = '2.5 deg'\n# fit\n#config_1d.fit.fit_range = dict(min='0.03 TeV', max='30 TeV')\n#config_1d.flux_points.energy = dict(min='0.03 TeV', max='30 TeV', nbins=3)\n#config_1d.flux_points.source = 'Crab'\n# write\n#config_1d.write(\"config1d.yaml\", overwrite=True)\n#config_1d = AnalysisConfig.read(\"config1d.yaml\")\ntconf = time.time() - t\nprint(f'Configuration : {tconf} s\\n')\nprint(target)\n# instantiate data reduction passing directly the config object\nt = time.time()\nanalysis_1d = Analysis(config_1d)\nanalysis_1d.observations = observations\nanalysis_1d.get_datasets()\ntred = time.time() - t\nprint(f'Data Reduction : {tred} s\\n')\n\n# statistics\nt = time.time()\nstats = analysis_1d.datasets.info_table()\nprint(stats['sqrt_ts'], '\\n')\ntstat = time.time() - t\nprint(f'Statistics : {tstat} s\\n')\n\n# prepare models\nt = time.time()\nstacked_1d = analysis_1d.datasets.stack_reduce(name=\"stacked\")\ntarget = SkyCoord(target['ra'], target['dec'], unit='deg', frame='icrs')\nspatial_model = PointSpatialModel(lon_0=target.ra, lat_0=target.dec, frame=\"icrs\")\nspectral_model = PowerLawSpectralModel(index=2.48, amplitude=2e-12 * u.Unit(\"1 / (cm2 s TeV)\"))\nspectral_model.parameters['index'].frozen = True\nspatial_model.parameters['lon_0'].frozen = True\nspatial_model.parameters['lat_0'].frozen = True\nsky_model = SkyModel(spatial_model=spatial_model, spectral_model=spectral_model, name=\"Crab\")\nstacked_1d.models = sky_model\ntmodel = time.time() - t\nprint(f'Modelling : {tmodel} s\\n')\n\n# fitting\nt = time.time()\nfit_1d = Fit([stacked_1d])\nresult_1d = fit_1d.run()\n#print(result_1d.parameters.to_table(), '\\n')\ntfit = time.time() - t\nprint(f'Fitting : {tfit} s\\n')\n\n# flux\nt = time.time()\nphflux_err = spectral_model.integral_error(0.05 * u.TeV, 20 * u.TeV)\nprint(f'\\nPH-FLUX {phflux_err.value[0]} +/- {phflux_err.value[1]}')\ntflux = time.time() - t\nprint(f'\\nFlux : {tflux} s\\n')\n\nttotal = time.time() - clock0\nprint(f'Total time: {ttotal} s\\n')\nprint('\\n\\n-----------------------------------------------------\\n\\n')\n\nlogname = f'{rootpath}/DATA/outputs/crab/gammapy1d_binned_fit.csv'\nrow = f'{texp} {stats[\"sqrt_ts\"][0]} {phflux_err.value[0]} {phflux_err.value[1]} {ttotal} {timport} {tsetup} {tconf} {tred} {tstat} {tmodel} {tfit} {tflux}\\n'\nif first == 'True':\n    hdr = 'texp sqrt_ts flux flux_err ttotal timport tsetup tobs tconf tred tstat tmodel tfit tflux\\n'\n    log = open(logname, 'w+')\n    log.write(hdr)\n    log.write(row)\n    log.close()\nelse:\n    log = open(logname, 'a')\n    log.write(row)\n    log.close()\n\nprint (row)", "meta": {"hexsha": "e73d0b1e1be3d5c88fe5e7cc6255013f16df5f54", "size": 5401, "ext": "py", "lang": "Python", "max_stars_repo_path": "RTAscience/timing/time_gammapy1d_binned_fit.py", "max_stars_repo_name": "ambra-dipiano/cta-sag-sci", "max_stars_repo_head_hexsha": "f2e238c323d35badd477ce4030069a0097d550bb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-29T15:17:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-29T15:17:31.000Z", "max_issues_repo_path": "RTAscience/timing/time_gammapy1d_binned_fit.py", "max_issues_repo_name": "ambra-dipiano/cta-sag-sci", "max_issues_repo_head_hexsha": "f2e238c323d35badd477ce4030069a0097d550bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-03-17T09:10:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T16:43:15.000Z", "max_forks_repo_path": "RTAscience/timing/time_gammapy1d_binned_fit.py", "max_forks_repo_name": "ambra-dipiano/cta-sag-sci", "max_forks_repo_head_hexsha": "f2e238c323d35badd477ce4030069a0097d550bb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0066666667, "max_line_length": 158, "alphanum_fraction": 0.6967228291, "include": true, "reason": "from astropy", "num_tokens": 1638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1865594640655067}}
{"text": "import operator\r\n\r\nimport numpy as np\r\nimport numpy.core.umath_tests as ut\r\n\r\nfrom Quaternions import Quaternions\r\n\r\nclass Animation:\r\n    \"\"\"\r\n    Animation is a numpy-like wrapper for animation data\r\n    \r\n    Animation data consists of several arrays consisting\r\n    of F frames and J joints.\r\n    \r\n    The animation is specified by\r\n    \r\n        rotations : (F, J) Quaternions | Joint Rotations\r\n        positions : (F, J, 3) ndarray  | Joint Positions\r\n    \r\n    The base pose is specified by\r\n    \r\n        orients   : (J) Quaternions    | Joint Orientations\r\n        offsets   : (J, 3) ndarray     | Joint Offsets\r\n        \r\n    And the skeletal structure is specified by\r\n        \r\n        parents   : (J) ndarray        | Joint Parents\r\n    \"\"\"\r\n    \r\n    def __init__(self, rotations, positions, orients, offsets, parents):\r\n        \r\n        self.rotations = rotations\r\n        self.positions = positions\r\n        self.orients   = orients\r\n        self.offsets   = offsets\r\n        self.parents   = parents\r\n    \r\n    def __op__(self, op, other):\r\n        return Animation(\r\n            op(self.rotations, other.rotations),\r\n            op(self.positions, other.positions),\r\n            op(self.orients, other.orients),\r\n            op(self.offsets, other.offsets),\r\n            op(self.parents, other.parents))\r\n\r\n    def __iop__(self, op, other):\r\n        self.rotations = op(self.roations, other.rotations)\r\n        self.positions = op(self.roations, other.positions)\r\n        self.orients   = op(self.orients, other.orients)\r\n        self.offsets   = op(self.offsets, other.offsets)\r\n        self.parents   = op(self.parents, other.parents)\r\n        return self\r\n    \r\n    def __sop__(self, op):\r\n        return Animation(\r\n            op(self.rotations),\r\n            op(self.positions),\r\n            op(self.orients),\r\n            op(self.offsets),\r\n            op(self.parents))\r\n    \r\n    def __add__(self, other): return self.__op__(operator.add, other)\r\n    def __sub__(self, other): return self.__op__(operator.sub, other)\r\n    def __mul__(self, other): return self.__op__(operator.mul, other)\r\n    def __div__(self, other): return self.__op__(operator.div, other)\r\n    \r\n    def __abs__(self): return self.__sop__(operator.abs)\r\n    def __neg__(self): return self.__sop__(operator.neg)\r\n    \r\n    def __iadd__(self, other): return self.__iop__(operator.iadd, other)\r\n    def __isub__(self, other): return self.__iop__(operator.isub, other)\r\n    def __imul__(self, other): return self.__iop__(operator.imul, other)\r\n    def __idiv__(self, other): return self.__iop__(operator.idiv, other)\r\n    \r\n    def __len__(self): return len(self.rotations)\r\n    \r\n    def __getitem__(self, k):\r\n        if isinstance(k, tuple):\r\n            return Animation(\r\n                self.rotations[k],\r\n                self.positions[k],\r\n                self.orients[k[1:]],\r\n                self.offsets[k[1:]],\r\n                self.parents[k[1:]]) \r\n        else:\r\n            return Animation(\r\n                self.rotations[k],\r\n                self.positions[k],\r\n                self.orients,\r\n                self.offsets,\r\n                self.parents) \r\n        \r\n    def __setitem__(self, k, v): \r\n        if isinstance(k, tuple):\r\n            self.rotations.__setitem__(k, v.rotations)\r\n            self.positions.__setitem__(k, v.positions)\r\n            self.orients.__setitem__(k[1:], v.orients)\r\n            self.offsets.__setitem__(k[1:], v.offsets)\r\n            self.parents.__setitem__(k[1:], v.parents)\r\n        else:\r\n            self.rotations.__setitem__(k, v.rotations)\r\n            self.positions.__setitem__(k, v.positions)\r\n            self.orients.__setitem__(k, v.orients)\r\n            self.offsets.__setitem__(k, v.offsets)\r\n            self.parents.__setitem__(k, v.parents)\r\n        \r\n    @property\r\n    def shape(self): return (self.rotations.shape[0], self.rotations.shape[1])\r\n            \r\n    def copy(self): return Animation(\r\n        self.rotations.copy(), self.positions.copy(), \r\n        self.orients.copy(), self.offsets.copy(), \r\n        self.parents.copy())\r\n    \r\n    def repeat(self, *args, **kw):\r\n        return Animation(\r\n            self.rotations.repeat(*args, **kw),\r\n            self.positions.repeat(*args, **kw),\r\n            self.orients, self.offsets, self.parents)\r\n        \r\n    def ravel(self):\r\n        return np.hstack([\r\n            self.rotations.log().ravel(),\r\n            self.positions.ravel(),\r\n            self.orients.log().ravel(),\r\n            self.offsets.ravel()])\r\n        \r\n    @classmethod\r\n    def unravel(clas, anim, shape, parents):\r\n        nf, nj = shape\r\n        rotations = anim[nf*nj*0:nf*nj*3]\r\n        positions = anim[nf*nj*3:nf*nj*6]\r\n        orients   = anim[nf*nj*6+nj*0:nf*nj*6+nj*3]\r\n        offsets   = anim[nf*nj*6+nj*3:nf*nj*6+nj*6]\r\n        return cls(\r\n            Quaternions.exp(rotations), positions,\r\n            Quaternions.exp(orients), offsets,\r\n            parents.copy())\r\n    \r\n    \r\n\r\n    \r\ndef transforms_local(anim):\r\n    \"\"\"\r\n    Computes Animation Local Transforms\r\n    \r\n    As well as a number of other uses this can\r\n    be used to compute global joint transforms,\r\n    which in turn can be used to compete global\r\n    joint positions\r\n    \r\n    Parameters\r\n    ----------\r\n    \r\n    anim : Animation\r\n        Input animation\r\n        \r\n    Returns\r\n    -------\r\n    \r\n    transforms : (F, J, 4, 4) ndarray\r\n    \r\n        For each frame F, joint local\r\n        transforms for each joint J\r\n    \"\"\"\r\n    \r\n    transforms = anim.rotations.transforms()\r\n    transforms = np.concatenate([transforms, np.zeros(transforms.shape[:2] + (3, 1))], axis=-1)\r\n    transforms = np.concatenate([transforms, np.zeros(transforms.shape[:2] + (1, 4))], axis=-2)\r\n    transforms[:,:,0:3,3] = anim.positions\r\n    transforms[:,:,3:4,3] = 1.0\r\n    return transforms\r\n\r\n    \r\ndef transforms_multiply(t0s, t1s):\r\n    \"\"\"\r\n    Transforms Multiply\r\n    \r\n    Multiplies two arrays of animation transforms\r\n    \r\n    Parameters\r\n    ----------\r\n    \r\n    t0s, t1s : (F, J, 4, 4) ndarray\r\n        Two arrays of transforms\r\n        for each frame F and each\r\n        joint J\r\n        \r\n    Returns\r\n    -------\r\n    \r\n    transforms : (F, J, 4, 4) ndarray\r\n        Array of transforms for each\r\n        frame F and joint J multiplied\r\n        together\r\n    \"\"\"\r\n    \r\n    return ut.matrix_multiply(t0s, t1s)\r\n    \r\ndef transforms_inv(ts):\r\n    fts = ts.reshape(-1, 4, 4)\r\n    fts = np.array(list(map(lambda x: np.linalg.inv(x), fts)))\r\n    return fts.reshape(ts.shape)\r\n    \r\ndef transforms_blank(anim):\r\n    \"\"\"\r\n    Blank Transforms\r\n    \r\n    Parameters\r\n    ----------\r\n    \r\n    anim : Animation\r\n        Input animation\r\n    \r\n    Returns\r\n    -------\r\n    \r\n    transforms : (F, J, 4, 4) ndarray\r\n        Array of identity transforms for \r\n        each frame F and joint J\r\n    \"\"\"\r\n\r\n    ts = np.zeros(anim.shape + (4, 4)) \r\n    ts[:,:,0,0] = 1.0; ts[:,:,1,1] = 1.0;\r\n    ts[:,:,2,2] = 1.0; ts[:,:,3,3] = 1.0;\r\n    return ts\r\n    \r\ndef transforms_global(anim):\r\n    \"\"\"\r\n    Global Animation Transforms\r\n    \r\n    This relies on joint ordering\r\n    being incremental. That means a joint\r\n    J1 must not be a ancestor of J0 if\r\n    J0 appears before J1 in the joint\r\n    ordering.\r\n    \r\n    Parameters\r\n    ----------\r\n    \r\n    anim : Animation\r\n        Input animation\r\n    \r\n    Returns\r\n    ------\r\n    \r\n    transforms : (F, J, 4, 4) ndarray\r\n        Array of global transforms for \r\n        each frame F and joint J\r\n    \"\"\"\r\n    \r\n    joints  = np.arange(anim.shape[1])\r\n    parents = np.arange(anim.shape[1])\r\n    locals  = transforms_local(anim)\r\n    globals = transforms_blank(anim)\r\n\r\n    globals[:,0] = locals[:,0]\r\n    \r\n    for i in range(1, anim.shape[1]):\r\n        globals[:,i] = transforms_multiply(globals[:,anim.parents[i]], locals[:,i])\r\n        \r\n    return globals\r\n    \r\n    \r\ndef positions_global(anim):\r\n    \"\"\"\r\n    Global Joint Positions\r\n    \r\n    Given an animation compute the global joint\r\n    positions at at every frame\r\n    \r\n    Parameters\r\n    ----------\r\n    \r\n    anim : Animation\r\n        Input animation\r\n        \r\n    Returns\r\n    -------\r\n    \r\n    positions : (F, J, 3) ndarray\r\n        Positions for every frame F \r\n        and joint position J\r\n    \"\"\"\r\n    \r\n    positions = transforms_global(anim)[:,:,:,3]\r\n    return positions[:,:,:3] / positions[:,:,3,np.newaxis]\r\n    \r\n", "meta": {"hexsha": "73e4a99854e9566e740d1d8ced21b5547f6a25f8", "size": 8426, "ext": "py", "lang": "Python", "max_stars_repo_path": "Data_Processing_Scripts/motion/Animation.py", "max_stars_repo_name": "ianxmason/Fewshot_Learning_of_Homogeneous_Human_Locomotion_Styles", "max_stars_repo_head_hexsha": "7fc993e9f918d30cfc19b6560963d7d7358209e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2019-01-03T20:10:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T06:42:51.000Z", "max_issues_repo_path": "Data_Processing_Scripts/motion/Animation.py", "max_issues_repo_name": "ianxmason/Fewshot_Learning_of_Homogeneous_Human_Locomotion_Styles", "max_issues_repo_head_hexsha": "7fc993e9f918d30cfc19b6560963d7d7358209e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data_Processing_Scripts/motion/Animation.py", "max_forks_repo_name": "ianxmason/Fewshot_Learning_of_Homogeneous_Human_Locomotion_Styles", "max_forks_repo_head_hexsha": "7fc993e9f918d30cfc19b6560963d7d7358209e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-03-06T23:39:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-06T23:39:49.000Z", "avg_line_length": 29.1557093426, "max_line_length": 96, "alphanum_fraction": 0.5519819606, "include": true, "reason": "import numpy", "num_tokens": 2010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1865594640655067}}
{"text": "\"\"\"The main lagrangian-filtering module.\n\nThis module contains the crucial datastructure for\nlagrangian-filtering, `LagrangeFilter`. See project documentation\nfor examples on how to construct a filtering workflow using this\nlibrary.\n\n\"\"\"\n\nimport dask.array as da\nimport numpy as np\nfrom datetime import timedelta, datetime\nfrom glob import iglob\nimport parcels\nfrom scipy import signal\nimport netCDF4\nimport xarray as xr\nimport netCDF4 as nc\nimport sys\nfrom .file import LagrangeParticleFile\n\nimport multiprocessing as mp\nfrom functools import partial\n\nimport pathos.pools as pp\n\nclass LagrangeFilter(object):\n    \"\"\"The main class for a Lagrangian filtering workflow.\n\n    The workflow is set up using the input files and the filtering\n    parameters. Filtering can be performed all at once, or on\n    individual time levels.\n\n    Data must contain horizontal velocity components `U` and `V` to\n    perform the Lagrangian frame transformation. Any variables that should\n    be filtered must be specified in the `sample_variables` list (this\n    includes velocity).\n\n    Note:\n        We use the OceanParcels convention for variable names. This means that\n        ``U``, ``V``, ``lon``, ``lat``, ``time`` and ``depth`` are canonical\n        names for properties required for particle advection. The mapping from\n        the actual variable name in your data files to these canonical names\n        is contained in the `variables` and `dimensions` dictionaries. When\n        specifying `filenames` or `sample_variables`, the canonical names\n        must be used, however any other variables may use whatever name you\n        would like.\n\n    Once the `LagrangeFilter` has been constructed, you may call it as\n    a function to perform the filtering workflow. See :func:`~filter`\n    for documentation.\n\n    Example:\n        A straightforward filtering workflow::\n\n            f = LagrangeFilter(\n                name, filenames, variables, dimensions, sample_variables,\n            )\n            f()\n\n        Would result in a new file with the given `name` and an appropriate\n        extension containing the filtered data for each of the `sample_variables`.\n\n    Args:\n        name (str): The name of the workflow\n        filenames (Dict[str, str]): A mapping from data variable names\n            to the files containing the data.\n\n            Filenames can contain globs if the data is spread across\n            multiple files.\n        variables_or_data (Union[Dict[str, str], xarray.Dataset]): Either\n            a mapping from canonical variable names to the variable\n            names in your data files, or an xarray Dataset containing\n            the input data.\n        dimensions (Dict[str, str]): A mapping from canonical dimension\n            names to the dimension names in your data files.\n        sample_variables ([str]): A list of variable names that should be sampled\n            into the Lagrangian frame of reference and filtered.\n        mesh (:obj:`str`, optional): The OceanParcels mesh type, either \"flat\"\n            or \"spherical\". \"flat\" meshes are expected to have dimensions\n            in metres, and \"spherical\" meshes in degrees.\n        c_grid (:obj:`bool`, optional): Whether to interpolate velocity\n            components on an Arakawa C grid (defaults to no).\n        indices (:obj:`Dict[str, [int]]`, optional): An optional dictionary\n            specifying the indices to which a certain dimension should\n            be restricted.\n        uneven_window (:obj:`bool`, optional): Whether to allow different\n            lengths for the forward and backward advection phases.\n        window_size (:obj:`float`, optional): The nominal length of the both\n            the forward and backward advection windows, in seconds. A\n            longer window may better capture the low-frequency signal to be\n            removed.\n        highpass_frequency (:obj:`float`, optional): The 3dB cutoff frequency\n            for filtering, below which spectral components will be\n            attenuated. This should be an angular frequency, in [rad/s].\n        advection_dt (:obj:`datetime.timedelta`, optional): The timestep\n            to use for advection. May need to be adjusted depending on the\n            resolution/frequency of your data.\n\n    \"\"\"\n\n    def __init__(\n        self,\n        name,\n        filenames_or_dataset,\n        variables,\n        dimensions,\n        sample_variables,\n        mesh=\"flat\",\n        c_grid=False,\n        indices={},\n        uneven_window=False,\n        window_size=None,\n        highpass_frequency=5e-5,\n        advection_dt=timedelta(minutes=5),\n    ):\n        # The name of this filter\n        self.name = name\n        # Width of window over which our filter computes a meaningful result\n        # in seconds. Default to 3.5 days on either side\n        if window_size is None:\n            self.window_size = timedelta(days=3.5).total_seconds()\n        else:\n            self.window_size = window_size\n        # Whether we're permitted to use uneven windows on either side\n        self.uneven_window = uneven_window\n\n        # copy input file dictionaries so we can construct the output file\n        # filenames dictionary is modified to expand globs when\n        # the fieldset is constructed\n        self._filenames = filenames_or_dataset\n        self._variables = variables\n        self._dimensions = dimensions\n        self._indices = indices\n        # sample variables without the \"var_\" prefix\n        self._sample_variables = sample_variables\n\n        # choose the fieldset constructor depending on the format\n        # of the input data\n        if isinstance(filenames_or_dataset, xr.Dataset):\n            fieldset_constructor = parcels.FieldSet.from_xarray_dataset\n        else:\n            fieldset_constructor = parcels.FieldSet.from_netcdf\n\n        # for C-grid data, we have to change the interpolation method\n        fieldset_kwargs = {}\n        if c_grid:\n            interp_method = {}\n            for v in variables:\n                if v in [\"U\", \"V\", \"W\"]:\n                    interp_method[v] = \"cgrid_velocity\"\n                else:\n                    interp_method[v] = \"cgrid_tracer\"\n\n            fieldset_kwargs[\"interp_method\"] = interp_method\n\n        # construct the OceanParcels FieldSet to use for particle advection\n        self.fieldset = fieldset_constructor(\n            filenames_or_dataset,\n            variables,\n            dimensions,\n            indices=indices,\n            mesh=mesh,\n            **fieldset_kwargs,\n        )\n        # save the lon/lat on which to seed particles\n        # this is saved here because if the grid is later made periodic, the\n        # underlying grids will be modified, and we'll seed particles in the halos\n        if self.fieldset.gridset.grids[0].gtype in [\n            parcels.GridCode.CurvilinearZGrid,\n            parcels.GridCode.CurvilinearSGrid,\n        ]:\n            self._curvilinear = True\n            self._grid_lon = self.fieldset.gridset.grids[0].lon\n            self._grid_lat = self.fieldset.gridset.grids[0].lat\n        else:\n            self._curvilinear = False\n            self._grid_lon, self._grid_lat = np.meshgrid(\n                self.fieldset.gridset.grids[0].lon, self.fieldset.gridset.grids[0].lat\n            )\n\n        # starts off non-periodic\n        self._is_zonally_periodic = False\n        self._is_meridionally_periodic = False\n\n        # guess the output timestep\n        times = self.fieldset.gridset.grids[0].time\n        self.output_dt = times[1] - times[0]\n        print('timestep =',self.output_dt,'seconds')\n\n        # create the filter - use a 4th order Butterworth for the moment\n        # make sure to convert angular frequency back to linear for passing to the\n        # filter constructor\n        fs = 1.0 / self.output_dt\n        self.inertial_filter = signal.butter(\n            4, highpass_frequency / (2 * np.pi), \"lowpass\", fs=fs\n        )\n\n        # timestep for advection\n        self.advection_dt = advection_dt\n\n        # the sample variable attribute has 'var_' prepended to map to\n        # variables on particles\n        self.sample_variables = [\"var_\" + v for v in sample_variables]\n        # create the particle class and kernel for sampling\n        # map sampled variables to fields\n        self.particleclass = ParticleFactory(sample_variables)\n        self._create_sample_kernel(sample_variables)\n        self.kernel = parcels.AdvectionRK4 + self.sample_kernel\n\n        # compile kernels\n        self._compile(self.sample_kernel)\n        self._compile(self.kernel)\n\n    def _create_sample_kernel(self, sample_variables):\n        \"\"\"Create the parcels kernel for sampling fields during advection.\"\"\"\n\n        # make sure the fieldset has C code names assigned, etc.\n        self.fieldset.check_complete()\n\n        # string for the kernel itself\n        f_str = \"def sample_kernel(particle, fieldset, time):\\n\"\n        for v in sample_variables:\n            f_str += f\"\\tparticle.var_{v} = fieldset.{v}[time, particle.depth, particle.lat, particle.lon]\\n\"\n        else:\n            f_str += \"\\tpass\"\n\n        # create the kernel\n        self.sample_kernel = parcels.Kernel(\n            self.fieldset,\n            self.particleclass.getPType(),\n            funcname=\"sample_kernel\",\n            funcvars=[\"particle\", \"fieldset\", \"time\"],\n            funccode=f_str,\n        )\n\n    def _compile(self, kernel):\n        \"\"\"Compile a kernel and tell it to load the resulting shared library.\"\"\"\n\n        kernel.compile(compiler=parcels.compiler.GNUCompiler())\n        kernel.load_lib()\n\n    def make_zonally_periodic(self, width=None):\n        \"\"\"Mark the domain as zonally periodic.\n\n        This will add a halo to the eastern and western edges of the\n        domain, so that they may cross over during advection without\n        being marked out of bounds. If a particle ends up within the\n        halo after advection, it is reset to the valid portion of the\n        domain.\n\n        If the domain has already been marked as zonally periodic,\n        nothing happens.\n\n        Due to the method of resetting particles that end up in the\n        halo, this is incompatible with curvilinear grids.\n\n        Args:\n            width (:obj:`int`, optional): The width of the halo,\n                defaults to 5 (per parcels). This needs to be less\n                than half the number of points in the grid in the x\n                direction. This may need to be adjusted for small\n                domains, or if particles are still escaping the halo.\n\n        Note:\n            This causes the kernel to be recompiled to add another stage\n            which resets particles that end up in the halo to the main\n            domain.\n\n            If the kernel has already been recompiled for meridional periodicity,\n            it is again reset to include periodicity in both\n            directions.\n\n        \"\"\"\n\n        # the method of resetting particles won't work on a curvilinear grid\n        if self._curvilinear:\n            raise Exception(\"curvilinear grids can not be periodic\")\n\n        # make sure we can't do this twice\n        if self._is_zonally_periodic:\n            return\n\n        # add constants that are accessible within the kernel denoting the\n        # edges of the halo region\n        self.fieldset.add_constant(\"halo_west\", self.fieldset.gridset.grids[0].lon[0])\n        self.fieldset.add_constant(\"halo_east\", self.fieldset.gridset.grids[0].lon[-1])\n\n        if width is None:\n            self.fieldset.add_periodic_halo(zonal=True)\n        else:\n            self.fieldset.add_periodic_halo(zonal=True, halosize=width)\n\n        # unload the advection-only kernel, and add the periodic-reset kernel\n        self.kernel.remove_lib()\n\n        if self._is_meridionally_periodic:\n            k = _doubly_periodic_BC\n        else:\n            k = _zonally_periodic_BC\n\n        periodic_kernel = parcels.Kernel(\n            self.fieldset, self.particleclass.getPType(), k\n        )\n\n        self.kernel = parcels.AdvectionRK4 + periodic_kernel + self.sample_kernel\n        self._compile(self.kernel)\n\n        self._is_zonally_periodic = True\n\n    def make_meridionally_periodic(self, width=None):\n        \"\"\"Mark the domain as meridionally periodic.\n\n        This will add a halo to the northern and southern edges of the\n        domain, so that they may cross over during advection without\n        being marked out of bounds. If a particle ends up within the\n        halo after advection, it is reset to the valid portion of the\n        domain.\n\n        If the domain has already been marked as meridionally periodic,\n        nothing happens.\n\n        Due to the method of resetting particles that end up in the\n        halo, this is incompatible with curvilinear grids.\n\n        Args:\n            width (:obj:`int`, optional): The width of the halo,\n                defaults to 5 (per parcels). This needs to be less\n                than half the number of points in the grid in the y\n                direction. This may need to be adjusted for small\n                domains, or if particles are still escaping the halo.\n\n        Note:\n            This causes the kernel to be recompiled to add another stage\n            which resets particles that end up in the halo to the main\n            domain.\n\n            If the kernel has already been recompiled for zonal periodicity,\n            it is again reset to include periodicity in both\n            directions.\n\n        \"\"\"\n\n        # the method of resetting particles won't work on a curvilinear grid\n        if self._curvilinear:\n            raise Exception(\"curvilinear grids can not be periodic\")\n\n        # make sure we can't do this twice\n        if self._is_meridionally_periodic:\n            return\n\n        # add constants that are accessible within the kernel denoting the\n        # edges of the halo region\n        self.fieldset.add_constant(\"halo_north\", self.fieldset.gridset.grids[0].lat[-1])\n        self.fieldset.add_constant(\"halo_south\", self.fieldset.gridset.grids[0].lat[0])\n\n        if width is None:\n            self.fieldset.add_periodic_halo(meridional=True)\n        else:\n            self.fieldset.add_periodic_halo(meridional=True, halosize=width)\n\n        # unload the previous kernel, and add the meridionally-periodic kernel\n        self.kernel.remove_lib()\n\n        if self._is_zonally_periodic:\n            k = _doubly_periodic_BC\n        else:\n            k = _meridionally_periodic_BC\n\n        periodic_kernel = parcels.Kernel(\n            self.fieldset, self.particleclass.getPType(), k\n        )\n\n        self.kernel = parcels.AdvectionRK4 + periodic_kernel + self.sample_kernel\n        self._compile(self.kernel)\n\n        self._is_meridionally_periodic = True\n\n    def particleset(self, time):\n        \"\"\"Create a ParticleSet initialised at the given time.\n\n        Args:\n            time (float): The origin time for forward and backward advection\n                on this ParticleSet.\n\n        Returns:\n            parcels.ParticleSet: A new ParticleSet containing a single particle\n                at every gridpoint, initialised at the specified time.\n\n        \"\"\"\n\n        # reset the global particle ID counter so we can rely on particle IDs making sense\n        parcels.particle.lastID = 0\n\n        return parcels.ParticleSet(\n            self.fieldset,\n            pclass=self.particleclass,\n            lon=self._grid_lon,\n            lat=self._grid_lat,\n            time=time,\n        )\n\n    def advection_step(self, time, output_time=False):\n        \"\"\"Perform forward-backward advection at a single point in time.\n\n        This routine is responsible for creating a new ParticleSet at\n        the given time, and performing the forward and backward\n        advection steps in the Lagrangian transformation.\n\n        Args:\n            time (float): The point in time at which to calculate filtered data.\n            output_time (:obj:`bool`, optional): Whether to include \"time\" as\n                a numpy array in the output dictionary, for doing manual analysis.\n\n        Note:\n            If ``output_time`` is True, the output object will not be compatible\n            with the default filtering workflow, :func:`~filter_step`!\n\n        Returns:\n            Dict[str, (int, dask.array)]: A dictionary of the advection\n                data, mapping variable names to a pair. The first element is\n                the index of the sampled timestep in the data, and the\n                second element is a lazy dask array concatenating the forward\n                and backward advection data.\n\n        \"\"\"\n\n        # seed all particles at gridpoints\n        ps = self.particleset(time)\n        # execute the sample-only kernel to efficiently grab the initial condition\n        ps.kernel = self.sample_kernel\n        ps.execute(self.sample_kernel, runtime=0, dt=self.advection_dt)\n\n        # set up the temporary output file for the initial condition and\n        # forward advection\n        outfile = LagrangeParticleFile(ps, self.output_dt, self.sample_variables)\n\n        # now the forward advection kernel can run\n        outfile.set_group(\"forward\")\n        ps.kernel = self.kernel\n        ps.execute(\n            self.kernel,\n            runtime=self.window_size,\n            dt=self.advection_dt,\n            output_file=outfile,\n        )\n\n        # reseed particles back on the grid, then advect backwards\n        # we don't need any initial condition sampling since we've already done it\n        outfile.set_group(\"backward\")\n        ps = self.particleset(time)\n        ps.kernel = self.kernel\n        ps.execute(\n            self.kernel,\n            runtime=self.window_size,\n            dt=-self.advection_dt,\n            output_file=outfile,\n        )\n\n        # stitch together and filter all sample variables from the temporary\n        # output data\n        da_out = {}\n        for v in self.sample_variables:\n            # load data lazily as dask arrays, for forward and backward segments\n            var_array_forward = da.from_array(\n                outfile.data(\"forward\")[v], chunks=(None, \"auto\")\n            )[:-1, :]\n            var_array_backward = da.from_array(\n                outfile.data(\"backward\")[v], chunks=(None, \"auto\")\n            )[:-1, :]\n\n            # get an index into the middle of the array\n            time_index_data = var_array_backward.shape[0] - 1\n\n            # construct proper sequence by concatenating data and flipping the backward segment\n            # for var_array_forward, skip the initial output for both the sample-only and\n            # sample-advection kernels, which have meaningless data\n            var_array = da.concatenate(\n                (da.flip(var_array_backward[1:, :], axis=0), var_array_forward)\n            )\n\n            da_out[v] = (time_index_data, var_array)\n\n        if output_time:\n            da_out[\"time\"] = np.concatenate(\n                (\n                    outfile.data(\"backward\").attrs[\"time\"][1:-1][::-1],\n                    outfile.data(\"forward\").attrs[\"time\"][:-1],\n                )\n            )\n\n        return da_out\n\n    def filter_step(self, advection_data):\n        \"\"\"Perform filtering of a single step of advection data.\n\n        The Lagrangian-transformed data from :func:`~advection_step` is\n        high-pass filtered in time, leaving only the signal at the\n        origin point (i.e. the filtered forward and backward advection\n        data is discarded).\n\n        Args:\n            advection_data (Dict[str, (int, dask.array)]): A dictionary of\n                particle advection data from a single timestep, returned\n                from :func:`~advection_step`.\n\n        Returns:\n            Dict[str, dask.array]: A dictionary mapping sampled\n                variable names to a 1D dask array containing the\n                filtered data at the specified time. This data is not\n                lazy, as it has already been computed out of the\n                temporary advection data.\n\n        \"\"\"\n\n        da_out = {}\n        for v, a in advection_data.items():\n            time_index_data, var_array = a\n\n            def filter_select(x):\n                return signal.filtfilt(*self.inertial_filter, x)[..., time_index_data]\n\n            # apply scipy filter as a ufunc\n            # mapping an array to scalar over the first axis, automatically vectorize execution\n            # and allow rechunking (since we have a chunk boundary across the first axis)\n            filtered = da.apply_gufunc(\n                filter_select,\n                \"(i)->()\",\n                var_array,\n                axis=0,\n                output_dtypes=var_array.dtype,\n                allow_rechunk=True,\n            )\n\n            da_out[v] = filtered.compute()\n\n        return da_out\n\n    def filter(self, *args, **kwargs):\n        \"\"\"Run the filtering process on this experiment.\n\n        Note:\n            Instead of `f.filter(...)`, you can call `f(...)` directly.\n\n        This is main method of the filtering workflow. The timesteps\n        to filter may either be specified manually, or determined from\n        the window size and the timesteps within the input files. In\n        this latter case, only timesteps that have the full window\n        size on either side are selected.\n\n        Note:\n            If `absolute` is True, the times must be the same datatype\n            as those the input data. For dates with a calendar, this\n            is likely :obj:`np.datetime64` or :obj:`cftime.datetime`.\n            For abstract times, this may simply be a number.\n\n        Args:\n            times (:obj:`[float]`, optional): A list of timesteps at\n                which to run the filtering. If this is omitted, all\n                timesteps that are fully covered by the filtering\n                window are selected.\n            clobber (:obj:`bool`, optional): Whether to overwrite any\n                existing output file with the same name as this\n                experiment. Default behaviour will not clobber an\n                existing output file.\n\n            absolute (:obj:`bool`, optional): If `times` is provided,\n                this argument determines whether to interpret them\n                as relative to the first timestep in the input dataset\n                (False, default), or as absolute, following the actual\n                time dimension in the dataset (True).\n\n        \"\"\"\n\n        self(*args, **kwargs)\n\n    def create_out(self, clobber=False, date=None):\n        \"\"\"Create a netCDF dataset to hold filtered output.\n\n        Here we create a new ``netCDF4.Dataset`` for filtered\n        output. For each sampled variable in the input files, a\n        corresponding variable in created in the output file, with\n        the same dimensions.\n\n        Returns:\n            netCDF4.Dataset: A single dataset that will hold all\n                filtered output.\n\n        \"\"\"\n\n        # the output dataset we're creating\n        filename = self.name \n        if date is not None:\n            date_str = str(date)[:13]\n            filename += '_' + date_str \n        filename += \".nc\"\n        print(filename)\n        ds = netCDF4.Dataset(filename, \"w\", clobber=clobber)\n\n        # helper function to create the dimensions in the ouput file\n        def create_dimension(dims, dim, var):\n            # translate from parcels -> file convention\n            # and check whether we've already created this dimension\n            # (e.g. for a previous variable)\n            file_dim = dims[dim]\n            if file_dim in ds.variables:\n                return ds.variables[file_dim].dimensions[\n                    1\n                    if len(ds.variables[file_dim].dimensions) > 1 and dim == \"lon\"\n                    else 0\n                ]\n\n            # get the file containing the dimension data\n            v_orig = self._variables.get(var, var)\n            if isinstance(self._filenames, xr.Dataset):\n                ds_orig = self._filenames[file_dim]\n            else:\n                if isinstance(self._filenames[var], dict):\n                    filename = self._filenames[var][dim]\n                else:\n                    filename = self._filenames[var]\n\n                if isinstance(filename, list):\n                    filename = filename[0]\n\n                ds_orig = xr.open_dataset(next(iglob(filename)))[file_dim]\n\n            # create dimensions if needed\n            for d in ds_orig.dims:\n                if d not in ds.dimensions:\n                    ds.createDimension(d, ds_orig[d].size)\n\n            # create the dimension variable\n            ds.createVariable(file_dim, ds_orig.dtype, dimensions=ds_orig.dims)\n            ds.variables[file_dim][:] = ds_orig\n\n            # curvilinear grid case\n            return ds_orig.dims[1 if len(ds_orig.dims) > 1 and dim == \"lon\" else 0]\n\n        # create a time dimension if dimensions are uniform across all variables\n        if \"time\" in self._dimensions:\n            dim_time = self._dimensions[\"time\"]\n            ds.createDimension(dim_time)\n            # Add by FlG\n            if date is not None:               \n                ds.createVariable(\n                \"time\",\n                \"float32\",\n                dimensions=(dim_time,),\n                )\n                calendar = 'standard'\n                units = 'seconds since 1900-01-01 00:00'\n                ts = (date - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's')\n                dt = datetime.utcfromtimestamp(ts)\n                ds[\"time\"][:] = nc.date2num(dt, units=units, calendar=calendar)\n                \n                           \n        else:\n            dim_time = None\n\n        \n            \n        for v in self._sample_variables:\n            # translate if required (parcels -> file convention)\n            v_orig = self._variables.get(v, v)\n\n            # open all the relevant files for this variable\n            if isinstance(self._filenames, xr.Dataset):\n                ds_orig = self._filenames[v_orig]\n            else:\n                if isinstance(self._filenames[v], dict):\n                    # variable -> dictionary (for separate coordinate files)\n                    filename = self._filenames[v][\"data\"]\n                else:\n                    # otherwise, we just have a plain variable -> file mapping\n                    filename = self._filenames[v]\n\n                # globs can give us a list, but we only need the first item\n                # to get the metadata\n                if isinstance(filename, list):\n                    filename = filename[0]\n\n                ds_orig = xr.open_dataset(next(iglob(filename)))[v_orig]\n\n            # are dimensions defined specifically for this variable?\n            if v in self._dimensions:\n                dims = self._dimensions[v]\n            else:\n                dims = self._dimensions\n\n            # are indices defined specifically for this variable?\n            if v in self._indices:\n                indices = self._indices[v]\n            else:\n                indices = self._indices\n\n            # translate to variable names from the source files\n            indices = {dims[v]: ind for v, ind in indices.items()}\n\n            # select only the relevant indices\n            # in particular, squeeze to drop z dimension if we index it out\n            local_indices = {k: v for k, v in indices.items() if k in ds_orig.dims}\n            ds_orig = ds_orig.isel(**local_indices).squeeze()\n\n            # create time dimension if required (i.e. not already in the\n            # output file we've created)\n            out_dims = {}\n            if dim_time is None:\n                out_dims[\"time\"] = dims[\"time\"]\n                if dims[\"time\"] not in ds.dimensions:\n                    ds.createDimension(dims[\"time\"])\n            else:\n                out_dims[\"time\"] = dim_time\n\n            # for each non-time dimension, create it if it doesn't already exist\n            # in the output file\n            for d in [\"lat\", \"lon\"]:\n                out_dims[d] = create_dimension(dims, d, v)\n\n            # create the variable in the dataset itself\n            ds.createVariable(\n                \"var_\" + v,\n                \"float32\",\n                dimensions=(out_dims[\"time\"], out_dims[\"lat\"], out_dims[\"lon\"]),\n            )\n            \n\n        return ds\n\n    def _window_times(self, times, absolute):\n        \n        \"\"\"Restrict an array of times to those which have an adequate window,\n        optionally converting from absolute to relative first.\n\n        \"\"\"\n\n        tgrid = self.fieldset.gridset.grids[0].time\n\n        if times is None:\n            times = tgrid.copy()\n\n        if absolute:\n            times = self.fieldset.gridset.grids[0].time_origin.reltime(times)\n\n        times = np.array(times)\n        window_left = times - tgrid[0] >= self.window_size\n        window_right = times <= tgrid[-1] - self.window_size\n        return times[window_left & window_right]\n\n    def _do_filtering(self, time):\n\n        date = self.fieldset.gridset.grids[0].time_origin.fulltime(time)\n        \n        print(date)\n        \n        ds = self.create_out(clobber=True, date=date)\n        \n        # returns a dictionary of sample_variable -> dask array\n        filtered = self.filter_step(self.advection_step(time))\n        for v, a in filtered.items():\n            ds[v][0, ...] = a \n            \n        ds.close()\n        \n\n\n    def __call__(self, times=None, absolute=False, clobber=False):\n        \"\"\"Run the filtering process on this experiment.\"\"\"\n\n        if self.uneven_window:\n            raise NotImplementedError(\"uneven windows aren't supported\")\n\n        # either restrict the specified times to period covered by window,\n        # or use the full range of times covered by window\n        times = self._window_times(times, absolute)\n\n        for time in times:\n            self._do_filtering(time)\n\n        print('End of the program')\n        \n\n    \n    \n\ndef ParticleFactory(variables, name=\"SamplingParticle\", BaseClass=parcels.JITParticle):\n    \"\"\"Create a Particle class that samples the specified variables.\n\n    The variables that should be sampled will be prepended by ``var_`` as\n    class attributes, in case there are any namespace clashes with existing\n    variables on the base class.\n\n    Args:\n        variables ([str]): A list of variable names which should be sampled.\n        name (str): The name of the generated particle class.\n        BaseClass (Type[parcels.particle._Particle]): The base particles class upon\n            which to append the required variables.\n\n    Returns:\n        Type[parcels.particle._Particle]: The new particle class\n\n    \"\"\"\n\n    var_dict = {\"var_\" + v: parcels.Variable(\"var_\" + v) for v in variables}\n\n    newclass = type(name, (BaseClass,), var_dict)\n    return newclass\n\n\ndef _zonally_periodic_BC(particle, fieldset, time):\n    if particle.lon < fieldset.halo_west:\n        particle.lon += fieldset.halo_east - fieldset.halo_west\n    elif particle.lon > fieldset.halo_east:\n        particle.lon -= fieldset.halo_east - fieldset.halo_west\n\n\ndef _meridionally_periodic_BC(particle, fieldset, time):\n    if particle.lat < fieldset.halo_south:\n        particle.lat += fieldset.halo_north - fieldset.halo_south\n    elif particle.lat > fieldset.halo_north:\n        particle.lat -= fieldset.halo_north - fieldset.halo_south\n\n\ndef _doubly_periodic_BC(particle, fieldset, time):\n    # because the kernel is run through code generation, we can't simply\n    # call the above kernels, so we unfortunately have to reproduce them\n    # in full here\n    if particle.lon < fieldset.halo_west:\n        particle.lon += fieldset.halo_east - fieldset.halo_west\n    elif particle.lon > fieldset.halo_east:\n        particle.lon -= fieldset.halo_east - fieldset.halo_west\n\n    if particle.lat < fieldset.halo_south:\n        particle.lat += fieldset.halo_north - fieldset.halo_south\n    elif particle.lat > fieldset.halo_north:\n        particle.lat -= fieldset.halo_north - fieldset.halo_south\n", "meta": {"hexsha": "3a73941c6a182802cef3282cf1e8859b78249717", "size": 32033, "ext": "py", "lang": "Python", "max_stars_repo_path": "filtering/filtering.py", "max_stars_repo_name": "leguillf/lagrangian-filtering", "max_stars_repo_head_hexsha": "ba9e605cfec39824880d960ba909bfa8bab6117d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "filtering/filtering.py", "max_issues_repo_name": "leguillf/lagrangian-filtering", "max_issues_repo_head_hexsha": "ba9e605cfec39824880d960ba909bfa8bab6117d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "filtering/filtering.py", "max_forks_repo_name": "leguillf/lagrangian-filtering", "max_forks_repo_head_hexsha": "ba9e605cfec39824880d960ba909bfa8bab6117d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2712066906, "max_line_length": 109, "alphanum_fraction": 0.6134299004, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1865594640655067}}
{"text": "\"\"\"\nReads collapsing matrix and summary file from ATAV and generates an \nempirical permutation-based Q-Q plot.\n\nWritten by Charlie Wolock <cw3026@cumc.columbia.edu> \n\"\"\"\n\nfrom functools import partial\nfrom operator import le, lt\nfrom scipy import stats\nimport argparse\nimport ctypes\nimport matplotlib\nmatplotlib.use('pdf')\nimport matplotlib.pyplot as plt\nimport multiprocessing as mp\nimport numpy as np\nimport random\nimport seaborn as sns\nimport sys\n\nsns.set_style('darkgrid')\n\n\ndef valid_numerical_argument(\n        arg, arg_name, arg_type=int, min_value=0, max_value=sys.maxint,\n        left_op=lt, right_op=le):\n    \"\"\"\n    Confirm that the specified value is valid in the range\n    (minimum_value, maximum_value] (by default)\n    :param arg: the value to be tested\n    :param arg_name: the name of the parameter\n    :param arg_type: the type of the parameter, e.g. int or float\n    :param min_value: the minimum value for the parameter, exclusive\n    :param max_value: the maximum value for the parameter, inclusive\n    :param left_op: the operator for testing left_op(min_value, value)\n    :param right_op: the operator testing right_op(value, max_value)\n    :return: arg_type(arg) if arg is valid\n    \"\"\"\n    try:\n        value = arg_type(arg)\n        if left_op(min_value, value) and right_op(value, max_value):\n            return value\n        else:\n            raise argparse.ArgumentTypeError(\n                \"{arg_name} ({arg}) is not in the range \"\n                \"{left_endpoint}{min_value}, {max_value}{right_endpoint}\".format(\n                    arg_name=arg_name, arg=arg, min_value=min_value,\n                    max_value=max_value, left_endpoint=\"(\" if left_op == lt else \"[\",\n                    right_endpoint=\"]\" if right_op == le else \")\"))\n    except TypeError:\n        raise argparse.ArgumentTypeError(\n            \"{arg_name} ({arg}) is not a valid {arg_type}\".format(\n                arg_name=arg_name, arg=arg, arg_type=arg_type.__name__))\n\n\ndef precalc(pair, num_case, num_ctrl):\n    \"\"\"\n    Calculate FET p-value for pair of qual case + qual ctrl\n    :param pair: (tuple) number of qualified cases and controls\n    :param num_case: (int) number of case samples\n    :param num_ctrl: (int) number of control samples\n    \"\"\"\n    odds, pval = stats.fisher_exact([[pair[0], num_case - pair[0]],\n                                     [pair[1], num_ctrl - pair[1]]])\n    return (pair[0], pair[1], pval)\n\n\ndef shared_mem(result):\n    \"\"\"\n    Populate lookup table with pre-calculated p-values\n    :param result: (tuple) num. qual. cases, num. qual ctrls, associated FET p-value\n    \"\"\"\n    lookup[result[0], result[1]] = result[2]\n\n\ndef permute(counter, statuses):\n    \"\"\"\n    Permute affection statuses and look up p-vals for this configuration\n    :param counter: (int) iteration counter for multiprocessing to keep track\n    :param statuses: (list) randomized list of case/control statuses\n    \"\"\"\n    # randomize the statuses\n    perm_statuses = np.array(random.sample(statuses, len(statuses)))\n    case_indices = np.where(perm_statuses == '2')[0]\n    ctrl_indices = np.where(perm_statuses == '1')[0]\n    # make contingency table and calculate pvals for each gene\n    pvals = []\n    for row in range(col_matrix.shape[0]):\n        q_case = np.where(col_matrix[row, case_indices] == 1)[0].shape[0]\n        q_ctrl = np.where(col_matrix[row, ctrl_indices] == 1)[0].shape[0]\n        # fisher exact test\n        # if number of qualified samples is in the lookup table, use that\n        if q_case + 1 <= lookup.shape[0] and q_ctrl + 1 <= lookup.shape[1]:\n            pvalue = lookup[q_case, q_ctrl]\n        # otherwise just do the FET\n        else:\n            odds, pvalue = stats.fisher_exact([[q_case, len(case_indices) - q_case],\n                                               [q_ctrl, len(ctrl_indices) - q_ctrl]])\n        pvals.append(pvalue)\n    pvals = sorted(pvals)\n    return pvals\n\n\ndef read_summary_file(summary_file):\n    \"\"\"\n    Read in partial summary and add gene info to dictionary\n    :param summary_file: (string) name of partial summary file\n    \"\"\"\n    genes = {}\n    case_qual = []\n    ctrl_qual = []\n    with open(summary_file, 'r') as infile:\n        header = infile.readline().strip().split(',')\n        gene_index = header.index('Gene Name')\n        qcase_index = header.index('Qualified Case')\n        uqcase_index = header.index('Unqualified Case')\n        qctrl_index = header.index('Qualified Ctrl')\n        uqctrl_index = header.index('Unqualified Ctrl')\n        # read first line to determine number of cases and ctrls\n        first = infile.readline().strip().split(',')\n        genes[first[gene_index]] = [x for x in first[2:]]\n        ncase = int(first[qcase_index]) + int(first[uqcase_index])\n        nctrl = int(first[qctrl_index]) + int(first[uqctrl_index])\n        case_qual.append(int(first[qcase_index]))\n        ctrl_qual.append(int(first[qctrl_index]))\n        for line in infile:\n            line = line.strip().split(',')\n            genes[line[gene_index]] = [x for x in line[2:]]\n            case_qual.append(int(line[qcase_index]))\n            ctrl_qual.append(int(line[qctrl_index]))\n    return (genes, ncase, nctrl, case_qual, ctrl_qual)\n\n\ndef read_matrix_file(matrix_file, ngenes):\n    \"\"\"\n    Read in matrix file\n    :param matrix_file: (string) name of matrix file\n    :param ngenes: (int) number of genes (or general collapsing units)\n    \"\"\"\n    with open(matrix_file, 'r') as infile:\n        samps = infile.readline().strip().split('\\t')\n        nsamps = len(samps) - 1\n        col_matrix = np.zeros((ngenes, nsamps))\n        for i, line in enumerate(infile):\n            line = line.strip().split('\\t')\n            col_matrix[i, :] = line[1:]\n    return col_matrix\n\n\ndef plot_qq(qq_file, exp, obs, lower, upper, sorted_genes):\n    \"\"\"\n    Create QQ-plot of observed and expected FET p-values, with 2.5%ile and 97.5%ile\n        bounds.\n    Lambda = slope of regression on chi-sq transformed obs and exp p-values, after\n         removal of p-values of 1 and genome-wide sig. p-values\n    :param qq_file: (string) name of QQ-plot file to be created\n    :param exp: (np array) expected p-values\n    :param obs: (np array) observed p-values\n    :param lower: (np array) 2.5%ile exp p-values\n    :param upper: (np array) 97.5%ile exp p-values\n    :param sorted_genes: (list) genes sorted by descending rank\n    \"\"\"\n    # change p-values > 1 to 1\n    exp[exp > 1] = 1\n    obs[obs > 1] = 1\n\n    # calculate lambda by regression method\n    # first remove p-values of 1 and < genome-wide significance\n    gws = 0.05 / len(obs)\n    reg_exp = exp[(obs > gws) & (exp > gws) & (exp < 1) & (obs < 1)]\n    reg_obs = obs[(obs > gws) & (exp > gws) & (exp < 1) & (obs < 1)]\n    reg_exp = stats.chi2.ppf(1 - reg_exp, 1)\n    reg_obs = stats.chi2.ppf(1 - reg_obs, 1)\n    # for lstsq, explanatory vars must be in column form\n    reg_exp = reg_exp[:, np.newaxis]\n    # this least squares regression forces intercept to be 0\n    slope = np.linalg.lstsq(reg_exp, reg_obs)[0][0]\n    lambda_factor = slope\n    lambda_factor = np.around(lambda_factor, 5)\n\n    # transform p-values to log10\n    exp = -np.log10(exp)\n    obs = -np.log10(obs)\n    # note that \"upper\" and \"lower\" switch here because of the transformation\n    lower = -np.log10(lower)\n    upper = -np.log10(upper)\n\n    # set limits of qq plot axes\n    axisMax_obs = np.ceil(max(obs))\n    axisMax_exp = np.ceil(max(exp))\n\n    # initialize qqplot with axes and labels\n    fig = plt.figure(figsize=(12, 12))\n    plt.xlim([0, axisMax_exp])\n    plt.xlabel('Expected -log10(p)', fontsize=20)\n    plt.ylim([0, axisMax_obs])\n    plt.ylabel('Observed -log10(p)', fontsize=20)\n    plt.title('QQ Plot: Observed vs. expected p-values. Lambda = {l}'.format(\n              l=lambda_factor), fontsize=20)\n\n    # change size of axis tick labels\n    plt.tick_params(axis='both', which='major', labelsize=12)\n\n    # plot the points, exp on x axis, obs on y axis\n    dataAx = fig.add_subplot(1, 1, 1)\n    dataAx.plot(exp, obs, 'r.', label='_nolegend_', markersize=12)\n\n    # plot a diagonal line for comparison\n    lineAx = fig.add_subplot(1, 1, 1)\n    lineAx.plot([0, max(axisMax_obs, axisMax_exp)], [0, max(axisMax_obs, axisMax_exp)],\n                'b-', label='_nolegend_')\n    uppAx = fig.add_subplot(1, 1, 1)\n    uppAx.plot(exp, upper, 'g-')\n    lowAx = fig.add_subplot(1, 1, 1)\n    lowAx.plot(exp, lower, 'y-')\n    plt.legend(['2.5th percentile of expected p-values',\n                '97.5th percentile of expected p-values'],\n               loc=2)\n    plt.tight_layout()\n    plt.savefig(qq_file)\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description=__doc__,\n        formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n    parser.add_argument('partial_summary_file',\n                        help='Specify name of summary file generated by summarize.py')\n    parser.add_argument('matrix_file',\n                        help='Specify name of matrix file generated by summarize.py')\n    parser.add_argument('output', help='Specify prefix for output files')\n    parser.add_argument('--nperms',\n                        type=partial(valid_numerical_argument, arg_name='nperms',\n                                     min_value=0, max_value=1000, arg_type=int),\n                        default=1000,\n                        help='Specify number of permutations')\n    parser.add_argument('--nprocs',\n                        type=partial(valid_numerical_argument, arg_name='nprocs',\n                                     min_value=0, max_value=10, arg_type=int),\n                        default=4,\n                        help='Specify number of concurrent processes')\n    args = parser.parse_args()\n\n    # read summary file to get dictionary of gene-level info\n    # num of cases, controls, and maximum number of qualified samples in any\n    # gene\n    genes, ncase, nctrl, case_qual, ctrl_qual = read_summary_file(\n        args.partial_summary_file)\n\n    # determine 99th percentile of qualified\n    case_qual = np.array(case_qual)\n    ctrl_qual = np.array(ctrl_qual)\n    qual_sum = np.sort(case_qual + ctrl_qual)\n    high_qual = np.percentile(qual_sum, 95, interpolation='higher')\n\n    # calculate number of genes\n    ngenes = len(genes)\n\n    # read matrix file to build collapsing matrix\n    col_matrix = read_matrix_file(args.matrix_file, ngenes)\n\n    # calculate number of samples\n    nsamps = col_matrix.shape[1]\n\n    # create shared memory version of collapsing matrix\n    shared_array_base1 = mp.Array(ctypes.c_int, ngenes * nsamps)\n    shared_col_matrix = np.ctypeslib.as_array(shared_array_base1.get_obj())\n    shared_col_matrix = shared_col_matrix.reshape(ngenes, nsamps)\n\n    # calculate necessary dimensions of FET lookup table\n    max_case = min([high_qual, ncase])\n    max_ctrl = min([high_qual, nctrl])\n\n    # create shared memory FET lookup table\n    shared_array_base2 = mp.Array(\n        ctypes.c_double, (max_case + 1) * (max_ctrl + 1))\n    lookup = np.ctypeslib.as_array(shared_array_base2.get_obj())\n    lookup = lookup.reshape(max_case + 1, max_ctrl + 1)\n\n    # make list of qual case/qual ctrl pairs that need to be calculated for\n    # lookup\n    pairs = []\n\n    # make list of (qual case, qual ctrl) tuples for FET lookup table\n    for i in xrange(max_case + 1):\n        for j in xrange(max_ctrl + 1):\n            pairs.append((i, j))\n\n    # generate FET p-values for lookup table\n    pool = mp.Pool(processes=args.nprocs)\n    fisher_results = pool.map(\n        partial(precalc, num_case=ncase, num_ctrl=nctrl), pairs)\n    pool.close()\n    pool.join()\n\n    # populate shared memory FET lookup table\n    pool = mp.Pool(processes=args.nprocs)\n    pool.map(shared_mem, fisher_results)\n    pool.close()\n    pool.join()\n\n    # perform permutations to generate expected p-values\n    status_l = ['2'] * ncase\n    status_l.extend(['1'] * nctrl)\n    pool = mp.Pool(processes=args.nprocs)\n    permute_results = pool.map(\n        partial(permute, statuses=status_l), range(args.nperms))\n    pool.close()\n    pool.join()\n\n    # populate array of permuted p-values\n    perm_pvals = np.ones((ngenes, args.nperms))\n    for i, pvals in enumerate(permute_results):\n        perm_pvals[:, i] = pvals\n\n    # calculate 2.5%ile and 97.5%ile of permuted pvals\n    bottom_perc = np.percentile(perm_pvals, 2.5, axis=1)\n    top_perc = np.percentile(perm_pvals, 97.5, axis=1)\n\n    # calculate observed p-values\n    for gene, v in genes.iteritems():\n        qcase = int(v[3])\n        qctrl = int(v[6])\n        if qcase + 1 <= lookup.shape[0] and qctrl + 1 <= lookup.shape[1]:\n            v.append(lookup[qcase, qctrl])\n        else:\n            v.append(stats.fisher_exact(\n                [[qcase, ncase - qcase], [qctrl, nctrl - qctrl]])[1])\n    ordered = sorted(genes.items(), key=lambda x: x[1][-1])\n\n    # create sorted gene list\n    sorted_genes = [gene for gene, info in ordered]\n\n    # make arrays of ordered observed and expected p-values\n    obs_pvals = np.array([x[1][-1] for x in ordered])\n    exp_pvals = np.mean(perm_pvals, axis=1)\n\n    # generate qq plot\n    plot_qq(args.output, exp_pvals, obs_pvals, bottom_perc, top_perc, sorted_genes)\n", "meta": {"hexsha": "ed770085a4ca8a506d80d280922d8ba94082c241", "size": 13177, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/generate_qq.py", "max_stars_repo_name": "jhostyk/atav", "max_stars_repo_head_hexsha": "65413cadf276d3859b8894332275eb1b85c5cf6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-12-17T20:16:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T16:18:25.000Z", "max_issues_repo_path": "lib/generate_qq.py", "max_issues_repo_name": "jhostyk/atav", "max_issues_repo_head_hexsha": "65413cadf276d3859b8894332275eb1b85c5cf6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2016-08-16T21:48:41.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-11T18:37:57.000Z", "max_forks_repo_path": "lib/generate_qq.py", "max_forks_repo_name": "jhostyk/atav", "max_forks_repo_head_hexsha": "65413cadf276d3859b8894332275eb1b85c5cf6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-06-18T14:19:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T17:43:34.000Z", "avg_line_length": 38.7558823529, "max_line_length": 87, "alphanum_fraction": 0.6410412082, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.3208213138121609, "lm_q1q2_score": 0.1864944259177853}}
{"text": "import numpy as np\n\nfrom numba import boolean, float64, int64, njit, optional, uint8\nfrom numba.core.types.containers import Tuple\n\n\n__author__ = \"Peter Maxwell\"\n__copyright__ = \"Copyright 2007-2021, The Cogent Project\"\n__credits__ = [\"Peter Maxwell\", \"Gavin Huttley\", \"Stephen Ma\"]\n__license__ = \"BSD-3\"\n__version__ = \"2021.5.7a\"\n__maintainer__ = \"Gavin Huttley\"\n__email__ = \"Gavin.Huttley@anu.edu.au\"\n__status__ = \"Production\"\n\n\n@njit(\n    Tuple(types=(Tuple(types=(int64, int64)), int64, float64,))(\n        int64[::1],\n        int64[::1],\n        int64[::1],\n        int64,\n        int64,\n        int64,\n        int64,\n        optional(int64[::1]),\n        optional(int64[::1]),\n        optional(int64[::1]),\n        optional(int64[::1]),\n        int64[:, ::1],\n        float64[:, ::1],\n        float64[:, ::1],\n        float64[:, ::1],\n        float64[:, :, ::1],\n        optional(float64[:, :, ::1]),\n        float64,\n        optional(int64[:, :, ::1]),\n        optional(uint8[:, :, ::1]),\n        optional(int64[::1]),\n        boolean,\n        boolean,\n        boolean,\n        boolean,\n    ),\n    cache=True,\n)\ndef calc_rows(\n    plan,\n    x_index,\n    y_index,\n    i_low,\n    i_high,\n    j_low,\n    j_high,\n    i_sources,\n    i_sources_offsets,\n    j_sources,\n    j_sources_offsets,\n    state_directions,\n    T,\n    xgap_scores,\n    ygap_scores,\n    match_scores,\n    mantissas,\n    mantissa,\n    exponents,\n    track,\n    track_enc,\n    viterbi,\n    local=False,\n    use_scaling=False,\n    use_logs=False,\n):\n    assert not (use_logs and not viterbi)\n    assert not (use_logs and use_scaling)\n    assert not (local and not viterbi)\n\n    MIN_SCALE = -10000\n    MAX_SCALE = +10000\n    SCALE_STEP = 2.0 ** 50\n    MIN_FLOAT_VALUE = 1.0 / SCALE_STEP\n    source_row_index_cache = np.zeros(256)\n\n    N = max(T.shape[0], T.shape[1])\n\n    dest_states = max(0, state_directions.shape[0])\n\n    row_count = x_index.shape[0]\n    row_length = y_index.shape[0]\n\n    max_x = match_scores.shape[1]\n    max_y = match_scores.shape[2]\n\n    max_x = max(xgap_scores.shape[1], max_x)\n    max_y = max(ygap_scores.shape[1], max_y)\n\n    for i in range(row_count):\n        assert 0 <= x_index[i] <= max_x\n\n    for j in range(row_length):\n        assert 0 <= y_index[j] <= max_y\n\n    assert j_low >= 0 and j_high > j_low and j_high <= row_length\n\n    row_length = max(mantissas.shape[1], row_length)\n    N = max(mantissas.shape[2], N)\n\n    if use_scaling:\n        row_length = max(exponents.shape[1], row_length)\n        N = max(exponents.shape[2], N)\n\n    if use_logs:\n        impossible = -np.inf\n    else:\n        impossible = 0.0\n\n    if viterbi and track is not None and track_enc is not None:\n        N = max(track.shape[2], N)\n        (tcode_x, tcode_y, tcode_s) = track_enc\n    else:\n        track = None\n        tcode_x = tcode_y = tcode_s = 0\n\n    overall_max_exponent = MIN_SCALE\n    overall_max_mantissa = impossible\n    last_i = last_j = last_state = -1\n\n    max_exponent = MIN_SCALE\n\n    for i in range(i_low, i_high):\n        x = x_index[i]\n\n        i_sources_start = i_sources_offsets[i]\n        i_sources_end = i_sources_offsets[i + 1]\n\n        current_row_index = plan[i]\n        source_row_index_cache[0] = current_row_index\n\n        a_count = i_sources_end - i_sources_start\n        for a in range(a_count):\n            prev_i = i_sources[a + i_sources_start]\n            source_row_index_cache[a + 1] = plan[prev_i]\n\n        if i == 0:\n            if use_logs:\n                mantissas[current_row_index, 0, 0] = 0.0\n            else:\n                mantissas[current_row_index, 0, 0] = 1.0\n            if use_scaling:\n                exponents[current_row_index, 0, 0] = 0\n        else:\n            mantissas[current_row_index, 0, 0] = impossible\n            if use_scaling:\n                exponents[current_row_index, 0, 0] = MIN_SCALE\n\n        j_sources_end = j_sources_offsets[j_low]\n        for j in range(j_low, j_high):\n            j_sources_start = j_sources_end\n            j_sources_end = j_sources_offsets[j + 1]\n\n            for dest_state in range(dest_states):\n                state = state_directions[dest_state, 0]\n                bin = state_directions[dest_state, 1]\n                dx = state_directions[dest_state, 2]\n                dy = state_directions[dest_state, 3]\n\n                max_mantissa = impossible\n                max_exponent = MIN_SCALE\n                partial_sum = 0.0\n                pointer_state = N\n\n                if dx:\n                    a_low = 1\n                    a_high = a_count + 1\n                else:\n                    a_low = 0\n                    a_high = 1\n\n                if dy:\n                    b_low = 1\n                    b_high = j_sources_end - j_sources_start + 1\n                else:\n                    b_low = 0\n                    b_high = 1\n\n                pointer_a = 0\n                pointer_b = 0\n\n                if use_scaling:\n                    sub_partial_sum = 0.0\n\n                    for a in range(a_low, a_high):\n                        source_row_index = int(source_row_index_cache[a])\n                        for b in range(b_low, b_high):\n                            if dy:\n                                prev_j = j_sources[b - 1 + j_sources_start]\n                            else:\n                                prev_j = j\n                            min_prev_state = prev_j > 0\n\n                            for prev_state in range(min_prev_state, N):\n                                exponent = exponents[\n                                    source_row_index, prev_j, prev_state\n                                ]\n                                if exponent == MIN_SCALE:\n                                    continue\n\n                                transition = T[prev_state, state]\n\n                                mantissa = mantissas[\n                                    source_row_index, prev_j, prev_state\n                                ]\n                                mantissa *= transition\n\n                                if mantissa < MIN_FLOAT_VALUE:\n                                    if mantissa == 0.0:\n                                        continue\n                                    assert mantissa >= 0.0 and transition >= 0.0\n\n                                    while mantissa < MIN_FLOAT_VALUE:\n                                        mantissa *= SCALE_STEP\n                                        exponent += -1\n                                        assert exponent > MIN_SCALE\n\n                                elif mantissa > 1.0:\n                                    mantissa *= MIN_FLOAT_VALUE\n                                    exponent += 1\n                                    assert exponent <= MAX_SCALE\n\n                                if exponent > max_exponent:\n                                    if exponent == max_exponent + 1:\n                                        sub_partial_sum = partial_sum\n                                    else:\n                                        sub_partial_sum = 0.0\n                                    partial_sum = 0.0\n                                    max_mantissa = 0.0\n                                    max_exponent = exponent\n\n                                if exponent == max_exponent:\n                                    partial_sum += mantissa\n                                    if viterbi and mantissa > max_mantissa:\n                                        max_mantissa = mantissa\n                                        pointer_state = prev_state\n                                        pointer_a = a\n                                        pointer_b = b\n\n                                elif exponent == max_exponent - 1:\n                                    sub_partial_sum += mantissa\n\n                            partial_sum += sub_partial_sum * MIN_FLOAT_VALUE\n                else:\n                    for a in range(a_low, a_high):\n                        source_row_index = int(source_row_index_cache[a])\n                        for b in range(b_low, b_high):\n                            if dy:\n                                prev_j = j_sources[b - 1 + j_sources_start]\n                            else:\n                                prev_j = j\n                            min_prev_state = prev_j > 0\n\n                            for prev_state in range(min_prev_state, N):\n                                mantissa = mantissas[\n                                    source_row_index, prev_j, prev_state\n                                ]\n                                transition = T[prev_state, state]\n                                if use_logs:\n                                    mantissa += transition\n                                else:\n                                    mantissa *= transition\n                                    partial_sum += mantissa\n                                if viterbi and mantissa > max_mantissa:\n                                    max_mantissa = mantissa\n                                    pointer_state = prev_state\n                                    pointer_a = a\n                                    pointer_b = b\n\n                if viterbi:\n                    mantissa = max_mantissa\n                    if track is not None:\n                        track[i, j, state] = (\n                            (pointer_a << tcode_x)\n                            | (pointer_b << tcode_y)\n                            | (pointer_state << tcode_s)\n                        )\n                else:\n                    mantissa = partial_sum\n\n                if dy:\n                    y = y_index[j]\n                    if dx:\n                        d_score = match_scores[bin, x, y]\n                    else:\n                        d_score = ygap_scores[bin, y]\n                elif dx:\n                    d_score = xgap_scores[bin, x]\n                elif use_logs:\n                    d_score = 0.0\n                else:\n                    d_score = 1.0\n\n                if use_logs:\n                    mantissa += d_score\n                else:\n                    mantissa *= d_score\n\n                mantissas[current_row_index, j, state] = mantissa\n\n                if use_scaling:\n                    exponents[current_row_index, j, state] = max_exponent\n\n                if local and dx and dy:\n                    if (use_scaling and max_exponent > overall_max_exponent) or (\n                        (not use_scaling or max_exponent == overall_max_exponent)\n                        and (mantissa > overall_max_mantissa)\n                    ):\n                        overall_max_exponent = max_exponent\n                        overall_max_mantissa = mantissa\n                        last_i = i\n                        last_j = j\n                        last_state = state\n\n    if not local:\n        last_i = i_high - 1\n        last_j = j_high - 1\n        last_state = state\n    else:\n        mantissa = overall_max_mantissa\n        max_exponent = overall_max_exponent\n\n    if use_scaling:\n        score = np.log(mantissa) + np.log(SCALE_STEP) * max_exponent\n    elif use_logs:\n        score = mantissa\n    else:\n        score = np.log(mantissa)\n    return ((last_i, last_j), last_state, score)\n", "meta": {"hexsha": "db5589687b575c2332a6507bcdb45ebccf6a4e32", "size": 11254, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/cogent3/align/pairwise_pogs_numba.py", "max_stars_repo_name": "jamesmartini/cogent3", "max_stars_repo_head_hexsha": "5d0aab1871561aa3d4cd6b629be6cc7a23f15c49", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cogent3/align/pairwise_pogs_numba.py", "max_issues_repo_name": "jamesmartini/cogent3", "max_issues_repo_head_hexsha": "5d0aab1871561aa3d4cd6b629be6cc7a23f15c49", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cogent3/align/pairwise_pogs_numba.py", "max_forks_repo_name": "jamesmartini/cogent3", "max_forks_repo_head_hexsha": "5d0aab1871561aa3d4cd6b629be6cc7a23f15c49", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3946587537, "max_line_length": 81, "alphanum_fraction": 0.4455304781, "include": true, "reason": "import numpy,from numba", "num_tokens": 2370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.32082131381216084, "lm_q1q2_score": 0.1864944166093711}}
{"text": "import os\nimport warnings\nimport numpy as np\nfrom pyrates.utility.genetic_algorithm import CGSGeneticAlgorithm\nfrom pandas import DataFrame, read_hdf\nfrom copy import deepcopy\n\n\nclass CustomGOA(CGSGeneticAlgorithm):\n\n    def eval_fitness(self, target: list, **kwargs):\n\n        # define simulation conditions\n        worker_file = self.cgs_config['worker_file'] if 'worker_file' in self.cgs_config else None\n        param_grid = self.pop.drop(['fitness', 'sigma', 'results'], axis=1)\n        result_vars = ['r_e', 'r_i', 'r_a']\n        freq_targets = [0.0, 0.0, 0.0, 0.0, np.nan]\n        #param_grid, invalid_params = eval_params(param_grid)\n        conditions = [{},  # healthy control\n                      {'k_pe': 0.2, 'k_ae': 0.2},  # AMPA blockade in GPe\n                      {'k_pe': 0.2, 'k_pp': 0.2, 'k_pa': 0.2, 'k_ae': 0.2, 'k_aa': 0.2, 'k_ap': 0.2,\n                       'k_ps': 0.2, 'k_as': 0.2},  # AMPA blockade and GABAA blockade in GPe\n                      {'k_pp': 0.2, 'k_pa': 0.2, 'k_aa': 0.2, 'k_ap': 0.2, 'k_ps': 0.2,\n                       'k_as': 0.2},  # GABAA blockade in GPe\n                      #{'k_pe': 0.0, 'k_ae': 0.0},  # STN blockade\n                      #{'k_pe': 0.0, 'k_ae': 0.0, 'k_pp': 0.2, 'k_pa': 0.2, 'k_aa': 0.2, 'k_ap': 0.2,\n                      # 'k_ps': 0.2, 'k_as': 0.2},  # STN blockade + GABAA blockade in GPe\n                      {'k_ep': 0.2}  # GABAA blocker in STN\n                      ]\n        param_scalings = [\n            ('delta_e', 'tau_e', 2.0),\n            ('delta_p', 'tau_p', 2.0),\n            ('delta_a', 'tau_a', 2.0),\n            ('k_ee', 'delta_e', 0.5),\n            ('k_ep', 'delta_e', 0.5),\n            ('k_pe', 'delta_p', 0.5),\n            ('k_pp', 'delta_p', 0.5),\n            ('k_pa', 'delta_p', 0.5),\n            ('k_ps', 'delta_p', 0.5),\n            ('k_ae', 'delta_a', 0.5),\n            ('k_ap', 'delta_a', 0.5),\n            ('k_aa', 'delta_a', 0.5),\n            ('k_as', 'delta_a', 0.5),\n            ('eta_e', 'delta_e', 1.0),\n            ('eta_p', 'delta_p', 1.0),\n            ('eta_a', 'delta_a', 1.0),\n            ]\n        chunk_size = [\n            #60,  # carpenters\n            200,  # osttimor\n            150,  # spanien\n            #100,  # animals\n            100,  # kongo\n            100,  # tschad\n            150,  # uganda\n            100,  # tiber\n            150,  # giraffe\n            100,  # lech\n            50,  # rilke\n            50,  # dinkel\n            #10,  # rosmarin\n            #10,  # mosambik\n        ]\n\n        # perform simulations\n        if len(param_grid) > 0:\n            self.gs_config['init_kwargs'].update(kwargs)\n            res_file = self.cgs.run(\n                circuit_template=self.gs_config['circuit_template'],\n                param_grid=deepcopy(param_grid),\n                param_map=self.gs_config['param_map'],\n                simulation_time=self.gs_config['simulation_time'],\n                dt=self.gs_config['step_size'],\n                inputs=self.gs_config['inputs'],\n                outputs=self.gs_config['outputs'],\n                sampling_step_size=self.gs_config['sampling_step_size'],\n                permute=False,\n                chunk_size=chunk_size,\n                worker_file=worker_file,\n                worker_env=self.cgs_config['worker_env'],\n                gs_kwargs={'init_kwargs': self.gs_config['init_kwargs'], 'conditions': conditions,\n                           'param_scalings': param_scalings},\n                worker_kwargs={'freq_targets': freq_targets, 'y': target, 'time_lim': 5400.0, 'cpu_lim': False,\n                               'nproc_lim': False, 'memory_lim': False, 'T': self.gs_config['simulation_time']},\n                result_concat_axis=0)\n            results_tmp = read_hdf(res_file, key=f'Results/results')\n\n            # calculate fitness\n            for gene_id in param_grid.index:\n                self.pop.at[gene_id, 'fitness'] = 1.0 / results_tmp.at[gene_id, 'fitness']\n                self.pop.at[gene_id, 'results'] = [results_tmp.at[gene_id, v] for v in result_vars]\n\n        # set fitness of invalid parametrizations\n        #for gene_id in invalid_params.index:\n        #    self.pop.at[gene_id, 'fitness'] = 0.0\n        #    self.pop.at[gene_id, 'results'] = [0. for _ in result_vars]\n\n\ndef fitness(y, t):\n    y = np.asarray(y).flatten()\n    t = np.asarray(t).flatten()\n    diff = np.asarray([0.0 if np.isnan(t_tmp) else y_tmp - t_tmp for y_tmp, t_tmp in zip(y, t)]).flatten()**2\n    t[np.isnan(t)] = 1.0\n    t[t == 0] = 1.0\n    weights = 1/np.abs(t)\n    return weights @ diff\n\n\nif __name__ == \"__main__\":\n    warnings.filterwarnings(\"ignore\")\n\n    pop_size = 2048\n    pop_genes = {\n        'k_ee': {'min': 0, 'max': 6, 'size': pop_size, 'sigma': 0.2, 'loc': 4.0, 'scale': 1.0},\n        'k_ae': {'min': 1, 'max': 100, 'size': pop_size, 'sigma': 1.0, 'loc': 50.0, 'scale': 5.0},\n        'k_pe': {'min': 1, 'max': 100, 'size': pop_size, 'sigma': 1.0, 'loc': 50.0, 'scale': 5.0},\n        'k_pp': {'min': 0, 'max': 6, 'size': pop_size, 'sigma': 0.2, 'loc': 3.0, 'scale': 1.0},\n        'k_ep': {'min': 1, 'max': 100, 'size': pop_size, 'sigma': 1.0, 'loc': 30.0, 'scale': 3.0},\n        'k_ap': {'min': 1, 'max': 100, 'size': pop_size, 'sigma': 1.0, 'loc': 50.0, 'scale': 5.0},\n        'k_aa': {'min': 0, 'max': 6, 'size': pop_size, 'sigma': 0.2, 'loc': 3.0, 'scale': 1.0},\n        'k_pa': {'min': 1, 'max': 100, 'size': pop_size, 'sigma': 1.0, 'loc': 50.0, 'scale': 5.0},\n        'k_ps': {'min': 3, 'max': 300, 'size': pop_size, 'sigma': 2.0, 'loc': 100.0, 'scale': 10.0},\n        'k_as': {'min': 3, 'max': 300, 'size': pop_size, 'sigma': 2.0, 'loc': 100.0, 'scale': 10.0},\n        'eta_e': {'min': -4, 'max': 4, 'size': pop_size, 'sigma': 0.1, 'loc': 0.0, 'scale': 1.0},\n        'eta_p': {'min': -4, 'max': 4, 'size': pop_size, 'sigma': 0.1, 'loc': 0.0, 'scale': 1.0},\n        'eta_a': {'min': -6, 'max': 2, 'size': pop_size, 'sigma': 0.1, 'loc': -1.0, 'scale': 1.0},\n        'delta_e': {'min': 0.02, 'max': 0.06, 'size': pop_size, 'sigma': 0.005, 'loc': 0.04, 'scale': 0.01},\n        'delta_p': {'min': 0.15, 'max': 0.35, 'size': pop_size, 'sigma': 0.01, 'loc': 0.2, 'scale': 0.05},\n        'delta_a': {'min': 0.05, 'max': 0.15, 'size': pop_size, 'sigma': 0.01, 'loc': 0.1, 'scale': 0.05},\n        'tau_e': {'min': 13, 'max': 13, 'size': pop_size, 'sigma': 0.0, 'loc': 13.0, 'scale': 0.0},\n        'tau_p': {'min': 25, 'max': 25, 'size': pop_size, 'sigma': 0.0, 'loc': 25.0, 'scale': 0.0},\n        'tau_a': {'min': 20, 'max': 20, 'size': pop_size, 'sigma': 0.0, 'loc': 20.0, 'scale': 0.0},\n    }\n\n    param_map = {\n        'k_ee': {'vars': ['weight'], 'edges': [('stn', 'stn')]},\n        'k_ae': {'vars': ['weight'], 'edges': [('stn', 'gpe_a')]},\n        'k_pe': {'vars': ['weight'], 'edges': [('stn', 'gpe_p')]},\n        'k_pp': {'vars': ['weight'], 'edges': [('gpe_p', 'gpe_p')]},\n        'k_ep': {'vars': ['weight'], 'edges': [('gpe_p', 'stn')]},\n        'k_ap': {'vars': ['weight'], 'edges': [('gpe_p', 'gpe_a')]},\n        'k_aa': {'vars': ['weight'], 'edges': [('gpe_a', 'gpe_a')]},\n        'k_pa': {'vars': ['weight'], 'edges': [('gpe_a', 'gpe_p')]},\n        'k_ps': {'vars': ['weight'], 'edges': [('str', 'gpe_p')]},\n        'k_as': {'vars': ['weight'], 'edges': [('str', 'gpe_a')]},\n        'eta_e': {'vars': ['stn_op/eta_e'], 'nodes': ['stn']},\n        'eta_p': {'vars': ['gpe_proto_op/eta_i'], 'nodes': ['gpe_p']},\n        'eta_a': {'vars': ['gpe_arky_op/eta_a'], 'nodes': ['gpe_a']},\n        'delta_e': {'vars': ['stn_op/delta_e'], 'nodes': ['stn']},\n        'delta_p': {'vars': ['gpe_proto_op/delta_i'], 'nodes': ['gpe_p']},\n        'delta_a': {'vars': ['gpe_arky_op/delta_a'], 'nodes': ['gpe_a']},\n        'tau_e': {'vars': ['stn_op/tau_e'], 'nodes': ['stn']},\n        'tau_p': {'vars': ['gpe_proto_op/tau_i'], 'nodes': ['gpe_p']},\n        'tau_a': {'vars': ['gpe_arky_op/tau_a'], 'nodes': ['gpe_a']},\n    }\n\n    T = 200.0\n    dt = 1e-2\n    dts = 1e-1\n\n    # perform genetic optimization\n    compute_dir = f\"{os.getcwd()}/stn_gpe_healthy_opt\"\n\n    ga = CustomGOA(fitness_measure=fitness,\n                   gs_config={\n                       'circuit_template': f\"{os.getcwd()}/config/stn_gpe/stn_gpe\",\n                       'permute_grid': True,\n                       'param_map': param_map,\n                       'simulation_time': T,\n                       'step_size': dt,\n                       'sampling_step_size': dts,\n                       'inputs': {},\n                       'outputs': {'r_e': \"stn/stn_op/R_e\",\n                                   'r_i': 'gpe_p/gpe_proto_op/R_i',\n                                   'r_a': 'gpe_a/gpe_arky_op/R_a'},\n                       'init_kwargs': {'backend': 'numpy', 'solver': 'scipy', 'step_size': dt},\n                   },\n                   cgs_config={'nodes': [\n                                           #'carpenters',\n                                           'osttimor',\n                                           'spanien',\n                                           #'animals',\n                                           'kongo',\n                                           'tschad',\n                                           'uganda',\n                                           'tiber',\n                                           'giraffe',\n                                           'lech',\n                                           'rilke',\n                                           'dinkel',\n                                           #'rosmarin',\n                                           #'mosambik',\n                                         ],\n                               'compute_dir': compute_dir,\n                               'worker_file': f'{os.getcwd()}/stn_gpe_healthy_worker.py',\n                               'worker_env': \"/data/u_rgast_software/anaconda3/envs/pyrates/bin/python3\",\n                               })\n\n    drop_save_dir = f'{compute_dir}/PopulationDrops/'\n    os.makedirs(drop_save_dir, exist_ok=True)\n\n    winner = ga.run(\n        initial_gene_pool=pop_genes,\n        gene_sampling_func=np.random.normal,\n        new_member_sampling_func=np.random.uniform,\n        target=[[19, 62, 31],  # healthy control\n                [np.nan, 35, np.nan],  # ampa blockade in GPe\n                [np.nan, 76, np.nan],  # ampa and gabaa blockade in GPe\n                [np.nan, 135, np.nan],  # GABAA blockade in GPe\n                #[np.nan, 30, np.nan],  # STN blockade\n                #[np.nan, 60, np.nan],  # STN blockade + gabaa blockade in GPe\n                [35, 124, np.nan]  # GABAA blockade in STN\n                ],\n        max_iter=500,\n        enforce_max_iter=True,\n        min_fit=1.0,\n        n_winners=30,\n        n_parent_pairs=120,\n        n_new=248,\n        sigma_adapt=0.05,\n        candidate_save=f'{compute_dir}/GeneticCGSCandidatestn.h5',\n        drop_save=drop_save_dir,\n        new_pop_on_drop=True,\n        pop_save=f'{drop_save_dir}/pop_summary',\n        permute=False,\n        max_stagnation_steps=5,\n        stagnation_decimals=3\n    )\n    #winner.to_hdf(f'{drop_save_dir}/winner.h5', key='data')\n", "meta": {"hexsha": "07cf8819f40180374c8656e20c0db85fab718ec8", "size": 11142, "ext": "py", "lang": "Python", "max_stars_repo_path": "BasalGanglia/stn_gpe_healthy_opt.py", "max_stars_repo_name": "Richert/BrainNetworks", "max_stars_repo_head_hexsha": "52119446191dabf0fcef2d3dda203c9fb5730c7d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BasalGanglia/stn_gpe_healthy_opt.py", "max_issues_repo_name": "Richert/BrainNetworks", "max_issues_repo_head_hexsha": "52119446191dabf0fcef2d3dda203c9fb5730c7d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BasalGanglia/stn_gpe_healthy_opt.py", "max_forks_repo_name": "Richert/BrainNetworks", "max_forks_repo_head_hexsha": "52119446191dabf0fcef2d3dda203c9fb5730c7d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.4434782609, "max_line_length": 112, "alphanum_fraction": 0.4640998025, "include": true, "reason": "import numpy", "num_tokens": 3459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371502, "lm_q2_score": 0.3208212878370535, "lm_q1q2_score": 0.18649440150996127}}
{"text": "\"\"\"\nTask:           Meta-Path Based Random Walk\nCoder:          Haoyu Huang\nSource Data:    Foursquare\nthe slow version\n\"\"\"\nimport time\nimport datetime\nimport argparse\nimport numpy as np\nimport pickle as pickle\nfrom collections import Counter\nimport collections\nfrom math import radians, cos, sin, asin, sqrt\nfrom tqdm import tqdm\n\n\nclass MPBasedRandomWalk:\n    def __init__(self, meta_path, walk_length, walk_num, data):\n        self.meta_path = meta_path\n        self.walk_length = walk_length\n        self.walk_num = walk_num\n        self.data = data\n\n        self.tmp_path = \"../data\"\n        self.triple_pc_path = self.tmp_path + \"/triple_pc.txt\"\n        self.triple_ptp_path = self.tmp_path + \"/triple_ptp.txt\"\n        self.triple_utp_path = self.tmp_path + \"/triple_utp.txt\"\n\n        self.word_loc_adlist = {}\n        self.loc_word_adlist = {}  # for convenience\n        self.user_loc_adlist = {}\n        self.loc_user_adlist = {}  # for convenience\n        self.loc_loc_adlist = {}  # dict的dict\n        self.loc2neighbor_LL_dict = {}\n        self.loc2neighbor_LUL_dict = {}\n        self.loc2neighbor_LVL_dict = {}\n        self.loc2neighbor_dict = {}  # 上面三者的merge\n        self.loc2paths_LL_dict = {}\n        self.loc2paths_LUL_dict = {}\n        self.loc2paths_LVL_dict = {}\n        self.v = {}\n\n    # load data from three triple file,或者可以理解为生成各自的转移矩阵\n    def make_adlist(self):\n        print('Reading ptp file:\\n')\n        with open(self.triple_ptp_path, 'r') as f:\n            for line in f:\n                line = line.strip('\\n').split('\\t')\n                pid1, _, pid2 = line  # 无向图，pid1->pid2 and pid2->pid1\n                if pid1 not in self.loc_loc_adlist:\n                    self.loc_loc_adlist.update({pid1: {pid2: 1}})\n                    if pid2 not in self.loc_loc_adlist:\n                        self.loc_loc_adlist.update({pid2: {pid1: 1}})\n                    else:\n                        if pid1 not in self.loc_loc_adlist[pid2]:\n                            self.loc_loc_adlist[pid2].update({pid1: 1})\n                        else:\n                            self.loc_loc_adlist[pid2][pid1] += 1\n                else:\n                    if pid2 not in self.loc_loc_adlist[pid1]:\n                        self.loc_loc_adlist[pid1].update({pid2: 1})\n                    else:\n                        self.loc_loc_adlist[pid1][pid2] += 1\n\n        print(\"Reading utp file:\\n\")\n        with open(self.triple_utp_path, 'r') as f:\n            for line in f:\n                line = line.strip('\\n').split('\\t')\n                uid, _, pid = line\n                if uid not in self.user_loc_adlist:\n                    self.user_loc_adlist.update({uid: {pid: 1}})\n                    if pid not in self.loc_user_adlist:\n                        self.loc_user_adlist.update({pid: {uid: 1}})\n                    else:\n                        if uid not in self.loc_user_adlist[pid]:\n                            self.loc_user_adlist[pid].update({uid: 1})\n                        else:\n                            self.loc_user_adlist[pid][uid] += 1\n                else:\n                    if pid not in self.user_loc_adlist[uid]:\n                        self.user_loc_adlist[uid].update({pid: 1})\n                    else:\n                        self.user_loc_adlist[uid][pid] += 1\n\n        print(\"Reading pc file:\\n\")\n        with open(self.triple_pc_path, 'r') as f:\n            for line in f:\n                line = line.strip('\\n').split('\\t')\n                pid, _, wid = line\n                if pid not in self.loc_word_adlist:\n                    self.loc_word_adlist.update({pid: {wid: 1}})\n                    if wid not in self.word_loc_adlist:\n                        self.word_loc_adlist.update({wid: {pid: 1}})\n                    else:\n                        if pid not in self.word_loc_adlist[wid]:\n                            self.word_loc_adlist[wid].update({pid: 1})\n                        else:\n                            self.word_loc_adlist[wid][pid] += 1\n                else:\n                    if wid not in self.loc_word_adlist[pid]:\n                        self.loc_word_adlist[pid].update({pid: 1})\n                    else:\n                        self.loc_word_adlist[pid][wid] += 1  # 逻辑上讲不可能出现这样的情况\n\n    # 生成一个单一类型元素的dict\n    def make_vec(self, keys):\n        result = dict()\n        for key in keys:\n            result.update({key: 1})\n        return result\n\n    # 对单一类型的元素dict进行平均分布\n    def nom_vec(self, vec):\n        tmp_vec = vec.copy()  # 不改变原本数据\n        total = sum(tmp_vec.values())\n        for key in tmp_vec.keys():\n            tmp_vec[key] = float(tmp_vec[key]) / total\n        return tmp_vec\n\n    # 起始的向量，只有一个起始点loc，也就是只有这一个元素为1\n    def begin_vec(self, vec, begin):\n        tmp_vec = vec.copy()\n        for key in tmp_vec.keys():\n            if key == begin:\n                tmp_vec[key] = float(1)\n            else:\n                tmp_vec[key] = float(0)\n        return tmp_vec\n\n    # 对adlist进行平均分布，也就是概率\n    def nom_adlist(self, adlist):\n        tmp_adlist = adlist.copy()                      # value->key,为什么以有向图的方式存，因为要方便不同种类的entity进行转移\n\n        for key1 in tqdm(tmp_adlist.keys()):            # 遍历所有的node（5000）\n            count = 0\n            for key2 in tmp_adlist.keys():              # 再次遍历所有的node, 计算key1的出度count\n                if key1 in tmp_adlist[key2]:\n                    count += 1\n            for key2 in tmp_adlist.keys():              # key1->key2，1/key1的出度\n                if key1 in tmp_adlist[key2]:\n                    tmp_adlist[key2][key1] = float(tmp_adlist[key2][key1]) / count\n\n        return tmp_adlist                               # 返回的结果是转移矩阵\n\n    # 矩阵与向量相乘 (n,n)·(n,1)=(n,1),<too slow>\n    def adlist_vec_multiply(self, adlist, vec):\n        result = dict()\n        for key1 in adlist.keys():\n            tmp1 = adlist[key1]                         # 是所有指向key1的node\n            tmp_sum = 0\n            for key2 in vec.keys():                     # 遍历向量的每一个元素\n                if key2 in tmp1:                        # 如果说向量的这个位置所对应的node，在矩阵的这一行中存在，就讲这两个值相乘\n                    tmp_sum += tmp1[key2] * vec[key2]   # 矩阵这一行的乘积加起来，没有的就是0，得到结果向量的某个位置的值\n            result.update({key1: tmp_sum})\n        return result\n\n    # 决定元路径\n    def method(self):\n        if self.meta_path == 'LL':\n            for pid in tqdm(self.loc_loc_adlist):\n                total_paths = self.run_with_LL(pid)\n                self.loc2paths_LL_dict[pid] = total_paths\n        # elif self.meta_path == 'LVL':\n            for pid in tqdm(self.loc_loc_adlist):\n                total_paths = self.run_with_LVL(pid)\n                self.loc2paths_LVL_dict[pid] = total_paths\n        # elif self.meta_path == 'LUL':\n            for pid in tqdm(self.loc_loc_adlist):\n                total_paths = self.run_with_LUL(pid)\n                self.loc2paths_LUL_dict[pid] = total_paths\n\n    # 三类随机游走的实现\n    def run_with_LL(self, pid):\n        print('LL based random walk:')\n        self.loc_loc_adlist = self.nom_adlist(self.loc_loc_adlist)\n        # self.v = self.nom_vec(self.make_vec(self.loc_loc_adlist.keys()))\n        total_paths = []\n        for i in range(self.walk_num):\n            self.v = self.begin_vec(self.make_vec(self.loc_loc_adlist.keys()), pid)\n            path = [pid]\n            for j in range(self.walk_length):                                                 # walk_length长度的path\n                self.v = self.adlist_vec_multiply(self.loc_loc_adlist, self.v)\n                tmp_vec = np.array(list(self.nom_vec(self.v).values()))                       # 以当前的权重向量为权重进行random walk下一跳的选择\n                next_pid = np.random.choice(list(self.v.keys()), p=tmp_vec.ravel())\n                path.append(next_pid)\n                self.v = self.begin_vec(self.make_vec(self.loc_loc_adlist.keys()), next_pid)  # 重置起点\n            total_paths.append(path)\n        return total_paths\n\n    def run_with_LUL(self, pid):\n        print('LUL based random walk:')\n        self.user_loc_adlist = self.nom_adlist(self.user_loc_adlist)\n        self.loc_user_adlist = self.nom_adlist(self.loc_user_adlist)\n        total_paths = []\n        for i in range(self.walk_num):\n            self.v = self.begin_vec(self.make_vec(self.loc_loc_adlist.keys()), pid)                # 依然将pid作为起点,loc的起点权重向量\n            path = [pid]\n            for j in range(self.walk_length):\n                self.v = self.adlist_vec_multiply(self.user_loc_adlist, self.v)                # L->U\n                tmp_vec = np.array(list(self.nom_vec(self.v).values()))                        # 得到下一个uid的分布权重\n                next_uid = np.random.choice(list(self.v.keys()), p=tmp_vec.ravel())            # 找到置信uid\n                path.append(next_uid)\n                self.v = self.begin_vec(self.make_vec(self.user_loc_adlist.keys()), next_uid)  # user的起点权重向量\n                self.v = self.adlist_vec_multiply(self.loc_user_adlist, self.v)                # U->L\n                tmp_vec = np.array(list(self.nom_vec(self.v).values()))                        # 得到下一个pid的分布权重\n                next_pid = np.random.choice(list(self.v.keys()), p=tmp_vec.ravel())            # 找到置信pid\n                path.append(next_pid)\n                self.v = self.begin_vec(self.make_vec(self.loc_user_adlist.keys()), next_uid)  # loc的起点权重向量\n            total_paths.append(path)\n        return total_paths\n\n    def run_with_LVL(self, pid):\n        print('LVL based random walk:')\n        self.loc_word_adlist = self.nom_adlist(self.loc_word_adlist)\n        self.word_loc_adlist = self.nom_adlist(self.word_loc_adlist)\n        total_paths = []\n        for i in range(self.walk_length):\n            self.v = self.begin_vec(self.make_vec(self.loc_loc_adlist.keys()), pid)\n            path = [pid]\n            for j in range(self.walk_length):\n                self.v = self.adlist_vec_multiply(self.word_loc_adlist, self.v)                # L->V\n                tmp_vec = np.array(list(self.nom_vec(self.v).values()))\n                next_wid = np.random.choice(list(self.v.keys()), p=tmp_vec.ravel())\n                path.append(next_wid)\n                self.v = self.begin_vec(self.make_vec(self.word_loc_adlist.keys()), next_wid)\n                self.v = self.adlist_vec_multiply(self.loc_word_adlist, self.v)                # V->L\n                tmp_vec = np.array(list(self.nom_vec(self.v).values()))\n                next_pid = np.random.choice(list(self.v.keys()), p=tmp_vec.ravel())\n                path.append(next_pid)\n                self.v = self.begin_vec(self.make_vec(self.loc_word_adlist.keys()), next_wid)\n            total_paths.append(path)\n        return total_paths\n\n    def save_variables(self):\n        paths = {'LL': self.loc2paths_LL_dict, 'LUL': self.loc2paths_LUL_dict, 'LVL': self.loc2paths_LVL_dict}\n        pickle.dump(paths, open(self.tmp_path + 'paths' + '.pkl', 'wb'))\n\n\nif __name__ == '__main__':\n    generator = MPBasedRandomWalk(meta_path='LL', walk_length=10, walk_num=50, data=[])\n    generator.make_adlist()\n    generator.method()\n", "meta": {"hexsha": "eb393d5790c0d63f4d9a4de778f03a05a5e0cee5", "size": 10986, "ext": "py", "lang": "Python", "max_stars_repo_path": "MPBRW_with_dict.py", "max_stars_repo_name": "hhy-huang/Meta-Path-Based-Random-Walk", "max_stars_repo_head_hexsha": "0fbafc3765ce055c515de3d04436e03fd4d1a528", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-18T11:49:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T11:49:47.000Z", "max_issues_repo_path": "MPBRW_with_dict.py", "max_issues_repo_name": "hhy-huang/Meta-Path-Based-Random-Walk", "max_issues_repo_head_hexsha": "0fbafc3765ce055c515de3d04436e03fd4d1a528", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MPBRW_with_dict.py", "max_forks_repo_name": "hhy-huang/Meta-Path-Based-Random-Walk", "max_forks_repo_head_hexsha": "0fbafc3765ce055c515de3d04436e03fd4d1a528", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.0245901639, "max_line_length": 126, "alphanum_fraction": 0.5433278718, "include": true, "reason": "import numpy", "num_tokens": 2840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.32082128783705344, "lm_q1q2_score": 0.18649440150996127}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jan  8 14:38:46 2021\r\n\r\nreduce temp layer and add prev cracking rates\r\n\r\n@author: Shih-Cheng Li\r\n\"\"\"\r\nfrom silence_tensorflow import silence_tensorflow\r\nsilence_tensorflow()\r\nfrom cantera import Species, one_atm, Solution, IdealGasReactor, MassFlowController, Reservoir, SolutionArray, MassFlowController, PressureController, ReactorNet\r\nfrom numpy import zeros, arange, zeros_like, sum, hstack\r\nfrom argparse import ArgumentParser\r\nfrom keras import optimizers\r\nfrom keras import losses\r\nfrom keras.models import Model\r\nfrom keras.layers import Input, Dense, Activation, concatenate\r\nfrom pickle import load\r\nfrom cantera import add_directory\r\nimport sys\r\nfrom os.path import dirname,join\r\nBASE_DIR=dirname(__file__)\r\nif getattr(sys, 'frozen', False):\r\n    BASE_DIR = sys._MEIPASS\r\n\r\nelse:\r\n    BASE_DIR = dirname(__file__) \r\ndef build_model(lr=0.001):\r\n    first_input = Input(shape=(2,), name='Input_layer_1')\r\n    second_input = Input(shape=(33,), name='Input_layer_2')\r\n    third_input = Input(shape=(1,), name='Prev_cracking')\r\n\r\n    layer = Dense(6, name='Hinden_layer_1')(first_input)\r\n    layer = Activation('relu')(layer)\r\n\r\n    layer = concatenate([layer, second_input], name='Concatenate_layer')\r\n    layer = Activation('relu')(layer)\r\n    layer = Dense(12, name='Hinden_layer_4')(layer)\r\n    layer = Activation('relu')(layer)\r\n    layer = Dense(12, name='Hinden_layer_5')(layer)\r\n    layer = Activation('relu')(layer)\r\n    layer = concatenate([layer, third_input], name='Concatenate_layer_2')\r\n    layer = Dense(1, name='Hinden_layer_6')(layer)\r\n    output = Activation('sigmoid')(layer)\r\n\r\n    model = Model(inputs=[first_input, second_input, third_input],\r\n                  outputs=output)\r\n    model.compile(optimizer=optimizers.Adam(lr=lr),\r\n                  loss=losses.mean_absolute_error,\r\n                  metrics=['accuracy', 'mae'])\r\n    return model\r\n\r\n\r\ndef EDC_cracking(\r\n        reaction_mech,\r\n        T_list,\r\n        pressure_0,\r\n        CCl4_X_0,\r\n        mass_flow_rate,\r\n        n_steps=1000,\r\n        n_pfr=18,\r\n        length=18,\r\n        area=0.03225097679\r\n):\r\n    \"\"\"\r\n    Module that runs a single PFR Cantera simulation via a series of CSTRs.\r\n    The Plug flow reactor is represented by a linear chain of zero-dimensional\r\n    reactors. The gas at the inlet to the first one has the specified inlet\r\n    composition, and for all others the inlet composition is fixed at the\r\n    composition of the reactor immediately upstream. Since in a PFR model there\r\n    is no diffusion, the upstream reactors are not affected by any downstream\r\n    reactors, and therefore the problem may be solved by simply marching from\r\n    the first to last reactor, integrating each one to steady state.\r\n    Parameters\r\n    =============== =============================================================\r\n    Attribute       Description\r\n    =============== =============================================================\r\n    `reaction_mech` Cantera reaction mechanism (.cti file)\r\n    `T_list`        Temperature profile (°C)\r\n    `pressure_0`    Initial pressue (atm)\r\n    `CCl4_X_0`      Initial CCl4 concentration (mass fraction)\r\n    `mass_flow_rate`Mass flow rate of input gas (T/H)      \r\n    `n_steps`       Number of iterations/number of CSTRs\r\n    `n_pfr`         Number of PFRs\r\n    `length`        Length of each PFR (m)\r\n    `area`          Cross-sectional area (m**2)\r\n    `label`         Label of this mechanism\r\n    =============== =============================================================\r\n\r\n\r\n    \"\"\"\r\n    #######################################################################\r\n    # Input Parameters\r\n    #######################################################################\r\n    if CCl4_X_0 > 1:  # ppm\r\n        CCl4_X_0 = float(CCl4_X_0) / 1000000\r\n    T_0 = 273.15 + T_list[0]  # inlet temperature [K]\r\n    pressure_0 *= one_atm\r\n    spcs = Species.listFromFile(reaction_mech)\r\n    for spc in spcs[::-1]:\r\n        if spc.composition == {'C': 2.0, 'Cl': 2.0, 'H': 4.0} and spc.charge == 0:\r\n            EDC_label = spc.name\r\n        if spc.composition == {'C': 1.0, 'Cl': 4.0} and spc.charge == 0:\r\n            CCl4_label = spc.name\r\n    EDC_X_0 = 1 - CCl4_X_0\r\n    composition_0 = '{}:{}, {}:{}'.format(\r\n        EDC_label, EDC_X_0, CCl4_label, CCl4_X_0)\r\n    mass_flow_rate *= 1000 / 3600  # T/H to kg/s\r\n\r\n    # import the gas model and set the initial conditions\r\n    model = Solution(reaction_mech)\r\n    model.TPX = T_0, pressure_0, composition_0\r\n    dz = length / n_steps\r\n    r_vol = area * dz\r\n\r\n    # create a new reactor\r\n    r = IdealGasReactor(model)\r\n    r.volume = r_vol\r\n\r\n    # create a reservoir to represent the reactor immediately upstream. Note\r\n    # that the gas object is set already to the state of the upstream reactor\r\n    upstream = Reservoir(model, name='upstream')\r\n\r\n    # create a reservoir for the reactor to exhaust into. The composition of\r\n    # this reservoir is irrelevant.\r\n    downstream = Reservoir(model, name='downstream')\r\n\r\n    # The mass flow rate into the reactor will be fixed by using a\r\n    # MassFlowController object.\r\n    m = MassFlowController(upstream, r, mdot=mass_flow_rate)\r\n\r\n    # We need an outlet to the downstream reservoir. This will determine the\r\n    # pressure in the reactor. The value of K will only affect the transient\r\n    # pressure difference.\r\n    v = PressureController(r, downstream, master=m, K=1e-5)\r\n\r\n    sim = ReactorNet([r])\r\n\r\n    # define time, space, and other information vectors\r\n    z = (arange(n_steps) + 1) * dz\r\n    t = zeros(n_pfr)  # residence time in each PFR reactor\r\n    # compositions of output stream in each PFR reactor\r\n    compositions = [None] * n_pfr\r\n    states = SolutionArray(r.thermo)\r\n\r\n    cracking_rates = [0]\r\n    for i, T in enumerate(T_list[1:]):\r\n        Ti = T_list[i] + 273.15\r\n        Te = T + 273.15\r\n        dT = (Te - Ti) / n_steps\r\n        T = Ti\r\n        t_r = zeros_like(z)  # residence time in each CSTR reactor\r\n        # iterate through the PFR cells\r\n        for n in range(n_steps):\r\n            # simulate the linear T-profile in each reactor\r\n            T = Ti + (n + 1) * dT\r\n            model.TP = T, None\r\n            r.syncState()\r\n            # Set the state of the reservoir to match that of the previous reactor\r\n            model.TPX = r.thermo.TPX\r\n            upstream.syncState()\r\n            # integrate the reactor forward in time until steady state is reached\r\n            sim.reinitialize()\r\n            sim.set_initial_time(0)\r\n            sim.advance_to_steady_state()\r\n            # compute velocity and transform into time\r\n            t_r[n] = r.mass / mass_flow_rate  # residence time in this reactor\r\n            # write output data\r\n            states.append(r.thermo.state)\r\n        t[i] = sum(t_r)\r\n        compositions[i] = model.X[4:]\r\n        cracking_rate = (\r\n            EDC_X_0 - model.X[model.species_index(EDC_label)]) / EDC_X_0\r\n        cracking_rates.append(cracking_rate)\r\n    return compositions, t, cracking_rates\r\n\r\n\r\ndef predict(reaction_mech, T_list, pressure_0, CCl4_X_0, mass_flow_rate,\r\n            n_steps, n_pfr, length, area):\r\n    \"\"\"\r\n    Load the saved parameters of StandardScaler() and rebuild the ML model to\r\n    do predictions.\r\n\r\n    =============== =============================================================\r\n    Attribute       Description\r\n    =============== =============================================================\r\n    `reaction_mech` Doctinary of Cantera reaction mechanism(s) (.cti file)\r\n    `T_list`        Temperature profile (°C)\r\n    `pressure_0`    Initial pressue (atm)\r\n    `CCl4_X_0`      Initial CCl4 concentration (mass fraction)\r\n    `mass_flow_rate`Mass flow rate of input gas (T/H)      \r\n    `n_steps`       Number of iterations/number of CSTRs\r\n    `n_pfr`         Number of PFRs\r\n    `length`        Length of each PFR (m)\r\n    `area`          Cross-sectional area (m**2)\r\n    `save_fig`      Save figure to `plots` folder\r\n    `name`          The file name of the saving figure\r\n    =============== =============================================================\r\n\r\n\r\n    \"\"\"\r\n    # Load scaler parameter\r\n    with open(join(BASE_DIR,'clf.pickle'), 'rb') as f:\r\n        scaler = load(f)\r\n    # Load model\r\n    model = build_model()\r\n    model.load_weights(join(BASE_DIR,'model.h5'))\r\n\r\n    if type(reaction_mech) != dict:\r\n        raise TypeError('The datatype of `reaction_mech` is {}.It should be a dict.'.format(\r\n            type(reaction_mech)))\r\n    results = {}\r\n    for label in reaction_mech.keys():\r\n        compositions, t, cracking_rates = EDC_cracking(\r\n            reaction_mech[label],\r\n            T_list,\r\n            pressure_0,\r\n            CCl4_X_0,\r\n            mass_flow_rate,\r\n            n_steps,\r\n            n_pfr,\r\n            length,\r\n            area\r\n        )\r\n        results[label] = {\r\n            'compositions': compositions,\r\n            't': t,\r\n            'cracking_rates': cracking_rates,\r\n        }\r\n    # Use ML model to predict\r\n    KM_label = 'Schirmeister'\r\n    y_predicted = [0]\r\n    prev_y = 0\r\n    for i, T in enumerate(T_list[1:]):\r\n        Ti = T_list[i]\r\n        Te = T\r\n        compositions = results[KM_label]['compositions'][i]\r\n        t = sum(results[KM_label]['t'][:i+1])\r\n        t_r = results[KM_label]['t'][i]\r\n\r\n        x_predict = [Ti, Te, compositions,\r\n                     pressure_0, CCl4_X_0, t, t_r, prev_y]\r\n        x_predict = hstack(x_predict).reshape(1, -1)\r\n        rescaled_X_predict = scaler.transform(x_predict)\r\n        x_predict = [rescaled_X_predict[:, 0:2],\r\n                     rescaled_X_predict[:, 2:-1], rescaled_X_predict[:, -1]]\r\n        y = float(model.predict(x_predict))\r\n        prev_y = y\r\n        y_predicted.append(y)\r\n    [print(i * 100, end=',') for i in y_predicted]\r\n    print(\"\\n\")\r\n\r\n\r\nif __name__ == '__main__':\r\n    parser = ArgumentParser(description='model parameters.')\r\n    parser.add_argument('mass_flow_rate', metavar='mass', type=float,\r\n                        help='mass flow rate of inlet stream, unit = T/H')\r\n    parser.add_argument('pressure_0', metavar='Pin',\r\n                        type=float, help='inlet pressure, unit = kg/cm2G')\r\n    parser.add_argument('CCl4_X_0', metavar='CCl4 concentration',\r\n                        type=float, help='inlet CCl4 concentration, unit = ppm')\r\n    parser.add_argument('T_list', metavar='Temperature profile', type=float,\r\n                        nargs='+', help='temperature profile of the process, unit= ℃')\r\n    args = parser.parse_args()\r\n    mass_flow_rate = args.mass_flow_rate\r\n    pressure_0 = args.pressure_0\r\n    CCl4_X_0 = args.CCl4_X_0\r\n    T_list = args.T_list\r\n    n_steps = 100\r\n    n_pfr = len(T_list)-1\r\n    length = 18\r\n    add_directory(join(BASE_DIR))\r\n    if n_pfr == 18:\r\n        area = 3.14 * (186.3 / 1000) ** 2 / 4\r\n    elif n_pfr == 22:\r\n        area = 3.14 * ((262) / 1000) ** 2 / 4\r\n    reaction_mech = {\r\n        'Schirmeister': join(BASE_DIR,'chem_annotated_irreversible.xml')\r\n    }\r\n    # Prediction\r\n    print('Starting prediction...')\r\n    print('cracking rates are:')\r\n    predict(reaction_mech, T_list, pressure_0, CCl4_X_0, mass_flow_rate,\r\n            n_steps, n_pfr, length, area)\r\n", "meta": {"hexsha": "de9449b2feae9203584b7b7d178d41c4eb7edf16", "size": 11294, "ext": "py", "lang": "Python", "max_stars_repo_path": "FPC/final_exe/ML_model_final.py", "max_stars_repo_name": "WesleyLeeNTU/EDC", "max_stars_repo_head_hexsha": "f28be5ff586f15b21a3cb53814da1039b118f321", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FPC/final_exe/ML_model_final.py", "max_issues_repo_name": "WesleyLeeNTU/EDC", "max_issues_repo_head_hexsha": "f28be5ff586f15b21a3cb53814da1039b118f321", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FPC/final_exe/ML_model_final.py", "max_forks_repo_name": "WesleyLeeNTU/EDC", "max_forks_repo_head_hexsha": "f28be5ff586f15b21a3cb53814da1039b118f321", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6280701754, "max_line_length": 162, "alphanum_fraction": 0.5808393837, "include": true, "reason": "from numpy", "num_tokens": 2809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.2909808785120009, "lm_q1q2_score": 0.1864127838476002}}
{"text": "\"\"\"\n\nVolumeLocal.py\n\nAuthor: Jordan Mirocha\nAffiliation: University of Colorado at Boulder\nCreated on: Mon Dec 31 11:16:59 2012\n\nDescription:\n\n\"\"\"\n\nimport copy\nimport numpy as np\nfrom ..util import ParameterFile\nfrom ..physics.SecondaryElectrons import SecondaryElectrons\nfrom ..physics.Constants import erg_per_ev, E_LyA, ev_per_hz\n\nclass LocalVolume:\n    def __init__(self, grid, sources, **kwargs):\n        self.pf = ParameterFile(**kwargs)\n        self.grid = grid\n        self.srcs = sources\n        self.esec = SecondaryElectrons(method=self.pf['secondary_ionization'])\n                \n        if self.srcs is not None:\n            self._initialize()\n    \n    def _initialize(self):\n        self.Ns = len(self.srcs)\n    \n        self.E_th = {}\n        for absorber in self.grid.absorbers:\n            self.E_th[absorber] = self.grid.ioniz_thresholds[absorber]\n    \n        # Array of cross-sections to match grid size \n        self.sigma = []\n        for src in self.srcs:\n            if src.continuous:\n                self.sigma.append(None)\n                continue\n    \n            self.sigma.append((np.ones([self.grid.dims, src.Nfreq]) \\\n                   * src.sigma).T)\n    \n        # Calculate correction to normalization factor if plane_parallel    \n        if self.pf['optically_thin']:\n            if self.pf['plane_parallel']:\n                self.pp_corr = 4. * np.pi * self.grid.r_mid**2\n            else:\n                self.pp_corr = 1.0\n        else:\n            if self.pf['photon_conserving']:\n                self.pp_corr = self.grid.Vsh / self.grid.dr\n            else:\n                self.A_npc = source.Lbol / 4. / np.pi / self.grid.r_mid**2\n                self.pp_corr = 4. * np.pi * self.grid.r_mid**2\n\n    @property\n    def rates_no_RT(self):\n        if not hasattr(self, '_rates_no_RT'):\n            self._rates_no_RT = \\\n                {'k_ion': np.zeros((self.Ns, self.grid.dims, \n                    self.grid.N_absorbers)),\n                 'k_heat': np.zeros((self.Ns, self.grid.dims, \n                    self.grid.N_absorbers)),\n                 'k_ion2': np.zeros((self.Ns, self.grid.dims, \n                    self.grid.N_absorbers, self.grid.N_absorbers)),\n                }\n        \n        return self._rates_no_RT\n\n    def update_rate_coefficients(self, data, t, rfield):\n        \"\"\"\n        Get rate coefficients for ionization and heating. Sort into dictionary.\n        \n        Parameters\n        ----------\n        rfield : RadialField instance\n            Contains attributes representing column densities and such.\n        \"\"\"\n    \n        # Return zeros for everything if RT is off\n        if not self.pf['radiative_transfer']:\n            self.kwargs = self.rates_no_RT.copy()\n            return self.kwargs\n        else:\n            self.kwargs = {}\n\n        # Parse column densities, set attributes\n        for attribute in ['logN_by_cell', 'logNdN', 'n', 'N', 'Nc']:\n            val = getattr(rfield, attribute)\n            setattr(self, attribute, val)\n\n        # Make data globally accessible\n        self.data = data.copy()\n\n        # Compute source dependent rate coefficients\n        k_ion_src, k_ion2_src, k_heat_src, Ja_src = \\\n            self._get_coefficients(data, t)\n                    \n        # Unpack source-specific rates if necessary            \n        if len(self.srcs) > 1:\n            for i, src in enumerate(self.srcs):\n                self.kwargs.update({'k_ion_{}'.format(i): k_ion_src[i], \n                    'k_ion2_{}'.format(i): k_ion2_src[i],\n                    'k_heat_{}'.format(i): k_heat_src[i]})\n                    \n                if False:\n                    self.kwargs.update({'Ja_{}'.format(i): Ja_src[i]})\n        \n                    #if self.pf['secondary_lya']:\n                    #    self.kwargs.update({'Ja_X_{}'.format(i): Ja_src[i]})\n        \n        # Sum over sources\n        k_ion = np.sum(k_ion_src, axis=0)\n        k_ion2 = np.sum(k_ion2_src, axis=0)\n        k_heat = np.sum(k_heat_src, axis=0)\n            \n        # Compute Lyman-Alpha emission\n        if False:\n            Ja = np.sum(Ja_src, axis=0)\n        \n        #if self.pf['secondary_lya']:\n        #    Ja_X = np.sum(Ja_src, axis=0)\n        \n        # Each is grid x absorbers, or grid x [absorbers, absorbers] for gamma\n        self.kwargs.update({'k_ion': k_ion, 'k_heat': k_heat, 'k_ion2': k_ion2})\n        \n        # Ja just has len(grid) \n        if False:\n            self.kwargs.update({'Ja': Ja})\n        \n        return self.kwargs\n               \n    def _get_coefficients(self, data, t):\n        \"\"\"\n        Compute rate coefficients for ionization and heating.\n        \n        Parameters\n        ----------\n        data : dict\n            Data for current snapshot.\n        t : int, float  \n            Current time (needed to make sure sources are on).\n        \n        \"\"\"\n        \n        self.k_ion = np.zeros((self.Ns, self.grid.dims, self.grid.N_absorbers))\n        self.k_heat = np.zeros((self.Ns, self.grid.dims, self.grid.N_absorbers))\n        self.k_ion2 = np.zeros((self.Ns, self.grid.dims, self.grid.N_absorbers, \n            self.grid.N_absorbers))\n        \n        if True:\n            self.Ja = [None] * self.Ns\n        else:\n            self.Ja = np.array(self.Ns * [np.zeros(self.grid.dims)])\n\n        # Loop over sources\n        for h, src in enumerate(self.srcs):      \n\n            if not src.SourceOn(t):\n                continue\n                \n            self.h = h\n            self.src = src\n                \n            # If we're operating under the optically thin assumption, \n            # return pre-computed source-dependent values.    \n            if self.pf['optically_thin']:\n                self.tau_tot = np.zeros(self.grid.dims) # by definition\n                self.k_ion[h] = src.k_ion_bar * self.pp_corr\n                self.k_heat[h] = src.k_heat_bar * self.pp_corr\n                self.k_ion2[h] = src.k_ion2_bar * self.pp_corr\n                continue\n\n            # Normalizations\n            self.A = {}\n            for absorber in self.grid.absorbers:          \n                \n                if self.pf['photon_conserving']:\n                    self.A[absorber] = self.src.Lbol(t) \\\n                        / self.n[absorber] / self.grid.Vsh\n                else:\n                    self.A[absorber] = self.A_npc\n                    \n                # Correct normalizations if radiation field is plane-parallel\n                if self.pf['plane_parallel']:\n                    self.A[absorber] = self.A[absorber] * self.pp_corr\n                                \n            \"\"\"\n            For sources with discrete SEDs.\n            \"\"\"\n            if self.src.discrete:\n            \n                # Loop over absorbing species\n                for i, absorber in enumerate(self.grid.absorbers):\n                                    \n                    # Discrete spectrum (multi-freq approach)\n                    if self.src.multi_freq:\n                        r1, r2, r3 = self.MultiFreqCoefficients(data, absorber, t)\n                        self.k_ion[h,:,i], self.k_ion2[h,:,i,:], \\\n                        self.k_heat[h,:,i] = \\\n                            self.MultiFreqCoefficients(data, absorber, t)\n                    \n                    # Discrete spectrum (multi-grp approach)\n                    elif self.src.multi_group:\n                        pass\n                \n                continue\n                \n            \"\"\"\n            For sources with continuous SEDs.\n            \"\"\"\n            \n            # This could be post-processed, but eventually may be more\n            # sophisticated\n            if True:\n                self.Ja = None\n            else:\n                self.Ja[h] = src.Spectrum(E_LyA) * ev_per_hz \\\n                    * src.Lbol(t) / 4. / np.pi / self.grid.r_mid**2 \\\n                    / E_LyA / erg_per_ev \n            \n            # Initialize some arrays/dicts\n            self.PhiN = {}\n            self.PhiNdN = {}\n            self.fheat = 1.0\n            self.fion = dict([(absorber, 1.0) for absorber in self.grid.absorbers])\n            \n            self.PsiN = {}\n            self.PsiNdN = {}\n            if not self.pf['isothermal'] and self.pf['secondary_ionization'] < 2:\n                self.fheat = self.esec.DepositionFraction(data['h_2'], \n                    channel='heat')\n                \n            self.logx = None            \n            if self.pf['secondary_ionization'] > 1:\n                \n                self.logx = np.log10(data['h_2'])\n                \n                self.PhiWiggleN = {}\n                self.PhiWiggleNdN = {}\n                self.PhiHatN = {}\n                self.PhiHatNdN = {}\n                self.PsiWiggleN = {}\n                self.PsiWiggleNdN = {}\n                self.PsiHatN = {}\n                self.PsiHatNdN = {}\n                \n                for absorber in self.grid.absorbers:\n                    self.PhiWiggleN[absorber] = {}\n                    self.PhiWiggleNdN[absorber] = {}\n                    self.PsiWiggleN[absorber] = {}\n                    self.PsiWiggleNdN[absorber] = {}\n                \n            else:\n                self.fion = {}\n                for absorber in self.grid.absorbers:\n                    self.fion[absorber] = \\\n                        self.esec.DepositionFraction(xHII=data['h_2'], \n                            channel=absorber)\n                            \n            # Loop over absorbing species, compute tabulated quantities\n            for i, absorber in enumerate(self.grid.absorbers):\n                                           \n                self.PhiN[absorber] = \\\n                    10**self.src.tables[\"logPhi_{!s}\".format(absorber)](self.logN_by_cell,\n                    self.logx, t)\n                \n                if (not self.pf['isothermal']) and (self.pf['secondary_ionization'] < 2):\n                    self.PsiN[absorber] = \\\n                        10**self.src.tables[\"logPsi_{!s}\".format(absorber)](self.logN_by_cell,\n                        self.logx, t)\n                    \n                if self.pf['photon_conserving']:\n                    self.PhiNdN[absorber] = \\\n                        10**self.src.tables[\"logPhi_{!s}\".format(absorber)](self.logNdN[i],\n                        self.logx, t)\n                    \n                    if (not self.pf['isothermal']) and (self.pf['secondary_ionization'] < 2):\n                        self.PsiNdN[absorber] = \\\n                            10**self.src.tables[\"logPsi_{!s}\".format(absorber)](self.logNdN[i],\n                            self.logx, t)\n            \n                if self.pf['secondary_ionization'] > 1:\n                    \n                    self.PhiHatN[absorber] = \\\n                        10**self.src.tables[\"logPhiHat_{!s}\".format(absorber)](self.logN_by_cell,\n                        self.logx, t)    \n                                        \n                    if not self.pf['isothermal']:\n                        self.PsiHatN[absorber] = \\\n                            10**self.src.tables[\"logPsiHat_{!s}\".format(absorber)](self.logN_by_cell,\n                            self.logx, t)  \n                                                \n                        if self.pf['photon_conserving']:    \n                            self.PhiHatNdN[absorber] = \\\n                                10**self.src.tables[\"logPhiHat_{!s}\".format(absorber)](self.logNdN[i],\n                                self.logx, t)\n                            self.PsiHatNdN[absorber] = \\\n                                10**self.src.tables[\"logPsiHat_{!s}\".format(absorber)](self.logNdN[i],\n                                self.logx, t)     \n                    \n                    for j, donor in enumerate(self.grid.absorbers):\n                        \n                        suffix = '{0!s}_{1!s}'.format(absorber, donor)\n                        \n                        self.PhiWiggleN[absorber][donor] = \\\n                            10**self.src.tables[\"logPhiWiggle_{!s}\".format(suffix)](self.logN_by_cell,\n                                self.logx, t)    \n                        \n                        self.PsiWiggleN[absorber][donor] = \\\n                            10**self.src.tables[\"logPsiWiggle_{!s}\".format(suffix)](self.logN_by_cell,\n                            self.logx, t)\n                            \n                        if not self.pf['photon_conserving']:\n                            continue\n                        \n                        self.PhiWiggleNdN[absorber][donor] = \\\n                            10**self.src.tables[\"logPhiWiggle_{!s}\".format(suffix)](self.logNdN[j],\n                            self.logx, t)\n                        self.PsiWiggleNdN[absorber][donor] = \\\n                            10**self.src.tables[\"logPsiWiggle_{!s}\".format(suffix)](self.logNdN[j],\n                            self.logx, t)\n\n            # Now, go ahead and calculate the rate coefficients\n            for k, absorber in enumerate(self.grid.absorbers):\n                self.k_ion[h][...,k] = self.PhotoIonizationRate(absorber)\n                self.k_heat[h][...,k] = self.PhotoHeatingRate(absorber)\n\n                for j, donor in enumerate(self.grid.absorbers):\n                    self.k_ion2[h][...,k,j] = \\\n                        self.SecondaryIonizationRate(absorber, donor)\n                       \n            # Compute total optical depth too\n            self.tau_tot = 10**self.src.tables[\"logTau\"](self.logN_by_cell)\n            \n        return self.k_ion, self.k_ion2, self.k_heat, self.Ja\n        \n    def MultiFreqCoefficients(self, data, absorber, t=None):\n        \"\"\"\n        Compute all source-dependent rates.\n        \n        (For given absorber assuming a multi-frequency SED)\n        \n        \"\"\"\n        \n        k_heat = np.zeros(self.grid.dims)\n        k_ion2 = np.zeros_like(self.grid.zeros_grid_x_absorbers)\n        \n        i = self.grid.absorbers.index(absorber)\n        n = self.n[absorber]\n        N = self.N[absorber]\n               \n        # Optical depth up to cells at energy E\n        N = np.ones([self.src.Nfreq, self.grid.dims]) * self.N[absorber]\n        \n        self.tau_r = N * self.sigma[self.h]\n        self.tau_tot = np.sum(self.tau_r, axis=1)\n        \n        Qdot = self.src.Qdot(t=t)\n                        \n        # Loop over energy groups\n        k_ion_E = np.zeros([self.grid.dims, self.src.Nfreq])\n        for j, E in enumerate(self.src.E):\n            \n            if E < self.E_th[absorber]:\n                continue    \n            \n            # Optical depth of cells (at this photon energy)                                                           \n            tau_c = self.Nc[absorber] * self.src.sigma[j]\n                                                            \n            # Photo-ionization by *this* energy group\n            k_ion_E[...,j] = \\\n                self.PhotoIonizationRateMultiFreq(Qdot[j], n,\n                self.tau_r[j], tau_c)     \n                                          \n            # Heating\n            if self.grid.isothermal:\n                continue\n\n            fheat = self.esec.DepositionFraction(xHII=data['h_2'], \n                E=E, channel='heat')\n\n            # Total energy deposition rate per atom i via photo-electrons \n            # due to ionizations by *this* energy group. \n            ee = k_ion_E[...,j] * (E - self.E_th[absorber]) \\\n               * erg_per_ev\n\n            k_heat += ee * fheat\n\n            if not self.pf['secondary_ionization']:\n                continue\n                                        \n            # Ionizations of species k by photoelectrons from species i\n            # Neglect HeII until somebody figures out how that works\n            for k, otherabsorber in enumerate(self.grid.absorbers):\n            \n                # If these photo-electrons don't have enough \n                # energy to ionize species k, continue    \n                if (E - self.E_th[absorber]) < \\\n                    self.E_th[otherabsorber]:\n                    continue    \n                \n                fion = self.esec.DepositionFraction(xHII=data['h_2'], \n                    E=E, channel=absorber)\n\n                # (This k) = i from paper, and (this i) = j from paper\n                k_ion2[...,k] += ee * fion \\\n                    / (self.E_th[otherabsorber] * erg_per_ev)\n                                                                           \n        # Total photo-ionization tally\n        k_ion = np.sum(k_ion_E, axis=1)\n                \n        return k_ion, k_ion2, k_heat\n    \n    def PhotoIonizationRateMultiFreq(self, qdot, n, tau_r_E, tau_c):\n        \"\"\"\n        Returns photo-ionization rate coefficient for single frequency over\n        the entire grid.\n        \"\"\"     \n                                        \n        q0 = qdot * np.exp(-tau_r_E)             # number of photons entering cell per sec\n        dq = q0 * (1. - np.exp(-tau_c))          # number of photons absorbed in cell per sec\n        IonizationRate = dq / n / self.grid.Vsh  # ionizations / sec / atom        \n                                  \n        if self.pf['plane_parallel']:\n            IonizationRate *= self.pp_corr\n        \n        return IonizationRate\n        \n    def PhotoIonizationRateMultiGroup(self):\n        pass\n        \n    def PhotoIonizationRate(self, absorber):\n        \"\"\"\n        Returns photo-ionization rate coefficient for continuous source.\n        \"\"\"                                     \n            \n        IonizationRate = self.PhiN[absorber].copy()\n        if self.pf['photon_conserving']:\n            IonizationRate -= self.PhiNdN[absorber]\n        \n        return self.A[absorber] * IonizationRate\n        \n    def PhotoHeatingRate(self, absorber):\n        \"\"\"\n        Photo-electric heating rate coefficient due to photo-electrons previously \n        bound to `species.'  If this method is called, it means TabulateIntegrals = 1.\n        \"\"\"\n\n        if self.pf['isothermal']:\n            return 0.0\n\n        if self.esec.method < 2:\n            HeatingRate = self.PsiN[absorber].copy()\n            HeatingRate -= self.E_th[absorber] * erg_per_ev  \\\n                * self.PhiN[absorber]\n            if self.pf['photon_conserving']:\n                HeatingRate -= self.PsiNdN[absorber]\n                HeatingRate += erg_per_ev \\\n                    * self.E_th[absorber] \\\n                    * self.PhiNdN[absorber]\n        else:\n            HeatingRate = self.PsiHatN[absorber].copy()\n            HeatingRate -= self.E_th[absorber] * erg_per_ev  \\\n                * self.PhiHatN[absorber]\n            if self.pf['photon_conserving']:\n                HeatingRate -= self.PsiHatNdN[absorber]\n                HeatingRate += erg_per_ev \\\n                    * self.E_th[absorber] \\\n                    * self.PhiHatNdN[absorber]\n\n        return self.A[absorber] * self.fheat * HeatingRate\n            \n    def SecondaryIonizationRate(self, absorber, donor):\n        \"\"\"\n        Secondary ionization rate which we denote elsewhere as gamma (note little g).\n        \n            absorber = species being ionized by photo-electron\n            donor = species the photo-electron came from\n            \n        If this routine is called, it means TabulateIntegrals = 1.\n        \"\"\"    \n        \n        if self.esec.method < 2:\n            IonizationRate = self.PsiN[donor].copy()\n            IonizationRate -= self.E_th[donor] \\\n                * erg_per_ev * self.PhiN[donor]\n            if self.pf['photon_conserving']:\n                IonizationRate -= self.PsiNdN[donor]\n                IonizationRate += self.E_th[donor] \\\n                    * erg_per_ev * self.PhiNdN[donor]\n                            \n        else:\n            IonizationRate = self.PsiWiggleN[absorber][donor] \\\n                - self.E_th[donor] \\\n                * erg_per_ev * self.PhiWiggleN[absorber][donor]\n            if self.pf['photon_conserving']:\n                IonizationRate -= self.PsiWiggleNdN[absorber][donor]\n                IonizationRate += self.E_th[donor] \\\n                    * erg_per_ev * self.PhiWiggleNdN[absorber][donor]            \n                        \n        # Normalization (by number densities) will be applied in \n        # chemistry solver    \n        return self.A[donor] * self.fion[absorber] * IonizationRate \\\n                / self.E_th[absorber] / erg_per_ev    \n        \n        \n        \n", "meta": {"hexsha": "696fea1076d5d60503ff1cc9bba3c5fb76335e4b", "size": 20501, "ext": "py", "lang": "Python", "max_stars_repo_path": "ares/static/VolumeLocal.py", "max_stars_repo_name": "jlashner/ares", "max_stars_repo_head_hexsha": "6df2b676ded6bd59082a531641cb1dadd475c8a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-03-26T01:08:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T13:02:10.000Z", "max_issues_repo_path": "ares/static/VolumeLocal.py", "max_issues_repo_name": "jlashner/ares", "max_issues_repo_head_hexsha": "6df2b676ded6bd59082a531641cb1dadd475c8a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2020-06-08T14:52:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T02:30:54.000Z", "max_forks_repo_path": "ares/static/VolumeLocal.py", "max_forks_repo_name": "jlashner/ares", "max_forks_repo_head_hexsha": "6df2b676ded6bd59082a531641cb1dadd475c8a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-03-24T14:11:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-06T06:32:59.000Z", "avg_line_length": 40.041015625, "max_line_length": 119, "alphanum_fraction": 0.4770499, "include": true, "reason": "import numpy", "num_tokens": 4679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.281405613455665, "lm_q1q2_score": 0.1862688091854089}}
{"text": "from __future__ import print_function\nimport numpy as np\nimport os\n\ntry:\n    from .gsm import GSM\nexcept:\n    from gsm import GSM\n\nfrom wrappers.molecule import Molecule\nfrom utilities.nifty import printcool\nfrom utilities.manage_xyz import write_molden_geoms,xyz_to_np,get_atoms,np_to_xyz\nfrom utilities import block_matrix\nfrom coordinate_systems import rotate\nfrom optimizers import eigenvector_follow\nimport multiprocessing as mp\nfrom itertools import chain\n\ndef worker(arg):\n   obj, methname = arg[:2]\n   return getattr(obj, methname)(*arg[2:])\n\n#######################################################################################\n############### This class contains the main GSM functions  ###########################\n#######################################################################################\n\nclass MainGSM(GSM):\n    \n    def grow_string(self,max_iters=30,max_opt_steps=3,nconstraints=1):\n        '''\n        Grow the string \n\n        Parameters\n        ----------\n        max_iter : int\n             Maximum number of GSM iterations \n        nconstraints : int\n        optsteps : int\n            Maximum number of optimization steps per node of string\n            \n        '''\n        printcool(\"In growth_iters\")\n\n        ncurrent,nlist = self.make_difference_node_list()\n        self.ictan,self.dqmaga = self.get_tangents_growing()\n        self.refresh_coordinates()\n        self.set_active(self.nR-1, self.nnodes-self.nP)\n\n        isGrown=False\n        iteration=0\n        while not isGrown:\n            if iteration>max_iters:\n                print(\" Ran out of iterations\")\n                return \n                # raise Exception(\" Ran out of iterations\")\n            printcool(\"Starting growth iteration %i\" % iteration)\n            self.optimize_iteration(max_opt_steps)\n            totalgrad,gradrms,sum_gradrms = self.calc_optimization_metrics(self.nodes)\n            self.xyz_writer('scratch/growth_iters_{:03}_{:03}.xyz'.format(self.ID,iteration),self.geometries,self.energies,self.gradrmss,self.dEs)\n            print(\" gopt_iter: {:2} totalgrad: {:4.3} gradrms: {:5.4} max E: {:5.4}\\n\".format(iteration,float(totalgrad),float(gradrms),float(self.emax)))\n                \n            try:\n                self.grow_nodes()\n            except Exception as error:\n                print(\"can't add anymore nodes, bdist too small\")\n\n                if self.__class__.__name__==\"SE_GSM\": # or self.__class__.__name__==\"SE_Cross\":\n                    # Don't do SE_cross because that already does optimization later\n                    if self.nodes[self.nR-1].PES.lot.do_coupling:\n                        opt_type='MECI'\n                    else:\n                        opt_type='UNCONSTRAINED'\n                    print(\" optimizing last node\")\n                    self.optimizer[self.nR-1].conv_grms = self.CONV_TOL\n                    print(self.optimizer[self.nR-1].conv_grms)\n                    path=os.path.join(os.getcwd(),'scratch/{:03d}/{}'.format(self.ID,self.nR-1))\n                    self.optimizer[self.nR-1].optimize(\n                            molecule=self.nodes[self.nR-1],\n                            refE=self.nodes[0].V0,\n                            opt_steps=50,\n                            opt_type=opt_type,\n                            path=path,\n                            )\n                elif self.__class__.__name__==\"SE_Cross\":\n                    print(\" Will do extra optimization of this node in SE-Cross\")\n                else:\n                    raise RuntimeError\n                break\n\n            self.set_active(self.nR-1, self.nnodes-self.nP)\n            self.ic_reparam_g()\n            self.ictan,self.dqmaga = self.get_tangents_growing()\n            self.refresh_coordinates()\n\n            iteration+=1\n            isGrown = self.check_if_grown()\n\n        # create newic object\n        print(\" creating newic molecule--used for ic_reparam\")\n        self.newic  = Molecule.copy_from_options(self.nodes[0])\n\n        # TODO should something be done for growthdirection 2?\n        if self.growth_direction==1:\n            print(\"Setting LOT of last node\")\n            self.nodes[-1] = Molecule.copy_from_options(\n                    MoleculeA = self.nodes[-2],\n                    xyz = self.nodes[-1].xyz,\n                    new_node_id = self.nnodes-1\n                    )\n        return \n\n\n    def optimize_string(self,max_iter=30,nconstraints=1,opt_steps=1,rtype=2):\n        '''\n        Optimize the grown string until convergence\n\n        Parameters\n        ----------\n        max_iter : int\n             Maximum number of GSM iterations \n        nconstraints : int\n        optsteps : int\n            Maximum number of optimization steps per node of string\n        rtype : int\n            An option to change how GSM optimizes  \n            TODO change this s***\n            0 is no-climb\n            1 is climber\n            2 is finder\n            \n        '''\n        printcool(\"In opt_iters\")\n\n        self.nclimb=0\n        self.nhessreset=10  # are these used??? TODO \n        self.hessrcount=0   # are these used?!  TODO\n        self.newclimbscale=2.\n        self.set_finder(rtype)\n\n\n        isConverged=False\n        oi = 0\n\n        # enter loop\n        while not isConverged:\n            printcool(\"Starting opt iter %i\" % oi)\n            if self.climb and not self.find: print(\" CLIMBING\")\n            elif self.find: print(\" TS SEARCHING\")\n\n            # stash previous TSnode  \n            self.pTSnode = self.TSnode\n            self.emaxp = self.emax\n\n            # store reparam energies\n            print(\" V_profile (beginning of iteration): \", end=' ')\n            self.print_energies()\n\n            # => Get all tangents 3-way <= #\n            self.get_tangents_opting()\n            self.refresh_coordinates()\n           \n            # => do opt steps <= #\n            self.set_node_convergence()\n            self.optimize_iteration(opt_steps)\n\n            print(\" V_profile: \", end=' ')\n            self.print_energies()\n\n            #TODO resetting\n            #TODO special SSM criteria if first opt'd node is too high?\n            if self.TSnode == self.nnodes-2 and (self.climb or self.find):\n                printcool(\"WARNING\\n: TS node shouldn't be second to last node for tangent reasons\")\n                self.add_node_after_TS()\n                added=True\n            elif self.TSnode == 1 and  (self.climb or self.find):\n                printcool(\"WARNING\\n: TS node shouldn't be first  node for tangent reasons\")\n                self.add_node_before_TS()\n                added=True\n            else:\n                added=False\n\n            # => find peaks <= #\n            fp = self.find_peaks('opting')\n\n            ts_cgradq = 0.\n            if not self.find:\n                ts_cgradq = np.linalg.norm(np.dot(self.nodes[self.TSnode].gradient.T,self.nodes[self.TSnode].constraints[:,0])*self.nodes[self.TSnode].constraints[:,0])\n                print(\" ts_cgradq %5.4f\" % ts_cgradq)\n\n            ts_gradrms=self.nodes[self.TSnode].gradrms\n            self.dE_iter=abs(self.emax-self.emaxp)\n            print(\" dE_iter ={:2.2f}\".format(self.dE_iter))\n\n            # => calculate totalgrad <= #\n            totalgrad,gradrms,sum_gradrms = self.calc_optimization_metrics(self.nodes)\n\n            # Check if allup or alldown\n            energies = np.array(self.energies)\n            if (np.all(energies[1:]+0.5 >= energies[:-1]) or np.all(energies[1:]-0.5<=energies[:-1])) and (self.climber or self.finder):\n                printcool(\" There is no TS, turning off TS search\")\n                rtype=0\n                self.climber=self.finder=self.find=self.climb=False\n                #self.CONV_TOL=self.options['CONV_TOL']*5\n                self.CONV_TOL=self.options['CONV_TOL']\n\n            #if self.has_intermediate(5) and rtype>0 and (self.climb or self.find):\n            #    printcool(\" THERE IS AN INTERMEDIATE, OPTIMIZE THE INTERMEDIATE AND TRY AGAIN\")\n            #    self.endearly=True\n            #    isConverged=True\n            #    self.tscontinue=False\n\n            # => Check Convergence <= #\n            isConverged = self.is_converged(totalgrad,fp,rtype,ts_cgradq)\n\n            # => set stage <= #\n            stage_changed=self.set_stage(totalgrad,sum_gradrms,ts_cgradq,ts_gradrms,fp)\n\n            if not stage_changed:\n                # Decrement stuff that controls stage\n                if self.climb: \n                    self.nclimb-=1\n                self.nhessreset-=1\n                if self.nopt_intermediate>0:\n                    self.nopt_intermediate-=1\n\n                if self.pTSnode!=self.TSnode and self.climb:\n                    print(\"TS node changed after opting\")\n                    self.climb=False\n                    #self.slow_down_climb()\n                    self.pTSnode=self.TSnode\n\n                # opt decided Hess is not good because of overlap\n                if self.find and (not self.optimizer[self.TSnode].maxol_good or added):\n                    self.ictan,self.dqmaga = self.get_three_way_tangents(self.nodes,self.energies)\n                    self.modify_TS_Hess()\n                elif self.find and (self.optimizer[self.TSnode].nneg > 3 or self.optimizer[self.TSnode].nneg==0 or self.hess_counter > 10 or np.abs(self.TS_E_0 - self.emax) > 10.) and ts_gradrms >self.CONV_TOL:\n\n                    # Reform the guess primitive Hessian\n                    self.nodes[self.TSnode].form_Primitive_Hessian()\n                    if self.hessrcount<1 and self.pTSnode == self.TSnode:\n                        print(\" resetting TS node coords Ut (and Hessian)\")\n                        self.ictan,self.dqmaga = self.get_three_way_tangents(self.nodes,self.energies)\n                        self.modify_TS_Hess()\n                        self.nhessreset=10\n                        self.hessrcount=1\n                    else:\n                        print(\" Hessian consistently bad, going back to climb (for 3 iterations)\")\n                        self.find=False\n                        self.nclimb=2\n                elif self.find and self.optimizer[self.TSnode].nneg <= 3:\n                    self.hessrcount-=1\n                    self.hess_counter += 1\n\n            # => write Convergence to file <= #\n            filename = 'scratch/opt_iters_{:03}_{:03}.xyz'.format(self.ID,oi)\n            self.xyz_writer(filename,self.geometries,self.energies,self.gradrmss,self.dEs)\n\n            print(\" End early counter {}\".format(self.endearly_counter))\n\n            #TODO prints tgrads and jobGradCount\n            print(\"opt_iter: {:2} totalgrad: {:4.3} gradrms: {:5.4} max E({}) {:5.4}\\n\".format(oi,float(totalgrad),float(gradrms),self.TSnode,float(self.emax)))\n            oi += 1\n\n            # => Reparam the String <= #\n            if oi<max_iter and not isConverged:\n                self.reparameterize(nconstraints=nconstraints)\n                self.get_tangents_opting()\n                self.refresh_coordinates()\n                if self.pTSnode!=self.TSnode and self.climb:\n                    print(\"TS node changed after reparameterizing\")\n                    self.slow_down_climb()\n            elif oi>=max_iter and not isConverged:\n                self.ran_out = True\n                print(\" Ran out of iterations\")\n                return \n                # raise Exception(\" Ran out of iterations\")\n\n\n        #TODO Optimize TS node to a finer convergence\n        #if rtype==2:\n        return\n\n\n    def refresh_coordinates(self,update_TS=False):\n        '''\n        Refresh the DLC coordinates for the string\n        '''\n\n        if not self.done_growing:\n            #TODO\n\n            if self.mp_cores==1:\n                for n in range(1,self.nnodes-1):\n                    if self.nodes[n] is not None:\n                        Vecs = self.newic.coord_obj.build_dlc(self.nodes[n].xyz,self.ictan[n])\n                        self.nodes[n].coord_basis = Vecs\n\n            else:\n                pool = mp.Pool(self.mp_cores)\n                Vecs = pool.map(worker,((self.newic.coord_obj,\"build_dlc\",self.nodes[n].xyz,self.ictan[n]) for n in range(1,self.nnodes-1) if self.nodes[n] is not None ))\n                pool.close()\n                pool.join()\n    \n                i=0\n                for n in range(1,self.nnodes-1):\n                    if self.nodes[n] is not None:\n                        self.nodes[n].coord_basis = Vecs[i]\n                        i+=1\n        else:\n            if self.find or self.climb:            \n                energies = self.energies\n                TSnode = self.TSnode\n                if self.mp_cores==1:\n                    for n in range(1,self.nnodes-1):\n                        # don't update tsnode coord basis \n                        if n!=TSnode or (n==TSnode and update_TS): \n                            Vecs = self.newic.coord_obj.build_dlc(self.nodes[n].xyz,self.ictan[n])\n                            self.nodes[n].coord_basis = Vecs\n                else:\n                    pool = mp.Pool(self.mp_cores)\n                    Vecs = pool.map(worker,((self.newic.coord_obj,\"build_dlc\",self.nodes[n].xyz,self.ictan[n]) for n in range(1,self.nnodes-1) if n!=TSnode))\n                    pool.close()\n                    pool.join()\n                    for i,n in enumerate(chain(range(1,TSnode),range(TSnode+1,self.nnodes-1))):\n                        self.nodes[n].coord_basis = Vecs[i]\n\n                    if update_TS:\n                        Vec = self.newic.coord_obj.build_dlc(self.nodes[TSnode].xyz,self.ictan[TSnode])\n                        self.nodes[TSnode].coord_basis = Vec\n\n            else:\n                #for n in range(1,self.nnodes-1):\n                #    self.nodes[n].update_coordinate_basis(self.ictan[n])\n\n                if self.mp_cores==1:\n                    Vecs=[]\n                    for n in range(1,self.nnodes-1):\n                        Vecs.append(self.newic.coord_obj.build_dlc(self.nodes[n].xyz,self.ictan[n]))\n                elif self.mp_cores>1:\n                    pool = mp.Pool(self.mp_cores)\n                    Vecs = pool.map(worker,((self.newic.coord_obj,\"build_dlc\",self.nodes[n].xyz,self.ictan[n]) for n in range(1,self.nnodes-1)))\n                    pool.close()\n                    pool.join()\n                for n,node in enumerate(self.nodes[1:self.nnodes-1]):\n                    node.coord_basis = Vecs[n]\n\n\n    def optimize_iteration(self,opt_steps):\n        '''\n        Optimize string iteration\n        '''\n\n        refE=self.nodes[0].energy\n\n        for n in range(self.nnodes):\n            if self.nodes[n] and self.active[n]:\n                print()\n                path=os.path.join(os.getcwd(),'scratch/{:03d}/{}'.format(self.ID,n))\n                printcool(\"Optimizing node {}\".format(n))\n                opt_type = self.set_opt_type(n)\n                osteps = self.mult_steps(n,opt_steps)\n                self.optimizer[n].optimize(\n                        molecule=self.nodes[n],\n                        refE=refE,\n                        opt_type=opt_type,\n                        opt_steps=osteps,\n                        ictan=self.ictan[n],\n                        xyzframerate=1,\n                        path=path,\n                        )\n\n        if self.__class__.__name__==\"SE-GSM\" and self.done_growing:\n            fp = self.find_peaks('opting')\n            if self.energies[self.nnodes-1]>self.energies[self.nnodes-2] and fp>0 and self.nodes[self.nnodes-1].gradrms>self.CONV_TOL:\n                printcool('Last node is not a minimum, Might need to verify that the last node is a minimum')\n                path=os.path.join(os.getcwd(),'scratch/{:03d}/{}'.format(self.ID,self.nnodes-1))\n                self.optimizer[self.nnodes-1].optimize(\n                        molecule=self.nodes[self.nnodes-1],\n                        refE=refE,\n                        opt_type='UNCONSTRAINED',\n                        opt_steps=osteps,\n                        ictan=None,\n                        path=path\n                        )\n\n\n\n    def get_tangents_opting(self,print_level=1):\n        if self.climb or self.find:\n            self.ictan,self.dqmaga = self.get_three_way_tangents(self.nodes,self.energies)\n        else:\n            self.ictan,self.dqmaga = self.get_tangents(self.nodes)\n\n\n    def get_tangents_growing(self,print_level=1):\n        \"\"\"\n        Finds the tangents during the growth phase. \n        Tangents referenced to left or right during growing phase.\n        Also updates coordinates\n        Not a static method beause no one should ever call this outside of GSM\n        \"\"\"\n\n        ncurrent,nlist = self.make_difference_node_list()\n        dqmaga = [0.]*self.nnodes\n        ictan = [[]]*self.nnodes\n    \n        if self.print_level>1:\n            print(\"ncurrent, nlist\")\n            print(ncurrent)\n            print(nlist)\n    \n        for n in range(ncurrent):\n            #ictan0,_ = self.get_tangent(\n            #        node1=self.nodes[nlist[2*n]],\n            #        node2=self.nodes[nlist[2*n+1]],\n            #        driving_coords=self.driving_coords,\n            #        )\n\n            if self.__class__.__name__==\"DE_GSM\": # or self.__class__.__name__==\"SE_Cross\":\n                print(\" getting tangent [%i ]from between %i %i pointing towards %i\"%(nlist[2*n],nlist[2*n],nlist[2*n+1],nlist[2*n]))\n                ictan0 = self.get_tangent_xyz(self.nodes[nlist[2*n]].xyz,\n                    self.nodes[nlist[2*n+1]].xyz,\n                    self.nodes[0].primitive_internal_coordinates)\n            else:\n                ictan0,_ = self.get_tangent(\n                        node1=self.nodes[nlist[2*n]],\n                        node2=self.nodes[nlist[2*n+1]],\n                        driving_coords=self.driving_coords,\n                        )\n\n    \n            if self.print_level>1:\n                print(\"forming space for\", nlist[2*n+1])\n            if self.print_level>1:\n                print(\"forming tangent for \",nlist[2*n])\n    \n            if (ictan0[:]==0.).all():\n                print(\" ICTAN IS ZERO!\")\n                print(nlist[2*n])\n                print(nlist[2*n+1])\n                raise RuntimeError\n    \n            #normalize ictan\n            norm = np.linalg.norm(ictan0)  \n            ictan[nlist[2*n]] = ictan0/norm\n           \n            # NOTE regular GSM does something weird here \n            #Vecs = self.nodes[nlist[2*n]].update_coordinate_basis(constraints=self.ictan[nlist[2*n]])\n            #constraint = self.nodes[nlist[2*n]].constraints\n            #prim_constraint = block_matrix.dot(Vecs,constraint)\n            # but this is not followed here anymore 7/1/2020\n            #dqmaga[nlist[2*n]] = np.dot(prim_constraint.T,ictan0) \n            #dqmaga[nlist[2*n]] = float(np.sqrt(abs(dqmaga[nlist[2*n]])))\n            #tmp_dqmaga = np.dot(prim_constraint.T,ictan0)\n            #tmp_dqmaga = np.sqrt(tmp_dqmaga)\n\n            dqmaga[nlist[2*n]] = norm\n    \n    \n        if print_level>0:\n            print('------------printing dqmaga---------------')\n            for n in range(self.nnodes):\n                print(\" {:5.3}\".format(dqmaga[n]), end=' ')\n                if (n+1)%5==0:\n                    print()\n            print() \n       \n        if print_level>1:\n            for n in range(ncurrent):\n                print(\"dqmag[%i] =%1.2f\" %(nlist[2*n],self.dqmaga[nlist[2*n]]))\n                print(\"printing ictan[%i]\" %nlist[2*n])       \n                print(self.ictan[nlist[2*n]].T)\n        for i,tan in enumerate(ictan):\n            if np.all(tan==0.0):\n                print(\"tan %i of the tangents is 0\" %i)\n                raise RuntimeError\n   \n        return ictan,dqmaga\n\n\n    # Refactor this code!\n    # TODO remove return form_TS hess  3/2021\n    def set_stage(self,totalgrad,sumgradrms, ts_cgradq,ts_gradrms,fp):\n\n        # checking sum gradrms is not good because if one node is converged a lot while others a re not this is bad\n        all_converged = all([ self.nodes[n].gradrms < self.optimizer[n].conv_grms*1.1 for n in range(1,self.nnodes-1) ])\n        all_converged_climb = all([ self.nodes[n].gradrms < self.optimizer[n].conv_grms*2.5 for n in range(1,self.nnodes-1) ])\n        stage_changed=False\n\n        #TODO totalgrad is not a good criteria for large systems\n        #if fp>0 and (((totalgrad < 0.3 or ts_cgradq < 0.01) and self.dE_iter < 2.) or all_converged) and self.nopt_intermediate<1: # extra criterion in og-gsm for added\n\n        if fp>0 and all_converged_climb and self.dE_iter<2.:   #and self.nopt_intermediate<1:\n            if not self.climb and self.climber:\n                print(\" ** starting climb **\")\n                self.climb=True\n                print(\" totalgrad %5.4f gradrms: %5.4f gts: %5.4f\" %(totalgrad,ts_gradrms,ts_cgradq))\n                # overwrite this here just in case TSnode changed wont cause slow down climb  \n                self.pTSnode = self.TSnode\n                stage_changed=True\n\n            # TODO deserves to be rethought 3/2021\n            elif (self.climb and not self.find and self.finder and self.nclimb<1  and\n                    ((totalgrad<0.2 and ts_gradrms<self.CONV_TOL*10. and ts_cgradq<0.01) or #  I hate totalgrad \n                    (totalgrad<0.1 and ts_gradrms<self.CONV_TOL*10. and ts_cgradq<0.02) or  #\n                    (all_converged) or\n                    (ts_gradrms<self.CONV_TOL*2.5 and ts_cgradq < 0.01)  #  used to be 5\n                    )) and self.dE_iter<1.:\n                print(\" ** starting exact climb **\")\n                print(\" totalgrad %5.4f gradrms: %5.4f gts: %5.4f\" %(totalgrad,ts_gradrms,ts_cgradq))\n                self.find=True\n\n                # Modify TS Hessian\n                self.ictan,self.dqmaga = self.get_three_way_tangents(self.nodes,self.energies)\n                self.modify_TS_Hess()\n\n                if self.optimizer[self.TSnode].options['DMAX']>0.1:\n                    self.optimizer[self.TSnode].options['DMAX']=0.1\n                self.optimizer[self.TSnode] = eigenvector_follow(self.optimizer[self.TSnode].options.copy())\n                self.optimizer[self.TSnode].options['SCALEQN'] = 1.\n                self.nhessreset=10  # are these used??? TODO \n                self.hessrcount=0   # are these used?!  TODO\n                stage_changed=True\n\n        return stage_changed\n\n\n    def add_GSM_nodeR(self,newnodes=1):\n        '''\n        Add a node between endpoints on the reactant side, should only be called inside GSM\n        '''\n        printcool(\"Adding reactant node\")\n\n        if self.current_nnodes+newnodes > self.nnodes:\n            raise ValueError(\"Adding too many nodes, cannot interpolate\")\n        for i in range(newnodes):\n            iR = self.nR-1\n            iP = self.nnodes-self.nP\n            iN = self.nR\n            print(\" adding node: %i between %i %i from %i\" %(iN,iR,iP,iR))\n            if self.nnodes - self.current_nnodes > 1:\n                stepsize = 1./float(self.nnodes-self.current_nnodes+1)\n            else:\n                stepsize = 0.5\n\n            self.nodes[self.nR] = GSM.add_node(\n                    self.nodes[iR],\n                    self.nodes[iP],\n                    stepsize,\n                    iN,\n                    DQMAG_MAX = self.DQMAG_MAX,\n                    DQMAG_MIN = self.DQMAG_MIN,\n                    driving_coords = self.driving_coords,\n                    )\n\n            if self.nodes[self.nR]==None:\n                raise Exception('Ran out of space')\n\n            if self.__class__.__name__!=\"DE_GSM\":\n                ictan,bdist =  self.get_tangent(\n                        self.nodes[self.nR],\n                        None,\n                        driving_coords=self.driving_coords,\n                        )\n                self.nodes[self.nR].bdist = bdist\n\n            self.optimizer[self.nR].DMAX = self.optimizer[self.nR-1].DMAX\n            self.current_nnodes+=1\n            self.nR+=1\n            print(\" nn=%i,nR=%i\" %(self.current_nnodes,self.nR))\n            self.active[self.nR-1] = True\n\n            # align center of mass  and rotation\n            #print(\"%i %i %i\" %(iR,iP,iN))\n\n            #print(\" Aligning\")\n            #self.nodes[self.nR-1].xyz = self.com_rotate_move(iR,iP,iN)\n\n\n    def add_GSM_nodeP(self,newnodes=1):\n        '''\n        Add a node between endpoints on the product side, should only be called inside GSM\n        '''\n        printcool(\"Adding product node\")\n        if self.current_nnodes+newnodes > self.nnodes:\n            raise ValueError(\"Adding too many nodes, cannot interpolate\")\n\n        for i in range(newnodes):\n            #self.nodes[-self.nP-1] = BaseClass.add_node(self.nnodes-self.nP,self.nnodes-self.nP-1,self.nnodes-self.nP)\n            n1=self.nnodes-self.nP\n            n2=self.nnodes-self.nP-1\n            n3=self.nR-1\n            print(\" adding node: %i between %i %i from %i\" %(n2,n1,n3,n1))\n            if self.nnodes - self.current_nnodes > 1:\n                stepsize = 1./float(self.nnodes-self.current_nnodes+1)\n            else:\n                stepsize = 0.5\n\n            self.nodes[-self.nP-1] = GSM.add_node(\n                    self.nodes[n1],\n                    self.nodes[n3],\n                    stepsize,\n                    n2\n                    )\n            if self.nodes[-self.nP-1]==None:\n                raise Exception('Ran out of space')\n\n            self.optimizer[n2].DMAX = self.optimizer[n1].DMAX\n            self.current_nnodes+=1\n            self.nP+=1\n            print(\" nn=%i,nP=%i\" %(self.current_nnodes,self.nP))\n            self.active[-self.nP] = True\n\n            # align center of mass  and rotation\n            #print(\"%i %i %i\" %(n1,n3,n2))\n            #print(\" Aligning\")\n            #self.nodes[-self.nP].xyz = self.com_rotate_move(n1,n3,n2)\n            #print(\" getting energy for node %d: %5.4f\" %(self.nnodes-self.nP,self.nodes[-self.nP].energy - self.nodes[0].V0))\n        return\n\n\n    def reparameterize(self,ic_reparam_steps=8,n0=0,nconstraints=1):\n        '''\n        Reparameterize the string\n        '''\n        if self.interp_method == 'DLC':\n            # print('reparameterizing')\n            self.ic_reparam(nodes=self.nodes,energies=self.energies,climbing=(self.climb or self.find),ic_reparam_steps=ic_reparam_steps,NUM_CORE=self.mp_cores)\n        return\n\n    \n\n    def ic_reparam_g(self,ic_reparam_steps=4,n0=0,reparam_interior=True):  #see line 3863 of gstring.cpp\n        \"\"\"\n        Reparameterize during growth phase        \n        \"\"\"\n\n        printcool(\"Reparamerizing string nodes\")\n        #close_dist_fix(0) #done here in GString line 3427.\n        rpmove = np.zeros(self.nnodes)\n        rpart = np.zeros(self.nnodes)\n        dqavg = 0.0\n        disprms = 0.0\n        h1dqmag = 0.0\n        h2dqmag = 0.0\n        dE = np.zeros(self.nnodes)\n        edist = np.zeros(self.nnodes)\n        emax = -1000 # And this?\n\n        if self.current_nnodes==self.nnodes:\n            return\n\n        for i in range(ic_reparam_steps):\n            self.ictan,self.dqmaga = self.get_tangents_growing()\n            totaldqmag = np.sum(self.dqmaga[n0:self.nR-1])+np.sum(self.dqmaga[self.nnodes-self.nP+1:self.nnodes])\n            if self.print_level>0:\n                if i==0:\n                    print(\" totaldqmag (without inner): {:1.2}\\n\".format(totaldqmag))\n                print(\" printing spacings dqmaga: \")\n                for n in range(self.nnodes):\n                    print(\" {:2.3}\".format(self.dqmaga[n]), end=' ')\n                    if (n+1)%5==0:\n                        print()\n                print() \n            \n            if i == 0:\n                if self.current_nnodes!=self.nnodes:\n                    rpart = np.zeros(self.nnodes)\n                    for n in range(n0+1,self.nR):\n                        rpart[n] = 1.0/(self.current_nnodes-2)\n                    for n in range(self.nnodes-self.nP,self.nnodes-1):\n                        rpart[n] = 1.0/(self.current_nnodes-2)\n                else:\n                    for n in range(n0+1,self.nnodes):\n                        rpart[n] = 1./(self.nnodes-1)\n                if self.print_level>0:\n                    if i==0:\n                        print(\" rpart: \")\n                        for n in range(1,self.nnodes-1):\n                            print(\" {:1.2}\".format(rpart[n]), end=' ')\n                            if (n)%5==0:\n                                print()\n                        print()\n            nR0 = self.nR\n            nP0 = self.nP\n\n            # TODO CRA 3/2019 why is this here?\n            if not reparam_interior:\n                if self.nnodes-self.current_nnodes > 2:\n                    nR0 -= 1\n                    nP0 -= 1\n            \n            deltadq = 0.0\n            for n in range(n0+1,nR0):\n                deltadq = self.dqmaga[n-1] - totaldqmag*rpart[n]\n                rpmove[n] = -deltadq\n            for n in range(self.nnodes-nP0,self.nnodes-1):\n                deltadq = self.dqmaga[n+1] - totaldqmag*rpart[n]\n                rpmove[n] = -deltadq\n\n            MAXRE = 1.1\n\n            for n in range(n0+1,self.nnodes-1):\n                if abs(rpmove[n]) > MAXRE:\n                    rpmove[n] = float(np.sign(rpmove[n])*MAXRE)\n\n            disprms = float(np.linalg.norm(rpmove[n0+1:self.nnodes-1]))\n            lastdispr = disprms\n            if self.print_level>0:\n                for n in range(n0+1,self.nnodes-1):\n                    print(\" disp[{}]: {:1.2f}\".format(n,rpmove[n]), end=' ')\n                    if (n)%5==0:\n                        print()\n                print()\n                print(\" disprms: {:1.3}\\n\".format(disprms))\n\n            if disprms < 1e-2:\n                break\n\n            move_list = self.make_move_list()\n            tan_list = self.make_tan_list()\n\n\n            if self.mp_cores>1:\n                pool = mp.Pool(self.mp_cores)\n                Vecs = pool.map(worker,((self.nodes[0].coord_obj,\"build_dlc\",self.nodes[n].xyz,self.ictan[ntan]) for n,ntan in zip(move_list,tan_list) if rpmove[n]<0))\n                pool.close()\n                pool.join()\n\n                i=0\n                for n in move_list:\n                    if rpmove[n]<0:\n                        self.nodes[n].coord_basis = Vecs[i]\n                        i+=1\n            \n                # move the positions\n                pool = mp.Pool(self.mp_cores)\n                newXyzs = pool.map(worker,((self.nodes[n].coord_obj,\"newCartesian\",self.nodes[n].xyz,rpmove[n]*self.nodes[n].constraints[:,0]) for n in move_list if rpmove[n]<0))\n                pool.close()\n                pool.join()\n                i=0\n                for n in move_list:\n                    if rpmove[n]<0:\n                        self.nodes[n].xyz = newXyzs[i]\n                        i+=1\n            else:\n                for nmove,ntan in zip(move_list,tan_list):\n                    if rpmove[nmove] <0:\n                            print('Moving {} along ictan[{}]'.format(nmove,ntan))\n                            self.nodes[nmove].update_coordinate_basis(constraints=self.ictan[ntan])\n                            constraint = self.nodes[nmove].constraints[:,0]\n                            dq0 = rpmove[nmove]*constraint\n                            self.nodes[nmove].update_xyz(dq0,verbose=True)\n\n        print(\" spacings (end ic_reparam, steps: {}/{}):\".format(i+1,ic_reparam_steps), end=' ')\n        for n in range(self.nnodes):\n            print(\" {:1.2}\".format(self.dqmaga[n]), end=' ')\n        print(\"  disprms: {:1.3}\".format(disprms))\n\n        #TODO old GSM does this here\n        #Failed = check_array(self.nnodes,self.dqmaga)\n        #If failed, do exit 1\n\n\n    def modify_TS_Hess(self):\n        ''' Modifies Hessian using RP direction'''\n        print(\"modifying %i Hessian with RP\" % self.TSnode)\n  \n        TSnode = self.TSnode\n        # a variable to determine how many time since last modify\n        self.hess_counter = 0\n        self.TS_E_0 = self.energies[TSnode]\n\n        E0 = self.energies[TSnode]/GSM.units.KCAL_MOL_PER_AU\n        Em1 = self.energies[TSnode-1]/GSM.units.KCAL_MOL_PER_AU\n        if self.TSnode+1<self.nnodes:\n            Ep1 = self.energies[TSnode+1]/GSM.units.KCAL_MOL_PER_AU\n        else:\n            Ep1 = Em1\n\n        # Update TS node coord basis\n        Vecs = self.nodes[TSnode].update_coordinate_basis(constraints=None)\n\n        # get constrained coord basis\n        self.newic.xyz = self.nodes[TSnode].xyz.copy()\n        const_vec = self.newic.update_coordinate_basis(constraints=self.ictan[TSnode])\n        q0 = self.newic.coordinates[0]\n        constraint = self.newic.constraints[:,0]\n\n        # this should just give back ictan[TSnode]? \n        tan0 = block_matrix.dot(const_vec,constraint)\n\n        # get qm1 (don't update basis)\n        self.newic.xyz = self.nodes[TSnode-1].xyz.copy()\n        qm1 = self.newic.coordinates[0]\n\n        if TSnode+1<self.nnodes:\n            # get qp1 (don't update basis)\n            self.newic.xyz = self.nodes[TSnode+1].xyz.copy()\n            qp1 = self.newic.coordinates[0]\n        else:\n            qp1 = qm1\n\n        print(\" TS Hess init'd w/ existing Hintp\")\n\n        # Go to non-constrained basis\n        self.newic.xyz = self.nodes[TSnode].xyz.copy()\n        self.newic.coord_basis = Vecs\n        self.newic.Primitive_Hessian = self.nodes[TSnode].Primitive_Hessian.copy()\n        self.newic.form_Hessian_in_basis()\n\n        tan = block_matrix.dot(block_matrix.transpose(Vecs),tan0)   # (nicd,1\n        Ht = np.dot(self.newic.Hessian,tan)                         # (nicd,nicd)(nicd,1) = nicd,1\n        tHt = np.dot(tan.T,Ht) \n\n        a = abs(q0-qm1)\n        b = abs(qp1-q0)\n        c = 2*(Em1/a/(a+b) - E0/a/b + Ep1/b/(a+b))\n        print(\" tHt %1.3f a: %1.1f b: %1.1f c: %1.3f\" % (tHt,a[0],b[0],c[0]))\n\n        ttt = np.outer(tan,tan)\n\n        # Hint before\n        #with np.printoptions(threshold=np.inf):\n        #    print self.newic.Hessian\n        #eig,tmph = np.linalg.eigh(self.newic.Hessian)\n        #print \"initial eigenvalues\"\n        #print eig\n      \n        # Finalize Hessian\n        self.newic.Hessian += (c-tHt)*ttt\n        self.nodes[TSnode].Hessian = self.newic.Hessian.copy()\n\n        # Hint after\n        #with np.printoptions(threshold=np.inf):\n        #    print self.nodes[TSnode].Hessian\n        #print \"shape of Hessian is %s\" % (np.shape(self.nodes[TSnode].Hessian),)\n\n        self.nodes[TSnode].newHess = 5\n\n        if False:\n            print(\"newHess of node %i %i\" % (TSnode,self.nodes[TSnode].newHess))\n            eigen,tmph = np.linalg.eigh(self.nodes[TSnode].Hessian) #nicd,nicd\n            print(\"eigenvalues of new Hess\")\n            print(eigen)\n\n        # reset pgradrms ? \n\n\n    def mult_steps(self,n,opt_steps):\n        exsteps=1\n        tsnode = int(self.TSnode)\n\n        if (self.find or self.climb) and self.energies[n] > self.energies[self.TSnode]*0.9 and n!=tsnode:  #\n            exsteps=2\n            print(\" multiplying steps for node %i by %i\" % (n,exsteps))\n        elif self.find and n==tsnode and self.energies[tsnode]>self.energies[tsnode-1]*1.1 and self.energies[tsnode]>self.energies[tsnode+1]*1.1: # Can also try self.climb but i hate climbing image \n            exsteps=2\n            print(\" multiplying steps for node %i by %i\" % (n,exsteps))\n        #elif not self.find and not self.climb and n==tsnode  and self.energies[tsnode]>self.energies[tsnode-1]*1.5 and self.energies[tsnode]>self.energies[tsnode+1]*1.5 and self.climber: \n        #    exsteps=2\n        #    print(\" multiplying steps for node %i by %i\" % (n,exsteps))\n\n        #elif not (self.find and self.climb) and self.energies[tsnode] > 1.75*self.energies[tsnode-1] and self.energies[tsnode] > 1.75*self.energies[tsnode+1] and self.done_growing and n==tsnode:  #or self.climb\n        #    exsteps=2\n        #    print(\" multiplying steps for node %i by %i\" % (n,exsteps))\n        return exsteps*opt_steps\n\n\n    def set_opt_type(self,n,quiet=False):\n        #TODO error for seam climb\n        opt_type='ICTAN' \n        if self.climb and n==self.TSnode and not self.find and self.nodes[n].PES.__class__.__name__!=\"Avg_PES\":\n            opt_type='CLIMB'\n            #opt_type='BEALES_CG'\n        elif self.find and n==self.TSnode:\n            opt_type='TS'\n        elif self.nodes[n].PES.__class__.__name__==\"Avg_PES\":\n            opt_type='SEAM'\n            if self.climb and n==self.TSnode:\n                opt_type='TS-SEAM'\n        if not quiet:\n            print((\" setting node %i opt_type to %s\" %(n,opt_type)))\n\n        #if isinstance(self.optimizer[n],beales_cg) and opt_type!=\"BEALES_CG\":\n        #    raise RuntimeError(\"This shouldn't happen\")\n\n        return opt_type\n\n\n    #TODO Remove me does not deserve to be a function\n    def set_finder(self,rtype):\n        assert rtype in [0,1,2], \"rtype not defined\"\n        print('')\n        print(\"*********************************************************************\")\n        if rtype==2:\n            print(\"****************** set climber and finder to True *******************\")\n            self.climber=True\n            self.finder=True\n        elif rtype==1:\n            print(\"***************** setting climber to True*************************\")\n            self.climber=True\n        else:\n            print(\"******** Turning off climbing image and exact TS search **********\")\n        print(\"*********************************************************************\")\n \n\n\n    def com_rotate_move(self,iR,iP,iN):\n        print(\" aligning com and to Eckart Condition\")\n\n        mfrac = 0.5\n        if self.nnodes - self.current_nnodes+1  != 1:\n            mfrac = 1./(self.nnodes - self.current_nnodes+1)\n\n        #if self.__class__.__name__ != \"DE_GSM\":\n        #    # no \"product\" structure exists, use initial structure\n        #    iP = 0\n\n        xyz0 = self.nodes[iR].xyz.copy()\n        xyz1 = self.nodes[iN].xyz.copy()\n        com0 = self.nodes[iR].center_of_mass\n        com1 = self.nodes[iN].center_of_mass\n        masses = self.nodes[iR].mass_amu\n\n        # From the old GSM code doesn't work\n        #com1 = mfrac*(com2-com0)\n        #print(\"com1\")\n        #print(com1)\n        ## align centers of mass\n        #xyz1 += com1\n        #Eckart_align(xyz1,xyz2,masses,mfrac)\n\n        # rotate to be in maximal coincidence with 0\n        # assumes iP i.e. 2 is also in maximal coincidence\n        U = rotate.get_rot(xyz0,xyz1)\n        xyz1 = np.dot(xyz1,U)\n\n        ## align \n        #if self.nodes[iP] != None:\n        #    xyz2 = self.nodes[iP].xyz.copy()\n        #    com2 = self.nodes[iP].center_of_mass\n\n        #    if abs(iN-iR) > abs(iN-iP):\n        #        avg_com = mfrac*com2 + (1.-mfrac)*com0\n        #    else:\n        #        avg_com = mfrac*com0 + (1.-mfrac)*com2\n        #    dist = avg_com - com1  #final minus initial\n        #else:\n        #    dist = com0 - com1  #final minus initial\n\n        #print(\"aligning to com\")\n        #print(dist)\n        #xyz1 += dist\n\n        return xyz1\n\n\n    def find_peaks(self,rtype='opting'):\n        '''\n        This doesnt actually calculate peaks, it calculates some other thing\n        '''\n        #rtype 1: growing\n        #rtype 2: opting\n        #rtype 3: intermediate check\n        if rtype not in ['growing','opting','intermediate']: raise RuntimeError\n\n        #if rtype==1:\n        if rtype==\"growing\":\n            nnodes=self.nR\n        elif rtype==\"opting\" or rtype==\"intermediate\":\n            nnodes=self.nnodes\n        else:\n            raise ValueError(\"find peaks bad input\")\n        #if rtype==1 or rtype==2:\n        #    print \"Energy\"\n        alluptol=0.1\n        alluptol2=0.5\n        allup=True\n        diss=False\n        energies = self.energies\n        for n in range(1,len(energies[:nnodes])):\n            if energies[n]+alluptol<energies[n-1]:\n                allup=False\n                break\n\n        if energies[nnodes-1]>15.0:\n            if nnodes-3>0:\n                if ((energies[nnodes-1]-energies[nnodes-2])<alluptol2 and \n                (energies[nnodes-2]-energies[nnodes-3])<alluptol2 and\n                (energies[nnodes-3]-energies[nnodes-4])<alluptol2):\n                    print(\" possible dissociative profile\")\n                    diss=True\n\n        print(\" nnodes \",nnodes)  \n        print(\" all uphill? \",allup)\n        print(\" dissociative? \",diss)\n        npeaks1=0\n        npeaks2=0\n        minnodes=[]\n        maxnodes=[]\n        if energies[1]>energies[0]:\n            minnodes.append(0)\n        if energies[nnodes-1]<energies[nnodes-2]:\n            minnodes.append(nnodes-1)\n        for n in range(self.n0,nnodes-1):\n            if energies[n+1]>energies[n]:\n                if energies[n]<energies[n-1]:\n                    minnodes.append(n)\n            if energies[n+1]<energies[n]:\n                if energies[n]>energies[n-1]:\n                    maxnodes.append(n)\n\n        print(\" min nodes \",minnodes)\n        print(\" max nodes \", maxnodes)\n        npeaks1 = len(maxnodes)\n        #print \"number of peaks is \",npeaks1\n        ediff=0.5\n        PEAK4_EDIFF = 2.0\n        if rtype==\"growing\":\n            ediff=1.\n        if rtype==\"intermediate\":\n            ediff=PEAK4_EDIFF\n\n        if rtype==\"growing\":\n            nmax = np.argmax(energies[:self.nR])\n            emax = float(max(energies[:self.nR]))\n        else:\n            emax = float(max(energies))\n            nmax = np.argmax(energies)\n\n        print(\" emax and nmax in find peaks %3.4f,%i \" % (emax,nmax))\n\n        #check if any node after peak is less than 2 kcal below\n        for n in maxnodes:\n            diffs=( energies[n]-e>ediff for e in energies[n:nnodes])\n            if any(diffs):\n                found=n\n                npeaks2+=1\n        npeaks = npeaks2\n        print(\" found %i significant peak(s) TOL %3.2f\" %(npeaks,ediff))\n\n        #handle dissociative case\n        if rtype==\"intermediate\" and npeaks==1:\n            nextmin=0\n            for n in range(found,nnodes-1):\n                if n in minnodes:\n                    nextmin=n\n                    break\n            if nextmin>0:\n                npeaks=2\n\n        #if rtype==3:\n        #    return nmax\n        if allup==True and npeaks==0:\n            return -1\n        if diss==True and npeaks==0:\n            return -2\n\n        return npeaks\n\n\n\n    def is_converged(self,totalgrad,fp,rtype,ts_cgradq):\n        '''\n        Check if optimization is converged\n        '''\n\n        # Important the factor 5 here corresponds to the same convergence criteria in the TS optimizer \n        #TS_conv = self.CONV_TOL*5\n        TS_conv = self.CONV_TOL\n        # => Check if intermediate exists \n        #ALEX REMOVED CLIMB REQUIREMENT\n        if self.has_intermediate(self.noise):\n            print(\"New pot min: {}\".format(self.get_intermediate(self.noise)))\n            print(\"Old pot min: {}\".format(self.pot_min))\n            if self.get_intermediate(self.noise) == self.pot_min:\n                self.endearly_counter += 1\n            else:\n                self.pot_min = self.get_intermediate(self.noise)\n                self.endearly_counter = 1\n            if self.endearly_counter >= 3:\n                self.end_early=True\n                self.tscontinue=False\n                printcool(\" THERE IS AN INTERMEDIATE, OPTIMIZE THE INTERMEDIATE AND TRY AGAIN\")\n                return True\n\n        elif not self.has_intermediate(self.noise):\n            self.endearly_counter = 0\n            self.pot_min = self.get_intermediate(self.noise)\n\n        #print(\" Number of imaginary frequencies %i\" % self.optimizer[self.TSnode].nneg)\n\n        # or (totalgrad<0.1 and self.nodes[self.TSnode].gradrms<2.5*TS_conv and self.dE_iter<0.02 and self.optimizer[self.TSnode].nneg <2)  #TODO extra crit here\n        if (self.finder and self.find):\n            return (self.nodes[self.TSnode].gradrms<self.CONV_TOL and abs(ts_cgradq)<TS_conv and self.dE_iter < self.optimizer[self.TSnode].conv_Ediff*3 and self.optimizer[self.TSnode].nneg<2)\n        elif self.climber and self.climb:\n            return (self.nodes[self.TSnode].gradrms<self.CONV_TOL and abs(ts_cgradq)<TS_conv and self.dE_iter < self.optimizer[self.TSnode].conv_Ediff*3)\n        elif not self.climber and not self.finder:\n            print(\" CONV_TOL=%.4f\" %self.CONV_TOL)\n            return all([self.optimizer[n].converged for n in range(1,self.nnodes-1)])\n\n\n        return False\n\n\n    def print_energies(self):\n        for n in range(len(self.energies)):\n            print(\" {:7.3f}\".format(float(self.energies[n])), end=' ')\n        print()\n\n\n    def get_intermediate(self,noise):\n        '''\n        Check string for intermediates\n        noise is a leeway factor for determining intermediate\n        '''\n   \n        energies = self.energies\n        potential_min = []\n        for i in range(1, (len(energies) - 1)):\n            rnoise = 0\n            pnoise = 0\n            a = 1\n            b = 1\n            while (energies[i-a] >= energies[i]):\n                if (energies[i-a] - energies[i]) > rnoise:\n                    rnoise = energies[i-a] - energies[i]\n                if rnoise > noise:\n                    break\n                if (i-a) == 0:\n                    break\n                a += 1\n    \n            while (energies[i+b] >= energies[i]):\n                if (energies[i+b] - energies[i]) > pnoise:\n                    pnoise = energies[i+b] - energies[i]\n                if pnoise > noise:\n                    break\n                if (i+b) == len(energies) - 1:\n                    break\n                b += 1\n            if ((rnoise > noise) and (pnoise > noise)):\n                print('Potential minimum at image %s' % i)\n                potential_min.append(i)\n    \n        return potential_min\n\n\n    def has_intermediate(self,noise):\n        pot_min = self.get_intermediate(noise)\n        return len(pot_min)>0\n\n\n    def setup_from_geometries(self,input_geoms,reparametrize=True,restart_energies=True,start_climb_immediately=False):\n        '''\n        Restart\n        '''\n\n        printcool(\"Restarting GSM from geometries\")\n        self.growth_direction=0\n        nstructs=len(input_geoms)\n\n        if nstructs != self.nnodes:\n            print('need to interpolate: loaded {} nodes but need {}'.format(nstructs, self.nnodes))\n            #if self.interp_method==\"DLC\": TODO\n            symbols = get_atoms(input_geoms[0])\n            #old_xyzs = [ xyz_to_np( geom ) for geom in input_geoms ]\n            xyzs = [ xyz_to_np( geom ) for geom in input_geoms ]\n            #xyzs = redistribute(symbols,old_xyzs,self.nnodes,tol=2e-3*5)\n            geoms = [ np_to_xyz(input_geoms[0],xyz) for xyz in xyzs ]\n            nstructs = len(geoms)\n        else:\n            geoms = input_geoms\n\n        self.gradrms = [0.]*nstructs\n        self.dE = [1000.]*nstructs\n\n        self.isRestarted=True\n        self.done_growing=True\n\n        # set coordinates from geoms\n        self.nodes[0].xyz = xyz_to_np(geoms[0])\n        self.nodes[nstructs-1].xyz = xyz_to_np(geoms[-1])\n        for struct in range(1,nstructs-1):\n            self.nodes[struct] = Molecule.copy_from_options(self.nodes[struct-1],\n                    xyz_to_np(geoms[struct]),\n                    new_node_id=struct,\n                    copy_wavefunction=False)\n            self.nodes[struct].newHess=5\n            # Turning this off\n            #self.nodes[struct].gradrms = np.sqrt(np.dot(self.nodes[struct].gradient,self.nodes\n            #self.nodes[struct].gradrms=grmss[struct]\n            #self.nodes[struct].PES.dE = dE[struct]\n        self.nnodes=self.nR=nstructs\n\n        if start_climb_immediately:\n            # should check that this is a climber...\n            self.climb=True\n\n        if reparametrize:\n            printcool(\"Reparametrizing\")\n            self.reparameterize(ic_reparam_steps=8)\n            self.xyz_writer('grown_string_{:03}.xyz'.format(self.ID),self.geometries,self.energies,self.gradrmss,self.dEs)\n\n        if restart_energies:\n            # initial energy\n            self.nodes[0].V0 = self.nodes[0].energy \n            self.energies[0] = 0.\n            print(\" initial energy is %3.4f\" % self.nodes[0].energy)\n\n            for struct in range(1,nstructs-1):\n                print(\" energy of node %i is %5.4f\" % (struct,self.nodes[struct].energy))\n                self.energies[struct] = self.nodes[struct].energy - self.nodes[0].V0\n                print(\" Relative energy of node %i is %5.4f\" % (struct,self.energies[struct]))\n\n            print(\" V_profile: \", end=' ')\n            energies= self.energies\n            for n in range(self.nnodes):\n                print(\" {:7.3f}\".format(float(energies[n])), end=' ')\n            print()\n\n\n        self.ictan,self.dqmaga = self.get_tangents(self.nodes)\n        self.refresh_coordinates()\n        print(\" setting all interior nodes to active\")\n        for n in range(1,self.nnodes-1):\n            self.active[n]=True\n            #self.optimizer[n].conv_grms=self.CONV_TOL*2.5\n            self.optimizer[n].conv_grms=self.CONV_TOL\n            self.optimizer[n].options['DMAX'] = 0.05\n\n        return\n\n    def add_node_before_TS(self):\n        '''\n        '''\n        new_node = GSM.add_node(\n                self.nodes[self.TSnode-1],\n                self.nodes[self.TSnode],\n                stepsize=0.5,\n                node_id = self.TSnode-1,\n                )\n        new_node_list = [None]*(self.nnodes+1)\n        new_optimizers = [None]*(self.nnodes+1)\n        for n in range(0,self.TSnode-1):\n            new_node_list[n] = self.nodes[n]\n            new_optimizers[n] = self.optimizer[n]\n        new_node_list[self.TSnode-1] = new_node\n        new_optimizers[self.TSnode-1] = self.optimizer[0].__class__(self.optimizer[0].options.copy())\n\n        for n in range(self.TSnode,self.nnodes+1):\n            new_node_list[n] = Molecule.copy_from_options(MoleculeA = self.nodes[n-1], new_node_id = n)\n            new_optimizers[n] = self.optimizer[n-1]\n        self.nodes = new_node_list\n        self.optimizer = new_optimizers\n        self.nnodes = len(self.nodes)\n        print(' New number of nodes %d' % self.nnodes)\n        self.active = [True] * self.nnodes\n        self.active[0] = False\n        self.active[self.nnodes-1] = False\n\n    def add_node_after_TS(self):\n        '''\n        '''\n        new_node = GSM.add_node(\n                self.nodes[self.TSnode],\n                self.nodes[self.TSnode+1],\n                stepsize=0.5,\n                node_id = self.TSnode+1,\n                )\n        new_node_list = [None]*(self.nnodes+1)\n        new_optimizers = [None]*(self.nnodes+1)\n        for n in range(0,self.TSnode+1):\n            new_node_list[n] = self.nodes[n]\n            new_optimizers[n] = self.optimizer[n]\n        new_node_list[self.TSnode+1] = new_node\n        new_optimizers[self.TSnode+1] = self.optimizer[0].__class__(self.optimizer[0].options.copy())\n\n        for n in range(self.TSnode+2,self.nnodes+1):\n            new_node_list[n] = Molecule.copy_from_options(MoleculeA = self.nodes[n-1], new_node_id = n)\n            new_optimizers[n] = self.optimizer[n-1]\n        self.nodes = new_node_list\n        self.optimizer = new_optimizers\n        self.nnodes = len(self.nodes)\n        print(' New number of nodes %d' % self.nnodes)\n        self.active = [True] * self.nnodes\n        self.active[0] = False\n        self.active[self.nnodes-1] = False\n\n\n    def set_node_convergence(self):\n        ''' set convergence for nodes\n        '''\n\n        factor = 5. if (self.climber or self.finder) else 1.\n        TSnode=self.TSnode\n        for n in range(1,self.nnodes-1):\n            if self.nodes[n] !=None:\n                #self.optimizer[n].conv_grms = self.CONV_TOL*factor\n                self.optimizer[n].conv_grms = self.CONV_TOL\n                self.optimizer[n].conv_gmax = self.options['CONV_gmax']*factor\n                self.optimizer[n].conv_Ediff = self.options['CONV_Ediff']*factor\n                if self.optimizer[n].converged:\n                    self.optimizer[n].check_only_grad_converged=True\n                if (self.climb or self.find) and self.energies[n]>self.energies[TSnode]*0.75 and n!=TSnode:\n                    self.optimizer[n].conv_grms = self.CONV_TOL     \n                    self.optimizer[n].conv_gmax = self.options['CONV_gmax']\n                    self.optimizer[n].conv_Ediff = self.options['CONV_Ediff']\n                    self.optimizer[n].check_only_grad_converged=False\n                if n==self.TSnode and (self.climb or self.find):\n                    self.optimizer[n].conv_grms = self.CONV_TOL     \n                    self.optimizer[n].conv_gmax = self.options['CONV_gmax']\n                    self.optimizer[n].conv_Ediff = self.options['CONV_Ediff']\n\n\n    def slow_down_climb(self):\n        if self.climb and not self.find:\n            print(\" slowing down climb optimization\")\n            self.optimizer[self.TSnode].options['DMAX'] /= self.newclimbscale\n            self.optimizer[self.TSnode].options['SCALEQN'] = 2.\n            if self.optimizer[self.TSnode].SCALE_CLIMB <5.:\n                self.optimizer[self.TSnode].SCALE_CLIMB +=1.\n            self.optimizer[self.pTSnode].options['SCALEQN'] = 1.\n            self.ts_exsteps=1\n            if self.newclimbscale<5.0:\n                self.newclimbscale +=1.\n        elif self.find:\n            self.find = False\n            self.climb = True\n            self.nclimb=1\n            print(\" Find bad, going back to climb\")\n\n", "meta": {"hexsha": "7cc94572fc7da05f89594baded09734eea707cbe", "size": 53392, "ext": "py", "lang": "Python", "max_stars_repo_path": "pygsm/growing_string_methods/main_gsm.py", "max_stars_repo_name": "bwvdg/pygsm", "max_stars_repo_head_hexsha": "de2c9ae86bc055bb9b2e6ffb46d403e689bf0bb3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pygsm/growing_string_methods/main_gsm.py", "max_issues_repo_name": "bwvdg/pygsm", "max_issues_repo_head_hexsha": "de2c9ae86bc055bb9b2e6ffb46d403e689bf0bb3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pygsm/growing_string_methods/main_gsm.py", "max_forks_repo_name": "bwvdg/pygsm", "max_forks_repo_head_hexsha": "de2c9ae86bc055bb9b2e6ffb46d403e689bf0bb3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.023988006, "max_line_length": 211, "alphanum_fraction": 0.5357356907, "include": true, "reason": "import numpy", "num_tokens": 13356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.28140560140262283, "lm_q1q2_score": 0.18626880496072126}}
{"text": "\n# Copyright (C) 2012 Victor Semionov\n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#  * Redistributions of source code must retain the above copyright notice, this\n#    list of conditions and the following disclaimer.\n#  * Redistributions in binary form must reproduce the above copyright notice,\n#    this list of conditions and the following disclaimer in the documentation\n#    and/or other materials provided with the distribution.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\nimport sys\nimport os\n\nimport math\n\nimport numpy as np\n\nimport model\n\nimport params\nimport output\nimport unitconv\n\n\nclass ComputationError(Exception):\n    pass\n\n\nclass PulseTrainMock(object):\n    \n    def __init__(self, pulse, count, period):\n        self.pulse = pulse\n        self.count = count\n        self.period = period\n\n\ndef create_medium(ref_inversion):\n    initial_inversion = None\n    if ref_inversion is not None:\n        initial_inversion = initial_inversion = model.inversion.UniformInversion(ref_inversion)\n    doping_agent = model.dopant.DopingAgent(params.lasing_wavelen, params.dopant_xsection, params.dopant_upper_lifetime, params.dopant_lower_lifetime, params.dopant_branching_ratio, params.dopant_concentration)\n    medium = model.medium.ActiveMedium(initial_inversion, doping_agent, params.medium_radius, params.medium_length, params.medium_refr_idx)\n    return medium\n\ndef create_beam():\n    pulse_photon_count = model.energy.photon_count(params.lasing_wavelen, params.pulse_energy)\n    ref_fluence = params.beam_class.ref_fluence(params.beam_radius, pulse_photon_count)\n    beam = params.beam_class(params.beam_radius, ref_fluence)\n    return beam\n\ndef create_pulse(active_medium, beam, rho, phi, ret_time_trunc_rel_error=False):\n    fluence = beam.fluence(rho, phi)\n    ref_density = params.pulse_class.ref_density(active_medium.light_speed, params.pulse_duration, fluence)\n    pulse = params.pulse_class(-params.pulse_duration/2.0, params.pulse_duration, ref_density)\n    scale, time_trunc_rel_error = model.error.pulse_scale(pulse, params.time_trunc_rtol)\n    pulse = model.pulse.ExtendedPulse(pulse, scale)\n    pulse = model.pulse.TruncatedPulse(pulse)\n    return (pulse, time_trunc_rel_error) if ret_time_trunc_rel_error else pulse\n\ndef create_train(pulse):\n    train = PulseTrainMock(pulse, params.train_pulse_count, params.train_pulse_period)\n    return train\n\ndef create_depop_model(active_medium, depop_model_class):\n    is_numerical = issubclass(depop_model_class, model.depop.NumericalDepopulationModel)\n    if is_numerical:\n        depop_model_kwargs = dict(rtol=params.depop_rate_rtol, min_samples=params.depop_rate_min_samples)\n    else:\n        depop_model_kwargs = {}\n    if depop_model_class is params.depop_model_class:\n        depop_model_kwargs.update(params.depop_model_extra_args)\n    depop_model = depop_model_class(active_medium, **depop_model_kwargs)\n    return depop_model\n\ndef compute_inversion(dirname):\n    print output.div_line\n    print \"computing population inversion\"\n    \n    active_medium = create_medium(None)\n    pump_system = model.pump.PumpSystem(params.pump_wavelen, params.pump_duration, params.pump_power, params.pump_efficiency)\n    depop_model = create_depop_model(active_medium, params.depop_model_class)\n    inv = params.inverter_class(active_medium, pump_system, depop_model)\n    \n    ref_inversion = inv.invert(params.inversion_rtol, params.inversion_min_count_t)\n    rate_evals = (len(inv.inversion) - 1) * inv.evals_per_step\n    pump_energy = params.pump_duration * params.pump_power\n    stored_energy = model.energy.energy(params.lasing_wavelen, ref_inversion * active_medium.volume)\n    \n    if params.verbose:\n        print \"count_t:\", len(inv.T)\n        print \"depopulation rate evaluation count:\", rate_evals\n    \n    if params.inversion_validate:\n        print \"validating uniform ASE-induced depopulation rate approximation\"\n        ross_num_model = depop_model if isinstance(depop_model, model.depop.RossNumericalASEModel) else model.depop.RossNumericalASEModel(active_medium, params.depop_rate_rtol, params.depop_rate_min_samples)\n        rate_rel_stddev = ross_num_model.rate_rel_stddev(ref_inversion)\n        unitconv.print_result(\"depopulation rate rel. std. deviation [{}]: {}\", (\"%\",), (rate_rel_stddev,))\n        if rate_rel_stddev > 10.0e-2:\n            output.warn(\"uniform ASE-induced depopulation rate approximation is invalid\")\n    \n    if isinstance(depop_model, model.depop.NumericalDepopulationModel):\n        print \"perturbing population inversion\"\n        perturb_depop_model = model.depop.PerturbedDepopulationModel(depop_model)\n        perturb_inv = params.inverter_class(active_medium, pump_system, perturb_depop_model)\n        perturb_ref_inversion = perturb_inv.invert(params.inversion_rtol, params.inversion_min_count_t)\n        rel_error = model.error.perturbed_inversion_rel_error(ref_inversion, perturb_ref_inversion, params.inversion_rtol)\n    else:\n        rel_error = params.inversion_rtol\n    \n    gain_coef = ref_inversion * active_medium.doping_agent.xsection\n    gain = math.exp(gain_coef * active_medium.length)\n    \n    ref_inversion_atol = ref_inversion * rel_error\n    gain_atol = gain * (math.exp(ref_inversion_atol * active_medium.doping_agent.xsection * active_medium.length) - 1.0)\n    stored_energy_atol = stored_energy * rel_error\n    \n    unitconv.print_result(\"pump energy [{}]: {}\", (\"mJ\",), (pump_energy,))\n    unitconv.print_result(\"population inversion [{}]: {} ~ {}\", (\"cm^-3\",), (ref_inversion, ref_inversion_atol))\n    unitconv.print_result(\"small signal gain: {} ~ {}\", (), (gain, gain_atol))\n    unitconv.print_result(\"stored energy [{}]: {} ~ {}\", (\"mJ\",), (stored_energy, stored_energy_atol))\n    \n    if params.graphs:\n        print output.status_writing\n        dirname = output.init_dir(dirname)\n        output.plot_inversion(dirname, inv)\n    \n    return ref_inversion, rel_error\n\ndef most_efficient_methods((int_types, amp_types), active_medium, input_beam, ref_pulse, quiet=False):\n    if not quiet:\n        print output.div_line\n    if not quiet or params.verbose:\n        print \"determining most efficient method combination\"\n    \n    min_xverse = (params.min_count_rho, params.min_count_phi)\n    min_evo = (min_count_z, min_count_t) = (params.min_count_z, params.min_count_t)\n    \n    pulse_train = create_train(ref_pulse)\n    \n    best_method = None\n    limit = 0\n    \n    for int_type in int_types:\n        if params.verbose:\n            print int_type.__name__\n        \n        integrator = model.integrator.DomainIntegrator(int_type)\n        min_count_int = integrator.num_integrator.min_count\n        min_count_amp_z = model.discrete.steps(model.discrete.divs(max(min_count_z, min_count_int)))\n        min_count_amp_t = model.discrete.steps(model.discrete.divs(max(min_count_t, min_count_int)))\n        min_count_amp = min_count_amp_z * min_count_amp_t\n        int_limit = limit // min_count_amp\n        try:\n            (count_rho, count_phi), int_rel_error = model.error.min_integration_steps(integrator, min_xverse, params.int_rtol, int_limit, active_medium, input_beam)\n        except model.exc.SoftLimitError:\n            sys.exc_clear()\n            continue\n        except (ValueError, MemoryError):\n            output.print_exception()\n            print >>sys.stderr, \"attempting to recover\"\n            sys.exc_clear()\n            continue\n        \n        for amp_type in amp_types:\n            if params.verbose:\n                print amp_type.__name__\n            \n            count_xverse = count_rho * count_phi\n            amp_limit = limit // count_xverse\n            try:\n                (count_z, count_t), amp_rel_error = model.error.min_amplification_steps(amp_type, min_evo, params.amp_rtol, amp_limit, active_medium, pulse_train, None, integrator)\n            except model.exc.SoftLimitError:\n                sys.exc_clear()\n                continue\n            except (ValueError, MemoryError):\n                output.print_exception()\n                print >>sys.stderr, \"attempting to recover\"\n                sys.exc_clear()\n                continue\n            \n            count = count_rho * count_phi * count_z * count_t\n            is_best = False\n            if best_method is None:\n                is_best = True\n            else:\n                _, _, best_count, (best_amp_rel_error, best_int_rel_error) = best_method\n                if count < best_count:\n                    is_best = True\n                elif count == best_count:\n                    if (amp_rel_error + int_rel_error) < (best_amp_rel_error + best_int_rel_error):\n                        is_best = True\n            if is_best:\n                best_method = (int_type, amp_type), (count_rho, count_phi, count_z, count_t), count, (amp_rel_error, int_rel_error)\n                limit = count\n    \n    if best_method is None:\n        raise ComputationError(\"no suitable numerical method combination found\")\n    \n    (int_type, amp_type), (count_rho, count_phi, count_z, count_t), _, (amp_rel_error, int_rel_error) = best_method\n    return (int_type, amp_type), (count_rho, count_phi, count_z, count_t), (amp_rel_error, int_rel_error)\n\ndef select_methods((int_types, amp_types), ref_inversion, quiet=False):\n    active_medium = create_medium(ref_inversion)\n    input_beam = create_beam()\n    ref_pulse, time_trunc_rel_error = create_pulse(active_medium, input_beam, input_beam.rho_ref, input_beam.phi_ref, ret_time_trunc_rel_error=True)\n    \n    methods = most_efficient_methods((int_types, amp_types), active_medium, input_beam, ref_pulse, quiet)\n    (int_type, amp_type), (count_rho, count_phi, count_z, count_t), (amp_rel_error, int_rel_error) = methods\n    \n    if params.verbose:\n        print \"int_type: %s; amp_type: %s\" % (int_type.__name__, amp_type.__name__, )\n        print \"count_rho: %d; count_phi: %d\" % (count_rho, count_phi)\n        print \"count_z: %d; count_t: %d\" % (count_z, count_t)\n    \n    numerics = (int_type, amp_type), (count_rho, count_phi, count_z, count_t)\n    rel_errors = time_trunc_rel_error, amp_rel_error, int_rel_error\n    return numerics, rel_errors\n\ndef amplify_ref_pulse(dirname, num_types, counts, ref_inversion):\n    print output.div_line\n    print \"amplifying ref. pulse\"\n    \n    dirname = os.path.join(dirname, output.ref_pulse_rel_path)\n    \n    (int_type, amp_type), (_, _, count_z, count_t) = num_types, counts\n    \n    active_medium = create_medium(ref_inversion)\n    input_beam = create_beam()\n    rho, phi = input_beam.rho_ref, input_beam.phi_ref\n    ref_pulse = create_pulse(active_medium, input_beam, rho, phi)\n    \n    integrator = model.integrator.DomainIntegrator(int_type)\n    amp = amp_type(active_medium, count_z)\n    \n    num_density_out, _ = amp.amplify(rho, phi, ref_pulse, count_t)\n    \n    if active_medium.doping_agent.lower_lifetime in model.amplifier.ExactAmplifier.analytical_lower_lifetimes:\n        exact_amp = model.amplifier.ExactOutputAmplifier(active_medium, count_z)\n        exact_density_out, exact_population_final = exact_amp.amplify(rho, phi, ref_pulse, count_t)\n    else:\n        exact_density_out, exact_population_final = None, None\n    \n    fluence_out = integrator.integrate(amp.T, num_density_out) * active_medium.light_speed\n    fluence_gain = fluence_out / input_beam.ref_fluence\n    unitconv.print_result(\"fluence gain: {}\", (), (fluence_gain,))\n    \n    if params.graphs:\n        count_z = len(amp.Z)\n        fluences = np.empty(count_z)\n        for l in range(count_z):\n            fluences[l] = integrator.integrate(amp.T, amp.density[l]) * active_medium.light_speed\n        print output.status_writing\n        dirname = output.init_dir(dirname)\n        output.plot_output(dirname, input_beam, ref_pulse, params.pulse_duration, amp, fluences, exact_density_out, exact_population_final)\n\ndef amplify_train(dirname, num_types, counts, ref_inversion, quiet=False):\n    if not quiet:\n        print output.div_line\n    if not quiet or params.verbose:\n        print \"amplifying pulse train\"\n    \n    active_medium = create_medium(ref_inversion)\n    input_beam = create_beam()\n    ref_pulse = create_pulse(active_medium, input_beam, input_beam.rho_ref, input_beam.phi_ref)\n    pulse_train = create_train(ref_pulse)\n    \n    int_type, amp_type = num_types\n    count_rho, count_phi, count_z, count_t = counts\n    integrator = model.integrator.DomainIntegrator(int_type)\n    amp = amp_type(active_medium, count_z)\n    \n    radius = min(active_medium.radius, input_beam.rho_trunc)\n    Rho = np.linspace(0.0, radius, count_rho)\n    Phi = np.linspace(0.0, 2.0*math.pi, count_phi)\n    \n    output_fluence = np.empty((count_rho, count_phi))\n    \n    max_fluences = np.empty(params.train_pulse_count)\n    output_photon_counts = np.empty(params.train_pulse_count)\n    \n    populations = [[None] * count_phi for _ in range(count_rho)]\n    for m, rho in enumerate(Rho):\n        for n, phi in enumerate(Phi):\n            upper = np.vectorize(active_medium.initial_inversion.inversion)(rho, phi, amp.Z)\n            lower = np.zeros(count_z)\n            populations[m][n] = (upper, lower)\n    \n    norm_beam = params.beam_class(params.beam_radius, 1.0)\n    norm_pulse = create_pulse(active_medium, norm_beam, norm_beam.rho_ref, norm_beam.phi_ref)\n    amp._init_time(norm_pulse, count_t)\n    norm_input_density = np.vectorize(norm_pulse.density)(amp.T)\n    \n    lower_decay = model.amplifier.lower_state_decay(active_medium, pulse_train)\n    \n    pulse_num_stride = params.pulse_num_stride\n    for pnum in range(params.train_pulse_count):\n        if not quiet or params.verbose:\n            output.show_status((pnum, None), (pulse_num_stride, None), False)\n        \n        for m, rho in enumerate(Rho):\n            for n, phi in enumerate(Phi):\n                input_density = norm_input_density * input_beam.fluence(rho, phi)\n                \n                density_out, population_final = amp.amplify(rho, phi, None, None, T=amp.T, initial_population=populations[m][n], input_density=input_density)\n                \n                upper = np.copy(population_final[0])\n                lower = population_final[1] * lower_decay\n                populations[m][n] = (upper, lower)\n                \n                fluence_out = integrator.integrate(amp.T, density_out) * active_medium.light_speed\n                output_fluence[m, n] = fluence_out\n        \n        if pnum == 0:\n            ref_idx = np.unravel_index(output_fluence.argmax(), output_fluence.shape)\n            ref_output_fluence = np.copy(output_fluence)\n        max_fluences[pnum] = output_fluence[ref_idx]\n        output_photon_counts[pnum] = integrator.integrate_base(active_medium, input_beam, Rho, Phi, output_fluence)\n    \n    del input_density, density_out, population_final, upper, lower\n    del amp, output_fluence, populations, norm_input_density\n    \n    if not quiet or params.verbose:\n        output.show_status((pnum+1, None), (pulse_num_stride, None), True)\n    \n    if not quiet or params.verbose:\n        print \"processing results\"\n    \n    max_output_fluence = max_fluences[::-1].sum()\n    max_output_fluence = model.energy.energy(params.lasing_wavelen, max_output_fluence)\n    del max_fluences\n    \n    train_output_photon_count = output_photon_counts[::-1].sum()\n    train_output_energy = model.energy.energy(params.lasing_wavelen, train_output_photon_count)\n    \n    rel_gain_decrease = 1.0 - output_photon_counts[-1] / output_photon_counts[0]\n    \n    if not quiet:\n        if params.graphs:\n            print output.status_writing\n            ref_pulse_dir = os.path.join(dirname, output.ref_pulse_rel_path)\n            dirname = output.init_dir(dirname)\n            ref_pulse_dir = output.init_dir(ref_pulse_dir)\n            output.plot_beam(ref_pulse_dir, input_beam, Rho, Phi, ref_output_fluence)\n            output.plot_train(dirname, input_beam, active_medium, output_photon_counts)\n    \n    return max_output_fluence, output_photon_counts, train_output_energy, rel_gain_decrease\n\ndef report_results(ref_inversion, max_output_fluence, output_photon_counts, output_energy, rel_gain_decrease, inversion_rel_error, rel_errors):\n    print output.div_line\n    print \"results:\"\n    \n    active_medium = create_medium(ref_inversion)\n    \n    energy_rel_error = model.error.energy_rel_error(active_medium, inversion_rel_error, rel_errors)\n    \n    pump_energy = params.pump_duration * params.pump_power\n    stored_energy = model.energy.energy(params.lasing_wavelen, ref_inversion * active_medium.volume)\n    \n    input_beam = create_beam()\n    \n    input_photon_count = input_beam.fluence_integral(active_medium.radius)\n    input_energy = model.energy.energy(params.lasing_wavelen, input_photon_count)\n    input_energy *= params.train_pulse_count\n    \n    energy_gain = output_energy / input_energy\n    added_energy = output_energy - input_energy\n    extraction_eff = added_energy / stored_energy\n    total_eff = added_energy / pump_energy\n    \n    stored_energy_abs_error = inversion_rel_error * stored_energy\n    output_energy_abs_error = energy_rel_error * output_energy\n    energy_gain_abs_error = energy_rel_error * energy_gain\n    \n    extraction_eff_abs_error = (added_energy + output_energy_abs_error) / max(stored_energy - stored_energy_abs_error, 0.0) - extraction_eff\n    total_eff_abs_error = output_energy_abs_error / pump_energy\n    \n    max_output_fluence_abs_error = max_output_fluence * energy_rel_error\n    \n    photon_count_first, photon_count_last = output_photon_counts[0], output_photon_counts[-1]\n    photon_count_first_abs_error, photon_count_last_abs_error = photon_count_first * energy_rel_error, photon_count_last * energy_rel_error\n    rel_gain_decrease_abs_error = 0.0\n    if params.train_pulse_count > 1:\n        rel_gain_decrease_abs_error = (photon_count_last + photon_count_last_abs_error) / max(photon_count_first - photon_count_first_abs_error, 0.0) - photon_count_last / photon_count_first\n    \n    unitconv.print_result(\"input energy [{}]: {}\", (\"mJ\",), (input_energy,))\n    unitconv.print_result(\"output energy [{}]: {} ~ {}\", (\"mJ\",), (output_energy, output_energy_abs_error))\n    unitconv.print_result(\"energy gain: {} ~ {}\", (), (energy_gain, energy_gain_abs_error))\n    unitconv.print_result(\"extraction efficiency [{}]: {} ~ {}\", (\"%\",), (extraction_eff, extraction_eff_abs_error))\n    unitconv.print_result(\"opt.-opt. efficiency [{}]: {} ~ {}\", (\"%\",), (total_eff, total_eff_abs_error))\n    unitconv.print_result(\"max. output fluence [{}]: {} ~ {}\", (\"J/cm^2\",), (max_output_fluence, max_output_fluence_abs_error))\n    unitconv.print_result(\"rel. gain decrease [{}]: {} ~ {}\", (\"%\",), (rel_gain_decrease, rel_gain_decrease_abs_error))\n", "meta": {"hexsha": "3649acf35bc8f6e9169da5e4e2eb93eb890b02ab", "size": 19527, "ext": "py", "lang": "Python", "max_stars_repo_path": "npamp/core.py", "max_stars_repo_name": "vsemionov/npamp", "max_stars_repo_head_hexsha": "b1eb07c7fe8204f4e316a26b56b12caa9b54d0b2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2016-03-18T16:02:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T00:59:28.000Z", "max_issues_repo_path": "npamp/core.py", "max_issues_repo_name": "vsemionov/npamp", "max_issues_repo_head_hexsha": "b1eb07c7fe8204f4e316a26b56b12caa9b54d0b2", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "npamp/core.py", "max_forks_repo_name": "vsemionov/npamp", "max_forks_repo_head_hexsha": "b1eb07c7fe8204f4e316a26b56b12caa9b54d0b2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-09-22T08:11:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T00:59:27.000Z", "avg_line_length": 48.0960591133, "max_line_length": 210, "alphanum_fraction": 0.7147027193, "include": true, "reason": "import numpy", "num_tokens": 4606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.2974699426047947, "lm_q1q2_score": 0.18625312306357772}}
{"text": "\"\"\"\n@author: mkowalska\n\"\"\"\nimport os\nfrom os.path import expanduser\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime\nimport time\n\nfrom kcsd import csd_profile as CSD\nfrom kcsd import ValidateKCSD1D, SpectralStructure\n\n__abs_file__ = os.path.abspath(__file__)\n\n\ndef makemydir(directory):\n    \"\"\"\n    Creates a new folder if it doesn't exist\n\n    Parameters\n    ----------\n    directory: string\n        directory\n\n    Returns\n    -------\n    None\n    \"\"\"\n    try:\n        os.makedirs(directory)\n    except OSError:\n        pass\n    os.chdir(directory)\n\n\ndef save_source_code(save_path, timestr):\n    \"\"\"\n    Saves the source code.\n\n    Parameters\n    ----------\n    save_path: string\n        directory\n    timestr: float\n\n    Returns\n    -------\n    None\n    \"\"\"\n    with open(save_path + '/source_code_' + str(timestr), 'w') as sf:\n        sf.write(open(__file__).read())\n\n\ndef stability_M(csd_profile, csd_seed, n_src, ele_lims, true_csd_xlims,\n                total_ele, noise=0, method='cross-validation', Rs=None,\n                lambdas=None):\n    \"\"\"\n    Investigates stability of reconstruction for different number of basis\n    sources\n\n    Parameters\n    ----------\n    csd_profile: function\n        Function to produce csd profile.\n    csd_seed: int\n        Seed for random generator to choose random CSD profile.\n    n_src: int\n        Number of basis sources.\n    ele_lims: list\n        Boundaries for electrodes placement.\n    true_csd_xlims: list\n        Boundaries for ground truth space.\n    total_ele: int\n        Number of electrodes.\n    noise: float\n        Determines the level of noise in the data.\n        Default: 0.\n    method: string\n        Determines the method of regularization.\n        Default: cross-validation.\n    Rs: numpy 1D array\n        Basis source parameter for crossvalidation.\n        Default: None.\n    lambdas: numpy 1D array\n        Regularization parameter for crossvalidation.\n        Default: None.\n\n    Returns\n    -------\n    obj_all: class object\n    rms: float\n        Normalized error of reconstruction.\n    point_error_all: numpy array\n        Normalized error of reconstruction calculated separetly at every point\n        point of estimation space.\n    eigenvalues: numpy array\n        Eigenvalues of k_pot matrix.\n    eigenvectors: numpy array\n        Eigen vectors of k_pot matrix.\n    \"\"\"\n    obj_all = []\n    rms = np.zeros((len(n_src)))\n    point_error_all = []\n    eigenvectors = np.zeros((len(n_src), total_ele, total_ele))\n    eigenvalues = np.zeros((len(n_src), total_ele))\n    for i, value in enumerate(n_src):\n        KK = ValidateKCSD1D(csd_seed, n_src_init=value, R_init=0.23,\n                            ele_lims=ele_lims, true_csd_xlims=true_csd_xlims,\n                            sigma=0.3, h=0.25, src_type='gauss', est_xres=0.01)\n        obj, rms[i], point_error = KK.make_reconstruction(csd_profile,\n                                                          csd_seed,\n                                                          total_ele=total_ele,\n                                                          noise=noise,\n                                                          Rs=Rs,\n                                                          lambdas=lambdas)\n        ss = SpectralStructure(obj)\n        eigenvectors[i], eigenvalues[i] = ss.evd()\n        point_error_all.append(point_error)\n        obj_all.append(obj)\n    return obj_all, rms, point_error_all, eigenvalues, eigenvectors\n\n\ndef plot_M(n_src_init, rms, save_path):\n    \"\"\"\n    Creates plot of relationship between RMS error and different number of\n    basis sources\n\n    Parameters\n    ----------\n    n_src_init: list\n        List of number of basis sources.\n    rms: numpy array\n        Error of reconstruction.\n    save_path: string\n        Directory.\n\n    Returns\n    -------\n    None\n    \"\"\"\n    fig = plt.figure()\n    plt.plot(n_src_init, rms, '--', marker='.')\n    plt.xscale('log')\n    plt.title('Stability of reconstruction for different number of basis '\n              'sources')\n    plt.xlabel('Number of basis sources')\n    plt.ylabel('RMS')\n    plt.show()\n    save_as = (save_path + '/RMS_for_different_M')\n    fig.savefig(os.path.join(save_path, save_as+'.png'))\n    plt.close()\n\n\ndef plot_eigenvalues(eigenvalues, save_path, n_src):\n    \"\"\"\n    Creates plot of eigenvalues of kernel matrix (k_pot) for different number\n    of basis sources\n\n    Parameters\n    ----------\n    eigenvalues: numpy array\n        Eigenvalues of k_pot matrix.\n    save_path: string\n        Directory.\n    n_src: list\n        List of number of basis sources.\n\n    Returns\n    -------\n    None\n    \"\"\"\n    fig = plt.figure()\n    for indx, i in enumerate(n_src):\n        plt.plot(eigenvalues[indx], '--', marker='.', label='M='+str(i))\n    plt.legend()\n#    plt.title('Eigenvalue decomposition of kernel matrix for different number '\n#              'of basis sources')\n    plt.xlabel('Number of components')\n    plt.ylabel('Eigenvalues')\n    plt.yscale('log')\n    save_as = (save_path + '/eigenvalues_for_different_M')\n    fig.savefig(os.path.join(save_path, save_as+'.png'))\n    plt.close()\n\n\ndef plot_max_eigenvalue_M(eigenvalues, save_path, n_src):\n    \"\"\"\n    Creates plot of eigenvalues of kernel matrix (k_pot) for different number\n    of basis sources\n\n    Parameters\n    ----------\n    eigenvalues: numpy array\n        Eigenvalues of k_pot matrix.\n    save_path: string\n        Directory.\n    n_src: list\n        List of number of basis sources.\n\n    Returns\n    -------\n    None\n    \"\"\"\n    fig = plt.figure(figsize=(8, 6))\n    plt.plot(n_src, eigenvalues[:, 0], '--', marker='.', label=r'$\\mu_1$')\n    plt.legend()\n    plt.title('First eigenvalue in the function of different number of basis'\n              'sources')\n    plt.xlabel('Number of basis sources')\n    plt.xscale('log')\n    plt.ylabel('Eigenvalues')\n    plt.yscale('log')\n    save_as = (save_path + '/max_eigenvalue_different_M')\n    fig.savefig(os.path.join(save_path, save_as+'.png'))\n    plt.close()\n\n\ndef plot_eigenvectors(eigenvectors, save_path, n_src):\n    \"\"\"\n    Creates plot of eigenvectors of kernel matrix (k_pot) for different number\n    of basis sources\n\n    Parameters\n    ----------\n    eigenvectors: numpy array\n        Eigenvectors of k_pot matrix.\n    save_path: string\n        Directory.\n    n_src: list\n        List of number of basis sources.\n\n    Returns\n    -------\n    None\n    \"\"\"\n    fig = plt.figure(figsize=(15, 15))\n#    plt.suptitle('Eigenvalue decomposition of kernel matrix for different '\n#                 'number of basis sources')\n    for i in range(eigenvectors.shape[2]):\n        plt.subplot(int(eigenvectors.shape[2]/2) + 1, 2, i + 1)\n        for idx, j in enumerate(n_src):\n            plt.plot(eigenvectors[idx, :, i].T, '--', marker='.',\n                     label='M='+str(j))\n        plt.ylabel('Eigenvectors')\n        plt.title(r'$v_' + str(i + 1) + '$')\n    plt.legend(bbox_to_anchor=(1.04, 1), loc=\"upper left\")\n    plt.xlabel('Number of components')\n    plt.tight_layout()\n    plt.show()\n    save_as = (save_path + '/eigenvectors_for_different_M')\n    fig.savefig(os.path.join(save_path, save_as+'.png'))\n    plt.close()\n\n\ndef plot_k_interp_cross(k_icross, save_path, n_src):\n    \"\"\"\n    Creates plot of vectors of cross kernel matrix (k_interp_cross) for\n    different number of basis sources\n\n    Parameters\n    ----------\n    k_icross: numpy array\n        List of cross kernel matrixes for different number of basis sources.\n    save_path: string\n        Directory.\n    n_src: list\n        List of number of basis sources.\n\n    Returns\n    -------\n    None\n    \"\"\"\n    fig = plt.figure(figsize=(k_icross[0].shape[1] + 5,\n                              k_icross[0].shape[1] + 5))\n#    plt.suptitle('Vectors of cross kernel matrix for different number '\n#                 'of basis sources')\n    for i in range(k_icross[0].shape[1]):\n        plt.subplot(int(k_icross[0].shape[1]/2) + 1, 2, i + 1)\n        for idx, j in enumerate(n_src):\n            plt.plot(k_icross[idx][:, i], '--', marker='.',\n                     label='M='+str(j))\n            plt.title(r'$\\tilde{K}_' + str(i + 1) + '$')\n        plt.ylabel('Cross kernel')\n    plt.legend(bbox_to_anchor=(1.04, 1), loc=\"upper left\")\n    plt.xlabel('Number of estimation points')\n    plt.tight_layout()\n    plt.show()\n    save_path = save_path + '/cross_kernel'\n    makemydir(save_path)\n    save_as = (save_path + '/cross_kernel_for_different_M')\n    fig.savefig(os.path.join(save_path, save_as+'.png'))\n    plt.close()\n\n\ndef plot_eigenvalue_lambda(eigenvalues, lambd, save_path, n_src):\n    \"\"\"\n    Creates plot of eigenvalues of kernel matrix (k_pot) with lambda for\n    different number of basis sources\n\n    Parameters\n    ----------\n    eigenvalues: numpy array\n        Eigenvalues of k_pot matrix.\n    lambd: list\n        Regularization parameter.\n    save_path: string\n        Directory.\n    n_src: list\n        List of number of basis sources.\n\n    Returns\n    -------\n    None\n    \"\"\"\n    fig = plt.figure(figsize=(7, 7))\n    x = np.arange(1, eigenvalues.shape[1] + 1)\n    for indx, i in enumerate(n_src):\n        plt.plot(x, 1/(eigenvalues[indx] + lambd[indx]), '--', marker='.',\n                 label='M='+str(i))\n    plt.legend()\n    plt.title(r'$\\frac{1}{(\\mu_j + \\lambda)}$')\n    plt.xlabel('Components number j')\n    plt.ylabel(r'1/($\\mu_j + \\lambda)$')\n    plt.yscale('log')\n    plt.tight_layout()\n    plt.show()\n    save_path = save_path + '/cross_kernel'\n    makemydir(save_path)\n    save_as = (save_path + '/eigenvalues_coefficients_for_different_M')\n    fig.savefig(os.path.join(save_path, save_as+'.png'))\n    plt.close()\n\n\ndef plot_k_interp_cross_v(k_icross, eigenvectors, save_path, n_src):\n    \"\"\"\n    Creates plot of product of cross kernel vectors and eigenvectors for\n    different number of basis sources\n\n    Parameters\n    ----------\n    k_icross: numpy array\n        List of cross kernel matrixes for different number of basis sources.\n    eigenvectors: numpy array\n        Eigenvectors of k_pot matrix.\n    save_path: string\n        Directory.\n    n_src: list\n        List of number of basis sources.\n\n    Returns\n    -------\n    None\n    \"\"\"\n    fig = plt.figure(figsize=(k_icross[0].shape[1] + 5,\n                              k_icross[0].shape[1] + 5))\n#    plt.suptitle('Vectors of cross kernel and eigenvectors product for '\n#                 'different number of basis sources')\n    for i in range(k_icross[0].shape[1]):\n        plt.subplot(int(k_icross[0].shape[1]/2) + 1, 2, i + 1)\n        for idx, j in enumerate(n_src):\n            plt.plot(np.dot(k_icross[idx], eigenvectors[idx, :, i]), '--',\n                     marker='.', label='M='+str(j))\n            plt.title(r'$\\tilde{K}*v_' + str(i) + '$')\n#        plt.ylabel(r'$\\tilde{K}*v_' + str(i) + '$')\n    plt.legend(bbox_to_anchor=(1.04, 1), loc=\"upper left\")\n    plt.xlabel('Number of estimation points')\n    plt.tight_layout()\n    plt.show()\n    save_path = save_path + '/cross_kernel'\n    makemydir(save_path)\n    save_as = (save_path + '/cross_kernel_eigenvector_product_for_different_M')\n    fig.savefig(os.path.join(save_path, save_as+'.png'))\n    plt.close()\n\n\ndef plot_k_pot(k_pot, save_path, n_src):\n    \"\"\"\n    Creates plot of vectors of kernel matrix (k_pot) for\n    different number of basis sources\n\n    Parameters\n    ----------\n    k_pot: numpy array\n        List of kernel matrixes for different number of basis sources.\n    save_path: string\n        Directory.\n    n_src: list\n        List of number of basis sources.\n\n    Returns\n    -------\n    None\n    \"\"\"\n    fig = plt.figure(figsize=(k_pot[0].shape[1] + 5,\n                              k_pot[0].shape[1] + 5))\n#    plt.suptitle('Vectors of kernel matrix for different number '\n#                 'of basis sources')\n    for i in range(k_pot[0].shape[1]):\n        plt.subplot(int(k_pot[0].shape[1]/2) + 1, 2, i + 1)\n        for idx, j in enumerate(n_src):\n            plt.plot(k_pot[idx][:, i], '--', marker='.',\n                     label='M='+str(j))\n            plt.title(r'$K_' + str(i + 1) + '$')\n        plt.ylabel('Kernel')\n    plt.legend(bbox_to_anchor=(1.04, 1), loc=\"upper left\")\n    plt.xlabel('Number of components')\n    plt.tight_layout()\n    plt.show()\n    save_path = save_path + '/kernel'\n    makemydir(save_path)\n    save_as = (save_path + '/kernel_for_different_M')\n    fig.savefig(os.path.join(save_path, save_as+'.png'))\n    plt.close()\n\n\nif __name__ == '__main__':\n    HOME = expanduser('~')\n    DAY = datetime.datetime.now()\n    DAY = DAY.strftime('%Y%m%d')\n    TIMESTR = time.strftime(\"%H%M%S\")\n    SAVE_PATH = HOME + \"/kCSD_results/\" + DAY + '/' + TIMESTR\n    makemydir(SAVE_PATH)\n    save_source_code(SAVE_PATH, time.strftime(\"%Y%m%d-%H%M%S\"))\n\n    CSD_PROFILE = CSD.gauss_1d_mono\n    CSD_SEED = 15\n#    N_SRC = [2, 4, 8, 16, 32, 64, 128, 256, 512]\n    N_SRC = [2, 8, 16, 512]\n    ELE_LIMS = [0.1, 0.9]  # range of electrodes space\n    TRUE_CSD_XLIMS = [0., 1.]\n    TOTAL_ELE = 10\n    noise = None\n    Rs = np.arange(0.1, 0.5, 0.1)\n    lambdas = None\n    method = 'cross-validation'\n    OBJ, RMS, POINT_ERROR, eigenval, eigenvec = stability_M(CSD_PROFILE,\n                                                            CSD_SEED,\n                                                            N_SRC, ELE_LIMS,\n                                                            TRUE_CSD_XLIMS,\n                                                            TOTAL_ELE, Rs=Rs,\n                                                            noise=noise,\n                                                            lambdas=lambdas,\n                                                            method=method)\n    k_pot_list = []\n    k_interp_cross_list = []\n    lambdas = []\n    for index in range(len(OBJ)):\n        k_pot_list.append(OBJ[index].k_pot)\n        k_interp_cross_list.append(OBJ[index].k_interp_cross)\n        lambdas.append(OBJ[index].lambd)\n\n    plot_M(N_SRC, RMS, SAVE_PATH)\n    plot_eigenvalues(eigenval, SAVE_PATH, N_SRC)\n    plot_max_eigenvalue_M(eigenval, SAVE_PATH, N_SRC)\n    plot_eigenvectors(eigenvec, SAVE_PATH, N_SRC)\n    plot_k_interp_cross(k_interp_cross_list, SAVE_PATH, N_SRC)\n    plot_k_interp_cross_v(k_interp_cross_list, eigenvec, SAVE_PATH, N_SRC)\n    plot_eigenvalue_lambda(eigenval, lambdas, SAVE_PATH, N_SRC)\n    plot_k_pot(k_pot_list, SAVE_PATH, N_SRC)\n", "meta": {"hexsha": "a22e3efd535c5a111a77874537f2b30423321fad", "size": 14374, "ext": "py", "lang": "Python", "max_stars_repo_path": "figures/kCSD_properties/reconstruction_stability.py", "max_stars_repo_name": "rdarie/kCSD-python", "max_stars_repo_head_hexsha": "5b9e1b1dce2ff95c0d981c2c4015b7a75199de9a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2017-11-06T21:24:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T21:17:13.000Z", "max_issues_repo_path": "figures/kCSD_properties/reconstruction_stability.py", "max_issues_repo_name": "aeladly91/kCSD-python", "max_issues_repo_head_hexsha": "4dd0015e9c5598e7eceeeb25668e696e495b2026", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 105, "max_issues_repo_issues_event_min_datetime": "2017-12-13T12:49:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T12:25:51.000Z", "max_forks_repo_path": "figures/kCSD_properties/reconstruction_stability.py", "max_forks_repo_name": "aeladly91/kCSD-python", "max_forks_repo_head_hexsha": "4dd0015e9c5598e7eceeeb25668e696e495b2026", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2017-06-08T07:32:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T21:17:15.000Z", "avg_line_length": 31.1800433839, "max_line_length": 80, "alphanum_fraction": 0.5870321414, "include": true, "reason": "import numpy", "num_tokens": 3588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.35577490034429643, "lm_q1q2_score": 0.18621982248099755}}
{"text": "\"\"\"Profiles to reduce data to 1-dimension.\"\"\"\n\n# Heavily inspired by pynbody (https://pynbody.github.io/).\n\nfrom __future__ import annotations\n\nfrom bisect import bisect\nfrom copy import copy\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    List,\n    Optional,\n    Sequence,\n    Tuple,\n    Union,\n)\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom numpy import ndarray\nfrom pandas import DataFrame\nfrom scipy.interpolate import interp1d\n\nfrom .._logging import logger\nfrom .._units import Quantity\nfrom .._units import units as plonk_units\nfrom ..utils.math import average\nfrom ..utils.snap import dust_array_names, vector_array_names\nfrom ..utils.strings import is_documented_by, pretty_array_name\nfrom .extra import extra_profiles\n\nif TYPE_CHECKING:\n    from ..snap.snap import SnapLike\n\n_aggregations = ('average', 'mean', 'median', 'std', 'sum')\n\n\nclass Profile:\n    \"\"\"Profiles.\n\n    A profile is a binning of particles in Cartesian slices, or\n    cylindrical or spherical shells around the origin, i.e. (0, 0, 0).\n    For cylindrical profiles the cylindrical cells are perpendicular to\n    the xy-plane, i.e. the bins are averaged azimuthally and in the\n    z-direction. Cartesian profiles can be in the x-, y-, and\n    z-directions.\n\n    Parameters\n    ----------\n    snap\n        The Snap object.\n    ndim : optional\n        The dimension of the profile. For ndim == 2, the radial binning\n        is cylindrical in the xy-plane. For ndim == 3, the radial\n        binning is spherical. For ndim == 1, the radial binning is\n        Cartesian along the x-axis. Default is 2.\n    cmin : optional\n        The minimum coordinate for binning. Can be a string, e.g.\n        '10 au', or a quantity with units, e.g. plonk.units('10 au').\n        Defaults to minimum on the particles.\n    cmax : optional\n        The maximum coordinate for binning. Can be a string, e.g.\n        '10 au', or a quantity with units, e.g. plonk.units('10 au').\n        Defaults to the 99 percentile distance.\n    n_bins : optional\n        The number of radial bins. Default is 100.\n    aggregation : optional\n        The method to aggregate particle quantities in bins by. Options\n        are 'average', 'mean', or 'median'. Here 'average' is a\n        mass-weighted average. Default is 'average'.\n    spacing : optional\n        The spacing of radial bins. Can be 'linear' or 'log'. Default is\n        'linear'.\n    coordinate : optional\n        The coordinate ('x', 'y', or 'z') for Cartesian profiles only,\n        i.e. when ndim==1. Default is 'x'. For cylindrical and spherical\n        profiles the coordinate is 'radius'.\n    ignore_accreted : optional\n        Ignore particles accreted onto sinks. Default is True.\n\n    Examples\n    --------\n    Generate profile from snapshot.\n\n    >>> prof = plonk.load_profile(snap=snap)\n    >>> prof = plonk.load_profile(snap=snap, n_bins=300)\n    >>> prof = plonk.load_profile(snap=snap, cmin='10 au', cmax='300 au')\n    >>> prof = plonk.load_profile(snap=snap, spacing='log')\n\n    To access a profile.\n\n    >>> prof['surface_density']\n    >>> prof['scale_height']\n\n    To set a new profile.\n\n    >>> prof['aspect_ratio'] = prof['scale_height'] / prof['radius']\n\n    Alternatively use the add_profile decorator.\n\n    >>> @prof.add_profile\n    ... def mass(prof):\n    ...     M = prof.snap['mass']\n    ...     return prof.particles_to_binned_quantity('sum', M)\n\n    Plot one or many quantities on the profile.\n\n    >>> prof.plot('radius', 'density')\n    >>> prof.plot('radius', ['angular_momentum_x', 'angular_momentum_y'])\n\n    Plot a quantity on the profile with units.\n\n    >>> units = {'position': 'au', 'surface_density'='g/cm^2'}\n    >>> prof.plot('radius', 'surface_density', units=units)\n    \"\"\"\n\n    _profile_aliases: Dict[str, str] = {}\n\n    def __init__(\n        self,\n        snap: SnapLike,\n        ndim: int = 2,\n        cmin: Any = None,\n        cmax: Any = None,\n        n_bins: int = 100,\n        aggregation: str = 'average',\n        spacing: str = 'linear',\n        coordinate: str = 'x',\n        ignore_accreted: bool = True,\n    ):\n\n        self.snap = snap\n        self.ndim = ndim\n        self.aggregation = _check_aggregation(aggregation)\n        self.spacing = _check_spacing(spacing)\n        self.properties: Dict[str, Any] = {}\n\n        self._profiles: Dict[str, Quantity] = {}\n        self._profile_functions: Dict[str, Callable] = {}\n        self._default_units = copy(self.snap._default_units)\n\n        self._weights = self.snap['mass']\n        self._mask = _setup_particle_mask(snap, ignore_accreted)\n        self._x = _calculate_x(snap, self._mask, ndim, coordinate)\n        self.range = _set_range(self._x, cmin, cmax)\n        self.n_bins = n_bins\n\n        self.bin_edges, self['size'] = _setup_bins(ndim, spacing, self.range, n_bins)\n        self.bin_centers = 0.5 * (self.bin_edges[:-1] + self.bin_edges[1:])\n        self._x = self._x.to(self.bin_edges.units)\n        self._particle_bin = np.digitize(self._x.magnitude, self.bin_edges.magnitude)\n        self.bin_indices = _set_particle_bin_indices(self._particle_bin, n_bins)\n\n        if ndim == 1:\n            self._coordinate = coordinate\n        else:\n            self._coordinate = 'radius'\n        self._profiles[self._coordinate] = self.bin_centers\n        self._profiles['number'] = np.histogram(\n            self._x.magnitude, self.bin_edges.magnitude\n        )[0] * plonk_units('dimensionless')\n\n        # Add pre-defined profiles\n        try:\n            num_separate_dust = len(self.snap.num_particles_of_type['dust'])\n        except KeyError:\n            num_separate_dust = 0\n        num_mixture_dust = self.snap.num_dust_species - num_separate_dust\n        extra_profiles(self, num_separate_dust, num_mixture_dust)\n\n    def add_profile(self, fn: Callable) -> Callable:\n        \"\"\"Decorate function to add profile to Profile.\n\n        Parameters\n        ----------\n        fn\n            A function that returns the profile as an array. The name of\n            the function is the string with which to reference the array.\n\n        Returns\n        -------\n        Callable\n            The function which returns the array.\n        \"\"\"\n        self._profile_functions[fn.__name__] = fn\n        return fn\n\n    def add_alias(self, name: str, alias: str) -> None:\n        \"\"\"Add alias to array.\n\n        Parameters\n        ----------\n        name\n            The name of the array.\n        alias\n            The alias to reference the array.\n        \"\"\"\n        self._profile_aliases[alias] = name\n\n    def loaded_profiles(self) -> List[str]:\n        \"\"\"Return a listing of loaded profiles.\"\"\"\n        return sorted(self._profiles.keys())\n\n    def available_profiles(self) -> List[str]:\n        \"\"\"Return a listing of available profiles.\"\"\"\n        loaded = list(self.loaded_profiles())\n        available = list(self._profile_functions.keys())\n        snap_arrays = _1d_arrays(list(self.snap.available_arrays(verbose=True)))\n        return sorted(set(loaded + available + snap_arrays))\n\n    @property\n    def default_units(self) -> Dict[str, Any]:\n        \"\"\"Profile default units.\"\"\"\n        return {\n            key: self._default_units[key] for key in sorted(self._default_units.keys())\n        }\n\n    def set_units(self, **kwargs) -> Profile:\n        \"\"\"Set default unit for profiles.\n\n        Parameters\n        ----------\n        kwargs\n            Keyword arguments with keys as the profile name, e.g.\n            'pressure', and with values as the unit as a string, e.g.\n            'pascal'.\n\n        Examples\n        --------\n        Set multiple default units.\n\n        >>> profile.set_units(pressure='pascal', density='g/cm^3')\n        \"\"\"\n        for key, val in kwargs.items():\n            defaults = list(self.default_units) + list(self.snap.default_units)\n            if key not in defaults:\n                logger.info(f'adding profile {key} to default_units dict')\n            self._default_units[key] = val\n\n        return self\n\n    def base_profile_name(self, name: str) -> str:\n        \"\"\"Get the base profile name from a string.\n\n        For example, 'velocity_x' returns 'velocity', 'density' returns\n        'density', 'dust_fraction_001' returns 'dust_fraction', 'x'\n        returns 'position'.\n\n        Parameters\n        ----------\n        name\n            The name as a string\n\n        Returns\n        -------\n        str\n            The base name.\n        \"\"\"\n        try:\n            return self.snap.base_array_name(name)\n        except ValueError:\n            if name == self._coordinate:\n                return 'position'\n            name_root = '_'.join(name.split('_')[:-1])\n            name_suffix = name.split('_')[-1]\n            if name_root == '' and name_suffix in ('x', 'y', 'z'):\n                return 'position'\n            if name_root in self.snap._array_aliases:\n                return self.snap._array_aliases[name_root]\n            if name_suffix in ('x', 'y', 'z', 'mag'):\n                return name_root\n            if _str_is_int(name_suffix):\n                return name_root\n            return name\n\n    def plot(\n        self,\n        x: str,\n        y: Union[str, List[str]],\n        units: Dict[str, Union[str, List[str]]] = None,\n        std: str = None,\n        label: Union[str, List[str]] = None,\n        ax: Any = None,\n        ax_kwargs={},\n        **kwargs,\n    ) -> Any:\n        \"\"\"Plot profile.\n\n        Parameters\n        ----------\n        x\n            The x axis to plot as a string.\n        y\n            The y axis to plot. Can be string or a list of strings.\n        units\n            The units of the plot as a dictionary. The keys correspond\n            to quantities such as 'position', 'density', 'velocity', and\n            so on. The values are strings representing units, e.g.\n            'g/cm^3' for density.\n        std : optional\n            Add standard deviation on profile. Can be 'shading' or\n            'errorbar'.\n        label : optional\n            A label for the plot. Can be a string or a list of strings,\n            one per y.\n        ax : optional\n            A matplotlib Axes object to plot to.\n        ax_kwargs\n            Keyword arguments to pass to matplotlib Axes.\n        **kwargs\n            Keyword arguments to pass to Axes plot method.\n\n        Returns\n        -------\n        ax\n            The matplotlib Axes object.\n        \"\"\"\n        if std is not None and std not in ('shading', 'errorbar'):\n            raise ValueError('std must be \"shading\" or \"errorbar\"')\n\n        ynames = _yname_from_yinput(y, self)\n        labels = _labels(label, ynames)\n\n        xunit = _get_unit(self, x, units)\n        yunits = [_get_unit(self, y, units) for y in ynames]\n\n        xdata = self[x].to(xunit)\n\n        if ax is None:\n            _, ax = plt.subplots()\n\n        for yname, yunit, label in zip(ynames, yunits, labels):\n            ydata = self[yname].to(yunit)\n            if label is None:\n                label = f'{pretty_array_name(yname)}'\n                if ydata.units != plonk_units.dimensionless:\n                    label = f'{pretty_array_name(yname)}'\n                    label += f' [{ydata.units:~P}]'\n            [line] = ax.plot(xdata.magnitude, ydata.magnitude, label=label, **kwargs)\n            if std:\n                color = line.get_color()\n                _std_plot(self, xdata, ydata, yname, yunit, std, color, ax)\n\n        ax.set_xlabel(f'{pretty_array_name(x)} [{xdata.units:~P}]')\n        ax.legend()\n        ax.set(**ax_kwargs)\n\n        return ax\n\n    def to_function(self, profile: str, **kwargs) -> Callable:\n        \"\"\"Create function via interpolation.\n\n        The function is of the coordinate of the profile, e.g.\n        'radius', and returns values of the selected profile, e.g.\n        'scale_height'. The function is generated from the\n        scipy.interpolate function interp1d.\n\n        Parameters\n        ----------\n        profile\n            The profile function to create as a string, e.g.\n            'scale_height'.\n\n        Returns\n        -------\n        Callable\n            The function.\n\n        Examples\n        --------\n        Select all particles within a scale height in a disc.\n\n        >>> scale_height = prof.to_function('scale_height')\n        >>> subsnap = snap[np.abs(snap['z']) < scale_height(snap['R'])]\n        \"\"\"\n        coord = self.bin_centers\n        prof = self[profile]\n\n        def fn(x):\n            nonlocal coord, prof\n            _coord = coord.to(x.units).magnitude\n            _prof = prof.magnitude\n            y = interp1d(_coord, _prof, fill_value='extrapolate', **kwargs)(x.magnitude)\n            return y * self[profile].units\n\n        return fn\n\n    def to_dataframe(\n        self, columns: List[str] = None, units: List[str] = None\n    ) -> DataFrame:\n        \"\"\"Convert Profile to DataFrame.\n\n        Parameters\n        ----------\n        columns : optional\n            A list of columns to add to the data frame. If None, add all\n            loaded columns. Default is None.\n        units : optional\n            A list of units corresponding to columns add to the data\n            frame. Units must be strings, and must be base units. I.e.\n            'cm' not '10 cm'. If None, use default, i.e. cgs. Default is\n            None.\n\n        Returns\n        -------\n        DataFrame\n        \"\"\"\n        data = dict()\n        if columns is None:\n            columns = self.loaded_profiles()\n        if units is None:\n            _units = list()\n            for column in columns:\n                try:\n                    _units.append(self[column].units)\n                except AttributeError:\n                    _units.append(plonk_units('dimensionless'))\n        else:\n            _units = list()\n            for unit in units:\n                u = plonk_units(unit)\n                if np.allclose(u.m, 1.0):\n                    _units.append(u.units)\n                else:\n                    raise ValueError(\n                        'Units must be strings, and must be base units. '\n                        'I.e. \"cm\" not \"10 cm\".'\n                    )\n        if len(_units) != len(columns):\n            raise ValueError('units and columns must have same length')\n        for column, unit in zip(columns, _units):\n            try:\n                name = column + f' [{unit:~}]'\n                array = self[column].to(unit).magnitude\n            except AttributeError:\n                name = column\n                array = self[column]\n            data[name] = array\n        return pd.DataFrame(data)\n\n    def particles_to_binned_quantity(\n        self, aggregation: str, array: Quantity\n    ) -> Quantity:\n        \"\"\"Calculate binned quantities from particles.\n\n        This takes care of the bin indices and ignoring accreted\n        particles (if requested in instantiating the profile).\n\n        Parameters\n        ----------\n        aggregation\n            The aggregation function that acts on particles in the\n            radial bin.\n        array\n            The particle array.\n        \"\"\"\n        if aggregation not in _aggregations:\n            raise ValueError('Cannot determine aggregation method')\n\n        _array = array[self._mask]\n        binned_quantity = np.zeros(self.n_bins) * _array.units\n        for idx, bin_ind in enumerate(self.bin_indices):\n            if bin_ind.size == 0:\n                continue\n            if aggregation == 'average':\n                val = average(\n                    _array[bin_ind], weights=self._weights[self._mask][bin_ind],\n                )\n            elif aggregation == 'mean':\n                val = np.mean(_array[bin_ind])\n            elif aggregation == 'median':\n                val = np.median(_array[bin_ind])\n            elif aggregation == 'std':\n                val = np.std(_array[bin_ind])\n            elif aggregation == 'sum':\n                val = np.sum(_array[bin_ind])\n\n            binned_quantity[idx] = val\n\n        return binned_quantity\n\n    def __getitem__(self, name: str) -> Quantity:\n        \"\"\"Return the profile of a given kind.\"\"\"\n        name_root = '_'.join(name.split('_')[:-1])\n        name_suffix = name.split('_')[-1]\n\n        if name in self._profile_aliases:\n            name = self._profile_aliases[name]\n        if name in self._profiles:\n            return self._profiles[name]\n        if name in self._profile_functions:\n            self._profiles[name] = self._profile_functions[name](self)\n            return self._profiles[name]\n\n        if name_suffix in _aggregations:\n            aggregation = name_suffix\n            array_name = name_root\n        else:\n            aggregation = self.aggregation\n            array_name = name\n        try:\n            array: Quantity = self.snap[array_name]\n        except ValueError as e:\n            logger.error(e)\n            raise ValueError(f'array \"{array_name}\" not available on snap')\n        if array.ndim == 1:\n            self._profiles[name] = self.particles_to_binned_quantity(aggregation, array)\n            return self._profiles[name]\n        raise ValueError(\n            'Requested profile has array dimension > 1.\\nTo access x-, y-, or '\n            'z-components, or magnitude of vector quantities,\\ntry, for '\n            'example, prof[\"velocity_x\"] or prof[\"momentum_mag\"].\\nTo '\n            'access dust profiles, try, for example, prof[\"stopping_time_001\"]'\n        )\n\n    def __setitem__(self, name: str, item: Quantity):\n        \"\"\"Set the profile directly.\"\"\"\n        if not isinstance(item, Quantity):\n            raise ValueError('\"item\" must be pint Quantity')\n        if item.shape[0] != self.n_bins:\n            raise ValueError('Length of array does not match number of bins')\n        if name in self.loaded_profiles():\n            raise ValueError(\n                'Attempting to overwrite existing profile. To do so, first delete the '\n                'profile\\nwith del prof[\"profile\"], then try again.'\n            )\n        if name in self.available_profiles():\n            raise ValueError(\n                'Attempting to set profile already available. '\n                'See prof.available_profiles().'\n            )\n        self._profiles[name] = item\n\n    def __delitem__(self, name):\n        \"\"\"Delete a profile from memory.\"\"\"\n        del self._profiles[name]\n\n    def __len__(self):\n        \"\"\"Length as number of bins.\"\"\"\n        return self.n_bins\n\n    def __repr__(self):\n        \"\"\"Dunder repr method.\"\"\"\n        return self.__str__()\n\n    def __str__(self):\n        \"\"\"Dunder str method.\"\"\"\n        return f'<plonk.Profile \"{self.snap.file_path.name}\">'\n\n    def _ipython_key_completions_(self):\n        \"\"\"Tab completion for IPython __getitem__ method.\"\"\"\n        return self.available_profiles()\n\n\n@is_documented_by(Profile)\ndef load_profile(\n    snap: SnapLike,\n    ndim: int = 2,\n    cmin: Any = None,\n    cmax: Any = None,\n    n_bins: int = 100,\n    aggregation: str = 'average',\n    spacing: str = 'linear',\n    coordinate: str = 'x',\n    ignore_accreted: bool = True,\n) -> Profile:\n    logger.debug(f'Loading profile: {snap.file_path.name}')\n    return Profile(\n        snap=snap,\n        ndim=ndim,\n        cmin=cmin,\n        cmax=cmax,\n        n_bins=n_bins,\n        aggregation=aggregation,\n        spacing=spacing,\n        coordinate=coordinate,\n        ignore_accreted=ignore_accreted,\n    )\n\n\ndef _setup_particle_mask(snap: SnapLike, ignore_accreted: bool) -> ndarray:\n    if ignore_accreted is False:\n        return np.ones(len(snap), dtype=bool)\n    h: Quantity = snap['h']\n    return h > 0\n\n\ndef _calculate_x(snap: SnapLike, mask: ndarray, ndim: int, coordinate: str) -> Quantity:\n    pos: Quantity = snap['position']\n    pos = pos[mask]\n    if ndim == 1:\n        if coordinate == 'x':\n            return pos[:, 0]\n        if coordinate == 'y':\n            return pos[:, 1]\n        if coordinate == 'z':\n            return pos[:, 2]\n        raise ValueError('coordinate must be \"x\", \"y\", or \"z\" for ndim==1')\n    if ndim == 2:\n        return np.sqrt(pos[:, 0] ** 2 + pos[:, 1] ** 2)\n    if ndim == 3:\n        return np.sqrt(pos[:, 0] ** 2 + pos[:, 1] ** 2 + pos[:, 2] ** 2)\n    raise ValueError('Unknown ndim: cannot calculate x array')\n\n\ndef _set_range(x: Quantity, cmin: Any, cmax: Any) -> Tuple[float, float]:\n    if cmin is None:\n        rmin = x.min()\n    else:\n        rmin = Quantity(cmin)\n        if not rmin.dimensionality == Quantity('cm').dimensionality:\n            raise ValueError('must specify cmin units, e.g. cmin=\"10 au\"')\n    if cmax is None:\n        rmax = np.percentile(x.magnitude, 99, axis=0) * x.units\n    else:\n        rmax = Quantity(cmax)\n        if not rmax.dimensionality == Quantity('cm').dimensionality:\n            raise ValueError('must specify cmin units, e.g. cmax=\"100 au\"')\n\n    return rmin, rmax\n\n\ndef _setup_bins(ndim: int, spacing: str, xrange: Quantity, n_bins: int) -> Quantity:\n    bin_edges = _bin_edges(spacing, xrange, n_bins)\n    if ndim == 1:\n        bin_sizes = bin_edges[1:] - bin_edges[:-1]\n    elif ndim == 2:\n        bin_sizes = np.pi * (bin_edges[1:] ** 2 - bin_edges[:-1] ** 2)\n    elif ndim == 3:\n        bin_sizes = 4 / 3 * np.pi * (bin_edges[1:] ** 3 - bin_edges[:-1] ** 3)\n    return bin_edges, bin_sizes\n\n\ndef _bin_edges(spacing: str, xrange: Quantity, n_bins: int) -> Quantity:\n    if spacing == 'linear':\n        bin_edges = (\n            np.linspace(xrange[0].magnitude, xrange[1].magnitude, n_bins + 1)\n            * xrange[0].units\n        )\n    elif spacing == 'log':\n        bin_edges = (\n            np.logspace(\n                np.log10(xrange[0].magnitude),\n                np.log10(xrange[1].magnitude),\n                n_bins + 1,\n            )\n            * xrange[0].units\n        )\n    else:\n        raise ValueError('Cannot determine spacing to setup bins')\n    return bin_edges\n\n\ndef _set_particle_bin_indices(particle_bin: ndarray, n_bins: int) -> List[ndarray]:\n    sortind = particle_bin.argsort()\n    sort_pind = particle_bin[sortind]\n    binind = list()\n    prev_index = bisect(sort_pind, 0)\n    for i in range(n_bins):\n        new_index = bisect(sort_pind, i + 1)\n        binind.append(np.sort(sortind[prev_index:new_index]))\n        prev_index = new_index\n    return binind\n\n\ndef _check_aggregation(method: str) -> str:\n    if method in _aggregations:\n        return method\n    raise ValueError(\n        f'Cannot determine aggregation method: choose from {_aggregations}'\n    )\n\n\ndef _check_spacing(spacing: str) -> str:\n    if spacing.lower() in ('lin', 'linear'):\n        return 'linear'\n    if spacing.lower() in ('log', 'logarithm', 'logarithmic'):\n        return 'log'\n    raise ValueError('Cannot determine spacing')\n\n\ndef _1d_arrays(arrays: list) -> list:\n    _arrays = list()\n    for array in arrays:\n        if (array + '_x' in arrays) or (array + '_001' in arrays):\n            pass\n        else:\n            _arrays.append(array)\n    return _arrays\n\n\ndef _get_unit(profile, name, units):\n    if name is None:\n        return None\n    base_name = profile.base_profile_name(name)\n    if units is not None:\n        if name in units:\n            return 1 * plonk_units(units[name])\n        if base_name in units:\n            return 1 * plonk_units(units[base_name])\n    if name in profile.default_units:\n        return 1 * plonk_units(profile.default_units[name])\n    if base_name in profile.default_units:\n        return 1 * plonk_units(profile.default_units[base_name])\n    return 1 * profile[name].units\n\n\ndef _yname_from_yinput(y, profile):\n    if isinstance(y, str):\n        if y not in profile.available_profiles():\n            if y + '_001' in profile.available_profiles():\n                return dust_array_names(\n                    name=y, num_dust_species=profile.snap.num_dust_species\n                )\n            elif y + '_x' in profile.available_profiles():\n                return vector_array_names(name=y)\n            return [y]\n        return [y]\n    return y\n\n\ndef _labels(label, ynames):\n    labels: Sequence[Optional[str]]\n    if label is not None:\n        if isinstance(label, str):\n            return [label for _ in ynames]\n        return label\n    else:\n        return [None for _ in ynames]\n\n\ndef _std_plot(profile, xdata, ydata, yname, yunit, std, color, ax):\n    if yname.split('_')[-1] in _aggregations:\n        _yname = '_'.join(yname.split('_')[:-1])\n    else:\n        _yname = yname\n    try:\n        y_std = profile[_yname + '_std']\n    except ValueError:\n        logger.warning('Cannot calculate standard deviation')\n        return\n    if profile.aggregation in ('std', 'sum'):\n        y_mean = profile[_yname + '_mean']\n    else:\n        y_mean = ydata\n    y_std = y_std.to(yunit).magnitude\n    y_mean = y_mean.to(yunit).magnitude\n    xdata = xdata.magnitude\n    if std == 'shading':\n        ax.fill_between(\n            xdata, y_mean - y_std, y_mean + y_std, color=color, alpha=0.2,\n        )\n    elif std == 'errorbar':\n        ax.errorbar(xdata, y_mean, yerr=y_std, linestyle='', color=color, alpha=0.5)\n\n\ndef _str_is_int(string: str) -> bool:\n    try:\n        int(string)\n        return True\n    except ValueError:\n        return False\n", "meta": {"hexsha": "ee1cc835f78522d2e3436f6376ddeec516724435", "size": 25150, "ext": "py", "lang": "Python", "max_stars_repo_path": "plonk/analysis/profile.py", "max_stars_repo_name": "distamio/plonk", "max_stars_repo_head_hexsha": "d8ff63a631981da652fb463d77ee289088acf2a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "plonk/analysis/profile.py", "max_issues_repo_name": "distamio/plonk", "max_issues_repo_head_hexsha": "d8ff63a631981da652fb463d77ee289088acf2a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plonk/analysis/profile.py", "max_forks_repo_name": "distamio/plonk", "max_forks_repo_head_hexsha": "d8ff63a631981da652fb463d77ee289088acf2a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-24T21:52:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T21:52:13.000Z", "avg_line_length": 32.7900912647, "max_line_length": 88, "alphanum_fraction": 0.5788071571, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 5905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3557748935136304, "lm_q1q2_score": 0.18621981890568795}}
{"text": "\"\"\"\nConstant molecular properties to be used in other modules.\n\nArrays are ordered by atomic number for convenience. Atomic symbols are case\nsensitive. This module should not depend on other modules.\n\nUnit types\n----------\nLength: Angstrom (ang), Bohr (bohr), picometre (pm), nanometre (nm)\n\nAngle: radian (rad), degree (deg)\n\nTime: femtosecond (fs), picosecond (ps), atomic unit (au)\n\nMass: atomic mass unit (amu), electron mass (me), proton mass (mp),\nkilogram (kg)\n\nEnergy: electron volt (ev), Hartree (har), kilocalorie per mole (kcm),\nkilojoule per mole (kjm), reciprocal centimetre (cm), joule (j),\nterahertz (thz)\n\nFor all types, 'auto' will give the default unit.\n\nAttributes\n----------\nsym : ndarray\n    List of atomic symbols up to Krypton. The ordering (with the\n    exception of deuterium) yields the correct atomic number from\n    ``sym.index(elem)``.\nmass : ndarray\n    List of atomic masses corresponding to the elements in `sym`.\ncovrad : ndarray\n    List of covalent radii corresponding to the elements in `sym`.\nlenunits : dict\n    Dictionary of units of length and their conversions from the\n    default (angstroms).\nangunits : dict\n    Dictionary of units of angle and their conversions from the\n    default (radians).\ntimunits : dict\n    Dictionary of units of time and their conversions from the\n    default (femtoseconds).\nmasunits : dict\n    Dictionary of units of mass and their conversions from the\n    default (atomic mass units).\neneunits : dict\n    Dictionary of units of energy and their conversion from the\n    default (electron volts).\n\"\"\"\nimport numpy as np\n\n\n# Global constants\nsym = np.array(['X', 'H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne',\n                'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca',\n                'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn',\n                'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr'])\nmass = np.array([0.00000000, 1.00782504, 4.00260325, 7.01600450, 9.01218250,\n                 11.00930530, 12.00000000, 14.00307401, 15.99491464,\n                 18.99840325, 19.99243910, 22.98976970, 23.98504500,\n                 26.98154130, 27.97692840, 30.97376340, 31.97207180,\n                 34.96885273, 39.96238310, 38.96370790, 39.0983,\n                 40.078, 44.955908, 47.867, 50.9415, 51.9961, 54.938044,\n                 55.845, 58.933194, 58.6934, 63.546, 65.38, 69.723, 72.630,\n                 74.921595, 78.971, 79.904, 83.798])\ncovrad = np.array([0.000, 0.320, 1.600, 0.680, 0.352, 0.832, 0.720, 0.680,\n                   0.680, 0.640, 1.120, 0.972, 1.100, 1.352, 1.200, 1.036,\n                   1.020, 1.000, 1.568, 1.328, 0.992, 1.440, 1.472, 1.328,\n                   1.352, 1.352, 1.340, 1.328, 1.620, 1.520, 1.448, 1.220,\n                   1.168, 1.208, 1.220, 1.208, 1.600])\nlenunits = dict(auto=1., ang=1., bohr=1./0.52917721, pm=100., nm=0.1)\nangunits = dict(auto=1., rad=1., deg=180./np.pi)\ntimunits = dict(auto=1., fs=1., ps=0.001, au=1./0.024188843)\nmasunits = dict(auto=1., amu=1., me=1822.888486209, mp=1./1.00727647,\n                kg=1.66053904e-27)\neneunits = dict(auto=1., ev=1., har=1./27.21138505, kcm=23.061, kjm=96.485,\n                cm=8065.5, j=1.602176634e-19, thz=241.8)\n\n\ndef get_num(elem):\n    \"\"\"Returns atomic number from atomic symbol.\n\n    Takes advantage of the fact that sym indices match atomic numbers.\n\n    Parameters\n    ----------\n    elem : str or array_like\n        The atomic symbol(s) to be parsed.\n\n    Returns\n    -------\n    int or ndarray\n        The atomic numbers corresponding to each symbol.\n    \"\"\"\n    if isinstance(elem, str):\n        return _find_index(elem)\n    else:\n        for atm in elem:\n            if atm not in sym and atm[0] not in ['X', 'D']:\n                raise ValueError('Unrecognized atomic symbol \\'' + atm +\n                                 '\\'. Use X prefix for dummy atoms.')\n        return np.array([_find_index(atm) for atm in elem])\n\n\ndef get_mass(elem):\n    \"\"\"Returns atomic mass from atomic symbol.\n\n    Parameters\n    ----------\n    elem : str of array_like\n        The atomic symbol(s) to be parsed.\n\n    Returns\n    -------\n    float or ndarray\n        The atomic masses corresponding to each symbol.\n    \"\"\"\n    return mass[get_num(elem)]\n\n\ndef get_covrad(elem):\n    \"\"\"Returns covalent radius from atomic symbol.\n\n    Parameters\n    ----------\n    elem : str of array_like\n        The atomic symbol(s) to be parsed.\n\n    Returns\n    -------\n    float or ndarray\n        The atomic covalent radii corresponding to each symbol.\n    \"\"\"\n    return covrad[get_num(elem)]\n\n\ndef unit_vec(v):\n    \"\"\"Returns a unit vector aligned with a given vector.\n\n    Parameters\n    ---------\n    v : array_like\n        The input, un-normalized vector.\n\n    Returns\n    -------\n    ndarray\n        The normalized (unit) vector.\"\"\"\n    vlen = np.linalg.norm(v)\n    if np.isclose(vlen, 0):\n        raise ValueError('Cannot make unit vector from zero vector.')\n    else:\n        return v / vlen\n\n\ndef arccos(val):\n    \"\"\"Returns the arccosine of an angle allowing for numerical errors.\n\n    NumPy's arccos function is defined for the range [-1, 1], but\n    returns NaN for :math:`|x| = 1 + \\delta`, where :math:`\\delta` is\n    small.  This can be avoided by checking for limiting cases with\n    ``numpy.isclose``.\n\n    Parameters\n    ----------\n    val : float\n        The x-coordinate on the unit circle.\n\n    Returns\n    -------\n    float\n        The angle intersecting the unit circle at x = val.\n    \"\"\"\n    if np.isclose(val, -1):\n        return np.pi\n    elif np.isclose(val, 1):\n        return 0.\n    else:\n        return np.arccos(val)\n\n\ndef conv(old='auto', new='auto'):\n    \"\"\"Returns conversion factor from old units to new units.\n\n    Parameters\n    ----------\n    old : str, optional\n        The units to be converted from. See different units types for\n        defaults.\n    new : str, optional\n        The units to be converted to. See different units types for\n        defaults.\n\n    Returns\n    -------\n    float\n        The conversion factor, new_units / old_units.\n    \"\"\"\n    if old == new:\n        return 1.\n    for unittype in [lenunits, angunits, timunits, masunits, eneunits]:\n        if old in unittype and new in unittype:\n            return unittype[new] / unittype[old]\n\n    raise ValueError('Units \\'{}\\' and \\'{}\\' unrecognized or '\n                     'not of same unit type'.format(old, new))\n\n\ndef _find_index(string):\n    \"\"\"Determines if dummy or regular atom and returns index.\n\n    Parameters\n    ----------\n    string : str\n        The atomic symbol.\n\n    Returns\n    -------\n    int\n        The atomic number of the given atomic symbol.\n    \"\"\"\n    if string[0] == 'X':\n        return 0\n    elif string  == 'D':\n        return 1\n    else:\n        return np.where(sym == string)[0][0]\n", "meta": {"hexsha": "77c862b66149413db36608c9adbd86ce68d81ed1", "size": 6804, "ext": "py", "lang": "Python", "max_stars_repo_path": "gimbal/constants.py", "max_stars_repo_name": "ryjmacdonell/geomtools", "max_stars_repo_head_hexsha": "f68252db8334f390801ce3af528fc7c298232c5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gimbal/constants.py", "max_issues_repo_name": "ryjmacdonell/geomtools", "max_issues_repo_head_hexsha": "f68252db8334f390801ce3af528fc7c298232c5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2016-10-17T21:22:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-28T20:50:03.000Z", "max_forks_repo_path": "gimbal/constants.py", "max_forks_repo_name": "ryjmacdonell/geomtools", "max_forks_repo_head_hexsha": "f68252db8334f390801ce3af528fc7c298232c5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8421052632, "max_line_length": 76, "alphanum_fraction": 0.5945032334, "include": true, "reason": "import numpy", "num_tokens": 1986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18621981890568792}}
{"text": "\"\"\"\nThis module generates waveforms for compact binary coalescences.\n\nOne first generates a high level specification JSON file that only specifies\nmeta information such as the number of waveforms and from which ranges to\nsample the parameters. Then we actually sample the parameters for the waveforms\nand saves those in a big JSON file. Next, we generate all these specified\nwaveforms and save them together with the configuration file in an hdf file.\n\"\"\"\n\nfrom __future__ import absolute_import, print_function\n\nimport os\nimport json\nimport pylab\nimport numpy as np\nimport h5py\nfrom tqdm import tqdm\n\nfrom pycbc.waveform import get_td_waveform\n\n\ndef data_generation_pipeline(meta_config_file='../data/config.json',\n                             sample_config_file='../data/sample_config.json',\n                             sample_file='../data/samples.h5'):\n    \"\"\"\n    Run through the whole data generation pipeline.\n\n    Arguments:\n\n        meta_config_file: Path of a JSON file created by `generate_meta_config`\n\n        sample_config_file: Path where to store the sample config JSON file\n\n        sample_file: Path where to store the samples hdf data file\n\n    Given a meta config file, sample the specified waveform parameters, compute\n    the waveforms and store them.\n    \"\"\"\n    WaveformConfigGenerator(meta_config_file,\n                            sample_config_file).generate_and_save_config()\n    WaveformGenerator(sample_config_file,\n                      sample_file).generate_and_save_waveforms()\n\n\nclass WaveformGenerator:\n    \"\"\"\n    Compute waveforms.\n    \"\"\"\n\n    def __init__(self, config_file, output_file):\n        \"\"\"\n        Initialize a WaveformGenerator.\n\n        Arguments:\n\n            config_file: A JSON configuration file generated by\n                         `WaveformConfigGenerator`\n\n            output_file: File path where to store the created hdf file\n        \"\"\"\n        self.config_file = config_file\n        self.output_file = output_file\n        print(\"Reading the configuration {}...\".format(config_file), end=' ')\n        with open(self.config_file, 'r') as f:\n            self.config = json.loads(f.read())\n        print(\"DONE\")\n\n    def generate_and_save_waveforms(self):\n        \"\"\"\n        Generate and save all specified waveforms.\n        \"\"\"\n        # How many waveforms do we have to generate\n        n_samples = len(self.config['injections'])\n        duration = self.config['meta']['duration']\n        sample_rate = self.config['meta']['sample_rate']\n\n        # Collect indices of failures during waveform generation\n        # Sometimes the model just fail to compute the requested waveform.\n        # This indicates that one should choose different parameter regions.\n        failed = []\n        # Compute the waveforms\n        print(\"Generate the waveforms...\", end=' ')\n        # If the duration is smaller 0, all waveforms are kept in full length\n        if duration > 0:\n            N = int(duration * sample_rate)\n            waveforms = np.zeros((n_samples, N))\n\n            for i, conf in enumerate(tqdm(self.config['injections'])):\n                x = np.zeros(N)\n                try:\n                    # Compute the current waveform\n                    hp, cp = tuple(map(np.array, get_td_waveform(**conf)))\n                    # Get the correct indices to inject it into the noise\n                    inj_time = conf['injection_time']\n                    Iembed, Isignal = self._get_embedding_indices(hp,\n                                                                  inj_time,\n                                                                  N)\n                    x[Iembed] += hp[Isignal]\n                except Exception as e:\n                    # If waveform fails, remember the index\n                    # and keep the waveform as all zeros\n                    failed.append(i)\n                    err = type(e).__name__\n                    print(\"Failure {}\\n during waveform {}: {}\".format(err,\n                                                                       i,\n                                                                       conf))\n                waveforms[i, :] = x\n        else:\n            waveforms_raw = []\n            for i, conf in enumerate(tqdm(self.config['injections'])):\n                try:\n                    # Compute the current waveform\n                    hp, cp = tuple(map(np.array, get_td_waveform(**conf)))\n                    waveforms_raw.append(hp)\n\n                    # Get the correct indices to inject it into the noise\n                    inj_time = conf['injection_time']\n                except Exception as e:\n                    # If waveform fails, remember the index\n                    # and keep the waveform as all zeros\n                    waveforms_raw.append(np.zeros(1))\n                    failed.append(i)\n                    err = type(e).__name__\n                    print(\"Failure {}\\n during waveform {}: {}\".format(err,\n                                                                       i,\n                                                                       conf))\n            N = max(map(len, waveforms_raw))\n            waveforms = np.zeros((n_samples, N))\n            for i, x in enumerate(waveforms_raw):\n                waveforms[i, :len(x)] = x\n                inj_time = np.argmax(x) / float(N)\n                self.config['injections'][i]['injection_time'] = inj_time\n        print(\"DONE\")\n\n        print(\"Save everything to file...\", end=' ')\n        with h5py.File(self.output_file, 'w') as f:\n            f['waveforms'] = waveforms\n            f['config'] = np.string_(json.dumps(self.config))\n            f['failed'] = failed\n        print(\"DONE\")\n\n    def plot_waveform(self, index=0):\n        \"\"\"\n        Plot a waveform.\n\n        This is mostly just for testing and visualization.\n        \"\"\"\n        fig = pylab.figure()\n        with h5py.File(self.output_file, 'r') as f:\n            x = f['X'][index, :]\n        pylab.plot(x)\n        pylab.ylabel('Strain')\n        pylab.xlabel('Time')\n        return fig\n\n    def _get_embedding_indices(self, f, frac, N):\n        \"\"\"\n        Return matching indices of background and waveform for superposition.\n\n        The waveform generating functions generate waveforms of different\n        length, depending on the input parameters. Together with a variable\n        injection time with in the sample, the waveform could be too\n        long or too short towards both sides. Hence computing the injection\n        indices is not completely straight forward.\n\n        This is highly non-trivial magic and after extensive testing I never\n        want to have to open this box again.\n        \"\"\"\n        ni = int(frac * N)\n        nn = N - 1\n        sn = len(f) - 1\n        si = np.argmax(f)\n        start = ni - si\n        nl, sl = abs(start), 0\n        if start < 0:\n            nl, sl = sl, nl\n        end = (nn - ni) - (sn - si)\n        nr, sr = ni + sn - si, sn\n        if end < 0:\n            nr, sr = nn, si + nn - ni\n        Iembed = range(nl, nr + 1)\n        Isignal = range(sl, sr + 1)\n        if len(Iembed) == 0 or len(Isignal) == 0:\n            print('Could not find appropriate ranges:')\n            print('noise length: {}, signal length: {}'.format(nn, sn))\n            print('noise: {} : {}, signal: {} : {}'.format(nl, nr, sl, sr))\n        return Iembed, Isignal\n\n\n# -----------------------------------------------------------------------------\n# ------------------------------  Generate a Waveform Configuration JSON File\n# -----------------------------------------------------------------------------\n\n\nclass WaveformConfigGenerator:\n    \"\"\"\n    Sample and save waveform parameters in a waveform configuration JSON file.\n    \"\"\"\n\n    waveform_config = {}\n\n    def __init__(self, meta_config_file, output_file):\n        \"\"\"\n        Initialize the WaveformConfigGenerator.\n\n        Arguments:\n\n            meta_config_file: A meta configuration file as generated by\n            `generate_meta_config`. This meta config file can be hand tuned.\n\n            output_file: The sample_configuration file holding information\n            about parameters of each individual waveform.\n        \"\"\"\n        self.output_file = output_file\n        self.meta_config_file = meta_config_file\n        print(\"Load meta configuration...\", end=' ')\n        with open(self.meta_config_file, 'r') as f:\n            self.meta_config = json.loads(f.read())\n        print(\"DONE\")\n        self.n_samples = self.meta_config['n_samples']\n        self.default_parameters = self.meta_config['default_parameters']\n        self.update_list = self.meta_config['update_list']\n\n    def generate_and_save_config(self):\n        \"\"\"\n        Generate and save the configuration JSON file for the injections.\n        \"\"\"\n        self.waveform_config.update(self._injections_spec())\n        self.waveform_config.update({'meta': self.meta_config})\n        print(\"Write configuration to {}...\".format(self.output_file), end=' ')\n        with open(self.output_file, 'w') as f:\n            json.dump(self.waveform_config, f, sort_keys=True, indent=2)\n        print(\"DONE\")\n\n    def _injections_spec(self):\n        \"\"\"\n        Generate and return specification of the injection waveforms.\n        \"\"\"\n        injections = []\n        print(\"Sampling the waveform parameters...\", end=' ')\n        for i in range(self.n_samples):\n            cp = self.default_parameters.copy()\n            # Set the id first as counter\n            cp.update({'id': i})\n            # Update other values in the update list with new samples\n            # Some magic to figure out how to sample the samples\n            # Very bad style with eval and everything. Works. Wouldn't touch.\n            for update, pars in self.update_list.iteritems():\n                args = '(\"' + update + '\", ' + str(pars) + ')'\n                fname = 'self._sample_' + update + args\n                cp.update(eval(fname))\n            injections.append(cp)\n        print(\"DONE\")\n        return {'injections': injections}\n\n    def _sample_distance(self, key, pars):\n        \"\"\"\n        Draw a random source distance.\n        \"\"\"\n        return {key: self._uniform_in_range(pars[0], pars[1])}\n\n    def _sample_masses(self, key, pars):\n        \"\"\"\n        Draw random compact object masses.\n        \"\"\"\n        mass1 = self._uniform_in_range(pars[0], pars[1])\n        mass2 = self._uniform_in_range(pars[0], pars[1])\n        return {'mass1': mass1, 'mass2': mass2}\n\n    def _sample_injection_time(self, key, pars):\n        \"\"\"\n        Draw a random injection time.\n        \"\"\"\n        return {key: self._uniform_in_range(pars[0], pars[1])}\n\n    def _uniform_in_range(self, lower_bound, upper_bound):\n        \"\"\"\n        Draw uniformly distributed number in a given range.\n        \"\"\"\n        return np.random.rand() * (upper_bound - lower_bound) + lower_bound\n\n\ndef generate_meta_config(output_file='../data/meta_config.json'):\n    \"\"\"\n    Generate a meta configuration JSON file for the data generation pipeline.\n\n    This spits out a valid template of a meta configuration file as the one\n    required by the `WaveformConfigGenerator`. Just run this once to have a\n    valid template and then you can go ahead an tweak the individual numbers in\n    that template. All the defaults are considered sane choices.\n    \"\"\"\n    print(\"Generate meta config file {}...\".format(output_file), end=' ')\n    n_samples = 1024\n    # If the duration is < 0.0 the whole waveform will be used.\n    # All waveforms will be padded to the right with zeros to the length of the\n    # longest generated waveform.\n    # Then the injection times are overriden(!) in the config file coming with\n    # the output h5 file with the fraction where the maximum of the waveform\n    # lies within the whole sample.\n    duration = -1.\n    sample_rate = 4096\n    # Default parameters passed to simulator in case a parameter is not sampled\n\n    # Possible approximants: ['TaylorEt', 'SEOBNRv3_opt', 'IMRPhenomA',\n    # 'IMRPhenomC', 'IMRPhenomB', 'EOBNRv2', 'SEOBNRv4_opt', 'PhenSpinTaylor',\n    # 'PhenSpinTaylorRD', 'NR_hdf5', 'SEOBNRv3_pert', 'EOBNRv2HM',\n    # 'SpinTaylorT4', 'TaylorT1', 'TaylorT3', 'TaylorT2', 'HGimri', 'TaylorT4',\n    # 'IMRPhenomD', 'IMRPhenomPv2', 'SEOBNRv1', 'SpinDominatedWf', 'SEOBNRv3',\n    # 'SEOBNRv2', 'SpinTaylorT1', 'SEOBNRv4', 'SpinTaylorT2', 'EccentricTD',\n    # 'SEOBNRv2_opt', 'SEOBNRv3_opt_rk4']\n    default_parameters = {\n        'mass1': 1.0,\n        'mass2': 1.0,\n        'spin1z': 0.0,\n        'spin2z': 0.0,\n        'lambda1': 0.0,\n        'lambda2': 0.0,\n        'distance': 1000.0,\n        'coa_phase': 0.0,\n        'inclination': 0.0,\n        'delta_t': 1.0 / sample_rate,\n        'f_lower': 15.0,\n        'approximant': 'SEOBNRv4',\n        'injection_time': 0.95\n        # id does not have a default because it must be unique\n    }\n\n    # Specify the parameters that should be varied and the ranges (uniform)\n    # For the chosen range consult\n    # https://www.lsc-group.phys.uwm.edu/ligovirgo/cbcnote/O2/OfflineTuningVerificationInjections\n    update_list = {\n        'masses': [2., 50.],\n        # 'injection_time': [0.5, 0.9],\n        'distance': [400., 800.]\n    }\n\n    # Collect everything in a big meta config dictionary\n    meta_config = {\n        'n_samples': n_samples,\n        'duration': duration,\n        'sample_rate': sample_rate,\n        'default_parameters': default_parameters,\n        'update_list': update_list,\n    }\n\n    with open(output_file, 'w') as f:\n        json.dump(meta_config, f, sort_keys=True, indent=2)\n    print(\"DONE -- Saved as {}\".format(output_file))\n\n\nif __name__ == '__main__':\n    import datetime\n    timestamp = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')\n    new_dir = os.path.join(os.getcwd(), timestamp)\n    print(\"Create new folder \", new_dir)\n    os.makedirs(new_dir)\n\n    meta_config_file = os.path.join(new_dir, 'config.json')\n    sample_config_file = os.path.join(new_dir, 'sample_config.json')\n    sample_file = os.path.join(new_dir, 'samples.h5')\n\n    generate_meta_config(meta_config_file)\n\n    data_generation_pipeline(meta_config_file,\n                             sample_config_file,\n                             sample_file)\n", "meta": {"hexsha": "e995d3e68fb8c65914b97429cca2223f29c36a23", "size": 14240, "ext": "py", "lang": "Python", "max_stars_repo_path": "quantum gravity/convwave/src/sample_generation/waveform_generator.py", "max_stars_repo_name": "DanielMabadeje/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials", "max_stars_repo_head_hexsha": "7adab3877fc1d3f1d5f57e6c1743dae8f76f72c5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3266, "max_stars_repo_stars_event_min_datetime": "2017-08-06T16:51:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T07:34:24.000Z", "max_issues_repo_path": "quantum gravity/convwave/src/sample_generation/waveform_generator.py", "max_issues_repo_name": "nuhaltinsoy/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials", "max_issues_repo_head_hexsha": "6017441f2d476f9c6c568dd886da43c6c0fd89bd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 150, "max_issues_repo_issues_event_min_datetime": "2017-08-28T14:59:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T23:21:35.000Z", "max_forks_repo_path": "quantum gravity/convwave/src/sample_generation/waveform_generator.py", "max_forks_repo_name": "nuhaltinsoy/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials", "max_forks_repo_head_hexsha": "6017441f2d476f9c6c568dd886da43c6c0fd89bd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1449, "max_forks_repo_forks_event_min_datetime": "2017-08-06T17:40:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:03:24.000Z", "avg_line_length": 38.6956521739, "max_line_length": 97, "alphanum_fraction": 0.576755618, "include": true, "reason": "import numpy", "num_tokens": 3137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.18615862445564657}}
{"text": "import numpy as np\nimport math\n\n\n##################################\n#\n#    Global variables\n#\n#################################\n\nPERIODIC_TABLE = {\n    1:  \"H\",\n    2:  \"He\",\n    3:  \"Li\",\n    4:  \"Be\",\n    5:  \"B\",\n    6:  \"C\",\n    7:  \"N\",\n    8:  \"O\",\n    9:  \"F\",\n    10:\t\"Ne\",\n    11:\t\"Na\",\n    12:\t\"Mg\",\n    13:\t\"Al\",\n    14:\t\"Si\",\n    15: \"P\",\n    16: \"S\",\n    17:\t\"Cl\",\n    18:\t\"Ar\",\n    19: \"K\",\n    20:\t\"Ca\",\n    21:\t\"Sc\",\n    22:\t\"Ti\",\n    23: \"V\",\n    24:\t\"Cr\",\n    25:\t\"Mn\",\n    26:\t\"Fe\",\n    27:\t\"Co\",\n    28:\t\"Ni\",\n    29:\t\"Cu\",\n    30:\t\"Zn\",\n    31:\t\"Ga\",\n    32:\t\"Ge\",\n    33:\t\"As\",\n    34:\t\"Se\",\n    35:\t\"Br\",\n    36:\t\"Kr\",\n    37:\t\"Rb\",\n    38:\t\"Sr\",\n    39: \"Y\",\n    40:\t\"Zr\",\n    41:\t\"Nb\",\n    42:\t\"Mo\",\n    43:\t\"Tc\",\n    44:\t\"Ru\",\n    45:\t\"Rh\",\n    46:\t\"Pd\",\n    47:\t\"Ag\",\n    48:\t\"Cd\",\n    49:\t\"In\",\n    50:\t\"Sn\",\n    51:\t\"Sb\",\n    52:\t\"Te\",\n    53: \"I\",\n    54:\t\"Xe\",\n    55:\t\"Cs\",\n    56:\t\"Ba\",\n    57:\t\"La\",\n    58:\t\"Ce\",\n    59:\t\"Pr\",\n    60:\t\"Nd\",\n    61:\t\"Pm\",\n    62:\t\"Sm\",\n    63:\t\"Eu\",\n    64:\t\"Gd\",\n    65:\t\"Tb\",\n    66:\t\"Dy\",\n    67:\t\"Ho\",\n    68:\t\"Er\",\n    69:\t\"Tm\",\n    70:\t\"Yb\",\n    71:\t\"Lu\",\n    72:\t\"Hf\",\n    73:\t\"Ta\",\n    74: \"W\",\n    75:\t\"Re\",\n    76:\t\"Os\",\n    77:\t\"Ir\",\n    78:\t\"Pt\",\n    79:\t\"Au\",\n    80:\t\"Hg\",\n    81:\t\"Tl\",\n    82:\t\"Pb\",\n    83:\t\"Bi\",\n    84:\t\"Po\",\n    85:\t\"At\",\n    86:\t\"Rn\",\n    87:\t\"Fr\",\n    88:\t\"Ra\",\n    89:\t\"Ac\",\n    90:\t\"Th\",\n    91:\t\"Pa\",\n    92: \"U\",\n    93:\t\"Np\",\n    94:\t\"Pu\",\n    95:\t\"Am\",\n    96:\t\"Cm\",\n    97:\t\"Bk\",\n    98:\t\"Cf\",\n    99:\t\"Es\",\n    100: \"Fm\",\n    101: \"Md\",\n    102: \"No\",\n    103: \"Lr\",\n    104: \"Rf\",\n    105: \"Db\",\n    106: \"Sg\",\n    107: \"Bh\",\n    108: \"Hs\",\n    109: \"Mt\",\n    110: \"Ds\",\n    111: \"Rg\",\n    112: \"Cn\",\n    113: \"Nh\",\n    114: \"Fl\",\n    115: \"Mc\",\n    116: \"Lv\",\n    117: \"Ts\",\n    118: \"Og\"\n}\n\n\n####################################\n#\n#        Classes\n#\n####################################\n\nclass atom(object):\n\n    def __init__(self, num, cartesian=None, unit=\"angstrom\"):\n\n        if cartesian is None:\n            cartesian = [0, 0, 0]\n        self.__atom_num = num\n        self.__label = PERIODIC_TABLE[num]\n        self.__cartesian = cartesian\n        self.__unit = unit\n\n    def get_atom_num(self):\n        return self.__atom_num\n\n    def get_label(self):\n        return self.__label\n\n    def get_cartesian(self):\n        return self.__cartesian\n\n    def get_unit(self):\n        return self.__unit\n\n    def set_atom_num(self, num):\n        self.__atom_num = num\n        self.__label = PERIODIC_TABLE[num]\n\n    def set_label(self, label):\n        self.__label = label\n        if dict_inv_search(label, PERIODIC_TABLE):\n            self.__atom_num = dict_inv_enquiry(label, PERIODIC_TABLE)\n        else:\n            raise Exception(\"Element {} is not found in periodic table.\".format(label))\n\n    def set_cartesian(self, cartesian):\n        self.__cartesian = cartesian\n\n    def unit_convert_to_bohr(self):\n        if self.__unit == 'angstrom':\n            self.__cartesian = [i / 0.529177210903 for i in self.__cartesian]\n\n        if self.__unit == 'SI':\n            self.__cartesian = [i / 5.29177210903e-11 for i in self.__cartesian]\n            \n        self.__unit = 'bohr'\n\n    def unit_convert_to_angstrom(self):\n        if self.__unit == 'bohr':\n            self.__cartesian = [i * 0.529177210903 for i in self.__cartesian]\n\n        if self.__unit == 'SI':\n            self.__cartesian = [i * 1e10 for i in self.__cartesian]\n\n        self.__unit = 'angstrom'\n\n#########################################\n#\n#        Functions\n#\n########################################\n\n\ndef is_member(value, iterable):\n    for i in iterable:\n        if value == i:\n            return True\n\n    return False\n\n\ndef dict_inv_enquiry(value, dictionary):\n    for i in dictionary:\n        if dictionary[i] == value:\n            return i\n        \n    return value\n\n\ndef dict_inv_search(value, dictionary):\n    for i in dictionary:\n        if dictionary[i] == value:\n            return True\n\n    return False\n\n\ndef rot(a_vec, b_vec):\n    x = np.linalg.det([[a_vec[1], a_vec[2]], [b_vec[1], b_vec[2]]])\n    y = - np.linalg.det([[a_vec[0], a_vec[2]], [b_vec[0], b_vec[2]]])\n    z = np.linalg.det([[a_vec[0], a_vec[1]], [b_vec[0], b_vec[1]]])\n\n    return [x, y, z]\n\n\ndef norm(vec):\n    return np.dot(np.array(vec), np.array(vec))\n\n\ndef ortho_mat(vec):\n    z = np.array(vec) / math.sqrt(norm(vec))\n    if z[0] == 0:\n        x = np.array([1, 0, 0])\n    else:\n        x = np.array([- (z[1] + z[2]) / z[0], 1, 1])\n\n    x = x / math.sqrt(norm(x))\n\n    y = np.array(rot(z, x))\n\n    y = y / math.sqrt(norm(y))\n\n    return np.array([x, y, z])\n\n\ndef rotation(coordinate, ref_point, ref_vec, deg):\n\n    reference_point = np.array(ref_point)\n    translated_cartesian = np.array(coordinate) - reference_point\n\n    tr_basis_mat = ortho_mat(ref_vec).transpose()\n\n    coefficient = np.linalg.solve(tr_basis_mat, translated_cartesian)\n\n    coefficient = np.array([coefficient[0] * math.cos(-deg) - coefficient[1] * math.sin(-deg),\n                            coefficient[0] * math.sin(-deg) + coefficient[1] * math.cos(-deg),\n                            coefficient[2]])\n\n    return list(tr_basis_mat.dot(coefficient) + reference_point)\n\n\ndef remove_axis_vec(coordinate, ref_point, ref_vec):\n\n    reference_point = np.array(ref_point)\n    translated_cartesian = np.array(coordinate) - reference_point\n\n    tr_basis_mat = ortho_mat(ref_vec).transpose()\n\n    coefficient = np.linalg.solve(tr_basis_mat, translated_cartesian)\n\n    coefficient = np.array([coefficient[0], coefficient[1], 0])\n\n    return list(tr_basis_mat.dot(coefficient))\n\n\ndef bond_length(a_atom, b_atom):\n    ab = np.array(a_atom.get_cartesian()) - np.array(b_atom.get_cartesian())\n\n    return math.sqrt(np.dot(ab, ab))\n\n\ndef bond_angle(a_atom, center_atom, b_atom):\n    ac = np.array(a_atom.get_cartesian()) - np.array(center_atom.get_cartesian())\n    bc = np.array(b_atom.get_cartesian()) - np.array(center_atom.get_cartesian())\n\n    return math.acos(np.dot(ac, bc) / math.sqrt(norm(ac)) / math.sqrt(norm(bc)))\n\n\ndef bond_dihedral_angle(a_atom, b_atom, c_atom, d_atom):\n    axis = np.array(b_atom.get_cartesian()) - np.array(c_atom.get_cartesian())\n\n    axis_removed_ab = remove_axis_vec(a_atom.get_cartesian(), b_atom.get_cartesian(), axis)\n    axis_removed_dc = remove_axis_vec(d_atom.get_cartesian(), c_atom.get_cartesian(), axis)\n\n    return math.acos(np.dot(axis_removed_ab, axis_removed_dc)\n                     / math.sqrt(norm(axis_removed_ab))\n                     / math.sqrt(norm(axis_removed_dc)))\n\n\n# all atoms in `group' should be bound to a_atom\ndef set_bond_length(a_atom, b_atom, length, group=None):\n    vec = np.array(b_atom.get_cartesian()) - np.array(a_atom.get_cartesian())\n    change = (math.sqrt(norm(vec)) - length) / math.sqrt(norm(vec)) * vec\n\n    if group is not None:\n        for i in group:\n            i.set_cartesian(list(np.array(i.get_cartesian()) + change))\n    else:\n        a_atom.set_cartesian(list(np.array(a_atom.get_cartesian()) + change))\n\n\n# all atoms in `group' should be bound to a_atom\ndef set_bond_angle(a_atom, center_atom, b_atom, angle, group=None):\n    original_angle = bond_angle(a_atom, center_atom, b_atom)\n    ac = np.array(a_atom.get_cartesian()) - np.array(center_atom.get_cartesian())\n    bc = np.array(b_atom.get_cartesian()) - np.array(center_atom.get_cartesian())\n    axis = np.array(rot(ac, bc))\n\n    change = angle - original_angle\n\n    if group is not None:\n        for i in group:\n            i.set_cartesian(rotation(i.get_cartesian(), center_atom.get_cartesian(), axis, change))\n\n    else:\n        a_atom.set_cartesian(rotation(a_atom.get_cartesian(), center_atom.get_cartesian(), axis, change))\n\n\n# all atoms in `group' should be bound to a_atom\ndef set_bond_dihedral_angle(a_atom, b_atom, c_atom, d_atom, angle, group=None):\n    axis = np.array(b_atom.get_cartesian()) - np.array(c_atom.get_cartesian())\n    original_angle = bond_dihedral_angle(a_atom, b_atom, c_atom, d_atom)\n\n    change = angle - original_angle\n\n    if group is not None:\n        for i in group:\n            i.set_cartesian(rotation(i.get_cartesian(), b_atom, axis, change))\n\n    else:\n        a_atom.set_cartesian(rotation(a_atom.get_cartesian(), b_atom, axis, change))\n\n\ndef atoms_to_string_template(atoms_list):\n    atoms_string = \"\"\n\n    for i in atoms_list:\n        atoms_string += ' ' + i.get_label().ljust(28)\n        for j in i.get_cartesian():\n            atoms_string += str(float(j)).ljust(28)\n\n        atoms_string += '\\n'\n\n    return atoms_string\n", "meta": {"hexsha": "7e4d87be72612bce6675168ad1c313d9adb89380", "size": 8545, "ext": "py", "lang": "Python", "max_stars_repo_path": "atom/__init__.py", "max_stars_repo_name": "Walter-Feng/myModule", "max_stars_repo_head_hexsha": "f8cf065d52153ef3d386d10be1771e80cf5af4e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "atom/__init__.py", "max_issues_repo_name": "Walter-Feng/myModule", "max_issues_repo_head_hexsha": "f8cf065d52153ef3d386d10be1771e80cf5af4e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "atom/__init__.py", "max_forks_repo_name": "Walter-Feng/myModule", "max_forks_repo_head_hexsha": "f8cf065d52153ef3d386d10be1771e80cf5af4e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6049723757, "max_line_length": 105, "alphanum_fraction": 0.5549444119, "include": true, "reason": "import numpy", "num_tokens": 2653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3665897363221599, "lm_q1q2_score": 0.18615861742737802}}
{"text": "# coding: utf-8\n# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\n\n\"\"\"\nThis module provides classes to perform fitting of molecule with arbitrary\natom orders.\nThis module is supposed to perform exact comparisons without the atom order\ncorrespondence prerequisite, while molecule_structure_comparator is supposed\nto do rough comparisons with the atom order correspondence prerequisite.\n\nThe implementation is based on an excellent python package called `rmsd` that\nyou can find at https://github.com/charnley/rmsd.\n\"\"\"\n\n__author__ = \"Xiaohui Qu, Adam Fekete\"\n__version__ = \"1.0\"\n__maintainer__ = \"Xiaohui Qu\"\n__email__ = \"xhqu1981@gmail.com\"\n__status__ = \"Development\"\n__date__ = \"Aug 21, 2020\"\n\n\nimport abc\nimport copy\nimport itertools\nimport logging\nimport math\nimport re\n\nimport numpy as np\nfrom monty.dev import requires\nfrom monty.json import MSONable\n\ntry:\n    from openbabel import openbabel as ob\n\n    from pymatgen.io.babel import BabelMolAdaptor\nexcept ImportError:\n    ob = None\n\nfrom scipy.optimize import linear_sum_assignment\nfrom scipy.spatial.distance import cdist\n\nfrom pymatgen.core.structure import Molecule  # pylint: disable=ungrouped-imports\n\nlogger = logging.getLogger(__name__)\n\n\nclass AbstractMolAtomMapper(MSONable, metaclass=abc.ABCMeta):\n    \"\"\"\n    Abstract molecular atom order mapping class. A mapping will be able to\n    find the uniform atom order of two molecules that can pair the\n    geometrically equivalent atoms.\n    \"\"\"\n\n    @abc.abstractmethod\n    def uniform_labels(self, mol1, mol2):\n        \"\"\"\n        Pair the geometrically equivalent atoms of the molecules.\n\n        Args:\n            mol1: First molecule. OpenBabel OBMol or pymatgen Molecule object.\n            mol2: Second molecule. OpenBabel OBMol or pymatgen Molecule object.\n\n        Returns:\n            (list1, list2) if uniform atom order is found. list1 and list2\n            are for mol1 and mol2, respectively. Their length equal\n            to the number of atoms. They represents the uniform atom order\n            of the two molecules. The value of each element is the original\n            atom index in mol1 or mol2 of the current atom in uniform atom\n            order.\n            (None, None) if unform atom is not available.\n        \"\"\"\n        pass\n\n    @abc.abstractmethod\n    def get_molecule_hash(self, mol):\n        \"\"\"\n        Defines a hash for molecules. This allows molecules to be grouped\n        efficiently for comparison.\n\n        Args:\n            mol: The molecule. OpenBabel OBMol or pymatgen Molecule object\n\n        Returns:\n            A hashable object. Examples can be string formulas, etc.\n        \"\"\"\n        pass\n\n    @classmethod\n    def from_dict(cls, d):\n        \"\"\"\n        Args:\n            d (): Dict\n\n        Returns:\n            AbstractMolAtomMapper\n        \"\"\"\n        for trans_modules in [\"molecule_matcher\"]:\n            import sys\n\n            if sys.version_info > (3, 0):\n                level = 0  # Python 3.x\n            else:\n                level = -1  # Python 2.x\n            mod = __import__(\n                \"pymatgen.analysis.\" + trans_modules,\n                globals(),\n                locals(),\n                [d[\"@class\"]],\n                level,\n            )\n            if hasattr(mod, d[\"@class\"]):\n                class_proxy = getattr(mod, d[\"@class\"])\n                from_dict_proxy = getattr(class_proxy, \"from_dict\")\n                return from_dict_proxy(d)\n        raise ValueError(\"Invalid Comparator dict\")\n\n\nclass IsomorphismMolAtomMapper(AbstractMolAtomMapper):\n    \"\"\"\n    Pair atoms by isomorphism permutations in the OpenBabel::OBAlign class\n    \"\"\"\n\n    def uniform_labels(self, mol1, mol2):\n        \"\"\"\n        Pair the geometrically equivalent atoms of the molecules.\n        Calculate RMSD on all possible isomorphism mappings and return mapping\n        with the least RMSD\n\n        Args:\n            mol1: First molecule. OpenBabel OBMol or pymatgen Molecule object.\n            mol2: Second molecule. OpenBabel OBMol or pymatgen Molecule object.\n\n        Returns:\n            (list1, list2) if uniform atom order is found. list1 and list2\n            are for mol1 and mol2, respectively. Their length equal\n            to the number of atoms. They represents the uniform atom order\n            of the two molecules. The value of each element is the original\n            atom index in mol1 or mol2 of the current atom in uniform atom\n            order.\n            (None, None) if unform atom is not available.\n        \"\"\"\n        obmol1 = BabelMolAdaptor(mol1).openbabel_mol\n        obmol2 = BabelMolAdaptor(mol2).openbabel_mol\n\n        h1 = self.get_molecule_hash(obmol1)\n        h2 = self.get_molecule_hash(obmol2)\n        if h1 != h2:\n            return None, None\n\n        query = ob.CompileMoleculeQuery(obmol1)\n        isomapper = ob.OBIsomorphismMapper.GetInstance(query)\n        isomorph = ob.vvpairUIntUInt()\n        isomapper.MapAll(obmol2, isomorph)\n\n        sorted_isomorph = [sorted(x, key=lambda morp: morp[0]) for x in isomorph]\n        label2_list = tuple([tuple([p[1] + 1 for p in x]) for x in sorted_isomorph])\n\n        vmol1 = obmol1\n        aligner = ob.OBAlign(True, False)\n        aligner.SetRefMol(vmol1)\n        least_rmsd = float(\"Inf\")\n        best_label2 = None\n        label1 = list(range(1, obmol1.NumAtoms() + 1))\n        # noinspection PyProtectedMember\n        elements1 = InchiMolAtomMapper._get_elements(vmol1, label1)\n        for label2 in label2_list:\n            # noinspection PyProtectedMember\n            elements2 = InchiMolAtomMapper._get_elements(obmol2, label2)\n            if elements1 != elements2:\n                continue\n            vmol2 = ob.OBMol()\n            for i in label2:\n                vmol2.AddAtom(obmol2.GetAtom(i))\n            aligner.SetTargetMol(vmol2)\n            aligner.Align()\n            rmsd = aligner.GetRMSD()\n            if rmsd < least_rmsd:\n                least_rmsd = rmsd\n                best_label2 = copy.copy(label2)\n        return label1, best_label2\n\n    def get_molecule_hash(self, mol):\n        \"\"\"\n        Return inchi as molecular hash\n        \"\"\"\n        obconv = ob.OBConversion()\n        obconv.SetOutFormat(str(\"inchi\"))\n        obconv.AddOption(str(\"X\"), ob.OBConversion.OUTOPTIONS, str(\"DoNotAddH\"))\n        inchi_text = obconv.WriteString(mol)\n        match = re.search(r\"InChI=(?P<inchi>.+)\\n\", inchi_text)\n        return match.group(\"inchi\")\n\n    def as_dict(self):\n        \"\"\"\n        Returns:\n            Jsonable dict.\n        \"\"\"\n        return {\n            \"version\": __version__,\n            \"@module\": self.__class__.__module__,\n            \"@class\": self.__class__.__name__,\n        }\n\n    @classmethod\n    def from_dict(cls, d):\n        \"\"\"\n        Args:\n            d (dict): Dict representation\n\n        Returns:\n            IsomorphismMolAtomMapper\n        \"\"\"\n        return IsomorphismMolAtomMapper()\n\n\nclass InchiMolAtomMapper(AbstractMolAtomMapper):\n    \"\"\"\n    Pair atoms by inchi labels.\n    \"\"\"\n\n    def __init__(self, angle_tolerance=10.0):\n        \"\"\"\n        Args:\n            angle_tolerance (float): Angle threshold to assume linear molecule. In degrees.\n        \"\"\"\n        self._angle_tolerance = angle_tolerance\n        self._assistant_mapper = IsomorphismMolAtomMapper()\n\n    def as_dict(self):\n        \"\"\"\n        Returns:\n            MSONAble dict.\n        \"\"\"\n        return {\n            \"version\": __version__,\n            \"@module\": self.__class__.__module__,\n            \"@class\": self.__class__.__name__,\n            \"angle_tolerance\": self._angle_tolerance,\n        }\n\n    @classmethod\n    def from_dict(cls, d):\n        \"\"\"\n        Args:\n            d (dict): Dict Representation\n\n        Returns:\n            InchiMolAtomMapper\n        \"\"\"\n        return InchiMolAtomMapper(angle_tolerance=d[\"angle_tolerance\"])\n\n    @staticmethod\n    def _inchi_labels(mol):\n        \"\"\"\n        Get the inchi canonical labels of the heavy atoms in the molecule\n\n        Args:\n            mol: The molecule. OpenBabel OBMol object\n\n        Returns:\n            The label mappings. List of tuple of canonical label,\n            original label\n            List of equivalent atoms.\n        \"\"\"\n        obconv = ob.OBConversion()\n        obconv.SetOutFormat(str(\"inchi\"))\n        obconv.AddOption(str(\"a\"), ob.OBConversion.OUTOPTIONS)\n        obconv.AddOption(str(\"X\"), ob.OBConversion.OUTOPTIONS, str(\"DoNotAddH\"))\n        inchi_text = obconv.WriteString(mol)\n        match = re.search(\n            r\"InChI=(?P<inchi>.+)\\nAuxInfo=.+\" r\"/N:(?P<labels>[0-9,;]+)/(E:(?P<eq_atoms>[0-9,\" r\";\\(\\)]*)/)?\",\n            inchi_text,\n        )\n        inchi = match.group(\"inchi\")\n        label_text = match.group(\"labels\")\n        eq_atom_text = match.group(\"eq_atoms\")\n        heavy_atom_labels = tuple([int(i) for i in label_text.replace(\";\", \",\").split(\",\")])\n        eq_atoms = []\n        if eq_atom_text is not None:\n            eq_tokens = re.findall(r\"\\(((?:[0-9]+,)+[0-9]+)\\)\", eq_atom_text.replace(\";\", \",\"))\n            eq_atoms = tuple([tuple([int(i) for i in t.split(\",\")]) for t in eq_tokens])\n        return heavy_atom_labels, eq_atoms, inchi\n\n    @staticmethod\n    def _group_centroid(mol, ilabels, group_atoms):\n        \"\"\"\n        Calculate the centroids of a group atoms indexed by the labels of inchi\n\n        Args:\n            mol: The molecule. OpenBabel OBMol object\n            ilabel: inchi label map\n\n        Returns:\n            Centroid. Tuple (x, y, z)\n        \"\"\"\n        c1x, c1y, c1z = 0.0, 0.0, 0.0\n        for i in group_atoms:\n            orig_idx = ilabels[i - 1]\n            oa1 = mol.GetAtom(orig_idx)\n            c1x += float(oa1.x())\n            c1y += float(oa1.y())\n            c1z += float(oa1.z())\n        num_atoms = len(group_atoms)\n        c1x /= num_atoms\n        c1y /= num_atoms\n        c1z /= num_atoms\n        return c1x, c1y, c1z\n\n    def _virtual_molecule(self, mol, ilabels, eq_atoms):\n        \"\"\"\n        Create a virtual molecule by unique atoms, the centriods of the\n        equivalent atoms\n\n        Args:\n            mol: The molecule. OpenBabel OBMol object\n            ilables: inchi label map\n            eq_atoms: equivalent atom labels\n            farthest_group_idx: The equivalent atom group index in which\n                there is the farthest atom to the centroid\n\n        Return:\n            The virtual molecule\n        \"\"\"\n        vmol = ob.OBMol()\n\n        non_unique_atoms = {a for g in eq_atoms for a in g}\n        all_atoms = set(range(1, len(ilabels) + 1))\n        unique_atom_labels = sorted(all_atoms - non_unique_atoms)\n\n        # try to align molecules using unique atoms\n        for i in unique_atom_labels:\n            orig_idx = ilabels[i - 1]\n            oa1 = mol.GetAtom(orig_idx)\n            a1 = vmol.NewAtom()\n            a1.SetAtomicNum(oa1.GetAtomicNum())\n            a1.SetVector(oa1.GetVector())\n\n        # try to align using centroids of the equivalent atoms\n        if vmol.NumAtoms() < 3:\n            for symm in eq_atoms:\n                c1x, c1y, c1z = self._group_centroid(mol, ilabels, symm)\n                min_distance = float(\"inf\")\n                for i in range(1, vmol.NumAtoms() + 1):\n                    va = vmol.GetAtom(i)\n                    distance = math.sqrt((c1x - va.x()) ** 2 + (c1y - va.y()) ** 2 + (c1z - va.z()) ** 2)\n                    if distance < min_distance:\n                        min_distance = distance\n                if min_distance > 0.2:\n                    a1 = vmol.NewAtom()\n                    a1.SetAtomicNum(9)\n                    a1.SetVector(c1x, c1y, c1z)\n\n        return vmol\n\n    @staticmethod\n    def _align_heavy_atoms(mol1, mol2, vmol1, vmol2, ilabel1, ilabel2, eq_atoms):\n        \"\"\"\n        Align the label of topologically identical atoms of second molecule\n        towards first molecule\n\n        Args:\n            mol1: First molecule. OpenBabel OBMol object\n            mol2: Second molecule. OpenBabel OBMol object\n            vmol1: First virtual molecule constructed by centroids. OpenBabel\n                OBMol object\n            vmol2: First virtual molecule constructed by centroids. OpenBabel\n                OBMol object\n            ilabel1: inchi label map of the first molecule\n            ilabel2: inchi label map of the second molecule\n            eq_atoms: equivalent atom lables\n\n        Return:\n            corrected inchi labels of heavy atoms of the second molecule\n        \"\"\"\n\n        nvirtual = vmol1.NumAtoms()\n        nheavy = len(ilabel1)\n\n        for i in ilabel2:  # add all heavy atoms\n            a1 = vmol1.NewAtom()\n            a1.SetAtomicNum(1)\n            a1.SetVector(0.0, 0.0, 0.0)  # useless, just to pair with vmol2\n            oa2 = mol2.GetAtom(i)\n            a2 = vmol2.NewAtom()\n            a2.SetAtomicNum(1)\n            # align using the virtual atoms, these atoms are not\n            # used to align, but match by positions\n            a2.SetVector(oa2.GetVector())\n\n        aligner = ob.OBAlign(False, False)\n        aligner.SetRefMol(vmol1)\n        aligner.SetTargetMol(vmol2)\n        aligner.Align()\n        aligner.UpdateCoords(vmol2)\n\n        canon_mol1 = ob.OBMol()\n        for i in ilabel1:\n            oa1 = mol1.GetAtom(i)\n            a1 = canon_mol1.NewAtom()\n            a1.SetAtomicNum(oa1.GetAtomicNum())\n            a1.SetVector(oa1.GetVector())\n\n        aligned_mol2 = ob.OBMol()\n        for i in range(nvirtual + 1, nvirtual + nheavy + 1):\n            oa2 = vmol2.GetAtom(i)\n            a2 = aligned_mol2.NewAtom()\n            a2.SetAtomicNum(oa2.GetAtomicNum())\n            a2.SetVector(oa2.GetVector())\n\n        canon_label2 = list(range(1, nheavy + 1))\n        for symm in eq_atoms:\n            for i in symm:\n                canon_label2[i - 1] = -1\n        for symm in eq_atoms:\n            candidates1 = list(symm)\n            candidates2 = list(symm)\n            for c2 in candidates2:\n                distance = 99999.0\n                canon_idx = candidates1[0]\n                a2 = aligned_mol2.GetAtom(c2)\n                for c1 in candidates1:\n                    a1 = canon_mol1.GetAtom(c1)\n                    d = a1.GetDistance(a2)\n                    if d < distance:\n                        distance = d\n                        canon_idx = c1\n                canon_label2[c2 - 1] = canon_idx\n                candidates1.remove(canon_idx)\n\n        canon_inchi_orig_map2 = list(zip(canon_label2, list(range(1, nheavy + 1)), ilabel2))\n        canon_inchi_orig_map2.sort(key=lambda m: m[0])\n        heavy_atom_indices2 = tuple([x[2] for x in canon_inchi_orig_map2])\n        return heavy_atom_indices2\n\n    @staticmethod\n    def _align_hydrogen_atoms(mol1, mol2, heavy_indices1, heavy_indices2):\n        \"\"\"\n        Align the label of topologically identical atoms of second molecule\n        towards first molecule\n\n        Args:\n            mol1: First molecule. OpenBabel OBMol object\n            mol2: Second molecule. OpenBabel OBMol object\n            heavy_indices1: inchi label map of the first molecule\n            heavy_indices2: label map of the second molecule\n\n        Return:\n            corrected label map of all atoms of the second molecule\n        \"\"\"\n        num_atoms = mol2.NumAtoms()\n        all_atom = set(range(1, num_atoms + 1))\n        hydrogen_atoms1 = all_atom - set(heavy_indices1)\n        hydrogen_atoms2 = all_atom - set(heavy_indices2)\n        label1 = heavy_indices1 + tuple(hydrogen_atoms1)\n        label2 = heavy_indices2 + tuple(hydrogen_atoms2)\n\n        cmol1 = ob.OBMol()\n        for i in label1:\n            oa1 = mol1.GetAtom(i)\n            a1 = cmol1.NewAtom()\n            a1.SetAtomicNum(oa1.GetAtomicNum())\n            a1.SetVector(oa1.GetVector())\n        cmol2 = ob.OBMol()\n        for i in label2:\n            oa2 = mol2.GetAtom(i)\n            a2 = cmol2.NewAtom()\n            a2.SetAtomicNum(oa2.GetAtomicNum())\n            a2.SetVector(oa2.GetVector())\n\n        aligner = ob.OBAlign(False, False)\n        aligner.SetRefMol(cmol1)\n        aligner.SetTargetMol(cmol2)\n        aligner.Align()\n        aligner.UpdateCoords(cmol2)\n\n        hydrogen_label2 = []\n        hydrogen_label1 = list(range(len(heavy_indices1) + 1, num_atoms + 1))\n        for h2 in range(len(heavy_indices2) + 1, num_atoms + 1):\n            distance = 99999.0\n            idx = hydrogen_label1[0]\n            a2 = cmol2.GetAtom(h2)\n            for h1 in hydrogen_label1:\n                a1 = cmol1.GetAtom(h1)\n                d = a1.GetDistance(a2)\n                if d < distance:\n                    distance = d\n                    idx = h1\n            hydrogen_label2.append(idx)\n            hydrogen_label1.remove(idx)\n\n        hydrogen_orig_idx2 = label2[len(heavy_indices2) :]\n        hydrogen_canon_orig_map2 = list(zip(hydrogen_label2, hydrogen_orig_idx2))\n        hydrogen_canon_orig_map2.sort(key=lambda m: m[0])\n        hydrogen_canon_indices2 = [x[1] for x in hydrogen_canon_orig_map2]\n\n        canon_label1 = label1\n        canon_label2 = heavy_indices2 + tuple(hydrogen_canon_indices2)\n\n        return canon_label1, canon_label2\n\n    @staticmethod\n    def _get_elements(mol, label):\n        \"\"\"\n        The the elements of the atoms in the specified order\n\n        Args:\n            mol: The molecule. OpenBabel OBMol object.\n            label: The atom indices. List of integers.\n\n        Returns:\n            Elements. List of integers.\n        \"\"\"\n        elements = [int(mol.GetAtom(i).GetAtomicNum()) for i in label]\n        return elements\n\n    def _is_molecule_linear(self, mol):\n        \"\"\"\n        Is the molecule a linear one\n\n        Args:\n            mol: The molecule. OpenBabel OBMol object.\n\n        Returns:\n            Boolean value.\n        \"\"\"\n        if mol.NumAtoms() < 3:\n            return True\n        a1 = mol.GetAtom(1)\n        a2 = mol.GetAtom(2)\n        for i in range(3, mol.NumAtoms() + 1):\n            angle = float(mol.GetAtom(i).GetAngle(a2, a1))\n            if angle < 0.0:\n                angle = -angle\n            if angle > 90.0:\n                angle = 180.0 - angle\n            if angle > self._angle_tolerance:\n                return False\n        return True\n\n    def uniform_labels(self, mol1, mol2):\n        \"\"\"\n        Args:\n            mol1 (Molecule): Molecule 1\n            mol2 (Molecule): Molecule 2\n\n        Returns:\n            Labels\n        \"\"\"\n        obmol1 = BabelMolAdaptor(mol1).openbabel_mol\n        obmol2 = BabelMolAdaptor(mol2).openbabel_mol\n\n        ilabel1, iequal_atom1, inchi1 = self._inchi_labels(obmol1)\n        ilabel2, iequal_atom2, inchi2 = self._inchi_labels(obmol2)\n\n        if inchi1 != inchi2:\n            return None, None  # Topoligically different\n\n        if iequal_atom1 != iequal_atom2:\n            raise Exception(\"Design Error! Equavilent atoms are inconsistent\")\n\n        vmol1 = self._virtual_molecule(obmol1, ilabel1, iequal_atom1)\n        vmol2 = self._virtual_molecule(obmol2, ilabel2, iequal_atom2)\n\n        if vmol1.NumAtoms() != vmol2.NumAtoms():\n            return None, None\n\n        if vmol1.NumAtoms() < 3 or self._is_molecule_linear(vmol1) or self._is_molecule_linear(vmol2):\n            # using isomorphism for difficult (actually simple) molecules\n            clabel1, clabel2 = self._assistant_mapper.uniform_labels(mol1, mol2)\n        else:\n            heavy_atom_indices2 = self._align_heavy_atoms(obmol1, obmol2, vmol1, vmol2, ilabel1, ilabel2, iequal_atom1)\n            clabel1, clabel2 = self._align_hydrogen_atoms(obmol1, obmol2, ilabel1, heavy_atom_indices2)\n        if clabel1 and clabel2:\n            elements1 = self._get_elements(obmol1, clabel1)\n            elements2 = self._get_elements(obmol2, clabel2)\n\n            if elements1 != elements2:\n                return None, None\n\n        return clabel1, clabel2\n\n    def get_molecule_hash(self, mol):\n        \"\"\"\n        Return inchi as molecular hash\n        \"\"\"\n        obmol = BabelMolAdaptor(mol).openbabel_mol\n        inchi = self._inchi_labels(obmol)[2]\n        return inchi\n\n\nclass MoleculeMatcher(MSONable):\n    \"\"\"\n    Class to match molecules and identify whether molecules are the same.\n    \"\"\"\n\n    @requires(\n        ob,\n        \"BabelMolAdaptor requires openbabel to be installed with \"\n        \"Python bindings. Please get it at http://openbabel.org \"\n        \"(version >=3.0.0).\",\n    )\n    def __init__(self, tolerance=0.01, mapper=InchiMolAtomMapper()):\n        \"\"\"\n        Args:\n            tolerance (float): RMSD difference threshold whether two molecules are\n                different\n            mapper (AbstractMolAtomMapper): MolAtomMapper object that is able to map the atoms of two\n                molecule to uniform order\n        \"\"\"\n        self._tolerance = tolerance\n        self._mapper = mapper\n\n    def fit(self, mol1, mol2):\n        \"\"\"\n        Fit two molecules.\n\n        Args:\n            mol1: First molecule. OpenBabel OBMol or pymatgen Molecule object\n            mol2: Second molecule. OpenBabel OBMol or pymatgen Molecule object\n\n        Returns:\n            A boolean value indicates whether two molecules are the same.\n        \"\"\"\n        return self.get_rmsd(mol1, mol2) < self._tolerance\n\n    def get_rmsd(self, mol1, mol2):\n        \"\"\"\n        Get RMSD between two molecule with arbitrary atom order.\n\n        Returns:\n            RMSD if topology of the two molecules are the same\n            Infinite if  the topology is different\n        \"\"\"\n        label1, label2 = self._mapper.uniform_labels(mol1, mol2)\n        if label1 is None or label2 is None:\n            return float(\"Inf\")\n        return self._calc_rms(mol1, mol2, label1, label2)\n\n    @staticmethod\n    def _calc_rms(mol1, mol2, clabel1, clabel2):\n        \"\"\"\n        Calculate the RMSD.\n\n        Args:\n            mol1: The first molecule. OpenBabel OBMol or pymatgen Molecule\n                object\n            mol2: The second molecule. OpenBabel OBMol or pymatgen Molecule\n                object\n            clabel1: The atom indices that can reorder the first molecule to\n                uniform atom order\n            clabel1: The atom indices that can reorder the second molecule to\n                uniform atom order\n\n        Returns:\n            The RMSD.\n        \"\"\"\n        obmol1 = BabelMolAdaptor(mol1).openbabel_mol\n        obmol2 = BabelMolAdaptor(mol2).openbabel_mol\n\n        cmol1 = ob.OBMol()\n        for i in clabel1:\n            oa1 = obmol1.GetAtom(i)\n            a1 = cmol1.NewAtom()\n            a1.SetAtomicNum(oa1.GetAtomicNum())\n            a1.SetVector(oa1.GetVector())\n        cmol2 = ob.OBMol()\n        for i in clabel2:\n            oa2 = obmol2.GetAtom(i)\n            a2 = cmol2.NewAtom()\n            a2.SetAtomicNum(oa2.GetAtomicNum())\n            a2.SetVector(oa2.GetVector())\n\n        aligner = ob.OBAlign(True, False)\n        aligner.SetRefMol(cmol1)\n        aligner.SetTargetMol(cmol2)\n        aligner.Align()\n        return aligner.GetRMSD()\n\n    def group_molecules(self, mol_list):\n        \"\"\"\n        Group molecules by structural equality.\n\n        Args:\n            mol_list: List of OpenBabel OBMol or pymatgen objects\n\n        Returns:\n            A list of lists of matched molecules\n            Assumption: if s1=s2 and s2=s3, then s1=s3\n            This may not be true for small tolerances.\n        \"\"\"\n        mol_hash = [(i, self._mapper.get_molecule_hash(m)) for i, m in enumerate(mol_list)]\n        mol_hash.sort(key=lambda x: x[1])\n\n        # Use molecular hash to pre-group molecules.\n        raw_groups = tuple([tuple([m[0] for m in g]) for k, g in itertools.groupby(mol_hash, key=lambda x: x[1])])\n\n        group_indices = []\n        for rg in raw_groups:\n            mol_eq_test = [\n                (p[0], p[1], self.fit(mol_list[p[0]], mol_list[p[1]])) for p in itertools.combinations(sorted(rg), 2)\n            ]\n            mol_eq = {(p[0], p[1]) for p in mol_eq_test if p[2]}\n            not_alone_mols = set(itertools.chain.from_iterable(mol_eq))\n            alone_mols = set(rg) - not_alone_mols\n            group_indices.extend([[m] for m in alone_mols])\n            while len(not_alone_mols) > 0:\n                current_group = {not_alone_mols.pop()}\n                while len(not_alone_mols) > 0:\n                    candidate_pairs = {tuple(sorted(p)) for p in itertools.product(current_group, not_alone_mols)}\n                    mutual_pairs = candidate_pairs & mol_eq\n                    if len(mutual_pairs) == 0:\n                        break\n                    mutual_mols = set(itertools.chain.from_iterable(mutual_pairs))\n                    current_group |= mutual_mols\n                    not_alone_mols -= mutual_mols\n                group_indices.append(sorted(current_group))\n\n        group_indices.sort(key=lambda x: (len(x), -x[0]), reverse=True)\n        all_groups = [[mol_list[i] for i in g] for g in group_indices]\n        return all_groups\n\n    def as_dict(self):\n        \"\"\"\n        Returns:\n            MSONAble dict.\n        \"\"\"\n        return {\n            \"version\": __version__,\n            \"@module\": self.__class__.__module__,\n            \"@class\": self.__class__.__name__,\n            \"tolerance\": self._tolerance,\n            \"mapper\": self._mapper.as_dict(),\n        }\n\n    @classmethod\n    def from_dict(cls, d):\n        \"\"\"\n        Args:\n            d (dict): Dict representation\n\n        Returns:\n            MoleculeMatcher\n        \"\"\"\n        return MoleculeMatcher(\n            tolerance=d[\"tolerance\"],\n            mapper=AbstractMolAtomMapper.from_dict(d[\"mapper\"]),\n        )\n\n\nclass KabschMatcher(MSONable):\n    \"\"\"Molecule matcher using Kabsch algorithm\n\n    The Kabsch algorithm capable aligning two molecules by finding the parameters\n    (translation, rotation) which minimize the root-mean-square-deviation (RMSD) of\n    two molecules which are topologically (atom types, geometry) similar two each other.\n\n    Notes:\n        When aligning molecules, the atoms of the two molecules **must** be in the same\n        order for the results to be sensible.\n    \"\"\"\n\n    def __init__(self, target: Molecule):\n        \"\"\"Constructor of the matcher object.\n\n        Args:\n            target: a `Molecule` object used as a target during the alignment\n        \"\"\"\n        self.target = target\n\n    def match(self, p: Molecule):\n        \"\"\"Using the Kabsch algorithm the alignment of two molecules (P, Q)\n        happens in three steps:\n        - translate the P and Q into their centroid\n        - compute of the optimal rotation matrix (U) using Kabsch algorithm\n        - compute the translation (V) and rmsd\n\n        The function returns the rotation matrix (U), translation vector (V),\n        and RMSD between Q and P', where P' is:\n\n            P' = P * U + V\n\n        Args:\n            p: a `Molecule` object what will be matched with the target one.\n\n        Returns:\n            U: Rotation matrix (D,D)\n            V: Translation vector (D)\n            RMSD : Root mean squared deviation between P and Q\n        \"\"\"\n        if self.target.atomic_numbers != p.atomic_numbers:\n            raise ValueError(\"The order of the species aren't matching! \" \"Please try using `PermInvMatcher`.\")\n\n        p_coord, q_coord = p.cart_coords, self.target.cart_coords\n\n        # Both sets of coordinates must be translated first, so that their\n        # centroid coincides with the origin of the coordinate system.\n        p_trans, q_trans = p_coord.mean(axis=0), q_coord.mean(axis=0)\n        p_centroid, q_centroid = p_coord - p_trans, q_coord - q_trans\n\n        # The optimal rotation matrix U using Kabsch algorithm\n        U = self.kabsch(p_centroid, q_centroid)\n\n        p_prime_centroid = np.dot(p_centroid, U)\n        rmsd = np.sqrt(np.mean(np.square(p_prime_centroid - q_centroid)))\n\n        V = q_trans - np.dot(p_trans, U)\n\n        return U, V, rmsd\n\n    def fit(self, p: Molecule):\n        \"\"\"Rotate and transform `p` molecule according to the best match.\n\n        Args:\n            p: a `Molecule` object what will be matched with the target one.\n\n        Returns:\n            p_prime: Rotated and translated of the `p` `Molecule` object\n            rmsd: Root-mean-square-deviation between `p_prime` and the `target`\n        \"\"\"\n        U, V, rmsd = self.match(p)\n\n        # Rotate and translate matrix `p` onto the target molecule.\n        # P' = P * U + V\n        p_prime = p.copy()\n        for site in p_prime:\n            site.coords = np.dot(site.coords, U) + V\n\n        return p_prime, rmsd\n\n    @staticmethod\n    def kabsch(P: np.ndarray, Q: np.ndarray):\n        \"\"\"The Kabsch algorithm is a method for calculating the optimal rotation matrix\n        that minimizes the root mean squared deviation (RMSD) between two paired sets of points\n        P and Q, centered around the their centroid.\n\n        For more info see:\n        - http://en.wikipedia.org/wiki/Kabsch_algorithm and\n        - https://cnx.org/contents/HV-RsdwL@23/Molecular-Distance-Measures\n\n        Args:\n            P: Nx3 matrix, where N is the number of points.\n            Q: Nx3 matrix, where N is the number of points.\n\n        Returns:\n            U: 3x3 rotation matrix\n        \"\"\"\n\n        # Computation of the cross-covariance matrix\n        C = np.dot(P.T, Q)\n\n        # Computation of the optimal rotation matrix\n        # using singular value decomposition (SVD).\n        V, S, WT = np.linalg.svd(C)\n\n        # Getting the sign of the det(V*Wt) to decide whether\n        d = np.linalg.det(np.dot(V, WT))\n\n        # And finally calculating the optimal rotation matrix R\n        # we need to correct our rotation matrix to ensure a right-handed coordinate system.\n        U = np.dot(np.dot(V, np.diag([1, 1, d])), WT)\n\n        return U\n\n\nclass BruteForceOrderMatcher(KabschMatcher):\n    \"\"\"Finding the best match between molecules by selecting molecule order\n    with the smallest RMSD from all the possible order combinations.\n\n    Notes:\n        When aligning molecules, the atoms of the two molecules **must** have same number\n        of atoms from the same species.\n    \"\"\"\n\n    def match(self, p: Molecule, ignore_warning=False):\n        \"\"\"Similar as `KabschMatcher.match` but this method also finds the order of\n        atoms which belongs to the best match.\n\n        A `ValueError` will be raised when the total number of possible combinations\n        become unfeasible (more than a million combination).\n\n        Args:\n            p: a `Molecule` object what will be matched with the target one.\n            ignore_warning: ignoring error when the number of combination is too large\n\n        Returns:\n            inds: The indices of atoms\n            U: 3x3 rotation matrix\n            V: Translation vector\n            rmsd: Root mean squared deviation between P and Q\n        \"\"\"\n\n        q = self.target\n\n        if sorted(p.atomic_numbers) != sorted(q.atomic_numbers):\n            raise ValueError(\"The number of the same species aren't matching!\")\n\n        _, count = np.unique(p.atomic_numbers, return_counts=True)\n        total_permutations = 1\n        for c in count:\n            total_permutations *= np.math.factorial(c)  # type: ignore\n\n        if not ignore_warning and total_permutations > 1_000_000:\n            raise ValueError(\n                \"The number of all possible permutations \"\n                \"({}) is not feasible to run this method!\".format(total_permutations)\n            )\n\n        p_coord, q_coord = p.cart_coords, q.cart_coords\n        p_atoms, q_atoms = np.array(p.atomic_numbers), np.array(q.atomic_numbers)\n\n        # Both sets of coordinates must be translated first, so that\n        # their centroid coincides with the origin of the coordinate system.\n        p_trans, q_trans = p_coord.mean(axis=0), q_coord.mean(axis=0)\n        p_centroid, q_centroid = p_coord - p_trans, q_coord - q_trans\n\n        # Sort the order of the target molecule by the elements\n        q_inds = np.argsort(q_atoms)\n        q_centroid = q_centroid[q_inds]\n\n        # Initializing return values\n        rmsd = np.inf\n\n        # Generate all permutation grouped/sorted by the elements\n        for p_inds_test in self.permutations(p_atoms):\n\n            p_centroid_test = p_centroid[p_inds_test]\n            U_test = self.kabsch(p_centroid_test, q_centroid)\n\n            p_centroid_prime_test = np.dot(p_centroid_test, U_test)\n            rmsd_test = np.sqrt(np.mean(np.square(p_centroid_prime_test - q_centroid)))\n\n            if rmsd_test < rmsd:\n                p_inds, U, rmsd = p_inds_test, U_test, rmsd_test\n\n        # Rotate and translate matrix P unto matrix Q using Kabsch algorithm.\n        # P' = P * U + V\n        V = q_trans - np.dot(p_trans, U)\n\n        # Using the original order of the indices\n        inds = p_inds[np.argsort(q_inds)]\n\n        return inds, U, V, rmsd\n\n    def fit(self, p: Molecule, ignore_warning=False):\n        \"\"\"Order, rotate and transform `p` molecule according to the best match.\n\n        A `ValueError` will be raised when the total number of possible combinations\n        become unfeasible (more than a million combinations).\n\n        Args:\n            p: a `Molecule` object what will be matched with the target one.\n            ignore_warning: ignoring error when the number of combination is too large\n\n        Returns:\n            p_prime: Rotated and translated of the `p` `Molecule` object\n            rmsd: Root-mean-square-deviation between `p_prime` and the `target`\n        \"\"\"\n\n        inds, U, V, rmsd = self.match(p, ignore_warning=ignore_warning)\n\n        p_prime = Molecule.from_sites([p[i] for i in inds])\n        for site in p_prime:\n            site.coords = np.dot(site.coords, U) + V\n\n        return p_prime, rmsd\n\n    @staticmethod\n    def permutations(atoms):\n        \"\"\"Generates all the possible permutations of atom order. To achieve better\n        performance all tha cases where the atoms are different has been ignored.\n        \"\"\"\n        element_iterators = [itertools.permutations(np.where(atoms == element)[0]) for element in np.unique(atoms)]\n\n        for inds in itertools.product(*element_iterators):\n            yield np.array(list(itertools.chain(*inds)))\n\n\nclass HungarianOrderMatcher(KabschMatcher):\n    \"\"\"This method pre-aligns the molecules based on their principal inertia\n    axis and then re-orders the input atom list using the Hungarian method.\n\n    Notes:\n        This method cannot guarantee the best match but is very fast.\n\n        When aligning molecules, the atoms of the two molecules **must** have same number\n        of atoms from the same species.\n    \"\"\"\n\n    def match(self, p: Molecule):\n        \"\"\"Similar as `KabschMatcher.match` but this method also finds the order of\n        atoms which belongs to the best match.\n\n        Args:\n            p: a `Molecule` object what will be matched with the target one.\n\n        Returns:\n            inds: The indices of atoms\n            U: 3x3 rotation matrix\n            V: Translation vector\n            rmsd: Root mean squared deviation between P and Q\n        \"\"\"\n\n        if sorted(p.atomic_numbers) != sorted(self.target.atomic_numbers):\n            raise ValueError(\"The number of the same species aren't matching!\")\n\n        p_coord, q_coord = p.cart_coords, self.target.cart_coords\n        p_atoms, q_atoms = (\n            np.array(p.atomic_numbers),\n            np.array(self.target.atomic_numbers),\n        )\n\n        p_weights = np.array([site.species.weight for site in p])\n        q_weights = np.array([site.species.weight for site in self.target])\n\n        # Both sets of coordinates must be translated first, so that\n        # their center of mass with the origin of the coordinate system.\n        p_trans, q_trans = p.center_of_mass, self.target.center_of_mass\n        p_centroid, q_centroid = p_coord - p_trans, q_coord - q_trans\n\n        # Initializing return values\n        rmsd = np.inf\n\n        # Generate all permutation grouped/sorted by the elements\n        for p_inds_test in self.permutations(p_atoms, p_centroid, p_weights, q_atoms, q_centroid, q_weights):\n\n            p_centroid_test = p_centroid[p_inds_test]\n            U_test = self.kabsch(p_centroid_test, q_centroid)\n\n            p_centroid_prime_test = np.dot(p_centroid_test, U_test)\n            rmsd_test = np.sqrt(np.mean(np.square(p_centroid_prime_test - q_centroid)))\n\n            if rmsd_test < rmsd:\n                inds, U, rmsd = p_inds_test, U_test, rmsd_test\n\n        # Rotate and translate matrix P unto matrix Q using Kabsch algorithm.\n        # P' = P * U + V\n        V = q_trans - np.dot(p_trans, U)\n\n        return inds, U, V, rmsd\n\n    def fit(self, p: Molecule):\n        \"\"\"Order, rotate and transform `p` molecule according to the best match.\n\n        Args:\n            p: a `Molecule` object what will be matched with the target one.\n\n        Returns:\n            p_prime: Rotated and translated of the `p` `Molecule` object\n            rmsd: Root-mean-square-deviation between `p_prime` and the `target`\n        \"\"\"\n\n        inds, U, V, rmsd = self.match(p)\n\n        # Translate and rotate `mol1` unto `mol2` using Kabsch algorithm.\n        p_prime = Molecule.from_sites([p[i] for i in inds])\n        for site in p_prime:\n            site.coords = np.dot(site.coords, U) + V\n\n        return p_prime, rmsd\n\n    @staticmethod\n    def permutations(p_atoms, p_centroid, p_weights, q_atoms, q_centroid, q_weights):\n        \"\"\"Generates two possible permutations of atom order. This method uses the principle component\n        of the inertia tensor to prealign the molecules and hungarian method to determine the order.\n        There are always two possible permutation depending on the way to pre-aligning the molecules.\n\n        Args:\n            p_atoms: atom numbers\n            p_centroid: array of atom positions\n            p_weights: array of atom weights\n            q_atoms: atom numbers\n            q_centroid: array of atom positions\n            q_weights: array of atom weights\n\n        Yield:\n            perm_inds: array of atoms' order\n        \"\"\"\n        # get the principal axis of P and Q\n        p_axis = HungarianOrderMatcher.get_principal_axis(p_centroid, p_weights)\n        q_axis = HungarianOrderMatcher.get_principal_axis(q_centroid, q_weights)\n\n        # rotate Q onto P considering that the axis are parallel and antiparallel\n        U = HungarianOrderMatcher.rotation_matrix_vectors(q_axis, p_axis)\n        p_centroid_test = np.dot(p_centroid, U)\n\n        # generate full view from q shape to fill in atom view on the fly\n        perm_inds = np.zeros(len(p_atoms), dtype=int)\n\n        # Find unique atoms\n        species = np.unique(p_atoms)\n\n        for specie in species:\n            p_atom_inds = np.where(p_atoms == specie)[0]\n            q_atom_inds = np.where(q_atoms == specie)[0]\n            A = q_centroid[q_atom_inds]\n            B = p_centroid_test[p_atom_inds]\n\n            # Perform Hungarian analysis on distance matrix between atoms of 1st\n            # structure and trial structure\n            distances = cdist(A, B, \"euclidean\")\n            a_inds, b_inds = linear_sum_assignment(distances)\n\n            perm_inds[q_atom_inds] = p_atom_inds[b_inds]\n\n        yield perm_inds\n\n        # rotate Q onto P considering that the axis are parallel and antiparallel\n        U = HungarianOrderMatcher.rotation_matrix_vectors(q_axis, -p_axis)\n        p_centroid_test = np.dot(p_centroid, U)\n\n        # generate full view from q shape to fill in atom view on the fly\n        perm_inds = np.zeros(len(p_atoms), dtype=int)\n\n        # Find unique atoms\n        species = np.unique(p_atoms)\n\n        for specie in species:\n            p_atom_inds = np.where(p_atoms == specie)[0]\n            q_atom_inds = np.where(q_atoms == specie)[0]\n            A = q_centroid[q_atom_inds]\n            B = p_centroid_test[p_atom_inds]\n\n            # Perform Hungarian analysis on distance matrix between atoms of 1st\n            # structure and trial structure\n            distances = cdist(A, B, \"euclidean\")\n            a_inds, b_inds = linear_sum_assignment(distances)\n\n            perm_inds[q_atom_inds] = p_atom_inds[b_inds]\n\n        yield perm_inds\n\n    @staticmethod\n    def get_principal_axis(coords, weights):\n        \"\"\"Get the molecule's principal axis.\n\n        Args:\n            coords: coordinates of atoms\n            weights: the weight use for calculating the inertia tensor\n\n        Returns:\n            Array of dim 3 containing the principal axis\n        \"\"\"\n\n        Ixx = Iyy = Izz = Ixy = Ixz = Iyz = 0.0\n\n        for (x, y, z), wt in zip(coords, weights):\n\n            Ixx += wt * (y * y + z * z)\n            Iyy += wt * (x * x + z * z)\n            Izz += wt * (x * x + y * y)\n\n            Ixy += -wt * x * y\n            Ixz += -wt * x * z\n            Iyz += -wt * y * z\n\n        inertia_tensor = np.array([[Ixx, Ixy, Ixz], [Ixy, Iyy, Iyz], [Ixz, Iyz, Izz]])\n\n        eigvals, eigvecs = np.linalg.eigh(inertia_tensor)\n\n        principal_axis = eigvecs[:, 0]\n        return principal_axis\n\n    @staticmethod\n    def rotation_matrix_vectors(v1, v2):\n        \"\"\"Returns the rotation matrix that rotates v1 onto v2 using\n        Rodrigues' rotation formula.\n\n        See more: https://math.stackexchange.com/a/476311\n\n        Args:\n            v1: initial vector\n            v2: target vector\n\n        Returns:\n            3x3 rotation matrix\n        \"\"\"\n\n        if np.allclose(v1, v2):\n            # same direction\n            return np.eye(3)\n\n        if np.allclose(v1, -v2):\n            # opposite direction: return a rotation of pi around the y-axis\n            return np.array([[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]])\n\n        v = np.cross(v1, v2)\n        s = np.linalg.norm(v)\n        c = np.vdot(v1, v2)\n\n        vx = np.array([[0.0, -v[2], v[1]], [v[2], 0.0, -v[0]], [-v[1], v[0], 0.0]])\n\n        return np.eye(3) + vx + np.dot(vx, vx) * ((1.0 - c) / (s * s))\n\n\nclass GeneticOrderMatcher(KabschMatcher):\n    \"\"\"This method was inspired by genetic algorithms and tries to match molecules\n    based on their already matched fragments.\n\n    It uses the fact that when two molecule is matching their sub-structures have to match as well.\n    The main idea here is that in each iteration (generation) we can check the match of all possible\n    fragments and ignore those which are not feasible.\n\n    Although in the worst case this method has N! complexity (same as the brute force one),\n    in practice it performs much faster because many of the combination can be eliminated\n    during the fragment matching.\n\n    Notes:\n        This method very robust and returns with all the possible orders.\n\n        There is a well known weakness/corner case: The case when there is\n        a outlier with large deviation with a small index might be ignored.\n        This happens due to the nature of the average function\n        used to calculate the RMSD for the fragments.\n\n        When aligning molecules, the atoms of the two molecules **must** have the\n        same number of atoms from the same species.\n    \"\"\"\n\n    def __init__(self, target: Molecule, threshold: float):\n        \"\"\"Constructor of the matcher object.\n\n        Args:\n            target: a `Molecule` object used as a target during the alignment\n            threshold: value used to match fragments and prune configuration\n        \"\"\"\n        super().__init__(target)\n        self.threshold = threshold\n        self.N = len(target)\n\n    def match(self, p: Molecule):\n        \"\"\"Similar as `KabschMatcher.match` but this method also finds all of the\n        possible atomic orders according to the `threshold`.\n\n        Args:\n            p: a `Molecule` object what will be matched with the target one.\n\n        Returns:\n            Array of the possible matches where the elements are:\n                inds: The indices of atoms\n                U: 3x3 rotation matrix\n                V: Translation vector\n                rmsd: Root mean squared deviation between P and Q\n        \"\"\"\n        out = []\n        for inds in self.permutations(p):\n            p_prime = p.copy()\n            p_prime._sites = [p_prime[i] for i in inds]\n\n            U, V, rmsd = super().match(p_prime)\n\n            out.append((inds, U, V, rmsd))\n\n        return out\n\n    def fit(self, p: Molecule):\n        \"\"\"Order, rotate and transform all of the matched `p` molecule\n        according to the given `threshold`.\n\n        Args:\n            p: a `Molecule` object what will be matched with the target one.\n\n        Returns:\n            Array of the possible matches where the elements are:\n                p_prime: Rotated and translated of the `p` `Molecule` object\n                rmsd: Root-mean-square-deviation between `p_prime` and the `target`\n        \"\"\"\n        out = []\n        for inds in self.permutations(p):\n            p_prime = p.copy()\n            p_prime._sites = [p_prime[i] for i in inds]\n\n            U, V, rmsd = super().match(p_prime)\n\n            # Rotate and translate matrix `p` onto the target molecule.\n            # P' = P * U + V\n            for site in p_prime:\n                site.coords = np.dot(site.coords, U) + V\n\n            out.append((p_prime, rmsd))\n\n        return out\n\n    def permutations(self, p: Molecule):\n        \"\"\"Generates all of possible permutations of atom order according the threshold.\n\n        Args:\n            p: a `Molecule` object what will be matched with the target one.\n\n        Returns:\n            Array of index arrays\n        \"\"\"\n\n        # caching atomic numbers and coordinates\n        p_atoms, q_atoms = p.atomic_numbers, self.target.atomic_numbers\n        p_coords, q_coords = p.cart_coords, self.target.cart_coords\n\n        if sorted(p_atoms) != sorted(q_atoms):\n            raise ValueError(\"The number of the same species aren't matching!\")\n\n        # starting maches (only based on element)\n        partial_matches = [[j] for j in range(self.N) if p_atoms[j] == q_atoms[0]]\n\n        for i in range(1, self.N):\n            # extending the target fragment with then next atom\n            f_coords = q_coords[: i + 1]\n            f_atom = q_atoms[i]\n\n            f_trans = f_coords.mean(axis=0)\n            f_centroid = f_coords - f_trans\n\n            matches = []\n            for indices in partial_matches:\n\n                for j in range(self.N):\n\n                    # skipping if the this index is already matched\n                    if j in indices:\n                        continue\n\n                    # skipping if they are different species\n                    if p_atoms[j] != f_atom:\n                        continue\n\n                    inds = indices + [j]\n                    P = p_coords[inds]\n\n                    # Both sets of coordinates must be translated first, so that\n                    # their centroid coincides with the origin of the coordinate system.\n                    p_trans = P.mean(axis=0)\n                    p_centroid = P - p_trans\n\n                    # The optimal rotation matrix U using Kabsch algorithm\n                    U = self.kabsch(p_centroid, f_centroid)\n\n                    p_prime_centroid = np.dot(p_centroid, U)\n                    rmsd = np.sqrt(np.mean(np.square(p_prime_centroid - f_centroid)))\n\n                    # rejecting if the deviation is too large\n                    if rmsd > self.threshold:\n                        continue\n\n                    logger.debug(\"match - rmsd: {}, inds: {}\".format(rmsd, inds))\n                    matches.append(inds)\n\n            partial_matches = matches\n\n            logger.info(\n                \"number of atom in the fragment: {}, \" \"number of possible matches: {}\".format(i + 1, len(matches))\n            )\n\n        return matches\n", "meta": {"hexsha": "8a1650eb55cb5bf2e512968e72a9be93d601c17e", "size": 47660, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymatgen/analysis/molecule_matcher.py", "max_stars_repo_name": "jacksund/pymatgen", "max_stars_repo_head_hexsha": "c9a7e9810b539d13398219ff06e333682881184e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pymatgen/analysis/molecule_matcher.py", "max_issues_repo_name": "jacksund/pymatgen", "max_issues_repo_head_hexsha": "c9a7e9810b539d13398219ff06e333682881184e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pymatgen/analysis/molecule_matcher.py", "max_forks_repo_name": "jacksund/pymatgen", "max_forks_repo_head_hexsha": "c9a7e9810b539d13398219ff06e333682881184e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1474926254, "max_line_length": 119, "alphanum_fraction": 0.5961812841, "include": true, "reason": "import numpy,from scipy", "num_tokens": 11465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.18614775834807187}}
{"text": "# ------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n# Written by Chunyu Wang (chnuwa@microsoft.com), modified by Yihui He\n# ------------------------------------------------------------------------------\n\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom data.transforms.image import get_affine_transform as get_transform\nfrom data.transforms.image import affine_transform_pts_cuda as do_transform\nfrom core import cfg\n\ndef infer(unary, pairwise, body):\n    \"\"\"\n    Args:\n        unary: [list] unary terms of all joints\n        pairwise: [list] pairwise terms of all edges\n        body: tree structure human body\n    Returns:\n        pose3d_as_cube_idx: 3d pose as cube index\n    \"\"\"\n    root_idx = cfg.KEYPOINT.ROOTIDX\n\n    skeleton = body.skeleton\n    skeleton_sorted_by_level = body.skeleton_sorted_by_level\n\n    states_of_all_joints = {}\n    for node in skeleton_sorted_by_level:\n        children_state = []\n        u = unary[node['idx']].clone()\n        if len(node['children']) == 0:\n            energy = u\n            children_state = [[-1]] * energy.numel()\n        else:\n            for child in node['children']:\n                pw = pairwise[(node['idx'], child)]\n                ce = states_of_all_joints[child]['Energy']\n                ce = ce.expand_as(pw)\n                pwce = torch.mul(pw, ce)\n                max_v, max_i = torch.max(pwce, dim=1)\n                u = torch.mul(u, max_v)\n                children_state.append(max_i.detach().cpu().numpy())\n\n            children_state = np.array(children_state).T\n\n        res = {'Energy': u, 'State': children_state}\n        states_of_all_joints[node['idx']] = res\n\n    pose3d_as_cube_idx = []\n    energy = states_of_all_joints[root_idx]['Energy'].detach().cpu().numpy()\n    cube_idx = np.argmax(energy)\n    pose3d_as_cube_idx.append([root_idx, cube_idx])\n\n    queue = pose3d_as_cube_idx.copy()\n    while queue:\n        joint_idx, cube_idx = queue.pop(0)\n        children_state = states_of_all_joints[joint_idx]['State']\n        state = children_state[cube_idx]\n\n        children_index = skeleton[joint_idx]['children']\n        if -1 not in state:\n            for joint_idx, cube_idx in zip(children_index, state):\n                pose3d_as_cube_idx.append([joint_idx, cube_idx])\n                queue.append([joint_idx, cube_idx])\n\n    pose3d_as_cube_idx.sort()\n    return pose3d_as_cube_idx\n\n\ndef get_loc_from_cube_idx(grid, pose3d_as_cube_idx):\n    \"\"\"\n    Estimate 3d joint locations from cube index.\n\n    Args:\n        grid: a list of grids\n        pose3d_as_cube_idx: a list of tuples (joint_idx, cube_idx)\n    Returns:\n        pose3d: 3d pose\n    \"\"\"\n    njoints = len(pose3d_as_cube_idx)\n    pose3d = torch.zeros(njoints, 3, device=grid[0].device)\n    single_grid = len(grid) == 1\n    for joint_idx, cube_idx in pose3d_as_cube_idx:\n        gridid = 0 if single_grid else joint_idx\n        pose3d[joint_idx] = grid[gridid][cube_idx]\n    return pose3d\n\n\ndef compute_grid(boxSize, boxCenter, nBins, device=None):\n    grid1D = torch.linspace(-boxSize / 2, boxSize / 2, nBins, device=device)\n    gridx, gridy, gridz = torch.meshgrid(\n        grid1D + boxCenter[0],\n        grid1D + boxCenter[1],\n        grid1D + boxCenter[2],\n    )\n    gridx = gridx.contiguous().view(-1, 1)\n    gridy = gridy.contiguous().view(-1, 1)\n    gridz = gridz.contiguous().view(-1, 1)\n    grid = torch.cat([gridx, gridy, gridz], dim=1)\n    return grid\n\n\ndef pdist2(x, y):\n    \"\"\"\n    Compute distance between each pair of row vectors in x and y\n\n    Args:\n        x: tensor of shape n*p\n        y: tensor of shape m*p\n    Returns:\n        dist: tensor of shape n*m\n    \"\"\"\n    p = x.shape[1]\n    n = x.shape[0]\n    m = y.shape[0]\n    xtile = torch.cat([x] * m, dim=1).view(-1, p)\n    ytile = torch.cat([y] * n, dim=0)\n    dist = torch.pairwise_distance(xtile, ytile)\n    return dist.view(n, m)\n\n\ndef compute_pairwise(skeleton, limb_length, grid, tolerance):\n\n    pairwise = {}\n    for node in skeleton:\n        current = node['idx']\n        children = node['children']\n        for child in children:\n            expect_length = limb_length[(current, child)]\n            distance = pdist2(grid[current], grid[child]) + 1e-9\n            pairwise[(current, child)] = (torch.abs(distance - expect_length) <\n                                          tolerance).float()\n    return pairwise\n\n\ndef compute_unary_term(heatmap, grid, bbox2D, cam, imgSize):\n    \"\"\"\n    Args:\n        heatmap: array of size (n * k * h * w)\n                -n: views,      -k: joints\n                -h: height,     -w: width\n\n        grid: k lists of ndarrays of size (nbins * 3)\n                -k: joints; 1 when the grid is shared in PSM\n                -nbins: bins in the grid\n\n        bbox2D: bounding box on which heatmap is computed\n\n    Returns:\n        unary_of_all_joints: a list of ndarray of size nbins\n    \"\"\"\n    device = heatmap.device\n    share_grid = len(grid) == 1\n\n    n, k = heatmap.shape[0], heatmap.shape[1]\n    h, w = heatmap.shape[2], heatmap.shape[3]\n\n    all_unary = {}\n    for v in range(n):\n        center = bbox2D[v]['center']\n        scale = bbox2D[v]['scale']\n        trans = torch.as_tensor(\n            get_transform(center, scale, 0, imgSize),\n            dtype=torch.float,\n            device=device)\n\n        for j in range(k):\n            grid_id = 0 if len(grid) == 1 else j\n            nbins = grid[grid_id].shape[0]\n\n            if (share_grid and j == 0) or not share_grid:\n                xy = grid[grid_id] @ cam[v][:, :-1].t() + cam[v][:, -1]\n                xy = xy[:, :2] / xy[:, -1, None]\n                # xy = cameras.project_pose(, cam[v])\n                xy = do_transform(xy, trans) * torch.tensor(\n                    [w, h], dtype=torch.float, device=device) / torch.tensor(\n                        imgSize, dtype=torch.float, device=device)\n\n                sample_grid = xy / torch.tensor(\n                    [h - 1, w - 1], dtype=torch.float,\n                    device=device) * 2.0 - 1.0\n                sample_grid = sample_grid.view(1, 1, nbins, 2)\n\n            unary_per_view_joint = F.grid_sample(\n                heatmap[v:v + 1, j:j + 1, :, :], sample_grid)\n\n            if j in all_unary:\n                all_unary[j] += unary_per_view_joint\n            else:\n                all_unary[j] = unary_per_view_joint\n\n    all_unary_list = []\n    for j in range(k):\n        all_unary_list.append(all_unary[j].view(1, -1))\n    return all_unary_list\n\n\ndef recursive_infer(initpose, cams, heatmaps, boxes, img_size, heatmap_size,\n                    body, limb_length, grid_size, nbins, tolerance):\n\n    device = heatmaps.device\n    njoints = initpose.shape[0]\n    grids = []\n    for i in range(njoints):\n        grids.append(compute_grid(grid_size, initpose[i], nbins, device=device))\n\n    unary = compute_unary_term(heatmaps, grids, boxes, cams, img_size)\n\n    skeleton = body.skeleton\n    pairwise = compute_pairwise(skeleton, limb_length, grids, tolerance)\n\n    pose3d_cube = infer(unary, pairwise, body)\n    pose3d = get_loc_from_cube_idx(grids, pose3d_cube)\n\n    return pose3d\n\n\ndef rpsm(cams, heatmaps, kw):\n    \"\"\"\n    Args:\n        cams : camera parameters for each view\n        heatmaps: 2d pose heatmaps (n, k, h, w)\n    Returns:\n        pose3d: 3d pose\n    \"\"\"\n\n    # all in this device\n    device = heatmaps.device\n\n    img_size = cfg.DATASETS.IMAGE_SIZE\n    map_size = cfg.KEYPOINT.HEATMAP_SIZE\n    grd_size = cfg.PICT_STRUCT.GRID_SIZE\n    fst_nbins = cfg.PICT_STRUCT.FIRST_NBINS\n    rec_nbins = cfg.PICT_STRUCT.RECUR_NBINS\n    rec_depth = cfg.PICT_STRUCT.RECUR_DEPTH\n    tolerance = cfg.PICT_STRUCT.LIMB_LENGTH_TOLERANCE\n\n    grid = compute_grid(grd_size, kw['center'], fst_nbins, device=device)\n    unary = compute_unary_term(heatmaps, [grid], kw['boxes'], cams, img_size)\n\n    pose3d_as_cube_idx = infer(unary, kw['pairwise'], kw['body'])\n    pose3d = get_loc_from_cube_idx([grid], pose3d_as_cube_idx)\n    cur_grd_size = grd_size / fst_nbins\n    for i in range(rec_depth):\n        pose3d = recursive_infer(pose3d, cams, heatmaps, kw['boxes'], img_size,\n                                 map_size, kw['body'], kw['limb_length'],\n                                 cur_grd_size, rec_nbins, tolerance)\n        cur_grd_size = cur_grd_size / rec_nbins\n\n    return pose3d\n", "meta": {"hexsha": "2ceaefd13c94763c6def6c9eb742489bea061797", "size": 8425, "ext": "py", "lang": "Python", "max_stars_repo_path": "modeling/pictorial_cuda.py", "max_stars_repo_name": "yihui-he2020/epipolar-transformers", "max_stars_repo_head_hexsha": "6824f4345b2998500fbacd0f4e30f67f8e3da7b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 360, "max_stars_repo_stars_event_min_datetime": "2020-03-30T07:15:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T14:08:04.000Z", "max_issues_repo_path": "modeling/pictorial_cuda.py", "max_issues_repo_name": "yihui-he2020/epipolar-transformers", "max_issues_repo_head_hexsha": "6824f4345b2998500fbacd0f4e30f67f8e3da7b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-05-12T11:12:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-31T05:49:10.000Z", "max_forks_repo_path": "modeling/pictorial_cuda.py", "max_forks_repo_name": "yihui-he2020/epipolar-transformers", "max_forks_repo_head_hexsha": "6824f4345b2998500fbacd0f4e30f67f8e3da7b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 38, "max_forks_repo_forks_event_min_datetime": "2020-05-12T05:33:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T22:27:45.000Z", "avg_line_length": 33.0392156863, "max_line_length": 80, "alphanum_fraction": 0.591810089, "include": true, "reason": "import numpy", "num_tokens": 2202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.18614775834807187}}
{"text": "# Motor class file\n# Author : Jules Triomphe\n# Date : 5 May 2019\n# EPFL Rocket Team, 1015 Lausanne, Switzerland\n\nfrom scipy.interpolate import interp1d\nfrom scipy.integrate import simps\nimport numpy as np\nimport bisect\n\n\nclass Motor:\n    \"\"\"\n    Motor object\n    ============\n\n    Motor object defined by it's file path and the source .eng document found on www.thrustcurve.org.\n\n    Attributes\n    ----------\n\n    diameter : float\n        Motor diameter (with casing), in [m].\n\n    length : float\n        Motor length (with casing), in [m].\n\n    delay_type : str\n        Time after burnout when the ejection charge ignites.\n        Classifications :\n            - Number : Time in seconds\n            - T : Tiny\n            - M : Medium (~10 s)\n            - P : Plugged ; no ejection charge\n            - N/A or not listed : not adjustable\n\n    propellant_mass : float\n        Propellant mass, in [kg].\n        Value is constant.\n        To get the actual mass of the motor, use the get_mass() method.\n\n    total_mass : float\n        Total mass, in [kg].\n\n    casing_mass : float\n        Casing mass, in [kg].\n        Value is constant.\n        Equal to the difference between the total mass and the propellant mass.\n\n    thrust_pairs : list of str\n        Table of the sampled thrust at the corresponding time after ignition.\n\n    thrust_time : list of float\n        First column of thrust_pairs listing the time of the provided thrust samples.\n        A 0 value is added at the beginning to provide a range from ignition to burnout.\n\n    thrust_force : list of float\n        Second column of thrust_pairs listing the thrust at the provided sampling times.\n        A 0 value is added at the beginning to provide a data set from ignition to burnout.\n\n    thrust_function : interp1d function\n        Handle to calculate the thrust at a given time t [s] between ignition at t=0 and burnout at t=burn_time.\n        Should be used as thrust_function(t).\n\n    burn_time : float\n        Motor burn time given by the last sampling time of the motor data sheet, in [s].\n\n    total_impulse : float64\n        Total impulse of the motor given by a Simpson interpolation of the samples, in [N.s].\n\n    thrust_to_mass : float64\n        Thrust to mass ratio of the motor, in [m.s^-2].\n        Used to calculate the mass during burn.\n\n\n    Constructor\n    -----------\n\n    __init__(motor_file_path)\n        Initializes a motor with its physical and mathematical characteristics from a given motor data sheet path.\n        The motor file can be a .txt or a .eng file.\n\n\n    Methods\n    -------\n\n    get_thrust(t) : float\n        Returns the thrust of the motor at time t [s], in [N].\n\n    get_propellant_mass(t) : float\n        Returns the propellant mass at time t [s], in [kg].\n\n    get_total_mass(t) : float\n        Returns the total mass of the motor, casing included, in [kg].\n\n    TODO: Add get_dmass_dt description\n\n    get_cg() : float\n        Returns the center of mass of the motor, in [m].\n        TODO: Rethink the output of the method.\n\n    get_propellant_inertia(t) : float\n        Returns the propellant's inertia at time t [s], in [kg.m^2].\n\n    get_casing_inertia() : float\n        Returns the casing's inertia, in [kg.m^2].\n\n    get_motor_inertia(t, d) : float\n        Returns the motor's inertia with respect to a point at a distance d [m], in [kg.m^2].\n        d is in [m].\n\n    get_total_inertia(t, d) : float\n        Returns the total inertia of the motor with respect to a point at a distance d at time t [s], in [kg.m^2].\n        d is in [m].\n\n    \"\"\"\n\n    # --------------------\n    # CONSTRUCTOR\n    # --------------------\n\n    def __init__(self, motor_file_path: str):\n        with open(motor_file_path, 'r') as motor_data:\n            motor_data.readline()\n            general_data = motor_data.readline().split()\n\n            self.diameter = float(general_data[1]) / 1000\n            self.length = float(general_data[2]) / 1000\n            self.delay_type = general_data[3]\n\n            self.propellant_mass = float(general_data[4])\n            self.total_mass = float(general_data[5])\n            self.casing_mass = self.total_mass - self.propellant_mass\n\n            # First value is thrust time\n            # Second value is thrust force\n            self.thrust_pairs = [line.split() for line in motor_data]\n            self.thrust_time = [float(thrust[0]) for thrust in self.thrust_pairs]\n            self.thrust_force = [float(thrust[1]) for thrust in self.thrust_pairs]\n            # Correct to add (0,0) point\n            self.thrust_time.insert(0, 0)\n            self.thrust_force.insert(0, 0)\n\n        # Linear interpolation of the thrust force samples\n        self.thrust_function = interp1d(self.thrust_time, self.thrust_force)\n\n        self.burn_time = self.thrust_time[-1]\n\n        # Simpson integration of the thrust curve\n        self.total_impulse = np.trapz(self.thrust_force, self.thrust_time)\n        # self.total_impulse = simps(sample_thrust, sample_time, even='avg')\n\n        self.thrust_to_mass = self.propellant_mass / self.total_impulse\n\n        self.motor_fac = 1\n\n    # --------------------\n    # METHODS\n    # --------------------\n\n    def set_motor_fac(self, motor_fac: float):\n        self.motor_fac = motor_fac\n\n    def get_motor_fac(self):\n        return self.motor_fac\n\n    def get_thrust(self, t: float) -> float:\n        \"\"\"\n        Computes the current thrust, in [N].\n        It is 0 if outside of burn time.\n\n        :param t: time, in [s]\n        :return: current thrust force, in [N]\n        \"\"\"\n        if 0 <= t <= self.burn_time:\n            return self.thrust_function(t)\n        else:\n            return 0\n\n    def get_burnt_propellant_mass(self, t: float) -> float:\n        \"\"\"\n        Computes the current burnt propellant mass, in [kg].\n\n        :param t: time, in [s]\n        :return: current burnt propellant mass, in [kg]\n        \"\"\"\n        if t < 0:\n            return 0\n        elif 0 <= t <= self.burn_time:\n            thrust_t = self.thrust_time[:bisect.bisect_right(self.thrust_time, t)]\n            thrust_f = self.thrust_force[:len(thrust_t)]\n            if t not in self.thrust_time:\n                thrust_t.append(t)\n                thrust_f.append(self.thrust_function(t).tolist())\n            current_impulse = np.trapz(thrust_f, thrust_t)\n            # Test to simulate exact Matlab code in 1D\n            # Yields higher results\n            time = np.linspace(0, t, 500)\n            current_impulse = np.trapz(self.thrust_function(time), time)\n            # current_impulse = simps(thrust_f, thrust_t, even='avg')\n            return self.thrust_to_mass * current_impulse\n        else:\n            return self.propellant_mass\n\n    def get_propellant_mass(self, t: float) -> float:\n        \"\"\"\n        Computes the current propellant mass, in [kg].\n\n        :param t: time, in [s]\n        :return: current propellant mass, in [kg]\n        \"\"\"\n        if t < 0:\n            return self.propellant_mass\n        elif 0 <= t <= self.burn_time:\n            thrust_t = self.thrust_time[:bisect.bisect_right(self.thrust_time, t)]\n            thrust_f = self.thrust_force[:len(thrust_t)]\n            if 0:  # t not in self.thrust_time: # Yields a higher altitude than 0\n                thrust_t.append(t)\n                thrust_f.append(self.thrust_function(t).tolist())\n            current_impulse = np.trapz(thrust_f, thrust_t)\n            # current_impulse = simps(thrust_f, thrust_t, even='avg')\n            return self.propellant_mass - self.thrust_to_mass * current_impulse\n        else:\n            return 0\n\n    def get_total_mass(self, t: float) -> float:\n        \"\"\"\n        Computes the current mass of the motor (casing included), in [kg].\n\n        :param t: time, in [s]\n        :return: current motor mass, in [kg]\n        \"\"\"\n        return self.total_mass - self.get_burnt_propellant_mass(t)\n\n    def get_dmass_dt(self, t: float) -> float:\n        \"\"\"\n        Computes the current change in mass of the motor over time, in [kg.s^-1].\n\n        :param t: time, in [s]\n        :return: current mass change over time, in [kg.s^-1]\n        \"\"\"\n        return self.thrust_to_mass * self.get_thrust(t)\n\n    @property\n    def get_cg(self) -> float:\n        \"\"\"\n        Computes the motor's center of mass (CG), in [m].\n\n        :return: distance of the CG to the top of the motor, in [m]\n        \"\"\"\n        return self.length / 2\n\n    def get_propellant_inertia(self, t: float) -> float:\n        \"\"\"\n        Computes the propellant's inertia, in [kg.m^2].\n\n        :param t: time, in [s]\n        :return: propellant inertia, in [kg.m^2]\n        \"\"\"\n        # Internal grain radius (stays constant)\n        r_i = 0.005\n        # External grain radius\n        r_e = self.diameter / 2\n\n        # Ix inertia : inertia along yaw/pitch axis.\n        # We call it \"longitudinal\" but it is a misuse of the term.\n        i_l_grain = self.get_propellant_mass(t) * (self.length ** 2 / 12 + (r_e ** 2 + r_i ** 2) / 4)\n        return i_l_grain\n\n    def get_casing_inertia(self) -> float:\n        \"\"\"\n        Computes the casing's inertia, in [kg.m^2].\n\n        :return: casing inertia, in [kg.m^2]\n        \"\"\"\n        # External grain radius\n        r_e = self.diameter / 2\n        # We consider an infinitesimal thickness for the casing.\n        # Hence r_e == r_i and (r_e**2 + r_i**2)/4 becomes r_e**2/2.\n        i_l_casing = self.casing_mass * (self.length ** 2 / 12 + r_e ** 2 / 2)\n        return i_l_casing\n\n    def get_motor_inertia(self, t: float, d: float) -> float:\n        \"\"\"\n        Computes the motor's inertia with respect to a point at a distance d [m] (e.g. rocket center of mass),\n        in [kg.m^2].\n\n        :param t: time, in [s]\n        :param d: distance, in [m]\n        :return: motor inertia from the distant point, in [kg.m^2]\n        \"\"\"\n        return self.get_total_mass(t) * d\n\n    def get_total_inertia(self, t: float, d: float) -> float:\n        \"\"\"\n        Computes the total motor inertia with respect to a point at a distance d [m] (e.g. rocket center of mass),\n        in [kg.m^2].\n\n        :param t: time, in [s]\n        :param d: distance, in [m]\n        :return: motor total inertia, in [kg.m^2]\n        \"\"\"\n        return self.get_propellant_inertia(t) + self.get_casing_inertia() + self.get_motor_inertia(t, d)\n\n    def get_thrust_time(self):\n        return self.thrust_time\n\n    def get_thrust_force(self):\n        return self.thrust_force\n\n\nif __name__ == '__main__':\n    # Location of current motor test file\n    CS_M1800 = Motor('../Motors/AT_L850.eng')\n    # get_thrust method test\n    print(CS_M1800.get_thrust(4.5))\n    # get_mass method tests\n    print(CS_M1800.get_total_mass(CS_M1800.burn_time))\n    print(CS_M1800.get_total_mass(10))\n    print(CS_M1800.total_impulse)\n    print(CS_M1800.thrust_to_mass ** -1 * CS_M1800.get_burnt_propellant_mass(CS_M1800.burn_time))\n    print(CS_M1800.get_burnt_propellant_mass(CS_M1800.burn_time))\n    print(CS_M1800.propellant_mass)\n", "meta": {"hexsha": "4045fa3a67b2657ef3a61f708bac9782d02f309d", "size": 10989, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/aero/Rocket/Motor.py", "max_stars_repo_name": "EPFLRocketTeam/real_time_simulator", "max_stars_repo_head_hexsha": "ec03a3baced59ea8cf4467ac8c22e0378d4268e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-03T17:25:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T00:26:25.000Z", "max_issues_repo_path": "scripts/aero/Rocket/Motor.py", "max_issues_repo_name": "EPFLRocketTeam/real_time_simulator", "max_issues_repo_head_hexsha": "ec03a3baced59ea8cf4467ac8c22e0378d4268e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-03-29T21:07:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:08:16.000Z", "max_forks_repo_path": "scripts/aero/Rocket/Motor.py", "max_forks_repo_name": "EPFLRocketTeam/real_time_simulator", "max_forks_repo_head_hexsha": "ec03a3baced59ea8cf4467ac8c22e0378d4268e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-18T05:24:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T05:24:15.000Z", "avg_line_length": 33.9166666667, "max_line_length": 114, "alphanum_fraction": 0.6062426062, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.1861477403095464}}
{"text": "import numpy as np\nfrom sklearn.linear_model import Ridge\nimport matplotlib.pyplot as plt\n\nglobal_proton_dict = {'H': 1, 'He': 2, 'Li': 3, 'Be': 4, 'B': 5, 'C': 6, 'N': 7, 'O': 8, 'F': 9, 'Ne': 10, 'Na': 11,\n                      'Mg': 12, 'Al': 13, 'Si': 14, 'P': 15, 'S': 16, 'Cl': 17, 'Ar': 18, 'K': 19, 'Ca': 20,\n                      'Sc': 21, 'Ti': 22, 'V': 23, 'Cr': 24, 'Mn': 25, 'Fe': 26, 'Co': 27, 'Ni': 28, 'Cu': 29,\n                      'Zn': 30, 'Ga': 31, 'Ge': 32, 'As': 33, 'Se': 34, 'Br': 35, 'Kr': 36, 'Rb': 37, 'Sr': 38,\n                      'Y': 39, 'Zr': 40, 'Nb': 41, 'Mo': 42, 'Tc': 43, 'Ru': 44, 'Rh': 45, 'Pd': 46, 'Ag': 47,\n                      'Cd': 48, 'In': 49, 'Sn': 50, 'Sb': 51, 'Te': 52, 'I': 53, 'Xe': 54, 'Cs': 55, 'Ba': 56,\n                      'La': 57, 'Ce': 58, 'Pr': 59, 'Nd': 60, 'Pm': 61, 'Sm': 62, 'Eu': 63, 'Gd': 64, 'Tb': 65,\n                      'Dy': 66, 'Ho': 67, 'Er': 68, 'Tm': 69, 'Yb': 70, 'Lu': 71, 'Hf': 72, 'Ta': 73, 'W': 74,\n                      'Re': 75, 'Os': 76, 'Ir': 77, 'Pt': 78, 'Au': 79, 'Hg': 80, 'Tl': 81, 'Pb': 82, 'Bi': 83,\n                      'Po': 84, 'At': 85, 'Rn': 86, 'Fr': 87, 'Ra': 88, 'Ac': 89, 'Th': 90, 'Pa': 91, 'U': 92,\n                      'Np': 93, 'Pu': 94, 'Am': 95, 'Cm': 96, 'Bk': 97, 'Cf': 98, 'Es': 99, 'Fm': 100, 'Md': 101,\n                      'No': 102, 'Lr': 103, 'Rf': 104, 'Db': 105, 'Sg': 106, 'Bh': 107, 'Hs': 108, 'Mt': 109,\n                      'Ds': 110, 'Rg': 111, 'Cn': 112, 'Nh': 113, 'Fl': 114, 'Mc': 115, 'Lv': 116, 'Ts': 117,\n                      'Og': 118, 'Uue': 119}\ninverse_global_proton_dict = {value: key for key, value in global_proton_dict.items()}\n\n\ndef get_connectivity_from_inverse_distance_matrix(inv_dist_mat, protons, radii_dict=None, k1=16.0, k2=4.0 / 3.0,\n                                                  cutoff=0.85, force_bonds=True):\n    r\"\"\"Get connectivity table from inverse distance matrix defined at last dimensions `(..., N, N)` and\n    corresponding bond-radii. Keeps shape with `(..., N, N)`.\n    Covalent radii, from Pyykko and Atsumi, Chem. Eur. J. 15, 2009, 188-197. \n    Values for metals decreased by 10% according to Robert Paton's Sterimol implementation. \n    Partially based on code from Robert Paton's Sterimol script, which based this part on Grimme's D3 code.\n    Vectorized version of the original code for numpy arrays that take atomic numbers as input.\n    \n    Args:\n        inv_dist_mat (np.ndarray): Inverse distance matrix defined at last dimensions `(..., N, N)`\n            distances must be in Angstrom not in Bohr.\n        protons (np.ndarray): An array of atomic numbers matching the inv_dist_mat `(..., N)`,\n            for which the radii are to be computed.\n        radii_dict (np.ndarray): Covalent radii for each element. If ``None``, stored values are used.\n            Otherwise expected numpy array with covalent bonding radii.\n            Example: ``np.array([0, 0.34, 0.46, 1.2, ...])`` for atomic number ``np.array([0, 1, 2, ...])``\n            that would match ``[None, 'H', 'He', 'Li', ...]``.\n        k1 (float): K1-value. Defaults to 16\n        k2 (float): K2-value. Defaults to 4.0/3.0\n        cutoff (float): Cutoff value to set values to Zero (no bond). Defaults to 0.85.\n        force_bonds (bool): Whether to force at least one bond in the bond table per atom. Default is True.\n        \n    Returns:\n        np.ndarray: Connectivity table with 1 for chemical bond and zero otherwise of shape `(..., N, N)`.\n    \"\"\"\n    # Dictionary of bond radii\n    proton_radii_dict = np.array(\n        [0, 0.34, 0.46, 1.2, 0.94, 0.77, 0.75, 0.71, 0.63, 0.64, 0.67, 1.4, 1.25, 1.13, 1.04, 1.1, 1.02, 0.99, 0.96,\n         1.76, 1.54, 1.33, 1.22, 1.21, 1.1, 1.07, 1.04, 1.0, 0.99, 1.01, 1.09, 1.12, 1.09, 1.15, 1.1, 1.14, 1.17, 1.89,\n         1.67, 1.47, 1.39, 1.32, 1.24, 1.15, 1.13, 1.13, 1.19, 1.15, 1.23, 1.28, 1.26, 1.26, 1.23, 1.32, 1.31, 2.09,\n         1.76, 1.62, 1.47, 1.58, 1.57, 1.56, 1.55, 1.51, 1.52, 1.51, 1.5, 1.49, 1.49, 1.48, 1.53, 1.46, 1.37, 1.31,\n         1.23, 1.18, 1.16, 1.11, 1.12, 1.13, 1.32, 1.3, 1.3, 1.36, 1.31, 1.38, 1.42, 2.01, 1.81, 1.67, 1.58, 1.52, 1.53,\n         1.54, 1.55])\n    if radii_dict is None:\n        radii_dict = proton_radii_dict  # index matches atom number\n    # Get Radii\n    protons = np.array(protons, dtype=\"int\")\n    radii = radii_dict[protons]\n    # Calculate\n    shape_rad = radii.shape\n    r1 = np.expand_dims(radii, axis=len(shape_rad) - 1)\n    r2 = np.expand_dims(radii, axis=len(shape_rad))\n    r_mat = r1 + r2\n    r_mat = k2 * r_mat\n    rr = r_mat * inv_dist_mat\n    damp = (1.0 + np.exp(-k1 * (rr - 1.0)))\n    damp = 1.0 / damp\n    if force_bonds:  # Have at least one bond\n        max_vals = np.expand_dims(np.argmax(damp, axis=-1), axis=-1)\n        np.put_along_axis(damp, max_vals, 1, axis=-1)\n        # To make it symmetric transpose last two axis\n        damp = np.swapaxes(damp, -2, -1)\n        np.put_along_axis(damp, max_vals, 1, axis=-1)\n        damp = np.swapaxes(damp, -2, -1)\n    damp[damp < cutoff] = 0\n    bond_tab = np.round(damp)\n    return bond_tab\n\n\nclass ExtensiveMolecularScaler:\n    \"\"\"Scaler for extensive properties like energy to remove a simple linear behaviour with additive atom\n    contributions. Interface is designed after scikit-learn standard scaler. Internally Ridge regression ist used.\n    Only the atomic number is used as extensive scaler. This could be further improved by also taking bonds and\n    interactions into account, e.g. as energy contribution.\n\n    \"\"\"\n\n    max_atomic_number = 95\n\n    def __init__(self, alpha: float = 1e-9, fit_intercept: bool = False, **kwargs):\n        r\"\"\"Initialize scaler with parameters directly passed to scikit-learns :obj:`Ridge()`.\n\n        Args:\n            alpha (float): Regularization parameter for regression.\n            fit_intercept (bool): Whether to allow a constant offset per target.\n            kwargs: Additional arguments passed to :obj:`Ridge()`.\n        \"\"\"\n\n        self.ridge = Ridge(alpha=alpha, fit_intercept=fit_intercept, **kwargs)\n\n        self._fit_atom_selection_mask = None\n        self._fit_atom_selection = None\n        self._fit_coef = None\n        self._fit_intercept = None\n        self.scale_ = None\n\n    def fit(self, atomic_number, molecular_property, sample_weight=None):\n        \"\"\"Fit atomic number to the molecular properties.\n\n        Args:\n            atomic_number (list): List of array of atomic numbers. Shape is `(n_samples, <#atoms>)`.\n            molecular_property (np.ndarray): Array of atomic properties of shape `(n_samples, n_properties)`.\n            sample_weight: Sample weights `(n_samples,)` directly passed to :obj:`Ridge()`. Default is None.\n\n        Returns:\n            self\n        \"\"\"\n        if len(atomic_number) != len(molecular_property):\n            raise ValueError(\n                \"`ExtensiveMolecularScaler` different input shape {0} vs. {1}\".format(\n                    len(atomic_number), len(molecular_property))\n            )\n\n        unique_number = [np.unique(x, return_counts=True) for x in atomic_number]\n        all_unique = np.unique(np.concatenate([x[0] for x in unique_number], axis=0))\n        self._fit_atom_selection = all_unique\n        atom_mask = np.zeros(self.max_atomic_number, dtype=\"bool\")\n        atom_mask[all_unique] = True\n        self._fit_atom_selection_mask = atom_mask\n        total_number = []\n        for unique_per_mol, num_unique in unique_number:\n            array_atoms = np.zeros(self.max_atomic_number)\n            array_atoms[unique_per_mol] = num_unique\n            positives = array_atoms[atom_mask]\n            total_number.append(positives)\n        total_number = np.array(total_number)\n        self.ridge.fit(total_number, molecular_property, sample_weight=sample_weight)\n        self._fit_coef = self.ridge.coef_\n        self._fit_intercept = self.ridge.intercept_\n        diff = molecular_property - self.ridge.predict(total_number)\n        self.scale_ = np.std(diff, axis=0, keepdims=True)\n        return self\n\n    def predict(self, atomic_number):\n        \"\"\"Predict the offset form atomic numbers. Requires :obj:`fit()` called previously.\n\n        Args:\n            atomic_number (list): List of array of atomic numbers. Shape is `(n_samples, <#atoms>)`.\n\n        Returns:\n            np.ndarray: Offset of atomic properties fitted previously. Shape is `(n_samples, n_properties)`.\n        \"\"\"\n        if self._fit_atom_selection_mask is None:\n            raise ValueError(\"ERROR:kgcnn: `ExtensiveMolecularScaler` has not been fitted yet. Can not predict.\")\n        unique_number = [np.unique(x, return_counts=True) for x in atomic_number]\n        total_number = []\n        for unique_per_mol, num_unique in unique_number:\n            array_atoms = np.zeros(self.max_atomic_number)\n            array_atoms[unique_per_mol] = num_unique\n            positives = array_atoms[self._fit_atom_selection_mask]\n            if np.sum(positives) != np.sum(num_unique):\n                print(\"`ExtensiveMolecularScaler` got unknown atom species in transform.\")\n            total_number.append(positives)\n        total_number = np.array(total_number)\n        offset = self.ridge.predict(total_number)\n        return offset\n\n    def _plot_predict(self, atomic_number, molecular_property):\n        \"\"\"Debug function to check prediction.\"\"\"\n        if len(molecular_property.shape) <= 1:\n            molecular_property = np.expand_dims(molecular_property, axis=-1)\n        predict_prop = self.predict(atomic_number)\n        if len(predict_prop.shape) <= 1:\n            predict_prop = np.expand_dims(predict_prop, axis=-1)\n        mae = np.mean(np.abs(molecular_property - predict_prop), axis=0)\n        plt.figure()\n        for i in range(predict_prop.shape[-1]):\n            plt.scatter(predict_prop[:, i], molecular_property[:, i], alpha=0.3,\n                        label=\"Pos: \" + str(i) + \" MAE: {0:0.4f} \".format(mae[i]))\n        plt.plot(np.arange(np.amin(molecular_property), np.amax(molecular_property), 0.05),\n                 np.arange(np.amin(molecular_property), np.amax(molecular_property), 0.05), color='red')\n        plt.xlabel('Fitted')\n        plt.ylabel('Actual')\n        plt.legend(loc='upper left', fontsize='x-small')\n        plt.show()\n\n    def transform(self, atomic_number, molecular_property):\n        \"\"\"Transform any atomic number list with matching properties based on previous fit. Also std-scaled.\n\n        Args:\n            atomic_number (list): List of array of atomic numbers. Shape is `(n_samples, <#atoms>)`.\n            molecular_property (np.ndarray): Array of atomic properties of shape `(n_samples, n_properties)`.\n\n        Returns:\n            np.ndarray: Transformed atomic properties fitted. Shape is `(n_samples, n_properties)`.\n        \"\"\"\n        return (molecular_property - self.predict(atomic_number)) / self.scale_\n\n    def fit_transform(self, atomic_number, molecular_property, sample_weight=None):\n        \"\"\"Combine fit and transform methods in one call.\n\n        Args:\n            atomic_number (list): List of array of atomic numbers. Shape is `(n_samples, <#atoms>)`.\n            molecular_property (np.ndarray): Array of atomic properties of shape `(n_samples, n_properties)`.\n            sample_weight: Sample weights `(n_samples,)` directly passed to :obj:`Ridge()`. Default is None.\n\n        Returns:\n            np.ndarray: Transformed atomic properties fitted. Shape is `(n_samples, n_properties)`.\n        \"\"\"\n        self.fit(atomic_number, molecular_property, sample_weight)\n        return self.transform(atomic_number, molecular_property)\n\n    def inverse_transform(self, atomic_number, molecular_property):\n        \"\"\"Reverse the transform method to original properties without offset and scaled to original units.\n\n        Args:\n            atomic_number (list): List of array of atomic numbers. Shape is `(n_samples, <#atoms>)`.\n            molecular_property (np.ndarray): Array of atomic properties of shape `(n_samples, n_properties)`\n\n        Returns:\n            np.ndarray: Original atomic properties. Shape is `(n_samples, n_properties)`.\n        \"\"\"\n        return molecular_property * self.scale_ + self.predict(atomic_number)\n", "meta": {"hexsha": "9c67908d50e5bb2f5056fb7ab401cac4eda7dfdd", "size": 12221, "ext": "py", "lang": "Python", "max_stars_repo_path": "kgcnn/mol/methods.py", "max_stars_repo_name": "aimat-lab/gcnn_keras", "max_stars_repo_head_hexsha": "69f6cf7fbcc056c75a77ae416d734adcdaa1d218", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47, "max_stars_repo_stars_event_min_datetime": "2021-03-10T10:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T00:53:40.000Z", "max_issues_repo_path": "kgcnn/mol/methods.py", "max_issues_repo_name": "aimat-lab/gcnn_keras", "max_issues_repo_head_hexsha": "69f6cf7fbcc056c75a77ae416d734adcdaa1d218", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2021-05-06T15:06:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T13:06:16.000Z", "max_forks_repo_path": "kgcnn/mol/methods.py", "max_forks_repo_name": "aimat-lab/gcnn_keras", "max_forks_repo_head_hexsha": "69f6cf7fbcc056c75a77ae416d734adcdaa1d218", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2021-04-05T02:14:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T03:25:52.000Z", "avg_line_length": 54.0752212389, "max_line_length": 120, "alphanum_fraction": 0.6051059651, "include": true, "reason": "import numpy", "num_tokens": 3613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3311197462295936, "lm_q1q2_score": 0.18614774030954637}}
{"text": "#Snake Tutorial Python\nimport dwave\nfrom pyqubo import Binary, solve_qubo\nfrom dwave.system import DWaveSampler, EmbeddingComposite\nfrom dimod import ExactSolver\nfrom pyqubo import Binary\nimport networkx as nx\n#import dwave_networkx as dnx\nimport math\nimport random\nimport pygame\nimport tkinter as tk\nimport dimod\nfrom tkinter import messagebox\nimport pickle\nimport json\nfrom dimod.serialization.json import DimodEncoder, DimodDecoder\n\nGRID_SIZE = 3\nNON_SNAKE_WEIGHTS=1\nSNAKE_WEIGHTS=100\nCHI = 3\nLAMBDA = 10\nMU = 2\nGAMMA = 10\n\nclass cube(object):\n    rows = 20\n    w = 500\n    def __init__(self,start,dirnx=1,dirny=0,color=(0,255,0)):\n        self.pos = start\n        self.dirnx = 1\n        self.dirny = 0\n        self.color = color\n\n\n    def move(self, dirnx, dirny):\n        self.dirnx = dirnx\n        self.dirny = dirny\n        self.pos = (self.pos[0] + self.dirnx, self.pos[1] + self.dirny)\n\n    def draw(self, surface, eyes=False):\n        dis = self.w // self.rows\n        i = self.pos[0]\n        j = self.pos[1]\n\n        pygame.draw.rect(surface, self.color, (i*dis+1,j*dis+1, dis-2, dis-2))\n        if eyes:\n            centre = dis//2\n            radius = 3\n            circleMiddle = (i*dis+centre-radius,j*dis+8)\n            circleMiddle2 = (i*dis + dis -radius*2, j*dis+8)\n            pygame.draw.circle(surface, (0,0,0), circleMiddle, radius)\n            pygame.draw.circle(surface, (0,0,0), circleMiddle2, radius)\n\n\n\nclass snake(object):\n    body = []\n    turns = {}\n    def __init__(self, color, pos):\n        self.color = color\n        self.head = cube(pos)\n        self.body.append(self.head)\n        self.dirnx = 0\n        self.dirny = 1\n\n    def move(self):\n        # for event in pygame.event.get():\n        #     if event.type == pygame.QUIT:\n        #         pygame.quit()\n\n        #     keys = pygame.key.get_pressed()\n\n            # for key in keys:\n            #     if keys[pygame.K_LEFT]:\n            #         self.dirnx = -1\n            #         self.dirny = 0\n            #         self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]\n\n            #     elif keys[pygame.K_RIGHT]:\n            #         self.dirnx = 1\n            #         self.dirny = 0\n            #         self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]\n\n            #     elif keys[pygame.K_UP]:\n            #         self.dirnx = 0\n            #         self.dirny = -1\n            #         self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]\n\n            #     elif keys[pygame.K_DOWN]:\n            #         self.dirnx = 0\n            #         self.dirny = 1\n\n        self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]\n        for i, c in enumerate(self.body):\n            p = c.pos[:]\n            if p in self.turns:\n                turn = self.turns[p]\n                c.move(turn[0],turn[1])\n                if i == len(self.body)-1:\n                    self.turns.pop(p)\n            else:\n                if c.dirnx == -1 and c.pos[0] <= 0: c.pos = (c.rows-1, c.pos[1])\n                elif c.dirnx == 1 and c.pos[0] >= c.rows-1: c.pos = (0,c.pos[1])\n                elif c.dirny == 1 and c.pos[1] >= c.rows-1: c.pos = (c.pos[0], 0)\n                elif c.dirny == -1 and c.pos[1] <= 0: c.pos = (c.pos[0],c.rows-1)\n                else: c.move(c.dirnx,c.dirny)\n\n\n    def move_via_dwave():\n        # 1: Embed Graph\n        # 2: Create Qubo\n        # 3: Pass Qubo to Dwave\n        # 4: Unpack qubo to graph\n        # 5:\n        pass\n\n    def get_snake_unconnected_graph(self):\n        # G = nx.Graph()\n        # for i in range(grid_size):\n        #     for j in range(grid_size):\n        #         G.add_node((i,j))\n        G = nx.grid_2d_graph(GRID_SIZE, GRID_SIZE, periodic =False)\n        nx.set_edge_attributes(G, NON_SNAKE_WEIGHTS, \"weight\" )\n        return G\n\n    def snake_to_graph(self):\n        G = s.get_snake_unconnected_graph()\n        prev_cube_pos = False\n        for cube in self.body:\n            print(f'snake body cube: {cube.pos}')\n            if prev_cube_pos:\n                G.add_edge(cube.pos, prev_cube_pos, weight=SNAKE_WEIGHTS)\n            prev_cube_pos = cube.pos\n        #nx.bipartite_layout(G,G.nodes())\n        #nx.draw(G)\n        #print(f'xs: {G.nodes()}')\n\n        return G\n\n\n    def graph_to_moves(self, path_graph):\n        num_moves = len(path_graph.edges)\n        moves = []\n        head_pos = self.body[0].pos\n        prev_head_poses = []\n        prev_head_poses.append(head_pos)\n        run_flag = True\n        print(f'all edges: {path_graph.edges()}')\n        for i in range(len(path_graph.edges)):\n            for edges in path_graph.edges(head_pos):\n                print(f'head_pos {head_pos}')\n                print(f'edges: {edges}')\n                for edge in edges:\n                    print(f'loop edge: {edge}')\n                    if edge not in prev_head_poses:\n                        print(\"AS\")\n                        prev_head_poses.append(head_pos)\n                        moves.append((head_pos[0]-edge[0], head_pos[1]-edge[1]))\n                        head_pos = edge\n                        break\n        print(moves)\n\n        # while run_flag:\n        #     if len(path_graph.edges(head_pos)) == 1 and head_pos not in prev_head_poses:\n        #         run_flag = False\n        #     for edges in path_graph.edges(head_pos):\n        #         for edge in edges:\n        #             if edge not in prev_head_poses:\n        #                 print(f'len:{len(path_graph.edges(head_pos))}  head: {head_pos} edge:{edge}')\n        #                 moves = (head_pos[0]-edge[0], head_pos[1]-edge[1])\n        #                 head_pos = edge\n\n        #                 break\n        # print(f'moves: {moves}')\n\n\n\n    def reset(self, pos):\n        self.head = cube(pos)\n        self.body = []\n        self.body.append(self.head)\n        self.turns = {}\n        self.dirnx = 0\n        self.dirny = 1\n\n\n    def addCube(self):\n        tail = self.body[-1]\n        dx, dy = tail.dirnx, tail.dirny\n\n        if dx == 1 and dy == 0:\n            self.body.append(cube((tail.pos[0]-1,tail.pos[1])))\n        elif dx == -1 and dy == 0:\n            self.body.append(cube((tail.pos[0]+1,tail.pos[1])))\n        elif dx == 0 and dy == 1:\n            self.body.append(cube((tail.pos[0],tail.pos[1]-1)))\n        elif dx == 0 and dy == -1:\n            self.body.append(cube((tail.pos[0],tail.pos[1]+1)))\n\n        self.body[-1].dirnx = dx\n        self.body[-1].dirny = dy\n\n\n    def draw(self, surface):\n        for i, c in enumerate(self.body):\n            if i ==0:\n                c.draw(surface, True)\n            else:\n                c.draw(surface)\n\n\ndef drawGrid(w, rows, surface):\n    sizeBtwn = w // rows\n\n    x = 0\n    y = 0\n    for l in range(rows):\n        x = x + sizeBtwn\n        y = y + sizeBtwn\n\n#        pygame.draw.line(surface, (000,000,000), (x,0),(x,w))\n #       pygame.draw.line(surface, (255,000), (0,y),(w,y))\n\n\ndef redrawWindow(surface):\n    global rows, width, s, snack\n    surface.fill((255,255,255))\n    s.draw(surface)\n    snack.draw(surface)\n    drawGrid(width,rows, surface)\n    pygame.display.update()\n\n\ndef randomSnack(rows, item):\n\n    positions = item.body\n\n    while True:\n        x = random.randrange(rows)\n        y = random.randrange(rows)\n        if len(list(filter(lambda z:z.pos == (x,y), positions))) > 0:\n            continue\n        else:\n            break\n\n    return (x,y)\n\n    def reset(self, pos):\n        self.head = cube(pos)\n        self.body = []\n        self.body.append(self.head)\n        self.turns = {}\n        self.dirnx = 0\n        self.dirny = 1\n\n\n    def addCube(self):\n        tail = self.body[-1]\n        dx, dy = tail.dirnx, tail.dirny\n\n        if dx == 1 and dy == 0:\n            self.body.append(cube((tail.pos[0]-1,tail.pos[1])))\n        elif dx == -1 and dy == 0:\n            self.body.append(cube((tail.pos[0]+1,tail.pos[1])))\n        elif dx == 0 and dy == 1:\n            self.body.append(cube((tail.pos[0],tail.pos[1]-1)))\n        elif dx == 0 and dy == -1:\n            self.body.append(cube((tail.pos[0],tail.pos[1]+1)))\n\n        self.body[-1].dirnx = dx\n        self.body[-1].dirny = dy\n\n\n    def draw(self, surface):\n        for i, c in enumerate(self.body):\n            if i ==0:\n                c.draw(surface, True)\n            else:\n                c.draw(surface)\n\n\ndef drawGrid(w, rows, surface):\n    sizeBtwn = w // rows\n\n    x = 0\n    y = 0\n    for l in range(rows):\n        x = x + sizeBtwn\n        y = y + sizeBtwn\n\n#        pygame.draw.line(surface, (000,000,000), (x,0),(x,w))\n #       pygame.draw.line(surface, (255,000), (0,y),(w,y))\n\n\ndef redrawWindow(surface):\n    global rows, width, s, snack\n    surface.fill((255,255,255))\n    s.draw(surface)\n    snack.draw(surface)\n    drawGrid(width,rows, surface)\n    pygame.display.update()\n\n\ndef randomSnack(rows, item):\n\n    positions = item.body\n\n    while True:\n        x = random.randrange(rows)\n        y = random.randrange(rows)\n        if len(list(filter(lambda z:z.pos == (x,y), positions))) > 0:\n            continue\n        else:\n            break\n\n    return (x,y)\n\n\ndef message_box(subject, content):\n    root = tk.Tk()\n    root.attributes(\"-topmost\", True)\n    root.withdraw()\n    messagebox.showinfo(subject, content)\n    try:\n        root.destroy()\n    except:\n        pass\n\n\nclass PathSolver():\n    def __init__(self, graph, snake, apple_pos):\n        self.head = snake.body[0].pos\n        self.snake = snake\n        self.apple = apple_pos\n        self.graph = graph.copy()\n        self.vars = self.create_vars()\n        self.get_qubo()\n        self.run_dwave()\n        self.get_shortest_path_graph()\n        self.get_moves()\n\n    def get_shortest_path_graph(self):\n        graph = nx.grid_2d_graph(GRID_SIZE, GRID_SIZE, periodic =False)\n        self.path_edges = []\n        for edge in graph.edges():\n            try:\n                if self.sampleset.first.sample[f'{edge}']:\n                    print(f'{edge} MADE IT')\n                    self.path_edges.append(edge)\n                #nx.set_edge_attributes(graph, f'{edge}', \n                \n                #print(f\"we made it: {edge}\")\n            except KeyError:\n                print(edge)\n                #print(f'No Key: {edge}')\n\n    def get_moves(self):\n        temp_head = self.head\n        i = 0\n        self.moves = []\n        while(i< len(self.path_edges)):\n            for path_edge in self.path_edges:\n                if path_edge[0] == temp_head:\n                    self.moves.append((path_edge[1][0] - temp_head[0], path_edge[1][1] - temp_head[1]))\n                    temp_head = path_edge[1]\n                    i+=1\n        print(self.moves)\n\n    def run_dwave(self):\n        #sampler = DWaveSampler().sample_qubo(self.qubo)\n        print(len(self.qubo))\n\n #       Dwavesolver = EmbeddingComposite(DWaveSampler())\n#        sampleset = Dwavesolver.sample_qubo(self.qubo, num_reads=1000)\n        self.sampleset = ExactSolver().sample_qubo(self.qubo)\n        #print(f'SAMPLE: {self.sampleset.first}')\n        for k,v in self.sampleset.first.sample.items():\n            print(f'Key: {k}\\t\\t\\t\\t Val: {v}')\n        \n  #      Q.update(coupler_strengths)\n        # Sample once on a D-Wave system and print the returned sample\n        #response = DWaveSampler().sample_qubo(Q, num_reads=1)\n\n\n        #print(sampleset)\n\n    def get_qubo(self):\n        H= self.one_body_terms() + self.two_body_terms() + self.get_justin_trubo()\n        model = H.compile()\n        #print(model)\n        self.qubo, self.offset = model.to_qubo()\n        #print(f'QUBO:\\n {self.qubo}')\n        \n\n    def create_vars(self):\n       vars ={}\n       print('===========MAPPINGS==============')\n       for i, edge in enumerate(self.graph.edges.data()):\n           e=(edge[0],edge[1])\n           print(f'edge: {e} \\t data: {edge[2]}')\n           label = f'({edge[0]}, {edge[1]})'\n           vars[e] = Binary(label)\n       return vars\n    \n    def two_body_terms(self):\n        #twobody head terms\n        #Checked @ 10:04\n        H=0\n        H1=0\n        for head_edge_1 in self.head_edges:\n            for head_edge_2 in self.head_edges:\n                if head_edge_1 == head_edge_2:\n                    H1 += LAMBDA*self.vars[head_edge_1]*self.vars[head_edge_2]\n                else:\n                    H1 += LAMBDA*self.vars[head_edge_1]*self.vars[head_edge_2]\n\n        #apple twobody terms\n        # Checked @ 10:06\n        H2=0\n        for apple_edge_1 in self.apple_edges:\n            for apple_edge_2 in self.apple_edges:\n                if apple_edge_1 == apple_edge_2:\n                    H2 +=GAMMA*self.vars[apple_edge_1]*self.vars[apple_edge_2]\n                else:\n                    H2 += GAMMA*self.vars[apple_edge_1]*self.vars[apple_edge_2]\n\n\n        #make sure graph is connected\n        H3=0\n        for edge in self.graph.edges():\n            e=self.get_valid_key(edge)\n            for nodal_edge in self.graph.edges(e[0]):\n                n = self.get_valid_key(nodal_edge)\n                if  e == n:\n                    pass\n                else:\n                    #print(f'EDGE: {e} OTHER EDGE: {n} FORMULA: {-1*MU*self.vars[n]*self.vars[e]}')\n                    H3 -= MU*self.vars[n]*self.vars[e]\n            for nodal_edge in self.graph.edges(e[1]):\n                n = self.get_valid_key(nodal_edge)\n                if e == n:\n                    pass\n                else:\n                    #print(f'EDGE: {e} OTHER EDGE: {n} FORMULA: {-1*MU*self.vars[n]*self.vars[e]}')\n                    H3 -= MU*self.vars[n]*self.vars[e]\n\n\n        #manby body terms\n        #Checked at 10:37\n        H4=0\n        for edge_1 in self.graph.edges():\n            e1 = self.get_valid_key(edge_1)\n            if e1 in self.apple_edges or e1 in self.head_edges:\n                pass\n            else:\n                for edge_2 in self.graph.edges():\n                    e2 = self.get_valid_key(edge_2)\n\n                    if e2 in self.apple_edges or e2 in self.head_edges or e2 in self.head_neck_edge:\n                        pass\n                    else:\n                        #print(f'edge1: {e1} edge2 {e2} forumla {-2*CHI*self.vars[e1]*self.vars[e2]}')\n                        H4 += -2*CHI*self.vars[e1]*self.vars[e2]\n        #print(H4)\n        H = H1+H2+H3+H4\n        return H\n\n    def get_justin_trubo(self):\n        #Checked @ 10:46\n        H=0\n        for edge_1 in self.graph.edges():\n            e1 = self.get_valid_key(edge_1)\n            if e1 in self.apple_edges or e1 in self.head_edges or e1 == self.head_neck_edge:\n                pass\n            else:\n                for edge_2 in self.graph.edges():\n                    e2 = self.get_valid_key(edge_2)\n                    if e2 in self.apple_edges or e2 in self.head_edges or e2 == self.head_neck_edge:\n                        pass\n                    else:\n                        for edge_3 in self.graph.edges():\n                            e3 = self.get_valid_key(edge_3)\n                            if e3 in self.apple_edges or e3 in self.head_edges or e3 == self.head_neck_edge:\n                                pass\n                            else:\n                                #print(f'Edge1: {e1}\\tEdge2: {e2}\\tEdge3: {e3}\\tFormula: {CHI*self.vars[e1]*self.vars[e2]*self.vars[e3]}')\n                                H += CHI*self.vars[e1]*self.vars[e2]*self.vars[e3]\n        #print(H)\n        return H\n\n\n\n    def get_node(self, tup):\n        if tup[0][0] == tup[1][0]:\n            return tup[0][0]\n        if tup[0][0] == tup[1][1]:\n            return tup[0][0]\n        if tup[0][1] == tup[1][0]:\n            return tup[0][1]\n        if tup[0][1] == tup[1][1]:\n            return tup[0][1]\n\n\n    def one_body_terms(self):\n        #Distance traversted term\n        H = 0\n        H1 = 0\n        #checked H1 @ 09:12\n        for edge in self.graph.edges.data():\n            dict_key = self.get_valid_key((edge[0],edge[1]))\n            #print(edge[2][\"weight\"])\n            H1 += edge[2][\"weight\"]*self.vars[dict_key]\n        \n        #Links around the head term\n        #checked @ 09:37\n        H2=0\n        self.head_edges = []\n        head_neck_edge = self.get_valid_key((self.head, self.snake.body[1].pos))\n        self.head_neck_edge = head_neck_edge\n        # print(f'head_neck_edge: {head_neck_edge}')\n        for edge in self.graph.edges(self.head):\n            head_edge = self.get_valid_key(edge)\n            # print(f'head_edge: {head_edge}')\n            if not self.get_valid_key(head_edge) == self.get_valid_key(head_neck_edge):\n                H2 -= 2*LAMBDA*self.vars[head_edge]\n                self.head_edges.append(head_edge)\n\n                \n        #Links around the apple term\n        #Checked at 09:38\n        H3=0\n        self.apple_edges=[]\n        for edge in self.graph.edges(self.apple):\n            apple_edge = self.get_valid_key(edge)\n            H3 -= 2*GAMMA*self.vars[apple_edge]\n            self.apple_edges.append(apple_edge)\n\n        #Links from 3body bulk term\n        # checked @ 09:55\n        H4=0\n        for edge in self.graph.edges():\n            e = self.get_valid_key(edge)\n            if e not in self.head_edges and edge not in self.apple_edges and not e==head_neck_edge:\n                H4 += 4*CHI*self.vars[self.get_valid_key(edge)]\n\n        H= H1 + H2 + H3 + H4\n\n        return H\n\n\n\n    def get_valid_key(self, key):\n        if key in self.vars:\n            return key\n        elif (key[1], key[0]) in self.vars:\n            return (key[1], key[0])\n        else:\n            raise \"Awer\"\n\n\n\n\n\ndef main():\n    global width, rows, s, snack, sampleset\n    width =  100\n    rows = 3\n    win = pygame.display.set_mode((width, width))\n    s = snake((0,255,0), (1,1)) #snake starts at rtupple\n    #snack = cube(randomSnack(rows, s), color=(255,0,0))\n    snack = cube(randomSnack(3, s), color=(255,0,0))\n    flag = True\n\n\n    s.addCube()\n    s.snake_to_graph()\n    H=s.get_snake_unconnected_graph()\n    H.add_node((10,10))\n    H.add_node((11,10))\n    H.add_node((11,11))\n    H.add_edge((10,10),(11,10))\n    H.add_edge((11,10),(11,11))\n    print(f'HYPERS \\t LAMBDA: {LAMBDA}\\t CHI: {CHI}\\t MU: {MU}\\t GAMMA: {GAMMA}')\n    ps=PathSolver(s.snake_to_graph(), s, snack.pos)\n    redrawWindow(win)\n\n    pygame.time.delay(10)\n\n    clock = pygame.time.Clock()\n    for move in ps.moves:\n        pygame.time.delay(10)\n        print(move)\n        s.dirnx=move[0]\n        s.dirny=move[1]\n        s.move()\n        redrawWindow(win)\n        \n        \n    \n    \n    \n    # while flag:\n    #     pygame.time.delay(50)\n    #     clock.tick(10)\n    #     s.move()\n    #     if s.body[0].pos == snack.pos:\n    #         s.addCube()\n    #         snack = cube(randomSnack(rows, s), color=(255,0,0))\n    #         for block in s.body:\n    #             print(block.pos)\n\n\n    #     for x in range(len(s.body)):\n    #         if s.body[x].pos in list(map(lambda z:z.pos,s.body[x+1:])):\n    #             print('Score: ', len(s.body))\n    #             message_box('You Lost!', 'Play again...')\n    #             s.reset((10,10))\n    #             break\n\n\n    #     redrawWindow(win)\n\n\n    # pass\n\n\n\nmain()\n", "meta": {"hexsha": "65d9fd6fe4678787f58e497f4a01083a98a6a618", "size": 19083, "ext": "py", "lang": "Python", "max_stars_repo_path": "snaqe.py", "max_stars_repo_name": "DurhamSmith/snaQe", "max_stars_repo_head_hexsha": "7492441304029a1629a3de4adc503255c3ea17c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2019-07-19T18:03:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-21T17:04:39.000Z", "max_issues_repo_path": "snaqe.py", "max_issues_repo_name": "DurhamSmith/snaQe", "max_issues_repo_head_hexsha": "7492441304029a1629a3de4adc503255c3ea17c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "snaqe.py", "max_forks_repo_name": "DurhamSmith/snaQe", "max_forks_repo_head_hexsha": "7492441304029a1629a3de4adc503255c3ea17c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2424722662, "max_line_length": 138, "alphanum_fraction": 0.5139653094, "include": true, "reason": "import networkx", "num_tokens": 5089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.18614773774590923}}
{"text": "#!/bin/env python2.7\n\nimport matplotlib as mpl\n#mpl.use('Agg')\n#mpl.style.use('classic')\n\nimport numpy as np\nimport netCDF4 as nc\nimport sys,os\nimport pickle\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport matplotlib.gridspec as gs\nfrom copy import deepcopy\nimport datetime as dt\n\nfrom imogen import data_info\nfrom PlotTools import plot_tools as PTs\n\n#import ipdb\n\ndef box_and_whisker(DS,xpos,color,ax,boxwidth=0.1,med_color=None,fill=False):\n    if med_color==None: med_color=color\n    datastats = DS.describe()\n    patch = patches.Rectangle( (xpos-(boxwidth/2.),datastats['25%']),\n                                boxwidth, datastats['75%']-datastats['25%'],\n                                fill=fill, edgecolor=color, color=color, lw=1.5)\n    ax.add_patch(patch)\n    line = ax.plot( [xpos-(boxwidth/2.),xpos+(boxwidth/2.)],\n                    [datastats['50%'],datastats['50%']], c=med_color, lw=2)\n    ax.plot( [xpos,xpos],[datastats['75%'],datastats['max']], c=color, lw=1.5)\n    ax.plot( [xpos,xpos],[datastats['25%'],datastats['min']], c=color, lw=1.5)\n    return line\n\ndef optional_argparse(arg,default):\n    if arg in sys.argv:\n        temp_loc=sys.argv.index(arg)\n        temp_arg=sys.argv.pop(temp_loc)\n        value=sys.argv.pop(temp_loc)\n    else:\n        value=default\n    return value\n\nINTERACTIVE  = '-interactive' in sys.argv\nkg_to_t      = 1e-3\nkg_to_Gt     = 1e-12\nkg_to_Mt     = 1e-9\nkg_to_Tg     = kg_to_Mt\nkg_to_Gg     = 1e-6\nm2_to_Mha    = 1e-10\nm2_to_Ha     = 1e-4\nGtC_to_ppm   = 0.471\nC_to_CH4     = 16.04/12.011\nppm_to_kgC   = 1e12/GtC_to_ppm\nC_to_water   = 530.0*1.0E-03            # Convert from GtC yr-1 to Tm3 yr-1\nkg_to_Tm3    = 1.0E-15                  # Assume 1 kg of water is 10-3 m3\nsec_to_year  = 3600.0*24.0*360.0        # 360 day year\n                                        # * kgC to biomass * 90% dry matter\nBECCS_harvest_conv        = (1./m2_to_Ha) * kg_to_t * 2.0  * 0.9 * (365./360.)\nkappa_efficiency_ratio    = 0.6/0.87\n \n# Optional input parameters\nDEBUG         = optional_argparse('-debug','N')\nsubregions    = optional_argparse('-subregions','IMAGE').upper()\nPLATFORM      = optional_argparse('-platform','JASMIN')\nsDATE         = optional_argparse('-date',dt.datetime.strftime(dt.datetime.now(),'%Y%m%d'))\nPLOT_TAG      = optional_argparse('-plottag', 'BECCS_Extra')\nVERSION       = optional_argparse('-BECCS','max_bioenergy')\nBECCS_NPP     = optional_argparse('-BECCS_NPP','N')\nPROC_STEP     = optional_argparse('-BECCS_NPY','Save')\nCCS_minimum_threshold     = float(optional_argparse('CCS_min','1e-4'))\nBIOFRAC_minimum_threshold = float(optional_argparse('CCSfrac_min','1e-2'))\nFILE_EXT      = optional_argparse('-ext','.jpg')\nPLOT_FIGURE   = False\n\n# Directories containing JULES output and plot output directories:\nif PLATFORM == 'JASMIN':\n    HOME_DIR      = '/gws/nopw/j04/clifftop/SYNTHESIS/PostReview_output/'\n    DATA_DIR      = HOME_DIR\n    ANCILS_DIR    = '/gws/nopw/j04/clifftop/COMMON_DATA/ANCILS/'\n    PLOT_DIR      = optional_argparse('-plotdir',DATA_DIR+'plots/'+PLOT_TAG+'/')\n    BECCS_npy_DIR = '/gws/nopw/j04/jules/aharper/PYTHON/SYNTHESIS/npy_files/'+VERSION+'/'\n    BECCS_npy_NPP = '/gws/nopw/j04/jules/ghayman/PYTHON/SYNTHESIS/npy_files/max_bioenergy_NPP/'\n    SCNPP_npy_DIR = '/gws/nopw/j04/jules/ghayman/PYTHON/SYNTHESIS/npy_files/Carbon/'\n    COMPS_npy_DIR = '/gws/nopw/j04/jules/ghayman/PYTHON/SYNTHESIS/npy_files/processed_output/'\n    LAND_npy_DIR  = '/gws/nopw/j04/jules/ghayman/PYTHON/SYNTHESIS/npy_files/land_cover/'\n#   BECCS_npy_NPP = '/work/scratch/ghayman/SYNTHESIS/npy_files/max_bioenergy_NPP/'\n#   SCNPP_npy_DIR = '/work/scratch/ghayman/SYNTHESIS/npy_files/Carbon/'\n#   COMPS_npy_DIR = '/work/scratch/ghayman/SYNTHESIS/npy_files/processed_output/'\n#   LAND_npy_DIR  = '/work/scratch/ghayman/SYNTHESIS/npy_files/land_cover/'\n\n    Q10_exps      = [ 'lowQ10', 'highQ10' ]\n    Ozone_exps    = [['L','lowO3'], ['H','highO3'], ]\n\n    COMPS_keys    = [ 'CTL', 'CH4', 'LULUC_CCS', 'LULUC_Nat', 'Coupled_CCS', 'Coupled_Nat' ]\n\nelif PLATFORM == 'CEH':\n    HOME_DIR      = '/prj/CLIFFTOP/SYNTHESIS/'\n    PLOT_DIR      = HOME_DIR+'Review_Response_Check2/plots/'\n    DATA_DIR      = HOME_DIR+'Review_Response_Check2/GCM_Output/'\n    ANCILS_DIR    = HOME_DIR+'Land_Cover/'\n    BECCS_npy_DIR = HOME_DIR+'Review_Response_Check2/'+VERSION+'/'\n    BECCS_npy_NPP = HOME_DIR+'Review_Response_Check2/max_bioenergy_NPP/'\n    SCNPP_npy_DIR = HOME_DIR+'Review_Response_Check2/Carbon/'\n    COMPS_npy_DIR = HOME_DIR+'Review_Response_Check2/processed_output/'\n    LAND_npy_DIR  = HOME_DIR+'Review_Response_Check2/land_cover/'\n\n    if PROC_STEP == \"Save\":\n        Q10_exps      = [ 'highQ10' ]\n        Ozone_exps    = [['L','lowO3']]\n    else:\n        Q10_exps      = [ 'lowQ10', 'highQ10' ]\n        Ozone_exps    = [['L','lowO3'], ['H','highO3'], ]\n\n    COMPS_keys    = [ 'CTL', 'CH4', 'LULUC_CCS', 'LULUC_Nat' ]\n\nCOMPS_opt     = [ 'LULUC_opt','Coupled_opt' ]\nCOMPS_keys_all= [ 'CTL', 'CH4', 'LULUC_CCS', 'LULUC_Nat', 'Coupled_CCS', 'Coupled_Nat' ]+[ 'LULUC_opt','Coupled_opt' ]\nCOMPS         = {\n                  'CTL': { 'config': 'highCH4_OZONESUB_LULUCBL', 'runid':'H_OZONESUB_BL' }\n                , 'CH4': { 'config':'lowCH4_OZONESUB_LULUCBL', 'runid':'L_OZONESUB_BL' }\n                , 'LULUC_CCS': { 'config':'highCH4_OZONESUB_LULUC1.9', 'runid':'H_OZONESUB_19' }\n                , 'LULUC_Nat': { 'config':'highCH4_OZONESUB_LULUC1.9Nat', 'runid':'H_OZONESUB_19N' }\n                , 'Coupled_CCS': { 'config':'lowCH4_OZONESUB_LULUC1.9', 'runid':'L_OZONESUB_19' }\n                , 'Coupled_Nat': { 'config':'lowCH4_OZONESUB_LULUC1.9Nat', 'runid':'L_OZONESUB_19N' }\n                }\n\nCOMPS_DIFF    = {\n                  'LULUC_CCS': { 'config':'highCH4_OZONESUB_LULUC1.9', 'runid':'H_OZONESUB_19' }\n                , 'LULUC_Nat': { 'config':'highCH4_OZONESUB_LULUC1.9Nat', 'runid':'H_OZONESUB_19N' }\n                }\n\n# Directories containing JULES output and plot output directories:\nDATA_DIR      = optional_argparse('-data_dir', DATA_DIR)\nPLOT_DIR      = optional_argparse('-plotdir',  PLOT_DIR+PLOT_TAG+'/')\nprint('DATA_DIR: '+DATA_DIR)\nprint('PLOT_DIR: '+PLOT_DIR)\nos.system('mkdir -p '+PLOT_DIR )\nos.system('mkdir -p '+PLOT_DIR+'npy_files' )\n\nPRESENT_DAY_YEAR = 2015\n\nALPHABET      = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o']\n\nSTART_YEAR    = PRESENT_DAY_YEAR\nEND_YEAR      = 2100\nnYEARS        = END_YEAR-START_YEAR # No data for 2100\n\n# Scenarios to plot:\nTEMPs         = ['1p5deg', '2deg' ] #'1p81p5deg',   # tag in the JULES output file directory\nTEMP_years    = [2099,2099,2099]    # tag in the JULES output file directory \nTEMP_names    = ['1.5$^o$C (2100)','2.0$^o$C (2100)'] # '1.5$^o$C Overshoot (2100)',\n                # Name to appear on plots etc.\n\nGLOBAL_pools  = [ 'Total','Atmos','Ocean' ]\nLAND_pools    = [ 'Land','CS','CV','WP','CCS','BE_Harvest' ]\nAREA_pools    = [ 'BECCS_Area' ]\nBECCS_pools   = [ 'BECCS_productivity', 'BECCS_ScaleFactor', \\\n                  'BECCS_productivity_JULES','BECCS_productivity_NPP' ]\n              #+[ 'BECCS_productivity','Harvest','kappaHarvest','kappamefficHarvest']\nSOIL_pools    = [ 'Soil_Carbon', 'Soil_Carbon_gb', 'NPP_gb' ]\n\ndzsoil        = np.array([ 0.05,0.08408964,0.11397535,0.14142136,0.16718508,0.19168293, \\\n                  0.21517585,0.23784142,0.25980762,0.28117066,0.30200527, \\\n                  0.32237098,0.34231625,0.36188121 ])\n\nnLAYERs       = 7\nsoil_depth    = dzsoil[0:nLAYERs].sum()\n \nLAND_TYPES    = [ 'Trees','Agriculture','Bioenergy','Grasses','Shrubs' ]\nnLAND_TYPES   = len(LAND_TYPES)\nnSCENARIOs    = 2\npools         = GLOBAL_pools+LAND_pools+BECCS_pools+SOIL_pools+LAND_TYPES+AREA_pools\n\nTile_names    = data_info.TILE_short_names()\nTile_colours  = data_info.TILE_colours()\nnTiles        = len(Tile_names)\nnTEMPs        = len(TEMPs)\nnQ10s         = len(Q10_exps)\nnO3s          = len(Ozone_exps)\nnpools        = len(pools)\nnPFTs         = 13\nnSOIL_L       = 14\nnSOIL_P       =  4\nnLAND_pts     = 1631\n\n# Indices of pfts for aggregation to trees, grasses, shrubs\nTREE_INDICES  = [ 0,1,2,3,4 ]\nGRASS_INDICES = [ 5,8 ] # natural grasses\nCROP_INDICES  = [ 6,9 ]\nPAST_INDICES  = [ 7,10 ]\nSHRUB_INDICES = [ 11,12 ]\n\n#  BECCS_multiplier not required for BECCS sensitivty routine\n### BECCS_multiplier = float(optional_argparse('-beccs_multiplier','1'))\n### print(BECCS_multiplier)\n\n# Select subregions (IMAGE, TRANSCOM)\nREGION_dict   = data_info.REGION_DICTIONARIES()[subregions]\nnREGIONs_DICT = REGION_dict['Nregions']\nREGION_idx    = [ idx for idx in range(11) ] + [ 25 ] + [ idx for idx in range(11,23) ] + [ 24, 23, 27 ]\nnREGIONS      = len(REGION_idx)\n\n# Directory of Ocean Uptake data:\nOCEAN_UPTAKE_DIR = optional_argparse('-ocean_uptake_dir',DATA_DIR) \nOCEAN_START_YEAR = 1850\nprint(\"Ocean Uptake data from: \" + OCEAN_UPTAKE_DIR)\n\n# Directory of ancillary data:\n# Grid File (My index for converting the 1D jules output to a 2D grid)\nGRID_file        = ANCILS_DIR+'grid_info.nc'\ngrinf            = nc.Dataset(GRID_file,'r')\ngrindex          = grinf.variables['land_index'][:]\nlats_2d          = grinf.variables['latitude'][:]\nlons_2d          = grinf.variables['longitude'][:]\n#Area_2d         = grinf.variables['Area'][:]       # I don't actually use this but it's here\nland_index       = grinf.variables['land_index'][:]\ngrinf.close()\n\n# 1Dimension grid cell area data for calculating totals etc.\nAREA_file        = ANCILS_DIR+'Area_in_iris_format.nc'\nAinf             = nc.Dataset(AREA_file,'r')\nlats_1D          = Ainf.variables['latitude'][:].squeeze()\nlons_1D          = Ainf.variables['longitude'][:].squeeze()\nAREA_1D          = Ainf.variables['area'][:].squeeze()\nREGIONS_1D       = Ainf.variables[REGION_dict['NCvarname']][:].squeeze()\nMAXBIOFRAC_1D    = Ainf.variables['maxbiofrac_19'][:].squeeze()\nAinf.close()\n#print(AREA_file)\n\nMAXBIOFRAC_2D    = np.ma.masked_array(MAXBIOFRAC_1D[grindex], mask=grindex.mask)\n\n####################################\n# select GCMs:\nGCMs=data_info.GCMs()\nnGCMs=len(GCMs)\nnGCMs_ALL=len(GCMs)\nfor igcm in range(nGCMs):\n    print('%3i: '%igcm+GCMs[igcm])\n\nif INTERACTIVE==True:\n    GCM_index=raw_input('Select GCMs to plot (Press Enter to select all): ')\n    if GCM_index.replace(' ','')!='':\n        GCM_index = [ int(i) for i in GCM_index.split(':') ]\n        GCMs=[ GCMs[i] for i in GCM_index ] \n        nGCMs=len(GCMs)\n    else:\n        GCM_index=[ i for i in range(nGCMs) ]\nelse:\n    GCM_index  = optional_argparse('-GCMs','ALL')\n    sGCM_index = GCM_index\n    if GCM_index=='ALL':\n        GCM_index=[ i for i in range(nGCMs) ]\n    else:\n        GCM_index=[ int(i) for i in GCM_index.split(':') ]\n        GCMs=[ GCMs[i] for i in GCM_index ] \n        nGCMs=len(GCMs)\n\ncmip5_runs = [ data_info.cmip5_runs()[i] for i in GCM_index ]\nprint(' -GCMs ',GCM_index)\nfor igcm in range(nGCMs):\n    print(igcm,GCM_index[igcm],GCMs[igcm])\n\n# Arrays and partial filenames for land-use files\nLAND_REGION    = np.zeros((nSCENARIOs,nTEMPs,nREGIONs_DICT,nLAND_TYPES,nYEARS,nGCMs,nQ10s,nO3s))\nLAND_LANDPTS   = np.zeros((nSCENARIOs,nTEMPs,nLAND_TYPES,nYEARS,nGCMs,nQ10s,nO3s,nLAND_pts))\nnFACTORIAL     = nGCMs*nQ10s*nO3s\n\nFILE_PART      = 'Land_Area_Max_'\nFILE_PART2     = 'Land_Area_Grid_'\n\nif sGCM_index == 'ALL':\n    FILE_PART3     = 'GCM_All_'+sDATE\nelse:\n    FILE_PART3     = 'GCM_'+sGCM_index.replace(':','_')+'_'+sDATE\n\n###################################################################################################\n\n# Read in the Control data\nOCEAN_START_YEAR=1850\n\nif PROC_STEP == 'Save':\n    for comp in COMPS_keys:\n        comp_Ocean_in = { Q10 : { O3[1]:  np.load(OCEAN_UPTAKE_DIR+Q10+'/' \n                                        + COMPS[comp]['config'].replace('OZONESUB',O3[1])+'/'\n                                        + COMPS[comp]['runid'].replace('OZONESUB',O3[0])\n                                        +'_ocean_uptake_accum.npy' ) * -1. / kg_to_Gt\n                         for O3 in Ozone_exps} for Q10 in Q10_exps }\n        \n        comp_Ocean = { '1p5deg':   { Q10:  { O3[1]: comp_Ocean_in[Q10][O3[1]][:,2,:] for O3 in Ozone_exps } for Q10 in Q10_exps},\n                       '1p81p5deg':{ Q10:  { O3[1]: comp_Ocean_in[Q10][O3[1]][:,1,:] for O3 in Ozone_exps } for Q10 in Q10_exps},\n                       '2deg':     { Q10:  { O3[1]: comp_Ocean_in[Q10][O3[1]][:,0,:] for O3 in Ozone_exps } for Q10 in Q10_exps}\n                       }\n        CH4 = COMPS[comp]['config'].split('_')[0]\n        for iTEMP in range(nTEMPs): \n            TEMP=TEMPs[iTEMP]\n            TEMP_year=TEMP_years[iTEMP]\n            TEMP_tag=TEMP\n            COMPS[comp][TEMP]={}\n            for iQ10 in range(nQ10s):\n                Q10 = Q10_exps[iQ10]\n                COMPS[comp][TEMP][Q10]={}\n                for iO3 in range(nO3s):\n                    O3 = Ozone_exps[iO3]\n                    COMPS[comp][TEMP][Q10][O3[1]]={ pool:{} for pool in pools  }  #+land_opt_pools }\n                    config=COMPS[comp]['config'].replace('OZONESUB',O3[1])\n                    runid=COMPS[comp]['runid'].replace('OZONESUB',O3[0])\n                    print('GCM Input:',comp,TEMP,TEMP_year,Q10,config,runid)\n                    for igcm in range(nGCMs):\n                        gcm=GCMs[igcm]\n                        gcm_index=GCM_index[igcm]\n                        print(gcm)\n                        DUMP_FILE=DATA_DIR+Q10+'/'+config+'/'+gcm+'/'+runid+'_'+gcm+'_'+TEMP_tag+'.dump.YYYY0101.0.nc'\n                        Ann_File=DATA_DIR+Q10+'/'+config+'/'+gcm+'/'+runid+'_'+gcm+'_'+TEMP_tag+'.Annual_carbon.YYYY.nc'\n                        #BECCSFile=DATA_DIR+Q10+'/'+config+'/'+gcm+'/'+runid+'_'+gcm+'_'+TEMP_tag+'.be_harvest_gb.MAX.nc'\n                        #DATA_DIR+Q10+'/'+config+'/'+gcm+'/'+runid+'_'+gcm+'_'+TEMP_tag+'.be_harvest_gb.MAX.nc'\n                        BECCS_numpy_File=BECCS_npy_DIR + CH4+'_'+O3[1]+'_'+Q10+'_'+gcm+'_'+TEMP_tag+'.npy'\n                        print(BECCS_numpy_File)\n                        #quit()\n                        #import  ipdb\n                        #ipdb.set_trace()\n                        #print(Ann_File)\n                        # Open end of sim files:\n                        Dinf = nc.Dataset(DUMP_FILE.replace('YYYY',str(TEMP_year+1)),'r')\n                        Ainf = nc.Dataset(Ann_File.replace('YYYY',str(TEMP_year)),'r')\n                        # Open Present day files:\n                        Dinf_0 = nc.Dataset(DUMP_FILE.replace('YYYY',str(START_YEAR+1)),'r')\n                        Ainf_0 = nc.Dataset(Ann_File.replace('YYYY',str(START_YEAR)),'r')\n                        # and Max BECCS file:\n                        #print(BECCSFile)\n                        #Binf = nc.Dataset(BECCSFile,'r')\n                        # Read in data, find delta from present day,    \n                        CV = ( Ainf.variables['cv'][:]-Ainf_0.variables['cv'][:] ).squeeze() * AREA_1D\n                        COMPS[comp][TEMP][Q10][O3[1]]['CV'][gcm] = CV *kg_to_Gt\n                        \n                        CS = ( Ainf.variables['cs_gb'][:]-Ainf_0.variables['cs_gb'][:] ).squeeze() * AREA_1D\n                        COMPS[comp][TEMP][Q10][O3[1]]['CS'][gcm] = CS*kg_to_Gt\n                        \n                        # Correction for bug in test runs, can remove this with final runs, although will not affect results\n                        #if '_Nat' in comp:\n                        #    CCS = np.zeros_like(CS)\n                        #else:\n                        CCS = ( Ainf.variables['ccs_gb'][:]-Ainf_0.variables['ccs_gb'][:] ).squeeze() * AREA_1D \n                                    #  * BECCS_multiplier (Not Required for BECCS sensitivity script)\n                        CCS[np.isfinite(CCS)==False]=0.\n                        COMPS[comp][TEMP][Q10][O3[1]]['CCS'][gcm] = CCS*kg_to_Gt\n                        \n                        # Read in the maximum BECCS harvest rate, to scale with kappa_threshold for Figure2\n                        #BE_H = ( Binf.variables['be_harvest_gb'][:] ).squeeze()\n                        #BE_H[ np.isinf(BE_H) ] = 0.\n                        BE_H = np.load(BECCS_numpy_File)  \n                        ##COMPS[comp][TEMP][Q10][O3[1]]['BECCS_productivity'][gcm] = BE_H * m2_to_Ha * kg_to_t \n                        COMPS[comp][TEMP][Q10][O3[1]]['BE_Harvest'][gcm] = BE_H * BECCS_harvest_conv \n                        COMPS[comp][TEMP][Q10][O3[1]]['BECCS_productivity_JULES'][gcm] = ( \n                                COMPS[comp][TEMP][Q10][O3[1]]['BE_Harvest'][gcm] )\n                        COMPS[comp][TEMP][Q10][O3[1]]['BECCS_productivity'][gcm] = ( \n                                COMPS[comp][TEMP][Q10][O3[1]]['BE_Harvest'][gcm] * kappa_efficiency_ratio )\n\n                        data_temp = COMPS[comp][TEMP][Q10][O3[1]]['BECCS_productivity_JULES'][gcm]\n                        data_temp = data_temp[MAXBIOFRAC_1D>BIOFRAC_minimum_threshold]\n                        print('BE mean: ',comp,TEMP,Q10,O3[1],gcm,data_temp.shape,data_temp.mean())\n\n                        #if comp=='LULUC_CCS':\n                        #    ipdb.set_trace() \n                        WP =(( Dinf.variables['wood_prod_fast'][:]+Dinf.variables['wood_prod_med'][:] +\n                               Dinf.variables['wood_prod_slow'][:]  )\n                           - ( Dinf_0.variables['wood_prod_fast'][:]+Dinf_0.variables['wood_prod_med'][:] +\n                               Dinf_0.variables['wood_prod_slow'][:]  ) )  *  AREA_1D\n                        WP[np.isfinite(WP)==False]=0.\n                        COMPS[comp][TEMP][Q10][O3[1]]['WP'][gcm] = WP*kg_to_Gt\n\n                        AtmCO2_ppm = Dinf.variables['co2_ppmv'][0]-Dinf_0.variables['co2_ppmv'][0]\n                        AtmCO2_kg = AtmCO2_ppm*ppm_to_kgC\n                        COMPS[comp][TEMP][Q10][O3[1]]['Atmos'][gcm] = AtmCO2_kg *kg_to_Gt\n                        \n                        Ocean =  comp_Ocean[TEMP][Q10][O3[1]][gcm_index,TEMP_year-OCEAN_START_YEAR]   \\\n                               - comp_Ocean[TEMP][Q10][O3[1]][gcm_index,START_YEAR-OCEAN_START_YEAR]\n                        COMPS[comp][TEMP][Q10][O3[1]]['Ocean'][gcm] = Ocean *kg_to_Gt\n                        \n                        COMPS[comp][TEMP][Q10][O3[1]]['Land'][gcm] = (  \n                                                                       COMPS[comp][TEMP][Q10][O3[1]]['CV'][gcm]\n                                                                     + COMPS[comp][TEMP][Q10][O3[1]]['CS'][gcm]\n                                                                     + COMPS[comp][TEMP][Q10][O3[1]]['WP'][gcm] ) \n                        COMPS[comp][TEMP][Q10][O3[1]]['Total'][gcm] = (  \n                                                                        COMPS[comp][TEMP][Q10][O3[1]]['Land'][gcm].sum()\n                                                                      + COMPS[comp][TEMP][Q10][O3[1]]['CCS'][gcm].sum()\n                                                                      + COMPS[comp][TEMP][Q10][O3[1]]['Atmos'][gcm]\n                                                                      + COMPS[comp][TEMP][Q10][O3[1]]['Ocean'][gcm] )\n                        \n                        Dinf.close(); Ainf.close(); Dinf_0.close(); Ainf_0.close(); # Binf.close()\n\n                        # Productivity based on NPP\n                        first_year = True\n                        if ('CTL' in comp or 'CCS' in comp or 'Nat' in comp) and (BECCS_NPP == 'Y'):\n\n                            # Skip if files already exist for bioenergy, NPP and soil carbon\n                            BECCS_NPP_FILE = BECCS_npy_NPP+comp+'_'+CH4+'_'+O3[1]+'_'+Q10+'_'+gcm+'_'+TEMP_tag+'_NPP.npy'\n                            SC_NPP_FILE    = SCNPP_npy_DIR+comp+'_'+CH4+'_'+O3[1]+'_'+Q10+'_'+gcm+'_'+TEMP_tag+'_SCNPP.pkl'\n\n                            print(not os.path.exists(BECCS_NPP_FILE))\n                            print(not os.path.exists(SC_NPP_FILE))\n\n                            if not os.path.exists(BECCS_NPP_FILE) and not os.path.exists(SC_NPP_FILE):\n\n                                for iyear in range(nYEARS):\n                                     YEAR = START_YEAR+iyear\n                                     DUMP_FILE=DATA_DIR+Q10+'/'+config+'/'+gcm+'/'+runid+'_'+gcm+'_'+TEMP_tag+'.dump.'+str(YEAR)+'0101.0.nc'\n                                     ANN_FILE=DATA_DIR+Q10+'/'+config+'/'+gcm+'/'+runid+'_'+gcm+'_'+TEMP_tag+'.Annual_carbon.'+str(YEAR)+'.nc'\n                                     if iyear == 0 or iyear == nYEARS-1: print(YEAR,ANN_FILE,DUMP_FILE)\n                                     # Open current year files:\n                                     Dinf = nc.Dataset(DUMP_FILE,'r')\n                                     Ainf = nc.Dataset(ANN_FILE,'r')\n\n                                     # Read in data from current year\n                                     FRAC       = Dinf.variables['frac'][:].squeeze()\n                                     NPP        = Ainf.variables['npp'][:].squeeze()\n                                     NPP_GB     = Ainf.variables['npp_gb'][:].squeeze()\n                                     SOILC      = Ainf.variables['cs'][:].squeeze()\n                                     SOILC_GB   = Ainf.variables['cs_gb'][:].squeeze()\n\n                                     if first_year:\n                                         first_year   = False\n                                         nLAND_PTS    = FRAC.shape[1]\n                                         NPP_ALL      = np.zeros((nYEARS,nPFTs,nLAND_PTS))\n                                         NPP_GB_ALL   = np.zeros((nYEARS,nLAND_PTS))\n                                         SOILC_ALL    = np.zeros((nYEARS,nSOIL_P,nSOIL_L,nLAND_PTS))\n                                         SOILC_GB_ALL = np.zeros((nYEARS,nLAND_PTS))\n                                         FRAC_ALL     = np.zeros((nYEARS,nPFTs,nLAND_PTS))\n                                         FRAC_TREES   = np.zeros((nYEARS,nLAND_PTS))\n                                         FRAC_GRASSES = np.zeros((nYEARS,nLAND_PTS))\n                                         FRAC_SHRUBS  = np.zeros((nYEARS,nLAND_PTS))\n                                         FRAC_CROPS   = np.zeros((nYEARS,nLAND_PTS))\n                                         FRAC_PAST    = np.zeros((nYEARS,nLAND_PTS))\n                                         FRAC_AGRIC   = np.zeros((nYEARS,nLAND_PTS))\n                                         FRAC_BECCS   = np.zeros((nYEARS,nLAND_PTS))\n                                         NPP_BECCS    = np.zeros((nYEARS,nLAND_PTS))\n\n                                     if len(FRAC) == 0:\n                                         print('No data for fractions      for '+str(YEAR))\n                                         FRAC_ALL[iyear,:,:]     = float('nan')\n                                     else:\n                                         FRAC_ALL[iyear,:,:]     = FRAC[0:nPFTs,:]\n\n                                     if len(NPP) == 0:\n                                         print('No data for npp            for '+str(YEAR))\n                                         NPP_ALL[iyear,:,:]      = float('nan')\n                                     else:\n                                         NPP_ALL[iyear,:,:]      = NPP\n\n                                     if len(NPP_GB) == 0:\n                                         print('No data for npp_gb         for '+str(YEAR))\n                                         NPP_GB_ALL[iyear,:]     = float('nan')\n                                     else:\n                                         NPP_GB_ALL[iyear,:]     = NPP_GB\n\n                                     if len(SOILC) == 0:\n                                         print('No data for soil carbon    for '+str(YEAR))\n                                         SOILC_ALL[iyear,:,:,:]  = float('nan')\n                                     else:\n                                         SOILC_ALL[iyear,:,:,:]  = SOILC\n\n                                     if len(SOILC_GB) == 0:\n                                         print('No data for soil carbon gb for '+str(YEAR))\n                                         SOILC_GB_ALL[iyear,:]   = float('nan')\n                                     else:\n                                         SOILC_GB_ALL[iyear,:]   = SOILC_GB\n\n                                     # Trees:\n                                     for index in TREE_INDICES:  FRAC_TREES[iyear,:]   += FRAC_ALL[iyear,index,:]\n                                     # Natural grasses:\n                                     for index in GRASS_INDICES: FRAC_GRASSES[iyear,:] += FRAC_ALL[iyear,index,:]\n                                     # Shrubs:\n                                     for index in SHRUB_INDICES: FRAC_SHRUBS[iyear,:]  += FRAC_ALL[iyear,index,:]\n                                     # Agriculture - Crops\n                                     for index in CROP_INDICES:  FRAC_CROPS[iyear,:]   += FRAC_ALL[iyear,index,:]\n                                     # Agriculture - Pasture\n                                     for index in PAST_INDICES:  FRAC_PAST[iyear,:]    += FRAC_ALL[iyear,index,:]\n\n                                     # All agriculture\n                                     # Issue with some of the annual files\n                                     TEMP_AGRIC          = Ainf.variables['frac_agr'][:].squeeze()\n                                     TEMP_BECCS          = Ainf.variables['frac_biocrop'][:].squeeze()\n\n                                     if len(TEMP_AGRIC) == 0:\n                                         print('No data for agriculture    for '+str(YEAR))\n                                         FRAC_AGRIC[iyear,:] = float('nan')\n                                     else:\n                                         FRAC_AGRIC[iyear,:] = TEMP_AGRIC\n\n                                     if len(TEMP_BECCS) == 0:\n                                         print('No data for bioenery crops for '+str(YEAR))\n                                         FRAC_BECCS[iyear,:] = float('nan')\n                                     else:\n                                         FRAC_BECCS[iyear,:] = TEMP_BECCS\n\n                                     Dinf.close(); Ainf.close()\n\n                                     for index in CROP_INDICES:\n                                          NPP_BECCS[iyear,:]  += FRAC_ALL[iyear,index,:]*NPP_ALL[iyear,index,:] \\\n                                                                *0.5*BECCS_harvest_conv*sec_to_year \\\n                                                                /FRAC_CROPS[iyear,:]\n                                                                 \n                                     if iyear == 0 or iyear == nYEARS-1:\n                                         NPP_TEMP            = NPP_BECCS[iyear,:]\n                                         print(YEAR,FRAC_CROPS[iyear,:].min(),FRAC_CROPS[iyear,:].max(), \\\n                                                    FRAC_PAST[iyear,:].min(),FRAC_PAST[iyear,:].max(),   \\\n                                                    FRAC_AGRIC[iyear,:].min(),FRAC_AGRIC[iyear,:].max(), \\\n                                                    FRAC_BECCS[iyear,:].min(),FRAC_BECCS[iyear,:].max() )\n\n                                COMPS[comp][TEMP][Q10][O3[1]]['BECCS_productivity_NPP'][gcm] = NPP_BECCS[0,:]\n                                COMPS[comp][TEMP][Q10][O3[1]]['Trees'][gcm]        = FRAC_TREES  *AREA_1D*m2_to_Mha\n                                COMPS[comp][TEMP][Q10][O3[1]]['Grasses'][gcm]      = FRAC_GRASSES*AREA_1D*m2_to_Mha\n                                COMPS[comp][TEMP][Q10][O3[1]]['Shrubs'][gcm]       = FRAC_SHRUBS *AREA_1D*m2_to_Mha\n                                COMPS[comp][TEMP][Q10][O3[1]]['Agriculture'][gcm]  = FRAC_AGRIC  *AREA_1D*m2_to_Mha\n                                COMPS[comp][TEMP][Q10][O3[1]]['Bioenergy'][gcm]    = FRAC_BECCS  *AREA_1D*m2_to_Mha\n\n                                for iLAND in range(nLAND_PTS):\n                                     NPP_TEMP            = NPP_BECCS[:,iLAND]\n                                     if len(NPP_TEMP[~np.isnan(NPP_TEMP)]) == 0:\n                                         COMPS[comp][TEMP][Q10][O3[1]]['BECCS_productivity_NPP'][gcm][iLAND] = float('nan') \n                                     else: \n                                         COMPS[comp][TEMP][Q10][O3[1]]['BECCS_productivity_NPP'][gcm][iLAND] = NPP_TEMP[~np.isnan(NPP_TEMP)].max() \n\n                                if ('CCS' in comp):\n                                    # Save as numpy file: filename defined earlier (l. 357)\n                                    np.save(BECCS_NPP_FILE,COMPS[comp][TEMP][Q10][O3[1]]['BECCS_productivity_NPP'][gcm])\n                                    print('Writing to: '+BECCS_NPP_FILE)\n\n                                if ('CCS' in comp or 'Nat' in comp):\n                                    # Save as pickle file: filename defined earlier (l. 358)\n                                    SC_NPP_FILE_ID = open(SC_NPP_FILE,'wb')\n                                    print('Writing to: '+SC_NPP_FILE)\n                                    pickle.dump( [ NPP_GB_ALL, SOILC_ALL, SOILC_GB_ALL ], SC_NPP_FILE_ID )\n                                    SC_NPP_FILE_ID.close()\n\n                                    COMPS[comp][TEMP][Q10][O3[1]]['NPP_gb'][gcm]         = NPP_GB_ALL\n                                    COMPS[comp][TEMP][Q10][O3[1]]['Soil_Carbon'][gcm]    = SOILC_ALL\n                                    COMPS[comp][TEMP][Q10][O3[1]]['Soil_Carbon_gb'][gcm] = SOILC_GB_ALL\n\n                                del FRAC,FRAC_ALL,FRAC_TREES,FRAC_GRASSES,FRAC_SHRUBS, \\\n                                    FRAC_CROPS,FRAC_PAST,FRAC_AGRIC,FRAC_BECCS,NPP,NPP_ALL,NPP_TEMP, \\\n                                    NPP_GB, SOILC_ALL, SOILC_GB_ALL\n\n                            else:\n\n                                if ('CCS' in comp):\n                                    # Read from numpy file\n                                    COMPS[comp][TEMP][Q10][O3[1]]['BECCS_productivity_NPP'][gcm] = \\\n                                        deepcopy(COMPS[comp][TEMP][Q10][O3[1]]['BECCS_productivity'][gcm])\n                                    print('Reading from: '+BECCS_NPP_FILE)\n                                    COMPS[comp][TEMP][Q10][O3[1]]['BECCS_productivity_NPP'][gcm] = \\\n                                        np.load(BECCS_NPP_FILE)\n\n                                # Read from pickle file\n                                SC_NPP_FILE_ID = open(SC_NPP_FILE,'rb')\n                                print('Reading from: '+SC_NPP_FILE)\n                                PKL_IN         = pickle.load(SC_NPP_FILE_ID)\n                                COMPS[comp][TEMP][Q10][O3[1]]['NPP_gb'][gcm]         = PKL_IN[0]\n                                COMPS[comp][TEMP][Q10][O3[1]]['Soil_Carbon'][gcm]    = PKL_IN[1]\n                                COMPS[comp][TEMP][Q10][O3[1]]['Soil_Carbon_gb'][gcm] = PKL_IN[2]\n\n                                SC_NPP_FILE_ID.close()\n                                del PKL_IN\n\n                        if not gcm in COMPS[comp][TEMP][Q10][O3[1]]['BECCS_productivity_NPP'].keys():\n                            # Set to zero\n                            COMPS[comp][TEMP][Q10][O3[1]]['BECCS_productivity_NPP'][gcm] = \\\n                                deepcopy(COMPS[comp][TEMP][Q10][O3[1]]['BECCS_productivity'][gcm])\n                            COMPS[comp][TEMP][Q10][O3[1]]['BECCS_productivity_NPP'][gcm][:] = 0.0\n\n                        data_temp = COMPS[comp][TEMP][Q10][O3[1]]['BECCS_productivity_NPP'][gcm]\n                        data_temp = data_temp[MAXBIOFRAC_1D>BIOFRAC_minimum_threshold]\n                        print('NPP mean: ',comp,TEMP,Q10,O3[1],gcm,data_temp.shape,data_temp.mean())\n                        print\n\n                        if ('CCS' in comp or 'Nat' in comp):\n                            # Modify NPP and Soil Carbon:\n                            # Change in variable over time series\n                            \n                            # (1) NPP_gb and convert to tC per hectare per year\n                            var       = 'NPP_gb'\n                            data_temp = COMPS[comp][TEMP][Q10][O3[1]][var][gcm]\n                            print(var,data_temp.shape)\n                            COMPS[comp][TEMP][Q10][O3[1]][var][gcm] = (data_temp[-1,:]-data_temp[0,:]) * \\\n                                sec_to_year\n                            print(var+': ',COMPS[comp][TEMP][Q10][O3[1]][var][gcm][:].min(), \\\n                                           COMPS[comp][TEMP][Q10][O3[1]][var][gcm][:].max() )\n\n                            # (2) Grid-box mean soil carbon and convert to tC per hectare\n                            var       = 'Soil_Carbon_gb'\n                            data_temp = COMPS[comp][TEMP][Q10][O3[1]][var][gcm]\n                            COMPS[comp][TEMP][Q10][O3[1]][var][gcm] = (data_temp[-1,:]-data_temp[0,:])\n                            print(var+': ',COMPS[comp][TEMP][Q10][O3[1]][var][gcm][:].min(), \\\n                                           COMPS[comp][TEMP][Q10][O3[1]][var][gcm][:].max() )\n\n                            # (3) Soil carbon and convert to tC per hectare\n                            var       = 'Soil_Carbon'\n                            data_temp = np.zeros((COMPS[comp][TEMP][Q10][O3[1]][var][gcm].shape[0], \\\n                                                  COMPS[comp][TEMP][Q10][O3[1]][var][gcm].shape[3]))\n                            for iLAYER in range(nLAYERs):\n                                for iPOOL in range(2):\n                                    data_temp[:,:] = data_temp[:,:] + \\\n                                        COMPS[comp][TEMP][Q10][O3[1]][var][gcm][:,iPOOL,iLAYER,:] * \\\n                                        dzsoil[iLAYER]/soil_depth\n                            COMPS[comp][TEMP][Q10][O3[1]][var][gcm] = (data_temp[-1,:]-data_temp[0,:])\n                            print(var+': ',COMPS[comp][TEMP][Q10][O3[1]][var][gcm][:].min(), \\\n                                           COMPS[comp][TEMP][Q10][O3[1]][var][gcm][:].max() )\n\n\n    # Need to create dummy datasets for CH4, \n    # Full set: COMPS_keys    = [ 'CTL', 'CH4', 'LULUC_CCS', 'LULUC_Nat', 'Coupled_CCS', 'Coupled_Nat' ]\n    # CEH  set: COMPS_keys    = [ 'CTL', 'LULUC_CCS', 'LULUC_Nat' ]\n    if PLATFORM == 'CEH':\n        COMPS['CH4']         = deepcopy(COMPS['CTL'])\n        COMPS['Coupled_CCS'] = deepcopy(COMPS['LULUC_CCS'])\n        COMPS['Coupled_Nat'] = deepcopy(COMPS['LULUC_Nat'])\n\n    #ipdb.set_trace()\n    # Create optimised LULUC mitigation option by choosing CCS or return to Natural Vegetation\n    for comp in COMPS_opt:\n        compCCS = comp.replace('opt','CCS')\n        compNat = comp.replace('opt','Nat')\n        # copy _CCS dictionay to _opt\n        COMPS[comp] = deepcopy(COMPS[compCCS])\n        for iTEMP in range(nTEMPs): \n            TEMP=TEMPs[iTEMP]\n            TEMP_tag=TEMP\n            for iQ10 in range(nQ10s):\n                Q10 = Q10_exps[iQ10]\n                for iO3 in range(nO3s):\n                    O3 = Ozone_exps[iO3]\n                    for igcm in range(nGCMs):\n                        gcm=GCMs[igcm]\n                        print('Optimisation: ',comp,TEMP,Q10,O3,gcm)\n                        # create mask, CCS>Nat = 1; CCS==Nat = 0; CCS<Nat = -1 \n                        difference = ( ( COMPS[compCCS][TEMP][Q10][O3[1]]['Land'][gcm]\n                                       + COMPS[compCCS][TEMP][Q10][O3[1]]['CCS'][gcm] )\n                                     - ( COMPS[compNat][TEMP][Q10][O3[1]]['Land'][gcm]\n                                       + COMPS[compNat][TEMP][Q10][O3[1]]['CCS'][gcm] )  )\n                        flag_mask = (difference/np.abs(difference)).astype(int)\n                        flag_mask[difference==0.] = 0\n                        \n                        # Substitute Nat for CCS in land/CCS arrays where Nat is the prefered choice:\n                        for pool in LAND_pools:\n                            COMPS[comp][TEMP][Q10][O3[1]][pool][gcm][flag_mask==-1] = \\\n                                    COMPS[compNat][TEMP][Q10][O3[1]][pool][gcm][flag_mask==-1]\n                        \n                        # Recalculate the Total emission budget:\n                        COMPS[comp][TEMP][Q10][O3[1]]['Total'][gcm] = (\n                                                 COMPS[comp][TEMP][Q10][O3[1]]['Land'][gcm].sum()\n                                               + COMPS[comp][TEMP][Q10][O3[1]]['CCS'][gcm].sum()\n                                               + COMPS[comp][TEMP][Q10][O3[1]]['Atmos'][gcm]\n                                               + COMPS[comp][TEMP][Q10][O3[1]]['Ocean'][gcm] )\n\n                        # Calculate the required scale factor for BECCS to become viable:\n                        #   What scale factor is required for the CCS to be greater than the \n                        #   benefit of returning land to natural vegetaiton?\n                        req_scale_factor = ( COMPS[compNat][TEMP][Q10][O3[1]]['Land'][gcm]\n                                           - COMPS[compCCS][TEMP][Q10][O3[1]]['Land'][gcm])\n                        #ccs_mask = COMPS[compCCS][TEMP][Q10][O3[1]]['CCS'][gcm]>CCS_minimum_threshold\n                        ccs_mask = (MAXBIOFRAC_1D>BIOFRAC_minimum_threshold) \\\n                                & (COMPS[compCCS][TEMP][Q10][O3[1]]['CCS'][gcm]>CCS_minimum_threshold)\n                        req_scale_factor[ccs_mask] /= COMPS[compCCS][TEMP][Q10][O3[1]]['CCS'][gcm][ccs_mask]\n                        req_scale_factor[~ccs_mask] = -1e20\n                        COMPS[comp][TEMP][Q10][O3[1]]['BECCS_ScaleFactor'][gcm] = \\\n                                np.ma.masked_equal(req_scale_factor,-1e20)\n\n                        # Calculate the required productivity for BECCS to become viable:\n                        #   including an efficiency increase of the farm to final store (kappa_efficiency_ratio)\n                        req_BECCS_product = deepcopy( COMPS[comp][TEMP][Q10][O3[1]]['BECCS_productivity'][gcm])\n                        work_scale_factor = deepcopy(req_scale_factor)\n                        #ipdb.set_trace()\n                        work_scale_factor[ccs_mask][work_scale_factor[ccs_mask]<1.0] = 1.0\n                        req_BECCS_product[ccs_mask] = req_BECCS_product[ccs_mask] * work_scale_factor[ccs_mask]\n                        COMPS[comp][TEMP][Q10][O3[1]]['BECCS_productivity'][gcm] = \\\n                                np.ma.masked_equal(req_BECCS_product,-1e20)\n\n                        # Process NPP_gb and Soil Carbon\n                        if comp == 'LULUC_opt':\n                            pool = 'NPP_gb'\n                            COMPS[comp][TEMP][Q10][O3[1]][pool][gcm] = \\\n                                (COMPS[compCCS][TEMP][Q10][O3[1]][pool][gcm] - \\\n                                 COMPS[compNat][TEMP][Q10][O3[1]][pool][gcm])*ccs_mask  \n\n                            pool = 'Soil_Carbon_gb'\n                            COMPS[comp][TEMP][Q10][O3[1]][pool][gcm] = \\\n                                (COMPS[compCCS][TEMP][Q10][O3[1]][pool][gcm] - \\\n                                 COMPS[compNat][TEMP][Q10][O3[1]][pool][gcm])*ccs_mask  \n\n                            pool = 'Soil_Carbon'\n                            COMPS[comp][TEMP][Q10][O3[1]][pool][gcm] = \\\n                                (COMPS[compCCS][TEMP][Q10][O3[1]][pool][gcm] - \\\n                                 COMPS[compNat][TEMP][Q10][O3[1]][pool][gcm])*ccs_mask  \n\n    for comp in COMPS_keys_all:\n        CH4 = COMPS[comp]['config'].split('_')[0]\n\n        pools_pkl = deepcopy(pools)\n\n        if comp in [ 'CTL', 'CH4', 'LULUC_CCS', 'LULUC_Nat', 'Coupled_CCS', 'Coupled_Nat' ]:\n            del pools_pkl[pools_pkl.index('BECCS_ScaleFactor')]\n        if comp in [ 'CTL', 'CH4' ]:\n            for pool in SOIL_pools: del pools_pkl[pools_pkl.index(pool)]\n\n        for pool in LAND_TYPES+AREA_pools: del pools_pkl[pools_pkl.index(pool)]\n\n        for iTEMP in range(nTEMPs): \n            TEMP=TEMPs[iTEMP]\n            TEMP_tag=TEMP\n            for iQ10 in range(nQ10s):\n                Q10 = Q10_exps[iQ10]\n                for iO3 in range(nO3s):\n                    O3 = Ozone_exps[iO3]\n                    for igcm in range(nGCMs):\n                        gcm=GCMs[igcm]\n\n                        # Save COMPS[comp][TEMP][Q10][O3[1]][pool][gcm] as pickle file\n                        COMPS_FILE     = COMPS_npy_DIR+comp+'_'+CH4+'_'+O3[1]+'_'+Q10+'_'+gcm+'_'+TEMP_tag+'_processed.pkl'\n                        COMPS_FILE_ID  = open(COMPS_FILE,'wb')\n                        print('Writing to: '+COMPS_FILE)\n                        pickle.dump( [ COMPS[comp][TEMP][Q10][O3[1]][pool][gcm] for pool in pools_pkl ], COMPS_FILE_ID )\n                        COMPS_FILE_ID.close()\n\n    # Land use: subtract baseline run\n\n    for comp in ['LULUC_CCS', 'LULUC_Nat']:\n        COMPS_DIFF[comp] = deepcopy(COMPS['CTL'])\n        for itemp in range(nTEMPs):\n            temp=TEMPs[itemp]\n            for iQ10 in range(nQ10s):\n                Q10 = Q10_exps[iQ10]\n                for iO3 in range(nO3s):\n                    O3 = Ozone_exps[iO3]\n                    for igcm in range(nGCMs):\n                        gcm=GCMs[igcm]\n                        #print(gcm)\n                        for land_type in LAND_TYPES:\n                            print(land_type,COMPS_DIFF[comp][temp][Q10][O3[1]][land_type], \\\n                                            COMPS[comp][temp][Q10][O3[1]][land_type], \\\n                                            COMPS['CTL'][temp][Q10][O3[1]][land_type])\n                            COMPS_DIFF[comp][temp][Q10][O3[1]][land_type][gcm] = \\\n                                COMPS[comp][temp][Q10][O3[1]][land_type][gcm] - \\\n                                COMPS['CTL'][temp][Q10][O3[1]][land_type][gcm]\n\n\n    # Save land use data into numpy file\n\n    for itemp in range(nTEMPs):\n        temp= TEMPs[itemp]\n        for iQ10 in range(nQ10s):\n            Q10 = Q10_exps[iQ10]\n            for iO3 in range(nO3s):\n                O3 = Ozone_exps[iO3]\n                for igcm in range(nGCMs):\n                    gcm=GCMs[igcm]\n                    for itype in range(nLAND_TYPES):\n                        land_type=LAND_TYPES[itype]\n\n                        # Regional Breakdown of the area\n                        for iregion in range(nREGIONs_DICT):\n                            region =REGION_dict['Name'][iregion]\n                            region_mask=REGIONS_1D==(iregion+1)\n                            if region=='Global': region_mask[:]=True\n                            if region=='International Transportation': region_mask[:]=False\n\n                            for iyear in range(nYEARS):\n                                LAND_REGION[0,itemp,iregion,itype,iyear,igcm,iQ10,iO3]   = \\\n                                     COMPS_DIFF['LULUC_CCS'][temp][Q10][O3[1]][land_type][gcm][iyear,region_mask].sum()\n\n                                LAND_REGION[1,itemp,iregion,itype,iyear,igcm,iQ10,iO3]   = \\\n                                     COMPS_DIFF['LULUC_Nat'][temp][Q10][O3[1]][land_type][gcm][iyear,region_mask].sum()\n\n                                LAND_LANDPTS[0,itemp,itype,iyear,igcm,iQ10,iO3,:]        = \\\n                                     COMPS_DIFF['LULUC_CCS'][temp][Q10][O3[1]][land_type][gcm][iyear,:]\n\n                                LAND_LANDPTS[1,itemp,itype,iyear,igcm,iQ10,iO3,:]        = \\\n                                     COMPS_DIFF['LULUC_Nat'][temp][Q10][O3[1]][land_type][gcm][iyear,:]\n\n    # Save by GCM\n    for igcm in range(nGCMs):\n        gcm=GCMs[igcm]\n\n        FILE_LAND_NUMPY    = LAND_npy_DIR+FILE_PART+gcm+'.npy'\n        FILE_LAND_NUMPY2   = LAND_npy_DIR+FILE_PART2+gcm+'.npy'\n\n        np.save(FILE_LAND_NUMPY,LAND_REGION[:,:,:,:,:,igcm,:,:])\n        np.save(FILE_LAND_NUMPY2,LAND_LANDPTS[:,:,:,:,igcm,:,:,:])\n\n    # No plotting if saving to NPP numpy files\n    print('Stopping without plots') \n    quit()\n\nelif PROC_STEP == 'Use':\n\n    # Need to create dummy datasets for CH4, \n    # Full set: COMPS_keys    = [ 'CTL', 'CH4', 'LULUC_CCS', 'LULUC_Nat', 'Coupled_CCS', 'Coupled_Nat' ]\n    # CEH  set: COMPS_keys    = [ 'CTL', 'LULUC_CCS', 'LULUC_Nat' ]\n    if PLATFORM == 'CEH':\n        # COMPS['CH4']         = deepcopy(COMPS['CTL'])\n        # COMPS['Coupled_CCS'] = deepcopy(COMPS['LULUC_CCS'])\n        # COMPS['Coupled_Nat'] = deepcopy(COMPS['LULUC_Nat'])\n        COMPS['Coupled_CCS'] = deepcopy(COMPS['CH4'])\n        COMPS['Coupled_Nat'] = deepcopy(COMPS['CH4'])\n\n    COMPS['LULUC_opt']   = deepcopy(COMPS['LULUC_CCS'])\n    COMPS['Coupled_opt'] = deepcopy(COMPS['Coupled_CCS'])\n\n    for comp in COMPS_keys_all:\n        CH4 = COMPS[comp]['config'].split('_')[0]\n\n        pools_pkl = deepcopy(pools)\n        if comp in [ 'CTL', 'CH4', 'LULUC_CCS', 'LULUC_Nat', 'Coupled_CCS', 'Coupled_Nat' ]:\n            del pools_pkl[pools_pkl.index('BECCS_ScaleFactor')]\n        if comp in [ 'CTL', 'CH4' ]:\n            for pool in SOIL_pools: del pools_pkl[pools_pkl.index(pool)]\n\n        for pool in LAND_TYPES+AREA_pools: del pools_pkl[pools_pkl.index(pool)]\n\n        for iTEMP in range(nTEMPs): \n            TEMP=TEMPs[iTEMP]\n            TEMP_year=TEMP_years[iTEMP]\n            TEMP_tag=TEMP\n            COMPS[comp][TEMP]={}\n            for iQ10 in range(nQ10s):\n                Q10 = Q10_exps[iQ10]\n                COMPS[comp][TEMP][Q10]={}\n                for iO3 in range(nO3s):\n                    O3 = Ozone_exps[iO3]\n                    COMPS[comp][TEMP][Q10][O3[1]]={ pool:{} for pool in pools  }  #+land_opt_pools }\n                    config=COMPS[comp]['config'].replace('OZONESUB',O3[1])\n                    runid=COMPS[comp]['runid'].replace('OZONESUB',O3[0])\n                    print('GCM Input:',comp,TEMP,TEMP_year,Q10,config,runid)\n                    for igcm in range(nGCMs):\n                        gcm=GCMs[igcm]\n\n                        # Read from pickle file\n                        COMPS_FILE     = COMPS_npy_DIR+comp+'_'+CH4+'_'+O3[1]+'_'+Q10+'_'+gcm+'_'+TEMP_tag+'_processed.pkl'\n                        COMPS_FILE_ID  = open(COMPS_FILE,'rb')\n                        print('Reading from:'+COMPS_FILE)\n                        PKL_LOAD       = pickle.load(COMPS_FILE_ID)\n\n                        for ipool, pool in enumerate(pools_pkl):\n                            COMPS[comp][TEMP][Q10][O3[1]][pool][gcm] = PKL_LOAD[ipool]\n    \n                            if (pool in [ 'BECCS_productivity_JULES','BECCS_productivity' ]) and DEBUG == \"Y\":\n                                for iregion in REGION_idx:\n                                    region            = REGION_dict['Name'][iregion]\n                                    region_mask       = REGIONS_1D==(iregion+1)\n                                    if region=='Global': region_mask[:]=True\n                                    if region=='International Transportation': region_mask[:]=False\n    \n                                    if len(COMPS[comp][TEMP][Q10][O3[1]][pool][gcm][region_mask]) > 0:\n                                        print(comp,TEMP,Q10,O3[1],pool,gcm,region, \\\n                                            np.min(COMPS[comp][TEMP][Q10][O3[1]][pool][gcm][region_mask]), \\\n                                            np.max(COMPS[comp][TEMP][Q10][O3[1]][pool][gcm][region_mask]) )\n                                    else:\n                                        print(comp,TEMP,Q10,O3[1],pool,gcm,region)\n\n                        COMPS_FILE_ID.close()\n                        del PKL_LOAD\n\n    # Input land use data from numpy file\n    # Saved by GCM\n    for igcm in range(nGCMs):\n        gcm=GCMs[igcm]\n\n        FILE_LAND_NUMPY    = LAND_npy_DIR+FILE_PART+gcm+'.npy'\n        print('Reading from: '+FILE_LAND_NUMPY)\n        LAND_ID      = open(FILE_LAND_NUMPY,'rb')\n        LAND_FILE    = np.load(LAND_ID)\n        LAND_ID.close()\n        LAND_REGION[:,:,:,:,:,igcm,:,:] = LAND_FILE\n\n        FILE_LAND_NUMPY2   = LAND_npy_DIR+FILE_PART2+gcm+'.npy'\n        print('Reading from: '+FILE_LAND_NUMPY2)\n        LAND_ID      = open(FILE_LAND_NUMPY2,'rb')\n        LAND_FILE    = np.load(LAND_ID)\n        LAND_ID.close()\n        LAND_LANDPTS[:,:,:,:,igcm,:,:,:] = LAND_FILE\n        \n    del LAND_FILE\n\n# For each IMAGE region, identify year of maximum bioenergy land use\nBECCS_year   = np.zeros((nTEMPs,nREGIONs_DICT))\nitype        = LAND_TYPES.index('Bioenergy')\n      \n# Need to assign BECCS_AREA from LAND_LANDPTS\nfor iCOMP,COMP in enumerate(['LULUC_CCS','LULUC_Nat']):\n    for itemp in range(nTEMPs): \n        TEMP=TEMPs[itemp]\n        for iQ10 in range(nQ10s):\n            Q10 = Q10_exps[iQ10]\n            for iO3 in range(nO3s):\n                O3 = Ozone_exps[iO3]\n                COMPS[COMP]['config'].replace('OZONESUB',O3[1])\n                COMPS[COMP]['runid'].replace('OZONESUB',O3[0])\n                for igcm in range(nGCMs):\n                    gcm=GCMs[igcm]\n\n                    iyear_max = np.where(LAND_REGION[0,itemp,-1,itype,:,igcm,iQ10,iO3] == \\\n                        LAND_REGION[0,itemp,-1,itype,:,igcm,iQ10,iO3].max())[0]\n\n                    COMPS[COMP][TEMP][Q10][O3[1]]['BECCS_Area'][gcm] = \\\n                            LAND_LANDPTS[iCOMP,itemp,itype,iyear_max,igcm,iQ10,iO3,:].squeeze()\n\n                    if DEBUG == 'Y':\n                        for iregion in REGION_idx:\n                            region            = REGION_dict['Name'][iregion]\n                            region_mask       = REGIONS_1D==(iregion+1)\n                            if region=='Global': region_mask[:]=True\n                            if region=='International Transportation': region_mask[:]=False\n\n                            print(iCOMP,COMP,TEMP,Q10,O3,region, \\\n                                 COMPS[COMP][TEMP][Q10][O3[1]]['BECCS_Area'][gcm][region_mask].sum())\n\n                if COMP == 'LULUC_CCS':\n                    print('LULUC_CCS')\n                    COMPS['Coupled_CCS'][TEMP][Q10][O3[1]]['BECCS_Area'] = deepcopy(COMPS[COMP][TEMP][Q10][O3[1]]['BECCS_Area'])\n                    COMPS['LULUC_opt'][TEMP][Q10][O3[1]]['BECCS_Area']   = deepcopy(COMPS[COMP][TEMP][Q10][O3[1]]['BECCS_Area'])\n                    COMPS['Coupled_opt'][TEMP][Q10][O3[1]]['BECCS_Area'] = deepcopy(COMPS[COMP][TEMP][Q10][O3[1]]['BECCS_Area'])\n                if COMP == 'LULUC_Nat':\n                    print('LULUC_Nat')\n                    COMPS['Coupled_Nat'][TEMP][Q10][O3[1]]['BECCS_Area'] = deepcopy(COMPS[COMP][TEMP][Q10][O3[1]]['BECCS_Area'])\n\n# From PLOT_MitigationOptions_synthesis_RRv1.4.py\n################################################################################\n\ndelCStores              = { TEMP: {} for TEMP in TEMPs }\ndelCStores_unc          = { TEMP: {} for TEMP in TEMPs }\n\ndelCStores_regions      =  { TEMP: { region : { Q10: {} for Q10 in Q10_exps } \n                                     for region in REGION_dict['Name'] } \n                                     for TEMP in TEMPs }\ndelCStores_regions_unc  =  { TEMP: { region : [] for region in REGION_dict['Name'] } \n                             for TEMP in TEMPs }\n\nSummaryFactExps         = ['CTL','CH4','LULUC_opt','Coupled_opt']\nFactExps                = ['CTL','CH4',\n                           'LULUC_CCS','LULUC_Nat','LULUC_opt',\n                           'Coupled_CCS','Coupled_Nat','Coupled_opt']\n\nregional_DF_columns     = [ 'CH4_mit', 'NatLand_mit', 'CCS_mit', 'LULUC_mit' ]\nnREGcolumns             = len(regional_DF_columns)\n\nStoreSinks              = ['Atmos','Ocean','Land','CCS']\ndelCStores_SINKS        = { TEMP: { } for TEMP in TEMPs }\ndelCStores_SINKS_unc    = { TEMP: { exp:[] for exp in FactExps } for TEMP in TEMPs }\ndelCStores_mitSINKS_unc = { TEMP: { exp:[] for exp in FactExps } for TEMP in TEMPs }\n\nos.system('mkdir -p '+PLOT_DIR+'CSVoutput/')\nprint('Storing basic stats in: '+PLOT_DIR+'CSVoutput/Mitigation_Summary_Region.csv')\n\noutf       = open(PLOT_DIR+'CSVoutput/Mitigation_Summary_Global.csv','w')\noutfreg    = open(PLOT_DIR+'CSVoutput/Mitigation_Summary_Region.csv','w')\noutfunc    = open(PLOT_DIR+'CSVoutput/Mitigation_Summary_FullUnc.csv','w')\noutfuncreg = open(PLOT_DIR+'CSVoutput/Mitigation_Summary_FullUnc_Reg.csv','w')\noutfsink   = open(PLOT_DIR+'CSVoutput/Mitigation_Summary_Sink_FullUnc.csv','w')\n\n#ipdb.set_trace()\nfor itemp in range(nTEMPs):\n    TEMP= TEMPs[itemp]\n    scen_list = []\n    for iQ10 in range(nQ10s):\n        Q10 = Q10_exps[iQ10]\n        delCStores[TEMP][Q10]={}\n        delCStores_SINKS[TEMP][Q10] = {}\n        for iO3 in range(nO3s):\n            O3 = Ozone_exps[iO3]\n            outf.write('%-30s'%(TEMP+', '+Q10+', '+O3[1]+':\\n'))\n            outfreg.write('%-30s'%(TEMP+', '+Q10+', '+O3[1]+':\\n'))\n            outfreg.write('%-30s:'%('Region') + nREGcolumns*'%10s,' % tuple(regional_DF_columns)+'\\n')\n            \n            # Global Emission budgets and mitigation potentials\n            # Budgets:\n            DataFrame_Tots         = pd.concat( [pd.Series(COMPS[factexp][TEMP][Q10][O3[1]]['Total'], index=GCMs)\n                                                           for factexp in FactExps ], axis=1 )\n            DataFrame_Tots.columns = [ factexp+'_tot' for factexp in FactExps ]\n\n            # Mitigation (difference from control)\n            DataFrame_Mits         = deepcopy(DataFrame_Tots)\n            for col in DataFrame_Tots.columns: DataFrame_Mits[col] -= DataFrame_Tots['CTL_tot']\n            DataFrame_Mits.columns = [ factexp+'_mit' for factexp in FactExps ]\n            \n            DF                     = pd.concat([DataFrame_Tots,DataFrame_Mits],axis=1)\n\n            delCStores[TEMP][Q10][O3[1]] = DF\n            DF.describe().to_csv(outf,float_format='%10.2f')\n            scen_list.append(DF) \n            \n            # Global Sinks:\n            delCStores_SINKS[TEMP][Q10][O3[1]] = {}\n            for exp in FactExps:\n                #print(exp)\n                delCStores_SINKS[TEMP][Q10][O3[1]][exp] = pd.DataFrame( \n                            { sink: pd.Series({gcm:COMPS[exp][TEMP][Q10][O3[1]][sink][gcm].sum() \n                                for gcm in GCMs } ) for sink in StoreSinks }  ) \n                # Append to full uncertatinty lists:\n                delCStores_SINKS_unc[TEMP][exp].append(delCStores_SINKS[TEMP][Q10][O3[1]][exp])\n                delCStores_mitSINKS_unc[TEMP][exp].append( delCStores_SINKS[TEMP][Q10][O3[1]][exp] \n                                                          -delCStores_SINKS[TEMP][Q10][O3[1]]['CTL'] )\n\n            # Land uptake on land points\n            LULUC_mit_landpts = { gcm: COMPS['LULUC_opt'][TEMP][Q10][O3[1]]['Land'][gcm]\n                                     - COMPS['CTL'][TEMP][Q10][O3[1]]['Land'][gcm] for gcm in GCMs}\n            CCS_mit_landpts   = {gcm:  COMPS['LULUC_opt'][TEMP][Q10][O3[1]]['CCS'][gcm]\n                                     - COMPS['CTL'][TEMP][Q10][O3[1]]['CCS'][gcm] for gcm in GCMs}\n            Total_Land_C_med  = (  np.median( [LULUC_mit_landpts[gcm] for gcm in GCMs], axis=0 )\n                                 + np.median( [CCS_mit_landpts[gcm] for gcm in GCMs], axis=0 ) )\n                         \n            # Regional Breakdown of the mitigaiton options\n            for iregion in range(REGION_dict['Nregions']):\n                region            = REGION_dict['Name'][iregion]\n                region_anthFrac   = REGION_dict['AnthroFraction'][iregion]\n                #region_map_index = REGION_dict['Index'][iregion]  #Not required as stored in oreder of map index\n                region_mask       = REGIONS_1D==(iregion+1)\n\n                if region=='Global':                       region_mask[:]=True\n                if region=='International Transportation': region_mask[:]=False\n\n                regional_CH4_mit   = DF['CH4_mit']*region_anthFrac\n                regional_Land_mit  = pd.Series({gcm:LULUC_mit_landpts[gcm][region_mask].sum() for gcm in GCMs} ) \n                regional_CCS_mit   = pd.Series({gcm:CCS_mit_landpts[gcm][region_mask].sum() for gcm in GCMs } ) \n                regional_LULUC_mit = regional_CCS_mit+regional_Land_mit\n                DFreg              = pd.concat([regional_CH4_mit,regional_Land_mit,regional_CCS_mit,\n                                                regional_LULUC_mit], axis=1) \n                DFreg.columns      = regional_DF_columns\n                delCStores_regions[TEMP][region][Q10][O3[1]] = DFreg\n                delCStores_regions_unc[TEMP][region].append(\n                                       delCStores_regions[TEMP][region][Q10][O3[1]] )\n                outfreg.write('%-30s: '%(region))\n                DFreg.describe()[5:6].to_csv(outfreg,header=False,float_format='%10.2f',index=False)\n                #print(region, DFreg.describe()[5:6])\n    \n    # compend Global Carbon Stores, full uncertainty to DataFrame and output to csv\n    delCStores_unc[TEMP] = pd.concat(scen_list)\n    outfunc.write(TEMP+': \\n')\n    outfunc.write('Global: \\n')\n    delCStores_unc[TEMP].describe().to_csv(outfunc,float_format='%10.2f')\n    \n    # Compend the global carbon stores by pool to DataFrame and output to csv \n    delCStores_SINKS_unc[TEMP] = pd.concat( { EXP: pd.concat(delCStores_SINKS_unc[TEMP][EXP]) \n                                                  for EXP in FactExps }, axis=1)\n    delCStores_mitSINKS_unc[TEMP] = pd.concat( { EXP: pd.concat(delCStores_mitSINKS_unc[TEMP][EXP]) \n                                                     for EXP in FactExps }, axis=1)\n    outfsink.write(TEMP+': \\n')\n    outfsink.write('Total Sink: \\n')\n    for EXP in FactExps: \n        outfsink.write('%16s'%(EXP+': \\n'))\n        delCStores_SINKS_unc[TEMP][EXP].describe().to_csv(outfsink,float_format='%10.2f')\n    outfsink.write('Mitigation Potential: \\n')\n    for EXP in FactExps: \n        outfsink.write('%16s'%(EXP+': \\n'))\n        delCStores_mitSINKS_unc[TEMP][EXP].describe().to_csv(outfsink,float_format='%10.2f')\n\n    # Compend the regional breakdown into DataFrame: \n    delCStores_regions_unc[TEMP] = pd.concat({ region: pd.concat(delCStores_regions_unc[TEMP][region])\n                                                    for region in REGION_dict['Name'] }, axis=1 )\n    # Output regional breakdown to csv file \n    outfuncreg.write(TEMP+': \\nMedian of GCMs:\\n')\n    outfuncreg.write('%-30s '%('Region,')+nREGcolumns*'%9s,' % tuple(regional_DF_columns)+'\\n')\n    for region in REGION_dict['Name']: \n        outfuncreg.write('%-30s '%(region+','))\n        delCStores_regions_unc[TEMP][region].describe()[5:6].to_csv(outfuncreg,float_format='%10.2f',\n                                                                         header=False,index=False)\n    outfuncreg.write('\\n\\n\\n25% of GCMs: \\n')\n    outfuncreg.write('%-30s '%('Region,')+nREGcolumns*'%9s,' % tuple(regional_DF_columns)+'\\n')\n    for region in REGION_dict['Name']: \n        outfuncreg.write('%-30s '%(region+','))\n        delCStores_regions_unc[TEMP][region].describe()[4:5].to_csv(outfuncreg,float_format='%10.2f',\n                                                                         header=False,index=False)\n    outfuncreg.write('\\n\\n\\n75% of GCMs: \\n')\n    outfuncreg.write('%-30s '%('Region,')+nREGcolumns*'%9s,' % tuple(regional_DF_columns)+'\\n')\n    for region in REGION_dict['Name']: \n        outfuncreg.write('%-30s '%(region+','))\n        delCStores_regions_unc[TEMP][region].describe()[6:7].to_csv(outfuncreg,float_format='%10.2f',\n                                                                         header=False,index=False)\n\noutfunc.close()\noutfuncreg.close()\noutfsink.close()\noutf.close()\noutfreg.close()\n\n# BECCS additional analysis\n# Produce output for BECCS scale factors (BECCS_multiplier) from 1 to 4\n\nEXTRA_pools_1   = [ 'BECCS_productivity_JULES','BECCS_productivity',    'BECCS_ScaleFactor' ]\nEXTRA_pools_tx1 = [ 'BECCS Productivity',      'Required Productivity', 'Required Scale Factor' ]\nEXTRA_pools_2   = [ 'BECCS_Area',    'CCS',     'Land' ]\nEXTRA_pools_tx2 = [ 'Area of BECCS', 'BECCS C', 'Land C' ]\nEXTRA_pools     = EXTRA_pools_1   + EXTRA_pools_2\nEXTRA_pools_txt = EXTRA_pools_tx1 + EXTRA_pools_tx2\n#EXTRA_pools    = [ 'BECCS_Area' ]\nnEXTRA          = len(EXTRA_pools)\n\nBECCS_SFs   = [ 1, 2, 3, 4 ]\n#BECCS_SFs   = [ 1, 3 ] \nnBECCS_SFs  = len(BECCS_SFs)\n\nEXTRA_global  = { TEMP: { BECCS_SF: { Q10: {} for Q10 in Q10_exps } \n                          for BECCS_SF in BECCS_SFs }\n                          for TEMP in TEMPs }\n\nEXTRA_region  = { TEMP: { BECCS_SF: { pool : { region: []\n                          for region in REGION_dict['Name'] }\n                          for pool in EXTRA_pools } \n                          for BECCS_SF in BECCS_SFs }\n                          for TEMP in TEMPs }\n\nEXTRA_output  = { TEMP: { BECCS_SF: []\n                          for BECCS_SF in BECCS_SFs }\n                          for TEMP in TEMPs }\n\n\ncomp    = 'LULUC_opt'\ncompCCS = comp.replace('opt','CCS')\ncompNat = comp.replace('opt','Nat')\n\nfor itemp in range(nTEMPs): \n    TEMP    = TEMPs[itemp]\n    for BECCS_SF in BECCS_SFs:\n        BECCS_multiplier = float(BECCS_SF)\n        for iQ10 in range(nQ10s):\n            Q10 = Q10_exps[iQ10]\n            EXTRA_global[TEMP][BECCS_SF][Q10] = {Ozone_exps[iO3][1]: {} for iO3 in range(nO3s) }\n            for iO3 in range(nO3s):\n                O3 = Ozone_exps[iO3]\n                EXTRA_global[TEMP][BECCS_SF][Q10][O3[1]] = {pool: {} for pool in EXTRA_pools}\n                for igcm in range(nGCMs):\n                    gcm=GCMs[igcm]\n\n                    # create mask, CCS>Nat = 1; CCS==Nat = 0; CCS<Nat = -1 \n                    difference = ( ( COMPS[compCCS][TEMP][Q10][O3[1]]['Land'][gcm]\n                                   + COMPS[compCCS][TEMP][Q10][O3[1]]['CCS'][gcm]*BECCS_multiplier )\n                                 - ( COMPS[compNat][TEMP][Q10][O3[1]]['Land'][gcm]\n                                   + COMPS[compNat][TEMP][Q10][O3[1]]['CCS'][gcm] )  )\n\n                    flag_mask = (difference/np.abs(difference)).astype(int)\n                    flag_mask[difference==0.] = 0\n                    \n                    # Calculate the required scale factor for BECCS to become viable:\n                    # What scale factor is required for the CCS to be greater than the \n                    # benefit of returning land to natural vegetaiton?\n                    req_scale_factor = ( COMPS[compNat][TEMP][Q10][O3[1]]['Land'][gcm]\n                                       - COMPS[compCCS][TEMP][Q10][O3[1]]['Land'][gcm])\n                    ccs_mask         = (MAXBIOFRAC_1D>BIOFRAC_minimum_threshold) \\\n                         & (COMPS[compCCS][TEMP][Q10][O3[1]]['CCS'][gcm]>CCS_minimum_threshold)\n                    req_scale_factor[ccs_mask] /= COMPS[compCCS][TEMP][Q10][O3[1]]['CCS'][gcm][ccs_mask]\n                    req_scale_factor[~ccs_mask] = -1e20\n                    COMPS[comp][TEMP][Q10][O3[1]]['BECCS_ScaleFactor'][gcm] = \\\n                         np.ma.masked_equal(req_scale_factor,-1e20)\n                    if DEBUG == \"Y\": print(TEMP,BECCS_SF,Q10,O3,gcm,'BECCS_ScaleFactor', \\\n                        np.min(COMPS[comp][TEMP][Q10][O3[1]]['BECCS_ScaleFactor'][gcm]),\n                        np.min(COMPS[comp][TEMP][Q10][O3[1]]['BECCS_ScaleFactor'][gcm]))\n\n                    # Substitute Nat for CCS in land/CCS arrays where Nat is the prefered choice\n                    for pool in EXTRA_pools:\n                        if DEBUG == \"Y\": print(comp,TEMP,Q10,O3,pool,gcm)\n\n                        if pool in EXTRA_pools_2:\n                            COMPS[comp][TEMP][Q10][O3[1]][pool][gcm][flag_mask!=-1] = \\\n                                deepcopy(COMPS[compCCS][TEMP][Q10][O3[1]][pool][gcm][flag_mask!=-1])\n                            COMPS[comp][TEMP][Q10][O3[1]][pool][gcm][flag_mask==-1] = \\\n                                deepcopy(COMPS[compNat][TEMP][Q10][O3[1]][pool][gcm][flag_mask==-1])\n\n                        # Subtract \"CTL\" for 'Land' pool to get mitigation potential\n                        if pool == 'Land':\n                            EXTRA_global[TEMP][BECCS_SF][Q10][O3[1]][pool][gcm] = \\\n                                COMPS[comp][TEMP][Q10][O3[1]][pool][gcm]-COMPS['CTL'][TEMP][Q10][O3[1]][pool][gcm]\n                            print('Land',np.sum(EXTRA_global[TEMP][BECCS_SF][Q10][O3[1]][pool][gcm]), \\\n                                         np.sum(COMPS[comp][TEMP][Q10][O3[1]][pool][gcm]), \\\n                                         np.sum(COMPS['CTL'][TEMP][Q10][O3[1]][pool][gcm]))\n                        elif pool == 'CCS':\n                            EXTRA_global[TEMP][BECCS_SF][Q10][O3[1]][pool][gcm] = deepcopy( \\\n                               COMPS[comp][TEMP][Q10][O3[1]][pool][gcm]*BECCS_multiplier )\n                        else:\n                            EXTRA_global[TEMP][BECCS_SF][Q10][O3[1]][pool][gcm] = deepcopy( \\\n                               COMPS[comp][TEMP][Q10][O3[1]][pool][gcm] )\n\n                        if pool == 'BECCS_Area' and DEBUG == 'Y':\n                            print(TEMP,BECCS_SF,Q10,O3,pool,len(flag_mask[flag_mask ==-1]),\n                                  len(flag_mask[flag_mask ==0]),len(flag_mask[flag_mask ==1]), \\\n                                  COMPS[compCCS][TEMP][Q10][O3[1]]['Land'][gcm].sum(), \\\n                                  COMPS[compCCS][TEMP][Q10][O3[1]]['CCS'][gcm].sum()*BECCS_multiplier, \\\n                                  COMPS[compNat][TEMP][Q10][O3[1]]['Land'][gcm].sum(), \\\n                                  COMPS[compNat][TEMP][Q10][O3[1]]['CCS'][gcm].sum())\n\n                            for i in range(len(COMPS[comp][TEMP][Q10][O3[1]][pool][gcm][:])):\n                                iregion = REGIONS_1D[i]\n                                print(i,iregion,REGION_dict['Name'][iregion-1],flag_mask[i],difference[i], \\\n                                   COMPS[comp][TEMP][Q10][O3[1]][pool][gcm][i], \\\n                                   COMPS[compCCS][TEMP][Q10][O3[1]][pool][gcm][i], \\\n                                   COMPS[compNat][TEMP][Q10][O3[1]][pool][gcm][i],\n                                   LAND_LANDPTS[0,itemp,itype,:,igcm,iQ10,iO3,i].max())\n\n                    if DEBUG == \"Y\":\n                        for pool in EXTRA_pools:\n                            for iregion in REGION_idx:\n                                region            = REGION_dict['Name'][iregion]\n                                region_mask       = REGIONS_1D==(iregion+1)\n                                if region=='Global': region_mask[:]=True\n                                if region=='International Transportation': region_mask[:]=False\n\n                                print(comp,TEMP,BECCS_SF,Q10,O3,pool,region)\n                                if pool == 'BECCS_ScaleFactor':\n                                    print(np.max(EXTRA_global[TEMP][BECCS_SF][Q10][O3[1]][pool][gcm][region_mask]))\n                                elif pool in EXTRA_pools_1:\n                                    print(np.max(EXTRA_global[TEMP][BECCS_SF][Q10][O3[1]][pool][gcm][region_mask]), \\\n                                       np.max(COMPS[compCCS][TEMP][Q10][O3[1]][pool][gcm][region_mask]), \\\n                                       np.max(COMPS[compNat][TEMP][Q10][O3[1]][pool][gcm][region_mask]))\n                                elif pool in EXTRA_pools_2:\n                                    print(np.sum(EXTRA_global[TEMP][BECCS_SF][Q10][O3[1]][pool][gcm][region_mask]), \\\n                                       np.sum(COMPS[compCCS][TEMP][Q10][O3[1]][pool][gcm][region_mask]), \\\n                                       np.sum(COMPS[compNat][TEMP][Q10][O3[1]][pool][gcm][region_mask]))\n\nprint(\"\\n\")\nprint('EXTRA_global: loaded')\n\nfor itemp in range(nTEMPs): \n    TEMP    = TEMPs[itemp]\n    for BECCS_SF in BECCS_SFs:\n        BECCS_multiplier = float(BECCS_SF)\n        for pool in EXTRA_pools:\n       \n            # Regional Breakdown\n            for iregion in REGION_idx:\n                region            = REGION_dict['Name'][iregion]\n                region_mask       = REGIONS_1D==(iregion+1)\n\n                if region=='Global':                       region_mask[:]=True\n                if region=='International Transportation': region_mask[:]=False\n\n                for iQ10 in range(nQ10s):\n                    Q10 = Q10_exps[iQ10]\n                    for iO3 in range(nO3s):\n                        O3 = Ozone_exps[iO3]\n                        for igcm in range(nGCMs):\n                            gcm=GCMs[igcm]\n\n                            if pool in EXTRA_pools_1:\n                                REGION_DATA  = EXTRA_global[TEMP][BECCS_SF][Q10][O3[1]][pool][gcm][region_mask]\n                                EXTRA_region[TEMP][BECCS_SF][pool][region] = np.append( \\\n                                   EXTRA_region[TEMP][BECCS_SF][pool][region], \\\n                                   REGION_DATA[REGION_DATA > 0.0])\n                                if DEBUG == \"Y\":\n                                    print(TEMP,BECCS_SF,region,Q10,O3[1],pool,gcm, \\\n                                       len(REGION_DATA),REGION_DATA.min(),REGION_DATA.max())\n\n                            if pool in EXTRA_pools_2:\n                                EXTRA_region[TEMP][BECCS_SF][pool][region] = np.append( \\\n                                   EXTRA_region[TEMP][BECCS_SF][pool][region], \\\n                                   np.sum(EXTRA_global[TEMP][BECCS_SF][Q10][O3[1]][pool][gcm][region_mask]))\n                                if DEBUG == \"Y\":\n                                    print(TEMP,BECCS_SF,region,Q10,O3[1],pool,gcm, \\\n                                       EXTRA_global[TEMP][BECCS_SF][Q10][O3[1]][pool][gcm][region_mask].sum())\n\nprint(\"\\n\")\nprint('EXTRA_regional: loaded')\nFILE_CSV    = PLOT_DIR+'BECCS_Extra_'+FILE_PART3+'.csv'\nprint('Writing to: '+FILE_CSV)\nOUT_FID     = open(FILE_CSV,'w')\n\nfor itemp in range(nTEMPs): \n    TEMP        = TEMPs[itemp]\n    OUT_TEXT1   = ('%-10s') % TEMP\n    OUT_FID.write(OUT_TEXT1+'\\n')\n\n    OUT_TEXT1   = ',,,,,'\n    OUT_TEXT2   = 'Region,Max BECCS Area,BECCS_Productivity,Required_Productivity,Required Scale Factor,'\n    for BECCS_SF in BECCS_SFs:\n        OUT_TEXT1   = OUT_TEXT1 + '%s' % ('BECCS scale factor = '+str(BECCS_SF))\n        for pool in EXTRA_pools_tx2:\n            OUT_TEXT1   = OUT_TEXT1 + ','\n            OUT_TEXT2   = OUT_TEXT2 + '%s,' % pool\n    OUT_FID.write(OUT_TEXT1+'\\n')    \n    OUT_FID.write(OUT_TEXT2+'\\n')    \n    \n    # Regional Breakdown\n    for iregion in REGION_idx:\n        region            = REGION_dict['Name'][iregion]\n        region_mask       = REGIONS_1D==(iregion+1)\n        OUT_TEXT1   = ('%s,%.1f,') % (region, \\\n            np.sum(LAND_LANDPTS[0,itemp,itype,iyear_max,:,:,:,region_mask])/nFACTORIAL)\n        for BECCS_SF in BECCS_SFs:\n            \n            if (BECCS_SF == 1):\n                for pool in EXTRA_pools_1:\n                    print(region,BECCS_SF,pool,len(EXTRA_region[TEMP][BECCS_SF][pool][region]))\n                    if len(EXTRA_region[TEMP][BECCS_SF][pool][region]) > 0:\n                        PERCENT     = np.percentile(np.array((EXTRA_region[TEMP][BECCS_SF][pool][region])),[50.0,10.0,90.0])\n                        OUT_TEXT1   = OUT_TEXT1 + '%.2f (%.2f-%.2f),' % \\\n                            (PERCENT[0],PERCENT[1],PERCENT[2])\n                    else:\n                        OUT_TEXT1   = OUT_TEXT1 + '-,'\n            \n            for pool in EXTRA_pools_2:\n                print(region,BECCS_SF,pool,len(EXTRA_region[TEMP][BECCS_SF][pool][region]))\n                if len(EXTRA_region[TEMP][BECCS_SF][pool][region]) > 0:\n                    PERCENT     = np.percentile(np.array((EXTRA_region[TEMP][BECCS_SF][pool][region])),[50.0,25.0,75.0])\n                    OUT_TEXT1   = OUT_TEXT1 + '%.2f (%.2f-%.2f),' % \\\n                        (PERCENT[0],PERCENT[1],PERCENT[2])\n                else:\n                    OUT_TEXT1   = OUT_TEXT1 + '-,'\n\n        OUT_FID.write(OUT_TEXT1+'\\n')\n\nOUT_FID.close()\n               \nprint(\"\\n\")\nprint('EXTRA_output')\n", "meta": {"hexsha": "ea19b2b6d9a52ec885cd209e18287132bb7344eb", "size": 72197, "ext": "py", "lang": "Python", "max_stars_repo_path": "Processing_Scripts/MITIGATION_Paper_BECCS_Extra_RRv1.2.py", "max_stars_repo_name": "GarryHayman/Regional_Mitigation_Paper_Software", "max_stars_repo_head_hexsha": "3a46d14bdf80677f2683e71369dd1110a06a5916", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Processing_Scripts/MITIGATION_Paper_BECCS_Extra_RRv1.2.py", "max_issues_repo_name": "GarryHayman/Regional_Mitigation_Paper_Software", "max_issues_repo_head_hexsha": "3a46d14bdf80677f2683e71369dd1110a06a5916", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Processing_Scripts/MITIGATION_Paper_BECCS_Extra_RRv1.2.py", "max_forks_repo_name": "GarryHayman/Regional_Mitigation_Paper_Software", "max_forks_repo_head_hexsha": "3a46d14bdf80677f2683e71369dd1110a06a5916", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.0282012195, "max_line_length": 147, "alphanum_fraction": 0.4908652714, "include": true, "reason": "import numpy,from numpy", "num_tokens": 19832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.18614773659884296}}
{"text": "#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: gingkg\n@contact: sby2015666@163.com\n@software: PyCharm\n@project: Learning_RL\n@file: PG_2048.py\n@time: 2020/6/26\n@desc: 使用策略梯度的方法玩2048\n\"\"\"\n\n# 导入依赖\nimport parl\nfrom parl import layers\nimport paddle.fluid as fluid\nimport copy\nimport numpy as np\nimport os\nimport gym\nfrom parl.utils import logger\nimport random\nimport collections\nimport time\nimport pickle\nimport gym_game2048\n\n# 设置超参数\nLEARNING_RATE = 1e-2\nGAMMA = 0.99                    # reward 的衰减因子，一般取 0.9 到 0.999 不等\n\nTRAIN_TOTAL_EPISODES = 50000    # 总训练步数\nTEST_EVERY_EPISODES = 100       # 每个N步评估一下算法效果，每次评估5个episode求平均reward\n\n\nclass Model(parl.Model):\n    def __init__(self, act_dim):\n        # 配置model\n        self.cnn1 = layers.conv2d(num_filters=256, filter_size=2, padding=\"SAME\", stride=1,act=\"softmax\")\n        self.cnn2 = layers.conv2d(num_filters=256, filter_size=2, padding=\"SAME\", stride=1,act=\"softmax\")\n        self.cnn3 = layers.conv2d(num_filters=256, filter_size=2, padding=\"SAME\", stride=1,act=\"softmax\")\n        self.cnn4 = layers.conv2d(num_filters=256, filter_size=2, padding=\"SAME\", stride=1,act=\"softmax\")\n        self.fc1 = layers.fc(size=act_dim, act=\"softmax\")\n    def forward(self, obs):\n        # 定义网络\n        # 输入state，输出所有action对应的Q，[Q(s,a1), Q(s,a2), Q(s,a3)...]\n        # 组装Q网络\n        h = self.cnn1(obs)\n        h = self.cnn2(h)\n        h = self.cnn3(h)\n        h = self.cnn4(h)\n        out = self.fc1(h)\n        return out\n\n\n# from parl.algorithms import PolicyGradient # 也可以直接从parl库中导入PolicyGradient算法，无需重复写算法\nclass PolicyGradient(parl.Algorithm):\n    def __init__(self, model, lr=None):\n        \"\"\" Policy Gradient algorithm\n\n        Args:\n            model (parl.Model): policy的前向网络.\n            lr (float): 学习率.\n        \"\"\"\n\n        self.model = model\n        assert isinstance(lr, float)\n        self.lr = lr\n\n    def predict(self, obs):\n        \"\"\" 使用policy model预测输出的动作概率\n        \"\"\"\n        return self.model(obs)\n\n    def learn(self, obs, action, reward):\n        \"\"\" 用policy gradient 算法更新policy model\n        \"\"\"\n        act_prob = self.model(obs)  # 获取输出动作概率\n        # log_prob = layers.cross_entropy(act_prob, action) # 交叉熵\n        log_prob = layers.reduce_sum(\n            -1.0 * layers.log(act_prob) * layers.one_hot(\n                action, act_prob.shape[1]),\n            dim=1)\n        cost = log_prob * reward\n        cost = layers.reduce_mean(cost)\n\n        optimizer = fluid.optimizer.Adam(self.lr)\n        optimizer.minimize(cost)\n        return cost\n\n\nclass Agent(parl.Agent):\n    def __init__(self, algorithm, obs_dim, act_dim):\n        self.obs_dim = obs_dim\n        self.act_dim = act_dim\n        super(Agent, self).__init__(algorithm)\n\n    def build_program(self):\n        self.pred_program = fluid.Program()\n        self.learn_program = fluid.Program()\n\n        with fluid.program_guard(self.pred_program):  # 搭建计算图用于 预测动作，定义输入输出变量\n            obs = layers.data(\n                name='obs', shape=self.obs_dim, dtype='float32')\n            self.act_prob = self.alg.predict(obs)\n\n        with fluid.program_guard(\n                self.learn_program):  # 搭建计算图用于 更新policy网络，定义输入输出变量\n            obs = layers.data(\n                name='obs', shape=self.obs_dim, dtype='float32')\n            act = layers.data(name='act', shape=[1], dtype='int64')\n            reward = layers.data(name='reward', shape=[], dtype='float32')\n            self.cost = self.alg.learn(obs, act, reward)\n\n    def sample(self, obs):\n        obs = np.expand_dims(obs, axis=0)  # 增加一维维度\n        act_prob = self.fluid_executor.run(\n            self.pred_program,\n            feed={'obs': obs.astype('float32')},\n            fetch_list=[self.act_prob])[0]\n        act_prob = np.squeeze(act_prob, axis=0)  # 减少一维维度\n        act = np.random.choice(range(self.act_dim), p=act_prob)  # 根据动作概率选取动作\n        return act\n\n    def predict(self, obs):\n        obs = np.expand_dims(obs, axis=0)\n        act_prob = self.fluid_executor.run(\n            self.pred_program,\n            feed={'obs': obs.astype('float32')},\n            fetch_list=[self.act_prob])[0]\n        act_prob = np.squeeze(act_prob, axis=0)\n        act = np.argmax(act_prob)  # 根据动作概率选择概率最高的动作\n        return act\n\n    def learn(self, obs, act, reward):\n        act = np.expand_dims(act, axis=-1)\n        feed = {\n            'obs': obs.astype('float32'),\n            'act': act.astype('int64'),\n            'reward': reward.astype('float32')\n        }\n        cost = self.fluid_executor.run(\n            self.learn_program, feed=feed, fetch_list=[self.cost])[0]\n        return cost\n\n\ndef run_episode(env, agent):\n    obs_list, action_list, reward_list = [], [], []\n    obs = env.reset()\n    obs = obs.swapaxes(0, 2).swapaxes(1, 2)\n    while True:\n        obs_list.append(obs)\n        action = agent.sample(obs)  # 采样动作\n        action_list.append(action)\n\n        obs, reward, done, info = env.step(action)\n        obs = obs.swapaxes(0, 2).swapaxes(1, 2)\n        reward_list.append(reward)\n\n        if done:\n            max_socre = env.get_board().max()\n            break\n\n    return obs_list, action_list, reward_list, max_socre\n\n\n# 评估 agent, 跑 5 个episode，总reward求平均\ndef evaluate(env, agent, render=False):\n    eval_reward = []\n    for i in range(5):\n        episode_log = {\"boards\": [env.get_board()], \"actions\": [\"#\"], \"scores\": [0]}\n        obs = env.reset()\n        episode_reward = 0\n        while True:\n            obs = obs.swapaxes(0, 2).swapaxes(1, 2)\n            action = agent.predict(obs)  # 预测动作，只选最优动作\n            obs, reward, done, info = env.step(action)\n            episode_log[\"boards\"].append(env.get_board())\n            episode_log[\"actions\"].append(ACTION_LIST[action])\n            episode_log[\"scores\"].append(info['total_score'])\n            episode_reward += reward\n            if done:\n                break\n        eval_reward.append(episode_reward)\n        if render:\n            env.render(episode_log)\n    return np.mean(eval_reward)\n\n\n# 根据一个episode的每个step的reward列表，计算每一个Step的Gt\ndef calc_reward_to_go(reward_list, gamma=0.99):\n    for i in range(len(reward_list) - 2, -1, -1):\n        # G_t = r_t + γ·r_t+1 + ... = r_t + γ·G_t+1\n        reward_list[i] += gamma * reward_list[i + 1]  # Gt\n    return np.array(reward_list)\n\n\nif __name__ == \"__main__\":\n    # 创建环境和Agent，创建经验池，启动训练，保存模型\n    board_size = 4\n    seed = None\n    binary = True\n    ACTION_LIST = [\"↑\", \"↓\", \"→\", \"←\"]\n    env = gym.make(\"game2048-v0\", board_size=board_size, seed=seed, binary=binary, extractor=\"cnn\", penalty=-10)\n    action_dim = len(ACTION_LIST)  # 2048:4个动作(0:上, 1:下, 2:右, 3:左)\n    obs_shape = [16,4,4]\n\n    # 根据parl框架构建agent\n    # 嵌套Model, DQN, Agent构建 agent\n    model = Model(action_dim)\n    algorithm = PolicyGradient(model, lr=LEARNING_RATE)\n    agent = Agent(algorithm, obs_shape, action_dim)\n\n    # 加载全局episode\n    episode_path = 'models/PG_CNN_2048/global_episodes.pkl'\n    if not os.path.exists(episode_path):\n        with open(episode_path, \"wb\") as f:\n            global_episodes = 0\n            pickle.dump(global_episodes, f)\n\n    with open(episode_path, \"rb\") as f:\n        global_episodes = pickle.load(f)\n\n    # 加载模型\n    model_path = \"models/PG_CNN_2048/pg_cnn_2048_model_50000.ckpt\"\n    if os.path.exists(model_path):\n        agent.restore(model_path)\n\n    total_episodes = 0\n    while total_episodes < TRAIN_TOTAL_EPISODES:\n        obs_list, action_list, reward_list, max_socre = run_episode(env, agent)\n        total_episodes += 1\n        if total_episodes % 10 == 0:\n            logger.info('Episode：{} Steps: {}  Max Socre: {} Reward: {}'.format\n                        (total_episodes, len(action_list), max_socre, sum(reward_list)))\n\n        batch_obs = np.array(obs_list)\n        batch_action = np.array(action_list)\n        batch_reward = calc_reward_to_go(reward_list, gamma=GAMMA)\n\n        agent.learn(batch_obs, batch_action, batch_reward)\n\n        if total_episodes % TEST_EVERY_EPISODES == 0:  # 每隔一定step数，评估一次模型\n            global_episodes = global_episodes + TEST_EVERY_EPISODES\n\n            evaluate_reward = evaluate(env, agent, render=False)\n            logger.info('Episode：{} , Test reward: {}'.format(global_episodes, evaluate_reward))  # 打印评估的reward\n\n            # 每评估一次，就保存一次模型，以训练的step数命名\n            agent.save('models/PG_CNN_2048/pg_cnn_2048_model_{}.ckpt'.format(global_episodes))\n\n            with open(episode_path, \"wb\") as f:\n                pickle.dump(global_episodes, f)\n\n\n", "meta": {"hexsha": "b514be98fe8af0fe882f392981e922ffa49aed57", "size": 8427, "ext": "py", "lang": "Python", "max_stars_repo_path": "PG_CNN_2048.py", "max_stars_repo_name": "gingkg/paly_2048_gym_by_RL", "max_stars_repo_head_hexsha": "3e5043169e637818ecae8f83688ffe52897e860f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-25T11:53:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-25T11:53:12.000Z", "max_issues_repo_path": "PG_CNN_2048.py", "max_issues_repo_name": "gingkg/paly_2048_gym_by_RL", "max_issues_repo_head_hexsha": "3e5043169e637818ecae8f83688ffe52897e860f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PG_CNN_2048.py", "max_forks_repo_name": "gingkg/paly_2048_gym_by_RL", "max_forks_repo_head_hexsha": "3e5043169e637818ecae8f83688ffe52897e860f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-30T13:12:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-30T13:12:41.000Z", "avg_line_length": 32.91796875, "max_line_length": 112, "alphanum_fraction": 0.611249555, "include": true, "reason": "import numpy", "num_tokens": 2502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.18614773545177646}}
{"text": "\"\"\"\nmodel_grid_utils.py\n(C) Zachary R. Claytor\nInstitute for Astronomy\nUniversity of Hawaiʻi\n2019 July 1\n\nPython utilities designed to interact with output model grids from the Yale\nRotating stellar Evolution Code (YREC, Demarque et al. 2008). The grid of\nmodels that accompany this software were produced by van Saders & \nPinsonneault (2013) and updated by Claytor et al. (2019, in prep) using Castelli & \nKurucz (2004) model atmospheres, which tabulate opacity information for various\nmetallicities and allow for alpha-enhancement. The rotation code within YREC\nassumes a stellar-wind-driven braking law, and specific details on braking\nparameters can be found in the file `braking_law_parameters.txt`.\n\nThese models span the following mass, metallicity, and alpha-enhancement\n(grid parameters can be changed in `config.py`):\n\n              |  min | max | step\n    -----------------------------\n      M/Msun  |  0.3 | 2.0 | 0.01\n      [M/H]   | -1.0 | 0.5 | 0.5\n    [alpha/M] |  0.0 | 0.4 | 0.4\n    -----------------------------\n\nAccording to Castelli & Kurucz (2004), [M/H] is log10(Z/Zsun), and \nalpha includes O, Ne, Mg, Si, S, Ar, Ca, and Ti.\n\nThe YREC output files have the format `met_###_alpha_###.out`, where ###\nspecifies the metallicity and alpha-enhancement for the models therein. The\nformatting is such that met_-050_alpha_040.out corresponds to the set of tracks\nwith [M/H] = -0.5 and [alpha/M] = 0.4. Any given `.out` file contains an\nevolution track for every mass in the grid. More details on these `.out` files\ncan be found in the files themselves.\n\"\"\"\n\n\nimport numpy as np\nimport pandas as pd\nfrom multiprocessing import Pool\nfrom tqdm import tqdm\n\nfrom .config import mass_grid, met_grid, alpha_grid\nfrom .config import model_path, column_labels\nfrom .config import eep_path, primary_eep_indices\n\n\ndef pickle_tracks(modelfile, columnfile=model_path+\"column_labels.txt\"):\n    \"\"\"\n    Takes YREC output files for a set of evolution tracks and converts\n    them to pandas DataFrames, then saves them to pickles in the same\n    directory as the model files.\n    Each YREC output file will yield a set of pickle files, one for each\n    evolutionary track contained in the model file.\n\n    PARAMETERS\n    ----------\n    `modelfile`: a string containing the full path to the desired model file\n\n    `columnfile`: a string containing the full path to the file listing the\n                  column names to be assigned in the output DataFrame. Each\n                  line in this file should contain an single label, and each\n                  column in the output file must have a corresponding label.\n                  Any columns that the user does not wish to be saved in the \n                  pickled track should have a `#` somewhere on the label line\n                  in the columnfile.\n\n    RETURNS nothing.\n    \"\"\"\n\n    with open(columnfile, \"r\") as cf:\n        # Read column labels, but we will use only labels with no '#'.\n        column_labels = np.asarray([line.strip() for line in cf.readlines()])\n        masked = np.asarray([\"#\" in label for label in column_labels])\n\n    with open(modelfile, \"r\") as f:\n        header = f.readline()\n        # Header format: ' NUMBER OF TRACKS XYZ ...'\n        # Each file contains `ntracks` evolutionary tracks, each with\n        # `nsteps` steps\n        ntracks = int(header[18:21])\n        nsteps = np.zeros(ntracks, dtype=int)\n        # initial mass and period also specified in preamble\n        mass_init = np.zeros(ntracks, dtype=float)\n        period_init = np.zeros(ntracks, dtype=float)\n\n        # read preamble. first column is an unnecessary index.\n        for i in range(ntracks):\n            line = f.readline().split()\n            _, nsteps[i], mass_init[i], period_init[i] = line\n\n       \n        # read the column label line, but don't use it\n        dummy_labels = f.readline()\n\n        # begin reading tracks\n        for i in range(ntracks):\n            # put together output filename\n            mass_str = \"_mass_%s.pkl\" %_to_string(mass_init[i])\n            out_fname = modelfile.replace(\".out\", mass_str)\n\n            track = np.zeros((nsteps[i], len(column_labels)))\n            for j in range(nsteps[i]):\n               track[j] = f.readline().split()\n\n            # put track into DataFrame, leaving out unwanted columns, then save.\n            df_track = pd.DataFrame(track[:,~masked], columns=column_labels[~masked])\n            df_track.to_pickle(out_fname)\n\n\ndef get_full_track(mass, met, alpha, labels=None, \n        read_path=model_path, return_fname=False):\n    \"\"\"\n    Obtains the desired stellar evolutionary track from the corresponding\n    pickle file\n\n    PARAMETERS\n    ----------\n    `mass`: (float) the mass of the star on the desired track, \n            in solar mass units\n\n    `met`: (float) the metallicity ([M/H]) of the star on the desired track\n\n    `alpha`: (float) the alpha-enhancement ([alpha/M]) of the star on \n             the desired track\n\n    `labels`: (list of str) the column labels for desired stellar parameters.\n              Default is None, which returns all parameters.\n\n    `models_path`: a string containing the path to the directory containing \n                   the model pickle files. Default is \"models/\".\n\n    `return_fname`: if True, returns the name of the file being read. This\n                    is mostly for convenience when converting to Equivalent-\n                    Evolutionary- Point- (EEP) based tracks, where the filename\n                    is different only by the \"eep\" prefix. Default is False.\n\n    RETURNS\n    -------\n    `track`: a pandas DataFrame containing the specified evolutionary track\n\n    `fname`: (optional) the name of the file containing the desired track\n    \"\"\"\n    \n    # convert input values to strings as they appear in filenames\n    mass_str = _to_string(mass)\n    met_str = _to_string(met)\n    alpha_str = _to_string(alpha)\n\n    fname = \"met_%s_alpha_%s_mass_%s.pkl\" %(met_str, alpha_str, mass_str)\n    track = pd.read_pickle(read_path+fname)\n    if labels is not None:\n        track = track[labels]\n\n    if return_fname:\n        return track, fname\n    return track\n\n\ndef _to_string(val):\n    \"\"\"\n    Converts a given float (`val`) of mass, metallicity, or alpha \n    enhancement to a string (`my_str`) formatted for the model filename.\n    For example, a metallicity [M/H] = -0.5 corresponds to the string \n    \"-050\", and the mass 1.32 corresponds to the string \"132\".\n    \"\"\"\n    if val < 0:\n        my_str = \"-\"\n    else:\n        my_str = \"\"\n\n    my_str += \"%03.f\" %abs(100*val)\n    return my_str\n           \n\ndef _pickle_series(save_path=model_path):\n    \"\"\"\n    Pickles all the models in the grid with specified metallicities\n    and alpha enhancements.\n    \"\"\"\n    metallicities = [_to_string(met) for met in met_grid]\n    alphas = [_to_string(alf) for alf in alpha_grid]\n\n    n_total = len(metallicities)*len(alphas)\n    with tqdm(total=n_total) as pbar:\n        for met in metallicities:\n            for alf in alphas:\n                fname = save_path + \"met_%s_alpha_%s.out\" %(met, alf)\n                pickle_tracks(fname)\n                pbar.update()\n\n\ndef _pickle_pool(save_path=model_path):\n    \"\"\"\n    Pickles all the models in the grid with specified metallicities\n    and alpha enhancements.\n    \"\"\"\n    metallicities = [_to_string(met) for met in met_grid]\n    alphas = [_to_string(alf) for alf in alpha_grid]\n\n    fnames = []\n    for met in metallicities:\n        for alf in alphas:\n            fnames.append(save_path + \"met_%s_alpha_%s.out\" % (met, alf))\n\n    print(\"Pickling evolution tracks...\")\n    with Pool() as pool:\n        with tqdm(total=len(fnames)) as pbar:\n            for i, _ in enumerate(pool.imap_unordered(pickle_tracks, fnames)):\n                pbar.update()\n\n\ndef pickle_all_tracks(use_pool=False):\n    \"\"\"\n    Wrapper for functions to pickle evolution tracks.\n    Allows user to pickle in series or in parallel using multiprocessing.Pool.\n    \"\"\"\n    if use_pool:\n        _pickle_pool()\n    else:\n        _pickle_series()\n\n\ndef get_eep_track(mass, met, alpha, labels=\"all\",\n                  re_index=None):\n    \"\"\"\n    Given mass, metallicity, and alpha-enhancement, we read and return an\n    Equivalent-Evolutionary-Phase- (EEP) based track from file with desired\n    column labels.\n\n    User can optionally reindex the EEP-based track. Indices outside\n    the current range will be set to NaN.\n    \"\"\"\n    met_str = _to_string(met)\n    alpha_str = _to_string(alpha)\n    mass_str = _to_string(mass)\n    fname = \"eep_met_%s_alpha_%s_mass_%s.pkl\" %(met_str, alpha_str, mass_str)\n\n    # eep_path is defined in eep_config.py\n    try:\n        if labels == \"all\":\n            eep_track = pd.read_pickle(eep_path+fname)\n        else:\n            eep_track = pd.read_pickle(eep_path+fname)[labels]\n        if re_index is not None:\n            eep_track = eep_track.reindex(range(re_index))\n        return eep_track\n    except FileNotFoundError:\n        return np.nan\n\n\ndef _import_model_grid(labels=\"all\"):\n    \"\"\"Gets the grid of all EEP-based evolution tracks; return as nested list.\n    \"\"\"\n\n    re_index = primary_eep_indices[-1]+1\n    grid_tracks = [[[get_eep_track(m, z, a, labels, re_index=re_index) \n                     for a in alpha_grid]\n                    for z in met_grid]\n                   for m in mass_grid]\n    return grid_tracks\n\n\nif __name__ == \"__main__\":\n    pickle_all_tracks(use_pool=True)\n", "meta": {"hexsha": "9d29c0c895a3f4d831b1f8f2d0e40f2eb78fc37c", "size": 9436, "ext": "py", "lang": "Python", "max_stars_repo_path": "kiauhoku/model_grid_utils.py", "max_stars_repo_name": "timothydmorton/kiauhoku", "max_stars_repo_head_hexsha": "a75e56d907cd89eacc01ff04e2197c2d956c72de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kiauhoku/model_grid_utils.py", "max_issues_repo_name": "timothydmorton/kiauhoku", "max_issues_repo_head_hexsha": "a75e56d907cd89eacc01ff04e2197c2d956c72de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kiauhoku/model_grid_utils.py", "max_forks_repo_name": "timothydmorton/kiauhoku", "max_forks_repo_head_hexsha": "a75e56d907cd89eacc01ff04e2197c2d956c72de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.34082397, "max_line_length": 85, "alphanum_fraction": 0.6470962272, "include": true, "reason": "import numpy", "num_tokens": 2262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.33111972642778714, "lm_q1q2_score": 0.1861477291774361}}
{"text": "#!/usr/bin/env python\n#\n# Author: Sandeep Sharma <sanshar@gmail.com>\n#         Sheng Guo <shengg@princeton.edu>\n#         Qiming Sun <osirpt.sun@gmail.com>\n#\n\n'''\nDMRG solver for CASCI and CASSCF.\n'''\n\nimport ctypes\nimport os\nimport sys\nimport struct\nimport time\nimport tempfile\nfrom subprocess import check_call, check_output, STDOUT, CalledProcessError\nimport numpy\nimport pyscf.tools\nimport pyscf.lib\nfrom pyscf.lib import logger\nfrom pyscf.lib import chkfile\nfrom pyscf import mcscf\nfrom pyscf.dmrgscf import dmrg_sym\n\nimport pyscf.lib\n\nlibunpack = pyscf.lib.load_library('libicmpspt')\n\n\ntry:\n    from pyscf.dmrgscf import settings\nexcept ImportError:\n    import sys\n    sys.stderr.write('''settings.py not found.  Please create %s\n''' % os.path.join(os.path.dirname(__file__), 'settings.py'))\n    raise ImportError\n\n\n\nclass DMRGCI(pyscf.lib.StreamObject):\n    '''Block program interface and the object to hold Block program input parameters.\n\n    Attributes:\n        outputlevel : int\n            Noise level for Block program output.\n        maxIter : int\n\n        approx_maxIter : int\n            To control the DMRG-CASSCF approximate DMRG solver accuracy.\n        twodot_to_onedot : int\n            When to switch from two-dot algroithm to one-dot algroithm.\n        nroots : int\n\n        weights : list of floats\n            Use this attribute with \"nroots\" attribute to set state-average calculation.\n        restart : bool\n            To control whether to restart a DMRG calculation.\n        tol : float\n            DMRG convergence tolerence\n        maxM : int\n            Bond dimension\n        scheduleSweeps, scheduleMaxMs, scheduleTols, scheduleNoises : list\n            DMRG sweep scheduler.  See also Block documentation\n        wfnsym : str or int\n            Wave function irrep label or irrep ID\n        orbsym : list of int\n            irrep IDs of each orbital\n        groupname : str\n            groupname, orbsym together can control whether to employ symmetry in\n            the calculation.  \"groupname = None and orbsym = []\" requires the\n            Block program using C1 symmetry.\n\n    Examples:\n\n    >>> mol = gto.M(atom='C 0 0 0; C 0 0 1')\n    >>> mf = scf.RHF(mol).run()\n    >>> mc = mcscf.CASCI(mf, 4, 4)\n    >>> mc.fcisolver = DMRGCI(mol)\n    >>> mc.kernel()\n    -74.379770619390698\n    '''\n    def __init__(self, mol, maxM=None, tol=None, num_thrds=1, memory=None):\n        self.mol = mol\n        self.verbose = mol.verbose\n        self.stdout = mol.stdout\n        self.outputlevel = 2\n\n        self.executable = settings.BLOCKEXE\n        self.scratchDirectory = os.path.abspath(settings.BLOCKSCRATCHDIR)\n        self.mpiprefix = settings.MPIPREFIX\n        self.memory = memory\n\n        self.integralFile = \"FCIDUMP\"\n        self.configFile = \"dmrg.conf\"\n        self.outputFile = \"dmrg.out\"\n        if hasattr(settings, 'BLOCKRUNTIMEDIR'):\n            self.runtimeDir = settings.BLOCKRUNTIMEDIR\n        else:\n            self.runtimeDir = '.'\n        self.maxIter = 20\n        self.approx_maxIter = 4\n        self.twodot_to_onedot = 15\n        self.dmrg_switch_tol = 1e-3\n        self.nroots = 1\n        self.weights = []\n        self.wfnsym = 1\n        self.extraline = []\n\n        if tol is None:\n            self.tol = 1e-8\n        else:\n            self.tol = tol/10\n        if maxM is None:\n            self.maxM = 1000\n        else:\n            self.maxM = maxM\n\n        self.num_thrds= num_thrds\n        self.startM =  None\n        self.restart = False\n        self.nonspinAdapted = False\n        self.scheduleSweeps = []\n        self.scheduleMaxMs  = []\n        self.scheduleTols   = []\n        self.scheduleNoises = []\n        self.onlywriteIntegral = False\n        self.spin = 0\n\n        self.orbsym = []\n        if mol.symmetry:\n            self.groupname = mol.groupname\n        else:\n            self.groupname = None\n\n##################################################\n# don't modify the following attributes, if you do not finish part of calculation, which can be reused.\n\n        #DO NOT CHANGE these parameters, unless you know the code in details\n        self.twopdm = True #By default, 2rdm is calculated after the calculations of wave function.\n        self.block_extra_keyword = [] #For Block advanced user only.\n        self.has_fourpdm = False\n        self.has_threepdm = False\n        self.has_nevpt = False\n# This flag _restart is set by the program internally, to control when to make\n# Block restart calculation.\n        self._restart = False\n        self.generate_schedule()\n\n        self._keys = set(self.__dict__.keys())\n\n\n    @property\n    def threads(self):\n        return self.num_thrds\n    @threads.setter\n    def threads(self, x):\n        self.num_thrds = x\n\n    def generate_schedule(self):\n\n        if self.startM is None:\n            if self.maxM < 200:\n                self.startM = 50\n            else:\n                self.startM = 200\n        if len(self.scheduleSweeps) == 0:\n            startM = self.startM\n            N_sweep = 0\n            if self.restart or self._restart :\n                Tol = self.tol / 10.0\n            else:\n                Tol = 1.0e-5\n            Noise = Tol\n            while startM < int(self.maxM):\n                self.scheduleSweeps.append(N_sweep)\n                N_sweep += 4\n                self.scheduleMaxMs.append(startM)\n                startM *= 2\n                self.scheduleTols.append(Tol)\n                self.scheduleNoises.append(Noise)\n            while Tol > float(self.tol):\n                self.scheduleSweeps.append(N_sweep)\n                N_sweep += 2\n                self.scheduleMaxMs.append(self.maxM)\n                self.scheduleTols.append(Tol)\n                Tol /= 10.0\n                self.scheduleNoises.append(5.0e-5)\n            self.scheduleSweeps.append(N_sweep)\n            N_sweep += 2\n            self.scheduleMaxMs.append(self.maxM)\n            self.scheduleTols.append(self.tol)\n            self.scheduleNoises.append(0.0)\n            self.twodot_to_onedot = N_sweep + 2\n            self.maxIter = self.twodot_to_onedot + 12\n        return self\n\n\n    def dump_flags(self, verbose=None):\n        if verbose is None:\n            verbose = self.verbose\n        log = logger.Logger(self.stdout, verbose)\n        log.info('******** Block flags ********')\n        log.info('executable = %s', self.executable)\n        log.info('Block version %s', block_version(self.executable))\n        log.info('BLOCKEXE_COMPRESS_NEVPT = %s', settings.BLOCKEXE_COMPRESS_NEVPT)\n        log.info('mpiprefix = %s', self.mpiprefix)\n        log.info('scratchDirectory = %s', self.scratchDirectory)\n        log.info('integralFile = %s', os.path.join(self.runtimeDir, self.integralFile))\n        log.info('configFile = %s', os.path.join(self.runtimeDir, self.configFile))\n        log.info('outputFile = %s', os.path.join(self.runtimeDir, self.outputFile))\n        log.info('maxIter = %d', self.maxIter)\n        log.info('scheduleSweeps = %s', str(self.scheduleSweeps))\n        log.info('scheduleMaxMs = %s', str(self.scheduleMaxMs))\n        log.info('scheduleTols = %s', str(self.scheduleTols))\n        log.info('scheduleNoises = %s', str(self.scheduleNoises))\n        log.info('twodot_to_onedot = %d', self.twodot_to_onedot)\n        log.info('tol = %g', self.tol)\n        log.info('maxM = %d', self.maxM)\n        log.info('fullrestart = %s', str(self.restart or self._restart))\n        log.info('dmrg switch tol =%s', self.dmrg_switch_tol)\n        log.info('wfnsym = %s', self.wfnsym)\n        log.info('num_thrds = %d', self.num_thrds)\n        log.info('memory = %s', self.memory)\n        return self\n\n    # ABOUT RDMs AND INDEXES: -----------------------------------------------------------------------\n    #   There is two ways to stored an RDM\n    #   (the numbers help keep track of creation/annihilation that go together):\n    #     E3[i1,j2,k3,l3,m2,n1] is the way BLOCK and STACKBLOCK outputs text and bin files\n    #     E3[i1,j2,k3,l1,m2,n3] is the way the tensors need to be written for SQA and ICPT\n    #\n    #   --> See various remarks in the pertinent functions below.\n    # -----------------------------------------------------------------------------------------------\n\n    def make_rdm1s(self, state, norb, nelec, link_index=None, **kwargs):\n        # Ref: IJQC, 109, 3552 Eq (3)\n        if isinstance(nelec, (int, numpy.integer)):\n            nelecb = (nelec-self.spin) // 2\n            neleca = nelec - nelecb\n        else :\n            neleca, nelecb = nelec\n        dm1, dm2 = DMRGCI.make_rdm12(self, state, norb, nelec, link_index, **kwargs)\n        dm1n = (2-(neleca+nelecb)/2.) * dm1 - numpy.einsum('pkkq->pq', dm2)\n        dm1n *= 1./(neleca-nelecb+1)\n        dm1a, dm1b = (dm1+dm1n)*.5, (dm1-dm1n)*.5\n        return dm1a, dm1b\n\n    def make_rdm1(self, state, norb, nelec, link_index=None, **kwargs):\n        # Avoid calling self.make_rdm12 because it may be overloaded\n        return DMRGCI.make_rdm12(self, state, norb, nelec, link_index, **kwargs)[0]\n\n    def make_rdm12(self, state, norb, nelec, link_index=None, **kwargs):\n        nelectrons = 0\n        if isinstance(nelec, (int, numpy.integer)):\n            nelectrons = nelec\n        else:\n            nelectrons = nelec[0]+nelec[1]\n\n        twopdm = numpy.zeros( (norb, norb, norb, norb) )\n        file2pdm = \"spatial_twopdm.%d.%d.txt\" %(state, state)\n        # The 2RDMs written by \"save_spatial_twopdm_text\" in BLOCK and STACKBLOCK\n        # are written as E2[i1,j2,k2,l1] (right?)\n        # and stored here as E2[i1,l1,j2,k2] (weird?)\n        # This is NOT done with SQA in mind.\n        with open(os.path.join(self.scratchDirectory, \"node0\", file2pdm), \"r\") as f:\n            norb_read = int(f.readline().split()[0])\n            assert(norb_read == norb)\n\n            for line in f:\n                linesp = line.split()\n                i, k, l, j = [int(x) for x in linesp[:4]]\n                twopdm[i,j,k,l] = 2.0 * float(linesp[4])\n\n        # (this is coherent with previous statement about indexes) (right?)\n        onepdm = numpy.einsum('ikjj->ik', twopdm)\n        onepdm /= (nelectrons-1)\n        return onepdm, twopdm\n\n    def trans_rdm1s(self, statebra, stateket, norb, nelec, link_index=None, **kwargs):\n        # Ref: IJQC, 109, 3552 Eq (3)\n        if isinstance(nelec, (int, numpy.integer)):\n            nelecb = (nelec-self.spin) // 2\n            neleca = nelec - nelecb\n        else :\n            neleca, nelecb = nelec\n        dm1, dm2 = DMRGCI.trans_rdm12(self, statebra, stateket, norb, nelec, link_index, **kwargs)\n        dm1n = (2-(neleca+nelecb)/2.) * dm1 - numpy.einsum('pkkq->pq', dm2)\n        dm1n *= 1./(neleca-nelecb+1)\n        dm1a, dm1b = (dm1+dm1n)*.5, (dm1-dm1n)*.5\n        return dm1a, dm1b\n\n    def trans_rdm1(self, statebra, stateket, norb, nelec, link_index=None, **kwargs):\n        return DMRGCI.trans_rdm12(self, statebra, stateket, norb, nelec, link_index, **kwargs)[0]\n\n    def trans_rdm12(self, statebra, stateket, norb, nelec, link_index=None, **kwargs):\n        nelectrons = 0\n        if isinstance(nelec, (int, numpy.integer)):\n            nelectrons = nelec\n        else:\n            nelectrons = nelec[0]+nelec[1]\n\n        writeDMRGConfFile(self, nelec, True, with_2pdm=False,\n                          extraline=['restart_tran_twopdm',\n                                     'specificpdm %d %d' % (statebra, stateket)])\n        executeBLOCK(self)\n\n        twopdm = numpy.zeros( (norb, norb, norb, norb) )\n        file2pdm = \"spatial_twopdm.%d.%d.txt\" %(statebra, stateket)\n        # The 2RDMs written by \"save_spatial_twopdm_text\" in BLOCK and STACKBLOCK\n        # are written as E2[i1,j2,k2,l1] (right?)\n        # and stored here as E2[i1,l1,j2,k2] (weird?)\n        # This is NOT done with SQA in mind.\n        with open(os.path.join(self.scratchDirectory, \"node0\", file2pdm), \"r\") as f:\n            norb_read = int(f.readline().split()[0])\n            assert(norb_read == norb)\n\n            for line in f:\n                linesp = line.split()\n                i, k, l, j = [int(x) for x in linesp[:4]]\n                twopdm[i,j,k,l] = 2.0 * float(linesp[4])\n\n        # (this is coherent with previous statement about indexes) (right?)\n        onepdm = numpy.einsum('ikjj->ik', twopdm)\n        onepdm /= (nelectrons-1)\n        return onepdm, twopdm\n\n    def make_rdm123(self, state, norb, nelec, link_index=None, **kwargs):\n        if self.has_threepdm == False:\n            writeDMRGConfFile(self, nelec, True,\n                              with_2pdm=False, extraline=['restart_threepdm'])\n            if self.verbose >= logger.DEBUG1:\n                inFile = os.path.join(self.runtimeDir, self.configFile)\n                logger.debug1(self, 'Block Input conf')\n                logger.debug1(self, open(inFile, 'r').read())\n            executeBLOCK(self)\n            if self.verbose >= logger.DEBUG1:\n                outFile = os.path.join(self.runtimeDir, self.outputFile)\n                logger.debug1(self, open(outFile).read())\n            self.has_threepdm = True\n\n        nelectrons = 0\n        if isinstance(nelec, (int, numpy.integer)):\n            nelectrons = nelec\n        else:\n            nelectrons = nelec[0]+nelec[1]\n\n        threepdm = numpy.zeros( (norb, norb, norb, norb, norb, norb) )\n        file3pdm = \"spatial_threepdm.%d.%d.txt\" %(state, state)\n        # The 3RDMs written by \"Threepdm_container::save_spatial_npdm_text\" in BLOCK and STACKBLOCK\n        # are written as E3[i1,j2,k3,l3,m2,n1]\n        # and are also stored here as E3[i1,j2,k3,l3,m2,n1]\n        # This is NOT done with SQA in mind.\n        with open(os.path.join(self.scratchDirectory, \"node0\", file3pdm), \"r\") as f:\n            norb_read = int(f.readline().split()[0])\n            assert(norb_read == norb)\n\n            for line in f:\n                linesp = line.split()\n                i, j, k, l, m, n = [int(x) for x in linesp[:6]]\n                threepdm[i,j,k,l,m,n] = float(linesp[6])\n\n        # (this is coherent with previous statement about indexes)\n        twopdm = numpy.einsum('ijkklm->ijlm',threepdm)\n        twopdm /= (nelectrons-2)\n        onepdm = numpy.einsum('ijjk->ik', twopdm)\n        onepdm /= (nelectrons-1)\n        return onepdm, twopdm, threepdm\n\n    def _make_dm123(self, state, norb, nelec, link_index=None, **kwargs):\n        r'''Note this function does NOT compute the standard density matrix.\n        The density matrices are reordered to match the the fci.rdm.make_dm123\n        function (used by NEVPT code).\n        The returned \"2pdm\" is :math:`\\langle p^\\dagger q r^\\dagger s\\rangle`;\n        The returned \"3pdm\" is :math:`\\langle p^\\dagger q r^\\dagger s t^\\dagger u\\rangle`.\n        '''\n        onepdm, twopdm, threepdm = self.make_rdm123(state, norb, nelec, None, **kwargs)\n        threepdm = numpy.einsum('mkijln->ijklmn',threepdm).copy()\n        threepdm += numpy.einsum('jk,lm,in->ijklmn',numpy.identity(norb),numpy.identity(norb),onepdm)\n        threepdm += numpy.einsum('jk,miln->ijklmn',numpy.identity(norb),twopdm)\n        threepdm += numpy.einsum('lm,kijn->ijklmn',numpy.identity(norb),twopdm)\n        threepdm += numpy.einsum('jm,kinl->ijklmn',numpy.identity(norb),twopdm)\n\n        twopdm =(numpy.einsum('iklj->ijkl',twopdm)\n               + numpy.einsum('il,jk->ijkl',onepdm,numpy.identity(norb)))\n\n        return onepdm, twopdm, threepdm\n\n    def make_rdm3(self, state, norb, nelec, dt=numpy.dtype('Float64'), filetype = \"binary\", link_index=None, **kwargs):\n        import os\n\n        if self.has_threepdm == False:\n            self.twopdm = False\n            self.extraline.append('threepdm\\n')\n\n            writeDMRGConfFile(self, nelec, False)\n            if self.verbose >= logger.DEBUG1:\n                inFile = self.configFile\n                #inFile = os.path.join(self.scratchDirectory,self.configFile)\n                logger.debug1(self, 'Block Input conf')\n                logger.debug1(self, open(inFile, 'r').read())\n            executeBLOCK(self)\n            if self.verbose >= logger.DEBUG1:\n                outFile = self.outputFile\n                #outFile = os.path.join(self.scratchDirectory,self.outputFile)\n                logger.debug1(self, open(outFile).read())\n            self.has_threepdm = True\n            self.extraline.pop()\n\n        # The binary files coming from STACKBLOCK and BLOCK are different\n        # - STACKBLOCK uses the 6-fold symmetry, this must be unpacked\n        #   using \"libunpack.unpackE3\" (see lib/icmpspt/icmpspt.c)\n        # - BLOCK just writes a list of all values, this is directly read\n        #   using \"unpackE3_BLOCK\" (see below)\n        if (filetype == \"binary\") :\n            fname = os.path.join(self.scratchDirectory,\"node0\", \"spatial_threepdm.%d.%d.bin\" %(state, state))\n            if 'stackblock' in settings.BLOCKEXE:\n              print 'Reading binary 3RDM from STACKBLOCK'\n              fnameout = os.path.join(self.scratchDirectory,\"node0\", \"spatial_threepdm.%d.%d.bin.unpack\" %(state, state))\n              libunpack.unpackE3(ctypes.c_char_p(fname), ctypes.c_char_p(fnameout), ctypes.c_int(norb))\n              E3 = numpy.fromfile(fnameout, dtype=numpy.dtype('Float64'))\n              E3 = numpy.reshape(E3, (norb, norb, norb, norb, norb, norb), order='F')\n            else:\n              print 'Reading binary 3RDM from BLOCK'\n              E3 = DMRGCI.unpackE3_BLOCK(self,fname,norb)\n\n        # The 3RDMs written by \"Threepdm_container::save_spatial_npdm_text\" in BLOCK and STACKBLOCK\n        # are written as E3[i1,j2,k3,l3,m2,n1]\n        # and are stored here as E3[i1,j2,k3,n1,m2,l3]\n        # This is done with SQA in mind.\n        else:\n            print 'Reading text-file 3RDM'\n            fname = os.path.join(self.scratchDirectory,\"node0\", \"spatial_threepdm.%d.%d.txt\" %(state, state))\n            f = open(fname, 'r')\n            lines = f.readlines()\n            E3 = numpy.zeros(shape=(norb, norb, norb, norb, norb, norb), dtype=dt, order='F')\n            assert(int(lines[0])==norb)\n            for line in lines[1:]:\n              linesp = line.split()\n              if (len(linesp) != 7) :\n                  continue\n              a, b, c, d, e, f, integral = int(linesp[0]), int(linesp[1]), int(linesp[2]), int(linesp[3]), int(linesp[4]), int(linesp[5]), float(linesp[6])\n              if (False):\n                E3[a,b,c, f,e,d] = integral\n                E3[a,c,b, f,d,e] = integral\n                E3[b,a,c, e,f,d] = integral\n                E3[b,c,a, e,d,f] = integral\n                E3[c,a,b, d,f,e] = integral\n                E3[c,b,a, d,e,f] = integral\n              else:\n                self.populate(E3, [a,b,c,  f,e,d], integral)\n        print ''\n        return E3\n\n    def make_rdm4(self, state, norb, nelec, dt=numpy.dtype('Float64'), filetype = \"binary\", link_index=None, **kwargs):\n        import os\n\n        if self.has_fourpdm == False:\n            self.twopdm = False\n            self.threepdm = False\n            self.extraline.append('threepdm\\n')\n            self.extraline.append('fourpdm\\n')\n\n            writeDMRGConfFile(self, nelec, False)\n            if self.verbose >= logger.DEBUG1:\n                inFile = self.configFile\n                #inFile = os.path.join(self.scratchDirectory,self.configFile)\n                logger.debug1(self, 'Block Input conf')\n                logger.debug1(self, open(inFile, 'r').read())\n            executeBLOCK(self)\n            if self.verbose >= logger.DEBUG1:\n                outFile = self.outputFile\n                #outFile = os.path.join(self.scratchDirectory,self.outputFile)\n                logger.debug1(self, open(outFile).read())\n            self.has_fourpdm = True\n            self.has_threepdm = True\n            self.extraline.pop()\n\n        # The binary files coming from STACKBLOCK and BLOCK are different:\n        # - STACKBLOCK does not have 4RDM\n        #   If it had, it would probably come in a 8-fold symmetr which must unpacked\n        #   using \"libunpack.unpackE4\" (see lib/icmpspt/icmpspt.c)\n        # - BLOCK just writes a list of all values, this is directly read\n        #   using \"unpackE4_BLOCK\" (see below)\n        if (filetype == \"binary\") :\n            fname = os.path.join(self.scratchDirectory,\"node0\", \"spatial_fourpdm.%d.%d.bin\" %(state, state))\n            if 'stackblock' in settings.BLOCKEXE:\n              print 'Reading binary 4RDM from STACKBLOCK'\n              fnameout = os.path.join(self.scratchDirectory,\"node0\", \"spatial_fourpdm.%d.%d.bin.unpack\" %(state, state))\n              libunpack.unpackE4(ctypes.c_char_p(fname), ctypes.c_char_p(fnameout), ctypes.c_int(norb))\n              E4 = numpy.fromfile(fnameout, dtype=numpy.dtype('Float64'))\n              E4 = numpy.reshape(E4, (norb, norb, norb, norb, norb, norb, norb, norb), order='F')\n            else:\n              print 'Reading binary 4RDM from BLOCK'\n              E4 = DMRGCI.unpackE4_BLOCK(self,fname,norb)\n\n        # The 4RDMs written by \"Fourpdm_container::save_spatial_npdm_text\" in BLOCK and STACKBLOCK\n        # are written as E4[i1,j2,k3,l4,m4,n3,o2,p1]\n        # and are stored here as E4[i1,j2,k3,l4,p1,o2,n3,m4]\n        # This is done with SQA in mind.\n        else:\n            print 'Reading text-file 4RDM'\n            fname = os.path.join(self.scratchDirectory,\"node0\", \"spatial_fourpdm.%d.%d.txt\" %(state, state))\n            f = open(fname, 'r')\n            lines = f.readlines()\n            E4 = numpy.zeros(shape=(norb, norb, norb, norb, norb, norb, norb, norb), dtype=dt, order='F')\n            assert(int(lines[0])==norb)\n            for line in lines[1:]:\n              linesp = line.split()\n              if (len(linesp) != 9) :\n                  continue\n              a, b, c, d, e, f, g, h, integral = int(linesp[0]), int(linesp[1]), int(linesp[2]), int(linesp[3]), int(linesp[4]), int(linesp[5]), int(linesp[6]), int(linesp[7]), float(linesp[8])\n              if (False):\n                up_indexes=[a,b,c,d]\n                dn_indexes=[h,g,f,e]\n                for i in range(4):\n                  for j in range(4):\n                    if (i==j):\n                      continue\n                    for k in range(4):\n                      if ((i==k)or(j==k)):\n                        continue\n                      for l in range(4):\n                        if ((i==l)or(j==l)or(k==l)):\n                          continue\n                        E4[up_indexes[i],up_indexes[j],up_indexes[k],up_indexes[l],\\\n                           dn_indexes[i],dn_indexes[j],dn_indexes[k],dn_indexes[l]] = integral\n              else:\n                self.populate(E4, [a,b,c,d,  h,g,f,e], integral)\n        print ''\n        return E4\n\n    def populate(self, array, list, value):\n        dim=len(list)/2\n        up=list[:dim]\n        dn=list[dim:]\n        import itertools\n        for t in itertools.permutations(range(dim), dim):\n          updn=[up[i] for i in t]+[dn[i] for i in t]\n          array[tuple(updn)] = value\n\n    def unpackE3_BLOCK(self,fname,norb):\n        # The 3RDMs written by \"Threepdm_container::save_spatial_npdm_binary\" in BLOCK\n        # are written as E3[i1,j2,k3,l3,m2,n1]\n        # and are stored here as E3[i1,j2,k3,n1,m2,l3]\n        # This is done with SQA in mind.\n        E3=numpy.zeros((norb,norb,norb,norb,norb,norb), order='F')\n        fil=open(fname,\"rb\")\n        fil.seek(93)\n        for a in range(norb):\n          for b in range(norb):\n            for c in range(norb):\n              for d in range(norb):\n                for e in range(norb):\n                  for f in range(norb):\n                    (value,)=struct.unpack('d',fil.read(8))\n                    E3[a,b,c,  f,e,d]=value\n        fil.close()\n        return E3\n\n    def unpackE4_BLOCK(self,fname,norb):\n        # The 4RDMs written by \"Fourpdm_container::save_spatial_npdm_binary\" in BLOCK\n        # are written as E4[i1,j2,k3,l4,m4,n3,o2,p1]\n        # and are stored here as E4[i1,j2,k3,l4,p1,o2,n3,m4]\n        # This is done with SQA in mind.\n        E4=numpy.zeros((norb,norb,norb,norb,norb,norb,norb,norb), order='F')\n        fil=open(fname,\"rb\")\n        fil.seek(109)\n        for a in range(norb):\n          for b in range(norb):\n            for c in range(norb):\n              for d in range(norb):\n                for e in range(norb):\n                  for f in range(norb):\n                    for g in range(norb):\n                      for h in range(norb):\n                        (value,)=struct.unpack('d',fil.read(8))\n                        E4[a,b,c,d,  h,g,f,e]=value\n        fil.close()\n        return E4\n\n    def clearSchedule(self):\n        self.scheduleSweeps = []\n        self.scheduleMaxMs = []\n        self.scheduleTols = []\n        self.scheduleNoises = []\n\n    def nevpt_intermediate(self, tag, norb, nelec, state, **kwargs):\n\n        if self.has_nevpt == False:\n            writeDMRGConfFile(self, nelec, True,\n                              with_2pdm=False, extraline=['restart_nevpt2_npdm'])\n            if self.verbose >= logger.DEBUG1:\n                inFile = os.path.join(self.runtimeDir, self.configFile)\n                logger.debug1(self, 'Block Input conf')\n                logger.debug1(self, open(inFile, 'r').read())\n            executeBLOCK(self)\n            if self.verbose >= logger.DEBUG1:\n                outFile = os.path.join(self.runtimeDir, self.outputFile)\n                logger.debug1(self, open(outFile).read())\n            self.has_nevpt = True\n\n        a16 = numpy.zeros( (norb, norb, norb, norb, norb, norb) )\n        filename = \"%s_matrix.%d.%d.txt\" % (tag, state, state)\n        with open(os.path.join(self.scratchDirectory, \"node0\", filename), \"r\") as f:\n            norb_read = int(f.readline().split()[0])\n            assert(norb_read == norb)\n\n            for line in f:\n                linesp = line.split()\n                i, j, k, l, m, n = [int(x) for x in linesp[:6]]\n                a16[i,j,k,l,m,n] = float(linesp[6])\n\n        return a16\n\n    def kernel(self, h1e, eri, norb, nelec, fciRestart=None, ecore=0, **kwargs):\n        if self.nroots == 1:\n            roots = 0\n        else:\n            roots = range(self.nroots)\n        if fciRestart is None:\n            fciRestart = self.restart or self._restart\n\n        if 'orbsym' in kwargs:\n            self.orbsym = kwargs['orbsym']\n        writeIntegralFile(self, h1e, eri, norb, nelec, ecore)\n        writeDMRGConfFile(self, nelec, fciRestart)\n        if self.verbose >= logger.DEBUG1:\n            inFile = os.path.join(self.runtimeDir, self.configFile)\n            logger.debug1(self, 'Block Input conf')\n            logger.debug1(self, open(inFile, 'r').read())\n        if self.onlywriteIntegral:\n            logger.info(self, 'Only write integral')\n            try:\n                calc_e = readEnergy(self)\n            except IOError:\n                if self.nroots == 1:\n                    calc_e = 0.0\n                else :\n                    calc_e = [0.0] * self.nroots\n            return calc_e, roots\n\n        executeBLOCK(self)\n        if self.verbose >= logger.DEBUG1:\n            outFile = os.path.join(self.runtimeDir, self.outputFile)\n            logger.debug1(self, open(outFile).read())\n        calc_e = readEnergy(self)\n\n        return calc_e, roots\n\n    def approx_kernel(self, h1e, eri, norb, nelec, fciRestart=None, ecore=0, **kwargs):\n        fciRestart = True\n\n        if 'orbsym' in kwargs:\n            self.orbsym = kwargs['orbsym']\n        writeIntegralFile(self, h1e, eri, norb, nelec, ecore)\n        writeDMRGConfFile(self, nelec, fciRestart, self.approx_maxIter)\n        if self.verbose >= logger.DEBUG1:\n            inFile = os.path.join(self.runtimeDir, self.configFile)\n            logger.debug1(self, 'Block Input conf')\n            logger.debug1(self, open(inFile, 'r').read())\n        executeBLOCK(self)\n        if self.verbose >= logger.DEBUG1:\n            outFile = os.path.join(self.runtimeDir, self.outputFile)\n            logger.debug1(self, open(outFile).read())\n        calc_e = readEnergy(self)\n\n        if self.nroots==1:\n            roots = 0\n        else:\n            roots = range(self.nroots)\n        return calc_e, roots\n\n    def restart_scheduler_(self):\n        def callback(envs):\n            if (envs['norm_gorb'] < self.dmrg_switch_tol or\n                ('norm_ddm' in envs and envs['norm_ddm'] < self.dmrg_switch_tol*10)):\n                self._restart = True\n            else :\n                self._restart = False\n        return callback\n\n# Block code also allows non-spin-adapted calculation. S^2 is not available in\n# this type of calculation\n    if 'spin_adapted' in settings.BLOCKEXE:\n        def spin_square(self, civec, norb, nelec):\n            if isinstance(nelec, (int, numpy.integer)):\n                nelecb = nelec//2\n                neleca = nelec - nelecb\n            else :\n                neleca, nelecb = nelec\n            s = (neleca - nelecb) * .5\n            ss = s * (s+1)\n            return ss, s*2+1\n\n\ndef make_schedule(sweeps, Ms, tols, noises, twodot_to_onedot):\n    if len(sweeps) == len(Ms) == len(tols) == len(noises):\n        schedule = ['schedule']\n        for i, s in enumerate(sweeps):\n            schedule.append('%d %6d  %8.4e  %8.4e' % (s, Ms[i], tols[i], noises[i]))\n        schedule.append('end')\n        if (twodot_to_onedot != 0):\n            schedule.append('twodot_to_onedot %i'%twodot_to_onedot)\n        return '\\n'.join(schedule)\n    else:\n\n        return 'schedule default\\nmaxM %s'%Ms[-1]\n\ndef writeDMRGConfFile(DMRGCI, nelec, Restart,\n                      maxIter=None, with_2pdm=True, extraline=[]):\n    confFile = os.path.join(DMRGCI.runtimeDir, DMRGCI.configFile)\n\n    f = open(confFile, 'w')\n\n    if isinstance(nelec, (int, numpy.integer)):\n        nelecb = (nelec-DMRGCI.spin) // 2\n        neleca = nelec - nelecb\n    else :\n        neleca, nelecb = nelec\n    f.write('nelec %i\\n'%(neleca+nelecb))\n    f.write('spin %i\\n' %(neleca-nelecb))\n    if DMRGCI.groupname is not None:\n        if isinstance(DMRGCI.wfnsym, str):\n            wfnsym = dmrg_sym.irrep_name2id(DMRGCI.groupname, DMRGCI.wfnsym)\n        else:\n            gpname = dmrg_sym.d2h_subgroup(DMRGCI.groupname)\n            assert(DMRGCI.wfnsym in dmrg_sym.IRREP_MAP[gpname])\n            wfnsym = DMRGCI.wfnsym\n        f.write('irrep %i\\n' % wfnsym)\n\n    if (not Restart):\n        #f.write('schedule\\n')\n        #f.write('0 %6i  %8.4e  %8.4e \\n' %(DMRGCI.maxM, 1e-5, 10.0))\n        #f.write('1 %6i  %8.4e  %8.4e \\n' %(DMRGCI.maxM, 1e-5, 1e-4))\n        #f.write('10 %6i  %8.4e  %8.4e \\n' %(DMRGCI.maxM, 1e-6, 1e-5))\n        #f.write('16 %6i  %8.4e  %8.4e \\n' %(DMRGCI.maxM, DMRGCI.tol/10.0, 0e-6))\n        #f.write('end\\n')\n        schedule = make_schedule(DMRGCI.scheduleSweeps,\n                                 DMRGCI.scheduleMaxMs,\n                                 DMRGCI.scheduleTols,\n                                 DMRGCI.scheduleNoises,\n                                 DMRGCI.twodot_to_onedot)\n        f.write('%s\\n' % schedule)\n    else :\n        f.write('schedule\\n')\n        #if approx == True :\n        #    f.write('0 %6i  %8.4e  %8.4e \\n' %(DMRGCI.maxM, DMRGCI.tol*10.0, 0e-6))\n        #else :\n        #    f.write('0 %6i  %8.4e  %8.4e \\n' %(DMRGCI.maxM, DMRGCI.tol, 0e-6))\n        f.write('0 %6i  %8.4e  %8.4e \\n' %(DMRGCI.maxM, DMRGCI.tol/10, 0e-6))\n        f.write('end\\n')\n        f.write('fullrestart\\n')\n        f.write('onedot \\n')\n\n    if DMRGCI.groupname is not None:\n        f.write('sym %s\\n' % dmrg_sym.d2h_subgroup(DMRGCI.groupname).lower())\n    f.write('orbitals %s\\n' % DMRGCI.integralFile)\n    if maxIter is None:\n        maxIter = DMRGCI.maxIter\n    f.write('maxiter %i\\n'%maxIter)\n    f.write('sweep_tol %8.4e\\n'%DMRGCI.tol)\n\n    f.write('outputlevel %s\\n'%DMRGCI.outputlevel)\n    f.write('hf_occ integral\\n')\n    if(with_2pdm and DMRGCI.twopdm):\n        f.write('twopdm\\n')\n    if(DMRGCI.nonspinAdapted):\n        f.write('nonspinAdapted\\n')\n    if(DMRGCI.scratchDirectory):\n        f.write('prefix  %s\\n'%DMRGCI.scratchDirectory)\n    if (DMRGCI.nroots !=1):\n        f.write('nroots %d\\n'%DMRGCI.nroots)\n        if (DMRGCI.weights==[]):\n            DMRGCI.weights= [1.0/DMRGCI.nroots]* DMRGCI.nroots\n        f.write('weights ')\n        for weight in DMRGCI.weights:\n            f.write('%f '%weight)\n        f.write('\\n')\n\n    block_extra_keyword = DMRGCI.extraline + DMRGCI.block_extra_keyword + extraline\n    if block_version(DMRGCI.executable).startswith('1.1'):\n        for line in block_extra_keyword:\n            if not ('num_thrds' in line or 'memory' in line):\n                f.write('%s\\n'%line)\n    else:\n        if DMRGCI.memory is not None:\n            f.write('memory, %i, g\\n'%(DMRGCI.memory))\n        if DMRGCI.num_thrds > 1:\n            f.write('num_thrds %d\\n'%DMRGCI.num_thrds)\n        for line in block_extra_keyword:\n            f.write('%s\\n'%line)\n    f.close()\n    #no reorder\n    #f.write('noreorder\\n')\n    return confFile\n\ndef writeIntegralFile(DMRGCI, h1eff, eri_cas, ncas, nelec, ecore=0):\n    if isinstance(nelec, (int, numpy.integer)):\n        neleca = nelec//2 + nelec%2\n        nelecb = nelec - neleca\n    else :\n        neleca, nelecb = nelec\n    integralFile = os.path.join(DMRGCI.runtimeDir, DMRGCI.integralFile)\n    if DMRGCI.groupname is not None and DMRGCI.orbsym is not []:\n# First removing the symmetry forbidden integrals. This has been done using\n# the pyscf internal irrep-IDs (stored in DMRGCI.orbsym)\n        orbsym = numpy.asarray(DMRGCI.orbsym) % 10\n        pair_irrep = (orbsym.reshape(-1,1) ^ orbsym)[numpy.tril_indices(ncas)]\n        sym_forbid = pair_irrep.reshape(-1,1) != pair_irrep.ravel()\n        eri_cas = pyscf.ao2mo.restore(4, eri_cas, ncas)\n        eri_cas[sym_forbid] = 0\n        eri_cas = pyscf.ao2mo.restore(8, eri_cas, ncas)\n# Then convert the pyscf internal irrep-ID to molpro irrep-ID\n        orbsym = numpy.asarray(dmrg_sym.convert_orbsym(DMRGCI.groupname, orbsym))\n    else:\n        orbsym = []\n        eri_cas = pyscf.ao2mo.restore(8, eri_cas, ncas)\n    if not os.path.exists(DMRGCI.scratchDirectory):\n        os.makedirs(DMRGCI.scratchDirectory)\n    if not os.path.exists(DMRGCI.runtimeDir):\n        os.makedirs(DMRGCI.runtimeDir)\n\n    pyscf.tools.fcidump.from_integrals(integralFile, h1eff, eri_cas, ncas,\n                                       neleca+nelecb, ecore, ms=abs(neleca-nelecb),\n                                       orbsym=orbsym)\n    return integralFile\n\n\ndef executeBLOCK(DMRGCI):\n\n    inFile  = DMRGCI.configFile\n    outFile = DMRGCI.outputFile\n    try:\n        cmd = ' '.join((DMRGCI.mpiprefix, DMRGCI.executable, inFile))\n        cmd = \"%s > %s 2>&1\" % (cmd, outFile)\n        check_call(cmd, cwd=DMRGCI.runtimeDir, shell=True)\n    except CalledProcessError as err:\n        logger.error(DMRGCI, cmd)\n        outFile = os.path.join(DMRGCI.runtimeDir, outFile)\n        DMRGCI.stdout.write(check_output(['tail', '-100', outFile]))\n        raise err\n\ndef readEnergy(DMRGCI):\n    file1 = open(os.path.join(DMRGCI.scratchDirectory, \"node0\", \"dmrg.e\"), \"rb\")\n    format = ['d']*DMRGCI.nroots\n    format = ''.join(format)\n    calc_e = struct.unpack(format, file1.read())\n    file1.close()\n    if DMRGCI.nroots == 1:\n        return calc_e[0]\n    else:\n        return numpy.asarray(calc_e)\n\n\ndef DMRGSCF(mf, norb, nelec, maxM=1000, tol=1.e-8, *args, **kwargs):\n    '''Shortcut function to setup CASSCF using the DMRG solver.  The DMRG\n    solver is properly initialized in this function so that the 1-step\n    algorithm can applied with DMRG-CASSCF.\n\n    Examples:\n\n    >>> mol = gto.M(atom='C 0 0 0; C 0 0 1')\n    >>> mf = scf.RHF(mol).run()\n    >>> mc = DMRGSCF(mf, 4, 4)\n    >>> mc.kernel()\n    -74.414908818611522\n    '''\n    if (hasattr(mf,'with_df')):\n      mc = mcscf.DFCASSCF(mf, norb, nelec, *args, **kwargs)\n    else:\n      mc = mcscf.CASSCF(mf, norb, nelec, *args, **kwargs)\n    mc.fcisolver = DMRGCI(mf.mol, maxM, tol=tol)\n    mc.callback = mc.fcisolver.restart_scheduler_()\n    if mc.chkfile == mc._scf._chkfile.name:\n        # Do not delete chkfile after mcscf\n        mc.chkfile = tempfile.mktemp(dir=settings.BLOCKSCRATCHDIR)\n        if not os.path.exists(settings.BLOCKSCRATCHDIR):\n            os.makedirs(settings.BLOCKSCRATCHDIR)\n    return mc\n\n\ndef dryrun(mc, mo_coeff=None):\n    '''Generate FCIDUMP and dmrg config file'''\n    if mo_coeff is None:\n        mo_coeff = mc.mo_coeff\n    mc.fcisolver.onlywriteIntegral, bak = True, mc.fcisolver.onlywriteIntegral\n    mc.casci(mo_coeff)\n    mc.fcisolver.onlywriteIntegral = bak\n\ndef block_version(blockexe):\n    version = getattr(settings, 'BLOCKVERSION', None)\n    if isinstance(version, str):\n        return version\n\n    try:\n        msg = check_output([blockexe, '-v'], stderr=STDOUT)\n        version = '1.1.0'\n        for line in msg.split('\\n'):\n            if line.startswith('Block '):\n                version = line.split()[1]\n                break\n        return version\n    except CalledProcessError:\n        f1 = tempfile.NamedTemporaryFile()\n        f1.write('memory 1 m\\n')\n        f1.flush()\n        try:\n            msg = check_output([blockexe, f1.name], stderr=STDOUT)\n        except CalledProcessError as err:\n            if 'Unrecognized option :: memory' in err.output:\n                version = '1.1.1'\n            elif 'need to specify hf_occ' in err.output:\n                version = '1.5'\n            else:\n                sys.stderr.write(err.output)\n                raise err\n        f1.close()\n        return version\n\n\nif __name__ == '__main__':\n    from pyscf import gto\n    from pyscf import scf\n    from pyscf import mcscf\n    settings.MPIPREFIX =''\n    b = 1.4\n    mol = gto.Mole()\n    mol.build(\n        verbose = 7,\n        output = 'out-dmrgci',\n        atom = [['H', (0.,0.,i-3.5)] for i in range(8)],\n        basis = {'H': 'sto-3g'},\n        symmetry = True\n    )\n    m = scf.RHF(mol)\n    m.scf()\n\n    mc = DMRGSCF(m, 4, 4)\n    mc.fcisolver.tol = 1e-9\n    emc_1 = mc.mc2step()[0]\n\n    mc = mcscf.CASCI(m, 4, 4)\n    mc.fcisolver = DMRGCI(mol)\n    mc.fcisolver.scheduleSweeps = []\n    emc_0 = mc.casci()[0]\n\n    b = 1.4\n    mol = gto.Mole()\n    mol.build(\n        verbose = 7,\n        output = 'out-casscf',\n        atom = [['H', (0.,0.,i-3.5)] for i in range(8)],\n        basis = {'H': 'sto-3g'},\n        symmetry = True\n    )\n    m = scf.RHF(mol)\n    m.scf()\n\n    mc = mcscf.CASSCF(m, 4, 4)\n    emc_1ref = mc.mc2step()[0]\n\n    mc = mcscf.CASCI(m, 4, 4)\n    emc_0ref = mc.casci()[0]\n\n    print('DMRGCI  = %.15g CASCI  = %.15g' % (emc_0, emc_0ref))\n    print('DMRGSCF = %.15g CASSCF = %.15g' % (emc_1, emc_1ref))\n\n", "meta": {"hexsha": "f7b292d4f172f8d0bd04559f5b0a3c513d5c65f3", "size": 38509, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/dmrgscf/dmrgci.py", "max_stars_repo_name": "1QB-Information-Technologies/pyscf", "max_stars_repo_head_hexsha": "8730b90439ca68106dca54d22c0d61e7422e557f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyscf/dmrgscf/dmrgci.py", "max_issues_repo_name": "1QB-Information-Technologies/pyscf", "max_issues_repo_head_hexsha": "8730b90439ca68106dca54d22c0d61e7422e557f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscf/dmrgscf/dmrgci.py", "max_forks_repo_name": "1QB-Information-Technologies/pyscf", "max_forks_repo_head_hexsha": "8730b90439ca68106dca54d22c0d61e7422e557f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-12-06T03:10:50.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-06T03:10:50.000Z", "avg_line_length": 39.7, "max_line_length": 193, "alphanum_fraction": 0.570100496, "include": true, "reason": "import numpy", "num_tokens": 11045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.18612726942801536}}
{"text": "\"\"\"\nClass for normalizing fission energy deposition\n\"\"\"\nimport bisect\nfrom collections import defaultdict\nfrom copy import deepcopy\nfrom itertools import product\nfrom numbers import Real\nimport sys\n\nfrom numpy import dot, zeros, newaxis, asarray\n\nfrom openmc.mpi import comm\nfrom openmc.checkvalue import check_type, check_greater_than\nfrom openmc.data import JOULE_PER_EV, REACTION_MT\nfrom openmc.lib import (\n    Tally, MaterialFilter, EnergyFilter, EnergyFunctionFilter)\nimport openmc.lib\nfrom .abc import (\n    ReactionRateHelper, NormalizationHelper, FissionYieldHelper,\n    TalliedFissionYieldHelper)\n\n__all__ = (\n    \"DirectReactionRateHelper\", \"ChainFissionHelper\", \"EnergyScoreHelper\"\n    \"SourceRateHelper\", \"ConstantFissionYieldHelper\", \"FissionYieldCutoffHelper\",\n    \"AveragedFissionYieldHelper\", \"FluxCollapseHelper\")\n\n# -------------------------------------\n# Helpers for generating reaction rates\n# -------------------------------------\n\n\nclass DirectReactionRateHelper(ReactionRateHelper):\n    \"\"\"Class for generating one-group reaction rates with direct tallies\n\n    This class generates reaction rate tallies for each nuclide and\n    transmutation reaction relevant for a depletion calculation.\n\n    Parameters\n    ----------\n    n_nucs : int\n        Number of burnable nuclides tracked by :class:`openmc.deplete.Operator`\n    n_react : int\n        Number of reactions tracked by :class:`openmc.deplete.Operator`\n\n    Attributes\n    ----------\n    nuclides : list of str\n        All nuclides with desired reaction rates.\n    \"\"\"\n    def __init__(self, n_nuc, n_react):\n        super().__init__(n_nuc, n_react)\n        self._rate_tally = None\n\n        # Automatically pre-calculate reaction rates for depletion\n        openmc.lib.settings.need_depletion_rx = True\n\n    @ReactionRateHelper.nuclides.setter\n    def nuclides(self, nuclides):\n        ReactionRateHelper.nuclides.fset(self, nuclides)\n        self._rate_tally.nuclides = nuclides\n\n    def generate_tallies(self, materials, scores):\n        \"\"\"Produce one-group reaction rate tally\n\n        Uses the :mod:`openmc.lib` to generate a tally\n        of relevant reactions across all burnable materials.\n\n        Parameters\n        ----------\n        materials : iterable of :class:`openmc.Material`\n            Burnable materials in the problem. Used to\n            construct a :class:`openmc.MaterialFilter`\n        scores : iterable of str\n            Reaction identifiers, e.g. ``\"(n, fission)\"``,\n            ``\"(n, gamma)\"``, needed for the reaction rate tally.\n        \"\"\"\n        self._rate_tally = Tally()\n        self._rate_tally.writable = False\n        self._rate_tally.scores = scores\n        self._rate_tally.filters = [MaterialFilter(materials)]\n\n    def get_material_rates(self, mat_id, nuc_index, react_index):\n        \"\"\"Return an array of reaction rates for a material\n\n        Parameters\n        ----------\n        mat_id : int\n            Unique ID for the requested material\n        nuc_index : iterable of int\n            Index for each nuclide in :attr:`nuclides` in the\n            desired reaction rate matrix\n        react_index : iterable of int\n            Index for each reaction scored in the tally\n\n        Returns\n        -------\n        rates : numpy.ndarray\n            Array with shape ``(n_nuclides, n_rxns)`` with the\n            reaction rates in this material\n        \"\"\"\n        self._results_cache.fill(0.0)\n        full_tally_res = self._rate_tally.mean[mat_id]\n        for i_tally, (i_nuc, i_react) in enumerate(\n                product(nuc_index, react_index)):\n            self._results_cache[i_nuc, i_react] = full_tally_res[i_tally]\n\n        return self._results_cache\n\n\nclass FluxCollapseHelper(ReactionRateHelper):\n    \"\"\"Class that generates one-group reaction rates using multigroup flux\n\n    This class generates a multigroup flux tally that is used afterward to\n    calculate a one-group reaction rate by collapsing it with continuous-energy\n    cross section data. Additionally, select nuclides/reactions can be treated\n    with a direct reaction rate tally when using a multigroup flux spectrum\n    would not be sufficiently accurate. This is often the case for (n,gamma) and\n    fission reactions.\n\n    .. versionadded:: 0.12.1\n\n    Parameters\n    ----------\n    n_nucs : int\n        Number of burnable nuclides tracked by :class:`openmc.deplete.Operator`\n    n_react : int\n        Number of reactions tracked by :class:`openmc.deplete.Operator`\n    energies : iterable of float\n        Energy group boundaries for flux spectrum in [eV]\n    reactions : iterable of str\n        Reactions for which rates should be directly tallied\n    nuclides : iterable of str\n        Nuclides for which some reaction rates should be directly tallied. If\n        None, then ``reactions`` will be used for all nuclides.\n\n    Attributes\n    ----------\n    nuclides : list of str\n        All nuclides with desired reaction rates.\n\n    \"\"\"\n    def __init__(self, n_nucs, n_reacts, energies, reactions=None, nuclides=None):\n        super().__init__(n_nucs, n_reacts)\n        self._energies = asarray(energies)\n        self._reactions_direct = list(reactions) if reactions is not None else []\n        self._nuclides_direct = list(nuclides) if nuclides is not None else None\n\n    @ReactionRateHelper.nuclides.setter\n    def nuclides(self, nuclides):\n        ReactionRateHelper.nuclides.fset(self, nuclides)\n        if self._reactions_direct and self._nuclides_direct is None:\n            self._rate_tally.nuclides = nuclides\n\n    def generate_tallies(self, materials, scores):\n        \"\"\"Produce multigroup flux spectrum tally\n\n        Uses the :mod:`openmc.lib` module to generate a multigroup flux tally\n        for each burnable material.\n\n        Parameters\n        ----------\n        materials : iterable of :class:`openmc.Material`\n            Burnable materials in the problem. Used to construct a\n            :class:`openmc.MaterialFilter`\n        scores : iterable of str\n            Reaction identifiers, e.g. ``\"(n, fission)\"``, ``\"(n, gamma)\"``,\n            needed for the reaction rate tally.\n        \"\"\"\n        self._materials = materials\n\n        # adds an entry for fisson to the dictionary of reactions\n        self._mts = [REACTION_MT[x] for x in scores]\n        self._scores = scores\n\n        # Create flux tally with material and energy filters\n        self._flux_tally = Tally()\n        self._flux_tally.writable = False\n        self._flux_tally.filters = [\n            MaterialFilter(materials),\n            EnergyFilter(self._energies)\n        ]\n        self._flux_tally.scores = ['flux']\n\n        # Create reaction rate tally\n        if self._reactions_direct:\n            self._rate_tally = Tally()\n            self._rate_tally.writable = False\n            self._rate_tally.scores = self._reactions_direct\n            self._rate_tally.filters = [MaterialFilter(materials)]\n            if self._nuclides_direct is not None:\n                self._rate_tally.nuclides = self._nuclides_direct\n\n    def get_material_rates(self, mat_index, nuc_index, react_index):\n        \"\"\"Return an array of reaction rates for a material\n\n        Parameters\n        ----------\n        mat_index : int\n            Index for material\n        nuc_index : iterable of int\n            Index for each nuclide in :attr:`nuclides` in the\n            desired reaction rate matrix\n        react_index : iterable of int\n            Index for each reaction scored in the tally\n\n        Returns\n        -------\n        rates : numpy.ndarray\n            Array with shape ``(n_nuclides, n_rxns)`` with the reaction rates in\n            this material\n\n        \"\"\"\n        self._results_cache.fill(0.0)\n\n        # Get flux for specified material\n        shape = (len(self._materials), len(self._energies) - 1)\n        mean_value = self._flux_tally.mean.reshape(shape)\n        flux = mean_value[mat_index]\n\n        # Get direct reaction rates\n        if self._reactions_direct:\n            nuclides_direct = self._rate_tally.nuclides\n            shape = (len(nuclides_direct), len(self._reactions_direct))\n            rx_rates = self._rate_tally.mean[mat_index].reshape(shape)\n\n        mat = self._materials[mat_index]\n\n        # Build nucname: density mapping to enable O(1) lookup in loop below\n        densities = dict(zip(mat.nuclides, mat.densities))\n\n        for name, i_nuc in zip(self.nuclides, nuc_index):\n            # Determine density of nuclide\n            density = densities[name]\n\n            for mt, score, i_rx in zip(self._mts, self._scores, react_index):\n                if score in self._reactions_direct and name in nuclides_direct:\n                    # Determine index in rx_rates\n                    i_rx_direct = self._reactions_direct.index(score)\n                    i_nuc_direct = nuclides_direct.index(name)\n\n                    # Get reaction rate from tally\n                    self._results_cache[i_nuc, i_rx] = rx_rates[i_nuc_direct, i_rx_direct]\n                else:\n                    # Use flux to collapse reaction rate (per N)\n                    nuc = openmc.lib.nuclides[name]\n                    rate_per_nuc = nuc.collapse_rate(\n                        mt, mat.temperature, self._energies, flux)\n\n                    # Multiply by density to get absolute reaction rate\n                    self._results_cache[i_nuc, i_rx] = rate_per_nuc * density\n\n        return self._results_cache\n\n\n# ------------------------------------------\n# Helpers for obtaining normalization factor\n# ------------------------------------------\n\n\nclass EnergyNormalizationHelper(NormalizationHelper):\n    \"\"\"Compute energy-based normalization.\"\"\"\n\n    def reset(self):\n        \"\"\"Reset energy produced prior to unpacking tallies\"\"\"\n        self._energy = 0.0\n\n    def factor(self, source_rate):\n        # Reduce energy produced from all processes\n        # J / source neutron\n        energy = comm.allreduce(self._energy) * JOULE_PER_EV\n\n        # Guard against divide by zero\n        if energy == 0:\n            if comm.rank == 0:\n                sys.stderr.flush()\n                print(\"No energy reported from OpenMC tallies. Do your HDF5 \"\n                      \"files have heating data?\\n\", file=sys.stderr, flush=True)\n            comm.barrier()\n            comm.Abort(1)\n\n        # Return normalization factor for scaling reaction rates. In this case,\n        # the source rate is the power in [W], so [W] / [J/src] = [src/s]\n        return source_rate / energy\n\n\nclass ChainFissionHelper(EnergyNormalizationHelper):\n    \"\"\"Computes normalization using fission Q values from depletion chain\n\n    Attributes\n    ----------\n    nuclides : list of str\n        All nuclides with desired reaction rates. Ordered to be\n        consistent with :class:`openmc.deplete.Operator`\n    energy : float\n        Total energy [J/s/source neutron] produced in a transport simulation.\n        Updated in the material iteration with :meth:`update`.\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self._fission_q_vector = None\n\n    def prepare(self, chain_nucs, rate_index):\n        \"\"\"Populate the fission Q value vector from a chain.\n\n        Parameters\n        ----------\n        chain_nucs : iterable of :class:`openmc.deplete.Nuclide`\n            Nuclides used in this depletion chain. Do not need\n            to be ordered\n        rate_index : dict of str to int\n            Dictionary mapping names of nuclides, e.g. ``\"U235\"``,\n            to a corresponding index in the desired fission Q\n            vector.\n        \"\"\"\n        if (self._fission_q_vector is not None\n                and self._fission_q_vector.shape == (len(rate_index),)):\n            return\n\n        fission_qs = zeros(len(rate_index))\n\n        for nuclide in chain_nucs:\n            if nuclide.name in rate_index:\n                for rx in nuclide.reactions:\n                    if rx.type == \"fission\":\n                        fission_qs[rate_index[nuclide.name]] = rx.Q\n                        break\n\n        self._fission_q_vector = fission_qs\n\n    def update(self, fission_rates):\n        \"\"\"Update energy produced with fission rates in a material\n\n        Parameters\n        ----------\n        fission_rates : numpy.ndarray\n            fission reaction rate for each isotope in the specified\n            material. Should be ordered corresponding to initial\n            ``rate_index`` used in :meth:`prepare`\n        \"\"\"\n        self._energy += dot(fission_rates, self._fission_q_vector)\n\n\nclass EnergyScoreHelper(EnergyNormalizationHelper):\n    \"\"\"Class responsible for obtaining system energy via a tally score\n\n    Parameters\n    ----------\n    score : string\n        Valid score to use when obtaining system energy from OpenMC.\n        Defaults to \"heating-local\"\n\n    Attributes\n    ----------\n    nuclides : list of str\n        List of nuclides with reaction rates. Not needed, but provided\n        for a consistent API across other :class:`NormalizationHelper`\n    energy : float\n        System energy [eV] computed from the tally. Will be zero for\n        all MPI processes that are not the \"master\" process to avoid\n        artificially increasing the tallied energy.\n    score : str\n        Score used to obtain system energy\n\n    \"\"\"\n\n    def __init__(self, score=\"heating-local\"):\n        super().__init__()\n        self.score = score\n        self._tally = None\n\n    def prepare(self, *args, **kwargs):\n        \"\"\"Create a tally for system energy production\n\n        Input arguments are not used, as the only information needed\n        is :attr:`score`\n\n        \"\"\"\n        self._tally = Tally()\n        self._tally.writable = False\n        self._tally.scores = [self.score]\n\n    def reset(self):\n        \"\"\"Obtain system energy from tally\n\n        Only the master process, ``comm.rank == 0`` will\n        have a non-zero :attr:`energy` taken from the tally.\n        This avoids accidentally scaling the system power by\n        the number of MPI processes\n        \"\"\"\n        super().reset()\n        if comm.rank == 0:\n            self._energy = self._tally.mean[0, 0]\n\n\nclass SourceRateHelper(NormalizationHelper):\n    def prepare(self, *args, **kwargs):\n        pass\n\n    def factor(self, source_rate):\n        return source_rate\n\n# ------------------------------------\n# Helper for collapsing fission yields\n# ------------------------------------\n\n\nclass ConstantFissionYieldHelper(FissionYieldHelper):\n    \"\"\"Class that uses a single set of fission yields on each isotope\n\n    Parameters\n    ----------\n    chain_nuclides : iterable of openmc.deplete.Nuclide\n        Nuclides tracked in the depletion chain. All nuclides are\n        not required to have fission yield data.\n    energy : float, optional\n        Key in :attr:`openmc.deplete.Nuclide.yield_data` corresponding\n        to the desired set of fission yield data. Typically one of\n        ``{0.0253, 500000, 14000000}`` corresponding to 0.0253 eV,\n        500 keV, and 14 MeV yield libraries. If the specific key is not\n        found, will fall back to closest energy present.\n        Default: 0.0253 eV for thermal yields\n\n    Attributes\n    ----------\n    constant_yields : collections.defaultdict\n        Fission yields for all nuclides that only have one set of\n        fission yield data. Dictionary of form ``{str: {str: float}}``\n        representing yields for ``{parent: {product: yield}}``. Default\n        return object is an empty dictionary\n    energy : float\n        Energy of fission yield libraries.\n    \"\"\"\n\n    def __init__(self, chain_nuclides, energy=0.0253):\n        check_type(\"energy\", energy, Real)\n        check_greater_than(\"energy\", energy, 0.0, equality=True)\n        self._energy = energy\n        super().__init__(chain_nuclides)\n        # Iterate over all nuclides with > 1 set of yields\n        for name, nuc in self._chain_nuclides.items():\n            yield_data = nuc.yield_data.get(energy)\n            if yield_data is not None:\n                self._constant_yields[name] = yield_data\n                continue\n            # Specific energy not found, use closest energy\n            distances = [abs(energy - ene) for ene in nuc.yield_energies]\n            min_E = min(nuc.yield_energies, key=lambda e: abs(e - energy))\n            self._constant_yields[name] = nuc.yield_data[min_E]\n\n    @classmethod\n    def from_operator(cls, operator, **kwargs):\n        \"\"\"Return a new ConstantFissionYieldHelper using operator data\n\n        All keyword arguments should be identical to their counterpart\n        in the main ``__init__`` method\n\n        Parameters\n        ----------\n        operator : openmc.deplete.TransportOperator\n            operator with a depletion chain\n        kwargs:\n            Additional keyword arguments to be used in construction\n\n        Returns\n        -------\n        ConstantFissionYieldHelper\n        \"\"\"\n        return cls(operator.chain.nuclides, **kwargs)\n\n    @property\n    def energy(self):\n        return self._energy\n\n    def weighted_yields(self, _local_mat_index=None):\n        \"\"\"Return fission yields for all nuclides requested\n\n        Parameters\n        ----------\n        _local_mat_index : int, optional\n            Current material index. Not used since all yields are\n            constant\n\n        Returns\n        -------\n        library : collections.defaultdict\n            Dictionary of ``{parent: {product: fyield}}``\n        \"\"\"\n        return self.constant_yields\n\n\nclass FissionYieldCutoffHelper(TalliedFissionYieldHelper):\n    \"\"\"Helper that computes fission yields based on a cutoff energy\n\n    Tally fission rates above and below the cutoff energy.\n    Assume that all fissions below cutoff energy have use thermal fission\n    product yield distributions, while all fissions above use a faster\n    set of yield distributions.\n\n    Uses a limit of 20 MeV for tallying fission.\n\n    Parameters\n    ----------\n    chain_nuclides : iterable of openmc.deplete.Nuclide\n        Nuclides tracked in the depletion chain. All nuclides are\n        not required to have fission yield data.\n    n_bmats : int, optional\n        Number of burnable materials tracked in the problem\n    cutoff : float, optional\n        Cutoff energy in [eV] below which all fissions will be\n        use thermal yields. All other fissions will use a\n        faster set of yields. Default: 112 [eV]\n    thermal_energy : float, optional\n        Energy of yield data corresponding to thermal yields.\n        Default: 0.0253 [eV]\n    fast_energy : float, optional\n        Energy of yield data corresponding to fast yields.\n        Default: 500 [kev]\n\n    Attributes\n    ----------\n    n_bmats : int\n        Number of burnable materials tracked in the problem.\n        Must be set prior to generating tallies\n    thermal_yields : dict\n        Dictionary of the form ``{parent: {product: yield}}``\n        with thermal yields\n    fast_yields : dict\n        Dictionary of the form ``{parent: {product: yield}}``\n        with fast yields\n    constant_yields : collections.defaultdict\n        Fission yields for all nuclides that only have one set of\n        fission yield data. Dictionary of form ``{str: {str: float}}``\n        representing yields for ``{parent: {product: yield}}``. Default\n        return object is an empty dictionary\n    results : numpy.ndarray\n        Array of fission rate fractions with shape\n        ``(n_mats, 2, n_nucs)``. ``results[:, 0]``\n        corresponds to the fraction of all fissions\n        that occured below ``cutoff``. The number\n        of materials in the first axis corresponds\n        to the number of materials burned by the\n        :class:`openmc.deplete.Operator`\n    \"\"\"\n\n    def __init__(self, chain_nuclides, n_bmats, cutoff=112.0,\n                 thermal_energy=0.0253, fast_energy=500.0e3):\n        check_type(\"cutoff\", cutoff, Real)\n        check_type(\"thermal_energy\", thermal_energy, Real)\n        check_type(\"fast_energy\", fast_energy, Real)\n        check_greater_than(\"thermal_energy\", thermal_energy, 0.0, equality=True)\n        check_greater_than(\"cutoff\", cutoff, thermal_energy, equality=False)\n        check_greater_than(\"fast_energy\", fast_energy, cutoff, equality=False)\n        self.n_bmats = n_bmats\n        super().__init__(chain_nuclides)\n        self._cutoff = cutoff\n        self._thermal_yields = {}\n        self._fast_yields = {}\n        convert_to_constant = set()\n        for name, nuc in self._chain_nuclides.items():\n            yields = nuc.yield_data\n            energies = nuc.yield_energies\n            thermal = yields.get(thermal_energy)\n            fast = yields.get(fast_energy)\n            if thermal is None or fast is None:\n                if cutoff <= energies[0]:\n                    # use lowest energy yields as constant\n                    self._constant_yields[name] = yields[energies[0]]\n                    convert_to_constant.add(name)\n                    continue\n                if cutoff >= energies[-1]:\n                    # use highest energy yields as constant\n                    self._constant_yields[name] = yields[energies[-1]]\n                    convert_to_constant.add(name)\n                    continue\n                cutoff_ix = bisect.bisect_left(energies, cutoff)\n                # find closest energy to requested thermal, fast energies\n                if thermal is None:\n                    min_E = min(energies[:cutoff_ix],\n                                key=lambda e: abs(e - thermal_energy))\n                    thermal = yields[min_E]\n                if fast is None:\n                    min_E = min(energies[cutoff_ix:],\n                                key=lambda e: abs(e - fast_energy))\n                    fast = yields[min_E]\n            self._thermal_yields[name] = thermal\n            self._fast_yields[name] = fast\n        for name in convert_to_constant:\n            self._chain_nuclides.pop(name)\n\n    @classmethod\n    def from_operator(cls, operator, **kwargs):\n        \"\"\"Construct a helper from an operator\n\n        All keyword arguments should be identical to their counterpart\n        in the main ``__init__`` method\n\n        Parameters\n        ----------\n        operator : openmc.deplete.Operator\n            Operator with a chain and burnable materials\n        kwargs:\n            Additional keyword arguments to be used in construction\n\n        Returns\n        -------\n        FissionYieldCutoffHelper\n\n        \"\"\"\n        return cls(operator.chain.nuclides, len(operator.burnable_mats),\n                   **kwargs)\n\n    def generate_tallies(self, materials, mat_indexes):\n        \"\"\"Use C API to produce a fission rate tally in burnable materials\n\n        Include a :class:`openmc.lib.EnergyFilter` to tally fission rates\n        above and below cutoff energy.\n\n        Parameters\n        ----------\n        materials : iterable of :class:`openmc.lib.Material`\n            Materials to be used in :class:`openmc.lib.MaterialFilter`\n        mat_indexes : iterable of int\n            Indices of tallied materials that will have their fission\n            yields computed by this helper. Necessary as the\n            :class:`openmc.deplete.Operator` that uses this helper\n            may only burn a subset of all materials when running\n            in parallel mode.\n        \"\"\"\n        super().generate_tallies(materials, mat_indexes)\n        energy_filter = EnergyFilter([0.0, self._cutoff, self._upper_energy])\n        self._fission_rate_tally.filters = (\n            self._fission_rate_tally.filters + [energy_filter])\n\n    def unpack(self):\n        \"\"\"Obtain fast and thermal fission fractions from tally\"\"\"\n        if not self._tally_nucs or self._local_indexes.size == 0:\n            self.results = None\n            return\n        fission_rates = self._fission_rate_tally.mean.reshape(\n            self.n_bmats, 2, len(self._tally_nucs))\n        self.results = fission_rates[self._local_indexes]\n        total_fission = self.results.sum(axis=1)\n        nz_mat, nz_nuc = total_fission.nonzero()\n        self.results[nz_mat, :, nz_nuc] /= total_fission[nz_mat, newaxis, nz_nuc]\n\n    def weighted_yields(self, local_mat_index):\n        \"\"\"Return fission yields for a specific material\n\n        For nuclides with both yield data above and below\n        the cutoff energy, the effective yield for nuclide ``A``\n        will be a weighted sum of fast and thermal yields. The\n        weights will be the fraction of ``A`` fission events\n        in the above and below the cutoff energy.\n\n        If ``A`` has fission product distribution ``F``\n        for fast fissions and ``T`` for thermal fissions, and\n        70% of ``A`` fissions are considered thermal, then\n        the effective fission product yield distributions\n        for ``A`` is ``0.7 * T + 0.3 * F``\n\n        Parameters\n        ----------\n        local_mat_index : int\n            Index for specific burnable material. Effective\n            yields will be produced using\n            ``self.results[local_mat_index]``\n\n        Returns\n        -------\n        library : collections.defaultdict\n            Dictionary of ``{parent: {product: fyield}}``\n        \"\"\"\n        yields = self.constant_yields\n        if not self._tally_nucs:\n            return yields\n        rates = self.results[local_mat_index]\n        # iterate over thermal then fast yields, prefer __mul__ to __rmul__\n        for therm_frac, fast_frac, nuc in zip(rates[0], rates[1], self._tally_nucs):\n            yields[nuc.name] = (self._thermal_yields[nuc.name] * therm_frac\n                                + self._fast_yields[nuc.name] * fast_frac)\n        return yields\n\n    @property\n    def thermal_yields(self):\n        return deepcopy(self._thermal_yields)\n\n    @property\n    def fast_yields(self):\n        return deepcopy(self._fast_yields)\n\n\nclass AveragedFissionYieldHelper(TalliedFissionYieldHelper):\n    r\"\"\"Class that computes fission yields based on average fission energy\n\n    Computes average energy at which fission events occured with\n\n    .. math::\n\n        \\bar{E} = \\frac{\n            \\int_0^\\infty E\\sigma_f(E)\\phi(E)dE\n        }{\n            \\int_0^\\infty\\sigma_f(E)\\phi(E)dE\n        }\n\n    If the average energy for a nuclide is below the lowest energy\n    with yield data, that set of fission yields is taken.\n    Conversely, if the average energy is above the highest energy\n    with yield data, that set of fission yields is used.\n    For the case where the average energy is between two sets\n    of yields, the effective fission yield computed by\n    linearly interpolating between yields provided at the\n    nearest energies above and below the average.\n\n    Parameters\n    ----------\n    chain_nuclides : iterable of openmc.deplete.Nuclide\n        Nuclides tracked in the depletion chain. All nuclides are\n        not required to have fission yield data.\n\n    Attributes\n    ----------\n    constant_yields : collections.defaultdict\n        Fission yields for all nuclides that only have one set of\n        fission yield data. Dictionary of form ``{str: {str: float}}``\n        representing yields for ``{parent: {product: yield}}``. Default\n        return object is an empty dictionary\n    results : None or numpy.ndarray\n        If tallies have been generated and unpacked, then the array will\n        have shape ``(n_mats, n_tnucs)``, where ``n_mats`` is the number\n        of materials where fission reactions were tallied and ``n_tnucs``\n        is the number of nuclides with multiple sets of fission yields.\n        Data in the array are the average energy of fission events for\n        tallied nuclides across burnable materials.\n    \"\"\"\n\n    def __init__(self, chain_nuclides):\n        super().__init__(chain_nuclides)\n        self._weighted_tally = None\n\n    def generate_tallies(self, materials, mat_indexes):\n        \"\"\"Construct tallies to determine average energy of fissions\n\n        Parameters\n        ----------\n        materials : iterable of :class:`openmc.lib.Material`\n            Materials to be used in :class:`openmc.lib.MaterialFilter`\n        mat_indexes : iterable of int\n            Indices of tallied materials that will have their fission\n            yields computed by this helper. Necessary as the\n            :class:`openmc.deplete.Operator` that uses this helper\n            may only burn a subset of all materials when running\n            in parallel mode.\n        \"\"\"\n        super().generate_tallies(materials, mat_indexes)\n        fission_tally = self._fission_rate_tally\n        filters = fission_tally.filters\n\n        ene_filter = EnergyFilter([0, self._upper_energy])\n        fission_tally.filters = filters + [ene_filter]\n\n        func_filter = EnergyFunctionFilter()\n        func_filter.set_data((0, self._upper_energy), (0, self._upper_energy))\n        weighted_tally = Tally()\n        weighted_tally.writable = False\n        weighted_tally.scores = ['fission']\n        weighted_tally.filters = filters + [func_filter]\n        self._weighted_tally = weighted_tally\n\n    def update_tally_nuclides(self, nuclides):\n        \"\"\"Tally nuclides with non-zero density and multiple yields\n\n        Must be run after :meth:`generate_tallies`.\n\n        Parameters\n        ----------\n        nuclides : iterable of str\n            Potential nuclides to be tallied, such as those with\n            non-zero density at this stage.\n\n        Returns\n        -------\n        nuclides : tuple of str\n            Union of input nuclides and those that have multiple sets\n            of yield data.  Sorted by nuclide name\n\n        Raises\n        ------\n        AttributeError\n            If tallies not generated\n        \"\"\"\n        tally_nucs = super().update_tally_nuclides(nuclides)\n        self._weighted_tally.nuclides = tally_nucs\n        return tally_nucs\n\n    def unpack(self):\n        \"\"\"Unpack tallies and populate :attr:`results` with average energies\"\"\"\n        if not self._tally_nucs or self._local_indexes.size == 0:\n            self.results = None\n            return\n        fission_results = (\n            self._fission_rate_tally.mean[self._local_indexes])\n        self.results = (\n            self._weighted_tally.mean[self._local_indexes]).copy()\n        nz_mat, nz_nuc = fission_results.nonzero()\n        self.results[nz_mat, nz_nuc] /= fission_results[nz_mat, nz_nuc]\n\n    def weighted_yields(self, local_mat_index):\n        \"\"\"Return fission yields for a specific material\n\n        Use the computed average energy of fission\n        events to determine fission yields. If average\n        energy is between two sets of yields, linearly\n        interpolate bewteen the two.\n        Otherwise take the closet set of yields.\n\n        Parameters\n        ----------\n        local_mat_index : int\n            Index for specific burnable material. Effective\n            yields will be produced using\n            ``self.results[local_mat_index]``\n\n        Returns\n        -------\n        library : collections.defaultdict\n            Dictionary of ``{parent: {product: fyield}}``. Default return\n            value is an empty dictionary\n        \"\"\"\n        if not self._tally_nucs:\n            return self.constant_yields\n        mat_yields = defaultdict(dict)\n        average_energies = self.results[local_mat_index]\n        for avg_e, nuc in zip(average_energies, self._tally_nucs):\n            nuc_energies = nuc.yield_energies\n            if avg_e <= nuc_energies[0]:\n                mat_yields[nuc.name] = nuc.yield_data[nuc_energies[0]]\n                continue\n            if avg_e >= nuc_energies[-1]:\n                mat_yields[nuc.name] = nuc.yield_data[nuc_energies[-1]]\n                continue\n            # in-between two energies\n            # linear search since there are usually ~3 energies\n            for ix, ene in enumerate(nuc_energies[:-1]):\n                if nuc_energies[ix + 1] > avg_e:\n                    break\n            lower, upper = nuc_energies[ix:ix + 2]\n            fast_frac = (avg_e - lower) / (upper - lower)\n            mat_yields[nuc.name] = (\n                nuc.yield_data[lower] * (1 - fast_frac)\n                + nuc.yield_data[upper] * fast_frac)\n        mat_yields.update(self.constant_yields)\n        return mat_yields\n\n    @classmethod\n    def from_operator(cls, operator, **kwargs):\n        \"\"\"Return a new helper with data from an operator\n\n        All keyword arguments should be identical to their counterpart\n        in the main ``__init__`` method\n\n        Parameters\n        ----------\n        operator : openmc.deplete.TransportOperator\n            Operator with a depletion chain\n        kwargs :\n            Additional keyword arguments to be used in construction\n\n        Returns\n        -------\n        AveragedFissionYieldHelper\n        \"\"\"\n        return cls(operator.chain.nuclides)\n", "meta": {"hexsha": "f223829233cf36ccdaae0a9f5df17947c7c31560", "size": 32723, "ext": "py", "lang": "Python", "max_stars_repo_path": "openmc/deplete/helpers.py", "max_stars_repo_name": "norberto-schmidt/openmc", "max_stars_repo_head_hexsha": "ff4844303154a68027b9c746300f5704f73e0875", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 262, "max_stars_repo_stars_event_min_datetime": "2018-08-09T21:27:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T05:02:10.000Z", "max_issues_repo_path": "openmc/deplete/helpers.py", "max_issues_repo_name": "norberto-schmidt/openmc", "max_issues_repo_head_hexsha": "ff4844303154a68027b9c746300f5704f73e0875", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 753, "max_issues_repo_issues_event_min_datetime": "2018-08-03T15:26:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T23:54:48.000Z", "max_forks_repo_path": "openmc/deplete/helpers.py", "max_forks_repo_name": "norberto-schmidt/openmc", "max_forks_repo_head_hexsha": "ff4844303154a68027b9c746300f5704f73e0875", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 196, "max_forks_repo_forks_event_min_datetime": "2018-08-06T13:41:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T20:47:12.000Z", "avg_line_length": 37.3977142857, "max_line_length": 90, "alphanum_fraction": 0.6265012377, "include": true, "reason": "from numpy", "num_tokens": 7374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.31405053215160805, "lm_q1q2_score": 0.1861272656230366}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport json\nimport math\nimport numpy\n\nclass Wavefront():\n\n    def __init__(self, path, triangulateQuads = True):\n\n        # These are the arrays we're going to produce, and which might \n        # make sense to manipulate from the outside:\n\n        self.vertexCoords = None  # XYZ coordinated for each vertex\n        self.vertexNormals = None # Normal (in XYZ form) for each vertex\n        self.faces = None         # Faces, specified by listing indexes for participating vertices\n\n        # These are internal work arrays\n\n        self._rawVertices = []\n        self._rawTexCo = []        \n        self._rawVertexTexCo = [];\n        self._rawFaces = []\n        self._vertexBelongsToFaces = None\n        self._faceVertCache = None\n\n        self.triangulateQuads = triangulateQuads\n\n        if not os.path.exists(path):\n            raise IOError(path + \" does not exist\")\n\n        self.content = []\n\n        with open(path,'r') as file:\n            self.content = file.readlines()\n\n        # self._mode can be:\n        #   ONLYTRIS:    The incoming mesh only contains tris (so no need to do anything)\n        #   TRIANGULATE: The incoming mesh contains quads (and may contain tris). Triangulate to get only tris.\n        #   ONLYQUADS:   The incoming mesh contains only quads. Keep these rather than triangulating\n\n        self._mode = None\n\n        # Check if mesh contains quads and/or tris\n        self._scanForMode()\n\n        # Make a sweep for vertices as faces need that information\n        self._extractVertices()\n\n        # Make a sweep for texture coordinates, as faces need that too\n        self._extractTextureCoordinates()\n\n        # Make a sweep for faces\n        self._extractFaces()\n\n        # TODO: Find texture coordinates for vertices\n\n        # create numpy arrays to contain vertices, faces and normals\n        self._createVerticesNumpyArray()\n        self._createFacesNumpyArray()\n\n        # These two operations need to be redone if vertex coordinates\n        # are changed\n        self.recalculateFaceNormals()\n        self.recalculateVertexNormals()\n\n    def _scanForMode(self):\n\n        containsTris = False\n        containsQuads = False\n\n        for line in self.content:\n            strippedLine = line.strip()\n            if not strippedLine is None and not strippedLine == \"\" and not strippedLine[0] == \"#\":\n                parts = strippedLine.split(' ')\n                if len(parts) > 4:\n                    containsQuads = True\n                if len(parts) == 4:\n                    containsTris = True\n                if len(parts) > 5:\n                    raise ValueError(\"Found a face with more than four vertices. N-gons are not supported.\")\n                # TODO: Check for n-gons?\n\n        if containsQuads:\n            if self.triangulateQuads:\n                self._mode = \"TRIANGULATE\"\n            else:\n                if containsTris:\n                    raise ValueError(\"Since the mesh contains both tris and quads, requesting the mesh to not be triangulated is illegal\")\n                else:\n                    self._mode = \"ONLYQUADS\"\n        else:\n            if containsTris:\n                self._mode = \"ONLYTRIS\"\n            else:\n                raise ValueError(\"The mesh didn't contain tris nor quads!?\")\n\n        if self._mode == \"ONLYQUADS\":\n            raise ValueError(\"The ONLYQUADS mode is not implemented yet\")\n\n        print(\"Tris \" + str(containsTris))\n        print(\"Quads \" + str(containsQuads))\n        print(self._mode)\n    \n\n    def _extractVertices(self):\n        for line in self.content:\n            strippedLine = line.strip()\n            if not strippedLine is None and not strippedLine == \"\" and not strippedLine[0] == \"#\":\n                parts = strippedLine.split(' ')\n                if len(parts) > 1:\n                    command = parts[0]\n                    if command == \"v\":\n                        x = float(parts[1])\n                        y = float(parts[2])\n                        z = float(parts[3])\n                        vertex = [x, y, z]\n                        self._rawVertices.append(vertex)\n                        self._rawVertexTexCo.append([0,0])\n\n\n    def _extractTextureCoordinates(self):\n\n        self.hasTexCo = False\n\n        for line in self.content:\n            strippedLine = line.strip()\n            if not strippedLine is None and not strippedLine == \"\" and not strippedLine[0] == \"#\":\n                parts = strippedLine.split(' ')\n                if len(parts) > 1:\n                    command = parts[0]\n                    if command == \"vt\":\n                        x = float(parts[1])\n                        y = float(parts[2])\n                        texco = [x, y]\n                        self._rawTexCo.append(texco)\n\n\n    def _distanceBetweenVerticesByIdx(self, idx1, idx2):\n\n        vert1 = numpy.array(self._rawVertices[idx1])\n        vert2 = numpy.array(self._rawVertices[idx2])    \n\n        difference = vert2 - vert1\n\n        x = difference[0]\n        y = difference[1]\n        z = difference[2]\n\n        distance = math.sqrt( x*x + y*y + z*z )\n        return distance\n\n\n    def _extractFaces(self):\n\n        # Note that wavefront lists starts at 1, not 0\n\n        for line in self.content:\n            strippedLine = line.strip()\n            if not strippedLine is None and not strippedLine == \"\" and not strippedLine[0] == \"#\":\n                parts = strippedLine.split(' ')\n                if len(parts) > 1:\n                    command = parts[0]\n                    if command == \"f\":\n\n                        # Face info is vertIdx / texCoIdx / faceNormalIdx  OR  vertIdx / texCoIdx  OR  vertIdx\n\n                        vInfo1 = parts[1].split('/')\n                        vInfo2 = parts[2].split('/')\n                        vInfo3 = parts[3].split('/')\n\n                        # Find indexes of vertices making up the face. Note \"-1\" since wavefront indexes start\n                        # at 1 rather than 0\n                        vidx1 = int(vInfo1[0]) - 1\n                        vidx2 = int(vInfo2[0]) - 1\n                        vidx3 = int(vInfo3[0]) - 1\n                        \n                        if len(parts) == 4:\n                            if self._mode == \"ONLYQUADS\":\n                                raise ValueError(\"Found tri although mode was ONLYQUADS\")\n                            face = [vidx1, vidx2, vidx3]\n                            self._rawFaces.append(face)\n                        else:\n                            vInfo4 = parts[4].split('/')\n                            vidx4 = int(vInfo4[0]) - 1\n                            if self._mode == \"ONLYTRIS\":\n                                raise ValueError(\"Found quad although mode was ONLYTRIS\")\n                            if self._mode == \"ONLYQUADS\":\n                                raise ValueError(\"ONLYQUADS mode not implemented yet\")\n\n                            # Perform triangulation by splitting quad into two tris, using the shortest diagonal\n                            distance13 = self._distanceBetweenVerticesByIdx(vidx1, vidx3)\n                            distance24 = self._distanceBetweenVerticesByIdx(vidx2, vidx4)\n\n                            if distance13 > distance24:\n                                face = [vidx1, vidx2, vidx4]\n                                self._rawFaces.append(face)\n                                face = [vidx3, vidx4, vidx2]\n                                self._rawFaces.append(face)\n                            else:\n                                face = [vidx1, vidx3, vidx4]\n                                self._rawFaces.append(face)\n                                face = [vidx2, vidx3, vidx1]\n                                self._rawFaces.append(face)\n\n                        i = 1\n                        while i < len(parts):\n\n                            f = parts[i].split('/')\n\n                            if len(f) > 1:\n                                vidx = int(f[0]) - 1 # Vertex index\n\n                                ti = f[1] # May be empty if no UV unwrap\n                                if ti != \"\":\n                                    tidx = int(ti) - 1 # Texture coordinate index\n                                    texco = self._rawTexCo[tidx] # Actual texture coordinats, x/y\n                                    self._rawVertexTexCo[vidx] = texco\n                                    self.hasTexCo = True\n\n                            i = i + 1\n\n\n    def _createFacesNumpyArray(self, assumeQuads = False):\n\n        numberOfFaces = len(self._rawFaces)\n\n        vertsPerFace = 3\n        if assumeQuads:\n            vertsPerFace = 4\n\n        # Create a two-dimensional int array with shape (numFace/vertsPerFace) and \n        # fill it values from the wavefront obj. This will contain vert indices.\n\n        self.faces = numpy.array( self._rawFaces, dtype=int ) # Values will be copied from self._rawFaces\n\n        # Create a two-dimensional float array with shape (numFace/ 3 ) and \n        # fill it with zeros. This will contain faces normals, but needs to\n        # be recalculated.\n\n        self.faceNormals = numpy.zeros( (numberOfFaces, 3), dtype=float )\n\n\n    def _createVerticesNumpyArray(self):\n\n        numberOfVertices = len(self._rawVertices)\n\n        if numberOfVertices != len(self._rawVertexTexCo):\n            raise ValueError(\"Not same number of elements in texco array\")\n\n        # Convert raw coords from wavefront into a 2d numpy array\n        self.vertexCoords = numpy.array( self._rawVertices, dtype=float )\n\n        # Create a two-dimensional float array with shape (numVerts/3) and \n        # fill it with zeros. This will contain vertex normals.\n        self.vertexNormals = numpy.zeros( (numberOfVertices, 3), dtype=float )\n\n        # Create a two-dimensional float array with shape (numVerts/2) and \n        # fill it with texture coordinates. \n        self.vertexTexCo = numpy.array( self._rawVertexTexCo, dtype=float )\n\n    \n\n\n    def recalculateVertexNormals(self, assumeQuads = False):\n\n        # Build a cache where we, per vertex, list which faces are relevant\n        # for it. We need this in order to calculate the vertex normal later,\n        # as an average of the face normals surrounding it\n        if self._vertexBelongsToFaces is None:\n\n            self._vertexBelongsToFaces = []\n\n            numberOfFaces = len(self.faces)\n            numberOfVertices = len(self.vertexCoords)\n\n            vertsPerFace = 3\n            if assumeQuads:\n                vertsPerFace = 4\n\n            currentVert = 0\n            while currentVert < numberOfVertices:\n                self._vertexBelongsToFaces.append([])\n                currentVert = currentVert + 1 \n\n            currentFace = 0\n            while currentFace < numberOfFaces:\n                fv = self.faces[currentFace]\n                currentVert = 0\n                while currentVert < vertsPerFace:\n                    vertexIndex = fv[currentVert]\n                    self._vertexBelongsToFaces[vertexIndex].append(currentFace)\n                    currentVert = currentVert + 1\n                currentFace = currentFace + 1\n        \n        # Calculate vertex normals as an average of the surrounding face\n        # normals. \n        currentVert = 0\n\n        zeroNormal = numpy.array([0.0, 0.0, 0.0], dtype=float)\n\n        while currentVert < numberOfVertices:\n            faces = self._vertexBelongsToFaces[currentVert]\n            numberOfFaces = len(faces)\n            currentNormal = numpy.array([0,0,0], dtype=float)\n            currentFace = 0\n            firstNormal = None\n            while currentFace < numberOfFaces:\n                fidx = faces[currentFace]\n                fnormal = self.faceNormals[fidx]\n                if firstNormal is None:\n                    firstNormal = fnormal\n                currentNormal = currentNormal + fnormal\n                currentFace = currentFace + 1\n            if numberOfFaces < 1:\n                raise ValueError(\"Found a vertex (\" + str(currentVert) + \") which did not belong to any face\")\n\n            averageNormal = currentNormal / numberOfFaces\n\n            if numpy.array_equal(averageNormal, zeroNormal):\n                print(\"WARNING: found zero vertex normal for vertex \" + str(currentVert))\n                averageNormal = firstNormal\n\n            self.vertexNormals[currentVert] = self._unitVector(averageNormal)\n\n            currentVert = currentVert + 1\n\n\n    def recalculateFaceNormals(self):\n\n        self._copyVertCoordsToCache()\n\n        # Calculate the face normal from the first three vertices. This might produce \n        # strange results if using quads. In that case we should probably triangulate and\n        # and weight together the face normals of the resulting two tris. \n        numberOfFaces = len(self.faces)\n\n        currentFace = 0\n        while currentFace < numberOfFaces:\n\n            U = self._faceVertCache[currentFace][1] - self._faceVertCache[currentFace][0]\n            V = self._faceVertCache[currentFace][2] - self._faceVertCache[currentFace][0]\n\n            cross = numpy.cross(U,V)\n            N = self._unitVector(cross)\n\n            self.faceNormals[currentFace] = N\n            currentFace = currentFace + 1\n\n\n    def _unitVector(self, normal):\n\n        # There is probably a numpy version of doing this calculation \n\n        x = normal[0] * normal[0]\n        y = normal[1] * normal[1]\n        z = normal[2] * normal[2]\n\n        magnitude = math.sqrt(x + y + z)\n\n        if magnitude == 0.0:\n            print(\"\\nINVALID MAGNITUDE:\\n\")\n            print(\"Normal was: \" + str(normal))\n            raise ValueError(\"Invalid magnitude\")\n            sys.exit(1)\n\n        return normal / magnitude\n\n\n    def _copyVertCoordsToCache(self, assumeQuads = False):\n\n        # Create a two-dimensional float array with shape ( numFace / vertsPerFace / 3 ) and \n        # fill it with the coordinates for each vertex participating  in each face\n        #\n        # This cache is used when recalculating face normals\n\n        numberOfFaces = len(self.faces)\n\n        vertsPerFace = 3\n        if assumeQuads:\n            vertsPerFace = 4\n\n        if self._faceVertCache is None:\n            self._faceVertCache = numpy.zeros( (numberOfFaces, vertsPerFace, 3), dtype=float )\n\n        currentFace = 0\n        while currentFace < numberOfFaces:\n            currentVertex = 0\n            while currentVertex < vertsPerFace:\n                vertexIndex = self.faces[currentFace][currentVertex]\n                self._faceVertCache[currentFace][currentVertex] = self.vertexCoords[vertexIndex]\n                currentVertex = currentVertex + 1\n            currentFace = currentFace + 1\n\n\n    def getVertexArray(self):\n        return self.vertexCoords\n\n\n    def getVertexNormals(self):\n        return self.vertexNormals\n\n\n    def getVertexAndNormalArray(self):\n        # This should possibly be cached\n        return numpy.hstack( (self.vertexCoords, self.vertexNormals) )\n\n    def getVertexAndNormalAndTexCoArray(self):\n        # This should possibly be cached\n        return numpy.hstack( (self.vertexCoords, self.vertexNormals, self.vertexTexCo) )\n\n\n    def getFaceArray(self):\n        return self.faces\n\n\n    def debugVertices(self):\n\n        vertices = self.getVertexAndNormalArray()\n\n        for vertex in vertices:\n            out = \"[\"\n            for i in vertex:\n                out = out + \" \" + str(round(i,4))\n            out = out + \" ]\"\n            print(out)\n\n\n\n", "meta": {"hexsha": "bb2131ce2d4fde796ac59c0ef60701b0817da56f", "size": 15517, "ext": "py", "lang": "Python", "max_stars_repo_path": "genericgl/wavefront.py", "max_stars_repo_name": "makehumancommunity/gl-test-cases", "max_stars_repo_head_hexsha": "47f553883a03193cd0ca1d2f9e2e9ca687afd6ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "genericgl/wavefront.py", "max_issues_repo_name": "makehumancommunity/gl-test-cases", "max_issues_repo_head_hexsha": "47f553883a03193cd0ca1d2f9e2e9ca687afd6ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "genericgl/wavefront.py", "max_forks_repo_name": "makehumancommunity/gl-test-cases", "max_forks_repo_head_hexsha": "47f553883a03193cd0ca1d2f9e2e9ca687afd6ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-08-09T15:21:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T14:17:06.000Z", "avg_line_length": 35.9189814815, "max_line_length": 138, "alphanum_fraction": 0.5464329445, "include": true, "reason": "import numpy", "num_tokens": 3318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.1860068473271219}}
{"text": "from itertools import chain\nimport numpy as np\nfrom numpy.polynomial.chebyshev import chebval\nfrom scipy.spatial import Delaunay\n\nfrom ..utils.smoothing import smoothspec\nfrom .constants import lightspeed, lsun, jansky_cgs, to_cgs_at_10pc\n\ntry:\n    from sklearn.neighbors import KDTree\nexcept(ImportError):\n    from scipy.spatial import cKDTree as KDTree\n\ntry:\n    from sedpy.observate import getSED, vac2air, air2vac\nexcept(ImportError):\n    pass\n\n\n__all__ = [\"StarBasis\", \"BigStarBasis\"]\n\n\n# Useful constants\n# value to go from L_sun to erg/s/cm^2 at 10pc\nto_cgs = to_cgs_at_10pc\n\n# for converting Kurucz spectral units\nlog4pi = np.log10(4 * np.pi)\nlog_rsun_cgs = np.log10(6.955) + 10\nlog_lsun_cgs = np.log10(lsun)\nlog_SB_cgs = np.log10(5.6704e-5)\nlog_SB_solar = log_SB_cgs + 2 * log_rsun_cgs - log_lsun_cgs\n\n\nclass StarBasis(object):\n\n    _spectra = None\n\n    def __init__(self, libname='ckc14_deimos.h5', verbose=False,\n                 n_neighbors=0, log_interp=True, logify_Z=False,\n                 use_params=None, rescale_libparams=False, in_memory=True,\n                 norm_spec = False,\n                 **kwargs):\n        \"\"\"An object which holds the stellar spectral library, performs\n        interpolations of that library, and has methods to return attenuated,\n        normalized, smoothed stellar spectra.  The interpolations are performed\n        using barycenter coordinates of the enclosing simplex found from the\n        Delauynay triangulation.  This is not tractable for large dimension\n        (see BigStarBasis for that case).\n\n        :param libname:\n            Path to the hdf5 file to use for the spectral library.\n\n        :param verbose:\n            If True, print information about the parameters used when a point\n            is outside the convex hull.\n\n        :param n_neighbors: (default:0)\n            Number of nearest neighbors to use when requested parameters are\n            outside the convex hull of the library prameters.  If ``0`` then a\n            ValueError is raised instead of the nearest spectrum.  If greater\n            than 1 then the neighbors are combined using inverse distance\n            weights.\n\n        :param log_interp: (default:True)\n            Switch to interpolate in log(flux) instead of linear flux.\n\n        :param use_params:\n            Sequence of strings. If given, only use the listed parameters\n            (which must be present in the `_libparams` structure) to build the\n            grid and construct spectra.  Otherwise all fields of `_libparams`\n            will be used.\n\n        :param rescale_libparams: (default: False)\n            If True, rescale the parameters to the unit cube before generating\n            the triangulation (and kd-tree).  Note that the `param_vector`\n            method will also rescale the input parameters in this case.  This\n            can help for nearest neighbor lookup and in the triangulation based\n            weights when your variables have very different scales, assuming\n            that the ranges give a reasonable relative distance metric.\n\n        :param in_memory: (default: True)\n            Switch to keep the spectral library in memory or access it through\n            the h5py File object.  Note if the latter, then zeroed spectra are\n            *not* filtered out.\n        \"\"\"\n        # Cache initialization variables\n        self.verbose = verbose\n        self.logarithmic = log_interp\n        self.logify_Z = logify_Z\n        self._in_memory = in_memory\n        self._libname = libname\n        self.n_neighbors = n_neighbors\n        self._rescale = rescale_libparams\n        self.norm_spec = norm_spec\n\n        # Load the library\n        self.load_lib(libname)\n\n        # Do some important bookkeeping\n        if use_params is None:\n            self.stellar_pars = self._libparams.dtype.names\n        else:\n            self.stellar_pars = tuple(use_params)\n        self.ndim = len(self.stellar_pars)\n\n        # Build the triangulation and kdtree (after rescaling)\n        if self._rescale:\n            ranges = [[self._libparams[d].min(), self._libparams[d].max()]\n                      for d in self.stellar_pars]\n            self.parameter_range = np.array(ranges).T\n        self.triangulate()\n        try:\n            self.build_kdtree()\n        except NameError:\n            pass\n\n        self.params = {}\n\n    def load_lib(self, libname='', driver=None):\n        \"\"\"Read a CKC library which has been pre-convolved to be close to your\n        resolution.  This library should be stored as an HDF5 file, with the\n        datasets ``wavelengths``, ``parameters`` and ``spectra``.  These are\n        ndarrays of shape (nwave,), (nmodels,), and (nmodels, nwave)\n        respecitvely.  The ``parameters`` array is a structured array.  Spectra\n        with no fluxes > 1e-32 are removed from the library if the librarty is\n        kept in memory.\n        \"\"\"\n        import h5py\n        f = h5py.File(libname, \"r\", driver=driver)\n        self._wave = np.array(f['wavelengths'])\n        self._libparams = np.array(f['parameters'])\n\n        if self._in_memory:\n\n            if not self.norm_spec:\n                self._spectra = np.array(f['spectra'])\n\n            elif self.norm_spec:\n                self._spectra = np.array(f['spectra']) / np.array(f['continuua'])\n\n            f.close()\n            # Filter library so that only existing spectra are included\n            maxf = np.max(self._spectra, axis=1)\n            good = maxf > 1e-32\n            self._libparams = self._libparams[good]\n            self._spectra = self._spectra[good, :]\n        else:\n\n            if not self.norm_spec:\n                self._spectra = f['spectra']\n            elif self.norm_spec:\n                self._spectra = f['spectra'] / f['continuua']\n\n        if self.logify_Z:\n            from numpy.lib import recfunctions as rfn\n            self._libparams['Z'] = np.log10(self._libparams['Z'])\n            self._libparams = rfn.rename_fields(self._libparams, {'Z': 'logZ'})\n\n    def update(self, **kwargs):\n        \"\"\"Update the `params` dictionary, turning length 1 arrays into scalars\n        and pull out functions from length one arrays\n        \"\"\"\n        for k, val in list(kwargs.items()):\n            v = np.atleast_1d(val)\n            try:\n                if (len(v) == 1) and callable(v[0]):\n                    self.params[k] = v[0]\n                else:\n                    self.params[k] = np.squeeze(v)\n            except(KeyError):\n                pass\n\n    def get_spectrum(self, outwave=None, filters=None, peraa=False, **kwargs):\n        \"\"\"Return an attenuated, smoothed, distance dimmed stellar spectrum and SED.\n\n        :returns spec:\n            The spectrum on the outwave grid (assumed in air), in AB maggies.\n            If peraa is True then the spectrum is erg/s/cm^2/AA.\n\n        :returns phot:\n            Observed frame photometry in units of AB maggies.  If ``lumdist``\n            is not present in the parameters then these are absolute maggies,\n            otherwise they are apparent.\n\n        :returns x:\n            A blob of extra quantities (e.g. mass, uncertainty)\n        \"\"\"\n        self.update(**kwargs)\n\n        # star spectrum (in Lsun/Hz)\n        wave, spec, unc = self.get_star_spectrum(**self.params)\n        spec *= self.normalize()\n\n        # dust\n        if 'dust_curve' in self.params:\n            att = self.params['dust_curve'](self._wave, **self.params)\n            spec *= np.exp(-att)\n\n        # Redshifting + Wavelength solution.  We also convert to in-air.\n        a = 1 + self.params.get('zred', 0)\n        b = 0.0\n\n        if 'wavecal_coeffs' in self.params:\n            x = wave - wave.min()\n            x = 2.0 * (x / x.max()) - 1.0\n            c = np.insert(self.params['wavecal_coeffs'], 0, 0)\n            # assume coeeficients give shifts in km/s\n            b = chebval(x, c) / (lightspeed*1e-13)\n\n        wa, sa = vac2air(wave) * (a + b), spec * a\n        if outwave is None:\n            outwave = wa\n\n        # Broadening, interpolation onto output wavelength grid\n        if 'sigma_smooth' in self.params:\n            smspec = self.smoothspec(wa, sa, self.params['sigma_smooth'],\n                                     outwave=outwave, **self.params)\n        elif outwave is not wa:\n            smspec = np.interp(outwave, wa, sa, left=0, right=0)\n        else:\n            smspec = sa\n\n        # Photometry (observed frame absolute maggies)\n        if filters is not None:\n            mags = getSED(wa, sa * lightspeed / wa**2 * to_cgs, filters)\n            phot = np.atleast_1d(10**(-0.4 * mags))\n        else:\n            phot = 0.0\n\n        # Distance dimming.  Default to 10pc distance (i.e. absolute)\n        dfactor = (self.params.get('lumdist', 1e-5) * 1e5)**2\n        if peraa:\n            # spectrum will be in erg/s/cm^2/AA\n            smspec *= to_cgs / dfactor * lightspeed / outwave**2\n        else:\n            # Spectrum will be in maggies\n            smspec *= to_cgs / dfactor / (3631*jansky_cgs)\n\n        # Convert from absolute maggies to apparent maggies\n        phot /= dfactor\n\n        return smspec, phot, None\n\n    def get_star_spectrum(self, **kwargs):\n        \"\"\"Given stellar parameters, obtain an interpolated spectrum at those\n        parameters.\n\n        :param **kwargs:\n            Keyword arguments must include values for the parameters listed in\n            ``stellar_pars``.\n\n        :returns wave:\n            The wavelengths at which the spectrum is defined.\n\n        :returns spec:\n            The spectrum interpolated to the requested parameters.  This has\n            the same units as the supplied library spectra.\n\n        :returns unc:\n            The uncertainty spectrum, where the uncertainty is due to\n            interpolation error.  Curently unimplemented (i.e. it is a None\n            type object).\n        \"\"\"\n        inds, wghts = self.weights(**kwargs)\n        if self.logarithmic:\n            spec = np.exp(np.dot(wghts, np.log(self._spectra[inds, :])))\n        else:\n            spec = np.dot(wghts, self._spectra[inds, :])\n        spec_unc = None\n        return self._wave, spec, spec_unc\n\n    def smoothspec(self, wave, spec, sigma, outwave=None, **kwargs):\n        outspec = smoothspec(wave, spec, sigma, outwave=outwave, **kwargs)\n        return outspec\n\n    def normalize(self):\n        \"\"\"Use either `logr` or `logl` to normalize the spectrum.  Both should\n        be in solar units.  `logr` is checked first.  If neither is present\n        then 1.0 is returned.\n\n        :returns norm:\n            Factor by which the CKC spectrum should be multiplied to get units\n            of L_sun/Hz.  This assumes the native library spectrum is in units\n            of erg/s/cm^2/Hz/sr.\n        \"\"\"\n        if 'logr' in self.params:\n            twologr = 2. * (self.params['logr'] + log_rsun_cgs)\n        elif 'logl' in self.params:\n            twologr = ((self.params['logl'] + log_lsun_cgs) -\n                       4 * self.params['logt'] - log_SB_cgs - log4pi)\n        else:\n            return 1.0\n\n        norm = 10**(twologr + 2 * log4pi - log_lsun_cgs)\n        return norm\n\n    def weights(self, **kwargs):\n        \"\"\"Delauynay weighting.  Return indices of the models forming the\n        enclosing simplex, as well as the barycentric coordinates of the point\n        within this simplex to use as weights.  If point is outside the convex\n        hull then fallback to nearest neighbor unless ``n_neighbors`` is 0.\n        \"\"\"\n        inparams = np.squeeze(self.param_vector(**kwargs))\n        triangle_ind = self._dtri.find_simplex(inparams)\n        if triangle_ind == -1:\n            self.edge_flag = True\n            if self.n_neighbors == 0:\n                pstring = ', '.join(self.ndim * ['{}={}'])\n                pstring = pstring.format(*chain(*zip(self.stellar_pars, inparams)))\n                raise ValueError(\"Requested spectrum ({}) outside convex hull,\"\n                                 \" and nearest neighbor interpolation turned \"\n                                 \"off.\".format(*pstring))\n            ind, wght = self.weights_knn(inparams, k=self.n_neighbors)\n            if self.verbose:\n                print(\"Parameters {0} outside model convex hull. \"\n                      \"Using model index {1} instead. \".format(inparams, ind))\n            return ind, wght\n\n        inds = self._dtri.simplices[triangle_ind, :]\n        transform = self._dtri.transform[triangle_ind, :, :]\n        Tinv = transform[:self.ndim, :]\n        x_r = inparams - transform[self.ndim, :]\n        bary = np.dot(Tinv, x_r)\n        last = np.clip(1.0 - bary.sum(), 0.0, 1.0)\n        wghts = np.append(bary, last)\n        oo = inds.argsort()\n        return inds[oo], wghts[oo]\n\n    def rescale_params(self, points):\n        \"\"\"Rescale the given parameters to the unit cube, if the ``_rescale`` attribute is ``True``\n\n        :param points:\n            An array of parameter values, of shape (npoint, ndim)\n\n        :returns x:\n            An array of parameter values rescaled to the unit cube, ndarray of\n            shape (npoint, ndim)\n        \"\"\"\n        if self._rescale:\n            x = np.atleast_2d(points)\n            x = (x - self.parameter_range[0, :]) / np.diff(self.parameter_range, axis=0)\n            return np.squeeze(x)\n        else:\n            return points\n\n    def triangulate(self):\n        \"\"\"Build the Delauynay Triangulation of the model library.\n        \"\"\"\n        # slow.  should use a view based method\n        model_points = np.array([list(self._libparams[d])\n                                 for d in self.stellar_pars]).T\n        self._dtri = Delaunay(self.rescale_params(model_points))\n\n    def build_kdtree(self):\n        \"\"\"Build the kdtree of the model points.\n        \"\"\"\n        # slow.  should use a view based method\n        model_points = np.array([list(self._libparams[d])\n                                 for d in self.stellar_pars])\n        self._kdt = KDTree(self.rescale_params(model_points.T))\n\n    def weights_knn(self, target_points, k=1):\n        \"\"\"The interpolation weights are determined from the inverse distance\n        to the k nearest neighbors.\n\n        :param target_points: ndarray, shape(ntarg,npar)\n            The coordinates to which you wish to interpolate.\n\n        :param k:\n            The number of nearest neighbors to use.\n\n        :returns inds: ndarray, shape(ntarg,npar+1)\n             The model indices of the interpolates.\n\n        :returns weights: narray, shape (ntarg,npar+1)\n             The weights of each model given by ind in the interpolates.\n        \"\"\"\n        try:\n            dists, inds = self._kdt.query(np.atleast_2d(target_points), k=k,\n                                          return_distance=True)\n        except:\n            return [0], [0]\n        inds = np.atleast_1d(np.squeeze(inds))\n        if k == 1:\n            return inds, np.ones(inds.shape)\n        weights = 1 / dists\n        # weights[np.isinf(weights)] = large_number\n        weights = weights/weights.sum(axis=-1)\n        return inds, np.atleast_1d(np.squeeze(weights))\n\n    def param_vector(self, **kwargs):\n        \"\"\"Take a dictionary of parameters and return the stellar library\n        parameter vector corresponding to these parameters as an ndarray.\n        Raises a KeyError if the dictionary does not contain *all* of the\n        required stellar parameters.\n        \"\"\"\n        pvec = [kwargs[n] for n in self.stellar_pars]\n        return self.rescale_params(np.array(pvec))\n\n    @property\n    def wavelengths(self):\n        return self._wave\n\n\nclass BigStarBasis(StarBasis):\n\n    def __init__(self, libname='', verbose=False, log_interp=True,\n                 n_neighbors=0, driver=None, in_memory=False,\n                 use_params=None, strictness=0.0, **kwargs):\n        \"\"\"An object which holds the stellar spectral library, performs linear\n        interpolations of that library, and has methods to return attenuated,\n        normalized, smoothed stellar spoectra.\n\n        This object is set up to work with large grids, so the models file is\n        kept open for access from disk.  scikits-learn or scipy kd-trees are\n        required for model access.  Ideally the grid should be regular (though\n        the spacings need not be equal along a given dimension).\n\n        :param libname:\n            Path to the hdf5 file to use for the spectral library.\n\n        :param n_neighbors: (default:0)\n            Number of nearest neighbors to use when requested parameters are\n            outside the convex hull of the library prameters.  If ``0`` then a\n            ValueError is raised instead of the nearest spectrum.  Does not\n            work, currently.\n\n        :param verbose:\n            If True, print information about the parameters used when a point\n            is outside the convex hull\n\n        :param log_interp: (default: True)\n            Interpolate in log(flux) instead of flux.\n\n        :param in_memory: (default: False)\n            Switch to determine whether the grid is loaded in memory or read\n            from disk each time a model is constructed (like you'd want for\n            very large grids).\n\n        :param use_params:\n            Sequence of strings. If given, only use the listed parameters\n            (which must be present in the `_libparams` structure) to build the\n            grid and construct spectra.  Otherwise all fields of `_libparams`\n            will be used.\n\n        :param strictness: (default: 0.0)\n            Float from 0.0 to 1.0 that gives the fraction of a unit hypercube\n            that is required for a parameter position to be accepted.  That is,\n            if the weights of the enclosing vertices sum to less than this\n            number, raise an error.\n        \"\"\"\n        self.verbose = verbose\n        self.logarithmic = log_interp\n        self._libname = libname\n        self.n_neighbors = n_neighbors\n        self._in_memory = in_memory\n        self._strictness = strictness\n\n        self.load_lib(libname, driver=driver)\n        # Do some important bookkeeping\n        if use_params is None:\n            self.stellar_pars = self._libparams.dtype.names\n        else:\n            self.stellar_pars = tuple(use_params)\n        self.ndim = len(self.stellar_pars)\n        self.lib_as_grid()\n        self.params = {}\n\n    def load_lib(self, libname='', driver=None):\n        \"\"\"Read a ykc library which has been preconvolved to be close to your\n        data resolution. This library should be stored as an HDF5 file, with\n        the datasets ``wavelengths``, ``parameters`` and ``spectra``.  These\n        are ndarrays of shape (nwave,), (nmodels,), and (nmodels, nwave)\n        respecitvely.  The ``parameters`` array is a structured array.  The h5\n        file object is left open so that spectra can be accessed from disk.\n        \"\"\"\n        import h5py\n        f = h5py.File(libname, \"r\", driver=driver)\n        self._wave = np.array(f['wavelengths'])\n        self._libparams = np.array(f['parameters'])\n        if self._in_memory:\n            self._spectra = np.array(f['spectra'])\n            f.close()\n        else:\n            self._spectra = f['spectra']\n\n    def get_star_spectrum(self, **kwargs):\n        \"\"\"Given stellar parameters, obtain an interpolated spectrum at those\n        parameters.\n\n        :param **kwargs:\n            Keyword arguments must include values for the ``stellar_pars``\n            parameters that are stored in ``_libparams``.\n\n        :returns wave:\n            The wavelengths at which the spectrum is defined.\n\n        :returns spec:\n            The spectrum interpolated to the requested parameters\n\n        :returns unc:\n            The uncertainty spectrum, where the uncertainty is due to\n            interpolation error.  Curently unimplemented (i.e. it is a None\n            type object)\n        \"\"\"\n        inds, wghts = self.weights(**kwargs)\n        if self.logarithmic:\n            spec = np.exp(np.dot(wghts, np.log(self._spectra[inds, :])))\n        else:\n            spec = np.dot(wghts, self._spectra[inds, :])\n        spec_unc = None\n        return self._wave, spec, spec_unc\n\n    def weights(self, **params):\n        inds = self.knearest_inds(**params)\n        wghts = self.linear_weights(inds, **params)\n        if wghts.sum() <= self._strictness:\n            raise ValueError(\"Something is wrong with the weights\")\n        good = wghts > 0\n        # if good.sum() < 2**self.ndim:\n        #     raise ValueError(\"Did not find all vertices of the hypercube, \"\n        #                      \"or there is no enclosing hypercube in the library.\")\n        inds = inds[good]\n        wghts = wghts[good]\n        wghts /= wghts.sum()\n        return inds, wghts\n\n    def lib_as_grid(self):\n        \"\"\"Convert the library parameters to pixel indices in each dimension,\n        and build and store a KDTree for the pixel coordinates.\n        \"\"\"\n        # Get the unique gridpoints in each param\n        self.gridpoints = {}\n        for p in self.stellar_pars:\n            self.gridpoints[p] = np.unique(self._libparams[p])\n        # Digitize the library parameters\n        X = np.array([np.digitize(self._libparams[p], bins=self.gridpoints[p],\n                                  right=True) for p in self.stellar_pars])\n        self.X = X.T\n        # Build the KDTree\n        self._kdt = KDTree(self.X)  # , metric='euclidean')\n\n    def params_to_grid(self, **targ):\n        \"\"\"Convert a set of parameters to grid pixel coordinates.\n\n        :param targ:\n            The target parameter location, as keyword arguments.  The elements\n            of ``stellar_pars`` must be present as keywords.\n\n        :returns x:\n            The target parameter location in pixel coordinates.\n        \"\"\"\n        # bin index\n        inds = np.array([np.digitize([targ[p]], bins=self.gridpoints[p], right=False) - 1\n                         for p in self.stellar_pars])\n        inds = np.squeeze(inds)\n        # fractional index.  Could use stored denominator to be slightly faster\n        try:\n            find = [(targ[p] - self.gridpoints[p][i]) /\n                    (self.gridpoints[p][i+1] - self.gridpoints[p][i])\n                    for i, p in zip(inds, self.stellar_pars)]\n        except(IndexError):\n            pstring = \"{0}: min={2} max={3} targ={1}\\n\"\n            s = [pstring.format(p, targ[p], *self.gridpoints[p][[0, -1]])\n                 for p in self.stellar_pars]\n            raise ValueError(\"At least one parameter outside grid.\\n{}\".format(' '.join(s)))\n        return inds + np.squeeze(find)\n\n    def knearest_inds(self, **params):\n        \"\"\"Find all parameter ``vertices`` within a sphere of radius\n        sqrt(ndim).  The parameter values are converted to pixel coordinates\n        before a search of the KDTree.\n\n        :param params:\n             Keyword arguments which must include keys corresponding to\n             ``stellar_pars``, the parameters of the grid.\n\n        :returns inds:\n             The sorted indices of all vertices within sqrt(ndim) of the pixel\n             coordinates, corresponding to **params.\n        \"\"\"\n        # Convert from physical space to grid index space\n        xtarg = self.params_to_grid(**params)\n        # Query the tree within radius sqrt(ndim)\n        try:\n            inds = self._kdt.query_radius(xtarg.reshape(1, -1),\n                                          r=np.sqrt(self.ndim))\n        except(AttributeError):\n            inds = self._kdt.query_ball_point(xtarg.reshape(1, -1),\n                                              np.sqrt(self.ndim))\n        return np.sort(inds[0])\n\n    def linear_weights(self, knearest, **params):\n        \"\"\"Use ND-linear interpolation over the knearest neighbors.\n\n        :param knearest:\n            The indices of the ``vertices`` for which to calculate weights.\n\n        :param params:\n            The target parameter location, as keyword arguments.\n\n        :returns wght:\n            The weight for each vertex, computed as the volume of the hypercube\n            formed by the target parameter and each vertex.  Vertices more than\n            1 away from the target in any dimension are given a weight of zero.\n        \"\"\"\n        xtarg = self.params_to_grid(**params)\n        x = self.X[knearest, :]\n        dx = xtarg - x\n        # Fractional pixel weights\n        wght = ((1 - dx) * (dx >= 0) + (1 + dx) * (dx < 0))\n        # set weights to zero if model is more than a pixel away\n        wght *= (dx > -1) * (dx < 1)\n        # compute hyperarea for each model and return\n        return wght.prod(axis=-1)\n\n    def triangle_weights(self, knearest, **params):\n        \"\"\"Triangulate the k-nearest models, then use the barycenter of the\n        enclosing simplex to interpolate.\n        \"\"\"\n        inparams = np.array([params[p] for p in self.stellar_pars])\n        dtri = Delaunay(self.model_points[knearest, :])\n        triangle_ind = dtri.find_simplex(inparams)\n        inds = dtri.simplices[triangle_ind, :]\n        transform = dtri.transform[triangle_ind, :, :]\n        Tinv = transform[:self.ndim, :]\n        x_r = inparams - transform[self.ndim, :]\n        bary = np.dot(Tinv, x_r)\n        last = 1.0 - bary.sum()\n        wghts = np.append(bary, last)\n        oo = inds.argsort()\n        return inds[oo], wghts[oo]\n", "meta": {"hexsha": "678df7c84b6133b4fbcc47366c685910775593ae", "size": 25281, "ext": "py", "lang": "Python", "max_stars_repo_path": "prospect/sources/star_basis.py", "max_stars_repo_name": "vedantchandra/prospector", "max_stars_repo_head_hexsha": "c63ca8076828d13d53f3d3e54cf54f07801d9a08", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prospect/sources/star_basis.py", "max_issues_repo_name": "vedantchandra/prospector", "max_issues_repo_head_hexsha": "c63ca8076828d13d53f3d3e54cf54f07801d9a08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prospect/sources/star_basis.py", "max_forks_repo_name": "vedantchandra/prospector", "max_forks_repo_head_hexsha": "c63ca8076828d13d53f3d3e54cf54f07801d9a08", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8753943218, "max_line_length": 99, "alphanum_fraction": 0.5961393932, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 5941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.18600684358106404}}
{"text": "import numbers\nfrom collections.abc import Iterable\nimport numpy as np\nfrom numpy.random import normal\nfrom qutip.qobjevo import QobjEvo, EvoElement\nfrom qutip.qip.gates import (\n    expand_operator, _check_qubits_oper)\nfrom qutip.qobj import Qobj\nfrom qutip.operators import sigmaz, destroy, identity\nfrom qutip.tensor import tensor\n\n\n__all__ = [\"Noise\", \"DecoherenceNoise\", \"RelaxationNoise\",\n           \"ControlAmpNoise\", \"RandomNoise\", \"UserNoise\"]\n\n\ndef _dummy_qobjevo(dims, **kwargs):\n    \"\"\"\n    Create a dummy :class\":`qutip.QobjEvo` with\n    a constant zero Hamiltonian. This is used since empty QobjEvo\n    is not yet supported.\n    \"\"\"\n    dummy = QobjEvo(tensor([identity(d) for d in dims]) * 0., **kwargs)\n    return dummy\n\n\nclass Noise(object):\n    \"\"\"\n    The base class representing noise in a processor.\n    The noise object can be added to :class:`qutip.qip.Processor` and\n    contributes to evolution.\n    \"\"\"\n    def __init__(self):\n        pass\n\n    def _check_coeff_num(self, coeffs, ops_num):\n        if len(coeffs) != ops_num:\n            raise ValueError(\n                \"The length of coeffs is not {}\".format(ops_num))\n\n\nclass DecoherenceNoise(Noise):\n    \"\"\"\n    The decoherence noise in a processor. It generates a list of\n    collapse operators.\n\n    Parameters\n    ----------\n    c_ops: :class:`qutip.Qobj` or list\n        The Hamiltonian representing the dynamics of the noise.\n        len(ops)=len(coeffs) is required.\n\n    targets: int or list, optional\n        The indices of qubits that are acted on. Default is the first\n        N qubits\n\n    coeffs: list, optional\n        A list of the coefficients for the control Hamiltonians.\n        For available choice, see :class:`Qutip.QobjEvo`\n\n    tlist: array_like, optional\n        A NumPy array specifies the time of each coefficient.\n\n    all_qubits: bool, optional\n        If c_ops contains only single qubits collapse operator,\n        all_qubits=True will allow it to be applied to all qubits.\n\n    Attributes\n    ----------\n    c_ops: :class:`qutip.Qobj` or list\n        The Hamiltonian representing the dynamics of the noise.\n\n    targets: list\n        The indices of qubits that are acted on.\n\n    coeffs: list\n        A list of the coefficients for the control Hamiltonians.\n        For available choice, see :class:`Qutip.QobjEvo`\n\n    tlist: array_like\n        A NumPy array specifies the time of each coefficient.\n\n    all_qubits: bool\n        If c_ops contains only single qubits collapse operator,\n        all_qubits=True will allow it to be applied to all qubits.\n    \"\"\"\n    def __init__(self, c_ops, targets=None, coeffs=None, tlist=None,\n                 all_qubits=False):\n        if isinstance(c_ops, Qobj):\n            self.c_ops = [c_ops]\n        else:\n            self.c_ops = c_ops\n        self.coeffs = coeffs\n        self.tlist = tlist\n        self.targets = targets\n        if all_qubits:\n            if not all([c_op.dims == [[2], [2]] for c_op in self.c_ops]):\n                raise ValueError(\n                    \"The operator is not a single qubit operator, \"\n                    \"thus cannot be applied to all qubits\")\n        self.all_qubits = all_qubits\n\n    def get_noise(self, N, dims=None):\n        \"\"\"\n        Return the quantum objects representing the noise.\n\n        Parameters\n        ----------\n        N: int\n            The number of component systems.\n\n        dims: list, optional\n            The dimension of the components system, the default value is\n            [2,2...,2] for qubits system.\n\n        Returns\n        -------\n        qobjevo_list: list\n            A list of :class:`qutip.Qobj` or :class:`qutip.QobjEvo`\n            representing the decoherence noise.\n        \"\"\"\n        if dims is None:\n            dims = [2] * N\n        qobj_list = []\n        for i, c_op in enumerate(self.c_ops):\n            if self.all_qubits:\n                qobj_list += expand_operator(\n                    oper=c_op, N=N, targets=self.targets, dims=dims,\n                    cyclic_permutation=True)\n            else:\n                qobj_list.append(\n                    expand_operator(\n                        oper=c_op, N=N, targets=self.targets, dims=dims))\n        # time-independent\n        if self.coeffs is None:\n            return qobj_list\n        # time-dependent\n        if self.tlist is None:\n            raise ValueError(\"tlist is required for time-dependent noise.\")\n        qobjevo_list = []\n        for i, temp in enumerate(qobj_list):\n            self._check_coeff_num(self.coeffs, len(qobj_list))\n            qobjevo_list.append(QobjEvo(\n                [qobj_list[i], self.coeffs[i]],\n                tlist=self.tlist))\n        return qobjevo_list\n\n\nclass RelaxationNoise(Noise):\n    \"\"\"\n    The decoherence on each qubit characterized by two time scales t1 and t2.\n\n    Parameters\n    ----------\n    t1: float or list, optional\n        Characterize the decoherence of amplitude damping for\n        each qubit.\n\n    t2: float or list, optional\n        Characterize the decoherence of dephasing for\n        each qubit.\n\n    Attributes\n    ----------\n    t1: list\n        Characterize the decoherence of amplitude damping for\n        each qubit.\n\n    t2: list\n        Characterize the decoherence of dephasing for\n        each qubit.\n    \"\"\"\n    def __init__(self, t1=None, t2=None):\n        self.t1 = t1\n        self.t2 = t2\n\n    def _T_to_list(self, T, N):\n        \"\"\"\n        Check if the relaxation time is valid\n\n        Parameters\n        ----------\n        T: list of float\n            The relaxation time\n\n        N: int\n            The number of component systems.\n\n        Returns\n        -------\n        T: list\n            The relaxation time in Python list form\n        \"\"\"\n        if (isinstance(T, numbers.Real) and T > 0) or T is None:\n            return [T] * N\n        elif isinstance(T, Iterable) and len(T) == N:\n            if all([isinstance(t, numbers.Real) and t > 0 for t in T]):\n                return T\n        else:\n            raise ValueError(\n                \"Invalid relaxation time T={},\"\n                \"either the length is not equal to the number of qubits, \"\n                \"or T is not a positive number.\".format(T))\n\n    def get_noise(self, N, dims=None):\n        \"\"\"\n        Return the quantum objects representing the noise.\n\n        Parameters\n        ----------\n        N: int\n            The number of component systems.\n\n        dims: list, optional\n            The dimension of the components system, the default value is\n            [2,2...,2] for qubits system.\n\n        Returns\n        -------\n        qobjevo_list: list\n            A list of :class:`qutip.Qobj` or :class:`qutip.QobjEvo`\n            representing the decoherence noise.\n        \"\"\"\n        if dims is None:\n            dims = [2] * N\n        self.t1 = self._T_to_list(self.t1, N)\n        self.t2 = self._T_to_list(self.t2, N)\n        if len(self.t1) != N or len(self.t2) != N:\n            raise ValueError(\n                \"Length of t1 or t2 does not match N, \"\n                \"len(t1)={}, len(t2)={}\".format(\n                    len(self.t1), len(self.t2)))\n        qobjevo_list = []\n        for qu_ind in range(N):\n            t1 = self.t1[qu_ind]\n            t2 = self.t2[qu_ind]\n            if t1 is not None:\n                qobjevo_list.append(\n                    expand_operator(\n                        1/np.sqrt(t1) * destroy(2), N, qu_ind, dims=dims))\n            if t2 is not None:\n                # Keep the total dephasing ~ exp(-t/t2)\n                if t1 is not None:\n                    if 2*t1 < t2:\n                        raise ValueError(\n                            \"t1={}, t2={} does not fulfill \"\n                            \"2*t1>t2\".format(t1, t2))\n                    T2_eff = 1./(1./t2-1./2./t1)\n                else:\n                    T2_eff = t2\n                qobjevo_list.append(\n                    expand_operator(\n                        1/np.sqrt(2*T2_eff) * sigmaz(), N, qu_ind, dims=dims))\n        return qobjevo_list\n\n\nclass ControlAmpNoise(Noise):\n    \"\"\"\n    The noise in the amplitude of the control pulse.\n\n    Parameters\n    ----------\n    coeffs: list\n        A list of the coefficients for the control Hamiltonians.\n        For available choices, see :class:`Qutip.QobjEvo`.\n\n    tlist: array_like, optional\n        A NumPy array specifies the time of each coefficient.\n\n    ops: :class:`qutip.Qobj` or list\n        The Hamiltonian representing the dynamics of the noise.\n        len(ops)=len(coeffs) is required.\n\n    targets: int or list, optional\n        The indices of qubits that are acted on. Default is the first\n        N qubits\n\n    cyclic_permutation: boolean, optional\n        If true, the Hamiltonian will be expanded for\n        all cyclic permutation of the target qubits.\n\n    Attributes\n    ----------\n    coeffs: list\n        A list of the coefficients for the control Hamiltonians.\n        For available choices, see :class:`Qutip.QobjEvo`.\n\n    tlist: array_like\n        A NumPy array specifies the time of each coefficient.\n\n    ops: list\n        The Hamiltonian representing the dynamics of the noise.\n\n    targets: list\n        The indices of qubits that are acted on.\n\n    cyclic_permutation: boolean\n        If true, the Hamiltonian will be expanded for\n        all cyclic permutation of the target qubits.\n    \"\"\"\n    def __init__(self, coeffs, tlist, ops=None, targets=None,\n                 cyclic_permutation=False):\n        self.coeffs = coeffs\n        self.tlist = tlist\n        if isinstance(ops, Qobj):\n            self.ops = [ops]\n        else:\n            self.ops = ops\n        self.targets = targets\n        self.cyclic_permutation = cyclic_permutation\n\n    def get_noise(self, N, proc_qobjevo=None, dims=None):\n        \"\"\"\n        Return the quantum objects representing the noise.\n\n        Parameters\n        ----------\n        N: int\n            The number of component systems.\n\n        proc_qobjevo: :class:`qutip.QobjEvo`, optional\n            If no operator is defined in the noise object, `proc_qobjevo`\n            will be used as operators, otherwise the operators in the\n            object is used.\n\n        dims: list, optional\n            The dimension of the components system, the default value is\n            [2,2...,2] for qubits system.\n\n        Returns\n        -------\n        noise_qobjevo: :class:`qutip.QobjEvo`\n            A :class:`qutip.Qobj` representing the noise.\n        \"\"\"\n        if dims is None:\n            dims = [2] * N\n\n        # If new operators are given\n        if self.ops is not None:\n            if self.cyclic_permutation:\n                ops = []\n                for op in self.ops:\n                    ops += expand_operator(\n                        oper=op, N=N, targets=self.targets, dims=dims,\n                        cyclic_permutation=True)\n            else:\n                ops = [\n                    expand_operator(\n                        oper=op, N=N, targets=self.targets, dims=dims)\n                    for op in self.ops]\n        # If no operators given, use operators in the processor\n        elif proc_qobjevo is not None:\n            # If there is a constant part\n            if proc_qobjevo.cte.norm() > 1.e-15:\n                ops = [proc_qobjevo.cte]\n            else:\n                ops = []\n            ops += [ele.qobj for ele in proc_qobjevo.ops]\n        else:\n            raise ValueError(\n                \"No operators found.\")\n\n        if len(ops) > len(self.coeffs):\n            raise ValueError(\"The number of coefficient has to be larger than\"\n                             \"{}\".format(len(ops)))\n        return QobjEvo([[ops[i], self.coeffs[i]] for i in range(len(ops))],\n                       tlist=self.tlist)\n\n\nclass RandomNoise(ControlAmpNoise):\n    \"\"\"\n    Random noise in the amplitude of the control pulse. The arguments for\n    the random generator need to be given as key word arguments.\n\n    Parameters\n    ----------\n    rand_gen: numpy.random, optional\n        A random generator in numpy.random, it has to take a ``size``\n        parameter.\n\n    dt: float, optional\n        The time interval between two random amplitude. The coefficients\n        of the noise are the same within this time range.\n\n    ops: list, optional\n        The Hamiltonian representing the dynamics of the noise.\n\n    targets: list or int, optional\n        The indices of qubits that are acted on.\n\n    cyclic_permutation: boolean, optional\n        If true, the Hamiltonian will be expanded for\n        all cyclic permutation of the target qubits.\n\n    kwargs:\n        Key word arguments for the random number generator.\n\n    Attributes\n    ----------\n    ops: list\n        The Hamiltonian representing the dynamics of the noise.\n\n    coeffs: list\n        A list of the coefficients for the control Hamiltonians.\n        For available choices, see :class:`Qutip.QobjEvo`.\n\n    targets: list\n        The indices of qubits that are acted on.\n\n    cyclic_permutation: boolean\n        If true, the Hamiltonian will be expanded for\n        all cyclic permutation of the target qubits.\n\n    rand_gen: numpy.random\n        A random generator in numpy.random, it has to take a ``size``\n        parameter.\n\n    kwargs: dict\n        Key word arguments for the random number generator.\n    \"\"\"\n    def __init__(\n            self, rand_gen=None, dt=None, ops=None, targets=None,\n            cyclic_permutation=False, **kwargs):\n        super(RandomNoise, self).__init__(\n            coeffs=None, tlist=None, ops=ops, targets=targets,\n            cyclic_permutation=cyclic_permutation)\n        if rand_gen is None:\n            self.rand_gen = np.random.normal\n        else:\n            self.rand_gen = rand_gen\n        self.kwargs = kwargs\n        if \"size\" in kwargs:\n            raise ValueError(\"size is preditermined inside the noise object.\")\n        self.dt = dt\n\n    def get_noise(self, N, proc_qobjevo=None, dims=None):\n        \"\"\"\n        Return the quantum objects representing the noise.\n\n        Parameters\n        ----------\n        N: int\n            The number of component systems.\n\n        proc_qobjevo: :class:`qutip.QobjEvo`, optional\n            If no operator is defined in the noise object, `proc_qobjevo`\n            wil be used as operators, otherwise the operators in the\n            object is used.\n\n        dims: list, optional\n            The dimension of the components system, the default value is\n            [2,2...,2] for qubits system.\n\n        Returns\n        -------\n        noise_qobjevo: :class:`qutip.QobjEvo`\n            A :class:`qutip.Qobj` representing the decoherence noise.\n        \"\"\"\n        if dims is None:\n            dims = [2] * N\n        tlist = proc_qobjevo.tlist\n        if self.ops is not None:\n            if self.cyclic_permutation:\n                ops_num = len(self.ops) * N\n            else:\n                ops_num = len(self.ops)\n        elif proc_qobjevo is not None:\n            # +1 for the constant part in QobjEvo,\n            # if no cte part the last coeffs will be ignored\n            ops_num = len(proc_qobjevo.ops) + 1\n        if self.dt is not None:\n            # create new tlist and random coeffs\n            num_rand = int(np.floor((tlist[-1]-tlist[0])/self.dt))+1\n            self.coeffs = self.rand_gen(\n                **self.kwargs, size=(ops_num, num_rand))\n            tlist = (np.arange(0, self.dt*num_rand, self.dt)[:num_rand] +\n                     tlist[0])\n            # [:num_rand] for round of error like 0.2*6=1.2000000000002\n        else:\n            self.coeffs = self.rand_gen(\n                **self.kwargs, size=(ops_num, len(tlist)))\n        self.tlist = tlist\n        return super(RandomNoise, self).get_noise(\n            N, proc_qobjevo=proc_qobjevo, dims=dims)\n\n\nclass UserNoise(Noise):\n    \"\"\"\n    Abstract class for user defined noise. To define a noise object,\n    one could overwrite the constructor and the class method `get_noise`.\n    \"\"\"\n    def get_noise(self, N, proc_qobjevo, dims=None):\n        \"\"\"\n        Template method. To define a noise object,\n        one should over write this method and\n        return the unitary evolution part as a :class: `qutip.QobjEvo`\n        and a list of collapse operators in the form of either\n        :class: `qutip.QobjEvo` or :class: `qutip.Qobj`.\n\n        Parameters\n        ----------\n        N: int\n            The number of component systems.\n\n        proc_qobjevo: :class:`qutip.QobjEvo`\n            The object representing the ideal evolution in the processor.\n\n        dims: list, optional\n            The dimension of the components system, the default value is\n            [2,2...,2] for qubits system.\n\n        Returns\n        -------\n        noise_qobjevo: :class:`qutip.QobjEvo`\n            A :class:`qutip.Qobj` representing the decoherence noise.\n\n        collapse_list: list\n            A list of :class:`qutip.Qobj` or :class:`qutip.QobjEvo`\n            representing the decoherence noise.\n        \"\"\"\n        if dims is None:\n            dims = [2] * N\n        return _dummy_qobjevo(dims), []\n", "meta": {"hexsha": "1aa1bcbc9294c89bbd006d037a7f2209ee139302", "size": 17068, "ext": "py", "lang": "Python", "max_stars_repo_path": "qutip/qip/device/noise.py", "max_stars_repo_name": "dweigand/qutip", "max_stars_repo_head_hexsha": "b57d5e4b4846880e894afa390c62f4d095c642e1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "qutip/qip/device/noise.py", "max_issues_repo_name": "dweigand/qutip", "max_issues_repo_head_hexsha": "b57d5e4b4846880e894afa390c62f4d095c642e1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qutip/qip/device/noise.py", "max_forks_repo_name": "dweigand/qutip", "max_forks_repo_head_hexsha": "b57d5e4b4846880e894afa390c62f4d095c642e1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.572519084, "max_line_length": 78, "alphanum_fraction": 0.5731778767, "include": true, "reason": "import numpy,from numpy", "num_tokens": 4019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3451052776934245, "lm_q1q2_score": 0.18600595404751952}}
{"text": "import os.path\nimport glob\nfrom collections import OrderedDict\n\nimport numpy as np\nimport astropy.units as u\nfrom astropy.table import Table, Column\nimport scipy.io\nfrom sunpy.io.special.genx import read_genx\nfrom sunpy.time import parse_time\nfrom sunpy.data import manager\n\n__all__  = ['chianti_kev_line_common_load_light', 'chianti_kev_line_common_load',\n            'chianti_kev_cont_common_load', 'read_abundance_genx', 'load_xray_abundances']\n\ndef chianti_kev_line_common_load_light():\n    \"\"\"\n    Read only X-ray emission line info needed for the chianti_kev functions.\n\n    Unlike chianti_kev_line_common_load which formats and returns all in the file,\n    this function only returns the data required by the ChiantiKevLines class.\n\n    Returns\n    -------\n    zindex: `numpy.ndarray`\n        Indicies of elements as they appear in periodic table.\n\n    line_peak_energies: `astropy.units.Quantity` of `list` of `astropy.units.Quantity`\n        The energies of the line peaks.\n\n    line_logT_bins: `numpy.ndarray` or `list` of `numpy.ndarray`\n        The log10 temperature bins over which the line intensities are known.\n\n    line_colEMs: `astropy.units.Quantity` of `list` of `astropy.units.Quantity`\n        The column emission measures used to calculate the intensities for each line.\n\n    line_element_indices: `numpy.ndarray` or `list` of `numpy.ndarray`\n        The atomic number of each line minus 1.\n\n    line_intensities: `astropy.units.Quantity`\n        Intensities of each of the lines in line_properties over a temperature axis.\n        The array is 2D with axes of (line, temperature axis)\n    \"\"\"\n    # Read linefile\n    contents = _read_linefile()\n    out = contents[\"out\"]\n\n    zindex = contents[\"zindex\"]\n    line_logT_bins = _clean_array_dims(out[\"LOGT_ISOTHERMAL\"])\n    line_colEMs = 10.**_clean_array_dims(out[\"LOGEM_ISOTHERMAL\"]) / u.cm**5\n    wvl_units = _clean_units(out[\"WVL_UNITS\"])\n    int_units = _clean_units(out[\"INT_UNITS\"])\n\n    line_intensities = []\n    line_element_indices = []\n    line_peak_energies = []\n    for j, lines in enumerate(out[\"lines\"]):\n        line_element_indices.append(lines[\"IZ\"])\n        line_peak_energies.append(u.Quantity(lines[\"WVL\"], unit=wvl_units).to(u.keV, equivalencies=u.spectral()))\n\n        # Sort lines in ascending energy.\n        ordd = np.argsort(np.array(line_peak_energies[j]))\n        line_element_indices[j] = line_element_indices[j][ordd]\n        line_peak_energies[j] = line_peak_energies[j][ordd]\n\n        # Extract line intensities.\n        line_intensities.append(_extract_line_intensities(lines[\"INT\"][ordd]) * int_units)\n\n    # If there is only one element in the line properties, unpack values.\n    if len(out[\"lines\"]) == 1:\n        line_element_indices = line_element_indices[0]\n        line_peak_energies = line_peak_energies[0]\n        line_intensities = line_intensities[0]\n\n    return zindex, line_peak_energies, line_logT_bins, line_colEMs, line_element_indices, \\\n        line_intensities\n\n\ndef chianti_kev_line_common_load():\n    \"\"\"\n    Read file containing X-ray emission line info needed for the chianti_kev functions.\n\n    Returns\n    -------\n    zindex: `numpy.ndarray`\n        Indicies of elements as they appear in periodic table.\n\n    line_meta: `dict`\n        Various metadata associated with line properties.\n\n    line_properties: `astropy.table.Table`\n        Various properties of each lines.\n\n    line_intensities: `astropy.units.Quantity`\n        Intensities of each of the lines in line_properties over a temperature axis.\n        The array is 2D with axes of (line, temperature axis)\n    \"\"\"\n    # Read linefile.\n    contents = _read_linefile()\n    zindex = contents[\"zindex\"]\n    out = contents[\"out\"]\n\n    # Repackage metadata from file.\n    date = []\n    for date_byte in out[\"DATE\"]:\n        date_strings = str(date_byte[3:], 'utf-8').split()\n        date.append(parse_time(\"{0}-{1}-{2} {3}\".format(date_strings[3], date_strings[0],\n                                                        date_strings[1], date_strings[2])))\n    if len(date) == 1:\n        date = date[0]\n    line_meta = {\n        \"IONEQ_LOGT\": _clean_array_dims(out[\"IONEQ_LOGT\"]),\n        \"IONEQ_NAME\": _clean_string_dims(out[\"IONEQ_NAME\"]),\n        \"IONEQ_REF\": _combine_strings(out[\"IONEQ_REF\"]),\n        \"WVL_LIMITS\": _clean_array_dims(out[\"WVL_LIMITS\"]),\n        \"MODEL_FILE\": _clean_string_dims(out[\"MODEL_FILE\"]),\n        \"MODEL_NAME\": _clean_string_dims(out[\"MODEL_NAME\"]),\n        \"MODEL_NE\": _clean_array_dims(out[\"MODEL_NE\"]),\n        \"MODEL_PE\": _clean_array_dims(out[\"MODEL_PE\"]),\n        \"MODEL_TE\": _clean_array_dims(out[\"MODEL_TE\"]),\n        \"WVL_UNITS\": _clean_units(out[\"WVL_UNITS\"]),\n        \"INT_UNITS\": _clean_units(out[\"INT_UNITS\"]),\n        \"ADD_PROTONS\": _clean_array_dims(out[\"ADD_PROTONS\"], dtype=int),\n        \"DATE\": date,\n        \"VERSION\": _clean_string_dims(out['VERSION']),\n        \"PHOTOEXCITATION\": _clean_array_dims(out[\"PHOTOEXCITATION\"], dtype=int),\n        \"LOGT_ISOTHERMAL\": _clean_array_dims(out[\"LOGT_ISOTHERMAL\"]),\n        \"LOGEM_ISOTHERMAL\": _clean_array_dims(out[\"LOGEM_ISOTHERMAL\"]),\n        \"chianti_doc\": _clean_chianti_doc(contents[\"chianti_doc\"])\n        }\n\n    # Repackage out[\"line\"] into a Table with appropriate units.\n    # Create a list of tables to make sure all data in file is captured.\n    # Although only one iteration is expected.\n    line_properties = []\n    line_intensities = []\n    for lines in out[\"lines\"]:\n        line_props = Table()\n        line_props[\"IZ\"] = Column(lines[\"IZ\"], description=\"Atomic number of ion element.\")\n        line_props[\"ION\"] = Column(lines[\"ION\"],\n            description=\"Integer ionization state in astronomical notation, i.e. ION-1 = negative charge of ion.\")\n        line_props[\"IDENT\"] = Column(lines[\"IDENT\"])\n        line_props[\"IDENT_LATEX\"] = Column(lines[\"IDENT_LATEX\"])\n        line_props[\"SNOTE\"] = Column(lines[\"SNOTE\"],\n            description=\"Ion label in astronomical (roman numeral) notation.\")\n        line_props[\"LVL1\"] = Column(lines[\"LVL1\"])\n        line_props[\"LVL2\"] = Column(lines[\"LVL2\"])\n        line_props[\"TMAX\"] = Column(lines[\"TMAX\"])\n        line_props[\"WVL\"] = Column(lines[\"WVL\"], unit=line_meta[\"WVL_UNITS\"])\n        line_props[\"ENERGY\"] = line_props[\"WVL\"].quantity.to(u.keV, equivalencies=u.spectral())\n        line_props[\"FLAG\"] = Column(lines[\"FLAG\"])\n\n        # Sort lines in ascending energy.\n        ordd = np.argsort(np.array(line_props[\"WVL\"]))[::-1]\n        line_props = line_props[ordd]\n\n        # Extract line intensities.\n        line_intensities.append(_extract_line_intensities(lines[\"INT\"][ordd]))\n\n        # Enter outputs from this iteration into list.\n        line_properties.append(line_props)\n        line_intensities.append(line_ints)\n\n    # If there is only one element in the line properties, unpack values.\n    if len(out[\"lines\"]) == 1:\n        line_properties = line_properties[0]\n        line_intensities = line_intensities[0]\n\n    return zindex, line_meta, line_properties, line_intensities * line_meta[\"INT_UNITS\"]\n\n\n@manager.require('chianti_cont_1_250',\n                 ['https://hesperia.gsfc.nasa.gov/ssw/packages/xray/dbase/chianti/chianti_cont_1_250_v71.sav'],\n                 'aadf4355931b4c241ac2cd5669e89928615dc1b55c9fce49a155b70915a454dd')\ndef chianti_kev_cont_common_load(_extra=None):\n    \"\"\"\n    Read X-ray continuum emission info needed for the chianti_kev functions.\n\n    Returns\n    -------\n    zindex: `numpy.ndarray`\n        Indicies of elements as they appear in periodic table.\n    continuum_properties: `dict`\n        Properties of continuum emission.\n    \"\"\"\n    contfile = manager.get(\"chianti_cont_1_250\")\n    # Read file\n    contents = scipy.io.readsav(contfile)\n    zindex = contents[\"zindex\"]\n    edge_str = {\n            \"CONVERSION\": _clean_array_dims(contents[\"edge_str\"][\"CONVERSION\"]),\n            \"WVL\": _clean_array_dims(contents[\"edge_str\"][\"WVL\"]),\n            \"WVLEDGE\": _clean_array_dims(contents[\"edge_str\"][\"WVLEDGE\"])\n                }\n    continuum_properties = {\n            \"totcont\": contents[\"totcont\"],\n            \"totcont_lo\": contents[\"totcont_lo\"],\n            \"edge_str\": edge_str,\n            \"ctemp\": contents[\"ctemp\"],\n            \"chianti_doc\": _clean_chianti_doc(contents[\"chianti_doc\"])\n                            }\n\n    return zindex, continuum_properties\n\n\n@manager.require('xray_abundances',\n                 ['https://hesperia.gsfc.nasa.gov/ssw/packages/xray/dbase/chianti/xray_abun_file.genx'],\n                 '92c0e1f9a83da393cc38840752fda5a5b44c5b18a4946e5bf12c208771fe0fd3')\ndef load_xray_abundances(abundance_type=None):\n    \"\"\"\n    Returns the abundances written in the xray_abun_file.genx\n\n    The abundances are taken from CHIANTI and MEWE.  The source filenames are:\n    cosmic sun_coronal sun_coronal_ext sun_hybrid sun_hybrid_ext sun_photospheric mewe_cosmic mewe_solar\n    The first six come fron Chianti, the last two from Mewe.  They are:\n    cosmic sun_coronal sun_coronal_ext sun_hybrid sun_hybrid_ext sun_photospheric mewe_cosmic mewe_solar\n    These abundances are used with CHIANTI_KEV.  MEWE_KEV can only use the two mewe sourced\n    abundance distributions unless using a heavily modified rel_abun structure for all of the elements.\n\n    Parameters\n    ----------\n    abundance_type: `str`\n        Type of abundance to be read from file.  Option are (From Chianti)\n        1. cosmic\n        2. sun_coronal - default abundance\n        3. sun_coronal_ext\n        4. sun_hybrid\n        5. sun_hybrid_ext\n        6. sun_photospheric\n        7. mewe_cosmic\n        8. mewe_solar - default for mewe_kev\n\n    Returns\n    -------\n    out:\n        Array of 50 abundance levels for first 50 elements.\n\n    \"\"\"\n    # If kwargs not set, set defaults\n    if abundance_type is None:\n        abundance_type = \"sun_coronal\"\n    xray_abundance_file = manager.get(\"xray_abundances\")\n    # Read file\n    contents = read_abundance_genx(xray_abundance_file)\n    # Extract relevant abundance type\n    abundances = contents[abundance_type]\n\n    return abundances\n\n\ndef read_abundance_genx(filename):\n    # Read file.\n    contents = read_genx(filename)\n    # Combine data and keys from each entry in file.\n    output = OrderedDict()\n    for arr in contents[\"SAVEGEN0\"]:\n        output[arr[\"FILNAM\"]] = arr[\"ABUND\"]\n    # Add header data\n    output[\"header\"] = contents[\"HEADER\"]\n    output[\"header\"][\"CHIANTI VERSION\"] = float(contents[\"SAVEGEN1\"][:3])\n\n    return output\n\n\n@manager.require('chianti_lines_1_10',\n                 ['https://hesperia.gsfc.nasa.gov/ssw/packages/xray/dbase/chianti/chianti_lines_1_10_v71.sav'],\n                  '2046d818efec207a83e9c5cc6ba4a5fa8574bf8c2bd8a6bb9801e4b8a2a0c677')\ndef _read_linefile():\n    linefile = manager.get('chianti_lines_1_10')\n    # Read file\n    contents = scipy.io.readsav(linefile)\n    zindex = contents[\"zindex\"]\n    out = contents[\"out\"]\n\n    return contents\n\n\ndef _extract_line_intensities(lines_int_sorted):\n    line_ints = np.empty((lines_int_sorted.shape[0], lines_int_sorted[0].shape[0]), dtype=float)\n    for i in range(line_ints.shape[0]):\n        line_ints[i, :] = lines_int_sorted[i]\n    return line_ints\n\ndef _clean_array_dims(arr, dtype=None):\n    # Initialize a single array to hold contents of input arr.\n    result = np.empty(list(arr.shape) + list(arr[0].shape))\n    # Combine arrays in arr into single array.\n    for i in range(arr.shape[0]):\n        result[i] = arr[i]\n    # Remove redundant dimensions\n    result = np.squeeze(result)\n    # If result is now unsized, convert to scalar.\n    if result.shape == ():\n        result = result.item()\n        if dtype is not None:\n            dtype(result)\n    return result\n\n\ndef _clean_string_dims(arr):\n    result = [str(s, 'utf-8') for s in arr]\n    if len(result) == 1:\n        result = result[0]\n    return result\n\n\ndef _combine_strings(arr):\n    result = [\".\".join([str(ss, 'utf-8') for ss in s]) for s in arr]\n    if len(result) == 1:\n        result = result[0]\n    return result\n\ndef _clean_units(arr):\n    result = []\n    for a in arr:\n        unit = str(a, 'utf-8')\n        unit_components = unit.split()\n        for i, component in enumerate(unit_components):\n            # Remove plurals\n            if component in [\"photons\", \"Angstroms\"]:\n                component = component[:-1]\n            # Insert ** for indices.\n            component_minus_split = component.split(\"-\")\n            if len(component_minus_split) > 1:\n                \"**-\".join(component_minus_split)\n            component_plus_split = component.split(\"+\")\n            if len(component_plus_split) > 1:\n                \"**-\".join(component_plus_split)\n            unit_components[i] = component\n        result.append(\"*\".join(unit_components))\n    if len(result) == 1:\n        result = result[0]\n\n    return u.Unit(result)\n\n\ndef _clean_chianti_doc(arr):\n    chianti_doc = {}\n    chianti_doc[\"ion_file\"] = str(arr[0][0], 'utf-8')\n    chianti_doc[\"ion_ref\"] = \"{0}.{1}.{2}\".format(str(arr[\"ion_ref\"][0][0], 'utf-8'),\n                                                  str(arr[\"ion_ref\"][0][1], 'utf-8'),\n                                                  str(arr[\"ion_ref\"][0][2], 'utf-8'))\n    chianti_doc[\"version\"] = str(arr[0][2], 'utf-8')\n    return chianti_doc\n", "meta": {"hexsha": "2cd6844187f6a8cca1ae61b326fde40f469297f7", "size": 13280, "ext": "py", "lang": "Python", "max_stars_repo_path": "sunxspex/sunxspex/io.py", "max_stars_repo_name": "KriSun95/sunxspex_examples_kris", "max_stars_repo_head_hexsha": "068c9eed8af63c427a8578ee15863092b2e4bc93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-12T21:42:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-22T16:30:06.000Z", "max_issues_repo_path": "sunxspex/sunxspex/io.py", "max_issues_repo_name": "KriSun95/sunxspex_examples_kris", "max_issues_repo_head_hexsha": "068c9eed8af63c427a8578ee15863092b2e4bc93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sunxspex/sunxspex/io.py", "max_forks_repo_name": "KriSun95/sunxspex_examples_kris", "max_forks_repo_head_hexsha": "068c9eed8af63c427a8578ee15863092b2e4bc93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-22T16:36:41.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-22T16:36:41.000Z", "avg_line_length": 38.4927536232, "max_line_length": 114, "alphanum_fraction": 0.6573042169, "include": true, "reason": "import numpy,import scipy,import astropy,from astropy", "num_tokens": 3389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.18600595189802974}}
{"text": "#Author - Evan Leister\nimport eclipse_cells as ec\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass Injector(object):\n    def __init__(self, index, x, y, ratio, layer_id, end_days, mass_rate):\n        self.index = index\n        self.x = x\n        self.y = y\n        self.ratio = ratio\n        self.layer_id = layer_id\n        self.end_days = end_days # list of intervals in integer days\n        self.mass_rate = mass_rate # list of mass rate is given in Mt/yr\n        self.radius = 1.0\n        if len(mass_rate) != len(end_days):\n            print \"Mass inflow and interval ends must match\"\n            return 1\n    def write_injector(self, f):\n        print \"mass rate is\"\n        print self.mass_rate\n        f.write(', '.join([str(self.index), str(self.x), str(self.y),\\\n                str(self.ratio), str(self.layer_id),\\\n                str(self.radius), str(len(self.mass_rate))]))\n        f.write('\\n')\n        for i in range(len(self.mass_rate)):\n            print len(self.mass_rate), len(self.end_days)\n            f.write(', '.join([str(self.end_days[i]), \\\n                    str(self.mass_rate[i])]))\n            f.write('\\n')\n        return f\n\ndef write_injwells(injectors):\n    f = open(\"InjWells.txt\",\"w\")\n    print \"writing Injwells.txt\"\n    for inj in injectors:\n        inj.write_injector(f)\n    f.close()\n    return 0\n\ndef write_system(timestep_days, output_days, simtime_years, output_control, layers):\n    f = open(\"System.txt\", \"w\")\n    print \"writing System.txt\"\n    f.write(''.join([str(timestep_days),'\\n']))\n    f.write(''.join([str(output_days),'\\n']))\n    years = simtime_years\n    f.write(''.join([str(simtime_years),'\\n']))\n    f.write(''.join([output_control,'\\n']))\n    # mass balance output 'string' massbalance nomassbalance\n    f.write('massbalance \\n')\n    # number of layers in the model [int]\n    f.write(''.join([str(len(layers)),'\\n']))\n    # file names that contain the grid data\n    for s in layers:\n        f.write(s)\n    f.close()\n    return 0\n\nclass Layer(object):\n    def __init__(self, layer_name, l_type, l_id, l_co2_rho, l_bri_rho, l_co2_mu,\\\n            l_bri_mu, sc_res, sb_res, c_co2, c_bri, c_roc, cap_rp_id, \\\n            nx, ny, nz = 1, gradient = 10.,\\\n            homogeneous = False, permval = 2000., poroval = False):\n        \"\"\"\n        self.layer_name : Name of Text File\n        l_type : Layer Type\n        l_id : Layer ID\n        l_co2_rho : CO2 density\n        self.l_bri_rho : Brine Density\n        self.l_co2_mu : CO2 viscosity\n        self.l_bri_mu : brine viscosity\n        self.sc_res : CO2 residual saturation\n        self.sb_res : brine residual saturation\n        self.c_co2 : CO2 compressibility\n        self.c_bri : Brine Compressibility\n        self.c_roc : Rock Compressibility\n        self.cap_rp_id : Capillary - Rel/perm ID\n        self.gradient : Pressure gradient\n        \"\"\"\n        self.layer_name = layer_name\n        self.l_type = l_type\n        self.l_id = l_id\n        self.l_co2_rho = l_co2_rho\n        self.l_bri_rho = l_bri_rho\n        self.l_co2_mu = l_co2_mu\n        self.l_bri_mu = l_bri_mu\n        self.sc_res = sc_res\n        self.sb_res = sb_res\n        self.c_co2 = c_co2\n        self.c_bri = c_bri\n        self.c_roc = c_roc\n        self.cap_rp_id = cap_rp_id\n        # list of GridCell objects\n        self.grid_cells = []\n        self.gradient = gradient #[MPa/km]\n        self.nx = nx\n        self.ny = ny\n        self.nz = nz\n        self.homogeneous = homogeneous\n        self.permval = permval\n        self.poroval = poroval\n\n\n    def fill_uniform_grid(self, dx, dy, dz, center_depth, phi, k):\n        for j in range(self.ny):\n            for i in range(self.nx):\n                x = (dx/2. + dx * i)\n                y = (dy/2. + dy * j)\n                top_b = -center_depth + dz/2.\n                bottom_b = -center_depth - dz/2.\n\n                if i == (self.nx - 1):\n                    east_bc = 3\n                else:\n                    east_bc = 1\n\n                if j == (self.ny - 1):\n                    north_bc = 3\n                else:\n                    north_bc = 1\n\n                if i == 0:\n                    west_bc = 3\n                else: \n                    west_bc = 1\n                    \n                if j == 0:\n                    south_bc = 3\n                else:\n                    south_bc = 1\n\n                pressure = -self.gradient * bottom_b * 1000\n                gc = GridCell(top_b, bottom_b, x, y, dx, dy, phi, k,\\\n                        west_bc, east_bc, south_bc, north_bc, pressure)\n                self.grid_cells.append(gc)\n            \n\n        return 0\n\n    def plot_perm_data(self, e_cells):\n        cell_ind = np.zeros(len(e_cells))\n        anis = np.zeros(len(e_cells))\n        depth = np.zeros(len(e_cells))\n        perm = np.zeros(len(e_cells))\n        poro = np.zeros(len(e_cells))\n        for i in range(len(e_cells)):\n            cell_ind[i] = i\n            perm[i] = e_cells[i].getXPermeability()\n            anis[i] = e_cells[i].getZPermeability() / \\\n                        e_cells[i].getXPermeability()\n            depth[i] = e_cells[i].getTopZ()\n            poro[i] = e_cells[i].getPorosity()\n        print \"plotting anisotropy ratio\"\n        fig1 = plt.figure()\n        ax1 = fig1.add_subplot(111)\n        a = ax1.plot(cell_ind, anis)\n        ax1.set_xlabel('cell_index []')\n        ax1.set_ylabel('anisotropy kz/kx')\n        plt.savefig('ec_anis_cells.png')\n        plt.close()\n        print \"plotting permeabilityvsdepth\"\n        fig2 = plt.figure()\n        ax2 = fig2.add_subplot(111)\n        b = ax2.scatter(depth, perm)\n        ax2.set_xlabel('depth [m]')\n        ax2.set_ylabel('permeability [md]')\n        plt.savefig('ec_perm_depth.png')\n        plt.close()\n        print \"plotting porosity vsdepth\"\n        fig3 = plt.figure()\n        ax3 = fig3.add_subplot(111)\n        b = ax3.scatter(depth, poro)\n        ax3.set_xlabel('depth [m]')\n        ax3.set_ylabel('porosity []')\n        plt.savefig('ec_poro_depth.png')\n        plt.close()\n\n        return 0\n\n    def fill_nonuniform_grid(self, e_cells):\n        print \"Filling nonuniform grid\" \n        count = 0\n        k = 0\n        columnz = []\n        columnk = []\n        columnphi = []\n        check_col = self.nz\n        check_plane = self.nx*self.ny\n        for j in range(self.ny-1,-1,-1):\n            for i in range(0,self.nx):\n                for k in range(0,self.nz):\n                    ind = (i + self.nx *j) + check_plane*k\n                    if i == 32 and j == 77:\n                        print k, e_cells[ind].getZPermeability()\n                    if e_cells[ind].getXPermeability() > 1:\n                        columnz.append(e_cells[ind].getTopZ())\n                        columnk.append(e_cells[ind].getXPermeability())\n                        columnphi.append(e_cells[ind].getPorosity())\n                # spits out the averages after the column index is filled.     \n                kmean, kvar = stats(columnk)\n                if self.homogeneous == True:\n                    k_write = self.permval\n                else:\n                    k_write = kmean\n                if self.poroval == False:\n                    phimean , phivar = stats(columnphi)\n                else:\n                    phimean = self.poroval\n\n                top_b = -columnz[0]\n                bottom_b = -columnz[-1]\n\n                x = e_cells[ i + self.nx * j].getCenterX()\n                y = e_cells[ i + self.nx * j].getCenterY()\n\n                # get correct dx and dy\n                if i != (self.nx-1):\n                    x_1 = e_cells[i+1 + self.nx*j].getCenterX()\n                    x_0 = e_cells[ i + self.nx * j].getCenterX()\n                    dx = (x_1 - x_0)\n                else:\n                    x_1 = e_cells[i + self.nx*j].getCenterX()\n                    x_0 = e_cells[ i-1 + self.nx * j].getCenterX()\n                    dx = (x_1 - x_0)\n                if j != 0:\n                    y_1 = e_cells[i + self.nx *(j-1)].getCenterY()\n                    y_0 = e_cells[i + self.nx * j].getCenterY()\n                    dy = y_1 - y_0\n                else: \n                    y_1 = e_cells[i + self.nx *j].getCenterY()\n                    y_0 = e_cells[i + self.nx *(j+1)].getCenterY()\n                    dy = y_1 - y_0\n\n                #boundary condition key [integers]\n                # 1 = internal\n                # 3 = constant pressure\n                # 4 = no flow\n                if i == (self.nx - 1):\n                    east_bc = 3\n                else:\n                    east_bc = 1\n\n                if j == 0:\n                    north_bc = 3\n                else:\n                    north_bc = 1\n\n                if i == 0:\n                    west_bc = 3\n                else: \n                    west_bc = 1\n                    \n                if j == (self.ny - 1):\n                    south_bc = 3\n                else:\n                    south_bc = 1\n\n                pressure = -self.gradient * bottom_b * 1000\n                gc = GridCell(top_b, bottom_b, x, y, dx, dy, phimean, k_write,\\\n                        west_bc, east_bc, south_bc, north_bc, pressure)\n                self.grid_cells.append(gc)\n\n                # increment loops\n                count += 1\n                columnz = []\n                columnk = []\n                columnphi = []\n                k = 0\n        return 0\n\n    def write_layer(self):\n        print \"writing layer \" + self.layer_name\n        f = open(\"\".join([self.layer_name,'.txt']),\"w\")\n        g = open(\"thickness.txt\",\"w\")\n        # layer type\n        f.write(''.join([str(self.l_type) + '\\n']))\n        # layer id\n        f.write(''.join([str(self.l_id) + '\\n']))\n        # fluid parameters\n        f.write(''.join([str(self.l_co2_rho),'\\n']))\n        f.write(''.join([str(self.l_bri_rho),'\\n']))\n        f.write(''.join([str(self.l_co2_mu),'\\n']))\n        f.write(''.join([str(self.l_bri_mu),'\\n']))\n        f.write(''.join([str(self.sc_res),'\\n']))\n        f.write(''.join([str(self.sb_res),'\\n']))\n        f.write(''.join([str(self.c_co2),'\\n']))\n        f.write(''.join([str(self.c_bri),'\\n']))\n        f.write(''.join([str(self.c_roc),'\\n']))\n        if self.cap_rp_id == 0:\n            f.write(''.join([str(self.cap_rp_id),'\\n']))\n        elif self.cap_rp_id == 1:\n            lamb = 3.\n            p_entry = 3000000.\n            f.write(''.join([str(self.cap_rp_id), ', ',\\\n                    str(lamb), ', ', \\\n                    str(p_entry), '\\n']))\n            self.plot_cap_rp_bc(lamb, p_entry)\n        # number of cells\n        f.write(''.join([str(self.nx * self.ny), '\\n']))\n        for cel in self.grid_cells:\n            g.write(''.join([str((cel.top_b - cel.bottom_b)),', ']))\n            cel.write_cell(f)\n        f.close()\n        return 0\n    def bc_cap(self, pentry, lamb):\n        return pcap\n    def plot_cap_rp_bc(self, lamb, p_entry):\n        sb = np.linspace(self.sb_res,1.)\n        pc = np.zeros(len(sb))\n        krb = np.zeros(len(sb))\n        krc = np.zeros(len(sb))\n        for i in range(len(sb)):\n            seff = (sb[i] - self.sb_res) / (1 - self.sb_res)\n            pc[i] = p_entry * pow(seff, -1/lamb)\n            krb[i] = pow(seff, (2 + 3 * lamb)/lamb)\n            krc[i] = (1 - seff)**2 * (1 - pow(seff, (2 + lamb) / lamb))\n        fig1 = plt.figure()\n        ax1 = fig1.add_subplot(111)\n        ax1.plot(sb, pc)\n        ax1.set_xlabel('sb []')\n        ax1.set_ylabel('pcap [Pa]')\n        plt.savefig('pcap.png')\n        plt.clf()\n        fig2 = plt.figure()\n        ax2 = fig2.add_subplot(111)\n        ax2.plot(sb, krb, label = 'krb')\n        ax2.plot(sb, krc, label = 'krc')\n        ax2.legend(loc=1)\n        ax2.set_xlabel('sb')\n        plt.savefig('relperm.png')\n        return 0\n\nclass GridCell(object):\n    def __init__(self, top_b, bottom_b, x, y, dx, dy, phi, k,\\\n            west_bc, east_bc, south_bc, north_bc, pressure): \n        self.top_b = top_b\n        self.bottom_b = bottom_b\n        self.x = x\n        self.y = y\n        self.dx = dx\n        self.dy = dy\n        self.phi = phi\n        self.k = k\n        self.west_bc = west_bc\n        self.east_bc = east_bc\n        self.south_bc = south_bc\n        self.north_bc = north_bc\n        self.pressure = pressure\n\n    def write_cell(self, f):\n        f.write(''.join([str(self.x),', ']))\n        f.write(''.join([str(self.y),', ']))\n        f.write(''.join([str(self.dx),', ']))\n        f.write(''.join([str(self.dy),', ']))\n        # porosity\n        f.write(''.join(['%.4f' % self.phi ,', ']))\n        # NOTE: Enters permeability for all dimensions since the formation is isotropic\n        # in the planar directions and the z permeability is not used in VESA.\n        xperm = self.k\n        yperm = self.k \n        zperm = self.k\n        f.write(''.join(['%.0f' % xperm, ', ' ,'%.0f' % yperm, ', ',\\\n                '%.0f' % zperm, ', ']))\n        f.write(''.join(['%.4f'  % self.bottom_b, ', ']))\n        f.write(''.join(['%.4f' % self.top_b, ', ']))\n        # initial CO2 saturation\n        f.write('0.0, ')\n        # past CO2 saturation\n        f.write('0.0, ')\n        #initial pressure at bottom of formation [Pa]\n        f.write(''.join(['%.0f' % self.pressure, ', ']))\n        f.write(''.join([str(self.east_bc), ', ']))\n        f.write(''.join([str(self.north_bc), ', ']))\n        f.write(''.join([str(self.west_bc), ', ']))\n        f.write(''.join([str(self.south_bc), ', ']))\n        f.write('\\n')\n        return f\n\ndef stats(data):\n    sum_s = 0.0\n    for value in data:\n        sum_s += value\n    mean = sum_s/len(data)\n    sum_s = 0.0\n    for value in data:\n        sum_s += (value - mean)**2\n    variance = sum_s/(len(data)-1)\n    return(mean,variance)\n", "meta": {"hexsha": "884d12a44a44896b9ad96a99f15f751e66013085", "size": 13731, "ext": "py", "lang": "Python", "max_stars_repo_path": "vesa/vesa_v02_13/vesa_writing_functions.py", "max_stars_repo_name": "evanl/vesa_tough_comparison", "max_stars_repo_head_hexsha": "b2990b84bca567d4244e774c918bbdd7c72fa4c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vesa/vesa_v02_13/vesa_writing_functions.py", "max_issues_repo_name": "evanl/vesa_tough_comparison", "max_issues_repo_head_hexsha": "b2990b84bca567d4244e774c918bbdd7c72fa4c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vesa/vesa_v02_13/vesa_writing_functions.py", "max_forks_repo_name": "evanl/vesa_tough_comparison", "max_forks_repo_head_hexsha": "b2990b84bca567d4244e774c918bbdd7c72fa4c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-10T09:51:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-10T09:51:55.000Z", "avg_line_length": 35.2982005141, "max_line_length": 87, "alphanum_fraction": 0.4885296045, "include": true, "reason": "import numpy", "num_tokens": 3676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.18600595041717}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n:mod:`milboost`\n==================\n\n.. module:: milboost\n    :platform: Unix, Windows\n    :synopsis:\n\n.. moduleauthor:: hbldh <henrik.blidh@nedomkull.com>\n\nCreated on 2015-11-06, 08:48\n\n\"\"\"\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom __future__ import absolute_import\n\nimport warnings\n\nimport numpy as np\nfrom sklearn.ensemble.weight_boosting import ClassifierMixin, BaseWeightBoosting\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.utils.validation import check_is_fitted\nfrom scipy.optimize import fminbound\n\nfrom skboost.milboost.softmax import SoftmaxFunction\n\n__all__ = ['MILBoostClassifier', ]\n\n\nclass MILBoostClassifier(ClassifierMixin, BaseWeightBoosting):\n\n    def __init__(self,\n                 base_estimator=DecisionTreeClassifier(max_depth=10),\n                 softmax=None,\n                 n_estimators=50,\n                 learning_rate=1.0,\n                 random_state=None,\n                 verbose=False):\n\n        super(MILBoostClassifier, self).__init__(\n            base_estimator=base_estimator,\n            n_estimators=n_estimators,\n            learning_rate=learning_rate,\n            random_state=random_state)\n\n        if not isinstance(softmax, SoftmaxFunction):\n            raise TypeError(\"Softmax input must be an object of class `SoftmaxFunction`\")\n        self.softmax_fcn = softmax\n        self._verbose = verbose\n\n        self._bag_labels = None\n        self._inferred_y = None\n        self._bag_partitioning = None\n\n    def __str__(self):\n        return \"{0}, with {1} {2} classifiers\".format(\n            self.__class__.__name__, len(self.estimators_), self.estimators_[0])\n\n    def fit(self, X, y, sample_weight=None):\n        \"\"\"Build a boosted classifier from the training set (X, y).\n\n        Parameters\n        ----------\n        X : {array-like, sparse matrix} of shape = [n_samples, n_features]\n            The training input samples. Sparse matrix can be CSC, CSR, COO,\n            DOK, or LIL. DOK and LIL are converted to CSR.\n\n        y : array-like of shape = [n_samples]\n            The target values (class labels).\n\n        sample_weight : array-like of shape = [n_samples], optional\n            Sample weights. If None, the sample weights are initialized to\n            ``1 / n_samples``.\n\n        Returns\n        -------\n        self : object\n            Returns self.\n        \"\"\"\n\n        # Pre-compute bag labels and inferred instance labels from y.\n        unique_bag_ids = np.unique(y)\n        self._bag_labels = np.zeros((max(np.abs(unique_bag_ids)) + 1, ), 'int')\n        self._bag_labels[np.abs(unique_bag_ids)] = np.sign(unique_bag_ids)\n        self._bag_labels = self._bag_labels[1:]\n        self._inferred_y = np.sign(y)\n        self._bag_partitioning = np.cumsum(np.bincount(np.abs(y))[1:])\n\n        # Fit\n        out = super(MILBoostClassifier, self).fit(X, y, sample_weight)\n\n        # Clean away stored labels.\n        self._bag_labels = None\n        self._inferred_y = None\n        self._bag_partitioning = None\n\n        return out\n\n    def _boost(self, iboost, X, y, sample_weight, random_state):\n\n        if iboost > 0:\n            dv_pre = self.decision_function(X)\n            instance_probabilites = self._estimate_instance_probabilities(dv_pre)\n            bag_probabilites = self._estimate_bag_probabilites(instance_probabilites)\n            sample_weight = self._calculate_new_weights(instance_probabilites, bag_probabilites)\n        else:\n            dv_pre = np.zeros(((X.shape[0]),), 'float')\n\n        estimator = self._make_estimator()\n        try:\n            estimator.set_params(random_state=self.random_state)\n        except ValueError:\n            pass\n\n        _weights = np.abs(sample_weight)\n        estimator.fit(X, self._inferred_y, sample_weight=_weights)\n        y_predict = estimator.predict(X)\n\n        # Instances incorrectly classified\n        incorrect = y_predict != self._inferred_y\n\n        # Error fraction\n        estimator_error = np.mean(\n            np.average(incorrect, weights=_weights, axis=0))\n\n        if iboost == 0:\n            self.classes_ = getattr(estimator, 'classes_', None)\n            self.n_classes_ = len(self.classes_)\n\n        # Estimate alpha, the estimator weight.\n        estimator_weight, nll = self._find_estimator_weight(y, dv_pre, y_predict)\n        if self._verbose:\n            print(\"[{0}] - err={1:.4f}, w={2:.4f}, -L={3:.4f}\".format(iboost, estimator_error, estimator_weight, nll))\n\n        if estimator_weight < 1e-5:\n            _weights = None\n\n        return _weights, estimator_weight, estimator_error\n\n    def _negative_log_likelihood(self, bag_probabilities):\n        positive_bags_log_prob = np.log(bag_probabilities[self._bag_labels > 0])\n        positive_bags_log_prob[np.isinf(positive_bags_log_prob)] = 0.0\n        negative_bags_log_prob = np.log(1 - bag_probabilities[self._bag_labels < 0])\n        negative_bags_log_prob[np.isinf(negative_bags_log_prob)] = 0.0\n\n        return -(np.sum(positive_bags_log_prob) + np.sum(negative_bags_log_prob))\n\n    def _find_estimator_weight(self, y, dv_pre, y_pred):\n        \"\"\"Make line search to determine estimator weights.\"\"\"\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n\n            def optimization_function(alpha):\n                p_ij = self._estimate_instance_probabilities(dv_pre + alpha * y_pred)\n                p_i = self._estimate_bag_probabilites(p_ij)\n                return self._negative_log_likelihood(p_i)\n\n            # TODO: Add option to choose optimization method.\n\n            alpha, fval, err, n_func = fminbound(optimization_function, 0.0, 5.0, full_output=True, disp=1)\n            if self.learning_rate < 1.0:\n                alpha *= self.learning_rate\n        return alpha, fval\n\n    def _estimate_instance_probabilities(self, dv):\n        return 1.0 / (1 + np.exp(-(2 * dv)))\n\n    def _estimate_bag_probabilites(self, instance_probabilites):\n        bags = self._bag_split(instance_probabilites)\n        bag_probabilities = np.array([self.softmax_fcn.f(x) for x in bags])\n        return bag_probabilities\n\n    def _calculate_new_weights(self, instance_probabilites, bag_probabilities):\n        weights = []\n        for p_ij, p_i, Y_i in zip(self._bag_split(instance_probabilites),\n                                  bag_probabilities,\n                                  self._bag_labels):\n            if Y_i > 0:\n                if p_i == 0.0:\n                    p_i = np.finfo(float).resolution\n                term_1 = (2 * p_ij * (1 - p_ij)) / p_i\n            else:\n                if p_i == 1.0:\n                    p_i = 1 - np.finfo(float).resolution\n                term_1 = -((2 * p_ij * (1 - p_ij)) / (1 - p_i))\n            weights += (term_1 * self.softmax_fcn.d_dt(p_ij)).tolist()\n\n        return np.array(weights) / np.sum(np.abs(weights))\n\n    def _bag_split(self, x):\n        return np.split(x, self._bag_partitioning)[:-1]\n\n    def decision_function(self, X):\n        \"\"\"Compute the decision function of ``X``.\n\n        Parameters\n        ----------\n        X : {array-like, sparse matrix} of shape = [n_samples, n_features]\n            The training input samples. Sparse matrix can be CSC, CSR, COO,\n            DOK, or LIL. DOK and LIL are converted to CSR.\n\n        Returns\n        -------\n        score : array, shape = [n_samples, k]\n            The decision function of the input samples. The order of\n            outputs is the same of that of the `classes_` attribute.\n            Binary classification is a special cases with ``k == 1``,\n            otherwise ``k==n_classes``. For binary classification,\n            values closer to -1 or 1 mean more like the first or second\n            class in ``classes_``, respectively.\n        \"\"\"\n        check_is_fitted(self, \"n_classes_\")\n        X = self._validate_X_predict(X)\n\n        classes = self.classes_[:, np.newaxis]\n        pred = sum((estimator.predict(X) == classes).T * w\n                   for estimator, w in zip(self.estimators_,\n                                           self.estimator_weights_))\n        pred[:, 0] *= -1\n        return pred.sum(axis=1)\n\n    def staged_decision_function(self, X):\n        \"\"\"Compute decision function of ``X`` for each boosting iteration.\n\n        This method allows monitoring (i.e. determine error on testing set)\n        after each boosting iteration.\n\n        Parameters\n        ----------\n        X : {array-like, sparse matrix} of shape = [n_samples, n_features]\n            The training input samples. Sparse matrix can be CSC, CSR, COO,\n            DOK, or LIL. DOK and LIL are converted to CSR.\n\n        Returns\n        -------\n        score : generator of array, shape = [n_samples, k]\n            The decision function of the input samples. The order of\n            outputs is the same of that of the `classes_` attribute.\n            Binary classification is a special cases with ``k == 1``,\n            otherwise ``k==n_classes``. For binary classification,\n            values closer to -1 or 1 mean more like the first or second\n            class in ``classes_``, respectively.\n        \"\"\"\n        check_is_fitted(self, \"n_classes_\")\n        X = self._validate_X_predict(X)\n\n        classes = self.classes_[:, np.newaxis]\n        pred = None\n\n        for weight, estimator in zip(self.estimator_weights_,\n                                     self.estimators_):\n\n            current_pred = estimator.predict(X)\n            current_pred = (current_pred == classes).T * weight\n\n            if pred is None:\n                pred = current_pred\n            else:\n                pred += current_pred\n\n            tmp_pred = np.copy(pred)\n            tmp_pred[:, 0] *= -1\n            yield (tmp_pred).sum(axis=1)\n\n    def predict(self, X):\n        \"\"\"Predict classes for X.\n\n        The predicted class of an input sample is computed as the weighted mean\n        prediction of the classifiers in the ensemble.\n\n        Parameters\n        ----------\n        X : {array-like, sparse matrix} of shape = [n_samples, n_features]\n            The training input samples. Sparse matrix can be CSC, CSR, COO,\n            DOK, or LIL. DOK and LIL are converted to CSR.\n\n        Returns\n        -------\n        y : array of shape = [n_samples]\n            The predicted classes.\n        \"\"\"\n        pred = self.decision_function(X)\n\n        return self.classes_.take(pred > 0, axis=0)\n\n    def staged_predict(self, X):\n        \"\"\"Return staged predictions for X.\n\n        The predicted class of an input sample is computed as the weighted mean\n        prediction of the classifiers in the ensemble.\n\n        This generator method yields the ensemble prediction after each\n        iteration of boosting and therefore allows monitoring, such as to\n        determine the prediction on a test set after each boost.\n\n        Parameters\n        ----------\n        X : array-like of shape = [n_samples, n_features]\n            The input samples.\n\n        Returns\n        -------\n        y : generator of array, shape = [n_samples]\n            The predicted classes.\n        \"\"\"\n        classes = self.classes_\n\n        for pred in self.staged_decision_function(X):\n            yield np.array(classes.take(pred > 0, axis=0))\n\n    def predict_proba(self, X):\n        \"\"\"Predict class probabilities for X.\n\n        The predicted class probabilities of an input sample is computed as\n        the weighted mean predicted class probabilities of the classifiers\n        in the ensemble.\n\n        Parameters\n        ----------\n        X : {array-like, sparse matrix} of shape = [n_samples, n_features]\n            The training input samples. Sparse matrix can be CSC, CSR, COO,\n            DOK, or LIL. DOK and LIL are converted to CSR.\n\n        Returns\n        -------\n        p : array of shape = [n_samples]\n            The class probabilities of the input samples. The order of\n            outputs is the same of that of the `classes_` attribute.\n        \"\"\"\n        check_is_fitted(self, \"n_classes_\")\n\n        n_classes = self.n_classes_\n        X = self._validate_X_predict(X)\n\n        proba = sum(estimator.predict_proba(X) * w\n                    for estimator, w in zip(self.estimators_,\n                                            self.estimator_weights_))\n\n        proba /= self.estimator_weights_.sum()\n        proba = np.exp((1. / (n_classes - 1)) * proba)\n        normalizer = proba.sum(axis=1)[:, np.newaxis]\n        normalizer[normalizer == 0.0] = 1.0\n        proba /= normalizer\n\n        return proba\n\n    def staged_predict_proba(self, X):\n        \"\"\"Predict class probabilities for X.\n\n        The predicted class probabilities of an input sample is computed as\n        the weighted mean predicted class probabilities of the classifiers\n        in the ensemble.\n\n        This generator method yields the ensemble predicted class probabilities\n        after each iteration of boosting and therefore allows monitoring, such\n        as to determine the predicted class probabilities on a test set after\n        each boost.\n\n        Parameters\n        ----------\n        X : {array-like, sparse matrix} of shape = [n_samples, n_features]\n            The training input samples. Sparse matrix can be CSC, CSR, COO,\n            DOK, or LIL. DOK and LIL are converted to CSR.\n\n        Returns\n        -------\n        p : generator of array, shape = [n_samples]\n            The class probabilities of the input samples. The order of\n            outputs is the same of that of the `classes_` attribute.\n        \"\"\"\n        X = self._validate_X_predict(X)\n\n        n_classes = self.n_classes_\n        proba = None\n        norm = 0.\n\n        for weight, estimator in zip(self.estimator_weights_,\n                                     self.estimators_):\n            norm += weight\n\n            current_proba = estimator.predict_proba(X) * weight\n\n            if proba is None:\n                proba = current_proba\n            else:\n                proba += current_proba\n\n            real_proba = np.exp((1. / (n_classes - 1)) * (proba / norm))\n            normalizer = real_proba.sum(axis=1)[:, np.newaxis]\n            normalizer[normalizer == 0.0] = 1.0\n            real_proba /= normalizer\n\n            yield real_proba\n\n    def predict_log_proba(self, X):\n        \"\"\"Predict class log-probabilities for X.\n\n        The predicted class log-probabilities of an input sample is computed as\n        the weighted mean predicted class log-probabilities of the classifiers\n        in the ensemble.\n\n        Parameters\n        ----------\n        X : {array-like, sparse matrix} of shape = [n_samples, n_features]\n            The training input samples. Sparse matrix can be CSC, CSR, COO,\n            DOK, or LIL. DOK and LIL are converted to CSR.\n\n        Returns\n        -------\n        p : array of shape = [n_samples]\n            The class probabilities of the input samples. The order of\n            outputs is the same of that of the `classes_` attribute.\n        \"\"\"\n        return np.log(self.predict_proba(X))\n", "meta": {"hexsha": "70ef852252d2defb3b3d29dbba5d5f0fd741056b", "size": 15123, "ext": "py", "lang": "Python", "max_stars_repo_path": "skboost/milboost/classifier.py", "max_stars_repo_name": "TMRert/skboost", "max_stars_repo_head_hexsha": "f5ba77cd75beca177b663e7994ae7c3616e278fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2016-05-09T09:17:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-03T02:55:33.000Z", "max_issues_repo_path": "skboost/milboost/classifier.py", "max_issues_repo_name": "TMRert/skboost", "max_issues_repo_head_hexsha": "f5ba77cd75beca177b663e7994ae7c3616e278fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-11-30T05:16:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-25T05:22:37.000Z", "max_forks_repo_path": "skboost/milboost/classifier.py", "max_forks_repo_name": "TMRert/skboost", "max_forks_repo_head_hexsha": "f5ba77cd75beca177b663e7994ae7c3616e278fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2017-06-27T02:37:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-16T15:24:13.000Z", "avg_line_length": 36.0071428571, "max_line_length": 118, "alphanum_fraction": 0.6023275805, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.18600594315647098}}
{"text": "#!/usr/bin/env python\n\n#everything is needed to perform the script and maybe something else\nfrom numpy import *\nfrom scipy import *\nfrom scipy import integrate\nfrom scipy.interpolate import interp1d\nimport pyfits\nimport os\nimport sys\nimport string \nimport shutil\nimport math\nimport glob\nfrom time import strftime, sleep\nimport time\nfrom pylab import *\nfrom scipy.optimize import curve_fit\nimport s3 #import metadata \nfrom s3.utilities import *  #import definitions\n# pre-set plot parameters, resolution untouched since it is not needed (default=80 dpi) \nfrom matplotlib.font_manager import FontProperties\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 11, 8\nrcParams['figure.subplot.top'] = 0.95\nrcParams['figure.subplot.right'] = 0.90\nrcParams['figure.subplot.left'] = 0.11\n###################################################\npypath = os.path.expandvars('$HOME')           # it copies login.cl if it is not in the same dir\nif not os.path.isfile('login.cl'):\n    shutil.copyfile(pypath+'/iraf/login.cl','login.cl')\n###################################################\n\n################### for the help ##################\nfrom optparse import OptionParser\n\ndescription = \" Synthetic magnitudes from flux calibrated spectra \"\nusage = \"%prog \"\nif __name__ == \"__main__\":\n    parser = OptionParser(usage=usage, description=description, version=\"%prog \" + str(s3.__version__))\n    parser.add_option(\"-v\", \"--verbose\",dest=\"verbose\",\\\n                  action=\"store_true\",default=False,\n                  help='Print tasks description')\n    parser.add_option(\"-s\", \"--sleep\",dest=\"sleepc\", action=\"store\", type=\"float\", default=None, \n                  help='Change the sleep time between cycles. Default is 1s (good for 4GB of RAM or greater), the lower your RAM, the higher it should be.')\n    option,args = parser.parse_args()\n\n###### moved here because OptionParser --version conflicts with pyraf version########\n#what we need from iraf\nfrom pyraf import iraf\n\n########### option to change the python sleep function between cycles #########\nif option.sleepc == None:\n    _sleepc = 1\nelse:\n    _sleepc = option.sleepc\n################ internal description #############\n\nh=\"######################################################################\\n\"+\\\n  \"###############  Synthetic  Magnitudes from Spectra  #################\\n\"+\\\n  \"###################             S.M.S.         #######################\\n\"+\\\n  \"##########         C. Inserra  v1.1.0  29/10/2015         ############\\n\"+\\\n  \"######################################################################\\n\"+\\\n  \" PLEASE READ CAREFULLY                            \\n\"+ \\\n  \" BE SURE that the spectra are flux calibrated  \\n\"+ \\\n  \" If you use this code and find it useful, please give a thought \\n\"+ \\\n  \" to cite it. \\n\"+ \\\n  \" The reference is Inserra et al. 2015, ApJ submitted \\n\"+\\\n  \"######################################################################\\n\"\nprint h \n####################################################\n\n#the path where the metatabs dat are\nfilterdir=s3.__path__[0]+'/metadata/' # To set the directory where are the synphot tabs created\n\n\n# cleaning process\nos.system('rm -rf sn.txt')\nos.system('rm -rf sn.fits')\nos.system('rm -rf sn_xbbody.txt')\nos.system('rm -rf bbody_sn_fit.fits')\nos.system('rm -rf bbody_sn_fit.dat')\nos.system('rm -rf bsn_combo.fits')\nos.system('rm -rf bsn_combo.txt')\n\n#######################################################\n# Variable definitions\n#######################################################\n\nquestion = raw_input('Do you have a list of spectra ? ([yes]/no) ')\nif not question:\n    question = 'yes'\n\nif question == 'yes' or question == 'y' or question == 'Y' or question == 'Yes' or question == 'YES':\n\tfiles = raw_input('List ? [e.g. list, list.txt, list.dat] ')\n\tlcf = open(files,'r')  \n\triga = lcf.readlines()             \n\tlcf.close()\n\tsnlist = []\n\tfor line in riga:\n\t\tp = line.split()\n\t\tsnlist.append(p[0])\nelse:\n\tfiles = raw_input('List the spectra to use (space separated list): ')\n\tsnlist = string.split(files)\n\nprint ''\nquestionfilobs = raw_input('Do you have a list of filters ? ([yes]/no) ')\nif not questionfilobs:\n    questionfilobs = 'yes'\n\nif questionfilobs == 'yes' or questionfilobs == 'y' or questionfilobs == 'Y' or questionfilobs == 'Yes' or questionfilobs == 'YES':\n\tfiles = raw_input('List ? [e.g. list, list.txt, list.dat] ')\n\tlcf = open(files,'r')  \n\triga = lcf.readlines()            \n\tlcf.close()\n\tfobs = []\n\tfor line in riga:\n\t\tp = line.split()\n\t\tfobs.append(p[0])\nelse:\n\tfolist = raw_input('List the filters you want to use (space separated list) or the observed filter that will be used for all the spectra: ')\n\tfolist_1 = string.split(folist)\n\tif len(folist_1) != len(snlist):\n\t\tif len(folist_1) == 1:\n\t\t\tfobs = folist_1 * len(snlist)\n\telse:\n\t\tfobs = folist_1\n\nlength = shape(snlist)[0]\nmag = array(zeros(length))\nmag_e = array(zeros(length))\nmethod = [None] * len(snlist)\nbtemp = [None] * len(snlist)\nanguncov = [None] * len(snlist)\nuncovside = [None] * len(snlist)\n\n\n##########################\n### Creating a txt file\n#########################\nTnow = int(strftime(\"%H%M%S\"))\nTnowd = int(strftime(\"%d%m%Y\"))\nkcf = \"Magnitudes_%.0i_%.0i.txt\" % (Tnowd,Tnow)\nfilekc = open(kcf,\"w\")\nfilekc.write(\"# Synthetic magnitudesfrom spectra \\n\")\nfilekc.write(\"# File\\tFilter\\tMagnitude\\t errore\\t SMS mode\\t Blackbody Temperature\\t Angstroms uncovered in the wavelength region\\n\\n\")\n\nnow = time.time() \nii = 0\nwhile ii != len(snlist):\n\t_snname = snlist[ii]\n\t#### it recognizes automatically the extension of your file and convert to fits\n\tfileName, fileExtension = os.path.splitext(_snname)\n\tif fileExtension == '.txt' or fileExtension == '.dat' or fileExtension == '.asci' or fileExtension == '.ascii':\n\t\tiraf.rspec(_snname,fileName+'.fits',flux='no',dtype='interp')\n\t\tsnname = fileName+'.fits'\n\telse:\n\t\tsnname = _snname\n\n\tfilter1 = fobs[ii]\n\tsnum = 1+ii\n\tprint ''\n\tprint '\\033[1mSpectrum number\\033[0m ', 1+ii\n\tprint 'Spectrum = ', snname\n\tsn = snname\n\n\t############################# Safety loop to check again if you have everything removed and avoid errors in the programme ###################\n\tfiletoremove = ['sn.txt','sn.fits','sn_xbbody.txt','bsn_combo.fits','bsn_combo.txt','bbody_sn_fit.dat','bbody_sn_fit.fits']\n\tjj = 0\n\twhile jj != len(filetoremove):\n\t\tif os.path.exists(filetoremove[jj]):\n\t\t\tprint ''\n\t\t\tprint \"######################################################################\"\n\t\t\tprint \"Sorry, I am going too fast for your computer RAM, I need to rest for a bit...\"\n\t\t\tprint \"######################################################################\"\n\t\t\tprint ''\n\t\t\tfor i in xrange(5,0,-1):\n\t\t\t\ttime.sleep(1)\n    \t\t\tsys.stdout.write(str(i)+' ')\n    \t\t\tsys.stdout.flush()\n\t\t\tif os.path.exists(filetoremove[jj]):\n\t\t\t\tprint ''\n\t\t\t\tprint \"######################################################################\"\n\t\t\t\tprint \"Ooops, that is kind of embarassing, apparently there is this file \"+filetoremove[jj]+\" that is delaying my job. May I ask you to assist me and remove it?\"\n\t\t\t\tfor i in xrange(10,0,-1):\n\t\t\t\t\ttime.sleep(1)\n    \t\t\t\tsys.stdout.write(str(i)+' ')\n    \t\t\t\tsys.stdout.flush()\n\n\t\t\t\tprint \"######################################################################\"\n\t\t\t\tprint ''\n\t\tjj = jj + 1\n\t#########################################################################################################\n\n\t#######################################################\n\t# Filter1 and its definitions\n\t#######################################################\n\tlcf = open(filterdir+filter1+'.txt','r')      # defintion of the file\n\triga = lcf.readlines()             # list of lines\n\triga1 = riga[4:len(riga)]  #list of lines where the wave and transmission are stored\n\tlcf.close()\n\tzp_ef = float(riga[0]) #zero point in energy flux (erg/cm^2/s)\n\tzp_ef_err = zp_ef * 1.0075\n\tfilter_ew = riga[1] #equivalent width of the filter\n\tpeak_wave = float(riga[2]) #peak wavelength of the filter\n\tsystem = riga[3] # system used: vega or ab\n\twavefilter, transmission= [], []\n\tfor line in riga1:\n\t    p = line.split()\n\t    wavefilter.append(float(p[0]))\n\t    transmission.append(float(p[1]))\n\t\n\twavefilterv = array(wavefilter)\n\ttransmissionv = array(transmission)\n\tfil_obs_min= min(wavefilterv)\n\tfil_obs_max= int(max(wavefilterv)) #integer is needed for a sharper cut-off\n\t#############################################################\n\t\n\n\t#############################################################\n\t##### Mananging the spectra\n\t#############################################################\n\n\tspec = sn + \"[*,1,1]\"            # generally multidimension\n\tiraf.imcopy(sn+'[*,1,1]','sn.fits',verbose='no')             # to create a onedimension fit to use during the script\n\t\n\t\n\tspectrum=iraf.wspec(\"sn.fits\",\"sn_xbbody.txt\", header='no')\n\tlcf = open('sn_xbbody.txt','r')     \n\triga = lcf.readlines()             \n\tlcf.close()\n\twave,flux= [],[]\n\tfor line in riga:\n\t    p = line.split()\n\t    wave.append(float(p[0]))\n\t    flux.append(float(p[1]))\n\t\n\twavev = array(wave)\n\tfluxv = array(flux)\n\twaveobs_min= min(wavev)\n\twaveobs_max= max(wavev)\n\t\n\t\n\tsplit = 0 # splitting value\n\n\tif ((waveobs_min-fil_obs_min) > 50) or ((fil_obs_max-waveobs_max) > 50):\n\t    print ''\n\t    if (waveobs_min-fil_obs_min) > 50:\n\t        print waveobs_min-fil_obs_min,' Angstrom not covered by the observed spectrum in the blue' \n\t        anguncov[ii] = waveobs_min-fil_obs_min\n\t        uncovside[ii] = 'Blue'\n\t    if (fil_obs_max-waveobs_max) > 50:\n\t        print fil_obs_max-waveobs_max,' Angstrom not covered by the observed spectrum in the red'\n\t        anguncov[ii] = fil_obs_max-waveobs_max\n\t        uncovside[ii] = 'Red'\n\t        ############################################\n\t        # Prevent small exceptions for blue bands or the extreme of the NIR\n\t        ############################################\n\t    if filter1 != 'U' or filter1 != 'u' or filter1 != 'K' or filter1 != 'uvw1' or filter1 != 'uvw2' or filter1 != 'uvm2' or filter1 != 'NUV' or filter1 != 'FUV':\n\n\t\t    ###############################\n\t\t    ### BBody evaluation of the observed spectrum\n\t\t    ###############################\n\t\t    BBparams, covar = curve_fit(bbody,wavev,fluxv,p0=(10000,1E-16)) #intial guess\n\t\t    T= BBparams[0]\n\t\t    Area = BBparams[1]\n\t\t    print '\\nBlackbody temperature observed spectrum = %.0f +\\- %.0f K\\n' % (T,np.sqrt(covar[0,0]))\n\t\t    bbt = 'BBobs = %.0f +\\- %.0f K' % (T,np.sqrt(covar[0,0]))\n\t\t    outputname = \"bbody_sn_fit.dat\" #% T\n\t\t    file = open(outputname,\"w\")\n\t\t    file.write(\"# Blackbody temperature = %.0f +\\- %.0f K\\n\" % (T,np.sqrt(covar[0,0])))\n\t\t    w,f = [],[]\n\t\t    for wav in range(900,26000):\n\t\t        file.write(\"%g\\t%g\\n\" % (wav,bbody(wav,T,Area)))\n\t\t        w.append(wav)\n\t\t        f.append(bbody(wav,T,Area))\n\n\t\t    iraf.rspec('bbody_sn_fit.dat','bbody_sn_fit.fits', title='bbodyfit',flux='no',dtype='interp',crval1=900,cdelt1=1)\n\t\t    iraf.scombine('bbody_sn_fit.fits,sn.fits,sn.fits,sn.fits', 'bsn_combo.fits',combine='median')\n\n\t\t    iraf.wspec('bsn_combo.fits','bsn_combo.txt',header='no')\n\n\n\t\t    lcf = open('bsn_combo.txt','r')\n\t\t    riga = lcf.readlines()\n\t\t    lcf.close()\n\t\t    wave,flux= [],[]\n\t\t    for line in riga:\n\t\t        p = line.split()\n\t\t        if float(line.split()[0]) >= fil_obs_min and float(line.split()[0]) <= fil_obs_max: #to match the spectrum wavelegnths to those of the filter\n\t\t            wave.append(float(p[0]))\n\t\t            flux.append(float(p[1]))\n\t\t        \n\t\t    wavev = array(wave)\n\t\t    fluxv = array(flux)\n\t\t    wavesp_min= min(wavev)\n\t\t    wavesp_max= int(max(wavev)) #needed to avoid problems with interp1d\n\n\t\t    # interpolating the two responses to match the length and sampling coverage\n\t\t    conf = conv(wavev,fluxv,wavefilterv,transmissionv,wavesp_min,wavesp_max,fil_obs_min,fil_obs_max)\n\t\t    ##################################\n\t\t    ### Evaluating the magnitudes\n\t\t    ##################################\n\t\t    flux_obs = max(integrate.cumtrapz(conf[0],conf[1])) # using trapezoidal rule to integrate\n\t\t    flux_obs_err = flux_obs * (1+(anguncov[ii]-50)*0.0001)\n\t\t\n\t\t    phot_filtobs_bb=-2.5*log10(flux_obs/zp_ef)\n\t\t    mcorrerrfilt_obs = abs(-2.5*log10(flux_obs/zp_ef_err) -(-2.5*log10(flux_obs/zp_ef)))\n\t\t    mcorrerr_bb = abs(-2.5*log10(flux_obs_err/zp_ef) - (-2.5*log10(flux_obs/zp_ef)))\n\t\t    mcorrerr = sqrt((mcorrerrfilt_obs**2 ++ mcorrerr_bb**2)/2)\n\n\t\t    mag[ii] = phot_filtobs_bb\n\t\t    mag_e[ii] = mcorrerr\n\t\t    method[ii] = 'Hybrid spec_BB'\n\t\t    btemp[ii] = bbt\t    \n\t\t    split = 1\n\n\t    elif filter1 == 'U' or filter1 == 'u' or filter1 == 'uvw1' or filter1 == 'uvw2' or filter1 == 'uvm2' or filter1 == 'NUV' or filter1 == 'FUV':\n\t\t    print waveobs_min-fil_obs_min,' Angstrom not covered by the observed spectrum in the blue'\n\t\t    mag[ii] = 0.0\n\t\t    mag_e[ii] = 0.0\n\t\t    method[ii] = 'None'\n\t\t    btemp[ii] = 'None' \n\t\t    anguncov[ii] = waveobs_min-fil_obs_min\n\t\t    uncovside[ii] = 'Blue'\n\t    elif filter1 == 'K':\n\t\t    print fil_obs_max-waveobs_max,' Angstrom not covered by the observed spectrum in the red'\n\t\t    mag[ii] = 0.0\n\t\t    mag_e[ii] = 0.0\n\t\t    method[ii] = 'None'\n\t\t    btemp[ii] = 'None'\n\t\t    anguncov[ii] = fil_obs_max-waveobs_max\n\t\t    uncovside[ii] = 'Red'\n\n\telse:\n\t\tiraf.wspec(\"sn.fits\",\"sn.txt\", header='no')\n\t\tlcf = open('sn.txt','r')\n\t\triga = lcf.readlines()\n\t\tlcf.close()\n\t\twave,flux= [],[]\n\t\tfor line in riga:\n\t\t    p = line.split()\n\t\t    if float(line.split()[0]) >= fil_obs_min and float(line.split()[0]) <= fil_obs_max: #to match the spectrum wavelegnths to those of the filter\n\t\t        wave.append(float(p[0]))\n\t\t        flux.append(float(p[1]))\n\t\t    \n\t\twavev = array(wave)\n\t\tfluxv = array(flux)\n\t\twavesp_min= min(wavev)\n\t\twavesp_max= int(max(wavev)) #needed to avoid problems with interp1d\n\t\t# interpolating the two responses to match the length and sampling coverage\n\t\tconf = conv(wavev,fluxv,wavefilterv,transmissionv,wavesp_min,wavesp_max,fil_obs_min,fil_obs_max)\n\t\t##################################\n\t\t### Evaluating the magnitudes\n\t\t##################################\n\t\tflux_obs = max(integrate.cumtrapz(conf[0],conf[1])) # using trapezoidal rule to integrate\n\t\tphot_filtobs_sn = -2.5*log10(flux_obs/zp_ef)\n\n\t\tmcorrerrfilt_obs = abs(-2.5*log10(flux_obs/zp_ef_err) -(-2.5*log10(flux_obs/zp_ef)))\n\n\t\tmag[ii] = phot_filtobs_sn\n\t\tmag_e[ii] = mcorrerrfilt_obs\n\t\tmethod[ii] = 'specTOspec'\n\t\tbtemp[ii] = 'None'\n\t\tanguncov[ii] = 0.0\n\t\tuncovside[ii] = 'None'\n\n\t# cleaning process (to avoid any problems with small RAM)\n\tos.system('rm -rf sn.txt')\n\tos.system('rm -rf sn.fits')\n\tos.system('rm -rf sn_xbbody.txt')\n\tos.system('rm -rf bsn_combo.fits')\n\tos.system('rm -rf bsn_combo.txt')\n\tos.system('rm -rf bbody_sn_fit.dat')\n\tos.system('rm -rf bbody_sn_fit.fits')\n\tsleep(_sleepc) #to avoid missing files and correction due to a combo of two different spectra (a.k.a. the code arrives at the right step before the system remove the file)\n\t##########################\n\t### Adding values to the txt file\n\t#########################\n\tfilekc.write(snname)\n\tfilekc.write(\"\\t\")\n\tfilekc.write(filter1)\n\tfilekc.write(\"\\t\\t\")\n\tfilekc.write(\"%0.3f\" % (mag[ii]))\n\tfilekc.write(\"\\t\\t\")\n\tfilekc.write(\"%0.3f\" % (mag_e[ii]))\n\tfilekc.write(\"\\t\\t\")\n\tfilekc.write(method[ii])\n\tfilekc.write(\"\\t\\t\")\n\tfilekc.write(btemp[ii])\n\tfilekc.write(\"\\t\\t\")\n\tfilekc.write(\"%s\" % (anguncov[ii]))\n\tfilekc.write(\"\\t\")\n\tfilekc.write(uncovside[ii])\n\tfilekc.write(\"\\n\")\n\n\tax = axes([0.1, 0.1, 0.65, 0.80])\n\tplot(9999,9999,color='k',marker='o',markeredgecolor='k',ms=10,ls='None')\n\tplot(9999,9999,color='k',marker='s',markeredgecolor='k',ms=10,ls='None')\n\tplot(9999,9999,color='k',marker='^',markeredgecolor='k',ms=10,ls='None')\n\tplot(9999,9999,color='k',marker='d',markeredgecolor='k',ms=10,ls='None')\n\tplot(9999,9999,color='k',marker='v',markeredgecolor='k',ms=10,ls='None')\n\tplot(9999,9999,color='k',marker='D',markeredgecolor='k',ms=10,ls='None')\n\tplot(9999,9999,color='k',marker='h',markeredgecolor='k',ms=10,ls='None')\n\tmags,snums = [],[]\n\tif fobs[ii] == 'rs':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='s',color='orange',ms=12)\n\tif fobs[ii] == 'is':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='s',color='r',ms=12)\n\tif fobs[ii] == 'zs':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='s',color='brown',ms=12)\n\tif fobs[ii] == 'gs':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='s',color='green',ms=12)\n\tif fobs[ii] == 'us':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='s',color='blue',ms=12)\n\tif fobs[ii] == 'U':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='o',color='darkblue',ms=12)\n\tif fobs[ii] == 'B':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='o',color='cyan',ms=12)\n\tif fobs[ii] == 'V':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='o',color='yellow',ms=12)\n\tif fobs[ii] == 'R':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='o',color='#C35817',ms=12)\n\tif fobs[ii] == 'I':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='o',color='m',ms=12)\t\n\tif fobs[ii] == 'J':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='^',color='#6F4E37',ms=12)\t\n\tif fobs[ii] == 'J_ab':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='d',color='#6F4E37',ms=12)\t\n\tif fobs[ii] == 'H':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='^',color='#B87333',ms=12)\t\n\tif fobs[ii] == 'H_ab':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='d',color='#B87333',ms=12)\t\n\tif fobs[ii] == 'K':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='^',color='#827B60',ms=12)\t\n\tif fobs[ii] == 'K_ab':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='d',color='#827B60',ms=12)\t\n\tif fobs[ii] == 'uvw1':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='v',color='#7FFFD4',ms=12)\t\n\tif fobs[ii] == 'uvw1_ab':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='D',color='#7FFFD4',ms=12)\t\n\tif fobs[ii] == 'uvm2':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='v',color='#6960EC',ms=12)\t\n\tif fobs[ii] == 'uvm2_ab':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='D',color='#6960EC',ms=12)\t\n\tif fobs[ii] == 'uvw2':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='v',color='#7D0552',ms=12)\t\n\tif fobs[ii] == 'uvw2_ab':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='D',color='#7D0552',ms=12)\t\n\tif fobs[ii] == 'FUV':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='h',color='#4B0082',ms=12)\t\n\tif fobs[ii] == 'NUV':\n\t\tmags.append(mag[ii])\n\t\tsnums.append(snum)\n\t\tplot(snums,mags,marker='h',color='#95B9C7',ms=12)\t\n\tii = ii + 1\n\nthen = time.time()\ntime = then -now\n###########################\n### plotting commands\n###########################\nxl = [0.2,float(len(snlist))+0.1]\nyl = [min(mag)-0.6,max(mag)+0.6]\nlegend(('Bessell', 'Sloan', 'NIR(Vega)', 'NIR(ab)','SwiftUV(Vega)','SwiftUV(ab)','GALEX'), numpoints=1,bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.)\nfont = FontProperties()\nfont.set_weight('bold')\ntext(0.3,max(mag)-((max(mag)-min(mag))/18),'U-Bessell',fontproperties=font,fontsize = 12, color = 'darkblue')\ntext(0.3,max(mag)-(2*(max(mag)-min(mag))/18),'B-Bessell',fontproperties=font,fontsize = 12, color = 'c')\ntext(0.3, max(mag)-(3*(max(mag)-min(mag))/18),'V-Bessell',fontproperties=font,fontsize = 12, color = 'yellow')\ntext(0.3, max(mag)-(4*(max(mag)-min(mag))/18),'R-Bessell',fontproperties=font,fontsize = 12, color = '#C35817')\ntext(0.3, max(mag)-(5*(max(mag)-min(mag))/18),'I-Bessell',fontproperties=font,fontsize = 12, color = 'm')\ntext(0.3, max(mag)-(6*(max(mag)-min(mag))/18),'u-Sloan',fontproperties=font,fontsize = 12, color = 'b')\ntext(0.3, max(mag)-(7*(max(mag)-min(mag))/18),'g-Sloan',fontproperties=font,fontsize = 12, color = 'g')\ntext(0.3, max(mag)-(8*(max(mag)-min(mag))/18),'r-Sloan',fontproperties=font,fontsize = 12, color = 'orange')\ntext(0.3, max(mag)-(9*(max(mag)-min(mag))/18),'i-Slaon',fontproperties=font,fontsize = 12, color = 'r')\ntext(0.3, max(mag)-(10*(max(mag)-min(mag))/18),'z-Sloan',fontproperties=font,fontsize = 12, color = 'brown')\ntext(0.3, max(mag)-(11*(max(mag)-min(mag))/18),'J-2MASS',fontproperties=font,fontsize = 12, color = '#6F4E37')\ntext(0.3, max(mag)-(12*(max(mag)-min(mag))/18),'H-2MASS',fontproperties=font,fontsize = 12, color = '#B87333')\ntext(0.3, max(mag)-(13*(max(mag)-min(mag))/18),'K-2MASS',fontproperties=font,fontsize = 12, color = '#827B60')\ntext(0.3, max(mag)-(14*(max(mag)-min(mag))/18),'uvw1-UVOT',fontproperties=font,fontsize = 12, color = '#7FFFD4')\ntext(0.3, max(mag)-(15*(max(mag)-min(mag))/18),'uvm2-UVOT',fontproperties=font,fontsize = 12, color = '#6960EC')\ntext(0.3, max(mag)-(16*(max(mag)-min(mag))/18),'uvw2-UVOT',fontproperties=font,fontsize = 12, color = '#7D0552')\ntext(0.3, max(mag)-(17*(max(mag)-min(mag))/18),'NUV-GALEX',fontproperties=font,fontsize = 12, color = '#95B9C7')\ntext(0.3, max(mag)-(18*(max(mag)-min(mag))/18),'FUV-GALEX',fontproperties=font,fontsize = 12, color = '#4B0082')\nxlim(xl[0],xl[1])\nylim(yl[0],yl[1])\n\nxlabel('Spectrum',size=18)\nylabel('Magnitude',size=18)\nax.minorticks_on()\nshow()\n####################\n##### writing legend on the file\n####################\nfilekc.write(\"\\n# ----------------------------------------------------------------------------------\\n\")\nfilekc.write(\"# Legend for SMS mode:\\n\")\nfilekc.write(\"# specTOspec        \\t--> Magnitude computed with original spectrum\\n\")\nfilekc.write(\"# Hybrid     spec_BB\\t--> Magnitude computed with a SN+Bbody hybrid\\n\")\nfilekc.write(\"# ----------------------------------------------------------------------------------\\n\")\n\nsltime = _sleepc*len(snlist)\nprint '######################################################################'\nprint ''\nprint ' Evaluation done in %.0is, of which %.0is to take a nap to let rest your Random Access Memory (RAM) ' % (time,sltime)\t\nprint ''\nprint ' \\033[46mList of Magnitudes\\033[0m ' , mag\nprint ' \\033[44mVersion used\\033[0m ' , method\nprint ''\nprint ' A text file has been created ===> Magnitudes_%.0i_%.0i.txt ' % (Tnowd,Tnow)\t\t\n\n", "meta": {"hexsha": "9d4987d31f975a772bec241f58e83c644a0a769d", "size": 22208, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/s3/SMS.py", "max_stars_repo_name": "cinserra/S3", "max_stars_repo_head_hexsha": "eefc12265bd7824204dc5cbbd648e3ff8b291273", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-07-24T17:35:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-05T15:40:45.000Z", "max_issues_repo_path": "src/s3/SMS.py", "max_issues_repo_name": "cinserra/S3", "max_issues_repo_head_hexsha": "eefc12265bd7824204dc5cbbd648e3ff8b291273", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-24T10:46:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-24T10:46:26.000Z", "max_forks_repo_path": "src/s3/SMS.py", "max_forks_repo_name": "cinserra/S3", "max_forks_repo_head_hexsha": "eefc12265bd7824204dc5cbbd648e3ff8b291273", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-12T13:03:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-12T13:03:05.000Z", "avg_line_length": 39.7280858676, "max_line_length": 172, "alphanum_fraction": 0.5896523775, "include": true, "reason": "from numpy,from scipy", "num_tokens": 6679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.30404168757891037, "lm_q1q2_score": 0.18588561122142797}}
{"text": "\"\"\"\nModule that si mulates the front-end electronics (triggering, ADC)\n\"\"\"\n\nimport numpy as np\nimport cupy as cp\nimport h5py\n\nfrom numba import cuda\nfrom numba.cuda.random import xoroshiro128p_normal_float32\n\nfrom larpix.packet import Packet_v2, TimestampPacket\nfrom larpix.packet import PacketCollection\nfrom larpix.format import hdf5format\nfrom tqdm import tqdm\nfrom . import consts, detsim\n\n#: Maximum number of ADC values stored per pixel\nMAX_ADC_VALUES = 10\n#: Discrimination threshold\nDISCRIMINATION_THRESHOLD = 5e3*consts.e_charge\n#: ADC hold delay in clock cycles\nADC_HOLD_DELAY = 15\n#: Clock cycle time in :math:`\\mu s`\nCLOCK_CYCLE = 0.1\n#: Front-end gain in :math:`mV/ke-`\nGAIN = 4/1e3\n#: Common-mode voltage in :math:`mV`\nV_CM = 288\n#: Reference voltage in :math:`mV`\nV_REF = 1300\n#: Pedestal voltage in :math:`mV`\nV_PEDESTAL = 580\n#: Number of ADC counts\nADC_COUNTS = 2**8\n#: Reset noise in e-\nRESET_NOISE_CHARGE = 900\n#: Uncorrelated noise in e-\nUNCORRELATED_NOISE_CHARGE = 500\n\ndef export_to_hdf5(adc_list, adc_ticks_list, unique_pix, track_ids, filename):\n    \"\"\"\n    Saves the ADC counts in the LArPix HDF5 format.\n\n    Args:\n        adc_list (:obj:`numpy.ndarray`): list of ADC values for each pixel\n        adc_ticks_list (:obj:`numpy.ndarray`): list of time ticks for each pixel\n        unique_pix (:obj:`numpy.ndarray`): list of pixel IDs\n        filename (str): filename of HDF5 output file\n\n    Returns:\n        list: list of LArPix packets\n    \"\"\"\n\n    dtype = np.dtype([('track_ids','(5,)i8')])\n    packets = {}\n    packets_mc = {}\n    packets_mc_ds = {}\n\n    for ic in range(consts.tpc_centers.shape[0]):\n        packets[ic] = []\n        packets_mc[ic] = []\n        packets_mc_ds[ic] = []\n\n    for itick, adcs in enumerate(tqdm(adc_list, desc=\"Writing to HDF5...\")):\n        ts = adc_ticks_list[itick]\n        pixel_id = unique_pix[itick]\n        plane_id = pixel_id[0] // consts.n_pixels[0]\n        pix_x, pix_y = detsim.get_pixel_coordinates(pixel_id)\n\n        try:\n            pix_x -= consts.tpc_centers[int(plane_id)][0]\n            pix_y -= consts.tpc_centers[int(plane_id)][1]\n        except IndexError:\n            print(\"Pixel (%i, %i) outside the TPC borders\" % (pixel_id[0], pixel_id[1]))\n\n        pix_x *= consts.cm2mm\n        pix_y *= consts.cm2mm\n\n        for iadc, adc in enumerate(adcs):\n            t = ts[iadc]\n\n            if adc > digitize(0):\n                p = Packet_v2()\n\n                try:\n                    channel, chip = consts.pixel_connection_dict[(round(pix_x/consts.pixel_size[0]),round(pix_y/consts.pixel_size[1]))]\n                except KeyError:\n                    print(\"Pixel coordinates not valid\", pix_x, pix_y, pixel_id, adc)\n                    continue\n\n                p.dataword = int(adc)\n                p.timestamp = int(np.floor(t/CLOCK_CYCLE))\n\n                if isinstance(chip, int):\n                    p.chip_id = chip\n                else:\n                    p.chip_key = chip\n\n                p.channel_id = channel\n                p.packet_type = 0\n                p.first_packet = 1\n                p.assign_parity()\n\n                if not packets[plane_id]:\n                    packets[plane_id].append(TimestampPacket())\n                    packets_mc[plane_id].append([-1]*5)\n\n                packets_mc[plane_id].append(track_ids[itick][iadc])\n                packets[plane_id].append(p)\n            else:\n                break\n\n    for ipc in packets:\n        packet_list = PacketCollection(packets[ipc], read_id=0, message='')\n\n        if len(packets.keys()) > 1:\n            if \".\" in filename:\n                pre_extension, post_extension = filename.rsplit('.', 1)\n                filename_ext = \"%s-%i.%s\" % (pre_extension, ipc, post_extension)\n            else:\n                filename_ext = \"%s-%i\" % (filename, ipc)\n        else:\n            filename_ext = filename\n\n        hdf5format.to_file(filename_ext, packet_list)\n        if len(packets[ipc]):\n            packets_mc_ds[ipc] = np.empty(len(packets[ipc]), dtype=dtype)\n            packets_mc_ds[ipc]['track_ids'] = packets_mc[ipc]\n\n        with h5py.File(filename_ext, 'a') as f:\n            if \"mc_packets_assn\" in f.keys():\n                del f['mc_packets_assn']\n            f.create_dataset(\"mc_packets_assn\", data=packets_mc_ds[ipc])\n\n    return packets, packets_mc\n\ndef digitize(integral_list):\n    \"\"\"\n    The function takes as input the integrated charge and returns the digitized\n    ADC counts.\n\n    Args:\n        integral_list (:obj:`numpy.ndarray`): list of charge collected by each pixel\n\n    Returns:\n        numpy.ndarray: list of ADC values for each pixel\n    \"\"\"\n    xp = cp.get_array_module(integral_list)\n    adcs = xp.minimum(xp.floor(xp.maximum((integral_list*GAIN/consts.e_charge+V_PEDESTAL - V_CM), 0) \\\n                      * ADC_COUNTS/(V_REF-V_CM)), ADC_COUNTS)\n\n    return adcs\n\n@cuda.jit\ndef get_adc_values(pixels_signals, time_ticks, adc_list, adc_ticks_list, time_padding, rng_states):\n    \"\"\"\n    Implementation of self-trigger logic\n\n    Args:\n        pixels_signals (:obj:`numpy.ndarray`): list of induced currents for\n            each pixel\n        time_ticks (:obj:`numpy.ndarray`): list of time ticks for each pixel\n        adc_list (:obj:`numpy.ndarray`): list of integrated charges for each\n            pixel\n        adc_ticks_list (:obj:`numpy.ndarray`): list of the time ticks that\n            correspond to each integrated charge.\n    \"\"\"\n    ip = cuda.grid(1)\n\n    if ip < pixels_signals.shape[0]:\n        curre = pixels_signals[ip]\n        ic = 0\n        iadc = 0\n        q_sum = xoroshiro128p_normal_float32(rng_states, ip) * RESET_NOISE_CHARGE * consts.e_charge\n\n        while ic < curre.shape[0]:\n\n            q = curre[ic]*consts.t_sampling\n\n            q_sum += q\n            q_noise = xoroshiro128p_normal_float32(rng_states, ip) * UNCORRELATED_NOISE_CHARGE * consts.e_charge\n\n            if q_sum + q_noise >= DISCRIMINATION_THRESHOLD:\n\n                interval = round((3 * CLOCK_CYCLE + ADC_HOLD_DELAY * CLOCK_CYCLE) / consts.t_sampling)\n                integrate_end = ic+interval\n\n                while ic <= integrate_end and ic < curre.shape[0]:\n                    q = curre[ic] * consts.t_sampling\n                    q_sum += q\n                    ic += 1\n\n                adc = q_sum + xoroshiro128p_normal_float32(rng_states, ip) * UNCORRELATED_NOISE_CHARGE * consts.e_charge\n\n                if adc < DISCRIMINATION_THRESHOLD:\n                    ic += round(CLOCK_CYCLE / consts.t_sampling)\n                    continue\n\n                if iadc >= MAX_ADC_VALUES:\n                    print(\"More ADC values than possible, \", MAX_ADC_VALUES)\n                    break\n\n                adc_list[ip][iadc] = adc\n                adc_ticks_list[ip][iadc] = time_ticks[ic]+time_padding\n                ic += round(CLOCK_CYCLE / consts.t_sampling)\n                q_sum = xoroshiro128p_normal_float32(rng_states, ip) * RESET_NOISE_CHARGE * consts.e_charge\n                iadc += 1\n\n            ic += 1\n", "meta": {"hexsha": "0f5869517157cc47517115c491b9d790058f3c3d", "size": 7023, "ext": "py", "lang": "Python", "max_stars_repo_path": "larndsim/fee.py", "max_stars_repo_name": "soleti/larnd-sim", "max_stars_repo_head_hexsha": "6e6054e44217441df77e885ea7833f8c576f9564", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-19T17:44:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-19T17:44:03.000Z", "max_issues_repo_path": "larndsim/fee.py", "max_issues_repo_name": "soleti/larnd-sim", "max_issues_repo_head_hexsha": "6e6054e44217441df77e885ea7833f8c576f9564", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-03T21:20:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T21:20:28.000Z", "max_forks_repo_path": "larndsim/fee.py", "max_forks_repo_name": "soleti/larnd-sim", "max_forks_repo_head_hexsha": "6e6054e44217441df77e885ea7833f8c576f9564", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-18T20:26:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-22T20:13:20.000Z", "avg_line_length": 33.2843601896, "max_line_length": 135, "alphanum_fraction": 0.5993165314, "include": true, "reason": "import numpy,from numba,import cupy", "num_tokens": 1733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.1857373765131136}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 24 22:17:09 2022\n\n@author: oiseth\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 16 22:09:00 2021\n\n@author: oiseth\n\"\"\"\nimport numpy as np\nfrom scipy import signal as spsp\nfrom scipy import linalg as spla\nfrom scipy import special as spspes\nfrom matplotlib import pyplot as plt\nfrom copy import deepcopy\nfrom ._exp import Experiment\nimport pandas as pd\n\n\n\n__all__ = [\"AerodynamicDerivatives\",\"AerodynamicDerivative\",]\n\n    \n   \nclass AerodynamicDerivative:\n    \"\"\" \n    A class used to represent a aerodynamic derivative\n    \n    Arguments\n    ---------\n    reduced_velocities  : float\n        reduced velocities\n    ad_load_cell_1      : float\n        contribution to aerodynamic derivative from load cell 1\n    ad_load_cell_2      : float\n        contribution to aerodynamic derivative from load cell 2\n    ad_load_cell_3      : float\n        contribution to aerodynamic derivative from load cell 3\n    ad_load_cell_4      : float\n        contribution to aerodynamic derivative from load cell 4\n    mean_wind_speeds    : float\n        mean wind velocities\n    frequencies         : float\n        frequencies of the motions applied to obtain ads\n    label               : str\n        aerodynamic derivative label\n    ---------\n    \n    Methods:\n    --------\n    plot()\n        plots the aerodynamic derivative        \n    \n    \"\"\"\n    def __init__(self,label=\"x\",reduced_velocities=[],ad_load_cell_1=[],ad_load_cell_2=[],ad_load_cell_3=[],ad_load_cell_4=[],mean_wind_speeds=[], frequencies=[]):\n        \"\"\"  \n            \n        Arguments\n        ---------\n        reduced_velocities  : float\n            reduced velocities\n        ad_load_cell_1      : float\n            contribution to aerodynamic derivative from load cell 1\n        ad_load_cell_2      : float\n            contribution to aerodynamic derivative from load cell 2\n        ad_load_cell_3      : float\n            contribution to aerodynamic derivative from load cell 3\n        ad_load_cell_4      : float\n            contribution to aerodynamic derivative from load cell 4\n        mean_wind_speeds    : float\n            mean wind velocities\n        frequencies         : float\n            frequencies of the motions applied to obtain ads\n        label               : str\n            aerodynamic derivative label\n        ---------\n        \n        \"\"\"\n        self.reduced_velocities = reduced_velocities\n        self.ad_load_cell_1 = ad_load_cell_1\n        self.ad_load_cell_2 = ad_load_cell_2\n        self.ad_load_cell_3 = ad_load_cell_3\n        self.ad_load_cell_4 = ad_load_cell_4\n        self.mean_wind_speeds = mean_wind_speeds\n        self.frequencies = frequencies\n        self.label = label\n    \n    @property    \n    def value(self):\n        return self.ad_load_cell_1 + self.ad_load_cell_2 + self.ad_load_cell_3 + self.ad_load_cell_4\n        \n        \n    def plot(self, mode = \"all\", conv = \"normal\", ax=[] ):\n        \"\"\" plots the aerodynamic derivative\n        \n        The method plots the aerodynamic derivative as function of the mean \n        wind speed. Four optimal modes are abailable.\n        \n        parameters:\n        ----------\n        mode : str, optional\n            selects the plot mode\n        conv: str, optional\n            selects which convention to use when plotting\n        fig : pyplot figure instance    \n        ---------        \n        \n        \"\"\"\n        if bool(ax) == False:\n            fig = plt.figure()\n            ax = fig.add_subplot(1,1,1)\n        \n        \n        if conv == \"normal\":\n            if mode == \"all\":\n                ax.plot(self.reduced_velocities,self.ad_load_cell_1 + self.ad_load_cell_2+ self.ad_load_cell_3 + self.ad_load_cell_4, \"o\", label=\"Total\")\n                ax.plot(self.reduced_velocities,self.ad_load_cell_1, \"o\", label=\"Load cell 1\", alpha = 0.5)\n                ax.plot(self.reduced_velocities,self.ad_load_cell_2, \"o\", label=\"Load cell 2\", alpha = 0.5)\n                ax.plot(self.reduced_velocities,self.ad_load_cell_3, \"o\", label=\"Load cell 3\", alpha = 0.5)\n                ax.plot(self.reduced_velocities,self.ad_load_cell_4, \"o\", label=\"Load cell 4\", alpha = 0.5)\n                ax.set_ylabel((\"$\" + self.label + \"$\"))\n                ax.set_xlabel(r\"Reduced velocity $\\hat{V}$\")\n                ax.legend()\n                ax.grid(True)\n            \n            elif mode == \"decks\":\n                ax.plot(self.reduced_velocities,self.ad_load_cell_1 + self.ad_load_cell_2+ self.ad_load_cell_3 + self.ad_load_cell_4, \"o\", label=\"Total\")\n                ax.plot(self.reduced_velocities,self.ad_load_cell_1 + self.ad_load_cell_2, \"o\", label=\"Upwind deck\", alpha = 0.5)\n                ax.plot(self.reduced_velocities,self.ad_load_cell_3 + self.ad_load_cell_4, \"o\", label=\"Downwind deck\", alpha = 0.5)\n                ax.set_ylabel((\"$\" + self.label + \"$\"))\n                ax.set_xlabel(r\"Reduced velocity $\\hat{V}$\")\n                ax.grid(True)\n                ax.legend()\n                \n            elif mode == \"total\":\n                ax.plot(self.reduced_velocities,self.ad_load_cell_1 + self.ad_load_cell_2+ self.ad_load_cell_3 + self.ad_load_cell_4, \"o\", label=\"Total\")\n                ax.set_ylabel((\"$\" + self.label + \"$\"))\n                ax.set_xlabel(r\"Reduced velocity $\\hat{V}$\")\n                ax.grid(True)\n            #plt.tight_layout()\n                \n        elif conv == \"zasso\" and len(self.reduced_velocities) != 0:\n            damping_ads =[\"P_1^*\",\"P_2^*\", \"P_5^*\", \"H_1^*\", \"H_2^*\", \"H_5^*\", \"A_1^*\", \"A_2^*\", \"A_5^*\" ]\n            stiffness_ads =[\"P_3^*\",\"P_4^*\", \"P_6^*\", \"H_3^*\", \"H_4^*\", \"H_6^*\", \"A_3^*\", \"A_4^*\", \"A_6^*\" ]\n            \n             \n            if self.label in damping_ads:\n                factor = 1.0/self.reduced_velocities\n                K_label = \"K\"\n            elif self.label in stiffness_ads:\n                factor = 1.0/self.reduced_velocities**2\n                K_label = \"K^2\"\n            else:\n                print(\"ERROR\")\n\n            \n            if mode == \"all\":\n                ax.plot(self.reduced_velocities,factor*(self.ad_load_cell_1 + self.ad_load_cell_2+ self.ad_load_cell_3 + self.ad_load_cell_4), \"o\", label=\"Total\")\n                ax.plot(self.reduced_velocities,factor*self.ad_load_cell_1, \"o\", label=\"Load cell 1\", alpha = 0.5)\n                ax.plot(self.reduced_velocities,factor*self.ad_load_cell_2, \"o\", label=\"Load cell 2\", alpha = 0.5)\n                ax.plot(self.reduced_velocities,factor*self.ad_load_cell_3, \"o\", label=\"Load cell 3\", alpha = 0.5)\n                ax.plot(self.reduced_velocities,factor*self.ad_load_cell_4, \"o\", label=\"Load cell 4\", alpha = 0.5)\n                ax.set_ylabel((\"$\" + K_label + self.label + \"$\"))\n                ax.set_xlabel(r\"Reduced velocity $\\hat{V}$\")\n                ax.legend()\n                ax.grid(True)\n            \n            elif mode == \"decks\":\n                ax.plot(self.reduced_velocities,factor*(self.ad_load_cell_1 + self.ad_load_cell_2+ self.ad_load_cell_3 + self.ad_load_cell_4), \"o\", label=\"Total\")\n                ax.plot(self.reduced_velocities,factor*(self.ad_load_cell_1 + self.ad_load_cell_2), \"o\", label=\"Upwind deck\", alpha = 0.5)\n                ax.plot(self.reduced_velocities,factor*(self.ad_load_cell_3 + self.ad_load_cell_4), \"o\", label=\"Downwind deck\", alpha = 0.5)\n                ax.set_ylabel((\"$\" + K_label + self.label + \"$\"))\n                ax.set_xlabel(r\"Reduced velocity $\\hat{V}$\")\n                ax.legend()\n                ax.grid(True)\n                \n            elif mode == \"total\":\n                ax.plot(self.reduced_velocities,factor*(self.ad_load_cell_1 + self.ad_load_cell_2+ self.ad_load_cell_3 + self.ad_load_cell_4), \"o\", label=\"Total\")\n                ax.set_ylabel((\"$\" + K_label + self.label + \"$\"))\n                ax.set_xlabel(r\"Reduced velocity $\\hat{V}$\")\n                ax.grid(True)\n        \n        #plt.tight_layout()\n                \n\nclass AerodynamicDerivatives:\n    \"\"\"\n    A class used to represent all aerodynamic derivatives for a 3 dof motion\n    \n    parameters:\n    ----------\n    p1...p6 : obj\n        aerodynamic derivatives related to the horizontal self-excited force\n    h1...h6 : obj\n        aerodynamic derivatives related to the vertical self-excited force\n    a1...a6 : obj\n        aerodynamic derivative related to the pitchingmoment\n    ---------   \n    \n    methods:\n    -------\n    .fromWTT()\n        obtains aerodynamic derivatives from a sequence of single harmonic wind tunnel tests\n    .append()\n        appends an instance of the class AerodynamicDerivtives to self    \n    .plot()\n        plots all aerodynamic derivatives    \n    \n    \n    \n    \"\"\"\n    def __init__(self, p1=None, p2=None, p3=None, p4=None, p5=None, p6=None, h1=None, h2=None, \n                 h3=None, h4=None, h5=None, h6=None, a1=None, a2=None, a3=None, a4=None, a5=None, a6=None):\n        \"\"\"\n        parameters:\n        ----------\n        p1...p6 : obj\n         aerodynamic derivatives related to the horizontal self-excited force\n        h1...h6 : obj\n         aerodynamic derivatives related to the vertical self-excited force\n        a1...a6 : obj\n         aerodynamic derivative related to the pitchingmoment\n        ---------\n        \"\"\"\n        \n        \n        self.p1 = p1 or AerodynamicDerivative(label=\"P_1^*\")\n        self.p2 = p2 or AerodynamicDerivative(label=\"P_2^*\")\n        self.p3 = p3 or AerodynamicDerivative(label=\"P_3^*\")\n        self.p4 = p4 or AerodynamicDerivative(label=\"P_4^*\")\n        self.p5 = p5 or AerodynamicDerivative(label=\"P_5^*\")\n        self.p6 = p6 or AerodynamicDerivative(label=\"P_6^*\")\n        \n        self.h1 = h1 or AerodynamicDerivative(label=\"H_1^*\")\n        self.h2 = h2 or AerodynamicDerivative(label=\"H_2^*\")\n        self.h3 = h3 or AerodynamicDerivative(label=\"H_3^*\")\n        self.h4 = h4 or AerodynamicDerivative(label=\"H_4^*\")\n        self.h5 = h5 or AerodynamicDerivative(label=\"H_5^*\")\n        self.h6 = h6 or AerodynamicDerivative(label=\"H_6^*\")\n        \n        self.a1 = a1 or AerodynamicDerivative(label=\"A_1^*\")\n        self.a2 = a2 or AerodynamicDerivative(label=\"A_2^*\")\n        self.a3 = a3 or AerodynamicDerivative(label=\"A_3^*\")\n        self.a4 = a4 or AerodynamicDerivative(label=\"A_4^*\")\n        self.a5 = a5 or AerodynamicDerivative(label=\"A_5^*\")\n        self.a6 = a6 or AerodynamicDerivative(label=\"A_6^*\")\n    \n        \n    @classmethod\n    def fromWTT(cls,experiment_in_still_air,experiment_in_wind,section_width,section_length, filter_order = 6, cutoff_frequency = 7):\n        \"\"\" obtains an instance of the class Aerodynamic derivatives from a wind tunnel experiment\n        \n        parameters:\n        ----------\n        experiment_in_still_air : instance of the class experiment\n        experiment_in_wind   : instance of the class experiment\n        section_width        : width of the bridge deck section model\n        section_length       : length of the section model\n        ---------\n        \n        returns:\n        --------\n        an instance of the class AerodynamicDerivatives\n        to instances of the class Experiment, one for model predictions and one for data used to fit the model\n        \n        \n        \"\"\"\n        experiment_in_wind.align_with(experiment_in_still_air)\n        experiment_in_wind_still_air_forces_removed = deepcopy(experiment_in_wind)\n        experiment_in_wind_still_air_forces_removed.substract(experiment_in_still_air)\n        starts, stops = experiment_in_wind_still_air_forces_removed.harmonic_groups()\n        \n        \n        frequencies_of_motion = np.zeros(len(starts))\n        reduced_velocities = np.zeros(len(starts))\n        mean_wind_speeds = np.zeros(len(starts))\n        \n        normalized_coefficient_matrix = np.zeros((2,3,len(starts),4))\n        \n        forces_predicted_by_ads = np.zeros((experiment_in_wind_still_air_forces_removed.forces_global_center.shape[0],24))\n        #model_forces = np.zeros((experiment_in_wind_still_air_forces_removed.forces_global_center.shape[0],3))\n        \n        # loop over all single harmonic test in the time series\n        for k in range(len(starts)):           \n\n            sampling_frequency = 1/(experiment_in_still_air.time[1]- experiment_in_still_air.time[0])\n       \n            sos = spsp.butter(filter_order,cutoff_frequency, fs=sampling_frequency, output=\"sos\")\n           \n            motions = experiment_in_wind_still_air_forces_removed.motion\n            \n            motions = spsp.sosfiltfilt(sos,motions,axis=0)\n            \n            time_derivative_motions = np.vstack((np.array([0,0,0]),np.diff(motions,axis=0)))*sampling_frequency\n            \n            max_hor_vert_pitch_motion = [np.max(motions[:,0]), np.max(motions[:,1]), np.max(motions[:,2]) ]\n            motion_type = np.argmax(max_hor_vert_pitch_motion)\n            \n            fourier_amplitudes = np.fft.fft(motions[starts[k]:stops[k],motion_type])\n            \n            \n            time_step = experiment_in_wind_still_air_forces_removed.time[1]- experiment_in_wind_still_air_forces_removed.time[0]\n            \n            peak_index = np.argmax(np.abs(fourier_amplitudes[0:np.int(len(fourier_amplitudes)/2)]))\n            \n            frequencies = np.fft.fftfreq(len(fourier_amplitudes),time_step)\n            \n            frequency_of_motion = frequencies[peak_index]\n            frequencies_of_motion[k] = frequency_of_motion\n         \n            regressor_matrix = np.vstack((time_derivative_motions[starts[k]:stops[k],motion_type],motions[starts[k]:stops[k],motion_type])).T\n                        \n            pseudo_inverse_regressor_matrix = spla.pinv(regressor_matrix) \n            selected_forces = np.array([0,2,4])\n            \n            \n            mean_wind_speed = np.mean(experiment_in_wind_still_air_forces_removed.wind_speed[starts[k]:stops[k]])\n            mean_wind_speeds[k] = mean_wind_speed\n                \n            reduced_frequency  = frequency_of_motion*2*np.pi*section_width/mean_wind_speed\n            \n            reduced_velocities[k] = 1/reduced_frequency\n            \n            #model_forces = np.zeros((experiment_in_wind_still_air_forces_removed.forces_global_center.shape))\n            \n            # Loop over all load cells\n            for m in range(4):            \n                forces = experiment_in_wind_still_air_forces_removed.forces_global_center[starts[k]:stops[k],selected_forces + 6*m]\n                froces_mean_wind_removed = forces - np.mean(experiment_in_wind_still_air_forces_removed.forces_global_center[0:400,selected_forces + 6*m],axis= 0)\n                                \n                coefficient_matrix = pseudo_inverse_regressor_matrix @ froces_mean_wind_removed\n                                \n                normalized_coefficient_matrix[:,:,k,m] = np.copy(coefficient_matrix)\n                normalized_coefficient_matrix[0,:,k,m] = normalized_coefficient_matrix[0,:,k,m]*2  / experiment_in_wind_still_air_forces_removed.air_density / mean_wind_speed / reduced_frequency / section_width / section_length\n                normalized_coefficient_matrix[1,:,k,m] = normalized_coefficient_matrix[1,:,k,m]*2  /experiment_in_wind_still_air_forces_removed.air_density / mean_wind_speed**2 / reduced_frequency**2 /section_length\n                normalized_coefficient_matrix[:,2,k,m] = normalized_coefficient_matrix[:,2,k,m]/section_width\n                \n                if motion_type ==2:\n                    normalized_coefficient_matrix[:,:,k,m] = normalized_coefficient_matrix[:,:,k,m]/section_width \n                \n                forces_predicted_by_ads[starts[k]:stops[k],selected_forces + 6*m] = forces_predicted_by_ads[starts[k]:stops[k],selected_forces + 6*m]  + regressor_matrix @ coefficient_matrix + np.mean(experiment_in_wind_still_air_forces_removed.forces_global_center[0:400,selected_forces + 6*m],axis= 0)\n            \n               \n        # Make Experiment object for simulation of model\n        obj1 = experiment_in_wind_still_air_forces_removed\n        obj2 = experiment_in_still_air\n        model_prediction = Experiment(obj1.name, obj1.time, obj1.temperature, obj1.air_density, obj1.wind_speed,[],forces_predicted_by_ads,obj2.motion)\n                 \n        \n        p1 = AerodynamicDerivative()\n        p2 = AerodynamicDerivative()\n        p3 = AerodynamicDerivative()\n        p4 = AerodynamicDerivative()\n        p5 = AerodynamicDerivative()\n        p6 = AerodynamicDerivative()\n            \n        h1 = AerodynamicDerivative()\n        h2 = AerodynamicDerivative()\n        h3 = AerodynamicDerivative()\n        h4 = AerodynamicDerivative()\n        h5 = AerodynamicDerivative()\n        h6 = AerodynamicDerivative()\n            \n        a1 = AerodynamicDerivative()\n        a2 = AerodynamicDerivative()\n        a3 = AerodynamicDerivative()\n        a4 = AerodynamicDerivative()\n        a5 = AerodynamicDerivative()\n        a6 = AerodynamicDerivative()\n            \n        if motion_type ==0:\n            row = 0\n            col = 0\n            p1 = AerodynamicDerivative(\"P_1^*\", reduced_velocities,normalized_coefficient_matrix[row,col,:,0],normalized_coefficient_matrix[row,col,:,1],normalized_coefficient_matrix[row,col,:,2],normalized_coefficient_matrix[row,col,:,3],mean_wind_speeds,frequencies_of_motion)\n            col = 1\n            h5 = AerodynamicDerivative(\"H_5^*\", reduced_velocities,normalized_coefficient_matrix[row,col,:,0],normalized_coefficient_matrix[row,col,:,1],normalized_coefficient_matrix[row,col,:,2],normalized_coefficient_matrix[row,col,:,3],mean_wind_speeds,frequencies_of_motion)\n            col = 2\n            a5 = AerodynamicDerivative(\"A_5^*\", reduced_velocities,normalized_coefficient_matrix[row,col,:,0],normalized_coefficient_matrix[row,col,:,1],normalized_coefficient_matrix[row,col,:,2],normalized_coefficient_matrix[row,col,:,3],mean_wind_speeds,frequencies_of_motion)\n           \n            row = 1\n            col = 0\n            p4 = AerodynamicDerivative(\"P_4^*\",reduced_velocities,normalized_coefficient_matrix[row,col,:,0],normalized_coefficient_matrix[row,col,:,1],normalized_coefficient_matrix[row,col,:,2],normalized_coefficient_matrix[row,col,:,3],mean_wind_speeds,frequencies_of_motion)\n            col = 1\n            h6 = AerodynamicDerivative(\"H_6^*\",reduced_velocities,normalized_coefficient_matrix[row,col,:,0],normalized_coefficient_matrix[row,col,:,1],normalized_coefficient_matrix[row,col,:,2],normalized_coefficient_matrix[row,col,:,3],mean_wind_speeds,frequencies_of_motion)\n            col = 2\n            a6 = AerodynamicDerivative(\"A_6^*\",reduced_velocities,normalized_coefficient_matrix[row,col,:,0],normalized_coefficient_matrix[row,col,:,1],normalized_coefficient_matrix[row,col,:,2],normalized_coefficient_matrix[row,col,:,3],mean_wind_speeds,frequencies_of_motion)\n        elif motion_type ==1:\n            row = 0\n            col = 0\n            p5 = AerodynamicDerivative(\"P_5^*\",reduced_velocities,normalized_coefficient_matrix[row,col,:,0],normalized_coefficient_matrix[row,col,:,1],normalized_coefficient_matrix[row,col,:,2],normalized_coefficient_matrix[row,col,:,3],mean_wind_speeds,frequencies_of_motion)\n            col = 1\n            h1 = AerodynamicDerivative(\"H_1^*\",reduced_velocities,normalized_coefficient_matrix[row,col,:,0],normalized_coefficient_matrix[row,col,:,1],normalized_coefficient_matrix[row,col,:,2],normalized_coefficient_matrix[row,col,:,3],mean_wind_speeds,frequencies_of_motion)\n            col = 2\n            a1 = AerodynamicDerivative(\"A_1^*\",reduced_velocities,normalized_coefficient_matrix[row,col,:,0],normalized_coefficient_matrix[row,col,:,1],normalized_coefficient_matrix[row,col,:,2],normalized_coefficient_matrix[row,col,:,3],mean_wind_speeds,frequencies_of_motion)\n           \n            row = 1\n            col = 0\n            p6 = AerodynamicDerivative(\"P_6^*\",reduced_velocities,normalized_coefficient_matrix[row,col,:,0],normalized_coefficient_matrix[row,col,:,1],normalized_coefficient_matrix[row,col,:,2],normalized_coefficient_matrix[row,col,:,3],mean_wind_speeds,frequencies_of_motion)\n            col = 1\n            h4 = AerodynamicDerivative(\"H_4^*\",reduced_velocities,normalized_coefficient_matrix[row,col,:,0],normalized_coefficient_matrix[row,col,:,1],normalized_coefficient_matrix[row,col,:,2],normalized_coefficient_matrix[row,col,:,3],mean_wind_speeds,frequencies_of_motion)\n            col = 2\n            a4 = AerodynamicDerivative(\"A_4^*\",reduced_velocities,normalized_coefficient_matrix[row,col,:,0],normalized_coefficient_matrix[row,col,:,1],normalized_coefficient_matrix[row,col,:,2],normalized_coefficient_matrix[row,col,:,3],mean_wind_speeds,frequencies_of_motion)\n        elif motion_type ==2:\n            row = 0\n            col = 0\n            p2 = AerodynamicDerivative(\"P_2^*\",reduced_velocities,normalized_coefficient_matrix[row,col,:,0],normalized_coefficient_matrix[row,col,:,1],normalized_coefficient_matrix[row,col,:,2],normalized_coefficient_matrix[row,col,:,3],mean_wind_speeds,frequencies_of_motion)\n            col = 1\n            h2 = AerodynamicDerivative(\"H_2^*\",reduced_velocities,normalized_coefficient_matrix[row,col,:,0],normalized_coefficient_matrix[row,col,:,1],normalized_coefficient_matrix[row,col,:,2],normalized_coefficient_matrix[row,col,:,3],mean_wind_speeds,frequencies_of_motion)\n            col = 2\n            a2 = AerodynamicDerivative(\"A_2^*\",reduced_velocities,normalized_coefficient_matrix[row,col,:,0],normalized_coefficient_matrix[row,col,:,1],normalized_coefficient_matrix[row,col,:,2],normalized_coefficient_matrix[row,col,:,3],mean_wind_speeds,frequencies_of_motion)\n           \n            row = 1\n            col = 0\n            p3 = AerodynamicDerivative(\"P_3^*\",reduced_velocities,normalized_coefficient_matrix[row,col,:,0],normalized_coefficient_matrix[row,col,:,1],normalized_coefficient_matrix[row,col,:,2],normalized_coefficient_matrix[row,col,:,3],mean_wind_speeds,frequencies_of_motion)\n            col = 1\n            h3 = AerodynamicDerivative(\"H_3^*\",reduced_velocities,normalized_coefficient_matrix[row,col,:,0],normalized_coefficient_matrix[row,col,:,1],normalized_coefficient_matrix[row,col,:,2],normalized_coefficient_matrix[row,col,:,3],mean_wind_speeds,frequencies_of_motion)\n            col = 2\n            a3 = AerodynamicDerivative(\"A_3^*\",reduced_velocities,normalized_coefficient_matrix[row,col,:,0],normalized_coefficient_matrix[row,col,:,1],normalized_coefficient_matrix[row,col,:,2],normalized_coefficient_matrix[row,col,:,3],mean_wind_speeds,frequencies_of_motion)\n              \n        return cls(p1, p2, p3, p4, p5, p6, h1, h2, h3, h4, h5, h6, a1, a2, a3, a4, a5, a6), model_prediction, experiment_in_wind_still_air_forces_removed\n    \n    @classmethod\n    def from_Theodorsen(cls,vred):\n        \n        vred[vred==0] = 1.0e-10\n        \n        k = 0.5/np.abs(vred)\n\n        j0 = spspes.jv(0,k)\n        j1 = spspes.jv(1,k)\n        y0 = spspes.yn(0,k)\n        y1 = spspes.yn(1,k)\n\n        a = j1 + y0\n        b = y1-j0\n        c = a**2 + b**2\n\n        f = (j1*a + y1*b)/c\n        g = -(j1*j0 + y1*y0)/c\n        \n        h1_value = -2*np.pi*f*np.abs(vred)\n        h2_value = np.pi/2*(1+f+4*g*np.abs(vred))*np.abs(vred)\n        h3_value = 2*np.pi*(f*np.abs(vred)-g/4)*np.abs(vred)\n        h4_value = np.pi/2*(1+4*g*np.abs(vred))\n        \n        \n        a1_value = -np.pi/2*f*np.abs(vred)\n        a2_value = -np.pi/8*(1-f-4*g*np.abs(vred))*np.abs(vred)\n        a3_value = np.pi/2*(f*np.abs(vred)-g/4)*np.abs(vred)\n        a4_value = np.pi/2*g*np.abs(vred)\n        \n        p1 = AerodynamicDerivative(\"P_1^*\",vred, vred*0, vred*0, vred*0, vred*0)\n        p2 = AerodynamicDerivative(\"P_2^*\",vred, vred*0, vred*0, vred*0, vred*0)\n        p3 = AerodynamicDerivative(\"P_3^*\",vred, vred*0, vred*0, vred*0, vred*0)\n        p4 = AerodynamicDerivative(\"P_4^*\",vred, vred*0, vred*0, vred*0, vred*0)\n        p5 = AerodynamicDerivative(\"P_5^*\",vred, vred*0, vred*0, vred*0, vred*0)\n        p6 = AerodynamicDerivative(\"P_6^*\",vred, vred*0, vred*0, vred*0, vred*0)\n           \n        h1 = AerodynamicDerivative(\"H_1^*\",vred, h1_value/2, h1_value/2, vred*0, vred*0)\n        h2 = AerodynamicDerivative(\"H_2^*\",vred, h2_value/2, h2_value/2, vred*0, vred*0)\n        h3 = AerodynamicDerivative(\"H_3^*\",vred, h3_value/2, h3_value/2, vred*0, vred*0)\n        h4 = AerodynamicDerivative(\"H_4^*\",vred, h4_value/2, h4_value/2, vred*0, vred*0)\n        h5 = AerodynamicDerivative(\"H_5^*\",vred, vred*0, vred*0, vred*0, vred*0)\n        h6 = AerodynamicDerivative(\"H_6^*\",vred, vred*0, vred*0, vred*0, vred*0)\n      \n        a1 = AerodynamicDerivative(\"A_1^*\",vred, a1_value/2, a1_value/2, vred*0, vred*0)\n        a2 = AerodynamicDerivative(\"A_2^*\",vred, a2_value/2, a2_value/2, vred*0, vred*0)\n        a3 = AerodynamicDerivative(\"A_3^*\",vred, a3_value/2, a3_value/2, vred*0, vred*0)\n        a4 = AerodynamicDerivative(\"A_4^*\",vred, a4_value/2, a4_value/2, vred*0, vred*0)\n        a5 = AerodynamicDerivative(\"A_5^*\",vred, vred*0, vred*0, vred*0, vred*0)\n        a6 = AerodynamicDerivative(\"A_6^*\",vred, vred*0, vred*0, vred*0, vred*0)\n        \n\n                \n        return cls(p1, p2, p3, p4, p5, p6, h1, h2, h3, h4, h5, h6, a1, a2, a3, a4, a5, a6)\n    \n    @classmethod\n    def from_poly_k(cls,poly_k,k_range, vred):\n        vred[vred==0] = 1.0e-10\n        uit_step = lambda k,kc: 1./(1 + np.exp(-2*20*(k-kc)))\n        fit = lambda p,k,k1c,k2c : np.polyval(p,k)*uit_step(k,k1c)*(1-uit_step(k,k2c)) + np.polyval(p,k1c)*(1-uit_step(k,k1c)) + np.polyval(p,k2c)*(uit_step(k,k2c))\n        \n        damping_ad = np.array([True, True, False, False, True, False,    True, True, False, False, True, False, True, True, False, False, True, False   ])\n        labels = [\"P_1^*\", \"P_2^*\", \"P_3^*\", \"P_4^*\", \"P_5^*\", \"P_6^*\",  \"H_1^*\", \"H_2^*\", \"H_3^*\", \"H_4^*\", \"H_5^*\", \"H_6^*\",     \"A_1^*\", \"A_2^*\", \"A_3^*\", \"A_4^*\", \"A_5^*\", \"A_6^*\"]\n        ads = []\n        for k in range(18):\n                      \n            if damping_ad[k] == True:\n                ad_value = np.abs(vred)*fit(poly_k[k,:],np.abs(1/vred),k_range[k,0],k_range[k,1])\n            else:\n                ad_value = np.abs(vred)**2*fit(poly_k[k,:],np.abs(1/vred),k_range[k,0],k_range[k,1])\n                \n            ads.append(AerodynamicDerivative(labels[k],vred,ad_value/2 , ad_value/2 , vred*0, vred*0))\n            \n             \n        return cls(ads[0], ads[1], ads[2], ads[3], ads[4], ads[5], ads[6], ads[7], ads[8], ads[9], ads[10], ads[11], ads[12], ads[13], ads[14], ads[15], ads[16], ads[17])\n    \n      \n    \n    def append(self,ads):\n        \"\"\" appends and instance of AerodynamicDerivatives to self\n        \n        Arguments:\n        ----------\n        ads         : an instance of the class AerodynamicDerivatives\n        \n        \"\"\"\n        objs1 = [self.p1, self.p2, self.p3, self.p4, self.p5, self.p6, self.h1, self.h2, self.h3, self.h4, self.h5, self.h6, self.a1, self.a2, self.a3, self.a4, self.a5, self.a6 ]\n        objs2 = [ads.p1, ads.p2, ads.p3, ads.p4, ads.p5, ads.p6, ads.h1, ads.h2, ads.h3, ads.h4, ads.h5, ads.h6, ads.a1, ads.a2, ads.a3, ads.a4, ads.a5, ads.a6 ]\n        \n        for k in range(len(objs1)):\n            objs1[k].ad_load_cell_1 = np.append(objs1[k].ad_load_cell_1,objs2[k].ad_load_cell_1)\n            objs1[k].ad_load_cell_2 = np.append(objs1[k].ad_load_cell_2,objs2[k].ad_load_cell_2) \n            objs1[k].ad_load_cell_3 = np.append(objs1[k].ad_load_cell_3,objs2[k].ad_load_cell_3) \n            objs1[k].ad_load_cell_4 = np.append(objs1[k].ad_load_cell_4,objs2[k].ad_load_cell_4) \n            \n            objs1[k].frequencies = np.append(objs1[k].frequencies,objs2[k].frequencies) \n            objs1[k].mean_wind_speeds = np.append(objs1[k].mean_wind_speeds,objs2[k].mean_wind_speeds) \n            objs1[k].reduced_velocities = np.append(objs1[k].reduced_velocities,objs2[k].reduced_velocities) \n            \n    @property\n    def ad_matrix(self):\n        \"\"\" Returns a matrix of aerodynamic derivatives and reduced velocities\n        \n        Returns\n        -------\n        ads : float\n        \n        a matrix of aerodynamic derivatives [18 x N reduced velocities]\n        \n        vreds : float\n        \n        a matrix of reduced velocities [18 x N reduced velocities]\n        \n        \n        \n        \"\"\"\n        ads = np.zeros((18,self.p1.reduced_velocities.shape[0]))\n        vreds = np.zeros((18,self.p1.reduced_velocities.shape[0]))\n        ads[0,:] = self.p1.value\n        ads[1,:] = self.p2.value\n        ads[2,:] = self.p3.value\n        ads[3,:] = self.p4.value\n        ads[4,:] = self.p5.value\n        ads[5,:] = self.p6.value\n\n        ads[6,:] = self.h1.value\n        ads[7,:] = self.h2.value\n        ads[8,:] = self.h3.value\n        ads[9,:] = self.h4.value\n        ads[10,:] = self.h5.value\n        ads[11,:] = self.h6.value\n        \n        ads[12,:] = self.a1.value\n        ads[13,:] = self.a2.value\n        ads[14,:] = self.a3.value\n        ads[15,:] = self.a4.value\n        ads[16,:] = self.a5.value\n        ads[17,:] = self.a6.value\n        \n        vreds[0,:] = self.p1.reduced_velocities\n        vreds[1,:] = self.p2.reduced_velocities\n        vreds[2,:] = self.p3.reduced_velocities\n        vreds[3,:] = self.p4.reduced_velocities\n        vreds[4,:] = self.p5.reduced_velocities\n        vreds[5,:] = self.p6.reduced_velocities\n\n        vreds[6,:] = self.h1.reduced_velocities\n        vreds[7,:] = self.h2.reduced_velocities\n        vreds[8,:] = self.h3.reduced_velocities\n        vreds[9,:] = self.h4.reduced_velocities\n        vreds[10,:] = self.h5.reduced_velocities\n        vreds[11,:] = self.h6.reduced_velocities\n        \n        vreds[12,:] = self.a1.reduced_velocities\n        vreds[13,:] = self.a2.reduced_velocities\n        vreds[14,:] = self.a3.reduced_velocities\n        vreds[15,:] = self.a4.reduced_velocities\n        vreds[16,:] = self.a5.reduced_velocities\n        vreds[17,:] = self.a6.reduced_velocities\n        \n        return ads, vreds\n    \n    \n    def frf_mat(self,mean_wind_velocity = 1.0, section_width = 1.0, air_density = 1.25):\n        \n        \n        frf_mat = np.zeros((3,3,len(self.p1.reduced_velocities)),dtype=complex)\n        \n        frf_mat[0,0,:] = 1/2*air_density*mean_wind_velocity**2 * (1/self.p1.reduced_velocities)**2 * (self.p1.value*1j + self.p4.value)\n        frf_mat[0,1,:] = 1/2*air_density*mean_wind_velocity**2 * (1/self.p5.reduced_velocities)**2 * (self.p5.value*1j + self.p6.value)\n        frf_mat[0,2,:] = 1/2*air_density*mean_wind_velocity**2 * section_width*(1/self.p2.reduced_velocities)**2 * (self.p2.value*1j + self.p3.value)\n        \n        frf_mat[1,0,:] = 1/2*air_density*mean_wind_velocity**2 * (1/self.h5.reduced_velocities)**2 * (self.h5.value*1j + self.h6.value)\n        frf_mat[1,1,:] = 1/2*air_density*mean_wind_velocity**2 * (1/self.h1.reduced_velocities)**2 * (self.h1.value*1j + self.h4.value)\n        frf_mat[1,2,:] = 1/2*air_density*mean_wind_velocity**2 * section_width*(1/self.h3.reduced_velocities)**2 * (self.h2.value*1j + self.h3.value)\n        \n        frf_mat[2,0,:] = 1/2*air_density*mean_wind_velocity**2 * section_width*(1/self.a5.reduced_velocities)**2 * (self.a5.value*1j + self.a6.value)\n        frf_mat[2,1,:] = 1/2*air_density*mean_wind_velocity**2 * section_width*(1/self.a1.reduced_velocities)**2 * (self.a1.value*1j + self.a4.value)\n        frf_mat[2,2,:] = 1/2*air_density*mean_wind_velocity**2 * section_width**2*(1/self.a2.reduced_velocities)**2 * (self.a2.value*1j + self.a3.value)\n        \n        return frf_mat\n    \n\n    def fit_poly_k(self,orders = np.ones(18,dtype=int)*2):\n        ad_matrix, vreds = self.ad_matrix\n        \n        poly_coeff = np.zeros((18,np.max(orders)+1))\n        k_range = np.zeros((18,2))\n        \n        damping_ad = np.array([True, True, False, False, True, False,    True, True, False, False, True, False,  True, True, False, False, True, False   ])\n        \n        \n        for k in range(18):\n            k_range[k,0] = 1/np.max(vreds)\n            k_range[k,1] = 1/np.min(vreds)\n            \n            if damping_ad[k] == True:\n                poly_coeff[k,-orders[k]-1:] = np.polyfit(1/vreds[k,:],1/vreds[k,:]*ad_matrix[k,:],orders[k])\n            elif damping_ad[k] == False:\n                poly_coeff[k,-orders[k]-1:] = np.polyfit(1/vreds[k,:],(1/vreds[k,:])**2*ad_matrix[k,:],orders[k])\n            \n                \n        \n        return poly_coeff, k_range\n    \n    def to_excel(self,section_name, section_height=0, section_width=0, section_length=0):\n        \"\"\"\n        \n\n        Parameters\n        ----------\n        section_name : string\n            section_name\n        section_height : float64, optional\n            Section height. The default is 0.\n        section_width : float64, optional\n            section width. The default is 0.\n        section_length : float 64, optional\n            section length. The default is 0.\n\n        Returns\n        -------\n        None.\n\n        \"\"\"\n        \n        ad_value = pd.DataFrame({\"P_1\": self.p1.value,\n                                 \"P_2\": self.p2.value,\n                                 \"P_3\": self.p3.value,\n                                 \"P_4\": self.p4.value,\n                                 \"P_5\": self.p5.value,\n                                 \"P_6\": self.p6.value,\n\n                                 \"H_1\": self.h1.value,\n                                 \"H_2\": self.h2.value,\n                                 \"H_3\": self.h3.value,\n                                 \"H_4\": self.h4.value,\n                                 \"H_5\": self.h5.value,\n                                 \"H_6\": self.h6.value,\n\n                                 \"A_1\": self.a1.value,\n                                 \"A_2\": self.a2.value,\n                                 \"A_3\": self.a3.value,\n                                 \"A_4\": self.a4.value,\n                                 \"A_5\": self.a5.value,\n                                 \"A_6\": self.a6.value,\n                                 })\n\n        ad_reduced_velocity = pd.DataFrame({\"P_1\": self.p1.reduced_velocities,\n                                            \"P_2\": self.p2.reduced_velocities,\n                                            \"P_3\": self.p3.reduced_velocities,\n                                            \"P_4\": self.p4.reduced_velocities,\n                                            \"P_5\": self.p5.reduced_velocities,\n                                            \"P_6\": self.p6.reduced_velocities,\n\n                                            \"H_1\": self.h1.reduced_velocities,\n                                            \"H_2\": self.h2.reduced_velocities,\n                                            \"H_3\": self.h3.reduced_velocities,\n                                            \"H_4\": self.h4.reduced_velocities,\n                                            \"H_5\": self.h5.reduced_velocities,\n                                            \"H_6\": self.h6.reduced_velocities,\n\n                                            \"A_1\": self.a1.reduced_velocities,\n                                            \"A_2\": self.a2.reduced_velocities,\n                                            \"A_3\": self.a3.reduced_velocities,\n                                            \"A_4\": self.a4.reduced_velocities,\n                                            \"A_5\": self.a5.reduced_velocities,\n                                            \"A_6\": self.a6.reduced_velocities,\n                                            })\n\n        ad_mean_wind_speeds = pd.DataFrame({\"P_1\": self.p1.mean_wind_speeds,\n                                            \"P_2\": self.p2.mean_wind_speeds,\n                                            \"P_3\": self.p3.mean_wind_speeds,\n                                            \"P_4\": self.p4.mean_wind_speeds,\n                                            \"P_5\": self.p5.mean_wind_speeds,\n                                            \"P_6\": self.p6.mean_wind_speeds,\n\n                                            \"H_1\": self.h1.mean_wind_speeds,\n                                            \"H_2\": self.h2.mean_wind_speeds,\n                                            \"H_3\": self.h3.mean_wind_speeds,\n                                            \"H_4\": self.h4.mean_wind_speeds,\n                                            \"H_5\": self.h5.mean_wind_speeds,\n                                            \"H_6\": self.h6.mean_wind_speeds,\n\n                                            \"A_1\": self.a1.mean_wind_speeds,\n                                            \"A_2\": self.a2.mean_wind_speeds,\n                                            \"A_3\": self.a3.mean_wind_speeds,\n                                            \"A_4\": self.a4.mean_wind_speeds,\n                                            \"A_5\": self.a5.mean_wind_speeds,\n                                            \"A_6\": self.a6.mean_wind_speeds,\n                                            })\n\n        geometry = pd.DataFrame({\"D\": [section_height],\n                                 \"B\": [section_width],\n                                 \"L\": [section_length]\n                                 })\n\n        with pd.ExcelWriter(\"ADs_\" + section_name + '.xlsx') as writer:\n            geometry.to_excel(writer, sheet_name=\"Dim section model\")\n            ad_value.to_excel(writer, sheet_name='Aerodynamic derivatives')\n            ad_reduced_velocity.to_excel(\n                writer, sheet_name='Reduced velocities')\n            ad_mean_wind_speeds.to_excel(\n                writer, sheet_name='Mean wind velocity')\n\n\n\n        \n        \n        \n            \n    def plot(self, fig_damping=[],fig_stiffness=[],conv='normal', mode='total'):\n        \n        \"\"\" plots all aerodynamic derivatives\n        \n        Arguments:\n        ----------\n        fig_damping     : figure object\n        \n        fig_stiffness   : figure object\n        \n        conv            : normal or zasso\n        \n        mode            : total, all or decks        \n        \n        \"\"\"\n        \n        # Make figure objects if not given\n        if bool(fig_damping) == False:\n            fig_damping = plt.figure()\n            for k in range(9):\n                fig_damping.add_subplot(3,3,k+1)\n        \n        if bool(fig_stiffness) == False:\n            fig_stiffness = plt.figure()\n            for k in range(9):\n                fig_stiffness.add_subplot(3,3,k+1)\n        \n        \n        axs_damping = fig_damping.get_axes()\n#        \n        self.p1.plot(mode=mode, conv=conv, ax=axs_damping[0])\n        self.p5.plot(mode=mode, conv=conv, ax=axs_damping[1])\n        self.p2.plot(mode=mode, conv=conv, ax=axs_damping[2])\n        \n        self.h5.plot(mode=mode, conv=conv, ax=axs_damping[3])\n        self.h1.plot(mode=mode, conv=conv, ax=axs_damping[4])\n        self.h2.plot(mode=mode, conv=conv, ax=axs_damping[5])\n        \n        self.a5.plot(mode=mode, conv=conv, ax=axs_damping[6])\n        self.a1.plot(mode=mode, conv=conv, ax=axs_damping[7])\n        self.a2.plot(mode=mode, conv=conv, ax=axs_damping[8])\n        \n        axs_stiffness = fig_stiffness.get_axes()\n        self.p4.plot(mode=mode, conv=conv, ax=axs_stiffness[0])\n        self.p6.plot(mode=mode, conv=conv, ax=axs_stiffness[1])\n        self.p3.plot(mode=mode, conv=conv, ax=axs_stiffness[2])\n        \n        self.h6.plot(mode=mode, conv=conv, ax=axs_stiffness[3])\n        self.h4.plot(mode=mode, conv=conv, ax=axs_stiffness[4])\n        self.h3.plot(mode=mode, conv=conv, ax=axs_stiffness[5])\n        \n        self.a6.plot(mode=mode, conv=conv, ax=axs_stiffness[6])\n        self.a4.plot(mode=mode, conv=conv, ax=axs_stiffness[7])\n        self.a3.plot(mode=mode, conv=conv, ax=axs_stiffness[8])\n        \n        \n        \n        for k in range(6):\n            axs_damping[k].set_xlabel(\"\")\n            axs_stiffness[k].set_xlabel(\"\")\n        \n        fig_damping.set_size_inches(20/2.54,15/2.54)\n        fig_stiffness.set_size_inches(20/2.54,15/2.54)\n        \n        fig_damping.tight_layout()\n        fig_stiffness.tight_layout()\n         \n      \n", "meta": {"hexsha": "ac4ecb91ed48afcb8b54748792b8cc45ed1bf81a", "size": 40025, "ext": "py", "lang": "Python", "max_stars_repo_path": "w3t/_ads.py", "max_stars_repo_name": "oiseth/w3tp", "max_stars_repo_head_hexsha": "548bca4514196d672055a0317a51d378a3ef9f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-15T09:43:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T09:43:28.000Z", "max_issues_repo_path": "w3t/_ads.py", "max_issues_repo_name": "oiseth/w3tp", "max_issues_repo_head_hexsha": "548bca4514196d672055a0317a51d378a3ef9f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "w3t/_ads.py", "max_forks_repo_name": "oiseth/w3tp", "max_forks_repo_head_hexsha": "548bca4514196d672055a0317a51d378a3ef9f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.7204968944, "max_line_length": 303, "alphanum_fraction": 0.5813866334, "include": true, "reason": "import numpy,from scipy", "num_tokens": 10448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.1857373694606667}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport collections\n\nfrom py4xs.data2d import Data2d\nfrom py4xs.mask import Mask\nfrom py4xs.utils import common_name,smooth\n\nimport os\nimport sys\nimport time\nimport copy\nimport itertools as it\nimport multiprocessing as mp\n\n# this is the ratio between protein average denstiy and water density\n# it is assumed to be a constant but in reality depends on the specific portein\n# see Fischer et.al.  Protein Sci. 2004 October; 13(10): 2825-2828\nPROTEIN_WATER_DENSITY_RATIO = 1.35\n\n# Each Data1d corresponds to one single scattering pattern\n# The intensity is normalized based on\n#     (1) beam intensity through the beam stop, as in prvious version\n#  or (2) WAXS intensity (water scattering)\n#  or (3) an externally dtermined value\n# The intensity can be further normalized a reference trans value, so\n#   that different sets can be compared.\n# Data1d sets (must share the same qgrid) can be merged: e.g. SAXS and WAXS\n# Background subtraction and flat field correction are also supported\n\nTRANS_EXTERNAL = 0\nTRANS_FROM_BEAM_CENTER = 1\nTRANS_FROM_WAXS = 2\n\nfrom enum import Enum\n# removed from_beam_center since it is really external\n# also it is difficult to keep track when merging multiple detectors\nclass trans_mode(Enum):\n    external = 0\n    from_waxs = 2\n\n# trans_mode=TRANS_FROM_BEAM_CENTER\n# this works if there is a semi-transparent beam stop\nBEAM_SIZE_hW = 5\nBEAM_SIZE_hH = 4\n\n# this is the global setting\nTRANS_MODE = trans_mode.from_waxs\n# this is the minimum intensity to be used for trans calculations\nWAXS_THRESH = 10\n\n\n# this is the scaling factor for indivudual curves that belong to the same sample\n# they are offset for clarity in the plots\nVOFFSET = 1.5\n\nfont_size_list = ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large']\ndef get_font_size(size_index):\n    \"\"\" \"medium\" has size_index of 0\n        the size_index is negative for smaller fonts and possitive for larger ones  \n    \"\"\"\n    if size_index in font_size_list:\n        i = font_size_list.index(size_index)\n    else:\n        i = int(size_index)+3\n        if i<0:\n            i = 0\n        elif i>=len(font_size_list):\n            i = len(font_size_list)-1\n    return i-3,font_size_list[i]\n        \nclass Data1d:\n    def __init__(self, transMode=None):\n        self.comments = \"\"\n        self.label = \"data\"\n        self.overlaps = []\n        self.raw_data = {}\n        self.timestamp = None\n        self.trans_w = -1\n        self.trans_e = -1\n        self.trans = -1\n        self.transMode = transMode\n        \n    def load_from_2D(self, image, exp_para, qgrid, pre_process=None, flat_cor=None,\n                     mask=None, save_ave=False, debug=False, label=None, dtype=None):\n        \"\"\"\n        image: a filename, or a Data2d instance, or a numpy array\n        qgrid: for the 1D data\n        exp_para: ExpPara\n        mask: no longer used, extract from exp_para\n        \"\"\"\n        self.qgrid = qgrid\n        mask = exp_para.mask\n\n        if debug==True:\n            print(\"loading data from 2D image: \", label)\n    \n        if isinstance(image, Data2d):\n            d2 = image\n        else:\n            d2 = Data2d(image, exp=exp_para, dtype=dtype)\n            self.timestamp = d2.timestamp\n            self.label = d2.label\n            self.timestamp = d2.timestamp\n            \n        if label is not None:\n            self.label = label\n            \n        # place holder for pre-processing, to deal with things like \n        # dark current, flat field, and dezinger corrections on the 2D data\n        if pre_process is not None:\n            pre_process(d2.data)\n        \n        cor_factor = exp_para.FSA*exp_para.FPol\n        if flat_cor is not None:\n            cor_factor *= flat_cor    # for rescuing data with incorrect flat field at the time of collection\n        self.data,self.err = d2.conv_Iq(qgrid, mask, cor_factor = cor_factor)  \n\n        if isinstance(image, np.ndarray):\n            del d2      # d2 is only used temporarily\n        \n        if save_ave and isinstance(image, str):\n            self.save(image + \".ave\", debug=debug)     \n        \n\n    def set_trans(self, transMode=None, trans=-1, ref_trans=-1,\n                  calc_water_peak=False, q_start=1.85, q_end=2.15, debug=False):\n        \"\"\"\n        normalize intensity, from trans to ref_trans\n        trans can be either from the beam center/beam stop or water scattering\n        sometimes the data may require both measures of transmitted intensity\n        \n        this operation should be performed after SAXS/WAXS merge, because\n          1. SAXS and WAXS should have the same trans\n          2. if trans_mode is TRNAS_FROM_WAXS, the trans value needs to be calculated from WAXS data\n        \n        \"\"\"\n        if transMode is None and self.transMode is not None:\n            transMode = self.transMode\n        else:\n            assert(isinstance(transMode, trans_mode))\n            self.transMode = transMode\n        if self.transMode==trans_mode.from_waxs or calc_water_peak:\n            # get trans for the near the maximum in the WAXS data\n            # for solution scattering, hopefully this reflect the intensity of water scattering\n            idx = (self.qgrid > q_start) & (self.qgrid < q_end)  # & (self.data>0.5*np.max(self.data))\n            if len(self.qgrid[idx]) < 5:\n                print(\"not enough data points under the water peak, consider using a different trans_mode.\")\n                #raise Exception()\n            \n            # trying to narrow down the peak range turns out to be a bad idea\n            # the width then could vary between datasets, creating artificial fluctuation in trans \n            #idx1 = idx & (self.data >= 0.95*np.max(self.data[idx]))\n\n            if (self.data[idx]<WAXS_THRESH).all() and debug!='quiet':\n                print(\"the data points for trans calculation are below WAXS_THRESH: \", \n                      np.max(self.data[idx]), WAXS_THRESH)                \n            self.trans_w = np.sum(self.data[idx])\n            if self.transMode==trans_mode.from_waxs:\n                self.trans = self.trans_w \n            qavg = np.average(self.qgrid[idx])\n            if self.trans_w<1.0:\n                print(f'caluclated trans is {self.trans_w}, setting it artifically to WAXS_THRESH.')\n                self.trans_w = WAXS_THRESH\n            if debug==True:\n                print(\"using data near the high q end (q~%f)\" % qavg, end=' ')\n            self.comments += \"# transmitted beam intensity from WAXS (q~%.2f)\" % qavg\n        if self.transMode==trans_mode.external and trans>=0: \n            # if the trans value is specified, by definition transMode should be external\n            # if trans=-1, it is not meant to be the value to be set\n            #if trans<0:\n            #    print(f\"Warning: {trans} is not a valid value for transmitted intensity.\")\n            #    trans = 0\n            self.comments += f\"# transmitted beam intensity given externally: {trans}\"\n            self.trans_e = trans\n            self.trans = trans\n            #if self.transMode==trans_mode.external:\n            #    self.trans = trans\n\n        self.comments += \": %f \\n\" % self.trans\n        if debug==True:\n            print(\"trans for %s set to %f\" % (self.label, self.trans))\n\n        if ref_trans > 0:\n            if self.trans<0:\n                print(f\"cannot normalize intensity since data1d does not have a valid trans value: {self.trans}\")\n            self.comments += \"# scattering intensity normalized to ref_trans = %f \\n\" % ref_trans\n            self.data *= ref_trans/self.trans\n            self.err *= ref_trans/self.trans\n            for ov in self.overlaps:\n                ov['raw_data1'] *= ref_trans/self.trans\n                ov['raw_data2'] *= ref_trans/self.trans\n            self.trans_w *= ref_trans/self.trans\n            self.trans_e *= ref_trans/self.trans\n            self.trans = ref_trans\n            if debug==True:\n                print(\"normalized to %f\" % ref_trans)\n\n\n    def avg(self, dsets, weighted=True, qmax_for_weight=0.3, \n            plot_data=False, ax=None, debug=False, fontsize='large'):\n        \"\"\"\n        dsets is a collection of Data1d\n        weighted:\n            if False \n                the dsets are simply averaged together \n                errorbar is increased if there are discrepencies between individual values?? \n            otherwise \n                weight should contain a list of weight factors, corresponding to each dset\n                each dset is first scaled by the \n                a weighted average (smaller errorbar has higher weight) is then performed\n        ax is the Axes to plot the data in\n        TODO: should calculate something like the cross-correlation between sets\n        to evaluate the consistency between them\n        \"\"\"\n        if debug!='quiet':\n            print(\"averaging data with %s: \\n\" % self.label, end=' ')\n        i_fs = get_font_size(fontsize)[0]\n        \n        n = 1\n        if plot_data:\n            if ax is None:\n                plt.figure()\n                plt.subplots_adjust(bottom=0.15)\n                ax = plt.gca()\n            ax.set_xlabel(\"$q (\\AA^{-1})$\", fontsize=get_font_size(i_fs)[1])\n            ax.set_ylabel(\"$I$\", fontsize=get_font_size(i_fs)[1])\n            ax.set_xscale('log')\n            ax.set_yscale('log')\n            idx = (self.data > 0)\n            ax.errorbar(self.qgrid[idx], self.data[idx], self.err[idx], label=self.label)\n            for ov in self.overlaps:\n                ax.plot(ov['q_overlap'], ov['raw_data1'], \"v\")\n                ax.plot(ov['q_overlap'], ov['raw_data2'], \"^\")\n        \n        d0 = copy.deepcopy(self)\n        if len(dsets)==0:\n            return d0\n\n        if weighted:\n            wt = []\n            for d in dsets+[self]:\n                w0 = np.sum(np.fabs(d.data[d.qgrid<qmax_for_weight]))\n                if w0<=0:\n                    raise Exception(f\"weight for averaging <0: {w0}\")\n                wt.append(w0)\n            wt = np.asarray(wt)\n            wt /= wt.max()\n            er2 = (self.err/wt[-1])**2\n            d0.err = 1./er2\n            d0.data = d0.data/er2 \n            if debug==True:\n                print(\"weight factors: \", wt)\n        \n        for i in range(len(dsets)):\n            d1 = dsets[i]\n            if debug==True:\n                print(\"%s \" % d1.label, end=' ')\n            if not (d0.qgrid == d1.qgrid).all():\n                raise Exception(\"\\n1D sets cannot be averaged: qgrid mismatch\")\n\n            d0.trans += d1.trans\n            d0.trans_w += d1.trans_w\n            d0.trans_e += d1.trans_e\n            if weighted:\n                er2 = (d1.err/wt[i])**2\n                d0.err += 1/er2\n                d0.data += d1.data/er2 \n            else:\n                d0.data += d1.data\n                d0.err += d1.err\n\n            #if self.transMode == trans_mode.from_beam_center:\n            #    d0.roi += d1.roi\n            d0.comments += \"# averaged with \\n%s\" % d1.comments.replace(\"# \", \"## \")\n            if plot_data:\n                idx = (d1.data > 0)  # Remove Zeros on plot\n                ax.errorbar(d1.qgrid[idx], d1.data[idx] * VOFFSET ** n, d1.err[idx] * VOFFSET ** n, label=d1.label)\n            for i in range(len(d1.overlaps)):\n                if plot_data:\n                    ax.plot(d1.overlaps[i]['q_overlap'], d1.overlaps[i]['raw_data1'] * VOFFSET ** n, \"v\")\n                    ax.plot(d1.overlaps[i]['q_overlap'], d1.overlaps[i]['raw_data2'] * VOFFSET ** n, \"^\")\n                d0.overlaps[i]['raw_data1'] += d1.overlaps[i]['raw_data1']\n                d0.overlaps[i]['raw_data2'] += d1.overlaps[i]['raw_data2']\n            n += 1\n            d0.label = common_name(d0.label, d1.label)\n\n        d0.trans /= n\n        d0.trans_w /= n\n        d0.trans_e /= n\n        if weighted:\n            d0.data /= d0.err\n            d0.err = 1./np.sqrt(d0.err)\n        else:    \n            d0.data /= n\n            d0.err /= (n*np.sqrt(n))   # should not be just sqrt(n), that would increase err after averaging\n        #if self.transMode == trans_mode.from_beam_center:\n        #    d0.roi /= n\n        for ov in d0.overlaps:\n            ov['raw_data1'] /= n\n            ov['raw_data2'] /= n\n        if debug==True:\n            print(\"\\naveraged set re-named to %s.\" % d0.label)\n\n        if plot_data:\n            # plot the averaged data over each individual curve\n            for i in range(n):\n                if i == 0:\n                    idx = (d0.data > 0)  # Remove Zeros on plot\n                    handles, labels = ax.get_legend_handles_labels()\n                    lbl = \"averaged\" if \"averaged\" not in labels else \"\"\n                    ax.plot(d0.qgrid[idx], d0.data[idx] * VOFFSET ** i, color=\"gray\", lw=2, ls=\"--\", label=lbl)\n                else:\n                    idx = (d0.data > 0)  # Remove Zeros on plot\n                    ax.plot(d0.qgrid[idx], d0.data[idx] * VOFFSET ** i, color=\"gray\", lw=2, ls=\"--\")\n            leg = ax.legend(loc='upper right', frameon=False)\n\n            for t in leg.get_texts():\n                t.set_fontsize(get_font_size(i_fs-2)[1])\n\n        return d0\n\n\n    def bkg_cor(self, dbak, sc_factor=1., plot_data=False, ax=None, \n                inplace=False, check_overlap=False, show_eb=True, debug=False, fontsize='large'):\n        \"\"\"\n        background subtraction\n        \"\"\"\n        dset = None\n        if inplace:\n            dset = self\n        else:\n            dset = copy.deepcopy(self)\n        i_fs = get_font_size(fontsize)[0]\n            \n        if debug==True:\n            print(\"background subtraction: %s - %s\" % (dset.label, dbak.label))\n        if not (dbak.qgrid == dset.qgrid).all():\n            print(\"background subtraction failed: qgrid mismatch\")\n            sys.exit()\n        if dset.trans < 0 or dbak.trans <= 0:\n            print(\"WARNING: trans value not assigned to data or background, assuming normalized intensity.\")\n            sc = 1.\n        else:\n            sc = dset.trans / dbak.trans\n\n        # need to include raw data\n        if plot_data:\n            if ax is None:\n                plt.figure()\n                plt.subplots_adjust(bottom=0.15)\n                ax = plt.gca()\n            ax.set_xlabel(\"$q (\\AA^{-1})$\", fontsize=get_font_size(i_fs)[1])\n            ax.set_ylabel(\"$I$\", fontsize=get_font_size(i_fs)[1])\n            ax.set_xscale('log')\n            ax.set_yscale('log')\n            ax.xaxis.set_tick_params(labelsize=get_font_size(i_fs-1)[1])\n            ax.yaxis.set_tick_params(labelsize=get_font_size(i_fs-1)[1])\n            idx = (dset.data > 0) & (dbak.data > 0)\n            ax.plot(dset.qgrid[idx], dset.data[idx], label=self.label)\n            ax.plot(dbak.qgrid[idx], dbak.data[idx], label=dbak.label)\n            ax.plot(dbak.qgrid[idx], dbak.data[idx] * sc * sc_factor, label=dbak.label + \", scaled\")\n\n        if len(dset.overlaps) != len(dbak.overlaps):\n            if check_overlap:\n                raise Exception(\"Background subtraction failed: overlaps mismatch.\")\n        else:\n            for i in range(len(dset.overlaps)):\n                dset.overlaps[i]['raw_data1'] -= dbak.overlaps[i]['raw_data1'] * sc_factor * sc\n                dset.overlaps[i]['raw_data2'] -= dbak.overlaps[i]['raw_data2'] * sc_factor * sc\n                if plot_data:\n                    ax.plot(dset.overlaps[i]['q_overlap'], dset.overlaps[i]['raw_data1'], \"v\")\n                    ax.plot(dset.overlaps[i]['q_overlap'], dset.overlaps[i]['raw_data2'], \"^\")\n        if plot_data:\n            leg = ax.legend(loc='upper right', frameon=False)\n            for t in leg.get_texts():\n                t.set_fontsize(get_font_size(i_fs-2)[1])\n\n        if debug==True:\n            print(\"using scaling factor of %f\" % (sc * sc_factor))\n        dset.data -= dbak.data * sc * sc_factor\n        dset.err += dbak.err * sc * sc_factor\n        if plot_data:\n            if show_eb:\n                ax.errorbar(dset.qgrid, dset.data, dset.err)\n            else:\n                ax.plot(dset.qgrid, dset.data)\n                \n        dset.comments += \"# background subtraction using the following set, scaled by %f (trans):\\n\" % sc\n        if not sc_factor == 1.:\n            dset.comments += \"# with addtional scaling factor of: %f\\n\" % sc_factor\n        dset.comments += dbak.comments.replace(\"# \", \"## \")\n\n        return dset\n\n    def scale(self, sc):\n        \"\"\"\n        scale the data by factor sc\n        \"\"\"\n        if sc <= 0:\n            print(\"scaling factor is non-positive: %f\" % sc)\n        self.data *= sc\n        self.err *= sc\n        self.trans *= sc\n        if self.trans_w>0:\n            self.trans_w *= sc\n        if self.trans_e>0:\n            self.trans_e *= sc\n        self.comments += \"# data is scaled by %f.\\n\" % sc\n        if len(self.overlaps) != 0:\n            for ov in self.overlaps:\n                ov['raw_data1'] *= sc\n                ov['raw_data2'] *= sc\n                \n        return self\n\n    def merge(self, d1, qmax=-1, qmin=-1, fix_scale=-1, debug=False):\n        \"\"\"\n        combine the data in self and d1\n        scale d1 intensity to match self\n        self and d1 should have the same qgrid\n\n        if qmax or qmin <0\n        simply keep the WAXS data that is beyond qmax for the SAXS data\n        this is useful for utilizing WAXS to normalize intensity but keep SAXS data only\n        \"\"\"\n\n        if debug==True:\n            print(\"merging data: %s and %s ...\" % (self.label, d1.label))\n        if not (d1.qgrid == self.qgrid).all():\n            print(\"merging data sets should have the same qgrid.\")\n            exit()\n\n        # this gives the overlapping region\n        idx = (self.data > 0) & (d1.data > 0)\n\n        if len(self.qgrid[idx]) > 0:\n            qmin0 = min(d1.qgrid[idx])\n            qmax0 = max(self.qgrid[idx])\n            # merge SAXS/WAXS based on intensity in the overlapping region\n            if qmax0 < qmax:\n                qmax = qmax0\n            if qmin0 > qmin:\n                qmin = qmin0\n            idx = (self.qgrid > qmin) & (self.qgrid < qmax)\n            # save the raw data in case needed, e.g. for ploting\n            self.overlaps.append({'q_overlap': self.qgrid[idx],\n                                  'raw_data1': self.data[idx],\n                                  'raw_data2': d1.data[idx]})\n        else:\n            # no overlap\n            # simply stack WAXS data to the high q end of SAXS data\n            qmin = qmax = max(self.qgrid[self.data > 0])\n            self.overlaps.append({'q_overlap': np.empty(0),\n                                  'raw_data1': np.empty(0),\n                                  'raw_data2': np.empty(0)})\n\n        # idx = np.asarray([],dtype=int)\n\n        if len(self.qgrid[idx])==0:\n            if debug!='quiet':\n                print(\"data sets are not overlapping in the given q range.\")\n            if fix_scale < 0:\n                fix_scale = 1\n                if debug!='quiet':\n                    print(\"forcing fix_scale=1.\")\n        elif len(self.qgrid[idx]) < 5 and debug!='quiet':\n            print(\"too few overlapping points: %d\" % len(self.qgrid[idx]))\n\n        if fix_scale > 0:\n            # For a given experimental configuration, the intensity normlization\n            # factor between the SAXS and WAXS should be well-defined. This factor\n            # can be determined using scattering data with siginificant intensity\n            # in the overlapping q-range and applied to all data collected in the\n            # same configuration.\n            sc = fix_scale\n        else:\n            sc = np.linalg.lstsq(np.asmatrix(self.data[idx]).T, np.asmatrix(d1.data[idx]).T)[0]\n            sc = np.trace(sc)\n\n        d1.data /= sc\n        d1.err /= sc\n        if len(self.qgrid[idx]) > 0:\n            if debug==True:\n                print(\"Scaled Overlaps by 1/%f\" % sc)\n            self.overlaps[-1]['raw_data2'] /= sc\n            self.overlaps[-1]['sc'] = sc\n\n        self.label = common_name(self.label, d1.label)\n        if debug==True:\n            print(\"set2 scaled by 1/%f\" % sc)\n            print(\"merged set re-named %s.\" % self.label)\n\n        if len(self.qgrid[idx]) > 0:\n            # averaging using 1/err^2 as weight, maximum likelihood estimator \n            w1 = 1./(self.err[idx]*self.err[idx]) \n            w2 = 1./(d1.err[idx]*d1.err[idx]) \n            self.data[idx] = (w1*self.data[idx] + w2*d1.data[idx]) / (w1+w2)\n            self.err[idx] = np.sqrt((w1/(w1+w2)*self.err[idx])**2 + (w2/(w1+w2)*d1.err[idx])**2)\n        self.data[self.qgrid >= qmax] = d1.data[self.qgrid >= qmax]\n        self.err[self.qgrid >= qmax] = d1.err[self.qgrid >= qmax]\n\n        self.comments += \"# merged with the following set by matching intensity within (%.4f, %.4f),\" % (qmin, qmax)\n        self.comments += \" scaled by %f\\n\" % sc\n        self.comments += d1.comments.replace(\"# \", \"## \")\n\n    def plot_Guinier(self, qs=0, qe=10, rg=15, fix_qe=False, scale_wabs=-1,\n                     ax=None, no_plot=False, fontsize=\"large\"):\n        \"\"\" do Gunier plot, estimate Rg automatically\n        qs specify the lower end of the q-range to perform the fit in\n        rg is the optinal initial estimate\n        if fix_qe==1, qe defined the end of the region to perform the fit\n        \"\"\"\n        idx = (self.data > 0)\n        i_fs = get_font_size(fontsize)[0]\n        # print self.data\n\n        scale = 1.0\n        if scale_wabs>0:\n            assert(self.trans_w>0)\n            scale *= scale_wabs/self.trans_w\n\n        if no_plot==False:\n            if ax is None:\n                ax = plt.gca()\n            ax.set_xscale('linear')\n            ax.set_yscale('log')\n            ax.errorbar(self.qgrid[idx]**2, self.data[idx]*scale, self.err[idx]*scale)\n\n        cnt = 0\n        t = self.qgrid[self.data > 0][0]\n        if qs < t: qs = t\n        while cnt < 10:\n            if (not fix_qe) and qe > 1.3/rg and 1.3/rg > qs+0.004: qe = 1.3/rg\n            td = np.vstack((self.qgrid, self.data))\n            td = td[:, td[0, :] >= qs]\n            td = td[:, td[0, :] <= qe]\n            td[0, :] = td[0, :] * td[0, :]\n            td[1, :] = np.log(td[1, :])\n            rg, i0 = np.polyfit(td[0, :], td[1, :], 1)\n            i0 = np.exp(i0)\n            if rg<0:\n                rg = np.sqrt(-rg * 3.)\n            else:\n                rg = 1e-6   # \n                print(\"likely strong inter-particle interaction ...\")\n                break\n            cnt += 1\n            # print i0, rg\n        td[1, :] = i0 * np.exp(-td[0, :]*rg*rg/3.)\n        n1 = len(self.qgrid[self.qgrid<qs])\n        n2 = len(self.qgrid)-len(self.qgrid[self.qgrid>qe])\n        fit_range = [n1,n2]\n        i0*=scale\n        \n        if no_plot==False and rg>0.1:\n            #ax.tick_params(axis='y', labelleft=False)    \n            ax.plot([td[0, 0], td[0, -1]], [td[1, 0]*scale, td[1, -1]*scale], \"ro\")\n            ax.plot(self.qgrid**2, i0*np.exp(-(self.qgrid*rg)**2/3))\n            ax.set_ylabel(\"$I$\", fontsize=get_font_size(i_fs)[1])\n            ax.set_xlabel(\"$q^2 (\\AA^{-2})$\", fontsize=get_font_size(i_fs)[1])\n            ax.xaxis.set_tick_params(labelsize=get_font_size(i_fs-1)[1])\n            ax.yaxis.set_tick_params(labelsize=get_font_size(i_fs-1)[1])\n            # plt.subplots_adjust(bottom=0.15)\n            ax.set_xlim(0, qe**2*1.2)\n            #ax.autoscale_view(tight=True, scalex=False, scaley=True)\n            if i0>0:\n                ax.set_ylim(top=i0*2, bottom=i0*np.exp(-(qe*rg)**2/3)/2)\n        # print \"I0=%f, Rg=%f\" % (i0,rg)\n        return (i0, rg, fit_range) # include fit range to be more compatible with ATSAS\n\n    def plot_pr(self, i0, rg, qmax=5., dmax=200., ax=None, fontsize='large'):\n        \"\"\" calculate p(r) function\n        use the given i0 and rg value to fill in the low q part of the gap in data\n        truncate the high q end at qmax\n        \"\"\"\n        i_fs = get_font_size(fontsize)[0]\n        if ax is None:\n            ax = plt.gca()\n        ax.set_xscale('linear')\n        ax.set_yscale('linear')\n\n        if self.qgrid[-1] < qmax: qmax = self.qgrid[-1]\n        tqgrid = np.arange(0, qmax, qmax / len(self.qgrid))\n        tint = np.interp(tqgrid, self.qgrid, self.data)\n\n        tint[tqgrid * rg < 1.] = i0 * np.exp(-(tqgrid[tqgrid * rg < 1.] * rg) ** 2 / 3.)\n        # tint -= tint[-10:].sum()/10\n        # Hanning window for reducing fringes in p(r)\n        tw = np.hanning(2 * len(tqgrid) + 1)[len(tqgrid):-1]\n        tint *= tw\n\n        trgrid = np.arange(0, dmax, 1.)\n        kern = np.asmatrix([[rj ** 2 * np.sinc(qi * rj / np.pi) for rj in trgrid] for qi in tqgrid])\n        tt = np.asmatrix(tint * tqgrid ** 2).T\n        tpr = np.reshape(np.array((kern.T * tt).T), len(trgrid))\n        tpr /= tpr.sum()\n\n        # plt.plot(tqgrid,tint,\"g-\")\n        # tpr = np.fft.rfft(tint)\n        # tx = range(len(tpr))\n        ax.plot(trgrid, tpr, \"g-\")\n        ax.set_xlabel(\"$r (\\AA)$\", fontsize=get_font_size(i_fs)[1])\n        ax.set_ylabel(\"$P(r)$\", fontsize=get_font_size(i_fs)[1])\n        # plt.subplots_adjust(bottom=0.15)\n\n    def save(self, fn, nz=True, scale_wabs=-1,\n             save_comments=False, debug=False, footer=None):\n        \"\"\"\n        should save all the relevant information, such as scaling, merging, averaging\n        save data points with non-zero intensity only if nz==1\n        \"\"\"\n        if scale_wabs>0:\n            assert(self.trans_w>0)\n            scale_wabs /= self.trans_w\n            qidi = np.vstack((self.qgrid, self.data*scale_wabs, self.err*scale_wabs))\n        else:\n            qidi = np.vstack((self.qgrid, self.data, self.err))\n        if nz:\n            qidi = qidi[:, self.data != 0]\n        if debug==True:\n            print(\"saving file: %s, nz=%d\" % (fn, nz))\n        np.savetxt(fn, qidi.T, \"%8.4f   %8.3e   %8.3e\")\n        if save_comments or footer is not None:\n            ff = open(fn, \"a\")\n            if save_comments:\n                ff.write(self.comments)\n                if scale_wabs>0:\n                    ff.write(\"# converted to abs scale by applying a scaling factor of {scale_wabs:.2e}\\n\")\n            elif footer is not None:\n                ff.write(footer)\n            ff.close()\n\n    def plot(self, ax=None, scale=1., fontsize='large', scale_wabs=-1):\n        i_fs = get_font_size(fontsize)[0]\n        if ax is None:\n            plt.figure()\n            plt.subplots_adjust(bottom=0.15)\n            ax = plt.gca()\n        if scale_wabs>0:\n            assert(self.trans_w>0)\n            scale *= scale_wabs/self.trans_w\n        ax.set_xlabel(\"$q (\\AA^{-1})$\", fontsize=get_font_size(i_fs)[1])\n        ax.set_ylabel(\"$I$\", fontsize=get_font_size(i_fs)[1])\n        ax.set_xscale('log')\n        ax.set_yscale('log')\n        ax.errorbar(self.qgrid, self.data*scale, self.err*scale, label=self.label)\n        for ov in self.overlaps:\n            ax.plot(ov['q_overlap'], ov['raw_data1']*scale, \"v\")\n            ax.plot(ov['q_overlap'], ov['raw_data2']*scale, \"^\")\n        leg = ax.legend(loc='upper right', frameon=False)\n\n        for t in leg.get_texts():\n            t.set_fontsize(get_font_size(i_fs-2)[1])\n\ndef normalize(ds):\n    return np.divide(ds.data, np.max(ds.data))\n\ndef calculate(ds0, ds1):\n    diff_coef = np.sum(np.abs(np.subtract(ds0, ds1)))  # How different the datasets are\n    return diff_coef            \n            \ndef filter_by_similarity(datasets, similarity_threshold=0.5, debug=False):\n    \n    if len(datasets)==1:\n        return datasets,None\n    \n    number_of_cpus = os.cpu_count()\n    number_of_datasets = len(datasets)\n    combinations = list(it.combinations(range(number_of_datasets), 2))\n    similarity_matrix = np.zeros((number_of_datasets, number_of_datasets), dtype=np.bool)\n    np.fill_diagonal(similarity_matrix, 1)  # If we compare the dataset with itself the result will always be one.\n\n    norm_data = collections.deque(map(normalize, datasets))\n    with mp.Pool(number_of_cpus) as pool:\n        differences = pool.starmap(calculate, [(norm_data[i], norm_data[j]) for i, j in combinations])\n\n    # print(\"Differences: \\n\", differences)\n    # print(\"Diff Norm: \\n\", np.divide(differences, np.max(differences)))\n    # print(\"Combinations: \\n\", combinations)\n    similarities = np.divide(differences, np.max(differences)) <= similarity_threshold\n\n    idx = 0\n    for c in combinations:\n        similarity_matrix[c[0]][c[1]] = similarities[idx]\n        similarity_matrix[c[1]][c[0]] = similarities[idx]\n        idx += 1\n\n    number_of_simil_per_column = np.sum(similarity_matrix, axis=0)\n\n    # No valid candidate, return all the data\n    if np.array_equal(number_of_simil_per_column, np.ones(number_of_datasets)):\n        if debug is True:\n            print(\"No dataset with similarity level below threshold. Returning everything.\")\n        return datasets, []\n\n    best_datasets_column = np.argmax(number_of_simil_per_column)\n    best_column = similarity_matrix[:, best_datasets_column]\n    valid_entries = list(it.compress(datasets, best_column))\n    invalid_entries = set(datasets) - set(valid_entries)\n    # print(\"Similarity Matrix: \\n\", similarity_matrix)\n    # print(\"Best Column: \\n\", best_column)\n    return valid_entries, invalid_entries\n\n\ndef merge_detectors(fns, detectors, qgrid, reft=-1, plot_data=False, save_ave=False, save_merged=False, ax=None, qmax=-1, qmin=-1, fix_scale=1, debug=False, transMode=trans_mode.from_waxs, trans=-1):\n    \"\"\"\n    fns: filename, without the _SAXS/_WAXS suffix\n    fix_scale is now default to 1\n    implicitly assume that all detectors have the same qgrid\n    \"\"\"\n    ss = []\n    t0 = time.time()\n    for fn in fns:\n        s0 = Data1d()\n        d_tot = np.zeros(qgrid.shape)\n        d_max = np.zeros(qgrid.shape)\n        d_min = np.zeros(qgrid.shape)+1.e32\n        e_tot = np.zeros(qgrid.shape)\n        c_tot = np.zeros(qgrid.shape)\n        label = None\n        comments = \"\"\n        #t1 = time.time()\n        for det in detectors:\n            #t2 = time.time()\n            # revised 2017mar10\n            # old conversion: fn+det.extension gives the complete filename, the extension looks like this: \"_SAXS.cbf\"\n            # this is a problem when the detector collect multiple images per trigger\n            # new comvention: fn is a template, e.g. '/GPFS/xf16id/exp_path/301525/301016/temp1_000002%s_00001.cbf', \n            # and the extension looks like this: \"_SAXS\"  \n            if \"%s\" in fn:\n                fn1 = fn % det.extension\n            else:\n                fn1 = fn + det.extension\n            if debug==True:\n                print(fn, det.extension, fn1) \n\n            s0.load_from_2D(fn1, det.exp_para, qgrid, det.pre_process,\n                            save_ave=save_ave, debug=debug)\n\n            if save_ave:\n                s0.save(fn1 + \".ave\", debug=debug)\n\n            if det.fix_scale is not None:\n                fix_scale = det.fix_scale\n                s0.scale(1./fix_scale)\n\n            # empty part of the data is nan\n            idx = ~np.isnan(s0.data)\n            d_tot[idx] += s0.data[idx]\n            e_tot[idx] += s0.err[idx]\n            c_tot[idx] += 1\n\n            idx1 = (np.ma.fix_invalid(s0.data, fill_value=-1)>d_max).data\n            d_max[idx1] = s0.data[idx1]\n            idx2 = (np.ma.fix_invalid(s0.data, fill_value=1e32)<d_min).data\n            d_min[idx2] = s0.data[idx2]\n            \n            comments += s0.comments\n            if label is None:\n                label = s0.label\n            else:\n                label = common_name(label, s0.label)\n        \n        s0.data = d_tot\n        s0.err = e_tot\n        idx = (c_tot>1)\n        s0.overlaps.append({'q_overlap': qgrid[idx],\n                             'raw_data1': d_max[idx],\n                             'raw_data2': d_min[idx]})\n        s0.data[idx] /= c_tot[idx]\n        s0.err[idx] /= c_tot[idx]\n        s0.transMode = transMode\n        s0.set_trans(transMode, trans=trans, ref_trans=reft, debug=debug)\n        s0.label = label\n        s0.comments = comments # .replace(\"# \", \"## \")\n\n        if save_merged:\n            s0.save(s0.label + \".dd\", debug=debug)\n        ss.append(s0)\n\n    return ss\n\n\ndef average(fns, detectors, qgrid, reft=-1, plot_data=False, save1d=0, ax=None, qmax=-1, qmin=-1, fix_scale=-1,\n            filter_datasets=True, similarity_threshold=0.5, debug=False):\n    \"\"\"\n    fns: filename, without the _SAXS/_WAXS suffix\n    save1d:  0 = do not save 1d data; 1 = save only the averaged data *.ddd;\n             2 = merged data before average as well, *.dd; 3 = also save the data before merge, *.ave \n    \"\"\"\n\n    save_dd = False\n    save_ave = False\n    save_ddd = False\n    if save1d>0:\n        save_ddd = True\n    if save1d>1: \n        save_dd = True\n    if save1d>2:\n        save_ave = True\n\n    t0 = time.time()\n    ss = merge_detectors(fns, detectors, qgrid, reft, plot_data, save_ave, save_dd, \n                         ax, qmax, qmin, fix_scale, debug=debug)\n    t1 = time.time()\n    if filter_datasets:\n        ss, invalids = filter_by_similarity(ss, similarity_threshold=similarity_threshold, debug=debug)\n        # TODO: Insert warning/exception when the number of datasets discarded is high.\n        # TODO: Define the % of discarded to result in a error.\n        if debug!='quiet':\n            print(\"Selected Datasets: \")\n            for s in ss:\n                print(s.label)\n\n        if len(invalids) > 0 and debug!='quiet':\n            print(\"The following datasets where discarded due to similarity level below the threshold: \",\n                  similarity_threshold)\n            for inv in invalids:\n                print(inv.label)\n    t2 = time.time()\n    if len(ss) > 0:\n        ss[0] = ss[0].avg(ss[1:], plot_data, ax=ax, debug=debug)\n    t3 = time.time()\n    if save_ddd:\n        ss[0].save(ss[0].label + \".ddd\", debug=debug)\n    t4 = time.time()\n    if debug==True:\n        print('Time to Merge: ', t1-t0)\n        print('Time to Filter: ', t2-t1)\n        print('Time to Average: ', t3-t2)\n        print('Time to Save Data: ', t4-t3)\n    return ss[0]\n\n\ndef process(sfns, bfns, detectors, qgrid, qmax=-1, qmin=-1, \n            reft=-1, save1d=False, conc=0., plot_data=True, fix_scale=-1,\n            filter_datasets=True, similarity_threshold=0.5, debug=False):\n    vfrac = 0.001 * conc / PROTEIN_WATER_DENSITY_RATIO\n\n    sample_axis = None\n    buffer_axis = None\n    bkg_cor_axis = None\n\n    if plot_data:\n        plt.figure()\n        sample_axis = plt.subplot2grid((2, 2), (0, 0), title=\"Sample Data\")\n        buffer_axis = plt.subplot2grid((2, 2), (0, 1), title=\"Buffer Data\")\n        bkg_cor_axis = plt.subplot2grid((2, 2), (1, 0), colspan=2, title=\"Background Correction\")\n\n    # TODO: Run the next two lines in parallel\n    args_sample = (sfns, detectors, qgrid, reft, plot_data, save1d, sample_axis, qmax,\n                   qmin, fix_scale, filter_datasets, similarity_threshold)\n    args_buffer = (bfns, detectors, qgrid, reft, plot_data, save1d, buffer_axis, qmax,\n                   qmin, fix_scale, filter_datasets, similarity_threshold)\n\n    # In order for the Pool to work we need to make the ExpPara something other than a SwigObject.\n    # Maybe it is time to change for something else\n    # with mp.Pool(1) as pool:\n    #     result = pool.starmap(average, (args_sample, args_buffer))\n    #\n    # ds = result[0]\n    # db = result[1]\n\n    ds = average(*args_sample, debug=debug)\n    db = average(*args_buffer, debug=debug)\n\n    ds.bkg_cor(db, 1.0 - vfrac, plot_data=plot_data, ax=bkg_cor_axis, inplace=True, debug=debug)\n\n    return ds\n\n\ndef analyze(d1, qstart, qend, fix_qe, qcutoff, dmax):\n    plt.figure(figsize=(14, 5.5))\n    plt.subplot(121)\n    I0,Rg,_ = d1.plot_Guinier(qs=qstart, qe=qend, fix_qe=fix_qe)\n\n    print(\"I0=%f, Rg=%f\" % (I0, Rg))\n\n    plt.subplot(122)\n    d1.plot_pr(I0, Rg, qmax=1.2, dmax=dmax)\n    plt.subplots_adjust(bottom=0.15, wspace=0.25)\n\n    \ndef estimate_scaling_factor(d1s, d1b, \n                            q_min=0.5, q_max=3.5, smoothing_width=5, prec=4, s_thresh=1,\n                            plot_data=False, ax=None, debug=False):\n    \"\"\" Estimate the scaling factor needed to subtract buffer scattering d1b\n        from sample scattering d1s, d1s/d1b should be instances of Data1d\n        \n        This function iteratively vary the scaling factor, up to the specified \n        precision (number of digits after the decimal point), and optinally smooth \n        the data before the calcualtion. Several critiera for over sub-traction are \n        used to stop the interation: \n        (1) non-zero value in the subtracted result\n        (2) minimum of the subtracted result fall below 1/q\n        (3) dynamic range of the value of the result, as measured by the span or std\n            deviation of the log, becomes too high\n        \n        only test the data above q_min, which should not exceed 1.0\n    \"\"\"\n    idx = (d1s.qgrid>q_min) & (d1s.qgrid<q_max) & (d1s.data>0) & (d1b.data>0)\n    md1s = d1s.data[idx]\n    md1b = d1b.data[idx]\n    try:\n        md1sm = smooth(md1s, half_window_len=smoothing_width)\n        md1bm = smooth(md1b, half_window_len=smoothing_width)\n    except:\n        return 1.0      # problems like incomplete data can cause smooth() to fail, no point to continue\n    mq = d1s.qgrid[idx]\n    sc = 0.9\n    prec0 = 2\n    std0 = np.log(md1s-md1b*sc).std()\n    n,bins = np.histogram((md1s-md1b*sc)*mq)\n    sp0 = bins[-1]-bins[0]\n    \n    if debug:\n        print(\"# sc,   mean,   std,   span,   qmin\")\n    while prec0<=prec:\n        sc1 = sc\n        while np.all(md1s-sc1*md1b>0):\n            # data should have finite dynamic range\n            td = np.log(md1s-md1b*sc1)\n            n,bins = np.histogram(td)\n            sp1 = bins[-1]-bins[0]\n            std1 = td.std()\n            #if std1>s_thresh*std0:\n            #    break\n            #elif std1<std0:\n            #    std0 = std1\n            if sp1>sp0+s_thresh:\n                if debug:\n                    print(f\"span exceeded threshold: {sp1}, {sp0}+{s_thresh}\")\n                break\n            # assume that data*q should have a lower bound\n            # this should work better on the smoothed data\n            td1 = (md1sm-md1bm*sc1)*mq\n            q_Imin = mq[td1.argmin()]\n            if q_Imin>1.7:  # under the water peak, indication of over-subtraction\n                if debug:\n                    print(f\"qxI min under water peak: q={q_Imin:.3f}\")\n                break\n            sc = sc1\n            if debug:\n                print(f\"{sc1:.5f}, {td.mean():.3f}, {std1:.3f}, {sp1:3f}, {q_Imin:.3f}\")\n            sc1 = sc+np.power(10., -prec0)\n        prec0 += 1\n    \n    if plot_data:\n        if ax is None:\n            plt.figure()\n            ax = plt.gca()\n        plt.semilogy(d1s.qgrid, d1s.data)\n        plt.semilogy(d1b.qgrid, d1b.data)\n        plt.errorbar(d1s.qgrid, (d1s.data-sc*d1b.data), d1s.err*1.414)\n    \n    return sc\n    \n", "meta": {"hexsha": "bba66ae11af5a4a2fc5baf9a56ffda732984e51c", "size": 38811, "ext": "py", "lang": "Python", "max_stars_repo_path": "py4xs/slnxs.py", "max_stars_repo_name": "NSLS-II-LIX/py4xs", "max_stars_repo_head_hexsha": "cc2102bd852a7ade1c1969fb5faf2ad361550617", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-10-23T21:00:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-09T15:57:31.000Z", "max_issues_repo_path": "py4xs/slnxs.py", "max_issues_repo_name": "NSLS-II-LIX/py4xs", "max_issues_repo_head_hexsha": "cc2102bd852a7ade1c1969fb5faf2ad361550617", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "py4xs/slnxs.py", "max_forks_repo_name": "NSLS-II-LIX/py4xs", "max_forks_repo_head_hexsha": "cc2102bd852a7ade1c1969fb5faf2ad361550617", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-09-27T15:16:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-09T15:23:36.000Z", "avg_line_length": 40.4702815433, "max_line_length": 199, "alphanum_fraction": 0.5615933627, "include": true, "reason": "import numpy", "num_tokens": 10206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.18573736240821992}}
{"text": "'''\n@Author: dengzaiyong\n@Date: 2021-08-21 15:16:08\n@LastEditTime: 2021-08-27 19:37:08\n@LastEditors: dengzaiyong\n@Desciption: 使用Faiss训练hnsw模型\n@FilePath: /JDQA/retrieval/hnsw_faiss.py\n'''\n\nimport os\nimport time\nimport numpy as np\nimport pandas as pd\nfrom gensim.models import KeyedVectors\nimport faiss\nimport config\nfrom preprocessor import clean\nfrom utils.tools import create_logger\n\nlogger = create_logger(config.root_path + '/logs/hnsw_faiss.log')\n\ndef sentence_embedding(sentence, w2v_model):\n    '''\n    通过词向量均值的方式生成句向量\n    sentence: 待生成句向量的句子\n    w2v_model: word2vec模型\n    return: 句子中所有词向量的均值\n    '''\n    embedding = []\n    for word in clean(sentence).split():\n        if word not in w2v_model.wv.index_to_key:\n            embedding.append(np.random.randn(1, config.embed_dim))\n        else:\n            embedding.append(w2v_model.wv.get_vector(word))\n\n    # 所有词向量的均值为句向量\n    return np.mean(np.array(embedding), axis=0).reshape(1, -1)\n\nclass HNSW(object):\n    def __init__(self,\n                 w2v_path,                      # word2vec模型路径\n                 ef=config.ef_construction,     # 搜索时保存最近邻的动态列表大小\n                 M=config.M,                    # 节点的邻结点的数量\n                 model_path=None,               # hnsw模型保存路径\n                 data_path=None):               # 数据文件路径\n\n        self.w2v_model = KeyedVectors.load(w2v_path)\n        self.data = self.load_data(data_path)\n\n        # 加载hnsw模型\n        if model_path and os.path.exists(model_path):\n            self.index = self.load_hnsw(model_path)            \n        # 训练hnsw模型\n        elif data_path:\n            self.index = self.build_hnsw(model_path, ef=ef, m=M)\n        else:\n            logger.error('No existing model and no building data provided.')\n\n        \n    def load_data(self, data_path):\n        '''\n        读取数据，并生成句向量        \n        data_path：问答pair数据所在路径\n        return: 包含句向量的dataframe\n        '''\n        data = pd.read_csv(data_path)\n\n        # 生成custom每条记录的句向量\n        data['custom_vec'] = data['custom'].apply(\n            lambda x: sentence_embedding(x, self.w2v_model))\n\n        # 确保句向量的维度为300\n        data['custom_vec'] = data['custom_vec'].apply(\n            lambda x: x[0][0] if x.shape[1] != config.embed_dim else x)\n        data = data.dropna()\n        \n        return data\n\n    def evaluate(self, vecs):\n        '''\n        验证模型\n        '''\n        logger.info('Evaluating hnsw model')\n        nq, d = vecs.shape\n        t0 = time.time\n        \n        # 找top1个相似的\n        D, I = self.index.search(vecs, 1)\n        t1 = time.time\n\n        missing_rate = (I == -1).sum() / float(nq)\n        recall_at_1 = (I == np.arange(nq)).sum() / float(nq)\n        print(\"\\t %7.3f ms per query, R@1 %.4f, missing rate %.4f\" % (\n            (t1 - t0) * 1000.0 / nq, recall_at_1, missing_rate))\n    \n    def build_hnsw(self, to_file, ef=2000, m=64):\n        \"\"\"\n        训练hnsw模型\n        \"\"\"\n        logger.info('building hnsw index')\n\n        # 所有的句向量拼接\n        vecs = np.stack(self.data['custom_vec'].values).reshape(-1, config.embed_dim)\n        vecs = vecs.astype('float32')\n\n        dim = self.w2v_model.vector_size\n\n         # 构建索引\n        index = faiss.IndexHNSWFlat(dim, m)\n\n        # 使用单个GPU资源\n        res = faiss.StandardGpuResources()\n        \n        faiss.index_cpu_to_gpu(res, 0, index)\n        index.hnsw.ef_construction = ef\n        index.verbose = True\n        index.add(vecs)\n\n        # 保存hnsw模型\n        faiss.write_index(index, to_file)\n\n        return index\n\n    def load_hnsw(self, model_path):\n        logger.info(f\"Loading hnsw from {model_path}\")\n        hnsw = faiss.read_index(model_path)\n        return hnsw\n\n    def search(self, text, k=5):\n        \"\"\"\n        通过hnsw检索topk\n        \"\"\"\n        print(f'Searching for {text}.')\n\n        # 转换句向量\n        test_vec = sentence_embedding(clean(text), self.w2v_model)\n        test_vec = test_vec.astype('float32')\n\n        # 搜索相似度最高的k个句向量\n        D, I = self.index.search(test_vec, k)           \n\n        df = pd.concat((self.data.iloc[I[0]]['custom'].reset_index(),\n                        self.data.iloc[I[0]]['assistance'].reset_index(drop=True),\n                        pd.DataFrame(D.reshape(-1, 1), columns=['q_distance'])),\n                        axis=1) \n\n        return df\n\nif __name__ == '__main__':\n    hnsw = HNSW(config.w2v_path,\n            config.ef_construction,\n            config.M,\n            config.fassi_path,\n            config.train_path)\n\n    text = '我要转人工'\n    print(hnsw.search(text, k=10))\n\n    # 验证模型\n    eval_vecs = np.stack(hnsw.data['custom_vec'].values).reshape(-1, config.embed_dim)\n    eval_vecs.astype('float32')\n    hnsw.evaluate(eval_vecs[:1000])", "meta": {"hexsha": "8f4210db0d76e2e5640e5f95a23e7cb8c9ded9ca", "size": 4642, "ext": "py", "lang": "Python", "max_stars_repo_path": "retrieval/hnsw_faiss.py", "max_stars_repo_name": "yzhhome/JDQA", "max_stars_repo_head_hexsha": "68e1d0259d316b3577a1f2fafa773b50f1885762", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-21T10:50:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T10:50:21.000Z", "max_issues_repo_path": "retrieval/hnsw_faiss.py", "max_issues_repo_name": "kalanile/JDQA", "max_issues_repo_head_hexsha": "68e1d0259d316b3577a1f2fafa773b50f1885762", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "retrieval/hnsw_faiss.py", "max_forks_repo_name": "kalanile/JDQA", "max_forks_repo_head_hexsha": "68e1d0259d316b3577a1f2fafa773b50f1885762", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-21T10:50:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T10:50:20.000Z", "avg_line_length": 28.6543209877, "max_line_length": 86, "alphanum_fraction": 0.5713054718, "include": true, "reason": "import numpy", "num_tokens": 1401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.18573736240821992}}
{"text": "\"\"\"\nCopyright 2017 Steven Diamond\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nfrom collections import namedtuple\n\nimport cvxpy.interface as intf\nimport cvxpy.settings as s\nimport cvxpy.lin_ops.lin_utils as lu\nimport numpy as np\nfrom cvxpy.problems.solvers.solver import Solver\nfrom scipy.sparse import dok_matrix\n\n# Values used to distinguish between linear and quadratic constraints.\n_LIN, _QUAD = 0, 1\n# For internal bookkeeping, we have to separate linear indices from\n# quadratic indices. The \"cpx_constrs\" member of the results_dict will\n# contain namedtuples of (constr_type, index) where constr_type is either\n# _LIN or _QUAD.\n_CpxConstr = namedtuple(\"_CpxConstr\", [\"constr_type\", \"index\"])\n\n\nclass CPLEX(Solver):\n    \"\"\"An interface for the CPLEX solver.\n    \"\"\"\n\n    # Solver capabilities.\n    LP_CAPABLE = True\n    SOCP_CAPABLE = True\n    SDP_CAPABLE = False\n    EXP_CAPABLE = False\n    MIP_CAPABLE = True\n\n    def name(self):\n        \"\"\"The name of the solver.\n        \"\"\"\n        return s.CPLEX\n\n    def import_solver(self):\n        \"\"\"Imports the solver.\n        \"\"\"\n        import cplex\n        cplex  # For flake8\n\n    def matrix_intf(self):\n        \"\"\"The interface for matrices passed to the solver.\n        \"\"\"\n        return intf.DEFAULT_SPARSE_INTF\n\n    def vec_intf(self):\n        \"\"\"The interface for vectors passed to the solver.\n        \"\"\"\n        return intf.DEFAULT_INTF\n\n    def split_constr(self, constr_map):\n        \"\"\"Extracts the equality, inequality, and nonlinear constraints.\n\n        Parameters\n        ----------\n        constr_map : dict\n            A dict of the canonicalized constraints.\n\n        Returns\n        -------\n        tuple\n            (eq_constr, ineq_constr, nonlin_constr)\n        \"\"\"\n        return (constr_map[s.EQ] + constr_map[s.LEQ], [], [])\n\n    @staticmethod\n    def _param_in_constr(constraints):\n        \"\"\"Do any of the constraints contain parameters?\n        \"\"\"\n        for constr in constraints:\n            if len(lu.get_expr_params(constr.expr)) > 0:\n                return True\n        return False\n\n    def solve(self, objective, constraints, cached_data,\n              warm_start, verbose, solver_opts):\n        \"\"\"Returns the result of the call to the solver.\n\n        Parameters\n        ----------\n        objective : LinOp\n            The canonicalized objective.\n        constraints : list\n            The list of canonicalized cosntraints.\n        cached_data : dict\n            A map of solver name to cached problem data.\n        warm_start : bool\n            Not used.\n        verbose : bool\n            Should the solver print output?\n        solver_opts : dict\n            Additional arguments for the solver.\n            'cplex_params' - a dictionary where the key-value pairs are\n                             composed of parameter names and parameter\n                             values.\n            'cplex_filename' - A string specifying the filename to which\n                               the problem will be written.\n\n        Returns\n        -------\n        tuple\n            (status, optimal value, primal, equality dual, inequality dual)\n        \"\"\"\n        import cplex\n\n        # Get problem data\n        data = self.get_problem_data(objective, constraints, cached_data)\n\n        c = data[s.C]\n        b = data[s.B]\n        A = dok_matrix(data[s.A])\n        # Save the dok_matrix.\n        data[s.A] = A\n        data[s.BOOL_IDX] = solver_opts[s.BOOL_IDX]\n        data[s.INT_IDX] = solver_opts[s.INT_IDX]\n\n        n = c.shape[0]\n\n        solver_cache = cached_data[self.name()]\n\n        # TODO: warmstart with SOC constraints.\n        if warm_start and solver_cache.prev_result is not None \\\n           and len(data[s.DIMS][s.SOC_DIM]) == 0:\n            model = solver_cache.prev_result[\"model\"]\n            variables = solver_cache.prev_result[\"variables\"]\n            # cpx_constrs contains CpxConstr namedtuples (see above).\n            cpx_constrs = solver_cache.prev_result[\"cpx_constrs\"]\n            c_prev = solver_cache.prev_result[\"c\"]\n            A_prev = solver_cache.prev_result[\"A\"]\n            b_prev = solver_cache.prev_result[\"b\"]\n\n            # If there is a parameter in the objective, it may have changed.\n            if len(lu.get_expr_params(objective)) > 0:\n                c_diff = c - c_prev\n\n                I_unique = list(set(np.where(c_diff)[0]))\n\n                for i in I_unique:\n                    model.objective.set_linear(variables[i], c[i])\n            else:\n                # Stay consistent with CPLEX's representation of the problem\n                c = c_prev\n\n            # Get equality and inequality constraints.\n            sym_data = self.get_sym_data(objective, constraints, cached_data)\n            all_constrs, _, _ = self.split_constr(sym_data.constr_map)\n\n            # If there is a parameter in the constraints,\n            # A or b may have changed.\n            if self._param_in_constr(all_constrs):\n                A_diff = dok_matrix(A - A_prev)\n                b_diff = b - b_prev\n\n                # Figure out which rows of A and elements of b have changed\n                try:\n                    idxs, _ = zip(*[x for x in A_diff.keys()])\n                except ValueError:\n                    idxs = []\n                I_unique = list(set(idxs) | set(np.where(b_diff)[0]))\n\n                # Update locations which have changed\n                csr = A.tocsr()\n                for i in I_unique:\n                    # To update a constraint, we first disable the old\n                    # constraint and then add a new constraint with the\n                    # modifications. This way we don't have to worry\n                    # about indices needing to shift. The old constraint\n                    # is disabled by setting all coefficients and the rhs\n                    # to zero.\n                    #\n                    # NOTE: This can change the relative order of the\n                    # constraints, which can result in performance\n                    # variability!\n\n                    # Disable the old constraint if it exists.\n                    assert cpx_constrs[i].index is not None\n                    assert cpx_constrs[i].constr_type == _LIN\n                    idx = cpx_constrs[i].index\n                    tmp = model.linear_constraints.get_rows(idx)\n                    model.linear_constraints.set_linear_components(\n                        idx,\n                        cplex.SparsePair(ind=tmp.ind, val=[0.0]*len(tmp.ind)))\n                    model.linear_constraints.set_rhs(idx, 0.0)\n\n                    # Add new constraint\n\n                    ind = [variables[x] for x in csr[i].indices]\n                    val = [x for x in csr[i].data]\n                    if i < data[s.DIMS][s.EQ_DIM]:\n                        ctype = \"E\"\n                    else:\n                        assert data[s.DIMS][s.EQ_DIM] <= i \\\n                            < data[s.DIMS][s.EQ_DIM] + data[s.DIMS][s.LEQ_DIM]\n                        ctype = \"L\"\n                    new_idx = list(model.linear_constraints.add(\n                        lin_expr=[cplex.SparsePair(ind=ind, val=val)],\n                        senses=ctype,\n                        rhs=[b[i]]))[0]\n                    cpx_constrs[i] = _CpxConstr(_LIN, new_idx)\n\n            else:\n                # Stay consistent with CPLEX's representation of the problem\n                A = A_prev\n                b = b_prev\n\n        else:\n            model = cplex.Cplex()\n            variables = []\n            # cpx_constrs will contain CpxConstr namedtuples (see above).\n            cpx_constrs = []\n            vtype = []\n            if self.is_mip(data):\n                for i in range(n):\n                    # Set variable type.\n                    if i in data[s.BOOL_IDX]:\n                        vtype.append('B')\n                    elif i in data[s.INT_IDX]:\n                        vtype.append('I')\n                    else:\n                        vtype.append('C')\n            else:\n                # If we specify types (even with 'C'), then the problem will\n                # be interpreted as a MIP. Leaving vtype as an empty list\n                # here, will ensure that the problem type remains an LP.\n                pass\n            # Add the variables in a batch\n            variables = list(model.variables.add(\n                obj=[c[i] for i in range(n)],\n                lb=[-cplex.infinity]*n,  # default LB is 0\n                ub=[cplex.infinity]*n,\n                types=\"\".join(vtype),\n                names=[\"x_%d\" % i for i in range(n)]))\n\n            # Add equality constraints\n            cpx_constrs += [_CpxConstr(_LIN, x)\n                            for x in self.add_model_lin_constr(\n                                    model, variables,\n                                    range(data[s.DIMS][s.EQ_DIM]),\n                                    'E', A, b)]\n\n            # Add inequality (<=) constraints\n            leq_start = data[s.DIMS][s.EQ_DIM]\n            leq_end = data[s.DIMS][s.EQ_DIM] + data[s.DIMS][s.LEQ_DIM]\n            cpx_constrs += [_CpxConstr(_LIN, x)\n                            for x in self.add_model_lin_constr(\n                                    model, variables,\n                                    range(leq_start, leq_end),\n                                    'L', A, b)]\n\n            # Add SOC constraints\n            soc_start = leq_end\n            for constr_len in data[s.DIMS][s.SOC_DIM]:\n                soc_end = soc_start + constr_len\n                soc_constr, new_leq, new_vars = self.add_model_soc_constr(\n                    model, variables, range(soc_start, soc_end), A, b)\n                cpx_constrs.append(_CpxConstr(_QUAD, soc_constr))\n                cpx_constrs += [_CpxConstr(_LIN, x) for x in new_leq]\n                variables += new_vars\n                soc_start += constr_len\n\n        # Set verbosity\n        if not verbose:\n            model.set_results_stream(None)\n            model.set_warning_stream(None)\n            model.set_error_stream(None)\n            model.set_log_stream(None)\n        else:\n            # By default the output will be sent to stdout.\n            pass\n\n        # TODO: user option to not compute duals.\n        model.parameters.preprocessing.qcpduals.set(\n            model.parameters.preprocessing.qcpduals.values.force)\n\n        # TODO: Parameter support is functional, but perhaps not ideal.\n        # The user must pass parameter names as used in the CPLEX Python\n        # API, and raw values (i.e., no enum support).\n        kwargs = sorted(solver_opts.keys())\n        if \"cplex_params\" in kwargs:\n            for param, value in solver_opts[\"cplex_params\"].items():\n                try:\n                    eval(\"model.parameters.{0}.set({1})\".format(param, value))\n                except AttributeError:\n                    raise ValueError(\n                        \"invalid CPLEX parameter, value pair ({0}, {1})\".format(\n                            param, value))\n            kwargs.remove(\"cplex_params\")\n        if \"cplex_filename\" in kwargs:\n            filename = solver_opts[\"cplex_filename\"]\n            if filename:\n                model.write(filename)\n            kwargs.remove(\"cplex_filename\")\n        if s.BOOL_IDX in kwargs:\n            kwargs.remove(s.BOOL_IDX)\n        if s.INT_IDX in kwargs:\n            kwargs.remove(s.INT_IDX)\n        if kwargs:\n            raise ValueError(\"invalid keyword-argument '{0}'\".format(kwargs[0]))\n\n        results_dict = {}\n        start_time = model.get_time()\n        solve_time = -1\n        try:\n            model.solve()\n            solve_time = model.get_time() - start_time\n            results_dict[\"primal objective\"] = model.solution.get_objective_value()\n            results_dict[\"x\"] = np.array(model.solution.get_values(variables))\n            results_dict[\"status\"] = self._get_status(model)\n\n            # Only add duals if not a MIP.\n            if not self.is_mip(data):\n                vals = []\n                for con in cpx_constrs:\n                    assert con.index is not None\n                    if con.constr_type == _LIN:\n                        vals.append(model.solution.get_dual_values(con.index))\n                    else:\n                        assert con.constr_type == _QUAD\n                        # Quadratic constraints not queried directly.\n                        vals.append(0.0)\n                results_dict[\"y\"] = -np.array(vals)\n        except Exception:\n            if solve_time < 0.0:\n                solve_time = model.get_time() - start_time\n            results_dict[\"status\"] = s.SOLVER_ERROR\n\n        results_dict[\"model\"] = model\n        results_dict[\"variables\"] = variables\n        results_dict[\"cpx_constrs\"] = cpx_constrs\n        results_dict[s.SOLVE_TIME] = solve_time\n\n        return self.format_results(results_dict, data, cached_data)\n\n    def _handle_solve_status(self, model, solstat):\n        \"\"\"Map CPLEX MIP solution status codes to non-MIP status codes.\"\"\"\n        status = model.solution.status\n        if solstat == status.MIP_optimal:\n            return status.optimal\n        elif solstat == status.MIP_infeasible:\n            return status.infeasible\n        elif solstat in (status.MIP_time_limit_feasible,\n                         status.MIP_time_limit_infeasible):\n            return status.abort_time_limit\n        elif solstat in (status.MIP_dettime_limit_feasible,\n                         status.MIP_dettime_limit_infeasible):\n            return status.abort_dettime_limit\n        elif solstat in (status.MIP_abort_feasible,\n                         status.MIP_abort_infeasible):\n            return status.abort_user\n        elif solstat == status.MIP_optimal_infeasible:\n            return status.optimal_infeasible\n        elif solstat == status.MIP_infeasible_or_unbounded:\n            return status.infeasible_or_unbounded\n        elif solstat in (status.MIP_unbounded,\n                         status.MIP_benders_master_unbounded,\n                         status.benders_master_unbounded):\n            return status.unbounded\n        elif solstat in (status.feasible_relaxed_sum,\n                         status.MIP_feasible_relaxed_sum,\n                         status.optimal_relaxed_sum,\n                         status.MIP_optimal_relaxed_sum,\n                         status.feasible_relaxed_inf,\n                         status.MIP_feasible_relaxed_inf,\n                         status.optimal_relaxed_inf,\n                         status.MIP_optimal_relaxed_inf,\n                         status.feasible_relaxed_quad,\n                         status.MIP_feasible_relaxed_quad,\n                         status.optimal_relaxed_quad,\n                         status.MIP_optimal_relaxed_quad):\n            raise AssertionError(\n                \"feasopt status encountered: {0}\".format(solstat))\n        elif solstat in (status.conflict_feasible,\n                         status.conflict_minimal,\n                         status.conflict_abort_contradiction,\n                         status.conflict_abort_time_limit,\n                         status.conflict_abort_dettime_limit,\n                         status.conflict_abort_iteration_limit,\n                         status.conflict_abort_node_limit,\n                         status.conflict_abort_obj_limit,\n                         status.conflict_abort_memory_limit,\n                         status.conflict_abort_user):\n            raise AssertionError(\n                \"conflict refiner status encountered: {0}\".format(solstat))\n        elif solstat == status.relaxation_unbounded:\n            return status.relaxation_unbounded\n        elif solstat in (status.feasible,\n                         status.MIP_feasible):\n            return status.feasible\n        elif solstat == status.benders_num_best:\n            return status.num_best\n        else:\n            return solstat\n\n    def _get_status(self, model):\n        \"\"\"Map CPLEX status to CPXPY status.\"\"\"\n        pfeas = model.solution.is_primal_feasible()\n        # NOTE: dfeas is always false for a MIP.\n        dfeas = model.solution.is_dual_feasible()\n        status = model.solution.status\n        solstat = self._handle_solve_status(model, model.solution.get_status())\n        if solstat in (status.node_limit_infeasible,\n                       status.fail_infeasible,\n                       status.mem_limit_infeasible,\n                       status.fail_infeasible_no_tree,\n                       status.num_best):\n            return s.SOLVER_ERROR\n        elif solstat in (status.abort_user,\n                         status.abort_iteration_limit,\n                         status.abort_time_limit,\n                         status.abort_dettime_limit,\n                         status.abort_obj_limit,\n                         status.abort_primal_obj_limit,\n                         status.abort_dual_obj_limit,\n                         status.abort_relaxed,\n                         status.first_order):\n            if pfeas:\n                return s.OPTIMAL_INACCURATE\n            else:\n                return s.SOLVER_ERROR\n        elif solstat in (status.node_limit_feasible,\n                         status.solution_limit,\n                         status.populate_solution_limit,\n                         status.fail_feasible,\n                         status.mem_limit_feasible,\n                         status.fail_feasible_no_tree,\n                         status.feasible):\n            if dfeas:\n                return s.OPTIMAL\n            else:\n                return s.OPTIMAL_INACCURATE\n        elif solstat in (status.optimal,\n                         status.optimal_tolerance,\n                         status.optimal_infeasible,\n                         status.optimal_populated,\n                         status.optimal_populated_tolerance):\n            return s.OPTIMAL\n        elif solstat in (status.infeasible,\n                         status.optimal_relaxed_sum,\n                         status.optimal_relaxed_inf,\n                         status.optimal_relaxed_quad):\n            return s.INFEASIBLE\n        elif solstat in (status.feasible_relaxed_quad,\n                         status.feasible_relaxed_inf,\n                         status.feasible_relaxed_sum):\n            return s.SOLVER_ERROR\n        elif solstat == status.infeasible_or_unbounded:\n            return s.INFEASIBLE\n        elif solstat == status.unbounded:\n            return s.UNBOUNDED\n        else:\n            return s.SOLVER_ERROR\n\n    def add_model_lin_constr(self, model, variables,\n                             rows, ctype, mat, vec):\n        \"\"\"Adds EQ/LEQ constraints to the model using the data from mat and vec.\n\n        Parameters\n        ----------\n        model : CPLEX model\n            The problem model.\n        variables : list\n            The problem variables.\n        rows : range\n            The rows to be constrained.\n        ctype : CPLEX constraint type\n            The type of constraint.\n        mat : SciPy COO matrix\n            The matrix representing the constraints.\n        vec : NDArray\n            The RHS part of the constraints.\n\n        Returns\n        -------\n        list\n            A list of new linear constraint indices.\n        \"\"\"\n        constr, lin_expr, rhs = [], [], []\n        csr = mat.tocsr()\n        for i in rows:\n            ind = [variables[x] for x in csr[i].indices]\n            val = [x for x in csr[i].data]\n            lin_expr.append([ind, val])\n            rhs.append(vec[i])\n        # For better performance, we add the contraints in a batch.\n        if lin_expr:\n            assert len(lin_expr) == len(rhs)\n            constr.extend(list(\n                model.linear_constraints.add(\n                    lin_expr=lin_expr,\n                    senses=ctype * len(lin_expr),\n                    rhs=rhs)))\n        return constr\n\n    def add_model_soc_constr(self, model, variables,\n                             rows, mat, vec):\n        \"\"\"Adds SOC constraint to the model using the data from mat and vec.\n\n        Parameters\n        ----------\n        model : CPLEX model\n            The problem model.\n        variables : list\n            The problem variables.\n        rows : range\n            The rows to be constrained.\n        mat : SciPy COO matrix\n            The matrix representing the constraints.\n        vec : NDArray\n            The RHS part of the constraints.\n\n        Returns\n        -------\n        tuple\n            A tuple of (a new quadratic constraint index, a list of new\n            supporting linear constr indices, and a list of new\n            supporting variable indices).\n        \"\"\"\n        import cplex\n        # Assume first expression (i.e. t) is nonzero.\n        lin_expr_list, soc_vars, lin_rhs = [], [], []\n        csr = mat.tocsr()\n        for i in rows:\n            ind = [variables[x] for x in csr[i].indices]\n            val = [x for x in csr[i].data]\n            # Ignore empty constraints.\n            if ind:\n                lin_expr_list.append((ind, val))\n                lin_rhs.append(vec[i])\n            else:\n                lin_expr_list.append(None)\n                lin_rhs.append(0.0)\n\n        # Make a variable and equality constraint for each term.\n        soc_vars, is_first = [], True\n        for i in rows:\n            if is_first:\n                lb = [0.0]\n                names = [\"soc_t_%d\" % i]\n                is_first = False\n            else:\n                lb = [-cplex.infinity]\n                names = [\"soc_x_%d\" % i]\n            soc_vars.extend(list(model.variables.add(\n                obj=[0],\n                lb=lb,\n                ub=[cplex.infinity],\n                types=\"\",\n                names=names)))\n\n        new_lin_constrs = []\n        for i, expr in enumerate(lin_expr_list):\n            if expr is None:\n                ind = [soc_vars[i]]\n                val = [1.0]\n            else:\n                ind, val = expr\n                ind.append(soc_vars[i])\n                val.append(1.0)\n            new_lin_constrs.extend(list(\n                model.linear_constraints.add(\n                    lin_expr=[cplex.SparsePair(ind=ind, val=val)],\n                    senses=\"E\",\n                    rhs=[lin_rhs[i]])))\n\n        assert len(soc_vars) > 0\n        qconstr = model.quadratic_constraints.add(\n            lin_expr=cplex.SparsePair(ind=[], val=[]),\n            quad_expr=cplex.SparseTriple(\n                ind1=soc_vars,\n                ind2=soc_vars,\n                val=[-1.0] + [1.0] * (len(soc_vars) - 1)),\n            sense=\"L\",\n            rhs=0.0,\n            name=\"\")\n        return (qconstr, new_lin_constrs, soc_vars)\n\n    def format_results(self, results_dict, data, cached_data):\n        \"\"\"Converts the solver output into standard form.\n\n        Parameters\n        ----------\n        results_dict : dict\n            The solver output.\n        data : dict\n            Information about the problem.\n        cached_data : dict\n            A map of solver name to cached problem data.\n\n        Returns\n        -------\n        dict\n            The solver output in standard form.\n        \"\"\"\n        dims = data[s.DIMS]\n        if results_dict[\"status\"] != s.SOLVER_ERROR:\n            solver_cache = cached_data[self.name()]\n            solver_cache.prev_result = {\n                \"model\": results_dict[\"model\"],\n                \"variables\": results_dict[\"variables\"],\n                \"cpx_constrs\": results_dict[\"cpx_constrs\"],\n                \"c\": data[s.C],\n                \"A\": data[s.A],\n                \"b\": data[s.B],\n            }\n        new_results = {}\n        new_results[s.STATUS] = results_dict['status']\n        new_results[s.SOLVE_TIME] = results_dict[s.SOLVE_TIME]\n        if new_results[s.STATUS] in s.SOLUTION_PRESENT:\n            primal_val = results_dict['primal objective']\n            new_results[s.VALUE] = primal_val + data[s.OFFSET]\n            new_results[s.PRIMAL] = results_dict['x']\n            if not self.is_mip(data):\n                new_results[s.EQ_DUAL] = results_dict[\"y\"][0:dims[s.EQ_DIM]]\n                new_results[s.INEQ_DUAL] = results_dict[\"y\"][dims[s.EQ_DIM]:]\n\n        return new_results\n", "meta": {"hexsha": "565f03455e3baba12876cc8ef7de05a32f205961", "size": 24689, "ext": "py", "lang": "Python", "max_stars_repo_path": "cvxpy/problems/solvers/cplex_intf.py", "max_stars_repo_name": "Hennich/cvxpy", "max_stars_repo_head_hexsha": "4dfd6d69ace76abf57d8b1d63db0556dee96e24f", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-15T14:01:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-15T14:01:03.000Z", "max_issues_repo_path": "cvxpy/problems/solvers/cplex_intf.py", "max_issues_repo_name": "Hennich/cvxpy", "max_issues_repo_head_hexsha": "4dfd6d69ace76abf57d8b1d63db0556dee96e24f", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cvxpy/problems/solvers/cplex_intf.py", "max_forks_repo_name": "Hennich/cvxpy", "max_forks_repo_head_hexsha": "4dfd6d69ace76abf57d8b1d63db0556dee96e24f", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0648734177, "max_line_length": 83, "alphanum_fraction": 0.534408036, "include": true, "reason": "import numpy,from scipy,import cvxpy,from cvxpy", "num_tokens": 5105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.36296919173767833, "lm_q1q2_score": 0.1857373624082199}}
{"text": "#! /usr/bin/env python3\n# coding: utf-8\n\nimport numpy as np\nimport chainer\nimport sys, os\nfrom chainer import cuda, serializers\nfrom chainer import functions as chf\nfrom progressbar import progressbar\nimport librosa\nimport soundfile as sf\nimport pickle as pic\n\nfrom FCA import FCA\nfrom configure import *\n\n\nclass MNMF_DP(FCA):\n    \"\"\" Blind Speech Enhancement Using Multichannel Nonnegative Matrix Factorization with a Deep Speech Prior (MNMF-DP)\n\n    X_FTM: the observed complex spectrogram\n    covarianceMatrix_NFMM: spatial covariance matrices (SCMs) for each source\n    W_noise_NnFK: basis vectors for noise sources (Nn means the number of noise sources)\n    H_noise_NnKT: activations for noise sources\n    Z_speech_DT: latent variables for speech\n    power_speech_FT: power spectra of speech that is the output of DNN(Z_speech_DT)\n    lambda_NFT: power spectral densities of each source\n        lambda_NFT[0] = U_F * V_T * power_speech_FT\n        lambda_NFT[1:] = W_noise_NnFK @ H_noise_NnKT\n    \"\"\"\n\n    def __init__(self, speech_VAE=None, n_noise=1, n_Z_iteration=30, n_latent=16, n_basis_noise=2, xp=np, init_SCM=\"unit\", mode_update_parameter=[\"all\", \"Z\", \"one_by_one\"][1],\\\n            mode_update_Z=[\"sampling\", \"backprop\"][0], normalize_encoder_input=True, seed=0):\n        \"\"\" initialize MNMF_DP\n\n        Parameters:\n        -----------\n            speech_VAE: VAE\n                trained speech VAE network\n            n_noise: int\n                the number of noise sources\n            n_Z_iteration: int\n                the number of iteration for updating Z per global iteration\n            n_latent: int\n                the dimension of latent variable Z\n            n_basis_noise: int\n                the number of bases of each noise source\n            xp : numpy or cupy\n            init_SCM: str\n                how to initialize covariance matrix {unit, obs, ILRMA}\n            mode_update_parameter: str\n                'all' : update all the variables simultanesouly\n                'one_by_one' : update one by one\n            mode_update_Z: str\n                how to update latent variable Z {sampling, backprop}\n            normalize_encoder_input: boolean\n                normalize observation to initialize latent variable by feeding the observation into a encoder\n        \"\"\"\n        super(MNMF_DP, self).__init__(n_source=n_noise+1, xp=xp, init_SCM=init_SCM, mode_update_parameter=mode_update_parameter, seed=seed)\n        self.method_name = \"MNMF_DP\"\n        self.n_source, self.n_noise, self.n_speech = n_noise+1, n_noise, 1\n        self.n_basis_noise = n_basis_noise\n        self.n_Z_iteration = n_Z_iteration\n        self.n_latent = n_latent\n        self.speech_VAE = speech_VAE\n        self.mode_update_Z = mode_update_Z\n        self.normalize_encoder_input = normalize_encoder_input\n\n\n    def initialize_PSD(self):\n        self.W_noise_NnFK = self.xp.random.rand(self.n_noise, self.n_freq, self.n_basis_noise).astype(self.xp.float)\n        self.H_noise_NnKT = self.xp.random.rand(self.n_noise, self.n_basis_noise, self.n_time).astype(self.xp.float)\n\n        self.u_F = self.xp.ones(self.n_freq, dtype=self.xp.float) / self.n_freq\n        self.v_T = self.xp.ones(self.n_time, dtype=self.xp.float)\n\n        power_observation_FT = (self.xp.abs(self.X_FTM) ** 2).mean(axis=2)\n        if self.normalize_encoder_input:\n            power_observation_FT = power_observation_FT / power_observation_FT.sum(axis=0).mean()\n        self.Z_speech_DT = self.speech_VAE.encode_cupy(power_observation_FT.astype(self.xp.float32))\n        self.z_link_speech = Z_link(self.Z_speech_DT.T)\n        self.z_optimizer_speech = chainer.optimizers.Adam().setup(self.z_link_speech)\n        self.power_speech_FT = self.speech_VAE.decode_cupy(self.Z_speech_DT)\n\n        self.lambda_NFT = self.xp.zeros([self.n_source, self.n_freq, self.n_time]).astype(self.xp.float)\n        self.lambda_NFT[0] = self.u_F[:, None] * self.v_T[None] * self.power_speech_FT\n        self.lambda_NFT[1:] = self.W_noise_NnFK @ self.H_noise_NnKT\n\n\n    def make_filename_suffix(self):\n        self.filename_suffix = f\"N={self.n_noise}-it={self.n_iteration}-itZ={self.n_Z_iteration}-Kn={self.n_basis_noise}-D={self.n_latent}-init={self.init_SCM}-latent={self.mode_update_Z}-update={self.mode_update_parameter}\"\n\n        if hasattr(self, \"name_DNN\"):\n            self.filename_suffix += f\"-DNN={self.name_DNN}\"\n        if hasattr(self, \"file_id\"):\n            self.filename_suffix += f\"-ID={self.file_id}\"\n        print(\"param:\", self.filename_suffix)\n\n\n    def update(self):\n        if self.mode_update_parameter == \"one_by_one\":\n            self.update_axiliary_variable()\n            self.update_W_noise()\n            self.update_axiliary_variable()\n            self.update_H_noise()\n            self.update_axiliary_variable()\n            self.update_covarianceMatrix()\n            self.update_axiliary_variable()\n            self.update_U()\n            self.update_axiliary_variable()\n            self.update_V()\n            self.update_axiliary_variable()\n            self.update_Z_speech(calc_constant=True)\n            self.normalize()\n        elif self.mode_update_parameter == \"all\":\n            self.update_axiliary_variable_and_Z()\n            self.update_WH_noise()\n            self.update_covarianceMatrix()\n            self.update_UV()\n            self.update_Z_speech(calc_constant=False)\n            self.normalize()\n        elif self.mode_update_parameter == \"Z\":\n            self.update_axiliary_variable_and_Z()\n            self.update_WH_noise()\n            self.update_covarianceMatrix()\n            self.update_UV()\n            self.update_Z_speech(calc_constant=True)\n            self.normalize()\n\n\n    def update_axiliary_variable_and_Z(self):\n        Y_NFTMM = self.lambda_NFT[..., None, None] * self.covarianceMatrix_NFMM[:, :, None]\n        if self.xp == np:\n            self.Yinv_FTMM = np.linalg.inv(Y_NFTMM.sum(axis=0))\n            Yx_FTM1 = self.Yinv_FTMM @ self.X_FTM[..., None]\n            self.Yinv_X_Yinv_FTMM = Yx_FTM1 @ Yx_FTM1.conj().transpose(0, 1, 3, 2) # for reducing computational cost in case of CPU\n            cov_inv_FMM = np.linalg.inv(self.covarianceMatrix_NFMM[0])\n        else:\n            self.Yinv_FTMM = self.xp.linalg.inv(Y_NFTMM.sum(axis=0))\n            Yx_FTM1 = self.Yinv_FTMM @ self.X_FTM[..., None]\n            self.Yinv_X_Yinv_FTMM = Yx_FTM1 @ Yx_FTM1.conj().transpose(0, 1, 3, 2) # for reducing computational cost in case of CPU\n            cov_inv_FMM = self.xp.linalg.inv(self.covarianceMatrix_NFMM[0])\n\n        self.tr_Cov_Yinv_X_Yinv_NFT = self.xp.trace(self.covarianceMatrix_NFMM[:, :, None] @ self.Yinv_X_Yinv_FTMM[None], axis1=3, axis2=4).real\n        self.tr_Cov_Yinv_NFT = self.xp.trace(self.covarianceMatrix_NFMM[:, :, None] @ self.Yinv_FTMM[None], axis1=3, axis2=4).real\n\n        Phi_FTMM = Y_NFTMM[0] @ self.Yinv_FTMM\n        self.tr_Omega_Cov_FT = self.tr_Cov_Yinv_NFT[0]\n        self.tr_Cov_Phi_X_Phi_FT = self.xp.trace(cov_inv_FMM[:, None] @ Phi_FTMM @ self.XX_FTMM @ Phi_FTMM.transpose(0, 1, 3, 2).conj(), axis1=2, axis2=3).real\n        self.UV_FT = self.u_F[:, None] * self.v_T[None]\n\n\n    def update_UV(self):\n        a_1 = (self.u_F[:, None] * self.power_speech_FT * self.tr_Cov_Yinv_X_Yinv_NFT[0]).sum(axis=0)\n        b_1 = (self.u_F[:, None] * self.power_speech_FT * self.tr_Cov_Yinv_NFT[0]).sum(axis=0)\n\n        a_2 = (self.v_T[None] * self.power_speech_FT * self.tr_Cov_Yinv_X_Yinv_NFT[0]).sum(axis=1)\n        b_2 = (self.v_T[None] * self.power_speech_FT * self.tr_Cov_Yinv_NFT[0]).sum(axis=1)\n\n        self.v_T *= self.xp.sqrt(a_1 / b_1)\n        self.u_F *= self.xp.sqrt(a_2 / b_2)\n\n\n    def update_U(self):\n        a_1 = (self.v_T[None] * self.power_speech_FT * self.tr_Cov_Yinv_X_Yinv_NFT[0]).sum(axis=1)\n        b_1 = (self.v_T[None] * self.power_speech_FT * self.tr_Cov_Yinv_NFT[0]).sum(axis=1)\n        self.u_F *= self.xp.sqrt(a_1 / b_1)\n        self.lambda_NFT[0] = self.u_F[:, None] * self.v_T[None] * self.power_speech_FT\n\n\n    def update_V(self):\n        a_1 = (self.u_F[:, None] * self.power_speech_FT * self.tr_Cov_Yinv_X_Yinv_NFT[0]).sum(axis=0)\n        b_1 = (self.u_F[:, None] * self.power_speech_FT * self.tr_Cov_Yinv_NFT[0]).sum(axis=0)\n        self.v_T *= self.xp.sqrt(a_1 / b_1)\n        self.UV_FT = self.u_F[:, None] * self.v_T[None]\n        self.lambda_NFT[0] = self.u_F[:, None] * self.v_T[None] * self.power_speech_FT\n\n\n    def update_WH_noise(self):\n        a_1 = (self.H_noise_NnKT.transpose(0, 2, 1)[:, None] * self.tr_Cov_Yinv_X_Yinv_NFT[1:, :, :, None]).sum(axis=2) # Nn F K\n        b_1 = (self.H_noise_NnKT.transpose(0, 2, 1)[:, None] * self.tr_Cov_Yinv_NFT[1:, :, :, None]).sum(axis=2) # Nn F K\n\n        a_2 = (self.W_noise_NnFK[..., None] * self.tr_Cov_Yinv_X_Yinv_NFT[1:, :, None]).sum(axis=1) # Nn K T\n        b_2 = (self.W_noise_NnFK[..., None] * self.tr_Cov_Yinv_NFT[1:, :, None]).sum(axis=1) # Nn K T\n\n        self.W_noise_NnFK *= self.xp.sqrt(a_1 / b_1)\n        self.H_noise_NnKT *= self.xp.sqrt(a_2 / b_2)\n\n\n    def update_H_noise(self):\n        a_1 = (self.W_noise_NnFK[..., None] * self.tr_Cov_Yinv_X_Yinv_NFT[1:, :, None]).sum(axis=1) # Nn K T\n        b_1 = (self.W_noise_NnFK[..., None] * self.tr_Cov_Yinv_NFT[1:, :, None]).sum(axis=1) # Nn K T\n        self.H_noise_NnKT *= self.xp.sqrt(a_1 / b_1)\n        self.lambda_NFT[1:] = self.W_noise_NnFK @ self.H_noise_NnKT + EPS\n\n\n    def update_W_noise(self):\n        a_1 = (self.H_noise_NnKT.transpose(0, 2, 1)[:, None] * self.tr_Cov_Yinv_X_Yinv_NFT[1:, :, :, None]).sum(axis=2) # Nn F K\n        b_1 = (self.H_noise_NnKT.transpose(0, 2, 1)[:, None] * self.tr_Cov_Yinv_NFT[1:, :, :, None]).sum(axis=2) # Nn F K\n        self.W_noise_NnFK *= self.xp.sqrt(a_1 / b_1)\n        self.lambda_NFT[1:] = self.W_noise_NnFK @ self.H_noise_NnKT + EPS\n\n\n    def normalize(self):\n        mu_NF = self.xp.trace(self.covarianceMatrix_NFMM, axis1=2, axis2=3).real\n        self.covarianceMatrix_NFMM = self.covarianceMatrix_NFMM / mu_NF[:, :, None, None]\n        self.u_F *= mu_NF[0]\n        self.W_noise_NnFK *= mu_NF[1:][:, :, None]\n\n        nu = self.u_F.sum()\n        self.u_F /= nu\n        self.v_T *= nu\n\n        nu_NnK = self.W_noise_NnFK.sum(axis=1)\n        self.W_noise_NnFK /= nu_NnK[:, None]\n        self.H_noise_NnKT *= nu_NnK[:, :, None]\n\n        self.lambda_NFT[0] = self.u_F[:, None] * self.v_T[None] * self.power_speech_FT\n        self.lambda_NFT[1:] = self.W_noise_NnFK @ self.H_noise_NnKT + EPS\n\n\n    def loss_func_Z(self, z, vae, n):\n        power_FT = chf.exp(vae.decode(z).T) * self.UV_FT + EPS\n        if n == 0:\n            loss = chf.sum(1 / power_FT * self.tr_Cov_Phi_X_Phi_FT + power_FT * self.tr_Omega_Cov_FT)\n        else:\n            raise NotImplementedError\n        return loss\n\n\n    def update_Z_speech(self, var_propose_distribution=1e-4, calc_constant=True):\n        \"\"\"\n        Parameters:\n            var_propose_distribution: float\n                the variance of the propose distribution\n\n        Results:\n            self.Z_speech_DT: self.xp.array [ n_latent x T ]\n                the latent variable of each speech\n        \"\"\"\n        if calc_constant:\n            self.calculate_constant_for_update_Z()\n\n        if \"backprop\" in self.mode_update_Z: # acceptance rate is calculated from likelihood\n            for it in range(self.n_Z_iteration):\n                with chainer.using_config('train', False):\n                    self.z_optimizer_speech.update(self.loss_func_Z, self.z_link_speech.z, self.speech_VAE, 0)\n\n            self.Z_speech_DT = self.z_link_speech.z.data.T\n            self.power_speech_FT = self.speech_VAE.decode_cupy(self.Z_speech_DT)\n\n        if \"sampling\" in self.mode_update_Z:\n            log_var = self.xp.log(self.xp.ones_like(self.Z_speech_DT).astype(self.xp.float32) * var_propose_distribution)\n            Z_speech_old_DT = self.Z_speech_DT\n            lambda_speech_old_FT = self.speech_VAE.decode_cupy(Z_speech_old_DT) * self.UV_FT\n            for it in range(self.n_Z_iteration):\n                Z_speech_new_DT = chf.gaussian(Z_speech_old_DT, log_var).data\n                lambda_speech_new_FT = self.speech_VAE.decode_cupy(Z_speech_new_DT) * self.UV_FT\n                acceptance_rate =  self.xp.exp((-1 * (1/lambda_speech_new_FT - 1/lambda_speech_old_FT) * self.tr_Cov_Phi_X_Phi_FT -  (lambda_speech_new_FT - lambda_speech_old_FT) * self.tr_Omega_Cov_FT).sum(axis=0) - (Z_speech_new_DT ** 2 - Z_speech_old_DT ** 2).sum(axis=0)/2)\n                acceptance_boolean = self.xp.random.random([self.n_time]) < acceptance_rate\n                Z_speech_old_DT[:, acceptance_boolean] = Z_speech_new_DT[:, acceptance_boolean]\n                lambda_speech_old_FT[:, acceptance_boolean] = lambda_speech_new_FT[:, acceptance_boolean]\n\n            self.Z_speech_DT = Z_speech_old_DT\n            self.z_link_speech.z = chainer.Parameter(self.Z_speech_DT.T)\n            self.power_speech_FT = self.speech_VAE.decode_cupy(self.Z_speech_DT)\n\n\n    def calculate_constant_for_update_Z(self):\n        Y_NFTMM = self.lambda_NFT[..., None, None] * self.covarianceMatrix_NFMM[:, :, None]\n        if self.xp == np:\n            self.Yinv_FTMM = np.linalg.inv(Y_NFTMM.sum(axis=0))\n            cov_inv_FMM = np.linalg.inv(self.covarianceMatrix_NFMM[0])\n        else:\n            self.Yinv_FTMM = self.xp.linalg.inv(Y_NFTMM.sum(axis=0))\n            cov_inv_FMM = self.xp.linalg.inv(self.covarianceMatrix_NFMM[0])\n\n        Phi_FTMM = Y_NFTMM[0] @ self.Yinv_FTMM\n        self.tr_Omega_Cov_FT = self.xp.trace(self.covarianceMatrix_NFMM[0, :, None] @ self.Yinv_FTMM, axis1=2, axis2=3).real\n        self.tr_Cov_Phi_X_Phi_FT = self.xp.trace(cov_inv_FMM[:, None] @ Phi_FTMM @ self.XX_FTMM @ Phi_FTMM.transpose(0, 1, 3, 2).conj(), axis1=2, axis2=3).real\n\n\n    def save_parameter(self, filename):\n        param_list = [self.covarianceMatrix_NFMM, self.lambda_NFT, self.u_F, self.v_T, self.Z_speech_DT, self.W_noise_NnFK, self.H_noise_NnKT]\n\n        if self.xp != np:\n            param_list = [cuda.to_cpu(param) for param in param_list]\n\n        pic.dump(param_list, open(filename, \"wb\"))\n\n\n    def load_parameter(self, filename):\n        param_list = pic.load(open(filename, \"rb\"))\n        if self.xp != np:\n            param_list = [cuda.to_gpu(param) for param in param_list]\n\n        self.covarianceMatrix_NFMM, self.lambda_NFT, self.u_F, self.v_T, self.Z_speech_DT, self.W_noise_NnFK, self.H_noise_NnKT = param_list\n        self.n_source, self.n_freq, self.n_time = self.lambda_NFT.shape\n        self.n_mic = self.covarianceMatrix_NFMM.shape[-1]\n        self.n_latent = self.Z_speech_DT.shape[0]\n        self.n_noise, self.n_speech = self.n_source - 1, 1\n\n\n\nclass Z_link(chainer.link.Link):\n    def __init__(self, z):\n        super(Z_link, self).__init__()\n\n        with self.init_scope():\n            self.z = chainer.Parameter(z)\n\n\n\nif __name__ == \"__main__\":\n    import argparse\n    parser = argparse.ArgumentParser()\n    parser.add_argument(         'input_fileName', type= str, help='filename of the multichannel observed signals')\n    parser.add_argument(              '--file_id', type= str, default=\"None\", help='file id')\n    parser.add_argument(                  '--gpu', type= int, default=     0, help='GPU ID')##\n    parser.add_argument(                '--n_fft', type= int, default=  1024, help='number of frequencies')\n    parser.add_argument(              '--n_noise', type= int, default=     1, help='number of noise')\n    parser.add_argument(             '--n_latent', type= int, default=    16, help='dimention of encoded vector')\n    parser.add_argument(                '--n_mic', type= int, default=     8, help='number of microphones')\n    parser.add_argument(        '--n_basis_noise', type= int, default=    64, help='number of basis of noise (MODE_noise=NMF)')\n    parser.add_argument(             '--init_SCM', type=  str, default=\"obs\", help='unit, obs, ILRMA')\n    parser.add_argument(          '--n_iteration', type= int, default=    30, help='number of iteration')\n    parser.add_argument(        '--n_Z_iteration', type= int, default=    30, help='number of update Z iteration')\n    parser.add_argument(        '--mode_update_Z', type= str, default=\"sampling\", help='sampling, sampling2, backprop, backprop2, hybrid, hybrid2')\n    parser.add_argument('--mode_update_parameter', type= str, default= \"all\", help='all, one_by_one')\n    args = parser.parse_args()\n\n\n    sys.path.append(\"../DeepSpeechPrior\")\n    import network_VAE\n    model_fileName = f\"../DeepSpeechPrior/model-VAE-best-scale=gamma-D={args.n_latent}.npz\"\n    speech_VAE = network_VAE.VAE(n_latent=args.n_latent)\n    serializers.load_npz(model_fileName, speech_VAE)\n    name_DNN = \"VAE\"\n\n    if args.gpu < 0:\n        import numpy as xp\n    else:\n        import cupy as xp\n        print(\"Use GPU \" + str(args.gpu))\n        cuda.get_device_from_id(args.gpu).use()\n        speech_VAE.to_gpu()\n\n    wav, fs = sf.read(args.input_fileName)\n    wav = wav.T\n    M = min(args.n_mic, len(wav))\n    for m in range(M):\n        tmp = librosa.core.stft(wav[m], n_fft=args.n_fft, hop_length=int(args.n_fft/4))\n        if m == 0:\n            spec = np.zeros([tmp.shape[0], tmp.shape[1], M], dtype=np.complex)\n        spec[:, :, m] = tmp\n\n    separater = MNMF_DP(n_noise=args.n_noise, n_Z_iteration=args.n_Z_iteration, speech_VAE=speech_VAE, n_latent=args.n_latent, n_basis_noise=args.n_basis_noise, xp=xp, init_SCM=args.init_SCM, mode_update_parameter=args.mode_update_parameter, seed=0)\n\n    separater.load_spectrogram(spec)\n    separater.name_DNN = name_DNN\n    separater.file_id = args.file_id\n    separater.solve(n_iteration=args.n_iteration, save_likelihood=False, save_parameter=False, save_path=\"./\", interval_save_parameter=100)\n", "meta": {"hexsha": "729ec4b0c828a25dfaab98d546900e1f229d4c6d", "size": 17698, "ext": "py", "lang": "Python", "max_stars_repo_path": "FullRank_Model/MNMF_DP.py", "max_stars_repo_name": "klauszwei/SoundSourceSeparation", "max_stars_repo_head_hexsha": "0583aed0b0ac429e40a7e221c4d09711903868e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-23T06:38:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-23T06:38:33.000Z", "max_issues_repo_path": "FullRank_Model/MNMF_DP.py", "max_issues_repo_name": "klauszwei/SoundSourceSeparation", "max_issues_repo_head_hexsha": "0583aed0b0ac429e40a7e221c4d09711903868e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FullRank_Model/MNMF_DP.py", "max_forks_repo_name": "klauszwei/SoundSourceSeparation", "max_forks_repo_head_hexsha": "0583aed0b0ac429e40a7e221c4d09711903868e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.7548209366, "max_line_length": 277, "alphanum_fraction": 0.6515425472, "include": true, "reason": "import numpy,import cupy", "num_tokens": 4984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.31742627850202554, "lm_q1q2_score": 0.18572648192597144}}
{"text": "from __future__ import print_function\nimport os\nimport csv\nimport numpy as np\nfrom scipy.signal import decimate\nimport soundfile as sf\nimport librosa\nfrom keras.models import model_from_json\n\nimport argparse\n\n__author__ = 'Jakob Abesser'\n__copyright__ = 'J. Abesser, S. Balke, K. Frieler, M. Pfleiderer, M. Mueller, 2017'\n\n\nclass WalkingBassTranscription:\n    \"\"\" Algorithm for walking bass transcription in jazz ensemble recordings\n         [1] J. Abesser, S. Balke, K. Frieler, M. Pfleiderer, M. Mueller: Deep Learning for Jazz Walking Bass Transcription, AES conference\n             on Semantic Audio, Erlangen, Germany, 2017\n        Examples can be found here:\n         [2] http://www. audiolabs- erlangen.de/resources/MIR/ 2017-AES-WalkingBassTranscription/\n        This algorithm was used to create the beat-wise bass pitch values included in the Weimar Jazz Database\n         [3] http://jazzomat.hfm-weimar.de/dbformat/dboverview.html\n    \"\"\"\n\n    def __init__(self,\n                 hopsize=1024,\n                 blocksize=2048,\n                 pitch_range=(28, 67),  # E1 - G4\n                 bins_per_octave=12):\n        \"\"\" Initialize transcriber\n        Args:\n            hopsize (int): Hopsize in samples\n            blocksize (int): Blocksize in samples\n            pitch_range (tuple of int): Lower and upper pitch range\n            bins_per_octave (int): Frequency axis resolution (number of bins per octave)\n        \"\"\"\n        self.hopsize = hopsize\n        self.blocksize = blocksize\n        self.pitch_range = pitch_range\n        self.bins_per_octave = bins_per_octave\n\n        # generate logarithmically spaced frequency axis\n        delta_midi = 12. / self.bins_per_octave\n        self.f_axis_midi = np.arange(self.pitch_range[0],\n                                     self.pitch_range[1] + delta_midi,\n                                     delta_midi, dtype=int)\n        tuning_freq_hz = 440.\n        self.f_axis_hz = tuning_freq_hz * 2 ** ((self.f_axis_midi - 69.) / 12.)\n\n        # load DNN model\n        self.model_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data')\n        self.model = None\n        self._load_model()\n\n    def _load_model(self):\n        \"\"\" Load DNN model by loading architecture and weights and initialize model accordingly\n        \"\"\"\n        fn_model_architecture = os.path.join(self.model_path, 'model.yaml')\n        fn_model_weights = os.path.join(self.model_path, 'weights.h5')\n        with open(fn_model_architecture, 'r') as f:\n            model_json = f.read()\n        self.model = model_from_json(model_json)\n        self.model.load_weights(fn_model_weights)\n\n    def transcribe(self,\n                   fn_wav,\n                   dir_out,\n                   beat_times=None,\n                   tuning_frequency_hz=440.,\n                   threshold=0.2,\n                   aggregation='beat'):\n        \"\"\" Transcribe audio file\n        Args:\n            fn_wav (string): WAV file name\n            dir_out (string): Directory to store results (if None, same directory as fn_wav is used)\n            beat_times (ndarray): Beat times in seconds (if None, only bass saliency is extracted)\n            tuning_frequency_hz (float): Tuning frequency (Hz)\n            threshold (float): Decision treshold\n            aggregation (string): Aggregation method. Possible values are 'beat' (beat-wise aggregation)\"\n                                  \"and 'flex-q' (dynamic estimation of most likely tatum per beat)\n        Returns:\n            pitch_saliency (2d ndarray): Bass pitch saliency (num_pitches x num_frames)\n            midi_axis (ndarray): MIDI pitch values of pitch axis\n            time_axis_sec (ndarray): Time frames [s]\n        \"\"\"\n        tuning_dev_in_semitones = np.log2(tuning_frequency_hz/440.)*12\n\n        # load audio file\n        x, fs = sf.read(fn_wav)\n\n        # convert to mono\n        if x.ndim == 2:\n            x = np.mean(x, axis=1)\n\n        # signal decimation\n        if fs != 22050.:\n            decimation_factor = int(np.round(fs / 22050.))\n            x = decimate(x, decimation_factor, zero_phase=True)\n            fs /= decimation_factor\n\n        # compute contant-Q spectrogram\n        mag_spec = np.abs(librosa.cqt(x,\n                                      sr=fs,\n                                      hop_length=self.hopsize,\n                                      fmin=440*2**((self.pitch_range[0]-69)/12.),\n                                      n_bins=self.pitch_range[1] - self.pitch_range[0] + 1,\n                                      bins_per_octave=self.bins_per_octave,\n                                      tuning=tuning_dev_in_semitones))\n\n        num_frames = mag_spec.shape[1]\n        time_axis_sec = (np.arange(num_frames) + .5) * self.hopsize / fs\n\n        # frame stacking\n        features = frame_stacking(mag_spec.T, 2)\n\n        # feature normalization\n        features = normalize_euclidean(features)\n\n        # model prediction\n        pitch_saliency = self.model.predict(features)\n\n        # save saliency matrix\n        base_name = os.path.basename(fn_wav).replace('.wav', '')\n        np.save(\n            os.path.join(dir_out, '{}_bass_pitch_saliency.npy'.format(base_name)),\n            pitch_saliency\n        )\n\n        # export most salient bass track as CSV file\n        with open(os.path.join(dir_out, '{}_bass_f0.csv'.format(base_name)), 'w') as fhandle:\n            writer = csv.writer(fhandle, delimiter=',')\n            for t in range(pitch_saliency.shape[0]):\n                i = np.argmax(pitch_saliency[t])\n                time_val = time_axis_sec[t]\n                if pitch_saliency[t, i] >= threshold:\n                    freq_val = self.f_axis_hz[i]\n                else:\n                    freq_val = -1*self.f_axis_hz[i]\n\n                writer.writerow([time_val, freq_val])\n\n        # aggregate pitch saliency to note events\n        if beat_times is not None:\n\n            onset_sec, offset_sec, pitch = aggregate_saliency_to_notes(pitch_saliency,\n                                                                       self.f_axis_midi,\n                                                                       time_axis_sec,\n                                                                       beat_times,\n                                                                       method=aggregation,\n                                                                       threshold=threshold)\n\n            # export score to be imported to Sonic Visualiser as note layer\n            score_mat = np.vstack((onset_sec, offset_sec, pitch)).T\n            np.savetxt(os.path.join(dir_out, '{}_bass_line.csv'.format(base_name)),\n                       score_mat,\n                       fmt='%4.4f,%4.4f,%d')\n\n        return pitch_saliency, self.f_axis_midi, time_axis_sec\n\n\ndef aggregate_saliency_to_notes(pitch_saliency,\n                                freq_bins_midi,\n                                frame_times_sec,\n                                beat_times_sec,\n                                method='beat',\n                                num_tatums_per_beat=None,\n                                threshold=0.2):\n    \"\"\" Aggregate frame-wise pitch saliency values to note events based on given beat times\n    Args:\n        pitch_saliency (2d np.ndarray): Frame-wise pitch saliency (num_frames x num_pitches)\n        freq_bins_midi (np.ndarray): MIDI pitch values (num_pitches)\n        frame_times_sec (np.ndarray): Frame times in seconds (num_pitches)\n        beat_times_sec (np.ndarray): Beat times in seconds (num_beats)\n        method (string): Aggregation method\n        aggregation (string): Aggregation method. Possible values are 'beat' (beat-wise aggregation)\"\n                              \"and 'flex-q' (dynamic estimation of most likely tatum per beat)\n        num_tatums_per_beat (tuple): Number of tatums per beats - different beat subdivisions that are tested if\n                                     aggregation == 'flex-q' (default: (1, 2, 3))\n        threshold (float): Minimum saliency threshold to detect notes\n    Returns:\n        onset (np.ndarray): Note-wise onset times in seconds\n        offset (np.ndarray): Note-wise offset times in seconds\n        pitch (np.ndarray): Note-wise pitch values\n    \"\"\"\n    assert method in ('beat', 'flex-q'), \"Non-valid value for method!\"\n\n    if num_tatums_per_beat is None:\n        num_tatums_per_beat = (1, 3)\n    num_subdivisions = len(num_tatums_per_beat)\n\n    num_beats = len(beat_times_sec)\n    pitch = []\n    onset = []\n    offset = []\n\n    # map beat times from seconds to frames\n    beat_frames = [closest_bin(frame_times_sec, _) for _ in beat_times_sec]\n\n    # iterate over beats\n    for b in range(num_beats-1):\n\n        if method == 'beat':\n            # take most likely pitch\n            beat_pitch_saliency = np.mean(\n                pitch_saliency[beat_frames[b]: beat_frames[b + 1], :], axis=0\n            )\n\n            # if saliency exceeds threshold > store note\n            if np.max(beat_pitch_saliency) > threshold:\n                best_pitch_idx = np.argmax(beat_pitch_saliency)\n                onset.append(beat_times_sec[b])\n                offset.append(beat_times_sec[b+1])\n                pitch.append(freq_bins_midi[best_pitch_idx])\n\n        elif method == 'flex-q':\n\n            curr_onset = []\n            curr_offset = []\n            curr_pitch = []\n\n            scores = np.zeros(num_subdivisions)\n            # try different tatum subdivisions\n            for s, sub_div in enumerate(num_tatums_per_beat):\n\n                scores[s], _, _ = get_sub_beat_saliency(pitch_saliency,\n                                                        beat_times_sec[b],\n                                                        beat_times_sec[b + 1],\n                                                        frame_times_sec,\n                                                        sub_div)\n\n            # get optimal subdivision from highest score\n            sub_div_opt = num_tatums_per_beat[np.argmax(scores)]\n\n            # use optimal subdivision to extract note events\n            _, sub_beat_saliency, sub_beat_times_sec = get_sub_beat_saliency(pitch_saliency,\n                                                                             beat_times_sec[b],\n                                                                             beat_times_sec[b + 1],\n                                                                             frame_times_sec,\n                                                                             sub_div_opt)\n\n            pitch_idx_opt = np.argmax(sub_beat_saliency, axis=1)\n            saliency_opt = np.max(sub_beat_saliency, axis=1)\n\n            # check in which tatum segments, the saliency exceeds the threshold\n            is_valid = saliency_opt >= threshold\n\n            for n in range(sub_div_opt):\n                curr_onset.append(sub_beat_times_sec[n])\n                curr_offset.append(sub_beat_times_sec[n+1])\n                curr_pitch.append(freq_bins_midi[pitch_idx_opt[n]])\n\n            curr_onset = np.array(curr_onset)\n            curr_offset = np.array(curr_offset)\n            curr_pitch = np.array(curr_pitch)\n\n            if np.all(is_valid):\n                # merge adjacent notes with same pitch as we can't do onset detection solely based on saliency\n                if len(np.unique(curr_pitch)) == 1:\n                    curr_pitch = np.array((curr_pitch[0],))\n                    curr_onset = np.array((curr_onset[0],))\n                    curr_offset = np.array((curr_offset[-1],))\n            else:\n                curr_onset = curr_onset[is_valid]\n                curr_offset = curr_offset[is_valid]\n                curr_pitch = curr_pitch[is_valid]\n\n            onset.append(curr_onset)\n            offset.append(curr_offset)\n            pitch.append(curr_pitch)\n\n    if method == 'beat':\n        onset = np.array(onset)\n        offset = np.array(offset)\n        pitch = np.array(pitch)\n    elif method == 'flex-q':\n        onset = np.concatenate(onset)\n        offset = np.concatenate(offset)\n        pitch = np.concatenate(pitch).astype(int)\n\n    return onset, offset, pitch\n\n\ndef get_sub_beat_saliency(pitch_saliency,\n                          start_time_sec,\n                          end_time_sec,\n                          frame_times_sec,\n                          sub_div):\n    \"\"\" Get pitch saliency and likelihood score for subdivision of given segment in pitch saliency matrix\n    Args:\n        pitch_saliency (2d np.ndarray): Frame-wise pitch saliency (num_frames x num_pitches)\n        start_time_sec (float): Start time in seconds\n        end_time_sec (float): End time in seconds\n        frame_times_sec (np.ndarray): Frame times in seconds\n        sub_div (int, >= 1): Number of subdivisions (e.g. 2 -> given segment is divided into 2 subsegments of equal\n                             duration)\n    Returns:\n        score (float): Likelihood score for current subdivision based on difference between highest and second\n                       highest saliency value\n        sub_beat_saliency (2d np.ndarray): Average pitch saliency vectors for each sub beat (tatum level) (num_sub_beats x num_pitches)\n        sub_beat_times_sec (np.ndarray): Boundary times in seconds for subbeats (num_sub_beats + 1)\n    \"\"\"\n    num_pitches = pitch_saliency.shape[1]\n    beat_len_sec = end_time_sec - start_time_sec\n    sub_beat_len_sec = beat_len_sec / sub_div\n    # sub_beat times\n    sub_beat_times_sec = np.arange(sub_div + 1) * sub_beat_len_sec + start_time_sec\n    assert len(sub_beat_times_sec) == sub_div + 1\n    # seconds to frames\n    sub_beat_times_frames = [closest_bin(frame_times_sec, _) for _ in sub_beat_times_sec]\n    sub_beat_saliency = np.zeros((sub_div, num_pitches))\n    for sb in range(sub_div):\n        sub_beat_saliency[sb, :] = get_segment_saliency(pitch_saliency,\n                                                        sub_beat_times_frames[sb],\n                                                        sub_beat_times_frames[sb + 1])\n\n    # sort pitch saliency values in descending order accross pitches\n    sub_beat_saliency_sorted = -np.sort(-sub_beat_saliency, axis=1)\n    score = np.mean(sub_beat_saliency_sorted[:, 0] - sub_beat_saliency_sorted[:, 1])\n\n    return score, sub_beat_saliency, sub_beat_times_sec\n\n\ndef get_segment_saliency(pitch_saliency, start_frame, end_frame):\n    \"\"\" Get average saliency over segment\n    Args:\n        pitch_saliency (2d np.ndarray): Frame-wise pitch saliency (num_frames x num_pitches)\n        start_frame (int): Start frame\n        end_frame (int): End frame\n    Returns:\n        segment_pitch_saliency (np.ndarray): Averaged pitch saliency over segment (num_pitches)\n    \"\"\"\n    return np.mean(pitch_saliency[start_frame:end_frame, :], axis=0)\n\n\ndef closest_bin(axis, val):\n    \"\"\" Return closest bin in axis to value\n    Args:\n        axis (ndarray): Axis\n        val (float / int): Value\n    Return:\n        idx (int): Closest index in axis to val\n    \"\"\"\n    return np.argmin(np.abs(axis-val))\n\n\ndef frame_stacking(x, context_size):\n    \"\"\" Stack frames to incorporate some temporal context\n    Args:\n        x (2d ndarray): Feature matrix (num_frames x num_features)\n        context_size (int): Context size for frame stacking (e.g. context size of 2 means that we stack 5 frames)\n    Return\n        x_stacked (2d ndarray): Stacked feature matrix (num_frames x ((context_size*2 + 1)*num_features)\n    \"\"\"\n    num_frames = x.shape[0]\n    c = 2 * context_size + 1\n    assert c < num_frames, \"Context size is too big for number of frames! Stacking not possible.\"\n    num_frames_after = num_frames - c\n    x_new = []\n    for start_frame in range(0, c):\n        x_new.append(x[start_frame:start_frame + num_frames_after + 1, :])\n    x = np.hstack(x_new)\n    x = np.vstack((np.random.random((context_size, x.shape[1])), x, np.random.random((context_size, x.shape[1]))))\n\n    return x\n\n\ndef normalize_euclidean(x):\n    \"\"\" Frame-wise feature normalization to mean euclidean norm\n    Args:\n        x (2d ndarray): Feature matrix (num_frames x num_feat_dims)\n    Returns:\n        x (2d ndarray): Feature matrix (num_frames x num_feat_dims)\n    \"\"\"\n    # avoid nans\n    idx_zero = np.where(np.sum(x, axis=1) == 0)[0]\n    for idx in idx_zero:\n        x[idx, :] = .000001\n    return x / np.sqrt(np.sum(np.square(x), axis=1, keepdims=True))\n\n\ndef main(args):\n    \"\"\"Main method to run transcription\n    \"\"\"\n\n    # parse beats_file argument\n    if args.beats_file == '':\n        beat_times = None\n    elif not os.path.exists(args.beats_file):\n        beat_times = None\n        print(\"[Warning] Could not find provided beats file.\")\n    else:\n        beat_times = np.loadtxt(args.beat_file, delimiter=',', usecols=[0])    \n\n    transcriber = WalkingBassTranscription()\n\n    transcriber.transcribe(args.input_wav,\n                           dir_out=args.output_dir,\n                           beat_times=beat_times,\n                           threshold=args.threshold,\n                           aggregation=args.aggregation)\n\n    print('Finished bass line transcription! :)')\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description=\"Predict walking bass salience or f0\"\n                    \"from and audio file.\")\n    parser.add_argument(\"input_wav\",\n                        type=str,\n                        help=\"Path to input wav file.\")\n    parser.add_argument(\"output_dir\",\n                        type=str,\n                        help=\"Path to save location of bass transcription.\")\n    parser.add_argument(\"-b\", \"--beats_file\",\n                        type=str,\n                        default='',\n                        help=\"Path to beat annotation file. If not given, \"\n                        \"does not produce note-level outputs.\")\n    parser.add_argument(\"-t\", \"--threshold\",\n                        type=float,\n                        default=0.2,\n                        help=\"Amplitude threshold. Only used when \"\n                        \"output_format is singlef0 or multif0\")\n    parser.add_argument(\"-a\", \"--aggregation\",\n                        type=str,\n                        default=\"beat\",\n                        help=\"Aggregation method. Possible values are 'beat' (beat-wise aggregation)\"\n                        \"and 'flex-q' (dynamic estimation of most likely tatum per beat)\")\n\n    main(parser.parse_args())\n", "meta": {"hexsha": "25b23ec97134cefe8fa02d92b296c1439b857f51", "size": 18422, "ext": "py", "lang": "Python", "max_stars_repo_path": "transcriber.py", "max_stars_repo_name": "jakobabesser/walking_bass_transcription_dnn", "max_stars_repo_head_hexsha": "2de16161344f8014864f2f2f9b0fbfadeace7136", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2017-06-27T10:35:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-13T23:46:25.000Z", "max_issues_repo_path": "transcriber.py", "max_issues_repo_name": "jakobabesser/walking_bass_transcription_dnn", "max_issues_repo_head_hexsha": "2de16161344f8014864f2f2f9b0fbfadeace7136", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-01-28T18:09:10.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-28T18:09:10.000Z", "max_forks_repo_path": "transcriber.py", "max_forks_repo_name": "jakobabesser/walking_bass_transcription_dnn", "max_forks_repo_head_hexsha": "2de16161344f8014864f2f2f9b0fbfadeace7136", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-01-15T19:31:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T00:02:27.000Z", "avg_line_length": 42.545034642, "max_line_length": 139, "alphanum_fraction": 0.571544892, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.18572647896276737}}
{"text": "# /usr/bin/python\n\nfrom __future__ import print_function\n\nimport argparse\nimport torch\nimport pickle\nimport numpy as np\nimport os\nimport math\nimport random\nimport sys\nimport matplotlib.pyplot as plt\nimport data\nimport scipy.io\nimport pyLDAvis\n\nfrom navec import Navec\n\nfrom torch import nn, optim\nfrom torch.nn import functional as F\n\nfrom etm import ETM\nfrom utils import (nearest_neighbors, get_topic_coherence, get_topic_diversity,\n                   get_coherence_gensim, get_dictionary, get_topics)\n\nparser = argparse.ArgumentParser(description='The Embedded Topic Model')\n\n### data and file related arguments\nparser.add_argument('--dataset', type=str, default='20ng', help='name of corpus')\nparser.add_argument('--data_path', type=str, default='data/20ng', help='directory containing data')\nparser.add_argument('--emb_path', type=str, default='data/20ng_embeddings.txt',\n                    help='directory containing word embeddings')\nparser.add_argument('--save_path', type=str, default='./results', help='path to save results')\nparser.add_argument('--batch_size', type=int, default=1000, help='input batch size for training')\n\n### model-related arguments\nparser.add_argument('--num_topics', type=int, default=50, help='number of topics')\nparser.add_argument('--rho_size', type=int, default=300, help='dimension of rho')\nparser.add_argument('--emb_size', type=int, default=300, help='dimension of embeddings')\nparser.add_argument('--t_hidden_size', type=int, default=800, help='dimension of hidden space of q(theta)')\nparser.add_argument('--theta_act', type=str, default='relu',\n                    help='tanh, softplus, relu, rrelu, leakyrelu, elu, selu, glu)')\nparser.add_argument('--train_embeddings', type=int, default=0, help='whether to fix rho or train it')\n\n### optimization-related arguments\nparser.add_argument('--lr', type=float, default=0.005, help='learning rate')\nparser.add_argument('--lr_factor', type=float, default=4.0, help='divide learning rate by this...')\nparser.add_argument('--epochs', type=int, default=20, help='number of epochs to train...150 for 20ng 100 for others')\nparser.add_argument('--mode', type=str, default='train', help='train or eval model')\nparser.add_argument('--optimizer', type=str, default='adam', help='choice of optimizer')\nparser.add_argument('--seed', type=int, default=2019, help='random seed (default: 1)')\nparser.add_argument('--enc_drop', type=float, default=0.0, help='dropout rate on encoder')\nparser.add_argument('--clip', type=float, default=0.0, help='gradient clipping')\nparser.add_argument('--nonmono', type=int, default=10, help='number of bad hits allowed')\nparser.add_argument('--wdecay', type=float, default=1.2e-6, help='some l2 regularization')\nparser.add_argument('--anneal_lr', type=int, default=0, help='whether to anneal the learning rate or not')\nparser.add_argument('--bow_norm', type=int, default=1, help='normalize the bows or not')\n\n### evaluation, visualization, and logging-related arguments\nparser.add_argument('--num_words', type=int, default=10, help='number of words for topic viz')\nparser.add_argument('--log_interval', type=int, default=2, help='when to log training')\nparser.add_argument('--visualize_every', type=int, default=10, help='when to visualize results')\nparser.add_argument('--eval_batch_size', type=int, default=1000, help='input batch size for evaluation')\nparser.add_argument('--load_from', type=str, default='', help='the name of the ckpt to eval from')\nparser.add_argument('--tc', type=int, default=0, help='whether to compute topic coherence or not')\nparser.add_argument('--td', type=int, default=0, help='whether to compute topic diversity or not')\n\nargs = parser.parse_args()\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nprint('\\n')\nnp.random.seed(args.seed)\ntorch.manual_seed(args.seed)\nif torch.cuda.is_available():\n    torch.cuda.manual_seed(args.seed)\n\n## get data\n# 1. vocabulary\nvocab, train, valid, test = data.get_data(os.path.join(args.data_path))\nvocab_size = len(vocab)\nargs.vocab_size = vocab_size\n\n# 1. training data\ntrain_tokens = train['tokens']\ntrain_counts = train['counts']\nargs.num_docs_train = len(train_tokens)\n\n# 2. dev set\nvalid_tokens = valid['tokens']\nvalid_counts = valid['counts']\nargs.num_docs_valid = len(valid_tokens)\n\n# 3. test data\ntest_tokens = test['tokens']\ntest_counts = test['counts']\nargs.num_docs_test = len(test_tokens)\ntest_1_tokens = test['tokens_1']\ntest_1_counts = test['counts_1']\nargs.num_docs_test_1 = len(test_1_tokens)\ntest_2_tokens = test['tokens_2']\ntest_2_counts = test['counts_2']\nargs.num_docs_test_2 = len(test_2_tokens)\n\nembeddings = None\nif not args.train_embeddings:\n    emb_path = args.emb_path\n    navec = Navec.load(emb_path)\n    # vect_path = os.path.join(args.data_path.split('/')[0], 'embeddings.pkl')\n    # vectors = {}\n    # with open(emb_path, 'rb') as f:\n    #    for l in f:\n    #        line = l.decode().split()\n    #        word = line[0]\n    #        if word in vocab:\n    #            vect = np.array(line[1:]).astype(np.float)\n    #            vectors[word] = vect\n    embeddings = np.zeros((vocab_size, args.emb_size))\n    words_found = 0\n    for i, word in enumerate(vocab):\n        try:\n            embeddings[i] = navec[word]\n            words_found += 1\n        except KeyError:\n            embeddings[i] = np.random.normal(scale=0.6, size=(args.emb_size,))\n    embeddings = torch.from_numpy(embeddings).to(device)\n    args.embeddings_dim = embeddings.size()\n\nprint('=*' * 100)\nprint('Training an Embedded Topic Model on {} with the following settings: {}'.format(args.dataset.upper(), args))\nprint('=*' * 100)\n\n## define checkpoint\nif not os.path.exists(args.save_path):\n    os.makedirs(args.save_path)\n\nif args.mode in ['eval', 'ppx']:\n    ckpt = args.load_from\nelse:\n    ckpt = os.path.join(args.save_path,\n                        'etm_{}_K_{}_Htheta_{}_Optim_{}_Clip_{}_ThetaAct_{}_Lr_{}_Bsz_{}_RhoSize_{}_trainEmbeddings_{}'.format(\n                            args.dataset, args.num_topics, args.t_hidden_size, args.optimizer, args.clip,\n                            args.theta_act,\n                            args.lr, args.batch_size, args.rho_size, args.train_embeddings))\n\n## define model and optimizer\nmodel = ETM(args.num_topics, vocab_size, args.t_hidden_size, args.rho_size, args.emb_size,\n            args.theta_act, embeddings, args.train_embeddings, args.enc_drop).to(device)\n\nprint('model: {}'.format(model))\n\nif args.optimizer == 'adam':\n    optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.wdecay)\nelif args.optimizer == 'adagrad':\n    optimizer = optim.Adagrad(model.parameters(), lr=args.lr, weight_decay=args.wdecay)\nelif args.optimizer == 'adadelta':\n    optimizer = optim.Adadelta(model.parameters(), lr=args.lr, weight_decay=args.wdecay)\nelif args.optimizer == 'rmsprop':\n    optimizer = optim.RMSprop(model.parameters(), lr=args.lr, weight_decay=args.wdecay)\nelif args.optimizer == 'asgd':\n    optimizer = optim.ASGD(model.parameters(), lr=args.lr, t0=0, lambd=0., weight_decay=args.wdecay)\nelse:\n    print('Defaulting to vanilla SGD')\n    optimizer = optim.SGD(model.parameters(), lr=args.lr)\n\ntrain_losses = []\nval_losses = []\n\n\ndef train(epoch):\n    model.train()\n    acc_loss = 0\n    acc_kl_theta_loss = 0\n    cnt = 0\n    indices = torch.randperm(args.num_docs_train)\n    indices = torch.split(indices, args.batch_size)\n    for idx, ind in enumerate(indices):\n        optimizer.zero_grad()\n        model.zero_grad()\n        data_batch = data.get_batch(train_tokens, train_counts, ind, args.vocab_size, device)\n        sums = data_batch.sum(1).unsqueeze(1)\n        if args.bow_norm:\n            normalized_data_batch = data_batch / sums\n        else:\n            normalized_data_batch = data_batch\n        recon_loss, kld_theta = model(data_batch, normalized_data_batch)\n        total_loss = recon_loss + kld_theta\n        total_loss.backward()\n\n        if args.clip > 0:\n            torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip)\n        optimizer.step()\n\n        acc_loss += torch.sum(recon_loss).item()\n        acc_kl_theta_loss += torch.sum(kld_theta).item()\n        cnt += 1\n\n        if idx % args.log_interval == 0 and idx > 0:\n            cur_loss = round(acc_loss / cnt, 2)\n            cur_kl_theta = round(acc_kl_theta_loss / cnt, 2)\n            cur_real_loss = round(cur_loss + cur_kl_theta, 2)\n\n            # print('Epoch: {} .. batch: {}/{} .. LR: {} .. KL_theta: {} .. Rec_loss: {} .. NELBO: {}'.format(\n            # epoch, idx, len(indices), optimizer.param_groups[0]['lr'], cur_kl_theta, cur_loss, cur_real_loss))\n\n    cur_loss = round(acc_loss / cnt, 2)\n    cur_kl_theta = round(acc_kl_theta_loss / cnt, 2)\n    cur_real_loss = round(cur_loss + cur_kl_theta, 2)\n\n    train_losses.append(cur_loss)\n\n    print('*' * 100)\n    print('Epoch----->{} .. LR: {} .. KL_theta: {} .. Rec_loss: {} .. NELBO: {}'.format(\n        epoch, optimizer.param_groups[0]['lr'], cur_kl_theta, cur_loss, cur_real_loss))\n    print('*' * 100)\n\n\ndef visualize(m, show_emb=True):\n    if not os.path.exists('./results'):\n        os.makedirs('./results')\n\n    m.eval()\n\n    queries = ['россия', 'человек', 'компьютер', 'спорт', 'религия', 'любовь',\n               'доллар', 'правительство', 'здоровье', 'семья']\n\n    ## visualize topics using monte carlo\n    with torch.no_grad():\n        print('#' * 100)\n        print('Visualize topics...')\n        topics_words = []\n        gammas = m.get_beta()\n        for k in range(args.num_topics):\n            gamma = gammas[k]\n            top_words = list(gamma.cpu().numpy().argsort()[-args.num_words + 1:][::-1])\n            topic_words = [vocab[a] for a in top_words]\n            topics_words.append(' '.join(topic_words))\n            print('Topic {}: {}'.format(k, topic_words))\n\n        if show_emb:\n            ## visualize word embeddings by using V to get nearest neighbors\n            print('#' * 100)\n            print('Visualize word embeddings by using output embedding matrix')\n            try:\n                embeddings = m.rho.weight  # Vocab_size x E\n            except:\n                embeddings = m.rho  # Vocab_size x E\n            neighbors = []\n            for word in queries:\n                print('word: {} .. neighbors: {}'.format(\n                    word, nearest_neighbors(word, embeddings, vocab)))\n            print('#' * 100)\n\n\ndef evaluate(m, source, tc=False, td=False):\n    \"\"\"Compute perplexity on document completion.\n    \"\"\"\n    m.eval()\n    with torch.no_grad():\n        if source == 'val':\n            indices = torch.split(torch.tensor(range(args.num_docs_valid)), args.eval_batch_size)\n            tokens = valid_tokens\n            counts = valid_counts\n        else:\n            indices = torch.split(torch.tensor(range(args.num_docs_test)), args.eval_batch_size)\n            tokens = test_tokens\n            counts = test_counts\n\n        ## get \\beta here\n        beta = m.get_beta()\n\n        ### do dc and tc here\n        acc_loss = 0\n        cnt = 0\n        indices_1 = torch.split(torch.tensor(range(args.num_docs_test_1)), args.eval_batch_size)\n        for idx, ind in enumerate(indices_1):\n            ## get theta from first half of docs\n            data_batch_1 = data.get_batch(test_1_tokens, test_1_counts, ind, args.vocab_size, device)\n            sums_1 = data_batch_1.sum(1).unsqueeze(1)\n            if args.bow_norm:\n                normalized_data_batch_1 = data_batch_1 / sums_1\n            else:\n                normalized_data_batch_1 = data_batch_1\n            theta, _ = m.get_theta(normalized_data_batch_1)\n\n            ## get prediction loss using second half\n            data_batch_2 = data.get_batch(test_2_tokens, test_2_counts, ind, args.vocab_size, device)\n            sums_2 = data_batch_2.sum(1).unsqueeze(1)\n            res = torch.mm(theta, beta)\n            preds = torch.log(res)\n            recon_loss = -(preds * data_batch_2).sum(1)\n\n            loss = recon_loss / sums_2.squeeze()\n            loss = loss.mean().item()\n            acc_loss += loss\n            cnt += 1\n        cur_loss = acc_loss / cnt\n        print('{} loss: {}'.format(source.upper(), cur_loss))\n        val_losses.append(cur_loss)\n\n        ppl_dc = round(math.exp(cur_loss), 1)\n        print('*' * 100)\n        print('{} Doc Completion PPL: {}'.format(source.upper(), ppl_dc))\n        print('*' * 100)\n        if tc or td:\n            beta = beta.data.cpu().numpy()\n            if tc:\n                print('Computing topic coherence...')\n                get_topic_coherence(beta, train_tokens, vocab)\n            if td:\n                print('Computing topic diversity...')\n                get_topic_diversity(beta, 25)\n        return ppl_dc\n\n\ndef prepare_viz_data(phi, theta, n_wd, vocab):\n    theta = theta / theta.sum(axis=1, keepdims=1)\n    data = {'topic_term_dists': phi,\n            'doc_topic_dists': theta,\n            'doc_lengths': n_wd.sum(axis=1).tolist(),\n            'vocab': vocab,\n            'term_frequency': n_wd.sum(axis=0).tolist()}\n    return data\n\n\ndef show_viz(model, data_batch, vocab):\n    phi = model.get_beta().cpu().numpy()\n    theta, _ = model.get_theta(data_batch)\n    theta = theta.cpu().numpy()\n    model_data = prepare_viz_data(phi, theta, data_batch, vocab)\n    model_viz = pyLDAvis.prepare(**model_data)\n    pyLDAvis.save_html(model_viz, 'etm_vis.html')\n    print('\\n\\nVisualization has been saved')\n\n\ndef plot_curves():\n    fig, axs = plt.subplots(1, 2)\n    axs[0].plot(train_losses)\n    axs[0].set_title('train')\n    axs[1].plot(val_losses)\n    axs[1].set_title('val')\n    plt.ylabel('loss values')\n    plt.xlabel('epoch')\n    plt.show()\n\n\nif args.mode == 'train':\n    ## train model on data\n    best_epoch = 0\n    best_val_ppl = 1e9\n    all_val_ppls = []\n    print('\\n')\n    print('Visualizing model quality before training...')\n    visualize(model)\n    print('\\n')\n    for epoch in range(1, args.epochs):\n        train(epoch)\n        val_ppl = evaluate(model, 'val')\n        if val_ppl < best_val_ppl:\n            with open(ckpt, 'wb') as f:\n                torch.save(model, f)\n            best_epoch = epoch\n            best_val_ppl = val_ppl\n        else:\n            ## check whether to anneal lr\n            lr = optimizer.param_groups[0]['lr']\n            if args.anneal_lr and (\n                    len(all_val_ppls) > args.nonmono and val_ppl > min(all_val_ppls[:-args.nonmono]) and lr > 1e-5):\n                optimizer.param_groups[0]['lr'] /= args.lr_factor\n        if epoch % args.visualize_every == 0:\n            visualize(model)\n        all_val_ppls.append(val_ppl)\n\n    plot_curves()\n\n    with open(ckpt, 'rb') as f:\n        model = torch.load(f)\n    model = model.to(device)\n    val_ppl = evaluate(model, 'val')\nelif args.mode == 'eval':\n    with open(ckpt, 'rb') as f:\n        model = torch.load(f)\n    model = model.to(device)\n    model.eval()\n\n    with torch.no_grad():\n        ## get document completion perplexities\n        test_ppl = evaluate(model, 'test', tc=args.tc, td=args.td)\n\n        ## get most used topics\n        indices = torch.tensor(range(args.num_docs_train))\n        indices = torch.split(indices, args.batch_size)\n        thetaAvg = torch.zeros(1, args.num_topics).to(device)\n        thetaWeightedAvg = torch.zeros(1, args.num_topics).to(device)\n        cnt = 0\n        for idx, ind in enumerate(indices):\n            data_batch = data.get_batch(train_tokens, train_counts, ind, args.vocab_size, device)\n            sums = data_batch.sum(1).unsqueeze(1)\n            cnt += sums.sum(0).squeeze().cpu().numpy()\n            if args.bow_norm:\n                normalized_data_batch = data_batch / sums\n            else:\n                normalized_data_batch = data_batch\n            theta, _ = model.get_theta(normalized_data_batch)\n            thetaAvg += theta.sum(0).unsqueeze(0) / args.num_docs_train\n            weighed_theta = sums * theta\n            thetaWeightedAvg += weighed_theta.sum(0).unsqueeze(0)\n            if idx % 100 == 0 and idx > 0:\n                print('batch: {}/{}'.format(idx, len(indices)))\n        thetaWeightedAvg = thetaWeightedAvg.squeeze().cpu().numpy() / cnt\n        print('\\nThe 10 most used topics are {}'.format(thetaWeightedAvg.argsort()[::-1][:10]))\n\n        ## show topics\n        beta = model.get_beta()\n        topic_indices = list(np.random.choice(args.num_topics, 10))  # 10 random topics\n        print('\\n')\n        for k in range(args.num_topics):  # topic_indices:\n            gamma = beta[k]\n            top_words = list(gamma.cpu().numpy().argsort()[-args.num_words + 1:][::-1])\n            topic_words = [vocab[a] for a in top_words]\n            print('Topic {}: {}'.format(k, topic_words))\n\n        if args.train_embeddings:\n            ## show etm embeddings\n            try:\n                rho_etm = model.rho.weight.cpu()\n            except:\n                rho_etm = model.rho.cpu()\n            queries = ['россия', 'человек', 'компьютер', 'спорт', 'религия', 'любовь',\n                       'доллар', 'правительство', 'здоровье', 'семья']\n            print('\\n')\n            print('ETM embeddings...')\n            for word in queries:\n                print('word: {} .. etm neighbors: {}'.format(word, nearest_neighbors(word, rho_etm, vocab)))\n            print('\\n')\nelse:\n    with open(ckpt, 'rb') as f:\n        model = torch.load(f)\n    model = model.to(device)\n    model.eval()\n\n    with torch.no_grad():\n        ## get document completion perplexities\n\n        indices = torch.split(torch.tensor(range(args.num_docs_test)), args.eval_batch_size)\n        tokens = test_tokens\n        counts = test_counts\n\n        beta = model.get_beta()\n        beta[beta < 9e-7] = 0\n\n        ppx = 0\n        nd = 0\n        indices_1 = torch.split(torch.tensor(range(args.num_docs_test_1)), args.eval_batch_size)\n        for idx, ind in enumerate(indices_1):\n            data_batch_1 = data.get_batch(test_1_tokens, test_1_counts, ind, args.vocab_size, device)\n            theta, _ = model.get_theta(data_batch_1)\n            theta[theta < 5e-5] = 0\n\n            np.seterr(divide='ignore')\n            p_wd = np.matmul(theta.cpu().numpy(), beta.cpu().numpy())\n            p_wd = np.log(p_wd)\n            p_wd[np.isneginf(p_wd)] = 0\n            recon_loss = -1 * np.multiply(p_wd, data_batch_1.cpu().numpy()).sum()\n\n            sums = data_batch_1.sum()\n            ppx += recon_loss.item()\n            nd += sums\n\n        avg_ppx = ppx / nd\n        res_ppx = math.exp(avg_ppx)\n        indices = torch.split(torch.tensor(range(args.num_docs_train)), 1000)\n        data_batch = data.get_batch(train_tokens, train_counts, indices[0], args.vocab_size, device)\n        show_viz(model, data_batch, vocab)\n\n        dictionary, docs = get_dictionary(vocab, data_batch)\n        print(dictionary.token2id['дело'])\n        topics = get_topics(vocab, beta, dictionary)\n\n        print(f'result perplexity: {res_ppx}')\n        print(f'beta sparsity: {1.0 - torch.count_nonzero(beta) / torch.numel(beta)}')\n        print(f'theta sparsity: {1.0 - torch.count_nonzero(theta) / torch.numel(theta)}')\n        print(f'Coherence c_v: {get_coherence_gensim(topics, dictionary, \"c_v\", docs)}')\n        print(f'Coherence c_nmpi: {get_coherence_gensim(topics, dictionary, \"c_npmi\", docs)}')\n", "meta": {"hexsha": "310dab90ae1d794b1b02fac31080b754db8a486a", "size": 19254, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "pacifikus/ETM", "max_stars_repo_head_hexsha": "bf7b2234330483773b3011a47fa7b6deefd1bf30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.py", "max_issues_repo_name": "pacifikus/ETM", "max_issues_repo_head_hexsha": "bf7b2234330483773b3011a47fa7b6deefd1bf30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.py", "max_forks_repo_name": "pacifikus/ETM", "max_forks_repo_head_hexsha": "bf7b2234330483773b3011a47fa7b6deefd1bf30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6172839506, "max_line_length": 127, "alphanum_fraction": 0.6293237769, "include": true, "reason": "import numpy,import scipy", "num_tokens": 4790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.18572647814787097}}
{"text": "# Copyright (c) Facebook, Inc. and its affiliates.\n# \n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n\"\"\" Helper functions and class to calculate Average Precisions for 3D object detection.\n\"\"\"\nimport os\nimport sys\nimport numpy as np\nimport torch\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT_DIR = os.path.dirname(BASE_DIR)\nsys.path.append(os.path.join(ROOT_DIR, 'utils'))\nfrom eval_det import eval_det_cls, eval_det_multiprocessing\nfrom eval_det import get_iou_obb\nfrom nms import nms_2d_faster, nms_3d_faster, nms_3d_faster_samecls\nfrom box_util import get_3d_box\nsys.path.append(os.path.join(ROOT_DIR, 'sunrgbd'))\nfrom sunrgbd_utils import extract_pc_in_box3d\n\ndef flip_axis_to_camera(pc):\n    ''' Flip X-right,Y-forward,Z-up to X-right,Y-down,Z-forward\n    Input and output are both (N,3) array\n    '''\n    pc2 = np.copy(pc)\n    pc2[...,[0,1,2]] = pc2[...,[0,2,1]] # cam X,Y,Z = depth X,-Z,Y\n    pc2[...,1] *= -1\n    return pc2\n\ndef flip_axis_to_depth(pc):\n    pc2 = np.copy(pc)\n    pc2[...,[0,1,2]] = pc2[...,[0,2,1]] # depth X,Y,Z = cam X,Z,-Y\n    pc2[...,2] *= -1\n    return pc2\n\ndef softmax(x):\n    ''' Numpy function for softmax'''\n    shape = x.shape\n    probs = np.exp(x - np.max(x, axis=len(shape)-1, keepdims=True))\n    probs /= np.sum(probs, axis=len(shape)-1, keepdims=True)\n    return probs\n\ndef parse_predictions(end_points, config_dict):\n    \"\"\" Parse predictions to OBB parameters and suppress overlapping boxes\n    \n    Args:\n        end_points: dict\n            {point_clouds, center, heading_scores, heading_residuals,\n            size_scores, size_residuals, sem_cls_scores}\n        config_dict: dict\n            {dataset_config, remove_empty_box, use_3d_nms, nms_iou,\n            use_old_type_nms, conf_thresh, per_class_proposal}\n\n    Returns:\n        batch_pred_map_cls: a list of len == batch size (BS)\n            [pred_list_i], i = 0, 1, ..., BS-1\n            where pred_list_i = [(pred_sem_cls, box_params, box_score)_j]\n            where j = 0, ..., num of valid detections - 1 from sample input i\n    \"\"\"\n    pred_center = end_points['center'] # B,num_proposal,3\n    pred_heading_class = torch.argmax(end_points['heading_scores'], -1) # B,num_proposal\n    pred_heading_residual = torch.gather(end_points['heading_residuals'], 2,\n        pred_heading_class.unsqueeze(-1)) # B,num_proposal,1\n    pred_heading_residual.squeeze_(2)\n    pred_size_class = torch.argmax(end_points['size_scores'], -1) # B,num_proposal\n    pred_size_residual = torch.gather(end_points['size_residuals'], 2,\n        pred_size_class.unsqueeze(-1).unsqueeze(-1).repeat(1,1,1,3)) # B,num_proposal,1,3\n    pred_size_residual.squeeze_(2)\n    pred_sem_cls = torch.argmax(end_points['sem_cls_scores'], -1) # B,num_proposal\n    sem_cls_probs = softmax(end_points['sem_cls_scores'].detach().cpu().numpy()) # B,num_proposal,10\n    pred_sem_cls_prob = np.max(sem_cls_probs,-1) # B,num_proposal\n\n    num_proposal = pred_center.shape[1] \n    # Since we operate in upright_depth coord for points, while util functions\n    # assume upright_camera coord.\n    bsize = pred_center.shape[0]\n    pred_corners_3d_upright_camera = np.zeros((bsize, num_proposal, 8, 3))\n    pred_center_upright_camera = flip_axis_to_camera(pred_center.detach().cpu().numpy())\n    for i in range(bsize):\n        for j in range(num_proposal):\n            heading_angle = config_dict['dataset_config'].class2angle(\\\n                pred_heading_class[i,j].detach().cpu().numpy(), pred_heading_residual[i,j].detach().cpu().numpy())\n            box_size = config_dict['dataset_config'].class2size(\\\n                int(pred_size_class[i,j].detach().cpu().numpy()), pred_size_residual[i,j].detach().cpu().numpy())\n            corners_3d_upright_camera = get_3d_box(box_size, heading_angle, pred_center_upright_camera[i,j,:])\n            pred_corners_3d_upright_camera[i,j] = corners_3d_upright_camera\n\n    K = pred_center.shape[1] # K==num_proposal\n    nonempty_box_mask = np.ones((bsize, K))\n\n    if config_dict['remove_empty_box']:\n        # -------------------------------------\n        # Remove predicted boxes without any point within them..\n        batch_pc = end_points['point_clouds'].cpu().numpy()[:,:,0:3] # B,N,3\n        for i in range(bsize):\n            pc = batch_pc[i,:,:] # (N,3)\n            for j in range(K):\n                box3d = pred_corners_3d_upright_camera[i,j,:,:] # (8,3)\n                box3d = flip_axis_to_depth(box3d)\n                pc_in_box,inds = extract_pc_in_box3d(pc, box3d)\n                if len(pc_in_box) < 5:\n                    nonempty_box_mask[i,j] = 0\n        # -------------------------------------\n\n    obj_logits = end_points['objectness_scores'].detach().cpu().numpy()\n    obj_prob = softmax(obj_logits)[:,:,1] # (B,K)\n    if not config_dict['use_3d_nms']:\n        # ---------- NMS input: pred_with_prob in (B,K,7) -----------\n        pred_mask = np.zeros((bsize, K))\n        for i in range(bsize):\n            boxes_2d_with_prob = np.zeros((K,5))\n            for j in range(K):\n                boxes_2d_with_prob[j,0] = np.min(pred_corners_3d_upright_camera[i,j,:,0])\n                boxes_2d_with_prob[j,2] = np.max(pred_corners_3d_upright_camera[i,j,:,0])\n                boxes_2d_with_prob[j,1] = np.min(pred_corners_3d_upright_camera[i,j,:,2])\n                boxes_2d_with_prob[j,3] = np.max(pred_corners_3d_upright_camera[i,j,:,2])\n                boxes_2d_with_prob[j,4] = obj_prob[i,j]\n            nonempty_box_inds = np.where(nonempty_box_mask[i,:]==1)[0]\n            pick = nms_2d_faster(boxes_2d_with_prob[nonempty_box_mask[i,:]==1,:],\n                config_dict['nms_iou'], config_dict['use_old_type_nms'])\n            assert(len(pick)>0)\n            pred_mask[i, nonempty_box_inds[pick]] = 1\n        end_points['pred_mask'] = pred_mask\n        # ---------- NMS output: pred_mask in (B,K) -----------\n    elif config_dict['use_3d_nms'] and (not config_dict['cls_nms']):\n        # ---------- NMS input: pred_with_prob in (B,K,7) -----------\n        pred_mask = np.zeros((bsize, K))\n        for i in range(bsize):\n            boxes_3d_with_prob = np.zeros((K,7))\n            for j in range(K):\n                boxes_3d_with_prob[j,0] = np.min(pred_corners_3d_upright_camera[i,j,:,0])\n                boxes_3d_with_prob[j,1] = np.min(pred_corners_3d_upright_camera[i,j,:,1])\n                boxes_3d_with_prob[j,2] = np.min(pred_corners_3d_upright_camera[i,j,:,2])\n                boxes_3d_with_prob[j,3] = np.max(pred_corners_3d_upright_camera[i,j,:,0])\n                boxes_3d_with_prob[j,4] = np.max(pred_corners_3d_upright_camera[i,j,:,1])\n                boxes_3d_with_prob[j,5] = np.max(pred_corners_3d_upright_camera[i,j,:,2])\n                boxes_3d_with_prob[j,6] = obj_prob[i,j]\n            nonempty_box_inds = np.where(nonempty_box_mask[i,:]==1)[0]\n            pick = nms_3d_faster(boxes_3d_with_prob[nonempty_box_mask[i,:]==1,:],\n                config_dict['nms_iou'], config_dict['use_old_type_nms'])\n            assert(len(pick)>0)\n            pred_mask[i, nonempty_box_inds[pick]] = 1\n        end_points['pred_mask'] = pred_mask\n        # ---------- NMS output: pred_mask in (B,K) -----------\n    elif config_dict['use_3d_nms'] and config_dict['cls_nms']:\n        # ---------- NMS input: pred_with_prob in (B,K,8) -----------\n        pred_mask = np.zeros((bsize, K))\n        for i in range(bsize):\n            boxes_3d_with_prob = np.zeros((K,8))\n            for j in range(K):\n                boxes_3d_with_prob[j,0] = np.min(pred_corners_3d_upright_camera[i,j,:,0])\n                boxes_3d_with_prob[j,1] = np.min(pred_corners_3d_upright_camera[i,j,:,1])\n                boxes_3d_with_prob[j,2] = np.min(pred_corners_3d_upright_camera[i,j,:,2])\n                boxes_3d_with_prob[j,3] = np.max(pred_corners_3d_upright_camera[i,j,:,0])\n                boxes_3d_with_prob[j,4] = np.max(pred_corners_3d_upright_camera[i,j,:,1])\n                boxes_3d_with_prob[j,5] = np.max(pred_corners_3d_upright_camera[i,j,:,2])\n                boxes_3d_with_prob[j,6] = obj_prob[i,j]\n                boxes_3d_with_prob[j,7] = pred_sem_cls[i,j] # only suppress if the two boxes are of the same class!!\n            nonempty_box_inds = np.where(nonempty_box_mask[i,:]==1)[0]\n            pick = nms_3d_faster_samecls(boxes_3d_with_prob[nonempty_box_mask[i,:]==1,:],\n                config_dict['nms_iou'], config_dict['use_old_type_nms'])\n            assert(len(pick)>0)\n            pred_mask[i, nonempty_box_inds[pick]] = 1\n        end_points['pred_mask'] = pred_mask\n        # ---------- NMS output: pred_mask in (B,K) -----------\n\n    batch_pred_map_cls = [] # a list (len: batch_size) of list (len: num of predictions per sample) of tuples of pred_cls, pred_box and conf (0-1)\n    for i in range(bsize):\n        if config_dict['per_class_proposal']:\n            cur_list = []\n            for ii in range(config_dict['dataset_config'].num_class):\n                cur_list += [(ii, pred_corners_3d_upright_camera[i,j], sem_cls_probs[i,j,ii]*obj_prob[i,j]) \\\n                    for j in range(pred_center.shape[1]) if pred_mask[i,j]==1 and obj_prob[i,j]>config_dict['conf_thresh']]\n            batch_pred_map_cls.append(cur_list)\n        else:\n            batch_pred_map_cls.append([(pred_sem_cls[i,j].item(), pred_corners_3d_upright_camera[i,j], obj_prob[i,j]) \\\n                for j in range(pred_center.shape[1]) if pred_mask[i,j]==1 and obj_prob[i,j]>config_dict['conf_thresh']])\n    end_points['batch_pred_map_cls'] = batch_pred_map_cls\n\n    return batch_pred_map_cls\n\ndef parse_groundtruths(end_points, config_dict):\n    \"\"\" Parse groundtruth labels to OBB parameters.\n    \n    Args:\n        end_points: dict\n            {center_label, heading_class_label, heading_residual_label,\n            size_class_label, size_residual_label, sem_cls_label,\n            box_label_mask}\n        config_dict: dict\n            {dataset_config}\n\n    Returns:\n        batch_gt_map_cls: a list  of len == batch_size (BS)\n            [gt_list_i], i = 0, 1, ..., BS-1\n            where gt_list_i = [(gt_sem_cls, gt_box_params)_j]\n            where j = 0, ..., num of objects - 1 at sample input i\n    \"\"\"\n    center_label = end_points['center_label']\n    heading_class_label = end_points['heading_class_label']\n    heading_residual_label = end_points['heading_residual_label']\n    size_class_label = end_points['size_class_label']\n    size_residual_label = end_points['size_residual_label']\n    box_label_mask = end_points['box_label_mask']\n    sem_cls_label = end_points['sem_cls_label']\n    bsize = center_label.shape[0]\n\n    K2 = center_label.shape[1] # K2==MAX_NUM_OBJ\n    gt_corners_3d_upright_camera = np.zeros((bsize, K2, 8, 3))\n    gt_center_upright_camera = flip_axis_to_camera(center_label[:,:,0:3].detach().cpu().numpy())\n    for i in range(bsize):\n        for j in range(K2):\n            if box_label_mask[i,j] == 0: continue\n            heading_angle = config_dict['dataset_config'].class2angle(heading_class_label[i,j].detach().cpu().numpy(), heading_residual_label[i,j].detach().cpu().numpy())\n            box_size = config_dict['dataset_config'].class2size(int(size_class_label[i,j].detach().cpu().numpy()), size_residual_label[i,j].detach().cpu().numpy())\n            corners_3d_upright_camera = get_3d_box(box_size, heading_angle, gt_center_upright_camera[i,j,:])\n            gt_corners_3d_upright_camera[i,j] = corners_3d_upright_camera\n\n    batch_gt_map_cls = []\n    for i in range(bsize):\n        batch_gt_map_cls.append([(sem_cls_label[i,j].item(), gt_corners_3d_upright_camera[i,j]) for j in range(gt_corners_3d_upright_camera.shape[1]) if box_label_mask[i,j]==1])\n    end_points['batch_gt_map_cls'] = batch_gt_map_cls\n\n    return batch_gt_map_cls\n\nclass APCalculator(object):\n    ''' Calculating Average Precision '''\n    def __init__(self, ap_iou_thresh=0.25, class2type_map=None):\n        \"\"\"\n        Args:\n            ap_iou_thresh: float between 0 and 1.0\n                IoU threshold to judge whether a prediction is positive.\n            class2type_map: [optional] dict {class_int:class_name}\n        \"\"\"\n        self.ap_iou_thresh = ap_iou_thresh\n        self.class2type_map = class2type_map\n        self.reset()\n        \n    def step(self, batch_pred_map_cls, batch_gt_map_cls):\n        \"\"\" Accumulate one batch of prediction and groundtruth.\n        \n        Args:\n            batch_pred_map_cls: a list of lists [[(pred_cls, pred_box_params, score),...],...]\n            batch_gt_map_cls: a list of lists [[(gt_cls, gt_box_params),...],...]\n                should have the same length with batch_pred_map_cls (batch_size)\n        \"\"\"\n        \n        bsize = len(batch_pred_map_cls)\n        assert(bsize == len(batch_gt_map_cls))\n        for i in range(bsize):\n            self.gt_map_cls[self.scan_cnt] = batch_gt_map_cls[i] \n            self.pred_map_cls[self.scan_cnt] = batch_pred_map_cls[i] \n            self.scan_cnt += 1\n    \n    def compute_metrics(self):\n        \"\"\" Use accumulated predictions and groundtruths to compute Average Precision.\n        \"\"\"\n        rec, prec, ap = eval_det_multiprocessing(self.pred_map_cls, self.gt_map_cls, ovthresh=self.ap_iou_thresh, get_iou_func=get_iou_obb)\n        ret_dict = {} \n        for key in sorted(ap.keys()):\n            clsname = self.class2type_map[key] if self.class2type_map else str(key)\n            ret_dict['%s Average Precision'%(clsname)] = ap[key]\n        temp = []\n        for v in list(ap.values()):\n            if np.isnan(v):\n                continue\n            temp.append(v)\n        ret_dict['mAP'] = np.mean(temp)\n        rec_list = []\n        for key in sorted(ap.keys()):\n            clsname = self.class2type_map[key] if self.class2type_map else str(key)\n            try:\n                ret_dict['%s Recall'%(clsname)] = rec[key][-1]\n                rec_list.append(rec[key][-1])\n            except:\n                ret_dict['%s Recall'%(clsname)] = 0\n                rec_list.append(0)\n        temp = []\n        for v in rec_list:\n            if np.isnan(v):\n                continue\n            temp.append(v)\n        ret_dict['AR'] = np.mean(temp)\n        return ret_dict\n\n    def reset(self):\n        self.gt_map_cls = {} # {scan_id: [(classname, bbox)]}\n        self.pred_map_cls = {} # {scan_id: [(classname, bbox, score)]}\n        self.scan_cnt = 0\n", "meta": {"hexsha": "22fbf679afd8705601f86739b6fc0ad293e4c16a", "size": 14375, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/ap_helper.py", "max_stars_repo_name": "zaiweizhang/votenet", "max_stars_repo_head_hexsha": "9fd1032fb67783b0f44b76a8118fbe16133981ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-02T23:45:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T23:45:16.000Z", "max_issues_repo_path": "models/ap_helper.py", "max_issues_repo_name": "zaiweizhang/votenet", "max_issues_repo_head_hexsha": "9fd1032fb67783b0f44b76a8118fbe16133981ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/ap_helper.py", "max_forks_repo_name": "zaiweizhang/votenet", "max_forks_repo_head_hexsha": "9fd1032fb67783b0f44b76a8118fbe16133981ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-01-12T17:13:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-18T11:30:33.000Z", "avg_line_length": 49.3986254296, "max_line_length": 177, "alphanum_fraction": 0.627826087, "include": true, "reason": "import numpy", "num_tokens": 3799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.1857264697767737}}
{"text": "#!/usr/bin/env python\n#####################################################\n# How to run this script\n#\n# From Linux Terminal:$./calculon.py Results_File Symbol_Ref1 Symbol_Ref2 Atomic_Number Output_File_Name\n#\n# 'Symbol_Ref1' and 'Symbol_Ref2' can take the following format --> '40Ca+19F' or '85Rb' (without the quotes)\n#\n# v1.0 Created  by D. Atanasov @ 16.09.2014\n# v2.0 Modified by D. Atanasov @ 14.02.2017\n# v3.0 Modified to have OOP by D. Atanaso @ 21.03.2017\n# v4.0 Modified to import full AME table by J. Karthein @ 11.04.2017\n#####################################################\nimport os\nimport sys\nimport re\nimport numpy as np\nimport pandas as pd\nimport platform\n\n\n#   ######################################################\n#   #              Function's Definition                 #\n#   ######################################################\nclass Ame():\n    def __init__(self):\n        self.scale = 931494.061                          # [amu]->[keV]  #\n        self.me = 548.57990946                           # Electron mass #\n        self.me_unc = 0.00000022                         # uncertainty   #\n        self.load_table()\n\n    def get_number_symbol(self, item):\n        \"\"\"\n        Get the Atomic number and the Element symbol from a specific string ()\n        Examples: (40Ca19F), (H1H1:O16), 85Rb, 136Cd etc.\n        :param item:\n        :return: Atomic number, Element Symbol\n        \"\"\"\n        return re.findall('[0-9][0-9][0-9]|[0-9][0-9]|[0-9]', item), re.findall('[A-Z][a-z]|[A-Z]', item)\n\n    def load_table(self, ame='AME16.txt'):\n        '''\n        The function reads the AME table and returns a DataFrame of str's.\n\n        Input name:     'AME16.txt'\n        Further info:   If a new table will be uploaded, please change the file + name.\n                        Before starting please remove all '*' by ' ' and all '#' by '.'\n        Questions to:   jonas.karthein@cern.ch\n        '''\n        if platform.system() == 'Windows':\n            os.chdir('G:\\\\Experiments\\\\ISOLTRAP\\\\Software\\\\PI-ICR\\\\Python-DAQ')\n        elif platform.system() == 'Darwin': # MacOS\n            # os.chdir('/Volumes/dfs/Software/PI-ICR/Python-DAQ/')\n            os.chdir('/Users/jonaskarthein/cernbox/Software/Python/piicr-analysis/')\n        ame_import = np.genfromtxt(ame, skip_header=39, dtype=['a1', 'int', 'int', 'int', 'int', 'a4', 'a4', 'float', 'float', 'float', 'float', 'a3', 'float', 'float', 'int', 'float', 'float'], delimiter=[1,3,5,5,5,4,4,16,12,12,6,3,11,8,4,13,11])\n        ame_table = [list(elem) for elem in ame_import.tolist()]    # convert list of tuples to list of lists\n\n        for i in range(len(ame_table)):\n            ame_table[i][15] = ame_table[i][14] * 1E6 + ame_table[i][15]    # calculate full atomic mass (int*1000000+float)\n            for j in range(len(ame_table[i])):\n                if type(ame_table[i][j]) == str:\n                    ame_table[i][j] = ame_table[i][j].replace(\" \", \"\")      # delete all spaces --> makes searching easier\n                ame_table[i][j] = str(ame_table[i][j])                      # convert all entries to int (needed for Dinkos class)\n        self.df = pd.DataFrame(ame_table, columns=['cc', 'NZ', 'N', 'Z', 'A', 'EL', 'o', 'mass excess / keV', 'mass excess unc / keV', 'binding energy / keV', 'binding energy unc / keV', 'B', 'beta decay energy / keV', 'beta decay energy unc / keV', 'atomic mass (int) / Dalton', 'atomic mass / micro Dalton', 'atomic mass unc'])\n\n\n    def get_ame_mass(self, el_expr):\n        \"\"\"\n        Checks AME Table for existing of the element with the given atomic number.\n        Calculates the mass. If a list is provided to the function (such as a molecule) it calculates\n        the summed mass of the constituents.\n        :param atomic_number:\n        :param symbols:\n        :param ame:\n        :return: el_expr, atom_mass, np.sqrt(unc)\n        \"\"\"\n        ame_mass = 0.0\n        ame_unc = 0.0\n        self.idx = []\n        atomic_number, symbols = self.get_number_symbol(el_expr)\n        for i in range(len(symbols)):\n            self.idx.append(self.df[(self.df['EL'] == symbols[i]) & (self.df['A'] == atomic_number[i])].index.tolist())\n        if len(self.idx[0]) == 0:\n            print \"Element or Atomic number not found in database\"\n        else:\n            for i in range(len(self.idx)):\n                ame_mass += float(self.df.get_value(self.idx[i][0], 'atomic mass / micro Dalton'))\n                ame_unc += float(self.df.get_value(self.idx[i][0], 'atomic mass unc'))**2\n        return el_expr, ame_mass, np.sqrt(ame_unc)\n\n    def get_ion_mass(self, mass_atom, mass_atom_unc, charge=1):\n        \"\"\"\n        Calculate the ion mass\n        :param mass_atom:\n        :param mass_atom_unc:\n        :param charge:\n        :return: massIon, massIonUnc\n        \"\"\"\n        return (mass_atom - charge*self.me), np.sqrt(mass_atom_unc**2 + charge*self.me_unc**2)\n\n    def get_isobars(self, atomic_number):\n        \"\"\"\n        Checks AME Table for existing of the element with the given atomic number.\n        Calculates the mass. If a list is provided to the function (such as a molecule) it calculates\n        the summed mass of the constituents.\n        :param atomic_number:\n        :param symbols:\n        :param ame:\n        :return: el_expr, atom_mass, np.sqrt(unc)\n        \"\"\"\n        idx = []\n        print atomic_number, type(atomic_number)\n        print self.df[self.df['A'] == str(atomic_number)]\n        idx = self.df[self.df['A'] == str(atomic_number)].index.tolist()\n        print len(idx)\n        isobars = np.empty((len(idx), 3,), dtype=object)\n        if len(idx) == 0:\n            print \"No isobars found! Please check the atomic Number\"\n        else:\n            for i in range(len(idx)):\n                print idx[i], type(idx[i])\n                isobars[i][0] = self.df.get_value(idx[i], 'EL')\n                isobars[i][1] = float(self.df.get_value(idx[i], 'atomic mass / micro Dalton'))\n                isobars[i][2] = float(self.df.get_value(idx[i], 'atomic mass unc'))\n        return isobars\n\n\nif __name__ == \"__main__\":\n    main(sys.argv)\n", "meta": {"hexsha": "0dab32399886f2442691f34b9b51d79ef07e1236", "size": 6088, "ext": "py", "lang": "Python", "max_stars_repo_path": "piicr-analysis/get_ame_data.py", "max_stars_repo_name": "lnies/lEval", "max_stars_repo_head_hexsha": "da9ce344a713c7fb46d53417e44a2f56956a1b60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "piicr-analysis/get_ame_data.py", "max_issues_repo_name": "lnies/lEval", "max_issues_repo_head_hexsha": "da9ce344a713c7fb46d53417e44a2f56956a1b60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "piicr-analysis/get_ame_data.py", "max_forks_repo_name": "lnies/lEval", "max_forks_repo_head_hexsha": "da9ce344a713c7fb46d53417e44a2f56956a1b60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.8307692308, "max_line_length": 329, "alphanum_fraction": 0.5599540079, "include": true, "reason": "import numpy", "num_tokens": 1605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.1857218280556574}}
{"text": "\"\"\"\nCreate extinguished grid more segmented dealing with large grids with enough\nmemory\n\nAll functions are now transformed into generators. As a result, any function\nallows computation of a grid in an arbitrary number of chunks. This offers the\npossibility to generate grids that cannot fit in memory.\n\n\n.. note::\n\n    * dependencies have also been updated accordingly.\n\n    * likelihood computations need to be updated to allow computations even if\n      the full grid does not fit in memory\n\"\"\"\nimport numpy as np\nimport copy\n\nfrom astropy import units\nfrom tqdm import tqdm\n\nfrom beast.physicsmodel.stars import stellib\nfrom beast.physicsmodel.grid import SpectralGrid, SEDGrid\nfrom beast.physicsmodel.prior_weights_dust import PriorWeightsDust\n# from beast.external.eztables import Table\nfrom astropy.table import Table\nfrom beast.tools.helpers import generator\nfrom beast.tools import helpers\n\nfrom beast.observationmodel.noisemodel import absflux_covmat\n\n__all__ = [\n    \"gen_spectral_grid_from_stellib_given_points\",\n    \"make_extinguished_grid\",\n    \"add_spectral_properties\",\n    \"calc_absflux_cov_matrices\",\n]\n\n\n@generator\ndef gen_spectral_grid_from_stellib_given_points(\n    osl, pts, bounds=dict(dlogT=0.1, dlogg=0.3), chunksize=0\n):\n    \"\"\"\n    Generator that reinterpolates a given stellar spectral library on to\n       an Isochrone grid\n\n    It will iterate over a list of `pts` points and generate\n       `chunksize` models until all the list of points is processed\n\n    Parameters\n    ----------\n    osl: stellib.stellib\n        a stellar library\n\n    pts: dict like structure of points\n        dictionary like or named data structure of points to interpolate at\n        must contain logg, logT, logL, and Z\n\n    bounds:  dict, optional (default={dlogT:0.1, dlogg:0.3})\n        sensitivity to extrapolation (see grid.get_stellib_boundaries)\n\n    chunksize: int, optional (default=0)\n        number of models to generate at each cycle.\n        If default <= 0, all models will be returned at once.\n\n    Returns\n    -------\n    g: SpectralGrid\n        Spectral grid (in memory) containing the requested list of stars\n        and associated spectra\n    \"\"\"\n\n    helpers.type_checker(\"osl\", osl, stellib.Stellib)\n\n    if chunksize <= 0:\n        yield osl.gen_spectral_grid_from_given_points(pts, bounds=bounds)\n    else:\n        try:\n            # Yield successive n-sized chunks from l, assuming we can take\n            # slices of the iterator\n            for chunk_slice in helpers.chunks(list(range(len(pts))), chunksize):\n                chunk_pts = pts[chunk_slice]\n                yield osl.gen_spectral_grid_from_given_points(chunk_pts, bounds=bounds)\n        except Exception as e:\n            # chunks may not work on this as pts is most likely a Table\n            print(e)\n            for chunk_pts in helpers.chunks(pts, chunksize):\n                yield osl.gen_spectral_grid_from_given_points(chunk_pts, bounds=bounds)\n\n\ndef _make_dust_fA_valid_points_generator(it, min_Rv, max_Rv):\n    \"\"\"\n    compute the allowed points based on the R(V) versus f_A plane\n    duplicates effort for all A(V) values, but it is quick compared to\n    other steps\n\n    .. note::\n\n        on 2.74: SMC extinction implies f_A = 0. and Rv = 2.74\n\n    Parameters\n    ----------\n    it: an iterable\n        an initial sequence of points that will be trimmed to only valid ones\n\n    min_Rv: float\n        lower Rv limit\n\n    max_Rv: float\n        upper Rv limit\n\n    Returns\n    -------\n    npts: int\n        the actual number of valid points\n\n    pts: generator\n        a generator that only produce valid points\n    \"\"\"\n    itn = copy.copy(it)\n    npts = 0\n\n    def is_valid(ak, rk, fk):\n        return (\n            fk / max_Rv + (1.0 - fk) / 2.74\n            <= 1.0 / rk\n            <= fk * 1.0 / min_Rv + (1.0 - fk) / 2.74\n        )\n\n    # explore the full list once\n    # not very time consuming\n    for ak, rk, fk in itn:\n        if is_valid(ak, rk, fk):\n            npts += 1\n\n    # make the iterator\n    pts = (\n        (float(ak), float(rk), float(fk)) for ak, rk, fk in it if is_valid(ak, rk, fk)\n    )\n\n    return npts, pts\n\n\ndef apply_distance_grid(specgrid, distances, redshift=0):\n    \"\"\"\n    Distances are applied to the spectral grid by copying the grid and\n    applying a scaling factor.\n\n    Parameters\n    ----------\n\n    project: str\n        project name\n\n    specgrid: grid.SpectralGrid object\n        spectral grid to transform\n\n    distances: list of float\n        Distances at which models should be shifted\n        0 means absolute magnitude.\n        Expecting pc units\n\n    redshift: float\n        Redshift to which wavelengths should be shifted\n        Default is 0 (rest frame)\n    \"\"\"\n    g0 = specgrid\n\n    # Current length of the grid\n    N0 = len(g0.grid)\n    N = N0 * len(distances)\n\n    # Make singleton list if a single distance is given\n    if not hasattr(distances, \"__iter__\"):\n        _distances = [distances]\n    else:\n        _distances = distances\n\n    # Add distance column if multiple distances are specified\n    cols = {}\n    cols[\"distance\"] = np.empty(N, dtype=float)\n\n    # Existing columns\n    keys0 = list(g0.keys())\n    for key in keys0:\n        cols[key] = np.empty(N, dtype=float)\n\n    n_sed_points = g0.seds.shape[1]\n    new_seds = np.empty((N, n_sed_points), dtype=float)\n\n    for count, distance in enumerate(tqdm(_distances, desc=\"Distance grid\")):\n\n        # The range where the current distance points will live\n        distance_slice = slice(N0 * count, N0 * (count + 1))\n\n        # The seds default to 10 pc.\n        # Therefore, scale them with (d / (10 pc))**(-2).\n        distance_pc = distance.to(units.pc).value\n        new_seds[distance_slice, :] = g0.seds / (0.1 * distance_pc) ** 2\n\n        # Fill in the distance in the distance column\n        cols[\"distance\"][distance_slice] = distance_pc\n\n        # Copy the old columns\n        for key in keys0:\n            cols[key][distance_slice] = g0.grid[key]\n\n    # apply redshift\n    g0.lamb = g0.lamb * (1.0 + redshift)\n\n    # New object\n    g = SpectralGrid(g0.lamb, seds=new_seds, grid=Table(cols), backend=\"memory\")\n    return g\n\n\n@generator\ndef make_extinguished_grid(\n    spec_grid,\n    filter_names,\n    extLaw,\n    avs,\n    rvs,\n    fAs=None,\n    av_prior_model={\"name\": \"flat\"},\n    rv_prior_model={\"name\": \"flat\"},\n    fA_prior_model={\"name\": \"flat\"},\n    chunksize=0,\n    add_spectral_properties_kwargs=None,\n    absflux_cov=False,\n    filterLib=None,\n):\n    \"\"\"\n    Extinguish spectra and extract an SEDGrid through given series of filters\n    (all wavelengths in stellar SEDs and filter response functions are assumed\n    to be in Angstroms)\n\n    Parameters\n    ----------\n    spec_grid: string or grid.SpectralGrid\n        if string:\n        spec_grid is the filename to the grid file with stellar spectra\n        the backend to load this grid will be the minimal invasive: 'HDF'\n        if possible, 'cache' otherwise.\n\n        if not a string, expecting the corresponding SpectralGrid instance\n        (backend already setup)\n\n    filter_names: list\n        list of filter names according to the filter lib\n\n    Avs: sequence\n        Av values to iterate over\n\n    av_prior_model: list\n        list including prior model name and parameters\n\n    Rvs: sequence\n        Rv values to iterate over\n\n    rv_prior_model: list\n        list including prior model name and parameters\n\n    fAs: sequence (optional)\n        f_A values to iterate over\n        f_A can be omitted if the extinction Law does not use it or allow\n        fixed values\n\n    fA_prior_model: list\n        list including prior model name and parameters\n\n    chunksize: int, optional (default=0)\n        number of extinction model variations to generate at each cycle.\n        Note that this means len(spec_grid * chunksize)\n        If default <= 0, all models will be returned at once.\n\n    filterLib:  str\n        full filename to the filter library hd5 file\n\n    add_spectral_properties_kwargs: dict\n        keyword arguments to call :func:`add_spectral_properties` at each\n        iteration to add model properties from the spectra into the grid\n        property table\n\n    asbflux_cov: boolean\n        set to calculate the absflux covariance matrices for each model\n        (can be very slow!!!  But it is the right thing to do)\n\n    Returns\n    -------\n    g: grid.SpectralGrid\n        final grid of reddened SEDs and models\n    \"\"\"\n    # Check inputs\n    # ============\n    # get the stellar grid (no dust yet)\n    # if string is provided try to load the most memory efficient backend\n    # otherwise use a cache-type backend (load only when needed)\n    if isinstance(spec_grid, str):\n        ext = spec_grid.split(\".\")[-1]\n        if ext in [\"hdf\", \"hd5\", \"hdf5\"]:\n            g0 = SpectralGrid(spec_grid, backend=\"disk\")\n        else:\n            g0 = SpectralGrid(spec_grid, backend=\"cache\")\n    else:\n        helpers.type_checker(\"spec_grid\", spec_grid, SpectralGrid)\n        g0 = spec_grid\n\n    # Tag fA usage\n    if fAs is None:\n        with_fA = False\n    else:\n        with_fA = True\n\n    # get the min/max R(V) values necessary for the grid point definition\n    min_Rv = min(rvs)\n    max_Rv = max(rvs)\n\n    # Create the sampling mesh\n    # ========================\n    # basically the dot product from all input 1d vectors\n    # setup interation over the full dust parameter grid\n    if with_fA:\n        dustpriors = PriorWeightsDust(\n            avs, av_prior_model, rvs, rv_prior_model, fAs, fA_prior_model\n        )\n\n        it = np.nditer(np.ix_(avs, rvs, fAs))\n        niter = np.size(avs) * np.size(rvs) * np.size(fAs)\n        npts, pts = _make_dust_fA_valid_points_generator(it, min_Rv, max_Rv)\n\n        # Pet the user\n        print(\n            \"\"\"number of initially requested points = {0:d}\n              number of valid points = {1:d} (based on restrictions in R(V)\n                 versus f_A plane)\n              \"\"\".format(\n                niter, npts\n            )\n        )\n\n        if npts == 0:\n            raise AttributeError(\"No valid points\")\n    else:\n        dustpriors = PriorWeightsDust(\n            avs, av_prior_model, rvs, rv_prior_model, [1.0], fA_prior_model\n        )\n\n        it = np.nditer(np.ix_(avs, rvs))\n        npts = np.size(avs) * np.size(rvs)\n        pts = ((float(ak), float(rk)) for ak, rk in it)\n\n    # Generate the Grid\n    # =================\n    N0 = len(g0.grid)\n    N = N0 * npts\n\n    if chunksize <= 0:\n        print(\"Generating a final grid of {0:d} points\".format(N))\n    else:\n        print(\n            \"Generating a final grid of {0:d} points in {1:d}\"\n            + \" pieces\".format(N, int(float(N0) / chunksize + 1.0))\n        )\n\n    if chunksize <= 0:\n        chunksize = npts\n\n    if add_spectral_properties_kwargs is not None:\n        nameformat = add_spectral_properties_kwargs.pop(\"nameformat\", \"{0:s}\") + \"_wd\"\n\n    for chunk_pts in helpers.chunks(pts, chunksize):\n        # iter over chunks of models\n\n        # setup chunk outputs\n        cols = {\"Av\": np.empty(N, dtype=float), \"Rv\": np.empty(N, dtype=float)}\n\n        if with_fA:\n            cols[\"Rv_A\"] = np.empty(N, dtype=float)\n            cols[\"f_A\"] = np.empty(N, dtype=float)\n\n        keys = list(g0.keys())\n        for key in keys:\n            cols[key] = np.empty(N, dtype=float)\n\n        n_filters = len(filter_names)\n        _seds = np.empty((N, n_filters), dtype=float)\n        if absflux_cov:\n            n_offdiag = ((n_filters ** 2) - n_filters) / 2\n            _cov_diag = np.empty((N, n_filters), dtype=float)\n            _cov_offdiag = np.empty((N, n_offdiag), dtype=float)\n\n        for count, pt in enumerate(tqdm(chunk_pts, desc=\"SED grid\")):\n\n            if with_fA:\n                Av, Rv, f_A = pt\n                dust_prior_weight = dustpriors.get_weight(Av, Rv, f_A)\n                Rv_MW = extLaw.get_Rv_A(Rv, f_A)\n                r = g0.applyExtinctionLaw(extLaw, Av=Av, Rv=Rv, f_A=f_A, inplace=False)\n                # add extra \"spectral bands\" if requested\n                if add_spectral_properties_kwargs is not None:\n                    r = add_spectral_properties(\n                        r,\n                        nameformat=nameformat,\n                        filterLib=filterLib,\n                        **add_spectral_properties_kwargs\n                    )\n                temp_results = r.getSEDs(filter_names, filterLib=filterLib)\n                # adding the dust parameters to the models\n                cols[\"Av\"][N0 * count : N0 * (count + 1)] = Av\n                cols[\"Rv\"][N0 * count : N0 * (count + 1)] = Rv\n                cols[\"f_A\"][N0 * count : N0 * (count + 1)] = f_A\n                cols[\"Rv_A\"][N0 * count : N0 * (count + 1)] = Rv_MW\n\n            else:\n                Av, Rv = pt\n                dust_prior_weight = dustpriors.get_weight(Av, Rv, 1.0)\n                r = g0.applyExtinctionLaw(extLaw, Av=Av, Rv=Rv, inplace=False)\n\n                if add_spectral_properties_kwargs is not None:\n                    r = add_spectral_properties(\n                        r,\n                        nameformat=nameformat,\n                        filterLib=filterLib,\n                        **add_spectral_properties_kwargs\n                    )\n                temp_results = r.getSEDs(filter_names, filterLib=filterLib)\n                # adding the dust parameters to the models\n                cols[\"Av\"][N0 * count : N0 * (count + 1)] = Av\n                cols[\"Rv\"][N0 * count : N0 * (count + 1)] = Rv\n\n            # get new attributes if exist\n            for key in list(temp_results.grid.keys()):\n                if key not in keys:\n                    k1 = N0 * count\n                    k2 = N0 * (count + 1)\n                    cols.setdefault(key, np.empty(N, dtype=float))[\n                        k1:k2\n                    ] = temp_results.grid[key]\n\n            # compute the fractional absflux covariance matrices\n            if absflux_cov:\n                absflux_covmats = calc_absflux_cov_matrices(\n                    r, temp_results, filter_names\n                )\n                _cov_diag[N0 * count : N0 * (count + 1)] = absflux_covmats[0]\n                _cov_offdiag[N0 * count : N0 * (count + 1)] = absflux_covmats[1]\n\n            # assign the extinguished SEDs to the output object\n            _seds[N0 * count : N0 * (count + 1)] = temp_results.seds[:]\n\n            # copy the rest of the parameters\n            for key in keys:\n                cols[key][N0 * count : N0 * (count + 1)] = g0.grid[key]\n\n            # multiply existing prior weights by the dust prior weight\n            cols[\"weight\"][N0 * count : N0 * (count + 1)] *= dust_prior_weight\n            cols[\"prior_weight\"][N0 * count : N0 * (count + 1)] *= dust_prior_weight\n\n            if count == 0:\n                cols[\"lamb\"] = temp_results.lamb[:]\n\n        _lamb = cols.pop(\"lamb\")\n\n        # free the memory of temp_results\n        # del temp_results\n        # del tempgrid\n\n        # Ship\n        if absflux_cov:\n            g = SEDGrid(\n                _lamb,\n                seds=_seds,\n                cov_diag=_cov_diag,\n                cov_offdiag=_cov_offdiag,\n                grid=Table(cols),\n                backend=\"memory\",\n            )\n        else:\n            g = SEDGrid(_lamb, seds=_seds, grid=Table(cols), backend=\"memory\")\n\n        g.header[\"filters\"] = \" \".join(filter_names)\n\n        yield g\n\n\ndef add_spectral_properties(\n    specgrid,\n    filternames=None,\n    filters=None,\n    callables=None,\n    nameformat=None,\n    filterLib=None,\n):\n    \"\"\"\n    Addon spectral calculations to spectral grids to extract in the fitting\n    routines\n\n    Parameters\n    ----------\n    specgrid: SpectralGrid instance\n        instance of the spectral grid\n\n    filternames: sequence(str)\n        compute the integrated values through given filters in the library\n\n    filters: sequence(Filters)\n        sequence of filter instances from which extract integrated values\n\n    callables: sequence(callable)\n        sequence of functions to apply onto the spectral grid assuming storing\n        results is internally processed by the individual functions\n\n    nameformat: str\n        naming format to adopt for filternames and filters\n        default value is '{0:s}_0' where the value will be the filter name\n\n    filterLib:  str\n        full filename to the filter library hd5 file\n\n    Returns\n    -------\n    specgrid: SpectralGrid instance\n        instance of the input spectral grid which will include more properties\n    \"\"\"\n    if nameformat is None:\n        nameformat = \"{0:s}_0\"\n\n    if filternames is not None:\n        temp = specgrid.getSEDs(filternames, extLaw=None, filterLib=filterLib)\n\n        logtempseds = np.array(temp.seds)\n        indxs = np.where(temp.seds > 0)\n        if len(indxs) > 0:\n            logtempseds[indxs] = np.log10(temp.seds[indxs])\n        indxs = np.where(temp.seds <= 0)\n        if len(indxs) > 0:\n            logtempseds[indxs] = -100.0\n\n        for i, fk in enumerate(filternames):\n            specgrid.grid[\"log\" + nameformat.format(fk)] = logtempseds[:, i]\n        del temp\n\n    if filters is not None:\n        temp = specgrid.getSEDs(filters, extLaw=None)\n\n        logtempseds = np.array(temp.seds)\n        indxs = np.where(temp.seds > 0)\n        if len(indxs) > 0:\n            logtempseds[indxs] = np.log10(temp.seds[indxs])\n\n        indxs = np.where(temp.seds <= 0)\n        if len(indxs) > 0:\n            logtempseds[indxs] = -100.0\n\n        for i, fk in enumerate(filters):\n            specgrid.grid[\"log\" + nameformat.format(fk.name)] = logtempseds[:, i]\n        del temp\n\n    if callables is not None:\n        for fn in callables:\n            fn(specgrid)\n\n    return specgrid\n\n\ndef calc_absflux_cov_matrices(specgrid, sedgrid, filter_names):\n    \"\"\" Calculate the absflux covariance matrices for each model\n    Must be done on the full spectrum of each model to account for\n    the changing combined spectral response due to the model SED and\n    the filter response curve.\n\n    Parameters\n    ----------\n    specgrid: SpectralGrid instance\n        instance of the spectral grid containing the full spectrum fluxes\n\n    sedgrid: SpectralGrid instance\n        instance of the spectral grid containing the band SED fluxes\n\n    Returns\n    -------\n    absflux_covmat :\n    \"\"\"\n\n    # get the fractional absflux covariance matrix\n    absflux_cov_mats = absflux_covmat.hst_frac_matrix(\n        filter_names, spectrum=(specgrid.lamb[:], specgrid.seds)\n    )\n\n    # setup the output quantities\n    n_models = specgrid.seds.shape[0]\n    n_filters = len(filter_names)\n    n_offdiag = ((n_filters ** 2) - n_filters) / 2\n    cov_diag = np.empty((n_models, n_filters), dtype=np.float64)\n    cov_offdiag = np.empty((n_models, n_offdiag), dtype=np.float64)\n\n    # pack the resulting covariance matrices into diganonal and\n    # non-diagnonal terms\n    #   much more efficient for use later in combining with AST results\n    #     and fitting\n    #   also convert from fractional to physical flux units\n    m = 0\n    cov_diag[:, n_filters - 1] = absflux_cov_mats[\n        :, n_filters - 1, n_filters - 1\n    ] * np.square(sedgrid.seds[:, n_filters - 1])\n    for k in range(n_filters - 1):\n        cov_diag[:, k] = absflux_cov_mats[:, k, k] * np.square(sedgrid.seds[:, k])\n        for l in range(k + 1, n_filters):\n            cov_offdiag[:, m] = (\n                absflux_cov_mats[:, k, l] * sedgrid.seds[:, k] * sedgrid.seds[:, l]\n            )\n            m += 1\n\n    return (cov_diag, cov_offdiag)\n", "meta": {"hexsha": "dc09a04a71f3c84eb28dc208202a310d06f29bd3", "size": 19525, "ext": "py", "lang": "Python", "max_stars_repo_path": "beast/physicsmodel/creategrid.py", "max_stars_repo_name": "cmurray-astro/beast", "max_stars_repo_head_hexsha": "cbbf6a663126367632c065ae63b341bea325e2ea", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "beast/physicsmodel/creategrid.py", "max_issues_repo_name": "cmurray-astro/beast", "max_issues_repo_head_hexsha": "cbbf6a663126367632c065ae63b341bea325e2ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-06-25T16:26:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-25T16:26:02.000Z", "max_forks_repo_path": "beast/physicsmodel/creategrid.py", "max_forks_repo_name": "cmurray-astro/beast", "max_forks_repo_head_hexsha": "cbbf6a663126367632c065ae63b341bea325e2ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6450567261, "max_line_length": 87, "alphanum_fraction": 0.60368758, "include": true, "reason": "import numpy,from astropy", "num_tokens": 4883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.18572182640863177}}
{"text": "#!/usr/bin/env python3\n\nimport fileinput\nimport numpy as np\nimport re\nimport os\nfrom collections import defaultdict\nimport argparse\nimport sys\nfrom pathlib import Path\n\n\nclass Atom:\n    S = ''\n    x = np.array([])\n\n    def __init__(self, string):\n        inp = string.split()\n        self.S = inp[0]\n        self.x = np.array(list(map(float, inp[1:])))\n\n    def __repr__(self):\n        return self.S + \" \" + \" \".join(map(str, self.x))\n\n    def scale(self, a):\n        self.x *= a\n\n\ndef getMol(qcfile):\n    m = {'molecule': re.compile('^[$]molecule', re.IGNORECASE),\n         'end':      re.compile('^[$]end', re.IGNORECASE),\n         'bohr':     re.compile('input_bohr.*true', re.IGNORECASE),\n         }\n\n    bohr = False\n    molecule = []\n\n    # find start of the molecule section\n    for line in qcfile:\n        if m['bohr'].match(line):\n            bohr = True\n        if m['molecule'].match(line):\n            break\n\n    next(qcfile)  # skip over comment line\n\n    # parse in molecules\n    for line in qcfile:\n        if m['end'].match(line):\n            break\n\n        molecule.append(Atom(line))\n\n    # keep looking for a unit conversion factor\n    for line in qcfile:\n        if m['bohr'].match(line):\n            bohr = True\n\n    scale = 0.10  # \\AA -> nm\n    if bohr:\n        scale *= 0.529177210903  # a_0 -> \\AA\n\n    for a in molecule:\n        a.scale(scale)\n\n    return molecule\n\n\ndef writeGRO(atoms, name=\"GIFS\", residue=\"QM\", output=sys.stdout):\n    \"\"\"gro file format:\n\n    title string (free format string, optional time in ps after ‘t=’)\n    number of atoms (free format integer)\n    one line for each atom (fixed format, see below)\n    box vectors (free format, space separated reals), values: v1(x) v2(y) v3(z)\n\n    [atoms]\n    residue number (5 positions, integer)\n    residue name (5 characters)\n    atom name (5 characters)\n    atom number (5 positions, integer)\n    position (in nm, x y z in 3 columns: 8 positions with 3 decimal places)\n    velocity (in nm/ps, x y z in 3 columns: 8 positions with 4 decimal places)\n    fmt=\"%5d%-5s%5s%5d%8.3f%8.3f%8.3f%8.4f%8.4f%8.4f\"\n\n    N.B.: We do not inclued velocities\n    \"\"\"\n    \n    print(name, file=output)\n    print(len(atoms), file=output)\n\n    for (i, a) in enumerate(atoms):\n        print(\"%5d%-5s%5s%5d%8.3f%8.3f%8.3f\" %\n              (1, residue, a.S, i, a.x[0], a.x[1], a.x[2]), file=output)\n\n    print(\"0 0 0\", file=output)\n\n\ndef get_block(block_name, f):\n    block = []\n    start = re.compile('^\\[ *' + block_name + ' *\\].*', re.IGNORECASE|re.MULTILINE)\n    stop = re.compile('^[\\[#].*', re.MULTILINE)\n    copy = False\n    with open(f) as lines:\n        for line in lines:\n            line = line.strip()\n            if copy and stop.search(line) is not None:\n                copy = False\n                break\n            if start.search(line) is not None:\n                copy = True\n\n            if copy:\n                block.append(line.strip())\n    \n    return block\n\n\ndef get_atomtypes(atoms, f):\n    ats = set([ ffDict[s2z[atom.S]] for atom in atoms])\n    output = []\n    with open(f) as lines:\n        for line in lines:\n            if ats & set(line.split()):\n                output.append(line.strip())\n    output.append('\\n')\n    return output\n\n\ndef writeTOP(atoms, name=\"GIFS\", system=\"GIFS\", residue=\"QM\", forcefield=None, noincludes=False, output=sys.stdout):\n    # FIXME: want to be able to choose the water topology\n\n    top = []\n    \n    if noincludes:\n        top += get_block('defaults', ffDict['path'] / \"forcefield.itp\")\n        \n        top.append('\\n[ atomtypes ]')\n        top.append('; name bond_type z mass charge ptype sigma espilon')\n        top += get_atomtypes(atoms, ffDict['path'] / \"ffnonbonded.itp\")\n\n    else:\n        top.append('; Include forcefield parameters')\n        top.append(f'#include \"{forcefield}/forcefield.itp\"')\n    \n    top.append(\"\\n[ moleculetype ]\")\n    top.append(\"; Name         nrexcl\")\n    top.append(f\"{name}        3\")\n\n    top.append(\"\\n[ atoms ]\")\n    top.append(\";  nr type         resnr residue atom      cgnr   charge       mass\")\n\n    for (i, a) in enumerate(atoms, start=1):\n        top.append(fmtTopAtoms(i, a, residue))\n\n    top.append(\"\\n[ system ]\")\n    top.append(\"; Name\")\n    top.append(f\"QMMM {system}\")\n    top.append(\"\\n[ molecules ]\")\n    top.append(\"; Compound        #mols\")\n    top.append(f\"{name}        1\")\n\n    print(\"\\n\".join(top), file=output)\n\n\n\ndef fmtTopAtoms(nr, atom, residue, resnr=1):\n    #  nr  type       resnr residue  atom    cgnr     charge   mass\n    #  1   opls_287      1    GLY      N      1\n    #  2   opls_290      1    GLY     H1      1\n    # ...\n    # or:\n    #  1   opls_287      1    GLY      N      1       -0.3    14.0067\n    #  2   opls_290      1    GLY     H1      1       0.33      1.008\n    # ...\n\n    # Notes: Charge and mass are optional. We do not perturb mass, but\n    # set the charge to 0. The name in the atom field must match that\n    # defined in type. Charge groups, cgnr, *were previously*\n    # constructed such that there are no more than 6 atoms in a single\n    # charge group (Gromacs' max is 32). However, this produced errors\n    # (blowing-up) with some solvents. Following qforce [1], we simply\n    # place each atom in its own charge group.\n\n    # [1]: https://github.com/selimsami/qforce/blob/master/qforce/forcefield.py#L168\n\n    sym = ffDict[s2z[atom.S]]\n    cgnr = nr\n    chg = 0.0\n    return f\"{nr:5} {sym:12} {resnr:5} {residue:7} {atom.S:5} {cgnr:5} {chg:8.3}\"\n\n\ndef genffD(forcefield):\n\n    ff = Path(forcefield)\n    if not ff.exists():\n        ff = Path(os.environ['GMXDATA']) / \"top\" / (forcefield)\n\n    ffDict['path']=ff\n\n    with open (ff / \"ffnonbonded.itp\") as f:\n        o = 0  # special case offset for OPLS-AA\n        if forcefield == \"oplsaa.ff\":\n            o = 1\n        for line in f:\n            field = line.split()\n            if len(field) > 4 + o and field[4+o] == 'A':\n                ffDict[int(field[1+o])] = field[0]\n                    \n\ndef main():\n    args = getArgs()\n    genffD(args.ff)\n\n    print(\"reading\", args.f)\n    with open(args.f) as f:\n        molecule = getMol(f)\n\n    with open(args.o + \".gro\", 'w') as f:\n        writeGRO(molecule, name=args.n, residue=args.r, output=f)\n    print(\"wrote\", args.o + \".gro\")\n\n    with open(args.o + \".top\", 'w') as f:\n        writeTOP(molecule, name=args.n, system=args.s, residue=args.r, forcefield=args.ff, noincludes=args.noincludes, output=f)\n    print(\"wrote\", args.o + \".top\")\n\n    print(\"Be sure to check your topology file for missing atoms\")\n    \n        \n\ndef getArgs():\n    parser = argparse.ArgumentParser(description='Convert a Q-Chem input file for use with Gromacs under GIFS')\n    parser.add_argument(\"-f\", metavar=\"input\", required=True,\n                        help=\"name of Q-Chem input file\")\n    parser.add_argument(\"-o\", metavar=\"output\", required=True,\n                        help=\"name of output .gro/.top files\")\n    parser.add_argument(\"-r\", metavar=\"residue\", default=\"QM\",\n                        help=\"name for residue; defaults to QM\")\n    parser.add_argument(\"-n\", metavar=\"name\", default=\"GIFS\",\n                        help=\"molecule name; defaults to GIFS\")\n    parser.add_argument(\"-s\", metavar=\"name\", default=\"GIFS\",\n                        help=\"system name; defaults to GIFS\")\n    parser.add_argument(\"--ff\", metavar=\"forcefield\", default=\"oplsaa.ff\",\n                        help=\"forcefield to use; defaults to oplsaa.ff\")\n    parser.add_argument(\"--noincludes\", default=False, action='store_true',\n                        help=\"generate self-contained topology with no includes\")\n    return parser.parse_args()\n\n\nffDict = defaultdict(lambda: print(\"Warning: unknown atom in forcefield\", file=sys.stderr) or \"ff_???\")\n\ns2z = {\n    'H':   1, 'He':  2, 'Li':  3, 'Be':  4, 'B':   5, 'C':   6,\n    'N':   7, 'O':   8, 'F':   9, 'Ne': 10, 'Na': 11, 'Mg': 12,\n    'Al': 13, 'Si': 14, 'P':  15, 'S':  16, 'Cl': 17, 'Ar': 18,\n    'K':  19, 'Ca': 20, 'Sc': 21, 'Ti': 22, 'V':  23, 'Cr': 24,\n    'Mn': 25, 'Fe': 26, 'Co': 27, 'Ni': 28, 'Cu': 29, 'Zn': 30,\n    'Ga': 31, 'Ge': 32, 'As': 33, 'Se': 34, 'Br': 35, 'Kr': 36,\n    'Rb': 37, 'Sr': 38, 'Y':  39, 'Zr': 40, 'Nb': 41, 'Mo': 42,\n    'Tc': 43, 'Ru': 44, 'Rh': 45, 'Pd': 46, 'Ag': 47, 'Cd': 48,\n    'In': 49, 'Sn': 50, 'Sb': 51, 'Te': 52, 'I':  53, 'Xe': 54,\n    'Cs': 55, 'Ba': 56, 'La': 57, 'Ce': 58, 'Pr': 59, 'Nd': 60,\n    'Pm': 61, 'Sm': 62, 'Eu': 63, 'Gd': 64, 'Tb': 65, 'Dy': 66,\n    'Ho': 67, 'Er': 68, 'Tm': 69, 'Yb': 70, 'Lu': 71, 'Hf': 72,\n    'Ta': 73, 'W':  74, 'Re': 75, 'Os': 76, 'Ir': 77, 'Pt': 78,\n    'Au': 79, 'Hg': 80, 'Tl': 81, 'Pb': 82, 'Bi': 83, 'Po': 84,\n    'At': 85, 'Rn': 86, 'Fr': 87, 'Ra': 88, 'Ac': 89, 'Th': 90,\n    'Pa': 91, 'U':  92, 'Np': 93, 'Pu': 94, 'Am': 95, 'Cm': 96,\n    'Bk': 97, 'Cf': 98, 'Es': 99, 'Fm': 100, 'Md': 101, 'No': 102,\n    'Lr': 103, 'Rf': 104, 'Db': 105, 'Sg': 106, 'Bh': 107, 'Hs': 108,\n    'Mt': 109, 'Ds': 110, 'Rg': 111, 'Cn': 112, 'Nh': 113, 'Fl': 114,\n    'Mc': 115, 'Lv': 116, 'Ts': 117, 'Og': 118,\n}\n\nz2s = {v:k for k,v in s2z.items()}\n\nif __name__ == \"__main__\":\n    main()\n    # genffD(\"oplsaa.ff\")\n    # buildffDict()\n    # print(ffDict)\n", "meta": {"hexsha": "d28b00ac2573e2e5c03bdafdd51ba6aaebe4a159", "size": 9183, "ext": "py", "lang": "Python", "max_stars_repo_path": "util/qc2gifs.py", "max_stars_repo_name": "farajilab/gifs_release", "max_stars_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-04T18:56:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:49:22.000Z", "max_issues_repo_path": "util/qc2gifs.py", "max_issues_repo_name": "farajilab/gifs_release", "max_issues_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util/qc2gifs.py", "max_forks_repo_name": "farajilab/gifs_release", "max_forks_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-08T00:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T00:11:00.000Z", "avg_line_length": 32.5638297872, "max_line_length": 128, "alphanum_fraction": 0.5425242296, "include": true, "reason": "import numpy", "num_tokens": 3005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.18572182447013202}}
{"text": "import os\nimport numpy as np\nimport subprocess\nfrom ..mbase import which\nfrom ..utils.cvfdutil import centroid_of_polygon\nfrom ..plot.plotutil import plot_cvfd\n\nclass Triangle(object):\n    \"\"\"\n    Class to work with the triangle program to unstructured triangular grids.\n    Information on the triangle program can be found at\n    https://www.cs.cmu.edu/~quake/triangle.html\n\n    Parameters\n    ----------\n    model_ws : str\n        workspace location for creating triangle files (default is '.')\n    exe_name : str\n        path and name of the triangle program. (default is triange, which\n        means that the triangle program must be in your path)\n    maximum_area : float\n        the maximum area for any triangle.  The default value is None, which\n        means that the user must specify maximum areas for each region.\n    angle : float\n        Triangle will continue to add vertices until no angle is less than\n        this specified value.  (default is 20 degrees)\n    additional_args : list\n        list of additional command line switches to pass to triangle\n\n    Returns\n    -------\n    None\n\n    \"\"\"\n    def __init__(self, model_ws='.', exe_name='triangle', maximum_area=None,\n                 angle=20., additional_args=None):\n        self.model_ws = model_ws\n        exe_name = which(exe_name)\n        if exe_name is None:\n            raise Exception('Cannot find gridgen binary executable')\n        self.exe_name = os.path.abspath(exe_name)\n        self.angle = angle\n        self.maximum_area = maximum_area\n        self.additional_args = additional_args\n        self._initialize_vars()\n        return\n\n    def add_polygon(self, polygon):\n        \"\"\"\n        Add a polygon\n\n        Parameters\n        ----------\n        polygon : list\n            polygon is a list of (x, y) points\n\n        Returns\n        -------\n        None\n\n        \"\"\"\n        self._polygons.append(polygon)\n        return\n\n    def add_hole(self, hole):\n        \"\"\"\n        Add a point that will turn enclosing polygon into a hole\n\n        Parameters\n        ----------\n        hole : tuple\n            (x, y)\n\n        Returns\n        -------\n        None\n\n        \"\"\"\n        self._holes.append(hole)\n        return\n\n    def add_region(self, point, attribute=0, maximum_area=None):\n        \"\"\"\n        Add a point that will become a region with a maximum area, if\n        specified.\n\n        Parameters\n        ----------\n        point : tuple\n            (x, y)\n\n        attribute : integer or float\n            integer value assigned to output elements\n\n        maximum_area : float\n            maximum area of elements in region\n\n        Returns\n        -------\n        None\n\n        \"\"\"\n        self._regions.append([point, attribute, maximum_area])\n        return\n\n    def build(self, verbose=False):\n        \"\"\"\n        Build the triangular mesh\n\n        Parameters\n        ----------\n        verbose : bool\n            If true, print the results of the triangle command to the terminal\n            (default is False)\n\n        Returns\n        -------\n        None\n\n        \"\"\"\n\n        # provide some protection by removing existing files\n        self.clean()\n\n        # write the active domain to a file\n        fname = os.path.join(self.model_ws, self.file_prefix + '.0.node')\n        self._write_nodefile(fname)\n\n        # poly file\n        fname = os.path.join(self.model_ws, self.file_prefix + '.0.poly')\n        self._write_polyfile(fname)\n\n        # Construct the triangle command\n        cmds = [self.exe_name]\n        if self.maximum_area is not None:\n            cmds.append('-a{}'.format(self.maximum_area))\n        else:\n            cmds.append('-a')\n        if self.angle is not None:\n            cmds.append('-q{}'.format(self.angle))\n        if self.additional_args is not None:\n            cmds += self.additional_args\n        cmds.append('-A') # assign attributes\n        cmds.append('-p') # triangulate .poly file\n        cmds.append('-V') # verbose\n        cmds.append('-D') # delaunay triangles for finite volume\n        cmds.append('-e') # edge file\n        cmds.append('-n') # neighbor file\n        cmds.append(self.file_prefix + '.0') # output file name\n\n        # run Triangle\n        buff = subprocess.check_output(cmds, cwd=self.model_ws)\n        buff = buff.decode()\n        if verbose:\n            print(buff)\n\n        # load the results\n        self._load_results()\n        self.ncpl = self.ele.shape[0]\n        self.nvert = self.node.shape[0]\n\n        # create verts and iverts\n        self.verts = self.node[['x', 'y']]\n        self.verts = np.array(self.verts.tolist(), np.float)\n        self.iverts = []\n        for row in self.ele:\n            self.iverts.append([row[1], row[2], row[3]])\n\n        return\n\n    def plot(self, ax=None, layer=0, edgecolor='k', facecolor='none',\n             cmap='Dark2', a=None, masked_values=None, **kwargs):\n        \"\"\"\n        Plot the grid.  This method will plot the grid using the shapefile\n        that was created as part of the build method.\n\n        Note that the layer option is not working yet.\n\n        Parameters\n        ----------\n        ax : matplotlib.pyplot axis\n            The plot axis.  If not provided it, plt.gca() will be used.\n            If there is not a current axis then a new one will be created.\n        layer : int\n            Layer number to plot\n        cmap : string\n            Name of colormap to use for polygon shading (default is 'Dark2')\n        edgecolor : string\n            Color name.  (Default is 'scaled' to scale the edge colors.)\n        facecolor : string\n            Color name.  (Default is 'scaled' to scale the face colors.)\n        a : numpy.ndarray\n            Array to plot.\n        masked_values : iterable of floats, ints\n            Values to mask.\n        kwargs : dictionary\n            Keyword arguments that are passed to\n            PatchCollection.set(``**kwargs``).  Some common kwargs would be\n            'linewidths', 'linestyles', 'alpha', etc.\n\n        Returns\n        -------\n        None\n\n        \"\"\"\n        import matplotlib.pyplot as plt\n\n        if ax is None:\n            ax = plt.gca()\n\n        pc = plot_cvfd(self.verts, self.iverts, ax=ax, edgecolor=edgecolor,\n                       facecolor=facecolor, cmap=cmap, a=a,\n                       masked_values=masked_values, **kwargs)\n        ax.autoscale()\n        return pc\n\n    def get_boundary_marker_array(self):\n        \"\"\"\n        Get an integer array that has boundary markers\n\n        Returns\n        -------\n        iedge : ndarray\n            integer array of size ncpl containing a boundary ids.  The array\n            contains zeros for cells that do not touch a boundary.  The\n            boundary ids are the segment numbers for each segment in each\n            polygon that is added with the add_polygon method.\n\n        \"\"\"\n        iedge = np.zeros((self.ncpl), dtype=np.int)\n        boundary_markers = np.unique(self.edge['boundary_marker'])\n        for ibm in boundary_markers:\n            icells = self.get_edge_cells(ibm)\n            iedge[icells] = ibm\n        return iedge\n\n    def plot_boundary(self, ibm, ax=None, **kwargs):\n        \"\"\"\n        Plot a line and vertices for the specified boundary marker\n\n        Parameters\n        ----------\n        ibm : integer\n            plot the boundary for this boundary marker\n\n        ax : matplotlib.pyplot.Axes\n           axis to add the plot to.  (default is plt.gca())\n\n        kwargs : dictionary\n            dictionary of arguments to pass to ax.plot()\n\n        Returns\n        -------\n        None\n\n        \"\"\"\n        import matplotlib.pyplot as plt\n        if ax is None:\n            ax = plt.gca()\n        idx = np.where(self.edge['boundary_marker'] == ibm)[0]\n        for i in idx:\n            iv1 = self.edge['endpoint1'][i]\n            iv2 = self.edge['endpoint2'][i]\n            x1 = self.node['x'][iv1]\n            x2 = self.node['x'][iv2]\n            y1 = self.node['y'][iv1]\n            y2 = self.node['y'][iv2]\n            ax.plot([x1, x2], [y1, y2], **kwargs)\n        return\n\n    def plot_vertices(self, ax=None, **kwargs):\n        \"\"\"\n        Plot the mesh vertices\n\n        Parameters\n        ----------\n        ax : matplotlib.pyplot.Axes\n           axis to add the plot to.  (default is plt.gca())\n\n        kwargs : dictionary\n            dictionary of arguments to pass to ax.plot()\n\n        Returns\n        -------\n        None\n\n        \"\"\"\n        import matplotlib.pyplot as plt\n        if ax is None:\n            ax = plt.gca()\n        ax.plot(self.node['x'], self.node['y'], lw=0, **kwargs)\n        return\n\n    def label_vertices(self, ax=None, onebased=True, **kwargs):\n        \"\"\"\n        Label the mesh vertices with their vertex numbers\n\n        Parameters\n        ----------\n        ax : matplotlib.pyplot.Axes\n           axis to add the plot to.  (default is plt.gca())\n\n        onebased : bool\n            Make the labels one-based if True so that they correspond to\n            what would be written to MODFLOW.\n\n        kwargs : dictionary\n            dictionary of arguments to pass to ax.text()\n\n        Returns\n        -------\n        None\n\n        \"\"\"\n        import matplotlib.pyplot as plt\n        if ax is None:\n            ax = plt.gca()\n        for i in range(self.verts.shape[0]):\n            x = self.verts[i, 0]\n            y = self.verts[i, 1]\n            s = i\n            if onebased:\n                s += 1\n            s = '{}'.format(s)\n            ax.text(x, y, s, **kwargs)\n        return\n\n    def plot_centroids(self, ax=None, **kwargs):\n        \"\"\"\n        Plot the cell centroids\n\n        Parameters\n        ----------\n        ax : matplotlib.pyplot.Axes\n           axis to add the plot to.  (default is plt.gca())\n\n        kwargs : dictionary\n            dictionary of arguments to pass to ax.plot()\n\n        Returns\n        -------\n        None\n\n        \"\"\"\n        import matplotlib.pyplot as plt\n        if ax is None:\n            ax = plt.gca()\n        xcyc = self.get_xcyc()\n        ax.plot(xcyc[:, 0], xcyc[:, 1], lw=0, **kwargs)\n        return\n\n    def label_cells(self, ax=None, onebased=True, **kwargs):\n        \"\"\"\n        Label the cells with their cell numbers\n\n        Parameters\n        ----------\n        ax : matplotlib.pyplot.Axes\n           axis to add the plot to.  (default is plt.gca())\n\n        onebased : bool\n            Make the labels one-based if True so that they correspond to\n            what would be written to MODFLOW.\n\n        kwargs : dictionary\n            dictionary of arguments to pass to ax.text()\n\n        Returns\n        -------\n        None\n\n        \"\"\"\n        import matplotlib.pyplot as plt\n        if ax is None:\n            ax = plt.gca()\n        xcyc = self.get_xcyc()\n        for i in range(xcyc.shape[0]):\n            x = xcyc[i, 0]\n            y = xcyc[i, 1]\n            s = i\n            if onebased:\n                s += 1\n            s = '{}'.format(s)\n            ax.text(x, y, s, **kwargs)\n        return\n\n    def get_xcyc(self):\n        \"\"\"\n        Get a 2-dimensional array of x and y cell center coordinates.\n\n        Returns\n        -------\n        xcyc : ndarray\n            column 0 contains the x coordinates and column 1 contains the\n            y coordinates\n\n        \"\"\"\n        ncpl = len(self.iverts)\n        xcyc = np.empty((ncpl, 2), dtype=np.float)\n        for i, icell2d in enumerate(self.iverts):\n            points = []\n            for iv in icell2d:\n                x = self.verts[iv, 0]\n                y = self.verts[iv, 1]\n                points.append((x, y))\n            xc, yc = centroid_of_polygon(points)\n            xcyc[i, 0] = xc\n            xcyc[i, 1] = yc\n        return xcyc\n\n    def get_cell2d(self):\n        \"\"\"\n        Get a list of the information needed for the MODFLOW DISV Package.\n\n        Returns\n        -------\n        cell2d : list (of lists)\n            innermost list contains cell number, x, y, number of vertices, and\n            then the vertex numbers comprising the cell.\n\n        \"\"\"\n        cell2d = []\n        xcyc = self.get_xcyc()\n        for i, icell2d in enumerate(self.iverts):\n            ic2dr = icell2d[::-1]\n            cell2d.append([i, xcyc[i, 0], xcyc[i, 1], len(icell2d)] + ic2dr)\n        return cell2d\n\n    def get_vertices(self):\n        \"\"\"\n        Get a list of vertices in the form needed for the MODFLOW DISV Package.\n\n        Returns\n        -------\n        vertices : list (of lists)\n            innermost list contains vertex number, x, and y\n\n        \"\"\"\n        vertices = []\n        for i, row in enumerate(self.verts):\n            vertices.append([i, row[0], row[1]])\n        return vertices\n\n    def get_edge_cells(self, ibm):\n        \"\"\"\n        Get a list of cell numbers that correspond to the specified boundary\n        marker.\n\n        Parameters\n        ----------\n        ibm : integer\n            boundary marker value\n\n        Returns\n        -------\n        cell_list : list\n            list of zero-based cell numbers\n\n        \"\"\"\n        # Create the edge dictionary if it doesn't exist\n        if self.edgedict is None:\n            edgedict = {}\n            for ie, iv1, iv2, iseg in self.edge:\n                if iseg != 0:\n                    edgedict[(iv1, iv2)] = iseg\n                    edgedict[(iv2, iv1)] = iseg\n\n        # Create a list of cells for boundary marker ibm\n        cell_list = []\n        for n, ivlist in enumerate(self.iverts):\n            itmp = ivlist + [ivlist[0]]\n            for i in range(len(ivlist)):\n                ie = (itmp[i], itmp[i + 1])\n                if ie in edgedict:\n                    if edgedict[ie] == ibm:\n                        cell_list.append(n)\n\n        return cell_list\n\n    def get_attribute_array(self):\n        \"\"\"\n        Return an array containing the attribute value for each cell.  These\n        are the attribute values that are passed into the add_region() method.\n\n        Returns\n        -------\n        attribute_array : ndarray\n\n        \"\"\"\n        return self.ele['attribute']\n\n    def clean(self):\n        \"\"\"\n        Remove the input and output files created by this class and by the\n        Triangle program\n\n        Returns\n        -------\n        None\n\n        \"\"\"\n        # remove input files\n        for ext in ['poly', 'node']:\n            fname = os.path.join(self.model_ws, self.file_prefix + '0.' + ext)\n            if os.path.isfile(fname):\n                os.remove(fname)\n                if os.path.isfile(fname):\n                    print('Could not remove: {}'.format(fname))\n        # remove output files\n        for ext in ['poly', 'ele', 'node', 'neigh', 'edge']:\n            fname = os.path.join(self.model_ws, self.file_prefix + '1.' + ext)\n            if os.path.isfile(fname):\n                os.remove(fname)\n                if os.path.isfile(fname):\n                    print('Could not remove: {}'.format(fname))\n        return\n\n    def _initialize_vars(self):\n        self.file_prefix = '_triangle'\n        self.ncpl = 0\n        self.nvert = 0\n        self._active_domain = None\n        self._polygons = []\n        self._holes = []\n        self._regions = []\n        self.verts = None\n        self.iverts = None\n        self.edgedict = None\n        return\n\n    def _load_results(self):\n\n        # node file\n        ext = 'node'\n        dt = [('ivert', int), ('x', float), ('y', float)]\n        fname = os.path.join(self.model_ws, self.file_prefix + '.1.' + ext)\n        setattr(self, ext, None)\n        if os.path.isfile(fname):\n            f = open(fname, 'r')\n            line = f.readline()\n            f.close()\n            ll = line.strip().split()\n            nvert = int(ll[0])\n            ndim = int(ll[1])\n            assert ndim == 2, 'Dimensions in node file is not 2'\n            iattribute = int(ll[2])\n            if iattribute == 1:\n                dt.append(('attribute', int))\n            ibm = int(ll[3])\n            if ibm == 1:\n                dt.append(('boundary_marker', int))\n            a = np.loadtxt(fname, skiprows=1, comments='#', dtype=dt)\n            assert a.shape[0] == nvert\n            setattr(self, ext, a)\n\n        # ele file\n        ext = 'ele'\n        dt = [('icell', int), ('iv1', int), ('iv2', int), ('iv3', int)]\n        fname = os.path.join(self.model_ws, self.file_prefix + '.1.' + ext)\n        setattr(self, ext, None)\n        if os.path.isfile(fname):\n            f = open(fname, 'r')\n            line = f.readline()\n            f.close()\n            ll = line.strip().split()\n            ncells = int(ll[0])\n            npt = int(ll[1])\n            assert npt == 3, 'Nodes per triangle in ele file is not 3'\n            iattribute = int(ll[2])\n            if iattribute == 1:\n                dt.append(('attribute', int))\n            a = np.loadtxt(fname, skiprows=1, comments='#', dtype=dt)\n            assert a.shape[0] == ncells\n            setattr(self, ext, a)\n\n        # edge file\n        ext = 'edge'\n        dt = [('iedge', int), ('endpoint1', int), ('endpoint2', int)]\n        fname = os.path.join(self.model_ws, self.file_prefix + '.1.' + ext)\n        setattr(self, ext, None)\n        if os.path.isfile(fname):\n            f = open(fname, 'r')\n            line = f.readline()\n            f.close()\n            ll = line.strip().split()\n            nedges = int(ll[0])\n            ibm = int(ll[1])\n            if ibm == 1:\n                dt.append(('boundary_marker', int))\n            a = np.loadtxt(fname, skiprows=1, comments='#', dtype=dt)\n            assert a.shape[0] == nedges\n            setattr(self, ext, a)\n\n        # neighbor file\n        ext = 'neigh'\n        dt = [('icell', int), ('neighbor1', int), ('neighbor2', int),\n              ('neighbor3', int)]\n        fname = os.path.join(self.model_ws, self.file_prefix + '.1.' + ext)\n        setattr(self, ext, None)\n        if os.path.isfile(fname):\n            f = open(fname, 'r')\n            line = f.readline()\n            f.close()\n            ll = line.strip().split()\n            ncells = int(ll[0])\n            nnpt = int(ll[1])\n            assert nnpt == 3, 'Neighbors per triangle in neigh file is not 3'\n            a = np.loadtxt(fname, skiprows=1, comments='#', dtype=dt)\n            assert a.shape[0] == ncells\n            setattr(self, ext, a)\n\n        return\n\n    def _write_nodefile(self, fname):\n        f = open(fname, 'w')\n        nvert = 0\n        for p in self._polygons:\n            nvert += len(p)\n        s = '{} {} {} {}\\n'.format(nvert, 2, 0, 0)\n        f.write(s)\n        ip = 0\n        for p in self._polygons:\n            for i, vertex in enumerate(p):\n                s = '{} {} {}\\n'.format(ip, vertex[0], vertex[1])\n                f.write(s)\n                ip += 1\n        f.close()\n\n    def _write_polyfile(self, fname):\n        f = open(fname, 'w')\n\n        # vertices, write zero to indicate read from node file\n        s = '{} {} {} {}\\n'.format(0, 0, 0, 0)\n        f.write(s)\n\n        # segments\n        nseg = 0\n        for p in self._polygons:\n            nseg += len(p)\n        bm = 1\n        s = '{} {}\\n'.format(nseg, bm)\n        f.write(s)\n\n        iseg = 0\n        ipstart = 0\n        for p in self._polygons:\n            nseg = len(p)\n            for i in range(nseg):\n                ep1 = i\n                ep2 = i + 1\n                if ep2 > nseg - 1:\n                    ep2 = 0\n                ep1 += ipstart\n                ep2 += ipstart\n                s = '{} {} {} {}\\n'.format(iseg, ep1, ep2, iseg + 1)\n                f.write(s)\n                iseg += 1\n            ipstart += len(p)\n\n        # holes\n        nholes = len(self._holes)\n        s = '{}\\n'.format(nholes)\n        f.write(s)\n        for i, hole in enumerate(self._holes):\n            s = '{} {} {}\\n'.format(i, hole[0], hole[1])\n            f.write(s)\n\n        # regions\n        nregions = len(self._regions)\n        s = '{}\\n'.format(nregions)\n        f.write(s)\n        for i, region in enumerate(self._regions):\n            pt = region[0]\n            attribute = region[1]\n            maxarea = region[2]\n            if maxarea is None:\n                maxarea = -1.\n            s = '{} {} {} {} {}\\n'.format(i, pt[0], pt[1], attribute, maxarea)\n            f.write(s)\n\n        f.close()\n        return\n", "meta": {"hexsha": "c495f2362964b77b8c1d0b42e1d6b56a686e5322", "size": 20222, "ext": "py", "lang": "Python", "max_stars_repo_path": "flopy/utils/triangle.py", "max_stars_repo_name": "pjhaest/flopy", "max_stars_repo_head_hexsha": "369893b6e58cf37bd09c95c6e7cb129c74359214", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "flopy/utils/triangle.py", "max_issues_repo_name": "pjhaest/flopy", "max_issues_repo_head_hexsha": "369893b6e58cf37bd09c95c6e7cb129c74359214", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "flopy/utils/triangle.py", "max_forks_repo_name": "pjhaest/flopy", "max_forks_repo_head_hexsha": "369893b6e58cf37bd09c95c6e7cb129c74359214", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.60761347, "max_line_length": 79, "alphanum_fraction": 0.5081099792, "include": true, "reason": "import numpy", "num_tokens": 4707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.3522017820478896, "lm_q1q2_score": 0.18572181923758121}}
{"text": "import os\nimport sys\nimport copy\nimport numpy\nimport weakref\n\nfrom astropy.coordinates import EarthLocation\nimport astropy.units as u\n\n__all__ = ['OVRO_CONFIG_FILENAME', 'Station', 'Antenna', 'parse_config', 'ovro']\n\n\nOVRO_CONFIG_FILENAME = os.path.join(os.path.dirname(__file__), 'ovro.txt')\n\n\ndef _smart_int(s, positive_only=False):\n    i = 0\n    v = None\n    while i < len(s):\n        try:\n            if positive_only and s[i] == '-':\n                raise ValueError\n            v = int(s[i:], 10)\n            break\n        except ValueError:\n            pass\n        i += 1\n    if v is None:\n        raise ValueError(\"Cannot convert '%s' to int\" % s)\n    return v\n    \n\nclass Station(object):\n    \"\"\"\n    Class to represent the OVRO-LWA station and its antennas.\n    \"\"\"\n    \n    def __init__(self, name, lat, lon, elev, antennas=None):\n        self.name = name\n        self.lat = lat\n        self.lon = lon\n        self.elev = elev\n        \n        self.antennas = []\n        if antennas is not None:\n            self.antennas = antennas\n            \n    @classmethod\n    def from_line(cls, line):\n        \"\"\"\n        Create a new Station instance from a line in an antenna positions file.\n        \"\"\"\n        \n        name, style, lat, lon, elev, x, y, active = line.split(None, 7)\n        lat = float(lat) * numpy.pi/180\n        lon = float(lon) * numpy.pi/180\n        elev = 1182.89  ## Mean of the first 256 antennas\n        return cls(name, lat, lon, elev)\n        \n    def append(self, ant):\n        \"\"\"\n        Add an antenna to the array.\n        \"\"\"\n        \n        if not isinstance(ant, Antenna):\n            raise TypeError(\"Expected an antenna\")\n        ant.parent = weakref.proxy(self)\n        self.antennas.append(ant)\n        \n    def select_subset(self, ids):\n        \"\"\"\n        Given a list of antenna IDs (either as integer index or name), return a\n        new Station instance that only contains those antennas.\n        \"\"\"\n        \n        subset = Station(self.name+\"-fast\", self.lat*1.0, self.lon*1.0, self.elev*1.0)\n        \n        all_ids = [ant.id for ant in self.antennas]\n        for id in ids:\n            if isinstance(id, int):\n                subset.append(copy.deepcopy(self.antennas[id]))\n            else:\n                subset.append(copy.deepcopy(self.antennas[all_ids.index(id)]))\n        return subset\n        \n    @property\n    def ecef(self):\n        \"\"\"\n        Return the Earth centered, Earth fixed location of the array in meters.\n        \"\"\"\n        \n        e =  EarthLocation(lat=self.lat*u.rad, lon=self.lon*u.rad, height=self.elev*u.m)\n        return (e.x.to_value(u.m), e.y.to_value(u.m), e.z.to_value(u.m))\n        \n    @property\n    def topo_rot_matrix(self):\n        \"\"\"\n        Return the rotation matrix that takes a difference in an Earth centered,\n        Earth fixed location relative to the Station and rotates it into a\n        topocentric frame that is south-east-zenith.\n        \"\"\"\n        \n        r = numpy.array([[ numpy.sin(self.lat)*numpy.cos(self.lon), numpy.sin(self.lat)*numpy.sin(self.lon), -numpy.cos(self.lat)],\n                         [-numpy.sin(self.lon),                     numpy.cos(self.lon),                      0                  ],\n                         [ numpy.cos(self.lat)*numpy.cos(self.lon), numpy.cos(self.lat)*numpy.sin(self.lon),  numpy.sin(self.lat)]])\n        return r\n        \n    @property\n    def casa_position(self):\n        \"\"\"\n        Return a four-element tuple of (CASA position reference, CASA position 1,\n        CASA position 2, CASA position 3, CASA position 4) that is suitable for\n        use with casacore.measures.measures.position.\n        \"\"\"\n        \n        x, y, z = self.ecef\n        return 'ITRF', '%fm' % x, '%fm' % y, '%fm' % z\n\n\nclass Antenna(object):\n    \"\"\"\n    Class to represent an antenna in the OVRO-LWA.\n    \"\"\"\n    \n    def __init__(self, id, lat, lon, elev):\n        if isinstance(id, str):\n            id = _smart_int(id, positive_only=True)\n        self.id = id\n        self.lat = lat\n        self.lon = lon\n        self.elev = elev\n        self.parent = None\n        \n    @classmethod\n    def from_line(cls, line):\n        \"\"\"\n        Create a new Antenna instance from a line in an antenna positions file.\n        \"\"\"\n        \n        name, style, lat, lon, elev, x, y, active = line.split(None, 7)\n        lat = float(lat) * numpy.pi/180\n        lon = float(lon) * numpy.pi/180\n        try:\n            elev = float(elev)\n        except ValueError:\n            elev = 1182.89  ## Mean of the first 256 antennas\n        return cls(name, lat, lon, elev)\n        \n    @property\n    def ecef(self):\n        \"\"\"\n        Return the Earth centered, Earth fixed location of the antenna in meters.\n        \"\"\"\n        \n        e = EarthLocation(lat=self.lat*u.rad, lon=self.lon*u.rad, height=self.elev*u.m)\n        return (e.x.to_value(u.m), e.y.to_value(u.m), e.z.to_value(u.m))\n        \n    @property\n    def enz(self):\n        \"\"\"\n        Return the topocentric east-north-zenith coordinates for the antenna \n        relative to the center of its associated Station in meters.\n        \"\"\"\n        \n        if self.parent is None:\n            raise RuntimeError(\"Cannot find east-north-zenith without an associated Station\")\n            \n        ecefFrom = numpy.array(self.parent.ecef)\n        ecefTo = numpy.array(self.ecef)\n\n        rho = ecefTo - ecefFrom\n        rot = self.parent.topo_rot_matrix\n        sez = numpy.dot(rot, rho)\n\n        # Convert from south, east, zenith to east, north, zenith\n        enz = 1.0*sez[[1,0,2]]\n        enz[1] *= -1.0\n        return enz\n\n\ndef parse_config(filename):\n    \"\"\"\n    Given an OVRO-LWA configuration file, parse it and return a Station instance.\n    \"\"\"\n    \n    with open(filename, 'r') as fh:\n        for line in fh:\n            if len(line) < 3:\n                continue\n            elif line[0] == '#':\n                continue\n                \n            if line.startswith('LWA-000'):\n                line = line.replace('LWA-000', 'OVRO-LWA')\n                station = Station.from_line(line)\n            elif line.find('NO') > -2:\n                ant = Antenna.from_line(line)\n                station.append(ant)\n                \n    return station\n\n\n# A ready-made Station instance, filled with Antennas\novro = parse_config(OVRO_CONFIG_FILENAME)\n\n# Use OVRO_MMA as the telescope name until CASA knows about OVRO-LWA\novro.name = 'OVRO_MMA'\n\n# Change the order to match what's going on in Phase I\n## The current list as of 2022 Jan 5\ninterim = ['LWA-266', 'LWA-259', 'LWA-268', 'LWA-267', 'LWA-271', 'LWA-269', \n           'LWA-276', 'LWA-273', 'LWA-278', 'LWA-277', 'LWA-282', 'LWA-281', \n           'LWA-307', 'LWA-285', 'LWA-309', 'LWA-308', 'LWA-311', 'LWA-310', \n           'LWA-313', 'LWA-312', 'LWA-321', 'LWA-314', 'LWA-330', 'LWA-327', \n           'LWA-338', 'LWA-332', 'LWA-340', 'LWA-339', 'LWA-352', 'LWA-341', \n           'LWA-362', 'LWA-353', 'LWA-257', 'LWA-255', 'LWA-260', 'LWA-258', \n           'LWA-265', 'LWA-263', 'LWA-272', 'LWA-270', 'LWA-283', 'LWA-280', \n           'LWA-288', 'LWA-284', 'LWA-292', 'LWA-291', 'LWA-296', 'LWA-295', \n           'LWA-301', 'LWA-298', 'LWA-305', 'LWA-303', 'LWA-317', 'LWA-306', \n           'LWA-320', 'LWA-318', 'LWA-336', 'LWA-335', 'LWA-343', 'LWA-337', \n           'LWA-351', 'LWA-344', 'LWA-360', 'LWA-354', 'LWA-002', 'LWA-001', \n           'LWA-004', 'LWA-003', 'LWA-006', 'LWA-005', 'LWA-009', 'LWA-007', \n           'LWA-011', 'LWA-010', 'LWA-012', 'LWA-008', 'LWA-040', 'LWA-038', \n           'LWA-042', 'LWA-041', 'LWA-044', 'LWA-043', 'LWA-046', 'LWA-045', \n           'LWA-071', 'LWA-047', 'LWA-074', 'LWA-073', 'LWA-077', 'LWA-075', \n           'LWA-275', 'LWA-274', 'LWA-302', 'LWA-286', 'LWA-363', 'LWA-323', \n           'LWA-013', 'LWA-016', 'LWA-015', 'LWA-014', 'LWA-018', 'LWA-017', \n           'LWA-020', 'LWA-019', 'LWA-022', 'LWA-021', 'LWA-024', 'LWA-023', \n           'LWA-026', 'LWA-025', 'LWA-029', 'LWA-027', 'LWA-049', 'LWA-048', \n           'LWA-051', 'LWA-050', 'LWA-053', 'LWA-052', 'LWA-054', 'LWA-080', \n           'LWA-084', 'LWA-055', 'LWA-324', 'LWA-262', 'LWA-348', 'LWA-331', \n           'LWA-365', 'LWA-364', 'LWA-030', 'LWA-028', 'LWA-032', 'LWA-031', \n           'LWA-063', 'LWA-060', 'LWA-057', 'LWA-056', 'LWA-059', 'LWA-058', \n           'LWA-062', 'LWA-061', 'LWA-085', 'LWA-064', 'LWA-087', 'LWA-086', \n           'LWA-089', 'LWA-096', 'LWA-091', 'LWA-090', 'LWA-093', 'LWA-092', \n           'LWA-095', 'LWA-094', 'LWA-122', 'LWA-121', 'LWA-325', 'LWA-316', \n           'LWA-334', 'LWA-328', 'LWA-361', 'LWA-358', 'LWA-035', 'LWA-033', \n           'LWA-034', 'LWA-036', 'LWA-066', 'LWA-065', 'LWA-068', 'LWA-067', \n           'LWA-070', 'LWA-069', 'LWA-097', 'LWA-072', 'LWA-099', 'LWA-098', \n           'LWA-101', 'LWA-100', 'LWA-103', 'LWA-102', 'LWA-105', 'LWA-104', \n           'LWA-129', 'LWA-037', 'LWA-131', 'LWA-130', 'LWA-134', 'LWA-132', \n           'LWA-252', 'LWA-139', 'LWA-294', 'LWA-289', 'LWA-319', 'LWA-299', \n           'LWA-078', 'LWA-076', 'LWA-081', 'LWA-079', 'LWA-108', 'LWA-107', \n           'LWA-110', 'LWA-109', 'LWA-112', 'LWA-111', 'LWA-114', 'LWA-113', \n           'LWA-116', 'LWA-115', 'LWA-118', 'LWA-117', 'LWA-120', 'LWA-082', \n           'LWA-143', 'LWA-142', 'LWA-145', 'LWA-144', 'LWA-147', 'LWA-150', \n           'LWA-149', 'LWA-148', 'LWA-151', 'LWA-172', 'LWA-279', 'LWA-178', \n           'LWA-355', 'LWA-349', 'LWA-124', 'LWA-127', 'LWA-126', 'LWA-125', \n           'LWA-188', 'LWA-128', 'LWA-153', 'LWA-152', 'LWA-155', 'LWA-154', \n           'LWA-157', 'LWA-156', 'LWA-159', 'LWA-158', 'LWA-182', 'LWA-160', \n           'LWA-185', 'LWA-184', 'LWA-187', 'LWA-186', 'LWA-190', 'LWA-189', \n           'LWA-191', 'LWA-192', 'LWA-224', 'LWA-222', 'LWA-326', 'LWA-322', \n           'LWA-345', 'LWA-333', 'LWA-359', 'LWA-347', 'LWA-135', 'LWA-133', \n           'LWA-137', 'LWA-136', 'LWA-140', 'LWA-138', 'LWA-161', 'LWA-141', \n           'LWA-163', 'LWA-162', 'LWA-165', 'LWA-164', 'LWA-167', 'LWA-166', \n           'LWA-193', 'LWA-226', 'LWA-195', 'LWA-194', 'LWA-197', 'LWA-196', \n           'LWA-200', 'LWA-199', 'LWA-202', 'LWA-201', 'LWA-227', 'LWA-225', \n           'LWA-287', 'LWA-253', 'LWA-293', 'LWA-290', 'LWA-357', 'LWA-329', \n           'LWA-170', 'LWA-234', 'LWA-173', 'LWA-171', 'LWA-176', 'LWA-175', \n           'LWA-204', 'LWA-203', 'LWA-206', 'LWA-205', 'LWA-208', 'LWA-207', \n           'LWA-210', 'LWA-209', 'LWA-228', 'LWA-230', 'LWA-231', 'LWA-229', \n           'LWA-233', 'LWA-232', 'LWA-236', 'LWA-235', 'LWA-238', 'LWA-237', \n           'LWA-240', 'LWA-239', 'LWA-297', 'LWA-254', 'LWA-346', 'LWA-342', \n           'LWA-356', 'LWA-350', 'LWA-177', 'LWA-247', 'LWA-180', 'LWA-179', \n           'LWA-183', 'LWA-181', 'LWA-212', 'LWA-211', 'LWA-214', 'LWA-213', \n           'LWA-243', 'LWA-215', 'LWA-218', 'LWA-217', 'LWA-221', 'LWA-219', \n           'LWA-241', 'LWA-223', 'LWA-244', 'LWA-242', 'LWA-246', 'LWA-245', \n           'LWA-249', 'LWA-248', 'LWA-251', 'LWA-250', 'LWA-261', 'LWA-256', \n           'LWA-300', 'LWA-264', 'LWA-315', 'LWA-304']\ninterm = [_smart_int(v.replace('-', '')) for v in interim]\n## Sort by swapping until there is nothing left to swap\nwhile True:\n    orig_order = [ant.id for ant in ovro.antennas]\n    done = True\n    for i,j in enumerate(interm):\n        k = orig_order.index(j)\n        if i != k:\n            temp = ovro.antennas[k]\n            ovro.antennas[k] = ovro.antennas[i]\n            ovro.antennas[i] = temp\n            done = False\n            break\n    if done:\n        break\n## Trim\novro.antennas = ovro.antennas[:352]\n         \n", "meta": {"hexsha": "ac20ba6ade1ef1641d65ae1336ebdb71cd0ba2bc", "size": 11638, "ext": "py", "lang": "Python", "max_stars_repo_path": "station.py", "max_stars_repo_name": "lwa-project/ovro_data_recorder", "max_stars_repo_head_hexsha": "c367ece54f57cd80903b35677b45c004ea0ced80", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-12T18:20:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-12T18:20:18.000Z", "max_issues_repo_path": "station.py", "max_issues_repo_name": "lwa-project/ovro_data_recorder", "max_issues_repo_head_hexsha": "c367ece54f57cd80903b35677b45c004ea0ced80", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-03-17T20:04:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T21:00:53.000Z", "max_forks_repo_path": "station.py", "max_forks_repo_name": "lwa-project/ovro_data_recorder", "max_forks_repo_head_hexsha": "c367ece54f57cd80903b35677b45c004ea0ced80", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4097222222, "max_line_length": 132, "alphanum_fraction": 0.5180443375, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 3944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318194686359, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.18562328252201157}}
{"text": "from functools import wraps\nimport logging\nimport sys\nimport warnings\n\nif sys.version_info[:2] >= (3, 8):\n    from functools import cached_property\nelse:\n    from backports.cached_property import cached_property\n\n\nimport numpy as np\nimport scipy.signal\nimport pandas as pd\n\nfrom endaq.batch import quat\nfrom endaq.batch.utils import ide_utils\nfrom endaq.batch.utils.calc import psd, stats, shock, integrate, filters\n\n\ndef as_series(\n    unit_type,\n    data_name,\n    *,\n    edit_axis_names=lambda axis_names: axis_names,\n    default_axis_names,\n):\n    \"\"\"Format method output as a pandas Series.\"\"\"\n\n    def decorator(method):\n        @wraps(method)\n        def wrapper(self, *args, **kwargs):\n            data = method(self, *args, **kwargs)\n\n            try:\n                ch_struct = self._channels[unit_type]\n            except KeyError:\n                axis_names = default_axis_names\n            else:\n                axis_names = edit_axis_names(ch_struct.axis_names)\n\n            return pd.Series(\n                data,\n                index=pd.Index(axis_names, name=\"axis\"),\n                name=data_name,\n            )\n\n        return wrapper\n\n    return decorator\n\n\nclass Analyzer:\n    \"\"\"\n    A class which will run the analyses for the endaq cloud work.  Take the\n    important info from the IDE document so that it can be released from memory.\n    \"\"\"\n\n    # TODO: This needs to be reworked, it's currently not very efficient.\n    #       -\n    #       The current strategy is to:\n    #         1. Create a list of time indices for each segment, where the\n    #            beginning of the first segment is the earliest data present\n    #            among all channels (not al channels start and end at the same time)\n    #         2. Create a numpy array from each channel, and grab metadata such\n    #            as sampling frequency.\n    #         3. For channels with a low sampling frequency, resample them to\n    #            five times the segment frequency.\n    #         4. Pad each channel with nans so that data exists for each channel\n    #            in each time segment.\n    #         5. Split each of these by the times created in step 1\n    #         6. Lazily run analyses as they're called and cache results.\n    #       -\n    #       The issue is that this is somewhat memory intensive and just doesn't\n    #       need to be. I think we can more efficiently do piecewise evaluation\n    #       and re-use intermediate calculations without saving all of the file\n    #       as an array.\n    #       _\n    #       Proposed strategy:\n    #         1. Same as above, create a list of time indices for each segment,\n    #            where the beginning of the first segment is the earliest data\n    #            present among all channels (not al channels start and end at\n    #            the same time)\n    #         2. For each sensor type:\n    #              a. If the sensor is not present, create a list of NaNs in the\n    #                 correct shape.\n    #              b. For sensors with low sampling rates, use some sort of\n    #                 wrapper or generator that will still lazily load data from\n    #                 the file but will return interpolated data as if it had a\n    #                 higher sample rate (five times the segment frequency)\n    #              c. Iterate through the segments.  If the segment is out of\n    #                 range, skip it and place Nans in each analysis for that\n    #                 channel type.\n    #              d. Do the analyses for that segment.  This will allow us to\n    #                 reuse intermediate calculations, such as the FFT of the\n    #                 acceleration.  This is used to calculate the RMS for the\n    #                 acceleration and its integrals.\n    #\n\n    MPS2_TO_G = 1 / 9.80665\n    MPS_TO_MMPS = 1000\n    MPS_TO_UMPS = 10 ** 6\n    MPS_TO_KMPH = 3600 / 1e3\n    M_TO_MM = 1000\n\n    PV_NATURAL_FREQS = np.logspace(0, 12, base=2, num=12 * 12 + 1, endpoint=True)\n\n    def __init__(\n        self,\n        doc,\n        *,\n        preferred_chs=[],\n        accel_highpass_cutoff,\n        accel_start_time,\n        accel_end_time,\n        accel_start_margin,\n        accel_end_margin,\n        psd_freq_bin_width,\n        psd_window=\"hanning\",\n        pvss_init_freq,\n        pvss_bins_per_octave,\n        vc_init_freq,\n        vc_bins_per_octave,\n    ):\n        \"\"\"\n        Copies out the numpy arrays for the highest priority channel for each\n        sensor type, and any relevant metadata.  Cuts them into chunks.\n        \"\"\"\n        if accel_start_time is not None and accel_start_margin is not None:\n            raise ValueError(\n                \"only one of `accel_start_time` and `accel_start_margin` may be set at once\"\n            )\n        if accel_end_time is not None and accel_end_margin is not None:\n            raise ValueError(\n                \"only one of `accel_end_time` and `accel_end_margin` may be set at once\"\n            )\n\n        self._channels = ide_utils.dict_chs_best(\n            (\n                (utype, ch_struct)\n                for (utype, ch_struct) in ide_utils.chs_by_utype(doc)\n                if len(ch_struct.eventarray) > 0\n            ),\n            max_key=lambda x: (x.channel.id in preferred_chs, len(x.eventarray)),\n        )\n\n        self._filename = doc.filename\n        self._accelerationFs = None  # gets set in `_accelerationData`\n        self._accel_highpass_cutoff = accel_highpass_cutoff\n        self._accel_start_time = accel_start_time\n        self._accel_end_time = accel_end_time\n        self._accel_start_margin = accel_start_margin\n        self._accel_end_margin = accel_end_margin\n        self._psd_window = psd_window\n        self._psd_freq_bin_width = psd_freq_bin_width\n        self._pvss_init_freq = pvss_init_freq\n        self._pvss_bins_per_octave = pvss_bins_per_octave\n        self._vc_init_freq = vc_init_freq\n        self._vc_bins_per_octave = vc_bins_per_octave\n\n    # ==========================================================================\n    # Data Processing, just to make init cleaner\n    # ==========================================================================\n\n    @cached_property\n    def _accelerationData(self):\n        \"\"\"Populate the _acceleration* fields, including splitting and extending data.\"\"\"\n        ch_struct = self._channels.get(\"acc\", None)\n        if ch_struct is None:\n            logging.warning(f\"no acceleration channel in {self._filename}\")\n            return np.empty((3, 0), dtype=np.float)\n\n        aUnits = ch_struct.units[1]\n        try:\n            conversionFactor = {  # core units = m/s^2\n                \"g\": 1 / self.MPS2_TO_G,\n                \"m/s\\u00b2\": 1,\n            }[aUnits.lower()]\n        except KeyError:\n            raise ValueError(f'unknown acceleration channel units \"{aUnits}\"')\n\n        self._accelerationName = ch_struct.channel.name\n        self._accelerationFs = ch_struct.fs\n\n        times = ch_struct.eventarray.arraySlice()[0] * 1e-6  # us -> s\n        aData = conversionFactor * ch_struct.eventarray.arrayValues(\n            subchannels=ch_struct.sch_ids,\n        )\n\n        if self._accel_start_margin is not None:\n            margin = int(np.ceil(ch_struct.fs * self._accel_start_margin))\n            aData = aData[:, margin:]\n        elif self._accel_start_time is not None:\n            i = np.searchsorted(times, self._accel_start_time)\n            aData = aData[:, i:]\n        if self._accel_end_margin is not None:\n            margin = int(np.ceil(ch_struct.fs * self._accel_end_margin))\n            aData = aData[:, : (-margin or None)]\n        elif self._accel_end_time is not None:\n            i = np.searchsorted(times, self._accel_end_time)\n            aData = aData[:, :i]\n\n        if self._accel_highpass_cutoff:\n            aData = filters.highpass(\n                aData, fs=ch_struct.fs, cutoff=self._accel_highpass_cutoff, axis=-1\n            )\n\n        return aData\n\n    @cached_property\n    def _accelerationResultant(self):\n        return stats.L2_norm(self._accelerationData, axis=0)\n\n    @cached_property\n    def _microphoneData(self):\n        \"\"\"Populate the _microphone* fields, including splitting and extending data.\"\"\"\n        ch_struct = self._channels.get(\"mic\", None)\n        if ch_struct is None:\n            return np.empty(0, dtype=np.float)\n\n        units = ch_struct.units[1]\n        if units.lower() != \"a\":\n            raise ValueError(f'unknown microphone channel units \"{units}\"')\n\n        self._micName = ch_struct.channel.name\n        self._micFs = ch_struct.fs\n        data = ch_struct.eventarray.arrayValues(subchannels=ch_struct.sch_ids)\n\n        return data\n\n    @cached_property\n    def _velocityData(self):\n        aData = self._accelerationData\n        if aData.size == 0:\n            return np.empty((3, 0), dtype=np.float)\n\n        if not self._accel_highpass_cutoff:\n            logging.warning(\n                \"no highpass filter used before integration; \"\n                \"velocity calculation may be unstable\"\n            )\n\n        vData = integrate._integrate(aData, dt=1 / self._accelerationFs, axis=1)\n\n        return vData\n\n    @cached_property\n    def _displacementData(self):\n        vData = self._velocityData\n        if vData.size == 0:\n            return np.empty((3, 0), dtype=np.float)\n\n        if not self._accel_highpass_cutoff:\n            logging.warning(\n                \"no highpass filter used before integration; \"\n                \"displacement calculation may be unstable\"\n            )\n\n        dData = integrate._integrate(vData, dt=1 / self._accelerationFs, axis=1)\n\n        return dData\n\n    @cached_property\n    def _PVSSData(self):\n        aData = self._accelerationData\n        if aData.size == 0:\n            return np.empty(0, dtype=np.float), self._accelerationData\n\n        log2_f0 = np.log2(self._pvss_init_freq)\n        log2_f1 = np.log2(self._accelerationFs)\n        num_bins = np.floor(\n            self._pvss_bins_per_octave * (log2_f1 - 1 - log2_f0)\n        ).astype(int)\n\n        freqs = np.logspace(\n            start=log2_f0,\n            stop=log2_f0 + num_bins / self._pvss_bins_per_octave,\n            num=num_bins + 1,\n            base=2,\n            endpoint=True,\n        )\n        freqs = freqs[\n            (freqs >= self._accelerationFs / self._accelerationData.shape[-1])\n        ]\n        pv = shock.pseudo_velocity(\n            self._accelerationData,\n            freqs,\n            dt=1 / self._accelerationFs,\n            damp=0.05,\n            two_sided=False,\n            axis=-1,\n        )\n        assert pv.ndim == 2\n        assert 1 <= pv.shape[0] <= 3\n        assert pv.shape[-1] == len(freqs)\n\n        return freqs, pv\n\n    @cached_property\n    def _PSDData(self):\n        aData = self._accelerationData\n        if aData.size == 0:\n            return np.empty(0, dtype=np.float), self._accelerationData\n\n        return scipy.signal.welch(\n            aData,\n            fs=self._accelerationFs,\n            nperseg=int(np.ceil(self._accelerationFs / self._psd_freq_bin_width)),\n            window=self._psd_window,\n            average=\"median\",\n            axis=1,\n        )\n\n    @cached_property\n    def _VCCurveData(self):\n        \"\"\"Calculate Vibration Criteria (VC) Curves for the accelerometer.\"\"\"\n        aData = self._accelerationData\n        if aData.size == 0:\n            return np.empty(0, dtype=np.float), self._accelerationData\n\n        \"\"\"\n        Theory behind the calculation:\n        \n        Let x(t) be a real-valued time-domain signal, and X(2πf) = F{x(t)}(2πf)\n        be the Fourier Transform of that signal. By Parseval's Theorem,\n\n            ∫x(t)^2 dt = ∫|X(2πf)|^2 df\n\n        (see https://en.wikipedia.org/wiki/Parseval%27s_theorem#Notation_used_in_physics)\n\n        Rewriting the right side of that equation in the discrete form becomes\n\n            ∫x(t)^2 dt ≈ ∑ |X[k]|^2 • ∆f\n        \n        where ∆f = fs/N = (1/∆t) / N = 1/T.\n        Limiting the right side to a range of discrete frequencies (k_0, k_1):\n\n            ∫x(t)^2 dt ≈ [∑; k=k_0 -> k≤k_1] |X[k]|^2 • ∆f\n\n        The VC curve calculation is the RMS over the time-domain. If T is the\n        duration of the time-domain signal, then:\n\n            √((1/T) ∫x(t)^2 dt)\n                ≈ √((1/T) [∑; k=k_0 -> k≤k_1] |X[k]|^2 • ∆f)\n                = ∆f • √([∑; k=k_0 -> k≤k_1] |X[k]|^2)\n\n        If the time-series data is acceleration, then the signal needs to first\n        be integrated into velocity. This can be done in the frequency domain\n        by replacing |X(2πf)|^2 with (1/2πf)^2 |X(2πf)|^2.\n        \"\"\"\n        f, a_psd = self._PSDData\n        f, v_psd = psd.differentiate(f, a_psd, n=-1)\n        f_oct, v_psd_oct = psd.to_octave(\n            f,\n            v_psd,\n            fstart=self._vc_init_freq,\n            octave_bins=self._vc_bins_per_octave,\n            mode=\"sum\",\n        )\n        v_vc = np.sqrt(f[1] * v_psd_oct)  # the PSD must already scale by ∆f?\n\n        return f_oct, v_vc\n\n    @cached_property\n    def _pressureData(self):\n        \"\"\"Populate the _pressure* fields, including splitting and extending data.\"\"\"\n        ch_struct = self._channels.get(\"pre\", None)\n        if ch_struct is None:\n            return np.empty(0, dtype=np.float)\n\n        units = ch_struct.units[1]\n        try:\n            conversionFactor = {  # core units = kPa\n                \"pa\": 1e-3,\n                \"psi\": 6.89476,\n                \"atm\": 101.325,\n            }[units.lower()]\n        except KeyError:\n            raise ValueError(f'unknown pressure channel units \"{units}\"')\n\n        self._preName = ch_struct.channel.name\n        self._preFs = ch_struct.fs\n        data = conversionFactor * ch_struct.eventarray.arrayValues(\n            subchannels=ch_struct.sch_ids,\n        )\n\n        return data\n\n    @cached_property\n    def _temperatureData(self):\n        \"\"\"Populate the _temperature* fields, including splitting and extending data.\"\"\"\n        ch_struct = self._channels.get(\"tmp\", None)\n        if ch_struct is None:\n            return np.empty(0, dtype=np.float)\n\n        units = ch_struct.units[1]\n        try:\n            conversionFactor, conversionOffset = {  # core units = degrees C\n                \"\\xb0c\": (1, 0),\n                \"\\xb0k\": (1, 273.15),\n                \"\\xb0f\": (5 / 9, -32 * (5 / 9)),\n            }[units.lower()]\n        except KeyError:\n            raise ValueError(f'unknown temperature channel units \"{units}\"')\n\n        self._tmpName = ch_struct.channel.name\n        self._tmpFs = ch_struct.fs\n        data = conversionOffset + conversionFactor * ch_struct.eventarray.arrayValues(\n            subchannels=ch_struct.sch_ids,\n        )\n\n        return data\n\n    @cached_property\n    def _gyroscopeData(self):\n        \"\"\"Populate the _gyro* fields, including splitting and extending data.\"\"\"\n        ch_struct = self._channels.get(\"gyr\", None)\n        if ch_struct is None:\n            return np.empty((3, 0), dtype=np.float)\n\n        self._gyroName = ch_struct.channel.name\n        self._gyroFs = ch_struct.fs\n\n        units = ch_struct.units[1]\n        if units.lower() == \"q\":\n            quat_array = ch_struct.eventarray.arrayValues(subchannels=ch_struct.sch_ids)\n            quat_raw = quat_array[\n                [3, 0, 1, 2]\n            ]  # reorders to <W, X, Y, Z> & strips out the \"Acc\" channel\n\n            data = (180 / np.pi) * quat.quat_to_angvel(quat_raw.T, 1 / self._gyroFs).T\n\n            def strip_invalid_prefix(data, prefix_len):\n                \"\"\"Search prefix for invalid data and remove it (if any).\"\"\"\n                data_mag = stats.L2_norm(data[: 4 * prefix_len], axis=0)\n                # the derivative method for `quat_to_angvel` uses the *average*\n                # of adjacent differences\n                # -> any rotation spikes will result in two adjacent,\n                # nearly-equal peaks\n                data_agg = 0.5 * (data_mag[:-1] + data_mag[1:])\n                argmax_prefix = np.argmax(data_agg[:prefix_len])\n\n                # Prefix data is considered \"anomalous\" if it is much larger\n                # than any surrounding data\n                if data_agg[argmax_prefix] > 2 * data_mag[prefix_len:].max():\n                    data = data[..., argmax_prefix + 2 :]\n\n                return data\n\n            data = strip_invalid_prefix(\n                data, prefix_len=max(4, int(np.ceil(0.25 * self._gyroFs)))\n            )\n        elif units.lower() in (\"dps\", \"deg/s\"):\n            data = ch_struct.eventarray.arrayValues(subchannels=ch_struct.sch_ids)\n        else:\n            raise ValueError(f'unknown gyroscope channel units \"{units}\"')\n\n        return data\n\n    def _processHumidity(self, channel):\n        \"\"\"Populate the _humidity* fields, including splitting and extending data.\"\"\"\n        pass\n\n    @cached_property\n    def _gpsPositionData(self):\n        ch_struct = self._channels.get(\"gps\", None)\n        if ch_struct is None:\n            return np.empty((2, 0), dtype=np.float)\n\n        units = ch_struct.units[1]\n        if units.lower() != \"degrees\":\n            raise ValueError(f'unknown GPS position channel units \"{units}\"')\n\n        data = ch_struct.eventarray.arrayValues(subchannels=ch_struct.sch_ids)\n\n        self._gpsName = ch_struct.channel.name\n        self._gpsFs = ch_struct.fs\n        # resampling destroys last values -> no resampling\n\n        return data\n\n    @cached_property\n    def _gpsSpeedData(self):\n        ch_struct = self._channels.get(\"spd\", None)\n        if ch_struct is None:\n            return np.empty(0)\n\n        units = ch_struct.units[1]\n        if units != \"m/s\":\n            raise ValueError(f'unknown GPS ground speed channel units \"{units}\"')\n\n        data = self.MPS_TO_KMPH * ch_struct.eventarray.arrayValues(\n            subchannels=ch_struct.sch_ids\n        )\n\n        self._gpsSpeedName = ch_struct.channel.name\n        self._gpsSpeedFs = ch_struct.fs\n\n        return data\n\n    # ==========================================================================\n    # Analyses\n    # ==========================================================================\n\n    @cached_property\n    @as_series(\n        \"acc\",\n        \"RMS Acceleration\",\n        edit_axis_names=lambda axis_names: axis_names + [\"Resultant\"],\n        default_axis_names=[\"X\", \"Y\", \"Z\", \"Resultant\"],\n    )\n    def accRMSFull(self):\n        \"\"\"Accelerometer Tri-axial RMS.\"\"\"\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            rms = stats.rms(\n                self._accelerationData, axis=1\n            )  # RuntimeWarning: Mean of empty slice.\n        return self.MPS2_TO_G * np.append(rms, stats.L2_norm(rms))\n\n    @cached_property\n    @as_series(\n        \"acc\",\n        \"RMS Velocity\",\n        edit_axis_names=lambda axis_names: axis_names + [\"Resultant\"],\n        default_axis_names=[\"X\", \"Y\", \"Z\", \"Resultant\"],\n    )\n    def velRMSFull(self):\n        \"\"\"Velocity Tri-axial RMS, after applying a 0.1Hz highpass filter.\"\"\"\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            rms = stats.rms(\n                self._velocityData, axis=1\n            )  # RuntimeWarning: Mean of empty slice.\n        return self.MPS_TO_MMPS * np.append(rms, stats.L2_norm(rms))\n\n    @cached_property\n    @as_series(\n        \"acc\",\n        \"RMS Displacement\",\n        edit_axis_names=lambda axis_names: axis_names + [\"Resultant\"],\n        default_axis_names=[\"X\", \"Y\", \"Z\", \"Resultant\"],\n    )\n    def disRMSFull(self):\n        \"\"\"Displacement Tri-axial RMS, after applying a 0.1Hz highpass filter.\"\"\"\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            rms = stats.rms(\n                self._displacementData, axis=1\n            )  # RuntimeWarning: Mean of empty slice.\n        return self.M_TO_MM * np.append(rms, stats.L2_norm(rms))\n\n    @cached_property\n    @as_series(\n        \"acc\",\n        \"Peak Absolute Acceleration\",\n        edit_axis_names=lambda axis_names: axis_names + [\"Resultant\"],\n        default_axis_names=[\"X\", \"Y\", \"Z\", \"Resultant\"],\n    )\n    def accPeakFull(self):\n        \"\"\"Peak instantaneous tri-axial acceleration\"\"\"\n        max_abs = stats.max_abs(self._accelerationData, axis=1)\n        max_abs_res = np.amax(\n            stats.L2_norm(self._accelerationData, axis=0),\n            initial=-np.inf,\n            axis=-1,\n        )\n        return self.MPS2_TO_G * np.nan_to_num(\n            np.append(max_abs, max_abs_res), nan=np.nan, posinf=np.inf, neginf=np.nan\n        )\n\n    @cached_property\n    @as_series(\n        \"acc\",\n        \"Peak Pseudo Velocity Shock Spectrum\",\n        edit_axis_names=lambda axis_names: axis_names + [\"Resultant\"],\n        default_axis_names=[\"X\", \"Y\", \"Z\", \"Resultant\"],\n    )\n    def pseudoVelPeakFull(self):\n        \"\"\"Peak Pseudo Velocity\"\"\"\n        if self._PVSSData[1].size == 0:\n            return np.full(self._PVSSData[1].shape[0] + 1, np.nan)\n\n        pv = self._PVSSData[1]\n        max_pv = np.amax(pv, initial=-np.inf, axis=1)\n        max_pv_res = np.amax(stats.L2_norm(pv, axis=0), initial=-np.inf, axis=-1)\n        return self.MPS_TO_MMPS * np.nan_to_num(\n            np.append(max_pv, max_pv_res), nan=np.nan, posinf=np.inf, neginf=np.nan\n        )\n\n    @cached_property\n    @as_series(\"gps\", \"GPS Position\", default_axis_names=[\"Latitude\", \"Longitude\"])\n    def gpsLocFull(self):\n        \"\"\"Average GPS location\"\"\"\n        data = self._gpsPositionData\n        # 0's occur when gps doesn't have a \"lock\" -> remove them\n        data = data[:, np.all(data != 0, axis=0)]\n        if data.size == 0:\n            return [np.nan, np.nan]\n\n        return data[..., -1]\n\n    @cached_property\n    @as_series(\"spd\", \"GPS Speed\", default_axis_names=[\"Ground\"])\n    def gpsSpeedFull(self):\n        \"\"\"Average GPS speed\"\"\"\n        data = self._gpsSpeedData\n        # 0's occur when gps doesn't have a \"lock\" -> remove them\n        data = data[data != 0]\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            return np.mean(data)  # RuntimeWarning: Mean of empty slice.\n\n    @cached_property\n    @as_series(\n        \"gyr\",\n        \"RMS Angular Velocity\",\n        edit_axis_names=lambda axis_names: [\"X\", \"Y\", \"Z\", \"Resultant\"],\n        default_axis_names=[\"X\", \"Y\", \"Z\", \"Resultant\"],\n    )\n    def gyroRMSFull(self):\n        \"\"\"Gyroscope RMS\"\"\"\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            rms = stats.rms(\n                self._gyroscopeData, axis=1\n            )  # RuntimeWarning: Mean of empty slice.\n        return np.append(rms, stats.L2_norm(rms))\n\n    @cached_property\n    @as_series(\"mic\", \"RMS Microphone\", default_axis_names=[\"\"])\n    def micRMSFull(self):\n        \"\"\"Microphone RMS\"\"\"\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            return stats.rms(\n                self._microphoneData\n            )  # RuntimeWarning: Mean of empty slice.\n\n    @cached_property\n    @as_series(\"tmp\", \"Average Temperature\", default_axis_names=[\"\"])\n    def tempFull(self):\n        \"\"\"Average Temperature\"\"\"\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            return self._temperatureData.mean()  # RuntimeWarning: Mean of empty slice.\n\n    @cached_property\n    @as_series(\"pre\", \"Average Pressure\", default_axis_names=[\"\"])\n    def pressFull(self):\n        \"\"\"Average Pressure\"\"\"\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            return self._pressureData.mean()  # RuntimeWarning: Mean of empty slice.\n", "meta": {"hexsha": "73ff8b53c6c9c955bd0497c5db524c71e61fab7f", "size": 23627, "ext": "py", "lang": "Python", "max_stars_repo_path": "endaq/batch/analyzer.py", "max_stars_repo_name": "MideTechnology/endaq-python-batch", "max_stars_repo_head_hexsha": "e578898091eb195b4107ebab9a0deb10f6358fdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "endaq/batch/analyzer.py", "max_issues_repo_name": "MideTechnology/endaq-python-batch", "max_issues_repo_head_hexsha": "e578898091eb195b4107ebab9a0deb10f6358fdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "endaq/batch/analyzer.py", "max_forks_repo_name": "MideTechnology/endaq-python-batch", "max_forks_repo_head_hexsha": "e578898091eb195b4107ebab9a0deb10f6358fdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0167682927, "max_line_length": 92, "alphanum_fraction": 0.5801413637, "include": true, "reason": "import numpy,import scipy", "num_tokens": 5692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.30735800417608683, "lm_q1q2_score": 0.18562327869031275}}
{"text": "import io as sysio\nimport time\n\nimport numba\nimport numpy as np\nfrom scipy.interpolate import interp1d\n\nfrom det3d.ops.nms.nms_gpu import rotate_iou_gpu_eval\nfrom det3d.core.bbox import box_np_ops\nfrom det3d.datasets.utils.eval import box3d_overlap_kernel\nfrom det3d.datasets.utils.eval import box3d_overlap\nfrom det3d.datasets.utils.eval import calculate_iou_partly\nfrom det3d.datasets.utils.eval import prepare_data\nfrom det3d.datasets.utils.eval import compute_statistics_jit\n\n\n@numba.jit\ndef get_thresholds(scores: np.ndarray, num_gt, num_sample_pts=41):\n    scores.sort()\n    scores = scores[::-1]\n    current_recall = 0\n    thresholds = []\n    for i, score in enumerate(scores):\n        l_recall = (i + 1) / num_gt\n        if i < (len(scores) - 1):\n            r_recall = (i + 2) / num_gt\n        else:\n            r_recall = l_recall\n        if ((r_recall - current_recall) < (current_recall - l_recall)) and (\n            i < (len(scores) - 1)\n        ):\n            continue\n        # recall = l_recall\n        thresholds.append(score)\n        current_recall += 1 / (num_sample_pts - 1.0)\n    # print(len(thresholds), len(scores), num_gt)\n    return thresholds\n\n\ndef clean_data(gt_anno, dt_anno, current_class, difficulty):\n    CLASS_NAMES = [\n        \"car\",\n        \"pedestrian\",\n        \"bicycle\",\n        \"truck\",\n        \"bus\",\n        \"trailer\",\n        \"construction_vehicle\",\n        \"motorcycle\",\n        \"barrier\",\n        \"traffic_cone\",\n        \"cyclist\",\n    ]\n    MIN_HEIGHT = [40, 25, 25]\n    MAX_OCCLUSION = [0, 1, 2]\n    MAX_TRUNCATION = [0.15, 0.3, 0.5]\n    dc_bboxes, ignored_gt, ignored_dt = [], [], []\n    current_cls_name = CLASS_NAMES[current_class].lower()\n    num_gt = len(gt_anno[\"name\"])\n    num_dt = len(dt_anno[\"name\"])\n    num_valid_gt = 0\n    for i in range(num_gt):\n        bbox = gt_anno[\"bbox\"][i]\n        gt_name = gt_anno[\"name\"][i].lower()\n        height = bbox[3] - bbox[1]\n        valid_class = -1\n        if gt_name == current_cls_name:\n            valid_class = 1\n        elif (\n            current_cls_name == \"Pedestrian\".lower()\n            and \"Person_sitting\".lower() == gt_name\n        ):\n            valid_class = 0\n        elif current_cls_name == \"Car\".lower() and \"Van\".lower() == gt_name:\n            valid_class = 0\n        else:\n            valid_class = -1\n        ignore = False\n        if (\n            (gt_anno[\"occluded\"][i] > MAX_OCCLUSION[difficulty])\n            or (gt_anno[\"truncated\"][i] > MAX_TRUNCATION[difficulty])\n            or (height <= MIN_HEIGHT[difficulty])\n        ):\n            ignore = True\n        if valid_class == 1 and not ignore:\n            ignored_gt.append(0)\n            num_valid_gt += 1\n        elif valid_class == 0 or (ignore and (valid_class == 1)):\n            ignored_gt.append(1)\n        else:\n            ignored_gt.append(-1)\n        # for i in range(num_gt):\n        if (gt_anno[\"name\"][i] == \"DontCare\") or (gt_anno[\"name\"][i] == \"ignore\"):\n            dc_bboxes.append(gt_anno[\"bbox\"][i])\n    for i in range(num_dt):\n        if dt_anno[\"name\"][i].lower() == current_cls_name:\n            valid_class = 1\n        else:\n            valid_class = -1\n        height = abs(dt_anno[\"bbox\"][i, 3] - dt_anno[\"bbox\"][i, 1])\n        if height < MIN_HEIGHT[difficulty]:\n            ignored_dt.append(1)\n        elif valid_class == 1:\n            ignored_dt.append(0)\n        else:\n            ignored_dt.append(-1)\n\n    return num_valid_gt, ignored_gt, ignored_dt, dc_bboxes\n\n\ndef get_split_parts(num, num_part):\n    same_part = num // num_part\n    remain_num = num % num_part\n    if remain_num == 0:\n        return [same_part] * num_part\n    else:\n        return [same_part] * num_part + [remain_num]\n\n\n@numba.jit(nopython=True)\ndef fused_compute_statistics(\n    overlaps,\n    pr,\n    gt_nums,\n    dt_nums,\n    dc_nums,\n    gt_datas,\n    dt_datas,\n    dontcares,\n    ignored_gts,\n    ignored_dets,\n    metric,\n    min_overlap,\n    thresholds,\n    compute_aos=False,\n):\n    gt_num = 0\n    dt_num = 0\n    dc_num = 0\n    for i in range(gt_nums.shape[0]):\n        for t, thresh in enumerate(thresholds):\n            overlap = overlaps[\n                dt_num : dt_num + dt_nums[i], gt_num : gt_num + gt_nums[i]\n            ]\n\n            gt_data = gt_datas[gt_num : gt_num + gt_nums[i]]\n            dt_data = dt_datas[dt_num : dt_num + dt_nums[i]]\n            ignored_gt = ignored_gts[gt_num : gt_num + gt_nums[i]]\n            ignored_det = ignored_dets[dt_num : dt_num + dt_nums[i]]\n            dontcare = dontcares[dc_num : dc_num + dc_nums[i]]\n            tp, fp, fn, similarity, _ = compute_statistics_jit(\n                overlap,\n                gt_data,\n                dt_data,\n                ignored_gt,\n                ignored_det,\n                dontcare,\n                metric,\n                min_overlap=min_overlap,\n                thresh=thresh,\n                compute_fp=True,\n                compute_aos=compute_aos,\n            )\n            pr[t, 0] += tp\n            pr[t, 1] += fp\n            pr[t, 2] += fn\n            if similarity != -1:\n                pr[t, 3] += similarity\n        gt_num += gt_nums[i]\n        dt_num += dt_nums[i]\n        dc_num += dc_nums[i]\n\n\ndef eval_class_v3(\n    gt_annos,\n    dt_annos,\n    current_classes,\n    difficultys,\n    metric,\n    min_overlaps,\n    compute_aos=False,\n    z_axis=1,\n    z_center=1.0,\n    num_parts=50,\n):\n    \"\"\"Kitti eval. support 2d/bev/3d/aos eval. support 0.5:0.05:0.95 coco AP.\n    Args:\n        gt_annos: dict, must from get_label_annos() in kitti_common.py\n        dt_annos: dict, must from get_label_annos() in kitti_common.py\n        current_class: int, 0: car, 1: pedestrian, 2: cyclist\n        difficulty: int. eval difficulty, 0: easy, 1: normal, 2: hard\n        metric: eval type. 0: bbox, 1: bev, 2: 3d\n        min_overlap: float, min overlap. official:\n            [[0.7, 0.5, 0.5], [0.7, 0.5, 0.5], [0.7, 0.5, 0.5]]\n            format: [metric, class]. choose one from matrix above.\n        num_parts: int. a parameter for fast calculate algorithm\n\n    Returns:\n        dict of recall, precision and aos\n    \"\"\"\n    assert len(gt_annos) == len(dt_annos)\n    num_examples = len(gt_annos)\n    split_parts = get_split_parts(num_examples, num_parts)\n    split_parts = [i for i in split_parts if i != 0]\n\n    rets = calculate_iou_partly(\n        dt_annos, gt_annos, metric, num_parts, z_axis=z_axis, z_center=z_center\n    )\n    overlaps, parted_overlaps, total_dt_num, total_gt_num = rets\n    N_SAMPLE_PTS = 41\n    num_minoverlap = len(min_overlaps)\n    num_class = len(current_classes)\n    num_difficulty = len(difficultys)\n    precision = np.zeros([num_class, num_difficulty, num_minoverlap, N_SAMPLE_PTS])\n    recall = np.zeros([num_class, num_difficulty, num_minoverlap, N_SAMPLE_PTS])\n    aos = np.zeros([num_class, num_difficulty, num_minoverlap, N_SAMPLE_PTS])\n    all_thresholds = np.zeros([num_class, num_difficulty, num_minoverlap, N_SAMPLE_PTS])\n    for m, current_class in enumerate(current_classes):\n        for l, difficulty in enumerate(difficultys):\n            rets = prepare_data(\n                gt_annos,\n                dt_annos,\n                current_class,\n                difficulty=difficulty,\n                clean_data=clean_data,\n            )\n            (\n                gt_datas_list,\n                dt_datas_list,\n                ignored_gts,\n                ignored_dets,\n                dontcares,\n                total_dc_num,\n                total_num_valid_gt,\n            ) = rets\n            for k, min_overlap in enumerate(min_overlaps[:, metric, m]):\n                thresholdss = []\n                for i in range(len(gt_annos)):\n                    rets = compute_statistics_jit(\n                        overlaps[i],\n                        gt_datas_list[i],\n                        dt_datas_list[i],\n                        ignored_gts[i],\n                        ignored_dets[i],\n                        dontcares[i],\n                        metric,\n                        min_overlap=min_overlap,\n                        thresh=0.0,\n                        compute_fp=False,\n                    )\n                    tp, fp, fn, similarity, thresholds = rets\n                    thresholdss += thresholds.tolist()\n                thresholdss = np.array(thresholdss)\n                thresholds = get_thresholds(thresholdss, total_num_valid_gt)\n                thresholds = np.array(thresholds)\n                # print(thresholds)\n                all_thresholds[m, l, k, : len(thresholds)] = thresholds\n                pr = np.zeros([len(thresholds), 4])\n                idx = 0\n                for j, num_part in enumerate(split_parts):\n                    gt_datas_part = np.concatenate(\n                        gt_datas_list[idx : idx + num_part], 0\n                    )\n                    dt_datas_part = np.concatenate(\n                        dt_datas_list[idx : idx + num_part], 0\n                    )\n                    dc_datas_part = np.concatenate(dontcares[idx : idx + num_part], 0)\n                    ignored_dets_part = np.concatenate(\n                        ignored_dets[idx : idx + num_part], 0\n                    )\n                    ignored_gts_part = np.concatenate(\n                        ignored_gts[idx : idx + num_part], 0\n                    )\n                    fused_compute_statistics(\n                        parted_overlaps[j],\n                        pr,\n                        total_gt_num[idx : idx + num_part],\n                        total_dt_num[idx : idx + num_part],\n                        total_dc_num[idx : idx + num_part],\n                        gt_datas_part,\n                        dt_datas_part,\n                        dc_datas_part,\n                        ignored_gts_part,\n                        ignored_dets_part,\n                        metric,\n                        min_overlap=min_overlap,\n                        thresholds=thresholds,\n                        compute_aos=compute_aos,\n                    )\n                    idx += num_part\n                for i in range(len(thresholds)):\n                    # recall[m, l, k, i] = pr[i, 0] / (pr[i, 0] + pr[i, 2])\n                    precision[m, l, k, i] = pr[i, 0] / (pr[i, 0] + pr[i, 1])\n                    if compute_aos:\n                        aos[m, l, k, i] = pr[i, 3] / (pr[i, 0] + pr[i, 1])\n                for i in range(len(thresholds)):\n                    precision[m, l, k, i] = np.max(precision[m, l, k, i:], axis=-1)\n                    if compute_aos:\n                        aos[m, l, k, i] = np.max(aos[m, l, k, i:], axis=-1)\n                # use interp to calculate recall\n                \"\"\"\n                current_recalls = np.linspace(0, 1, 41)\n                prec_unique, inds = np.unique(precision[m, l, k], return_index=True)\n                current_recalls = current_recalls[inds]\n                f = interp1d(prec_unique, current_recalls)\n                precs_for_recall = np.linspace(0, 1, 41)\n                max_prec = np.max(precision[m, l, k])\n                valid_prec = precs_for_recall < max_prec\n                num_valid_prec = valid_prec.sum()\n                recall[m, l, k, :num_valid_prec] = f(precs_for_recall[valid_prec])\n                \"\"\"\n    ret_dict = {\n        \"recall\": recall,  # [num_class, num_difficulty, num_minoverlap, N_SAMPLE_PTS]\n        \"precision\": precision,\n        \"orientation\": aos,\n        \"thresholds\": all_thresholds,\n        \"min_overlaps\": min_overlaps,\n    }\n    return ret_dict\n\n\ndef get_mAP2(prec):\n    sums = 0\n    interval = 4\n    for i in range(0, prec.shape[-1], interval):\n        sums = sums + prec[..., i]\n    return sums / int(prec.shape[-1] / interval) * 100\n\n\ndef get_mAP(prec):\n    sums = 0\n    for i in range(0, prec.shape[-1], 4):\n        sums = sums + prec[..., i]\n    return sums / 11 * 100\n\n#def get_mAP(prec):\n#    sums = 0\n#    for i in range(0, prec.shape[-1], 1):\n#        sums = sums + prec[..., i]\n#    return sums / 40 * 100\n\n\ndef do_eval_v2(\n    gt_annos,\n    dt_annos,\n    current_classes,\n    min_overlaps,\n    compute_aos=False,\n    difficultys=(0, 1, 2),\n    z_axis=1,\n    z_center=1.0,\n):\n    # min_overlaps: [num_minoverlap, metric, num_class]\n    ret = eval_class_v3(\n        gt_annos,\n        dt_annos,\n        current_classes,\n        difficultys,\n        0,\n        min_overlaps,\n        compute_aos,\n        z_axis=z_axis,\n        z_center=z_center,\n    )\n    # ret: [num_class, num_diff, num_minoverlap, num_sample_points]\n    mAP_bbox = get_mAP(ret[\"precision\"])\n    mAP_aos = None\n    if compute_aos:\n        mAP_aos = get_mAP(ret[\"orientation\"])\n    ret = eval_class_v3(\n        gt_annos,\n        dt_annos,\n        current_classes,\n        difficultys,\n        1,\n        min_overlaps,\n        z_axis=z_axis,\n        z_center=z_center,\n    )\n    mAP_bev = get_mAP(ret[\"precision\"])\n    ret = eval_class_v3(\n        gt_annos,\n        dt_annos,\n        current_classes,\n        difficultys,\n        2,\n        min_overlaps,\n        z_axis=z_axis,\n        z_center=z_center,\n    )\n    mAP_3d = get_mAP(ret[\"precision\"])\n    return mAP_bbox, mAP_bev, mAP_3d, mAP_aos\n\n\ndef do_eval_v3(\n    gt_annos,\n    dt_annos,\n    current_classes,\n    min_overlaps,\n    compute_aos=False,\n    difficultys=(0, 1, 2),\n    z_axis=1,\n    z_center=1.0,\n):\n    # min_overlaps: [num_minoverlap, metric, num_class]\n    types = [\"bbox\", \"bev\", \"3d\"]\n    metrics = {}\n    for i in range(3):\n        ret = eval_class_v3(\n            gt_annos,\n            dt_annos,\n            current_classes,\n            difficultys,\n            i,\n            min_overlaps,\n            compute_aos,\n            z_axis=z_axis,\n            z_center=z_center,\n        )\n        metrics[types[i]] = ret\n    return metrics\n\n\ndef do_coco_style_eval(\n    gt_annos,\n    dt_annos,\n    current_classes,\n    overlap_ranges,\n    compute_aos,\n    z_axis=1,\n    z_center=1.0,\n):\n    # overlap_ranges: [range, metric, num_class]\n    min_overlaps = np.zeros([10, *overlap_ranges.shape[1:]])\n    for i in range(overlap_ranges.shape[1]):\n        for j in range(overlap_ranges.shape[2]):\n            min_overlaps[:, i, j] = np.linspace(*overlap_ranges[:, i, j])\n    mAP_bbox, mAP_bev, mAP_3d, mAP_aos = do_eval_v2(\n        gt_annos,\n        dt_annos,\n        current_classes,\n        min_overlaps,\n        compute_aos,\n        z_axis=z_axis,\n        z_center=z_center,\n    )\n    # ret: [num_class, num_diff, num_minoverlap]\n    mAP_bbox = mAP_bbox.mean(-1)\n    mAP_bev = mAP_bev.mean(-1)\n    mAP_3d = mAP_3d.mean(-1)\n    if mAP_aos is not None:\n        mAP_aos = mAP_aos.mean(-1)\n    return mAP_bbox, mAP_bev, mAP_3d, mAP_aos\n\n\ndef print_str(value, *arg, sstream=None):\n    if sstream is None:\n        sstream = sysio.StringIO()\n    sstream.truncate(0)\n    sstream.seek(0)\n    print(value, *arg, file=sstream)\n    return sstream.getvalue()\n\n\ndef get_official_eval_result(\n    gt_annos, dt_annos, current_classes, difficultys=[0, 1, 2], z_axis=1, z_center=1.0\n):\n    \"\"\"\n        gt_annos and dt_annos must contains following keys:\n        [bbox, location, dimensions, rotation, score]\n    \"\"\"\n    overlap_mod = np.array(\n        [\n            [0.7, 0.5, 0.5, 0.7, 0.7, 0.7, 0.7, 0.5, 0.5, 0.5, 0.5],\n            [0.7, 0.5, 0.5, 0.7, 0.7, 0.7, 0.7, 0.5, 0.5, 0.5, 0.5],\n            [0.7, 0.5, 0.5, 0.7, 0.7, 0.7, 0.7, 0.5, 0.5, 0.5, 0.5],\n        ]\n    )\n    overlap_easy = np.array(\n        [\n            [0.7, 0.5, 0.5, 0.7, 0.7, 0.7, 0.7, 0.5, 0.25, 0.25, 0.5],\n            [0.5, 0.25, 0.25, 0.5, 0.5, 0.5, 0.5, 0.25, 0.25, 0.25, 0.25],\n            [0.5, 0.25, 0.25, 0.5, 0.5, 0.5, 0.5, 0.25, 0.25, 0.25, 0.25],\n        ]\n    )\n    min_overlaps = np.stack([overlap_mod, overlap_easy], axis=0)  # [2, 3, 5]\n    class_to_name = {\n        0: \"car\",\n        1: \"pedestrian\",\n        2: \"bicycle\",\n        3: \"truck\",\n        4: \"bus\",\n        5: \"trailer\",\n        6: \"construction_vehicle\",\n        7: \"motorcycle\",\n        8: \"barrier\",\n        9: \"traffic_cone\",\n        10: \"cyclist\",\n    }\n    name_to_class = {v: n for n, v in class_to_name.items()}\n    if not isinstance(current_classes, (list, tuple)):\n        current_classes = [current_classes]\n    current_classes_int = []\n    for curcls in current_classes:\n        if isinstance(curcls, str):\n            current_classes_int.append(name_to_class[curcls.lower()])\n        else:\n            current_classes_int.append(curcls)\n    current_classes = current_classes_int\n    min_overlaps = min_overlaps[:, :, current_classes]\n    result = \"\"\n    # check whether alpha is valid\n    compute_aos = False\n    for anno in dt_annos:\n        if anno[\"alpha\"].shape[0] != 0:\n            if anno[\"alpha\"][0] != -10:\n                compute_aos = True\n            break\n    # TODO dt2gt\n    metrics = do_eval_v3(\n        gt_annos,\n        dt_annos,\n        current_classes,\n        min_overlaps,\n        compute_aos,\n        difficultys,\n        z_axis=z_axis,\n        z_center=z_center,\n    )\n    detail = {}\n    for j, curcls in enumerate(current_classes):\n        # mAP threshold array: [num_minoverlap, metric, class]\n        # mAP result: [num_class, num_diff, num_minoverlap]\n        class_name = class_to_name[curcls]\n        detail[class_name] = {}\n        for i in range(min_overlaps.shape[0]):\n            mAPbbox = get_mAP(metrics[\"bbox\"][\"precision\"][j, :, i])\n            mAPbev = get_mAP(metrics[\"bev\"][\"precision\"][j, :, i])\n            mAP3d = get_mAP(metrics[\"3d\"][\"precision\"][j, :, i])\n            detail[class_name][f\"bbox@{min_overlaps[i, 0, j]:.2f}\"] = mAPbbox.tolist()\n            detail[class_name][f\"bev@{min_overlaps[i, 1, j]:.2f}\"] = mAPbev.tolist()\n            detail[class_name][f\"3d@{min_overlaps[i, 2, j]:.2f}\"] = mAP3d.tolist()\n\n            result += print_str(\n                (\n                    f\"{class_to_name[curcls]} \"\n                    \"AP(Average Precision)@{:.2f}, {:.2f}, {:.2f}:\".format(\n                        *min_overlaps[i, :, j]\n                    )\n                )\n            )\n            mAPbbox = \", \".join(f\"{v:.2f}\" for v in mAPbbox)\n            mAPbev = \", \".join(f\"{v:.2f}\" for v in mAPbev)\n            mAP3d = \", \".join(f\"{v:.2f}\" for v in mAP3d)\n            result += print_str(f\"bbox AP:{mAPbbox}\")\n            result += print_str(f\"bev  AP:{mAPbev}\")\n            result += print_str(f\"3d   AP:{mAP3d}\")\n            if compute_aos:\n                mAPaos = get_mAP(metrics[\"bbox\"][\"orientation\"][j, :, i])\n                detail[class_name][f\"aos\"] = mAPaos.tolist()\n                mAPaos = \", \".join(f\"{v:.2f}\" for v in mAPaos)\n                result += print_str(f\"aos  AP:{mAPaos}\")\n    return {\n        \"result\": result,\n        \"detail\": detail,\n    }\n\n\ndef get_coco_eval_result(gt_annos, dt_annos, current_classes, z_axis=1, z_center=1.0):\n    class_to_name = {\n        0: \"car\",\n        1: \"pedestrian\",\n        2: \"bicycle\",\n        3: \"truck\",\n        4: \"bus\",\n        5: \"trailer\",\n        6: \"construction_vehicle\",\n        7: \"motorcycle\",\n        8: \"barrier\",\n        9: \"traffic_cone\",\n        10: \"cyclist\",\n    }\n    class_to_range = {\n        0: [0.5, 0.95, 10],\n        1: [0.25, 0.7, 10],\n        2: [0.25, 0.7, 10],\n        3: [0.5, 0.95, 10],\n        4: [0.5, 0.95, 10],\n        5: [0.5, 0.95, 10],\n        6: [0.5, 0.95, 10],\n        7: [0.25, 0.7, 10],\n        8: [0.25, 0.7, 10],\n        9: [0.25, 0.7, 10],\n        10: [0.25, 0.7, 10],\n    }\n    # class_to_range = {\n    #     0: [0.5, 0.95, 10],\n    #     1: [0.25, 0.7, 10],\n    #     2: [0.25, 0.7, 10],\n    #     3: [0.5, 0.95, 10],\n    #     4: [0.25, 0.7, 10],\n    #     5: [0.5, 0.95, 10],\n    #     6: [0.5, 0.95, 10],\n    #     7: [0.5, 0.95, 10],\n    # }\n\n    name_to_class = {v: n for n, v in class_to_name.items()}\n    if not isinstance(current_classes, (list, tuple)):\n        current_classes = [current_classes]\n    current_classes_int = []\n    for curcls in current_classes:\n        if isinstance(curcls, str):\n            current_classes_int.append(name_to_class[curcls.lower()])\n        else:\n            current_classes_int.append(curcls)\n    current_classes = current_classes_int\n    overlap_ranges = np.zeros([3, 3, len(current_classes)])\n    for i, curcls in enumerate(current_classes):\n        overlap_ranges[:, :, i] = np.array(class_to_range[curcls])[:, np.newaxis]\n    result = \"\"\n    # check whether alpha is valid\n    compute_aos = False\n    for anno in dt_annos:\n        if anno[\"alpha\"].shape[0] != 0:\n            if anno[\"alpha\"][0] != -10:\n                compute_aos = True\n            break\n    mAPbbox, mAPbev, mAP3d, mAPaos = do_coco_style_eval(\n        gt_annos,\n        dt_annos,\n        current_classes,\n        overlap_ranges,\n        compute_aos,\n        z_axis=z_axis,\n        z_center=z_center,\n    )\n    detail = {}\n    for j, curcls in enumerate(current_classes):\n        class_name = class_to_name[curcls]\n        detail[class_name] = {}\n        # mAP threshold array: [num_minoverlap, metric, class]\n        # mAP result: [num_class, num_diff, num_minoverlap]\n        o_range = np.array(class_to_range[curcls])[[0, 2, 1]]\n        o_range[1] = (o_range[2] - o_range[0]) / (o_range[1] - 1)\n        result += print_str(\n            (\n                f\"{class_to_name[curcls]} \"\n                \"coco AP@{:.2f}:{:.2f}:{:.2f}:\".format(*o_range)\n            )\n        )\n        result += print_str(\n            (\n                f\"bbox AP:{mAPbbox[j, 0]:.2f}, \"\n                f\"{mAPbbox[j, 1]:.2f}, \"\n                f\"{mAPbbox[j, 2]:.2f}\"\n            )\n        )\n        result += print_str(\n            (\n                f\"bev  AP:{mAPbev[j, 0]:.2f}, \"\n                f\"{mAPbev[j, 1]:.2f}, \"\n                f\"{mAPbev[j, 2]:.2f}\"\n            )\n        )\n        result += print_str(\n            (f\"3d   AP:{mAP3d[j, 0]:.2f}, \" f\"{mAP3d[j, 1]:.2f}, \" f\"{mAP3d[j, 2]:.2f}\")\n        )\n        detail[class_name][f\"bbox\"] = mAPbbox[j].tolist()\n        detail[class_name][f\"bev\"] = mAPbev[j].tolist()\n        detail[class_name][f\"3d\"] = mAP3d[j].tolist()\n\n        if compute_aos:\n            detail[class_name][f\"aos\"] = mAPaos[j].tolist()\n            result += print_str(\n                (\n                    f\"aos  AP:{mAPaos[j, 0]:.2f}, \"\n                    f\"{mAPaos[j, 1]:.2f}, \"\n                    f\"{mAPaos[j, 2]:.2f}\"\n                )\n            )\n    return {\n        \"result\": result,\n        \"detail\": detail,\n    }\n", "meta": {"hexsha": "8cd59d87d269ea0cf74c6d0d04152ccd3347e870", "size": 22381, "ext": "py", "lang": "Python", "max_stars_repo_path": "det3d/datasets/kitti/eval.py", "max_stars_repo_name": "reinforcementdriving/CIA-SSD", "max_stars_repo_head_hexsha": "f7b4a9ed4a2b852845303efc6c972125438817a6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 382, "max_stars_repo_stars_event_min_datetime": "2020-12-05T06:46:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T17:40:58.000Z", "max_issues_repo_path": "det3d/datasets/kitti/eval.py", "max_issues_repo_name": "reinforcementdriving/CIA-SSD", "max_issues_repo_head_hexsha": "f7b4a9ed4a2b852845303efc6c972125438817a6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2020-12-08T07:50:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T03:54:43.000Z", "max_forks_repo_path": "det3d/datasets/kitti/eval.py", "max_forks_repo_name": "reinforcementdriving/CIA-SSD", "max_forks_repo_head_hexsha": "f7b4a9ed4a2b852845303efc6c972125438817a6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 57, "max_forks_repo_forks_event_min_datetime": "2020-12-10T02:19:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T09:49:38.000Z", "avg_line_length": 32.6729927007, "max_line_length": 88, "alphanum_fraction": 0.5209776149, "include": true, "reason": "import numpy,from scipy,import numba", "num_tokens": 6390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847395, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.18551996798910303}}
{"text": "\"\"\"\nComputation of the demagnetising field using the Fredkin-Koehler\ntechnique and the infamous magpar method.\n\nRationale: The previous implementation in FemBemFKSolver (child class\nof FemBemDeMagSolver) was kind of a mess. This does the same thing in the same\ntime with less code. Should be more conducive to further optimisation or as\na template for other techniques like the GCR.\n\n\"\"\"\nimport numpy as np\nimport dolfin as df\nimport logging\nfrom aeon import timer, Timer\nfrom finmag.util.consts import mu0\nfrom finmag.native.llg import compute_bem_fk\nfrom finmag.util.meshes import nodal_volume\nfrom finmag.util import helpers, configuration\nfrom finmag.field import Field\nfrom fk_demag_pbc import BMatrixPBC\n\n\nlogger = logging.getLogger('finmag')\nfk_timer = Timer()\n\n\nclass FKDemag(object):\n\n    \"\"\"\n    Computation of the demagnetising field using the Fredkin-Koehler hybrid\n    FEM/BEM technique.\n\n    Fredkin, D.R. and Koehler, T.R., \"`Hybrid method for computing\n    demagnetizing fields`_\", IEEE Transactions on Magnetics, vol.26, no.2,\n    pp.415-417, Mar 1990.\n\n    .. _Hybrid method for computing demagnetizing fields:\n       http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=106342\n\n    \"\"\"\n\n    def __init__(self, name='Demag', thin_film=False, macrogeometry=None,\n                 solver_type=None, parameters=None):\n        \"\"\"\n        Create a new FKDemag instance.\n\n        The attribute `parameters` is a dict that contains the settings for the\n        solvers for the Neumann (potential phi_1) and Laplace (potential phi_2)\n        problems.\n\n        Setting the method used by the solvers:\n        Change the entries `phi_1_solver` and `phi_2_solver` to a value from\n        `df.list_krylov_solver_methods()`. Default is dolfin's default.\n\n        Setting the preconditioners:\n        Change the entries `phi_1_preconditioner` and `phi_2_preconditioner` to\n        a value from `df.list_krylov_solver_preconditioners()`. Default is\n        dolfin's default. There is a set of parameters optimised for thin films\n        (cg/ilu followed by default without preconditioner) that can be used by\n        passing in the argument 'thin_film` set to True.\n\n        Setting the tolerances:\n        Change the existing entries inside `phi_1` and `phi_2` which are\n        themselves dicts. You can add new entries to these dicts as well.\n        Everything which is understood by `df.KrylovSolver` is valid.\n\n        Allowed values for `solver_type` are 'Krylov','LU' and `None` (the\n        latter uses the value set in the .finmagrc file, defaulting to 'Krylov'\n        as no value is provided there).\n\n        \"\"\"\n        self.name = name\n        self.in_jacobian = False\n        default_parameters = {\n            'absolute_tolerance': 1e-6,\n            'relative_tolerance': 1e-6,\n            'maximum_iterations': int(1e4)\n        }\n        self.parameters = {\n            'phi_1_solver': 'default',\n            'phi_1_preconditioner': 'default',\n            'phi_1': default_parameters,\n            'phi_2_solver': 'default',\n            'phi_2_preconditioner': 'default',\n            'phi_2': default_parameters.copy()\n        }\n        if parameters is not None:\n            for (k, v) in parameters.items():\n                logger.debug(\n                    \"Setting demag solver parameter {}='{}'\".format(k, v))\n                if k in ['phi_1', 'phi_2']:\n                    # Since self.parameters['phi_1'] is a dictionary itself,\n                    # only update the keys that are given (and similarly for\n                    # 'phi_2').\n                    for (k2, v2) in v.items():\n                        self.parameters[k][k2] = v2\n                else:\n                    self.parameters[k] = v\n            logger.debug(\"Demag parameters now: {}\".format(self.parameters))\n\n        self.solver_type = solver_type\n\n        if thin_film:\n            self.parameters[\"phi_1_solver\"] = \"cg\"\n            self.parameters[\"phi_1_preconditioner\"] = \"ilu\"\n            self.parameters[\"phi_2_preconditioner\"] = \"none\"\n\n        self.macrogeometry = macrogeometry\n\n    @timer.method\n    def setup(self, m, Ms, unit_length=1):\n        \"\"\"\n        Setup the FKDemag instance. Usually called automatically by the\n        Simulation object.\n\n        *Arguments*\n\n        m: finmag.Field\n\n            The unit magnetisation on a finite element space.\n\n        Ms: float\n\n            The saturation magnetisation in A/m.\n\n        unit_length: float\n\n            The length (in m) represented by one unit on the mesh. Default 1.\n\n        \"\"\"\n        assert isinstance(m, Field)\n        assert isinstance(Ms, Field)\n\n        self.m = m\n        self.Ms = Ms\n        self.unit_length = unit_length\n        self.S1 = df.FunctionSpace(self.m.mesh(), \"Lagrange\", 1)\n\n        self._test1 = df.TestFunction(self.S1)\n        self._trial1 = df.TrialFunction(self.S1)\n        self._test3 = df.TestFunction(self.m.functionspace)\n        self._trial3 = df.TrialFunction(self.m.functionspace)\n\n        # for computation of energy\n        self._nodal_volumes = nodal_volume(self.S1, unit_length)\n        self._H_func = df.Function(m.functionspace)  # we will copy field into\n        # this when we need the\n        # energy\n        self._E_integrand = -0.5 * mu0 * \\\n            df.dot(self._H_func, self.m.f * self.Ms.f)\n        self._E = self._E_integrand * df.dx\n        self._nodal_E = df.dot(self._E_integrand, self._test1) * df.dx\n        self._nodal_E_func = df.Function(self.S1)\n\n        # for computation of field and scalar magnetic potential\n        self._poisson_matrix = self._poisson_matrix()\n        self._laplace_zeros = df.Function(self.S1).vector()\n\n        # determine the solver type to be used (Krylov or LU); if the kwarg\n        # 'solver_type' is not provided, try to read the setting from the\n        # .finmagrc file; use 'Krylov' if this fails.\n        solver_type = self.solver_type\n        if solver_type is None:\n            solver_type = configuration.get_config_option(\n                'demag', 'solver_type', 'Krylov')\n        if solver_type == 'None':  # if the user set 'solver_type = None' in\n                                   # the .finmagrc file, solver_type will be a\n                                   # string so we need to catch this here.\n            solver_type = 'Krylov'\n        logger.debug(\"Using {} solver for demag.\".format(solver_type))\n\n        if solver_type == 'Krylov':\n            self._poisson_solver = df.KrylovSolver(self._poisson_matrix.copy(),\n                                                   self.parameters['phi_1_solver'], self.parameters['phi_1_preconditioner'])\n            self._poisson_solver.parameters.update(self.parameters['phi_1'])\n            self._laplace_solver = df.KrylovSolver(\n                self.parameters['phi_2_solver'], self.parameters['phi_2_preconditioner'])\n            self._laplace_solver.parameters.update(self.parameters['phi_2'])\n            # We're setting 'same_nonzero_pattern=True' to enforce the\n            # same matrix sparsity pattern across different demag solves,\n            # which should speed up things.\n            #self._laplace_solver.parameters[\"preconditioner\"][\n            #    \"structure\"] = \"same_nonzero_pattern\"\n        elif solver_type == 'LU':\n            self._poisson_solver = df.LUSolver(self._poisson_matrix.copy())\n            self._laplace_solver = df.LUSolver()\n            self._poisson_solver.parameters[\"reuse_factorization\"] = True\n            self._laplace_solver.parameters[\"reuse_factorization\"] = True\n        else:\n            raise ValueError(\"Argument 'solver_type' must be either 'Krylov' or 'LU'. \"\n                             \"Got: '{}'\".format(solver_type))\n\n        with fk_timer('compute BEM'):\n            if not hasattr(self, \"_bem\"):\n                if self.macrogeometry is not None:\n                    Ts = self.macrogeometry.compute_Ts(self.m.mesh())\n                    pbc = BMatrixPBC(self.m.mesh(), Ts)\n                    self._b2g_map = np.array(pbc.b2g_map, dtype=np.int)\n                    self._bem = pbc.bm\n                else:\n                    self._bem, self._b2g_map = compute_bem_fk(\n                        df.BoundaryMesh(self.m.mesh(), 'exterior', False))\n        logger.debug(\"Boundary element matrix uses {:.2f} MB of memory.\".format(\n            self._bem.nbytes / 1024. ** 2))\n        # solution of inhomogeneous Neumann problem\n        self._phi_1 = df.Function(self.S1)\n        # solution of Laplace equation inside domain\n        self._phi_2 = df.Function(self.S1)\n        self._phi = df.Function(self.S1)  # magnetic potential phi_1 + phi_2\n\n        # To be applied to the vector field m as first step of computation of\n        # _phi_1.  This gives us div(M), which is equal to Laplace(_phi_1),\n        # equation which is then solved using _poisson_solver.\n        self._Ms_times_divergence = df.assemble(\n            self.Ms.f * df.inner(self._trial3, df.grad(self._test1)) * df.dx)\n\n        # we move the boundary condition here to avoid create a instance each\n        # time when compute the magnetic potential\n        self.boundary_condition = df.DirichletBC(\n            self.S1, self._phi_2, df.DomainBoundary())\n        self.boundary_condition.apply(self._poisson_matrix)\n\n        self._setup_gradient_computation()\n\n    @timer.method\n    def precomputed_bem(self, bem, b2g_map):\n        \"\"\"\n        If the BEM and a boundary to global vertices map are known, they can be\n        passed to the FKDemag object with this method so it will skip\n        re-computing them.\n\n        \"\"\"\n        self._bem, self._b2g_map = bem, b2g_map\n\n    @timer.method\n    def compute_potential(self):\n        \"\"\"\n        Compute the magnetic potential.\n\n        *Returns*\n            df.Function\n                The magnetic potential.\n\n        \"\"\"\n        self._compute_magnetic_potential()\n        return self._phi\n\n    @timer.method\n    def compute_field(self):\n        \"\"\"\n        Compute the demagnetising field.\n\n        *Returns*\n            numpy.ndarray\n                The demagnetising field.\n\n        \"\"\"\n        self._compute_magnetic_potential()\n        return self._compute_gradient()\n\n    def average_field(self):\n        \"\"\"\n        Compute the average demag field.\n        \"\"\"\n        return helpers.average_field(self.compute_field())\n\n    @timer.method\n    def compute_energy(self):\n        \"\"\"\n        Compute the total energy of the field.\n\n        .. math::\n\n            E_\\\\mathrm{d} = -\\\\frac12 \\\\mu_0 \\\\int_\\\\Omega\n            H_\\\\mathrm{d} \\\\cdot \\\\vec M \\\\mathrm{d}x\n\n        *Returns*\n            Float\n                The energy of the demagnetising field.\n\n        \"\"\"\n        self._H_func.vector()[:] = self.compute_field()\n        return df.assemble(self._E) * self.unit_length ** self.m.mesh_dim()\n\n    @timer.method\n    def energy_density(self):\n        \"\"\"\n        Compute the energy density in the field.\n\n        .. math::\n            \\\\rho = \\\\frac{E_{\\\\mathrm{d}, i}}{V_i},\n\n        where V_i is the volume associated with the node i.\n\n        *Returns*\n            numpy.ndarray\n                The energy density of the demagnetising field.\n\n        \"\"\"\n        self._H_func.vector()[:] = self.compute_field()\n        nodal_E = df.assemble(self._nodal_E).array() * \\\n            self.unit_length ** self.m.mesh_dim()\n        return nodal_E / self._nodal_volumes\n\n    @timer.method\n    def energy_density_function(self):\n        \"\"\"\n        Returns the energy density in the field as a dolfin function to allow probing.\n\n        *Returns*\n            dolfin.Function\n                The energy density of the demagnetising field.\n\n        \"\"\"\n        self._nodal_E_func.vector()[:] = self.energy_density()\n        return self._nodal_E_func\n\n    @fk_timer.method\n    def _poisson_matrix(self):\n        A = df.dot(df.grad(self._trial1), df.grad(self._test1)) * df.dx\n        return df.assemble(A)  # stiffness matrix for Poisson equation\n\n    def _compute_magnetic_potential(self):\n        # compute _phi_1 on the whole domain\n        g_1 = self._Ms_times_divergence * self.m.f.vector()\n        with fk_timer(\"first linear solve\"):\n            self._poisson_solver.solve(self._phi_1.vector(), g_1)\n\n        # compute _phi_2 on the boundary using the Dirichlet boundary\n        # conditions we get from BEM * _phi_1 on the boundary.\n        with fk_timer(\"using boundary conditions\"):\n            phi_1 = self._phi_1.vector()[self._b2g_map]\n            self._phi_2.vector()[self._b2g_map[:]] = np.dot(\n                self._bem, phi_1)\n            #boundary_condition = df.DirichletBC(self.S1, self._phi_2, df.DomainBoundary())\n            #A = self._poisson_matrix.copy()\n            #b = self._laplace_zeros\n            #boundary_condition.apply(A, b)\n            A = self._poisson_matrix\n            b = self._laplace_zeros\n            self.boundary_condition.set_value(self._phi_2)\n            self.boundary_condition.apply(A, b)\n\n        # compute _phi_2 on the whole domain\n        with fk_timer(\"second linear solve\"):\n            self._laplace_solver.solve(A, self._phi_2.vector(), b)\n\n        # add _phi_1 and _phi_2 to obtain magnetic potential\n        self._phi.vector()[:] = self._phi_1.vector() + self._phi_2.vector()\n\n    @fk_timer.method\n    def _setup_gradient_computation(self):\n        \"\"\"\n        Prepare the discretised gradient to use in :py:meth:`FKDemag._compute_gradient`.\n\n        We don't need the gradient field as a continuous field, we are only\n        interested in the values at specific points. It is thus a waste of\n        computational effort to use a projection of the gradient field, since\n        it performs the fairly large operation of assembling a matrix and\n        solving a linear system of equations.\n\n        \"\"\"\n        A = df.inner(self._test3, - df.grad(self._trial1)) * df.dx\n        # This can be applied to scalar functions.\n        self._gradient = df.assemble(A)\n\n        # The `A` above is in fact not quite the gradient, since we integrated\n        # over the volume as well. We will divide by the volume later, after\n        # the multiplication of the scalar magnetic potential. Since the two\n        # operations are symmetric (multiplying by volume, dividing by volume)\n        # we don't have to care for the units, i.e. unit_length.\n        b = df.dot(self._test3, df.Constant((1, 1, 1))) * df.dx\n        self._nodal_volumes_S3_no_units = df.assemble(b).array()\n\n    @fk_timer.method\n    def _compute_gradient(self):\n        \"\"\"\n        Get the demagnetising field from the magnetic scalar potential.\n\n        .. math::\n\n            \\\\vec{H}_{\\\\mathrm{d}} = - \\\\nabla \\\\phi (\\\\vec{r})\n\n        Using dolfin, we would translate this to\n\n        .. sourcecode::\n\n            H_d = df.project(- df.grad(self._phi), self.m.functionspace)\n\n        but the method used here is computationally less expensive.\n\n        \"\"\"\n        H = self._gradient * self._phi.vector()\n        return H.array() / self._nodal_volumes_S3_no_units\n", "meta": {"hexsha": "16853ecfee5850a3d8ad78aa2f8c41fc4fd2df7d", "size": 15001, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/finmag/energies/demag/fk_demag.py", "max_stars_repo_name": "davidcortesortuno/finmag", "max_stars_repo_head_hexsha": "9ac0268d2c0e45faf1284cee52a73525aa589e2b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2018-03-24T07:43:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:42:27.000Z", "max_issues_repo_path": "src/finmag/energies/demag/fk_demag.py", "max_issues_repo_name": "davidcortesortuno/finmag", "max_issues_repo_head_hexsha": "9ac0268d2c0e45faf1284cee52a73525aa589e2b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2018-03-26T15:08:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-10T16:11:14.000Z", "max_forks_repo_path": "src/finmag/energies/demag/fk_demag.py", "max_forks_repo_name": "davidcortesortuno/finmag", "max_forks_repo_head_hexsha": "9ac0268d2c0e45faf1284cee52a73525aa589e2b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-04-09T11:50:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T09:23:25.000Z", "avg_line_length": 37.9772151899, "max_line_length": 124, "alphanum_fraction": 0.6158256116, "include": true, "reason": "import numpy", "num_tokens": 3568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.1855199630625036}}
{"text": "\"\"\"\nClasses and methods needed to do hypersurface interpolation over arbitrary parameters.\n\"\"\"\n\n__all__ = ['HypersurfaceInterpolator', 'run_interpolated_fit', 'prepare_interpolated_fit',\n            'assemble_interpolated_fits', 'load_interpolated_hypersurfaces', 'pipeline_cfg_from_states',\n            'serialize_pipeline_cfg', 'get_incomplete_job_idx']\n\n__author__ = 'T. Stuttard, A. Trettin'\n\n__license__ = '''Copyright (c) 2014-2017, The IceCube Collaboration\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n   http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.'''\n\n\nimport os\nimport collections\nimport copy\n\nimport numpy as np\nfrom scipy import interpolate\nfrom .hypersurface import Hypersurface, HypersurfaceParam\nfrom pisa import FTYPE, ureg\nfrom pisa.utils import matrix\nfrom pisa.utils.jsons import from_json, to_json\nfrom pisa.utils.fileio import from_file, to_file\nfrom pisa.core.pipeline import Pipeline\nfrom pisa.core.binning import MultiDimBinning, is_binning\nfrom pisa.core.map import Map\nfrom pisa.core.param import Param, ParamSet\nfrom pisa.utils.resources import find_resource\nfrom pisa.utils.fileio import mkdir\nfrom pisa.utils.log import logging, set_verbosity\nfrom pisa.utils.comparisons import ALLCLOSE_KW\nfrom uncertainties import ufloat, correlated_values\nfrom uncertainties import unumpy as unp\n\nclass HypersurfaceInterpolator(object):\n    \"\"\"Factory for interpolated hypersurfaces.\n\n    After being initialized with a set of hypersurface fits produced at different\n    parameters, it uses interpolation to produce a Hypersurface object\n    at a given point in parameter space using scipy's `RegularGridInterpolator`.\n\n    The interpolation is piecewise-linear between points. All points must lie on a\n    rectilinear ND grid.\n\n    Parameters\n    ----------\n    interpolation_param_spec : dict\n        Specification of interpolation parameter grid of the form::\n            interpolation_param_spec = {\n                'param1': {\"values\": [val1_1, val1_2, ...], \"scales_log\": True/False}\n                'param2': {\"values\": [val2_1, val2_2, ...], \"scales_log\": True/False}\n                ...\n                'paramN': {\"values\": [valN_1, valN_2, ...], \"scales_log\": True/False}\n            }\n        where values are given as :obj:`Quantity`.\n    hs_fits : list of dict\n        list of dicts with hypersurfacesthat were fit at the points of the parameter mesh\n        defined by interpolation_param_spec\n    ignore_nan : bool\n        Ignore empty bins in hypersurfaces. The intercept in those bins is set to 1 and\n        all slopes are set to 0.\n\n    Notes\n    -----\n    Be sure to give a support that covers the entire relevant parameter range and a\n    good distance beyond! To prevent minimization failure from NaNs, extrapolation\n    is used if hypersurfaces outside the support are requested but needless to say\n    these numbers are unreliable.\n\n    See Also\n    --------\n    scipy.interpolate.RegularGridInterpolator :\n        class used for interpolation\n    \"\"\"\n\n    def __init__(self, interpolation_param_spec, hs_fits, ignore_nan=True):\n        self.ndim = len(interpolation_param_spec.keys())\n        # key ordering is important to guarantee that dimensions stay consistent\n        msg = \"interpolation params must be specified as a dict with ordered keys\"\n        assert isinstance(interpolation_param_spec, collections.OrderedDict), msg\n        for k, v in interpolation_param_spec.items():\n            assert set(v.keys()) == {\"values\", \"scales_log\"}\n            assert isinstance(v[\"values\"], collections.Sequence)\n        self.interp_param_spec = interpolation_param_spec\n        reference_hs = hs_fits[0][\"hs_fit\"]\n        # we are going to produce the hypersurface from a state that is the same\n        # as the reference, only the coefficients and covariance matrices are\n        # injected from the interpolation.\n        self._reference_state = copy.deepcopy(reference_hs.serializable_state)\n        # for cleanliness we wipe numbers from the original state\n        self._reference_state[\"intercept_sigma\"] = np.nan\n        self._reference_state[\"fit_maps_norm\"] = None\n        self._reference_state[\"fit_maps_raw\"] = None\n        self._reference_state[\"fit_chi2\"] = np.nan\n        for param in self._reference_state['params'].values():\n            param['fit_coeffts_sigma'] = np.full_like(\n                param['fit_coeffts_sigma'], np.nan)\n        # Instead of holding numbers, these coefficients and covariance matrices are\n        # interpolator objects the produce them at the requested point.\n        # The shape of fit_coeffts is [binning ..., fit coeffts]\n        self.coeff_shape = reference_hs.fit_coeffts.shape\n        self.coefficients = None\n        # The shape of fit_cov_mat is [binning ..., fit coeffts, fit coeffts]\n        self.covars_shape = reference_hs.fit_cov_mat.shape\n        self.covars = None\n\n        # We now need to massage the fit coefficients into the correct shape\n        # for interpolation.\n        # The dimensions of the interpolation parameters come first, the dimensions\n        # of the hypersurface coefficients comes last.\n        self.interp_shape = tuple(len(v[\"values\"]) for v in self.interp_param_spec.values())\n        # dimension is [interp_shape, binning..., fit coeffts]\n        self._coeff_z = np.zeros(self.interp_shape + self.coeff_shape)\n        # dimension is [interp_shape, binning..., fit coeffts, fit coeffts]\n        self._covar_z = np.zeros(self.interp_shape + self.covars_shape)\n        # Here we use the same indexing as below in `fit_hypersurfaces`\n        for i, idx in enumerate(np.ndindex(self.interp_shape)):\n            # As an additional safety measure, we check that the parameters are what\n            # we expect to find at this index.\n            expected_params = dict(\n                (n, self.interp_param_spec[n][\"values\"][idx[j]])\n                for j, n in enumerate(self.interp_param_spec.keys())\n            )\n            param_values = hs_fits[i][\"param_values\"]\n            msg = (\"The stored values where hypersurfaces were fit do not match those\"\n                   \"in the interpolation grid.\")\n            assert np.all([expected_params[n].m == param_values[n].m\n                           for n in self.interp_param_spec.keys()]), msg\n            self._coeff_z[idx] = hs_fits[i][\"hs_fit\"].fit_coeffts\n            self._covar_z[idx] = hs_fits[i][\"hs_fit\"].fit_cov_mat\n\n        grid_coords = list(\n            np.array([val.m for val in val_list[\"values\"]])\n            for val_list in self.interp_param_spec.values()\n        )\n        self.param_bounds = [(np.min(grid_vals), np.max(grid_vals))\n                             for grid_vals in grid_coords]\n        # If a parameter scales as log, we give the log of the parameter to the\n        # interpolator. We must not forget to do this again when we call the\n        # interpolator later!\n        for i, param_name in enumerate(self.interpolation_param_names):\n            if self.interp_param_spec[param_name][\"scales_log\"]:\n                grid_coords[i] = np.log10(grid_coords[i])\n        self.coefficients = interpolate.RegularGridInterpolator(\n            grid_coords,\n            self._coeff_z,\n            # We disable extrapolation, but clip parameter values inside the valid\n            # range.\n            bounds_error=True, fill_value=None\n        )\n        self.covars = interpolate.RegularGridInterpolator(\n            grid_coords,\n            self._covar_z,\n            bounds_error=True, fill_value=None\n        )\n        # In order not to spam warnings, we only want to warn about non positive\n        # semi definite covariance matrices once for each bin. We store the bin\n        # indeces for which the warning has already been issued.\n        self.covar_bins_warning_issued = []\n        self.ignore_nan = ignore_nan\n\n    @property\n    def interpolation_param_names(self):\n        return list(self.interp_param_spec.keys())\n\n    @property\n    def param_names(self):\n        return list(self._reference_state[\"params\"].keys())\n\n    @property\n    def binning(self):\n        binning = self._reference_state[\"binning\"]\n        if not is_binning(binning) :\n            binning = MultiDimBinning(**binning)\n        return binning\n\n    @property\n    def num_interp_params(self):\n        return len(self.interp_param_spec.keys())\n\n    def get_hypersurface(self, **param_kw):\n        \"\"\"\n        Get a Hypersurface object with interpolated coefficients.\n\n        Parameters\n        ----------\n        **param_kw\n            Parameters are given as keyword arguments, where the names\n            of the arguments must match the names of the parameters over\n            which the hypersurfaces are interpolated. The values\n            are given as :obj:`Quantity` objects with units.\n        \"\"\"\n        assert set(param_kw.keys()) == set(self.interp_param_spec.keys()), \"invalid parameters\"\n        # getting param magnitudes in the same units as the parameter specification\n        x = np.array([\n            param_kw[p].m_as(self.interp_param_spec[p][\"values\"][0].u)\n            # we have checked that this is an OrderedDict so that the order of x is not\n            # ambiguous here\n            for p in self.interp_param_spec.keys()\n        ])\n        assert len(x) == len(self.param_bounds)\n        for i, bounds in enumerate(self.param_bounds):\n            x[i] = np.clip(x[i], *bounds)\n        # if a parameter scales as log, we have to take the log here again\n        for i, param_name in enumerate(self.interpolation_param_names):\n            if self.interp_param_spec[param_name][\"scales_log\"]:\n                # We must be strict with raising errors here, because otherwise\n                # the Hypersurface will suddenly have NaNs everywhere! This shouldn't\n                # happen because we clip values into the valid parameter range.\n                if x[i] <= 0:\n                    raise RuntimeError(\"A log-scaling parameter cannot become zero \"\n                                       \"or negative!\")\n                x[i] = np.log10(x[i])\n\n        state = copy.deepcopy(self._reference_state)\n        # fit covariance matrices are stored directly in the state while fit coeffts\n        # must be assigned with the setter method...\n        # need squeeze here because the RegularGridInterpolator always puts another\n        # dimension around the output\n        state[\"fit_cov_mat\"] = np.squeeze(self.covars(x))\n        assert state[\"fit_cov_mat\"].shape == self.covars_shape\n        for idx in np.ndindex(state['fit_cov_mat'].shape):\n            if self.ignore_nan: continue\n            assert np.isfinite(state['fit_cov_mat'][idx]), (\"invalid cov matrix \"\n                f\"element encountered at {param_kw} in loc {idx}\")\n        # check covariance matrices for symmetry, positive semi-definiteness\n        for bin_idx in np.ndindex(state['fit_cov_mat'].shape[:-2]):\n            m = state['fit_cov_mat'][bin_idx]\n            if self.ignore_nan and np.any(~np.isfinite(m)):\n                state['fit_cov_mat'][bin_idx] = np.identity(m.shape[0])\n                m = state['fit_cov_mat'][bin_idx]\n            assert np.allclose(\n                m, m.T, rtol=ALLCLOSE_KW['rtol']*10.), f'cov matrix not symmetric in bin {bin_idx}'\n            if not matrix.is_psd(m):\n                state['fit_cov_mat'][bin_idx] = matrix.fronebius_nearest_psd(m)\n                if not bin_idx in self.covar_bins_warning_issued:\n                    logging.warn(\n                        f'Invalid covariance matrix fixed in bin: {bin_idx}')\n                    self.covar_bins_warning_issued.append(bin_idx)\n        hypersurface = Hypersurface.from_state(state)\n        coeffts = np.squeeze(self.coefficients(x))  # calls interpolator\n        assert coeffts.shape == self.coeff_shape\n        # check that coefficients exist and if not replace with default values\n        for idx in np.ndindex(self.coeff_shape):\n            if self.ignore_nan and ~np.isfinite(coeffts[idx]):\n                coeffts[idx] = 1 if idx[-1] == 0 else 0  # set intercept to 1, slopes 0\n            assert np.isfinite(coeffts[idx]), (\"invalid coeff encountered at \"\n                f\"{param_kw} in loc {idx}\")\n        # the setter method defined in the Hypersurface class takes care of\n        # putting the coefficients in the right place in their respective parameters\n        hypersurface.fit_coeffts = coeffts\n        return hypersurface\n\n    def _make_slices(self, *xi):\n        \"\"\"Make slices of hypersurfaces for plotting.\n\n        In some covariance matrices, the spline fits are corrected to make\n        the matrix positive semi-definite. The slices produced by this function\n        include all of those effects.\n\n        Parameters\n        ----------\n        xi : list of ndarray\n            Points at which the hypersurfaces are to be evaluated. The length of the\n            list must equal the number of parameters, each ndarray in the list must have\n            the same shape (slice_shape).\n\n        Returns\n        -------\n        coeff_slices : numpy.ndarray\n            slices in fit coefficients. Size: (binning..., number of coeffs) + slice_shape\n        covar_slices : numpy.ndarray\n            slices in covariance matrix elements.\n            Size: (binning..., number of coeffs, number of coeffs) + slice_shape\n        \"\"\"\n        slice_shape = xi[0].shape\n        for x in xi:\n            assert x.shape == slice_shape\n        assert len(xi) == self.num_interp_params\n        coeff_slices = np.zeros(self.coeff_shape + slice_shape)\n        covar_slices = np.zeros(self.covars_shape + slice_shape)\n        for idx in np.ndindex(slice_shape):\n            pars = collections.OrderedDict()\n            for i, name in enumerate(self.interpolation_param_names):\n                pars[name] = xi[i][idx]\n            hs = self.get_hypersurface(**pars)\n            slice_idx = (Ellipsis,) + idx\n            coeff_slices[slice_idx] = hs.fit_coeffts\n            covar_slices[slice_idx] = hs.fit_cov_mat\n        return coeff_slices, covar_slices\n\n    def plot_fits_in_bin(self, bin_idx, ax=None, n_steps=20, **param_kw):\n        \"\"\"\n        Plot the coefficients as well as covariance matrix elements as a function\n        of the interpolation parameters.\n\n        Parameters\n        ----------\n            bin_idx : tuple\n                index of the bin for which to plot the fits\n            ax : 2D array of axes, optional\n                axes into which to place the plots. If None (default),\n                appropriate axes will be generated. Must have at least\n                size (n_coeff, n_coeff + 1).\n            n_steps : int, optional\n                number of steps to plot between minimum and maximum\n            **param_kw :\n                Parameters to be fixed when producing slices. If the interpolation\n                is in N-D, then (N-2) parameters need to be fixed to produce 2D plots\n                of the remaining 2 parameters and (N-1) need to be fixed to produce a\n                1D slice.\n        \"\"\"\n        plot_dim = self.ndim - len(param_kw.keys())\n        assert plot_dim in [1, 2], \"plotting only supported in 1D or 2D\"\n        import matplotlib.pyplot as plt\n        n_coeff = self.coeff_shape[-1]\n        hs_param_names = list(self._reference_state['params'].keys())\n        hs_param_labels = [\"intercept\"] + [f\"{p} p{i}\" for p in hs_param_names\n                                           for i in range(self._reference_state['params'][p]['num_fit_coeffts'])]\n\n        fig = None\n        if ax is None:\n            fig, ax = plt.subplots(nrows=n_coeff, ncols=n_coeff+1,\n                                   squeeze=False, sharex=True,\n                                   figsize=(3+(5*(n_coeff+1)), 2+(3*n_coeff)) )\n        # remember whether the plots need log scale or not, by default not\n        x_is_log = False\n        y_is_log = False\n\n        # names of the variables we are plotting\n        plot_names = set(self.interpolation_param_names) - set(param_kw.keys())\n        if plot_dim == 1:\n            x_name = list(plot_names)[0]\n        else:\n            x_name, y_name = list(plot_names)\n\n        # in both 1D and 2D cases, we always plot at least an x-variable\n        x_unit = self.interp_param_spec[x_name][\"values\"][0].u\n        # we need the magnitudes here so that units are unambiguous when we make\n        # the linspace/geomspace for plotting\n        x_mags = [v.m_as(x_unit) for v in self.interp_param_spec[x_name][\"values\"]]\n        if self.interp_param_spec[x_name][\"scales_log\"]:\n            x_plot = np.geomspace(np.min(x_mags), np.max(x_mags), n_steps)\n            x_is_log = True\n        else:\n            x_plot = np.linspace(np.min(x_mags), np.max(x_mags), n_steps)\n        # we put the unit back later\n        if plot_dim == 1:\n            # To make slices, we need to set any variables we do not plot over to the\n            # value given in param_kw.\n            slice_args = []\n            # We need to make sure that we give the values in the correct order!\n            for n in self.interpolation_param_names:\n                if n == x_name:\n                    slice_args.append(x_plot * x_unit)\n                elif n in param_kw.keys():\n                    # again, insure that the same unit is used that went into the\n                    # interpolation\n                    param_unit = self.interp_param_spec[n][\"values\"][0].u\n                    slice_args.append(\n                        np.full(x_plot.shape, param_kw[n].m_as(param_unit)) * param_unit\n                    )\n                else:\n                    raise ValueError(\"parameter neither specified nor plotted\")\n            coeff_slices, covar_slices = self._make_slices(*slice_args)\n        else:\n            # if we are in 2D, we need to do the same procedure again for the y-variable\n            y_unit = self.interp_param_spec[y_name][\"values\"][0].u\n            y_mags = [v.m_as(y_unit) for v in self.interp_param_spec[y_name][\"values\"]]\n            if self.interp_param_spec[y_name][\"scales_log\"]:\n                # we add one step to the size in y so that transposition is unambiguous\n                y_plot = np.geomspace(np.min(y_mags), np.max(y_mags), n_steps + 1)\n                y_is_log = True\n            else:\n                y_plot = np.linspace(np.min(y_mags), np.max(y_mags), n_steps + 1)\n\n            x_mesh, y_mesh = np.meshgrid(x_plot, y_plot)\n            slice_args = []\n            for n in self.interpolation_param_names:\n                if n == x_name:\n                    slice_args.append(x_mesh * x_unit)\n                elif n == y_name:\n                    slice_args.append(y_mesh * y_unit)\n                elif n in param_kw.keys():\n                    # again, insure that the same unit is used that went into the\n                    # interpolation\n                    param_unit = self.interp_param_spec[n][\"values\"][0].u\n                    slice_args.append(\n                        np.full(x_mesh.shape, param_kw[n].m_as(param_unit)) * param_unit\n                    )\n                else:\n                    raise ValueError(\"parameter neither specified nor plotted\")\n            coeff_slices, covar_slices = self._make_slices(*slice_args)\n\n        # first column plots fit coefficients\n        for i in range(n_coeff):\n            z_slice = coeff_slices[bin_idx][i]\n            if plot_dim == 1:\n                ax[i, 0].plot(x_plot, z_slice, label='interpolation')\n                # Plotting the original input points only works if the interpolation\n                # is in 1D. If we are plotting a 1D slice from a 2D interpolation, this\n                # does not work.\n                # The number of fit points is the first dimension in self._coeff_z\n                if plot_dim == self.ndim:\n                    slice_idx = (Ellipsis,) + bin_idx + (i,)\n                    ax[i, 0].scatter(x_mags, self._coeff_z[slice_idx],\n                                     color='k', marker='x', label='fit points')\n                ax[i, 0].set_ylabel(hs_param_labels[i])\n            else:\n                pc = ax[i, 0].pcolormesh(x_mesh, y_mesh, z_slice)\n                cbar = plt.colorbar(pc, ax=ax[i, 0])\n                cbar.ax.ticklabel_format(style='sci', scilimits=(0, 0))\n                ax[i, 0].set_ylabel(y_name)\n                ax[i, 0].set_xlabel(x_name)\n\n            # later column plots the elements of the covariance matrix\n            for j in range(0, n_coeff):\n                z_slice = covar_slices[bin_idx][i, j]\n                if plot_dim == 1:\n                    ax[i, j+1].plot(x_plot, z_slice, label='interpolation')\n                    # Same problem as above, only in 1D case can this be shown\n                    # the number of points is the first dim in self._covar_z\n                    if plot_dim == self.ndim:\n                        coeff_idx = (Ellipsis,) + bin_idx + (i, j)\n                        ax[i, j+1].scatter(x_mags, self._covar_z[coeff_idx],\n                                           color='k', marker='x', label='fit points')\n                else:\n                    pc = ax[i, j+1].pcolormesh(x_mesh, y_mesh, z_slice)\n                    cbar = plt.colorbar(pc, ax=ax[i, j+1])\n                    cbar.ax.ticklabel_format(style='sci', scilimits=(0, 0))\n                    ax[i, j+1].set_ylabel(y_name)\n                    ax[i, j+1].set_xlabel(x_name)\n\n        if plot_dim == 1:\n            # in the 1D case, labels can be placed on the x and y axes\n            for j in range(n_coeff+1):\n                ax[-1, j].set_xlabel(x_name)\n            ax[0, 0].set_title('coefficient')\n            for j in range(n_coeff):\n                ax[0, j+1].set_title(f'cov. {hs_param_labels[j]}')\n        else:\n            # in the 2D case, we need separate annotations\n            rows = hs_param_labels\n            cols = [\"coefficient\"] + [f\"cov. {hl}\" for hl in hs_param_labels]\n            pad = 20\n            for a, col in zip(ax[0], cols):\n                a.annotate(col, xy=(0.5, 1), xytext=(0, pad),\n                           xycoords='axes fraction', textcoords='offset points',\n                           size='x-large', ha='center', va='baseline')\n\n            for a, row in zip(ax[:, 0], rows):\n                a.annotate(row, xy=(0, 0.5), xytext=(-a.yaxis.labelpad - pad, 0),\n                           xycoords=a.yaxis.label, textcoords='offset points',\n                           size='x-large', ha='right', va='center')\n        for i, j in np.ndindex((n_coeff, n_coeff+1)):\n            if x_is_log: ax[i, j].set_xscale(\"log\")\n            if y_is_log: ax[i, j].set_yscale(\"log\")\n            ax[i, j].grid()\n            if plot_dim == 1:\n                ax[i, j].legend()\n            # ax[i, j].relim()\n            # ax[i, j].autoscale_view()\n            if not x_is_log:\n                ax[i, j].ticklabel_format(style='sci', scilimits=(0, 0), axis=\"x\")\n            if not y_is_log:\n                ax[i, j].ticklabel_format(style='sci', scilimits=(0, 0), axis=\"y\")\n\n        if fig is not None :\n            fig.tight_layout()\n            if plot_dim == 2:\n                fig.subplots_adjust(left=0.15, top=0.95)\n            return fig\n        else :\n            return\n\n\ndef pipeline_cfg_from_states(state_dict):\n    \"\"\"Recover a pipeline cfg containing PISA objects from a raw state.\n\n    When a pipeline configuration is stored to JSON, the PISA objects turn into\n    their serialized states. This function looks through the dictionary returned by\n    `from_json` and recovers the PISA objects such as `ParamSet` and `MultiDimBinning`.\n\n    It should really become part of PISA file I/O functionality to read and write\n    PISA objects inside dictionaries/lists into a JSON and be able to recover\n    them...\n    \"\"\"\n\n    # TODO: Make this a core functionality of PISA\n\n    # This is just a mess... some objects have a `from_state` method, some take the\n    # unpacked state dict as input, some take the state...\n\n    pipeline_cfg = collections.OrderedDict()\n    for stage_key in state_dict.keys():\n        # need to check all of this manually... no automatic way to do it :(\n        if stage_key == \"pipeline\":\n            pipeline_cfg[stage_key] = copy.deepcopy(state_dict[stage_key])\n            pipeline_cfg[stage_key][\"output_key\"] = tuple(\n                pipeline_cfg[stage_key][\"output_key\"])\n            binning_state = pipeline_cfg[stage_key][\"output_binning\"]\n            pipeline_cfg[stage_key][\"output_binning\"] = MultiDimBinning(**binning_state)\n            continue\n        # undo what we did in `serialize_pipeline_cfg` by splitting the keys into tuples\n        tuple_key = tuple(stage_key.split(\"__\"))\n        pipeline_cfg[tuple_key] = copy.deepcopy(state_dict[stage_key])\n        for k in [\"calc_mode\", \"apply_mode\", \"node_mode\"]:\n            if k in pipeline_cfg[tuple_key]:\n                if isinstance(pipeline_cfg[tuple_key][k], collections.Mapping):\n                    pipeline_cfg[tuple_key][k] = MultiDimBinning(\n                        **pipeline_cfg[tuple_key][k])\n        if \"params\" in pipeline_cfg[tuple_key].keys():\n            pipeline_cfg[tuple_key][\"params\"] = ParamSet(\n                pipeline_cfg[tuple_key][\"params\"])\n    # if any stage takes any other arguments that we didn't think of here, they\n    # won't work\n    return pipeline_cfg\n\ndef serialize_pipeline_cfg(pipeline_cfg):\n    \"\"\"Turn a pipeline configuration into something we can store to JSON.\n\n    It doesn't work by default because tuples are not allowed as keys when storing to\n    JSON. All we do is to turn the tuples into strings divided by a double underscore.\n    \"\"\"\n    serializable_state = collections.OrderedDict()\n    serializable_state[\"pipeline\"] = pipeline_cfg[\"pipeline\"]\n    for k in pipeline_cfg.keys():\n        if k == \"pipeline\": continue\n        flat_key = \"__\".join(k)\n        serializable_state[flat_key] = pipeline_cfg[k]\n    # this isn't _really_ a serializable state, the objects are still PISA objects...\n    # bit it will convert correctly when thrown into `to_json`\n    return serializable_state\n\n\ndef assemble_interpolated_fits(fit_directory, output_file, drop_fit_maps=False):\n    \"\"\"After all of the fits on the cluster are done, assemble the results to one JSON.\n\n    The JSON produced by this function is what `load_interpolated_hypersurfaces`\n    expects.\n    \"\"\"\n    assert os.path.isdir(fit_directory), \"fit directory does not exist\"\n    metadata = from_json(os.path.join(fit_directory, \"metadata.json\"))\n\n    combined_data = collections.OrderedDict()\n    combined_data[\"interpolation_param_spec\"] = metadata[\"interpolation_param_spec\"]\n\n    # Loop over grid points\n    hs_fits = []\n    grid_shape = tuple(metadata[\"grid_shape\"])\n    for job_idx, grid_idx in enumerate(np.ndindex(grid_shape)):\n\n        # Load grid point data\n        gridpoint_json = os.path.join(fit_directory, f\"gridpoint_{job_idx:06d}.json.bz2\")\n        logging.info(f\"Reading {gridpoint_json}\")\n        gridpoint_data = from_json(gridpoint_json)\n\n        # Check the loaded data\n        assert job_idx == gridpoint_data[\"job_idx\"]\n        assert np.all(grid_idx == gridpoint_data[\"grid_idx\"])\n        # TODO: Offer to run incomplete fits locally\n        assert gridpoint_data[\"fit_successful\"], f\"job no. {job_idx} not finished\"\n\n        # Drop fit maps if requested (can significantly reduce file size)\n        if drop_fit_maps :\n            for key, hs_state in gridpoint_data[\"hs_fit\"].items() :\n                hs_state[\"fit_maps_raw\"] = None\n                hs_state[\"fit_maps_norm\"] = None\n\n        # Add grid point data to output file\n        hs_fits.append(collections.OrderedDict(\n            param_values=gridpoint_data[\"param_values\"],\n            hs_fit=gridpoint_data[\"hs_fit\"]\n        ))\n\n    # Write the output file\n    combined_data[\"hs_fits\"] = hs_fits\n    to_file(combined_data, output_file)\n\n\ndef get_incomplete_job_idx(fit_directory):\n    \"\"\"Get job indices of fits that are not flagged as successful.\"\"\"\n\n    assert os.path.isdir(fit_directory), \"fit directory does not exist\"\n    metadata = from_json(os.path.join(fit_directory, \"metadata.json\"))\n    grid_shape = tuple(metadata[\"grid_shape\"])\n    failed_idx = []\n    for job_idx, grid_idx in enumerate(np.ndindex(grid_shape)):\n        try:\n            gridpoint_json = os.path.join(fit_directory,\n                                          f\"gridpoint_{job_idx:06d}.json.bz2\")\n            logging.info(f\"Reading {gridpoint_json}\")\n            gridpoint_data = from_json(gridpoint_json)\n        except:\n            break\n        if not gridpoint_data[\"fit_successful\"]:\n            failed_idx.append(job_idx)\n        job_idx += 1\n    return failed_idx\n\ndef run_interpolated_fit(fit_directory, job_idx, skip_successful=False):\n    \"\"\"Run the hypersurface fit for a grid point.\n\n    If `skip_successful` is true, do not run if the `fit_successful` flag is already\n    True.\n    \"\"\"\n\n    #TODO a lot of this is copied from fit_hypersurfaces in hypersurface.py, would be safer to make more OAOO\n    #TODO Copy the param value storage stuff from fit_hypersurfaces across in the meantime\n\n    assert os.path.isdir(fit_directory), \"fit directory does not exist\"\n\n    gridpoint_json = os.path.join(fit_directory, f\"gridpoint_{job_idx:06d}.json.bz2\")\n    gridpoint_data = from_json(gridpoint_json)\n\n    if skip_successful and gridpoint_data[\"fit_successful\"]:\n        logging.info(f\"Fit at job index {job_idx} already successful, skipping...\")\n        return\n\n    metadata = from_json(os.path.join(fit_directory, \"metadata.json\"))\n\n    interpolation_param_spec = metadata[\"interpolation_param_spec\"]\n\n    # this is a pipeline configuration in the form of an OrderedDict\n    nominal_dataset = metadata[\"nominal_dataset\"]\n    # Why can we still not load PISA objects from JSON that are inside a dict?! Grrr...\n    nominal_dataset[\"pipeline_cfg\"] = pipeline_cfg_from_states(\n        nominal_dataset[\"pipeline_cfg\"]\n    )\n    # this is a list of pipeline configurations\n    sys_datasets = metadata[\"sys_datasets\"]\n    for sys_dataset in sys_datasets:\n        sys_dataset[\"pipeline_cfg\"] = pipeline_cfg_from_states(\n            sys_dataset[\"pipeline_cfg\"]\n        )\n    # this is a dict of param_name : value pairs\n    param_values = gridpoint_data[\"param_values\"]\n    # we do a redundant check to make sure the parameter values at this grid point are\n    # correct\n    interpolation_param_names = metadata[\"interpolation_param_names\"]\n    grid_shape = tuple(metadata[\"grid_shape\"])\n    # the grid point index of this job\n    grid_idx = list(np.ndindex(grid_shape))[job_idx]\n    for i, n in enumerate(interpolation_param_names):\n        ms = \"Inconsistent parameter values at grid point!\"\n        assert interpolation_param_spec[n][\"values\"][grid_idx[i]] == param_values[n], ms\n\n    # now we need to adjust the values of the parameter in all pipelines for this point\n    logging.info(f\"updating pipelines with parameter values: {param_values}\")\n    for dataset in [nominal_dataset] + sys_datasets:\n        for stage_cfg in dataset[\"pipeline_cfg\"].values():\n            if \"params\" not in stage_cfg.keys(): continue\n            for param in interpolation_param_names:\n                if param in stage_cfg[\"params\"].names:\n                    stage_cfg[\"params\"][param].value = param_values[param]\n\n    # these are the parameters of the hypersurface, NOT the ones we interpolate them\n    # over!\n    hypersurface_params = []\n    for param_state in metadata[\"hypersurface_params\"]:\n        hypersurface_params.append(HypersurfaceParam.from_state(param_state))\n\n    def find_hist_stage(pipeline):\n        \"\"\"Locate the index of the hist stage in a pipeline.\"\"\"\n        hist_idx_found = False\n        for i, s in enumerate(pipeline.stages):\n            if s.__class__.__name__ == \"hist\":\n                hist_idx = i\n                hist_idx_found = True\n                break\n        if not hist_idx_found:\n            raise RuntimeError(\"Could not find histogram stage in pipeline, aborting.\")\n        return hist_idx\n\n    # We create Pipeline objects, get their outputs and then forget about the Pipeline\n    # object on purpose! The memory requirement to hold all systematic sets at the same\n    # time is just too large, especially on the cluster. The way we do it below we\n    # only need enough memory for one dataset at a time.\n\n    for dataset in [nominal_dataset] + sys_datasets:\n        pipeline = Pipeline(dataset[\"pipeline_cfg\"])\n        dataset[\"mapset\"] = pipeline.get_outputs()\n        # get the un-weighted event counts as well so that we can exclude bins\n        # with too little statistics\n        # First, find out which stage is the hist stage\n        hist_idx = find_hist_stage(pipeline)\n        pipeline.stages[hist_idx].unweighted = True\n        dataset[\"mapset_unweighted\"] = pipeline.get_outputs()\n    del pipeline\n\n    # Merge maps according to the combine regex, if one was provided\n    combine_regex = metadata[\"combine_regex\"]\n    if combine_regex is not None:\n        for dataset in [nominal_dataset] + sys_datasets:\n            dataset[\"mapset\"] = dataset[\"mapset\"].combine_re(combine_regex)\n            dataset[\"mapset_unweighted\"] = dataset[\"mapset_unweighted\"].combine_re(combine_regex)\n\n    minimum_mc = metadata[\"minimum_mc\"]\n    # Remove bins (i.e. set their count to zero) that have too few MC events\n    for dataset in sys_datasets + [nominal_dataset]:\n        for map_name in dataset[\"mapset\"].names:\n            insuff_mc = dataset[\"mapset_unweighted\"][map_name].nominal_values < minimum_mc\n            # Setting the hist to zero sets both nominal value and std_dev to zero\n            dataset[\"mapset\"][map_name].hist[insuff_mc] = 0.\n\n    hypersurface_fit_kw = metadata[\"hypersurface_fit_kw\"]\n    hypersurfaces = collections.OrderedDict()\n    log = metadata[\"log\"]  # flag determining whether hs fit is run in log-space or not\n    for map_name in nominal_dataset[\"mapset\"].names:\n        nominal_map = nominal_dataset[\"mapset\"][map_name]\n        nominal_param_values = nominal_dataset[\"sys_params\"]\n\n        sys_maps = [sys_dataset[\"mapset\"][map_name] for sys_dataset in sys_datasets]\n        sys_param_values = [sys_dataset[\"sys_params\"] for sys_dataset in sys_datasets]\n\n        hypersurface = Hypersurface(\n            # Yes, this MUST be a deepcopy! Otherwise weird memory overwrites happen\n            # and all the numbers get jumbled across the hypersurfaces of different maps\n            params=copy.deepcopy(hypersurface_params),\n            initial_intercept=0. if log else 1.,  # Initial value for intercept\n            log=log\n        )\n\n        hypersurface.fit(\n            nominal_map=nominal_map,\n            nominal_param_values=nominal_param_values,\n            sys_maps=sys_maps,\n            sys_param_values=sys_param_values,\n            norm=True,\n            # Is the space or loading time really a problem?\n            # keep_maps=False,  # it would take a lot more space otherwise\n            **hypersurface_fit_kw\n        )\n\n        logging.debug(\"\\nFitted hypersurface report:\\n%s\" % hypersurface)\n        hypersurfaces[map_name] = hypersurface\n\n    gridpoint_data[\"hs_fit\"] = hypersurfaces\n    gridpoint_data[\"fit_successful\"] = True\n\n    to_json(gridpoint_data, gridpoint_json)\n\n\ndef prepare_interpolated_fit(\n    nominal_dataset, sys_datasets, params, fit_directory, interpolation_param_spec,\n    combine_regex=None, log=False, minimum_mc=0, **hypersurface_fit_kw\n):\n    '''\n    Writes steering files for fitting hypersurfaces on a grid of arbitrary parameters.\n    The fits can then be run on a cluster with `run_interpolated_fit`.\n\n    Parameters\n    ----------\n    nominal_dataset : dict\n        Definition of the nominal dataset. Specifies the pipleline with which the maps\n        can be created, and the values of all systematic parameters used to produced the\n        dataset.\n        Format must be:\n            nominal_dataset = {\n                \"pipeline_cfg\" = <pipeline cfg file (either cfg file path or dict)>),\n                \"sys_params\" = { param_0_name : param_0_value_in_dataset, ..., param_N_name : param_N_value_in_dataset }\n            }\n        Sys params must correspond to the provided HypersurfaceParam instances provided\n        in the `params` arg.\n\n    sys_datasets : list of dicts\n        List of dicts, where each dict defines one of the systematics datasets to be\n        fitted. The format of each dict is the same as explained for `nominal_dataset`\n\n    params : list of HypersurfaceParams\n        List of HypersurfaceParams instances that define the hypersurface. Note that\n        this defined ALL hypersurfaces fitted in this function, e.g. only supports a\n        single parameterisation for all maps (this is almost always what you want).\n\n    output_directory : str\n        Directory in which the fits will be run. Steering files for the fits to be run\n        will be stored here.\n\n    combine_regex : list of str, or None\n        List of string regex expressions that will be used for merging maps. Used to\n        combine similar species. Must be something that can be passed to the\n        `MapSet.combine_re` function (see that functions docs for more details). Choose\n        `None` is do not want to perform this merging.\n\n    interpolation_param_spec : collections.OrderedDict\n        Specification of parameter grid that hypersurfaces should be interpolated over.\n        The dict should have the following form::\n            interpolation_param_spec = {\n                'param1': {\"values\": [val1_1, val1_2, ...], \"scales_log\": True/False}\n                'param2': {\"values\": [val2_1, val2_2, ...], \"scales_log\": True/False}\n                ...\n                'paramN': {\"values\": [valN_1, valN_2, ...], \"scales_log\": True/False}\n            }\n        The hypersurfaces will be fit on an N-dimensional rectilinear grid over\n        parameters 1 to N. The flag `scales_log` indicates that the interpolation over\n        that parameter should happen in log-space.\n\n    minimum_mc : int, optional\n        Minimum number of un-weighted MC events required in each bin.\n\n    hypersurface_fit_kw : kwargs\n        kwargs will be passed on to the calls to `Hypersurface.fit`\n    '''\n\n    # Take (deep) copies of lists/dicts to avoid modifying the originals\n    # Useful for cases where this function is called in a loop (e.g. leave-one-out tests)\n    nominal_dataset = copy.deepcopy(nominal_dataset)\n    sys_datasets = copy.deepcopy(sys_datasets)\n    params = copy.deepcopy(params)\n\n    # Check types\n    assert isinstance(sys_datasets, collections.Sequence)\n    assert isinstance(params, collections.Sequence)\n    assert isinstance(fit_directory, str)\n    # there must not be any ambiguity between fitting the hypersurfaces and\n    # interpolating them later\n    msg = \"interpolation params must be specified as a dict with ordered keys\"\n    assert isinstance(interpolation_param_spec, collections.OrderedDict), msg\n    for k, v in interpolation_param_spec.items():\n        assert set(v.keys()) == {\"values\", \"scales_log\"}\n        assert isinstance(v[\"values\"], collections.Sequence)\n        # We need to extract the magnitudes from the Quantities to avoid a\n        # UnitStrippedWarning. For some reason, doing `np.min(v[\"values\"])` messes up\n        # the data structure inside the values in a way that can cause a crash when we\n        # try to serialize the values later. Lesson: Stripping units inadvertently can\n        # have strange, unforeseen consequences.\n        mags = [x.m for x in v[\"values\"]]\n        if v[\"scales_log\"] and np.min(mags) <= 0:\n            raise ValueError(\"A log-scaling parameter cannot be equal to or less \"\n                \"than zero!\")\n\n    # Check output format and path\n    assert os.path.isdir(fit_directory), \"fit directory does not exist\"\n\n    # Check formatting of datasets is as expected\n    all_datasets = [nominal_dataset] + sys_datasets\n    for dataset in all_datasets:\n        assert isinstance(dataset, collections.Mapping)\n        assert \"pipeline_cfg\" in dataset\n        assert isinstance(dataset[\"pipeline_cfg\"], (str, collections.Mapping))\n        assert \"sys_params\" in dataset\n        assert isinstance(dataset[\"sys_params\"], collections.Mapping)\n\n        dataset[\"pipeline_cfg\"] = serialize_pipeline_cfg(dataset[\"pipeline_cfg\"])\n\n    # Check params\n    assert len(params) >= 1\n    for p in params:\n        assert isinstance(p, HypersurfaceParam)\n\n    # Report inputs\n    msg = \"Hypersurface fit details :\\n\"\n    msg += f\"  Num params            : {len(params)}\\n\"\n    msg += f\"  Num fit coefficients  : {sum([p.num_fit_coeffts for p in params])}\\n\"\n    msg += f\"  Num datasets          : 1 nominal + {len(sys_datasets)} systematics\\n\"\n    msg += f\"  Nominal values        : {nominal_dataset['sys_params']}\\n\"\n    msg += \"Hypersurface fits are prepared on the following grid:\\n\"\n    msg += str(interpolation_param_spec)\n    logging.info(msg)\n\n    # because we require this to be an OrderedDict, there is no ambiguity in the\n    # construction of the mesh here\n    param_names = list(interpolation_param_spec.keys())\n    grid_shape = tuple(len(v[\"values\"]) for v in interpolation_param_spec.values())\n\n    # We store all information needed to run a fit in metadata\n    metadata = collections.OrderedDict(\n        interpolation_param_spec=interpolation_param_spec,\n        interpolation_param_names=param_names,  # convenience\n        grid_shape=grid_shape,  # convenience\n        nominal_dataset=nominal_dataset,\n        sys_datasets=sys_datasets,\n        hypersurface_params=params,\n        combine_regex=combine_regex,\n        log=log,\n        minimum_mc=minimum_mc,\n        hypersurface_fit_kw=hypersurface_fit_kw\n    )\n\n    to_json(metadata, os.path.join(fit_directory, \"metadata.json\"))\n\n    # we write on JSON file for each grid point\n    for job_idx, grid_idx in enumerate(np.ndindex(grid_shape)):\n        # Although this is technically redundant, we store the parameter values\n        # explicitly for each grid point.\n        param_values = {}\n        for i, n in enumerate(param_names):\n            param_values[n] = interpolation_param_spec[n][\"values\"][grid_idx[i]]\n\n        gridpoint_data = {\n            \"param_values\": param_values,\n            \"hs_fit\": None,\n            \"job_idx\": job_idx,\n            \"grid_idx\": grid_idx,\n            \"fit_successful\": False\n        }\n        to_json(gridpoint_data, os.path.join(fit_directory,\n            f\"gridpoint_{job_idx:06d}.json.bz2\"))\n\n    logging.info(f\"Grid fit preparation complete! Total number of jobs: {job_idx+1}\")\n    return job_idx+1  # zero-indexing\n\ndef load_interpolated_hypersurfaces(input_file):\n    '''\n    Load a set of interpolated hypersurfaces from a file.\n\n    Analogously to \"load_hypersurfaces\", this function returns a\n    collection with a HypersurfaceInterpolator object for each Map.\n\n    Parameters\n    ----------\n    input_file : str\n        A JSON input file as produced by fit_hypersurfaces if interpolation params\n        were given. It has the form::\n            {\n                interpolation_param_spec = {\n                    'param1': {\"values\": [val1_1, val1_2, ...], \"scales_log\": True/False}\n                    'param2': {\"values\": [val2_1, val2_2, ...], \"scales_log\": True/False}\n                    ...\n                    'paramN': {\"values\": [valN_1, valN_2, ...], \"scales_log\": True/False}\n                },\n                'hs_fits': [\n                    <list of dicts where keys are map names such as 'nue_cc' and values\n                    are hypersurface states>\n                ]\n            }\n\n    Returns\n    -------\n    collections.OrderedDict\n        dictionary with a :obj:`HypersurfaceInterpolator` for each map\n    '''\n    assert isinstance(input_file, str)\n\n    logging.info(f\"Loading interpolated hypersurfaces from file: {input_file}\")\n\n    # Load the data from the file\n    input_data = from_file(input_file)\n\n    # check the file contents\n    assert set(['interpolation_param_spec', 'hs_fits']).issubset(\n        set(input_data.keys())), 'missing keys'\n\n    # input_data['hs_fits'] is a list of dicts, each dict contains \"param_values\"\n    # and \"hs_fit\"\n    map_names = None\n    logging.info(\"Reading file complete, generating hypersurfaces...\")\n    for hs_fit_dict in input_data['hs_fits']:\n        # this is still not the actual Hypersurface, but a dict with the (linked)\n        # maps and the HS fit for the map...\n        hs_state_maps = hs_fit_dict[\"hs_fit\"]\n        if map_names is None:\n            map_names = list(hs_state_maps.keys())\n        else:\n            assert set(map_names) == set(hs_state_maps.keys()), \"inconsistent maps\"\n        # When data is recovered from JSON, the object states are not automatically\n        # converted to the corresponding objects, so we need to do it manually here.\n        for map_name in map_names:\n            hs_state_maps[map_name] = Hypersurface.from_state(hs_state_maps[map_name])\n\n    logging.info(f\"Read hypersurface maps: {map_names}\")\n\n    # Now we have a list of dicts where the map names are on the lower level.\n    # We need to convert this into a dict of HypersurfaceInterpolator objects.\n    output = collections.OrderedDict()\n    for m in map_names:\n        hs_fits = [{\"param_values\": fd[\"param_values\"], \"hs_fit\": fd['hs_fit'][m]} for fd in input_data['hs_fits']]\n        output[m] = HypersurfaceInterpolator(input_data['interpolation_param_spec'], hs_fits)\n\n    return output\n", "meta": {"hexsha": "e14740b89a0539c20418d33c0c80eddb3a4f8ced", "size": 45879, "ext": "py", "lang": "Python", "max_stars_repo_path": "pisa/utils/hypersurface/hyper_interpolator.py", "max_stars_repo_name": "BenSmithers/pisa", "max_stars_repo_head_hexsha": "59d83e82c7492722d8238b14dde00d3199cf099b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pisa/utils/hypersurface/hyper_interpolator.py", "max_issues_repo_name": "BenSmithers/pisa", "max_issues_repo_head_hexsha": "59d83e82c7492722d8238b14dde00d3199cf099b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pisa/utils/hypersurface/hyper_interpolator.py", "max_forks_repo_name": "BenSmithers/pisa", "max_forks_repo_head_hexsha": "59d83e82c7492722d8238b14dde00d3199cf099b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.625, "max_line_length": 120, "alphanum_fraction": 0.6390287495, "include": true, "reason": "import numpy,from scipy", "num_tokens": 10299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.18551995938349805}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr  1 20:20:31 2019\n基于Keras 的条件随机场分词算法\n@author: 李畅\n\"\"\"\n\nfrom keras.models import Sequential\nfrom keras.layers import Embedding,Bidirectional,LSTM,BatchNormalization\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras import optimizers\nfrom keras_contrib.layers import CRF\nfrom keras.callbacks import TensorBoard\nimport numpy as np\nfrom os import path,rename,remove\nimport pickle\n\nmcrf_datas='./mcrf.data' # 以二进制保存的mcrf类数据\n\nclass MCRF:\n    def __init__(self,train_file,validate_file,model_file=\\\n            './crf_model.h5',embedding_dim=128,birnn_units=128,feat_filt_freq=3,\\\n            train_max_len=64,test_max_len=1024,batch_size=64,epochs=10):\n        \"\"\"\n        @param train_file : 训练文件\n        @param validate_file : 验证文件\n        @param model_file: 模型文件,h5类型文件\n        @param embedding_dim: 隐层维度\n        @param birnn_units: RNN 单元个数\n        @param feat_filt_freq: 将出现频次低于该值的特征过滤掉\n        @param train_max_len: 训练集中的最大长度\n        @param test_max_len: 测试文件一行最长的长度\n        @param batch_size: 训练过程中的批次大小\n        @param epochs: 训练的轮次\n        \"\"\"\n        self.train_file=train_file\n        self.validate_file = validate_file\n        self.model_file=model_file\n        self.feat_filt_freq=feat_filt_freq\n        self.embedding_dim=embedding_dim\n        self.birnn_units=birnn_units\n        self.test_max_len=test_max_len\n        self.batch_size=batch_size\n        self.epochs=epochs\n        self.tags=['B','M','E','S'] # 字符所有可能的标记\n        self.max_len=train_max_len # 最长的一段文字的长度\n        self.vocab=[]\n        (self.train_x,self.train_y),(self.test_x,self.test_y)=self._preprocess()\n        pass\n    \n    def _process_data(self, data):\n        \"\"\"\n        数据处理\n        \"\"\"\n        word_index=dict((w,i) for i,w in enumerate(self.vocab))\n        x=[[word_index.get(w[0], 1) for w in s] for s in data] # 对未登录词，index=0\n        y_chunk=[[self.tags.index(w[1]) for w in s] for s in data]\n        x= pad_sequences(x,self.max_len) # 在 x 的左侧填充0，使得各个sample的长度相同\n        y_chunk=pad_sequences(y_chunk,self.max_len,value=-1) # 左侧填充-1\n        y_chunk=np.expand_dims(y_chunk,2) # 扩充维度，每个标记为一个list[]\n        return x,y_chunk\n    \n    def _preprocess(self):\n        \"\"\"\n        数据预处理\n        \"\"\"\n        feat_freqs={}\n        data=[] # 二维矩阵，一行为一段文字\n        with open(self.train_file,encoding='utf-8',mode='r') as fr:\n            sample_len=0 # 记录当前一段文字的长度\n            one_sample=[]\n            for line in fr.readlines():\n                line=line.strip()\n                if not line or len(line) < 3:\n                    sample_len=0\n                    data.append(one_sample)\n                    one_sample=[]\n                    continue\n                sample_len +=1\n                word,tag=line.split()\n                one_sample.append([word,tag])\n                if (word,tag) not in feat_freqs.keys():\n                    feat_freqs.update({(word,tag):0})\n                feat_freqs[(word,tag)] +=1\n        # 特征值过滤\n        self.vocab=[key[0] for key,val in feat_freqs.items() if val > \\\n                    self.feat_filt_freq]\n        train_datas = self._process_data(data)\n        del data,feat_freqs\n        data=[]\n        #读取测试文件\n        with open(self.validate_file,encoding='utf-8',mode='r') as fr:\n            one_example=[]\n            for line in fr.readlines():\n                line=line.strip()\n                if not line or len(line) < 3:\n                    data.append(one_example)\n                    one_example=[]\n                    continue\n                word,tag = line.split()\n                one_example.append([word,tag])\n        test_datas=self._process_data(data)\n        return train_datas,test_datas\n    \n    def _create_model(self):\n        \"\"\"\n        创建训练使用的模型\n        \"\"\"\n        model=Sequential()\n        model.add(Embedding(len(self.vocab),self.embedding_dim,mask_zero=True))\n        model.add(Bidirectional(LSTM(self.birnn_units//2, return_sequences=True)))\n        crf=CRF(len(self.tags),sparse_target=True)\n        model.add(crf)\n        model.summary()\n#        model.compile('adam',loss=crf.loss_function,metrics=[crf.accuracy])\n        rms_prop=optimizers.RMSprop(lr=0.01,decay=1e-4)\n        model.compile(optimizer=rms_prop,loss=crf.loss_function,metrics=\\\n                      [crf.accuracy])\n        return model\n    \n    def train(self,model_exists=False):\n        \"\"\"\n        模型训练\n        \"\"\"\n        model=self._create_model()\n        if not model_exists:\n            # 创建tensorboard 回调\n            tb_callback=TensorBoard(log_dir='./logs',\n                    histogram_freq=0,\n                    batch_size=64,\n                    write_graph=True,\n                    write_grads=True,\n                    write_images=True,\n                    embeddings_freq=0,\n                    embeddings_layer_names=None,\n                    embeddings_metadata=None)\n            model.fit(self.train_x, self.train_y, batch_size=self.batch_size,epochs=self.epochs,\\\n                 validation_data=[self.test_x,self.test_y],callbacks=[tb_callback])\n            model.save(self.model_file)\n        else:\n            model.load_weights(self.model_file)\n        return model\n    \n    def _predict_str_preprocess(self,string):\n        \"\"\"\n        对待处理的字符串预处理\n        \"\"\"\n        word_index=dict((w,i) for i,w in enumerate(self.vocab))\n        x=[word_index.get(w[0], 1) for w in string]\n        length = len(x)\n        x=pad_sequences([x],self.test_max_len)\n        return x,length\n    \n    def predict(self,string,model):\n        \"\"\"\n        对序列的标记进行预测\n        @param string: 待处理的一串字符\n        @param model: 模型\n        \"\"\"\n        string,length=self._predict_str_preprocess(string)\n        raw=model.predict(string)[0][-length:]\n        result=[np.argmax(row) for row in raw]\n        result_tags=[self.tags[i] for i in result]\n        return result,result_tags\n    \n    def predict_file(self,testfile):\n        \"\"\"\n        对测试文件4词位标记\n        \"\"\"\n        if not path.exists(self.model_file):\n            model = self.train(model_exists=False)\n        else:\n            model = self.train(model_exists=True)\n        tmpfile=path.join(path.dirname(testfile),'tmp')\n        with open(testfile,encoding='utf-8',mode='r') as fr, open(tmpfile,\\\n                 encoding='utf-8',mode='w') as fw:\n            prog=0\n            for line in fr.readlines():\n                prog +=1\n                if prog % 100==0:\n                    print('processing line{}'.format(prog))\n                line=line.strip()\n                if not line:\n                    print('',file=fw)\n                    continue\n                _, tags=self.predict(line,model)\n                line=list(line)\n                # 对该行文字分词\n                ans=[]\n                tmpstr=''\n                for i in range(len(line)):\n                    if tags[i]=='S':\n                        tmpstr=''\n                        ans.append(line[i])\n                    elif tags[i] == 'B':\n                        tmpstr=''\n                        tmpstr=line[i]\n                    elif tags[i] == 'M':\n                        tmpstr += line[i]\n                    else:\n                        tmpstr += line[i]\n                        ans.append(tmpstr)\n                        tmpstr=''\n                print('  '.join(ans),file=fw)\n        remove(testfile)\n        rename(tmpfile,testfile)\n        pass\n    \nif not path.exists(mcrf_datas):\n    mcrf=MCRF('./pku_training.utf8','./pku_validate.utf8')\nelse:\n    with open(mcrf_datas,mode='rb') as fr:\n        mcrf=pickle.load(fr)\ntest_file='./pku_test.utf8'\nmcrf.predict_file(test_file)\n", "meta": {"hexsha": "c546da41193408c86a7544be7d6477b3d1148109", "size": 7598, "ext": "py", "lang": "Python", "max_stars_repo_path": "crf_keras.py", "max_stars_repo_name": "lichang98/alg-explore", "max_stars_repo_head_hexsha": "ae70dba90a14f511b8e89a64093b987ab3853643", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-15T10:19:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-15T10:19:53.000Z", "max_issues_repo_path": "crf_keras.py", "max_issues_repo_name": "lichang98/file-processing-algs", "max_issues_repo_head_hexsha": "ae70dba90a14f511b8e89a64093b987ab3853643", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "crf_keras.py", "max_forks_repo_name": "lichang98/file-processing-algs", "max_forks_repo_head_hexsha": "ae70dba90a14f511b8e89a64093b987ab3853643", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1759259259, "max_line_length": 97, "alphanum_fraction": 0.546986049, "include": true, "reason": "import numpy", "num_tokens": 1909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.32766831395172374, "lm_q1q2_score": 0.18546633909313096}}
{"text": "\"\"\"### FastJet Tools\n\nThe [FastJet package](http://fastjet.fr/) provides, among other things, fast\njet clustering utilities. It is written in C++ and includes a Python interface\nthat is easily installed at compile time by passing the `--enable-pyext` flag\nto `configure`. If you use this module for published research, please [cite\nFastJet appropriately](http://fastjet.fr/about.html).\n\nThe core of EnergyFlow does not rely on FastJet, and hence it is not required\nto be installed, but the following utilities are available assuming that\n`import fastjet` succeeds in your Python environment (if not, no warnings or\nerrors will be issued but this module will not be usable).\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nimport numpy as np\n\nfrom energyflow.utils.generic_utils import import_fastjet\n\nfj = import_fastjet()\n\n__all__ = []\n\nif fj:\n\n    __all__ = ['pjs_from_ptyphims', 'ptyphims_from_pjs', 'cluster', 'softdrop']\n\n    def pjs_from_ptyphims(ptyphims):\n        \"\"\"Converts particles in hadronic coordinates to FastJet PseudoJets.\n\n        **Arguments**\n\n        - **ptyphims** : _2d numpy.ndarray_\n            - An array of particles in hadronic coordinates.\n\n        **Returns**\n\n        - _list_ of _fastjet.PseudoJet_\n            - A list of PseudoJets corresponding to the particles in the given\n            array.\n        \"\"\"\n\n        pjs = []\n        for ptyphim in ptyphims:\n            pj = fj.PseudoJet()\n            pj.reset_PtYPhiM(*ptyphim[:4])\n            pjs.append(pj)\n\n        return pjs\n\n    def ptyphims_from_pjs(pjs, mass=True):\n        \"\"\"Extracts hadronic four-vectors from FastJet PseudoJets.\n\n        **Arguments**\n\n        - **pjs** : _list_ of _fastjet.PseudoJet_\n            - An iterable of PseudoJets.\n        - **mass** : _bool_\n            - Whether or not to include the mass in the extracted four-vectors.\n\n        **Returns**\n\n        - _numpy.ndarray_\n            - An array of four-vectors corresponding to the given PseudoJets as\n            `[pT, y, phi, m]`, where the mass is optional.\n        \"\"\"\n\n        if mass:\n            return np.asarray([[pj.pt(), pj.rap(), pj.phi(), pj.m()] for pj in pjs])\n        else:\n            return np.asarray([[pj.pt(), pj.rap(), pj.phi()] for pj in pjs])\n\n    def cluster(pjs, algorithm='ca', R=fj.JetDefinition.max_allowable_R):\n        \"\"\"Clusters a list of PseudoJets according to a specified jet\n        algorithm and jet radius.\n\n        **Arguments**\n\n        - **pjs** : _list_ of _fastjet.PseudoJet_\n            - A list of Pseudojets representing particles or other kinematic\n            objects that are to be clustered into jets.\n        - **algorithm** : {'kt', 'antikt', 'ca', 'cambridge', 'cambridge_aachen'}\n            - The jet algorithm to use during the clustering. Note that the\n            last three options all refer to the same strategy and are provided\n            because they are all used by the FastJet Python package.\n        - **R** : _float_\n            - The jet radius. The default value corresponds to\n            `max_allowable_R` as defined by the FastJet python package.\n\n        **Returns**\n\n        - _list_ of _fastjet.PseudoJet_\n            - A list of PseudoJets corresponding to the clustered jets.\n        \"\"\"\n\n        algorithm_l = algorithm.lower()\n        if algorithm_l  == 'kt':\n            jet_alg = fj.kt_algorithm\n        elif algorithm_l == 'antikt':\n            jet_alg = fj.antikt_algorithm\n        elif algorithm_l in {'ca', 'cambridge', 'cambridge_aachen'}:\n            jet_alg = fj.cambridge_algorithm\n        else:\n            raise ValueError(\"algorithm '{}' not understood\".format(algorithm))\n\n        return fj.JetDefinition(jet_alg, R)(pjs)\n\n    def softdrop(jet, zcut=0.1, beta=0, R=1.0):\n        r\"\"\"Implements the SoftDrop grooming algorithm on a jet that has been\n        found via clustering. Specifically, given a jet, it is recursively\n        declustered and the softer branch removed until the SoftDrop condition\n        is satisfied:\n\n        $$\n        \\frac{\\min(p_{T,1},p_{T,2})}{p_{T,1}+p_{T,2}} > z_{\\rm cut}\n        \\left(\\frac{\\Delta R_{12}}{R}\\right)^\\beta\n        $$\n\n        where $1$ and $2$ refer to the two PseudoJets declustered at this stage.\n        See the [SoftDrop paper](https://arxiv.org/abs/1402.2657) for a\n        complete description of SoftDrop. If you use this function for your\n        research, please cite [1402.2657](https://doi.org/10.1007/\n        JHEP05(2014)146).\n\n        **Arguments**\n\n        - **jet** : _fastjet.PseudoJet_\n            - A FastJet PseudoJet that has been obtained from a suitable\n            clustering (typically Cambridge/Aachen).\n        - **zcut** : _float_\n            - The $z_{\\rm cut}$ parameter of SoftDrop. Should be between `0`\n            and `1`.\n        - **beta** : _int_ or _float_\n            - The $\\beta$ parameter of SoftDrop.\n        - **R** : _float_\n            - The jet radius to use for the grooming. Only relevant if `beta!=0`.\n\n        **Returns**\n\n        - _fastjet.PseudoJet_\n            - The groomed jet. Note that it will not necessarily have all of\n            the same associated structure as the original jet, but it is\n            suitable for obtaining kinematic quantities, e.g. [$z_g$](/docs/\n            obs/#zg_from_pj).\n        \"\"\"\n\n        parent1, parent2 = fj.PseudoJet(), fj.PseudoJet()\n        if not jet.has_parents(parent1, parent2):\n            return jet\n        \n        pt1, pt2 = parent1.pt(), parent2.pt()\n        z = min(pt1, pt2)/(pt1 + pt2)\n \n        if z >= (zcut if beta == 0 else zcut * (parent1.delta_R(parent2)/R)**beta):\n            return jet\n        else:\n            return softdrop(parent1 if pt1 >= pt2 else parent2, zcut=zcut, beta=beta, R=R)\n", "meta": {"hexsha": "8c229e89c6902947d731e3884c3b67afd225296e", "size": 5753, "ext": "py", "lang": "Python", "max_stars_repo_path": "env/lib/python3.7/site-packages/energyflow/utils/fastjet_utils.py", "max_stars_repo_name": "nickchak21/particledist", "max_stars_repo_head_hexsha": "59b788a894655273ec177a3a6bb4cf9526f8c402", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-01T19:47:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-01T19:47:13.000Z", "max_issues_repo_path": "env/lib/python3.7/site-packages/energyflow/utils/fastjet_utils.py", "max_issues_repo_name": "nickchak21/particledist", "max_issues_repo_head_hexsha": "59b788a894655273ec177a3a6bb4cf9526f8c402", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "env/lib/python3.7/site-packages/energyflow/utils/fastjet_utils.py", "max_forks_repo_name": "nickchak21/particledist", "max_forks_repo_head_hexsha": "59b788a894655273ec177a3a6bb4cf9526f8c402", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4113924051, "max_line_length": 90, "alphanum_fraction": 0.6132452633, "include": true, "reason": "import numpy", "num_tokens": 1455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.18546633537693347}}
{"text": "\nimport ccllib as lib\nimport numpy as np\nfrom warnings import warn\nfrom pyutils import check\n\n# Configuration types\ntransfer_function_types = {\n    'none':             lib.none,\n    'emulator':         lib.emulator,\n    'fitting_function': lib.fitting_function,\n    'eisenstein_hu':    lib.eisenstein_hu,\n    'bbks':             lib.bbks,\n    'boltzmann':        lib.boltzmann,\n    'boltzmann_camb':   lib.boltzmann_camb,\n    'camb':             lib.boltzmann_camb,\n    'boltzmann_class':  lib.boltzmann_class,\n    'class':            lib.boltzmann_class\n}\n\nmatter_power_spectrum_types = {\n    'halo_model':   lib.halo_model,\n    'halomodel':    lib.halo_model,\n    'halofit':      lib.halofit,\n    'linear':       lib.linear\n}\n\nmass_function_types = {\n    'angulo':   lib.angulo,\n    'tinker':   lib.tinker,\n    'tinker10': lib.tinker10,\n    'watson':   lib.watson\n}\n\n# Error types\nerror_types = {\n    lib.CCL_ERROR_MEMORY:       'CCL_ERROR_MEMORY',\n    lib.CCL_ERROR_LINSPACE:     'CCL_ERROR_LINSPACE',\n    lib.CCL_ERROR_INCONSISTENT: 'CCL_ERROR_INCONSISTENT',\n    lib.CCL_ERROR_SPLINE:       'CCL_ERROR_SPLINE',\n    lib.CCL_ERROR_SPLINE_EV:    'CCL_ERROR_SPLINE_EV',\n    lib.CCL_ERROR_INTEG:        'CCL_ERROR_INTEG',\n    lib.CCL_ERROR_ROOT:         'CCL_ERROR_ROOT',\n    lib.CCL_ERROR_CLASS:        'CCL_ERROR_CLASS',\n    lib.CCL_ERROR_COMPUTECHI:   'CCL_ERROR_COMPUTECHI',\n    lib.CCL_ERROR_MF:           'CCL_ERROR_MF',\n    lib.CCL_ERROR_HMF_INTERP:   'CCL_ERROR_HMF_INTERP',\n    lib.CCL_ERROR_PARAMETERS:   'CCL_ERROR_PARAMETERS',\n}\n\n\nclass Parameters(object):\n    \"\"\"The Parameters class contains cosmological parameters.\n\n    \"\"\"\n    \n    def __init__(self, Omega_c=None, Omega_b=None, h=None, A_s=None, n_s=None, \n                 Omega_k=0., Omega_n=0., w0=-1., wa=0., sigma8=None,\n                 z_mg=None, df_mg=None):\n        \"\"\"\n        Creates a set of cosmological parameters.\n\n        Note:\n            Although some arguments default to `None`, they will raise a \n            ValueError inside this function if not specified, so they are not \n            optional.\n        \n        Args:\n            Omega_c (float): Cold dark matter density fraction.\n            Omega_b (float): Baryonic matter density fraction.\n            h (float): Hubble constant divided by 100 km/s/Mpc; unitless.\n            A_s (float): Power spectrum normalization. Optional if sigma8 is \n                         specified.\n            n_s (float): Primordial scalar perturbation spectral index.\n            Omega_k (float, optional): Curvature density fraction. Defaults to 0.\n            Omega_n (float, optional): Massless neutrino density fraction. \n                                       Defaults to 0.\n            w0 (float, optional): First order term of dark energy equation of \n                                  state. Defaults to -1.\n            wa (float, optional): Second order term of dark energy equation of \n                                  state. Defaults to 0.\n            sigma8 (float): Variance of matter density perturbations at 8 Mpc/h\n                            scale. Optional if A_s is specified.\n            df_mg (:obj: array_like): Perturbations to the GR growth rate as a \n                                      function of redshift, Delta f. Used to \n                                      implement simple modified growth \n                                      scenarios.\n            z_mg (:obj: array_like): Array of redshifts corresponding to df_mg.\n\n        \"\"\"\n        # Set current ccl_parameters object to None\n        self.parameters = None\n        \n         # Set nz_mg (no. of redshift bins for modified growth fns.)\n        if z_mg is not None and df_mg is not None:\n            # Get growth array size and do sanity check\n            z_mg = np.atleast_1d(z_mg)\n            df_mg = np.atleast_1d(df_mg)\n            assert z_mg.size == df_mg.size\n            nz_mg = z_mg.size\n        else:\n            # If one or both of the MG growth arrays are set to zero, disable \n            # all of them\n            if z_mg is not None or df_mg is not None:\n                raise ValueError(\"Must specify both z_mg and df_mg.\")\n            z_mg = None\n            df_mg = None\n            nz_mg = -1\n        \n        # Check to make sure specified amplitude parameter is consistent\n        if (A_s is None and sigma8 is None) \\\n        or (A_s is not None and sigma8 is not None):\n            raise ValueError(\"Must set either A_s or sigma8.\")\n        \n        # Set norm_pk to either A_s or sigma8\n        norm_pk = A_s if A_s is not None else sigma8\n        \n        # The C library decides whether A_s or sigma8 was the input parameter \n        # based on value, so we need to make sure this is consistent too\n        if norm_pk >= 1e-5 and A_s is not None:\n            raise ValueError(\"A_s must be less than 1e-5.\")\n            \n        if norm_pk < 1e-5 and sigma8 is not None:\n            raise ValueError(\"sigma8 must be greater than 1e-5.\")\n        \n        # Check if any compulsory parameters are not set\n        compul = [Omega_c, Omega_b, Omega_k, Omega_n, w0, wa, h, norm_pk, n_s]\n        names = ['Omega_c', 'Omega_b', 'Omega_k', 'Omega_n', 'w0', 'wa', \n                 'h', 'norm_pk', 'n_s']\n        for nm, item in zip(names, compul):\n            if item is None:\n                raise ValueError(\"Necessary parameter '%s' was not set \"\n                                 \"(or set to None).\" % nm)\n        \n        # Create new instance of ccl_parameters object\n        if nz_mg == -1:\n            # Create ccl_parameters without modified growth\n            self.parameters = lib.parameters_create(\n                                    Omega_c, Omega_b, Omega_k, Omega_n, \n                                    w0, wa, h, norm_pk, n_s, \n                                    -1, None, None)\n        else:\n            # Create ccl_parameters with modified growth arrays\n            self.parameters = lib.parameters_create_vec(\n                                    Omega_c, Omega_b, Omega_k, Omega_n, \n                                    w0, wa, h, norm_pk, n_s, \n                                    z_mg, df_mg)\n    \n    def __getitem__(self, key):\n        \"\"\"Access parameter values by name.\n\n        \"\"\"\n        try:\n            val = getattr(self.parameters, key)\n        except AttributeError:\n            raise KeyError(\"Parameter '%s' not recognized.\" % key)\n        return val\n    \n    def __setitem__(self, key, val):\n        \"\"\"Set parameter values by name.\n\n        \"\"\"\n        raise NotImplementedError(\"Parameters objects are immutable; create a \"\n                                  \"new Parameters() instance instead.\")\n        \n        try:\n            # First check if the key already exists (otherwise the parameter \n            # would be silently added to the ccl_parameters class instance)\n            getattr(self.parameters, key)\n        except AttributeError:\n            raise KeyError(\"Parameter '%s' not recognized.\" % key)\n        \n        # Set value of parameter\n        setattr(self.parameters, key, val)\n        # TODO: Should update/replace CCL objects appropriately\n    \n    def __str__(self):\n        \"\"\"Output the parameters that were set, and their values.\n\n        \"\"\"\n        params = ['Omega_c', 'Omega_b', 'Omega_m', 'Omega_n', 'Omega_k', \n                  'w0', 'wa', 'H0', 'h', 'A_s', 'n_s', 'Omega_g', 'T_CMB', \n                  'sigma_8', 'Omega_l', 'z_star', 'has_mgrowth']\n  \n        vals = [\"%15s: %s\" % (p, getattr(self.parameters, p)) for p in params]\n        string = \"Parameters\\n----------\\n\"\n        string += \"\\n\".join(vals)\n        return string\n\n\nclass Cosmology(object):\n    \"\"\"Wrapper for the ccl_cosmology object.\n\n    Includes cosmological parameters and cached data.\n\n    \"\"\"\n    \n    def __init__(self, \n                 params=None, config=None,\n                 Omega_c=None, Omega_b=None, h=None, A_s=None, n_s=None, \n                 Omega_k=0., Omega_n=0., w0=-1., wa=0., sigma8=None,\n                 z_mg=None, df_mg=None, \n                 transfer_function='boltzmann_class',\n                 matter_power_spectrum='halofit',\n                 mass_function='tinker'):\n        \"\"\"Creates a wrapper for ccl_cosmology.\n\n        TODO: enumerate transfer_function and \n        matter_power_spectrum options.\n\n        Args:\n            params (:obj:`Parameters`): Cosmological parameters object.\n            config (:obj:`ccl_configuration`, optional): Configuration for how \n            to use CCL. Takes precident over any other passed in configuration. \n            Defaults to None.\n            transfer_function (:obj:`str`, optional): The transfer function to \n            use. Defaults to `boltzmann_class`.\n            matter_power_spectrum (:obj:`str`, optional): The matter power \n            spectrum to use. Defaults to `halofit`.\n            mass_function (:obj:`str`, optional): The mass function to use. \n            Defaults to `tinker` (2010).\n\n        \"\"\"\n        \n        # Use either input cosmology parameters or Parameters() object\n        if params is None:\n            # Create new Parameters object\n            params = Parameters(Omega_c=Omega_c, Omega_b=Omega_b, h=h, A_s=A_s, \n                                n_s=n_s, Omega_k=Omega_k, Omega_n=Omega_n, \n                                w0=w0, wa=wa, sigma8=sigma8, z_mg=z_mg, \n                                df_mg=df_mg)\n            self.params = params\n            params = params.parameters # We only need the ccl_parameters object\n        elif isinstance(params, lib.parameters):\n            # Raise an error if ccl_parameters given directly\n            raise TypeError(\"Must pass a Parameters() object, not ccl_parameters.\")\n        elif isinstance(params, Parameters):\n            # Parameters object given directly\n            self.params = params\n            \n            # Warn if any cosmological parameters were specified at the same \n            # time as a Parameters() object; they will be ignored\n            argtest = [Omega_c==None, Omega_b==None, h==None, A_s==None, \n                       n_s==None, Omega_k==0., Omega_n==0., w0==-1., wa==0., \n                       sigma8==None, z_mg==None, df_mg==None]\n            \n            if not all(arg == True for arg in argtest):\n                warn(\"Cosmological parameter kwargs are ignored if 'params' is \"\n                     \"not None\", UserWarning)\n        else:\n            raise TypeError(\"'params' is not a valid Parameters object.\")\n        \n        # Check that the ccl_configuration-related arguments are valid\n        if config is not None:\n            # User passed a ccl_configuration object; ignore other arguments \n            # and use this\n            \n            # Check that input object is of the correct type\n            if not isinstance(config, lib.configuration):\n                raise TypeError(\"'config' is not a valid ccl_configuration \"\n                                \"object.\")\n            \n            # Store ccl_configuration for later access\n            self.configuration = config\n            \n        else:\n            # Construct a new ccl_configuration object from kwargs\n            \n            # Check validity of configuration-related arguments\n            if transfer_function not in transfer_function_types.keys():\n                raise ValueError( \"'%s' is not a valid transfer_function type. \"\n                                  \"Available options are: %s\" \\\n                                 % (transfer_function, \n                                    transfer_function_types.keys()) )\n            if matter_power_spectrum not in matter_power_spectrum_types.keys():\n                raise ValueError( \"'%s' is not a valid matter_power_spectrum \"\n                                  \"type. Available options are: %s\" \\\n                                 % (matter_power_spectrum, \n                                    matter_power_spectrum_types.keys()) )\n            if mass_function not in mass_function_types.keys():\n                raise ValueError( \"'%s' is not a valid mass_function type. \"\n                                  \"Available options are: %s\" \\\n                                 % (mass_function, \n                                    mass_function_types.keys()) )\n            \n            # Assign values to new ccl_configuration object\n            config = lib.configuration()\n            \n            config.transfer_function_method = \\\n                            transfer_function_types[transfer_function]\n            config.matter_power_spectrum_method = \\\n                            matter_power_spectrum_types[matter_power_spectrum]\n            config.mass_function_method = \\\n                            mass_function_types[mass_function]\n            \n            # Store ccl_configuration for later access\n            self.configuration = config\n        \n        # Create new ccl_cosmology instance\n        self.cosmo = lib.cosmology_create(self.params.parameters, config)\n        \n        # Check status\n        if self.cosmo.status != 0:\n            raise RuntimeError(\"(%d): %s\" \\\n                               % (self.cosmo.status, self.cosmo.status_message))\n    \n    def __del__(self):\n        \"\"\"Free the ccl_cosmology instance that this Cosmology object is managing.\n\n        \"\"\"\n        lib.cosmology_free(self.cosmo)\n    \n    def __str__(self):\n        \"\"\"Output the cosmological parameters that were set, and their values,\n        as well as the status of precomputed quantities and the internal CCL\n        status.\n\n        \"\"\"\n        # String of cosmo parameters, from self.params (Parameters object)\n        param_str = self.params.__str__()\n        \n        # String containing precomputation statuses\n        precomp_stats = [\n            ('has_distances', self.has_distances()),\n            ('has_growth',    self.has_growth()),\n            ('has_power',     self.has_power()),\n            ('has_sigma',     self.has_sigma()),\n            ]\n        precomp_stat = [\"%15s: %s\" % stat for stat in precomp_stats]\n        precomp_str = \"\\n\".join(precomp_stat)\n        \n        # String from internal CCL status\n        status_str = self.status()\n        \n        # Return composite string\n        string = param_str\n        string += \"\\n\\nPrecomputed data\\n----------------\\n\"\n        string += precomp_str\n        string += \"\\n\\nStatus\\n------\\n\"\n        string += status_str\n        return string\n    \n    def __getitem__(self, key):\n        \"\"\"Access cosmological parameter values by name.\n\n        \"\"\"\n        return self.params.__getitem__(key)\n    \n    def compute_distances(self):\n        \"\"\"Interfaces with src/compute_background.c: ccl_cosmology_compute_distances().\n        Sets up the splines for the distances.\n\n        \"\"\"\n        status = 0\n        status = lib.cosmology_compute_distances(self.cosmo, status)\n        check(status)\n    \n    def compute_growth(self):\n        \"\"\"Interfaces with src/ccl_background.c: ccl_cosmology_compute_growth().\n        Sets up the splines for the growth function.\n\n        \"\"\"\n        status = 0\n        status = lib.cosmology_compute_growth(self.cosmo, status)\n        check(status)\n    \n    def compute_power(self):\n        \"\"\"Interfaces with src/ccl_power.c: ccl_cosmology_compute_power().\n        Sets up the splines for the power spectrum.\n\n        \"\"\"\n        status = 0\n        status = lib.cosmology_compute_power(self.cosmo, status)\n        check(status)\n    \n    def has_distances(self):\n        \"\"\"Checks if the distances have been precomputed.\n\n        Returns:\n            True if precomputed, False otherwise.\n\n        \"\"\"\n        return bool(self.cosmo.computed_distances)\n    \n    def has_growth(self):\n        \"\"\"Checks if the growth function has been precomputed.\n\n        Returns:\n            True if precomputed, False otherwise.\n\n        \"\"\"\n        return bool(self.cosmo.computed_growth)\n    \n    def has_power(self):\n        \"\"\"Checks if the power spectra have been precomputed.\n\n        Returns:\n            True if precomputed, False otherwise.\n\n        \"\"\"\n        return bool(self.cosmo.computed_power)\n    \n    def has_sigma(self):\n        \"\"\"Checks if sigma8 has been computed.\n\n        Returns:\n            True if precomputed, False otherwise.\n\n        \"\"\"\n        return bool(self.cosmo.computed_sigma)\n    \n    def status(self):\n        \"\"\"Get error status of the ccl_cosmology object.\n\n        Note: error status is all currently under development.\n\n        Returns:\n            :obj:`str` containing the status message.\n\n        \"\"\"\n        # Get status ID string if one exists\n        if self.cosmo.status in error_types.keys():\n            status = error_types[self.cosmo.status]\n        else:\n            status = self.cosmo.status\n        \n        # Get status message\n        msg = self.cosmo.status_message\n        \n        # Return status information\n        return \"status(%s): %s\" % (status, msg)\n        \n", "meta": {"hexsha": "83b46d650bcbf643e9a114de2c746d7d4b420727", "size": 16933, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyccl/core.py", "max_stars_repo_name": "WeikangLin/CCL", "max_stars_repo_head_hexsha": "d22490f1aab27b3b0d8ab22272d13a649e47c6f3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyccl/core.py", "max_issues_repo_name": "WeikangLin/CCL", "max_issues_repo_head_hexsha": "d22490f1aab27b3b0d8ab22272d13a649e47c6f3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyccl/core.py", "max_forks_repo_name": "WeikangLin/CCL", "max_forks_repo_head_hexsha": "d22490f1aab27b3b0d8ab22272d13a649e47c6f3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1062355658, "max_line_length": 87, "alphanum_fraction": 0.5609756098, "include": true, "reason": "import numpy", "num_tokens": 3679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.185466331660736}}
{"text": "# Copyright Ryan-Rhys Griffiths and Aditya Raymond Thawani 2020\n# Author: Ryan-Rhys Griffiths\n\"\"\"\nScript for comparing against human performance on a set of 5 molecules with Tanimoto MOGP.\n\"\"\"\n\nimport argparse\n\nimport gpflow\nfrom gpflow.ci_utils import ci_niter\nfrom gpflow.mean_functions import Constant\nfrom gpflow.utilities import print_summary\nimport numpy as np\nfrom sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error\n\nfrom data_utils import transform_data, TaskDataLoader, featurise_mols\nfrom kernels import Tanimoto\n\n\ndef main(path, representation):\n    \"\"\"\n    :param path: str specifying path to dataset.\n    :param representation: str specifying the molecular representation. One of ['fingerprints, 'fragments', 'fragprints']\n    \"\"\"\n\n    task = 'e_iso_pi'  # task always e_iso_pi with human performance comparison\n    data_loader = TaskDataLoader(task, path)\n    smiles_list, y = data_loader.load_property_data()\n    X = featurise_mols(smiles_list, representation)\n\n    # 5 test molecules\n\n    test_smiles = ['BrC1=CC=C(/N=N/C2=CC=CC=C2)C=C1',\n                   'O=[N+]([O-])C1=CC=C(/N=N/C2=CC=CC=C2)C=C1',\n                   'CC(C=C1)=CC=C1/N=N/C2=CC=C(N(C)C)C=C2',\n                   'BrC1=CC([N+]([O-])=O)=CC([N+]([O-])=O)=C1/N=N/C2=CC([H])=C(C=C2[H])N(CC)CC',\n                   'ClC%11=CC([N+]([O-])=O)=CC(C#N)=C%11/N=N/C%12=CC([H])=C(C=C%12OC)N(CC)CC']\n\n    # and their indices in the loaded data\n    test_smiles_indices = [116, 131, 168, 221, 229]\n\n    X_train = np.delete(X, np.array(test_smiles_indices), axis=0)\n    y_train = np.delete(y, np.array(test_smiles_indices))\n    X_test = X[[116, 131, 168, 221, 229]]\n\n    # experimental wavelength values in EtOH. Main csv file has 400nm instead of 407nm because measurement was\n    # under a different solvent\n    y_test = y[[116, 131, 168, 221, 229]]\n    y_test[2] = 407.\n\n    y_train = y_train.reshape(-1, 1)\n    y_test = y_test.reshape(-1, 1)\n\n    # #  We standardise the outputs but leave the inputs unchanged\n    #\n    # _, y_train, _, y_test, y_scaler = transform_data(X_train, y_train, X_test, y_test)\n\n    X_train = X_train.astype(np.float64)\n    X_test = X_test.astype(np.float64)\n\n    data_loader_z_iso_pi = TaskDataLoader('z_iso_pi', path)\n    data_loader_e_iso_n = TaskDataLoader('e_iso_n', path)\n    data_loader_z_iso_n = TaskDataLoader('z_iso_n', path)\n\n    smiles_list_z_iso_pi, y_z_iso_pi = data_loader_z_iso_pi.load_property_data()\n    smiles_list_e_iso_n, y_e_iso_n = data_loader_e_iso_n.load_property_data()\n    smiles_list_z_iso_n, y_z_iso_n = data_loader_z_iso_n.load_property_data()\n\n    y_z_iso_pi = y_z_iso_pi.reshape(-1, 1)\n    y_e_iso_n = y_e_iso_n.reshape(-1, 1)\n    y_z_iso_n = y_z_iso_n.reshape(-1, 1)\n\n    X_z_iso_pi = featurise_mols(smiles_list_z_iso_pi, representation)\n    X_e_iso_n = featurise_mols(smiles_list_e_iso_n, representation)\n    X_z_iso_n = featurise_mols(smiles_list_z_iso_n, representation)\n\n    output_dim = 4  # Number of outputs\n    rank = 1  # Rank of W\n    feature_dim = len(X_train[0, :])\n\n    tanimoto_active_dims = [i for i in range(feature_dim)]  # active dims for Tanimoto base kernel.\n\n    # We define the Gaussian Process Regression Model using the Tanimoto kernel\n\n    m = None\n\n    def objective_closure():\n        return -m.log_marginal_likelihood()\n\n    # Augment the input with zeroes, ones, twos, threes to indicate the required output dimension\n    X_augmented = np.vstack((np.append(X_train, np.zeros((len(X_train), 1)), axis=1),\n                             np.append(X_z_iso_pi, np.ones((len(X_z_iso_pi), 1)), axis=1),\n                             np.append(X_e_iso_n, np.ones((len(X_e_iso_n), 1)) * 2, axis=1),\n                             np.append(X_z_iso_n, np.ones((len(X_z_iso_n), 1)) * 3, axis=1)))\n\n    X_test = np.append(X_test, np.zeros((len(X_test), 1)), axis=1)\n    X_train = np.append(X_train, np.zeros((len(X_train), 1)), axis=1)\n\n    # Augment the Y data with zeroes, ones, twos and threes that specify a likelihood from the list of likelihoods\n    Y_augmented = np.vstack((np.hstack((y_train, np.zeros_like(y_train))),\n                             np.hstack((y_z_iso_pi, np.ones_like(y_z_iso_pi))),\n                             np.hstack((y_e_iso_n, np.ones_like(y_e_iso_n) * 2)),\n                             np.hstack((y_z_iso_n, np.ones_like(y_z_iso_n) * 3))))\n\n    y_test = np.hstack((y_test, np.zeros_like(y_test)))\n\n    # Base kernel\n    k = Tanimoto(active_dims=tanimoto_active_dims)\n    # set_trainable(k.variance, False)\n\n    # Coregion kernel\n    coreg = gpflow.kernels.Coregion(output_dim=output_dim, rank=rank, active_dims=[feature_dim])\n\n    # Create product kernel\n    kern = k * coreg\n\n    # This likelihood switches between Gaussian noise with different variances for each f_i:\n    lik = gpflow.likelihoods.SwitchedLikelihood([gpflow.likelihoods.Gaussian(), gpflow.likelihoods.Gaussian(),\n                                                 gpflow.likelihoods.Gaussian(), gpflow.likelihoods.Gaussian()])\n\n    # now build the GP model as normal\n    m = gpflow.models.VGP((X_augmented, Y_augmented), mean_function=Constant(np.mean(y_train[:, 0])), kernel=kern,\n                          likelihood=lik)\n\n    # fit the covariance function parameters\n    maxiter = ci_niter(1000)\n    gpflow.optimizers.Scipy().minimize(m.training_loss, m.trainable_variables, options=dict(maxiter=maxiter),\n                                       method=\"L-BFGS-B\", )\n    print_summary(m)\n\n    # mean and variance GP prediction\n\n    y_pred, y_var = m.predict_f(X_test)\n\n    # Output Standardised RMSE and RMSE on Train Set\n\n    y_pred_train, _ = m.predict_f(X_train)\n    train_rmse_stan = np.sqrt(mean_squared_error(y_train, y_pred_train))\n    train_rmse = np.sqrt(mean_squared_error(y_train, y_pred_train))\n    print(\"\\nStandardised Train RMSE: {:.3f}\".format(train_rmse_stan))\n    print(\"Train RMSE: {:.3f}\".format(train_rmse))\n\n    r2 = r2_score(y_test[:, 0], y_pred)\n    rmse = np.sqrt(mean_squared_error(y_test[:, 0], y_pred))\n    mae = mean_absolute_error(y_test[:, 0], y_pred)\n    per_molecule = np.diag(abs(y_pred - y_test[:, 0]))\n\n    print(\"\\n Averaged test statistics are\")\n    print(\"\\nR^2: {:.3f}\".format(r2))\n    print(\"RMSE: {:.3f}\".format(rmse))\n    print(\"MAE: {:.3f}\".format(mae))\n    print(\"\\nAbsolute error per molecule is {} \".format(per_molecule))\n\n\nif __name__ == '__main__':\n\n    parser = argparse.ArgumentParser()\n\n    parser.add_argument('-p', '--path', type=str, default='../dataset/photoswitches.csv',\n                        help='Path to the photoswitches.csv file.')\n    parser.add_argument('-r', '--representation', type=str, default='fragprints',\n                        help='str specifying the molecular representation. '\n                             'One of [fingerprints, fragments, fragprints].')\n\n    args = parser.parse_args()\n\n    main(args.path, args.representation)", "meta": {"hexsha": "2a094a04b4a1dd9d692b6e7dfdb142b542cda7c5", "size": 6874, "ext": "py", "lang": "Python", "max_stars_repo_path": "human_comparison/human_performance_comparison_MOGP.py", "max_stars_repo_name": "Ryan-Rhys/Photoswitches", "max_stars_repo_head_hexsha": "08a057bd78d669dd149e82f2e8f2de847b7f58d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 53, "max_stars_repo_stars_event_min_datetime": "2020-05-25T13:02:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T07:59:11.000Z", "max_issues_repo_path": "human_comparison/human_performance_comparison_MOGP.py", "max_issues_repo_name": "Ryan-Rhys/The-Photoswitch-Dataset", "max_issues_repo_head_hexsha": "3ab16fd4e35fad58f5de46192fe6cddcded2f0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "human_comparison/human_performance_comparison_MOGP.py", "max_forks_repo_name": "Ryan-Rhys/The-Photoswitch-Dataset", "max_forks_repo_head_hexsha": "3ab16fd4e35fad58f5de46192fe6cddcded2f0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-07-24T03:23:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T16:13:16.000Z", "avg_line_length": 41.1616766467, "max_line_length": 121, "alphanum_fraction": 0.6630782659, "include": true, "reason": "import numpy", "num_tokens": 1901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.34158250614097546, "lm_q1q2_score": 0.18543260075798237}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE\n'''\nThis module provides the framework for the creation of the photometric likelihoods\nused in the cross-matching of the two catalogues.\n'''\n\nimport os\nimport sys\nimport numpy as np\n\nfrom .misc_functions import map_large_index_to_small_index, _load_single_sky_slice\nfrom .misc_functions_fortran import misc_functions_fortran as mff\nfrom .photometric_likelihood_fortran import photometric_likelihood_fortran as plf\n\n__all__ = ['compute_photometric_likelihoods']\n\n\ndef compute_photometric_likelihoods(joint_folder_path, a_cat_folder_path, b_cat_folder_path,\n                                    afilts, bfilts, mem_chunk_num, cf_points, cf_areas,\n                                    include_phot_like, use_phot_priors, bright_frac=None,\n                                    field_frac=None):\n    '''\n    Derives the photometric likelihoods and priors for use in the catalogue\n    cross-match process.\n\n    Parameters\n    ----------\n    joint_folder_path : string\n        The folder where all folders and files created during the cross-match\n        process are stored.\n    a_cat_folder_path : string\n        The folder where the input data for catalogue \"a\" are located.\n    b_cat_folder_path : string\n        The location of catalogue \"b\"'s input data.\n    afilts : list of string\n        A list of the filters in catalogue \"a\"'s photometric data file.\n    bfilts : list of string\n        List of catalogue \"b\"'s filters.\n    mem_chunk_num : integer\n        Fraction of input datasets to load at once, in the case of data larger\n        than the memory of the system.\n    cf_points : numpy.ndarray\n        The on-sky coordinates that define the locations of each small\n        set of sources to be used to derive the relative match and non-match\n        photometric likelihoods.\n    cf_areas : numpy.ndarray\n        The areas of closest on-sky separation surrounding each point in\n        ``cf_points``, used to normalise numbers of sources to sky densities.\n    include_phot_like : boolean\n        Flag to indicate whether to derive astrophysical likelihoods ``c`` and\n        ``f``, based on the common coevality of sources of given magnitudes.\n    use_phot_priors : boolean\n        Indicator as to whether to use astrophysical priors, based on the common\n        number of likely matches and non-matches in each ``cf_points`` area, or\n        use naive, asymmetric priors solely based on number density of sources.\n    bright_frac : float, optional\n        Expected fraction of sources inside the \"bright\" error circles used to\n        construct the counterpart distribution, to correct for missing numbers.\n        If ``include_phot_like`` or ``use_phot_prior`` is True then this must\n        be supplied, otherwise it can be omitted.\n    field_frac : float, optional\n        Expected fraction of sources inside the \"field\" error circles used to\n        construct the counterpart distribution, to correct for missing numbers.\n        If ``include_phot_like`` or ``use_phot_prior`` is True then this must\n        be supplied, otherwise it can be omitted.\n    '''\n\n    if bright_frac is None and (include_phot_like or use_phot_priors):\n        raise ValueError(\"bright_frac must be supplied if include_phot_like or use_phot_priors \"\n                         \"is set to True. Please supply an appropriate fraction.\")\n    if field_frac is None and (include_phot_like or use_phot_priors):\n        raise ValueError(\"field_frac must be supplied if include_phot_like or use_phot_priors \"\n                         \"is set to True. Please supply an appropriate fraction.\")\n\n    print(\"Creating c(m, m) and f(m)...\")\n\n    len_a = len(np.load('{}/con_cat_astro.npy'.format(a_cat_folder_path), mmap_mode='r'))\n    len_b = len(np.load('{}/con_cat_astro.npy'.format(b_cat_folder_path), mmap_mode='r'))\n\n    print(\"Distributing sources into sky slices...\")\n    sys.stdout.flush()\n\n    a_sky_inds = distribute_sky_indices(joint_folder_path, a_cat_folder_path, 'a', mem_chunk_num,\n                                        cf_points)\n    b_sky_inds = distribute_sky_indices(joint_folder_path, b_cat_folder_path, 'b', mem_chunk_num,\n                                        cf_points)\n\n    print(\"Making bins...\")\n    sys.stdout.flush()\n\n    abinlengths, abinsarray, longabinlen = create_magnitude_bins(\n        cf_points, afilts, mem_chunk_num, joint_folder_path, a_cat_folder_path, 'a', a_sky_inds,\n        include_phot_like or use_phot_priors)\n    bbinlengths, bbinsarray, longbbinlen = create_magnitude_bins(\n        cf_points, bfilts, mem_chunk_num, joint_folder_path, b_cat_folder_path, 'b', b_sky_inds,\n        include_phot_like or use_phot_priors)\n\n    print(\"Calculating PDFs...\")\n    sys.stdout.flush()\n\n    c_priors = np.lib.format.open_memmap(\n        '{}/phot_like/c_priors.npy'.format(joint_folder_path), mode='w+', dtype=float,\n        shape=(len(bfilts), len(afilts), len(cf_points)), fortran_order=True)\n    fa_priors = np.lib.format.open_memmap(\n        '{}/phot_like/fa_priors.npy'.format(joint_folder_path), mode='w+', dtype=float,\n        shape=(len(bfilts), len(afilts), len(cf_points)), fortran_order=True)\n    fb_priors = np.lib.format.open_memmap(\n        '{}/phot_like/fb_priors.npy'.format(joint_folder_path), mode='w+', dtype=float,\n        shape=(len(bfilts), len(afilts), len(cf_points)), fortran_order=True)\n    c_array = np.lib.format.open_memmap(\n        '{}/phot_like/c_array.npy'.format(joint_folder_path), mode='w+', dtype=float,\n        shape=(longbbinlen-1, longabinlen-1, len(bfilts), len(afilts),\n               len(cf_points)), fortran_order=True)\n    fa_array = np.lib.format.open_memmap(\n        '{}/phot_like/fa_array.npy'.format(joint_folder_path), mode='w+', dtype=float,\n        shape=(longabinlen-1, len(bfilts), len(afilts), len(cf_points)), fortran_order=True)\n    fb_array = np.lib.format.open_memmap(\n        '{}/phot_like/fb_array.npy'.format(joint_folder_path), mode='w+', dtype=float,\n        shape=(longbbinlen-1, len(bfilts), len(afilts), len(cf_points)), fortran_order=True)\n\n    # Within each loop, since we've already assigned all sources to have a closest\n    # c/f sky position pointing to be assigned to, we simply slice within the _load\n    # functions on ID, and for the initial mem_chunk_num stepping load in the range\n    # [m_, m_+mem_chunk_num).\n    for m_ in range(0, len(cf_points), mem_chunk_num):\n        a_multi_return = _load_multiple_sky_slice(joint_folder_path, 'a', m_, m_+mem_chunk_num,\n                                                  a_cat_folder_path, a_sky_inds,\n                                                  include_phot_like or use_phot_priors)\n        if include_phot_like or use_phot_priors:\n            (a_small_photo, a_sky_ind_small, a_small_astro, a_blen_small, a_inds_small,\n             a_size_small) = a_multi_return\n        else:\n            a_small_photo, a_sky_ind_small = a_multi_return\n        del a_multi_return\n\n        b_multi_return = _load_multiple_sky_slice(joint_folder_path, 'b', m_, m_+mem_chunk_num,\n                                                  b_cat_folder_path, b_sky_inds,\n                                                  include_phot_like or use_phot_priors)\n        if include_phot_like or use_phot_priors:\n            (b_small_photo, b_sky_ind_small, b_small_astro, b_blen_small, b_inds_small,\n             b_size_small) = b_multi_return\n            del b_blen_small\n        else:\n            b_small_photo, b_sky_ind_small = b_multi_return\n        del b_multi_return\n\n        for m in range(m_, min(len(cf_points), m_+mem_chunk_num)):\n            area = cf_areas[m]\n            a_sky_cut = _load_single_sky_slice(\n                joint_folder_path, 'a', m, a_sky_ind_small)\n            a_photo_cut = a_small_photo[a_sky_cut]\n            if include_phot_like or use_phot_priors:\n                a_astro_cut, a_blen_cut, a_inds_cut, a_size_cut = (\n                    a_small_astro[a_sky_cut], a_blen_small[a_sky_cut], a_inds_small[:, a_sky_cut],\n                    a_size_small[a_sky_cut])\n\n            b_sky_cut = _load_single_sky_slice(\n                joint_folder_path, 'b', m, b_sky_ind_small)\n            b_photo_cut = b_small_photo[b_sky_cut]\n            if include_phot_like or use_phot_priors:\n                b_astro_cut, b_inds_cut, b_size_cut = (\n                    b_small_astro[b_sky_cut], b_inds_small[:, b_sky_cut], b_size_small[b_sky_cut])\n\n                # Return the overall to subarray mapping of *_inds_cut, as well\n                # as the unique values of *_inds_cut, for use in creating the\n                # opposing view slices into the other catalogue, for each\n                # catalogue. Note that the lengths are swapped in the two calls,\n                # as the a_inds map into length of catalogue \"b\" and vice versa.\n                a_inds_map, a_inds_cut_unique = map_large_index_to_small_index(\n                    a_inds_cut, len_b, '{}/phot_like'.format(joint_folder_path))\n                b_inds_map, b_inds_cut_unique = map_large_index_to_small_index(\n                    b_inds_cut, len_a, '{}/phot_like'.format(joint_folder_path))\n\n                # Combined with b_inds_map, this subarray of the catalogue gives\n                # an array that has every \"a\" source that overlaps the \"b\"\n                # subarray objects. Note we use b_inds_cut_unique for catalogue\n                # \"a\" sources.\n                a_astro_ind = np.load('{}/con_cat_astro.npy'.format(a_cat_folder_path),\n                                      mmap_mode='r')[b_inds_cut_unique]\n                b_astro_ind = np.load('{}/con_cat_astro.npy'.format(b_cat_folder_path),\n                                      mmap_mode='r')[a_inds_cut_unique]\n                a_photo_ind = np.load('{}/con_cat_photo.npy'.format(a_cat_folder_path),\n                                      mmap_mode='r')[b_inds_cut_unique]\n                b_photo_ind = np.load('{}/con_cat_photo.npy'.format(b_cat_folder_path),\n                                      mmap_mode='r')[a_inds_cut_unique]\n                a_flen_ind = np.load('{}/group/aflen.npy'.format(joint_folder_path),\n                                     mmap_mode='r')[b_inds_cut_unique]\n                b_flen_ind = np.load('{}/group/bflen.npy'.format(joint_folder_path),\n                                     mmap_mode='r')[a_inds_cut_unique]\n\n            for i in range(0, len(afilts)):\n                if not include_phot_like and not use_phot_priors:\n                    a_num_photo_cut = np.sum(~np.isnan(a_photo_cut[:, i]))\n                    Na = a_num_photo_cut / area\n                else:\n                    a_bins = abinsarray[:abinlengths[i, m], i, m]\n                    a_mag = a_photo_cut[:, i]\n                    a_flags = ~np.isnan(a_mag)\n                    a_flags_ind = ~np.isnan(a_photo_ind[:, i])\n                for j in range(0, len(bfilts)):\n                    if not include_phot_like and not use_phot_priors:\n                        b_num_photo_cut = np.sum(~np.isnan(b_photo_cut[:, j]))\n                        Nb = b_num_photo_cut / area\n                        # Without using photometric-based priors, all we can\n                        # do is set the prior on one catalogue to 0.5 -- that\n                        # is, equal chance of match or non-match; for this we\n                        # use the less dense of the two catalogues as our\n                        # \"one-sided\" match. Then, accordingly, we update the\n                        # \"field\" source density of the more dense catalogue\n                        # with its corresponding density, based on the input\n                        # density and the counterpart density calculated.\n                        c_prior = min(Na, Nb) / 2\n                        fa_prior = Na - c_prior\n                        fb_prior = Nb - c_prior\n                        # To fake no photometric likelihoods, simply set all\n                        # values to one, to cancel in the ratio later.\n                        c_like, fa_like, fb_like = 1-1e-10, 1-1e-10, 1-1e-10\n                    else:\n                        b_bins = bbinsarray[:bbinlengths[j, m], j, m]\n                        b_mag = b_photo_cut[:, j]\n                        b_flags = ~np.isnan(b_mag)\n                        b_mag_ind = b_photo_ind[:, j]\n                        b_flags_ind = ~np.isnan(b_mag_ind)\n\n                        c_prior, c_like, fa_prior, fa_like, fb_prior, fb_like = create_c_and_f(\n                            a_astro_cut, b_astro_cut, a_mag, b_mag, a_inds_map, a_size_cut,\n                            b_inds_map, b_size_cut, a_blen_cut, a_bins, b_bins, bright_frac,\n                            field_frac, a_flags, b_flags, a_astro_ind, b_astro_ind, a_flen_ind,\n                            b_flen_ind, a_flags_ind, b_flags_ind, b_mag_ind, area)\n                    if use_phot_priors and not include_phot_like:\n                        # If we only used the create_c_and_f routine to derive\n                        # priors, then quickly update likelihoods here.\n                        c_like, fa_like, fb_like = 1-1e-10, 1-1e-10, 1-1e-10\n\n                    # Have to add a very small \"fire extinguisher\" value to all\n                    # likelihoods and priors, to avoid ever having exactly zero\n                    # value in either, which would mean all island permutations\n                    # were rejected.\n                    c_priors[j, i, m] = c_prior + 1e-10\n                    fa_priors[j, i, m] = fa_prior + 1e-10\n                    fb_priors[j, i, m] = fb_prior + 1e-10\n                    c_array[:bbinlengths[j, m]-1,\n                            :abinlengths[i, m]-1, j, i, m] = c_like + 1e-10\n                    fa_array[:abinlengths[i, m]-1, j, i, m] = fa_like + 1e-10\n                    fb_array[:bbinlengths[j, m]-1, j, i, m] = fb_like + 1e-10\n\n    os.system('rm {}/a_small_sky_slice.npy'.format(joint_folder_path))\n    os.system('rm {}/b_small_sky_slice.npy'.format(joint_folder_path))\n\n    # *binsarray is passed back from create_magnitude_bins as a memmapped array,\n    # but *binlengths is just a numpy array, so quickly save these before returning.\n    np.save('{}/phot_like/abinlengths.npy'.format(joint_folder_path), abinlengths)\n    np.save('{}/phot_like/bbinlengths.npy'.format(joint_folder_path), bbinlengths)\n\n    return\n\n\ndef distribute_sky_indices(joint_folder_path, cat_folder, name, mem_chunk_num, cf_points):\n    '''\n    Function to calculate the nearest on-sky photometric likelihood point for\n    each catalogue source.\n\n    Parameters\n    ----------\n    joint_folder_path : string\n        Top-level folder path for the common files created during the cross-match\n        process.\n    cat_folder : string\n        The location of a given catalogue's input data files.\n    name : string\n        Representation of whether we are calculating sky indices for catalogue\n        \"a\", or catalogue \"b\".\n    mem_chunk_num : integer\n        Number of sub-sets to break larger data files down to, to preserve memory.\n    cf_points : numpy.ndarray\n        The two-point sky coordinates for each point to be used as a central\n        point of a small sky area, for calculating \"counterpart\" and \"field\"\n        photometric likelihoods.\n\n    Returns\n    -------\n    sky_inds : numpy.ndarray\n        The indices, matching ``cf_points``, of the closest sky position for each\n        source in this catalogue.\n    '''\n    n_sources = len(np.load('{}/con_cat_astro.npy'.format(cat_folder), mmap_mode='r'))\n    sky_inds = np.lib.format.open_memmap('{}/phot_like/{}_sky_inds.npy'.format(\n                                         joint_folder_path, name), mode='w+', dtype=int,\n                                         shape=(n_sources,), fortran_order=True)\n    for cnum in range(0, mem_chunk_num):\n        lowind = np.floor(n_sources*cnum/mem_chunk_num).astype(int)\n        highind = np.floor(n_sources*(cnum+1)/mem_chunk_num).astype(int)\n        a = np.load('{}/con_cat_astro.npy'.format(cat_folder), mmap_mode='r')[lowind:highind]\n        sky_inds[lowind:highind] = mff.find_nearest_point(a[:, 0], a[:, 1],\n                                                          cf_points[:, 0], cf_points[:, 1])\n\n    return sky_inds\n\n\ndef create_magnitude_bins(cf_points, filts, mem_chunk_num, joint_folder_path,\n                          cat_folder_path, cat_type, sky_inds, load_extra_arrays):\n    '''\n    Creates the N-dimensional arrays of single-band photometric bins, and\n    corresponding array lengths.\n\n    Parameters\n    ----------\n    cf_points : numpy.ndarray\n        List of the two-dimensional on-sky coordinates defining the centers\n        of each cutout for which the photometric likelihoods should be\n        calculated.\n    filts : list of strings\n        List of the filters to create magnitude bins for in this catalogue.\n    mem_chunk_num : integer\n        Number of sub-sets to break larger catalogues down into, for memory\n        saving purposes.\n    joint_folder_path : string\n        Location of top-level folder into which all intermediate files are\n        saved for the cross-match process.\n    cat_folder_path : string\n        Location of the input data for this catalogue.\n    cat_type : string\n        String to indicate which catalogue we are creating bins for, either\n        \"a\", or \"b\".\n    sky_inds : numpy.ndarray\n        Array of indices, showing which on-sky photometric point, from\n        ``cf_points``, each source in the catalogue is closest to.\n    load_extra_arrays : boolean\n        Flag to indicate whether the photometric information is being used in\n        the cross-match process, and whether to load additional arrays accordingly.\n\n    Returns\n    -------\n    binlengths : numpy.ndarray\n        Two-dimensional array, indicating the length of the magnitude bins for\n        each filter-sky coordinate combination.\n    binsarray : numpy.ndarray\n        Three-dimensional array, containing the values of the magnitude bins for\n        the filter-sky combinations.\n    longbinlen : integer\n        Value of the largest of all filter-sky combinations of ``binlengths``.\n    '''\n    binlengths = np.empty((len(filts), len(cf_points)), int)\n\n    for m_ in range(0, len(cf_points), mem_chunk_num):\n        a_multi_return = _load_multiple_sky_slice(\n            joint_folder_path, cat_type, m_, m_+mem_chunk_num, cat_folder_path, sky_inds,\n            load_extra_arrays)\n        if load_extra_arrays:\n            (a_phot_, sky_inds_, _, _, _, _) = a_multi_return\n        else:\n            a_phot_, sky_inds_ = a_multi_return\n        del a_multi_return\n        for m in range(m_, min(len(cf_points), m_+mem_chunk_num)):\n            sky_cut = _load_single_sky_slice(\n                joint_folder_path, cat_type, m, sky_inds_)\n            for i in range(0, len(filts)):\n                a = a_phot_[sky_cut, i]\n                if np.sum(~np.isnan(a)) > 0:\n                    f = make_bins(a[~np.isnan(a)])\n                else:\n                    f = np.array([0])\n                del a\n                binlengths[i, m] = len(f)\n\n    longbinlen = np.amax(binlengths)\n    binsarray = np.lib.format.open_memmap(\n        '{}/phot_like/{}binsarray.npy'.format(joint_folder_path, cat_type), mode='w+', dtype=float,\n        shape=(longbinlen, len(filts), len(cf_points)), fortran_order=True)\n    binsarray[:, :, :] = -1\n    for m_ in range(0, len(cf_points), mem_chunk_num):\n        a_multi_return = _load_multiple_sky_slice(\n            joint_folder_path, cat_type, m_, m_+mem_chunk_num, cat_folder_path, sky_inds,\n            load_extra_arrays)\n        if load_extra_arrays:\n            (a_phot_, sky_inds_, _, _, _, _) = a_multi_return\n        else:\n            a_phot_, sky_inds_ = a_multi_return\n        for m in range(m_, min(len(cf_points), m_+mem_chunk_num)):\n            sky_cut = _load_single_sky_slice(\n                joint_folder_path, cat_type, m, sky_inds_)\n            for i in range(0, len(filts)):\n                a = a_phot_[sky_cut, i]\n                if np.sum(~np.isnan(a)) > 0:\n                    f = make_bins(a[~np.isnan(a)])\n                else:\n                    f = np.array([0])\n                del a\n                binsarray[:binlengths[i, m], i, m] = f\n\n    return binlengths, binsarray, longbinlen\n\n\ndef make_bins(input_mags):\n    '''\n    Calculate bins for a catalogue's magnitude distribution, ensuring all stars\n    are in histogram bins of sufficient number statistics.\n\n    Parameters\n    ----------\n    input_mags : numpy.ndarray\n        Array of magnitudes of given filter from the specific catalogue, to be\n        placed in a histogram.\n\n    Returns\n    -------\n    output_bins : numpy.ndarray\n        Bins for the given catalogue-filter combination that produce robust\n        numbers of sources within each magnitude interval.\n    '''\n    minamag = np.amin(input_mags)\n    maxamag = np.amax(input_mags)\n    da = 0.1\n    maxa = da*np.ceil(maxamag/da)\n    mina = da*np.floor(minamag/da)\n    na = int(np.ceil((maxa - mina)/da) + 1)\n    output_bins = np.linspace(mina, maxa, na)\n    # If min/max magnitudes that define magnitude bins happen to lie exactly\n    # on a bin edge (i.e., maxamag % da == 0), then just pad bin edge slightly.\n    if np.abs(mina - minamag) < 1e-5:\n        output_bins[0] -= 1e-4\n    if np.abs(maxa - maxamag) < 1e-5:\n        output_bins[-1] += 1e-4\n\n    hist, output_bins = np.histogram(input_mags, bins=output_bins)\n    smalllist = []\n    # Minimum number statistics in each 1-D bin.\n    minnum = 250\n\n    for i in range(0, len(output_bins)-1):\n        if hist[i] < minnum:\n            smalllist.extend([i])\n    smalllist = np.array(smalllist)\n    dellist = []\n    if len(smalllist) > 0:\n        for i in smalllist:\n            if i not in dellist:\n                flag = 0\n                for j in range(i+1, len(output_bins)-1):\n                    if np.sum(hist[i:j+1]) > minnum:\n                        dellist.extend([k for k in range(i+1, j+1)])\n                        flag = 1\n                        break\n                if flag == 0:\n                    dellist.extend([k for k in range(i+1, len(output_bins)-1)])\n    output_bins = np.delete(output_bins, dellist)\n\n    return output_bins\n\n\ndef _load_multiple_sky_slice(joint_folder_path, cat_name, ind1, ind2, cat_folder_path, sky_inds,\n                             load_extra_arrays):\n    '''\n    Function to, in a memmap-friendly way, return a sub-set of the photometry\n    of a given catalogue.\n\n    Parameters\n    ----------\n    joint_folder_path : string\n        Folder in which common cross-match intermediate data files are stored.\n    cat_name : string\n        String defining whether this function was called on catalogue \"a\" or \"b\".\n    ind1 : float\n        The lower of the two sky indices, as defined in ``distribute_sky_indices``,\n        to return a sub-set of the larger catalogue between. This value represents\n        the index of a given on-sky position, used to construct the \"counterpart\"\n        and \"field\" likelihoods.\n    ind2 : float\n        The upper of the sky indices, defining the sub-set of the photometric\n        array to return.\n    cat_folder_path : string\n        The folder defining where this particular catalogue is stored.\n    sky_inds : numpy.ndarray\n        The given catalogue's ``distribute_sky_indices`` values, to compare\n        with ``ind1`` and ``ind2``.\n    load_extra_arrays : boolean\n        Flag to indicate whether the photometric information is being used in\n        the cross-match process, and whether to load additional arrays accordingly.\n\n    Returns\n    -------\n    photo_cutout : numpy.ndarray\n        A sub-set of the photometry of the given catalogue, those points which are\n        astrometrically closest to the sky indices between ``ind1`` and ``ind2``.\n    sky_ind_cutout : numpy.ndarray\n        The reduced ``sky_inds`` array, containing only those between ``ind1`` and\n        ``ind2``.\n    list_of_arrays : list of numpy.ndarrays\n        Depending on whether ``load_extra_arrays`` is ``True`` or not, this list\n        contains either just a cutout of the photometric data for this catalogue\n        and the corresponding subset of the sky index array, or it also contains\n        subsets of the astrometry array, and \"bright\" source error circle length,\n        and overlap index and size arrays.\n    '''\n    sky_cut = np.lib.format.open_memmap('{}/{}_temporary_sky_slice_combined.npy'.format(\n        joint_folder_path, cat_name), mode='w+', dtype=bool, shape=(len(sky_inds),))\n\n    di = max(1, len(sky_inds) // 20)\n\n    for i in range(0, len(sky_inds), di):\n        sky_cut[i:i+di] = (sky_inds[i:i+di] >= ind1) & (sky_inds[i:i+di] < ind2)\n\n    if load_extra_arrays:\n        astro_cutout = np.load('{}/con_cat_astro.npy'.format(cat_folder_path),\n                               mmap_mode='r')[sky_cut]\n        a_blen_cutout = np.load('{}/group/{}blen.npy'.format(joint_folder_path, cat_name),\n                                mmap_mode='r')[sky_cut]\n        a_inds_cutout = np.load('{}/group/{}inds.npy'.format(joint_folder_path, cat_name),\n                                mmap_mode='r')[:, sky_cut]\n        a_size_cutout = np.load('{}/group/{}size.npy'.format(joint_folder_path, cat_name),\n                                mmap_mode='r')[sky_cut]\n\n    photo_cutout = np.load('{}/con_cat_photo.npy'.format(cat_folder_path), mmap_mode='r')[sky_cut]\n    sky_ind_cutout = np.load('{}/phot_like/{}_sky_inds.npy'.format(joint_folder_path, cat_name),\n                             mmap_mode='r')[sky_cut]\n\n    if load_extra_arrays:\n        list_of_arrays = (photo_cutout, sky_ind_cutout, astro_cutout, a_blen_cutout, a_inds_cutout,\n                          a_size_cutout)\n    else:\n        list_of_arrays = (photo_cutout, sky_ind_cutout)\n\n    os.system('rm {}/{}_temporary_sky_slice_combined.npy'.format(joint_folder_path, cat_name))\n\n    return list_of_arrays\n\n\ndef create_c_and_f(a_astro, b_astro, a_mag, b_mag, a_inds, a_size, b_inds, b_size, a_blen,\n                   a_bins, b_bins, bright_frac, field_frac, a_flags, b_flags, a_astro_ind,\n                   b_astro_ind, a_flen_ind, b_flen_ind, a_flags_ind, b_flags_ind, b_mag_ind, area):\n    '''\n    Functionality to create the photometric likelihood and priors from a set\n    of photometric data in a given pair of filters.\n\n    Parameters\n    ----------\n    a_astro : numpy.ndarray\n        Array of astrometric parameters for all catalogue \"a\" sources in this\n        given sky slice.\n    b_astro : numpy.ndarray\n        Astrometric parameters for small sky region catalogue \"b\" objects.\n    a_mag : numpy.ndarray\n        Catalogue \"a\" magnitudes for sky area.\n    b_mag : numpy.ndarray\n        Catalogue \"b\" magnitudes for sources in sky region.\n    a_inds : numpy.ndarray\n        Indices into catalogue \"b\" for each \"a\" object, indicating potential\n        overlaps in counterparts.\n    a_size : numpy.ndarray\n        The number of potential overlapping sources in catalogue \"b\", for each\n        catalogue \"a\" object.\n    b_inds : numpy.ndarray\n        Overlap indices into catalogue \"a\" for each catalogue \"b\" object.\n    b_size : numpy.ndarray\n        Number of overlaps from catalogue \"b\" into catalogue \"a\".\n    a_blen : numpy.ndarray\n        The \"bright\" error circle radius, integrating the joint AUF convolution\n        out to ``expected_frac`` for largest \"a\"-\"b\" potential pairing, for each\n        catalogue \"a\" object.\n    a_bins : numpy.ndarray\n        Array containing the magnitude bins into which to place catalogue \"a\"\n        sources.\n    b_bins : numpy.ndarray\n        Array containing the magnitude bins into which to place catalogue \"b\"\n        sources.\n    bright_frac : float\n        Fraction of total probability integral to consider potential counterparts\n        out to, when considering potential overlaps between catalogue-catalogue\n        pairings.\n    field_frac : float\n        Fraction of total probability integral out to which sources are removed\n        from consideration as \"field\" sources (i.e., they are not assumed to be\n        ruled out as potential counterparts), when considering potential overlaps\n        in pairs of objects between the two catalogues.\n    a_flags : numpy.ndarray\n        Boolean flags for whether a source in catalogue \"a\" has a detected\n        magnitude in ``a_mag``.\n    b_flags : numpy.ndarray\n        Detection flags for catalogue \"b\" sources in ``b_mag``.\n    a_astro_ind : numpy.ndarray\n        Astrometric information for all catalogue \"a\" sources with at least one\n        overlap with catalogue \"b\" sources from ``b_astro``.\n    b_astro_ind : numpy.ndarray\n        Astrometric information for all catalogue \"b\" sources with an overlap\n        with at least one catalogue \"a\" source in ``a_astro``.\n    a_flen_ind : numpy.ndarray\n        Largest joint AUF integral error circle radius for the \"field\" source\n        integral fraction, for each catalogue \"a\" object in ``a_astro_ind``.\n    b_flen_ind : numpy.ndarray\n        Maximum AUF integral distance for each source in ``b_astro_ind``.\n    a_flags_ind : numpy.ndarray\n        Boolean flags for catalogue \"a\" sources which have an overlap with any\n        catalogue \"b\" objects that are in this sky region.\n    b_flags_ind : numpy.ndarray\n        Boolean detection flags for all catalogue \"b\" sources for which any\n        sources in catalogue \"a\" have a potential overlap in this sky region.\n    b_mag_ind : numpy.ndarray\n        All source magnitudes for which the catalogue \"a\" subset of sources\n        have an overlap in catalogue \"b\".\n    area : float\n        Area of sky region for which photometric likelihood and prior are\n        being calculated, in square degrees.\n\n    Returns\n    -------\n    Nc : float\n        The prior density of counterpart sources between the catalogues.\n    cdmdm : numpy.ndarray\n        Two-dimensional array of the photometric likelihood of counterpart between\n        the two catalogues.\n    Nfa : float\n        So-called \"field\" source density in catalogue \"a\".\n    fa : numpy.ndarray\n        Probability density array of field sources for catalogue \"a\".\n    Nfb : float\n        Field source density prior for catalogue \"b\".\n    fb : numpy.ndarray\n        Field source PDF for catalogue \"b\".\n    '''\n    a_hist, a_bins = np.histogram(a_mag[a_flags], bins=a_bins)\n    pa = a_hist/(np.sum(a_hist)*np.diff(a_bins))\n\n    a_cuts = plf.find_mag_bin_inds(a_mag, a_flags, a_bins)\n\n    # get_field_dists allows for magnitude slicing, to get f(m | m) instead of f(m),\n    # but when we do want f(m) we just pass two impossible magnitudes as the limits.\n    a_mask, a_area = plf.get_field_dists(a_astro[:, 0], a_astro[:, 1], b_astro_ind[:, 0],\n                                         b_astro_ind[:, 1], a_inds, a_size, b_flen_ind, a_flags,\n                                         b_flags_ind, b_mag, -999, 999)\n    b_mask, b_area = plf.get_field_dists(b_astro[:, 0], b_astro[:, 1], a_astro_ind[:, 0],\n                                         a_astro_ind[:, 1], b_inds, b_size, a_flen_ind, b_flags,\n                                         a_flags_ind, a_mag, -999, 999)\n    a_mask = a_mask.astype(bool)\n    b_mask = b_mask.astype(bool)\n    a_left = a_mag[a_mask]\n    b_left = b_mag[b_mask]\n    hist, a_bins = np.histogram(a_left, bins=a_bins)\n    Num_fa = np.sum(a_mask)\n\n    fa = hist / (np.sum(hist)*np.diff(a_bins))\n\n    hist, b_bins = np.histogram(b_left, bins=b_bins)\n    Num_fb = np.sum(b_mask)\n\n    fb = hist / (np.sum(hist)*np.diff(b_bins))\n\n    Nfa = Num_fa/(area - a_area)\n    Nfb = Num_fb/(area - b_area)\n\n    bm = np.empty((len(b_bins)-1, len(a_bins)-1), float, order='F')\n    z = np.empty(len(a_bins)-1, float)\n\n    mag_mask, aa = plf.brightest_mag(a_astro[:, 0], a_astro[:, 1], b_astro_ind[:, 0],\n                                     b_astro_ind[:, 1], a_mag, b_mag_ind, a_inds, a_size, a_blen,\n                                     a_flags, b_flags_ind, a_bins)\n    mag_mask = mag_mask.astype(bool)\n    for i in range(0, len(a_bins)-1):\n        hist, b_bins = np.histogram(b_mag_ind[mag_mask[:, i]], bins=b_bins)\n        q = np.sum(mag_mask[:, i])\n        if q > 0:\n            bm[:, i] = hist/(np.diff(b_bins)*q)\n        else:\n            bm[:, i] = 0\n        z[i] = np.sum(hist)/np.sum(a_cuts[i])\n    cdmdm = np.empty((len(b_bins)-1, len(a_bins)-1), float, order='F')\n    for i in range(0, len(a_bins)-1):\n        bmask, barea = plf.get_field_dists(\n            b_astro[:, 0], b_astro[:, 1], a_astro[:, 0], a_astro[:, 1], b_inds, b_size, a_flen_ind,\n            b_flags, a_flags_ind, a_mag, a_bins[i], a_bins[i+1])\n        bmask = bmask.astype(bool)\n        b_left = b_mag[bmask]\n        hist, b_bins = np.histogram(b_left, bins=b_bins)\n        _Num_fb = np.sum(b_mask)\n\n        _fb = hist / (np.sum(hist)*np.diff(b_bins))\n        _Nfb = _Num_fb/(area - barea)\n        Fm = np.append(0, np.cumsum(_fb[:-1] * np.diff(b_bins[:-1])))\n        for j in range(0, len(b_bins)-1):\n            Cm = np.sum(cdmdm[:j, i]*np.diff(b_bins[:j+1]))\n            cdmdm[j, i] = max(0, z[i]*bm[j, i]*np.exp(aa[i]*_Nfb*Fm[j]) - (1-Cm)*aa[i]*_Nfb*_fb[j])\n\n    zc = np.sum(cdmdm*np.diff(b_bins).reshape(-1, 1), axis=0)\n    frac = zc/bright_frac\n    density_of_inputs = np.sum(a_cuts, axis=1)/area\n    Nc = np.sum(frac*density_of_inputs)\n\n    integral = 0\n    for i in range(0, len(a_bins)-1):\n        cdmdm[:, i] *= pa[i] / (a_bins[i+1] - a_bins[i])\n        integral = integral + np.sum(cdmdm[:, i]*np.diff(b_bins))*(a_bins[i+1] - a_bins[i])\n    if integral > 0:\n        cdmdm /= integral\n\n    # Correct the field priors for the fraction of counterparts that get left\n    # in their \"cutout\" circle, by the fact that we don't use the entire integral:\n    Nfa = Nfa - (1 - field_frac)*Nc\n    Nfb = Nfb - (1 - field_frac)*Nc\n\n    return Nc, cdmdm, Nfa, fa, Nfb, fb\n", "meta": {"hexsha": "d54e80e00a6feadc6dc9e4dad180d4fff363503a", "size": 33822, "ext": "py", "lang": "Python", "max_stars_repo_path": "macauff/photometric_likelihood.py", "max_stars_repo_name": "lsst-uk/macauff", "max_stars_repo_head_hexsha": "02ce5caeaa1523957f914155dd433c7d1bf65869", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "macauff/photometric_likelihood.py", "max_issues_repo_name": "lsst-uk/macauff", "max_issues_repo_head_hexsha": "02ce5caeaa1523957f914155dd433c7d1bf65869", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "macauff/photometric_likelihood.py", "max_forks_repo_name": "lsst-uk/macauff", "max_forks_repo_head_hexsha": "02ce5caeaa1523957f914155dd433c7d1bf65869", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-24T13:21:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T13:21:37.000Z", "avg_line_length": 48.3171428571, "max_line_length": 99, "alphanum_fraction": 0.622198569, "include": true, "reason": "import numpy", "num_tokens": 8248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.18543258984210098}}
{"text": "# Lint as python3\n# Copyright 2020 DeepMind Technologies Limited. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or  implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"A tree search ideal observer for alchemy.\"\"\"\n\nimport collections\nimport copy\nimport math\nfrom typing import Any, Counter, List, Mapping, MutableMapping, Sequence, Tuple\n\nfrom dm_alchemy.ideal_observer import helpers\nfrom dm_alchemy.ideal_observer import precomputed_maps\nfrom dm_alchemy.types import graphs\nfrom dm_alchemy.types import helpers as types_helpers\nfrom dm_alchemy.types import stones_and_potions\nimport numpy as np\n\n# Alias these for readability\nAlignedStone = stones_and_potions.AlignedStone\nPerceivedStone = stones_and_potions.PerceivedStone\nPerceivedPotion = stones_and_potions.PerceivedPotion\nLatentStone = stones_and_potions.LatentStone\nLatentPotion = stones_and_potions.LatentPotion\nStoneMap = stones_and_potions.StoneMap\nPotionMap = stones_and_potions.PotionMap\nPartialStoneMap = stones_and_potions.PartialStoneMap\nPartialPotionMap = stones_and_potions.PartialPotionMap\nPartialGraph = graphs.PartialGraph\n\nPrecomputedMaps = precomputed_maps.PrecomputedMaps\n\n# We use indices in place of actual types for speed\nAlignedStoneIndex = stones_and_potions.AlignedStoneIndex\nPerceivedPotionIndex = stones_and_potions.PerceivedPotionIndex\nLatentStoneIndex = stones_and_potions.LatentStoneIndex\nLatentPotionIndex = stones_and_potions.LatentPotionIndex\nStoneMapIndex = stones_and_potions.StoneMapIndex\nPotionMapIndex = stones_and_potions.PotionMapIndex\n\nAction = Tuple[AlignedStoneIndex, PerceivedPotionIndex]\nActionObjective = Tuple[Action, Any]\nSearchResults = MutableMapping[int, ActionObjective]\nActionObjectiveAndSearchResults = Tuple[Action, Any, SearchResults]\n\nEND_TRIAL = types_helpers.END_TRIAL\n\n\ndef get_possible_stone_maps(\n    stone_map_indices: Sequence[StoneMapIndex],\n    aligned_stones: Sequence[AlignedStone]\n) -> Tuple[List[int], List[StoneMapIndex]]:\n  \"\"\"Gets possible stone maps (and their indices) consistent with stones passed.\"\"\"\n  # This doesn't need to be especially fast as it just happens once per trial.\n  still_in_s = []\n  poss_sms = []\n  for i, sm in enumerate(stone_map_indices):\n    stone_map = stones_and_potions.stone_map_from_index(sm)\n    if stone_map.consistent_with_stones(aligned_stones):\n      still_in_s.append(i)\n      poss_sms.append(sm)\n  return still_in_s, poss_sms\n\n\nclass WorldStateDistribution:\n  \"\"\"Distribution over world states.\"\"\"\n\n  def __init__(\n      self, stone_map_distr: Mapping[StoneMapIndex, float],\n      potion_map_distr: Mapping[PotionMapIndex, float],\n      precomputed: PrecomputedMaps\n  ):\n\n    self.stone_map_possible = sorted(stone_map_distr.keys())\n    self.potion_map_possible = sorted(potion_map_distr.keys())\n    self.partial_potion_map_index = (\n        stones_and_potions.partial_potion_map_from_possibles(\n            self.potion_map_possible, precomputed.index_to_perm_index).index(\n                precomputed.perm_index_to_index))\n    self.partial_stone_map_index = (\n        stones_and_potions.partial_stone_map_from_possibles(\n            self.stone_map_possible).index())\n\n    # Use a bitfield like structure otherwise it takes forever to copy\n    self.partial_graph_possible = helpers.list_to_bitfield(\n        range(precomputed.graphs_list.shape[0]))\n    self.partial_graph_index = (\n        precomputed.partial_graph_index_to_possible_index[\n            graphs.partial_graph_from_possibles(\n                precomputed.graphs_list[self.get_possible_graphs()]).index()])\n\n    self.poss_world_states = np.zeros((\n        len(potion_map_distr), len(stone_map_distr),\n        precomputed.graph_index_distr.shape[0]), dtype=np.float)\n    for potion_map_index, p1 in enumerate(potion_map_distr.values()):\n      for stone_map_index, p2 in enumerate(stone_map_distr.values()):\n        for graph_index, p3 in enumerate(precomputed.graph_index_distr):\n          p = p1 * p2 * p3\n          self.poss_world_states[\n              potion_map_index, stone_map_index, graph_index] = p\n\n    self.observed_no_effect_bits = 0\n\n  def new_trial(\n      self, aligned_stone_indices: Counter[AlignedStoneIndex]\n  ) -> None:\n    \"\"\"Updates the world state distribution given the stones perceived.\n\n    The reward indicator on the stones allows us to limit the possible maps from\n    stone space to latent space. For example if we see a stone with reward 3\n    then it must be at [1, 1, 1] in latent space.\n\n    Args:\n      aligned_stone_indices: The stones seen in this trial.\n    \"\"\"\n    # The stones seen when we start a new trial could eliminate stone map\n    # possibilities if there are multiple.\n    aligned_stones = [\n        stones_and_potions.aligned_stone_from_index(aligned_stone_index)\n        for aligned_stone_index in aligned_stone_indices]\n    still_in_s, poss_sms = get_possible_stone_maps(\n        self.stone_map_possible, aligned_stones)\n    assert still_in_s, 'Stones seen in trial are impossible.'\n\n    self.stone_map_possible = poss_sms\n    self.partial_stone_map_index = (\n        stones_and_potions.partial_stone_map_from_possibles(\n            self.stone_map_possible).index())\n    self.poss_world_states = self.poss_world_states[:, still_in_s, :]\n    total_prob = self.poss_world_states.sum()\n    self.poss_world_states /= total_prob\n\n  def get_possible_graphs(self) -> List[int]:\n    return helpers.bitfield_to_list(self.partial_graph_possible)\n\n  def potions_equivalent(\n      self, p1: PerceivedPotionIndex, p2: PerceivedPotionIndex,\n      s: AlignedStoneIndex, precomputed: PrecomputedMaps\n  ) -> bool:\n    \"\"\"If the potions effect on the stone are equivalent in this belief state.\n\n    This is the case if we have the same knowledge about the potions effect and\n    the same number of these potions and their counterparts on the same\n    dimension. In this case the calculation of the expected reward must be\n    exactly the same. This does not imply that the actual effect of the potions\n    will be the same.\n\n    For example, if we have no knowledge of the perceptual mapping and graph and\n    we have one red potion and one green potion then the calculation will\n    include terms for the probability that the red potion acts on each of the\n    directed edges in latent space. The calculation for the green potion would\n    have all of the same terms.\n\n    Args:\n      p1: The first potion.\n      p2: The second potion.\n      s: The stone they will be applied to.\n      precomputed: Precomputed maps used for speed.\n\n    Returns:\n      True if they are equivalent.\n    \"\"\"\n    latent_dims = precomputed.possible_latent_dims[\n        p1, self.partial_potion_map_index[0]]\n    latent_dims2 = precomputed.possible_latent_dims[\n        p2, self.partial_potion_map_index[0]]\n    if latent_dims != latent_dims2:\n      return False\n    for latent_dim in latent_dims:\n      this_could_stay_still1, latent_dirs1 = precomputed.possible_latent_dirs[\n          self.partial_potion_map_index[1], self.partial_stone_map_index,\n          latent_dim, p1, s]\n      this_could_stay_still2, latent_dirs2 = precomputed.possible_latent_dirs[\n          self.partial_potion_map_index[1], self.partial_stone_map_index,\n          latent_dim, p2, s]\n      if this_could_stay_still1 != this_could_stay_still2:\n        return False\n      if latent_dirs1 != latent_dirs2:\n        return False\n    return True\n\n  def update_possible(\n      self, stone_index: AlignedStoneIndex,\n      potion_index: PerceivedPotionIndex,\n      result_index: AlignedStoneIndex,\n      precomputed: PrecomputedMaps\n  ) -> None:\n    \"\"\"Updates which possibilities are consistent with this observation.\n\n    Args:\n      stone_index: The initial stone.\n      potion_index: The potion applied to the stone.\n      result_index: The resulting stone.\n      precomputed: Precomputed maps used for speed.\n    \"\"\"\n    # Update which potion maps are possible\n    poss_p = precomputed.poss_p_maps[stone_index, potion_index, result_index]\n    if poss_p is not None:\n      self.partial_potion_map_index = precomputed.partial_potion_map_update[\n          stone_index, potion_index, result_index,\n          self.partial_potion_map_index[0], self.partial_potion_map_index[1]]\n      self.potion_map_possible, still_in_p = helpers.sorted_intersection(\n          self.potion_map_possible, poss_p)\n      self.poss_world_states = self.poss_world_states[still_in_p, :, :]\n\n    # Update which stone maps are possible\n    poss_s = precomputed.poss_s_maps[stone_index, potion_index, result_index]\n    if poss_s is not None:\n      self.partial_stone_map_index = precomputed.partial_stone_map_update[\n          stone_index, result_index, self.partial_stone_map_index]\n      self.stone_map_possible, still_in_s = helpers.sorted_intersection(\n          self.stone_map_possible, poss_s)\n      self.poss_world_states = self.poss_world_states[:, still_in_s, :]\n\n    # Update which graphs are possible\n    update_graphs_possible = False\n    if stone_index != result_index:\n      update_graphs_possible = True\n      self.partial_graph_index = precomputed.partial_graph_update[\n          precomputed.drop_reward[stone_index],\n          precomputed.drop_reward[result_index]][self.partial_graph_index]\n\n    if not update_graphs_possible:\n      missing_edge = precomputed.missing_edge_no_change[\n          self.partial_stone_map_index, self.partial_potion_map_index[0],\n          self.partial_potion_map_index[1], potion_index,\n          precomputed.drop_reward[stone_index]]\n      if missing_edge != -1:\n        update_graphs_possible = True\n        self.partial_graph_index = precomputed.update_partial_graph_no_change[\n            self.partial_graph_index, missing_edge]\n\n    if update_graphs_possible:\n      new_graphs_possible = precomputed.partial_graph_to_matching_graphs[\n          self.partial_graph_index]\n      remaining_graphs_possible = (self.partial_graph_possible &\n                                   new_graphs_possible)\n      # Work out the position of the eliminated slices in poss_world_states.\n      still_in_g = []\n      ind = 0\n      for i in range(precomputed.graphs_list.shape[0]):\n        check = 1 << i\n        poss_check = self.partial_graph_possible & check\n        if remaining_graphs_possible & check and poss_check:\n          still_in_g.append(ind)\n        if poss_check:\n          ind += 1\n      self.partial_graph_possible = remaining_graphs_possible\n\n      self.poss_world_states = self.poss_world_states[:, :, still_in_g]\n\n    # If stone map is known then get info about which actions will have no\n    # effect because they take the stone out of the latent cube\n    stone_map_index = precomputed.partial_stone_map_to_stone_map[\n        self.partial_stone_map_index]\n    if stone_map_index != -1:\n      self.observed_no_effect_bits |= precomputed.no_effect_from_partial_chem[\n          stone_map_index, self.partial_potion_map_index[0],\n          self.partial_potion_map_index[1]]\n\n  def possible_outcomes(\n      self, perceived_potion_index: PerceivedPotionIndex,\n      aligned_stone_index: AlignedStoneIndex, precomputed: PrecomputedMaps\n  ) -> Tuple[List[AlignedStoneIndex], bool]:\n    \"\"\"Gets a list of outcomes we could see applying this potion to this stone.\n\n    Args:\n      perceived_potion_index: The potion we apply.\n      aligned_stone_index: The stone we apply it to.\n      precomputed: Precomputed maps used for speed.\n\n    Returns:\n      A list of possible outcomes and a boolean saying whether one of them is\n      the stone remaining the same.\n    \"\"\"\n    outcomes = []\n    could_stay_still = False\n    for latent_dim in precomputed.possible_latent_dims[\n        perceived_potion_index, self.partial_potion_map_index[0]]:\n      # latent_dir may not be possible if the reward for the stone is already at\n      # max or min. If you know stone position in latent space on latent_dim\n      # then latent_dir can only be the opposite so you don't need to consider\n      # the reward going the other way even if you don't know what direction the\n      # potion acts in.\n      this_could_stay_still, latent_dirs = precomputed.possible_latent_dirs[\n          self.partial_potion_map_index[1], self.partial_stone_map_index,\n          latent_dim, perceived_potion_index, aligned_stone_index]\n      # Could stay still due to going outside the cube.\n      could_stay_still |= this_could_stay_still\n      for latent_dir in latent_dirs:\n        result = precomputed.react_result[\n            aligned_stone_index, latent_dim, (latent_dir + 1) // 2,\n            self.partial_graph_index]\n        if result != helpers.IMPOSSIBLE:\n          outcomes.append(result)\n      if latent_dirs:\n        # Could stay still due to edge not existing\n        this_edge_exists = precomputed.edge_exists[\n            self.partial_graph_index, precomputed.drop_reward[\n                aligned_stone_index], latent_dim]\n        # If either we know the edge isn't there or we are not sure if the edge\n        # is there then could stay still.\n        if this_edge_exists != graphs.KNOWN_EDGE:\n          could_stay_still = True\n\n    if could_stay_still:\n      outcomes.append(aligned_stone_index)\n    return outcomes, could_stay_still\n\n  def action_and_outcome(\n      self, stone_index: AlignedStoneIndex,\n      potion_index: PerceivedPotionIndex, result_index: AlignedStoneIndex,\n      precomputed: PrecomputedMaps, bit_mask: int\n  ) -> float:\n    \"\"\"Updates the world state distribution given we saw this observation.\"\"\"\n\n    # Eliminate whole slices of the world state distribution if possible given\n    # the new information.\n    self.update_possible(stone_index, potion_index, result_index, precomputed)\n\n    # If the stone changed as a result of applying the potion then all\n    # information gained removes whole slices otherwise we must remove\n    # combinations of potion map, stone map and graph.\n    if stone_index == result_index:\n      for potion_i, potion_map_index in enumerate(self.potion_map_possible):\n        for stone_i, stone_map_index in enumerate(self.stone_map_possible):\n          graphs_bitfield = precomputed.graphs_with_edge[\n              stone_map_index, potion_map_index, stone_index, potion_index]\n\n          # If there are no graphs with an edge between the stone and result\n          # then continue.\n          if graphs_bitfield == 0:\n            continue\n\n          # Graphs in the list are not possible because they contain the edge so\n          # the stone should have changed but didn't.\n          not_possible = []\n          ind = 0\n          for i in range(precomputed.graphs_list.shape[0]):\n            check = 1 << i\n            poss_check = self.partial_graph_possible & check\n            if graphs_bitfield & check and poss_check:\n              not_possible.append(ind)\n            if poss_check:\n              ind += 1\n\n          self.poss_world_states[potion_i, stone_i, not_possible] = 0.0\n      self.observed_no_effect_bits |= bit_mask\n\n    # Re-normalise\n    total_prob = self.poss_world_states.sum()\n    if total_prob > 0.0:\n      self.poss_world_states /= total_prob\n    return total_prob\n\n  def __len__(self):\n    return len(self.poss_world_states)\n\n  def update_stone_map(self, new_to_old: StoneMap) -> None:\n    \"\"\"If we assumed the wrong rotation we may need to swap stone map dims.\"\"\"\n    # Change partial stone map.\n    partial_stone_map = stones_and_potions.partial_stone_map_from_index(\n        self.partial_stone_map_index)\n    # If the partial stone map is not completely known at this point then it is\n    # completely unknown since any 2 bits of information would be enough to\n    # completely determine the rotation.\n    if any(c == types_helpers.UNKNOWN\n           for c in partial_stone_map.latent_pos_dir):\n      assert all(c == types_helpers.UNKNOWN\n                 for c in partial_stone_map.latent_pos_dir)\n    else:\n      partial_stone_map.chain(new_to_old)\n    self.partial_stone_map_index = partial_stone_map.index()\n    # Change poss stone maps.\n    old_stone_map_possible = copy.deepcopy(self.stone_map_possible)\n    old_stone_map_to_new_stone_map = {}\n    for stone_map_index in self.stone_map_possible:\n      stone_map = stones_and_potions.stone_map_from_index(stone_map_index)\n      stone_map.chain(new_to_old)\n      old_stone_map_to_new_stone_map[stone_map_index] = stone_map.index()\n    self.stone_map_possible = sorted(\n        old_stone_map_to_new_stone_map[stone_map_index]\n        for stone_map_index in self.stone_map_possible)\n    new_stone_map_to_index = {\n        stone_map_index: i\n        for i, stone_map_index in enumerate(self.stone_map_possible)}\n    old_index_to_new_index = [\n        new_stone_map_to_index[old_stone_map_to_new_stone_map[stone_map]]\n        for stone_map in old_stone_map_possible]\n    # Change poss world states.\n    old_poss_world_states = copy.deepcopy(self.poss_world_states)\n    for old_index, new_index in enumerate(old_index_to_new_index):\n      self.poss_world_states[new_index] = old_poss_world_states[old_index]\n    # Change observed no effect.\n    old_observed_no_effect_bits = copy.deepcopy(self.observed_no_effect_bits)\n    self.observed_no_effect_bits = 0\n    for old_index in range(stones_and_potions.AlignedStone.num_dir_assignments):\n      aligned_stone = stones_and_potions.aligned_stone_from_index(\n          AlignedStoneIndex(old_index))\n      new_index = new_to_old.apply(aligned_stone).index()\n      for potion_index in range(stones_and_potions.PerceivedPotion.num_types):\n        old_mask = 1 << (old_index * PerceivedPotion.num_types) + potion_index\n        masked = old_observed_no_effect_bits & old_mask\n        if masked:\n          new_mask = 1 << (new_index * PerceivedPotion.num_types) + potion_index\n          self.observed_no_effect_bits |= new_mask\n\n\ndef init_world_state_distribution(\n    precomputed: PrecomputedMaps\n) -> WorldStateDistribution:\n  \"\"\"Creates an initial world state distribution from observed stones.\"\"\"\n  # Initialise the ideal observer based on the stones and potions you can see\n  return WorldStateDistribution(\n      stones_and_potions.stone_map_distr(precomputed.stone_maps),\n      stones_and_potions.potion_map_distr(precomputed.potion_maps),\n      precomputed)\n\n\ndef stone_potion_bit_mask(\n    stone_index: AlignedStoneIndex, potion_index: PerceivedPotionIndex,\n    precomputed: PrecomputedMaps\n) -> int:\n  \"\"\"Returns a mask for the bit representing a stone potion pair.\"\"\"\n  stone_part = precomputed.drop_reward[stone_index] * PerceivedPotion.num_types\n  return 1 << (stone_part + potion_index)\n\n\nclass BeliefState:\n  \"\"\"Belief the ideal observer has about stones, potions, world and reward.\n\n  The belief state consists of a set of perceived stones, a set of perceived\n  potions, a distribution over world states, and a reward so far.\n  \"\"\"\n\n  possible_partial_graph_num_bits = None\n\n  def __init__(self, precomputed: PrecomputedMaps):\n\n    # These should be set by calling new_trial\n    self.aligned_stones: Counter[AlignedStoneIndex] = collections.Counter()\n    self.perceived_potions: Counter[PerceivedPotionIndex] = (\n        collections.Counter())\n    self.world_state_distribution = init_world_state_distribution(precomputed)\n\n  def representative_potions(\n      self, stone_index: AlignedStoneIndex, precomputed: PrecomputedMaps\n  ) -> List[PerceivedPotionIndex]:\n    \"\"\"Gets a representative set of potions for this stone and belief state.\n\n    Some potions will be equivalent if we don't know what they do and we have\n    the same number of them and their counterparts on the same perceptual\n    dimension. For each equivalence set we return one potion as a representative\n    of the set.\n\n    Args:\n      stone_index: The stone to apply potions to.\n      precomputed: Precomputed maps used for speed.\n\n    Returns:\n      A representative set of potions.\n    \"\"\"\n    potion_to_count = [0 for _ in range(PerceivedPotion.num_types)]\n    for p1 in self.perceived_potions:\n      p2 = precomputed.potion_to_pair[p1]\n      c1 = self.perceived_potions[p1]\n      c2 = self.perceived_potions[p2]\n      potion_to_count[p1] = (c1, c2)\n    representative_potions = []\n    for p2 in self.perceived_potions:\n      equiv = False\n      for p1 in representative_potions:\n        b1 = (self.world_state_distribution.observed_no_effect_bits &\n              precomputed.potion_masks[p1]) >> p1\n        b2 = (self.world_state_distribution.observed_no_effect_bits &\n              precomputed.potion_masks[p2]) >> p2\n        if (potion_to_count[p1] == potion_to_count[p2] and\n            (b1 == b2) and\n            self.world_state_distribution.potions_equivalent(\n                p1, p2, stone_index, precomputed)):\n          equiv = True\n          break\n      if not equiv:\n        representative_potions.append(p2)\n    return representative_potions\n\n  def _remove_stone(self, stone_index: AlignedStoneIndex) -> None:\n    if stone_index in self.aligned_stones:\n      self.aligned_stones[stone_index] -= 1\n    if self.aligned_stones[stone_index] == 0:\n      del self.aligned_stones[stone_index]\n\n  def _add_stone(self, stone_index: AlignedStoneIndex) -> None:\n    self.aligned_stones.update([stone_index])\n\n  def _remove_potion(self, potion_index: PerceivedPotionIndex) -> None:\n    self.perceived_potions.subtract([potion_index])\n    if self.perceived_potions[potion_index] == 0:\n      del self.perceived_potions[potion_index]\n\n  def possible_actions(\n      self, precomputed: PrecomputedMaps\n  ) -> List[Tuple[AlignedStoneIndex, PerceivedPotionIndex]]:\n    \"\"\"Gets representative list of possible actions which have an effect.\"\"\"\n    # Use -1, -1 to represent ending and putting all stones in the cauldron or\n    # throwing them away. If we consider this action first then in the event\n    # that it has the same expected reward as using a potion we will take this\n    # action instead. This gives more intuitive behaviour, for example if we\n    # have the best stone we won't transform it to something less good and then\n    # transform it back.\n    poss_actions = [(AlignedStoneIndex(END_TRIAL),\n                     PerceivedPotionIndex(END_TRIAL))]\n    for s in self.aligned_stones:\n      # Don't consider potions if we have observed that they have no effect.\n      potions = [p for p in self.representative_potions(s, precomputed)\n                 if not (self.world_state_distribution.observed_no_effect_bits &\n                         stone_potion_bit_mask(s, p, precomputed))]\n      poss_actions.extend([(s, p) for p in potions])\n\n    return poss_actions\n\n  def use_potion(\n      self, stone_index: AlignedStoneIndex,\n      potion_index: PerceivedPotionIndex,\n      result_index: AlignedStoneIndex\n  ) -> None:\n    \"\"\"Uses the potion on the current stone.\n\n    Args:\n      stone_index: The stone used in the potion.\n      potion_index: The potion applied to the stone.\n      result_index: The result observed.\n    \"\"\"\n    # Remove the used potion\n    self._remove_potion(potion_index)\n    # If the stone has not changed then we don't need to do anything else.\n    if stone_index == result_index:\n      return\n    # Remove the initial stone and replace with the result\n    self._remove_stone(stone_index)\n    self._add_stone(result_index)\n\n  def action_and_outcome(\n      self, stone_index: AlignedStoneIndex,\n      potion_index: PerceivedPotionIndex, result_index: AlignedStoneIndex,\n      precomputed: PrecomputedMaps, bit_mask: int\n  ) -> float:\n    \"\"\"Updates the belief state given the action and observation.\n\n    Args:\n      stone_index: The stone used in the potion.\n      potion_index: The potion in which the stone is used.\n      result_index: The resulting stone.\n      precomputed: Precomputed maps used for speed.\n      bit_mask: Mask on observed no effect for the stone and potion passed.\n\n    Returns:\n      The probability given our prior belief state of this observation.\n    \"\"\"\n    self.use_potion(stone_index, potion_index, result_index)\n\n    # Update the world state distribution\n    total_prob = self.world_state_distribution.action_and_outcome(\n        stone_index, potion_index, result_index, precomputed, bit_mask)\n\n    return total_prob\n\n  def new_trial(\n      self, aligned_stones: Counter[AlignedStoneIndex],\n      perceived_potions: Counter[PerceivedPotionIndex]\n  ) -> None:\n    self.aligned_stones = copy.deepcopy(aligned_stones)\n    self.perceived_potions = copy.deepcopy(perceived_potions)\n    self.world_state_distribution.new_trial(aligned_stones)\n\n  def to_bitfield(self) -> int:\n    \"\"\"Converts to a bitfield to cache results.\"\"\"\n\n    def perceived_potions_to_bits(\n        perceived_potions: Mapping[PerceivedPotionIndex, int]\n    ) -> Tuple[int, int]:\n      \"\"\"Converts the set of perceived potions to a bitfield.\"\"\"\n      local_int_rep = 0\n      for potion_type, count in perceived_potions.items():\n        local_int_rep |= (count << (\n            PerceivedPotion.count_num_bits * potion_type))\n        if count > PerceivedPotion.max_present:\n          raise ValueError('Too many potions present.')\n        if potion_type >= PerceivedPotion.num_types:\n          raise ValueError('Invalid potion type.')\n      return local_int_rep, (\n          PerceivedPotion.num_types * PerceivedPotion.count_num_bits)\n\n    def aligned_stones_to_bits(\n        aligned_stones: Mapping[AlignedStoneIndex, int]\n    ) -> Tuple[int, int]:\n      \"\"\"Converts the set of perceived stones to a bitfield.\"\"\"\n      local_int_rep = 0\n      stone_number = 0\n      for stone_type, count in sorted(aligned_stones.items()):\n        for _ in range(count):\n          local_int_rep |= (stone_type << (\n              AlignedStone.num_bits * stone_number))\n          stone_number += 1\n        if stone_type >= stones_and_potions.AlignedStone.num_types:\n          raise ValueError('Invalid stone type')\n      if stone_number > AlignedStone.max_present:\n        raise ValueError('Too many stones present.')\n      return local_int_rep, AlignedStone.max_present * AlignedStone.num_bits\n\n    all_things = [\n        perceived_potions_to_bits(self.perceived_potions),\n        aligned_stones_to_bits(self.aligned_stones),\n        (self.world_state_distribution.observed_no_effect_bits,\n         LatentStone.num_types * PerceivedPotion.num_types),\n        (self.world_state_distribution.partial_potion_map_index[0],\n         PartialPotionMap.num_bits_axis),\n        (self.world_state_distribution.partial_potion_map_index[1],\n         PartialPotionMap.num_bits_dir),\n        (self.world_state_distribution.partial_stone_map_index,\n         PartialStoneMap.num_bits),\n        (self.world_state_distribution.partial_graph_index,\n         BeliefState.possible_partial_graph_num_bits)\n    ]\n\n    return helpers.pack_to_bitfield(all_things)\n\n  def __repr__(self) -> str:\n    # Convert the observed_no_effect bitfield to a matrix before printing.\n    observed_no_effect = np.zeros(\n        (stones_and_potions.LatentStone.num_types,\n         stones_and_potions.PerceivedPotion.num_types))\n    for pe_st in range(stones_and_potions.LatentStone.num_types):\n      for pe_po in range(stones_and_potions.PerceivedPotion.num_types):\n        bit_num = (pe_st * stones_and_potions.PerceivedPotion.num_types) + pe_po\n        observed_no_effect[pe_st, pe_po] = (\n            self.world_state_distribution.observed_no_effect_bits &\n            (1 << bit_num))\n\n    return (\n        'BeliefState(aligned_stones={aligned_stones}, '\n        'perceived_potions={perceived_potions}, '\n        'observed_no_effect={observed_no_effect}, '\n        'poss_world_states={poss_world_states}, '\n        'partial_potion_map_index={partial_potion_map_index}, '\n        'partial_stone_map_index={partial_stone_map_index}, '\n        'partial_graph_index={partial_graph_index}, '\n        'partial_graph_possible={partial_graph_possible}, '\n        'stone_map_possible={stone_map_possible}, '\n        'potion_map_possible={potion_map_possible}, '\n        'num_world_states = {num_world_states}, '.format(\n            aligned_stones=self.aligned_stones,\n            perceived_potions=self.perceived_potions,\n            observed_no_effect=types_helpers.str_np_array_construct(\n                observed_no_effect),\n            poss_world_states=types_helpers.str_np_array_construct(\n                self.world_state_distribution.poss_world_states),\n            partial_potion_map_index=(\n                self.world_state_distribution.partial_potion_map_index),\n            partial_stone_map_index=(\n                self.world_state_distribution.partial_stone_map_index),\n            partial_graph_index=(\n                self.world_state_distribution.partial_graph_index),\n            partial_graph_possible=(\n                self.world_state_distribution.partial_graph_possible),\n            stone_map_possible=self.world_state_distribution.stone_map_possible,\n            potion_map_possible=(\n                self.world_state_distribution.potion_map_possible),\n            num_world_states=len(self.world_state_distribution)))\n\n  def update_stone_map(\n      self, new_to_old: StoneMap\n  ) -> None:\n    \"\"\"If we assumed the wrong rotation we may need to swap stone map dims.\"\"\"\n    # Change poss stone maps.\n    old_aligned_stones = {\n        stones_and_potions.aligned_stone_from_index(stone): count\n        for stone, count in self.aligned_stones.items()}\n    new_aligned_stones = collections.Counter({\n        AlignedStone(stone.reward, new_to_old.apply(\n            stone).latent_coords).index(): count\n        for stone, count in old_aligned_stones.items()})\n    self.aligned_stones = new_aligned_stones\n    self.world_state_distribution.update_stone_map(new_to_old)\n\n  @property\n  def num_world_states(self) -> int:\n    return np.where(self.world_state_distribution.poss_world_states)[0].size\n\n  @property\n  def num_potion_maps(self) -> int:\n    return len(self.world_state_distribution.potion_map_possible)\n\n  @property\n  def num_stone_maps(self) -> int:\n    return len(self.world_state_distribution.stone_map_possible)\n\n  @property\n  def num_graphs(self) -> int:\n    return len(self.world_state_distribution.get_possible_graphs())\n\n  def partial_potion_map(\n      self, index_to_perm_index: np.ndarray\n  ) -> PartialPotionMap:\n    return stones_and_potions.partial_potion_map_from_index(\n        self.world_state_distribution.partial_potion_map_index,\n        index_to_perm_index)\n\n  def partial_stone_map(self) -> PartialStoneMap:\n    return stones_and_potions.partial_stone_map_from_index(\n        self.world_state_distribution.partial_stone_map_index)\n\n  def partial_graph(\n      self, possible_partial_graph_indices: np.ndarray\n  ) -> PartialGraph:\n    return graphs.partial_graph_from_index(\n        possible_partial_graph_indices[\n            self.world_state_distribution.partial_graph_index])\n\n\nclass BeliefStateWithRotation:\n  \"\"\"Belief state over chem including rotations.\"\"\"\n\n  def __init__(self, precomputed: precomputed_maps.PrecomputedMaps):\n    self.belief_state = BeliefState(precomputed)\n    self.possible_rotations = stones_and_potions.possible_rotations()\n    self.rotation = None\n    # We need to know 1 stone which is consistent with the selected rotation.\n    self._observed_stone = None\n    self._rotation_to_angles = (\n        lambda rotation: tuple(stones_and_potions.rotation_to_angles(rotation)))\n    stone_map_indices = [\n        sm.index() for sm in stones_and_potions.possible_stone_maps()]\n    self._stone_maps_for_rotation = {\n        self._rotation_to_angles(rotation): copy.deepcopy(stone_map_indices)\n        for rotation in stones_and_potions.possible_rotations()}\n\n  def _update_given_stones(\n      self, perceived_stones: Sequence[PerceivedStone]\n  ) -> None:\n    \"\"\"Updates the possible rotations and belief state given observed stones.\"\"\"\n    if not perceived_stones:\n      raise ValueError(\n          'Must pass perceived stones to update possible rotations.')\n\n    # Given the stones we see can we eliminate some possible rotations.\n    valid_rotations = []\n    for rotation in self.possible_rotations:\n      # For a rotation to be possible all stones have to go to corners of the\n      # cube and the change in latent variables has to be consistent with the\n      # change in reward (i.e. at least one stone map gives the observed\n      # rewards).\n      aligned_stones = []\n      rotation_valid = True\n      for stone in perceived_stones:\n        valid, coords = stones_and_potions.aligns(stone, rotation)\n        if valid:\n          aligned_stones.append(stones_and_potions.aligned_stone_from_coords(\n              coords, stone.reward))\n        else:\n          rotation_valid = False\n          break\n\n      if rotation_valid:\n        stone_maps = self._stone_maps_for_rotation[self._rotation_to_angles(\n            rotation)]\n        _, possible_stone_maps = get_possible_stone_maps(\n            stone_maps, aligned_stones)\n        self._stone_maps_for_rotation[self._rotation_to_angles(\n            rotation)] = possible_stone_maps\n        if possible_stone_maps:\n          valid_rotations.append(rotation)\n    assert valid_rotations, 'No rotation is valid.'\n    self.possible_rotations = valid_rotations\n    if self.rotation is None:\n      self.rotation = self.possible_rotations[0]\n      self._observed_stone = stones_and_potions.align(\n          perceived_stones[0], self.rotation)\n    elif not stones_and_potions.rotations_equal(\n        self.rotation, self.possible_rotations[0]):\n      new_to_old = stones_and_potions.get_new_mapping_to_old_mapping(\n          self.rotation, self.possible_rotations[0], self._observed_stone)\n      self.belief_state.update_stone_map(new_to_old)\n      self.rotation = self.possible_rotations[0]\n      self._observed_stone = stones_and_potions.align(\n          perceived_stones[0], self.rotation)\n\n  def new_trial(\n      self, perceived_stones: Counter[PerceivedStone],\n      perceived_potions: Counter[PerceivedPotion]\n  ) -> None:\n    \"\"\"Updates belief state given that new trial has started.\"\"\"\n    self._update_given_stones(list(perceived_stones.keys()))\n    aligned_stones = collections.Counter(\n        {stones_and_potions.align(stone, self.rotation).index(): count\n         for stone, count in perceived_stones.items()})\n    perceived_potion_indices = collections.Counter(\n        {potion.index(): count for potion, count in perceived_potions.items()})\n    self.belief_state.new_trial(aligned_stones, perceived_potion_indices)\n\n  def action_and_outcome(\n      self, stone: PerceivedStone, potion: PerceivedPotion,\n      result: PerceivedStone, precomputed: PrecomputedMaps\n  ) -> float:\n    self._update_given_stones([result])\n    stone_index = stones_and_potions.align(stone, self.rotation).index()\n    result_index = stones_and_potions.align(result, self.rotation).index()\n    bit_mask = stone_potion_bit_mask(stone_index, potion.index(), precomputed)\n    return self.belief_state.action_and_outcome(\n        stone_index, potion.index(), result_index, precomputed, bit_mask)\n\n  @property\n  def num_world_states(self) -> int:\n    return self.belief_state.num_world_states\n\n  @property\n  def num_potion_maps(self) -> int:\n    return self.belief_state.num_potion_maps\n\n  @property\n  def num_stone_maps(self) -> int:\n    return self.belief_state.num_stone_maps\n\n  @property\n  def num_graphs(self) -> int:\n    return self.belief_state.num_graphs\n\n  def partial_potion_map(\n      self, index_to_perm_index: np.ndarray\n  ) -> PartialPotionMap:\n    return self.belief_state.partial_potion_map(index_to_perm_index)\n\n  def partial_stone_map(self) -> PartialStoneMap:\n    return self.belief_state.partial_stone_map()\n\n  def partial_graph(\n      self, possible_partial_graph_indices: np.ndarray\n  ) -> PartialGraph:\n    return self.belief_state.partial_graph(possible_partial_graph_indices)\n\n\ndef search(\n    belief_state: BeliefState,\n    search_results: SearchResults,\n    bonus: int, precomputed: PrecomputedMaps,\n    depth: int = 0,\n    minimise_world_states: bool = False\n) -> ActionObjective:\n  \"\"\"Searches iteratively over actions and outcomes to find expected reward.\n\n  Conducts a depth first search over the DAG of available actions and the\n  possible outcomes. The reward for a latent stone is assumed to be the sum of\n  the latent values plus the passed bonus if all latent values are positive. We\n  do not deal with reward functions with arbitrary coefficient vectors and\n  offsets.\n\n  Args:\n    belief_state: The current belief state.\n    search_results: A cache of previously computed results mapping the belief\n      state as a bitfield to the best action and expected reward.\n    bonus: The extra reward we get by reaching the stone of reward 3.\n    precomputed: Precomputed maps used for speed.\n    depth: Number of actions taken in this search to reach this belief state.\n    minimise_world_states: Let the objective be to minimise the number of world\n      states at the end of the trial instead of to maximise the accumulated\n      reward. Actions selected will not necessarily produce reward but will\n      narrow down the possible chemistries, e.g. given a maximum value stone on\n      the first trial and a potion we would use the potion to find out the\n      effect even though it could reduce the value of the stone.\n\n  Returns:\n    The best action and maximum expected reward achievable from this state.\n  \"\"\"\n\n  # If we have searched from this belief state before return the cached result.\n  belief_state_bitfield = belief_state.to_bitfield()\n  if belief_state_bitfield in search_results:\n    return search_results[belief_state_bitfield]\n\n  # For all possible actions consider all possible outcomes and then search from\n  # the outcome.\n  action_rewards = {}\n  for stone_index, potion_index in belief_state.possible_actions(precomputed):\n    # This action means use or discard all stones.\n    if potion_index == END_TRIAL:\n      # Ending the trial so get the actual number of world states\n      if minimise_world_states:\n        expected_num_world_states = np.where(\n            belief_state.world_state_distribution.poss_world_states)[0].size\n      else:\n        raw_reward_count = [(precomputed.stone_to_reward[s], c) for s, c in\n                            belief_state.aligned_stones.items()]\n        reward_per_stone_type = [\n            0.0 if reward < 0 else c * (reward + bonus)\n            if reward == stones_and_potions.max_reward() else c * reward\n            for reward, c in raw_reward_count]\n        action_reward = sum(reward_per_stone_type)\n        best_action_depth = depth\n    else:\n      bit_mask = stone_potion_bit_mask(stone_index, potion_index, precomputed)\n      if belief_state.world_state_distribution.observed_no_effect_bits & bit_mask:\n        continue\n      # Using a potion on a stone could lead to a number of possible outcomes\n      # with various probabilities. The ideal observer must calculate what\n      # reward it can expect to obtain for each of these.\n      if minimise_world_states:\n        # The expected number of world states when the trial ends\n        expected_num_world_states = 0\n      else:\n        action_reward = 0.0\n        best_action_depth = 0.0\n      poss_outcomes, could_stay_still = (\n          belief_state.world_state_distribution.possible_outcomes(\n              potion_index, stone_index, precomputed))\n      if len(poss_outcomes) == 1:\n        # If there is only one possibility and it is staying still then there is\n        # no need to search this action as it will have no effect.\n        if could_stay_still:\n          continue\n        new_game_state = copy.deepcopy(belief_state)\n        new_game_state.use_potion(stone_index, potion_index, poss_outcomes[0])\n        _, objective = search(\n            new_game_state, search_results, bonus, precomputed, depth + 1,\n            minimise_world_states)\n        if minimise_world_states:\n          expected_num_world_states -= objective\n        else:\n          search_reward, neg_search_action_depth = objective\n          action_reward += search_reward\n          best_action_depth -= neg_search_action_depth\n      else:\n        for outcome in poss_outcomes:\n          new_game_state = copy.deepcopy(belief_state)\n          prob = new_game_state.action_and_outcome(\n              stone_index, potion_index, outcome, precomputed, bit_mask)\n          if prob > 0:\n            _, objective = search(\n                new_game_state, search_results, bonus, precomputed, depth + 1,\n                minimise_world_states)\n            if minimise_world_states:\n              expected_num_world_states -= prob * objective\n            else:\n              search_reward, neg_search_action_depth = objective\n              action_reward += prob * search_reward\n              best_action_depth -= prob * neg_search_action_depth\n    # Store the expected reward and the negative search depth so that when we\n    # maximise reward, if 2 actions have the same expected reward then we will\n    # take the action with the minimum search depth. This prevents us taking\n    # actions which do not harm our expected reward but do not help us.\n    if minimise_world_states:\n      action_rewards[\n          (stone_index, potion_index)] = -expected_num_world_states\n    else:\n      action_rewards[(stone_index, potion_index)] = (\n          action_reward, -best_action_depth)\n\n  result = max(action_rewards.items(), key=lambda a: a[1])\n\n  search_results[belief_state_bitfield] = result\n  return result\n\n\ndef ideal_observer(\n    init_game_state: BeliefState,\n    search_results: SearchResults,\n    bonus: int, precomputed: PrecomputedMaps, minimise_world_states: bool\n) -> ActionObjectiveAndSearchResults:\n  \"\"\"Runs the ideal observer given a set of stones and potions.\n\n  This runs an exhaustive search from the initial state over possible actions\n  and possible outcomes of those actions. It returns which action to take, the\n  expected reward and a set of search results for belief states encountered.\n\n  Args:\n    init_game_state: The initial belief state of the system.\n    search_results: Previously computed action and reward for belief states.\n    bonus: The additional reward for getting the best stone.\n    precomputed: Precomputed maps used for speed.\n    minimise_world_states: Let the objective be to minimise the number of world\n      states at the end of the trial instead of to maximise the accumulated\n      reward.\n\n  Returns:\n    The best action to take, the expected reward and a set of search results for\n    belief states encountered.\n  \"\"\"\n  # Set the number of bits required to fit all possible partial graph indices.\n  BeliefState.possible_partial_graph_num_bits = math.ceil(math.log2(\n      len(precomputed.partial_graph_index_to_possible_index)))\n\n  # Run the search over all possible next actions\n  action, objective = search(\n      init_game_state, search_results, bonus, precomputed,\n      minimise_world_states=minimise_world_states)\n  return action, objective, search_results\n", "meta": {"hexsha": "798e844eebc50e32501c14ee9c7f0c2322150312", "size": 43282, "ext": "py", "lang": "Python", "max_stars_repo_path": "dm_alchemy/ideal_observer/ideal_observer.py", "max_stars_repo_name": "locross93/dm_alchemy", "max_stars_repo_head_hexsha": "35449de51d56c427959ae6a3be13d6c6ab738be5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 182, "max_stars_repo_stars_event_min_datetime": "2021-02-08T15:25:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:46:23.000Z", "max_issues_repo_path": "dm_alchemy/ideal_observer/ideal_observer.py", "max_issues_repo_name": "locross93/dm_alchemy", "max_issues_repo_head_hexsha": "35449de51d56c427959ae6a3be13d6c6ab738be5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-02-12T10:42:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T23:59:45.000Z", "max_forks_repo_path": "dm_alchemy/ideal_observer/ideal_observer.py", "max_forks_repo_name": "locross93/dm_alchemy", "max_forks_repo_head_hexsha": "35449de51d56c427959ae6a3be13d6c6ab738be5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2021-02-08T20:37:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T20:54:14.000Z", "avg_line_length": 42.9811320755, "max_line_length": 83, "alphanum_fraction": 0.7240192228, "include": true, "reason": "import numpy", "num_tokens": 9726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.18530843677167178}}
{"text": "\"\"\"\nModule containing the basic class for handling particles properties.\n\"\"\"\n\nfrom copy import deepcopy\nfrom numpy import arange, ceil, empty, floor, int64\nfrom numpy import load as np_load\nfrom numpy import loadtxt, meshgrid, ndarray, pi, sqrt, triu_indices, zeros\nfrom numpy.random import Generator, PCG64\nfrom os.path import join\nfrom scipy.linalg import norm\nfrom scipy.spatial.distance import pdist\nfrom warnings import warn\n\nfrom .utilities.exceptions import ParticlesError, ParticlesWarning\n\n\nclass Particles:\n    \"\"\"\n    Class handling particles' properties.\n\n    Attributes\n    ----------\n    kB : float\n        Boltzmann constant.\n\n    fourpie0: float\n        Electrostatic constant :math:`4\\\\pi \\\\epsilon_0`.\n\n    pos : numpy.ndarray\n        Particles' positions.\n\n    vel : numpy.ndarray\n        Particles' velocities.\n\n    acc : numpy.ndarray\n        Particles' accelerations.\n\n    box_lengths : numpy.ndarray\n        Box sides' lengths.\n\n    pbox_lengths : numpy.ndarray\n        Initial particle box sides' lengths.\n\n    masses : numpy.ndarray\n        Mass of each particle. Shape = (attr:`sarkas.core.Parameters.total_num_ptcls`).\n\n    charges : numpy.ndarray\n        Charge of each particle. Shape = (attr:`sarkas.core.Parameters.total_num_ptcls`).\n\n    id : numpy.ndarray,\n        Species identifier. Shape = (attr:`sarkas.core.Parameters.total_num_ptcls`).\n\n    names : numpy.ndarray\n        Species' names. (attr:`sarkas.core.Parameters.total_num_ptcls`).\n\n    rdf_nbins : int\n        Number of bins for radial pair distribution.\n\n    no_grs : int\n        Number of independent :math:`g_{ij}(r)`.\n\n    rdf_hist : numpy.ndarray\n        Histogram array for the radial pair distribution function.\n\n    prod_dump_dir : str\n        Directory name where to store production phase's simulation's checkpoints. Default = 'dumps'.\n\n    eq_dump_dir : str\n        Directory name where to store equilibration phase's simulation's checkpoints. Default = 'dumps'.\n\n    total_num_ptcls : int\n        Total number of simulation's particles.\n\n    num_species : int\n        Number of species.\n\n    species_num : numpy.ndarray\n        Number of particles of each species. Shape = (attr:`sarkas.particles.Particles.num_species`).\n\n    dimensions : int\n        Number of non-zero dimensions. Default = 3.\n\n    potential_energy : float\n        Instantaneous value of the potential energy.\n\n    rnd_gen : numpy.random.Generator\n        Random number generator.\n\n    \"\"\"\n\n    def __init__(self):\n        self.mag_dump_dir = None\n        self.rdf_nbins = None\n        self.potential_energy = 0.0\n        self.kB = None\n        self.fourpie0 = None\n        self.prod_dump_dir = None\n        self.eq_dump_dir = None\n        self.box_lengths = None\n        self.pbox_lengths = None\n        self.total_num_ptcls = None\n        self.num_species = 1\n        self.species_num = None\n        self.dimensions = None\n        self.rnd_gen = None\n\n        self.pos = None\n        self.vel = None\n        self.acc = None\n\n        self.virial = None\n        self.pbc_cntr = None\n\n        self.names = None\n        self.id = None\n\n        self.species_initial_velocity = None\n        self.species_thermal_velocity = None\n\n        self.masses = None\n        self.charges = None\n        self.cyclotron_frequencies = None\n\n        self.no_grs = None\n        self.rdf_hist = None\n\n    def __repr__(self):\n        sortedDict = dict(sorted(self.__dict__.items(), key=lambda x: x[0].lower()))\n        disp = \"Particles( \\n\"\n        for key, value in sortedDict.items():\n            disp += \"\\t{} : {}\\n\".format(key, value)\n        disp += \")\"\n        return disp\n\n    def __copy__(self):\n        \"\"\"\n        Make a shallow copy of the object using copy by creating a new instance of the object and copying its __dict__.\"\"\"\n        # Create a new object\n        _copy = type(self)()\n        # copy the dictionary\n        _copy.__dict__.update(self.__dict__)\n        return _copy\n\n    def __deepcopy__(self, memodict: dict = {}):\n        \"\"\"Make a deepcopy of the object.\n\n        Parameters\n        ----------\n        memodict: dict\n            Dictionary of id's to copies\n\n        Returns\n        -------\n        _copy: :class:`sarkas.particles.Particles`\n            A new Particles class.\n        \"\"\"\n        id_self = id(self)  # memorization avoids unnecessary recursion\n        _copy = memodict.get(id_self)\n        if _copy is None:\n\n            # Make a shallow copy of all attributes\n            _copy = type(self)()\n            # Make a deepcopy of the mutable arrays using numpy copy function\n            for k, v in self.__dict__.items():\n                if isinstance(v, ndarray):\n                    _copy.__dict__[k] = v.copy()\n                else:\n                    _copy.__dict__[k] = deepcopy(v, memodict)\n\n        return _copy\n\n    def __getstate__(self):\n        \"\"\"Copy the object's state from self.__dict__ which contains all our instance attributes.\n        Always use the dict.copy() method to avoid modifying the original state.\n        Reference: https://docs.python.org/3/library/pickle.html#handling-stateful-objects\n        \"\"\"\n\n        state = self.__dict__.copy()\n        # Remove the data that is stored already\n        del state[\"pos\"]\n        del state[\"vel\"]\n        del state[\"acc\"]\n        del state[\"id\"]\n        del state[\"names\"]\n        del state[\"pbc_cntr\"]\n        del state[\"rdf_hist\"]\n        del state[\"virial\"]\n\n        return state\n\n    def __setstate__(self, state):\n        # Restore instance attributes.\n        self.__dict__.update(state)\n        # Initialize arrays\n        self.pos = zeros((self.__dict__[\"total_num_ptcls\"], 3))\n        self.vel = zeros((self.__dict__[\"total_num_ptcls\"], 3))\n        self.acc = zeros((self.__dict__[\"total_num_ptcls\"], 3))\n        self.id = zeros(self.__dict__[\"total_num_ptcls\"])\n        self.names = zeros(self.__dict__[\"total_num_ptcls\"])\n        self.pbc_cntr = zeros((self.__dict__[\"total_num_ptcls\"], 3))\n        self.rdf_hist = zeros((self.__dict__[\"rdf_nbins\"], self.__dict__[\"num_species\"], self.__dict__[\"num_species\"]))\n        self.virial = zeros((self.__dict__[\"dimensions\"], self.__dict__[\"dimensions\"], self.__dict__[\"total_num_ptcls\"]))\n\n    def copy_params(self, params):\n        \"\"\"\n        Copy necessary parameters.\n\n        Parameters\n        ----------\n        params: :class:`sarkas.core.Parameters`\n            Simulation's parameters.\n\n        \"\"\"\n\n        self.kB = params.kB\n        self.fourpie0 = params.fourpie0\n        self.prod_dump_dir = params.prod_dump_dir\n        self.eq_dump_dir = params.eq_dump_dir\n        self.box_lengths = params.box_lengths.copy()\n        self.pbox_lengths = params.pbox_lengths.copy()\n        self.total_num_ptcls = params.total_num_ptcls\n        self.total_num_density = params.total_num_density\n        self.num_species = params.num_species\n        self.species_num = params.species_num.copy()\n        self.dimensions = params.dimensions\n        self.load_method = params.load_method\n        self.restart_step = params.restart_step\n        self.particles_input_file = params.particles_input_file\n        self.load_perturb = params.load_perturb\n        self.load_rejection_radius = params.load_rejection_radius\n        self.load_halton_bases = params.load_halton_bases\n\n        if hasattr(params, \"np_per_side\"):\n            self.np_per_side = params.np_per_side\n\n        if hasattr(params, \"initial_lattice_config\"):\n            self.lattice_type = params.initial_lattice_config\n\n        if hasattr(params, \"load_gauss_sigma\"):\n            self.load_gauss_sigma = params.load_gauss_sigma.copy()\n\n        self.species_names = params.species_names\n\n        if hasattr(params, \"rdf_nbins\"):\n            self.rdf_nbins = params.rdf_nbins\n        else:\n            # nbins = 5% of the number of particles.\n            self.rdf_nbins = int(0.05 * params.total_num_ptcls)\n            params.rdf_nbins = self.rdf_nbins\n\n    def gaussian(self, mean, sigma, size):\n        \"\"\"\n        Initialize particles' velocities according to a normalized Maxwell-Boltzmann (Normal) distribution.\n        It calls ``numpy.random.Generator.normal``\n\n        Parameters\n        ----------\n        size : tuple\n            Size of the array to initialize. (no. of particles, dimensions).\n\n        mean : float\n            Center of the normal distribution.\n\n        sigma : float\n            Scale of the normal distribution.\n\n        Returns\n        -------\n         : numpy.ndarray\n            Particles property distributed according to a Normal probability density function.\n\n        \"\"\"\n        return self.rnd_gen.normal(mean, sigma, size)\n\n    def halton_reject(self, bases, r_reject):\n        \"\"\"\n        Place particles according to a Halton sequence from 0 to LP (the initial particle box length)\n        and uses a rejection radius to avoid placing particles to close to each other.\n\n        Parameters\n        ----------\n        bases : numpy.ndarray\n            Array of 3 ints each of which is a base for the Halton sequence.\n            Defualt: bases = array([2,3,5])\n\n        r_reject : float\n            Value of rejection radius.\n\n        \"\"\"\n\n        # Get bases\n        b1, b2, b3 = bases\n\n        # Allocate space and store first value from Halton\n        x = zeros(self.total_num_ptcls)\n        y = zeros(self.total_num_ptcls)\n        z = zeros(self.total_num_ptcls)\n\n        # Initialize particle counter and Halton counter\n        i = 1\n        k = 1\n\n        # Loop over all particles\n        while i < self.total_num_ptcls:\n\n            # Increment particle counter\n            n = k\n            m = k\n            p = k\n\n            # Determine x coordinate\n            f1 = 1\n            r1 = 0\n            while n > 0:\n                f1 /= b1\n                r1 += f1 * (n % int(b1))\n                n = floor(n / b1)\n            x_new = self.pbox_lengths[0] * r1  # new x value\n\n            # Determine y coordinate\n            f2 = 1\n            r2 = 0\n            while m > 0:\n                f2 /= b2\n                r2 += f2 * (m % int(b2))\n                m = floor(m / b2)\n            y_new = self.pbox_lengths[1] * r2  # new y value\n\n            # Determine z coordinate\n            f3 = 1\n            r3 = 0\n            while p > 0:\n                f3 /= b3\n                r3 += f3 * (p % int(b3))\n                p = floor(p / b3)\n            z_new = self.pbox_lengths[2] * r3  # new z value\n\n            # Check if particle was place too close relative to all other current particles\n            for j in range(len(x)):\n\n                # Flag for if particle is outside of cutoff radius (1 -> not inside rejection radius)\n                flag = 1\n\n                # Compute distance b/t particles for initial placement\n                x_diff = x_new - x[j]\n                y_diff = y_new - y[j]\n                z_diff = z_new - z[j]\n\n                # Periodic condition applied for minimum image\n                if x_diff < -self.pbox_lengths[0] / 2:\n                    x_diff = x_diff + self.pbox_lengths[0]\n                if x_diff > self.pbox_lengths[0] / 2:\n                    x_diff = x_diff - self.pbox_lengths[0]\n\n                if y_diff < -self.pbox_lengths[1] / 2:\n                    y_diff = y_diff + self.pbox_lengths[1]\n                if y_diff > self.pbox_lengths[1] / 2:\n                    y_diff = y_diff - self.pbox_lengths[1]\n\n                if z_diff < -self.pbox_lengths[2] / 2:\n                    z_diff = z_diff + self.pbox_lengths[2]\n                if z_diff > self.pbox_lengths[2] / 2:\n                    z_diff = z_diff - self.pbox_lengths[2]\n\n                # Compute distance\n                r = sqrt(x_diff**2 + y_diff**2 + z_diff**2)\n\n                # Check if new particle is below rejection radius. If not, break out and try again\n                if r <= r_reject:\n                    k += 1  # Increment Halton counter\n                    flag = 0  # New position not added (0 -> no longer outside reject r)\n                    break\n\n            # If flag true add new position\n            if flag == 1:\n                # Add new positions to arrays\n                x[i] = x_new\n                y[i] = y_new\n                z[i] = z_new\n\n                k += 1  # Increment Halton counter\n                i += 1  # Increment particle number\n\n        self.pos[:, 0] = x + self.box_lengths[0] / 2 - self.pbox_lengths[0] / 2\n        self.pos[:, 1] = y + self.box_lengths[1] / 2 - self.pbox_lengths[1] / 2\n        self.pos[:, 2] = z + self.box_lengths[2] / 2 - self.pbox_lengths[2] / 2\n\n    def initialize_accelerations(self):\n        \"\"\"\n        Initialize particles' accelerations.\n        \"\"\"\n        self.acc = zeros((self.total_num_ptcls, 3))\n\n    def initialize_arrays(self):\n        \"\"\"Initialize the needed arrays\"\"\"\n        self.pos = zeros((self.total_num_ptcls, 3))\n        self.vel = zeros((self.total_num_ptcls, 3))\n        self.acc = zeros((self.total_num_ptcls, 3))\n\n        self.pbc_cntr = zeros((self.total_num_ptcls, 3))\n        self.virial = zeros((3, 3, self.total_num_ptcls))\n\n        self.names = empty(self.total_num_ptcls, dtype=self.species_names.dtype)\n        self.id = zeros(self.total_num_ptcls, dtype=int64)\n\n        self.species_initial_velocity = zeros((self.num_species, 3))\n        self.species_thermal_velocity = zeros((self.num_species, 3))\n\n        self.masses = zeros(self.total_num_ptcls)  # mass of each particle\n        self.charges = zeros(self.total_num_ptcls)  # charge of each particle\n        self.cyclotron_frequencies = zeros(self.total_num_ptcls)\n\n        # No. of independent rdf\n        self.no_grs = int(self.num_species * (self.num_species + 1) / 2)\n\n        self.rdf_hist = zeros((self.rdf_nbins, self.num_species, self.num_species))\n\n    def initialize_positions(self):\n        \"\"\"\n        Initialize particles' positions based on the load method.\n        \"\"\"\n        # Particles Position Initialization\n        if self.load_method in [\n            \"equilibration_restart\",\n            \"eq_restart\",\n            \"magnetization_restart\",\n            \"mag_restart\",\n            \"production_restart\",\n            \"prod_restart\",\n        ]:\n            # checks\n            if self.restart_step is None:\n                raise AttributeError(\"Restart step not defined.\" \"Please define Parameters.restart_step.\")\n\n            if type(self.restart_step) is not int:\n                self.restart_step = int(self.restart_step)\n\n            if self.load_method[:2] == \"eq\":\n                self.load_from_restart(\"equilibration\", self.restart_step)\n            elif self.load_method[:2] == \"pr\":\n                self.load_from_restart(\"production\", self.restart_step)\n            elif self.load_method[:2] == \"ma\":\n                self.load_from_restart(\"magnetization\", self.restart_step)\n\n        elif self.load_method == \"file\":\n            # check\n            if not hasattr(self, \"particles_input_file\"):\n                raise AttributeError(\"Input file not defined.\" \"Please define Parameters.particles_input_file.\")\n            self.load_from_file(self.particles_input_file)\n\n        # position distribution.\n        elif self.load_method == \"lattice\":\n            self.lattice(self.load_perturb)\n\n        elif self.load_method == \"random_reject\":\n            # check\n            if not hasattr(self, \"load_rejection_radius\"):\n                raise AttributeError(\"Rejection radius not defined. \" \"Please define Parameters.load_rejection_radius.\")\n            self.random_reject(self.load_rejection_radius)\n\n        elif self.load_method == \"halton_reject\":\n            # check\n            if not hasattr(self, \"load_rejection_radius\"):\n                raise AttributeError(\"Rejection radius not defined. \" \"Please define Parameters.load_rejection_radius.\")\n            self.halton_reject(self.load_halton_bases, self.load_rejection_radius)\n\n        elif self.load_method in [\"uniform\", \"random_no_reject\"]:\n            self.pos = self.uniform_no_reject(\n                0.5 * self.box_lengths - 0.5 * self.pbox_lengths, 0.5 * self.box_lengths + 0.5 * self.pbox_lengths\n            )\n\n        elif self.load_method == \"gaussian\":\n            sp_start = 0\n            sp_end = 0\n            for sp, sp_num in enumerate(self.species_num):\n                sp_end += sp_num\n                self.pos[sp_start:sp_end, :] = self.gaussian(\n                    self.box_lengths[0] / 2.0, self.load_gauss_sigma[sp], (sp_num, 3)\n                )\n                sp_start += sp_num\n        else:\n            raise AttributeError(\"Incorrect particle placement scheme specified.\")\n\n    def initialize_velocities(self, species):\n        \"\"\"\n        Initialize particles' velocities based on the species input values. The velocities can be initialized from a\n        Maxwell-Boltzmann distribution or from a monochromatic distribution.\n\n        Parameters\n        ----------\n        species: list\n            List of :class:`sarkas.core.Spcies`.\n\n        \"\"\"\n        species_end = 0\n        species_start = 0\n        for ic, sp in enumerate(species):\n            if sp.name != \"electron_background\":\n                species_end += sp.num\n                self.species_initial_velocity[ic, :] = sp.initial_velocity\n\n                if sp.initial_velocity_distribution == \"boltzmann\":\n                    if isinstance(sp.temperature, (int, float)):\n                        sp_temperature = zeros(3)\n                        for d in range(self.dimensions):\n                            sp_temperature[d] = sp.temperature\n\n                    self.species_thermal_velocity[ic] = sqrt(self.dimensions * self.kB * sp_temperature / (2.0 * sp.mass))\n                    # Note gaussian(0.0, 0.0, N) = array of zeros\n                    self.vel[species_start:species_end, :] = self.gaussian(\n                        sp.initial_velocity, self.species_thermal_velocity[ic], (sp.num, 3)\n                    )\n\n                elif sp.initial_velocity_distribution == \"monochromatic\":\n                    vrms = sqrt(self.dimensions * self.kB * sp.temperature / sp.mass)\n                    self.vel[species_start:species_end, :] = vrms * self.random_unit_vectors(sp.num, self.dimensions)\n\n                species_start += sp.num\n\n    def kinetic_temperature(self):\n        \"\"\"\n        Calculate the kinetic energy and temperature of each species.\n\n        Returns\n        -------\n        K : numpy.ndarray\n            Kinetic energy of each species. Shape=(``num_species``).\n\n        T : numpy.ndarray\n            Temperature of each species. Shape=(``num_species``).\n\n        \"\"\"\n        K = zeros(self.num_species)\n        T = zeros(self.num_species)\n        const = 2.0 / (self.kB * self.species_num * self.dimensions)\n        kinetic = 0.5 * self.masses * (self.vel * self.vel).transpose()\n\n        species_start = 0\n        species_end = 0\n        for i, num in enumerate(self.species_num):\n            species_end += num\n            K[i] = kinetic[:, species_start:species_end].sum()\n            T[i] = const[i] * K[i]\n            species_start = species_end\n\n        return K, T\n\n    def lattice(self, perturb):\n        \"\"\"\n        Place particles in a simple cubic lattice with a slight perturbation ranging\n        from 0 to 0.5 times the lattice spacing.\n\n        Parameters\n        ----------\n        perturb : float\n            Value of perturbation, p, such that 0 <= p <= 1.\n\n        \"\"\"\n\n        # Check if perturbation is below maximum allowed. If not, default to maximum perturbation.\n        if perturb > 1:\n            warn(\"Random perturbation must not exceed 1. Setting perturb = 1.\", category=ParticlesWarning)\n\n        if self.lattice_type == \"simple_cubic\":\n            # Determining number of particles per side of simple cubic lattice\n            part_per_side = self.total_num_ptcls ** (1.0 / 3.0)  # Number of particles per side of cubic lattice\n\n            # Check if total number of particles is a perfect cube, if not, place more than the requested amount\n            if round(part_per_side) ** 3 != self.total_num_ptcls:\n                part_per_side = ceil(self.total_num_ptcls ** (1.0 / 3.0))\n                raise ParticlesError(\n                    f\"N = {self.total_num_ptcls} cannot be placed in a simple cubic lattice. \"\n                    f\"Use {int(part_per_side ** 3)} particles instead.\"\n                )\n\n            dx_lattice = self.pbox_lengths[0] / (self.total_num_ptcls ** (1.0 / 3.0))  # Lattice spacing\n            dy_lattice = self.pbox_lengths[1] / (self.total_num_ptcls ** (1.0 / 3.0))  # Lattice spacing\n            dz_lattice = self.pbox_lengths[2] / (self.total_num_ptcls ** (1.0 / 3.0))  # Lattice spacing\n\n            # Create x, y, and z position arrays\n            x = arange(0, self.pbox_lengths[0], dx_lattice) + 0.5 * dx_lattice\n            y = arange(0, self.pbox_lengths[1], dy_lattice) + 0.5 * dy_lattice\n            z = arange(0, self.pbox_lengths[2], dz_lattice) + 0.5 * dz_lattice\n\n            # Create a lattice with appropriate x, y, and z values based on arange\n            X, Y, Z = meshgrid(x, y, z)\n\n            # Perturb lattice\n            X += self.rnd_gen.uniform(-0.5, 0.5, X.shape) * perturb * dx_lattice\n            Y += self.rnd_gen.uniform(-0.5, 0.5, Y.shape) * perturb * dy_lattice\n            Z += self.rnd_gen.uniform(-0.5, 0.5, Z.shape) * perturb * dz_lattice\n\n            # Flatten the meshgrid values for plotting and computation\n            self.pos[:, 0] = X.ravel() + self.box_lengths[0] / 2 - self.pbox_lengths[0] / 2\n            self.pos[:, 1] = Y.ravel() + self.box_lengths[1] / 2 - self.pbox_lengths[1] / 2\n            self.pos[:, 2] = Z.ravel() + self.box_lengths[2] / 2 - self.pbox_lengths[2] / 2\n\n        elif self.lattice_type in [\"square\", \"tetragonal_2D\"]:\n            # Determining number of particles per side of simple cubic lattice\n            part_per_side = round(sqrt(self.total_num_ptcls))  # Number of particles per side of a square lattice\n\n            # Check if total number of particles is a perfect cube, if not, place more than the requested amount\n            if part_per_side**2 != self.total_num_ptcls:\n                raise ParticlesError(\n                    f\"N = {self.total_num_ptcls} cannot be placed in a square lattice. \"\n                    f\"Use {int(part_per_side ** 2)} particles instead.\"\n                )\n\n            dx_lattice = self.pbox_lengths[0] / sqrt(self.total_num_ptcls)  # Lattice spacing\n            dy_lattice = self.pbox_lengths[1] / sqrt(self.total_num_ptcls)  # Lattice spacing\n\n            # Create x, y, and z position arrays\n            x = arange(0, self.pbox_lengths[0], dx_lattice) + 0.5 * dx_lattice\n            y = arange(0, self.pbox_lengths[1], dy_lattice) + 0.5 * dy_lattice\n\n            # Create a lattice with appropriate x, y, and z values based on arange\n            X, Y = meshgrid(x, y)\n\n            # Perturb lattice\n            X += self.rnd_gen.uniform(-0.5, 0.5, X.shape) * perturb * dx_lattice\n            Y += self.rnd_gen.uniform(-0.5, 0.5, Y.shape) * perturb * dy_lattice\n\n            # Flatten the meshgrid values for plotting and computation\n            self.pos[:, 0] = X.ravel() + self.box_lengths[0] / 2 - self.pbox_lengths[0] / 2\n            self.pos[:, 1] = Y.ravel() + self.box_lengths[1] / 2 - self.pbox_lengths[1] / 2\n            self.pos[:, 2] = 0.0\n\n        elif self.lattice_type in [\"hexagonal\", \"triangular\"]:\n\n            # Determining number of particles per side of simple cubic lattice\n            part_per_side = round(sqrt(self.total_num_ptcls))  # Number of particles per side of cubic lattice\n\n            # Check if total number of particles is a perfect cube, if not, place more than the requested amount\n            if self.np_per_side[:2].prod() != part_per_side * (part_per_side + 1):\n                raise ParticlesError(\n                    f\"N = {self.total_num_ptcls} cannot be placed in an hexagonal lattice. \"\n                    f\"Use Nx = {part_per_side} and Ny = {part_per_side + 1} particles instead.\"\n                )\n\n            dx_lattice = self.pbox_lengths[0] / (self.np_per_side[0])  # Lattice spacing\n            dy_lattice = self.pbox_lengths[1] / (self.np_per_side[1])  # Lattice spacing\n\n            if self.np_per_side[0] > self.np_per_side[1]:\n                # Create x, y, and z position arrays\n                x = arange(0, self.pbox_lengths[0], dx_lattice)\n                y = arange(0, self.pbox_lengths[1], dy_lattice) + 0.5 * dy_lattice\n\n                # Create a lattice with appropriate x, y, and z values based on arange\n                X, Y = meshgrid(x, y)\n                # Shift the Y axis of every other row of particles\n                X[:, ::2] += 0.5 * dx_lattice\n\n            else:\n                # Create x, y, and z position arrays\n                x = arange(0, self.pbox_lengths[0], dx_lattice) + 0.5 * dx_lattice\n                y = arange(0, self.pbox_lengths[1], dy_lattice)\n\n                # Create a lattice with appropriate x, y, and z values based on arange\n                X, Y = meshgrid(x, y)\n                # Shift the Y axis of every other row of particles\n                Y[:, ::2] += 0.5 * dy_lattice\n\n            # Perturb lattice\n            X += self.rnd_gen.uniform(-0.5, 0.5, X.shape) * perturb * dx_lattice\n            Y += self.rnd_gen.uniform(-0.5, 0.5, Y.shape) * perturb * dy_lattice\n\n            # Flatten the meshgrid values for plotting and computation\n            self.pos[:, 0] = X.ravel() + self.box_lengths[0] / 2 - self.pbox_lengths[0] / 2\n            self.pos[:, 1] = Y.ravel() + self.box_lengths[1] / 2 - self.pbox_lengths[1] / 2\n            self.pos[:, 2] = 0.0\n\n    def load(self):\n        \"\"\"\n        Initialize particles' positions and velocities.\n        Positions are initialized based on the load method while velocities are chosen\n        from a Maxwell-Boltzmann distribution.\n\n        \"\"\"\n\n        warn(\n            \"Deprecated feature. It will be removed in the v2.0.0 release. \\n\"\n            \"Use parameters.calc_electron_properties(species). You need to pass the species list.\",\n            category=DeprecationWarning,\n        )\n\n        self.initialize_positions()\n\n    def load_from_file(self, f_name):\n        \"\"\"\n        Load particles' data from a specific file.\n\n        Parameters\n        ----------\n        f_name : str\n            Filename\n        \"\"\"\n        pv_data = loadtxt(f_name)\n        if not (pv_data.shape[0] == self.total_num_ptcls):\n            msg = (\n                f\"Number of particles is not same between input file and initial p & v data file. \\n \"\n                f\"Input file: N = {self.total_num_ptcls}, load data: N = {pv_data.shape[0]}\"\n            )\n            raise ParticlesError(msg)\n\n        self.pos[:, 0] = pv_data[:, 0]\n        self.pos[:, 1] = pv_data[:, 1]\n        self.pos[:, 2] = pv_data[:, 2]\n\n        self.vel[:, 0] = pv_data[:, 3]\n        self.vel[:, 1] = pv_data[:, 4]\n        self.vel[:, 2] = pv_data[:, 5]\n\n    def load_from_restart(self, phase, it):\n        \"\"\"\n        Load particles' data from a checkpoint of a previous run\n\n        Parameters\n        ----------\n        it : int\n            Timestep.\n\n        phase: str\n            Restart phase.\n\n        \"\"\"\n        if phase == \"equilibration\":\n            file_name = join(self.eq_dump_dir, \"checkpoint_\" + str(it) + \".npz\")\n            data = np_load(file_name, allow_pickle=True)\n            self.id = data[\"id\"]\n            self.names = data[\"names\"]\n            self.pos = data[\"pos\"]\n            self.vel = data[\"vel\"]\n            self.acc = data[\"acc\"]\n\n        elif phase == \"production\":\n            file_name = join(self.prod_dump_dir, \"checkpoint_\" + str(it) + \".npz\")\n            data = np_load(file_name, allow_pickle=True)\n            self.id = data[\"id\"]\n            self.names = data[\"names\"]\n            self.pos = data[\"pos\"]\n            self.vel = data[\"vel\"]\n            self.acc = data[\"acc\"]\n            self.pbc_cntr = data[\"cntr\"]\n            self.rdf_hist = data[\"rdf_hist\"]\n\n        elif phase == \"magnetization\":\n            file_name = join(self.mag_dump_dir, \"checkpoint_\" + str(it) + \".npz\")\n            data = np_load(file_name, allow_pickle=True)\n            self.id = data[\"id\"]\n            self.names = data[\"names\"]\n            self.pos = data[\"pos\"]\n            self.vel = data[\"vel\"]\n            self.acc = data[\"acc\"]\n            self.pbc_cntr = data[\"cntr\"]\n            self.rdf_hist = data[\"rdf_hist\"]\n\n    def potential_energies(self):\n        \"\"\"\n        Calculate the potential energies of each species.\n\n        Returns\n        -------\n        P : numpy.ndarray\n            Potential energy of each species. Shape=(``num_species``).\n\n        \"\"\"\n        P = zeros(self.num_species)\n\n        species_start = 0\n        species_end = 0\n        for i, num in enumerate(self.species_num):\n            species_end += num\n\n            # TODO: Consider writing a numba function speedup in distance calculation\n            species_charges = self.charges[species_start:species_end]\n            uti = triu_indices(species_charges.size, k=1)\n            species_charge2 = species_charges[uti[0]] * species_charges[uti[1]]\n            species_distances = pdist(self.pos[species_start:species_end, :])\n            potential = species_charge2 / self.fourpie0 / species_distances\n            P[i] = potential.sum()\n\n            species_start = species_end\n\n        return P\n\n    def random_reject(self, r_reject):\n        \"\"\"\n        Place particles by sampling a uniform distribution from 0 to LP (the initial particle box length)\n        and uses a rejection radius to avoid placing particles to close to each other.\n\n        Parameters\n        ----------\n        r_reject : float\n            Value of rejection radius.\n        \"\"\"\n\n        # Initialize Arrays\n        x = zeros(self.total_num_ptcls)\n        y = zeros(self.total_num_ptcls)\n        z = zeros(self.total_num_ptcls)\n\n        # Set first x, y, and z positions\n        x_new = self.rnd_gen.uniform(0, self.pbox_lengths[0])\n        y_new = self.rnd_gen.uniform(0, self.pbox_lengths[1])\n        z_new = self.rnd_gen.uniform(0, self.pbox_lengths[2])\n\n        # Append to arrays\n        x[0] = x_new\n        y[0] = y_new\n        z[0] = z_new\n\n        # Particle counter\n        i = 1\n\n        cntr_reject = 0\n        cntr_total = 0\n        # Loop to place particles\n        while i < self.total_num_ptcls:\n\n            # Set x, y, and z positions\n            x_new = self.rnd_gen.uniform(0.0, self.pbox_lengths[0])\n            y_new = self.rnd_gen.uniform(0.0, self.pbox_lengths[1])\n            z_new = self.rnd_gen.uniform(0.0, self.pbox_lengths[2])\n\n            # Check if particle was place too close relative to all other current particles\n            for j in range(len(x)):\n\n                # Flag for if particle is outside of cutoff radius (True -> not inside rejection radius)\n                flag = 1\n\n                # Compute distance b/t particles for initial placement\n                x_diff = x_new - x[j]\n                y_diff = y_new - y[j]\n                z_diff = z_new - z[j]\n\n                # periodic condition applied for minimum image\n                if x_diff < -self.pbox_lengths[0] / 2:\n                    x_diff += self.pbox_lengths[0]\n                if x_diff > self.pbox_lengths[0] / 2:\n                    x_diff -= self.pbox_lengths[0]\n\n                if y_diff < -self.pbox_lengths[1] / 2:\n                    y_diff += self.pbox_lengths[1]\n                if y_diff > self.pbox_lengths[1] / 2:\n                    y_diff -= self.pbox_lengths[1]\n\n                if z_diff < -self.pbox_lengths[2] / 2:\n                    z_diff += self.pbox_lengths[2]\n                if z_diff > self.pbox_lengths[2] / 2:\n                    z_diff -= self.pbox_lengths[2]\n\n                # Compute distance\n                r = sqrt(x_diff**2 + y_diff**2 + z_diff**2)\n\n                # Check if new particle is below rejection radius. If not, break out and try again\n                if r <= r_reject:\n                    flag = 0  # new position not added (False -> no longer outside reject r)\n                    cntr_reject += 1\n                    cntr_total += 1\n                    break\n\n            # If flag true add new position\n            if flag == 1:\n                x[i] = x_new\n                y[i] = y_new\n                z[i] = z_new\n\n                # Increment particle number\n                i += 1\n                cntr_total += 1\n\n        self.pos[:, 0] = x + self.box_lengths[0] / 2 - self.pbox_lengths[0] / 2\n        self.pos[:, 1] = y + self.box_lengths[1] / 2 - self.pbox_lengths[1] / 2\n        self.pos[:, 2] = z + self.box_lengths[2] / 2 - self.pbox_lengths[2] / 2\n\n    def random_unit_vectors(self, num_ptcls, dimensions):\n        \"\"\"\n        Initialize random unit vectors for particles' velocities (e.g. for monochromatic energies but random velocities)\n        It calls ``numpy.random.Generator.normal``\n\n        Parameters\n        ----------\n        num_ptcls : int\n            Number of particles to initialize.\n\n        dimensions : int\n            Number of non-zero dimensions.\n\n        Returns\n        -------\n        uvec : numpy.ndarray\n            Random unit vectors of specified dimensions for all particles\n\n        \"\"\"\n\n        uvec = self.rnd_gen.normal(size=(num_ptcls, dimensions))\n        # Broadcasting\n        uvec /= norm(uvec).reshape(num_ptcls, 1)\n\n        return uvec\n\n    def remove_drift(self):\n        \"\"\"\n        Enforce conservation of total linear momentum. Updates particles velocities\n        \"\"\"\n        species_start = 0\n        species_end = 0\n        momentum = self.masses * self.vel.transpose()\n        for ic, nums in enumerate(self.species_num):\n            species_end += nums\n            P = momentum[:, species_start:species_end].sum(axis=1)\n            self.vel[species_start:species_end, :] -= P / (nums * self.masses[species_end - 1])\n            species_start = species_end\n\n    def setup(self, params, species):\n        \"\"\"\n        Initialize class' attributes\n\n        Parameters\n        ----------\n        params: :class:`sarkas.core.Parameters`\n            Simulation's parameters.\n\n        species : list\n            List of :meth:`sarkas.plasma.Species` objects.\n\n        \"\"\"\n\n        if hasattr(params, \"rand_seed\"):\n            self.rand_seed = params.rand_seed\n            self.rnd_gen = Generator(PCG64(params.rand_seed))\n        else:\n            self.rnd_gen = Generator(PCG64())\n\n        self.copy_params(params)\n        self.initialize_arrays()\n        self.update_attributes(species)\n        self.initialize_positions()\n        self.initialize_velocities(species)\n        self.initialize_accelerations()\n\n    def uniform_no_reject(self, mins, maxs):\n        \"\"\"\n        Randomly distribute particles along each direction.\n\n        Parameters\n        ----------\n        mins : float\n            Minimum value of the range of a uniform distribution.\n\n        maxs : float\n            Maximum value of the range of a uniform distribution.\n\n        Returns\n        -------\n         : numpy.ndarray\n            Particles' property, e.g. pos, vel. Shape = (``total_num_ptcls``, 3).\n\n        \"\"\"\n\n        return self.rnd_gen.uniform(mins, maxs, (self.total_num_ptcls, 3))\n\n    def update_attributes(self, species):\n        \"\"\"\n        Assign particles attributes.\n\n        Parameters\n        ----------\n        species : list\n            List of :class:`sarkas.plasma.Species` objects.\n\n        \"\"\"\n        species_end = 0\n        species_start = 0\n\n        for ic, sp in enumerate(species):\n            if sp.name != \"electron_background\":\n                species_end += sp.num\n\n                self.names[species_start:species_end] = sp.name\n                self.masses[species_start:species_end] = sp.mass\n\n                if hasattr(sp, \"charge\"):\n                    self.charges[species_start:species_end] = sp.charge\n                else:\n                    self.charges[species_start:species_end] = 1.0\n\n                if hasattr(sp, \"cyclotron_frequency\"):\n                    self.cyclotron_frequencies[species_start:species_end] = sp.cyclotron_frequency\n\n                self.id[species_start:species_end] = ic\n                species_start += sp.num\n", "meta": {"hexsha": "b0209215b7b62817bfae06e4e4153a7d150a56ea", "size": 36292, "ext": "py", "lang": "Python", "max_stars_repo_path": "sarkas/particles.py", "max_stars_repo_name": "lucianogsilvestri/sarkas", "max_stars_repo_head_hexsha": "f4ab00014d09976561fbd4349b9d0610e47a61e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sarkas/particles.py", "max_issues_repo_name": "lucianogsilvestri/sarkas", "max_issues_repo_head_hexsha": "f4ab00014d09976561fbd4349b9d0610e47a61e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sarkas/particles.py", "max_forks_repo_name": "lucianogsilvestri/sarkas", "max_forks_repo_head_hexsha": "f4ab00014d09976561fbd4349b9d0610e47a61e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5110663984, "max_line_length": 122, "alphanum_fraction": 0.5710073845, "include": true, "reason": "from numpy,from scipy", "num_tokens": 8563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.1852953173168032}}
{"text": "import datetime\nimport logging\nimport os\nimport numpy as np\nfrom multiprocessing import Pool\nfrom functools import partial\nimport us\nimport pickle\nimport simplejson as json\nimport copy\nfrom collections import defaultdict\nfrom pyseir.models.seir_model import SEIRModel\nfrom pyseir.parameters.parameter_ensemble_generator import ParameterEnsembleGenerator\nfrom pyseir.models.suppression_policies import generate_empirical_distancing_policy, generate_covidactnow_scenarios\nfrom pyseir import load_data\nfrom pyseir.reports.county_report import CountyReport\nfrom pyseir.utils import get_run_artifact_path, RunArtifact, RunMode\nfrom pyseir.load_data import FAULTY_HOSPITAL_DATA_STATES\nfrom libs.datasets.dataset_utils import AggregationLevel\nfrom libs.datasets import CovidTrackingDataSource\nfrom libs.datasets import JHUDataset\n\n\n_logger = logging.getLogger(__name__)\n\n\ncompartment_to_capacity_attr_map = {\n    'HGen': 'beds_general',\n    'HICU': 'beds_ICU',\n    'HVent': 'ventilators'\n}\n\n\nclass EnsembleRunner:\n    \"\"\"\n    The EnsembleRunner executes a collection of N_samples simulations based on\n    priors defined in the ParameterEnsembleGenerator.\n\n    Parameters\n    ----------\n    fips: str\n        County or state fips code\n    n_years: int\n        Number of years to simulate\n    n_samples: int\n        Ensemble size to run for each suppression policy.\n    suppression_policy: list(float or str)\n        List of suppression policies to apply.\n    output_percentiles: list\n        List of output percentiles desired. These will be computed for each\n        compartment.\n    run_mode: str\n        Individual parameters can be overridden here.\n    min_hospitalization_threshold: int\n        Require this number of hospitalizations before initializing based on\n        observations. Fallback to cases otherwise.\n    hospitalization_to_confirmed_case_ratio: float\n        When hospitalization data is not available directly, this fraction of\n        confirmed cases defines the initial number of hospitalizations.\n    covid_timeseries: NoneType or DataSet\n        Can be optionally passed in to prevent reloading.\n    \"\"\"\n    def __init__(self, fips, n_years=.5, n_samples=250,\n                 suppression_policy=(0.35, 0.5, 0.75, 1),\n                 skip_plots=False,\n                 output_percentiles=(5, 25, 32, 50, 75, 68, 95),\n                 generate_report=True,\n                 run_mode=RunMode.DEFAULT,\n                 min_hospitalization_threshold=5,\n                 hospitalization_to_confirmed_case_ratio=1 / 4,\n                 covid_timeseries=None):\n\n        self.fips = fips\n        self.agg_level = AggregationLevel.COUNTY if len(fips) == 5 else AggregationLevel.STATE\n\n        self.t_list = np.linspace(0, int(365 * n_years), int(365 * n_years))\n        self.skip_plots = skip_plots\n        self.run_mode = RunMode(run_mode)\n        self.hospitalizations_for_state = None\n        self.min_hospitalization_threshold = min_hospitalization_threshold\n        self.hospitalization_to_confirmed_case_ratio = hospitalization_to_confirmed_case_ratio\n\n        if self.agg_level is AggregationLevel.COUNTY:\n            self.county_metadata = load_data.load_county_metadata_by_fips(fips)\n            self.state_abbr = us.states.lookup(self.county_metadata['state']).abbr\n            self.state_name = us.states.lookup(self.county_metadata['state']).name\n\n            self.output_file_report = get_run_artifact_path(self.fips, RunArtifact.ENSEMBLE_REPORT)\n            self.output_file_data = get_run_artifact_path(self.fips, RunArtifact.ENSEMBLE_RESULT)\n\n        else:\n            self.state_abbr = us.states.lookup(self.fips).abbr\n            self.state_name = us.states.lookup(self.fips).name\n\n            self.output_file_report = None\n            self.output_file_data = get_run_artifact_path(self.fips, RunArtifact.ENSEMBLE_RESULT)\n\n        county_fips = None if self.agg_level is AggregationLevel.STATE else self.fips\n\n        if not covid_timeseries:\n            covid_timeseries = JHUDataset.local().timeseries()\n        else:\n            covid_timeseries = covid_timeseries.timeseries()\n\n        self.covid_data = covid_timeseries\\\n            .get_subset(self.agg_level, country='USA', state=self.state_abbr) \\\n            .get_data(country='USA', state=self.state_abbr, fips=county_fips) \\\n            .sort_values('date')\n\n        os.makedirs(os.path.dirname(self.output_file_data), exist_ok=True)\n        if self.output_file_report:\n            os.makedirs(os.path.dirname(self.output_file_report), exist_ok=True)\n\n        self.output_percentiles = output_percentiles\n        self.n_samples = n_samples\n        self.n_years = n_years\n        # TODO: Will be soon replaced with loaders for all the inferred params.\n        # self.t0 = fit_results.load_t0(fips)\n        self.date_generated = datetime.datetime.utcnow().isoformat()\n        self.suppression_policy = suppression_policy\n        self.summary = copy.deepcopy(self.__dict__)\n        self.summary.pop('t_list')\n        self.generate_report = generate_report\n\n        self.suppression_policies = None\n        self.override_params = dict()\n        self.init_run_mode()\n\n        self.all_outputs = {}\n\n    def get_initial_hospitalizations(self, use_cases=False):\n        \"\"\"\n        Attempt a two level hierarchy of lookups for hospitalizations.\n\n        1. Direct hospitalizations if available\n        2. Inferred from covid case data.\n\n        Returns\n        -------\n        latest_date: date\n            Last date of data available.\n        hospitalizations_total: int\n            Estimated number of current hospitalizations total.\n        \"\"\"\n        fips = None if self.agg_level is AggregationLevel.STATE else self.fips\n\n        hospitalization_data = CovidTrackingDataSource.local()\\\n            .timeseries()\\\n            .get_subset(self.agg_level, country='USA', state=self.state_abbr)\\\n            .get_data(state=self.state_abbr, country='USA', fips=fips)\\\n            .sort_values('date')\n\n        # If there are enough hospitalizations, use those to define initial conditions.\n        if not use_cases and len(hospitalization_data) > 0 and self.state_abbr not in FAULTY_HOSPITAL_DATA_STATES:\n            latest_date = hospitalization_data.iloc[-1]['date'].date()\n            n_current = hospitalization_data.iloc[-1]['current_hospitalized']\n            if n_current > self.min_hospitalization_threshold and not np.isnan(n_current):\n                hospitalizations_total = n_current\n\n            # TODO: We will need a better estimator for current hospitalizations\n            # in cases where cumulative is not available. Punting on this until\n            # post-release.\n            else:\n                hospitalizations_total = hospitalization_data.iloc[-1]['cumulative_hospitalized']\n\n        # Fallback to case data if not.\n        else:\n            latest_date = self.covid_data.date.max()\n            hospitalizations_total = self.covid_data.cases.max() * self.hospitalization_to_confirmed_case_ratio\n        return latest_date, hospitalizations_total\n\n    def init_run_mode(self):\n        \"\"\"\n        Based on the run mode, generate suppression policies and ensemble\n        parameters.  This enables different model combinations and project\n        phases.\n        \"\"\"\n        self.suppression_policies = dict()\n\n        if self.run_mode is RunMode.CAN_BEFORE_HOSPITALIZATION:\n            self.n_samples = 1\n\n            for scenario in ['no_intervention', 'flatten_the_curve', 'full_containment', 'social_distancing']:\n                R0 = 3.6\n                self.override_params['R0'] = R0\n                policy = generate_covidactnow_scenarios(t_list=self.t_list, R0=R0, t0=datetime.datetime.today(), scenario=scenario)\n                self.suppression_policies[f'suppression_policy__{scenario}'] = policy\n                self.override_params = ParameterEnsembleGenerator(\n                    self.fips, N_samples=500, t_list=self.t_list, suppression_policy=policy).get_average_seir_parameters()\n\n            self.override_params['mortality_rate_no_general_beds'] = 0.0\n            self.override_params['mortality_rate_from_hospital'] = 0.0\n            self.override_params['mortality_rate_from_ICU'] = 0.40\n            self.override_params['mortality_rate_no_ICU_beds'] = 1.0\n\n            self.override_params['hospitalization_length_of_stay_general'] = 6\n            self.override_params['hospitalization_length_of_stay_icu'] = 13\n            self.override_params['hospitalization_length_of_stay_icu_and_ventilator'] = 14\n\n            self.override_params['hospitalization_rate_general'] = 0.0727\n            self.override_params['hospitalization_rate_icu'] = 0.13 * self.override_params['hospitalization_rate_general']\n            self.override_params['beds_ICU'] = 0\n            self.override_params['symptoms_to_hospital_days'] = 6\n\n            if len(self.covid_data) > 0 and self.covid_data.cases.max() > 0:\n                self.t0 = self.covid_data.date.max()\n                self.t0, hospitalizations_total = self.get_initial_hospitalizations()\n\n                self.override_params['HGen_initial'] = hospitalizations_total * (1 - self.override_params['hospitalization_rate_icu'] / self.override_params['hospitalization_rate_general'])\n                self.override_params['HICU_initial'] = hospitalizations_total * self.override_params['hospitalization_rate_icu']/ self.override_params['hospitalization_rate_general']\n                self.override_params['HICUVent_initial'] = self.override_params['HICU_initial'] * self.override_params['fraction_icu_requiring_ventilator']\n                self.override_params['I_initial'] = hospitalizations_total / self.override_params['hospitalization_rate_general']\n\n                # The following two params disable the asymptomatic compartment.\n                self.override_params['A_initial'] = 0\n                self.override_params['gamma'] = 1   # 100% of Exposed go to the infected bucket.\n\n                # 0.6 is a ~ steady state for the exposed bucket initialization at Reff ~ 1.2\n                self.override_params['E_initial'] = 0.6 * (self.override_params['I_initial'] + self.override_params['A_initial'])\n                self.override_params['D_initial'] = self.covid_data.deaths.max()\n\n            else:\n                self.t0 = datetime.datetime.today()\n                self.override_params['I_initial'] = 1\n                self.override_params['A_initial'] = 0\n                self.override_params['gamma'] = 1  # 100% of Exposed go to the infected bucket.\n\n        elif self.run_mode is RunMode.CAN_BEFORE_HOSPITALIZATION_NEW_PARAMS:\n            self.n_samples = 1\n\n            for scenario in ['no_intervention', 'flatten_the_curve', 'inferred', 'social_distancing']:\n                R0 = 3.6\n                self.override_params['R0'] = R0\n                if scenario != 'inferred':\n                    policy = generate_covidactnow_scenarios(t_list=self.t_list, R0=R0, t0=datetime.datetime.today(), scenario=scenario)\n                else:\n                    policy = None\n                self.suppression_policies[f'suppression_policy__{scenario}'] = policy\n                self.override_params = ParameterEnsembleGenerator(\n                    self.fips, N_samples=500, t_list=self.t_list, suppression_policy=policy).get_average_seir_parameters()\n\n            if len(self.covid_data) > 0 and self.covid_data.cases.max() > 0:\n                self.t0 = self.covid_data.date.max()\n                self.t0, hospitalizations_total = self.get_initial_hospitalizations()\n\n                self.override_params['HGen_initial'] = hospitalizations_total * (1 - self.override_params['hospitalization_rate_icu'])\n                self.override_params['HICU_initial'] = hospitalizations_total * self.override_params['hospitalization_rate_icu']\n                self.override_params['HICUVent_initial'] = self.override_params['HICU_initial'] * self.override_params['fraction_icu_requiring_ventilator']\n                self.override_params['I_initial'] = hospitalizations_total / self.override_params['hospitalization_rate_general']\n\n                # The following two params disable the asymptomatic compartment.\n                self.override_params['A_initial'] = 0\n                self.override_params['gamma'] = 1   # 100% of Exposed go to the infected bucket.\n\n                # 1.2 is a ~ steady state for the exposed bucket initialization.\n                self.override_params['E_initial'] = 0.6 * (self.override_params['I_initial'] + self.override_params['A_initial'])\n                self.override_params['D_initial'] = self.covid_data.deaths.max()\n\n        elif self.run_mode is RunMode.DEFAULT:\n            for suppression_policy in self.suppression_policy:\n                self.suppression_policies[f'suppression_policy__{suppression_policy}']= generate_empirical_distancing_policy(\n                    t_list=self.t_list, fips=self.fips, future_suppression=suppression_policy)\n            self.override_params = dict()\n        else:\n            raise ValueError('Invalid run mode.')\n\n    @staticmethod\n    def _run_single_simulation(parameter_set):\n        \"\"\"\n        Run a single simulation instance.\n\n        Parameters\n        ----------\n        parameter_set: dict\n            Params passed to the SEIR model\n\n        Returns\n        -------\n        model: SEIRModel\n            Executed model.\n        \"\"\"\n        model = SEIRModel(**parameter_set)\n        model.run()\n        return model\n\n    def run_ensemble(self):\n        \"\"\"\n        Run an ensemble of models for each suppression policy nad generate the\n        output report / results dataset.\n        \"\"\"\n        for suppression_policy_name, suppression_policy in self.suppression_policies.items():\n\n            logging.info(f'Running simulation ensemble for {self.state_name} {self.fips} {suppression_policy_name}')\n\n            if suppression_policy_name == 'suppression_policy__inferred':\n\n                artifact_path = get_run_artifact_path(self.fips, RunArtifact.MLE_FIT_MODEL)\n                if os.path.exists(artifact_path):\n                    with open(artifact_path, 'rb') as f:\n                        model_ensemble = [pickle.load(f)]\n                else:\n                    logging.warning(f'No MLE model found for {self.state_name}: {self.fips}. Skipping.')\n            else:\n                parameter_sampler = ParameterEnsembleGenerator(\n                    fips=self.fips,\n                    N_samples=self.n_samples,\n                    t_list=self.t_list,\n                    suppression_policy=suppression_policy)\n                parameter_ensemble = parameter_sampler.sample_seir_parameters(override_params=self.override_params)\n                model_ensemble = list(map(self._run_single_simulation, parameter_ensemble))\n\n            if self.agg_level is AggregationLevel.COUNTY:\n                self.all_outputs['county_metadata'] = self.county_metadata\n                self.all_outputs['county_metadata']['age_distribution'] = list(self.all_outputs['county_metadata']['age_distribution'])\n                self.all_outputs['county_metadata']['age_bins'] = list(self.all_outputs['county_metadata']['age_distribution'])\n\n            self.all_outputs[f'{suppression_policy_name}'] = self._generate_output_for_suppression_policy(model_ensemble)\n\n        if self.generate_report and self.output_file_report:\n            report = CountyReport(self.fips,\n                                  model_ensemble=model_ensemble,\n                                  county_outputs=self.all_outputs,\n                                  filename=self.output_file_report,\n                                  summary=self.summary)\n            report.generate_and_save()\n\n        with open(self.output_file_data, 'w') as f:\n            json.dump(self.all_outputs, f)\n\n    @staticmethod\n    def _generate_compartment_arrays(model_ensemble):\n        \"\"\"\n        Given a collection of SEIR models, convert these to numpy arrays for\n        each compartment, with axis 0 being the model index and axis 1 being the\n        timestep.\n\n        Parameters\n        ----------\n        model_ensemble: list(SEIRModel)\n\n        Returns\n        -------\n        value_stack: array[n_samples, time steps]\n            Array with the stacked model output results.\n        \"\"\"\n        compartments = {key: [] for key in model_ensemble[0].results.keys() if key not in ('t_list', 'county_metadata')}\n        for model in model_ensemble:\n            for key in compartments:\n                compartments[key].append(model.results[key])\n\n        return {key: np.vstack(value_stack) for key, value_stack in compartments.items()}\n\n    @staticmethod\n    def _get_surge_window(model_ensemble, compartment):\n        \"\"\"\n        Calculate the list of surge window starts and ends for an ensemble.\n\n        Parameters\n        ----------\n        model_ensemble: list(SEIRModel)\n            List of models to compute the surge windows for.\n        compartment: str\n            Compartment to calculate the surge window over.\n\n        Returns\n        -------\n        surge_start: np.array\n            For each model, the surge start window time (since beginning of\n            simulation). NaN implies no surge occurred.\n        surge_end: np.array\n            For each model, the surge end window time (since beginning of\n            simulation). NaN implies no surge occurred.\n        \"\"\"\n        surge_start = []\n        surge_end = []\n        for m in model_ensemble:\n            # Find the first t where overcapacity occurs\n            surge_start_idx = np.argwhere(m.results[compartment] > getattr(m, compartment_to_capacity_attr_map[compartment]))\n            surge_start.append(m.t_list[surge_start_idx[0][0]] if len(surge_start_idx) > 0 else float('NaN'))\n\n            # Reverse the t-list and capacity and do the same.\n            surge_end_idx = np.argwhere(m.results[compartment][::-1] > getattr(m, compartment_to_capacity_attr_map[compartment]))\n            surge_end.append(m.t_list[::-1][surge_end_idx[0][0]] if len(surge_end_idx) > 0 else float('NaN'))\n\n        return surge_start, surge_end\n\n    def _detect_peak_time_and_value(self, value_stack, t_list):\n        \"\"\"\n        Compute the peak times for each compartment by finding the arg\n        max, and selecting the corresponding time.\n\n        Parameters\n        ----------\n        value_stack: array[n_samples, time steps]\n            Array with the stacked model output results.\n        t_list: array\n            Array of timesteps.\n\n        Returns\n        -------\n        peak_data: dict\n            For each confidence interval, produce key, value pairs for e.g.\n                - peak_time_cl50\n                - peak_value_cl50\n            Also add peak_value_mean.\n        \"\"\"\n        peak_indices = value_stack.argmax(axis=1)\n        peak_times = [t_list[peak_index] for peak_index in peak_indices]\n        values_at_peak_index = [val[idx] for val, idx in zip(value_stack, peak_indices)]\n\n        peak_data = dict()\n        for percentile in self.output_percentiles:\n            peak_data['peak_value_ci%i' % percentile] = np.percentile(values_at_peak_index, percentile).tolist()\n            peak_data['peak_time_ci%i' % percentile] = np.percentile(peak_times, percentile).tolist()\n\n        peak_data['peak_value_mean'] = np.mean(values_at_peak_index).tolist()\n        return peak_data\n\n    def _generate_output_for_suppression_policy(self, model_ensemble):\n        \"\"\"\n        Generate output data for a given suppression policy.\n\n        Parameters\n        ----------\n        model_ensemble: list(SEIRModel)\n            List of models to compute the surge windows for.\n\n        Returns\n        -------\n        outputs: dict\n            Output data for this suppression policc ensemble.\n        \"\"\"\n        outputs = defaultdict(dict)\n        outputs['t_list'] = model_ensemble[0].t_list.tolist()\n\n        # ------------------------------------------\n        # Calculate Confidence Intervals and Peaks\n        # ------------------------------------------\n        for compartment, value_stack in self._generate_compartment_arrays(model_ensemble).items():\n            compartment_output = dict()\n\n            # Compute percentiles over the ensemble\n            for percentile in self.output_percentiles:\n                outputs[compartment]['ci_%i' % percentile] = np.percentile(value_stack, percentile, axis=0).tolist()\n\n            if compartment in compartment_to_capacity_attr_map:\n                compartment_output['surge_start'], compartment_output['surge_start'] = self._get_surge_window(model_ensemble, compartment)\n                compartment_output['capacity'] = [getattr(m, compartment_to_capacity_attr_map[compartment]) for m in model_ensemble]\n\n            compartment_output.update(self._detect_peak_time_and_value(value_stack, outputs['t_list']))\n\n            # Merge this dictionary into the suppression level one.\n            outputs[compartment].update(compartment_output)\n\n        return outputs\n\n\ndef _run_county(fips, ensemble_kwargs):\n    \"\"\"\n    Execute the ensemble runner for a specific county.\n\n    Parameters\n    ----------\n    fips: str\n        County fips.\n    ensemble_kwargs: dict\n        Kwargs passed to the EnsembleRunner object.\n    \"\"\"\n    runner = EnsembleRunner(fips=fips, **ensemble_kwargs)\n    runner.run_ensemble()\n\n\ndef run_state(state, ensemble_kwargs, states_only=False):\n    \"\"\"\n    Run the EnsembleRunner for each county in a state.\n\n    Parameters\n    ----------\n    state: str\n        State to run against.\n    ensemble_kwargs: dict\n        Kwargs passed to the EnsembleRunner object.\n    states_only: bool\n        If True only run the state level.\n    \"\"\"\n    # Run the state level\n    runner = EnsembleRunner(fips=us.states.lookup(state).fips, **ensemble_kwargs)\n    runner.run_ensemble()\n\n    if not states_only:\n        # Run county level\n        df = load_data.load_county_metadata()\n        all_fips = df[df['state'].str.lower() == state.lower()].fips\n        p = Pool()\n        f = partial(_run_county, ensemble_kwargs=ensemble_kwargs)\n        p.map(f, all_fips)\n        p.close()\n", "meta": {"hexsha": "02e9a3f282c0752ff331b90464b1632bb9e538e6", "size": 22135, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyseir/ensembles/ensemble_runner.py", "max_stars_repo_name": "paulirish/covid-data-model", "max_stars_repo_head_hexsha": "b93ae5d598b8378f9c1f2698e3162f87136cde74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-25T02:51:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-25T02:51:26.000Z", "max_issues_repo_path": "pyseir/ensembles/ensemble_runner.py", "max_issues_repo_name": "paulirish/covid-data-model", "max_issues_repo_head_hexsha": "b93ae5d598b8378f9c1f2698e3162f87136cde74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyseir/ensembles/ensemble_runner.py", "max_forks_repo_name": "paulirish/covid-data-model", "max_forks_repo_head_hexsha": "b93ae5d598b8378f9c1f2698e3162f87136cde74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.4477911647, "max_line_length": 189, "alphanum_fraction": 0.6555229275, "include": true, "reason": "import numpy", "num_tokens": 4628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.1852953173168032}}
{"text": "# Copyright 2019 The Cirq Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom typing import List, Optional\n\nimport numpy as np\nimport sympy\n\nimport cirq\n\nSQRT_ISWAP = cirq.ISWAP ** 0.5\nSQRT_ISWAP_INV = cirq.ISWAP ** -0.5\n\n\n# TODO: Combine this with the equivalent functions in google/gate_set.py\n# Or better yet, write a proper gate set so we don't need this in two places.\n# Github issue: https://github.com/quantumlib/Cirq/issues/2970\ndef _near_mod_n(e, t, n, atol=1e-8):\n    return abs((e - t + 1) % n - 1) <= atol\n\n\ndef _near_mod_2pi(e, t, atol=1e-8):\n    return _near_mod_n(e, t, 2 * np.pi, atol=atol)\n\n\nclass ConvertToSqrtIswapGates(cirq.PointOptimizer):\n    \"\"\"Attempts to convert gates into ISWAP**-0.5 gates.\n\n    Since we have Z rotations and arbitrary XY rotations, we\n    can rely on cirq decomposition for one qubit gates and\n    need to only specify special decompositions for two qubit gates.\n\n    Currently natively specified gates are CZPowGate, ISwapPowGate,\n    and FSimGate.  This will also support gates that decompose into\n    the above gates.\n    \"\"\"\n\n    def __init__(self, ignore_failures=False) -> None:\n        \"\"\"\n        Args:\n            ignore_failures: If set, gates that fail to convert are forwarded\n                unchanged. If not set, conversion failures raise a TypeError.\n        \"\"\"\n        super().__init__()\n        self.ignore_failures = ignore_failures\n\n    def _convert_one(self, op: cirq.Operation) -> cirq.OP_TREE:\n        \"\"\"\n        Decomposer intercept:  Let cirq decompose one-qubit gates,\n        intercept on 2-qubit gates if they are known gates.\n        \"\"\"\n        if isinstance(op, cirq.GlobalPhaseOperation):\n            return []\n\n        gate = op.gate\n\n        if len(op.qubits) != 2:\n            return NotImplemented\n\n        q0, q1 = op.qubits\n\n        if isinstance(gate, cirq.CZPowGate):\n            if isinstance(gate.exponent, sympy.Basic):\n                return cphase_symbols_to_sqrt_iswap(q0, q1, gate.exponent)\n            else:\n                return cphase_to_sqrt_iswap(q0, q1, gate.exponent)\n        if isinstance(gate, cirq.SwapPowGate):\n            return swap_to_sqrt_iswap(q0, q1, gate.exponent)\n        if isinstance(gate, cirq.ISwapPowGate):\n            return iswap_to_sqrt_iswap(q0, q1, gate.exponent)\n        if isinstance(gate, cirq.FSimGate):\n            return fsim_gate(q0, q1, gate.theta, gate.phi)\n\n        return NotImplemented\n\n    def _on_stuck_raise(self, bad):\n        return TypeError(\n            f\"Don't know how to work with {bad}. \"\n            \"It isn't a native sqrt ISWAP operation, \"\n            \"a 1 or 2 qubit gate with a known unitary, \"\n            \"or composite.\"\n        )\n\n    def convert(self, op: cirq.Operation) -> List[cirq.Operation]:\n        return cirq.decompose(\n            op,\n            keep=is_sqrt_iswap_compatible,\n            intercepting_decomposer=self._convert_one,\n            on_stuck_raise=(None if self.ignore_failures else self._on_stuck_raise),\n        )\n\n    def optimization_at(\n        self, circuit: cirq.Circuit, index: int, op: cirq.Operation\n    ) -> Optional[cirq.PointOptimizationSummary]:\n        if isinstance(op.gate, cirq.MatrixGate) and len(op.qubits) == 1:\n            return None\n\n        converted = self.convert(op)\n        if len(converted) == 1 and converted[0] is op:\n            return None\n\n        return cirq.PointOptimizationSummary(\n            clear_span=1, new_operations=converted, clear_qubits=op.qubits\n        )\n\n\ndef is_sqrt_iswap_compatible(op: cirq.Operation) -> bool:\n    \"\"\"Check if the given operation is compatible with the sqrt_iswap gateset\n    gate set.\n\n    Args:\n        op: Input operation.\n\n    Returns:\n        True if the operation is native to the gate set, false otherwise.\n    \"\"\"\n    return is_basic_gate(op.gate) or is_sqrt_iswap(op.gate)\n\n\ndef is_sqrt_iswap(gate: Optional[cirq.Gate]) -> bool:\n    \"\"\"Checks if this is a ± sqrt(iSWAP) gate specified using either\n    ISwapPowGate or with the equivalent FSimGate.\n    \"\"\"\n    if (\n        isinstance(gate, cirq.FSimGate)\n        and not isinstance(gate.theta, sympy.Basic)\n        and _near_mod_2pi(abs(gate.theta), np.pi / 4)\n        and _near_mod_2pi(gate.phi, 0)\n    ):\n        return True\n    return (\n        isinstance(gate, cirq.ISwapPowGate)\n        and not isinstance(gate.exponent, sympy.Basic)\n        and _near_mod_n(abs(gate.exponent), 0.5, 4)\n    )\n\n\ndef is_basic_gate(gate: Optional[cirq.Gate]) -> bool:\n    \"\"\"Check if a gate is a basic supported one-qubit gate.\n\n    Args:\n        gate: Input gate.\n\n    Returns:\n        True if the gate is native to the gate set, false otherwise.\n    \"\"\"\n    return isinstance(\n        gate,\n        (\n            cirq.MeasurementGate,\n            cirq.PhasedXZGate,\n            cirq.PhasedXPowGate,\n            cirq.XPowGate,\n            cirq.YPowGate,\n            cirq.ZPowGate,\n        ),\n    )\n\n\ndef cphase_to_sqrt_iswap(a, b, turns):\n    \"\"\"Implement a C-Phase gate using two sqrt ISWAP gates and single-qubit\n    operations. The circuit is equivalent to cirq.CZPowGate(exponent=turns).\n\n    Output unitary:\n    [1   0   0   0],\n    [0   1   0   0],\n    [0   0   1   0],\n    [0   0   0   e^{i turns pi}].\n\n    Args:\n        a: the first qubit\n        b: the second qubit\n        turns: Exponent specifying the evolution time in number of rotations.\n    \"\"\"\n    theta = (turns % 2) * np.pi\n    if 0 <= theta <= np.pi:\n        sign = 1.0\n        theta_prime = theta\n    elif np.pi < theta < 2 * np.pi:\n        sign = -1.0\n        theta_prime = 2 * np.pi - theta\n\n    if np.isclose(theta, np.pi):\n        # If we are close to pi, just set values manually to avoid possible\n        # numerical errors with arcsin of greater than 1.0 (Ahem, Windows).\n        phi = np.pi / 2\n        xi = np.pi / 2\n    else:\n        phi = np.arcsin(np.sqrt(2) * np.sin(theta_prime / 4))\n        xi = np.arctan(np.tan(phi) / np.sqrt(2))\n\n    yield cirq.rz(sign * 0.5 * theta_prime).on(a)\n    yield cirq.rz(sign * 0.5 * theta_prime).on(b)\n    yield cirq.rx(xi).on(a)\n    yield cirq.X(b) ** (-sign * 0.5)\n    yield SQRT_ISWAP_INV(a, b)\n    yield cirq.rx(-2 * phi).on(a)\n    yield SQRT_ISWAP(a, b)\n\n    yield cirq.rx(xi).on(a)\n    yield cirq.X(b) ** (sign * 0.5)\n    # Corrects global phase\n    yield cirq.GlobalPhaseOperation(np.exp(sign * theta_prime * 0.25j))\n\n\ndef cphase_symbols_to_sqrt_iswap(a, b, turns):\n    \"\"\"Version of cphase_to_sqrt_iswap that works with symbols.\n\n    Note that the formulae contained below will need to be flattened\n    into a sweep before serializing.\n    \"\"\"\n    theta = sympy.Mod(turns, 2.0) * sympy.pi\n\n    # -1 if theta > pi.  Adds a hacky fudge factor so theta=pi is not 0\n    sign = sympy.sign(sympy.pi - theta + 1e-9)\n\n    # For sign = 1: theta. For sign = -1, 2pi-theta\n    theta_prime = (sympy.pi - sign * sympy.pi) + sign * theta\n\n    phi = sympy.asin(np.sqrt(2) * sympy.sin(theta_prime / 4))\n    xi = sympy.atan(sympy.tan(phi) / np.sqrt(2))\n\n    yield cirq.rz(sign * 0.5 * theta_prime).on(a)\n    yield cirq.rz(sign * 0.5 * theta_prime).on(b)\n    yield cirq.rx(xi).on(a)\n    yield cirq.X(b) ** (-sign * 0.5)\n    yield SQRT_ISWAP_INV(a, b)\n    yield cirq.rx(-2 * phi).on(a)\n    yield SQRT_ISWAP(a, b)\n    yield cirq.rx(xi).on(a)\n    yield cirq.X(b) ** (sign * 0.5)\n\n\ndef iswap_to_sqrt_iswap(a, b, turns):\n    \"\"\"Implement the evolution of the hopping term using two sqrt_iswap gates\n     and single-qubit operations. Output unitary:\n    [1   0   0   0],\n    [0   c  is   0],\n    [0  is   c   0],\n    [0   0   0   1],\n    where c = cos(t * np.pi / 2) and s = sin(t * np.pi / 2).\n\n    Args:\n        a: the first qubit\n        b: the second qubit\n        t: Exponent that specifies the evolution time in number of rotations.\n    \"\"\"\n    yield cirq.Z(a) ** 0.75\n    yield cirq.Z(b) ** 0.25\n    yield SQRT_ISWAP_INV(a, b)\n    yield cirq.Z(a) ** (-turns / 2 + 1)\n    yield cirq.Z(b) ** (turns / 2)\n    yield SQRT_ISWAP_INV(a, b)\n    yield cirq.Z(a) ** 0.25\n    yield cirq.Z(b) ** -0.25\n\n\ndef swap_to_sqrt_iswap(a, b, turns):\n    \"\"\"Implement the evolution of the hopping term using two sqrt_iswap gates\n     and single-qubit operations. Output unitary:\n    [[1, 0,        0,     0],\n     [0, g·c,    -i·g·s,  0],\n     [0, -i·g·s,  g·c,    0],\n     [0,   0,      0,     1]]\n     where c = cos(theta) and s = sin(theta).\n        Args:\n            a: the first qubit\n            b: the second qubit\n            theta: The rotational angle that specifies the gate, where\n            c = cos(π·t/2), s = sin(π·t/2), g = exp(i·π·t/2).\n    \"\"\"\n    if not isinstance(turns, sympy.Basic) and _near_mod_n(turns, 1.0, 2):\n        # Decomposition for cirq.SWAP\n        yield cirq.Y(a) ** 0.5\n        yield cirq.Y(b) ** 0.5\n        yield SQRT_ISWAP(a, b)\n        yield cirq.Y(a) ** -0.5\n        yield cirq.Y(b) ** -0.5\n        yield SQRT_ISWAP(a, b)\n        yield cirq.X(a) ** -0.5\n        yield cirq.X(b) ** -0.5\n        yield SQRT_ISWAP(a, b)\n        yield cirq.X(a) ** 0.5\n        yield cirq.X(b) ** 0.5\n        return\n\n    yield cirq.Z(a) ** 1.25\n    yield cirq.Z(b) ** -0.25\n    yield cirq.ISWAP(a, b) ** -0.5\n    yield cirq.Z(a) ** (-turns / 2 + 1)\n    yield cirq.Z(b) ** (turns / 2)\n    yield cirq.ISWAP(a, b) ** -0.5\n    yield cirq.Z(a) ** (turns / 2 - 0.25)\n    yield cirq.Z(b) ** (turns / 2 + 0.25)\n    yield cirq.CZ.on(a, b) ** (-turns)\n\n\ndef fsim_gate(a, b, theta, phi):\n    \"\"\"FSimGate has a default decomposition in cirq to XXPowGate and YYPowGate,\n    which is an awkward decomposition for this gate set.\n    Decompose into ISWAP and CZ instead.\"\"\"\n    if theta != 0.0:\n        yield cirq.ISWAP(a, b) ** (-2 * theta / np.pi)\n    if phi != 0.0:\n        yield cirq.CZPowGate(exponent=-phi / np.pi)(a, b)\n", "meta": {"hexsha": "0ab0eea71e1c02a8d7c47770614058cb0c92bc8a", "size": 10223, "ext": "py", "lang": "Python", "max_stars_repo_path": "cirq-google/cirq_google/optimizers/convert_to_sqrt_iswap.py", "max_stars_repo_name": "stubbi/Cirq", "max_stars_repo_head_hexsha": "6d2cd16991bd7fde352010d31010f85d7eafc0ba", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-01-12T07:10:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-08T03:47:22.000Z", "max_issues_repo_path": "cirq-google/cirq_google/optimizers/convert_to_sqrt_iswap.py", "max_issues_repo_name": "resduo/Cirq", "max_issues_repo_head_hexsha": "680f897345eb1c71c9242515edda8f04b8594319", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cirq-google/cirq_google/optimizers/convert_to_sqrt_iswap.py", "max_forks_repo_name": "resduo/Cirq", "max_forks_repo_head_hexsha": "680f897345eb1c71c9242515edda8f04b8594319", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3512658228, "max_line_length": 84, "alphanum_fraction": 0.6066712315, "include": true, "reason": "import numpy,import sympy", "num_tokens": 3076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3593641588823761, "lm_q1q2_score": 0.18529531731680318}}
{"text": "import collections\nfrom typing import Callable, Iterable, List\n\nimport numpy as np\nimport torch\nfrom numpy import ceil\nfrom ppq.core import (CHECKPOINT_TOLERANCE, OPTIM_ADVOPT_GRAPH_MAXSIZE,\n                      OPTIM_ADVOPT_INITIAL_THRES, OPTIM_ADVOPT_PASSIVE_BOOST,\n                      OPTIM_ADVOPT_PATIENT, OPTIM_ADVOPT_STEP_PER_EPOCH,\n                      OPTIM_ADVOPT_THRESHOLD_STEP, QuantizationProperty,\n                      QuantizationStates, empty_ppq_cache)\nfrom ppq.executor import BaseGraphExecutor, TorchExecutor\nfrom ppq.IR import (BaseGraph, GraphCommandProcesser, Operation,\n                    QuantableOperation)\nfrom ppq.quantization.algorithm.training import (AdaroundRegTerm,\n                                                 FinetuneCheckPoint, Lp_norm,\n                                                 RandomMemDataset,\n                                                 TrainableDelegate)\nfrom ppq.quantization.analyise.util import MeasurePrinter\nfrom ppq.quantization.measure import torch_mean_square_error, torch_snr_error\nfrom torch.cuda import empty_cache\nfrom tqdm import tqdm\n\nfrom .base import QuantizationOptimizationPass\n\n\ndef has_bias(op: Operation):\n    if op.type in {'Conv', 'ConvTranspose', 'Gemm'}:\n        return op.meta_data.num_of_input == 3\n    else: return False\n\n\nclass TrainingBasedPass(QuantizationOptimizationPass):\n    \"\"\"\n    Training Based Pass is a basic class that provides necessary function for\n        all training optimizition passes. Optimization will be more stable and\n        accurate with functions provided by this pass. (Might be a little slower).\n\n    This pass will collect result of interested outputs after optimization and\n        check if the optimized result has a lower SNR. If so, the optimization will be\n        accepted, layer weight will be updated, otherwise optimization will be rejected and\n        takes no effects.\n\n    Choose interested_outputs carefully, cause we compare loss only with those output variables.\n        If interested_outputs is None, all graph output variables will be choosen.\n\n    YOUR SHOULD NOTICE THAT SNR REFERS TO: POWER OF NOISE / POWER OF SIGNAL IN PPQ.\n\n    Args:\n        QuantizationOptimizationPass ([type]): [description]\n    \"\"\"\n    def __init__(self, name: str = 'Default Quanzation Optim', \n                 interested_outputs: List[str] = None, verbose: bool = True) -> None:\n        self._loss_fn = torch_snr_error\n        self._interested_outputs = interested_outputs\n        self._checkpoints = {}\n        self._verbose = verbose\n        self._quant_state_recorder = {}\n        super().__init__(name=name)\n\n    @ empty_ppq_cache\n    def initialize_checkpoints(\n        self, graph: BaseGraph, executor: BaseGraphExecutor, \n        dataloader: Iterable, collate_fn: Callable):\n        \"\"\"\n        Establish a series of network checkpoints with your network.\n            Checkpoint is a data structure that helps us compare quant results and fp32 results. \n        Args:\n            graph (BaseGraph): [description]\n            executor (BaseGraphExecutor): [description]\n            dataloader (Iterable): [description]\n            collate_fn (Callable): [description]\n\n        Raises:\n            PermissionError: [description]\n        \"\"\"\n        for operation in graph.operations.values():\n            if isinstance(operation, QuantableOperation):\n                for cfg, var in operation.config_with_variable:\n                    if cfg.state in {QuantizationStates.BAKED, QuantizationStates.PASSIVE_BAKED}:\n                        raise PermissionError('Can not initialize checkpoints when weight value is baked. '\n                                              f'Variable {var.name} has a baked value.')\n\n        if self._interested_outputs is None or len(self._interested_outputs) == 0:\n            self._interested_outputs = [name for name in graph.outputs]\n        \n        for name in self._interested_outputs:\n            self._checkpoints[name] = FinetuneCheckPoint(variable=name)\n\n        # dequantize graph, collect references\n        for op in graph.operations.values():\n            if isinstance(op, QuantableOperation): \n                op.dequantize()\n\n        for data in dataloader:\n            if collate_fn is not None: data = collate_fn(data)\n            outputs = executor.forward(inputs=data, output_names=self._interested_outputs)\n            for name, output in zip(self._interested_outputs, outputs):\n                ckpt = self._checkpoints[name]\n                assert isinstance(ckpt, FinetuneCheckPoint)\n                ckpt.push(tensor=output, is_reference=True)\n\n        # restore quantization state:\n        for op in graph.operations.values():\n            if isinstance(op, QuantableOperation): \n                op.restore_quantize_state()\n        \n        # update state\n        verbose, self._verbose = self._verbose, False\n        self.check(executor=executor, dataloader=dataloader, collate_fn=collate_fn)\n        self._verbose = verbose\n\n    def check(self, executor: BaseGraphExecutor,\n        dataloader: Iterable, collate_fn: Callable):\n        \"\"\"\n        Check quantization error with a given dataloader with current checkpoints.\n            Return whether quantization error is lower than before.\n\n        Args:\n            executor (BaseGraphExecutor): [description]\n            dataloader (Iterable): [description]\n            collate_fn (Callable): [description]\n\n        Returns:\n            [type]: [description]\n        \"\"\"\n        \n        # step - 1, collecting data\n        for data in dataloader:\n            if collate_fn is not None: data = collate_fn(data)\n            outputs = executor.forward(inputs=data, output_names=self._interested_outputs)\n            for name, output in zip(self._interested_outputs, outputs):\n                self._checkpoints[name].push(tensor=output, is_reference=False)\n\n        # step - 2, calculating loss\n        losses = []\n        for name in self._interested_outputs:\n            ckpt = self._checkpoints[name]\n            assert isinstance(ckpt, FinetuneCheckPoint)\n            qt_out, fp_out = ckpt.pop()\n            qt_out = torch.cat([tensor for tensor in qt_out])\n            fp_out = torch.cat([tensor for tensor in fp_out])\n            losses.append(self._loss_fn(y_pred=qt_out, y_real=fp_out).item())\n            ckpt.clear()\n\n        # step - 3, comparing loss\n        loss_now, loss_old = sum(losses), sum([ckpt.best_loss for ckpt in self._checkpoints.values()])\n        loss_now, loss_old = loss_now / len(losses), loss_old / len(losses)\n        if self._verbose: print(f'SNR after optimization: {loss_old * 100 :.4f}% -> {loss_now * 100:.4f}%.')\n\n        # if there is a loss drop, update all losses.\n        if loss_old > (loss_now * CHECKPOINT_TOLERANCE):\n            for idx, name in enumerate(self._interested_outputs):\n                ckpt = self._checkpoints[name]\n                assert isinstance(ckpt, FinetuneCheckPoint)\n                ckpt.best_loss = losses[idx]\n            return True\n\n        if self._verbose: print(f'Not a perfect loss drop, skip this optimization.')\n        return False\n\n    def optimize(\n        self, processer: GraphCommandProcesser,\n        dataloader: Iterable, executor: BaseGraphExecutor, **kwargs) -> None:\n        raise NotImplementedError('Can not invoke this function. '\n                                  'Please inherit this class and give an implmenetation to override this function.')\n\n    def dequantize_immediately(self, operation: Operation):\n        \"\"\"\n        Dequantize an operation inplace, use this function carefully.\n            if parameter value has been changed during your optimization procedure,\n            then it is not safe to dequantize an operation via this function,\n            use operation.dequantize to load stored fp32 value instead.\n        \n        This function will change quantization state to dequantize an operation,\n            Only quantization state will be changed by this function so that it is\n            extremely fast.\n        \n        If your parameter value has already been baked, an exception will be thrown.\n        Args:\n            operation (Operation): [description]\n        \"\"\"\n        if isinstance(operation, QuantableOperation):\n            for cfg, _ in operation.config_with_variable:\n                assert cfg.state not in {QuantizationStates.BAKED, QuantizationStates.PASSIVE_BAKED}, (\n                    'Value has already been baked, can not dequantize it via this function.')\n\n                if cfg not in self._quant_state_recorder:\n                    self._quant_state_recorder[cfg] = cfg.state\n                    cfg.state = QuantizationStates.DEQUANTIZED\n\n    def quantize_immediately(self, operation: Operation):\n        \"\"\"\n        Restore quantization state of an operation, use this function carefully.\n            if parameter value has been changed during your optimization procedure,\n            then it is not safe to restore state via this function,\n            use operation.restore_quantize_state to load stored quant value instead.\n\n        This function will change quantization state to quantize an operation,\n            Only quantization state will be changed by this function so that it is\n            extremely fast.\n\n        If your parameter value has already been baked, an exception will be thrown.\n        Args:\n            operation (Operation): [description]\n        \"\"\"\n        if isinstance(operation, QuantableOperation):\n            for cfg, _ in operation.config_with_variable:\n                if cfg in self._quant_state_recorder:\n                    stored_state = self._quant_state_recorder[cfg]\n                    cfg.state = stored_state\n                    self._quant_state_recorder.pop(cfg)\n            \n\nclass BiasCorrectionPass(TrainingBasedPass):\n    def __init__(self, auto_check: bool=False, interested_output: List[str] = None, \n                 verbose: bool = True, max_steps:int = 8) -> None:\n        \"\"\"\n        Quantization can introduce a biased error in the activations.\n            Bias correction serves as a useful prosedure to eliminate those introduced bias error.\n\n        let: Y = WX + b\n             Quant(Y) = Qunat(W) Quant(X) + b\n             \n             bias_error = reduce_mean(Y - Quant(Y))\n             \n        Correct bias by: b = b + bias_error\n        \n        Args:\n            quantize_function (BaseQuantFunction): [description]\n            auto_check (bool, optional): [description]. Defaults to False.\n        \"\"\"\n        super().__init__(name='PPQ Bias Correction Pass', \n                         interested_outputs=interested_output, verbose=verbose)\n        self._auto_check = auto_check\n        self._max_steps = max_steps\n\n    @ empty_ppq_cache\n    def optimize(\n        self,\n        processer: GraphCommandProcesser,\n        dataloader: Iterable,\n        executor: BaseGraphExecutor,\n        collate_fn: Callable,\n        **kwargs\n    ) -> None:\n        def collect_bias(output: torch.Tensor, collector: list, op_type: str):\n            if op_type in {'Conv', 'ConvTranspose'}: \n                collector.append(torch.mean(output, dim=(0, 2, 3)).unsqueeze(0))\n            elif op_type in {'Gemm'}: \n                collector.append(torch.mean(output, dim=(0, )).unsqueeze(0))\n            else: raise TypeError(f'Unsupported Operation type: {op_type}')\n\n        assert isinstance(executor, TorchExecutor), (\n            'PPQ Training-based optimization algorithm needs a TorchExecutor.')\n    \n        if self._auto_check:\n            self.initialize_checkpoints(graph=processer.graph, executor=executor, \n                                        dataloader=dataloader, collate_fn=collate_fn)    \n    \n        for idx, operation in tqdm(enumerate(executor._executing_order), \n                                   desc='Bias Correction Procedure ...', \n                                   total=len(executor._executing_order)):\n            assert isinstance(operation, Operation)\n            if not has_bias(operation): continue\n            \n            bias, output_var = operation.inputs[-1].value, operation.outputs[0]\n            qt_collector, fp_collector = [], []\n\n            for idx, data in enumerate(dataloader):\n                if collate_fn is not None: data = collate_fn(data)\n                [output] = executor.forward(inputs=data, output_names=[output_var.name])\n                collect_bias(output, qt_collector, op_type=operation.type)\n                if idx >= self._max_steps: break\n            self.dequantize_immediately(operation)\n            \n            for idx, data in enumerate(dataloader):\n                if collate_fn is not None: data = collate_fn(data)\n                [output] = executor.forward(inputs=data, output_names=[output_var.name])\n                collect_bias(output, fp_collector, op_type=operation.type)\n                if idx >= self._max_steps: break\n            self.quantize_immediately(operation)\n\n            bias_error = (torch.mean(torch.cat(fp_collector), dim=0) - torch.mean(torch.cat(qt_collector), dim=0))\n            if self._auto_check:\n                backup = bias.clone()\n                operation.inputs[-1].value = bias + bias_error\n                if not self.check(executor=executor, dataloader=dataloader, collate_fn=collate_fn):\n                    operation.inputs[-1].value = backup\n            else: operation.inputs[-1].value = bias + bias_error\n\n\nclass AdaRoundPass(QuantizationOptimizationPass):\n    def __init__(self,\n                 collecting_device: str = 'cpu',\n                 epoch: int = 512,\n                 batch_size: int = 32) -> None:\n        super().__init__(name='PPQ AdaRound Pass')\n        self._collecting_device = collecting_device\n        self.epoch = epoch\n        self.batch_size = batch_size\n\n    @ empty_ppq_cache\n    def optimize(\n        self,\n        processer: GraphCommandProcesser,\n        dataloader: Iterable,\n        executor: BaseGraphExecutor,\n        collate_fn: Callable,\n        **kwargs\n    ) -> None:\n        assert isinstance(executor, TorchExecutor), ('PPQ Training-based optimization algorithm needs a TorchExecutor.')\n        graph = processer.graph\n        sorted_ops = graph.topological_sort()\n        for idx, target_op in tqdm(enumerate(sorted_ops), desc='AdaRound...', total=len(graph.operations)):\n            if not isinstance(target_op, QuantableOperation): continue\n            if not target_op.type in {'Conv', 'ConvTranspose', 'Gemm'}: continue\n\n            fp_outputs, quant_inputs = [], []\n            interested_var = (target_op.inputs[0].name, target_op.outputs[0].name)\n\n            for op in sorted_ops[: idx + 1]:\n                if isinstance(op, QuantableOperation): op.dequantize()\n            for data in tqdm(dataloader, desc='AdaRound Procedure 1', total=len(dataloader)):\n                if collate_fn is not None: data = collate_fn(data)\n                fp_input, fp_output = executor.forward(inputs=data, output_names=interested_var)\n                fp_outputs.append(fp_output)\n            fp_weight = target_op.parameters[0].value.clone()\n\n            for op in sorted_ops[: idx + 1]:\n                if isinstance(op, QuantableOperation): op.restore_quantize_state()\n            for data in tqdm(dataloader, desc='AdaRound Procedure 2', total=len(dataloader)):\n                if collate_fn is not None: data = collate_fn(data)\n                quant_input, _ = executor.forward(inputs=data, output_names=interested_var)\n                quant_inputs.append(quant_input)\n\n            fp_outputs_concat = torch.cat(fp_outputs)\n            quant_inputs_concat = torch.cat(quant_inputs)\n            weight, bias = target_op.parameters[0].value, None\n            if target_op.num_of_input == 3:\n                bias = target_op.parameters[1].value\n                bias = bias.clone()\n            weight = weight.clone()\n            params = [weight, bias] if bias is not None else [weight]\n            for param in params: param.requires_grad = True\n\n            print ('Adaround optimize {}'.format(target_op.name))\n            weight_quantization_config = target_op.config.input_quantization_config[1].dominated_by\n            weight_scale = weight_quantization_config.scale\n            weight_offset = weight_quantization_config.offset\n\n            max_iter = self.epoch * fp_outputs_concat.shape[0] / self.batch_size\n            reg = AdaroundRegTerm(max_iter)\n\n            # per-channel scale preprocess\n            if weight_quantization_config.policy.has_property(QuantizationProperty.PER_CHANNEL):\n                view_shape = [\n                    1 if axis != weight_quantization_config.channel_axis else -1\n                    for axis in range(fp_weight.ndim)]\n                weight_scale = weight_scale.view(view_shape)\n                weight_offset = weight_offset.view(view_shape)\n\n            # init continuous_v, make sure h(v) = round_diff\n            round_diff = (fp_weight / weight_scale) - (fp_weight / weight_scale).floor()\n            v_init = -torch.log((reg.zeta - reg.gamma) / (round_diff - reg.gamma) - 1)\n            continuous_v = torch.nn.Parameter(v_init.to(executor._device), True)\n            optimizer = torch.optim.Adam([continuous_v])\n\n            cur_iter = 0\n            data_len = quant_inputs_concat.shape[0]\n            for ep_idx in range(self.epoch):\n                batch_num = int(ceil(data_len / self.batch_size))\n                # shuffle data\n                index = np.arange(data_len)\n                np.random.shuffle(index)\n                for idx in range(batch_num):\n                    st = idx * self.batch_size\n                    ed = min(st + self.batch_size, data_len)\n\n                    # soft AdaRound quant weight\n                    params[0] = self.adaround_quant_weight(fp_weight, weight_scale, weight_offset, weight_quantization_config, continuous_v)\n                    in_snap = [ quant_inputs_concat[index[st:ed,]] ]\n                    [quant_output] = executor.operation_forward(target_op, inputs=in_snap + params)\n                    fp32_output = fp_outputs_concat[index[st:ed],]\n\n                    loss = Lp_norm(fp32_output, quant_output) + reg(continuous_v, cur_iter)\n                    optimizer.zero_grad()\n                    loss.backward(retain_graph=True)\n                    optimizer.step()\n                    cur_iter += 1\n\n                if ep_idx % 100 == 0:\n                    print(\"Epoch: {:<4} L2 Loss: {:>10.3f} Beta: {:>3.3f}\".format(ep_idx, loss, reg.beta))\n            h_v = AdaroundRegTerm().rectified_sigmoid(continuous_v)\n            print(\"Loss: {:>5.3f} Ceil: {:>5} Floor: {:>5} Total: {:>5} Ratio: {:>.3f}\".format(\n                loss,\n                h_v[h_v + 1e-4 >= 1.0].numel(), h_v[h_v <= 1e-4].numel(), torch.numel(h_v),\n                (h_v[h_v + 1e-4 >= 1.0].numel() + h_v[h_v <= 1e-4].numel()) / torch.numel(h_v)))\n\n            # update weight\n            rounded_weight = self.adaround_quant_weight(fp_weight, weight_scale, weight_offset, weight_quantization_config, continuous_v, soft=False)\n            target_op.parameters[0].value.copy_(rounded_weight)\n            del fp_outputs_concat\n            del quant_inputs_concat\n            target_op.config.input_quantization_config[1].state = QuantizationStates.ACTIVATED\n            if bias is not None:\n                target_op.parameters[1].value.copy_(bias)\n                target_op.config.input_quantization_config[-1].state = QuantizationStates.PASSIVE\n\n    def adaround_quant_weight(self, weight, scale, offset, weight_quantization_config, round_var, soft=True):\n        quant_max = weight_quantization_config.quant_max\n        quant_min = weight_quantization_config.quant_min\n        if soft:\n            weight = (weight / scale).floor() + AdaroundRegTerm().rectified_sigmoid(round_var)\n        else:\n            weight = (weight / scale).floor() + (round_var >= 0).float()\n        weight = torch.clamp(weight + offset, quant_min, quant_max)\n        weight = (weight - offset) * scale\n        return weight\n\n\nclass LearningStepSizeOptimization(TrainingBasedPass):\n    def __init__(self, name: str = 'PPQ LSQ Optimization') -> None:\n        super().__init__(name=name)\n    \n    def optimize(self, processer: GraphCommandProcesser, \n                 dataloader: Iterable, executor: BaseGraphExecutor,\n                 **kwargs) -> None:\n        \n        return super().optimize(processer, dataloader, executor, **kwargs)\n\n\nclass AdvancedQuantOptimization(TrainingBasedPass):\n    \"\"\"\n    PPQ Advanced Quantization Optimization\n\n    This optimization pass minimize the quantization errors of each subgraph separately\n        by optimizing its parameters over the calibration set.\n\n    Where:\n        qout = quant( quant(W + W_offset) * quant(X) + quant(bias + bias_offset) )\n    \n        fout = W * B + bias\n    \n        error = Mean((qout - fout)^2)\n    \n    This training procedure trys to solve best W_offest and bias_offset to minimize error\n        Based on your setting and network size, the training procedure will takes 5~120 minutes.\n    \n    This function will treat your network as a series of subgraph, you should notice that\n        ONLY THE OUTPUT VALUE OF A SUBGRAPH IS OPTIMIZED IN THIS PASS, \n        ACTIVATIONS THAT INSIDE YOUR SUBGRAPH MIGHT BE GREATLY CHANGED!\n        DO NOT ATTEMPT TO COMPARE THOSE QUANTIZED ACTIVATION WITH ITS FP32 VERSION.\n    \n    We use graph search engine to build subgraph from your network with pattern below:\n\n    while len(graph.get_downstream_operations(start_op)) == 1:\n        end_op = graph.get_downstream_operations(start_op)[0]\n        if len(graph.get_upstream_operations(end_op)) == 1:\n            path.append(end_op)\n            start_op = end_op\n        else: break\n\n    Args:\n        TrainingBasedPass ([type]): [description]\n    \"\"\"\n    def __init__(self, collecting_device: str, limit: float = 3.0, lr: float = 1e-3,\n                 interested_outputs: List[str] = None, interested_layers: List[str] = None,\n                 verbose: bool = True, check: bool = True) -> None:\n\n        super().__init__(\n            name='PPQ Advanced Optimization Procedure(Blockwise)', \n            interested_outputs=interested_outputs, verbose=verbose)\n\n        self.lr                = lr\n        self.collecting_device = collecting_device\n        self.check_flag        = check\n        self.offset_limit      = limit\n        self.interested_layers = interested_layers\n        self.t_step            = OPTIM_ADVOPT_THRESHOLD_STEP\n        self.steps_per_epoch   = OPTIM_ADVOPT_STEP_PER_EPOCH\n        self.patient           = OPTIM_ADVOPT_PATIENT\n        self.passive_boost     = OPTIM_ADVOPT_PASSIVE_BOOST\n        self.max_iter          = 10000\n        \n        if isinstance(self.interested_layers, list) and len(self.interested_layers) == 0:\n            self.interested_layers = None\n\n    def collect_training_data(\n        self, output_name: str,\n        dataloader: Iterable,\n        executor: BaseGraphExecutor, \n        collate_fn: Callable) -> List[List[torch.Tensor]]:\n\n        output_collector = []\n        for data in dataloader:\n            if collate_fn is not None: data = collate_fn(data)\n            [output] = executor.forward(data, output_names=[output_name])\n            output_collector.append(output.to(self.collecting_device))\n        return output_collector\n\n    @ empty_ppq_cache\n    def finetune(\n        self, quant_inputs: List[torch.Tensor], fp32_outputs: List[torch.Tensor],\n        executor: TorchExecutor, block: List[Operation], \n        dataloader: Iterable, collate_fn:Callable) -> None:\n\n        # initialize training environment.\n        losses     = []\n        last_loss  = 1e9\n        threshold  = OPTIM_ADVOPT_INITIAL_THRES\n        trys_count = 0\n        cur_iter   = 0\n        delegates  = []\n        device     = executor._executing_contenxt.executing_device\n        loss_recorder = {}\n        output_var = block[-1].outputs[0]\n        input_var  = block[0].inputs[0]\n        \n        dataset = RandomMemDataset(data=[[qt, fp] for qt, fp in zip(quant_inputs, fp32_outputs)])\n\n        # create trainable delegates for each parameter.\n        for operation in block:\n            if operation.is_computing_op and isinstance(operation, QuantableOperation):\n                for cfg, var in operation.config_with_variable:\n                    if not var.is_parameter: continue\n                    boost = 1 if cfg.state == QuantizationStates.PASSIVE else self.passive_boost\n                    delegates.append(TrainableDelegate(\n                        value=var.value, config=cfg, \n                        limit=self.offset_limit, boost=boost, binding=var\n                        )\n                    )\n\n        # set up optimizer, ready for training.\n        optimizer = torch.optim.Adam(params=[d.offset for d in delegates], lr=self.lr)\n        while cur_iter < self.max_iter:\n            for _ in range(self.steps_per_epoch):\n                qt_input, fp_output = dataset.pop()\n                # update weights:\n                for parameter in delegates:\n                    assert isinstance(parameter, TrainableDelegate)\n                    parameter.quantize(threshold=threshold)\n\n                qt_input, fp_output = qt_input.to(device), fp_output.to(device)\n                qt_output = executor.partial_graph_forward(\n                    operations=block, feed_dict={input_var.name: qt_input}, \n                    output_names=[output_var.name])[0]\n\n                # compute loss\n                optimizer.zero_grad()\n                loss = torch_mean_square_error(qt_output, fp_output)\n                loss.backward()\n                optimizer.step()\n\n                cur_iter += 1\n                losses.append(loss.detach().item())\n\n            # pleatu interval schedule.\n            cur_loss = sum(losses) / len(losses)\n            if cur_loss < last_loss * .99:\n                last_loss, trys_count = cur_loss, 0\n                # record loss\n                loss_recorder[threshold] = cur_loss\n            else:\n                trys_count += 1\n                if trys_count > self.patient:\n                    # rebuild optimizer, clear all state.\n                    optimizer.state = collections.defaultdict(dict)\n                    trys_count, last_loss, threshold = 0, 1e9, threshold - self.t_step\n                    if threshold <= 0.5: break\n\n            # clear loss state\n            losses.clear()\n\n        # DEBUG INFO, JUST IN CASE.\n        '''\n        for offset in [d.offset for d in delegates]:\n            print(offset.shape)\n            print(' ------ GARD ------')\n            print(offset._grad.flatten().max())\n            print(' ------ VALUE ------')\n            print(offset.flatten().max())\n        '''\n\n        # clear all delegates\n        for delegate in delegates:\n            assert isinstance(delegate, TrainableDelegate)\n            delegate.clear()\n        \n        # display loss\n        if self._verbose:\n            loss_recorder = {f'{threshold * 100:.1f}%': loss for threshold, loss in loss_recorder.items()}\n            print(f'Optimize Result For Block: ', end='')\n            # display your block with following ugly code.\n            print(block[0].name, end='')\n            for operation in block[1:]: print('->' + operation.name, end='')\n            print('')\n    \n            MeasurePrinter(\n                data=loss_recorder, measure='MSE', \n                label='Threshold', order=None).print()\n\n        # Check\n        if self.check_flag:\n            if not self.check(executor=executor, dataloader=dataloader, collate_fn=collate_fn):\n                for delegate in delegates:\n                    assert isinstance(delegate, TrainableDelegate)\n                    delegate.withdraw()\n\n        # detach weight\n        for delegate in delegates:\n            assert isinstance(delegate, TrainableDelegate)\n            delegate.binding.value = delegate.binding.value.detach()\n\n    def build_block_from_start(self, graph: BaseGraph, start_op: QuantableOperation) -> List[Operation]:\n        path = [start_op]\n        while len(graph.get_downstream_operations(start_op)) == 1:\n            end_op = graph.get_downstream_operations(start_op)[0]\n            if len(graph.get_upstream_operations(end_op)) == 1:\n                path.append(end_op)\n                start_op = end_op\n            else: break\n\n        num_of_computing_ops = sum([1 for op in path if op.is_computing_op])\n        while num_of_computing_ops > OPTIM_ADVOPT_GRAPH_MAXSIZE:\n            if path[-1].is_computing_op: num_of_computing_ops -= 1\n            path.pop(-1)\n        return path\n\n    def optimize(\n        self, processer: GraphCommandProcesser, dataloader: Iterable,\n        executor: TorchExecutor, collate_fn: Callable, **kwargs) -> None:\n        \n        if self._interested_outputs is None:\n            self._interested_outputs = [name for name in processer.graph.outputs]\n\n        if self.collecting_device == 'executor': \n            self.collecting_device = executor._device\n\n        graph = processer.graph\n        visited = set()\n\n        # check if there is any baked value inside your graph\n        for operation in graph.operations.values():\n            if isinstance(operation, QuantableOperation):\n                for cfg, var in operation.config_with_variable:\n                    if cfg.state in {QuantizationStates.BAKED, QuantizationStates.PASSIVE_BAKED}:\n                        raise PermissionError('Can not apply advanced optimization pass when weight value is baked. '\n                                              f'Variable {var.name} has a baked value.')\n\n        # find all operations that need to be finetuned.\n        interested_ops = []\n        for target_op in graph.topological_sort():\n            if isinstance(target_op, QuantableOperation) and target_op.is_computing_op:\n                if self.interested_layers is None: interested_ops.append(target_op)\n                elif self.interested_layers is not None and target_op.name in self.interested_layers:\n                    interested_ops.append(target_op)\n\n        # set up checkpoints\n        if self.check_flag:\n            self.initialize_checkpoints(\n                graph=graph, executor=executor, \n                dataloader=dataloader, collate_fn=collate_fn)\n\n        for start_op in tqdm(interested_ops, total=len(interested_ops), desc='Advanced Optim Procedure...'):\n            assert isinstance(start_op, QuantableOperation)\n\n            if start_op in visited: continue\n            block = self.build_block_from_start(graph=graph, start_op=start_op)\n\n            end_op       = block[-1]\n            block_input  = start_op.inputs[0]\n            block_output = end_op.outputs[0]\n            \n            # dequantize prefix operations and block operations\n            for op in graph.operations.values():\n                if isinstance(op, QuantableOperation): \n                    op.dequantize()\n                    # can not use dequantize_immediately cause weight has been changed.\n                    # self.dequantize_immediately(op)\n            \n            fp32_outputs = self.collect_training_data(\n                output_name=block_output.name, dataloader=dataloader, \n                executor=executor, collate_fn=collate_fn)\n\n            # quantize prefix operations and block operations\n            for op in graph.operations.values():\n                if isinstance(op, QuantableOperation): \n                    op.restore_quantize_state()\n\n            quant_inputs = self.collect_training_data(\n                output_name= block_input.name, dataloader=dataloader, \n                executor=executor, collate_fn=collate_fn)\n\n            # start training, solve the best parameters\n            self.finetune(\n                quant_inputs=quant_inputs, fp32_outputs=fp32_outputs,\n                executor=executor, block=block, \n                dataloader=dataloader, collate_fn=collate_fn)\n            \n            for op in block: visited.add(op)\n\n            # empty cache.\n            fp32_outputs.clear()\n            quant_inputs.clear()\n            empty_cache()\n", "meta": {"hexsha": "bd602e97314adf9bdc8331da23d17195dbd63608", "size": 32170, "ext": "py", "lang": "Python", "max_stars_repo_path": "ppq/quantization/optim/training.py", "max_stars_repo_name": "wdian/ppq", "max_stars_repo_head_hexsha": "58bd1271ea6f0dfaf602eb72bdca63ea79f191b8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ppq/quantization/optim/training.py", "max_issues_repo_name": "wdian/ppq", "max_issues_repo_head_hexsha": "58bd1271ea6f0dfaf602eb72bdca63ea79f191b8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ppq/quantization/optim/training.py", "max_forks_repo_name": "wdian/ppq", "max_forks_repo_head_hexsha": "58bd1271ea6f0dfaf602eb72bdca63ea79f191b8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.5021216407, "max_line_length": 149, "alphanum_fraction": 0.6138638483, "include": true, "reason": "import numpy,from numpy", "num_tokens": 6703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3593641588823761, "lm_q1q2_score": 0.18529531731680315}}
{"text": "\"\"\"Energy calculations and histograms.\"\"\"\r\n\r\nimport abc\r\nimport collections\r\nimport datetime\r\nimport functools\r\nimport itertools\r\nimport math\r\nimport os\r\nimport pickle\r\nimport warnings\r\n\r\nimport numpy\r\nimport pandas\r\nfrom matplotlib import pyplot\r\n\r\n# Use seaborn's plotting styles.\r\ntry:\r\n    import seaborn\r\n    seaborn.set()\r\nexcept ModuleNotFoundError:\r\n    msg = \"Seaborn wasn't found.\"\r\n    warnings.warn(msg)\r\n\r\n# Energy-z histogram z-limits for the 8 by 4 plate arrangements. The\r\n# z-limits for other plate arrangements are adjusted in increments equal\r\n# to the `_plate_separation`.\r\n_z_lims_8_4 = (-65, 95)\r\n_plate_separation = 4.15 + 3.5\r\n\r\n# Energy-z histogram energy-limits.\r\n_e_lims_200 = (0, 400)  # for 200 GeV\r\n_e_lims_350 = (0, 650)  # for 350 GeV\r\n_tube_e_lims_200 = tuple(lim / 25 for lim in _e_lims_200)\r\n_tube_e_lims_350 = tuple(lim / 25 for lim in _e_lims_350)\r\n\r\n_default_bin_density = 10\r\n_default_dpi = 300\r\n_default_length_units = 'mm'\r\n_default_energy_units = 'MeV'\r\n\r\n# Just used to split energy-z plots.\r\n_PEEK_z_lims = (-43.5 / 2, 43.5 / 2)\r\n\r\n_default_tube_z_lims = (-35 / 2, 35 / 2)\r\n\r\n# Convert the _default_middle_z_lims to integers so that the plot\r\n# tick labels are displayed without decimals.\r\n_default_middle_z_lims = tuple(int(lim) for lim in (-8 / 2, 8 / 2))\r\n\r\n_default_xy_lims = 2 * ((-3, 3),)\r\n_default_xy_hist_z_lims = _default_middle_z_lims\r\n\r\n_image_format = 'jpg'\r\n_data_format = 'csv'\r\nlinewidth = 0.5\r\n\r\n\r\nclass Calc(abc.ABC):\r\n    \"\"\"\r\n    A base for calculations and presentations of results a certain\r\n    kind.\r\n\r\n        Attributes:\r\n            resultss: A collection of the results. It is a pandas DataFrame\r\n            in this base class, but that can change.\r\n\r\n            piece: Piece of analysis that this calculation is for.\r\n\r\n            save_dir: Save output in this folder.\r\n\r\n            save_name: A name for the saved files.\r\n    \"\"\"\r\n\r\n    def __init__(self, piece):\r\n        self._piece = piece\r\n        self.resultss = pandas.DataFrame()\r\n\r\n        if self._piece.out_dir:\r\n            # Save when Piece has an output directory.\r\n            self.save_dir = self._piece.out_dir\r\n            self.save_name = self._piece.name\r\n        else:\r\n            self.save_dir = None\r\n            self.save_name = None\r\n\r\n    def __repr__(self):\r\n        return repr(self.resultss)\r\n\r\n    def get(self, i=None):\r\n        \"\"\"\r\n        Get the ith set of results, or if i isn't given, make sure\r\n        resultss contains only one entry and return it.\r\n\r\n        :param i: The index of the results to get.\r\n        :type i: int or None\r\n        :return: Results.\r\n        :rtype:\r\n        \"\"\"\r\n        if i is None:\r\n            self._assert_single_entry()\r\n            return self.resultss.loc[0]\r\n\r\n        return self.resultss.loc[i]\r\n\r\n    def add_data(self, data):\r\n        \"\"\"\r\n        Calculate results from data and keep them.\r\n\r\n        :param data: Hits data.\r\n        :type data: pandas.DataFrame\r\n        :return:\r\n        :rtype:\r\n        \"\"\"\r\n        self.add_results(self._data2results(data))\r\n\r\n    def add_results(self, results):\r\n        \"\"\"\r\n        Keep some already calculated results (after making sure they are\r\n        good results).\r\n\r\n        :param results: Results to add.\r\n        :type results: pandas.Series or dict or collections.OrderedDict\r\n        :return:\r\n        :rtype: None\r\n        \"\"\"\r\n        self._check_results(results)\r\n        self.resultss = _ordered_append(self.resultss, results)\r\n\r\n    def save(self):\r\n        \"\"\"\r\n        Save results to a csv file if save_dir is set.\r\n\r\n        :return: Path to saved results file.\r\n        :rtype: str\r\n        \"\"\"\r\n        if not self.save_dir:\r\n            return None\r\n\r\n        filename = '.'.join((self.save_name, _data_format))\r\n        filepath = os.path.join(self.save_dir, filename)\r\n\r\n        return save_dataframe(self.resultss, filepath)\r\n\r\n    def pickle_save(self, filepath=None):\r\n        \"\"\"Save self in a pickle format. Does nothing if `filepath`\r\n        isn't given and `self.save_dir` is not set.\r\n\r\n        :param filepath: Location to save. If not given, use\r\n        `self.save_dir`.\r\n        \"\"\"\r\n        if not filepath:\r\n            if not self.save_dir:\r\n                return\r\n            filepath = os.path.join(self.save_dir, self.save_name + '.p')\r\n        with open(filepath, 'wb') as file:\r\n            pickle.dump(self, file)\r\n\r\n    def _assert_single_entry(self):\r\n        \"\"\"Make sure only one set of results has been added.\"\"\"\r\n        assert len(self.resultss) == 1, \\\r\n            \"This Calc container does not have a single entry.\"\r\n\r\n    def _assert_multiple_entries(self):\r\n        \"\"\"Make sure more than one set of results has been added.\"\"\"\r\n        assert len(self.resultss) > 1, \\\r\n            \"This Calc container does not have more than one set of\" \\\r\n            \" results.\"\r\n\r\n    def _assert_nonempty(self):\r\n        \"\"\"Make sure at least one set of results has been added.\"\"\"\r\n        assert len(self.resultss) >= 1, \\\r\n            \"This Calc container is empty.\"\r\n\r\n    @abc.abstractmethod\r\n    def _data2results(self, data):\r\n        \"\"\"\r\n        Calculate results from hits data and return them.\r\n\r\n        :param data: Hits data.\r\n        :return: Calc results.\r\n        \"\"\"\r\n\r\n    @abc.abstractmethod\r\n    def _check_results(self, results):\r\n        \"\"\"Make sure some calculated results are good to keep.\"\"\"\r\n\r\n\r\nclass Numbers(Calc):\r\n    \"\"\"\r\n    The numbers don't lie.\r\n\r\n    This class manages calculations of different numbers from the data\r\n    and writes them to files.\r\n    \"\"\"\r\n\r\n    def add_data(self, data, tags=None):\r\n        self.add_results(self._data2results(data, tags))\r\n\r\n    def append_mean_and_uncertainties(\r\n            self, mean_tags=None, std_tags=None, sem_tags=None\r\n    ):\r\n        \"\"\"\r\n        Append mean, standard deviation and standard error entries to\r\n        the collection of results.\r\n\r\n        :param mean_tags: Tags to use for the new means entry.\r\n        :type mean_tags: dict or collections.OrderedDict or None\r\n        :param std_tags: Tags to use for the new standard deviation\r\n            entry.\r\n        :type std_tags: dict or collections.OrderedDict or None\r\n        :param sem_tags: Tags to use for the new standard error in the\r\n            mean entry.\r\n        :type sem_tags: dict or collections.OrderedDict or None\r\n        :return: The new mean, standard deviation, and standard error.\r\n        :rtype:\r\n        \"\"\"\r\n        # Pandas' std function gives NANs for DataFrames with only one\r\n        # entry.\r\n        self._assert_multiple_entries()\r\n\r\n        new_rows = [self.resultss.mean(), self.resultss.std()]\r\n        new_rows.append(  # standard error\r\n            new_rows[1] / math.sqrt(len(self.resultss))\r\n        )\r\n\r\n        for i, tags in enumerate((mean_tags, std_tags, sem_tags)):\r\n            if tags:\r\n                new_rows[i] = pandas.Series(tags).combine_first(new_rows[i])\r\n            self.add_results(new_rows[i])\r\n\r\n        return new_rows\r\n\r\n    def _data2results(self, data, tags=None):\r\n        \"\"\"\r\n\r\n        :param data:\r\n        :type data:\r\n        :param tags: Extra result values for tagging an entry (e.g. with\r\n            its event and run).\r\n        :type tags: dict or collections.OrderedDict or None\r\n        :return:\r\n        :rtype:\r\n        \"\"\"\r\n        new_results = collections.OrderedDict()\r\n\r\n        if tags:\r\n            new_results.update(tags)\r\n\r\n        new_results.update(self.__split_z(data))\r\n\r\n        return new_results\r\n\r\n    def _check_results(self, results):\r\n        assert len(results) <= 9, \"Tried to add funny results.\"\r\n\r\n    @staticmethod\r\n    def __split_z(data):\r\n        \"\"\"\r\n        Calculate energy deposit mean and std dev on sections of\r\n        data split up along z.\r\n\r\n        :param data: Hits data.\r\n        :type data: pandas.DataFrame\r\n        :return: Calculation results.\r\n        :rtype: dict\r\n        \"\"\"\r\n        tube_indices = numpy.logical_and(\r\n            _default_tube_z_lims[0] <= data.z,\r\n            data.z <= _default_tube_z_lims[1]\r\n        )\r\n        middle_indices = numpy.logical_and(\r\n            _default_middle_z_lims[0] <= data.z,\r\n            data.z <= _default_middle_z_lims[1]\r\n        )\r\n        return {\r\n            'full_e_dep':\r\n                data.energy_deposit.sum(),\r\n            'tube_e_dep':\r\n                data.energy_deposit[tube_indices].sum(),\r\n            'middle_e_dep':\r\n                data.energy_deposit[middle_indices].sum(),\r\n        }\r\n\r\n    @staticmethod\r\n    def __tubes(data):\r\n        \"\"\"TODO: Document and organize this.\"\"\"\r\n        offset = 7.5 / 4\r\n        # TODO: Change default to self (probably don't need to do this).\r\n        data = data[numpy.logical_and(\r\n            _default_middle_z_lims[0] < data.z,\r\n            data.z < _default_middle_z_lims[1]\r\n        )]\r\n\r\n        bottom = data.y <= 0\r\n        top = data.y > 0\r\n\r\n        bottom_left = numpy.logical_and(bottom, data.x <= -offset)\r\n        bottom_right = numpy.logical_and(bottom, data.x > -offset)\r\n        top_left = numpy.logical_and(top, data.x <= offset)\r\n        top_right = numpy.logical_and(top, data.x > offset)\r\n\r\n        bottom_left_sum = data.energy_deposit[bottom_left].sum()\r\n        bottom_right_sum = data.energy_deposit[bottom_right].sum()\r\n        top_left_sum = data.energy_deposit[top_left].sum()\r\n        top_right_sum = data.energy_deposit[top_right].sum()\r\n\r\n        return {\r\n            'top_right': top_right_sum,\r\n            'top_left': top_left_sum,\r\n            'bottom_left': bottom_left_sum,\r\n            'bottom_right': bottom_right_sum\r\n        }\r\n\r\n\r\nclass Histogram(Calc):\r\n    \"\"\"\r\n    Base histogram.\r\n\r\n        Attributes:\r\n            bin_density: E.g. bins per mm.\r\n\r\n            dpi: Dots per inch for images.\r\n\r\n            title: The plot title.\r\n\r\n    TODO: Add the option to close all the plot figures created.\r\n    \"\"\"\r\n\r\n    def __init__(\r\n            self,\r\n            piece,\r\n            title=None,\r\n            bin_density=None,\r\n            dpi=None,\r\n            energy_units=None,\r\n            length_units=None\r\n    ):\r\n        super().__init__(piece)\r\n\r\n        # Attributes with defaults.\r\n        self.title = title or self._default_title\r\n        self.bin_density = bin_density or _default_bin_density\r\n        self.dpi = dpi or _default_dpi\r\n        self.energy_units = energy_units or _default_energy_units\r\n        self.length_units = length_units or _default_length_units\r\n\r\n    def save_fig(self, fig, file_suffix):\r\n        \"\"\"\r\n        Save a figure to a new file if save_dir is set.\r\n\r\n        :param fig: The figure to save.\r\n        :type fig: figure\r\n        :param file_suffix: Added to the end of the saved filename.\r\n        :type file_suffix: str or None\r\n        :return: File path of the saved figure.\r\n        :rtype: str\r\n        \"\"\"\r\n        if not self.save_dir:\r\n            return None\r\n\r\n        if file_suffix:\r\n            save_name = '-'.join((self.save_name, file_suffix))\r\n        else:\r\n            save_name = self.save_name\r\n\r\n        filename = '.'.join((save_name, _image_format))\r\n        filepath = os.path.join(self.save_dir, filename)\r\n\r\n        fig.savefig(\r\n            filepath, dpi=self.dpi, format=_image_format, bbox_inches='tight'\r\n        )\r\n\r\n        return filepath\r\n\r\n    def _to_density(self, sums):\r\n        \"\"\"\r\n        Convert values from units of energy/bin to units of\r\n        energy/distance.\r\n\r\n        :param sums: Values to convert.\r\n        :type sums: numpy.ndarray\r\n        :return: Converted values.\r\n        :rtype: numpy.ndarray\r\n        \"\"\"\r\n        return sums * self.bin_density\r\n\r\n    @property\r\n    def _default_title(self):\r\n        \"\"\"Default plot title.\"\"\"\r\n        raise NotImplementedError\r\n\r\n    @abc.abstractmethod\r\n    def plot_single(self, i=None, save=True):\r\n        \"\"\"\r\n        Plot the ith set of sums. If i isn't given, assume there is only\r\n        set of sums and plot it.\r\n\r\n        :param save: Save to file with the standard filename if True.\r\n        :type save: bool\r\n        :param i: Index of the sums.\r\n        :type i: int\r\n        :return: New figure and axis/axes.\r\n        :rtype: tuple\r\n        \"\"\"\r\n\r\n    @abc.abstractmethod\r\n    def plot_means(self):\r\n        \"\"\"\r\n        Plot the mean, and maybe the standard deviation, of all results.\r\n\r\n        :return: New figure and axis/axes.\r\n        :rtype: tuple\r\n        \"\"\"\r\n\r\n    @abc.abstractmethod\r\n    def _make_fig_and_axes(self):\r\n        \"\"\"\r\n        Make a new labeled figure and axis/axes.\r\n\r\n        :return: The figure and axis/axes.\r\n        :rtype: tuple\r\n        \"\"\"\r\n\r\n\r\nclass EnergyVsZ(Histogram):\r\n    \"\"\"\r\n    Histograms of energy deposit vs. z.\r\n\r\n        Attributes:\r\n            e_lims: Overall energy/y-axis limits.\r\n\r\n            tube_e_lims: Tube energy/y-axis limits.\r\n\r\n            z_lims: Overall z limits.\r\n\r\n            tube_z_lims: Tube z limits.\r\n\r\n            middle_z_lims: Tube middle section z limits.\r\n    \"\"\"\r\n\r\n    _default_title = 'Energy vs. z.'\r\n\r\n    def __init__(\r\n            self,\r\n            piece,\r\n            title=None,\r\n            e_lims=None,\r\n            tube_e_lims=None,\r\n            z_lims=None,\r\n            tube_z_lims=None,\r\n            middle_z_lims=None,\r\n            **kwargs\r\n    ):\r\n        super().__init__(piece, title, **kwargs)\r\n\r\n        # Limits according to piece info.\r\n        self.__e_lims, self.__tube_e_lims, self.__z_lims = self.__get_lims(\r\n            e_lims, tube_e_lims, z_lims\r\n        )\r\n\r\n        self.__tube_z_lims = tube_z_lims or _default_tube_z_lims\r\n        self.__middle_z_lims = middle_z_lims or _default_middle_z_lims\r\n\r\n        # Histogram bins.\r\n        self.__bins = _make_bins(\r\n            self.__z_lims[0], self.__z_lims[1], self.bin_density\r\n        )\r\n        self.__bin_mids = _make_bin_midpoints(self.__bins)\r\n\r\n    def plot_single(self, i=None, save=True, energy_label=None):\r\n        \"\"\"\r\n        Plot a single event.\r\n\r\n        :param energy_label: Energy deposit in middle tube sections,\r\n            displayed in a text label on the plot.\r\n        \"\"\"\r\n        fig, ax, ax_middle = self._make_fig_and_axes()\r\n        fig.suptitle(self.title)\r\n        self.__label_middle(ax_middle, energy_label)\r\n\r\n        tube_kwargs = {\r\n            'linewidth': linewidth, 'color': 'purple', 'label': 'Tube Cals'\r\n        }\r\n        plate_kwargs = {\r\n            'linewidth': linewidth, 'color': 'blue', 'label': 'Plate Cals'\r\n        }\r\n        self.__split_plot(\r\n            x=self.__bin_mids,\r\n            ys=(self._to_density(self.get(i)),),\r\n            plot_fn=ax_middle.show_plots,\r\n            main_ax=ax,\r\n            kwargs1=tube_kwargs,\r\n            kwargs2=plate_kwargs\r\n        )\r\n\r\n        self.__add_legend(fig, ax, ax_middle)\r\n        if save:\r\n            self.save_fig(fig, file_suffix='z')\r\n\r\n    def plot_means(self, energy_label=None):\r\n        fig, ax, ax_middle = self._make_fig_and_axes()\r\n        fig.suptitle(self.title + ' Averaged.')\r\n        self.__label_middle(ax_middle, energy_label)\r\n\r\n        means = self._to_density(numpy.mean(self.resultss, axis=0))\r\n        stds = self._to_density(numpy.std(self.resultss, axis=0))\r\n\r\n        tube_means_kwargs = {\r\n            'linewidth': linewidth,\r\n            'color': 'purple',\r\n            'label': 'Tube Cals Average'\r\n        }\r\n        plate_means_kwargs = {\r\n            'linewidth': linewidth,\r\n            'color': 'blue',\r\n            'label': 'Plate Cals Average'\r\n        }\r\n        tube_stds_kwargs = tube_means_kwargs.copy()\r\n        plate_stds_kwargs = plate_means_kwargs.copy()\r\n        tube_stds_kwargs.update({'alpha': 0.3, 'label': 'Standard Deviation'})\r\n        plate_stds_kwargs.update({'alpha': 0.3, 'label': 'Standard Deviation'})\r\n\r\n        self.__split_plot(  # Plot means.\r\n            x=self.__bin_mids,\r\n            ys=(means,),\r\n            plot_fn=ax_middle.show_plots,\r\n            main_ax=ax,\r\n            kwargs1=tube_means_kwargs,\r\n            kwargs2=plate_means_kwargs\r\n        )\r\n        self.__split_plot(  # Plot standard deviations.\r\n            x=self.__bin_mids,\r\n            ys=(means + stds, means - stds),\r\n            plot_fn=ax_middle.fill_between,\r\n            main_ax=ax,\r\n            kwargs1=tube_stds_kwargs,\r\n            kwargs2=plate_stds_kwargs\r\n        )\r\n\r\n        self.__add_legend(fig, ax, ax_middle)\r\n        self.save_fig(fig, file_suffix='z')\r\n\r\n    def plot_multi(self, energy_label=None):\r\n        \"\"\"Plot all of the events on one graph at once.\"\"\"\r\n        fig, ax, ax_middle = self._make_fig_and_axes()\r\n        num_events = len(self.resultss)\r\n        fig.suptitle(self.title + f' {num_events} events.')\r\n        self.__label_middle(ax_middle, energy_label)\r\n\r\n        kwargs = {'linewidth': linewidth, 'alpha': 0.2}\r\n        colors = itertools.cycle((\r\n            'red', 'orange', 'yellow', 'pink', 'purple', 'brown', 'black'\r\n        ))\r\n        for _, sums in self.resultss.iterrows():\r\n            kwargs['color'] = next(colors)\r\n            self.__split_plot(\r\n                x=self.__bin_mids,\r\n                ys=(self._to_density(sums),),\r\n                plot_fn=ax_middle.show_plots,\r\n                main_ax=ax,\r\n                kwargs1=kwargs,\r\n                kwargs2=kwargs\r\n            )\r\n\r\n        self.save_fig(fig, file_suffix=f'z-{num_events}events')\r\n\r\n    def _data2results(self, data):\r\n        return pandas.Series(\r\n            numpy.histogram(\r\n                data.z, bins=self.__bins, weights=data.energy_deposit\r\n            )[0],\r\n            index=self.__bin_mids\r\n        )\r\n\r\n    def _check_results(self, sums):\r\n        assert len(sums) == (len(self.__bins) - 1), \\\r\n            \"Tried to add funny histogram sums.\"\r\n\r\n    def _make_fig_and_axes(self):\r\n        fig, ax = pyplot.subplots()\r\n        ax_middle = ax.twinx()\r\n\r\n        ax.set_xlabel(f'z ({self.length_units})')\r\n        ax.set_ylabel(\r\n            'E Dep Density - Plate Cals'\r\n            f' ({self.energy_units} / {self.length_units})'\r\n        )\r\n        ax_middle.set_ylabel(\r\n            'E Dep Density - Tube Cals'\r\n            f' ({self.energy_units} / {self.length_units})'\r\n        )\r\n\r\n        # Indicate the middle tube sections with vertical bars and axis\r\n        # ticks.\r\n        for lim in self.__middle_z_lims:\r\n            ax_middle.axvline(\r\n                lim, linestyle='--', linewidth=1, color='gray', zorder=0\r\n            )\r\n        ax_middle.set_xticks(self.__middle_z_lims, minor=True)\r\n        ax_middle.set_xticklabels(self.__middle_z_lims, minor=True)\r\n\r\n        # for axes in (ax, ax_middle):\r\n        #     axes.spines['right'].set_visible(False)\r\n        #     axes.spines['top'].set_visible(False)\r\n\r\n        for axes, e_limits in zip(\r\n                (ax, ax_middle), (self.__e_lims, self.__tube_e_lims)\r\n        ):\r\n            axes.set_xlim(self.__z_lims)\r\n            axes.set_ylim(e_limits)\r\n\r\n        return fig, ax, ax_middle\r\n\r\n    def __split_plot(\r\n            self, x, ys, plot_fn, main_ax, kwargs1=None, kwargs2=None\r\n    ):\r\n        \"\"\"\r\n        Split up data and plot it on two axes.\r\n\r\n        The data with x values inside split_lims (inclusive) is plotted\r\n        using `plot_fn` normally, and the rest is scaled to `main_ax`.\r\n\r\n        :param x: x values.\r\n        :type x: 1d array\r\n        :param ys: All the y values.\r\n        :type ys: 2d array\r\n        :param plot_fn: Function that plots data to the middle axes.\r\n            The middle axes are displayed on top, so all plotting uses\r\n            this function to avoid overlapping axes.\r\n        :type plot_fn: function\r\n        :param main_ax: The main axes, which lie underneath the middle\r\n            axes.\r\n        :type ax2_plot_func: matplotlib.pyplot.axes\r\n        :param kwargs1: Keyword arguments passed to the middle plot.\r\n        :type kwargs1: dict or None\r\n        :param kwargs2: Keyword arguments passed to the full plot.\r\n        :type kwargs2: dict or None\r\n        :return: The two plot results.\r\n        :rtype: (handle, handle)\r\n        \"\"\"\r\n        kwargs1 = kwargs1 or None\r\n        kwargs2 = kwargs2 or None\r\n\r\n        inside_indices = _range2indices(x, _PEEK_z_lims)\r\n        outside_indices = numpy.logical_not(inside_indices)\r\n\r\n        plots = plot_fn(\r\n            x[outside_indices],\r\n            *(y[outside_indices] for y in ys),\r\n            transform=main_ax.transData,\r\n            **kwargs2\r\n        )\r\n        plots_middle = plot_fn(\r\n            x[inside_indices],\r\n            *(y[inside_indices] for y in ys),\r\n            **kwargs1\r\n        )\r\n        return plots, plots_middle\r\n\r\n    def __label_middle(self, ax, energy_label):\r\n        \"\"\"Label the energy deposit in the middle tube sections.\"\"\"\r\n        if energy_label:\r\n            ax.annotate(\r\n                energy_label,\r\n                bbox={\r\n                    'boxstyle': 'round4',\r\n                    'facecolor':\r\n                        pyplot.style.library['seaborn']['axes.facecolor'],\r\n                    'edgecolor': 'silver',\r\n                    'alpha': 0.7\r\n                },\r\n                xy=(0, 0),\r\n                xycoords='data',\r\n                xytext=(0, 25),\r\n                textcoords='offset points',\r\n                horizontalalignment='center',\r\n                verticalalignment='center'\r\n            )\r\n\r\n    def __get_lims(self, e_lims=None, tube_e_lims=None, z_lims=None):\r\n        \"\"\"\r\n        Get the plot energy-limits for both sets of axes (full and\r\n        tubes) and the plot z-limits from Piece info.\r\n\r\n        The z-limits are shifted from the default 8 by 4 limits in\r\n        increments equal to the `_plate_separation`. Arguments passed in\r\n        will override the calculated limits.\r\n        \"\"\"\r\n        if ('incident_energy' not in self._piece.info) \\\r\n                or (self._piece.info['incident_energy'] == '350gev'):\r\n            if not e_lims:\r\n                e_lims = _e_lims_350\r\n            if not tube_e_lims:\r\n                tube_e_lims = _tube_e_lims_350\r\n        else:\r\n            if not e_lims:\r\n                e_lims = _e_lims_200\r\n            if not tube_e_lims:\r\n                tube_e_lims = _tube_e_lims_200\r\n\r\n        if not z_lims:\r\n            plates = self._piece.info.get('plates')\r\n            if (not plates) or plates == (8, 4):\r\n                z_lims = _z_lims_8_4\r\n            else:\r\n                z_lims = (\r\n                    # limit at back plate\r\n                    _z_lims_8_4[0] - (plates[1] - 4) * _plate_separation,\r\n                    # limit at front plate\r\n                    _z_lims_8_4[1] + (plates[0] - 8) * _plate_separation\r\n                )\r\n\r\n        return e_lims, tube_e_lims, z_lims\r\n\r\n    @staticmethod\r\n    def __add_legend(fig, ax, ax_middle):\r\n        \"\"\"Place a legend at the upper-right corner of the axes\"\"\"\r\n        # Combine legend handles and labels from both axes.\r\n        handles, labels = (val1 + val2 for val1, val2 in zip(\r\n            ax.get_legend_handles_labels(),\r\n            ax_middle.get_legend_handles_labels()\r\n        ))\r\n\r\n        legend = ax_middle.legend(\r\n            handles,\r\n            labels,\r\n            loc='upper right',\r\n            ncol=2,\r\n            fontsize='small',\r\n\r\n            # Place legend at the corner of the axes rather.\r\n            # `figure.legend` places the legend at the corner of the\r\n            # figure instead.\r\n            # bbox_to_anchor=(1, 1),\r\n            # bbox_transform=ax.transAxes\r\n        )\r\n        legend.set_zorder(1)\r\n\r\n\r\nclass EnergyVsXY(Histogram):\r\n    \"\"\"Histogram of energy deposit vs. x and y.\"\"\"\r\n\r\n    _default_title = 'Energy vs. x and y.'\r\n\r\n    def __init__(self, piece, title=None, xy_lims=None, z_lims=None):\r\n        super().__init__(piece, title)\r\n        self.resultss = []  # Ust a list instead of a DataFrame.\r\n\r\n        # Attributes with defaults.\r\n        self.__xy_lims = xy_lims or _default_xy_lims\r\n        self.__z_lims = z_lims or _default_xy_hist_z_lims\r\n\r\n        self.__binss = tuple(\r\n            _make_bins(limits[0], limits[1], self.bin_density)\r\n            for limits in self.__xy_lims\r\n        )\r\n        self.__binss_mesh = numpy.meshgrid(*self.__binss)\r\n        # self.__bin_midss = tuple(\r\n        #     _make_bin_midpoints(bins) for bins in self.__binss\r\n        # )\r\n\r\n    def plot_single(self, i=None, save=True):\r\n        fig, ax = self._make_fig_and_axes()\r\n        fig.suptitle(self.title)\r\n\r\n        ax.pcolormesh(*self.__binss_mesh, self._to_density(self.get(i)))\r\n\r\n        if save:\r\n            self.save_fig(fig, file_suffix='xy')\r\n\r\n    def plot_means(self):\r\n        fig, ax = self._make_fig_and_axes()\r\n        fig.suptitle(self.title + ' Averaged.')\r\n\r\n        ax.pcolormesh(\r\n            *self.__binss_mesh,\r\n            self._to_density(numpy.mean(self.resultss, axis=0))\r\n        )\r\n\r\n        self.save_fig(fig, file_suffix='xy')\r\n\r\n    def get(self, i=None):\r\n        \"\"\"\r\n        Overrides the base to get from a list instead of a DataFrame.\r\n        \"\"\"\r\n        if i is None:\r\n            self._assert_single_entry()\r\n            return self.resultss[0]\r\n\r\n        return self.resultss[i]\r\n\r\n    def add_results(self, sums):\r\n        \"\"\"\r\n        Overrides the base to append to a list instead of a DataFrame.\r\n        \"\"\"\r\n        self._check_results(sums)\r\n        self.resultss.append(sums)\r\n\r\n    def _data2results(self, data):\r\n        sliced = data[numpy.logical_and(\r\n            self.__z_lims[0] <= data.z, data.z <= self.__z_lims[1]\r\n        )]\r\n        # Transpose the sums to match the xy/Cartesian indexing used by\r\n        # `numpy.meshgrid` and Matplotlib's `pcolormesh`.\r\n        return numpy.histogram2d(\r\n            sliced.x, sliced.y, bins=self.__binss, weights=sliced.energy_deposit\r\n        )[0].T\r\n\r\n    def _check_results(self, sums):\r\n        \"\"\"Check that `sums` is the correct shape for the bins.\"\"\"\r\n        assert numpy.all(numpy.equal(\r\n            sums.shape,\r\n            tuple(len(bins) - 1 for bins in self.__binss)\r\n        ))\r\n\r\n    def _make_fig_and_axes(self):\r\n        fig, ax = pyplot.subplots()\r\n        fig.tight_layout(rect=(0, 0, 1, 0.86))\r\n\r\n        ax.set_xlabel(f'x ({self.length_units})')\r\n        ax.set_ylabel(f'y ({self.length_units})')\r\n\r\n        # No need to set x limits since the axes will be equal.\r\n        # ax.set_xlim(self.__xy_lims[0])\r\n        ax.set_ylim(self.__xy_lims[1])\r\n\r\n        ax.set_aspect('equal')\r\n\r\n        return fig, ax\r\n\r\n\r\ndef save_dataframe(dataframe, path):\r\n    \"\"\"\r\n    Write a DataFrame to a csv file with nicely spaced columns and a\r\n    header, and also write it to a second file compatible with Office\r\n    365 (since it seems to prohibit the use of csv's).\r\n\r\n    :param dataframe: The DataFrame to save.\r\n    :param path: Path to save the files at. The extension of the\r\n        filename at `path` is ignored and replaced with 'csv' and\r\n        'xlsx'.\r\n    :return: The paths to the saved files, (csv_path, excel_path).\r\n    \"\"\"\r\n    tail, ext = os.path.splitext(path)\r\n\r\n    csv_path = tail + '.csv'\r\n    header = (\r\n        'FCal and SCal analysis output.'\r\n        f' {datetime.datetime.now().ctime()}'\r\n    )\r\n    with open(csv_path, 'w') as file:\r\n        file.write('\\n'.join((\r\n            header,\r\n            dataframe.to_string(index=False),\r\n            ''\r\n        )))\r\n\r\n    excel_path = tail + '.xlsx'\r\n    dataframe.to_excel(excel_path, index=False)\r\n\r\n    return csv_path, excel_path\r\n\r\n\r\ndef _range2indices(array, range_lims):\r\n    \"\"\"\r\n    Find the values of an array that are inclusively within range_lims.\r\n\r\n    :param array: Array of values that are compared to range_lims.\r\n    :type array: numpy.ndarray\r\n    :param range_lims: (lower limit, upper limit)\r\n    :type range_lims: (float, float)\r\n    :return: Boolean array locating the indices of the values within the\r\n        range.\r\n    :rtype: numpy.ndarray\r\n    \"\"\"\r\n    return numpy.logical_and(range_lims[0] <= array, array <= range_lims[1])\r\n\r\n\r\n@functools.lru_cache()\r\ndef _make_bins(start, end, bin_density):\r\n    \"\"\"\r\n    Make histogram bins with a given bin density.\r\n\r\n    Since the bin density is fixed, the bins start exactly at `start`\r\n    and end at a rounded up value near `end`.\r\n\r\n    :param start: Exact start of the first bin.\r\n    :type start: float\r\n    :param end: Lower limit of the end of last bin.\r\n    :type end: float\r\n    :param bin_density: Exact bin density.\r\n    :type bin_density: float\r\n    :return: Bin endpoints.\r\n    :rtype: numpy.ndarray\r\n    \"\"\"\r\n    assert (end > start)\r\n\r\n    # Round the end limit so the bin size is correct.\r\n    num_bins = math.ceil(bin_density * (end - start))\r\n    new_end = start + num_bins / bin_density\r\n\r\n    return numpy.linspace(start, new_end, num_bins + 1)\r\n\r\n\r\n# @functools.lru_cache()\r\ndef _make_bin_midpoints(bins):\r\n    \"\"\"Get midpoints of histogram bins.\"\"\"\r\n    return (bins[:-1] + bins[1:]) / 2\r\n\r\n\r\ndef _ordered_append(dataframe, other):\r\n    \"\"\"\r\n    Append `other` to `dataframe` while keeping the order of the columns\r\n    in both.\r\n\r\n    The `append` method that comes with pandas Dataframes alphabetizes\r\n    the order of the columns, which may not always be desired. This\r\n    function provides an alternative.\r\n\r\n    :param dataframe: The DataFrame to append to.\r\n    :type dataframe: pandas.DataFrame\r\n    :param other: The data to append.\r\n    :type other: pandas.DataFrame or pandas.Series/dict-like object,\r\n        or list of these\r\n    :return: New DataFrame with appended data.\r\n    :rtype: pandas.DataFrame\r\n    \"\"\"\r\n    # The new column order. New columns from `other` are inserted in\r\n    # front of the original `dataframe` columns.\r\n    columns = [\r\n                  col for col in other.keys() if col not in dataframe.keys()\r\n              ] + list(dataframe.keys())\r\n\r\n    # pandas' append alphabetizes the columns here. Indexing the result\r\n    # with `columns` sets our own column order.\r\n    return dataframe.append(other, ignore_index=True)[columns]\r\n", "meta": {"hexsha": "e3576e349c9470b264bf75f4c6e5cc6cfe475082", "size": 30024, "ext": "py", "lang": "Python", "max_stars_repo_path": "analysis/calc.py", "max_stars_repo_name": "atlas-forward-calorimeter/showers", "max_stars_repo_head_hexsha": "fa47f9f0d6e8237a0b067e5289578d8368d1908f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analysis/calc.py", "max_issues_repo_name": "atlas-forward-calorimeter/showers", "max_issues_repo_head_hexsha": "fa47f9f0d6e8237a0b067e5289578d8368d1908f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analysis/calc.py", "max_forks_repo_name": "atlas-forward-calorimeter/showers", "max_forks_repo_head_hexsha": "fa47f9f0d6e8237a0b067e5289578d8368d1908f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0085287846, "max_line_length": 81, "alphanum_fraction": 0.5730082601, "include": true, "reason": "import numpy", "num_tokens": 6927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.18529531024132528}}
{"text": "# -*- coding: utf-8 -*-\n\n\"\"\"Functions and classes for reading and writing ADIPLS binary output.  Many\nreturn or contain what I call ``cs`` arrays.  These are defined in Section 8.2 of\nthe `ADIPLS documentation`_.  They are structured arrays containing\nvarious scalar results from the frequency calculation.\n\n    .. _ADIPLS documentation: https://sourceforge.net/p/mesa/code/HEAD/tree/trunk/adipls/adipack.c/notes/adiab.prg.c.pdf\n\"\"\"\nimport numpy as np\nimport warnings\nfrom .constants import G_DEFAULT\nfrom .utils import integrate, complement, regularize\nfrom .utils import AdiabaticStellarModel\n\n\ndef read_one_cs(f):\n    \"\"\"Utility function to parse one ``cs`` array from a binary file\n    handle ``f``.\"\"\"\n    cs = np.fromfile(f, dtype=cs_floats, count=1)\n    cs = cs.astype(cs_dtypes, copy=False)\n    return cs\n\n\ndef load_pointwise_data(filename, ncols):\n    \"\"\"Utility function for common structure of ADIPLS data that has a\n    value at each point in a stellar model. e.g. eigenfunction or\n    kernel files.\n\n    Parameters\n    ----------\n    filename: str\n        Name of the file to be read.\n    ncols: int\n        Number of columns in the data.\n\n    Returns\n    -------\n    css: structured array\n        The ``cs`` arrays for each mode.\n    data: list of arrays\n        The point-wise data arrays for each mode.\n\n    \"\"\"\n    css = []\n    data = []\n\n    with open(filename, 'rb') as f:\n        while True:\n            if not f.read(4): break\n            css.append(read_one_cs(f))\n            nnw = np.fromfile(f, dtype='i', count=1)[0]\n            row = np.fromfile(f, dtype='d', count=ncols*nnw).reshape((-1, ncols))\n            data.append(row)\n            f.read(4)\n\n    return np.squeeze(css), np.squeeze(data)\n\n\ndef load_agsm(filename, return_object=True):\n    \"\"\"Reads an ADIPLS grand summary file and returns a structured array.\n\n    If `return_object` is `True`, instead returns an\n    :py:class:`ADIPLSGrandSummary` object.  This is the\n    default behaviour as of v0.0.12.  The old behaviour will be\n    dropped completely from v0.1.0.\n\n    Parameters\n    ----------\n    filename: str\n        Name of the grand summary file, usually starting or ending\n        with ``agsm``.\n\n    Returns\n    -------\n    css: structured array\n        The ``cs`` arrays for each mode.\n\n    \"\"\"\n\n    css = []\n\n    with open(filename, 'rb') as f:\n        while True:\n            if not f.read(4): break\n            css.append(read_one_cs(f))\n            f.read(4)\n\n    if return_object:\n        return ADIPLSGrandSummary(np.squeeze(css))\n    else:\n        warnings.warn(\"From tomso 0.1.0+, `adipls.load_agsm` will only \"\n                      \"return an `ADIPLSGrandSummary` object: use \"\n                      \"`return_object=True` to mimic future behaviour\",\n                      FutureWarning)\n        return np.squeeze(css)\n\n\ndef load_amde(filename, nfmode=1, return_object=True):\n    \"\"\"Reads an ADIPLS eigenfunction file written with the specified value\n    of ``nfmode`` in the input file (either 1, 2 or 3).\n\n    If `return_object` is `True`, instead returns an\n    :py:class:`ADIPLSEigenfunctions` object.  This is the default\n    behaviour as of v0.0.12.  The old behaviour will be dropped\n    completely from v0.1.0.\n\n    Parameters\n    ----------\n    filename: str\n        Name of the eigenfunction file, usually starting or ending\n        with ``amde``.\n    nfmode: int, optional\n        ADIPLS's ``nfmode`` parameter, which determines the format of\n        the eigenfunction data.  See Section 8.4 of the `ADIPLS\n        documentation`_ for details of the output.  Note that for\n        ``nfmode=2`` or ``3``, the fractional radius is returned as an\n        extra (third) component.\n\n    Returns\n    -------\n    css: structured array\n        The ``cs`` arrays for each mode.\n    eigs: list of arrays\n        The eigenfunction arrays for each mode.  Each array has seven\n        columns: the fractional radius :math:`x` and six columns of\n        ADIPLS's :math:`y` matrix.  The first four columns of\n        :math:`y` are defined by equation (2.5) of the documentation\n        and the last two by equations (4.4) and (4.6).\n    x: array\n        Fractional radius co-ordinate ``x`` of the eigenfunctions.  If\n        ``nfmode=1``, the radial co-ordinate is also stored in\n        ``eigs[...,0]`` but it's returned anyway so that the returned\n        data always has the same structure.\n\n    \"\"\"\n\n    if nfmode == 1:\n        css, data = load_pointwise_data(filename, 7)\n        x = data[0,:,0]\n    elif nfmode == 2 or nfmode == 3:\n        # thanks to Vincent Boening for this\n        ncols = 2\n        css = []\n        data = []\n        with open(filename, 'rb') as f:\n            f.read(4)\n            nnw = np.fromfile(f, dtype='i', count=1)[0]\n            x = np.fromfile(f, dtype='d', count=nnw)\n            f.read(4)\n\n            while True:\n                if not f.read(4): break\n                css.append(read_one_cs(f))\n                row = np.fromfile(f, dtype='d', count=ncols*nnw).reshape((-1, ncols))\n                data.append(row)\n                f.read(4)\n    else:\n        raise ValueError('nfmode must be 1, 2 or 3 but got %i' % nfmode)\n\n    if return_object:\n        return ADIPLSEigenfunctions(np.squeeze(css), np.squeeze(data), x=x, nfmode=nfmode)\n    else:\n        warnings.warn(\"From tomso 0.1.0+, `adipls.load_amde` will only \"\n                      \"return an `ADIPLSEigenfunctions` object: use \"\n                      \"`return_object=True` to mimic future behaviour\",\n                      FutureWarning)\n        return np.squeeze(css), np.squeeze(data), x\n\ndef load_amdl(filename, return_nmod=False, live_dangerously=False,\n              return_object=True, G=G_DEFAULT):\n    \"\"\"Reads an ADIPLS model file.  See Section 5 of the `ADIPLS\n    documentation`_ for details.\n\n    If `return_object` is `True`, instead returns an\n    :py:class:`ADIPLSStellarModel` object.  This is the default\n    behaviour as of v0.0.12.  The old behaviour will be dropped\n    completely from v0.1.0.\n\n    Parameters\n    ----------\n    filename: str\n        Name of the model file, usually starting or ending with ``amdl``.\n    return_nmod: bool, optional\n        If `True`, return the ``nmod`` parameter in the file.\n    live_dangerously: bool, optional\n        If `True`, load the file even if it looks like it might be\n        too large for an AMDL file (i.e. has more than a million points).\n    G: float, optional\n        Value for the gravitational constant, in cgs units.  If not\n        given (which is the default behaviour), we use the module-wise\n        default value.\n\n    Returns\n    -------\n    D: 1-d NumPy array\n        Global data, as defined by eq. (5.2) of the ADIPLS\n        documentation.\n    A: 2-d NumPy array\n        Point-wise data, as defined by eq. (5.1) of the ADIPLS\n        documentation.\n    nmod: int, optional\n        The model number.  I'm not sure what it's used for but it\n        doesn't seem to matter.  Only returned if `return_nmod=True`.\n\n    \"\"\"\n\n    with open(filename, 'rb') as f:\n        f.read(4)\n        nmod = np.fromfile(f, dtype='i', count=1)[0]\n        nn = np.fromfile(f, dtype='i', count=1)[0]\n        if not live_dangerously and nn > 1000000:\n            raise IOError(\"Model appears to have %i points; \"\n                          \"it probably isn't an AMDL file. \"\n                          \"If you're sure that it is, try again \"\n                          \"with live_dangerously=True\" % nn)\n\n        D = np.fromfile(f, dtype='d', count=8)\n        A = np.fromfile(f, dtype='d', count=6*nn).reshape((-1,6))\n        f.read(4)\n        # check that this is the end of the file\n\n    if return_object:\n        return ADIPLSStellarModel(D, A, nmod=nmod, G=G)\n    else:\n        warnings.warn(\"From tomso 0.1.0+, `adipls.load_amdl` will only \"\n                      \"return an `ADIPLSStellarModel` object: use \"\n                      \"`return_object=True` to mimic future behaviour\",\n                      FutureWarning)\n        if return_nmod:\n            return D, A, int(nmod)\n        else:\n            return D, A\n\n\ndef load_rkr(filename, return_object=True):\n    \"\"\"Reads an ADIPLS rotational kernel file.\n\n    If `return_object` is `True`, instead returns an\n    :py:class:`ADIPLSRotationKenerls` object.  This is the default\n    behaviour as of v0.0.12.  The old behaviour will be dropped\n    completely from v0.1.0.\n\n    Parameters\n    ----------\n    filename: str\n        Name of the kernel file, usually starting or ending with\n        ``rkr``.\n\n    Returns\n    -------\n    css: structured array\n        The ``cs`` arrays for each mode.\n    rkrs: list of arrays\n        The kernel arrays for each mode.  Each array has two columns:\n        the fractional radius :math:`x` and the kernel :math:`K(x)`.\n\n    \"\"\"\n\n    if return_object:\n        return ADIPLSRotationKernels(*load_pointwise_data(filename, 2))\n    else:\n        warnings.warn(\"From tomso 0.1.0+, `adipls.load_rkr` will only \"\n                      \"return an `ADIPLSRotationKernels` object: use \"\n                      \"`return_object=True` to mimic future behaviour\",\n                      FutureWarning)\n    return load_pointwise_data(filename, 2)\n\n\ndef save_amdl(filename, D, A, nmod=0):\n    \"\"\"Writes an ADIPLS model file, given data in the same form as\n    returned by :py:meth:`load_amdl`.  See Section 5 of the `ADIPLS\n    documentation`_ for details.\n\n    Parameters\n    ----------\n    filename: str\n        Name of the model file, usually starting or ending with amdl.\n    D: 1-d NumPy array\n        Global data, as defined by eq. (5.2) of the `ADIPLS\n        documentation`_.\n    A: 2-d NumPy array\n        Point-wise data, as defined by eq. (5.1) of the `ADIPLS\n        documentation`_.\n    nmod: int, optional\n        The model number.  I'm not sure what it's used for but it\n        doesn't seem to matter.\n\n    \"\"\"\n    nn = len(A)\n    length = np.array(8*(1+8+6*nn), dtype=np.int32)\n    with open(filename, 'wb') as f:\n        length.tofile(f)\n        np.array((nmod,), dtype=np.int32).tofile(f)\n        np.array((nn,), dtype=np.int32).tofile(f)\n        D.tofile(f)\n        A.tofile(f)\n        length.tofile(f)\n\n\ndef amdl_get(key_or_keys, D, A, G=G_DEFAULT):\n    \"\"\"Retrieves physical properties of an AMDL model from the ``D`` and\n    ``A`` arrays.\n\n    Parameters\n    ----------\n    keys: list of strs\n        A desired variable or a list of desired variables.  Current\n        options are:\n\n        - ``M``: total mass (float)\n        - ``R``: photospheric radius (float)\n        - ``P_c``: central pressure (float)\n        - ``rho_c``: central density (float)\n        - ``r``: radius (array)\n        - ``x``: fractional radius (array)\n        - ``m``: mass co-ordinate (array)\n        - ``q``: fractional mass co-ordinate (array)\n        - ``g``: gravity (array)\n        - ``rho``: density (array)\n        - ``P``: pressure (array)\n        - ``AA``: Ledoux discriminant (array)\n        - ``Hp``: pressure scale height (array)\n        - ``G1``: first adiabatic index (array)\n        - ``cs2``: sound speed squared (array)\n        - ``cs``: sound speed (array)\n        - ``tau``: acoustic depth\n\n        For example, if ``D`` and ``A`` have been returned from\n        :py:meth:`load_amdl`, you could use\n\n        >>> M, m = adipls.amdl_get(['M', 'm'], D, A)\n\n        to get the total mass and mass co-ordinate.  If you only want\n        one variable, you don't need to use a list.  The return type\n        is just the one corresponding float or array.  So, to get a\n        single variable you could use either\n\n        >>> x, = adipls.amdl_get(['x'], D, A)\n\n        or\n\n        >>> x = adipls.amdl_get('x', D, A)\n\n    D: 1-d array\n        Global data, as defined by eq. (5.2) of the `ADIPLS\n        documentation`_ and returned by :py:meth:`load_amdl`.\n    A: 2-d array\n        Point-wise data, as defined by eq. (5.1) of the `ADIPLS\n        documentation`_ and returned by :py:meth:`load_amdl`.\n\n    Returns\n    -------\n    output: list of floats and arrays\n        A list returning the floats or arrays in the order requested\n        by the parameter ``keys``.\n\n    \"\"\"\n    M, R, P_c, rho_c = D[:4]\n    x = A[:,0]                                      # fractional radius\n    q = A[:,1]*x**3                                 # fractional mass\n    m = q*M                                         # mass\n    r = x*R                                         # radius\n    G1 = A[:,3]                                     # first adiabatic index\n    AA = A[:,4]                                     # Ledoux disciminant\n\n    # we can safely ignore 0/0s here\n    with np.errstate(invalid='ignore'):\n        g = G*m/r**2\n        rho = A[:,5]*m/r**3/4./np.pi                # density\n        rho[x==0] = rho_c\n        P = G*m*rho/G1/r/A[:,2]                     # pressure\n        P[x==0] = P_c\n\n    Hp = P/(rho*g)                                  # pressure scale height\n    cs2 = G1*P/rho                                  # sound speed squared\n    cs = np.sqrt(cs2)                               # sound speed\n    tau = -integrate(1./cs[::-1], r[::-1])[::-1]    # acoustic depth\n\n    if type(key_or_keys) == str:\n        keys = [key_or_keys]\n        just_one = True\n    else:\n        keys = key_or_keys\n        just_one = False\n\n    output = []\n    for key in keys:\n        if key == 'M': output.append(M)\n        elif key == 'R': output.append(R)\n        elif key == 'P_c': output.append(P_c)\n        elif key == 'rho_c': output.append(rho_c)\n        elif key == 'r': output.append(r)\n        elif key == 'x': output.append(x)\n        elif key == 'm': output.append(m)\n        elif key == 'q': output.append(q)\n        elif key == 'g': output.append(g)\n        elif key == 'rho': output.append(rho)\n        elif key == 'P': output.append(P)\n        elif key == 'AA': output.append(AA)\n        elif key == 'Hp': output.append(Hp)\n        elif key == 'G1': output.append(G1)\n        elif key == 'cs2': output.append(cs2)\n        elif key == 'cs': output.append(cs)\n        elif key == 'tau': output.append(tau)\n        else: raise ValueError('%s is not a valid key for adipls.amdl_get' % key)\n\n    if just_one:\n        assert(len(output) == 1)\n        return output[0]\n    else:\n        return output\n\n\ndef kernels(cs, eig, D, A, G=G_DEFAULT, alpha=None):\n    \"\"\"Returns the density and squared sound speed kernels.  I have tried\n    to make this as notationally similar to Gough & Thompson (1991) as\n    possible.  The kernels are normalized to have unit integrals over\n    the radius *r*.\n\n    Parameters\n    ----------\n    cs: structured array\n        The ``cs`` array for the mode.\n    eig: np.array, shape(N,7)\n        Eigenfunction data for the mode, as returned by\n        :py:meth:`load_amde`.\n    D: 1-d array\n        Global data, as defined by eq. (5.2) of the `ADIPLS\n        documentation`_ and returned by :py:meth:`load_amdl`.\n    A: 2-d array\n        Point-wise data, as defined by eq. (5.1) of the `ADIPLS\n        documentation`_ and returned by :py:meth:`load_amdl`.\n    G: float, optional\n        Value for the gravitational constant, in cgs units.  If not\n        given (which is the default behaviour), we use the module-wise\n        default value.\n    alpha: float, optional\n        Coefficient of the complementary function.  If ``None``, computed\n        as in Michael Thompson's kernel code.\n\n    Returns\n    -------\n    K_cs2: np.array, length N\n        The sound speed squared structure kernel.\n    K_rho: np.array, length N\n        The density structure kernel.\n\n    \"\"\"\n\n    l = cs['l']\n    M, R, P_c, rho_c = D[:4]                # mass and radius from FGONG\n    y = eig.T\n    sigma2 = cs['sigma2']\n    omega = np.sqrt(sigma2*G*M/R**3)        # convert to angular frequency\n    L2 = l*(l+1)\n\n    x = A[:,0]\n    r = x*R                                 # radial co-ordinate\n    m = A[:,1]*x**3*M                       # mass co-ordinate\n    g = G*m/r**2                            # gravity\n    g[x==0] = 0.\n    rho = A[:,1]*A[:,5]*M/4./np.pi/R**3     # density\n    rho[x==0] = rho_c\n    G1 = A[:,3]                             # first adiabatic index\n    P = G*m*rho/G1/r/A[:,2]                 # pressure\n    P[x==0] = P_c\n    cs2 = G1*P/rho                          # square of the sound speed\n    A1 = A[:,1]\n    A2 = A[:,2]\n    Vg = A2[:]\n    drho_dr = -(A[:,4]+A[:,2])*rho/r        # density gradient\n    drho_dr[x==0] = 0.\n\n    xi_r = y[1]*R\n\n    if l == 0:\n        xi_h = 0.*xi_r  # radial modes have zero horizontal component\n        chi = Vg/x*(y[1]-sigma2/A1/x*y[2])\n        dxi_r_dr = chi - 2.*y[1]/x\n        dPhi_dr = -4.*np.pi*G*rho*xi_r\n        Phi = -complement(dPhi_dr, r)  # but actually you don't even need it\n    elif l > 0:\n        xi_h = y[2]*R/L2\n        eta = L2*A1/sigma2\n        chi = Vg/x*(y[1]-y[2]/eta-y[3])\n        dxi_r_dr = chi - 2.*y[1]/x + y[2]/x\n        dPhi_dr = -g/x*(y[3] + y[4]) - y[3]*R*(4.*np.pi*G*rho - 2.*g/r)\n        Phi = -g*R*y[3]\n    else:\n        raise ValueError('l must be non-negative')\n\n    chi[x==0] = 0.\n    dxi_r_dr[x==0] = 0.\n    dPhi_dr[x==0] = 0.\n    Phi_r = Phi/r\n    Phi_r[x==0] = 0.\n\n    S = np.trapz((xi_r**2 + L2*xi_h**2)*rho*r**2, r)\n\n    K_cs2 = rho*cs2*chi**2*r**2  # c.f. equation (60)\n    K_cs2 = K_cs2/S/omega**2/2.\n\n    # following InversionKit (103)\n    K_rho = cs2*chi**2 - omega**2*(xi_r**2+L2*xi_h**2) \\\n        - 2.*g*xi_r*(chi - dxi_r_dr) \\\n        + 4.*np.pi*G*rho*xi_r**2 \\\n        - 4.*np.pi*G*complement((2.*rho*chi+xi_r*drho_dr)*xi_r, r) \\\n        + 2.*(xi_r*dPhi_dr + L2*xi_h*Phi_r)\n    K_rho = K_rho*rho*r**2/2./S/omega**2\n\n    comp = rho*r**2\n    if alpha is None:\n        alpha = np.trapz(K_rho*comp, r)/np.trapz(comp*comp, r)\n\n    K_rho = K_rho - alpha*comp\n\n    return K_cs2, K_rho\n\n\ndef fgong_to_amdl(glob, var, G=G_DEFAULT):\n    \"\"\"Converts FGONG data (in the form of `glob` and `var`, as returned\n    by :py:meth:`~tomso.fgong.load_fgong`) into ADIPLS binary data,\n    which can be saved using :py:meth:`save_amdl`.\n\n    The output should be identical (to within a few times machine\n    error) to the output of ``fgong-amdl.d`` tool distributed with\n    ADIPLS.\n\n    Parameters\n    ----------\n    glob: NumPy array\n        The scalar (or global) variables for the stellar model\n    var: NumPy array\n        The point-wise variables for the stellar model. i.e. things\n        that vary through the star like temperature, density, etc.\n    G: float, optional\n        Value for the gravitational constant, in cgs units.  If not\n        given (which is the default behaviour), we use the module-wise\n        default value.\n\n    Returns\n    -------\n    D: 1-d array\n        Global data, as defined by eq. (5.2) of the `ADIPLS\n        documentation`_.\n    A: 2-d array\n        Point-wise data, as defined by eq. (5.1) of the `ADIPLS\n        documentation`_.\n\n    \"\"\"\n    warnings.warn(\"From tomso 0.1.0+, FGONG must be converted to \"\n                  \"AMDL by loading an `FGONG` object and using its \"\n                  \"`to_amdl` function.  To mimic the future behaviour, \"\n                  \"load an FGONG object by using `fgong.load_fgong` \"\n                  \"with `return_object=True`.\",\n                  FutureWarning)\n\n    M, R = glob[:2]\n    r, P, rho, G1, AA = var[::-1,[0,3,4,9,14]].T\n    m = np.exp(var[::-1,1])*M\n\n    ioff = (0 if r[0] < 1e6 else 1)\n    nn = len(var) + ioff\n\n    # convert profile\n    A = np.zeros((nn, 6))\n\n    # we can safely ignore division by 0 here\n    with np.errstate(divide='ignore', invalid='ignore'):\n        A[ioff:,0] = r/R\n        A[ioff:,1] = m/M/(r/R)**3\n        A[ioff:,2] = G*m*rho/(G1*P*r)\n        A[ioff:,3] = G1\n        A[ioff:,4] = AA\n        A[ioff:,5] = 4.*np.pi*rho*r**3/m\n\n    A[0,0] = 0.\n    A[0,1] = 4.*np.pi/3.*rho[0]*R**3/M\n    A[0,2] = 0.\n    A[0,3] = G1[0]\n    A[0,4] = 0.\n    A[0,5] = 3.\n\n    # convert header\n    D = np.zeros(8)\n    D[0] = M\n    D[1] = R\n    D[2] = P[0]\n    D[3] = rho[0]\n\n    # second derivatives at centre are given\n    if glob[10] < 0.:\n        D[4] = -glob[10]/G1[0]\n        D[5] = -glob[11]\n    else:\n        D[4] = 4.*np.pi/3.*G*(rho[0]*R)**2/(P[0]*G1[0])\n        # D[5] = np.nanmax((A[1:,4]/A[1:,0]**2)[A[1:,0]<0.05])\n        # D[5] = np.max((D[5], 0.))+D[4]\n        D[5] = D[4]\n\n    D[6] = -1.\n    D[7] = 0.\n\n    if A[-1,4] <= 10.:\n        # chop off outermost point\n        A = A[:-1]\n        nn -= 1\n\n    return D, A\n\n\ndef amdl_to_fgong(D, A, G=G_DEFAULT):\n    \"\"\"Converts ADIPLS binary data (in the form of `D` and `A`, as\n    returned by :py:meth:`load_amdl`) into FGONG data,\n    which can be saved using :py:meth:`~tomso.fgong.save_fgong`.\n\n    Designed to be the inverse of the ``fgong-amdl.d`` tool\n    distributed with ADIPLS, modulo the fact that various thermal\n    variables (e.g. temperature and luminosity) are not stored in the\n    AMDL format, and that the innermost point may have been truncated.\n    It's impossible to tell when reversing the process, so we assume\n    not.\n\n    The output should be identical (to within a few times machine\n    error) of going from FGONG to AMDL and back again.\n\n    Parameters\n    ----------\n    D: 1-d array\n        Global data, as defined by eq. (5.2) of the `ADIPLS\n        documentation`_.\n    A: 2-d array\n        Point-wise data, as defined by eq. (5.1) of the `ADIPLS\n        documentation`_.\n    G: float, optional\n        Value for the gravitational constant, in cgs units.  If not\n        given (which is the default behaviour), we use the module-wise\n        default value.\n\n    Returns\n    -------\n    glob: NumPy array\n        The scalar (or global) variables for the stellar model\n    var: NumPy array\n        The point-wise variables for the stellar model. i.e. things\n        that vary through the star like temperature, density, etc.\n\n    \"\"\"\n    warnings.warn(\"From tomso 0.1.0+, AMDL should be converted to \"\n                  \"FGONG by loading an `ADIPLSStellarModel` object \"\n                  \"and using its `to_fgong` function.  To mimic the \"\n                  \"future behaviour, load an FGONG object by using \"\n                  \"`adipls.load_amdl` with `return_object=True`.\",\n                  FutureWarning)\n    M, R = D[:2]\n\n    glob = np.zeros(15)\n    var = np.zeros((len(A), 40))\n\n    r = A[:,0]*R\n    q = A[:,1]*A[:,0]**3\n    m = q*M\n    G1 = A[:,3]\n    AA = A[:,4]\n\n    # we can safely ignore division by 0 here\n    with np.errstate(divide='ignore', invalid='ignore'):\n        lnq = np.log(q)\n        rho = A[:,5]*m/(4.*np.pi*r**3)\n        P = G*m*rho/(G1*r*A[:,2])\n\n    P[0] = D[2]\n    rho[0] = D[3]\n\n    var[::-1,0] = r\n    var[::-1,1] = lnq\n    var[::-1,3] = P\n    var[::-1,4] = rho\n    var[::-1,9] = G1\n    var[::-1,14] = AA\n\n    glob[0] = M\n    glob[1] = R\n    glob[10] = -D[4]*G1[0]\n    glob[11] = -D[5]\n\n    return glob, var\n\n\ncs_dtypes = [('xmod','float'), ('M','float'), ('R','float'),\n             ('P_c','float'), ('rho_c','float'), ('D_5','float'),\n             ('D_6','float'), ('D_7','float'), ('D_8','float'),\n             ('A_2(x_s)','float'), ('A_5(x_s)','float'),\n             ('x_1','float'), ('sigma2_Omega','float'),\n             ('x_f','float'), ('fctsbc','int'), ('fcttbc','int'),\n             ('lambda','float'), ('l','int'), ('n','int'),\n             ('sigma2','float'), ('sigma2_c','float'),\n             ('y_1,max','float'), ('x_max', 'float'), ('E','float'),\n             ('Pi_E','float'), ('Pi_V','float'), ('nu_V','float'),\n             ('ddsig','float'), ('ddsol','float'),\n             ('y_1(x_s)','float'), ('y_2(x_s)','float'),\n             ('y_3(x_s)','float'), ('y_4(x_s)','float'),\n             ('z_1,max','float'), ('xhat_max','float'),\n             ('beta_nl','float'), ('nu_Ri','float'), ('m','int')]\n\nfor i in range(len(cs_dtypes), 50):\n    cs_dtypes.append(('col%i' % i, 'float'))\n\ncs_floats = [(k, 'float') for (k,v) in cs_dtypes]\n\n\nclass ADIPLSStellarModel(AdiabaticStellarModel):\n    \"\"\"A class that contains and allows one to manipulate the data in a\n    stellar model stored in ADIPLS's internal binary model format.\n    See Section 5 of the `ADIPLS documentation`_ for details.\n\n    This will usually be provided from a file by using\n    :py:meth:`load_amdl` but an object can be constructed from any\n    similarly structured arrays.\n\n    The main attributes are the **D** and **A** arrays, which follow\n    the definitions in the ADIPLS documentation.  The data in these\n    arrays can be accessed via the attributes with more\n    physically-meaningful names (e.g. the radius is\n    ``ADIPLSStellarModel.r``).\n\n    Some of these values can also be set via the attributes if doing\n    so is unambiguous. For example, the fractional radius **x** is not a\n    member of the **var** array but setting **x** will assign the actual\n    radius **r**, which is the first column of **var**.  Values that are\n    settable are indicated in the list of parameters.\n\n    Parameters\n    ----------\n    D: 1-d array\n        Global data, as defined by eq. (5.2) of the ADIPLS\n        documentation.\n    A: 2-d array\n        Point-wise data, as defined by eq. (5.1) of the ADIPLS\n        documentation.\n    nmod: int, optional\n        The model number.  I'm not sure what it's used for but it\n        doesn't seem to matter.\n    G: float, optional\n        Value for the gravitational constant, in cgs units.  If not\n        given (which is the default behaviour), we use the module-wise\n        default value.\n\n    Attributes\n    ----------\n    nn: int\n        number of points in stellar model (i.e. number of rows in **A**)\n    M: float, settable\n        total mass\n    R: float, settable\n        photospheric radius\n    P_c: float, settable\n        central pressure\n    rho_c: float, settable\n        central density\n    x: NumPy array, settable\n        fractional radius co-ordinate\n    q: NumPy array, settable\n        fractional mass co-ordinate\n    lnq: NumPy array, settable\n        natural logarithm of the fractional mass co-ordinate\n    Vg: NumPy array\n        homology invariant *V/Gamma_1*\n    Gamma_1: NumPy array, settable\n        first adiabatic index, aliased by **G1**\n    G1: NumPy array, settable\n        first adiabatic index, alias of **Gamma_1**\n    AA: NumPy array, settable\n        Ledoux discriminant\n    U: NumPy array\n        homology invariant *dlnm/dlnr*\n    V: NumPy array\n        homology invariant *dlnP/dlnr*\n    r: NumPy array, settable\n        radius co-ordinate\n    m: NumPy array, settable\n        mass co-ordinate\n    P: NumPy array\n        pressure\n    rho: NumPy array\n        density\n    g: NumPy array\n        local gravitational acceleration\n    Hp: NumPy array\n        pressure scale height\n    Hrho: NumPy array\n        density scale height\n    N2: NumPy array\n        squared Brunt–Väisälä (angular) frequency\n    cs2: NumPy array\n        squared adiabatic sound speed\n    cs: NumPy array\n        adiabatic sound speed\n    tau: NumPy array\n        acoustic depth\n    \"\"\"\n    def __init__(self, D, A, nmod=0, G=G_DEFAULT):\n        self.D = D\n        self.A = A\n        self.nmod = nmod\n        self.G = G\n\n    def __len__(self):\n        return len(self.A)\n\n    def __repr__(self):\n        with np.printoptions(threshold=10):\n            return('ADIPLSStellarModel(\\nD=\\n%s,\\nA=\\n%s,\\nG=%.15g,\\nnmod=%s\\n)' % (self.D, self.A, self.G, self.nmod))\n\n    def to_file(self, filename):\n        \"\"\"Save the model to an ADIPLS binary stellar model file (usually\n        either starting or ending with `amdl`).\n\n        Parameters\n        ----------\n        filename: str\n            Filename to which the data is written.\n        \"\"\"\n        save_amdl(filename, self.D, self.A, nmod=self.nmod)\n\n    def to_fgong(self, reverse=True, ivers=1300):\n        \"\"\"Convert the model to an :py:class:`~tomso.fgong.FGONG` object.\n\n        Note that the ADIPLS binary format only has the data necessary\n        to compute adiabiatic stellar oscillations, so the FGONG will\n        be missing some data (e.g. temperature, luminosity).\n\n        Parameters\n        ----------\n        reverse: bool, optional\n            If ``True`` (the default), store the FGONG data ordered\n            from the surface to the centre.  Otherwise, store the\n            FGONG data ordered from the centre to the surface.\n        \"\"\"\n        from .fgong import FGONG\n\n        # `amdl_to_fgong` already reverses the data by default\n        if reverse:\n            return FGONG(*amdl_to_fgong(self.D, self.A, G=self.G),\n                         ivers=ivers)\n        else:\n            return FGONG(*amdl_to_fgong(self.D, self.A[::-1], G=self.G),\n                         ivers=ivers)\n\n    def to_gyre(self, version=None):\n        \"\"\"Convert the model to an :py:class:`~tomso.gyre.GYREStellarModel`\n        object.\n\n        Note that the ADIPLS binary format only has the data necessary\n        to compute adiabiatic stellar oscillations, so the GYRE\n        stellar model will be missing some data (e.g. temperature,\n        luminosity).\n\n        Parameters\n        ----------\n        version: int, optional\n            Specify GYRE format version number times 100. i.e.,\n            ``version=101`` produce a file with data version 1.01.  If\n            ``None`` (the default), the latest version available in\n            TOMSO is used.\n        \"\"\"\n        from .gyre import gyre_header_dtypes, gyre_data_dtypes, GYREStellarModel\n\n        if version is None:\n            version = max([k for k in gyre_header_dtypes.keys()])\n\n        header = np.zeros(1, gyre_header_dtypes[version])\n        header['M'] = self.D[0]\n        header['R'] = self.D[1]\n        header['L'] = 42.0\n        header['version'] = version\n\n        data = np.ones(self.nn, gyre_data_dtypes[version])\n        g = GYREStellarModel(header[0], data, G=self.G)\n\n        g.r = self.r\n        g.m = self.m\n        g.P = self.P\n        g.rho = self.rho\n        g.Gamma_1 = self.Gamma_1\n        g.N2 = self.N2\n\n        # GYRE doesn't know if it's doing adiabatic or non-adiabatic\n        # modes when it reads the file, so it does some calculations\n        # expecting meaningful data.  We fudge this so we don't get\n        # FPEs.\n        g.kappa = 42.0\n        g.L_r = 42.0\n        if version < 101:\n            g.data['eps_tot'] = 42.0\n        else:\n            g.data['eps'] = 42.0\n\n        g.data['k'] = np.arange(self.nn) + 1\n        return g\n\n\n    # AMDL parameters that can be derived from data\n    @property\n    def nn(self): return len(self.A)\n\n    # Various properties for easier access to the data in `glob` and\n    # `var`.\n\n    @property\n    def M(self): return self.D[0]\n\n    @M.setter\n    def M(self, val): self.D[0] = val\n\n    @property\n    def R(self): return self.D[1]\n\n    @R.setter\n    def R(self, val): self.D[1] = val\n\n    @property\n    def P_c(self): return self.D[2]\n\n    @P_c.setter\n    def P_c(self, val): self.D[2] = val\n\n    @property\n    def rho_c(self): return self.D[3]\n\n    @rho_c.setter\n    def rho_c(self, val): self.D[3] = val\n\n    @property\n    def x(self): return self.A[:,0]\n\n    @x.setter\n    def x(self, val): self.A[:,0] = val\n\n    @property\n    def q(self): return self.A[:,1]*self.x**3\n\n    @q.setter\n    def q(self, val): self.A[:,1] = val/self.x**3\n\n    @property\n    def Vg(self): return self.A[:,2]\n\n    @Vg.setter\n    def Vg(self, val): self.A[:,2] = val\n\n    @property\n    def Gamma_1(self): return self.A[:,3]\n\n    @Gamma_1.setter\n    def Gamma_1(self, val): self.A[:,3] = val\n\n    @property\n    def G1(self): return self.A[:,3]\n\n    @G1.setter\n    def G1(self, val): self.A[:,3] = val\n\n    @property\n    def AA(self): return self.A[:,4]\n\n    @AA.setter\n    def AA(self, val): self.A[:,4] = val\n\n    @property\n    def U(self): return self.A[:,5]\n\n    @U.setter\n    def U(self, val): self.A[:,5] = val\n\n    @property\n    def V(self): return self.Vg*self.Gamma_1\n\n    @V.setter\n    def V(self, val): self.Vg = val/self.Gamma_1\n\n    @property\n    def r(self): return self.x*self.R\n\n    @r.setter\n    def r(self, val): self.x = val/self.R\n\n    @property\n    def m(self): return self.q*self.M\n\n    @m.setter\n    def m(self, val): self.q = val/self.M\n\n    @property\n    @regularize(y0=-np.inf, x0=1e-308)\n    def lnq(self): return np.log(self.q)\n\n    @lnq.setter\n    def lnq(self, val): self.q = np.exp(val)\n\n    @property\n    def P(self):\n        with np.errstate(invalid='ignore'):\n            val = self.G*self.m*self.rho/(self.Gamma_1*self.r*self.A[:,2])\n\n        val[self.x==0] = self.P_c\n        return val\n\n    @property\n    def rho(self):\n        with np.errstate(invalid='ignore'):\n            val = self.A[:,5]*self.m/self.r**3/4./np.pi\n\n        val[self.x==0] = self.rho_c\n        return val\n\n    @property\n    @regularize()\n    def N2(self): return self.AA*self.g/self.r\n\n    @property\n    def tau(self):\n        tau = integrate(1./self.cs[::-1], self.r[::-1])[::-1]\n        return np.max(tau)-tau\n\n\nclass ADIPLSGrandSummary(object):\n    \"\"\"A class that represents the information for a set of mode\n    frequencies, loaded from an ADIPLS grand summary file (often\n    starting or ending with ``agsm``).  The main data is stored in the\n    ``css`` attribute, which is a structured array.  This will usually\n    be provided from a file by using :py:meth:`load_agsm` but an object can be\n    constructed from any similarly structured array.\n\n    A subset of the information in the ``css`` array is made available\n    through attributes.\n\n    Parameters\n    ----------\n    css: structured NumPy array\n        The ``cs`` arrays for each mode.\n\n    Attributes\n    ----------\n    G: float\n        gravitational constant\n    M: float\n        total mass\n    R: float\n        photospheric radius\n    l: NumPy array of ints\n        angular degrees\n    n: NumPy array of ints\n        angular degrees\n    sigma2: NumPy array of floats\n        square of the dimensionless angular eigenfrequency\n    sigma2_c: NumPy array of floats\n        square of the dimensionless angular eigenfrequency corrected\n        for the Cowling approximation\n    Pi_E: NumPy array of floats\n        eigenperiod, in seconds\n    Pi_V: NumPy array of floats\n        variational period, in seconds\n    nu_Ri: NumPy array of floats\n        cyclic eigenfrequency corrected using Richardson\n        extrapolation, in Hz\n    nu_V: NumPy array of floats\n        variational cyclic frequency, in Hz\n    nu_E: NumPy array of floats\n        cyclic eigenfrequency, in seconds\n    nu_c: NumPy array of floats\n        cyclic eigenfrequency corrected for the Cowling approximation,\n        in Hz\n    nu: NumPy array of floats\n        alias of ``nu_c``\n    E: NumPy array of floats\n        Normalised mode inertia (see eq. (4.3) of ADIPLS notes).  Note\n        that ADIPLS's definition is smaller than GYRE's by a factor of\n        4π.\n    beta: NumPy array of floats\n        Weight for rotation kernel (see eq. (4.7) of ADIPLS notes or\n        (8.43) of JCD's oscillation notes).\n\n    \"\"\"\n    def __init__(self, css):\n        self.css = css\n\n    def __len__(self):\n        return len(self.css)\n\n    def __str__(self):\n        return '\\n'.join([\n            '%s' % type(self),\n            'G    %11.6g cm³/g/s²' % self.G,\n            'M    %9.3e g    %7.3f Msun' % (self.M, self.M/1.98841e33),\n            'R    %9.3e cm   %7.3f Rsun' % (self.R, self.R/695.7e8)])\n\n    def __repr__(self):\n        with np.printoptions(threshold=10):\n            return('ADIPLSGrandSummary(\\ncss=\\n%s)' % self.css)\n\n    @property\n    def G(self): return self.R**3/self.M/self.sigma2[0]*(2.*np.pi/self.Pi_E[0])**2\n\n    @property\n    def M(self): return self.css[0]['M']\n\n    @property\n    def R(self): return self.css[0]['R']\n\n    @property\n    def l(self): return self.css['l']\n\n    @property\n    def n(self): return self.css['n']\n\n    @property\n    def sigma2(self): return self.css['sigma2']\n\n    @property\n    def sigma2_c(self): return self.css['sigma2_c']\n\n    @property\n    def Pi_E(self): return self.css['Pi_E']*60.0\n\n    @property\n    def Pi_V(self): return self.css['Pi_V']*60.0\n\n    @property\n    def nu_Ri(self): return self.css['nu_Ri']/1e3\n\n    @property\n    def nu_V(self): return self.css['nu_V']/1e3\n\n    @property\n    def nu_E(self): return 1/self.Pi_E\n\n    @property\n    def nu_c(self): return np.sqrt(self.sigma2_c/self.sigma2)/self.Pi_E\n\n    @property\n    def nu(self): return self.nu_c\n\n    @property\n    def E(self): return self.css['E']\n\n    @property\n    def beta(self): return self.css['beta_nl']\n\n    def index_ln(self, l, n):\n        \"\"\"Returns the index of mode with angular degree *l*\n        and radial order *n*.\"\"\"\n        return np.where((self.l==l)&(self.n==n))[0][0]\n\n    def index_nl(self, n, l):\n        \"\"\"Returns the index of mode with radial order *n*\n        and angular degree *l*.\"\"\"\n        return self.index_ln(l, n)\n\n\nclass ADIPLSEigenfunctions(ADIPLSGrandSummary):\n    \"\"\"A class that represents the information for a set of eigenfunction\n    data kernels produced by ADIPLS.  This will usually be provided\n    from a file by using :py:meth:`load_amde` but an object can be\n    constructed from any similarly structured array.\n\n    Parameters\n    ----------\n    css: structured NumPy array\n        The ``cs`` arrays for each mode.\n    eigs: 3-d NumPy array\n        The eigenfunction arrays for each mode.  The nth element of\n        the array has the eigenfunction data for the nth mode, in\n        the same order as the summary data in *css*.  The number of\n        rows in the array for a given mode is the number of meshpoints\n        in the model.  The number of columns is either 6 or 2,\n        depending on **nfmode**.\n    nfmode: int\n        The output mode used by ADIPLS' when the data was stored.\n    x: NumPy array, optional\n        If **nfmode** is 2 or 3, the fractional radius must be\n        provided separately.  If **nfmode** is 1, it will be inferred\n        from the eigenfunction data if not explicitly provided.\n\n\n    This class has all the attributes of\n    :py:class:`ADIPLSGrandSummary` as well as the following extras.\n\n    Attributes\n    ----------\n    x: NumPy array\n        fractional radius co-ordinate\n    eigs: list of NumPy arrays\n        The nth row is the eigenfunction data for the nth mode, in\n        the same order as the summary data in *css*.\n\n    \"\"\"\n    # TODO: add some derived properties: xi_r, xi_h\n    # TODO: add access to eigenfunctions by n and l, like rotation kernels\n    def __init__(self, css, eigs, nfmode=1, x=None):\n        ADIPLSGrandSummary.__init__(self, css)\n\n        self.nfmode = nfmode\n        if nfmode == 1:\n            if x is None:\n                self.x = eigs[0,:,0]\n            else:\n                self.x = x\n        elif nfmode == 2 or nfmode == 3:\n            self.x = x\n        else:\n            raise ValueError('nfmode must be 1, 2 or 3, not %i' % nfmode)\n\n        self.eigs = eigs\n\n    def __str__(self):\n        return super(ADIPLSEigenfunctions, self).__str__()\n\n    def __repr__(self):\n        with np.printoptions(threshold=10):\n            return('ADIPLSEigenfunctions(nfmode=%i,\\ncss=\\n%s,\\neigs=\\n%s)' % (self.nfmode, self.css, self.eigs))\n\n    def eig_ln(self, l, n):\n        \"Load eigenfunction by *l* and *n*.\"\n        return self.eigs[(self.l==l)&(self.n==n)][0]\n\n    def eig_nl(self, n, l):\n        \"Load eigenfunction by *n* and *l*.\"\n        return self.eig_ln(l, n)\n\n\nclass ADIPLSRotationKernels(ADIPLSGrandSummary):\n    \"\"\"A class that represents the information for a set of rotational\n    kernels produced by ADIPLS.  This will usually be provided from a\n    file by using :py:meth:`load_rkr` but an object can be constructed\n    from any similarly structured array.\n\n    Parameters\n    ----------\n    css: structured NumPy array\n        The ``cs`` arrays for each mode.\n    rkrs: list of arrays\n        The kernel arrays for each mode.  Each array has two columns:\n        the fractional radius :math:`x` and the kernel :math:`K(x)`.\n\n\n    This class has all the attributes of\n    :py:class:`ADIPLSGrandSummary` as well as the following extras.\n\n    Attributes\n    ----------\n    x: NumPy array\n        fractional radius co-ordinate\n    K: list of NumPy arrays\n        The nth row is the rotation kernel for the nth mode, in\n        the same order as the summary data in *css*.  The mode with\n        radial order *n* and angular degree *l* can be accessed by the\n        functions ``K_ln(l,n)`` or ``K_nl(n,l)``.\n\n    \"\"\"\n    def __init__(self, css, rkr):\n        ADIPLSGrandSummary.__init__(self, css)\n        self.x = rkr[0,:,0]\n        self.K = rkr[:,:,1]\n\n    def __str__(self):\n        return super(ADIPLSRotationKernels, self).__str__()\n\n    def __repr__(self):\n        with np.printoptions(threshold=10):\n            return('ADIPLSRotationKernels(\\ncss=\\n%s,\\nx=%s,\\nK=\\n%s)' % (self.css, self.x, self.K))\n\n    def K_ln(self, l, n):\n        \"Load kernel by *l* and *n*.\"\n        return self.K[(self.l==l)&(self.n==n)][0]\n\n    def K_nl(self, n, l):\n        \"Load kernel by *n* and *l*.\"\n        return self.K_ln(l, n)\n", "meta": {"hexsha": "b4f9387e9e0b7de43a41c939eb1da2b6186865e1", "size": 40886, "ext": "py", "lang": "Python", "max_stars_repo_path": "tomso/adipls.py", "max_stars_repo_name": "warrickball/tomso", "max_stars_repo_head_hexsha": "842c4287a827c252ef0b25f443370ab71900c77a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-09-26T10:32:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T09:59:55.000Z", "max_issues_repo_path": "tomso/adipls.py", "max_issues_repo_name": "warrickball/tomso", "max_issues_repo_head_hexsha": "842c4287a827c252ef0b25f443370ab71900c77a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-09-26T11:32:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-11T13:13:37.000Z", "max_forks_repo_path": "tomso/adipls.py", "max_forks_repo_name": "warrickball/tomso", "max_forks_repo_head_hexsha": "842c4287a827c252ef0b25f443370ab71900c77a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-12-11T14:32:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T06:03:01.000Z", "avg_line_length": 31.9172521468, "max_line_length": 120, "alphanum_fraction": 0.5747688695, "include": true, "reason": "import numpy", "num_tokens": 11692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.1852953048916083}}
{"text": "#!/usr/bin/env python\n\n# Modified by Jakob Gelszinnis\n\n\"\"\"\n\n What is the standard of this data format anyhow. If we have a load function, do we also have save function other than .pickle \n ... the issue of pickling is that it leads to very strong coupling.\n\n\"\"\"\n\n\n\nfrom __future__ import division,print_function\n\nimport os\nimport errno\nimport struct\nimport sys\nimport numpy as np\nimport clusterbuster.constants as cgsconst\n\nconst = cgsconst.ConstantsCGS()\n\ndef get_identi (f, end, verbose = False ) :\n   bytes  = f.read( 4 )\n   if len(bytes) != 4 :\n      if verbose: print(' get_identi: no further valid identifier found')\n      return None\n   identy = ''.join( struct.unpack( end+'4c', bytes ) ) \n   return identy \n   \n   \ndef Loadsnap(strSn, transform=True, headerc='Mpc'):\n  \n  #====  Hoeft_radio/q_mach_machr_table.txt for spectral index \n    snap = Snapshot(strSn, transform=transform, headerc=headerc)  #, radio_name = strRa\n    snap.loaddata()\n    snap.head['gamma'] = 5./3.  # add adiabatic expansion factor\n\n    #==== psiFile   for psi factor; machfile for mach-numbers conversion factors\n    return snap\n\ndef savesnap(strSn, savefolder, transform=True, headerc='Mpc'):\n  \n    snap = Snapshot(strSn, transform=transform, headerc=headerc)  #, radio_name = strRa\n    snap.savedata(savefolder) \n\n\ndef load_snap(snap, verbose=False):\n    \n   if verbose:\n     print(' load snapshot <%s> :' % snap.name)\n   \n   try :\n      f = open( snap.name, 'rb' )\n   except IOError:\n      print('Fatal Error: apparently %s does not exist' % (snap.name))\n      print('... I better stop now !!!')\n      sys.exit()\n      \n   end = '<' # args.endian\n      \n   # check FileInit\n   FileInit = struct.unpack( end+'II',  f.read( 2*4 ) )\n   if FileInit != (1,2) :\n      print('Fatal Error: FileInit != (1,2)')\n      print('(possibly something wrong with endian)')\n      print('... I better stop now !!!')\n      sys.exit()\n      \n   # read header\n   NumPart, Mvir, Rvir, Xc, Yc, Zc, aexpan, hubble = struct.unpack( end+'lfffffff', f.read( 8*4 ) )\n   \"\"\"DEVELOPMENT, allows to use data that were already transformed\"\"\"\n   if snap.headerc == 'Mpc':\n       Xc *= 1e3   #  Mpc -> kpc\n       Yc *= 1e3   #  Mpc -> kpc\n       Zc *= 1e3   #  Mpc -> kpc\n\n   elif snap.headerc != 'kpc':\n       print('Snapshot header of central coordinates: UNIT \"%s\" unkown!' % (snap.headerc))\n       \n   if verbose:\n      print('   NumPart = %6i'         % NumPart )\n      print('   Mvir    = %.3e Msun/h' % Mvir    )\n      print('   Rvir    = %.3e kpc/h'  % Rvir    )\n      print('   Xc      = %.3e kpc/h'  % Xc      )\n      print('   Yc      = %.3e kpc/h'  % Yc      )\n      print('   Zc      = %.3e kpc/h'  % Zc      )\n      print('   axpan   = %.3f    '    % aexpan  )\n      print('   hubble  = %.3f    '    % hubble  )\n   f.read( 512 - 10*4 )\n   \n   snap.head = { 'hubble':hubble, 'aexpan':aexpan, 'Xc':Xc, 'Yc':Yc, 'Zc':Zc, 'NumPart':NumPart, 'Mvir':Mvir, 'Rvir':Rvir }\n   \n   while True:\n   \n      identi = get_identi ( f, end )\n      if identi == None :\n         break\n      \n      if verbose: print(' following identifer found: <%s>' % identi)\n   \n#      print('_',identi)\n      if identi == 'POS ':\n         snap.pos  =  np.fromfile(f, dtype=end+'f', count=3*NumPart ).reshape( (NumPart, 3 ) )\n         if snap.transform:\n             snap.pos[:,0] -= Xc\n             snap.pos[:,1] -= Yc\n             snap.pos[:,2] -= Zc \n      elif identi == 'VEL ' :\n         snap.vel  =  np.fromfile( f, dtype=end+'f', count=3*NumPart ).reshape( (NumPart, 3 ) )\n      elif identi == 'MGAS' :\n         snap.mgas =  np.fromfile( f, dtype=end+'f', count=NumPart )\n      elif identi == 'ID  ' :\n         snap.id   =  np.fromfile( f, dtype=end+'I', count=NumPart )\n      elif identi == 'HSML' :\n         snap.hsml =  np.fromfile( f, dtype=end+'f', count=NumPart )\n      elif identi == 'U   ' :\n         snap.u    =  np.fromfile( f, dtype=end+'f', count=NumPart )\n      elif identi == 'RHO ' :\n         snap.rho  =  np.fromfile( f, dtype=end+'f', count=NumPart )\n      elif identi == 'ENDT' :\n         snap.endt =  np.fromfile( f, dtype=end+'f', count=NumPart )\n      elif identi == 'NORM' :\n         snap.norm =  np.fromfile( f, dtype=end+'f', count=3*NumPart ).reshape( (NumPart, 3 ) )\n      elif identi == 'UUP ' :\n         snap.uup  =  np.fromfile( f, dtype=end+'f', count=NumPart )\n      elif identi == 'UDOW' :\n         snap.udow =  np.fromfile( f, dtype=end+'f', count=NumPart )\n      elif identi == 'RUP ' :\n         snap.rup  =  np.fromfile( f, dtype=end+'f', count=NumPart )\n      elif identi == 'RDOW' :\n         snap.rdow =  np.fromfile( f, dtype=end+'f', count=NumPart )\n      elif identi == 'DIVV' :\n         snap.divv =  np.fromfile( f, dtype=end+'f', count=NumPart )\n      elif identi == 'MACH' :\n         snap.mach =  np.fromfile( f, dtype=end+'f', count=NumPart )\n      else :\n         print('Identifier is not recognized'  ) \n         break\n      \n   f.close()\n   if verbose:\n      print(' load snapshot ... done')\n\n   return \n\n\n\ndef save_snap ( snap, filename, verbose=False) :\n    \n   if verbose:\n       print(' save snapshot <%s> :' % snap.name)\n     \n#   try :\n\n   if not os.path.exists(os.path.dirname(filename)):\n        try:\n            os.makedirs(os.path.dirname(filename))\n        except OSError as exc: # Guard against race condition\n            if exc.errno != errno.EEXIST:\n                raise\n   fwrite = open( filename, 'w' )\n   end = '<'\n\n   fwrite.write(struct.pack( end+'II',  1,2 ))\n      \n   \"\"\" The snapshot is altered, i.e. this is smelly codeas it should just save a snapshot. In our case only not of relevance because, we either save the snapshots or create radio maps.\"\"\"\n   if snap.transform:\n         snap.pos[:,0] += snap.head['Xc']\n         snap.pos[:,1] += snap.head['Yc']\n         snap.pos[:,2] += snap.head['Zc']\n    \n   if snap.headerc == 'Mpc':\n       snap.head['Xc'] /= 1e3   #  Mpc -> kpc\n       snap.head['Yc'] /= 1e3   #  Mpc -> kpc\n       snap.head['Zc'] /= 1e3   #  Mpc -> kpc\n   elif snap.headerc != 'kpc':\n       print('Snapshot header of central coordinates: UNIT \"%s\" unkown!' % (snap.headerc))\n   \n \n\n   snap.head['NumPart'] = snap.hsml.shape[0]\n   fwrite.write(struct.pack( end+'lfffffff', snap.head['NumPart'], snap.head['Mvir'], snap.head['Rvir'], snap.head['Xc'], snap.head['Yc'], snap.head['Zc'], snap.head['aexpan'], snap.head['hubble'] ) )\n\n#   f.read( 512 - 10*4 )\n   fwrite.write( '{0:0472b}'.format(0) )\n   \n   pairs  = [ ['POS ',lambda x:  x.pos],\n              ['VEL ',lambda x:  x.vel],\n              ['NORM',lambda x:  x.norm] ]\n   for ident,lambd in pairs:\n#       print(struct.pack( end+'s', ident), struct.pack( end+'c', ident[0]), struct.pack( end+'c', ident[1]), struct.pack( end+'c', ident[2]), struct.pack( end+'c', ident[3]))\n#       leads to an bug, because 4 chars do not equal an string of for chars:\n#       fwrite.write( struct.pack( end+'s', ident)) #end+'4c'\n       try:\n           towrite = lambd(snap).astype('f').tostring()\n           fwrite.write( struct.pack( end+'c', ident[0]) + struct.pack( end+'c', ident[1]) + struct.pack( end+'c', ident[2]) + struct.pack( end+'c', ident[3])) \n           fwrite.write( towrite  )#end+f\n       except:\n           print('save_snap:',ident,'not found')\n\n       \n   pairs  = [ ['HSML',lambda x:x.hsml],\n#              ['MGAS',lambda x:x.mgas],\n              ['U   ',lambda x:x.u],\n              ['RHO ',lambda x:x.rho],\n              ['ENDT',lambda x:x.endt],\n              ['UUP ',lambda x:x.uup],\n              ['UDOW',lambda x:x.udow],\n              ['RUP ',lambda x:x.rup],\n              ['RDOW',lambda x:x.rdow],\n              ['DIVV',lambda x:x.divv],\n              ['MACH',lambda x:x.mach],]\n   for ident,lambd in pairs:\n#       leads to an bug, because 4 chars do not equal an string of for chars:\n#       fwrite.write( struct.pack( end+'s', ident)) #\n       try:\n           towrite = lambd(snap).astype('f').tostring()\n           fwrite.write( struct.pack( end+'c', ident[0]) + struct.pack( end+'c', ident[1]) + struct.pack( end+'c', ident[2]) + struct.pack( end+'c', ident[3]))\n           fwrite.write( towrite) \n       except:\n           print('save_snap:',ident,'not found')\n\n   fwrite.close()\n   \n   if verbose:\n      print(' saving snapshot ... done')\n     \n   return \n\n\n\n\nclass Snapshot:\n   # A simple class for a snapshot of one resimulated Volume of MUSIC-2\n\n   def __init__(self, name, radio_name='', transform=True, headerc='Mpc') :\n       \n      self.name       = name.replace('Additional2','') # Compability with old folder structure\n      self.radio_name = radio_name\n      self.head = None \n      self.hsml = None\n      self.pos  = None \n      self.vel  = None\n      self.mgas = None\n      self.id   = None \n      self.u    = None\n      self.rho  = None \n      self.endt = None \n      self.norm = None\n      self.uup  = None\n      self.udow = None \n      self.rup  = None\n      self.rdow = None \n      self.divv = None \n      self.mach = None\n      self.radi = None\n      self.xray = None \n      self.transform  = transform\n      self.headerc    = headerc\n\n   def loaddata(self, term=False) : \n      if term: print('endian= ', '<') # args.endian\n      load_snap ( self, ) \n      \n   def savedata(self, savefolder, term=False):\n      if term: print('endian= ', '<') # args.endian\n      save_snap ( self, savefolder)    \n      \n# conversion factor gadget density to proper baryon density [cm-3]\ndef conversion_fact_gadget_rho_to_nb ( head ) :\n   fact  = 1e10 * const.solar_mass / head['hubble'] / const.proton_mass\n   fact /= ( 1e3 * const.parsec / head['hubble'] )**3.\n   fact /= ( head['aexpan'] )**3. \n   return fact \n   \n# conversion factor gadget density to proper baryon density [cm-3] as if the snapshot was taken at z=0\ndef conversion_fact_gadget_rho_to_nb_z0 ( head ) :\n   fact  = 1e10 * const.solar_mass / head['hubble'] / const.proton_mass\n   fact /= ( 1e3 * const.parsec / head['hubble'] )**3.\n   #fact /= ( head['aexpan'] )**3. \n   return fact  \n   \n# electron density for fully ionized medium\n# ......    Y = 4nHe / ( nH + 4nHe )\n# ......    ne / nb = nH + 2nHe / ( nH + 4nHe )\n# ......    nb / ntot = nH + 4nHe / ( 2nH + 3nHe )    (note ne = nH + 2nHe, fully ionized)\ndef conversion_fact_ne_per_nb( ) :\t\n\tnHe_per_nH  = const.Y_helium / ( 4.0 * ( 1.0 - const.Y_helium ))\n\tne_per_nb   = 1.0 + 2.0 * nHe_per_nH / ( 1 + 4.0 * nHe_per_nH )\n\treturn ne_per_nb\n   \ndef conversion_fact_nb_per_ntot ( ) :\n\tnHe_per_nH  = const.Y_helium / ( 4.0 * ( 1.0 - const.Y_helium ))\n\tnb_per_ntot = ( 1.0 + 4.0*nHe_per_nH ) / ( 2.0 + 3.0 * nHe_per_nH )\n\treturn nb_per_ntot\n   \n# convert gadget specific energy density (U) to temperature [keV]\n# ......   GADGET CONVERSION FROM U TO T\n# ......   XH      = Zmgas(6,*)/mass_gas(*)\n# ......   yHelium = (1. - XH)/(4.*XH)\n# ......   mu      = (1 + 4.* yHelium)/ (1.+ yHelium + ne1gas )\n# ......   temp    = GAMMA_MINUS1 * ugas * mu * 1.6726 / 1.3806 * 1.e-8 ; / BOLTZMANN  * PROTONMASS\n# ......   temp    = temp * 1e10 ; UnitEnergy_in_cgs/UnitMass_in_g (to get T in Kelvin)\ndef conversion_fact_gadget_U_to_keV( head ) :\n   nb_per_ntot = conversion_fact_nb_per_ntot( )\n   fact  = const.kilometer_per_sec**2. * ( head['gamma'] - 1. ) * nb_per_ntot * const.proton_mass\n   fact /= 1e3*const.electron_volt\n   return fact\n\n\ndef comH_to_phys( head, z=None ) :\n \n    if z is not None:\n        return 1/(1+z)/head['hubble'] \n    else:\n        return head['aexpan']/head['hubble']\n\n\n\n", "meta": {"hexsha": "5507506a8cac8f42b7fa9c6e9d6d09c220c8ef34", "size": 11413, "ext": "py", "lang": "Python", "max_stars_repo_path": "surveysim/music2/loadsnap.py", "max_stars_repo_name": "jakgel/clusterbuster", "max_stars_repo_head_hexsha": "d79400a0faf43dece457d99b024b955aef544fc2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-09-10T14:06:45.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-10T14:06:45.000Z", "max_issues_repo_path": "surveysim/music2/loadsnap.py", "max_issues_repo_name": "jakgel/clusterbuster", "max_issues_repo_head_hexsha": "d79400a0faf43dece457d99b024b955aef544fc2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "surveysim/music2/loadsnap.py", "max_forks_repo_name": "jakgel/clusterbuster", "max_forks_repo_head_hexsha": "d79400a0faf43dece457d99b024b955aef544fc2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3343653251, "max_line_length": 200, "alphanum_fraction": 0.5625164286, "include": true, "reason": "import numpy", "num_tokens": 3558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3593641314378279, "lm_q1q2_score": 0.18529530316584752}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul  1 10:26:52 2021\n\n@author: dlvilla\n\n\nCreated on Tue Apr 20 14:50:39 2021\n\nCopyright Notice\n=================\n\nCopyright 2021 National Technology and Engineering Solutions of Sandia, LLC. \nUnder the terms of Contract DE-NA0003525, there is a non-exclusive license \nfor use of this work by or on behalf of the U.S. Government. \nExport of this program may require a license from the \nUnited States Government.\n\nPlease refer to the LICENSE.md file for a full description of the license\nterms for MEWS. \n\nThe license for MEWS is the Modified BSD License and copyright information\nmust be replicated in any derivative works that use the source code.\n\n@author: dlvilla\n\nMEWS = Multi-senario Extreme Weather Simulator\n\nMETHODS   mews.weather.DOE2Weather.read_doe2_bin and  \n          mews.weather.DOE2Weather.write_doe2_bin\n \n   Are translations of parts of BIN2TXT.F and TXT2BIN.F translated with permission\n   from James and Jeff Hirsch and Associates (JJH&A). The license for these utilities \n   must be formed with (JJH&A) before they are distributed in any other package\n   besides MEWS\n\n\n\"\"\"\n\nfrom numpy import zeros,cumsum,arange, int64, float64,array\nimport numpy as np\nimport pandas as pd\nfrom subprocess import Popen, PIPE\nfrom os.path import isfile, dirname,basename, join\nfrom os import chdir as cd\nfrom os import remove as rm\nfrom os import getcwd as pwd\nimport os\nfrom shutil import copy as cp\nfrom pandas import DataFrame, DatetimeIndex, DateOffset, Series\nfrom datetime import datetime, timedelta\nimport warnings\nimport logging\nimport struct\n\nclass DataFormats():\n    # changing this will cause significant portions of the code to fail\n    header_dtype = np.dtype([('location_IWDID','a20'),\n                                            ('year_IWYR', 'i4'),\n                                            ('latitude_WLAT','f4'),\n                                            ('longitude_WLONG','f4'),\n                                            ('timezone_IWTZN','i4'),\n                                            ('record_length_LRECX','i4'),\n                                            ('number_days_NUMDAY','i4'),\n                                            ('clearness_number_CLN_IM1','f4'),\n                                            ('ground_temperature_GT_IM1','f4'),\n                                            ('solar_flag_IWSOL','i4')])\n    column_description = ['MONTH (1-12)',\n        'DAY OF MONTH',\n        'HOUR OF DAY',\n        'WET BULB TEMP (DEG F)',\n        'DRY BULB TEMP (DEG F)',\n        'PRESSURE (INCHES OF HG)',\n        'CLOUD AMOUNT (0 - 10)',\n        'SNOW FLAG (1 = SNOWFALL)',\n        'RAIN FLAG (1 = RAINFALL)',\n        'WIND DIRECTION (0 - 15; 0=N, 1=NNE, ETC)',\n        'HUMIDITY RATIO (LB H2O/LB AIR)',\n        'DENSITY OF AIR (LB/CU FT)',\n        'SPECIFIC ENTHALPY (BTU/LB)',\n        'TOTAL HOR. SOLAR (BTU/HR-SQFT)',\n        'DIR. NORMAL SOLAR (BTU/HR-SQFT)',\n        'CLOUD TYPE (0 - 2)',\n        'WIND SPEED (KNOTS)']\n\nclass DOE2_Weather_Error(Exception):\n    def __init__(self,error_message):\n        self.error_message = error_message\n\nclass DOE2Weather(object):\n    \n    def __init__(self):\n        self.column_description = DataFormats.column_description\n    \n    def _rm_file(self,filenamepath):\n        if isfile(filenamepath):\n            try:\n                rm(filenamepath)\n            except:\n                raise DOE2_Weather_Error(\"The operating system will not allow python to remove the \" +\n                            filenamepath + \" file!\")\n\n    def bin2txt(self,binfilename,bin2txtpath):\n        txtfilename = \"\"\n        if isfile(bin2txtpath) and isfile(binfilename):\n            curdir = pwd()\n            try:\n                cd(dirname(bin2txtpath))\n                self._rm_file(\"WEATHER.FMT\")\n                self._rm_file(\"WEATHER.BIN\")\n                if not os.path.isabs(binfilename):\n                    binfilename2 = os.path.join(curdir,binfilename)\n                else:\n                    binfilename2 = binfilename\n                cp(binfilename2,\"WEATHER.BIN\")\n                    \n                # no arguments needed\n                pp = Popen(basename(bin2txtpath),stdout=PIPE, stderr=PIPE, shell=True)\n                output, errors = pp.communicate()\n                if not errors == b'':\n                    warnings.warn(\"WARNING! An error was recorded by Popen.communicate but this does not mean the BIN2TXT did not work. Investigate further to verify it worked.\")\n                txtfilename = join(dirname(binfilename2) , basename(binfilename2).split(\".\")[0] + \".txt\")\n                cp(\"WEATHER.FMT\",txtfilename)\n                cd(curdir)\n            except:\n                # return to the correct directory\n                try:\n                    cd(curdir)\n                    raise DOE2_Weather_Error(\"The bin to text process failed!\")\n                except:\n                    raise DOE2_Weather_Error(\"The OS will not allow return to the original directory. \" + curdir)\n        else:\n            if not isfile(bin2txtpath):\n                raise DOE2_Weather_Error(\"doe2bin2txt.conver_bin_to_txt: the requested bin2txtpath\" + \n                        \" executable does not exist! A valid path to the BIN2TXT.EXE\" +\n                        \" utility must be provided.\")\n            else:\n                raise DOE2_Weather_Error(\"doe2bin2txt.conver_bin_to_txt: the requested binfilename\" + \n                        \" does not exist! A valid path to a valid DOE2 weather binary\" +\n                        \" file must be provided.\")\n        return txtfilename\n    \n    \n    def txt2bin(self,txtfilename,txt2binpath,binfilename):\n        if isfile(txt2binpath) and isfile(txtfilename):\n            curdir = pwd()\n            try:\n                change_dir = len(dirname(txt2binpath)) != 0\n                if change_dir:\n                    cd(dirname(txt2binpath))\n                self._rm_file(\"WEATHER.BIN\")\n                if txtfilename != \"WEATHER.FMT\":\n                   cp(txtfilename,\"WEATHER.FMT\")\n                # no arguments needed\n                p = Popen(basename(txt2binpath),stdout=PIPE, stderr=PIPE, shell=True)\n                output, errors = p.communicate()\n                if not errors == b'':\n                    warnings.warn(\"The process produced an error make sure the process worked!\\n\\n\" + str(errors) + \"\\n\\n\" + str(output))\n                cp(\"WEATHER.BIN\",binfilename)\n                self._rm_file(\"WEATHER.BIN\")\n                cd(curdir)\n            except:\n                # return to the correct directory\n                try:\n                    cd(curdir)\n                except:\n                    raise DOE2_Weather_Error(\"The OS will not allow return to the original directory.\\n\\n \" + curdir)\n        else:\n            if not isfile(txt2binpath):\n                raise DOE2_Weather_Error(\"doe2bin2txt.txt2bin: the requested bin2txtpath\" + \n                        \" executable does not exist! A valid path to the TXT2BIN.EXE\" +\n                        \" utility must be provided.\")\n            else:\n                raise DOE2_Weather_Error(\"doe2bin2txt.txt2bin: the requested txtfilename\" + \n                        \" does not exist! A valid path to a valid DOE2 weather textfile\" +\n                        \" file must be provided.\")\n    \n    \n    def df2bin(self,df, binfilename, use_exe=False, start_datetime=None, hour_in_file=None, txt2bin_exepath=None,\n               location=None,fyear=None,latitude=None,longitude=None,timezone=None,\n               iwsz=2,iftyp=3,clearness_number=None,ground_temp=None):\n    \n        \"\"\"\n        df2bin(df, binfilename, start_datetime, hour_in_file, txt2bin_exepath,\n               location=None,fyear=None,latitude=None,longitude=None,timezone=None,\n               iwsz=2,iftyp=3,clearness_number=None,ground_temp=None)\n        \n        Parameters\n        ----------\n            df              : pd.Dataframe: must contain the columns originally read from a\n                                   DOE2 BIN weather file format (in the table below)\n                                   if use_exe = False, df must have a \n            binfilename     : str : path and filename that will be output with the\n                                   weather signals in df.\n            use_exe         : bool : optional : Default=False\n                                    Set to True if using TXT2BIN is desired \n                                    instead of python. Changing use_exe between\n                                    reads and writes is not allowed\n            \n            All other parameters only apply if use_exe = True                         \n                                    \n            start_datetime  : datetime :start date and time to be output in the weather file\n                                    typically this is Jan 1st, fyear\n            hour_in_file    : int : Either 8760 or 8784\n            txt2bin_exepath : str : path and filename that point to TXT2BIN.EXE\n                                    DOE2 utility that can be obtained from www.doe2.com\n                                    after forming a license agreement with James Hirsch\n                                    and associates.\n            location .. and all other inputs\n            \n            \n        Returns\n        =======\n        \n        None\n        \n        \n        %% From TXT2BIN.FMT - this gives the exact format needed to output a\n        %                     text file that TXT2BIN.EXE can process.\n        %       THIS DOCUMENTS A FORMATTED WEATHER FILE (WEATHER.FMT) MADE FROM\n        %       A PACKED BINARY DOE2 WEATHER FILE (WEATHER.BIN) USING WTHFMT2.EXE\n        %       AND THE EXTRA FILE NEEDED (not really!) TO PACK IT WITH FMTWTH2.EXE\n        %  \n        % on input.dat:              \n        % \n        % Record 1       IWSZ,IFTYP\n        %                FORMAT(12X,I1,17X,I1)     \n        % \n        %       IWSZ           WORD SIZE          1 = 60-BIT, 2 = 30-BIT\n        %       IFTYP          FILE TYPE          1 = OLD, 2 = NORMAL (NO SOLAR),\n        %                                         3 = THE DATA HAS SOLAR\n        % on weather.fmt:              \n        % \n        % Record 1       (IWDID(I),I=1,5),IWYR,WLAT,WLONG,IWTZN,IWSOL\n        %                FORMAT(5A4,I5,2F8.2,2I5)     \n        % \n        % Record 2       (CLN(I),I=1,12)\n        %                FORMAT(12F6.2)      \n        % \n        % Record 3       (GT(I),I=1,12)\n        %                FORMAT(12F6.1)\n        % \n        % Records 4,8763\n        %                KMON, KDAY, KH, WBT, DBT, PATM, CLDAMT, ISNOW, \n        %                IRAIN, IWNDDR, HUMRAT, DENSTY, ENTHAL, SOLRAD,\n        %                DIRSOL, ICLDTY, WNDSPD\n        %                FORMAT(3I2,2F5.0,F6.1,F5.0,2I3,I4,F7.4,F6.3,F6.1,2F7.1,I3,F5.0)      \n        %       IWDID          LOCATION I.D.\n        %       IWYR           YEAR\n        %       WLAT           LATITUDE\n        %       WLONG          LONGITUDE\n        %       IWTZN          TIME ZONE NUMBER\n        %       IWSOL          SOLAR FLAG         IWSOL = IWSZ + (IFTYP-1)*2 - 1\n        %       CLN            CLEARNESS NO.\n        %       GT             GROUND TEMP.       (DEG R)\n        %       KMON           MONTH              (1-12)\n        %       KDAY           DAY OF MONTH\n        %       KH             HOUR OF DAY\n        %       WBT            WET BULB TEMP      (DEG F)\n        %       DBT            DRY BULB TEMP      (DEG F)\n        %       PATM           PRESSURE           (INCHES OF HG)\n        %       CLDAMT         CLOUD AMOUNT       (0 - 10)\n        %       ISNOW          SNOW FLAG          (1 = SNOWFALL)\n        %       IRAIN          RAIN FLAG          (1 = RAINFALL)\n        %       IWNDDR         WIND DIRECTION     (0 - 15; 0=N, 1=NNE, ETC)\n        %       HUMRAT         HUMIDITY RATIO     (LB H2O/LB AIR)\n        %       DENSTY         DENSITY OF AIR     (LB/CU FT)\n        %       ENTHAL         SPECIFIC ENTHALPY  (BTU/LB)\n        %       SOLRAD         TOTAL HOR. SOLAR   (BTU/HR-SQFT)\n        %       DIRSOL         DIR. NORMAL SOLAR  (BTU/HR-SQFT)\n        %       ICLDTY         CLOUD TYPE         (0 - 2)\n        %       WNDSPD         WIND SPEED         KNOTS\"\"\"\n        if hasattr(self,'use_exe'):\n            if self.use_exe != use_exe:\n                raise ValueError(\"This class does not support switching between\"+\n                                 \" using Python and using the BIN2TXT.F and TXT2BIN.F\"+\n                                 \" executables!\")\n        else:\n            self.use_exe = use_exe\n        \n\n        if use_exe:        \n            cdir = pwd()\n            #try:\n            change_dir = len(dirname(binfilename)) != 0 \n            if change_dir:\n                cd(dirname(binfilename))\n            self._rm_file(\"WEATHER.FMT\")\n            self._rm_file(\"WEATHER.BIN\")\n            with open(\"INPUT.DAT\",'w') as dat:\n                dat.write('            {0:1.0f}                 {1:1.0f}'.format(iwsz,iftyp))\n            with open(\"WEATHER.FMT\",'w') as fmt:\n                # 3 header rows\n    # header_dtype = np.dtype([('location_IWDID','a20'),\n    #                                         ('year_IWYR', 'i4'),\n    #                                         ('latitude_WLAT','f4'),\n    #                                         ('longitude_WLONG','f4'),\n    #                                         ('timezone_IWTZN','i4'),\n    #                                         ('record_length_LRECX','i4'),\n    #                                         ('number_days_NUMDAY','i4'),\n    #                                         ('clearness_number_CLN_IM1','f4'),\n    #                                         ('ground_temperature_GT_IM1','f4'),\n    #                                         ('solar_flag_IWSOL','i4')])                \n                \n                if isinstance(df.headers[0]['location_IWDID'][0],np.bytes_):\n                    location_str = df.headers[0]['location_IWDID'][0].decode('ascii')\n                else:\n                    location_str = df.headers[0]['location_IWDID'][0]\n                    \n                row1 = '{0:20s}{1:5d}{2:8.2f}{3:8.2f}{4:5d}{5:5d}\\n'.format(\n                    location_str,\n                    df.headers[0]['year_IWYR'][0],\n                    df.headers[0]['latitude_WLAT'][0], \n                    df.headers[0]['longitude_WLONG'][0], \n                    df.headers[0]['timezone_IWTZN'][0],\n                    df.headers[0]['solar_flag_IWSOL'][0])\n                fmt.write(row1)\n                clearness_number = [head['clearness_number_CLN_IM1'][0] for head in df.headers]\n                ground_temp = [head['ground_temperature_GT_IM1'][0] for head in df.headers]\n                \n                fmt.write((12*'{:6.2f}'+'\\n').format(*clearness_number))\n                fmt.write((12*'{:6.2f}'+'\\n').format(*ground_temp))\n                \n                for index, row in df.iterrows():\n                    fmt.write((3*'{:2.0f}'+2*'{:5.0f}' + '{:6.1f}{:5.0f}' + 2*'{:3.0f}' + \n                     '{:4.0f}{:7.4f}{:6.3f}{:6.1f}' + 2*'{:7.1f}'+'{:3.0f}{:5.0f}\\n').format(\n                             *row.tolist()))\n            if isfile(txt2bin_exepath):\n                if change_dir:\n                    cp(txt2bin_exepath,\".\")\n                else:\n                    cp(txt2bin_exepath,\".\")\n                new_exe_path = join(\".\",basename(txt2bin_exepath))\n                self.txt2bin(\"WEATHER.FMT\",new_exe_path,os.path.basename(binfilename))\n            else:\n                cd(cdir)\n                raise DOE2_Weather_Error(\"The txt2bin.exe utility is not present at: \\n\\n\" + txt2bin_exepath)        \n            cd(cdir)    \n        \n        else:\n            # size and type checking\n            m = df[self.column_description].values\n            \n            if m.shape[1] != 17:\n                raise ValueError(\"This function only handles dataframes with\"+\n                                 \" 17 columns as defined for DOE-2 BIN weather files!\")\n            elif not hasattr(df,'headers'):\n                raise ValueError(\"The input dataframe df must have an attribute \"+\n                                 \"'headers' that contains a list of \")\n            headers = df.headers\n            DOE2Weather.write_doe2_bin(m, headers, binfilename)\n\n\n    def bin2df(self,binfilename, start_datetime=None, hour_in_file=None, bin2txt_exepath=None, timezone=None, dst=None, use_exe=False):\n        \"\"\" This function was originally written in matlab and is the \n        \"ReadDOE2BINTXTFile.m\" function except that it also includes conversion\n        of the BIN file into a text file  \n        \n        DST is a list of the start of daylight savings and end so that\n        adjustments can be made and the time stamps adjusted for daylight savings.\n    % the input *.txt \"filename\" must come from a DOE2 bin file that has been\n    %  converted to a text file. It has the following columns of information:\n    % Column Number   Variable      Description         Units\n    %C 1              IM2            MOMTH              (1-12)\n    %C 2             ID             DAY OF MONTH\n    %C 3             IH             HOUR OF DAY\n    %C 4             CALC(1)        WET BULB TEMP      (DEG F)\n    %C 5             CALC(2)        DRY BULB TEMP      (DEG F)\n    %C 6             CALC(3)        PRESSURE           (INCHES OF HG)\n    %C 7             CALC(4)        CLOUD AMOUNT       (0 - 10)\n    %C 8             ISNOW          SNOW FLAG          (1 = SNOWFALL)\n    %C 9             IRAIN          RAIN FLAG          (1 = RAINFALL)\n    %C 10            IWNDDR         WIND DIRECTION     (0 - 15; 0=N, 1=NNE, ETC)\n    %C 11            CALC(8)        HUMIDITY RATIO     (LB H2O/LB AIR)\n    %C 12            CALC(9)        DENSITY OF AIR     (LB/CU FT)\n    %C 13            CALC(10)       SPECIFIC ENTHALPY  (BTU/LB)\n    %C 14            CALC(11)       TOTAL HOR. SOLAR   (BTU/HR-SQFT)\n    %C 15            CALC(12)       DIR. NORMAL SOLAR  (BTU/HR-SQFT)\n    %C 16            ICLDTY         CLOUD TYPE         (0 - 2)\n    %C 17            CALC(14)       WIND SPEED         KNOTS    \n        \n        \n        \"\"\"\n        if (timezone is None and not dst is None) or (not timezone is None and dst is None):\n            raise ValueError(\"The timezone and dst values must be specified together!\")\n        \n        \n        hour_in_day = 24\n        if hasattr(self,'use_exe'):\n            if use_exe != self.use_exe:\n                raise ValueError(\"This class does not support switching between\" +\n                                 \" using BIN2TXT.EXE and TXT2BIN.EXE and using\" +\n                                 \" Python for translation! None returned as a result!\")\n        else:\n            # set the mode of operation of the class\n            self.use_exe = use_exe\n        \n        if use_exe:\n            # this is the old way of doing things.\n            txtname = self.bin2txt(binfilename, bin2txt_exepath)\n            \n            if len(txtname)==0:\n                raise DOE2_Weather_Error(\"bom2df:The bin file was not successfully converted please troubleshoot!\")\n\n            num = 0\n            m = zeros((hour_in_file,17))\n            # this is specific to the conversion utility and how it writes out ASCII.\n            EntryLength = [0, 2, 2, 2, 5, 5, 6, 5, 3, 3, 4, 7, 6, 6, 7, 7, 3, 5]\n            j = 0\n            i = 0\n            b_lines = []\n            \n            with open(txtname,'r') as h:\n                for text_line in h:\n                    if num <= 2:\n                        num += 1 # skip three lines\n                        b_lines.append(text_line)\n                    else:  \n                        for mm,nn in zip(cumsum(EntryLength[0:-1]),cumsum(EntryLength[1:])):\n                            m[j,i] = float(text_line[mm:nn])\n                            i+=1\n                        j +=1\n                        i = 0\n        else:\n            # use pure python to do this \n            m, headers = self.read_doe2_bin(binfilename)\n        \n        # adjust for leap year by repeating February 28th on February 29th.\n        if hour_in_file == 8784:\n            # February 28th is the 59th day of the year\n            # Febrary 29th is the 60th day of a year\n            sid = 59 * 24\n            \n            # shift all of March1st to December 31 over 24 hours\n            m[sid+24:] = m[sid:-24]\n            # repeat February 28th \n            m[sid:sid+24] = m[sid-24:sid]\n            # reassign Feb 28th to Feb 29th - \n            # day of month column\n            ind = self.column_description.index(\"DAY OF MONTH\")\n            m[sid:sid+24,ind] = 29\n            MDAYS = [31,29,31,30,31,30,31,31,30,31,30,31] \n        else:\n            MDAYS = [31,28,31,30,31,30,31,31,30,31,30,31]\n        \n        \n        \n        dateVec = []\n        reached_hours_to_next = True\n        start_datetime_was_None = False\n        get_year_from_headers = False\n        \n        month = 0  # 0 = Jan\n        for i in arange(m.shape[0]):\n            \n            # see whether a replacement year has been provided - if not, use what\n            # is in the BIN file - if Python is used, the the header of each\n            # month can have a different year if it is TMY3\n            if start_datetime is None and use_exe:\n                start_datetime = datetime(year=int(b_lines[0][20:25]),day=1,month=1)\n                start_datetime_was_None = True\n            elif start_datetime is None and reached_hours_to_next and not use_exe:\n                hour_count = 0\n                hours_to_next = MDAYS[month]* hour_in_day\n\n                year = headers[month]['year_IWYR'][0]\n                month += 1\n                start_datetime_was_None = True\n                get_year_from_headers = True\n            elif not use_exe and start_datetime is None:\n                hour_count += 1\n\n            \n            if get_year_from_headers:\n                if hour_count > hours_to_next:    \n                    reached_hours_to_next = True\n                else:\n                    reached_hours_to_next = False\n\n            \n            # for cases with a replacement year OR use_exe where the text file \n            # does not convey the year at every header\n            if use_exe or not start_datetime_was_None:\n\n                current_time = start_datetime+timedelta(hours=float(i))\n                dateVec.append(datetime(current_time.year,current_time.month,\n                                        current_time.day,current_time.hour,0,0))\n            # \n            else:\n                dateVec.append(datetime(year,int(m[i,0]),int(m[i,1]),int(m[i,2])-1,0,0))\n            \n            if not dst is None:\n                #Handle daylight savings correctly\n                if dateVec[-1] == dst[0]:\n                    dateVec[-1] = dateVec[-1] + DateOffset(hour=1)\n                elif dateVec[-1] == dst[1]:\n                    dateVec[-1] = dateVec[-1] - DateOffset(hour=1)\n            \n            \n                \n        dateTimeIn = DatetimeIndex(dateVec)\n        if not timezone is None:\n            try:\n                dateTimeIn = dateTimeIn.tz_localize(timezone, ambiguous=True)\n            except Exception as e:\n                warnings.warn(\"The time zone localization process failed. \" \n                              + \" This probably happened because the time zone \" \n                              + \"input is incorrect!\")\n                raise e\n\n        df = DataFrame(index=dateTimeIn,data=m,columns=self.column_description,dtype=float64)\n    \n        # add header information (different depending on use_exe)\n        \n        # suppress warnings here. - We want to add attributes to the dataframe\n        # and are NOT trying to add columns\n        warnings.simplefilter(\"ignore\",category=UserWarning)\n\n        if use_exe:\n            clearness_number = [float(x) for x in b_lines[1].split(\" \") if len(x)!=0]\n            ground_temps = [float(x) for x in b_lines[2].split(\" \") if len(x)!=0]\n            headers = []\n            month = 0\n            \n            for num,temp in zip(clearness_number,ground_temps):\n                header_list = [(b_lines[0][0:20],\n                                     np.int32(b_lines[0][20:25]),\n                                     np.float32(b_lines[0][25:33]),\n                                     np.float32(b_lines[0][33:41]),\n                                     np.int32(b_lines[0][41:46]),\n                                     np.int32(1),\n                                     np.int32(MDAYS[month]),\n                                     np.float32(clearness_number[month]),\n                                     np.float32(ground_temps[month]),\n                                     np.int32(b_lines[0][46:51]))]\n                lheaders = np.array(header_list,dtype=DataFormats.header_dtype)\n \n                headers.append(lheaders)\n\n\n        df.headers = headers\n            \n        return df\n    \n    @staticmethod\n    def read_doe2_bin(binfilename):\n        with open(binfilename,mode='rb') as bh:\n            bin_content = bh.read()\n        \"\"\"\n        obj.read_doe2_bin(binfilename)\n        \n        Parameters\n        ==========\n        \n        binfilename : str : valid path and file name to a DOE-2 *.BIN weather \n                            file.\n        \n        Returns\n        =======\n        \n        m : np.array(x,17) : x = length of BIN file (ussually 8760)\n            The columns of this array are:\n                        \n            % Column Number   Variable      Description         Units\n            %C 1              IM2            MOMTH              (1-12)\n            %C 2             ID             DAY OF MONTH\n            %C 3             IH             HOUR OF DAY\n            %C 4             CALC(1)        WET BULB TEMP      (DEG F)\n            %C 5             CALC(2)        DRY BULB TEMP      (DEG F)\n            %C 6             CALC(3)        PRESSURE           (INCHES OF HG)\n            %C 7             CALC(4)        CLOUD AMOUNT       (0 - 10)\n            %C 8             ISNOW          SNOW FLAG          (1 = SNOWFALL)\n            %C 9             IRAIN          RAIN FLAG          (1 = RAINFALL)\n            %C 10            IWNDDR         WIND DIRECTION     (0 - 15; 0=N, 1=NNE, ETC)\n            %C 11            CALC(8)        HUMIDITY RATIO     (LB H2O/LB AIR)\n            %C 12            CALC(9)        DENSITY OF AIR     (LB/CU FT)\n            %C 13            CALC(10)       SPECIFIC ENTHALPY  (BTU/LB)\n            %C 14            CALC(11)       TOTAL HOR. SOLAR   (BTU/HR-SQFT)\n            %C 15            CALC(12)       DIR. NORMAL SOLAR  (BTU/HR-SQFT)\n            %C 16            ICLDTY         CLOUD TYPE         (0 - 2)\n            %C 17            CALC(14)       WIND SPEED         KNOTS    \n            \n        headers : list : list of np.array with specialized dtype to capture\n            the header for each month of data in the DOE-2 *.BIN file.\n            The dtype spec is as follows:\n                np.dtype([('location_IWDID','a20'),\n                          ('year_IWYR', 'i4'),\n                          ('latitude_WLAT','f4'),\n                          ('longitude_WLONG','f4'),\n                          ('timezone_IWTZN','i4'),\n                          ('record_length_LRECX','i4'),\n                          ('number_days_NUMDAY','i4'),\n                          ('clearness_number_CLN_IM1','f4'),\n                          ('ground_temperature_GT_IM1','f4'),\n                          ('solar_flag_IWSOL','i4')])\n        \n        License Note:\n        =============\n        \n        # THIS IS A TRANSLATION OF BIN2TXT.F except the TXT file is never written\n        # because data for direct use in Python is desired.\n        \n        # THIS reverse engineering was approved by Jeff Hirsch on behalf of\n        # James and Jeff Hirsch and Associates (JJH&A)\n        # along with putting the code on GITHUB with the contingency that the\n        # JJH&A license be acknowledged. The original correspondence is provided \n        # below:\n        \n        # Wed 7/7/2021 4:10 PM\n        Yes, you have my permission to distribute your DOE-2 weather file \n        python libraries with TXT2BIN and BIN2TXT executables on Github or \n        also translate the fortran source versions of those apps into python \n        and then distribute on Github as long as your acknowledge the \n        JJH&A license\n \n        ________________________________________\n        Jeff Hirsch\n        James J. Hirsch & Associates\n        Voice mail: (XXX) XXX-XXXX\n        mobile: (XXX) XXX-XXXX\n        -----------------------------------------------------\n        From: Villa, Daniel L \n        Sent: Wednesday, July 7, 2021 11:02 AM\n        To: Jeff.Hirsch@DOE2.com \n        Subject: Tranlate TXT2BIN.F and BIN2TXT.F into Python and distribute \n                 as open source??\n         \n        Jeff,\n         \n        I have built a tool that inputs and outputs DOE-2 weather files with \n        extreme events. I use the TXT2BIN.F and BIN2TXT.F executables with \n        the version of DOE-2 that I have licensed with Hirsch and Associates. \n        I would like to be able to distribute the python libraries with these \n        executables on Github or else be able to translate the *.F files into \n        python but know that the code is distributed under your license. \n         \n        Would Hirsch and Associates be willing to let me create Python \n        versions of TXT2BIN.F and BIN2TXT.F and to distribute them as open \n        source code on GitHUB? I understand and respect Hirsch and Associate’s \n        decision if this is not allowed. Thank you.\n         \n        Daniel Villa\n        Energy-Water System Integration Department 08825\n        Sandia National Laboratories\n        dlvilla@sandia.gov\n        XXX-XXX-XXXX\n\n        \"\"\"\n        \n        # initiate constants in BIN2TXT\n        MDAYS = [31,28,31,30,31,30,31,31,30,31,30,31]\n        XMASK_1D = np.array([-99., -99., 15., 0., 0., 0., 0., 0., .02, -30., 0.,\n                          .0, .0, .0, .0, 10., 1., 1., .1, 1., 1., 1., 1.,\n                          .0001, .001, .5, 1., 1., 1., 1., 0., 0.])\n        XMASK = XMASK_1D.reshape((2,16)).T\n        \n        # record length is 6200 and Fortran puts a 4 byte buffer at the beginning\n        # and end of the record. making each record a total of 6208 bytes.\n        #\n        recl = 6200 \n        num_buf_bytes = 4\n        tot_recl = recl + 2 * num_buf_bytes\n        blocksize=148992\n        \n        header_length = 56\n        num_month_in_year = 12\n        num_hour_in_day = 24\n        headers = []\n        \n        # read in headers\n      #   DO 100 IM1=1,12\n      #   READ (10) (IWDID(I),I=1,5),IWYR,WLAT,WLONG,IWTZN,LRECX,NUMDAY,\n      # _          CLN(IM1),GT(IM1),IWSOL\n      #   READ (10) IDUM\n      #   100 CONTINUE\n        \n        for IM1 in range(num_month_in_year):\n            head_start_byte = (recl + 2*num_buf_bytes) * IM1 + num_buf_bytes\n            headers.append(np.frombuffer(bin_content[head_start_byte:head_start_byte+header_length+1],\n                                         dtype=DataFormats.header_dtype\n                                         ,count=1)\n                            )\n        # Read and process data\n        LRECX = 0\n        byte_position = num_buf_bytes\n        IWTH = np.zeros(15)  # keep 1 indexing and leave the first element 0\n        CALC = np.zeros(15)\n        data_records = []\n        IDAT30 = np.zeros(1537)\n        iterIH = 0\n        iter_max = 1e6\n        for IM2 in range(1,num_month_in_year+1):\n            IDE = MDAYS[IM2-1]\n            for ID in range(1,IDE+1):\n                IH = 1\n                while IH <= num_hour_in_day and iterIH < iter_max:\n                    IRECX = int(IM2 * 2 + (ID-1)/16 - 1)   #105\n                    IDX = int(np.mod(ID-1,16) + 1)\n                    comparison = int(IRECX-LRECX)\n                    if comparison < 0:\n                        IDIF = int(LRECX - IRECX + 1)\n                        for I in range(IDIF):\n                            if np.mod(byte_position,tot_recl)==0 and byte_position > num_buf_bytes:\n                                byte_position = byte_position - tot_recl\n                            elif byte_position > num_buf_bytes:\n                                byte_position = byte_position - np.mod(byte_position,tot_recl)\n                        next_record = byte_position + tot_recl\n                        cur_dat = DOE2Weather._doe2_bin_data_format(bin_content,byte_position,next_record)\n                        LRECX = cur_dat['record_length_LRECX']\n                        byte_position = next_record\n                    elif comparison == 0:\n                        IDAT30[1:] = cur_dat['IDAT30']\n                        IP1 = int(96*(IDX-1) + 4*IH - 3)\n                        IWTH[3] = IDAT30[IP1]/65536\n                        IWTH[1] = np.mod(IDAT30[IP1],65536)/256\n                        IWTH[2] = np.mod(IDAT30[IP1],256)\n                        IWTH[11] = IDAT30[IP1+1]/1048576\n                        IWTH[12] = np.mod(IDAT30[IP1+1],1048576)/1024\n                        IWTH[4] = np.mod(IDAT30[IP1+1],1024)/64\n                        IWTH[5] = np.mod(IDAT30[IP1+1],64)/32\n                        IWTH[6] = np.mod(IDAT30[IP1+1],32)/16\n                        IWTH[7] = np.mod(IDAT30[IP1+1],16)\n                        IWTH[8] = IDAT30[IP1+2]/128\n                        IWTH[9] = np.mod(IDAT30[IP1+2],128)\n                        IWTH[10] = IDAT30[IP1+3]/2048\n                        IWTH[13] = np.mod(IDAT30[IP1+3],2048)/128\n                        IWTH[14] = np.mod(IDAT30[IP1+3],128)\n                        for I in range(1,15):\n                            CALC[I] = float(IWTH[I])*XMASK[I-1,2-1] + XMASK[I-1,1-1]\n                        \n                        \n                        ISNOW = int(CALC[5] + .01)\n                        IRAIN = int(CALC[6] + .01)\n                        IWNDDR = int(CALC[7] + .01)\n                        ICLDTY = int(CALC[13] + .01)\n                        \n                        data_records.append([IM2,ID,IH,CALC[1],CALC[2],CALC[3],\n                                             CALC[4],ISNOW,IRAIN,IWNDDR,CALC[8],\n                                             CALC[9],CALC[10],CALC[11],CALC[12],\n                                             ICLDTY,CALC[14]])\n                        IH += 1\n               \n                    elif comparison > 0:\n                        next_record = byte_position + tot_recl\n                        cur_dat = DOE2Weather._doe2_bin_data_format(bin_content,byte_position,next_record)\n                        LRECX = cur_dat['record_length_LRECX']\n                        byte_position = next_record\n                        \n                    iterIH += 1\n                if iterIH >= iter_max:\n                    raise StopIteration(\"The while loop over days has gotten\"\n                                        +\" stuck! The file being read may not\"\n                                        +\" be the correct BIN Format for DOE-2.\")\n        m = np.array(data_records)\n        return m, headers \n                        \n    @staticmethod\n    def _doe2_bin_data_format(bin_content,byte_position,next_record):\n        return np.frombuffer(bin_content[byte_position:next_record+1],\n                             np.dtype([('location_IWDID','a20'),\n                                            ('year_IWYR', 'i4'),\n                                            ('latitude_WLAT','f4'),\n                                            ('longitude_WLONG','f4'),\n                                            ('timezone_IWTZN','i4'),\n                                            ('record_length_LRECX','i4'),\n                                            ('number_days_NUMDAY','i4'),\n                                            ('clearness_number_CLN_IM1','f4'),\n                                            ('ground_temperature_GT_IM1','f4'),\n                                            ('solar_flag_IDUM','i4'),\n                                            ('IDAT30','1536i4')]),count=1)[0]    \n    @staticmethod\n    def write_doe2_bin(m,headers,binfilename,IWSZ=1,IFTYP=2):\n        \"\"\"\n        DOE2Weather.write_doe2_bin(m,headers,binfilename,IWSZ=1,IFTYP=2)\n        \n        Parameters\n        ==========\n\n        m : np.array(x,17) : x = length of BIN file (ussually 8760)\n            The columns of this array are:\n                        \n            % Column Number   Variable      Description         Units\n            %C 1              IM2            MOMTH              (1-12)\n            %C 2             ID             DAY OF MONTH\n            %C 3             IH             HOUR OF DAY\n            %C 4             CALC(1)        WET BULB TEMP      (DEG F)\n            %C 5             CALC(2)        DRY BULB TEMP      (DEG F)\n            %C 6             CALC(3)        PRESSURE           (INCHES OF HG)\n            %C 7             CALC(4)        CLOUD AMOUNT       (0 - 10)\n            %C 8             ISNOW          SNOW FLAG          (1 = SNOWFALL)\n            %C 9             IRAIN          RAIN FLAG          (1 = RAINFALL)\n            %C 10            IWNDDR         WIND DIRECTION     (0 - 15; 0=N, 1=NNE, ETC)\n            %C 11            CALC(8)        HUMIDITY RATIO     (LB H2O/LB AIR)\n            %C 12            CALC(9)        DENSITY OF AIR     (LB/CU FT)\n            %C 13            CALC(10)       SPECIFIC ENTHALPY  (BTU/LB)\n            %C 14            CALC(11)       TOTAL HOR. SOLAR   (BTU/HR-SQFT)\n            %C 15            CALC(12)       DIR. NORMAL SOLAR  (BTU/HR-SQFT)\n            %C 16            ICLDTY         CLOUD TYPE         (0 - 2)\n            %C 17            CALC(14)       WIND SPEED         KNOTS    \n            \n        headers : list : list of np.array with specialized dtype to capture\n            the header for each month of data in the DOE-2 *.BIN file.\n            The dtype spec is as follows:\n                np.dtype([('location_IWDID','a20'),\n                          ('year_IWYR', 'i4'),\n                          ('latitude_WLAT','f4'),\n                          ('longitude_WLONG','f4'),\n                          ('timezone_IWTZN','i4'),\n                          ('record_length_LRECX','i4'),\n                          ('number_days_NUMDAY','i4'),\n                          ('clearness_number_CLN_IM1','f4'),\n                          ('ground_temperature_GT_IM1','f4'),\n                          ('solar_flag_IWSOL','i4')])\n                \n        binfilename : str : valid path/filename for which a file will be \n            written.\n                \n        Returns\n        =======\n        None \n        \n        License Note:\n        =============\n        \n        # THIS IS A TRANSLATION OF TXT2BIN.F except the TXT file is never read\n        # from because data is coming from Python.\n        \n        # THIS reverse engineering was approved by Jeff Hirsch on behalf of\n        # James and Jeff Hirsch and Associates (JJH&A)\n        # along with putting the code on GITHUB with the contingency that the\n        # JJH&A license be acknowledged. The original correspondence is provided \n        # below:\n        \n        # Wed 7/7/2021 4:10 PM\n        Yes, you have my permission to distribute your DOE-2 weather file \n        python libraries with TXT2BIN and BIN2TXT executables on Github or \n        also translate the fortran source versions of those apps into python \n        and then distribute on Github as long as your acknowledge the \n        JJH&A license\n \n        ________________________________________\n        Jeff Hirsch\n        James J. Hirsch & Associates\n        Voice mail: (XXX) XXX-XXXX\n        mobile: (XXX) XXX-XXXX\n        -----------------------------------------------------\n        From: Villa, Daniel L \n        Sent: Wednesday, July 7, 2021 11:02 AM\n        To: Jeff.Hirsch@DOE2.com \n        Subject: Tranlate TXT2BIN.F and BIN2TXT.F into Python and distribute \n                 as open source??\n         \n        Jeff,\n         \n        I have built a tool that inputs and outputs DOE-2 weather files with \n        extreme events. I use the TXT2BIN.F and BIN2TXT.F executables with \n        the version of DOE-2 that I have licensed with Hirsch and Associates. \n        I would like to be able to distribute the python libraries with these \n        executables on Github or else be able to translate the *.F files into \n        python but know that the code is distributed under your license. \n         \n        Would Hirsch and Associates be willing to let me create Python \n        versions of TXT2BIN.F and BIN2TXT.F and to distribute them as open \n        source code on GitHUB? I understand and respect Hirsch and Associate’s \n        decision if this is not allowed. Thank you.\n         \n        Daniel Villa\n        Energy-Water System Integration Department 08825\n        Sandia National Laboratories\n        dlvilla@sandia.gov\n        XXX-XXX-XXXX\n        \n        FORTRAN VARIABLE MEANING KEY:\n            \n            C              \n            C     IWSZ           WORD SIZE          1 = 60-BIT, 2 = 30-BIT\n            C     IFTYP          FILE TYPE          1 = OLD, 2 = NORMAL (NO SOLAR),\n            C                                       3 = THE DATA HAS SOLAR\n            C     IWDID          LOCATION I.D.\n            C     IWYR           YEAR\n            C     WLAT           LATITUDE\n            C     WLONG          LONGITUDE\n            C     IWTZN          TIME ZONE NUMBER\n            C     IWSOL          SOLAR FLAG         FUNCTION OF IWSZ + IFTYP\n            C     CLN            CLEARNESS NO.\n            C     GT             GROUND TEMP.       (DEG R)\n            C     KMON           MONTH              (1-12)\n            C     KDAY           DAY OF MONTH\n            C     KH             HOUR OF DAY\n            C     WBT            WET BULB TEMP      (DEG F)\n            C     DBT            DRY BULB TEMP      (DEG F)\n            C     PATM           PRESSURE           (INCHES OF HG)\n            C     CLDAMT         CLOUD AMOUNT       (0 - 10)\n            C     ISNOW          SNOW FLAG          (1 = SNOWFALL)\n            C     IRAIN          RAIN FLAG          (1 = RAINFALL)\n            C     IWNDDR         WIND DIRECTION     (0 - 15; 0=N, 1=NNE, ETC)\n            C     HUMRAT         HUMIDITY RATIO     (LB H2O/LB AIR)\n            C     DENSTY         DENSITY OF AIR     (LB/CU FT)\n            C     ENTHAL         SPECIFIC ENTHALPY  (BTU/LB)\n            C     SOLRAD         TOTAL HOR. SOLAR   (BTU/HR-SQFT)\n            C     DIRSOL         DIR. NORMAL SOLAR  (BTU/HR-SQFT)\n            C     ICLDTY         CLOUD TYPE         (0 - 2)\n            C     WNDSPD         WIND SPEED         KNOTS\n\n        \"\"\" \n        # record length is 6200 and Fortran puts a 4 byte buffer at the beginning\n        # and end of the record. making each record a total of 6208 bytes.\n        #\n        recl = 6200 \n        num_buf_bytes = 4\n        tot_recl = recl + 2 * num_buf_bytes\n        num_month_in_year = 12\n        num_hour_in_day = 24\n        \n        CLN = []; GT = []; IWYR = []; WLAT = []; WLONG = []; IWTZN = []; \n        LRECX = []; NUMDAY = []; IWSOL = []; IWDID = [];\n        \n        # translate to the original syntax for clarity\n        for header in headers:\n            IWDID.append(header['location_IWDID'][0])\n            CLN.append(header[\"clearness_number_CLN_IM1\"][0])\n            GT.append(header[\"ground_temperature_GT_IM1\"][0])\n            IWYR.append(header[\"year_IWYR\"][0])\n            WLAT.append(header[\"latitude_WLAT\"][0])\n            WLONG.append(header[\"longitude_WLONG\"][0])\n            IWTZN.append(header[\"timezone_IWTZN\"][0])\n            LRECX.append(header[\"record_length_LRECX\"][0])  #not needed\n            NUMDAY.append(header[\"number_days_NUMDAY\"][0]) # not needed\n            IWSOL.append(header[\"solar_flag_IWSOL\"][0])  # not needed recalculated here\n        \n        MDAYS = np.zeros(num_month_in_year+1)\n        MDAYS[1:] = np.array([31,28,31,30,31,30,31,31,30,31,30,31])\n        IDAT = np.zeros(1536+1,dtype=np.int32)\n\n        # record buffer. TODO- find out the exact 4 bytes FORTRAN puts here!\n        IDUM = np.int32(recl)  # Fortran buffers with 4 bytes at the begin and\n                            # end of each record indicating the length in bytes \n                            # of the record.\n        \n        if (IWSZ == 0):\n            raise ValueError(\"IWSZ = 0 does not work in Python because the WEATHER.FMT file does not exist!\")\n        else:\n            IWSOL = np.int32(IWSZ + (IFTYP-1)*2 - 1)\n        \n        count = 0\n        # ARRAYS are zero base! - The fortran is base 1 - watch out!\n        with open(binfilename,'wb',buffering=tot_recl) as file:\n            for IM in range(1,num_month_in_year+1):\n                IDE = np.int32(MDAYS[IM])\n                for ID in range(1,IDE+1):\n                    \n                    IRECXO = np.int32(IM*2 + (ID-1)/16 - 1)\n                    IDXO = np.int32(np.mod(ID-1,16) + 1)\n                    \n                    for IH in range(1,num_hour_in_day+1):\n\n                        KMON = m[count,0]      # Month\n                        KDAY = m[count,1]      # Day\n                        KH = m[count,2]        # Hour\n                        WBT = m[count,3]       # Wet bulb temperature (F)\n                        DBT = m[count,4]       # Dry bulb temperature (F)\n                        PATM = m[count,5]      # Atmospheric Pressure (in Hg)\n                        CLDAMT = m[count,6]    # Cloud amount (0-10)\n                        ISNOW = m[count,7]     # Snow flag (1=snowing)\n                        IRAIN = m[count,8]     # Rainfall flag (1=precipitation happening)\n                        IWNDDR = m[count,9]    # Wind Direction (0 - 15; 0=N, 1=NNE, ETC)\n                        HUMRAT = m[count,10]   # Humidity ratio (lb h2o/lb air)\n                        DENSTY = m[count,11]   # Air density (lb/ft3)\n                        ENTHAL = m[count,12]   # Enthalpy (BTU/LB)\n                        SOLRAD = m[count,13]   # Diffuse solar radiation (BTU/HR-SQFT)\n                        DIRSOL = m[count,14]   # Direct solar radiation ((BTU/HR-SQFT))\n                        ICLDTY = m[count,15]   # Cloud type (0-2)\n                        WNDSPD = m[count,16]   # Wind speed (knots)\n                        \n                        ISOL = np.int32(SOLRAD + .5)\n                        IDN = np.int32(DIRSOL + .5)\n                        IWET = np.int32(WBT+99.5)\n                        IDRY = np.int32(DBT+99.5)\n                        IPRES = np.int32(PATM*10.-149.5)\n                        ICLDAM = np.int32(CLDAMT)\n                        IWNDSP = np.int32(WNDSPD+0.5)\n                        IHUMRT = np.int32(HUMRAT*10000.+0.5)\n                        IDENS = np.int32(DENSTY*1000.-19.5)\n                        IENTH = np.int32(ENTHAL*2.0+60.5)\n                        IP1 = np.int32((IDXO-1)*96 + IH*4 - 3)\n                        IDAT[IP1] = np.int32(IPRES*65536 + IWET*256 + IDRY)\n                        IDAT[IP1+1] = np.int32(ISOL*1048576 + IDN*1024 + \n                                      ICLDAM*64 + ISNOW*32 + IRAIN*16 + IWNDDR) \n                        IDAT[IP1+2] = np.int32(IHUMRT*128 + IDENS)\n                        IDAT[IP1+3] = np.int32(IENTH*2048 + ICLDTY*128 + IWNDSP)\n                        \n                    if ID != 16 and ID != IDE:\n                        pass # keep the loop \n                    else:\n                        # IDUM is the padding written by Fortran that\n                        #   has to be explicitly included here.\n                        byte_arr = struct.pack('i',IDUM)\n                        byte_arr = byte_arr + struct.pack('20s',IWDID[IM-1])\n                        \n                        byte_arr = (byte_arr +\n                                    struct.pack('i',IWYR[IM-1]) +\n                                    struct.pack('f',WLAT[IM-1]) +\n                                    struct.pack('f',WLONG[IM-1]) +\n                                    struct.pack('i',IWTZN[IM-1]) +\n                                    struct.pack('i',IRECXO) +\n                                    struct.pack('i',IDE) +\n                                    struct.pack('f',CLN[IM-1]) +\n                                    struct.pack('f',GT[IM-1]) +\n                                    struct.pack('i',IWSOL)) \n                        byte_arr = byte_arr + b\"\".join([struct.pack('i',i4) for i4 in IDAT[1:]]) \n                        byte_arr = byte_arr + struct.pack('i',IDUM)\n                        \n                        file.write(byte_arr)\n                            \n                            \n                        count += 1\n        return # end of write_doe2_bin     ", "meta": {"hexsha": "755749f845bdb208dd3104724f5e9ea9275d2dd8", "size": 48896, "ext": "py", "lang": "Python", "max_stars_repo_path": "mews/weather/doe2weather.py", "max_stars_repo_name": "sandialabs/MEWS", "max_stars_repo_head_hexsha": "0817022836c5617295a73ccd856b8519ce114bad", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2021-07-07T19:43:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:00:44.000Z", "max_issues_repo_path": "mews/weather/doe2weather.py", "max_issues_repo_name": "sandialabs/MEWS", "max_issues_repo_head_hexsha": "0817022836c5617295a73ccd856b8519ce114bad", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-07-13T21:15:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-14T20:22:39.000Z", "max_forks_repo_path": "mews/weather/doe2weather.py", "max_forks_repo_name": "sandialabs/MEWS", "max_forks_repo_head_hexsha": "0817022836c5617295a73ccd856b8519ce114bad", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.0786627335, "max_line_length": 178, "alphanum_fraction": 0.4714087042, "include": true, "reason": "import numpy,from numpy", "num_tokens": 11862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.18527281427909362}}
{"text": "#!/usr/bin/env python\n#--coding:utf-8 --\n\"\"\"\nplot.py\nPlotting related functions for cLoops2.\n2020-02-25: refine plot bigWig tracks, reduce the figure size by bin the data\n2020-06-24: going to add virtual 4C plot such as https://www.researchgate.net/publication/317638806_Evolutionary_Analysis_of_Candidate_Non-Coding_Elements_Regulating_Neurodevelopmental_Genes_in_Vertebrates/figures?lo=1 \n2020-08-25: adding eigenvector for the plot of heatmap, not available in command line\n2020-08-27: adding genes for the plot of heatmap\n2020-09-03: change line style of bed annotations to recetangle style.\n2020-09-13: refine virtual4C plot\n2020-10-30: adding plotting PETs as arches\n2021-02-04: adding option for not requring heatmps/arches\n2021-02-09: refine some details of code\n2021-09-18: improved parsing speed for plots\n2021-10-20: add a parameter to control PETs number for loops\n\"\"\"\n\n__author__ = \"CAO Yaqiang\"\n__date__ = \"\"\n__modified__ = \"\"\n__email__ = \"caoyaqiang0410@gmail.com\"\n\n#general library\nimport os\nimport json\nimport argparse\nfrom datetime import datetime\nfrom argparse import RawTextHelpFormatter\n\n#3rd library\nimport pyBigWig\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nfrom scipy import sparse\nimport matplotlib as plt\nfrom matplotlib.patches import Arc\nimport matplotlib.ticker as ticker\nimport matplotlib.patches as patches\nfrom sklearn.decomposition import PCA\nfrom matplotlib.ticker import AutoLocator\nfrom matplotlib.colors import ListedColormap\nfrom scipy.ndimage import rotate  #rotate the domain\n\n#cLoops2\nfrom cLoops2.ds import XY, Exon, Gene\nfrom cLoops2.settings import *\nfrom cLoops2.utils import getLogger\nfrom cLoops2.io import parseIxy, parseTxt2Loops\nfrom cLoops2.cmat import getObsMat, getExpMat, get1DSig, getBinMean, getVirtual4CSig\n\n\ndef plotGmmEst(dis, ps, eps, fout):\n    \"\"\"\n    Plot the distribution of distances estimated from the gaussian mixture models. \n    @param dis: numpy.array, distance vector\n    @param ps: numpy.array, classification of points type vector\n    @param eps: int, eps\n    @param fout: str, outpuf pdf file name\n    \"\"\"\n    fig, axs = pylab.subplots(1, 2, figsize=(4, 2.75), sharey=True)\n    #raw PETs\n    sns.kdeplot(dis, ax=axs[0], shade=True, color=colors[2])\n    axs[0].set_ylabel(\"Density\")\n    axs[0].set_title(\"Raw\")\n    #gmm infered PETs\n    nsa = np.where(ps == 0)[0]\n    nsb = np.where(ps == 1)[0]\n    if np.mean(dis[nsa]) > np.mean(\n            dis[nsb]):  #change the order if first classes mean larger\n        nsa, nsb = nsb, nsa\n    sns.kdeplot(dis[nsa],\n                ax=axs[1],\n                shade=True,\n                color=colors[0],\n                label=\"potential peak PETs\")  #colors from the cLoops2.settings\n    sns.kdeplot(dis[nsb],\n                ax=axs[1],\n                shade=True,\n                color=colors[1],\n                label=\"potential loop PETs\")  #colors from the cLoops2.settings\n    axs[1].legend()\n    axs[1].set_title(\"GMM inferred PETs\\nEstimated eps=%s\" % eps)\n    #set common x-label\n    fig.text(0.5, 0.0, \"Distance between two ends (log2,bp)\", ha='center')\n    pylab.tight_layout()\n    pylab.savefig(fout)\n\n\ndef plotKDis(dis, k, fout):\n    \"\"\"\n    Plot the k-distance distribution. \n    @param dis: numpy.array, distance vector\n    @param k: int, k-neighbor\n    @param fout: str, outpuf pdf file name\n    \"\"\"\n    fig, ax = pylab.subplots()\n    x = np.arange(len(dis))\n    #ax.scatter( x,dis,color=colors[0],s=1 )\n    ax.plot(x, dis, color=colors[0])\n    ax.set_xlabel(\"Points sorted by distance\")\n    #ax.set_ylabel(\"%s-NN distance (log2,bp)\" % k)\n    ax.set_ylabel(\"%s-NN distance (log10,bp)\" % k)\n    #ax.set_xscale(\"log\")\n    pylab.tight_layout()\n    pylab.savefig(fout)\n\n\ndef plotKDisE(dis, k, knee, eps, fout):\n    \"\"\"\n    Plot the k-distance distribution, enhanced, if can auto detect the knee.\n    @param dis: numpy.array, distance vector\n    @param k: int, k-neighbor\n    @param knee:int, the knee for the plot, show the vertical line \n    @param eps: float, the log2 transform eps, show the horizontal \n    @param fout: str, outpuf pdf file name\n    \"\"\"\n    fig, ax = pylab.subplots()\n    x = np.arange(len(dis))\n    #ax.scatter( x,dis,color=colors[0],s=1 )\n    ax.plot(x, dis, color=colors[0])\n    ax.set_xlabel(\"Points sorted by distance\")\n    #ax.set_ylabel(\"%s-NN distance (log2,bp)\" % k)\n    ax.set_ylabel(\"%s-NN distance\" % k)\n    ax.axvline(knee, label=\"knee\", linestyle=\"--\", color=colors[1])\n    ax.axhline(eps,\n               label=\"estimated eps:%s bp\" % (int(2**eps)),\n               linestyle=\"--\",\n               color=colors[2])\n    ax.legend()\n    #ax.set_xscale(\"log\")\n    ax.set_xticklabels([])\n    pylab.tight_layout()\n    pylab.savefig(fout)\n\n\ndef plotIntraCut(di, ds, cut, log=True, prefix=\"test\"):\n    \"\"\"\n    Plot the distance cutoff of self-ligation and inter-ligation reads.\n    \"\"\"\n    di = np.abs(np.array(di))\n    ds = np.abs(np.array(ds))\n    di = di[~np.isnan(di)]\n    ds = ds[~np.isnan(ds)]\n    di = di[di > 0]\n    ds = ds[ds > 0]\n    if log:\n        di = np.log2(di)\n        ds = np.log2(ds)\n    fig, ax = pylab.subplots()\n    sns.kdeplot(di,\n                ax=ax,\n                shade=True,\n                label=\"inter-ligation PETs:%s\" % len(di),\n                color=colors[0])\n    sns.kdeplot(ds,\n                ax=ax,\n                shade=True,\n                label=\"self-ligation PETs:%s\" % len(ds),\n                color=colors[1])\n    ax.axvline(np.log2(cut),\n               label=\"distance cutoff:%.2f kb\" % (cut / 1000.0),\n               color=colors[2])\n    leg = ax.legend(loc=\"best\", shadow=True, fancybox=True)\n    ax.set_xlabel(\"Distance between PET ends (log2(bp))\")\n    ax.set_ylabel(\"Density\")\n    pylab.savefig(\"%s.pdf\" % prefix)\n\n\ndef plotEstRes(binSizes, cumBins, singletonRatios, PETsRatio, prefix):\n    \"\"\"\n    Plot the estimation of resolution.\n    \"\"\"\n    fig, ax = pylab.subplots()\n    for i in range(len(binSizes)):\n        ss = cumBins[i]\n        r = singletonRatios[i]\n        tp = int(round(r))\n        pr = PETsRatio[i]\n        ax.plot(ss.index[:tp],\n                ss.values[:tp],\n                color=colors[i],\n                linestyle=\"--\",\n                linewidth=1)\n        ax.plot(ss.index[tp:],\n                ss.values[tp:],\n                label=\"%s: %.2f %% bins %.2f %% PETs\" %\n                (binSizes[i], 100 - r, 100 - pr),\n                color=colors[i],\n                linewidth=2)\n    ax.plot([0, 100], [0, 100], color=\"k\", label=\"random\")\n    ax.set_xlim([0, 100])\n    ax.set_ylim([0, 100])\n    ax.legend(fontsize=6, fancybox=False, frameon=False)\n    ax.set_xlabel(\"Percentage of contact matrix bins\")\n    ax.set_ylabel(\"Percentage of PETs\")\n    pylab.savefig(\"%s_estRes.pdf\" % prefix)\n\n\ndef plotEstSat(binSizes, totPETs, data, tol, prefix):\n    \"\"\"\n    Plot the estimation of sequencing signal saturation.\n    \"\"\"\n    fig, ax = pylab.subplots()\n    for i in range(len(binSizes)):\n        d = data[i]\n        xs = d.index\n        ys = d.mean(axis=1)\n        std = d.std(axis=1)\n        ax.errorbar(xs,\n                    ys,\n                    yerr=std,\n                    capsize=3,\n                    linewidth=1,\n                    elinewidth=1,\n                    color=colors[i],\n                    label=\"resolution:%s\" % binSizes[i])\n        #ax.set_xticks(xs)\n    ax.legend()\n    ax.set_title(\"total PETs:%s M\" % (totPETs / 10**6))\n    ax.set_xlabel(\"Sub-sampling ratio\")\n    ax.set_ylabel(\"Detected contact matrix bins ratio (>=%sPETs)\" % tol)\n    pylab.savefig(\"%s_estSat.pdf\" % prefix)\n\n\ndef plotCorrScatterPCC(mat, fout):\n    \"\"\"\n    Density scatter plot for two samples correlation\n    \"\"\"\n    fig, ax = pylab.subplots()\n    cmap = sns.light_palette(\"red\", n_colors=9).as_hex()\n    cmap[0] = \"#FFFFFF\"\n    cmap = ListedColormap(cmap)\n    #cmap = sns.cubehelix_palette(light=1, as_cmap=True)\n    #print(type(cmap))\n    da = mat.columns[0]\n    db = mat.columns[1]\n    sa = mat[da]\n    sb = mat[db]\n    corr = sa.corr(sb)\n    hb = ax.hexbin(sa + 1,\n                   sb + 1,\n                   gridsize=100,\n                   cmap=cmap,\n                   bins=\"log\",\n                   xscale=\"log\",\n                   yscale=\"log\")\n    cb = fig.colorbar(hb, ax=ax)\n    cb.set_label('log10(N), number of points')\n    ax.set_title(\"vector size:%s\\nPCC:%.3f\" % (len(sa), corr))\n    #ax.set_xlabel(da + \",log10(PET+1)\")\n    #ax.set_ylabel(db + \",log10(PET+1)\")\n    ax.set_xlabel(da)\n    ax.set_ylabel(db)\n    pylab.savefig(\"%s\" % fout)\n\n\ndef plotCorrScatterPCA(mat, fout):\n    \"\"\"\n    Density scatter plot for two samples correlation\n    \"\"\"\n    fig, ax = pylab.subplots()\n    cmap = sns.light_palette(\"red\", n_colors=9).as_hex()\n    cmap[0] = \"#FFFFFF\"\n    cmap = ListedColormap(cmap)\n    da = mat.columns[0]\n    db = mat.columns[1]\n    sa = mat[da]\n    sb = mat[db]\n    corr = sa.corr(sb)\n    hb = ax.hexbin(\n        sa,\n        sb,\n        gridsize=100,\n        cmap=cmap,\n        bins=\"log\",\n    )\n    cb = fig.colorbar(hb, ax=ax)\n    cb.set_label('log10(N), number of points')\n    ax.set_title(\"vector size:%s\\nPCC:%.3f\" % (len(sa), corr))\n    ax.set_xlabel(da + \", top PCs\")\n    ax.set_ylabel(db + \", top PCs\")\n    pylab.savefig(\"%s\" % fout)\n\n\ndef plotCorrHeatmap(mat, fout):\n    \"\"\"\n    Correlation heatmap plot for two samples correlation.\n    \"\"\"\n    #fig, ax = pylab.subplots(\n    cmap = sns.diverging_palette(250, 15, s=75, l=40, n=11).as_hex()\n    cmap[int(len(cmap) / 2)] = \"#FFFFFF\"\n    cmap = ListedColormap(cmap)\n    g = sns.clustermap(\n        mat,\n        xticklabels=False,\n        yticklabels=True,\n        square=True,\n        center=0,\n        linewidths=0.0,\n        cmap=cmap,\n        figsize=(0.5 * mat.shape[1], 0.5 * mat.shape[1]),\n        annot=True,\n        fmt=\".3f\",\n        annot_kws={\n            \"size\": \"3\",\n            'label': \"PCC\",\n        },\n    )\n    pylab.setp(g.ax_heatmap.yaxis.get_majorticklabels(), rotation=0)\n    pylab.savefig(fout)\n\n\ndef getBedRegion(f, chrom, start, end):\n    \"\"\"\n    Get the target region in bed file.\n    \"\"\"\n    rs = []\n    for line in open(f):\n        line = line.split(\"\\n\")[0].split(\"\\t\")\n        if len(line) < 3:\n            continue\n        try:\n            c = line[0]\n            s = int(line[1])\n            e = int(line[2])\n        except:\n            continue\n        if c != chrom:\n            continue\n        if s >= start and e <= end:\n            rs.append([s, e])\n    return rs\n\n\ndef parseGtf(line):\n    \"\"\"\n    Parse gene gtf line.\n    \"\"\"\n    e = Exon()\n    e.chrom = line[0]\n    e.start = int(line[3])\n    e.end = int(line[4])\n    e.length = e.end - e.start\n    e.strand = line[6]\n    attr = line[8].replace('\"', '').split(\";\")\n    ts = {}\n    for t in attr:\n        t = t.split()\n        if len(t) != 2:\n            continue\n        ts[t[0]] = t[1]\n    e.name = ts[\"gene_name\"]\n    e.id = ts[\"gene_id\"]\n    return e\n\n\ndef stichExons(exons, margin=1):\n    \"\"\"\n    Stich close exons based on postion array. \n    \"\"\"\n    cov = set()\n    for i, exon in enumerate(exons):\n        cov.update(range(exon.start, exon.end + 1))\n    cov = list(cov)\n    cov.sort()\n    nexons = []\n    i = 0\n    while i < len(cov) - 1:\n        for j in range(i + 1, len(cov)):\n            if cov[j] - cov[j - 1] > margin:\n                break\n            else:\n                continue\n        exon = exons[0].chrom\n        exon = Exon()\n        exon.chrom = exons[0].chrom\n        exon.start = cov[i]\n        exon.end = cov[j - 1]\n        exon.strand = exons[0].strand\n        exon.length = cov[j - 1] - cov[i] + 1\n        exon.id = exons[0].id\n        exon.name = exons[0].name\n        nexons.append(exon)\n        i = j  #update search start\n    return nexons\n\n\ndef getGenes(f, chrom, start, end):\n    \"\"\"\n    Get the target gene in the gtf file.\n    \"\"\"\n    gs = {}\n    for line in open(f):\n        if line.startswith(\"#\"):\n            continue\n        line = line.split(\"\\n\")[0].split(\"\\t\")\n        if line[0] != chrom:\n            continue\n        if line[2] != \"exon\":\n            continue\n        e = parseGtf(line)\n        if e.name not in gs:\n            g = Gene()\n            g.chrom = e.chrom\n            g.start = e.start\n            g.end = e.end\n            g.strand = e.strand\n            g.name = e.name\n            g.id = e.id\n            g.exons = {(e.start, e.end): e}\n            gs[g.name] = g\n        else:\n            #same position exons\n            if (e.start, e.end) in gs[e.name].exons:\n                continue\n            else:\n                g = gs[e.name]\n                if e.start < g.start:\n                    g.start = e.start\n                if e.end > g.end:\n                    g.end = e.end\n                g.exons[(e.start, e.end)] = e\n    #select genes in the target region\n    ngs = {}\n    for n, g in gs.items():\n        if (g.start >= start and g.start <= end ) or ( g.end >=start and g.end <=end ):\n            g.exons = stichExons(list(g.exons.values()))\n            ngs[n] = g\n    return ngs\n\n\ndef parseBwvs(bws, bwvs=\"\"):\n    \"\"\"\n    Parse input bigwig values limts.\n    \"\"\"\n    if bwvs == \"\":\n        bwvs = []\n        for i in range(len(bws)):\n            bwvs.append([None, None])\n    else:\n        bwvs = bwvs.split(\";\")\n        nbwvs = []\n        for t in bwvs:\n            if t == \"\":\n                nbwvs.append([None, None])\n            else:\n                t = t.split(\",\")\n                t = list(map(float, t))\n                t.sort()\n                nbwvs.append(t)\n        bwvs = nbwvs\n    return bwvs\n\n\ndef plotGene(ax, n, g, start, end, space=0.02,lencut=1000):\n    \"\"\"\n    Plot one genes.\n    @param ax: maplotlib ax\n    @param n: str, gene name\n    @param g: cLoops2:ds:Gene object\n    @param start: int, start region for plotting\n    @param end: int, end region for plotting\n    @param space: float, name and gene distance releative\n    \"\"\"\n    ax.axis(\"off\")\n    #ax.set_xlim([start, end])\n    ax.set_ylim([0, 1])\n    #plot intron as line, exon as block\n    for i, exon in enumerate(g.exons):\n        c = \"k\"\n        if g.strand == \"+\" and i == 0:\n            c = colors[1]\n        if g.strand == \"-\" and i == len(g.exons) - 1:\n            c = colors[3]\n        p = patches.Rectangle((exon.start, 0.1),\n                              exon.end - exon.start,\n                              0.8,\n                              fill=True,\n                              color=c,\n                              alpha=1)\n        ax.add_patch(p)\n        if i > 0:\n            ax.plot([g.exons[i - 1].end, exon.start], [0.5, 0.5],\n                    color=\"gray\",\n                    linewidth=0.5,\n                    linestyle=\"--\")\n    #plot direction and name\n    if len(g.exons) > 1:\n        if g.strand == \"+\":\n            #c = \"green\"\n            c = colors[1]\n            ax.plot([g.exons[0].end, g.exons[1].start], [0.5, 0.5],\n                    color=c,\n                    linewidth=1,\n                    linestyle=\"-\")\n            p = g.exons[0].start - (end - start) * (space * 2)\n            if p < start:\n                p = start\n            if p > end:\n                p = end\n            ax.text(p, 0.15, n, color=c, fontsize=5)\n        else:\n            c = colors[3]\n            ax.plot([g.exons[-2].end, g.exons[-1].start], [0.5, 0.5],\n                    color=c,\n                    linewidth=1,\n                    linestyle=\"-\")\n            p = g.exons[-1].end + (end - start) * space\n            if p < start:\n                p = start\n            if p > end:\n                p = end\n            ax.text(p, 0.15, n, color=c, fontsize=5)\n    else:\n        if g.strand == \"+\":\n            c = colors[1]\n            p = g.exons[0].start - (end - start) * (space * 2)\n            if p < start:\n                p = start\n            if p > end:\n                p = end\n            ax.text(p, 0.15, n, color=c, fontsize=5,style=\"italic\")\n        else:\n            c = colors[3]\n            p = g.exons[-1].end + (end - start) * space\n            if p < start:\n                p = start\n            if p > end:\n                p = end\n            ax.text(p, 0.15, n, color=c, fontsize=5,style=\"italic\")\n    if end - start > lencut:\n        nend = start + int( (end-start)/lencut ) * lencut\n        ax.set_xlim([start,nend])\n    else: \n        ax.set_xlim([start, end])\n    return ax\n\n\ndef plotCoverage(ax, ys, colori=1, label=\"\", vmin=None, vmax=None,\n                 lencut=1000):\n    \"\"\"\n    Plot 1D coverage data.\n    @param ax: matplotlib ax\n    @param ys: numpy.array, y-axis coverages\n    @param colori: int, color index\n    @param label: str, name/label for the data\n    @param vmin: float, y-axis vmin\n    @param vmax: float, y-axis vmax\n    @param lencut: int, if the vector of xs/ys is too long, short them by bin averages\n    @return ax: matplotlib ax\n    \"\"\"\n    if len(ys) > lencut:\n        ys = getBinMean(ys, lencut)\n    xs = np.arange(len(ys))\n    ax.plot(xs, ys, color=colors[colori], label=label, linewidth=0)\n    ax.fill_between(np.arange(len(ys)), 0, ys, color=colors[colori], alpha=0.8)\n    ax.set_xticklabels([])\n    ax.set_xlim([np.min(xs), np.max(xs)])\n    #set y-axis lim\n    if vmin is None:\n        vmin = np.min(ys)\n    if vmax is None:\n        vmax = np.max(ys)\n    vmin = float(\"%.3f\"%vmin)\n    vmax = float(\"%.3f\"%vmax)\n    p = (vmax - vmin) * 0.15\n    ax.set_yticks([vmin, vmax - p])\n    ax.set_yticklabels([str(vmin), str(vmax)])\n    ax.set_ylim([vmin,vmax])\n    ax.tick_params(axis='both', which='major', labelsize=4)\n    ax.legend(fontsize=6, fancybox=False, frameon=False)\n    return ax\n\n\ndef plotRegion(ax, rs, start, end, colori=1, lencut=1000, label=\"\"):\n    \"\"\"\n    Plot genomic region.\n    @param ax: matplotlib ax\n    @param rs: [start,end], both start and end are ints\n    @param colori: int, color index\n    @param label: str, name/label for the data\n    \"\"\"\n    for r in rs:\n        p = patches.Rectangle((r[0], 0.2),\n                              r[1] - r[0],\n                              0.6,\n                              fill=True,\n                             color=colors[colori],\n                              alpha=0.8)\n        ax.add_patch(p)\n    ax.set_ylim([0, 1])\n    ax.text((start + end) / 2, 0.2, label, fontsize=6)\n    ax.axis(\"off\")\n    if end - start > lencut:\n        nend = start + int( (end-start)/lencut ) * lencut\n        ax.set_xlim([start,nend])\n    else: \n        ax.set_xlim([start, end])\n    return ax\n\n\ndef plotLoops(ax, loops, nchrom, start, end,xy2=None,loopCut=0):\n    \"\"\"\n    Plot loops as arches\n    \"\"\"\n    cabs = []\n    nloops = []\n    for loop in loops[nchrom]:\n        s = min(loop.x_start, loop.y_start)\n        e = max(loop.x_end, loop.y_end)\n        if start < s and e < end:\n            #query from the data for number of PETs\n            if xy2 is not None:\n                ca, cb, cab = xy2.queryLoop(loop.x_start, loop.x_end,\n                                        loop.y_start, loop.y_end)\n            else:\n                cab = [1]\n            if loopCut > 0 and len(cab) < loopCut:\n                continue\n            nloops.append(loop)\n            cabs.append(len(cab))\n    #start plot\n    ncabs = [c for c in cabs if c > 0]\n    if len(ncabs) > 0:\n        minCab = np.min(ncabs)\n        #modify line width for arches , just in case the line too wide\n        lws = [c / minCab for c in cabs]\n        if max(lws) > 10:\n            lws = [1] * len(lws)\n        #lws = [1] * len(lws)\n        pa = 0\n        pb = 1.0\n        ymax = 0\n        for i, loop in enumerate(nloops):\n            ca = (loop.x_start + loop.x_end) / 2\n            cb = (loop.y_start + loop.y_end) / 2\n            cc = (ca + cb) / 2\n            npa = float(ca - start) / (end - start) * (pb - pa)\n            npb = float(cb - start) / (end - start) * (pb - pa)\n            npc = float(cc - start) / (end - start) * (pb - pa)\n            a = npb - npa  #a is x axis size for eclipse\n            b = a / 2  #b is y axis size for eclipse\n            if b > ymax:\n                ymax = b\n            if cabs[i] < 1:\n                continue\n            ax.add_patch(\n                Arc(\n                    (npc, 0),\n                    a,\n                    b,\n                    theta1=0,\n                    theta2=180,\n                    edgecolor=colors[1],\n                    lw=lws[i],\n                ))\n            if xy2 is not None:\n                ax.text(npc, b / 2, cabs[i], fontsize=5)\n        ax.set_xlim([0, 1])\n        ax.set_ylim([0, ymax * 0.6])\n    ax.set_yticklabels([])\n    ax.set_xticklabels([])\n    return ax\n\n\ndef plotMatHeatmap(\n        f,\n        fo,\n        start=0,\n        end=-1,\n        res=5000,\n        cut=0,\n        mcut=-1,\n        log=False,\n        method=\"obs\",\n        oneD=False,\n        oneDv=\"\",\n        corr=False,\n        triu=False,\n        norm=False,\n        bws=[],\n        bwvs=\"\",\n        bwcs=\"\",\n        beds=[],\n        loops=None,\n        loopCut=0,\n        domains=\"\",\n        eig=False,\n        eig_r=False,\n        gtf=\"\",\n        virtual4C=False,\n        viewStart=-1,\n        viewEnd=-1,\n        viewV=\"\",\n        vmin=None,\n        vmax=None,\n        width=4,\n):\n    \"\"\"\n    Plot the contact matrix heatmap with 1D tracks or 2D annotations\n    \"\"\"\n    \n    #prepare data\n    chrom, xy = parseIxy(f, cut=cut, mcut=mcut)\n    if start == 0:\n        start = np.min(xy)\n    if end == -1:\n        end = np.max(xy)\n    ps = np.where((xy[:, 0] >= start) & (xy[:, 1] <= end))[0]\n    xy = xy[ps, ]\n    xy2 = XY(xy[:, 0], xy[:, 1])  #XY object\n\n    mat = getObsMat(xy, start, end, res)\n    bgmat = None\n    if method == \"obs/exp\":\n        bgmat = getExpMat(xy, mat.shape, start, end, res)\n    if log:\n        if bgmat is None:\n            ano = \"log10(Obs)\"\n            mat = np.log10(mat + 1)\n        else:\n            ano = \"log10(Obs/Exp)\"\n            mat = np.log10(mat + 1) - np.log10(bgmat + 1)\n    else:\n        if bgmat is not None:\n            mat = (mat + 1) / (bgmat + 1)\n            ano = \"Obs/Exp\"\n        else:\n            ano = \"Obs\"\n    if corr:\n        ano = ano + \" correlation\"\n        mat = np.corrcoef(mat)\n        mat = np.nan_to_num(mat)\n    if norm:\n        #diag = np.diag(np.diagonal(mat))\n        #mat = mat - diag\n        m = np.mean(mat)\n        s = np.std(mat)\n        mat = (mat - m) / s\n        ano = ano + \" z-socore normalized\"\n    if oneD:\n        predir = os.path.dirname(os.path.realpath(f))\n        metaf = predir + \"/petMeta.json\"\n        meta = json.loads(open(metaf).read())\n        total = meta[\"Unique PETs\"] * 2\n        sig = get1DSig(xy2, start, end)\n        sig = sig / total * 10**6\n    if eig:\n        nmat = np.sum(mat, axis=0).astype(\"int\")\n        ps = np.where(nmat == 0)[0]\n        cmat = np.corrcoef(mat)\n        cmat = np.nan_to_num(cmat)\n        pca = PCA(n_components=1)\n        mat_r = pca.fit(cmat).transform(cmat)\n        eigs = np.array([t[0] for t in mat_r])\n        eigs[ps] = 0\n        if eig_r:  #flip the PC1 values according to other data such as histone markers\n            eigs = 0 - eigs\n    if virtual4C:\n        predir = os.path.dirname(os.path.realpath(f))\n        metaf = predir + \"/petMeta.json\"\n        meta = json.loads(open(metaf).read())\n        virtual4Csig = getVirtual4CSig(xy2, start, end, viewStart, viewEnd)\n    if triu:\n        mat = rotate(mat, angle=45, reshape=True)\n        #take the uppper matrix and remove padding zeros\n        to = int(mat.shape[0] / 2)\n        mat = mat[to:, ]\n        if norm == False:\n            ns = list(range(mat.shape[0]))\n            ns.reverse()\n            for n in ns:\n                if np.sum(mat[n, ]) > 0:\n                    break\n            mat = mat[:n, ]\n\n            ns = list(range(mat.shape[1]))\n            for na in ns:\n                if np.sum(mat[:, na]) > 0:\n                    break\n            ns.reverse()\n            for nb in ns:\n                if np.sum(mat[:, nb]) > 0:\n                    break\n            mat = mat[:, na:nb + 1]\n    #figure helights\n    if triu:\n        initSize = 3\n        square = False\n    else:\n        initSize = 4\n        square = False\n    hights = initSize\n    #heights ratio\n    hr = []\n    if gtf != \"\":\n        genes = getGenes(gtf, chrom[0], start, end)\n        \"\"\"\n        if len(genes) > 20:\n            print(\n                \"More than 20 genes in the target region, only plot random 20.\"\n            )\n            ns = list(genes.keys())[:20]\n            ng = {}\n            for n in ns:\n                ng[n] = genes[n]\n            genes = ng\n        \"\"\"\n        hights += len(genes) * 0.1\n        hr.extend([0.1] * len(genes))\n    if len(bws) > 0:\n        hights += len(bws) * 0.5\n        hr.extend([1] * len(bws))\n    if oneD:\n        hights += 0.5\n        hr.append(1)\n    if eig:\n        hights += 0.5\n        hr.append(1)\n    if virtual4C:\n        hights += 0.5\n        hr.append(1)\n    if loops is not None:\n        hights += 0.5\n        hr.append(1)\n    if len(beds) > 0:\n        hights += len(beds) * 0.2\n        hr.extend([0.2] * len(beds))\n    #heatmap and colorbar\n    if triu:\n        hr.extend([3, 0.1])\n    else:\n        hr.extend([6, 0.1])\n\n    #prepare figure\n    fig = pylab.figure(figsize=(width, hights))\n    gs = mpl.gridspec.GridSpec(len(hr),\n                               1,\n                               height_ratios=hr,\n                               top=0.95,\n                               bottom=0.05,\n                               left=0.1,\n                               right=0.9,\n                               wspace=0.05)\n    pylab.suptitle(\n        \"%.2f kb,%s kb resolution, %s:%s-%s\" %\n        (float(end - start) / 1000.0, res / 1000.0, chrom[0], start, end),\n        fontsize=8)\n    axi = -1\n\n    #plot gene\n    if gtf != \"\":\n        for n, g in genes.items():\n            axi += 1\n            ax = fig.add_subplot(gs[axi])\n            plotGene(ax, n, g, start, end)\n\n    #plot bigWig\n    #prepare y-axis limitations\n    bwvs = parseBwvs(bws, bwvs)\n    #colors\n    if bwcs == \"\":\n        bwcs = range(len(bws))\n    else:\n        bwcs = list(map(int, bwcs.split(\",\")))\n    for i, bw in enumerate(bws):\n        axi += 1\n        ax = fig.add_subplot(gs[axi])\n        name = bw.split(\"/\")[-1].split(\".bw\")[0]\n        bw = pyBigWig.open(bw)\n        ys = bw.values(chrom[0], start, end)\n        ys = np.nan_to_num(ys)\n        plotCoverage(ax,\n                     ys,\n                     colori=bwcs[i],\n                     label=name,\n                     vmin=bwvs[i][0],\n                     vmax=bwvs[i][1])\n\n    #plot 1D signal\n    if oneD:\n        axi += 1\n        ax = fig.add_subplot(gs[axi])\n        if oneDv != \"\":\n            oneDv = list(map(float, oneDv.split(\",\")))\n        else:\n            oneDv = [None, None]\n        plotCoverage(ax,\n                     sig,\n                     colori=3,\n                     label=\"1D signal\",\n                     vmin=oneDv[0],\n                     vmax=oneDv[1])\n\n    #plot eigenvector\n    if eig:\n        axi += 1\n        ax = fig.add_subplot(gs[axi])\n        xs = np.arange(len(eigs))\n        minxs = np.min(xs)\n        maxns = np.max(xs)\n        #ps = np.where( eigs!=0)[0]\n        #eigs = eigs[ps]\n        #xs = xs[ps]\n        ps = np.where(eigs > 0)\n        peigs = eigs[ps]\n        pxs = xs[ps]\n        ax.bar(pxs, peigs, color=colors[0], edgecolor=colors[0], alpha=0.5)\n        ns = np.where(eigs < 0)\n        neigs = eigs[ns]\n        nxs = xs[ns]\n        ax.bar(nxs, neigs, color=colors[1], edgecolor=colors[1], alpha=0.5)\n        ax.plot(xs, [0] * len(xs), color=\"gray\", alpha=0.8, linestyle=\"--\")\n        ax.tick_params(axis='both', which='major', labelsize=4)\n        ax.set_xticklabels([])\n        ax.set_xlim([minxs, maxns])\n        ax.set_ylabel(\"eigenvector\")\n\n    #plot view point, virtual 4C plot\n    if virtual4C:\n        axi += 1\n        ax = fig.add_subplot(gs[axi])\n        if viewV != \"\":\n            viewV = list(map(float, viewV.split(\",\")))\n        else:\n            viewV = [None, None]\n        if len(virtual4Csig) > 1000:\n            virtual4Csig = getBinMean(virtual4Csig, 1000)\n        #log2 is nesscessary\n        virtual4Csig = np.log2(virtual4Csig + 1)\n        ax = plotCoverage(ax,\n                     virtual4Csig,\n                     colori=0,\n                     label=\"virtual 4C signal\",\n                     vmin=viewV[0],\n                     vmax=viewV[1],\n        )\n        ax.set_ylabel(\"log2(counts)\", fontsize=6)\n        \n    #plot loops as arches\n    nchrom = \"-\".join(chrom)\n    if loops is not None and nchrom in loops and len(loops[nchrom]) > 0:\n        axi += 1\n        ax = fig.add_subplot(gs[axi])\n        #plot the arch and annotate the PETs support the loop\n        plotLoops(ax, loops, nchrom,start,end,xy2=xy2,loopCut=loopCut)\n        \n    #plot genomic features\n    for i, bed in enumerate(beds):\n        axi += 1\n        name = bed.split(\"/\")[-1].split(\".bed\")[0]\n        ax = fig.add_subplot(gs[axi])\n        rs = getBedRegion(bed, chrom[0], start, end)\n        plotRegion(ax, rs, start, end, i, label=name)\n\n    #plot the heatmap\n    ax = fig.add_subplot(gs[-2])\n    cax = fig.add_subplot(gs[-1])\n    sns.set(font_scale=0.5)\n    if corr:\n        cmap = sns.diverging_palette(250, 15, s=75, l=40, n=11).as_hex()\n        cmap[int(len(cmap) / 2)] = \"#FFFFFF\"\n        cmap = ListedColormap(cmap)\n        ax = sns.heatmap(mat,\n                         xticklabels=False,\n                         yticklabels=False,\n                         square=square,\n                         center=0,\n                         linewidths=0.0,\n                         ax=ax,\n                         cmap=cmap,\n                         cbar_ax=cax,\n                         cbar_kws={\n                             'label': ano,\n                             'orientation': 'horizontal',\n                             \"shrink\": 0.5,\n                             \"fraction\": 0.2,\n                             \"anchor\": (0.0, 1.0)\n                         })\n\n    else:\n        if norm == False:\n            #cmap = sns.cubehelix_palette(n_colors=11, as_cmap=True, light=1, hue=3)\n            cmap = sns.light_palette(\"red\", n_colors=9).as_hex()\n            #cmap = plt.cm.Reds\n            cmap[0] = \"#FFFFFF\"\n            cmap = ListedColormap(cmap)\n            center = None\n            if vmin is None:\n                vmin = 0\n            vmax = vmax\n        else:\n            cmap = sns.color_palette(\"RdBu_r\", 11).as_hex()\n            cmap[int(len(cmap) / 2)] = \"#FFFFFF\"\n            cmap = ListedColormap(cmap)\n            center = 0\n        ax = sns.heatmap(mat,\n                         xticklabels=False,\n                         yticklabels=False,\n                         linewidths=0.0,\n                         square=square,\n                         center=center,\n                         cmap=cmap,\n                         vmin=vmin,\n                         vmax=vmax,\n                         ax=ax,\n                         cbar_ax=cax,\n                         cbar_kws={\n                             'label': ano,\n                             'orientation': 'horizontal',\n                             \"shrink\": 0.3,\n                             \"fraction\": 0.2,\n                             \"anchor\": (0.0, 1.0)\n                         })\n    cax.tick_params(labelsize=4)\n\n    #on the heatmap, draw the highlight region, such as TADs\n    if domains != \"\":\n        rs = getBedRegion(domains, chrom[0], start, end)\n        if len(rs) > 0:\n            pa = int(ax.get_xlim()[0])\n            pb = int(ax.get_xlim()[1])\n            if pa > pb:\n                pa, pb = pb, pa\n            ypa = int(ax.get_ylim()[0])\n            ypb = int(ax.get_ylim()[1])\n            if ypa > ypb:\n                ypa, ypb = ypb, ypa\n            for r in rs:\n                npa = (r[0] - start) / (end - start)\n                npb = (r[1] - start) / (end - start)\n                if triu:\n                    xa = npa * (pb - pa)\n                    xb = npb * (pb - pa)\n                    ya = npa * (ypb - ypa)\n                    yb = npb * (ypb - ypa)\n                    ax.plot([xa, (xa + xb) / 2, xb], [ypa, (yb - ya), ypa],\n                            color=colors[1],\n                            linewidth=1,\n                            linestyle=\"--\")\n                else:\n                    ax.axvline(x=npa * (pb - pa),\n                               ymin=1 - npa,\n                               ymax=1 - npb,\n                               color=colors[1],\n                               linewidth=1,\n                               linestyle=\"--\")\n                    ax.axvline(x=npb * (pb - pa),\n                               ymin=1 - npa,\n                               ymax=1 - npb,\n                               color=colors[1],\n                               linewidth=1,\n                               linestyle=\"--\")\n                    ax.axhline(y=npa * (pb - pa),\n                               xmin=npa,\n                               xmax=npb,\n                               color=colors[1],\n                               linewidth=1,\n                               linestyle=\"--\")\n                    ax.axhline(y=npb * (pb - pa),\n                               xmin=npa,\n                               xmax=npb,\n                               color=colors[1],\n                               linewidth=1,\n                               linestyle=\"--\")\n    #draw the box\n    ax.axvline(x=ax.get_xlim()[0], color=\"k\", linewidth=2)\n    ax.axvline(x=ax.get_xlim()[1], color=\"k\", linewidth=2)\n    ax.axhline(y=ax.get_ylim()[0], color=\"k\", linewidth=2)\n    ax.axhline(y=ax.get_ylim()[1], color=\"k\", linewidth=2)\n    if not triu:\n        pylab.tight_layout()\n    pylab.savefig(fo + \"_matrix.pdf\")\n\n\ndef plotPETsArches(\n        f,\n        fo,\n        start=0,\n        end=-1,\n        cut=0,\n        mcut=-1,\n        oneD=False,\n        oneDv=\"\",\n        bws=[],\n        bwvs=\"\",\n        bwcs=\"\",\n        beds=[],\n        loops=None,\n        loopCut=0,\n        gtf=\"\",\n        aw=1,\n        ac=1,\n        aa=1,\n        width=4,\n):\n    \"\"\"\n    Plot the interacting PETs as arches, showing the raw data. \n    \"\"\"\n    #prepare data\n    chrom, xy = parseIxy(f, cut=cut, mcut=mcut)\n    if start == 0:\n        start = np.min(xy)\n    if end == -1:\n        end = np.max(xy)\n    ps = np.where((xy[:, 0] >= start) & (xy[:, 1] <= end))[0]\n    xy = xy[ps, ]\n    xy2 = XY(xy[:, 0], xy[:, 1])  #XY object\n\n    if oneD:\n        predir = os.path.dirname(os.path.realpath(f))\n        metaf = predir + \"/petMeta.json\"\n        meta = json.loads(open(metaf).read())\n        total = meta[\"Unique PETs\"] * 2\n        sig = get1DSig(xy2, start, end)\n        sig = sig / total * 10**6\n    hights = 0\n    #heights ratio\n    hr = []\n    if gtf != \"\":\n        genes = getGenes(gtf, chrom[0], start, end)\n        \"\"\"\n        if len(genes) > 20:\n            print(\n                \"More than 20 genes in the target region, only plot random 20.\"\n            )\n            ns = list(genes.keys())[:20]\n            ng = {}\n            for n in ns:\n                ng[n] = genes[n]\n            genes = ng\n        \"\"\"\n        hights += len(genes) * 0.1\n        hr.extend([0.1] * len(genes))\n    if len(bws) > 0:\n        hights += len(bws) * 0.5\n        hr.extend([1] * len(bws))\n    if oneD:\n        hights += 0.5\n        hr.append(1)\n    if loops is not None:\n        hights += 0.5\n        hr.append(1)\n    if len(beds) > 0:\n        hights += len(beds) * 0.2\n        hr.extend([0.2] * len(beds))\n    #arches\n    hights += 2\n    hr.append(2.5)\n\n    #prepare figure\n    fig = pylab.figure(figsize=(width, hights))\n    gs = mpl.gridspec.GridSpec(len(hr),\n                               1,\n                               height_ratios=hr,\n                               top=0.9,\n                               bottom=0.05,\n                               left=0.1,\n                               right=0.9,\n                               wspace=0.05)\n    pylab.suptitle(\"%.2f kb,%s:%s-%s\" %\n                   (float(end - start) / 1000.0, chrom[0], start, end),\n                   fontsize=8)\n    axi = -1\n\n    #plot gene\n    if gtf != \"\":\n        for n, g in genes.items():\n            axi += 1\n            ax = fig.add_subplot(gs[axi])\n            plotGene(ax, n, g, start, end)\n\n    #plot bigWig\n    #yaxis limitaitons\n    bwvs = parseBwvs(bws, bwvs)\n    #colors\n    if bwcs == \"\":\n        bwcs = range(len(bws))\n    else:\n        bwcs = list(map(int, bwcs.split(\",\")))\n    for i, bw in enumerate(bws):\n        axi += 1\n        ax = fig.add_subplot(gs[axi])\n        name = bw.split(\"/\")[-1].split(\".bw\")[0]\n        bw = pyBigWig.open(bw)\n        ys = bw.values(chrom[0], start, end)\n        ys = np.nan_to_num(ys)\n        plotCoverage(ax,\n                     ys,\n                     colori=bwcs[i],\n                     label=name,\n                     vmin=bwvs[i][0],\n                     vmax=bwvs[i][1])\n\n    #plot 1D signal\n    if oneD:\n        axi += 1\n        ax = fig.add_subplot(gs[axi])\n        if oneDv != \"\":\n            oneDv = list(map(float, oneDv.split(\",\")))\n        else:\n            oneDv = [None, None]\n        plotCoverage(ax,\n                     sig,\n                     colori=3,\n                     label=\"1D signal\",\n                     vmin=oneDv[0],\n                     vmax=oneDv[1])\n\n    #plot loops as arches\n    nchrom = \"-\".join(chrom)\n    if loops is not None and nchrom in loops and len(loops[nchrom]) > 0:\n        axi += 1\n        ax = fig.add_subplot(gs[axi])\n        #plot the arch and annotate the PETs support the loop\n        #get the minal PETs number as linewidth 1,others are fold\n        plotLoops(ax, loops, nchrom,start,end,xy2=xy2,loopCut=loopCut)\n       \n    #plot genomic features\n    for i, bed in enumerate(beds):\n        axi += 1\n        name = bed.split(\"/\")[-1].split(\".bed\")[0]\n        ax = fig.add_subplot(gs[axi])\n        rs = getBedRegion(bed, chrom[0], start, end)\n        plotRegion(ax, rs, start, end, i, label=name)\n\n    #plot PETs as arches\n    axi += 1\n    ax = fig.add_subplot(gs[axi])\n    ps = xy2.queryPeakBoth(start, end)\n    pa = 0\n    pb = 1.0\n    if len(ps) > 0:\n        ymax = 0\n        for p in ps:\n            ca = xy[p, 0]\n            cb = xy[p, 1]\n            cc = (ca + cb) / 2\n            npa = float(ca - start) / (end - start) * (pb - pa)\n            npb = float(cb - start) / (end - start) * (pb - pa)\n            npc = float(cc - start) / (end - start) * (pb - pa)\n            a = npb - npa  #a is x axis size for eclipse\n            b = a / 2 * 0.6  #b is y axis size for eclipse\n            if b > ymax:\n                ymax = b\n            ax.add_patch(\n                Arc(\n                    (npc, 0),\n                    a,\n                    b,\n                    theta1=180,\n                    theta2=360,\n                    edgecolor=colors[ac],\n                    lw=aw,\n                    alpha=aa,\n                ))\n        ax.set_xticks([])\n        ax.set_yticks([])\n        ax.set_xlim([0, 1])\n        ax.set_ylim([0, -ymax * 0.55])\n        ax.invert_yaxis()\n    pylab.savefig(fo + \"_arches.pdf\")\n\n\ndef plotPETsScatter(\n        f,\n        fo,\n        start=0,\n        end=-1,\n        cut=0,\n        mcut=-1,\n        oneD=False,\n        oneDv=\"\",\n        bws=[],\n        bwvs=\"\",\n        bwcs=\"\",\n        beds=[],\n        loops=None,\n        loopCut=0,\n        gtf=\"\",\n        ss = 1,\n        sc = 0,\n        sa = 0.5,\n        triu=False,\n        virtual4C=False,\n        viewStart=-1,\n        viewEnd=-1,\n        viewV=\"\",\n        width=8,\n):\n    \"\"\"\n    Plot the interacting PETs as scatter, showing the raw data. \n    \"\"\"\n    #prepare data\n    chrom, xy = parseIxy(f, cut=cut, mcut=mcut)\n    if start == 0:\n        start = np.min(xy)\n    if end == -1:\n        end = np.max(xy)\n    ps = np.where((xy[:, 0] >= start) & (xy[:, 1] <= end))[0]\n    xy = xy[ps, ]\n    xy2 = XY(xy[:, 0], xy[:, 1])  #XY object\n\n    if oneD:\n        predir = os.path.dirname(os.path.realpath(f))\n        metaf = predir + \"/petMeta.json\"\n        meta = json.loads(open(metaf).read())\n        total = meta[\"Unique PETs\"] * 2\n        sig = get1DSig(xy2, start, end)\n        sig = sig / total * 10**6\n    if virtual4C:\n        predir = os.path.dirname(os.path.realpath(f))\n        metaf = predir + \"/petMeta.json\"\n        meta = json.loads(open(metaf).read())\n        virtual4Csig = getVirtual4CSig(xy2, start, end, viewStart, viewEnd)\n\n    hights = 0\n    #heights ratio\n    hr = []\n    if gtf != \"\":\n        genes = getGenes(gtf, chrom[0], start, end)\n        hights += len(genes) * 0.1\n        hr.extend([0.1] * len(genes))\n    if len(bws) > 0:\n        hights += len(bws) * 0.5\n        hr.extend([1] * len(bws))\n    if oneD:\n        hights += 0.5\n        hr.append(1)\n    if virtual4C:\n        hights += 0.5\n        hr.append(1)\n    if loops is not None:\n        hights += 0.5\n        hr.append(1)\n    if len(beds) > 0:\n        hights += len(beds) * 0.2\n        hr.extend([0.2] * len(beds))\n    #scatter plot\n    hights += 2\n    hr.append(2.5)\n    if triu:\n        hights += 3\n        square = False\n    else:\n        hights += 4\n        square = False\n  \n    #prepare figure\n    fig = pylab.figure(figsize=(width, hights))\n    gs = mpl.gridspec.GridSpec(len(hr),\n                               1,\n                               height_ratios=hr,\n                               top=0.9,\n                               bottom=0.05,\n                               left=0.1,\n                               right=0.9,\n                               wspace=0.05)\n    pylab.suptitle(\"%.2f kb,%s:%s-%s\" %\n                   (float(end - start) / 1000.0, chrom[0], start, end),\n                   fontsize=8)\n    axi = -1\n\n    #plot gene\n    if gtf != \"\":\n        for n, g in genes.items():\n            axi += 1\n            ax = fig.add_subplot(gs[axi])\n            plotGene(ax, n, g, start, end)\n\n    #plot bigWig\n    #yaxis limitaitons\n    bwvs = parseBwvs(bws, bwvs)\n    #colors\n    if bwcs == \"\":\n        bwcs = range(len(bws))\n    else:\n        bwcs = list(map(int, bwcs.split(\",\")))\n    for i, bw in enumerate(bws):\n        axi += 1\n        ax = fig.add_subplot(gs[axi])\n        name = bw.split(\"/\")[-1].split(\".bw\")[0]\n        bw = pyBigWig.open(bw)\n        ys = bw.values(chrom[0], start, end)\n        ys = np.nan_to_num(ys)\n        plotCoverage(ax,\n                     ys,\n                     colori=bwcs[i],\n                     label=name,\n                     vmin=bwvs[i][0],\n                     vmax=bwvs[i][1])\n\n    #plot 1D signal\n    if oneD:\n        axi += 1\n        ax = fig.add_subplot(gs[axi])\n        if oneDv != \"\":\n            oneDv = list(map(float, oneDv.split(\",\")))\n        else:\n            oneDv = [None, None]\n        plotCoverage(ax,\n                     sig,\n                     colori=3,\n                     label=\"1D signal\",\n                     vmin=oneDv[0],\n                     vmax=oneDv[1])\n    #plot view point, virtual 4C plot\n    if virtual4C:\n        axi += 1\n        ax = fig.add_subplot(gs[axi])\n        if viewV != \"\":\n            viewV = list(map(float, viewV.split(\",\")))\n        else:\n            viewV = [None, None]\n        if len(virtual4Csig) > 1000:\n            virtual4Csig = getBinMean(virtual4Csig, 1000)\n        #log2 is nesscessary\n        virtual4Csig = np.log2(virtual4Csig + 1)\n        ax = plotCoverage(ax,\n                     virtual4Csig,\n                     colori=0,\n                     label=\"virtual 4C signal\",\n                     vmin=viewV[0],\n                     vmax=viewV[1],\n        )\n        ax.set_ylabel(\"log2(counts)\", fontsize=6)\n \n    #plot loops as arches\n    nchrom = \"-\".join(chrom)\n    if loops is not None and nchrom in loops and len(loops[nchrom]) > 0:\n        axi += 1\n        ax = fig.add_subplot(gs[axi])\n        #plot the arch and annotate the PETs support the loop\n        #get the minal PETs number as linewidth 1,others are fold\n        plotLoops(ax, loops, nchrom,start,end,xy2=xy2,loopCut=loopCut)\n       \n    #plot genomic features\n    for i, bed in enumerate(beds):\n        axi += 1\n        name = bed.split(\"/\")[-1].split(\".bed\")[0]\n        ax = fig.add_subplot(gs[axi])\n        rs = getBedRegion(bed, chrom[0], start, end)\n        plotRegion(ax, rs, start, end, i, label=name)\n\n    #plot PETs as dots\n    axi += 1\n    ax = fig.add_subplot(gs[axi])\n    ps = xy2.queryPeakBoth(start, end)\n    mat = xy[list(ps)] \n    mat = mat - start\n    if triu:\n        #caculating the rotate coordinates\n        x = mat[:,0]*np.cos( -np.pi/4 ) - mat[:,1]*np.sin( -np.pi/4 )\n        y = mat[:,1]*np.cos( -np.pi/4 ) + mat[:,0]*np.sin( -np.pi/4 )\n        xlim = (end - start) * ( np.cos(-np.pi/4) - np.sin(-np.pi/4) )\n        ax.scatter( x,y, s =ss, color=colors[sc], alpha=sa)\n        ax.set_ylim([np.min(y),np.max(y)])\n        ax.set_xlim([0,xlim])\n    else:\n        ax.scatter( mat[:,0], mat[:,1], s =ss, color=colors[sc], alpha=sa)\n        ax.scatter( mat[:,1], mat[:,0], s =ss, color=colors[sc], alpha=sa)\n        ax.set_xlim([0, end-start])\n        ax.set_ylim([0, end-start])\n    ax.set_xticks([])\n    ax.set_yticks([])\n    ax.invert_yaxis()\n    pylab.savefig(fo + \"_scatter.pdf\")\n\n\ndef plotProfiles(\n        fo,\n        chrom=\"\",\n        start=0,\n        end=-1,\n        bws=[],\n        bwvs=\"\",\n        bwcs=\"\",\n        beds=[],\n        loops=None,\n        loopCut=0,\n        gtf=\"\",\n        width=8,\n):\n    \"\"\"\n    Plot profiles. \n    \"\"\"\n    #heights ratio\n    hights = 0\n    hr = []\n    if gtf != \"\":\n        genes = getGenes(gtf, chrom, start, end)\n        \"\"\"\n        if len(genes) > 20:\n            print(\n                \"More than 20 genes in the target region, only plot random 20.\"\n            )\n            ns = list(genes.keys())[:20]\n            ng = {}\n            for n in ns:\n                ng[n] = genes[n]\n            genes = ng\n        \"\"\"\n        hights += len(genes) * 0.12\n        hr.extend([0.12] * len(genes))\n    if len(bws) > 0:\n        hights += len(bws) * 0.3\n        hr.extend([0.8] * len(bws))\n    if loops is not None:\n        hights += 0.5\n        hr.append(1)\n    if len(beds) > 0:\n        hights += len(beds) * 0.2\n        hr.extend([0.2] * len(beds))\n\n    #prepare figure\n    fig = pylab.figure(figsize=(width, hights))\n    gs = mpl.gridspec.GridSpec(\n        len(hr),\n        1,\n        height_ratios=hr,\n        top=0.9,\n        bottom=0.05,\n        left=0.1,\n        right=0.9,\n        wspace=0.0,\n        hspace=0.05,\n    )\n    pylab.suptitle(\"%.2f kb,%s:%s-%s\" %\n                   (float(end - start) / 1000.0, chrom, start, end),\n                   fontsize=8)\n    axi = -1\n    #plot gene\n    if gtf != \"\":\n        for n, g in genes.items():\n            axi += 1\n            ax = fig.add_subplot(gs[axi])\n            plotGene(ax, n, g, start, end)\n\n    #plot bigWig\n    #yaxis limitaitons\n    bwvs = parseBwvs(bws, bwvs)\n    #colors\n    if bwcs == \"\":\n        bwcs = range(len(bws))\n    else:\n        bwcs = list(map(int, bwcs.split(\",\")))\n    for i, bw in enumerate(bws):\n        axi += 1\n        ax = fig.add_subplot(gs[axi])\n        name = bw.split(\"/\")[-1].split(\".bw\")[0]\n        bw = pyBigWig.open(bw)\n        ys = bw.values(chrom, start, end)\n        ys = np.nan_to_num(ys)\n        ax = plotCoverage(ax,\n                          ys,\n                          colori=bwcs[i],\n                          label=name,\n                          vmin=bwvs[i][0],\n                          vmax=bwvs[i][1])\n        if i == 0:\n            sns.despine(ax=ax, bottom=False, right=False, left=False, top=False)\n        elif i == len(bws) - 1:\n            sns.despine(ax=ax, bottom=False, right=False, left=False, top=True)\n        else:\n            #sns.despine(ax=ax, bottom=True, right=False, left=False, top=True)\n            sns.despine(ax=ax, bottom=False, right=False, left=False, top=True)\n\n    #plot loops as arches\n    nchrom = chrom + \"-\" + chrom\n    if loops is not None and nchrom in loops and len(loops[nchrom]) > 0:\n        axi += 1\n        ax = fig.add_subplot(gs[axi])\n        #plot the arch for loops, all same width\n        plotLoops(ax, loops, nchrom,start,end,xy2=xy2,loopCut=loopCut)\n\n    #plot genomic features\n    for i, bed in enumerate(beds):\n        axi += 1\n        name = bed.split(\"/\")[-1].split(\".bed\")[0]\n        ax = fig.add_subplot(gs[axi])\n        rs = getBedRegion(bed, chrom, start, end)\n        plotRegion(ax, rs, start, end, i, label=name)\n    pylab.savefig(fo + \"_profiles.pdf\")\n", "meta": {"hexsha": "8bd9f7c49f125e679f1f128c1c78d3ec2ba79afa", "size": 48389, "ext": "py", "lang": "Python", "max_stars_repo_path": "cLoops2/plot.py", "max_stars_repo_name": "KejiZhaoLab/cLoops2", "max_stars_repo_head_hexsha": "2a1ce6b63a912cdd282dc40718d2c7333e3c16b2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2021-07-17T07:39:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T05:35:59.000Z", "max_issues_repo_path": "cLoops2/plot.py", "max_issues_repo_name": "KejiZhaoLab/cLoops2", "max_issues_repo_head_hexsha": "2a1ce6b63a912cdd282dc40718d2c7333e3c16b2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-31T07:56:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T16:20:29.000Z", "max_forks_repo_path": "cLoops2/plot.py", "max_forks_repo_name": "KejiZhaoLab/cLoops2", "max_forks_repo_head_hexsha": "2a1ce6b63a912cdd282dc40718d2c7333e3c16b2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-07-22T03:56:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T05:52:14.000Z", "avg_line_length": 30.5100882724, "max_line_length": 219, "alphanum_fraction": 0.4723800864, "include": true, "reason": "import numpy,from scipy", "num_tokens": 13605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.18520356904553004}}
{"text": "#!/usr/bin/env python\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom astropy.table import Table\nfrom astropy.io import ascii\nimport astropy.units as u\nimport astropy.constants as const\nfrom scipy.interpolate import griddata, interp1d\nimport sys\nimport glob\n\n\n\n__author__ ='David Wilson, Parke Loyd'\n__version__=5.01\n__date__=20210209\n\n\n\"\"\"\nBT Settl models are now availabe on the SVO, and are much easier to work with.\n\"\"\"\n\n\ndef make_filepath(Teff, logg=4.5, repo='ftp'):\n    \"\"\"\n    Constructs the filepath for a phoenix spectrum file for a star with effective\n    temperature Teff, log surface gravity logg. \n    \"\"\"\n   \n    name = 'lte{T:05.1f}-{g:3.1f}-0.0a+0.0.BT-Settl.spec.7.dat'.format(T=Teff/100.0, g=logg)\n    #print(name)\n    \n    return os.path.join(repo, name)\n\ndef make_dicts(param_list):\n    \"\"\"\n    makes array of dictionaries with parameters to load\n    \"\"\"\n    param_dicts = []\n    for teff in param_list[0]:\n        for logg in param_list[1]:\n            for feh in param_list[2]:\n                for aM in param_list[3]:\n                    param_dict = {'Teff':teff, 'logg':logg, 'FeH': feh, 'aM': aM}\n                    if param_dict not in param_dicts:\n                        param_dicts.append(param_dict)\n    return param_dicts\n\ndef make_param_list(star_params, grids):\n    \"\"\"\n    makes a list of required atmospheric parameters to be retreived, also records which params need interpolation. Fixing FeH and aM = 0.0 for now.\n    \"\"\"\n    params_to_interp = []\n    param_names = ['Teff', 'logg', 'FeH', 'aM']\n    param_list = []\n    for param, grid, name in zip([star_params['Teff'],star_params['logg'] ,0.0, 0.0], grids, param_names):\n        if param in grid:\n            param_list.append([param, param])\n        else:\n            idx = np.searchsorted(grid, param)\n            param_list.append([grid[idx-1],grid[idx]])\n            params_to_interp.append(name)\n  #  print (param_list)\n    return param_list, params_to_interp\n\ndef get_grids():\n    \"\"\"\n    arrays storing the available phoenix spectra. NOTE: check svo is the same\n    \"\"\"\n    phxTgrid = np.arange(1200, 7001, 100)\n    phxTgrid = np.hstack([np.arange(2300,7000,100),\n                   np.arange(7000,12001,200)])\n    phxggrid = np.arange(0.0, 6.1, 0.5)\n    phxZgrid = np.array([0.0])\n    phxagrid = np.array([0.0])\n    return phxTgrid,phxggrid,phxZgrid, phxagrid\n\ndef get_models(repo,param_dicts):\n    \"\"\"\n    Returns \"spectra\" param_dicts but with the model flux added to each dictionary\n    \"\"\"\n    spectra = []\n    for params in param_dicts:\n        Teff, logg, FeH, aM = params['Teff'], params['logg'], params['FeH'], params['aM']\n        filepath = make_filepath(Teff, logg, repo=repo) \n        wavelength, flux =  extract_spectrum(filepath)\n        params.update({'wavelength':wavelength})\n        params.update({'flux':flux})\n        spectra.append(params)\n    return spectra\n\ndef interp_flux(spectra, params_to_interp, star_params):\n    \"\"\"\n    build the new spectrum, interpolation each phoenix model onto the shortest wavelength array then interploating to the correct parameters\n    \"\"\"\n    out_vals = [star_params[p] for p in params_to_interp]\n    in_vals = [[s[p] for p in params_to_interp] for s in spectra]\n    wavelengths = [s['wavelength'] for s in spectra]\n    nwave = np.min([len(w) for w in wavelengths])\n    for w in wavelengths: \n        if len(w) == nwave:\n            wavelength = w\n    fluxes = []\n    for s in spectra:\n        if len(s['flux']) == nwave:\n           # print(len(s['wavelength']), s['wavelength'][0], s['wavelength'][-1])\n            fluxes.append(s['flux'])\n        else:\n           # print(len(s['wavelength']), s['wavelength'][0], s['wavelength'][-1])\n            fi = interp1d(s['wavelength'], s['flux'], fill_value='extrapolate')(wavelength)\n            fluxes.append(fi)\n        \n    if len(params_to_interp) == 1:\n        in_vals = [s[params_to_interp[0]] for s in spectra]\n        new_flux = interp1d(in_vals, fluxes, axis=0, fill_value='extrapolate')(star_params[params_to_interp[0]])\n    else:\n        out_vals = [star_params[p] for p in params_to_interp]\n        in_vals = [[s[p] for p in params_to_interp] for s in spectra]\n     #   print(in_vals)\n      #  print(out_vals)\n       # print(len(fluxes))\n        new_flux = griddata(in_vals, fluxes, out_vals)[0]\n    return wavelength, new_flux\n\n    \ndef save_to_ecsv(star,wavelength, flux, save_path, star_params, normfac):\n    \"\"\"\n  #  save the new model to an ecsv file\n  #  \"\"\"\n    if os.path.exists(save_path) == False:\n        os.mkdir(save_path)\n    metadata = {'OBJECT':star, 'TEFF':star_params['Teff'], 'LOGG':star_params['logg'], 'NORMFAC':normfac}\n    savedat = Table([wavelength*u.AA, flux], names=['WAVELENGTH', 'FLUX'], meta=metadata)\n    star = star.replace(' ', '')\n    #ascii.write(savedat, save_path+star+'_phoenix_interpolated.ecsv', overwrite=True, format='ecsv')\n    savedat.write(save_path+star+'_phoenix_interpolated.ecsv', overwrite=True, format='ascii.ecsv')\n    \ndef plot_spectrum(wavelength, flux, star, normfac):\n    plt.figure(star, figsize=(5, 5))\n    plt.subplot(211)\n    plt.plot(wavelength, flux, label = 'Flux at stellar surface')\n    plt.ylabel('Flux (erg s$^{-1}$ cm$^{-2}$ \\AA$^{-1}$)')\n    plt.xscale('log')\n    plt.yscale('log')\n    plt.legend(loc=1, frameon=True)\n    plt.subplot(212)\n    plt.plot(wavelength, flux*normfac, label = 'Flux at Earth')\n    plt.ylabel('Flux (erg s$^{-1}$ cm$^{-2}$ \\AA$^{-1}$)')\n    plt.xlabel('Wavelength (\\AA)')\n    plt.xscale('log')\n    plt.yscale('log')\n    plt.legend(loc=1, frameon=True)\n    plt.tight_layout()\n    plt.show()\n\ndef get_existing_model(star_params, repo):\n    \"\"\"\n    Get the flux if there's already a good phoenix model\n    \"\"\"\n    Teff, logg, FeH, aM = star_params['Teff'], star_params['logg'], star_params['FeH'], star_params['aM']\n    file_path = make_filepath(Teff, logg, FeH, aM, repo=repo)\n    wavelength, flux = extract_spectrum(filepath)\n    return wavelength, flux\n  \ndef air_to_vac(w_air, flux, flux_interp = False):\n    \"\"\"\n    Converts the air wavelengths to vaccum wavelengths via the formular from https://www.astro.uu.se/valdwiki/Air-to-vacuum%20conversion\n    \"\"\"\n    if w_air[0] == 0.0: #correct a divide by zero problem by adding a very small number to the first wavelength element\n        w_air[0] += 0.01 * w_air[1]\n        print(w_air[0])\n    print(w_air[0])   \n    s = 1e4/w_air\n    n = 1. + 0.00008336624212083 + (0.02408926869968 / (130.1065924522 - s**2)) + (0.0001599740894897 / (38.92568793293 - s**2))\n    w_vac = w_air * n\n    if flux_interp: #interpolate flux back onto old wavelength grid\n        flux = interp1d(w_vac, flux, fill_value='extrapolate')(w_air)\n        w_vac = w_air\n    return w_vac, flux\n    \n    \ndef extract_spectrum(filepath):\n    \"\"\"\n    Open and extract a svo txt file. So much easier than before!\n    \"\"\"\n    try:\n        w_raw, f_raw = np.loadtxt(filepath, unpack=True)\n    except:\n        print ('model {} not in repo'.format(os.path.split(filepath)[1]))\n        sys.exit(1)\n    return w_raw, f_raw\n    \ndef make_phoenix_spectrum(star, save_path, repo, star_params, save_ecsv=False, plot=False, to_vac=False):\n    \"\"\"\n    Main array. Takes a list of stellar parameters and makes a phoenix spectrum out of. Save_path is where you want the final spectrum to go, repo is where downloaded phoenix files go. wave_file is where the wavelength array is \n    \"\"\"\n    tgrid, ggrig,fgrid, agrid = get_grids()\n    param_list, params_to_interp = make_param_list(star_params, [tgrid, ggrig,fgrid, agrid])\n    if len(params_to_interp) == 0: #i.e. if there's an existing model\n        print('phoenix model available')\n        wavelength, flux = get_existing_model(star_params, repo)\n    else:\n        param_dicts = make_dicts(param_list)\n        print(param_dicts)\n        spectra = get_models(repo,param_dicts)\n        wavelength, flux = interp_flux(spectra, params_to_interp, star_params)\n    wavelength, flux = wavelength[wavelength >= 501.0], flux[wavelength >= 501.0] #spectrum does funny things at lambda < 501\n    normfac = find_normfac(star_params['Radius'], star_params['Distance'])\n    if to_vac:\n        wavelength, flux = air_to_vac(wavelength, flux)\n    if save_ecsv:\n        save_to_ecsv(star, wavelength, flux, save_path, star_params, normfac)\n    if plot == True:\n        plot_spectrum(wavelength, flux, star, normfac)\n    return wavelength, flux\n\n\ndef find_normfac(radius, distance):\n    \"\"\"\n    finds the scaling factor for the spectrum\n    \"\"\"\n    return (radius.to(u.cm)/distance.to(u.cm))**2\n \n\n\ndef test():\n    star = 'Trappist-1_test' \n    repo = '/media/david/5tb_storage1/btsettl_test/t1_test/' #where the files to be interpolated are\n    save_path = 'test_output/' #where you want the ecsv files to be saved\n    star_params = {'Teff': 2628, 'logg': 5.21, 'FeH':0.0, 'aM':0.0, 'Radius':1.16*u.R_jup, 'Distance':12.43*u.pc}\n    w_phx, f_phx = make_phoenix_spectrum(star, save_path, repo, star_params, save_ecsv=True, plot=True)\n\ndef test_load():\n    path = 'test_output/'\n    spectra = glob.glob('{}*.ecsv'.format(path))\n    if len(spectra) > 0:\n        for spectrum in spectra:\n            data = Table.read(spectrum)\n            plot_spectrum(data['WAVELENGTH'], data['FLUX'], data.meta['OBJECT'],data.meta['NORMFAC'])\n    else:\n        print('No ecsv files in path')\n        \n    \n\n    \n# test()\n# test_load() ", "meta": {"hexsha": "7e053a4b8dc9df970f20426d9d276ffaae5de949", "size": 9383, "ext": "py", "lang": "Python", "max_stars_repo_path": "prepare_phoenix_svo.py", "max_stars_repo_name": "davidjwilson/ltt1445", "max_stars_repo_head_hexsha": "845686c1e699fd97de3b0dadbdc62069b700df33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prepare_phoenix_svo.py", "max_issues_repo_name": "davidjwilson/ltt1445", "max_issues_repo_head_hexsha": "845686c1e699fd97de3b0dadbdc62069b700df33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prepare_phoenix_svo.py", "max_forks_repo_name": "davidjwilson/ltt1445", "max_forks_repo_head_hexsha": "845686c1e699fd97de3b0dadbdc62069b700df33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.532, "max_line_length": 228, "alphanum_fraction": 0.6457422999, "include": true, "reason": "import numpy,from scipy,import astropy,from astropy", "num_tokens": 2621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.18520356387055378}}
{"text": "# Copyright 2020 IBM Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport logging\nimport argparse\nimport itertools\nimport numpy as np\nimport pandas as pd\nimport datetime as dt\nimport xgboost as xgb\nimport os.path as path\nimport physics_model as pm\nimport spacetrack_etl as st\nfrom functools import partial\nimport pred_physics_err as err_ml\n\n\nlogging.basicConfig(level=os.environ.get(\"LOGLEVEL\", \"INFO\"))\nlogger = logging.getLogger(__name__)\n\n\ndef get_latest_orbit_data(space_track_user,\n                          space_track_password,\n                          norad_ids=None):\n    \"\"\"Fetches the latest TLE data from Space Track\n\n    :param space_track_user: The user name for the Space Track account\n    :type space_track_user: str\n\n    :param space_track_password: The password for the Space Track account\n    :type space_track_password:\n\n    :param norad_ids: An optional list of NORAD IDs to fetch the TLEs\n        for.  If NORAD IDs are not provided then data will be fetched\n        for all RSOs in LEO.\n    :type norad_ids: [str]\n\n    :return: A DataFrame containing the latest TLE data for the requested RSOs\n    :rtype: pandas.DataFrame\n    \"\"\"\n    stc = st.build_space_track_client(space_track_user, space_track_password)\n    latest_orbit_data = st.build_leo_df(stc,\n                                        norad_ids=norad_ids,\n                                        only_latest=True)\n    return latest_orbit_data\n\n\ndef predict_orbit(row, pred_start, timesteps):\n    \"\"\"Uses a physical model to predict the orbital state vectors\n    for each provided timestep into the future.\n\n    :param row: The DataFrame row to make the orbit predictions for\n    :type row: pandas.Series\n\n    :param pred_start: The timestamp at which to start the prediction window\n    :type pred_start: pandas.Timestamp\n\n    :param timestep: A list of seconds into the future to predict the orbit\n       for\n    :type timestep: [float]\n\n    :return: The elapsed seconds from `pred_start` and the predicted\n        state vectors for each timestep\n    :rtype: np.array\n    \"\"\"\n    orbit = pm.build_orbit(row)\n    if row.epoch == pred_start:\n        # The row's epoch is the same as the prediction window start timestamp\n        # so we don't need to fast forward the first prediction.\n        timesteps = [0] + timesteps\n    else:\n        # The row's epoch is behind the prediction window start timestamp so we\n        # calculate the number of seconds we need to propagate the orbit to have\n        # the epoch be the same as the prediction start time.\n        offset = (pred_start - row.epoch).total_seconds()\n        timesteps = [offset] + timesteps\n\n    ts_preds = []\n    elapsed_seconds = 0\n    for ts in timesteps:\n        orbit_propagator = pm.build_orbit_propagator(orbit,\n                                                     return_orbit=True)\n        orbit, orbit_pred = orbit_propagator(ts)\n        elapsed_seconds += ts\n        # Create a numpy array where the first value is number of seconds\n        # that have elpased since the prediction window's start time and then\n        # the next six values are the predicted orbital state vector.\n        ts_pred = np.insert(orbit_pred, 0, elapsed_seconds, axis=0)\n        ts_preds.append(ts_pred)\n    return np.stack(ts_preds, axis=0)\n\n\nDEFAULT_N_DAYS = 7\nDEFAULT_TIMESTEP = 600\n\ndef predict_orbits(df, ml_models,\n                   n_days=DEFAULT_N_DAYS,\n                   timestep=DEFAULT_TIMESTEP):\n    \"\"\"Use a physical model to predict the future orbits of all RSOs in the\n    provided DataFrame, then use ML models to predict the error in the physics\n    predictions, and finally adjust the physical predictions based on the error\n    estimates.\n\n    :param df: The latest TLE data for the RSOs to predict the orbits of\n    :type df: pandas.DataFrame\n\n    :param ml_models: The ML models to use to estimate the error for each\n        component of the predicted state vector\n    :type ml_models: [xgboost.XGBRegressor]\n\n    :param n_days: The number of days into the future to predict orbits for\n    :type n_days: int\n\n    :param timestep: The frequency in seconds to make orbital predictions at\n    :type timestep: float\n\n    :return: The input DataFrame with the physical orbit predictions, the\n        estimated errors, and the corrected orbit predictions added\n        as columns\n    :rtype: pandas.DataFrame\n    \"\"\"\n    # Use the latest epoch in the dataset as the start of the prediction window\n    pred_start = df.epoch.max()\n    pred_end = pred_start + dt.timedelta(days=n_days)\n    df['pred_start_dt'] = pred_start\n    df['pred_end_dt'] = pred_end\n    # Get the total amount of seconds in the prediction window\n    pred_window_seconds = (pred_end - pred_start).total_seconds()\n    # Calculate how many predictions we will make based on the\n    # the length of the prediction window and the timestep\n    n_pred_intervals = int(pred_window_seconds / timestep) - 1\n    timesteps = [timestep]*n_pred_intervals\n\n    orbit_predictor = partial(predict_orbit,\n                              pred_start=pred_start,\n                              timesteps=timesteps)\n    err_est = lambda preds: err_ml.predict_err(ml_models, preds)\n    logger.info('Predicting Orbits...')\n    df['physics_preds'] = df.apply(orbit_predictor, axis=1)\n    logger.info('Estimating physics errors...')\n    df['ml_err_preds'] = df.physics_preds.apply(err_est)\n\n    # Convert the physical predictions to a numpy 3D array and drop\n    # the first element of the last axis which is the elapsed time\n    physics_array = np.stack(df.physics_preds.to_numpy())[:, :, 1:]\n    ml_array = np.stack(df.ml_err_preds.to_numpy())\n    # the corrected predictions are the physics predictions with the\n    # estimated errors subtracted off\n    corrected_preds = physics_array - ml_array\n    # Convert the 3D numpy array into a list of 2D arrays\n    orbit_preds = [corrected_preds[i]\n                   for i\n                   in range(corrected_preds.shape[0])]\n    df['orbit_preds'] = pd.Series(orbit_preds)\n    return df\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Predict orbits using physical and ML models.',\n        formatter_class=argparse.ArgumentDefaultsHelpFormatter\n    )\n    parser.add_argument(\n        '--st_user',\n        help='The username for space-track.org',\n        type=str,\n        required=True\n    )\n    parser.add_argument(\n        '--st_password',\n        help='The password for space-track.org',\n        type=str,\n        required=True\n    )\n    parser.add_argument(\n        '--ml_model_dir',\n        help=('The path to the directory containing the error prediction'\n              ' models searilized as JSON'),\n        required=True\n    )\n    parser.add_argument(\n        '--norad_id_file',\n        help=('A text file containing a single NORAD ID on each row to fetch '\n              'orbit data for. If no file are passed then orbit data for '\n              'all LEO RSOs will be fetched'),\n        type=str\n    )\n    parser.add_argument(\n        '--n_days',\n        help='The number of days in the future to make orbit predictions for',\n        default=DEFAULT_N_DAYS,\n        type=int\n    )\n    parser.add_argument(\n        '--timestep',\n        help='The frequency in seconds to make orbit predictions for',\n        default=DEFAULT_TIMESTEP,\n        type=float\n    )\n    parser.add_argument(\n        '--output_path',\n        help='The path to save the orbit prediction pickle file to',\n        required=True,\n        type=str\n    )\n\n    args = parser.parse_args()\n\n    if args.norad_id_file:\n        with open(args.norad_id_file) as norad_id_file:\n            norad_ids = [l.strip() for l in norad_id_file.readlines()]\n    else:\n        norad_ids = []\n\n    latest_orbit_data = get_latest_orbit_data(args.st_user,\n                                              args.st_password,\n                                              norad_ids=norad_ids)\n    logger.info('Loading ML Models...')\n    ml_models = err_ml.load_models(args.ml_model_dir)\n\n    orbit_pred_df = predict_orbits(latest_orbit_data,\n                                   ml_models,\n                                   n_days=args.n_days,\n                                   timestep=args.timestep)\n    logger.info('Serializing Results...')\n    orbit_pred_df.to_pickle(args.output_path)\n", "meta": {"hexsha": "6b0d078bdebd1f09e754bf194a1339d415aed1b2", "size": 8841, "ext": "py", "lang": "Python", "max_stars_repo_path": "orbit_prediction/orbit_prediction/pred_orbits.py", "max_stars_repo_name": "lahorite/spacetech-ssa", "max_stars_repo_head_hexsha": "81742156b1b157b1d9981a66dee7506a1101b760", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-26T17:09:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T17:09:17.000Z", "max_issues_repo_path": "orbit_prediction/orbit_prediction/pred_orbits.py", "max_issues_repo_name": "ibmspacetech/spacetech-ssa", "max_issues_repo_head_hexsha": "ea1c8ca2c5300cfabaa3e8fc22e35624ccca97ca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "orbit_prediction/orbit_prediction/pred_orbits.py", "max_forks_repo_name": "ibmspacetech/spacetech-ssa", "max_forks_repo_head_hexsha": "ea1c8ca2c5300cfabaa3e8fc22e35624ccca97ca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-27T14:07:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-27T14:07:07.000Z", "avg_line_length": 36.9916317992, "max_line_length": 80, "alphanum_fraction": 0.6629340572, "include": true, "reason": "import numpy", "num_tokens": 1949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.18520356185522835}}
{"text": "import warnings\nfrom typing import Any, Dict, List, Optional, Tuple\n\nimport numpy as np\nimport pandas as pd\n\nfrom .unilateral import Unilateral\nfrom .utils import HDFMixin, draw_diagnose_times, fast_binomial_pmf\n\n\n# I chose not to make this one a child of System, since it is basically only a\n# container for two System instances\nclass Bilateral(HDFMixin):\n    \"\"\"Class that models metastatic progression in a lymphatic system\n    bilaterally by creating two :class:`Unilateral` instances that are\n    symmetric in their connections. The parameters describing the spread\n    probabilities however need not be symmetric.\n\n    See Also:\n        :class:`Unilateral`: Two instances of this class are created as\n        attributes.\n    \"\"\"\n    def __init__(\n        self,\n        graph: Dict[Tuple[str], List[str]] = {},\n        base_symmetric: bool = False,\n        trans_symmetric: bool = True,\n        **kwargs\n    ):\n        \"\"\"Initialize both sides of the network as a :class:`Unilateral`\n        instance:\n\n        Args:\n            graph: Dictionary of the same kind as for initialization of\n                :class:`Unilateral`. This graph will be passed to the\n                constructors of two :class:`Unilateral` attributes of this\n                class.\n            base_symmetric: If ``True``, the spread probabilities of the two\n                sides from the tumor(s) to the LNLs will be set symmetrically.\n            trans_symmetric: If ``True``, the spread probabilities among the\n                LNLs will be set symmetrically.\n        \"\"\"\n        self.ipsi   = Unilateral(graph=graph)   # ipsilateral and...\n        self.contra = Unilateral(graph=graph)   # ...contralateral network\n\n        self.base_symmetric  = base_symmetric\n        self.trans_symmetric = trans_symmetric\n\n\n    def __str__(self):\n        \"\"\"Print info about the structure and parameters of the bilateral\n        lymphatic system.\n        \"\"\"\n        num_tumors = len(self.ipsi.tumors)\n        num_lnls   = len(self.ipsi.lnls)\n        string = (\n            f\"Bilateral lymphatic system with {num_tumors} tumor(s) \"\n            f\"and 2 * {num_lnls} LNL(s).\\n\"\n        )\n        string += \"Symmetry: \"\n        string += \"base \" if self.base_symmetric else \"\"\n        string += \"trans\\n\" if self.trans_symmetric else \"\\n\"\n        string += \"Ipsilateral:\\t\" + \" \".join([f\"{e}\" for e in self.ipsi.edges])\n        string += \"\\n\"\n        string += \"Contralateral:\\t\" + \" \".join([f\"{e}\" for e in self.contra.edges])\n\n        return string\n\n\n    @property\n    def graph(self) -> Dict[Tuple[str], List[str]]:\n        \"\"\"Return the (unilateral) graph that was used to create this network.\n        \"\"\"\n        return self.ipsi.graph\n\n\n    @property\n    def system(self):\n        \"\"\"Return a dictionary with the ipsi- & contralateral side's\n        :class:`Unilateral` under the keys ``\"ipsi\"`` and ``\"contra\"``\n        respectively.\n\n        This is needed since in some weak moment, I thought it would be a great\n        idea if a class named ``BilateralSystem`` had an attriute called\n        ``system`` which contained two instances of the ``System`` class under\n        the keys ``\"ipsi\"`` and ``\"contra\"``...\n        \"\"\"\n        return {\n            \"ipsi\"  : self.ipsi,\n            \"contra\": self.contra\n        }\n\n\n    @property\n    def state(self) -> np.ndarray:\n        \"\"\"\n        Return the currently state (healthy or involved) of all LNLs in the\n        system.\n        \"\"\"\n        ipsi_state = self.ipsi.state\n        contra_state = self.contra.state\n        return np.concatenate([ipsi_state, contra_state])\n\n\n    @state.setter\n    def state(self, newstate: np.ndarray):\n        \"\"\"\n        Set the state of the system to ``newstate``.\n        \"\"\"\n        self.ipsi.state = newstate[:len(self.ipsi.lnls)]\n        self.contra.state = newstate[len(self.ipsi.lnls):]\n\n\n    @property\n    def base_probs(self) -> np.ndarray:\n        \"\"\"Probabilities of lymphatic spread from the tumor(s) to the lymph\n        node levels. If the ipsi- & contralateral spread from the tumor is set\n        to be symmetric (``base_symmetric = True``) this only returns the\n        parameters of one side. So, the returned array is composed like so:\n\n        +-----------------+--------------------+\n        | base probs ipsi | base probs contra* |\n        +-----------------+--------------------+\n\n        *Only when ``base_symmetric = False``, which is the default.\n\n        When setting these parameters, the length of the provided array only\n        needs to be half as long if ``base_symmetric`` is ``True``, since both\n        sides will be set to the same values.\n\n        See Also:\n            :attr:`Unilateral.base_probs`\n        \"\"\"\n        if self.base_symmetric:\n            return self.ipsi.base_probs\n        else:\n            return np.concatenate([self.ipsi.base_probs,\n                                   self.contra.base_probs])\n\n    @base_probs.setter\n    def base_probs(self, new_base_probs: np.ndarray):\n        \"\"\"Set the base probabilities from the tumor(s) to the LNLs.\n        \"\"\"\n        if self.base_symmetric:\n            self.ipsi.base_probs = new_base_probs\n            self.contra.base_probs = new_base_probs\n        else:\n            num_base_probs = len(self.ipsi.base_edges)\n            self.ipsi.base_probs = new_base_probs[:num_base_probs]\n            self.contra.base_probs = new_base_probs[num_base_probs:]\n\n\n    @property\n    def trans_probs(self) -> np.ndarray:\n        \"\"\"Probabilities of lymphatic spread among the lymph node levels. If\n        this ipsi- & contralateral spread is set to be symmetric\n        (``trans_symmetric = True``) this only returns the parameters of one\n        side. Similiar to the :attr:`base_probs`, this array's shape is:\n\n        +------------------+---------------------+\n        | trans probs ipsi | trans probs contra* |\n        +------------------+---------------------+\n\n        *Only if ``trans_symmetric = False``.\n\n        And correspondingly, if setting these transmission probability one only\n        needs half as large an array if ``trans_symmetric`` is ``True``.\n\n        See Also:\n            :attr:`Unilateral.trans_probs`\n        \"\"\"\n        if self.trans_symmetric:\n            return self.ipsi.trans_probs\n        else:\n            return np.concatenate([self.ipsi.trans_probs,\n                                   self.contra.trans_probs])\n\n    @trans_probs.setter\n    def trans_probs(self, new_trans_probs: np.ndarray):\n        \"\"\"Set the transmission probabilities (from LNL to LNL) of the network.\n        \"\"\"\n        if self.trans_symmetric:\n            self.ipsi.trans_probs = new_trans_probs\n            self.contra.trans_probs = new_trans_probs\n        else:\n            num_trans_probs = len(self.ipsi.trans_edges)\n            self.ipsi.trans_probs = new_trans_probs[:num_trans_probs]\n            self.contra.trans_probs = new_trans_probs[num_trans_probs:]\n\n\n    @property\n    def spread_probs(self) -> np.ndarray:\n        \"\"\"The parameters representing the probabilities for lymphatic spread\n        along a directed edge of the graph representing the lymphatic network.\n\n        If the bilateral network is set to have symmetries, the length of the\n        list/array of numbers that need to be provided will be shorter. E.g.,\n        when the bilateral lymphatic network is completely asymmetric, it\n        requires an array of length :math:`2n_b + 2n_t` where :math:`n_b` is\n        the number of edges from the tumor to the LNLs and :math:`n_t` the\n        number of edges among the LNLs.\n\n        Similar to the :attr:`base_probs` and the :attr:`trans_probs`, we can\n        describe its shape like this:\n\n        +-----------------+--------------------+------------------+----------------------+\n        | base probs ipsi | base probs contra* | trans probs ipsi | trans probs contra** |\n        +-----------------+--------------------+------------------+----------------------+\n\n        | *Only if ``base_symmetric = False``, which is the default.\n        | **Only if ``trans_symmetric = False``.\n\n        See Also:\n            :attr:`Unilateral.spread_probs`\n        \"\"\"\n        return np.concatenate([self.base_probs, self.trans_probs])\n\n\n    @spread_probs.setter\n    def spread_probs(self, new_spread_probs: np.ndarray):\n        \"\"\"Set the spread probabilities of the :class:`Edge` instances in the\n        the network.\n        \"\"\"\n        num_base_probs = len(self.ipsi.base_edges)\n\n        if self.base_symmetric:\n            self.base_probs = new_spread_probs[:num_base_probs]\n            self.trans_probs = new_spread_probs[num_base_probs:]\n        else:\n            self.base_probs = new_spread_probs[:2*num_base_probs]\n            self.trans_probs = new_spread_probs[2*num_base_probs:]\n\n\n    @property\n    def modalities(self):\n        \"\"\"Compute the two system's observation matrices\n        :math:`\\\\mathbf{B}^{\\\\text{i}}` and :math:`\\\\mathbf{B}^{\\\\text{c}}`.\n\n        See Also:\n            :meth:`Unilateral.modalities`: Setting modalities in unilateral\n            System.\n        \"\"\"\n        ipsi_modality_spsn = self.ipsi.modalities\n        if ipsi_modality_spsn != self.contra.modalities:\n            msg = (\"Ipsi- & contralaterally stored modalities are not the same\")\n            raise RuntimeError(msg)\n\n        return ipsi_modality_spsn\n\n\n    @modalities.setter\n    def modalities(self, modality_spsn: Dict[str, List[float]]):\n        \"\"\"\n        Given specificity :math:`s_P` & sensitivity :math:`s_N` of different\n        diagnostic modalities, compute the system's two observation matrices\n        :math:`\\\\mathbf{B}_i` and :math:`\\\\mathbf{B}_c`.\n        \"\"\"\n        self.ipsi.modalities = modality_spsn\n        self.contra.modalities = modality_spsn\n\n\n    @property\n    def patient_data(self):\n        \"\"\"Table with rows of patients. Columns should have three levels. The\n        first column is ('info', 'tumor', 't_stage'). The rest of the columns\n        are separated by modality names on the top level, then subdivided into\n        'ipsi' & 'contra' by the second level and finally, in the third level,\n        the names of the lymph node level are given. Here is an example of such\n        a table:\n\n        +---------+----------------------+----------------------+\n        |  info   |         MRI          |         PET          |\n        +---------+----------+-----------+----------+-----------+\n        |  tumor  |   ipsi   |  contra   |   ipsi   |  contra   |\n        +---------+----------+-----------+----------+-----------+\n        | t_stage |    II    |    II     |    II    |    II     |\n        +=========+==========+===========+==========+===========+\n        | early   | ``True`` | ``None``  | ``True`` | ``False`` |\n        +---------+----------+-----------+----------+-----------+\n        | late    | ``None`` | ``None``  | ``None`` | ``None``  |\n        +---------+----------+-----------+----------+-----------+\n        | early   | ``True`` | ``False`` | ``True`` | ``True``  |\n        +---------+----------+-----------+----------+-----------+\n        \"\"\"\n        try:\n            return self._patient_data\n        except AttributeError:\n            raise AttributeError(\n                \"No patient data has been loaded yet\"\n            )\n\n    @patient_data.setter\n    def patient_data(self, patient_data: pd.DataFrame):\n        \"\"\"Load the patient data. For now, this just calls the :meth:`load_data`\n        method, but at a later point, I would like to write a function here\n        that generates the pandas :class:`DataFrame` from the internal matrix\n        representation of the data.\n        \"\"\"\n        self._patient_data = patient_data.copy()\n        self.load_data(patient_data)\n\n\n    def load_data(\n        self,\n        data: pd.DataFrame,\n        t_stages: Optional[List[int]] = None,\n        modality_spsn: Optional[Dict[str, List[float]]] = None,\n        mode: str = \"HMM\"\n    ):\n        \"\"\"Load a dataset by converting it into internal representation as data\n        matrix.\n\n        Args:\n            data: Table with rows of patients. Columns must have three levels.\n                The first column is ('info', 'tumor', 't_stage'). The rest of\n                the columns are separated by modality names on the top level,\n                then subdivided into 'ipsi' & 'contra' by the second level and\n                finally, in the third level, the names of the lymph node level\n                are given. Here is an example of such a table:\n\n                +---------+---------------------+-----------------------+\n                |  info   |         MRI         |         PET           |\n                +---------+----------+----------+-----------+-----------+\n                |  tumor  |   ipsi   |  contra  |   ipsi    |  contra   |\n                +---------+----------+----------+-----------+-----------+\n                | t_stage |    II    |    II    |    II     |    II     |\n                +=========+==========+==========+===========+===========+\n                | early   | ``True`` | ``None`` | ``True``  | ``False`` |\n                +---------+----------+----------+-----------+-----------+\n                | late    | ``None`` | ``None`` | ``False`` | ``False`` |\n                +---------+----------+----------+-----------+-----------+\n                | early   | ``True`` | ``True`` | ``True``  | ``None``  |\n                +---------+----------+----------+-----------+-----------+\n\n        See Also:\n            :meth:`Unilateral.load_data`: Data loading method of unilateral\n            system.\n        \"\"\"\n        # split the DataFrame into two, one for ipsi-, one for contralateral\n        ipsi_data = data.drop(\n            columns=[\"contra\"], axis=1, level=1, inplace=False\n        )\n        ipsi_data = pd.DataFrame(\n            ipsi_data.values,\n            index=ipsi_data.index,\n            columns=ipsi_data.columns.droplevel(1)\n        )\n        contra_data = data.drop(\n            columns=[\"ipsi\"], axis=1, level=1, inplace=False\n        )\n        contra_data = pd.DataFrame(\n            contra_data.values,\n            index=contra_data.index,\n            columns=contra_data.columns.droplevel(1)\n        )\n\n        self.ipsi.load_data(\n            ipsi_data,\n            t_stages=t_stages,\n            modality_spsn=modality_spsn,\n            mode=mode\n        )\n        self.contra.load_data(\n            contra_data,\n            t_stages=t_stages,\n            modality_spsn=modality_spsn,\n            mode=mode\n        )\n\n\n    def _are_valid_(self, new_spread_probs: np.ndarray) -> bool:\n        \"\"\"Check that the spread probability (rates) are all within limits.\n        \"\"\"\n        if new_spread_probs.shape != self.spread_probs.shape:\n            msg = (\"Shape of provided spread parameters does not match network\")\n            raise ValueError(msg)\n        if np.any(np.greater(0., new_spread_probs)):\n            return False\n        if np.any(np.greater(new_spread_probs, 1.)):\n            return False\n\n        return True\n\n\n    def _log_likelihood(\n        self,\n        t_stages: Optional[List[Any]] = None,\n        diag_times: Optional[Dict[Any, int]] = None,\n        max_t: Optional[int] = 10,\n        time_dists: Optional[Dict[Any, np.ndarray]] = None\n    ):\n        \"\"\"Compute the log-likelihood of data, using the stored spread probs.\n        This method mainly exists so that the checking and assigning of the\n        spread probs can be skipped.\n        \"\"\"\n        llh = 0.\n\n        if diag_times is not None:\n            if len(diag_times) != len(t_stages):\n                msg = (\"One diagnose time must be provided for each T-stage.\")\n                raise ValueError(msg)\n\n            for stage in t_stages:\n                diag_time = np.around(diag_times[stage]).astype(int)\n                if diag_time > max_t:\n                    return -np.inf\n\n                # probabilities for any hidden state (ipsi- & contralaterally)\n                state_probs = {}\n                state_probs[\"ipsi\"] = self.ipsi._evolve(diag_time)\n                state_probs[\"contra\"] = self.contra._evolve(diag_time)\n\n                # joint probs for ipsi- & contralateral hidden states\n                joint_state_probs = np.outer(state_probs[\"ipsi\"],\n                                             state_probs[\"contra\"])\n                log_p = np.log(\n                    np.sum(\n                        self.ipsi.diagnose_matrices[stage]\n                        * (joint_state_probs\n                           @ self.contra.diagnose_matrices[stage]),\n                        axis=0\n                    )\n                )\n                llh += np.sum(log_p)\n\n            return llh\n\n        elif time_dists is not None:\n            if len(time_dists) != len(t_stages):\n                msg = (\"One distribution over diagnose times must be provided \"\n                       \"for each T-stage.\")\n                raise ValueError(msg)\n\n            # subtract 1, to also consider healthy starting state (t = 0)\n            max_t = len(time_dists[t_stages[0]]) - 1\n\n            state_probs = {}\n            state_probs[\"ipsi\"] = self.ipsi._evolve(t_last=max_t)\n            state_probs[\"contra\"] = self.contra._evolve(t_last=max_t)\n\n            for stage in t_stages:\n                joint_state_probs = (\n                    state_probs[\"ipsi\"].T\n                    @ np.diag(time_dists[stage])\n                    @ state_probs[\"contra\"]\n                )\n                log_p = np.log(\n                    np.sum(\n                        self.ipsi.diagnose_matrices[stage]\n                        * (joint_state_probs\n                           @ self.contra.diagnose_matrices[stage]),\n                        axis=0\n                    )\n                )\n                llh += np.sum(log_p)\n\n            return llh\n\n        else:\n            msg = (\"Either provide a list of diagnose times for each T-stage \"\n                   \"or a distribution over diagnose times for each T-stage.\")\n            raise ValueError(msg)\n\n\n    def log_likelihood(\n        self,\n        spread_probs: np.ndarray,\n        t_stages: Optional[List[Any]] = None,\n        diag_times: Optional[Dict[Any, int]] = None,\n        max_t: Optional[int] = 10,\n        time_dists: Optional[Dict[Any, np.ndarray]] = None\n    ):\n        \"\"\"Compute log-likelihood of (already stored) data, given the spread\n        probabilities and either a discrete diagnose time or a distribution to\n        use for marginalization over diagnose times.\n\n        Args:\n            spread_probs: Spread probabiltites from the tumor to the LNLs, as\n                well as from (already involved) LNLs to downsream LNLs. Includes\n                both sides of the neck. The composition of this array is:\n\n                +----------------------------+-----------------------------+\n                | base probs (ipsi & contra) | trans probs (ipsi & contra) |\n                +----------------------------+-----------------------------+\n\n                If certain symmetries are chosen, only one set of base or\n                transmission probabilities might have to be provided.\n\n            t_stages: List of T-stages that are also used in the data to denote\n                how advanced the primary tumor of the patient is. This does not\n                need to correspond to the clinical T-stages 'T1', 'T2' and so\n                on, but can also be more abstract like 'early', 'late' etc.\n\n            diag_times: For each T-stage, one can specify with what time step\n                the likelihood should be computed. If this is set to `None`,\n                and a distribution over diagnose times `time_dists` is provided,\n                the function marginalizes over diagnose times.\n\n            max_t: Latest possible diagnose time. This is only used to return\n                `-np.inf` in case one of the `diag_times` exceeds this value.\n\n            time_dists: Distribution over diagnose times that can be used to\n                compute the likelihood of the data, given the spread\n                probabilities, but marginalized over the time of diagnosis. If\n                set to `None`, a diagnose time must be explicitly set for each\n                T-stage.\n\n        Returns:\n            The log-likelihood :math:`\\\\log{p(D \\\\mid \\\\theta)}` where :math:`D`\n            is the data and :math:`\\\\theta` is the tuple of spread probabilities\n            and diagnose times or distributions over diagnose times.\n\n        See Also:\n            :attr:`spread_probs`: Property for getting and setting the spread\n            probabilities, of which a lymphatic network has as many as it has\n            :class:`Edge` instances (in case no symmetries apply).\n\n            :meth:`Unilateral.log_likelihood`: The log-likelihood function of\n            the unilateral system.\n        \"\"\"\n        if not self._are_valid_(spread_probs):\n            return -np.inf\n\n        self.spread_probs = spread_probs\n\n        if t_stages is None:\n            t_stages = list(self.ipsi.f.keys())\n\n        return self._log_likelihood(\n            t_stages=t_stages,\n            diag_times=diag_times,\n            max_t=max_t,\n            time_dists=time_dists,\n        )\n\n\n    def marginal_log_likelihood(\n        self,\n        theta: np.ndarray,\n        t_stages: Optional[List[Any]] = None,\n        time_dists: dict = {}\n    ) -> float:\n        \"\"\"\n        Compute the likelihood of the (already stored) data, given the spread\n        parameters, marginalized over time of diagnosis via time distributions.\n        Wraps the :meth:`log_likelihood` method.\n\n        Args:\n            theta: Spread probabiltites from the tumor to the LNLs, as well as\n                from (already involved) LNLs to downsream LNLs. Includes both\n                sides of the neck. The composition of this array is:\n\n                +----------------------------+-----------------------------+\n                | base probs (ipsi & contra) | trans probs (ipsi & contra) |\n                +----------------------------+-----------------------------+\n\n                If certain symmetries are chosen, only one set of base or\n                transmission probabilities might have to be provided.\n\n            t_stages: List of T-stages that should be included in the learning\n                process.\n\n            time_dists: Distribution over the probability of diagnosis at\n                different times :math:`t` given T-stage.\n\n        Returns:\n            The log-likelihood of a parameter sample.\n\n        See Also:\n            :meth:`log_likelihood`: Simply calls the actual likelihood function\n            where it sets the `diag_times` to `None`.\n        \"\"\"\n        return self.log_likelihood(\n            theta, t_stages,\n            diag_times=None, time_dists=time_dists\n        )\n\n\n    def time_log_likelihood(\n        self,\n        theta: np.ndarray,\n        t_stages: List[Any],\n        max_t: int = 10\n    ) -> float:\n        \"\"\"\n        Compute likelihood given the spread parameters and the time of diagnosis\n        for each T-stage. Wraps the :math:`log_likelihood` method.\n\n        Args:\n            theta: Set of parameters, consisting of the spread probabilities\n                and the time of diagnosis for all T-stages. It is therefore\n                made up these parts and in that order:\n\n                +------------+-------------+----------------+\n                | base probs | trans probs | diagnose times |\n                +------------+-------------+----------------+\n\n            t_stages: keywords of T-stages that are present in the dictionary of\n                C matrices and the previously loaded dataset.\n\n            max_t: Latest accepted time-point.\n\n        Returns:\n            The likelihood of the data, given the spread parameters as well as\n            the diagnose time for each T-stage.\n\n        See Also:\n            :meth:`log_likelihood`: The `theta` argument of this function is\n            split into `spread_probs` and `diag_times`, which are then passed\n            to the actual likelihood function.\n        \"\"\"\n        # splitting theta into spread parameters and...\n        len_spread_probs = len(theta) - len(t_stages)\n        spread_probs = theta[:len_spread_probs]\n        # ...diagnose times for each T-stage\n        tmp = theta[len_spread_probs:]\n        diag_times = {t_stages[t]: tmp[t] for t in range(len(t_stages))}\n\n        return self.log_likelihood(\n            spread_probs, t_stages,\n            diag_times=diag_times, max_t=max_t, time_dists=None\n        )\n\n\n    def binom_marg_log_likelihood(\n        self,\n        theta: np.ndarray,\n        t_stages: List[Any],\n        max_t: int = 10\n    ) -> float:\n        \"\"\"\n        Compute marginal log-likelihood using binomial distributions to sum\n        over the diagnose times.\n\n        Args:\n            theta: Set of parameters, consisting of the spread probabilities\n                and the binomial distribution's :math:`p` parameters for each\n                T-category. One has to provide a concatenated array of these\n                numbers like this:\n\n                +------------+-------------+--------------------------+\n                | base probs | trans probs | binomial :math`p` params |\n                +------------+-------------+--------------------------+\n\n            t_stages: keywords of T-stages that are present in the dictionary of\n                C matrices and the previously loaded dataset.\n\n            max_t: Latest accepted time-point.\n\n        Returns:\n            The log-likelihood of the (already stored) data, given the spread\n            prbabilities as well as the parameters for binomial distribtions\n            used to marginalize over diagnose times.\n        \"\"\"\n        # splitting theta into spread parameters and...\n        len_spread_probs = len(theta) - len(t_stages)\n        spread_probs = theta[:len_spread_probs]\n        # ...p-values for the binomial distribution\n        p = theta[len_spread_probs:]\n\n        if np.any(np.greater(p, 1.)) or np.any(np.less(p, 0.)):\n            return -np.inf\n\n        t = np.arange(max_t + 1)\n        time_dists = {}\n        for i,stage in enumerate(t_stages):\n            time_dists[stage] = fast_binomial_pmf(t, max_t, p[i])\n\n        return self.marginal_log_likelihood(\n            spread_probs, t_stages,\n            time_dists=time_dists\n        )\n\n\n    def risk(\n        self,\n        spread_probs: Optional[np.ndarray] = None,\n        inv: Dict[str, Optional[np.ndarray]] = {\"ipsi\": None, \"contra\": None},\n        diagnoses: Dict[str, Dict] = {\"ipsi\": {}, \"contra\": {}},\n        diag_time: Optional[int] = None,\n        time_dist: Optional[np.ndarray] = None,\n        mode: str = \"HMM\"\n    ) -> float:\n        \"\"\"Compute risk of ipsi- & contralateral involvement given specific (but\n        potentially incomplete) diagnoses for each side of the neck.\n\n        Args:\n            spread_probs: Set of new spread parameters. If not given (``None``),\n                the currently set parameters will be used.\n\n            inv: Dictionary that can have the keys ``\"ipsi\"`` and ``\"contra\"``\n                with the respective values being the involvements of interest.\n                If (for one side or both) no involvement of interest is given,\n                it'll be marginalized.\n                The array themselves may contain ``True``, ``False`` or ``None``\n                for each LNL corresponding to the risk for involvement, no\n                involvement and \"not interested\".\n\n            diagnoses: Dictionary that itself may contain two dictionaries. One\n                with key \"ipsi\" and one with key \"contra\". The respective value\n                is then a dictionary that can hold a potentially incomplete\n                (mask with ``None``) diagnose for every available modality.\n                Leaving out available modalities will assume a completely\n                missing diagnosis.\n\n            diag_time: Time of diagnosis. Either this or the `time_dist` to\n                marginalize over diagnose times must be given.\n\n            time_dist: Distribution to marginalize over diagnose times. Either\n                this, or the `diag_time` must be given.\n\n            mode: Set to ``\"HMM\"`` for the hidden Markov model risk (requires\n                the ``time_dist``) or to ``\"BN\"`` for the Bayesian network\n                version.\n        \"\"\"\n        if spread_probs is not None:\n            self.spread_probs = spread_probs\n\n        cX = {}   # marginalize over matching complete involvements.\n        cZ = {}   # marginalize over Z for incomplete diagnoses.\n        pXt = {}  # probability p(X|t) of state X at time t as 2D matrices\n        pD = {}   # probability p(D|X) of a (potentially incomplete) diagnose,\n                  # given an involvement. Should be a 1D vector\n\n        for side in [\"ipsi\", \"contra\"]:\n            involvement = np.array(inv[side])\n            # build vector to marginalize over involvements\n            cX[side] = np.zeros(shape=(len(self.system[side].state_list)),\n                                dtype=bool)\n            for i,state in enumerate(self.system[side].state_list):\n                cX[side][i] = np.all(\n                    np.equal(\n                        involvement, state,\n                        where=(involvement!=None),\n                        out=np.ones_like(involvement, dtype=bool)\n                    )\n                )\n\n            # create one large diagnose vector from the individual modalitie's\n            # diagnoses\n            obs = np.array([])\n            for mod in self.system[side]._spsn_tables:\n                if mod in diagnoses[side]:\n                    obs = np.append(obs, diagnoses[side][mod])\n                else:\n                    obs = np.append(obs, np.array([None] * len(self.system[side].lnls)))\n\n            # build vector to marginalize over diagnoses\n            cZ[side] = np.zeros(shape=(len(self.system[side].obs_list)),\n                                dtype=bool)\n            for i,complete_obs in enumerate(self.system[side].obs_list):\n                cZ[side][i] = np.all(\n                    np.equal(\n                        obs, complete_obs,\n                        where=(obs!=None),\n                        out=np.ones_like(obs, dtype=bool)\n                    )\n                )\n\n            if diag_time is not None:\n                pXt[side] = self.system[side]._evolve(diag_time)\n\n            elif time_dist is not None:\n                max_t = len(time_dist)\n                pXt[side] = self.system[side]._evolve(t_last=max_t-1)\n\n            else:\n                msg = (\"Either diagnose time or distribution to marginalize \"\n                       \"over it must be given.\")\n                raise ValueError(msg)\n\n            pD[side] = self.system[side].observation_matrix @ cZ[side]\n\n        # joint probability of Xi & Xc (marginalized over time). Acts as prior\n        # for p( Di,Dc | Xi,Xc ) and should be a 2D matrix\n        if diag_time is not None:\n            pXX = np.outer(pXt[\"ipsi\"], pXt[\"contra\"])\n\n        elif time_dist is not None:\n            # time-prior in diagnoal matrix form\n            PT = np.diag(time_dist)\n            pXX = pXt[\"ipsi\"].T @ PT @ pXt[\"contra\"]\n\n        # joint probability of all hidden states and the requested diagnosis\n        pDDXX = np.einsum(\"i,ij,j->ij\", pD[\"ipsi\"], pXX, pD[\"contra\"])\n        # joint probability of the requested involvement and diagnosis\n        pDDII = cX[\"ipsi\"].T @ pDDXX @ cX[\"contra\"]\n\n        # denominator p(Di, Dc). Joint probability for ipsi- & contralateral\n        # diagnoses. Marginalized over all hidden involvements and over all\n        # matching complete observations that give rise to the specific\n        # diagnose. The result should be just a number\n        pDD = (cZ[\"ipsi\"].T\n               @ self.ipsi.observation_matrix.T\n               @ pXX\n               @ self.contra.observation_matrix\n               @ cZ[\"contra\"])\n\n        return pDDII / pDD\n\n\n    def generate_dataset(\n        self,\n        num_patients: int,\n        stage_dist: List[float],\n        diag_times: Optional[Dict[Any, int]] = None,\n        time_dists: Optional[Dict[Any, np.ndarray]] = None,\n    ) -> pd.DataFrame:\n        \"\"\"Generate/sample a pandas :class:`DataFrame` from the defined network.\n\n        Args:\n            num_patients: Number of patients to generate.\n            stage_dist: Probability to find a patient in a certain T-stage.\n            diag_times: For each T-stage, one can specify until which time step\n                the corresponding patients should be evolved. If this is set to\n                ``None``, and a distribution over diagnose times ``time_dists``\n                is provided, the diagnose time is drawn from the ``time_dist``.\n            time_dists: Distributions over diagnose times that can be used to\n                draw a diagnose time for the respective T-stage.\n        \"\"\"\n        drawn_t_stages, drawn_diag_times = draw_diagnose_times(\n            num_patients=num_patients,\n            stage_dist=stage_dist,\n            diag_times=diag_times,\n            time_dists=time_dists\n        )\n\n        drawn_obs_ipsi = self.ipsi._draw_patient_diagnoses(drawn_diag_times)\n        drawn_obs_contra = self.contra._draw_patient_diagnoses(drawn_diag_times)\n        drawn_obs = np.concatenate([drawn_obs_ipsi, drawn_obs_contra], axis=1)\n\n        # construct MultiIndex for dataset from stored modalities\n        sides = [\"ipsi\", \"contra\"]\n        modalities = list(self.modalities.keys())\n        lnl_names = [lnl.name for lnl in self.ipsi.lnls]\n        multi_cols = pd.MultiIndex.from_product([sides, modalities, lnl_names])\n\n        # create DataFrame\n        dataset = pd.DataFrame(drawn_obs, columns=multi_cols)\n        dataset = dataset.reorder_levels(order=[1, 0, 2], axis=\"columns\")\n        dataset = dataset.sort_index(axis=\"columns\", level=0)\n        dataset[('info', 'tumor', 't_stage')] = drawn_t_stages\n\n        return dataset\n\n\nclass BilateralSystem(Bilateral):\n    \"\"\"Class kept for compatibility after renaming to :class:`Bilateral`.\n\n    See Also:\n        :class:`Bilateral`\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        msg = (\"This class has been renamed to `Bilateral`.\")\n        warnings.warn(msg, DeprecationWarning)\n\n        super().__init__(*args, **kwargs)", "meta": {"hexsha": "43e4ce266226270e9d7941383f6f50180acde90f", "size": 34383, "ext": "py", "lang": "Python", "max_stars_repo_path": "lymph/bilateral.py", "max_stars_repo_name": "lfranceschetti/lymph", "max_stars_repo_head_hexsha": "d7fc8c0709316fb1b055487f6c3c2165d889974a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lymph/bilateral.py", "max_issues_repo_name": "lfranceschetti/lymph", "max_issues_repo_head_hexsha": "d7fc8c0709316fb1b055487f6c3c2165d889974a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lymph/bilateral.py", "max_forks_repo_name": "lfranceschetti/lymph", "max_forks_repo_head_hexsha": "d7fc8c0709316fb1b055487f6c3c2165d889974a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1201866978, "max_line_length": 90, "alphanum_fraction": 0.5485850566, "include": true, "reason": "import numpy", "num_tokens": 7559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.1852035566802523}}
{"text": "#!/usr/bin/env python\n#\n#Copyright 2019 Allan Haldane.\n\n#This file is part of Mi3-GPU.\n\n#Mi3-GPU is free software: you can redistribute it and/or modify\n#it under the terms of the GNU General Public License as published by\n#the Free Software Foundation, version 3 of the License.\n\n#Mi3-GPU is distributed in the hope that it will be useful,\n#but WITHOUT ANY WARRANTY; without even the implied warranty of\n#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n#GNU General Public License for more details.\n\n#You should have received a copy of the GNU General Public License\n#along with Mi3-GPU.  If not, see <http://www.gnu.org/licenses/>.\n\n#Contact: allan.haldane _AT_ gmail.com\nimport sys, os, argparse\nfrom Bio.Alphabet import IUPAC\nimport seqload\nimport numpy as np\nfrom alphabet_reduction import getLq\n\ndef indmap(oldalpha, amap):\n    def ind(x):\n        for i in range(len(amap)):\n            if x in amap[i]:\n                return i\n        return 0\n\n    return  np.array([ind(let) for let in oldalpha])\n\ndef reduceSeqAlphaPerpos(seqs, newalphas, oldalpha, out=None):\n    rseqs = np.empty(seqs.shape, dtype=int)\n    for n,a in enumerate(newalphas):\n        conv = indmap(oldalpha, a)\n        rseqs[:,n] = conv[seqs[:,n]]\n\n    if out is None:\n        out = sys.stdout\n    seqload.writeSeqs(out, rseqs, \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", noheader=True)\n\ndef reduceBimAlphaPerpos(bimarg, newalphas, oldalpha, out):\n    if out is None:\n        raise ValueError('out argument required for bimarg reduction')\n\n    L, q = getLq(bimarg)\n    qout = len(newalphas[0])\n    nPairs = L*(L-1)//2\n\n    # strategy: compute index mapping array to use in add.at\n    maps = np.array([indmap(oldalpha, a) for a in newalphas])\n    qqmap = np.array([np.add.outer(qout*maps[i], maps[j]).ravel()\n                      for i in range(L-1) for j in range(i+1,L)])\n    nmap = np.broadcast_to(np.arange(nPairs, dtype=int)[:,None], (nPairs, q*q))\n\n    # allocate new bimarg\n    newbim = np.zeros((nPairs, qout*qout), dtype='f8')\n\n    # do the accumulation with `at`\n    np.add.at(newbim, (nmap, qqmap), bimarg)\n\n    # renormalize\n    newbim /= np.sum(newbim, axis=1, keepdims=True)\n\n    np.save(out, newbim.astype('f4'))\n\ndef main():\n    parser = argparse.ArgumentParser(\n                                description='Apply alphabet reduction to MSA')\n    parser.add_argument('file', help='either seq file or bimarg file')\n    parser.add_argument('alphamap')\n    parser.add_argument('--alpha', default='protgap')\n    parser.add_argument('--out')\n\n    args = parser.parse_args(sys.argv[1:])\n    alphabets = {'protein': IUPAC.protein.letters,\n                 'protgap': '-' + IUPAC.protein.letters,\n                 'charge': '0+-',\n                 'nuc': \"ACGT\"}\n    alpha = alphabets.get(args.alpha, args.alpha)\n\n    with open(args.alphamap) as f:\n        # assumed to be a file containing the output of alphabet reduction, but\n        # only for one reduction level.  Each line should look like:\n        # ALPHA8 -DNAGSQFMYCI E HWP K L R T V\n        newalphas = [a.split()[1:] for a in f.readlines()]\n\n    try:\n        bimarg = np.load(args.file)\n    except ValueError:\n        seqs = seqload.loadSeqs(args.file, alpha)[0]\n        reduceSeqAlphaPerpos(seqs, newalphas, alpha, args.out)\n    else:\n        reduceBimAlphaPerpos(bimarg, newalphas, alpha, args.out)\n\nif __name__ == '__main__':\n    main()\n\n", "meta": {"hexsha": "13097b127f38c80ac2a119005daec1cacb616852", "size": 3385, "ext": "py", "lang": "Python", "max_stars_repo_path": "helpers/mi3gpu/utils/apply_alphamap.py", "max_stars_repo_name": "carnevale-lab/torch_ising_vae", "max_stars_repo_head_hexsha": "f2b7b8581cf416e907c57f16b5eb7a9d86b31644", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "helpers/mi3gpu/utils/apply_alphamap.py", "max_issues_repo_name": "carnevale-lab/torch_ising_vae", "max_issues_repo_head_hexsha": "f2b7b8581cf416e907c57f16b5eb7a9d86b31644", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "helpers/mi3gpu/utils/apply_alphamap.py", "max_forks_repo_name": "carnevale-lab/torch_ising_vae", "max_forks_repo_head_hexsha": "f2b7b8581cf416e907c57f16b5eb7a9d86b31644", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1862745098, "max_line_length": 79, "alphanum_fraction": 0.6531757755, "include": true, "reason": "import numpy", "num_tokens": 930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.1852035566802523}}
{"text": "# Script for running MCMC sampling of EDF\n# Constructs mock sample, then re-samples the velocities\n\nimport sys, os\ndir_path = os.path.dirname(os.path.realpath(__file__))\nsys.path.append(dir_path+'/py/')\nimport edf_sampling\nimport json\nimport numpy as np\nimport emcee\nfrom itertools import izip\nimport pandas as pd\nimport subprocess\nimport pickle\n\n# default parameters\nnames = ['age', 'RcP', 'mass', 'vR', 'vphi', 'vz', 'I', 'l', 'b', 's',\n         'Z', 'Teff', 'logg', 'R', 'phi', 'z', 'vlos', 'pm_l', 'pm_b',\n         'RA', 'DEC', 'pm_ra', 'pm_dec', 'I', 'JR', 'Lz', 'Jz', 'Rc', 'logl']\n\ndef LogL_Zsample(*args):\n    return edf_sampling.LogL_sample(*args)\n\ndef deccut_fn(l,b,deccut):\n    ad = edf_sampling.check_dec(l,b)\n    if(deccut<np.pi):\n        if(deccut>0.):\n            if(ad<deccut-.5*np.pi):\n                return 0\n        if(deccut<0.):\n            if(ad>deccut+.5*np.pi):\n                return 0\n    return 0\n\ndef run_mcmc_sample(\n                 Nsamples, mag_band, maglimits,\n                 # Isochrone set -- currently probably only Padova will work in all cases\n                 which_iso='Padova',\n                 # Extra magnitudes to calculate\n                 extra_mags=None,\n                 # Introduce a colour cut\n                 color=None, colorlimits=None, \n                 # Coordinate cuts (in radians) -- remove everything |b|<modbcut\n                 # If deccut>0 cut all dec<deccut-pi/2\n                 # If deccut<0 cut all dec>deccut+pi/2\n                 modbcut=0.,deccut=2.*np.pi,\n                 # Spectroscopic parameter cut -- log10Teff\n                 logglimits=None,Tefflimits=None,fehlimits=None,\n                 # Flags for different options \n                 extinct=True, with_halo=True, interp=False,dered=False,\n                 # Debugging and outputting\n                 output_file=None,messages=True, extra_magnitudes=None,\n                 # Sampler parameters\n                 nwalkers=1000,Nburn=None,threads=1,thin=20,pt=False,ntemp=1,asampler=2.,\n                 # Adjust magnitude selection with a taper (1-break_grad(mag-break_pos))\n                 #break_pos=1000.,break_grad=1000.,\n                 # If cutting on error-convolved teff, logg and color -- currently won't do anything\n                 tgcolor_errs=np.array([0.,0.,0.])):\n\n    ''' \n\tDraws a Monte Carlo sample from an EDF model\n\t\n\tDraws Nsamples across the sky between magnitudes maglimits for band mag_band\n    '''\n    nsamples = int(Nsamples/nwalkers)+1\n   \n    # Turn on/off halo \n    if(with_halo):\n        edf_sampling.turn_on_halo()\n    else:\n        edf_sampling.turn_off_halo()\n\n    # -- Set arguments\n    check = lambda x: np.array([-10000.,10000.]) if x is None else x\n    checkcolor = lambda x: np.array(['J','K']) if x is None else color # as a default\n    args =[which_iso,mag_band,maglimits,extinct,interp,modbcut,deccut,check(color),\n           check(colorlimits),check(Tefflimits),check(logglimits),check(fehlimits)]\n    \n    # -- Set sampler\n    ndim, nwalker = 9, nwalkers\n    sampler = emcee.EnsembleSampler(nwalker, ndim,\n                                    LogL_Zsample, threads=threads,\n                                    args=args)\n    if(pt):\n        # Parallel tempering\n        sampler = emcee.PTSampler(ntemp, nwalker, ndim,los_magbox_LogL_sample_py, \n                                  logp, loglargs=llos_args, threads=threads)\n    # Initialize walkers\n    # Sample uniform in age, mass\n    # Sample gaussian in Z and velocities\n    # Sample exp in (unextincted) magnitude\n    lomag,himag=maglimits[0],maglimits[1]\n    Zlim=[-3.,1.]\n    if fehlimits is not None:\n        Zlim=fehcut\n    if not with_halo:\n        Zlim[0]=edf_sampling.minZ()\n        Zlim[1]=edf_sampling.maxZ()\n    p0 = np.random.uniform(\n        low=[0.2, Zlim[0], 0.5, -150., 50., -100., lomag, 0., modbcut],\n        high=[12., Zlim[1], 3.5, 150., 350., 100., himag, 2.*np.pi, np.pi /2.],\n        size=(nwalker, ndim))\n    p0[:,-1]*=(1.-2.*(np.random.uniform(low=0,high=1,size=nwalker)>0.5))\n    if fehlimits is not None:\n        meanZ,sigZ = 0.,.4\n        p0.T[1]=np.random.normal(size=nwalker)*sigZ+meanZ\n    meanV,sigV = 0.,50.\n    for i in range(3,6):\n        p0.T[i]=np.random.normal(size=nwalker)*sigV+meanV\n    p0.T[4]+=200.\n    p0.T[6]=trunc_exp_rv(lomag,himag,1.,size=len(p0))\n\n    # -- Only choose physically allowed masses for selected age, Z\n    for i in np.arange(len(p0)):\n        maxmass,minmass=0.,0.\n        maxmass = edf_sampling.check_highmass_Z(p0[i][0], p0[i][1],which_iso)\n        minmass = edf_sampling.check_lowmass_Z(p0[i][0], p0[i][1],which_iso)\n        while(maxmass < 0. or minmass<0. or \n\t      edf_sampling.check_radius_positive(p0[i][0], p0[i][1]) == 0 or \n              deccut_fn(p0[i][-2],p0[i][-1],deccut)):\n            p0[i][-3] = np.random.uniform(low=lomag, high=himag)\n            p0[i][1] = np.random.uniform(low=Zlim[0], high=Zlim[1])\n            p0[i][0] = np.random.uniform(low=0., high=12.)\n            maxmass = edf_sampling.check_highmass_Z(p0[i][0], p0[i][1],which_iso)\n            minmass = edf_sampling.check_lowmass_Z(p0[i][0], p0[i][1],which_iso)\n        MAXMASS=3.\n        if(maxmass>MAXMASS):\n            maxmass=MAXMASS\n        p0[i][2] = np.random.uniform(low=minmass, high=maxmass)\n        # Check other cuts satisfied\n        if(check(colorlimits)[0]>-10. or check(logglimits)[0]>-10. or check(Tefflimits)[0]>-10.):\n            while(edf_sampling.check_color_logg_cut(p0[i][0], p0[i][1], p0[i][2], \n                                                 0.,180.,checkcolor(color),\n\t\t\t\t\t\t check(colorlimits),check(logglimits),check(Tefflimits),\n\t\t\t\t\t\t which_iso,False)==0):\n                    p0[i][2] = np.random.uniform(low=minmass, high=maxmass)\n   \n    # Now wiggle the walkers a bit \n    err = [0.5,0.1,0.1,10.,10.,10.,0.1,0.01,0.01]\n    for i in np.arange(len(p0)):\n        extinctMag = edf_sampling.get_extinct(p0[i][-2],p0[i][-1],3.,mag_band)\n        if(extinctMag>err[-3]):\n            err[-3]=extinctMag\n        pp = edf_sampling.LogL_sample(p0[i],*args)\n        n=0\n        while(np.isinf(pp) and n<10000):\n            p0[i]=p0[np.random.randint(len(p0))]+np.random.normal(size=ndim)*err\n            pp = edf_sampling.LogL_sample(p0[i],*args)\n            n+=1\n        if(n==10000):\n            print \"Can't find start point:\",p0[i],deccut_fn(p0[i][-2],p0[i][-1],deccut)\n\n    if(messages): print 'Initial points sampled'\n    if(pt):\n        p0=np.reshape(p0,(ntemp,nwalker,ndim))\n\n    if(Nburn==None):\n        Nburn=2*thin*nsamples\n    # -- Run a burn-in\n    pos, prob, state = sampler.run_mcmc(p0, Nburn, storechain=False)\n    if messages: print 'Number of logl=-inf = '+str(len(prob[np.isinf(prob)]))\n    if messages: print(\"Burnt\")\n    sampler.reset()\n\n    # -- Sample with thinning and calculating dependent variables\n    pos, prob, state = sampler.run_mcmc(pos, nsamples*thin, thin=thin)\n    if messages: print (\"Sampled\")\n    flatchain = sampler.flatchain\n    lnprob = sampler.lnprobability\n    if(pt):\n        flatchain=flatchain[0]\n        lnprob=lnprob[0]\n    extras = np.array(\n        map(lambda i: edf_sampling.get_extra_data(i,mag_band,which_iso,False,extinct,interp), sampler.flatchain))\n    actions = np.array([edf_sampling.get_actions(np.concatenate((b[4:7], a[3:6])))\n                        for a, b in izip(flatchain, extras)])\n\n    nameslist = np.copy(names)\n    nameslist[1]=\"Z\"\n    nameslist[10]=\"RcP\"\n    nameslist[23]=mag_band\n    nameslist[6]=mag_band+\"0\"\n\n    if messages: print(\"Mean acceptance fraction:\", np.mean(sampler.acceptance_fraction))\n    everything = np.vstack((flatchain.T, extras.T,\n                     actions.T,lnprob.flatten())).T\n    if color is not None:\n        if extra_magnitudes is not None:\n            extra_magnitudes=np.unique(np.concatenate((color,extra_magnitudes,np.array([mag_band]))))\n        else:\n            extra_magnitudes=np.unique(np.concatenate((color,np.array([mag_band]))))\n        extra_magnitudes = extra_magnitudes[extra_magnitudes!=mag_band]\n    \n    if extra_magnitudes is not None:\n        extra_mags = np.array(\n        map(lambda i: edf_sampling.get_extra_magnitudes(i,\n                       mag_band, extra_magnitudes,which_iso, False, extinct,interp), flatchain))\n        nameslist=np.concatenate((nameslist,extra_magnitudes))\n        print extra_magnitudes\n        nameslist=np.concatenate((nameslist,np.array([e+'0' for e in list(extra_magnitudes)])))\n        everything = np.vstack((everything.T, extra_mags.T)).T\n    \n    df = pd.DataFrame(everything,columns=nameslist)\n    df = df.sample(Nsamples,replace=False).reset_index(drop=True)\n    if(output_file):\n        df.to_csv(output_file)\n    return df\n\ndef los_magbox_LogL_sample_py(*args):\n    return edf_sampling.los_magbox_LogL_sample(*args)\n\nimport scipy.stats\n\ndef trunc_exp_rv(lo, hi, scale, size):\n    low = 0.\n    high=hi-lo\n    rnd_cdf = np.random.uniform(scipy.stats.expon.cdf(x=low, scale=scale),\n                                scipy.stats.expon.cdf(x=high, scale=scale),\n                                size=size)\n    return hi-scipy.stats.expon.ppf(q=rnd_cdf, scale=scale)\n\ndef logp(p):\n    return 1.\n\ndef run_mcmc_los(Nsamples, l, b, mag_band, maglimits,\n                 # Field radius (in radians)\n                 fieldradius=-10.,\n                 # Isochrone set -- currently probably only Padova will work in all cases\n                 which_iso='Padova',\n                 # Extra magnitudes to calculate\n                 extra_mags=None,\n                 # Introduce a colour cut\n                 color=None, colorlimits=None, \n                 # Spectroscopic parameter cut\n                 logglimits=None,Tefflimits=None,\n                 # Flags for different options \n                 extinct=True, RcPorZ=False, with_halo=True, interp=False,dered=False,\n                 # Debugging and outputting\n                 output_file=None,messages=True, extra_magnitudes=None,\n                 # Sampler parameters\n                 nwalkers=1000,Nburn=None,threads=1,thin=20,pt=False,ntemp=1,asampler=2.,\n                 # Adjust magnitude selection with a taper (1-break_grad(mag-break_pos))\n                 break_pos=1000.,break_grad=1000.,\n                 # If cutting on error-convolved teff, logg and color\n                 tgcolor_errs=np.array([0.,0.,0.])):\n\n    ''' \n\tDraws a Monte Carlo sample from an EDF model\n\t\n\tDraws Nsamples in a field of radius \n        fieldradius (in radians) at (l,b) (in radians) between magnitudes maglimits for\n        band mag_band\n    '''\n    nsamples = int(Nsamples/nwalkers)+1\n\n    if(with_halo):\n        edf_sampling.turn_on_halo()\n    else:\n        edf_sampling.turn_off_halo()\n\n    if(np.fabs(b)<fieldradius/4.):\n        b+=fieldradius/2.\n\n    # -- Initialise walkers\n    ndim, nwalker = 7 + 2*(fieldradius>0), nwalkers\n    # Parameters for log-likelihood\n    check = lambda x: np.array([-10000.,10000.]) if x is None else x\n    checkcolor = lambda x: np.array(['J','K']) if x is None else color\n    llos_args =[np.array([l,b]), mag_band, maglimits, which_iso, RcPorZ, \n                checkcolor(color), check(colorlimits), check(logglimits), check(Tefflimits), \n                np.array([1*extinct,1*dered]), fieldradius,interp,\n                np.array([break_pos,break_grad]),tgcolor_errs]\n    ## Samplers \n    sampler = emcee.EnsembleSampler(nwalker, ndim,los_magbox_LogL_sample_py, \n                                    args=llos_args, threads=threads,a=asampler)\n    if(pt):\n        # Parallel tempering\n        sampler = emcee.PTSampler(ntemp, nwalker, ndim,los_magbox_LogL_sample_py, \n                                  logp, loglargs=llos_args, threads=threads)\n    # Either sample in birth radius or metallicity -- birth radius sampling obsolete but good for checks\n    RorZlim=[0.,18.]\n    if(RcPorZ==False):\n        RorZlim=[-1.,0.6]\n        if not with_halo:\n            RorZlim[0]=edf_sampling.minZ()\n            RorZlim[1]=edf_sampling.maxZ()\n    \n    # Sample uniform in age, mass\n    # Sample gaussian in Z and velocities\n    # Sample exp in (unextincted) magnitude\n    meanZ,sigZ = 0.,.4\n    meanV,sigV = 0.,50.\n    #     age  Z           mass  vr     vphi    vz   mag\n    lo = [0.5, RorZlim[0], 0.5, -150., -200., -150., maglimits[0]]\n    hi = [12., RorZlim[1], 2.,   150.,  200.,  150., maglimits[1]]\n    if(fieldradius>0.):\n        # also sample in l,b \n        hi=np.concatenate((hi,[l,b]))\n        lo=np.concatenate((lo,[l,b]))\n    # Initial sample\n    p0 = np.random.uniform(low=lo,high=hi,size=(nwalker*ntemp, ndim))\n    p0.T[1]=np.random.normal(size=(nwalker*ntemp))*sigZ+meanZ # metallicity\n    for i in range(3,6):\n        # velocities\n        p0.T[i]=np.random.normal(size=(nwalker*ntemp))*sigV+meanV\n    p0.T[4]+=200. # shift vphi\n    # magnitudes\n    p0.T[6]=trunc_exp_rv(maglimits[0],maglimits[1],1.,size=len(p0))\n\n    # -- Only choose physically allowed masses for selected age, Z\n    for i in np.arange(len(p0)):\n        maxmass,minmass=0.,0.\n        check_highmass_fn = edf_sampling.check_highmass_Z\n        check_lowmass_fn = edf_sampling.check_lowmass_Z\n        if(RcPorZ==True):\n            check_highmass_fn = edf_sampling.check_highmass\n            check_lowmass_fn = edf_sampling.check_lowmass\n        maxmass = check_highmass_fn(p0[i][0], p0[i][1],which_iso)\n        minmass = check_lowmass_fn(p0[i][0], p0[i][1],which_iso)\n\n        while(maxmass < 0. or minmass<0. or \n              edf_sampling.check_radius_positive(p0[i][0], p0[i][1]) == 0):\n            p0[i][1] = np.random.uniform(low=RorZlim[0], high=RorZlim[1])\n            maxmass = check_highmass_fn(p0[i][0], p0[i][1],which_iso)\n            minmass = check_lowmass_fn(p0[i][0], p0[i][1],which_iso)\n        MAXMASS=3.\n        if(maxmass>MAXMASS):\n            maxmass=MAXMASS\n        p0[i][2] = np.random.uniform(low=minmass, high=maxmass)\n        # Check other cuts satisfied\n        if(check(colorlimits)[0]>-10. or check(logglimits)[0]>-10. or check(Tefflimits)[0]>-10.):\n            while(edf_sampling.check_color_logg_cut(p0[i][0], p0[i][1], p0[i][2], \n                                                 0.,180.,checkcolor(color),\n\t\t\t\t\t\t check(colorlimits),check(logglimits),check(Tefflimits),\n\t\t\t\t\t\t which_iso,False)==0):\n                p0[i][2] = np.random.uniform(low=minmass, high=maxmass)\n\n    # Got reasonable starting points but now want to shuffle slightly to ensure\n    err = [0.5,0.1,0.1,10.,10.,10.,0.1]\n    # Shuffle by extinction if large\n    max_distance=3.\n    extinctBand = edf_sampling.get_extinct(l,b,max_distance,mag_band)\n    if(extinct>err[-1]):\n        err[-1]=extinctBand\n    if(fieldradius>0.):\n        err=np.concatenate((err,[0.,0.]))\n    # Shuffle\n    for i in np.arange(len(p0)):\n        pp = los_magbox_LogL_sample_py(p0[i],*llos_args)\n        n,maxn=0,10000\n        while(np.isinf(pp) and n<maxn):\n            p0[i]=p0[np.random.randint(len(p0))]+np.random.normal(size=ndim)*err\n            pp = los_magbox_LogL_sample_py(p0[i],*llos_args)\n            n+=1\n        if(n==maxn):\n            print 'No finite LogL found:', p0[i]\n    ## Now sample l and b if needed\n    if(fieldradius>0.):\n        rad = np.random.uniform(size=len(p0))*fieldradius\n        thet = np.random.uniform(size=len(p0))*2.*np.pi\n        p0.T[7]=l+np.cos(thet)*rad/np.cos(b)\n        p0.T[8]=b+np.sin(thet)*rad\n\n    if(messages): print 'Initial points sampled'\n    if(pt):\n        p0=np.reshape(p0,(ntemp,nwalker,ndim))\n    # -- Run a burn-in\n    Nb=16000\n    if(Nburn):\n        Nb=Nburn\n    else:\n        Nb=nsamples*thin*2\n    pos, prob, state = sampler.run_mcmc(p0, Nb, storechain=False)\n    if(messages):\n        print 'Number of logl=-inf = '+str(len(prob[np.isinf(prob)]))\n        print(\"Burnt\")\n    sampler.reset()\n\n    # -- Sample with thinning and calculating dependent variables\n    pos, prob, state = sampler.run_mcmc(pos, nsamples*thin, thin=thin)\n    flatchain = sampler.flatchain\n    lnprob = sampler.lnprobability\n    if(pt):\n        flatchain=flatchain[0]\n        lnprob=lnprob[0]\n\n    extras = np.array(\n        map(lambda i: edf_sampling.get_extra_data(i if fieldradius>0. else np.append(i,[l,b]), \n                       mag_band, which_iso, RcPorZ, extinct,interp), flatchain))\n    actions = np.array([edf_sampling.get_actions(np.concatenate((j[4:7], i[3:6])))\n                        for i,j in izip(flatchain, extras)])\n\n    nameslist = np.copy(names)\n    if(RcPorZ==False):\n        nameslist[1]=\"Z\"\n        nameslist[10]=\"RcP\"\n    nameslist[23]=mag_band\n    nameslist[6]=mag_band+\"0\"\n    \n    LB = np.reshape(np.tile([l,b],len(flatchain)),(len(flatchain),2))\n    everything = np.vstack((flatchain.T, LB.T, extras.T,\n                 actions.T,lnprob.flatten())).T\n    if fieldradius>0.:\n        everything = np.vstack((flatchain.T, extras.T,\n                 actions.T,lnprob.flatten())).T\n\n    if color is not None:\n        if extra_magnitudes is not None:\n            extra_magnitudes=np.unique(np.concatenate((color,extra_magnitudes,np.array([mag_band]))))\n        else:\n            extra_magnitudes=np.unique(np.concatenate((color,np.array([mag_band]))))\n        extra_magnitudes = extra_magnitudes[extra_magnitudes!=mag_band]\n    \n    if extra_magnitudes is not None:\n        extra_mags = np.array(\n        map(lambda i: edf_sampling.get_extra_magnitudes(i if fieldradius>0. else np.append(i,[l,b]),\n                       mag_band, extra_magnitudes,which_iso, RcPorZ, extinct,interp), flatchain))\n        nameslist=np.concatenate((nameslist,extra_magnitudes))\n        print extra_magnitudes\n        nameslist=np.concatenate((nameslist,np.array([e+'0' for e in list(extra_magnitudes)])))\n        everything = np.vstack((everything.T, extra_mags.T)).T\n\n    if(messages): print(\"Mean acceptance fraction:\", np.mean(sampler.acceptance_fraction))\n    df=pd.DataFrame(everything,columns=nameslist)\n    df = df.sample(Nsamples,replace=False).reset_index(drop=True)\n    if(output_file):\n        df.to_csv(output_file)\n    return df\n\nfrom sklearn.neighbors import KDTree\n\ndef add_errors_to_sample(sample,data,\n                         data_tree_fields = ['Teff_K','logg_K','Met_N_K_DR5'],\n                         sample_tree_fields = ['Teff','logg','Z'],\n                         err_fields = {'Teff':'eTeff_K',\n                                       'logg':'elogg_K',\n                                       'Z':'eMet_N_K',\n                                       'vlos':'eHRV'},\n                         leaf_size=10):\n    '''\n        Add errors to a mock sample\n        sample -- sample catalogue\n        data -- data\n        data_tree_fields -- the data entries used to construct the tree\n        sample_tree_fields -- the sample entries corresponding to the data used\n                              to generate the tree\n        err_fields -- a dictionary of the fields to add errors to in the keys\n                      and the corresponding error fields in the data\n    '''\n    # Build tree\n    data_tr = data[data_tree_fields]\n    m,s = data_tr.mean(), data_tr.std()\n    data_tr = (data_tr-m)/s\n    kdt = KDTree(data_tr, leaf_size=leaf_size, metric='euclidean')\n    RAVE_dd = (sample[sample_tree_fields].values-m.values)/s.values\n\n    index = kdt.query(RAVE_dd, k=1, return_distance=False)\n    for k,e in err_fields.items():\n        sample['e'+k]=data[e].take(index.flatten()).values\n        sample[k+'_e']=np.random.normal(size=len(sample))*sample['e'+k]+sample[k]\n\n    return sample\n\ndef add_errors_to_sample_astrometry_covariance(sample,data,\n                         data_tree_fields = ['BVmag','Vmag','l','b'],\n                         sample_tree_fields = ['BV','V','l','b'],\n                         err_fields = {'B':'Bmag','V':'Vmag'},\n                         leaf_size=10):\n    '''\n        Add errors to a mock sample\n        sample -- sample catalogue\n        data -- data\n        data_tree_fields -- the data entries used to construct the tree\n        sample_tree_fields -- the sample entries corresponding to the data used\n                              to generate the tree\n        err_fields -- a dictionary of the fields to add errors to in the keys\n                      and the corresponding error fields in the data\n        Will also use tree fields to assign covariant astrometry errors\n    '''\n    # Build tree\n    data_tr = data[data_tree_fields]\n    m,s = data_tr.mean(), data_tr.std()\n    data_tr = (data_tr-m)/s\n    kdt = KDTree(data_tr, leaf_size=leaf_size, metric='euclidean')\n    sample_dd = (sample[sample_tree_fields].values-m.values)/s.values\n\n    sample['parallax'] = 1./sample['s']\n\n    index = kdt.query(sample_dd, k=1, return_distance=False)\n    ## First photometry\n    for k,e in err_fields.items():\n        sample['e'+k]=data[e].take(index.flatten()).values\n        sample[k+'_e']=np.random.normal(size=len(sample))*sample['e'+k]+sample[k]\n    ## Now astrometry\n    cov = np.array([[data.parallax_error.values**2,\n        data.parallax_pmra_corr.values*data.parallax_error.values*data.pmra_error.values,\n        data.parallax_pmdec_corr.values*data.parallax_error.values*data.pmdec_error.values],\n       [data.parallax_pmra_corr.values*data.parallax_error.values*data.pmra_error.values,\n        data.pmra_error.values**2,\n        data.pmra_pmdec_corr.values*data.pmra_error.values*data.pmdec_error.values],\n       [data.parallax_pmdec_corr.values*data.parallax_error.values*data.pmdec_error.values,\n        data.pmra_pmdec_corr.values*data.pmra_error.values*data.pmdec_error.values,\n        data.pmdec_error.values**2]]).T\n    #DD = np.array(map(lambda x: np.random.multivariate_normal(np.zeros(3),x),\n    #        cov[index.flatten()]))\n    DD = np.einsum('jik,jk->ji',np.linalg.cholesky(cov[index.flatten()]),\n                                np.random.normal(size=(len(sample),3)))\n    for i,p in enumerate(['parallax','pm_ra','pm_dec']):\n        sample[p+'_e']=DD[:,i]+sample[p]\n        sample['e'+p]=np.sqrt(cov[index.flatten()][:,i,i])\n    sample['parallax_pmra_corr']=cov[index.flatten()][:,1,0]/np.sqrt(cov[index.flatten()][:,0,0]*cov[index.flatten()][:,1,1])\n    sample['parallax_pmdec_corr']=cov[index.flatten()][:,2,0]/np.sqrt(cov[index.flatten()][:,0,0]*cov[index.flatten()][:,2,2])\n    sample['pmra_pmdec_corr']=cov[index.flatten()][:,1,2]/np.sqrt(cov[index.flatten()][:,2,2]*cov[index.flatten()][:,1,1])\n    return sample\n\ndef compute_velocities_actions_with_errors(sample):\n    '''\n        compute the velocities and actions of a sample with erroneous\n        quantities.\n        sample must have fields RA, DEC, s_e, vlos_e, pm_ra_e, pm_dec_e\n\n        NEED TO RUN edf_sampling.setup first\n\n    '''\n\n    fields =['PMl_e','PMb_e','R_e','phi_e','z_e','vR_e','vphi_e','vz_e','JR_e','Lz_e','Jz_e','Rc_e']\n    for f in fields:\n        sample[f]=np.ones(len(sample))*-9999.\n\n    for i in range(len(sample)):\n        if(sample['s_e'][i]>0. and sample['s_e'][i]==sample['s_e'][i]):\n            X = edf_sampling.process_data(\n                np.array([sample['RA'][i],     sample['DEC'][i],\n                          sample['s_e'][i],    sample['vlos_e'][i],\n                          sample['pm_ra_e'][i],sample['pm_dec_e'][i]]))\n            sample['PMl_e'][i],sample['PMb_e'][i]=X[4],X[5]\n            sample['R_e'][i],sample['phi_e'][i],sample['z_e'][i]=X[6],X[7],X[8]\n            sample['vR_e'][i],sample['vphi_e'][i],sample['vz_e'][i]=X[9],X[10],X[11]\n            sample['JR_e'][i],sample['Lz_e'][i],sample['Jz_e'][i],sample['Rc'][i]=X[12],X[13],X[14],X[15]\n\n    return sample\n\n\ndef compute_velocities_with_errors(sample):\n    '''\n        compute the velocities and actions of a sample with erroneous\n        quantities.\n        sample must have fields RA, DEC, s_e, vlos_e, pm_ra_e, pm_dec_e\n    '''\n\n    fields =['PMl_e','PMb_e','R_e','phi_e','z_e','vR_e','vphi_e','vz_e','JR_e','Lz_e','Jz_e','Rc_e']\n    for f in fields:\n        sample[f]=np.ones(len(sample))*-9999.\n\n    for i in range(len(sample)):\n        if(sample['s_e'][i]>0. and sample['s_e'][i]==sample['s_e'][i]):\n            X = edf_sampling.process_data(\n                np.array([sample['RA'][i],     sample['DEC'][i],\n                          sample['s_e'][i],    sample['vlos_e'][i],\n                          sample['pm_ra_e'][i],sample['pm_dec_e'][i]]))\n            sample['PMl_e'][i],sample['PMb_e'][i]=X[4],X[5]\n            sample['R_e'][i],sample['phi_e'][i],sample['z_e'][i]=X[6],X[7],X[8]\n            sample['vR_e'][i],sample['vphi_e'][i],sample['vz_e'][i]=X[9],X[10],X[11]\n            sample['JR_e'][i],sample['Lz_e'][i],sample['Jz_e'][i],sample['Rc'][i]=X[12],X[13],X[14],X[15]\n\n    return sample\n", "meta": {"hexsha": "5d5932097398ebde356fb5db1308eb7ed199138f", "size": 24553, "ext": "py", "lang": "Python", "max_stars_repo_path": "edf_sampling/edf_samplers.py", "max_stars_repo_name": "ktfm2/Kai_updates", "max_stars_repo_head_hexsha": "f731922d3e140c1f16ea9b4b45f39232fe19a1ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-30T02:33:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-30T02:33:45.000Z", "max_issues_repo_path": "edf_sampling/edf_samplers.py", "max_issues_repo_name": "ktfm2/Kai_updates", "max_issues_repo_head_hexsha": "f731922d3e140c1f16ea9b4b45f39232fe19a1ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "edf_sampling/edf_samplers.py", "max_forks_repo_name": "ktfm2/Kai_updates", "max_forks_repo_head_hexsha": "f731922d3e140c1f16ea9b4b45f39232fe19a1ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-09-26T05:15:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-27T21:10:11.000Z", "avg_line_length": 43.30335097, "max_line_length": 126, "alphanum_fraction": 0.5970349855, "include": true, "reason": "import numpy,import scipy", "num_tokens": 6912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.29746994883293104, "lm_q1q2_score": 0.18516294540319614}}
{"text": "import sys, os\nimport time\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.utils import data\nfrom parsers import parse_a3m, read_templates\nfrom TrunkModel  import TrunkModule\nimport util\nfrom collections import namedtuple\nfrom ffindex import *\nfrom kinematics import xyz_to_c6d, c6d_to_bins2, xyz_to_t2d\nfrom trFold import TRFold\n\nNBIN = [37, 37, 37, 19]\n\nMODEL_PARAM ={\n        \"n_module\"     : 8,\n        \"n_module_str\" : 4,\n        \"n_layer\"      : 1,\n        \"d_msa\"        : 384 ,\n        \"d_pair\"       : 288,\n        \"d_templ\"      : 64,\n        \"n_head_msa\"   : 12,\n        \"n_head_pair\"  : 8,\n        \"n_head_templ\" : 4,\n        \"d_hidden\"     : 64,\n        \"r_ff\"         : 4,\n        \"n_resblock\"   : 1,\n        \"p_drop\"       : 0.0,\n        \"use_templ\"    : True,\n        \"performer_N_opts\": {\"nb_features\": 64},\n        \"performer_L_opts\": {\"nb_features\": 64}\n        }\n\nSE3_param = {\n        \"num_layers\"    : 3,\n        \"num_channels\"  : 16,\n        \"num_degrees\"   : 2,\n        \"l0_in_features\": 32,\n        \"l0_out_features\": 8,\n        \"l1_in_features\": 3,\n        \"l1_out_features\": 2,\n        \"num_edge_features\": 32,\n        \"div\": 2,\n        \"n_heads\": 4\n        }\nMODEL_PARAM['SE3_param'] = SE3_param\n\n# params for the folding protocol\nfold_params = {\n    \"SG7\"     : np.array([[[-2,3,6,7,6,3,-2]]])/21,\n    \"SG9\"     : np.array([[[-21,14,39,54,59,54,39,14,-21]]])/231,\n    \"DCUT\"    : 19.5,\n    \"ALPHA\"   : 1.57,\n    \n    # TODO: add Cb to the motif\n    \"NCAC\"    : np.array([[-0.676, -1.294,  0.   ],\n                          [ 0.   ,  0.   ,  0.   ],\n                          [ 1.5  , -0.174,  0.   ]], dtype=np.float32),\n    \"CLASH\"   : 2.0,\n    \"PCUT\"    : 0.5,\n    \"DSTEP\"   : 0.5,\n    \"ASTEP\"   : np.deg2rad(10.0),\n    \"XYZRAD\"  : 7.5,\n    \"WANG\"    : 0.1,\n    \"WCST\"    : 0.1\n}\n\nfold_params[\"SG\"] = fold_params[\"SG9\"]\n\nclass Predictor():\n    def __init__(self, model_dir=None, device=\"cuda:0\"):\n        if model_dir == None:\n            self.model_dir = \"%s/models\"%(os.path.dirname(os.path.realpath(__file__)))\n        else:\n            self.model_dir = model_dir\n        #\n        # define model name\n        self.model_name = \"BFF\"\n        self.device = device\n        self.active_fn = nn.Softmax(dim=1)\n\n        # define model & load model\n        self.model = TrunkModule(**MODEL_PARAM).to(self.device)\n        could_load = self.load_model(self.model_name)\n        if not could_load:\n            print (\"ERROR: failed to load model\")\n            sys.exit()\n\n    def load_model(self, model_name, suffix='last'):\n        chk_fn = \"%s/%s_%s.pt\"%(self.model_dir, model_name, suffix)\n        print (chk_fn)\n        if not os.path.exists(chk_fn):\n            return False\n        checkpoint = torch.load(chk_fn, map_location=self.device)\n        self.model.load_state_dict(checkpoint['model_state_dict'])\n        return True\n    \n    def predict(self, a3m_fn, out_prefix, hhr_fn=None, atab_fn=None, window=150, shift=50, n_latent=128):\n        msa_orig = parse_a3m(a3m_fn)\n        N, L = msa_orig.shape\n        #\n        if os.path.exists(hhr_fn):\n            xyz_t, t1d, t0d = read_templates(L, ffdb, hhr_fn, atab_fn, n_templ=10)\n        else:\n            xyz_t = torch.full((1, L, 3, 3), np.nan).float()\n            t1d = torch.zeros((1, L, 1)).float()\n            t0d = torch.zeros((1,3)).float()\n        #\n        # template features\n        xyz_t = xyz_t.float().unsqueeze(0)\n        t1d = t1d.float().unsqueeze(0)\n        t0d = t0d.float().unsqueeze(0)\n        t2d = xyz_to_t2d(xyz_t, t0d)\n       \n        self.model.eval()\n        for i_trial in range(10):\n            self.run_prediction(msa_orig, t1d, t2d, \"%s_%02d\"%(out_prefix, i_trial), n_latent=n_latent)\n            torch.cuda.empty_cache()\n    def run_prediction(self, msa_orig, t1d, t2d, out_prefix, n_latent=128):\n        N, L = msa_orig.shape\n        with torch.no_grad():\n            #\n            msa = torch.tensor(msa_orig).long() # (N, L)\n            random_idx = torch.randperm(N-1)\n            msa = torch.cat([msa[:1,:], msa[1:,:][random_idx]], dim=0).view(1, N, L)\n            #\n            if n_latent < N:\n                msa_latent = msa[:,:n_latent]\n                msa_extra = msa[:,n_latent:,:]\n            else:\n                msa_latent = msa\n                msa_extra = msa[:,:1,:]\n            msa_extra = msa_extra[:,:10000]\n            print (msa_latent.shape, msa_extra.shape, N, L)\n            #\n            idx_pdb = torch.arange(L).long().view(1, L)\n            #\n            msa_latent = msa_latent.to(self.device)\n            msa_extra = msa_extra.to(self.device)\n            seq = msa_latent[:,0]\n            idx_pdb = idx_pdb.to(self.device)\n            t1d = t1d.to(self.device)\n            t2d = t2d.to(self.device)\n            with torch.cuda.amp.autocast(enabled=True):\n                logit_s, init_crds, pred_lddt = self.model(msa_latent, msa_extra, seq, idx_pdb, t1d=t1d, t2d=t2d)\n            prob_s = list()\n            for logit in logit_s:\n                prob = self.active_fn(logit.float()) # distogram\n                prob = prob.reshape(-1, L, L) #.permute(1,2,0).cpu().numpy()\n                prob_s.append(prob)\n        \n        for prob in prob_s:\n            prob += 1e-8\n            prob = prob / torch.sum(prob, dim=0)[None]\n        self.write_pdb(seq[0], init_crds[0], Bfacts=pred_lddt[0], prefix=\"%s_init\"%(out_prefix))\n        xyz = init_crds[0, :, 1] # initial ca coordinates\n        TRF = TRFold(prob_s, fold_params)\n        xyz = TRF.fold(xyz, batch=45, lr=0.1, nsteps=200)\n        self.write_pdb(seq[0], xyz, prefix=\"%s\"%(out_prefix), Bfacts=pred_lddt[0])\n\n        prob_s = [prob.permute(1,2,0).detach().cpu().numpy().astype(np.float16) for prob in prob_s]\n        np.savez_compressed(\"%s.npz\"%(out_prefix), dist=prob_s[0].astype(np.float16), \\\n                            omega=prob_s[1].astype(np.float16),\\\n                            theta=prob_s[2].astype(np.float16),\\\n                            phi=prob_s[3].astype(np.float16))\n\n                    \n    def write_pdb(self, seq, atoms, Bfacts=None, prefix=None):\n        L = len(seq)\n        filename = \"%s.pdb\"%prefix\n        ctr = 1\n        with open(filename, 'wt') as f:\n            if Bfacts == None:\n                Bfacts = np.zeros(L)\n            else:\n                Bfacts = torch.clamp( Bfacts, 0, 1)\n            \n            for i,s in enumerate(seq):\n                if (len(atoms.shape)==2):\n                    f.write (\"%-6s%5s %4s %3s %s%4d    %8.3f%8.3f%8.3f%6.2f%6.2f\\n\"%(\n                            \"ATOM\", ctr, \" CA \", util.num2aa[s], \n                            \"A\", i+1, atoms[i,0], atoms[i,1], atoms[i,2],\n                            1.0, Bfacts[i] ) )\n                    ctr += 1\n\n                elif atoms.shape[1]==3:\n                    for j,atm_j in enumerate((\" N  \",\" CA \",\" C  \")):\n                        f.write (\"%-6s%5s %4s %3s %s%4d    %8.3f%8.3f%8.3f%6.2f%6.2f\\n\"%(\n                                \"ATOM\", ctr, atm_j, util.num2aa[s], \n                                \"A\", i+1, atoms[i,j,0], atoms[i,j,1], atoms[i,j,2],\n                                1.0, Bfacts[i] ) )\n                        ctr += 1                \n        \ndef get_args():\n    #DB=\"/home/robetta/rosetta_server_beta/external/databases/trRosetta/pdb100_2021Mar03/pdb100_2021Mar03\"\n    DB = \"/projects/ml/TrRosetta/pdb100_2020Mar11/pdb100_2020Mar11\"\n    import argparse\n    parser = argparse.ArgumentParser(description=\"RoseTTAFold: Protein structure prediction with 3-track attentions on 1D, 2D, and 3D features\")\n    parser.add_argument(\"a3m_fn\", help=\"input MSA in a3m format\")\n    parser.add_argument(\"out_prefix\", help=\"prefix for output file. [out_prefix].npz file will be generated\")\n    parser.add_argument(\"hhr_fn\",\n                        help=\"HHsearch result file in hhr format\")\n    parser.add_argument(\"atab_fn\",\n                        help=\"HHsearch result file in atab format\")\n    parser.add_argument(\"-db\", default=DB, required=False, \n                        help=\"HHsearch database [%s]\"%DB)\n    args = parser.parse_args()\n    return args\n\nif __name__ == \"__main__\":\n    args = get_args()\n    if not os.path.exists(\"%s.npz\"%args.out_prefix):\n        FFDB = args.db\n        FFindexDB = namedtuple(\"FFindexDB\", \"index, data\")\n        ffdb = FFindexDB(read_index(FFDB+'_pdb.ffindex'),\n                         read_data(FFDB+'_pdb.ffdata'))\n        pred = Predictor()\n        pred.predict(args.a3m_fn, args.out_prefix, args.hhr_fn, args.atab_fn)\n", "meta": {"hexsha": "2627fe14a6e44cdc400c90df333f752bb7d8cfc7", "size": 8509, "ext": "py", "lang": "Python", "max_stars_repo_path": "hallucination/models/rf_perceiver_v00/predict_tbm.py", "max_stars_repo_name": "guyujun/RFDesign", "max_stars_repo_head_hexsha": "3eac8aa5e5a58beeb6bdacc3e38ad1300b2eaff0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-13T00:58:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T04:14:05.000Z", "max_issues_repo_path": "hallucination/models/rf_perceiver_v00/predict_tbm.py", "max_issues_repo_name": "ZhuofanShen/RFDesign", "max_issues_repo_head_hexsha": "9fea2bafbbb7cbf702c9884e8b3ec69ed50ff2f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hallucination/models/rf_perceiver_v00/predict_tbm.py", "max_forks_repo_name": "ZhuofanShen/RFDesign", "max_forks_repo_head_hexsha": "9fea2bafbbb7cbf702c9884e8b3ec69ed50ff2f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5022624434, "max_line_length": 144, "alphanum_fraction": 0.5254436479, "include": true, "reason": "import numpy", "num_tokens": 2544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.29746993014852224, "lm_q1q2_score": 0.18516293377291157}}
{"text": "import contextlib\nimport os\nimport pathlib\nimport tempfile\nfrom dataclasses import dataclass\nfrom typing import Optional, Union\n\nimport isce3\nimport numpy as np\nfrom isce3.ext.isce3.unwrap import _snaphu_unwrap\n\n\n@dataclass(frozen=True)\nclass TopoCostParams:\n    r\"\"\"Configuration parameters for SNAPHU \"topo\" cost mode\n\n    Unwrapped phase is modelled as a topographic SAR interferometry signal\n    in additive phase noise.\n\n    Backscatter brightness is modelled according to the scattering model:\n\n    .. math::\n\n        \\sigma^0 = C * \\left( kds * \\cos \\theta_{inc} +\n                \\cos ^n (2 \\theta_{inc}) \\right) * \\cos \\theta_{inc}\n\n    where :math:`C` is a scaling factor, :math:`kds` is the ratio of diffuse to\n    specular scattering, :math:`\\theta_{inc}` is the local incidence angle, and\n    :math:`n` (input parameter `specular_exp`) is the power to which the\n    specular cosine term is raised.\n\n    Attributes\n    ----------\n    bperp : float\n        Perpendicular baseline length, in meters. If the value is negative,\n        increasing phase implies increasing topographic height.\n    near_range : float\n        Slant range from platform to the first range bin, in meters.\n    dr, da : float\n        Range & azimuth bin spacing after any multi-looking, in meters.\n    range_res, az_res : float\n        Single-look range & azimuth resolution, in meters.\n    wavelength : float\n        Wavelength, in meters.\n    transmit_mode : {\"pingpong\", \"repeat_pass\", \"single_antenna_transmit\"}\n        Radar transmit mode. 'pingpong' and 'repeat_pass' modes indicate that\n        both antennas both transmitted and received. Both modes have the same\n        effect in the algorithm. 'single_antenna_transmit' indicates that a\n        single antenna was used to transmit while both antennas received. In\n        this mode, the baseline is effectively halved.\n    altitude : float\n        Platform altitude relative to the Earth's surface, in meters.\n    earth_radius : float, optional\n        Local Earth radius, in meters. A spherical-Earth model is used.\n        (default: 6378000.0)\n    kds : float, optional\n        Ratio of diffuse to specular scattering. (default: 0.02)\n    specular_exp : float, optional\n        Power specular scattering component. Larger values imply a sharper peak\n        for specular scatter. (default: 8.0)\n    dzr_crit_factor : float, optional\n        Multiplicative factor applied to diffuse scatter term in evaluating\n        crossover point between diffuse and specular scatter in terms of range\n        slope. (default: 2.0)\n    shadow : bool, optional\n        Allow discontinuities from shadowing? If this is disabled, the minimum\n        topographic slope estimated from mean backscatter intensity is clipped\n        to the value of `dz_ei_min`. (default: False)\n    dz_ei_min : float, optional\n        Minimum slope expected in the absence of layover, in meters per\n        slant-range pixel. (default: -4.0)\n    lay_width : int, optional\n        Width of window (number of pixels) for summing layover brightness.\n        (default: 16)\n    lay_min_ei : float, optional\n        Threshold brightness (normalized) for assuming layover. (default: 1.25)\n    slope_ratio_factor : float, optional\n        Multiplicative factor applied to kds in order to get ratio of slopes for\n        linearized scattering model. The term improves agreement of the\n        piecewise-linear model with the cosine model near the transition point\n        (dzrcrit) at the expense of poorer agreement at very large slopes.\n        (default: 1.18)\n    sigsq_ei : float, optional\n        Variance of range slopes due to uncertainties in slope estimation from\n        brightness, in (meters/pixel)^2. (default: 100.0)\n    drho : float, optional\n        Step size for calculating lookup table of maximum layover slope based on\n        measured correlation. (default: 0.005)\n    dz_lay_peak : float, optional\n        Layover peak location, in meters/pixel. (default: -2.0)\n    azdz_factor : float, optional\n        Factor applied to range layover probability density to get azimuth\n        layover probability density. (default: 0.99)\n    dz_ei_factor : float, optional\n        Factor applied to slope expected from brightness without layover. Can\n        account for underestimation of brightness from averaging with\n        neighboring dark pixels when despeckling. (default: 4.0)\n    dz_ei_weight : float, optional\n        Weight applied to slope expected from brightness without layover. Must\n        be between zero and one. Can reduce influence of intensity on\n        non-layover slope. This is useful if there are lots of non-topographic\n        variations in brightness (i.e. changes in surface reflectivity).\n        (default: 0.5)\n    dz_lay_factor : float, optional\n        Factor applied to slope expected from brightness with layover. Can\n        account for underestimation of brightness from averaging with\n        neighboring dark pixels when despeckling. (default: 1.0)\n    lay_const : float, optional\n        Ratio of layover probability density to peak probability density for\n        non-layover slopes expected. (default: 0.9)\n    lay_falloff_const : float, optional\n        Factor applied to slope variance for non-layover to get falloff of\n        probability density after the  upper layover slope limit has been\n        exceeded. (default: 2.0)\n    sigsq_lay_factor : float, optional\n        Fraction of (ambiguity height)^2 to use for slope variance in the\n        presence of layover. (default: 0.1)\n    krow_ei, kcol_ei : int, optional\n        Number of rows & columns to use in sliding average window used for\n        normalizing intensity values. (default: 65, 257)\n    init_dzr : float, optional\n        Initial value of range slope for dzrcrit numerical solution, in\n        meters/pixel. (default: 2048.0)\n    init_dz_step : float, optional\n        Initial range slope step size in dzrhomax numerical solution, in\n        meters/pixel. (default: 100.0)\n    cost_scale_ambig_ht : float, optional\n        Ambiguity height for auto-scaling the `SolverParams.cost_scale`\n        parameter to equal 100. This is the amount of height change, in meters,\n        that results in a :math:`2 \\pi` change in the interferometric phase. The\n        cost scale is automatically adjusted to be inversely proportional to the\n        midswath ambiguity height. (default: 80.0)\n    dnom_inc_angle : float, optional\n        Step size, in radians, for dzrhomax lookup table. The index is on the\n        flat-earth incidence angle; this is the sample spacing in the table.\n        (default: 0.01)\n    kpar_dpsi, kperp_dpsi : int, optional\n        Number of pixels in sliding window used for averaging wrapped phase\n        gradients to get mean non-layover slope, in directions parallel and\n        perpendicular to the examined phase difference. (default: 7, 7)\n    \"\"\"\n\n    bperp: float\n    near_range: float\n    dr: float\n    da: float\n    range_res: float\n    az_res: float\n    wavelength: float\n    transmit_mode: str\n    altitude: float\n    earth_radius: float = 6_378_000.0\n    kds: float = 0.02\n    specular_exp: float = 8.0\n    dzr_crit_factor: float = 2.0\n    shadow: bool = False\n    dz_ei_min: float = -4.0\n    lay_width: int = 16\n    lay_min_ei: float = 1.25\n    slope_ratio_factor: float = 1.18\n    sigsq_ei: float = 100.0\n    drho: float = 0.005\n    dz_lay_peak: float = -2.0\n    azdz_factor: float = 0.99\n    dz_ei_factor: float = 4.0\n    dz_ei_weight: float = 0.5\n    dz_lay_factor: float = 1.0\n    lay_const: float = 0.9\n    lay_falloff_const: float = 2.0\n    sigsq_lay_factor: float = 0.1\n    krow_ei: int = 65\n    kcol_ei: int = 257\n    init_dzr: float = 2048.0\n    init_dz_step: float = 100.0\n    cost_scale_ambig_ht: float = 80.0\n    dnom_inc_angle: float = 0.01\n    kpar_dpsi: int = 7\n    kperp_dpsi: int = 7\n\n    def tostring(self):\n        \"\"\"Convert to string in SNAPHU config file format.\"\"\"\n\n        def parse_transmit_mode(s):\n            if s == \"pingpong\":\n                return \"PINGPONG\"\n            if s == \"repeat_pass\":\n                return \"REPEATPASS\"\n            if s == \"single_antenna_transmit\":\n                return \"SINGLEANTENNATRANSMIT\"\n            raise ValueError(f\"invalid transmit mode '{s}'\")\n\n        s = \"\"\n        s += f\"BPERP {self.bperp}\\n\"\n        s += f\"NEARRANGE {self.near_range}\\n\"\n        s += f\"DR {self.dr}\\n\"\n        s += f\"DA {self.da}\\n\"\n        s += f\"RANGERES {self.range_res}\\n\"\n        s += f\"AZRES {self.az_res}\\n\"\n        s += f\"LAMBDA {self.wavelength}\\n\"\n        s += f\"TRANSMITMODE {parse_transmit_mode(self.transmit_mode)}\\n\"\n        s += f\"ALTITUDE {self.altitude}\\n\"\n        s += f\"EARTHRADIUS {self.earth_radius}\\n\"\n        s += f\"KDS {self.kds}\\n\"\n        s += f\"SPECULAREXP {self.specular_exp}\\n\"\n        s += f\"DZRCRITFACTOR {self.dzr_crit_factor}\\n\"\n        s += f\"SHADOW {self.shadow}\\n\"\n        s += f\"DZEIMIN {self.dz_ei_min}\\n\"\n        s += f\"LAYWIDTH {self.lay_width}\\n\"\n        s += f\"LAYMINEI {self.lay_min_ei}\\n\"\n        s += f\"SLOPERATIOFACTOR {self.slope_ratio_factor}\\n\"\n        s += f\"SIGSQEI {self.sigsq_ei}\\n\"\n        s += f\"DRHO {self.drho}\\n\"\n        s += f\"DZLAYPEAK {self.dz_lay_peak}\\n\"\n        s += f\"AZDZFACTOR {self.azdz_factor}\\n\"\n        s += f\"DZEIFACTOR {self.dz_ei_factor}\\n\"\n        s += f\"DZEIWEIGHT {self.dz_ei_weight}\\n\"\n        s += f\"DZLAYFACTOR {self.dz_lay_factor}\\n\"\n        s += f\"LAYCONST {self.lay_const}\\n\"\n        s += f\"LAYFALLOFFCONST {self.lay_falloff_const}\\n\"\n        s += f\"SIGSQLAYFACTOR {self.sigsq_lay_factor}\\n\"\n        s += f\"KROWEI {self.krow_ei}\\n\"\n        s += f\"KCOLEI {self.kcol_ei}\\n\"\n        s += f\"INITDZR {self.init_dzr}\\n\"\n        s += f\"INITDZSTEP {self.init_dz_step}\\n\"\n        s += f\"COSTSCALEAMBIGHT {self.cost_scale_ambig_ht}\\n\"\n        s += f\"DNOMINCANGLE {self.dnom_inc_angle}\\n\"\n        s += f\"KPARDPSI {self.kpar_dpsi}\\n\"\n        s += f\"KPERPDPSI {self.kperp_dpsi}\\n\"\n        return s\n\n\n@dataclass(frozen=True)\nclass DefoCostParams:\n    \"\"\"Configuration parameters for SNAPHU \"defo\" cost mode\n\n    Unwrapped phase is modelled as a surface deformation signature in additive\n    phase noise.\n\n    Attributes\n    ----------\n    azdz_factor : float, optional\n        Factor applied to range discontinuity probability density to get\n        corresponding value for azimuth. (default: 1.0)\n    defo_max : float, optional\n        Maximum phase discontinuity, in units of cycles (of 2*pi). If abrupt\n        phase discontinuities are not expected, this parameter can be set to\n        zero. (default: 1.2)\n    sigsq_corr : float, optional\n        Phase variance, in cycles^2, reflecting uncertainty in measurement of\n        actual statistical correlation. (default: 0.05)\n    defo_const : float, optional\n        Ratio of phase discontinuity probability density to peak probability\n        density expected for discontinuity-possible pixel differences. A value\n        of 1 means zero cost for discontinuity, 0 means infinite cost.\n        (default: 0.9)\n    lay_falloff_const : float, optional\n        Factor applied to slope variance for non-layover to get falloff of\n        probability density after the  upper layover slope limit has been\n        exceeded. (default: 2.0)\n    kpar_dpsi, kperp_dpsi : int, optional\n        Number of pixels in sliding window used for averaging wrapped phase\n        gradients to get mean non-layover slope, in directions parallel and\n        perpendicular to the examined phase difference. (default: 7, 7)\n    \"\"\"\n\n    azdz_factor: float = 1.0\n    defo_max: float = 1.2\n    sigsq_corr: float = 0.05\n    defo_const: float = 0.9\n    lay_falloff_const: float = 2.0\n    kpar_dpsi: int = 7\n    kperp_dpsi: int = 7\n\n    def tostring(self):\n        \"\"\"Convert to string in SNAPHU config file format.\"\"\"\n        s = \"\"\n        s += f\"DEFOAZDZFACTOR {self.azdz_factor}\\n\"\n        s += f\"DEFOMAX_CYCLE {self.defo_max}\\n\"\n        s += f\"SIGSQCORR {self.sigsq_corr}\\n\"\n        s += f\"DEFOCONST {self.defo_const}\\n\"\n        s += f\"LAYFALLOFFCONST {self.lay_falloff_const}\\n\"\n        s += f\"KPARDPSI {self.kpar_dpsi}\\n\"\n        s += f\"KPERPDPSI {self.kperp_dpsi}\\n\"\n        return s\n\n\n@dataclass(frozen=True)\nclass SmoothCostParams:\n    \"\"\"Configuration parameters for SNAPHU \"smooth\" cost mode\n\n    Attributes\n    ----------\n    kpar_dpsi, kperp_dpsi : int, optional\n        Number of pixels in sliding window used for averaging wrapped phase\n        gradients to get mean non-layover slope, in directions parallel and\n        perpendicular to the examined phase difference. (default: 7, 7)\n    \"\"\"\n\n    kpar_dpsi: int = 7\n    kperp_dpsi: int = 7\n\n    def tostring(self):\n        \"\"\"Convert to string in SNAPHU config file format.\"\"\"\n        s = \"\"\n        s += f\"KPARDPSI {self.kpar_dpsi}\\n\"\n        s += f\"KPERPDPSI {self.kperp_dpsi}\\n\"\n        return s\n\n\n@dataclass(frozen=True)\nclass PNormCostParams:\n    r\"\"\"Configuration parameters for SNAPHU \"p-norm\" cost mode\n\n    In this mode, the minimization objective is the :math:`L^p` norm of the\n    difference between the unwrapped and wrapped phase gradients.\n\n    .. math:: cost = \\sum_i \\left| \\Delta \\phi_i - \\Delta \\psi_i \\right| ^ p\n\n    Attributes\n    ----------\n    p : float, optional\n        Lp norm exponent. Must be nonnegative. (default: 0.0)\n    bidir : bool, optional\n        If True, bidirectional Lp costs are used. This implies that the scalar\n        weight of an Lp arc may be different depending on the direction of net\n        flow on the arc. If False, the weight is the same regardless of arc\n        direction. (default: True)\n    \"\"\"\n\n    p: float = 0.0\n    bidir: bool = True\n\n    def tostring(self):\n        \"\"\"Convert to string in SNAPHU config file format.\"\"\"\n        s = \"\"\n        s += f\"PLPN {self.p}\\n\"\n        s += f\"BIDIRLPN {self.bidir}\\n\"\n        return s\n\n\n@dataclass(frozen=True)\nclass TilingParams:\n    \"\"\"Configuration parameters affecting scene tiling and parallel processing.\n\n    Attributes\n    ----------\n    nproc : int, optional\n        Maximum number of child processes to spawn for parallel tile unwrapping.\n        If nproc is less than 1, use all available processors. (default: 1)\n    tile_nrows, tile_ncols : int, optional\n        Number of tiles along the row/column directions. If `tile_nrows` and\n        `tile_ncols` are both 1, the interferogram is unwrapped as a single\n        tile. (default: 1, 1)\n    row_overlap, col_overlap : int, optional\n        Overlap, in number of rows/columns, between neighboring tiles.\n        (default: 0)\n    tile_cost_thresh : int, optional\n        Cost threshold to use for determining boundaries of reliable regions.\n        Larger cost threshold implies smaller regions (safer, but more expensive\n        computationally). (default: 500)\n    min_region_size : int, optional\n        Minimum size of a reliable region in tile mode, in pixels. (default: 100)\n    tile_edge_weight : float, optional\n        Extra weight applied to secondary arcs on tile edges. (default: 2.5)\n    secondary_arc_flow_max : int, optional\n        Maximum flow magnitude whose cost will be stored in the secondary cost\n        lookup table. Secondary costs larger than this will be approximated by a\n        quadratic function. (default: 8)\n    single_tile_reoptimize : bool, optional\n        If True, re-optimize as a single tile after using tile mode for\n        initialization. This is equivalent to unwrapping with multiple tiles,\n        then using the unwrapped output as the input to a new, single-tile run\n        of snaphu to make iterative improvements to the solution. This may\n        improve speed compared to a single single-tile run. (default: False)\n    \"\"\"\n\n    nproc: int = 1\n    tile_nrows: int = 1\n    tile_ncols: int = 1\n    row_overlap: int = 0\n    col_overlap: int = 0\n    tile_cost_thresh: int = 500\n    min_region_size: int = 100\n    tile_edge_weight: float = 2.5\n    secondary_arc_flow_max: int = 8\n    single_tile_reoptimize: bool = False\n\n    def tostring(self):\n        \"\"\"Convert to string in SNAPHU config file format.\"\"\"\n        s = \"\"\n        if self.nproc < 1:\n            nproc = os.cpu_count() or 1\n            s += f\"NPROC {nproc}\\n\"\n        else:\n            s += f\"NPROC {self.nproc}\\n\"\n        s += f\"NTILEROW {self.tile_nrows}\\n\"\n        s += f\"NTILECOL {self.tile_ncols}\\n\"\n        s += f\"ROWOVRLP {self.row_overlap}\\n\"\n        s += f\"COLOVRLP {self.col_overlap}\\n\"\n        s += f\"TILECOSTTHRESH {self.tile_cost_thresh}\\n\"\n        s += f\"MINREGIONSIZE {self.min_region_size}\\n\"\n        s += f\"TILEEDGEWEIGHT {self.tile_edge_weight}\\n\"\n        s += f\"SCNDRYARCFLOWMAX {self.secondary_arc_flow_max}\\n\"\n        s += f\"SINGLETILEREOPTIMIZE {self.single_tile_reoptimize}\\n\"\n\n        # Don't remove temporary files for each tile since they may be useful\n        # for debugging. If the scratch directory is cleaned up, they'll be\n        # removed as well.\n        s += \"RMTMPTILE FALSE\\n\"\n\n        return s\n\n\n@dataclass(frozen=True)\nclass SolverParams:\n    \"\"\"Configuration parameters used by the network initialization and nonlinear\n    network flow solver algorithms.\n\n    Attributes\n    ----------\n    max_flow_inc : int, optional\n        Maximum flow increment. (default: 4)\n    init_max_flow : int, optional\n        Maximum flow to allow in initialization. If this is zero, then the\n        maximum is calculated automatically from the statistical cost functions.\n        To disable, set it to a large value like 9999, but do not overflow the\n        long integer data type. (default: 9999)\n    arc_max_flow_const : int, optional\n        Constant to add to maximum flow expected from statistical cost functions\n        for automatically determining initial maximum flow. (default: 3)\n    threshold : float, optional\n        Threshold precision for iterative numerical calculations.\n        (default: 0.001)\n    max_cost : float, optional\n        Maximum cost allowed for scalar MST costs and for estimating the number\n        of buckets needed for the solver routine. (default: 1000.0)\n    cost_scale : float, optional\n        Cost scaling factor applied to floating-point costs before quantization\n        to integer costs. (default: 100.0)\n    n_cycle : int, optional\n        Integer spacing that represents one unit of flow (one cycle of phase)\n        when storing costs as short integers. (default: 200)\n    max_new_node_const : float, optional\n        Fraction of total number of nodes to add in each tree expansion phase of\n        the solver algorithm. (default: 0.0008)\n    max_n_flow_cycles : float or None, optional\n        Number of cycles to allow for a call to the solver with a specific flow\n        increment delta and still consider that increment done. Ideally it would\n        be zero, but scaling for different deltas may leave some negative cycles\n        that won't affect the solution much. If None, this is automatically\n        determined based on the size of the interferogram. (default: None)\n    max_cycle_frac : float, optional\n        Fraction of the number of pixels to use as the maximum number of cycles\n        allowed for a specific flow increment if max_n_flow_cycles was None.\n        (default: 0.00001)\n    n_conn_node_min : int, optional\n        Minimum number of connected nodes to consider for unwrapping. If masking\n        separates the input data into disconnected sets of pixels, a source is\n        selected for each connected set, provided that the number of nodes in\n        the set is greater than n_conn_node_min. Must be nonnegative.\n        (default: 0)\n    n_major_prune : int, optional\n        Number of major iterations between tree pruning operations. A smaller\n        number causes pruning to occur more frequently. (default: 2000000000)\n    prune_cost_thresh : int, optional\n        Cost threshold for pruning the tree. A lower threshold prunes more\n        aggressively. (default: 2000000000)\n    \"\"\"\n\n    max_flow_inc: int = 4\n    init_max_flow: int = 9999\n    arc_max_flow_const: int = 3\n    threshold: float = 0.001\n    max_cost: float = 1000.0\n    cost_scale: float = 100.0\n    n_cycle: int = 200\n    max_new_node_const: float = 0.0008\n    max_n_flow_cycles: Optional[float] = None\n    max_cycle_frac: float = 0.00001\n    n_conn_node_min: int = 0\n    n_major_prune: int = 2_000_000_000\n    prune_cost_thresh: int = 2_000_000_000\n\n    def tostring(self):\n        \"\"\"Convert to string in SNAPHU config file format.\"\"\"\n        s = \"\"\n        s += f\"MAXFLOW {self.max_flow_inc}\\n\"\n        s += f\"INITMAXFLOW {self.init_max_flow}\\n\"\n        s += f\"ARCMAXFLOWCONST {self.arc_max_flow_const}\\n\"\n        s += f\"THRESHOLD {self.threshold}\\n\"\n        s += f\"MAXCOST {self.max_cost}\\n\"\n        s += f\"COSTSCALE {self.cost_scale}\\n\"\n        s += f\"NSHORTCYCLE {self.n_cycle}\\n\"\n        s += f\"MAXNEWNODECONST {self.max_new_node_const}\\n\"\n        if self.max_n_flow_cycles is not None:\n            s += f\"MAXNFLOWCYCLES {self.max_n_flow_cycles}\\n\"\n        else:\n            s += f\"MAXCYCLEFRACTION {self.max_cycle_frac}\\n\"\n        s += f\"NCONNNODEMIN {self.n_conn_node_min}\\n\"\n        s += f\"NMAJORPRUNE {self.n_major_prune}\\n\"\n        s += f\"PRUNECOSTTHRESH {self.prune_cost_thresh}\\n\"\n        return s\n\n\n@dataclass(frozen=True)\nclass ConnCompParams:\n    \"\"\"Configuration parameters affecting the generation of connected component\n    labels.\n\n    Attributes\n    ----------\n    min_frac_area : float, optional\n        Minimum size of a single connected component, as a fraction of the total\n        number of pixels in the tile. (default: 0.01)\n    cost_thresh : int, optional\n        Cost threshold for connected components. Higher threshold will give\n        smaller connected components. (default: 300)\n    max_ncomps : int, optional\n        Maximum number of connected components per tile. (default: 32)\n    \"\"\"\n\n    min_frac_area: float = 0.01\n    cost_thresh: int = 300\n    max_ncomps: int = 32\n\n    def tostring(self):\n        \"\"\"Convert to string in SNAPHU config file format.\"\"\"\n        s = \"\"\n        s += f\"MINCONNCOMPFRAC {self.min_frac_area}\\n\"\n        s += f\"CONNCOMPTHRESH {self.cost_thresh}\\n\"\n        s += f\"MAXNCOMPS {self.max_ncomps}\\n\"\n        return s\n\n\n@dataclass(frozen=True)\nclass CorrBiasModelParams:\n    r\"\"\"Model parameters for estimating bias in sample correlation magnitude\n    expected for zero true correlation\n\n    The multilooked correlation magnitude of the interferometric pair\n    :math:`z_1` and :math:`z_2` is commonly estimated as\n\n    .. math::\n\n        \\rho = \\left| \\frac{ \\sum_{i=1}^{N}{z_{1i} z_{2i} ^*} }\n            { \\sqrt{ \\sum_{i=1}^{N}{ \\left| z_{1i} \\right| ^2 } }\n            \\sqrt{ \\sum_{i=1}^{N}{ \\left| z_{2i} \\right| ^2 } } }  \\right|\n\n    where :math:`N` is the number of statistically independent looks. SNAPHU\n    uses the estimated correlation coefficient to infer statistics of the\n    interferometric phase.\n\n    This estimator is biased with respect to the expected true correlation,\n    particularly at lower correlation values. In order to compensate for this,\n    SNAPHU models the expected biased correlation measure, given that true\n    interferometric correlation is zero, as\n\n    .. math:: \\rho_0 = \\frac{c_1}{N} + c_2\n\n    where :math:`N` is the number of effective looks used to estimate the\n    correlation and :math:`c_1` & :math:`c_2` are the model coefficients. This\n    approximately matches the curves of Touzi et al [1]_.\n\n    Attributes\n    ----------\n    c1, c2 : float, optional\n        Correlation bias model parameters.\n    min_corr_factor : float, optional\n        Factor applied to expected minimum measured (biased) correlation\n        coefficient. Values smaller than the threshold min_corr_factor * rho0\n        are assumed to come from zero statistical correlation because of\n        estimator bias. rho0 is the expected biased correlation measure if the\n        true correlation is zero. (default: 1.25)\n\n    References\n    ----------\n    .. [1] R. Touzi, A. Lopes, J. Bruniquel, and P. W. Vachon, \"Coherence\n       estimation for SAR imagery,\" IEEE Trans. Geosci. Remote Sens. 37, 135-149\n       (1999).\n    \"\"\"\n\n    c1: float = 1.3\n    c2: float = 0.14\n    min_corr_factor: float = 1.25\n\n    def tostring(self):\n        \"\"\"Convert to string in SNAPHU config file format.\"\"\"\n        s = \"\"\n        s += f\"RHOSCONST1 {self.c1}\\n\"\n        s += f\"RHOSCONST2 {self.c2}\\n\"\n\n        # This parameter has different names depending on which cost mode was\n        # selected -- \"RHOMINFACTOR\" for \"topo\" mode, \"DEFOTHRESHFACTOR\" for\n        # \"defo\" and \"smooth\" mode -- but the semantics & effect are the same.\n        # We redundantly define both params here since it's harmless and avoids\n        # introducing a dependency on cost mode.\n        s += f\"RHOMINFACTOR {self.min_corr_factor}\\n\"\n        s += f\"DEFOTHRESHFACTOR {self.min_corr_factor}\\n\"\n\n        return s\n\n\n@dataclass(frozen=True)\nclass PhaseStddevModelParams:\n    r\"\"\"Model parameters for approximating phase standard deviation from\n    correlation magnitude\n\n    Interferometric phase standard deviation is modelled as\n\n    .. math:: \\sigma_{\\phi} = \\rho ^{ c_1 + c_2 * \\log nlooks + c_3 * nlooks }\n\n    where :math:`\\rho` is the sample correlation magnitude and :math:`nlooks` is\n    the effective number of looks. :math:`c_1`, :math:`c_2`, and :math:`c_3` are\n    the model coefficients. This approximately matches the curves of [1]_.\n\n    Attributes\n    ----------\n    c1, c2, c3 : float, optional\n        Interferometric phase standard deviation model parameters.\n    sigsq_min : int\n        Minimum value of phase variance after quantization to integer values.\n        Must be greater than zero to prevent division by zero. (default: 1)\n\n    References\n    ----------\n    .. [1] J. S. Lee, K. W. Hoppel, S. A. Mango, and A. R. Miller, \"Intensity\n       and phase statistics of multilook polarimetric and interferometric SAR\n       imagery,\" IEEE Trans. Geosci. Remote Sens. 32, 1017-1028 (1994).\n    \"\"\"\n\n    c1: float = 0.4\n    c2: float = 0.35\n    c3: float = 0.06\n    sigsq_min: int = 1\n\n    def tostring(self):\n        \"\"\"Convert to string in SNAPHU config file format.\"\"\"\n        s = \"\"\n        s += f\"CSTD1 {self.c1}\\n\"\n        s += f\"CSTD2 {self.c2}\\n\"\n        s += f\"CSTD3 {self.c3}\\n\"\n        s += f\"SIGSQSHORTMIN {self.sigsq_min}\\n\"\n        return s\n\n\n@contextlib.contextmanager\ndef scratch_directory(d: Optional[os.PathLike] = None) -> pathlib.Path:\n    \"\"\"Context manager that creates a (possibly temporary) filesystem directory\n\n    If the input is a path-like object, a directory will be created at the\n    specified filesystem path if it did not already exist. The directory will\n    persist after leaving the context manager scope.\n\n    If the input is None, a temporary directory is created as though by\n    `tempfile.TemporaryDirectory()`. Upon exiting the context manager scope, the\n    directory and its contents are removed from the filesystem.\n\n    Parameters\n    ----------\n    d : path-like or None, optional\n        Scratch directory path. If None, a temporary directory is created.\n        (default: None)\n\n    Yields\n    ------\n    d : pathlib.Path\n        Scratch directory path. If the input was None, the directory is removed\n        from the filesystem upon exiting the context manager scope.\n    \"\"\"\n    if d is None:\n        try:\n            d = tempfile.TemporaryDirectory()\n            yield pathlib.Path(d.name)\n        finally:\n            d.cleanup()\n    else:\n        d = pathlib.Path(d)\n        d.mkdir(parents=True, exist_ok=True)\n        yield d\n\n\ndef to_flat_file(\n    path: os.PathLike,\n    raster: isce3.io.gdal.Raster,\n    dtype: Optional[np.dtype] = None,\n    batchsize: int = -1,\n):\n    \"\"\"Write raster data to flat binary file.\n\n    The output file is overwritten if it exists.\n\n    Parameters\n    ----------\n    path : path-like\n        Output filepath.\n    raster : isce3.io.gdal.Raster\n        Input raster.\n    dtype : data-type or None, optional\n        Output datatype. If None, use the input raster datatype. (default: None)\n    batchsize : int, optional\n        If this is a positive number, the data is copied serially in batches of\n        this many rows to avoid holding the full dataset in memory at once.\n        Otherwise, copy the full data array as a single batch. (default: -1)\n    \"\"\"\n    if dtype is None:\n        dtype = raster.data.dtype\n\n    if batchsize < 1:\n        batchsize = raster.length\n\n    # Memory-map the output file.\n    shape = (raster.length, raster.width)\n    mmap = np.memmap(path, dtype=dtype, mode=\"w+\", shape=shape)\n\n    # Write data in batches.\n    for i0 in range(0, raster.length, batchsize):\n        i1 = i0 + batchsize\n        mmap[i0:i1] = raster.data[i0:i1]\n\n    # Explicitly flush to disk instead of waiting for the memory map to be\n    # garbage-collected.\n    mmap.flush()\n\n\ndef from_flat_file(\n    path: os.PathLike,\n    raster: isce3.io.gdal.Raster,\n    dtype: Optional[np.dtype] = None,\n    batchsize: int = -1,\n):\n    \"\"\"Read raster data from flat binary file.\n\n    Parameters\n    ----------\n    path : path-like\n        Input filepath.\n    raster : isce3.io.gdal.Raster\n        Output raster.\n    dtype : data-type or None, optional\n        Input file datatype. If None, assume the same as the output raster\n        datatype. (default: None)\n    batchsize : int, optional\n        If this is a positive number, the data is copied serially in batches of\n        this many rows to avoid holding the full dataset in memory at once.\n        Otherwise, copy the full data array as a single batch. (default: -1)\n    \"\"\"\n    if dtype is None:\n        dtype = raster.data.dtype\n\n    if batchsize < 1:\n        batchsize = raster.length\n\n    # Memory-map the input file.\n    shape = (raster.length, raster.width)\n    mmap = np.memmap(path, dtype=dtype, mode=\"r\", shape=shape)\n\n    # Read data in batches.\n    for i0 in range(0, raster.length, batchsize):\n        i1 = i0 + batchsize\n        raster.data[i0:i1] = mmap[i0:i1]\n\n\nCostParams = Union[\n    TopoCostParams, DefoCostParams, SmoothCostParams, PNormCostParams,\n]\nCostParams.__doc__ = \"\"\"SNAPHU cost mode configuration parameters\"\"\"\n\n\ndef unwrap(\n    unw: isce3.io.gdal.Raster,\n    conncomp: isce3.io.gdal.Raster,\n    igram: isce3.io.gdal.Raster,\n    corr: isce3.io.gdal.Raster,\n    nlooks: float,\n    cost: str = \"smooth\",\n    cost_params: Optional[CostParams] = None,\n    init_method: str = \"mcf\",\n    pwr: Optional[isce3.io.gdal.Raster] = None,\n    mask: Optional[isce3.io.gdal.Raster] = None,\n    unwest: Optional[isce3.io.gdal.Raster] = None,\n    tiling_params: Optional[TilingParams] = None,\n    solver_params: Optional[SolverParams] = None,\n    conncomp_params: Optional[ConnCompParams] = None,\n    corr_bias_model_params: Optional[CorrBiasModelParams] = None,\n    phase_stddev_model_params: Optional[PhaseStddevModelParams] = None,\n    scratchdir: Optional[os.PathLike] = None,\n    debug: bool = False,\n):\n    r\"\"\"Performs 2-D phase unwrapping on an input interferogram using the SNAPHU\n    algorithm.\n\n    The algorithm attempts to estimate the unwrapped phase field by\n    approximately solving a non-linear optimization problem using cost functions\n    based on simple statistical models of the unwrapped phase gradients.\n\n    The total cost is approximately minimized by applying a non-linear network\n    flow solver based on the network simplex algorithm. An initial feasible\n    solution is first computed before optimizing according to the specified cost\n    mode.\n\n    Different statistical cost functions may be applied depending on the\n    application:\n    - The \"topo\" cost mode generates cost functions for topographic SAR\n    interferometry. The problem statistics are based on the assumption that the\n    true unwrapped phase represents surface elevation. The input interferogram\n    is assumed to be in radar (range-azimuth) coordinates for this mode.\n    - The \"defo\" cost mode generates cost functions for deformation\n    measurements. The problem statistics are based on the assumption that the\n    true unwrapped phase represents surface displacement.\n    - The \"smooth\" cost mode models the problem statistics based on the\n    assumption that the true unwrapped phase represents a generic surface with\n    no discontinuities.\n    - The \"p-norm\" cost mode is not based on a statistical model but rather\n    minimizes the :math:`L^p` norm of the difference between the unwrapped and\n    wrapped phase gradients.\n\n    The outputs include the unwrapped phase and a raster of connected component\n    labels. Each connected component is a region of pixels in the solution that\n    is believed to have been unwrapped in an internally self-consistent manner.\n    Each distinct region is assigned a unique positive integer label. Pixels not\n    belonging to any component are assigned a label of zero.\n\n    The effective number of looks used to form the input correlation data must\n    be provided in order to estimate interferometric phase statistics. The\n    effective number of looks is an estimate of the number of statistically\n    independent samples averaged in multilooked data, taking into account\n    spatial correlation due to oversampling/filtering. It is approximately equal\n    to\n\n    .. math:: n_e = k_r k_a \\frac{d_r d_a}{\\rho_r \\rho_a}\n\n    where :math:`k_r` and :math:`k_a` are the number of looks in range and\n    azimuth, :math:`d_r` and :math:`d_a` are the sample spacing in range and\n    azimuth, and :math:`\\rho_r` and :math:`\\rho_a are the range and azimuth\n    resolution.\n\n    Unwrapping can be performed in tile mode to potentially speed up processing\n    and make use of multiple processors in parallel, though this may result in\n    processing artifacts at tile boundaries. The interferogram is partitioned\n    into rectangular tiles, each of which is unwrapped independently before\n    reassembly. The default behavior is to unwrap the full interferogram as a\n    single tile.\n\n    .. warning:: Currently, if tile mode is used and any connected component\n    crosses spans multiple tiles, the assigned connected component label may be\n    inconsistent across tiles.\n\n    Parameters\n    ----------\n    unw : isce3.io.gdal.Raster\n        Output raster for unwrapped phase, in radians. Must have the same\n        dimensions as the input interferogram and GDT_Float32 datatype.\n    conncomp : isce3.io.gdal.Raster\n        Output connected component labels. Must have the same dimensions as the\n        input interferogram and GDT_UInt32 datatype.\n    igram : isce3.io.gdal.Raster\n        Input interferogram. Must have GDT_CFloat32 datatype.\n    corr : isce3.io.gdal.Raster\n        Correlation magnitude, normalized to the interval [0, 1]. Must have the\n        same dimensions as the input interferogram and GDT_Float32 datatype.\n    nlooks : float\n        Effective number of looks used to form the input correlation data.\n    cost : {\"topo\", \"defo\", \"smooth\", \"p-norm\"}, optional\n        Statistical cost mode. (default: \"smooth\")\n    cost_params : CostParams or None, optional\n        Configuration parameters for the specified cost mode. This argument is\n        required for \"topo\" mode and optional for all other modes. If None, the\n        default configuration parameters are used. (default: None)\n    init_method: {\"mst\", \"mcf\"}, optional\n        Algorithm used for initialization of unwrapped phase gradients.\n        Supported algorithms include Minimum Spanning Tree (\"mst\") and Minimum\n        Cost Flow (\"mcf\"). (default: \"mcf\")\n    pwr : isce3.io.gdal.Raster or None, optional\n        Average intensity of the two SLCs, in linear units (not dB). Only used\n        in \"topo\" cost mode. If None, interferogram magnitude is used as\n        intensity. Must have the same dimensions as the input interferogram and\n        GDT_Float32 datatype. (default: None)\n    mask : isce3.io.gdal.Raster or None, optional\n        Binary mask of valid pixels. Zeros in this raster indicate interferogram\n        pixels that should be masked out. Must have the same dimensions as the\n        input interferogram and GDT_Byte datatype. (default: None)\n    unwest : isce3.io.gdal.Raster or None, optional\n        Initial estimate of unwrapped phase, in radians. This can be used to\n        provide a coarse unwrapped estimate to guide the algorithm. Must have\n        the same dimensions as the input interferogram and GDT_Float32 datatype.\n        (default: None)\n    tiling_params : TilingParams or None, optional\n        Configuration parameters affecting scene tiling and parallel processing.\n        If None, the default configuration parameters are used. (default: None)\n    solver_params : SolverParams or None, optional\n        Configuration parameters used by the network initialization and\n        nonlinear network flow solver algorithms. If None, the default\n        configuration parameters are used. (default: None)\n    conncomp_params : ConnCompParams or None, optional\n        Configuration parameters affecting the generation of connected component\n        labels. If None, the default configuration parameters are used.\n        (default: None)\n    corr_bias_model_params : CorrBiasModelParams or None, optional\n        Model parameters for estimating bias in sample correlation magnitude\n        expected for zero true correlation. If None, the default model\n        parameters are used. (default: None)\n    phase_stddev_model_params : PhaseStddevModelParams or None, optional\n        Model parameters for approximating phase standard deviation from\n        correlation magnitude. If None, the default model parameters are used.\n        (default: None)\n    scratchdir : path-like or None, optional\n        Scratch directory where intermediate processing artifacts are written.\n        If the specified directory does not exist, it will be created. If None,\n        a temporary directory will be created and automatically removed from the\n        filesystem at the end of processing. Otherwise, the directory and its\n        contents will not be cleaned up. (default: None)\n    debug : bool, optional\n        Dump intermediate data arrays to scratch directory for debugging?\n        (default: False)\n\n    See Also\n    --------\n    isce3.unwrap.ICU : Branch-cut-based phase unwrapping\n    isce3.unwrap.Phass : Minimum Cost Flow-based phase unwrapping\n\n    References\n    ----------\n    .. [1] C. W. Chen and H. A. Zebker, \"Network approaches to two-dimensional\n       phase unwrapping: intractability and two new algorithms,\" Journal of the\n       Optical Society of America A, vol. 17, pp. 401-414 (2000).\n    .. [2] C. W. Chen and H. A. Zebker, \"Two-dimensional phase unwrapping with\n       use of statistical models for cost functions in nonlinear optimization,\"\n       Journal of the Optical Society of America A, vol. 18, pp. 338-351 (2001).\n    .. [3] C. W. Chen and H. A. Zebker, \"Phase unwrapping for large SAR\n       interferograms: Statistical segmentation and generalized network models,\"\n       IEEE Transactions on Geoscience and Remote Sensing, vol. 40, pp.\n       1709-1719 (2002).\n    \"\"\"\n    # Verify input & output raster datatypes.\n    if unw.datatype != isce3.io.gdal.GDT_Float32:\n        raise TypeError(\"unw raster must have GDT_Float32 datatype\")\n    if conncomp.datatype != isce3.io.gdal.GDT_UInt32:\n        raise TypeError(\"conncomp raster must have GDT_UInt32 datatype\")\n    if igram.datatype != isce3.io.gdal.GDT_CFloat32:\n        raise TypeError(\"igram raster must have GDT_CFloat32 datatype\")\n    if corr.datatype != isce3.io.gdal.GDT_Float32:\n        raise TypeError(\"corr raster must have GDT_Float32 datatype\")\n\n    length, width = igram.length, igram.width\n\n    # Check that raster dimensions are consistent.\n    if (unw.length != length) or (unw.width != width):\n        raise ValueError(\"unw raster dimensions must match interferogram\")\n    if (conncomp.length != length) or (conncomp.width != width):\n        raise ValueError(\"conncomp raster dimensions must match interferogram\")\n    if (corr.length != length) or (corr.width != width):\n        raise ValueError(\"corr raster dimensions must match interferogram\")\n\n    # Check specified number of effective looks.\n    if nlooks < 1.0:\n        raise ValueError(\"nlooks must be >= 1.0\")\n\n    # Generate a SNAPHU text configuration file to pass to the C++ code.\n    configstr = \"\"\n    configstr += f\"LINELENGTH {width}\\n\"\n    configstr += f\"NCORRLOOKS {nlooks}\\n\"\n\n    def cost_string():\n        if cost == \"topo\":\n            return \"TOPO\"\n        if cost == \"defo\":\n            return \"DEFO\"\n        if cost == \"smooth\":\n            return \"SMOOTH\"\n        if cost == \"p-norm\":\n            return \"NOSTATCOSTS\"\n        raise ValueError(f\"invalid cost mode '{cost}'\")\n\n    configstr += f\"STATCOSTMODE {cost_string()}\\n\"\n\n    def init_string():\n        if init_method == \"mst\":\n            return \"MST\"\n        if init_method == \"mcf\":\n            return \"MCF\"\n        raise ValueError(f\"invalid init method '{init_method}'\")\n\n    configstr += f\"INITMETHOD {init_string()}\\n\"\n\n    # Check cost mode-specific configuration params.\n    if cost == \"topo\":\n        # In \"topo\" mode, configuration params must be provided (there is no\n        # default configuration).\n        if not isinstance(cost_params, TopoCostParams):\n            raise TypeError(\n                \"cost_params for 'topo' cost mode must be an \"\n                \"instance of TopoCostParams\"\n            )\n    elif cost == \"defo\":\n        if cost_params is None:\n            cost_params = DefoCostParams()\n        if not isinstance(cost_params, DefoCostParams):\n            raise TypeError(\"invalid cost_params for 'defo' cost mode\")\n    elif cost == \"smooth\":\n        if cost_params is None:\n            cost_params = SmoothCostParams()\n        if not isinstance(cost_params, SmoothCostParams):\n            raise TypeError(\"invalid cost_params for 'smooth' cost mode\")\n    elif cost == \"p-norm\":\n        if cost_params is None:\n            cost_params = PNormCostParams()\n        if not isinstance(cost_params, PNormCostParams):\n            raise TypeError(\"invalid cost_params for 'p-norm' cost mode\")\n    else:\n        raise ValueError(f\"invalid cost mode '{cost}'\")\n\n    configstr += cost_params.tostring()\n\n    # Additional optional configuration parameters.\n    if tiling_params is not None:\n        configstr += tiling_params.tostring()\n    if solver_params is not None:\n        configstr += solver_params.tostring()\n    if conncomp_params is not None:\n        configstr += conncomp_params.tostring()\n\n    # Curve-fitting coefficients.\n    if corr_bias_model_params is not None:\n        configstr += corr_bias_model_params.tostring()\n    if phase_stddev_model_params is not None:\n        configstr += phase_stddev_model_params.tostring()\n\n    # Debug mode requires that a scratch directory is specified (otherwise, all\n    # debug output would be automatically discarded anyway).\n    if debug and (scratchdir is None):\n        raise ValueError(\"scratchdir path must be specified if debug is True\")\n\n    # If no scratch directory was specified, make a temporary one. Otherwise,\n    # create the directory if it doesn't already exist.\n    with scratch_directory(scratchdir) as d:\n        # SNAPHU expects flat binary data files, not GDAL rasters, as inputs &\n        # outputs. Therefore, we create some intermediate files in the scratch\n        # directory to pass to the backend code.\n\n        # Output unwrapped data\n        tmp_unw = d / \"unw.f4\"\n        configstr += f\"OUTFILE {tmp_unw.resolve()}\\n\"\n        configstr += f\"OUTFILEFORMAT FLOAT_DATA\\n\"\n\n        # Output connected component labels\n        tmp_conncomp = d / \"conncomp.u4\"\n        configstr += f\"CONNCOMPFILE {tmp_conncomp.resolve()}\\n\"\n        configstr += f\"CONNCOMPOUTTYPE UINT\\n\"\n\n        # Input interferogram\n        tmp_igram = d / \"igram.c8\"\n        to_flat_file(tmp_igram, igram, batchsize=1024)\n        configstr += f\"INFILE {tmp_igram.resolve()}\\n\"\n        configstr += f\"INFILEFORMAT COMPLEX_DATA\\n\"\n\n        # Input correlation magnitude\n        tmp_corr = d / \"corr.f4\"\n        to_flat_file(tmp_corr, corr, batchsize=1024)\n        configstr += f\"CORRFILE {tmp_corr.resolve()}\\n\"\n        configstr += f\"CORRFILEFORMAT FLOAT_DATA\\n\"\n\n        # Input SLC intensity data\n        if pwr is not None:\n            if cost != \"topo\":\n                raise ValueError(\"SLC intensity data is only used in 'topo' mode\")\n            if pwr.datatype != isce3.io.gdal.GDT_Float32:\n                raise TypeError(\"pwr raster must have GDT_Float32 datatype\")\n            if (pwr.length != length) or (pwr.width != width):\n                raise ValueError(\"pwr raster dimensions must match interferogram\")\n\n            tmp_pwr = d / \"pwr.f4\"\n            to_flat_file(tmp_pwr, pwr, batchsize=1024)\n            configstr += f\"PWRFILE {tmp_pwr.resolve()}\\n\"\n            configstr += f\"AMPFILEFORMAT FLOAT_DATA\\n\"\n\n        # Input data mask\n        if mask is not None:\n            if mask.datatype != isce3.io.gdal.GDT_Byte:\n                raise TypeError(\"mask raster must have GDT_Byte datatype\")\n            if (mask.length != length) or (mask.width != width):\n                raise ValueError(\"mask raster dimensions must match interferogram\")\n\n            tmp_mask = d / \"mask.i1\"\n            to_flat_file(tmp_mask, mask, batchsize=1024)\n            configstr += f\"BYTEMASKFILE {tmp_mask.resolve()}\\n\"\n\n        # Input unwrapped phase estimate\n        if unwest is not None:\n            if unwest.datatype != isce3.io.gdal.GDT_Float32:\n                raise TypeError(\"unwest raster must have GDT_Float32 datatype\")\n            if (unwest.length != length) or (unwest.width != width):\n                raise ValueError(\"unwest raster dimensions must match interferogram\")\n\n            tmp_unwest = d / \"unwest.f4\"\n            to_flat_file(tmp_unwest, unwest, batchsize=1024)\n            configstr += f\"ESTIMATEFILE {tmp_unwest.resolve()}\\n\"\n            configstr += f\"ESTFILEFORMAT FLOAT_DATA\\n\"\n\n        configstr += f\"DEBUG {debug}\\n\"\n\n        # Ensure that debug outputs are written to the scratch directory.\n        if debug:\n            configstr += f\"INITFILE {(d / 'snaphu.init')}\\n\"\n            configstr += f\"FLOWFILE {(d / 'snaphu.flow')}\\n\"\n            configstr += f\"ROWCOSTFILE {(d / 'snaphu.rowcost')}\\n\"\n            configstr += f\"COLCOSTFILE {(d / 'snaphu.colcost')}\\n\"\n            configstr += f\"CORRDUMPFILE {(d / 'snaphu.corr')}\\n\"\n\n        # Write config params to file.\n        configpath = d / \"snaphu.conf\"\n        configpath.write_text(configstr)\n\n        # Run SNAPHU.\n        _snaphu_unwrap(str(configpath))\n\n        # Copy output data to GDAL rasters.\n        from_flat_file(tmp_unw, unw, batchsize=1024)\n        from_flat_file(tmp_conncomp, conncomp, batchsize=1024)\n", "meta": {"hexsha": "052aa30935c8426f4931cfe367c1e9e6acae779e", "size": 46796, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/packages/isce3/unwrap/snaphu.py", "max_stars_repo_name": "isce3-testing/isce3-circleci-poc", "max_stars_repo_head_hexsha": "ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/packages/isce3/unwrap/snaphu.py", "max_issues_repo_name": "isce3-testing/isce3-circleci-poc", "max_issues_repo_head_hexsha": "ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-23T00:00:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-23T00:00:31.000Z", "max_forks_repo_path": "python/packages/isce3/unwrap/snaphu.py", "max_forks_repo_name": "isce3-testing/isce3-circleci-poc", "max_forks_repo_head_hexsha": "ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-02T21:10:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T21:10:11.000Z", "avg_line_length": 41.8194816801, "max_line_length": 85, "alphanum_fraction": 0.6674288401, "include": true, "reason": "import numpy", "num_tokens": 11849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3007455664065234, "lm_q1q2_score": 0.18498494549695324}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2021 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Timothy Berkelbach <tim.berkelbach@gmail.com>\n#\n\n'''\nRestricted QCISD implementation\nThe 4-index integrals are saved on disk entirely (without using any symmetry).\n\nNote MO integrals are treated in chemist's notation\n\nRef:\n'''\n\n\nimport numpy\nimport numpy as np\n\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf.cc import rccsd_slow as rccsd\nfrom pyscf.cc import rintermediates as imd\nfrom pyscf import __config__\n\nBLKMIN = getattr(__config__, 'cc_ccsd_blkmin', 4)\nMEMORYMIN = getattr(__config__, 'cc_ccsd_memorymin', 2000)\n\n\ndef kernel(mycc, eris=None, t1=None, t2=None, max_cycle=50, tol=1e-8,\n           tolnormt=1e-6, verbose=None):\n    '''Same as ccsd.kernel with strings modified to correct the method name'''\n    log = logger.new_logger(mycc, verbose)\n    if eris is None:\n        eris = mycc.ao2mo(mycc.mo_coeff)\n    if t1 is None and t2 is None:\n        t1, t2 = mycc.get_init_guess(eris)\n    elif t2 is None:\n        t2 = mycc.get_init_guess(eris)[1]\n\n    cput1 = cput0 = (logger.process_clock(), logger.perf_counter())\n    eold = 0\n    eccsd = mycc.energy(t1, t2, eris)\n    log.info('Init E_corr(QCISD) = %.15g', eccsd)\n\n    if isinstance(mycc.diis, lib.diis.DIIS):\n        adiis = mycc.diis\n    elif mycc.diis:\n        adiis = lib.diis.DIIS(mycc, mycc.diis_file, incore=mycc.incore_complete)\n        adiis.space = mycc.diis_space\n    else:\n        adiis = None\n\n    conv = False\n    for istep in range(max_cycle):\n        t1new, t2new = mycc.update_amps(t1, t2, eris)\n        tmpvec = mycc.amplitudes_to_vector(t1new, t2new)\n        tmpvec -= mycc.amplitudes_to_vector(t1, t2)\n        normt = numpy.linalg.norm(tmpvec)\n        tmpvec = None\n        if mycc.iterative_damping < 1.0:\n            alpha = mycc.iterative_damping\n            t1new = (1-alpha) * t1 + alpha * t1new\n            t2new *= alpha\n            t2new += (1-alpha) * t2\n        t1, t2 = t1new, t2new\n        t1new = t2new = None\n        t1, t2 = mycc.run_diis(t1, t2, istep, normt, eccsd-eold, adiis)\n        eold, eccsd = eccsd, mycc.energy(t1, t2, eris)\n        log.info('cycle = %d  E_corr(QCISD) = %.15g  dE = %.9g  norm(t1,t2) = %.6g',\n                 istep+1, eccsd, eccsd - eold, normt)\n        cput1 = log.timer('QCISD iter', *cput1)\n        if abs(eccsd-eold) < tol and normt < tolnormt:\n            conv = True\n            break\n    log.timer('QCISD', *cput0)\n    return conv, eccsd, t1, t2\n\n\ndef update_amps(cc, t1, t2, eris):\n    # Ref: Hirata et al., J. Chem. Phys. 120, 2581 (2004) Eqs.(35)-(36)\n    nocc, nvir = t1.shape\n    fock = eris.fock\n\n    fov = fock[:nocc,nocc:].copy()\n    foo = fock[:nocc,:nocc].copy()\n    fvv = fock[nocc:,nocc:].copy()\n\n    Foo = imd.cc_Foo(0*t1,t2,eris)\n    Fvv = imd.cc_Fvv(0*t1,t2,eris)\n    Fov = imd.cc_Fov(t1,t2,eris)\n\n    Foo -= np.diag(np.diag(foo))\n    Fvv -= np.diag(np.diag(fvv))\n\n    # T1 equation\n    t1new = np.asarray(fov).conj().copy()\n    t1new +=   lib.einsum('ac,ic->ia', Fvv, t1)\n    t1new +=  -lib.einsum('ki,ka->ia', Foo, t1)\n    t1new += 2*lib.einsum('kc,kica->ia', Fov, t2)\n    t1new +=  -lib.einsum('kc,ikca->ia', Fov, t2)\n    t1new += 2*lib.einsum('kcai,kc->ia', eris.ovvo, t1)\n    t1new +=  -lib.einsum('kiac,kc->ia', eris.oovv, t1)\n    eris_ovvv = np.asarray(eris.ovvv)\n    t1new += 2*lib.einsum('kdac,ikcd->ia', eris_ovvv, t2)\n    t1new +=  -lib.einsum('kcad,ikcd->ia', eris_ovvv, t2)\n    t1new +=-2*lib.einsum('kilc,klac->ia', eris.ooov, t2)\n    t1new +=   lib.einsum('likc,klac->ia', eris.ooov, t2)\n\n    # T2 equation\n    t2new = np.asarray(eris.ovov).conj().transpose(0,2,1,3).copy()\n    Loo = imd.Loo(0*t1, t2, eris)\n    Lvv = imd.Lvv(0*t1, t2, eris)\n    Loo -= np.diag(np.diag(foo))\n    Lvv -= np.diag(np.diag(fvv))\n    Woooo = imd.cc_Woooo(0*t1, t2, eris)\n    Wvoov = imd.cc_Wvoov(0*t1, t2, eris)\n    Wvovo = imd.cc_Wvovo(0*t1, t2, eris)\n    Wvvvv = imd.cc_Wvvvv(0*t1, t2, eris)\n    t2new += lib.einsum('klij,klab->ijab', Woooo, t2)\n    t2new += lib.einsum('abcd,ijcd->ijab', Wvvvv, t2)\n    tmp = lib.einsum('ac,ijcb->ijab', Lvv, t2)\n    t2new += (tmp + tmp.transpose(1,0,3,2))\n    tmp = lib.einsum('ki,kjab->ijab', Loo, t2)\n    t2new -= (tmp + tmp.transpose(1,0,3,2))\n    tmp  = 2*lib.einsum('akic,kjcb->ijab', Wvoov, t2)\n    tmp -=   lib.einsum('akci,kjcb->ijab', Wvovo, t2)\n    t2new += (tmp + tmp.transpose(1,0,3,2))\n    tmp = lib.einsum('akic,kjbc->ijab', Wvoov, t2)\n    t2new -= (tmp + tmp.transpose(1,0,3,2))\n    tmp = lib.einsum('bkci,kjac->ijab', Wvovo, t2)\n    t2new -= (tmp + tmp.transpose(1,0,3,2))\n\n    tmp2 = np.asarray(eris.ovvv).conj().transpose(1,3,0,2)\n    tmp = lib.einsum('abic,jc->ijab', tmp2, t1)\n    t2new += (tmp + tmp.transpose(1,0,3,2))\n    tmp2 = np.asarray(eris.ooov).transpose(3,1,2,0).conj()\n    tmp = lib.einsum('akij,kb->ijab', tmp2, t1)\n    t2new -= (tmp + tmp.transpose(1,0,3,2))\n\n    mo_e = eris.fock.diagonal().real\n    eia = mo_e[:nocc,None] - mo_e[None,nocc:]\n    eijab = lib.direct_sum('ia,jb->ijab',eia,eia)\n    t1new /= eia\n    t2new /= eijab\n\n    return t1new, t2new\n\n\nclass QCISD(rccsd.RCCSD):\n    '''restricted QCISD\n    '''\n\n    def kernel(self, t1=None, t2=None, eris=None):\n        return self.qcisd(t1, t2, eris)\n    def qcisd(self, t1=None, t2=None, eris=None):\n        assert(self.mo_coeff is not None)\n        assert(self.mo_occ is not None)\n\n        if self.verbose >= logger.WARN:\n            self.check_sanity()\n        self.dump_flags()\n\n        if eris is None:\n            eris = self.ao2mo(self.mo_coeff)\n\n        self.e_hf = getattr(eris, 'e_hf', None)\n        if self.e_hf is None:\n            self.e_hf = self._scf.e_tot\n\n        self.converged, self.e_corr, self.t1, self.t2 = \\\n                kernel(self, eris, t1, t2, max_cycle=self.max_cycle,\n                       tol=self.conv_tol, tolnormt=self.conv_tol_normt,\n                       verbose=self.verbose)\n        self._finalize()\n        return self.e_corr, self.t1, self.t2\n\n    def energy(self, t1=None, t2=None, eris=None):\n        return rccsd.energy(self, t1*0, t2, eris)\n\n    update_amps = update_amps\n\n    def qcisd_t(self, t1=None, t2=None, eris=None):\n        from pyscf.cc import qcisd_t_slow as qcisd_t\n        if t1 is None: t1 = self.t1\n        if t2 is None: t2 = self.t2\n        if eris is None: eris = self.ao2mo(self.mo_coeff)\n        return qcisd_t.kernel(self, eris, t1, t2, self.verbose)\n\n    def density_fit(self, auxbasis=None, with_df=None):\n        raise NotImplementedError\n\n\nif __name__ == '__main__':\n    from pyscf import gto, scf\n\n    mol = gto.Mole()\n    mol.atom = \"\"\"C  0.000  0.000  0.000\n                  H  0.637  0.637  0.637\n                  H -0.637 -0.637  0.637\n                  H -0.637  0.637 -0.637\n                  H  0.637 -0.637 -0.637\"\"\"\n    mol.basis = 'cc-pvdz'\n    mol.verbose = 7\n    mol.spin = 0\n    mol.build()\n    mf = scf.RHF(mol).run(conv_tol=1e-14)\n\n    mycc = QCISD(mf, frozen=1)\n    ecc, t1, t2 = mycc.kernel()\n    print(mycc.e_tot - -40.383989)\n    et = mycc.qcisd_t()\n    print(mycc.e_tot+et - -40.387679)\n", "meta": {"hexsha": "379f9b18b0f2a32772ebfa561842c5c560322a8b", "size": 7610, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/cc/qcisd_slow.py", "max_stars_repo_name": "umamibeef/pyscf", "max_stars_repo_head_hexsha": "1263d54b02914caf4476a3ed9a2de5e0c848954c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 501, "max_stars_repo_stars_event_min_datetime": "2018-12-06T23:48:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:53:18.000Z", "max_issues_repo_path": "pyscf/cc/qcisd_slow.py", "max_issues_repo_name": "fabijan5/pyscf", "max_issues_repo_head_hexsha": "09834c8f5a4f5320cdde29d285b6ccd89b3263e0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 710, "max_issues_repo_issues_event_min_datetime": "2018-11-26T22:04:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:53:12.000Z", "max_forks_repo_path": "pyscf/cc/qcisd_slow.py", "max_forks_repo_name": "fabijan5/pyscf", "max_forks_repo_head_hexsha": "09834c8f5a4f5320cdde29d285b6ccd89b3263e0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 273, "max_forks_repo_forks_event_min_datetime": "2018-11-26T10:10:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:25:28.000Z", "avg_line_length": 33.6725663717, "max_line_length": 84, "alphanum_fraction": 0.6082785808, "include": true, "reason": "import numpy", "num_tokens": 2734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878414043814, "lm_q2_score": 0.30074557267388247, "lm_q1q2_score": 0.1849849451079029}}
{"text": "\"\"\"\nEnergy-conserving solver for the binary accretion problem in 2D.\n\"\"\"\n\nfrom typing import NamedTuple\nfrom logging import getLogger\nfrom sailfish.kernel.library import Library\nfrom sailfish.kernel.system import get_array_module, execution_context, num_devices\nfrom sailfish.mesh import PlanarCartesian2DMesh\nfrom sailfish.physics.circumbinary import Physics, EquationOfState, ViscosityModel\nfrom sailfish.solver import SolverBase\nfrom sailfish.subdivide import subdivide, concat_on_host, lazy_reduce\n\n\nlogger = getLogger(__name__)\n\n\nclass Options(NamedTuple):\n    pressure_floor: float = 1e-12\n    density_floor: float = 1e-10\n    velocity_ceiling: float = 1e16\n    mach_ceiling: float = 1e5\n\n\ndef initial_condition(setup, mesh, time):\n    \"\"\"\n    Generate a 2D array of primitive data from a mesh and a setup.\n    \"\"\"\n    import numpy as np\n\n    ni, nj = mesh.shape\n    primitive = np.zeros([ni, nj, 4])\n\n    for i in range(ni):\n        for j in range(nj):\n            setup.primitive(time, mesh.cell_coordinates(i, j), primitive[i, j])\n\n    return primitive\n\n\nclass Patch:\n    \"\"\"\n    Holds the array buffer state for the solution on a subset of the\n    solution domain.\n    \"\"\"\n\n    def __init__(\n        self,\n        time,\n        primitive,\n        mesh,\n        index_range,\n        physics,\n        options,\n        buffer_outer_radius,\n        buffer_surface_density,\n        buffer_surface_pressure,\n        lib,\n        xp,\n        execution_context,\n    ):\n        i0, i1 = index_range\n        ni, nj = i1 - i0, mesh.shape[1]\n        self.lib = lib\n        self.mesh = mesh\n        self.xp = xp\n        self.execution_context = execution_context\n        self.time = self.time0 = time\n        self.shape = (i1 - i0, nj)  # not including guard zones\n        self.physics = physics\n        self.options = options\n        self.xl, self.yl = mesh.vertex_coordinates(i0, 0)\n        self.xr, self.yr = mesh.vertex_coordinates(i1, nj)\n        self.buffer_outer_radius = buffer_outer_radius\n        self.buffer_surface_density = buffer_surface_density\n        self.buffer_surface_pressure = buffer_surface_pressure\n\n        with self.execution_context:\n            self.wavespeeds = self.xp.zeros(primitive.shape[:2])\n            self.primitive1 = self.xp.array(primitive)\n            self.primitive2 = self.xp.array(primitive)\n            self.conserved0 = self.xp.zeros(primitive.shape)\n\n    def point_mass_source_term(self, which_mass):\n        if which_mass not in (1, 2):\n            raise ValueError(\"the mass must be either 1 or 2\")\n\n        m1, m2 = self.physics.point_masses(self.time)\n        with self.execution_context:\n            cons_rate = self.xp.zeros_like(self.conserved0)\n            self.lib.cbdgam_2d_point_mass_source_term[self.shape](\n                self.xl,\n                self.xr,\n                self.yl,\n                self.yr,\n                m1.position_x,\n                m1.position_y,\n                m1.velocity_x,\n                m1.velocity_y,\n                m1.mass,\n                m1.softening_length,\n                m1.sink_rate,\n                m1.sink_radius,\n                m1.sink_model.value,\n                m2.position_x,\n                m2.position_y,\n                m2.velocity_x,\n                m2.velocity_y,\n                m2.mass,\n                m2.softening_length,\n                m2.sink_rate,\n                m2.sink_radius,\n                m2.sink_model.value,\n                which_mass,\n                self.primitive1,\n                cons_rate,\n                int(self.physics.constant_softening),\n                self.physics.gamma_law_index,\n            )\n            return cons_rate\n\n    def maximum_wavespeed(self):\n        with self.execution_context:\n            self.lib.cbdgam_2d_wavespeed[self.shape](\n                self.primitive1,\n                self.wavespeeds,\n                self.physics.gamma_law_index,\n            )\n            return self.wavespeeds.max()\n\n    def recompute_conserved(self):\n        with self.execution_context:\n            return self.lib.cbdgam_2d_primitive_to_conserved[self.shape](\n                self.primitive1,\n                self.conserved0,\n                self.physics.gamma_law_index,\n            )\n\n    def advance_rk(self, rk_param, dt):\n        m1, m2 = self.physics.point_masses(self.time)\n        buffer_central_mass = m1.mass + m2.mass\n        buffer_surface_density = self.buffer_surface_density\n        buffer_surface_pressure = self.buffer_surface_pressure\n\n        with self.execution_context:\n            self.lib.cbdgam_2d_advance_rk[self.shape](\n                self.xl,\n                self.xr,\n                self.yl,\n                self.yr,\n                self.conserved0,\n                self.primitive1,\n                self.primitive2,\n                self.physics.gamma_law_index,\n                buffer_surface_density,\n                buffer_surface_pressure,\n                buffer_central_mass,\n                self.physics.buffer_driving_rate,\n                self.buffer_outer_radius,\n                self.physics.buffer_onset_width,\n                int(self.physics.buffer_is_enabled),\n                m1.position_x,\n                m1.position_y,\n                m1.velocity_x,\n                m1.velocity_y,\n                m1.mass,\n                m1.softening_length,\n                m1.sink_rate,\n                m1.sink_radius,\n                m1.sink_model.value,\n                m2.position_x,\n                m2.position_y,\n                m2.velocity_x,\n                m2.velocity_y,\n                m2.mass,\n                m2.softening_length,\n                m2.sink_rate,\n                m2.sink_radius,\n                m2.sink_model.value,\n                self.physics.alpha,\n                rk_param,\n                dt,\n                self.options.velocity_ceiling,\n                self.physics.cooling_coefficient,\n                self.options.mach_ceiling,\n                self.options.density_floor,\n                self.options.pressure_floor,\n                int(self.physics.constant_softening),\n            )\n\n        self.time = self.time0 * rk_param + (self.time + dt) * (1.0 - rk_param)\n        self.primitive1, self.primitive2 = self.primitive2, self.primitive1\n\n    def new_iteration(self):\n        self.time0 = self.time\n        self.recompute_conserved()\n\n    @property\n    def primitive(self):\n        return self.primitive1\n\n\nclass Solver(SolverBase):\n    \"\"\"\n    Adapter class to drive the cbdgam_2d C extension module.\n    \"\"\"\n\n    def __init__(\n        self,\n        setup=None,\n        mesh=None,\n        time=0.0,\n        solution=None,\n        num_patches=1,\n        mode=\"cpu\",\n        physics=dict(),\n        options=dict(),\n    ):\n        import numpy as np\n\n        self._physics = physics = Physics(**physics)\n        self._options = options = Options(**options)\n\n        if type(mesh) is not PlanarCartesian2DMesh:\n            raise ValueError(\"solver only supports 2D cartesian mesh\")\n\n        if setup.boundary_condition != \"outflow\":\n            raise ValueError(\"solver only supports outflow boundary condition\")\n\n        if physics.viscosity_model not in (\n            ViscosityModel.NONE,\n            ViscosityModel.CONSTANT_ALPHA,\n        ):\n            raise ValueError(\"solver only supports constant-nu viscosity\")\n\n        if physics.eos_type != EquationOfState.GAMMA_LAW:\n            raise ValueError(\"solver only supports isothermal equation of states\")\n\n        xp = get_array_module(mode)\n        ng = 2  # number of guard zones\n        nq = 4  # number of conserved quantities\n        with open(__file__.replace(\".py\", \".c\")) as f:\n            code = f.read()\n        lib = Library(code, mode=mode, debug=True)\n\n        logger.info(f\"initiate with time={time:0.4f}\")\n        logger.info(f\"subdivide grid over {num_patches} patches\")\n        logger.info(f\"mesh is {mesh}\")\n        logger.info(f\"boundary condition is outflow\")\n\n        self.mesh = mesh\n        self.setup = setup\n        self.num_guard = ng\n        self.num_cons = nq\n        self.xp = xp\n        self.patches = []\n        ni, nj = mesh.shape\n        self.domain_radius = self.mesh.x1\n        self.buffer_onset_width = 0.1\n\n        if solution is None:\n            primitive = initial_condition(setup, mesh, time)\n        else:\n            primitive = solution\n\n        if physics.buffer_is_enabled:\n            # Here we sample the initial condition at the buffer onset radius\n            # to determine the disk surface density at the radius where the\n            # buffer begins to ramp up. This procedure makes sense as long as\n            # the initial condition is axisymmetric.\n            buffer_prim = [0.0] * 4\n            buffer_outer_radius = mesh.x1  # this assumes the mesh is a centered squared\n            buffer_onset_radius = buffer_outer_radius - physics.buffer_onset_width\n            setup.primitive(time, [buffer_onset_radius, 0.0], buffer_prim)\n            buffer_surface_density = buffer_prim[0]\n            buffer_surface_pressure = buffer_prim[3]\n        else:\n            buffer_outer_radius = 0.0\n            buffer_surface_density = 0.0\n            buffer_surface_pressure = 0.0\n\n        for n, (a, b) in enumerate(subdivide(ni, num_patches)):\n            prim = np.zeros([b - a + 2 * ng, nj + 2 * ng, nq])\n            prim[ng:-ng, ng:-ng] = primitive[a:b]\n            patch = Patch(\n                time,\n                prim,\n                mesh,\n                (a, b),\n                physics,\n                options,\n                buffer_outer_radius,\n                buffer_surface_density,\n                buffer_surface_pressure,\n                lib,\n                xp,\n                execution_context(mode, device_id=n % num_devices(mode)),\n            )\n            self.patches.append(patch)\n\n    @property\n    def solution(self):\n        return self.primitive\n\n    @property\n    def primitive(self):\n        return concat_on_host(\n            [p.primitive for p in self.patches], (self.num_guard, self.num_guard)\n        )\n\n    @property\n    def time(self):\n        return self.patches[0].time\n\n    @property\n    def options(self):\n        return self._options._asdict()\n\n    @property\n    def physics(self):\n        return self._physics._asdict()\n\n    @property\n    def recommended_cfl(self):\n        return 0.1\n\n    @property\n    def maximum_cfl(self):\n        return 0.4\n\n    def maximum_wavespeed(self):\n        return lazy_reduce(\n            max,\n            float,\n            (patch.maximum_wavespeed for patch in self.patches),\n            (patch.execution_context for patch in self.patches),\n        )\n\n    def advance(self, dt):\n        self.new_iteration()\n        self.advance_rk(0.0, dt)\n        self.advance_rk(0.5, dt)\n\n    def advance_rk(self, rk_param, dt):\n        self.set_bc(\"primitive1\")\n        for patch in self.patches:\n            patch.advance_rk(rk_param, dt)\n\n    def set_bc(self, array):\n        ng = self.num_guard\n        num_patches = len(self.patches)\n        for i0 in range(num_patches):\n            il = (i0 + num_patches - 1) % num_patches\n            ir = (i0 + num_patches + 1) % num_patches\n            pl = getattr(self.patches[il], array)\n            pc = getattr(self.patches[i0], array)\n            pr = getattr(self.patches[ir], array)\n            self.set_bc_patch(pl, pc, pr, i0)\n\n    def set_bc_patch(self, pl, pc, pr, patch_index):\n        ni, nj = self.mesh.shape\n        ng = self.num_guard\n\n        # 1. write to the guard zones of pc, the internal BC\n        pc[:+ng] = pl[-2 * ng : -ng]\n        pc[-ng:] = pr[+ng : +2 * ng]\n\n        # 2. Set outflow BC on the left/right patch edges\n        if patch_index == 0:\n            for i in range(ng):\n                pc[i] = pc[ng]\n        if patch_index == len(self.patches) - 1:\n            for i in range(pc.shape[0] - ng, pc.shape[0]):\n                pc[i] = pc[-ng - 1]\n\n        # 3. Set outflow BC on bottom and top edges\n        for i in range(ng):\n            pc[:, i] = pc[:, ng]\n\n        for i in range(pc.shape[1] - ng, pc.shape[1]):\n            pc[:, i] = pc[:, -ng - 1]\n\n    def new_iteration(self):\n        for patch in self.patches:\n            patch.new_iteration()\n", "meta": {"hexsha": "163ac8d273fef226d18628679e729364b7dea967", "size": 12218, "ext": "py", "lang": "Python", "max_stars_repo_path": "sailfish/solvers/cbdgam_2d.py", "max_stars_repo_name": "jwestern/sailfish", "max_stars_repo_head_hexsha": "a594ab13060bfe760a4f79cfb4923e1691949ba6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sailfish/solvers/cbdgam_2d.py", "max_issues_repo_name": "jwestern/sailfish", "max_issues_repo_head_hexsha": "a594ab13060bfe760a4f79cfb4923e1691949ba6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sailfish/solvers/cbdgam_2d.py", "max_forks_repo_name": "jwestern/sailfish", "max_forks_repo_head_hexsha": "a594ab13060bfe760a4f79cfb4923e1691949ba6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6528497409, "max_line_length": 88, "alphanum_fraction": 0.5631036176, "include": true, "reason": "import numpy", "num_tokens": 2759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.3140505449918074, "lm_q1q2_score": 0.18494095245738937}}
{"text": "\"\"\"Wrapper for performing an electronic circular dichroism (ECD)\ncalculation.\"\"\"\n\nimport numpy as np\n\nfrom pyresponse.constants import HARTREE_TO_EV, HARTREE_TO_INVCM, alpha, esuecd\nfrom pyresponse.core import Program\nfrom pyresponse.molecular_property import TransitionProperty\nfrom pyresponse.operators import Operator\nfrom pyresponse.td import TDHF\nfrom pyresponse.utils import form_indices_zero\n\n\nclass ECD(TransitionProperty):\n    \"\"\"Wrapper for performing an electronic circular dichroism (ECD)\n    calculation.\n    \"\"\"\n\n    def __init__(\n        self,\n        program: Program,\n        program_obj,\n        driver: TDHF,\n        mocoeffs: np.ndarray,\n        moenergies: np.ndarray,\n        occupations: np.ndarray,\n        *,\n        do_tda: bool = False,\n        do_dipvel: bool = False,\n    ) -> None:\n        super().__init__(\n            program, program_obj, driver, mocoeffs, moenergies, occupations, do_tda=do_tda\n        )\n        self.do_dipvel = do_dipvel\n\n    def form_operators(self) -> None:\n\n        if self.program == Program.PySCF:\n            from pyresponse.pyscf import integrals\n\n            integral_generator = integrals.IntegralsPyscf(self.program_obj)\n        elif self.program == Program.Psi4:\n            from pyresponse.psi4 import integrals\n\n            integral_generator = integrals.IntegralsPsi4(self.program_obj)\n        else:\n            raise RuntimeError\n\n        operator_angmom = Operator(\n            label=\"angmom\", is_imaginary=True, is_spin_dependent=False, triplet=False\n        )\n        operator_angmom.ao_integrals = integral_generator.integrals(integrals.ANGMOM_COMMON_GAUGE)\n        self.driver.add_operator(operator_angmom)\n\n        operator_diplen = Operator(\n            label=\"dipole\", is_imaginary=False, is_spin_dependent=False, triplet=False\n        )\n        operator_diplen.ao_integrals = integral_generator.integrals(integrals.DIPOLE)\n        self.driver.add_operator(operator_diplen)\n\n        if self.do_dipvel:\n            operator_dipvel = Operator(\n                label=\"dipvel\", is_imaginary=True, is_spin_dependent=False, triplet=False\n            )\n            operator_dipvel.ao_integrals = integral_generator.integrals(integrals.DIPVEL)\n            self.driver.add_operator(operator_dipvel)\n\n    def form_results(self) -> None:\n\n        operator_angmom = self.driver.solver.operators[0]\n        operator_diplen = self.driver.solver.operators[1]\n        assert len(operator_angmom.transition_moments) == len(operator_diplen.transition_moments)\n        nstates = len(operator_diplen.transition_moments)\n        rotational_strengths_diplen = []\n        rotational_strengths_dipvel = []\n        if self.do_dipvel:\n            assert len(self.driver.solver.operators) == 3\n            operator_dipvel = self.driver.solver.operators[2]\n            assert len(operator_dipvel.transition_moments) == nstates\n        for stateidx in range(nstates):\n            print(\"-\" * 78)\n            eigval = self.driver.solver.eigvals[stateidx].real\n            rotstr_diplen = (\n                esuecd\n                * (-1 / 2)\n                * np.dot(\n                    operator_diplen.transition_moments[stateidx],\n                    operator_angmom.transition_moments[stateidx],\n                )\n            )\n            print(\"length  \", rotstr_diplen)\n            rotational_strengths_diplen.append(rotstr_diplen)\n            if self.do_dipvel:\n                rotstr_dipvel = (\n                    esuecd\n                    * (-1 / 2)\n                    * np.dot(\n                        operator_dipvel.transition_moments[stateidx] / eigval,\n                        operator_angmom.transition_moments[stateidx],\n                    )\n                )\n                print(\"velocity\", rotstr_dipvel)\n                rotational_strengths_dipvel.append(rotstr_dipvel)\n        self.rotational_strengths_diplen = np.array(rotational_strengths_diplen)\n        if self.do_dipvel:\n            self.rotational_strengths_dipvel = np.array(rotational_strengths_dipvel)\n\n    def print_results_nwchem(self) -> str:\n        excitation_block = self.driver.print_results_nwchem()\n        lines = [excitation_block]\n        energies = self.driver.solver.eigvals.real\n        energies_ev = energies * HARTREE_TO_EV\n        op_diplen = self.driver.solver.operators[1]\n        tmom_diplen = op_diplen.transition_moments\n        etoscslen = op_diplen.total_oscillator_strengths\n        op_angmom = self.driver.solver.operators[0]\n        tmom_angmom = op_angmom.transition_moments\n        rotstrlen = self.rotational_strengths_diplen\n        if self.do_dipvel:\n            op_dipvel = self.driver.solver.operators[2]\n            rotstrvel = self.rotational_strengths_dipvel\n            tmom_dipvel = op_dipvel.transition_moments\n            etoscsvel = op_dipvel.total_oscillator_strengths\n        nstates = len(energies)\n        for state in range(nstates):\n            lines.append(\n                \"  ----------------------------------------------------------------------------\"\n            )\n            lines.append(\n                f\"  Root {state + 1:>3d} singlet a{energies[state]:>25.9f} a.u.{energies_ev[state]:>22.4f} eV\"\n            )\n            lines.append(\n                \"  ----------------------------------------------------------------------------\"\n            )\n            lines.append(\n                f\"     Transition Moments    X{tmom_diplen[state, 0]:>9.5f}   Y{tmom_diplen[state, 1]:>9.5f}   Z{tmom_diplen[state, 2]:>9.5f}\"\n            )\n            ## TODO these require second moment (length) integrals\n            ## lines.append(f'     Transition Moments   XX -0.28379  XY  0.08824  XZ -0.17416')\n            ## lines.append(f'     Transition Moments   YY -0.40247  YZ -0.45981  ZZ  0.59211')\n            lines.append(f\"     Dipole Oscillator Strength {etoscslen[state]:>31.5f}\")\n            lines.append(\"\")\n            lines.append(\"     Electric Transition Dipole:\")\n            lines.append(\n                f\"            X{tmom_diplen[state, 0]:>13.7f}   Y{tmom_diplen[state, 1]:>13.7f}   Z{tmom_diplen[state, 2]:>13.7f}\"\n            )\n            lines.append(\"     Magnetic Transition Dipole (Length):\")\n            lines.append(\n                f\"            X{tmom_angmom[state, 0]:>13.7f}   Y{tmom_angmom[state, 1]:>13.7f}   Z{tmom_angmom[state, 2]:>13.7f}\"\n            )\n            lines.append(\"     Magnetic Transition Dipole * 1/c :\")\n            lines.append(\n                f\"            X{tmom_angmom[state, 0] * alpha:>13.7f}   Y{tmom_angmom[state, 1] * alpha:>13.7f}   Z{tmom_angmom[state, 2] * alpha:>13.7f}\"\n            )\n            lines.append(f\"     Rotatory Strength (1E-40 esu**2cm**2):{rotstrlen[state]:>21.7f}\")\n            lines.append(\"\")\n            if self.do_dipvel:\n                lines.append(\"     Electric Transition Dipole (velocity representation):\")\n                lines.append(\n                    f\"            X{tmom_dipvel[state, 0]:>13.7f}   Y{tmom_dipvel[state, 1]:>13.7f}   Z{tmom_dipvel[state, 2]:>13.7f}\"\n                )\n                # lines.append(f'     Oscillator Strength (velocity repr.) :            0.0069989')\n                lines.append(\n                    f\"     Oscillator Strength (velocity repr.) :{etoscsvel[state]:>21.7f}\"\n                )\n                # lines.append(f'     Oscillator Strength (mixed repr.   ) :            0.0074981')\n                # lines.append(f'     Oscillator Strength (mixed repr.   ) :{>21.7f}')\n                lines.append(\n                    f\"     Rotatory Strength   (velocity repr.) :{rotstrvel[state]:>21.7f}\"\n                )\n                lines.append(\"\")\n            # lines.append(str(self.driver.solver.eigvecs[:, state]))\n            # lines.append(str(self.driver.solver.eigvecs_normed[:, state]))\n\n        return \"\\n\".join(lines)\n\n    def print_results_orca(self) -> str:\n        excitation_block = self.driver.print_results_orca()\n        lines = [excitation_block]\n        energies = self.driver.solver.eigvals.real\n        energies_to_invcm = energies * HARTREE_TO_INVCM\n        energies_to_nm = 10000000 / energies_to_invcm\n        op_diplen = self.driver.solver.operators[1]\n        etoscslen = op_diplen.total_oscillator_strengths\n        tmom_diplen = op_diplen.transition_moments\n        t2_diplen = np.asarray(\n            [np.dot(tmom_diplen[x], tmom_diplen[x]) for x in range(len(tmom_diplen))]\n        )\n        rotstrlen = self.rotational_strengths_diplen\n        op_angmom = self.driver.solver.operators[0]\n        tmom_angmom = op_angmom.transition_moments\n        if self.do_dipvel:\n            op_dipvel = self.driver.solver.operators[2]\n            rotstrvel = self.rotational_strengths_dipvel\n            etoscsvel = op_dipvel.total_oscillator_strengths\n            tmom_dipvel = op_dipvel.transition_moments\n            t2_dipvel = np.asarray(\n                [np.dot(tmom_dipvel[x], tmom_dipvel[x]) for x in range(len(tmom_dipvel))]\n            )\n        nstates = len(energies)\n        lines.append(\n            \"-----------------------------------------------------------------------------\"\n        )\n        lines.append(\"         ABSORPTION SPECTRUM VIA TRANSITION ELECTRIC DIPOLE MOMENTS\")\n        lines.append(\n            \"-----------------------------------------------------------------------------\"\n        )\n        lines.append(\"State   Energy  Wavelength   fosc         T2         TX        TY        TZ\")\n        lines.append(\"        (cm-1)    (nm)                  (au**2)     (au)      (au)      (au)\")\n        lines.append(\n            \"-----------------------------------------------------------------------------\"\n        )\n        for state in range(nstates):\n            lines.append(\n                f\"{state + 1:>4d}{energies_to_invcm[state]:>10.1f}{energies_to_nm[state]:>9.1f}{etoscslen[state]:>14.9f}{t2_diplen[state]:>10.5f}{tmom_diplen[state, 0]:>10.5f}{tmom_diplen[state, 1]:>10.5f}{tmom_diplen[state, 2]:>10.5f}\"\n            )\n        lines.append(\"\")\n        lines.append(\n            \"-----------------------------------------------------------------------------\"\n        )\n        lines.append(\"         ABSORPTION SPECTRUM VIA TRANSITION VELOCITY DIPOLE MOMENTS\")\n        lines.append(\n            \"-----------------------------------------------------------------------------\"\n        )\n        lines.append(\"State   Energy  Wavelength   fosc         P2         PX        PY        PZ\")\n        lines.append(\"        (cm-1)    (nm)                  (au**2)     (au)      (au)      (au)\")\n        lines.append(\n            \"-----------------------------------------------------------------------------\"\n        )\n        for state in range(nstates):\n            lines.append(\n                f\"{state + 1:>4d}{energies_to_invcm[state]:>10.1f}{energies_to_nm[state]:>9.1f}{etoscsvel[state]:>14.9f}{t2_dipvel[state]:>10.5f}{tmom_dipvel[state, 0]:>10.5f}{tmom_dipvel[state, 1]:>10.5f}{tmom_dipvel[state, 2]:>10.5f}\"\n            )\n        lines.append(\"\")\n        lines.append(\"-------------------------------------------------------------------\")\n        lines.append(\"                             CD SPECTRUM\")\n        lines.append(\"-------------------------------------------------------------------\")\n        lines.append(\"State   Energy Wavelength       R         MX        MY        MZ\")\n        lines.append(\"        (cm-1)   (nm)       (1e40*cgs)   (au)      (au)      (au)\")\n        lines.append(\"-------------------------------------------------------------------\")\n        for state in range(nstates):\n            lines.append(\n                f\"{state + 1:>4d}{energies_to_invcm[state]:>10.1f}{energies_to_nm[state]:>9.1f}{rotstrlen[state]:>13.5f}{tmom_angmom[state, 0]:>10.5f}{tmom_angmom[state, 1]:>10.5f}{tmom_angmom[state, 2]:>10.5f}\"\n            )\n        lines.append(\"\")\n        return \"\\n\".join(lines)\n\n    _HAMILTONIAN_PREFIX_QCHEM = {\"tda\": \"\", \"rpa\": \"X: \"}\n\n    # TODO cutoff taken from ORCA, check the source code to see the\n    # real criterion\n    def print_results_qchem(self, cutoff: float = 0.01) -> str:\n        energies = self.driver.solver.eigvals.real\n        energies_ev = energies * HARTREE_TO_EV\n        op_diplen = self.driver.solver.operators[1]\n        tmom_diplen = op_diplen.transition_moments\n        etoscslen = op_diplen.total_oscillator_strengths\n        nocc_tot, nvirt_tot, _, _ = self.driver.solver.occupations\n        indices = form_indices_zero(nocc_tot, nvirt_tot)\n        eigvecs = self.driver.solver.eigvecs\n        square_eigvecs = np.power(eigvecs, 2)\n        lines = []\n        lines.append(\" ---------------------------------------------------\")\n        lines.append(\n            f\"               {self.driver._HAMILTONIAN_MAP_ORCA[self.driver.hamiltonian]} Excitation Energies              \"\n        )\n        lines.append(\" ---------------------------------------------------\")\n        lines.append(\"\")\n        nstates = len(energies)\n        for state in range(nstates):\n            lines.append(\n                f\" Excited state{state + 1:>4d}: excitation energy (eV) ={energies_ev[state]:>10.4f}\"\n            )\n            lines.append(f\" Total energy for state{state + 1:>3d}:{0:>31.8f} au\")\n            lines.append(f\"    Multiplicity: {self.driver._SPIN_MAP_QCHEM[self.driver.spin]}\")\n            lines.append(\n                f\"    Trans. Mom.:{tmom_diplen[state, 0]:>8.4f} X{tmom_diplen[state, 1]:>9.4f} Y{tmom_diplen[state, 2]:>9.4f} Z\"\n            )\n            lines.append(f\"    Strength   :{etoscslen[state]:>17.10f}\")\n            eigvec_state = eigvecs[:, state]\n            square_eigvec_state = square_eigvecs[:, state]\n            mask = square_eigvec_state > cutoff\n            coeffs_cutoff = eigvec_state[mask]\n            mask_indices = np.array([p for (p, b) in enumerate(mask) if b])\n            for i in range(len(coeffs_cutoff)):\n                iocc, ivirt = indices[mask_indices[i]]\n                lines.append(\n                    f\"    {self._HAMILTONIAN_PREFIX_QCHEM[self.driver.hamiltonian]}D({iocc + 1:>3d}) --> V({ivirt + 1:>3d}) amplitude ={coeffs_cutoff[i]:>8.4f}\"\n                )\n            lines.append(\"\")\n        return \"\\n\".join(lines)\n", "meta": {"hexsha": "14b534bd2cff587a6a80064e1322b38bb50dd9a4", "size": 14206, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyresponse/properties/ecd.py", "max_stars_repo_name": "berquist/pyresponse", "max_stars_repo_head_hexsha": "3267b0ca1e5b2e638cd2388532897f2749af8397", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2017-09-26T07:02:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T15:01:16.000Z", "max_issues_repo_path": "pyresponse/properties/ecd.py", "max_issues_repo_name": "berquist/pyresponse", "max_issues_repo_head_hexsha": "3267b0ca1e5b2e638cd2388532897f2749af8397", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2018-02-17T22:32:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-19T03:25:13.000Z", "max_forks_repo_path": "pyresponse/properties/ecd.py", "max_forks_repo_name": "berquist/pyresponse", "max_forks_repo_head_hexsha": "3267b0ca1e5b2e638cd2388532897f2749af8397", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-03-25T01:16:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T07:55:52.000Z", "avg_line_length": 48.6506849315, "max_line_length": 236, "alphanum_fraction": 0.5368154301, "include": true, "reason": "import numpy", "num_tokens": 3557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.18487308530687224}}
{"text": "#!/usr/bin/env python\n\"\"\"\nBuilding blocks for Blow\n\nSerra, J., Pascual, S. & Segura, C. Blow: a single-scale hyperconditioned flow \nfor non-parallel raw-audio voice conversion. in Proc. NIPS (2019). \n\nReference: https://github.com/joansj/blow\n\"\"\"\nfrom __future__ import absolute_import\n\nimport sys\nimport numpy as np\n\nimport torch\nimport torch.nn as torch_nn\nimport torch.nn.functional as torch_nn_func\nimport torch.nn.init as torch_init\n\nimport sandbox.block_glow as nii_glow\nimport core_scripts.data_io.wav_tools as nii_wav_tk\nimport core_scripts.data_io.conf as nii_io_conf\nimport core_scripts.other_tools.debug as nii_debug\n\n__author__ = \"Xin Wang\"\n__email__ = \"wangxin@nii.ac.jp\"\n__copyright__ = \"Copyright 2021, Xin Wang\"\n\n\n#######################################\n# Numpy utilities for data augmentation\n#######################################\ndef flip(x):\n    \"\"\"y=flip(x) flips the sign of x\n    input: x, np.array\n    output: y, np.array\n    \"\"\"\n    return np.sign(np.random.rand(1)-0.5) * x\n\ndef ampscale(x):\n    \"\"\"y=ampscale(x) randomly scale the amplitude of x\n    input: x, np.array\n    output: y, np.array\n    \"\"\"\n    return (2*np.random.rand(1)-1) * x / (np.max(np.abs(x)) + 1e-07)\n\ndef framejitter(x, framelen):\n    \"\"\"y=framejitter(x, framelen)\n    input: x, np.array, original waveform (length, 1)\n           framelen, int, framelen\n    output: y, np.array, segment of the waveform\n    \"\"\"\n    framelen = x.shape[0] if framelen > x.shape[0] else framelen\n    random_start = int(np.ceil(np.random.rand(1) * (x.shape[0] - framelen)))\n    return x[random_start:random_start+framelen]\n\n\ndef emphasis_rand(x, coef_val):\n    \"\"\"y=deemphasis(x, coef_val)\n    input: x, np.array, original waveform (length, 1) or (length) \n           framelen, int, framelen\n    output: y, np.array, segment of the waveform\n    \"\"\"\n    coef = (2 * np.random.rand(1) - 1) * coef_val\n    x_new = np.zeros_like(x) + x\n    x_new[1:] = x_new[1:] - coef * x[:-1]\n    return x_new\n\ndef wav_aug(x, framelen, coef_val, sr):\n    \"\"\"y = wav_aug(x, framelen, coef_val, sr)\n    input\n    -----\n      x: np.array, original waveform (length, 1) \n      framelen: int, frame length\n      coef_val: float, reference coefficient for emphasis-rand\n      sr: int, sampling rate (e.g., 16000)\n    \n    output\n    ------\n      y: np.array, pre-processed waveform (length, 1)\n    \"\"\"\n    trimmed_x = nii_wav_tk.silence_handler_wrapper(x, sr, flag_output=1)\n    x_frame = framejitter(trimmed_x, framelen)\n    return ampscale(emphasis_rand(x_frame, coef_val))\n\n\n\nclass OverlapAdder(torch_nn.Module):\n    \"\"\"OverlapAdder\n    \"\"\"\n    def __init__(self, fl, fs, flag_win_analysis=True):\n        \"\"\"OverlapAdder(flag_windowing_before=True)\n        Args\n        ----\n          fl: int, frame length\n          fs: int, frame shift\n          flag_win_analysis: bool (default True)\n              True: apply windowing during analysis\n              False: apply windowing during synthesis          \n        \"\"\"\n        super(OverlapAdder, self).__init__()\n        self.fl = fl\n        self.fs = fs\n        self.flag_win_ana = flag_win_analysis\n        \n        # assume even \n        self.m_win = torch_nn.Parameter(torch.hann_window(self.fl))\n        return\n    \n    def get_frame_num(self, wav_length):\n        \"\"\"frame_num = get_frame_num(wav_length)\n        wav_length: int, waveform length\n        frame_num: int, number of frames\n        \"\"\"\n        return (wav_length - self.fl) // self.fs + 1\n    \n    def get_wavlength(self, frame_num):\n        \"\"\"wav_length = get_wavlength(self, frame_num)\n        wav_length: int, waveform length\n        frame_num: int, number of frames\n        \"\"\"\n        return (frame_num - 1) * self.fs + self.fl\n    \n    def forward(self, x):\n        \"\"\"OverlapAdder(x)\n        \n        input\n        -----\n          x: tensor, (batch, length, 1)\n        \n        output\n        ------\n          y: tensor, (batch, frame_num, frame_length)\n        \"\"\"\n        frame_num = self.get_frame_num(x.shape[1])\n        \n        # (batch, num_patches, 1, patch_size)\n        # num_patches = (length - length) // shift + 1\n        # and copy the data\n        # note that unfold put each patch as the last dimension\n        # x_tmp (batch, frame_num, 1, frame_length)\n        x_tmp = x.unfold(1, self.fl, self.fs)\n\n        # apply window\n        if self.flag_win_ana:\n            x_tmp = x_tmp * self.m_win\n            \n        # (batch, frame_num, frame_length)\n        return x_tmp.view(x.shape[0], x_tmp.shape[1], -1)\n\n    def reverse(self, x_framed, flag_scale=False):\n        \"\"\"OverlapAdder(x)\n        \n        input\n        -----\n          x: tensor, (batch, frame_num, frame_length)\n          flag_scale: bool, whether scale the ampltidue to (-1, 1)\n                      default False\n        output\n        ------\n          y: tensor, (batch, length, 1)\n        \"\"\"\n        batch, frame_num, frame_len = x_framed.shape\n        x_len = self.get_wavlength(frame_num)\n        x_buf = torch.zeros(\n            [batch, x_len], device=x_framed.device, dtype=x_framed.dtype)\n        x_win = torch.zeros_like(x_buf)\n        \n        for idx in range(frame_num):\n            sdx = idx * self.fs\n            edx = sdx + self.fl\n            x_win[:, sdx:edx] += self.m_win\n            if not self.flag_win_ana: \n                x_buf[:, sdx:edx] += x_framed[:, idx] * self.m_win\n            else:\n                x_buf[:, sdx:edx] += x_framed[:, idx]\n        # assume the overlapped window has a constant amplitude\n        x_buf = x_buf / x_win.mean()\n\n        # normalize the amplitude between (-1, 1)\n        if flag_scale:\n            # if input is between (-1, 1), there is no need to \n            # do this normalization\n            x_buf = x_buf / (x_buf.abs().max())\n        return x_buf.unsqueeze(-1)\n\n#######################################\n# Torch model definition\n#######################################\n\nclass AffineCouplingBlow_core(torch_nn.Module):\n    \"\"\"AffineCouplingBlow_core\n    \n    AffineCoupling core layer the produces the scale and bias parameters.\n    \n    Example:\n        feat_dim = 10\n        cond_dim = 20\n\n        m_layer = AffineCouplingBlow_core(feat_dim, cond_dim, 64, 2)\n\n        data = torch.randn([2, 100, feat_dim])\n        cond = torch.randn([2, 1, cond_dim])\n        scale, bias, log_scale = m_layer(data, cond)\n    \"\"\"\n    def __init__(self, feat_dim, cond_dim, num_ch, kernel_size=3):\n        \"\"\"AffineCouplingBlow_core(feat_dim, cond_dim, num_ch, kernel_size=3)\n        \n        Args\n        ----\n          feat_dim: int, dimension of input feature\n          cond_dim: int, dimension of conditional features\n          num_ch: int, number of channels for conv layers\n          kernel_size: int, kernel size of conv layer, default 3\n          \n        input_feature -------> func.conv1d -----> conv1ds -> scale, bias\n                                    ^\n                                    |\n        cond_dim ---> Adapter -> conv weight/bias\n        \"\"\"\n        super(AffineCouplingBlow_core, self).__init__()\n        \n        self.feat_dim = feat_dim\n        self.cond_dim = cond_dim\n        \n        # make sure that kernel is odd\n        if kernel_size % 2 == 0:\n            self.kernel_s = kernel_size + 1\n            print(\"\\tAffineCouplingBlow_core\", end=\" \")\n            print(\"kernel size {:d} -> {:d}\".format(kernel_size, self.kernel_s))\n        else:\n            self.kernel_s = kernel_size\n            \n        if num_ch % feat_dim != 0:\n            # make sure that number of channel is good\n            self.num_ch = num_ch // feat_dim * feat_dim\n            print(\"\\tAffineCouplingBlow_core\", end=\" \")\n            print(\"conv channel {:d} -> {:d}\".format(num_ch, self.num_ch))\n        else:\n            self.num_ch = num_ch\n            \n        # Adapter\n        # (batch, 1, cond_dim) -> (batch, 1, kernel_size * num_ch) for weight\n        #                      -> (batch, 1, num_ch) for bias\n        self.m_adapter = torch_nn.Linear(cond_dim, \n                                         (self.kernel_s+1) * self.num_ch)\n        \n        # conv1d with condition-independent parameters\n        self.m_conv1ds = torch_nn.Sequential(\n            torch_nn.ReLU(),\n            torch_nn.Conv1d(self.num_ch, self.num_ch, 1),\n            torch_nn.ReLU(),\n            torch_nn.Conv1d(self.num_ch, feat_dim * 2, self.kernel_s, \n                           padding=(self.kernel_s-1)//2)\n        )\n        \n        # zero initialization for the last conv layers\n        # similar to Glow and WaveGlow\n        self.m_conv1ds[-1].weight.data.zero_()\n        self.m_conv1ds[-1].bias.data.zero_()\n        return\n    \n    def forward(self, x, cond):\n        \"\"\"scale, bias = AffineCouplingBlow_core(x, cond)\n        \n        input\n        -----\n          x: tensor, input tensor (batch, length, feat_dim)\n          cond: tensor, condition feature (batch, 1, cond_dim)\n        \n        output\n        ------\n          scale: tensor, scaling parameters (batch, length, feat_dim)\n          bias: tensor, bias paramerters (batch, length, feat_dim) \n        \"\"\"\n        # cond_dim -> Adapter -> conv weight/bias\n        # cond[:, 0, :] -> (batch, cond_dim)\n        # adapter(cond[:, 0, :]) -> (batch, kernel_size * num_ch + num_ch)\n        # view(...) -> (batch * num_ch, kernel_size + 1)\n        weight_bias = self.m_adapter(cond[:, 0, :]).view(-1, self.kernel_s+1)\n        # (batch * num_ch, 1, kernel_size)\n        weight = weight_bias[:, 0:self.kernel_s].unsqueeze(1)\n        # (batch * num_ch)\n        bias = weight_bias[:, self.kernel_s]\n        \n        # convolution given weight_bias\n        padsize = (self.kernel_s - 1) // 2\n        groupsize = x.shape[0] * self.feat_dim\n        length = x.shape[1]\n        \n        #  x.permute(0, 2, 1)...view -> (1, batch*feat_dim, length)\n        #  conv1d -> (1, batch * num_ch, length)\n        #  view -> (batch, num_ch, length)\n        x_tmp = torch_nn_func.conv1d(\n            x.permute(0, 2, 1).contiguous().view(1, -1, length),\n            weight, \n            bias = bias,\n            padding = padsize,\n            groups = groupsize\n        ).view(x.shape[0], -1, length)\n        \n        # condition invariant conv -> (batch, feat_dim * 2, length)\n        x_tmp = self.m_conv1ds(x_tmp)\n        \n        # scale and bias (batch, feat_dim, length)\n        raw_scale, bias = torch.chunk(x_tmp, 2, dim=1)\n\n        #  -> (batch, length, feat_dim)\n        bias = bias.permute(0, 2, 1)\n\n        #  re-parameterize\n        #   Here we need to add a small number, otherwise, log(scale)\n        #   somtime times become -inf during training\n        scale = torch.sigmoid(raw_scale + 2).permute(0, 2, 1) * 0.5 + 0.5\n        \n        log_scale = torch.log(scale)\n\n        #print(\"Debug: {:.3f} {:.3f} {:.3f} {:3f}\".format(\n        #    log_scale.max().item(), log_scale.min().item(), \n        #    scale.max().item(), scale.min().item()), \n        #    file=sys.stderr)\n        return scale, bias, log_scale\n    \n    \n    \nclass AffineCouplingBlow(torch_nn.Module):\n    \"\"\"AffineCouplingBlow\n    \n    AffineCoupling block in Blow\n    \n    Example:\n        feat_dim = 10\n        cond_dim = 20\n\n        m_layer = AffineCouplingBlow(feat_dim, cond_dim,60,3, flag_detjac=True)\n\n        data = torch.randn([2, 100, feat_dim])\n        cond = torch.randn([2, 1, cond_dim])\n        out, detjac = m_layer(data, cond)\n\n        data_rever = m_layer.reverse(out, cond)\n\n        torch.std(data - data_rever)\n    \"\"\"\n    def __init__(self, in_dim, cond_dim,  \n                 conv_dim_channel, conv_kernel_size,\n                 flag_detjac=False):\n        \"\"\"AffineCouplingBlow(in_dim, cond_dim,  \n            wn_num_conv1d, wn_dim_channel, wn_kernel_size, \n            flag_affine=True, flag_detjac=False)\n        \n        Args:\n        -----\n          in_dim: int, dim of input audio data (batch, length, in_dim)\n          cond_dim, int, dim of condition feature (batch, length, cond_dim)\n          conv_dim_channel: int, dime of the convolution channels\n          conv_kernel_size: int, kernel size of the convolution layers\n          flag_detjac: bool, whether return the determinant of Jacobian,\n                       default False\n        \n        y -> split() -> y1, y2 -> concate([y1, (y2+bias) * scale])\n        When flag_affine == True, y1 -> H() -> scale, bias\n        When flag_affine == False, y1 -> H() -> bias, scale=1 \n        Here, H() is AffineCouplingBlow_core layer\n        \"\"\"\n        super(AffineCouplingBlow, self).__init__()\n        \n        self.flag_detjac = flag_detjac\n        \n        if in_dim % 2 > 0:\n            print(\"AffineCouplingBlow(feat_dim), feat_dim is an odd number?!\")\n            sys.exit(1)\n        \n        # Convolution block to get scale and bias\n        self.m_core = AffineCouplingBlow_core(\n            in_dim // 2, cond_dim, conv_dim_channel, conv_kernel_size)\n        \n        return\n    \n    def _detjac(self, log_scale, factor=1):\n        # (batch, dim1, dim2, ..., feat_dim) -> (batch)\n        # sum over dim1, ... feat_dim\n        return nii_glow.sum_over_keep_batch(log_scale / factor)\n        \n    def _nn_trans(self, y1, cond):\n        \"\"\"_nn_trans(self, y1, cond)\n        \n        input\n        -----\n          y1: tensor, input feature, (batch, lengh, input_dim//2)\n          cond: tensor, condition feature, (batch, length, cond_dim)\n          \n        output\n        ------\n          scale: tensor, (batch, lengh, input_dim // 2)\n          bias: tensor, (batch, lengh, input_dim // 2)\n          log_scale: tensor, (batch, lengh, input_dim // 2)\n        \n        Affine transformaiton can be done by scale * feature + bias\n        log_scale is used for det Jacobian computation\n        \"\"\"\n        scale, bias, log_scale = self.m_core(y1, cond)\n        return scale, bias, log_scale\n        \n    def forward(self, y, cond, factor=1):\n        \"\"\"AffineCouplingBlow.forward(y, cond)\n        \n        input\n        -----\n          y: tensor, input feature, (batch, lengh, input_dim)\n          cond: tensor, condition feature , (batch, 1, cond_dim)\n          \n        output\n        ------\n          x: tensor, input feature, (batch, lengh, input_dim)\n          detjac: tensor, det of jacobian, (batch,)\n        \n        y1, y2 = split(y)\n        scale, bias = Conv(y1)\n        x2 = y2 * scale + bias or (y2 + bias) * scale\n        return [y1, x2]\n        \"\"\"\n        # split\n        y1, y2 = y.chunk(2, -1)\n        scale, bias, log_scale = self._nn_trans(y1, cond)\n        \n        # transform\n        x1 = y1\n        x2 = (y2 + bias) * scale\n\n        # concatenate\n        x = torch.cat([x1, x2], dim=-1)\n        if self.flag_detjac:\n            return x, self._detjac(log_scale, factor)\n        else:\n            return x\n        \n        \n    def reverse(self, x, cond):\n        \"\"\"AffineCouplingBlow.reverse(y, cond)\n        \n        input\n        -----\n          x: tensor, input feature, (batch, lengh, input_dim)\n          cond: tensor, condition feature , (batch, 1, cond_dim)\n          \n        output\n        ------\n          y: tensor, input feature, (batch, lengh, input_dim)\n        \n        x1, x2 = split(x)\n        scale, bias = conv(x1)\n        y2 = x2 / scale - bias\n        return [x1, y2]\n        \"\"\"\n        # split\n        x1, x2 = x.chunk(2, -1)\n        # reverse transform\n        y1 = x1\n        scale, bias, log_scale = self._nn_trans(y1, cond)\n        y2 = x2 / scale - bias\n        return torch.cat([y1, y2], dim=-1)\n        \n        \nclass SqueezeForBlow(torch_nn.Module):\n    \"\"\"SqueezeForBlow\n    \n    Squeeze input feature for Blow.\n    \n    Example\n        data = torch.randn([2, 10, 3])\n        m_sq = SqueezeForBlow()\n        data_out = m_sq(data)\n        data_rev = m_sq.reverse(data_out)\n        torch.std(data_rev - data)\n    \"\"\"\n    def __init__(self, mode=1):\n        \"\"\"SqueezeForBlow(mode=1)\n        \n        Args\n        ----\n          mode: int, mode of squeeze, default 1\n          \n        Mode 1: squeeze by a factor of 2 as in original paper\n        \"\"\"\n        super(SqueezeForBlow, self).__init__()\n        \n        self.m_mode = mode\n        \n        if self.m_mode == 1:\n            self.squeeze_factor = 2\n        else:\n            print(\"SqueezeForBlow mode {:d} not implemented\".format(mode))\n            sys.exit(1)\n        return\n\n    \n    def get_expected_squeeze_length(self, orig_length):\n        # return expected length after squeezing\n        if self.m_mode == 1:\n            return orig_length // self.squeeze_factor\n        else:\n            print(\"unknown mode for SqueezeForBlow\")\n            sys.exit(1)\n    \n    def get_recovered_length(self, squeezed_length):\n        # return original length before squeezing\n        if self.m_mode == 1:\n            return squeezed_length * self.squeeze_factor\n        else:\n            print(\"unknown mode for SqueezeForBlow\")\n            sys.exit(1)\n    \n    def get_squeeze_factor(self):\n        # return the configuration for squeezing\n        if self.m_mode == 1:\n            return self.squeeze_factor\n        else:\n            print(\"unknown mode for SqueezeForBlow\")\n            sys.exit(1)\n    \n    def forward(self, x):\n        \"\"\"SqueezeForBlow(x)\n        \n        input\n        -----\n          x: tensor, (batch, length, feat_dim)\n        \n        output\n        ------\n          y: tensor, (batch, length//squeeze_factor, feat_dim*squeeze_factor)\n        \n        \"\"\"\n        if self.m_mode == 1:\n            # squeeze, the 8 points should be the last dimension\n            squeeze_len = self.get_expected_squeeze_length(x.shape[1])\n            # trim length first\n            trim_len = squeeze_len * self.squeeze_factor\n            x_tmp = x[:, 0:trim_len, :]\n            \n            # (batch, time//squeeze_size, squeeze_size, dim)\n            x_tmp = x_tmp.view(x_tmp.shape[0], squeeze_len, \n                               self.squeeze_factor, -1)\n            \n            # (batch, time//squeeze_size, dim, squeeze_size)\n            x_tmp = x_tmp.permute(0, 1, 3, 2).contiguous()\n            \n            # (batch, time//squeeze_size, dim * squeeze_size)\n            return x_tmp.view(x_tmp.shape[0], squeeze_len, -1)\n        else:\n            print(\"SqueezeForWaveGlow not implemented\")\n            sys.exit(1)\n        return x_squeezed\n\n    def reverse(self, x_squeezed):\n        if self.m_mode == 1:\n            # (batch, time//squeeze_size, dim * squeeze_size)\n            batch, squeeze_len, squeeze_dim = x_squeezed.shape\n            \n            # (batch, time//squeeze_size, dim, squeeze_size)\n            x_tmp = x_squeezed.view(\n                batch, squeeze_len, squeeze_dim // self.squeeze_factor, \n                self.squeeze_factor)\n            \n            # (batch, time//squeeze_size, squeeze_size, dim)\n            x_tmp = x_tmp.permute(0, 1, 3, 2).contiguous()\n            \n            # (batch, time, dim)\n            x = x_tmp.view(batch, squeeze_len * self.squeeze_factor, -1)\n        else:\n            print(\"SqueezeForWaveGlow not implemented\")\n            sys.exit(1)\n        return x\n\n    \n    \nclass FlowStepBlow(torch_nn.Module):\n    \"\"\"FlowStepBlow\n    One flow step for Blow\n    y -> intertical_1x1() -> ActNorm -> AffineCoupling -> x\n    \n    Example\n        feat_dim = 10\n        cond_dim = 20\n\n        m_layer = FlowStepBlow(feat_dim, cond_dim, 60, 3)\n\n        data = torch.randn([2, 100, feat_dim])\n        cond = torch.randn([2, 1, cond_dim])\n        out, detjac = m_layer(data, cond)\n\n        data_rever = m_layer.reverse(out, cond)\n\n        torch.std(data - data_rever) \n    \"\"\"\n    def __init__(self, in_dim, cond_dim, conv_dim_channel, conv_kernel_size):\n        \"\"\"FlowStepBlow(in_dim, cond_dim, \n                            conv_dim_channel, conv_kernel_size)\n        \n        Args\n        ----\n          in_dim: int, input feature dim, (batch, length, in_dim)\n          cond_dim:, int, conditional feature dim, (batch, length, cond_dim)\n          cond_dim_channel: int, dim of the convolution layers\n          conv_kernel_size: int, kernel size of the convolution layers\n\n        For cond_dim_channel and conv_kernel_size, see AffineCouplingBlow\n        \"\"\"\n        super(FlowStepBlow, self).__init__()\n        \n        # Invertible transformation layer\n        self.m_invtrans = nii_glow.InvertibleTrans(in_dim, flag_detjac=True)\n        \n        # Act norm layer\n        self.m_actnorm = nii_glow.ActNorm(in_dim, flag_detjac=True)\n        \n        # coupling layer\n        self.m_coupling = AffineCouplingBlow(\n            in_dim, cond_dim, conv_dim_channel, conv_kernel_size, \n            flag_detjac=True)\n        \n        return\n    \n    def forward(self, y, cond, factor=1):\n        \"\"\"FlowStepBlow.forward(y, cond, factor=1)\n        \n        input\n        -----\n          y: tensor, input feature, (batch, lengh, in_dim)\n          cond: tensor, condition feature , (batch, 1, cond_dim)\n          factor: int, this is used to divde likelihood, default 1\n                  if we directly sum all detjac, they will become very large\n                  however, we cannot average them directly on y because y\n                  may have a different shape from the actual data y\n        output\n        ------\n          x: tensor, input feature, (batch, lengh, input_dim)\n          detjac: tensor, det of jacobian, (batch,)\n        \"\"\"\n        # 1x1 transform\n        x_tmp, log_det_1 = self.m_invtrans(y, factor)\n        \n        # Actnorm\n        x_tmp, log_det_2 = self.m_actnorm(x_tmp, factor)\n        \n        # coupling\n        x_tmp, log_det_3 = self.m_coupling(x_tmp, cond, factor)\n        return x_tmp, log_det_1 + log_det_2 + log_det_3\n    \n    def reverse(self, x, cond):\n        \"\"\"FlowStepBlow.reverse(y, cond)\n        \n        input\n        -----\n          x: tensor, input feature, (batch, lengh, input_dim)\n          cond: tensor, condition feature , (batch, 1, cond_dim)\n          \n        output\n        ------\n          y: tensor, input feature, (batch, lengh, input_dim)\n        \"\"\"\n        y_tmp1 = self.m_coupling.reverse(x, cond) \n        y_tmp2 = self.m_actnorm.reverse(y_tmp1) \n        y_tmp3 = self.m_invtrans.reverse(y_tmp2)\n        #print(\"Debug: {:.3f} {:.3f} {:.3f} {:.3f} {:.3f} {:.3f}\".format(\n        #    y_tmp1.max().item(), y_tmp1.min().item(),\n        #    y_tmp2.max().item(), y_tmp2.min().item(),\n        #    y_tmp3.max().item(), y_tmp3.min().item()))\n        return y_tmp3\n\n\n    \nclass BlowBlock(torch_nn.Module):\n    \"\"\"BlowBlock\n    A BlowBlok includes multiple steps of flow for Blow.\n    \n    Each block conducts:\n    x -> squeeze -> flow step1 -> ... -> flow step N\n\n    Compared with WaveGlowBlock, this is easier because there is no\n    multi-scale structure, no need to split the latent z.\n    \n    Example:\n        \n    \"\"\"\n    def __init__(self, in_dim, cond_dim, n_flow_steps,\n                 conv_dim_channel, conv_kernel_size):\n        \"\"\"BlowBlock(in_dim, cond_dim, n_flow_steps,\n                 conv_dim_channel, conv_kernel_size)\n        Args\n        ----\n          in_dim: int, input feature dim, (batch, length, in_dim)\n          cond_dim:, int, conditional feature dim, (batch, length, cond_dim)\n          n_flow_steps: int, number of flow steps in one block\n          conv_dim_channel: int, dim of the conv residual and skip channels\n          conv_kernel_size: int, kernel size of the convolution layers\n         \n        For conv_dim_channel and conv_kernel_size, see AffineCouplingBlow\n        \"\"\"\n        super(BlowBlock, self).__init__()\n        \n        # squeeze\n        self.m_squeeze = SqueezeForBlow()\n        \n        squeezed_feat_dim = in_dim * self.m_squeeze.get_squeeze_factor()\n                \n        # flow steps\n        tmp_flows = []\n        for i in range(n_flow_steps):\n            tmp_flows.append(\n                FlowStepBlow(\n                    squeezed_feat_dim, cond_dim, \n                    conv_dim_channel, conv_kernel_size))\n        self.m_flows = torch_nn.ModuleList(tmp_flows)            \n        \n        self.m_out_dim = squeezed_feat_dim\n        return\n    \n    def get_out_feat_dim(self):\n        return self.m_out_dim\n    \n    def get_expected_squeeze_length(self, orig_length):\n        return self.m_squeeze.get_expected_squeeze_length(orig_length)\n    \n    def forward(self, y, cond, factor=1):\n        \"\"\"z, log_detjac = BlowBlock(y) \n        \n        y -> squeeze -> H() -> z, log_det_jacobian\n        H() consists of multiple flow steps (1x1conv + Actnorm + AffineCoupling)\n        \n        input\n        -----\n          y: tensor, (batch, length, dim)\n          cond, tensor, (batch, 1, cond_dim)\n          factor, None or int, this is used to divde likelihood, default 1\n\n        output\n        ------\n         log_detjac: tensor or scalar\n         z: tensor, (batch, length, dim), for N(z; 0, I) or next flow block\n        \"\"\"\n        # squeeze\n        x_tmp = self.m_squeeze(y)\n\n        # flows\n        log_detjac = 0\n        for idx, l_flow in enumerate(self.m_flows):\n            x_tmp, log_detjac_tmp = l_flow(x_tmp, cond, factor)\n            log_detjac = log_detjac + log_detjac_tmp\n            \n        return x_tmp, log_detjac\n    \n    def reverse(self, z, cond):\n        \"\"\"y = BlowBlock.reverse(z, cond) \n        \n        z -> H^{-1}() -> unsqueeze -> y\n        \n        input\n        -----\n          z: tensor, (batch, length, in_dim)\n          cond, tensor, (batch, 1, cond_dim)\n          \n        output\n        ------\n          y: tensor, (batch, length, in_dim)          \n        \"\"\"\n        y_tmp = z\n        for l_flow in self.m_flows[::-1]:\n            y_tmp = l_flow.reverse(y_tmp, cond)\n        y = self.m_squeeze.reverse(y_tmp)\n        return y\n\n    \nclass Blow(torch_nn.Module):\n    \"\"\"Blow                     \n    \"\"\"\n    def __init__(self, cond_dim, num_blocks, num_flows_inblock, \n                 conv_dim_channel, conv_kernel_size):\n        \"\"\"Blow(cond_dim, num_blocks, num_flows_inblock, \n                conv_dim_channel, conv_kernel_size)\n        \n        Args\n        ----\n          cond_dim:, int, conditional feature dim, (batch, length, cond_dim)\n          num_blocks: int, number of WaveGlowBlocks\n          num_flows_inblock: int, number of flow steps in one WaveGlowBlock\n          conv_dim_channel: int, dim of convolution layers channels\n          conv_kernel_size: int, kernel size of the convolution layers\n          \n        This model defines:\n        \n        cond (global) ----- -> | ------> | --------> | \n                               v         v           v   \n        y --------------> BlowBlock1 -> BlowBlock2 -> ... -> z\n        \"\"\"\n        super(Blow, self).__init__()\n        \n        # input is assumed to be waveform\n        self.m_input_dim = 1\n        \n        # save the dimension for get_z_noises\n        self.m_z_dim = 0\n\n        # define blocks\n        tmp_squeezed_in_dim = self.m_input_dim\n        tmp_flow_blocks = []\n        for i in range(num_blocks):\n            tmp_flow_blocks.append(\n                BlowBlock(\n                    tmp_squeezed_in_dim, cond_dim, num_flows_inblock,\n                    conv_dim_channel, conv_kernel_size))\n            \n            tmp_squeezed_in_dim = tmp_flow_blocks[-1].get_out_feat_dim()\n        self.m_z_dim = tmp_squeezed_in_dim\n        \n        self.m_flowblocks = torch_nn.ModuleList(tmp_flow_blocks)\n        \n        # done\n        return\n    \n    \n    def get_expected_squeeze_length(self, wave_length):\n        \"\"\"length = get_expected_squeeze_length(self, wave_length)\n        Return expected length of latent z\n        \n        input\n        -----\n          wave_length: int, length of original waveform\n        \n        output\n        ------\n          length: int, length of latent z\n        \"\"\"\n        \n        length = wave_length\n        for glowblock in self.m_flowblocks:\n            length = glowblock.get_expected_squeeze_length(length)\n        return length\n    \n    def _normal_lh(self, noise):\n        # likelihood of normal distribution on the given noise\n        return -0.5 * np.log(2 * np.pi) - 0.5 * noise ** 2\n    \n    def forward(self, y, cond):\n        \"\"\"z, neg_logp_y, logp_z, logdet = Blow.forward(y, cond) \n        \n        cond (global) ----- -> | ------> | --------> | \n                               v         v           v   \n        y --------------> BlowBlock1 -> BlowBlock2 -> ... -> z\n                             \n        input\n        -----\n          y: tensor, (batch, waveform_length, 1)\n          cond: tensor,  (batch, 1, cond_dim)\n          \n        output\n        ------\n          z: tensor\n          neg_logp_y: scalar, - log p(y)\n          logp_z: scalar, -log N(z), summed over one data sequence, but averaged\n                  over batch.\n          logdet: scalar, -|det dH(.)/dy|, summed over one data sequence, \n                  but averaged\n                  over batch.\n        \"\"\"\n        \n        # Rather than summing the likelihood and divide it by the number of \n        #  data in the final step, we divide this factor from the likelihood\n        #  caculating by each flow step and sum the scaled likelihood. \n        # Two methods are equivalent, but the latter may prevent numerical \n        #  overflow of the likelihood value for long sentences\n        factor = np.prod([dim for dim in y.shape])\n        \n        # flows\n        log_detjac = 0\n        log_pz = 0\n\n        x_tmp = y\n        for m_block in self.m_flowblocks:\n            x_tmp, log_detjac_tmp = m_block(\n                x_tmp, cond, factor)\n            \n            # accumulate log det jacobian\n            log_detjac += log_detjac_tmp\n        \n        z_tmp = x_tmp\n        # compute N(z; 0, I)\n        # accumulate log_N(z; 0, I) only if it is valid\n        if z_tmp is not None:\n            log_pz += nii_glow.sum_over_keep_batch2(\n                self._normal_lh(z_tmp), factor)\n        \n        # average over batch and data points\n        neg_logp_y = -(log_pz + log_detjac).sum()\n        return z_tmp, neg_logp_y, \\\n            log_pz.sum(), log_detjac.sum()\n        \n    def reverse(self, z, cond):\n        \"\"\"y = Blow.reverse(z_bags, cond) \n        \n        cond (global) ----- -> | ------> | --------> | \n                               v         v           v   \n        y <--------------- BlowBlock1 <- BlowBlock2 <- ... <- z\n                             \n        input\n        -----\n          z: tensor, shape decided by the model configuration\n          cond: tensor,  (batch, 1, cond_dim)\n          \n        output\n        ------\n          y: tensor, (batch, waveform_length, 1)\n        \"\"\"\n        # initial\n        y_tmp = z\n        for m_block in self.m_flowblocks[::-1]:\n            y_tmp = m_block.reverse(y_tmp, cond)\n        return y_tmp\n    \n    def get_z_noises(self, length, noise_std=0.7, batchsize=1):\n        \"\"\"z_bags = Blow.get_z_noises(length, noise_std=0.7, batchsize=1)\n        Return random noise for random sampling\n        \n        input\n        -----\n          length: int, length of target waveform (without squeeze)\n          noise_std: float, std of Gaussian noise, default 0.7\n          batchsize: int, batch size of this random data, default 1\n        \n        output\n        ------\n          z: tensor, shape decided by the network\n        \n        Blow.reverse(z, cond) can be used to generate waveform\n        \"\"\"\n        squeeze_length = self.get_expected_squeeze_length(length)\n        \n        device = next(self.parameters()).device\n        \n        z_tmp = torch.randn(\n            [batchsize, squeeze_length, self.m_z_dim], \n            dtype=nii_io_conf.d_dtype, \n            device=device)\n        return z_tmp\n    \n    \nif __name__ == \"__main__\":\n    print(\"Definition of Blow\")\n", "meta": {"hexsha": "ae2aed57e146e47bfdf041d7b10551aa273e9d54", "size": 31665, "ext": "py", "lang": "Python", "max_stars_repo_path": "sandbox/block_blow.py", "max_stars_repo_name": "Nijta/project-NN-Pytorch-scripts", "max_stars_repo_head_hexsha": "06a50ab072613fb60b8b8e1cea85c4aa8e75549d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 150, "max_stars_repo_stars_event_min_datetime": "2020-06-04T00:02:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:32:56.000Z", "max_issues_repo_path": "sandbox/block_blow.py", "max_issues_repo_name": "Nijta/project-NN-Pytorch-scripts", "max_issues_repo_head_hexsha": "06a50ab072613fb60b8b8e1cea85c4aa8e75549d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2020-06-17T04:08:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T03:42:25.000Z", "max_forks_repo_path": "sandbox/block_blow.py", "max_forks_repo_name": "Nijta/project-NN-Pytorch-scripts", "max_forks_repo_head_hexsha": "06a50ab072613fb60b8b8e1cea85c4aa8e75549d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2020-06-16T03:28:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T03:46:13.000Z", "avg_line_length": 33.3667017914, "max_line_length": 80, "alphanum_fraction": 0.5453971262, "include": true, "reason": "import numpy", "num_tokens": 7926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.1848396657323493}}
{"text": "r\"\"\"\nProbabilistic / decoder modules for DIRECTi\n\"\"\"\n\nimport typing\nimport abc\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom . import module, nn\n\n\nclass ProbModel(module.Module):\n    r\"\"\"\n    Abstract base class for generative model modules.\n    \"\"\"\n    def __init__(\n            self, h_dim: int = 128, depth: int = 1, dropout: float = 0.0,\n            lambda_reg: float = 0.0, fine_tune: bool = False,\n            deviation_reg: float = 0.0, name: str = \"ProbModel\"\n    ) -> None:\n        super(ProbModel, self).__init__(name=name)\n        self.h_dim = h_dim\n        self.depth = depth\n        self.dropout = dropout\n        self.lambda_reg = lambda_reg\n        self.fine_tune = fine_tune\n        self.deviation_reg = deviation_reg\n        self.deviation_regularizer = \\\n            (lambda x: self.deviation_reg * tf.reduce_mean(tf.square(x))) \\\n            if self.fine_tune and self.deviation_reg > 0 else None\n\n    @staticmethod\n    def _normalize(  # pylint: disable=unused-argument\n            x: typing.Union[np.ndarray, tf.Tensor],\n            library_size: typing.Union[np.ndarray, tf.Tensor]\n    ) -> typing.Union[np.ndarray, tf.Tensor]:  # pragma: no cover\n        return x\n\n    @staticmethod\n    def _add_noise(  # pylint: disable=unused-argument\n            x: typing.Union[np.ndarray, tf.Tensor],\n            random_state: typing.Optional[np.random.RandomState] = None\n    ) -> typing.Union[np.ndarray, tf.Tensor]:  # pragma: no cover\n        return x\n\n    @staticmethod\n    def _preprocess(x: tf.Tensor) -> tf.Tensor:\n        return x\n\n    def _loss(\n            self, ref: tf.Tensor, latent: tf.Tensor, training_flag: tf.Tensor,\n            tail_concat: typing.Optional[typing.List[tf.Tensor]] = None,\n            scope: str = \"decoder\"\n    ) -> tf.Tensor:\n        with tf.variable_scope(f\"{scope}/{self.scope_safe_name}\"):\n            dropout = np.zeros(self.depth)\n            dropout[1:] = self.dropout  # No dropout for first layer\n            mlp_kwargs = dict(\n                dropout=dropout.tolist(), dense_kwargs=dict(\n                    deviation_regularizer=self.deviation_regularizer\n                ), training_flag=training_flag\n            )\n            ptr = nn.mlp(latent, [self.h_dim] * self.depth, **mlp_kwargs)\n            ptr = (ptr if isinstance(ptr, list) else [ptr]) + (tail_concat or [])\n            self.log_likelihood = self._log_likelihood(ref, ptr)\n            self.mean_log_likelihood = tf.reduce_mean(self.log_likelihood, axis=1)  # feature size invariant\n            raw_loss = tf.negative(tf.reduce_mean(self.mean_log_likelihood), name=\"raw_loss\")\n            regularized_loss = tf.add(\n                raw_loss, self.lambda_reg * self._build_regularizer(),\n                name=\"regularized_loss\"\n            )\n        self.vars_to_save += tf.get_collection(\n            tf.GraphKeys.GLOBAL_VARIABLES, f\"{scope}/{self.scope_safe_name}\")\n        tf.add_to_collection(tf.GraphKeys.LOSSES, raw_loss)\n        tf.add_to_collection(tf.GraphKeys.LOSSES, regularized_loss)\n        return regularized_loss\n\n    @abc.abstractmethod\n    def _log_likelihood(\n            self, ref: tf.Tensor, pre_recon: typing.List[tf.Tensor]\n    ) -> tf.Tensor:  # pragma: no cover\n        raise NotImplementedError\n\n    def _build_regularizer(self) -> tf.Tensor:\n        return 0\n\n    def _get_config(self) -> typing.Mapping:\n        return {\n            \"h_dim\": self.h_dim,\n            \"depth\": self.depth,\n            \"dropout\": self.dropout,\n            \"lambda_reg\": self.lambda_reg,\n            \"fine_tune\": self.fine_tune,\n            \"deviation_reg\": self.deviation_reg,\n            **super(ProbModel, self)._get_config()\n        }\n\n    def __bool__(self) -> bool:\n        return True\n\n\nclass CountBased(ProbModel):  # pylint: disable=abstract-method\n\n    @staticmethod\n    def _normalize(\n            x: typing.Union[np.ndarray, tf.Tensor],\n            library_size: typing.Union[np.ndarray, tf.Tensor]\n    ) -> typing.Union[tf.Tensor]:\n        return x / (library_size / 10000)\n\n    @staticmethod\n    def _add_noise(\n            x: typing.Union[np.ndarray, tf.Tensor],\n            random_state: typing.Optional[np.random.RandomState] = None\n    ) -> typing.Union[np.ndarray, tf.Tensor]:\n        if random_state is None:\n            return tf.squeeze(tf.random_poisson(x, [1]), axis=0)\n        else:\n            return random_state.poisson(x)\n\n    @staticmethod\n    def _preprocess(x: tf.Tensor) -> tf.Tensor:\n        return tf.log1p(x)\n\n\nclass NB(CountBased):  # Negative binomial\n    r\"\"\"\n    Build a Negative Binomial generative module.\n\n    Parameters\n    ----------\n    h_dim\n        Dimensionality of the hidden layers in the decoder MLP.\n    depth\n        Number of hidden layers in the decoder MLP.\n    dropout\n        Dropout rate.\n    fine_tune\n        Whether the module is used in fine-tuning.\n    lambda_reg\n        Regularization strength for the generative model parameters.\n        Here log-scale variance of the scale parameter\n        is regularized to improve numerical stability.\n    deviation_reg\n        Regularization strength for the deviation from original model weights.\n    name\n        Name of the module.\n    \"\"\"\n    def __init__(\n            self, h_dim: int = 128, depth: int = 1, dropout: float = 0.0,\n            lambda_reg: float = 0.0, fine_tune: bool = False,\n            deviation_reg: float = 0.0, name: str = \"NB\"\n    ) -> None:\n        super(NB, self).__init__(\n            h_dim, depth, dropout, lambda_reg,\n            fine_tune, deviation_reg, name=name\n        )\n\n    def _log_likelihood(\n            self, ref: tf.Tensor, pre_recon: typing.List[tf.Tensor]\n    ) -> tf.Tensor:\n        recon_dim = ref.get_shape().as_list()[1]\n        self.softmax_mu = tf.nn.softmax(nn.dense(\n            pre_recon, recon_dim,\n            deviation_regularizer=self.deviation_regularizer,\n            scope=\"softmax_mu_dense\"\n        ), name=\"softmax_mu\")\n        self.log_theta = tf.identity(nn.dense(\n            pre_recon, recon_dim,\n            deviation_regularizer=self.deviation_regularizer,\n            scope=\"log_theta_dense\"\n        ), name=\"log_theta\")\n        self.recon = mu = \\\n            self.softmax_mu * tf.reduce_sum(ref, axis=1, keepdims=True)\n        return self._log_nb_positive(ref, mu, self.log_theta)\n\n    def _build_regularizer(self) -> tf.Tensor:\n        with tf.name_scope(\"regularization\"):\n            return tf.nn.moments(self.log_theta, axes=[0, 1])[1]\n\n    @staticmethod\n    def _log_nb_positive(\n            x: tf.Tensor, mu: tf.Tensor, log_theta: tf.Tensor,\n            eps: float = 1e-8\n    ) -> tf.Tensor:\n        with tf.name_scope(\"log_nb_positive\"):\n            theta = tf.exp(log_theta)\n            return theta * log_theta \\\n                - theta * tf.log(theta + mu + eps) \\\n                + x * tf.log(mu + eps) - x * tf.log(theta + mu + eps) \\\n                + tf.lgamma(x + theta) - tf.lgamma(theta) \\\n                - tf.lgamma(x + 1)\n\n\nclass ZINB(NB):  # Zero-inflated negative binomial\n    r\"\"\"\n    Build a Zero-Inflated Negative Binomial generative module.\n\n    Parameters\n    ----------\n    h_dim\n        Dimensionality of the hidden layers in the decoder MLP.\n    depth\n        Number of hidden layers in the decoder MLP.\n    dropout\n        Dropout rate.\n    fine_tune\n        Whether the module is used in fine-tuning.\n    lambda_reg\n        Regularization strength for the generative model parameters.\n        Here log-scale variance of the scale parameter\n        is regularized to improve numerical stability.\n    deviation_reg\n        Regularization strength for the deviation from original model weights.\n    name\n        Name of the module.\n    \"\"\"\n    def __init__(\n            self, h_dim: int = 128, depth: int = 1, dropout: float = 0.0,\n            lambda_reg: float = 0.0, fine_tune: bool = False,\n            deviation_reg: float = 0.0, name: str = \"ZINB\"\n    ) -> None:\n        super(ZINB, self).__init__(\n            h_dim, depth, dropout, lambda_reg,\n            fine_tune, deviation_reg, name=name\n        )\n\n    def _log_likelihood(\n            self, ref: tf.Tensor, pre_recon: typing.List[tf.Tensor]\n    ) -> tf.Tensor:\n        recon_dim = ref.get_shape().as_list()[1]\n        self.softmax_mu = tf.nn.softmax(nn.dense(\n            pre_recon, recon_dim,\n            deviation_regularizer=self.deviation_regularizer,\n            scope=\"softmax_mu_dense\"\n        ), name=\"softmax_mu\")\n        self.log_theta = tf.identity(nn.dense(\n            pre_recon, recon_dim,\n            deviation_regularizer=self.deviation_regularizer,\n            scope=\"log_theta_dense\"\n        ), name=\"log_theta\")\n        self.pi = tf.identity(nn.dense(\n            pre_recon, recon_dim,\n            deviation_regularizer=self.deviation_regularizer,\n            scope=\"dropout_logit_dense\"\n        ), name=\"dropout_logit\")\n        self.recon = mu = \\\n            self.softmax_mu * tf.reduce_sum(ref, axis=1, keepdims=True)\n        self.dropout_rate = tf.sigmoid(self.pi)\n        return self._log_zinb_positive(ref, mu, self.log_theta, self.pi)\n\n    @staticmethod\n    def _log_zinb_positive(\n            x: tf.Tensor, mu: tf.Tensor, log_theta: tf.Tensor,\n            pi: tf.Tensor, eps: float = 1e-8\n    ) -> tf.Tensor:\n        r\"\"\"\n        From scVI\n        \"\"\"\n        with tf.name_scope(\"log_zinb_positive\"):\n            theta = tf.exp(log_theta)\n            with tf.name_scope(\"case_zero\"):\n                case_zero = tf.nn.softplus(\n                    - pi + theta * log_theta -\n                    theta * tf.log(theta + mu + eps)\n                ) - tf.nn.softplus(- pi)\n            with tf.name_scope(\"case_non_zero\"):\n                case_non_zero = - pi - tf.nn.softplus(- pi) \\\n                    + theta * log_theta \\\n                    - theta * tf.log(theta + mu + eps) \\\n                    + x * tf.log(mu + eps) - x * tf.log(theta + mu + eps) \\\n                    + tf.lgamma(x + theta) - tf.lgamma(theta) \\\n                    - tf.lgamma(x + 1)\n            with tf.name_scope(\"mixture\"):\n                mask = tf.cast(tf.less(x, eps), tf.float32)\n                res = tf.identity(\n                    tf.multiply(mask, case_zero) +\n                    tf.multiply(1 - mask, case_non_zero),\n                    name=\"likelihood\")\n            return res\n\n\nclass LN(CountBased):\n    r\"\"\"\n    Build a Log Normal generative module.\n\n    Parameters\n    ----------\n    h_dim\n        Dimensionality of the hidden layers in the decoder MLP.\n    depth\n        Number of hidden layers in the decoder MLP.\n    dropout\n        Dropout rate.\n    lambda_reg\n        NOT USED.\n    fine_tune\n        Whether the module is used in fine-tuning.\n    deviation_reg\n        Regularization strength for the deviation from original model weights.\n    name\n        Name of the module.\n    \"\"\"\n    def __init__(\n            self, h_dim: int = 128, depth: int = 1, dropout: float = 0.0,\n            lambda_reg: float = 0.0, fine_tune: bool = False,\n            deviation_reg: float = 0.0, name: str = \"LN\"\n    ) -> None:\n        super(LN, self).__init__(\n            h_dim, depth, dropout, lambda_reg,\n            fine_tune, deviation_reg, name=name\n        )\n\n    def _log_likelihood(\n            self, ref: tf.Tensor, pre_recon: typing.List[tf.Tensor]\n    ) -> tf.Tensor:\n        recon_dim = ref.get_shape().as_list()[1]\n        self.mu = tf.identity(nn.dense(\n            pre_recon, recon_dim,\n            deviation_regularizer=self.deviation_regularizer,\n            scope=\"mu_dense\"\n        ), name=\"mu\")\n        self.log_var = tf.identity(nn.dense(\n            pre_recon, recon_dim,\n            deviation_regularizer=self.deviation_regularizer,\n            scope=\"log_var_dense\"\n        ), name=\"log_var\")\n        self.recon = tf.expm1(self.mu)\n        return self._log_ln_positive(\n            tf.log1p(ref), self.mu, self.log_var)\n\n    @staticmethod\n    def _log_ln_positive(\n            x: tf.Tensor, mu: tf.Tensor, log_var: tf.Tensor\n    ) -> tf.Tensor:\n        with tf.name_scope(\"log_ln\"):\n            return - 0.5 * (\n                tf.square(x - mu) / tf.exp(log_var)\n                + tf.log(2 * np.pi) + log_var\n            )\n\n\nclass ZILN(LN):\n    r\"\"\"\n    Build a Zero-Inflated Log Normal generative module.\n\n    Parameters\n    ----------\n    h_dim\n        Dimensionality of the hidden layers in the decoder MLP.\n    depth\n        Number of hidden layers in the decoder MLP.\n    dropout\n        Dropout rate.\n    lambda_reg\n        NOT USED.\n    fine_tune\n        Whether the module is used in fine-tuning.\n    deviation_reg\n        Regularization strength for the deviation from original model weights.\n    name\n        Name of the module.\n    \"\"\"\n    def __init__(\n            self, h_dim: int = 128, depth: int = 1, dropout: float = 0.0,\n            lambda_reg: float = 0.0, fine_tune: bool = False,\n            deviation_reg: float = 0.0, name: str = \"ZILN\"\n    ) -> None:\n        super(ZILN, self).__init__(\n            h_dim, depth, dropout, lambda_reg,\n            fine_tune, deviation_reg, name=name\n        )\n\n    def _log_likelihood(\n            self, ref: tf.Tensor, pre_recon: typing.List[tf.Tensor]\n    ) -> tf.Tensor:\n        recon_dim = ref.get_shape().as_list()[1]\n        self.mu = tf.identity(nn.dense(\n            pre_recon, recon_dim,\n            deviation_regularizer=self.deviation_regularizer,\n            scope=\"mu_dense\"\n        ), name=\"mu\")\n        self.log_var = tf.identity(nn.dense(\n            pre_recon, recon_dim,\n            deviation_regularizer=self.deviation_regularizer,\n            scope=\"log_var_dense\"\n        ), name=\"log_var\")\n        self.pi = tf.identity(nn.dense(\n            pre_recon, recon_dim,\n            deviation_regularizer=self.deviation_regularizer,\n            scope=\"dropout_logit_dense\"\n        ), name=\"dropout_logit\")\n        self.recon = tf.expm1(self.mu)\n        self.dropout_rate = tf.sigmoid(self.pi)\n        return self._log_ziln_positive(\n            tf.log1p(ref), self.mu, self.log_var, self.pi)\n\n    @staticmethod\n    def _log_ziln_positive(\n            x: tf.Tensor, mu: tf.Tensor, log_var: tf.Tensor,\n            pi: tf.Tensor, eps: float = 1e-8\n    ) -> tf.Tensor:\n        with tf.name_scope(\"log_ziln\"):\n            with tf.name_scope(\"case_zero\"):\n                case_zero = - tf.nn.softplus(- pi)\n            with tf.name_scope(\"case_non_zero\"):\n                case_non_zero = - pi - tf.nn.softplus(- pi) - 0.5 * (\n                    tf.square(x - mu) / tf.exp(log_var)\n                    + tf.log(2 * np.pi) + log_var\n                )\n            with tf.name_scope(\"mixture\"):\n                mask = tf.cast(tf.less(x, eps), tf.float32)\n                res = tf.identity(\n                    tf.multiply(mask, case_zero) +\n                    tf.multiply(1 - mask, case_non_zero),\n                    name=\"likelihood\"\n                )\n            return res\n\n\nclass MSE(ProbModel):\n\n    def __init__(\n            self, h_dim: int = 128, depth: int = 1, dropout: float = 0.0,\n            lambda_reg: float = 0.0, fine_tune: bool = False,\n            deviation_reg: float = 0.0, name=\"MSE\"\n    ) -> None:\n        super(MSE, self).__init__(\n            h_dim, depth, dropout, lambda_reg,\n            fine_tune, deviation_reg, name=name\n        )\n\n    def _log_likelihood(\n            self, ref: tf.Tensor, pre_recon: typing.List[tf.Tensor]\n    ) -> tf.Tensor:\n        recon_dim = ref.get_shape().as_list()[1]\n        self.mu = tf.identity(nn.dense(\n            pre_recon, recon_dim,\n            deviation_regularizer=self.deviation_regularizer,\n            scope=\"mu_dense\"\n        ), name=\"mu\")\n        return tf.negative(tf.square(ref - self.mu))\n", "meta": {"hexsha": "b966be738644392f40a95bc2db5c0b23b76fb404", "size": 15667, "ext": "py", "lang": "Python", "max_stars_repo_path": "Cell_BLAST/prob.py", "max_stars_repo_name": "gao-lab/Cell_BLAST", "max_stars_repo_head_hexsha": "45b14bbd3385b8a7be0b48ef5ab42bc946f3558f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61, "max_stars_repo_stars_event_min_datetime": "2019-04-12T17:31:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T11:46:29.000Z", "max_issues_repo_path": "Cell_BLAST/prob.py", "max_issues_repo_name": "gao-lab/Cell_BLAST", "max_issues_repo_head_hexsha": "45b14bbd3385b8a7be0b48ef5ab42bc946f3558f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2019-08-16T21:19:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T09:13:58.000Z", "max_forks_repo_path": "Cell_BLAST/prob.py", "max_forks_repo_name": "gao-lab/Cell_BLAST", "max_forks_repo_head_hexsha": "45b14bbd3385b8a7be0b48ef5ab42bc946f3558f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-11-14T06:22:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T08:01:45.000Z", "avg_line_length": 35.206741573, "max_line_length": 108, "alphanum_fraction": 0.5776472841, "include": true, "reason": "import numpy", "num_tokens": 3710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.18483966208604702}}
{"text": "import os\nimport numpy as np\nimport h5py\n\nfrom ...utils.collections import dotdict\n\n\ndef loadDefaultParams(Cmat=None, Dmat=None, lookupTableFileName=None, seed=None):\n    \"\"\"Load default parameters for a network of aLN nodes.\n    :param Cmat: Structural connectivity matrix (adjacency matrix) of coupling strengths, will be normalized to 1. If not given, then a single node simulation will be assumed, defaults to None\n    :type Cmat: numpy.ndarray, optional\n    :param Dmat: Fiber length matrix, will be used for computing the delay matrix together with the signal transmission speed parameter `signalV`, defaults to None\n    :type Dmat: numpy.ndarray, optional\n    :param lookUpTableFileName: Filename of lookup table with aln non-linear transfer functions and other precomputed quantities., defaults to aln-precalc/quantities_cascade.h\n    :type lookUpTableFileName: str, optional\n    :param seed: Seed for the random number generator, defaults to None\n    :type seed: int, optional\n    \n    :return: A dictionary with the default parameters of the model\n    :rtype: dict\n    \"\"\"\n\n    params = dotdict({})\n\n    # Todo: Model metadata\n    # recently added for easier simulation of aln and brian in pypet\n    params.model = \"aln\"\n    params.name = \"aln\"\n    params.description = \"Adaptive linear-nonlinear model of exponential integrate-and-fire neurons\"\n\n    # runtime parameters\n    params.dt = 0.1  # ms 0.1ms is reasonable\n    params.duration = 2000  # Simulation duration (ms)\n    np.random.seed(seed)  # seed for RNG of noise and ICs\n    # set seed to 0, pypet will complain otherwise\n    if seed is None:\n        seed = 0\n    params.seed = seed\n\n    # options\n    params.warn = 0  # warn if limits of lookup tables are exceeded\n    params.dosc_version = 0  # if 0, use exponential fit to linear response function\n    params.distr_delay = 0  # if 1, use distributed delays instead of fixed\n    params.filter_sigma = 0  # if 1, filter sigmae/sigmai\n    params.fast_interp = 1  # if 1, Interpolate the value from the look-up table instead of taking the closest value\n\n    # ------------------------------------------------------------------------\n    # global whole-brain network parameters\n    # ------------------------------------------------------------------------\n\n    if Cmat is None:\n        params.N = 1\n        params.Cmat = np.zeros((1, 1))\n        params.lengthMat = np.zeros((1, 1))\n\n    else:\n        params.Cmat = Cmat.copy()  # coupling matrix\n        np.fill_diagonal(params.Cmat, 0)  # no self connections\n        params.N = len(params.Cmat)  # number of nodes\n        params.lengthMat = Dmat  # delay matrix\n\n    # Signal transmission speed in mm/ms\n    params.signalV = 20.0\n\n    # PSP current amplitude in (mV/ms) (or nA/[C]) for global coupling\n    # connections between areas\n    params.c_gl = 0.3\n    # number of incoming E connections (to E population) from each area\n    params.Ke_gl = 250.0\n\n    # ------------------------------------------------------------------------\n    # local E-I node parameters\n    # ------------------------------------------------------------------------\n\n    # external input parameters:\n    params.tau_ou = 5.0  # ms timescale of ornstein-uhlenbeck (OU) noise\n    params.sigma_ou = 0.0  # mV/ms/sqrt(ms) intensity of OU oise\n    params.mue_ext_mean = 0.4  # mV/ms mean external input current to E\n    params.mui_ext_mean = 0.3  # mV/ms mean external input current to I\n\n    # Ornstein-Uhlenbeck noise state variables, set to mean input\n    # mue_ou will fluctuate around mue_ext_mean (mean of the OU process)\n    params.mue_ou = params.mue_ext_mean * np.ones((params.N,))  # np.zeros((params.N,))\n    params.mui_ou = params.mui_ext_mean * np.ones((params.N,))  # np.zeros((params.N,))\n\n    # external neuronal firing rate input\n    params.ext_exc_rate = 0.0  # kHz external excitatory rate drive\n    params.ext_inh_rate = 0.0  # kHz external inhibiroty rate drive\n\n    # externaln input currents, same as mue_ext_mean but can be time-dependent!\n    params.ext_exc_current = 0.0  # external excitatory input current [mV/ms], C*[]V/s=[]nA\n    params.ext_inh_current = 0.0  # external inhibiroty input current [mV/ms]\n\n    # Fokker Planck noise (for N->inf)\n    params.sigmae_ext = 1.5  # mV/sqrt(ms) (fixed, for now) [1-5] (Internal noise due to random coupling)\n    params.sigmai_ext = 1.5  # mV/sqrt(ms) (fixed, for now) [1-5]\n\n    # recurrent coupling parameters\n    params.Ke = 800.0  # Number of excitatory inputs per neuron\n    params.Ki = 200.0  # Number of inhibitory inputs per neuron\n\n    # synaptic delays\n    params.de = 4.0  # ms local constant delay \"EE = IE\"\n    params.di = 2.0  # ms local constant delay \"EI = II\"\n\n    # synaptic time constants\n    params.tau_se = 2.0  # ms  \"EE = IE\", for fixed delays\n    params.tau_si = 5.0  # ms  \"EI = II\"\n\n    # time constant for distributed delays (untested)\n    params.tau_de = 1.0  # ms  \"EE = IE\"\n    params.tau_di = 1.0  # ms  \"EI = II\"\n\n    # PSC amplitudes\n    params.cee = 0.3  # mV/ms\n    params.cie = 0.3  # AMPA\n    params.cei = 0.5  # GABA BrunelWang2003\n    params.cii = 0.5\n\n    # Coupling strengths used in Cakan2020\n    params.Jee_max = 2.43  # mV/ms\n    params.Jie_max = 2.60  # mV/ms\n    params.Jei_max = -3.3  # mV/ms [0-(-10)]\n    params.Jii_max = -1.64  # mV/ms\n\n    # neuron model parameters\n    params.a = 0.0  # nS, can be 15.0\n    params.b = 0.0  # pA, can be 40.0\n    params.EA = -80.0  # mV\n    params.tauA = 200.0  # ms\n\n    # single neuron paramters - if these are changed, new transfer functions must be precomputed!\n    params.C = 200.0  # pF\n    params.gL = 10.0  # nS\n    params.EL = -65.0  # mV\n    params.DeltaT = 1.5  # mV\n    params.VT = -50.0  # mV\n    params.Vr = -70.0  # mV\n    params.Vs = -40.0  # mV\n    params.Tref = 1.5  # ms\n\n    # ------------------------------------------------------------------------\n\n    # Generate and set random initial conditions\n    (\n        mufe_init,\n        mufi_init,\n        IA_init,\n        seem_init,\n        seim_init,\n        seev_init,\n        seiv_init,\n        siim_init,\n        siem_init,\n        siiv_init,\n        siev_init,\n        rates_exc_init,\n        rates_inh_init,\n    ) = generateRandomICs(params.N, seed)\n\n    params.mufe_init = mufe_init  # (linear) filtered mean input\n    params.mufi_init = mufi_init  #\n    params.IA_init = IA_init  # adaptation current\n    params.seem_init = seem_init  # mean of fraction of active synapses [0-1] (post-synaptic variable), chap. 4.2\n    params.seim_init = seim_init  #\n    params.seev_init = seev_init  # variance of fraction of active synapses [0-1]\n    params.seiv_init = seiv_init  #\n    params.siim_init = siim_init  #\n    params.siem_init = siem_init  #\n    params.siiv_init = siiv_init  #\n    params.siev_init = siev_init  #\n    params.rates_exc_init = rates_exc_init  #\n    params.rates_inh_init = rates_inh_init  #\n\n    # load precomputed aLN transfer functions from hdfs\n    if lookupTableFileName is None:\n        lookupTableFileName = os.path.join(os.path.dirname(__file__), \"aln-precalc\", \"quantities_cascade.h5\")\n\n    hf = h5py.File(lookupTableFileName, \"r\")\n    params.Irange = hf.get(\"mu_vals\")[()]\n    params.sigmarange = hf.get(\"sigma_vals\")[()]\n    params.dI = params.Irange[1] - params.Irange[0]\n    params.ds = params.sigmarange[1] - params.sigmarange[0]\n\n    params.precalc_r = hf.get(\"r_ss\")[()][()]\n    params.precalc_V = hf.get(\"V_mean_ss\")[()]\n    params.precalc_tau_mu = hf.get(\"tau_mu_exp\")[()]\n    params.precalc_tau_sigma = hf.get(\"tau_sigma_exp\")[()]\n\n    return params\n\n\ndef computeDelayMatrix(lengthMat, signalV, segmentLength=1):\n    \"\"\"\n    Compute the delay matrix from the fiber length matrix and the signal\n    velocity\n\n        :param lengthMat:       A matrix containing the connection length in\n            segment\n        :param signalV:         Signal velocity in m/s\n        :param segmentLength:   Length of a single segment in mm\n\n        :returns:    A matrix of connexion delay in ms\n    \"\"\"\n\n    normalizedLenMat = lengthMat * segmentLength\n    if signalV > 0:\n        Dmat = normalizedLenMat / signalV  # Interareal delays in ms\n    else:\n        Dmat = lengthMat * 0.0\n    return Dmat\n\n\ndef generateRandomICs(N, seed=None):\n    \"\"\" Generates random Initial Conditions for the interareal network\n\n        :params N:  Number of area in the large scale network\n\n        :returns:   A tuple of 9 N-length numpy arrays representining:\n                        mufe_init, IA_init, mufi_init, sem_init, sev_init,\n                        sim_init, siv_init, rates_exc_init, rates_inh_init\n    \"\"\"\n    np.random.seed(seed)\n\n    mufe_init = 3 * np.random.uniform(0, 1, (N,))  # mV/ms\n    mufi_init = 3 * np.random.uniform(0, 1, (N,))  # mV/ms\n    IA_init = 200.0 * np.random.uniform(0, 1, (N,))  # pA\n    seem_init = 0.5 * np.random.uniform(0, 1, (N,))\n    seim_init = 0.5 * np.random.uniform(0, 1, (N,))\n    seev_init = 0.001 * np.random.uniform(0, 1, (N,))\n    seiv_init = 0.001 * np.random.uniform(0, 1, (N,))\n    siim_init = 0.5 * np.random.uniform(0, 1, (N,))\n    siem_init = 0.5 * np.random.uniform(0, 1, (N,))\n    siiv_init = 0.01 * np.random.uniform(0, 1, (N,))\n    siev_init = 0.01 * np.random.uniform(0, 1, (N,))\n    rates_exc_init = 0.01 * np.random.uniform(0, 1, (N, 1))\n    rates_inh_init = 0.01 * np.random.uniform(0, 1, (N, 1))\n\n    return (\n        mufe_init,\n        mufi_init,\n        IA_init,\n        seem_init,\n        seim_init,\n        seev_init,\n        seiv_init,\n        siim_init,\n        siem_init,\n        siiv_init,\n        siev_init,\n        rates_exc_init,\n        rates_inh_init,\n    )\n", "meta": {"hexsha": "7cd0a995827acca567fb47777862b4be65f6a50b", "size": 9611, "ext": "py", "lang": "Python", "max_stars_repo_path": "neurolib/models/aln/loadDefaultParams.py", "max_stars_repo_name": "ChristophMetzner/neurolib", "max_stars_repo_head_hexsha": "912da81fc9dd3a348684ba695f0f4b739e596bad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-05T10:55:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-05T10:55:14.000Z", "max_issues_repo_path": "neurolib/models/aln/loadDefaultParams.py", "max_issues_repo_name": "ChristophMetzner/neurolib", "max_issues_repo_head_hexsha": "912da81fc9dd3a348684ba695f0f4b739e596bad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "neurolib/models/aln/loadDefaultParams.py", "max_forks_repo_name": "ChristophMetzner/neurolib", "max_forks_repo_head_hexsha": "912da81fc9dd3a348684ba695f0f4b739e596bad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8385826772, "max_line_length": 192, "alphanum_fraction": 0.6228280096, "include": true, "reason": "import numpy", "num_tokens": 2778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.18483965843974481}}
{"text": "import struct\nimport numpy as np\nfrom astropy import units as u\nfrom astropy.coordinates import Angle\nimport os\n\n###\n# Header parsing\n###\n\n# Dictionary of allowed keywords and their types\n# Here are the keywordss that a filter bank file may\n# contain.  Items marked with \"[*]\" are not yet # supported.  See docs for\n# indivisuabl attribtues for more detailed info.\n#\n#   * telescope_id (int): 0=fake data; 1=Arecibo; 2=Ooty... others to be added\n#   * machine_id (int): 0=FAKE; 1=PSPM; 2=WAPP; 3=OOTY... others to be added\n#   * data_type (int): 1=blimpy; 2=time series... others to be added\n#   * rawdatafile (string): the name of the original data file\n#   * source_name (string): the name of the source being observed by the telescope\n#   * barycentric (int): equals 1 if data are barycentric or 0 otherwise\n#   * pulsarcentric (int): equals 1 if data are pulsarcentric or 0 otherwise\n#   * az_start (double): telescope azimuth at start of scan (degrees)\n#   * za_start (double): telescope zenith angle at start of scan (degrees)\n#   * src_raj (double): right ascension (J2000) of source (hours, converted from hhmmss.s)\n#   * src_dej (double): declination (J2000) of source (degrees, converted from ddmmss.s)\n#   * tstart (double): time stamp (MJD) of first sample\n#   * tsamp (double): time interval between samples (s)\n#   * nbits (int): number of bits per time sample\n#   * nsamples (int): number of time samples in the data file (rarely used any more)\n#   * fch1 (double): centre frequency (MHz) of first blimpy channel\n#   * foff (double): blimpy channel bandwidth (MHz)\n#   * FREQUENCY_START [*] (character): start of frequency table (see below for explanation)\n#   * fchannel [*] (double): frequency channel value (MHz)\n#   * FREQUENCY_END [*] (character): end of frequency table (see below for explanation)\n#   * nchans (int): number of blimpy channels\n#   * nifs (int): number of seperate IF channels\n#   * refdm (double): reference dispersion measure (pc/cm**3)\n#   * period (double): folding period (s)\n#   * nbeams (int):total number of beams (?)\n#   * ibeam (int): number of the beam in this file (?)\n\nheader_keyword_types = {\n    'telescope_id' : '<l',\n    'machine_id'   : '<l',\n    'data_type'    : '<l',\n    'barycentric'  : '<l',\n    'pulsarcentric': '<l',\n    'nbits'        : '<l',\n    'nsamples'     : '<l',\n    'nchans'       : '<l',\n    'nifs'         : '<l',\n    'nbeams'       : '<l',\n    'ibeam'        : '<l',\n    'rawdatafile'  : 'str',\n    'source_name'  : 'str',\n    'az_start'     : '<d',\n    'za_start'     : '<d',\n    'tstart'       : '<d',\n    'tsamp'        : '<d',\n    'fch1'         : '<d',\n    'foff'         : '<d',\n    'refdm'        : '<d',\n    'period'       : '<d',\n    'src_raj'      : 'angle',\n    'src_dej'      : 'angle',\n}\n\n\ndef len_header(filename):\n    \"\"\" Return the length of the blimpy header, in bytes\n\n    Args:\n        filename (str): name of file to open\n\n    Returns:\n        idx_end (int): length of header, in bytes\n    \"\"\"\n    with open(filename, 'rb') as f:\n        header_sub_count = 0\n        eoh_found = False\n        while not eoh_found:\n            header_sub = f.read(512)\n            header_sub_count += 1\n            if b'HEADER_END' in header_sub:\n                idx_end = header_sub.index(b'HEADER_END') + len(b'HEADER_END')\n                eoh_found = True\n                break\n\n        idx_end = (header_sub_count -1) * 512 + idx_end\n    return idx_end\n\n\ndef read_next_header_keyword(fh):\n    \"\"\"\n\n    Args:\n        fh (file): file handler\n\n    Returns:\n    \"\"\"\n    n_bytes = np.frombuffer(fh.read(4), dtype='uint32')[0]\n\n    if n_bytes > 255:\n        n_bytes = 16\n\n    keyword = fh.read(n_bytes).decode('ascii')\n\n    if keyword in ('HEADER_START', 'HEADER_END'):\n        return keyword, 0, fh.tell()\n    dtype = header_keyword_types[keyword]\n    idx = fh.tell()\n    if dtype == '<l':\n        val = struct.unpack(dtype, fh.read(4))[0]\n    if dtype == '<d':\n        val = struct.unpack(dtype, fh.read(8))[0]\n    if dtype == 'str':\n        str_len = np.frombuffer(fh.read(4), dtype='uint32')[0]\n        val = fh.read(str_len).decode('ascii')\n    if dtype == 'angle':\n        val = struct.unpack('<d', fh.read(8))[0]\n        val = fil_double_to_angle(val)\n        if keyword == 'src_raj':\n            val = Angle(val, unit=u.hour)\n        else:\n            val = Angle(val, unit=u.deg)\n    return keyword, val, idx\n\n\ndef is_filterbank(filename):\n    \"\"\" Open file and confirm if it is a filterbank file or not. \"\"\"\n    with open(filename, 'rb') as fh:\n        is_fil = True\n\n        # Check this is a blimpy file\n        try:\n            keyword, value, idx = read_next_header_keyword(fh)\n            try:\n                assert keyword == 'HEADER_START'\n            except AssertionError:\n                is_fil = False\n        except KeyError:\n            is_fil = False\n        return is_fil\n\n\ndef read_header(filename, return_idxs=False):\n    \"\"\" Read blimpy header and return a Python dictionary of key:value pairs\n\n    Args:\n        filename (str): name of file to open\n\n    Optional args:\n        return_idxs (bool): Default False. If true, returns the file offset indexes\n                            for values\n\n    returns\n\n    \"\"\"\n    with open(filename, 'rb') as fh:\n        header_dict = {}\n        header_idxs = {}\n\n        # Check this is a blimpy file\n        keyword, value, idx = read_next_header_keyword(fh)\n\n        try:\n            assert keyword == 'HEADER_START'\n        except AssertionError:\n            raise RuntimeError(\"Not a valid blimpy file.\")\n\n        while True:\n            keyword, value, idx = read_next_header_keyword(fh)\n            if keyword == 'HEADER_END':\n                break\n            header_dict[keyword] = value\n            header_idxs[keyword] = idx\n\n    if return_idxs:\n        return header_idxs\n    return header_dict\n\ndef fix_header(filename, keyword, new_value):\n    \"\"\" Apply a quick patch-up to a Filterbank header by overwriting a header value\n\n\n    Args:\n        filename (str): name of file to open and fix. WILL BE MODIFIED.\n        keyword (stt):  header keyword to update\n        new_value (long, double, angle or string): New value to write.\n\n    Notes:\n        This will overwrite the current value of the blimpy with a desired\n        'fixed' version. Note that this has limited support for patching\n        string-type values - if the length of the string changes, all hell will\n        break loose.\n\n    \"\"\"\n\n    # Read header data and return indexes of data offsets in file\n    hd = read_header(filename)\n    hi = read_header(filename, return_idxs=True)\n    idx = hi[keyword]\n\n    # Find out the datatype for the given keyword\n    dtype = header_keyword_types[keyword]\n    dtype_to_type = {'<l'  : np.int32,\n                     'str' : bytes,\n                     '<d'  : np.float64,\n                     'angle' : to_sigproc_angle}\n    value_dtype = dtype_to_type[dtype]\n\n    # Generate the new string\n    if isinstance(value_dtype, bytes):\n        if len(hd[keyword]) == len(new_value):\n            val_str = np.int32(len(new_value)).tostring() + new_value\n        else:\n            raise RuntimeError(\"String size mismatch. Cannot update without rewriting entire file.\")\n    else:\n        val_str = value_dtype(new_value).tostring()\n\n    # Write the new string to file\n    with open(filename, 'rb+') as fh:\n        fh.seek(idx)\n        fh.write(val_str)\n\ndef fil_double_to_angle(angle):\n    \"\"\" Reads a little-endian double in ddmmss.s (or hhmmss.s) format and then\n    converts to Float degrees (or hours).  This is primarily used to read\n    src_raj and src_dej header values. \"\"\"\n\n    negative = (angle < 0.0)\n    angle = np.abs(angle)\n\n    dd = np.floor((angle / 10000))\n    angle -= 10000 * dd\n    mm = np.floor((angle / 100))\n    ss = angle - 100 * mm\n    dd += mm/60.0 + ss/3600.0\n\n    if negative:\n        dd *= -1\n\n    return dd\n\n###\n# sigproc writing functions\n###\n\ndef to_sigproc_keyword(keyword, value=None):\n    \"\"\" Generate a serialized string for a sigproc keyword:value pair\n\n    If value=None, just the keyword will be written with no payload.\n    Data type is inferred by keyword name (via a lookup table)\n\n    Args:\n        keyword (str): Keyword to write\n        value (None, float, str, double or angle): value to write to file\n\n    Returns:\n        value_str (str): serialized string to write to file.\n    \"\"\"\n    if value is None:\n        return np.int32(len(keyword)).tobytes() + keyword.encode('ascii')\n    dtype = header_keyword_types[keyword]\n\n    dtype_to_type = {'<l'  : np.int32,\n                     'str' : str,\n                     '<d'  : np.float64,\n                     'angle' : to_sigproc_angle}\n\n    value_dtype = dtype_to_type[dtype]\n\n    if isinstance(value, str):\n        value = value.encode('ascii')\n    if value_dtype is str:\n        return np.int32(len(keyword)).tobytes() + keyword.encode('ascii') + np.int32(len(value)).tobytes() + value\n    return np.int32(len(keyword)).tobytes() + keyword.encode('ascii') + value_dtype(value).tobytes()\n\ndef generate_sigproc_header(f):\n    \"\"\" Generate a serialzed sigproc header which can be written to disk.\n\n    Args:\n        f (Filterbank object): Filterbank object for which to generate header\n\n    Returns:\n        header_str (str): Serialized string corresponding to header\n    \"\"\"\n\n    header_string = b''\n    header_string += to_sigproc_keyword('HEADER_START')\n\n    for keyword in f.header.keys():\n        if keyword == 'src_raj':\n            header_string += to_sigproc_keyword('src_raj')  + to_sigproc_angle(f.header['src_raj'])\n        elif keyword == 'src_dej':\n            header_string += to_sigproc_keyword('src_dej')  + to_sigproc_angle(f.header['src_dej'])\n        elif keyword in ('az_start', 'za_start'):\n            header_string += to_sigproc_keyword(keyword)  + np.float64(f.header[keyword]).tobytes()\n        elif keyword not in header_keyword_types.keys():\n            pass\n        else:\n            header_string += to_sigproc_keyword(keyword, f.header[keyword])\n\n    header_string += to_sigproc_keyword('HEADER_END')\n    return header_string\n\n\ndef to_sigproc_angle(angle_val):\n    \"\"\" Convert an astropy.Angle to the ridiculous sigproc angle format string. \"\"\"\n    x = str(angle_val)\n\n    if '.' in x:\n        if 'h' in x:\n            d, m, s, ss = int(x[0:x.index('h')]), int(x[x.index('h')+1:x.index('m')]), \\\n            int(x[x.index('m')+1:x.index('.')]), float(x[x.index('.'):x.index('s')])\n        if 'd' in x:\n            d, m, s, ss = int(x[0:x.index('d')]), int(x[x.index('d')+1:x.index('m')]), \\\n            int(x[x.index('m')+1:x.index('.')]), float(x[x.index('.'):x.index('s')])\n    else:\n        if 'h' in x:\n            d, m, s = int(x[0:x.index('h')]), int(x[x.index('h')+1:x.index('m')]), \\\n            int(x[x.index('m')+1:x.index('s')])\n        if 'd' in x:\n            d, m, s = int(x[0:x.index('d')]), int(x[x.index('d')+1:x.index('m')]), \\\n            int(x[x.index('m')+1:x.index('s')])\n        ss = 0\n    num = str(d).zfill(2) + str(m).zfill(2) + str(s).zfill(2)+ '.' + str(ss).split(\".\")[-1]\n    return np.float64(num).tobytes()\n\n\ndef calc_n_ints_in_file(filename):\n    \"\"\" Calculate number of integrations in a given file \"\"\"\n    # Load binary data\n    h = read_header(filename)\n    n_chans = h['nchans']\n    n_ifs   = h['nifs']\n    idx_data = len_header(filename)\n    filesize = os.path.getsize(filename)\n    n_bytes_data = filesize - idx_data\n\n    if h['nbits'] == 2:\n        n_ints = int(4 * n_bytes_data / (n_chans * n_ifs))\n    elif h['nbits'] == 4:\n        n_ints = int(2 * n_bytes_data / (n_chans * n_ifs))\n    else:\n        n_bytes  = int(h['nbits'] / 8)\n        n_ints = int(n_bytes_data / (n_bytes * n_chans * n_ifs))\n\n    return n_ints\n", "meta": {"hexsha": "44933110dd819b91fa33577e71997f67f35f7028", "size": 11735, "ext": "py", "lang": "Python", "max_stars_repo_path": "blimpy/io/sigproc.py", "max_stars_repo_name": "kcui5/blimpy", "max_stars_repo_head_hexsha": "ee3e02e66cfcb6b41c7ead61cc1aad20a02d8985", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "blimpy/io/sigproc.py", "max_issues_repo_name": "kcui5/blimpy", "max_issues_repo_head_hexsha": "ee3e02e66cfcb6b41c7ead61cc1aad20a02d8985", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "blimpy/io/sigproc.py", "max_forks_repo_name": "kcui5/blimpy", "max_forks_repo_head_hexsha": "ee3e02e66cfcb6b41c7ead61cc1aad20a02d8985", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-15T16:39:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-15T16:39:07.000Z", "avg_line_length": 33.433048433, "max_line_length": 114, "alphanum_fraction": 0.5935236472, "include": true, "reason": "import numpy,from astropy", "num_tokens": 3147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18483264828894422}}
{"text": "from math import ceil\n\nimport blosc\nfrom blosc import compress_ptr, decompress_ptr, get_cbuffer_sizes\nfrom numpy import ndarray\n\n\ndef compress_array(array: ndarray, clevel: int = 3, compressor: str = \"lz4\", min_num_chunks: int = 0) -> bytes:\n    \"\"\"\n    Compresses an arbitrary ndarray that supports the '__array_interface__' into a Blosc compressed buffer.\n\n    Parameters\n    ----------\n    array: Array to compress\n    clevel: Compression level\n    compressor: compressor (any supported by Blosc)\n    min_num_chunks: Minimum number of chunks to split array into before compression.\n\n    Returns\n    -------\n    Compressed buffer (as bytes)\n\n    \"\"\"\n    array_address = array.__array_interface__[\"data\"][0]\n    array_length = array.nbytes\n    end_address = array_address + array_length\n    itemsize = array.itemsize\n\n    # Blosc does not support 64bit buffers, only 32 bit buffers:\n    max_chunk_length = blosc.MAX_BUFFERSIZE\n\n    # Let's avoid small trailing chunks and make them all about teh same size:\n    number_of_chunks = max(2, ceil(array_length / max_chunk_length)) if array_length > max_chunk_length else 1\n    number_of_chunks = max(min_num_chunks, number_of_chunks)\n    approx_chunk_length_in_bytes = array_length // number_of_chunks\n\n    # Let's make sure that the chunks are aligned to the data type:\n    approx_chunk_length_in_bytes = (approx_chunk_length_in_bytes // itemsize) * itemsize\n\n    # Let' make the chunks large enough that we are garanteed to cover the whole array:\n    approx_chunk_length_in_bytes += number_of_chunks * itemsize\n\n    # this will hold the compressed data:\n    compressed_buffer = bytearray()\n\n    # we start reading the array data here:\n    chunk_address = array_address\n\n    # We loop through each chunk:\n    while chunk_address < end_address:\n        chunk_length_in_bytes = min(approx_chunk_length_in_bytes, end_address - chunk_address)\n        compressed_chunk = compress_ptr(\n            address=chunk_address,\n            items=chunk_length_in_bytes // itemsize,\n            typesize=itemsize,\n            clevel=clevel,\n            shuffle=blosc.BITSHUFFLE,\n            cname=compressor,\n        )\n        if number_of_chunks == 1:\n            # If there is only one chunk, let's not be complicated about it:\n            compressed_buffer = compressed_chunk\n        else:\n            # If not, so bit it:\n            compressed_buffer.extend(compressed_chunk)\n        chunk_address += chunk_length_in_bytes\n\n    return bytes(compressed_buffer)\n\n\ndef decompress_array(compressed_bytes, out_array: ndarray = None) -> ndarray:\n    \"\"\"\n    Decompresses an array compressed with the 'compress_array' function.\n\n    Parameters\n    ----------\n    compressed_bytes: buffer containing compressed data\n    out_array: array of _correct_ size to put the decompressed daat in.\n\n    Returns\n    -------\n    Same array as passed as 'out_array'\n\n    \"\"\"\n\n    # get the array pointer and length in bytes:\n    array_address = out_array.__array_interface__[\"data\"][0]\n\n    # prepare the basics:\n    num_of_compressed_bytes = len(compressed_bytes)\n    offset_compressed = 0\n    address_decompressed = array_address\n\n    while num_of_compressed_bytes - offset_compressed > 32:\n\n        # This is the BLOSC header:\n        blosc_header = bytes(compressed_bytes[offset_compressed : offset_compressed + 32])\n\n        # we check how large is the first chunk available:\n        num_decompressed_bytes, num_compressed_bytes, _ = get_cbuffer_sizes(blosc_header)\n\n        # we prepare the corresponding region of the array:\n        compressed_chunk = compressed_bytes[offset_compressed : offset_compressed + num_compressed_bytes]\n\n        # do the actual decompression:\n        decompress_ptr(compressed_chunk, address_decompressed)\n\n        # we move the pointers forward:\n        offset_compressed += num_compressed_bytes\n        address_decompressed += num_decompressed_bytes\n\n    return out_array\n", "meta": {"hexsha": "5c0f74a70f12c5a2ba8861aea4d725b8c65a4c82", "size": 3925, "ext": "py", "lang": "Python", "max_stars_repo_path": "dexp/io/compress_array.py", "max_stars_repo_name": "haesleinhuepf/dexp", "max_stars_repo_head_hexsha": "2ea84f3db323724588fac565fae56f0d522bc5ca", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2021-04-21T14:09:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T02:30:59.000Z", "max_issues_repo_path": "dexp/io/compress_array.py", "max_issues_repo_name": "haesleinhuepf/dexp", "max_issues_repo_head_hexsha": "2ea84f3db323724588fac565fae56f0d522bc5ca", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2021-04-15T17:43:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T16:08:35.000Z", "max_forks_repo_path": "dexp/io/compress_array.py", "max_forks_repo_name": "haesleinhuepf/dexp", "max_forks_repo_head_hexsha": "2ea84f3db323724588fac565fae56f0d522bc5ca", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2022-02-08T17:41:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T15:32:27.000Z", "avg_line_length": 34.7345132743, "max_line_length": 111, "alphanum_fraction": 0.7077707006, "include": true, "reason": "from numpy", "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.35577490034429643, "lm_q1q2_score": 0.18483264654424303}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# ----------------------------------------------------------------------\n# Copyright 2017-2020 Airinnova AB and the PyTornado authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ----------------------------------------------------------------------\n\n# Authors:\n# * Alessandro Gastaldi\n# * Aaron Dettmann\n\n\"\"\"\nFunctions for the discretisation of the aircraft geometry into panels.\n\nDeveloped for AIRINNOVA AB, Stockholm, Sweden.\n\"\"\"\n\nimport logging\nfrom math import ceil\n\nimport numpy as np\nimport scipy.linalg.lapack as lapack\nfrom commonlibs.math.vectors import axis_rot_matrix\nfrom commonlibs.math.interpolation import lin_interpol\n\nfrom pytornado.objects.vlm_struct import VLMLattice\nimport pytornado.aero.c_vlm as c_vlm\nimport pytornado.objects.objecttools as ot\nfrom pytornado.objects.vlm_struct import BookKeepingEntry\nfrom pytornado.objects.aircraft import get_abs_segment_point_coords\n\nlogger = logging.getLogger(__name__)\n\nMIN_AUTOPANELS = 1\n\n\ndef set_autopanels(aircraft, settings):\n    \"\"\"\n    Automatically set chord- and spanwise discretisation settings\n\n    Args:\n        :aircraft: (object) data structure for aircraft geometry\n        :autopanels_c: (int) number of chordwise panels on the main wing\n        :autopanels_s: (int) number of spanwise panels on the main wing\n    \"\"\"\n\n    autopanels_c = settings.settings.get('vlm_autopanels_c', MIN_AUTOPANELS)\n    autopanels_s = settings.settings.get('vlm_autopanels_s', MIN_AUTOPANELS)\n\n    for this_segment, _ in ot.all_segments(aircraft):\n        segment = this_segment[2]\n\n        if segment.panels['num_c'] is None:\n            segment.panels['num_c'] = autopanels_c\n\n        if segment.panels['num_s'] is None:\n            wing_span = segment.parent_wing.span\n            segment_span = segment.geometry['span']\n            segment.panels['num_s'] = ceil((segment_span/wing_span)*autopanels_s)\n\n    for this_control, this_wing in ot.all_controls(aircraft):\n        control = this_control[2]\n\n        if control.panels['num_c'] is None:\n            control.panels['num_c'] = autopanels_c\n\n\ndef pre_panelling(aircraft):\n    \"\"\"\n    Create subdivisions and subareas for all aircraft wings\n\n    Note:\n        * This routine divides the wing into subdivisions and subareas\n          in order to generate a suitable mesh for wing with control surfaces.\n        * In a first step \"mandatory\" subdivisions are made: The wing is divided\n          into a minimum amount of subareas according to the leading and trailing\n          edge control surfaces.\n        * In a second step further spanwise subdivisions are added.\n\n    Args:\n        :aircraft: (obj) aircraft object\n    \"\"\"\n\n    # TODO:\n    # - Potential problem:\n    #   * The algorithm is based on \"correct ordering\" of segments:\n    #     Segments must be ordered from root to tip (check if this always given!?)\n\n    # ===== PART ONE (MANDATORY SUBDIVISIONS) =====\n\n    # For each control we must add suitable subdivisions\n    for this_control, this_wing in ot.all_controls(aircraft):\n        control = this_control[2]\n        wing = this_wing[2]\n\n        # Segment names on which control surface edges are located\n        segment_inner_name = control.segment_uid['inner']\n        segment_outer_name = control.segment_uid['outer']\n\n        # Control surface geometry\n        eta_inner = control.rel_vertices['eta_inner']\n        eta_outer = control.rel_vertices['eta_outer']\n        xsi_inner = control.rel_vertices['xsi_inner']\n        xsi_outer = control.rel_vertices['xsi_outer']\n\n        # Hinge axis\n        xsi_h1 = control.rel_hinge_vertices['xsi_inner']\n        xsi_h2 = control.rel_hinge_vertices['xsi_outer']\n\n        # ----- CASE (A) -----\n        # The left and right edge of the control are located on SAME segment\n        if segment_inner_name == segment_outer_name:\n            wing.segments[segment_inner_name].add_subdivision_for_control(\n                    eta_inner, eta_outer, control,\n                    xsi_inner, xsi_outer, xsi_h1, xsi_h2)\n\n        # ----- CASE (B) -----\n        # - The control surface spans over one or more segment borders\n        # - Now we will make a list of segments over which the control spans\n        # - We will interpolate the position of the control and the hinge\n        #   axis at segment borders\n        else:\n            # Create a list of segments which contain the control\n            # list_of_segments[0]: segment_uid\n            # list_of_segments[1]: eta_inner\n            # list_of_segments[2]: eta_outer\n            # list_of_segments[3]: xsi_inner\n            # list_of_segments[4]: xsi_outer\n            # list_of_segments[5]: xsi_h1\n            # list_of_segments[6]: xsi_h2\n            list_of_segments = []\n\n            # Flags to indicate that the inner or outer control positions have been set\n            inner_set = False\n            outer_set = False\n\n            # To start with we use averaged values for xsi (geometry and hinge axis)\n            xsi_avg = (xsi_inner + xsi_outer)/2\n            xsi_h_avg = (xsi_h1 + xsi_h2)/2\n\n            for segment_uid in wing.segments.keys():\n                if segment_uid == segment_inner_name:\n                    inner_set = True\n                    # Note: eta_outer = 1\n                    list_of_segments.append([segment_uid, eta_inner, 1, xsi_inner, xsi_avg, xsi_h1, xsi_h_avg])\n                    continue\n\n                elif inner_set and not outer_set:\n                    # Note: eta_inner = 0\n                    # Note: eta_outer = 1\n                    list_of_segments.append([segment_uid, 0, 1, xsi_avg, xsi_avg, xsi_h_avg, xsi_h_avg])\n\n                    # If we are on the last segment we must update some incorrectly set values\n                    if segment_uid == segment_outer_name:\n                        outer_set = True\n                        list_of_segments[-1][2] = eta_outer\n                        list_of_segments[-1][4] = xsi_outer\n                        list_of_segments[-1][6] = xsi_h2\n                        break\n\n            # Potentially, we must readjust the control surface geometry/hinge axis at borders\n            if (xsi_inner != xsi_outer) or (xsi_h1 != xsi_h2):\n                # Let's first compute the \"length\" of the control surface\n                control_len = [0, ]\n\n                for row in list_of_segments:\n                    segment_uid, eta_i, eta_o, xsi_i, xsi_o, xsi_hi, xsi_ho = row\n\n                    segment = wing.segments[segment_uid]\n                    segment_vertices = segment.vertices\n\n                    a = get_abs_segment_point_coords(segment_vertices, eta_i, xsi_i)\n                    b = get_abs_segment_point_coords(segment_vertices, eta_o, xsi_o)\n                    ab = b - a\n\n                    # l: total length of control\n                    l = control_len[-1]\n                    control_len.append(l + np.sqrt(np.dot(ab, ab)))\n\n                l = control_len[-1]\n\n                # Now, we update the xsi values using linear interpolation\n                for i, row in enumerate(list_of_segments):\n                    segment_uid, eta_i, eta_o, xsi_i, xsi_o, xsi_hi, xsi_ho = row\n\n                    # Update the xsi values\n                    l_i = control_len[i]\n                    l_o = control_len[i+1]\n\n                    xsi_i = lin_interpol((xsi_inner, xsi_outer), (0, l), l_i)\n                    xsi_o = lin_interpol((xsi_inner, xsi_outer), (0, l), l_o)\n                    xsi_hi = lin_interpol((xsi_h1, xsi_h2), (0, l), l_i)\n                    xsi_ho = lin_interpol((xsi_h1, xsi_h2), (0, l), l_o)\n\n                    list_of_segments[i] = [segment_uid, eta_i, eta_o, xsi_i, xsi_o, xsi_hi, xsi_ho]\n\n            # Finally, we create the subdivisions using our list\n            for row in list_of_segments:\n                segment_uid, eta_i, eta_o, xsi_i, xsi_o, xsi_h1, xsi_h2 = row\n\n                wing.segments[segment_uid].add_subdivision_for_control(\n                        eta_i, eta_o, control, xsi_i, xsi_o, xsi_h1, xsi_h2)\n\n    # ===== PART TWO (ADDITIONAL SPANWISE SUBDIVISIONS) =====\n\n    # - Adding additional spanwise subdivisions is done here in Python rather\n    #   than in the C code as it is more convenient to keep track of which\n    #   parts (subareas) of the discretised surface have which functions\n    for this_segment, _ in ot.all_segments(aircraft):\n        segment = this_segment[2]\n\n        for eta in np.linspace(0, 1, segment.panels['num_s']+1):\n            if (eta == 0) or (eta == 1):\n                continue\n            segment.add_subdivision(eta, eta, ignore_inval_eta=True)\n\n\ndef gen_lattice(aircraft, state, settings, make_new_subareas=True):\n    \"\"\"\n    Generate aircraft lattice\n\n    Perform count of number of wings, segments, controls, panels and strips.\n    Pre-allocate memory for lattice data, which is directly operated on in C.\n\n    The function `py2c_lattice` is called which generates the VLM lattice.\n    The following lattice data (for all panel) is generated:\n\n        * :lattice.p: panel corner points\n        * :lattice.v: panel vortex filament endpoints\n        * :lattice.c: panel collocation point\n        * :lattice.n: panel normal vector\n        * :lattice.a: panel surface area\n\n    When `py2c_lattice` is called it takes the following input arguments:\n\n        * :lattice: pre-allocated memory for the struct described above\n        * :array_segments: segment corner points (N*4*3)\n        * :array_airfoils: file names for airfoils at inner and outer segment (N*2)\n        * :array_symmetry: segment symmetry information (N)\n        * :array_panels: number of chordwise and spanwise panels for each segment (N*2)\n\n    Display lattice metrics in console and log file.\n\n    Args:\n        :aircraft: (object) data structure for aircraft geometry\n        :state: (object) data structure for flight state\n        :settings: (object) data structure for execution settings\n        :make_new_subareas: Flag\n\n    Returns:\n        :lattice: (object) data structure for VLM lattice\n    \"\"\"\n\n    if make_new_subareas:\n        pre_panelling(aircraft)\n\n    # Start the panel bookkeping with a clean slate\n    lattice = VLMLattice()\n    lattice.clean_bookkeeping()\n\n    logger.info(\"Getting lattice information ... \")\n\n    num_subareas = 0\n    num_r = 0  # total number of panel strips\n    num_p = 0  # total number of panels\n\n    # PANEL COUNT AND BOOK KEEPING\n    for this_subarea, _, this_segment, this_wing in ot.all_subareas(aircraft):\n        wing = this_wing[2]\n        segment = this_segment[2]\n        subarea = this_subarea[2]\n\n        num_subareas += 1\n\n        pan_idx1 = num_p\n\n        # A subarea only has chordwise subdivisions\n        num_chordwise_panels = subarea.parent_control.panels['num_c'] if \\\n                               subarea.parent_control is not None else \\\n                               segment.panels['num_c']\n\n        # If a subdivisions has a flap and/or slat we can reduce the number of\n        # chordwise subdivision\n        if subarea.type == 'segment':\n            num_chordwise_panels = ceil(subarea.rel_length*num_chordwise_panels)\n\n        # NOTE: now num_r and num_p are the same (improve !?)\n        num_r += num_chordwise_panels\n        num_p += num_chordwise_panels\n\n        lattice.update_bookkeeping(\n                BookKeepingEntry(subarea, range(pan_idx1, num_p), num_chordwise_panels, mirror=False))\n\n        if wing.symmetry:\n            num_subareas += 1\n\n            pan_idx1 = num_p\n            num_r += num_chordwise_panels\n            num_p += num_chordwise_panels\n\n            lattice.update_bookkeeping(\n                    BookKeepingEntry(subarea, range(pan_idx1, num_p), num_chordwise_panels, mirror=True))\n\n    # Make sure integers are stored as integers\n    num_wings = int(ot.count_all_wings(aircraft))\n    num_controls = int(ot.count_all_controls(aircraft))\n    num_subareas = int(num_subareas)\n    num_r = int(num_r)\n    num_p = int(num_p)\n\n    lattice.info['num_wings'] = num_wings\n    lattice.info['num_segments'] = num_subareas\n    lattice.info['num_controls'] = num_controls\n    lattice.info['num_strips'] = num_r\n    lattice.info['num_panels'] = num_p\n\n    logger.info(\"Pre-allocating lattice memory...\")\n\n    array_subareas = np.zeros((num_subareas, 4, 3), dtype=float, order='C')\n    array_symmetry = np.zeros((num_subareas), dtype=int, order='C')\n    array_panels = np.ones((num_subareas, 2), dtype=int, order='C')\n\n    i = 0\n    for entry in lattice.panel_bookkeeping:\n        subarea = entry.subarea\n        pan_idx = entry.pan_idx\n        mirror = entry.mirror\n\n        vertices = subarea.abs_vertices(mirror)\n\n        array_subareas[i, 0, :] = vertices['a']\n        array_subareas[i, 1, :] = vertices['b']\n        array_subareas[i, 2, :] = vertices['c']\n        array_subareas[i, 3, :] = vertices['d']\n\n        # TODO: array_panels can be simplified (now only vector)\n        # array_panels[i, 0] = 1\n        array_panels[i, 1] = entry.num_chordwise_panels\n        i += 1\n\n    # Override symmetry flags (0, do not mirror anything that is passed in)\n    array_symmetry = np.zeros((num_p), dtype=int, order='C')\n\n    lattice.p = np.zeros((num_p, 4, 3), dtype=float, order='C')\n    lattice.v = np.zeros((num_p, 4, 3), dtype=float, order='C')\n    lattice.c = np.zeros((num_p, 3), dtype=float, order='C')\n    lattice.bound_leg_midpoints = np.zeros((num_p, 3), dtype=float, order='C')\n    lattice.n = np.zeros((num_p, 3), dtype=float, order='C')\n    lattice.a = np.zeros((num_p), dtype=float, order='C')\n    lattice.epsilon = settings.settings['_epsilon']\n\n    logger.info(\"Generating lattice...\")\n    c_vlm.py2c_lattice(lattice, state, array_subareas, array_symmetry, array_panels)\n\n    # ----- Compute the length of the bound leg -----\n    logger.info(f\"--> Number of panels: {lattice.info['num_panels']}\")\n    logger.info(f\"--> Min panel area = {lattice.info['area_min']:.3e}\")\n    logger.info(f\"--> Max panel area = {lattice.info['area_max']:.3e}\")\n    logger.info(f\"--> Avg panel area = {lattice.info['area_avg']:.3e}\")\n    logger.info(f\"--> Min panel aspect ratio = {lattice.info['aspect_min']:.3e}\")\n    logger.info(f\"--> Max panel aspect ratio = {lattice.info['aspect_max']:.3e}\")\n    logger.info(f\"--> Avg panel aspect ratio = {lattice.info['aspect_avg']:.3e}\")\n\n    # ========== ROTATE NORMALS ==========\n    if settings.settings['_do_normal_rotations']:\n        for entry in lattice.panel_bookkeeping:\n            subarea = entry.subarea\n            pan_idx = entry.pan_idx\n            mirror = entry.mirror\n\n            # CONTROL SURFACE DEFLECTIONS\n            if subarea.parent_control is not None:\n                hinge_axis = subarea.abs_hinge_axis(mirror)\n\n                if mirror:\n                    deflection = subarea.parent_control.deflection_mirror\n                else:\n                    deflection = subarea.parent_control.deflection\n\n                # If deflection is 0, do not attempt rotation\n                if deflection:\n                    deflection = np.deg2rad(deflection)\n                    R = axis_rot_matrix(hinge_axis, deflection)\n\n                    for i in pan_idx:\n                        lattice.n[i, :] = R @ lattice.n[i, :]\n\n            # CAMBER LINE\n            eta_a = subarea.parent_subdivision.rel_vertices['eta_a']\n            eta_b = subarea.parent_subdivision.rel_vertices['eta_b']\n            eta_m = (eta_a + eta_b)/2\n            airfoil = subarea.parent_segment.segment_airfoil.at_eta(eta_m)\n\n            num_panels = len([i for i in pan_idx])\n            collocation_xsi = subarea.get_xsi_for_collocation_points(num_panels)\n\n            for pan_of_subarea, i in enumerate(pan_idx):\n                rot_axis = subarea.abs_camber_line_rot_axis(mirror)\n                xsi = collocation_xsi[pan_of_subarea]\n                angle = np.deg2rad(airfoil.camber_line_angle(xsi))\n\n                # If deflection is 0, do not attempt rotation\n                if angle:\n                    R = axis_rot_matrix(rot_axis, angle)\n                    lattice.n[i, :] = R @ lattice.n[i, :]\n    return lattice\n\n\ndef calc_downwash(lattice, vlmdata):\n    \"\"\"\n    Generate downwash factors for aircraft lattice.\n\n    Pre-allocate memory for the (num_p x num_p) downwash factor matrix.\n    The downwash calculations are performed in C, directly into this matrix.\n\n    Display matrix condition number in console and log file.\n\n    Args:\n        :lattice: (object) data structure for VLM lattice\n        :vlmdata: (object) data structure for VLM input and output\n    \"\"\"\n\n    logger.info(\"Pre-allocating downwash matrix in memory...\")\n    num_p = lattice.info['num_panels']\n    vlmdata.matrix_downwash = np.zeros((num_p, num_p), dtype=float, order='C')\n\n    logger.info(\"Computing downwash factors...\")\n    c_vlm.py2c_downwash(lattice, vlmdata.matrix_downwash)\n    logger.info(f\"--> Condition number = {np.linalg.cond(vlmdata.matrix_downwash):.3e}\")\n\n\ndef calc_boundary(lattice, state, vlmdata):\n    \"\"\"\n    Generate boundary conditions (RHS term) for VLM.\n\n    Pre-allocate memory for the (num_p x 1) right-hand-side array.\n    The right-hand side terms are computed in C, directly into this memory.\n\n    Args:\n        :lattice: (object) data structure for VLM lattice\n        :state: (object) data structure for flight state\n        :vlmdata: (object) data structure for VLM input and output\n    \"\"\"\n\n    logger.info(\"Pre-allocating rhs array in memory...\")\n    num_p = lattice.info['num_panels']\n    vlmdata.array_rhs = np.zeros((num_p), dtype=float, order='C')\n\n    logger.info(\"Computing right-hand side term...\")\n    c_vlm.py2c_boundary(lattice, state, vlmdata.array_rhs)\n    vlmdata.array_rhs = np.array(vlmdata.array_rhs)\n\n\ndef solver(vlmdata):\n    \"\"\"\n    Solve linear system for vortex strengths\n\n    Args:\n        :vlmdata: (object) data structure for VLM input and output\n    \"\"\"\n\n    logger.info(\"Solving linear system...\")\n    vlmdata.matrix_lu, vlmdata.array_pivots, vlmdata.panelwise['gamma'], _ \\\n        = lapack.dgesv(vlmdata.matrix_downwash, vlmdata.array_rhs)\n\n########\n########\n########\n    # Needed???\n    # vlmdata.panelwise['gamma'] = np.array(vlmdata.panelwise['gamma'], dtype=float, order='C')\n########\n########\n########\n\n\ndef calc_results(lattice, state, vlmdata):\n    \"\"\"\n    Calculate inwash at collocation points\n\n    Args:\n        :lattice: (object) data structure for VLM lattice\n        :state: (object) data structure for flight state\n        :vlmdata: (object) data structure for VLM input and output\n    \"\"\"\n\n    logger.info(\"Pre-allocating vortex-lattice method results...\")\n    num_p = lattice.info['num_panels']\n\n    # Allocate memory for panelwise results\n    for key in ['vx', 'vy', 'vz', 'vmag',  'fx', 'fy', 'fz', 'fmag', 'cp']:\n        vlmdata.panelwise[key] = np.zeros((num_p), dtype=float, order='C')\n\n    logger.info(\"Computing results...\")\n    c_vlm.py2c_results(lattice, state, vlmdata)\n\n    logger.info(f\"--> Fx = {vlmdata.forces['x']:10.3e}\")\n    logger.info(f\"--> Fy = {vlmdata.forces['y']:10.3e}\")\n    logger.info(f\"--> Fz = {vlmdata.forces['z']:10.3e}\")\n    logger.info(f\"--> FD = {vlmdata.forces['D']:10.3e}\")\n    logger.info(f\"--> FC = {vlmdata.forces['C']:10.3e}\")\n    logger.info(f\"--> FL = {vlmdata.forces['L']:10.3e}\")\n    logger.info(f\"--> Mx = {vlmdata.forces['l']:10.3e}\")\n    logger.info(f\"--> My = {vlmdata.forces['m']:10.3e}\")\n    logger.info(f\"--> Mz = {vlmdata.forces['n']:10.3e}\")\n\n    logger.info(f\"--> Cx = {vlmdata.coeffs['x']:7.4f}\")\n    logger.info(f\"--> Cy = {vlmdata.coeffs['y']:7.4f}\")\n    logger.info(f\"--> Cz = {vlmdata.coeffs['z']:7.4f}\")\n    logger.info(f\"--> CD = {vlmdata.coeffs['D']:7.4f}\")\n    logger.info(f\"--> CC = {vlmdata.coeffs['C']:7.4f}\")\n    logger.info(f\"--> CL = {vlmdata.coeffs['L']:7.4f}\")\n    logger.info(f\"--> Cl = {vlmdata.coeffs['l']:7.4f}\")\n    logger.info(f\"--> Cm = {vlmdata.coeffs['m']:7.4f}\")\n    logger.info(f\"--> Cn = {vlmdata.coeffs['n']:7.4f}\")\n", "meta": {"hexsha": "5381fdd83d4044cd2d60336f4eaf98372f73443e", "size": 20435, "ext": "py", "lang": "Python", "max_stars_repo_path": "_OLD_VERSION/src/lib/pytornado/aero/vlm.py", "max_stars_repo_name": "airinnova/pytornado", "max_stars_repo_head_hexsha": "6127f45af60ab05f15b441bc134089a7e7a59669", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2019-08-13T18:49:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T15:41:12.000Z", "max_issues_repo_path": "_OLD_VERSION/src/lib/pytornado/aero/vlm.py", "max_issues_repo_name": "airinnova/pytornado", "max_issues_repo_head_hexsha": "6127f45af60ab05f15b441bc134089a7e7a59669", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2019-09-11T14:48:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T08:17:52.000Z", "max_forks_repo_path": "_OLD_VERSION/src/lib/pytornado/aero/vlm.py", "max_forks_repo_name": "airinnova/pytornado", "max_forks_repo_head_hexsha": "6127f45af60ab05f15b441bc134089a7e7a59669", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-09-20T18:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-08T01:44:43.000Z", "avg_line_length": 38.7760910816, "max_line_length": 111, "alphanum_fraction": 0.6232933692, "include": true, "reason": "import numpy,import scipy", "num_tokens": 5095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18483264299556634}}
{"text": "# Copyright (c) 2017, Lehrstuhl fuer Angewandte Mechanik, Technische\n# Universitaet Muenchen.\n#\n# Distributed under BSD-3-Clause License. See LICENSE-File for more information\n#\n\"\"\"\nModule handling the whole mechanical system, no matter if it's a finite element\nsystem, defined by certain parameters or a multibody system.\n\"\"\"\n\n\nimport time\nimport os\nimport copy\n\nimport h5py\nimport numpy as np\n\nfrom .mesh import Mesh\nfrom .assembly import Assembly\nfrom .boundary import DirichletBoundary\n\n__all__ = ['MechanicalSystem',\n           'ReducedSystem',\n           'reduce_mechanical_system'\n           ]\n\nclass MechanicalSystem():\n    '''\n    Master class for mechanical systems with the goal to black-box the routines\n    of assembly and element selection.\n\n    Attributes\n    ----------\n    mesh_class : instance of Mesh()\n        Class handling the mesh.\n    assembly_class : instance of Assembly()\n        Class handling the assembly.\n    dirichlet_class : instance of DirichletBoundary\n        Class handling the Dirichlet boundary conditions.\n    T_output : list of floats\n        List of timesteps saved.\n    u_output : list of ndarrays\n        List of unconstrained displacement arrays corresponding to the\n        timesteps in T_output.\n    S_output : list of ndarrays\n        List of stress arrays corresponding to the timesteps in T_output.\n    E_output : list of ndarrays\n        List of strain arrays corresponding to the timesteps in T_output.\n    stress : ndarray\n        Array of nodal stress of the last assembly run. Shape is\n        (no_of_nodes, 6).\n    strain : ndarray\n        Array of nodal strain of the last assembly run. Shape is\n        (no_of_nodes, 6).\n    stress_recovery : bool\n        Flag for option stress_recovery.\n    iteration_info : ndarray\n        array containing the information of an iterative solution procedure.\n        iteration_info[:,0] is the time information,\n        iteration_info[:,1] is the number of iterations,\n        iteration_info[:,3] is the residual.\n    M_constr : ?\n        Mass matrix\n    D_constr : ?\n        Damping matrix\n    '''\n\n    def __init__(self, stress_recovery=False):\n        '''\n        Parameters\n        ----------\n        stress_recovery : bool, optional\n            Flag, for setting stress recovery option. Default is False.\n\n        '''\n        self.stress_recovery = stress_recovery\n        self.T_output = []\n        self.u_output = []\n        self.S_output = []\n        self.E_output = []\n        self.stress = None\n        self.strain = None\n        self.iteration_info = np.array([])\n\n        # instantiate the important classes needed for the system:\n        self.mesh_class = Mesh()\n        self.assembly_class = Assembly(self.mesh_class)\n        self.dirichlet_class = DirichletBoundary(np.nan)\n\n        # make syntax a little bit leaner\n        # !Christian Meyer: ! careful: This prohibits to easily change dirichlet_class instance, because old instance\n        # still will be referenced!\n        self.unconstrain_vec = self.dirichlet_class.unconstrain_vec\n        self.constrain_vec = self.dirichlet_class.constrain_vec\n        self.constrain_matrix = self.dirichlet_class.constrain_matrix\n\n        # initializations to be overwritten by loading functions\n        self.M_constr = None\n        self.D_constr = None\n        self.no_of_dofs_per_node = None\n\n        # external force to be overwritten by user-defined external forces\n        # self._f_ext_unconstr = lambda t: np.zeros(self.mesh_class.no_of_dofs)\n\n\n    def load_mesh_from_gmsh(self, msh_file, phys_group, material,\n                            scale_factor=1):\n        '''\n        Load the mesh from a msh-file generated by gmsh.\n\n        Parameters\n        ----------\n        msh_file : str\n            file name to an existing .msh file\n        phys_group : int\n            integer key of the physical group which is considered as the\n            mesh part\n        material : amfe.Material\n            Material associated with the physical group to be computed\n        scale_factor : float, optional\n            scale factor for the mesh to adjust the units. The default value is\n            1, i.e. no scaling is done.\n\n        Returns\n        -------\n        None\n        '''\n        self.mesh_class.import_msh(msh_file, scale_factor=scale_factor)\n        self.mesh_class.load_group_to_mesh(phys_group, material)\n        self.no_of_dofs_per_node = self.mesh_class.no_of_dofs_per_node\n\n        self.assembly_class.preallocate_csr()\n        self.dirichlet_class.no_of_unconstrained_dofs = self.mesh_class.no_of_dofs\n        self.dirichlet_class.update()\n\n\n    def deflate_mesh(self):\n        '''\n        Remove free floating nodes not connected to a selected element from\n        the mesh.\n\n        Parameters\n        ----------\n        None\n\n        Returns\n        -------\n        None\n        '''\n        self.mesh_class.deflate_mesh()\n        self.assembly_class.preallocate_csr()\n        self.dirichlet_class.no_of_unconstrained_dofs = self.mesh_class.no_of_dofs\n        self.dirichlet_class.update()\n\n\n    def load_mesh_from_csv(self, node_list_csv, element_list_csv,\n                           no_of_dofs_per_node=2,\n                           explicit_node_numbering=False,\n                           ele_type=False):\n        '''\n        Loads the mesh from two csv-files containing the node and the element list.\n\n        Parameters\n        ----------\n        node_list_csv: str\n            filename of the csv-file containing the coordinates of the nodes (x, y, z)\n        element_list_csv: str\n            filename of the csv-file containing the nodes which belong to one element\n        no_of_dofs_per_node: int, optional\n            degree of freedom per node as saved in the csv-file\n        explicit_node_numbering : bool, optional\n            flag stating, if the node numbers are explcitly numbered in the\n            csv file, i.e. if the first column gives the numbers of the nodes.\n        ele_type: str\n            Spezifiy elements type of the mesh (e.g. for a Tri-Mesh different\n            elements types as Tri3, Tri4, Tri6 can be used)\n            If not spezified value is set to 'False'\n\n        Returns\n        -------\n        None\n\n        Examples\n        --------\n        todo\n\n        '''\n        self.mesh_class.import_csv(node_list_csv, element_list_csv,\n                                   explicit_node_numbering=explicit_node_numbering,\n                                   ele_type=ele_type)\n        self.no_of_dofs_per_node = no_of_dofs_per_node\n        self.assembly_class.preallocate_csr()\n        return\n\n    def tie_mesh(self, master_key, slave_key, master_prop='phys_group',\n                 slave_prop='phys_group', tying_type='fixed', verbose=False,\n                 conform_slave_mesh=False, fix_mesh_dist=1E-3):\n        '''\n        Tie nonconforming meshes for a given master and slave side.\n\n        Parameters\n        ----------\n        master_key : int or string\n            mesh key of the master face mesh. The master face mesh has to be at\n            least the size of the slave mesh. It is better, when the master\n            mesh is larger than the slave mesh.\n        slave_key : int or string\n            mesh key of the slave face mesh or point cloud\n        master_prop : string, optional\n            mesh property for which master_key is specified.\n            Default value: 'phys_group'\n        slave_prop : string, optional\n            mesh property for which slave_key is specified.\n            Default value: 'phys_group'\n        tying_type : string {'fixed', 'slide'}\n            Mesh tying type. 'fixed' glues the meshes together while 'slide'\n            allows for a sliding motion between the meshes.\n\n        Returns\n        -------\n        None\n\n        Notes\n        -----\n        The master mesh has to embrace the full slave mesh. If this is not the\n        case, the routine will fail, a slave point outside the master mesh\n        cannot be addressed to a specific element.\n\n        '''\n\n        vals = self.mesh_class.tie_mesh(master_key=master_key,\n                                        slave_key=slave_key,\n                                        master_prop=master_prop,\n                                        slave_prop=slave_prop,\n                                        tying_type=tying_type,\n                                        verbose=verbose,\n                                        fix_mesh_dist=fix_mesh_dist)\n\n        self.dirichlet_class.add_constraints(*vals)\n        self.dirichlet_class.update()\n        return\n\n\n    def apply_dirichlet_boundaries(self, key, coord, mesh_prop='phys_group'):\n        '''\n        Apply dirichlet-boundaries to the system.\n\n        Parameters\n        ----------\n        key : int\n            Key for mesh property which is to be chosen. Matches the group given\n            in the gmsh file. For help, the function mesh_information or\n            boundary_information gives the groups\n        coord : str {'x', 'y', 'z', 'xy', 'xz', 'yz', 'xyz'}\n            coordinates which should be fixed\n        mesh_prop : str {'phys_group', 'geom_entity', 'el_type'}, optional\n            label of which the element should be chosen from. Default is\n            'phys_group'.\n\n        Returns\n        -------\n        None\n        '''\n        self.mesh_class.set_dirichlet_bc(key, coord, mesh_prop)\n        self.dirichlet_class.constrain_dofs(self.mesh_class.dofs_dirichlet)\n        return\n\n    def apply_neumann_boundaries(self, key, val, direct, time_func=None,\n                                 shadow_area=False, mesh_prop='phys_group'):\n        '''\n        Apply neumann boundaries to the system via skin elements.\n\n        Parameters\n        ----------\n        key : int\n            Key of the physical domain to be chosen for the neumann bc\n        val : float\n            value for the pressure/traction onto the element\n        direct : ndarray or str 'normal'\n            Direction, in which force should act at. If\n        time_func : function object\n            Function object returning a value between -1 and 1 given the\n            input t:\n\n            >>> val = time_func(t)\n\n        shadow_area : bool, optional\n            flag, if force should be proportional to shadow area of surface\n            with respect to direction. Default: False.\n        mesh_prop : str {'phys_group', 'geom_entity', 'el_type'}, optional\n            label of which the element should be chosen from. Default is\n            phys_group.\n\n        Returns\n        -------\n        None\n        '''\n        self.mesh_class.set_neumann_bc(key=key, val=val, direct=direct,\n                                       time_func=time_func,\n                                       shadow_area=shadow_area,\n                                       mesh_prop=mesh_prop)\n        self.assembly_class.compute_element_indices()\n        return\n\n\n    def export_paraview(self, filename, field_list=None):\n        '''\n        Export the system with the given information to paraview.\n\n        Parameters\n        ----------\n        filename : str\n            filename to which the xdmf file and the hdf5 file will be saved.\n        field_list : list, optional\n            list of tuples containing a field to be exported as well as a\n            dictionary with the attribute information of the hdf5 file.\n            Example:\n\n                >>> # example field list with reduced displacement not to export\n                >>> # ParaView and strain epsilon to be exported to ParaView\n                >>> field_list = [(q_red, {'ParaView':False, 'Name':'q_red'}),\n                                  (eps, {'ParaView':True,\n                                         'Name':'epsilon',\n                                         'AttributeType':'Tensor6',\n                                         'Center':'Node',\n                                         'NoOfComponents':6})]\n\n        Returns\n        -------\n        None\n        '''\n        if field_list is None:\n            field_list = []\n        t1 = time.time()\n        if len(self.T_output) is 0:\n            self.T_output.append(0)\n            self.u_output.append(np.zeros(self.mesh_class.no_of_dofs))\n            if self.stress_recovery:\n                self.S_output.append(np.zeros((self.mesh_class.no_of_nodes, 6)))\n                self.E_output.append(np.zeros((self.mesh_class.no_of_nodes, 6)))\n        print('Start exporting mesh for paraview to:\\n    ', filename)\n\n        if self.stress_recovery and len(self.S_output) > 0 \\\n           and len(self.E_output) > 0:\n            no_of_timesteps = len(self.T_output)\n            S_array = np.array(self.S_output).reshape((no_of_timesteps, -1))\n            E_array = np.array(self.E_output).reshape((no_of_timesteps, -1))\n            S_export = (S_array.T, {'ParaView':True,\n                                  'Name':'stress',\n                                  'AttributeType':'Tensor6',\n                                  'Center':'Node',\n                                  'NoOfComponents':6})\n            E_export = (E_array.T, {'ParaView':True,\n                                  'Name':'strain',\n                                  'AttributeType':'Tensor6',\n                                  'Center':'Node',\n                                  'NoOfComponents':6})\n            field_list.append(S_export)\n            field_list.append(E_export)\n\n        bmat = self.dirichlet_class.b_matrix()\n        self.mesh_class.save_mesh_xdmf(filename, field_list, bmat, u=self.u_output, timesteps=self.T_output)\n        t2 = time.time()\n        print('Mesh for paraview successfully exported in ' +\n              '{0:4.2f} seconds.'.format(t2 - t1))\n        return\n\n    def M(self, u=None, t=0):\n        '''\n        Compute the Mass matrix of the dynamical system.\n\n        Parameters\n        ----------\n        u : ndarray, optional\n            array of the displacement\n        t : float\n            time\n\n        Returns\n        -------\n        M : sp.sparse.sparse_matrix\n            Mass matrix with applied constraints in sparse csr-format\n        '''\n        if u is not None:\n            u_unconstr = self.unconstrain_vec(u)\n        else:\n            u_unconstr = None\n\n        M_unconstr = self.assembly_class.assemble_m(u_unconstr, t)\n        self.M_constr = self.constrain_matrix(M_unconstr)\n        return self.M_constr\n\n    def K(self, u=None, t=0):\n        '''\n        Compute the stiffness matrix of the mechanical system\n\n        Parameters\n        ----------\n        u : ndarray, optional\n            Displacement field in voigt notation\n        t : float, optional\n            Time\n\n        Returns\n        -------\n        K : sp.sparse.sparse_matrix\n            Stiffness matrix with applied constraints in sparse csr-format\n        '''\n        if u is None:\n            u = np.zeros(self.dirichlet_class.no_of_constrained_dofs)\n\n        K_unconstr = \\\n            self.assembly_class.assemble_k_and_f(self.unconstrain_vec(u), t)[0]\n\n        return self.constrain_matrix(K_unconstr)\n\n    def D(self, u=None, t=0):\n        '''\n        Return the damping matrix of the mechanical system\n\n        Parameters\n        ----------\n        u : ndarray, optional\n            Displacement field in voigt notation\n        t : float, optional\n            Time\n\n        Returns\n        -------\n        D : sp.sparse.sparse_matrix\n            Damping matrix with applied constraints in sparse csr-format\n        '''\n        if self.D_constr is None:\n            return self.K()*0\n        else:\n            return self.D_constr\n\n    def f_int(self, u, t=0):\n        '''Return the elastic restoring force of the system '''\n        f_unconstr = \\\n            self.assembly_class.assemble_k_and_f(self.unconstrain_vec(u), t)[1]\n        return self.constrain_vec(f_unconstr)\n\n    def _f_ext_unconstr(self, u, t):\n        '''\n        Return the unconstrained external force coming from the Neumann BCs.\n        \n        This function is just a placeholder if you want to change the behavior of f_ext:\n        This function may be monkeypatched if necessary, for instance, when a\n        global external force, e.g. gravity, should be applied.\n        '''\n        f_unconstr = \\\n            self.assembly_class.assemble_k_and_f_neumann(self.unconstrain_vec(u), t)[1]\n        return f_unconstr\n\n    def f_ext(self, u, du, t):\n        '''\n        Return the nonlinear external force of the right hand side\n        of the equation, i.e. the excitation.\n        '''\n        if u is None:\n            u = np.zeros(self.dirichlet_class.no_of_constrained_dofs)\n        return self.constrain_vec(self._f_ext_unconstr(u, t))\n\n    def K_and_f(self, u=None, t=0):\n        '''\n        Compute tangential stiffness matrix and nonlinear force vector\n        in one assembly run.\n        '''\n        if u is None:\n            u = np.zeros(self.dirichlet_class.no_of_constrained_dofs)\n        if self.stress_recovery: # make sure, that current stress / strain is exported\n            K_unconstr, f_unconstr, self.stress, self.strain = \\\n                self.assembly_class.assemble_k_f_S_E(self.unconstrain_vec(u), t)\n        else:\n            K_unconstr, f_unconstr = \\\n                self.assembly_class.assemble_k_and_f(self.unconstrain_vec(u), t)\n        K = self.constrain_matrix(K_unconstr)\n        f = self.constrain_vec(f_unconstr)\n        return K, f\n\n    def S_and_res(self, u, du, ddu, dt, t, beta, gamma):\n        r'''\n        Compute jacobian and residual for implicit Newmark time integration.\n\n        Parameters\n        ----------\n        u : ndarray\n            displacement; dimension (ndof,)\n        du : ndarray\n            velocity; dimension (ndof,)\n        ddu : ndarray\n            acceleration; dimension (ndof,)\n        dt : float\n            time step width\n        t : float\n            time of current time step (for time dependent loads)\n        beta : float\n            weighting factor for position in generalized-:math:`\\alpha` scheme\n        gamma : float\n            weighting factor for velocity in generalized-:math:`\\alpha` scheme\n\n        Returns\n        -------\n        S : ndarray\n            jacobian matrix of residual; dimension (ndof, ndof)\n        res : ndarray\n            residual; dimension (ndof,)\n\n        Notes\n        -----\n        Time integration scheme: The iteration matrix is composed using the\n        Newmark scheme:\n\n        .. math:: \\mathbf S \\Delta u = -\\mathbf{res}\n        \n        .. math:: \\mathbf S = K + \\frac{\\gamma}{\\beta h} \\mathbf{D}\n                    + \\frac{1}{\\beta h^2} \\mathbf{M}\n        \n        which bases on the time discretization of the velocity and the\n        displacement:\n\n        .. math:: \\mathbf{\\dot{q}}_{n+1} & = \\mathbf{\\dot{q}}_{n} + (1-\\gamma)h\n                  \\mathbf{\\ddot{q}}_{n} + \\gamma h \\mathbf{\\ddot{q}}_{n+1}\n\n        #.. math:: \\mathbf{q}_{n+1} & = \\mathbf{q}_n + h \\mathbf{\\dot{q}}_n +\n        #          \\left(\\frac{1}{2} - \\beta\\right)h^2\\mathbf{\\ddot{q}}_n +\n        #          h^2\\beta\\mathbf{\\ddot{q}}_{n+1}\n        .. math:: \\mathbf{\\ddot{q}}_{n+1} &= \\frac{1}{\\beta h^2} \\left(\n                    \\mathbf{\\Delta q} - h \\mathbf{q}_n - (\\frac{1}{2} - \\beta) h^2 \\mathbf{\\ddot q}_n \\right)\n\n        This method is using the variables/methods\n\n            - self.M()\n            - self.M_constr\n            - self.K_and_f()\n            - self.f_ext()\n\n        If these methods are implemented correctly in a daughter class, the\n        time integration interface should work properly.\n\n        '''\n        # compute mass matrix only once if it hasnt's been computed yet\n        if self.M_constr is None:\n            self.M()\n\n        K, f = self.K_and_f(u, t)\n        f_ext = self.f_ext(u, du, t)\n        if self.D_constr is None:\n            S = K + 1/(beta*dt**2)*self.M_constr\n            res = f - f_ext + self.M_constr @ ddu\n        else: # damping\n            S = K \\\n                + gamma/(beta*dt) * self.D_constr \\\n                + 1/(beta*dt**2) * self.M_constr\n            res = f - f_ext + self.M_constr @ ddu + self.D_constr @ du\n        return S, res, f_ext\n\n\n\n    def gen_alpha(self, q, dq, ddq, q_old, dq_old, ddq_old,\n                  f_ext_old, dt, t, alpha_m, alpha_f, beta, gamma):\n        '''\n        Computation of Jacobian and residual for generalized-alpha time\n        integration scheme.\n\n        TODO\n\n        '''\n        # compute mass matrix only if it has not been computed yet\n        if self.M_constr is None:\n            self.M()\n\n        ddq_m = (1-alpha_m)*ddq + alpha_m*ddq_old\n        dq_f = (1-alpha_f)*dq + alpha_f*dq_old\n        q_f = (1-alpha_f)*q + alpha_f*q_old\n\n        K_f, f_f = self.K_and_f(q_f, t)\n        f_ext = self.f_ext(q, dq, t)\n        f_ext_f = (1-alpha_f) * f_ext + alpha_f * f_ext_old\n\n        if self.D_constr is None:\n            Jac = (1-alpha_f) * K_f + (1-alpha_m)/(beta*dt**2) * self.M_constr\n            res = f_f - f_ext_f + self.M_constr @ ddq_m\n        else: # damping\n            Jac =   (1-alpha_f) * K_f \\\n                  + (1-alpha_f)*gamma/(beta*dt) * self.D_constr \\\n                  + (1-alpha_m)/(beta*dt**2) * self.M_constr\n            res = f_f - f_ext_f + self.D_constr @ dq_f + self.M_constr @ ddq_m\n\n        return Jac, res, f_ext\n\n\n    def apply_rayleigh_damping(self, alpha, beta):\n        '''\n        Apply Rayleigh damping to the system.\n\n        The damping matrix D is defined as\n\n        D = alpha*M + beta*K(0)\n\n        Thus, it is Rayleigh Damping applied to the linearized system\n        around zero deformation.\n\n        Parameters\n        ----------\n        alpha : float\n            damping coefficient for the mass matrix\n        beta : float\n            damping coefficient for the stiffness matrix\n\n        '''\n        if self.M_constr is None:\n            self.M()\n        self.D_constr = alpha*self.M_constr + beta*self.K()\n        return\n\n    def write_timestep(self, t, u):\n        '''\n        write the timestep to the mechanical_system class\n        '''\n        self.T_output.append(t)\n        self.u_output.append(self.unconstrain_vec(u))\n        # Check both, if stress recovery and if stress and strain is there\n        if self.stress_recovery:\n            # catch the case when no stress was computed, for instance in time\n            # integration\n            if self.stress is None and self.strain is None:\n                self.stress = np.zeros((self.mesh_class.no_of_nodes,6))\n                self.strain = np.zeros((self.mesh_class.no_of_nodes,6))\n            self.S_output.append(self.stress.copy())\n            self.E_output.append(self.strain.copy())\n\n    def clear_timesteps(self):\n        '''\n        Clear the timesteps gathered internally\n        '''\n        self.T_output = []\n        self.u_output = []\n        self.S_output = []\n        self.E_output = []\n        self.stress = None\n        self.strain = None\n        self.iteration_info = np.array([])\n        return\n\n\nclass ReducedSystem(MechanicalSystem):\n    '''\n    Class for reduced systems.\n    It is directly inherited from MechanicalSystem.\n    Provides the interface for an integration scheme and so on where a basis\n    vector is to be chosen...\n\n    Notes\n    -----\n    The Basis V is a Matrix with x = V*q mapping the reduced set of coordinates\n    q onto the physical coordinates x. The coordinates x are constrained, i.e.\n    the x denotes the full system in the sense of the problem set and not of\n    the pure finite element set.\n\n    The system runs without providing a V_basis when constructing the method\n    only for the unreduced routines.\n\n\n    Attributes\n    ----------\n    V : ?\n        Set of basis vectors the system has been reduced with u_constr = V * q\n    V_unconstr : ?\n        Extended reduction basis that is extended by the displacement coordinates of the constrained degrees of\n        freedom\n    u_red_output : ?\n        Stores the timeseries of the generalized coordinates (similar to u_output)\n    assembly_type : {'indirect', 'direct'}\n        Stores the type of assembly method how the reduced system is computed\n    \n    Examples\n    --------\n    \n    my_system = amfe.MechanicalSystem()\n    V = vibration_modes(my_system, n=20)\n    my_reduced_system = amfe.reduce_mechanical_system(my_system, V)\n    \n\n    '''\n\n    def __init__(self, V_basis=None, assembly='indirect', **kwargs):\n        '''\n        Parameters\n        ----------\n        V_basis : ndarray, optional\n            Basis onto which the problem will be projected with an\n            Galerkin-Projection.\n        assembly : str {'direct', 'indirect'}\n            flag setting, if direct or indirect assembly is done. For larger\n            reduction bases, the indirect method is much faster.\n        **kwargs : dict, optional\n            Keyword arguments to be passed to the mother class MechanicalSystem.\n\n        Returns\n        -------\n        None\n        '''\n        MechanicalSystem.__init__(self, **kwargs)\n        self.V = V_basis\n        self.u_red_output = []\n        self.V_unconstr = self.dirichlet_class.unconstrain_vec(V_basis)\n        self.assembly_type = assembly\n\n    def K_and_f(self, u=None, t=0):\n        if u is None:\n            u = np.zeros(self.V.shape[1])\n        if self.assembly_type == 'direct':\n            # this is really slow! So this is why the assembly is done diretly\n            K, f_int = self.assembly_class.assemble_k_and_f_red(self.V_unconstr,\n                                                                u, t)\n        elif self.assembly_type == 'indirect':\n            K_raw, f_raw = self.assembly_class.assemble_k_and_f(self.V_unconstr @ u,\n                                                                t)\n            K = self.V_unconstr.T @ K_raw @ self.V_unconstr\n            f_int = self.V_unconstr.T @ f_raw\n        else:\n            raise ValueError('The given assembly type for a reduced system '\n                             + 'is not valid.')\n        return K, f_int\n\n    def K(self, u=None, t=0):\n        if u is None:\n            u = np.zeros(self.V.shape[1])\n\n        if self.assembly_type == 'direct':\n            # this is really slow! So this is why the assembly is done diretly\n            K, f_int = self.assembly_class.assemble_k_and_f_red(self.V_unconstr,\n                                                                u, t)\n        elif self.assembly_type == 'indirect':\n            K_raw, f_raw = self.assembly_class.assemble_k_and_f(self.V_unconstr @ u,\n                                                                t)\n            K = self.V_unconstr.T @ K_raw @ self.V_unconstr\n        else:\n            raise ValueError('The given assembly type for a reduced system '\n                             + 'is not valid.')\n        return K\n\n    def f_ext(self, u, du, t):\n        return self.V.T @ MechanicalSystem.f_ext(self, self.V @ u, du, t)\n\n    def f_int(self, u, t=0):\n\n        if self.assembly_type == 'direct':\n            # this is really slow! So this is why the assembly is done diretly\n            K, f_int = self.assembly_class.assemble_k_and_f_red(self.V_unconstr,\n                                                                u, t)\n        elif self.assembly_type == 'indirect':\n            K_raw, f_raw = self.assembly_class.assemble_k_and_f(self.V_unconstr @ u,\n                                                                t)\n            f_int = self.V_unconstr.T @ f_raw\n        else:\n            raise ValueError('The given assembly type for a reduced system '\n                             + 'is not valid.')\n\n        return f_int\n\n    def D(self, u=None, t=0):\n\n        if self.assembly_type == 'direct':\n            raise NotImplementedError('The direct method is note implemented yet for damping matrices')\n        elif self.assembly_type == 'indirect':\n            self.D_constr = self.V.T @ MechanicalSystem.D(self, self.V @ u, t) @ self.V\n        else:\n            raise ValueError('The given assembly type for a reduced system '\n                             + 'is not valid.')\n\n        return self.D_constr\n\n    def M(self, u=None, t=0):\n        # Just a plain projection\n        # not so well but works...\n        self.M_constr = self.V.T @ MechanicalSystem.M(self, u, t) @ self.V\n        return self.M_constr\n\n    def write_timestep(self, t, u):\n        MechanicalSystem.write_timestep(self, t, self.V @ u)\n        self.u_red_output.append(u.copy())\n\n    def K_unreduced(self, u=None, t=0):\n        '''\n        Unreduced Stiffness Matrix.\n\n        Parameters\n        ----------\n        u : ndarray, optional\n            Displacement of constrained system. Default is zero vector.\n        t : float, optionial\n            Time. Default is 0.\n\n        Returns\n        -------\n        K : sparse csr matrix\n            Stiffness matrix\n\n        '''\n        return MechanicalSystem.K(self, u, t)\n\n    def f_int_unreduced(self, u, t=0):\n        '''\n        Internal nonlinear force of the unreduced system.\n\n        Parameters\n        ----------\n        u : ndarray\n            displacement of unreduces system.\n        t : float, optional\n            time, default value: 0.\n\n        Returns\n        -------\n        f_nl : ndarray\n            nonlinear force of unreduced system.\n\n        '''\n        return MechanicalSystem.f_int(self, u, t)\n\n    def M_unreduced(self):\n        '''\n        Unreduced mass matrix.\n        '''\n        return MechanicalSystem.M(self)\n\n    def export_paraview(self, filename, field_list=None):\n        '''\n        Export the produced results to ParaView via XDMF format.\n        '''\n        u_red_export = np.array(self.u_red_output).T\n        u_red_dict = {'ParaView':'False', 'Name':'q_red'}\n\n        if field_list is None:\n            new_field_list = []\n        else:\n            new_field_list = field_list.copy()\n\n        new_field_list.append((u_red_export, u_red_dict))\n\n        MechanicalSystem.export_paraview(self, filename, new_field_list)\n\n        # add V and Theta to the hdf5 file\n        filename_no_ext, _ = os.path.splitext(filename)\n        with h5py.File(filename_no_ext + '.hdf5', 'r+') as f:\n            f.create_dataset('reduction/V', data=self.V)\n\n        return\n\n    def clear_timesteps(self):\n        MechanicalSystem.clear_timesteps(self)\n        self.u_red_output = []\n\n\n\ndef reduce_mechanical_system(mechanical_system, V, overwrite=False,\n                             assembly='indirect'):\n    '''\n    Reduce the given mechanical system with the linear basis V.\n\n    Parameters\n    ----------\n    mechanical_system : instance of MechanicalSystem\n        Mechanical system which will be transformed to a ReducedSystem.\n    V : ndarray\n        Reduction Basis for the reduced system\n    overwrite : bool, optional\n        switch, if mechanical system should be overwritten (is less memory\n        intensive for large systems) or not.\n    assembly : str {'direct', 'indirect'}\n            flag setting, if direct or indirect assembly is done. For larger\n            reduction bases, the indirect method is much faster.\n\n    Returns\n    -------\n    reduced_system : instance of ReducedSystem\n        Reduced system with same properties of the mechanical system and\n        reduction basis V\n\n    Example\n    -------\n\n    '''\n\n    if overwrite:\n        reduced_sys = mechanical_system\n    else:\n        reduced_sys = copy.deepcopy(mechanical_system)\n    reduced_sys.__class__ = ReducedSystem\n    reduced_sys.V = V.copy()\n    reduced_sys.V_unconstr = reduced_sys.dirichlet_class.unconstrain_vec(V)\n    reduced_sys.u_red_output = []\n    reduced_sys.M_constr = None\n    # reduce Rayleigh damping matrix\n    if reduced_sys.D_constr is not None:\n        reduced_sys.D_constr = V.T @ reduced_sys.D_constr @ V\n    reduced_sys.assembly_type = assembly\n    return reduced_sys\n\n\n# This class is not integrated in AMfe yet.\n# It should apply linear combinations of external forces\n# f_ext = B(x) * F(t)\n# This function is not integrated in the Neumann Boundary conditions.\n#\n# class ExternalForce:\n#     '''\n#     Class for mimicking the external forces based on a force basis and time\n#     values. The force values are linearly interpolated.\n#\n#     '''\n#     def __init__(self, force_basis, force_series, t_series):\n#         '''\n#         Parameters\n#         ----------\n#         force_basis : ndarray, shape(ndim, n_dofs)\n#             force basis for the force series\n#         force_seris : ndarray, shape(n_timesteps, n_dofs)\n#             array containing the force dofs corresponding to the time values\n#             given in t_series\n#         t_series : ndarray, shape(n_timesteps)\n#             array containing the time values\n#\n#         '''\n#         self.force_basis = force_basis\n#         self.force_series= force_series\n#         self.T = t_series\n#         return\n#\n#     def f_ext(self, u, du, t):\n#         '''\n#         Mimicked external force for the given force time series\n#         '''\n#         # Catch the case that t is larger than the data set\n#         if t >= self.T[-1]:\n#             return self.force_basis @ self.force_series[-1]\n#\n#         t2_idx = np.where(self.T > t)[0][0]\n#\n#         # if t is smaller than lowest value of T, pick the first value in the\n#         # force series\n#         if t2_idx == 0:\n#             force_amplitudes = self.force_series[0]\n#         else:\n#             t1_idx = t2_idx - 1\n#             t2 = self.T[t2_idx]\n#             t1 = self.T[t1_idx]\n#\n#             force_amplitudes = ( (t2-t)*self.force_series[t1_idx]\n#                                + (t-t1)*self.force_series[t2_idx]) / (t2-t1)\n#         return self.force_basis @ force_amplitudes\n", "meta": {"hexsha": "33aa7c9997b6f01069a1b09dec69cbcdc5c1ac33", "size": 33589, "ext": "py", "lang": "Python", "max_stars_repo_path": "amfe/mechanical_system.py", "max_stars_repo_name": "c-meyer/github-spielwiese", "max_stars_repo_head_hexsha": "0dad8df6277a09b2f250010b476854dc91d4d8ad", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "amfe/mechanical_system.py", "max_issues_repo_name": "c-meyer/github-spielwiese", "max_issues_repo_head_hexsha": "0dad8df6277a09b2f250010b476854dc91d4d8ad", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "amfe/mechanical_system.py", "max_forks_repo_name": "c-meyer/github-spielwiese", "max_forks_repo_head_hexsha": "0dad8df6277a09b2f250010b476854dc91d4d8ad", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1349372385, "max_line_length": 117, "alphanum_fraction": 0.575247849, "include": true, "reason": "import numpy", "num_tokens": 7502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.18483263944688968}}
{"text": "import numpy as np\n\n\n# -----------------------------------------------------------------------------------------\n# \n# \n\nclass Ion:\n    def __init__(self, protons, neutrons, electrons, energy, x=0., dx=0., y=0., dy=0., dl=0., dp=0.):\n        self.protons = protons\n        self.neutrons = neutrons\n        self.electrons = electrons\n        self.energy = energy\n        self.x = x\n        self.dx = dx\n        self.y = y\n        self.dy = dy\n        self.dl = dl\n        self.dp = dp\n\n    def __repr__(self):\n        r = \"Ion(mass=\" + str(self.mass) + \"u, \"\n        r += \"chargeState=\" + str(self.charge) + \"e, \"\n        r += \"energy=\" + str(self.energy) + \"eV, \"\n        r += \"x=\" + str(self.x) + \"m, \"\n        r += \"dx=\" + str(self.dx) + \"rad, \"\n        r += \"y=\" + str(self.y) + \"m, \"\n        r += \"dy=\" + str(self.dy) + \"rad, \"\n        r += \"dl=\" + str(self.dl) + \"m, \"\n        r += \"dp=\" + str(self.dp) + \")\"\n        return r\n\n    def __str__(self):\n        if self.charge>0:\n            return str(self.mass_number) + self.nomenclature + \"+\" + str(self.charge)\n        else:\n            return str(self.mass_number) + self.nomenclature + str(self.charge)\n\n    @property\n    def charge(self):\n        return self.protons-self.electrons\n\n    @property\n    def mass_number(self):\n        return self.protons+self.neutrons\n\n    @property\n    def nomenclature(self):\n        symbols = [\"H\", \"He\", \"Li\", \"Be\", \"B\", \"C\", \"N\", \"O\", \"F\", \"Ne\", \"Na\",\n         \"Mg\", \"Al\", \"Si\", \"P\", \"S\", \"Cl\", \"Ar\", \"K\", \"Ca\", \"Sc\", \"Ti\",\n         \"V\", \"Cr\", \"Mn\", \"Fe\", \"Co\", \"Ni\", \"Cu\", \"Zn\", \"Ga\", \"Ge\", \"As\",\n         \"Se\", \"Br\", \"Kr\", \"Rb\", \"Sr\", \"Y\", \"Zr\", \"Nb\", \"Mo\", \"Tc\", \"Ru\",\n         \"Rh\", \"Pd\", \"Ag\", \"Cd\", \"In\", \"Sn\", \"Sb\", \"Te\", \"I\", \"Xe\", \"Cs\",\n         \"Ba\", \"La\", \"Ce\", \"Pr\", \"Nd\", \"Pm\", \"Sm\", \"Eu\", \"Gd\", \"Tb\", \"Dy\",\n         \"Ho\", \"Er\", \"Tm\", \"Yb\", \"Lu\", \"Hf\", \"Ta\", \"W\", \"Re\", \"Os\", \"Ir\",\n         \"Pt\", \"Au\", \"Hg\", \"TI\", \"Pb\", \"Bi\", \"Po\", \"At\", \"Rn\", \"Fr\", \"Ra\",\n         \"Ac\", \"Th\", \"Pa\", \"U\", \"Np\", \"Pu\", \"Am\", \"Cm\", \"Bk\", \"Cf\", \"Es\",\n         \"Fm\", \"Md\", \"No\", \"Lr\", \"Rf\", \"Db\", \"Sg\", \"Bh\", \"Hs\", \"Mt\", \"Ds\",\n         \"Rg\", \"Cn\", \"Uut\", \"Fl\", \"Uup\", \"Lv\"]\n        if self.protons > 117:\n            return \"??\"\n        elif self.protons < 1:\n            raise Exception(\"Number of protons < 1\")\n        else:\n            return symbols[self.protons-1]\n\n", "meta": {"hexsha": "ca61871049edca3a3ef1ba94bc5f28109d2064cb", "size": 2357, "ext": "py", "lang": "Python", "max_stars_repo_path": "particles.py", "max_stars_repo_name": "StephanII/accelerator-toolkit", "max_stars_repo_head_hexsha": "e0d1e829aa7288ddcd8707fa5dc07f31939d26b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "particles.py", "max_issues_repo_name": "StephanII/accelerator-toolkit", "max_issues_repo_head_hexsha": "e0d1e829aa7288ddcd8707fa5dc07f31939d26b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "particles.py", "max_forks_repo_name": "StephanII/accelerator-toolkit", "max_forks_repo_head_hexsha": "e0d1e829aa7288ddcd8707fa5dc07f31939d26b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1791044776, "max_line_length": 101, "alphanum_fraction": 0.4094187527, "include": true, "reason": "import numpy", "num_tokens": 830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.18483263944688968}}
{"text": "import numpy as np\nimport math\nimport ctypes\nimport util.utilities as util\nimport gadget_lib.gadget as gadget\n\ndef checklen(x):\n    return len(np.array(x,ndmin=1));\n\ndef int_round(x):\n    return np.int(np.round(x));\n\ndef ok_scan(input,xmax=1.0e10,pos=0):\n    if (pos==1):\n        return (np.isnan(input)==False) & (np.fabs(input)<=xmax) & (input > 0.);\n    else:\n        return (np.isnan(input)==False) & (np.fabs(input)<=xmax);\n\ndef fcor(x):\n    return np.array(x,dtype='f',ndmin=1)\ndef vfloat(x):\n    return x.ctypes.data_as(ctypes.POINTER(ctypes.c_float));\n\n\n\ndef calculate_zoom_center(sdir,snum,cen=[0.,0.,0.],clip_size=2.e10):\n    rgrid=np.array([1.0e10,1000.,700.,500.,300.,200.,100.,70.,50.,30.,20.,10.,5.,2.5,1.]);\n    rgrid=rgrid[rgrid <= clip_size];\n    Ps=gadget.readsnap(sdir,snum,4,cosmological=1);\n    n_new=Ps['m'].shape[0];\n    if (n_new > 1):\n        pos=Ps['p']; x0s=pos[:,0]; y0s=pos[:,1]; z0s=pos[:,2];\n    Pg=gadget.readsnap(sdir,snum,0,cosmological=1);\n    rho=np.array(Pg['rho'])*407.5;\n    if (rho.shape[0] > 0):\n        pos=Pg['p']; x0g=pos[:,0]; y0g=pos[:,1]; z0g=pos[:,2];\n    rho_cut=1.0e-5;\n    cen=np.array(cen);\n\n    for i_rcut in range(len(rgrid)):\n        for j_looper in range(5):\n            if (n_new > 1000):\n                x=x0s; y=y0s; z=z0s;\n            else:\n                ok=(rho > rho_cut);\n                x=x0g[ok]; y=y0g[ok]; z=z0g[ok];\n            x=x-cen[0]; y=y-cen[1]; z=z-cen[2];\n            r = np.sqrt(x*x + y*y + z*z);\n            ok = (r < rgrid[i_rcut]);\n            if (len(r[ok]) > 1000):\n                x=x[ok]; y=y[ok]; z=z[ok];\n                if (i_rcut <= len(rgrid)-5):\n                    cen+=np.array([np.median(x),np.median(y),np.median(z)]);\n                else:\n                    cen+=np.array([np.mean(x),np.mean(y),np.mean(z)]);\n            else:\n                if (len(r[ok]) > 200):\n                    x=x[ok]; y=y[ok]; z=z[ok];\n                    cen+=np.array([np.mean(x),np.mean(y),np.mean(z)]);\n                    \n    return cen;\n    \n    \ndef test():\n    import gadget\n    sdir='../zooms/m10_dw/'\n    snum=440\n    cen=calculate_zoom_center(sdir,snum);\n    cen=np.array([ 3306.55575601,  3029.35099489,  3235.4757624 ]);\n    print cen;\n\n    PPPs=gadget.readsnap(sdir,snum,4,cosmological=1);\n    PPP=gadget.readsnap(sdir,snum,0,cosmological=1);\n    source_pos=(np.random.rand(3,5)-0.5)*100.\n    source_pos[2,:] *= 0.02\n    for i in [0,1,2]: source_pos[i,:]+=cen[i];\n    source_pos=PPPs['p']\n    \n    mm=PPP['m'];\n    rho=PPP['rho'];\n    \n    #mm *= PPP['nh'];\n    #rho *= PPP['nh'];\n    #print np.min(PPP['nh']), np.median(PPP['nh']), np.max(PPP['nh'])\n    \n    \n    \n    xlen = 10.\n    los_nh,los_nh_hot,los_z = \\\n      return_columns_to_sources(source_pos,\\\n      PPP['p'],PPP['u'],rho,PPP['h'],PPP['ne'],PPP['nh'],PPP['z'],mm,\\\n      xrange=cen[0]+[-xlen,xlen],yrange=cen[1]+[-xlen,xlen],zrange=cen[2]+[-xlen,xlen])\n\n    print los_nh\n    print los_nh_hot\n    print los_z\n\n\n\n##\n## return: los_NH_allgas, los_NH_hotphase, los_gas_metallicity \n##\ndef return_columns_to_sources( source_pos, gas_pos, \\\n    gas_u, gas_rho, gas_hsml, gas_numh, gas_nume, gas_metallicity, gas_mass, \\\n    xrange=0, yrange=0, zrange=0, \\\n    MIN_CELL_SIZE=0.01, OUTER_RANGE_OF_INT=1200., \\\n    TRIM_PARTICLES=1 ):\n    \n    ## check the ordering of the position matrices:\n    if ((checklen(gas_pos[0,:])==3) & (checklen(gas_pos[:,0]) !=3)): gas_pos=np.transpose(gas_pos);\n    if ((checklen(source_pos[0,:])==3) & (checklen(source_pos[:,0]) !=3)): source_pos=np.transpose(source_pos);\n    ## and that metallicities are a vector, not a matrix\n    if (len(gas_metallicity.shape)>1): gas_metallicity=gas_metallicity[:,0]\n\n    if ((checklen(gas_pos[:,0]) != 3) | (checklen(gas_pos[0,:]) <= 1)):\n        print 'ERROR WILL OCCUR :: need pos to be (3,N)'\n\n    x=source_pos[0,:] ; y=source_pos[1,:] ; z=source_pos[2,:]\n    if(checklen(xrange)<=1): xrange=[np.min(x),np.max(x)];\n    if(checklen(yrange)<=1): yrange=[np.min(y),np.max(y)];\n    xr=xrange; yr=yrange;\n    if(checklen(zrange)<=1):\n        zrr=np.sqrt((xr[1]-xr[0])**2.+(yr[1]-yr[0])**2.)/np.sqrt(2.);\n        zmin=np.median(z)-zrr; zmax=np.median(z)+zrr;\n        if (np.min(z) > zmin): zmin=np.min(z);\n        zrange=[zmin,zmax]; print 'z_range (calc) == ',zrange\n    zr=zrange;\n    x00=0.5*(xr[1]+xr[0]); y00=0.5*(yr[1]+yr[0]); z00=0.5*(zr[1]+zr[0]); \n    tolfac = 1.0e10;\n    if (TRIM_PARTICLES==1):\n        tolfac = 0.05; \n        #tolfac = -0.01;\n        ## trim down the incoming list to only whats in the range plotted \n        ##   (saves a ton of time and memory overflow crashes)\n\n    dx=(0.5+tolfac)*(xr[1]-xr[0]); dy=(0.5+tolfac)*(yr[1]-yr[0]); dz=(0.5+tolfac)*(zr[1]-zr[0]);\n    ok_sources=ok_scan(x-x00,xmax=dx) & ok_scan(y-y00,xmax=dy) & ok_scan(z-z00,xmax=dz);\n    x=gas_pos[0,:] ; y=gas_pos[1,:] ; z=gas_pos[2,:]\n    gw=gas_rho ; gh=gas_hsml ; gz=gas_metallicity ; gm=gas_mass\n    ok_gas=ok_scan(x-x00,xmax=dx) & ok_scan(y-y00,xmax=dy) & ok_scan(z-z00,xmax=dz) & \\\n        ok_scan(gw,pos=1) & ok_scan(gh,pos=1) & ok_scan(gz,pos=1) & ok_scan(gm,pos=1,xmax=1.0e40);\n\n    Ngas = checklen(gas_mass[ok_gas]);\n    Nstars = checklen(source_pos[0,ok_sources]);\n    if (Nstars<=1) or (Ngas<=1):\n        print ' UH-OH: EXPECT ERROR NOW, there are no valid source/gas particles to send!'\n        print 'Ngas=',Ngas,'Nstars=',Nstars,'dx=',dx,'dy=',dy,'dz=',dz,'x00=',x00,'y00=',y00,'z00=',z00\n        return -1,-1,-1;\n\n    dzmax=np.max(gas_pos[2,ok_gas])-z00; \n    if(dzmax<OUTER_RANGE_OF_INT): OUTER_RANGE_OF_INT=dzmax;\n    print 'PASSING: N_gas=',Ngas,'N_sources=',Nstars,'MaxDist=',OUTER_RANGE_OF_INT,'MinCell=',MIN_CELL_SIZE;\n    Nbh=0; theta=1.0e-4; phi=1.0e-4;\n  \n    ## load the routine we need\n    exec_call=util.return_python_routines_cdir()+'/LOS_column_singlePOV/getnh.so'\n    NH_routine=ctypes.cdll[exec_call];\n    ## cast the variables to store the results\n    nh_out_cast=ctypes.c_float*Nstars; \n    los_NH_out=nh_out_cast(); los_NH_hot_out=nh_out_cast(); los_Z_out=nh_out_cast();\n\n    ## ok this is a bit arcane but the routine will read appropriately this block order\n    Coord = np.zeros((Ngas+Nstars,10),dtype='f');\n    Coord[0:Ngas,0] = gas_pos[0,ok_gas]-x00;\n    Coord[0:Ngas,1] = gas_pos[1,ok_gas]-y00;\n    Coord[0:Ngas,2] = gas_pos[2,ok_gas]-z00;\n    Coord[0:Ngas,3] = gas_u[ok_gas]\n    Coord[0:Ngas,4] = gas_rho[ok_gas]\n    Coord[0:Ngas,5] = gas_hsml[ok_gas]\n    Coord[0:Ngas,6] = gas_numh[ok_gas]\n    Coord[0:Ngas,7] = gas_nume[ok_gas]\n    Coord[0:Ngas,8] = gas_metallicity[ok_gas]\n    Coord[0:Ngas,9] = gas_mass[ok_gas]\n    Coord[Ngas:Nstars+Ngas,0] = source_pos[0,ok_sources]-x00;\n    Coord[Ngas:Nstars+Ngas,1] = source_pos[1,ok_sources]-y00;\n    Coord[Ngas:Nstars+Ngas,2] = source_pos[2,ok_sources]-z00;\n    Coord=np.copy(np.transpose(Coord));\n\n    ## main call to the NH-calculation routine\n    NH_routine.getnh( ctypes.c_int(Ngas), ctypes.c_int(Nstars), ctypes.c_int(Nbh), \\\n        ctypes.c_float(theta), ctypes.c_float(phi), \\\n        vfloat(Coord), \\\n        ctypes.byref(los_NH_out),  ctypes.byref(los_NH_hot_out),  ctypes.byref(los_Z_out), \\\n        ctypes.c_float(OUTER_RANGE_OF_INT), ctypes.c_float(MIN_CELL_SIZE) );\n    ## now put the output arrays into a useful format \n    print type(los_NH_out), los_NH_out\n    los_NH = np.ctypeslib.as_array(np.copy(los_NH_out));\n    los_NH_hot = np.ctypeslib.as_array(np.copy(los_NH_hot_out));\n    los_Z = np.ctypeslib.as_array(np.copy(los_Z_out));\n\n    # trap for really low NH value and zero metallicity (make it small instead)\n    low_NH = 1.0e10;\n    los_NH[los_NH<low_NH]=low_NH; los_NH_hot[los_NH_hot<low_NH]=low_NH;\n    los_Z[los_Z<=1.0e-5]=1.0e-5;\n\n    ## assign strong attenuation to all 'off-grid' sources, then fill in calc. vals\n    Nstarstot=checklen(source_pos[0,:]);\n    los_NH_allgas=np.zeros(Nstarstot,dtype='f')+1.0e23;\n    los_NH_hotgas=np.zeros(Nstarstot,dtype='f')+1.0e23;\n    los_gas_metallicity=np.zeros(Nstarstot,dtype='f')+0.02;\n    nok=checklen(los_NH_allgas[ok_sources])\n    los_NH_allgas[ok_sources]=fcor(los_NH[0:Nstars]);\n    los_NH_hotgas[ok_sources]=fcor(los_NH_hot[0:Nstars]);\n    los_gas_metallicity[ok_sources]=fcor(los_Z[0:Nstars]);\n\n    return los_NH_allgas, los_NH_hotgas, los_gas_metallicity;\n", "meta": {"hexsha": "dc00988c3740f9d9084eb044cf9cdc2d85cb5c64", "size": 8229, "ext": "py", "lang": "Python", "max_stars_repo_path": "paul_analysis/Python/visualization/return_columns_to_sources.py", "max_stars_repo_name": "lzkelley/arepo-mbh-sims_analysis", "max_stars_repo_head_hexsha": "f14519552cedd39a040b53e6d7cc538b5b8f38a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paul_analysis/Python/visualization/return_columns_to_sources.py", "max_issues_repo_name": "lzkelley/arepo-mbh-sims_analysis", "max_issues_repo_head_hexsha": "f14519552cedd39a040b53e6d7cc538b5b8f38a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paul_analysis/Python/visualization/return_columns_to_sources.py", "max_forks_repo_name": "lzkelley/arepo-mbh-sims_analysis", "max_forks_repo_head_hexsha": "f14519552cedd39a040b53e6d7cc538b5b8f38a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7536231884, "max_line_length": 111, "alphanum_fraction": 0.6119820148, "include": true, "reason": "import numpy", "num_tokens": 2890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.1848326358982131}}
{"text": "\"\"\"Module for solving different master equations.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport numpy as np\nimport scipy as sp\nimport scipy.sparse.linalg\nimport copy\n\nfrom qmeq.mytypes import doublenp\nfrom qmeq.mytypes import complexnp\n\nfrom qmeq import Builder\nfrom qmeq import Approach\nfrom qmeq import StateIndexingDM\nfrom qmeq import StateIndexingDMc\nfrom qmeq import QuantumDot\nfrom qmeq import LeadsTunneling\nfrom qmeq import FunctionProperties\nfrom .baths import PhononBaths\n\n#-----------------------------------------------------------\n# Python modules\n\nfrom .approach.pauli import Approach_pyPauli\nfrom .approach.lindblad import Approach_pyLindblad\nfrom .approach.neumann1 import Approach_py1vN\nfrom .approach.redfield import Approach_pyRedfield\nfrom qmeq.approach.neumann2 import Approach_py2vN\n\n# Cython compiled modules\n\nfrom .approach.c_pauli import Approach_Pauli\nfrom .approach.c_lindblad import Approach_Lindblad\nfrom .approach.c_redfield import Approach_Redfield\nfrom .approach.c_neumann1 import Approach_1vN\nfrom qmeq.approach.c_neumann2 import Approach_2vN\n#-----------------------------------------------------------\n\ndef check_parameters(indexing, symmetry, itype, kerntype):\n    if indexing is 'n':\n        if symmetry is 'spin' and kerntype not in {'py2vN', '2vN'}:\n            indexing = 'ssq'\n        else:\n            indexing = 'charge'\n\n    if not indexing in {'Lin', 'charge', 'sz', 'ssq'}:\n        print(\"WARNING: Allowed indexing values are: \\'Lin\\', \\'charge\\', \\'sz\\', \\'ssq\\'. \"+\n              \"Using default indexing=\\'charge\\'.\")\n        indexing = 'charge'\n\n    if not itype in {0,1,2,3}:\n        print(\"WARNING: itype needs to be 0, 1, 2, or 3. Using default itype=0.\")\n        itype = 0\n\n    if isinstance(kerntype, str):\n        if not kerntype in {'Pauli', 'Lindblad', 'Redfield', '1vN', '2vN',\n                            'pyPauli', 'pyLindblad', 'pyRedfield', 'py1vN', 'py2vN'}:\n            print(\"WARNING: Allowed kerntype values are: \"+\n                  \"\\'Pauli\\', \\'Lindblad\\', \\'Redfield\\', \\'1vN\\', \\'2vN\\', \"+\n                  \"\\'pyPauli\\', \\'pyLindblad\\', \\'pyRedfield\\', \\'py1vN\\', \\'py2vN\\'. \"+\n                  \"Using default kerntype=\\'Pauli\\'.\")\n            kerntype = 'Pauli'\n\n    if not indexing in {'Lin', 'charge'} and kerntype in {'py2vN', '2vN'}:\n        print(\"WARNING: For 2vN approach indexing needs to be \\'Lin\\' or \\'charge\\'. \"+\n              \"Using indexing=\\'charge\\' as a default.\")\n        indexing = 'charge'\n\n    return indexing, itype, kerntype\n\n# Inherit from qmeq.Builder\nclass Builder_elph(Builder):\n\n    def __init__(self, nsingle=0, hsingle={}, coulomb={},\n                       nleads=0, tleads={}, mulst={}, tlst={}, dband={},\n                       nbaths=0, velph={}, tlst_ph={}, dband_ph={},\n                       indexing='n', kpnt=None,\n                       kerntype='Pauli', symq=True, norm_row=0, solmethod='n',\n                       itype=0, itype_ph=0, dqawc_limit=10000,\n                       mfreeq=False, phi0_init=None,\n                       mtype_qd=complex, mtype_leads=complex,\n                       symmetry='n', herm_hs=True, herm_c=False, m_less_n=True,\n                       bath_func=None, eps_elph=1.0e-6):\n        '''\n        `nbaths', `velph', `tlst_ph', `dband_ph''\n        are new parameters for Electron-Phonon coupling\n        '''\n\n        indexing, itype, kerntype = check_parameters(indexing, symmetry,\n                                                     itype, kerntype)\n\n        if not itype_ph in {0,2}:\n            print(\"WARNING: itype needs to be 0, or 2. Using default itype=0.\")\n            itype_ph = 0\n\n        if isinstance(kerntype, str):\n            self.Approach = globals()['Approach_'+kerntype]\n        elif issubclass(kerntype, Approach):\n            self.Approach = kerntype\n            kerntype = self.Approach.kerntype\n\n        # Make copies of initialized parameters.\n        hsingle = copy.deepcopy(hsingle)\n        coulomb = copy.deepcopy(coulomb)\n        tleads = copy.deepcopy(tleads)\n        mulst = copy.deepcopy(mulst)\n        tlst = copy.deepcopy(tlst)\n        dband = copy.deepcopy(dband)\n        phi0_init = copy.deepcopy(phi0_init)\n        #\n        velph = copy.deepcopy(velph)\n        tlst_ph = copy.deepcopy(tlst_ph)\n        dband_ph = copy.deepcopy(dband_ph)\n\n        self.funcp = FunctionProperties(symq=symq, norm_row=norm_row, solmethod=solmethod,\n                                        itype=itype, dqawc_limit=dqawc_limit,\n                                        mfreeq=mfreeq, phi0_init=phi0_init,\n                                        mtype_qd=mtype_qd, mtype_leads=mtype_leads,\n                                        kpnt=kpnt, dband=dband)\n        self.funcp.itype_ph = itype_ph\n        self.funcp.eps_elph = eps_elph\n\n        icn = self.Approach.indexing_class_name\n        self.si = globals()[icn](nsingle, indexing, symmetry)\n        self.qd = QuantumDot(hsingle, coulomb, self.si, herm_hs, herm_c, m_less_n, mtype_qd)\n        self.leads = LeadsTunneling(nleads, tleads, self.si, mulst, tlst, dband, mtype_leads)\n        self.baths = PhononBaths(nbaths, velph, self.si, tlst_ph, dband_ph)\n        self.baths.bath_func = bath_func\n\n        self.appr = self.Approach(self)\n        self.create_si_elph()\n\n    def create_si_elph(self):\n        si = self.si\n        si_elph = StateIndexingDMc(si.nsingle, si.indexing,\n                                   si.symmetry, si.nleads)\n        si_elph.nbaths = si.nbaths\n        self.si_elph = si_elph\n        self.appr.si_elph = si_elph\n\n    def remove_states(self, dE):\n        Builder.remove_states(self, dE)\n        self.si_elph.set_statesdm(si.statesdm)\n\n    # kerntype\n    def get_kerntype(self):\n        return self.appr.kerntype\n    def set_kerntype(self, value):\n        if isinstance(value, str):\n            if self.appr.kerntype != value:\n                self.Approach = globals()['Approach_'+value]\n                self.change_si()\n                self.appr = self.Approach(self)\n                self.create_si_elph()\n        else:\n            if issubclass(value, Approach):\n                self.Approach = value\n                self.change_si()\n                self.appr = self.Approach(self)\n                self.create_si_elph()\n    kerntype = property(get_kerntype, set_kerntype)\n", "meta": {"hexsha": "eeeb8cdaff05822807f5d5a62b9a170d84e5d330", "size": 6385, "ext": "py", "lang": "Python", "max_stars_repo_path": "qmeq_elph/builder.py", "max_stars_repo_name": "gedaskir/qmeq_elph", "max_stars_repo_head_hexsha": "8330d8df32b92f928b33c8cfaa3a309655b34f02", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-10T17:46:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-10T17:46:35.000Z", "max_issues_repo_path": "qmeq_elph/builder.py", "max_issues_repo_name": "gedaskir/qmeq_elph", "max_issues_repo_head_hexsha": "8330d8df32b92f928b33c8cfaa3a309655b34f02", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qmeq_elph/builder.py", "max_forks_repo_name": "gedaskir/qmeq_elph", "max_forks_repo_head_hexsha": "8330d8df32b92f928b33c8cfaa3a309655b34f02", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9329268293, "max_line_length": 93, "alphanum_fraction": 0.5907595928, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.18476641024988413}}
{"text": "\"\"\"\nThe ``block`` class represents a block of material in a simulation. Blocks are not meant to be\ninteracted with directly -- when using the ``problem`` class to set up a simulation, blocks are\nautomatically added or deleted as needed using the provided interfaces. This documentation\nis provided for completeness, but should not need to be used in regular use of the code.\n\nThe class contains information on the number of grid points in the block, the location of the block\nwithin the simulation, the material properties using the ``material`` class, the types of boundary\nconditions at the block edges, and any complex geometries specified through the ``surface``\nand ``curve`` classes.\n\"\"\"\n\nfrom __future__ import division, print_function\nfrom os.path import join\nfrom .surface import surface, curve\nfrom .material import material\n\nimport numpy as np\n\nclass block(object):\n    '''\n    Class representing a block in a simulation\n\n    A block contains the following internal variables:\n\n    :ivar ndim: Number of dimensions (2 or 3)\n    :type ndim: int\n    :ivar mode: Rupture mode (2 or 3, relevant only for 2D problems)\n    :type mode: int\n    :ivar nx: Number of grid points (tuple of 3 positive integers)\n    :type nx: tuple\n    :ivar xm: Coordinates of lower left corner in simulation (tuple of 3 nonnegative integers)\n    :type xm: tuple\n    :ivar coords: Location of block within simulation domain (tuple of 3 nonnegative integers)\n    :type coords: tuple\n    :ivar lx: Block length in each spatial dimension (tuple of 3 positive floats, can be overridden\n                by setting a curve or surface to one of the edges)\n    :type lx: tuple\n    :param m: Material properties (see ``material`` class)\n    :type m: material\n    :param bounds: List of boundary conditions. Position indicates boundary location (0 = left,\n                             1 = right, 2 = front, 3 = back, 4 = bottom, 5 = top). Possible strings for\n                             boundary condition include ``'absorbing'`` (no incoming wave), ``'free'``\n                             (traction free surface), ``'rigid'`` (no displacement), or ``'none'`` (boundary\n                             conditions determined by interface conditions)\n    :type bounds: list\n    :param surfs: List of bounding surfaces. Position indicates boundary location (0 = left,\n                             1 = right, 2 = front, 3 = back, 4 = bottom, 5 = top). For 2D problems,\n                             you can only populate the list with curves, and 3D problems require\n                             surfaces. If the default rectangular surface is to be used, use ``None``\n                             for a particular surface.\n    :type surfs: list\n    '''\n    def __init__(self, ndim, mode, nx, mat):\n        '''\n        Initialize a new ``block`` instance\n\n        Creates a new block instance with the given dimensionality, rupture mode, number of\n        grid points, and material type. If the problem is 2d, the number of z grid points will\n        be automatically set to one. By default, the block length is unity in each direction,\n        the lower left coordinate is ``(0., 0., 0.)``,  all boundary conditions are set to ``'none'``,\n        material properties take on their default values, and there are no irregular edge shapes.\n        All of these default properties can be modified using the provided interfaces.\n        \n        :param ndim: Number of spatial dimensions (must be 2 or 3)\n        :type ndim: int\n        :param mode: Slip mode (2 or 3, only relevant if the problem is in 2D)\n        :type mode: int\n        :param nx: Tuple of length 3 with number of grid points ``(nx, ny, nz)``\n        :type nx: tuple or list        \n        :param mat: Block material type (string, must be ``'elastic'`` or ``'plastic'``). The\n                            method initializes a default set of material properties based on this type.\n        :type mat: str\n        :returns: New block instance\n        :rtype: block\n        '''\n        assert(ndim == 2 or ndim == 3), \"ndim must be 2 or 3\"\n        assert(mode == 2 or mode == 3), \"mode must be 2 or 3\"\n        assert len(nx) == 3, \"nx must be a list or tuple of positive integers\"\n        assert (nx[0] > 0 and nx[1] > 0 and nx[2] >0),  \"nx must be a list or tuple of positive integers\"\n        assert (mat == \"elastic\" or mat == \"plastic\"), \"material type must be elastic or plastic\"\n        self.ndim = int(ndim)\n        self.mode = int(mode)\n        self.coords = (0, 0, 0)\n        if (self.ndim == 2):\n            self.nx = (int(nx[0]), int(nx[1]), 1)\n        else:\n            self.nx = (int(nx[0]), int(nx[1]), int(nx[2]))\n        self.xm = (0., 0., 0.)\n        self.lx = (1., 1., 1.)\n        if (self.ndim == 2):\n            self.lx = (1., 1., 0.)\n        self.m = material(mat)\n        self.bounds = 2*self.ndim*[\"none\"]\n        self.surfs = 2*self.ndim*[None]\n\n    def get_mode(self):\n        \"\"\"\n        Returns rupture mode (2 or 3), only valid for 2D problems (stored at domain level)\n\n        :returns: Rupture mode\n        :rtype: int\n        \"\"\"\n        return self.mode\n\n    def set_mode(self,mode):\n        \"\"\"\n        Sets rupture mode\n\n        Rupture mode is only valid for 2D problems, and is either 2 or 3 (other values will\n        cause an error, and non-integer values will be converted to integers). For 3D problems,\n        entering a different value of the rupture mode will alter the rupture mode cosmetically\n        but will have no effect on the simulation.\n\n        :param mode: New value of rupture mode\n        :type mode: int\n        :returns: None\n        \"\"\"\n        assert(mode == 2 or mode == 3), \"Rupture mode must be 2 or 3\"\n        self.mode = int(mode)\n\n    def get_ndim(self):\n        \"\"\"\n        Returns Number of spatial dimensions\n\n        :returns: Number of spatial dimensions\n        :rtype: int\n        \"\"\"\n        return self.ndim\n\n    def set_ndim(self,ndim):\n        \"\"\"\n        Sets number of dimensions\n\n        The new number of spatial dimensions must be an integer, either 2 or 3. If a different\n        value is given, the code will raise an error. If a non-integer value is given that is acceptable,\n        the code will convert it to an integer.\n\n        **Note:** Converting a 3D problem into a 2D problem will automatically collapse the\n        number of grid points and the number of blocks in the $z$ direction to be 1. Any\n        modifications to these quantities that were done previously will be lost.\n        \n        :param ndim: New value for ndim (must be 2 or 3)\n        :type ndim: int\n        :returns: None\n        \"\"\"\n        assert(ndim == 2 or ndim == 3), \"Number of dimensions must be 2 or 3\"\n        self.ndim = int(ndim)\n        if self.ndim == 2:\n            self.nx = (self.nx[0], self.nx[1], 1)\n            self.xm = (self.xm[0], self.xm[1], 0.)\n            self.lx = (self.lx[0], self.lx[1], 0.)\n            self.bounds = self.bounds[0:4]\n            self.surfs = self.surfs[0:4]\n        else:\n            if len(self.bounds) == 4:\n                self.bounds += 2*[\"none\"]\n            if len(self.surfs) == 4:\n                self.surfs += 2*[None]\n\n    def get_nx(self):\n        \"\"\"\n        Returns number of grid points in (nx, ny, nz) format for the given block\n\n        :returns: Number of grid points (tuple of three integers)\n        :rtype: tuple\n        \"\"\"\n        return self.nx\n\n    def set_nx(self,nx):\n        \"\"\"\n        Sets number of grid points\n\n        Changes the number of grid points to the specified tuple/list of 3 nonnegative integers.\n        Bad values of ``nx`` will raise an error.\n\n        :param nx: New value of number of grid points (tuple of 3 positive integers)\n        :type nx: tuple or list\n        :returns: None\n        \"\"\"\n        assert len(nx) == 3, \"nx must be a list or tuple of length 3 of positive integers\"\n        for i in range(3):\n            assert nx[i] >= 0, \"nx must be a list or tuple of length 3 of positive integers\"\n        if (self.ndim == 2):\n            self.nx = (int(nx[0]), int(nx[1]), 1)\n        else:\n            self.nx = (int(nx[0]), int(nx[1]), int(nx[2]))\n\n    def get_xm(self):\n        \"\"\"\n        Returns starting index (zero-indexed) of block (tuple of 3 integers)\n\n        :returns: Coordinates of lower left corner (tuple of 3 integers)\n        :rtype: tuple\n        \"\"\"\n        return self.xm\n\n    def set_xm(self,xm):\n        \"\"\"\n        Sets block lower left coordinate\n\n        Changes lower left coordinate of a block to the provided tuple/list of integers.\n\n        :param xm: New value of lower left coordinate (list/tuple of integers)\n        :type xm: tuple or list\n        :returns: None\n        \"\"\"\n        assert len(xm) == 3 or (self.ndim == 2 and len(xm) == 2), \"xm must be a list or tuple of length 3 of floats\"\n\n        if self.ndim == 2:\n            self.xm = (float(xm[0]), float(xm[1]), 0.)\n        else:\n            self.xm = (float(xm[0]), float(xm[1]), float(xm[2]))\n\n    def get_lx(self):\n        \"\"\"\n        Returns block lengths as (lx, ly, lz) tuple\n\n        :returns: Block dimensions (tuple of 3 floats) in x, y, and z dimensions\n        :rtype: tuple\n        \"\"\"\n        return self.lx\n\n    def set_lx(self,lx):\n        \"\"\"\n        Sets block lengths\n\n        Changes block length to ``lx`` (tuple of 2 (2D only) or 3 floats) where the block length\n        in each dimension is given by ``(lx, ly, lz)``\n\n        :param lx: New value of block lengths (tuple of 2 (2D) or 3 floats)\n        :type lx: tuple or list\n        :returns: None\n        \"\"\"\n        assert (len(lx) == 3 or (len(lx) == 2 and self.ndim == 2)), \"lx must be a list or tuple of length 3 of positive floats\"\n        for l in lx:\n            assert l >= 0., \"lx must be a list or tuple of length 3 of positive floats\"\n        if self.ndim == 3:\n            self.lx = (float(lx[0]), float(lx[1]), float(lx[2]))\n        else:\n            self.lx = (float(lx[0]), float(lx[1]), 0.)\n\n    def get_coords(self):\n        \"\"\"\n       Returns block coordinates (tuple of integer indices in each coordinate direction)\n\n       :returns: Block coordinates (tuple of 3 integers)\n       :rtype: tuple\n       \"\"\"\n        return self.coords\n\n    def set_coords(self,coords):\n        \"\"\"\n        Sets block coordinates to a new value\n\n        Set block coordinates to ``coords``, and tuple of nonnegative integers denoting the location\n        of the block in the domain.\n\n        :param coords: New coordaintes (tuple or list of nonnegative integers)\n        :type coords: tuple or list\n        :returns: None\n        \"\"\"\n        assert len(coords) == 3, \"coords must be a list or tuple of length 3 of nonnegative integers\"\n        for i in range(3):\n            assert coords[i] >= 0, \"coords must be a list or tuple of length 3 of floats\"\n        self.coords = (int(coords[0]), int(coords[1]), int(coords[2]))\n        if self.ndim == 2:\n            self.coords = (int(coords[0]), int(coords[1]), 0)\n\n    def get_bounds(self, loc = None):\n        \"\"\"\n        Returns boundary types\n        \n        If ``loc`` (int) is provided, the method returns a specific location (str). Otherwise it returns a list\n        of all boundaries, which will have length 4 for 2D problems and length 6 for 3D problems.\n        ``loc`` serves effectively as an index into the list, and the indices correspond to the following:\n        0 = left, 1 = right, 2 = front, 3 = back, 4 = bottom, 5 = top. Note that the location must be\n        0 <= loc < 2*ndim\n\n        :param loc: Location of boundary that is desired (optional). If ``loc`` is not provided, returns\n                           a list\n        :type loc: int or None\n        :returns: Boundary type (if ``loc`` provided, returns a string of the boundary type for the\n                      desired location, of not returns a list of strings indicating all boundary types)\n        :rtype: str or list\n        \"\"\"\n        if loc is None:\n            return self.bounds\n        elif loc >= 0 and loc < 2*self.ndim:\n            return self.bounds[loc]\n        else:\n            raise TypeError(\"loc must be None or an integer location\")\n\n    def set_bounds(self, bounds, loc = None):\n        \"\"\"\n        Sets boundary types\n\n        Changes the type of boundary conditions on a block. Acceptable values are 'absorbing'\n        (incoming wave amplitude set to zero), 'free' (no traction on boundary), 'rigid' (no displacement\n        of boundary), or 'none' (boundary conditions set by imposing interface conditions).\n        \n        There are two ways to use ``set_bounds``:\n        \n        1. Set ``loc`` to be ``None`` (default) and provide a list of strings specifying boundary\n           type for ``bounds``. The length of ``bounds`` is 4 for a 2D simulation and 6 for 3D.\n           \n        2. Set ``loc`` to be an integer denoting location and give ``bounds`` as a single string. \n           The possible locations correspond to the following: 0 = left, 1 = right, 2 = front, 3 = back,\n           4 = bottom, 5 = top. 4 and 5 are only applicable to 3D simulations (0 <= loc < 2*ndim).\n\n        :param bounds: New boundary condition type (string or list of strings)\n        :type bounds: str or list\n        :param loc: If provided, only change one type of boundary condition rather than all (optional,\n                           loc serves as an index into the list if used)\n        :type loc: int or None\n        :returns: None\n        \"\"\"\n        if loc is None:\n            assert len(bounds) == 2*self.ndim, \"Must give 2*ndim boundary types\"\n            for i in range(2*self.ndim):\n                assert (bounds[i] == \"none\") or (bounds[i] == \"absorbing\") or (bounds[i] == \"free\") or (bounds[i] == \"rigid\"), \"Boundary types must be none, absorbing, free, or rigid\"\n            self.bounds = bounds\n        elif loc >=0 and loc < 2*self.ndim:\n            assert (bounds == \"none\") or (bounds == \"absorbing\") or (bounds == \"free\") or (bounds == \"rigid\"), \"Boundary types must be none, absorbing, free, or rigid\"\n            self.bounds[loc] = bounds\n        else:\n            raise TypeError(\"loc must either be None or an integer location\")\n\n    def get_surf(self, loc):\n        \"\"\"\n        Returns block boundary surface for a block edge\n\n        Returns the surface assigned to a specific edge. ``loc`` determines the edge that is\n        returned (integer, corresponding to an index). Location indices correspond to the\n        following: 0 = left, 1 = right, 2 = front, 3 = back, 4 = bottom, 5 = top\n        Note that the location must be 0 <= loc < 2*ndim (for 2D problems, ``loc`` cannot be 5 or 6).\n\n        Returns either a curve (2D problems) or surface (3D problems) or None\n\n        If ``loc`` indices are out of bounds, the code will raise an error.\n\n        :param loc: Location of desired boundary (0 = left, 1 = right, 2 = front, 3 = back,\n                          4 = bottom, 5 = top). For 2D problems, ``loc`` must be between 0 and 3.\n        :type loc: int\n        :returns: curve or surface corresponding to the selected location. If the\n                      desired edge does not have a bounding surface, returns None.\n        :rtype: curve or surface or None\n        \"\"\"\n        assert type(loc) is int and (loc >= 0 and loc < 2*self.ndim), \"location out of range\"\n        return self.surfs[loc]\n\n    def set_surf(self, loc, surf):\n        \"\"\"\n        Sets boundary surface for a particular block edge\n\n        Changes the bounding surface of a particular block edge. Location is determined\n        by ``loc`` which is an integer that indexes into a list. Locations correspond to the\n        following: 0 = left, 1 = right, 2 = front, 3 = back, 4 = bottom, 5 = top. Note that the\n        location must be 0 <= loc < 2*ndim\n\n        For 2D problems, ``surf`` must be a curve. For 3D problems, ``surf`` must be a surface.\n        Other choices will raise an error. If ``loc`` is out of bounds, the code\n        will also signal an error.\n\n        :param loc: Location of desired boundary (0 = left, 1 = right, 2 = front, 3 = back,\n                          4 = bottom, 5 = top). For 2D problems, ``loc`` must be between 0 and 3.\n        :type loc: int\n        :param surf: curve or surface corresponding to the selected block and location\n        :type surf: curve or surface\n        :returns: None\n        \"\"\"\n        assert type(loc) is int and (loc >= 0 and loc < 2*self.ndim), \"location out of range\"\n        if self.ndim == 3:\n            assert type(surf) is surface\n            if loc == 0 or loc == 1:\n                assert surf.get_direction() == 'x', \"surface direction does not match location\"\n                assert surf.get_n1() == self.nx[1] and surf.get_n2() == self.nx[2], \"number of grid points does not match\"\n            elif loc == 2 or loc == 3:\n                assert surf.get_direction() == 'y', \"surface direction does not match location\"\n                assert surf.get_n1() == self.nx[0] and surf.get_n2() == self.nx[2], \"number of grid points does not match\"\n            else:\n                assert surf.get_direction() == 'z', \"surface direction does not match location\"\n                assert surf.get_n1() == self.nx[0] and surf.get_n2() == self.nx[1], \"number of grid points does not match\"\n        else:\n            assert type(surf) is curve\n            if loc == 0 or loc == 1:\n                assert surf.get_direction() == 'x', \"surface direction does not match location\"\n                assert surf.get_n1() == self.nx[1], \"number of grid points does not match\"\n            else:\n                assert surf.get_direction() == 'y', \"surface direction does not match location\"\n                assert surf.get_n1() == self.nx[0], \"number of grid points does not match\"\n        self.surfs[loc] = surf\n\n    def delete_surf(self, loc):\n        \"\"\"\n        Removes boundary surface for a particular block edge\n\n        Removes the bounding surface of a particular block edge. Location is determined by\n        ``loc`` which is an integer that indexes into a list. Locations correspond to the following:\n        0 = left, 1 = right, 2 = front, 3 = back, 4 = bottom, 5 = top. Note that the location must be\n        0 <= loc < 2*ndim\n\n        If ``loc`` is out of bounds, the code will also signal an error.\n\n        :param loc: Location of desired boundary to be removed (0 = left, 1 = right, 2 = front,\n                          3 = back, 4 = bottom, 5 = top). For 2D problems, ``loc`` must be between 0 and 3.\n        :type loc: int\n        :returns: None\n        \"\"\"\n        assert type(loc) is int and (loc >= 0 and loc < 2*self.ndim), \"location out of range\"\n        self.surfs[loc] = None\n\n    def get_material(self):\n        \"\"\"\n        Returns material\n\n        Returns the material class associated with this block\n\n        :returns: Material class with properties for this block\n        :rtype: material\n        \"\"\"\n        return self.m\n\n    def set_mattype(self, mattype):\n        \"\"\"\n        Sets block material type ('elastic' or 'plastic')\n\n        Sets the material type for the block. Options are 'elastic' for an elastic simulation\n        and 'plastic' for a plastic simulation. Anything else besides these options will cause the\n        code to raise an error.\n\n        :param mattype: New material type ('elastic' or 'plastic')\n        :type mattype: str\n        :returns: None\n        \"\"\"\n        self.m.set_type(mattype)\n\n    def set_material(self,mat):\n        \"\"\"\n        Sets block material properties\n        \n        Sets new material properties stored in an instance of the ``material`` class.\n\n        :param newmaterial: New material properties\n        :type newmaterial: material\n        :param coords: Coordinates of block to be changed (optional, omitting changes all blocks).\n                                 ``coords`` must be a tuple or list of three integers that match the coordinates\n                                 of a block.\n        :type coords: tuple or list\n        :returns: None\n        \"\"\"\n        assert type(mat) is material\n        self.m = mat\n\n    def get_x(self, coord):\n        \"\"\"\n        Returns grid value for given spatial index\n        \n        For a given problem set up, returns the location of a particular set of coordinate indices.\n        Note that since blocks are set up by setting values only on the edges, coordinates on\n        the interior are not specified *a priori* and instead determined using transfinite interpolation\n        to generate a regular grid on the block interiors. Calling ``get_x`` generates the interior grid\n        to find the coordinates of the desired point.\n\n        Within each call to ``get_x``, the grid is generated on the fly only for the relevant block\n        where the desired point is located. It is not stored. This helps reduce memory requirements\n        for large 3D problems (since the Python module does not run in parallel), but is slower.\n        Because the computational grid is regular, though, it can be done in a single step in closed\n        form.\n        \n        Returns a numpy array of length 3 holding the spatial location (x, y, z).\n\n        :param coord: Spatial coordinate where grid values are desired (tuple or list of 3 integers\n                               or 2 integers for 2D problems)\n        :type coord: tuple or list\n        :returns: (x, y, z) coordinates of spatial location\n        :rtype: ndarray\n        \"\"\"\n\n        if self.ndim == 2:\n            assert (len(coord) == 2 or len(coord) == 3), \"Coordinates must have length 2 or 3\"\n            coord = (coord[0], coord[1])\n        else:\n            assert len(coord) == 3, \"Coordinates must have length 3\"\n        for i in range(self.ndim):\n            assert (coord[i] >= 0 and coord[i] < self.nx[i]), \"Coordinate value out of range\"\n\n        # make temporary surfaces and check that edges match\n\n        tmpsurfs = self.make_tempsurfs()\n        self.checksurfs(tmpsurfs)\n\n        p = float(coord[0])/float(self.nx[0]-1)\n        q = float(coord[1])/float(self.nx[1]-1)\n        x = np.zeros(3)\n        if self.ndim == 2:\n            x[0] = ((1.-p)*tmpsurfs[0].get_x(coord[1])+p*tmpsurfs[1].get_x(coord[1])+\n                        (1.-q)*tmpsurfs[2].get_x(coord[0])+q*tmpsurfs[3].get_x(coord[0])-\n                        (1.-p)*(1.-q)*tmpsurfs[0].get_x(0)-(1.-q)*p*tmpsurfs[1].get_x(0)-\n                        q*(1.-p)*tmpsurfs[0].get_x(-1)-q*p*tmpsurfs[1].get_x(-1))\n            x[1] = ((1.-p)*tmpsurfs[0].get_y(coord[1])+p*tmpsurfs[1].get_y(coord[1])+\n                            (1.-q)*tmpsurfs[2].get_y(coord[0])+q*tmpsurfs[3].get_y(coord[0])-\n                            (1.-p)*(1.-q)*tmpsurfs[0].get_y(0)-(1.-q)*p*tmpsurfs[1].get_y(0)-\n                            q*(1.-p)*tmpsurfs[0].get_y(-1)-q*p*tmpsurfs[1].get_y(-1))\n        else:\n            r = float(coord[2])/float(self.nx[2]-1)\n            x[0] = ((1.-p)*tmpsurfs[0].get_x((coord[1], coord[2]))+p*tmpsurfs[1].get_x((coord[1], coord[2]))+\n                    (1.-q)*tmpsurfs[2].get_x((coord[0], coord[2]))+q*tmpsurfs[3].get_x((coord[0], coord[2]))+\n                    (1.-r)*tmpsurfs[4].get_x((coord[0], coord[1]))+r*tmpsurfs[5].get_x((coord[0], coord[1])))\n            x[1] = ((1.-p)*tmpsurfs[0].get_y((coord[1], coord[2]))+p*tmpsurfs[1].get_y((coord[1], coord[2]))+\n                    (1.-q)*tmpsurfs[2].get_y((coord[0], coord[2]))+q*tmpsurfs[3].get_y((coord[0], coord[2]))+\n                    (1.-r)*tmpsurfs[4].get_y((coord[0], coord[1]))+r*tmpsurfs[5].get_y((coord[0], coord[1])))\n            x[2] = ((1.-p)*tmpsurfs[0].get_z((coord[1], coord[2]))+p*tmpsurfs[1].get_z((coord[1], coord[2]))+\n                    (1.-q)*tmpsurfs[2].get_z((coord[0], coord[2]))+q*tmpsurfs[3].get_z((coord[0], coord[2]))+\n                    (1.-r)*tmpsurfs[4].get_z((coord[0], coord[1]))+r*tmpsurfs[5].get_z((coord[0], coord[1])))\n            x[0] -= ((1.-q)*(1.-p)*tmpsurfs[0].get_x((0, coord[2]))+(1.-q)*p*tmpsurfs[1].get_x((0, coord[2]))+\n                     q*(1.-p)*tmpsurfs[0].get_x((-1,coord[2]))+q*p*tmpsurfs[1].get_x((-1,coord[2]))+\n                     (1.-p)*(1.-r)*tmpsurfs[0].get_x((coord[1], 0))+p*(1.-r)*tmpsurfs[1].get_x((coord[1], 0))+\n                     (1.-q)*(1.-r)*tmpsurfs[2].get_x((coord[0], 0))+q*(1.-r)*tmpsurfs[3].get_x((coord[0], 0))+\n                     (1.-p)*r*tmpsurfs[0].get_x((coord[1], -1))+p*r*tmpsurfs[1].get_x((coord[1],-1))+\n                     (1.-q)*r*tmpsurfs[2].get_x((coord[0], -1))+q*r*tmpsurfs[3].get_x((coord[0], -1)))\n            x[1] -= ((1.-q)*(1.-p)*tmpsurfs[0].get_y((0, coord[2]))+(1.-q)*p*tmpsurfs[1].get_y((0, coord[2]))+\n                     q*(1.-p)*tmpsurfs[0].get_y((-1,coord[2]))+q*p*tmpsurfs[1].get_y((-1,coord[2]))+\n                     (1.-p)*(1.-r)*tmpsurfs[0].get_y((coord[1], 0))+p*(1.-r)*tmpsurfs[1].get_y((coord[1], 0))+\n                     (1.-q)*(1.-r)*tmpsurfs[2].get_y((coord[0], 0))+q*(1.-r)*tmpsurfs[3].get_y((coord[0], 0))+\n                     (1.-p)*r*tmpsurfs[0].get_y((coord[1], -1))+p*r*tmpsurfs[1].get_y((coord[1],-1))+\n                     (1.-q)*r*tmpsurfs[2].get_y((coord[0], -1))+q*r*tmpsurfs[3].get_y((coord[0], -1)))\n            x[2] -= ((1.-q)*(1.-p)*tmpsurfs[0].get_z((0, coord[2]))+(1.-q)*p*tmpsurfs[1].get_z((0, coord[2]))+\n                     q*(1.-p)*tmpsurfs[0].get_z((-1,coord[2]))+q*p*tmpsurfs[1].get_z((-1,coord[2]))+\n                     (1.-p)*(1.-r)*tmpsurfs[0].get_z((coord[1], 0))+p*(1.-r)*tmpsurfs[1].get_z((coord[1], 0))+\n                     (1.-q)*(1.-r)*tmpsurfs[2].get_z((coord[0], 0))+q*(1.-r)*tmpsurfs[3].get_z((coord[0], 0))+\n                     (1.-p)*r*tmpsurfs[0].get_z((coord[1], -1))+p*r*tmpsurfs[1].get_z((coord[1],-1))+\n                     (1.-q)*r*tmpsurfs[2].get_z((coord[0], -1))+q*r*tmpsurfs[3].get_z((coord[0], -1)))\n            x[0] += ((1.-p)*(1.-q)*(1.-r)*tmpsurfs[0].get_x((0,0))+p*(1.-q)*(1.-r)*tmpsurfs[1].get_x((0,0))+\n                     (1.-p)*q*(1.-r)*tmpsurfs[0].get_x((-1,0))+(1.-p)*(1.-q)*r*tmpsurfs[0].get_x((0,-1))+\n                     p*q*(1.-r)*tmpsurfs[1].get_x((-1,0))+p*(1.-q)*r*tmpsurfs[1].get_x((0,-1))+\n                     (1.-p)*q*r*tmpsurfs[0].get_x((-1,-1))+p*q*r*tmpsurfs[1].get_x((-1,-1)))\n            x[1] += ((1.-p)*(1.-q)*(1.-r)*tmpsurfs[0].get_y((0,0))+p*(1.-q)*(1.-r)*tmpsurfs[1].get_y((0,0))+\n                     (1.-p)*q*(1.-r)*tmpsurfs[0].get_y((-1,0))+(1.-p)*(1.-q)*r*tmpsurfs[0].get_y((0,-1))+\n                     p*q*(1.-r)*tmpsurfs[1].get_y((-1,0))+p*(1.-q)*r*tmpsurfs[1].get_y((0,-1))+\n                     (1.-p)*q*r*tmpsurfs[0].get_y((-1,-1))+p*q*r*tmpsurfs[1].get_y((-1,-1)))\n            x[2] += ((1.-p)*(1.-q)*(1.-r)*tmpsurfs[0].get_z((0,0))+p*(1.-q)*(1.-r)*tmpsurfs[1].get_z((0,0))+\n                     (1.-p)*q*(1.-r)*tmpsurfs[0].get_x((-1,0))+(1.-p)*(1.-q)*r*tmpsurfs[0].get_z((0,-1))+\n                     p*q*(1.-r)*tmpsurfs[1].get_z((-1,0))+p*(1.-q)*r*tmpsurfs[1].get_z((0,-1))+\n                     (1.-p)*q*r*tmpsurfs[0].get_z((-1,-1))+p*q*r*tmpsurfs[1].get_z((-1,-1)))\n\n        return np.array(x)\n\n    def make_tempsurfs(self):\n        \"\"\"\n        Create temporary surface list\n\n        This method generates all six (four in 2D) bounding surfaces (curves in 2D). Note that\n        these surfaces are not usually stored for rectangular block edges to save memory,\n        as they are trivial to create. The temporary surfaces can be used to check that the\n        edges of the surfaces/curves match or to use transfinite interpolation to generate the grid.\n\n        :returns: List of all bounding surfaces (not stored beyond the time they are needed)\n        :rtype: list\n        \"\"\"\n\n        tmpsurf = []\n\n        if self.ndim == 2:\n            for i in range(4):\n                if self.surfs[i] is None:\n                    if i == 0:\n                        tmpsurf.append(curve(self.nx[1], 'x', np.ones(self.nx[1])*self.xm[0],\n                                             np.linspace(self.xm[1], self.xm[1]+self.lx[1], self.nx[1])))\n                    elif i == 1:\n                        tmpsurf.append(curve(self.nx[1], 'x', np.ones(self.nx[1])*(self.xm[0]+self.lx[0]),\n                                             np.linspace(self.xm[1], self.xm[1]+self.lx[1], self.nx[1])))\n                    elif i == 2:\n                        tmpsurf.append(curve(self.nx[0], 'y', np.linspace(self.xm[0], self.xm[0]+self.lx[0], self.nx[0]),\n                                             np.ones(self.nx[0])*self.xm[1]))\n                    else:\n                        tmpsurf.append(curve(self.nx[0], 'y',np.linspace(self.xm[0], self.xm[0]+self.lx[0], self.nx[0]),\n                                             np.ones(self.nx[0])*(self.xm[1]+self.lx[1])))\n                else:\n                    tmpsurf.append(self.surfs[i])\n\n        else:\n            for i in range(6):\n                if self.surfs[i] is None:\n                    if i == 0:\n                        tmpsurf.append(surface(self.nx[1], self.nx[2], 'x', np.ones((self.nx[1], self.nx[2]))*self.xm[0],\n                                               np.meshgrid(np.linspace(self.xm[1], self.xm[1]+self.lx[1], self.nx[1]),np.linspace(self.xm[2], self.xm[2]+self.lx[2], self.nx[2]), indexing='ij')[0],\n                                               np.meshgrid(np.linspace(self.xm[1], self.xm[1]+self.lx[1], self.nx[1]),np.linspace(self.xm[2], self.xm[2]+self.lx[2], self.nx[2]), indexing='ij')[1]))                                               \n                    elif i == 1:\n                        tmpsurf.append(surface(self.nx[1], self.nx[2], 'x', np.ones((self.nx[1], self.nx[2]))*(self.xm[0]+self.lx[0]),\n                                               np.meshgrid(np.linspace(self.xm[1], self.xm[1]+self.lx[1], self.nx[1]),np.linspace(self.xm[2], self.xm[2]+self.lx[2], self.nx[2]), indexing='ij')[0],\n                                               np.meshgrid(np.linspace(self.xm[1], self.xm[1]+self.lx[1], self.nx[1]),np.linspace(self.xm[2], self.xm[2]+self.lx[2], self.nx[2]), indexing='ij')[1])) \n                    elif i == 2:\n                        tmpsurf.append(surface(self.nx[0], self.nx[2], 'y',\n                                               np.meshgrid(np.linspace(self.xm[0], self.xm[0]+self.lx[0], self.nx[0]),np.linspace(self.xm[2], self.xm[2]+self.lx[2], self.nx[2]), indexing='ij')[0],\n                                               np.ones((self.nx[0], self.nx[2]))*self.xm[1],\n                                               np.meshgrid(np.linspace(self.xm[0], self.xm[0]+self.lx[0], self.nx[0]),np.linspace(self.xm[2], self.xm[2]+self.lx[2], self.nx[2]), indexing='ij')[1]))\n                    elif i == 3:\n                        tmpsurf.append(surface(self.nx[0], self.nx[2], 'y',\n                                               np.meshgrid(np.linspace(self.xm[0], self.xm[0]+self.lx[0], self.nx[0]),np.linspace(self.xm[2], self.xm[2]+self.lx[2], self.nx[2]), indexing='ij')[0],\n                                               np.ones((self.nx[0], self.nx[2]))*(self.xm[1]+self.lx[1]),\n                                               np.meshgrid(np.linspace(self.xm[0], self.xm[0]+self.lx[0], self.nx[0]),np.linspace(self.xm[2], self.xm[2]+self.lx[2], self.nx[2]), indexing='ij')[1]))\n                    elif i == 4:\n                        tmpsurf.append(surface(self.nx[0], self.nx[1], 'z',\n                                               np.meshgrid(np.linspace(self.xm[0], self.xm[0]+self.lx[0], self.nx[0]),np.linspace(self.xm[1], self.xm[1]+self.lx[1], self.nx[1]), indexing='ij')[0],\n                                               np.meshgrid(np.linspace(self.xm[0], self.xm[0]+self.lx[0], self.nx[0]),np.linspace(self.xm[1], self.xm[1]+self.lx[1], self.nx[1]), indexing='ij')[1],\n                                               np.ones((self.nx[0], self.nx[1]))*self.xm[2]))                                             \n                    else:\n                        tmpsurf.append(surface(self.nx[0], self.nx[1], 'z',\n                                               np.meshgrid(np.linspace(self.xm[0], self.xm[0]+self.lx[0], self.nx[0]),np.linspace(self.xm[1], self.xm[1]+self.lx[1], self.nx[1]), indexing='ij')[0],\n                                               np.meshgrid(np.linspace(self.xm[0], self.xm[0]+self.lx[0], self.nx[0]),np.linspace(self.xm[1], self.xm[1]+self.lx[1], self.nx[1]), indexing='ij')[1],\n                                               np.ones((self.nx[0], self.nx[1]))*(self.xm[2]+self.lx[2])))\n                else:\n                    tmpsurf.append(self.surfs[i])\n            \n        return tmpsurf\n\n    def check(self):\n        \"\"\"\n        Checks for errors before writing input file\n\n        Checks that edges of bounding surfaces match. If the edges are not defined as\n        surfaces, the code temporarily creates them to check that they match.\n\n        :returns: None\n        \"\"\"\n\n        tmpsurfs = self.make_tempsurfs()\n        self.checksurfs(tmpsurfs)\n\n    def checksurfs(self, tmpsurfs):\n        \"\"\"\n        Checks that surface boundaries match\n\n        Input is a list of surfaces, with order corresponding to (left, right, front, back, top, bottom).\n        In 2D problems, there is no top or bottom surface.\n\n        :param tmpsurfs: List of surfaces to compare (lenth 4 or 6)\n        :type tmpsurfs: list\n        :returns: None\n        \"\"\"\n\n        surf1 = [0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 3, 3]\n        surf2 = [2, 3, 2, 3, 4, 5, 4, 5, 4, 5, 4, 5]\n        edge1 = [1, 3,1, 3, 0, 2, 0, 2, 0, 2, 0, 2]\n        edge2 = [1, 1, 3, 3, 1, 1, 3, 3, 0, 0, 2, 2]\n\n        for i in range(2**(self.ndim-1)*self.ndim):\n            assert tmpsurfs[surf1[i]].has_same_edge(edge1[i], edge2[i], tmpsurfs[surf2[i]]), \"surface edges do not match\"\n\n    def write_input(self, f, probname, directory, endian = '='):\n        \"\"\"\n        Writes block information to input file\n\n        Method writes information for block to file. It also writes all relevant surface data to file\n        to describe non-rectangular geometries. Inputs inlcude the file handle for the input\n        file, the problem name (used for naming surface files), the destination directory for\n        all files, and endianness (optional, default is native) for binary surface files.\n\n        :param f: file handle for input file\n        :type f: file\n        :param probname: Problem name\n        :type probname: str\n        :param directory: Directory where output should be written\n        :type directory: str\n        :param endian: Byte-ordering for binary files for surface data. Possible values are\n                                ``'<'`` (little endian), ``'>'`` (big endian), or ``'='`` (native, default)\n        :type endian: str\n        :returns: None\n        \"\"\"\n\n        if directory == \"\":\n            inputfiledir = 'problems/'\n        else:\n            inputfiledir = directory\n        \n        f.write(\"[fdfault.block\"+str(self.coords[0])+str(self.coords[1])+str(self.coords[2])+\"]\\n\")\n        self.m.write_input(f)\n        outstring = \"\"\n        for i in range(self.ndim):\n            outstring += repr(self.xm[i])+\" \"\n        outstring = outstring[0:-1]\n        f.write(outstring+\"\\n\")\n        outstring = \"\"\n        for i in range(self.ndim):\n            outstring += repr(self.lx[i])+\" \"\n        outstring = outstring[0:-1]\n        f.write(outstring+\"\\n\")\n        for btype in self.bounds:\n            f.write(btype+\"\\n\")\n        nsurfs = 0\n        for s in self.surfs:\n            if s is None:\n                f.write(\"none\\n\")\n            else:\n                f.write(join(inputfiledir, probname)+\"_block\"+str(self.coords[0])+str(self.coords[1])+str(self.coords[2])+str(nsurfs)+\".surf\\n\")\n                s.write(join(directory, probname+\"_block\"+str(self.coords[0])+str(self.coords[1])+str(self.coords[2])+str(nsurfs)+\".surf\"), endian)\n            nsurfs += 1\n        f.write(\"\\n\")\n    \n    def __str__(self):\n        '''\n        returns a string representation\n        '''\n        surfstring = ''\n        for surf in self.surfs:\n            surfstring += str(surf)+\"\\n\"\n        return (\"Block \"+str(self.coords)+\":\\nnx = \"+str(self.nx)+\"\\nxm = \"+str(self.xm)+\"\\nlx = \"+\n                str(self.lx)+\"\\nbounds = \"+str(self.bounds)+\"\\nsurfaces =\\n\"+surfstring+str(self.m))\n", "meta": {"hexsha": "055278be867a950789a070a3b0b484de610d970a", "size": 36214, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/fdfault/block.py", "max_stars_repo_name": "egdaub/fdfault", "max_stars_repo_head_hexsha": "ec066f032ba109843164429aa7d9e7352485d735", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2017-10-05T22:04:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:32:17.000Z", "max_issues_repo_path": "python/fdfault/block.py", "max_issues_repo_name": "jhsa26/fdfault", "max_issues_repo_head_hexsha": "ec066f032ba109843164429aa7d9e7352485d735", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-05-06T16:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-18T11:41:41.000Z", "max_forks_repo_path": "python/fdfault/block.py", "max_forks_repo_name": "jhsa26/fdfault", "max_forks_repo_head_hexsha": "ec066f032ba109843164429aa7d9e7352485d735", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2017-03-24T19:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-31T08:32:18.000Z", "avg_line_length": 51.0056338028, "max_line_length": 244, "alphanum_fraction": 0.551582261, "include": true, "reason": "import numpy", "num_tokens": 10120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.18476639807054682}}
{"text": "#!/usr/bin/env python\n\n\"\"\"Calculate total number of fully bound staples for a simulation set\"\"\"\n\n\nimport argparse\nimport os.path\n\nimport numpy as np\n\nfrom origamipy import biases\nfrom origamipy import conditions\nfrom origamipy import config_process\nfrom origamipy import datatypes\nfrom origamipy import files\nfrom origamipy import outputs\nfrom origamipy import decorrelate\nfrom origamipy import mbar_wrapper\n\n\ndef main():\n    args = parse_args()\n    system_file = files.JSONStructInpFile(args.system_filename)\n    domain_pairs = parse_domain_pairs(args.domain_pairs)\n\n    fileformatter = construct_fileformatter()\n    all_conditions = construct_conditions(args, fileformatter, system_file)\n    inp_filebase = create_input_filepathbase(args)\n    sim_collections = outputs.create_sim_collections(inp_filebase,\n                                                     all_conditions, args.reps)\n    for sim_collection in sim_collections:\n        for rep in sim_collection._reps:\n            ops = sim_collection.get_reps_data('ops', concatenate=False)\n            runs = len(ops[rep])\n            for run in range(runs):\n                run_filebase = sim_collection.get_filebase(run, rep)\n                trj_filename = '{}.trj'.format(run_filebase)\n                trj_file = files.TxtTrajInpFile(trj_filename, system_file)\n                ops = datatypes.OrderParams.from_file(run_filebase)\n                all_dists = [[] for i in range(len(domain_pairs))]\n                for i, step in enumerate(trj_file):\n                    config = np.array(step[0]['positions'])\n                    for j, domain_pair in enumerate(domain_pairs):\n                        pos_i = config[domain_pair[0]]\n                        pos_j = config[domain_pair[1]]\n                        all_dists[j].append(\n                            config_process.calc_dist(pos_i, pos_j))\n\n                for domain_pair, dists in zip(domain_pairs, all_dists):\n                    dist_tag = 'dist-d{}-d{}'.format(\n                        domain_pair[0], domain_pair[1])\n                    if dist_tag in ops.tags:\n                        ops[dist_tag] = dists\n                    else:\n                        ops.add_column(dist_tag, dists)\n                    adj_tag = 'adj-d{}-d{}'.format(\n                        domain_pair[0], domain_pair[1])\n                    adj_sites = np.array(dists) == 1\n                    if adj_tag in ops.tags:\n                        ops[adj_tag] = adj_sites\n                    else:\n                        ops.add_column(adj_tag, adj_sites)\n\n                dist_sum = np.sum(all_dists, axis=0)\n                tag = 'dist-sum'\n                if tag in ops.tags:\n                    ops[tag] = dist_sum\n                else:\n                    ops.add_column(tag, dist_sum)\n\n                ops.to_file(run_filebase)\n\n\ndef construct_conditions(args, fileformatter, system_file):\n    stack_biases = []\n    for stack_mult in args.stack_mults:\n        stack_bias = biases.StackingBias(args.stack_ene, stack_mult)\n        stack_biases.append(stack_bias)\n\n    conditions_map = {'temp': args.temps,\n                      'staple_m': [args.staple_m],\n                      'bias': stack_biases}\n\n    return conditions.AllSimConditions(conditions_map, fileformatter, system_file)\n\n\ndef construct_fileformatter():\n    specs = []\n    specs.append(conditions.ConditionsFileformatSpec('temp', '{}'))\n    specs.append(conditions.ConditionsFileformatSpec('bias', '{}'))\n\n    return conditions.ConditionsFileformatter(specs)\n\n\ndef create_input_filepathbase(args):\n    return '{}/{}'.format(args.input_dir, args.filebase)\n\n\ndef create_output_filepathbase(args):\n    return '{}/{}'.format(args.output_dir, args.filebase)\n\n\ndef parse_domain_pairs(domain_pair_strings):\n    domain_pairs = []\n    for domain_pair in domain_pair_strings:\n        domain_pairs.append([int(d) for d in domain_pair.split(',')])\n\n    return domain_pairs\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser(\n        description=__doc__,\n        formatter_class=argparse.RawDescriptionHelpFormatter)\n    parser.add_argument(\n        'system_filename',\n        type=str,\n        help='System file')\n    parser.add_argument(\n        'filebase',\n        type=str,\n        help='Base name for files')\n    parser.add_argument(\n        'input_dir',\n        type=str,\n        help='Directory of inputs')\n    parser.add_argument(\n        'output_dir',\n        type=str,\n        help='Directory to output to')\n    parser.add_argument(\n        'staple_m',\n        type=float,\n        help='Staple molarity (mol/V)')\n    parser.add_argument(\n        'stack_ene',\n        type=float,\n        help='Stacking energy (kb K)')\n    parser.add_argument(\n        '--reps',\n        nargs='+',\n        type=int,\n        help='Reps (leave empty for all available)')\n    parser.add_argument(\n        '--temps',\n        nargs='+',\n        type=str,\n        help='Temperatures')\n    parser.add_argument(\n        '--stack_mults',\n        nargs='+',\n        type=str,\n        help='Stacking energy multipliers')\n    parser.add_argument(\n        '--domain_pairs',\n        nargs='+',\n        type=str,\n        help='Scaffold domain pairs to calculate distances between')\n\n    return parser.parse_args()\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "6f824185d4d7236de9d7ba9f23e5088e982a2af4", "size": 5287, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/analysis/calc_2d-remc_scaffold_distances.py", "max_stars_repo_name": "acumb/LatticeDNAOrigami", "max_stars_repo_head_hexsha": "0f2522286adc9815865d4abfc55f546da40e606b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2016-04-10T21:21:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-21T15:33:07.000Z", "max_issues_repo_path": "scripts/analysis/calc_2d-remc_scaffold_distances.py", "max_issues_repo_name": "cumberworth/LatticeDNAOrigami", "max_issues_repo_head_hexsha": "71570107890e5de602cee2aacf7db9aea2907892", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-09-16T13:07:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-16T13:08:02.000Z", "max_forks_repo_path": "scripts/analysis/calc_2d-remc_scaffold_distances.py", "max_forks_repo_name": "cumberworth/LatticeDNAOrigami", "max_forks_repo_head_hexsha": "71570107890e5de602cee2aacf7db9aea2907892", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-08-19T09:49:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-19T10:10:06.000Z", "avg_line_length": 32.0424242424, "max_line_length": 82, "alphanum_fraction": 0.5946661623, "include": true, "reason": "import numpy", "num_tokens": 1101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.32423538592116924, "lm_q1q2_score": 0.18476639434947076}}
{"text": "# -*- coding: utf-8 -*-\n#\n# This file is part of QuTiP: Quantum Toolbox in Python.\n#\n#    Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.\n#    All rights reserved.\n#\n#    Redistribution and use in source and binary forms, with or without\n#    modification, are permitted provided that the following conditions are\n#    met:\n#\n#    1. Redistributions of source code must retain the above copyright notice,\n#       this list of conditions and the following disclaimer.\n#\n#    2. Redistributions in binary form must reproduce the above copyright\n#       notice, this list of conditions and the following disclaimer in the\n#       documentation and/or other materials provided with the distribution.\n#\n#    3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names\n#       of its contributors may be used to endorse or promote products derived\n#       from this software without specific prior written permission.\n#\n#    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n#    \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n#    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n#    PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n#    HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n#    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n#    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n#    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n#    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n#    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n#    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n###############################################################################\nimport numpy as np\nimport scipy.sparse as sp\nfrom qutip.cy.stochastic import (SSESolver, SMESolver, PcSSESolver, PcSMESolver,\n                                 PmSMESolver, GenericSSolver, Solvers)\nfrom qutip.qobj import Qobj, isket, isoper, issuper\nfrom qutip.states import ket2dm\nfrom qutip.solver import Result\nfrom qutip.qobjevo import QobjEvo\nfrom qutip.superoperator import (spre, spost, mat2vec, vec2mat,\n                                 liouvillian, lindblad_dissipator)\nfrom qutip.solver import Options, _solver_safety_check\nfrom qutip.parallel import serial_map\nfrom qutip.ui.progressbar import TextProgressBar\nfrom qutip.pdpsolve import main_ssepdpsolve, main_smepdpsolve\n\n__all__ = ['ssesolve', 'photocurrent_sesolve', 'smepdpsolve',\n           'smesolve', 'photocurrent_mesolve', 'ssepdpsolve',\n           'stochastic_solvers', 'general_stochastic']\n\n\ndef stochastic_solvers():\n    \"\"\"Available solvers for ssesolve and smesolve\n    euler-maruyama:\n        A simple generalization of the Euler method for ordinary\n        differential equations to stochastic differential equations.\n        Only solver which could take non-commuting sc_ops. *not tested*\n        -Order 0.5\n        -Code: 'euler-maruyama', 'euler', 0.5\n\n    milstein, Order 1.0 strong Taylor scheme:\n        Better approximate numerical solution to stochastic\n        differential equations.\n        -Order strong 1.0\n        -Code: 'milstein', 1.0\n        Numerical Solution of Stochastic Differential Equations\n        Chapter 10.3 Eq. (3.1), By Peter E. Kloeden, Eckhard Platen\n\n    milstein-imp, Order 1.0 implicit strong Taylor scheme:\n        Implicit milstein scheme for the numerical simulation of stiff\n        stochastic differential equations.\n        -Order strong 1.0\n        -Code: 'milstein-imp'\n        Numerical Solution of Stochastic Differential Equations\n        Chapter 12.2 Eq. (2.9), By Peter E. Kloeden, Eckhard Platen\n\n    predictor-corrector:\n        Generalization of the trapezoidal method to stochastic\n        differential equations. More stable than explicit methods.\n        -Order strong 0.5, weak 1.0\n        Only the stochastic part is corrected.\n            (alpha = 0, eta = 1/2)\n            -Code: 'pred-corr', 'predictor-corrector', 'pc-euler'\n        Both the deterministic and stochastic part corrected.\n            (alpha = 1/2, eta = 1/2)\n            -Code: 'pc-euler-imp', 'pc-euler-2', 'pred-corr-2'\n        Numerical Solution of Stochastic Differential Equations\n        Chapter 15.5 Eq. (5.4), By Peter E. Kloeden, Eckhard Platen\n\n    platen:\n        Explicit scheme, create the milstein using finite difference instead of\n        derivatives. Also contain some higher order terms, thus converge better\n        than milstein while staying strong order 1.0.\n        Do not require derivatives, therefore usable for\n        :func:`qutip.stochastic.general_stochastic`\n        -Order strong 1.0, weak 2.0\n        -Code: 'platen', 'platen1', 'explicit1'\n        The Theory of Open Quantum Systems\n        Chapter 7 Eq. (7.47), H.-P Breuer, F. Petruccione\n\n    rouchon:\n        Scheme keeping the positivity of the density matrix. (smesolve only)\n        -Order strong 1.0?\n        -Code: 'rouchon', 'Rouchon'\n        Eq. 4 of arXiv:1410.5345 with eta=1\n        Efficient Quantum Filtering for Quantum Feedback Control\n        Pierre Rouchon, Jason F. Ralph\n        arXiv:1410.5345 [quant-ph]\n        Phys. Rev. A 91, 012118, (2015)\n\n    taylor1.5, Order 1.5 strong Taylor scheme:\n        Solver with more terms of the Ito-Taylor expansion.\n        Default solver for smesolve and ssesolve.\n        -Order strong 1.5\n        -Code: 'taylor1.5', 'taylor15', 1.5, None\n        Numerical Solution of Stochastic Differential Equations\n        Chapter 10.4 Eq. (4.6), By Peter E. Kloeden, Eckhard Platen\n\n    taylor1.5-imp, Order 1.5 implicit strong Taylor scheme:\n        implicit Taylor 1.5 (alpha = 1/2, beta = doesn't matter)\n        -Order strong 1.5\n        -Code: 'taylor1.5-imp', 'taylor15-imp'\n        Numerical Solution of Stochastic Differential Equations\n        Chapter 12.2 Eq. (2.18), By Peter E. Kloeden, Eckhard Platen\n\n    explicit1.5, Explicit Order 1.5 Strong Schemes:\n        Reproduce the order 1.5 strong Taylor scheme using finite difference\n        instead of derivatives. Slower than taylor15 but usable by\n        :func:`qutip.stochastic.general_stochastic`\n        -Order strong 1.5\n        -Code: 'explicit1.5', 'explicit15', 'platen15'\n        Numerical Solution of Stochastic Differential Equations\n        Chapter 11.2 Eq. (2.13), By Peter E. Kloeden, Eckhard Platen\n\n    taylor2.0, Order 2 strong Taylor scheme:\n        Solver with more terms of the Stratonovich expansion.\n        -Order strong 2.0\n        -Code: 'taylor2.0', 'taylor20', 2.0\n        Numerical Solution of Stochastic Differential Equations\n        Chapter 10.5 Eq. (5.2), By Peter E. Kloeden, Eckhard Platen\n\n    ---All solvers, except taylor2.0, are usable in both smesolve and ssesolve\n    and for both heterodyne and homodyne. taylor2.0 only work for 1 stochastic\n    operator not dependent of time with the homodyne method.\n    The :func:`qutip.stochastic.general_stochastic` only accept derivatives\n    free solvers: ['euler', 'platen', 'explicit1.5'].\n\nAvailable solver for photocurrent_sesolve and photocurrent_mesolve:\n        Photocurrent use ordinary differential equations between\n        stochastic \"jump/collapse\".\n    euler:\n        Euler method for ordinary differential equations between jumps.\n        Only 1 jumps per time interval.\n        Default solver\n        -Order 1.0\n        -Code: 'euler'\n        Quantum measurement and control\n        Chapter 4, Eq 4.19, 4.40, By Howard M. Wiseman, Gerard J. Milburn\n\n    predictor–corrector:\n        predictor–corrector method (PECE) for ordinary differential equations.\n        Use poisson distribution to obtain the number of jump at each timestep.\n        -Order 2.0\n        -Code: 'pred-corr'\n\n    \"\"\"\n    pass\n\n\nclass StochasticSolverOptions:\n    \"\"\"Class of options for stochastic solvers such as\n    :func:`qutip.stochastic.ssesolve`, :func:`qutip.stochastic.smesolve`, etc.\n\n    The stochastic solvers :func:`qutip.stochastic.general_stochastic`,\n    :func:`qutip.stochastic.ssesolve`, :func:`qutip.stochastic.smesolve`,\n    :func:`qutip.stochastic.photocurrent_sesolve` and\n    :func:`qutip.stochastic.photocurrent_mesolve`\n    all take the same keyword arguments as\n    the constructor of these class, and internally they use these arguments to\n    construct an instance of this class, so it is rarely needed to explicitly\n    create an instance of this class.\n\n    Attributes\n    ----------\n\n    H : :class:`qutip.Qobj`, time-dependent Qobj as a list*\n        System Hamiltonian.\n\n    state0 : :class:`qutip.Qobj`\n        Initial state vector (ket) or density matrix.\n\n    times : *list* / *array*\n        List of times for :math:`t`. Must be uniformly spaced.\n\n    c_ops : list of :class:`qutip.Qobj`, :class:`qutip.QobjEvo` or [Qobj, coeff*]\n        List of deterministic collapse operators.\n\n    sc_ops : list of :class:`qutip.Qobj`, :class:`qutip.QobjEvo` or [Qobj, coeff*]\n        List of stochastic collapse operators. Each stochastic collapse\n        operator will give a deterministic and stochastic contribution\n        to the equation of motion according to how the d1 and d2 functions\n        are defined.\n\n    e_ops : list of :class:`qutip.Qobj`\n        Single operator or list of operators for which to evaluate\n        expectation values.\n\n    m_ops : list of :class:`qutip.Qobj`\n        List of operators representing the measurement operators. The expected\n        format is a nested list with one measurement operator for each\n        stochastic increament, for each stochastic collapse operator.\n\n    args : dict\n        Dictionary of parameters for time dependent systems.\n\n    tol : float\n        Tolerance of the solver for implicit methods.\n\n    ntraj : int\n        Number of trajectors.\n\n    nsubsteps : int\n        Number of sub steps between each time-spep given in `times`.\n\n    dW_factors : array\n        Array of length len(sc_ops), containing scaling factors for each\n        measurement operator in m_ops.\n\n    solver : string\n        Name of the solver method to use for solving the stochastic\n        equations. Valid values are:\n        order 1/2 algorithms: 'euler-maruyama', 'pc-euler', 'pc-euler-imp'\n        order 1 algorithms: 'milstein', 'platen', 'milstein-imp', 'rouchon'\n        order 3/2 algorithms: 'taylor1.5', 'taylor1.5-imp', 'explicit1.5'\n        order 2 algorithms: 'taylor2.0'\n        call help of :func:`qutip.stochastic.stochastic_solvers`\n        for a description of the solvers.\n        Implicit methods can adjust tolerance via the kw 'tol'\n        default is {'tol':1e-6}\n\n    method : string ('homodyne', 'heterodyne')\n        The name of the type of measurement process that give rise to the\n        stochastic equation to solve.\n\n    store_all_expect : bool (default False)\n        Whether or not to store the e_ops expect values for all paths.\n\n    store_measurement : bool (default False)\n        Whether or not to store the measurement results in the\n        :class:`qutip.solver.Result` instance returned by the solver.\n\n    noise : int, array[int, 1d], array[double, 4d]\n        int : seed of the noise\n        array[int, 1d], length = ntraj, seeds for each trajectories\n        array[double, 4d] (ntraj, len(times), nsubsteps, len(sc_ops)*[1|2])\n            vector for the noise, the len of the last dimensions is doubled for\n            solvers of order 1.5. The correspond to results.noise\n\n    noiseDepth : int\n        Number of terms kept of the truncated series used to create the\n        noise used by taylor2.0 solver.\n\n    normalize : bool\n        (default True for (photo)ssesolve, False for (photo)smesolve)\n        Whether or not to normalize the wave function during the evolution.\n        Normalizing density matrices introduce numerical errors.\n\n    options : :class:`qutip.solver.Options`\n        Generic solver options. Only options.average_states and\n        options.store_states are used.\n\n    map_func: function\n        A map function or managing the calls to single-trajactory solvers.\n\n    map_kwargs: dictionary\n        Optional keyword arguments to the map_func function function.\n\n    progress_bar : :class:`qutip.ui.BaseProgressBar`\n        Optional progress bar class instance.\n\n    *\n    time-dependent Qobj can be used for H, c_ops and sc_ops.\n    The format for time-dependent system hamiltonian is:\n    H = [Qobj0,[Qobj1,coeff1],[Qobj2,coeff2],...]\n      = Qobj0 + Qobj1 * coeff1(t) + Qobj2 * coeff2(t)\n\n    coeff function can be:\n        function: coeff(t, args) -> complex\n        str: \"sin(1j*w*t)\"\n        np.array[complex, 1d] of length equal to the times array\n    The argument args for the function coeff is the args keyword argument of\n        the stochastic solver.\n    Likewisem in str cases, the parameters ('w' in this case) are taken from\n        the args keywords argument.\n    *While mixing coeff type does not results in errors, it is not recommended.*\n\n    For the collapse operators (c_ops, sc_ops):\n    Each operators can only be composed of 1 Qobj.\n    c_ops = [c_op1, c_op2, ...]\n    where, c_opN = Qobj or [Qobj,coeff]\n    The coeff format is the same as for the Hamiltonian.\n    \"\"\"\n    def __init__(self, me, H=None, c_ops=[], sc_ops=[], state0=None,\n                 e_ops=[], m_ops=None, store_all_expect=False,\n                 store_measurement=False, dW_factors=None,\n                 solver=None, method=\"homodyne\", normalize=None,\n                 times=None, nsubsteps=1, ntraj=1, tol=None,\n                 generate_noise=None, noise=None,\n                 progress_bar=None, map_func=None, map_kwargs=None,\n                 args={}, options=None, noiseDepth=20):\n\n        if options is None:\n            options = Options()\n\n        if progress_bar is None:\n            progress_bar = TextProgressBar()\n\n        # System\n        # Cast to QobjEvo so the code has only one version for both the\n        # constant and time-dependent case.\n        self.me = me\n\n        if H is not None:\n            msg = \"The Hamiltonian format is not valid. \"\n            try:\n                self.H = QobjEvo(H, args=args, tlist=times)\n            except Exception as e:\n                raise ValueError(msg + str(e)) from e\n            except:\n                raise ValueError(msg)\n        else:\n            self.H = H\n\n        if sc_ops:\n            msg = (\"The sc_ops format is not valid. Options are \"\n                   \"[ Qobj / QobjEvo / [Qobj, coeff]]. \")\n            try:\n                self.sc_ops = [QobjEvo(op, args=args, tlist=times)\n                               for op in sc_ops]\n            except Exception as e:\n                raise ValueError(msg + str(e)) from e\n            except:\n                raise ValueError(msg)\n        else:\n            self.sc_ops = sc_ops\n\n        if c_ops:\n            msg = (\"The c_ops format is not valid. Options are \"\n                   \"[ Qobj / QobjEvo / [Qobj, coeff]]. \")\n            try:\n                self.c_ops = [QobjEvo(op, args=args, tlist=times)\n                              for op in c_ops]\n            except Exception as e:\n                raise ValueError(msg + str(e)) from e\n            except:\n                raise ValueError(msg)\n        else:\n            self.c_ops = c_ops\n\n        self.state0 = state0\n        self.rho0 = mat2vec(state0.full()).ravel()\n\n        # Observation\n        self.e_ops = e_ops\n        self.m_ops = m_ops\n        self.store_measurement = store_measurement\n        self.store_all_expect = store_all_expect\n        self.store_states = options.store_states\n        self.dW_factors = dW_factors\n\n        # Solver\n        self.solver = solver\n        self.method = method\n        if normalize is None and me:\n            self.normalize = 0\n        elif normalize is None and not me:\n            self.normalize = 1\n        elif normalize:\n            self.normalize = 1\n        else:\n            self.normalize = 0\n\n        self.times = times\n        self.nsubsteps = nsubsteps\n        self.dt = (times[1] - times[0]) / self.nsubsteps\n        self.ntraj = ntraj\n        if tol is not None:\n            self.tol = tol\n        elif \"tol\" in args:\n            self.tol = args[\"tol\"]\n        else:\n            self.tol = 1e-7\n\n        # Noise\n        if noise is not None:\n            if isinstance(noise, int):\n                # noise contain a seed\n                np.random.seed(noise)\n                noise = np.random.randint(0, 2**32, ntraj)\n            noise = np.array(noise)\n            if len(noise.shape) == 1:\n                if noise.shape[0] < ntraj:\n                    raise ValueError(\"'noise' does not have enought seeds \" +\n                                     \"len(noise) >= ntraj\")\n                # numpy seed must be between 0 and 2**32-1\n                # 'u4': unsigned 32bit int\n                self.noise = noise.astype(\"u4\")\n                self.noise_type = 0\n\n            elif len(noise.shape) == 4:\n                # taylor case not included\n                dw_len = (2 if method == \"heterodyne\" else 1)\n                dw_len_str = (\" * 2\" if method == \"heterodyne\" else \"\")\n                msg = \"Incorrect shape for 'noise': \"\n                if noise.shape[0] < ntraj:\n                    raise ValueError(msg + \"shape[0] >= ntraj\")\n                if noise.shape[1] < len(times):\n                    raise ValueError(msg + \"shape[1] >= len(times)\")\n                if noise.shape[2] < nsubsteps:\n                    raise ValueError(msg + \"shape[2] >= nsubsteps\")\n                if noise.shape[3] < len(self.sc_ops) * dw_len:\n                    raise ValueError(msg + \"shape[3] >= len(self.sc_ops)\" +\n                                     dw_len_str)\n                self.noise_type = 1\n                self.noise = noise\n\n        else:\n            self.noise = np.random.randint(0, 2**32, ntraj).astype(\"u4\")\n            self.noise_type = 0\n\n        # Map\n        self.progress_bar = progress_bar\n        if self.ntraj > 1 and map_func:\n            self.map_func = map_func\n        else:\n            self.map_func = serial_map\n        self.map_kwargs = map_kwargs if map_kwargs is not None else {}\n\n        # Other\n        self.options = options\n        self.args = args\n        self.set_solver()\n        self.p = noiseDepth\n\n    def set_solver(self):\n        if self.solver in ['euler-maruyama', 'euler', 50, 0.5]:\n            self.solver_code = 50\n            self.solver = 'euler-maruyama'\n        elif self.solver in ['platen', 'platen1', 'explicit1', 100]:\n            self.solver_code = 100\n            self.solver = 'platen'\n        elif self.solver in ['pred-corr', 'predictor-corrector',\n                             'pc-euler', 101]:\n            self.solver_code = 101\n            self.solver = 'pred-corr'\n        elif self.solver in ['milstein', 102, 1.0]:\n            self.solver_code = 102\n            self.solver = 'milstein'\n        elif self.solver in ['milstein-imp', 103]:\n            self.solver_code = 103\n            self.solver = 'milstein-imp'\n        elif self.solver in ['pred-corr-2', 'pc-euler-2', 'pc-euler-imp', 104]:\n            self.solver_code = 104\n            self.solver = 'pred-corr-2'\n        elif self.solver in ['Rouchon', 'rouchon', 120]:\n            self.solver_code = 120\n            self.solver = 'rouchon'\n            if not all((op.const for op in self.sc_ops)):\n                raise ValueError(\"Rouchon only works with constant sc_ops\")\n        elif self.solver in ['platen15', 'explicit1.5', 'explicit15', 150]:\n            self.solver_code = 150\n            self.solver = 'explicit1.5'\n        elif self.solver in ['taylor15', 'taylor1.5', None, 1.5, 152]:\n            self.solver_code = 152\n            self.solver = 'taylor1.5'\n        elif self.solver in ['taylor15-imp', 'taylor1.5-imp', 153]:\n            self.solver_code = 153\n            self.solver = 'taylor1.5-imp'\n        elif self.solver in ['taylor2.0', 'taylor20', 2.0, 202]:\n            self.solver_code = 202\n            self.solver = 'taylor2.0'\n            if not len(self.sc_ops) == 1 or \\\n                    not self.sc_ops[0].const or \\\n                    not self.method == \"homodyne\":\n                raise ValueError(\"Taylor2.0 only works with 1 constant \" +\n                                \"sc_ops and for homodyne method\")\n        else:\n            raise ValueError((\n                    \"The solver should be one of \"\n                    \"[None, 'euler-maruyama', 'platen', 'pc-euler', \"\n                    \"'pc-euler-imp', 'milstein', 'milstein-imp', \"\n                    \"'rouchon', \"\n                    \"'taylor1.5', 'taylor1.5-imp', 'explicit1.5' \"\n                    \"'taylor2.0']\"))\n\n\nclass StochasticSolverOptionsPhoto(StochasticSolverOptions):\n    \"\"\"\n    Attributes\n    ----------\n\n    solver : string\n        Name of the solver method to use for solving the evolution\n        of the system.*\n        order 1 algorithms: 'euler'\n        order 2 algorithms: 'pred-corr'\n        In photocurrent evolution\n    \"\"\"\n    def set_solver(self):\n        if self.solver in [None, 'euler', 1, 60]:\n            self.solver_code = 60\n            self.solver = 'euler'\n        elif self.solver in ['pred-corr', 'predictor-corrector', 110, 2]:\n            self.solver_code = 110\n            self.solver = 'pred-corr'\n        else:\n            raise Exception(\"The solver should be one of \" +\n                            \"[None, 'euler', 'predictor-corrector']\")\n\n\ndef smesolve(H, rho0, times, c_ops=[], sc_ops=[], e_ops=[],\n             _safe_mode=True, args={}, **kwargs):\n    \"\"\"\n    Solve stochastic master equation. Dispatch to specific solvers\n    depending on the value of the `solver` keyword argument.\n\n    Parameters\n    ----------\n\n    H : :class:`qutip.Qobj`, or time dependent system.\n        System Hamiltonian.\n        Can depend on time, see StochasticSolverOptions help for format.\n\n    rho0 : :class:`qutip.Qobj`\n        Initial density matrix or state vector (ket).\n\n    times : *list* / *array*\n        List of times for :math:`t`. Must be uniformly spaced.\n\n    c_ops : list of :class:`qutip.Qobj`, or time dependent Qobjs.\n        Deterministic collapse operator which will contribute with a standard\n        Lindblad type of dissipation.\n        Can depend on time, see StochasticSolverOptions help for format.\n\n    sc_ops : list of :class:`qutip.Qobj`, or time dependent Qobjs.\n        List of stochastic collapse operators. Each stochastic collapse\n        operator will give a deterministic and stochastic contribution\n        to the eqaution of motion according to how the d1 and d2 functions\n        are defined.\n        Can depend on time, see StochasticSolverOptions help for format.\n\n    e_ops : list of :class:`qutip.Qobj`\n        single operator or list of operators for which to evaluate\n        expectation values.\n\n    kwargs : *dictionary*\n        Optional keyword arguments. See\n        :class:`qutip.stochastic.StochasticSolverOptions`.\n\n    Returns\n    -------\n\n    output: :class:`qutip.solver.Result`\n\n        An instance of the class :class:`qutip.solver.Result`.\n\n    \"\"\"\n    if \"method\" in kwargs and kwargs[\"method\"] == \"photocurrent\":\n        print(\"stochastic solver with photocurrent method has been moved to \"\n              \"it's own function: photocurrent_mesolve\")\n        return photocurrent_mesolve(H, rho0, times, c_ops=c_ops, sc_ops=sc_ops,\n                                   e_ops=e_ops, _safe_mode=_safe_mode,\n                                   args=args, **kwargs)\n    if isket(rho0):\n        rho0 = ket2dm(rho0)\n\n    if isinstance(e_ops, dict):\n        e_ops_dict = e_ops\n        e_ops = [e for e in e_ops.values()]\n    else:\n        e_ops_dict = None\n\n    sso = StochasticSolverOptions(True, H=H, state0=rho0, times=times,\n                                  c_ops=c_ops, sc_ops=sc_ops, e_ops=e_ops,\n                                  args=args, **kwargs)\n\n    if _safe_mode:\n        _safety_checks(sso)\n\n    if sso.solver_code == 120:\n        return _positive_map(sso, e_ops_dict)\n\n    sso.LH = liouvillian(sso.H, c_ops=sso.sc_ops + sso.c_ops) * sso.dt\n    if sso.method == 'homodyne' or sso.method is None:\n        if sso.m_ops is None:\n            sso.m_ops = [op + op.dag() for op in sso.sc_ops]\n        sso.sops = [spre(op) + spost(op.dag()) for op in sso.sc_ops]\n        if not isinstance(sso.dW_factors, list):\n            sso.dW_factors = [1] * len(sso.m_ops)\n        elif len(sso.dW_factors) != len(sso.m_ops):\n            raise Exception(\"The len of dW_factors is not the same as m_ops\")\n\n    elif sso.method == 'heterodyne':\n        if sso.m_ops is None:\n            m_ops = []\n        sso.sops = []\n        for c in sso.sc_ops:\n            if sso.m_ops is None:\n                m_ops += [c + c.dag(), -1j * c - c.dag()]\n            sso.sops += [(spre(c) + spost(c.dag())) / np.sqrt(2),\n                         (spre(c) - spost(c.dag())) * -1j / np.sqrt(2)]\n        sso.m_ops = m_ops\n        if not isinstance(sso.dW_factors, list):\n            sso.dW_factors = [np.sqrt(2)] * len(sso.sops)\n        elif len(sso.dW_factors) == len(sso.m_ops):\n            pass\n        elif len(sso.dW_factors) == len(sso.sc_ops):\n            dW_factors = []\n            for fact in sso.dW_factors:\n                dW_factors += [np.sqrt(2) * fact, np.sqrt(2) * fact]\n            sso.dW_factors = dW_factors\n        elif len(sso.dW_factors) != len(sso.m_ops):\n            raise Exception(\"The len of dW_factors is not the same as sc_ops\")\n\n    elif sso.method == \"photocurrent\":\n        raise NotImplementedError(\"Moved to 'photocurrent_mesolve'\")\n\n    else:\n        raise Exception(\"The method must be one of None, homodyne, heterodyne\")\n\n    sso.ce_ops = [QobjEvo(spre(op)) for op in sso.e_ops]\n    sso.cm_ops = [QobjEvo(spre(op)) for op in sso.m_ops]\n\n    sso.LH.compile()\n    [op.compile() for op in sso.sops]\n    [op.compile() for op in sso.cm_ops]\n    [op.compile() for op in sso.ce_ops]\n\n    if sso.solver_code in [103, 153]:\n        sso.imp = 1 - sso.LH * 0.5\n        sso.imp.compile()\n\n    sso.solver_obj = SMESolver\n    sso.solver_name = \"smesolve_\" + sso.solver\n\n    res = _sesolve_generic(sso, sso.options, sso.progress_bar)\n\n    if e_ops_dict:\n        res.expect = {e: res.expect[n]\n                      for n, e in enumerate(e_ops_dict.keys())}\n    return res\n\n\ndef ssesolve(H, psi0, times, sc_ops=[], e_ops=[],\n             _safe_mode=True, args={}, **kwargs):\n    \"\"\"\n    Solve stochastic schrodinger equation. Dispatch to specific solvers\n    depending on the value of the `solver` keyword argument.\n\n    Parameters\n    ----------\n\n    H : :class:`qutip.Qobj`, or time dependent system.\n        System Hamiltonian.\n        Can depend on time, see StochasticSolverOptions help for format.\n\n    psi0 : :class:`qutip.Qobj`\n        State vector (ket).\n\n    times : *list* / *array*\n        List of times for :math:`t`. Must be uniformly spaced.\n\n    sc_ops : list of :class:`qutip.Qobj`, or time dependent Qobjs.\n        List of stochastic collapse operators. Each stochastic collapse\n        operator will give a deterministic and stochastic contribution\n        to the eqaution of motion according to how the d1 and d2 functions\n        are defined.\n        Can depend on time, see StochasticSolverOptions help for format.\n\n    e_ops : list of :class:`qutip.Qobj`\n        single operator or list of operators for which to evaluate\n        expectation values.\n\n    kwargs : *dictionary*\n        Optional keyword arguments. See\n        :class:`qutip.stochastic.StochasticSolverOptions`.\n\n    Returns\n    -------\n\n    output: :class:`qutip.solver.Result`\n\n        An instance of the class :class:`qutip.solver.Result`.\n    \"\"\"\n    if \"method\" in kwargs and kwargs[\"method\"] == \"photocurrent\":\n        print(\"stochastic solver with photocurrent method has been moved to \"\n              \"it's own function: photocurrent_sesolve\")\n        return photocurrent_sesolve(H, psi0, times, c_ops=c_ops,\n                                   e_ops=e_ops, _safe_mode=_safe_mode,\n                                   args=args, **kwargs)\n\n    if isinstance(e_ops, dict):\n        e_ops_dict = e_ops\n        e_ops = [e for e in e_ops.values()]\n    else:\n        e_ops_dict = None\n\n    sso = StochasticSolverOptions(False, H=H, state0=psi0, times=times,\n                                  sc_ops=sc_ops, e_ops=e_ops,\n                                  args=args, **kwargs)\n\n    if _safe_mode:\n        _safety_checks(sso)\n\n    if sso.solver_code == 120:\n        raise Exception(\"rouchon only work with smesolve\")\n\n    if sso.method == 'homodyne' or sso.method is None:\n        if sso.m_ops is None:\n            sso.m_ops = [op + op.dag() for op in sso.sc_ops]\n        sso.sops = [[op, op + op.dag()] for op in sso.sc_ops]\n        if not isinstance(sso.dW_factors, list):\n            sso.dW_factors = [1] * len(sso.sops)\n        elif len(sso.dW_factors) != len(sso.sops):\n            raise Exception(\"The len of dW_factors is not the same as sc_ops\")\n\n    elif sso.method == 'heterodyne':\n        if sso.m_ops is None:\n            m_ops = []\n        sso.sops = []\n        for c in sso.sc_ops:\n            if sso.m_ops is None:\n                m_ops += [c + c.dag(), -1j * (c - c.dag())]\n            c1 = c / np.sqrt(2)\n            c2 = c * (-1j / np.sqrt(2))\n            sso.sops += [[c1, c1 + c1.dag()],\n                         [c2, c2 + c2.dag()]]\n        sso.m_ops = m_ops\n        if not isinstance(sso.dW_factors, list):\n            sso.dW_factors = [np.sqrt(2)] * len(sso.sops)\n        elif len(sso.dW_factors) == len(sso.sc_ops):\n            dW_factors = []\n            for fact in sso.dW_factors:\n                dW_factors += [np.sqrt(2) * fact, np.sqrt(2) * fact]\n            sso.dW_factors = dW_factors\n        elif len(sso.dW_factors) != len(sso.sops):\n            raise Exception(\"The len of dW_factors is not the same as sc_ops\")\n\n    elif sso.method == \"photocurrent\":\n        NotImplementedError(\"Moved to 'photocurrent_sesolve'\")\n\n    else:\n        raise Exception(\"The method must be one of None, homodyne, heterodyne\")\n\n    sso.LH = sso.H * (-1j*sso.dt)\n    for ops in sso.sops:\n        sso.LH -= ops[0]._cdc()*0.5*sso.dt\n\n    sso.ce_ops = [QobjEvo(op) for op in sso.e_ops]\n    sso.cm_ops = [QobjEvo(op) for op in sso.m_ops]\n\n    sso.LH.compile()\n    [[op.compile() for op in ops] for ops in sso.sops]\n    [op.compile() for op in sso.cm_ops]\n    [op.compile() for op in sso.ce_ops]\n\n    sso.solver_obj = SSESolver\n    sso.solver_name = \"ssesolve_\" + sso.solver\n\n    res = _sesolve_generic(sso, sso.options, sso.progress_bar)\n\n    if e_ops_dict:\n        res.expect = {e: res.expect[n]\n                      for n, e in enumerate(e_ops_dict.keys())}\n\n    return res\n\n\ndef _positive_map(sso, e_ops_dict):\n    if sso.method == 'homodyne' or sso.method is None:\n        sops = sso.sc_ops\n        if sso.m_ops is None:\n            sso.m_ops = [op + op.dag() for op in sso.sc_ops]\n        if not isinstance(sso.dW_factors, list):\n            sso.dW_factors = [1] * len(sops)\n        elif len(sso.dW_factors) != len(sops):\n            raise Exception(\"The len of dW_factors is not the same as sc_ops\")\n\n    elif sso.method == 'heterodyne':\n        if sso.m_ops is None:\n            m_ops = []\n        sops = []\n        for c in sso.sc_ops:\n            if sso.m_ops is None:\n                m_ops += [c + c.dag(), -1j * c - c.dag()]\n            sops += [c / np.sqrt(2), -1j / np.sqrt(2) * c]\n        sso.m_ops = m_ops\n        if not isinstance(sso.dW_factors, list):\n            sso.dW_factors = [np.sqrt(2)] * len(sops)\n        elif len(sso.dW_factors) == len(sso.sc_ops):\n            dW_factors = []\n            for fact in sso.dW_factors:\n                dW_factors += [np.sqrt(2) * fact, np.sqrt(2) * fact]\n            sso.dW_factors = dW_factors\n        elif len(sso.dW_factors) != len(sops):\n            raise Exception(\"The len of dW_factors is not the same as sc_ops\")\n    else:\n        raise Exception(\"The method must be one of homodyne or heterodyne\")\n\n    LH = 1 - (sso.H * 1j * sso.dt)\n    sso.pp = spre(sso.H) * 0\n    sso.sops = []\n    sso.preops = []\n    sso.postops = []\n    sso.preops2 = []\n    sso.postops2 = []\n\n    def _prespostdag(op):\n        return spre(op) * spost(op.dag())\n\n    for op in sso.c_ops:\n        LH -= op._cdc() * sso.dt * 0.5\n        sso.pp += op.apply(_prespostdag)._f_norm2() * sso.dt\n\n    for i, op in enumerate(sops):\n        LH -= op._cdc() * sso.dt * 0.5\n        sso.sops += [(spre(op) + spost(op.dag())) * sso.dt]\n        sso.preops += [spre(op)]\n        sso.postops += [spost(op.dag())]\n        for op2 in sops[i:]:\n            sso.preops2 += [spre(op * op2)]\n            sso.postops2 += [spost(op.dag() * op2.dag())]\n\n    sso.ce_ops = [QobjEvo(spre(op)) for op in sso.e_ops]\n    sso.cm_ops = [QobjEvo(spre(op)) for op in sso.m_ops]\n    sso.preLH = spre(LH)\n    sso.postLH = spost(LH.dag())\n    sso.preLH.compile()\n    sso.postLH.compile()\n    sso.pp.compile()\n    [op.compile() for op in sso.sops]\n    [op.compile() for op in sso.preops]\n    [op.compile() for op in sso.postops]\n    [op.compile() for op in sso.preops2]\n    [op.compile() for op in sso.postops2]\n    [op.compile() for op in sso.cm_ops]\n    [op.compile() for op in sso.ce_ops]\n\n    sso.solver_obj = PmSMESolver\n    sso.solver_name = \"smesolve_\" + sso.solver\n    res = _sesolve_generic(sso, sso.options, sso.progress_bar)\n\n    if e_ops_dict:\n        res.expect = {e: res.expect[n]\n                      for n, e in enumerate(e_ops_dict.keys())}\n\n    return res\n\n\ndef photocurrent_mesolve(H, rho0, times, c_ops=[], sc_ops=[], e_ops=[],\n                        _safe_mode=True, args={}, **kwargs):\n    \"\"\"\n    Solve stochastic master equation using the photocurrent method.\n\n    Parameters\n    ----------\n\n    H : :class:`qutip.Qobj`, or time dependent system.\n        System Hamiltonian.\n        Can depend on time, see StochasticSolverOptions help for format.\n\n    rho0 : :class:`qutip.Qobj`\n        Initial density matrix or state vector (ket).\n\n    times : *list* / *array*\n        List of times for :math:`t`. Must be uniformly spaced.\n\n    c_ops : list of :class:`qutip.Qobj`, or time dependent Qobjs.\n        Deterministic collapse operator which will contribute with a standard\n        Lindblad type of dissipation.\n        Can depend on time, see StochasticSolverOptions help for format.\n\n    sc_ops : list of :class:`qutip.Qobj`, or time dependent Qobjs.\n        List of stochastic collapse operators. Each stochastic collapse\n        operator will give a deterministic and stochastic contribution\n        to the eqaution of motion according to how the d1 and d2 functions\n        are defined.\n        Can depend on time, see StochasticSolverOptions help for format.\n\n    e_ops : list of :class:`qutip.Qobj` / callback function single\n        single operator or list of operators for which to evaluate\n        expectation values.\n\n    kwargs : *dictionary*\n        Optional keyword arguments. See\n        :class:`qutip.stochastic.StochasticSolverOptions`.\n\n    Returns\n    -------\n\n    output: :class:`qutip.solver.Result`\n\n        An instance of the class :class:`qutip.solver.Result`.\n    \"\"\"\n    if isket(rho0):\n        rho0 = ket2dm(rho0)\n\n    if isinstance(e_ops, dict):\n        e_ops_dict = e_ops\n        e_ops = [e for e in e_ops.values()]\n    else:\n        e_ops_dict = None\n\n    sso = StochasticSolverOptionsPhoto(True, H=H, state0=rho0, times=times,\n                                       c_ops=c_ops, sc_ops=sc_ops, e_ops=e_ops,\n                                       args=args, **kwargs)\n\n    if _safe_mode:\n        _safety_checks(sso)\n\n    if sso.m_ops is None:\n        sso.m_ops = [op * 0 for op in sso.sc_ops]\n    if not isinstance(sso.dW_factors, list):\n        sso.dW_factors = [1] * len(sso.sc_ops)\n    elif len(sso.dW_factors) != len(sso.sc_ops):\n        raise Exception(\"The len of dW_factors is not the same as sc_ops\")\n\n    sso.solver_obj = PcSMESolver\n    sso.solver_name = \"photocurrent_mesolve\"\n    sso.LH = liouvillian(sso.H, c_ops=sso.c_ops) * sso.dt\n\n    def _prespostdag(op):\n        return spre(op) * spost(op.dag())\n\n    sso.sops = [[spre(op._cdc()) + spost(op._cdc()),\n                 spre(op._cdc()),\n                 op.apply(_prespostdag)._f_norm2()] for op in sso.sc_ops]\n    sso.ce_ops = [QobjEvo(spre(op)) for op in sso.e_ops]\n    sso.cm_ops = [QobjEvo(spre(op)) for op in sso.m_ops]\n\n    sso.LH.compile()\n    [[op.compile() for op in ops] for ops in sso.sops]\n    [op.compile() for op in sso.cm_ops]\n    [op.compile() for op in sso.ce_ops]\n\n    res = _sesolve_generic(sso, sso.options, sso.progress_bar)\n    res.num_collapse = [np.count_nonzero(noise) for noise in res.noise]\n\n    if e_ops_dict:\n        res.expect = {e: res.expect[n]\n                      for n, e in enumerate(e_ops_dict.keys())}\n\n    return res\n\n\ndef photocurrent_sesolve(H, psi0, times, sc_ops=[], e_ops=[],\n                        _safe_mode=True, args={}, **kwargs):\n    \"\"\"\n    Solve stochastic schrodinger equation using the photocurrent method.\n\n    Parameters\n    ----------\n\n    H : :class:`qutip.Qobj`, or time dependent system.\n        System Hamiltonian.\n        Can depend on time, see StochasticSolverOptions help for format.\n\n    psi0 : :class:`qutip.Qobj`\n        Initial state vector (ket).\n\n    times : *list* / *array*\n        List of times for :math:`t`. Must be uniformly spaced.\n\n    sc_ops : list of :class:`qutip.Qobj`, or time dependent Qobjs.\n        List of stochastic collapse operators. Each stochastic collapse\n        operator will give a deterministic and stochastic contribution\n        to the eqaution of motion according to how the d1 and d2 functions\n        are defined.\n        Can depend on time, see StochasticSolverOptions help for format.\n\n    e_ops : list of :class:`qutip.Qobj` / callback function single\n        single operator or list of operators for which to evaluate\n        expectation values.\n\n    kwargs : *dictionary*\n        Optional keyword arguments. See\n        :class:`qutip.stochastic.StochasticSolverOptions`.\n\n    Returns\n    -------\n\n    output: :class:`qutip.solver.Result`\n\n        An instance of the class :class:`qutip.solver.Result`.\n    \"\"\"\n    if isinstance(e_ops, dict):\n        e_ops_dict = e_ops\n        e_ops = [e for e in e_ops.values()]\n    else:\n        e_ops_dict = None\n\n    sso = StochasticSolverOptionsPhoto(False, H=H, state0=psi0, times=times,\n                                       sc_ops=sc_ops, e_ops=e_ops,\n                                       args=args, **kwargs)\n\n    if _safe_mode:\n        _safety_checks(sso)\n\n    if sso.m_ops is None:\n        sso.m_ops = [op * 0 for op in sso.sc_ops]\n    if not isinstance(sso.dW_factors, list):\n        sso.dW_factors = [1] * len(sso.sc_ops)\n    elif len(sso.dW_factors) != len(sso.sc_ops):\n        raise Exception(\"The len of dW_factors is not the same as sc_ops\")\n\n    sso.solver_obj = PcSSESolver\n    sso.solver_name = \"photocurrent_sesolve\"\n    sso.sops = [[op, op._cdc()] for op in sso.sc_ops]\n    sso.LH = sso.H * (-1j*sso.dt)\n    for ops in sso.sops:\n        sso.LH -= ops[0]._cdc()*0.5*sso.dt\n    sso.ce_ops = [QobjEvo(op) for op in sso.e_ops]\n    sso.cm_ops = [QobjEvo(op) for op in sso.m_ops]\n\n    sso.LH.compile()\n    [[op.compile() for op in ops] for ops in sso.sops]\n    [op.compile() for op in sso.cm_ops]\n    [op.compile() for op in sso.ce_ops]\n\n    res = _sesolve_generic(sso, sso.options, sso.progress_bar)\n    res.num_collapse = [np.count_nonzero(noise) for noise in res.noise]\n\n    if e_ops_dict:\n        res.expect = {e: res.expect[n]\n                      for n, e in enumerate(e_ops_dict.keys())}\n\n    return res\n\n\ndef general_stochastic(state0, times, d1, d2, e_ops=[], m_ops=[],\n                       _safe_mode=True, len_d2=1, args={}, **kwargs):\n    \"\"\"\n    Solve stochastic general equation. Dispatch to specific solvers\n    depending on the value of the `solver` keyword argument.\n\n\n    Parameters\n    ----------\n\n    state0 : :class:`qutip.Qobj`\n        Initial state vector (ket) or density matrix as a vector.\n\n    times : *list* / *array*\n        List of times for :math:`t`. Must be uniformly spaced.\n\n    d1 : function, callable class\n        Function representing the deterministic evolution of the system.\n\n        def d1(time (double), state (as a np.array vector)):\n            return 1d np.array\n\n    d2 : function, callable class\n        Function representing the stochastic evolution of the system.\n\n        def d2(time (double), state (as a np.array vector)):\n            return 2d np.array (N_sc_ops, len(state0))\n\n    len_d2 : int\n        Number of output vector produced by d2\n\n    e_ops : list of :class:`qutip.Qobj`\n        single operator or list of operators for which to evaluate\n        expectation values.\n        Must be a superoperator if the state vector is a density matrix.\n\n    kwargs : *dictionary*\n        Optional keyword arguments. See\n        :class:`qutip.stochastic.StochasticSolverOptions`.\n\n    Returns\n    -------\n\n    output: :class:`qutip.solver.Result`\n        An instance of the class :class:`qutip.solver.Result`.\n    \"\"\"\n\n    if isinstance(e_ops, dict):\n        e_ops_dict = e_ops\n        e_ops = [e for e in e_ops.values()]\n    else:\n        e_ops_dict = None\n\n    if \"solver\" not in kwargs:\n        kwargs[\"solver\"] = 50\n\n    sso = StochasticSolverOptions(False, H=None, state0=state0, times=times,\n                                  e_ops=e_ops, args=args, **kwargs)\n    if sso.solver_code not in [50, 100, 150]:\n        raise ValueError(\"Only Euler, platen, platen15 can be \" +\n                         \"used for the general stochastic solver.\")\n\n    sso.d1 = d1\n    sso.d2 = d2\n    if _safe_mode:\n        # This state0_vec is computed as mat2vec(state0.full()).ravel()\n        # in the sso init.\n        state0_vec = sso.rho0\n        l_vec = state0_vec.shape[0]\n        try:\n            out_d1 = d1(0., sso.rho0)\n        except Exception as e:\n            raise RuntimeError(\"Safety check: d1(0., state0_vec) failed.:\\n\" +\n                               str(e)) from e\n        except:\n            raise RuntimeError(\"Safety check: d1(0., state0_vec) failed.\")\n        try:\n            out_d2 = d2(0., sso.rho0)\n        except Exception as e:\n            raise RuntimeError(\"Safety check: d2(0., state0_vec) failed:\\n\" +\n                               str(e)) from e\n        except:\n            raise RuntimeError(\"Safety check: d2(0., state0_vec) failed.\")\n\n        msg_d1 = (\"d1 must return an 1d numpy array with the same number \"\n                  \"of elements as the initial state as a vector.\")\n        if not isinstance(out_d1, np.ndarray):\n            raise TypeError(msg_d1)\n        if (out_d1.ndim != 1\n                or out_d1.shape[0] != l_vec or len(out_d1.shape) != 1):\n            raise ValueError(msg_d1)\n\n        msg_d2 = (\"Safety check: d2 must return a 2d numpy array \"\n                  \"with the shape (len_d2, len(state0_vec) ).\")\n        if not isinstance(out_d2, np.ndarray):\n            raise TypeError(msg_d2)\n        if (out_d2.ndim != 2\n                or out_d2.shape[1] != l_vec or out_d2.shape[0] != len_d2):\n            raise ValueError(msg_d2)\n        if out_d1.dtype != np.dtype('complex128') or \\\n           out_d2.dtype != np.dtype('complex128'):\n            raise ValueError(\"Safety check: d1 and d2 must return \" +\n                             \"complex numpy array.\")\n        msg_e_ops = (\"Safety check: The shape of the e_ops \"\n                     \"does not fit the intial state.\")\n        for op in sso.e_ops:\n            shape_op = op.shape\n            if sso.me:\n                if shape_op[0]**2 != l_vec or shape_op[1]**2 != l_vec:\n                    raise ValueError(msg_e_ops)\n            else:\n                if shape_op[0] != l_vec or shape_op[1] != l_vec:\n                    raise ValueError(msg_e_ops +\n                                     \" Expecting e_ops as superoperators.\")\n\n    sso.m_ops = []\n    sso.cm_ops = []\n    if sso.store_measurement:\n        if not m_ops:\n            raise ValueError(\"General stochastic needs explicit \" +\n                             \"m_ops to store measurement.\")\n        sso.m_ops = m_ops\n        sso.cm_ops = [QobjEvo(op) for op in sso.m_ops]\n        [op.compile() for op in sso.cm_ops]\n        if sso.dW_factors is None:\n            sso.dW_factors = [1.] * len(sso.m_ops)\n        elif len(sso.dW_factors) == 1:\n                sso.dW_factors = sso.dW_factors * len(sso.m_ops)\n        elif len(sso.dW_factors) != len(sso.m_ops):\n            raise ValueError(\"The number of dW_factors must fit\" +\n                             \" the number of m_ops.\")\n\n    if sso.dW_factors is None:\n        sso.dW_factors = [1.] * len_d2\n    sso.sops = [None] * len_d2\n    sso.ce_ops = [QobjEvo(op) for op in sso.e_ops]\n    [op.compile() for op in sso.ce_ops]\n\n    sso.solver_obj = GenericSSolver\n    sso.solver_name = \"general_stochastic_solver_\" + sso.solver\n\n    ssolver = GenericSSolver()\n    # ssolver.set_data(sso)\n    ssolver.set_solver(sso)\n\n    res = _sesolve_generic(sso, sso.options, sso.progress_bar)\n\n    if e_ops_dict:\n        res.expect = {e: res.expect[n]\n                      for n, e in enumerate(e_ops_dict.keys())}\n\n    return res\n\n\ndef _safety_checks(sso):\n    l_vec = sso.rho0.shape[0]\n    if sso.H.cte.issuper:\n        if not sso.me:\n            raise\n        shape_op = sso.H.cte.shape\n        if shape_op[0] != l_vec or shape_op[1] != l_vec:\n            raise Exception(\"The size of the hamiltonian does \"\n                            \"not fit the intial state\")\n    else:\n        shape_op = sso.H.cte.shape\n        if sso.me:\n            if shape_op[0]**2 != l_vec or shape_op[1]**2 != l_vec:\n                raise Exception(\"The size of the hamiltonian does \"\n                                \"not fit the intial state\")\n        else:\n            if shape_op[0] != l_vec or shape_op[1] != l_vec:\n                raise Exception(\"The size of the hamiltonian does \"\n                                \"not fit the intial state\")\n\n    for op in sso.sc_ops:\n        if op.cte.issuper:\n            if not sso.me:\n                raise\n            shape_op = op.cte.shape\n            if shape_op[0] != l_vec or shape_op[1] != l_vec:\n                raise Exception(\"The size of the sc_ops does \"\n                                \"not fit the intial state\")\n        else:\n            shape_op = op.cte.shape\n            if sso.me:\n                if shape_op[0]**2 != l_vec or shape_op[1]**2 != l_vec:\n                    raise Exception(\"The size of the sc_ops does \"\n                                    \"not fit the intial state\")\n            else:\n                if shape_op[0] != l_vec or shape_op[1] != l_vec:\n                    raise Exception(\"The size of the sc_ops does \"\n                                    \"not fit the intial state\")\n\n    for op in sso.c_ops:\n        if op.cte.issuper:\n            if not sso.me:\n                raise\n            shape_op = op.cte.shape\n            if shape_op[0] != l_vec or shape_op[1] != l_vec:\n                raise Exception(\"The size of the c_ops does \"\n                                \"not fit the intial state\")\n        else:\n            shape_op = op.cte.shape\n            if sso.me:\n                if shape_op[0]**2 != l_vec or shape_op[1]**2 != l_vec:\n                    raise Exception(\"The size of the c_ops does \"\n                                    \"not fit the intial state\")\n            else:\n                if shape_op[0] != l_vec or shape_op[1] != l_vec:\n                    raise Exception(\"The size of the c_ops does \"\n                                    \"not fit the intial state\")\n\n    for op in sso.e_ops:\n        shape_op = op.shape\n        if sso.me:\n            if shape_op[0]**2 != l_vec or shape_op[1]**2 != l_vec:\n                raise Exception(\"The size of the e_ops does \"\n                                \"not fit the intial state\")\n        else:\n            if shape_op[0] != l_vec or shape_op[1] != l_vec:\n                raise Exception(\"The size of the e_ops does \"\n                                \"not fit the intial state\")\n\n    if sso.m_ops is not None:\n        for op in sso.m_ops:\n            shape_op = op.shape\n            if sso.me:\n                if shape_op[0]**2 != l_vec or shape_op[1]**2 != l_vec:\n                    raise Exception(\"The size of the m_ops does \"\n                                    \"not fit the intial state\")\n            else:\n                if shape_op[0] != l_vec or shape_op[1] != l_vec:\n                    raise Exception(\"The size of the m_ops does \"\n                                    \"not fit the intial state\")\n\n\ndef _sesolve_generic(sso, options, progress_bar):\n    \"\"\"\n    Internal function. See smesolve.\n    \"\"\"\n    res = Result()\n    res.times = sso.times\n    res.expect = np.zeros((len(sso.e_ops), len(sso.times)), dtype=complex)\n    res.ss = np.zeros((len(sso.e_ops), len(sso.times)), dtype=complex)\n    res.measurement = []\n    res.solver = sso.solver_name\n    res.ntraj = sso.ntraj\n    res.num_expect = len(sso.e_ops)\n\n    nt = sso.ntraj\n    task = _single_trajectory\n    map_kwargs = {'progress_bar': sso.progress_bar}\n    map_kwargs.update(sso.map_kwargs)\n    task_args = (sso,)\n    task_kwargs = {}\n\n    results = sso.map_func(task, list(range(sso.ntraj)),\n                           task_args, task_kwargs, **map_kwargs)\n    noise = []\n    for result in results:\n        states_list, dW, m, expect = result\n        res.states.append(states_list)\n        noise.append(dW)\n        res.measurement.append(m)\n        res.expect += expect\n        res.ss += expect * expect\n    res.noise = np.stack(noise)\n\n    if sso.store_all_expect:\n        paths_expect = []\n        for result in results:\n            paths_expect.append(result[3])\n        res.runs_expect = np.stack(paths_expect)\n\n    # average density matrices (vectorized maybe)\n    # ajgpitch 2019-10-25: np.any(res.states) seems to error\n    # I guess there may be a potential exception if there are no states?\n    # store individual trajectory states\n    res.traj_states = res.states\n    res.avg_states = None\n    if options.average_states and options.store_states:\n        avg_states_list = []\n        for n in range(len(res.times)):\n            tslot_states = [res.states[mm][n].data for mm in range(nt)]\n            if len(tslot_states) > 0:\n                state = Qobj(np.sum(tslot_states),\n                             dims=res.states[0][n].dims).unit()\n                avg_states_list.append(state)\n        # store average states\n        res.states = res.avg_states = avg_states_list\n\n    # average\n    res.expect = res.expect / nt\n\n    # standard error\n    if nt > 1:\n        res.se = (res.ss - nt * (res.expect ** 2)) / (nt * (nt - 1))\n    else:\n        res.se = None\n\n    # convert complex data to real if hermitian\n    res.expect = [np.real(res.expect[n, :])\n                  if e.isherm else res.expect[n, :]\n                  for n, e in enumerate(sso.e_ops)]\n\n    return res\n\n\ndef _single_trajectory(i, sso):\n    # Only one step?\n    ssolver = sso.solver_obj()\n    #ssolver.set_data(sso)\n    ssolver.set_solver(sso)\n    result = ssolver.cy_sesolve_single_trajectory(i)#, sso)\n    return result\n\n\n# The code for ssepdpsolve have been moved to the file pdpsolve.\n# The call is still in stochastic for consistance.\ndef ssepdpsolve(H, psi0, times, c_ops, e_ops, **kwargs):\n    \"\"\"\n    A stochastic (piecewse deterministic process) PDP solver for wavefunction\n    evolution. For most purposes, use :func:`qutip.mcsolve` instead for quantum\n    trajectory simulations.\n\n    Parameters\n    ----------\n\n    H : :class:`qutip.Qobj`\n        System Hamiltonian.\n\n    psi0 : :class:`qutip.Qobj`\n        Initial state vector (ket).\n\n    times : *list* / *array*\n        List of times for :math:`t`. Must be uniformly spaced.\n\n    c_ops : list of :class:`qutip.Qobj`\n        Deterministic collapse operator which will contribute with a standard\n        Lindblad type of dissipation.\n\n    e_ops : list of :class:`qutip.Qobj` / callback function single\n        single operator or list of operators for which to evaluate\n        expectation values.\n\n    kwargs : *dictionary*\n        Optional keyword arguments. See\n        :class:`qutip.stochastic.StochasticSolverOptions`.\n\n    Returns\n    -------\n\n    output: :class:`qutip.solver.Result`\n\n        An instance of the class :class:`qutip.solver.Result`.\n\n    \"\"\"\n    return main_ssepdpsolve(H, psi0, times, c_ops, e_ops, **kwargs)\n\n\n# The code for smepdpsolve have been moved to the file pdpsolve.\n# The call is still in stochastic for consistance.\ndef smepdpsolve(H, rho0, times, c_ops, e_ops, **kwargs):\n    \"\"\"\n    A stochastic (piecewse deterministic process) PDP solver for density matrix\n    evolution.\n\n    Parameters\n    ----------\n\n    H : :class:`qutip.Qobj`\n        System Hamiltonian.\n\n    rho0 : :class:`qutip.Qobj`\n        Initial density matrix.\n\n    times : *list* / *array*\n        List of times for :math:`t`. Must be uniformly spaced.\n\n    c_ops : list of :class:`qutip.Qobj`\n        Deterministic collapse operator which will contribute with a standard\n        Lindblad type of dissipation.\n\n    sc_ops : list of :class:`qutip.Qobj`\n        List of stochastic collapse operators. Each stochastic collapse\n        operator will give a deterministic and stochastic contribution\n        to the eqaution of motion according to how the d1 and d2 functions\n        are defined.\n\n    e_ops : list of :class:`qutip.Qobj` / callback function single\n        single operator or list of operators for which to evaluate\n        expectation values.\n\n    kwargs : *dictionary*\n        Optional keyword arguments. See\n        :class:`qutip.stochastic.StochasticSolverOptions`.\n\n    Returns\n    -------\n\n    output: :class:`qutip.solver.Result`\n\n        An instance of the class :class:`qutip.solver.Result`.\n\n    \"\"\"\n    return main_smepdpsolve(H, rho0, times, c_ops, e_ops, **kwargs)\n", "meta": {"hexsha": "316223e989a387f65c25507107ebfdee46997b5f", "size": 53921, "ext": "py", "lang": "Python", "max_stars_repo_path": "qutip/stochastic.py", "max_stars_repo_name": "dweigand/qutip", "max_stars_repo_head_hexsha": "b57d5e4b4846880e894afa390c62f4d095c642e1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "qutip/stochastic.py", "max_issues_repo_name": "dweigand/qutip", "max_issues_repo_head_hexsha": "b57d5e4b4846880e894afa390c62f4d095c642e1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qutip/stochastic.py", "max_forks_repo_name": "dweigand/qutip", "max_forks_repo_head_hexsha": "b57d5e4b4846880e894afa390c62f4d095c642e1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2125603865, "max_line_length": 82, "alphanum_fraction": 0.5954822796, "include": true, "reason": "import numpy,import scipy", "num_tokens": 14012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.3040416686603661, "lm_q1q2_score": 0.1847549241394398}}
{"text": "# Copyright 2020 NREL\n\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy of\n# the License at http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations under\n# the License.\n\nimport numpy as np\n\nfrom ....utilities import cosd, sind, tand\nfrom ..base_velocity_deficit import VelocityDeficit\n\n\nclass GaussianModel(VelocityDeficit):\n    \"\"\"\n    This is the super-class for all Gaussian-type wake models. It includes\n    implementations of functions that subclasses should use to perform\n    Gaussian-related calculations (see :cite:`gmb-King2019Controls`)\n\n    References:\n        .. bibliography:: /source/zrefs.bib\n            :style: unsrt\n            :filter: docname in docnames\n            :keyprefix: gmb-\n    \"\"\"\n\n    def __init__(self, parameter_dictionary):\n        \"\"\"\n        See super-class for initialization details.\n\n        Args:\n            parameter_dictionary (dict): Model-specific parameters.\n        \"\"\"\n        super().__init__(parameter_dictionary)\n\n    def correction_steps(\n        self, U_local, U, V, W, x_locations, y_locations, turbine, turbine_coord\n    ):\n        \"\"\"\n        This method corrects the U-component velocities when yaw added recovery\n        is enabled. For more details on how the velocities are changed, see [1].\n        # TODO add reference to 1\n\n        Args:\n            U_local (np.array): U-component velocities across the flow field.\n            U (np.array): U-component velocity deficits across the flow field.\n            V (np.array): V-component velocity deficits across the flow field.\n            W (np.array): W-component velocity deficits across the flow field.\n            x_locations (np.array): Streamwise locations in wake.\n            y_locations (np.array): Spanwise locations in wake.\n            turbine (:py:class:`floris.simulation.turbine.Turbine`):\n                Turbine object.\n            turbine_coord (:py:obj:`floris.simulation.turbine_map.TurbineMap.coords`):\n                Spatial coordinates of wind turbine.\n\n        Returns:\n            np.array: U-component velocity deficits across the flow field.\n        \"\"\"\n        if self.use_yaw_added_recovery:\n            U = self.yaw_added_recovery_correction(\n                U_local, U, W, x_locations, y_locations, turbine, turbine_coord\n            )\n        return U\n\n    def calculate_VW(\n        self, V, W, coord, turbine, flow_field, x_locations, y_locations, z_locations\n    ):\n        \"\"\"\n        This method calculates the V- and W-component velocities using\n        methods developed in [1].\n        # TODO add reference to 1\n        # TODO is this function needed? It simply calls another function\n\n        Args:\n            V (np.array): V-component velocity deficits across the flow field.\n            W (np.array): W-component velocity deficits across the flow field.\n            coord (:py:obj:`floris.simulation.turbine_map.TurbineMap.coords`):\n                Spatial coordinates of wind turbine.\n            turbine (:py:class:`floris.simulation.turbine.Turbine`):\n                Turbine object.\n            flow_field ([type]): [description]\n            x_locations (np.array): Streamwise locations in wake.\n            y_locations (np.array): Spanwise locations in wake.\n            z_locations (np.array): Vertical locations in wake.\n\n        Raises:\n            ValueError: It appears that 'use_yaw_added_recovery' is set\n                to True and 'calculate_VW_velocities' is set to False.\n                This configuration is not valid. Please set\n                'calculate_VW_velocities' to True if you wish to use\n                yaw-added recovery.\n\n        Returns:\n            np.array, np.array:\n\n                - V-component velocity deficits across the flow field.\n                - W-component velocity deficits across the flow field.\n        \"\"\"\n        if self.use_yaw_added_recovery:\n            if not self.calculate_VW_velocities:\n                err_msg = (\n                    \"It appears that 'use_yaw_added_recovery' is set \"\n                    + \"to True and 'calculate_VW_velocities' is set to False. \"\n                    + \"This configuration is not valid. Please set \"\n                    + \"'calculate_VW_velocities' to True if you wish to use \"\n                    + \"yaw-added recovery.\"\n                )\n                self.logger.error(err_msg, stack_info=True)\n                raise ValueError(err_msg)\n        if self.calculate_VW_velocities:\n            V, W = self.calc_VW(\n                coord, turbine, flow_field, x_locations, y_locations, z_locations\n            )\n        return V, W\n\n    def yaw_added_recovery_correction(\n        self, U_local, U, W, x_locations, y_locations, turbine, turbine_coord\n    ):\n        \"\"\"\n        This method corrects the U-component velocities when yaw added recovery\n        is enabled. For more details on how the velocities are changed, see [1].\n        # TODO add reference to 1\n\n        Args:\n            U_local (np.array): U-component velocities across the flow field.\n            U (np.array): U-component velocity deficits across the flow field.\n            W (np.array): W-component velocity deficits across the flow field.\n            x_locations (np.array): Streamwise locations in wake.\n            y_locations (np.array): Spanwise locations in wake.\n            turbine (:py:class:`floris.simulation.turbine.Turbine`):\n                Turbine object.\n            turbine_coord (:py:obj:`floris.simulation.turbine_map.TurbineMap.coords`):\n                Spatial coordinates of wind turbine.\n\n        Returns:\n            np.array: U-component velocity deficits across the flow field.\n        \"\"\"\n        # compute the velocity without modification\n        U1 = U_local - U\n\n        # set dimensions\n        D = turbine.rotor_diameter\n        xLocs = x_locations - turbine_coord.x1\n        ky = self.ka * turbine.current_turbulence_intensity + self.kb\n        U2 = (np.mean(W) * xLocs) / ((ky * xLocs + D / 2))\n        U_total = U1 + np.nan_to_num(U2)\n\n        # turn it back into a deficit\n        U = U_local - U_total\n\n        # zero out anything before the turbine\n        U[x_locations < turbine_coord.x1] = 0\n\n        return U\n\n    def calc_VW(\n        self, coord, turbine, flow_field, x_locations, y_locations, z_locations\n    ):\n        \"\"\"\n        This method calculates the V- and W-component velocities using\n        methods developed in [1].\n        # TODO add reference to 1\n\n        Args:\n            coord (:py:obj:`floris.simulation.turbine_map.TurbineMap.coords`):\n                Spatial coordinates of wind turbine.\n            turbine (:py:class:`floris.simulation.turbine.Turbine`):\n                Turbine object.\n            flow_field ([type]): [description]\n            x_locations (np.array): Streamwise locations in wake.\n            y_locations (np.array): Spanwise locations in wake.\n            z_locations (np.array): Vertical locations in wake.\n\n        Returns:\n            np.array, np.array:\n\n                - V-component velocity deficits across the flow field.\n                - W-component velocity deficits across the flow field.\n        \"\"\"\n        # turbine parameters\n        D = turbine.rotor_diameter\n        HH = turbine.hub_height\n        yaw = turbine.yaw_angle\n        Ct = turbine.Ct\n        TSR = turbine.tsr\n        aI = turbine.aI\n\n        # flow parameters\n        Uinf = np.mean(flow_field.wind_map.grid_wind_speed)\n\n        scale = 1.0\n        vel_top = (\n            Uinf\n            * ((HH + D / 2) / flow_field.specified_wind_height) ** flow_field.wind_shear\n        ) / Uinf\n        vel_bottom = (\n            Uinf\n            * ((HH - D / 2) / flow_field.specified_wind_height) ** flow_field.wind_shear\n        ) / Uinf\n        Gamma_top = (\n            scale * (np.pi / 8) * D * vel_top * Uinf * Ct * sind(yaw) * cosd(yaw)\n        )\n        Gamma_bottom = (\n            -scale * (np.pi / 8) * D * vel_bottom * Uinf * Ct * sind(yaw) * cosd(yaw)\n        )\n        Gamma_wake_rotation = (\n            0.25 * 2 * np.pi * D * (aI - aI ** 2) * turbine.average_velocity / TSR\n        )\n\n        # compute the spanwise and vertical velocities induced by yaw\n        eps = self.eps_gain * D  # Use set value\n\n        # decay the vortices as they move downstream - using mixing length\n        lmda = D / 8\n        kappa = 0.41\n        lm = kappa * z_locations / (1 + kappa * z_locations / lmda)\n        z = np.linspace(\n            np.min(z_locations), np.max(z_locations), np.shape(flow_field.u_initial)[2]\n        )\n        dudz_initial = np.gradient(flow_field.u_initial, z, axis=2)\n        nu = lm ** 2 * np.abs(dudz_initial[0, :, :])\n\n        # top vortex\n        yLocs = y_locations + 0.01 - (coord.x2)\n        zT = z_locations + 0.01 - (HH + D / 2)\n        rT = yLocs ** 2 + zT ** 2\n        V1 = (\n            (zT * Gamma_top)\n            / (2 * np.pi * rT)\n            * (1 - np.exp(-rT / (eps ** 2)))\n            * eps ** 2\n            / (4 * nu * (x_locations - coord.x1) / Uinf + eps ** 2)\n        )\n\n        W1 = (\n            (-yLocs * Gamma_top)\n            / (2 * np.pi * rT)\n            * (1 - np.exp(-rT / (eps ** 2)))\n            * eps ** 2\n            / (4 * nu * (x_locations - coord.x1) / Uinf + eps ** 2)\n        )\n\n        # bottom vortex\n        zB = z_locations + 0.01 - (HH - D / 2)\n        rB = yLocs ** 2 + zB ** 2\n        V2 = (\n            (zB * Gamma_bottom)\n            / (2 * np.pi * rB)\n            * (1 - np.exp(-rB / (eps ** 2)))\n            * eps ** 2\n            / (4 * nu * (x_locations - coord.x1) / Uinf + eps ** 2)\n        )\n\n        W2 = (\n            ((-yLocs * Gamma_bottom) / (2 * np.pi * rB))\n            * (1 - np.exp(-rB / (eps ** 2)))\n            * eps ** 2\n            / (4 * nu * (x_locations - coord.x1) / Uinf + eps ** 2)\n        )\n\n        # top vortex - ground\n        yLocs = y_locations + 0.01 - (coord.x2)\n        zLocs = z_locations + 0.01 + (HH + D / 2)\n        V3 = (\n            (\n                ((zLocs * -Gamma_top) / (2 * np.pi * (yLocs ** 2 + zLocs ** 2)))\n                * (1 - np.exp(-(yLocs ** 2 + zLocs ** 2) / (eps ** 2)))\n                + 0.0\n            )\n            * eps ** 2\n            / (4 * nu * (x_locations - coord.x1) / Uinf + eps ** 2)\n        )\n\n        W3 = (\n            ((-yLocs * -Gamma_top) / (2 * np.pi * (yLocs ** 2 + zLocs ** 2)))\n            * (1 - np.exp(-(yLocs ** 2 + zLocs ** 2) / (eps ** 2)))\n            * eps ** 2\n            / (4 * nu * (x_locations - coord.x1) / Uinf + eps ** 2)\n        )\n\n        # bottom vortex - ground\n        yLocs = y_locations + 0.01 - (coord.x2)\n        zLocs = z_locations + 0.01 + (HH - D / 2)\n        V4 = (\n            (\n                ((zLocs * -Gamma_bottom) / (2 * np.pi * (yLocs ** 2 + zLocs ** 2)))\n                * (1 - np.exp(-(yLocs ** 2 + zLocs ** 2) / (eps ** 2)))\n                + 0.0\n            )\n            * eps ** 2\n            / (4 * nu * (x_locations - coord.x1) / Uinf + eps ** 2)\n        )\n\n        W4 = (\n            ((-yLocs * -Gamma_bottom) / (2 * np.pi * (yLocs ** 2 + zLocs ** 2)))\n            * (1 - np.exp(-(yLocs ** 2 + zLocs ** 2) / (eps ** 2)))\n            * eps ** 2\n            / (4 * nu * (x_locations - coord.x1) / Uinf + eps ** 2)\n        )\n\n        # wake rotation vortex\n        zC = z_locations + 0.01 - (HH)\n        rC = yLocs ** 2 + zC ** 2\n        V5 = (\n            (zC * Gamma_wake_rotation)\n            / (2 * np.pi * rC)\n            * (1 - np.exp(-rC / (eps ** 2)))\n            * eps ** 2\n            / (4 * nu * (x_locations - coord.x1) / Uinf + eps ** 2)\n        )\n\n        W5 = (\n            (-yLocs * Gamma_wake_rotation)\n            / (2 * np.pi * rC)\n            * (1 - np.exp(-rC / (eps ** 2)))\n            * eps ** 2\n            / (4 * nu * (x_locations - coord.x1) / Uinf + eps ** 2)\n        )\n\n        # wake rotation vortex - ground effect\n        yLocs = y_locations + 0.01 - coord.x2\n        zLocs = z_locations + 0.01 + HH\n        V6 = (\n            (\n                (\n                    (zLocs * -Gamma_wake_rotation)\n                    / (2 * np.pi * (yLocs ** 2 + zLocs ** 2))\n                )\n                * (1 - np.exp(-(yLocs ** 2 + zLocs ** 2) / (eps ** 2)))\n                + 0.0\n            )\n            * eps ** 2\n            / (4 * nu * (x_locations - coord.x1) / Uinf + eps ** 2)\n        )\n\n        W6 = (\n            ((-yLocs * -Gamma_wake_rotation) / (2 * np.pi * (yLocs ** 2 + zLocs ** 2)))\n            * (1 - np.exp(-(yLocs ** 2 + zLocs ** 2) / (eps ** 2)))\n            * eps ** 2\n            / (4 * nu * (x_locations - coord.x1) / Uinf + eps ** 2)\n        )\n\n        # print(Gamma_wake_rotation, np.mean(W5), np.mean(W6))\n\n        # total spanwise velocity\n        V = V1 + V2 + V3 + V4 + V5 + V6\n        W = W1 + W2 + W3 + W4 + W5 + W6\n\n        # no spanwise and vertical velocity upstream of the turbine\n        V[x_locations < coord.x1 + 10] = 0.0\n        W[x_locations < coord.x1 + 10] = 0.0\n        W[W < 0] = 0\n\n        return V, W\n\n    @property\n    def calculate_VW_velocities(self):\n        \"\"\"\n        Flag to enable the calculation of V- and W-component velocities using\n        methods developed in [1].\n\n        **Note:** This is a virtual property used to \"get\" or \"set\" a value.\n\n        Args:\n            value (bool): Value to set.\n\n        Returns:\n            float: Value currently set.\n\n        Raises:\n            ValueError: Invalid value.\n        \"\"\"\n        return self._calculate_VW_velocities\n\n    @calculate_VW_velocities.setter\n    def calculate_VW_velocities(self, value):\n        if type(value) is not bool:\n            err_msg = (\n                \"Value of calculate_VW_velocities must be type \"\n                + \"float; {} given.\".format(type(value))\n            )\n            self.logger.error(err_msg, stack_info=True)\n            raise ValueError(err_msg)\n        self._calculate_VW_velocities = value\n\n    @property\n    def use_yaw_added_recovery(self):\n        \"\"\"\n        Flag to use yaw added recovery on the wake velocity using methods\n        developed in [1].\n\n        **Note:** This is a virtual property used to \"get\" or \"set\" a value.\n\n        Args:\n            value (bool): Value to set.\n\n        Returns:\n            float: Value currently set.\n\n        Raises:\n            ValueError: Invalid value.\n        \"\"\"\n        return self._use_yaw_added_recovery\n\n    @use_yaw_added_recovery.setter\n    def use_yaw_added_recovery(self, value):\n        if type(value) is not bool:\n            # TODO Shouldn't this be a bool?\n            err_msg = (\n                \"Value of use_yaw_added_recovery must be type \"\n                + \"float; {} given.\".format(type(value))\n            )\n            self.logger.error(err_msg, stack_info=True)\n            raise ValueError(err_msg)\n        self._use_yaw_added_recovery = value\n\n    @property\n    def eps_gain(self):\n        \"\"\"\n        Tuning value for calculating the V- and W- component velocities using\n        methods developed in [1].\n\n        **Note:** This is a virtual property used to \"get\" or \"set\" a value.\n\n        Args:\n            value (bool): Value to set.\n\n        Returns:\n            float: Value currently set.\n\n        Raises:\n            ValueError: Invalid value.\n        \"\"\"\n        return self._eps_gain\n\n    @eps_gain.setter\n    def eps_gain(self, value):\n        if type(value) is not float:\n            err_msg = \"Value of eps_gain must be type \" + \"float; {} given.\".format(\n                type(value)\n            )\n            self.logger.error(err_msg, stack_info=True)\n            raise ValueError(err_msg)\n        self._eps_gain = value\n\n    @staticmethod\n    def mask_upstream_wake(y_locations, turbine_coord, yaw):\n        \"\"\"\n        Calculates values to be used for masking the upstream wake relative to\n        the current turbine.\n\n        Args:\n            y_locations (np.array): Spanwise locations in wake.\n            turbine_coord (:py:obj:`floris.simulation.turbine_map.TurbineMap.coords`):\n                Spatial coordinates of wind turbine.\n            yaw (float): The turbine yaw angle.\n\n        Returns:\n            tuple: tuple containing:\n\n                -   yR (np.array): Y locations to mask upstream wake.\n                -   xR (np.array): X locations to mask upstream wake.\n        \"\"\"\n        yR = y_locations - turbine_coord.x2\n        xR = yR * tand(yaw) + turbine_coord.x1\n        return xR, yR\n\n    @staticmethod\n    def initial_velocity_deficits(U_local, Ct):\n        \"\"\"\n        Calculates the initial velocity deficits used in determining the wake\n        expansion in a Gaussian wake velocity model.\n\n        Args:\n            U_local (np.array): U-component velocities across the flow field.\n            Ct (float): The thrust coefficient of a turbine at the current\n                operating conditions.\n\n        Returns:\n            tuple: tuple containing:\n\n                -   uR (np.array): Initial velocity deficit used in calculation\n                    of wake expansion.\n                -   u0 (np.array): Initial velocity deficit used in calculation\n                    of wake expansion.\n        \"\"\"\n        uR = U_local * Ct / (2.0 * (1 - np.sqrt(1 - Ct)))\n        u0 = U_local * np.sqrt(1 - Ct)\n        return uR, u0\n\n    @staticmethod\n    def initial_wake_expansion(turbine, U_local, veer, uR, u0):\n        \"\"\"\n        Calculates the initial wake widths associated with wake expansion.\n\n        Args:\n            turbine (:py:class:`floris.simulation.turbine.Turbine`):\n                Turbine object.\n            U_local (np.array): U-component velocities across the flow field.\n            veer (float): The amount of veer across the rotor.\n            uR (np.array): Initial velocity deficit used in calculation of wake\n                expansion.\n            u0 (np.array): Initial velocity deficit used in calculation of wake\n                expansion.\n\n        Returns:\n            tuple: tuple containing:\n\n                -   sigma_y0 (np.array): Initial wake width in the spanwise\n                    direction.\n                -   sigma_z0 (np.array): Initial wake width in the vertical\n                    direction.\n        \"\"\"\n        yaw = -1 * turbine.yaw_angle\n        sigma_z0 = turbine.rotor_diameter * 0.5 * np.sqrt(uR / (U_local + u0))\n        sigma_y0 = sigma_z0 * cosd(yaw) * cosd(veer)\n        return sigma_y0, sigma_z0\n\n    @staticmethod\n    def gaussian_function(U, C, r, n, sigma):\n        \"\"\"\n        A general form of the Gaussian function used in the Gaussian wake\n        models.\n\n        Args:\n            U (np.array): U-component velocities across the flow field.\n            C (np.array): Velocity deficit at the wake center normalized by the\n                incoming wake velocity.\n            r (float): Radial distance from the wake center.\n            n (float): Exponent of radial distance from the wake center.\n            sigma (np.array): Standard deviation of the wake.\n\n        Returns:\n            np.array: U (np.array): U-component velocity deficits across the\n            flow field.\n        \"\"\"\n        return U * C * np.exp(-1 * r ** n / (2 * sigma ** 2))\n", "meta": {"hexsha": "1647c53dca3e171473eceef84a5b3b74ff865ff1", "size": 19491, "ext": "py", "lang": "Python", "max_stars_repo_path": "floris/simulation/wake_velocity/gaussianModels/gaussian_model_base.py", "max_stars_repo_name": "eirikur16/flrs", "max_stars_repo_head_hexsha": "c98604593753def05086b54ce82f5551f01d2529", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "floris/simulation/wake_velocity/gaussianModels/gaussian_model_base.py", "max_issues_repo_name": "eirikur16/flrs", "max_issues_repo_head_hexsha": "c98604593753def05086b54ce82f5551f01d2529", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-01-27T23:41:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-07T04:12:23.000Z", "max_forks_repo_path": "floris/simulation/wake_velocity/gaussianModels/gaussian_model_base.py", "max_forks_repo_name": "eirikur16/flrs", "max_forks_repo_head_hexsha": "c98604593753def05086b54ce82f5551f01d2529", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8950276243, "max_line_length": 88, "alphanum_fraction": 0.5396849828, "include": true, "reason": "import numpy", "num_tokens": 4834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.18472683715957755}}
{"text": "import numbers\nfrom typing import Optional, Iterable, Tuple, Union\n\nimport numpy as np\n\nfrom ..algorithms.matrixaverager import MatrixAverager, ErrorPropagationMethod\n\n\nclass Curve:\n    _data: np.ndarray\n\n    def __init__(self):\n        pass\n\n    @property\n    def q(self) -> np.ndarray:\n        return self._data[:, 0]\n\n    @q.setter\n    def q(self, newvalue):\n        self._data[:, 0] = newvalue\n\n    @property\n    def intensity(self) -> np.ndarray:\n        return self._data[:, 1]\n\n    @intensity.setter\n    def intensity(self, newvalue):\n        self._data[:, 1] = newvalue\n\n    @property\n    def uncertainty(self) -> np.ndarray:\n        return self._data[:, 2]\n\n    @uncertainty.setter\n    def uncertainty(self, newvalue):\n        self._data[:, 2] = newvalue\n\n    @property\n    def quncertainty(self) -> np.ndarray:\n        return self._data[:, 3]\n\n    @quncertainty.setter\n    def quncertainty(self, newvalue):\n        self._data[:, 3] = newvalue\n\n    @property\n    def binarea(self) -> np.ndarray:\n        return self._data[:, 4]\n\n    @binarea.setter\n    def binarea(self, newvalue):\n        self._data[:, 4] = newvalue\n\n    @property\n    def pixel(self) -> np.ndarray:\n        return self._data[:, 5]\n\n    @pixel.setter\n    def pixel(self, newvalue):\n        self._data[:, 5] = newvalue\n\n    @classmethod\n    def fromFile(cls, filename: str, *args, **kwargs) -> \"Curve\":\n        data = np.loadtxt(filename, *args, **kwargs)\n        self = cls()\n        self._data = np.empty((data.shape[0], 6)) * np.nan\n        self._data[:, :min(data.shape[1], 6)] = data[:, :min(data.shape[1], 6)]\n        return self\n\n    @classmethod\n    def fromArray(cls, array: np.ndarray) -> \"Curve\":\n        self = cls()\n        self._data = np.empty((array.shape[0], 6), array.dtype) + np.nan\n        self._data[:, :array.shape[1]] = array\n        return self\n\n    def __array__(self) -> np.ndarray:\n        return self._data\n\n    asArray = __array__\n\n    @classmethod\n    def fromVectors(cls, q: np.ndarray, intensity: np.ndarray, uncertainty: Optional[np.ndarray] = None,\n                    quncertainty: Optional[np.ndarray] = None, binarea: Optional[np.ndarray] = None,\n                    pixel: Optional[np.ndarray] = None) -> \"Curve\":\n        assert (q is not None) and (intensity is not None)\n        if not all([\n            q.ndim == 1,\n            intensity.ndim == 1,\n            (uncertainty is None) or (uncertainty.ndim == 1),\n            (quncertainty is None) or (quncertainty.ndim == 1),\n            (binarea is None) or (binarea.ndim == 1),\n            (pixel is None) or (pixel.ndim == 1)\n        ]):\n            raise ValueError('Supplied arrays must be one-dimensional.')\n        if not all([\n            len(intensity) == len(q),\n            (uncertainty is None) or (len(uncertainty) == len(q)),\n            (quncertainty is None) or (len(quncertainty) == len(q)),\n            (binarea is None) or (len(binarea) == len(q)),\n            (pixel is None) or (len(pixel) == len(q))\n        ]):\n            raise ValueError('All vectors must have the same length.')\n        self = cls()\n        self._data = np.empty((len(q), 6))\n        self._data[:, 0] = q\n        self._data[:, 1] = intensity\n        self._data[:, 2] = uncertainty if uncertainty is not None else np.nan\n        self._data[:, 3] = quncertainty if quncertainty is not None else np.nan\n        self._data[:, 4] = binarea if binarea is not None else np.nan\n        self._data[:, 5] = pixel if pixel is not None else np.nan\n        return self\n\n    def trim(self, left: float = -np.inf, right: float = np.inf, bottom=-np.inf, top=np.inf, bypixel: bool = False):\n        if bypixel:\n            xtrimidx = np.logical_and(self._data[:, 5] <= right, self._data[:, 5] >= left)\n        else:\n            xtrimidx = np.logical_and(self._data[:, 0] <= right, self._data[:, 0] >= left)\n        ytrimidx = np.logical_and(self._data[:, 1] <= top, self._data[:, 1] >= bottom)\n        curve = Curve()\n        curve._data = self._data[np.logical_and(xtrimidx, ytrimidx)]\n        return curve\n\n    def __len__(self) -> int:\n        return self._data.shape[0]\n\n    def sanitize(self) -> \"Curve\":\n        return Curve.fromArray(self._data[self.isvalid(), :])\n\n    @classmethod\n    def average(cls, curves: Iterable[\"Curve\"], ierrorpropagation: ErrorPropagationMethod,\n                qerrorpropagation: ErrorPropagationMethod) -> \"Curve\":\n        qavg = MatrixAverager(errorpropagationmethod=qerrorpropagation)\n        iavg = MatrixAverager(errorpropagationmethod=ierrorpropagation)\n        aavg = MatrixAverager(errorpropagationmethod=ierrorpropagation)\n        pavg = MatrixAverager(errorpropagationmethod=ierrorpropagation)\n        for c in curves:\n            qavg.add(c.q, c.quncertainty)\n            iavg.add(c.intensity, c.uncertainty)\n            aavg.add(c.binarea, c.binarea)\n            pavg.add(c.pixel, c.pixel)\n        q, dq = qavg.get()\n        i, di = iavg.get()\n        a = aavg.get()[0]\n        p = pavg.get()[0]\n        return Curve.fromVectors(q, i, di, dq, a, p)\n\n    def isfinite(self) -> np.ndarray:\n        idx = np.logical_and(np.isfinite(self.q, np.isfinite(self.intensity)))\n        for vector in [self.uncertainty, self.quncertainty, self.pixel, self.binarea]:\n            if np.isfinite(vector).sum() > 0:  # if not all elements are NaN\n                idx = np.logical_and(idx, np.isfinite(vector))\n        return idx\n\n    def isvalid(self) -> np.ndarray:\n        idx = np.logical_and(np.isfinite(self.q), np.isfinite(self.intensity))\n        idx = np.logical_and(idx, self.q > 0)\n        for vector in [self.uncertainty, self.quncertainty, self.pixel]:\n            if np.isfinite(vector).sum() > 0:\n                idx = np.logical_and(\n                    idx,\n                    np.logical_and(\n                        np.isfinite(vector),\n                        vector >= 0\n                    ))\n        if np.isfinite(self.binarea).sum() > 0:\n            idx = np.logical_and(\n                idx,\n                np.logical_and(\n                    np.isfinite(self.binarea),\n                    self.binarea > 0\n                ))\n        return idx\n\n    def __getitem__(self, item) -> \"Curve\":\n        if isinstance(item, np.ndarray) and (item.dtype == np.bool):\n            return Curve.fromArray(self._data[item, :])\n\n    def _checkcompatibility(self, other: \"Curve\", maxdifferenceratio: float = 0.005):\n        incompatibility = np.abs(self.q - other.q) / np.max(np.mean((self.q, other.q)), axis=0) * 2\n        if np.any(incompatibility[np.isfinite(incompatibility)] > maxdifferenceratio):  # 0.01 means 1%\n            raise ValueError(\n                f'The two q-scales are incompatible. Max. incompatibility: {incompatibility[np.isfinite(incompatibility)].max()}')\n\n    def __sub__(self, other: Union[\"Curve\", numbers.Real, Tuple[numbers.Real, numbers.Real]]) -> \"Curve\":\n        if isinstance(other, Curve):\n            self._checkcompatibility(other)\n            return self.fromVectors(\n                q=0.5 * (self.q + other.q),\n                intensity=self.intensity - other.intensity,\n                uncertainty=(self.uncertainty ** 2 + other.uncertainty ** 2) ** 0.5,\n                quncertainty=(self.quncertainty ** 2 + other.quncertainty ** 2) ** 0.5 / 2.0,\n                binarea=None,\n                pixel=None\n            )\n        elif isinstance(other, numbers.Real):\n            return self.fromVectors(\n                q=self.q,\n                intensity=self.intensity - other,\n                uncertainty=self.uncertainty,\n                quncertainty=self.quncertainty,\n                binarea=self.binarea,\n                pixel=self.pixel\n            )\n        elif isinstance(other, tuple) and (len(other) == 2) and isinstance(other[0], numbers.Real) and isinstance(\n                other[1], numbers.Real):\n            return self.fromVectors(\n                q=self.q,\n                intensity=self.intensity - other[0],\n                uncertainty=(self.uncertainty ** 2 + other[1] ** 2) ** 0.5,\n                quncertainty=self.quncertainty,\n                binarea=self.binarea,\n                pixel=self.pixel\n            )\n        else:\n            return NotImplemented\n\n    def __add__(self, other: Union[\"Curve\", numbers.Real, Tuple[numbers.Real, numbers.Real]]) -> \"Curve\":\n        if isinstance(other, Curve):\n            self._checkcompatibility(other)\n            return self.fromVectors(\n                q=0.5 * (self.q + other.q),\n                intensity=self.intensity + other.intensity,\n                uncertainty=(self.uncertainty ** 2 + other.uncertainty ** 2) ** 0.5,\n                quncertainty=(self.quncertainty ** 2 + other.quncertainty ** 2) ** 0.5 / 2.0,\n                binarea=None,\n                pixel=None\n            )\n        elif isinstance(other, numbers.Real):\n            return self.fromVectors(\n                q=self.q,\n                intensity=self.intensity + other,\n                uncertainty=self.uncertainty,\n                quncertainty=self.quncertainty,\n                binarea=self.binarea,\n                pixel=self.pixel\n            )\n        elif isinstance(other, tuple) and (len(other) == 2) and isinstance(other[0], numbers.Real) and isinstance(\n                other[1], numbers.Real):\n            return self.fromVectors(\n                q=self.q,\n                intensity=self.intensity + other[0],\n                uncertainty=(self.uncertainty ** 2 + other[1] ** 2) ** 0.5,\n                quncertainty=self.quncertainty,\n                binarea=self.binarea,\n                pixel=self.pixel\n            )\n        else:\n            return NotImplemented\n\n    def __rsub__(self, other: Union[numbers.Real, Tuple[numbers.Real, numbers.Real]]) -> \"Curve\":\n        if isinstance(other, numbers.Real):\n            return self.fromVectors(\n                q=self.q,\n                intensity=other - self.intensity,\n                uncertainty=self.uncertainty,\n                quncertainty=self.quncertainty,\n                binarea=self.binarea,\n                pixel=self.pixel\n            )\n        elif isinstance(other, tuple) and (len(other) == 2) and isinstance(other[0], numbers.Real) and isinstance(\n                other[1], numbers.Real):\n            return self.fromVectors(\n                q=self.q,\n                intensity=other[0] - self.intensity,\n                uncertainty=(self.uncertainty ** 2 + other[1] ** 2) ** 0.5,\n                quncertainty=self.quncertainty,\n                binarea=self.binarea,\n                pixel=self.pixel\n            )\n        else:\n            return NotImplemented\n\n    def __radd__(self, other: Union[numbers.Real, Tuple[numbers.Real, numbers.Real]]) -> \"Curve\":\n        if isinstance(other, numbers.Real):\n            return self.fromVectors(\n                q=self.q,\n                intensity=self.intensity + other,\n                uncertainty=self.uncertainty,\n                quncertainty=self.quncertainty,\n                binarea=self.binarea,\n                pixel=self.pixel\n            )\n        elif isinstance(other, tuple) and (len(other) == 2) and isinstance(other[0], numbers.Real) and isinstance(\n                other[1], numbers.Real):\n            return self.fromVectors(\n                q=self.q,\n                intensity=self.intensity + other[0],\n                uncertainty=(self.uncertainty ** 2 + other[1] ** 2) ** 0.5,\n                quncertainty=self.quncertainty,\n                binarea=self.binarea,\n                pixel=self.pixel\n            )\n        else:\n            return NotImplemented\n\n    def __truediv__(self, other: Union[\"Curve\", numbers.Real, Tuple[numbers.Real, numbers.Real]]) -> \"Curve\":\n        if isinstance(other, Curve):\n            self._checkcompatibility(other)\n            return self.fromVectors(\n                q=0.5 * (self.q + other.q),\n                intensity=self.intensity / other.intensity,\n                uncertainty=(\n                                    self.uncertainty ** 2 / other.intensity ** 2 + other.uncertainty ** 2 * self.intensity ** 2 / other.intensity ** 4) ** 0.5,\n                quncertainty=(self.quncertainty ** 2 + other.quncertainty ** 2) ** 0.5 / 2.0,\n                binarea=None,\n                pixel=None\n            )\n        elif isinstance(other, numbers.Real):\n            return self.fromVectors(\n                q=self.q,\n                intensity=self.intensity / other,\n                uncertainty=np.abs(self.uncertainty / other),\n                quncertainty=self.quncertainty,\n                binarea=self.binarea,\n                pixel=self.pixel\n            )\n        elif isinstance(other, tuple) and (len(other) == 2) and isinstance(other[0], numbers.Real) and isinstance(\n                other[1], numbers.Real):\n            return self.fromVectors(\n                q=self.q,\n                intensity=self.intensity / other[0],\n                uncertainty=(self.uncertainty ** 2 / other[0] ** 2 + other[1] ** 2 * self.intensity ** 2 / other[\n                    0] ** 4) ** 0.5,\n                quncertainty=self.quncertainty,\n                binarea=self.binarea,\n                pixel=self.pixel\n            )\n        else:\n            return NotImplemented\n\n    def __mul__(self, other: Union[\"Curve\", numbers.Real, Tuple[numbers.Real, numbers.Real]]) -> \"Curve\":\n        if isinstance(other, Curve):\n            self._checkcompatibility(other)\n            return self.fromVectors(\n                q=0.5 * (self.q + other.q),\n                intensity=self.intensity * other.intensity,\n                uncertainty=(\n                                    self.uncertainty ** 2 * other.intensity ** 2 + other.uncertainty ** 2 * self.intensity ** 2) ** 0.5,\n                quncertainty=(self.quncertainty ** 2 + other.quncertainty ** 2) ** 0.5 / 2.0,\n                binarea=None,\n                pixel=None\n            )\n        elif isinstance(other, numbers.Real):\n            return self.fromVectors(\n                q=self.q,\n                intensity=self.intensity * other,\n                uncertainty=np.abs(self.uncertainty * other),\n                quncertainty=self.quncertainty,\n                binarea=self.binarea,\n                pixel=self.pixel\n            )\n        elif isinstance(other, tuple) and (len(other) == 2) and isinstance(other[0], numbers.Real) and isinstance(\n                other[1], numbers.Real):\n            return self.fromVectors(\n                q=self.q,\n                intensity=self.intensity * other[0],\n                uncertainty=(self.uncertainty ** 2 * other[0] ** 2 + self.intensity ** 2 * other[1] ** 2) ** 0.5,\n                quncertainty=self.quncertainty,\n                binarea=self.binarea,\n                pixel=self.pixel\n            )\n        else:\n            return NotImplemented\n\n    def __rtruediv__(self, other: Union[numbers.Real, Tuple[numbers.Real, numbers.Real]]) -> \"Curve\":\n        if isinstance(other, numbers.Real):\n            return self.fromVectors(\n                q=self.q,\n                intensity=other / self.intensity,\n                uncertainty=np.abs(other * self.uncertainty / self.intensity ** 2),\n                quncertainty=self.quncertainty,\n                binarea=self.binarea,\n                pixel=self.pixel\n            )\n        elif isinstance(other, tuple) and (len(other) == 2) and isinstance(other[0], numbers.Real) and isinstance(\n                other[1], numbers.Real):\n            return self.fromVectors(\n                q=self.q,\n                intensity=other[0] / self.intensity,\n                uncertainty=(self.uncertainty ** 2 / self.intensity ** 4 * other[0] ** 2 + other[\n                    1] ** 2 / self.intensity ** 2) ** 0.5,\n                quncertainty=self.quncertainty,\n                binarea=self.binarea,\n                pixel=self.pixel\n            )\n        else:\n            return NotImplemented\n\n    def __rmul__(self, other: Union[numbers.Real, Tuple[numbers.Real, numbers.Real]]) -> \"Curve\":\n        if isinstance(other, numbers.Real):\n            return self.fromVectors(\n                q=self.q,\n                intensity=self.intensity * other,\n                uncertainty=np.abs(self.uncertainty * other),\n                quncertainty=self.quncertainty,\n                binarea=self.binarea,\n                pixel=self.pixel\n            )\n        elif isinstance(other, tuple) and (len(other) == 2) and isinstance(other[0], numbers.Real) and isinstance(\n                other[1], numbers.Real):\n            return self.fromVectors(\n                q=self.q,\n                intensity=self.intensity * other[0],\n                uncertainty=(self.uncertainty ** 2 * other[0] ** 2 + self.intensity ** 2 * other[1] ** 2) ** 0.5,\n                quncertainty=self.quncertainty,\n                binarea=self.binarea,\n                pixel=self.pixel\n            )\n        else:\n            return NotImplemented\n", "meta": {"hexsha": "e5ceb9f4e9edc457b3cd26ba6cd4bb60158e2e20", "size": 16920, "ext": "py", "lang": "Python", "max_stars_repo_path": "cct/core2/dataclasses/curve.py", "max_stars_repo_name": "awacha/cct", "max_stars_repo_head_hexsha": "be1adbed2533df15c778051f3f4f9da0749c873a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-11-04T16:37:39.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-04T16:37:39.000Z", "max_issues_repo_path": "cct/core2/dataclasses/curve.py", "max_issues_repo_name": "awacha/cct", "max_issues_repo_head_hexsha": "be1adbed2533df15c778051f3f4f9da0749c873a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cct/core2/dataclasses/curve.py", "max_forks_repo_name": "awacha/cct", "max_forks_repo_head_hexsha": "be1adbed2533df15c778051f3f4f9da0749c873a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-05T02:50:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-05T02:50:43.000Z", "avg_line_length": 40.9685230024, "max_line_length": 159, "alphanum_fraction": 0.5432033097, "include": true, "reason": "import numpy", "num_tokens": 3930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.18472683715957755}}
{"text": "\"\"\"\nFunctions for aeri retrievals.\n\n\"\"\"\n\nimport numpy as np\nfrom scipy.optimize import brentq\n\nfrom act.retrievals.irt import irt_response_function, sum_function_irt\n\n\ndef aeri2irt(\n    aeri_ds,\n    wnum_name='wnum',\n    rad_name='mean_rad',\n    hatch_name='hatchOpen',\n    tolerance=0.1,\n    temp_low=150.0,\n    temp_high=320.0,\n    maxiter=200,\n):\n    \"\"\"\n    This function will integrate over the correct wavenumber values to produce\n    the effective IRT temperature.\n\n    As a note from the ARM IRT Instrument Handbook\n    A positive bias of the sky temperature is exhibited by the downwelling IRT,\n    compared to the AERI, during clear-sky conditions when the sky temperature\n    is less than ~180K. The effect depends on the characteristics of the\n    individual IRT and the internal reference temperature of the IRT. The\n    greatest difference compared to AERI will occur when the sky is very clear,\n    dry, and cold and the ambient temperature is relatively hot, maximizing the\n    difference in temperature between the sky and instrument, and the\n    calibration of the IRT at the lower limit of 223K was not performed\n    accurately. This bias is especially apparent at high-latitude sites\n    (e.g., NSA, OLI, and AWR).\n\n    https://www.arm.gov/publications/tech_reports/handbooks/irt_handbook.pdf\n\n    Author - Ken Kehoe\n\n    Parameters\n    ----------\n    aeri_ds : Xarray Dataset Object\n        The Dataset object containing AERI data.\n    wnum_name : str\n        The variable name for coordinate dimention of wave number Xarray Dataset.\n    hatch_name : str or None\n        The variable name for hatch status. If set to None will not try to set\n        when hatch is not opent to NaN.\n    rad_name : str\n        The variable name for mean radiance in Xarray Dataset.\n    tolerance : float\n        The tolerance value to try and match for returned temperature.\n    temp_low : float\n        The initial low value to use in zbren function to invert radiances.\n    temp_high : float\n        The initial low value to use in zbren function to invert radiances.\n    maxiter : int\n        The maximum number if iterations to use with invertion process.\n        Prevents runaway processes.\n\n    Returns\n    -------\n    obj : Xarray Dataset Object or None\n        The aeri_ds Dataset with new DataArray of temperatures added under\n        variable name 'aeri_irt_equiv_temperature'.\n\n    \"\"\"\n    # Get data values\n    rf_wnum, rf = irt_response_function()\n    wnum = aeri_ds[wnum_name].values\n    mean_rad = aeri_ds[rad_name].values\n\n    # Pull out AERI data for correct wavenumbers and apply response function --;\n    index = np.where((wnum >= (rf_wnum[0] - 0.001)) & (wnum <= (rf_wnum[-1] + 0.001)))[0]\n    if index.size == 0:\n        raise ValueError('No wavenumbers match for aeri2irt')\n\n    wnum = wnum[index]\n    mean_rad = mean_rad[:, index]\n    # If the wavenumbers in AERI data are not close enough to response function\n    # match the wavenumbers and adjust.\n    atol = 0.001\n    if not np.all(np.isclose(wnum, rf_wnum, atol=atol)):\n        index_wnum = []\n        index_rf = []\n        for ii in range(wnum.size):\n            idx = (np.abs(wnum[ii] - rf_wnum)).argmin()\n            if np.isclose(wnum[ii], rf_wnum[idx], atol=atol):\n                index_wnum.append(ii)\n                index_rf.append(idx)\n        mean_rad = mean_rad[:, index_wnum]\n        rf = rf[index_rf]\n\n    # Apply response function to AERI radiance\n    mean_rad = mean_rad * rf\n\n    # Sum along wavenumber dimention to get a single value for each time step\n    mean_rad = np.nansum(mean_rad, axis=1)\n\n    # Loop over each time step of the AERI data and through the use of\n    # solving for zero determine the AERI equivlante IRT sky temperature.\n    aeri_irt_vals = np.full(mean_rad.size, np.nan, dtype=mean_rad.dtype)\n\n    # Look for when the hatch is not in Open position and set values to NaN.\n    if hatch_name is not None:\n        flag_values = aeri_ds[hatch_name].attrs['flag_values']\n        flag_meanings = aeri_ds[hatch_name].attrs['flag_meanings']\n        if not isinstance(flag_meanings, list):\n            flag_meanings = flag_meanings.split()\n        flag_meanings = [att.lower() for att in flag_meanings]\n        if not isinstance(flag_values, list):\n            flag_values = flag_values.split()\n            flag_values = [int(att) for att in flag_values]\n        value = flag_values[flag_meanings.index('open')]\n        mean_rad[aeri_ds[hatch_name].values != value] = np.nan\n\n    for ii in range(mean_rad.size):\n        if np.isnan(mean_rad[ii]):\n            continue\n        else:\n            try:\n                aeri_irt_vals[ii] = brentq(\n                    sum_function_irt,\n                    temp_low,\n                    temp_high,\n                    args=(mean_rad[ii],),\n                    xtol=tolerance,\n                    maxiter=maxiter,\n                )\n            except ValueError:\n                pass\n\n    # Add new values to Xarray Dataset\n    aeri_ds['aeri_irt_equiv_temperature'] = (\n        'time',\n        aeri_irt_vals,\n        {'long_name': 'Derived IRT equivalent temperatrues from AERI', 'units': 'K'},\n    )\n\n    return aeri_ds\n", "meta": {"hexsha": "cbcd7690251620e24d42a6d305947d7c02753e52", "size": 5174, "ext": "py", "lang": "Python", "max_stars_repo_path": "act/retrievals/aeri.py", "max_stars_repo_name": "jrobrien91/ACT", "max_stars_repo_head_hexsha": "604b93d75366d23029f89d88df9053d52825c214", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-03-11T19:41:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-17T08:34:19.000Z", "max_issues_repo_path": "act/retrievals/aeri.py", "max_issues_repo_name": "jrobrien91/ACT", "max_issues_repo_head_hexsha": "604b93d75366d23029f89d88df9053d52825c214", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 127, "max_issues_repo_issues_event_min_datetime": "2019-03-18T12:24:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-06T20:53:06.000Z", "max_forks_repo_path": "act/retrievals/aeri.py", "max_forks_repo_name": "jrobrien91/ACT", "max_forks_repo_head_hexsha": "604b93d75366d23029f89d88df9053d52825c214", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2019-03-11T15:30:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-01T19:10:11.000Z", "avg_line_length": 36.1818181818, "max_line_length": 89, "alphanum_fraction": 0.6524932354, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.18472683715957752}}
{"text": "# coding: utf-8\n# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\nfrom __future__ import division, unicode_literals\n\nimport warnings\nimport subprocess\nimport numpy as np\nimport os.path\n\nfrom pymatgen.core import Structure, Lattice, PeriodicSite, Molecule\nfrom pymatgen.util.coord import lattice_points_in_supercell\nfrom pymatgen.vis.structure_vtk import EL_COLORS\n\nfrom monty.json import MSONable\nfrom monty.os.path import which\nfrom operator import itemgetter\nfrom collections import namedtuple\nfrom scipy.spatial import KDTree\n\ntry:\n    import networkx as nx\n    from networkx.readwrite import json_graph\n    from networkx.drawing.nx_agraph import write_dot\nexcept ImportError:\n    raise ImportError(\"This module requires the NetworkX \"\n                      \"graph library to be installed.\")\n\nimport logging\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n__author__ = \"Matthew Horton\"\n__version__ = \"0.1\"\n__maintainer__ = \"Matthew Horton\"\n__email__ = \"mkhorton@lbl.gov\"\n__status__ = \"Beta\"\n__date__ = \"August 2017\"\n\nConnectedSite = namedtuple('ConnectedSite', 'periodic_site, jimage, index, weight, dist')\n\nclass StructureGraph(MSONable):\n\n    def __init__(self, structure, graph_data):\n        \"\"\"\n        If constructing this class manually, use the `with_empty_graph`\n        method or `with_local_env_strategy` method (using an algorithm\n        provided by the `local_env` module, such as O'Keeffe).\n\n        This class that contains connection information:\n        relationships between sites represented by a Graph structure,\n        and an associated structure object.\n\n        This class uses the NetworkX package to store and operate\n        on the graph itself, but contains a lot of helper methods\n        to make associating a graph with a given crystallographic\n        structure easier.\n\n        Use cases for this include storing bonding information,\n        NMR J-couplings, Heisenberg exchange parameters, etc.\n\n        For periodic graphs, class stores information on the graph\n        edges of what lattice image the edge belongs to.\n\n        :param *args: same as in :class: `pymatgen.core.Structure`\n        :param graph_data: dict containing graph information in\n        dict format, not intended to be constructed manually\n        \"\"\"\n\n        self.structure = structure\n        self.graph = nx.readwrite.json_graph.adjacency_graph(graph_data)\n\n        # tidy up edge attr dicts, reading to/from json duplicates\n        # information\n        for u, v, k, d in self.graph.edges(keys=True, data=True):\n            if 'id' in d:\n                del d['id']\n            if 'key' in d:\n                del d['key']\n\n    @classmethod\n    def with_empty_graph(cls, structure, name=\"bonds\",\n                        edge_weight_name=None,\n                         edge_weight_units=None):\n        \"\"\"\n        Constructor for StructureGraph, returns a StructureGraph\n        object with an empty graph (no edges, only nodes defined\n        that correspond to Sites in Structure).\n\n        :param structure (Structure):\n        :param name (str): name of graph, e.g. \"bonds\"\n        :param edge_weight_name (str): name of edge weights,\n        e.g. \"bond_length\" or \"exchange_constant\"\n        :param edge_weight_units (str): name of edge weight units\n        e.g. \"Å\" or \"eV\"\n        :return (StructureGraph):\n        \"\"\"\n\n        if edge_weight_name and (edge_weight_units is None):\n            raise ValueError(\"Please specify units associated \"\n                             \"with your edge weights. Can be \"\n                             \"empty string if arbitrary or \"\n                             \"dimensionless.\")\n\n        # construct graph with one node per site\n        # graph attributes don't change behavior of graph,\n        # they're just for book-keeping\n        graph = nx.MultiDiGraph(edge_weight_name=edge_weight_name,\n                                edge_weight_units=edge_weight_units,\n                                name=name)\n        graph.add_nodes_from(range(len(structure)))\n\n        graph_data = json_graph.adjacency_data(graph)\n\n        return cls(structure, graph_data=graph_data)\n\n    @staticmethod\n    def with_local_env_strategy(structure, strategy):\n        \"\"\"\n        Constructor for StructureGraph, using a strategy\n        from  :Class: `pymatgen.analysis.local_env`.\n\n        :param structure: Structure object\n        :param strategy: an instance of a\n         :Class: `pymatgen.analysis.local_env.NearNeighbors`\n         object\n        :return:\n        \"\"\"\n\n        sg = StructureGraph.with_empty_graph(structure, name=\"bonds\",\n                                             edge_weight_name=\"weight\",\n                                             edge_weight_units=\"\")\n\n        for n in range(len(structure)):\n            neighbors = strategy.get_nn_info(structure, n)\n            for neighbor in neighbors:\n\n                # local_env will always try to add two edges\n                # for any one bond, one from site u to site v\n                # and another form site v to site u: this is\n                # harmless, so warn_duplicates=False\n                sg.add_edge(from_index=n,\n                            from_jimage=(0, 0, 0),\n                            to_index=neighbor['site_index'],\n                            to_jimage=neighbor['image'],\n                            weight=neighbor['weight'],\n                            warn_duplicates=False)\n\n        return sg\n\n    @property\n    def name(self):\n        \"\"\"\n        :return: Name of graph\n        \"\"\"\n        return self.graph.graph['name']\n\n    @property\n    def edge_weight_name(self):\n        \"\"\"\n        :return: Name of the edge weight property of graph\n        \"\"\"\n        return self.graph.graph['edge_weight_name']\n\n    @property\n    def edge_weight_unit(self):\n        \"\"\"\n        :return: Units of the edge weight property of graph\n        \"\"\"\n        return self.graph.graph['edge_weight_units']\n\n    def add_edge(self, from_index, to_index,\n                 from_jimage=(0, 0, 0), to_jimage=None,\n                 weight=None, warn_duplicates=True):\n        \"\"\"\n        Add edge to graph.\n\n        Since physically a 'bond' (or other connection\n        between sites) doesn't have a direction, from_index,\n        from_jimage can be swapped with to_index, to_jimage.\n\n        However, images will always always be shifted so that\n        from_index < to_index and from_jimage becomes (0, 0, 0).\n\n        :param from_index: index of site connecting from\n        :param to_index: index of site connecting to\n        :param from_jimage (tuple of ints): lattice vector of periodic\n        image, e.g. (1, 0, 0) for periodic image in +x direction\n        :param to_jimage (tuple of ints): lattice vector of image\n        :param weight (float): e.g. bond length\n        :param warn_duplicates (bool): if True, will warn if\n        trying to add duplicate edges (duplicate edges will not\n        be added in either case)\n        :return:\n        \"\"\"\n\n        # this is not necessary for the class to work, but\n        # just makes it neater\n        if to_index < from_index:\n            to_index, from_index = from_index, to_index\n            to_jimage, from_jimage = from_jimage, to_jimage\n\n        # constrain all from_jimages to be (0, 0, 0),\n        # initial version of this class worked even if\n        # from_jimage != (0, 0, 0), but making this\n        # assumption simplifies logic later\n        if not np.array_equal(from_jimage, (0, 0, 0)):\n            shift = from_jimage\n            from_jimage = np.subtract(from_jimage, shift)\n            to_jimage = np.subtract(to_jimage, shift)\n\n        # automatic detection of to_jimage if user doesn't specify\n        # will try and detect all equivalent images and add multiple\n        # edges if appropriate\n        if to_jimage is None:\n            # assume we want the closest site\n            warnings.warn(\"Please specify to_jimage to be unambiguous, \"\n                          \"trying to automatically detect.\")\n            dist, to_jimage = self.structure[from_index].distance_and_image(self.structure[to_index])\n            if dist == 0:\n                # this will happen when from_index == to_index,\n                # typically in primitive single-atom lattices\n                images = [1, 0, 0], [0, 1, 0], [0, 0, 1]\n                dists = []\n                for image in images:\n                    dists.append(self.structure[from_index].distance_and_image(self.structure[from_index],\n                                                                               jimage=image)[0])\n                dist = min(dists)\n            equiv_sites = self.structure.get_neighbors_in_shell(self.structure[from_index].coords,\n                                                                dist,\n                                                                dist*0.01,\n                                                                include_index=True)\n            for site, dist, to_index in equiv_sites:\n                to_jimage = np.subtract(site.frac_coords, self.structure[from_index].frac_coords)\n                to_jimage = to_jimage.astype(int)\n                self.add_edge(from_index=from_index, from_jimage=(0, 0, 0),\n                              to_jimage=to_jimage, to_index=to_index)\n            return\n\n        from_jimage, to_jimage = tuple(from_jimage), tuple(to_jimage)\n\n        # check we're not trying to add a duplicate edge\n        # there should only ever be at most one edge\n        # between a given (site, jimage) pair and another\n        # (site, jimage) pair\n        existing_edge_data = self.graph.get_edge_data(from_index, to_index)\n        if existing_edge_data:\n            for key, d in existing_edge_data.items():\n                if d[\"to_jimage\"] == to_jimage:\n                    if warn_duplicates:\n                        warnings.warn(\"Trying to add an edge that already exists from \"\n                                      \"site {} to site {} in {}.\".format(from_index,\n                                                                         to_index,\n                                                                         to_jimage))\n                    return\n\n        if weight:\n            self.graph.add_edge(from_index, to_index,\n                                from_jimage=from_jimage, to_jimage=to_jimage,\n                                weight=weight)\n        else:\n            self.graph.add_edge(from_index, to_index,\n                                from_jimage=from_jimage, to_jimage=to_jimage)\n\n    def get_connected_sites(self, n, jimage=(0, 0, 0)):\n        \"\"\"\n        Returns a named tuple of neighbors of site n:\n        periodic_site, jimage, index, weight.\n        Index is the index of the corresponding site\n        in the original structure, weight can be\n        None if not defined.\n        :param n: index of Site in Structure\n        :param jimage: lattice vector of site\n        :return: list of ConnectedSite tuples,\n        sorted by closest first\n        \"\"\"\n\n        connected_sites = set()\n\n        out_edges = [(u, v, d, 'out') for u, v, d in self.graph.out_edges(n, data=True)]\n        in_edges = [(u, v, d, 'in') for u, v, d in self.graph.in_edges(n, data=True)]\n\n        for u, v, d, dir in out_edges + in_edges:\n\n            to_jimage = d['to_jimage']\n\n            if dir == 'in':\n                u, v = v, u\n                to_jimage = np.multiply(-1, to_jimage)\n\n            site_d = self.structure[v].as_dict()\n            site_d['abc'] = np.add(site_d['abc'], to_jimage).tolist()\n            to_jimage = tuple(map(int, np.add(to_jimage, jimage)))\n            periodic_site = PeriodicSite.from_dict(site_d)\n\n            weight = d.get('weight', None)\n\n            # from_site if jimage arg != (0, 0, 0)\n            relative_jimage = np.subtract(to_jimage, jimage)\n            dist = self.structure[u].distance(self.structure[v], jimage=relative_jimage)\n\n            connected_site = ConnectedSite(periodic_site=periodic_site,\n                                           jimage=to_jimage,\n                                           index=v,\n                                           weight=weight,\n                                           dist=dist)\n\n            connected_sites.add(connected_site)\n\n        # return list sorted by closest sites first\n        connected_sites = list(connected_sites)\n        connected_sites.sort(key=lambda x: x.dist)\n\n        return connected_sites\n\n    def get_coordination_of_site(self, n):\n        \"\"\"\n        Returns the number of neighbors of site n.\n        In graph terms, simply returns degree\n        of node corresponding to site n.\n        :param n: index of site\n        :return (int):\n        \"\"\"\n        return self.graph.degree(n)\n\n    def draw_graph_to_file(self, filename=\"graph\",\n                           diff=None,\n                           hide_unconnected_nodes=False,\n                           hide_image_edges=True,\n                           edge_colors=False,\n                           node_labels=False,\n                           weight_labels=False,\n                           image_labels=False,\n                           color_scheme=\"VESTA\",\n                           keep_dot=False,\n                           algo=\"fdp\"):\n        \"\"\"\n        Draws graph using GraphViz.\n\n        The networkx graph object itself can also be drawn\n        with networkx's in-built graph drawing methods, but\n        note that this might give misleading results for\n        multigraphs (edges are super-imposed on each other).\n\n        If visualization is difficult to interpret,\n        `hide_image_edges` can help, especially in larger\n        graphs.\n\n        :param filename: filename to output, will detect filetype\n        from extension (any graphviz filetype supported, such as\n        pdf or png)\n        :param diff (StructureGraph): an additional graph to\n        compare with, will color edges red that do not exist in diff\n        and edges green that are in diff graph but not in the\n        reference graph\n        :param hide_unconnected_nodes: if True, hide unconnected\n        nodes\n        :param hide_image_edges: if True, do not draw edges that\n        go through periodic boundaries\n        :param edge_colors (bool): if True, use node colors to\n        color edges\n        :param node_labels (bool): if True, label nodes with\n        species and site index\n        :param weight_labels (bool): if True, label edges with\n        weights\n        :param image_labels (bool): if True, label edges with\n        their periodic images (usually only used for debugging,\n        edges to periodic images always appear as dashed lines)\n        :param color_scheme (str): \"VESTA\" or \"JMOL\"\n        :param keep_dot (bool): keep GraphViz .dot file for later\n        visualization\n        :param algo: any graphviz algo, \"neato\" (for simple graphs)\n        or \"fdp\" (for more crowded graphs) usually give good outputs\n        :return:\n        \"\"\"\n\n        if not which(algo):\n            raise RuntimeError(\"StructureGraph graph drawing requires \"\n                               \"GraphViz binaries to be in the path.\")\n\n        # Developer note: NetworkX also has methods for drawing\n        # graphs using matplotlib, these also work here. However,\n        # a dedicated tool like GraphViz allows for much easier\n        # control over graph appearance and also correctly displays\n        # mutli-graphs (matplotlib can superimpose multiple edges).\n\n        g = self.graph.copy()\n\n        g.graph = {'nodesep': 10.0, 'dpi': 300, 'overlap': \"false\"}\n\n        # add display options for nodes\n        for n in g.nodes():\n\n            # get label by species name\n            label = \"{}({})\".format(str(self.structure[n].specie), n) if node_labels else \"\"\n\n            # use standard color scheme for nodes\n            c = EL_COLORS[color_scheme].get(str(self.structure[n].specie.symbol), [0, 0, 0])\n\n            # get contrasting font color\n            # magic numbers account for perceived luminescence\n            # https://stackoverflow.com/questions/1855884/determine-font-color-based-on-background-color\n            fontcolor = '#000000' if 1 - (c[0] * 0.299 + c[1] * 0.587\n                                          + c[2] * 0.114) / 255 < 0.5 else '#ffffff'\n\n            # convert color to hex string\n            color = \"#{:02x}{:02x}{:02x}\".format(c[0], c[1], c[2])\n\n            g.add_node(n, fillcolor=color, fontcolor=fontcolor, label=label,\n                       fontname=\"Helvetica-bold\", style=\"filled\", shape=\"circle\")\n\n        edges_to_delete = []\n\n        # add display options for edges\n        for u, v, k, d in g.edges(keys=True, data=True):\n\n            # retrieve from/to images, set as origin if not defined\n            to_image = d['to_jimage']\n\n            # set edge style\n            d['style'] = \"solid\"\n            if to_image != (0, 0, 0):\n                d['style'] = \"dashed\"\n                if hide_image_edges:\n                    edges_to_delete.append((u, v, k))\n\n            # don't show edge directions\n            d['arrowhead'] = \"none\"\n\n            # only add labels for images that are not the origin\n            if image_labels:\n                d['headlabel'] = \"\" if to_image == (0, 0, 0) else \"to {}\".format((to_image))\n                d['arrowhead'] = \"normal\" if d['headlabel'] else \"none\"\n\n            # optionally color edges using node colors\n            color_u = g.node[u]['fillcolor']\n            color_v = g.node[v]['fillcolor']\n            d['color_uv'] = \"{};0.5:{};0.5\".format(color_u, color_v) if edge_colors else \"#000000\"\n\n            # optionally add weights to graph\n            if weight_labels:\n                units = g.graph.get('edge_weight_units', \"\")\n                if d.get('weight'):\n                    d['label'] = \"{:.2f} {}\".format(d['weight'], units)\n\n            # update edge with our new style attributes\n            g.edges[u, v, k].update(d)\n\n        # optionally remove periodic image edges,\n        # these can be confusing due to periodic boundaries\n        if hide_image_edges:\n            for edge_to_delete in edges_to_delete:\n                g.remove_edge(*edge_to_delete)\n\n        # optionally hide unconnected nodes,\n        # these can appear when removing periodic edges\n        if hide_unconnected_nodes:\n            g = g.subgraph([n for n in g.degree() if g.degree()[n] != 0])\n\n        # optionally highlight differences with another graph\n        if diff:\n            diff = self.diff(diff, strict=True)\n            green_edges = []\n            red_edges = []\n            for u, v, k, d in g.edges(keys=True, data=True):\n                if (u, v, d['to_jimage']) in diff['self']:\n                    # edge has been deleted\n                    red_edges.append((u, v, k))\n                elif (u, v, d['to_jimage']) in diff['other']:\n                    # edge has been added\n                    green_edges.append((u, v, k))\n            for u, v, k in green_edges:\n                g.edges[u, v, k].update({'color_uv': '#00ff00'})\n            for u, v, k in red_edges:\n                g.edges[u, v, k].update({'color_uv': '#ff0000'})\n\n        basename, extension = os.path.splitext(filename)\n        extension = extension[1:]\n\n        write_dot(g, basename+\".dot\")\n\n        with open(filename, \"w\") as f:\n\n            args = [algo, \"-T\", extension, basename+\".dot\"]\n            rs = subprocess.Popen(args,\n                                  stdout=f,\n                                  stdin=subprocess.PIPE, close_fds=True)\n            rs.communicate()\n            if rs.returncode != 0:\n                raise RuntimeError(\"{} exited with return code {}.\".format(algo, rs.returncode))\n\n        if not keep_dot:\n            os.remove(basename+\".dot\")\n\n    def as_dict(self):\n        \"\"\"\n        As in :Class: `pymatgen.core.Structure` except\n        with using `to_dict_of_dicts` from NetworkX\n        to store graph information.\n        \"\"\"\n\n        d = {\"@module\": self.__class__.__module__,\n             \"@class\": self.__class__.__name__,\n             \"structure\": self.structure.as_dict(),\n             \"graphs\": json_graph.adjacency_data(self.graph)}\n\n        return d\n\n    @classmethod\n    def from_dict(cls, d):\n        \"\"\"\n        As in :Class: `pymatgen.core.Structure` except\n        restoring graphs using `from_dict_of_dicts`\n        from NetworkX to restore graph information.\n        \"\"\"\n        s = Structure.from_dict(d['structure'])\n        return cls(s, d['graphs'])\n\n    def __mul__(self, scaling_matrix):\n        \"\"\"\n        Replicates the graph, creating a supercell,\n        intelligently joining together\n        edges that lie on periodic boundaries.\n        In principle, any operations on the expanded\n        graph could also be done on the original\n        graph, but a larger graph can be easier to\n        visualize and reason about.\n        :param scaling_matrix: same as Structure.__mul__\n        :return:\n        \"\"\"\n\n        # Developer note: a different approach was also trialed, using\n        # a simple Graph (instead of MultiDiGraph), with node indices\n        # representing both site index and periodic image. Here, the\n        # number of nodes != number of sites in the Structure. This\n        # approach has many benefits, but made it more difficult to\n        # keep the graph in sync with its corresponding Structure.\n\n        # Broadly, it would be easier to multiply the Structure\n        # *before* generating the StructureGraph, but this isn't\n        # possible when generating the graph using critic2 from\n        # charge density.\n\n        # Multiplication works by looking for the expected position\n        # of an image node, and seeing if that node exists in the\n        # supercell. If it does, the edge is updated. This is more\n        # computationally expensive than just keeping track of the\n        # which new lattice images present, but should hopefully be\n        # easier to extend to a general 3x3 scaling matrix.\n\n        # code adapted from Structure.__mul__\n        scale_matrix = np.array(scaling_matrix, np.int16)\n        if scale_matrix.shape != (3, 3):\n            scale_matrix = np.array(scale_matrix * np.eye(3), np.int16)\n        else:\n            # TODO: test __mul__ with full 3x3 scaling matrices\n            raise NotImplementedError('Not tested with 3x3 scaling matrices yet.')\n        new_lattice = Lattice(np.dot(scale_matrix, self.structure.lattice.matrix))\n\n        f_lat = lattice_points_in_supercell(scale_matrix)\n        c_lat = new_lattice.get_cartesian_coords(f_lat)\n\n        new_sites = []\n        new_graphs = []\n\n        for v in c_lat:\n\n            # create a map of nodes from original graph to its image\n            mapping = {n: n + len(new_sites) for n in range(len(self.structure))}\n\n            for idx, site in enumerate(self.structure):\n\n                s = PeriodicSite(site.species_and_occu, site.coords + v,\n                                 new_lattice, properties=site.properties,\n                                 coords_are_cartesian=True, to_unit_cell=False)\n\n                new_sites.append(s)\n\n            new_graphs.append(nx.relabel_nodes(self.graph, mapping, copy=True))\n\n        new_structure = Structure.from_sites(new_sites)\n\n        # merge all graphs into one big graph\n        new_g = nx.MultiDiGraph()\n        for new_graph in new_graphs:\n            new_g = nx.union(new_g, new_graph)\n\n        edges_to_remove = []  # tuple of (u, v, k)\n        edges_to_add = []  # tuple of (u, v, attr_dict)\n\n        # list of new edges inside supercell\n        # for duplicate checking\n        edges_inside_supercell = [{u, v} for u, v, d in new_g.edges(data=True)\n                                  if d['to_jimage'] == (0, 0, 0)]\n        new_periodic_images = []\n\n        orig_lattice = self.structure.lattice\n\n        # use k-d tree to match given position to an\n        # existing Site in Structure\n        kd_tree = KDTree(new_structure.cart_coords)\n\n        # tolerance in Å for sites to be considered equal\n        # this could probably be a lot smaller\n        tol = 0.05\n\n        for u, v, k, d in new_g.edges(keys=True, data=True):\n\n            to_jimage = d['to_jimage']  # for node v\n\n            # reduce unnecessary checking\n            if to_jimage != (0, 0, 0):\n\n                # get index in original site\n                n_u = u % len(self.structure)\n                n_v = v % len(self.structure)\n\n                # get fractional co-ordinates of where atoms defined\n                # by edge are expected to be, relative to original\n                # lattice (keeping original lattice has\n                # significant benefits)\n                v_image_frac = np.add(self.structure[n_v].frac_coords, to_jimage)\n                u_frac = self.structure[n_u].frac_coords\n\n                # using the position of node u as a reference,\n                # get relative Cartesian co-ordinates of where\n                # atoms defined by edge are expected to be\n                v_image_cart = orig_lattice.get_cartesian_coords(v_image_frac)\n                u_cart = orig_lattice.get_cartesian_coords(u_frac)\n                v_rel = np.subtract(v_image_cart, u_cart)\n\n                # now retrieve position of node v in\n                # new supercell, and get absolute Cartesian\n                # co-ordinates of where atoms defined by edge\n                # are expected to be\n                v_expec = new_structure[u].coords + v_rel\n\n                # now search in new structure for these atoms\n                # query returns (distance, index)\n                v_present = kd_tree.query(v_expec)\n                v_present = v_present[1] if v_present[0] <= tol else None\n\n                # check if image sites now present in supercell\n                # and if so, delete old edge that went through\n                # periodic boundary\n                if v_present is not None:\n\n                    new_u = u\n                    new_v = v_present\n                    new_d = d.copy()\n\n                    # node now inside supercell\n                    new_d['to_jimage'] = (0, 0, 0)\n\n                    edges_to_remove.append((u, v, k))\n\n                    # make sure we don't try to add duplicate edges\n                    # will remove two edges for everyone one we add\n                    if {new_u, new_v} not in edges_inside_supercell:\n\n                        # normalize direction\n                        if new_v < new_u:\n                            new_u, new_v = new_v, new_u\n\n                        edges_inside_supercell.append({new_u, new_v})\n                        edges_to_add.append((new_u, new_v, new_d))\n\n                else:\n\n                    # want to find new_v such that we have\n                    # full periodic boundary conditions\n                    # so that nodes on one side of supercell\n                    # are connected to nodes on opposite side\n\n                    v_expec_frac = new_structure.lattice.get_fractional_coords(v_expec)\n\n                    # find new to_jimage\n                    # use np.around to fix issues with finite precision leading to incorrect image\n                    v_expec_image = np.around(v_expec_frac, decimals=3)\n                    v_expec_image = v_expec_image - v_expec_image%1\n\n                    v_expec_frac = np.subtract(v_expec_frac, v_expec_image)\n                    v_expec = new_structure.lattice.get_cartesian_coords(v_expec_frac)\n                    v_present = kd_tree.query(v_expec)\n                    v_present = v_present[1] if v_present[0] <= tol else None\n\n                    if v_present is not None:\n\n                        new_u = u\n                        new_v = v_present\n                        new_d = d.copy()\n                        new_to_jimage = tuple(map(int, v_expec_image))\n\n                        # normalize direction\n                        if new_v < new_u:\n                            new_u, new_v = new_v, new_u\n                            new_to_jimage = tuple(np.multiply(-1, d['to_jimage']).astype(int))\n\n                        new_d['to_jimage'] = new_to_jimage\n\n                        edges_to_remove.append((u, v, k))\n\n                        if (new_u, new_v, new_to_jimage) not in new_periodic_images:\n                            edges_to_add.append((new_u, new_v, new_d))\n                            new_periodic_images.append((new_u, new_v, new_to_jimage))\n\n        logger.debug(\"Removing {} edges, adding {} new edges.\".format(len(edges_to_remove),\n                                                                      len(edges_to_add)))\n\n        # add/delete marked edges\n        for edges_to_remove in edges_to_remove:\n            new_g.remove_edge(*edges_to_remove)\n        for (u, v, d) in edges_to_add:\n            new_g.add_edge(u, v, **d)\n\n        # return new instance of StructureGraph with supercell\n        d = {\"@module\": self.__class__.__module__,\n             \"@class\": self.__class__.__name__,\n             \"structure\": new_structure.as_dict(),\n             \"graphs\": json_graph.adjacency_data(new_g)}\n\n        sg = StructureGraph.from_dict(d)\n\n        return sg\n\n    def __rmul__(self, other):\n        return self.__mul__(other)\n\n    def _edges_to_string(self, g):\n\n        header = \"from    to  to_image    \"\n        header_line = \"----  ----  ------------\"\n        edge_weight_name = g.graph[\"edge_weight_name\"]\n        if edge_weight_name:\n            print_weights = [\"weight\"]\n            edge_label = g.graph[\"edge_weight_name\"]\n            edge_weight_units = g.graph[\"edge_weight_units\"]\n            if edge_weight_units:\n                edge_label += \" ({})\".format(edge_weight_units)\n            header += \"  {}\".format(edge_label)\n            header_line += \"  {}\".format(\"-\"*max([18, len(edge_label)]))\n        else:\n            print_weights = False\n\n        s = header + \"\\n\" + header_line + \"\\n\"\n\n        edges = list(g.edges(data=True))\n\n        # sort edges for consistent ordering\n        edges.sort(key=itemgetter(0,1))\n\n        if print_weights:\n            for u, v, data in edges:\n                s += \"{:4}  {:4}  {:12}  {:.12E}\\n\".format(u, v, str(data.get(\"to_jimage\", (0, 0, 0))),\n                                                           data.get(\"weight\", 0))\n        else:\n            for u, v, data in edges:\n                s += \"{:4}  {:4}  {:12}\\n\".format(u, v,\n                                                  str(data.get(\"to_jimage\", (0, 0, 0))))\n\n        return s\n\n    def __str__(self):\n        s = \"Structure Graph\"\n        s += \"\\nStructure: \\n{}\".format(self.structure.__str__())\n        s += \"\\nGraph: {}\\n\".format(self.name)\n        s += self._edges_to_string(self.graph)\n        return s\n\n    def __repr__(self):\n        s = \"Structure Graph\"\n        s += \"\\nStructure: \\n{}\".format(self.structure.__repr__())\n        s += \"\\nGraph: {}\\n\".format(self.name)\n        s += self._edges_to_string(self.graph)\n        return s\n\n    def __len__(self):\n        \"\"\"\n        :return: length of Structure / number of nodes in graph\n        \"\"\"\n        return len(self.structure)\n\n    def sort(self, key=None, reverse=False):\n        \"\"\"\n        Same as Structure.sort(), also remaps nodes in graph.\n        :param key:\n        :param reverse:\n        :return:\n        \"\"\"\n\n        old_structure = self.structure.copy()\n\n        # sort Structure\n        self.structure._sites = sorted(self.structure._sites, key=key, reverse=reverse)\n\n        # apply Structure ordering to graph\n        mapping = {idx:self.structure.index(site) for idx, site in enumerate(old_structure)}\n        self.graph = nx.relabel_nodes(self.graph, mapping, copy=True)\n\n        # normalize directions of edges\n        edges_to_remove = []\n        edges_to_add = []\n        for u, v, k, d in self.graph.edges(keys=True, data=True):\n            if v < u:\n                new_v, new_u, new_d = u, v, d.copy()\n                new_d['to_jimage'] = tuple(np.multiply(-1, d['to_jimage']).astype(int))\n                edges_to_remove.append((u,v,k))\n                edges_to_add.append((new_u, new_v, new_d))\n\n        # add/delete marked edges\n        for edges_to_remove in edges_to_remove:\n            self.graph.remove_edge(*edges_to_remove)\n        for (u, v, d) in edges_to_add:\n            self.graph.add_edge(u, v, **d)\n\n    def __copy__(self):\n        return StructureGraph.from_dict(self.as_dict())\n\n    def __eq__(self, other):\n        \"\"\"\n        Two StructureGraphs are equal if they have equal Structures,\n        and have the same edges between Sites. Edge weights can be\n        different and StructureGraphs can still be considered equal.\n\n        :param other: StructureGraph\n        :return (bool):\n        \"\"\"\n\n        # sort for consistent node indices\n        # PeriodicSite should have a proper __hash__() value,\n        # using its frac_coords as a convenient key\n        mapping = {tuple(site.frac_coords):self.structure.index(site) for site in other.structure}\n        other_sorted = other.__copy__()\n        other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)])\n\n        edges = {(u, v, d['to_jimage'])\n                 for u, v, d in self.graph.edges(keys=False, data=True)}\n\n        edges_other = {(u, v, d['to_jimage'])\n                       for u, v, d in other_sorted.graph.edges(keys=False, data=True)}\n\n        return (edges == edges_other) and \\\n               (self.structure == other_sorted.structure)\n\n    def diff(self, other, strict=True):\n        \"\"\"\n        Compares two StructureGraphs. Returns dict with\n        keys 'self', 'other', 'both' with edges that are\n        present in only one StructureGraph ('self' and\n        'other'), and edges that are present in both.\n\n        The Jaccard distance is a simple measure of the\n        dissimilarity between two StructureGraphs (ignoring\n        edge weights), and is defined by 1 - (size of the\n        intersection / size of the union) of the sets of\n        edges. This is returned with key 'dist'.\n\n        Important note: all node indices are in terms\n        of the StructureGraph this method is called\n        from, not the 'other' StructureGraph: there\n        is no guarantee the node indices will be the\n        same if the underlying Structures are ordered\n        differently.\n\n        :param other: StructureGraph\n        :param strict: if False, will compare bonds\n        from different Structures, with node indices\n        replaced by Specie strings, will not count\n        number of occurrences of bonds\n        :return:\n        \"\"\"\n\n        if self.structure != other.structure and strict:\n            return ValueError(\"Meaningless to compare StructureGraphs if \"\n                              \"corresponding Structures are different.\")\n\n        if strict:\n\n            # sort for consistent node indices\n            # PeriodicSite should have a proper __hash__() value,\n            # using its frac_coords as a convenient key\n            mapping = {tuple(site.frac_coords):self.structure.index(site) for site in other.structure}\n            other_sorted = other.__copy__()\n            other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)])\n\n            edges = {(u, v, d['to_jimage'])\n                     for u, v, d in self.graph.edges(keys=False, data=True)}\n\n            edges_other = {(u, v, d['to_jimage'])\n                           for u, v, d in other_sorted.graph.edges(keys=False, data=True)}\n\n        else:\n\n            edges = {(str(self.structure[u].specie),\n                      str(self.structure[v].specie))\n                     for u, v, d in self.graph.edges(keys=False, data=True)}\n\n            edges_other = {(str(other.structure[u].specie),\n                            str(other.structure[v].specie))\n                           for u, v, d in other.graph.edges(keys=False, data=True)}\n\n        if len(edges) == 0 and len(edges_other) == 0:\n            jaccard_dist = 0  # by definition\n        else:\n            jaccard_dist = 1 - len(edges.intersection(edges_other)) / len(edges.union(edges_other))\n\n        return {\n            'self': edges - edges_other,\n            'other': edges_other - edges,\n            'both': edges.intersection(edges_other),\n            'dist': jaccard_dist\n        }\n\n    def get_subgraphs_as_molecules(self, use_weights=False):\n        \"\"\"\n        Retrieve subgraphs as molecules, useful for extracting\n        molecules from periodic crystals.\n\n        Will only return unique molecules, not any duplicates\n        present in the crystal (a duplicate defined as an\n        isomorphic subgraph).\n\n        :param use_weights (bool): If True, only treat subgraphs\n        as isomorphic if edges have the same weights. Typically,\n        this means molecules will need to have the same bond\n        lengths to be defined as duplicates, otherwise bond\n        lengths can differ. This is a fairly robust approach,\n        but will treat e.g. enantiomers as being duplicates.\n\n        :return: list of unique Molecules in Structure\n        \"\"\"\n\n        # creating a supercell is an easy way to extract\n        # molecules (and not, e.g., layers of a 2D crystal)\n        # without adding extra logic\n        if getattr(self, '_supercell_sg', None) is None:\n            self._supercell_sg = supercell_sg = self*(3,3,3)\n\n        # make undirected to find connected subgraphs\n        supercell_sg.graph = nx.Graph(supercell_sg.graph)\n\n        # find subgraphs\n        all_subgraphs = list(nx.connected_component_subgraphs(supercell_sg.graph))\n\n        # discount subgraphs that lie across *supercell* boundaries\n        # these will subgraphs representing crystals\n        molecule_subgraphs = []\n        for subgraph in all_subgraphs:\n            intersects_boundary = any([d['to_jimage'] != (0, 0, 0)\n                                      for u, v, d in subgraph.edges(data=True)])\n            if not intersects_boundary:\n                molecule_subgraphs.append(subgraph)\n\n        # add specie names to graph to be able to test for isomorphism\n        for subgraph in molecule_subgraphs:\n            for n in subgraph:\n                subgraph.add_node(n, specie=str(supercell_sg.structure[n].specie))\n\n        # now define how we test for isomorphism\n        def node_match(n1, n2):\n            return n1['specie'] == n2['specie']\n        def edge_match(e1, e2):\n            if use_weights:\n                return e1['weight'] == e2['weight']\n            else:\n                return True\n\n        # prune duplicate subgraphs\n        unique_subgraphs = []\n        for subgraph in molecule_subgraphs:\n\n            already_present = [nx.is_isomorphic(subgraph, g,\n                                                node_match=node_match,\n                                                edge_match=edge_match)\n                               for g in unique_subgraphs]\n\n            if not any(already_present):\n                unique_subgraphs.append(subgraph)\n\n        # get Molecule objects for each subgraph\n        molecules = []\n        for subgraph in unique_subgraphs:\n\n            coords = [supercell_sg.structure[n].coords for n\n                      in subgraph.nodes()]\n            species = [supercell_sg.structure[n].specie for n\n                      in subgraph.nodes()]\n\n            molecule = Molecule(species, coords)\n\n            # shift so origin is at center of mass\n            molecule = molecule.get_centered_molecule()\n\n            molecules.append(molecule)\n\n        return molecules\n", "meta": {"hexsha": "ba210230320fd4082e48c4d28bebc1f88ca09d70", "size": 39582, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymatgen/analysis/graphs.py", "max_stars_repo_name": "ltalirz/pymatgen", "max_stars_repo_head_hexsha": "894cdb2ec7b9bd74f0ac3cdad40d144203ccdcf6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-11T20:57:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T05:00:42.000Z", "max_issues_repo_path": "pymatgen/analysis/graphs.py", "max_issues_repo_name": "ltalirz/pymatgen", "max_issues_repo_head_hexsha": "894cdb2ec7b9bd74f0ac3cdad40d144203ccdcf6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pymatgen/analysis/graphs.py", "max_forks_repo_name": "ltalirz/pymatgen", "max_forks_repo_head_hexsha": "894cdb2ec7b9bd74f0ac3cdad40d144203ccdcf6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-14T19:47:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-02T08:10:45.000Z", "avg_line_length": 39.6613226453, "max_line_length": 106, "alphanum_fraction": 0.5693749684, "include": true, "reason": "import numpy,from scipy,import networkx,from networkx", "num_tokens": 8504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.18472683018536493}}
{"text": "# Copyright 2018 The Cirq Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import Any, cast, Dict, NamedTuple, Optional, Sequence, Tuple, TYPE_CHECKING, Union\n\nimport numpy as np\n\nfrom cirq import protocols, value, linalg\nfrom cirq._doc import document\nfrom cirq.ops import common_gates, gate_features, named_qubit, pauli_gates\nfrom cirq.ops.pauli_gates import Pauli\nfrom cirq.type_workarounds import NotImplementedType\n\nif TYPE_CHECKING:\n    import cirq\n\nPauliTransform = NamedTuple('PauliTransform', [('to', Pauli), ('flip', bool)])\ndocument(PauliTransform, \"\"\"+X, -X, +Y, -Y, +Z, or -Z.\"\"\")\n\n\ndef _to_pauli_transform(matrix: np.ndarray) -> Optional[PauliTransform]:\n    \"\"\"Converts matrix to PauliTransform.\n\n    If matrix is not ±Pauli matrix, returns None.\n    \"\"\"\n    for pauli in Pauli._XYZ:\n        p = protocols.unitary(pauli)\n        if np.allclose(matrix, p):\n            return PauliTransform(pauli, False)\n        if np.allclose(matrix, -p):\n            return PauliTransform(pauli, True)\n    return None\n\n\ndef _pretend_initialized() -> 'SingleQubitCliffordGate':\n    # HACK: This is a workaround to fool mypy and pylint into correctly handling\n    # class fields that can't be initialized until after the class is defined.\n    pass\n\n\n@value.value_equality\nclass SingleQubitCliffordGate(gate_features.SingleQubitGate):\n    \"\"\"Any single qubit Clifford rotation.\"\"\"\n\n    I = _pretend_initialized()\n    H = _pretend_initialized()\n    X = _pretend_initialized()\n    Y = _pretend_initialized()\n    Z = _pretend_initialized()\n    X_sqrt = _pretend_initialized()\n    Y_sqrt = _pretend_initialized()\n    Z_sqrt = _pretend_initialized()\n    X_nsqrt = _pretend_initialized()\n    Y_nsqrt = _pretend_initialized()\n    Z_nsqrt = _pretend_initialized()\n\n    def __init__(\n        self,\n        *,\n        _rotation_map: Dict[Pauli, PauliTransform],\n        _inverse_map: Dict[Pauli, PauliTransform],\n    ) -> None:\n        self._rotation_map = _rotation_map\n        self._inverse_map = _inverse_map\n\n    @staticmethod\n    def from_xz_map(\n        x_to: Tuple[Pauli, bool], z_to: Tuple[Pauli, bool]\n    ) -> 'SingleQubitCliffordGate':\n        \"\"\"Returns a SingleQubitCliffordGate for the specified transforms.\n        The Y transform is derived from the X and Z.\n\n        Args:\n            x_to: Which Pauli to transform X to and if it should negate.\n            z_to: Which Pauli to transform Z to and if it should negate.\n        \"\"\"\n        return SingleQubitCliffordGate.from_double_map(x_to=x_to, z_to=z_to)\n\n    @staticmethod\n    def from_single_map(\n        pauli_map_to: Optional[Dict[Pauli, Tuple[Pauli, bool]]] = None,\n        *,\n        x_to: Optional[Tuple[Pauli, bool]] = None,\n        y_to: Optional[Tuple[Pauli, bool]] = None,\n        z_to: Optional[Tuple[Pauli, bool]] = None,\n    ) -> 'SingleQubitCliffordGate':\n        \"\"\"Returns a SingleQubitCliffordGate for the\n        specified transform with a 90 or 180 degree rotation.\n\n        The arguments are exclusive, only one may be specified.\n\n        Args:\n            pauli_map_to: A dictionary with a single key value pair describing\n                the transform.\n            x_to: The transform from cirq.X\n            y_to: The transform from cirq.Y\n            z_to: The transform from cirq.Z\n        \"\"\"\n        rotation_map = SingleQubitCliffordGate._validate_map_input(\n            1, pauli_map_to, x_to=x_to, y_to=y_to, z_to=z_to\n        )\n        ((trans_from, (trans_to, flip)),) = tuple(rotation_map.items())\n        if trans_from == trans_to:\n            trans_from2 = Pauli.by_relative_index(trans_to, 1)  # 1 or 2 work\n            trans_to2 = Pauli.by_relative_index(trans_from, 1)\n            flip2 = False\n        else:\n            trans_from2 = trans_to\n            trans_to2 = trans_from\n            flip2 = not flip\n        rotation_map[trans_from2] = PauliTransform(trans_to2, flip2)\n        return SingleQubitCliffordGate.from_double_map(\n            cast(Dict[Pauli, Tuple[Pauli, bool]], rotation_map)\n        )\n\n    @staticmethod\n    def from_double_map(\n        pauli_map_to: Optional[Dict[Pauli, Tuple[Pauli, bool]]] = None,\n        *,\n        x_to: Optional[Tuple[Pauli, bool]] = None,\n        y_to: Optional[Tuple[Pauli, bool]] = None,\n        z_to: Optional[Tuple[Pauli, bool]] = None,\n    ) -> 'SingleQubitCliffordGate':\n        \"\"\"Returns a SingleQubitCliffordGate for the\n        specified transform with a 90 or 180 degree rotation.\n\n        Either pauli_map_to or two of (x_to, y_to, z_to) may be specified.\n\n        Args:\n            pauli_map_to: A dictionary with two key value pairs describing\n                two transforms.\n            x_to: The transform from cirq.X\n            y_to: The transform from cirq.Y\n            z_to: The transform from cirq.Z\n        \"\"\"\n        rotation_map = SingleQubitCliffordGate._validate_map_input(\n            2, pauli_map_to, x_to=x_to, y_to=y_to, z_to=z_to\n        )\n        (from1, trans1), (from2, trans2) = tuple(rotation_map.items())\n        from3 = from1.third(from2)\n        to3 = trans1.to.third(trans2.to)\n        flip3 = trans1.flip ^ trans2.flip ^ ((from1 < from2) != (trans1.to < trans2.to))\n        rotation_map[from3] = PauliTransform(to3, flip3)\n        inverse_map = {to: PauliTransform(frm, flip) for frm, (to, flip) in rotation_map.items()}\n        return SingleQubitCliffordGate(_rotation_map=rotation_map, _inverse_map=inverse_map)\n\n    @staticmethod\n    def from_pauli(pauli: Pauli, sqrt: bool = False) -> 'SingleQubitCliffordGate':\n        prev_pauli = Pauli.by_relative_index(pauli, -1)\n        next_pauli = Pauli.by_relative_index(pauli, 1)\n        if sqrt:\n            rotation_map = {\n                prev_pauli: PauliTransform(next_pauli, True),\n                pauli: PauliTransform(pauli, False),\n                next_pauli: PauliTransform(prev_pauli, False),\n            }\n        else:\n            rotation_map = {\n                prev_pauli: PauliTransform(prev_pauli, True),\n                pauli: PauliTransform(pauli, False),\n                next_pauli: PauliTransform(next_pauli, True),\n            }\n        inverse_map = {to: PauliTransform(frm, flip) for frm, (to, flip) in rotation_map.items()}\n        return SingleQubitCliffordGate(_rotation_map=rotation_map, _inverse_map=inverse_map)\n\n    @staticmethod\n    def from_quarter_turns(pauli: Pauli, quarter_turns: int) -> 'SingleQubitCliffordGate':\n        quarter_turns = quarter_turns % 4\n        if quarter_turns == 0:\n            return SingleQubitCliffordGate.I\n        if quarter_turns == 1:\n            return SingleQubitCliffordGate.from_pauli(pauli, True)\n        if quarter_turns == 2:\n            return SingleQubitCliffordGate.from_pauli(pauli)\n\n        return SingleQubitCliffordGate.from_pauli(pauli, True) ** -1\n\n    @staticmethod\n    def _validate_map_input(\n        required_transform_count: int,\n        pauli_map_to: Optional[Dict[Pauli, Tuple[Pauli, bool]]],\n        x_to: Optional[Tuple[Pauli, bool]],\n        y_to: Optional[Tuple[Pauli, bool]],\n        z_to: Optional[Tuple[Pauli, bool]],\n    ) -> Dict[Pauli, PauliTransform]:\n        if pauli_map_to is None:\n            xyz_to = {pauli_gates.X: x_to, pauli_gates.Y: y_to, pauli_gates.Z: z_to}\n            pauli_map_to = {\n                cast(Pauli, p): trans for p, trans in xyz_to.items() if trans is not None\n            }\n        elif x_to is not None or y_to is not None or z_to is not None:\n            raise ValueError(\n                '{} can take either pauli_map_to or a combination'\n                ' of x_to, y_to, and z_to but both were given'\n            )\n        if len(pauli_map_to) != required_transform_count:\n            raise ValueError(\n                'Method takes {} transform{} but {} {} given'.format(\n                    required_transform_count,\n                    '' if required_transform_count == 1 else 's',\n                    len(pauli_map_to),\n                    'was' if len(pauli_map_to) == 1 else 'were',\n                )\n            )\n        if len(set((to for to, _ in pauli_map_to.values()))) != len(pauli_map_to):\n            raise ValueError('A rotation cannot map two Paulis to the same')\n        return {frm: PauliTransform(to, flip) for frm, (to, flip) in pauli_map_to.items()}\n\n    @staticmethod\n    def from_unitary(u: np.ndarray) -> Optional['SingleQubitCliffordGate']:\n        \"\"\"Creates Clifford gate with given unitary (up to global phase).\n\n        Args:\n            u: 2x2 unitary matrix of a Clifford gate.\n\n        Returns:\n            SingleQubitCliffordGate, whose matrix is equal to given matrix (up\n            to global phase), or `None` if `u` is not a matrix of a single-qubit\n            Clifford gate.\n        \"\"\"\n        if u.shape != (2, 2) or not linalg.is_unitary(u):\n            return None\n        x = protocols.unitary(pauli_gates.X)\n        z = protocols.unitary(pauli_gates.Z)\n        x_to = _to_pauli_transform(u @ x @ u.conj().T)\n        z_to = _to_pauli_transform(u @ z @ u.conj().T)\n        if x_to is None or z_to is None:\n            return None\n        return SingleQubitCliffordGate.from_double_map({pauli_gates.X: x_to, pauli_gates.Z: z_to})\n\n    def transform(self, pauli: Pauli) -> PauliTransform:\n        return self._rotation_map[pauli]\n\n    def _value_equality_values_(self):\n        return (\n            self.transform(pauli_gates.X),\n            self.transform(pauli_gates.Y),\n            self.transform(pauli_gates.Z),\n        )\n\n    def __pow__(self, exponent) -> 'SingleQubitCliffordGate':\n        if exponent == 0.5 or exponent == -0.5:\n            return SQRT_EXP_MAP[exponent][self]\n        if exponent != -1:\n            return NotImplemented\n\n        return SingleQubitCliffordGate(\n            _rotation_map=self._inverse_map, _inverse_map=self._rotation_map\n        )\n\n    def _commutes_(self, other: Any, atol: float) -> Union[bool, NotImplementedType]:\n        if isinstance(other, SingleQubitCliffordGate):\n            return self.commutes_with_single_qubit_gate(other)\n        if isinstance(other, Pauli):\n            return self.commutes_with_pauli(other)\n        return NotImplemented\n\n    def commutes_with_single_qubit_gate(self, gate: 'SingleQubitCliffordGate') -> bool:\n        \"\"\"Tests if the two circuits would be equivalent up to global phase:\n        --self--gate-- and --gate--self--\"\"\"\n        for pauli0 in (pauli_gates.X, pauli_gates.Z):\n            pauli1, flip1 = self.transform(cast(Pauli, pauli0))\n            pauli2, flip2 = gate.transform(cast(Pauli, pauli1))\n            pauli3, flip3 = self._inverse_map[pauli2]\n            pauli4, flip4 = gate._inverse_map[pauli3]\n            if pauli4 != pauli0 or (flip1 ^ flip2 ^ flip3 ^ flip4):\n                return False\n        return True\n\n    def commutes_with_pauli(self, pauli: Pauli) -> bool:\n        to, flip = self.transform(pauli)\n        return to == pauli and not flip\n\n    def merged_with(self, second: 'SingleQubitCliffordGate') -> 'SingleQubitCliffordGate':\n        \"\"\"Returns a SingleQubitCliffordGate such that the circuits\n            --output-- and --self--second--\n        are equivalent up to global phase.\"\"\"\n        x_intermediate_pauli, x_flip1 = self.transform(pauli_gates.X)\n        x_final_pauli, x_flip2 = second.transform(x_intermediate_pauli)\n        z_intermediate_pauli, z_flip1 = self.transform(pauli_gates.Z)\n        z_final_pauli, z_flip2 = second.transform(z_intermediate_pauli)\n        return SingleQubitCliffordGate.from_xz_map(\n            (x_final_pauli, x_flip1 ^ x_flip2), (z_final_pauli, z_flip1 ^ z_flip2)\n        )\n\n    def _has_unitary_(self) -> bool:\n        return True\n\n    def _unitary_(self) -> np.ndarray:\n        mat = np.eye(2)\n        qubit = named_qubit.NamedQubit('arbitrary')\n        for op in protocols.decompose_once_with_qubits(self, (qubit,)):\n            mat = protocols.unitary(op).dot(mat)\n        return mat\n\n    def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':\n        (qubit,) = qubits\n        if self == SingleQubitCliffordGate.H:\n            return (common_gates.H(qubit),)\n        rotations = self.decompose_rotation()\n        return tuple(r.on(qubit) ** (qt / 2) for r, qt in rotations)\n\n    def decompose_rotation(self) -> Sequence[Tuple[Pauli, int]]:\n        \"\"\"Returns ((first_rotation_axis, first_rotation_quarter_turns), ...)\n\n        This is a sequence of zero, one, or two rotations.\"\"\"\n        x_rot = self.transform(pauli_gates.X)\n        y_rot = self.transform(pauli_gates.Y)\n        z_rot = self.transform(pauli_gates.Z)\n        whole_arr = (\n            x_rot.to == pauli_gates.X,\n            y_rot.to == pauli_gates.Y,\n            z_rot.to == pauli_gates.Z,\n        )\n        num_whole = sum(whole_arr)\n        flip_arr = (x_rot.flip, y_rot.flip, z_rot.flip)\n        num_flip = sum(flip_arr)\n        if num_whole == 3:\n            if num_flip == 0:\n                # Gate is identity\n                return []\n\n            # 180 rotation about some axis\n            pauli = Pauli.by_index(flip_arr.index(False))\n            return [(pauli, 2)]\n        if num_whole == 1:\n            index = whole_arr.index(True)\n            pauli = Pauli.by_index(index)\n            next_pauli = Pauli.by_index(index + 1)\n            flip = flip_arr[index]\n            output = []\n            if flip:\n                # 180 degree rotation\n                output.append((next_pauli, 2))\n            # 90 degree rotation about some axis\n            if self.transform(next_pauli).flip:\n                # Negative 90 degree rotation\n                output.append((pauli, -1))\n            else:\n                # Positive 90 degree rotation\n                output.append((pauli, 1))\n            return output\n        elif num_whole == 0:\n            # Gate is a 120 degree rotation\n            if x_rot.to == pauli_gates.Y:\n                return [\n                    (pauli_gates.X, -1 if y_rot.flip else 1),\n                    (pauli_gates.Z, -1 if x_rot.flip else 1),\n                ]\n\n            return [\n                (pauli_gates.Z, 1 if y_rot.flip else -1),\n                (pauli_gates.X, 1 if z_rot.flip else -1),\n            ]\n        # coverage: ignore\n        assert (\n            False\n        ), 'Impossible condition where this gate only rotates one Pauli to a different Pauli.'\n\n    def equivalent_gate_before(self, after: 'SingleQubitCliffordGate') -> 'SingleQubitCliffordGate':\n        \"\"\"Returns a SingleQubitCliffordGate such that the circuits\n            --output--self-- and --self--gate--\n        are equivalent up to global phase.\"\"\"\n        return self.merged_with(after).merged_with(self ** -1)\n\n    def __repr__(self) -> str:\n        x = self.transform(pauli_gates.X)\n        y = self.transform(pauli_gates.Y)\n        z = self.transform(pauli_gates.Z)\n        x_sign = '-' if x.flip else '+'\n        y_sign = '-' if y.flip else '+'\n        z_sign = '-' if z.flip else '+'\n        return (\n            f'cirq.SingleQubitCliffordGate(X:{x_sign}{x.to!s}, '\n            f'Y:{y_sign}{y.to!s}, Z:{z_sign}{z.to!s})'\n        )\n\n    def _circuit_diagram_info_(\n        self, args: 'cirq.CircuitDiagramInfoArgs'\n    ) -> 'cirq.CircuitDiagramInfo':\n        well_known_map = {\n            SingleQubitCliffordGate.I: 'I',\n            SingleQubitCliffordGate.H: 'H',\n            SingleQubitCliffordGate.X: 'X',\n            SingleQubitCliffordGate.Y: 'Y',\n            SingleQubitCliffordGate.Z: 'Z',\n            SingleQubitCliffordGate.X_sqrt: 'X',\n            SingleQubitCliffordGate.Y_sqrt: 'Y',\n            SingleQubitCliffordGate.Z_sqrt: 'Z',\n            SingleQubitCliffordGate.X_nsqrt: 'X',\n            SingleQubitCliffordGate.Y_nsqrt: 'Y',\n            SingleQubitCliffordGate.Z_nsqrt: 'Z',\n        }\n        if self in well_known_map:\n            symbol = well_known_map[self]\n        else:\n            rotations = self.decompose_rotation()\n            symbol = '-'.join(str(r) + ('^' + str(qt / 2)) * (qt % 4 != 2) for r, qt in rotations)\n            symbol = '({})'.format(symbol)\n        return protocols.CircuitDiagramInfo(\n            wire_symbols=(symbol,),\n            exponent={\n                SingleQubitCliffordGate.X_sqrt: 0.5,\n                SingleQubitCliffordGate.Y_sqrt: 0.5,\n                SingleQubitCliffordGate.Z_sqrt: 0.5,\n                SingleQubitCliffordGate.X_nsqrt: -0.5,\n                SingleQubitCliffordGate.Y_nsqrt: -0.5,\n                SingleQubitCliffordGate.Z_nsqrt: -0.5,\n            }.get(self, 1),\n        )\n\n\nSingleQubitCliffordGate.I = SingleQubitCliffordGate.from_xz_map(\n    (pauli_gates.X, False), (pauli_gates.Z, False)\n)\nSingleQubitCliffordGate.H = SingleQubitCliffordGate.from_xz_map(\n    (pauli_gates.Z, False), (pauli_gates.X, False)\n)\nSingleQubitCliffordGate.X = SingleQubitCliffordGate.from_xz_map(\n    (pauli_gates.X, False), (pauli_gates.Z, True)\n)\nSingleQubitCliffordGate.Y = SingleQubitCliffordGate.from_xz_map(\n    (pauli_gates.X, True), (pauli_gates.Z, True)\n)\nSingleQubitCliffordGate.Z = SingleQubitCliffordGate.from_xz_map(\n    (pauli_gates.X, True), (pauli_gates.Z, False)\n)\nSingleQubitCliffordGate.X_sqrt = SingleQubitCliffordGate.from_xz_map(\n    (pauli_gates.X, False), (pauli_gates.Y, True)\n)\nSingleQubitCliffordGate.X_nsqrt = SingleQubitCliffordGate.from_xz_map(\n    (pauli_gates.X, False), (pauli_gates.Y, False)\n)\nSingleQubitCliffordGate.Y_sqrt = SingleQubitCliffordGate.from_xz_map(\n    (pauli_gates.Z, True), (pauli_gates.X, False)\n)\nSingleQubitCliffordGate.Y_nsqrt = SingleQubitCliffordGate.from_xz_map(\n    (pauli_gates.Z, False), (pauli_gates.X, True)\n)\nSingleQubitCliffordGate.Z_sqrt = SingleQubitCliffordGate.from_xz_map(\n    (pauli_gates.Y, False), (pauli_gates.Z, False)\n)\nSingleQubitCliffordGate.Z_nsqrt = SingleQubitCliffordGate.from_xz_map(\n    (pauli_gates.Y, True), (pauli_gates.Z, False)\n)\n\nSQRT_EXP_MAP = {\n    0.5: {\n        SingleQubitCliffordGate.X: SingleQubitCliffordGate.X_sqrt,\n        SingleQubitCliffordGate.Y: SingleQubitCliffordGate.Y_sqrt,\n        SingleQubitCliffordGate.Z: SingleQubitCliffordGate.Z_sqrt,\n    },\n    -0.5: {\n        SingleQubitCliffordGate.X: SingleQubitCliffordGate.X_nsqrt,\n        SingleQubitCliffordGate.Y: SingleQubitCliffordGate.Y_nsqrt,\n        SingleQubitCliffordGate.Z: SingleQubitCliffordGate.Z_nsqrt,\n    },\n}\n", "meta": {"hexsha": "86b02fa53ad8cc941aa7fb47d7551761cc04910c", "size": 18750, "ext": "py", "lang": "Python", "max_stars_repo_path": "cirq/ops/clifford_gate.py", "max_stars_repo_name": "exAClior/Cirq", "max_stars_repo_head_hexsha": "0701327bc66c988428f302dd1e4bed1eef1535a6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-05T19:47:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T19:47:55.000Z", "max_issues_repo_path": "cirq/ops/clifford_gate.py", "max_issues_repo_name": "rohitvuppala/Cirq", "max_issues_repo_head_hexsha": "0ff2894e053e4ce3bb1b54e9b9de1cc4345d10b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-01-11T10:35:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-28T19:17:02.000Z", "max_forks_repo_path": "cirq/ops/clifford_gate.py", "max_forks_repo_name": "rohitvuppala/Cirq", "max_forks_repo_head_hexsha": "0ff2894e053e4ce3bb1b54e9b9de1cc4345d10b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-30T21:50:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T21:50:00.000Z", "avg_line_length": 39.8936170213, "max_line_length": 100, "alphanum_fraction": 0.6288, "include": true, "reason": "import numpy", "num_tokens": 5088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.36658972940200996, "lm_q1q2_score": 0.18472682669825874}}
{"text": "# This file is part of QuTiP: Quantum Toolbox in Python.\n#\n#    Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.\n#    All rights reserved.\n#\n#    Redistribution and use in source and binary forms, with or without\n#    modification, are permitted provided that the following conditions are\n#    met:\n#\n#    1. Redistributions of source code must retain the above copyright notice,\n#       this list of conditions and the following disclaimer.\n#\n#    2. Redistributions in binary form must reproduce the above copyright\n#       notice, this list of conditions and the following disclaimer in the\n#       documentation and/or other materials provided with the distribution.\n#\n#    3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names\n#       of its contributors may be used to endorse or promote products derived\n#       from this software without specific prior written permission.\n#\n#    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n#    \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n#    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n#    PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n#    HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n#    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n#    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n#    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n#    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n#    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n#    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n###############################################################################\nfrom collections.abc import Iterable\nimport numbers\n\nimport numpy as np\n\nfrom qutip.qobj import Qobj\nfrom qutip.qobjevo import QobjEvo\nfrom qutip.qip.operations.gates import globalphase\nfrom qutip.tensor import tensor\nfrom qutip.mesolve import mesolve\nfrom qutip.qip.circuit import QubitCircuit\nfrom qutip.qip.device.processor import Processor\n\n\n__all__ = ['ModelProcessor']\n\n\nclass ModelProcessor(Processor):\n    \"\"\"\n    The base class for a circuit processor simulating a physical device,\n    e.g cavityQED, spinchain.\n    The available Hamiltonian of the system is predefined.\n    The processor can simulate the evolution under the given\n    control pulses either numerically or analytically.\n    It cannot be used alone, please refer to the sub-classes.\n    (Only additional attributes are documented here, for others please\n    refer to the parent class :class:`.Processor`)\n\n    Parameters\n    ----------\n    N: int\n        The number of component systems.\n\n    correct_global_phase: boolean, optional\n        If true, the analytical solution will track the global phase. It\n        has no effect on the numerical solution.\n\n    t1: list or float\n        Characterize the decoherence of amplitude damping for\n        each qubit. A list of size `N` or a float for all qubits.\n\n    t2: list of float\n        Characterize the decoherence of dephasing for\n        each qubit. A list of size `N` or a float for all qubits.\n\n    Attributes\n    ----------\n    params: dict\n        A Python dictionary contains the name and the value of the parameters\n        in the physical realization, such as laser frequency, detuning etc.\n\n    correct_global_phase: float\n        Save the global phase, the analytical solution\n        will track the global phase.\n        It has no effect on the numerical solution.\n    \"\"\"\n    def __init__(self, N, correct_global_phase=True, t1=None, t2=None):\n        super(ModelProcessor, self).__init__(N, t1=t1, t2=t2)\n        self.correct_global_phase = correct_global_phase\n        self.global_phase = 0.\n        self._params = {}\n\n    def to_array(self, params, N):\n        \"\"\"\n        Transfer a parameter to an array.\n        \"\"\"\n        if isinstance(params, numbers.Real):\n            return np.asarray([params] * N)\n        elif isinstance(params, Iterable):\n            return np.asarray(params)\n\n    def set_up_params(self):\n        \"\"\"\n        Save the parameters in the attribute `params` and check the validity.\n        (Defined in subclasses)\n\n        Notes\n        -----\n        All parameters will be multiplied by 2*pi for simplicity\n        \"\"\"\n        raise NotImplementedError(\"Parameters should be defined in subclass.\")\n\n    @property\n    def params(self):\n        return self._params\n\n    @params.setter\n    def params(self, par):\n        self._params = par\n\n    def run_state(self, init_state=None, analytical=False, qc=None,\n                  states=None, **kwargs):\n        \"\"\"\n        If `analytical` is False, use :func:`qutip.mesolve` to\n        calculate the time of the state evolution\n        and return the result. Other arguments of mesolve can be\n        given as keyword arguments.\n        If `analytical` is True, calculate the propagator\n        with matrix exponentiation and return a list of matrices.\n\n        Parameters\n        ----------\n        init_state: Qobj\n            Initial density matrix or state vector (ket).\n\n        analytical: boolean\n            If True, calculate the evolution with matrices exponentiation.\n\n        qc: :class:`.QubitCircuit`, optional\n            A quantum circuit. If given, it first calls the ``load_circuit``\n            and then calculate the evolution.\n\n        states: :class:`qutip.Qobj`, optional\n         Old API, same as init_state.\n\n        **kwargs\n           Keyword arguments for the qutip solver.\n\n        Returns\n        -------\n        evo_result: :class:`qutip.Result`\n            If ``analytical`` is False,  an instance of the class\n            :class:`qutip.Result` will be returned.\n\n            If ``analytical`` is True, a list of matrices representation\n            is returned.\n        \"\"\"\n        if qc is not None:\n            self.load_circuit(qc)\n        return super(ModelProcessor, self).run_state(\n            init_state=init_state, analytical=analytical,\n            states=states, **kwargs)\n\n    def get_ops_and_u(self):\n        \"\"\"\n        Get the labels for each Hamiltonian.\n\n        Returns\n        -------\n        ctrls: list\n            The list of Hamiltonians\n        coeffs: array_like\n            The transposed pulse matrix\n        \"\"\"\n        return (self.ctrls, self.get_full_coeffs().T)\n\n    def pulse_matrix(self, dt=0.01):\n        \"\"\"\n        Generates the pulse matrix for the desired physical system.\n\n        Returns\n        -------\n        t, u, labels:\n            Returns the total time and label for every operation.\n        \"\"\"\n        ctrls = self.ctrls\n        coeffs = self.get_full_coeffs().T\n\n        # FIXME This might becomes a problem if new tlist other than\n        # int the default pulses are added.\n        tlist = self.get_full_tlist()\n        dt_list = tlist[1:] - tlist[:-1]\n        t_tot = tlist[-1]\n        num_step = int(np.ceil(t_tot / dt))\n\n        t = np.linspace(0, t_tot, num_step)\n        u = np.zeros((len(ctrls), num_step))\n\n        t_start = 0\n        for n in range(len(dt_list)):\n            t_idx_len = int(np.floor(dt_list[n] / dt))\n            mm = 0\n            for m in range(len(ctrls)):\n                u[mm, t_start:(t_start + t_idx_len)] = (np.ones(t_idx_len) *\n                                                        coeffs[n, m])\n                mm += 1\n            t_start += t_idx_len\n\n        return t, u, self.get_operators_labels()\n", "meta": {"hexsha": "82fabfe96aa8b622da26cefea3c38820241076c8", "size": 7556, "ext": "py", "lang": "Python", "max_stars_repo_path": "qutip/qip/device/modelprocessor.py", "max_stars_repo_name": "LaurentAjdnik/qutip", "max_stars_repo_head_hexsha": "b836829f7c5389185b676eed7c5f801613689f9f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-11T06:20:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-11T06:20:23.000Z", "max_issues_repo_path": "qutip/qip/device/modelprocessor.py", "max_issues_repo_name": "DRA-chaos/qutip", "max_issues_repo_head_hexsha": "297776737cf91df0468022ba2b1a3090af0d6549", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-06-24T14:38:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-08T16:54:37.000Z", "max_forks_repo_path": "qutip/qip/device/modelprocessor.py", "max_forks_repo_name": "DRA-chaos/qutip", "max_forks_repo_head_hexsha": "297776737cf91df0468022ba2b1a3090af0d6549", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-22T12:57:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-22T12:57:42.000Z", "avg_line_length": 35.641509434, "max_line_length": 79, "alphanum_fraction": 0.6377713076, "include": true, "reason": "import numpy", "num_tokens": 1664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.18466529180450186}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Authors: Tomas Cassanelli and Andrea Pinna\n\nimport logging\nimport os\nimport shutil\nimport sys\nimport yaml\nimport numpy as np\nfrom astropy.io import ascii, fits\nfrom scipy.constants import c as light_speed\nfrom .aperture import illum_gauss, illum_pedestal\n\n# ---------------------------------------------------------------------------- #\n\n__all__ = [\n    'get_run_config', 'init_output_dir', 'init_logger',\n    'extract_data_pyoof', 'extract_data_effelsberg',\n    'extract_real_data_srt', 'extract_synthetic_data_srt', 'extract_data_srt',\n    'precompute_srt_opd', 'str2LaTeX',\n    'store_data_csv', 'uv_ratio', 'illum_strings', 'store_data_ascii'\n    ]\n\n# ---------------------------------------------------------------------------- #\n\ndef get_run_config(yaml_config_file):\n    \"\"\"\n    Read configuration parameters for the current run.\n    \"\"\"\n\n    if not os.path.exists(yaml_config_file):\n        sys.exit('Error! Configuration file \"{}\" does not exist!'.format(\n            yaml_config_file))\n    try:\n        with open(yaml_config_file, 'r') as f:\n            return yaml.load(f, Loader=yaml.SafeLoader)\n    except:\n        sys.exit('Cannot read configuration file \"{}\"!'.format(\n            yaml_config_file))\n\n# ---------------------------------------------------------------------------- #\n\ndef init_output_dir(config):\n    \"\"\"\n    Create output directory.\n    \"\"\"\n\n    # Create output directory\n    if not os.path.exists(config['output']['output_dir']):\n        os.makedirs(config['output']['output_dir'])\n    elif config['output']['overwrite_dir']:\n        shutil.rmtree(config['output']['output_dir'])\n        os.mkdir(config['output']['output_dir'])\n    else:\n        try:\n            os.mkdir(config['output']['output_dir'])\n        except FileExistsError:\n            sys.exit('Error! Directory \"{}\" already exists!'.format(\n                config['output']['output_dir']))\n\n# ---------------------------------------------------------------------------- #\n\ndef init_logger(config):\n    \"\"\"\n    Initialize loggers to standard output and to file.\n    \"\"\"\n\n    logger = logging.getLogger('pyoof')\n    logger.setLevel(logging.DEBUG)\n\n    log_file = os.path.join(config['output']['output_dir'],\n                            '{}.log'.format(config['info']['label']))\n\n    fh = logging.FileHandler(log_file)\n    fh.setLevel(logging.DEBUG)\n\n    ch = logging.StreamHandler()\n    ch.setLevel(logging.INFO)\n\n    formatter = logging.Formatter('%(asctime)s : %(levelname)s : %(message)s')\n    fh.setFormatter(formatter)\n    ch.setFormatter(formatter)\n\n    logger.addHandler(fh)\n    logger.addHandler(ch)\n\n    return logger\n\n# ---------------------------------------------------------------------------- #\n\ndef illum_strings(illum_func):\n    \"\"\"\n    It assigns string labels to the illumination function. The `~pyoof` package\n    has two standard illumination functions, `~pyoof.aperture.illum_pedestal`\n    and `~pyoof.aperture.illum_gauss`.\n\n    Parameters\n    ----------\n    illum_func : `function`\n        Illumination function, :math:`E_\\\\mathrm{a}(x, y)`, to be evaluated\n        with ``I_coeff``. The illumination functions available are\n        `~pyoof.aperture.illum_pedestal` and `~pyoof.aperture.illum_gauss`.\n\n    Returns\n    -------\n    illum_name : `str`\n        String with the illumination function name.\n    taper_name : `str`\n        String with the illumination function taper.\n    \"\"\"\n\n    # adding illumination function information\n    if illum_func == illum_pedestal:\n        illum_name = 'pedestal'\n        taper_name = 'c_dB'\n    elif illum_func == illum_gauss:\n        illum_name = 'gauss'\n        taper_name = 'sigma_dB'\n    else:\n        illum_name = 'manual'\n        taper_name = 'taper_dB'\n\n    return illum_name, taper_name\n\n# ---------------------------------------------------------------------------- #\n\ndef extract_data_pyoof(pathfits):\n    \"\"\"\n    Extracts data from the `~pyoof` default fits file OOF holography\n    observations, ready to use for the least squares minimization (see\n    `~pyoof.fit_beam`). The fits file has to have the following keys on its\n    PrimaryHDU header: ``'FREQ'``, ``'WAVEL'``, ``'MEANEL'``, ``'OBJECT'`` and\n    ``'DATE_OBS'``. Besides this three BinTableHDU are required for the data\n    itself; ``MINUS OOF``, ``ZERO OOF`` and ``PLUS OOF``. The BinTableHDU\n    header has to have the ``'DZ'`` key which includes the radial offset,\n    :math:`d_z`. Finally the BinTableHDU has the data files ``'U'``, ``'V'``\n    and ``'BEAM'``, which is the :math:`x`- and :math:`y`-axis position in\n    radians and the ``'BEAM'`` in a flat array, in mJy.\n\n    Parameters\n    ----------\n    pathfits : `str`\n        Path to the fits file that contains the three beam maps pre-calibrated,\n        using the correct PrimaryHDU and the three BinTableHDU (``MINUS OOF``,\n        ``ZERO OOF`` and ``PLUS OOF``).\n\n    Returns\n    -------\n    data_info : `list`\n        It contains all extra data besides the beam map. The output\n        corresponds to a list,\n        ``[name, pthto, obs_object, obs_date, freq, wavel, d_z, meanel]``.\n        These are, name of the fits file, paht of the fits file, observed\n        object, observation date, frequency, wavelength, radial offset and\n        mean elevation, respectively.\n    data_obs : `list`\n        It contains beam maps and :math:`x`-, and :math:`y`-axis\n        (:math:`uv`-plane in Fourier space) data for the least squares\n        minimization (see `~pyoof.fit_beam`). The list has the following order\n        ``[beam_data, u_data, v_data]``. ``beam_data`` is the three beam\n        observations, minus, zero and plus out-of-focus, in a flat array.\n        ``u_data`` and ``v_data`` are the beam axes in a flat array.\n    \"\"\"\n\n    hdulist = fits.open(pathfits)  # open fits file, pyoof format\n    # path or directory where the fits file is located\n    pthto = os.path.split(pathfits)[0]\n    # name of the fit file to fit\n    name = os.path.split(pathfits)[1][:-5]\n\n    if not all(k in hdulist[0].header\n               for k in ['FREQ', 'WAVEL', 'MEANEL', 'OBJECT', 'DATE_OBS']):\n        raise TypeError('Not all necessary keys found in FITS header.')\n\n    freq = hdulist[0].header['FREQ']\n    wavel = hdulist[0].header['WAVEL']\n    meanel = hdulist[0].header['MEANEL']\n    obs_object = hdulist[0].header['OBJECT']\n    obs_date = hdulist[0].header['DATE_OBS']\n\n    beam_data = [hdulist[i].data['BEAM'] for i in range(1, 4)]\n    u_data = [hdulist[i].data['U'] for i in range(1, 4)]\n    v_data = [hdulist[i].data['V'] for i in range(1, 4)]\n    d_z = [hdulist[i].header['DZ'] for i in range(1, 4)]\n\n    data_file = [name, pthto]\n    data_info = data_file + [obs_object, obs_date, freq, wavel, d_z, meanel]\n    data_obs = [beam_data, u_data, v_data]\n\n    return data_info, data_obs\n\n# ---------------------------------------------------------------------------- #\n\ndef extract_data_srt(config, logger):\n    \"\"\"\n    Read data from synthetic or real measurement files and generate the output\n    FITS file in the requested format by pyoof.\n    \"\"\"\n\n    data_files = [os.path.join(config['input']['input_dir'],\n                               config['input']['oof_minus']),\n                  os.path.join(config['input']['input_dir'],\n                               config['input']['in_focus']),\n                  os.path.join(config['input']['input_dir'],\n                               config['input']['oof_plus'])]\n\n    d_z = [-float(config['params']['delta_z']),\n           0.0,\n           float(config['params']['delta_z'])]\n\n    wavelength = light_speed / float(config['params']['frequency'])  # Hz frequency\n\n    if config['input']['real_data']:\n        u, v, P = extract_real_data_srt(data_files, logger)\n    else:\n        u, v, P = extract_synthetic_data_srt(data_files, logger)\n\n    u_to_save = [u[i].flatten() for i in range(3)]\n    v_to_save = [v[i].flatten() for i in range(3)]\n    p_to_save = [P[i].flatten() for i in range(3)]\n\n    # Writing default fits file for OOF observations\n    table_hdu0 = fits.BinTableHDU.from_columns([\n        fits.Column(name='U', format='E', array=u_to_save[0]),\n        fits.Column(name='V', format='E', array=v_to_save[0]),\n        fits.Column(name='BEAM', format='E', array=p_to_save[0])\n        ])\n\n    table_hdu1 = fits.BinTableHDU.from_columns([\n        fits.Column(name='U', format='E', array=u_to_save[1]),\n        fits.Column(name='V', format='E', array=v_to_save[1]),\n        fits.Column(name='BEAM', format='E', array=p_to_save[1])\n        ])\n\n    table_hdu2 = fits.BinTableHDU.from_columns([\n        fits.Column(name='U', format='E', array=u_to_save[2]),\n        fits.Column(name='V', format='E', array=v_to_save[2]),\n        fits.Column(name='BEAM', format='E', array=p_to_save[2])\n        ])\n\n    fits_file = os.path.join(config['output']['output_dir'],\n                             '{}.fits'.format(config['info']['label']))\n\n    logger.info('Writing data to {}...'.format(fits_file))\n\n    prihdr = fits.Header()\n    prihdr['FREQ'] = float(config['params']['frequency'])\n    prihdr['WAVEL'] = wavelength\n    prihdr['MEANEL'] = 0\n    prihdr['OBJECT'] = config['info']['label']\n    prihdr['DATE_OBS'] = config['info']['observation_date']\n    prihdr['COMMENT'] = config['info']['comment']\n    prihdr['AUTHOR'] = config['info']['author']\n    prihdu = fits.PrimaryHDU(header=prihdr)\n    pyoof_fits = fits.HDUList([prihdu, table_hdu0, table_hdu1, table_hdu2])\n\n    for i in range(3):\n        pyoof_fits[i + 1].header['DZ'] = d_z[i]\n\n    pyoof_fits[1].name = 'MINUS OOF'\n    pyoof_fits[2].name = 'ZERO OOF'\n    pyoof_fits[3].name = 'PLUS OOF'\n\n    pyoof_fits.writeto(fits_file)\n    logger.info('Done!')\n\n    data_info, data_obs = extract_data_pyoof(fits_file)\n    return data_info, data_obs\n\n# ---------------------------------------------------------------------------- #\n\ndef extract_real_data_srt(data_files, logger):\n    \"\"\"\n    Read data from input files containing real measurements and generate\n    organized output variables.\n    \"\"\"\n\n    # Load SRT data\n    u_all, v_all, P_all = [], [], []\n\n    for i in range(3):\n        logger.info('Reading data from file \"{}\"...'.format(data_files[i]))\n        u_data, v_data, beam_data = np.loadtxt(data_files[i], unpack=True)\n        u = sorted(set(u_data))\n        v = sorted(set(v_data))\n        n_u = len(u)\n        n_v = len(v)\n        n_values = n_u * n_v\n        uu, vv = np.meshgrid(u, v)\n        P_tot = beam_data.reshape(n_u, n_v).transpose()\n\n        u_all.append(uu)\n        v_all.append(vv)\n        P_all.append(P_tot)\n\n    return u_all, v_all, P_all\n\n# ---------------------------------------------------------------------------- #\n\ndef extract_synthetic_data_srt(data_files, logger):\n    \"\"\"\n    Read data from input files containing synthetic measurements and generate\n    organized output variables.\n    \"\"\"\n\n    u_all, v_all, P_all = [], [], []\n\n    for i in range(3):\n\n        logger.info('Reading data from file \"{}\"...'.format(data_files[i]))\n        with open(data_files[i], 'r') as f:\n            data = f.readlines()[9:]\n\n        grid_start, grid_end = [float(k) for k in data[0].split()[0::2]]\n        n_u, n_v = [int(k) for k in data[1].split()[0:2]]\n        n_values = n_u * n_v\n        u = np.linspace(grid_start, grid_end, n_u)\n        v = np.linspace(grid_start, grid_end, n_v)\n        uu, vv = np.meshgrid(u, v)\n        pr = np.zeros(n_values)\n        pi = np.zeros(n_values)\n        lines = data[2:]\n        for j, line in enumerate(lines):\n            pr[j], pi[j] = [float(k) for k in line.split()[0:2]]\n        P_tot = np.power(pr, 2) + np.power(pi, 2)\n\n        u_all.append(uu)\n        v_all.append(vv)\n        P_all.append(P_tot)\n\n    return u_all, v_all, P_all\n\n# ---------------------------------------------------------------------------- #\n\ndef precompute_srt_opd(data_info, telgeo, resolution, box_factor, config, logger):\n    \"\"\"\n    Precompute the optical path difference for the Sardinia Radio Telescope.\n    \"\"\"\n\n    pr = telgeo[2]\n    box_size = pr * box_factor\n\n    x = np.linspace(-box_size, box_size, resolution)\n    y = x\n    x_grid, y_grid = np.meshgrid(x, y)\n\n    # Cassegrain/Gregorian (at focus) telescope\n    Fp = config['params']['focus_primary_reflector']  # Focus primary reflector m\n    F = config['params']['total_focus']  # Total focus Gregorian telescope m\n    r = np.sqrt(np.power(x_grid, 2) + np.power(y_grid, 2))  # polar coordinates radius\n    a = r / (2 * Fp)\n    b = r / (2 * F)\n\n    # Polynomial fitting\n    R = np.asarray([\n        [-1.438998E-09, -2.706440E-10, -7.098885E-14],\n        [ 1.467218E-07,  2.888850E-08,  7.767377E-12],\n        [-5.904197E-06, -1.234467E-06, -3.330234E-10],\n        [ 1.188731E-04,  2.717683E-05,  7.038221E-09],\n        [-1.239164E-03, -3.357801E-04, -7.544711E-08],\n        [ 6.017033E-03,  2.461091E-03,  3.776198E-07],\n        [-1.323805E-02, -9.312688E-03, -7.093549E-07],\n        [ 5.676379E-03,  8.636208E-04,  2.160941E-07]])\n\n    # Degree of polynomial\n    N1 = R.shape[0]\n    N2 = R.shape[1]\n\n    opd = [[], [], []]\n    delta_opd = [[], [], []]\n    for i_dz in range(3):\n        d_z = data_info[6][i_dz]\n        opd[i_dz] = d_z * ((1 - a ** 2) / (1 + a ** 2) + \\\n                           (1 - b ** 2) / (1 + b ** 2))\n\n        coeff = np.zeros(N1)\n        for k in range(N1-1, -1, -1):\n            for i in range(N2-1, -1, -1):\n                coeff[k] = coeff[k] + R[k, i] * np.power(d_z, N2-i)\n\n        delta_opd[i_dz] = np.zeros(r.shape)\n        for i in range(r.shape[0]):\n            for j in range(r.shape[1]):\n                for k in range(N1-1, -1, -1):\n                    delta_opd[i_dz][i, j] = delta_opd[i_dz][i, j] + \\\n                                            coeff[k] * np.power(r[i, j], N1-k)\n\n    if config['params']['residual_opd']:\n        logger.info('Returning \"opd + delta_opd\"...')\n        return [opd[0] + delta_opd[0], opd[1] + delta_opd[1], opd[2] + delta_opd[2]]\n    else:\n        logger.info('Returning \"opd\" without \"delta_opd\"...')\n        return opd\n\n# ---------------------------------------------------------------------------- #\n\ndef extract_data_effelsberg(pathfits):\n    \"\"\"\n    Extracts data from the Effelsberg OOF holography observations, ready to\n    use for the least squares minimization. This function will only work for\n    the Effelsberg telescope beam maps.\n\n    Parameters\n    ----------\n    pathfits : `str`\n        Path to the fits file that contains the three beam maps pre-calibrated,\n        from the Effelsberg telescope.\n\n    Returns\n    -------\n    data_info : `list`\n        It contains all extra data besides the beam map. The output\n        corresponds to a list,\n        ``[name, pthto, obs_object, obs_date, freq, wavel, d_z, meanel]``.\n        These are, name of the fits file, paht of the fits file, observed\n        object, observation date, frequency, wavelength, radial offset and\n        mean elevation, respectively.\n    data_obs : `list`\n        It contains beam maps and :math:`x`-, and :math:`y`-axis\n        (:math:`uv`-plane in Fourier space) data for the least squares\n        minimization (see `~pyoof.fit_beam`). The list has the following order\n        ``[beam_data, u_data, v_data]``. ``beam_data`` is the three beam\n        observations, minus, zero and plus out-of-focus, in a flat array.\n        ``u_data`` and ``v_data`` are the beam axes in a flat array.\n    \"\"\"\n\n    # Opening fits file with astropy\n    try:\n        # main fits file with the OOF holography format\n        hdulist = fits.open(pathfits)\n\n        # Observation frequency\n        freq = hdulist[0].header['FREQ']  # Hz\n        wavel = light_speed / freq\n\n        # Mean elevation\n        meanel = hdulist[0].header['MEANEL']  # Degrees\n        obs_object = hdulist[0].header['OBJECT']  # observed object\n        obs_date = hdulist[0].header['DATE_OBS']  # observation date\n        d_z = [hdulist[i].header['DZ'] for i in range(1, 4)][::-1]\n\n        beam_data = [hdulist[i].data['fnu'] for i in range(1, 4)][::-1]\n        u_data = [hdulist[i].data['DX'] for i in range(1, 4)][::-1]\n        v_data = [hdulist[i].data['DY'] for i in range(1, 4)][::-1]\n\n    except FileNotFoundError:\n        print('Fits file does not exists in directory: ' + pathfits)\n    except NameError:\n        print('Fits file does not have the OOF holography format')\n\n    else:\n        pass\n\n    # Permuting the position to provide same as main_functions\n    beam_data.insert(1, beam_data.pop(2))\n    u_data.insert(1, u_data.pop(2))\n    v_data.insert(1, v_data.pop(2))\n    d_z.insert(1, d_z.pop(2))\n\n    # path or directory where the fits file is located\n    pthto = os.path.split(pathfits)[0]\n    # name of the fit file to fit\n    name = os.path.split(pathfits)[1][:-5]\n\n    data_info = [name, pthto, obs_object, obs_date, freq, wavel, d_z, meanel]\n    data_obs = [beam_data, u_data, v_data]\n\n    return data_info, data_obs\n\n# ---------------------------------------------------------------------------- #\n\ndef str2LaTeX(python_string):\n    \"\"\"\n    Function that solves the underscore problem in a python string to\n    :math:`\\LaTeX` string.\n\n    Parameters\n    ----------\n    python_string : `str`\n        String that needs to be changed.\n\n    Returns\n    -------\n    LaTeX_string : `str`\n        String with the new underscore symbol.\n    \"\"\"\n\n    string_list = list(python_string)\n    for idx, string in enumerate(string_list):\n        if string_list[idx] == '_':\n            string_list[idx] = '\\\\_'\n\n    LaTeX_string = ''.join(string_list)\n\n    return LaTeX_string\n\n# ---------------------------------------------------------------------------- #\n\ndef store_data_csv(name, name_dir, order, save_to_csv):\n    \"\"\"\n    Stores all important information in a csv file after the least squares\n    minimization has finished, `~pyoof.fit_beam`. All data will be stores in\n    the ``pyoof_out/name`` directory, with ``name`` the name of the fits file.\n\n    Parameters\n    ----------\n    name : `str`\n        File name of the fits file to be optimized.\n    name_dir : `str`\n        Path to store all the csv files. The files will depend on the order of\n        the Zernike circle polynomial.\n    order : `int`\n        Order used for the Zernike circle polynomial, :math:`n`.\n    save_to_csv : `list`\n        It contains all data that will be stored. The list must have the\n        following order, ``[beam_data, u_data, v_data, res_optim, jac_optim,\n        grad_optim, phase, cov_ptrue, corr_ptrue]``.\n    \"\"\"\n\n    headers = [\n        'Normalized beam', 'u vector radians', 'v vector radians', 'Residual',\n        'Jacobian', 'Gradient', 'Phase primary reflector radians', 'Deformation Error',\n        'Variance-Covariance matrix (first row fitted parameters idx)',\n        'Correlation matrix (first row fitted parameters idx)'\n        ]\n\n    fnames = [\n        '/beam_data.csv', '/u_data.csv', '/v_data.csv',\n        '/res_n{}.csv'.format(order), '/jac_n{}.csv'.format(order),\n        '/grad_n{}.csv'.format(order), '/phase_n{}.csv'.format(order),\n        '/error_n{}.csv'.format(order),\n        '/cov_n{}.csv'.format(order), '/corr_n{}.csv'.format(order)\n        ]\n\n    if order != 1:\n        headers = headers[3:]\n        fnames = fnames[3:]\n        save_to_csv = save_to_csv[3:]\n\n    for fname, header, file in zip(fnames, headers, save_to_csv):\n        np.savetxt(\n            fname=name_dir + fname,\n            X=file,\n            header=header + ' ' + name\n            )\n\n# ---------------------------------------------------------------------------- #\n\ndef store_data_ascii(name, name_dir, taper_name, order, params_solution,\n                     params_init):\n    \"\"\"\n    Stores in an ascii format the parameters found by the least squares\n    minimization (see `~pyoof.fit_beam`).\n\n    Parameters\n    ----------\n    name : `str`\n        File name of the fits file to be optimized.\n    name_dir : `str`\n        Path to store all the csv files. The files will depend on the order of\n        the Zernike circle polynomial.\n    taper_name : `str`\n        Name of the illumination function taper.\n    order : `int`\n        Order used for the Zernike circle polynomial, :math:`n`.\n    params_solution : `~numpy.ndarray`\n        Contains the best fitted parameters, the illumination function\n        coefficients, ``I_coeff`` and the Zernike circle polynomial\n        coefficients, ``K_coeff`` in one array.\n    params_init : `~numpt.ndarray`\n        Contains the initial parameters used in the least squares minimization\n        to start finding the best fitted combination of them.\n    \"\"\"\n\n    n = order\n    N_K_coeff = (n + 1) * (n + 2) // 2\n\n    # Making nice table :)\n    ln = [(j, i) for i in range(0, n + 1) for j in range(-i, i + 1, 2)]\n    L = np.array(ln)[:, 0]\n    N = np.array(ln)[:, 1]\n\n    params_names = ['i_amp', taper_name, 'x_0', 'y_0']\n    for i in range(N_K_coeff):\n        params_names.append('K({}, {})'.format(N[i], L[i]))\n\n    # To store fit information and found parameters in ascii file\n    ascii.write(table=[params_names, params_solution, params_init],\n                output=os.path.join(name_dir, 'fitpar_n{}.csv'.format(n)),\n                names=['parname', 'parfit', 'parinit'],\n                comment='Fitted parameters {}'.format(name))\n\n# ---------------------------------------------------------------------------- #\n\ndef uv_ratio(u, v):\n    \"\"\"\n    Calculates the aspect ratio for the 3 power pattern plots, plus some\n    corrections for the text on it. Used in the `function` `~pyoof.plot_beam`\n    and `~pyoof.plot_data`\n\n    Parameters\n    ----------\n    u : `~numpy.ndarray`\n        Spatial frequencies from the power pattern, usually in degrees.\n    v : `~numpy.ndarray`\n        Spatial frequencies from the power pattern, usually in degrees.\n\n    Returns\n    -------\n    plot_width : `float`\n        Width for the power pattern figure.\n    plot_height : `float`\n        Height for the power pattern figure.\n    \"\"\"\n\n    ratio = (v.max() - v.min()) / (3 * (u.max() - u.min()))\n    width = 14\n    height = width * (ratio) + 0.2\n\n    return width, height\n\n# ---------------------------------------------------------------------------- #\n", "meta": {"hexsha": "3542ef75d452086407767a27620bd4be8a3b9b2e", "size": 22157, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyoof/aux_functions.py", "max_stars_repo_name": "pinno/pyoof-srt", "max_stars_repo_head_hexsha": "4ebef0aeeddc2738289d9232aea9e3ad7f0ecdd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyoof/aux_functions.py", "max_issues_repo_name": "pinno/pyoof-srt", "max_issues_repo_head_hexsha": "4ebef0aeeddc2738289d9232aea9e3ad7f0ecdd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyoof/aux_functions.py", "max_forks_repo_name": "pinno/pyoof-srt", "max_forks_repo_head_hexsha": "4ebef0aeeddc2738289d9232aea9e3ad7f0ecdd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4512, "max_line_length": 87, "alphanum_fraction": 0.5717831836, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 5751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.18466528820031858}}
{"text": "#!/usr/env/python\n\n## Import General Tools\nimport sys\nimport argparse\nimport logging\nfrom pathlib import Path\n\nimport numpy as np\nfrom astropy import units as u\nfrom astropy.io import fits\nfrom astropy import stats\nfrom astropy.table import Table, Column\nfrom astropy.modeling import models, fitting\nfrom astropy.visualization import MinMaxInterval, PercentileInterval, ImageNormalize\nimport ccdproc\nfrom ccdproc import ImageFileCollection as IFC\n\nfrom matplotlib import pyplot as plt\n\nimport warnings\nfrom astropy.utils.exceptions import AstropyDeprecationWarning as ADW\nwarnings.filterwarnings('ignore', category=ADW, append=True)\n\n\n##-------------------------------------------------------------------------\n## Parse Command Line Arguments\n##-------------------------------------------------------------------------\n## create a parser object for understanding command-line arguments\np = argparse.ArgumentParser(description='''\n''')\n## add flags\np.add_argument(\"-v\", \"--verbose\", dest=\"verbose\",\n    default=False, action=\"store_true\",\n    help=\"Be verbose! (default = False)\")\np.add_argument(\"-p\", \"--plot\", \"--plots\", dest=\"plot\",\n    default=False, action=\"store_true\",\n    help=\"Generate plots\")\n## add options\np.add_argument(\"--aduthreshold\", dest=\"aduthreshold\", type=float,\n    default=65000,\n    help=\"ADU threshold above which files are ignored.\")\np.add_argument(\"--exptime\", dest=\"exptime\", type=str,\n    default=\"EXPTIME\",\n    help=\"Header keyword for exposure time in seconds.\")\np.add_argument(\"--exptimefactor\", dest=\"exptimefactor\", type=float,\n    default=1,\n    help=\"\"\"Multiplicative factor for EXPTIME header keyword value to convert \n    it to seconds.\"\"\")\np.add_argument(\"--imtype\", dest=\"imtype\", type=str,\n    default=\"IMAGETYP\",\n    help=\"Header keyword for image type.\")\np.add_argument(\"--ccdtemp\", dest=\"ccdtemp\", type=str,\n    default=\"CCD-TEMP\",\n    help=\"Header keyword for CCD temperature.  None to ignore.\")\np.add_argument(\"--gain\", dest=\"gain\", type=str,\n    default=\"GAIN\",\n    help=\"Header keyword for gain in e/ADU.\")\np.add_argument(\"--trimpix\", dest=\"trimpix\", type=int,\n    default=0,\n    help=\"Number of pixels to trim from edges before analysis.\")\np.add_argument(\"--clippingsigma\", dest=\"clippingsigma\", type=float,\n    default=5,\n    help=\"Clipping sigma.\")\np.add_argument(\"--clippingiters\", dest=\"clippingiters\", type=int,\n    default=3,\n    help=\"Number of sigma clipping iterations.\")\np.add_argument(\"--hpthresh\", dest=\"hpthresh\", type=int,\n    default=10,\n    help=\"Threshold for tagging as a hot pixel (in ADU/s).\")\np.add_argument(\"--darkfilter\", dest=\"darkfilter\", type=str,\n    default=\"None\",\n    help=\"\"\"If CCD uses a dark filter rather than an IMTYPE to distingush bias\n    and dark files, set the filter keyword here which will be searched for \n    \"dark\".  Set to None to ignore.\"\"\")\np.add_argument(\"--ext\", \"-e\", dest=\"ext\", type=int,\n    default=0,\n    help=\"FITS extension to analyze.\")\n\n## add arguments\np.add_argument('files', nargs='*',\n               help=\"Input files\")\nargs = p.parse_args()\n\n\n##-------------------------------------------------------------------------\n## Create logger object\n##-------------------------------------------------------------------------\nlog = logging.getLogger()\nlog.setLevel(logging.DEBUG)\n## Set up console output\nLogConsoleHandler = logging.StreamHandler()\nif args.verbose is True:\n    LogConsoleHandler.setLevel(logging.DEBUG)\nelse:\n    LogConsoleHandler.setLevel(logging.INFO)\nLogFormat = logging.Formatter('%(asctime)s %(levelname)8s: %(message)s',\n                              datefmt='%Y-%m-%d %H:%M:%S')\nLogConsoleHandler.setFormatter(LogFormat)\nlog.addHandler(LogConsoleHandler)\n## Set up file output\n# LogFileName = None\n# LogFileHandler = logging.FileHandler(LogFileName)\n# LogFileHandler.setLevel(logging.DEBUG)\n# LogFileHandler.setFormatter(LogFormat)\n# log.addHandler(LogFileHandler)\n\n##-------------------------------------------------------------------------\n## get_mode\n##-------------------------------------------------------------------------\ndef get_mode(im):\n    '''\n    Return mode of image.  Assumes int values (ADU), so uses binsize of one.\n    '''\n    if type(im) == ccdproc.CCDData:\n        data = im.data.ravel()\n    elif type(im) == fits.HDUList:\n        data = im[0].data.ravel()\n    else:\n        data = im\n    \n    bmin = np.floor(min(data)) - 1./2.\n    bmax = np.ceil(max(data)) + 1./2.\n    bins = np.arange(bmin,bmax,1)\n    hist, bins = np.histogram(data, bins=bins)\n    centers = (bins[:-1] + bins[1:]) / 2\n    w = np.argmax(hist)\n    mode = int(centers[w])\n    return mode\n\n\n##-------------------------------------------------------------------------\n## Determine Read Noise\n##-------------------------------------------------------------------------\ndef determine_read_noise(ifc):\n    log.info('Determining read noise')\n    buf = args.trimpix\n\n    bias_type_names = ['bias', 'dark', 'zero', 'bias frame', 'dark frame']\n    if args.darkfilter is not \"None\":\n        bias_type_names.append('light frame')\n    bias_match = (ifc.summary[args.exptime] < 1)\n    bias_match &= np.array([t.lower() in bias_type_names\\\n                            for t in ifc.summary[args.imtype]])\n    if args.darkfilter is not \"None\":\n        bias_match &= np.array([f.lower() == 'dark'\\\n                                for f in ifc.summary[args.darkfilter]])\n\n    bias_files = ifc.summary[bias_match]\n    log.info(f'  Found {len(bias_files)} bias files')\n    biases = []\n    for i,bias_file_name in enumerate(bias_files['file']):\n        bias_file = Path(ifc.location).joinpath(bias_file_name)\n        if i == 0:\n            bias0 = ccdproc.fits_ccddata_reader(bias_file, unit='adu',\n                                                ext=args.ext)\n            ny, nx = bias0.data.shape\n            mean, median, stddev = stats.sigma_clipped_stats(\n                                         bias0.data[buf:ny-buf,buf:nx-buf],\n                                         sigma=args.clippingsigma,\n                                         iters=args.clippingiters) * u.adu\n            mode = get_mode(bias0)\n            log.debug(f'  Bias (mean, med, mode, std) = {mean.value:.1f}, '\\\n                      f'{median.value:.1f}, {mode:d}, {stddev.value:.2f}')\n        else:\n            biases.append(ccdproc.fits_ccddata_reader(bias_file, unit='adu',\n                          ext=args.ext))\n\n    log.info('  Making master bias')\n    master_bias = ccdproc.combine(biases, combine='average',\n                                  sigma_clip=True,\n                                  sigma_clip_low_thresh=args.clippingsigma,\n                                  sigma_clip_high_thresh=args.clippingsigma)\n    ny, nx = master_bias.data.shape\n    mean, median, stddev = stats.sigma_clipped_stats(\n                                 master_bias.data[buf:ny-buf,buf:nx-buf],\n                                 sigma=args.clippingsigma,\n                                 iters=args.clippingiters) * u.adu\n    mode = get_mode(master_bias)\n    log.debug(f'  Master Bias (mean, med, mode, std) = {mean.value:.1f}, '\\\n              f'{median.value:.1f}, {mode:d}, {stddev.value:.2f}')\n\n    diff = bias0.subtract(master_bias)\n    ny, nx = diff.data.shape\n    mean, median, stddev = stats.sigma_clipped_stats(\n                                 diff.data[buf:ny-buf,buf:nx-buf],\n                                 sigma=args.clippingsigma,\n                                 iters=args.clippingiters) * u.adu\n    mode = get_mode(diff)\n    log.debug(f'  Bias Difference (mean, med, mode, std) = {mean.value:.1f}, '\\\n              f'{median.value:.1f}, {mode:d}, {stddev.value:.2f}')\n\n    RN = stddev / np.sqrt(1.+1./(len(biases)))\n    log.info(f'  Read Noise is {RN:.2f}')\n\n    # Generate Bias Plots\n    if args.plot is True:\n        log.info(f'Generating plot for bias file: {bias_files[0][\"file\"]}')\n        data = biases[0].data[buf:ny-buf,buf:nx-buf]\n        std = np.std(data)\n        binwidth = int(20*std)\n        binsize = 1\n        med = np.median(data)\n        bins = [x+med for x in range(-binwidth,binwidth,binsize)]\n        norm = ImageNormalize(data, interval=PercentileInterval(98))\n\n        plt.figure(figsize=(18,18))\n        plt.subplot(2,1,1)\n        plt.title(bias_files[0]['file'])\n        plt.imshow(data, origin='lower', norm=norm, cmap='gray')\n        plt.subplot(2,1,2)\n        plt.hist(data.ravel(), log=True, bins=bins, color='g', alpha=0.5)\n        plt.xlabel('Value (ADU)')\n        plt.ylabel('N Pix')\n        plt.grid()\n        plot_filename = bias_files[0][\"file\"].replace('.fits', '.png')\n        plot_filename = plot_filename.replace('.fit', '.png')\n        plot_file = Path(ifc.location).joinpath(plot_filename)\n        plt.savefig(plot_file, bbox_inches='tight', pad_inches=0.10)\n\n        # Master Bias\n        log.info(f'Generating plot for master bias')\n        data = master_bias.data[buf:ny-buf,buf:nx-buf]\n        std = np.std(data)\n        binwidth = int(20*std)\n        binsize = 1\n        med = np.median(data)\n        bins = [x+med for x in range(-binwidth,binwidth,binsize)]\n        norm = ImageNormalize(data, interval=PercentileInterval(98))\n\n        plt.figure(figsize=(18,18))\n        plt.subplot(2,1,1)\n        plt.title('Master Bias')\n        plt.imshow(data, origin='lower', norm=norm, cmap='gray')\n        plt.subplot(2,1,2)\n        plt.hist(data.ravel(), log=True, bins=bins, color='g', alpha=0.5)\n        plt.xlabel('Value (ADU)')\n        plt.ylabel('N Pix')\n        plt.grid()\n        plot_file = Path(ifc.location).joinpath('MasterBias.png')\n        plt.savefig(plot_file, bbox_inches='tight', pad_inches=0.10)\n\n    return RN, master_bias\n\n\n##-------------------------------------------------------------------------\n## Determine Dark Current\n##-------------------------------------------------------------------------\ndef determine_dark_current(ifc, master_bias):\n\n    log.info('Determining dark current')\n    buf = args.trimpix\n\n    dark_type_names = ['dark', 'dark frame']\n    if args.darkfilter is not \"None\":\n        dark_type_names.append('light frame')\n    dark_match = (ifc.summary[args.exptime] > 0)\n    dark_match &= np.array([t.lower() in dark_type_names\\\n                            for t in ifc.summary[args.imtype]])\n    if args.darkfilter is not \"None\":\n        dark_match &= np.array([f.lower() == 'dark'\\\n                                for f in ifc.summary[args.darkfilter]])\n    dark_files = ifc.summary[dark_match]\n    if len(dark_files) == 0:\n        return None\n\n    dark_table = Table(names=('filename', 'exptime', 'mean', 'median', 'stddev', 'nhotpix'),\\\n                       dtype=('a100', 'f4', 'f4', 'f4', 'f4', 'i4'))\n    log.info(f'  Found {len(dark_files)} dark files')\n\n    darks = []\n    for i,entry in enumerate(dark_files):\n        dark_file = Path(ifc.location).joinpath(entry['file'])\n        exptime = entry[args.exptime]\n\n        dark = ccdproc.fits_ccddata_reader(dark_file, unit='adu', ext=args.ext)\n        dark_diff = ccdproc.subtract_bias(dark, master_bias)\n        ny, nx = dark_diff.data.shape\n        mean, median, stddev = stats.sigma_clipped_stats(\n                                     dark_diff.data[buf:ny-buf,buf:nx-buf],\n                                     sigma=args.clippingsigma,\n                                     iters=args.clippingiters) * u.adu\n        thresh = args.hpthresh*exptime\n        nhotpix = len(dark_diff.data.ravel()[dark_diff.data.ravel() > thresh])\n        dark_table.add_row([dark_file.name, exptime, mean, median, stddev, nhotpix])\n\n    # Fit Line to Dark Level to Determine Dark Current\n    line = models.Linear1D(intercept=0, slope=0)\n    line.intercept.fixed = True\n    fitter = fitting.LinearLSQFitter()\n\n    longest_exptime = int(max(dark_table['exptime']))\n    long_dark_table = dark_table[np.array(dark_table['exptime'], dtype=int) == longest_exptime]\n\n    dc_fit = fitter(line, dark_table['exptime'], dark_table['mean'])\n    dark_current = dc_fit.slope.value * u.adu/u.second\n\n    nhotpix = int(np.mean(long_dark_table['nhotpix'])) * u.pix\n    nhotpixstd = int(np.std(long_dark_table['nhotpix']))\\\n                 / np.sqrt(len(long_dark_table['nhotpix'])) * u.pix\n    dark_stats = [dark_current, nhotpix, nhotpixstd]\n    log.info(f'  Dark Current = {dark_current:.3f}')\n    log.info(f'  N Hot Pixels = {nhotpix:.0f} +/- {nhotpixstd:.0f}')\n\n    # Plot Dark Current Fit\n    if args.plot is True:\n        log.info(f'Generating plot for dark current')\n        plt.figure(figsize=(12,6))\n        plt.title('Dark Current')\n        ax = plt.gca()\n        ax.plot(dark_table['exptime'], dark_table['mean'], 'ko', alpha=1.0,\n                label='mean count level in ADU')\n        ax.plot([0, longest_exptime], [dc_fit(0), dc_fit(longest_exptime)],\n                'k-', alpha=0.3,\n                label=f'dark current = {dark_stats[0].value:.2f} ADU/s')\n        plt.xlim(-0.02*max(dark_table['exptime']), 1.10*max(dark_table['exptime']))\n        min_level = np.floor(min(dark_table['mean']))\n        max_level = np.ceil(max(dark_table['mean']))\n        plt.ylim(min([0,min_level]), 1.05*max_level)\n        ax.set_xlabel('Exposure Time (s)')\n        ax.set_ylabel('Dark Level (ADU)')\n        ax.legend(loc='upper left', fontsize=10)\n        ax.grid()\n        plot_file = Path(ifc.location).joinpath('DarkCurrent.png')\n        plt.savefig(plot_file, bbox_inches='tight', pad_inches=0.10)\n\n    return dark_current\n\n\n##-------------------------------------------------------------------------\n## Determine Gain\n##-------------------------------------------------------------------------\ndef determine_gain(ifc, master_bias, RN):\n\n    log.info('Determining gain')\n    buf = args.trimpix\n\n    flat_type_names = ['light', 'light frame', 'flat', 'intflat', 'domeflat', 'twiflat']\n    flat_match = (ifc.summary[args.exptime] > 0)\n    flat_match &= np.array([t.lower() in flat_type_names\n                            for t in ifc.summary[args.imtype]])\n    if args.darkfilter is not \"None\":\n        flat_match &= np.array([f.lower() != 'dark'\\\n                                for f in ifc.summary[args.darkfilter]])\n    flat_files = ifc.summary[flat_match]\n    if len(flat_files) == 0:\n        return None\n\n    flat_table = Table()\n    signal = []\n\n    flat_table = Table(names=('filename', args.exptime, 'mean', 'median', 'stddev'),\\\n                       dtype=('a100', 'f4', 'f4', 'f4', 'f4'))\n    flats = {}\n    log.info(f'  Found {len(flat_files)} flat files')\n    for i,entry in enumerate(flat_files):\n        flat_file = Path(ifc.location).joinpath(entry['file'])\n        exptime = entry[args.exptime]\n        flat = ccdproc.fits_ccddata_reader(flat_file, unit='adu', ext=args.ext)\n        flat = ccdproc.subtract_bias(flat, master_bias)\n        flats[flat_file.name] = flat\n        ny, nx = flat.data.shape\n        mean, med, std = stats.sigma_clipped_stats(\n                               flat.data[buf:ny-buf,buf:nx-buf],\n                               sigma=args.clippingsigma,\n                               iters=args.clippingiters) * u.adu\n        flat_table.add_row([flat_file.name, entry[args.exptime], mean, med, std])\n\n    bytime = flat_table.group_by(args.exptime)\n    exptimes = sorted(set(flat_table[args.exptime]))\n    signal = []\n    variance = []\n    signal_times = []\n    for exptime in exptimes:\n        exps = bytime.groups[bytime.groups.keys[args.exptime] == exptime]\n        nexps = len(exps)\n        log.info(f'  Measuring statistics for {nexps} {exptime:.0f}s flats')\n        for i in np.arange(0,nexps,2):\n            if i+1 < nexps:\n                try:\n                    flat_fileA = exps['filename'][i].decode('utf8')\n                    flat_fileB = exps['filename'][i+1].decode('utf8')\n                except:\n                    flat_fileA = exps['filename'][i]\n                    flat_fileB = exps['filename'][i+1]\n\n                expA = flats[flat_fileA]\n                expB = flats[flat_fileB]\n                meanA = exps[i]['median']\n                meanB = exps[i+1]['median']\n                ratio = meanA/meanB\n                log.debug(f'  Forming difference with scaling ratio {ratio:.3f}')\n                expB_scaled = expB.multiply(ratio)\n                diff = expA.subtract(expB_scaled)\n                ny, nx = flats[flat_file.name].data.shape\n                mean, med, std = stats.sigma_clipped_stats(\n                                    diff.data[buf:ny-buf,buf:nx-buf],\n                                    sigma=args.clippingsigma,\n                                    iters=args.clippingiters) * u.adu\n                log.debug(f'  Signal Level = {meanA:.2f}')\n                log.debug(f'  Variance = {std.to(u.adu).value**2/2.:.2f}')\n                variance.append(std.to(u.adu).value**2/2.)\n                signal.append(meanA)\n                signal_times.append(exps[i][args.exptime])\n\n\n\n    ## Fit model to variance vs. signal\n    log.info('  Fitting model to varaiance vs. signal to determine gain')\n    ## var = RN^2 + 1/g S + k^2 S^2\n    mask = np.array(np.array(signal) > args.aduthreshold)\n    poly = models.Polynomial1D(degree=2, c0=RN.to(u.adu).value)\n    poly.c0.fixed = True\n    poly.c2.min = 0.0\n    fitter = fitting.LevMarLSQFitter()\n    y = np.array(variance)[~mask]\n    x = np.array(signal)[~mask]\n    gainfits = fitter(poly, x, y)\n    # perr = np.sqrt(np.diag(fitter.fit_info['param_cov']))\n    ksq = gainfits.c2.value\n    # ksqerr = perr[1]\n    # print('  k^2 = {:.2e} +/- {:.2e} e/ADU'.format(ksq, ksqerr))\n    # print('  k^2 = {:.2e} e/ADU'.format(ksq))\n    g = gainfits.c1**-1 * u.electron/u.adu\n    # gerr = gainfits.c1**-2 * perr[0] * u.electron/u.adu\n    log.info(f'  Gain = {g:.3f}')\n\n    ## Fit Linearity\n    log.info('  Fitting linear model to find linearity limit')\n    line = models.Linear1D(intercept=0, slope=500)\n    line.intercept.fixed = True\n    fitter = fitting.LinearLSQFitter()\n    x = np.array(signal_times)[~mask]\n    y = np.array(signal)[~mask]\n    linearity_fit = fitter(line, x, y)\n\n    if args.plot is True:\n        log.info('  Generating figure with flat statistics and gain fits')\n        plt.figure(figsize=(12,12))\n        for i,plottype in enumerate(['', '_log']):\n            plt.subplot(2,1,i+1)\n            ax = plt.gca()\n            x = np.array(signal)[mask]\n            y = np.array(variance)[mask]\n            ax.plot(x, y, 'ko', alpha=0.3, markersize=5, markeredgewidth=0)\n            x = np.array(signal)[~mask]\n            y = np.array(variance)[~mask]\n            if plottype == '_log':\n                ax.semilogx(x, y, 'ko', alpha=1.0, markersize=8, markeredgewidth=0)\n                sig_fit = np.linspace(min(signal), max(signal), 50)\n                var_fit = [gainfits(x) for x in sig_fit]\n                ax.semilogx(sig_fit, var_fit, 'k-', alpha=0.7,\n                        label='Gain={g.value:.2f}e/ADU')\n            else:\n                ax.plot(x, y, 'ko', alpha=1.0, markersize=8, markeredgewidth=0)\n                sig_fit = np.linspace(min(signal), max(signal), 50)\n                var_fit = [gainfits(x) for x in sig_fit]\n                ax.plot(sig_fit, var_fit, 'k-', alpha=0.7,\n                        label=f'Gain={g.value:.2f}e/ADU')\n            ax.set_ylabel('Variance')\n            ax.set_xlabel('Mean Level (ADU)')\n            ax.grid()\n            ax.legend(loc='upper left', fontsize=10)\n        plot_file = Path(ifc.location).joinpath(f'Gain.png')\n        plt.savefig(plot_file, bbox_inches='tight', pad_inches=0.10)\n\n        log.info('  Generating figure with flat statistics and gain fits')\n        plt.figure(figsize=(12,12))\n        for i,plottype in enumerate(['', '_log']):\n            log.info('  Generating figure with linearity plot')\n            ax = plt.gca()\n            time = np.array(signal_times)\n            counts = np.array(signal)\n            fit_counts = [linearity_fit(t) for t in time]\n            y = (counts-fit_counts)/counts * 100.\n            if plottype == '_log':\n                ax.semilogx(counts, y, 'ko', alpha=0.5, markersize=5, markeredgewidth=0)\n                ax.semilogx([min(counts), max(counts)], [0, 0], 'k-')\n            else:\n                ax.plot(counts, y, 'ko', alpha=0.5, markersize=5, markeredgewidth=0)\n                ax.plot([min(counts), max(counts)], [0, 0], 'k-')\n            ax.set_xlabel('Mean Level (ADU)')\n            ax.set_ylabel('Signal Decrement (%) [(counts-fit)/counts]')\n        #     plt.ylim(np.floor(min(decrements)), np.ceil(max(decrements)))\n            ax.grid()\n        plot_file = Path(ifc.location).joinpath(f'Linearity.png')\n        plt.savefig(plot_file, bbox_inches='tight', pad_inches=0.10)\n\n    return g\n\n\n\n\n##-------------------------------------------------------------------------\n## Main Program\n##-------------------------------------------------------------------------\ndef main():\n    files = [Path(f) for f in args.files]\n    keywords = [args.exptime, args.imtype, args.ccdtemp]\n    if args.darkfilter is not \"None\":\n        keywords.append(args.darkfilter)\n    ifc = IFC(location=files[0].parent, filenames=files, keywords=keywords,\n              ext=args.ext)\n\n    if args.exptimefactor != 1:\n        new_exptime = Column([t*args.exptimefactor for t in\n                              ifc.summary[args.exptime]],\n                              dtype=float, name=args.exptime)\n        ifc.summary[args.exptime] = new_exptime\n\n    log.info(f'Found {len(ifc.summary)} image files')\n    if args.verbose is True:\n        print(ifc.summary)\n    RN, master_bias = determine_read_noise(ifc)\n    DC = determine_dark_current(ifc, master_bias)\n    gain = determine_gain(ifc, master_bias, RN)\n\n    if gain is not None:\n        print(f\"Read Noise = {RN*gain:.2f}\")\n        if DC is not None:\n            print(f\"Dark Current = {DC*gain:.3f}\")\n        print(f\"Gain = {gain:.3f}\")\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "de45e10bd1a78ffbc97441cdc24c3c4bcd57193f", "size": 21850, "ext": "py", "lang": "Python", "max_stars_repo_path": "characterize_detector.py", "max_stars_repo_name": "joshwalawender/CharacterizeDetector", "max_stars_repo_head_hexsha": "3c945b7536dd72c7c8083971b3345b757c1ab13b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "characterize_detector.py", "max_issues_repo_name": "joshwalawender/CharacterizeDetector", "max_issues_repo_head_hexsha": "3c945b7536dd72c7c8083971b3345b757c1ab13b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "characterize_detector.py", "max_forks_repo_name": "joshwalawender/CharacterizeDetector", "max_forks_repo_head_hexsha": "3c945b7536dd72c7c8083971b3345b757c1ab13b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4611005693, "max_line_length": 95, "alphanum_fraction": 0.5621510297, "include": true, "reason": "import numpy,from astropy", "num_tokens": 5454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.18466528820031852}}
{"text": "# Modified work:\n# ------------------------------------------------------------------------\n# Copyright (c) 2018 Preferred Networks, Inc.\n# ------------------------------------------------------------------------\n\n# Original works of CUDA kernel in forward_gpu and backward_gpu:\n# ------------------------------------------------------------------------\n# Copyright (c) 2017 Microsoft\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Written by Yi Li, Tairui Chen, Guodong Zhang, Haozhi Qi and Jifeng Dai\n# https://github.com/msracver/FCIS\n# ------------------------------------------------------------------------\n\n\nfrom __future__ import division\n\nimport numpy as np\nimport six\n\nimport chainer\nfrom chainer.backends import cuda\nfrom chainer import function\nfrom chainer.utils import type_check\n\n\ndef _outsize(x):\n    if isinstance(x, chainer.utils.collections_abc.Iterable):\n        if len(x) == 2:\n            return (None, ) + x\n        else:\n            return x\n    return None, x, x\n\n\nclass PSROIAveragePooling2D(function.Function):\n\n    def __init__(self, outsize, spatial_scale, group_size):\n        out_c, out_h, out_w = _outsize(outsize)\n        if out_c is not None and not (isinstance(out_c, int) and out_c > 0):\n            raise TypeError(\n                'outsize[0] must be positive integer: {}, {}'\n                .format(type(out_c), out_c))\n        if not (isinstance(out_h, int) and out_h > 0):\n            raise TypeError(\n                'outsize[1] must be positive integer: {}, {}'\n                .format(type(out_h), out_h))\n        if not (isinstance(out_w, int) and out_w > 0):\n            raise TypeError(\n                'outsize[2] must be positive integer: {}, {}'\n                .format(type(out_w), out_w))\n        if isinstance(spatial_scale, int):\n            spatial_scale = float(spatial_scale)\n        if not (isinstance(group_size, int) and group_size > 0):\n            raise TypeError(\n                'group_size must be positive integer: {}, {}'\n                .format(type(group_size), group_size))\n        self.out_c, self.out_h, self.out_w = out_c, out_h, out_w\n        self.spatial_scale = spatial_scale\n        self.group_size = group_size\n\n    def check_type_forward(self, in_types):\n        type_check.expect(in_types.size() == 3)\n\n        x_type, roi_type, roi_index_type = in_types\n        type_check.expect(\n            x_type.dtype == np.float32,\n            x_type.ndim == 4,\n            roi_type.dtype == np.float32,\n            roi_type.ndim == 2,\n            roi_type.shape[1] == 4,\n            roi_index_type.dtype == np.int32,\n            roi_index_type.ndim == 1,\n            roi_type.shape[0] == roi_index_type.shape[0]\n        )\n\n    def forward_cpu(self, inputs):\n        self.retain_inputs((1, 2))\n        self._bottom_data_shape = inputs[0].shape\n\n        bottom_data, bottom_rois, bottom_roi_indices = inputs\n        channel, height, width = bottom_data.shape[1:]\n        if self.out_c is None:\n            if channel % (self.group_size * self.group_size) != 0:\n                raise ValueError(\n                    'input channel must be divided by group_size * group_size:'\n                    '{} % {} != 0'\n                    .format(channel, self.group_size * self.group_size))\n            out_c = channel // (self.group_size * self.group_size)\n        else:\n            if channel != self.out_c * self.group_size * self.group_size:\n                raise ValueError(\n                    'input channel must be equal to'\n                    'outsize[0] * group_size * group_size: {} != {}'\n                    .format(channel,\n                            self.out_c * self.group_size * self.group_size))\n            out_c = self.out_c\n        n_roi = bottom_rois.shape[0]\n        top_data = np.empty(\n            (n_roi, out_c, self.out_h, self.out_w), dtype=np.float32)\n\n        spatial_scale = self.spatial_scale\n        pooled_height = self.out_h\n        pooled_width = self.out_w\n        group_size = self.group_size\n\n        for i in six.moves.range(top_data.size):\n            n, ctop, ph, pw = np.unravel_index(i, top_data.shape)\n\n            roi_batch_ind = bottom_roi_indices[n]\n            roi_start_h = bottom_rois[n, 0] * spatial_scale\n            roi_start_w = bottom_rois[n, 1] * spatial_scale\n            roi_end_h = bottom_rois[n, 2] * spatial_scale\n            roi_end_w = bottom_rois[n, 3] * spatial_scale\n\n            roi_height = max(roi_end_h - roi_start_h, 0.1)\n            roi_width = max(roi_end_w - roi_start_w, 0.1)\n            bin_size_h = roi_height / pooled_height\n            bin_size_w = roi_width / pooled_width\n\n            hstart = int(np.floor(ph * bin_size_h + roi_start_h))\n            wstart = int(np.floor(pw * bin_size_w + roi_start_w))\n            hend = int(np.ceil((ph + 1) * bin_size_h + roi_start_h))\n            wend = int(np.ceil((pw + 1) * bin_size_w + roi_start_w))\n            hstart = min(max(hstart, 0), height)\n            wstart = min(max(wstart, 0), width)\n            hend = min(max(hend, 0), height)\n            wend = min(max(wend, 0), width)\n\n            gh = int(np.floor(ph * group_size / pooled_height))\n            gw = int(np.floor(pw * group_size / pooled_width))\n            gh = min(max(gh, 0), group_size - 1)\n            gw = min(max(gw, 0), group_size - 1)\n            c = (ctop * group_size + gh) * group_size + gw\n\n            if hstart >= hend or wstart >= wend:\n                top_data[n, ctop, ph, pw] = 0\n                continue\n\n            top_data[n, ctop, ph, pw] = np.mean(\n                bottom_data[roi_batch_ind, c, hstart:hend, wstart:wend])\n\n        return top_data,\n\n    def forward_gpu(self, inputs):\n        self.retain_inputs((1, 2))\n        self._bottom_data_shape = inputs[0].shape\n\n        bottom_data, bottom_rois, bottom_roi_indices = inputs\n        channel, height, width = bottom_data.shape[1:]\n        if self.out_c is None:\n            if channel % (self.group_size * self.group_size) != 0:\n                raise ValueError(\n                    'input channel must be divided by group_size * group_size:'\n                    '{} % {} != 0'\n                    .format(channel, self.group_size * self.group_size))\n            out_c = channel // (self.group_size * self.group_size)\n        else:\n            if channel != self.out_c * self.group_size * self.group_size:\n                raise ValueError(\n                    'input channel must be equal to'\n                    'outsize[0] * group_size * group_size: {} != {}'\n                    .format(channel,\n                            self.out_c * self.group_size * self.group_size))\n            out_c = self.out_c\n        n_roi = bottom_rois.shape[0]\n        top_data = cuda.cupy.empty(\n            (n_roi, out_c, self.out_h, self.out_w), dtype=np.float32)\n        cuda.elementwise(\n            '''\n            raw T bottom_data, raw T bottom_rois,\n            raw int32 bottom_roi_indices,\n            T spatial_scale, int32 channel,\n            int32 height, int32 width,\n            int32 pooled_dim, int32 pooled_height, int32 pooled_width,\n            int32 group_size\n            ''',\n            'T top_data',\n            '''\n            // pos in output filter\n            int ph = (i / pooled_width) % pooled_height;\n            int pw = i % pooled_width;\n            int ctop = (i / pooled_width / pooled_height) % pooled_dim;\n            int n = i / pooled_width / pooled_height / pooled_dim;\n\n            int roi_batch_ind = bottom_roi_indices[n];\n            T roi_start_h = bottom_rois[n * 4 + 0] * spatial_scale;\n            T roi_start_w = bottom_rois[n * 4 + 1] * spatial_scale;\n            T roi_end_h = bottom_rois[n * 4 + 2] * spatial_scale;\n            T roi_end_w = bottom_rois[n * 4 + 3] * spatial_scale;\n\n            // Force too small ROIs to be 1x1\n            T roi_height = max(roi_end_h - roi_start_h, 0.1);\n            T roi_width = max(roi_end_w - roi_start_w, 0.1);  // avoid 0\n\n            // Compute w and h at bottom\n            T bin_size_h = roi_height / static_cast<T>(pooled_height);\n            T bin_size_w = roi_width / static_cast<T>(pooled_width);\n\n            int hstart = floor(\n                static_cast<T>(ph) * bin_size_h + roi_start_h);\n            int wstart = floor(\n                static_cast<T>(pw) * bin_size_w + roi_start_w);\n            int hend = ceil(\n                static_cast<T>(ph + 1) * bin_size_h + roi_start_h);\n            int wend = ceil(\n                static_cast<T>(pw + 1) * bin_size_w + roi_start_w);\n\n            // Add roi offsets and clip to input boundaries\n            hstart = min(max(hstart, 0), height);\n            wstart = min(max(wstart, 0), width);\n            hend = min(max(hend, 0), height);\n            wend = min(max(wend, 0), width);\n            bool is_empty = (hend <= hstart) || (wend <= wstart);\n\n            // Compute c at bottom\n            int gh = floor(\n                static_cast<T>(ph) * group_size / pooled_height);\n            int gw = floor(\n                static_cast<T>(pw) * group_size / pooled_width);\n            gh = min(max(gh, 0), group_size - 1);\n            gw = min(max(gw, 0), group_size - 1);\n            int c = (ctop * group_size + gh) * group_size + gw;\n\n            int data_offset = (roi_batch_ind * channel + c) * height * width;\n            T out_sum = 0;\n            for (int h = hstart; h < hend; ++h){\n              for (int w = wstart; w < wend; ++w){\n                 int bottom_index = h * width + w;\n                 out_sum += bottom_data[data_offset + bottom_index];\n              }\n            }\n\n            T bin_area = (hend - hstart) * (wend - wstart);\n            top_data = is_empty? (T) 0. : out_sum / bin_area;\n            ''', 'ps_roi_average_pooling_2d_fwd'\n        )(bottom_data, bottom_rois, bottom_roi_indices,\n          self.spatial_scale, channel, height, width,\n          out_c, self.out_h, self.out_w, self.group_size,\n          top_data)\n\n        return top_data,\n\n    def backward_cpu(self, inputs, gy):\n        _, bottom_rois, bottom_roi_indices = inputs\n        top_diff = gy[0]\n        height, width = self._bottom_data_shape[2:]\n        bottom_diff = np.zeros(self._bottom_data_shape, np.float32)\n\n        spatial_scale = self.spatial_scale\n        pooled_height = self.out_h\n        pooled_width = self.out_w\n        group_size = self.group_size\n\n        for i in six.moves.range(top_diff.size):\n            n, ctop, ph, pw = np.unravel_index(i, top_diff.shape)\n\n            roi_batch_ind = int(bottom_roi_indices[n])\n            roi_start_h = bottom_rois[n, 0] * spatial_scale\n            roi_start_w = bottom_rois[n, 1] * spatial_scale\n            roi_end_h = bottom_rois[n, 2] * spatial_scale\n            roi_end_w = bottom_rois[n, 3] * spatial_scale\n\n            roi_height = max(roi_end_h - roi_start_h, 0.1)\n            roi_width = max(roi_end_w - roi_start_w, 0.1)\n            bin_size_h = roi_height / pooled_height\n            bin_size_w = roi_width / pooled_width\n\n            hstart = int(np.floor(ph * bin_size_h + roi_start_h))\n            wstart = int(np.floor(pw * bin_size_w + roi_start_w))\n            hend = int(np.ceil((ph + 1) * bin_size_h + roi_start_h))\n            wend = int(np.ceil((pw + 1) * bin_size_w + roi_start_w))\n            hstart = min(max(hstart, 0), height)\n            wstart = min(max(wstart, 0), width)\n            hend = min(max(hend, 0), height)\n            wend = min(max(wend, 0), width)\n\n            gh = int(np.floor(ph * group_size / pooled_height))\n            gw = int(np.floor(pw * group_size / pooled_width))\n            gh = min(max(gh, 0), group_size - 1)\n            gw = min(max(gw, 0), group_size - 1)\n            c = (ctop * group_size + gh) * group_size + gw\n\n            if (hstart >= hend) or (wstart >= wend):\n                continue\n\n            count = (hend - hstart) * (wend - wstart)\n            diff_val = top_diff[n, ctop, ph, pw] / count\n            bottom_diff[roi_batch_ind, c, hstart:hend, wstart:wend] += diff_val\n\n        return bottom_diff, None, None\n\n    def backward_gpu(self, inputs, gy):\n        _, bottom_rois, bottom_roi_indices = inputs\n        channels, height, width = self._bottom_data_shape[1:]\n        out_c, out_h, out_w = gy[0].shape[1:]\n        bottom_diff = cuda.cupy.zeros(self._bottom_data_shape, np.float32)\n        cuda.elementwise(\n            '''\n            raw T top_diff, raw T bottom_rois,\n            raw int32 bottom_roi_indices,\n            T spatial_scale, int32 channels, int32 height, int32 width,\n            int32 pooled_dim, int32 pooled_height, int32 pooled_width,\n            int32 group_size\n            ''',\n            'raw T bottom_diff',\n            '''\n            int ph = (i / pooled_width) % pooled_height;\n            int pw = i % pooled_width;\n            int ctop = (i / pooled_width / pooled_height) % pooled_dim;\n            int n = i / pooled_width / pooled_height / pooled_dim;\n\n            // [start, end) interval for spatial sampling\n            int roi_batch_ind = bottom_roi_indices[n];\n            T roi_start_h = bottom_rois[n * 4 + 0] * spatial_scale;\n            T roi_start_w = bottom_rois[n * 4 + 1] * spatial_scale;\n            T roi_end_h = bottom_rois[n * 4 + 2] * spatial_scale;\n            T roi_end_w = bottom_rois[n * 4 + 3] * spatial_scale;\n\n            // Force too small ROIs to be 1x1\n            T roi_height = max(roi_end_h - roi_start_h, 0.1);\n            T roi_width = max(roi_end_w - roi_start_w, 0.1); // avoid 0\n\n            // Compute w and h at bottom\n            T bin_size_h = roi_height / static_cast<T>(pooled_height);\n            T bin_size_w = roi_width / static_cast<T>(pooled_width);\n\n            int hstart = floor(\n                static_cast<T>(ph) * bin_size_h + roi_start_h);\n            int wstart = floor(\n                static_cast<T>(pw) * bin_size_w + roi_start_w);\n            int hend = ceil(\n                static_cast<T>(ph + 1.0) * bin_size_h + roi_start_h);\n            int wend = ceil(\n                static_cast<T>(pw + 1.0) * bin_size_w + roi_start_w);\n\n            // Add roi offsets and clip to input boundaries\n            hstart = min(max(hstart, 0), height);\n            wstart = min(max(wstart, 0), width);\n            hend = min(max(hend, 0), height);\n            wend = min(max(wend, 0), width);\n            bool is_empty = (hend <= hstart) || (wend <= wstart);\n\n            // Compute c at bottom\n            int gh = floor(\n                static_cast<T>(ph) * group_size / pooled_height);\n            int gw = floor(\n                static_cast<T>(pw) * group_size / pooled_width);\n            gh = min(max(gh, 0), group_size - 1);\n            gw = min(max(gw, 0), group_size - 1);\n            int c = (ctop * group_size + gh) * group_size + gw;\n\n            int bottom_diff_offset = (roi_batch_ind * channels + c);\n            bottom_diff_offset = bottom_diff_offset * height * width;\n            int top_offset =\n                (n * pooled_dim + ctop) * pooled_height * pooled_width;\n\n            T bin_area = (hend - hstart) * (wend - wstart);\n            T diff_val = is_empty ? (T) 0. :\n                top_diff[top_offset + ph * pooled_width + pw] / bin_area;\n            for (int h = hstart; h < hend; ++h){\n              for (int w = wstart; w < wend; ++w){\n                int bottom_index = h * width + w;\n                atomicAdd(\n                    &bottom_diff[bottom_diff_offset + bottom_index], diff_val);\n              }\n            }\n            ''', 'ps_roi_average_pooling_2d_bwd'\n        )(gy[0], bottom_rois, bottom_roi_indices,\n          self.spatial_scale, channels, height, width,\n          out_c, out_h, out_w, self.group_size, bottom_diff,\n          size=gy[0].size)\n\n        return bottom_diff, None, None\n\n\ndef ps_roi_average_pooling_2d(\n        x, rois, roi_indices, outsize,\n        spatial_scale, group_size\n):\n    \"\"\"Position Sensitive Region of Interest (ROI) Average pooling function.\n\n    This function computes position sensitive average of input spatial patch\n    with the given region of interests. Each ROI is splitted into\n    :math:`(group\\_size, group\\_size)` regions, and position sensitive values\n    in each region is computed.\n\n    Args:\n        x (~chainer.Variable): Input variable. The shape is expected to be\n            4 dimentional: (n: batch, c: channel, h, height, w: width).\n        rois (array): Input roi. The shape is expected to\n            be :math:`(R, 4)`, and each datum is set as below:\n            (y_min, x_min, y_max, x_max). The dtype is :obj:`numpy.float32`.\n        roi_indices (array): Input roi indices. The shape is expected to\n            be :math:`(R, )`. The dtype is :obj:`numpy.int32`.\n        outsize ((int, int, int) or (int, int) or int): Expected output size\n            after pooled: (channel, height, width) or (height, width)\n            or outsize. ``outsize=o`` and ``outsize=(o, o)`` are equivalent.\n            Channel parameter is used to assert the input shape.\n        spatial_scale (float): Scale of the roi is resized.\n        group_size (int): Position sensitive group size.\n\n    Returns:\n        ~chainer.Variable: Output variable.\n\n    See the original paper proposing PSROIPooling:\n    `R-FCN <https://arxiv.org/abs/1605.06409>`_.\n\n    \"\"\"\n    return PSROIAveragePooling2D(outsize, spatial_scale,\n                                 group_size)(x, rois, roi_indices)\n", "meta": {"hexsha": "b46d43d6162d7046f65edeaf95562a8943f8af7e", "size": 17867, "ext": "py", "lang": "Python", "max_stars_repo_path": "chainercv/functions/ps_roi_average_pooling_2d.py", "max_stars_repo_name": "tn1031/chainercv", "max_stars_repo_head_hexsha": "6c96fedf283d69f6d328bf504a201299120c407b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-14T06:27:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-14T06:27:10.000Z", "max_issues_repo_path": "chainercv/functions/ps_roi_average_pooling_2d.py", "max_issues_repo_name": "tn1031/chainercv", "max_issues_repo_head_hexsha": "6c96fedf283d69f6d328bf504a201299120c407b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chainercv/functions/ps_roi_average_pooling_2d.py", "max_forks_repo_name": "tn1031/chainercv", "max_forks_repo_head_hexsha": "6c96fedf283d69f6d328bf504a201299120c407b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.2387706856, "max_line_length": 79, "alphanum_fraction": 0.5579000392, "include": true, "reason": "import numpy", "num_tokens": 4441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.18466528099195198}}
{"text": "from collections import defaultdict\nimport numpy as np\nimport jieba\n\ntext1 = \"\"\"\nHi, everyone! My name is Gang and I am gonna introduce you an amazing text-rank algorithm. What is this algorithm? It's \na really good algorithm because its efficiency and robust. You can type your own text to get a text-rank of your own \nwords, to see how brilliant this algorithm is. So, how does this algorithm work? It uses a concept that an algorithm \nis always an good algorithm as long as it is written by me. Make sense? No? OK, actually this text-rank algorithm uses\nconcept of NLP, which is Natural Language Processing, a significant algorithm nowadays in machine learning area.\nActually I don't know well about NLP, but I understand NLP algorithm is very cool. NLP algorithm help me design and \nimplement this text rank algorithm. Now, can you guess the keywords of this stupid text? \nIs that like \"Algorithm\",\"text rank\"? Do you believe this program can figure it out? Let's see!\"\"\"\n\n\"\"\"confidence between word and word, dict\"\"\"\n# text = open('./words/text.txt','r',encoding='utf-8').read()\n#text = text1\n\n\nclass TextRank():\n    def __init__(self,txtin):\n        self.text = txtin\n        self.confidence_Dict = dict()\n        self.allWord = \"\"\n        self.li_np = np.array(0)\n        self.M = \"\"\n        self.U = \"\"\n        self.li = \"\"\n\n    def get_word_confidence(self):\n        # global confidence_Dict\n        # global allWord\n        stopwords = {line.strip(): 1 for line in open('./words/stopwords.txt', 'r', encoding='utf-8').readlines()}\n\n        sentence_li = [i.lstrip().rstrip() for i in self.text.split('.')]\n\n        co_tuple_dict = defaultdict(int)\n        num_dict = defaultdict(int)\n        for sentence in sentence_li:\n\n            word_li = [i for i in jieba.cut(sentence) if not stopwords.get(i, None)]\n            # print(word_li)\n            for i in range(word_li.count(' ')):\n                if ' ' in word_li:\n                    word_li.remove(' ')\n                if '\\n' in word_li:\n                    word_li.remove('\\n')\n            # print(word_li)\n            for index in range(100):\n                new_word_li = word_li[index:index + 5]\n                if len(new_word_li) == 5:\n                    for a in new_word_li:\n                        num_dict[a] += 1\n                        for b in new_word_li:\n                            if a != b:\n                                co_tuple_dict[(a, b)] += 1\n\n        # print(co_tuple_dict)\n        # print(num_dict)\n        self.confidence_Dict = dict()\n        for tuple_ab, num in co_tuple_dict.items():\n            self.confidence_Dict[tuple_ab] = num / num_dict[tuple_ab[0]]\n\n        self.allWord = num_dict.keys()\n        # print(allWord)\n        # print(len(allWord))\n        # return self.confidence_Dict, self.allWord\n\n\n    \"\"\"get textrank's idea\"\"\"\n\n\n    def get_matrix(self):\n        # global li_np\n        li = []\n        for word in self.allWord:\n            li2 = []\n            for word2 in self.allWord:\n                cow = self.confidence_Dict.get((word, word2), 0)\n                li2.append(cow / 4)\n            li.append(li2)\n            # print(sum(li2))\n        # print(li)\n        self.li_np = np.array(li)\n        # return li_np\n\n\n    \"\"\"initialize,converge\"\"\"\n\n\n    def calculate_converge_list(self):\n        # global M, U\n        self.M = self.li_np.T\n        self.U = [1 / len(self.allWord) for i in self.allWord]\n        U0 = np.array(self.U)\n        # print(U0)\n        U_past = []\n        while True:\n            # U = np.dot(M, U)\n            self.U = 0.85 * (np.dot(self.M, self.U)) + 0.15 * U0\n            # print('Un: ', U)\n            if str(self.U) == str(U_past):\n                break\n            U_past = self.U\n            # print(U)\n\n        # print('U converge to: ', U)\n        # print(list(zip(allWord, U)))\n        self.li = sorted(list(zip(self.allWord, self.U)), key=lambda x: x[1], reverse=True)\n        # print(li)\n        # return li\n\n\n    '''\n    In this approach, I just try to combine any two words of the sorted (ranked) words.\n    '''\n\n\n    def get_combine_word(self):\n        \"\"\"combination of words\"\"\"\n        i = 0\n        j = 0\n        k = 0\n        wordlist = []\n        # print(sorted_li)\n        sorted_li = self.li\n        print(\"Ranked keywords of this article:\\n\")\n        for w1 in sorted_li[:10]:\n            for w2 in sorted_li[:10]:\n                if w1[0] + ' ' + w2[0] in self.text:\n                    i += 1\n                    print(\"Two keywords combination \" + str(i)\n                          + \": \" + w1[0] + ' ' + w2[0])\n                    wordlist.append((\"Two keywords combination \" + str(i)\n                          + \": \" + w1[0] + ' ' + w2[0]))\n                for w3 in sorted_li[:10]:\n                    if w1[0] + ' ' + w2[0] + ' ' + w3[0] in self.text:\n                        j += 1\n                        print(\"Three keywords combination \" + str(j)\n                              + \": \" + w1[0] + ' ' + w2[0] + ' ' + w3[0])\n                        wordlist.append((\"Three keywords combination \" + str(j)\n                              + \": \" + w1[0] + ' ' + w2[0] + ' ' + w3[0]))\n                    for w4 in sorted_li[:20]:\n                        if w1[0] + ' ' + w2[0] + ' ' + w3[0] + ' ' + w4[0] in self.text:\n                            k += 1\n                            print(\"Four keywords combination \" + str(j)\n                                  + \": \" + w1[0] + ' ' + w2[0] + ' '\n                                  + w4[0] + ' ' + w3[0])\n        return wordlist\n\n# if __name__ == '__main__':\n#     confidence_Dict, allWord = get_word_confidence()\n#     li_np = get_matrix()\n#     sorted_li = calculate_converge_list()\n#     out_path = './words/keywords.txt'\n#     file = open(out_path, 'w')\n#     for i in get_combine_word():\n#         file.write(i + '\\n')\n#     file.close()\n", "meta": {"hexsha": "8dc39dd8f35a9286e9b629fd4974483c8c32623b", "size": 5859, "ext": "py", "lang": "Python", "max_stars_repo_path": "textRankVersion0.py", "max_stars_repo_name": "ec500-software-engineering/project-20-solar_wind_classification", "max_stars_repo_head_hexsha": "da2abdd1a729e307165719b439469f2723460c46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "textRankVersion0.py", "max_issues_repo_name": "ec500-software-engineering/project-20-solar_wind_classification", "max_issues_repo_head_hexsha": "da2abdd1a729e307165719b439469f2723460c46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "textRankVersion0.py", "max_forks_repo_name": "ec500-software-engineering/project-20-solar_wind_classification", "max_forks_repo_head_hexsha": "da2abdd1a729e307165719b439469f2723460c46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.61875, "max_line_length": 120, "alphanum_fraction": 0.5081071855, "include": true, "reason": "import numpy", "num_tokens": 1479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.1845208729913743}}
{"text": "# This file is part of the OpenProtein project.\n#\n# @author Jeppe Hallgren\n#\n# For license information, please see the LICENSE file in the root directory.\n\nimport torch\nimport torch.utils.data\nimport h5py\nfrom datetime import datetime\nimport PeptideBuilder\nimport Bio.PDB\nimport math\nimport numpy as np\nimport os\nimport pnerf.pnerf as pnerf\n\nAA_ID_DICT = {'A': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'K': 9,\n              'L': 10, 'M': 11, 'N': 12, 'P': 13, 'Q': 14, 'R': 15, 'S': 16, 'T': 17,\n              'V': 18, 'W': 19,'Y': 20}\n\ndef contruct_dataloader_from_disk(filename, minibatch_size):\n    return torch.utils.data.DataLoader(H5PytorchDataset(filename), batch_size=minibatch_size,\n                                       shuffle=True, collate_fn=H5PytorchDataset.merge_samples_to_minibatch)\n\n\nclass H5PytorchDataset(torch.utils.data.Dataset):\n    def __init__(self, filename):\n        super(H5PytorchDataset, self).__init__()\n\n        self.h5pyfile = h5py.File(filename, 'r')\n        self.num_proteins, self.max_sequence_len = self.h5pyfile['primary'].shape\n\n    def __getitem__(self, index):\n        mask = torch.Tensor(self.h5pyfile['mask'][index,:]).type(dtype=torch.uint8)\n        prim = torch.masked_select(torch.Tensor(self.h5pyfile['primary'][index,:]).type(dtype=torch.long), mask)\n        tertiary = torch.Tensor(self.h5pyfile['tertiary'][index][:int(mask.sum())]) # max length x 9\n        return  prim, tertiary, mask\n\n    def __len__(self):\n        return self.num_proteins\n\n    def merge_samples_to_minibatch(samples):\n        samples_list = []\n        for s in samples:\n            samples_list.append(s)\n        # sort according to length of aa sequence\n        samples_list.sort(key=lambda x: len(x[0]), reverse=True)\n        return zip(*samples_list)\n\ndef set_experiment_id(data_set_identifier, learning_rate, minibatch_size):\n    output_string = datetime.now().strftime('%Y-%m-%d_%H_%M_%S')\n    output_string += \"-\" + str(os.getpid())\n    output_string += \"-\" + data_set_identifier\n    output_string += \"-LR\" + str(learning_rate).replace(\".\",\"_\")\n    output_string += \"-MB\" + str(minibatch_size)\n    globals().__setitem__(\"experiment_id\",output_string)\n\ndef get_experiment_id():\n    return globals().get(\"experiment_id\")\n\ndef write_out(*args, end='\\n'):\n    output_string = datetime.now().strftime('%Y-%m-%d %H:%M:%S') + \": \" + str.join(\" \", [str(a) for a in args]) + end\n    if globals().get(\"experiment_id\") is not None:\n        with open(\"output/\"+globals().get(\"experiment_id\")+\".txt\", \"a+\") as output_file:\n            output_file.write(output_string)\n            output_file.flush()\n    print(output_string, end=\"\")\n\ndef write_model_to_disk(model):\n    path = \"output/models/\"+globals().get(\"experiment_id\")+\".model\"\n    torch.save(model,path)\n    return path\n\n\ndef write_prediction_data_to_disk(prediction_data):\n    filepath = \"output/predictions/\"+globals().get(\"experiment_id\")+\".txt\"\n    output_file = open(filepath, 'w')\n    output_file.write(prediction_data)\n    output_file.close()\n\ndef draw_plot(fig, plt, validation_dataset_size, sample_num, train_loss_values,\n              validation_loss_values):\n    def draw_with_vars():\n        ax = fig.gca()\n        ax2 = ax.twinx()\n        plt.grid(True)\n        plt.title(\"Training progress (\" + str(validation_dataset_size) + \" samples in validation set)\")\n        train_loss_plot, = ax.plot(sample_num, train_loss_values)\n        ax.set_ylabel('Train Negative log likelihood')\n        ax.yaxis.labelpad = 0\n        validation_loss_plot, = ax2.plot(sample_num, validation_loss_values, color='black')\n        ax2.set_ylabel('Validation loss')\n        ax2.set_ylim(bottom=0)\n        plt.legend([train_loss_plot, validation_loss_plot],\n                   ['Train loss on last batch', 'Validation loss'])\n        ax.set_xlabel('Minibatches processed (=network updates)', color='black')\n    return draw_with_vars\n\ndef draw_ramachandran_plot(fig, plt, phi, psi):\n    def draw_with_vars():\n        ax = fig.gca()\n        plt.grid(True)\n        plt.title(\"Ramachandran plot\")\n        train_loss_plot, = ax.plot(phi, psi)\n        ax.set_ylabel('Psi')\n        ax.yaxis.labelpad = 0\n        plt.legend([train_loss_plot],\n                   ['Phi psi'])\n        ax.set_xlabel('Phi', color='black')\n    return draw_with_vars\n\ndef write_result_summary(accuracy):\n    output_string = globals().get(\"experiment_id\") + \": \" + str(accuracy) + \"\\n\"\n    with open(\"output/result_summary.txt\", \"a+\") as output_file:\n        output_file.write(output_string)\n        output_file.flush()\n    print(output_string, end=\"\")\n\ndef calculate_dihedral_angles_over_minibatch(atomic_coords_padded, batch_sizes, use_gpu):\n    angles = []\n    atomic_coords = atomic_coords_padded.transpose(0,1)\n    for idx, _ in enumerate(batch_sizes):\n        angles.append(calculate_dihedral_angles(atomic_coords[idx][:batch_sizes[idx]], use_gpu))\n    return torch.nn.utils.rnn.pad_packed_sequence(\n            torch.nn.utils.rnn.pack_sequence(angles))\n\ndef protein_id_to_str(protein_id_list):\n    _aa_dict_inverse = {v: k for k, v in AA_ID_DICT.items()}\n    aa_list = []\n    for a in protein_id_list:\n        aa_symbol = _aa_dict_inverse[int(a)]\n        aa_list.append(aa_symbol)\n    return aa_list\n\ndef calculate_dihedral_angles(atomic_coords, use_gpu):\n\n    assert int(atomic_coords.shape[1]) == 9\n    atomic_coords = atomic_coords.contiguous().view(-1,3)\n\n    zero_tensor = torch.tensor(0.0)\n    if use_gpu:\n        zero_tensor = zero_tensor.cuda()\n\n    dihedral_list = [zero_tensor,zero_tensor]\n    dihedral_list.extend(compute_dihedral_list(atomic_coords))\n    dihedral_list.append(zero_tensor)\n    angles = torch.tensor(dihedral_list).view(-1,3)\n    return angles\n\ndef compute_dihedral_list(atomic_coords):\n    # atomic_coords is -1 x 3\n    ba = atomic_coords[1:] - atomic_coords[:-1]\n    ba /= ba.norm(dim=1).unsqueeze(1)\n    ba_neg = -1 * ba\n\n    n1_vec = torch.cross(ba[:-2], ba_neg[1:-1], dim=1)\n    n2_vec = torch.cross(ba_neg[1:-1], ba[2:], dim=1)\n    n1_vec /= n1_vec.norm(dim=1).unsqueeze(1)\n    n2_vec /= n2_vec.norm(dim=1).unsqueeze(1)\n\n    m1_vec = torch.cross(n1_vec, ba_neg[1:-1], dim=1)\n\n    x = torch.sum(n1_vec*n2_vec,dim=1)\n    y = torch.sum(m1_vec*n2_vec,dim=1)\n\n    return torch.atan2(y,x)\n\ndef get_structure_from_angles(aa_list_encoded, angles):\n    aa_list = protein_id_to_str(aa_list_encoded)\n    omega_list = angles[1:,0]\n    phi_list = angles[1:,1]\n    psi_list = angles[:-1,2]\n    assert len(aa_list) == len(phi_list)+1 == len(psi_list)+1 == len(omega_list)+1\n    structure = PeptideBuilder.make_structure(aa_list,\n                                              list(map(lambda x: math.degrees(x), phi_list)),\n                                              list(map(lambda x: math.degrees(x), psi_list)),\n                                              list(map(lambda x: math.degrees(x), omega_list)))\n    return structure\n\ndef write_to_pdb(structure, prot_id):\n    out = Bio.PDB.PDBIO()\n    out.set_structure(structure)\n    out.save(\"output/protein_\" + str(prot_id) + \".pdb\")\n\ndef calc_pairwise_distances(chain_a, chain_b, use_gpu):\n    distance_matrix = torch.Tensor(chain_a.size()[0], chain_b.size()[0]).type(torch.float)\n    # add small epsilon to avoid boundary issues\n    epsilon = 10 ** (-4) * torch.ones(chain_a.size(0), chain_b.size(0))\n    if use_gpu:\n        distance_matrix = distance_matrix.cuda()\n        epsilon = epsilon.cuda()\n\n    for i, row in enumerate(chain_a.split(1)):\n        distance_matrix[i] = torch.sum((row.expand_as(chain_b) - chain_b) ** 2, 1).view(1, -1)\n\n    return torch.sqrt(distance_matrix + epsilon)\n\ndef calc_drmsd(chain_a, chain_b, use_gpu=False):\n    assert len(chain_a) == len(chain_b)\n    distance_matrix_a = calc_pairwise_distances(chain_a, chain_a, use_gpu)\n    distance_matrix_b = calc_pairwise_distances(chain_b, chain_b, use_gpu)\n    return torch.norm(distance_matrix_a - distance_matrix_b, 2) \\\n            / math.sqrt((len(chain_a) * (len(chain_a) - 1)))\n\n# method for translating a point cloud to its center of mass\ndef transpose_atoms_to_center_of_mass(x):\n    # calculate com by summing x, y and z respectively\n    # and dividing by the number of points\n    centerOfMass = np.matrix([[x[0, :].sum() / x.shape[1]],\n                    [x[1, :].sum() / x.shape[1]],\n                    [x[2, :].sum() / x.shape[1]]])\n    # translate points to com and return\n    return x - centerOfMass\n\ndef calc_rmsd(chain_a, chain_b):\n    # move to center of mass\n    a = chain_a.cpu().numpy().transpose()\n    b = chain_b.cpu().numpy().transpose()\n    X = transpose_atoms_to_center_of_mass(a)\n    Y = transpose_atoms_to_center_of_mass(b)\n\n    R = Y * X.transpose()\n    # extract the singular values\n    _, S, _ = np.linalg.svd(R)\n    # compute RMSD using the formular\n    E0 = sum(list(np.linalg.norm(x) ** 2 for x in X.transpose())\n             + list(np.linalg.norm(x) ** 2 for x in Y.transpose()))\n    TraceS = sum(S)\n    RMSD = np.sqrt((1 / len(X.transpose())) * (E0 - 2 * TraceS))\n    return RMSD\n\ndef calc_angular_difference(a1, a2):\n    a1 = a1.transpose(0,1).contiguous()\n    a2 = a2.transpose(0,1).contiguous()\n    sum = 0\n    for idx, _ in enumerate(a1):\n        assert a1[idx].shape[1] == 3\n        assert a2[idx].shape[1] == 3\n        a1_element = a1[idx].view(-1, 1)\n        a2_element = a2[idx].view(-1, 1)\n        sum += torch.sqrt(torch.mean(\n            torch.min(torch.abs(a2_element - a1_element),\n                      2 * math.pi - torch.abs(a2_element - a1_element)\n                      ) ** 2))\n    return sum / a1.shape[0]\n\ndef structures_to_backbone_atoms_padded(structures):\n    backbone_atoms_list = []\n    for structure in structures:\n        backbone_atoms_list.append(structure_to_backbone_atoms(structure))\n    backbone_atoms_padded, batch_sizes_backbone = torch.nn.utils.rnn.pad_packed_sequence(\n        torch.nn.utils.rnn.pack_sequence(backbone_atoms_list))\n    return backbone_atoms_padded, batch_sizes_backbone\n\ndef structure_to_backbone_atoms(structure):\n    predicted_coords = []\n    for res in structure.get_residues():\n        predicted_coords.append(torch.Tensor(res[\"N\"].get_coord()))\n        predicted_coords.append(torch.Tensor(res[\"CA\"].get_coord()))\n        predicted_coords.append(torch.Tensor(res[\"C\"].get_coord()))\n    return torch.stack(predicted_coords).view(-1,9)\n\ndef get_backbone_positions_from_angular_prediction(angular_emissions, batch_sizes, use_gpu):\n    # angular_emissions -1 x minibatch size x 3 (omega, phi, psi)\n    points = pnerf.dihedral_to_point(angular_emissions, use_gpu)\n    coordinates = pnerf.point_to_coordinate(points, use_gpu) / 100 # devide by 100 to angstrom unit\n    return coordinates.transpose(0,1).contiguous().view(len(batch_sizes),-1,9).transpose(0,1), batch_sizes\n\n\ndef calc_avg_drmsd_over_minibatch(backbone_atoms_padded, actual_coords_padded, batch_sizes):\n    backbone_atoms_list = list(\n        [backbone_atoms_padded[:batch_sizes[i], i] for i in range(int(backbone_atoms_padded.size(1)))])\n    actual_coords_list = list(\n        [actual_coords_padded[:batch_sizes[i], i] for i in range(int(actual_coords_padded.size(1)))])\n    drmsd_avg = 0\n    for idx, backbone_atoms in enumerate(backbone_atoms_list):\n        actual_coords = actual_coords_list[idx].transpose(0, 1).contiguous().view(-1, 3)\n        drmsd_avg += calc_drmsd(backbone_atoms.transpose(0, 1).contiguous().view(-1, 3), actual_coords)\n    return drmsd_avg / len(backbone_atoms_list)\n\ndef encode_primary_string(primary):\n    return list([AA_ID_DICT[aa] for aa in primary])\n\ndef intial_pos_from_aa_string(batch_aa_string):\n    structures = []\n    for aa_string in batch_aa_string:\n        structure = get_structure_from_angles(aa_string,\n                                              np.repeat([-120], len(aa_string)-1),\n                                              np.repeat([140], len(aa_string)-1),\n                                              np.repeat([-370], len(aa_string)-1))\n        structures.append(structure)\n    return structures\n\ndef pass_messages(aa_features, message_transformation, use_gpu):\n    # aa_features (#aa, #features) - each row represents the amino acid type (embedding) and the positions of the backbone atoms\n    # message_transformation: (-1 * 2 * feature_size) -> (-1 * output message size)\n    feature_size = aa_features.size(1)\n    aa_count = aa_features.size(0)\n    eye = torch.eye(aa_count,dtype=torch.uint8).view(-1).expand(2,feature_size,-1).transpose(1,2).transpose(0,1)\n    eye_inverted = torch.ones(eye.size(),dtype=torch.uint8) - eye\n    if use_gpu:\n        eye_inverted = eye_inverted.cuda()\n    features_repeated = aa_features.repeat((aa_count,1)).view((aa_count,aa_count,feature_size))\n    aa_messages = torch.stack((features_repeated.transpose(0,1), features_repeated)).transpose(0,1).transpose(1,2).view(-1,2,feature_size)\n    aa_msg_pairs = torch.masked_select(aa_messages,eye_inverted).view(-1,2,feature_size) # (aa_count^2 - aa_count) x 2 x aa_features     (all pairs except for reflexive connections)\n    transformed = message_transformation(aa_msg_pairs).view(aa_count, aa_count - 1, -1)\n    transformed_sum = transformed.sum(dim=1) # aa_count x output message size\n    return transformed_sum\n\ndef load_model_from_disk(path, force_cpu=True):\n    if force_cpu:\n        # load model with map_location set to storage (main mem)\n        model = torch.load(path, map_location=lambda storage, loc: storage)\n        # flattern parameters in memory\n        model.flatten_parameters()\n        # update internal state accordingly\n        model.use_gpu = False\n    else:\n        # load model using default map_location\n        model = torch.load(path)\n        model.flatten_parameters()\n    return model", "meta": {"hexsha": "ca40aa93d92c82e96789b0c2442b4ad302588968", "size": 13714, "ext": "py", "lang": "Python", "max_stars_repo_path": "util.py", "max_stars_repo_name": "lucidrains/openprotein", "max_stars_repo_head_hexsha": "c3a996a2fd233e465760888d2255ce35be050c5e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "util.py", "max_issues_repo_name": "lucidrains/openprotein", "max_issues_repo_head_hexsha": "c3a996a2fd233e465760888d2255ce35be050c5e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util.py", "max_forks_repo_name": "lucidrains/openprotein", "max_forks_repo_head_hexsha": "c3a996a2fd233e465760888d2255ce35be050c5e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-10T12:40:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T12:40:29.000Z", "avg_line_length": 42.4582043344, "max_line_length": 181, "alphanum_fraction": 0.6658888727, "include": true, "reason": "import numpy", "num_tokens": 3523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.18452087299137426}}
{"text": "import os\nimport warnings\nimport subprocess \nimport numpy as np\nimport pandas as pd\nfrom astropy.time import Time\n\nfrom ..constants import Constants as c\nfrom ..utils import _checkTime\nfrom ..orbits import propagateUniversal\nfrom ..orbits import generateEphemerisUniversal\nfrom ..orbits import shiftOrbitsOrigin\nfrom ..observatories import getObserverState\nfrom .backend import Backend\n\nMU = c.G * c.M_SUN\nMJOLNIR_CONFIG = {\n    \"origin\" : \"heliocenter\",\n    \"light_time\" : True, \n    \"lt_tol\" : 1e-10,\n    \"stellar_aberration\" : False,\n    \"mu\" : MU,\n    \"max_iter\" : 1000, \n    \"tol\" : 1e-16 \n}\n\nclass MJOLNIR(Backend):\n    \n    def __init__(self, **kwargs):\n        \n        # Make sure only the correct kwargs\n        # are passed to the constructor\n        allowed_kwargs = MJOLNIR_CONFIG.keys()\n        for k in kwargs:\n            if k not in allowed_kwargs:\n                raise ValueError()\n        \n        # If an allowed kwarg is missing, add the \n        # default \n        for k in allowed_kwargs:\n            if k not in kwargs:\n                kwargs[k] = MJOLNIR_CONFIG[k]\n        \n        super(MJOLNIR, self).__init__(**kwargs)\n\n        return\n\n    def _propagateOrbits(self, orbits, t1):\n        \"\"\"\n        \n\n        \"\"\"\n        # All propagations in THOR should be done with times in the TDB time scale\n        t0_tdb = orbits.epochs.tdb.mjd\n        t1_tdb = t1.tdb.mjd\n\n        if self.origin == \"barycenter\":\n            # Shift orbits to barycenter\n            orbits_ = shiftOrbitsOrigin(\n                orbits.cartesian, \n                orbits.epochs,  \n                origin_in=\"heliocenter\",\n                origin_out=\"barycenter\"\n            )\n\n        elif self.origin == \"heliocenter\":\n            orbits_ = orbits.cartesian\n            \n        else:\n            err = (\n                \"origin should be one of {'heliocenter', 'barycenter'}\"\n            )\n            raise ValueError(err)\n\n        propagated = propagateUniversal(\n            orbits_, \n            t0_tdb, \n            t1_tdb, \n            mu=self.mu,\n            max_iter=self.max_iter,\n            tol=self.tol\n        )\n\n        if self.origin == \"barycenter\":\n            t1_tdb_stacked = Time(\n                propagated[:, 1], \n                scale=\"tdb\", \n                format=\"mjd\"\n            )\n            propagated[:, 2:] = shiftOrbitsOrigin(\n                propagated[:, 2:], \n                t1_tdb_stacked, \n                origin_in=\"barycenter\",\n                origin_out=\"heliocenter\"\n            )\n\n        propagated = pd.DataFrame(\n            propagated,\n            columns=[\n                \"orbit_id\",\n                \"epoch_mjd_tdb\",\n                \"x\",\n                \"y\",\n                \"z\",\n                \"vx\",\n                \"vy\",\n                \"vz\",\n            ]\n        )\n        propagated[\"orbit_id\"] = propagated[\"orbit_id\"].astype(int)\n\n        if orbits.ids is not None:\n            propagated[\"orbit_id\"] = orbits.ids[propagated[\"orbit_id\"].values]\n\n        return propagated\n\n    def _generateEphemeris(self, orbits, observers):\n\n        observer_states_list = []\n        for observatory_code, observation_times in observers.items():\n            # Check that the observation times are astropy time objects\n            _checkTime(\n                observation_times, \n                \"observation_times for observatory {}\".format(observatory_code)\n            )\n\n            # Get the observer state for observation times and append to list \n            observer_states = getObserverState(\n                [observatory_code], \n                observation_times\n            )\n            observer_states_list.append(observer_states)\n\n        # Concatenate the dataframes\n        observer_states = pd.concat(observer_states_list)\n        observer_states.reset_index(\n            inplace=True, \n            drop=True\n        )\n\n        ephemeris_dfs = []\n        for observatory_code in observer_states[\"observatory_code\"].unique():\n            \n            observer_selected = observer_states[observer_states[\"observatory_code\"].isin([observatory_code])]\n            observation_times = observers[observatory_code]\n            \n            # Grab observer state vectors\n            cols = [\"obs_x\", \"obs_y\", \"obs_z\"]\n            velocity_cols =  [\"obs_vx\", \"obs_vy\", \"obs_vz\"]\n            if set(velocity_cols).intersection(set(observer_selected.columns)) == set(velocity_cols):\n                observer_selected = observer_selected[cols + velocity_cols].values\n            else:\n                observer_selected = observer_selected[cols].values\n            \n            # Generate ephemeris for each orbit \n            ephemeris = generateEphemerisUniversal(\n                orbits.cartesian, \n                orbits.epochs,\n                observer_selected, \n                observation_times, \n                light_time=self.light_time, \n                lt_tol=self.lt_tol, \n                stellar_aberration=self.stellar_aberration, \n                mu=self.mu, \n                max_iter=self.max_iter, \n                tol=self.tol\n            )\n            \n            ephemeris[\"observatory_code\"] = [observatory_code for i in range(len(ephemeris))]\n            ephemeris_dfs.append(ephemeris)\n\n        # Concatenate data frames, reset index and then keep only the columns\n        # we care about \n        ephemeris = pd.concat(ephemeris_dfs)\n        ephemeris.reset_index(\n            inplace=True, \n            drop=True\n        )\n        ephemeris = ephemeris[[\n            \"orbit_id\",\n            \"observatory_code\",\n            \"mjd_utc\",\n            \"RA_deg\",\n            \"Dec_deg\",\n            \"vRAcosDec\",\n            \"vDec\",\n            \"r_au\",\n            \"delta_au\",\n            \"light_time\",\n            \"obj_x\",\n            \"obj_y\",\n            \"obj_z\",\n            \"obj_vx\",\n            \"obj_vy\",\n            \"obj_vz\",\n            \"obs_x\",\n            \"obs_y\",\n            \"obs_z\",\n            \"obs_vx\",\n            \"obs_vy\",\n            \"obs_vz\",\n        ]]\n\n        if orbits.ids is not None:\n            ephemeris[\"orbit_id\"] = orbits.ids[ephemeris[\"orbit_id\"].values]\n        return ephemeris\n", "meta": {"hexsha": "0f696c1dd2c37072bb8ab3cda73a13bd8ca7cfdc", "size": 6179, "ext": "py", "lang": "Python", "max_stars_repo_path": "thor/backend/mjolnir.py", "max_stars_repo_name": "B612-Asteroid-Institute/thor", "max_stars_repo_head_hexsha": "d3d1dcbe86f67a62c90b4cde3fc577e414825cf2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thor/backend/mjolnir.py", "max_issues_repo_name": "B612-Asteroid-Institute/thor", "max_issues_repo_head_hexsha": "d3d1dcbe86f67a62c90b4cde3fc577e414825cf2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thor/backend/mjolnir.py", "max_forks_repo_name": "B612-Asteroid-Institute/thor", "max_forks_repo_head_hexsha": "d3d1dcbe86f67a62c90b4cde3fc577e414825cf2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8502415459, "max_line_length": 109, "alphanum_fraction": 0.5237093381, "include": true, "reason": "import numpy,from astropy", "num_tokens": 1373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3073580168652638, "lm_q1q2_score": 0.1844727038478331}}
{"text": "from __future__ import division\nfrom misc import fs_to_au, au_to_A, call_name, typewriter\nimport textwrap, datetime\nimport numpy as np\nimport os, shutil\n\n\nclass MQC(object):\n    \"\"\" Class for nuclear/electronic propagator used in MQC dynamics\n\n        :param object molecule: Molecule object\n        :param object thermostat: Thermostat type\n        :param integer istate: Initial adiabatic state\n        :param double dt: Time interval\n        :param integer nsteps: Nuclear step\n        :param integer nesteps: Electronic step\n        :param string elec_object: Electronic equation of motions\n        :param string propagator: Electronic propagator\n        :param boolean l_print_dm: Logical to print BO population and coherence\n        :param boolean l_adj_nac: Logical to adjust nonadiabatic coupling\n        :param init_coef: Initial BO coefficient\n        :type init_coef: Double, list or complex, list\n        :param string unit_dt: Unit of time step (fs = femtosecond, au = atomic unit)\n        :param integer out_freq: Frequency of printing output\n        :param integer verbosity: Verbosity of output\n    \"\"\"\n    def __init__(self, molecule, thermostat, istate, dt, nsteps, nesteps, \\\n        elec_object, propagator, l_print_dm, l_adj_nac, init_coef, unit_dt, out_freq, verbosity):\n        # Save name of MQC dynamics\n        self.md_type = self.__class__.__name__\n\n        # Initialize Molecule object\n        self.mol = molecule\n\n        # Initialize Thermostat object\n        self.thermo = thermostat\n\n        # Initialize input values\n        self.istate = istate\n        self.nsteps = nsteps\n        self.nesteps = nesteps\n\n        # Initialize time step\n        self.istep = -1\n        self.fstep = -1\n\n        # Decide unit of time step\n        self.unit_dt = unit_dt.lower()\n        if (self.unit_dt == 'au'):\n            self.dt = dt\n        elif (self.unit_dt == 'fs'):\n            self.dt = dt * fs_to_au\n        else:\n            error_message = \"Invalid unit for time step!\"\n            error_vars = f\"unit_dt = {unit_dt}\"\n            raise ValueError (f\"( {self.md_type}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n        # Check number of state and initial state\n        if (self.istate >= self.mol.nst):\n            error_message = \"Index for initial state must be smaller than number of states! The index for ground state is zero\"\n            error_vars = f\"istate = {self.istate}, Molecule.nstates = {self.mol.nst}\"\n            raise ValueError (f\"( {self.md_type}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n        # None for BOMD case\n        self.elec_object = elec_object\n        if (self.elec_object != None):\n            self.elec_object = self.elec_object.lower()\n\n        if not (self.elec_object in [None, \"coefficient\", \"density\"]):\n            error_message = \"Invalid electronic object!\"\n            error_vars = f\"elec_object = {self.elec_object}\"\n            raise ValueError (f\"( {self.md_type}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n        self.propagator = propagator\n        if (self.propagator != None):\n            self.propagator = self.propagator.lower()\n\n        if not (self.propagator in [None, \"rk4\"]):\n            error_message = \"Invalid electronic propagator!\"\n            error_vars = f\"propagator = {self.propagator}\"\n            raise ValueError (f\"( {self.md_type}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n        self.l_print_dm = l_print_dm\n\n        self.l_adj_nac = l_adj_nac\n\n        self.rforce = np.zeros((self.mol.nat, self.mol.ndim))\n\n        self.out_freq = out_freq\n        self.verbosity = verbosity\n\n        # Initialize coefficients and densities\n        self.mol.get_coefficient(init_coef, self.istate)\n\n    def run_init(self, qm, mm, output_dir, l_save_qm_log, l_save_mm_log, l_save_scr, restart):\n        \"\"\" Initialize MQC dynamics\n\n            :param object qm: QM object containing on-the-fly calculation infomation\n            :param object mm: MM object containing MM calculation infomation\n            :param string output_dir: Location of input directory\n            :param boolean l_save_qm_log: Logical for saving QM calculation log\n            :param boolean l_save_mm_log: Logical for saving MM calculation log\n            :param boolean l_save_scr: Logical for saving scratch directory\n            :param string restart: Option for controlling dynamics restarting\n        \"\"\"\n        # Check whether the restart option is right\n        if (restart != None):\n            restart = restart.lower()\n\n        if not (restart in [None, \"write\", \"append\"]):\n            error_message = \"Invalid restart option!\"\n            error_vars = f\"restart = {restart}\"\n            raise ValueError (f\"( {self.md_type}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n        # Check if NACVs are calculated for Ehrenfest dynamics\n        if (self.md_type == \"Eh\" and self.mol.l_nacme):\n            error_message = \"Ehrenfest dynamics needs evaluation of NACVs, check your QM object!\"\n            error_vars = f\"(QM) qm_prog.qm_method = {qm.qm_prog}.{qm.qm_method}\"\n            raise ValueError (f\"( {self.md_type}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n        # Check compatibility of variables for QM and MM calculation\n        if ((self.mol.l_qmmm and mm == None) or (not self.mol.l_qmmm and mm != None)):\n            error_message = \"Both logical for QM/MM and MM object is necessary!\"\n            error_vars = f\"Molecule.l_qmmm = {self.mol.l_qmmm}, mm = {mm}\"\n            raise ValueError (f\"( {self.md_type}.{call_name()} ) {error_message} ( {error_vars} )\")\n        if (self.mol.l_qmmm and mm != None):\n            self.check_qmmm(qm, mm)\n\n        # Set directory information\n        output_dir = os.path.expanduser(output_dir)\n        base_dir = []\n        unixmd_dir = []\n        qm_log_dir = []\n        mm_log_dir = [None]\n\n        if (self.mol.l_qmmm and mm != None):\n            mm_log_dir = []\n\n        dir_tmp = os.path.join(os.getcwd(), output_dir)\n        if (self.md_type != \"CT\"):\n            base_dir.append(dir_tmp)\n        else:\n            for itraj in range(self.ntrajs):\n                itraj_dir = os.path.join(dir_tmp, f\"traj{itraj + 1:0{self.digit}d}\")\n                base_dir.append(itraj_dir)\n\n        for idir in base_dir:\n            unixmd_dir.append(os.path.join(idir, \"md\"))\n            qm_log_dir.append(os.path.join(idir, \"qm_log\"))\n            if (self.mol.l_qmmm and mm != None):\n                mm_log_dir.append(os.path.join(idir, \"mm_log\"))\n\n        # Check and make directories\n        if (restart == \"append\"):\n            # For MD output directory\n            for md_idir in unixmd_dir:\n                if (not os.path.exists(md_idir)):\n                    error_message = f\"Directory {md_idir} to be appended for restart not found!\"\n                    error_vars = f\"restart = {restart}, output_dir = {output_dir}\"\n                    raise ValueError (f\"( {self.md_type}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n            # For QM output directory\n            if (l_save_qm_log):\n                for qm_idir in qm_log_dir:\n                    if (not os.path.exists(qm_idir)):\n                        os.makedirs(qm_idir)\n\n            # For MM output directory\n            if (self.mol.l_qmmm and mm != None):\n                if (l_save_mm_log):\n                    for mm_idir in mm_log_dir:\n                        if (not os.path.exists(mm_idir)):\n                            os.makedirs(mm_idir)\n        else:\n            # For MD output directory\n            for md_idir in unixmd_dir:\n                if (os.path.exists(md_idir)):\n                    shutil.move(md_idir, md_idir + \"_old_\" + str(os.getpid()))\n                os.makedirs(md_idir)\n\n                self.touch_file(md_idir)\n\n            # For QM output directory\n            for qm_idir in qm_log_dir:\n                if (os.path.exists(qm_idir)):\n                    shutil.move(qm_idir, qm_idir + \"_old_\" + str(os.getpid()))\n                if (l_save_qm_log):\n                    os.makedirs(qm_idir)\n\n            # For MM output directory\n            for mm_idir in mm_log_dir:\n                if (self.mol.l_qmmm and mm != None):\n                    if (os.path.exists(mm_idir)):\n                        shutil.move(mm_idir, mm_idir + \"_old_\" + str(os.getpid()))\n                    if (l_save_mm_log):\n                        os.makedirs(mm_idir)\n\n        os.chdir(base_dir[0])\n\n        if (self.md_type != \"CT\"):\n            return base_dir[0], unixmd_dir[0], qm_log_dir[0], mm_log_dir[0]\n        else:\n            return base_dir, unixmd_dir, qm_log_dir, mm_log_dir\n\n    def cl_update_position(self):\n        \"\"\" Routine to update nuclear positions\n        \"\"\"\n        self.mol.vel += 0.5 * self.dt * self.rforce / np.column_stack([self.mol.mass] * self.mol.ndim)\n        self.mol.pos += self.dt * self.mol.vel\n\n    def cl_update_velocity(self):\n        \"\"\" Routine to update nuclear velocities\n        \"\"\"\n        self.mol.vel += 0.5 * self.dt * self.rforce / np.column_stack([self.mol.mass] * self.mol.ndim)\n        self.mol.update_kinetic()\n\n#    def calculate_temperature(self):\n#        \"\"\" Routine to calculate current temperature\n#        \"\"\"\n#        pass\n#        #self.temperature = self.mol.ekin * 2 / float(self.mol.ndof) * au_to_K\n\n    def calculate_force(self):\n        \"\"\" Routine to calculate the forces\n        \"\"\"\n        pass\n\n    def update_potential(self):\n        \"\"\" Routine to update the potential of molecules\n        \"\"\"\n        pass\n\n    def print_init(self, qm, mm, restart):\n        \"\"\" Routine to print the initial information of dynamics\n\n            :param object qm: QM object containing on-the-fly calculation infomation\n            :param object mm: MM object containing MM calculation infomation\n            :param string restart: Option for controlling dynamics restarting\n        \"\"\"\n        # Print PyUNIxMD version\n        cur_time = datetime.datetime.now()\n        cur_time = cur_time.strftime(\"%Y-%m-%d %H:%M:%S\")\n        prog_info = textwrap.dedent(f\"\"\"\\\n        {\"-\" * 68}\n\n        {\"PyUNIxMD version 20.1\":>43s}\n\n        {\"< Developers >\":>40s}\n        {\" \" * 4}Seung Kyu Min,  In Seong Lee,  Jong-Kwon Ha,  Daeho Han,\n        {\" \" * 4}Kicheol Kim,  Tae In Kim,  Sung Wook Moon\n\n        {\"-\" * 68}\n\n        {\" \" * 4}Please cite PyUNIxMD as follows:\n        {\" \" * 4}This is article\n\n        {\" \" * 4}PyUNIxMD begins on {cur_time}\n        \"\"\")\n        print (prog_info, flush=True)\n\n        # Print restart info\n        if (restart != None):\n            restart_info = textwrap.indent(textwrap.dedent(f\"\"\"\\\n            Dynamics is restarted from the last step of a previous dynamics.\n            Restart Mode: {restart}\n            \"\"\"), \"    \")\n            print (restart_info, flush=True)\n\n        # Print self.mol information: coordinate, velocity\n        if (self.md_type != \"CT\"):\n            self.mol.print_init(mm)\n        else:\n            for itraj, mol in enumerate(self.mols):\n                mol.print_init(mm)\n\n        # Print dynamics information\n        dynamics_info = textwrap.dedent(f\"\"\"\\\n        {\"-\" * 68}\n        {\"Dynamics Information\":>43s}\n        {\"-\" * 68}\n          QM Program               = {qm.qm_prog:>16s}\n          QM Method                = {qm.qm_method:>16s}\n        \"\"\")\n        if (self.mol.l_qmmm and mm != None):\n            dynamics_info += textwrap.indent(textwrap.dedent(f\"\"\"\\\n              MM Program               = {mm.mm_prog:>16s}\n              QMMM Scheme              = {mm.scheme:>16s}\n            \"\"\"), \"  \")\n            # Print charge embedding in MM program\n            if (mm.embedding != None):\n                dynamics_info += f\"  Charge Embedding         = {mm.embedding:>16s}\\n\"\n            else:\n                dynamics_info += f\"  Charge Embedding         = {'No':>16s}\\n\"\n            # Print vdw interaction in MM program\n            if (mm.vdw != None):\n                dynamics_info += f\"  VDW Interaction          = {mm.vdw:>16s}\\n\"\n            else:\n                dynamics_info += f\"  VDW Interaction          = {'No':>16s}\\n\"\n\n        dynamics_info += textwrap.indent(textwrap.dedent(f\"\"\"\\\n\n          MQC Method               = {self.md_type:>16s}\n          Time Interval (fs)       = {self.dt / fs_to_au:16.6f}\n          Initial State (0:GS)     = {self.istate:>16d}\n          Nuclear Step             = {self.nsteps:>16d}\n        \"\"\"), \"  \")\n        if (self.md_type != \"BOMD\"):\n            dynamics_info += f\"  Electronic Step          = {self.nesteps:>16d}\\n\"\n            dynamics_info += f\"  Propagation Scheme       = {self.elec_object:>16s}\\n\"\n\n        # Print surface hopping variables\n        if (self.md_type == \"SH\" or self.md_type == \"SHXF\"):\n            dynamics_info += f\"\\n  Rescaling after Hop      = {self.hop_rescale:>16s}\\n\"\n            dynamics_info += f\"  Rescaling after Reject   = {self.hop_reject:>16s}\\n\"\n\n        # Print XF variables\n        if (self.md_type == \"SHXF\"):\n            # Print density threshold used in decoherence term\n            dynamics_info += f\"\\n  Density Threshold        = {self.rho_threshold:>16.6f}\"\n            if (self.md_type == \"SHXF\" and self.l_xf1d):\n                # Print reduced mass\n                dynamics_info += f\"\\n  Reduced Mass             = {self.aux.mass[0]:16.6f}\"\n            # Print sigma values\n            if (isinstance(self.sigma, float)):\n                dynamics_info += f\"\\n  Sigma                    = {self.sigma:16.3f}\\n\"\n            elif (isinstance(self.sigma, list)):\n                dynamics_info += f\"\\n  Sigma (1:N)              =\\n\"\n                nlines = int(self.aux.nat / 6)\n                if (self.aux.nat % 6 != 0):\n                    nlines += 1\n                sigma_info = \"\"\n                for iline in range(nlines):\n                    iline1 = iline * 6\n                    iline2 = (iline + 1) * 6\n                    if (iline2 > self.aux.nat):\n                        iline2 = self.aux.nat\n                    sigma_info += f\"  {iline1 + 1:>3d}:{iline2:<3d};\"\n                    sigma_info += \"\".join([f'{sigma:7.3f}' for sigma in self.sigma[iline1:iline2]])\n                    sigma_info += \"\\n\"\n                dynamics_info += sigma_info\n\n        print (dynamics_info, flush=True)\n\n        # Print thermostat information\n        if (self.thermo != None):\n            self.thermo.print_init()\n        else:\n            thermostat_info = \"  No Thermostat: Total energy is conserved!\\n\"\n            print (thermostat_info, flush=True)\n\n    def touch_file(self, unixmd_dir):\n        \"\"\" Routine to write PyUNIxMD output files\n\n            :param string unixmd_dir: Directory where MD output files are written\n        \"\"\"\n        # Energy information file header\n        tmp = f'{\"#\":5s}{\"Step\":9s}{\"Kinetic(H)\":15s}{\"Potential(H)\":15s}{\"Total(H)\":15s}' + \\\n            \"\".join([f'E({ist})(H){\"\":8s}' for ist in range(self.mol.nst)])\n        typewriter(tmp, unixmd_dir, \"MDENERGY\", \"w\")\n\n        if (self.md_type != \"BOMD\"):\n            # BO coefficents, densities file header\n            if (self.elec_object == \"density\"):\n                tmp = f'{\"#\":5s} Density Matrix: population Re; see the manual for detail orders'\n                typewriter(tmp, unixmd_dir, \"BOPOP\", \"w\")\n                tmp = f'{\"#\":5s} Density Matrix: coherence Re-Im; see the manual for detail orders'\n                typewriter(tmp, unixmd_dir, \"BOCOH\", \"w\")\n            elif (self.elec_object == \"coefficient\"):\n                tmp = f'{\"#\":5s} BO State Coefficients: state Re-Im; see the manual for detail orders'\n                typewriter(tmp, unixmd_dir, \"BOCOEF\", \"w\")\n                if (self.l_print_dm):\n                    tmp = f'{\"#\":5s} Density Matrix: population Re; see the manual for detail orders'\n                    typewriter(tmp, unixmd_dir, \"BOPOP\", \"w\")\n                    tmp = f'{\"#\":5s} Density Matrix: coherence Re-Im; see the manual for detail orders'\n                    typewriter(tmp, unixmd_dir, \"BOCOH\", \"w\")\n\n            # NACME file header\n            tmp = f'{\"#\":5s}Non-Adiabatic Coupling Matrix Elements: off-diagonal'\n            typewriter(tmp, unixmd_dir, \"NACME\", \"w\")\n\n            # DOTPOPNAC file header\n            if (self.verbosity >= 1):\n                tmp = f'{\"#\":5s} Time-derivative Density Matrix by NAC: population; see the manual for detail orders'\n                typewriter(tmp, unixmd_dir, \"DOTPOPNAC\", \"w\")\n\n        # file header for SH-based methods\n        if (self.md_type == \"SH\" or self.md_type == \"SHXF\"):\n            tmp = f'{\"#\":5s}{\"Step\":8s}{\"Running State\":10s}'\n            typewriter(tmp, unixmd_dir, \"SHSTATE\", \"w\")\n\n            tmp = f'{\"#\":5s}{\"Step\":12s}' + \"\".join([f'Prob({ist}){\"\":8s}' for ist in range(self.mol.nst)])\n            typewriter(tmp, unixmd_dir, \"SHPROB\", \"w\")\n\n        # file header for XF-based methods\n        if (self.md_type == \"SHXF\"):\n            if (self.verbosity >= 1):\n                tmp = f'{\"#\":5s} Time-derivative Density Matrix by decoherence: population; see the manual for detail orders'\n                typewriter(tmp, unixmd_dir, \"DOTPOPDEC\", \"w\")\n\n    def write_md_output(self, unixmd_dir, istep):\n        \"\"\" Write output files\n\n            :param string unixmd_dir: Directory where MD output files are written\n            :param integer istep: Current MD step\n        \"\"\"\n        # Write MOVIE.xyz file including positions and velocities\n        tmp = f'{self.mol.nat:6d}\\n{\"\":2s}Step:{istep + 1:6d}{\"\":12s}Position(A){\"\":34s}Velocity(au)' + \\\n            \"\".join([\"\\n\" + f'{self.mol.symbols[iat]:5s}' + \\\n            \"\".join([f'{self.mol.pos[iat, isp] * au_to_A:15.8f}' for isp in range(self.mol.ndim)]) + \\\n            \"\".join([f\"{self.mol.vel[iat, isp]:15.8f}\" for isp in range(self.mol.ndim)]) for iat in range(self.mol.nat)])\n        typewriter(tmp, unixmd_dir, \"MOVIE.xyz\", \"a\")\n\n        # Write MDENERGY file including several energy information\n        tmp = f'{istep + 1:9d}{self.mol.ekin:15.8f}{self.mol.epot:15.8f}{self.mol.etot:15.8f}' \\\n            + \"\".join([f'{states.energy:15.8f}' for states in self.mol.states])\n        typewriter(tmp, unixmd_dir, \"MDENERGY\", \"a\")\n\n        if (self.md_type != \"BOMD\"):\n            # Write BOCOEF, BOPOP, BOCOH files\n            if (self.elec_object == \"density\"):\n                tmp = f'{istep + 1:9d}' + \"\".join([f'{self.mol.rho.real[ist, ist]:15.8f}' for ist in range(self.mol.nst)])\n                typewriter(tmp, unixmd_dir, \"BOPOP\", \"a\")\n                tmp = f'{istep + 1:9d}' + \"\".join([f\"{self.mol.rho.real[ist, jst]:15.8f}{self.mol.rho.imag[ist, jst]:15.8f}\" \\\n                    for ist in range(self.mol.nst) for jst in range(ist + 1, self.mol.nst)])\n                typewriter(tmp, unixmd_dir, \"BOCOH\", \"a\")\n            elif (self.elec_object == \"coefficient\"):\n                tmp = f'{istep + 1:9d}' + \"\".join([f'{states.coef.real:15.8f}{states.coef.imag:15.8f}' \\\n                    for states in self.mol.states])\n                typewriter(tmp, unixmd_dir, \"BOCOEF\", \"a\")\n                if (self.l_print_dm):\n                    tmp = f'{istep + 1:9d}' + \"\".join([f'{self.mol.rho.real[ist, ist]:15.8f}' for ist in range(self.mol.nst)])\n                    typewriter(tmp, unixmd_dir, \"BOPOP\", \"a\")\n                    tmp = f'{istep + 1:9d}' + \"\".join([f\"{self.mol.rho.real[ist, jst]:15.8f}{self.mol.rho.imag[ist, jst]:15.8f}\" \\\n                        for ist in range(self.mol.nst) for jst in range(ist + 1, self.mol.nst)])\n                    typewriter(tmp, unixmd_dir, \"BOCOH\", \"a\")\n\n            # Write NACME file\n            tmp = f'{istep + 1:10d}' + \"\".join([f'{self.mol.nacme[ist, jst]:15.8f}' \\\n                for ist in range(self.mol.nst) for jst in range(ist + 1, self.mol.nst)])\n            typewriter(tmp, unixmd_dir, \"NACME\", \"a\")\n\n            # Write NACV file\n            if (not self.mol.l_nacme and self.verbosity >= 2):\n                for ist in range(self.mol.nst):\n                    for jst in range(ist + 1, self.mol.nst):\n                        tmp = f'{self.mol.nat_qm:6d}\\n{\"\":2s}Step:{istep + 1:6d}{\"\":12s}NACV' + \\\n                            \"\".join([\"\\n\" + f'{self.mol.symbols[iat]:5s}' + \\\n                            \"\".join([f'{self.mol.nac[ist, jst, iat, isp]:15.8f}' for isp in range(self.mol.ndim)]) for iat in range(self.mol.nat_qm)])\n                        typewriter(tmp, unixmd_dir, f\"NACV_{ist}_{jst}\", \"a\")\n\n    def write_final_xyz(self, unixmd_dir, istep):\n        \"\"\" Write final positions and velocities\n\n            :param string unixmd_dir: Directory where MD output files are written\n            :param integer istep: Current MD step\n        \"\"\"\n        # Write FINAL.xyz file including positions and velocities\n        tmp = f'{self.mol.nat:6d}\\n{\"\":2s}Step:{istep + 1:6d}{\"\":12s}Position(A){\"\":34s}Velocity(au)'\n        for iat in range(self.mol.nat):\n            tmp += \"\\n\" + f'{self.mol.symbols[iat]:5s}' + \\\n                \"\".join([f'{self.mol.pos[iat, isp] * au_to_A:15.8f}' for isp in range(self.mol.ndim)]) \\\n                + \"\".join([f\"{self.mol.vel[iat, isp]:15.8f}\" for isp in range(self.mol.ndim)])\n\n        typewriter(tmp, unixmd_dir, \"FINAL.xyz\", \"w\")\n\n    def check_qmmm(self, qm, mm):\n        \"\"\" Routine to check compatibility between QM and MM objects\n\n            :param object qm: QM object containing on-the-fly calculation infomation\n            :param object mm: MM object containing MM calculation infomation\n        \"\"\"\n        # Now check MM object\n        if (mm.mm_prog == \"Tinker\"):\n            # Now check QM object\n            if (qm.qm_prog == \"dftbplus\"):\n                if (qm.qm_method == \"SSR\"):\n                    do_qmmm = True\n                else:\n                    do_qmmm = False\n            else:\n                do_qmmm = False\n        else:\n            do_qmmm = False\n\n        if (do_qmmm):\n            if (qm.embedding != mm.embedding):\n                error_message = \"Inconsistent charge embedding between QM and MM objects!\"\n                error_vars = f\"(QM) embedding = {qm.embedding}, (MM) embedding = {mm.embedding}\"\n                raise ValueError (f\"( {self.md_type}.{call_name()} ) {error_message} ( {error_vars} )\")\n        else:\n            error_message = \"Incompatible QM and MM objects for QM/MM calculation!\"\n            error_vars = f\"(QM) qm_prog.qm_method = {qm.qm_prog}.{qm.qm_method}, (MM) mm_prog = {mm.mm_prog}\"\n            raise ValueError (f\"( {self.md_type}.{call_name()} ) {error_message} ( {error_vars} )\")\n\n\n", "meta": {"hexsha": "90894a006a33ca564e45b74568968e128c3340cc", "size": 22518, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/mqc/mqc.py", "max_stars_repo_name": "jkha-unist/for_test", "max_stars_repo_head_hexsha": "56fe5aa3aa400914a38d88fb136bc486fe3d7678", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mqc/mqc.py", "max_issues_repo_name": "jkha-unist/for_test", "max_issues_repo_head_hexsha": "56fe5aa3aa400914a38d88fb136bc486fe3d7678", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mqc/mqc.py", "max_forks_repo_name": "jkha-unist/for_test", "max_forks_repo_head_hexsha": "56fe5aa3aa400914a38d88fb136bc486fe3d7678", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.3991935484, "max_line_length": 150, "alphanum_fraction": 0.5528466116, "include": true, "reason": "import numpy", "num_tokens": 5892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.1843495867735675}}
{"text": "import copy\nfrom typing import Any, Dict, Sequence\n\nimport numpy\nimport torch\nimport torch.nn.functional as F\nfrom torch.optim import Optimizer\n\nfrom draugr.torch_utilities import freeze_model, frozen_model, to_tensor\nfrom draugr.writers import MockWriter, Writer\nfrom neodroid.utilities import ActionSpace, ObservationSpace, SignalSpace\nfrom neodroidagent.agents.torch_agents.torch_agent import TorchAgent\nfrom neodroidagent.common import (\n    Architecture,\n    LateConcatInputMLP,\n    MLP,\n    Memory,\n    TransitionPoint,\n    TransitionPointBuffer,\n)\nfrom neodroidagent.utilities import (\n    ActionSpaceNotSupported,\n    OrnsteinUhlenbeckProcess,\n    update_target,\n)\nfrom numpy import mean\nfrom tqdm import tqdm\nfrom warg import GDKC, drop_unused_kws, is_zero_or_mod_zero, super_init_pass_on_kws\n\n__author__ = \"Christian Heider Nielsen\"\n__doc__ = r\"\"\"\n\"\"\"\n__all__ = [\"DeepDeterministicPolicyGradientAgent\"]\n\ntqdm.monitor_interval = 0\n\n\n@super_init_pass_on_kws\nclass DeepDeterministicPolicyGradientAgent(TorchAgent):\n    \"\"\"\nThe Deep Deterministic Policy Gradient (DDPG) Agent\n\nParameters\n----------\nactor_optimizer_spec: OptimiserSpec\nSpecifying the constructor and kwargs, as well as learning rate and other\nparameters for the optimiser\ncritic_optimizer_spec: OptimiserSpec\nnum_feature: int\nThe number of features of the environmental state\nnum_action: int\nThe number of available actions that agent can choose from\nreplay_memory_size: int\nHow many memories to store in the replay memory.\nbatch_size: int\nHow many transitions to sample each time experience is replayed.\ntau: float\nThe update rate that target networks slowly track the learned networks.\n\"\"\"\n\n    def __init__(\n        self,\n        random_process_spec: GDKC = GDKC(constructor=OrnsteinUhlenbeckProcess),\n        memory_buffer: Memory = TransitionPointBuffer(),\n        evaluation_function: callable = F.mse_loss,\n        actor_arch_spec: GDKC = GDKC(MLP, output_activation=torch.nn.Tanh()),\n        critic_arch_spec: GDKC = GDKC(LateConcatInputMLP),\n        discount_factor: float = 0.95,\n        update_target_interval: int = 1,\n        batch_size: int = 128,\n        noise_factor: float = 1e-1,\n        copy_percentage: float = 0.005,\n        actor_optimiser_spec: GDKC = GDKC(constructor=torch.optim.Adam, lr=3e-4),\n        critic_optimiser_spec: GDKC = GDKC(constructor=torch.optim.Adam, lr=3e-4),\n        **kwargs\n    ):\n        \"\"\"\n\n@param random_process_spec:\n@param memory_buffer:\n@param evaluation_function:\n@param actor_arch_spec:\n@param critic_arch_spec:\n@param discount_factor:\n@param update_target_interval:\n@param batch_size:\n@param noise_factor:\n@param copy_percentage:\n@param actor_optimiser_spec:\n@param critic_optimiser_spec:\n@param kwargs:\n\"\"\"\n        super().__init__(**kwargs)\n\n        assert 0 <= discount_factor <= 1.0\n        assert 0 <= copy_percentage <= 1.0\n\n        self._copy_percentage = copy_percentage\n        self._actor_optimiser_spec = actor_optimiser_spec\n        self._critic_optimiser_spec = critic_optimiser_spec\n        self._actor_arch_spec = actor_arch_spec\n        self._critic_arch_spec = critic_arch_spec\n        self._random_process_spec = random_process_spec\n\n        self._memory_buffer = memory_buffer\n        self._critic_criteria = evaluation_function\n        self._discount_factor = discount_factor\n        self._update_target_interval = update_target_interval\n\n        self._batch_size = batch_size\n        self._noise_factor = noise_factor\n\n    @drop_unused_kws\n    def __build__(\n        self,\n        observation_space: ObservationSpace,\n        action_space: ActionSpace,\n        signal_space: SignalSpace,\n        metric_writer: Writer = MockWriter(),\n        print_model_repr: bool = True,\n    ) -> None:\n        \"\"\"\n\n@param observation_space:\n@param action_space:\n@param signal_space:\n@param metric_writer:\n@param print_model_repr:\n@param critic:\n@param critic_optimiser:\n@param actor:\n@param actor_optimiser:\n@return:\n\"\"\"\n\n        if action_space.is_discrete:\n            raise ActionSpaceNotSupported()\n\n        self._actor_arch_spec.kwargs[\"input_shape\"] = self._input_shape\n        self._actor_arch_spec.kwargs[\"output_shape\"] = self._output_shape\n        self._actor = self._actor_arch_spec().to(self._device)\n        self._target_actor = copy.deepcopy(self._actor).to(self._device)\n        freeze_model(self._target_actor, True, True)\n        self._actor_optimiser = self._actor_optimiser_spec(self._actor.parameters())\n\n        self._critic_arch_spec.kwargs[\"input_shape\"] = (\n            *self._input_shape,\n            *self._output_shape,\n        )\n        self._critic_arch_spec.kwargs[\"output_shape\"] = 1\n        self._critic = self._critic_arch_spec().to(self._device)\n        self._target_critic = copy.deepcopy(self._critic).to(self._device)\n        freeze_model(self._target_critic, True, True)\n        self._critic_optimiser = self._critic_optimiser_spec(self._critic.parameters())\n\n        self._random_process = self._random_process_spec(\n            sigma=mean([r.span for r in action_space.ranges])\n        )\n\n    @property\n    def models(self) -> Dict[str, Architecture]:\n        \"\"\"\n\n@return:\n\"\"\"\n        return {\"_actor\": self._actor, \"_critic\": self._critic}\n\n    @property\n    def optimisers(self) -> Dict[str, Optimizer]:\n        return {\n            \"_actor_optimiser\": self._actor_optimiser,\n            \"_critic_optimiser\": self._critic_optimiser,\n        }\n\n    def update_targets(\n        self, update_percentage: float, *, metric_writer: Writer = None\n    ) -> None:\n        \"\"\"\n\n@param update_percentage:\n@return:\n\"\"\"\n        with torch.no_grad():\n            if metric_writer:\n                metric_writer.blip(\"Target Model Synced\", self.update_i)\n\n            update_target(\n                target_model=self._target_critic,\n                source_model=self._critic,\n                copy_percentage=update_percentage,\n            )\n            update_target(\n                target_model=self._target_actor,\n                source_model=self._actor,\n                copy_percentage=update_percentage,\n            )\n\n    @drop_unused_kws\n    def _remember(self, *, signal, terminated, state, successor_state, sample) -> None:\n        self._memory_buffer.add_transition_point(\n            TransitionPoint(state, sample, successor_state, signal, terminated)\n        )\n\n    @drop_unused_kws\n    def _update(self, *, metric_writer: Writer = MockWriter()) -> None:\n        \"\"\"\nUpdate\n\n:return:\n:rtype:\n\"\"\"\n        tensorised = TransitionPoint(\n            *[to_tensor(a, device=self._device) for a in self._memory_buffer.sample()]\n        )\n\n        self._memory_buffer.clear()\n\n        # Compute next Q value based on which action target actor would choose\n        # Detach variable from the current graph since we don't want gradients for next Q to propagated\n        with torch.no_grad():\n            next_max_q = self._target_critic(\n                tensorised.successor_state, self._target_actor(tensorised.state)\n            )\n            Q_target = tensorised.signal + (\n                self._discount_factor * next_max_q * tensorised.non_terminal_numerical\n            )\n            # Compute the target of the current Q values\n\n        # Compute current Q value, critic takes state and action chosen\n        td_error = self._critic_criteria(\n            self._critic(tensorised.state, tensorised.action), Q_target.detach()\n        )\n        self._critic_optimiser.zero_grad()\n        td_error.backward()\n        self.post_process_gradients(self._critic.parameters())\n        self._critic_optimiser.step()\n\n        with frozen_model(self._critic):\n            policy_loss = -torch.mean(\n                self._critic(tensorised.state, self._actor(tensorised.state))\n            )\n            self._actor_optimiser.zero_grad()\n            policy_loss.backward()\n            self.post_process_gradients(self._actor.parameters())\n            self._actor_optimiser.step()\n\n        if is_zero_or_mod_zero(self._update_target_interval, self.update_i):\n            self.update_targets(self._copy_percentage, metric_writer=metric_writer)\n\n        if metric_writer:\n            metric_writer.scalar(\"td_error\", td_error.cpu().item())\n            metric_writer.scalar(\"critic_loss\", policy_loss.cpu().item())\n\n        with torch.no_grad():\n            return (td_error + policy_loss).cpu().item()\n\n    def extract_action(self, sample: Any) -> numpy.ndarray:\n        \"\"\"\n\n@param sample:\n@return:\n\"\"\"\n        return sample.to(\"cpu\").numpy()\n\n    @drop_unused_kws\n    def _sample(self, state: Sequence) -> Any:\n        \"\"\"\n\n@param state:\n@param deterministic:\n@return:\n\"\"\"\n\n        with torch.no_grad():\n            action_out = self._actor(to_tensor(state, device=self._device)).detach()\n\n        deterministic = False\n        if not deterministic:\n            # Add action space noise for exploration, alternative is parameter space noise\n            noise = self._random_process.sample(action_out.shape)\n            action_out += to_tensor(noise * self._noise_factor, device=self.device)\n\n        return action_out\n", "meta": {"hexsha": "1e54f32db4752e2a6d715b039e1825c71a8a93a8", "size": 9078, "ext": "py", "lang": "Python", "max_stars_repo_path": "neodroidagent/agents/torch_agents/model_free/on_policy/ddpg_agent.py", "max_stars_repo_name": "gitter-badger/agent", "max_stars_repo_head_hexsha": "3f53eaa7ebdee3ab423c7b58785d584fe1a6ae11", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-09-13T08:28:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T15:59:19.000Z", "max_issues_repo_path": "neodroidagent/agents/torch_agents/model_free/on_policy/ddpg_agent.py", "max_issues_repo_name": "gitter-badger/agent", "max_issues_repo_head_hexsha": "3f53eaa7ebdee3ab423c7b58785d584fe1a6ae11", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:49:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-25T13:49:39.000Z", "max_forks_repo_path": "neodroidagent/agents/torch_agents/model_free/on_policy/ddpg_agent.py", "max_forks_repo_name": "gitter-badger/agent", "max_forks_repo_head_hexsha": "3f53eaa7ebdee3ab423c7b58785d584fe1a6ae11", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-09-13T08:31:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-09T11:22:27.000Z", "avg_line_length": 31.9647887324, "max_line_length": 103, "alphanum_fraction": 0.6816479401, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.1843495848922022}}
{"text": "#!/usr/bin/env python3\n\n\"\"\"Module dedicated to the time simulation of reaction models.\n\nHere are functions that calculate reaction rates as well, which is needed for\nthe time simulations.\n\"\"\"\n\n\nfrom __future__ import annotations\n\n__all__ = [\"get_y\", \"get_dydt\", \"get_fixed_scheme\"]\n\n\nimport logging\n\nimport numpy as np\nfrom scipy.integrate import solve_ivp\nfrom scipy.optimize import minimize_scalar\n\nimport overreact as rx\nfrom overreact import _constants as constants\nfrom overreact._misc import _found_jax\n\nEF = 5\n\n\nlogger = logging.getLogger(__name__)\n\n\nif _found_jax:\n    import jax.numpy as jnp\n    from jax import jacfwd, jit\n    from jax.config import config\n\n    config.update(\"jax_enable_x64\", True)\nelse:\n    logger.warning(\n        \"Install JAX to have just-in-time compilation: \"\n        'pip install jax (or pip install \"overreact[fast]\")'\n    )\n    jnp = np\n\n\n# TODO(schneiderfelipe): allow y0 to be a dict-like object.\ndef get_y(\n    dydt, y0, t_span=None, method=\"Radau\", rtol=1e-5, atol=1e-11, max_time=24 * 60 * 60\n):\n    \"\"\"Simulate a reaction scheme from its rate function.\n\n    This function provides two functions that calculate the concentrations and\n    the rates of formation at any point in time for any compound. It does that\n    by solving an initial value problem (IVP) through scipy's ``solve_ivp``\n    under the hood.\n\n    Parameters\n    ----------\n    dydt : callable\n        Right-hand side of the system.\n    y0 : array-like\n        Initial state.\n    t_span : array-like, optional\n        Interval of integration (t0, tf). The solver starts with t=t0 and\n        integrates until it reaches t=tf. If not given, a conservative value\n        is chosen based on the system at hand (the method of choice works for\n        any zeroth-, first- or second-order reactions).\n    method : str, optional\n        Integration method to use. See `scipy.integrate.solve_ivp` for details.\n        Kinetics problems are very often stiff and, as such, \"RK45\" is\n        normally unsuited. \"Radau\", \"BDF\" or \"LSODA\" are good choices.\n    rtol, atol : array-like\n        See `scipy.integrate.solve_ivp` for details.\n    max_time : float, optional\n        If `t_span` is not given, an interval will be estimated, but it can't\n        be larger than this parameter.\n\n    Returns\n    -------\n    y, r : callable\n        Concentrations and reaction rates as functions of time. The y object\n        is an OdeSolution and stores attributes t_min and t_max.\n\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> import overreact as rx\n\n    A toy simulation can be performed in just two lines:\n\n    >>> scheme = rx.parse_reactions(\"A <=> B\")\n    >>> y, r = get_y(get_dydt(scheme, np.array([1, 1])), y0=[1, 0])\n\n    The `y` object stores information about the simulation time, which can be\n    used to produce a suitable vector of timepoints for, e.g., plotting:\n\n    >>> y.t_min, y.t_max  # doctest: +SKIP\n    (0.0, 3.0)\n    >>> t = np.linspace(y.t_min, y.t_max)\n    >>> t  # doctest: +SKIP\n    array([0. , 0.06122449, ..., 2.93877551, 3. ])\n\n    Both `y` and `r` can be used to check concentrations and rates in any\n    point in time. In particular, both are vectorized:\n\n    >>> y(t)  # doctest: +SKIP\n    array([[1. , 0.94237559, ..., 0.5012394, 0.5 ],\n           [0. , 0.05762441, ..., 0.4987606, 0.5 ]])\n    >>> r(t)  # doctest: +SKIP\n    array([[-1.00000000e+00, ..., -1.39544265e-10],\n           [ 1.00000000e+00, ...,  1.39544265e-10]])\n    \"\"\"\n    # TODO(schneiderfelipe): raise a meaningful error when y0 has the wrong shape.\n    y0 = np.asarray(y0)\n\n    if t_span is None:\n        # We defined alpha such that 1.0 - alpha is an (under)estimate of the extend\n        # to which the reaction is simulated. And then we apply the Pareto principle.\n        alpha = 0.2\n        n_halflives = np.ceil(-np.log(alpha) / np.log(2))\n\n        halflife_estimate = 1.0\n        if hasattr(dydt, \"k\"):\n            halflife_estimate = np.max(\n                [\n                    np.max(y0) / 2.0,  # zeroth-order halflife\n                    np.log(2.0),  # first-order halflife\n                    1.0 / np.min(y0[np.nonzero(y0)]),  # second-order halflife\n                ]\n            ) / np.min(dydt.k)\n            logger.info(f\"largest halflife guess = {halflife_estimate} s\")\n\n        t_span = [0.0, min(n_halflives * halflife_estimate, max_time)]\n        logger.info(f\"simulation time span   = {t_span} s\")\n\n    jac = None\n    if hasattr(dydt, \"jac\"):\n        jac = dydt.jac\n\n    # TODO(schneiderfelipe): log solve_ivp stuff.\n    res = solve_ivp(\n        dydt,\n        t_span,\n        y0,\n        method=method,\n        dense_output=True,\n        rtol=rtol,\n        atol=atol,\n        jac=jac,\n    )\n    y = res.sol\n\n    def r(t):\n        # TODO(schneiderfelipe): this is probably not the best way to\n        # vectorize a function!\n        try:\n            return np.array([dydt(_t, _y) for _t, _y in zip(t, y(t).T)]).T\n        except TypeError:\n            return dydt(t, y(t))\n\n    return y, r\n\n\ndef get_dydt(scheme, k, ef=EF):\n    \"\"\"Generate a rate function that models a reaction scheme.\n\n    Parameters\n    ----------\n    scheme : Scheme\n        A descriptor of the reaction scheme.\n        Mostly likely, this comes from a parsed model input file.\n        See `overreact.io.parse_model`.\n    k : array-like\n        Reaction rate constant(s). Units match the concentration units given to\n        the returned function ``dydt``.\n    ef : float, optional\n        Equilibrium factor. This is a parameter that can be used to scale the\n        reaction rates associated to half-equilibrium reactions such that they\n        are faster than the other reactions.\n\n    Returns\n    -------\n    dydt : callable\n        Reaction rate function. The actual reaction rate constants employed\n        are stored in the attribute `k` of the returned function. If JAX is\n        available, the attribute `jac` will hold the Jacobian function of\n        `dydt`.\n\n    Notes\n    -----\n    The returned function is suited to be used by ODE solvers such as\n    `scipy.integrate.solve_ivp` or the older `scipy.integrate.ode` (see\n    examples below). This is actually what the function `get_y` from the\n    current module does.\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> import overreact as rx\n\n    >>> scheme = rx.parse_reactions(\"A <=> B\")\n    >>> dydt = get_dydt(scheme, np.array([1, 1]))\n    >>> dydt(0.0, np.array([1., 1.]))  # doctest: +SKIP\n    array([0., 0.])\n\n    If available, JAX is used for JIT compilation. This will make `dydt`\n    complain if given lists instead of numpy arrays. So stick to the safer,\n    faster side as above.\n\n    The actually used reaction rate constants can be inspected with the `k`\n    attribute of `dydt`:\n\n    >>> dydt.k  # doctest: +SKIP\n    array([1., 1.])\n\n    If JAX is available, the Jacobian function will be available as\n    `dydt.jac`:\n\n    >>> dydt.jac(0.0, np.array([1., 1.]))  # doctest: +SKIP\n    DeviceArray([[-1.,  1.],\n                 [ 1., -1.]], dtype=float64)\n\n    \"\"\"\n    scheme = rx.core._check_scheme(scheme)\n    A = jnp.asarray(scheme.A)\n    M = jnp.where(A > 0, 0, -A).T\n    k_adj = _adjust_k(scheme, k, ef=ef)\n\n    def _dydt(t, y):\n        r = k_adj * jnp.prod(jnp.power(y, M), axis=1)\n        return jnp.dot(A, r)\n\n    if _found_jax:\n        # Using JAX for JIT compilation is much faster.\n        _dydt = jit(_dydt)\n\n        def _jac(t, y):\n            # _jac(t, y)[i, j] == d f_i / d y_j\n            # shape is (n_compounds, n_compounds)\n            return jacfwd(lambda _y: _dydt(t, _y))(y)\n\n        _dydt.jac = _jac\n\n    _dydt.k = k_adj\n    return _dydt\n\n\ndef _adjust_k(scheme, k, ef=EF):\n    \"\"\"Adjust reaction rate constants so that equilibria are equilibria.\n\n    Parameters\n    ----------\n    scheme : Scheme\n        A descriptor of the reaction scheme.\n        Mostly likely, this comes from a parsed model input file.\n        See `overreact.io.parse_model`.\n    k : array-like\n        Reaction rate constant(s). Units match the concentration units given to\n        the returned function ``dydt``.\n    ef : float, optional\n\n    Returns\n    -------\n    k : array-like\n        Adjusted constants.\n\n    Examples\n    --------\n    >>> import overreact as rx\n\n    >>> scheme = rx.parse_reactions(\"A <=> B\")\n    >>> _adjust_k(scheme, [1, 1])  # doctest: +SKIP\n    array([1., 1.])\n\n    >>> model = rx.parse_model(\"data/ethane/B97-3c/model.k\")\n    >>> _adjust_k(model.scheme,\n    ...           rx.get_k(model.scheme, model.compounds))  # doctest: +SKIP\n    array([8.16880917e+10])\n\n    >>> model = rx.parse_model(\"data/acetate/Orca4/model.k\")\n    >>> _adjust_k(model.scheme,\n    ...           rx.get_k(model.scheme, model.compounds))  # doctest: +SKIP\n    array([1.00000000e+00, 5.74491548e+04, 1.61152010e+07,\n           1.00000000e+00, 1.55695112e+56, 1.00000000e+00])\n\n    >>> model = rx.parse_model(\n    ...     \"data/perez-soto2020/RI/BLYP-D4/def2-TZVP/model.k\"\n    ... )\n    >>> _adjust_k(model.scheme,\n    ...           rx.get_k(model.scheme, model.compounds))  # doctest: +SKIP\n    array([1.02320357e+12, ..., 1.02320357e+12])\n\n    \"\"\"\n    scheme = rx.core._check_scheme(scheme)\n    is_half_equilibrium = np.asarray(scheme.is_half_equilibrium)\n    k = np.asarray(k, dtype=float).copy()\n\n    if np.any(is_half_equilibrium):\n        # at least one equilibrium\n        if np.any(~is_half_equilibrium):\n            # at least one true reaction\n\n            k_slowest_equil = k[is_half_equilibrium].min()\n            k_fastest_react = k[~is_half_equilibrium].max()\n            adjustment = ef * (k_fastest_react / k_slowest_equil)\n\n            k[is_half_equilibrium] *= adjustment\n            logger.warning(f\"equilibria adjustment = {adjustment}\")\n        else:\n            # only equilibria\n\n            # set the smallest one to be equal to one\n            k = k / k.min()\n    # else:\n    #     # only zero or more true reactions (no equilibria)\n    #     pass\n\n    return jnp.asarray(k)\n\n\ndef get_fixed_scheme(scheme, k, fixed_y0):\n    \"\"\"Generate an alternative scheme with some concentrations fixed.\n\n    This function returns data that allow the microkinetic simulation of a\n    reaction network under constraints, namely when some compounds have fixed\n    concentrations. This works by 1. removing all references to the fixed\n    compounds and by 2. properly multiplying the reaction rate constants by\n    the respective concentrations.\n\n    Parameters\n    ----------\n    scheme : Scheme\n        A descriptor of the reaction scheme.\n        Mostly likely, this comes from a parsed model input file.\n        See `overreact.io.parse_model`.\n    k : array-like\n        Reaction rate constant(s). Units match the concentration units given to\n        the returned function ``dydt``.\n    fixed_y0 : dict-like\n        Fixed initial state. Units match the concentration units given to\n        the returned function ``dydt``.\n\n    Returns\n    -------\n    scheme : Scheme\n        Associated reaction scheme with all references to fixed compounds\n        removed.\n    k : array-like\n        Associated (effective) reaction rate constants that model the fixed\n        concentrations.\n\n    Notes\n    -----\n    Keep in mind that when a compound get its concentration fixed, the\n    reaction scheme no longer conserves matter. You can think of it as\n    reacting close to an infinite source of the compound, but it accumulates\n    in the milleu at the given concentration.\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> import overreact as rx\n\n    Equilibria under a specific pH can be easily modeled:\n\n    >>> pH = 7\n    >>> scheme = rx.parse_reactions(\"AH <=> A- + H+\")\n    >>> k = np.array([1, 1])\n    >>> scheme, k = rx.get_fixed_scheme(scheme, k, {\"H+\": 10**-pH})\n    >>> scheme\n    Scheme(compounds=('AH', 'A-'),\n           reactions=('AH -> A-',\n                      'A- -> AH'),\n           is_half_equilibrium=(True, True),\n           A=((-1.0, 1.0),\n              (1.0, -1.0)),\n           B=((-1.0, 0.0),\n              (1.0, 0.0)))\n    >>> k\n    array([1.e+00, 1.e-07])\n\n    It is also possible to model the fixed activity of a solvent, for\n    instance:\n\n    >>> scheme = rx.parse_reactions(\"A + 2H2O -> B\")\n    >>> k = np.array([1.0])\n    >>> scheme, k = rx.get_fixed_scheme(scheme, k, {\"H2O\": 55.6})\n    >>> scheme\n    Scheme(compounds=('A', 'B'),\n           reactions=('A -> B',),\n           is_half_equilibrium=(False,),\n           A=((-1.0,),\n              (1.0,)),\n           B=((-1.0,),\n              (1.0,)))\n    >>> k\n    array([3091.36])\n\n    Multiple reactions work fine, see both examples below:\n\n    >>> pH = 12\n    >>> scheme = rx.parse_reactions(\"B <- AH <=> A- + H+\")\n    >>> k = np.array([10.0, 1, 1])\n    >>> scheme, k = rx.get_fixed_scheme(scheme, k, {\"H+\": 10**-pH})\n    >>> scheme\n    Scheme(compounds=('AH', 'B', 'A-'),\n           reactions=('AH -> B',\n                      'AH -> A-',\n                      'A- -> AH'),\n           is_half_equilibrium=(False, True, True),\n           A=((-1.0, -1.0, 1.0),\n              (1.0, 0.0, 0.0),\n              (0.0, 1.0, -1.0)),\n           B=((-1.0, -1.0, 0.0),\n              (1.0, 0.0, 0.0),\n              (0.0, 1.0, 0.0)))\n    >>> k\n    array([1.e+01, 1.e+00, 1.e-12])\n\n    >>> pH = 2\n    >>> scheme = rx.parse_reactions([\"AH <=> A- + H+\", \"B- + H+ <=> BH\"])\n    >>> k = np.array([1, 1, 2, 2])\n    >>> scheme, k = rx.get_fixed_scheme(scheme, k, {\"H+\": 10**-pH})\n    >>> scheme\n    Scheme(compounds=('AH', 'A-', 'B-', 'BH'),\n           reactions=('AH -> A-',\n                      'A- -> AH',\n                      'B- -> BH',\n                      'BH -> B-'),\n           is_half_equilibrium=(True, True, True, True),\n           A=((-1.0, 1.0, 0.0, 0.0),\n              (1.0, -1.0, 0.0, 0.0),\n              (0.0, 0.0, -1.0, 1.0),\n              (0.0, 0.0, 1.0, -1.0)),\n           B=((-1.0, 0.0, 0.0, 0.0),\n              (1.0, 0.0, 0.0, 0.0),\n              (0.0, 0.0, -1.0, 0.0),\n              (0.0, 0.0, 1.0, 0.0)))\n    >>> k\n    array([1. , 0.01, 0.02, 2. ])\n\n    Multiple fixed compounds also work fine:\n\n    >>> pH = 6\n    >>> scheme = rx.parse_reactions(\"A + H2O -> B <=> B- + H+\")\n    >>> k = np.array([1.0, 100.0, 2.0])\n    >>> scheme, k = rx.get_fixed_scheme(scheme, k, {\"H+\": 10**-pH, \"H2O\": 55.6})\n    >>> scheme\n    Scheme(compounds=('A', 'B', 'B-'),\n           reactions=('A -> B',\n                      'B -> B-',\n                      'B- -> B'),\n           is_half_equilibrium=(False, True, True),\n           A=((-1.0, 0.0, 0.0),\n              (1.0, -1.0, 1.0),\n              (0.0, 1.0, -1.0)),\n           B=((-1.0, 0.0, 0.0),\n              (1.0, -1.0, 0.0),\n              (0.0, 1.0, 0.0)))\n    >>> k\n    array([5.56e+01, 1.00e+02, 2.00e-06])\n\n    This function is a no-op if `fixed_y0` is empty, which is very important\n    for overall code consistency:\n\n    >>> scheme = rx.parse_reactions([\"AH <=> A- + H+\", \"B- + H+ <=> BH\"])\n    >>> k = np.array([1, 1, 2, 2])\n    >>> new_scheme, new_k = rx.get_fixed_scheme(scheme, k, {})\n    >>> new_scheme == scheme\n    True\n    >>> np.allclose(new_k, k)\n    True\n\n    \"\"\"\n    new_k = np.asarray(k, dtype=float).copy()\n    new_reactions = []\n    for i, (reaction, is_half_equilibrium) in enumerate(\n        zip(scheme.reactions, scheme.is_half_equilibrium)\n    ):\n        for reactants, products, _ in rx.core._parse_reactions(reaction):\n            new_reactants = tuple(\n                (coeff, compound)\n                for (coeff, compound) in reactants\n                if compound not in fixed_y0\n            )\n            new_products = tuple(\n                (coeff, compound)\n                for (coeff, compound) in products\n                if compound not in fixed_y0\n            )\n\n            for fixed_compound in fixed_y0:\n                for coeff, compound in reactants:\n                    if fixed_compound == compound:\n                        new_k[i] *= fixed_y0[fixed_compound] ** coeff\n\n            new_reactions.append((new_reactants, new_products, is_half_equilibrium))\n\n    new_reactions = tuple(r for r in rx.core._unparse_reactions(new_reactions))\n    new_is_half_equilibrium = scheme.is_half_equilibrium\n\n    new_A = []\n    new_B = []\n    new_compounds = []\n    for i, (compound, row_A, row_B) in enumerate(\n        zip(scheme.compounds, scheme.A, scheme.B)\n    ):\n        if compound not in fixed_y0:\n            new_compounds.append(compound)\n            new_A.append(row_A)\n            new_B.append(row_B)\n\n    new_compounds = tuple(new_compounds)\n    new_A = tuple(new_A)\n    new_B = tuple(new_B)\n\n    return (\n        rx.core.Scheme(\n            compounds=new_compounds,\n            reactions=new_reactions,\n            is_half_equilibrium=new_is_half_equilibrium,\n            A=new_A,\n            B=new_B,\n        ),\n        new_k,\n    )\n\n\n# TODO(schneiderfelipe): this is probably not ready yet\ndef get_bias(\n    scheme,\n    compounds,\n    data,\n    y0,\n    tunneling=\"eckart\",\n    qrrho=True,\n    temperature=298.15,\n    pressure=constants.atm,\n    method=\"Radau\",\n    rtol=1e-5,\n    atol=1e-11,\n):\n    r\"\"\"Estimate a energy bias for a given set of reference data points.\n\n    Parameters\n    ----------\n    scheme : Scheme\n        A descriptor of the reaction scheme.\n        Mostly likely, this comes from a parsed model input file.\n        See `overreact.io.parse_model`.\n    compounds : dict-like\n        A descriptor of the compounds.\n        Mostly likely, this comes from a parsed model input file.\n        See `overreact.io.parse_model`.\n    data : dict-like of array-like\n    y0: array-like\n    tunneling : str or None, optional\n        Choose between \"eckart\", \"wigner\" or None (or \"none\").\n    qrrho : bool or tuple-like, optional\n        Apply both the quasi-rigid rotor harmonic oscillator (QRRHO)\n        approximations of M. Head-Gordon and others (enthalpy correction, see\n        [*J. Phys. Chem. C* **2015**, 119, 4, 1840–1850](http://dx.doi.org/10.1021/jp509921r)) and S. Grimme (entropy correction, see\n        [*Theory. Chem. Eur. J.*, **2012**, 18: 9955-9964](https://doi.org/10.1002/chem.201200497)) on top of the classical RRHO.\n    temperature : array-like, optional\n        Absolute temperature in Kelvin.\n    pressure : array-like, optional\n        Reference gas pressure.\n    delta_freeenergies : array-like, optional\n        Use this instead of obtaining delta free energies from the compounds.\n    molecularity : array-like, optional\n        Reaction order, i.e., number of molecules that come together to react.\n        If set, this is used to calculate `delta_moles` for\n        `equilibrium_constant`, which effectively calculates a solution\n        equilibrium constant between reactants and the transition state for\n        gas phase data. You should set this to `None` if your free energies\n        were already adjusted for solution Gibbs free energies.\n    volume : float, optional\n        Molar volume.\n\n    Returns\n    -------\n    array-like\n\n    Examples\n    --------\n    >>> model = rx.parse_model(\"data/tanaka1996/UMP2/cc-pVTZ/model.jk\")\n\n    The following are some estimates on actual atmospheric concentrations:\n\n    >>> y0 = [4.8120675684099e-5,\n    ...       2.8206357713029e-5,\n    ...       0.0,\n    ...       0.0,\n    ...       2.7426565371219e-5]\n    >>> data = {\"t\": [1.276472128376942246e-6,\n    ...               1.446535794555581743e-4,\n    ...               1.717069678525567564e-2],\n    ...         \"CH3·\": [9.694916853338366211e-9,\n    ...                  1.066033349343709026e-6,\n    ...                  2.632179124780495175e-5]}\n    >>> get_bias(model.scheme, model.compounds, data, y0) / constants.kcal\n    -1.364171\n    \"\"\"\n    max_time = np.max(data[\"t\"])\n\n    def f(bias):\n        k = rx.get_k(\n            scheme,\n            compounds,\n            bias=bias,\n            tunneling=tunneling,\n            qrrho=qrrho,\n            temperature=temperature,\n            pressure=pressure,\n        )\n\n        # TODO(schneiderfelipe): support schemes with fixed concentrations\n        dydt = rx.get_dydt(scheme, k)\n        y, _ = rx.get_y(\n            dydt, y0=y0, method=method, rtol=rtol, atol=atol, max_time=max_time\n        )\n\n        yhat = y(data[\"t\"])\n        return np.sum(\n            [\n                (yhat[i] - data[name]) ** 2\n                for (i, name) in enumerate(compounds)\n                if name in data\n            ]\n        )\n\n    res = minimize_scalar(f)\n    return res.x\n", "meta": {"hexsha": "22e0ef7b2d5b300285e6226a53ed5c7544d02e42", "size": 20423, "ext": "py", "lang": "Python", "max_stars_repo_path": "overreact/simulate.py", "max_stars_repo_name": "geem-lab/overreact", "max_stars_repo_head_hexsha": "4f2c0d4a28c9f9a0fd12dca061483348ecdcd86e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2021-08-11T20:18:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T18:22:35.000Z", "max_issues_repo_path": "overreact/simulate.py", "max_issues_repo_name": "Leticia-maria/overreact", "max_issues_repo_head_hexsha": "eede50a45df5bfae942b3251f04b80ca8cd8f9c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 73, "max_issues_repo_issues_event_min_datetime": "2021-10-15T17:21:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T12:28:36.000Z", "max_forks_repo_path": "overreact/simulate.py", "max_forks_repo_name": "Leticia-maria/overreact", "max_forks_repo_head_hexsha": "eede50a45df5bfae942b3251f04b80ca8cd8f9c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-10-13T23:43:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T19:45:55.000Z", "avg_line_length": 32.2129337539, "max_line_length": 133, "alphanum_fraction": 0.5731773001, "include": true, "reason": "import numpy,from scipy,import jax,from jax", "num_tokens": 5767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.18434957609646863}}
{"text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport warnings\nimport numpy as np\n\nfrom astropy.time import Time, TimeDelta\n\nfrom ..interval_set import IntervalSet\nfrom ..abstract_moc import AbstractMOC\n\nfrom .. import mocpy\nfrom .. import utils\n\n__author__ = \"Matthieu Baumann, François-Xavier Pineau\"\n__copyright__ = \"CDS, Centre de Données astronomiques de Strasbourg\"\n\n__license__ = \"BSD 3-Clause License\"\n__email__ = \"baumannmatthieu0@gmail.com, francois-xavier.pineau@astro.unistra.fr\"\n\nclass TimeMOC(AbstractMOC):\n    \"\"\"Multi-order time coverage class. Experimental\"\"\"\n    DAY_MICRO_SEC = 86400000000.\n    # default observation time : 30 min\n    DEFAULT_OBSERVATION_TIME = TimeDelta(30 * 60, format='sec', scale='tdb')\n\n    # I introduced, but do not like, the double `make_consistent` (MOC + IntervalSet)\n    # but `coverage_merge_time_intervals` is no more genric\n    # and I can't remove `make_consistent` from `IntervalSet` without changing tests\n    def __init__(self, interval_set=None, make_consistent=True, min_depth=None):\n        \"\"\"\n        TimeMoc constructor.\n\n        The merging step of the overlapping intervals is done here.\n\n        Parameters\n        ----------\n        intervals : `~numpy.ndarray`\n            a N x 2 numpy array representing the set of intervals.\n        make_consistent : bool, optional\n            True by default. Remove the overlapping intervals that makes\n            a valid MOC (i.e. can be plot, serialized, manipulated).\n        \"\"\"\n        super(TimeMOC, self).__init__(interval_set)\n\n        if make_consistent:\n            if min_depth is None:\n                min_depth = -1\n\n            min_depth = np.int8(min_depth)\n            self._merge_intervals(min_depth)\n\n    def _merge_intervals(self, min_depth):\n        if not self.empty():\n            self._interval_set._intervals = mocpy.coverage_merge_time_intervals(self._interval_set._intervals, min_depth)\n\n\n    @property\n    def max_order(self):\n        \"\"\"\n        Depth of the smallest Time cells found in the MOC instance.\n        \"\"\"\n        depth = mocpy.time_coverage_depth(self._interval_set._intervals)\n        depth = np.uint8(depth)\n        return depth\n\n    def refine_to_order(self, min_depth):\n        intervals = mocpy.coverage_merge_time_intervals(self._interval_set._intervals, min_depth)\n        interval_set = IntervalSet(intervals, make_consistent=False)\n        return TimeMOC(interval_set, make_consistent=False)\n\n    def complement(self):\n        \"\"\"\n        Returns the complement of the TimeMOC instance.\n\n        Returns\n        -------\n        result : `~mocpy.moc.TimeMOC`\n            The resulting TimeMOC.\n        \"\"\"\n        intervals = mocpy.time_coverage_complement(self._interval_set._intervals)\n        interval_set = IntervalSet(intervals, make_consistent=False)\n        return TimeMOC(interval_set, make_consistent=False)\n\n    def degrade_to_order(self, new_order):\n        \"\"\"\n        Degrades the MOC instance to a new, less precise, MOC.\n\n        The maximum depth (i.e. the depth of the smallest Time cells that can be found in the MOC) of the\n        degraded MOC is set to ``new_order``.\n\n        Parameters\n        ----------\n        new_order : int\n            Maximum depth of the output degraded MOC.\n\n        Returns\n        -------\n        moc : `~mocpy.tmoc.TimeMOC`\n            The degraded MOC.\n        \"\"\"\n        assert self._interval_set._intervals.shape[1] == 2\n        intervals = mocpy.time_coverage_degrade(self._interval_set._intervals, new_order)\n        return TimeMOC(IntervalSet(intervals, make_consistent=False), make_consistent=False)\n\n    @classmethod\n    def from_times(cls, times, delta_t=DEFAULT_OBSERVATION_TIME):\n        \"\"\"\n        Create a TimeMOC from a `astropy.time.Time`\n\n        Parameters\n        ----------\n        times : `astropy.time.Time`\n            Astropy observation times\n        delta_t : `astropy.time.TimeDelta`, optional\n            The duration of one observation. It is set to 30 min by default. This data is used to compute the\n            more efficient TimeMOC order to represent the observations (Best order = the less precise order which\n            is able to discriminate two observations separated by ``delta_t``).\n\n        Returns\n        -------\n        time_moc : `~mocpy.tmoc.TimeMOC`\n        \"\"\"\n        times = utils.times_to_microseconds(times)\n        times = np.atleast_1d(times)\n\n        times = times.reshape((times.shape[0], 1))\n        intervals = np.hstack((times, times + np.uint64(1)))\n        assert intervals.shape[1] == 2\n\n        # degrade the TimeMoc to the order computed from ``delta_t``\n        depth = TimeMOC.time_resolution_to_order(delta_t)\n        tmoc = TimeMOC(IntervalSet(intervals))\n        return tmoc.degrade_to_order(depth)\n\n    @classmethod\n    def from_time_ranges(cls, min_times, max_times, delta_t=DEFAULT_OBSERVATION_TIME):\n        \"\"\"\n        Create a TimeMOC from a range defined by two `astropy.time.Time`\n\n        Parameters\n        ----------\n        min_times : `astropy.time.Time`\n            astropy times defining the left part of the intervals\n        max_times : `astropy.time.Time`\n            astropy times defining the right part of the intervals\n        delta_t : `astropy.time.TimeDelta`, optional\n            the duration of one observation. It is set to 30 min by default. This data is used to compute the\n            more efficient TimeMOC order to represent the observations (Best order = the less precise order which\n            is able to discriminate two observations separated by ``delta_t``).\n\n        Returns\n        -------\n        time_moc : `~mocpy.tmoc.TimeMOC`\n        \"\"\"\n        # degrade the TimeMoc to the order computed from ``delta_t``\n        depth = TimeMOC.time_resolution_to_order(delta_t)\n        \n        min_times = utils.times_to_microseconds(min_times)\n        min_times = np.atleast_1d(min_times)\n\n        max_times = utils.times_to_microseconds(max_times)\n        max_times = np.atleast_1d(max_times)\n\n        assert min_times.shape == max_times.shape\n\n        intervals = mocpy.from_time_ranges_in_microsec_since_jd_origin(min_times, max_times)\n\n        tmoc = TimeMOC(IntervalSet(intervals, make_consistent=False), make_consistent=False)\n        return tmoc.degrade_to_order(depth)\n\n\n    @classmethod\n    def from_time_ranges_approx(cls, min_times, max_times, delta_t=DEFAULT_OBSERVATION_TIME):\n        \"\"\"\n        Create a TimeMOC from a range defined by two `astropy.time.Time`.\n        Uses the following approximation: simple take the JD time and multiply by the number of microseconds in a day.\n\n        Parameters\n        ----------\n        min_times : `astropy.time.Time`\n            astropy times defining the left part of the intervals\n        max_times : `astropy.time.Time`\n            astropy times defining the right part of the intervals\n        delta_t : `astropy.time.TimeDelta`, optional\n            the duration of one observation. It is set to 30 min by default. This data is used to compute the\n            more efficient TimeMOC order to represent the observations (Best order = the less precise order which\n            is able to discriminate two observations separated by ``delta_t``).\n\n        Returns\n        -------\n        time_moc : `~mocpy.tmoc.TimeMOC`\n        \"\"\"\n        # degrade the TimeMoc to the order computed from ``delta_t``\n        depth = TimeMOC.time_resolution_to_order(delta_t)\n\n        min_times = np.asarray(min_times.jd)\n        min_times = np.atleast_1d(min_times)\n\n        max_times = np.asarray(max_times.jd)\n        max_times = np.atleast_1d(max_times)\n\n        assert min_times.shape == max_times.shape\n\n        intervals = mocpy.from_time_ranges(min_times, max_times)\n\n        tmoc = TimeMOC(IntervalSet(intervals, make_consistent=False), make_consistent=False)\n        return tmoc.degrade_to_order(depth)\n\n    def add_neighbours(self):\n        \"\"\"\n        Add all the pixels at max order in the neighbourhood of the moc\n\n        Returns\n        -------\n        tmoc : `~mocpy.tmoc.TimeMOC`\n            self extended by one degree of neighbors.\n        \"\"\"\n        time_delta = np.uint64(1) << (IntervalSet.TIME_MAX_ORDER - self.max_order)\n\n        intervals = self._interval_set._intervals\n        # WARN: astype gives the ownership/writeable of the array to python\n        # It is necessary for writing the array\n        # This will be removed as soon as this code is ported in rust\n        intervals = intervals.astype(np.uint64)\n\n        intervals[:, 0] = np.maximum(intervals[:, 0] - time_delta, np.uint64(0))\n        intervals[:, 1] = np.minimum(intervals[:, 1] + time_delta, np.uint64((1 << 62) - 1))\n\n        self._interval_set = IntervalSet(intervals)\n        return self\n\n    def remove_neighbours(self):\n        \"\"\"\n        Remove all the pixels at max order located at the bound of the moc\n\n        Returns\n        -------\n        tmoc : `~mocpy.tmoc.TimeMOC`\n            self shrinked by one degree of neighbors.\n        \"\"\"\n        time_delta = np.uint64(1) << (IntervalSet.TIME_MAX_ORDER - self.max_order)\n\n        intervals = self._interval_set._intervals\n        # WARN: astype gives the ownership/writeable of the array to python\n        # It is necessary for writing the array\n        # This will be removed as soon as this code is ported in rust\n        intervals = intervals.astype(np.uint64)\n\n        intervals[:, 0] = np.minimum(intervals[:, 0] + time_delta, np.uint64((1 << 62) - 1))\n        intervals[:, 1] = np.maximum(intervals[:, 1] - time_delta, np.uint64(0))\n\n        good_intervals = intervals[:, 1] > intervals[:, 0]\n\n        self._interval_set = IntervalSet(intervals[good_intervals])\n        return self\n\n    def _process_degradation(self, another_moc, order_op):\n        \"\"\"\n        Degrade (down-sampling) self and ``another_moc`` to ``order_op`` order\n\n        Parameters\n        ----------\n        another_moc : `~mocpy.tmoc.TimeMoc`\n        order_op : int\n            the order in which self and ``another_moc`` will be down-sampled to.\n\n        Returns\n        -------\n        result : (`~mocpy.tmoc.TimeMoc`, `~mocpy.tmoc.TimeMoc`)\n            self and ``another_moc`` degraded TimeMocs\n\n        \"\"\"\n        max_order = max(self.max_order, another_moc.max_order)\n        if order_op > max_order:\n            message = 'Requested time resolution for the operation cannot be applied.\\n' \\\n                      'The TimeMoc object resulting from the operation is of time resolution {0} sec.'.format(\n                TimeMOC.order_to_time_resolution(max_order).sec)\n            warnings.warn(message, UserWarning)\n\n        self_degradation = self.degrade_to_order(order_op)\n        another_moc_degradation = another_moc.degrade_to_order(order_op)\n\n        result = self_degradation, another_moc_degradation\n        return result\n\n    def intersection_with_timeresolution(self, another_moc, delta_t=DEFAULT_OBSERVATION_TIME):\n        \"\"\"\n        Intersection between self and moc. ``delta_t`` gives the possibility to the user\n        to set a time resolution for performing the tmoc intersection\n\n        Parameters\n        ----------\n        another_moc : `~mocpy.abstract_moc.AbstractMOC`\n            the MOC/TimeMOC used for performing the intersection with self\n        delta_t : `~astropy.time.TimeDelta`, optional\n            the duration of one observation. It is set to 30 min by default. This data is used to compute the\n            more efficient TimeMoc order to represent the observations. (Best order = the less precise order which\n            is able to discriminate two observations separated by ``delta_t``)\n\n        Returns\n        -------\n        result : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC`\n            MOC object whose interval set corresponds to : self & ``moc``\n\n        \"\"\"\n\n        order_op = TimeMOC.time_resolution_to_order(delta_t)\n\n        self_degraded, moc_degraded = self._process_degradation(another_moc, order_op)\n        return super(TimeMOC, self_degraded).intersection(moc_degraded)\n\n    def union_with_timeresolution(self, another_moc, delta_t=DEFAULT_OBSERVATION_TIME):\n        \"\"\"\n        Union between self and moc. ``delta_t`` gives the possibility to the user\n        to set a time resolution for performing the tmoc union\n\n        Parameters\n        ----------\n        another_moc : `~mocpy.abstract_moc.AbstractMOC`\n            the MOC/TimeMoc to bind to self\n        delta_t : `~astropy.time.TimeDelta`, optional\n            the duration of one observation. It is set to 30 min by default. This data is used to compute the\n            more efficient TimeMoc order to represent the observations. (Best order = the less precise order which\n            is able to discriminate two observations separated by ``delta_t``)\n\n        Returns\n        -------\n        result : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMoc`\n            MOC object whose interval set corresponds to : self | ``moc``\n\n        \"\"\"\n\n        order_op = TimeMOC.time_resolution_to_order(delta_t)\n\n        self_degraded, moc_degraded = self._process_degradation(another_moc, order_op)\n        return super(TimeMOC, self_degraded).union(moc_degraded)\n\n    def difference_with_timeresolution(self, another_moc, delta_t=DEFAULT_OBSERVATION_TIME):\n        \"\"\"\n        Difference between self and moc. ``delta_t`` gives the possibility to the user\n        to set a time resolution for performing the tmoc diff\n\n        Parameters\n        ----------\n        another_moc : `~mocpy.abstract_moc.AbstractMOC`\n            the MOC/TimeMoc to substract from self\n        delta_t : `~astropy.time.TimeDelta`, optional\n            the duration of one observation. It is set to 30 min by default. This data is used to compute the\n            more efficient TimeMoc order to represent the observations. (Best order = the less precise order which\n            is able to discriminate two observations separated by ``delta_t``)\n\n        Returns\n        -------\n        result : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMoc`\n            MOC object whose interval set corresponds to : self - ``moc``\n\n        \"\"\"\n\n        order_op = TimeMOC.time_resolution_to_order(delta_t)\n\n        self_degraded, moc_degraded = self._process_degradation(another_moc, order_op)\n        return super(TimeMOC, self_degraded).difference(moc_degraded)\n\n    @property\n    def _fits_header_keywords(self):\n        return {\n            'PIXTYPE': 'HEALPIX',\n            'ORDERING': 'NUNIQ',\n            'TIMESYS': ('JD', 'ref system JD BARYCENTRIC TT, 1 usec level 29'),\n            'MOCORDER': self.max_order,\n            'MOCTOOL': 'MOCPy'\n        }\n    \n    @property\n    def _fits_format(self):\n        depth = self.max_order\n        if depth <= 13:\n            fits_format = '1J'\n        else:\n            fits_format = '1K'\n        return fits_format\n\n    @property\n    def total_duration(self):\n        \"\"\"\n        Get the total duration covered by the temporal moc\n\n        Returns\n        -------\n        duration : `~astropy.time.TimeDelta`\n            total duration of all the observation times of the tmoc\n            total duration of all the observation times of the tmoc\n\n        \"\"\"\n\n        if self._interval_set.empty():\n            return 0\n\n        total_time_us = 0\n        # The interval set is checked for consistency before looping over all the intervals\n        for (start_time, stop_time) in self._interval_set._intervals:\n            total_time_us = total_time_us + (stop_time - start_time)\n\n        duration = TimeDelta(total_time_us / 1e6, format='sec', scale='tdb')\n        return duration\n\n    @property\n    def consistency(self):\n        \"\"\"\n        Get a percentage of fill between the min and max time the moc is defined.\n\n        A value near 0 shows a sparse temporal moc (i.e. the moc does not cover a lot\n        of time and covers very distant times. A value near 1 means that the moc covers\n        a lot of time without big pauses.\n\n        Returns\n        -------\n        result : float\n            fill percentage (between 0 and 1.)\n\n        \"\"\"\n\n        result = self.total_duration.jd / (self.max_time - self.min_time).jd\n        return result\n\n    @property\n    def min_time(self):\n        \"\"\"\n        Get the `~astropy.time.Time` time of the tmoc first observation\n\n        Returns\n        -------\n        min_time : `astropy.time.Time`\n            time of the first observation\n\n        \"\"\"\n\n        # min_time = Time(self._interval_set.min / TimeMOC.DAY_MICRO_SEC, format='jd', scale='tdb')\n        min_time = utils.microseconds_to_times(self._interval_set.min)\n        return min_time\n\n    @property\n    def max_time(self):\n        \"\"\"\n        Get the `~astropy.time.Time` time of the tmoc last observation\n\n        Returns\n        -------\n        max_time : `~astropy.time.Time`\n            time of the last observation\n\n        \"\"\"\n\n        max_time = utils.microseconds_to_times(self._interval_set.max)\n        return max_time\n\n    def contains(self, times, keep_inside=True, delta_t=DEFAULT_OBSERVATION_TIME):\n        \"\"\"\n        Get a mask array (e.g. a numpy boolean array) of times being inside (or outside) the\n        TMOC instance.\n\n        Parameters\n        ----------\n        times : `astropy.time.Time`\n            astropy times to check whether they are contained in the TMOC or not.\n        keep_inside : bool, optional\n            True by default. If so the filtered table contains only observations that are located the MOC.\n            If ``keep_inside`` is False, the filtered table contains all observations lying outside the MOC.\n        delta_t : `astropy.time.TimeDelta`, optional\n            the duration of one observation. It is set to 30 min by default. This data is used to compute the\n            more efficient TimeMOC order to represent the observations (Best order = the less precise order which\n            is able to discriminate two observations separated by ``delta_t``).\n\n        Returns\n        -------\n        array : `~numpy.darray`\n            A mask boolean array\n        \"\"\"\n        # the requested order for filtering the astropy observations table is more precise than the order\n        # of the TimeMoc object\n        current_max_order = self.max_order\n        new_max_order = TimeMOC.time_resolution_to_order(delta_t)\n        if new_max_order > current_max_order:\n            message = 'Requested time resolution filtering cannot be applied.\\n' \\\n                      'Filtering is applied with a time resolution of {0} sec.'.format(\n                TimeMOC.order_to_time_resolution(current_max_order).sec)\n            warnings.warn(message, UserWarning)\n\n        rough_tmoc = self.degrade_to_order(new_max_order)\n\n        #pix_arr = (times.jd * TimeMOC.DAY_MICRO_SEC)\n        #pix_arr = pix_arr.astype(np.uint64)\n        pix_arr = utils.times_to_microseconds(times)\n\n        intervals = rough_tmoc._interval_set._intervals\n        inf_arr = np.vstack([pix_arr[i] >= intervals[:, 0] for i in range(pix_arr.shape[0])])\n        sup_arr = np.vstack([pix_arr[i] <= intervals[:, 1] for i in range(pix_arr.shape[0])])\n\n        if keep_inside:\n            res = inf_arr & sup_arr\n            filtered_rows = np.any(res, axis=1)\n        else:\n            res = ~inf_arr | ~sup_arr\n            filtered_rows = np.all(res, axis=1)\n\n        return filtered_rows\n\n    @staticmethod\n    def order_to_time_resolution(order):\n        \"\"\"\n        Convert an TimeMoc order to its equivalent time\n\n        Parameters\n        ----------\n        order : int\n            order to convert\n\n        Returns\n        -------\n        delta_t : `~astropy.time.TimeDelta`\n            time equivalent to ``order``\n\n        \"\"\"\n\n        delta_t = TimeDelta(2**(61 - order) / 1e6, format='sec', scale='tdb')\n        return delta_t\n\n    @staticmethod\n    def time_resolution_to_order(delta_time):\n        \"\"\"\n        Convert a time resolution to a TimeMoc order.\n\n        Parameters\n        ----------\n        delta_time : `~astropy.time.TimeDelta`\n            time to convert\n\n        Returns\n        -------\n        order : int\n            The less precise order which is able to discriminate two observations separated by ``delta_time``.\n\n        \"\"\"\n\n        order = 61 - int(np.log2(delta_time.sec * 1e6))\n        return np.uint8(order)\n\n    def plot(self, title='TimeMoc', view=(None, None), figsize=(9.5, 5), **kwargs):\n        \"\"\"\n        Plot the TimeMoc in a time window.\n\n        This method uses interactive matplotlib. The user can move its mouse through the plot to see the\n        time (at the mouse position).\n\n        Parameters\n        ----------\n        title : str, optional\n            The title of the plot. Set to 'TimeMoc' by default.\n        view : (`~astropy.time.Time`, `~astropy.time.Time`), optional\n            Define the view window in which the observations are plotted. Set to (None, None) by default (i.e.\n            all the observation time window is rendered).\n\n        \"\"\"\n        from matplotlib.colors import LinearSegmentedColormap\n        import matplotlib.pyplot as plt\n\n        if self._interval_set.empty():\n            import warnings\n            warnings.warn('This time moc is empty', UserWarning)\n            return\n\n        plot_order = 30\n        if self.max_order > plot_order:\n            plotted_moc = self.degrade_to_order(plot_order)\n        else:\n            plotted_moc = self\n\n        min_jd = plotted_moc.min_time.jd if not view[0] else view[0].jd\n        max_jd = plotted_moc.max_time.jd if not view[1] else view[1].jd\n\n        \n        if max_jd < min_jd:\n            raise ValueError(\"Invalid selection: max_jd = {0} must be > to min_jd = {1}\".format(max_jd, min_jd))\n\n        fig1 = plt.figure(figsize=figsize)\n        ax = fig1.add_subplot(111)\n\n        ax.set_xlabel('iso')\n        ax.get_yaxis().set_visible(False)\n\n        size = 2000\n        delta = (max_jd - min_jd) / size\n        min_jd_time = min_jd\n\n        ax.set_xticks([0, size])\n        ax.set_xticklabels(Time([min_jd_time, max_jd], format='jd', scale='tdb').iso, rotation=70)\n\n        y = np.zeros(size)\n        for (s_time_us, e_time_us) in plotted_moc._interval_set._intervals:\n            s_index = int((utils.microseconds_to_times(s_time_us).jd - min_jd_time) / delta)\n            e_index = int((utils.microseconds_to_times(e_time_us).jd - min_jd_time) / delta)\n            y[s_index:(e_index+1)] = 1.0\n\n        # hack in case of full time mocs.\n        if np.all(y):\n            y[0] = 0\n\n        z = np.tile(y, (int(size//10), 1))\n\n        plt.title(title)\n\n        color_map = LinearSegmentedColormap.from_list('w2r', ['#fffff0', '#aa0000'])\n        color_map.set_under('w')\n        color_map.set_bad('gray')\n\n        plt.imshow(z, interpolation='bilinear', **kwargs)\n\n        def on_mouse_motion(event):\n            for txt in ax.texts:\n                txt.set_visible(False)\n\n            text = ax.text(0, 0, \"\", va=\"bottom\", ha=\"left\")\n\n            time = Time(event.xdata * delta + min_jd_time, format='jd', scale='tdb')\n\n            tx = '{0}'.format(time.iso)\n            text.set_position((event.xdata - 50, 700))\n            text.set_rotation(70)\n            text.set_text(tx)\n\n        cid = fig1.canvas.mpl_connect('motion_notify_event', on_mouse_motion)\n\n        plt.show()\n\n    def save(self, path, format='fits', overwrite=False):\n        \"\"\"\n        Writes the Time MOC to a file.\n\n        Format can be 'fits', 'ascii', or 'json', though the json format is not officially supported by the IVOA.\n\n        Parameters\n        ----------\n        path : str\n            The path to the file to save the MOC in.\n        format : str, optional\n            The format in which the MOC will be serialized before being saved.\n            Possible formats are \"fits\", \"ascii\" or \"json\".\n            By default, ``format`` is set to \"fits\".\n        overwrite : bool, optional\n            If the file already exists and you want to overwrite it, then set the  ``overwrite`` keyword.\n            Default to False.\n        \"\"\"\n        import os\n        file_exists = os.path.isfile(path)\n        \n        if file_exists and not overwrite:\n            raise OSError('File {} already exists! Set ``overwrite`` to '\n                          'True if you want to replace it.'.format(path))        \n        \n        if format == 'fits':\n            mocpy.time_moc_to_fits_file(self.max_order, self._interval_set._intervals, path)\n        elif format == 'ascii':\n            mocpy.time_moc_to_ascii_file(self.max_order, self._interval_set._intervals, path)\n        elif format == 'json':\n            mocpy.time_moc_to_json_file(self.max_order, self._interval_set._intervals, path)\n        else:\n            formats = ('fits', 'ascii', 'json')\n            raise ValueError('format should be one of %s' % (str(formats)))\n\n    @classmethod\n    def load(cls, path, format='fits'):\n        \"\"\"\n        Load the Time MOC from a file.\n\n        Format can be 'fits', 'ascii', or 'json', though the json format is not officially supported by the IVOA.\n\n        Parameters\n        ----------\n        path : str\n            The path to the file to load the MOC from.\n        format : str, optional\n            The format from which the MOC is loaded.\n            Possible formats are \"fits\", \"ascii\" or \"json\".\n            By default, ``format`` is set to \"fits\".\n        \"\"\"\n        if format == 'fits':\n            intervals = mocpy.time_moc_from_fits_file(path)\n            return cls(IntervalSet(intervals, make_consistent=False), make_consistent=False)\n        elif format == 'ascii':\n            intervals = mocpy.time_moc_from_ascii_file(path)\n            return cls(IntervalSet(intervals, make_consistent=False), make_consistent=False)\n        elif format == 'json':\n            intervals = mocpy.time_moc_from_json_file(path)\n            return cls(IntervalSet(intervals, make_consistent=False), make_consistent=False)\n        else:\n            formats = ('fits', 'ascii', 'json')\n            raise ValueError('format should be one of %s' % (str(formats)))\n\n    def to_string(self, format='ascii'):\n        \"\"\"\n        Writes the Time MOC into a string.\n\n        Format can be 'ascii' or 'json', though the json format is not officially supported by the IVOA.\n\n        Parameters\n        ----------\n        format : str, optional\n            The format in which the MOC will be serialized before being saved.\n            Possible formats are \"ascii\" or \"json\".\n            By default, ``format`` is set to \"ascii\".\n        \"\"\"\n        if format == 'ascii':\n            return mocpy.time_moc_to_ascii_str(self.max_order, self._interval_set._intervals)\n        elif format == 'json':\n            return mocpy.time_moc_to_json_str(self.max_order, self._interval_set._intervals)\n        else:\n            formats = ('ascii', 'json')\n            raise ValueError('format should be one of %s' % (str(formats)))\n\n    @classmethod\n    def from_string(cls, value, format='ascii'):\n        \"\"\"\n        Deserialize the Time MOC from the given string.\n\n        Format can be 'ascii' or 'json', though the json format is not officially supported by the IVOA.\n\n        WARNING: the serialization must be strict, i.e. **must not** contain overlapping elements\n\n        Parameters\n        ----------\n        format : str, optional\n            The format in which the MOC will be serialized before being saved.\n            Possible formats are \"ascii\" or \"json\".\n            By default, ``format`` is set to \"ascii\".\n        \"\"\"\n        if format == 'ascii':\n            intervals = mocpy.time_moc_from_ascii_str(value)\n            return cls(IntervalSet(intervals, make_consistent=False), make_consistent=False)\n        elif format == 'json':\n            intervals = mocpy.time_moc_from_json_str(value)\n            return cls(IntervalSet(intervals, make_consistent=False), make_consistent=False)\n        else:\n            formats = ('ascii', 'json')\n            raise ValueError('format should be one of %s' % (str(formats)))", "meta": {"hexsha": "6f34deede77fd87d2b3581170412769329106c31", "size": 28030, "ext": "py", "lang": "Python", "max_stars_repo_path": "mocpy/tmoc/tmoc.py", "max_stars_repo_name": "marxide/mocpy", "max_stars_repo_head_hexsha": "280ad1fcda1461f356728a1527395a18a9d19fec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2017-07-24T10:11:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T06:22:59.000Z", "max_issues_repo_path": "mocpy/tmoc/tmoc.py", "max_issues_repo_name": "tboch/pymoc", "max_issues_repo_head_hexsha": "fbbde759f18ebeb656ec2b2150225e453c3b4550", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 55, "max_issues_repo_issues_event_min_datetime": "2017-10-17T12:05:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T21:31:06.000Z", "max_forks_repo_path": "mocpy/tmoc/tmoc.py", "max_forks_repo_name": "tboch/pymoc", "max_forks_repo_head_hexsha": "fbbde759f18ebeb656ec2b2150225e453c3b4550", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2017-10-17T09:51:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-07T21:09:23.000Z", "avg_line_length": 37.6241610738, "max_line_length": 121, "alphanum_fraction": 0.6231180878, "include": true, "reason": "import numpy,from astropy", "num_tokens": 6451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.18432007243017431}}
{"text": "\"\"\"\n\"\"\"\nfrom __future__ import absolute_import\n\nimport sys\nimport weakref\n\nimport numpy\n\nfrom .dimensionality import Dimensionality\nfrom . import markup\nfrom .quantity import Quantity, get_conversion_factor\nfrom .registry import unit_registry\nfrom .decorators import memoize, with_doc\n\n\n__all__ = [\n    'CompoundUnit', 'Dimensionless', 'UnitConstant', 'UnitCurrency',\n    'UnitCurrent', 'UnitInformation', 'UnitLength', 'UnitLuminousIntensity',\n    'UnitMass', 'UnitMass', 'UnitQuantity', 'UnitSubstance', 'UnitTemperature',\n    'UnitTime', 'set_default_units'\n]\n\n\nclass UnitQuantity(Quantity):\n\n    _primary_order = 90\n    _secondary_order = 0\n    _reference_quantity = None\n\n    __array_priority__ = 20\n\n    def __new__(\n        cls, name, definition=None, symbol=None, u_symbol=None,\n        aliases=[], doc=None\n    ):\n        try:\n            assert isinstance(name, str)\n        except AssertionError:\n            raise TypeError('name must be a string, got %s (not unicode)'%name)\n        try:\n            assert symbol is None or isinstance(symbol, str)\n        except AssertionError:\n            raise TypeError(\n                'symbol must be a string, '\n                'got %s (u_symbol can be unicode)'%symbol\n            )\n\n        ret = numpy.array(1, dtype='d').view(cls)\n        ret.flags.writeable = False\n\n        ret._name = name\n        ret._symbol = symbol\n        ret._u_symbol = u_symbol\n        if doc is not None:\n            ret.__doc__ = doc\n\n        if definition is not None:\n            if not isinstance(definition, Quantity):\n                definition *= dimensionless\n            ret._definition = definition\n            ret._conv_ref = definition._reference\n        else:\n            ret._definition = None\n            ret._conv_ref = None\n\n        ret._aliases = aliases\n\n        ret._format_order = (ret._primary_order, ret._secondary_order)\n        ret.__class__._secondary_order += 1\n\n        return ret\n\n    def __init__(\n        self, name, definition=None, symbol=None, u_symbol=None,\n        aliases=[], doc=None\n    ):\n        unit_registry[name] = self\n        if symbol:\n            unit_registry[symbol] = self\n        for alias in aliases:\n            unit_registry[alias] = self\n\n    def __array_finalize__(self, obj):\n        pass\n\n    def __hash__(self):\n        return hash((type(self), self._name))\n\n    @property\n    def _reference(self):\n        if self._conv_ref is None:\n            return self\n        else:\n            return self._conv_ref\n\n    @property\n    def _dimensionality(self):\n        return Dimensionality({self:1})\n\n    @property\n    def format_order(self):\n        return self._format_order\n\n    @property\n    def name(self):\n        return self._name\n\n    @property\n    def definition(self):\n        if self._definition is None:\n            return self\n        else:\n            return self._definition\n\n    @property\n    def simplified(self):\n        return self._reference.simplified\n\n    @property\n    def symbol(self):\n        if self._symbol:\n            return self._symbol\n        else:\n            return self.name\n\n    @property\n    def u_symbol(self):\n        if self._u_symbol:\n            return self._u_symbol\n        else:\n            return self.symbol\n\n    @property\n    def units(self):\n        return self\n    @units.setter\n    def units(self, units):\n        raise AttributeError('can not modify protected units')\n\n    def __repr__(self):\n        ref = self._definition\n        if ref:\n            ref = ', %s * %s'%(str(ref.magnitude), ref.dimensionality.string)\n        else:\n            ref = ''\n        symbol = self._symbol\n        symbol = ', %s'%(repr(symbol)) if symbol else ''\n        if markup.config.use_unicode:\n            u_symbol = self._u_symbol\n            u_symbol = ', %s'%(repr(u_symbol)) if u_symbol else ''\n        else:\n            u_symbol = ''\n        return '%s(%s%s%s%s)'%(\n            self.__class__.__name__, repr(self.name), ref, symbol, u_symbol\n        )\n\n    @with_doc(Quantity.__str__, use_header=False)\n    def __str__(self):\n        if self.u_symbol != self.name:\n            if markup.config.use_unicode:\n                s = '1 %s (%s)'%(self.u_symbol, self.name)\n            else:\n                s = '1 %s (%s)'%(self.symbol, self.name)\n        else:\n            s = '1 %s'%self.name\n\n        return s\n\n    @with_doc(Quantity.__add__, use_header=False)\n    def __add__(self, other):\n        return self.view(Quantity).__add__(other)\n\n    @with_doc(Quantity.__radd__, use_header=False)\n    def __radd__(self, other):\n        try:\n            return self.rescale(other.units).__radd__(other)\n        except AttributeError:\n            return self.view(Quantity).__radd__(other)\n\n    @with_doc(Quantity.__sub__, use_header=False)\n    def __sub__(self, other):\n        return self.view(Quantity).__sub__(other)\n\n    @with_doc(Quantity.__rsub__, use_header=False)\n    def __rsub__(self, other):\n        try:\n            return self.rescale(other.units).__rsub__(other)\n        except AttributeError:\n            return self.view(Quantity).__rsub__(other)\n\n    @with_doc(Quantity.__mod__, use_header=False)\n    def __mod__(self, other):\n        return self.view(Quantity).__mod__(other)\n\n    @with_doc(Quantity.__rsub__, use_header=False)\n    def __rmod__(self, other):\n        try:\n            return self.rescale(other.units).__rmod__(other)\n        except AttributeError:\n            return self.view(Quantity).__rmod__(other)\n\n    @with_doc(Quantity.__mul__, use_header=False)\n    def __mul__(self, other):\n        return self.view(Quantity).__mul__(other)\n\n    @with_doc(Quantity.__rmul__, use_header=False)\n    def __rmul__(self, other):\n        return self.view(Quantity).__rmul__(other)\n\n    @with_doc(Quantity.__truediv__, use_header=False)\n    def __truediv__(self, other):\n        return self.view(Quantity).__truediv__(other)\n\n    @with_doc(Quantity.__rtruediv__, use_header=False)\n    def __rtruediv__(self, other):\n        return self.view(Quantity).__rtruediv__(other)\n\n    if sys.version_info[0] < 3:\n        @with_doc(Quantity.__div__, use_header=False)\n        def __div__(self, other):\n            return self.view(Quantity).__div__(other)\n\n        @with_doc(Quantity.__rdiv__, use_header=False)\n        def __rdiv__(self, other):\n            return self.view(Quantity).__rdiv__(other)\n\n    @with_doc(Quantity.__pow__, use_header=False)\n    def __pow__(self, other):\n        return self.view(Quantity).__pow__(other)\n\n    @with_doc(Quantity.__rpow__, use_header=False)\n    def __rpow__(self, other):\n        return self.view(Quantity).__rpow__(other)\n\n    @with_doc(Quantity.__iadd__, use_header=False)\n    def __iadd__(self, other):\n        raise TypeError('can not modify protected units')\n\n    @with_doc(Quantity.__isub__, use_header=False)\n    def __isub__(self, other):\n        raise TypeError('can not modify protected units')\n\n    @with_doc(Quantity.__imul__, use_header=False)\n    def __imul__(self, other):\n        raise TypeError('can not modify protected units')\n\n    @with_doc(Quantity.__itruediv__, use_header=False)\n    def __itruediv__(self, other):\n        raise TypeError('can not modify protected units')\n\n    if sys.version_info[0] < 3:\n        @with_doc(Quantity.__idiv__, use_header=False)\n        def __idiv__(self, other):\n            raise TypeError('can not modify protected units')\n\n    @with_doc(Quantity.__ipow__, use_header=False)\n    def __ipow__(self, other):\n        raise TypeError('can not modify protected units')\n\n    def __getstate__(self):\n        \"\"\"\n        Return the internal state of the quantity, for pickling\n        purposes.\n\n        \"\"\"\n        state = (1, self._format_order)\n        return state\n\n    def __setstate__(self, state):\n        ver, fo = state\n        self._format_order = fo\n\n    def __reduce__(self):\n        \"\"\"\n        Return a tuple for pickling a UnitQuantity.\n        \"\"\"\n        return (\n            type(self),\n            (\n                self._name,\n                self._definition,\n                self._symbol,\n                self._u_symbol,\n                self._aliases,\n                self.__doc__\n            ),\n            self.__getstate__()\n        )\n\n    def copy(self):\n        return (\n            type(self)(\n                self._name,\n                self._definition,\n                self._symbol,\n                self._u_symbol,\n                self._aliases,\n                self.__doc__\n                )\n            )\n\nunit_registry['UnitQuantity'] = UnitQuantity\n\n\nclass IrreducibleUnit(UnitQuantity):\n\n    _default_unit = None\n\n    def __init__(\n        self, name, definition=None, symbol=None, u_symbol=None,\n        aliases=[], doc=None\n    ):\n        super(IrreducibleUnit, self).__init__(\n            name, definition, symbol, u_symbol, aliases, doc\n        )\n        cls = type(self)\n        if cls._default_unit is None:\n            cls._default_unit = self\n\n    @property\n    def simplified(self):\n        return self.view(Quantity).rescale(self.get_default_unit())\n\n    @classmethod\n    def get_default_unit(cls):\n        return cls._default_unit\n    @classmethod\n    def set_default_unit(cls, unit):\n        if unit is None:\n            return\n        if isinstance(unit, str):\n            unit = unit_registry[unit]\n        try:\n            # check that conversions are possible:\n            get_conversion_factor(cls._default_unit, unit)\n        except ValueError:\n            raise TypeError('default unit must be of same type')\n        cls._default_unit = unit\n\n\nclass UnitMass(IrreducibleUnit):\n\n    _primary_order = 1\n\n\nclass UnitLength(IrreducibleUnit):\n\n    _primary_order = 2\n\n\nclass UnitTime(IrreducibleUnit):\n\n    _primary_order = 3\n\n\nclass UnitCurrent(IrreducibleUnit):\n\n    _primary_order = 4\n\n\nclass UnitLuminousIntensity(IrreducibleUnit):\n\n    _primary_order = 5\n\n\nclass UnitSubstance(IrreducibleUnit):\n\n    _primary_order = 6\n\n\nclass UnitTemperature(IrreducibleUnit):\n\n    _primary_order = 7\n\n\nclass UnitInformation(IrreducibleUnit):\n\n    _primary_order = 8\n\n\nclass UnitCurrency(IrreducibleUnit):\n\n    _primary_order = 9\n\n\nclass CompoundUnit(UnitQuantity):\n\n    _primary_order = 99\n\n    def __new__(cls, name):\n        return UnitQuantity.__new__(cls, name, unit_registry[name])\n\n    def __init__(self, name):\n        # do not register\n        return\n\n    @with_doc(UnitQuantity.__add__, use_header=False)\n    def __repr__(self):\n        return '1 %s'%self.name\n\n    @property\n    def name(self):\n        if markup.config.use_unicode:\n            return '(%s)'%(markup.superscript(self._name))\n        else:\n            return '(%s)'%self._name\n\n    def __reduce__(self):\n        \"\"\"\n        Return a tuple for pickling a UnitQuantity.\n        \"\"\"\n        return (\n            type(self),\n            (self._name, ),\n            self.__getstate__()\n            )\n\n    def copy(self):\n        return type(self)(self._name)\n\nunit_registry['CompoundUnit'] = CompoundUnit\n\n\nclass Dimensionless(UnitQuantity):\n\n    _primary_order = 100\n\n    def __init__(self, name, definition=None):\n        self._name = name\n\n        if definition is None:\n            definition = self\n        self._definition = definition\n\n        self._format_order = (self._primary_order, self._secondary_order)\n        self.__class__._secondary_order += 1\n\n        unit_registry[name] = self\n\n    def __reduce__(self):\n        \"\"\"\n        Return a tuple for pickling a UnitQuantity.\n        \"\"\"\n        return (\n            type(self),\n            (\n                self._name,\n            ),\n            self.__getstate__()\n        )\n\n    @property\n    def _dimensionality(self):\n        return Dimensionality()\n\ndimensionless = Dimensionless('dimensionless')\n\n\nclass UnitConstant(UnitQuantity):\n\n    _primary_order = 0\n\n    def __init__(\n        self, name, definition=None, symbol=None, u_symbol=None,\n        aliases=[], doc=None\n    ):\n        # we dont want to register constants in the unit registry\n        return\n\n\ndef set_default_units(\n    system=None, currency=None, current=None, information=None, length=None,\n    luminous_intensity=None, mass=None, substance=None, temperature=None,\n    time=None\n):\n    \"\"\"\n    Set the default units in which simplified quantities will be\n    expressed.\n\n    system sets the unit system, and can be \"SI\" or \"cgs\". All other\n    keyword arguments will accept either a string or a unit quantity.\n    An error will be raised if it is not possible to convert between\n    old and new defaults, so it is not possible to set \"kg\" as the\n    default unit for time.\n\n    If both system and individual defaults are given, the system\n    defaults will be applied first, followed by the individual ones.\n    \"\"\"\n    if system is not None:\n        system = system.lower()\n        try:\n            assert system in ('si', 'cgs')\n        except AssertionError:\n            raise ValueError('system must be \"SI\" or \"cgs\", got \"%s\"' % system)\n        if system == 'si':\n            UnitCurrent.set_default_unit('A')\n            UnitLength.set_default_unit('m')\n            UnitMass.set_default_unit('kg')\n        elif system == 'cgs':\n            UnitLength.set_default_unit('cm')\n            UnitMass.set_default_unit('g')\n        UnitLuminousIntensity.set_default_unit('cd')\n        UnitSubstance.set_default_unit('mol')\n        UnitTemperature.set_default_unit('degK')\n        UnitTime.set_default_unit('s')\n\n    UnitCurrency.set_default_unit(currency)\n    UnitCurrent.set_default_unit(current)\n    UnitInformation.set_default_unit(information)\n    UnitLength.set_default_unit(length)\n    UnitLuminousIntensity.set_default_unit(luminous_intensity)\n    UnitMass.set_default_unit(mass)\n    UnitSubstance.set_default_unit(substance)\n    UnitTemperature.set_default_unit(temperature)\n    UnitTime.set_default_unit(time)\n\n", "meta": {"hexsha": "9ecc0ebe0bf6fc497d2ee5104cdd50718d581722", "size": 13792, "ext": "py", "lang": "Python", "max_stars_repo_path": "quantities/unitquantity.py", "max_stars_repo_name": "burnpanck/python-quantities", "max_stars_repo_head_hexsha": "39d9b4a32af40dbee27fef3c24fc8322deca7b2e", "max_stars_repo_licenses": ["DOC"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-17T15:34:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T15:34:13.000Z", "max_issues_repo_path": "quantities/unitquantity.py", "max_issues_repo_name": "burnpanck/python-quantities", "max_issues_repo_head_hexsha": "39d9b4a32af40dbee27fef3c24fc8322deca7b2e", "max_issues_repo_licenses": ["DOC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quantities/unitquantity.py", "max_forks_repo_name": "burnpanck/python-quantities", "max_forks_repo_head_hexsha": "39d9b4a32af40dbee27fef3c24fc8322deca7b2e", "max_forks_repo_licenses": ["DOC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6254826255, "max_line_length": 79, "alphanum_fraction": 0.6170243619, "include": true, "reason": "import numpy", "num_tokens": 3165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.36296920551961687, "lm_q1q2_score": 0.18432006893085834}}
{"text": "\"\"\" Module for coadding spectra, and comparing customized and default data reduction\n\"\"\"\n\nfrom __future__ import (print_function, absolute_import, division, unicode_literals)\n\nimport numpy as np\nimport glob\nimport pdb\n\nfrom matplotlib import pyplot as plt\n\nfrom astropy.table import Table\nfrom astropy.io import fits\nimport linetools.spectra.xspectrum1d as xspec\n\nfrom pypeit.core import coadd1d as coadd1d\n\n\ndef flxwave(fname1, fname2s, xlim=(1900, 1950), ylim=None, norm=True, nseg=0, figsize=(6, 5)):\n    \"\"\" Plot flux vs wavelength for default and customized data reduction\n\n    Parameters\n    ----------\n    fname1 : str\n      a summ file that is output of the default data reduction\n    fname2s : list of str\n      summ files that are output ot customized data reductions.\n      It is needed that these files have spectra taken with the same optical element and central wavelenght as fname1.\n    xlim : float\n      displayed wavelength range\n    ylim : float\n      dislayed flux range\n    norm : bool\n      normalize fluxes to the same median flux\n    nseg : 0,1,2 (for segments A, B, C)\n      plot flux for segment nseg\n\n    Returns\n    -------\n\n    \"\"\"\n\n    # default data reduction\n    fnm = fname1\n    tbl = Table.read(fnm)\n    wave1 = tbl['WAVELENGTH'][nseg]\n    flx1 = tbl['FLUX'][nseg]\n    err1 = tbl['ERROR'][nseg]\n\n    plt.figure(figsize=figsize)\n    plt.plot(wave1, flx1, color='blue')\n    plt.plot(wave1, err1, '--', color='blue', label='previous')\n\n    # customized data reduction\n    colors = ['red', 'orange', 'limegreen']\n    for i in range(len(fname2s)):\n        fname2 = fname2s[i]\n        fnm = fname2\n        tbl = Table.read(fnm)\n        wave2 = tbl['WAVELENGTH'][nseg]\n        flx2 = tbl['FLUX'][nseg]\n        err2 = tbl['ERROR'][nseg]\n\n        # normalize to median flux\n        if norm:\n            sc = np.median(flx1) / np.median(flx2)\n        else:\n            sc = 1\n        print(sc)\n        flx2 = flx2 * sc\n        err2 = err2 * sc\n\n        # plot\n        plt.plot(wave2, flx2, color=colors[i])\n        plt.plot(wave2, err2, '--', color=colors[i], label='new ' + str(i+1))\n\n    plt.xlim(xlim)\n    if ylim is not None:\n        plt.ylim(ylim)\n    plt.xlabel('Wavelength')\n    plt.ylabel('Flux')\n    plt.legend()\n    plt.show()\n\n\n\n\n\n\ndef findsp(fldpth, verbose=True, emax=None):\n    \"\"\" Find all NUV and FUV spectra\n\n    Parameters\n    ----------\n    fldpth : str\n       path to the files\n    emax : int\n      read extensions 0, 1, ..., emax-1 of sum.fits files (corresponding to segments A,B,C)\n\n    Returns\n    -------\n    fuvsp : array of XSpectrum1D objects\n      FUV spectra\n    nuvsp : array of XSpectrum1D objects\n      NUV spectra\n\n    \"\"\"\n\n    # find all spectra\n    sumfiles = glob.glob(fldpth + '*sum.fits')\n\n    fuvsp = []\n    nuvsp = []\n    for i in range(len(sumfiles)):\n        spf = sumfiles[i]\n        hdu = fits.open(spf)\n        # FUV or NUV\n        det = hdu[0].header['DETECTOR']\n        hdu.close()\n\n        # read data\n        tbl = Table.read(spf)\n        jmax = len(tbl)\n        if (emax is not None):\n            if (emax < len(tbl)):\n                jmax = emax\n        for j in range(jmax):\n            wave = tbl['WAVELENGTH'][j]\n            flx = tbl['FLUX'][j]\n            err = tbl['ERROR'][j]\n\n            # append xspectrum\n            xsp = xspec.XSpectrum1D.from_tuple((wave, flx, err))\n            if det == 'NUV':\n                nuvsp.append(xsp)\n            elif det == 'FUV':\n                fuvsp.append(xsp)\n            else:\n                raise IOError(\"Detector not well defined in \", spf)\n\n    if verbose:\n        print('Number of NUV and FUV spectra: ', len(nuvsp), len(fuvsp))\n    nuvsp = np.asarray(nuvsp)\n    fuvsp = np.asarray(fuvsp)\n\n    return nuvsp, fuvsp\n\n\n\n\ndef snf1(wave,flux,error):\n    \"\"\" Calculate S/N per NUV resolution element = 3 pixels\n\n    Parameters\n    ----------\n    wave : list of floats\n      wavelength\n    flux : list of floats\n      flux\n    error : list of floats\n      error in flux\n    Returns\n    -------\n    sn : list of floats\n      S/N per resolution element, for each pixel\n\n    \"\"\"\n\n    sn = []\n    for i in np.arange(len(wave)):\n        if flux[i] == 0:\n            sn.append(0)\n        else:\n            s = 0\n            n = 0\n            for j in [-1,0,1]: # resolution element = 3 pixels\n                ij = i+j\n                if ij < 0:\n                    ij = 0\n                if ij >= len(flux):\n                    ij = len(flux)-1\n                s = s + flux[ij]\n                n = n + error[ij]**2\n            isn = s/(n**0.5)\n            sn.append(isn)\n    return sn\n\n\ndef snf2(wave,flux,error, R = 19000.):\n    \"\"\" Calculate S/N per resolution R (for FUV)\n\n    Parameters\n    ----------\n    wave : list of floats\n      wavelength\n    flux : list of floats\n      flux\n    error : list of floats\n      error in flux\n    Returns\n    -------\n    sn : list of floats\n      S/N per  R = 19000, for each pixel\n\n    \"\"\"\n\n    sn = []\n    for i in np.arange(len(wave)):\n        if flux[i] == 0:\n            sn.append(0)\n        else:\n            s = 0\n            n = 0\n            dlam = wave[i]/R\n            lam1 = wave[i] - dlam/2\n            lam2 = wave[i] + dlam/2\n            pix1 = np.argmin(abs(wave - lam1))\n            pix2 = np.argmin(abs(wave - lam2))\n            for j in (np.arange(pix2-pix1+1)+pix1):\n                s = s + flux[j]\n                n = n + error[j]**2\n            isn = s/(n**0.5)\n            sn.append(isn)\n    return sn\n\n\n\n\n\ndef findspsn(spectra,det,minsn=1,verbose=True):\n    \"\"\" Find all spectra, with median S/N per resolution element greater than minsn.\n        Spectra are taken with detector det.\n\n    Parameters\n    ----------\n    fldpth : str\n       path to the files\n    det : 'FUV' or 'NUV'\n      detector\n    minsn : float\n      minimum S/N per resolution element, default = 1\n\n    Returns\n    -------\n    spectrasn : array of XSpectrum1D objects\n      spectra with median S/N per resolution element greater than minsn\n\n    \"\"\"\n\n    spectrasn = []\n    for ispec in spectra:\n        # S/N\n        if det == 'NUV':\n            sn = snf1(ispec.wavelength,ispec.flux,ispec.sig)\n        elif det == 'FUV':\n            sn = snf2(ispec.wavelength,ispec.flux,ispec.sig)\n        else:\n            raise IOError(\"det (Detector) could be 'NUV' or 'FUV' only \")\n        medsn = np.median(sn)\n\n        # append\n        if medsn > minsn:\n            spectrasn.append(ispec)\n            if verbose:\n                print('S/N:',medsn)\n        else:\n            if verbose:\n                print('S/N low ',medsn)\n\n    if verbose:\n        print('Number of spectra with S/N > {:f}: {:f}'.format(minsn,len(spectrasn)))\n\n    spectrasn = np.asarray(spectrasn)\n\n    return spectrasn\n\n\n\n\ndef medsn(ispec, det):\n    \"\"\" Find S/N per resolution element for a given spectrum\n\n    Parameters\n    ----------\n    ispec : XSpectrum1D object\n      spectrum\n    det : 'NUV' or 'FUV'\n\n    Returns\n    -------\n    medsn : float\n      median S/N per resolution element\n\n    \"\"\"\n\n    # S/N\n    if det == 'NUV':\n        sn = snf1(ispec.wavelength, ispec.flux, ispec.sig)\n    elif det == 'FUV':\n        sn = snf2(ispec.wavelength, ispec.flux, ispec.sig)\n    else:\n        print('Det options are only NUV and FUV')\n        pdb.set_trace()\n\n    medsn = np.median(sn)\n\n    return medsn\n\n\n\n\ndef smoothsp(spects, det, snmin, outf=None):\n    \"\"\" Smooth noisy spectra, and return smoothed spectra with S/N per pixel higher than snmin\n\n    Parameters\n    ----------\n    spects : list of XSpectrum1D objects\n      spectra\n    det : 'NUV' or 'FUV'\n      'NUV' or 'FUV' detector\n    snmin : float\n      median S/N per pixel needs to be > snmin\n\n    Returns\n    -------\n    smspects : list of XSpectrum1D objects\n      smoothed spectra with S/N > snmin\n\n    \"\"\"\n\n    outpspec = []\n    print('Total number of spectra: ',len(spects))\n\n    # For each spectrum find median S/N, and boxcar smooth over ism pixels\n    # Return only spectra that have S/N > snmin\n    for ispec in spects:\n        print(ispec)\n\n        # S/N\n        imedsn = medsn(ispec, det)\n        print(imedsn)\n\n        # sm - lists of the number of pixels to smooth over\n        if det == 'NUV':\n            sm = [2,3]\n        elif det == 'FUV':\n            sm = [2,4,8,12,16,20]\n            # or define any other list with sm, e.g.:\n            # sm = [2,4,6,8,10,12,14,16,18,20]\n        else:\n            raise IOError(\"Detector could be 'NUV' or 'FUV' only \")\n\n        # smooth over ism pixels, until the spectrum has S/N > snmin\n        if imedsn > snmin:\n            outpspec.append(ispec)\n        else:\n            for ism in sm:\n                ispecsm = ispec.box_smooth(ism)\n                imedsn = medsn(ispecsm, det)\n                print(ism,imedsn)\n                if imedsn > snmin:\n                    outpspec.append(ispecsm)\n                    print('Smoothing with {:f} pixels'.format(ism))\n                    break\n            if imedsn <= snmin:\n                outpspec.append(ispecsm)\n                print('Smoothing with {:f} pixels. S/N still low.'.format(ism))\n\n    if outf is not None:\n        outpspec[0].write(outf)\n\n    return outpspec\n\n\n\ndef binsp(spf,kbin = 3, outf=None):\n    \"\"\" Bin spectrum\n\n        Parameters\n        ----------\n        spf : file with a XSpectrum1D object\n          input spectrum\n        kbin : int\n          number of pixels to bin\n        outf : str\n          output file in which the binned spectrum will be written\n\n        Returns\n        -------\n        xsp2 : XSpectrum1D object\n          binned spectrum\n\n        \"\"\"\n\n    # read spectrum from the file\n    xsp = xspec.XSpectrum1D.from_file(spf)\n    n = len(xsp.wavelength)\n    wave = xsp.wavelength\n    flx = xsp.flux\n    sig = xsp.sig\n\n    # lists with binned wavelength, flux, error in flux\n    waveb = []\n    flxb = []\n    sigb = []\n\n    # bin\n    for j in range(int(n / kbin)):\n        i = kbin * j\n        waveb.append(np.mean(wave[i:i + kbin].value)) # [angstrom]\n        flxb.append(np.mean(flx[i:i + kbin].value))  # [erg /s /cm**2 /angstrom]\n        isigb = np.sum((sig[i:i + kbin].value)**2)\n        isigb = (isigb**0.5)/kbin\n        sigb.append(isigb)\n\n    # output spectrum\n    waveb = np.asarray(waveb)\n    flxb = np.asarray(flxb)\n    sigb = np.asarray(sigb)\n    xsp2 = xspec.XSpectrum1D.from_tuple((waveb, flxb, sigb))\n\n    # write\n    if outf is not None:\n        xsp2.write(outf)\n\n    return xsp2\n\n\ndef coaddspectra(splist,plotsp=True,outf=None,sn_smooth_npix=10):\n    \"\"\"  Coadd spectra\n\n    Parameters\n    ----------\n    splist : list of XSpectrum1D objects\n        List of spectra to coadd\n    plotsp : bool\n        If True, plot the coadded spectrum\n    outf : str\n        Output file\n    sn_smooth_npix : float\n        Parameter in coadd1d.combspec function that defines\n        number of pixels to median filter by when computing S/N used to decide how to scale and weight spectra\n\n    Returns\n    -------\n    sp : XSpectrum1D\n        A spectrum that represents coadded spectra from the splist list\n\n    \"\"\"\n    waves = []\n    fluxes = []\n    ivars = []\n    masks = []\n\n    for isp in splist:\n        waves.append(isp.wavelength)\n        fluxes.append(isp.flux)\n        ivars.append(1. / (isp.sig) ** 2.)\n        imask = np.repeat(True, len(isp.flux))\n        j = np.where((isp.flux == 0) & (isp.sig == 0))[0]\n        imask[j] = False\n        masks.append(imask)\n\n    waves = np.ndarray.transpose(np.asarray(waves))\n    fluxes = np.ndarray.transpose(np.asarray(fluxes))\n    ivars = np.ndarray.transpose(np.asarray(ivars))\n    masks = np.ndarray.transpose(np.asarray(masks))\n\n    wave_stack, flux_stack, ivar_stack, mask_stack = coadd1d.combspec(\n        waves, fluxes, ivars, masks, sn_smooth_npix, show=plotsp)\n\n    ii = np.where(wave_stack > 0)[0]\n    coadded_waves = wave_stack[ii]\n    coadded_fluxes = flux_stack[ii]\n    coadded_sigs = 1 / (np.sqrt(ivar_stack[ii]))\n\n    # write and return the spectrum\n    sp = xspec.XSpectrum1D(coadded_waves, coadded_fluxes, coadded_sigs)\n\n    if outf is not None:\n        sp.write_to_fits(outf)\n\n    return sp\n\n\n\n", "meta": {"hexsha": "784a6d9bb02f1b8d97f13ddafe8581da873f44ab", "size": 12080, "ext": "py", "lang": "Python", "max_stars_repo_path": "cosredux/coadding.py", "max_stars_repo_name": "marijana777/COS_REDUX", "max_stars_repo_head_hexsha": "03acd7f5f41bd619d38ad5996972d24d39b0844f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-03-15T14:07:39.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-15T14:07:39.000Z", "max_issues_repo_path": "cosredux/coadding.py", "max_issues_repo_name": "marijana777/COS_REDUX", "max_issues_repo_head_hexsha": "03acd7f5f41bd619d38ad5996972d24d39b0844f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-11-11T19:50:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-10T08:16:01.000Z", "max_forks_repo_path": "cosredux/coadding.py", "max_forks_repo_name": "marijana777/COS_REDUX", "max_forks_repo_head_hexsha": "03acd7f5f41bd619d38ad5996972d24d39b0844f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-05T04:54:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-05T04:54:37.000Z", "avg_line_length": 24.8049281314, "max_line_length": 118, "alphanum_fraction": 0.5514900662, "include": true, "reason": "import numpy,from astropy", "num_tokens": 3364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.1843200689308583}}
{"text": "# Copyright 2021 United States Government as represented by the Administrator of the National Aeronautics and Space\n# Administration.  No copyright is claimed in the United States under Title 17, U.S. Code. All Other Rights Reserved.\n\n\nr\"\"\"\nThis module provides a subclass of the :class:`.OpNav` class for performing stellar OpNav and camera calibration.\n\nInterface Description\n---------------------\n\nIn GIANT, calibration refers primarily to the process of estimating a model to map points in the 3D\nworld to the observed points in a 2D image.  This is done by estimating both a geometric\n:mod:`camera model <.camera_models>` along with an optional pointing alignment between the camera frame and the base\nframe the knowledge of the camera attitude is tied to (for instance the spacecraft bus frame).  For both of these, we\nuse observations of stars to get highly accurate models.\n\nThe :class:`Calibration` class is the main interface for performing calibration in GIANT, and in general is all the user\nwill need to interact with.  It is a subclass of the :class:`.StellarOpNav` class and as such provides a very similar\ninterface with only a few additional features. It provides direct access to the :class:`.ImageProcessing`,\n:class:`.StarID`, :mod:`.stellar_opnav.estimators`, and :mod:`.calibration.estimators` objects and automatically\npreforms the required data transfer between the objects for you.  To begin you simply provide the :class:`.StellarOpNav`\nconstructor a :class:`.Camera` instance, either a :class:`.ImageProcessing` instance or the keyword arguments to create\none, a :class:`.StarID` instance or the keyword arguments to creation one, the attitude estimation object you wish to\nuse to perform the attitude estimation, the static alignment estimation object you wish to use to perform the static\nalignment estimation, the temperature dependent alignment estimation object you wish to use to perform the temperature\ndependent alignment, and the calibration estimation object you wish to use to perform the calibration. You can then use\nthe :class:`Calibration` instance to perform all of the aspects of stellar OpNav and calibration with never having to\ninteract with the internal objects again.\n\nFor example, we could do something like the following (from the directory containing ``sample_data``):\n\n    >>> import pickle\n    >>> from giant.calibration import Calibration\n    >>> from giant.rotations import Rotation\n    >>> with open('sample_data/camera.pickle', 'rb') as ifile:\n    ...     camera = pickle.load(ifile)\n    >>> # Returns the identity to signify the base frame is the inertial frame\n    >>> def base_frame(*args):\n    ...     return Rotation([0, 0, 0, 1])\n    >>> cal = Calibration(camera, alignment_base_frame_func=base_frame)\n    >>> cal.id_stars()  # id the stars for each image\n    >>> cal.sid_summary()  # print out a summary of the star identification success for each image\n    >>> cal.estimate_attitude()  # estimate an updated attitude for each image\n    >>> cal.estimate_calibration()  # estimate an updated camera model\n    >>> cal.calib_summary()  # print out a summary of the star identification success for each image\n    >>> cal.estimate_static_alignment()  # estimate the alignment between the camera frame and hte base frame\n    >>> cal.estimate_temperature_dependent_alignment()  # estimate the temperature dependent alignment\n\nFor a more general description of the steps needed to perform calibration, refer to the :mod:`.calibration` package.\nFor a more in-depth examination of the :class:`Calibration` class see the following API Reference.\n\"\"\"\n\nimport warnings\n\nfrom copy import deepcopy\n\nfrom typing import Optional, Sequence, Callable\n\nimport numpy as np\n\nfrom . import estimators as est\nfrom ..stellar_opnav.stellar_class import StellarOpNav\nfrom ..image_processing import ImageProcessing\nfrom ..stellar_opnav.star_identification import StarID\nfrom ..stellar_opnav import estimators as sopnavest\nfrom ..camera import Camera\nfrom ..rotations import Rotation\n\nfrom .._typing import NONEARRAY, SCALAR_OR_ARRAY\n\n\ndef _print_lr(labels: Sequence, values: np.ndarray):\n    \"\"\"\n    This pretty prints the lower left triangle of a matrix with labels.\n\n    This is used to print covariance and correlation matrices.\n\n    :param labels: The labels for each row/column of the matrix\n    :param values: The matrix to print\n    \"\"\"\n\n    # get the maximum length of the labels, with a minimum size of 10\n    max_label = max(max(map(len, labels)), 10)\n\n    # make the label format string based on the maximum label length\n    label_format = '{:<' + str(max_label) + 's}'\n\n    # make the value format string based on the maximum label length\n    value_format = '{:>' + str(max_label) + '.' + str(max_label-7) + 'e}'\n\n    # loop through the rows\n    for rind, rlabel in enumerate(labels):\n        # print the label format at the beginning of each new row.  Don't use a new line after\n        print(label_format.format(rlabel), end='  ')\n        # loop through the columns\n        for cind, clabel in enumerate(labels):\n            # skip the upper right triangle\n            if cind > rind:\n                print('\\n', end='')\n                break\n            # print out the value using the format string.  Don't use a new line after\n            print(value_format.format(values[rind, cind]), end='  ')\n\n    # print out a space to get the column labels in the right place\n    print('\\n' + label_format.format(''), end='')\n\n    # change the label format to be right aligned\n    label_format = label_format.replace('<', '>')\n\n    # print out a row of column labels\n    for clabel in labels:\n\n        print(label_format.format(clabel), end='  ')\n\n    # print a new line\n    print('')\n\n    return max_label\n\n\nclass Calibration(StellarOpNav):\n    \"\"\"\n    This class serves as the main user interface for performing geometric camera calibration and camera frame attitude\n    alignment.\n\n    The class acts as a container for the :class:`.Camera`, :class:`.ImageProcessing`, and\n    :mod:`.stellar_opnav.estimators`, :mod:`.calibration.estimators` objects and also passes the correct and up-to-date\n    data from one object to the other. In general, this class will be the exclusive interface to the mentioned objects\n    and models for the user.\n\n    This class provides a number of features that make doing stellar OpNav and camera calibration/alignment easy.  The\n    first is it provides aliases to the image processing, star id, attitude estimation, calibration estimation, and\n    alignment estimation objects. These aliases make it easy to quickly change/update the various tuning parameters that\n    are necessary to make star identification and calibration a success. In addition to providing convenient access to\n    the underlying settings, some of these aliases also update internal flags that specify whether individual images\n    need to be reprocessed, saving computation time when you're trying to find the best tuning.\n\n    This class also provides simple methods for performing star identification, attitude estimation, camera calibration,\n    and aligment estimation after you have set the tuning parameters. These methods (:meth:`id_stars`,\n    :meth:`sid_summary`, :meth:`estimate_attitude`, :meth:`estimate_calibration`, :meth:`calib_summary`,\n    :meth:`estimate_static_alignment`, and :meth:`estimate_temperature_dependent_alignment`) combine all of the\n    required steps into a few simple calls, and pass the resulting data from one object to the next. They also store off\n    the results of the star identification in the :attr:`queried_catalogue_star_records`,\n    :attr:`queried_catalogue_image_points`, :attr:`queried_catalogue_unit_vectors`, :attr:`ip_extracted_image_points`,\n    :attr:`ip_image_illums`, :attr:`ip_psfs`, :attr:`ip_stats`, :attr:`ip_snrs`,\n    :attr:`unmatched_catalogue_image_points`, :attr:`unmatched_image_illums`,\n    :attr:`unmatched_psfs`, :attr:`unmatched_stats`, :attr:`unmatched_snrs`\n    :attr:`unmatched_catalogue_star_records`,\n    :attr:`unmatched_catalogue_unit_vectors`,\n    :attr:`unmatched_extracted_image_points`,\n    :attr:`matched_catalogue_image_points`, :attr:`matched_image_illums`,\n    :attr:`matched_psfs`, :attr:`matched_stats`, :attr:`matched_snrs`\n    :attr:`matched_catalogue_star_records`,\n    :attr:`matched_catalogue_unit_vectors_inertial`,\n    :attr:`matched_catalogue_unit_vectors_camera`, and\n    :attr:`matched_extracted_image_points` attributes, enabling more advanced analysis to be performed external to the\n    class.\n\n    This class stores the updated attitude solutions in the image objects themselves, allowing you to directly\n    pass your images from stellar OpNav to the :mod:`.relative_opnav` routines with updated attitude solutions. It also\n    stores the estimated camera model in the original camera model itself, and store the estimated alignments in the\n    :attr:`static_alignment` and :attr:`temperature_dependent_alignment` attributes. Finally, this class\n    respects the :attr:`.image_mask` attribute of the :class:`.Camera` object, only considering images that are\n    currently turned on.\n\n    When initializing this class, most of the initial options can be set using the ``*_kwargs`` inputs with\n    dictionaries specifying the keyword arguments and values. Alternatively, you can provide already initialized\n    instances of the :class:`.ImageProcessing`, :class:`.AttitudeEstimator`, :class:`.StarID`,\n    :class:`.CalibrationEstimator`, :class:`.StaticAlignmentEstimator`, or\n    :class:`.TemperatureDependentAlignmentEstimator` classes or subclasses\n    if you want a little more control.  You should see the documentation for these classes for more details on what you\n    can do with them.\n    \"\"\"\n\n    def __init__(self, camera: Camera, use_weights: bool = False,\n                 image_processing: Optional[ImageProcessing] = None, image_processing_kwargs: Optional[dict] = None,\n                 star_id: Optional[StarID] = None, star_id_kwargs: Optional[dict] = None,\n                 alignment_base_frame_func: Optional[Callable] = None,\n                 attitude_estimator: Optional[sopnavest.AttitudeEstimator] = None,\n                 attitude_estimator_kwargs: Optional[dict] = None,\n                 static_alignment_estimator: Optional[est.StaticAlignmentEstimator] = None,\n                 static_alignment_estimator_kwargs: Optional[dict] = None,\n                 temperature_dependent_alignment_estimator: Optional[est.TemperatureDependentAlignmentEstimator] = None,\n                 temperature_dependent_alignment_estimator_kwargs: Optional[dict] = None,\n                 calibration_estimator: Optional[est.CalibrationEstimator] = None,\n                 calibration_estimator_kwargs: Optional[dict] = None):\n        \"\"\"\n        :param camera: The :class:`.Camera` object containing the camera model and images to be utilized\n        :param use_weights: A flag specifying whether to use weighted estimation for attitude, alignment, and\n                            calibration\n        :param alignment_base_frame_func: A callable object which returns the orientation of the base frame with respect\n                                          to the inertial frame the alignment of the camera frame is to be done with\n                                          respect to for a given date.\n        :param image_processing: An already initialized instance of :class:`.ImageProcessing` (or a subclass).  If not\n                                 ``None`` then ``image_processing_kwargs`` are ignored.\n        :param image_processing_kwargs: The keyword arguments to pass to the :class:`.ImageProcessing` class\n                                        constructor.  These are ignored if argument ``image_processing`` is not ``None``\n        :param star_id: An already initialized instance of :class:`.StarID` (or a subclass).  If not\n                        ``None`` then ``star_id_kwargs`` are ignored.\n        :param star_id_kwargs:  The keyword arguments to pass to the :class:`.StarID` class constructor as\n                                a dictionary.  These are ignored if argument ``star_id`` is not ``None``.\n        :param attitude_estimator: An already initialized instance of :class:`.AttitudeEstimator` (or a subclass).  If\n                                   not ``None`` then ``attitude_estimator_kwargs`` are ignored.\n        :param attitude_estimator_kwargs: The keyword arguments to pass to the :class:`.DavenportQMethod`\n                                          constructor as a dictionary.  If argument ``attitude_estimator`` is not\n                                          ``None`` then this is ignored.\n        :param static_alignment_estimator: An already initialized instance of :class:`.StaticAlignmentEstimator` (or a\n                                           subclass).  If not ``None`` then ``static_alignment_estimator_kwargs`` are\n                                           ignored.\n        :param static_alignment_estimator_kwargs: The keyword arguments to pass to the\n                                                  :class:`.StaticAlignmentEstimator` constructor as a dictionary.  If\n                                                  argument ``static_alignment_estimator`` is not ``None`` then this is\n                                                  ignored.\n        :param temperature_dependent_alignment_estimator: An already initialized instance of\n                                                          :class:`.TemperatureDependentAlignmentEstimator` (or a\n                                                          subclass).  If not ``None`` then\n                                                          ``temperature_dependent_alignment_estimator_kwargs`` are\n                                                          ignored.\n        :param temperature_dependent_alignment_estimator_kwargs: The keyword arguments to pass to the\n                                                                 :class:`.TemperatureDependentAlignmentEstimator`\n                                                                 constructor as a dictionary.  If argument\n                                                                 ``temperature_dependent_alignment_estimator`` is not\n                                                                 ``None`` then this is ignored.\n        :param calibration_estimator: An already initialized instance of :class:`.CalibrationEstimator` (or a\n                                      subclass).  If not ``None`` then ``calibration_estimator_kwargs`` are ignored.\n        :param calibration_estimator_kwargs: The keyword arguments to pass to the :class:`.IterativeNonlinearLSTSQ`\n                                             constructor as a dictionary.  If argument ``static_alignment_estimator is\n                                             not ``None`` then this is ignored.\n        \"\"\"\n\n        # initialize the StellarOpNav super class\n        super().__init__(camera, use_weights=use_weights,\n                         image_processing=image_processing, image_processing_kwargs=image_processing_kwargs,\n                         star_id=star_id, star_id_kwargs=star_id_kwargs,\n                         attitude_estimator=attitude_estimator, attitude_estimator_kwargs=attitude_estimator_kwargs)\n\n        if calibration_estimator is None:\n            if calibration_estimator_kwargs is not None:\n                self._calibration_est = est.IterativeNonlinearLSTSQ(model=self._camera.model,\n                                                                    **calibration_estimator_kwargs)\n            else:\n                self._calibration_est = est.IterativeNonlinearLSTSQ(model=self._camera.model)\n        else:\n            self._calibration_est = calibration_estimator\n\n        self.alignment_base_frame_func = alignment_base_frame_func  # type: Optional[Callable]\n        \"\"\"\n        A callable object which returns the orientation of the base frame with respect  \n        to the inertial frame the alignment of the camera frame is to be done with      \n        respect to for a given date.                                                    \n        \n        This is used on calls to :meth:`estimate_static_alignment` and :meth`estimate_temperature_dependent_alignment` \n        to determine the base frame the alignment is being done with respect to.  Typically this returns something like \n        the spacecraft body frame with respect to the inertial frame (inertial to spacecraft body) or another camera \n        frame.\n        \"\"\"\n\n        if static_alignment_estimator is None:\n            if static_alignment_estimator_kwargs is not None:\n                self._static_alignment_est = est.StaticAlignmentEstimator(**static_alignment_estimator_kwargs)\n            else:\n                self._static_alignment_est = est.StaticAlignmentEstimator()\n        else:\n            self._static_alignment_est = static_alignment_estimator\n\n        self.static_alignment = None  # type: Optional[Rotation]\n        \"\"\"\n        The static alignment as a :class:`.Rotation` object.\n        \n        This will be none until the :meth:`estimate_static_alignment` method is called at which point it will contain \n        the estimated alignment.\n        \"\"\"\n\n        if temperature_dependent_alignment_estimator is None:\n            if temperature_dependent_alignment_estimator_kwargs is not None:\n                self._temperature_dependent_alignment_est = est.TemperatureDependentAlignmentEstimator(\n                    **temperature_dependent_alignment_estimator_kwargs\n                )\n            else:\n                self._temperature_dependent_alignment_est = est.TemperatureDependentAlignmentEstimator()\n        else:\n            self._temperature_dependent_alignment_est = temperature_dependent_alignment_estimator\n\n        self.temperature_dependent_alignment = None  # type: NONEARRAY\n        \"\"\"\n        The temperature dependent alignment as a 3x2 numpy array.\n\n        The temperature dependent alignment array is stored such that the first column is the\n        static offset for the alignment, the second column is the temperature dependent slope, and each row represents\n        the euler angle according to the requested order (so if the requested order is ``'xyx'`` then the rotation from\n        the base frame to the camera frame at temperature ``t`` can be computed using:\n\n            >>> from giant.rotations import euler_to_rotmat, Rotation\n            >>> import numpy as np\n            >>> temperature_dependent_alignment = np.arange(6).reshape(3, 2)  # temp array just to demonstrate\n            >>> t = -22.5  # temp temperature just to demonstrate\n            >>> angles =temperature_dependent_alignment@[1, t]\n            >>> order = 'xyx'\n            >>> rotation_base_to_camera = Rotation(euler_to_rotmat(angles, order))\n            \n        \"\"\"\n\n        self._initial_calibration_est = self._calibration_est.__class__\n        self._initial_calibration_est_kwargs = calibration_estimator_kwargs\n        self._initial_static_alignment_est = self._static_alignment_est.__class__\n        self._initial_static_alignment_est_kwargs = static_alignment_estimator_kwargs\n        self._initial_temperature_dependent_alignment_est = self._temperature_dependent_alignment_est.__class__\n        self._initial_temperature_dependent_alignment_est_kwargs = temperature_dependent_alignment_estimator_kwargs\n\n    # update the model setter to also update the sid model\n    @StellarOpNav.model.setter\n    def model(self, val):\n        # dispatch to the super setter\n        super().model.__set__(val)\n        self._calibration_est.model = val\n\n    @property\n    def calibration_estimator(self) -> est.CalibrationEstimator:\n        \"\"\"\n        The calibration estimator to use when estimating the geometric calibration\n\n        This should typically be a subclass of the :class:`.CalibrationEstimator` meta class.\n\n        See the :mod:`~.calibration.estimators` documentation for more details.\n        \"\"\"\n\n        return self._calibration_est\n\n    @calibration_estimator.setter\n    def calibration_estimator(self, val):\n        if isinstance(val, est.CalibrationEstimator):\n            self._calibration_est = val\n        else:\n            warnings.warn(\"The calibration_estimator object should probably subclass the CalibrationEstimator \"\n                          \"metaclass. We'll assume you know what you're doing for now, but see the \"\n                          \"calibration.estimator documentation for details\")\n\n            self._calibration_est = val\n\n    @property\n    def static_alignment_estimator(self) -> est.StaticAlignmentEstimator:\n        \"\"\"\n        The static alignment estimator to use when estimating the static alignment\n\n        This should typically be a subclass of the :class:`.StaticAlignmentEstimator` class.\n\n        See the :mod:`~.calibration.estimators` documentation for more details.\n        \"\"\"\n\n        return self._static_alignment_est\n\n    @static_alignment_estimator.setter\n    def static_alignment_estimator(self, val: est.StaticAlignmentEstimator):\n        if isinstance(val, est.StaticAlignmentEstimator):\n            self._static_alignment_est = val\n        else:\n            warnings.warn(\"The static alignment_estimator object should probably subclass the \"\n                          \"StaticAlignmentEstimator class. We'll assume you know what you're doing for \"\n                          \"now, but see the calibration.estimator documentation for details\")\n\n            self._static_alignment_est = val\n\n    @property\n    def temperature_dependent_alignment_estimator(self) -> est.TemperatureDependentAlignmentEstimator:\n        \"\"\"\n        The temperature_dependent_alignment estimator to use when estimating the temperature_dependent_alignment\n\n        This should typically be a subclass of the :class:`.TemperatureDependentAlignmentEstimator` class.\n\n        See the :mod:`~.calibration.estimators` documentation for more details.\n        \"\"\"\n\n        return self._temperature_dependent_alignment_est\n\n    @temperature_dependent_alignment_estimator.setter\n    def temperature_dependent_alignment_estimator(self, val: est.TemperatureDependentAlignmentEstimator):\n        if isinstance(val, est.StaticAlignmentEstimator):\n            self._temperature_dependent_alignment_est = val\n        else:\n            warnings.warn(\"The temperature_dependent_alignment_estimator object should probably subclass the \"\n                          \"TemperatureDependentAlignmentEstimator class. We'll assume you know what you're doing for \"\n                          \"now, but see the calibration.estimator documentation for details\")\n\n            self._temperature_dependent_alignment_est = val\n\n    # ____________________________________________________METHODS________________________________________________\n\n    def estimate_calibration(self) -> None:\n        \"\"\"\n        This method estimates an updated camera model using all stars identified in all images that are turned on.\n\n        For each turned on image in the :attr:`camera` attribute, this method provides the :attr:`calibration_estimator`\n        with the :attr:`matched_extracted_image_points`, the :attr:`matched_catalogue_unit_vectors_camera`, and\n        optionally the :attr:`matched_weights_picture` if :attr:`use_weights` is ``True``. The\n        :meth:`~.CalibrationEstimator.estimate` method is then called and the resulting updated camera model is stored\n        in the :attr:`model` attribute.  Finally, the updated camera model is used to update the following:\n\n        * :attr:`matched_catalogue_image_points`\n        * :attr:`queried_catalogue_image_points`\n        * :attr:`unmatched_catalogue_image_points`\n\n        For a more thorough description of the calibration estimation routines see the :mod:`.calibration.estimators`\n        documentation.\n\n        .. warning::\n            This method overwrites the camera model information in the :attr:`camera` attribute and\n            does not save old information anywhere.  If you want this information saved be sure to store it yourself.\n        \"\"\"\n        # reset things to make sure we don't mix information\n        self._calibration_est.reset()\n\n        # prepare the inputs\n        use_pois = [[[], []]]*len(self.camera.images)\n        use_vecs = [[[], [], []]]*len(self.camera.images)\n        big_weights = [[[], []]]*len(self.camera.images)\n        temperatures = [0]*len(self.camera.images)\n        for ind, image in self.camera:\n            pois = self._matched_extracted_image_points[ind]\n            if pois is not None:\n                use_pois[ind] = pois\n            vecs = self._matched_catalogue_unit_vectors_camera[ind]\n            if vecs is not None:\n                use_vecs[ind] = vecs\n            if self.use_weights:\n                weights = self._matched_weights_picture[ind]\n                if weights is not None:\n                    big_weights[ind] = weights\n\n            temperatures[ind] = image.temperature\n\n        # update the attributes for the calibration estimator\n        if self.use_weights:\n            big_weights = np.diag(np.concatenate(big_weights).ravel())\n            self._calibration_est.weighted_estimation = True\n            self._calibration_est.measurement_covariance = big_weights\n        else:\n            self._calibration_est.weighted_estimation = False\n\n        self._calibration_est.measurements = np.concatenate(use_pois, axis=1)\n\n        self._calibration_est.camera_frame_directions = use_vecs\n\n        self._calibration_est.temperatures = temperatures\n\n        self._calibration_est.model = self.model.copy()\n\n        # do the estimation\n        self._calibration_est.estimate()\n\n        # store the updated camera model\n        self._camera.model.overwrite(self._calibration_est.model)\n\n        # update the catalogue locations\n        self.reproject_stars()\n\n    def estimate_static_alignment(self) -> None:\n        \"\"\"\n        This method estimates a static (not temeprature dependent) alignment between a base frame and the camera frame\n        over multiple images.\n\n        This method uses the :attr:`alignment_base_frame_func` to retrieve the rotation from the inertial frame to the\n        base frame the alignment is to be done with respect to for each image time. The inertial matched catalogue unit\n        vectors are then rotated into the base frame. Then, the matched image points-of-interest are converted to unit\n        vectors in the camera frame. These 2 sets of unit vectors are then provided to the\n        :attr:`static_alignment_estimator` and its :meth:`~.StaticAlignmentEstimator.estimate` method is called to\n        estimate the alignment between the frames.  The resulting alignment is stored in the :attr:`static_alignment`\n        attribute.\n\n        Note that to do alignment, the base frame and the camera frame should generally be fixed with respect to one\n        another.  This means that you can't do alignment with respect to something like the inertial frame in general,\n        unless your camera is magically fixed with respect to the inertial frame.\n\n        Generally, this method should be called after you have estimated the geometric camera model, because the\n        geometric camera model is used to convert the observed pixel locations in the image to unit vectors in the\n        camera frame (using :meth:`~.CameraModel.pixels_to_unit`).\n\n        .. Note::\n            This method will attempt to account for misalignment estimated along with the camera model when performing\n            the estimation; however, this is not recommended. Instead, once you have performed your camera model\n            calibration, you should consider resetting the camera model misalignment to 0 and then calling\n            :meth:`estimate_attitude` before a call to this function.\n        \"\"\"\n\n        # prepare the inputs\n        base_uvecs = []\n        cam_uvecs = []\n\n        for ind, image in self.camera:\n            if self._matched_catalogue_unit_vectors_inertial[ind] is not None:\n\n                # rotate the inertial catalogue directions into the base frame\n                rot_inertial2base = self.alignment_base_frame_func(image.observation_date)\n\n                base_uvecs.append(np.matmul(rot_inertial2base.matrix,\n                                            self._matched_catalogue_unit_vectors_inertial[ind]))\n\n                # get the unit vectors in the camera frame using the camera model\n                cam_uvecs.append(self.model.pixels_to_unit(self._matched_extracted_image_points[ind],\n                                                           temperature=image.temperature, image=ind))\n\n        self._static_alignment_est.frame1_unit_vecs = base_uvecs\n        self._static_alignment_est.frame2_unit_vecs = cam_uvecs\n\n        # do the static alignment\n        self._static_alignment_est.estimate()\n\n        # store the results\n        self.static_alignment = self._static_alignment_est.alignment\n\n    def estimate_temperature_dependent_alignment(self) -> None:\n        \"\"\"\n        This method estimates a temperature dependent (not static) alignment between a base frame and the camera frame\n        over multiple images.\n\n        This method uses the :attr:`alignment_base_frame_func` to retrieve the rotation from the inertial frame to the\n        base frame the alignment is to be done with respect to for each image time. Then, the rotation from the\n        inertial frame to the camera frame is retrieved for each image from the\n        :attr:`.Image.rotation_inertial_to_camera` attribute for each image (which is updated by a call to\n        :meth:`estimate_attitude`).  These frame definitions are then provided to the\n        :attr:`temperature_dependent_alignment_estimator` whose\n        :meth:`~.TemperatureDependentAlignmentEstimator.estimate` method is then called to estimate the temperature\n        dependent alignment.  The estimated alignment is then stored as a 3x2 numpy array where the first column is the\n        static offset for the alignment, the second column is the temperature dependent slope, and each row represents\n        the euler angle according to the requested order (so if the requested order is ``'xyx'`` then the rotation from\n        the base frame to the camera frame at temperature ``t`` can be computed using:\n\n            >>> from giant.rotations import euler_to_rotmat, Rotation\n            >>> from giant.calibration.calibration_class import Calibration\n            >>> cal = Calibration()\n            >>> cal.estimate_temperature_dependent_alignment()\n            >>> t = -22.5\n            >>> angles = cal.temperature_dependent_alignment@[1, t]\n            >>> order = cal.temperature_dependent_alignment_estimator.order\n            >>> rotation_base_to_camera = Rotation(euler_to_rotmat(angles, order))\n\n        This example is obviously incomplete but gives the concept of how things could be used.\n\n        Note that to do alignment, the base frame and the camera frame should generally be fixed with respect to one\n        another (with the exception of small variations with temperature).  This means that you can't do alignment with\n        respect to something like the inertial frame in general, unless your camera is magically fixed with respect to\n        the inertial frame.\n\n        Generally, this method should be called after you have estimated the attitude for each image, because the\n        estimated image pointing is used to estimate the alignment.  As such, only images where there are successfully\n        matched stars are used in the estimation.\n\n        .. Note::\n            This method will attempt to account for misalignment estimated along with the camera model when performing\n            the estimation; however, this is not recommended. Instead, once you have performed your camera model\n            calibration, you should consider resetting the camera model misalignment to 0 and then calling\n            :meth:`estimate_attitude` before a call to this function.\n        \"\"\"\n\n        # prepare the inputs\n        base_frame_rotations = []\n        camera_frame_rotations = []\n        temperatures = []\n\n        for ind, image in self.camera:\n            # only consider images where we have matched stars\n            if self._matched_catalogue_unit_vectors_inertial[ind] is not None:\n\n                # rotate the inertial catalogue directions into the base frame\n                base_frame_rotations.append(self.alignment_base_frame_func(image.observation_date))\n\n                # get the unit vectors in the camera frame using the camera model\n                camera_rotation = image.rotation_inertial_to_camera\n                # handle the misalignment if it exists\n                if hasattr(self.camera.model, 'get_misalignment'):\n                    camera_rotation = self.camera.model.get_misalignment(ind)*camera_rotation\n\n                camera_frame_rotations.append(camera_rotation)\n\n                temperatures.append(image.temperature)\n\n        self._temperature_dependent_alignment_est.frame_1_rotations = base_frame_rotations\n        self._temperature_dependent_alignment_est.frame_2_rotations = camera_frame_rotations\n        self._temperature_dependent_alignment_est.temperatures = temperatures\n\n        # do the static alignment\n        self._temperature_dependent_alignment_est.estimate()\n\n        # store the results\n        self.temperature_dependent_alignment = np.array(\n            [[self._temperature_dependent_alignment_est.angle_m_offset,\n              self._temperature_dependent_alignment_est.angle_m_slope],\n             [self._temperature_dependent_alignment_est.angle_n_offset,\n              self._temperature_dependent_alignment_est.angle_n_slope],\n             [self._temperature_dependent_alignment_est.angle_p_offset,\n              self._temperature_dependent_alignment_est.angle_p_slope]\n             ]\n        )\n\n    def reset_calibration_estimator(self):\n        \"\"\"\n        This method resets the existing calibration estimator instance with a new instance using the initial\n        ``calibration_estimator_update`` argument passed to the constructor.\n\n        A new instance of the object is created, therefore there is no backwards reference whatsoever to the state\n        before a call to this method.\n        \"\"\"\n        if self._initial_calibration_est_kwargs is not None:\n            self._calibration_est = self._initial_calibration_est(self._camera.model,\n                                                                  **self._initial_calibration_est_kwargs)\n        else:\n            self._calibration_est = self._initial_calibration_est(self._camera.model)\n\n    def update_calibration_estimator(self, calibration_estimator_update: Optional[dict] = None):\n        \"\"\"\n        This method updates the attributes of the :attr:`calibration_estimator` attribute.\n\n        See the :mod:`.calibration.estimators` documentation for accepted attribute values.\n\n        If a supplied attribute is not found in the :attr:`calibration_estimator` attribute then this will print a\n        warning and ignore the attribute. Any attributes that are not supplied are left alone.\n\n        :param calibration_estimator_update: A dictionary of attribute->value pairs to update the\n                                             :attr:`calibration_estimator` attribute with\n        \"\"\"\n        if calibration_estimator_update is not None:\n            for key, val in calibration_estimator_update.items():\n                if hasattr(self._calibration_est, key):\n                    setattr(self._calibration_est, key, val)\n                else:\n                    warnings.warn(\"The attribute {0} was not found.\\n\"\n                                  \"Cannot update calibration estimation instance\".format(key))\n\n    def reset_static_alignment_estimator(self):\n        \"\"\"\n        This method replaces the existing static alignment estimator instance with a new instance\n        using the initial ``static_alignment_estimator_kwargs`` argument passed to the constructor.\n\n        A new instance of the object is created, therefore there is no backwards reference whatsoever to the state\n        before a call to this method.\n        \"\"\"\n        if self._initial_static_alignment_est_kwargs is not None:\n            self._static_alignment_est = self._initial_static_alignment_est(**self._initial_static_alignment_est_kwargs)\n        else:\n            self._static_alignment_est = self._initial_static_alignment_est()\n\n    def update_static_alignment_estimator(self, alignment_estimator_update: Optional[dict] = None):\n        \"\"\"\n        This method updates the attributes of the :attr:`static_alignment_estimator` attribute.\n\n        See the :mod:`.calibration.estimators` documentation for accepted attribute values.\n\n        If a supplied attribute is not found in the :attr:`static_alignment_estimator` attribute then this will print a\n        warning and ignore the attribute. Any attributes that are not supplied are left alone.\n\n        :param alignment_estimator_update: A dictionary of attribute->value pairs to update the\n                                           :attr:`static_alignment_estimator` attribute with\n        \"\"\"\n\n        if alignment_estimator_update is not None:\n            for key, val in alignment_estimator_update.items():\n                if hasattr(self._static_alignment_est, key):\n                    setattr(self._static_alignment_est, key, val)\n                else:\n                    warnings.warn(\"The attribute {0} was not found.\\n\"\n                                  \"Cannot update static alignment estimation instance\".format(key))\n\n    def reset_temperature_dependent_alignment_estimator(self):\n        \"\"\"\n        This method replaces the existing temperature_dependent_alignment estimator instance with a new instance\n        using the initial ``temperature_dependent_alignment_estimator_kwargs`` argument passed to the constructor.\n\n        A new instance of the object is created, therefore there is no backwards reference whatsoever to the state\n        before a call to this method.\n        \"\"\"\n        if self._initial_temperature_dependent_alignment_est_kwargs is not None:\n            self._temperature_dependent_alignment_est = self._initial_temperature_dependent_alignment_est(\n                **self._initial_temperature_dependent_alignment_est_kwargs\n            )\n        else:\n            self._temperature_dependent_alignment_est = self._initial_temperature_dependent_alignment_est()\n\n    def update_temperature_dependent_alignment_estimator(self,\n                                                         temperature_dependent_alignment_estimator_update:\n                                                         Optional[dict] = None):\n        \"\"\"\n        This method updates the attributes of the :attr:`temperature_dependent_alignment_estimator` attribute.\n\n        See the :mod:`.calibration.estimators` documentation for accepted attribute values.\n\n        If a supplied attribute is not found in the :attr:`temperature_dependent_alignment_estimator` attribute then \n        this will print a warning and ignore the attribute. Any attributes that are not supplied are left alone.\n\n        :param temperature_dependent_alignment_estimator_update: A dictionary of attribute->value pairs to update the\n                                                                 :attr:`temperature_dependent_alignment_estimator` \n                                                                 attribute with\n        \"\"\"\n\n        if temperature_dependent_alignment_estimator_update is not None:\n            for key, val in temperature_dependent_alignment_estimator_update.items():\n                if hasattr(self._temperature_dependent_alignment_est, key):\n                    setattr(self._temperature_dependent_alignment_est, key, val)\n                else:\n                    warnings.warn(\"The attribute {0} was not found.\\n\"\n                                  \"Cannot update temperature_dependent_alignment estimation instance\".format(key))\n\n    def reset_settings(self):\n        \"\"\"\n        This method resets all settings to their initially provided values (at class construction)\n\n        Specifically, the following are reset\n\n        * :attr:`star_id`\n        * :attr:`image_processing`\n        * :attr:`attitude_estimator`\n        * :attr:`calibration_estimator`\n        * :attr:`static_alignment_estimator`\n        * :attr:`temperature_dependent_alignment_estimator`\n\n        In each case, a new instance of the object is created supplying the corresponding ``_kwargs`` argument supplied\n        when this class what initialized.\n\n        This is simply a shortcut to calling the ``reset_XXX``` methods individually.\n        \"\"\"\n        self.reset_star_id()\n        self.reset_image_processing()\n        self.reset_attitude_estimator()\n        self.reset_calibration_estimator()\n        self.reset_static_alignment_estimator()\n        self.reset_temperature_dependent_alignment_estimator()\n\n    def update_settings(self, star_id_update: Optional[dict] = None,\n                        image_processing_update: Optional[dict] = None,\n                        attitude_estimator_update: Optional[dict] = None,\n                        calibration_estimator_update: Optional[dict] = None,\n                        static_alignment_estimator_update: Optional[dict] = None,\n                        temperature_dependent_alignment_estimator_update: Optional[dict] = None):\n        \"\"\"\n        This method updates all settings to their provided values\n\n        Specifically, the following are updated depending on the input\n\n        * :attr:`star_id`\n        * :attr:`image_processing`\n        * :attr:`attitude_estimator`\n        * :attr:`calibration_estimator`\n        * :attr:`static_alignment_estimator`\n\n        In each case, the existing instance is modified in place with the attributes provided.  Any attributes that are\n        not specified are left as is.\n\n        This is simply a shortcut to calling the ``update_XXX`` methods individually.\n\n        :param star_id_update: The updates to :attr:`star_id`.\n        :param attitude_estimator_update: The updates to :attr:`attitude_estimator`.\n        :param image_processing_update: The updates to :attr:`image_processing`.\n        :param calibration_estimator_update: The updates to :attr:`calibration_estimator`.\n        :param static_alignment_estimator_update: The updates to :attr:`static_alignment_estimator`.\n        :param temperature_dependent_alignment_estimator_update: The updates to\n                                                                 :attr:`temperature_dependent_alignment_estimator`.\n        \"\"\"\n        self.update_star_id(star_id_update)\n        self.update_image_processing(image_processing_update)\n        self.update_attitude_estimator(attitude_estimator_update)\n        self.update_calibration_estimator(calibration_estimator_update)\n        self.update_static_alignment_estimator(static_alignment_estimator_update)\n        self.update_temperature_dependent_alignment_estimator(temperature_dependent_alignment_estimator_update)\n\n    def calib_summary(self, measurement_covariance: Optional[SCALAR_OR_ARRAY] = None):\n        \"\"\"\n        This prints a summary of the results of calibration to the screen\n\n        The resulting summary displays the labeled covariance matrix, followed by the labeled correlation coefficients,\n        followed by the state parameters and their formal uncertainty.\n\n        One optional inputs can be used to specify the uncertainty on the measurements if weighted estimation wasn't\n        already used to ensure the post-fit covariance\n        has the proper scaling.\n\n        Note that if multiple misalignments were estimated in the calibration, only the first is printed in the\n        correlation and covariance matrices.  For all misalignments, the values are replaced with NaN.\n\n        :param measurement_covariance: The covariance for the measurements either as a nxn matrix or as a scalar.\n        \"\"\"\n\n        if measurement_covariance is not None:\n            self._calibration_est.weighted_estimation = True\n            self._calibration_est.measurement_covariance = measurement_covariance\n            covariance = self.calibration_estimator.postfit_covariance\n        else:\n            covariance = self.calibration_estimator.postfit_covariance\n\n        # get the uncertainty for each parameter\n        sigmas = np.sqrt(np.diag(covariance))\n\n        # compute the correlation coefficients\n        coefficients = covariance / np.outer(*[np.sqrt(np.diag(covariance))] * 2)\n\n        # get the labels for each element\n        labels = self.model.get_state_labels()  # type: list\n\n        # if misalignment is in labels we need to do some fancy manipulation\n        if 'misalignment' in labels:\n            labels.remove('misalignment')\n            labels.append('align_x')\n            labels.append('align_y')\n            labels.append('align_z')\n\n        # print the covariance matrix\n        print('Covariance:')\n        _print_lr(labels, covariance)\n\n        # print the correlation coefficient matrix and get the maximum label size\n        print('Correlation coefficients:')\n        max_label = _print_lr(labels, coefficients)\n\n        # build the format strings for the parameter/formal uncertainty pairs\n        label_format = '{:<' + str(max_label) + 's}'\n        number_format = '{:>' + str(max_label) + '.' + str(max_label - 7) + 'e}'\n        fmt = label_format + ' ' + number_format + ' ' + number_format\n        state_vector = self.model.state_vector\n        print('Parameter value and formal uncertainty:')\n        for ind, label in enumerate(labels):\n            if 'align' not in labels:\n                print(fmt.format(label, state_vector[ind], sigmas[ind]))\n            else:\n                print(fmt.format(label, np.nan, sigmas[ind]))\n\n    def limit_magnitude(self, min_magnitude: float, max_magnitude: float, in_place=False) -> 'Calibration':\n        \"\"\"\n        This method removes stars from the ``matched_...`` attributes that are not within the provided magnitude bounds.\n\n        This method should be used rarely, as you can typically achieve the same functionality by use the\n        :attr:`.StarID.max_magnitude` and :attr:`.StarID.min_magnitude` attributes before calling :meth:`id_stars`.  The\n        most typical use case for this method is when you have already completed a full calibration and you now either\n        want to filter out some of the stars for plotting purposes, or you want to filter out some of the stars to do an\n        alignment analysis, where it is generally better to use only well exposed stars since fewer are needed to\n        fully define the alignment.\n\n        When you use this method, by default it will edit and return a copy of the current instance to preserve the\n        current instance.  if you are using many images with many stars in them this can use a large amount of memory;\n        however, so you can optionally specify ``in_place=True`` to modify the current instance in place.  Note however\n        that this not a reversible operation (that is you cannot get back to the original state) so be cautious about\n        using this option.\n\n        :param min_magnitude: The minimum star magnitude to accept (recall that minimum magnitude limits the brightest\n                              stars)\n        :param max_magnitude: The maximum star magnitude to accept (recall that maximum magnitude limits the dimmest\n                              stars)\n        :param in_place: A flag specifying whether to work on a copy or the original\n        :return: The edited Calibration instance (either a copy or a reference)\n        \"\"\"\n\n        if in_place:\n            out = self\n        else:\n            out = deepcopy(self)\n\n        for ind, _ in out.camera:\n            # test which stars don't meet the requirements\n            mag_test = (out.matched_catalogue_star_records[ind].mag.values >= max_magnitude) | \\\n                       (out.matched_catalogue_star_records[ind].mag.values <= min_magnitude)\n\n            if mag_test.any():\n                indicies = np.argwhere(mag_test).ravel()\n\n                out.remove_matched_stars(ind, indicies)\n\n        return out\n", "meta": {"hexsha": "d9eadb8e6a191a95c2ad6c02cbd9fdc9de12f604", "size": 48384, "ext": "py", "lang": "Python", "max_stars_repo_path": "giant/calibration/calibration_class.py", "max_stars_repo_name": "nasa/giant", "max_stars_repo_head_hexsha": "1e939272d9a0ca533b4da400d132f854520f3adc", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-09-10T14:29:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T20:15:01.000Z", "max_issues_repo_path": "giant/calibration/calibration_class.py", "max_issues_repo_name": "nasa/giant", "max_issues_repo_head_hexsha": "1e939272d9a0ca533b4da400d132f854520f3adc", "max_issues_repo_licenses": ["NASA-1.3"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "giant/calibration/calibration_class.py", "max_forks_repo_name": "nasa/giant", "max_forks_repo_head_hexsha": "1e939272d9a0ca533b4da400d132f854520f3adc", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-10-01T18:39:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T08:53:08.000Z", "avg_line_length": 56.0, "max_line_length": 120, "alphanum_fraction": 0.6829530423, "include": true, "reason": "import numpy", "num_tokens": 9263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.1843200689308583}}
{"text": "# -*- coding: utf-8 -*-\n# Copyright (C) by\n# All rights reserved.\n\nfrom psutil import cpu_count\nimport shutil\nimport numpy as np\nimport os\nimport svmbir._utils as utils\n\nif os.environ.get('CLIB') =='CMD_LINE':\n    import svmbir.interface_py_c as ci\nelse:\n    import svmbir.interface_cy_c as ci\n\n__svmbir_lib_path = os.path.join(os.path.expanduser('~'), '.cache', 'svmbir')\n\ndef _svmbir_lib_path():\n    \"\"\"Returns the path to the cache directory used by svmbir\n    \"\"\"\n    return __svmbir_lib_path\n\n\ndef _clear_cache(svmbir_lib_path = __svmbir_lib_path):\n    \"\"\"Clears the cache files used by svmbir\n    \n    Args:\n        svmbir_lib_path (string): Path to svmbir cache directory. Defaults to __svmbir_lib_path variable\n    \"\"\"\n    shutil.rmtree(svmbir_lib_path)\n\ndef sino_sort(sino, angles, weights=None):\n    \"\"\" Sort sinogram views (and sinogram weights if provided) so that view angles are in monotonically increasing order on the interval :math:`[0,2\\pi)`.\n        This function can be used to preprocess the sinogram data so that svmbir reconstruction is faster.\n        The function may create additional arrays that increase memory usage.\n    \n    Args:\n        sino (ndarray): 3D numpy array of unsorted sinogram data with shape (num_views, num_slices, num_channels)\n        angles (ndarray): 1D unsorted array of view angles in radians.\n        weights (ndarray, optional): [Default=None] 3D unsorted array of weights with same shape as sino. \n    \n    Returns:\n        - A tuple (sino, angles) when weights=None\n        - A tuple (sino, angles, weights) if weights is not None.\n        \n        The arrays are sorted along the view axis so that they have monotone increasing view angles in the interval :math:`[0,2\\pi)`.\n    \"\"\" \n\n    # Wrap the view angles modulo 2pi and sort\n    angles = np.mod(angles, 2*np.pi)\n    sorted_indices = np.argsort(angles)\n\n    # Sort sino, angles, and weights (if any) to be in monotone increasing order\n    sino = np.array(sino)[sorted_indices]\n    sino = np.ascontiguousarray(sino) # ensure views are in sorted order in memory\n    angles = angles[sorted_indices]\n    angles = np.ascontiguousarray(angles)\n\n    if weights is None:\n        return sino, angles\n    else:\n        weights = np.array(weights)[sorted_indices]\n        weights = np.ascontiguousarray(weights)\n        return sino, angles, weights\n\n\ndef calc_weights(sino, weight_type ):\n    \"\"\"Computes the weights used in MBIR reconstruction.\n\n    Args:\n        sino (ndarray): 3D numpy array of sinogram data with shape (num_views,num_slices,num_channels)\n        weight_type (string):[Default=0] Type of noise model used for data.\n\n            If weight_type=\"unweighted\"        => weights = numpy.ones_like(sino)\n\n            If weight_type=\"transmission\"      => weights = numpy.exp(-sino)\n\n            If weight_type=\"transmission_root\" => weights = numpy.exp(-sino/2)\n\n            If weight_type=\"emission\"         => weights = 1/(sino + 0.1)\n\n    Returns:\n        ndarray: 3D numpy array of weights with same shape as sino.\n\n    Raises:\n        Exception: Description\n    \"\"\"\n    if weight_type == 'unweighted' :\n        weights = np.ones(sino.shape)\n    elif weight_type == 'transmission' :\n        weights = np.exp(-sino)\n    elif weight_type == 'transmission_root' :\n        weights = np.exp(-sino / 2)\n    elif weight_type == 'emission' :\n        weights = 1 / (sino + 0.1)\n    else :\n        raise Exception(\"calc_weights: undefined weight_type {}\".format(weight_type))\n\n    return weights\n\n\ndef auto_sigma_y(sino, weights, snr_db = 30.0, delta_pixel = 1.0, delta_channel = 1.0):\n    \"\"\"Computes the automatic value of ``sigma_y`` for use in MBIR reconstruction.\n\n    Args:\n        sino (ndarray):\n            3D numpy array of sinogram data with shape (num_views,num_slices,num_channels)\n        weights (ndarray):\n            3D numpy array of weights with same shape as sino.\n            The parameters weights should be the same values as used in svmbir reconstruction.\n        snr_db (float, optional):\n            [Default=30.0] Scalar value that controls assumed signal-to-noise ratio of the data in dB.\n        delta_pixel (float, optional):\n            [Default=1.0] Scalar value of pixel spacing in :math:`ALU`.\n        delta_channel (float, optional):\n            [Default=1.0] Scalar value of detector channel spacing in :math:`ALU`.\n\n\n    Returns:\n        ndarray: Automatic values of regularization parameter.\n    \"\"\"\n    # Compute indicator function for sinogram support\n    sino_indicator = _sino_indicator(sino)\n\n    # compute RMS value of sinogram excluding empty space\n    signal_rms = np.average(weights * sino ** 2, None, sino_indicator) ** 0.5\n\n    # convert snr to relative noise standard deviation\n    rel_noise_std = 10 ** (-snr_db / 20)\n\n    # compute sigma_y and scale by relative pixel and detector pitch\n    sigma_y = rel_noise_std * signal_rms * (delta_pixel / delta_channel) ** (0.5)\n\n    return sigma_y\n\ndef auto_sigma_x(sino, delta_channel = 1.0, sharpness = 0.0 ):\n    \"\"\"Computes the automatic value of ``sigma_x`` for use in MBIR reconstruction.\n\n    Args:\n        sino (ndarray):\n            3D numpy array of sinogram data with shape (num_views,num_slices,num_channels)\n        delta_channel (float, optional):\n            [Default=1.0] Scalar value of detector channel spacing in :math:`ALU`.\n        sharpness (float, optional):\n            [Default=0.0] Scalar value that controls level of sharpness.\n            ``sharpness=0.0`` is neutral; ``sharpness>0`` increases sharpness; ``sharpness<0`` reduces sharpness\n\n    Returns:\n        float: Automatic value of regularization parameter.\n    \"\"\"\n    return 0.2 * auto_sigma_prior(sino, delta_channel, sharpness)\n\n\ndef auto_sigma_p(sino, delta_channel = 1.0, sharpness = 0.0 ):\n    \"\"\"Computes the automatic value of ``sigma_p`` for use in proximal map estimation.\n\n    Args:\n        sino (ndarray):\n            3D numpy array of sinogram data with shape (num_views,num_slices,num_channels)\n        delta_channel (float, optional):\n            [Default=1.0] Scalar value of detector channel spacing in :math:`ALU`.\n        sharpness (float, optional):\n            [Default=0.0] Scalar value that controls level of sharpness.\n            ``sharpness=0.0`` is neutral; ``sharpness>0`` increases sharpness; ``sharpness<0`` reduces sharpness\n\n    Returns:\n        float: Automatic value of regularization parameter.\n    \"\"\"\n    return 1.0 * auto_sigma_prior(sino, delta_channel, sharpness)\n\ndef auto_sigma_prior(sino, delta_channel = 1.0, sharpness = 0.0 ):\n    \"\"\"Computes the automatic value of prior model regularization term for use in MBIR reconstruction or proximal map estimation. This subroutine is called by ``auto_sigma_x`` in MBIR reconstruction, or ``auto_sigma_p`` in proximal map estimation.\n\n    Args:\n        sino (ndarray):\n            3D numpy array of sinogram data with shape (num_views,num_slices,num_channels)\n        delta_channel (float, optional):\n            [Default=1.0] Scalar value of detector channel spacing in :math:`ALU`.\n        sharpness (float, optional):\n            [Default=0.0] Scalar value that controls level of sharpness.\n            ``sharpness=0.0`` is neutral; ``sharpness>0`` increases sharpness; ``sharpness<0`` reduces sharpness\n\n    Returns:\n        float: Automatic value of regularization parameter.\n    \"\"\"\n    (num_views, num_slices, num_channels) = sino.shape\n\n    # Compute indicator function for sinogram support\n    sino_indicator = _sino_indicator(sino)\n\n    # Compute a typical image value by dividing average sinogram value by a typical projection path length\n    typical_img_value = np.average(sino, weights=sino_indicator) / (num_channels * delta_channel)\n\n    # Compute sigma_p as the typical image value when sharpness==0\n    sigma_prior = (2 ** sharpness) * typical_img_value\n\n    return sigma_prior\n\n\ndef auto_num_rows(num_channels, delta_channel, delta_pixel):\n    \"\"\"Computes the automatic value of ``num_rows``.\n    \"\"\"\n    num_rows = int(np.ceil(num_channels * delta_channel / delta_pixel))\n    return num_rows\n\n\ndef auto_num_cols(num_channels, delta_channel, delta_pixel):\n    \"\"\"Computes the automatic value of ``num_cols``.\n    \"\"\"\n    num_cols = int(np.ceil(num_channels * delta_channel / delta_pixel))\n    return num_cols\n\n\ndef auto_roi_radius(delta_pixel, num_rows, num_cols):\n    \"\"\"Computes the automatic value of ``roi_radius``.\n       Chosen so that it inscribes the largest axis of the recon image.\n    \"\"\"\n    roi_radius = float(delta_pixel * max(num_rows, num_cols))/2.0\n    return roi_radius\n\n\ndef recon(sino, angles,\n          weights = None, weight_type = 'unweighted', init_image = 0.0, prox_image = None, init_proj = None,\n          num_rows = None, num_cols = None, roi_radius = None,\n          delta_channel = 1.0, delta_pixel = 1.0, center_offset = 0.0,\n          sigma_y = None, snr_db = 30.0, sigma_x = None, sigma_p = None, p = 1.2, q = 2.0, T = 1.0, b_interslice = 1.0,\n          sharpness = 0.0, positivity = True, max_resolutions = 0, stop_threshold = 0.02, max_iterations = 100,\n          num_threads = None, delete_temps = True, svmbir_lib_path = __svmbir_lib_path, object_name = 'object',\n          verbose = 1) :\n    \"\"\"recon(sino, angles, weights = None, weight_type = 'unweighted', init_image = 0.0, prox_image = None, init_proj = None, num_rows = None, num_cols = None, roi_radius = None, delta_channel = 1.0, delta_pixel = 1.0, center_offset = 0.0, sigma_y = None, snr_db = 30.0, sigma_x = None, p = 1.2, q = 2.0, T = 1.0, b_interslice = 1.0, sharpness = 1.0, positivity = True, max_resolutions = 0, stop_threshold = 0.02, max_iterations = 100, num_threads = None, delete_temps = True, svmbir_lib_path = '~/.cache/svmbir', object_name = 'object', verbose = 1)\n\n    Computes 3D parallel beam MBIR reconstruction using multi-resolution SVMBIR algorithm.\n\n    Args:\n        sino (ndarray): 3D sinogram array with shape (num_views, num_slices, num_channels)\n\n        angles (ndarray): 1D view angles array in radians.\n\n        weights (ndarray, optional): [Default=None] 3D weights array with same shape as sino.\n\n        weight_type (string, optional): [Default=\"unweighted\"] Type of noise model used for data.\n            If the ``weights`` array is not supplied, then the function ``svmbir.calc_weights`` is used to set weights using specified ``weight_type`` parameter.\n            Option \"unweighted\" corresponds to unweighted reconstruction;\n            Option \"transmission\" is the correct weighting for transmission CT with constant dosage;\n            Option \"transmission_root\" is commonly used with transmission CT data to improve image homogeneity;\n            Option \"emission\" is appropriate for emission CT data.\n\n        init_image (float, optional): [Default=0.0] Initial value of reconstruction image, specified by either a scalar value or a 3D numpy array with shape (num_slices,num_rows,num_cols).\n\n        prox_image (ndarray, optional): [Default=None] 3D proximal map input image.\n            If prox_image is supplied, then the proximal map prior model is used, and the qGGMRF parameters are ignored.\n\n        init_proj (None, optional): [Default=None] Initial value of forward projection of the init_image.\n            This can be used to reduce computation for the first iteration when using the proximal map option.\n\n        num_rows (int, optional): [Default=None] Integer number of rows in reconstructed image.\n            If None, automatically set.\n\n        num_cols (int, optional): [Default=None] Integer number of columns in reconstructed image.\n            If None, automatically set.\n\n        roi_radius (float, optional): [Default=None] Scalar value of radius of reconstruction in :math:`ALU`.\n            If None, automatically set with auto_roi_radius().\n            Pixels outside the radius roi_radius in the :math:`(x,y)` plane are disregarded in the reconstruction.\n\n        delta_channel (float, optional): [Default=1.0] Scalar value of detector channel spacing in :math:`ALU`.\n\n        delta_pixel (float, optional): [Default=1.0] Scalar value of the spacing between image pixels in the 2D slice plane in :math:`ALU`.\n\n        center_offset (float, optional): [Default=0.0] Scalar value of offset from center-of-rotation.\n\n        sigma_y (float, optional): [Default=None] Scalar value of noise standard deviation parameter.\n            If None, automatically set with auto_sigma_y.\n\n        snr_db (float, optional): [Default=30.0] Scalar value that controls assumed signal-to-noise ratio of the data in dB.\n            Ignored if sigma_y is not None.\n\n        sigma_x (float, optional): [Default=None] Scalar value :math:`>0` that specifies the qGGMRF scale parameter.\n            Ignored if prox_image is not None.\n            If None and prox_image is also None, automatically set with auto_sigma_x. Regularization should be controled with the ``sharpness`` parameter, but ``sigma_x`` can be set directly by expert users.\n        \n        sigma_p (float, optional): [Default=None] Scalar value :math:`>0` that specifies the proximal map parameter.\n            Ignored if prox_image is None.\n            If None and proximal image is not None, automatically set with auto_sigma_p. Regularization should be controled with the ``sharpness`` parameter, but ``sigma_p`` can be set directly by expert users.\n\n        p (float, optional): [Default=1.2] Scalar value in range :math:`[1,2]` that specifies the qGGMRF shape parameter.\n\n        q (float, optional): [Default=2.0] Scalar value in range :math:`[p,1]` that specifies the qGGMRF shape parameter.\n\n        T (float, optional): [Default=1.0] Scalar value :math:`>0` that specifies the qGGMRF threshold parameter.\n\n        b_interslice (float, optional): [Default=1.0] Scalar value :math:`>0` that specifies the interslice regularization.\n            The default value of 1.0 should be fine for most applications.\n            However, b_interslice can be increased to values :math:`>1` in order to increase regularization along the slice axis.\n\n        sharpness (float, optional):\n            [Default=0.0] Scalar value that controls level of sharpness.\n            ``sharpness=0.0`` is neutral; ``sharpness>0`` increases sharpness; ``sharpness<0`` reduces sharpness.\n            Ignored if ``sigma_x`` is not None in qGGMRF mode, or if ``sigma_p`` is not None in proximal map mode.\n\n        positivity (bool, optional): [Default=True] Boolean value that determines if positivity constraint is enforced. The positivity parameter defaults to True; however, it should be changed to False when used in applications that can generate negative image values.\n\n        max_resolutions (int, optional): [Default=0] Integer >=0 that specifies the maximum number of grid resolutions used to solve MBIR reconstruction problem.\n\n        stop_threshold (float, optional): [Default=0.02] Scalar valued stopping threshold in percent.\n            If stop_threshold=0.0, then run max iterations.\n\n        max_iterations (int, optional): [Default=100] Integer valued specifying the maximum number of iterations. The value of ``max_iterations`` may need to be increased for reconstructions with limited tilt angles or high regularization.\n\n        num_threads (int, optional): [Default=None] Number of compute threads requested when executed.\n            If None, num_threads is set to the number of cores in the system\n\n        delete_temps (bool, optional): [Default=True] Delete temporary files used in computation.\n\n        svmbir_lib_path (string, optional): [Default='~/.cache/svmbir'] Path to directory containing library of forward projection matrices.\n\n        object_name (string, optional): [Default='object'] Specifies filenames of cached files.\n            Can be changed suitably for running multiple instances of reconstructions.\n            Useful for building multi-process and multi-node functionality on top of svmbir.\n\n        verbose (int, optional): [Default=1] Possible values are {0,1,2}, where 0 is quiet, 1 prints minimal reconstruction progress information, and 2 prints the full information.\n\n    Returns:\n        3D numpy array: 3D reconstruction with shape (num_slices,num_rows,num_cols) in units of :math:`ALU^{-1}`.\n    \"\"\"\n\n    # If not specified, then set number of threads = to number of processors\n    if num_threads is None :\n        num_threads = cpu_count(logical=False)\n    os.environ['OMP_NUM_THREADS'] = str(num_threads)\n    os.environ['OMP_DYNAMIC'] = 'true'\n\n    # Test for valid sino and angles structure. If sino is 2D, make it 3D\n    angles = utils.test_args_angles(angles)\n    sino = utils.test_args_sino(sino,angles)\n    (num_views, num_slices, num_channels) = sino.shape\n\n    # Tests parameters for valid types and values; print warnings if necessary; and return default values.\n    num_rows, num_cols, delta_pixel, roi_radius, delta_channel, center_offset = utils.test_args_geom(num_rows, num_cols, delta_pixel, roi_radius, delta_channel, center_offset)\n    sharpness, positivity, max_resolutions, stop_threshold, max_iterations = utils.test_args_recon(sharpness, positivity, max_resolutions, stop_threshold, max_iterations)\n    init_image, prox_image, init_proj, weights, weight_type = utils.test_args_inits(init_image, prox_image, init_proj, weights, weight_type)\n    sigma_y, snr_db, sigma_x, sigma_p = utils.test_args_noise(sigma_y, snr_db, sigma_x, sigma_p)\n    p, q, T, b_interslice = utils.test_args_qggmrf(p, q, T, b_interslice)\n    num_threads, delete_temps, verbose = utils.test_args_sys(num_threads, delete_temps, verbose)\n\n    # Set automatic values of num_rows, num_cols, and roi_radius\n    if num_rows is None:\n        num_rows = auto_num_rows(num_channels, delta_channel, delta_pixel)\n    if num_cols is None:\n        num_cols = auto_num_cols(num_channels, delta_channel, delta_pixel)\n    if roi_radius is None:\n        roi_radius = auto_roi_radius(delta_pixel, num_rows, num_cols)\n\n    # Set automatic values for weights\n    if weights is None:\n        weights = calc_weights(sino, weight_type)\n\n    # Set automatic value of sigma_y\n    if sigma_y is None:\n        sigma_y = auto_sigma_y(sino, weights, snr_db, delta_pixel=delta_pixel, delta_channel=delta_channel)\n\n    # Set automatic value of sigma_x\n    # if qGGMRF mode, then set sigma_x either using the provided value by user, or with auto_sigma_x\n    if prox_image is None:\n        if sigma_x is None:\n            sigma_x = auto_sigma_x(sino, delta_channel, sharpness)\n    # if proximal map mode, then overwrite sigma_x with sigma_p\n    else:\n        if sigma_p is None:\n            sigma_p = auto_sigma_p(sino, delta_channel, sharpness)\n        sigma_x = sigma_p\n    reconstruction = ci.multires_recon(sino=sino, angles=angles, weights=weights, weight_type=weight_type,\n                                       init_image=init_image, prox_image=prox_image, init_proj=init_proj,\n                                       num_rows=num_rows, num_cols=num_cols, roi_radius=roi_radius,\n                                       delta_channel=delta_channel, delta_pixel=delta_pixel, center_offset=center_offset,\n                                       sigma_y=sigma_y, snr_db=snr_db, sigma_x=sigma_x, p=p, q=q, T=T, b_interslice=b_interslice,\n                                       sharpness=sharpness, positivity=positivity, max_resolutions=max_resolutions,\n                                       stop_threshold=stop_threshold, max_iterations=max_iterations, num_threads=num_threads,\n                                       delete_temps=delete_temps, svmbir_lib_path=svmbir_lib_path, object_name=object_name,\n                                       verbose=verbose)\n\n    return reconstruction\n\n\n\ndef project(image, angles, num_channels,\n            delta_channel = 1.0, delta_pixel = 1.0, center_offset = 0.0, roi_radius = None,\n            num_threads = None, svmbir_lib_path = __svmbir_lib_path, delete_temps = True, \n            object_name = 'object', verbose = 1):\n    \"\"\"project(image, angles, num_channels, delta_channel = 1.0, delta_pixel = 1.0, center_offset = 0.0, roi_radius = None, num_threads = None, svmbir_lib_path = '~/.cache/svmbir', delete_temps = True, object_name = 'object', verbose = 1)\n\n    Computes 3D parallel beam forward-projection.\n\n    Args:\n        image (ndarray):\n            3D numpy array of image being projected.\n            The image shape is (num_slices,num_rows,num_cols). The output will contain 'num_slices' projections.\n            Note the image is considered 0 outside the 'roi_radius' (disregarded pixels).\n        angles (ndarray):\n            1D numpy array of view angles in radians.\n            'angles[k]' is the angle in radians for view :math:`k`.\n        num_channels (int):\n            Number of sinogram channels.\n        delta_channel (float, optional):\n            [Default=1.0] Detector channel spacing in :math:`ALU`.\n        delta_pixel (float, optional):\n            [Default=1.0] Size of image pixels in the 2D slice plane in :math:`ALU`.\n        center_offset (float, optional):\n            [Default=0.0] Offset from center-of-rotation in 'fractional number of channels' units.\n        roi_radius (float, optional): [Default=None] Radius of relevant image region in :math:`ALU`.\n            Pixels outside the radius are disregarded in the forward projection.\n            If not given, the value is set with auto_roi_radius().\n        num_threads (int, optional): [Default=None] Number of compute threads requested when executed.\n            If None, num_threads is set to the number of cores in the system.\n        svmbir_lib_path (string, optional):\n            [Default='~/.cache/svmbir'] Path to directory containing library of projection matrices and temp files.\n        delete_temps (bool, optional):\n            [Default=True] Delete any temporary files generated during computation. Unused for cython version.\n        object_name (string, optional):\n            [Default='object'] Specifies base filename of temporary files. Unused for cython version.\n        verbose (int, optional): [Default=1] Level of printed status output. {0,1,2} Set to 0 for quiet mode.\n\n    Returns:\n        ndarray: 3D numpy array containing projection with shape (num_views, num_slices, num_channels).\n    \"\"\"\n\n    # Temporary check for argument order. From v0.2.4, order is project(image,angles,...)\n    if isinstance(image,np.ndarray) and isinstance(angles,np.ndarray) and (image.ndim < angles.ndim):\n        print(\"WARNING: Check the argument order svmbir.project(image,angles,...)\")\n        print(\"**This is the order definition as of svmbir v0.2.4\")\n        print(\"**Swapping and proceeding...\")\n        temp_id = image\n        image = angles\n        angles = temp_id\n\n    # validate input arguments\n    image = utils.test_args_image(image)\n    angles = utils.test_args_angles(angles)\n\n    if num_threads is None :\n        num_threads = cpu_count(logical=False)\n\n    os.environ['OMP_NUM_THREADS'] = str(num_threads)\n    os.environ['OMP_DYNAMIC'] = 'true'\n\n    num_slices = image.shape[0]\n    num_rows = image.shape[1]\n    num_cols = image.shape[2]\n    num_views = len(angles)\n\n    if roi_radius is None :\n        roi_radius = auto_roi_radius(delta_pixel, num_rows, num_cols)\n\n    paths, sinoparams, imgparams = ci._init_geometry(angles, center_offset=center_offset,\n                                                     num_channels=num_channels, num_views=num_views, num_slices=num_slices,\n                                                     num_rows=num_rows, num_cols=num_cols,\n                                                     delta_channel=delta_channel, delta_pixel=delta_pixel,\n                                                     roi_radius=roi_radius,\n                                                     svmbir_lib_path=svmbir_lib_path, object_name=object_name,\n                                                     verbose=verbose)\n\n    # Collect settings to pass to C\n    settings = dict()\n    settings['paths'] = paths\n    settings['imgparams'] = imgparams\n    settings['sinoparams'] = sinoparams\n    settings['verbose'] = verbose\n    settings['num_threads'] = num_threads\n    settings['delete_temps'] = delete_temps\n\n    # Do the projection\n    proj = ci.project(image, settings)\n\n    return proj\n\n\n\ndef backproject(sino, angles, num_rows=None, num_cols=None,\n            delta_channel = 1.0, delta_pixel = 1.0, center_offset = 0.0, roi_radius = None,\n            num_threads = None, svmbir_lib_path = __svmbir_lib_path, delete_temps = True, \n            object_name = 'object', verbose = 1):\n    \"\"\"backproject(sino, angles, num_rows = None, num_cols = None, delta_channel = 1.0, delta_pixel = 1.0, center_offset = 0.0, roi_radius = None, num_threads = None, svmbir_lib_path = '~/.cache/svmbir', delete_temps = True, object_name = 'object', verbose = 1)\n\n    Computes 3D parallel beam back-projection.\n\n    Args:\n        sino (ndarray):\n            3D numpy array of input sinogram with shape (num_views,num_slices,num_channels).\n        angles (ndarray):\n            1D numpy array of view angles in radians.\n            'angles[k]' is the angle in radians for view :math:`k`.\n        num_rows (int, optional):\n            [Default=num_channels] Integer number of output image rows.\n        num_cols (int, optional):\n            [Default=num_channels] Integer number of output image columns.\n        delta_channel (float, optional):\n            [Default=1.0] Detector channel spacing in :math:`ALU`.\n        delta_pixel (float, optional):\n            [Default=1.0] Size of image pixels in the 2D slice plane in :math:`ALU`.\n        center_offset (float, optional):\n            [Default=0.0] Offset from center-of-rotation in 'fractional number of channels' units.\n        roi_radius (float, optional): [Default=None] Radius of relevant image region in :math:`ALU`.\n            Pixels outside the radius are disregarded in the forward projection.\n            If not given, the value is set with auto_roi_radius().\n        num_threads (int, optional): [Default=None] Number of compute threads requested when executed.\n            If None, num_threads is set to the number of cores in the system\n        svmbir_lib_path (string, optional):\n            [Default='~/.cache/svmbir'] Path to directory containing library of projection matrices and temp files.\n        delete_temps (bool, optional):\n            [Default=True] Delete any temporary files generated during computation. Unused for cython version.\n        object_name (string, optional):\n            [Default='object'] Specifies base filename of temporary files. Unused for cython version.\n        verbose (int, optional): [Default=1] Level of printed status output. {0,1,2} Set to 0 for quiet mode.\n\n    Returns:\n        ndarray: 3D numpy array containing back projected image (num_slices,num_rows,num_cols).\n    \"\"\"\n\n    # validate input arguments\n    angles = utils.test_args_angles(angles)\n    sino = utils.test_args_sino(sino,angles)\n\n    if num_threads is None :\n        num_threads = cpu_count(logical=False)\n\n    os.environ['OMP_NUM_THREADS'] = str(num_threads)\n    os.environ['OMP_DYNAMIC'] = 'true'\n\n    num_views = sino.shape[0]\n    num_slices = sino.shape[1]\n    num_channels = sino.shape[2]\n\n    if num_views != len(angles):\n        raise Exception('svmbir.backproject(): angles and sinogram arrays have conflicting sizes')\n\n    if num_rows is None:\n        num_rows = num_channels\n    if num_cols is None:\n        num_cols = num_channels\n    if roi_radius is None:\n        roi_radius = auto_roi_radius(delta_pixel, num_rows, num_cols)\n\n    paths, sinoparams, imgparams = ci._init_geometry(angles, center_offset=center_offset,\n                                                     num_channels=num_channels, num_views=num_views, num_slices=num_slices,\n                                                     num_rows=num_rows, num_cols=num_cols,\n                                                     delta_channel=delta_channel, delta_pixel=delta_pixel,\n                                                     roi_radius=roi_radius,\n                                                     svmbir_lib_path=svmbir_lib_path, object_name=object_name,\n                                                     verbose=verbose)\n\n    # Collect settings to pass to C\n    settings = dict()\n    settings['paths'] = paths\n    settings['imgparams'] = imgparams\n    settings['sinoparams'] = sinoparams\n    settings['verbose'] = verbose\n    settings['num_threads'] = num_threads\n    settings['delete_temps'] = delete_temps\n\n    return ci.backproject(sino, settings)\n\n\ndef _sino_indicator(sino):\n    \"\"\"Computes a binary function that indicates the region of sinogram support.\n\n    Args:\n        sino (ndarray):\n            3D numpy array of sinogram data with shape (num_views,num_slices,num_channels)\n\n    Returns:\n        int8: A binary value: =1 within sinogram support; =0 outside sinogram support.\n    \"\"\"\n    indicator = np.int8(sino > 0.05 * np.mean(np.fabs(sino)))  # for excluding empty space from average\n    return indicator\n", "meta": {"hexsha": "e1b1e4787f40a15a8e674a940e764bc123777a00", "size": 29039, "ext": "py", "lang": "Python", "max_stars_repo_path": "svmbir.py", "max_stars_repo_name": "cabouman/sandbox", "max_stars_repo_head_hexsha": "8e198c09c91acaffaf75055e4d61f85d14983316", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-09-12T03:14:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T15:34:46.000Z", "max_issues_repo_path": "svmbir.py", "max_issues_repo_name": "cabouman/sandbox", "max_issues_repo_head_hexsha": "8e198c09c91acaffaf75055e4d61f85d14983316", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 117, "max_issues_repo_issues_event_min_datetime": "2020-07-24T20:13:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T16:10:05.000Z", "max_forks_repo_path": "svmbir.py", "max_forks_repo_name": "cabouman/sandbox", "max_forks_repo_head_hexsha": "8e198c09c91acaffaf75055e4d61f85d14983316", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2020-07-24T19:38:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-11T13:44:40.000Z", "avg_line_length": 50.5026086957, "max_line_length": 550, "alphanum_fraction": 0.6735424774, "include": true, "reason": "import numpy", "num_tokens": 6839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.18432006543154236}}
{"text": "##    _____  _____\n##   |  __ \\|  __ \\    AUTHOR: Pedro Rivero\n##   | |__) | |__) |   ---------------------------------\n##   |  ___/|  _  /    DATE: May 12, 2021\n##   | |    | | \\ \\    ---------------------------------\n##   |_|    |_|  \\_\\   https://github.com/pedrorrivero\n##\n\n## Copyright 2021 Pedro Rivero\n##\n## Licensed under the Apache License, Version 2.0 (the \"License\");\n## you may not use this file except in compliance with the License.\n## You may obtain a copy of the License at\n##\n## http://www.apache.org/licenses/LICENSE-2.0\n##\n## Unless required by applicable law or agreed to in writing, software\n## distributed under the License is distributed on an \"AS IS\" BASIS,\n## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n## See the License for the specific language governing permissions and\n## limitations under the License.\n\nfrom struct import pack, unpack\nfrom typing import Any, Callable, Final, Union\n\nfrom numpy import float64, uint32, uint64\nfrom randomgen import UserBitGenerator\n\nfrom .bit_cache import BitCache\nfrom .platforms import QuantumPlatform\nfrom .protocols import QuantumProtocol\n\n\n###############################################################################\n## QUANTUM BIT GENERATOR (FACADE)\n###############################################################################\nclass QuantumBitGenerator(UserBitGenerator):\n    def __init__(\n        self,\n        platform: QuantumPlatform,\n        protocol: QuantumProtocol,\n        ISRAW32: bool = False,\n    ) -> None:\n        self.platform: QuantumPlatform = platform\n        self.protocol: QuantumProtocol = protocol\n        self._ISRAW32: Final[bool] = ISRAW32\n        self._bitcache: BitCache = BitCache()\n        super().__init__(\n            bits=self.BITS,\n            next_raw=self._next_raw,\n            next_32=self._next_32,\n            next_64=self._next_64,\n            next_double=self._next_double,\n        )\n\n    ############################### PUBLIC API ###############################\n    @property\n    def BITS(self) -> int:\n        \"\"\"\n        Either 32 or 64. The number of bits output by NumPy's `random_raw()`\n        method. Final, it cannot be modified after instantiation through the\n        ISRAW32 parameter.\n        \"\"\"\n        return 32 if self._ISRAW32 else 64\n\n    @property\n    def platform(self) -> QuantumPlatform:\n        return self._platform\n\n    @platform.setter\n    def platform(self, p: QuantumPlatform) -> None:\n        self._platform = p\n\n    @property\n    def protocol(self) -> QuantumProtocol:\n        return self._protocol\n\n    @protocol.setter\n    def protocol(self, p: QuantumProtocol) -> None:\n        self._protocol = p\n\n    def dump_cache(self, flush: bool = False) -> str:\n        \"\"\"\n        Returns all the contents stored in the cache.\n\n        PARAMETERS\n        ----------\n        flush: bool\n            If `True` erase the cache after dumping.\n\n        RETURNS\n        -------\n        out: str\n            The bitstring stored in cache.\n        \"\"\"\n        bitstring: str = self._bitcache.dump()\n        if flush:\n            self._bitcache.flush()\n        return bitstring\n\n    def flush_cache(self) -> None:\n        \"\"\"\n        Erase the cache.\n\n        RETURNS\n        -------\n        out: bool\n            `True` if succeeds, `False` otherwise.\n        \"\"\"\n        self._bitcache.flush()\n\n    def load_cache(self, bitstring: str, flush: bool = False) -> None:\n        \"\"\"\n        Load cache contents from bitstring.\n\n        PARAMETERS\n        ----------\n        bitstring: str\n            The bitstring to load to cache.\n        flush: bool\n            If `True` erase cache before loading.\n\n        RETURNS\n        -------\n        out: bool\n            `True` if succeeds, `False` otherwise.\n\n        RAISES\n        ------\n        TypeError (push)\n            If input bitstring is not str\n        ValueError (push)\n            If input bitstring is not a valid bitstring\n        \"\"\"\n        if flush:\n            self._bitcache.flush()\n        self._bitcache.push(bitstring)\n\n    def random_bitstring(self, num_bits: int = 0) -> str:\n        \"\"\"\n        Returns a random bitstring of a given lenght. If less than one it\n        defaults to the raw number of bits for the instance QiskitBitGenerator\n        (i.e. 32 or 64).\n\n        PARAMETERS\n        ----------\n        num_bits: int\n            Number of bits to retrieve.\n\n        RETURNS\n        -------\n        out: str\n            Bitstring of lenght `num_bits`.\n        \"\"\"\n        if num_bits < 1:\n            num_bits = self.BITS\n        while self._bitcache.size < num_bits:\n            self._refill_cache()\n        return self._bitcache.pop(num_bits)\n\n    def random_double(self, n: float = 1) -> float:\n        \"\"\"\n        Returns a random double from a uniform distribution in the range\n        [0,n). Defaults to [0,1).\n\n        PARAMETERS\n        ----------\n        n: float\n            Size of the range [0,n) from which to draw the random number.\n\n        RETURNS\n        -------\n        out: float\n            Random float in the range [0,n).\n\n        COPYRIGHT NOTICE\n        ----------------\n        Source: https://github.com/ozanerhansha/qRNG\n        License: GNU GENERAL PUBLIC LICENSE VERSION 3\n        Changes:\n            - Add static type hints\n            - Limit range to [0,n) instead of [min,max) and add default\n            - Replace call to original get_random_int64\n        \"\"\"\n        unpacked = 0x3FF0000000000000 | self.random_uint(64) >> 12\n        packed = pack(\"Q\", unpacked)\n        value: float = unpack(\"d\", packed)[0] - 1.0\n        return value * n\n\n    def random_uint(self, num_bits: int = 0) -> int:\n        \"\"\"\n        Returns a random unsigned int of a given size in bits.\n\n        PARAMETERS\n        ----------\n        num_bits: int\n            Number of bits to retrieve. If less than one it defaults to the raw\n            number of bits for the instance QiskitBitGenerator (i.e. 32 or 64).\n\n        RETURNS\n        -------\n        out: int\n            Unsigned int of `num_bits` bits.\n        \"\"\"\n        if num_bits < 1:\n            num_bits = self.BITS\n        return int(self.random_bitstring(num_bits), 2)\n\n    ############################### PRIVATE API ###############################\n    def _refill_cache(self) -> None:\n        bitstring: str = self.platform.fetch_random_bits(self.protocol)\n        self._bitcache.push(bitstring)\n\n    ############################# NUMPY INTERFACE #############################\n    @property\n    def _next_raw(self) -> Callable[[Any], Union[uint32, uint64]]:\n        \"\"\"\n        A callable that returns either 64 or 32 random bits. It must accept\n        a single input which is a void pointer to a memory address.\n        \"\"\"\n        return self._next_32 if self._ISRAW32 else self._next_64\n\n    @property\n    def _next_32(self) -> Callable[[Any], uint32]:\n        \"\"\"\n        A callable with the same signature as as next_raw that always returns\n        a random numpy 32-bit unsigned int.\n        \"\"\"\n\n        def next_32(void_p: Any) -> uint32:\n            return uint32(self.random_uint(32))\n\n        return next_32\n\n    @property\n    def _next_64(self) -> Callable[[Any], uint64]:\n        \"\"\"\n        A callable with the same signature as as next_raw that always returns\n        a random numpy 64-bit unsigned int.\n        \"\"\"\n\n        def next_64(void_p: Any) -> uint64:\n            return uint64(self.random_uint(64))\n\n        return next_64\n\n    @property\n    def _next_double(self) -> Callable[[Any], float64]:\n        \"\"\"\n        A callable with the same signature as as next_raw that always return\n        a random double in [0,1).\n        \"\"\"\n\n        def next_double(void_p: Any) -> float64:\n            return float64(self.random_double(1))\n\n        return next_double\n", "meta": {"hexsha": "327d2ca8272b0cfc4ed7994264a0ce1491d1897c", "size": 7802, "ext": "py", "lang": "Python", "max_stars_repo_path": "qrand/quantum_bit_generator.py", "max_stars_repo_name": "gprs1809/qrand", "max_stars_repo_head_hexsha": "4113d1dc9cc87a50b4514fb20693ed2508ca8fdd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "qrand/quantum_bit_generator.py", "max_issues_repo_name": "gprs1809/qrand", "max_issues_repo_head_hexsha": "4113d1dc9cc87a50b4514fb20693ed2508ca8fdd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qrand/quantum_bit_generator.py", "max_forks_repo_name": "gprs1809/qrand", "max_forks_repo_head_hexsha": "4113d1dc9cc87a50b4514fb20693ed2508ca8fdd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-16T20:24:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-16T20:24:47.000Z", "avg_line_length": 30.2403100775, "max_line_length": 79, "alphanum_fraction": 0.5485772879, "include": true, "reason": "from numpy", "num_tokens": 1765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.1843200654315423}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nfrom __future__ import absolute_import, division, print_function\nimport copy\nimport numpy as np\nimport healpy as hp\nfrom scipy.interpolate import RegularGridInterpolator\nfrom scipy.ndimage.interpolation import map_coordinates\nfrom astropy.io import fits\nfrom astropy.wcs import WCS\nfrom astropy.table import Table\nfrom astropy.coordinates import SkyCoord\nfrom astropy.coordinates import Galactic, ICRS\nimport gammapy\nimport fermipy.utils as utils\nimport fermipy.wcs_utils as wcs_utils\nimport fermipy.hpx_utils as hpx_utils\nimport fermipy.fits_utils as fits_utils\nfrom fermipy.hpx_utils import HPX, HpxToWcsMapping\n\n\ndef coadd_maps(geom, maps, preserve_counts=True):\n    \"\"\"Coadd a sequence of `~gammapy.maps.Map` objects.\"\"\"\n\n    # FIXME: This functionality should be built into the Map.coadd method\n    map_out = gammapy.maps.Map.from_geom(geom)\n    for m in maps:\n        m_tmp = m\n        if isinstance(m, gammapy.maps.HpxNDMap):\n            if m.geom.order < map_out.geom.order:\n                factor = map_out.geom.nside // m.geom.nside\n                m_tmp = m.upsample(factor, preserve_counts=preserve_counts)\n        map_out.coadd(m_tmp)\n\n    return map_out\n\n\ndef make_coadd_map(maps, proj, shape, preserve_counts=True):\n\n    if isinstance(proj, WCS):\n        return make_coadd_wcs(maps, proj, shape)\n    elif isinstance(proj, HPX):\n        return make_coadd_hpx(maps, proj, shape, preserve_counts=preserve_counts)\n    else:\n        raise Exception(\"Can't co-add map of unknown type %s\" % type(proj))\n\n\ndef make_coadd_wcs(maps, wcs, shape):\n    data = np.zeros(shape)\n    axes = wcs_utils.wcs_to_axes(wcs, shape)\n\n    for m in maps:\n        c = wcs_utils.wcs_to_coords(m.wcs, m.counts.shape)\n        o = np.histogramdd(c.T, bins=axes[::-1], weights=np.ravel(m.counts))[0]\n        data += o\n\n    return Map(data, copy.deepcopy(wcs))\n\n\ndef make_coadd_hpx(maps, hpx, shape, preserve_counts=True):\n    data = np.zeros(shape)\n    axes = hpx_utils.hpx_to_axes(hpx, shape)\n    for m in maps:\n        if m.hpx.order != hpx.order:\n            m_copy = m.ud_grade(hpx.order, preserve_counts)\n        else:\n            m_copy = m\n        c = hpx_utils.hpx_to_coords(m_copy.hpx, m_copy.counts.shape)\n        o = np.histogramdd(c.T, bins=axes, weights=np.ravel(m_copy.counts))[0]\n        data += o\n    return HpxMap(data, copy.deepcopy(hpx))\n\n\ndef read_map_from_fits(fitsfile, extname=None):\n    \"\"\"\n    \"\"\"\n    proj, f, hdu = fits_utils.read_projection_from_fits(fitsfile, extname)\n    if isinstance(proj, WCS):\n        ebins = fits_utils.find_and_read_ebins(f)\n        m = Map(hdu.data, proj, ebins=ebins)\n    elif isinstance(proj, HPX):\n        m = HpxMap.create_from_hdu(hdu, proj.ebins)\n    else:\n        raise Exception(\"Did not recognize projection type %s\" % type(proj))\n    return m\n\n\nclass Map_Base(object):\n    \"\"\" Abstract representation of a 2D or 3D counts map.\"\"\"\n\n    def __init__(self, counts):\n        self._counts = counts\n\n    @property\n    def counts(self):\n        return self._counts\n\n    @property\n    def data(self):\n        return self._counts\n\n    @data.setter\n    def data(self, val):\n        if val.shape != self.data.shape:\n            raise Exception('Wrong shape.')\n        self._counts = val\n\n    def get_pixel_skydirs(self):\n        \"\"\"Get a list of sky coordinates for the centers of every pixel. \"\"\"\n        raise NotImplementedError(\"MapBase.get_pixel_skydirs()\")\n\n    def get_pixel_indices(self, lats, lons):\n        \"\"\"Return the indices in the flat array corresponding to a set of coordinates \"\"\"\n        raise NotImplementedError(\"MapBase.get_pixel_indices()\")\n\n    def sum_over_energy(self):\n        \"\"\"Reduce a counts cube to a counts map by summing over the energy planes \"\"\"\n        raise NotImplementedError(\"MapBase.sum_over_energy()\")\n\n    def get_map_values(self, lons, lats, ibin=None):\n        \"\"\"Return the map values corresponding to a set of coordinates. \"\"\"\n        raise NotImplementedError(\"MapBase.get_map_values()\")\n\n    def interpolate(self, lon, lat, egy=None):\n        \"\"\"Return the interpolated map values corresponding to a set of coordinates. \"\"\"\n        raise NotImplementedError(\"MapBase.interpolate()\")\n\n\nclass Map(Map_Base):\n    \"\"\" Representation of a 2D or 3D counts map using WCS. \"\"\"\n\n    def __init__(self, counts, wcs, ebins=None):\n        \"\"\"\n        Parameters\n        ----------\n        counts : `~numpy.ndarray`\n            Counts array in row-wise ordering (LON is first dimension).\n        \"\"\"\n        Map_Base.__init__(self, counts)\n        self._wcs = wcs\n\n        self._npix = counts.shape[::-1]\n\n        if len(self._npix) == 3:\n            self._xindex = 2\n            self._yindex = 1\n        elif len(self._npix) == 2:\n            self._xindex = 1\n            self._yindex = 0\n        else:\n            raise Exception('Wrong number of dimensions for Map object.')\n\n        # if len(self._npix) != 3 and len(self._npix) != 2:\n        #    raise Exception('Wrong number of dimensions for Map object.')\n\n        self._width = np.array([np.abs(self.wcs.wcs.cdelt[0]) * self.npix[0],\n                                np.abs(self.wcs.wcs.cdelt[1]) * self.npix[1]])\n        self._pix_center = np.array([(self.npix[0] - 1.0) / 2.,\n                                     (self.npix[1] - 1.0) / 2.])\n        self._pix_size = np.array([np.abs(self.wcs.wcs.cdelt[0]),\n                                   np.abs(self.wcs.wcs.cdelt[1])])\n\n        self._skydir = SkyCoord.from_pixel(self._pix_center[0],\n                                           self._pix_center[1],\n                                           self.wcs)\n        self._ebins = ebins\n        if ebins is not None:\n            self._ectr = np.exp(utils.edge_to_center(np.log(ebins)))\n        else:\n            self._ectr = None\n\n    @property\n    def wcs(self):\n        return self._wcs\n\n    @property\n    def npix(self):\n        return self._npix\n\n    @property\n    def skydir(self):\n        \"\"\"Return the sky coordinate of the image center.\"\"\"\n        return self._skydir\n\n    @property\n    def width(self):\n        \"\"\"Return the dimensions of the image.\"\"\"\n        return self._width\n\n    @property\n    def pix_size(self):\n        \"\"\"Return the pixel size along the two image dimensions.\"\"\"\n        return self._pix_size\n\n    @property\n    def pix_center(self):\n        \"\"\"Return the ROI center in pixel coordinates.\"\"\"\n        return self._pix_center\n\n    @classmethod\n    def create_from_hdu(cls, hdu, wcs):\n        return cls(hdu.data.T, wcs)\n\n    @classmethod\n    def create_from_fits(cls, fitsfile, **kwargs):\n        hdu = kwargs.get('hdu', 0)\n\n        with fits.open(fitsfile) as hdulist:\n            header = hdulist[hdu].header\n            data = hdulist[hdu].data\n            header = fits.Header.fromstring(header.tostring())\n            wcs = WCS(header)\n\n            ebins = None\n            if 'ENERGIES' in hdulist:\n                tab = Table.read(fitsfile, 'ENERGIES')\n                ectr = np.array(tab.columns[0])\n                ebins = np.exp(utils.center_to_edge(np.log(ectr)))\n            elif 'EBOUNDS' in hdulist:\n                tab = Table.read(fitsfile, 'EBOUNDS')\n                emin = np.array(tab['E_MIN']) / 1E3\n                emax = np.array(tab['E_MAX']) / 1E3\n                ebins = np.append(emin, emax[-1])\n\n        return cls(data, wcs, ebins)\n\n    @classmethod\n    def create(cls, skydir, cdelt, npix, coordsys='CEL', projection='AIT', ebins=None, differential=False):\n        crpix = np.array([n / 2. + 0.5 for n in npix])\n\n        if ebins is not None:\n            if differential:\n                nebins = len(ebins)\n            else:\n                nebins = len(ebins) - 1\n            data = np.zeros(list(npix) + [nebins]).T\n            naxis = 3\n        else:\n            data = np.zeros(npix).T\n            naxis = 2\n\n        wcs = wcs_utils.create_wcs(skydir, coordsys, projection,\n                                   cdelt, crpix, naxis=naxis, energies=ebins)\n        return cls(data, wcs, ebins=ebins)\n\n    def create_image_hdu(self, name=None, **kwargs):\n        return fits.ImageHDU(self.counts, header=self.wcs.to_header(),\n                             name=name)\n\n    def create_primary_hdu(self):\n        return fits.PrimaryHDU(self.counts, header=self.wcs.to_header())\n\n    def sum_over_energy(self):\n        \"\"\" Reduce a 3D counts cube to a 2D counts map\n        \"\"\"\n        # Note that the array is using the opposite convention from WCS\n        # so we sum over axis 0 in the array, but drop axis 2 in the WCS object\n        return Map(np.sum(self.counts, axis=0), self.wcs.dropaxis(2))\n\n    def xypix_to_ipix(self, xypix, colwise=False):\n        \"\"\"Return the flattened pixel indices from an array multi-dimensional\n        pixel indices.\n\n        Parameters\n        ----------\n        xypix : list\n            List of pixel indices in the order (LON,LAT,ENERGY).\n\n        colwise : bool\n            Use column-wise pixel indexing.\n        \"\"\"\n        return np.ravel_multi_index(xypix, self.npix,\n                                    order='F' if colwise else 'C',\n                                    mode='raise')\n\n    def ipix_to_xypix(self, ipix, colwise=False):\n        \"\"\"Return array multi-dimensional pixel indices from flattened index.\n\n        Parameters\n        ----------\n        colwise : bool\n            Use column-wise pixel indexing.\n        \"\"\"\n        return np.unravel_index(ipix, self.npix,\n                                order='F' if colwise else 'C')\n\n    def ipix_swap_axes(self, ipix, colwise=False):\n        \"\"\" Return the transposed pixel index from the pixel xy coordinates\n\n        if colwise is True (False) this assumes the original index was\n        in column wise scheme\n        \"\"\"\n        xy = self.ipix_to_xypix(ipix, colwise)\n        return self.xypix_to_ipix(xy, not colwise)\n\n    def get_pixel_skydirs(self):\n        \"\"\"Get a list of sky coordinates for the centers of every pixel.\n\n        \"\"\"\n\n        xpix = np.linspace(0, self.npix[0] - 1., self.npix[0])\n        ypix = np.linspace(0, self.npix[1] - 1., self.npix[1])\n        xypix = np.meshgrid(xpix, ypix, indexing='ij')\n        return SkyCoord.from_pixel(np.ravel(xypix[0]),\n                                   np.ravel(xypix[1]), self.wcs)\n\n    def get_pixel_indices(self, lons, lats, ibin=None):\n        \"\"\"Return the indices in the flat array corresponding to a set of coordinates\n\n        Parameters\n        ----------\n        lons  : array-like\n           'Longitudes' (RA or GLON)\n\n        lats  : array-like\n           'Latitidues' (DEC or GLAT)\n\n        ibin : int or array-like\n           Extract data only for a given energy bin.  None -> extract data for all energy bins.\n\n        Returns\n        ----------\n        pixcrd : list\n           Pixel indices along each dimension of the map.\n        \"\"\"\n        lons = np.array(lons, ndmin=1)\n        lats = np.array(lats, ndmin=1)\n\n        if len(lats) != len(lons):\n            raise RuntimeError('Map.get_pixel_indices, input lengths '\n                               'do not match %i %i' % (len(lons), len(lats)))\n        if len(self._npix) == 2:\n            pix_x, pix_y = self._wcs.wcs_world2pix(lons, lats, 0)\n            pixcrd = [np.floor(pix_x).astype(int), np.floor(pix_y).astype(int)]\n        elif len(self._npix) == 3:\n            all_lons = np.expand_dims(lons, -1)\n            all_lats = np.expand_dims(lats, -1)\n            if ibin is None:\n                all_bins = (np.expand_dims(\n                    np.arange(self.npix[2]), -1) * np.ones(lons.shape)).T\n            else:\n                all_bins = ibin\n\n            l = self.wcs.wcs_world2pix(all_lons, all_lats, all_bins, 0)\n            pix_x = l[0]\n            pix_y = l[1]\n            pixcrd = [np.floor(l[0]).astype(int), np.floor(l[1]).astype(int),\n                      all_bins.astype(int)]\n\n        return pixcrd\n\n    def get_map_values(self, lons, lats, ibin=None):\n        \"\"\"Return the map values corresponding to a set of coordinates.\n\n        Parameters\n        ----------\n        lons  : array-like\n           'Longitudes' (RA or GLON)\n\n        lats  : array-like\n           'Latitidues' (DEC or GLAT)\n\n        ibin : int or array-like\n           Extract data only for a given energy bin.  None -> extract data for all bins\n\n        Returns\n        ----------\n        vals : numpy.ndarray((n))\n           Values of pixels in the flattened map, np.nan used to flag\n           coords outside of map\n        \"\"\"\n        pix_idxs = self.get_pixel_indices(lons, lats, ibin)\n        idxs = copy.copy(pix_idxs)\n\n        m = np.empty_like(idxs[0], dtype=bool)\n        m.fill(True)\n        for i, p in enumerate(pix_idxs):\n            m &= (pix_idxs[i] >= 0) & (pix_idxs[i] < self._npix[i])\n            idxs[i][~m] = 0\n\n        vals = self.counts.T[idxs]\n        vals[~m] = np.nan\n        return vals\n\n    def interpolate(self, lon, lat, egy=None):\n\n        if len(self.npix) == 2:\n            pixcrd = self.wcs.wcs_world2pix(lon, lat, 0)\n        else:\n            if egy is None:\n                egy = self._ectr\n            pixcrd = self.wcs.wcs_world2pix(lon, lat, egy, 0)\n            pixcrd[2] = np.array(utils.val_to_pix(np.log(self._ectr),\n                                                  np.log(egy)), ndmin=1)\n\n        points = []\n        for npix in self.npix:\n            points += [np.linspace(0, npix - 1., npix)]\n        data = self.counts\n        fn = RegularGridInterpolator(points, data.T,\n                                     bounds_error=False,\n                                     fill_value=None)\n        return fn(np.column_stack(pixcrd))\n\n    def interpolate_at_skydir(self, skydir):\n\n        coordsys = wcs_utils.get_coordsys(self.wcs)\n        if coordsys == 'CEL':\n            skydir = skydir.transform_to('icrs')\n            return self.interpolate(skydir.ra.deg, skydir.dec.deg)\n        else:\n            skydir = skydir.transform_to('galactic')\n            return self.interpolate(skydir.l.deg, skydir.b.deg)\n\n\nclass HpxMap(Map_Base):\n    \"\"\" Representation of a 2D or 3D counts map using HEALPix. \"\"\"\n\n    def __init__(self, counts, hpx):\n        \"\"\" C'tor, fill with a counts vector and a HPX object \"\"\"\n        super(HpxMap, self).__init__(counts)\n        self._hpx = hpx\n        self._wcs2d = None\n        self._hpx2wcs = None\n\n    @property\n    def hpx(self):\n        return self._hpx\n\n    @classmethod\n    def create_from_hdu(cls, hdu, ebins):\n        \"\"\" Creates and returns an HpxMap object from a FITS HDU.\n\n        hdu    : The FITS\n        ebins  : Energy bin edges [optional]\n        \"\"\"\n        hpx = HPX.create_from_hdu(hdu, ebins)\n        colnames = hdu.columns.names\n        cnames = []\n        if hpx.conv.convname == 'FGST_SRCMAP_SPARSE':\n            pixs = hdu.data.field('PIX')\n            chans = hdu.data.field('CHANNEL')\n            keys = chans * hpx.npix + pixs\n            vals = hdu.data.field('VALUE')\n            nebin = len(ebins)\n            data = np.zeros((nebin, hpx.npix))\n            data.flat[keys] = vals\n        else:\n            for c in colnames:\n                if c.find(hpx.conv.colstring) == 0:\n                    cnames.append(c)\n            nebin = len(cnames)\n            data = np.ndarray((nebin, hpx.npix))\n            for i, cname in enumerate(cnames):\n                data[i, 0:] = hdu.data.field(cname)\n\n        return cls(data, hpx)\n\n    @classmethod\n    def create_from_hdulist(cls, hdulist, **kwargs):\n        \"\"\" Creates and returns an HpxMap object from a FITS HDUList\n\n        extname : The name of the HDU with the map data\n        ebounds : The name of the HDU with the energy bin data\n        \"\"\"\n        extname = kwargs.get('hdu', hdulist[1].name)\n        ebins = fits_utils.find_and_read_ebins(hdulist)\n        return cls.create_from_hdu(hdulist[extname], ebins)\n\n    @classmethod\n    def create_from_fits(cls, fitsfile, **kwargs):\n        hdulist = fits.open(fitsfile)\n        return cls.create_from_hdulist(hdulist, **kwargs)\n\n    def create_image_hdu(self, name=None, **kwargs):\n        kwargs['extname'] = name\n        return self.hpx.make_hdu(self.counts, **kwargs)\n\n    def make_wcs_from_hpx(self, sum_ebins=False, proj='CAR', oversample=2,\n                          normalize=True):\n        \"\"\"Make a WCS object and convert HEALPix data into WCS projection\n\n        NOTE: this re-calculates the mapping, if you have already\n        calculated the mapping it is much faster to use\n        convert_to_cached_wcs() instead\n\n        Parameters\n        ----------\n        sum_ebins  : bool\n           sum energy bins over energy bins before reprojecting\n\n        proj       : str\n           WCS-projection\n\n        oversample : int\n           Oversampling factor for WCS map\n\n        normalize  : bool\n           True -> perserve integral by splitting HEALPix values between bins\n\n        returns (WCS object, np.ndarray() with reprojected data)\n\n        \"\"\"\n        self._wcs_proj = proj\n        self._wcs_oversample = oversample\n        self._wcs_2d = self.hpx.make_wcs(2, proj=proj, oversample=oversample)\n        self._hpx2wcs = HpxToWcsMapping(self.hpx, self._wcs_2d)\n        wcs, wcs_data = self.convert_to_cached_wcs(self.counts, sum_ebins,\n                                                   normalize)\n        return wcs, wcs_data\n\n    def convert_to_cached_wcs(self, hpx_in, sum_ebins=False, normalize=True):\n        \"\"\" Make a WCS object and convert HEALPix data into WCS projection\n\n        Parameters\n        ----------\n        hpx_in     : `~numpy.ndarray`\n           HEALPix input data\n        sum_ebins  : bool\n           sum energy bins over energy bins before reprojecting\n        normalize  : bool\n           True -> perserve integral by splitting HEALPix values between bins\n\n        returns (WCS object, np.ndarray() with reprojected data)\n        \"\"\"\n        if self._hpx2wcs is None:\n            raise Exception('HpxMap.convert_to_cached_wcs() called '\n                            'before make_wcs_from_hpx()')\n\n        if len(hpx_in.shape) == 1:\n            wcs_data = np.ndarray(self._hpx2wcs.npix)\n            loop_ebins = False\n            hpx_data = hpx_in\n        elif len(hpx_in.shape) == 2:\n            if sum_ebins:\n                wcs_data = np.ndarray(self._hpx2wcs.npix)\n                hpx_data = hpx_in.sum(0)\n                loop_ebins = False\n            else:\n                wcs_data = np.ndarray((self.counts.shape[0],\n                                       self._hpx2wcs.npix[0],\n                                       self._hpx2wcs.npix[1]))\n                hpx_data = hpx_in\n                loop_ebins = True\n        else:\n            raise Exception('Wrong dimension for HpxMap %i' %\n                            len(hpx_in.shape))\n\n        if loop_ebins:\n            for i in range(hpx_data.shape[0]):\n                self._hpx2wcs.fill_wcs_map_from_hpx_data(\n                    hpx_data[i], wcs_data[i], normalize)\n                pass\n            wcs_data.reshape((self.counts.shape[0], self._hpx2wcs.npix[\n                             0], self._hpx2wcs.npix[1]))\n            # replace the WCS with a 3D one\n            wcs = self.hpx.make_wcs(3, proj=self._wcs_proj,\n                                    energies=np.log10(self.hpx.ebins),\n                                    oversample=self._wcs_oversample)\n        else:\n            self._hpx2wcs.fill_wcs_map_from_hpx_data(\n                hpx_data, wcs_data, normalize)\n            wcs_data.reshape(self._hpx2wcs.npix)\n            wcs = self._wcs_2d\n\n        return wcs, wcs_data\n\n    def get_pixel_skydirs(self):\n        \"\"\"Get a list of sky coordinates for the centers of every pixel. \"\"\"\n        sky_coords = self._hpx.get_sky_coords()\n        if self.hpx.coordsys == 'GAL':\n            return SkyCoord(l=sky_coords.T[0], b=sky_coords.T[1], unit='deg', frame='galactic')\n        else:\n            return SkyCoord(ra=sky_coords.T[0], dec=sky_coords.T[1], unit='deg', frame='icrs')\n\n    def get_pixel_indices(self, lats, lons):\n        \"\"\"Return the indices in the flat array corresponding to a set of coordinates \"\"\"\n        return self._hpx.get_pixel_indices(lats, lons)\n\n    def sum_over_energy(self):\n        \"\"\" Reduce a counts cube to a counts map \"\"\"\n        # We sum over axis 0 in the array, and drop the energy binning in the\n        # hpx object\n        return HpxMap(np.sum(self.counts, axis=0), self.hpx.copy_and_drop_energy())\n\n    def get_map_values(self, lons, lats, ibin=None):\n        \"\"\"Return the indices in the flat array corresponding to a set of coordinates\n\n        Parameters\n        ----------\n        lons  : array-like\n           'Longitudes' (RA or GLON)\n\n        lats  : array-like\n           'Latitidues' (DEC or GLAT)\n\n        ibin : int or array-like\n           Extract data only for a given energy bin.  None -> extract data for all bins\n\n        Returns\n        ----------\n        vals : numpy.ndarray((n))\n           Values of pixels in the flattened map, np.nan used to flag\n           coords outside of map\n        \"\"\"\n        theta = np.pi / 2. - np.radians(lats)\n        phi = np.radians(lons)\n\n        pix = hp.ang2pix(self.hpx.nside, theta, phi, nest=self.hpx.nest)\n\n        if self.data.ndim == 2:\n            return self.data[:, pix] if ibin is None else self.data[ibin, pix]\n        else:\n            return self.data[pix]\n\n    def interpolate(self, lon, lat, egy=None, interp_log=True):\n        \"\"\"Interpolate map values.\n\n        Parameters\n        ----------\n        interp_log : bool\n            Interpolate the z-coordinate in logspace.\n\n        \"\"\"\n\n        if self.data.ndim == 1:\n            theta = np.pi / 2. - np.radians(lat)\n            phi = np.radians(lon)\n            return hp.pixelfunc.get_interp_val(self.counts, theta,\n                                               phi, nest=self.hpx.nest)\n        else:\n            return self._interpolate_cube(lon, lat, egy, interp_log)\n\n    def _interpolate_cube(self, lon, lat, egy=None, interp_log=True):\n        \"\"\"Perform interpolation on a healpix cube.  If egy is None\n        then interpolation will be performed on the existing energy\n        planes.\n\n        \"\"\"\n\n        shape = np.broadcast(lon, lat, egy).shape\n        lon = lon * np.ones(shape)\n        lat = lat * np.ones(shape)\n        theta = np.pi / 2. - np.radians(lat)\n        phi = np.radians(lon)\n        vals = []\n        for i, _ in enumerate(self.hpx.evals):\n            v = hp.pixelfunc.get_interp_val(self.counts[i], theta,\n                                            phi, nest=self.hpx.nest)\n            vals += [np.expand_dims(np.array(v, ndmin=1), -1)]\n\n        vals = np.concatenate(vals, axis=-1)\n\n        if egy is None:\n            return vals.T\n\n        egy = egy * np.ones(shape)\n\n        if interp_log:\n            xvals = utils.val_to_pix(np.log(self.hpx.evals), np.log(egy))\n        else:\n            xvals = utils.val_to_pix(self.hpx.evals, egy)\n\n        vals = vals.reshape((-1, vals.shape[-1]))\n        xvals = np.ravel(xvals)\n        v = map_coordinates(vals, [np.arange(vals.shape[0]), xvals],\n                            order=1)\n        return v.reshape(shape)\n\n    def swap_scheme(self):\n        \"\"\"\n        \"\"\"\n        hpx_out = self.hpx.make_swapped_hpx()\n        if self.hpx.nest:\n            if self.data.ndim == 2:\n                data_out = np.vstack([hp.pixelfunc.reorder(\n                    self.data[i], n2r=True) for i in range(self.data.shape[0])])\n            else:\n                data_out = hp.pixelfunc.reorder(self.data, n2r=True)\n        else:\n            if self.data.ndim == 2:\n                data_out = np.vstack([hp.pixelfunc.reorder(\n                    self.data[i], r2n=True) for i in range(self.data.shape[0])])\n            else:\n                data_out = hp.pixelfunc.reorder(self.data, r2n=True)\n        return HpxMap(data_out, hpx_out)\n\n    def expanded_counts_map(self):\n        \"\"\" return the full counts map \"\"\"\n        if self.hpx._ipix is None:\n            return self.counts\n\n        output = np.zeros(\n            (self.counts.shape[0], self.hpx._maxpix), self.counts.dtype)\n        for i in range(self.counts.shape[0]):\n            output[i][self.hpx._ipix] = self.counts[i]\n        return output\n\n    def explicit_counts_map(self, pixels=None):\n        \"\"\" return a counts map with explicit index scheme\n\n        Parameters\n        ----------\n        pixels : `np.ndarray` or None\n            If set, grab only those pixels.  \n            If none, grab only non-zero pixels\n        \"\"\"\n        # No pixel index, so build one\n        if self.hpx._ipix is None:\n            if self.data.ndim == 2:\n                summed = self.counts.sum(0)\n                if pixels is None:\n                    nz = summed.nonzero()[0]\n                else:\n                    nz = pixels\n                data_out = np.vstack(self.data[i].flat[nz]\n                                     for i in range(self.data.shape[0]))\n            else:\n                if pixels is None:\n                    nz = self.data.nonzero()[0]\n                else:\n                    nz = pixels\n                data_out = self.data[nz]\n            return (nz, data_out)\n        else:\n            if pixels is None:\n                return (self.hpx._ipix, self.data)\n        # FIXME, can we catch this\n        raise RuntimeError(\n            'HPX.explicit_counts_map called with pixels for a map that already has pixels')\n\n    def sparse_counts_map(self):\n        \"\"\" return a counts map with sparse index scheme\n        \"\"\"\n        if self.hpx._ipix is None:\n            flatarray = self.data.flattern()\n        else:\n            flatarray = self.expanded_counts_map()\n        nz = flatarray.nonzero()[0]\n        data_out = flatarray[nz]\n        return (nz, data_out)\n\n    def ud_grade(self, order, preserve_counts=False):\n        \"\"\"\n        \"\"\"\n        new_hpx = self.hpx.ud_graded_hpx(order)\n        if new_hpx.evals is None:\n            nebins = 1\n        else:\n            nebins = len(new_hpx.evals)\n        shape = self.counts.shape\n\n        if preserve_counts:\n            power = -2.\n        else:\n            power = 0\n\n        if len(shape) == 1:\n            new_data = hp.pixelfunc.ud_grade(self.counts,\n                                             nside_out=new_hpx.nside,\n                                             order_in=new_hpx.ordering,\n                                             order_out=new_hpx.ordering,\n                                             power=power)\n        else:\n            new_data = np.vstack([hp.pixelfunc.ud_grade(self.counts[i],\n                                                        nside_out=new_hpx.nside,\n                                                        order_in=new_hpx.ordering,\n                                                        order_out=new_hpx.ordering,\n                                                        power=power) for i in range(shape[0])])\n        return HpxMap(new_data, new_hpx)\n", "meta": {"hexsha": "0c40e80aa939cd86a6177aff7c4e0b43dd5a215a", "size": 26951, "ext": "py", "lang": "Python", "max_stars_repo_path": "fermipy/skymap.py", "max_stars_repo_name": "damgreen/fermipy", "max_stars_repo_head_hexsha": "92b693a9272453bc6eb5c21e9bbac912408122fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 42, "max_stars_repo_stars_event_min_datetime": "2015-05-08T14:47:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T03:28:54.000Z", "max_issues_repo_path": "fermipy/skymap.py", "max_issues_repo_name": "damgreen/fermipy", "max_issues_repo_head_hexsha": "92b693a9272453bc6eb5c21e9bbac912408122fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 321, "max_issues_repo_issues_event_min_datetime": "2015-10-01T18:57:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T13:02:05.000Z", "max_forks_repo_path": "fermipy/skymap.py", "max_forks_repo_name": "damgreen/fermipy", "max_forks_repo_head_hexsha": "92b693a9272453bc6eb5c21e9bbac912408122fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 44, "max_forks_repo_forks_event_min_datetime": "2015-11-23T08:54:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T17:50:51.000Z", "avg_line_length": 35.0012987013, "max_line_length": 107, "alphanum_fraction": 0.5565656191, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 6572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.29098087236345377, "lm_q1q2_score": 0.18431026706168063}}
{"text": "#!/usr/bin/env python\nimport emcee\nimport celerite\nfrom celerite import terms\n\nimport numpy as np\nimport astropy.units as u\nfrom astropy.modeling.blackbody import blackbody_lambda\n\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport seaborn as sns\n\nfrom pylcurve.lcurve import Lcurve\nfrom pylcurve.modeling import Model\nimport pylcurve.mcmc_utils as m\nfrom pylcurve.utils import log_g, separation, get_limbdark_params, wd_to_bb_temp\n\nband_wavs = dict(\n    u=3543*u.AA,\n    g=4770*u.AA,\n    r=6231*u.AA,\n    i=7625*u.AA,\n    z=9134*u.AA\n)\n\n\ndef scale_pulsation(band, temp):\n    return blackbody_lambda(band_wavs[band], temp*u.K) / blackbody_lambda(band_wavs['g'], temp*u.K)\n\n\nclass EclipseLC(Model):\n    parameter_names = ('t1', 't2', 'm1', 'm2', 'incl', 'r1', 'r2', 't0', 'per',\n                       'pulse_omega', 'pulse_q', 'pulse_temp', 'pulse_amp')\n\n    def __init__(self, model_file, lightcurves, *args, **kwargs):\n        \"\"\"\n        A lightcurve model for an eclipsing DWD with pulsations\n\n        Parameters\n        ----------\n        model_file: model containing LCURVE file with auxillary (fixed) params\n        lightcurves: a dictionary of band: filename pairs\n\n        The remaining parameters are either passed in as a list of arguments\n        (in order) or specified as a dictionary:\n\n        t1, t2 :  white dwarf temp in K\n        m1, m2 : white dwarf masses in solar masses (constrained through RV prior)\n        incl : inclination of system\n        r1, r2 : white dwarf radii in solar radii\n        t0 : mid-eclipse time of primary eclipse\n        pulse_omega : frequency of pulsations\n        pulse_q : q factor of pulsations\n        pulse_temp : BB temperature of pulsations\n        pulse_amp : amplitude of pulsations in g band\n        \"\"\"\n        super().__init__(*args, **kwargs)\n        self.lightcurves = lightcurves\n        self.model_file = model_file\n\n    def get_value(self, band):\n        \"\"\"\n        Calculate lightcurve\n\n        Parameters\n        ----------\n        band : string\n            SDSS/HiPERCAM bandpass\n\n        Returns\n        -------\n        ym : np.ndarray\n            model values\n        \"\"\"\n        # setup LCURVE file for this band\n        lcurve_model = Lcurve(self.model_file)\n        lcurve_pars = dict()\n\n        log_g1 = log_g(self.m1, self.r1)\n        log_g2 = log_g(self.m2, self.r2)\n        a = separation(self.m1, self.m2, self.per)\n        lcurve_pars['t1'] = wd_to_bb_temp(band, self.t1, log_g1)\n        lcurve_pars['t2'] = wd_to_bb_temp(band, self.t2, log_g2)\n        lcurve_pars['r1'] = self.r1/a  # scale from solar radii to separation units\n        lcurve_pars['r2'] = self.r2/a  # scale from solar radii to separation units\n        lcurve_pars['t0'] = self.t0\n        lcurve_pars['period'] = self.per\n        lcurve_pars['iangle'] = self.incl\n        lcurve_pars['q'] = self.m1/self.m2\n        lcurve_pars['wavelength'] = band_wavs[band].to_value(u.nm)\n        lcurve_model.set(lcurve_pars)\n        lcurve_model.set(get_limbdark_params(self.t1, log_g1, self.t2, log_g2, band))\n\n        if not lcurve_model.ok():\n            raise ValueError('invalid parameter combination')\n        x, y, e, ym = lcurve_model(self.lightcurves[band])\n        return ym\n\n    def log_prior(self):\n        \"\"\"\n        Prior probabilities\n        \"\"\"\n        # first call parent class log_prior -> checks params in bounds\n        val = super().log_prior()\n        if np.isinf(val):\n            return val\n\n        # OK, we are within limits, check M1, M2 against RV constraints\n        # K1 (brighter, hotter WD rv): 186.3 +/- 1.6 km/s\n        # K2 (fainter, cooler WD rv): 213.6 +/- 4.6 km/s\n        # mass ratio\n        q_prior = m.Prior('gauss', 1.146, 0.027)\n        q_act = self.m1/self.m2\n        val += q_prior.ln_prob(q_act)\n        # (m1 + m2) * sini**3 = (P/2piG) * (v1+v2)**3\n        mt_prior = m.Prior('gauss', 0.66, 0.02)\n        val += mt_prior.ln_prob((self.m1 + self.m2) * np.sin(self.incl)**3)\n\n        # priors on t0, p from ephemeris\n        prior = m.Prior('gauss', 57460.6510218, 0.0000010)\n        val += prior.ln_prob(self.t0)\n\n        prior = m.Prior('gauss', 0.09986526542, 0.00000000010)\n        val += prior.ln_prob(self.per)\n\n        return val\n\n    def plot(self, ax, band, params, style='whole', dcolor='k', gpcolor='r'):\n        \"\"\"\n        Plots data and model on axis\n\n        style is either whole, model or residuals.\n            'whole' plots the raw data and the full model (mean model + GP).\n\n            'model' plots the mean model and the data after subtraction\n             of the mean of the GP - i.e the data minus the pulsations\n\n            'residuals' plots the data minus the mean model, together with the\n            mean and range of the GP\n        \"\"\"\n        self.set_parameter_vector(params)\n        t, _, y, ye, _, _ = np.loadtxt(self.lightcurves[band]).T\n        ym = self.get_value(band)\n\n        pulsation_amp = self.pulse_amp * scale_pulsation(band, self.pulse_temp)\n        gp = self.gpdict[band]\n        gp.set_parameter_vector((np.log(pulsation_amp),\n                                 np.log(self.pulse_q),\n                                 np.log(self.pulse_omega)))\n\n        samples = gp.sample_conditional(y-ym, t, size=300)\n        mu = np.mean(samples, axis=0)\n        std = np.std(samples, axis=0)\n\n        toff = int(np.floor(np.min(t)))\n        tplot = t - toff\n\n        if style == 'whole':\n            ax.errorbar(tplot, y, yerr=ye, fmt='none', color=dcolor, alpha=0.5)\n            ax.plot(tplot, ym + mu, color=gpcolor, lw=2)\n            ax.plot(tplot, ym, color='k', lw=2, ls=':')\n            ax.fill_between(tplot, ym+mu+std, ym+mu-std, color=gpcolor, alpha=0.6)\n        elif style == 'model':\n            ax.errorbar(tplot, y-mu, yerr=ye, fmt='none', color=dcolor, alpha=0.5)\n            ax.plot(tplot, ym, color=gpcolor, lw=2)\n            ax.fill_between(tplot, ym+std, ym-std, color=gpcolor, alpha=0.6)\n        elif style == 'residuals':\n            ax.errorbar(tplot, y-ym, yerr=ye, fmt='none', color=dcolor, alpha=0.5)\n            ax.plot(tplot, mu, color=gpcolor, lw=2)\n            ax.fill_between(tplot, mu+std, mu-std, color=gpcolor, alpha=0.6)\n        else:\n            raise ValueError('style not recognised')\n\n    def log_probability(self, params, band):\n        \"\"\"\n        Calculate log of posterior probability\n\n        Parameters\n        -----------\n        params : iterable\n            list of parameter values\n        band : string\n            SDSS/HiPERCAM band\n        \"\"\"\n        self.set_parameter_vector(params)\n        t, _, y, ye, _, _ = np.loadtxt(self.lightcurves[band]).T\n\n        # check model params are valid - checks against bounds\n        lp = self.log_prior()\n        if not np.isfinite(lp):\n            return -np.inf\n\n        # make a GP for this band, if it doesnt already exist\n        if not hasattr(self, 'gpdict'):\n            self.gpdict = dict()\n\n        # Oscillation params\n        pulsation_amp = self.pulse_amp * scale_pulsation(band, self.pulse_temp)\n\n        if band not in self.gpdict:\n            kernel = terms.SHOTerm(np.log(pulsation_amp),\n                                   np.log(self.pulse_q),\n                                   np.log(self.pulse_omega))\n            gp = celerite.GP(kernel)\n            gp.compute(t, ye)\n            self.gpdict[band] = gp\n        else:\n            gp = self.gpdict[band]\n            gp.set_parameter_vector((\n                np.log(pulsation_amp),\n                np.log(self.pulse_q),\n                np.log(self.pulse_omega)\n            ))\n            gp.compute(t, ye)\n\n        # now add prior of Gaussian process\n        lp += gp.log_prior()\n        if not np.isfinite(lp):\n            return -np.inf\n\n        try:\n            ym = self.get_value(band)\n        except ValueError as err:\n            # invalid lcurve params\n            print('warning: model failed ', err)\n            return -np.inf\n        else:\n            return gp.log_likelihood(y - ym) + lp\n\n\nif __name__ == \"__main__\":\n    import argparse\n    parser = argparse.ArgumentParser(description='Fit or plot model of LC')\n    parser.add_argument('--nwalkers', action='store', type=int, default=40)\n    parser.add_argument('--fit', '-f', action='store_true')\n    parser.add_argument('--nburn', action='store', type=int, default=100)\n    parser.add_argument('--nprod', action='store', type=int, default=100)\n    parser.add_argument('--nthreads', action='store', type=int, default=4)\n    args = parser.parse_args()\n\n    nameList = np.array(['t1', 't2', 'm1', 'm2', 'incl',\n                         'r1', 'r2', 't0', 'per', 'pulse_omega',\n                         'pulse_q', 'pulse_temp', 'pulse_amp'])\n    params = np.array([25000, 9000, 0.40, 0.35, 89.4, 0.0193, 0.0186, 57460.6510218, 0.09986526542,\n                       60.0, 10, 10000, 0.005])\n    ndim = len(params)\n\n    model_bounds = dict(\n        t1=(20000, 30000),\n        t2=(8000, 10000),\n        m1=(0.3, 0.5),\n        m2=(0.3, 0.5),\n        incl=(89, 90),\n        r1=(0.01, 0.025), r2=(0.01, 0.025),\n        t0=(57460.6508313, 57460.6512313),\n        per=(0.0998650, 0.099866),\n        pulse_omega=(1, 200), pulse_q=(1, 100),\n        pulse_temp=(5000, 40000), pulse_amp=(0.00001, 0.1)\n    )\n    # dictionary of Tseries objects, one for each band\n    light_curves = dict(\n        u='u.dat',\n        g='g.dat',\n        r='r.dat',\n        i='i.dat',\n        z='z.dat'\n    )\n    model = EclipseLC('lcurve_model', light_curves, *params, bounds=model_bounds)\n\n    # wrapper to combine log probability from all bands\n    def log_probability(params):\n        val = 0\n        for band in ('u', 'g', 'r', 'i', 'z'):\n            val += model.log_probability(params, band)\n        return val\n\n    if args.fit:\n        nwalkers = args.nwalkers\n\n        def log_prior(params):\n            model.set_parameter_vector(params)\n            return model.log_prior()\n\n        # amount to scatter initial ball of walkers\n        scatter = 0.01*np.ones_like(params)\n        # small scatter for t0 and period\n        scatter[7] = 1.0e-9\n        scatter[8] = 1.0e-9\n        p0 = m.initialise_walkers(params, scatter, nwalkers, log_prior)\n        sampler = emcee.EnsembleSampler(nwalkers, ndim, log_probability, threads=args.nthreads)\n\n        pos, prob, state = m.run_burnin(sampler, p0, args.nburn)\n        sampler.reset()\n\n        sampler = m.run_mcmc_save(sampler, pos, args.nprod, state, 'chain.txt')\n        chain = m.flatchain(sampler.chain, ndim, thin=3)\n\n        bestPars = []\n        for i in range(ndim):\n            par = chain[:, i]\n            lolim, best, uplim = np.percentile(par, [16, 50, 84])\n            print(\"%s = %f +%f -%f\" % (nameList[i], best, uplim-best, best-lolim))\n            bestPars.append(best)\n        fig = m.thumbPlot(chain, nameList)\n        fig.savefig('cornerPlot.pdf')\n        plt.close()\n\n    else:\n        try:\n            chain = m.readchain('chain.txt')\n            fchain = m.flatchain(chain, ndim+1, thin=3)[:, :-1]\n            bestPars = np.median(fchain, axis=0)\n            lolim, uplim = np.percentile(fchain, (16, 84), axis=0)\n            for name, par, lo, hi in zip(nameList, bestPars, lolim, uplim):\n                print('{} = {} + {} - {}'.format(name, par, hi-par, par-lo))\n        except Exception as err:\n            print('no chain read, falling back to guess ' + str(err))\n            bestPars = params\n\n    print('Best fit has ln_prob of {}'.format(log_probability(bestPars)))\n\n    gs = gridspec.GridSpec(5, 2)\n    gs.update(hspace=0.0)\n\n    shared_ax = None\n    for iband, band in enumerate(('u', 'g', 'r', 'i', 'z')):\n        if shared_ax:\n            ax_main = plt.subplot(gs[iband, 0], sharex=shared_ax)\n            ax_res = plt.subplot(gs[iband, 1], sharex=ax_main)\n        else:\n            ax_main = plt.subplot(gs[iband, 0])\n            shared_ax = ax_main\n            ax_res = plt.subplot(gs[iband, 1], sharex=ax_main)\n\n        color = sns.color_palette('nipy_spectral', 5)[iband-1]\n        model.plot(ax_main, band, bestPars, style='whole', dcolor=color)\n        model.plot(ax_res, band, bestPars, style='residuals', dcolor=color)\n        if band != 'z':\n            plt.setp(ax_main.get_xticklabels(), visible=False)\n            plt.setp(ax_res.get_xticklabels(), visible=False)\n\n    plt.show()\n", "meta": {"hexsha": "f5547333d342c5184690590c67db5414d2410f79", "size": 12315, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/lcmcmc_pulse.py", "max_stars_repo_name": "Alex-J-Brown/pyclurve", "max_stars_repo_head_hexsha": "1a08031f6b63944f12cc5ded4c86eda1fce3d670", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-30T00:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-30T00:55:37.000Z", "max_issues_repo_path": "scripts/lcmcmc_pulse.py", "max_issues_repo_name": "Alex-J-Brown/pyclurve", "max_issues_repo_head_hexsha": "1a08031f6b63944f12cc5ded4c86eda1fce3d670", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/lcmcmc_pulse.py", "max_forks_repo_name": "Alex-J-Brown/pyclurve", "max_forks_repo_head_hexsha": "1a08031f6b63944f12cc5ded4c86eda1fce3d670", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-03-25T16:18:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-01T02:09:50.000Z", "avg_line_length": 35.7994186047, "max_line_length": 99, "alphanum_fraction": 0.574908648, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 3429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.2814056194821861, "lm_q1q2_score": 0.18429106071256268}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n'''FCI 1, 2, 3, 4-particle density matrices.\n\nNote the 1-particle density matrix has the same convention as the mean-field\n1-particle density matrix (see McWeeney's book Eq 5.4.20), which is\n        dm[p,q] = < q^+ p >\nThe contraction between 1-particle Hamiltonian and 1-pdm is\n        E = einsum('pq,qp', h1, 1pdm)\nDifferent conventions are used in the high order density matrices:\n        dm[p,q,r,s,...] = < p^+ r^+ ... s q >\n'''\n\nimport ctypes\nimport numpy\nfrom pyscf import lib\nfrom pyscf.fci import cistring\nfrom pyscf.fci.addons import _unpack_nelec\n\nlibrdm = lib.load_library('libfci')\n\ndef reorder_rdm(rdm1, rdm2, inplace=False):\n    nmo = rdm1.shape[0]\n    if not inplace:\n        rdm2 = rdm2.copy()\n    for k in range(nmo):\n        rdm2[:,k,k,:] -= rdm1.T\n    #return rdm1, rdm2\n    rdm2 = lib.transpose_sum(rdm2.reshape(nmo*nmo,-1), inplace=True) * .5\n    return rdm1, rdm2.reshape(nmo,nmo,nmo,nmo)\n\n# dm[p,q] = <|q^+ p|>\ndef make_rdm1_ms0(fname, cibra, ciket, norb, nelec, link_index=None):\n    assert(cibra is not None and ciket is not None)\n    cibra = numpy.asarray(cibra, order='C')\n    ciket = numpy.asarray(ciket, order='C')\n    if link_index is None:\n        neleca, nelecb = _unpack_nelec(nelec)\n        assert(neleca == nelecb)\n        link_index = cistring.gen_linkstr_index(range(norb), neleca)\n    na, nlink = link_index.shape[:2]\n    assert(cibra.size == na**2)\n    assert(ciket.size == na**2)\n    rdm1 = numpy.empty((norb,norb))\n    fn = getattr(librdm, fname)\n    fn(rdm1.ctypes.data_as(ctypes.c_void_p),\n       cibra.ctypes.data_as(ctypes.c_void_p),\n       ciket.ctypes.data_as(ctypes.c_void_p),\n       ctypes.c_int(norb),\n       ctypes.c_int(na), ctypes.c_int(na),\n       ctypes.c_int(nlink), ctypes.c_int(nlink),\n       link_index.ctypes.data_as(ctypes.c_void_p),\n       link_index.ctypes.data_as(ctypes.c_void_p))\n    return rdm1.T\n\n# NOTE rdm1 in this function is calculated as rdm1[p,q] = <q^+ p>;\n# rdm2 is calculated as <p^+ q r^+ s>. Call reorder_rdm to transform to the\n# normal rdm2, which is  dm2[p,q,r,s] = <p^+ r^+ s q>.\n# symm = 1: bra, ket symmetry\n# symm = 2: particle permutation symmetry\ndef make_rdm12_ms0(fname, cibra, ciket, norb, nelec, link_index=None, symm=0):\n    if link_index is None:\n        neleca, nelecb = _unpack_nelec(nelec)\n        assert(neleca == nelecb)\n        link_index = cistring.gen_linkstr_index(range(norb), neleca)\n    link_index = (link_index, link_index)\n    return make_rdm12_spin1(fname, cibra, ciket, norb, nelec, link_index, symm)\n\nmake_rdm1 = make_rdm1_ms0\nmake_rdm12 = make_rdm12_ms0\n\n###################################################\n#\n# nelec and link_index are tuples of (alpha,beta)\n#\ndef make_rdm1_spin1(fname, cibra, ciket, norb, nelec, link_index=None):\n    assert(cibra is not None and ciket is not None)\n    cibra = numpy.asarray(cibra, order='C')\n    ciket = numpy.asarray(ciket, order='C')\n    if link_index is None:\n        neleca, nelecb = _unpack_nelec(nelec)\n        link_indexa = link_indexb = cistring.gen_linkstr_index(range(norb), neleca)\n        if neleca != nelecb:\n            link_indexb = cistring.gen_linkstr_index(range(norb), nelecb)\n    else:\n        link_indexa, link_indexb = link_index\n    na,nlinka = link_indexa.shape[:2]\n    nb,nlinkb = link_indexb.shape[:2]\n    assert(cibra.size == na*nb)\n    assert(ciket.size == na*nb)\n    rdm1 = numpy.empty((norb,norb))\n    fn = getattr(librdm, fname)\n    fn(rdm1.ctypes.data_as(ctypes.c_void_p),\n       cibra.ctypes.data_as(ctypes.c_void_p),\n       ciket.ctypes.data_as(ctypes.c_void_p),\n       ctypes.c_int(norb),\n       ctypes.c_int(na), ctypes.c_int(nb),\n       ctypes.c_int(nlinka), ctypes.c_int(nlinkb),\n       link_indexa.ctypes.data_as(ctypes.c_void_p),\n       link_indexb.ctypes.data_as(ctypes.c_void_p))\n    return rdm1.T\n\n# NOTE rdm1 in this function is calculated as rdm1[p,q] = <q^+ p>;\n# rdm2 is calculated as <p^+ q r^+ s>. Call reorder_rdm to transform to the\n# normal rdm2, which is  dm2[p,q,r,s] = <p^+ r^+ s q>.\n# symm = 1: bra, ket symmetry\n# symm = 2: particle permutation symmetry\ndef make_rdm12_spin1(fname, cibra, ciket, norb, nelec, link_index=None, symm=0):\n    assert(cibra is not None and ciket is not None)\n    cibra = numpy.asarray(cibra, order='C')\n    ciket = numpy.asarray(ciket, order='C')\n    if link_index is None:\n        neleca, nelecb = _unpack_nelec(nelec)\n        link_indexa = link_indexb = cistring.gen_linkstr_index(range(norb), neleca)\n        if neleca != nelecb:\n            link_indexb = cistring.gen_linkstr_index(range(norb), nelecb)\n    else:\n        link_indexa, link_indexb = link_index\n    na,nlinka = link_indexa.shape[:2]\n    nb,nlinkb = link_indexb.shape[:2]\n    assert(cibra.size == na*nb)\n    assert(ciket.size == na*nb)\n    rdm1 = numpy.empty((norb,norb))\n    rdm2 = numpy.empty((norb,norb,norb,norb))\n    librdm.FCIrdm12_drv(getattr(librdm, fname),\n                        rdm1.ctypes.data_as(ctypes.c_void_p),\n                        rdm2.ctypes.data_as(ctypes.c_void_p),\n                        cibra.ctypes.data_as(ctypes.c_void_p),\n                        ciket.ctypes.data_as(ctypes.c_void_p),\n                        ctypes.c_int(norb),\n                        ctypes.c_int(na), ctypes.c_int(nb),\n                        ctypes.c_int(nlinka), ctypes.c_int(nlinkb),\n                        link_indexa.ctypes.data_as(ctypes.c_void_p),\n                        link_indexb.ctypes.data_as(ctypes.c_void_p),\n                        ctypes.c_int(symm))\n    return rdm1.T, rdm2\n\n\n##############################\n#\n# 3-particle and 4-particle density matrix for RHF-FCI wfn\n#\n# NOTE the dm3[p,q,r,s,t,u] is calculated as <p^+ q r^+ s t^+ u>\n# call reorder_dm123 to transform dm3 to regular 3-pdm\ndef make_dm123(fname, cibra, ciket, norb, nelec):\n    r'''Spin traced 1, 2 and 3-particle density matrices.\n\n    .. note::\n        In this function, 2pdm[p,q,r,s] is :math:`\\langle p^\\dagger q r^\\dagger s\\rangle`;\n        3pdm[p,q,r,s,t,u] is :math:`\\langle p^\\dagger q r^\\dagger s t^\\dagger u\\rangle`.\n\n        After calling reorder_dm123, the 2pdm and 3pdm are transformed to\n        the normal density matrices:\n        2pdm[p,r,q,s] = :math:`\\langle p^\\dagger q^\\dagger s r\\rangle`\n        3pdm[p,s,q,t,r,u] = :math:`\\langle p^\\dagger q^\\dagger r^\\dagger u t s\\rangle`.\n    '''\n    cibra = numpy.asarray(cibra, order='C')\n    ciket = numpy.asarray(ciket, order='C')\n    neleca, nelecb = _unpack_nelec(nelec)\n    link_indexa = cistring.gen_linkstr_index(range(norb), neleca)\n    link_indexb = cistring.gen_linkstr_index(range(norb), nelecb)\n    na,nlinka = link_indexa.shape[:2]\n    nb,nlinkb = link_indexb.shape[:2]\n    assert(cibra.size == na*nb)\n    assert(ciket.size == na*nb)\n    rdm1 = numpy.empty((norb,)*2)\n    rdm2 = numpy.empty((norb,)*4)\n    rdm3 = numpy.empty((norb,)*6)\n    librdm.FCIrdm3_drv(getattr(librdm, fname),\n                       rdm1.ctypes.data_as(ctypes.c_void_p),\n                       rdm2.ctypes.data_as(ctypes.c_void_p),\n                       rdm3.ctypes.data_as(ctypes.c_void_p),\n                       cibra.ctypes.data_as(ctypes.c_void_p),\n                       ciket.ctypes.data_as(ctypes.c_void_p),\n                       ctypes.c_int(norb),\n                       ctypes.c_int(na), ctypes.c_int(nb),\n                       ctypes.c_int(nlinka), ctypes.c_int(nlinkb),\n                       link_indexa.ctypes.data_as(ctypes.c_void_p),\n                       link_indexb.ctypes.data_as(ctypes.c_void_p))\n    rdm3 = _complete_dm3_(rdm2, rdm3)\n    return rdm1.T, rdm2, rdm3\ndef _complete_dm3_(dm2, dm3):\n# fci_4pdm.c assumed symmetry p >= r >= t for 3-pdm <p^+ q r^+ s t^+ u>\n# Using E^r_sE^p_q = E^p_qE^r_s - \\delta_{qr}E^p_s + \\delta_{ps}E^r_q to\n# complete the full 3-pdm\n    def transpose01(ijk, i, j, k):\n        jik = ijk.transpose(1,0,2)\n        jik[:,j] -= dm2[i,:,k,:]\n        jik[i,:] += dm2[j,:,k,:]\n        dm3[j,:,i,:,k,:] = jik\n        return jik\n    def transpose12(ijk, i, j, k):\n        ikj = ijk.transpose(0,2,1)\n        ikj[:,:,k] -= dm2[i,:,j,:]\n        ikj[:,j,:] += dm2[i,:,k,:]\n        dm3[i,:,k,:,j,:] = ikj\n        return ikj\n\n# ijk -> jik -> jki -> kji -> kij -> ikj\n    norb = dm2.shape[0]\n    for i in range(norb):\n        for j in range(i+1):\n            for k in range(j+1):\n                tmp = transpose01(dm3[i,:,j,:,k,:].copy(), i, j, k)\n                tmp = transpose12(tmp, j, i, k)\n                tmp = transpose01(tmp, j, k, i)\n                tmp = transpose12(tmp, k, j, i)\n                tmp = transpose01(tmp, k, i, j)\n    return dm3\n\ndef make_dm1234(fname, cibra, ciket, norb, nelec):\n    r'''Spin traced 1, 2, 3 and 4-particle density matrices.\n\n    .. note::\n        In this function, 2pdm[p,q,r,s] is :math:`\\langle p^\\dagger q r^\\dagger s\\rangle`;\n        3pdm[p,q,r,s,t,u] is :math:`\\langle p^\\dagger q r^\\dagger s t^\\dagger u\\rangle`;\n        4pdm[p,q,r,s,t,u,v,w] is :math:`\\langle p^\\dagger q r^\\dagger s t^\\dagger u v^\\dagger w\\rangle`.\n\n        After calling reorder_dm123, the 2pdm and 3pdm are transformed to\n        the normal density matrices:\n        2pdm[p,r,q,s] = :math:`\\langle p^\\dagger q^\\dagger s r\\rangle`\n        3pdm[p,s,q,t,r,u] = :math:`\\langle p^\\dagger q^\\dagger r^\\dagger u t s\\rangle`.\n        4pdm[p,t,q,u,r,v,s,w] = :math:`\\langle p^\\dagger q^\\dagger r^\\dagger s^dagger w v u t\\rangle`.\n    '''\n    cibra = numpy.asarray(cibra, order='C')\n    ciket = numpy.asarray(ciket, order='C')\n    neleca, nelecb = _unpack_nelec(nelec)\n    link_indexa = cistring.gen_linkstr_index(range(norb), neleca)\n    link_indexb = cistring.gen_linkstr_index(range(norb), nelecb)\n    na,nlinka = link_indexa.shape[:2]\n    nb,nlinkb = link_indexb.shape[:2]\n    assert(cibra.size == na*nb)\n    assert(ciket.size == na*nb)\n    rdm1 = numpy.empty((norb,)*2)\n    rdm2 = numpy.empty((norb,)*4)\n    rdm3 = numpy.empty((norb,)*6)\n    rdm4 = numpy.empty((norb,)*8)\n    librdm.FCIrdm4_drv(getattr(librdm, fname),\n                       rdm1.ctypes.data_as(ctypes.c_void_p),\n                       rdm2.ctypes.data_as(ctypes.c_void_p),\n                       rdm3.ctypes.data_as(ctypes.c_void_p),\n                       rdm4.ctypes.data_as(ctypes.c_void_p),\n                       cibra.ctypes.data_as(ctypes.c_void_p),\n                       ciket.ctypes.data_as(ctypes.c_void_p),\n                       ctypes.c_int(norb),\n                       ctypes.c_int(na), ctypes.c_int(nb),\n                       ctypes.c_int(nlinka), ctypes.c_int(nlinkb),\n                       link_indexa.ctypes.data_as(ctypes.c_void_p),\n                       link_indexb.ctypes.data_as(ctypes.c_void_p))\n    rdm3 = _complete_dm3_(rdm2, rdm3)\n    rdm4 = _complete_dm4_(rdm3, rdm4)\n    return rdm1.T, rdm2, rdm3, rdm4\ndef _complete_dm4_(dm3, dm4):\n# fci_4pdm.c assumed symmetry p >= r >= t >= v for 4-pdm <p^+ q r^+ s t^+ u v^+ w>\n# Using E^r_sE^p_q = E^p_qE^r_s - \\delta_{qr}E^p_s + \\delta_{ps}E^r_q to\n# complete the full 4-pdm\n    def transpose01(ijkl, i, j, k, l):\n        jikl = ijkl.transpose(1,0,2,3)\n        jikl[:,j] -= dm3[i,:,k,:,l,:]\n        jikl[i,:] += dm3[j,:,k,:,l,:]\n        dm4[j,:,i,:,k,:,l,:] = jikl\n        return jikl\n    def transpose12(ijkl, i, j, k, l):\n        ikjl = ijkl.transpose(0,2,1,3)\n        ikjl[:,:,k] -= dm3[i,:,j,:,l,:]\n        ikjl[:,j,:] += dm3[i,:,k,:,l,:]\n        dm4[i,:,k,:,j,:,l,:] = ikjl\n        return ikjl\n    def transpose23(ijkl, i, j, k, l):\n        ijlk = ijkl.transpose(0,1,3,2)\n        ijlk[:,:,:,l] -= dm3[i,:,j,:,k,:]\n        ijlk[:,:,k,:] += dm3[i,:,j,:,l,:]\n        dm4[i,:,j,:,l,:,k,:] = ijlk\n        return ijlk\n    def chain(ijkl, i, j, k, l):\n        tmp = transpose23(ijkl, i, j, k, l)\n        tmp = transpose12(tmp, i, j, l, k)\n        tmp = transpose23(tmp, i, l, j, k)\n        tmp = transpose12(tmp, i, l, k, j)\n        tmp = transpose23(tmp, i, k, l, j)\n        return tmp\n\n# ijkl -> ijlk -> iljk -> ilkj -> iklj -> ikjl\n#      -> jikl -> jilk -> jlik -> jlki -> jkli -> jkil\n#(ikjl)-> kijl -> kilj -> klij -> klji -> kjli -> kjil\n#(iljk)-> lijk -> likj -> lkij -> lkji -> ljki -> ljik\n    norb = dm3.shape[0]\n    for i in range(norb):\n        for k in range(i+1):\n            for j in range(k+1):\n                for l in range(j+1):\n                    tmp = chain(dm4[i,:,j,:,k,:,l,:].copy(), i, j, k, l)\n                    tmp = transpose01(tmp, i, k, j, l)\n                    tmp = chain(tmp, k, i, j, l)\n                    tmp = transpose01(dm4[i,:,j,:,k,:,l,:].copy(), i, j, k, l)\n                    tmp = chain(tmp, j, i, k, l)\n                    tmp = transpose01(dm4[i,:,l,:,j,:,k,:].copy(), i, l, j, k)\n                    tmp = chain(tmp, l, i, j, k)\n    return dm4\n\ndef reorder_dm12(rdm1, rdm2, inplace=True):\n    return reorder_rdm(rdm1, rdm2, inplace)\n\n# <p^+ q r^+ s t^+ u> => <p^+ r^+ t^+ u s q>\n# rdm2[p,q,r,s] is <p^+ q r^+ s>\ndef reorder_dm123(rdm1, rdm2, rdm3, inplace=True):\n    rdm1, rdm2 = reorder_rdm(rdm1, rdm2, inplace)\n    if not inplace:\n        rdm3 = rdm3.copy()\n    norb = rdm1.shape[0]\n    for q in range(norb):\n        rdm3[:,q,q,:,:,:] -= rdm2\n        rdm3[:,:,:,q,q,:] -= rdm2\n        rdm3[:,q,:,:,q,:] -= rdm2.transpose(0,2,3,1)\n        for s in range(norb):\n            rdm3[:,q,q,s,s,:] -= rdm1.T\n    return rdm1, rdm2, rdm3\n\n\n# <p^+ q r^+ s t^+ u w^+ v> => <p^+ r^+ t^+ w^+ v u s q>\n# rdm2, rdm3 are the (reordered) standard 2-pdm and 3-pdm\ndef reorder_dm1234(rdm1, rdm2, rdm3, rdm4, inplace=True):\n    rdm1, rdm2, rdm3 = reorder_dm123(rdm1, rdm2, rdm3, inplace)\n    if not inplace:\n        rdm4 = rdm4.copy()\n    norb = rdm1.shape[0]\n    for q in range(norb):\n        rdm4[:,q,:,:,:,:,q,:] -= rdm3.transpose(0,2,3,4,5,1)\n        rdm4[:,:,:,q,:,:,q,:] -= rdm3.transpose(0,1,2,4,5,3)\n        rdm4[:,:,:,:,:,q,q,:] -= rdm3\n        rdm4[:,q,:,:,q,:,:,:] -= rdm3.transpose(0,2,3,1,4,5)\n        rdm4[:,:,:,q,q,:,:,:] -= rdm3\n        rdm4[:,q,q,:,:,:,:,:] -= rdm3\n        for s in range(norb):\n            rdm4[:,q,q,s,:,:,s,:] -= rdm2.transpose(0,2,3,1)\n            rdm4[:,q,q,:,:,s,s,:] -= rdm2\n            rdm4[:,q,:,:,q,s,s,:] -= rdm2.transpose(0,2,3,1)\n            rdm4[:,q,:,s,q,:,s,:] -= rdm2.transpose(0,2,1,3)\n            rdm4[:,q,:,s,s,:,q,:] -= rdm2.transpose(0,2,3,1)\n            rdm4[:,:,:,s,s,q,q,:] -= rdm2\n            rdm4[:,q,q,s,s,:,:,:] -= rdm2\n            for u in range(norb):\n                rdm4[:,q,q,s,s,u,u,:] -= rdm1.T\n    return rdm1, rdm2, rdm3, rdm4\n\n", "meta": {"hexsha": "6ad5d23863301d1213ad8a30137b5f05b3d87132", "size": 14999, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/fci/rdm.py", "max_stars_repo_name": "crisely09/pyscf", "max_stars_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-03T12:32:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T08:19:02.000Z", "max_issues_repo_path": "pyscf/fci/rdm.py", "max_issues_repo_name": "crisely09/pyscf", "max_issues_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2018-08-22T19:44:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-09T10:02:36.000Z", "max_forks_repo_path": "pyscf/fci/rdm.py", "max_forks_repo_name": "crisely09/pyscf", "max_forks_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-02-14T16:28:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-12T16:40:30.000Z", "avg_line_length": 41.7799442897, "max_line_length": 104, "alphanum_fraction": 0.5753716914, "include": true, "reason": "import numpy", "num_tokens": 5034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.1842274071309516}}
{"text": "#!/usr/bin/env python3\n# -*- encoding: utf-8 -*-\n\n'''Functions to quickly simulate the observation of the sky through the year.\n\nWe call *scanning strategy* the way the instrument changes its orientation\ntowards the sky with the passing of time. It is encoded as a set of times and\nsky coordinates, and it depends on the way the Earth rotates and the instrument\nwheels are operated.\n\nStripeline offers a set of utilities to generate a scanning strategy, given a\nset of instrumental parameters. These are used to determine which configuration\nhas the most desirable properties in terms of the scientific outcome (sky\ncoverage, integration time per pixel, etc.).\n\nThe function which creates pointing information from a description of the\nscanning strategy is :meth:`~stripeline.scanning.generate_pointings`, which\ndepends on the class :class:`~stripeline.scanning.ScanningStrategy`. This\nfunction is `quick`, in the sense that it does not take into account many\ntime-dependent effects (like the nutation of the Earth's axis), it just models\nthe Earth as a sphere rotating around a fixed axis with constant angular\nvelocity. To make a more realistic simulation, see Sect.\n:ref:`accurate-generation-of-pointing-timelines`.\n\nHere is a short example which shows how to use these facilities::\n\n    import stripeline.scanning as sc\n\n    def save_tod(pointings,\n                 scanning: sc.ScanningStrategy,\n                 dir_vec,\n                 index: int):\n        # Here you can save/use \"pointings\", which is a 4xn matrix\n        pass\n\n    scanning = sc.ScanningStrategy(wheel3_rpm=1.0,\n                                   wheel2_angle0_deg=45.0,\n                                   latitude_deg=28.3,\n                                   overall_time_s=3600.0,\n                                   sampling_frequency_hz=50.0)\n    sc.generate_pointings(scanning=scanning,\n                          dir_vec=[0., 0., 1.],\n                          num_of_chunks=1,\n                          tod_callback=save_tod)\n\nThis module provides the class :class:`~stripeline.scanning.TodWriter`, which\nsaves pointing information in FITS files.\n'''\n\nimport logging as log\nimport io\nimport os.path\nimport sys\nfrom typing import Any\nimport click\nimport healpy\nimport numpy as np\nfrom astropy.io import fits\nimport yaml\n\nimport stripeline.quaternions as q\nimport stripeline.timetools as timetools\n\n\nclass ScanningStrategy:\n    '''Parameters of a sky scanning strategy.\n\n    This class holds together a number of information needed to define a\n    strategy to scan the sky. It works like a named tuple, but it allows\n    members to be changed after the object has been created.\n\n    The following parameters are accepted:\n\n    - `wheel1_rpm`: rotations per minute of the first wheel\n        (focal plane wheel);\n    - `wheel3_rpm`: rotations per minute of the third wheel\n        (ground wheel, also called «azimuth wheel»);\n    - `wheel1_angle0_deg`: angle of the first wheel when the simulation\n        starts (degrees);\n    - `wheel2_angle0_deg`: angle of the second wheel (elevation wheel)\n        when the simulation starts (degrees);\n    - `wheel3_angle0_deg`: angle of the third wheel when the simulation\n        starts (degrees);\n    - `latitude_deg`: latitude (in degrees) of the observing site;\n    - `overall_time_s`: overall duration of the observation (in seconds);\n    - `sampling_frequency_hz`: sampling frequency of the detector (in Hz).\n\n     The class implements YAML serialization through the methods\n     :meth:`~stripeline.scanning.ScanningStrategy.load` and\n     :meth:`~stripeline.scanning.ScanningStrategy.save`.'''\n\n    def __init__(self,\n                 wheel1_rpm=0.0,\n                 wheel3_rpm=0.0,\n                 wheel1_angle0_deg=0.0,\n                 wheel2_angle0_deg=0.0,\n                 wheel3_angle0_deg=0.0,\n                 latitude_deg=0.0,\n                 overall_time_s=0.0,\n                 sampling_frequency_hz=0.0):\n        self.wheel1_rpm = wheel1_rpm\n        self.wheel3_rpm = wheel3_rpm\n        self.wheel1_angle0_deg = wheel1_angle0_deg\n        self.wheel2_angle0_deg = wheel2_angle0_deg\n        self.wheel3_angle0_deg = wheel3_angle0_deg\n        self.latitude_deg = latitude_deg\n        self.overall_time_s = overall_time_s\n        self.sampling_frequency_hz = sampling_frequency_hz\n\n    def validate(self):\n        '''Raise a ValueError if the scanning strategy is invalid.'''\n\n        if not isinstance(self.wheel1_rpm, float) or self.wheel1_rpm < 0.0:\n            raise ValueError('invalid value for wheel1_rpm ({0})'\n                             .format(self.wheel1_rpm))\n\n        if not isinstance(self.wheel3_rpm, float) or self.wheel3_rpm < 0.0:\n            raise ValueError('invalid value for wheel3_rpm ({0})'\n                             .format(self.wheel3_rpm))\n\n        if not isinstance(self.wheel1_angle0_deg, float):\n            raise ValueError('invalid value for wheel1_angle0_deg ({0})'\n                             .format(self.wheel1_angle0_deg))\n\n        if not isinstance(self.wheel2_angle0_deg, float):\n            raise ValueError('invalid value for wheel2_angle0_deg ({0})'\n                             .format(self.wheel2_angle0_deg))\n\n        if not isinstance(self.wheel3_angle0_deg, float):\n            raise ValueError('invalid value for wheel3_angle0_deg ({0})'\n                             .format(self.wheel3_angle0_deg))\n\n        if not isinstance(self.latitude_deg, float) or \\\n                self.latitude_deg < 0.0 or self.latitude_deg > 90.0:\n            raise ValueError('invalid value for latitude_deg ({0})'\n                             .format(self.latitude_deg))\n\n        if not isinstance(self.sampling_frequency_hz, float) or \\\n                self.sampling_frequency_hz <= 0.0:\n            raise ValueError('invalid value for sampling_frequency_hz ({0})'\n                             .format(self.sampling_frequency_hz))\n\n    def save(self, stream):\n        '''Write a YAML representation of `self` into the stream.'''\n\n        yaml.dump({'wheel1_rpm': self.wheel1_rpm,\n                   'wheel3_rpm': self.wheel3_rpm,\n                   'wheel1_angle0_deg': self.wheel1_angle0_deg,\n                   'wheel2_angle0_deg': self.wheel2_angle0_deg,\n                   'wheel3_angle0_deg': self.wheel3_angle0_deg,\n                   'latitude_deg': self.latitude_deg,\n                   'overall_time_s': self.overall_time_s,\n                   'sampling_frequency_hz': self.sampling_frequency_hz},\n                  stream=stream,\n                  explicit_start=True,\n                  explicit_end=True)\n\n    def load(self, input):\n        '''Build a :class:`ScanningStrategy` object from its YAML representation.\n\n        The parameter \"input\" can either be a file object, a dictionary or a string.'''\n        if isinstance(input, dict):\n            d = input\n        else:\n            d = yaml.load(input)\n\n        self.wheel1_rpm = d['wheel1_rpm']\n        self.wheel3_rpm = d['wheel3_rpm']\n        self.wheel1_angle0_deg = d['wheel1_angle0_deg']\n        self.wheel2_angle0_deg = d['wheel2_angle0_deg']\n        self.wheel3_angle0_deg = d['wheel3_angle0_deg']\n        self.latitude_deg = d['latitude_deg']\n        self.overall_time_s = d['overall_time_s']\n        self.sampling_frequency_hz = d['sampling_frequency_hz']\n\n\ndef time_to_rot_angle(time_vec: Any, rpm: float) -> Any:\n    '''Return a set of angles given a set of times and the RPMs.\n\n    RPM is Rotation Per Minute, of course!'''\n\n    assert rpm >= 0.0\n\n    if rpm == 0.0:\n        return np.zeros_like(time_vec)\n    else:\n        return 2 * np.pi * time_vec * (rpm / 60.0)\n\n\ndef generate_pointings(scanning: ScanningStrategy,\n                       dir_vec=[0, 0, 1],\n                       num_of_chunks=1,\n                       tod_callback=None,\n                       time0_s=0.0):\n    '''Generate a set of pointing directions.\n\n    Simulate the scanning of the sky with the parameters provided in `scanning`,\n    `dir_vec`. The `tod_callback` parameter is a function which is called\n    whenever a new chunk of samples has been calculated. (It is fine if it is\n    set to ``None``: in this case, pointings will be silently thrown away once\n    they have been computed.) The value `time0_s` specifies the time of the\n    first sample.\n\n    The callback must accept the following parameters:\n\n    - `pointings`: 4xn matrix containing the time (in seconds), colatitude (in\n      radians), longitude (ditto), and polarization angle (ditto), each in its\n      own column;\n    - `scanning`: copy of the parameter passed to this function;\n    - `dir_vec`: copy of the parameter passed to this function;\n    - `index`: counter which keeps track of how many times the callback has been\n      called, starting from 0.\n    '''\n    x_vec = np.array([1, 0, 0])\n    z_vec = np.array([0, 0, 1])\n\n    chunks = timetools.split_time_range(time_length=scanning.overall_time_s,\n                                        num_of_chunks=num_of_chunks,\n                                        sampfreq=scanning.sampling_frequency_hz,\n                                        time0=time0_s)\n    for chunk_idx, cur_chunk in enumerate(chunks):\n        start_time, samples_per_chunk = cur_chunk\n\n        time_vec = start_time + \\\n            np.arange(samples_per_chunk) / scanning.sampling_frequency_hz\n\n        # Determine the angle of each wheel (the second wheel is the simplest)\n        wheel1_angle = np.deg2rad(scanning.wheel1_angle0_deg) + time_to_rot_angle(\n            time_vec, scanning.wheel1_rpm)\n        wheel3_angle = np.deg2rad(scanning.wheel3_angle0_deg) + time_to_rot_angle(\n            time_vec, scanning.wheel3_rpm)\n\n        tile_dir = np.reshape(np.tile(dir_vec, time_vec.size), (-1, 3))\n        tile_x = np.reshape(np.tile(x_vec, time_vec.size), (-1, 3))\n        tile_z = np.reshape(np.tile(z_vec, time_vec.size), (-1, 3))\n        # Build the wheel quaternions\n        qwheel1 = q.qfromaxisangle(tile_dir, wheel1_angle)\n        qwheel2 = np.reshape(\n            np.tile(\n                q.qfromaxisangle(\n                    [x_vec], [np.deg2rad(scanning.wheel2_angle0_deg)]),\n                time_vec.size), (-1, 4))\n        qwheel3 = q.qfromaxisangle(tile_z, wheel3_angle)\n\n        # This is in the ground's reference frame\n        ground_quat = q.qmul(qwheel3, q.qmul(qwheel2, qwheel1))\n\n        # Now we convert from the ground reference frame to the Earth's centre\n        location_quat = np.reshape(\n            np.tile(\n                q.qfromaxisangle(\n                    [x_vec], [np.deg2rad(90.0 - scanning.latitude_deg)]),\n                time_vec.size), (-1, 4))\n        earth_rot_quat = q.qfromaxisangle(tile_z,\n                                          2 * np.pi * time_vec / 86400.0)\n        quat = q.qmul(earth_rot_quat, q.qmul(location_quat, ground_quat))\n        dirs = q.qrotate(tile_dir, quat)\n        poldirs = q.qrotate(tile_x, quat)\n        theta, phi = healpy.vec2ang(dirs)\n\n        # The north direction for a vector v is just -dv/dtheta, as\n        # theta is the colatitude and moves along the meridian\n        thetapol, phipol = healpy.vec2ang(dirs)\n        northdir = np.column_stack((-np.cos(thetapol) * np.cos(phipol),\n                                    -np.cos(thetapol) * np.sin(phipol),\n                                    np.sin(thetapol)))\n\n        # The counterclockwise/clockwise measurement of the polarization angle\n        # is determined by the ordering of the terms in the call to \"np.cross\"\n        cos_psi = np.clip(np.sum(northdir * poldirs, axis=1), -1.0, 1.0)\n        cross = np.cross(northdir, poldirs)\n        sin_psi = np.clip(np.sum(cross * cross, axis=1), -1.0, 1.0)\n        psi = np.arctan2(sin_psi, cos_psi)\n        psi *= np.sign(np.sum(cross * dirs, axis=1))\n\n        if tod_callback is not None:\n            tod_callback(pointings=np.column_stack((time_vec, theta, phi, psi)),\n                         scanning=scanning,\n                         dir_vec=dir_vec,\n                         index=chunk_idx)\n\n\nclass TodWriter:\n    '''Write a TOD.\n\n    This class has been designed to be used together with\n    :meth:`~stripeline.scanning.generate_pointings`.\n\n    You create an instance of the object and then pass it to\n    :meth:`~stripeline.scanning.generate_pointings`, like in the following way::\n\n        writer = TodWriter(outdir='/storage',\n                           file_name_mask='mytod_{index:04d}.fits.gz')\n        generate_pointings(..., tod_callback=writer)\n\n    As you can see, you can use the `index` key in the `file_name_mask`\n    parameter to separate the files in chunks. The number of times `writer` is\n    called depends on the parameter `num_of_chunks` passed to\n    :meth:`~stripeline.scanning.generate_pointings`.\n    '''\n\n    def __init__(self,\n                 outdir='.',\n                 file_name_mask='pointings_{index:04d}.fits'):\n        self.outdir = outdir\n        self.file_name_mask = file_name_mask\n\n    def __call__(self,\n                 pointings,\n                 scanning: ScanningStrategy,\n                 dir_vec,\n                 index: int):\n        ''' Save a TOD into a FITS file'''\n\n        file_name = os.path.join(self.outdir,\n                                 self.file_name_mask.format(index=index))\n        cols = [\n            fits.Column(name=name, format=fmt, unit=unit, array=arr)\n            for name, fmt, unit, arr in (('TIME', 'D', 's', pointings[:, 0]),\n                                         ('THETA', 'D', 'rad',\n                                          pointings[:, 1]),\n                                         ('PHI', 'D', 'rad', pointings[:, 2]),\n                                         ('PSI', 'D', 'rad', pointings[:, 3]))\n        ]\n        hdu = fits.BinTableHDU.from_columns(cols, name='TOD')\n        hdu.header['FSTTIME'] = (\n            pointings[0, 0], 'Time of the first sample in the file [s]')\n        hdu.header['LSTTIME'] = (\n            pointings[-1, 0], 'Time of the last sample in the file [s]')\n        hdu.header['DIRX'] = (dir_vec[0], 'X component of the beam axis')\n        hdu.header['DIRY'] = (dir_vec[1], 'Y component of the beam axis')\n        hdu.header['DIRZ'] = (dir_vec[2], 'Z component of the beam axis')\n        hdu.header['SAMPFREQ'] = (scanning.sampling_frequency_hz,\n                                  'Sampling frequency [Hz]')\n        hdu.header['SITELAT'] = (\n            scanning.latitude_deg, 'Latitude of the site [deg]')\n        hdu.header['W1RPM'] = (scanning.wheel1_rpm,\n                               'Angular speed of wheel 1 [rpm]')\n        hdu.header['W3RPM'] = (scanning.wheel3_rpm,\n                               'Angular speed of wheel 3 [rpm]')\n        hdu.header['W1ANG0'] = (\n            scanning.wheel1_angle0_deg, 'Start angle for wheel 1 [deg]')\n        hdu.header['W2ANG0'] = (\n            scanning.wheel2_angle0_deg, 'Start angle for wheel 2 [deg]')\n        hdu.header['W3ANG0'] = (\n            scanning.wheel3_angle0_deg, 'Start angle for wheel 3 [deg]')\n        hdu.header['TIMELEN'] = (\n            scanning.overall_time_s, 'Time span of the *whole* sim [s]')\n        hdu.header['TODIDX'] = (index, '0-based index of this file')\n\n        with io.StringIO() as primary_data:\n            scanning.save(stream=primary_data)\n            raw_bytes = np.array(list(primary_data.getvalue().encode('utf-8')))\n            primhdu = fits.PrimaryHDU(data=raw_bytes)\n\n        hdulist = fits.HDUList([primhdu, hdu])\n        hdulist.writeto(file_name, clobber=True)\n        log.info('file \"%s\" written successfully', file_name)\n\n\n@click.command()\n@click.argument('output_path')\n@click.option('--input-file',\n              type=str,\n              default=None,\n              help='Path to a YAML file containing the parameters of the '\n              'scanning strategy')\n@click.option('--wheel1-rpm',\n              'wheel1_rpm',\n              type=float,\n              default=None,\n              help='Rotations per minute of the first (focal plane) wheel')\n@click.option('--wheel3-rpm',\n              'wheel3_rpm',\n              type=float,\n              default=None,\n              help='Rotations per minute of the third (ground) wheel')\n@click.option('--wheel1-angle0',\n              'wheel1_angle0',\n              type=float,\n              default=None,\n              help='Initial angle of the first (focal plane) wheel [deg]')\n@click.option('--wheel2-angle0',\n              'wheel2_angle0',\n              type=float,\n              default=None,\n              help='Initial angle of the second (elevation) wheel [deg]')\n@click.option('--wheel3-angle0',\n              'wheel3_angle0',\n              type=float,\n              default=None,\n              help='Initial angle of the third (ground) wheel [deg]')\n@click.option('--latitude',\n              'latitude',\n              type=float,\n              default=None,\n              help='Latitude of the observing site (North is positive) [deg]')\n@click.option('--time',\n              'time_length',\n              type=float,\n              default=None,\n              help='Amount of observation time [s]')\n@click.option('--samp',\n              'sampfreq',\n              type=float,\n              default=None,\n              help='Sampling frequency [Hz]')\n@click.option('--num-of-chunks',\n              '-n',\n              type=int,\n              default=1,\n              help='Number of chunks for splitting the computation')\n@click.option('--direction',\n              type=str,\n              default='0,0,1',\n              help='Pointing direction of the main beam with respect to '\n              'the focal plane (3D vector, written as a comma-separated list '\n              'of 3 numbers)')\ndef main(output_path, input_file, wheel1_rpm, wheel3_rpm, wheel1_angle0, wheel2_angle0,\n         wheel3_angle0, latitude, time_length, sampfreq, num_of_chunks,\n         direction):\n    '''This function is called when the script is ran from the command line.'''\n\n    log.basicConfig(\n        level=log.INFO, format='%(asctime)s %(levelname)s] %(message)s')\n\n    num_of_samples = int(time_length * sampfreq)\n    log.info('%d samples will be processed in %d steps', num_of_samples,\n             num_of_chunks)\n\n    try:\n        direction = np.array([float(x) for x in direction.split(',')])\n        if len(direction) != 3:\n            raise ValueError()\n    except ValueError:\n        log.error('pointing direction must be a comma-separated list of '\n                  'three floating-point numbers (es., \"0,0,1\")')\n        sys.exit(1)\n\n    scanning = ScanningStrategy()\n    if input_file is not None:\n        with open(input_file, 'rt') as f:\n            scanning.load(f)\n\n    if wheel1_rpm is not None:\n        scanning.wheel1_rpm = wheel1_rpm\n    if wheel3_rpm is not None:\n        scanning.wheel3_rpm = wheel3_rpm\n    if wheel1_angle0 is not None:\n        scanning.wheel1_angle0_deg = wheel1_angle0\n    if wheel2_angle0 is not None:\n        scanning.wheel2_angle0_deg = wheel2_angle0\n    if wheel3_angle0 is not None:\n        scanning.wheel3_angle0_deg = wheel3_angle0\n    if latitude is not None:\n        scanning.latitude_deg = latitude\n    if time_length is not None:\n        scanning.overall_time_s = time_length\n    if sampfreq is not None:\n        scanning.sampling_frequency_hz = sampfreq\n\n    scanning.validate()\n\n    writer = TodWriter(output_path)\n    generate_pointings(scanning=scanning,\n                       dir_vec=direction,\n                       num_of_chunks=num_of_chunks,\n                       tod_callback=writer)\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "97d597973ad50497f49ed5c543dd8d480d195274", "size": 19550, "ext": "py", "lang": "Python", "max_stars_repo_path": "stripeline/scanning.py", "max_stars_repo_name": "ziotom78/stripsim", "max_stars_repo_head_hexsha": "1bd6dd29290a78cf4cd7971b0fb03d5544cd2b11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stripeline/scanning.py", "max_issues_repo_name": "ziotom78/stripsim", "max_issues_repo_head_hexsha": "1bd6dd29290a78cf4cd7971b0fb03d5544cd2b11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-05-29T10:10:37.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-29T13:11:27.000Z", "max_forks_repo_path": "stripeline/scanning.py", "max_forks_repo_name": "ziotom78/stripsim", "max_forks_repo_head_hexsha": "1bd6dd29290a78cf4cd7971b0fb03d5544cd2b11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3319238901, "max_line_length": 87, "alphanum_fraction": 0.6026598465, "include": true, "reason": "import numpy,from astropy", "num_tokens": 4561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.18422740584962996}}
{"text": "# coding: utf-8\n# pylint: disable=invalid-name, no-member, arguments-differ\n\"\"\" EIT protocol \"\"\"\n# Copyright (c) Benyuan Liu. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\nfrom __future__ import absolute_import, division, print_function\n\nfrom dataclasses import dataclass\nfrom typing import Union\n\nimport numpy as np\n\n\n@dataclass\nclass PyEITProtocol:\n    \"\"\"\n    EIT Protocol buid-in protocol object\n\n    \"\"\"\n\n    ex_mat: np.ndarray\n    meas_mat: np.ndarray\n\n    def __post_init__(self) -> None:\n        \"\"\"Checking of the inputs\"\"\"\n        self.ex_mat = self._check_ex_mat(self.ex_mat)\n        self.meas_mat = self._check_meas_mat(self.meas_mat)\n\n    def _check_ex_mat(self, ex_mat: np.ndarray) -> np.ndarray:\n        \"\"\"\n        Check/init stimulation\n\n        Parameters\n        ----------\n        ex_mat : np.ndarray\n            stimulation/excitation matrix, of shape (n_exc, 2).\n            If single stimulation (ex_line) is passed only a list of length 2\n            and np.ndarray of size 2 will be treated.\n\n        Returns\n        -------\n        np.ndarray\n            stimulation matrix\n\n        Raises\n        ------\n        TypeError\n            Only accept, list of length 2, np.ndarray of size 2,\n            or np.ndarray of shape (n_exc, 2)\n        \"\"\"\n        if isinstance(ex_mat, list) and len(ex_mat) == 2:\n            # case ex_line has been passed instead of ex_mat\n            ex_mat = np.array([ex_mat]).reshape((1, 2))  # build a 2D array\n        elif isinstance(ex_mat, np.ndarray) and ex_mat.size == 2:\n            #     case ex_line np.ndarray has been passed instead of ex_mat\n            ex_mat = ex_mat.reshape((-1, 2))\n\n        if (\n            not isinstance(ex_mat, np.ndarray)\n            or ex_mat.ndim != 2\n            or ex_mat.shape[1] != 2\n        ):\n            raise TypeError(\n                f\"Wrong shape of {ex_mat=} expected an ndarray ; shape (n_exc, 2)\"\n            )\n\n        return ex_mat\n\n    def _check_meas_mat(self, meas_mat: np.ndarray) -> np.ndarray:\n        \"\"\"\n        Check measurement pattern\n\n        Parameters\n        ----------\n        n_exc : int\n            number of excitations/stimulations\n        meas_pattern : np.ndarray, optional\n           measurements pattern / subtract_row pairs [N, M] to check; shape (n_exc, n_meas_per_exc, 2)\n\n        Returns\n        -------\n        np.ndarray\n            measurements pattern / subtract_row pairs [N, M]; shape (n_exc, n_meas_per_exc, 2)\n\n        Raises\n        ------\n        TypeError\n            raised if meas_pattern is not a np.ndarray of shape (n_exc, : , 2)\n        \"\"\"\n        if not isinstance(meas_mat, np.ndarray):\n            raise TypeError(\n                f\"Wrong type of {meas_mat=}, expected an ndarray; shape ({self.n_exc}, n_meas_per_exc, 2)\"\n            )\n        # test shape is something like (n_exc, :, 2)\n        if meas_mat.ndim != 3 or meas_mat.shape[::2] != (self.n_exc, 2):\n            raise TypeError(\n                f\"Wrong shape of {meas_mat=}: {meas_mat.shape=}, expected an ndarray; shape ({self.n_exc}, n_meas_per_exc, 2)\"\n            )\n\n        return meas_mat\n\n    @property\n    def n_exc(self) -> int:\n        \"\"\"\n        Returns\n        -------\n        int\n            number of excitation\n        \"\"\"\n        return self.ex_mat.shape[0]\n\n    @property\n    def n_meas(self) -> int:\n        \"\"\"\n        Returns\n        -------\n        int\n            number of measurements per excitations\n        \"\"\"\n        return self.meas_mat.shape[1]\n\n    @property\n    def n_meas_tot(self) -> int:\n        \"\"\"\n        Returns\n        -------\n        int\n            total amount of measurements\n        \"\"\"\n        return self.n_meas * self.n_exc\n\n    @property\n    def n_el(self) -> int:\n        \"\"\"\n        Returns\n        -------\n        int\n            number of electrodes used in the excitation and\n        \"\"\"\n        return max(max(self.ex_mat.flatten()), max(self.meas_mat.flatten())) + 1\n\n\ndef create(\n    n_el: int = 16,\n    dist_exc: Union[int, list[int]] = 1,\n    step_meas: int = 1,\n    parser_meas: Union[str, list[str]] = \"std\",\n) -> PyEITProtocol:\n    \"\"\"\n    Return an EIT protocol, comprising an excitation and a measuremnet pattern\n\n    Parameters\n    ----------\n    n_el : int, optional\n        number of total electrodes, by default 16\n    dist_exc : Union[int, list[int]], optional\n        distance (number of electrodes) of A to B, by default 1\n        For 'adjacent'- or 'neighbore'-mode (default) use `1` , and\n        for 'apposition'-mode use `n_el/2`. (see `build_exc_pattern`)\n        if a list of integer is passed the excitation will bee stacked together.\n    step_meas : int, optional\n    measurement method (two adjacent electrodes are used for measuring), by default 1 (adjacent).\n        (see `build_meas_pattern`)\n    parser_meas : Union[str, list[str]], optional\n        parsing the format of each frame in measurement/file, by default 'std'.\n        (see `build_meas_pattern`)\n\n    Returns\n    -------\n    PyEITProtocol\n        EIT protocol object\n\n    Raises\n    ------\n    TypeError\n        if dist_exc is not list or an int\n    \"\"\"\n    if isinstance(dist_exc, int):\n        dist_exc = [dist_exc]\n\n    if not isinstance(dist_exc, list):\n        raise TypeError(f\"{dist_exc=}; {type(dist_exc)=} should be a list[int]\")\n\n    _ex_mat = [build_exc_pattern_std(n_el, dist) for dist in dist_exc]\n    ex_mat = np.vstack(_ex_mat)\n\n    meas_mat = build_meas_pattern_std(ex_mat, n_el, step_meas, parser_meas)\n    return PyEITProtocol(ex_mat, meas_mat)\n\n\ndef build_meas_pattern_std(\n    ex_mat: np.ndarray,\n    n_el: int = 16,\n    step: int = 1,\n    parser: Union[str, list[str]] = \"std\",\n) -> np.ndarray:\n    \"\"\"\n    Build the measurement pattern (subtract_row-voltage pairs [N, M])\n    for all excitations on boundary electrodes.\n\n    we direct operate on measurements or Jacobian on electrodes,\n    so, we can use LOCAL index in this module, do not require el_pos.\n\n    Notes\n    -----\n    ABMN Model.\n    A: current driving electrode,\n    B: current sink,\n    M, N: boundary electrodes, where v_diff = v_n - v_m.\n\n    Parameters\n    ----------\n    ex_mat : np.ndarray\n        Nx2 array, [positive electrode, negative electrode]. ; shape (n_exc, 2)\n    n_el : int, optional\n        number of total electrodes, by default 16\n    step : int, optional\n        measurement method (two adjacent electrodes are used for measuring), by default 1 (adjacent)\n    parser : Union[str, list[str]], optional\n        parsing the format of each frame in measurement/file, by default 'std'\n        if parser contains 'fmmu', or 'rotate_meas' then data are trimmed,\n        boundary voltage measurements are re-indexed and rotated,\n        start from the positive stimulus electrode start index 'A'.\n        if parser contains 'std', or 'no_rotate_meas' then data are trimmed,\n        the start index (i) of boundary voltage measurements is always 0.\n        if parser contains 'meas_current', the measurements on current carrying\n        electrodes are allowed. Otherwise the measurements on current carrying\n        electrodes are discarded (like 'no_meas_current' option in EIDORS3D).\n\n    Returns\n    -------\n    np.ndarray\n        measurements pattern / subtract_row pairs [N, M]; shape (n_exc, n_meas_per_exc, 2)\n    \"\"\"\n    if not isinstance(parser, list):  # transform parser into list\n        parser = [parser]\n    meas_current = \"meas_current\" in parser\n    fmmu_rotate = any(p in (\"fmmu\", \"rotate_meas\") for p in parser)\n\n    diff_op = []\n    for ex_line in ex_mat:\n        a, b = ex_line[0], ex_line[1]\n        i0 = a if fmmu_rotate else 0\n        m = (i0 + np.arange(n_el)) % n_el\n        n = (m + step) % n_el\n        meas_pattern = np.vstack([n, m]).T\n\n        if not meas_current:\n            diff_keep = np.logical_and.reduce((m != a, m != b, n != a, n != b))\n            meas_pattern = meas_pattern[diff_keep]\n\n        diff_op.append(meas_pattern)\n\n    return np.array(diff_op)\n\n\ndef build_exc_pattern_std(n_el: int = 16, dist: int = 1) -> np.ndarray:\n    \"\"\"\n    Generate scan matrix, `ex_mat` ( or excitation pattern), see notes\n\n    Parameters\n    ----------\n    n_el : int, optional\n        number of electrodes, by default 16\n    dist : int, optional\n        distance (number of electrodes) of A to B, by default 1\n        For 'adjacent'- or 'neighbore'-mode (default) use `1` , and\n        for 'apposition'-mode use `n_el/2` (see Examples).\n\n    Returns\n    -------\n    np.ndarray\n        stimulation matrix; shape (n_exc, 2)\n\n    Notes\n    -----\n        - in the scan of EIT (or stimulation matrix), we use 4-electrodes\n        mode, where A, B are used as positive and negative stimulation\n        electrodes and M, N are used as voltage measurements.\n        - `1` (A) for positive current injection, `-1` (B) for negative current\n        sink\n\n    Examples\n    --------\n        n_el=16\n        if mode=='neighbore':\n            ex_mat = build_exc_pattern(n_el=n_el)\n        elif mode=='apposition':\n            ex_mat = build_exc_pattern(dist=n_el/2)\n\n    WARNING\n    -------\n        `ex_mat` is a local index, where it is ranged from 0...15, within the\n        range of the number of electrodes. In FEM applications, you should\n        convert `ex_mat` to global index using the (global) `el_pos` parameters.\n    \"\"\"\n    return np.array([[i, np.mod(i + dist, n_el)] for i in range(n_el)])\n", "meta": {"hexsha": "e22b0910b3281ba337b17bd19a3eb8aa3df29472", "size": 9431, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyeit/eit/protocol.py", "max_stars_repo_name": "DavidMetzIMT/pyEIT", "max_stars_repo_head_hexsha": "a3c64f7b869e7a00a102fc93feea4999c8bed6d1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyeit/eit/protocol.py", "max_issues_repo_name": "DavidMetzIMT/pyEIT", "max_issues_repo_head_hexsha": "a3c64f7b869e7a00a102fc93feea4999c8bed6d1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyeit/eit/protocol.py", "max_forks_repo_name": "DavidMetzIMT/pyEIT", "max_forks_repo_head_hexsha": "a3c64f7b869e7a00a102fc93feea4999c8bed6d1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6476510067, "max_line_length": 126, "alphanum_fraction": 0.5987700138, "include": true, "reason": "import numpy", "num_tokens": 2332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.18422740347757832}}
{"text": "import os\nimport time\nimport uuid\nimport yaml\nimport logging\nimport shutil\nimport numpy as np\nimport pandas as pd\nimport multiprocessing as mp\nfrom functools import partial\nfrom astropy.time import Time\n\nfrom .config import Config\nfrom .config import Configuration\nfrom .clusters import find_clusters, filter_clusters_by_length\nfrom .cell import Cell\nfrom .orbit import TestOrbit\nfrom .orbits import Orbits\nfrom .orbits import generateEphemeris\nfrom .orbits import initialOrbitDetermination\nfrom .orbits import differentialCorrection\nfrom .orbits import mergeAndExtendOrbits\nfrom .observatories import getObserverState\nfrom .utils import _initWorker\nfrom .utils import _checkParallel\n\nos.environ['OPENBLAS_NUM_THREADS'] = '1'\nos.environ['MKL_NUM_THREADS'] = '1'\n\nlogger = logging.getLogger(\"thor\")\n\n__all__ = [\n    \"rangeAndShift_worker\",\n    \"rangeAndShift\",\n    \"clusterVelocity\",\n    \"clusterVelocity_worker\",\n    \"clusterAndLink\",\n    \"runTHOROrbit\",\n    \"runTHOR\",\n]\n\ndef rangeAndShift_worker(observations, ephemeris, cell_area=10):\n\n    assert len(observations[\"mjd_utc\"].unique()) == 1\n    assert len(ephemeris[\"mjd_utc\"].unique()) == 1\n    assert observations[\"mjd_utc\"].unique()[0] == ephemeris[\"mjd_utc\"].unique()[0]\n    observation_time = observations[\"mjd_utc\"].unique()[0]\n\n    # Create Cell centered on the sky-plane location of the\n    # test orbit\n    cell = Cell(\n        ephemeris[[\"RA_deg\", \"Dec_deg\"]].values[0],\n        observation_time,\n        area=cell_area,\n    )\n\n    # Grab observations within cell\n    cell.getObservations(observations)\n\n    if len(cell.observations) != 0:\n\n        # Create test orbit with state of orbit at visit time\n        test_orbit = TestOrbit(\n            ephemeris[[\"obj_x\", \"obj_y\", \"obj_z\", \"obj_vx\", \"obj_vy\", \"obj_vz\"]].values[0],\n            observation_time\n        )\n\n        # Prepare rotation matrices\n        test_orbit.prepare()\n\n        # Apply rotation matrices and transform observations into the orbit's\n        # frame of motion.\n        test_orbit.applyToObservations(cell.observations)\n\n        projected_observations = cell.observations\n\n    else:\n\n        projected_observations = pd.DataFrame()\n\n    return projected_observations\n\ndef clusterVelocity(\n        obs_ids,\n        x,\n        y,\n        dt,\n        vx,\n        vy,\n        eps=0.005,\n        min_obs=5,\n        min_arc_length=1.0,\n        alg=\"hotspot_2d\",\n    ):\n    \"\"\"\n    Clusters THOR projection with different velocities\n    in the projection plane using `~scipy.cluster.DBSCAN`.\n    Parameters\n    ----------\n    obs_ids : `~numpy.ndarray' (N)\n        Observation IDs.\n    x : `~numpy.ndarray' (N)\n        Projection space x coordinate in degrees or radians.\n    y : `~numpy.ndarray' (N)\n        Projection space y coordinate in degrees or radians.\n    dt : `~numpy.ndarray' (N)\n        Change in time from 0th exposure in units of MJD.\n    vx : `~numpy.ndarray' (N)\n        Projection space x velocity in units of degrees or radians per day in MJD.\n    vy : `~numpy.ndarray' (N)\n        Projection space y velocity in units of degrees or radians per day in MJD.\n    eps : float, optional\n        The maximum distance between two samples for them to be considered\n        as in the same neighborhood.\n        See: http://scikit-learn.org/stable/modules/generated/sklearn.cluster.dbscan.html\n        [Default = 0.005]\n    min_obs : int, optional\n        The number of samples (or total weight) in a neighborhood for a\n        point to be considered as a core point. This includes the point itself.\n        See: http://scikit-learn.org/stable/modules/generated/sklearn.cluster.dbscan.html\n        [Default = 5]\n    min_arc_length : float, optional\n        Minimum arc length in units of days for a cluster to be accepted.\n\n    Returns\n    -------\n    list\n        If clusters are found, will return a list of numpy arrays containing the\n        observation IDs for each cluster. If no clusters are found, will return np.NaN.\n    \"\"\"\n    logger.debug(f\"cluster: vx={vx} vy={vy} n_obs={len(obs_ids)}\")\n    xx = x - vx * dt\n    yy = y - vy * dt\n\n    X = np.stack((xx, yy), 1)\n\n    clusters = find_clusters(X, eps, min_obs, alg=alg)\n    clusters = filter_clusters_by_length(\n        clusters, dt, min_obs, min_arc_length,\n    )\n\n    cluster_ids = []\n    for cluster in clusters:\n        cluster_ids.append(obs_ids[cluster])\n\n    if len(cluster_ids) == 0:\n        cluster_ids = np.NaN\n\n    return cluster_ids\n\n\ndef clusterVelocity_worker(\n        vx,\n        vy,\n        obs_ids=None,\n        x=None,\n        y=None,\n        dt=None,\n        eps=None,\n        min_obs=None,\n        min_arc_length=None,\n        alg=None\n    ):\n    \"\"\"\n    Helper function to multiprocess clustering.\n\n    \"\"\"\n    cluster_ids = clusterVelocity(\n        obs_ids,\n        x,\n        y,\n        dt,\n        vx,\n        vy,\n        eps=eps,\n        min_obs=min_obs,\n        min_arc_length=min_arc_length,\n        alg=alg\n    )\n    return cluster_ids\n\ndef rangeAndShift(\n        observations,\n        orbit,\n        cell_area=10,\n        backend=\"PYOORB\",\n        backend_kwargs={},\n        num_jobs=1,\n        parallel_backend=\"mp\"\n    ):\n    \"\"\"\n    Propagate the orbit to all observation times in observations. At each epoch gather a circular region of observations of size cell_area\n    centered about the location of the orbit on the sky-plane. Transform and project each of the gathered observations into\n    the frame of motion of the test orbit.\n\n    Parameters\n    ----------\n    observations : `~pandas.DataFrame`\n        DataFrame containing preprocessed observations.\n            Should contain the following columns:\n                obs_id : observation IDs\n                RA_deg : Right Ascension in degrees.\n                Dec_deg : Declination in degrees.\n                RA_sigma_deg : 1-sigma uncertainty for Right Ascension in degrees.\n                Dec_sigma_deg : 1-sigma uncertainty for Declination in degrees.\n                observatory_code : MPC observatory code\n    orbit : `~numpy.ndarray` (6)\n        Orbit to propagate. If backend is 'THOR', then these orbits must be expressed\n        as heliocentric ecliptic cartesian elements. If backend is 'PYOORB' orbits may be\n        expressed in keplerian, cometary or cartesian elements.\n    cell_area : float, optional\n        Cell's area in units of square degrees.\n        [Default = 10]\n    backend : {'THOR', 'PYOORB'}, optional\n        Which backend to use.\n    backend_kwargs : dict, optional\n        Settings and additional parameters to pass to selected\n        backend.\n    num_jobs : int, optional\n        Number of jobs to launch.\n    parallel_backend : str, optional\n        Which parallelization backend to use {'ray', 'mp'}. Defaults to using Python's multiprocessing\n        module ('mp').\n\n    Returns\n    -------\n    projected_observations : {`~pandas.DataFrame`, -1}\n        Observations dataframe (from cell.observations) with columns containing\n        projected coordinates.\n    \"\"\"\n    time_start = time.time()\n    logger.info(\"Running range and shift...\")\n    logger.info(\"Assuming r = {} au\".format(orbit.cartesian[0, :3]))\n    logger.info(\"Assuming v = {} au per day\".format(orbit.cartesian[0, 3:]))\n\n    # Build observers dictionary: keys are observatory codes with exposure times (as astropy.time objects)\n    # as values\n    observers = {}\n    for code in observations[\"observatory_code\"].unique():\n        observers[code] = Time(\n            observations[observations[\"observatory_code\"].isin([code])][\"mjd_utc\"].unique(),\n            format=\"mjd\",\n            scale=\"utc\"\n        )\n\n    # Propagate test orbit to all times in observations\n    ephemeris = generateEphemeris(\n        orbit,\n        observers,\n        backend=backend,\n        backend_kwargs=backend_kwargs,\n        chunk_size=1,\n        num_jobs=1,\n        parallel_backend=parallel_backend\n    )\n    if backend == \"FINDORB\":\n\n        observer_states = []\n        for observatory_code, observation_times in observers.items():\n            observer_states.append(\n                getObserverState(\n                    [observatory_code],\n                    observation_times,\n                    frame='ecliptic',\n                    origin='heliocenter',\n                )\n            )\n\n        observer_states = pd.concat(observer_states)\n        observer_states.reset_index(\n            inplace=True,\n            drop=True\n        )\n        ephemeris = ephemeris.join(observer_states[[\"obs_x\", \"obs_y\", \"obs_z\", \"obs_vx\", \"obs_vy\", \"obs_vz\"]])\n\n    velocity_cols = []\n    if backend != \"PYOORB\":\n        velocity_cols = [\"obs_vx\", \"obs_vy\", \"obs_vz\"]\n\n    observations = observations.merge(\n        ephemeris[[\"mjd_utc\", \"observatory_code\", \"obs_x\", \"obs_y\", \"obs_z\"] + velocity_cols],\n        left_on=[\"mjd_utc\", \"observatory_code\"],\n        right_on=[\"mjd_utc\", \"observatory_code\"]\n    )\n\n    # Split the observations into a single dataframe per unique observatory code and observation time\n    # Basically split the observations into groups of unique exposures\n    observations_grouped = observations.groupby(by=[\"observatory_code\", \"mjd_utc\"])\n    observations_split = [observations_grouped.get_group(g) for g in observations_grouped.groups]\n\n    # Do the same for the test orbit's ephemerides\n    ephemeris_grouped = ephemeris.groupby(by=[\"observatory_code\", \"mjd_utc\"])\n    ephemeris_split = [ephemeris_grouped.get_group(g) for g in ephemeris_grouped.groups]\n\n    parallel, num_workers = _checkParallel(num_jobs, parallel_backend)\n    if parallel:\n        if parallel_backend == \"ray\":\n            import ray\n            if not ray.is_initialized():\n                ray.init(address=\"auto\")\n\n            rangeAndShift_worker_ray = ray.remote(rangeAndShift_worker)\n            rangeAndShift_worker_ray = rangeAndShift_worker_ray.options(\n                num_returns=1,\n                num_cpus=1\n            )\n\n            p = []\n            for observations_i, ephemeris_i in zip(observations_split, ephemeris_split):\n                p.append(\n                    rangeAndShift_worker_ray.remote(\n                        observations_i,\n                        ephemeris_i,\n                        cell_area=cell_area\n                    )\n                )\n            projected_dfs = ray.get(p)\n\n        else: # parallel_backend == \"mp\"\n            p = mp.Pool(\n                processes=num_workers,\n                initializer=_initWorker,\n            )\n            projected_dfs = p.starmap(\n                partial(\n                    rangeAndShift_worker,\n                    cell_area=cell_area\n                ),\n                zip(\n                    observations_split,\n                    ephemeris_split,\n                )\n            )\n            p.close()\n\n    else:\n        projected_dfs = []\n        for observations_i, ephemeris_i in zip(observations_split, ephemeris_split):\n            projected_df = rangeAndShift_worker(\n                observations_i,\n                ephemeris_i,\n                cell_area=cell_area\n            )\n            projected_dfs.append(projected_df)\n\n    projected_observations = pd.concat(projected_dfs)\n    if len(projected_observations) > 0:\n        projected_observations.sort_values(by=[\"mjd_utc\", \"observatory_code\"], inplace=True)\n        projected_observations.reset_index(inplace=True, drop=True)\n    else:\n        projected_observations = pd.DataFrame(\n            columns=[\n                'obs_id', 'mjd_utc', 'RA_deg', 'Dec_deg', 'RA_sigma_deg',\n                'Dec_sigma_deg', 'observatory_code', 'obs_x', 'obs_y', 'obs_z', 'obj_x',\n                'obj_y', 'obj_z', 'theta_x_deg', 'theta_y_deg'\n            ]\n        )\n\n    time_end = time.time()\n    logger.info(\"Found {} observations.\".format(len(projected_observations)))\n    logger.info(\"Range and shift completed in {:.3f} seconds.\".format(time_end - time_start))\n\n    return projected_observations\n\ndef clusterAndLink(\n        observations,\n        vx_range=[-0.1, 0.1],\n        vy_range=[-0.1, 0.1],\n        vx_bins=100,\n        vy_bins=100,\n        vx_values=None,\n        vy_values=None,\n        eps=0.005,\n        min_obs=5,\n        min_arc_length=1.0,\n        alg=\"dbscan\",\n        num_jobs=1,\n        parallel_backend=\"mp\"\n    ):\n    \"\"\"\n    Cluster and link correctly projected (after ranging and shifting)\n    detections.\n\n    Parameters\n    ----------\n    observations : `~pandas.DataFrame`\n        DataFrame containing post-range and shift observations.\n    vx_range : {None, list or `~numpy.ndarray` (2)}\n        Maximum and minimum velocity range in x.\n        Will not be used if vx_values are specified.\n        [Default = [-0.1, 0.1]]\n    vy_range : {None, list or `~numpy.ndarray` (2)}\n        Maximum and minimum velocity range in y.\n        Will not be used if vy_values are specified.\n        [Default = [-0.1, 0.1]]\n    vx_bins : int, optional\n        Length of x-velocity grid between vx_range[0]\n        and vx_range[-1]. Will not be used if vx_values are\n        specified.\n        [Default = 100]\n    vy_bins: int, optional\n        Length of y-velocity grid between vy_range[0]\n        and vy_range[-1]. Will not be used if vy_values are\n        specified.\n        [Default = 100]\n    vx_values : {None, `~numpy.ndarray`}, optional\n        Values of velocities in x at which to cluster\n        and link.\n        [Default = None]\n    vy_values : {None, `~numpy.ndarray`}, optional\n        Values of velocities in y at which to cluster\n        and link.\n        [Default = None]\n    eps : float, optional\n        The maximum distance between two samples for them to be considered\n        as in the same neighborhood.\n        See: http://scikit-learn.org/stable/modules/generated/sklearn.cluster.dbscan.html\n        [Default = 0.005]\n    min_obs : int, optional\n        The number of samples (or total weight) in a neighborhood for a\n        point to be considered as a core point. This includes the point itself.\n        See: http://scikit-learn.org/stable/modules/generated/sklearn.cluster.dbscan.html\n        [Default = 5]\n    alg: str\n        Algorithm to use. Can be \"dbscan\" or \"hotspot_2d\".\n    num_jobs : int, optional\n        Number of jobs to launch.\n    parallel_backend : str, optional\n        Which parallelization backend to use {'ray', 'mp'}. Defaults to using Python's multiprocessing\n        module ('mp').\n\n    Returns\n    -------\n    clusters : `~pandas.DataFrame`\n        DataFrame with the cluster ID, the number of observations, and the x and y velocity.\n    cluster_members : `~pandas.DataFrame`\n        DataFrame containing the cluster ID and the observation IDs of its members.\n\n    Notes\n    -----\n    The algorithm chosen can have a big impact on performance and accuracy.\n\n    alg=\"dbscan\" uses the DBSCAN algorithm of Ester et. al. It's relatively slow\n    but works with high accuracy; it is certain to find all clusters with at\n    least min_obs points that are separated by at most eps.\n\n    alg=\"hotspot_2d\" is much faster (perhaps 10-20x faster) than dbscan, but it\n    may miss some clusters, particularly when points are spaced a distance of 'eps'\n    apart.\n    \"\"\"\n    time_start_cluster = time.time()\n    logger.info(\"Running velocity space clustering...\")\n\n    # Extract useful quantities\n    obs_ids = observations[\"obs_id\"].values\n    theta_x = observations[\"theta_x_deg\"].values\n    theta_y = observations[\"theta_y_deg\"].values\n    mjd = observations[\"mjd_utc\"].values\n\n    # Select detections in first exposure\n    first = np.where(mjd == mjd.min())[0]\n    mjd0 = mjd[first][0]\n    dt = mjd - mjd0\n\n    if vx_values is None and vx_range is not None:\n        vx = np.linspace(*vx_range, num=vx_bins)\n    elif vx_values is None and vx_range is None:\n        raise ValueError(\"Both vx_values and vx_range cannot be None.\")\n    else:\n        vx = vx_values\n        vx_range = [vx_values[0], vx_values[-1]]\n        vx_bins = len(vx)\n\n    if vy_values is None and vy_range is not None:\n        vy = np.linspace(*vy_range, num=vy_bins)\n    elif vy_values is None and vy_range is None:\n        raise ValueError(\"Both vy_values and vy_range cannot be None.\")\n    else:\n        vy = vy_values\n        vy_range = [vy_values[0], vy_values[-1]]\n        vy_bins = len(vy)\n\n    if vx_values is None and vy_values is None:\n        vxx, vyy = np.meshgrid(vx, vy)\n        vxx = vxx.flatten()\n        vyy = vyy.flatten()\n    elif vx_values is not None and vy_values is not None:\n        vxx = vx\n        vyy = vy\n    else:\n        raise ValueError(\"\")\n\n    logger.debug(\"X velocity range: {}\".format(vx_range))\n    if vx_values is not None:\n        logger.debug(\"X velocity values: {}\".format(vx_bins))\n    else:\n        logger.debug(\"X velocity bins: {}\".format(vx_bins))\n\n    logger.debug(\"Y velocity range: {}\".format(vy_range))\n    if vy_values is not None:\n        logger.debug(\"Y velocity values: {}\".format(vy_bins))\n    else:\n        logger.debug(\"Y velocity bins: {}\".format(vy_bins))\n    if vx_values is not None:\n        logger.debug(\"User defined x velocity values: True\")\n    else:\n        logger.debug(\"User defined x velocity values: False\")\n    if vy_values is not None:\n        logger.debug(\"User defined y velocity values: True\")\n    else:\n        logger.debug(\"User defined y velocity values: False\")\n\n    if vx_values is None and vy_values is None:\n        logger.debug(\"Velocity grid size: {}\".format(vx_bins * vy_bins))\n    else:\n        logger.debug(\"Velocity grid size: {}\".format(vx_bins))\n    logger.info(\"Max sample distance: {}\".format(eps))\n    logger.info(\"Minimum samples: {}\".format(min_obs))\n\n    possible_clusters = []\n    parallel, num_workers = _checkParallel(num_jobs, parallel_backend)\n    if parallel:\n        if parallel_backend == \"ray\":\n            import ray\n            if not ray.is_initialized():\n                ray.init(address=\"auto\")\n\n            clusterVelocity_worker_ray = ray.remote(clusterVelocity_worker)\n            clusterVelocity_worker_ray = clusterVelocity_worker_ray.options(\n                num_returns=1,\n                num_cpus=1\n            )\n\n            # Put all arrays (which can be large) in ray's\n            # local object store ahead of time\n            obs_ids_oid = ray.put(obs_ids)\n            theta_x_oid = ray.put(theta_x)\n            theta_y_oid = ray.put(theta_y)\n            dt_oid = ray.put(dt)\n\n            p = []\n            for vxi, vyi in zip(vxx, vyy):\n                p.append(\n                    clusterVelocity_worker_ray.remote(\n                        vxi,\n                        vyi,\n                        obs_ids=obs_ids_oid,\n                        x=theta_x_oid,\n                        y=theta_y_oid,\n                        dt=dt_oid,\n                        eps=eps,\n                        min_obs=min_obs,\n                        min_arc_length=min_arc_length,\n                        alg=alg\n                    )\n                )\n            possible_clusters = ray.get(p)\n\n        else: # parallel_backend == \"mp\"\n\n            p = mp.Pool(\n                processes=num_workers,\n                initializer=_initWorker\n            )\n            possible_clusters = p.starmap(\n                partial(\n                    clusterVelocity_worker,\n                    obs_ids=obs_ids,\n                    x=theta_x,\n                    y=theta_y,\n                    dt=dt,\n                    eps=eps,\n                    min_obs=min_obs,\n                    min_arc_length=min_arc_length,\n                    alg=alg\n                ),\n                zip(vxx, vyy)\n            )\n            p.close()\n\n    else:\n        possible_clusters = []\n        for vxi, vyi in zip(vxx, vyy):\n            possible_clusters.append(\n                clusterVelocity(\n                    obs_ids,\n                    theta_x,\n                    theta_y,\n                    dt,\n                    vxi,\n                    vyi,\n                    eps=eps,\n                    min_obs=min_obs,\n                    min_arc_length=min_arc_length,\n                    alg=alg\n                )\n            )\n    time_end_cluster = time.time()\n    logger.info(\"Clustering completed in {:.3f} seconds.\".format(time_end_cluster - time_start_cluster))\n\n    logger.info(\"Restructuring clusters...\")\n    time_start_restr = time.time()\n\n    possible_clusters = pd.DataFrame({\"clusters\": possible_clusters})\n\n    # Remove empty clusters\n    possible_clusters = possible_clusters[~possible_clusters[\"clusters\"].isna()]\n\n    if len(possible_clusters) != 0:\n        ### The following code is a little messy, its a lot of pandas dataframe manipulation.\n        ### I have tried doing an overhaul wherein the clusters and cluster_members dataframe are created per\n        ### velocity combination in the clusterVelocity function. However, this adds an overhead in that function\n        ### of ~ 1ms. So clustering 90,000 velocities takes 90 seconds longer which on small datasets is problematic.\n        ### On large datasets, the effect is not as pronounced because the below code takes a while to run due to\n        ### in-memory pandas dataframe restructuring.\n\n        # Make DataFrame with cluster velocities so we can figure out which\n        # velocities yielded clusters, add names to index so we can enable the join\n        cluster_velocities = pd.DataFrame({\"vtheta_x\": vxx, \"vtheta_y\": vyy})\n        cluster_velocities.index.set_names(\"velocity_id\", inplace=True)\n\n        # Split lists of cluster ids into one column per cluster for each different velocity\n        # then stack the result\n        possible_clusters = pd.DataFrame(\n            possible_clusters[\"clusters\"].values.tolist(),\n            index=possible_clusters.index\n        )\n        possible_clusters = pd.DataFrame(possible_clusters.stack())\n        possible_clusters.rename(\n            columns={0: \"obs_ids\"},\n            inplace=True\n        )\n        possible_clusters = pd.DataFrame(possible_clusters[\"obs_ids\"].values.tolist(), index=possible_clusters.index)\n\n        # Drop duplicate clusters\n        possible_clusters.drop_duplicates(inplace=True)\n\n        # Set index names\n        possible_clusters.index.set_names([\"velocity_id\", \"cluster_id\"], inplace=True)\n\n        # Reset index\n        possible_clusters.reset_index(\n            \"cluster_id\",\n            drop=True,\n            inplace=True\n        )\n        possible_clusters[\"cluster_id\"] = [str(uuid.uuid4().hex) for i in range(len(possible_clusters))]\n\n        # Make clusters DataFrame\n        clusters = possible_clusters.join(cluster_velocities)\n        clusters.reset_index(drop=True, inplace=True)\n        clusters = clusters[[\"cluster_id\", \"vtheta_x\", \"vtheta_y\"]]\n\n        # Make cluster_members DataFrame\n        cluster_members = possible_clusters.reset_index(drop=True).copy()\n        cluster_members.index = cluster_members[\"cluster_id\"]\n        cluster_members.drop(\"cluster_id\", axis=1, inplace=True)\n        cluster_members = pd.DataFrame(cluster_members.stack())\n        cluster_members.rename(columns={0: \"obs_id\"}, inplace=True)\n        cluster_members.reset_index(inplace=True)\n        cluster_members.drop(\"level_1\", axis=1, inplace=True)\n\n        # Calculate arc length and add it to the clusters dataframe\n        cluster_members_time = cluster_members.merge(\n            observations[[\"obs_id\", \"mjd_utc\"]],\n            on=\"obs_id\",\n            how=\"left\"\n        )\n        clusters_time = cluster_members_time.groupby(\n            by=[\"cluster_id\"])[\"mjd_utc\"].apply(lambda x: x.max() - x.min()).to_frame()\n        clusters_time.reset_index(\n            inplace=True\n        )\n        clusters_time.rename(\n            columns={\"mjd_utc\" : \"arc_length\"},\n            inplace=True\n        )\n        clusters = clusters.merge(\n            clusters_time[[\"cluster_id\", \"arc_length\"]],\n            on=\"cluster_id\",\n            how=\"left\",\n        )\n\n    else:\n        cluster_members = pd.DataFrame(columns=[\"cluster_id\", \"obs_id\"])\n        clusters = pd.DataFrame(columns=[\"cluster_id\", \"vtheta_x\", \"vtheta_y\", \"arc_length\"])\n\n\n    time_end_restr = time.time()\n    logger.info(\"Restructuring completed in {:.3f} seconds.\".format(time_end_restr - time_start_restr))\n    logger.info(\"Found {} clusters.\".format(len(clusters)))\n    logger.info(\"Clustering and restructuring completed in {:.3f} seconds.\".format(time_end_restr - time_start_cluster))\n\n    return clusters, cluster_members\n\ndef runTHOROrbit(\n        preprocessed_observations,\n        orbit,\n        range_shift_config=Config.RANGE_SHIFT_CONFIG,\n        cluster_link_config=Config.CLUSTER_LINK_CONFIG,\n        iod_config=Config.IOD_CONFIG,\n        od_config=Config.OD_CONFIG,\n        odp_config=Config.ODP_CONFIG,\n        out_dir=None,\n        if_exists=\"continue\",\n        logging_level=logging.INFO\n    ):\n    logger = logging.getLogger(\"thor\")\n    logger.setLevel(logging_level)\n\n    # Build the configuration class which stores the run parameters\n    config = Configuration(\n        range_shift_config=range_shift_config,\n        cluster_link_config=cluster_link_config,\n        iod_config=iod_config,\n        od_config=od_config,\n        odp_config=odp_config\n    )\n    status = {\n        \"rangeAndShift\" : False,\n        \"clusterAndLink\" : False,\n        \"initialOrbitDetermination\" : False,\n        \"differentialCorrection\" : False,\n        \"mergeAndExtendOrbits\" : False,\n        \"complete\" : False\n    }\n\n    continue_ = False\n    if out_dir is not None:\n        if not os.path.exists(out_dir):\n            os.mkdir(out_dir)\n            logger.debug(\"Created {} directory.\".format(out_dir))\n\n        else:\n            if if_exists == \"continue\":\n                logger.warning(\"{} directory already exists, attempting to continue previous run.\".format(out_dir))\n                continue_ = True\n            elif if_exists == \"erase\":\n                logger.warning(\"{} directory already exists, removing previous results.\".format(out_dir))\n                shutil.rmtree(out_dir)\n                os.mkdir(out_dir)\n                logger.debug(\"Created {} directory.\".format(out_dir))\n            else:\n                err = (\n                    \"if_exists should be one of {'continue', 'erase'}.\"\n                )\n                raise ValueError(err)\n\n        file_handler = logging.FileHandler(\n            os.path.join(out_dir, \"thor.log\"),\n            encoding=\"utf-8\",\n            delay=False\n        )\n        file_handler.setLevel(logging.DEBUG)\n        file_format = logging.Formatter(\n            '%(asctime)s.%(msecs)03d [%(levelname)s] [%(thread)s] %(message)s (%(filename)s, %(funcName)s, %(lineno)d)',\n            datefmt='%Y-%m-%d %H:%M:%S'\n        )\n        file_handler.setFormatter(file_format)\n        logger.addHandler(file_handler)\n\n        # The primary files which will be used to determine if the run\n        # can be continued from a previous state and, if so, from where\n        # to continue the run\n        config_file = os.path.join(out_dir, \"config.yml\")\n        test_orbit_file = os.path.join(out_dir, \"test_orbit.csv\")\n        status_file = os.path.join(out_dir, \"status.yml\")\n        config_eq = False\n        test_orbit_eq = False\n        save_orbit = True\n        save_config = True\n\n        if continue_:\n\n            if not os.path.exists(config_file):\n                logger.warning(\"No previous configuration file found.\")\n                save_config = True\n            else:\n                logger.info(\"Previous configuration file found. Comparing settings...\")\n\n                config_prev = Configuration.fromYaml(config_file)\n                if config_prev != config:\n                    logger.warning(\"Previous configuration does not match current configuration. Processing will not continue from previous state.\")\n                else:\n                    config_eq = True\n                    save_config = False\n                    logger.info(\"Previous configuration matches current configuration.\")\n\n            if not os.path.exists(test_orbit_file):\n                logger.warning(\"No previous test orbit file found.\")\n                save_orbit = True\n            else:\n                logger.info(\"Previous test orbit file found.\")\n\n                test_orbit_prev = Orbits.from_csv(\n                    test_orbit_file,\n                )\n                if test_orbit_prev != orbit:\n                    logger.warning(\"Previous test orbit does not match current test orbit.\")\n                else:\n                    test_orbit_eq = True\n                    save_orbit = False\n                    logger.info(\"Previous test orbit matches current test orbit.\")\n\n            if not os.path.exists(status_file):\n                logger.warning(\"No previous status file found.\")\n            else:\n                if test_orbit_eq and config_eq:\n                    with open(status_file, \"r\") as status_in:\n                        status = yaml.load(status_in, Loader=yaml.FullLoader)\n                    logger.info(\"Previous status file found.\")\n\n        if save_config:\n            config.toYaml(config_file)\n            logger.debug(\"Saved config.yml.\")\n\n        if save_orbit:\n            orbit.to_csv(\n                test_orbit_file\n            )\n            logger.debug(\"Saved test_orbit.csv.\")\n\n            if status[\"complete\"]:\n                logger.info(\"Orbit has already finished processing.\")\n\n    if not status[\"complete\"]:\n        if not status[\"rangeAndShift\"]:\n            projected_observations = rangeAndShift(\n                preprocessed_observations,\n                orbit,\n                **range_shift_config\n            )\n            if out_dir is not None:\n                projected_observations.to_csv(\n                    os.path.join(out_dir, \"projected_observations.csv\"),\n                    index=False,\n                    float_format=\"%.15e\"\n                )\n                logger.debug(\"Saved projected_observations.csv.\")\n\n        else:\n            logger.info(\"Range and shift completed previously.\")\n            projected_observations = pd.read_csv(\n                os.path.join(out_dir, \"projected_observations.csv\"),\n                index_col=False,\n                dtype={\"obs_id\" : str},\n                float_precision=\"round_trip\"\n            )\n            logger.debug(\"Read projected_observations.csv.\")\n\n        status[\"rangeAndShift\"] = True\n        if out_dir is not None:\n            with open(status_file, \"w\") as status_out:\n                yaml.safe_dump(status, status_out)\n            logger.debug(\"Updated status.yml.\")\n\n        if not status[\"clusterAndLink\"]:\n            clusters, cluster_members = clusterAndLink(\n                projected_observations,\n                **cluster_link_config\n            )\n            if out_dir is not None:\n                clusters.to_csv(\n                    os.path.join(out_dir, \"clusters.csv\"),\n                    index=False,\n                    float_format=\"%.15e\"\n                )\n                logger.debug(\"Saved clusters.csv.\")\n\n                cluster_members.to_csv(\n                    os.path.join(out_dir, \"cluster_members.csv\"),\n                    index=False,\n                    float_format=\"%.15e\"\n                )\n                logger.debug(\"Saved cluster_members.csv.\")\n        else:\n            logger.info(\"Clustering completed previously.\")\n            clusters = pd.read_csv(\n                os.path.join(out_dir, \"clusters.csv\"),\n                index_col=False\n            )\n            logger.debug(\"Read clusters.csv.\")\n\n            cluster_members = pd.read_csv(\n                os.path.join(out_dir, \"cluster_members.csv\"),\n                index_col=False,\n                dtype={\"obs_id\" : str},\n                float_precision=\"round_trip\"\n            )\n            logger.debug(\"Read cluster_members.csv.\")\n\n        status[\"clusterAndLink\"] = True\n        if out_dir is not None:\n            with open(status_file, \"w\") as status_out:\n                yaml.safe_dump(status, status_out)\n            logger.debug(\"Updated status.yml.\")\n\n        if not status[\"initialOrbitDetermination\"]:\n            iod_orbits, iod_orbit_members = initialOrbitDetermination(\n                projected_observations,\n                cluster_members,\n                **iod_config\n            )\n            if out_dir is not None:\n                Orbits.from_df(iod_orbits).to_csv(\n                    os.path.join(out_dir, \"iod_orbits.csv\")\n                )\n                logger.debug(\"Saved iod_orbits.csv.\")\n\n                iod_orbit_members.to_csv(\n                    os.path.join(out_dir, \"iod_orbit_members.csv\"),\n                    index=False,\n                    float_format=\"%.15e\"\n                )\n                logger.debug(\"Saved iod_orbit_members.csv.\")\n        else:\n            logger.info(\"Initial orbit determination completed previously.\")\n            iod_orbits = Orbits.from_csv(\n                os.path.join(out_dir, \"iod_orbits.csv\"),\n            ).to_df(include_units=False)\n            logger.debug(\"Read iod_orbits.csv.\")\n\n            iod_orbit_members = pd.read_csv(\n                os.path.join(out_dir, \"iod_orbit_members.csv\"),\n                index_col=False,\n                dtype={\"obs_id\" : str},\n                float_precision=\"round_trip\"\n            )\n            logger.debug(\"Read iod_orbit_members.csv.\")\n\n        status[\"initialOrbitDetermination\"] = True\n        if out_dir is not None:\n            with open(status_file, \"w\") as status_out:\n                yaml.safe_dump(status, status_out)\n            logger.debug(\"Updated status.yml.\")\n\n        iod_orbits = iod_orbits[[\"orbit_id\", \"epoch\", \"x\", \"y\", \"z\", \"vx\", \"vy\", \"vz\"]]\n        iod_orbit_members = iod_orbit_members[iod_orbit_members[\"outlier\"] == 0][[\"orbit_id\", \"obs_id\"]]\n        iod_orbits = iod_orbits[iod_orbits[\"orbit_id\"].isin(iod_orbit_members[\"orbit_id\"].unique())]\n        for df in [iod_orbits, iod_orbit_members]:\n            df.reset_index(\n                inplace=True,\n                drop=True\n            )\n\n        if not status[\"differentialCorrection\"]:\n            od_orbits, od_orbit_members = differentialCorrection(\n                iod_orbits,\n                iod_orbit_members,\n                projected_observations,\n                **od_config\n            )\n            if out_dir is not None:\n                Orbits.from_df(od_orbits).to_csv(\n                    os.path.join(out_dir, \"od_orbits.csv\")\n                )\n                logger.debug(\"Saved od_orbits.csv.\")\n\n                od_orbit_members.to_csv(\n                    os.path.join(out_dir, \"od_orbit_members.csv\"),\n                    index=False,\n                    float_format=\"%.15e\"\n                )\n                logger.debug(\"Saved od_orbit_members.csv.\")\n        else:\n            logger.info(\"Differential correction completed previously.\")\n            od_orbits = Orbits.from_csv(\n                os.path.join(out_dir, \"od_orbits.csv\"),\n            ).to_df(include_units=False)\n            logger.debug(\"Read od_orbits.csv.\")\n\n            od_orbit_members = pd.read_csv(\n                os.path.join(out_dir, \"od_orbit_members.csv\"),\n                index_col=False,\n                dtype={\"obs_id\" : str},\n                float_precision=\"round_trip\"\n            )\n            logger.debug(\"Read od_orbit_members.csv.\")\n\n        status[\"differentialCorrection\"] = True\n        if out_dir is not None:\n            with open(status_file, \"w\") as status_out:\n                yaml.safe_dump(status, status_out)\n            logger.debug(\"Updated status.yml.\")\n\n        od_orbit_members = od_orbit_members[od_orbit_members[\"outlier\"] == 0][[\"orbit_id\", \"obs_id\"]]\n        od_orbits = od_orbits[od_orbits[\"orbit_id\"].isin(od_orbit_members[\"orbit_id\"].unique())]\n        for df in [od_orbits, od_orbit_members]:\n            df.reset_index(\n                inplace=True,\n                drop=True\n            )\n\n        if not status[\"mergeAndExtendOrbits\"]:\n\n            recovered_orbits, recovered_orbit_members = mergeAndExtendOrbits(\n                od_orbits,\n                od_orbit_members,\n                projected_observations,\n                **odp_config\n            )\n            if out_dir is not None:\n                Orbits.from_df(recovered_orbits).to_csv(\n                    os.path.join(out_dir, \"recovered_orbits.csv\")\n                )\n                logger.debug(\"Saved recovered_orbits.csv.\")\n\n                recovered_orbit_members.to_csv(\n                    os.path.join(out_dir, \"recovered_orbit_members.csv\"),\n                    index=False,\n                    float_format=\"%.15e\"\n                )\n                logger.debug(\"Saved recovered_orbit_members.csv.\")\n        else:\n            logger.info(\"Orbit extension and merging completed previously.\")\n            recovered_orbits = Orbits.from_csv(\n                os.path.join(out_dir, \"recovered_orbits.csv\"),\n            ).to_df(include_units=False)\n            logger.debug(\"Read recovered_orbits.csv.\")\n\n            recovered_orbit_members = pd.read_csv(\n                os.path.join(out_dir, \"recovered_orbit_members.csv\"),\n                index_col=False,\n                dtype={\"obs_id\" : str},\n                float_precision=\"round_trip\"\n            )\n            logger.debug(\"Read recovered_orbit_members.csv.\")\n\n        status[\"mergeAndExtendOrbits\"] = True\n        status[\"complete\"] = True\n        if out_dir is not None:\n            with open(status_file, \"w\") as status_out:\n                yaml.safe_dump(status, status_out)\n            logger.debug(\"Updated status.yml.\")\n\n    else:\n        logger.info(\"Orbit previously completed processing.\")\n        recovered_orbits = Orbits.from_csv(\n            os.path.join(out_dir, \"recovered_orbits.csv\"),\n        ).to_df(include_units=False)\n        logger.debug(\"Read recovered_orbits.csv.\")\n\n        recovered_orbit_members = pd.read_csv(\n            os.path.join(out_dir, \"recovered_orbit_members.csv\"),\n            index_col=False,\n            dtype={\"obs_id\" : str},\n            float_precision=\"round_trip\"\n        )\n        logger.debug(\"Read recovered_orbit_members.csv.\")\n\n    logger.removeHandler(file_handler)\n    return recovered_orbits, recovered_orbit_members\n\ndef runTHOR(\n        preprocessed_observations,\n        test_orbits,\n        range_shift_config=Config.RANGE_SHIFT_CONFIG,\n        cluster_link_config=Config.CLUSTER_LINK_CONFIG,\n        iod_config=Config.IOD_CONFIG,\n        od_config=Config.OD_CONFIG,\n        odp_config=Config.ODP_CONFIG,\n        out_dir=None,\n        if_exists=\"continue\",\n        logging_level=logger.info\n    ):\n    logger.setLevel(logging_level)\n\n    # Connect to ray cluster if enabled\n    enable_ray = False\n    configs = [\n        range_shift_config,\n        cluster_link_config,\n        iod_config,\n        od_config,\n        odp_config\n    ]\n    for conf in configs:\n        if conf[\"parallel_backend\"] == \"ray\":\n            enable_ray = True\n\n    if enable_ray:\n        import ray\n        if not ray.is_initialized():\n            ray.init(address=\"auto\")\n\n    # Build the configuration class which stores the run parameters\n    config = Configuration(\n        range_shift_config=range_shift_config,\n        cluster_link_config=cluster_link_config,\n        iod_config=iod_config,\n        od_config=od_config,\n        odp_config=odp_config\n    )\n\n    orbits_completed = []\n    continue_ = False\n    if_exists_ = if_exists\n    if out_dir is not None:\n        if not os.path.exists(out_dir):\n            os.mkdir(out_dir)\n            logger.debug(\"Created {} directory.\".format(out_dir))\n\n        else:\n            if if_exists == \"continue\":\n                logger.warning(\"{} directory already exists, attempting to continue previous run.\".format(out_dir))\n                continue_ = True\n            elif if_exists == \"erase\":\n                logger.warning(\"{} directory already exists, removing previous results.\".format(out_dir))\n                shutil.rmtree(out_dir)\n                os.mkdir(out_dir)\n                logger.debug(\"Created {} directory.\".format(out_dir))\n            else:\n                err = (\n                    \"if_exists should be one of {'continue', 'erase'}.\"\n                )\n                raise ValueError(err)\n\n        # The primary files which will be used to determine if the run\n        # can be continued from a previous state and, if so, from where\n        # to continue the run\n        config_file = os.path.join(out_dir, \"config.yml\")\n        test_orbits_in_file = os.path.join(out_dir, \"test_orbits_in.csv\")\n        status_file = os.path.join(out_dir, \"status.txt\")\n        config_eq = False\n        test_orbits_eq = False\n        save_orbits = True\n        save_config = True\n\n        # Add summary file for test_orbits that tracks number of recovered orbits and number of observations\n        # linked in addition to the test_orbit_id used by THOR\n        test_orbits_out_file = os.path.join(out_dir, \"test_orbits_out.csv\")\n        if continue_:\n            if not os.path.exists(config_file):\n                logger.warning(\"No previous configuration file found.\")\n                save_config = True\n                if_exists_ = \"erase\"\n            else:\n                logger.info(\"Previous configuration file found. Comparing settings...\")\n\n                config_prev = Configuration.fromYaml(config_file)\n                if config_prev != config:\n                    logger.warning(\"Previous configuration does not match current configuration. Processing will not continue from previous state.\")\n                    if_exists_ = \"erase\"\n                else:\n                    config_eq = True\n                    save_config = False\n                    logger.info(\"Previous configuration matches current configuration.\")\n\n            if not os.path.exists(test_orbits_in_file):\n                logger.warning(\"No previous test orbits file found.\")\n                save_orbits = True\n            else:\n                logger.info(\"Previous test orbits file found.\")\n\n                test_orbits_prev = Orbits.from_csv(\n                    test_orbits_in_file,\n                )\n                if test_orbits_prev != test_orbits:\n                    logger.warning(\"Previous test orbits do not match current test orbits.\")\n                else:\n                    test_orbits_eq = True\n                    save_orbits = False\n                    test_orbits_df = test_orbits_prev.to_df(include_units=False)\n                    logger.info(\"Previous test orbits match current test orbits.\")\n\n            if not os.path.exists(status_file):\n                logger.warning(\"No previous status file found.\")\n            else:\n                if test_orbits_eq and config_eq:\n                    orbits_completed = np.loadtxt(\n                        os.path.join(out_dir, \"status.txt\"),\n                        delimiter=\"\\n\",\n                        dtype=str,\n                        ndmin=1\n                    )\n                    logger.info(\"Previous status file found.\")\n\n        if (not test_orbits_eq or not config_eq) and continue_:\n            if if_exists == \"continue\":\n                logger.critical(\"Previous run cannot continue from previous state.\")\n                raise ValueError(\"Previous run cannot continue from previous state. Set if_exists to 'erase' or change/delete the output directory.\")\n            elif if_exists == \"erase\":\n                shutil.rmtree(out_dir)\n                os.mkdir(out_dir)\n                logger.debug(\"Created {} directory.\".format(out_dir))\n            else:\n                pass\n\n        if save_config:\n            config.toYaml(config_file)\n            logger.debug(\"Saved config.yml.\")\n\n        if save_orbits:\n            test_orbits.to_csv(\n                test_orbits_in_file\n            )\n            logger.debug(\"Saved test_orbits_in.csv.\")\n\n            preprocessed_observations.to_csv(\n                os.path.join(out_dir, \"preprocessed_observations.csv\"),\n                index=False,\n                float_format=\"%.15e\"\n            )\n            logger.debug(\"Saved preprocessed_observations.csv.\")\n\n    test_orbit_dfs = []\n    recovered_orbits_dfs = []\n    recovered_orbit_members_dfs = []\n    obs_ids_linked = []\n    num_orbits = len(test_orbits)\n    if num_orbits != len(orbits_completed):\n        test_orbits_split = test_orbits[len(orbits_completed):].split(1)\n    else:\n        test_orbits_split = []\n\n    # If orbits have previously completed, read the results and continue iterating\n    # through orbits not previously completed.\n    id_offset = 0\n    if len(orbits_completed) > 0:\n        logger.info(\"{}/{} orbits have previously finished processing.\".format(len(orbits_completed), num_orbits))\n\n        test_orbits_df = Orbits.from_csv(\n            test_orbits_out_file,\n        ).to_df(include_units=False)\n        logger.debug(\"Read previous test_orbits_out.csv.\")\n\n        recovered_orbits = Orbits.from_csv(\n            os.path.join(out_dir, \"recovered_orbits.csv\"),\n        ).to_df(include_units=False)\n        logger.debug(\"Read previous recovered_orbits.csv.\")\n\n        recovered_orbit_members = pd.read_csv(\n            os.path.join(out_dir, \"recovered_orbit_members.csv\"),\n            index_col=False,\n            dtype={\"obs_id\" : str},\n            float_precision=\"round_trip\"\n        )\n        logger.debug(\"Read previous recovered_orbit_members.csv.\")\n\n        test_orbit_dfs = [test_orbits_df]\n        recovered_orbits_dfs = [recovered_orbits]\n        recovered_orbit_members_dfs = [recovered_orbit_members]\n        obs_ids_linked = recovered_orbit_members[\"obs_id\"].values\n        id_offset = len(orbits_completed)\n\n    if len(test_orbits_split) != 0:\n        for i, orbit_i in enumerate(test_orbits_split):\n\n            time_start = time.time()\n            orbit_id = \"{:08d}\".format(i + id_offset)\n\n            logger.info(\"Processing orbit {} ({}/{})...\".format(orbit_id, i + 1 + id_offset, num_orbits))\n\n            if out_dir is not None:\n                orbit_dir = os.path.join(out_dir, \"orbit_{}\".format(orbit_id))\n            else:\n                orbit_dir = None\n\n            linked_mask = (~preprocessed_observations[\"obs_id\"].isin(obs_ids_linked))\n\n            recovered_orbits_i, recovered_orbit_members_i = runTHOROrbit(\n                preprocessed_observations[linked_mask],\n                orbit_i,\n                range_shift_config=range_shift_config,\n                cluster_link_config=cluster_link_config,\n                iod_config=iod_config,\n                od_config=od_config,\n                odp_config=odp_config,\n                out_dir=orbit_dir,\n                if_exists=if_exists_,\n                logging_level=logging_level\n            )\n\n            time_end = time.time()\n\n            if len(recovered_orbits_i) > 0:\n                recovered_orbits_i.insert(0, \"test_orbit_id\", orbit_id)\n                recovered_orbit_members_i.insert(0, \"test_orbit_id\", orbit_id)\n                obs_ids_linked_i = recovered_orbit_members_i[\"obs_id\"].unique()\n                obs_ids_linked = np.concatenate([obs_ids_linked, obs_ids_linked_i])\n\n                orbits_recovered = len(recovered_orbits_i)\n                observations_linked = len(obs_ids_linked_i)\n            else:\n                orbits_recovered = 0\n                observations_linked = 0\n\n            test_orbit_i = orbit_i.to_df(include_units=False)\n            test_orbit_i[\"test_orbit_id\"] = orbit_id\n            test_orbit_i[\"orbits_recovered\"] = orbits_recovered\n            test_orbit_i[\"observations_linked\"] = observations_linked\n            test_orbit_i[\"processing_time\"] = time_end - time_start\n            test_orbit_dfs.append(test_orbit_i)\n\n            logger.info(\"Completed processing orbit {} in {:.3f} seconds.\".format(orbit_id, time_end - time_start))\n\n            recovered_orbits_dfs.append(recovered_orbits_i)\n            recovered_orbit_members_dfs.append(recovered_orbit_members_i)\n\n            test_orbits_df = pd.concat(\n                test_orbit_dfs,\n                ignore_index=True\n            )\n            recovered_orbits = pd.concat(\n                recovered_orbits_dfs,\n                ignore_index=True\n            )\n            recovered_orbit_members = pd.concat(\n                recovered_orbit_members_dfs,\n                ignore_index=True\n            )\n\n            if out_dir is not None:\n                Orbits.from_df(test_orbits_df).to_csv(\n                    test_orbits_out_file\n                )\n                logger.debug(\"Saved test_orbits_out.csv.\")\n\n                Orbits.from_df(recovered_orbits).to_csv(\n                    os.path.join(out_dir, \"recovered_orbits.csv\")\n                )\n                logger.debug(\"Saved recovered_orbits.csv.\")\n\n                recovered_orbit_members.to_csv(\n                    os.path.join(out_dir, \"recovered_orbit_members.csv\"),\n                    index=False,\n                    float_format=\"%.15e\"\n                )\n                logger.debug(\"Saved recovered_orbit_members.csv.\")\n\n            orbits_completed = np.concatenate([orbits_completed, np.array([orbit_id])])\n            if out_dir is not None:\n                with open(os.path.join(out_dir, \"status.txt\"), \"w\") as status_out:\n                    np.savetxt(\n                        status_out,\n                        orbits_completed,\n                        delimiter=\"\\n\",\n                        fmt=\"%s\"\n                    )\n                logger.info(\"Saved status.txt.\")\n\n\n    else:\n\n        logger.info(\"Run completed previously.\")\n        test_orbits_df = Orbits.from_csv(\n                test_orbits_out_file,\n        ).to_df(include_units=False)\n        logger.debug(\"Read test_orbits_out.csv.\")\n\n        recovered_orbits = Orbits.from_csv(\n            os.path.join(out_dir, \"recovered_orbits.csv\"),\n        ).to_df(include_units=False)\n        logger.debug(\"Read recovered_orbits.csv.\")\n\n        recovered_orbit_members = pd.read_csv(\n            os.path.join(out_dir, \"recovered_orbit_members.csv\"),\n            index_col=False,\n            dtype={\"obs_id\" : str},\n            float_precision=\"round_trip\"\n        )\n        logger.debug(\"Read recovered_orbit_members.csv.\")\n\n    return test_orbits_df, recovered_orbits, recovered_orbit_members\n", "meta": {"hexsha": "03e2f4bcb29d549f45f6d0e35100dffe7d86f7cb", "size": 50272, "ext": "py", "lang": "Python", "max_stars_repo_path": "thor/main.py", "max_stars_repo_name": "KatKiker/thor", "max_stars_repo_head_hexsha": "ffc8ab3fbaa8af046f531e8111907a891998d14b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thor/main.py", "max_issues_repo_name": "KatKiker/thor", "max_issues_repo_head_hexsha": "ffc8ab3fbaa8af046f531e8111907a891998d14b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thor/main.py", "max_forks_repo_name": "KatKiker/thor", "max_forks_repo_head_hexsha": "ffc8ab3fbaa8af046f531e8111907a891998d14b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-29T15:20:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-29T15:20:34.000Z", "avg_line_length": 36.8293040293, "max_line_length": 149, "alphanum_fraction": 0.5871459262, "include": true, "reason": "import numpy,from astropy", "num_tokens": 10546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241911813149, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.18421511535377116}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n#    Project: Fast Azimuthal integration\n#             https://github.com/silx-kit/pyFAI\n#\n#    Copyright (C) 2017-2018 European Synchrotron Radiation Facility, Grenoble, France\n#\n#    Principal author:       Jérôme Kieffer (Jerome.Kieffer@ESRF.eu)\n#\n#  Permission is hereby granted, free of charge, to any person obtaining a copy\n#  of this software and associated documentation files (the \"Software\"), to deal\n#  in the Software without restriction, including without limitation the rights\n#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n#  copies of the Software, and to permit persons to whom the Software is\n#  furnished to do so, subject to the following conditions:\n#  .\n#  The above copyright notice and this permission notice shall be included in\n#  all copies or substantial portions of the Software.\n#  .\n#  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n#  THE SOFTWARE.\n\n\"\"\"\nDetectors manufactured by PSI, those may be different from the one from Dectris\n\"\"\"\n\n__author__ = \"Jerome Kieffer\"\n__contact__ = \"Jerome.Kieffer@ESRF.eu\"\n__license__ = \"MIT\"\n__copyright__ = \"2021 European Synchrotron Radiation Facility, Grenoble, France\"\n__date__ = \"15/03/2021\"\n__status__ = \"production\"\n\nimport numpy\nimport logging\nfrom ._common import Detector\nfrom ..utils import mathutil\nlogger = logging.getLogger(__name__)\n\n\nclass Jungfrau(Detector):\n    \"\"\"\n    Raw Jungfrau module without sub-module pixel expension applied.\n    \"\"\"\n    MANUFACTURER = \"PSI\"\n\n    MODULE_SIZE = (256, 256)  # number of pixels per module (y, x)\n    MAX_SHAPE = (512, 1024)  # max size of the detector\n    PIXEL_SIZE = (75e-6, 75e-6)\n    BORDER_SIZE_RELATIVE = 2.0\n    force_pixel = True\n    aliases = [\"Jungfrau 500k\"]\n    uniform_pixel = False\n\n    @classmethod\n    def _calc_pixels_size(cls, length, module_size, pixel_size):\n        \"\"\"\n        given the length (in pixel) of the detector, the size of a\n        module (in pixels) and the pixel_size (in meter). this method\n        return the length of each pixels 0..length.\n\n        :param length: the number of pixel to compute\n        :type length: int\n        :param module_size: the number of pixel of one module\n        :type module_size: int\n        :param pixel_size: the size of one pixels (meter per pixel)\n        :type length: float\n\n        :return: the coordinates of each pixels 0..length\n        :rtype: ndarray\n        \"\"\"\n        size = numpy.ones(length)\n        n = length // module_size\n        for i in range(1, n):\n            size[i * module_size - 1] = cls.BORDER_SIZE_RELATIVE\n            size[i * module_size] = cls.BORDER_SIZE_RELATIVE\n        return pixel_size * size\n\n    def __init__(self, pixel1=75e-6, pixel2=75e-6, max_shape=None, module_size=None):\n        Detector.__init__(self, pixel1=pixel1, pixel2=pixel2, max_shape=max_shape)\n        self._pixel_edges = None  # array of size max_shape+1: pixels are contiguous\n        if (module_size is None) and (\"MODULE_SIZE\" in dir(self.__class__)):\n            self.module_size = tuple(self.MODULE_SIZE)\n        else:\n            self.module_size = module_size\n\n    def __repr__(self):\n        return \"Detector %s\\t PixelSize= %.3e, %.3e m\" % \\\n            (self.name, self.pixel1, self.pixel2)\n\n    def calc_pixels_edges(self):\n        \"\"\"\n        Calculate the position of the pixel edges\n        \"\"\"\n        if self._pixel_edges is None:\n            pixel_size1 = self._calc_pixels_size(self.max_shape[0], self.module_size[0], self.PIXEL_SIZE[0])\n            pixel_size2 = self._calc_pixels_size(self.max_shape[1], self.module_size[1], self.PIXEL_SIZE[1])\n            pixel_edges1 = numpy.zeros(self.max_shape[0] + 1)\n            pixel_edges2 = numpy.zeros(self.max_shape[1] + 1)\n            pixel_edges1[1:] = numpy.cumsum(pixel_size1)\n            pixel_edges2[1:] = numpy.cumsum(pixel_size2)\n            self._pixel_edges = pixel_edges1, pixel_edges2\n        return self._pixel_edges\n\n    def get_pixel_corners(self, correct_binning=False):\n        \"\"\"\n        Calculate the position of the corner of the pixels\n\n        This should be overwritten by class representing non-contiguous detector (Xpad, ...)\n\n        Precision float32 is ok: precision of 1µm for a detector size of 1m\n\n\n        :return:  4D array containing:\n                    pixel index (slow dimension)\n                    pixel index (fast dimension)\n                    corner index (A, B, C or D), triangles or hexagons can be handled the same way\n                    vertex position (z,y,x)\n        \"\"\"\n\n        if self._pixel_corners is None:\n            with self._sem:\n                if self._pixel_corners is None:\n                    edges1, edges2 = self.calc_pixels_edges()\n                    p1 = mathutil.expand2d(edges1, self.shape[1] + 1, False)\n                    p2 = mathutil.expand2d(edges2, self.shape[0] + 1, True)\n                    # p3 = None\n                    self._pixel_corners = numpy.zeros((self.shape[0], self.shape[1], 4, 3), dtype=numpy.float32)\n                    self._pixel_corners[:,:, 0, 1] = p1[:-1,:-1]\n                    self._pixel_corners[:,:, 0, 2] = p2[:-1,:-1]\n                    self._pixel_corners[:,:, 1, 1] = p1[1:,:-1]\n                    self._pixel_corners[:,:, 1, 2] = p2[1:,:-1]\n                    self._pixel_corners[:,:, 2, 1] = p1[1:, 1:]\n                    self._pixel_corners[:,:, 2, 2] = p2[1:, 1:]\n                    self._pixel_corners[:,:, 3, 1] = p1[:-1, 1:]\n                    self._pixel_corners[:,:, 3, 2] = p2[:-1, 1:]\n                    # if p3 is not None:\n                    #     # non flat detector\n                    #    self._pixel_corners[:, :, 0, 0] = p3[:-1, :-1]\n                    #     self._pixel_corners[:, :, 1, 0] = p3[1:, :-1]\n                    #     self._pixel_corners[:, :, 2, 0] = p3[1:, 1:]\n                    #     self._pixel_corners[:, :, 3, 0] = p3[:-1, 1:]\n        if correct_binning and self._pixel_corners.shape[:2] != self.shape:\n            return self._rebin_pixel_corners()\n        else:\n            return self._pixel_corners\n\n    def calc_cartesian_positions(self, d1=None, d2=None, center=True, use_cython=True):\n        \"\"\"\n        Calculate the position of each pixel center in cartesian coordinate\n        and in meter of a couple of coordinates.\n        The half pixel offset is taken into account here !!!\n\n        :param d1: the Y pixel positions (slow dimension)\n        :type d1: ndarray (1D or 2D)\n        :param d2: the X pixel positions (fast dimension)\n        :type d2: ndarray (1D or 2D)\n\n        :return: position in meter of the center of each pixels.\n        :rtype: ndarray\n\n        d1 and d2 must have the same shape, returned array will have\n        the same shape.\n\n        \"\"\"\n        # if the detctor has been tweaked with an ASCII geometry ... fall-back on the classical method:\n        if self._pixel_corners is not None:\n            return Detector.calc_cartesian_positions(self, d1=d1, d2=d2, center=center, use_cython=use_cython)\n\n        edges1, edges2 = self.calc_pixels_edges()\n\n        if (d1 is None) or (d2 is None):\n            if center:\n                # Take the center of each pixel\n                d1 = 0.5 * (edges1[:-1] + edges1[1:])\n                d2 = 0.5 * (edges2[:-1] + edges2[1:])\n            else:\n                # take the lower corner\n                d1 = edges1[:-1]\n                d2 = edges2[:-1]\n            p1 = numpy.outer(d1, numpy.ones(self.shape[1]))\n            p2 = numpy.outer(numpy.ones(self.shape[0]), d2)\n        else:\n            if center:\n                # Not +=: do not mangle in place arrays\n                d1 = d1 + 0.5\n                d2 = d2 + 0.5\n            p1 = numpy.interp(d1, numpy.arange(self.max_shape[0] + 1), edges1, edges1[0], edges1[-1])\n            p2 = numpy.interp(d2, numpy.arange(self.max_shape[1] + 1), edges2, edges2[0], edges2[-1])\n        return p1, p2, None\n\n\nclass Jungfrau_16M_cor(Jungfrau):\n    \"\"\"Jungfrau 16 corrected for double-sized pixels\n    \"\"\"\n    MODULE_SIZE = ((512 + 2), 1024 + 6)  # number of pixels per module (y, x)\n    MAX_SHAPE = ((512 + 2) * 32, 1024 + 6)  # max size of the detector\n    force_pixel = True\n    aliases = [\"Jungfrau 16M cor\"]\n\n    @staticmethod\n    def load_geom(geom_fname):\n        \"\"\"\"Load module geometry from ASCII file\n        \n        Stollen from Alejandro Homs' code\n        \"\"\"\n        import re\n        geom_re = re.compile('m(?P<mod>[0-9]+)/(?P<par>[^ \\t=]+)[ \\t]*='\n                         '[ \\t]*(?P<val>.+)')\n        module_geom = {}\n        with open(geom_fname) as ifile:\n            for l in ifile:\n                m = geom_re.match(l)\n                if not m:\n                    continue\n                mod = int(m.group('mod'))\n                mod_data = module_geom.setdefault(mod, {})\n                val = m.group('val')\n                if ' ' in val:\n                    val = val.split()\n                    if val[0].endswith('x') and val[1].endswith('y'):\n                        val = [v[:-1] for v in val]\n                else:\n                    val = [val]\n                key = m.group('par')\n                if key.startswith(\"min_\") or key.startswith(\"max_\"):\n                    mod_data[key] = int(val[0])\n                elif key.startswith(\"corner\"):\n                    mod_data[key] = float(val[0])\n                else:\n                    mod_data[key] = [float(v) for v in val]\n        return module_geom\n\n    def init_from_geometry(self, filename):\n        \"\"\"initialize the detector from \"geom\" file produced at  PSI\"\"\"\n        config = self.load_geom(filename)\n        shape0 = 0\n        shape1 = 0\n        for m in config.values():\n            shape0 = max(shape0, m.get(\"max_ss\", 0))\n            shape1 = max(shape1, m.get(\"max_fs\", 0))\n        self.MAX_SHAPE = (shape0 + 1, shape1 + 1)\n\n        position_array = numpy.zeros(self.MAX_SHAPE + (4, 3), dtype=numpy.float32)\n\n        for module in config.values():\n            slab = position_array[module[\"min_ss\"]: 1 + module[\"max_ss\"], module[\"min_fs\"]: 1 + module[\"max_fs\"]]\n            ss_edges = numpy.arange(2 + module[\"max_ss\"] - module[\"min_ss\"], dtype=numpy.int32)\n            fs_edges = numpy.arange(2 + module[\"max_fs\"] - module[\"min_fs\"], dtype=numpy.int32)\n            p1 = mathutil.expand2d(ss_edges, fs_edges.size, False)\n            p2 = mathutil.expand2d(fs_edges, ss_edges.size, True)\n            indexes = numpy.vstack([p2.ravel(), p1.ravel()])  # XY\n            mat = numpy.array([module[\"fs\"], module[\"ss\"]], dtype=numpy.float64)\n            position_xy = mat.dot(indexes) + numpy.array([[module[\"corner_x\"]], [module[\"corner_y\"]]])\n            p2, p1 = position_xy.reshape((2,) + p1.shape)\n            slab[:,:, 0, 1] = p1[:-1,:-1]\n            slab[:,:, 0, 2] = p2[:-1,:-1]\n            slab[:,:, 1, 1] = p1[1:,:-1]\n            slab[:,:, 1, 2] = p2[1:,:-1]\n            slab[:,:, 2, 1] = p1[1:, 1:]\n            slab[:,:, 2, 2] = p2[1:, 1:]\n            slab[:,:, 3, 1] = p1[:-1, 1:]\n            slab[:,:, 3, 2] = p2[:-1, 1:]\n        self._pixel_corners = (position_array * self.pixel1).astype(numpy.float32)\n        self.IS_CONTIGUOUS = False\n\n    def calc_mask(self):\n        \"Mask out sub-module junctions\"\n        mask = numpy.zeros(self.MAX_SHAPE, dtype=numpy.int8)\n        mask[255:self.MAX_SHAPE[0] - 2:self.MODULE_SIZE[0]] = 1\n        mask[256:self.MAX_SHAPE[0] - 2:self.MODULE_SIZE[0]] = 1\n        mask[257:self.MAX_SHAPE[0] - 2:self.MODULE_SIZE[0]] = 1\n        mask[258:self.MAX_SHAPE[0] - 2:self.MODULE_SIZE[0]] = 1\n\n        for i in range(0, self.MODULE_SIZE[1], 258):\n            mask[:, i + 255:self.MAX_SHAPE[1] - 2:self.MODULE_SIZE[1]] = 1\n            mask[:, i + 256:self.MAX_SHAPE[1] - 2:self.MODULE_SIZE[1]] = 1\n            mask[:, i + 257:self.MAX_SHAPE[1] - 2:self.MODULE_SIZE[1]] = 1\n            mask[:, i + 258:self.MAX_SHAPE[1] - 2:self.MODULE_SIZE[1]] = 1\n        return mask\n\n", "meta": {"hexsha": "b67f199113fc934bfc6d1af5cd045d94e1a606e1", "size": 12362, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyFAI/detectors/_psi.py", "max_stars_repo_name": "tacaswell/pyFAI", "max_stars_repo_head_hexsha": "fd63c7d9ba35e687ef5c4ec717c01bf46564572a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45, "max_stars_repo_stars_event_min_datetime": "2016-07-16T19:43:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T16:53:47.000Z", "max_issues_repo_path": "pyFAI/detectors/_psi.py", "max_issues_repo_name": "tacaswell/pyFAI", "max_issues_repo_head_hexsha": "fd63c7d9ba35e687ef5c4ec717c01bf46564572a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1125, "max_issues_repo_issues_event_min_datetime": "2016-06-09T07:47:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:34:00.000Z", "max_forks_repo_path": "pyFAI/detectors/_psi.py", "max_forks_repo_name": "tacaswell/pyFAI", "max_forks_repo_head_hexsha": "fd63c7d9ba35e687ef5c4ec717c01bf46564572a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 52, "max_forks_repo_forks_event_min_datetime": "2016-06-09T07:30:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T08:25:11.000Z", "avg_line_length": 42.9236111111, "max_line_length": 113, "alphanum_fraction": 0.5723992881, "include": true, "reason": "import numpy", "num_tokens": 3326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.32766830082071396, "lm_q1q2_score": 0.18420741880658406}}
{"text": "\"\"\"\nThis module contains the classes and functions to generate the zmatrix of\na molecule.\n\"\"\"\n\nfrom copy import deepcopy\n\nimport numpy as np\n\nfrom peleffy.topology.elements import DummyAtom\n\n\nclass ZMatrix(np.ndarray):\n    \"\"\"\n    It generates the zmatrix of a molecule as a numpy.array.\n\n    Inspired by the PlopRotTemp algorithm.\n    \"\"\"\n\n    def __init__(self, topology):\n        \"\"\"\n        It initializes a ZMatrix object.\n\n        Parameters\n        ----------\n        topology : a peleffy.topology.Topology\n            The molecular topology representation to generate the\n            zmatrix with\n\n        Examples\n        --------\n\n        Given a molecular topology, build its Z-matrix\n\n        >>> from peleffy.topology import Molecule\n\n        >>> molecule = Molecule(smiles='Cc1ccccc1')\n\n        >>> from peleffy.forcefield import OpenForceField\n\n        >>> openff = OpenForceField('openff_unconstrained-1.2.1.offxml')\n        >>> parameters = openff.parameterize(molecule)\n\n        >>> from peleffy.topology import Topology\n        >>> topology = Topology(molecule, parameters)\n\n        >>> from peleffy.topology import ZMatrix\n\n        >>> zmatrix = ZMatrix(topology)\n\n        \"\"\"\n        # We will work on a copy of the topology's object to modify it freely\n        self._topology = deepcopy(topology)\n\n    def __new__(cls, topology):\n        \"\"\"\n        It customizes the creation of the numpy.array.\n\n        Parameters\n        ----------\n        topology : a peleffy.topology.Topology\n            The molecular topology representation to generate the\n            zmatrix with\n        \"\"\"\n        topology = deepcopy(topology)\n        obj = np.zeros((len(topology.atoms), 3)).view(cls)\n        coords = cls._extract_coords(topology)\n        obj = cls._build_zmatrix(cls, obj, coords, topology)\n\n        return obj\n\n    @staticmethod\n    def _extract_coords(topology):\n        \"\"\"\n        It extracts the coordinates of the molecule's atoms.\n\n        Parameters\n        ----------\n        topology : a peleffy.topology.Topology\n            The molecular topology representation to generate the\n            zmatrix with\n\n        Returns\n        -------\n        coords : list[tuple[float]]\n            The coordinates of the molecule\n        \"\"\"\n        coords = list()\n        for atom in topology.atoms:\n            coords.append((atom.x, atom.y, atom.z))\n\n        return coords\n\n    @staticmethod\n    def _get_absolute_parent(topology):\n        \"\"\"\n        It returns the absolute parent in the topology of the molecule.\n\n        Parameters\n        ----------\n        topology : a peleffy.topology.Topology\n            The molecular topology representation to generate the\n            zmatrix with\n\n        Returns\n        -------\n        absolute_parent : peleffy.topology.molecule.Atom\n            The absolute parent of the molecule\n        \"\"\"\n        absolute_parent = list()\n        for atom in topology.atoms:\n            if atom.parent is None:\n                absolute_parent.append(atom)\n\n        assert len(absolute_parent) == 1, 'Only 1 absolute parent is expected'\n\n        return absolute_parent[0]\n\n    @staticmethod\n    def _calculate_bond(x1, y1, z1, x2, y2, z2):\n        \"\"\"\n        It calculates the bond distance between two sets of coordinates.\n\n        Parameters\n        ----------\n        x1 : float\n            The x1 coordinate\n        y1 : float\n            The y1 coordinate\n        z1 : float\n            The z1 coordinate\n        x2 : float\n            The x2 coordinate\n        y2 : float\n            The y2 coordinate\n        z2 : float\n            The z2 coordinate\n\n        Returns\n        -------\n        distance : float\n            The bond distance between the two sets of coordinates\n        \"\"\"\n        dx = x1 - x2\n        dy = y1 - y2\n        dz = z1 - z2\n\n        return np.sqrt(dx * dx + dy * dy + dz * dz)\n\n    @staticmethod\n    def _calculate_angle(x1, y1, z1, x2, y2, z2, x3, y3, z3):\n        \"\"\"\n        It calculates the angle between three sets of coordinates.\n\n        Parameters\n        ----------\n        x1 : float\n            The x1 coordinate\n        y1 : float\n            The y1 coordinate\n        z1 : float\n            The z1 coordinate\n        x2 : float\n            The x2 coordinate\n        y2 : float\n            The y2 coordinate\n        z2 : float\n            The z2 coordinate\n        x3 : float\n            The x3 coordinate\n        y3 : float\n            The y3 coordinate\n        z3 : float\n            The z3 coordinate\n\n        Returns\n        -------\n        angle : float\n            The angle between the three sets of coordinates\n        \"\"\"\n        dx_12 = x1 - x2\n        dy_12 = y1 - y2\n        dz_12 = z1 - z2\n\n        dx_31 = x3 - x1\n        dy_31 = y3 - y1\n        dz_31 = z3 - z1\n\n        vdot = dx_12 * dx_31 + dy_12 * dy_31 + dz_12 * dz_31\n\n        assert np.fabs(vdot) > 0, 'A non-zero angle is expected'\n\n        d12 = np.sqrt(dx_12 * dx_12 + dy_12 * dy_12 + dz_12 * dz_12)\n        d31 = np.sqrt(dx_31 * dx_31 + dy_31 * dy_31 + dz_31 * dz_31)\n\n        xang = vdot / (d12 * d31)\n\n        if xang - 1.0 > -0.0000000001:\n            return 0.0\n        elif xang + 1.0 < 0.0000000001:\n            return np.pi\n\n        return np.arccos(xang) * 180.0 / np.pi\n\n    @staticmethod\n    def _calculate_dihedral(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4):\n        \"\"\"\n        It calculates the dihedral between four sets of coordinates.\n\n        Parameters\n        ----------\n        x1 : float\n            The x1 coordinate\n        y1 : float\n            The y1 coordinate\n        z1 : float\n            The z1 coordinate\n        x2 : float\n            The x2 coordinate\n        y2 : float\n            The y2 coordinate\n        z2 : float\n            The z2 coordinate\n        x3 : float\n            The x3 coordinate\n        y3 : float\n            The y3 coordinate\n        z3 : float\n            The z3 coordinate\n        x4 : float\n            The x4 coordinate\n        y4 : float\n            The y4 coordinate\n        z4 : float\n            The z4 coordinate\n\n        Returns\n        -------\n        dihedral : float\n            The dihedral between the four sets of coordinates\n        \"\"\"\n        dx_12 = x1 - x2\n        dy_12 = y1 - y2\n        dz_12 = z1 - z2\n\n        dx_32 = x3 - x2\n        dy_32 = y3 - y2\n        dz_32 = z3 - z2\n\n        dx_34 = x3 - x4\n        dy_34 = y3 - y4\n        dz_34 = z3 - z4\n\n        ax = dy_12 * dz_32 - dz_12 * dy_32\n        ay = dz_12 * dx_32 - dx_12 * dz_32\n        az = dx_12 * dy_32 - dy_12 * dx_32\n        cx = dy_32 * dz_34 - dz_32 * dy_34\n        cy = dz_32 * dx_34 - dx_32 * dz_34\n        cz = dx_32 * dy_34 - dy_32 * dx_34\n\n        rac = ax * cx + ay * cy + az * cz\n        ra = ax * ax + ay * ay + az * az\n        rc = cx * cx + cy * cy + cz * cz\n\n        cosang = rac / np.sqrt(ra * rc)\n\n        if cosang - 1.0 > -0.00000000001:\n            phi = 0.0\n        elif cosang + 1.0 < 0.00000000001:\n            phi = np.pi\n        else:\n            phi = np.arccos(cosang)\n\n        s = dx_12 * cx + dy_12 * cy + dz_12 * cz\n        if (s < 0):\n            phi = -phi  # to account for phi between pi and 2pi\n\n        return phi * 180.0 / np.pi\n\n    @staticmethod\n    def _build_zmatrix(cls, obj, coords, topology):\n        \"\"\"\n        It buils the zmatrix.\n\n        Parameters\n        ----------\n        cls : ZMatrix class\n            The ZMatrix class\n        obj : ZMatrix object\n            The ZMatrix object\n        coords : list[tuple[float]]\n            The coordinates of the molecule\n        topology : a peleffy.topology.Topology\n            The molecular topology representation to generate the\n            zmatrix with\n\n        Returns\n        -------\n        obj :  ZMatrix object\n            The ZMatrix object which is a numpy.array with the corresponding\n            zmatrix initialized.\n        \"\"\"\n        dummy1 = DummyAtom(index=-3, PDB_name='DUM1', parent=None)\n        dummy2 = DummyAtom(index=-2, PDB_name='DUM2', parent=dummy1)\n        dummy3 = DummyAtom(index=-1, PDB_name='DUM3', parent=dummy2)\n        absolute_parent = cls._get_absolute_parent(topology)\n        absolute_parent.set_parent(dummy3)\n\n        dummy1.set_coords([0.0, 0.0, 0.0])  # at origin\n        dummy2.set_coords([0.0, 0.0, 1.0])  # at z axis\n        dummy3.set_coords([1.0, 0.0, 0.0])  # at x axis\n\n        for i, atom in enumerate(topology.atoms):\n            atom1 = atom\n            atom2 = atom1.parent\n            atom3 = atom2.parent\n            atom4 = atom3.parent\n\n            assert atom1 is not None and atom2 is not None \\\n                and atom3 is not None and atom4 is not None, \\\n                'A None as parent is not expected'\n\n            x1, y1, z1 = (atom1.x, atom1.y, atom1.z)\n            x2, y2, z2 = (atom2.x, atom2.y, atom2.z)\n            x3, y3, z3 = (atom3.x, atom3.y, atom3.z)\n            x4, y4, z4 = (atom4.x, atom4.y, atom4.z)\n\n            obj[i][0] = cls._calculate_bond(x1, y1, z1,\n                                            x2, y2, z2)\n            obj[i][1] = cls._calculate_angle(x1, y1, z1,\n                                             x2, y2, z2,\n                                             x3, y3, z3)\n            obj[i][2] = cls._calculate_dihedral(x1, y1, z1,\n                                                x2, y2, z2,\n                                                x3, y3, z3,\n                                                x4, y4, z4)\n\n        return obj\n", "meta": {"hexsha": "16d4cc83c07cfc674a4707a7b5eccd5aaed33f21", "size": 9450, "ext": "py", "lang": "Python", "max_stars_repo_path": "peleffy/topology/zmatrix.py", "max_stars_repo_name": "frumpowy/peleffy", "max_stars_repo_head_hexsha": "9b6110a9bf50bedd8e299271a8ff9c3b79339e63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-11-16T15:07:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T12:48:20.000Z", "max_issues_repo_path": "peleffy/topology/zmatrix.py", "max_issues_repo_name": "NBDsoftware/peleffy", "max_issues_repo_head_hexsha": "d0ca27a366f74b097aac450451f2ad47a3a3f5c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 75, "max_issues_repo_issues_event_min_datetime": "2020-11-02T18:49:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T16:41:26.000Z", "max_forks_repo_path": "peleffy/topology/zmatrix.py", "max_forks_repo_name": "NBDsoftware/peleffy", "max_forks_repo_head_hexsha": "d0ca27a366f74b097aac450451f2ad47a3a3f5c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-12-02T16:00:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T11:11:30.000Z", "avg_line_length": 27.8761061947, "max_line_length": 78, "alphanum_fraction": 0.5135449735, "include": true, "reason": "import numpy", "num_tokens": 2512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.18413818819528052}}
{"text": "\"\"\"\nA GP prior over qso spectrum for zQSO estimation.\n\"\"\"\nfrom .null_gp import NullGP\n\nimport numpy as np\nfrom scipy import interpolate\nimport h5py\n\nfrom .zqso_set_parameters import ZParameters\nfrom .zqso_samples import ZSamples\n\n\nclass ZGP(NullGP):\n    \"\"\"\n    GP inference on zQSO:\n        p(y | λ, σ², M, ω, blue_σ², red_σ²),\n    where we also model the data outside of the modelling window\n    as i.i.d Gaussians. See details in\n    <Automated Measurement of Quasar Redshift with a Gaussian Process\n    https://arxiv.org/abs/2006.07343>\n\n    :param rest_wavelengths: λ, the range of λ you model your GP on QSO emission\n    :param mu: mu, the mean model of the GP.\n    :param M: M, the low rank decomposition of the covariance kernel: K = MM^T.\n    :param bluewards_mu: the mean model for blueward part of the data outside of\n        the modelling window.\n    :param bluewards_sigma: the noise model for blueward part of the data outside of\n        the modelling window.\n    :param redwards_mu: the mean model for redward part of the data outside of\n        the modelling window.\n    :param redwards_sigma: the noise model for redward part of the data outside of\n        the modelling window.\n    \"\"\"\n\n    def __init__(\n        self,\n        params: ZParameters,\n        z_qso_samples: ZSamples,\n        rest_wavelengths: np.ndarray,\n        mu: np.ndarray,\n        M: np.ndarray,\n        bluewards_mu: float,\n        redwards_mu: float,\n        bluewards_sigma: float,\n        redwards_sigma: float,\n    ):\n        self.params = params\n        self.z_qso_samples = z_qso_samples\n\n        # learned GP model\n        self.rest_wavelengths = rest_wavelengths\n        self.mu = mu\n        self.M = M\n        self.bluewards_mu = bluewards_mu\n        self.redwards_mu = redwards_mu\n        self.bluewards_sigma = bluewards_sigma\n        self.redwards_sigma = redwards_sigma\n\n        # preprocess model interpolants\n        self.mu_interpolator = interpolate.interp1d(rest_wavelengths, mu)\n        self.list_M_interpolators = [\n            interpolate.interp1d(rest_wavelengths, eigenvector) for eigenvector in M.T\n        ]\n\n    def get_interp(\n        self, x: np.ndarray, y: np.ndarray, wavelengths: np.ndarray, z_qso: float\n    ) -> None:\n        \"\"\"\n        Build and interpolate the GP model onto the observed data.\n        \n        p(y | λ, zqso, v, ω, M_nodla) = N(y; μ, (K + Ω) + V)\n        \n        :param x: this_rest_wavelengths\n        :param y: this_flux\n        :param wavelengths: observed wavelengths, put this arg is just for making the\n            code looks similar to the MATLAB code. This could be taken off in the future.\n        :param z_qso: quasar redshift\n\n        Note: assume already pixel masked.\n        \"\"\"\n        # interpolate model onto given wavelengths\n        this_mu = self.mu_interpolator(x)\n        this_M = self.M_interpolator(x)\n\n        assert this_M.shape[1] == self.params.k\n\n        # assign to instance attrs\n        self.this_mu = this_mu\n        self.this_M = this_M\n\n    def set_data(\n        self,\n        X: np.ndarray,\n        Y: np.ndarray,\n        noise_variance: np.ndarray,\n        pixel_mask: np.ndarray,\n        z_qso: float,\n        normalize: bool = True,\n        build_model: bool = True,\n    ) -> None:\n        \"\"\"\n        Set \"testing\" data to be evaluated. Now assumed to be a single\n        spectrum, but we can implement a batch of spectra in the future.\n\n        The difference between this and the null model set_data is that\n        we need to keep all of the data no matter they are inside or\n        outside the modelling range, and extend the model to fill up\n        all of the data points.\n\n        :param X: (n_points, ) this_wavelengths, the `OBSERVED` wavelengths of the spectrum.\n        :param Y: (n_points, ) this_flux, the flux of the observed spectrum\n        :param noise_variance: (n_points, ) the instrumental noise variance per pixel.\n        :param pixel_mask: (n_points, ) the pixel mask corresponding to the read_spec you used.\n        :param z_qso: the redshift of the quasar.\n\n        Note: n_points represents number of pixels within a spectrum\n        \"\"\"\n        # variant redshift in quasars\n        self.z_qso = z_qso\n\n        # cut-off observations\n        max_pos_lambda = self.params.observed_wavelengths(self.params.max_lambda, z_qso)\n        min_pos_lambda = self.params.observed_wavelengths(self.params.min_lambda, z_qso)\n\n        max_observed_lambda = np.min((max_pos_lambda, np.max(X)))\n        min_observed_lambda = np.max((min_pos_lambda, np.min(X)))\n\n        labmda_observed = max_observed_lambda - min_observed_lambda\n\n        # filter the spectrum; these quantities are within the modelling window\n        ind = (X > min_observed_lambda) * (X < max_observed_lambda)\n        self.y = Y[ind]\n        self.this_wavelengths = X[ind]\n        self.v = noise_variance[ind]\n        self.pixel_mask = pixel_mask[ind]\n\n        # convert to QSO rest frame\n        self.x = self.params.emitted_wavelengths(X[ind], z_qso)\n\n        # normalize flux\n        if normalize:\n            ind = (self.x >= self.params.normalization_min_lambda) & (\n                self.x <= self.params.normalization_max_lambda\n            )\n            this_median = np.nanmedian(self.y[ind])\n            self.y = self.y / this_median\n            self.v = self.v / this_median ** 2\n\n        # Normalise the observed flux for out-of-range model since the\n        # redward- and blueward- models were trained with normalisation.\n        # Find probability for out-of-range model\n        this_normalized_flux = (\n            Y / this_median\n        )  # since we've modified self.y, we thus need to\n        # use this_out_flux which is outside the parfor loop\n        this_normalized_v = noise_variance / this_median ** 2\n\n        # select blueward region\n        ind_bw = (X < min_observed_lambda) & (~pixel_mask)\n        self.y_bw = this_normalized_flux[ind_bw]\n        self.v_bw = this_normalized_v[ind_bw]\n        # select redward region\n        ind_rw = (X > max_observed_lambda) & (~pixel_mask)\n        self.y_rw = this_normalized_flux[ind_rw]\n        self.v_rw = this_normalized_v[ind_rw]\n\n        # apply pixel mask and filter spectrum within modelling range\n        ind = (self.x >= self.params.min_lambda) & (self.x <= self.params.max_lambda)\n        ind = ind & (~self.pixel_mask)\n\n        self.this_wavelengths = self.this_wavelengths[ind]\n        self.x = self.x[ind]\n        self.y = self.y[ind]\n        self.v = self.v[ind]\n\n        self.v[np.isinf(self.v)] = np.nanmean(self.v)  # rare kludge to fix bad data\n\n        self.ind = ind\n\n        if build_model:\n            self.get_interp(self.x, self.y, self.this_wavelengths, self.z_qso)\n\n    def log_model_evidence(self) -> float:\n        \"\"\"\n        Compute the log model evidence with the learned model.\n        \n        Note: assume the model has already interpolated onto the observed data,\n        and data got loaded into the GP instance.        \n        \"\"\"\n        # log likelihood within the modelling window\n        log_likelihood = self.log_mvnpdf_low_rank(\n            self.y, self.this_mu, self.this_M, self.v\n        )\n\n        n_bw = self.y_bw.shape[0]\n        n_rw = self.y_rw.shape[0]\n\n        # calculate log likelihood of iid multivariate normal with\n        #   log N(y; mu, diag(V) + sigma^2 )\n        bw_log_likelihood = self.log_mvnpdf_iid(\n            self.y_bw,\n            self.bluewards_mu * np.ones((n_bw,)),\n            self.bluewards_sigma ** 2 * np.ones((n_bw,)) + self.v_bw,\n        )\n        rw_log_likelihood = self.log_mvnpdf_iid(\n            self.y_rw,\n            self.redwards_mu * np.ones((n_rw,)),\n            self.redwards_sigma ** 2 * np.ones((n_rw,)) + self.v_rw,\n        )\n\n        return log_likelihood + bw_log_likelihood + rw_log_likelihood\n\n    def inference_z_qso(\n        self,\n        wavelengths: np.ndarray,\n        flux: np.ndarray,\n        noise_variance: np.ndarray,\n        pixel_mask: np.ndarray,\n        z_qso_min: float = 2.14,\n        z_qso_max: float = 6.16,\n    ):\n        \"\"\"\n        Sample the zQSO within a prior volume define in self.z_qso_samples\n        \"\"\"\n        sample_log_likelihoods = np.full((self.z_qso_samples.num_zqso_samples,), np.nan)\n        sample_z_qsos = self.z_qso_samples.sample_z_qsos(\n            z_qso_min=z_qso_min, z_qso_max=z_qso_max\n        )\n\n        for i, z_qso in enumerate(sample_z_qsos):\n            # set the data and interpolate the model\n            self.set_data(\n                wavelengths,\n                flux,\n                noise_variance,\n                pixel_mask,\n                z_qso=z_qso,\n                normalize=True,\n                build_model=True,\n            )\n\n            sample_log_likelihoods[i] = self.log_model_evidence()\n\n        self.sample_log_likelihoods = sample_log_likelihoods\n\n        # maximum a posteriori\n        I = np.nanargmax(sample_log_likelihoods)\n        self.z_map = sample_z_qsos[I]\n        print(\"[Info] Z MAP = {:.3g}\".format(self.z_map))\n\n    @staticmethod\n    def log_mvnpdf_iid(y: np.ndarray, mu: np.ndarray, d: np.ndarray,) -> float:\n        \"\"\"\n        computes mutlivariate normal dist with\n        each dim is iid, so no covariance. \n            log N(y; mu, diag(d))\n\n        :param y: this_flux, (n_points, )\n        :param mu: this_mu, the mean vector of GP, (n_points, )\n        :param d: diagonal noise term, (n_points, )\n        \"\"\"\n        log_2pi = 1.83787706640934534\n\n        n = d.shape[0]\n\n        y = y[:, None] - mu[:, None]\n\n        d_inv = 1 / d[:, None]  # (n_points, 1)\n        D_inv_y = d_inv * y  # (n_points, 1)\n\n        K_inv_y = D_inv_y  # (n_points, 1)\n\n        log_det_K = np.sum(np.log(d))\n\n        log_p = -0.5 * (np.matmul(y.T, K_inv_y).sum() + log_det_K + n * log_2pi)\n\n        return log_p\n\n    @property\n    def this_noise(self):\n        \"\"\"\n        noise kernel: instrumental noise\n        \"\"\"\n        return self.v\n\n\nclass ZGPMAT(ZGP):\n    \"\"\"\n    Load learned model from .mat file\n    \"\"\"\n\n    def __init__(\n        self,\n        params: ZParameters,\n        z_qso_samples: ZSamples,\n        learned_file: str = \"learned_zqso_only_model_outdata_full_dr9q_minus_concordance_norm_1176-1256.mat\",\n    ):\n        with h5py.File(learned_file, \"r\") as learned:\n\n            rest_wavelengths = learned[\"rest_wavelengths\"][:, 0]\n            mu = learned[\"mu\"][:, 0]\n            M = learned[\"M\"][()].T\n            bluewards_mu = learned[\"bluewards_mu\"][0, 0]\n            redwards_mu = learned[\"redwards_mu\"][0, 0]\n            bluewards_sigma = learned[\"bluewards_sigma\"][0, 0]\n            redwards_sigma = learned[\"redwards_sigma\"][0, 0]\n\n        super().__init__(\n            params=params,\n            z_qso_samples=z_qso_samples,\n            rest_wavelengths=rest_wavelengths,\n            mu=mu,\n            M=M,\n            bluewards_mu=bluewards_mu,\n            redwards_mu=redwards_mu,\n            bluewards_sigma=bluewards_sigma,\n            redwards_sigma=redwards_sigma,\n        )\n", "meta": {"hexsha": "7b56b42b36278fa2c9c9f7d5ae5ead13e9b6e3ee", "size": 11012, "ext": "py", "lang": "Python", "max_stars_repo_path": "gpy_dla_detection/zqso_gp.py", "max_stars_repo_name": "jibanCat/gpy_dla_detection", "max_stars_repo_head_hexsha": "4d987adec75a417313fdc6601ee41a0ea60a0a2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-31T01:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-31T01:31:52.000Z", "max_issues_repo_path": "gpy_dla_detection/zqso_gp.py", "max_issues_repo_name": "jibanCat/gpy_dla_detection", "max_issues_repo_head_hexsha": "4d987adec75a417313fdc6601ee41a0ea60a0a2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-07-20T18:55:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T05:08:26.000Z", "max_forks_repo_path": "gpy_dla_detection/zqso_gp.py", "max_forks_repo_name": "jibanCat/gpy_dla_detection", "max_forks_repo_head_hexsha": "4d987adec75a417313fdc6601ee41a0ea60a0a2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4125, "max_line_length": 109, "alphanum_fraction": 0.6109698511, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.18413818750733035}}
{"text": "import numpy as np\nfrom scipy import interpolate\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import AutoMinorLocator\nimport pandas as pd\nfrom astropy.io import fits\nfrom astropy import units as u\nimport sys\nimport os\nimport warnings\nimport copy\nimport smart\nwarnings.filterwarnings(\"ignore\")\n\n\nclass Spectrum():\n\t\"\"\"\n\tThe spectrum class for reading the reduced Keck/NIRSPEC data by NSDRP and SDSS/APOGEE data.\n\n\tParameters\n\t----------\n\tname : str\n\t       The data filename before the order number.\n\t       Ex. name='jan19s0022'\n\torder: int\n\t       The order of the spectra.\n\tpath : str\n\t       The directory where the reduced data is.\n\n\tReturns\n\t-------\n\tflux : numpy.ndarray\n\t       The flux of the spectrum.\n\twave : numpy.ndarray\n\t       The wavelength of the spectrum\n\tnoise: numpy.ndarray\n\t       The noise of the spectrum\n\tsky  : numpy.ndarray\n\t       The sky emission\n\tplot : matplotlib plot\n\t       plot the spectrum (with noise on/off option)\n\n\tExamples\n\t--------\n\t>>> import smart\n\t>>> path = '/path/to/reducedData'\n\t>>> data = smart.Spectrum(name='jan19s0022', order=33, path=path)\n\t>>> data.plot()\n\n\t\"\"\"\n\tdef __init__(self, **kwargs):\n\t\tself.instrument = kwargs.get('instrument','nirspec')\n\t\tif self.instrument == 'nirspec':\n\t\t\tself.name      = kwargs.get('name')\n\t\t\tself.order     = kwargs.get('order')\n\t\t\tself.path      = kwargs.get('path')\n\t\t\tself.apply_sigma_mask = kwargs.get('apply_sigma_mask',False)\n\t\t\t#self.manaulmask = kwargs('manaulmask', False)\n\n\t\t\tif self.path == None:\n\t\t\t\tself.path = './'\n\n\t\t\tfullpath = self.path + '/' + self.name + '_' + str(self.order) + '_all.fits'\n\n\t\t\thdulist = fits.open(fullpath, ignore_missing_end=True)\n\n\t\t\t#The indices 0 to 3 correspond to wavelength, flux, noise, and sky\n\t\t\tself.header = hdulist[0].header\n\t\t\tself.wave   = hdulist[0].data\n\t\t\tself.flux   = hdulist[1].data\n\t\t\tself.noise  = hdulist[2].data\n\t\t\ttry:\n\t\t\t\tself.sky = hdulist[3].data\n\t\t\texcept IndexError:\n\t\t\t\tprint(\"No sky line data.\")\n\t\t\t\tself.sky = np.zeros(self.wave.shape)\n\n\t\t\tself.mask  = []\n\n\t\t\t# define a list for storing the best wavelength shift\n\t\t\tself.bestshift = []\n\n\t\t\t# store the original parameters\n\t\t\tself.oriWave  = hdulist[0].data\n\t\t\tself.oriFlux  = hdulist[1].data\n\t\t\tself.oriNoise = hdulist[2].data\n\n\t\telif self.instrument == 'apogee':\n\t\t\tself.name      = kwargs.get('name')\n\t\t\tself.path      = kwargs.get('path')\n\t\t\tself.datatype  = kwargs.get('datatype','aspcap')\n\t\t\tself.apply_sigma_mask = kwargs.get('apply_sigma_mask',False)\n\t\t\tself.applytell = kwargs.get('applytell', False)\n\t\t\tself.chip      = kwargs.get('chip', 'all')\n\n\t\t\thdulist        = fits.open(self.path)\n\t\t\t\n\t\t\tif self.datatype == 'aspcap':\n\t\t\t\tcrval1         = hdulist[1].header['CRVAL1']\n\t\t\t\tcdelt1         = hdulist[1].header['CDELT1']\n\t\t\t\tnaxis1         = hdulist[1].header['NAXIS1']\n\t\t\t\tself.header4   = hdulist[4].header\n\t\t\t\tself.param     = hdulist[4].data['PARAM']\n\t\t\t\tself.wave      = np.array(pow(10, crval1 + cdelt1 * np.arange(naxis1)))\n\t\t\t\tself.oriWave   = np.array(pow(10, crval1 + cdelt1 * np.arange(naxis1)))\n\t\t\t\tself.flux      = np.array(hdulist[1].data)\n\t\t\t\tself.noise     = np.array(hdulist[2].data)\n\n\t\t\t\n\t\t\telif self.datatype == 'ap1d':\n\t\t\t\tself.header4   = hdulist[4].header\n\t\t\t\tself.header5   = hdulist[5].header\n\t\t\t\t# use aspcap data as wavelength calibrators\n\t\t\t\tself.wave      = np.array(hdulist[4].data)\n\t\t\t\tself.flux      = np.array(hdulist[1].data)\n\t\t\t\tself.noise     = np.array(hdulist[2].data)\n\t\t\t\t# store the original parameters\n\t\t\t\tself.oriWave   = np.array(hdulist[4].data)\n\t\t\t\tself.oriFlux  = np.array(hdulist[1].data)\n\t\t\t\tself.oriNoise = np.array(hdulist[2].data)\n\t\t\t\n\t\t\telif self.datatype == 'apvisit':\n\t\t\t\tself.header1   = hdulist[1].header\n\t\t\t\tself.header2   = hdulist[2].header\n\t\t\t\tself.header3   = hdulist[3].header\n\t\t\t\tself.header4   = hdulist[4].header\n\t\t\t\tself.header5   = hdulist[5].header\n\t\t\t\tself.header6   = hdulist[6].header\n\t\t\t\tself.header7   = hdulist[7].header\n\t\t\t\tself.header8   = hdulist[8].header\n\t\t\t\tself.header9   = hdulist[9].header\n\t\t\t\tself.header10  = hdulist[10].header\n\n\t\t\t\t# read the bitmask\n\t\t\t\tself.bitmask   = hdulist[3].data\n\n\t\t\t\t#import bitmask\n\t\t\t\t# chip a\n\t\t\t\tif self.chip == 'all' or self.chip == 'a':\n\t\t\t\t\tmask_0 = []\n\t\t\t\t\tfor i in range(len(hdulist[3].data[0])):\n\t\t\t\t\t\tbitmask = smart.bits_set(hdulist[3].data[0][i])\n\t\t\t\t\t\tif (0 in bitmask) or (1 in bitmask) or (2 in bitmask) or \\\n\t\t\t\t\t\t(3 in bitmask) or (4 in bitmask) or (5 in bitmask) or \\\n\t\t\t\t\t\t(6 in bitmask) or (12 in bitmask) or (14 in bitmask):\n\t\t\t\t\t\t\tmask_0.append(i)\n\t\t\t\t\n\t\t\t\t# chip b\n\t\t\t\tif self.chip == 'all' or self.chip == 'b':\n\t\t\t\t\tmask_1 = []\n\t\t\t\t\tfor i in range(len(hdulist[3].data[1])):\n\t\t\t\t\t\tbitmask = smart.bits_set(hdulist[3].data[1][i])\n\t\t\t\t\t\tif (0 in bitmask) or (1 in bitmask) or (2 in bitmask) or \\\n\t\t\t\t\t\t(3 in bitmask) or (4 in bitmask) or (5 in bitmask) or \\\n\t\t\t\t\t\t(6 in bitmask) or (12 in bitmask) or (14 in bitmask):\n\t\t\t\t\t\t\tmask_1.append(i)\n\t\t\t\t\n\t\t\t\t# chip c\n\t\t\t\tif self.chip == 'all' or self.chip == 'c':\n\t\t\t\t\tmask_2 = []\n\t\t\t\t\tfor i in range(len(hdulist[3].data[2])):\n\t\t\t\t\t\tbitmask = smart.bits_set(hdulist[3].data[2][i])\n\t\t\t\t\t\tif (0 in bitmask) or (1 in bitmask) or (2 in bitmask) or \\\n\t\t\t\t\t\t(3 in bitmask) or (4 in bitmask) or (5 in bitmask) or \\\n\t\t\t\t\t\t(6 in bitmask) or (12 in bitmask) or (14 in bitmask):\n\t\t\t\t\t\t\tmask_2.append(i)\n\n\n\t\t\t\tif self.chip == 'all':\n\t\t\t\t\tself.wave      = np.array(list(np.delete(hdulist[4].data[0], mask_0))+list(np.delete(hdulist[4].data[1], mask_1))+list(np.delete(hdulist[4].data[2], mask_2)))\n\t\t\t\t\tself.flux      = np.array(list(np.delete(hdulist[1].data[0], mask_0))+list(np.delete(hdulist[1].data[1], mask_1))+list(np.delete(hdulist[1].data[2], mask_2)))\n\t\t\t\t\tself.noise     = np.array(list(np.delete(hdulist[2].data[0], mask_0))+list(np.delete(hdulist[2].data[1], mask_1))+list(np.delete(hdulist[2].data[2], mask_2)))\n\t\t\t\t\tself.sky       = np.array(list(hdulist[5].data[0])+list(hdulist[5].data[1])+list(hdulist[5].data[2]))\n\t\t\t\t\tself.skynoise  = np.array(list(hdulist[6].data[0])+list(hdulist[6].data[1])+list(hdulist[6].data[2]))\n\t\t\t\t\tself.tell      = np.array(list(np.delete(hdulist[7].data[0], mask_0))+list(np.delete(hdulist[7].data[1], mask_1))+list(np.delete(hdulist[7].data[2], mask_2)))\n\t\t\t\t\tself.tellnoise = np.array(list(np.delete(hdulist[8].data[0], mask_0))+list(np.delete(hdulist[8].data[1], mask_1))+list(np.delete(hdulist[8].data[2], mask_2)))\n\t\t\t\t\n\t\t\t\t\t# store the original parameters\n\t\t\t\t\tself.oriWave   = np.array(list(hdulist[4].data[0])+list(hdulist[4].data[1])+list(hdulist[4].data[2]))\n\t\t\t\t\tself.oriFlux   = np.array(list(hdulist[1].data[0])+list(hdulist[1].data[1])+list(hdulist[1].data[2]))\n\t\t\t\t\tself.oriNoise  = np.array(list(hdulist[2].data[0])+list(hdulist[2].data[1])+list(hdulist[2].data[2]))\n\n\t\t\t\telif self.chip == 'a':\n\t\t\t\t\tself.wave      = np.array(list(np.delete(hdulist[4].data[0], mask_0)))\n\t\t\t\t\tself.flux      = np.array(list(np.delete(hdulist[1].data[0], mask_0)))\n\t\t\t\t\tself.noise     = np.array(list(np.delete(hdulist[2].data[0], mask_0)))\n\t\t\t\t\tself.sky       = np.array(list(hdulist[5].data[0]))\n\t\t\t\t\tself.skynoise  = np.array(list(hdulist[6].data[0]))\n\t\t\t\t\tself.tell      = np.array(list(np.delete(hdulist[7].data[0], mask_0)))\n\t\t\t\t\tself.tellnoise = np.array(list(np.delete(hdulist[8].data[0], mask_0)))\n\t\t\t\t\n\t\t\t\t\t# store the original parameters\n\t\t\t\t\tself.oriWave   = np.array(list(hdulist[4].data[0]))\n\t\t\t\t\tself.oriFlux   = np.array(list(hdulist[1].data[0]))\n\t\t\t\t\tself.oriNoise  = np.array(list(hdulist[2].data[0]))\n\n\t\t\t\telif self.chip == 'b':\n\t\t\t\t\tself.wave      = np.array(list(np.delete(hdulist[4].data[1], mask_1)))\n\t\t\t\t\tself.flux      = np.array(list(np.delete(hdulist[1].data[1], mask_1)))\n\t\t\t\t\tself.noise     = np.array(list(np.delete(hdulist[2].data[1], mask_1)))\n\t\t\t\t\tself.sky       = np.array(list(hdulist[5].data[1]))\n\t\t\t\t\tself.skynoise  = np.array(list(hdulist[6].data[1]))\n\t\t\t\t\tself.tell      = np.array(list(np.delete(hdulist[7].data[1], mask_1)))\n\t\t\t\t\tself.tellnoise = np.array(list(np.delete(hdulist[8].data[1], mask_1)))\n\t\t\t\t\n\t\t\t\t\t# store the original parameters\n\t\t\t\t\tself.oriWave   = np.array(list(hdulist[4].data[1]))\n\t\t\t\t\tself.oriFlux   = np.array(list(hdulist[1].data[1]))\n\t\t\t\t\tself.oriNoise  = np.array(list(hdulist[2].data[1]))\n\n\t\t\t\telif self.chip == 'c':\n\t\t\t\t\tself.wave      = np.array(list(np.delete(hdulist[4].data[2], mask_2)))\n\t\t\t\t\tself.flux      = np.array(list(np.delete(hdulist[1].data[2], mask_2)))\n\t\t\t\t\tself.noise     = np.array(list(np.delete(hdulist[2].data[2], mask_2)))\n\t\t\t\t\tself.sky       = np.array(list(hdulist[5].data[2]))\n\t\t\t\t\tself.skynoise  = np.array(list(hdulist[6].data[2]))\n\t\t\t\t\tself.tell      = np.array(list(np.delete(hdulist[7].data[2], mask_2)))\n\t\t\t\t\tself.tellnoise = np.array(list(np.delete(hdulist[8].data[2], mask_2)))\n\t\t\t\t\n\t\t\t\t\t# store the original parameters\n\t\t\t\t\tself.oriWave   = np.array(list(hdulist[4].data[2]))\n\t\t\t\t\tself.oriFlux   = np.array(list(hdulist[1].data[2]))\n\t\t\t\t\tself.oriNoise  = np.array(list(hdulist[2].data[2]))\n\n\t\t\t\tif self.applytell:\n\t\t\t\t\tself.flux *= self.tell\n\t\t\t\tself.wavecoeff = hdulist[9].data\n\t\t\t\tself.lsfcoeff  = hdulist[10].data\n\n\n\n\t\t\t\tif self.wave[0] > self.wave[-1]:\n\t\t\t\t\tself.wave      = self.wave[::-1]\n\t\t\t\t\tself.flux      = self.flux[::-1]\n\t\t\t\t\tself.noise     = self.noise[::-1]\n\t\t\t\t\tself.sky       = self.sky[::-1]\n\t\t\t\t\tself.skynoise  = self.skynoise[::-1]\n\t\t\t\t\tself.tell      = self.tell[::-1]\n\t\t\t\t\tself.tellnoise = self.tellnoise[::-1]\n\t\t\t\t\tself.oriWave   = self.oriWave[::-1]\n\t\t\t\t\tself.oriFlux   = self.oriFlux[::-1]\n\t\t\t\t\tself.oriNoise  = self.oriNoise[::-1]\n\n\t\t\t\t# to separate the continuum end points\n\t\t\t\tself.oriWave0  = hdulist[4].data\n\t\t\t\tself.oriFlux0  = hdulist[1].data\n\n\t\t\t\t## APOGEE APVISIT has corrected the telluric absorption; the forward-modeling routine needs to put it back\n\t\t\t\t#self.flux     *= self.tell\n\n\t\t\telif self.datatype == 'apstar':\n\t\t\t\tcrval1         = hdulist[0].header['CRVAL1']\n\t\t\t\tcdelt1         = hdulist[0].header['CDELT1']\n\t\t\t\tnaxis1         = hdulist[0].header['NWAVE']\n\t\t\t\tself.header4   = hdulist[4].header\n\t\t\t\tself.header5   = hdulist[5].header\n\t\t\t\tself.header6   = hdulist[6].header\n\t\t\t\tself.header7   = hdulist[7].header\n\t\t\t\tself.header8   = hdulist[8].header\n\t\t\t\tself.header9   = hdulist[9].header\n\n\t\t\t\t#print(hdulist)\n\t\t\t\t#print(hdulist[1])\n\t\t\t\t#print(hdulist[1].data.shape)\n\t\t\t\t#sys.exit()\n\n\t\t\t\tself.wave      = np.array(pow(10, crval1 + cdelt1 * np.arange(1, naxis1+1)))\n\t\t\t\tself.flux      = hdulist[1].data\n\t\t\t\tself.noise     = hdulist[2].data\n\t\t\t\tself.sky       = hdulist[4].data\n\t\t\t\tself.skynoise  = hdulist[5].data\n\t\t\t\tself.tell      = hdulist[6].data\n\t\t\t\tself.tellnoise = hdulist[7].data\n\t\t\t\tself.lsfcoeff  = hdulist[8].data\n\t\t\t\tself.binary    = hdulist[9].data\n\n\n\t\t\t\t# store the original parameters\n\t\t\t\tself.oriWave   = np.array(pow(10, crval1 + cdelt1 * np.arange(1, naxis1+1)))\t\n\t\t\t\tself.oriFlux   = hdulist[1].data\n\t\t\t\tself.oriNoise  = hdulist[2].data\n\n\t\t\t\t## APOGEE APVISIT has corrected the telluric absorption; the forward-modeling routine needs to put it back\n\t\t\t\t#self.flux     *= self.tell\n\n\t\t\tself.header   = hdulist[0].header\n\t\t\tself.header1  = hdulist[1].header\n\t\t\tself.header2  = hdulist[2].header\n\t\t\tself.header3  = hdulist[3].header\n\n\t\t\tself.model    = np.array(hdulist[3].data)\n\t\t\tself.mask     = []\n\n\t\telif self.instrument == 'igrins':\n\t\t\tself.name      = kwargs.get('name')\n\t\t\tself.order     = kwargs.get('order')\n\t\t\tself.path      = kwargs.get('path')\n\t\t\tself.apply_sigma_mask = kwargs.get('apply_sigma_mask',False)\n\t\t\t#self.manaulmask = kwargs('manaulmask', False)\n\n\t\t\tif self.path == None:\n\t\t\t\tself.path = './'\n\n\t\t\tfullpath = self.path + '/' + self.name + '_' + str(self.order) + '.fits'\n\n\t\t\thdulist = fits.open(fullpath, ignore_missing_end=True)\n\n\t\t\t#The indices 0 to 3 correspond to wavelength, flux, noise, and sky\n\t\t\tself.header = hdulist[0].header\n\t\t\tself.wave   = hdulist[0].data * 10000.0 # convert to Angstrom\n\t\t\tself.flux   = hdulist[1].data\n\t\t\tself.noise  = hdulist[2].data\n\n\t\tif self.apply_sigma_mask:\n\t\t\t# set up masking criteria\n\t\t\tself.avgFlux = np.mean(self.flux)\n\t\t\tself.stdFlux = np.std(self.flux)\n\n\t\t\tself.smoothFlux = self.flux\n\t\t\t# set the outliers as the flux below \n\t\t\t#self.smoothFlux[self.smoothFlux <= self.avgFlux - 2 * self.stdFlux] = 0\n\t\t\t#self.smoothFlux[ np.abs(self.smoothFlux - self.avgFlux ) <= 2 * self.stdFlux] = 0\n\t\t\n\t\t\tself.mask  = np.where(np.abs(self.flux - self.avgFlux ) >= 3. * self.stdFlux)\n\t\t\t#print(self.mask)\n\n\t\t\tif self.instrument == 'apogee':\n\t\t\t\t#self.mask = np.union1d(self.mask[0],np.where(self.noise >= self.flux)[0])\n\t\t\t\tnoise_median = np.median(self.noise)\n\t\t\t\tself.mask = np.union1d(self.mask[0], np.where(self.noise >= 3. * noise_median)[0])\n\t\t\tself.wave  = np.delete(self.wave, list(self.mask))\n\t\t\tself.flux  = np.delete(self.flux, list(self.mask))\n\t\t\tself.noise = np.delete(self.noise, list(self.mask))\n\t\t\t\n\t\t\tif self.instrument == 'nirspec':\n\t\t\t\tself.sky   = np.delete(self.sky, list(self.mask))\n\t\t\tself.mask  = self.mask[0]\n\n\tdef mask_custom(self, custom_mask):\n\t\t\"\"\"\n\t\tMask the pixels by a self-defined list.\n\t\t\"\"\"\n\t\t## combine the list and remove the duplicates\n\t\tself.mask  =  list(set().union(self.mask, custom_mask))\n\n\t\tself.wave  = np.delete(self.oriWave, list(self.mask))\n\t\tself.flux  = np.delete(self.oriFlux, list(self.mask))\n\t\tself.noise = np.delete(self.oriNoise, list(self.mask))\n\n\t\treturn self\n\n\n\tdef maskBySigmas(self, sigma=2):\n\t\t\"\"\"\n\t\tMask the outlier data points by sigmas.\n\t\t\"\"\"\n\t\t# set up masking criteria\n\t\tself.avgFlux = np.mean(self.flux)\n\t\tself.stdFlux = np.std(self.flux)\n\n\t\tself.smoothFlux = self.flux\n\t\t# set the outliers as the flux below \n\t\tself.smoothFlux[self.smoothFlux <= self.avgFlux - sigma * self.stdFlux] = 0\n\t\t\n\t\tself.mask  = np.where(self.smoothFlux <= 0)\n\t\tself.wave  = np.delete(self.wave, list(self.mask))\n\t\tself.flux  = np.delete(self.flux, list(self.mask))\n\t\tself.noise = np.delete(self.noise, list(self.mask))\n\t\tself.sky   = np.delete(self.sky, list(self.mask))\n\t\tself.mask  = self.mask[0]\n\n\tdef maskByModel(self, model, sigma=3, pixel_start=30, pixel_end=-10):\n\t\t\"\"\"\n\t\tMask the data by a forward model.\n\t\t\"\"\"\n\t\tpixel        = np.delete(np.arange(len(self.oriWave)),self.mask)[pixel_start: pixel_end]\n\t\tcustom_mask2 = pixel[np.where(np.abs(self.flux-model.flux) > sigma*np.std(self.flux-model.flux))]\n\t\tprint(custom_mask2)\n\t\tcustom_mask2 = np.append(custom_mask2, np.array(self.mask))\n\t\tcustom_mask2.sort()\n\t\tcustom_mask2 = custom_mask2.tolist()\n\t\tself.mask_custom(custom_mask2)\n\n\tdef plot(self, **kwargs):\n\t\t\"\"\"\n\t\tPlot the spectrum.\n\t\t\"\"\"\n\t\t#xlim   = kwargs.get('xrange', [self.wave[0], self.wave[-1]])\n\t\t#ylim   = kwargs.get('yrange', [min(self.flux)-.2, max(self.flux)+.2])\n\t\titems  = kwargs.get('items', ['spec','noise'])\n\t\ttitle  = kwargs.get('title')\n\t\tmask   = kwargs.get('mask', True)\n\t\tsave   = kwargs.get('save', False)\n\t\toutput = kwargs.get('output', str(self.name) + '.png')\n\t\t\n\t\tplt.figure(figsize=(16,6))\n\t\tplt.rc('font', family='sans-serif')\n\t\t## Plot masked spectrum\n\t\tif ('spectrum' in items) or ('spec' in items):\n\t\t\tif \"_\" in self.name:\n\t\t\t\tplot_name = self.name.split(\"_\")[0]\n\t\t\telse:\n\t\t\t\tplot_name = self.name\n\t\t\tif mask:\n\t\t\t\tplt.plot(self.wave, self.flux, color='k', \n\t\t\t\t\talpha=.8, linewidth=1, \n\t\t\t\t\tlabel=\"{} O{}\".format(plot_name,self.order))\n\t\t\tif not mask:\n\t\t\t\tplt.plot(self.oriWave, self.oriFlux, color='k', \n\t\t\t\t\talpha=.8, linewidth=1, \n\t\t\t\t\tlabel=\"{} O{}\".format(plot_name,self.order))\n\n\t\t## Plot spectrum noise\n\t\tif 'noise' in items:\n\t\t\tif mask:\n\t\t\t\tplt.fill_between(self.wave, -self.noise, self.noise,\n\t\t\t\t\tcolor='gray', linewidth=1, alpha=.6)\n\t\t\telif not mask:\n\t\t\t\tplt.fill_between(self.oriWave, -self.oriNoise, \n\t\t\t\t\tself.oriNoise,\n\t\t\t\t\tcolor='gray', linewidth=1, alpha=.6)\n\n\t\tplt.legend(fontsize=12)\n\t\t#plt.xlim(xlim)\n\t\t#plt.ylim(ylim)    \n    \n\t\tplt.xlabel('Wavelength [$\\AA$]', fontsize=18)\n\t\tplt.ylabel('Flux (cnts/s)', fontsize=18)\n\t\tplt.minorticks_on()\n\t\tplt.tick_params(axis='both', labelsize=18)\n\n\t\tif title != None:\n\t\t\tplt.title(title, fontsize=20)\n\n\t\tif save == True:\n\t\t\tplt.savefig(output)\n\n\t\tplt.show()\n\t\tplt.close()\n\n\tdef writeto(self, save_to_path, method='ascii',\n\t\ttell_sp=None):\n\t\t\"\"\"\n\t\tSave the data as an ascii or a fits file.\n\n\t\tParameters\n\t\t----------\n\t\tsave_to_path \t:\tstr\n\t\t\t\t\t\t\tthe path to save the output file\n\n\t\tmethod \t\t\t: \t'ascii' or 'fits'\n\t\t\t\t\t\t\tthe output file format, either in\n\t\t\t\t\t\t\ta single ascii file or several fits\n\t\t\t\t\t\t\tfiles labeled in the order of \n\t\t\t\t\t\t\twavelength\n\n\n\t\tOptional Parameters\n\t\t-------------------\n\t\ttell_sp \t\t: \tSpectrum object\n\t\t\t\t\t\t\tthe telluric data for the corresponding\n\t\t\t\t\t\t\twavelength calibration\n\n\t\tReturns\n\t\t-------\n\t\tascii or fits \t: \tsee the method keyword\n\t\t\t\t\t\t\tThe wavelength is in microns\n\n\n\t\t\"\"\"\n\t\t#pixel = np.delete(np.arange(1024),list(self.mask))\n\t\tpixel = np.arange(len(self.oriWave))\n\t\t## create the output mask array 0=good; 1=bad\n\t\tif (self.apply_sigma_mask) or (self.mask != []):\n\t\t\tmask = np.zeros((len(self.oriWave),),dtype=int)\n\t\t\tnp.put(mask,self.mask,int(1))\n\t\telse:\n\t\t\tmask = np.zeros((len(self.oriWave),),dtype=int)\n\n\t\tif method == 'fits':\n\t\t\t#fullpath = self.path + '/' + self.name + '_' + str(self.order) + '_all.fits'\n\t\t\t#hdulist = fits.open(fullpath, ignore_missing_end=True)\n\t\t\t#hdulist.writeto(save_to_path)\n\t\t\t#hdulist.close()\n\t\t\tif self.header['NAXIS1'] == 1024:\n\t\t\t\tsave_to_path2 = save_to_path + self.header['FILENAME'].split('.')[0]\\\n\t\t\t\t+ '_O' + str(self.order)\n\t\t\telse:\n\t\t\t\tsave_to_path2 = save_to_path + self.header['OFNAME'].split('.')[0]\\\n\t\t\t\t+ '_O' + str(self.order)\n\t\t\t## wavelength\n\t\t\thdu1 = fits.PrimaryHDU(self.wave/10000, header=self.header)\n\t\t\tsave_to_path2_1 = save_to_path2 + '_wave.fits'\n\t\t\thdu1.writeto(save_to_path2_1)\n\t\t\t## flux\n\t\t\thdu2 = fits.PrimaryHDU(self.flux, header=self.header)\n\t\t\tsave_to_path2_2 = save_to_path2 + '_flux.fits'\n\t\t\thdu2.writeto(save_to_path2_2)\n\t\t\t## uncertainty\n\t\t\thdu3 = fits.PrimaryHDU(self.noise, header=self.header)\n\t\t\tsave_to_path2_3 = save_to_path2 + '_uncertainty.fits'\n\t\t\thdu3.writeto(save_to_path2_3)\n\t\t\t## pixel\n\t\t\thdu4 = fits.PrimaryHDU(pixel, header=self.header)\n\t\t\tsave_to_path2_4 = save_to_path2 + '_pixel.fits'\n\t\t\thdu4.writeto(save_to_path2_4)\n\t\t\t## mask\n\t\t\thdu5 = fits.PrimaryHDU(mask, header=self.header)\n\t\t\tsave_to_path2_5 = save_to_path2 + '_mask.fits'\n\t\t\thdu5.writeto(save_to_path2_5)\n\n\t\t\tif tell_sp is not None:\n\t\t\t\ttell_sp2 = copy.deepcopy(tell_sp)\n\t\t\t\t# the telluric standard model\n\t\t\t\twavelow = tell_sp2.wave[0] - 20\n\t\t\t\twavehigh = tell_sp2.wave[-1] + 20\n\t\t\t\ttell_mdl = smart.getTelluric(wavelow=wavelow,wavehigh=wavehigh)\n\t\t\t\t# continuum correction for the data\n\t\t\t\ttell_sp2 = smart.continuumTelluric(data=tell_sp2, \n\t\t\t\t\tmodel=tell_mdl,order=tell_sp2.order)\n\t\t\t\t# telluric flux\n\t\t\t\thdu6 = fits.PrimaryHDU(tell_sp.flux, header=tell_sp.header)\n\t\t\t\tsave_to_path2_6 = save_to_path2 + '_telluric_flux.fits'\n\t\t\t\thdu5.writeto(save_to_path2_6)\n\t\t\t\t# telluric uncertainty\n\t\t\t\thdu7 = fits.PrimaryHDU(tell_sp.noise, header=tell_sp.header)\n\t\t\t\tsave_to_path2_7 = save_to_path2 + '_telluric_uncertainty.fits'\n\t\t\t\thdu5.writeto(save_to_path2_7)\n\t\t\t\t# telluric model\n\t\t\t\thdu8 = fits.PrimaryHDU(tell_mdl.flux, header=tell_sp.header)\n\t\t\t\tsave_to_path2_8 = save_to_path2 + '_telluric_model.fits'\n\t\t\t\thdu5.writeto(save_to_path2_8)\n\t\t\t\t\n\n\t\telif method == 'ascii':\n\t\t\tif '.txt' not in save_to_path:\n\t\t\t\tif self.header['NAXIS1'] == 1024:\n\t\t\t\t\tsave_to_path2 = save_to_path + self.header['FILENAME'].split('.')[0]\\\n\t\t\t\t\t+ '_O' + str(self.order) + '.txt'\n\t\t\t\telse:\n\t\t\t\t\tsave_to_path2 = save_to_path + self.header['OFNAME'].split('.')[0]\\\n\t\t\t\t\t+ '_O' + str(self.order) + '.txt'\n\t\t\telse:\n\t\t\t\tsave_to_path2 = save_to_path\n\n\t\t\tif tell_sp is None:\n\t\t\t\tdf = pd.DataFrame(data={'wavelength':list(self.oriWave/10000),\n\t\t\t\t\t'flux':list(self.oriFlux),\n\t\t\t\t\t'uncertainty':list(self.oriNoise),\n\t\t\t\t\t'pixel':list(pixel),\n\t\t\t\t\t'mask':list(mask)})\n\t\t\t\tdf.to_csv(save_to_path2, index=None, sep='\\t', mode='a',\n\t\t\t\t\theader=True, columns=['wavelength', 'flux', 'uncertainty',\n\t\t\t\t\t'pixel', 'mask'])\n\t\t\t\n\t\t\telif tell_sp is not None:\n\t\t\t\ttell_sp2 = copy.deepcopy(tell_sp)\n\t\t\t\ttell_sp2 = smart.continuumTelluric(data=tell_sp2\n\t\t\t\t\t,order=self.order)\n\t\t\t\tlsf0 = smart.getLSF(tell_sp2)\n\t\t\t\ttell_sp2.flux = tell_sp2.oriFlux\n\t\t\t\ttell_sp2.wave = tell_sp2.oriWave\n\t\t\t\ttell_mdl = smart.convolveTelluric(lsf0, tell_sp2)\n\n\t\t\t\tprint(len(self.oriWave), len(self.oriFlux), len(self.oriNoise), len(tell_sp.oriFlux),\n\t\t\t\t\tlen(tell_sp.oriNoise), len(tell_mdl.flux), len(pixel), len(mask))\n\n\t\t\t\tdf = pd.DataFrame(data={'wavelength':list(self.oriWave/10000),\n\t\t\t\t\t'flux':list(self.oriFlux),\n\t\t\t\t\t'uncertainty':list(self.oriNoise),\n\t\t\t\t\t'telluric_flux':list(tell_sp.oriFlux),\n\t\t\t\t\t'telluric_uncertainty':list(tell_sp.oriNoise),\n\t\t\t\t\t'telluric_model':list(tell_mdl.flux),\n\t\t\t\t\t'pixel':list(pixel),\n\t\t\t\t\t'mask':list(mask)})\n\n\n\t\t\t\tdf.to_csv(save_to_path2, index=None, sep='\\t', mode='a',\n\t\t\t\t\theader=True, columns=['wavelength', 'flux', 'uncertainty', \n\t\t\t\t\t'telluric_flux', 'telluric_uncertainty', 'telluric_model',\n\t\t\t\t\t'pixel', 'mask'])\n\n\n\tdef coadd(self, sp, method='pixel'):\n\t\t\"\"\"\n\t\tCoadd individual extractions, either in pixel space or\n\t\twavelength space.\n\n\t\tParameters\n\t\t----------\n\t\tsp \t\t: \tSpectrum object\n\t\t\t\t\tspectrum to be coadded\n\n\t\tmethod \t: \t'pixel' or 'wavelength'\n\t\t\t\t\tcoadd based on adding pixels or wavelength\n\t\t\t\t\tIf 'wavelength', the second spectrum would be\n\t\t\t\t\t10x supersample and then cross correlated\n\t\t\t\t\tto be optimally shifted and coadded\n\n\t\tReturns\n\t\t-------\n\t\tself \t: \tSpectrum object\n\t\t\t\t\tcoadded spectra\n\n\t\t\"\"\"\n\t\tif method == 'pixel':\n\t\t\tw1 = 1/self.oriNoise**2\n\t\t\tw2 = 1/sp.oriNoise**2\n\t\t\tself.oriFlux = (self.oriFlux*w1 + sp.oriFlux*w2)/(w1 + w2)\n\t\t\tself.oriNoise = np.sqrt(1/(w1 + w2))\n\t\t\t## set up masking criteria\n\t\t\tself.avgFlux = np.mean(self.oriFlux)\n\t\t\tself.stdFlux = np.std(self.oriFlux)\n\t\t\tself.smoothFlux = self.oriFlux\n\t\t\t## set the outliers as the flux below \n\t\t\tif self.apply_sigma_mask:\n\t\t\t\tself.smoothFlux[self.smoothFlux <= self.avgFlux-2*self.stdFlux] = 0\n\t\t\t\tself.mask = np.where(self.smoothFlux <= 0)\n\t\t\telse:\n\t\t\t\tself.mask = []\n\t\t\tself.wave  = np.delete(self.oriWave, list(self.mask))\n\t\t\tself.flux  = np.delete(self.oriFlux, list(self.mask))\n\t\t\tself.noise = np.delete(self.oriNoise, list(self.mask))\n\n\t\telif method == 'wavelength':\n\t\t\tself_supers = copy.deepcopy(self)\n\t\t\tg = interpolate.interp1d(self.wave, self.flux)\n\t\t\tsp_supers = copy.deepcopy(sp)\n\t\t\tf = interpolate.interp1d(sp.wave, sp.flux)\n\t\t\t## 10x supersample the average difference of \n\t\t\t## the wavelength\n\t\t\t#step0 = np.mean(np.diff(self.wave))/10\n\t\t\t#self_supers.wave = np.arange(self.wave[0],\n\t\t\t#\tself.wave[-1],step0)\n\t\t\tself_supers.flux = g(self_supers.wave)\n\t\t\tself_supers.oriWave = np.arange(self.oriWave[0],\n\t\t\t\tself.oriWave[-1],(self.oriWave[-1]-self.oriWave[0])/10240)\n\t\t\tg1 = interpolate.interp1d(self.oriWave, self.oriFlux)\n\t\t\tself_supers.oriFlux = g1(self_supers.oriWave)\n\n\t\t\t#step = np.mean(np.diff(sp.wave))/10\n\t\t\t#sp_supers.wave = np.arange(sp.wave[0],sp.wave[-1],step)\n\t\t\t#sp_supers.flux = f(sp_supers.wave)\n\t\t\tsp_supers.oriWave = np.arange(sp.oriWave[0],\n\t\t\t\tsp.oriWave[-1],(sp.oriWave[-1]-sp.oriWave[0])/10240)\n\t\t\tf1 = interpolate.interp1d(sp.oriWave, sp.oriFlux)\n\t\t\tsp_supers.oriFlux = f1(sp_supers.oriWave)\n\n\t\t\t## calculate the max cross correlation value\n\t\t\tdef xcorr(a0,b0,shift):\n\t\t\t\t\"\"\"\n\t\t\t\tShift is the index number after supersampling \n\t\t\t\tboth of the spectra.\n\t\t\t\t\"\"\"\n\t\t\t\ta = copy.deepcopy(a0)\n\t\t\t\tb = copy.deepcopy(b0)\n\n\t\t\t\t## shift the wavelength of b\n\t\t\t\tlength = b.oriFlux.shape[0]\n\t\t\t\tif shift >= 0:\n\t\t\t\t\tmask_a = np.arange(0,shift,1)\n\t\t\t\t\ta.oriFlux = np.delete(a.oriFlux,mask_a)\n\t\t\t\t\tmask_b = np.arange(length-1,length-shift-1,-1)\n\t\t\t\t\tb.oriFlux = np.delete(b.oriFlux,mask_b)\n\n\t\t\t\telif shift < 0:\n\t\t\t\t\tmask_a = np.arange(length-1,length+shift-1,-1)\n\t\t\t\t\ta.oriFlux = np.delete(a.oriFlux,mask_a)\n\t\t\t\t\tmask_b = np.arange(0,-shift,1)\n\t\t\t\t\tb.oriFlux = np.delete(b.oriFlux,mask_b)\n\n\t\t\t\t## shift the wavelength of b\n\t\t\t\t#b.wave += shift * step\n\t\t\t\t## discard the points where the wavelength values\n\t\t\t\t## are larger\n\t\t\t\t#condition = (a.wave > b.wave[0]) & (a.wave < b.wave[-1])\n\t\t\t\t\n\t\t\t\t#a.flux = a.flux[np.where(condition)]\n\t\t\t\t#a.wave = a.wave[np.where(condition)]\n\t\t\t\t## resampling the telluric model\n\t\t\t\t#b.flux = np.array(smart.integralResample(xh=b.wave, \n\t\t\t\t#\tyh=b.flux, xl=a.wave))\n\t\t\t\t\n\t\t\t\treturn np.inner(a.oriFlux, b.oriFlux)/\\\n\t\t\t\t(np.average(a.oriFlux)*np.average(b.oriFlux))/a.oriFlux.shape[0]\n\n\t\t\txcorr_list = []\n\t\t\t## mask the ending pixels\n\t\t\tself_supers2 = copy.deepcopy(self_supers)\n\t\t\tsp_supers2 = copy.deepcopy(sp_supers)\n\t\t\tself_supers2.wave = self_supers2.wave[1000:-1000]\n\t\t\tself_supers2.flux = self_supers2.flux[1000:-1000]\n\t\t\tsp_supers2.wave = sp_supers2.wave[1000:-1000]\n\t\t\tsp_supers2.flux = sp_supers2.flux[1000:-1000]\n\t\t\tfor shift in np.arange(-10,10,1):\n\t\t\t\txcorr_list.append(xcorr(self_supers2,sp_supers2,shift))\n\n\t\t\t## dignostic plot for cc result\n\t\t\tfig, ax = plt.subplots()\n\t\t\tax.plot(np.arange(-10,10,1),np.array(xcorr_list),'k-')\n\t\t\tplt.show()\n\t\t\tplt.close()\n\n\t\t\tstep = np.absolute(np.mean(np.diff(sp_supers.wave)))\n\t\t\tbestshift = np.arange(-10*step,10*step,step)[np.argmax(xcorr_list)]\n\t\t\tsp_supers.oriWave += bestshift\n\t\t\t## discard the points where the wavelength values\n\t\t\t## are larger\n\t\t\tcondition = (self.oriWave > sp_supers.oriWave[0])\\\n\t\t\t& (self.oriWave < sp_supers.oriWave[-1])\n\n\t\t\tself.oriFlux = self.oriFlux[np.where(condition)]\n\t\t\tself.oriWave = self.oriWave[np.where(condition)]\n\t\t\tself.oriNoise = self.oriNoise[np.where(condition)]\n\t\t\tsp_supers.oriNoise = sp_supers.oriNoise[np.where(condition)]\n\t\t\tsp_supers.oriFlux = np.array(smart.integralResample(xh=sp_supers.oriWave, \n\t\t\t\tyh=sp_supers.oriFlux, xl=self.oriWave))\n\n\t\t\tw1 = 1/self.oriNoise**2\n\t\t\tw2 = 1/sp_supers.oriNoise**2\n\t\t\tself.oriFlux = (self.oriFlux*w1 + sp_supers.oriFlux*w2)/(w1 + w2)\n\t\t\tself.oriNoise = np.sqrt(1/(w1 + w2))\n\t\t\t## set up masking criteria\n\t\t\tself.avgFlux = np.mean(self.oriFlux)\n\t\t\tself.stdFlux = np.std(self.oriFlux)\n\t\t\tself.smoothFlux = self.oriFlux\n\t\t\t## set the outliers as the flux below \n\t\t\tself.smoothFlux[self.smoothFlux <= self.avgFlux-2*self.stdFlux] = 0\n\t\t\tself.mask = np.where(self.smoothFlux <= 0)\n\t\t\tself.wave  = np.delete(self.oriWave, list(self.mask))\n\t\t\tself.flux  = np.delete(self.oriFlux, list(self.mask))\n\t\t\tself.noise = np.delete(self.oriNoise, list(self.mask))\n\n\t\treturn self\n\n\tdef updateWaveSol(self, tell_sp):\n\t\t\"\"\"\n\t\tReturn a new wavelength solution given a wavelength \n\t\tcalibrated telluric spectrum.\n\n\t\tParameters\n\t\t----------\n\t\ttell_sp \t: \tSpectrum object\n\t\t\t\t\t\tthe calibrated telluric spectra\n\t\t\"\"\"\n\t\twfit0 = tell_sp.header['WFIT0NEW']\n\t\twfit1 = tell_sp.header['WFIT1NEW']\n\t\twfit2 = tell_sp.header['WFIT2NEW']\n\t\twfit3 = tell_sp.header['WFIT3NEW']\n\t\twfit4 = tell_sp.header['WFIT4NEW']\n\t\twfit5 = tell_sp.header['WFIT5NEW']\n\t\tc3    = tell_sp.header['c3']\n\t\tc4    = tell_sp.header['c4']\n\n\t\tlength1 = tell_sp.header['NAXIS1']\n\n\t\tself.wave = np.delete(smart.waveSolution(np.arange(length1),\n\t\t\twfit0,wfit1,wfit2,wfit3,wfit4,wfit5,c3,c4, order=self.order), list(self.mask))\n\t\tself.oriWave = smart.waveSolution(np.arange(length1),\n\t\t\twfit0,wfit1,wfit2,wfit3,wfit4,wfit5,c3,c4, order=self.order)\n\n\t\treturn self\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "0c81a7fa066d65895168f953f146b96aab977a4c", "size": 27061, "ext": "py", "lang": "Python", "max_stars_repo_path": "smart/forward_model/classSpectrum.py", "max_stars_repo_name": "chihchunhsu/smart", "max_stars_repo_head_hexsha": "c4d5668a0c44e9780290f7f7eba24726f5262b97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-01-21T09:09:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T18:24:02.000Z", "max_issues_repo_path": "smart/forward_model/classSpectrum.py", "max_issues_repo_name": "chihchunhsu/smart", "max_issues_repo_head_hexsha": "c4d5668a0c44e9780290f7f7eba24726f5262b97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-02-07T19:03:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T01:21:56.000Z", "max_forks_repo_path": "smart/forward_model/classSpectrum.py", "max_forks_repo_name": "chihchunhsu/smart", "max_forks_repo_head_hexsha": "c4d5668a0c44e9780290f7f7eba24726f5262b97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-22T21:54:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-11T05:16:53.000Z", "avg_line_length": 35.0531088083, "max_line_length": 163, "alphanum_fraction": 0.6475739995, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 8706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.1841381754711787}}
{"text": "# -*- encoding: utf-8 -*-\n\"\"\"\n@File : tools.py\n@Time : 2019/03/04 08:35:46\n@Author : wangtf\n@Version : 1.0\n@Desc : None\n\"\"\"\n\n# here put the import lib\nimport os\nimport glob\nimport numpy as np\n\n\ndef voc_ap(recall, precision, use_07_metric=False):\n    \"\"\"\n    ap = voc_ap(recall, precision, [use_07_metric])\n\n    Compute VOC AP given precision and recall.\n    If use_07_metric is true, uses  the\n    VOC 07 11 point method (default: False).\n    Please make shure that recall and precison are sorted by scores.\n\n    Args:\n        recall: the shape of (n,) ndarray;\n        precision: the shape of (n,) ndarray;\n        use_07_metric: if true, the 11 points method will be used.\n    Returns:\n        the float number result of average precision.\n    \"\"\"\n    if use_07_metric:\n        # 11 point metric\n        ap = 0.\n        for t in np.arange(0., 1.1, 0.1):\n            if np.sum(recall >= t) == 0:\n                p = 0\n            else:\n                p = np.max(precision[recall >= t])\n            ap = ap + p / 11.\n    else:\n        # correct AP calculation\n        # first append sentinel values at the end\n        mrec = np.concatenate(([0.], recall, [1.]))\n        mpre = np.concatenate(([0.], precision, [0.]))\n\n        # compute the precision envelope\n        for i in range(mpre.size - 1, 0, -1):\n            mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n\n        # to calculate area under PR curve, look for points\n        # where X axis (recall) changes value\n        i = np.where(mrec[1:] != mrec[:-1])[0]\n\n        # and sum (\\Delta recall) * prec\n        ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n    return ap\n\n\ndef compute_overlaps(boxes, one_box):\n    \"\"\"\n    iou = compute_overlaps(boxes, one_box)\n\n    compute intersection over union of ndarray.\n    The format of one_box is [xmin, ymin, xmax, ymax].\n\n    Args:\n        boxes: the (n, 4) shape ndarray, ground truth boundboxes;\n        bb: the (4,) shape ndarray, detected boundboxes;\n    Returns:\n        a (n, ) shape ndarray.\n    \"\"\"\n    # compute overlaps\n    # intersection\n    ixmin = np.maximum(boxes[:, 0], one_box[0])\n    iymin = np.maximum(boxes[:, 1], one_box[1])\n    ixmax = np.minimum(boxes[:, 2], one_box[2])\n    iymax = np.minimum(boxes[:, 3], one_box[3])\n    iw = np.maximum(ixmax - ixmin + 1., 0.)\n    ih = np.maximum(iymax - iymin + 1., 0.)\n    inters = iw * ih\n\n    # union\n    boxes_area = (boxes[:, 2] - boxes[:, 0] + 1.) * (boxes[:, 3] -\n                                                     boxes[:, 1] + 1.)\n    one_box_area = (one_box[2] - one_box[0] + 1.) * (one_box[3] - one_box[1] +\n                                                     1.)\n    iou = inters / (one_box_area + boxes_area - inters)\n\n    return iou\n\n\ndef voc_eval(class_recs: dict,\n             detect: dict,\n             iou_thresh: float = 0.5,\n             use_07_metric: bool = False):\n    \"\"\"\n    recall, precision, ap = voc_eval(class_recs, detection,\n                                [iou_thresh],\n                                [use_07_metric])\n\n    Top level function that does the PASCAL VOC evaluation.\n    Please make sure that the class_recs only have one class annotations.\n\n    precision = tp / (tp + fp)\n    recall = tp / (tp + fn)\n\n    Args:\n        class_recalls: recalls dict of a class\n            class_recs[image_name]={'bbox': []}.\n        detection: Path to annotations\n            detection={'image_ids':[], bbox': [], 'confidence':[]}.\n        [iou_thresh]: Overlap threshold (default = 0.5)\n        [use_07_metric]: Whether to use VOC07's 11 point AP computation\n            (default False)\n    Returns:\n        a dict of result including true_positive_number, false_positive_number,\n        recall, precision and average_precision.\n    Raises:\n        TypeError: the data format is not np.ndarray.\n    \"\"\"\n    # format data\n    # class_rec data load\n    npos = 0\n    for imagename in class_recs.keys():\n        if not isinstance(class_recs[imagename]['bbox'], np.ndarray):\n            raise TypeError\n        detected_num = class_recs[imagename]['bbox'].shape[0]\n        npos += detected_num\n        class_recs[imagename]['det'] = [False] * detected_num\n\n    # detections data load\n    image_ids = detect['image_ids']\n    confidence = detect['confidence']\n    BB = detect['bbox']\n    if not isinstance(confidence, np.ndarray):\n        raise TypeError\n    if not isinstance(BB, np.ndarray):\n        raise TypeError\n\n    # sort by confidence\n    sorted_ind = np.argsort(-confidence)\n    BB = BB[sorted_ind, :]\n    image_ids = [image_ids[x] for x in sorted_ind]\n\n    # go down dets and mark TPs and FPs\n    nd = len(image_ids)\n    tp = np.zeros(nd)\n    fp = np.zeros(nd)\n    for d in range(nd):\n        R = class_recs[image_ids[d]]\n        bb = BB[d, :].astype(float)\n        iou_max = -np.inf\n        BBGT = R['bbox'].astype(float)\n\n        if BBGT.size > 0:\n            overlaps = compute_overlaps(BBGT, bb)\n            iou_max = np.max(overlaps)\n            iou_max_index = np.argmax(overlaps)\n\n        if iou_max > iou_thresh:\n            if not R['det'][iou_max_index]:\n                tp[d] = 1.\n                R['det'][iou_max_index] = 1\n            else:\n                fp[d] = 1.\n        else:\n            fp[d] = 1.\n\n    # compute precision recall\n    fp = np.cumsum(fp)\n    tp = np.cumsum(tp)\n    true_positive_number = tp[-1]\n    false_positive_number = fp[-1]\n\n    recall = tp / float(npos)\n    # avoid divide by zero in case the first detection matches\n    # a difficult ground truth\n    precision = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)\n    average_precision = voc_ap(recall, precision, use_07_metric)\n\n    result = {}\n    result['true_positive_number'] = true_positive_number\n    result['false_positive_number'] = false_positive_number\n    result['recall'] = recall\n    result['precision'] = precision\n    result['average_precision'] = average_precision\n    return result\n\n\ndef voc_eval_files(class_recs_dir,\n                   detect_file,\n                   label_id,\n                   iou_thresh=0.5,\n                   use_07_metric=False):\n    \"\"\"\n    recall, precision, ap = voc_eval(class_recs, detection,\n                                [iou_thresh],\n                                [use_07_metric])\n\n    Top level function that does the PASCAL VOC evaluation.\n    Please make sure that the class_recs only have one class annotations.\n\n    precision = tp / (tp + fp)\n    recall = tp / (tp + fn)\n\n    Args:\n        class_recalls: recalls dict of a class\n            class_recs[image_name]={'bbox': []}.\n        detection: Path to annotations\n            detection={'image_ids':[], bbox': [], 'confidence':[]}.\n        [iou_thresh]: Overlap threshold (default = 0.5)\n        [use_07_metric]: Whether to use VOC07's 11 point AP computation\n            (default False)\n    Returns:\n        a dict of result including true_positive_number, false_positive_number,\n        recall, precision and average_precision.\n    Raises:\n        IOError: can not find the path.\n    \"\"\"\n    if not os.path.exists(class_recs_dir):\n        raise IOError\n    if not os.path.exists(detect_file):\n        raise IOError\n\n    class_recs = {}\n    recs_list = glob.glob(os.path.join(class_recs_dir, '*.txt'))\n    for path in recs_list:\n        image_id = os.path.basename(path)[:-4]\n        with open(path) as f:\n            data = f.read().strip().split('\\n')\n            bboxes = []\n            for line in data:\n                label, xmin, ymin, xmax, ymax = line.strip().split(' ')\n                if label == str(label_id):\n                    bboxes.append([xmin, ymin, xmax, ymax])\n            bboxes = np.array(bboxes)\n            class_recs[image_id] = {'bbox': bboxes}\n\n    detection = {'image_ids': [], 'bbox': [], 'confidence': []}\n    with open(detect_file) as f:\n        data = f.read().strip().split('\\n')\n        for line in data:\n            image_id, confidence, xmin, ymin, xmax, ymax = line.strip().split()\n            detection['image_ids'].append(image_id)\n            detection['confidence'].append(confidence)\n            detection['bbox'].append([xmin, ymin, xmax, ymax])\n    detection['image_ids'] = np.array(detection['image_ids'])\n    detection['confidence'] = np.array(detection['confidence'])\n    detection['bbox'] = np.array(detection['bbox'])\n\n    result = voc_eval(class_recs,\n                      detection,\n                      iou_thresh=iou_thresh,\n                      use_07_metric=use_07_metric)\n    return result\n", "meta": {"hexsha": "b9838e540b86585c4d1388ba0426bff228696fed", "size": 8462, "ext": "py", "lang": "Python", "max_stars_repo_path": "pascal_voc_tools/Evaluater/tools.py", "max_stars_repo_name": "lardemua/pascal_voc_tools", "max_stars_repo_head_hexsha": "75391d156306853d5e7211d584af8012ea1cd877", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2019-05-20T07:21:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T02:29:17.000Z", "max_issues_repo_path": "pascal_voc_tools/Evaluater/tools.py", "max_issues_repo_name": "lardemua/pascal_voc_tools", "max_issues_repo_head_hexsha": "75391d156306853d5e7211d584af8012ea1cd877", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-09-20T10:52:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-03T08:48:48.000Z", "max_forks_repo_path": "pascal_voc_tools/Evaluater/tools.py", "max_forks_repo_name": "lardemua/pascal_voc_tools", "max_forks_repo_head_hexsha": "75391d156306853d5e7211d584af8012ea1cd877", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-04-22T06:59:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-08T09:07:58.000Z", "avg_line_length": 32.9260700389, "max_line_length": 79, "alphanum_fraction": 0.5694871189, "include": true, "reason": "import numpy", "num_tokens": 2150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.18410723567781317}}
{"text": "# Copyright 2020 Arthur Coqué, Guillaume Morin, Pôle OFB-INRAE ECLA, UR RECOVER\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"This module gathers wc algorithms used for estimating Chl-a concentrations.\n\nEach class of this module correspond to one algorithm. An algorithm can have\nseveral calibrations (a calibration is a set of parameters), either\npackaged within SISPPEO (these default calibrations are located in\n'resources/wc_algo_calibration') or provided by the user.\nBefore its utilisation, an algorithm has to be instantiate with specific\nsettings like the product_type of further input products, the calibration\nused, the band used (if needed), etc.\n\nExample:\n\n    algo1 = CHLAGons('S2_GRS', 'Gons_2004')\n    out_array1 = algo1(red_array, rededge_array, nir_array, 'rho')\n\n    algo2 = CHLAGittelson('L8_GRS', '3_bands', 'Gitelson_2008')\n    out_array2 = algo2(red_array, rededge_array, nir_array, 'rrs')\n\"\"\"\n\nfrom pathlib import Path\nfrom typing import Optional, Union\n\nimport numpy as np\nimport xarray as xr\n\nfrom sisppeo.utils.algos import load_calib, producttype_to_sat\nfrom sisppeo.utils.config import wc_algo_config as algo_config, wc_calib\nfrom sisppeo.utils.exceptions import InputError\n\n# pylint: disable=invalid-name\n# Ok for a custom type.\nP = Union[str, Path]\nN = Union[int, float]\n\n\nclass CHLAGons:\n    \"\"\"Chlorophyll-a concentration (in mg/m3) from 3 red bands after Gons et al., 1999, 2002, 2004\n\n    Red edge algorithm to retrieve Chlorophyll-a concentration (in mg/m3) from\n    surface reflectances (rho, unitless) or remote sensing reflectances (Rrs,\n    in sr-1) at 665nm B4 MSI, 704nm B5 MSI and 783nm B7 MSI.\n    This algorithm was published in Gons et al., 1999, 2002, 2004\n\n    Attributes:\n        name: The name of the algorithm used. This is the key used by\n            L3AlgoBuilder and that you must provide in config or when using\n            the CLI.\n        requested_bands: A list of bands further used by the algorithm.\n        meta: A dict of metadata (calibration name, model coefficients, etc).\n    \"\"\"\n    _default_calibration_file = wc_calib / 'chla-gons.yaml'\n    _default_calibration_name = 'Gons_2004'\n    name = 'chla-gons'\n\n    def __init__(self,\n                 product_type: str,\n                 calibration: Optional[P] = None,\n                 **_ignored) -> None:\n        \"\"\"Inits an 'CHLAGons' instance with specific settings.\n\n        Args:\n            product_type: The type of the input satellite product (e.g.\n                S2_ESA_L2A or L8_USGS_L1GT)\n            calibration: Optional; The calibration (set of parameters) used by\n                the algorithm (default=_default_calibration_name).\n            **_ignored: Unused kwargs sent to trash.\n        \"\"\"\n        try:\n            self.requested_bands = algo_config[self.name][\n                producttype_to_sat(product_type)]\n        except KeyError as invalid_product:\n            msg = f'{product_type} is not allowed with {self.name}'\n            raise InputError(msg) from invalid_product\n        calibration_dict, calibration_name = load_calib(\n            calibration,\n            self._default_calibration_file,\n            self._default_calibration_name\n        )\n        self._valid_limit = calibration_dict['validity_limit']\n        try:\n            params = calibration_dict[producttype_to_sat(product_type)]\n        except KeyError as invalid_product:\n            msg = f'{product_type} is not allowed with this calibration'\n            raise InputError(msg) from invalid_product\n        self.__dict__.update(params)\n        self.meta = {'calibration': calibration_name,\n                     'validity_limit': self._valid_limit,\n                     **params}\n\n    def __call__(self,\n                 ref_red: xr.DataArray,\n                 ref_rededge: xr.DataArray,\n                 ref_nir: xr.DataArray,\n                 data_type: str,\n                 **_ignored) -> xr.DataArray:\n        \"\"\"Runs the algorithm on the input array ('ref').\n\n        Args:\n            ref_red: An array (dimension 1 * N * M) of 'data_type'.\n            ref_redegde: An array (dimension 1 * N * M) of 'data_type'.\n            ref_nir: An array (dimension 1 * N * M) of 'data_type'.\n            data_type: Either 'ref' or 'rrs' (respectively surface reflectance\n                and remote sensing reflectance).\n            **_ignored: Unused kwargs sent to trash.\n\n        Returns:\n            An array (dimension 1 * N * M) of chl-a (in mg/m3).\n        \"\"\"\n\n        if data_type == 'rho':\n            ref_red = ref_red / np.pi\n            ref_rededge = ref_rededge / np.pi\n            ref_nir = ref_nir / np.pi\n\n        np.warnings.filterwarnings('ignore')\n        ref_red = ref_red.where(ref_red >= 0)\n        ref_rededge = ref_rededge.where(ref_red >= 0)\n        ref_nir = ref_red.where(ref_nir >= 0)\n\n        bb783 = ref_nir.where(ref_nir >= 0).copy()\n        # pylint: disable=no-member\n        # Loaded in __init__ whit \"__dict__.update\".\n        bb783 = (self.a * bb783) / (0.082 - 0.6 * bb783)\n        aphy = ref_rededge / ref_red * (self.aw705 + bb783) - self.aw665 \\\n            - np.power(bb783, self.p)\n        chla = aphy / self.aphy_star\n        chla = chla.where((chla >= 0) & (chla <= self._valid_limit))\n        return chla\n\n\nclass CHLAGitelson:\n    \"\"\"Chlorophyll-a concentration (in mg/m3) from 3 red bands after Gitelson et al., 2008\n\n    Red edge algorithm to retrieve Chlorophyll-a concentration (in mg/m3) from\n    surface reflectances (rho, unitless) or remote sensing reflectances (Rrs,\n    in sr-1) at 665nm B4 MSI, 705nm B5 MSI and 740nm B6 MSI.\n    This algorithm was published in Gitelson et al., 2008\n\n    Attributes:\n        name: The name of the algorithm used. This is the key used by\n            L3AlgoBuilder and that you must provide in config or when using\n            the CLI.\n        requested_bands: A list of bands further used by the algorithm.\n        meta: A dict of metadata (calibration name, model coefficients, etc).\n    \"\"\"\n    _default_calibration_file = wc_calib / 'chla-gitelson.yaml'\n    _default_calibration_name = 'Gitelson_2008'\n    _default_design = '3_bands'\n    name = 'chla-gitelson'\n\n    def __init__(self,\n                 product_type: str,\n                 design: str = _default_design,\n                 calibration: Optional[P] = None,\n                 **_ignored) -> None:\n        \"\"\"Inits an 'CHLAGitelson' instance with specific settings.\n\n        Args:\n            product_type: The type of the input satellite product (e.g.\n                S2_ESA_L2A or L8_USGS_L1GT)\n            calibration: The calibration (set of parameters) used by the\n                algorithm (default=_default_calibration_name).\n            **_ignored: Unused kwargs sent to trash.\n        \"\"\"\n        self._design = design\n        try:\n            self.requested_bands = algo_config[self.name][\n                producttype_to_sat(product_type)]\n        except KeyError as invalid_product:\n            msg = f'{product_type} is not allowed with {self.name}'\n            raise InputError(msg) from invalid_product\n        calibration_dict, calibration_name = load_calib(\n            calibration,\n            self._default_calibration_file,\n            self._default_calibration_name\n        )\n        self._valid_limit = calibration_dict['validity_limit']\n        try:\n            params = calibration_dict[producttype_to_sat(product_type)]\n        except KeyError as invalid_product:\n            msg = f'{product_type} is not allowed with this calibration'\n            raise InputError(msg) from invalid_product\n        self.__dict__.update(params)\n        self.meta = {'calibration': calibration_name,\n                     'design': design,\n                     'validity_limit': self._valid_limit,\n                     **params}\n\n    def __call__(self,\n                 ref_red: xr.DataArray,\n                 ref_rededge: xr.DataArray,\n                 ref_nir: xr.DataArray,\n                 data_type: str,\n                 **_ignored) -> xr.DataArray:\n        \"\"\"Runs the algorithm on the input array ('ref').\n\n        Args:\n            ref_red: An array (dimension 1 * N * M) of 'data_type'.\n            ref_redegde: An array (dimension 1 * N * M) of 'data_type'.\n            ref_nir: An array (dimension 1 * N * M) of 'data_type'.\n            data_type: Either 'rho' or 'rrs' (respectively surface reflectance\n                and remote sensing reflectance).\n            **_ignored: Unused kwargs sent to trash.\n\n        Returns:\n            An array (dimension 1 * N * M) of chl-a (in mg/m3).\n        \"\"\"\n\n        if data_type == 'rho':\n            ref_red = ref_red / np.pi\n            ref_rededge = ref_rededge / np.pi\n            ref_nir = ref_nir / np.pi\n\n        np.warnings.filterwarnings('ignore')\n        ref_red = ref_red.where(ref_red >= 0)\n        ref_rededge = ref_rededge.where(ref_red >= 0)\n        ref_nir = ref_red.where(ref_nir >= 0)\n        print(self._design, self._valid_limit)\n        if self._design == '3_bands':\n            print('3 bands selected')\n            # pylint: disable=no-member\n            # Loaded in __init__ whit \"__dict__.update\".\n            chla = self.a_3bands + self.b_3bands \\\n                * (1 / ref_red - 1 / ref_rededge) * ref_nir\n        else:\n            print('2 bands selected')\n            # pylint: disable=no-member\n            # Loaded in __init__ whit \"__dict__.update\".\n            chla = self.a_2bands + self.b_2bands * (1 / ref_red) * ref_nir\n        chla = chla.where((chla >= 0) & (chla <= self._valid_limit))\n        return chla\n\n\nclass CHLAGurlin:\n    \"\"\"Chlorophyll-a concentration (in mg/m3) from 3 red bands after Gurlin et al., 2011\n\n    Red edge algorithm to retrieve Chlorophyll-a concentration (in mg/m3) from\n    surface reflectances (rho, unitless) or remote sensing reflectances (Rrs,\n    in sr-1) at 665nm B4 MSI, 704nm B5 MSI and 783nm B7 MSI.\n    This algorithm was published in Gons et al., 1999, 2002, 2004\n\n    Attributes:\n        name: The name of the algorithm used. This is the key used by\n            L3AlgoBuilder and that you must provide in config or when using\n            the CLI.\n        requested_bands: A list of bands further used by the algorithm.\n        meta: A dict of metadata (calibration name, model coefficients, etc).\n    \"\"\"\n    _default_calibration_file = wc_calib / 'chla-gurlin.yaml'\n    _default_calibration_name = 'Gurlin_2011'\n    name = 'chla-gurlin'\n\n    def __init__(self,\n                 product_type: str,\n                 calibration: Optional[P] = None,\n                 **_ignored) -> None:\n        \"\"\"Inits an 'CHLAGurlin' instance with specific settings.\n\n        Args:\n            product_type: The type of the input satellite product (e.g.\n                S2_ESA_L2A or L8_USGS_L1GT)\n            calibration: The calibration (set of parameters) used by the\n                algorithm (default=_default_calibration_name).\n            **_ignored: Unused kwargs sent to trash.\n        \"\"\"\n        try:\n            self.requested_bands = algo_config[self.name][\n                producttype_to_sat(product_type)]\n        except KeyError as invalid_product:\n            msg = f'{product_type} is not allowed with {self.name}'\n            raise InputError(msg) from invalid_product\n        calibration_dict, calibration_name = load_calib(\n            calibration,\n            self._default_calibration_file,\n            self._default_calibration_name\n        )\n        self._valid_limit = calibration_dict['validity_limit']\n        try:\n            params = calibration_dict[producttype_to_sat(product_type)]\n        except KeyError as invalid_product:\n            msg = f'{product_type} is not allowed with this calibration'\n            raise InputError(msg) from invalid_product\n        self.__dict__.update(params)\n        self.meta = {'calibration': calibration_name,\n                     'validity_limit': self._valid_limit,\n                     **params}\n\n    def __call__(self,\n                 ref_red: xr.DataArray,\n                 ref_rededge: xr.DataArray,\n                 data_type: str,\n                 **_ignored) -> xr.DataArray:\n        \"\"\"Runs the algorithm on the input array ('ref').\n\n        Args:\n            ref_red: An array (dimension 1 * N * M) of 'data_type'.\n            ref_redegde: An array (dimension 1 * N * M) of 'data_type'.\n            data_type: Either 'rho' or 'rrs' (respectively surface reflectance\n                and remote sensing reflectance).\n            **_ignored: Unused kwargs sent to trash.\n\n        Returns:\n            An array (dimension 1 * N * M) of chl-a (in mg/m3).\n        \"\"\"\n        np.warnings.filterwarnings('ignore')\n        ref_red = ref_red.where(ref_red >= 0)\n        ref_rededge = ref_rededge.where(ref_red >= 0)\n        # pylint: disable=no-member\n        # Loaded in __init__ whit \"__dict__.update\".\n        chla = self.a * pow(ref_rededge / ref_red, 2) + self.b \\\n            * (ref_rededge / ref_red) + self.c\n        chla = chla.where((chla >= 0) & (chla <= self._valid_limit))\n        return chla\n\n\nclass CHLAOC:\n    \"\"\"Chlorophyll-a concentration (in mg/m3) from polynomial maximum band ratio by O'Reilly et al., 1998 and updates\n\n    Blue/green algorithm to retrieve Chlorophyll-a concentration (in mg/m3) from\n    surface reflectances (rho, unitless) or remote sensing reflectances (Rrs,\n    in sr-1)\n    This algorithm was published in O'Reilly 1998, 2000\n    calibration OC2 for OLI from Franz et al., 2015, OC3 for OLI O'Reilly and Werdell, 2019\n    MSI Pahlevan et al., 2020 after O'Reilly and Werdell, 2019\n\n    Attributes:\n        name: The name of the algorithm used. This is the key used by\n            L3AlgoBuilder and that you must provide in config or when using\n            the CLI.\n        requested_bands: A list of bands further used by the algorithm.\n        meta: A dict of metadata (calibration name, model coefficients, etc).\n    \"\"\"\n    _default_calibration_file = wc_calib / 'chla-oc.yaml'\n    _default_calibration_name = 'OC3'\n    name = 'chla-oc'\n\n    def __init__(self,\n                 product_type: str,\n                 calibration: Optional[P] = None,\n                 **_ignored) -> None:\n        \"\"\"Inits an 'CHLAOC' instance with specific settings.\n\n        Args:\n            product_type: The type of the input satellite product (e.g.\n                S2_ESA_L2A or L8_USGS_L1GT)\n            calibration: The calibration (set of parameters) used by the\n                algorithm (default=_default_calibration_name).\n            **_ignored: Unused kwargs sent to trash.\n        \"\"\"\n        try:\n            self.requested_bands = algo_config[self.name][\n                producttype_to_sat(product_type)]\n        except KeyError as invalid_product:\n            msg = f'{product_type} is not allowed with {self.name}'\n            raise InputError(msg) from invalid_product\n        calibration_dict, calibration_name = load_calib(\n            calibration,\n            self._default_calibration_file,\n            self._default_calibration_name\n        )\n        self._valid_limit = calibration_dict['validity_limit']\n        self._version = calibration_name\n        try:\n            params = calibration_dict[producttype_to_sat(product_type)]\n        except KeyError as invalid_product:\n            msg = f'{product_type} is not allowed with this calibration'\n            raise InputError(msg) from invalid_product\n        self.__dict__.update(params)\n        self.meta = {'calibration': self._version,\n                     'validity_limit': self._valid_limit,\n                     **params}\n\n    def __call__(self,\n                 ref_violet: xr.DataArray,\n                 ref_blue: xr.DataArray,\n                 ref_green: xr.DataArray,\n                 data_type: str,\n                 **_ignored) -> xr.DataArray:\n        \"\"\"Runs the algorithm on the input array ('ref').\n\n        Args:\n            ref_violet: An array (dimension 1 * N * M) of 'data_type'.\n            ref_blue: An array (dimension 1 * N * M) of 'data_type'.\n            ref_green: An array (dimension 1 * N * M) of 'data_type'.\n            data_type: Either 'ref' or 'rrs' (respectively surface reflectance\n                and remote sensing reflectance).\n            **_ignored: Unused kwargs sent to trash.\n\n        Returns:\n            An array (dimension 1 * N * M) of chl-a (in mg/m3).\n        \"\"\"\n\n        np.warnings.filterwarnings('ignore')\n        if data_type == 'rho':\n            ref_violet = ref_violet / np.pi\n            ref_blue = ref_blue / np.pi\n            ref_green = ref_green / np.pi\n\n        if self._version == 'OC3':\n            print(f'{self._version} is used')\n            max_ratio = np.log(np.maximum(ref_violet.values, ref_blue.values)\n                               / ref_green)\n            # np.log(max(Rrs_B1, Rrs_B2) / Rrs_B3))\n        else:   # self._version == 'OC2'\n            print(f'{self._version} is used')\n            max_ratio = np.log(ref_blue.values / ref_green)\n        # pylint: disable=no-member\n        # Loaded in __init__ whit \"__dict__.update\".\n        chla = np.power(10, self.a0 + self.a1 * max_ratio + self.a2\n                        * np.power(max_ratio, 2) + self.a3\n                        * np.power(max_ratio, 3) + self.a4\n                        * np.power(max_ratio, 4))\n        chla = chla.where((chla >= 0) & (chla <= self._valid_limit))\n        return chla\n\n\nclass CHLALins:\n    \"\"\"Chlorophyll-a concentration (in mg/m3) from NIR/Red bands ratio after Lins et al., 2017\n\n    Red edge algorithm to retrieve Chlorophyll-a concentration (in mg/m3) from\n    surface reflectances (rho, unitless) or remote sensing reflectances (Rrs,\n    in sr-1) at 665nm B4 MSI, 705nm B5 MSI\n    This algorithm was published in Lins et al., 2017\n\n    Attributes:\n        name: The name of the algorithm used. This is the key used by\n          L3AlgoBuilder and that you must provide in config or when using\n          the CLI.\n        requested_bands: A list of bands further used by the algorithm.\n        meta: A dict of metadata (calibration name, model coefficients, etc).\n    \"\"\"\n    _default_calibration_file = wc_calib / 'chla-lins.yaml'\n    _default_calibration_name = 'Lins_2017'\n    name = 'chla-lins'\n\n    def __init__(self,\n                 product_type: str,\n                 calibration: Optional[P] = None,\n                 **_ignored) -> None:\n        \"\"\"Inits an 'CHLALins' instance with specific settings.\n\n        Args:\n            product_type: The type of the input satellite product (e.g.\n                S2_ESA_L2A or L8_USGS_L1GT)\n            calibration: The calibration (set of parameters) used by the\n                algorithm (default=_default_calibration_name).\n            **_ignored: Unused kwargs sent to trash.\n        \"\"\"\n        try:\n            self.requested_bands = algo_config[self.name][\n                producttype_to_sat(product_type)]\n        except KeyError as invalid_product:\n            msg = f'{product_type} is not allowed with {self.name}'\n            raise InputError(msg) from invalid_product\n        calibration_dict, calibration_name = load_calib(\n            calibration,\n            self._default_calibration_file,\n            self._default_calibration_name\n        )\n        self._valid_limit = calibration_dict['validity_limit']\n        try:\n            params = calibration_dict[producttype_to_sat(product_type)]\n        except KeyError as invalid_product:\n            msg = f'{product_type} is not allowed with this calibration'\n            raise InputError(msg) from invalid_product\n        self.__dict__.update(params)\n        self.meta = {'calibration': calibration_name,\n                     'validity_limit': self._valid_limit,\n                     **params}\n\n    def __call__(self,\n                 ref_red: xr.DataArray,\n                 ref_rededge: xr.DataArray,\n                 data_type: str,\n                 **_ignored) -> xr.DataArray:\n        \"\"\"Runs the algorithm on the input array ('ref').\n\n        Args:\n            ref_red: An array (dimension 1 * N * M) of 'data_type'.\n            ref_redegde: An array (dimension 1 * N * M) of 'data_type'.\n            data_type: Either 'rho' or 'rrs' (respectively surface reflectance\n                and remote sensing reflectance).\n            **_ignored: Unused kwargs sent to trash.\n\n        Returns:\n            An array (dimension 1 * N * M) of chl-a (in mg/m3).\n        \"\"\"\n        np.warnings.filterwarnings('ignore')\n        ref_red = ref_red.where(ref_red >= 0)\n        ref_rededge = ref_rededge.where(ref_red >= 0)\n        # pylint: disable=no-member\n        # Loaded in __init__ whit \"__dict__.update\".\n        chla = self.p * (ref_rededge / ref_red) + self.q\n        chla = chla.where((chla >= 0) & (chla <= self._valid_limit))\n        return chla\n\n\nclass NDCI:\n    \"\"\"Normalized Difference Chlorophyll Index\n\n    NDCI from surface reflectances (rho, unitless) or remote sensing reflectances (Rrs,\n    in sr-1) at 665nm B4 MSI, 704nm B5 MSI\n\n    Attributes:\n        name: The name of the algorithm used. This is the key used by\n            L3AlgoBuilder and that you must provide in config or when using\n            the CLI.\n        requested_bands: A list of bands further used by the algorithm.\n        meta: An empty dict, since there is no parametrisation for NDWI.\n    \"\"\"\n    name = 'ndci'\n\n    def __init__(self, product_type: str, **_ignored) -> None:\n        \"\"\"Inits an 'Ndci' instance for a given 'product_type'.\n\n        Args:\n            product_type: The type of the input satellite product (e.g.\n              S2_ESA_L2A or L8_USGS_L1GT)\n            **_ignored: Unused kwargs send to trash.\n        \"\"\"\n        try:\n            self.requested_bands = algo_config[self.name][\n                producttype_to_sat(product_type)]\n        except KeyError as unvalid_product:\n            msg = f'{product_type} is not allowed with {self.name}'\n            raise InputError(msg) from unvalid_product\n        self.meta = {}\n\n    def __call__(self,\n                 ref_red: xr.DataArray,\n                 ref_nir: xr.DataArray,\n                 **_ignored) -> xr.DataArray:\n        \"\"\"Runs the algorithm on the input array ('ref').\n\n        Args:\n            ref_red: An array (dimension 1 * N * M) of 'data_type'.\n            ref_nir: An array (dimension 1 * N * M) of 'data_type'.\n            data_type: Either 'rho' or 'rrs' (respectively surface reflectance\n                and remote sensing reflectance).\n            **_ignored: Unused kwargs sent to trash.\n\n        Returns:\n            An array (dimension 1 * N * M) of NDCI values.\n        \"\"\"\n        np.warnings.filterwarnings('ignore')\n        red = ref_red.where(ref_red >= 0)\n        nir = ref_nir.where(ref_nir >= 0)\n\n        return (nir - red) / (nir + red)\n", "meta": {"hexsha": "b1ac95fa2b58268d577410ab6a6387bbac815b61", "size": 23280, "ext": "py", "lang": "Python", "max_stars_repo_path": "sisppeo/wcproducts/chla.py", "max_stars_repo_name": "inrae/SISPPEO", "max_stars_repo_head_hexsha": "f516bb778b505739fdf320affe651b715ed75324", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-11-05T09:23:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T10:39:13.000Z", "max_issues_repo_path": "sisppeo/wcproducts/chla.py", "max_issues_repo_name": "inrae/SISPPEO", "max_issues_repo_head_hexsha": "f516bb778b505739fdf320affe651b715ed75324", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sisppeo/wcproducts/chla.py", "max_forks_repo_name": "inrae/SISPPEO", "max_forks_repo_head_hexsha": "f516bb778b505739fdf320affe651b715ed75324", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2765957447, "max_line_length": 117, "alphanum_fraction": 0.6100945017, "include": true, "reason": "import numpy", "num_tokens": 5583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771035, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.18410723061877798}}
{"text": "# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2020, the cclib development team\n#\n# This file is part of cclib (http://cclib.github.io) and is distributed under\n# the terms of the BSD 3-Clause License.\n\n\"\"\"Calculation of DDEC charges based on data parsed by cclib.\"\"\"\nimport copy\nimport random\nimport numpy\nimport logging\nimport math\nimport os\nimport sys\n\nfrom cclib.method.calculationmethod import Method\nfrom cclib.method.volume import electrondensity_spin\nfrom cclib.parser.utils import convertor\nfrom cclib.parser.utils import find_package\n\nfrom typing import List\n\n\nclass MissingInputError(Exception):\n    pass\n\n\nclass DDEC6(Method):\n    \"\"\"DDEC6 charges.\"\"\"\n\n    # All of these are required for DDEC6 charges.\n    required_attrs = (\"homos\", \"mocoeffs\", \"nbasis\", \"gbasis\")\n\n    def __init__(\n        self, data, volume, proatom_path=None, progress=None, loglevel=logging.INFO, logname=\"Log\"\n    ):\n        # Inputs are:\n        # data -- ccData object that describe target molecule.\n        # volume -- Volume object that describe target Cartesian grid.\n        # proatom_path -- path to proatom densities\n        #      (directory containing atoms.h5 in horton or c2_001_001_000_400_075.txt in chargemol)\n        super(DDEC6, self).__init__(data, progress, loglevel, logname)\n\n        self.volume = volume\n        self.fragresults = None\n        self.proatom_path = proatom_path\n\n        if numpy.sum(self.data.coreelectrons) != 0:\n            # TODO: Pseudopotentials should be added back\n            pass\n\n        # Check whether proatom_path is a valid directory or not.\n        assert os.path.isdir(\n            proatom_path\n        ), \"Directory that contains proatom densities should be added as an input.\"\n\n        # Read in reference charges.\n        self.proatom_density = []\n        self.radial_grid_r = []\n        for atom_number in self.data.atomnos:\n            density, r = self._read_proatom(proatom_path, atom_number, 0)\n            self.proatom_density.append(density)\n            self.radial_grid_r.append(r)\n\n    def __str__(self):\n        \"\"\"Return a string representation of the object.\"\"\"\n        return \"DDEC6 charges of {}\".format(self.data)\n\n    def __repr__(self):\n        \"\"\"Return a representation of the object.\"\"\"\n        return \"DDEC6({})\".format(self.data)\n\n    def _check_required_attributes(self):\n        super(DDEC6, self)._check_required_attributes()\n\n    def _cartesian_dist(self, pt1, pt2):\n        \"\"\" Small utility function that calculates Euclidian distance between two points\n            pt1 and pt2 are numpy arrays representing a point in Cartesian coordinates. \"\"\"\n        return numpy.sqrt(numpy.dot(pt1 - pt2, pt1 - pt2))\n\n    def _read_proatom(\n        self, directory, atom_num, charge  # type = str  # type = int  # type = float\n    ):\n        # type: (...) -> numpy.ndarray, numpy.ndarray\n        \"\"\"Return a list containing proatom reference densities.\"\"\"\n        # TODO: Treat calculations with psuedopotentials\n        # TODO: Modify so that proatom densities are read only once for horton\n        #       [https://github.com/cclib/cclib/pull/914#discussion_r464039991]\n        # File name format:\n        #   ** Chargemol **\n        #       c2_[atom number]_[nuclear charge]_[electron count]_[cutoff radius]_[# shells]\n        #   ** Horton **\n        #       atoms.h5\n        # File format:\n        #   Starting from line 13, each line contains the charge densities for each shell\n        # If `charge` is not an integer, proatom densities have to be linearly interpolated between\n        # the densities of the ion/atom with floor(charge) and ceiling(charge)\n        charge_floor = int(math.floor(charge))\n        charge_ceil = int(math.ceil(charge))\n\n        chargemol_path_floor = os.path.join(\n            directory,\n            \"c2_{:03d}_{:03d}_{:03d}_500_100.txt\".format(\n                atom_num, atom_num, atom_num - charge_floor\n            ),\n        )\n        chargemol_path_ceil = os.path.join(\n            directory,\n            \"c2_{:03d}_{:03d}_{:03d}_500_100.txt\".format(\n                atom_num, atom_num, atom_num - charge_ceil\n            ),\n        )\n        horton_path = os.path.join(directory, \"atoms.h5\")\n\n        if os.path.isfile(chargemol_path_floor) or os.path.isfile(chargemol_path_ceil):\n            # Use chargemol proatom densities\n            # Each shell is .05 angstroms apart (uniform).\n            # *scalefactor* = 10.58354497764173 bohrs in module_global_parameter.f08\n            if atom_num <= charge_floor:\n                density_floor = numpy.array([0])\n            else:\n                density_floor = numpy.loadtxt(chargemol_path_floor, skiprows=12, dtype=float)\n            if atom_num >= charge_ceil:\n                density_ceil = numpy.array([0])\n            else:\n                density_ceil = numpy.loadtxt(chargemol_path_ceil, skiprows=12, dtype=float)\n\n            density = (charge_ceil - charge) * density_floor + (\n                charge - charge_floor\n            ) * density_ceil\n            radiusgrid = numpy.arange(1, len(density) + 1) * 0.05\n\n        elif os.path.isfile(horton_path):\n            # Use horton proatom densities\n            assert find_package(\"h5py\"), \"h5py is needed to read in proatom densities from horton.\"\n\n            import h5py\n\n            with h5py.File(horton_path, \"r\") as proatomdb:\n                if atom_num <= charge_floor:\n                    density_floor = numpy.array([0])\n                    radiusgrid = numpy.array([0])\n                else:\n                    keystring_floor = \"Z={}_Q={:+d}\".format(atom_num, charge_floor)\n                    density_floor = numpy.asanyarray(list(proatomdb[keystring_floor][\"rho\"]))\n\n                    # gridspec is specification of integration grid for proatom densities in horton.\n                    # Example -- ['PowerRTransform', '1.1774580743206259e-07', '20.140888089596444', '41']\n                    #   is constructed using PowerRTransform grid\n                    #   with rmin = 1.1774580743206259e-07\n                    #        rmax = 20.140888089596444\n                    #   and  ngrid = 41\n                    # PowerRTransform is default in horton-atomdb.py.\n                    gridtype, gridmin, gridmax, gridn = (\n                        proatomdb[keystring_floor].attrs[\"rtransform\"].split()\n                    )\n                    gridmin = convertor(float(gridmin), \"bohr\", \"Angstrom\")\n                    gridmax = convertor(float(gridmax), \"bohr\", \"Angstrom\")\n                    gridn = int(gridn)\n                    # Convert byte to string in Python3\n                    if sys.version[0] == \"3\":\n                        gridtype = gridtype.decode(\"UTF-8\")\n\n                    # First verify that it is one of recognized grids\n                    assert gridtype in [\n                        \"LinearRTransform\",\n                        \"ExpRTransform\",\n                        \"PowerRTransform\",\n                    ], \"Grid type not recognized.\"\n\n                    if gridtype == \"LinearRTransform\":\n                        # Linear transformation. r(t) = rmin + t*(rmax - rmin)/(npoint - 1)\n                        gridcoeff = (gridmax - gridmin) / (gridn - 1)\n                        radiusgrid = gridmin + numpy.arange(1, gridn + 1) * gridcoeff\n                    elif gridtype == \"ExpRTransform\":\n                        # Exponential transformation. r(t) = rmin*exp(t*log(rmax/rmin)/(npoint - 1))\n                        gridcoeff = math.log(gridmax / gridmin) / (gridn - 1)\n                        radiusgrid = gridmin * numpy.exp(numpy.arange(1, gridn + 1) * gridcoeff)\n                    elif gridtype == \"PowerRTransform\":\n                        # Power transformation. r(t) = rmin*t^power\n                        # with  power = log(rmax/rmin)/log(npoint)\n                        gridcoeff = math.log(gridmax / gridmin) / math.log(gridn)\n                        radiusgrid = gridmin * numpy.power(numpy.arange(1, gridn + 1), gridcoeff)\n\n                if atom_num <= charge_ceil:\n                    density_ceil = numpy.array([0])\n                else:\n                    keystring_ceil = \"Z={}_Q={:+d}\".format(atom_num, charge_ceil)\n                    density_ceil = numpy.asanyarray(list(proatomdb[keystring_ceil][\"rho\"]))\n\n                density = (charge_ceil - charge) * density_floor + (\n                    charge - charge_floor\n                ) * density_ceil\n\n                del h5py\n\n        else:\n            raise MissingInputError(\"Pro-atom densities were not found in the specified path.\")\n\n        if charge == charge_floor:\n            density = density_floor\n\n        return density, radiusgrid\n\n    def calculate(self, indices=None, fupdate=0.05):\n        \"\"\"\n        Calculate DDEC6 charges based on doi: 10.1039/c6ra04656h paper.\n        Cartesian, uniformly spaced grids are assumed for this function.\n        \"\"\"\n\n        # Obtain charge densities on the grid if it does not contain one.\n        if not numpy.any(self.volume.data):\n            self.logger.info(\"Calculating charge densities on the provided empty grid.\")\n            if len(self.data.mocoeffs) == 1:\n                self.chgdensity = electrondensity_spin(\n                    self.data, self.volume, [self.data.mocoeffs[0][: self.data.homos[0]]]\n                )\n                self.chgdensity.data *= 2\n            else:\n                self.chgdensity = electrondensity_spin(\n                    self.data,\n                    self.volume,\n                    [\n                        self.data.mocoeffs[0][: self.data.homos[0]],\n                        self.data.mocoeffs[1][: self.data.homos[1]],\n                    ],\n                )\n        # If charge densities are provided beforehand, log this information\n        # `Volume` object does not contain (nor rely on) information about the constituent atoms.\n        else:\n            self.logger.info(\"Using charge densities from the provided Volume object.\")\n            self.chgdensity = self.volume\n\n        # STEP 1\n        # Carry out step 1 of DDEC6 algorithm [Determining ion charge value]\n        # Refer to equations 49-57 in doi: 10.1039/c6ra04656h\n        self.logger.info(\"Creating first reference charges.\")\n        ref, loc, stock = self.calculate_refcharges()\n        self.refcharges = [ref]\n        self._localizedcharges = [loc]\n        self._stockholdercharges = [stock]\n\n        # STEP 2\n        # Load new proatom densities.\n        self.logger.info(\"Creating second reference charges.\")\n        self.proatom_density = []\n        self.radial_grid_r = []\n        for i, atom_number in enumerate(self.data.atomnos):\n            density, r = self._read_proatom(\n                self.proatom_path, atom_number, float(self.refcharges[0][i])\n            )\n            self.proatom_density.append(density)\n            self.radial_grid_r.append(r)\n\n        # Carry out step 2 of DDEC6 algorithm [Determining ion charge value again]\n        ref, loc, stock = self.calculate_refcharges()\n        self.refcharges.append(ref)\n        self._localizedcharges.append(loc)\n        self._stockholdercharges.append(stock)\n\n        # STEP 3\n        # Load new proatom densities.\n        self.proatom_density = []\n        self.radial_grid_r = []\n        for i, atom_number in enumerate(self.data.atomnos):\n            density, r = self._read_proatom(\n                self.proatom_path, atom_number, float(self.refcharges[1][i])\n            )\n            self.proatom_density.append(density)\n            self.radial_grid_r.append(r)\n\n        # Carry out step 3 of DDEC6 algorithm [Determine conditioned charge density and tau]\n        self.logger.info(\"Conditioning charge densities.\")\n        self.condition_densities()\n\n    def calculate_refcharges(self):\n        \"\"\" Calculate reference charges from proatom density and molecular density\n            [STEP 1 and 2]\n        \"\"\"\n        # Generator object to iterate over the grid\n        xshape, yshape, zshape = self.chgdensity.data.shape\n        atoms = len(self.data.atomnos)\n        indices = (\n            (i, x, y, z)\n            for i in range(atoms)\n            for x in range(xshape)\n            for y in range(yshape)\n            for z in range(zshape)\n        )\n\n        stockholder_w = numpy.zeros((atoms, xshape, yshape, zshape))\n        localized_w = numpy.zeros((atoms, xshape, yshape, zshape))\n        self.closest_r_index = numpy.zeros((atoms, xshape, yshape, zshape), dtype=int)\n\n        for atomi, xindex, yindex, zindex in indices:\n            # Distance of the grid from atom grid\n            dist_r = self._cartesian_dist(\n                self.data.atomcoords[-1][atomi],\n                self.chgdensity.coordinates([xindex, yindex, zindex]),\n            )\n            self.closest_r_index[atomi][xindex][yindex][zindex] = numpy.abs(\n                self.radial_grid_r[atomi] - dist_r\n            ).argmin()\n\n            # Equation 54 in doi: 10.1039/c6ra04656h\n            stockholder_w[atomi][xindex][yindex][zindex] = self.proatom_density[atomi][\n                self.closest_r_index[atomi][xindex][yindex][zindex]\n            ]\n\n        # Equation 55 in doi: 10.1039/c6ra04656h\n        localized_w = numpy.power(stockholder_w, 4)\n\n        # Equation 53 in doi: 10.1039/c6ra04656h\n        stockholder_bigW = numpy.sum(stockholder_w, axis=0)\n        localized_bigW = numpy.sum(localized_w, axis=0)\n\n        refcharges = numpy.zeros((atoms))\n        localizedcharges = numpy.zeros((atoms))\n        stockholdercharges = numpy.zeros((atoms))\n\n        for atomi in range(atoms):\n            # Equation 52 and 51 in doi: 10.1039/c6ra04656h\n            localizedcharges[atomi] = self.data.atomnos[atomi] - self.chgdensity.integrate(\n                weights=(localized_w[atomi] / localized_bigW)\n            )\n            stockholdercharges[atomi] = self.data.atomnos[atomi] - self.chgdensity.integrate(\n                weights=(stockholder_w[atomi] / stockholder_bigW)\n            )\n\n            # In DDEC6, weights of 1/3 and 2/3 are assigned for stockholder and localized charges.\n            # (Equation 50 and 58 in doi: 10.1039/c6ra04656h)\n            refcharges[atomi] = (stockholdercharges[atomi] / 3.0) + (\n                localizedcharges[atomi] * 2.0 / 3.0\n            )\n\n        return refcharges, localizedcharges, stockholdercharges\n\n    def condition_densities(self):\n        \"\"\" Calculate conditioned densities\n            [STEP 3]\n        \"\"\"\n        # Generator object to iterate over the grid\n        xshape, yshape, zshape = self.chgdensity.data.shape\n        atoms = len(self.data.atomnos)\n        indices = (\n            (i, x, y, z)\n            for i in range(atoms)\n            for x in range(xshape)\n            for y in range(yshape)\n            for z in range(zshape)\n        )\n\n        self._rho_ref = numpy.zeros((xshape, yshape, zshape))\n\n        for atomi, xindex, yindex, zindex in indices:\n            # rho_ref -- Equation 41 in doi: 10.1039/c6ra04656h\n            self._rho_ref[xindex][yindex][zindex] += self.proatom_density[atomi][\n                self.closest_r_index[atomi][xindex][yindex][zindex]\n            ]\n\n        self._candidates_bigPhi = []\n        self._candidates_phi = []\n\n        # Initial conditions are detailed in Figure S1 in doi: 10.1039/c6ra04656h\n        phiAI = numpy.zeros_like(self.data.atomnos, dtype=float)\n        bigphiAI = numpy.zeros_like(self.data.atomnos, dtype=float)\n        self._y_a = []\n        self._cond_density = []\n\n        for atomi in range(len(self.data.atomnos)):\n            # y_a -- equation 40 in doi: 10.1039/c6ra04656h\n            self._y_a.append(self._ya(self.proatom_density, atomi))\n            # rho_A^cond -- equation S97 in doi: 10.1039/c6ra04656h\n            self._cond_density.append(\n                self._y_a[atomi] + bigphiAI[atomi] * numpy.sqrt(self._y_a[atomi])\n            )\n            # Monotonic Decrease Condition (as expressed in equation S99)\n            self._cond_density[atomi] = numpy.minimum.accumulate(self._cond_density[atomi])\n            # phi_A^I -- Equation S100 in doi: 10.1039/c6ra04656h\n            phiAI[atomi] = (\n                self._integrate_from_radial([self._cond_density[atomi]], [atomi])\n                - self.data.atomnos[atomi]\n                + self.refcharges[-1][atomi]\n            )\n\n            self._candidates_bigPhi.append([bigphiAI[atomi]])\n            self._candidates_phi.append([phiAI[atomi]])\n\n            fitphi = True  # when convergence is reached, this is modified to False.\n\n            while phiAI[atomi] <= 0:\n                # Iterative algorithm until convergence\n                # Refer to S101 in doi: 10.1039/c6ra04656h\n                bigphiAI[atomi] = 2 * bigphiAI[atomi] - phiAI[atomi] / self._integrate_from_radial(\n                    [numpy.sqrt(self._y_a[atomi])], [atomi]\n                )\n\n                # When Phi is updated, related quantities are updated as well\n                # Refer to S100 in doi: 10.1039/c6ra04656h\n                phiAI[atomi], self._cond_density[atomi] = self._phiai(\n                    self._y_a[atomi], bigphiAI[atomi], atomi\n                )\n\n                self._candidates_phi[atomi].append(phiAI[atomi])\n                self._candidates_bigPhi[atomi].append(bigphiAI[atomi])\n\n            # lowerbigPhi is largest negative Phi.\n            # upperbigPhi is smallest positive Phi.\n            if fitphi:\n                self._candidates_phi[atomi] = numpy.array(self._candidates_phi[atomi], dtype=float)\n                self._candidates_bigPhi[atomi] = numpy.array(\n                    self._candidates_bigPhi[atomi], dtype=float\n                )\n                if numpy.count_nonzero(self._candidates_phi[atomi] < 0) > 0:\n                    lower_ind = numpy.where(\n                        self._candidates_phi[atomi]\n                        == self._candidates_phi[atomi][self._candidates_phi[atomi] < 0].max()\n                    )[0][0]\n                    lowerbigPhi = self._candidates_bigPhi[atomi][lower_ind]\n                    lowerphi = self._candidates_phi[atomi][lower_ind]\n                else:  # assign some large negative number\n                    lowerbigPhi = numpy.NINF\n                    lowerphi = numpy.NINF\n                if numpy.count_nonzero(self._candidates_phi[atomi] > 0) > 0:\n                    upper_ind = numpy.where(\n                        self._candidates_phi[atomi]\n                        == self._candidates_phi[atomi][self._candidates_phi[atomi] > 0].min()\n                    )[0][0]\n                    upperbigPhi = self._candidates_bigPhi[atomi][upper_ind]\n                    upperphi = self._candidates_phi[atomi][upper_ind]\n                else:  # assign some large positive number\n                    upperbigPhi = numpy.PINF\n                    upperphi = numpy.PINF\n\n            iter = 0\n            while fitphi and iter < 50:\n                # Flow diagram on Figure S1 in doi: 10.1039/c6ra04656h details the procedure.\n                iter = iter + 1\n                midbigPhi = (lowerbigPhi + upperbigPhi) / 2.0\n                midphi = self._phiai(self._y_a[atomi], midbigPhi, atomi)[0]\n                # Exit conditions\n                if abs(lowerphi) < 1e-10:\n                    bigphiAI[atomi] = lowerbigPhi\n                    fitphi = False\n                elif abs(upperphi) < 1e-10:\n                    bigphiAI[atomi] = upperbigPhi\n                    fitphi = False\n                elif abs(midphi) < 1e-10:\n                    bigphiAI[atomi] = midbigPhi\n                    fitphi = False\n                else:\n                    # Parabolic fitting as described on Figure S1 in doi: 10.1039/c6ra04656h\n                    # Type casting here converts from size 1 numpy.ndarray to float\n                    xpts = numpy.array(\n                        [float(lowerbigPhi), float(midbigPhi), float(upperbigPhi)], dtype=float\n                    )\n                    ypts = numpy.array(\n                        [float(lowerphi), float(midphi), float(upperphi)], dtype=float\n                    )\n                    fit = numpy.polyfit(xpts, ypts, 2)\n                    roots = numpy.roots(fit)  # max two roots (bigPhi)\n\n                    belowphi = self._phiai(self._y_a[atomi], roots.min(), atomi)[0]\n                    abovephi = self._phiai(self._y_a[atomi], roots.max(), atomi)[0]\n\n                    if abs(abovephi) < 1e-10:\n                        bigphiAI[atomi] = roots.min()\n                        fitphi = False\n                    elif abs(belowphi) < 1e-10:\n                        bigphiAI[atomi] = roots.max()\n                        fitphi = False\n                    else:\n                        if 3 * abs(abovephi) < abs(belowphi):\n                            corbigPhi = roots.max() - 2.0 * abovephi * (\n                                roots.max() - roots.min()\n                            ) / (abovephi - belowphi)\n                        elif 3 * abs(belowphi) < abs(abovephi):\n                            corbigPhi = roots.min() - 2.0 * belowphi * (\n                                roots.max() - roots.min()\n                            ) / (abovephi - belowphi)\n                        else:\n                            corbigPhi = (roots.max() + roots.min()) / 2.0\n                        # New candidates\n                        corphi = self._phiai(self._y_a[atomi], corbigPhi, atomi)[0]\n                        self._candidates_bigPhi[atomi] = numpy.array(\n                            [\n                                lowerbigPhi,\n                                midbigPhi,\n                                upperbigPhi,\n                                roots.max(),\n                                roots.min(),\n                                corbigPhi,\n                            ],\n                            dtype=float,\n                        )\n                        self._candidates_phi[atomi] = numpy.array(\n                            [lowerphi, midphi, upperphi, abovephi, belowphi, corphi], dtype=float\n                        )\n\n                        # Update upperphi and lowerphi\n                        lower_ind = numpy.where(\n                            self._candidates_phi[atomi]\n                            == self._candidates_phi[atomi][self._candidates_phi[atomi] < 0].max()\n                        )[0][0]\n                        upper_ind = numpy.where(\n                            self._candidates_phi[atomi]\n                            == self._candidates_phi[atomi][self._candidates_phi[atomi] > 0].min()\n                        )[0][0]\n\n                        lowerphi = self._candidates_phi[atomi][lower_ind]\n                        upperphi = self._candidates_phi[atomi][upper_ind]\n\n                        if abs(lowerphi) < 1e-10:\n                            bigphiAI[atomi] = self._candidates_bigPhi[atomi][lower_ind]\n                            fitphi = False\n                        elif abs(upperphi) < 1e-10:\n                            bigphiAI[atomi] = self._candidates_bigPhi[atomi][upper_ind]\n                            fitphi = False\n                        else:\n                            # Fitting needs to continue in this case.\n                            lowerbigPhi = self._candidates_bigPhi[atomi][lower_ind]\n                            lowerphi = self._candidates_phi[atomi][lower_ind]\n                            upperbigPhi = self._candidates_bigPhi[atomi][upper_ind]\n                            upperphi = self._candidates_phi[atomi][upper_ind]\n\n            assert not fitphi, \"Iterative conditioning failed to converge.\"\n\n            # Set final conditioned density using chosen Phi\n            self._cond_density[atomi] = self._phiai(self._y_a[atomi], bigphiAI[atomi], atomi)[1]\n\n        self.logger.info(\"Calculating tau and combined conditioned densities.\")\n\n        # Calculate tau(r) and rho^cond(r)\n        # Refer to equation 65 and 66 in doi: 10.1039/c6ra04656h\n        # Assign rho^cond on grid using generator object\n        self.rho_cond = copy.deepcopy(self.chgdensity)\n        self.rho_cond.data = numpy.zeros_like(self.rho_cond.data, dtype=float)\n        rho_cond_sqrt = numpy.zeros_like(self.rho_cond.data, dtype=float)\n\n        # Generator object to iterate over the grid\n        xshape, yshape, zshape = self.chgdensity.data.shape\n        atoms = len(self.data.atomnos)\n        indices = (\n            (i, x, y, z)\n            for i in range(atoms)\n            for x in range(xshape)\n            for y in range(yshape)\n            for z in range(zshape)\n        )\n\n        self._leftterm = numpy.zeros((atoms, xshape, yshape, zshape), dtype=float)\n        self.tau = []\n\n        # rho_cond -- equation 65 in doi: 10.1039/c6ra04656h\n        for atomi, xindex, yindex, zindex in indices:\n            self.rho_cond.data[xindex][yindex][zindex] += self._cond_density[atomi][\n                self.closest_r_index[atomi][xindex][yindex][zindex]\n            ]\n\n        rho_cond_sqrt = numpy.sqrt(self.rho_cond.data)\n\n        for atomi in range(len(self.data.atomnos)):\n            self.tau.append(numpy.zeros_like(self.proatom_density[atomi], dtype=float))\n            grid = ((x, y, z) for x in range(xshape) for y in range(yshape) for z in range(zshape))\n            for xindex, yindex, zindex in grid:\n                # leftterm is the first spherical average term in equation 66.\n                # <rho^cond_A(r_A) / sqrt(rho^cond(r))>\n                self._leftterm[atomi][xindex][yindex][zindex] = self._cond_density[atomi][\n                    self.closest_r_index[atomi][xindex][yindex][zindex]\n                ]\n            self._leftterm[atomi] = self._leftterm[atomi] / rho_cond_sqrt\n            for radiusi in range(len(self.tau[atomi])):\n                grid_filter = self.closest_r_index[atomi] == radiusi\n                num_grid_filter = numpy.count_nonzero(grid_filter)\n                if num_grid_filter < 1:\n                    self.tau[atomi][radiusi] = 0.0\n                else:\n                    leftaverage = numpy.sum(grid_filter * self._leftterm[atomi]) / num_grid_filter\n                    rightaverage = numpy.sum(grid_filter * rho_cond_sqrt) / num_grid_filter\n                    if leftaverage < 1e-20:\n                        self.tau[atomi][radiusi] = 0.0\n                    else:\n                        self.tau[atomi][radiusi] = numpy.divide(\n                            leftaverage,\n                            rightaverage,\n                            out=numpy.zeros_like(leftaverage),\n                            where=rightaverage != 0.0,\n                        )\n            # Make tau monotonic decreasing\n            self.tau[atomi] = numpy.maximum.accumulate(self.tau[atomi][::-1])[::-1]\n\n    def _phiai(self, ya, bigphiAI, atomi):\n        \"\"\" Evaluate phi_A^I based on equation S100\n        \"\"\"\n        # Re-evaluate cond_density\n        if isinstance(bigphiAI, float) and not numpy.isinf(bigphiAI):\n            cond_density = ya + bigphiAI * numpy.sqrt(ya)\n        else:\n            cond_density = ya\n\n        # Monotonic Decrease Condition\n        cond_density = numpy.minimum.accumulate(cond_density)\n\n        # Re-evaluate phi_AI\n        phiAI = (\n            self._integrate_from_radial([cond_density], [atomi])\n            - self.data.atomnos[atomi]\n            + self.refcharges[-1][atomi]\n        )\n\n        return phiAI, cond_density\n\n    def _ya(self, proatom_density, atomi):\n        # Function that calculates Y_a^avg\n        # See Eq. 40-41 in doi: 10.1039/c6ra04656h\n        rho_ref = self._rho_ref\n        # Y_a^avg -- Equation 40 in doi: 10.1039/c6ra04656h\n        ya = numpy.zeros_like(proatom_density[atomi], dtype=float)\n        weights = self.chgdensity.data / rho_ref\n        for radiusi in range(len(ya)):\n            grid_filter = self.closest_r_index[atomi] == radiusi\n            num_grid_filter = numpy.count_nonzero(grid_filter)\n            if num_grid_filter < 1:\n                ya[radiusi] = 0.0\n            else:\n                spherical_avg = numpy.sum(grid_filter * weights) / num_grid_filter\n                ya[radiusi] = proatom_density[atomi][radiusi] * spherical_avg\n\n        # Make y_a monotonic decreasing\n        # Refer to module_reshaping_functions.f08::77-79\n        ya = numpy.maximum.accumulate(ya[::-1])[::-1]\n        ya = numpy.minimum.accumulate(ya)\n\n        # Normalize y_a (see module_DDEC6_valence_iterator.f08::284)\n        nelec = self._integrate_from_radial([ya], [atomi])\n        ya *= (self.data.atomnos[atomi] - self.refcharges[-1][atomi]) / nelec\n\n        return ya\n\n    def _integrate_from_radial(self, radial_density_list, atom_list):\n        # Function that reads in list of radial densities, projects it on Cartesian grid,\n        # and returns integrated value\n        grid = copy.deepcopy(self.chgdensity)\n        grid.data = numpy.zeros_like(grid.data)\n\n        xshape, yshape, zshape = self.chgdensity.data.shape\n        indices = ((x, y, z) for x in range(xshape) for y in range(yshape) for z in range(zshape))\n\n        for density, atomi in zip(radial_density_list, atom_list):\n            for x, y, z in indices:\n                grid.data[x][y][z] = (\n                    grid.data[x][y][z] + density[self.closest_r_index[atomi][x][y][z]]\n                )\n\n        return grid.integrate()\n", "meta": {"hexsha": "722c51fddbd33f51392ae9cc1d55438826fb6511", "size": 29281, "ext": "py", "lang": "Python", "max_stars_repo_path": "cclib/method/ddec.py", "max_stars_repo_name": "cks-coil/cclib", "max_stars_repo_head_hexsha": "fe8a4471ec79917ac50eac52d8250c4ae0a532da", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-19T09:04:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-19T09:04:00.000Z", "max_issues_repo_path": "cclib/method/ddec.py", "max_issues_repo_name": "cks-coil/cclib", "max_issues_repo_head_hexsha": "fe8a4471ec79917ac50eac52d8250c4ae0a532da", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cclib/method/ddec.py", "max_forks_repo_name": "cks-coil/cclib", "max_forks_repo_head_hexsha": "fe8a4471ec79917ac50eac52d8250c4ae0a532da", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.5677321157, "max_line_length": 106, "alphanum_fraction": 0.5539428298, "include": true, "reason": "import numpy", "num_tokens": 6784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.1841072284525724}}
{"text": "#  Copyright (C) 2012 Matt Hagy <hagy@gatech.edu>\n#\n#  Licensed under the Apache License, Version 2.0 (the \"License\");\n#  you may not use this file except in compliance with the License.\n#  You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n#  Unless required by applicable law or agreed to in writing, software\n#  distributed under the License is distributed on an \"AS IS\" BASIS,\n#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#  See the License for the specific language governing permissions and\n#  limitations under the License.\n#\n\nfrom __future__ import division\n\nfrom functools import wraps\n\nimport numpy as np\ntry:\n    from scipy.optimize import fmin_cg\nexcept ImportError:\n    def fmin_cg(*args, **kwds):\n        raise RuntimeError('fmin_cg not available; install scipy to use this functionality')\n\nfrom base_components import (NeighborsTable, BaseForceField, LJForceField, BaseConfig,\n                             BasePairCorrelationFunctionCalculator,\n                             BaseMeanSquareDisplacementCalculator,\n                             BaseVelocityAutocorrelationCalculator)\nfrom util import periodic_distances\n\n# TODO\n# Separate simulation and analysis code into separate modules.\n# Further separate analysis code into static vs. dynamic analysis.\n\n__all__ = ['NeighborsTable', 'BaseForceField', 'LJForceField',\n           'Config', 'NeighborsTableTracker', 'EnergyMinimzer',\n           'MDSimulator',\n           'StaticPairCorrelation',\n           'StaticPairCorrelationCalculator',\n           'StaticPairCorrelationIntegrator',\n           'MeanSquareDisplacementCalculator',\n           'VelocityAutocorrelationCalculator']\n\ndef create_random_state(op=None):\n    if isinstance(op, np.random.RandomState):\n        return op\n    return np.random.RandomState(op)\n\ndef create_velocities(N, T=1.0, mass=1.0, random_state=None):\n    return create_random_state(random_state).normal(scale=np.sqrt(T / mass), size=(N, 3))\n\ndef calculate_box_size(N, sigma, rho):\n    '''Calculate the lateral size for a cubic box of N\n       particles, each of diameter sigma, such that the particle\n       density is rho = N*sigma**3/V\n    '''\n    V = N * sigma**3 / rho\n    return V**(1/3)\n\ndef create_hcp_positions(l):\n    '''Create a hexagonal close-packed (hcp) lattice of sphere positions that are\n       contained within a cubic box of lateral size l (each sphere has unit diameter).\n    '''\n    r = 0.5\n    row_height_shift = r * np.sqrt(3)\n    plane_height_shift = np.sqrt(6) * r * 2.0 / 3.0\n    n_row = int(np.floor(l))\n\n    row0 = np.array([np.arange(n_row), np.zeros(n_row), np.zeros(n_row)]).T\n    plane0 = np.array([row0 + np.array([r if i%2==1 else 0, i*row_height_shift, 0])\n                       for i in xrange(int(np.floor(l / row_height_shift)))])\n    planes = np.array([plane0 + np.array([r if i%2==1 else 0,\n                                         np.sqrt(3)/3*r if i%2==1 else 0,\n                                          i * plane_height_shift])\n                       for i in xrange(int(np.floor(l / plane_height_shift)))])\n\n    sites = planes.reshape((np.prod(planes.shape[:3:]), 3))\n    return sites\n\nclass Config(BaseConfig):\n    '''Represents the current static and dynamic state of isotropic\n       particle system within a cubic periodic box.\n    '''\n\n    @classmethod\n    def create(cls, N, rho, dt, sigma=1.0, T=1.0, mass=1.0, random_state=None):\n        '''Create a new random config with N particle at density rho.\n        '''\n        random_state = create_random_state(random_state)\n        box_size = calculate_box_size(N, sigma, rho)\n        hcp_positions = sigma * create_hcp_positions(box_size / sigma)\n        if len(hcp_positions) < N:\n            raise ValueError(\"config cannot be initialized from hcp lattice\")\n        hcp_indices = np.arange(len(hcp_positions))\n        random_state.shuffle(hcp_indices)\n        positions = hcp_positions[hcp_indices[:N:]]\n        inst = cls(positions, last_positions=None, box_size=box_size, dt=dt, sigma=sigma)\n        inst.randomize_velocities(T=T, mass=mass, random_state=random_state)\n        return inst\n\n    def copy(self):\n        return self.__class__(positions=self.positions.copy(),\n                              last_positions=self.last_positions.copy(),\n                              box_size=self.box_size,\n                              dt=self.dt,\n                              sigma=self.sigma)\n\n    def with_new_positions(self, new_positions):\n        cp = self.__class__(positions=new_positions, last_positions=None,\n                            box_size=self.box_size, dt=self.dt, sigma=self.sigma)\n        cp.set_velocities(self.calculate_velocities())\n        return cp\n\n    def randomize_velocities(self, **kwds):\n        self.set_velocities(create_velocities(self.N, **kwds))\n\n    def set_velocities(self, velocities):\n        self.last_positions = self.positions - self.dt * velocities\n\n    def calculate_velocities(self):\n        return (self.positions - self.last_positions) / self.dt\n\n    def calculate_rms_velocity(self):\n        v = self.calculate_velocities()\n        return (v**2).sum(axis=1).mean()**0.5\n\n    def calculate_kinetic_energy(self, mass):\n        v_rms = self.calculate_rms_velocity()\n        return 0.5 * mass * v_rms**2\n\n    def calculate_temperature(self, mass):\n        KE = self.calculate_kinetic_energy(mass)\n        return 2.0 / 3.0 * KE\n\n    @property\n    def N(self):\n        return len(self.positions)\n\n    @property\n    def V(self):\n        return self.box_size**3\n\n    @property\n    def rho(self):\n        return self.N / self.V\n\n    def rescale_boxsize(self, new_boxsize):\n        velocities = self.calculate_velocities()\n        self.positions %= self.box_size\n        self.positions *= new_boxsize / self.box_size\n        self.box_size = new_boxsize\n        self.set_velocities(velocities)\n\n    def rescale_boxsize_rho(self, new_rho):\n        self.rescale_boxsize(calculate_box_size(self.N, self.sigma, new_rho))\n\n    def normalize_positions(self):\n        velocities = self.calculate_velocities()\n        self.positions %= self.box_size\n        self.set_velocities(velocities)\n\n    def change_dt(self, dt):\n        velocities = self.calculate_velocities()\n        self.dt = dt\n        self.set_velocities(velocities)\n\n    def propagate(self, forces, mass=1.0):\n        positions = -self.last_positions + 2 * self.positions + (self.dt**2 / mass) * forces\n        self.last_positions = self.positions\n        self.positions = positions\n\n    def __reduce__(self):\n        return (Config, (self.positions, self.last_positions, self.box_size, self.dt, self.sigma))\n\n\nclass NeighborsTableTracker(object):\n\n    def __init__(self, neighbors_table, box_size):\n        self.neighbors_table = neighbors_table\n        self.box_size = box_size\n        self.last_positions = None\n\n    def reset(self, current_positions):\n        self.neighbors_table.rebuild_neighbors(current_positions, self.box_size)\n        self.last_positions = current_positions\n        if self.acc_delta is None:\n            self.acc_delta = np.empty_like(current_positions)\n        self.acc_delta.fill(0.0)\n\n    def moved(self, current_positions, check_were_valid=True):\n        delta = periodic_distances(current_positions, self.last_positions, self.box_size)\n        self.last_positions = current_positions\n        self.acc_delta += delta\n        dr_max = (self.acc_delta**2).sum(axis=1).max()**0.5\n        r_acceptable = 0.5 * self.neighbors_table.r_skin\n        if dr_max > r_acceptable:\n            return self.rebuild_neighbors(current_positions, check_were_valid=check_were_valid)\n        return True\n\n    acc_delta = None\n\n    def rebuild_neighbors(self, current_positions, check_were_valid=True):\n        if check_were_valid:\n            old_vital_neighbors = self.find_vital_neighbors(current_positions)\n        self.neighbors_table.rebuild_neighbors(current_positions, self.box_size)\n        if check_were_valid:\n            new_vital_neighbors = self.find_vital_neighbors(current_positions)\n            were_valid = old_vital_neighbors >= new_vital_neighbors\n        self.acc_delta.fill(0.0)\n        if check_were_valid:\n            return were_valid\n\n    def find_vital_neighbors(self, positions):\n        return self.neighbors_table.find_set_of_neighbors_within_distance(self.neighbors_table.r_forcefield_cutoff,\n                                                                          positions, self.box_size)\n\nclass EnergyMinimzer(object):\n\n    def __init__(self, config_init, forcefield, maxiter=100, neighbors_table=None, neighbors_table_skin=1.0):\n        self.config_init = config_init\n        self.forcefield = forcefield\n        self.maxiter = maxiter\n\n        if neighbors_table is None:\n            neighbors_table = NeighborsTable(\n                r_forcefield_cutoff=forcefield.r_cutoff,\n                r_skin=neighbors_table_skin)\n        self.neighbors_table = neighbors_table\n\n        self.forces = np.empty_like(self.config_init.positions)\n        self.neighbors_table_tracker = NeighborsTableTracker(self.neighbors_table, self.config_init.box_size)\n\n    def minimize(self):\n        self.neighbors_table_tracker.reset(self.config_init.positions)\n        [x_final, self.U_min, self.n_func_calls, self.n_grad_calls, self.warnfalgs\n         ] = fmin_cg(self.evaluate_potential,\n                     self.config_init.positions,\n                     fprime=self.evaluate_gradient,\n                     maxiter=self.maxiter,\n                     callback=self.callback,\n                     full_output=True, disp=False)\n        self.config_final = self.config_init.with_new_positions(self.create_positions(x_final))\n        return self.config_final\n\n    def evaluate_potential(self, x):\n        return self.forcefield.evaluate_potential(self.create_positions(x),\n                                                  self.config_init.box_size,\n                                                  self.neighbors_table)\n\n    def evaluate_gradient(self, x):\n        self.forcefield.evaluate_forces(self.forces,\n                                        self.create_positions(x),\n                                        self.config_init.box_size,\n                                        self.neighbors_table)\n        return -self.forces.reshape(3 * self.config_init.N)\n\n    def callback(self, x):\n        self.neighbors_table_tracker.moved(self.create_positions(x))\n\n    def create_positions(self, x):\n        return x.reshape((self.config_init.N, 3)) % self.config_init.box_size\n\n\nclass MDSimulator(object):\n\n    kB = 1.0\n\n    def __init__(self, config, forcefield, mass=1.0, r_skin=1.0):\n        self.config = config\n        self.forcefield = forcefield\n        self.forces = np.empty_like(config.positions)\n        self.mass = mass\n        self.neighbors_table = NeighborsTable(r_forcefield_cutoff=self.forcefield.r_cutoff,\n                                              r_skin=r_skin)\n        self.neighbors_table_tracker = NeighborsTableTracker(self.neighbors_table, self.config.box_size)\n        self.neighbors_table_tracker.reset(self.config.positions)\n\n        self.backup_positions = np.empty_like(self.config.positions)\n        self.backup_last_positions = np.empty_like(self.config.last_positions)\n\n    normalize_positions_rate = 20\n\n    def cycle(self, n=1):\n        for i in xrange(n):\n            if not i%self.normalize_positions_rate:\n                self.normalize_positions()\n\n            self.backup_positions[...] = self.config.positions\n            self.backup_last_positions[...] = self.config.last_positions\n            were_neighbors_valid = self.propagate_attempt()\n            if not were_neighbors_valid:\n                self.config.positions[...] = self.backup_positions\n                self.config.last_positions[...] = self.backup_last_positions\n                were_neighbors_valid = self.propagate_attempt()\n                if not were_neighbors_valid:\n                    raise RuntimeError(\"couldn't create valid neighbor list, increase r_skin or decrease dt\")\n\n    def propagate_attempt(self):\n        self.forcefield.evaluate_forces(self.forces,\n                                        self.config.positions % self.config.box_size,\n                                        self.config.box_size, self.neighbors_table)\n        self.config.propagate(self.forces, self.mass)\n        return self.neighbors_table_tracker.moved(self.config.positions, check_were_valid=True)\n\n    def normalize_positions(self):\n        self.config.normalize_positions()\n        self.neighbors_table_tracker.reset(self.config.positions)\n\n    def rescale_boxsize_rho(self, rho):\n        self.config.rescale_boxsize_rho(rho)\n        self.neighbors_table_tracker.reset(self.config.positions)\n\n    def compute_potential_energy(self):\n        '''Compute the internal potential energy due to the force field\n           interactions. Result are inversely scaled by the number of particles.\n        '''\n        return self.forcefield.evaluate_potential(self.config.positions % self.config.box_size,\n                                                  self.config.box_size, self.neighbors_table)\n\n    def compute_kinetic_energy(self):\n        '''Compute the kinetic energy due to translational veloctiy of particles.\n           Result are inversely scaled by the number of particles.\n        '''\n        return self.config.calculate_kinetic_energy(self.mass)\n\n    def compute_energy(self):\n        '''Compute the total energy (sum kinetic and potential) of the system.\n           Result are inversely scaled by the number of particles.\n        '''\n        return self.compute_potential_energy() + self.compute_kinetic_energy()\n\n    def compute_temperature(self):\n        return self.config.calculate_temperature(self.mass)\n\n    def compute_excess_pressure(self, correct_long_range):\n        '''Compute the pressure due to particle pair interactions.\n           Result are inversely scaled by the number of particles.\n        '''\n        v = 1.0 / 3.0 * self.forcefield.evaluate_virial_sum(\n            self.config.positions % self.config.box_size,\n            self.config.box_size, self.neighbors_table)\n        if correct_long_range:\n            v += self.forcefield.long_range_virial_correction()\n        return (self.kB / self.config.V) * v\n\n    def compute_ideal_pressure(self):\n        '''Compute pressure due to kinetic energy alone.\n           Result are inversely scaled by the number of particles.\n        '''\n        return self.kB * self.compute_temperature() / self.config.V\n\n    def compute_total_pressure(self, correct_long_range=True):\n        '''Compute the total (sum kinetic and potential) pressure.\n           Result are inversely scaled by the number of particles.\n        '''\n        return self.compute_excess_pressure(correct_long_range) + self.compute_ideal_pressure()\n\n    def compute_virial(self, correct_long_range=True):\n        P = self.compute_total_pressure(correct_long_range)\n        return P * self.config.V / (self.kB * self.compute_temperature())\n\n    def compute_excess_virial(self, correct_long_range):\n        v = ((3 * self.kB * self.compute_temperature())**-1 *\n             self.forcefield.evaluate_virial_sum(self.config.positions % self.config.box_size,\n                                                 self.config.box_size, self.neighbors_table))\n        if correct_long_range:\n            v += self.forcefield.long_range_virial_correction()\n        return v\n\n    # Old (deprecated) methods\n    def evaluate_potential(self):\n        return self.compute_potential_energy()\n\n    def evaluate_hamiltonian(self):\n        return self.compute_energy()\n\n    def minimize(self, maxiter=10):\n        minimizer = EnergyMinimzer(self.config, self.forcefield, maxiter=8,\n                                   neighbors_table=self.neighbors_table)\n        self.config = minimizer.minimize()\n        return minimizer.U_min\n\n    def minimize_until(self, cutoff, verbose=True):\n        while True:\n            U_min = self.minimize(100)\n            if verbose:\n                print '%.4e' % U_min\n            if U_min < cutoff:\n                return U_min\n\n    def get_config(self):\n        config = self.config.copy()\n        config.normalize_positions()\n        return config\n\n\ndef cached_property(name_or_func, cache_name=None):\n    '''Wrapper to create a cached readonly property for a class.\n    '''\n    if isinstance(name_or_func, basestring):\n        return lambda func: cached_property(func, cache_name=name_or_func)\n\n    func = name_or_func\n    assert callable(func)\n\n    if cache_name is None:\n        cache_name = '_' + func.func_name\n    assert isinstance(cache_name, basestring)\n\n    @property\n    @wraps(func)\n    def wrapper(self):\n        try:\n            return getattr(self, cache_name)\n        except AttributeError:\n            value = func(self)\n            setattr(self, cache_name, value)\n            return value\n    return wrapper\n\n\nclass StaticPairCorrelation(object):\n    '''Describes the static correlation of isotropic particle pairs.\n          e.g. The numerical analogs of the standard g(r) and h(r) functions.\n\n       The underlying data is a histogram of pair separation distances at\n       fixed spacing dr (i.e. the i-th bin contains the total number of\n       pair observed at distances of i*dr <= r < (i+1)*dr.\n\n       Additionally, the separation distances can be shifted by an r_offset.\n       This is useful in avoiding the avoid the leading zeros that correspond\n       to unphysically close pair distances.\n    '''\n\n    def __init__(self, pair_distance_histogram, dr, r_offset=0.0):\n        pair_distance_histogram = np.asarray(pair_distance_histogram)\n        assert pair_distance_histogram.ndim == 1\n        assert pair_distance_histogram.size > 0\n        self.pair_distance_histogram = pair_distance_histogram\n        self.dr = dr\n        self.r_offset = r_offset\n\n    @cached_property\n    def r_lower(self):\n        '''Radial distance corresponding to correlation distances at\n           the lower bound of each bin.\n        '''\n        return self.r_offset + self.dr * np.arange(self.pair_distance_histogram.size)\n\n    @cached_property\n    def r_mid(self):\n        '''Radial distance corresponding to correlation distances at\n           center of each bin.\n        '''\n        return self.r_lower + 0.5 * self.dr\n\n    @property\n    def r(self):\n        return self.r_mid\n\n    @cached_property\n    def g(self):\n        '''Reducued density pair correlations\n        '''\n        N = self.pair_distance_histogram.sum()\n        if not N:\n            return None\n\n        r_max = self.pair_distance_histogram.size * self.dr\n        V = 4.0 / 3.0 * np.pi * r_max**3\n        rho = N / V\n        v = 4.0 / 3.0 * np.pi * ((self.r_lower + self.dr)**3 - self.r_lower**3)\n        rhos =  self.pair_distance_histogram / v\n        return rhos / rho\n\n    @cached_property\n    def h(self):\n        '''Shifted reducued density pair correlations\n        '''\n        if self.g is None:\n            return None\n        return self.g - 1.0\n\n\nclass StaticPairCorrelationCalculator(BasePairCorrelationFunctionCalculator):\n    '''Calculate the PairCorrelationData from configurations (Config) of\n       particles. The calculation is performed by accumulating a histogram\n       of pair separation distances one configuration at a time. The\n       intermediate state of calculation can be saved by pickeling the\n       calculator object.\n    '''\n\n    def accumulate_config(self, config):\n        self.accumulate_positions(config.positions, config.box_size)\n\n    def get_accumulated(self):\n        return StaticPairCorrelation(self.bins.copy(), self.dr, self.r_min)\n\n\nclass StaticPairCorrelationIntegrator(object):\n    '''Calculate thermodynamic properties of an isotropic particle system\n       by integrating over the sampled pair correlation (StaticPairCorrelation object)\n       for the system. Uses the potential and gradient of the force field associated\n       with the system.\n    '''\n\n    def __init__(self, pair_correlation, forcefield, rho, beta):\n        self.pair_correlation = pair_correlation\n        self.forcefield = forcefield\n        self.rho = rho\n        self.beta = beta\n\n    def integrate_g_product_over_space_ex(self, func, mask=Ellipsis):\n        '''Numerically integrate\n            \\int g(r) * r**2 * func(r)\n\n           The mask argument allows the specification of which\n           elements of data arrays to include (i.e. allows the\n           exclusion of zero elements)\n        '''\n        r = self.pair_correlation.r[mask]\n        g = self.pair_correlation.g[mask]\n        return np.trapz(r**2 * g * func(r), r)\n\n    @cached_property\n    def where_g_nonzero(self):\n        return self.pair_correlation.g != 0.0\n\n    @cached_property\n    def where_g_nonzero_and_in_cutoff(self):\n        return (self.pair_correlation.g != 0.0) & (self.pair_correlation.r <= self.forcefield.r_cutoff)\n\n    def integrate_g_product_over_space(self, func):\n        return self.integrate_g_product_over_space_ex(func, self.where_g_nonzero)\n\n    def integrate_g_product_over_space_in_cutoff(self, func):\n        return self.integrate_g_product_over_space_ex(func, self.where_g_nonzero_and_in_cutoff)\n\n    def calculate_excess_internal_energy(self):\n        return (2.0 * np.pi * self.rho *\n                self.integrate_g_product_over_space_in_cutoff(self.forcefield.evaluate_potential_function))\n\n    def calculate_virial(self, correct_long_range=True):\n        v = 1.0 - 2.0 / 3.0 * np.pi * self.beta * self.rho * (\n            self.integrate_g_product_over_space_in_cutoff(\n            lambda r: r * -self.forcefield.evaluate_scalar_force_function(r)))\n        if correct_long_range:\n            v += self.forcefield.long_range_virial_correction(self.pair_correlation.r.max())\n        return v\n\n\nclass BaseTimeCorelationCalculator(object):\n    '''Base class for Time Correlation Function (TCF) computations\n    '''\n\n    def __init__(self, window_size, N_particles, *args, **kwds):\n        assert 'analyze_rate' in kwds\n        self.analyze_rate = kwds.pop('analyze_rate')\n        super(BaseTimeCorelationCalculator, self).__init__(window_size, N_particles, *args, **kwds)\n\n    @classmethod\n    def create(cls, window_size, N_particles, analyze_rate=1):\n        # ensure analyze_rate is passed as a keyword\n        return cls(window_size, N_particles, analyze_rate=analyze_rate)\n\n    def compute_time(self):\n        return self.analyze_rate * np.arange(self.window_size)\n\n\nclass MeanSquareDisplacementCalculator(BaseTimeCorelationCalculator, BaseMeanSquareDisplacementCalculator):\n    '''Compute the mean square displacment TCF; i.e. th self-positional TCF\n    '''\n\n    def analyze_config(self, config):\n        self.analyze_positions(config.positions, config.box_size)\n\n    def compute_msd(self):\n        n_acc = self.calculate_n_accumulates()\n        if not n_acc:\n            return None\n\n        return self.acc_msd_data / float(n_acc * self.N_particles)\n\n    def __reduce__(self):\n        return (create_msdc,\n                (self.window_size, self.N_particles,\n                 self.analyze_rate,\n                 self.n_positions_seen,\n                 self.displacement_window, self.last_positions,\n                 self.acc_msd_data))\n\ndef create_msdc(window_size, N_particles, analyze_rate, n_positions_seen,\n                displacement_window, last_positions, acc_msd_data):\n    return MeanSquareDisplacementCalculator(window_size, N_particles,\n                                            analyze_rate=analyze_rate,\n                                            n_positions_seen=n_positions_seen,\n                                            displacement_window=displacement_window,\n                                            last_positions=last_positions,\n                                            acc_msd_data=acc_msd_data)\n\n\nclass VelocityAutocorrelationCalculator(BaseTimeCorelationCalculator, BaseVelocityAutocorrelationCalculator):\n    '''Compute the velocity autocorrelation TCF (VACF); i.e. the self-velocity TCF\n    '''\n\n    def analyze_config(self, config):\n        self.analyze_velocities(config.calculate_velocities())\n\n    def compute_vacf(self):\n        n_acc = self.calculate_n_accumulates()\n        if not n_acc:\n            return None\n\n        return self.acc_correlations / float(n_acc * self.N_particles)\n\n    def __reduce__(self):\n        return (create_vacfc,\n                (self.window_size, self.N_particles,\n                 self.analyze_rate,\n                 self.n_velocities_seen,\n                 self.velocities_windows, self.acc_correlations))\n\ndef create_vacfc(window_size, N_particles, analyze_rate, n_velocities_seen,\n                 velocities_windows, acc_correlations):\n    return VelocityAutocorrelationCalculator(window_size, N_particles,\n                                             analyze_rate=analyze_rate,\n                                             n_velocities_seen=n_velocities_seen,\n                                             velocities_windows=velocities_windows,\n                                             acc_correlations=acc_correlations)\n\n\n\n", "meta": {"hexsha": "2a50f7a0f14fbc5f0bf09995ca2ab33e2e90fbeb", "size": 25158, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyljfluid/components.py", "max_stars_repo_name": "matthagy/PyLJFluid", "max_stars_repo_head_hexsha": "386925e76283e5340e2cb55599e2a799e9606152", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-04-19T12:35:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-06T04:52:31.000Z", "max_issues_repo_path": "pyljfluid/components.py", "max_issues_repo_name": "matthagy/PyLJFluid", "max_issues_repo_head_hexsha": "386925e76283e5340e2cb55599e2a799e9606152", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-04-18T14:52:53.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-18T14:52:53.000Z", "max_forks_repo_path": "pyljfluid/components.py", "max_forks_repo_name": "matthagy/PyLJFluid", "max_forks_repo_head_hexsha": "386925e76283e5340e2cb55599e2a799e9606152", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-01T08:41:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T19:17:31.000Z", "avg_line_length": 39.6188976378, "max_line_length": 115, "alphanum_fraction": 0.6527943398, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.18404826133604635}}
{"text": "# Copyright 2020 The FedLearner Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# coding: utf-8\n\nimport os\nimport math\nimport queue\nimport logging\nimport multiprocessing as mp\nimport numpy as np\nfrom google.protobuf import text_format\n\nfrom fedlearner.model.tree.loss import LogisticLoss\nfrom fedlearner.model.crypto import paillier, fixed_point_number\nfrom fedlearner.common import tree_model_pb2 as tree_pb2\n\n\nBST_TYPE = np.float32\nPRECISION = 1e38\nEXPONENT = math.floor(\n    math.log(PRECISION, fixed_point_number.FixedPointNumber.BASE))\nKEY_NBITS = 1024\nCIPHER_NBYTES = (KEY_NBITS * 2)//8\n\n\ndef _send_public_key(bridge, public_key):\n    msg = tree_pb2.EncryptedNumbers()\n    msg.ciphertext.append(public_key.n.to_bytes(KEY_NBITS//8, 'little'))\n    bridge.send_proto(bridge.current_iter_id, 'public_key', msg)\n\ndef _receive_public_key(bridge):\n    msg = tree_pb2.EncryptedNumbers()\n    bridge.receive_proto(bridge.current_iter_id, 'public_key').Unpack(msg)\n    return paillier.PaillierPublicKey(\n        int.from_bytes(msg.ciphertext[0], 'little'))\n\ndef _encode_encrypted_numbers(numbers):\n    return [\n        i.ciphertext(False).to_bytes(CIPHER_NBYTES, 'little') \\\n        for i in numbers]\n\ndef _encrypt_numbers(public_key, numbers):\n    return _encode_encrypted_numbers(\n        [public_key.encrypt(i, PRECISION) for i in numbers])\n\ndef _decrypt_number(private_key, numbers):\n    return [private_key.decrypt(i) for i in numbers]\n\ndef _from_ciphertext(public_key, ciphertext):\n    return [\n        paillier.PaillierEncryptedNumber(\n            public_key, int.from_bytes(i, 'little'), EXPONENT)\n        for i in ciphertext]\n\ndef _encrypt_and_send_numbers(bridge, name, public_key, numbers):\n    msg = tree_pb2.EncryptedNumbers()\n    msg.ciphertext.extend(_encrypt_numbers(public_key, numbers))\n    bridge.send_proto(bridge.current_iter_id, name, msg)\n\ndef _receive_encrypted_numbers(bridge, name, public_key):\n    msg = tree_pb2.EncryptedNumbers()\n    bridge.receive_proto(bridge.current_iter_id, name).Unpack(msg)\n    return _from_ciphertext(public_key, msg.ciphertext)\n\n\nclass BinnedFeatures(object):\n    def __init__(self, features, max_bins):\n        super(BinnedFeatures, self).__init__()\n\n        self._max_bins = max_bins\n        self.features = features\n        self.binned, self.thresholds = self._bin_features(features)\n\n    def _bin_features(self, features):\n        thresholds = []\n        binned = np.zeros_like(features, dtype=np.uint8, order='F')\n        for i in range(features.shape[1]):\n            x = features[:, i]\n            missing_mask = np.isnan(x)\n            nonmissing_x = x\n            if missing_mask.any():\n                nonmissing_x = x[~missing_mask]\n            nonmissing_x = np.ascontiguousarray(\n                nonmissing_x, dtype=BST_TYPE)\n            unique_x = np.unique(nonmissing_x)\n            if len(unique_x) <= self._max_bins:\n                threshold = (unique_x[:-1] + unique_x[1:]) * 0.5\n            else:\n                percentiles = np.linspace(0, 100, num=self._max_bins + 1)\n                percentiles = percentiles[1:-1]\n                threshold = np.percentile(\n                    nonmissing_x, percentiles, interpolation='midpoint')\n                assert threshold.size == self._max_bins - 1\n            thresholds.append(threshold)\n\n            binned[:, i] = np.searchsorted(threshold, x, side='right')\n            binned[missing_mask, i] = threshold.size + 1\n\n        return binned, thresholds\n\n\ndef _compute_histogram_helper(args):\n    values, binned_features, thresholds, zero = args\n    hists = []\n    for i, threshold in enumerate(thresholds):\n        num_bins = threshold.size + 2\n        hist = np.asarray([zero for _ in range(num_bins)])\n        np.add.at(hist, binned_features[:, i], values)\n        hists.append(hist)\n\n    return hists\n\n\nclass HistogramBuilder(object):\n    def __init__(self, binned_features, dtype=BST_TYPE,\n                 num_parallel=1, pool=None):\n        self._bins = binned_features\n        self._dtype = dtype\n        self._zero = dtype(0.0)\n        self._num_parallel = num_parallel\n        self._pool = pool\n        if self._num_parallel > 1:\n            assert pool is not None\n            self._job_size = \\\n                (len(self._bins.binned) + num_parallel - 1)//num_parallel\n\n    def compute_histogram(self, values, sample_ids):\n        if not self._pool:\n            return _compute_histogram_helper(\n                (values[sample_ids], self._bins.binned[sample_ids],\n                 self._bins.thresholds, self._zero))\n\n        args = [\n            (values[sample_ids],\n             self._bins.binned[\n                 sample_ids, self._job_size*i:self._job_size*(i+1)],\n             self._bins.thresholds[self._job_size*i:self._job_size*(i+1)],\n             self._zero)\n            for i in range(self._num_parallel)\n        ]\n\n        rets = self._pool.map(_compute_histogram_helper, args)\n        return sum(rets, [])\n\n\nclass GrowerNode(object):\n    def __init__(self, node_id):\n        self.node_id = node_id\n        self.feature_id = None\n        self.threshold = None\n        self.is_owner = None\n        self.owner_id = None\n        self.weight = None\n\n        self.parent = None\n        self.left_child = None\n        self.right_child = None\n\n        self.sample_ids = None\n        self.grad_hists = None\n        self.hess_hists = None\n\n    def to_proto(self):\n        return tree_pb2.RegressionTreeNodeProto(\n            node_id=self.node_id,\n            left_child=self.left_child,\n            right_child=self.right_child,\n            parent=self.parent,\n            is_owner=self.is_owner,\n            owner_id=self.owner_id,\n            feature_id=self.feature_id,\n            threshold=self.threshold,\n            weight=self.weight)\n\n\nclass BaseGrower(object):\n    def __init__(self, binned, grad, hess, grow_policy='depthwise',\n                 max_leaves=None, max_depth=None, learning_rate=0.3,\n                 l2_regularization=1.0, dtype=BST_TYPE, num_parallel=1):\n        self._binned = binned\n        self._grad = grad\n        self._hess = hess\n\n        self._grow_policy = grow_policy\n        if grow_policy == 'depthwise':\n            self._split_candidates = queue.Queue()\n            assert max_depth is not None, \\\n                \"max_depth must be set when grow_policy is depthwise\"\n            self._max_depth = max_depth\n            self._max_leaves = 2**max_depth\n        else:\n            self._split_candidates = queue.PriorityQueue()\n            assert max_leaves is not None, \\\n                \"max_leaves must be set when grow_policy is lossguided\"\n            self._max_leaves = max_leaves\n            self._max_depth = max_depth if max_depth is not None else 2**31\n\n        self._learning_rate = learning_rate\n        self._l2_regularization = l2_regularization\n\n        self._num_parallel = num_parallel\n        self._pool = None\n        if self._num_parallel > 1:\n            self._pool = mp.Pool(num_parallel)\n        self._hist_builder = HistogramBuilder(\n            binned, dtype, num_parallel, self._pool)\n\n        self._nodes = [GrowerNode(0)]\n        self._nodes[0].sample_ids = list(range(binned.features.shape[0]))\n        self._num_leaves = 1\n\n    def _compute_histogram(self, node):\n        node.grad_hists = self._hist_builder.compute_histogram(\n            self._grad, node.sample_ids)\n        node.hess_hists = self._hist_builder.compute_histogram(\n            self._hess, node.sample_ids)\n\n    def _compute_histogram_from_sibling(self, node, sibling):\n        parent = self._nodes[node.parent]\n        node.grad_hists = [\n            p - l for p, l in zip(parent.grad_hists, sibling.grad_hists)]\n        node.hess_hists = [\n            p - l for p, l in zip(parent.hess_hists, sibling.hess_hists)]\n\n    def _find_split_and_push(self, node):\n        max_gain = -1\n        max_fid = None\n        split_point = None\n        left_weight = None\n        right_weight = None\n        lam = self._l2_regularization\n        for fid, (grad_hist, hess_hist) in \\\n                enumerate(zip(node.grad_hists, node.hess_hists)):\n            sum_g = sum(grad_hist[:-1])\n            sum_h = sum(hess_hist[:-1])\n            left_g = 0.0\n            left_h = 0.0\n            for i in range(len(grad_hist[:-1]) - 1):\n                left_g += grad_hist[i]\n                left_h += hess_hist[i]\n                right_g = sum_g - left_g\n                right_h = sum_h - left_h\n                gain = left_g*left_g/(left_h + lam) + \\\n                    right_g*right_g/(right_h + lam) - \\\n                    sum_g*sum_g/(sum_h + lam)\n                if gain > max_gain:\n                    max_gain = gain\n                    max_fid = fid\n                    split_point = i\n                    left_weight = - left_g/(left_h + lam)\n                    right_weight = - right_g/(right_h + lam)\n\n        split_info = tree_pb2.SplitInfo(\n            node_id=node.node_id, gain=max_gain, feature_id=max_fid,\n            split_point=split_point,\n            left_weight=left_weight * self._learning_rate,\n            right_weight=right_weight * self._learning_rate)\n\n        self._split_candidates.put((-max_gain, split_info))\n\n        return max_gain, split_info\n\n    def _add_node(self, parent_id):\n        node_id = len(self._nodes)\n        node = GrowerNode(node_id)\n        node.parent = parent_id\n        self._nodes.append(node)\n        return node_id\n\n    def _set_node_partition(self, node, split_info):\n        node.is_owner = True\n        node.feature_id = split_info.feature_id\n        node.threshold = self._binned.thresholds[\n            split_info.feature_id][split_info.split_point]\n        left_child = self._nodes[node.left_child]\n        left_child.sample_ids = [\n            i for i in node.sample_ids if \\\n                self._binned.features[i, node.feature_id] < node.threshold]\n        right_child = self._nodes[node.right_child]\n        right_child.sample_ids = [\n            i for i in node.sample_ids if \\\n                self._binned.features[i, node.feature_id] >= node.threshold]\n\n    def _split_next(self):\n        _, split_info = self._split_candidates.get()\n        node = self._nodes[split_info.node_id]\n\n        node.left_child = self._add_node(node.node_id)\n        left_child = self._nodes[node.left_child]\n        left_child.weight = split_info.left_weight\n\n        node.right_child = self._add_node(node.node_id)\n        right_child = self._nodes[node.right_child]\n        right_child.weight = split_info.right_weight\n\n        self._num_leaves += 1\n\n        self._set_node_partition(node, split_info)\n\n        return left_child, right_child, split_info\n\n    def _log_split(self, left_child, right_child, split_info):\n        parent = self._nodes[split_info.node_id]\n\n        logging.info(\n            \"Split node %d at feature %d for gain=%f. \" \\\n            \"Left(w=%f, nsamples=%d), Right(w=%f, nsamples=%d)\",\n            split_info.node_id, split_info.feature_id, split_info.gain,\n            left_child.weight, len(left_child.sample_ids),\n            right_child.weight, len(right_child.sample_ids))\n        assert len(left_child.sample_ids) + len(right_child.sample_ids) \\\n            == len(parent.sample_ids)\n\n    def to_proto(self):\n        proto = tree_pb2.RegressionTreeProto()\n        for node in self._nodes:\n            proto.nodes.append(node.to_proto())\n        return proto\n\n    def get_prediction(self):\n        prediction = np.zeros(self._binned.features.shape[0], dtype=BST_TYPE)\n        for node in self._nodes:\n            if node.left_child is not None:\n                continue\n            prediction[node.sample_ids] = node.weight\n        return prediction\n\n    def grow(self):\n        self._compute_histogram(self._nodes[0])\n        self._find_split_and_push(self._nodes[0])\n\n        while self._num_leaves < self._max_leaves:\n            left_child, right_child, split_info = self._split_next()\n            self._log_split(left_child, right_child, split_info)\n            self._compute_histogram(left_child)\n            self._find_split_and_push(left_child)\n            self._compute_histogram_from_sibling(right_child, left_child)\n            self._find_split_and_push(right_child)\n\ndef _decrypt_histogram_helper(args):\n    public_key, private_key, hists = args\n    rets = []\n    for hist in hists:\n        hist = _from_ciphertext(public_key, hist.ciphertext)\n        rets.append(np.asarray(_decrypt_number(private_key, hist)))\n    return rets\n\nclass LeaderGrower(BaseGrower):\n    def __init__(self, bridge, public_key, private_key,\n                 binned, grad, hess, **kwargs):\n        super(LeaderGrower, self).__init__(\n            binned, grad, hess, dtype=np.float32, **kwargs)\n        self._bridge = bridge\n        self._public_key = public_key\n        self._private_key = private_key\n\n    def _receive_and_decrypt_histogram(self, name):\n        msg = tree_pb2.Histograms()\n        self._bridge.receive_proto(\n            self._bridge.current_iter_id, name).Unpack(msg)\n        if not self._pool:\n            return _decrypt_histogram_helper(\n                self._public_key, self._private_key, msg.hists)\n\n        job_size = (len(msg.hists) + self._num_parallel - 1)//self._num_parallel\n        args = [\n            (self._public_key, self._private_key,\n             msg.hists[i*job_size:(i+1)*job_size])\n            for i in range(self._num_parallel)\n        ]\n        hists = self._pool.map(_decrypt_histogram_helper, args)\n        return sum(hists, [])\n\n    def _compute_histogram(self, node):\n        self._bridge.start(self._bridge.new_iter_id())\n        grad_hists = self._hist_builder.compute_histogram(\n            self._grad, node.sample_ids)\n        hess_hists = self._hist_builder.compute_histogram(\n            self._hess, node.sample_ids)\n        follower_grad_hists = self._receive_and_decrypt_histogram('grad_hists')\n        follower_hess_hists = self._receive_and_decrypt_histogram('hess_hists')\n        node.grad_hists = grad_hists + follower_grad_hists\n        node.hess_hists = hess_hists + follower_hess_hists\n        self._bridge.commit()\n\n    def _split_next(self):\n        self._bridge.start(self._bridge.new_iter_id())\n\n        _, split_info = self._split_candidates.get()\n        node = self._nodes[split_info.node_id]\n\n        node.left_child = self._add_node(node.node_id)\n        left_child = self._nodes[node.left_child]\n        left_child.weight = split_info.left_weight\n\n        node.right_child = self._add_node(node.node_id)\n        right_child = self._nodes[node.right_child]\n        right_child.weight = split_info.right_weight\n\n        self._num_leaves += 1\n\n        if split_info.feature_id < self._binned.features.shape[1]:\n            self._set_node_partition(node, split_info)\n            self._bridge.send_proto(\n                self._bridge.current_iter_id, 'split_info',\n                tree_pb2.SplitInfo(\n                    node_id=split_info.node_id, feature_id=-1,\n                    left_samples=left_child.sample_ids,\n                    right_samples=right_child.sample_ids))\n        else:\n            node.is_owner = False\n            fid = split_info.feature_id - self._binned.features.shape[1]\n            self._bridge.send_proto(\n                self._bridge.current_iter_id, 'split_info',\n                tree_pb2.SplitInfo(\n                    node_id=split_info.node_id, feature_id=fid,\n                    split_point=split_info.split_point))\n\n            follower_split_info = tree_pb2.SplitInfo()\n            self._bridge.receive_proto(\n                self._bridge.current_iter_id, 'follower_split_info') \\\n                .Unpack(follower_split_info)\n            left_child.sample_ids = list(follower_split_info.left_samples)\n            right_child.sample_ids = list(follower_split_info.right_samples)\n\n        self._bridge.commit()\n        return left_child, right_child, split_info\n\n\nclass FollowerGrower(BaseGrower):\n    def __init__(self, bridge, public_key, binned, grad, hess, **kwargs):\n        dtype = lambda x: public_key.encrypt(x, PRECISION)\n        super(FollowerGrower, self).__init__(\n            binned, grad, hess, dtype=dtype, **kwargs)\n        self._bridge = bridge\n        self._public_key = public_key\n\n    def _compute_histogram_from_sibling(self, node, sibling):\n        pass\n\n    def _find_split_and_push(self, node):\n        pass\n\n    def _send_histograms(self, name, hists):\n        msg = tree_pb2.Histograms()\n        for hist in hists:\n            ciphertext = _encode_encrypted_numbers(hist)\n            msg.hists.append(\n                tree_pb2.EncryptedNumbers(ciphertext=ciphertext))\n        self._bridge.send_proto(self._bridge.current_iter_id, name, msg)\n\n    def _compute_histogram(self, node):\n        self._bridge.start(self._bridge.new_iter_id())\n        grad_hists = self._hist_builder.compute_histogram(\n            self._grad, node.sample_ids)\n        hess_hists = self._hist_builder.compute_histogram(\n            self._hess, node.sample_ids)\n        self._send_histograms('grad_hists', grad_hists)\n        self._send_histograms('hess_hists', hess_hists)\n        self._bridge.commit()\n\n    def _split_next(self):\n        self._bridge.start(self._bridge.new_iter_id())\n\n        split_info = tree_pb2.SplitInfo()\n        self._bridge.receive_proto(\n            self._bridge.current_iter_id, 'split_info') \\\n            .Unpack(split_info)\n\n        node = self._nodes[split_info.node_id]\n\n        node.left_child = self._add_node(node.node_id)\n        left_child = self._nodes[node.left_child]\n        left_child.weight = float('nan')\n\n        node.right_child = self._add_node(node.node_id)\n        right_child = self._nodes[node.right_child]\n        right_child.weight = float('nan')\n\n        self._num_leaves += 1\n\n        if split_info.feature_id >= 0:\n            self._set_node_partition(node, split_info)\n            self._bridge.send_proto(\n                self._bridge.current_iter_id, 'follower_split_info',\n                tree_pb2.SplitInfo(\n                    left_samples=left_child.sample_ids,\n                    right_samples=right_child.sample_ids))\n        else:\n            node.is_owner = False\n            left_child.sample_ids = list(split_info.left_samples)\n            right_child.sample_ids = list(split_info.right_samples)\n\n        self._bridge.commit()\n        return left_child, right_child, split_info\n\n\nclass BoostingTreeEnsamble(object):\n    def __init__(self, bridge, learning_rate=0.3, max_iters=50, max_depth=6,\n                 max_leaves=None, l2_regularization=1.0, max_bins=33,\n                 grow_policy='depthwise', num_parallel=1):\n        self._learning_rate = learning_rate\n        self._max_iters = max_iters\n        self._max_depth = max_depth\n        self._max_leaves = max_leaves\n        self._l2_regularization = l2_regularization\n        self._grow_policy = grow_policy\n        self._num_parallel = num_parallel\n\n        assert max_bins < 255, \"Only support max_bins < 255\"\n        self._max_bins = max_bins\n\n        self._loss = LogisticLoss()\n        self._trees = []\n\n        self._bridge = bridge\n        if bridge is not None:\n            self._role = self._bridge.role\n            self._bridge.connect()\n            self._make_key_pair()\n\n    def _make_key_pair(self):\n        # make key pair\n        self._bridge.start(self._bridge.new_iter_id())\n        if self._role == 'leader':\n            self._public_key, self._private_key = \\\n                paillier.PaillierKeypair.generate_keypair(KEY_NBITS)\n            _send_public_key(self._bridge, self._public_key)\n        else:\n            self._public_key = _receive_public_key(self._bridge)\n            self._private_key = None\n        self._bridge.commit()\n\n    def save_model(self, path):\n        with open(path, 'w') as fout:\n            model = tree_pb2.BoostingTreeEnsambleProto()\n            model.trees.extend(self._trees)\n            fout.write(text_format.MessageToString(model))\n\n    def load_saved_model(self, path):\n        with open(path, 'r') as fin:\n            model = tree_pb2.BoostingTreeEnsambleProto()\n            text_format.Parse(fin.read(), model)\n            self._trees = list(model.trees)\n\n    def batch_predict(self, features, raw_score=False):\n        if self._bridge is None:\n            return self._batch_predict_local(features, raw_score)\n        if self._bridge.role == 'leader':\n            return self._batch_predict_leader(features, raw_score)\n        return self._batch_predict_follower(features, raw_score)\n\n    def _batch_predict_local(self, features, raw_score):\n        N = features.shape[0]\n        raw_prediction = []\n        for i in range(features.shape[0]):\n            score = 0.0\n            for tree in self._trees:\n                node = tree.nodes[0]\n                while node.left_child != 0:\n                    assert node.is_owner\n                    if features[i, node.feature_id] < node.threshold:\n                        node = tree.nodes[node.left_child]\n                    else:\n                        node = tree.nodes[node.right_child]\n                score += node.weight\n            raw_prediction.append(score)\n        raw_prediction = np.asarray(raw_prediction)\n        if raw_score:\n            return raw_prediction\n        return self._loss.predict(raw_prediction)\n\n    def _batch_predict_leader(self, features, raw_score):\n        N = features.shape[0]\n        raw_prediction = np.zeros(N, dtype=BST_TYPE)\n        for tree in self._trees:\n            assignment = np.zeros(N, dtype=np.int32)\n            finish_count = 0\n            while finish_count != N:\n                self._bridge.start(self._bridge.new_iter_id())\n                finish_count = 0\n                for i in range(N):\n                    node = tree.nodes[assignment[i]]\n                    if node.left_child == 0:\n                        finish_count += 1\n                        continue\n                    if node.is_owner:\n                        if features[i, node.feature_id] < node.threshold:\n                            assignment[i] = node.left_child\n                        else:\n                            assignment[i] = node.right_child\n                    else:\n                        assignment[i] = -1\n\n                self._bridge.send(\n                    self._bridge.current_iter_id, 'leader_assignment',\n                    assignment)\n                follower_assignment = self._bridge.receive(\n                    self._bridge.current_iter_id, 'follower_assignment')\n                assignment = np.maximum(assignment, follower_assignment)\n                self._bridge.commit()\n            for i in range(N):\n                raw_prediction[i] += tree.nodes[assignment[i]].weight\n\n        if raw_score:\n            return raw_prediction\n        return self._loss.predict(raw_prediction)\n\n    def _batch_predict_follower(self, features, raw_score):\n        N = features.shape[0]\n        for tree in self._trees:\n            assignment = np.zeros(N, dtype=np.int32)\n            finish_count = 0\n            while finish_count != N:\n                self._bridge.start(self._bridge.new_iter_id())\n                finish_count = 0\n                for i in range(N):\n                    node = tree.nodes[assignment[i]]\n                    if node.left_child == 0:\n                        finish_count += 1\n                        continue\n                    if node.is_owner:\n                        if features[i, node.feature_id] < node.threshold:\n                            assignment[i] = node.left_child\n                        else:\n                            assignment[i] = node.right_child\n                    else:\n                        assignment[i] = -1\n\n                self._bridge.send(\n                    self._bridge.current_iter_id, 'follower_assignment',\n                    assignment)\n                leader_assignment = self._bridge.receive(\n                    self._bridge.current_iter_id, 'leader_assignment')\n                assignment = np.maximum(assignment, leader_assignment)\n                self._bridge.commit()\n\n\n    def fit(self, features, labels=None, checkpoint_path=None):\n        num_examples = features.shape[0]\n\n        # sort feature columns\n        binned = BinnedFeatures(features, self._max_bins)\n\n        # initial f(x)\n        if len(self._trees) > 0:\n            sum_prediction = self.batch_predict(features)\n        else:\n            sum_prediction = np.zeros(num_examples, dtype=BST_TYPE)\n\n        # start iterations\n        while len(self._trees) < self._max_iters:\n            if self._bridge is None:\n                tree, raw_prediction = self._fit_one_round_local(\n                    sum_prediction, binned, labels)\n                sum_prediction += raw_prediction\n            elif self._bridge.role == 'leader':\n                tree, raw_prediction = self._fit_one_round_leader(\n                    sum_prediction, binned, labels)\n                sum_prediction += raw_prediction\n            else:\n                tree = self._fit_one_round_follower(binned)\n\n            self._trees.append(tree)\n\n            if checkpoint_path is not None:\n                filename = os.path.join(\n                    checkpoint_path, 'checkpoint-%04d.proto')\n                self.save_model(filename)\n\n    def _fit_one_round_local(self, sum_fx, binned, labels):\n        # compute grad and hess\n        pred = self._loss.predict(sum_fx)\n        grad = self._loss.gradient(sum_fx, pred, labels)\n        hess = self._loss.hessian(sum_fx, pred, labels)\n        logging.info(\n            'Leader starting iteration %d. Metrics are %s',\n            len(self._trees), self._loss.metrics(pred, labels))\n\n        grower = BaseGrower(\n            binned, grad, hess,\n            learning_rate=self._learning_rate,\n            max_depth=self._max_depth,\n            max_leaves=self._max_leaves,\n            l2_regularization=self._l2_regularization,\n            grow_policy=self._grow_policy,\n            num_parallel=self._num_parallel)\n        grower.grow()\n\n        return grower.to_proto(), grower.get_prediction()\n\n    def _fit_one_round_leader(self, sum_fx, binned, labels):\n        # compute grad and hess\n        self._bridge.start(self._bridge.new_iter_id())\n        pred = self._loss.predict(sum_fx)\n        grad = self._loss.gradient(sum_fx, pred, labels)\n        hess = self._loss.hessian(sum_fx, pred, labels)\n        print('metrics: %s'%self._loss.metrics(pred, labels))\n        _encrypt_and_send_numbers(\n            self._bridge, 'grad', self._public_key, grad)\n        _encrypt_and_send_numbers(\n            self._bridge, 'hess', self._public_key, hess)\n        self._bridge.commit()\n\n        grower = LeaderGrower(\n            self._bridge, self._public_key, self._private_key,\n            binned, grad, hess,\n            learning_rate=self._learning_rate,\n            max_depth=self._max_depth,\n            max_leaves=self._max_leaves,\n            l2_regularization=self._l2_regularization,\n            grow_policy=self._grow_policy,\n            num_parallel=self._num_parallel)\n        grower.grow()\n\n        return grower.to_proto(), grower.get_prediction()\n\n\n    def _fit_one_round_follower(self, binned):\n        # compute grad and hess\n        self._bridge.start(self._bridge.new_iter_id())\n        grad = np.asarray(_receive_encrypted_numbers(\n            self._bridge, 'grad', self._public_key))\n        hess = np.asarray(_receive_encrypted_numbers(\n            self._bridge, 'hess', self._public_key))\n        self._bridge.commit()\n        logging.info(\n            'Follower starting iteration %d.',\n            len(self._trees))\n\n        grower = FollowerGrower(\n            self._bridge, self._public_key,\n            binned, grad, hess,\n            learning_rate=self._learning_rate,\n            max_depth=self._max_depth,\n            max_leaves=self._max_leaves,\n            l2_regularization=self._l2_regularization,\n            grow_policy=self._grow_policy,\n            num_parallel=self._num_parallel)\n        grower.grow()\n\n        return grower.to_proto()\n", "meta": {"hexsha": "0a2bf9e67276ae85cf35f9b9813faa58a79e4cde", "size": 28582, "ext": "py", "lang": "Python", "max_stars_repo_path": "fedlearner/model/tree/tree.py", "max_stars_repo_name": "feiga/fedlearner", "max_stars_repo_head_hexsha": "99a19934b872a9fba6d85ae018b0ec145612fbca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fedlearner/model/tree/tree.py", "max_issues_repo_name": "feiga/fedlearner", "max_issues_repo_head_hexsha": "99a19934b872a9fba6d85ae018b0ec145612fbca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fedlearner/model/tree/tree.py", "max_forks_repo_name": "feiga/fedlearner", "max_forks_repo_head_hexsha": "99a19934b872a9fba6d85ae018b0ec145612fbca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-09T07:50:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-09T07:50:55.000Z", "avg_line_length": 37.8569536424, "max_line_length": 80, "alphanum_fraction": 0.6163319572, "include": true, "reason": "import numpy", "num_tokens": 6340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.18404825665924268}}
{"text": "# Copyright 2018-2021 Xanadu Quantum Technologies Inc.\r\n\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n\r\n#     http://www.apache.org/licenses/LICENSE-2.0\r\n\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\"\"\"\r\nThis module contains functions for adding the Autograd interface\r\nto a PennyLane Device class.\r\n\"\"\"\r\n# pylint: disable=too-many-arguments\r\nimport autograd\r\nfrom autograd.numpy.numpy_boxes import ArrayBox\r\n\r\nimport pennylane as qml\r\nfrom pennylane import numpy as np\r\n\r\n\r\ndef execute(tapes, device, execute_fn, gradient_fn, gradient_kwargs, _n=1, max_diff=2):\r\n    \"\"\"Execute a batch of tapes with Autograd parameters on a device.\r\n\r\n    Args:\r\n        tapes (Sequence[.QuantumTape]): batch of tapes to execute\r\n        device (.Device): Device to use to execute the batch of tapes.\r\n            If the device does not provide a ``batch_execute`` method,\r\n            by default the tapes will be executed in serial.\r\n        execute_fn (callable): The execution function used to execute the tapes\r\n            during the forward pass. This function must return a tuple ``(results, jacobians)``.\r\n            If ``jacobians`` is an empty list, then ``gradient_fn`` is used to\r\n            compute the gradients during the backwards pass.\r\n        gradient_kwargs (dict): dictionary of keyword arguments to pass when\r\n            determining the gradients of tapes\r\n        gradient_fn (callable): the gradient function to use to compute quantum gradients\r\n        _n (int): a positive integer used to track nesting of derivatives, for example\r\n            if the nth-order derivative is requested.\r\n        max_diff (int): If ``gradient_fn`` is a gradient transform, this option specifies\r\n            the maximum order of derivatives to support. Increasing this value allows\r\n            for higher order derivatives to be extracted, at the cost of additional\r\n            (classical) computational overhead during the backwards pass.\r\n\r\n    Returns:\r\n        list[list[float]]: A nested list of tape results. Each element in\r\n        the returned list corresponds in order to the provided tapes.\r\n    \"\"\"\r\n    for tape in tapes:\r\n        # set the trainable parameters\r\n        params = tape.get_parameters(trainable_only=False)\r\n        tape.trainable_params = qml.math.get_trainable_indices(params)\r\n\r\n    parameters = autograd.builtins.tuple(\r\n        [autograd.builtins.list(t.get_parameters()) for t in tapes]\r\n    )\r\n\r\n    return _execute(\r\n        parameters,\r\n        tapes=tapes,\r\n        device=device,\r\n        execute_fn=execute_fn,\r\n        gradient_fn=gradient_fn,\r\n        gradient_kwargs=gradient_kwargs,\r\n        _n=_n,\r\n        max_diff=max_diff,\r\n    )[0]\r\n\r\n\r\n@autograd.extend.primitive\r\ndef _execute(\r\n    parameters,\r\n    tapes=None,\r\n    device=None,\r\n    execute_fn=None,\r\n    gradient_fn=None,\r\n    gradient_kwargs=None,\r\n    _n=1,\r\n    max_diff=2,\r\n):  # pylint: disable=dangerous-default-value,unused-argument\r\n    \"\"\"Autodifferentiable wrapper around ``Device.batch_execute``.\r\n\r\n    The signature of this function is designed to work around Autograd restrictions.\r\n    Note that the ``parameters`` argument is dependent on the ``tapes`` argument;\r\n    this function should always be called as follows:\r\n\r\n    >>> parameters = [autograd.builtins.list(t.get_parameters()) for t in tapes])\r\n    >>> parameters = autograd.builtins.tuple(parameters)\r\n    >>> _execute(parameters, tapes=tapes, device=device)\r\n\r\n    In particular:\r\n\r\n    - ``parameters`` is dependent on the provided tapes: always extract them as above\r\n    - ``tapes`` is a *required* argument\r\n    - ``device`` is a *required* argument\r\n\r\n    The private argument ``_n`` is used to track nesting of derivatives, for example\r\n    if the nth-order derivative is requested. Do not set this argument unless you\r\n    understand the consequences!\r\n    \"\"\"\r\n    with qml.tape.Unwrap(*tapes):\r\n        res, jacs = execute_fn(tapes, **gradient_kwargs)\r\n\r\n    for i, r in enumerate(res):\r\n        res[i] = np.tensor(r)\r\n\r\n        if res[i].dtype == np.dtype(\"object\"):\r\n            # For backwards compatibility, we flatten ragged tape outputs\r\n            res[i] = np.hstack(r)\r\n\r\n    return res, jacs\r\n\r\n\r\ndef vjp(\r\n    ans,\r\n    parameters,\r\n    tapes=None,\r\n    device=None,\r\n    execute_fn=None,\r\n    gradient_fn=None,\r\n    gradient_kwargs=None,\r\n    _n=1,\r\n    max_diff=2,\r\n):  # pylint: disable=dangerous-default-value,unused-argument\r\n    \"\"\"Returns the vector-Jacobian product operator for a batch of quantum tapes.\r\n\r\n    Args:\r\n        ans (array): the result of the batch tape execution\r\n        parameters (list[list[Any]]): Nested list of the quantum tape parameters.\r\n            This argument should be generated from the provided list of tapes.\r\n        tapes (Sequence[.QuantumTape]): batch of tapes to execute\r\n        device (.Device): Device to use to execute the batch of tapes.\r\n            If the device does not provide a ``batch_execute`` method,\r\n            by default the tapes will be executed in serial.\r\n        execute_fn (callable): The execution function used to execute the tapes\r\n            during the forward pass. This function must return a tuple ``(results, jacobians)``.\r\n            If ``jacobians`` is an empty list, then ``gradient_fn`` is used to\r\n            compute the gradients during the backwards pass.\r\n        gradient_fn (callable): the gradient function to use to compute quantum gradients\r\n        gradient_kwargs (dict): dictionary of keyword arguments to pass when\r\n            determining the gradients of tapes\r\n        _n (int): a positive integer used to track nesting of derivatives, for example\r\n            if the nth-order derivative is requested.\r\n        max_diff (int): If ``gradient_fn`` is a gradient transform, this option specifies\r\n            the maximum number of derivatives to support. Increasing this value allows\r\n            for higher order derivatives to be extracted, at the cost of additional\r\n            (classical) computational overhead during the backwards pass.\r\n\r\n    Returns:\r\n        function: this function accepts the backpropagation\r\n        gradient output vector, and computes the vector-Jacobian product\r\n    \"\"\"\r\n\r\n    def grad_fn(dy):\r\n        \"\"\"Returns the vector-Jacobian product with given\r\n        parameter values and output gradient dy\"\"\"\r\n\r\n        dy = dy[0]\r\n        jacs = ans[1]\r\n\r\n        if jacs:\r\n            # Jacobians were computed on the forward pass (mode=\"forward\")\r\n            # No additional quantum evaluations needed; simply compute the VJPs directly.\r\n            vjps = [qml.gradients.compute_vjp(d, jac) for d, jac in zip(dy, jacs)]\r\n\r\n        else:\r\n            # Need to compute the Jacobians on the backward pass (accumulation=\"backward\")\r\n\r\n            if isinstance(gradient_fn, qml.gradients.gradient_transform):\r\n                # Gradient function is a gradient transform.\r\n\r\n                # Generate and execute the required gradient tapes\r\n                if _n == max_diff:\r\n                    with qml.tape.Unwrap(*tapes):\r\n                        vjp_tapes, processing_fn = qml.gradients.batch_vjp(\r\n                            tapes,\r\n                            dy,\r\n                            gradient_fn,\r\n                            reduction=\"append\",\r\n                            gradient_kwargs=gradient_kwargs,\r\n                        )\r\n\r\n                        vjps = processing_fn(execute_fn(vjp_tapes)[0])\r\n\r\n                else:\r\n                    vjp_tapes, processing_fn = qml.gradients.batch_vjp(\r\n                        tapes, dy, gradient_fn, reduction=\"append\", gradient_kwargs=gradient_kwargs\r\n                    )\r\n\r\n                    # This is where the magic happens. Note that we call ``execute``.\r\n                    # This recursion, coupled with the fact that the gradient transforms\r\n                    # are differentiable, allows for arbitrary order differentiation.\r\n                    vjps = processing_fn(\r\n                        execute(\r\n                            vjp_tapes,\r\n                            device,\r\n                            execute_fn,\r\n                            gradient_fn,\r\n                            gradient_kwargs,\r\n                            _n=_n + 1,\r\n                            max_diff=max_diff,\r\n                        )\r\n                    )\r\n\r\n            else:\r\n                # Gradient function is not a gradient transform\r\n                # (e.g., it might be a device method).\r\n                # Note that unlike the previous branch:\r\n                #\r\n                # - there is no recursion here\r\n                # - gradient_fn is not differentiable\r\n                #\r\n                # so we cannot support higher-order derivatives.\r\n                with qml.tape.Unwrap(*tapes):\r\n                    jacs = gradient_fn(tapes, **gradient_kwargs)\r\n\r\n                vjps = [qml.gradients.compute_vjp(d, jac) for d, jac in zip(dy, jacs)]\r\n\r\n        return [qml.math.to_numpy(v, max_depth=_n) if isinstance(v, ArrayBox) else v for v in vjps]\r\n\r\n    return grad_fn\r\n\r\n\r\nautograd.extend.defvjp(_execute, vjp, argnums=[0])\r\n", "meta": {"hexsha": "9c3060a8c15d11253d55dd5c16ab731fdf2be5dc", "size": 9570, "ext": "py", "lang": "Python", "max_stars_repo_path": "pennylane/interfaces/batch/autograd.py", "max_stars_repo_name": "ianmclean2011/pennylane", "max_stars_repo_head_hexsha": "abfc481bd8531462f059002e76ec9a2ca9dcca35", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pennylane/interfaces/batch/autograd.py", "max_issues_repo_name": "ianmclean2011/pennylane", "max_issues_repo_head_hexsha": "abfc481bd8531462f059002e76ec9a2ca9dcca35", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pennylane/interfaces/batch/autograd.py", "max_forks_repo_name": "ianmclean2011/pennylane", "max_forks_repo_head_hexsha": "abfc481bd8531462f059002e76ec9a2ca9dcca35", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9736842105, "max_line_length": 100, "alphanum_fraction": 0.6153605016, "include": true, "reason": "import numpy", "num_tokens": 1932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.18389260723565773}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nGenerates circuits for quantum error correction with surface code patches.\n\"\"\"\nimport copy\nimport warnings\nfrom abc import ABC, abstractmethod\n\nimport numpy as np\nimport networkx as nx\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute\n\ntry:\n    from qiskit import Aer\n\n    HAS_AER = True\nexcept ImportError:\n    from qiskit import BasicAer\n\n    HAS_AER = False\n\n\nclass LatticeError(Exception):\n    pass\n\n\nclass _Face:\n    \"\"\"\n    Abstract class for a single *face* of the surface code, which is described\n    by a syndrome qubit and the four data qubits that surround it. If the face\n    exists on an edge of the surface code lattice, some of the data qubits may\n    be None.\n    \"\"\"\n\n    def __init__(self, syndrome, top_l, top_r, bot_l, bot_r):\n        \"\"\"\n        Initialize a face by passing in the single QubitRegisters of the circuit\n        in which this face will be embedded.\n        \"\"\"\n        self.syndrome = syndrome\n        self.top_l = top_l\n        self.top_r = top_r\n        self.bot_l = bot_l\n        self.bot_r = bot_r\n\n    @abstractmethod\n    def entangle(self, circ):\n        pass\n\n\nclass _FaceX(_Face):\n    \"\"\"\n    X-syndrome face of the rotated surface code.\n    \"\"\"\n\n    def entangle(self, circ):\n        \"\"\"\n        Traverse in reverse \"Z\" pattern\n        \"\"\"\n        if (self.top_r and not self.top_l) or (self.bot_r and not self.bot_l):\n            raise LatticeError(\"Inconsistent X syndrome connections\")\n\n        circ.h(self.syndrome)\n        if self.top_r:\n            circ.cx(self.syndrome, self.top_r)\n            circ.cx(self.syndrome, self.top_l)\n        if self.bot_r:\n            circ.cx(self.syndrome, self.bot_r)\n            circ.cx(self.syndrome, self.bot_l)\n        circ.h(self.syndrome)\n\n\nclass _FaceZ(_Face):\n    \"\"\"\n    Z-syndrome face of the rotated surface code.\n    \"\"\"\n\n    def entangle(self, circ):\n        \"\"\"\n        Traverse in reverse \"N\" pattern\n        \"\"\"\n        if (self.top_r and not self.bot_r) or (self.top_l and not self.bot_l):\n            raise LatticeError(\"Inconsistent Z syndrome connections\")\n\n        if self.top_r:\n            circ.cx(self.top_r, self.syndrome)\n            circ.cx(self.bot_r, self.syndrome)\n        if self.top_l:\n            circ.cx(self.top_l, self.syndrome)\n            circ.cx(self.bot_l, self.syndrome)\n\n\nclass RotatedSurfaceCodeLattice:\n    \"\"\"\n    This class is essentially a helper class that translates between the lattice\n    abstraction of the surface code and the physical qubits in the circuit. This\n    promotes a clean separation of concerns and wraps the implementation details\n    of the lattice + code entanglement ordering.\n    \"\"\"\n\n    def __init__(self, d, data_register, mx_register, mz_register):\n        \"\"\"\n        Initializes an instance of the rotated surface code lattice with our\n        chosen layout and numbering.\n\n        Args:\n            d (int): surface code distance\n            data_register (QuantumRegister): grouped register of all data qubits\n            mx_register (QuantumRegister): grouped register of all measure-x qubits\n            mz_register (QuantumRegister): grouped register of all measure-z qubits\n        \"\"\"\n        self.d = d\n        self.measure_x = []\n        self.measure_z = []\n\n        per_row_x = (d ** 2 - 1) // 2 // (d + 1)\n        per_row_z = (d ** 2 - 1) // 2 // (d - 1)\n        for mx in mx_register:\n            idx = mx.index\n            row = idx // per_row_x\n            offset = idx % per_row_x\n            start = (row - 1) * d\n            row_parity = row % 2\n\n            if row == 0:  # First row\n                top_l, top_r = None, None\n                bot_l = data_register[idx * 2]\n                bot_r = data_register[idx * 2 + 1]\n            elif row == d:  # Last row\n                bot_l, bot_r = None, None\n                top_l = data_register[idx * 2 + 1]\n                top_r = data_register[idx * 2 + 2]\n            else:\n                top_l = data_register[start + (offset * 2) + row_parity]\n                top_r = data_register[start + (offset * 2) + row_parity + 1]\n                bot_l = data_register[start + d + (offset * 2) + row_parity]\n                bot_r = data_register[start + d + (offset * 2) + row_parity + 1]\n            self.measure_x.append(_FaceX(mx, top_l, top_r, bot_l, bot_r))\n\n        for mz in mz_register:\n            idx = mz.index\n            row = idx // per_row_z\n            offset = idx % per_row_z\n            start = row * d\n            row_parity = row % 2\n\n            top_l = data_register[start + (offset * 2) - row_parity]\n            top_r = data_register[start + (offset * 2) - row_parity + 1]\n            bot_l = data_register[start + d + (offset * 2) - row_parity]\n            bot_r = data_register[start + d + (offset * 2) - row_parity + 1]\n\n            # Overwrite edge column syndromes\n            if row_parity == 0 and offset == per_row_z:  # Last column\n                top_r, bot_r = None, None\n            elif row_parity == 1 and offset == 0:  # First column\n                top_l, bot_l = None, None\n\n            self.measure_z.append(_FaceZ(mz, top_l, top_r, bot_l, bot_r))\n\n    def entangle(self, circ):\n        \"\"\"\n        Entangles the entire surface code by calling the entangle method of each\n        syndrome face. Within a face, order is determined by the delegated\n        method. Order between faces should not matter here, since the projection\n        will be determined by the measurement order.\n        \"\"\"\n        for syndrome in (self.measure_x, self.measure_z):\n            for face in syndrome:\n                face.entangle(circ)\n\n    def parse_readout(self, readout_string):\n        \"\"\"\n        Helper method to turn a result string (e.g. 1 10100000 10010000) into an\n        appropriate logical readout value and XOR-ed syndrome locations\n        according to our grid coordinate convention.\n        \"\"\"\n        syn_len = (self.d ** 2 - 1) // 2\n        chunks = readout_string.split(\" \")\n\n        int_syndromes = [int(x, base=2) for x in chunks[-1:0:-1]]\n        xor_syndromes = [a ^ b for (a, b) in zip(int_syndromes, int_syndromes[1:])]\n\n        mask_Z = \"1\" * syn_len\n        mask_X = mask_Z + \"0\" * syn_len\n        X_syndromes = [(x & int(mask_X, base=2)) >> syn_len for x in xor_syndromes]\n        Z_syndromes = [x & int(mask_Z, base=2) for x in xor_syndromes]\n\n        X = []\n        for T, syndrome in enumerate(X_syndromes):\n            for loc in range(syn_len):\n                if syndrome & 1 << loc:\n                    X.append((T, -0.5 + loc, 0.5 + loc % 2))\n\n        Z = []\n        for T, syndrome in enumerate(Z_syndromes):\n            for loc in range(syn_len):\n                if syndrome & 1 << loc:\n                    Z.append((T, 0.5 + loc // 2, 0.5 + loc % 2 * 2 - loc // 2))\n\n        return (\n            int(chunks[0]),\n            {\"X\": X, \"Z\": Z,},\n        )\n\n\nclass SurfaceCodeLogicalQubit(QuantumCircuit):\n    \"\"\"\n    A single logical surface code qubit. At the physical level, this wraps a\n    circuit, so we chose to subclass and extend QuantumCircuit.\n    \"\"\"\n\n    def __init__(self, d, *args, **kwargs):\n        \"\"\"\n        Initializes a new QuantumCircuit for this logical qubit and calculates\n        the underlying surface code lattice ordering.\n        \n        Args:\n            d (int): Number of physical \"data\" qubits. Only odd d is possible!\n        \"\"\"\n        if d % 2 != 1:\n            raise ArgumentError(\"Surface code distance must be odd!\")\n        self.__d = d\n        self.__T = 0\n        self.__num_data = d ** 2\n        self.__num_syn = (d ** 2 - 1) // 2\n\n        self.__data = QuantumRegister(self.__num_data, \"data\")\n        self.__mz = QuantumRegister(self.__num_syn, \"mz\")\n        self.__mx = QuantumRegister(self.__num_syn, \"mx\")\n\n        # We implement and assume the rotated lattice only, but this can be\n        # imagined to accept other layouts in the future.\n        self.__lattice = RotatedSurfaceCodeLattice(d, self.__data, self.__mx, self.__mz)\n\n        # Spare ancilla (e.g. for readout)\n        self.__ancilla = QuantumRegister(1, name=\"ancilla\")\n        super().__init__(self.__data, self.__mz, self.__mx, self.__ancilla)\n\n    def stabilize(self):\n        \"\"\"\n        Run a single round of stabilization (entangle and measure).\n        \"\"\"\n        syndrome_readouts = ClassicalRegister(\n            self.__num_syn * 2, name=\"c{}\".format(self.__T)\n        )\n        self.add_register(syndrome_readouts)\n        self.__T += 1\n\n        self.__lattice.entangle(self)\n        self.barrier()\n        self.measure(self.__mz, syndrome_readouts[0 : self.__num_syn])\n        self.measure(self.__mx, syndrome_readouts[self.__num_syn : self.__num_syn * 2])\n        self.reset(self.__mz)\n        self.reset(self.__mx)\n        self.barrier()\n\n    def identity(self):\n        \"\"\"\n        Inserts an identity on the data and syndrome qubits. This is a hack to\n        create an isolated error model.\n        \"\"\"\n        [\n            self.id(x)\n            for register in (self.__data, self.__mz, self.__mx)\n            for x in register\n        ]\n        self.barrier()\n\n    def hadamard_reset(self):\n        \"\"\"\n        A hack to initialize a + and - logical qubit for now...\n        \"\"\"\n        [self.reset(x) for x in self.__data]\n        [self.h(x) for x in self.__data]\n        self.barrier()\n\n    def logical_x(self):\n        \"\"\"\n        Logical X operator on the qubit.\n        \"\"\"\n        for i in range(0, self.__num_data, self.__d):\n            self.x(self.__data[i])\n        self.barrier()\n\n    def logical_z(self):\n        \"\"\"\n        Logical Z operator on the qubit.\n        \"\"\"\n        for i in range(self.__d):\n            self.z(self.__data[i])\n        self.barrier()\n\n    def readout_z(self):\n        \"\"\"\n        Convenience method to read-out the logical-Z projection.\n        \"\"\"\n        readout = ClassicalRegister(1, name=\"readout\")\n        self.add_register(readout)\n\n        self.reset(self.__ancilla)\n        for i in range(self.__d):\n            self.cx(self.__data[i], self.__ancilla)\n        self.measure(self.__ancilla, readout)\n        self.barrier()\n\n    def readout_x(self):\n        \"\"\"\n        Convenience method to read-out the logical-X projection.\n        \"\"\"\n        readout = ClassicalRegister(1, name=\"readout\")\n        self.add_register(readout)\n\n        self.reset(self.__ancilla)\n        self.h(self.__ancilla)\n        for i in range(0, self.__num_data, self.__d):\n            self.cx(self.__ancilla, self.__data[i])\n        self.h(self.__ancilla)\n        self.measure(self.__ancilla, readout)\n        self.barrier()\n\n    def parse_readout(self, readout_string):\n        return self.__lattice.parse_readout(readout_string)\n", "meta": {"hexsha": "ed2eca90f608f141e6fd8ac24c70f1dae12b8587", "size": 10735, "ext": "py", "lang": "Python", "max_stars_repo_path": "surface_code/circuits.py", "max_stars_repo_name": "liuhenry/qiskit_surface_codes", "max_stars_repo_head_hexsha": "4bb0345cf56086a2e844263f5150c2fa014880e4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "surface_code/circuits.py", "max_issues_repo_name": "liuhenry/qiskit_surface_codes", "max_issues_repo_head_hexsha": "4bb0345cf56086a2e844263f5150c2fa014880e4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "surface_code/circuits.py", "max_forks_repo_name": "liuhenry/qiskit_surface_codes", "max_forks_repo_head_hexsha": "4bb0345cf56086a2e844263f5150c2fa014880e4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2352941176, "max_line_length": 88, "alphanum_fraction": 0.5805309735, "include": true, "reason": "import numpy,import networkx", "num_tokens": 2703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.18389260372469995}}
{"text": "import os,os.path,shutil\nimport numpy as np\nimport pickle\n\nimport dmdd\nimport dmdd_efficiencies as eff\n\n\ndef check_min_mass(element='fluorine', Qmin=1., v_esc=544., v_lag=220., mx_guess=1.):\n    experiment = dmdd.Experiment('test',element,Qmin, 40.,100., eff.efficiency_unit)\n    res = experiment.find_min_mass(v_esc=v_esc, v_lag=v_lag, mx_guess=mx_guess)\n    print res,'GeV'\n    if res<0:\n        print 'Problem: try another mx_guess...'\n    \n    \n\ndef make_UVmodels(return_models=False):\n    SI_Higgs = dmdd.UV_Model('SI_Higgs', ['mass', 'sigma_si'], fixed_params={'fnfp_si': 1})\n    milicharge = dmdd.UV_Model('Milicharge', ['mass', 'sigma_si_massless'], fixed_params={'fnfp_si_massless': 0})\n    SD_flavoruniversal = dmdd.UV_Model('SD_fu', ['mass','sigma_sd'], fixed_params={'fnfp_sd': -1.1})\n    anapole = dmdd.UV_Model('Anapole', ['mass','sigma_anapole'])\n    magdip_heavy = dmdd.UV_Model('Mag.dip.heavy', ['mass','sigma_magdip'])\n    magdip_0 = dmdd.UV_Model('Mag.dip.light', ['mass','sigma_magdip_massless'])\n    elecdip_heavy = dmdd.UV_Model('Elec.dip.heavy', ['mass','sigma_elecdip'])\n    elecdip_0 = dmdd.UV_Model('Elec.dip.light', ['mass','sigma_elecdip_massless'])\n    f1 = dmdd.UV_Model('f1', ['mass','sigma_f1'], fixed_params={'fnfp_f1': 1.})\n    f2_Higgs = dmdd.UV_Model('f2_Higgs', ['mass','sigma_f2'], fixed_params={'fnfp_f2': -0.05})\n    #f2_flavoruniversal = dmdd.UV_Model('f2_flavor-universal', ['mass','sigma_f2'], fixed_params={'fnfp_f2': 1.})\n    f3_Higgs = dmdd.UV_Model('f3_Higgs', ['mass','sigma_f3'], fixed_params={'fnfp_f3': -0.05})\n    #f3_flavoruniversal = dmdd.UV_Model('f3_flavor-universal', ['mass','sigma_f3'], fixed_params={'fnfp_f3': 1.})\n    LS = dmdd.UV_Model('LS', ['mass','sigma_LS'], fixed_params={'fnfp_LS': 0.})\n\n    models = [SI_Higgs, milicharge, SD_flavoruniversal, anapole,\n              magdip_heavy, magdip_0, elecdip_heavy, elecdip_0,\n              f1, f2_Higgs, f3_Higgs, LS]\n\n    if return_models:\n        return models\n\ndef make_experiments(return_experiments=False):\n    xe = dmdd.Experiment('Xe','xenon',5., 40.,100., eff.efficiency_unit)\n    ge = dmdd.Experiment('Ge','germanium',0.4, 100.,100., eff.efficiency_unit)\n    if return_experiments:\n        return [xe,ge]\n\n\ndef test_MultinestRun(mass=50,test_fits=False):\n\n    SI_Higgs = dmdd.UV_Model('SI_Higgs', ['mass', 'sigma_si'], fixed_params={'fnfp_si': 1})\n    elecdip_heavy = dmdd.UV_Model('Elec.dip.heavy', ['mass','sigma_elecdip'])\n\n    experiment = make_experiments(return_experiments=True)\n    \n    simmodel = SI_Higgs\n    fitmodel1 = SI_Higgs\n    fitmodel2 = elecdip_heavy\n    \n    pardic = {'sigma_si': 70.,'mass': mass}\n    simname = 'simtest'\n    \n    testrun1 = dmdd.MultinestRun(simname, experiment, simmodel, pardic,\n                                 fitmodel1, prior_ranges={'mass':(1,1000),\n                                                          'sigma_si':(0.001,100000),\n                                                          'sigma_elecdip':(0.001,100000)})\n    data1 = np.loadtxt(testrun1.simulations[0].datafile)\n\n    pardic = {'sigma_si': 70.0007,'mass': mass}\n    testrun2 = dmdd.MultinestRun(simname, experiment, simmodel, pardic,\n                                 fitmodel2, empty_run=False,\n                                 prior_ranges={'mass':(1,1000),\n                                                'sigma_si':(0.001,100000),\n                                                'sigma_elecdip':(0.001,100000)})\n    data2 = np.loadtxt(testrun1.simulations[0].datafile)\n\n    #simulation datafile should be created only for the first instance of MultinestRun:\n    assert np.allclose(data1, data2) \n\n    if test_fits:\n    \n        testrun1.fit()        \n        testrun1.visualize()\n        testrun2.fit()\n        testrun2.visualize()\n\n\n        if (not os.path.exists(testrun1.chains_file)) or (not os.path.exists(testrun1.pickle_file)) or (not os.path.exists(testrun1.stats_file)):\n            raise AssertionError('Stats or chains or pickle are not created or are erased.')\n\n        plotfile1 = testrun1.chainspath + '2d_posterior_mass_vs_sigma_si.pdf'\n        plotfile2 = testrun1.chainspath + '{}_theoryfitdata_Ge.pdf'.format(simname)\n        plotfile3 = testrun1.chainspath + '{}_theoryfitdata_Xe.pdf'.format(simname)\n        if (not os.path.exists(plotfile1)) or (not os.path.exists(plotfile2)) or (not os.path.exists(plotfile3)):\n            raise AssertionError('Plots are not created or are erased.')\n\n        if (not os.path.exists(testrun2.chains_file)) or (not os.path.exists(testrun2.pickle_file)) or (not os.path.exists(testrun2.stats_file)):\n            raise AssertionError('Stats or chains or pickle are not created.')\n\n        plotfile1 = testrun2.chainspath + '2d_posterior_mass_vs_sigma_elecdip.pdf'\n        plotfile2 = testrun2.chainspath + '{}_theoryfitdata_Ge.pdf'.format(simname)\n        plotfile3 = testrun2.chainspath + '{}_theoryfitdata_Xe.pdf'.format(simname)\n        if (not os.path.exists(plotfile1)) or (not os.path.exists(plotfile2)) or (not os.path.exists(plotfile3)):\n            raise AssertionError('Plots are not created.')\n\n\ndef test_UVrate():\n    \n    experiment = dmdd.Experiment('Xe','xenon',5., 40.,10000., eff.efficiency_unit)\n    models = make_UVmodels(return_models=True)\n    mass = 40.\n    qs = np.array([15.])\n    v_lag = 200.\n    v_rms = 100.\n    v_esc = 600.\n    rho_x = 0.4\n    \n    sigma_names = {}\n    fnfp_names = {}\n    fnfp_vals = {}\n    for m in models:\n        sigma_names[m.name] = m.param_names[1]    \n        if len(m.fixed_params)>0:\n            fnfp_names[m.name] = m.fixed_params.keys()[0]\n            fnfp_vals[m.name] = m.fixed_params.values()[0] \n        else:\n            fnfp_names[m.name] = None\n            fnfp_vals[m.name] = None\n\n    dRdQs = np.zeros(len(models))\n    Rs = np.zeros(len(models))\n    for i,m in enumerate(models):\n        kwargs = {sigma_names[m.name]:1.}\n        if fnfp_names[m.name] is not None:\n            kwargs[fnfp_names[m.name]] = fnfp_vals[m.name]\n\n        dRdQs[i] = dmdd.rate_UV.dRdQ(qs, mass=mass, element=experiment.element,\n                                        v_lag=v_lag, v_rms=v_rms, v_esc=v_esc, rho_x=rho_x,\n                                        **kwargs)\n        Rs[i] = dmdd.rate_UV.R(eff.efficiency_unit, mass=mass, element=experiment.element,\n                                        Qmin=experiment.Qmin, Qmax=experiment.Qmax,\n                                        v_lag=v_lag, v_rms=v_rms, v_esc=v_esc, rho_x=rho_x,\n                                        **kwargs)\n    #print 'dRdQs = {}\\n'.format(dRdQs)\n    #print 'Rs = {}\\n'.format(Rs)\n    dRdQs_correct = [  1.27974652e-12,   1.67031585e-13,   6.28936205e-13,   7.76864477e-13,\n                       7.71724584e-13,   5.66164037e-13,   8.40579288e-13,   6.16678247e-13,\n                       4.72480605e-13,   2.59857470e-16,   9.59390104e-16,   1.14295679e-13]\n\n    Rs_correct = [  6.15358778e-11,   3.10857259e-11,   3.14982315e-11,   4.14119198e-11,\n                    1.82181891e-11,   3.84877268e-11,   2.35638282e-11,   5.50063883e-11,\n                    1.34702925e-11,   5.82472177e-15,   1.64213483e-14,   2.26028126e-12]\n\n    assert np.allclose(dRdQs_correct, dRdQs)\n    assert np.allclose(Rs_correct, Rs)\n\n    ###\n    qs = np.array([8.3,15.7])\n    logtest1 = dmdd.rate_UV.loglikelihood(qs, eff.efficiency_unit, mass=mass,\n                                              sigma_si=1.,fnfp_si=1.,\n                                                element=experiment.element,\n                                                Qmin=experiment.Qmin, Qmax=experiment.Qmax,\n                                                exposure=experiment.exposure,energy_resolution=True,\n                                                v_lag=v_lag, v_rms=v_rms, v_esc=v_esc, rho_x=rho_x)\n    logtest2 = dmdd.rate_UV.loglikelihood(qs, eff.efficiency_unit, mass=mass,\n                                              sigma_si=1.,fnfp_si=1.,\n                                                element=experiment.element,\n                                                Qmin=experiment.Qmin, Qmax=experiment.Qmax,\n                                                exposure=experiment.exposure,energy_resolution=False,\n                                                v_lag=v_lag, v_rms=v_rms, v_esc=v_esc, rho_x=rho_x)\n\n    #print 'logtest1_correct={}'.format(logtest1)\n    #print 'logtest2_correct={}'.format(logtest2)\n    logtest1_correct=-19.6890210901\n    logtest2_correct=-13.4627188661\n\n    print('correct={}  got={}\\n'.format(logtest1_correct,logtest1))\n    print('correct={}  got={}\\n'.format(logtest2_correct,logtest2))\n\n    assert np.isclose(logtest1_correct, logtest1)\n    assert np.isclose(logtest2_correct, logtest2) \n\n\n\n", "meta": {"hexsha": "1e25a51ae8f7d0a0791a002295995fa2dfc9aa41", "size": 8718, "ext": "py", "lang": "Python", "max_stars_repo_path": "dmdd/tests/test.py", "max_stars_repo_name": "hyounggyu/dmdd", "max_stars_repo_head_hexsha": "5d3cdc0b49be452349d0778e3ef4dd6fa4cc9045", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2015-06-16T02:11:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-22T03:01:01.000Z", "max_issues_repo_path": "dmdd/tests/test.py", "max_issues_repo_name": "hyounggyu/dmdd", "max_issues_repo_head_hexsha": "5d3cdc0b49be452349d0778e3ef4dd6fa4cc9045", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-07-28T14:34:56.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-07T02:44:29.000Z", "max_forks_repo_path": "dmdd/tests/test.py", "max_forks_repo_name": "hyounggyu/dmdd", "max_forks_repo_head_hexsha": "5d3cdc0b49be452349d0778e3ef4dd6fa4cc9045", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-06-22T15:00:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-13T21:13:26.000Z", "avg_line_length": 47.3804347826, "max_line_length": 145, "alphanum_fraction": 0.59669649, "include": true, "reason": "import numpy", "num_tokens": 2545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.18389260021374215}}
{"text": "from __future__ import print_function, division\n\nimport os, os.path, sys, re, glob\nimport itertools\nfrom copy import deepcopy\nimport logging\nimport json\n\nfrom .config import on_rtd\n\nif not on_rtd:\n    import numpy as np\n    import pandas as pd\n\n    import numpy.random as rand\n    from scipy.stats import gaussian_kde\n    import scipy\n    import emcee\n    import corner\n\n    try:\n        import pymultinest\n    except ImportError:\n        logging.warning('PyMultiNest not imported.  MultiNest fits will not work.')\n\n    import configobj\n    from astropy.coordinates import SkyCoord\n\n    try:\n        basestring\n    except NameError:\n        basestring = str\n\nfrom .utils import addmags\nfrom .observation import ObservationTree, Observation, Source\nfrom .priors import age_prior, distance_prior, AV_prior, q_prior\nfrom .priors import salpeter_prior, feh_prior\nfrom .isochrone import get_ichrone, Isochrone\n\ndef _parse_config_value(v):\n    try:\n        val = float(v)\n    except:\n        try:\n            val = [float(x) for x in v]\n        except:\n            val = v\n    #print('{} becomes {}, type={}'.format(v,val,type(val)))\n    return val\n\n\n\nclass StarModel(object):\n    \"\"\"\n\n    :param ic:\n        :class:`Isochrone` object used to model star.\n\n    :param obs: (optional)\n        :class:`ObservationTree` object containing photometry information.\n        If not provided, then one will be constructed from the provided\n        keyword arguments (which must include at least one photometric\n        bandpass).  This should only happen in the simplest case\n        of a single star system---if multiple stars are detected\n        in any of the observations being used, an :class:`ObservationTree`\n        should be passed.  If `obs` is a string, then it is assumed\n        to be a filename of an obs summary DataFrame.\n\n    :param N:\n        Number of model stars to assign to each \"leaf node\" of the\n        :class:`ObservationTree`.  If you want to model a binary star,\n        provide ``N=2``.\n\n    :param **kwargs:\n        Keyword arguments must be properties of given isochrone, e.g., logg,\n        feh, Teff, and/or magnitudes.  The values represent measurements of\n        the star, and must be in (value,error) format. All such keyword\n        arguments will be held in ``self.properties``.  ``parallax`` is\n        also a valid property, and should be provided in miliarcseconds,\n        as is ``density`` [g/cc], and ``nu_max`` and ``delta_nu``\n        (asteroseismic parameters in uHz.)\n    \"\"\"\n\n    # These are allowable parameters that are not photometric bands\n    _not_a_band = ('RA','dec','ra','Dec','maxAV','parallax',\n                  'logg','Teff','feh','density', 'separation',\n                 'PA','resolution','relative','N','index', 'id')\n\n    _default_name = 'single'\n\n    def __init__(self, ic, obs=None, N=1, index=0,\n                 name='', use_emcee=False,\n                 RA=None, dec=None, coords=None,\n                 **kwargs):\n\n        self.name = name if name else self._default_name\n\n        if coords is None:\n            if RA is not None and dec is not None:\n                try:\n                    coords = SkyCoord(RA, dec)\n                except:\n                    coords = SkyCoord(float(RA), float(dec), unit='deg')\n        self.coords = coords\n        self._ic = ic\n\n        self.use_emcee = use_emcee\n\n        # If obs is not provided, build it\n        if obs is None:\n            self._build_obs(**kwargs)\n            self.obs.define_models(ic, N=N, index=index)\n            self._add_properties(**kwargs)\n        elif isinstance(obs, basestring):\n            df = pd.read_csv(obs)\n            obs = ObservationTree.from_df(df)\n            obs.define_models(ic, N=N, index=index)\n            self.obs = obs\n            self._add_properties(**kwargs)\n        else:\n            self.obs = obs\n            if len(self.obs.get_model_nodes())==0:\n                self.obs.define_models(ic, N=N, index=index)\n                self._add_properties(**kwargs)\n\n        self._priors = {'mass':salpeter_prior,\n                        'feh':feh_prior,\n                        'q':q_prior,\n                        'age':age_prior,\n                        'distance':distance_prior,\n                        'AV':AV_prior}\n\n        self._bounds = {'mass':None,\n                        'feh':None,\n                        'age':None,\n                        'q':q_prior.bounds,\n                        'distance':distance_prior.bounds,\n                        'AV':AV_prior.bounds}\n\n        if 'maxAV' in kwargs:\n            self.set_bounds(AV=(0, kwargs['maxAV']))\n\n        if 'max_distance' in kwargs:\n            self.set_bounds(distance=(0, kwargs['max_distance']))\n\n        self._directory = '.'\n        self._samples = None\n\n    @property\n    def directory(self):\n        return self._directory\n\n    @property\n    def ic(self):\n        if type(self._ic)==type:\n            self._ic = self._ic()\n        return self._ic\n\n    @classmethod\n    def _parse_band(cls, kw):\n        \"\"\"Returns photometric band from inifile keyword\n        \"\"\"\n        m = re.search('([a-zA-Z0-9]+)(_\\d+)?', kw)\n        if m:\n            if m.group(1) in cls._not_a_band:\n                return None\n            else:\n                return m.group(1)\n\n    @classmethod\n    def get_bands(cls, inifile):\n\n        bands = []\n        c = configobj.ConfigObj(inifile)\n        for kw,v in c.items():\n            if type(v) is configobj.Section:\n                for kw in v:\n                    b = cls._parse_band(kw)\n                    if b is not None:\n                        bands.append(b)\n            else:\n                b = cls._parse_band(kw)\n                if b is not None:\n                    bands.append(b)\n\n        return list(set(bands))\n\n\n    @classmethod\n    def from_ini(cls, ic, folder='.', ini_file='star.ini', **kwargs):\n        \"\"\"\n        Initialize a StarModel from a .ini file\n\n        The \"classic\" format (version <= 0.9) should still work for a single star,\n        where all properties are just listed in the file; e.g.,\n\n            J = 10, 0.05\n            H = 9.5, 0.05\n            K = 9.0, 0.05\n            Teff = 5000, 150\n\n        If there are multiple stars observed, you can either define them in\n        the ini file, or use the `obsfile` keyword, pointing to a file with\n        the summarized photometric observations.  In this case, spectroscopic/parallax\n        info should still be included in the .ini file; e.g.,\n\n            obsfile = obs.csv\n            Teff = 5000, 150\n\n        The obsfile should be a comma-separated table with the following columns:\n        `[name, band, resolution, mag, e_mag, separation, pa, relative]`.\n\n          * `name` is the name of instrument\n          * `band` is the photometric bandpass\n          * `resolution` is the approximate spatial resolution of instrument\n          * `mag`, `e_mag` describe magnitude of source (absolute or relative)\n          * `separation`, `pa` describe position of source\n          * `relative`: single-bit flag; if 1 then magnitudes taken with this\n            instrument are assumed to be relative rather than absolute.\n\n        If an obsfile is not provided, you can also define all the same information\n        in the ini file, following these rules:\n\n          * Every instrument/survey gets its own [section].  Sections are only\n        created for different photometric observations.\n\n          * if photometry relates to *all* stars in aperture,\n            there is no extra info in the section, just the photometry.  In this case, it is\n            also assumed that the photometry is absolute. (`relative=False`)\n\n          * If 'resolution' is an attribute under a particular survey section (and\n        'relative' is not explicitly stated), then the survey is assumed to have relative\n        photometry, and to be listing\n        information about companion stars.  In this case, there must be \"separation\"\n        and \"PA\" included for each companion.  If there is more than one companion star,\n        they must be identifed by tag, e.g., separation_1, PA_1, Ks_1, J_1, etc.  The\n        tag can be anything alphanumeric, but it must be consistent within a particular\n        section (instrument).  If there\n        is no tag, there is assumed to be only one companion detected.\n\n          * If there are no sections, then bands will be interpreted at face value\n        and will all be assumed to apply to all stars modeled.\n\n          * Default is to model each star in the highest-resolution observation as a\n        single star, at the same distance/age/feh/AV.\n\n\n        The `N` and `index`\n        parameters may also be provided, to specify the relations between the\n        model stars.  If these are not provided, then `N` will default to `1`\n        (one model star per star observed in highest-resolution observation)\n        and `index` will default to all `0` (all stars physically associated).\n\n        \"\"\"\n\n        if not os.path.isabs(ini_file):\n            ini_file = os.path.join(folder,ini_file)\n\n        bands = cls.get_bands(ini_file)\n\n        if not isinstance(ic, Isochrone):\n            ic = get_ichrone(ic, bands)\n\n        logging.debug('Initializing StarModel from {}'.format(ini_file))\n\n        c = configobj.ConfigObj(ini_file)\n\n        RA = c.get('RA')\n        dec = c.get('dec')\n        maxAV = c.get('maxAV')\n\n        if len(c.sections) == 0:\n            for k in c:\n                kwargs[k] = _parse_config_value(c[k])\n            obs = None\n        else:\n\n            columns = ['name', 'band', 'resolution', 'relative', 'separation', 'pa', 'mag', 'e_mag']\n            df = pd.DataFrame(columns=columns)\n            i = 0\n            for k in c:\n                if type(c[k]) != configobj.Section:\n                    kwargs[k] = _parse_config_value(c[k])\n                else:\n                    instrument = k\n\n                    # Set values of 'resolution' and 'relative'\n                    if 'resolution' in c[k]:\n                        resolution = float(c[k]['resolution'])\n                        relative = True\n                    else:\n                        resolution = 4.0 #default\n                        relative = False\n\n                    # Overwrite value of 'relative' if it is explicitly set\n                    if 'relative' in c[k]:\n                        relative = c[k]['relative']=='True'\n\n\n                    # Check if there are multiple stars (defined by whether\n                    # any separations are listed).\n                    # While we're at it, keep track of tags if they exist,\n                    #  and pull out the names of the bands.\n                    multiple = False\n                    tags = []\n                    bands = []\n                    for label in c[k]:\n                        m = re.search('separation(_\\w+)?', label)\n                        if m:\n                            multiple = True\n                            if m.group(1) is not None:\n                                if m.group(1) not in tags:\n                                    tags.append(m.group(1))\n                        elif re.search('PA', label) or re.search('id', label) or \\\n                                label in ['resolution', 'relative']:\n                            continue\n                        else:\n                            # At this point, this should be a photometric band\n                            m = re.search('([a-zA-Z0-9]+)(_\\w+)?', label)\n                            b = m.group(1)\n                            if b not in bands:\n                                bands.append(b)\n\n                    # If a blank tags needs to be created, do so\n                    if len(bands) > 0 and (len(tags)==0 or bands[0] in c[k]):\n                        tags.append('')\n\n                    # For each band and each star, create a row\n                    for b in bands:\n                        for tag in tags:\n                            if '{}{}'.format(b, tag) not in c[k]:\n                                continue\n                            row = {}\n                            row['name'] = instrument\n                            row['band'] = b\n                            row['resolution'] = resolution\n                            row['relative'] = relative\n                            if 'separation{}'.format(tag) in c[k]:\n                                row['separation'] = c[k]['separation{}'.format(tag)]\n                                row['pa'] = c[k]['PA{}'.format(tag)]\n                            else:\n                                row['separation'] = 0.\n                                row['pa'] = 0.\n                            mag, e_mag = c[k]['{}{}'.format(b,tag)]\n                            row['mag'] = float(mag)\n                            row['e_mag'] = float(e_mag)\n                            if not np.isnan(row['mag']) and not np.isnan(row['e_mag']):\n                                df = df.append(pd.DataFrame(row, index=[i]))\n                                i += 1\n\n                        # put the reference star in w/ mag=0\n                        if relative:\n                            row = {}\n                            row['name'] = instrument\n                            row['band'] = b\n                            row['resolution'] = resolution\n                            row['relative'] = relative\n                            row['separation'] = 0.\n                            row['pa'] = 0.\n                            row['mag'] = 0.\n                            row['e_mag'] = 0.01\n                            df = df.append(pd.DataFrame(row, index=[i]))\n                            i += 1\n\n            obs = ObservationTree.from_df(df)\n\n        if 'obsfile' in c:\n            obs = c['obsfile']\n\n        logging.debug('Obs is {}'.format(obs))\n\n        if 'name' not in kwargs:\n            kwargs['name'] = os.path.basename(folder)\n        new = StarModel(ic, obs=obs, **kwargs)\n        new._directory = os.path.abspath(folder)\n\n        return new\n\n    def print_ascii(self):\n        \"\"\"Prints an ascii representation of the observation tree structure.\n        \"\"\"\n        return self.obs.print_ascii()\n\n    def bounds(self, prop):\n        if self._bounds[prop] is not None:\n            return self._bounds[prop]\n        elif prop=='mass':\n            lo, hi = (self.ic.minmass, self.ic.maxmass)\n            self._bounds['mass'] = (lo, hi)\n            self._priors['mass'].bounds = (lo, hi)\n        elif prop=='feh':\n            lo, hi = (self.ic.minfeh, self.ic.maxfeh)\n            self._bounds['feh'] = (lo, hi)\n            self._priors['feh'].bounds = (lo, hi)\n        elif prop=='age':\n            lo, hi = (self.ic.minage, self.ic.maxage)\n            self._bounds['age'] = (lo, hi)\n            self._priors['age'].bounds = (lo, hi)\n            self._bounds['age'] = (self.ic.minage,\n                                   self.ic.maxage)\n        else:\n            raise ValueError('Unknown property {}'.format(prop))\n        return self._bounds[prop]\n\n    def set_bounds(self, **kwargs):\n        for k,v in kwargs.items():\n            if len(v) != 2:\n                raise ValueError('Must provide (min, max)')\n            self._bounds[k] = v\n            self._priors[k].bounds = v\n\n    def _build_obs(self, **kwargs):\n        \"\"\"\n        Builds ObservationTree out of keyword arguments\n\n        Ignores anything that is not a photometric bandpass.\n        This should not be used if there are multiple stars observed.\n\n        Creates self.obs\n        \"\"\"\n        logging.debug('Building ObservationTree...')\n        tree = ObservationTree()\n        for k,v in kwargs.items():\n            if k in self.ic.bands:\n                if np.size(v) != 2:\n                    logging.warning('{}={} ignored.'.format(k,v))\n                    # continue\n                    v = [v, np.nan]\n                o = Observation('', k, 99) #bogus resolution=99\n                s = Source(v[0], v[1])\n                o.add_source(s)\n                logging.debug('Adding {} ({})'.format(s,o))\n                tree.add_observation(o)\n\n        self.obs = tree\n\n    def _add_properties(self, **kwargs):\n        \"\"\"\n        Adds non-photometry properties to ObservationTree\n        \"\"\"\n        for k,v in kwargs.items():\n            if k=='parallax':\n                self.obs.add_parallax(v)\n            elif k in ['Teff','logg','feh']:\n                par = {k:v}\n                self.obs.add_spectroscopy(**par)\n            elif re.search('_', k):\n                m = re.search('^(\\w+)_(\\w+)$', k)\n                prop = m.group(1)\n                tag = m.group(2)\n                self.obs.add_spectroscopy(**{prop:v, 'label':'0_{}'.format(tag)})\n\n\n    @property\n    def param_description(self):\n        return self.obs.param_description\n\n    @property\n    def param_names(self):\n        return self.param_description\n\n    @property\n    def mags(self):\n        return {n.band : n.value[0] for n in self.obs.get_obs_nodes()}\n\n    def lnpost(self, p, **kwargs):\n        lnpr = self.lnprior(p)\n        if not np.isfinite(lnpr):\n            return lnpr\n        return lnpr + self.lnlike(p, **kwargs)\n\n    def lnlike(self, p, **kwargs):\n        lnl = self.obs.lnlike(p, **kwargs)\n        return lnl\n\n    def lnprior(self, p):\n        N = self.obs.Nstars\n        i = 0\n        lnp = 0\n        for s in self.obs.systems:\n            age, feh, dist, AV = p[i+N[s]:i+N[s]+4]\n            for prop, val in zip(['age','feh','distance','AV'],\n                                 [age, feh, dist, AV]):\n                lo,hi = self.bounds(prop)\n                if val < lo or val > hi:\n                    return -np.inf\n                lnp += np.log(self.prior(prop, val))\n                if not np.isfinite(lnp):\n                    logging.debug('lnp=-inf for {}={} (system {})'.format(prop,val,s))\n                    return -np.inf\n\n            # Note: this is just assuming proper order.\n            #  Is this OK?  Should keep eye out for bugs here.\n\n            masses = p[i:i+N[s]]\n\n            # Mass prior for primary\n            lnp += np.log(self.prior('mass', masses[0]))\n            if not np.isfinite(lnp):\n                logging.debug('lnp=-inf for mass={} (system {})'.format(masses[0],s))\n\n            # Priors for mass ratios\n            for j in range(N[s]-1):\n                q = masses[j+1]/masses[0]\n                qmin, qmax = self.bounds('q')\n\n                ## The following would enforce MA > MB > MC, but seems to make things very slow:\n                #if j+1 > 1:\n                #    qmax = masses[j] / masses[0]\n\n                lnp += np.log(self.prior('q', q))\n                if not np.isfinite(lnp):\n                    logging.debug('lnp=-inf for q={} (system {})'.format(q,s))\n                    return -np.inf\n\n            i += N[s] + 4\n\n        return lnp\n\n    def prior(self, prop, val, **kwargs):\n        return self._priors[prop](val, **kwargs)\n\n\n    @property\n    def n_params(self):\n        tot = 0\n        for _,n in self.obs.Nstars.items():\n            tot += 4+n\n        return tot\n\n    def mnest_prior(self, cube, ndim, nparams):\n        i = 0\n        for _,n in self.obs.Nstars.items():\n            minmass, maxmass = self.bounds('mass')\n            for j in range(n):\n                cube[i+j] = (maxmass - minmass)*cube[i+j] + minmass\n\n            for j, par in enumerate(['age','feh','distance','AV']):\n                lo, hi = self.bounds(par)\n                cube[i+n+j] = (hi - lo)*cube[i+n+j] + lo\n            i += 4 + n\n\n    def mnest_loglike(self, cube, ndim, nparams):\n        \"\"\"loglikelihood function for multinest\n        \"\"\"\n        return self.lnpost(cube)\n\n    @property\n    def labelstring(self):\n        return '--'.join(['-'.join([n.label for n in l.children]) for l in self.obs.get_obs_leaves()])\n\n    def fit(self, **kwargs):\n        if self.use_emcee:\n            return self.fit_mcmc(**kwargs)\n        else:\n            return self.fit_multinest(**kwargs)\n\n    @property\n    def mnest_basename(self):\n        \"\"\"Full path to basename\n        \"\"\"\n        if not hasattr(self, '_mnest_basename'):\n            s = self.labelstring\n            if s=='0_0':\n                s = 'single'\n            elif s=='0_0-0_1':\n                s = 'binary'\n            elif s=='0_0-0_1-0_2':\n                s = 'triple'\n\n            s = '{}-{}'.format(self.ic.name, s)\n            self._mnest_basename = os.path.join('chains', s+'-')\n\n        if os.path.isabs(self._mnest_basename):\n            return self._mnest_basename\n        else:\n            return os.path.join(self.directory, self._mnest_basename)\n\n    @mnest_basename.setter\n    def mnest_basename(self, basename):\n        if os.path.isabs(basename):\n            self._mnest_basename = basename\n        else:\n            self._mnest_basename = os.path.join('chains', basename)\n\n    def lnpost_polychord(self, theta):\n        phi = [0.0] #nDerived\n        return self.lnpost(theta), phi\n\n    def fit_polychord(self, basename, verbose=False, **kwargs):\n        from .config import POLYCHORD\n        sys.path.append(POLYCHORD)\n        import PyPolyChord.PyPolyChord as PolyChord\n\n        return PolyChord.run_nested_sampling(self.lnpost_polychord,\n                        self.n_params, 0, file_root=basename, **kwargs)\n\n\n    def fit_multinest(self, n_live_points=1000, basename=None,\n                      verbose=True, refit=False, overwrite=False,\n                      test=False,\n                      **kwargs):\n        \"\"\"\n        Fits model using MultiNest, via pymultinest.\n\n        :param n_live_points:\n            Number of live points to use for MultiNest fit.\n\n        :param basename:\n            Where the MulitNest-generated files will live.\n            By default this will be in a folder named `chains`\n            in the current working directory.  Calling this\n            will define a `_mnest_basename` attribute for\n            this object.\n\n        :param verbose:\n            Whether you want MultiNest to talk to you.\n\n        :param refit, overwrite:\n            Set either of these to true if you want to\n            delete the MultiNest files associated with the\n            given basename and start over.\n\n        :param **kwargs:\n            Additional keyword arguments will be passed to\n            :func:`pymultinest.run`.\n\n        \"\"\"\n\n        if basename is not None: #Should this even be allowed?\n            self.mnest_basename = basename\n\n        basename = self.mnest_basename\n        if verbose:\n            logging.info('MultiNest basename: {}'.format(basename))\n\n        folder = os.path.abspath(os.path.dirname(basename))\n        if not os.path.exists(folder):\n            os.makedirs(folder)\n\n\n        #If previous fit exists, see if it's using the same\n        # observed properties\n        prop_nomatch = False\n        propfile = '{}properties.json'.format(basename)\n\n        \"\"\"\n        if os.path.exists(propfile):\n            with open(propfile) as f:\n                props = json.load(f)\n            if set(props.keys()) != set(self.properties.keys()):\n                prop_nomatch = True\n            else:\n                for k,v in props.items():\n                    if np.size(v)==2:\n                        if not self.properties[k][0] == v[0] and \\\n                                self.properties[k][1] == v[1]:\n                            props_nomatch = True\n                    else:\n                        if not self.properties[k] == v:\n                            props_nomatch = True\n\n        if prop_nomatch and not overwrite:\n            raise ValueError('Properties not same as saved chains ' +\n                            '(basename {}*). '.format(basename) +\n                            'Use overwrite=True to fit.')\n        \"\"\"\n\n        if refit or overwrite:\n            files = glob.glob('{}*'.format(basename))\n            [os.remove(f) for f in files]\n\n        short_basename = self._mnest_basename\n\n        mnest_kwargs = dict(n_live_points=n_live_points, outputfiles_basename=short_basename,\n                        verbose=verbose)\n\n        for k,v in kwargs.items():\n            mnest_kwargs[k] = v\n\n        if test:\n            print('pymultinest.run() with the following kwargs: {}'.format(mnest_kwargs))\n        else:\n            wd = os.getcwd()\n            os.chdir(os.path.join(folder, '..'))\n            pymultinest.run(self.mnest_loglike, self.mnest_prior, self.n_params,\n                            **mnest_kwargs)\n            os.chdir(wd)\n            #with open(propfile, 'w') as f:\n            #    json.dump(self.properties, f, indent=2)\n\n            self._make_samples()\n\n    @property\n    def mnest_analyzer(self):\n        \"\"\"\n        PyMultiNest Analyzer object associated with fit.\n\n        See PyMultiNest documentation for more.\n        \"\"\"\n        return pymultinest.Analyzer(self.n_params, self.mnest_basename)\n\n    @property\n    def evidence(self):\n        \"\"\"\n        Log(evidence) from multinest fit\n        \"\"\"\n        s = self.mnest_analyzer.get_stats()\n        return (s['global evidence'],s['global evidence error'])\n\n\n    def maxlike(self, p0, **kwargs):\n        \"\"\" Finds (local) optimum in parameter space.\n        \"\"\"\n        def fn(p):\n            return -self.lnpost(p)\n\n        if 'method' not in kwargs:\n            kwargs['method'] = 'Nelder-Mead'\n\n        p0 = [0.8, 9.5, 0.0, 200, 0.2]\n        fit = scipy.optimize.minimize(fn, p0, **kwargs)\n        return fit\n\n    def sample_from_prior(self, n):\n        return self.emcee_p0(n)\n\n    def emcee_p0(self, nwalkers):\n\n        def sample_row(nstars, n=nwalkers):\n            p = []\n            m0 = self._priors['mass'].sample(n)\n            age0 = self._priors['age'].sample(n)\n            feh0 = self._priors['feh'].sample(n)\n            d0 = self._priors['distance'].sample(n)\n            AV0 = self._priors['AV'].sample(n)\n\n            for i in range(nstars):\n                p += [m0 * 0.95**i]\n            p += [age0, feh0, d0, AV0]\n            return p\n\n        p0 = []\n        for _,n in self.obs.Nstars.items():\n            p0 += sample_row(n)\n\n        p0 = np.array(p0).T\n\n        nbad = 1\n\n        while True:\n            ibad = []\n            for i, p in enumerate(p0):\n                if not np.isfinite(self.lnpost(p)):\n                    ibad.append(i)\n\n            nbad = len(ibad)\n            if nbad == 0:\n                break\n\n            pnew = []\n            for _, n in self.obs.Nstars.items():\n                pnew += sample_row(n, n=nbad)\n\n            pnew = np.array(pnew).T\n\n            p0[ibad, :] = pnew\n\n        return p0\n\n    def fit_mcmc(self,nwalkers=300,nburn=200,niter=100,\n                 p0=None,initial_burn=None,\n                 ninitial=50, loglike_kwargs=None,\n                 **kwargs):\n        \"\"\"Fits stellar model using MCMC.\n\n        :param nwalkers: (optional)\n            Number of walkers to pass to :class:`emcee.EnsembleSampler`.\n            Default is 200.\n\n        :param nburn: (optional)\n            Number of iterations for \"burn-in.\"  Default is 100.\n\n        :param niter: (optional)\n            Number of for-keeps iterations for MCMC chain.\n            Default is 200.\n\n        :param p0: (optional)\n            Initial parameters for emcee.  If not provided, then chains\n            will behave according to whether inital_burn is set.\n\n        :param initial_burn: (optional)\n            If `True`, then initialize walkers first with a random initialization,\n            then cull the walkers, keeping only those with > 15% acceptance\n            rate, then reinitialize sampling.  If `False`, then just do\n            normal burn-in.  Default is `None`, which will be set to `True` if\n            fitting for distance (i.e., if there are apparent magnitudes as\n            properties of the model), and `False` if not.\n\n        :param ninitial: (optional)\n            Number of iterations to test walkers for acceptance rate before\n            re-initializing.\n\n        :param loglike_args:\n            Any arguments to pass to :func:`StarModel.loglike`, such\n            as what priors to use.\n\n        :param **kwargs:\n            Additional keyword arguments passed to :class:`emcee.EnsembleSampler`\n            constructor.\n\n        :return:\n            :class:`emcee.EnsembleSampler` object.\n\n        \"\"\"\n\n        #clear any saved _samples\n        if self._samples is not None:\n            self._samples = None\n\n        npars = self.n_params\n\n        if p0 is None:\n            p0 = self.emcee_p0(nwalkers)\n            if initial_burn:\n                sampler = emcee.EnsembleSampler(nwalkers,npars,self.lnpost,\n                                                **kwargs)\n                #ninitial = 300 #should this be parameter?\n                pos, prob, state = sampler.run_mcmc(p0, ninitial)\n\n                # Choose walker with highest final lnprob to seed new one\n                i,j = np.unravel_index(sampler.lnprobability.argmax(),\n                                        sampler.shape)\n                p0_best = sampler.chain[i,j,:]\n                print(\"After initial burn, p0={}\".format(p0_best))\n                p0 = p0_best * (1 + rand.normal(size=p0.shape)*0.001)\n                print(p0)\n        else:\n            p0 = np.array(p0)\n            p0 = rand.normal(size=(nwalkers,npars))*0.01 + p0.T[None,:]\n\n        sampler = emcee.EnsembleSampler(nwalkers,npars,self.lnpost)\n        pos, prob, state = sampler.run_mcmc(p0, nburn)\n        sampler.reset()\n        sampler.run_mcmc(pos, niter, rstate0=state)\n\n        self._sampler = sampler\n        return sampler\n\n    @property\n    def sampler(self):\n        \"\"\"\n        Sampler object from MCMC run.\n        \"\"\"\n        if hasattr(self,'_sampler'):\n            return self._sampler\n        else:\n            raise AttributeError('MCMC must be run to access sampler')\n\n    def _make_samples(self):\n\n        if not self.use_emcee:\n            filename = '{}post_equal_weights.dat'.format(self.mnest_basename)\n            try:\n                chain = np.loadtxt(filename)\n                try:\n                    lnprob = chain[:,-1]\n                    chain = chain[:,:-1]\n                except IndexError:\n                    lnprob = np.array([chain[-1]])\n                    chain = np.array([chain[:-1]])\n            except:\n                logging.error('Error loading chains from {}'.format(filename))\n                raise\n        else:\n            #select out only walkers with > 0.15 acceptance fraction\n            ok = self.sampler.acceptance_fraction > 0.15\n\n            chain = self.sampler.chain[ok,:,:]\n            chain = chain.reshape((chain.shape[0]*chain.shape[1],\n                                        chain.shape[2]))\n\n            lnprob = self.sampler.lnprobability[ok, :].ravel()\n\n        df = pd.DataFrame()\n\n        i=0\n        for s,n in self.obs.Nstars.items():\n            age = chain[:,i+n]\n            feh = chain[:,i+n+1]\n            distance = chain[:,i+n+2]\n            AV = chain[:,i+n+3]\n            for j in range(n):\n                mass = chain[:,i+j]\n                d = self.ic(mass, age, feh,\n                             distance=distance, AV=AV)\n                for c in d.columns:\n                    df[c+'_{}_{}'.format(s,j)] = d[c]\n            df['age_{}'.format(s)] = age\n            df['feh_{}'.format(s)] = feh\n            df['distance_{}'.format(s)] = distance\n            df['AV_{}'.format(s)] = AV\n\n            i += 4 + n\n\n        for b in self.ic.bands:\n            tot = np.inf\n            for s,n in self.obs.Nstars.items():\n                for j in range(n):\n                    tot = addmags(tot,df[b + '_mag_{}_{}'.format(s,j)])\n            df[b + '_mag'] = tot\n\n        df['lnprob'] = lnprob\n\n        self._samples = df.copy()\n\n    @property\n    def samples(self):\n        \"\"\"Dataframe with samples drawn from isochrone according to posterior\n\n        Columns include both the sampling parameters from the MCMC\n        fit (mass, age, Fe/H, [distance, A_V]), and also evaluation\n        of the :class:`Isochrone` at each of these sample points---this\n        is how chains of physical/observable parameters get produced.\n\n        \"\"\"\n        if not hasattr(self,'sampler') and self._samples is None:\n            raise AttributeError('Must run MCMC (or load from file) '+\n                                 'before accessing samples')\n\n        if self._samples is not None:\n            df = self._samples\n        else:\n            self._make_samples()\n            df = self._samples\n\n        return df\n\n    def random_samples(self, n):\n        \"\"\"\n        Returns a random sampling of given size from the existing samples.\n\n        :param n:\n            Number of samples\n\n        :return:\n            :class:`pandas.DataFrame` of length ``n`` with random samples.\n        \"\"\"\n        samples = self.samples\n        inds = rand.randint(len(samples),size=int(n))\n\n        newsamples = samples.iloc[inds]\n        newsamples.reset_index(inplace=True)\n        return newsamples\n\n    def triangle(self, *args, **kwargs):\n        return self.corner(*args, **kwargs)\n\n    def corner(self, params, query=None, **kwargs):\n        df = self.samples\n        if query is not None:\n            df = df.query(query)\n\n        priors = []\n        for p in params:\n            if re.match('mass', p):\n                priors.append(lambda x: self.prior('mass', x, bounds=self.bounds('mass')))\n            elif re.match('age', p):\n                priors.append(lambda x: self.prior('age', x, bounds=self.bounds('age')))\n            elif re.match('feh', p):\n                priors.append(lambda x: self.prior('feh', x, bounds=self.bounds('feh')))\n            elif re.match('distance', p):\n                priors.append(lambda x: self.prior('distance', x, bounds=self.bounds('distance')))\n            elif re.match('AV', p):\n                priors.append(lambda x: self.prior('AV', x, bounds=self.bounds('AV')))\n            else:\n                priors.append(None)\n\n        try:\n            fig = corner.corner(df[params], labels=params, priors=priors, **kwargs)\n        except:\n            logging.warning(\"Use Tim's version of corner to plot priors.\")\n            fig = corner.corner(df[params], labels=params, **kwargs)\n        fig.suptitle(self.name, fontsize=22)\n        return fig\n\n    def triangle_physical(self, *args, **kwargs):\n        return self.corner_physical(*args, **kwargs)\n\n    def corner_plots(self, basename, **kwargs):\n        fig1, fig2 = self.corner_physical(**kwargs), self.corner_observed(**kwargs)\n        fig1.savefig(basename + '_physical.png')\n        fig2.savefig(basename + '_observed.png')\n        return fig1, fig2\n\n    def triangle_plots(self, *args, **kwargs):\n        return self.corner_plots(*args, **kwargs)\n\n    def corner_physical(self, props=['mass','radius','feh','age','distance','AV'], **kwargs):\n        collective_props = ['feh','age','distance','AV']\n        indiv_props = [p for p in props if p not in collective_props]\n        sys_props = [p for p in props if p in collective_props]\n\n        props = ['{}_{}'.format(p,l) for p in indiv_props for l in self.obs.leaf_labels]\n        props += ['{}_{}'.format(p,s) for p in sys_props for s in self.obs.systems]\n\n        if 'range' not in kwargs:\n            rng = [0.995 for p in props]\n\n        return self.corner(props, range=rng, **kwargs)\n\n    def mag_plot(self, *args, **kwargs):\n        pass\n\n    def corner_observed(self, **kwargs):\n        \"\"\"Makes corner plot for each observed node magnitude\n        \"\"\"\n        tot_mags = []\n        names = []\n        truths = []\n        rng = []\n        for n in self.obs.get_obs_nodes():\n            labels = [l.label for l in n.get_model_nodes()]\n            band = n.band\n            mags = [self.samples['{}_mag_{}'.format(band, l)] for l in labels]\n            tot_mag = addmags(*mags)\n\n            if n.relative:\n                name = '{} $\\Delta${}'.format(n.instrument, n.band)\n                ref = n.reference\n                if ref is None:\n                    continue\n                ref_labels = [l.label for l in ref.get_model_nodes()]\n                ref_mags = [self.samples['{}_mag_{}'.format(band, l)] for l in ref_labels]\n                tot_ref_mag = addmags(*ref_mags)\n                tot_mags.append(tot_mag - tot_ref_mag)\n                truths.append(n.value[0] - ref.value[0])\n            else:\n                name = '{} {}'.format(n.instrument, n.band)\n                tot_mags.append(tot_mag)\n                truths.append(n.value[0])\n\n            names.append(name)\n            rng.append((min(truths[-1], np.percentile(tot_mags[-1],0.5)),\n                        max(truths[-1], np.percentile(tot_mags[-1],99.5))))\n        tot_mags = np.array(tot_mags).T\n\n\n        return corner.corner(tot_mags, labels=names, truths=truths, range=rng, **kwargs)\n\n\n    def save_hdf(self, filename, path='', overwrite=False, append=False):\n        \"\"\"Saves object data to HDF file (only works if MCMC is run)\n\n        Samples are saved to /samples location under given path,\n        :class:`ObservationTree` is saved to /obs location under given path.\n\n        :param filename:\n            Name of file to save to.  Should be .h5 file.\n\n        :param path: (optional)\n            Path within HDF file structure to save to.\n\n        :param overwrite: (optional)\n            If ``True``, delete any existing file by the same name\n            before writing.\n\n        :param append: (optional)\n            If ``True``, then if a file exists, then just the path\n            within the file will be updated.\n        \"\"\"\n        if os.path.exists(filename):\n            with pd.HDFStore(filename) as store:\n                if path in store:\n                    if overwrite:\n                        os.remove(filename)\n                    elif not append:\n                        raise IOError('{} in {} exists.  Set either overwrite or append option.'.format(path,filename))\n\n        if self.samples is not None:\n            self.samples.to_hdf(filename, path+'/samples')\n        else:\n            pd.DataFrame().to_hdf(filename, path+'/samples')\n\n        self.obs.save_hdf(filename, path+'/obs', append=True)\n\n        with pd.HDFStore(filename) as store:\n            # store = pd.HDFStore(filename)\n            attrs = store.get_storer('{}/samples'.format(path)).attrs\n\n            attrs.ic_type = type(self.ic)\n            attrs.ic_bands = list(self.ic.bands)\n            attrs.use_emcee = self.use_emcee\n            if hasattr(self, '_mnest_basename'):\n                attrs._mnest_basename = self._mnest_basename\n\n            attrs._bounds = self._bounds\n            attrs._priors = self._priors\n\n            attrs.name = self.name\n            store.close()\n\n    @classmethod\n    def load_hdf(cls, filename, path='', name=None):\n        \"\"\"\n        A class method to load a saved StarModel from an HDF5 file.\n\n        File must have been created by a call to :func:`StarModel.save_hdf`.\n\n        :param filename:\n            H5 file to load.\n\n        :param path: (optional)\n            Path within HDF file.\n\n        :return:\n            :class:`StarModel` object.\n        \"\"\"\n        if not os.path.exists(filename):\n            raise IOError('{} does not exist.'.format(filename))\n        store = pd.HDFStore(filename)\n        try:\n            samples = store[path+'/samples']\n            attrs = store.get_storer(path+'/samples').attrs\n        except:\n            store.close()\n            raise\n\n        try:\n            ic = attrs.ic_type(attrs.ic_bands)\n        except AttributeError:\n            ic = attrs.ic_type\n\n        use_emcee = attrs.use_emcee\n        mnest = True\n        try:\n            basename = attrs._mnest_basename\n        except AttributeError:\n            mnest = False\n        bounds = attrs._bounds\n        priors = attrs._priors\n\n        if name is None:\n            try:\n                name = attrs.name\n            except:\n                name = ''\n\n        store.close()\n\n        obs = ObservationTree.load_hdf(filename, path+'/obs', ic=ic)\n\n        mod = cls(ic, obs=obs,\n                  use_emcee=use_emcee, name=name)\n        mod._samples = samples\n        if mnest:\n            mod._mnest_basename = basename\n        mod._directory = os.path.dirname(filename)\n        return mod\n\nclass BinaryStarModel(StarModel):\n    _default_name = 'binary'\n    def __init__(self, *args, **kwargs):\n        kwargs['N'] = 2\n        super(BinaryStarModel, self).__init__(*args, **kwargs)\n\n    @classmethod\n    def from_ini(cls, *args, **kwargs):\n        kwargs['N'] = 2\n        return super(BinaryStarModel, cls).from_ini(*args, **kwargs)\n\nclass TripleStarModel(StarModel):\n    _default_name = 'triple'\n    def __init__(self, *args, **kwargs):\n        kwargs['N'] = 3\n        super(TripleStarModel, self).__init__(*args, **kwargs)\n\n    @classmethod\n    def from_ini(cls, *args, **kwargs):\n        kwargs['N'] = 3\n        return super(TripleStarModel, cls).from_ini(*args, **kwargs)\n\nclass StarModelGroup(object):\n    \"\"\"A collection of StarModel objects with different model node specifications\n\n    Pass a single StarModel, and model nodes will be cleared and replaced with\n    different variants.\n    \"\"\"\n    def __init__(self, base_model, max_multiples=1, max_stars=2):\n\n        self.base_model = deepcopy(base_model)\n        self.base_model.obs.clear_models()\n        self.max_multiples = max_multiples\n        self.max_stars = max_stars\n\n        self.models = []\n        for N, index in self.model_options:\n            mod = deepcopy(self.base_model)\n            mod.obs.define_models(self.ic, N=N, index=index)\n            self.models.append(mod)\n\n    @property\n    def ic(self):\n        return self.base_model.ic\n\n    @property\n    def N_stars(self):\n        return len(self.base_model.obs.leaves)\n\n    @property\n    def N_options(self):\n        return N_options(self.N_stars, max_multiples=self.max_multiples,\n                         max_stars=self.max_stars)\n\n    @property\n    def index_options(self):\n        return index_options(self.N_stars)\n\n    @property\n    def model_options(self):\n        return [(N, index) for N in self.N_options for index in self.index_options]\n\n########## Utility functions ###############\n\ndef N_options(N_stars, max_multiples=1, max_stars=2):\n    return [N for N in itertools.product(np.arange(max_stars) + 1, repeat=N_stars)\n            if (np.array(N)>1).sum() <= max_multiples]\n\ndef index_options(N_stars):\n    if N_stars==1:\n        return [0]\n\n    options = []\n    for ind in itertools.product(range(N_stars), repeat=N_stars):\n        diffs = np.array(ind[1:]) - np.array(ind[:-1])\n        if ind[0]==0 and diffs.max()<=1:\n            options.append(ind)\n    return options\n", "meta": {"hexsha": "1377bd3e4032865eec525438b9a1ae4e0a27c213", "size": 42726, "ext": "py", "lang": "Python", "max_stars_repo_path": "isochrones/starmodel.py", "max_stars_repo_name": "smoh/isochrones", "max_stars_repo_head_hexsha": "cfd93aacaf114dfec1676ed0d5de5cd4d5ff85ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "isochrones/starmodel.py", "max_issues_repo_name": "smoh/isochrones", "max_issues_repo_head_hexsha": "cfd93aacaf114dfec1676ed0d5de5cd4d5ff85ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "isochrones/starmodel.py", "max_forks_repo_name": "smoh/isochrones", "max_forks_repo_head_hexsha": "cfd93aacaf114dfec1676ed0d5de5cd4d5ff85ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-15T16:02:37.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-15T16:02:37.000Z", "avg_line_length": 34.4842615012, "max_line_length": 119, "alphanum_fraction": 0.5271497449, "include": true, "reason": "import numpy,import scipy,from scipy,from astropy", "num_tokens": 9785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.18389259319182674}}
{"text": "\"\"\"\nauthor: ouyangtianxiong\ndate: 2019/12/23\ndes: implements attention-based emotion recognition\nBased on code from https://github.com/KaihuaTang/VQA2.0-Recent-Approachs-2018.pytorch\n\"\"\"\nimport sys\nsys.path.append('../')\n__author__ = 'ouyangtianxiong.bupt.edu.cn'\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nfrom torch.nn.utils import clip_grad_norm_\nfrom torch.optim import Adam,SGD\nfrom torch.nn import CrossEntropyLoss\nimport numpy as np\nfrom Common_utils.model_evaluation import plot_acc_loss_curve\nfrom Common_utils.model_training import GradualWarmupScheduler, LabelSmoothSoftmax\nfrom Common_utils.basic_module import FCNet\nimport os\nfrom data_set.seed_iv import SEED_IV, SEED_IV_DATASET\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '2'\ndevice = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\nclass InterModalityUpdate(nn.Module):\n    \"\"\"\n    Inter-Modality Attention Flow\n    \"\"\"\n    def __init__(self, v_size, q_size, output_size, num_head, drop=0.0):\n        super(InterModalityUpdate, self).__init__()\n        self.v_size = v_size\n        self.q_size = q_size\n        self.output_size = output_size\n        self.num_head = num_head\n\n        self.v_lin = FCNet(v_size, output_size * 3, drop=drop)\n        self.q_lin = FCNet(q_size, output_size * 3, drop=drop)\n\n        self.v_output = FCNet(output_size + v_size, output_size, drop=drop)\n        self.q_output = FCNet(output_size + q_size, output_size, drop=drop)\n\n    def forward(self, v, q):\n        \"\"\"\n        :param v: eeg feature [batch, regions, feature_size]\n        :param q: eye feature [batch, regions, feature_size]\n        :return:\n        \"\"\"\n        batch_size, num_obj = v.shape[0], v.shape[1]\n        max_len = q.shape[1]\n\n        # transfer feature to Q, K ,V matrix, here Q, K, V are concat together\n        v_tran = self.v_lin(v)\n        q_tran = self.q_lin(q)\n        # mask all padding object/word feature\n        # split Q, K, V\n        v_key, v_query, v_val = torch.split(v_tran, v_tran.size(2) // 3, dim=2)\n        q_key, q_query, q_val = torch.split(q_tran, q_tran.size(2) // 3, dim=2)\n\n        # apply multi-head\n        v_key_set = torch.split(v_key, v_key.size(2) // self.num_head, dim=2)\n        v_query_set = torch.split(v_query, v_query.size(2) // self.num_head, dim=2)\n        v_val_set = torch.split(v_val, v_val.size(2) // self.num_head, dim=2)\n        q_key_set = torch.split(q_key, q_key.size(2) // self.num_head, dim=2)\n        q_query_set = torch.split(q_query, q_query.size(2) // self.num_head, dim=2)\n        q_val_set = torch.split(q_val, q_val.size(2) // self.num_head, dim=2)\n\n        # apply multi-head operation\n        for i in range(self.num_head):\n            v_key_slice, v_query_slice, v_val_slice = v_key_set[i], v_query_set[i], v_val_set[i]\n            q_key_slice, q_query_slice, q_val_slice = q_key_set[i], q_query_set[i], q_val_set[i]\n            # calculating attention\n            # [batch, num_obj, max_len]\n            #print(v_query_slice.shape, q_key_slice.shape)\n            q2v = (v_query_slice @ q_key_slice.transpose(1, 2)) / ((self.output_size // self.num_head) ** 0.5)\n            #print(q_query_slice.shape, v_key_slice.shape)\n            v2q = (q_query_slice @ v_key_slice.transpose(1, 2)) / ((self.output_size // self.num_head) ** 0.5)\n            # softmax attention\n            interMAF_q2v = F.softmax(q2v, dim=2).unsqueeze(3) #[batch_size, num_obj, max_len, 1]\n            interMAF_v2q = F.softmax(v2q, dim=2).unsqueeze(3) #[batch_size, max_len, num_obj, 1] torch.cat((v_update, (interMAF_q2v * q_val_slice.unsqueeze(1)).sum(2)), dim=2)\n\n            #print(\"inter head {} \\tinterMAF_q2v\\n{}\".format(i, interMAF_q2v.cpu().detach().numpy()))\n            #print(\"inter head {} \\tinterMAF_v2q\\n{}\".format(i, interMAF_v2q.cpu().detach().numpy()))\n            v_update = (interMAF_q2v * q_val_slice.unsqueeze(1)).sum(2) if (i == 0) else  torch.cat((v_update, (interMAF_q2v * q_val_slice.unsqueeze(1)).sum(2)), dim=2)\n            q_update = (interMAF_v2q * v_val_slice.unsqueeze(1)).sum(2) if (i == 0) else torch.cat((q_update, (interMAF_v2q * v_val_slice.unsqueeze(1)).sum(2)), dim=2)\n        # update new feature\n        cat_v = torch.cat((v, v_update), dim=2)\n        cat_q = torch.cat((q, q_update), dim=2)\n        updated_v = self.v_output(cat_v)\n        updated_q = self.q_output(cat_q)\n        return updated_v, updated_q\n\nclass OneSideInterModalityUpdate(nn.Module):\n    \"\"\"\n    one-side Inter-Modality Attention Flow\n    according to the paper, instead of parallel V->Q & Q->V, we first to V->Q and then Q->V\n    \"\"\"\n    def __init__(self,src_size,tgt_size,output_size,num_head,drop=0.0):\n        super(OneSideInterModalityUpdate, self).__init__()\n        self.src_size = src_size\n        self.tgt_size = tgt_size\n        self.output_size = output_size\n        self.num_head = num_head\n\n        self.src_lin = FCNet(src_size, output_size * 2, drop=drop)\n        self.tgt_lin = FCNet(tgt_size, output_size, drop=drop)\n\n        self.tgt_output = FCNet(output_size + tgt_size, output_size, drop=drop)\n\n    def forward(self, src, tgt):\n        \"\"\"\n        :param src: eeg feature [batch, regions, feature_size]\n        :param tgt: eye feature [batch, regions, feature_size]\n        :return:\n        \"\"\"\n        batch_size, num_src = src.shape[0],src.shape[1]\n        num_tgt = tgt.shape[1]\n\n        src_tran = self.src_lin(src)\n        tgt_tran = self.tgt_lin(tgt)\n\n\n        src_key, src_val = torch.split(src_tran, src_tran.size(2) // 2, dim=2)\n        tgt_query = tgt_tran\n        src_key_set = torch.split(src_key, src_key.size(2) // self.num_head, dim=2)\n        src_val_set = torch.split(src_val, src_val.size(2) // self.num_head, dim=2)\n        tgt_query_set = torch.split(tgt_query,tgt_query.size(2) // self.num_head, dim=2)\n        for i in range(self.num_head):\n            src_key_slice, tgt_query_slice, src_val_slice = src_key_set[i], tgt_query_set[i], src_val_set[i]\n            src2tgt = (tgt_query_slice @ src_key_slice.transpose(1, 2)) / ((self.output_size // self.num_head) ** 0.5)\n            interMAF_src2tgt = F.softmax(src2tgt, dim=2).unsqueeze(3)\n            tgt_update = (interMAF_src2tgt * src_val_slice.unsqueeze(1)).sum(2) if (i == 0) else torch.cat((tgt_update, (interMAF_src2tgt * src_val_slice.unsqueeze(1)).sum(2)), dim=2)\n        cat_tgt = torch.cat((tgt, tgt_update), dim=2)\n        tgt_updated = self.tgt_output(cat_tgt)\n        return tgt_updated\n\nclass DyIntraModalityUpdate(nn.Module):\n    \"\"\"\n    Dynamic Intra-Modality Attention Flow\n    \"\"\"\n    def __init__(self, v_size, q_size, output_size, num_head, drop=0.0):\n        super(DyIntraModalityUpdate, self).__init__()\n        self.v_size = v_size\n        self.q_size = q_size\n        self.output_size = output_size\n        self.num_head = num_head\n\n        self.v4q_gate_lin = FCNet(v_size, output_size, drop=drop)\n        self.q4v_gate_lin = FCNet(q_size, output_size, drop=drop)\n\n        self.v_lin = FCNet(v_size, output_size * 3, drop=drop)\n        self.q_lin = FCNet(q_size, output_size * 3, drop=drop)\n\n        self.v_output = FCNet(output_size, output_size, drop=drop)\n        self.q_output = FCNet(output_size, output_size, drop=drop)\n\n        self.relu = nn.ReLU()\n        self.tanh = nn.Tanh()\n        self.sigmoid = nn.Sigmoid()\n\n    def forward(self, v, q):\n        \"\"\"\n        :param v: [batch_size, num_obj, feature_size]\n        :param q: [batch_size, max_len, feature_size]\n\n        :return:\n        \"\"\"\n        batch_size, num_obj = v.shape[0], v.shape[1]\n        max_len = q.shape[1]\n\n        # conditioned gating vector\n        v_mean = v.sum(1) / num_obj\n        q_mean = q.sum(1) / max_len\n\n        v4q_gate = self.sigmoid(self.v4q_gate_lin(v_mean)).unsqueeze(1) # [batch_size, 1, feature_size]\n        q4v_gate = self.sigmoid(self.q4v_gate_lin(q_mean)).unsqueeze(1) # [batch_size, 1, feature_size]\n\n        # K, Q, V\n        v_tran = self.v_lin(v)\n        q_tran = self.q_lin(q)\n\n        # split for different use\n        v_key, v_query, v_val = torch.split(v_tran, v_tran.size(2) // 3, dim=2)\n        q_key, q_query, q_val = torch.split(q_tran, q_tran.size(2) // 3, dim=2)\n\n        # apply conditioned gate\n        gated_v_query = (1 + q4v_gate) * v_query\n        gated_v_key = (1 + q4v_gate) * v_key\n        gated_v_val = (1 + q4v_gate) * v_val\n        gated_q_query = (1 + v4q_gate) * q_query\n        gated_q_key = (1 + v4q_gate) * q_key\n        gated_q_val = (1 + v4q_gate) * q_val\n\n        # apply multi-head\n        v_key_set = torch.split(gated_v_key, gated_v_key.size(2) // self.num_head, dim=2)\n        v_query_set = torch.split(gated_v_query, gated_v_query.size(2) // self.num_head, dim=2)\n        v_val_set = torch.split(gated_v_val, gated_v_val.size(2) // self.num_head, dim=2)\n        q_key_set = torch.split(gated_q_key, gated_q_key.size(2) // self.num_head, dim=2)\n        q_query_set = torch.split(gated_q_query, gated_q_query.size(2) // self.num_head, dim=2)\n        q_val_set = torch.split(gated_q_val, gated_q_val.size(2) // self.num_head, dim=2)\n\n        for i in range(self.num_head):\n            v_key_slice, v_query_slice, v_val_slice = v_key_set[i], v_query_set[i], v_val_set[i]\n            q_key_slice, q_query_slice, q_val_slice = q_key_set[i], q_query_set[i], q_val_set[i]\n            # calcuating attention\n            v2v = (v_query_slice @ v_key_slice.transpose(1,2)) / ((self.output_size // self.num_head) ** 0.5)\n            q2q = (q_query_slice @ q_key_slice.transpose(1,2)) / ((self.output_size // self.num_head) ** 0.5)\n            dyIntranMAF_v2v = F.softmax(v2v, dim=2).unsqueeze(3) # [batch_size, num_obj, num_obj, 1]\n            dyIntranMAF_q2q = F.softmax(q2q, dim=2).unsqueeze(3) # [batch_size, max_len, max_len, 1]\n            # calculating update input\n            #print(\"intra head {} \\tinterMAF_q2v\\n{}\".format(i, dyIntranMAF_v2v.cpu().detach().numpy()))\n            #print(\"intra head {} \\tinterMAF_v2q\\n{}\".format(i, dyIntranMAF_q2q.cpu().detach().numpy()))\n            v_update = (dyIntranMAF_v2v * v_val_slice.unsqueeze(1)).sum(2) if (i == 0) else torch.cat((v_update, (dyIntranMAF_v2v * v_val_slice.unsqueeze(1)).sum(2)), dim=2)\n            q_update = (dyIntranMAF_q2q * q_val_slice.unsqueeze(1)).sum(2) if (i == 0) else torch.cat((q_update, (dyIntranMAF_q2q * q_val_slice.unsqueeze(1)).sum(2)), dim=2)\n\n        # update\n        updated_v = self.v_output(v + v_update)\n        updated_q = self.q_output(q + q_update)\n        return updated_v, updated_q\n\nclass SingleBlock(nn.Module):\n    \"\"\"\n        Single Block Inter- and Intra modality stack multiple times, in such circumstance, all the\n        basic blocks share the same parameters in the model\n    \"\"\"\n    def __init__(self, num_blocks, v_size, q_size, output_size, num_inter_head, num_intra_head, drop=0.0):\n        super(SingleBlock, self).__init__()\n        self.v_size = v_size\n        self.q_size = q_size\n        self.output_size = output_size\n        self.num_inter_head = num_inter_head\n        self.num_intra_head = num_intra_head\n        self.num_block = num_blocks\n\n        self.v_lin = FCNet(v_size, output_size, drop=drop)\n        self.q_lin = FCNet(q_size, output_size, drop=drop)\n\n        self.v2q_interBlock = OneSideInterModalityUpdate(output_size, output_size, output_size, num_inter_head, drop)\n        self.q2v_interBlock = OneSideInterModalityUpdate(output_size, output_size, output_size, num_inter_head, drop)\n        self.intraBlock = DyIntraModalityUpdate(output_size, output_size, output_size, num_intra_head, drop)\n\n    def forward(self, v, q):\n        \"\"\"\n        :param v: eeg feature [batch_size, regions, feature_size]\n        :param q: eye feature [batch_size, regions, feature_size]\n        :return:\n        \"\"\"\n        # transfer features\n        v = self.v_lin(v)\n        q = self.q_lin(q)\n        # residual connection\n        v_container = [v]\n        q_container = [q]\n        result_v = [v]\n        result_q = [q]\n        for i in range(self.num_block):\n            q1 = self.v2q_interBlock(v_container[-1], q_container[-1])\n            q_container.append(q1)\n            v1 = self.q2v_interBlock(q_container[-1], v_container[-1])\n            v_container.append(v1)\n            v2, q2 = self.intraBlock(v_container[-1] + v_container[-2], q_container[-1] + q_container[-2])\n            v_container.append(v2)\n            q_container.append(q2)\n            result_v.append(v1)\n            result_v.append(v2)\n            result_q.append(q1)\n            result_q.append(q2)\n            v_container.append(v_container[-1] + v_container[-2] + v_container[-3])\n            q_container.append(q_container[-1] + q_container[-2] + q_container[-3])\n        return sum(result_v), sum(result_q)\n\nclass MultiBlocks(nn.Module):\n    \"\"\"\n    Stack multiple single block layer, each layer possess their own parameters\n    \"\"\"\n\n    def __init__(self, num_blocks, v_size, q_size, output_size, num_inter_head, num_intra_head, drop=0.0):\n        super(MultiBlocks, self).__init__()\n        self.v_size = v_size\n        self.q_size = q_size\n        self.output_size = output_size\n        self.num_inter_head = num_inter_head\n        self.num_intra_head = num_intra_head\n        self.num_blocks = num_blocks\n\n        self.v_lin = FCNet(v_size, output_size, drop=drop)\n        self.q_lin = FCNet(q_size, output_size, drop=drop)\n\n        blocks = []\n        for i in range(self.num_blocks):\n            #blocks.append(OneSideInterModalityUpdate(output_size, output_size, output_size, num_inter_head, drop))\n            #blocks.append(OneSideInterModalityUpdate(output_size, output_size, output_size, num_inter_head, drop))\n            blocks.append(InterModalityUpdate(output_size, output_size, output_size, num_inter_head, drop))\n            blocks.append(DyIntraModalityUpdate(output_size, output_size, output_size, num_intra_head, drop))\n        self.multi_blocks = nn.ModuleList(blocks)\n\n    def forward(self, v, q):\n        \"\"\"\n        :param v: eeg feature [batch, regions, feature_size]\n        :param q: eye feature [batch, regions, feature_size]\n        :return:\n        \"\"\"\n        # transfer feature\n        v = self.v_lin(v)\n        q = self.q_lin(q)\n        v_container = [v]\n        q_container = [q]\n        result_v = [v]\n        result_q = [q]\n\n        # dense residule connection\n        for i in range(self.num_blocks):\n            # q1 = self.multi_blocks[i * 3 + 0](v_container[-1], q_container[-1])\n            # q_container.append(q1)\n            # v1 = self.multi_blocks[i * 3 + 1](q_container[-1], v_container[-1])\n            # v_container.append(v1)\n            v1, q1 = self.multi_blocks[i * 2 + 0](v_container[-1], q_container[-1])\n            q_container.append(q1)\n            v_container.append(v1)\n            v2, q2 = self.multi_blocks[i * 2 + 1](v_container[-1] + v_container[-2], q_container[-1] + q_container[-2])\n            v_container.append(v2)\n            q_container.append(q2)\n            result_v.append(v1)\n            result_v.append(v2)\n            result_q.append(q1)\n            result_q.append(q2)\n            v_container.append(v_container[-1] + v_container[-2] + v_container[-3])\n            q_container.append(q_container[-1] + q_container[-2] + q_container[-3])\n        return sum(result_v), sum(result_q)\n\nclass EEGFeatureExtractor(nn.Module):\n    def __init__(self, eeg_size, output_size):\n        super(EEGFeatureExtractor, self).__init__()\n        self.eeg_size = eeg_size\n        self.output_size = output_size\n        self.regions = 16  # regions的数量\n        self.regions_indexs = [torch.LongTensor(e) for e in\n                               [[3, 0, 1, 2, 4], [7, 8, 9, 10, 11], [5, 6], [13, 12], [14, 15, 23, 24, 32, 33],\n                                [22, 21, 31, 30, 40, 39], [16, 17, 18, 19, 20], [25, 26, 27, 28, 29],\n                                [34, 35, 36, 37, 38], [41, 42], [49, 48], [43, 44, 45, 46, 47],\n                                [50, 51, 57], [56, 55, 61], [52, 53, 54], [58, 59, 60]]]\n        reginal_extractors = []\n        for i in range(self.regions):\n            reginal_extractors.append(nn.LSTM(input_size=eeg_size, hidden_size= output_size // 2, batch_first=True, bias=True, bidirectional=True))\n\n        self.reginalFeatureExtractors = nn.ModuleList(reginal_extractors)\n        self.bn = nn.BatchNorm1d(num_features=self.regions)\n\n\n    def forward(self, x):\n        \"\"\"\n        :param x: [batch, n_electrode, 5]\n        :return: [batch, regions, feature_size]\n        \"\"\"\n        batch, n_electrode, _ = x.shape\n        X_regions_input = []  # 列表存储不同区域的张量输入\n        for i in range(self.regions):\n            X_regions_input.append(x.index_select(dim=1, index=self.regions_indexs[i].to(device)))\n        X_regional_lstm_out = []\n        for i in range(self.regions):\n            shape = X_regions_input[i].shape\n            # print(shape)\n            # 先转成（B*T,n_i,d）再进LSTM\n            hidden_units, _ = self.reginalFeatureExtractors[i](X_regions_input[i].reshape((-1, shape[-2], shape[-1])))\n            X_regional_lstm_out.append(hidden_units[:, -1, :].squeeze())\n        # X_regional_feature : 列表：元素为tensor [ B*T, regions_num, 2*self.d_r]\n        # reshape成(B*T, regions, 2*self.d_r)\n        # (B * T, regions, 2* self.d_r)\n        X_regional_feature = torch.cat(X_regional_lstm_out, dim=-1).reshape(batch, self.regions, self.output_size)\n        return self.bn(X_regional_feature)\n\n\nclass EYEFeatureExtractor(nn.Module):\n    def __init__(self, eye_size, output_size):\n        super(EYEFeatureExtractor, self).__init__()\n        self.eye_size = eye_size\n        self.output_size = output_size\n        self.regions = 5\n        self.regions_indexs = [torch.LongTensor(e) for e in\n                               [[0,1,2,3,4,5,6,7,8,9,10,11],\n                                [12,13,14,15],\n                                [16,17],\n                                [18,19,20,21],\n                                [22,23,24,25,26,27,28,29,30]]]\n\n        eye_extractor = []\n        eye_extractor.append(FCNet(in_size=12, out_size=output_size, activate='relu'))\n        eye_extractor.append(FCNet(in_size=4, out_size=output_size, activate='relu'))\n        eye_extractor.append(FCNet(in_size=2, out_size=output_size, activate='relu'))\n        eye_extractor.append(FCNet(in_size=4, out_size=output_size, activate='relu'))\n        eye_extractor.append(FCNet(in_size=9, out_size=output_size, activate='relu'))\n        self.eyeFeatureExtractor = nn.ModuleList(eye_extractor)\n        self.bn = nn.BatchNorm1d(num_features=self.regions)\n\n    def forward(self, x):\n        \"\"\"\n        :param x: EYE feature [batch, 31]\n        :return: [batch, regons, output_size]\n        \"\"\"\n        B = x.shape[0]\n        X_regional_output = []\n        for i in range(self.regions):\n            X_regional_output.append(self.eyeFeatureExtractor[i](x.index_select(dim=1, index=self.regions_indexs[i].to(device))))\n        X_regional_feature = torch.cat(X_regional_output, dim=-1).reshape(B, self.regions, self.output_size)\n        return self.bn(X_regional_feature)\n\n\nclass Classifier(nn.Sequential):\n    def __init__(self, in_features, mid_features, out_features, drop=0.0):\n        super(Classifier, self).__init__()\n        # define number of detector for each sentiment class\n        self.lin1 = FCNet(in_features, mid_features, activate='relu', drop=drop)\n        self.lin2 = FCNet(mid_features, out_features, drop=drop)\n        #\n        self.bilinear = nn.Bilinear(in1_features=in_features, in2_features=in_features, out_features=in_features)\n    def forward(self, v, q):\n        \"\"\"\n        :param v: [batch, r1, features]\n        :param q: [batch, r2, features]\n        :return:\n        \"\"\"\n        num_obj = v.shape[2]\n        max_len = q.shape[2]\n\n        v_mean = v.sum(1) / num_obj\n        q_mean = q.sum(1) / max_len\n        #print(\"classifier v_mean\", v_mean[0])\n        #print(\"classifier q_mean\", q_mean[0])\n\n        #out = self.lin1(v_mean * q_mean)\n        out = self.lin1(self.bilinear(v_mean, q_mean))\n        #print(\"classifier out 1\", out[0])\n        out = self.lin2(out)\n        #print(\"classifier out 2\", out[0])\n        return out\nclass Hierarchical_ATTN(nn.Module):\n    def __init__(self):\n        super(Hierarchical_ATTN, self).__init__()\n        self.eye_features = 16 # 256\n        self.eeg_features = 16 # 256\n        self.hidden_feature = 32 # 256\n        self.num_inter_head = 4\n        self.num_intra_head = 4\n        self.num_block = 1\n\n        assert self.hidden_feature % self.num_inter_head == 0, 'hidden features size can not be divided by header nums, please check!!'\n        assert self.hidden_feature % self.num_inter_head == 0, 'hidden features size can not be divided by header nums, please check!!'\n\n        # basic feature extractor\n        self.eegFeatureExtractor = EEGFeatureExtractor(eeg_size=5, output_size=self.eeg_features)\n\n        self.eyeFeatureExtractor = EYEFeatureExtractor(eye_size=31, output_size=self.eeg_features)\n\n        # inter- & intra-modality attention flow mechanism for fusion cross modality feature\n        self.interIntraBlocks = MultiBlocks(\n            num_blocks=self.num_block,\n            v_size=self.eeg_features,\n            q_size=self.eye_features,\n            output_size=self.hidden_feature,\n            num_inter_head=self.num_inter_head,\n            num_intra_head=self.num_intra_head,\n            drop=0.1\n        )\n\n        # emotion classifier\n        self.classifier = Classifier(\n            in_features=self.hidden_feature,\n            mid_features=512, out_features=4,\n            drop=0.5)\n        # self.classifier = Senti_Map_Classifier(\n        #     in_features=self.hidden_feature,\n        #     mid_features=256, out_features=4,\n        #     drop=0.5)\n    def forward(self, v, q):\n        \"\"\"\n        :param v: eeg feature [batch, n, 5]\n        :param q:  eye feature [batch, 31]\n        :return: predict logits [batch, max_answer]\n        \"\"\"\n        # prepare v & q feature\n\n        v = self.eegFeatureExtractor(v)\n        q = self.eyeFeatureExtractor(q)\n\n        # feature normalization\n        v = v / (v.norm(p=2, dim=2, keepdim=True) + 1e-12).expand_as(v) # [batch, num_obj, feature]\n        q = q / (q.norm(p=2, dim=2, keepdim=True) + 1e-12).expand_as(q)\n\n        # inter- & intra- modality attention flow\n        v, q = self.interIntraBlocks(v, q)\n\n        # predict logits\n        answer = self.classifier(v, q)\n        return answer\n\ndef main(session=1, mode='subject_dependent'):\n    os.environ['CUDA_VISIBLE_DEVICES'] = '2'\n    # prepare data\n    session = session\n    balance = False\n    shuffle = False\n    modal = 'concat'\n    nor_method = 1\n    label_smooth = 0.1\n    fine_tuning = True\n\n    # reading the data in the whole dataset\n    all_individual_data = []\n    for i in range(1, 16):\n        print(\"contructing dataset...\")\n        eeg = SEED_IV(session=session, individual=i, modal=modal, shuffle=shuffle, balance=balance,\n                      normalization=nor_method)\n        _train_X, _train_Y = eeg.get_train_data()\n        _test_X, _test_Y = eeg.get_test_data()\n        all_individual_data.append([(_train_X, _train_Y), (_test_X, _test_Y)])\n\n    # Hyper-parameters\n    device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n    epochs = 120\n    batch_size = 128\n    learning_rate = 1e-3\n    criterion = LabelSmoothSoftmax(lb_smooth=label_smooth)\n    for idx in range(1, 16):\n        if mode == 'subject_dependent':\n            train_X, train_Y = all_individual_data[idx-1][0][0], all_individual_data[idx-1][0][1]\n            test_X, test_Y = all_individual_data[idx-1][1][0], all_individual_data[idx-1][1][1]\n            exp_des = \"%d_dependent_in_seesion_%d_%s_%s_%s_%d_%d\" % (\n                idx, session, 'balance' if balance else 'without_balance',\n                'shuffle' if shuffle else \"without_shuffle\", 'seed', epochs, batch_size)\n            print(\"starting subject-dependent training experiments on individual %d in session %d\"% (idx, session))\n        elif mode == 'subject_independent':\n            train_X = np.vstack([np.vstack((e[0][0], e[1][0])) for i, e in enumerate(all_individual_data) if i != idx-1])\n            train_Y = np.hstack([np.hstack((e[0][1], e[1][1])) for i, e in enumerate(all_individual_data) if i != idx-1])\n            test_X = np.vstack((all_individual_data[idx-1][0][0], all_individual_data[idx-1][1][0]))\n            test_Y = np.hstack((all_individual_data[idx-1][0][1], all_individual_data[idx-1][1][1]))\n            exp_des = \"%d_independent_as_testset_in_seesion_%d_%s_%s_%s_%d_%d\" % (\n                idx, session, 'balance' if balance else 'without_balance',\n                'shuffle' if shuffle else \"without_shuffle\", 'seed', epochs, batch_size)\n            print(\"starting subject-independent training experiments with individual %d in session %d as test set\" % (idx, session))\n        else:\n            raise ValueError\n\n        print(\"train_X shape\", train_X.shape)\n        print(\"train_Y shape\", train_Y.shape)\n        print(\"test_X shape\", test_X.shape)\n        print(\"test_Y shape\", test_Y.shape)\n        train_loader = DataLoader(dataset=SEED_IV_DATASET(train_X, train_Y), batch_size=batch_size, shuffle=shuffle,\n                                  num_workers=4)\n        test_loader = DataLoader(dataset=SEED_IV_DATASET(test_X, test_Y), batch_size=batch_size, shuffle=shuffle,\n                                 num_workers=4)\n\n        print(\"model construction...\")\n        net = Hierarchical_ATTN()\n        # if fine_tuning we continue train the pretrained model\n        if mode == 'subject_dependent' and fine_tuning:\n            load_path = \"../../saved_models/%s/session_%d/subject_%d_as_testset\" % (net.__class__.__name__, session, idx)\n            files = os.listdir(load_path)\n            best_model = max(files)\n            checkpoint = torch.load(os.path.join(load_path, best_model))\n            net.load_state_dict(checkpoint['net'])\n            learning_rate = 1e-5\n            batch_size = train_X.shape[0]\n\n        net = net.to(device)\n        save_model_path = '../../saved_models/%s/session_%d/subject_%d_as_testset' % (\n        net.__class__.__name__, session, idx) if mode == 'subject_independent' else '../../saved_models/%s/session_%d/subject_%d' % (\n        net.__class__.__name__, session, idx)\n        if not os.path.exists(save_model_path):\n            os.makedirs(save_model_path)\n        optimization = Adam(net.parameters(), lr=learning_rate, weight_decay=0.001)\n\n        # save model training state\n        running_loss_list = []\n        running_acc_list = []\n        testing_loss_list =[]\n        testing_acc_list = []\n        best_acc = -1\n        print(\"start training...\")\n        scheduler_cosine = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer=optimization, T_max=epochs)\n        scheduler_warmup = GradualWarmupScheduler(optimizer=optimization, multiplier=10,\n                                                        total_epoch=np.ceil(0.1 * epochs),\n                                                        after_scheduler=scheduler_cosine)\n        for epoch in range(epochs):\n            net.train()\n            running_loss = 0.0\n            correct = 0.0\n            total = 0.0\n            for i, (feature, target) in enumerate(train_loader):\n                optimization.zero_grad()\n                #print(\"脏数据统计\", torch.sum(torch.isnan(feature), dim=0))\n                eeg = feature[:, :310]\n                eye = feature[:, 310:]\n                eeg = eeg.reshape(-1, 62, 5)\n                eeg = eeg.to(device)\n                eye = eye.to(device)\n                target = target.type(torch.LongTensor).to(device)\n                out = net(eeg, eye)\n                #print(\"batch output\",out[0])\n                cross_entropy_loss = criterion(out, target)\n                cross_entropy_loss.backward()\n                clip_grad_norm_(net.parameters(), max_norm=10)\n                optimization.step()\n                running_loss += cross_entropy_loss.item()\n                #print(\"batch loss\", loss.item())\n                _, prediction = torch.max(out.data, dim=-1)\n                total += target.size(0)\n                correct += prediction.eq(target.data).cpu().sum()\n            cur_loss = running_loss / len(train_loader)\n            cur_acc = correct / total\n            if isinstance(cur_acc, torch.Tensor):\n                cur_acc = cur_acc.item()\n            if isinstance(cur_loss, torch.Tensor):\n                cur_loss = cur_loss.item()\n            print('Loss: %.10f | Acc: %.3f%% (%d/%d)' % (\n                cur_loss, 100 * cur_acc, correct, total))\n            running_loss_list.append(cur_loss)\n            running_acc_list.append(cur_acc)\n            scheduler_warmup.step()\n            if epoch % 1 == 0:\n                net.eval()\n                print(\"start evaluating...\")\n                testing_loss = 0.0\n                test_correct = 0.0\n                test_total = 0.0\n                for i, (feature, target) in enumerate(test_loader):\n                    eeg = feature[:, :310]\n                    eye = feature[:, 310:]\n                    eeg = eeg.reshape(-1, 62, 5)\n                    eeg = eeg.to(device)\n                    eye = eye.to(device)\n                    target = target.type(torch.LongTensor).to(device)\n                    with torch.no_grad():\n                        out = net(eeg, eye)\n                        loss = criterion(out, target)\n                        testing_loss += loss.item()\n                        _, prediction = torch.max(out.data, dim=-1)\n                        # print(prediction)\n                        test_total += target.size(0)\n                        test_correct += prediction.eq(target.data).cpu().sum()\n                test_acc = test_correct / test_total\n                test_loss = testing_loss / len(test_loader)\n                if isinstance(test_acc, torch.Tensor):\n                    test_acc = test_acc.item()\n                if isinstance(test_loss, torch.Tensor):\n                    test_loss = test_loss.item()\n                print('Testset Loss: %.10f | Acc: %.3f%% (%d/%d)' % (\n                    test_loss, 100 * test_acc, test_correct, test_total))\n                testing_acc_list.append(test_acc)\n                testing_loss_list.append(test_loss)\n                if test_acc > best_acc:\n                    best_acc = test_acc\n                    print(\"better model founded in testsets, start saving new model\")\n                    model_name = '%s_%s' % (net.__class__.__name__, str(best_acc)[2:6])\n                    state = {\n                        'net': net.state_dict(),\n                        'epoch': epoch,\n                        'best_acc': best_acc,\n                        'current_loss': test_loss\n                    }\n                    torch.save(state, os.path.join(save_model_path, model_name))\n        plot_acc_loss_curve({'train_loss': running_loss_list,\n                            'train_acc': running_acc_list,\n                            'test_loss': testing_loss_list,\n                            'test_acc': testing_acc_list}, net.__class__.__name__, exp_des)\nif __name__ == '__main__':\n    for mode in ['subject_independent','subject_dependent']:\n        for session in range(1, 4):\n            main(session, mode)\n    # main(1, 'subject_dependent')\n    print(\"experiment done!\")\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "108fdb3150db2444ffca1ea925f5b9ec69b4a772", "size": 31407, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/OYTX_Recog/Hierarchical_Attn.py", "max_stars_repo_name": "Ruiver/CTCNet", "max_stars_repo_head_hexsha": "539e55ec9fed06028379d35dfd5cd4074755ffd8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-09-17T06:30:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T14:19:23.000Z", "max_issues_repo_path": "src/OYTX_Recog/Hierarchical_Attn.py", "max_issues_repo_name": "Ruiver/CTCNet", "max_issues_repo_head_hexsha": "539e55ec9fed06028379d35dfd5cd4074755ffd8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/OYTX_Recog/Hierarchical_Attn.py", "max_forks_repo_name": "Ruiver/CTCNet", "max_forks_repo_head_hexsha": "539e55ec9fed06028379d35dfd5cd4074755ffd8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-09-21T13:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-30T07:32:05.000Z", "avg_line_length": 46.1867647059, "max_line_length": 183, "alphanum_fraction": 0.6064889993, "include": true, "reason": "import numpy", "num_tokens": 8191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.34864514886966624, "lm_q1q2_score": 0.18384634779510403}}
{"text": "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"A Transformed Distribution class.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\n# Bijectors must be directly imported because `remove_undocumented` prevents\n# individual file imports.\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import check_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops.distributions import distribution as distribution_lib\nfrom tensorflow.python.ops.distributions import identity_bijector\nfrom tensorflow.python.ops.distributions import util as distribution_util\n\n__all__ = [\n    \"TransformedDistribution\",\n]\n\n\n# The following helper functions attempt to statically perform a TF operation.\n# These functions make debugging easier since we can do more validation during\n# graph construction.\n\n\ndef _static_value(x):\n  \"\"\"Returns the static value of a `Tensor` or `None`.\"\"\"\n  return tensor_util.constant_value(ops.convert_to_tensor(x))\n\n\ndef _logical_and(*args):\n  \"\"\"Convenience function which attempts to statically `reduce_all`.\"\"\"\n  args_ = [_static_value(x) for x in args]\n  if any(x is not None and not bool(x) for x in args_):\n    return constant_op.constant(False)\n  if all(x is not None and bool(x) for x in args_):\n    return constant_op.constant(True)\n  if len(args) == 2:\n    return math_ops.logical_and(*args)\n  return math_ops.reduce_all(args)\n\n\ndef _logical_equal(x, y):\n  \"\"\"Convenience function which attempts to statically compute `x == y`.\"\"\"\n  x_ = _static_value(x)\n  y_ = _static_value(y)\n  if x_ is None or y_ is None:\n    return math_ops.equal(x, y)\n  return constant_op.constant(np.array_equal(x_, y_))\n\n\ndef _logical_not(x):\n  \"\"\"Convenience function which attempts to statically apply `logical_not`.\"\"\"\n  x_ = _static_value(x)\n  if x_ is None:\n    return math_ops.logical_not(x)\n  return constant_op.constant(np.logical_not(x_))\n\n\ndef _concat_vectors(*args):\n  \"\"\"Convenience function which concatenates input vectors.\"\"\"\n  args_ = [_static_value(x) for x in args]\n  if any(x_ is None for x_ in args_):\n    return array_ops.concat(args, 0)\n  return constant_op.constant([x_ for vec_ in args_ for x_ in vec_])\n\n\ndef _pick_scalar_condition(pred, cond_true, cond_false):\n  \"\"\"Convenience function which chooses the condition based on the predicate.\"\"\"\n  # Note: This function is only valid if all of pred, cond_true, and cond_false\n  # are scalars. This means its semantics are arguably more like tf.cond than\n  # tf.select even though we use tf.select to implement it.\n  pred_ = _static_value(pred)\n  if pred_ is None:\n    return array_ops.where(pred, cond_true, cond_false)\n  return cond_true if pred_ else cond_false\n\n\ndef _ones_like(x):\n  \"\"\"Convenience function attempts to statically construct `ones_like`.\"\"\"\n  # Should only be used for small vectors.\n  if x.get_shape().is_fully_defined():\n    return array_ops.ones(x.get_shape().as_list(), dtype=x.dtype)\n  return array_ops.ones_like(x)\n\n\ndef _ndims_from_shape(shape):\n  \"\"\"Returns `Tensor`'s `rank` implied by a `Tensor` shape.\"\"\"\n  if shape.get_shape().ndims not in (None, 1):\n    raise ValueError(\"input is not a valid shape: not 1D\")\n  if not shape.dtype.is_integer:\n    raise TypeError(\"input is not a valid shape: wrong dtype\")\n  if shape.get_shape().is_fully_defined():\n    return constant_op.constant(shape.get_shape().as_list()[0])\n  return array_ops.shape(shape)[0]\n\n\ndef _is_scalar_from_shape(shape):\n  \"\"\"Returns `True` `Tensor` if `Tensor` shape implies a scalar.\"\"\"\n  return _logical_equal(_ndims_from_shape(shape), 0)\n\n\nclass TransformedDistribution(distribution_lib.Distribution):\n  \"\"\"A Transformed Distribution.\n\n  A `TransformedDistribution` models `p(y)` given a base distribution `p(x)`,\n  and a deterministic, invertible, differentiable transform, `Y = g(X)`. The\n  transform is typically an instance of the `Bijector` class and the base\n  distribution is typically an instance of the `Distribution` class.\n\n  A `Bijector` is expected to implement the following functions:\n  - `forward`,\n  - `inverse`,\n  - `inverse_log_det_jacobian`.\n  The semantics of these functions are outlined in the `Bijector` documentation.\n\n  We now describe how a `TransformedDistribution` alters the input/outputs of a\n  `Distribution` associated with a random variable (rv) `X`.\n\n  Write `cdf(Y=y)` for an absolutely continuous cumulative distribution function\n  of random variable `Y`; write the probability density function `pdf(Y=y) :=\n  d^k / (dy_1,...,dy_k) cdf(Y=y)` for its derivative wrt to `Y` evaluated at\n  `y`. Assume that `Y = g(X)` where `g` is a deterministic diffeomorphism,\n  i.e., a non-random, continuous, differentiable, and invertible function.\n  Write the inverse of `g` as `X = g^{-1}(Y)` and `(J o g)(x)` for the Jacobian\n  of `g` evaluated at `x`.\n\n  A `TransformedDistribution` implements the following operations:\n\n    * `sample`\n      Mathematically:   `Y = g(X)`\n      Programmatically: `bijector.forward(distribution.sample(...))`\n\n    * `log_prob`\n      Mathematically:   `(log o pdf)(Y=y) = (log o pdf o g^{-1})(y)\n                         + (log o abs o det o J o g^{-1})(y)`\n      Programmatically: `(distribution.log_prob(bijector.inverse(y))\n                         + bijector.inverse_log_det_jacobian(y))`\n\n    * `log_cdf`\n      Mathematically:   `(log o cdf)(Y=y) = (log o cdf o g^{-1})(y)`\n      Programmatically: `distribution.log_cdf(bijector.inverse(x))`\n\n    * and similarly for: `cdf`, `prob`, `log_survival_function`,\n     `survival_function`.\n\n  A simple example constructing a Log-Normal distribution from a Normal\n  distribution:\n\n  ```python\n  ds = tf.contrib.distributions\n  log_normal = ds.TransformedDistribution(\n    distribution=ds.Normal(loc=0., scale=1.),\n    bijector=ds.bijectors.Exp(),\n    name=\"LogNormalTransformedDistribution\")\n  ```\n\n  A `LogNormal` made from callables:\n\n  ```python\n  ds = tf.contrib.distributions\n  log_normal = ds.TransformedDistribution(\n    distribution=ds.Normal(loc=0., scale=1.),\n    bijector=ds.bijectors.Inline(\n      forward_fn=tf.exp,\n      inverse_fn=tf.log,\n      inverse_log_det_jacobian_fn=(\n        lambda y: -tf.reduce_sum(tf.log(y), axis=-1)),\n    name=\"LogNormalTransformedDistribution\")\n  ```\n\n  Another example constructing a Normal from a StandardNormal:\n\n  ```python\n  ds = tf.contrib.distributions\n  normal = ds.TransformedDistribution(\n    distribution=ds.Normal(loc=0., scale=1.),\n    bijector=ds.bijectors.Affine(\n      shift=-1.,\n      scale_identity_multiplier=2.)\n    name=\"NormalTransformedDistribution\")\n  ```\n\n  A `TransformedDistribution`'s batch- and event-shape are implied by the base\n  distribution unless explicitly overridden by `batch_shape` or `event_shape`\n  arguments. Specifying an overriding `batch_shape` (`event_shape`) is\n  permitted only if the base distribution has scalar batch-shape (event-shape).\n  The bijector is applied to the distribution as if the distribution possessed\n  the overridden shape(s). The following example demonstrates how to construct a\n  multivariate Normal as a `TransformedDistribution`.\n\n  ```python\n  ds = tf.contrib.distributions\n  # We will create two MVNs with batch_shape = event_shape = 2.\n  mean = [[-1., 0],      # batch:0\n          [0., 1]]       # batch:1\n  chol_cov = [[[1., 0],\n               [0, 1]],  # batch:0\n              [[1, 0],\n               [2, 2]]]  # batch:1\n  mvn1 = ds.TransformedDistribution(\n      distribution=ds.Normal(loc=0., scale=1.),\n      bijector=ds.bijectors.Affine(shift=mean, scale_tril=chol_cov),\n      batch_shape=[2],  # Valid because base_distribution.batch_shape == [].\n      event_shape=[2])  # Valid because base_distribution.event_shape == [].\n  mvn2 = ds.MultivariateNormalTriL(loc=mean, scale_tril=chol_cov)\n  # mvn1.log_prob(x) == mvn2.log_prob(x)\n  ```\n\n  \"\"\"\n\n  def __init__(self,\n               distribution,\n               bijector=None,\n               batch_shape=None,\n               event_shape=None,\n               validate_args=False,\n               name=None):\n    \"\"\"Construct a Transformed Distribution.\n\n    Args:\n      distribution: The base distribution instance to transform. Typically an\n        instance of `Distribution`.\n      bijector: The object responsible for calculating the transformation.\n        Typically an instance of `Bijector`. `None` means `Identity()`.\n      batch_shape: `integer` vector `Tensor` which overrides `distribution`\n        `batch_shape`; valid only if `distribution.is_scalar_batch()`.\n      event_shape: `integer` vector `Tensor` which overrides `distribution`\n        `event_shape`; valid only if `distribution.is_scalar_event()`.\n      validate_args: Python `bool`, default `False`. When `True` distribution\n        parameters are checked for validity despite possibly degrading runtime\n        performance. When `False` invalid inputs may silently render incorrect\n        outputs.\n      name: Python `str` name prefixed to Ops created by this class. Default:\n        `bijector.name + distribution.name`.\n    \"\"\"\n    parameters = locals()\n    name = name or ((\"\" if bijector is None else bijector.name) +\n                    distribution.name)\n    with ops.name_scope(name, values=[event_shape, batch_shape]) as name:\n      # For convenience we define some handy constants.\n      self._zero = constant_op.constant(0, dtype=dtypes.int32, name=\"zero\")\n      self._empty = constant_op.constant([], dtype=dtypes.int32, name=\"empty\")\n\n      if bijector is None:\n        bijector = identity_bijector.Identity(validate_args=validate_args)\n\n      # We will keep track of a static and dynamic version of\n      # self._is_{batch,event}_override. This way we can do more prior to graph\n      # execution, including possibly raising Python exceptions.\n\n      self._override_batch_shape = self._maybe_validate_shape_override(\n          batch_shape, distribution.is_scalar_batch(), validate_args,\n          \"batch_shape\")\n      self._is_batch_override = _logical_not(_logical_equal(\n          _ndims_from_shape(self._override_batch_shape), self._zero))\n      self._is_maybe_batch_override = bool(\n          tensor_util.constant_value(self._override_batch_shape) is None or\n          tensor_util.constant_value(self._override_batch_shape).size != 0)\n\n      self._override_event_shape = self._maybe_validate_shape_override(\n          event_shape, distribution.is_scalar_event(), validate_args,\n          \"event_shape\")\n      self._is_event_override = _logical_not(_logical_equal(\n          _ndims_from_shape(self._override_event_shape), self._zero))\n      self._is_maybe_event_override = bool(\n          tensor_util.constant_value(self._override_event_shape) is None or\n          tensor_util.constant_value(self._override_event_shape).size != 0)\n\n      # To convert a scalar distribution into a multivariate distribution we\n      # will draw dims from the sample dims, which are otherwise iid. This is\n      # easy to do except in the case that the base distribution has batch dims\n      # and we're overriding event shape. When that case happens the event dims\n      # will incorrectly be to the left of the batch dims. In this case we'll\n      # cyclically permute left the new dims.\n      self._needs_rotation = _logical_and(\n          self._is_event_override,\n          _logical_not(self._is_batch_override),\n          _logical_not(distribution.is_scalar_batch()))\n      override_event_ndims = _ndims_from_shape(self._override_event_shape)\n      self._rotate_ndims = _pick_scalar_condition(\n          self._needs_rotation, override_event_ndims, 0)\n      # We'll be reducing the head dims (if at all), i.e., this will be []\n      # if we don't need to reduce.\n      self._reduce_event_indices = math_ops.range(\n          self._rotate_ndims - override_event_ndims, self._rotate_ndims)\n\n    self._distribution = distribution\n    self._bijector = bijector\n    super(TransformedDistribution, self).__init__(\n        dtype=self._distribution.dtype,\n        reparameterization_type=self._distribution.reparameterization_type,\n        validate_args=validate_args,\n        allow_nan_stats=self._distribution.allow_nan_stats,\n        parameters=parameters,\n        # We let TransformedDistribution access _graph_parents since this class\n        # is more like a baseclass than derived.\n        graph_parents=(distribution._graph_parents +  # pylint: disable=protected-access\n                       bijector.graph_parents),\n        name=name)\n\n  @property\n  def distribution(self):\n    \"\"\"Base distribution, p(x).\"\"\"\n    return self._distribution\n\n  @property\n  def bijector(self):\n    \"\"\"Function transforming x => y.\"\"\"\n    return self._bijector\n\n  def _event_shape_tensor(self):\n    return self.bijector.forward_event_shape_tensor(\n        distribution_util.pick_vector(\n            self._is_event_override,\n            self._override_event_shape,\n            self.distribution.event_shape_tensor()))\n\n  def _event_shape(self):\n    # If there's a chance that the event_shape has been overridden, we return\n    # what we statically know about the `event_shape_override`. This works\n    # because: `_is_maybe_event_override` means `static_override` is `None` or a\n    # non-empty list, i.e., we don't statically know the `event_shape` or we do.\n    #\n    # Since the `bijector` may change the `event_shape`, we then forward what we\n    # know to the bijector. This allows the `bijector` to have final say in the\n    # `event_shape`.\n    static_override = tensor_util.constant_value_as_shape(\n        self._override_event_shape)\n    return self.bijector.forward_event_shape(\n        static_override\n        if self._is_maybe_event_override\n        else self.distribution.event_shape)\n\n  def _batch_shape_tensor(self):\n    return distribution_util.pick_vector(\n        self._is_batch_override,\n        self._override_batch_shape,\n        self.distribution.batch_shape_tensor())\n\n  def _batch_shape(self):\n    # If there's a chance that the batch_shape has been overridden, we return\n    # what we statically know about the `batch_shape_override`. This works\n    # because: `_is_maybe_batch_override` means `static_override` is `None` or a\n    # non-empty list, i.e., we don't statically know the `batch_shape` or we do.\n    #\n    # Notice that this implementation parallels the `_event_shape` except that\n    # the `bijector` doesn't get to alter the `batch_shape`. Recall that\n    # `batch_shape` is a property of a distribution while `event_shape` is\n    # shared between both the `distribution` instance and the `bijector`.\n    static_override = tensor_util.constant_value_as_shape(\n        self._override_batch_shape)\n    return (static_override\n            if self._is_maybe_batch_override\n            else self.distribution.batch_shape)\n\n  def _sample_n(self, n, seed=None):\n    sample_shape = _concat_vectors(\n        distribution_util.pick_vector(self._needs_rotation, self._empty, [n]),\n        self._override_batch_shape,\n        self._override_event_shape,\n        distribution_util.pick_vector(self._needs_rotation, [n], self._empty))\n    x = self.distribution.sample(sample_shape=sample_shape, seed=seed)\n    x = self._maybe_rotate_dims(x)\n    # We'll apply the bijector in the `_call_sample_n` function.\n    return x\n\n  def _call_sample_n(self, sample_shape, seed, name, **kwargs):\n    # We override `_call_sample_n` rather than `_sample_n` so we can ensure that\n    # the result of `self.bijector.forward` is not modified (and thus caching\n    # works).\n    with self._name_scope(name, values=[sample_shape]):\n      sample_shape = ops.convert_to_tensor(\n          sample_shape, dtype=dtypes.int32, name=\"sample_shape\")\n      sample_shape, n = self._expand_sample_shape_to_vector(\n          sample_shape, \"sample_shape\")\n\n      # First, generate samples. We will possibly generate extra samples in the\n      # event that we need to reinterpret the samples as part of the\n      # event_shape.\n      x = self._sample_n(n, seed, **kwargs)\n\n      # Next, we reshape `x` into its final form. We do this prior to the call\n      # to the bijector to ensure that the bijector caching works.\n      batch_event_shape = array_ops.shape(x)[1:]\n      final_shape = array_ops.concat([sample_shape, batch_event_shape], 0)\n      x = array_ops.reshape(x, final_shape)\n\n      # Finally, we apply the bijector's forward transformation. For caching to\n      # work, it is imperative that this is the last modification to the\n      # returned result.\n      y = self.bijector.forward(x, **kwargs)\n      y = self._set_sample_static_shape(y, sample_shape)\n\n      return y\n\n  def _log_prob(self, y):\n    # For caching to work, it is imperative that the bijector is the first to\n    # modify the input.\n    x = self.bijector.inverse(y)\n    event_ndims = self._maybe_get_event_ndims_statically()\n\n    ildj = self.bijector.inverse_log_det_jacobian(y, event_ndims=event_ndims)\n    if self.bijector._is_injective:  # pylint: disable=protected-access\n      return self._finish_log_prob_for_one_fiber(y, x, ildj, event_ndims)\n\n    lp_on_fibers = [\n        self._finish_log_prob_for_one_fiber(y, x_i, ildj_i, event_ndims)\n        for x_i, ildj_i in zip(x, ildj)]\n    return math_ops.reduce_logsumexp(array_ops.stack(lp_on_fibers), axis=0)\n\n  def _finish_log_prob_for_one_fiber(self, y, x, ildj, event_ndims):\n    \"\"\"Finish computation of log_prob on one element of the inverse image.\"\"\"\n    x = self._maybe_rotate_dims(x, rotate_right=True)\n    log_prob = self.distribution.log_prob(x)\n    if self._is_maybe_event_override:\n      log_prob = math_ops.reduce_sum(log_prob, self._reduce_event_indices)\n    log_prob += math_ops.cast(ildj, log_prob.dtype)\n    if self._is_maybe_event_override and isinstance(event_ndims, int):\n      log_prob.set_shape(array_ops.broadcast_static_shape(\n          x.get_shape().with_rank_at_least(1)[:-event_ndims], self.batch_shape))\n    return log_prob\n\n  def _prob(self, y):\n    x = self.bijector.inverse(y)\n    event_ndims = self._maybe_get_event_ndims_statically()\n    ildj = self.bijector.inverse_log_det_jacobian(y, event_ndims=event_ndims)\n    if self.bijector._is_injective:  # pylint: disable=protected-access\n      return self._finish_prob_for_one_fiber(y, x, ildj, event_ndims)\n\n    prob_on_fibers = [\n        self._finish_prob_for_one_fiber(y, x_i, ildj_i, event_ndims)\n        for x_i, ildj_i in zip(x, ildj)]\n    return sum(prob_on_fibers)\n\n  def _finish_prob_for_one_fiber(self, y, x, ildj, event_ndims):\n    \"\"\"Finish computation of prob on one element of the inverse image.\"\"\"\n    x = self._maybe_rotate_dims(x, rotate_right=True)\n    prob = self.distribution.prob(x)\n    if self._is_maybe_event_override:\n      prob = math_ops.reduce_prod(prob, self._reduce_event_indices)\n    prob *= math_ops.exp(math_ops.cast(ildj, prob.dtype))\n    if self._is_maybe_event_override and isinstance(event_ndims, int):\n      prob.set_shape(array_ops.broadcast_static_shape(\n          y.get_shape().with_rank_at_least(1)[:-event_ndims], self.batch_shape))\n    return prob\n\n  def _log_cdf(self, y):\n    if self._is_maybe_event_override:\n      raise NotImplementedError(\"log_cdf is not implemented when overriding \"\n                                \"event_shape\")\n    if not self.bijector._is_injective:  # pylint: disable=protected-access\n      raise NotImplementedError(\"log_cdf is not implemented when \"\n                                \"bijector is not injective.\")\n    x = self.bijector.inverse(y)\n    return self.distribution.log_cdf(x)\n\n  def _cdf(self, y):\n    if self._is_maybe_event_override:\n      raise NotImplementedError(\"cdf is not implemented when overriding \"\n                                \"event_shape\")\n    if not self.bijector._is_injective:  # pylint: disable=protected-access\n      raise NotImplementedError(\"cdf is not implemented when \"\n                                \"bijector is not injective.\")\n    x = self.bijector.inverse(y)\n    return self.distribution.cdf(x)\n\n  def _log_survival_function(self, y):\n    if self._is_maybe_event_override:\n      raise NotImplementedError(\"log_survival_function is not implemented when \"\n                                \"overriding event_shape\")\n    if not self.bijector._is_injective:  # pylint: disable=protected-access\n      raise NotImplementedError(\"log_survival_function is not implemented when \"\n                                \"bijector is not injective.\")\n    x = self.bijector.inverse(y)\n    return self.distribution.log_survival_function(x)\n\n  def _survival_function(self, y):\n    if self._is_maybe_event_override:\n      raise NotImplementedError(\"survival_function is not implemented when \"\n                                \"overriding event_shape\")\n    if not self.bijector._is_injective:  # pylint: disable=protected-access\n      raise NotImplementedError(\"survival_function is not implemented when \"\n                                \"bijector is not injective.\")\n    x = self.bijector.inverse(y)\n    return self.distribution.survival_function(x)\n\n  def _quantile(self, value):\n    if self._is_maybe_event_override:\n      raise NotImplementedError(\"quantile is not implemented when overriding \"\n                                \"event_shape\")\n    if not self.bijector._is_injective:  # pylint: disable=protected-access\n      raise NotImplementedError(\"quantile is not implemented when \"\n                                \"bijector is not injective.\")\n    # x_q is the \"qth quantile\" of X iff q = P[X <= x_q].  Now, since X =\n    # g^{-1}(Y), q = P[X <= x_q] = P[g^{-1}(Y) <= x_q] = P[Y <= g(x_q)],\n    # implies the qth quantile of Y is g(x_q).\n    inv_cdf = self.distribution.quantile(value)\n    return self.bijector.forward(inv_cdf)\n\n  def _entropy(self):\n    if not self.bijector.is_constant_jacobian:\n      raise NotImplementedError(\"entropy is not implemented\")\n    if not self.bijector._is_injective:  # pylint: disable=protected-access\n      raise NotImplementedError(\"entropy is not implemented when \"\n                                \"bijector is not injective.\")\n    # Suppose Y = g(X) where g is a diffeomorphism and X is a continuous rv. It\n    # can be shown that:\n    #   H[Y] = H[X] + E_X[(log o abs o det o J o g)(X)].\n    # If is_constant_jacobian then:\n    #   E_X[(log o abs o det o J o g)(X)] = (log o abs o det o J o g)(c)\n    # where c can by anything.\n    entropy = self.distribution.entropy()\n    if self._is_maybe_event_override:\n      # H[X] = sum_i H[X_i] if X_i are mutually independent.\n      # This means that a reduce_sum is a simple rescaling.\n      entropy *= math_ops.cast(math_ops.reduce_prod(self._override_event_shape),\n                               dtype=entropy.dtype.base_dtype)\n    if self._is_maybe_batch_override:\n      new_shape = array_ops.concat([\n          _ones_like(self._override_batch_shape),\n          self.distribution.batch_shape_tensor()\n      ], 0)\n      entropy = array_ops.reshape(entropy, new_shape)\n      multiples = array_ops.concat([\n          self._override_batch_shape,\n          _ones_like(self.distribution.batch_shape_tensor())\n      ], 0)\n      entropy = array_ops.tile(entropy, multiples)\n    dummy = array_ops.zeros(\n        shape=array_ops.concat(\n            [self.batch_shape_tensor(), self.event_shape_tensor()],\n            0),\n        dtype=self.dtype)\n    event_ndims = (self.event_shape.ndims if self.event_shape.ndims is not None\n                   else array_ops.size(self.event_shape_tensor()))\n    ildj = self.bijector.inverse_log_det_jacobian(\n        dummy, event_ndims=event_ndims)\n\n    entropy -= math_ops.cast(ildj, entropy.dtype)\n    entropy.set_shape(self.batch_shape)\n    return entropy\n\n  def _maybe_validate_shape_override(self, override_shape, base_is_scalar,\n                                     validate_args, name):\n    \"\"\"Helper to __init__ which ensures override batch/event_shape are valid.\"\"\"\n    if override_shape is None:\n      override_shape = []\n\n    override_shape = ops.convert_to_tensor(override_shape, dtype=dtypes.int32,\n                                           name=name)\n\n    if not override_shape.dtype.is_integer:\n      raise TypeError(\"shape override must be an integer\")\n\n    override_is_scalar = _is_scalar_from_shape(override_shape)\n    if tensor_util.constant_value(override_is_scalar):\n      return self._empty\n\n    dynamic_assertions = []\n\n    if override_shape.get_shape().ndims is not None:\n      if override_shape.get_shape().ndims != 1:\n        raise ValueError(\"shape override must be a vector\")\n    elif validate_args:\n      dynamic_assertions += [check_ops.assert_rank(\n          override_shape, 1,\n          message=\"shape override must be a vector\")]\n\n    if tensor_util.constant_value(override_shape) is not None:\n      if any(s <= 0 for s in tensor_util.constant_value(override_shape)):\n        raise ValueError(\"shape override must have positive elements\")\n    elif validate_args:\n      dynamic_assertions += [check_ops.assert_positive(\n          override_shape,\n          message=\"shape override must have positive elements\")]\n\n    is_both_nonscalar = _logical_and(_logical_not(base_is_scalar),\n                                     _logical_not(override_is_scalar))\n    if tensor_util.constant_value(is_both_nonscalar) is not None:\n      if tensor_util.constant_value(is_both_nonscalar):\n        raise ValueError(\"base distribution not scalar\")\n    elif validate_args:\n      dynamic_assertions += [check_ops.assert_equal(\n          is_both_nonscalar, False,\n          message=\"base distribution not scalar\")]\n\n    if not dynamic_assertions:\n      return override_shape\n    return control_flow_ops.with_dependencies(\n        dynamic_assertions, override_shape)\n\n  def _maybe_rotate_dims(self, x, rotate_right=False):\n    \"\"\"Helper which rolls left event_dims left or right event_dims right.\"\"\"\n    needs_rotation_const = tensor_util.constant_value(self._needs_rotation)\n    if needs_rotation_const is not None and not needs_rotation_const:\n      return x\n    ndims = array_ops.rank(x)\n    n = (ndims - self._rotate_ndims) if rotate_right else self._rotate_ndims\n    return array_ops.transpose(\n        x, _concat_vectors(math_ops.range(n, ndims), math_ops.range(0, n)))\n\n  def _maybe_get_event_ndims_statically(self):\n    if self.event_shape.ndims is not None:\n      return self.event_shape.ndims\n\n    event_ndims = array_ops.size(self.event_shape_tensor())\n\n    static_event_ndims = tensor_util.constant_value(event_ndims)\n\n    if static_event_ndims is not None:\n      return static_event_ndims\n\n    return event_ndims\n", "meta": {"hexsha": "6aa6ec40d9b2ac4d156ba132e75e1846c870b772", "size": 27352, "ext": "py", "lang": "Python", "max_stars_repo_path": "tensorflow/python/ops/distributions/transformed_distribution.py", "max_stars_repo_name": "noahl/tensorflow", "max_stars_repo_head_hexsha": "b95d8cce7323d328565378e0d60d72603393f87d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-09-22T20:16:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T10:35:19.000Z", "max_issues_repo_path": "tensorflow/python/ops/distributions/transformed_distribution.py", "max_issues_repo_name": "noahl/tensorflow", "max_issues_repo_head_hexsha": "b95d8cce7323d328565378e0d60d72603393f87d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tensorflow/python/ops/distributions/transformed_distribution.py", "max_forks_repo_name": "noahl/tensorflow", "max_forks_repo_head_hexsha": "b95d8cce7323d328565378e0d60d72603393f87d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-08-14T09:04:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T20:08:02.000Z", "avg_line_length": 43.074015748, "max_line_length": 88, "alphanum_fraction": 0.7012649898, "include": true, "reason": "import numpy", "num_tokens": 6412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.183846340657495}}
{"text": "\"\"\"Module containing main Neural Style Transfer class and methods\"\"\"\nfrom keras import backend as K\nfrom keras.models import Sequential\nfrom keras.layers import AveragePooling2D, InputLayer\nfrom keras.applications.vgg19 import preprocess_input, VGG19\nfrom .utils import Image\nimport tensorflow as tf\nfrom typing import Optional, Tuple\nimport numpy as np\nfrom copy import deepcopy\nimport os\nfrom tqdm import tqdm\nfrom streamlit.DeltaGenerator import DeltaGenerator\nimport datetime as dt\n\n\nclass NeuralStyleTransfer:\n    \"\"\"Neural style transfer class that implements the whole workflow for\n    transfering artistic style to pictures, as described in the NST paper by\n    Gatys et al. (2015) (https://arxiv.org/abs/1508.06576),\n    and using a Keras pre-trained VGG19 neural network and the Adam optimizer.\n    \"\"\"\n    style_layers = {'block1_conv1': 0.2,\n                    'block2_conv1': 0.2,\n                    'block3_conv1': 0.2,\n                    'block4_conv1': 0.2,\n                    'block5_conv1': 0.2}\n\n    def __init__(self, alpha: float = 5., beta: float = 100.,\n                 gamma: float = 1e-3, dir_path: Optional[str] = None):\n        \"\"\"Initialize with the default loss weights and the directory\n        path that will be used to write the outputs.\n\n        Parameters\n        ----------\n        alpha\n            Weight associated with content image loss (default = 5)\n        beta\n            Weight associated with style image loss (default = 100)\n        gamma\n            Weight associated with image variation loss (default = 1e-3)\n        dir_path\n            Directory where generated images will be written\n            (default = current working directory)\n        \"\"\"\n        self.dir_path = dir_path or os.getcwd()\n        self.run_dir = None\n        self.default_alpha = alpha\n        self.default_beta = beta\n        self.default_gamma = gamma\n        # Image parameters\n        self.img_height = None\n        self.img_width = None\n        self.color_channels = None\n        self.input_shape = None\n        # Initialize images\n        self.img_content = None\n        self.img_style = None\n        self.input_content = None\n        self.input_style = None\n        self.input_generated = None\n        # Tensorflow stuff\n        self.session = None\n        self.kmodel = None\n        # Cost functions\n        self.j_style = None\n        self.j_content = None\n        self.j_var = None\n        self.j_total = None\n\n    def load_content_image(self, fpath: str, content_size: int = 512,\n                           interpolation: str = 'bilinear'):\n        \"\"\"Load content image, and scale it. Scaling the style image will\n        affect the artistic features transfered to the generated image.\n\n        Parameters\n        ----------\n        fpath\n            Path of style image\n        content_size\n            Height to be used for scaling the content image\n            (default = 512)\n        interpolation\n            Interpolation scheme to use when rescaling image\n            (default = bilinear)\n        \"\"\"\n        self.img_content = Image.from_fp(fpath, label='content')\n        # Resize content image\n        n_h, n_w, n_c = self.img_content.data.shape\n        n_h_scaled = content_size\n        n_w_scaled = int(n_w * content_size / n_h)\n        self.img_content.resize(n_w_scaled, n_h_scaled,\n                                resample=interpolation)\n        model_input = np.expand_dims(deepcopy(self.img_content.data), axis=0)\n        self.input_content = preprocess_input(model_input)\n        # Save the content image shape for loading model\n        self.img_height, self.img_width, self.color_channels = \\\n            self.img_content.data.shape\n        self.input_shape = (1, self.img_height, self.img_width,\n                            self.color_channels)\n\n    def load_style_image(self, fpath: str, scale: float = 1.0,\n                         interpolation: str = 'bilinear'):\n        \"\"\"Load style image, and scale it. Scaling the style image will\n        affect the artistic features transfered to the generated image.\n\n        Parameters\n        ----------\n        fpath\n            Path of style image\n        scale\n            Scaling factor of style image (default = 1., no scaling)\n        interpolation\n            Interpolation scheme to use when rescaling image\n            (default = bilinear)\n        \"\"\"\n        self.img_style = Image.from_fp(fpath, label='content')\n        if scale != 1.0:\n            n_h, n_w, n_c = self.img_style.data.shape\n            n_h_scaled = int(scale * n_h)\n            n_w_scaled = int(scale * n_w)\n            self.img_style.resize(n_w_scaled, n_h_scaled,\n                                  resample=interpolation)\n        model_input = np.expand_dims(deepcopy(self.img_style.data), axis=0)\n        self.input_style = preprocess_input(model_input)\n\n    def run(self, num_iterations: int = 1000, learning_rate: float = 2.0,\n            alpha: Optional[float] = None, beta: Optional[float] = None,\n            gamma: Optional[float] = None,\n            noise_low: float = -20, noise_high: float = 20,\n            noise_ratio: float = 0.6, write_steps: int = 20,\n            style_layers: Optional[dict] = None,\n            progress_bar: DeltaGenerator = None):\n        \"\"\"Run style transfer optimization that will generate the new image\n        build from content and style images.\n\n        Parameters\n        ----------\n        num_iterations\n            Number of optimization steps to run (default = 1000)\n        learning_rate\n            Learning rate to use for the Adam optimizer (default = 2.0)\n        alpha\n            Weight associated with content image loss (default = default_alpha)\n        beta\n            Weight associated with style image loss (default = default_beta)\n        gamma\n            Weight associated with image variation loss\n            (default = default_gamma)\n        noise_low\n            Min of random values to use when first creating the generated image\n            from noise (default = -20)\n        noise_high\n            Max of random values to use when first creating the generated image\n            from noise (default = 20)\n        noise_ratio\n            When first creating the generated image, ratio of amount coming\n            from noise to amount coming from content image (default = 0.6)\n        write_steps\n            A generated image will be written every time after this number\n            of iterations (default = 20)\n        style_layers\n            The weight to give to each VGG19 layer used in the style loss\n            calculation (default = all equal weights)\n        progress_bar\n            Streamlit progress bar to be updated when training\n            (default = None)\n        \"\"\"\n        # Create a directory specific to this run\n        self.run_dir = os.path.join(\n            self.dir_path, dt.datetime.now().strftime(\"%Y%m%d-%H%M%S\"))\n        if not os.path.exists(self.run_dir):\n            os.makedirs(self.run_dir)\n\n        # Initialize Keras model to be used\n        print('...creating Keras model to be trained')\n        self.kmodel = self._init_model(self.img_content.data.shape)\n        # For name formatting\n        n_digits = len(str(abs(num_iterations)))\n        # Input weights\n        alpha = alpha or self.default_alpha\n        beta = beta or self.default_beta\n        gamma = self.default_gamma if gamma is None else gamma\n        # Session: need to get session from Keras, because it contains\n        # the pre-trained weight initialization for the model variables\n        self.session = K.get_session()\n\n        # get parameters for style cost\n        style_layers = style_layers or self.style_layers\n        # build total cost function\n        print('...building cost function')\n        self._build_cost_function(self.session, alpha, beta, gamma,\n                                  style_layers)\n        # Define optimizer\n        optimizer = tf.train.AdamOptimizer(learning_rate)\n        # Define training step, and specify input variable explicitely,\n        # otherwise will train all the variables in the graph\n        train_step = optimizer.minimize(self.j_total,\n                                        var_list=[self.kmodel.input])\n        # All variables need to be initialized because we rely on tensorflow,\n        # but we don't want to lose the pretrained weights\n        self._custom_global_variable_initialization(self.session)\n\n        # Assign generated image to variable\n        self._generate_noise_image(low=noise_low, high=noise_high,\n                                   noise_ratio=noise_ratio)\n        K.set_value(self.kmodel.input, self.input_generated)\n\n        print('...training')\n        # Start progress bar\n        if progress_bar is not None:\n            progress_bar.progress(0)\n        for i in tqdm(range(num_iterations)):\n            # Update progress bar if any\n            if progress_bar is not None:\n                progress_bar.progress((i + 1) / num_iterations)\n            # Print every `write_steps` iteration.\n            if i % write_steps == 0:\n                jt, jc, js, jv = self.session.run(\n                    [self.j_total, self.j_content, self.j_style, self.j_var])\n                print(\"Iteration: {}\".format(i))\n                print(\"total cost = {}\".format(jt))\n                print(\"content cost = {}\".format(jc))\n                print(\"style cost = {}\".format(js))\n                print(\"variation cost = {}\".format(jv))\n\n                # save current generated image in `dir_path`\n                fname = str(i).zfill(n_digits) + '.png'\n                fpath = os.path.join(self.run_dir, fname)\n                img = self._model_input_to_image(self.input_generated, label=i)\n                img.save(fpath)\n\n            # Run minimization step\n            self.session.run(train_step)\n            # Get generated image\n            self.input_generated = self.session.run(self.kmodel.input)\n\n        print('...done training')\n        # save last generated image\n        fpath = os.path.join(self.run_dir, 'image_generated.png')\n        img = self._model_input_to_image(self.input_generated, label='final')\n        img.save(fpath)\n\n    @property\n    def img_generated(self) -> Image:\n        \"\"\"Deprocess the generated input into the generated image\"\"\"\n        return self._model_input_to_image(self.input_generated)\n\n    def _init_model(self, input_shape: Tuple) -> Sequential:\n        \"\"\"Create keras model used for neural style transfer\n        - import VGG19 model with pre-trained weights\n        - remove end layers if existing (no top)\n        - change max pool layers into avg pool layers\n        - set weights as non trainable (doesn't really matter since we'll use\n        tensorflow directly for training)\n        - use variable as input\n        - use input shape from given image\n\n        Check out original model build here:\n        https://github.com/keras-team/keras-applications/blob/master/keras_applications/vgg19.py\n\n        Parameters\n        ----------\n        input_shape\n            Input shape of the image that will be used as input to the model:\n            (input height, input width, number of channels)\n\n        Returns\n        -------\n        model\n            Keras sequential model\n        \"\"\"\n        # Get pretrained keras model: if using docker image, the weights\n        # will be saved inside the mounted volume (since it takes a while\n        # to download)\n        kmodel = VGG19(include_top=False, weights='imagenet',\n                       input_tensor=None, input_shape=input_shape)\n        # Build new model from pretrained keras model\n        new_kmodel = Sequential(name='VGG19_nst')\n        # Create variable input tensor\n        var = K.zeros(shape=(1,) + input_shape)\n        input_var = InputLayer(input_tensor=var)\n        input_var.trainable = True\n        # Add input layer\n        new_kmodel.add(input_var)\n        # Add pretrained layers\n        i_pool = 1\n        for layer in kmodel.layers[1:]:\n            if 'pool' in layer.name:\n                name = 'block%i_avgpool' % i_pool\n                layer = AveragePooling2D((2, 2), strides=(2, 2),\n                                         padding='same', name=name)\n                i_pool += 1\n            else:\n                # clear all the nodes from the layer before adding it to model\n                layer._inbound_nodes = []\n                layer._outbound_nodes = []\n            # make all layers non trainable\n            layer.trainable = False\n            new_kmodel.add(layer)\n\n        # build: need to rebuild model wo input layer since already exist\n        new_kmodel.build(None)\n\n        return new_kmodel\n\n    def _custom_global_variable_initialization(self, session: tf.Session):\n        \"\"\"Custom variable initialization:\n        the problem is that tensorflow requires all variables to\n        be initialized, but that would erase all the pre-trained values\n        obtained with Keras. So here we save their values before\n        initialization, and then reassign it afterwards.\n\n        Parameters\n        ----------\n        session\n            Tensorflow session where graph resides\n        \"\"\"\n        # There are other hidden variables in the model that need to\n        # be initialized, and we can't get their values\n        all_variables = tf.global_variables()\n        model_variables = self.kmodel.weights\n        # save variable values\n        list_values = []\n        for var in model_variables:\n            list_values.append(session.run(var))\n        # run initialization on that variable only\n        init_op = tf.initialize_variables(all_variables)\n        session.run(init_op)\n        # then assign previous value again\n        for idx, var in enumerate(model_variables):\n            K.set_value(var, list_values[idx])\n\n    def _generate_noise_image(self, low: int = -20, high: int = 20,\n                              noise_ratio: float = 0.6):\n        \"\"\"Generate noise image from combination of random noise and\n        content image pixel values.\n\n        Parameters\n        ----------\n        noise_low\n            Min of random values to use when first creating the generated image\n            from noise (default = -20)\n        noise_high\n            Max of random values to use when first creating the generated image\n            from noise (default = 20)\n        noise_ratio\n            When first creating the generated image, ratio of amount coming\n            from noise to amount coming from content image (default = 0.6)\n        \"\"\"\n        shape_img = (1, self.img_height, self.img_width, self.color_channels)\n        noise_data = np.random.uniform(low, high, shape_img).astype('float32')\n        input_data = (noise_data * noise_ratio\n                      + self.input_content * (1 - noise_ratio))\n        self.input_generated = input_data\n\n    def _build_cost_function(self, session: tf.Session, alpha: float,\n                             beta: float, gamma: float, style_layers: dict):\n        \"\"\"Build total cost function, which is the weighted sum of the\n        content loss, the style loss, and the variation loss functions.\n        This will create the loss functions and sum them up.\n\n        Parameters\n        ----------\n        session\n            Tensorflow session where the graph resides\n        alpha\n            Weight associated with content image loss\n        beta\n            Weight associated with style image loss\n        gamma\n            Weight associated with image variation loss\n        style_layers\n            The weight to give to each VGG19 layer used in the style loss\n            calculation\n        \"\"\"\n        # Calculate costs\n        self.j_content = self._compute_content_cost(self.input_content,\n                                                    session=session)\n        self.j_style = self._compute_style_cost(self.input_style,\n                                                style_layers, session=session)\n        self.j_var = self._compute_variation_cost(session)\n        # Get total weighted cost\n        self.j_total = self._total_cost(self.j_content, self.j_style,\n                                        self.j_var, alpha, beta, gamma)\n\n    def _model_input_to_image(self, input_data: np.ndarray,\n                              label: Optional[str] = None) -> Image:\n        \"\"\"Undo all the preprocessing done for modeling and return image\n        Reversing this:\n        https://github.com/keras-team/keras-applications/blob/master/keras_applications/imagenet_utils.py#L60-L61\n\n        Parameters\n        ----------\n        input_data\n            Image input data used for model, of shape\n            (1, image height, image width, number of channels)\n        label\n            Optional label for created image (default = None)\n        \"\"\"\n        x = deepcopy(input_data)\n        # Add what was subtracted\n        mean = [103.939, 116.779, 123.68]\n        x[..., 0] += mean[0]\n        x[..., 1] += mean[1]\n        x[..., 2] += mean[2]\n        # BGR -> RGB\n        x = x[..., ::-1]\n        # Images need integer\n        x = np.clip(x[0, ...], 0, 255).astype('uint8')\n        return Image(x, label)\n\n    @staticmethod\n    def _total_cost(j_content: tf.Tensor, j_style: tf.Tensor, j_var: tf.Tensor,\n                    alpha: float, beta: float, gamma: float) -> tf.Tensor:\n        \"\"\"Compute total weighted averaged cost of the content, style, and\n        variation losses.\n\n        Parameters\n        ----------\n        j_content\n            Content loss\n        j_style\n            Style loss\n        j_var\n            Variation loss\n        alpha\n            Weight associated with content image loss\n        beta\n            Weight associated with style image loss\n        gamma\n            Weight associated with image variation loss\n\n        Returns\n        -------\n        total loss\n            Weighted sum of all losses\n        \"\"\"\n        return alpha * j_content + beta * j_style + gamma * j_var\n\n    def _compute_content_cost(self, input_content: np.ndarray,\n                              session: Optional[tf.Session] = None\n                              ) -> tf.Tensor:\n        \"\"\"\n        Compute content loss\n\n        Parameters\n        ----------\n        input_content\n            Model input of content image\n            Shape = (1, image height, image width, number of channels)\n        session\n            Session where graph resides (default = NST object session)\n\n        Returns\n        -------\n        content loss\n        \"\"\"\n\n        session = session or self.session\n        # get model outputs\n        output = self.kmodel.get_layer('block4_conv2').output\n        # Get activations from content inputs\n        K.set_value(self.kmodel.input, input_content)\n        a_c = session.run(output)\n        # Get symbolic activation for future updates of generated image\n        a_g = output\n        # Get shapes of activation\n        _, n_h, n_w, n_c = a_c.shape\n        # compute content loss\n        j_content = 1. / (4 * n_h * n_w * n_c) * K.sum(K.square(a_c - a_g))\n\n        return j_content\n\n    def _compute_style_cost(self, input_style: np.ndarray, style_layers: dict,\n                            session: tf.Session = None) -> tf.Tensor:\n        \"\"\"\n        Compute the total style loss\n\n        Parameters\n        ----------\n        input_style\n            Model input for style image\n        style_layers\n            The weight to give to each VGG19 layer used in the style loss\n            calculation\n        session\n            Session where graph resides (default = NST object session)\n\n        Returns\n        -------\n        total style loss\n        \"\"\"\n\n        session = session or self.session\n        # initialize the overall style cost\n        j_style = 0\n        # Create temporary model to calculate activations for style image\n        kmodel_style = self._init_model(self.img_style.data.shape)\n        # Sum up losses for each layer\n        for layer_name, coeff in style_layers.items():\n            # Set input variable to style image inputs\n            K.set_value(kmodel_style.input, input_style)\n            # Set a_s to be the hidden layer activation from the layer we\n            # have selected, by running the session on layer.output\n            a_s = session.run(kmodel_style.get_layer(layer_name).output)\n            # Get symbolic a_g\n            a_g = self.kmodel.get_layer(layer_name).output\n            # Compute style_cost for the current layer\n            j_style_layer = self._compute_layer_style_cost(a_s, a_g, session)\n            # Add coeff * J_style_layer of this layer to overall style cost\n            j_style += coeff * j_style_layer\n\n        return j_style\n\n    @staticmethod\n    def _compute_layer_style_cost(a_s: np.ndarray, a_g: tf.Tensor,\n                                  session: tf.Session):\n        \"\"\"\n        Calculate layer-specific style loss using style image and generated\n        image activations. Style image and generated image number of channels\n        must be equal.\n\n        Parameters\n        ----------\n        a_s\n            Activations of style image for layer\n            Shape = (1, style img height, style img width, n channels)\n        a_g\n            Activations of generated image for layer\n            Shape = (1, generated img height, generated img width, n channels)\n        session\n            Session where graph resides\n\n        Returns\n        -------\n        Layer-specific style loss\n        \"\"\"\n\n        # Retrieve dimensions from a_g (≈1 line)\n        _, n_h, n_w, n_c = K.shape(a_g).eval(session=session)\n\n        # Reshape the images to have them of shape (n_c, n_h*n_w) (≈2 lines)\n        a_s = K.reshape(K.permute_dimensions(a_s, (3, 0, 1, 2)), (n_c, -1))\n        a_g = K.reshape(K.permute_dimensions(a_g, (3, 0, 1, 2)), (n_c, -1))\n\n        # Computing gram_matrices for both images S and G (≈2 lines)\n        gs = NeuralStyleTransfer._gram_matrix(a_s)\n        gg = NeuralStyleTransfer._gram_matrix(a_g)\n\n        # Computing the loss (≈1 line)\n        j_style_layer = 1 / (2 * n_c * n_w * n_h)**2 * K.sum(K.square(gs - gg))\n\n        return j_style_layer\n\n    def _compute_variation_cost(self, session: tf.Session) -> tf.Tensor:\n        \"\"\"Compute variation loss of Keras model input to keep the image locally\n        coherent.\n\n        Inspired by:\n        https://github.com/keras-team/keras/blob/master/examples/neural_style_transfer.py\n\n        Parameters\n        ----------\n        session\n            Session where graph resides\n\n        Returns\n        -------\n        Variation loss\n        \"\"\"\n        # Get shape of input var\n        input_var = self.kmodel.input\n        _, n_h, n_w, n_c = K.shape(input_var).eval(session=session)\n        a = K.square(\n            input_var[:, :n_h - 1, :n_w - 1, :]\n            - input_var[:, 1:, :n_w - 1, :])\n        b = K.square(\n            input_var[:, :n_h - 1, :n_w - 1, :]\n            - input_var[:, :n_h - 1, 1:, :])\n        return K.sum(K.pow(a + b, 1.25))\n\n    @staticmethod\n    def _gram_matrix(a: tf.Tensor) -> tf.Tensor:\n        \"\"\"\n        Calculate gram matrix of given tensor.\n\n        Parameters\n        ----------\n        a\n            Input tensor for which to calculate gram matrix\n\n        Returns\n        -------\n        ga\n            Gram matrix of input tensor\n        \"\"\"\n        ga = K.dot(a, K.transpose(a))\n        return ga\n", "meta": {"hexsha": "d2304a8242a509c573a572ba4b27b4b1efc9550c", "size": 23367, "ext": "py", "lang": "Python", "max_stars_repo_path": "nst/main.py", "max_stars_repo_name": "anomam/nst", "max_stars_repo_head_hexsha": "42f82c301e9333f2256b444677f816d93e4bfeed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-06-09T16:28:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-27T07:24:19.000Z", "max_issues_repo_path": "nst/main.py", "max_issues_repo_name": "anomam/neural-style-transfer-tensorflow", "max_issues_repo_head_hexsha": "42f82c301e9333f2256b444677f816d93e4bfeed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-11-10T19:39:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T01:14:23.000Z", "max_forks_repo_path": "nst/main.py", "max_forks_repo_name": "anomam/neural-style-transfer-tensorflow", "max_forks_repo_head_hexsha": "42f82c301e9333f2256b444677f816d93e4bfeed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-12-05T10:31:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-07T18:03:41.000Z", "avg_line_length": 38.945, "max_line_length": 113, "alphanum_fraction": 0.5903196816, "include": true, "reason": "import numpy", "num_tokens": 4954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.18384633547778412}}
{"text": "import os\nimport sys\nimport numpy as np\nfrom scipy.interpolate import interp1d\nimport matplotlib.pyplot as plt\nfrom matplotlib import gridspec\nimport matplotlib.lines as mlines\nimport warnings\n\nfrom MulensModel.utils import Utils, MAG_ZEROPOINT\nfrom MulensModel import Event, Trajectory\nfrom MulensModel import __version__ as mm_version\n\nfrom MCPM import utils\n\n\nK2_MAG_ZEROPOINT = 25.\n\n# Multiple cpm_source-s to be done:\n#     def set_pixel_coeffs_from_models\n#     def satellite_maximum\n\n# Issues with flux uncertsinteis read from TPF files:\n#  - not yet properly used in chi2_fun()\n#  - plot functions here and in cpmfitsource.py\n#  - also CpmFitPixel.target_masked needs _err equivalent\n\n\nclass Minimizer(object):\n    \"\"\"\n    An object to link an Event to the functions necessary to minimize chi2.\n\n    Arguments :\n        event: *MulensModel.Event*\n            ...\n            It is assumed that the last datasets are the satellite ones.\n\n        parameters_to_fit: *list* of *str*\n            Parameters that will be fitted. Except\n            the *MulensModel.ModelParameters* parameters one can use satellite\n            source fluxes: 'f_s_sat', 'f_s_sat_over_u_0',\n            and 'f_b_sat' (I suggest not to use it).\n\n        cpm_sources: *CpmFitSource* or *list* of them\n\n    To force periodic flush of file with all models set n_flush to\n    100 or 1000 etc.\n\n    \"\"\"\n    def __init__(self, event, parameters_to_fit, cpm_sources):\n        self.event = event\n        self._MM = isinstance(event, Event)\n        self.n_datasets = len(self.event.datasets)\n        self.parameters_to_fit = parameters_to_fit\n        self.n_parameters = len(self.parameters_to_fit)\n        # self.n_parameters += 1\n        if not isinstance(cpm_sources, list):\n            cpm_sources = [cpm_sources]\n        self.cpm_sources = cpm_sources\n        self.n_sat = len(self.cpm_sources)\n        self.reset_min_chi2()\n        self._chi2_0 = None\n\n        self._prior_min_values = None\n        self._prior_max_values = None\n        self._prior_gaussian = dict()\n        self._prior_tabulated = dict()\n\n        self._n_calls = 0\n        self._color_constraint = None\n        self.model_masks = [None] * self.n_sat\n        self.fit_blending = [True] * self.n_datasets\n\n        self._file_all_models_name = None\n        self._file_all_models = None\n        self.save_fluxes = True\n\n        self._sat_masks = None\n        self._sat_times = None\n        self._sat_models = None\n        self._sat_magnifications = None\n        self._sat_source_flux = None\n        self._sat_blending_flux = 0.\n\n        self._coeffs_cache = None\n        self.n_flush = None\n\n        self.other_constraints = dict()\n\n        self.sigma_scale = 1.\n\n    def close_file_all_models(self):\n        \"\"\"closes the file to which all models are saved\"\"\"\n        self._file_all_models.close()\n        self._file_all_models = None\n\n    @property\n    def file_all_models(self):\n        \"\"\"name of the file to save all the models\"\"\"\n        return self._file_all_models_name\n\n    @file_all_models.setter\n    def file_all_models(self, file_name):\n        if self._file_all_models_name is not None:\n            self.close_file_all_models()\n        self._file_all_models_name = file_name\n        if self._file_all_models_name is not None:\n            self._file_all_models = open(self._file_all_models_name, 'w')\n\n    def reset_min_chi2(self):\n        \"\"\"reset best model and corresponding parameters\"\"\"\n        self._best_ln_prob = None\n        self._best_ln_prob_theta = None\n\n    def print_min_chi2(self):\n        \"\"\"Print best model (including prior) and corresponding chi2 value\"\"\"\n        # fmt = \" \".join([\"{:.4f}\"] * self.n_parameters)\n        fmt = \" \".join([\"{:}\"] * self.n_parameters)\n        parameters = fmt.format(*list(self._best_ln_prob_theta))\n        print(\"{:.3f}  {:}\".format(self._min_chi2, parameters))\n\n    def set_satellite_source_flux(self, sat_source_flux):\n        \"\"\"\n        Provide value of satellite source flux. It's useful only if f_s_sat\n        is not a fitting parameter.\n\n        Parameters :\n            sat_source_flux: *float*\n                Satellite source flux\n        \"\"\"\n        self._sat_source_flux = sat_source_flux\n\n    def set_parameters(self, theta):\n        \"\"\"\n        for given event set attributes from parameters_to_fit (list of str)\n        to values from theta list\n        \"\"\"\n        if len(self.parameters_to_fit) != len(theta):\n            raise ValueError('wrong number of parameters {:} vs {:}'.format(\n                    len(self.parameters_to_fit), len(theta)))\n        combined = dict(zip(self.parameters_to_fit, theta))\n        if 't_0_pl' in self.parameters_to_fit:\n            combined = utils.get_standard_parameters(combined)\n        for (param, value) in combined.items():\n            if param == 'f_s_sat':\n                self.set_satellite_source_flux(value)\n            elif param == 'f_s_sat_over_u_0':\n                try:\n                    u_0 = self.parameters_to_fit.index('u_0')\n                except Exception:\n                    raise ValueError(\n                        'This case is not yet coded: f_s_sat_over_u_0 is '\n                        'fitted, but u_0 is not')\n                self.set_satellite_source_flux(value*u_0)\n            elif param == 'f_b_sat':\n                self._sat_blending_flux = value\n            elif param == 'q_f':\n                self.event.model.set_source_flux_ratio(value)\n            elif param[:4] == 'q_f_':\n                self.event.model.set_source_flux_ratio_for_band(\n                    param[4:], value)\n            elif param == 'log_q_f':\n                self.event.model.set_source_flux_ratio(10**value)\n            elif param[:8] == 'log_q_f_':\n                self.event.model.set_source_flux_ratio_for_band(\n                    param[8:], 10**value)\n            else:\n                setattr(self.event.model.parameters, param, value)\n\n    def _run_cpm(self, theta):\n        \"\"\"set the satellite light curve and run CPM\"\"\"\n        self.set_parameters(theta)\n        n_0 = self.n_datasets - self.n_sat\n\n        if self._sat_masks is None:\n            self._sat_masks = [\n                cpm_source.residuals_mask for cpm_source in self.cpm_sources]\n            self._sat_times = [\n                self.cpm_sources[i].pixel_time[self._sat_masks[i]] + 2450000.\n                for i in range(self.n_sat)]\n            self._sat_models = [\n                np.zeros(len(cpm_source.pixel_time))\n                for cpm_source in self.cpm_sources]\n            self._sat_magnifications = [None] * self.n_sat\n\n        data = self.event.datasets\n        for i in range(self.n_sat):\n            # Here we prepare the satellite lightcurves:\n            kwargs = {\n                'time': self._sat_times[i],\n                'satellite_skycoord': data[n_0+i].satellite_skycoord}\n            if hasattr(self.event.model, \"bandpasses\"):\n                if 'K2' in self.event.model.bandpasses:\n                    kwargs['gamma'] = (\n                        self.event.model.get_limb_coeff_gamma('K2'))\n            if self.event.model.n_sources == 2:\n                if not self._MM:\n                    raise NotImplementedError('not yet coded in pixel_lensing')\n                kwargs['flux_ratio_constraint'] = 'K2'\n            if self._MM:\n                if mm_version[0] in ['0', '1']:\n                    out = self.event.model.magnification(**kwargs)\n                else:\n                    out = self.event.model.get_magnification(**kwargs)\n                self._sat_magnifications[i] = out\n                model = self._magnification_to_sat_flux(out)\n            else:\n                model = self.event.model.flux_difference(self._sat_times[i])\n                # XXX satellite_skycoord is ignored above\n            self._sat_models[i][self._sat_masks[i]] = model\n            self.cpm_sources[i].run_cpm(\n                self._sat_models[i], model_mask=self.model_masks[i])\n\n    def _sat_flux_to_magnification(self, sat_flux):\n        \"\"\"\n        translates satellite flux to magnification\n        \"\"\"\n        if self._sat_blending_flux != 0.:\n            warnings.warn(\n                \"self._sat_blending_flux is not 0. - not sure if this works\")\n\n        magnification = (\n            (sat_flux - self._sat_blending_flux) / self._sat_source_flux + 1.)\n        return magnification\n\n    def _magnification_to_sat_flux(self, magnification):\n        \"\"\"\n        translates magnification to satellite flux\n        \"\"\"\n        if self._sat_blending_flux != 0.:\n            warnings.warn(\n                \"self._sat_blending_flux is not 0. - not sure if this works\")\n\n        flux = (magnification - 1.) * self._sat_source_flux\n        flux += self._sat_blending_flux\n        return flux\n\n    def _magnitude_to_sat_flux(self, magnitude):\n        \"\"\"\n        translates magnitude in reference frame (OGLE I-band in most cases)\n        to satellite flux scale\n        \"\"\"\n        if self._sat_blending_flux != 0.:\n            warnings.warn(\n                \"self._sat_blending_flux is not 0. - not sure if this works\")\n\n        flux = Utils.get_flux_from_mag(magnitude)\n        (fs, fb) = self.event.model.get_ref_fluxes()\n        magnification = (flux - fb) / fs[0]\n        flux_sat = self._magnification_to_sat_flux(magnification)\n        return flux_sat\n\n    def set_satellite_data(self, theta):\n        \"\"\"set satellite dataset magnitudes and fluxes\"\"\"\n        self._run_cpm(theta)\n        n_0 = self.n_datasets - self.n_sat\n        for i in range(self.n_sat):\n            ii = n_0 + i\n            # OLD:\n            sat_residuals = self.cpm_sources[i].residuals[self._sat_masks[i]]\n            flux = self._sat_models[i][self._sat_masks[i]] + sat_residuals\n            # NEW - IF ACCEPTED!!! :\n            # sat_residuals = self.cpm_sources[i].residuals[\n            #     self.cpm_sources[i].residuals_mask]\n            # flux = self._sat_models[i][self.cpm_sources[i].residuals_mask]\n            # flux += sat_residuals\n            #\n            # Below we use private properties from MulensModel - this\n            # should be corrected (maybe make new MulensData object and\n            # delete the old one).\n            self.event.datasets[ii]._flux = flux\n            mag_and_err = Utils.get_mag_and_err_from_flux(\n                flux,\n                self.event.datasets[ii].err_flux, zeropoint=K2_MAG_ZEROPOINT)\n            self.event.datasets[ii]._mag = mag_and_err[0]\n            self.event.datasets[ii]._err_mag = mag_and_err[1]\n\n    def add_full_color_constraint(\n            self,\n            ref_dataset_0, ref_dataset_1, ref_dataset_2,\n            polynomial_2, sigma, ref_zero_point_0=MAG_ZEROPOINT,\n            ref_zero_point_1=MAG_ZEROPOINT, ref_zero_point_2=MAG_ZEROPOINT):\n        \"\"\"\n        Specify parameters that are used to constrain the source flux in\n        satellite band:\n                Kp-m0 = polynomial_value(m1-m2)\n        In common case (e.g., Zhu+17 method: Kp-I = f(V-I)) m0 can be equal to\n        m1 or m2.\n            ref_dataset_0 (int) - dataset to calculate satellite color\n            ref_dataset_1 (int) - first dataset for ground-based color\n            ref_dataset_2 (int) - second dataset for ground-based color\n            polynomial (np.array of floats) - color polynomial coefficients:\n                    a0, a1, a2, that will be translated to\n                    a0 + a1*(m1-m2) + a2*(m1-m2)**2\n            sigma (float) - scatter or color for the constraint\n            ref_zero_point_0 (float) - defines magnitude scale for 0-th dataset\n            ref_zero_point_1 (float) - defines magnitude scale for 1-st dataset\n            ref_zero_point_2 (float) - defines magnitude scale for 2-nd dataset\n        \"\"\"\n        self._color_constraint = [ref_dataset_0, ref_dataset_1, ref_dataset_2,\n                                  ref_zero_point_0, ref_zero_point_1,\n                                  ref_zero_point_2, polynomial_2, sigma]\n\n    def add_color_constraint(self, ref_dataset, ref_zero_point,\n                             color, sigma_color):\n        \"\"\"\n        Specify parameters that are used to constrain the source flux in\n        satellite band:\n            ref_dataset (int) - reference dataset\n            ref_zero_point (float) - magnitude zeropoint of reference dataset\n                                    probably MulensModel.utils.MAG_ZEROPOINT\n            color (float) - (satellite-ref_dataset) color (NOTE ORDER)\n            sigma_color (float) - sigma of color\n        \"\"\"\n        self._color_constraint = [\n            ref_dataset, ref_zero_point, color, sigma_color]\n\n    def _get_source_flux(self, index):\n        \"\"\"\n        Return source flux for dataset index.\n        It uses self.fit_blending properly.\n        index - int\n        \"\"\"\n        if not self._MM:\n            raise NotImplementedError('not yet coded in pixel_lensing')\n        if self.fit_blending[index]:\n            return self.event.get_ref_fluxes(index)[0][0]\n\n        if self.event.model.n_lenses > 1:\n            warnings.warn('The code is not optimized for binary lens and ' +\n                          'no blending flux. It can be very slow...')\n        fit_before = self.event.fit\n        self.event.get_chi2_for_dataset(index, fit_blending=False)\n        f_s = self.event.fit.flux_of_sources(self.event.datasets[index])[0]\n        self.event.fit = fit_before\n        return f_s\n\n    def _chi2_for_color_constraint(self, satellite_flux):\n        \"\"\"calculate chi2 for flux constraint\"\"\"\n        if not self._MM:\n            raise NotImplementedError('not yet coded in pixel_lensing')\n        before_ref = self.event.data_ref\n        if len(self._color_constraint) == 4:\n            (ref_dataset, ref_zero_point) = self._color_constraint[:2]\n            (color, sigma_color) = self._color_constraint[2:]\n        elif len(self._color_constraint) == 8:\n            (ref_dataset, ref_dataset_1) = self._color_constraint[:2]\n            (ref_dataset_2, ref_zero_point) = self._color_constraint[2:4]\n            (ref_zero_point_1, ref_zero_point_2) = self._color_constraint[4:6]\n            (polynomial, sigma_color) = self._color_constraint[6:]\n            flux_1 = self._get_source_flux(ref_dataset_1)\n            flux_2 = self._get_source_flux(ref_dataset_2)\n            mag_1 = ref_zero_point_1 - 2.5 * np.log10(flux_1)\n            mag_2 = ref_zero_point_2 - 2.5 * np.log10(flux_2)\n            c = mag_1 - mag_2\n            x = 1.\n            color = 0.\n            for p in polynomial:\n                color += x * p\n                x *= c\n        else:\n            raise ValueError('wrong size of internal variable')\n\n        flux_ref = self._get_source_flux(ref_dataset)\n        self.event.get_ref_fluxes(before_ref)\n\n        mag_ref = ref_zero_point - 2.5 * np.log10(flux_ref)\n        mag_sat = K2_MAG_ZEROPOINT - 2.5 * np.log10(satellite_flux)\n        color_value = mag_sat - mag_ref\n        out = ((color_value - color) / sigma_color)**2\n        return out\n\n    def chi2_fun(self, theta):\n        \"\"\"for a given set of parameters (theta), return the chi2\"\"\"\n        self._run_cpm(theta)\n        n = self.n_datasets - self.n_sat\n        chi2_sat = []\n        for source in self.cpm_sources:\n            residuals = source.residuals_prf()[source.residuals_mask]\n            # OLD:\n            # residuals = source.residuals[source.residuals_mask]\n            sigma = source.all_pixels_flux_err[source.residuals_mask]\n            sigma *= self.sigma_scale\n            chi2_sat.append(np.sum((residuals/sigma)**2))\n        # Correct the line below.\n        # chi2_sat = [\n        #     np.sum(self._sat_masks[i]) *\n        #     (self.cpm_sources[i].residuals_rms/np.mean(\n        #     self.event.datasets[n+i].err_flux))**2\n        #     for i in range(self.n_sat)]\n        # We also tried:\n        # chi2_sat = 0.\n        # for i in range(self.n_sat):\n            # ii = n + i\n            # rms = self.cpm_sources[i].residuals_rms_prf_photometry(\n            #     self._sat_models[i])\n            # rms /= np.mean(self.event.datasets[n+i].err_flux)\n            # chi2_sat += np.sum(self._sat_masks[i]) * rms**2\n\n        # self.chi2 = [\n        #     self.event.get_chi2_for_dataset(\n        #         i, fit_blending=self.fit_blending[i])\n        #     for i in range(n)]\n        if self._MM:\n            temp_chi2 = self.event.get_chi2_per_point()  # XXX - this\n            # ignores self.fit_blending\n        else:\n            if n > 0:\n                raise NotImplementedError('not yet coded in pixel_lensing')\n            temp_chi2 = []\n        self.chi2 = [np.sum(temp_chi2[i]) for i in range(n)]\n        self.chi2 += chi2_sat\n        if self._color_constraint is not None:\n            self.chi2.append(\n                self._chi2_for_color_constraint(self._sat_source_flux))\n        chi2 = sum(self.chi2)\n        self._last_chi2 = chi2\n        self._n_calls += 1\n        if self.save_fluxes:\n            self.fluxes = 2 * n * [0.]\n            if not self._MM:\n                if n > 0:\n                    raise NotImplementedError('not yet coded in pixel_lensing')\n            else:\n                self.event.get_chi2_per_point()\n                for i in range(n):\n                    d = self.event.datasets[i]\n                    if self.fit_blending[i]:\n                        self.fluxes[2*i] = self.event.fit.flux_of_sources(d)[0]\n                        self.fluxes[2*i+1] = self.event.fit.blending_flux(d)\n                    else:\n                        self.fluxes[2*i] = self._get_source_flux(i)\n        if self._file_all_models is not None:\n            text = \" \".join([repr(chi2)] + [repr(ll) for ll in theta])\n            if self.save_fluxes:\n                text += \" \" + \" \".join(\n                    [\"{:.5f}\".format(f) for f in self.fluxes])\n            self._file_all_models.write(text + '\\n')\n            if self.n_flush is not None and self._n_calls % self.n_flush == 0:\n                self._file_all_models.flush()\n                os.fsync(self._file_all_models.fileno())\n        if self._coeffs_cache is not None:\n            coeffs = []\n            for i in range(self.n_sat):\n                n_pixels = self.cpm_sources[i].n_pixels\n                source = self.cpm_sources[i]\n                c = [source.pixel_coeffs(j).flatten() for j in range(n_pixels)]\n                coeffs.append(np.array(c))\n            self._coeffs_cache[tuple(theta.tolist())] = coeffs\n\n        return chi2\n\n    def set_chi2_0(self, chi2_0=None):\n        \"\"\"set reference value of chi2\"\"\"\n        if chi2_0 is None:\n            chi2_0 = np.sum([np.sum(d.good) for d in self.event.datasets])\n        self._chi2_0 = chi2_0\n\n    def set_pixel_coeffs_from_samples(self, samples):\n        \"\"\"\n        Provide a matrix samples[n_models, n_params] and for each\n        model there get the cached coeffs (caching MUST be turned ON)\n        and set pixel coeffs to the mean of these cached coeffs.\n        You may want to run stop_coeffs_cache() afterward.\n        \"\"\"\n        weights = dict()\n        coeffs = dict()\n        for sample in samples:\n            key = tuple(sample.tolist())\n            if key in weights:\n                weights[key] += 1\n            else:\n                weights[key] = 1\n                coeffs[key] = self.get_cached_coeffs(key)\n        self.set_pixel_coeffs_from_dicts(coeffs, weights)\n\n    def set_pixel_coeffs_from_dicts(self, coeffs, weights=None):\n        \"\"\"\n        Take coeffs, average them, and set pixel coeffs to the averages.\n\n        Arguments :\n            coeffs: *dict*\n                Dictionary of pixel coeffs. Each value specifies a list\n                (length same as number of satellite datasets) of coeffs for all\n                pixels i.e., coeffs[key][i][j] is for\n                j-th pixel in i-th cpm_source.\n                The keys can be whatever, but most probably you want\n                tuple(list(model_parameters)) to be the keys.\n            weights: *dict*, optional\n                Dictionary of weights - uses the same keys as coeffs.\n        \"\"\"\n        keys = list(coeffs.keys())\n        if weights is None:\n            weights_ = None\n        else:\n            weights_ = [weights[key] for key in keys]\n\n        for i in range(self.n_sat):\n            for j in range(self.cpm_sources[i].n_pixels):\n                data = [coeffs[key][i][j] for key in keys]\n                average = np.average(np.array(data), 0, weights=weights_)\n                self.cpm_sources[i].set_pixel_coeffs(\n                    j, average.reshape((-1, 1)))\n\n    def set_pixel_coeffs_from_models(self, models, weights=None):\n        \"\"\"run a set of models, remember the coeffs for every pixel,\n        then average them (using weights) and remember\n\n        NOTE: this version may be not very stable numerically. Try using\n        e.g., set_pixel_coeffs_from_dicts()\n        \"\"\"\n        if self.n_sat > 1:\n            raise ValueError(\n                \"set_pixel_coeffs_from_models() doesn't allow \" +\n                \"multiple cpm_sources\")\n        n_models = len(models)\n        shape = (n_models, self.cpm_source.predictor_matrix.shape[1])\n        coeffs = [np.zeros(shape) for i in range(self.cpm_source.n_pixels)]\n\n        for i in range(n_models):\n            self._run_cpm(models[i])\n            for j in range(self.cpm_source.n_pixels):\n                coeffs[j][i] = self.cpm_source.pixel_coeffs(j).reshape(\n                    shape[1])\n\n        for j in range(self.cpm_source.n_pixels):\n            average = np.average(coeffs[j], 0, weights=weights)\n            self.cpm_source.set_pixel_coeffs(j, average.reshape((-1, 1)))\n\n    def start_coeffs_cache(self):\n        \"\"\"\n        Start internally remembering coeffs; also resets cache if caching was\n        working.\n        \"\"\"\n        self._coeffs_cache = dict()\n\n    def get_cached_coeffs(self, theta):\n        \"\"\"\n        Get pixel coeffs for model defined by theta; note that\n        theta = tuple(list(model_parameters))\n        \"\"\"\n        if self._coeffs_cache is None:\n            raise ValueError(\n                \"You want to get cached values and you haven't \" +\n                \"turned on caching (see start_coeffs_cache())? Strange...\")\n        if not isinstance(theta, tuple):\n            raise TypeError(\n                'wrong type of get_cached_coeffs() input: \\n' +\n                'got {:}, expected tuple'.format(type(theta)))\n        return self._coeffs_cache[theta]\n\n    def stop_coeffs_cache(self):\n        \"\"\"turn off internally remembering coeffs\"\"\"\n        self._coeffs_cache = None\n\n    def save_coeffs_to_fits(self, files):\n        \"\"\"saves coeffs to fits files\"\"\"\n        for (file_, cpm_source) in zip(files, self.cpm_sources):\n            cpm_source.save_coeffs_to_fits(file_)\n\n    def read_coeffs_from_fits(self, files):\n        \"\"\"read coeffs from fits files\"\"\"\n        for (file_, cpm_source) in zip(files, self.cpm_sources):\n            cpm_source.read_coeffs_from_fits(file_)\n\n    def set_prior_boundaries(\n            self, parameters_min_values, parameters_max_values):\n        \"\"\"\n        remembers 2 dictionaries that set minimum and maximum values of\n        parameters\n        \"\"\"\n        self._prior_min_values = parameters_min_values\n        self._prior_max_values = parameters_max_values\n\n    def set_prior_gaussian(self, settings):\n        \"\"\"\n        Set gaussian priors. The keywords *settings* is a *dict* with keys\n        being names of parameters (e.g., 't_E') and values being lists of 2\n        *floats* - mean and sigma (e.g., [10., 2.]).\n        \"\"\"\n        self._prior_gaussian = settings\n\n    def set_prior_tabulated(self, parameter, file_name, outside_factor=1.e-4):\n        \"\"\"\n        Add settings to calculate prior based on tabulated data.\n\n        Parameters :\n            parameter: *str*\n                Name of the parameter to be used for prior, e.g. 't_0'\n\n            file_name: *str*\n                Name of 2-column text file with a histogram. Columns are bin\n                centers and counts (the latter are normalized by this function)\n\n            outside_factor: *str*\n                Ratio of largest to smallest value of prior - used both to\n                places where histogram = 0 and values that are beyond the prior\n        \"\"\"\n        (bin_centers, counts) = np.loadtxt(file_name, unpack=True)\n        counts = counts / float(np.sum(counts))\n        min_counts = outside_factor * np.max(counts)\n        counts[counts < min_counts] = min_counts\n        self._prior_tabulated[parameter] = interp1d(\n            bin_centers, counts, fill_value=min_counts, bounds_error=False)\n\n    def ln_prior(self, theta):\n        \"\"\"return 0 in most cases, or -np.inf if beyond ranges provided\"\"\"\n        out = 0.\n        outside = -np.inf\n\n        if self._prior_min_values is not None:\n            for (parameter, value) in self._prior_min_values.items():\n                index = self.parameters_to_fit.index(parameter)\n                if theta[index] < value:\n                    return outside\n\n        if self._prior_max_values is not None:\n            for (parameter, value) in self._prior_max_values.items():\n                index = self.parameters_to_fit.index(parameter)\n                if theta[index] > value:\n                    return outside\n\n        for (key, value) in self.other_constraints.items():\n            if key == 't_0':\n                t_0_1 = theta[self.parameters_to_fit.index('t_0_1')]\n                t_0_2 = theta[self.parameters_to_fit.index('t_0_2')]\n                if value == 't_0_1 < t_0_2':\n                    if t_0_1 >= t_0_2:\n                        return outside\n                elif value == 't_0_1 > t_0_2':\n                    if t_0_2 >= t_0_1:\n                        return outside\n                else:\n                    raise ValueError('urecognized value: {:}'.format(value))\n            elif key == 'min_blending_flux':\n                (data, limit) = value\n                index = self.event.datasets.index(data)\n                if not self.fit_blending[index]:\n                    raise NotImplementedError(\n                        'min_blending_flux and no blending flux make no sense')\n                if not self._MM:\n                    raise NotImplementedError('not yet coded in pixel_lensing')\n                self.event.get_chi2_for_dataset(index)\n                if self.event.fit.blending_flux(data) <= limit:\n                    return outside\n            else:\n                raise KeyError('unkown constraint: {:}'.format(key))\n\n        for (parameter, gauss) in self._prior_gaussian.items():\n            value = theta[self.parameters_to_fit.index(parameter)]\n            out -= ((value - gauss[0]) / gauss[1])**2\n\n        for (parameter, function) in self._prior_tabulated.items():\n            value = theta[self.parameters_to_fit.index(parameter)]\n            out += np.log(function(value))\n\n        return out\n\n    def ln_like(self, theta):\n        \"\"\"logarithm of likelihood\"\"\"\n        chi2 = self.chi2_fun(theta)\n\n        ln_likelihood = -0.5 * (chi2 - self._chi2_0)\n\n        return ln_likelihood\n\n    def ln_prob(self, theta):\n        \"\"\"combines prior and likelihood\"\"\"\n        ln_prior = self.ln_prior(theta)\n        if not np.isfinite(ln_prior):\n            if self.save_fluxes:\n                return (-np.inf, self.fluxes)\n            else:\n                return -np.inf\n\n        ln_like = self.ln_like(theta)\n        if np.isnan(ln_like):\n            if self.save_fluxes:\n                return (-np.inf, self.fluxes)\n            else:\n                return -np.inf\n\n        ln_probability = ln_prior + ln_like\n\n        if self._best_ln_prob is None or ln_probability > self._best_ln_prob:\n            self._min_chi2 = self._last_chi2\n            self._best_ln_prob = ln_probability\n            self._best_ln_prob_theta = theta\n\n        if self.save_fluxes:\n            return (ln_probability, self.fluxes)\n        else:\n            return ln_probability\n\n    def set_MN_cube(self, min_values, max_values):\n        \"\"\"\n        remembers how to transform unit cube to physical parameters for MN\n        \"\"\"\n        self._MN_cube = [(min_values[i], (max_values[i]-min_values[i]))\n                         for i in range(self.n_parameters)]\n\n    def transform_MN_cube(self, cube):\n        \"\"\"transform unit cube to physical parameters\"\"\"\n        out = []\n        for i in range(len(cube)):\n            (zero_point, range_) = self._MN_cube[i]\n            out.append(zero_point + range_ * cube[i])\n        return np.array(out)\n\n    def satellite_maximum(self):\n        \"\"\"\n        return time of maximum magnification, its value, and corresponding\n        flux for the satellite dataset; takes into account the epochs when\n        satellite data exist\n\n        NOTE: This function is not yet fully tested.\n        \"\"\"\n        if self._MM:\n            return self._satellite_maximum_MM()\n        else:\n            return (self.event.model.parameters.t_0,\n                    self.event.model.parameters.f_s_sat_over_beta)\n\n    def _satellite_maximum_MM(self):\n        \"\"\"\n        satellite_maximum() for MulensModel\n        \"\"\"\n        if not self._MM:\n            raise NotImplementedError('not yet coded in pixel_lensing')\n        if self.n_sat > 1:\n            raise ValueError(\n                \"satellite_maximum() doesn't allow \" +\n                \"multiple cpm_sources\")\n        index = np.argmax(self._sat_magnifications[0])\n        magnification = self._sat_magnifications[0][index]\n        u_0 = (2*magnification*(magnification**2-1.)**-.5 - 2.)**.5\n        if self.event.model.n_sources == 1:\n            trajectory = Trajectory(\n                self._sat_times[-1], parameters=self.event.model.parameters,\n                parallax=self.event.model._parallax, coords=self.event.coords,\n                satellite_skycoord=self.event.datasets[-1].satellite_skycoord)\n            if trajectory.y[index] < 0.:\n                u_0 = -u_0\n        else:\n            warnings.warn(\"binary source model - code is not yet ready \" +\n                          \"to provide signed u_0 for K2\")\n        return (self._sat_times[0][index], u_0, magnification)\n\n    def plot_sat_magnitudes(self, **kwargs):\n        \"\"\"\n        Plot satellite model in reference magnitude system\n        \"\"\"\n        if not self._MM:\n            raise NotImplementedError('not yet coded in pixel_lensing')\n        data_ref = self.event.model.data_ref\n        (fs, fb) = self.event.model.get_ref_fluxes()\n        n = self.n_datasets - self.n_sat\n        if 'zorder' not in kwargs:\n            kwargs['zorder'] = np.inf\n\n        for i in range(self.n_sat):\n            times = self._sat_times[i] - 2450000.\n            flux = self._sat_magnifications[i] * fs[0] + fb\n            plt.plot(\n                times, Utils.get_mag_from_flux(flux), **kwargs)\n        self.event.model.data_ref = data_ref\n\n    def _legend_standard_plot(self, legend_order, legend_kwargs, color_list,\n                              label_list, alphas):\n        \"\"\"\n        plots legend for standard plots\n        \"\"\"\n        # legend_kwargs['ncol'] = 2 # XXX\n        if legend_order is not None:\n            (handles, labels) = plt.gca().get_legend_handles_labels()\n            if isinstance(legend_order, tuple):\n                for (i, l_o) in enumerate(legend_order):\n                    handles_ = [handles[idx] for idx in l_o]\n                    labels_ = [labels[idx] for idx in l_o]\n                    if i == 0:\n                        first_legend = plt.legend(handles_, labels_,\n                                                  loc='upper left')\n                        plt.gca().add_artist(first_legend)\n                    else:\n                        plt.legend(handles_, labels_, loc='upper right',\n                                   **legend_kwargs)\n            else:\n                handles_ = [handles[idx] for idx in legend_order]\n                labels_ = [labels[idx] for idx in legend_order]\n                plt.legend(handles_, labels_, **legend_kwargs)\n        elif color_list is not None and label_list is not None:\n            plt.legend(loc='best', **legend_kwargs)\n        else:  # Prepare legend \"manually\":\n            if self.n_sat == 0:\n                plt.legend(loc='best', **legend_kwargs)\n            else:\n                black_line = mlines.Line2D(\n                    [], [], color='black', marker='o',\n                    lw=0, markersize=5, label='ground-based', alpha=alphas[0])\n                red_line = mlines.Line2D(\n                    [], [], color='red', marker='o',\n                    lw=0, markersize=5, label='K2C9 data')\n                blue_line = mlines.Line2D(\n                    [], [], color='orange', lw=2, markersize=5,\n                    label='K2C9 model')  # alpha=0.75,\n                handles_ = [red_line, blue_line, black_line]\n                plt.legend(handles=handles_, loc='best', **legend_kwargs)\n\n    def standard_plot(self, t_start, t_stop, ylim, title=None,\n                      label_list=None, color_list=None, line_width=1.5,\n                      legend_order=None, separate_residuals=False,\n                      model_line_width=4., legend_kwargs=None,\n                      fluxes_y_axis=None, ground_model_zorder=None,\n                      sat_model_zorder=None):\n        \"\"\"\n        Make plot of the event and residuals.\n\n        Parameters :\n            XXX\n\n            ylim: [*float*, *float*]\n                A list o two values that are used to set y axis limits\n                (in mag).\n\n            fluxes_y_axis: *list* or *np.ndarray* of *floats*\n                K2 fluxes which will be marked on right side of Y axis.\n\n            ground_model_zorder: *float*\n                Passed to pyplot to control if ground model is plotted\n                at the top or bottom.\n\n            sat_model_zorder: *float*\n                Passed to pyplot to control if satellite model is\n                plotted at the top or bottom. Defualts to *np.inf*.\n        \"\"\"\n        if not self._MM:\n            raise NotImplementedError('not yet coded in pixel_lensing')\n        if (label_list is None) != (color_list is None):\n            raise ValueError('wrong input in standard_plot')\n        if not separate_residuals:\n            grid_spec = gridspec.GridSpec(2, 1, height_ratios=[5, 1],\n                                          hspace=0.12)\n        else:\n            grid_spec = gridspec.GridSpec(3, 1, height_ratios=[5, 1, 1],\n                                          hspace=0.13)\n        plt.figure()\n        plt.subplot(grid_spec[0])\n        if title is not None:\n            plt.title(title)\n        alphas = [0.5] * self.n_datasets\n        for i in range(self.n_sat):\n            alphas[-(i+1)] = 1.\n\n        self.event.plot_model(\n            color='black', subtract_2450000=True,\n            t_start=t_start+2450000., t_stop=t_stop+2450000.,\n            label=\"ground-based model\", lw=model_line_width,\n            zorder=ground_model_zorder)\n        self.plot_sat_magnitudes(color='orange', lw=2,\n                                 label=\"K2 model\", zorder=sat_model_zorder)\n\n        if color_list is not None:\n            color_list_ = color_list\n        else:\n            if self.n_sat == 0:\n                color_list_ = None\n            else:\n                color_list_ = ['black'] * (self.n_datasets-self.n_sat)\n                color_list_ += ['red']*self.n_sat\n        zorder_list = np.arange(self.n_datasets, 0, -1)\n        zorder_list[1] = self.n_datasets + 1\n\n        self.event.plot_data(  # alpha_list=alphas,\n            zorder_list=zorder_list, mfc='none', lw=line_width, mew=line_width,\n            marker='o', markersize=6, subtract_2450000=True,\n            color_list=color_list_, label_list=label_list)\n        if ylim is not None:\n            plt.ylim(ylim[0], ylim[1])\n        else:\n            ylim = plt.ylim()\n        plt.xlim(t_start, t_stop)\n        plt.gca().tick_params(top=True, direction='in')\n\n        if legend_kwargs is None:\n            legend_kwargs = dict()\n        self._legend_standard_plot(legend_order, legend_kwargs, color_list,\n                                   label_list, alphas)\n\n        y_K2_max = self._magnitude_to_sat_flux(np.min(ylim))\n        y_K2_min = self._magnitude_to_sat_flux(np.max(ylim))\n        print(\"Y-axis limits:\")\n        print(\"   mag:      {:.3f} {:.3f}\".format(*ylim))\n        print(\"   K2 flux:  {:.2f} {:.2f}\".format(y_K2_min, y_K2_max))\n\n        if fluxes_y_axis is not None:\n            y_color = 'red'\n            y_label = r'K2 differential counts [e$^-$s$^{-1}$]'\n\n            min_ = np.min(fluxes_y_axis)\n            if min_ < y_K2_min or np.max(fluxes_y_axis) > y_K2_max:\n                raise ValueError('ylim incompatible with fluxes_y_axis')\n\n            (fs, fb) = self.event.model.get_ref_fluxes()\n            mags = self._sat_flux_to_magnification(np.array(fluxes_y_axis))\n            mags_fluxes = Utils.get_mag_from_flux(fb + fs[0] * mags)\n            ax2 = plt.gca().twinx()\n            ax2.set_ylabel(y_label).set_color(y_color)\n            ax2.spines['right'].set_color(y_color)\n            ax2.set_ylim(ylim[0], ylim[1])\n            ax2.tick_params(axis='y', colors=y_color)\n            plt.yticks(mags_fluxes.tolist(), fluxes_y_axis, color=y_color)\n\n        plt.subplot(grid_spec[1])\n        kwargs_ = dict(mfc='none', lw=line_width, mew=line_width)\n        if not separate_residuals:\n            self.event.plot_residuals(subtract_2450000=True, **kwargs_)\n            plt.xlim(t_start, t_stop)\n        else:\n            plt.plot([0., 3000000.], [0., 0.], color='black')\n            self.event.datasets[-1].plot(\n                phot_fmt='mag', show_errorbars=True, subtract_2450000=True,\n                model=self.event.model, plot_residuals=True, **kwargs_)\n            plt.ylim(0.29, -0.29)  # XXX\n            plt.ylabel('K2 residuals')\n            plt.xlim(t_start, t_stop)\n            plt.gca().tick_params(top=True, direction='in')\n            plt.gca().tick_params(right=True, direction='in')\n\n            plt.subplot(grid_spec[2])\n            plt.plot([0., 3000000.], [0., 0.], color='black')\n            for data in self.event.datasets[:-1]:\n                data.plot(\n                    phot_fmt='mag', show_errorbars=True, subtract_2450000=True,\n                    model=self.event.model, plot_residuals=True, **kwargs_)\n            plt.ylabel('Residuals')\n            plt.xlim(t_start, t_stop)\n        plt.gca().tick_params(top=True, direction='in')\n        plt.gca().tick_params(right=True, direction='in')\n\n    def very_standard_plot(self, t_start, t_stop, ylim, title=None):\n        \"\"\"Make plot of the event and residuals. \"\"\"\n        if not self._MM:\n            raise NotImplementedError('not yet coded in pixel_lensing')\n        grid_spec = gridspec.GridSpec(2, 1, height_ratios=[5, 1], hspace=0.1)\n        plt.figure()\n        plt.subplot(grid_spec[0])\n        if title is not None:\n            plt.title(title)\n        alphas = [0.95] * self.n_datasets\n        for i in range(self.n_sat):\n            alphas[-(i+1)] = 1.\n\n        constraint = None\n        if self.event.model.n_sources > 1:\n            constraint = 'I'  # XXX\n        self.event.plot_model(\n            color='black', subtract_2450000=True,\n            t_start=t_start+2450000., t_stop=t_stop+2450000.,\n            flux_ratio_constraint=constraint)\n        self.plot_sat_magnitudes(color='blue', lw=3.5, alpha=0.75)\n\n        if self.n_sat == 0:\n            colors = None\n        else:\n            colors = ['black'] * (self.n_datasets - self.n_sat)\n            colors += ['red'] * self.n_sat\n\n        self.event.plot_data(\n            alpha_list=alphas,\n            zorder_list=np.arange(self.n_datasets, 0, -1),\n            marker='o', markersize=5, subtract_2450000=True,\n            color_list=colors)\n        if ylim is not None:\n            plt.ylim(ylim[0], ylim[1])\n        plt.xlim(t_start, t_stop)\n\n        # Prepare legend \"manually\":\n        if self.n_sat == 0:\n            plt.legend(fontsize='small')\n        else:\n            black_line = mlines.Line2D(\n                [], [], color='black', marker='o', lw=0,\n                markersize=5, label='ground-based', alpha=alphas[0])\n            red_line = mlines.Line2D(\n                [], [], color='red', marker='o', lw=0,\n                markersize=5, label='K2C9 data')\n            blue_line = mlines.Line2D(\n                [], [], color='blue', lw=3.5, alpha=0.75,\n                markersize=5, label='K2C9 model')\n            plt.legend(handles=[red_line, blue_line, black_line], loc='best')\n\n        plt.subplot(grid_spec[1])\n        self.event.plot_residuals(subtract_2450000=True)\n        plt.xlim(t_start, t_stop)\n", "meta": {"hexsha": "e6ac7c6881e59b0a90325011c7da9934acaecb89", "size": 40729, "ext": "py", "lang": "Python", "max_stars_repo_path": "source/MCPM/minimizer.py", "max_stars_repo_name": "NewCPM/MCPM", "max_stars_repo_head_hexsha": "9fb9b7725ccc4452701be47d103ab61f81b4595b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-04-10T22:35:11.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-16T21:00:40.000Z", "max_issues_repo_path": "source/MCPM/minimizer.py", "max_issues_repo_name": "CPM-project/MCPM", "max_issues_repo_head_hexsha": "9fb9b7725ccc4452701be47d103ab61f81b4595b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/MCPM/minimizer.py", "max_forks_repo_name": "CPM-project/MCPM", "max_forks_repo_head_hexsha": "9fb9b7725ccc4452701be47d103ab61f81b4595b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9336683417, "max_line_length": 79, "alphanum_fraction": 0.5743082325, "include": true, "reason": "import numpy,from scipy", "num_tokens": 9384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3140505578320071, "lm_q1q2_score": 0.18375134386567593}}
{"text": "#! /usr/bin/env python\n\nimport matplotlib\nfrom math import log\nimport numpy as np\n# import scipy.interpolate as interpolate\nimport matplotlib.pyplot as plt\nimport operator\nimport matplotlib.patheffects\nimport math\nfrom matplotlib import gridspec\ntry:\n    import CIAlign.utilityFunctions as utilityFunctions\nexcept ImportError:\n    import utilityFunctions\nimport os\nmatplotlib.use('Agg')\n\n\ndef getAxisUnits(subplot):\n    '''\n    Translates the height of one unit of y axis\n    and width of one unit of x axis into pixels\n    Translates height of y axis and width of x axis\n    to pixels\n\n    Parameters\n    ----------\n    subplot: matplotlib.pyplot.subplot\n        An open subplot\n\n    Returns\n    -------\n    D: dict\n        Keys are names of axis heights and widths, the values are in units\n        or pixels\n    '''\n    axis_dimensions = subplot.transData.transform(\n        [(subplot.get_xlim()[1],\n          subplot.get_ylim()[1]), (0, 0)]) - subplot.transData.transform((\n              0, 0))\n    D = dict()\n    # height of y in pixels\n    D['axis_height_px'] = axis_dimensions[0][1]\n    # height of x in pixels\n    D['axis_width_px'] = axis_dimensions[0][0]\n    D['axis_bottom'], D['axis_top'] = subplot.get_ylim()\n    D['axis_left'], D['axis_right'] = subplot.get_xlim()\n    # total number of units on x axis\n    D['axis_width_u'] = D['axis_right'] - D['axis_left']\n    # total number of units on y axis\n    D['axis_height_u'] = D['axis_top'] - D['axis_bottom']\n    # height of one y axis unit in pixels\n    D['u_height_px'] = D['axis_height_px'] / D['axis_height_u']\n    # width of one x axis unit in pixels\n    D['u_width_px'] = D['axis_width_px'] / D['axis_width_u']\n\n    return (D)\n\n\ndef getFontSize(figure, subplot, height_u):\n    '''\n    Based on axes units, converts specified number of y axis units into\n    the font size in points\n\n    Parameters\n    ----------\n    figure: matplotlib.Figure\n        An open figure\n\n    subplot: matplotlib.pyplot.subplot\n        An open subplot\n\n    height_u: float\n        Height in units\n\n    Returns\n    -------\n    Height_points*1.8: float\n        adjusted height in points\n    '''\n\n    D = getAxisUnits(subplot)\n    perc_height = height_u / (D['axis_top'] - D['axis_bottom'])\n    height_pixels = D['axis_height_px'] * perc_height\n    dpi = figure.dpi\n    height_points = PixelsToPoints(height_pixels, dpi)\n\n    return (height_points * 1.8)\n\n\ndef PixelsToPoints(pixels, dpi):\n    '''\n    Converts pixel values to point values\n\n    Parameters\n    ----------\n    pixels: float\n        pixel value\n\n    dpi: int\n        dpi value\n\n    Returns\n    -------\n    points: float\n        points value\n    '''\n    # one point is 1/72 of an inch\n    points = pixels * (72 / dpi)\n\n    return (points)\n\n\ndef getLetters(typ='nt', fontname='monospace', dpi=500):\n    '''\n    Generates a temporary image file for every letter (4 nt or 20 aa)\n    Each letter extends to the full length of both axes\n\n    Parameters\n    ----------\n    typ: string\n        nt (default) or aa\n\n    fontname: string\n        name of a font (default: monospace)\n\n    dpi: int\n        DPI value (default: 500)\n\n    Returns\n    -------\n    none\n    '''\n    # obtain color scheme depending on nt or aa alignment\n    if typ == 'nt':\n        colours = utilityFunctions.getNtColours()\n    elif typ == 'aa':\n        colours = utilityFunctions.getAAColours()\n    # for each possible base/aa create temporary plot\n    for base in colours.keys():\n        f = plt.figure(figsize=(1, 1), dpi=dpi, edgecolor='black')\n        a = f.add_subplot(1, 1, 1)\n        a.set_xlim(0, 1)\n        a.set_ylim(0, 1)\n        fs = getFontSize(f, a, 1)\n        a.text(0.5, 0.02, base, fontsize=fs*0.95,\n               fontdict={'family': 'monospace',\n                         'name': fontname},\n               color=colours[base], va='baseline',\n               ha='center')\n        plt.gca().set_axis_off()\n        a.margins(0, 0)\n        f.subplots_adjust(top=1, bottom=0, right=1, left=0,\n                          wspace=None, hspace=None)\n        a.set_frame_on(False)\n        # temporarily safe plot in working directory\n        f.savefig(\"%s_temp.png\" % base, dpi=500,\n                  pad_inches=0.1)\n        plt.close()\n\n\ndef findConsensus(alignment, log, consensus_type=\"majority\"):\n    '''\n    Calculates the consensus sequence and the coverage for the alignment\n    Utilises different types of the consensus\n\n    Parameters\n    ----------\n    alignment: np.array\n        The alignment stored as a numpy array\n\n    log: string\n        name of log file\n\n    consensus_type: string\n        majority (default) or majority_nongap\n\n    Returns\n    -------\n    consensus: list of strings\n        consensus sequence\n\n    coverage: list of floats\n        alignment coverage\n    '''\n\n    consensus = []\n    coverage = []\n    numberOfSequences = len(alignment[:, 0])\n\n    # need the reverse of array to access every column\n    for i in range(0, len(alignment[0, :])):\n        unique, counts = np.unique(alignment[:, i], return_counts=True)\n        count = dict(zip(unique, counts))\n        unique_ng = unique[unique != \"-\"]\n        counts_ng = counts[unique != \"-\"]\n        # deal with gap only columns\n        if counts_ng.size == 0:\n            count_ng = {\"N\": len(alignment[:, i])}\n            nonGapContent = 0\n        else:\n            count_ng = dict(zip(unique_ng, counts_ng))\n            if '-' in count:\n                nonGapContent = 1-(count['-']/numberOfSequences)\n            else:\n                nonGapContent = 1\n\n        # dealing with gap only collumns\n        maxChar, maxCount = max(count.items(), key=operator.itemgetter(1))\n        maxChar_ng, maxCount_ng = max(count_ng.items(),\n                                      key=operator.itemgetter(1))\n\n        # if there is an equal number of gap and non-gap characters at the\n        # site, keep the non-gap character\n        # if majoriy_nongap chosen, use the nongap\n        if maxCount_ng == maxCount or consensus_type == \"majority_nongap\":\n            maxChar = maxChar_ng\n        consensus.append(maxChar)\n        coverage.append(nonGapContent)\n\n    return consensus, coverage\n\n\ndef makeCoveragePlot(coverage, dest, dpi=300, height=3, width=5,\n                     colour='#007bf5'):\n    '''\n    Creates a plot of the coverage\n\n    Parameters\n    ----------\n    coverage: list of strings\n        Coverage for alignment\n\n    dest: str\n        folder to store file\n\n    dpi: int\n        DPI value (default: 500)\n\n    height: int\n            height of plot, default: 3\n\n    width: int\n            height of plot, default: 5\n\n    colour: str\n            coverage colour (default: #007bf5)\n\n    Returns\n    -------\n    none\n    '''\n\n    fontsize = 1500 / dpi\n    x = np.arange(0, len(coverage), 1)\n    y = coverage\n\n    xmax = x.max()\n    # used for polynomial interpolation\n    # xmin = x.min()\n    # N = 100\n    # xx = np.linspace(xmin, xmax, N)\n\n    # plain plotting of the coverage\n    f = plt.figure(figsize=(width, height), dpi=dpi)\n    a = f.add_subplot(2, 1, 1)\n    a.plot(x, y, color=colour)\n    a.set_xlabel('Position', fontsize=fontsize)\n    a.set_ylabel('Coverage', fontsize=fontsize)\n    a.set_xticks([0, xmax])\n    a.set_xticklabels([0, xmax], fontsize=fontsize)\n    a.set_yticks(np.arange(0, 1.1, 0.5))\n    a.set_yticklabels(np.arange(0, 1.1, 0.5), fontsize=fontsize)\n\n    # b = f.add_subplot('212')\n\n    # polynomial interpolation leaving this in just in case\n    # c = f.add_subplot('313')\n    # z = np.polyfit(x, bla, 30)\n    # p = np.poly1d(z)\n    # c.plot(xx, p(xx))\n    # xnew = np.linspace(x.min(),x.max(),300)\n    # 300 represents number of points to make between T.min and T.max\n\n    # interpolating the coverage function to make it smooth\n    # t, c, k = interpolate.splrep(x, y, s=0, k=4)\n    # spline = interpolate.BSpline(t, c, k, extrapolate=False)\n    # b.plot(xx, spline(xx), color=colour)\n    # b.set_xlabel('Position', fontsize=fontsize)\n    # b.set_ylabel('Coverage (Smoothed)', fontsize=fontsize)\n    # b.set_xticks([0, xmax])\n    # b.set_xticklabels([0, xmax], fontsize=fontsize)\n    # b.set_yticks(np.arange(0, 1.1, 0.5))\n    # b.set_yticklabels(np.arange(0, 1.1, 0.5), fontsize=fontsize)\n    f.savefig(dest, dpi=dpi, bbox_inches='tight')\n\n\ndef sequence_logo(alignment,\n                  figname,\n                  typ='nt',\n                  figfontname='Arial',\n                  figdpi=300,\n                  figrowlength=50,\n                  start=0,\n                  end=0):\n    '''\n    Creates a sequence logo based on an entropy calculation using letters\n    Scales the letters according to the information content of the alignment\n    Representation of the consensus sequence of the alignment\n\n    Parameters\n    ----------\n    alignment: np.array\n        The alignment stored as a numpy array\n\n    figname: str\n        name of figure\n\n    typ: str\n        Either 'aa' - amino acid - or 'nt' - nucleotide\n\n    figfontname: str\n            Name of font, default: Arial\n\n    figdpi: int\n            DPI (default: 300)\n\n    figrowlength: int\n            clength of figure (default: 50)\n\n    start: int\n           start pos to be turned into logo\n\n    end: int\n         end pos to be turned into logo\n\n    Returns\n    -------\n    none\n    '''\n\n    if start == 0 and end == 0:\n        alignment_width = len(alignment[0, :])\n    else:\n        if end == 0:\n            end = len(alignment[0,:])\n        alignment_width = len(alignment[0,start:end])\n\n    if alignment_width < figrowlength:\n        figrowlength = alignment_width\n    nsegs = math.ceil(alignment_width / figrowlength)\n    f = plt.figure(figsize=(figrowlength, nsegs*2), dpi=figdpi)\n    gs = gridspec.GridSpec(ncols=1, nrows=nsegs)\n    getLetters(typ=typ, fontname=figfontname, dpi=figdpi)\n    rstart = start\n    rend = rstart + figrowlength\n\n    for n in range(nsegs):\n\n        if rend > (alignment_width + start):\n            rend = alignment_width + start\n        a = plt.subplot(gs[n])\n        a.set_xlim(rstart, rstart+figrowlength)\n        if typ == 'nt':\n            a.set_ylim(0, 2.1)\n            a.set_yticks(np.arange(0, 2.1, 1))\n        elif typ == 'aa':\n            a.set_ylim(0, 4.6)\n            a.set_yticks(np.arange(0, 4.6, 1))\n        limits = a.axis()\n\n        # for each column calculate heights via entropy\n        # and scale letters accordlingly\n        for i in range(rstart, rend):\n            unique, counts = np.unique(alignment[:, i],\n                                       return_counts=True)\n            count = dict(zip(unique, counts))\n            height_per_base, info_per_base = calc_entropy(count,\n                                                          len(alignment[:, 0]),\n                                                          typ=typ)\n            height_sum_higher = 0\n            Z = zip(height_per_base.keys(), height_per_base.values())\n            Z = sorted(Z, key=lambda x: x[1])\n            for base, height in Z:\n                if height > 0:\n                    L = plt.imread(\"%s_temp.png\" % base)\n                    a.imshow(L, extent=(i, i+1, height_sum_higher,\n                                        height_sum_higher+height),\n                             filternorm=False)\n\n                    height_sum_higher += height\n        a.axis(limits)\n        a.set_xticks([rstart, rend])\n        a.set_xticklabels([rstart, rend])\n\n        a.spines['right'].set_visible(False)\n        a.spines['top'].set_visible(False)\n        if n == (nsegs - 1):\n            a.set_xlabel(\"Position\")\n        a.set_ylabel(\"Bit Score\")\n        rstart += figrowlength\n        rend += figrowlength\n    # obtain colours\n    if typ == 'nt':\n        allbases = utilityFunctions.getNtColours()\n    elif typ == 'aa':\n        allbases = utilityFunctions.getAAColours()\n    for base in allbases:\n        os.unlink(\"%s_temp.png\" % base)\n    # save plot using figname\n    f.savefig(figname, dpi=figdpi, bbox_inches='tight')\n    plt.close()\n\n\ndef sequence_bar_logo(alignment,\n                      figname,\n                      typ='nt',\n                      figdpi=300,\n                      figrowlength=50,\n                      start=0,\n                      end=0):\n    '''\n    Creates a sequence logo based on an entropy calculation using bars\n    Scales the bars according to the information content of the alignment\n    Representation of the consensus sequence of the alignment\n\n    Parameters\n    ----------\n    alignment: np.array\n        The alignment stored as a numpy array\n\n    figname: str\n        name of figure\n\n    typ: str\n        Either 'aa' - amino acid - or 'nt' - nucleotide\n\n    figfontname: str\n            Name of font, default: Arial\n\n    figdpi: int\n            DPI (default: 300)\n\n    figrowlength: int\n            clength of figure (default: 50)\n\n    start: int\n           start pos to be turned into logo\n\n    end: int\n         end pos to be turned into logo\n\n    Returns\n    -------\n    none\n    '''\n\n    if start == 0 and end == 0:\n        alignment_width = len(alignment[0, :])\n    else:\n        if end == 0:\n            end = len(alignment[0,:])\n        alignment_width = len(alignment[0,start:end])\n\n    if alignment_width < figrowlength:\n        figrowlength = alignment_width\n    nsegs = math.ceil(alignment_width / figrowlength)\n    f = plt.figure(figsize=(figrowlength/5, nsegs*2), dpi=figdpi)\n    gs = gridspec.GridSpec(ncols=1, nrows=nsegs)\n    rstart = start\n    rend = rstart + figrowlength\n\n    for n in range(nsegs):\n        if rend > (alignment_width + start):\n            rend = alignment_width + start\n        axes = f.add_subplot(gs[n])\n        axes.set_xlim(rstart-0.5, rend-0.5)\n        if typ == 'nt':\n            axes.set_ylim(0, 2.1)\n            axes.set_yticks(np.arange(0, 2.1, 1))\n        elif typ == 'aa':\n            axes.set_ylim(0, 4.6)\n            axes.set_yticks(np.arange(0, 4.6, 1))\n        seq_count = len(alignment[:, 0])\n        width = 0.75\n        ind = np.arange(rstart, rend)\n\n        if typ == \"nt\":\n            element_list = utilityFunctions.getNtColours()\n            colours = utilityFunctions.getNtColours()\n        elif typ == \"aa\":\n            element_list = utilityFunctions.getAAColours()\n            colours = utilityFunctions.getAAColours()\n        height_list = {}\n\n        for element in element_list:\n            height_list[element] = []\n\n        bottom_height = []\n        # for each column calculate heights via entropy\n        # and scale letters accordlingly\n        for i in range(rstart, rend):\n            unique, counts = np.unique(alignment[:, i], return_counts=True)\n            count = dict(zip(unique, counts))\n            height_per_base, info_per_base = calc_entropy(count, seq_count,\n                                                          typ)\n            bottom_height.append(0)\n\n            # need a list of each nt/aa separately to plot them as bars\n            for base, height in height_per_base.items():\n                height_list[base].append(height_per_base[base])\n\n        # stag bars on top of each other\n        for base, height in height_list.items():\n            plt.bar(ind, height, width, bottom=bottom_height,\n                    color=colours[base])\n            bottom_height = [i+j for i, j in zip(bottom_height, height)]\n\n        plt.xticks([rstart, rend-1], [rstart+1, rend])\n        plt.yticks(np.arange(0, 2.1, 1))\n        plt.xlabel(\"Position\")\n        plt.ylabel(\"Bit Score\")\n\n        axes.spines['right'].set_visible(False)\n        axes.spines['top'].set_visible(False)\n        rstart += figrowlength\n        rend += figrowlength\n    # save plot as figname\n    plt.savefig(figname, bbox_inches='tight', dpi=figdpi)\n    plt.close()\n\n\ndef calc_entropy(count, seq_count, typ):\n    '''\n    Creates a sequence logo based on an entropy calculation using bars\n    Scales the bars according to the information content of the alignment\n    Representation of the consensus sequence of the alignment\n\n    Parameters\n    ----------\n    count: dict\n        of nt/aa with counts\n\n    seq_count: int\n        number of sequences in alignment\n\n    typ: str\n        nt or aa\n\n    Returns\n    -------\n    height_per_base: dictionary\n        height for each nt/aa\n\n    info_per_base: dictionary\n        information content for each nt/aa\n\n    '''\n    # obtain nt/aa lists, use colour scheme for that w/o using colours here\n    # just because another list of nt/aa would be obsolete\n    if typ == \"nt\":\n        element_list = utilityFunctions.getNtColours()\n        s = 4\n        max_entropy = log(4, 2)\n    elif typ == \"aa\":\n        element_list = utilityFunctions.getAAColours()\n        s = 20\n        max_entropy = log(20, 2)\n\n    info_per_base = {}\n    freq_per_base = {}\n    height_per_base = {}\n    entropy_per_base = {}\n\n    for element in element_list:\n        info_per_base[element] = 0\n        freq_per_base[element] = 0\n        height_per_base[element] = 0\n        entropy_per_base[element] = 0\n\n    # correct for small sample sizes\n    sample_size_correction = (1/log(s,2)) * ((s-1)/(2*seq_count))\n    gap_correction = seq_count\n    if count.get(\"-\"):\n        seq_count -= count.get(\"-\")\n    # correct for gaps, since they lower the information content\n    gap_correction = seq_count/gap_correction\n    entropy = 0\n    if seq_count == 0:\n        return height_per_base, info_per_base\n    # calculate entropy, from that information, from that height\n    for base, quantity in count.items():\n        if base != \"-\":\n            frequency = quantity/seq_count\n            freq_per_base[base] = frequency\n            entropy -= frequency*log(frequency, 2)\n            info_per_base[base] = max_entropy + frequency*log(frequency, 2)\n            entropy_per_base[base] = -frequency * log(frequency, 2)\n    information_per_column = max_entropy - entropy - sample_size_correction\n\n    # if the information content is constant throughout the column,\n    # these value will be negative. Since this does not add any information\n    # set them to 0\n    # they can be negative due to the sample size correction (otherwise they'd be 0)\n    for base, quantity in info_per_base.items():\n        if freq_per_base[base]*information_per_column < 0:\n            height_per_base[base] = 0\n        else:\n            # scale to accomodate gaps\n            height_per_base[base] = (gap_correction *\n                                     freq_per_base[base] *\n                                     information_per_column)\n\n    return height_per_base, info_per_base\n", "meta": {"hexsha": "31ec261302dc7d1959fb2887e90e30247fd0fdf9", "size": 18447, "ext": "py", "lang": "Python", "max_stars_repo_path": "CIAlign/consensusSeq.py", "max_stars_repo_name": "schnamo/CIAlign", "max_stars_repo_head_hexsha": "6985d74bb9a59535bb01751fcb739dd5ca219607", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CIAlign/consensusSeq.py", "max_issues_repo_name": "schnamo/CIAlign", "max_issues_repo_head_hexsha": "6985d74bb9a59535bb01751fcb739dd5ca219607", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CIAlign/consensusSeq.py", "max_forks_repo_name": "schnamo/CIAlign", "max_forks_repo_head_hexsha": "6985d74bb9a59535bb01751fcb739dd5ca219607", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9464285714, "max_line_length": 84, "alphanum_fraction": 0.5837805605, "include": true, "reason": "import numpy,import scipy", "num_tokens": 4560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.1837513401092681}}
{"text": "\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#from glob import glob\nimport os, sys, csv, re\nfrom numpy import array, loadtxt, savetxt,  amin, amax, uint8,arange,logical_or, mean\nfrom numpy.random import random,shuffle\nfrom time import time,sleep,localtime\n#import pymorph as p\nfrom PIL import Image\nimport matplotlib.cm as cm\n\n#length of first generation sticky ends\nfgsn=5\ntvsn=8\ntyp='xj'\n#typ='tw'\nmodel=\"new\"\ntestdir=\"/windows/D/NY/python/DNAmodule/\"\nif sys.platform==\"win32\":\n    testdir=\"D:/NY/python/DNAmodule/\"\ntemplatedir=testdir+\"templates/\"\nallstrandfile=testdir+\"strands-new-cond-cnv-low8.csv\"\nif typ=='xj':\n  tvsn=5\n  fgsn=3\n\n\n#bodylen=6\n#selen=4\n\nextract = lambda x, y: dict(zip(x, map(y.get, x)))\ncols={10:\"#008000;\",11:\"#aa0044;\",12:\"#d45500;\",13:\"#668000;\",14:\"#ff00ff;\",15:\"#00ff00;\",16:\"#008080;\",17:\"#000080;\",18:\"#800000;\",20:\"#800080;\"}\n\n\ndef noRepetitions(lst,length, cgs=0):\n    \"\"\"takes a list of possible sequences and removes those containing sections of repeating bases of length 'length' and, optionally, those containing local CG accumulations of length 'cgs' (default: disabled with cgs=0).\n    Input: string list for DNA, integer for length, returns reduced string list\"\"\"\n    newitems=[]\n    for item in lst:\n        flag=0\n        for base in [\"G\",\"A\",\"T\",\"C\"]:\n            if item.find(base*length)>-1:\n                flag=1\n                break\n        if cgs>0:\n            for pos in range(len(item)-cgs):\n                if item[pos:pos+cgs].count(\"C\")+item[pos:pos+cgs].count(\"G\")==cgs:\n                    flag=1\n                    break\n\n        if flag==0: newitems=newitems+[item]\n    return newitems\n\ndef CGContent(lst,lower,upper,  verbose=True):\n    \"\"\"reduces a list of DNA sequences to ones with CG content in the range (lower,upper). Verbose prints the actual content\"\"\"\n    newlist=[]\n    for item in lst:\n        cont=0\n        for char in item:\n            if char==\"G\" or char==\"C\":cont=cont+1\n        cont=cont/float(len(item))\n        if (lower<cont) & (cont<upper):\n            newlist=newlist+[item]\n            if verbose==True: print cont\n    return newlist\n\n#def findPalindromic(lseq):\n #   \"\"\"takes a list of DNA sequences and returns the ones that are entirely palindromic. Why the hell do I need this function?\"\"\"\n  #  ispal=[]\n   # for seq in lseq:\n\t#seq = seq.upper()        \n\t#if seq[:len(seq)/2]==get_complement(seq[-(len(seq)/2):][::-1]): ispal=ispal+[seq]\n#    return ispal\n\n\ndef genSingle(char,totallength):\n    \"\"\"generates a DNA duplex with maximised randomness (input random char length 'char' and intended length of strand)\"\"\"\n    f=randBase(char)\n    fcomp=get_complement(f)\n    j=0\n    while len(f)<totallength and j<20000:\n        j=j+1\n        breakflag=1\n        bases=[\"G\",\"A\",\"T\",\"C\"]\n        shuffle(bases)\n        i=0\n        for base in bases:\n            i=i+1\n            f=f+base\n            fcomp=get_complement(f)\n            if f[:-1].find(f[-char:])+f[:-1].find(f[-char:][::-1])+fcomp[:-1].find(f[-char:])+fcomp[:-1].find(f[-char:][::-1]) == -4:\n                breakflag=0\n                print i\n                break\n            f=f[:-1]\n        if breakflag==1:\n            f=f[:-1]\n    print \"iterations \", j\n    return f\n\ndef findSortList(item,mylist,num):\n    \"\"\"looks for the occurrence of an item in a given list, starting from num, and removes it.\n    Helper function for PossCompl\"\"\"\n    for i in range(num, len(mylist)):\n        if mylist[i]==item:\n            mylist.pop(i)\n            return i-1\n            break\n\n        #\ndef find_key(dic, val):\n    #\n    \"\"\"return the key of dictionary dic given the value\"\"\"\n    #\n    return [k for k, v in dic.iteritems() if v == val][0]\n\ndef pylabPilPal(cmap_name,N):\n    cmap = cm.get_cmap(cmap_name, N)\n    return (cmap(arange(N))[:,0:3].reshape(1,-1)[0]*256).astype(uint8)\n\n\ndef uniq(seq, idfun=None):\n    \"\"\"return all unique items in a list (preserves list order)\"\"\"\n    # order preserving\n    if idfun is None:\n        def idfun(x): return x\n    seen = {}\n    result = []\n    for item in seq:\n        marker = idfun(item)\n        if marker in seen: continue\n        seen[marker] = 1\n        result.append(item)\n    return result\n\n\ndef generate_possibles(length):\n    b=['A','C','G','T']\n    for i in range(2, length+1):\n        a=['A'+s for s in b]\n        c=['C'+s for s in b]\n        g=['G'+s for s in b]\n        t=['T'+s for s in b]\n        b=a\n        b.extend(c)\n        b.extend(g)\n        b.extend(t)\n    return b\n\ndef sortedDictValues(adict):\n    \"\"\"sort a dictionary's values by the order of the keys in it.\"\"\"\n    keys = adict.keys()\n    keys.sort()\n    return map(adict.get, keys)\n\n\ndef OD2C(OD, lDNA,DNAvol=5., H2Ovol=500.):\n  return (OD*3.5e-5)/(DNAvol*(1000/H2Ovol)*0.001*lDNA*330)\n\ndef randBase(length=1, bases=[\"G\",\"A\",\"T\",\"C\"]):\n    result=\"\"\n    for i in range(length):\n        a=int(random(1)*len(bases))\n        result=result+bases[a]\n    return result\n\ndef allstrands(allstrandfile,redux=False):\n    \"\"\"reads sequence identifiers and sequences from CSV into a dictionary.\"\"\"\n    strandsdict={}\n    csvfile = open(allstrandfile)\n    dialect = csv.Sniffer().sniff(csvfile.read(1024))\n    csvfile.seek(0)\n    data = csv.reader(csvfile, dialect)\n    # ... process CSV file contents here ...\n    for row in data:\n        strandsdict[row[0]]=row[1]\n    if redux:\n        for key in strandsdict.keys():\n            strandsdict[key]=strandsdict[key].replace(\" \",\"\")\n            strandsdict[key]=strandsdict[key].replace(\"5'-\",\"\")\n            strandsdict[key]=strandsdict[key].replace(\"-3'\",\"\")\n\n    return strandsdict\n\ndef get_complement(string):\n    \"\"\"returns a complementary DNA sequence, e.g. GCTA for TAGC. Mind the sequence inversion!\"\"\"\n    string=string.replace('G','1')\n    string=string.replace('A','2')\n    string=string.replace('T','3')\n    string=string.replace('C','4')\n    string=string.replace('1','C')\n    string=string.replace('2','T')\n    string=string.replace('3','A')\n    string=string.replace('4','G')\n    string=string.replace('X','Z')#for 'blank' sticky ends and cinnamate\n    return string[::-1]\n\n    \n    \ndef test_strands(strands,charl=5,verbose=False):\n  forb=0\n  for n in range(len(strands)):\n    for i in range(len(strands[n])-charl+1):\n      test=get_complement(strands[n][i:i+charl])\n      for j in range(n)+range(n+1,len(strands)):\n\tfor k in range(len(strands[j])-charl+1):\n\t  if strands[j][k:k+charl]==test: \n\t    if verbose: print 'forbidden: ', key, i, j\n\t    forb=forb+1\n  return forb\n    \n    \n    \ndef hamming(s1, s2):\n    nc=0\n    for i in range(len(s1)):\n        if s2[-i]==get_complement(s1[i]): nc=nc+1\n        if s2[i]==s1[i]:nc=nc+1\n    return nc/float(len(s1))\n\ndef countercheck(sequence, strfile=allstrandfile,revtest=True, bmmatch=5,  emmatch=7):\n    stdic=allstrands(strfile, redux=True)\n    psdic=allstrands(testdir+\"DNAspecs/pseudohelices.csv\")\n    out=\"\"\n    for key in stdic.keys():\n        strand=stdic[key]\n        rstrand=stdic[key][::-1]\n        for i in range(len(strand)-len(sequence)+1):\n            num=0\n            rnum=0\n            for j in range(len(sequence)):\n                if not sequence[j]==get_complement(strand)[j+i]: num=num+1\n                if not sequence[j]==get_complement(rstrand)[j+i]: rnum=rnum+1\n\n            if revtest:\n                if not i in [0, len(strand)-len(sequence)] and rnum<=bmmatch: out=out+ \"Warning! insufficient mismatch, %s[%d]:%d\\n\"%(key,i,num)\n                if i in [0, len(strand)-len(sequence)] and rnum<=emmatch: out=out+ \"Warning! insufficient SE mismatch, %s[%d]:%d\\n\"%(key,i,num)\n            if not i in [0, len(strand)-len(sequence)] and num<=bmmatch: out=out+ \"Warning! insufficient reverse mismatch, %s[%d]:%d\\n\"%(key,i,rnum)\n            if i in [0, len(strand)-len(sequence)] and num<=emmatch: out=out+ \"Warning! insufficient SE reverse mismatch, %s[%d]:%d\\n\"%(key,i,rnum)\n    for key in psdic.keys():\n        strand=psdic[key]\n        rstrand=psdic[key][::-1]\n        for i in range(len(strand)-len(sequence)+1):\n            num=0\n            rnum=0\n            for j in range(len(sequence)):\n                if not sequence[j]==get_complement(strand)[j+i]: num=num+1\n                if not sequence[j]==get_complement(rstrand)[j+i]: rnum=rnum+1\n            if revtest:\n                if num<=bmmatch: out=out+ \"Warning! insufficient mismatch, %s[%d]:%d\\n\"%(key,i,num)\n            if rnum<=bmmatch: out=out+ \"Warning! insufficient reverse mismatch, %s[%d]:%d\\n\"%(key,i,rnum)\n    return out\n\ndef TMelt(string, mg=\"12.5e-3\", conc=\"5e-7\", meltdir=testdir+'../MELTING5.0.3/executable', comp='', verbose=False):\n    \"\"\"passes a DNA sequence to the external MELTING Java app and returns\n    the approximate melting temperature, entropy and enthalpy. Default values for Mg++\n    and DNA concentration can be adjusted as well as the location of the melting5.jar\n    executable. Note: This function assumes your system's decimal separator to be a dot '.', not a comma ','!\"\"\"\n    thisdir=os.getcwd()\n    #os.chdir(meltdir)\n    #if os.path.exists('melttemp.txt'): os.remove('melttemp.txt')\n    if len(comp) >0: os.system('melting -S%s -C%s -G%s -P%s -Hdnadna -Omelttemp.txt'%(string,comp[::-1],mg,conc))\n    #os.system('java -jar melting5.jar -S %s -C %s -E Mg=%s -P %s -H dnadna -O melttemp.txt'%(string,comp[::-1],mg,conc))\n    else:os.system('melting -S%s -G%s -P%s -Hdnadna -Omelttemp.txt'%(string,mg,conc))\n    #os.system('java -jar melting5.jar -S %s -E Mg=%s -P %s -H dnadna -O melttemp.txt'%(string,mg,conc))\n    f=open('melttemp.txt')\n    dat=f.read()\n    f.close()\n    if verbose:\n        print os.getcwd()\n        print 'melting -S%s -G%s -P%s -Hdnadna -Omelttemp.txt'%(string,mg,conc)\n        print dat\n    dat=dat.replace(',','')\n    if dat.find('SEVERE') > -1: res={'temp':-300,'S':-1,'H':-1}\n    else:\n        res={}\n        se=re.finditer(': .*? J.mol', dat)\n        res['H']=float(se.next().group(0)[2:-6])\n        res['S']=float(se.next().group(0)[2:-6])\n        res[\"temp\"]=float(re.search('temperature: .*? deg C', dat).group(0)[13:-6])\n    os.chdir(thisdir)\n    if os.path.exists('melttemp.txt'): os.remove('melttemp.txt')\n    return res\n\n\n\ndef TMeltSelect(lst, interv=(20, 40), comp=[], mg=\"12.5e-3\", conc=\"5e-7\", meltdir=testdir+'../MELTING5.0.3/executable',  verbose=False, threads=1):\n    mdir={}\n    thisdir=os.getcwd()\n    #os.chdir(meltdir)\n    for i in range(len(lst)/threads):\n        if verbose: \n\t  if len(comp)>0: print ';'.join([\"melting -S'%s' -C'%s' -G%s -P%s -Hdnadna -Omelttemp%d.txt\"%(lst[threads*i+j],comp[threads*i+j],mg,conc, j) for j in range(threads)])\n\t  else: print ';'.join([\"melting -S'%s' -G%s -P%s -Hdnadna -Omelttemp%d.txt\"%(lst[threads*i+j],mg,conc, j) for j in range(threads)])\n        if len(comp) >0: os.system(';'.join([\"melting -S'%s' -C'%s' -G%s -P%s -Hdnadna -Omelttemp%d.txt\"%(lst[threads*i+j],comp[threads*i+j],mg,conc, j) for j in range(threads)]))\n        else:os.system(';'.join([\"melting -S'%s' -G%s -P%s -Hdnadna -Omelttemp%d.txt\"%(lst[threads*i+j],mg,conc, j) for j in range(threads)]))\n        for j in range(threads):\n\t  f=open('melttemp%d.txt'%j)\n\t  dat=f.read()\n\t  f.close()\n\t  dat=dat.replace(',','')\n\t  if dat.find('SEVERE') > -1: res={'temp':-300,'S':-1,'H':-1}\n\t  else:\n\t    res={}\n\t    se=re.finditer(': .*? J.mol', dat)\n\t    res['H']=float(se.next().group(0)[2:-6])\n\t    res['S']=float(se.next().group(0)[2:-6])\n\t    res[\"temp\"]=float(re.search('temperature: .*? deg C', dat).group(0)[13:-6])\n            if interv[0]<res['temp']<interv[1]: \n                mdir[lst[i*threads+j]]=res['temp']\n                if verbose: print \"%d: s.e. %s, T melt. %.02f\"%(i*threads+j,  lst[i*threads+j],  res['temp'])\n    os.system('rm melttemp?.txt')\n    os.chdir(thisdir)\n    return mdir\n\ndef ExchangeSticky(trange=(10, 45)):\n    sevensticky=[\"tw-ICN4-11\",\"tw-ICN4-13\", \"tw-AA2-11\", \"tw-AA2-13\",\"tw-BB2-11\", \"tw-BB2-13\",\"tw-ICN4-03\",\"tw-ICN4-05\", \"tw-AA2-03\",\"tw-AA2-05\",\"tw-u3B-03\",\"tw-u3B-05\"]\n    replacedir={}\n    for end in sevensticky: replacedir[end]=\"\"\n\nclass seedtile:\n    \"\"\"Definitions and helper functions for Tong's seed tiles.\"\"\"\n    def __init__(self,newID):\n        self.seedID=newID\n        self.type=self.seedID[0].upper()\n        try: self.num=int(self.seedID[1])\n        except ValueError: self.num=0\n        self.stringIDs={}\n        self.stringSequences={}\n        self.subsequences={}\n        self.cand=[]\n        self.matches={\"10B\":\"15C\",\"10C\":\"11B\",\"10D\":\"12E\",\"10F\":\"13B\",\"10G\":\"14B\",\"15B\":\"16H\",\"11C\":\"16G\", \"11D\":\"16F\",\"12C\":\"16E\",\"13C\":\"16D\",\"13D\":\"16C\",\"18C\":\"16B\",\"17B\":\"20A\",\"17C\":\"11E\",\"17D\":\"12B\", \"17E\":\"12A\",\"17F\":\"13E\",\"17G\":\"18B\",'11E': '17C', '12A': '17E', '12B': '17D', '16H': '15B', '12E': '10D', '13E': '17F', '11B': '10C', '16D': '13C', '16E': '12C', '16F': '11D', '16G': '11C', '16B': '18C', '16C': '13D', '20A': '17B', '15C': '10B', '14B': '10G', '18B': '17G', '12D': '10E'}\n        self.semfile=testdir+'sematches.txt'\n        if model=='new':self.semfile=testdir+'sematches-new.txt'\n        self.connect=[(\"10D\",\"10E\"),(\"12D\",\"12E\"),(\"11C\",\"11D\"),(\"16G\",\"16F\"),(\"13C\",\"13D\"),(\"16C\",\"16E\"),(\"17D\",\"17E\"),(\"12A\",\"12B\")]\n        self.sticky=[\"11F\",\"13F\",\"11A\",\"13A\"]\n        self.templatefile=\"SEEDmidtemplate%d.svg\"%tvsn\n        if self.num==1: self.templatefile=\"A1template%d.svg\"%tvsn\n        if self.num==7: self.templatefile=\"B7template%d.svg\"%tvsn\n        if typ=='xj': \n\t  self.templatefile=\"SEEDmidtemplatexj.svg\"\n          if self.num==1: self.templatefile=\"A1templatexj.svg\"\n          if self.num==7: self.templatefile=\"B7templatexj.svg\"\n        self.templateStrands={}\n        self.stringNums=[10,11,12,13,14,15,16,17,18,20]\n\n    def init(self, newID):\n        \"\"\"initialises the tile to a new template\"\"\"\n        self.seedID=newID\n        self.type=self.seedID[0].upper()        \n        if self.num==7: self.templatefile=\"B7template%d.svg\"%tvsn\n        if typ=='xj': \n\t  self.templatefile=\"SEEDmidtemplatexj.svg\"\n          if self.num==1: self.templatefile=\"A1templatexj.svg\"\n          if self.num==7: self.templatefile=\"B7templatexj.svg\"\n        self.num=int(self.seedID[1])\n        self.stringIDs={}\n        self.stringSequences={}\n\n    def readSVGtemplate(self, verbose=False):\n        o=open(templatedir+self.templatefile)\n        svg=o.read()\n        o.close()\n        lengths={}\n        for num in self.stringNums:\n            index=0\n            for alph in \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\": \n                n=re.search(\"%02d%s.*?<\"%(num,alph), svg)\n                if type(n).__name__!='SRE_Match':\n                    pass\n                else:\n                    n=n.group(0)[:-1]\n                    aug=len(n)\n                    if n[-1]==\"R\":  self.templateStrands[\"%02d%s\"%(num,alph)]=(index+aug,index)\n                    if n[-1]==\"N\":  self.templateStrands[\"%02d%s\"%(num,alph)]=(index,index+aug)\n                    if n[-1]==\"T\":\n                        aug=int(n[-2])\n                        self.templateStrands[\"%02d%s\"%(num,alph)]=(index,index+aug)\n                        \n                    if aug<4: #infer from 'B' strand\n                        if re.search(\"%02dB.*?<\"%num, svg).group(0)[-1]=='R':self.templateStrands[\"%02d%s\"%(num,alph)]=(index+aug,index)\n                        else:self.templateStrands[\"%02d%s\"%(num,alph)]=(index,index+aug)\n\n                    if verbose:\n                        print \"%s, %02d\"%(n,aug)\n                    index=index+aug\n            if verbose: print \"Strand %d, length %d\"%(num, index)\n            lengths[num]=index\n        return lengths    \n\n    def replaceStrand(self, s1, s2):\n        num=find_key(self.stringIDs, s1)\n        self.stringIDs[num]=s2\n        self.getStrands()\n\n\n    def getIDs(self):\n        \"\"\"identifies SEED tile strings according to the seed ID and\n        writes them into the stringIDs dictionary\"\"\"\n        self.stringIDs[12]=\"tw-ICEN-12\"\n        self.stringIDs[20]=\"tw-ICEN-20\"\n        a=[10,14,15,16,17,18]\n        for i in a:\n            self.stringIDs[i]=\"tw-%s-%02d\"%(self.seedID,i)\n        a=[11,13]\n        for i in a:\n            self.stringIDs[i]=\"tw-%s%d-%02d\"%(2*self.seedID[0],tvsn, i)\n        if self.seedID==\"A1\":\n            self.stringIDs[10]=\"tw-ICEN-10\"\n            self.stringIDs[11]=\"tw-ICN%d-11\"%tvsn\n            self.stringIDs[13]=\"tw-ICN%d-13\"%tvsn\n            self.stringIDs[17]=\"tw-ICEN-17\"\n        if self.seedID==\"B7\":\n            self.stringIDs[16]=\"tw-ICEN-16\"\n        if typ=='xj':\n\t  for i in [10,11,12,13,14,17,20]:self.stringIDs[i]=self.stringIDs[i]+'xj'\n        #print self.stringIDs\n\n    def getStrands(self, verbose=False):\n        \"\"\"reads DNA sequences from CSV file and pairs them with identifiers (dictionary)\"\"\"\n        self.getIDs()\n        strandsd=allstrands(allstrandfile)\n        self.stringSequences=extract(self.stringIDs.values(),strandsd)\n        for key in self.stringSequences.keys():\n            if verbose: print key\n            self.stringSequences[key]=self.stringSequences[key].replace(\" \",\"\")\n            self.stringSequences[key]=self.stringSequences[key].replace(\"5'-\",\"\")\n            self.stringSequences[key]=self.stringSequences[key].replace(\"-3'\",\"\")\n\n\n\n\n    def getSubseq(self,num, comp=False):\n        \"\"\"splits all sequences into possible subsequences of length num (for num=5, as in 12345, 23456, 34567 ...).\n        Identifiers AABBB, with AA sequence number, BBB position of first base in string.\n        Negative identifiers denote reversed sequences.\n        If comp is set, the function returns complementary subsequences instead.\"\"\"\n        ##add reverses!!!\n        self.getStrands()\n        for  key in self.stringSequences.keys():\n            string=self.stringSequences[key].replace(\"5'-\",\"\")\n            string=string.replace(\"-3'\",\"\")\n            string=string.replace(\" \",\"\")\n            for i in range(len(string)+1-num):\n                if comp:\n                    self.subsequences[get_complement(string[i:i+num])]=int(key[-2:])*1000+i\n                    self.subsequences[get_complement(string[i:i+num][::-1])]=-int(key[-2:])*1000+i\n                else:\n                    self.subsequences[string[i:i+num]]=int(key[-2:])*1000+i\n                    self.subsequences[string[i:i+num][::-1]]=-int(key[-2:])*1000+i\n\n\n    def PossCompl(self, num):\n        self.getSubseq(num,comp=True)\n        vals=self.subsequences.keys()\n        vals.sort()\n        vals=uniq(vals)\n        self.cand=generate_possibles(num)\n        print \"before: %d\"%len(self.cand)\n        a=0\n        for string in vals:\n            a=findSortList(string,self.cand,a)\n        print \"after: %d\"%len(self.cand)\n\n\n    def fetchAllSticky(self,charlen):\n        allsticky={}\n        strandsd=allstrands(allstrandfile)\n        for key in strandsd.keys():\n            strand=strandsd[key]\n            strand=strand.replace(\" \",\"\")\n            strand=strand.replace(\"5'-\",\"\")\n            strand=strand.replace(\"-3'\",\"\")\n            strandsd[key]=strand\n\n        for tile in [\"A1\", \"B2\",\"B3\", \"A4\", \"B5\", \"A6\", \"B7\"]:\n            for i in [10,14,15,16,17,18]:\n                thisid=\"tw-%s-%02d\"%(tile,i)\n                try:\n                    allsticky[thisid]=strandsd[thisid][:16+charlen-1]\n                    if thisid==\"tw-B7-18\":\n                        allsticky[thisid+\"e\"]=strandsd[thisid][-(6+charlen-1):][::-1]\n                    if allsticky[thisid][:6]==\"TTTTTT\":\n                        allsticky[thisid]=allsticky[thisid][:6+charlen-1]\n                except KeyError:\n                    pass\n            if model=='new':#why doesn't this register?\n                for i in [10,14,15,16,17,18]:\n                    thisid=\"tw-%s-%02dn\"%(tile,i)#use a newer version if possible (what to do about dated strands?)\n                    try:\n                        allsticky[thisid]=strandsd[thisid][:16+charlen-1]\n                        dummy=allsticky.pop(thisid[:-1])\n                        if thisid==\"tw-B7-18\":\n                            allsticky[thisid+\"e\"]=strandsd[thisid][-(6+charlen-1):][::-1]\n                        if allsticky[thisid][:6]==\"TTTTTT\":\n                            allsticky[thisid]=allsticky[thisid][:6+charlen-1]\n                    except KeyError:\n                        pass\n\n        for thisid in [\"tw-ICN%d-11\"%tvsn,\"tw-ICN%d-13\"%tvsn, \"tw-AA%d-11\"%tvsn, \"tw-AA%d-13\"%tvsn,\"tw-BB%d-11\"%tvsn, \"tw-BB%d-13\"%tvsn,\"tw-ICN%d-03\"%tvsn,\"tw-ICN%d-05\"%tvsn, \"tw-AA%d-03\"%tvsn,\"tw-AA%d-05\"%tvsn,\"tw-u3B%d-03\"%tvsn,\"tw-u3B%d-05\"%tvsn,\"tw-BB%d-03\"%tvsn,\"tw-BB%d-05\"%tvsn]:\n            allsticky[thisid+\"b\"]=strandsd[thisid][:tvsn+charlen-1]\n            allsticky[thisid+\"e\"]=strandsd[thisid][-(tvsn+charlen-1):][::-1]\n\n\n        if fgsn==0:\n            for thisid in [\"tw-u2AB-02\",\"tw-u2AB-06\",\"tw-u2AB-09\", \"tw-u2AB-10\", \"tw-u2AB-16\", \"tw-u2AB-17\"]:#find solution for new model\n                allsticky[thisid+\"b\"]=strandsd[thisid][:9+charlen-1]\n                allsticky[thisid+\"e\"]=strandsd[thisid][-(9+charlen-1):][::-1]\n        else:\n            for i in [1, 2, 6, 7, 8, 9, 10,14,15,16,17,18, 19]:\n                thisid=\"tw-u2AB%d-%02d\"%(fgsn,i)#use a newer version if possible (what to do about dated strands?)\n                allsticky[thisid]=strandsd[thisid][:fgsn+charlen-1]\n        return allsticky\n\n    def fetchBody(self):\n        body={}\n        bfile=open(testdir+\"blunt-seed.txt\")\n        for line in bfile:\n            body[line.split(\"\\t\")[0]]=line.split(\"\\t\")[1].replace('\\n','')\n\n        return body\n\n    def fetchMatches(self):\n        body={}\n        bfile=open(self.semfile)\n        for line in bfile:\n            line=line.replace('#t','%d'%tvsn)\n            body[line.split(\"\\t\")[0]]=line.split(\"\\t\")[1][:-1]\n            body[line.split(\"\\t\")[1][:-1]]=line.split(\"\\t\")[0]\n        return body\n\n    def ReplaceSticky(self,seqID,selen,bm=6,sm=5,palin=0, revtest=False,  replacements={},tlim=300,  nlim=20000, verbose=False, constraints=''):\n        \"\"\"argument: strand ID like 'tw-B7-10'. Sticky ends are _always_ at 5' end!\n         options: bm=6, maximum number of random body matches in a row\n              sm=5, maximum number of random sticky end matches in a row\n              palin=0, number of palindromic bases (for hairpins) at each end. This results           in a shortened path matrix\n              revtest=False, check for reverse compelentarity (not necessary, parallel DNA binding is unfavourable\n              replacements: dictionary of already generated replacement SE's {'tw-A6-17':'AGTAGGC...'}\n              tlim=300, time limit in seconds\n              nlim=20000, max. number of generated possibilities\n              verbose=False, prints all matches (A LOT!!!!)\n              constraints='', string of pre-determined bases like 'UYAXXXGC', 'S' and 'W' for G/C or A/T, 'X' for free choice, Replaces rows in the path matrix. \"\"\"\n        t1=time()\n        self.allsticky=self.fetchAllSticky(max(bm,sm))\n        if len(replacements)>0:\n            for key in replacements.keys():\n                if verbose==True: print key,\":\",self.allsticky[key]\n                self.allsticky[key]=replacements[key]+self.allsticky[key][-max(bm,sm)+1:]\n                if verbose==True: print \"replaced by\", self.allsticky[key]\n                self.getStrands()\n        body=self.fetchBody()\n        if self.seedID in [\"A1\",\"B2\", \"B3\", \"A4\", \"B5\", \"A6\", \"B7\", \"A''\", \"B''\" , \"I''\"]:\n            #comptile=firstgentile(self.type+\"'\")\n            comptile=newfgtile(self.type+\"'\")\n        if self.seedID in [\"A'\", \"B'\", \"I'\"]:\n            #comptile=secgentile(self.type+\"''\")\n            comptile=newsgtile(self.type+\"''\")\n        compbody=comptile.fetchBody()\n        matches=self.fetchMatches()\n        # identify sticky end\n        stubseq=self.allsticky[seqID][-max(bm,sm)+1:]\n        print len(stubseq)\n        #take it from allsticky... and delete\n        del self.allsticky[seqID]\n\n        try: del self.allsticky[matches[seqID]]\n        except KeyError: pass\n\n        self.basematrix=[]\n        for i in range(0,selen-palin):\n            bases=[\"G\",\"A\",\"T\",\"C\"]\n            shuffle(bases)\n            self.basematrix=self.basematrix+bases\n        self.basematrix=array(self.basematrix).reshape(selen-palin,4)\n        if len(constraints)>0:\n            for i in range(0,selen-palin):\n                try:\n                    if constraints[i]=='S': self.basematrix[i,:]=['C', 'C', 'G', 'G']\n                    if constraints[i]=='W': self.basematrix[i,:]=['A', 'A', 'T', 'T']\n                    if constraints[i] in ['G','A','T','C']: self.basematrix[i,:]=[constraints[i]]*4\n                except IndexError: break\n\n        possibles=[]\n        baseind=0\n        seind=0\n        count=0\n        path=[0]\n        alloverflag=0\n\n        while(alloverflag==0):\n            matchflag=0\n            testseq=stubseq\n            for i in range(len(path)):\n                testseq=self.basematrix[i,path[i]]+testseq\n            seseq=get_complement(testseq[:sm])\n            for m,n in self.allsticky.iteritems():\n                count=count+1\n                if revtest:\n                    rev=n.find(seseq[::-1])\n                else: rev=-1\n                if rev+n.find(seseq)>-2:\n                    if verbose: print \"s.e.\",count,m,rev,n.find(seseq),path, len(possibles)\n                    matchflag=1\n                    break\n            bodyseq=get_complement(testseq[:bm])\n            for m,n in body.iteritems():\n                count=count+1\n                if count%10000==0: print len(possibles)\n                if revtest:\n                    rev=n.find(bodyseq[::-1])\n                else: rev=-1\n                if rev+n.find(bodyseq)>-2:\n                    if verbose: print \"body\",count,m,rev,n.find(bodyseq),path, len(possibles)\n                    matchflag=1\n                    break\n\n        #-----------conditions for aborting-----------------------\n            if mean(path)==3 and len(path)==selen-palin-1:\n                print len(path), baseind,count\n                print \"no combinations left, aborting!\"\n                alloverflag=1\n                break\n            else:\n                if len(possibles)>nlim:\n                    print \"%d possible sequences, aborting!\"%nlim\n                    alloverflag=1\n                    break\n                if time()-t1>tlim:\n                    print \"time limit of %d seconds exceeded, aborting!\"%tlim\n                    alloverflag=1\n                    break\n                if matchflag==0 and seind==selen-palin-1: #base passed testss\n                    nmatchflag=0\n                    if palin>0:\n                        # make sure that middle bit _not_ palindromic\n                        for i in range((selen-2*palin)/2):\n                            if get_complement(testseq[:selen-2*palin][-i-1])==testseq[:selen-2*palin][i]:\n                                nmatchflag=1 #\n                                break #\n                        testseq=get_complement(testseq[selen-2*palin:selen-palin])+testseq #append the palindromic part's complement\n                        for c in range(palin):\n                            seseq=get_complement(testseq[c:c+sm])\n                            for m,n in self.allsticky.iteritems():\n                                count=count+1\n                                if revtest:\n                                    rev=n.find(seseq[::-1])\n                                else: rev=-1\n                                if rev+n.find(seseq)>-2:\n                                    if verbose: print \"Palindrome SE match\",count,m,rev,n.find(seseq)\n                                    nmatchflag=1\n                                    break\n                            if nmatchflag==1: break\n                            seseq=get_complement(testseq[c:c+bm])\n                            for m,n in body.iteritems():\n                                count=count+1\n                                if revtest:\n                                    rev=n.find(seseq[::-1])\n                                else: rev=-1\n                                if rev+n.find(seseq)>-2:\n                                    if verbose: print \"Palindrome body match\",count,m,rev,n.find(seseq) #TODO: probably only [::-1] case necessary\n                                    nmatchflag=1 #f\n                                    break\n                            if nmatchflag==1: break\n                        #TODO: where is the countercheck routine?\n                    try:\n                        match=matches[seqID]\n                        match=get_complement(testseq[:selen])+match[selen:]\n                    except KeyError:\n                        match=get_complement(testseq[:selen])\n                    for a in range(len(match)-sm):\n                        seseq=get_complement(match[a:a+sm])\n                        for m,n in self.allsticky.iteritems():\n                            count=count+1\n                            if n.find(seseq)>-1:\n                                if verbose: print \"comp s.e.\",count,m,n.find(seseq)#,n.find(seseq[::-1])\n                                nmatchflag=1\n                                break\n                        if nmatchflag==1: break\n                    for a in range(len(match)-bm):\n                        seseq=match[a:a+bm]\n                        for m,n in body.iteritems():\n                            count=count+1\n                            if n.find(seseq)>-1:\n                                if verbose: print \"comp body\",count,m,n.find(seseq)#,n.find(seseq[::-1])\n                                nmatchflag=1\n                                break\n                        if nmatchflag==1: break\n                    if nmatchflag==0: possibles=possibles+[testseq[:selen]]\n                    else:\n                        if verbose==True: print \"complement match!\"\n\n                if matchflag==1 or seind==selen-palin-1:\n                    while(baseind==3):\n                        testseq=testseq[1:]#when?\n                        seind=seind-1\n                        path=path[:-1]\n                        try: baseind=path[-1]\n                        except IndexError:\n                            print \"End of line!\"\n                            alloverflag=1\n                            break\n                    if alloverflag==1: break\n                    baseind=baseind+1\n                    testseq=bases[baseind]+testseq[1:]\n                    path[-1]=baseind\n\n                if matchflag==0 and seind<selen-palin-1:\n                    seind=seind+1\n                    baseind=0\n                    testseq=bases[baseind]+testseq\n                    path=path+[baseind]\n\n\n        print \"Finished in %.2f minutes, resulting in %d possible sequences from %d string comparisons\"%((time()-t1)/60.0,len(possibles),count)\n        return possibles\n\n\n    def testStructure(self):\n        self.getStrands()\n        self.readSVGtemplate()\n        failcount=0\n        stickcount=0\n        for key in self.matches.keys():\n            si=self.templateStrands[key]\n            try:\n                sii=self.templateStrands[self.matches[key]]\n                if si[1]<si[0]:\n                    seqi=self.stringSequences[self.stringIDs[int(key[0:2])]][si[1]:si[0]][::-1]\n                else:\n                    seqi=self.stringSequences[self.stringIDs[int(key[0:2])]][si[0]:si[1]]\n                if sii[1]<sii[0]:\n                    seqii=self.stringSequences[self.stringIDs[int(self.matches[key][0:2])]][sii[1]:sii[0]][::-1]\n                else:\n                    seqii=self.stringSequences[self.stringIDs[int(self.matches[key][0:2])]][sii[0]:sii[1]]\n                if seqi != get_complement(seqii):\n                    print \"Match? %s:%s %s:%s\"%(key,seqi,self.matches[key],get_complement(seqii))\n                    failcount+=1\n            except KeyError: print \"Key Error: %s,%s\"%(key,self.matches[key])\n        print \"Missed matches: %s\"%failcount\n        m=firstgentile(\"%s'\"%self.type)\n        try: dummy= self.num\n        except AttributeError:\n            print \"First gen?\"\n            return\n        if self.num==1: m=firstgentile(\"I'\")\n        m.getStrands()\n        m.readSVGtemplate()\n        for i in range(4):\n            #print i\n            si=self.templateStrands[self.sticky[i]]\n            sii=m.templateStrands[m.sticky[(i+2)%4]]\n            if si[1]<si[0]:\n                seqi=self.stringSequences[self.stringIDs[int(self.sticky[i][0:2])]][si[1]:si[0]][::-1]\n            else:\n                seqi=self.stringSequences[self.stringIDs[int(self.sticky[i][0:2])]][si[0]:si[1]]\n            if sii[1]<sii[0]:\n                seqii=m.stringSequences[m.stringIDs[int(m.sticky[(i+2)%4][0:2])]][sii[1]:sii[0]][::-1]\n            else:\n                seqii=m.stringSequences[m.stringIDs[int(m.sticky[(i+2)%4][0:2])]][sii[0]:sii[1]]\n            if seqi != get_complement(seqii):\n                print \"Sticky ends? %s:%s %s:%s\"%(self.sticky[i],seqi,m.sticky[(i+2)%4],get_complement(seqii))\n                stickcount+=1\n        return (failcount, stickcount)\n\n    def wikiOutput(self):\n        \"\"\"format a tile image and its sequences for Tiddly Wiki copy and paste output.\"\"\"\n        self.getStrands()\n        output='[img(100%%+,+)[img/col_%s.png]]\\n'%(self.seedID)\n        for i in self.stringIDs.keys():\n            iID=''\n            key=self.stringIDs[i]\n            out=\"%02d. %s. %s\"%(i, key,self.stringSequences[key])\n            if len(out)>80:\n                output=output+\"@@color:\"+cols[i]+\"font-size:0.92em;\"+out[:int(len(out)/2)+8]+\"@@\\n@@color:\"+cols[i]+\"font-size:0.92em;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\"+out[int(len(out)/2)+8:]+\"@@\\n\"\n            else:\n                output=output+\"@@color:\"+cols[i]+\"font-size:0.92em;\"+out+\"@@\\n\"\n        print output\n\n    def fillTemplate(self, fname, verbose=False):\n\tif self.stringSequences=={} or self.stringIDs=={}:  self.getStrands()\n        ls=self.readSVGtemplate()\n        o=open(templatedir+self.templatefile)\n        svg=o.read()\n        o.close()\n        for num in self.stringNums:\n            index=0\n            count=0\n            if len(self.stringSequences[self.stringIDs[num]])!=ls[num]: \n\t      print \"warning: strand %s doesn't match template!\"%self.stringIDs[num]\n            for alph in \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\":\n                try:\n                    si=self.templateStrands[\"%02d%s\"%(num,alph)]\n                    if si[1]<si[0]:\n                        seq=self.stringSequences[self.stringIDs[num]][si[1]:si[0]][::-1]\n                        if si[0]-si[1]>3: plac=\"%02d%s\"%(num,alph+\"X\"*(si[0]-si[1]-4)+\"R\")\n                        else: plac=\"%02d%s\"%(num,alph)\n                    else:\n                        seq=self.stringSequences[self.stringIDs[num]][si[0]:si[1]]\n                        if si[1]-si[0]>3: plac=\"%02d%s\"%(num,alph+\"X\"*(si[1]-si[0]-4)+\"N\")\n                        else: plac=\"%02d%s\"%(num,alph)\n                    if verbose: print \"%s %s\"%(plac,seq)\n                    svg=svg.replace(plac,seq)\n                except KeyError: pass\n        svg=svg.replace(\"TITLE\",self.seedID)\n        o=open(fname, \"w\")\n        o.write(svg)\n        o.close()\n        os.system('inkscape -z -A \"'+fname[:-4]+'.pdf\" \"'+fname+'\"')\n        print fname\n\n\n\n\nclass firstgentile(seedtile):\n    def __init__(self,newID):\n        seedtile.__init__(self,newID)\n        del self.num\n        if self.type==\"B\":\n            self.matches={\"01A\":\"02G\",\"03I\":\"02F\", \"04A\":\"O2E\",\"04F\":\"02D\", \"05I\":\"02C\",\"19A\":\"02B\",\"06B\":\"01B\",\"06C\":\"03H\",\"06D\":\"03C\",\"06E\":\"04G\",\"06F\":\"05H\",\"06G\":\"05C\",\"06H\":\"07A\",\"08A\":\"09G\",\"03B\":\"09F\",\"04H\":\"09E\",\"04M\":\"09D\",\"05B\":\"09C\",\"07B\":\"09B\",\"03F\":\"03D\",\"04B\":\"04D\",\"04I\":\"04K\",\"05F\":\"05D\"}\n            self.connect=[]\n            self.sticky=[\"03A\",\"05A\",\"03J\",\"05J\"]\n            self.templatefile=\"B'template.svg\"\n        else:\n            self.matches={\"01A\":\"02G\",\"03E\":\"02F\", \"04A\":\"O2E\",\"04B\":\"02D\", \"05E\":\"02C\",\"19A\":\"02B\",\"06B\":\"01B\",\"06C\":\"03D\",\"06D\":\"03C\",\"06E\":\"04C\",\"06F\":\"05D\",\"06G\":\"05C\",\"06H\":\"07A\",\"08A\":\"09G\",\"03B\":\"09F\",\"04H\":\"09E\",\"04M\":\"09D\",\"05B\":\"09C\",\"07B\":\"09B\"}\n            self.connect=[(\"04A\",\"04B\"),(\"02D\",\"02E\"),(\"06C\",\"06D\"),(\"03C\",\"03D\"),(\"06F\",\"06G\"),(\"05C\",\"05D\"),(\"04D\",\"04E\"),(\"09D\",\"09E\")]\n            self.sticky=[\"03A\",\"05A\",\"03F\",\"05F\"]\n            if self.type==\"I\": self.templatefile=\"I'template.svg\"\n            else: self.templatefile=\"A'template.svg\"\n        self.stringNums=[1,2,3,4,5,6,7,8,9,19]\n        \n\t  \n\n        \n\n    def getIDs(self):\n        \"\"\"identifies SEED tile strings according to the seed ID and\n        writes them into the stringIDs dictionary\"\"\"\n        for i in [1, 2, 6, 7, 8, 9, 19]:\n            self.stringIDs[i]=\"tw-u2AB-%02d\"%i\n        self.stringIDs[3]=\"tw-AA%d-03\"%tvsn\n        self.stringIDs[4]=\"tw-ICEN-04\"\n        self.stringIDs[5]=\"tw-AA%d-05\"%tvsn\n        \n        if self.type==\"I\":\n            self.stringIDs[1]=\"tw-ICEN-01\"\n            self.stringIDs[2]=\"tw-u1I-02\"\n            self.stringIDs[3]=\"tw-ICN%d-03\"%tvsn\n            self.stringIDs[4]=\"tw-ICEN-04\"\n            self.stringIDs[5]=\"tw-ICN%d-05\"%tvsn\n            self.stringIDs[6]=\"tw-u1I-06\"\n            self.stringIDs[8]=\"tw-ICEN-08\"\n            self.stringIDs[9]=\"tw-u1I-09\"\n            self.stringIDs[19]=\"tw-ICEN-19\"\n\n        if self.type==\"B\":\n            self.stringIDs[3]=\"tw-u3B%d-03\"%tvsn\n            self.stringIDs[4]=\"tw-u3AB-04\"\n            self.stringIDs[5]=\"tw-u3B%d-05\"%tvsn\n\n    def fetchBody(self):\n        body={}\n        if self.type==\"B\":\n            bfile=open(testdir+\"blunt-fgen-hp.txt\")\n        else:\n            bfile=open(testdir+\"blunt-fgen.txt\")\n        for line in bfile:\n            body[line.split(\"\\t\")[0]]=line.split(\"\\t\")[1][:-1]\n        return body\n\n\nclass newfgtile(firstgentile):\n    def __init__(self,newID):\n        seedtile.__init__(self,newID)\n        del self.num\n        if self.type==\"B\":\n            self.matches={\"01B\":\"02G\",\"03I\":\"02F\", \"04A\":\"O2E\",\"04F\":\"02D\", \"05I\":\"02C\",\"19A\":\"02B\",\"06B\":\"01C\",\"06C\":\"03H\",\"06D\":\"03C\",\"06E\":\"04G\",\"06F\":\"05H\",\"06G\":\"05C\",\"06H\":\"07B\",\"08B\":\"09G\",\"03B\":\"09F\",\"04H\":\"09E\",\"04M\":\"09D\",\"05B\":\"09C\",\"07C\":\"09B\",\"03F\":\"03D\",\"04B\":\"04D\",\"04I\":\"04K\",\"05F\":\"05D\"}\n            self.connect=[]\n            self.sticky=[\"03A\",\"05A\",\"03J\",\"05J\"]\n            self.templatefile=\"B'newtemplate%d-%d.svg\"%(fgsn,tvsn)\n        else:\n            self.matches={\"01B\":\"02G\",\"03E\":\"02F\", \"04A\":\"O2E\",\"04B\":\"02D\", \"05E\":\"02C\",\"19A\":\"02B\",\"06B\":\"01C\",\"06C\":\"03D\",\"06D\":\"03C\",\"06E\":\"04C\",\"06F\":\"05D\",\"06G\":\"05C\",\"06H\":\"07B\",\"08B\":\"09G\",\"03B\":\"09F\",\"04D\":\"09E\",\"04E\":\"09D\",\"05B\":\"09C\",\"07C\":\"09B\"}\n            self.connect=[(\"04A\",\"04B\"),(\"02D\",\"02E\"),(\"06C\",\"06D\"),(\"03C\",\"03D\"),(\"06F\",\"06G\"),(\"05C\",\"05D\"),(\"04D\",\"04E\"),(\"09D\",\"09E\")]\n            self.sticky=[\"03A\",\"05A\",\"03F\",\"05F\"]\n            if self.type==\"I\":\n                self.templatefile=\"I'newtemplate%d-%d.svg\"%(fgsn,tvsn)\n            else:\n                self.templatefile=\"A'newtemplate%d-%d.svg\"%(fgsn,tvsn)\n        self.stringNums=[1,2,3,4,5,6,7,8,9,19]\n        if typ=='xj': \n\t  self.templatefile=\"A'newtemplate%dxj.svg\"%fgsn\n\n        \n\n    def getIDs(self):#TODO:what about I???\n        \"\"\"identifies SEED tile strings according to the seed ID and\n        writes them into the stringIDs dictionary\"\"\"\n        for i in [1, 2, 6, 7, 8, 9, 19]:\n            self.stringIDs[i]=\"tw-u2AB%d-%02d\"%(fgsn, i)\n        self.stringIDs[3]=\"tw-%s%d-03\"%(2*self.type, tvsn)\n        self.stringIDs[4]=\"tw-ICEN-04\"\n        self.stringIDs[5]=\"tw-%s%d-05\"%(2*self.type, tvsn)\n\n        if self.type==\"I\":\n            for i in [1, 6, 8]:\n                #self.stringIDs[i]=\"tw-u2AB%dB-%02d\"%(fgsn, i) #TODO: missing!!!!!\n                self.stringIDs[i]=\"tw-u2AB%d-%02d\"%(fgsn, i) #TODO: missing!!!!!\n            self.stringIDs[3]=\"tw-ICN%d-03\"%tvsn\n            self.stringIDs[5]=\"tw-ICN%d-05\"%tvsn\n        \n        if self.type==\"B\":\n            #self.stringIDs[3]=\"tw-u3B%d-03\"%tvsn\n            #self.stringIDs[4]=\"tw-u3AB-04\"\n            #self.stringIDs[5]=\"tw-u3B%d-05\"%tvsn            \n\t    self.stringIDs[3]=\"tw-%s%d-03\"%(2*self.type, tvsn)\n\t    self.stringIDs[4]=\"tw-ICEN-04\"\n\t    self.stringIDs[5]=\"tw-%s%d-05\"%(2*self.type, tvsn)\n        if typ=='xj': \n\t  for i in [3,4,5,8,19]:self.stringIDs[i]=self.stringIDs[i]+'xj'\n\t  self.stringIDs[2]=\"tw-u2%s%d-02xj\"%(2*self.type, fgsn)\n\t  self.stringIDs[9]=\"tw-u2%s%d-09xj\"%(2*self.type, fgsn)\n\n    def fetchBody(self):\n        body={}\n        if self.type==\"B\":\n            bfile=open(testdir+\"blunt-fgen-hp-new%d.txt\"%fgsn)\n        else:\n            bfile=open(testdir+\"blunt-fgen-new%d.txt\"%fgsn)\n        for line in bfile:\n            body[line.split(\"\\t\")[0]]=line.split(\"\\t\")[1].replace('\\n','')\n        bfile.close()\n        return body\n\n\n    def fetchAllSticky(self,charlen):\n        allsticky={}\n        strandsd=allstrands(allstrandfile)\n        for key in strandsd.keys():\n            strand=strandsd[key]\n            strand=strand.replace(\" \",\"\")\n            strand=strand.replace(\"5'-\",\"\")\n            strand=strand.replace(\"-3'\",\"\")\n            strandsd[key]=strand\n\n        for tile in [\"A1\", \"B2\",\"B3\", \"A4\", \"B5\", \"A6\", \"B7\"]:\n            for i in [10,14,15,16,17,18]:\n                thisid=\"tw-%s-%02d\"%(tile,i)\n                try:\n                    allsticky[thisid]=strandsd[thisid][:16+charlen-1]\n                    if thisid==\"tw-B7-18\":\n                        allsticky[thisid+\"e\"]=strandsd[thisid][-(6+charlen-1):][::-1]\n                    if allsticky[thisid][:6]==\"TTTTTT\":\n                        allsticky[thisid]=allsticky[thisid][:6+charlen-1]\n                except KeyError:\n                    pass\n\n            if model=='new':#why doesn't this register?\n                for i in [10,14,15,16,17,18]:\n                    thisid=\"tw-%s-%02dn\"%(tile,i)#use a newer version if possible (what to do about dated strands?)\n                    try:\n                        allsticky[thisid]=strandsd[thisid][:16+charlen-1]\n                        dummy=allsticky.pop(thisid[:-1])\n                        if thisid==\"tw-B7-18\":\n                            allsticky[thisid+\"e\"]=strandsd[thisid][-(6+charlen-1):][::-1]\n                        if allsticky[thisid][:6]==\"TTTTTT\":\n                            allsticky[thisid]=allsticky[thisid][:6+charlen-1]\n                    except KeyError:\n                        pass\n\n            for thisid in [\"tw-ICN%d-11\"%tvsn,\"tw-ICN%d-13\"%tvsn, \"tw-AA%d-11\"%tvsn, \"tw-AA%d-13\"%tvsn,\"tw-BB%d-11\"%tvsn, \"tw-BB%d-13\"%tvsn,\"tw-ICN%d-03\"%tvsn,\"tw-ICN%d-05\"%tvsn, \"tw-AA%d-03\"%tvsn,\"tw-AA%d-05\"%tvsn,\"tw-u3B%d-03\"%tvsn,\"tw-u3B%d-05\"%tvsn, \"tw-BB%d-03\"%tvsn, \"tw-BB%d-05\"%tvsn ]:\n                allsticky[thisid+\"b\"]=strandsd[thisid][:7+charlen-1]\n                allsticky[thisid+\"e\"]=strandsd[thisid][-(7+charlen-1):][::-1]\n\n            for thisid in [\"tw-u2AB%d-%02d\"%(fgsn, i) for i in [1,2,6,7,8,9,10,14,15,16,17,18]]:\n\t\ttry: allsticky[thisid]=strandsd[thisid][:fgsn+charlen-1]\n\t\texcept KeyError: print 'key not found: '+thisid\n\n        return allsticky\n\n\nclass secgentile(seedtile):\n    def __init__(self,newID):\n        seedtile.__init__(self,newID)\n        del self.num\n        if self.type==\"B\":\n            self.matches={\"10B\":\"15B\", \"10C\":\"11B\", \"10D\":\"12E\", \"10E\":\"12D\", \"10F\":\"13B\", \"10G\":\"14A\", \"15A\":\"16H\", \"11C\":\"16G\", \"11D\":\"16F\", \"12C\":\"16E\", \"13C\":\"16D\", \"13D\":\"16C\", \"18B\":\"16B\", \"17B\":\"20A\", \"17C\":\"11E\",  \"17D\":\"12B\", \"17E\":\"12A\", \"17F\":\"13E\",  \"17G\":\"18A\"}\n            self.connect=[(\"10D\",\"10E\"),(\"12D\",\"12E\"), (\"11C\",\"11D\"),(\"16F\",\"16G\"), (\"13C\",\"13D\"),(\"16C\",\"16D\"),(\"17D\",\"17E\"),(\"12A\",\"12B\")]\n            self.sticky=[\"11A\",\"13A\",\"11J\",\"13J\"]\n            self.templatefile=\"B''template.svg\"\n        else:\n            self.matches={\"10B\":\"15B\", \"10C\":\"11B\", \"10D\":\"12M\", \"10E\":\"12H\", \"10F\":\"13B\", \"10G\":\"14A\", \"15A\":\"16H\", \"11C\":\"16G\", \"11H\":\"16F\", \"12G\":\"16E\", \"13C\":\"16D\", \"13H\":\"16C\", \"18B\":\"16B\", \"17B\":\"20A\", \"17C\":\"11I\", \"17D\":\"12F\", \"17E\":\"12A\", \"17F\":\"13I\", \"17G\":\"18A\", \"11D\":\"11F\", \"12I\":\"12K\", \"13D\":\"13F\", \"12B\":\"12D\"}\n            self.sticky=[\"11A\",\"13A\",\"11J\",\"13J\"]\n            self.connect=[]\n            if self.type==\"I\": self.templatefile=\"I''template.svg\"\n            else: self.templatefile=\"A''template.svg\"\n        self.stringNums=[10,11,12,13,14,15,16,17,18,20]\n\n    def getIDs(self):\n        \"\"\"identifies SEED tile strings according to the seed ID and\n        writes them into the stringIDs dictionary. This had better work\"\"\"\n        for i in [10, 14, 15, 16, 17, 18, 20]:\n            self.stringIDs[10]=\"tw-u2AB-%02d\"%i\n            \n        self.stringIDs[11]=\"tw-u3A%d-11\"%tvsn\n        self.stringIDs[12]=\"tw-u3A-12\"\n        self.stringIDs[13]=\"tw-u3A%d-13\"%tvsn\n\n        if self.type==\"I\":\n            self.stringIDs[10]=\"tw-u2I-10\"\n            self.stringIDs[11]=\"tw-u3I%d-11\"%tvsn\n            self.stringIDs[12]=\"tw-u3AB-12\"\n            self.stringIDs[13]=\"tw-u3I%d-13\"%tvsn\n            self.stringIDs[16]=\"tw-u2I-16\"\n            self.stringIDs[17]=\"tw-u2I-17\"\n            self.stringIDs[20]=\"tw-ICEN-20\"\n\n        if self.type==\"B\":\n            self.stringIDs[11]=\"tw-BB%d-11\"%tvsn\n            self.stringIDs[12]=\"tw-ICEN-12\"\n            self.stringIDs[13]=\"tw-BB%d-13\"%tvsn\n\n    def fetchBody(self):\n        body={}\n        if self.type==\"B\":\n            bfile=open(testdir+\"blunt-sg.txt\")\n        else:\n            bfile=open(testdir+\"blunt-sg-hp.txt\")\n        for line in bfile:\n            body[line.split(\"\\t\")[0]]=line.split(\"\\t\")[1].replace('\\n','')\n        return body\n\nclass newsgtile(seedtile):\n    def __init__(self,newID):\n        seedtile.__init__(self,newID)\n        del self.num\n        if self.type==\"B\":\n            self.matches={\"10B\":\"15C\", \"10C\":\"11B\", \"10D\":\"12E\", \"10E\":\"12D\", \"10F\":\"13B\", \"10G\":\"14B\", \"15B\":\"16H\", \"11C\":\"16G\", \"11D\":\"16F\", \"12C\":\"16E\", \"13C\":\"16D\", \"13D\":\"16C\", \"18C\":\"16B\", \"17B\":\"20A\", \"17C\":\"11E\",  \"17D\":\"12B\", \"17E\":\"12A\", \"17F\":\"13E\",  \"17G\":\"18B\"}\n            self.connect=[(\"10D\",\"10E\"),(\"12D\",\"12E\"), (\"11C\",\"11D\"),(\"16F\",\"16G\"), (\"13C\",\"13D\"),(\"16C\",\"16D\"),(\"17D\",\"17E\"),(\"12A\",\"12B\")]\n            self.sticky=[\"11A\",\"13A\",\"11J\",\"13J\"]\n            self.templatefile=\"B''newtemplate%d-%d.svg\"%(fgsn,tvsn)\n            #if fgsn==9: self.templatefile=\"B''newtemplate9.svg\"\n        else:\n            self.matches={\"10B\":\"15C\", \"10C\":\"11B\", \"10D\":\"12M\", \"10E\":\"12H\", \"10F\":\"13B\", \"10G\":\"14B\", \"15B\":\"16H\", \"11C\":\"16G\", \"11H\":\"16F\", \"12G\":\"16E\", \"13C\":\"16D\", \"13H\":\"16C\", \"18C\":\"16B\", \"17B\":\"20A\", \"17C\":\"11I\", \"17D\":\"12F\", \"17E\":\"12A\", \"17F\":\"13I\", \"17G\":\"18B\", \"11D\":\"11F\", \"12I\":\"12K\", \"13D\":\"13F\", \"12B\":\"12D\"}\n            self.sticky=[\"11A\",\"13A\",\"11J\",\"13J\"]\n            self.connect=[]\n            if self.type==\"I\":\n                self.templatefile=\"I''newtemplate%d-%d.svg\"%(fgsn,tvsn)\n                #if fgsn==9: self.templatefile=\"I''newtemplate9.svg\"\n            else:\n                self.templatefile=\"A''newtemplate%d-%d.svg\"%(fgsn,tvsn)\n                #if fgsn==9: self.templatefile=\"A''newtemplate9.svg\"\n        self.stringNums=[10,11,12,13,14,15,16,17,18,20]\n\n    def getIDs(self):\n        \"\"\"identifies SEED tile strings according to the seed ID and\n        writes them into the stringIDs dictionary. This had better work\"\"\"\n        \n        for i in [10, 14, 15, 16, 17, 18, 20]:\n            self.stringIDs[i]=\"tw-u2AB%d-%02d\"%(fgsn, i)\n        \n        self.stringIDs[11]=\"tw-u3A%d-11\"%tvsn\n        self.stringIDs[12]=\"tw-u3AB-12\"\n        self.stringIDs[13]=\"tw-u3A%d-13\"%tvsn\n\n        if self.type==\"B\":\n            self.stringIDs[11]=\"tw-BB%d-11\"%tvsn\n            self.stringIDs[12]=\"tw-ICEN-12\"\n            self.stringIDs[13]=\"tw-BB%d-13\"%tvsn\n\n        if self.type==\"I\":\n            self.stringIDs[10]=\"tw-u2I%d-10\"%fgsn\n            self.stringIDs[11]=\"tw-u3I%d-11\"%tvsn\n            self.stringIDs[12]=\"tw-u3AB-12\"\n            self.stringIDs[13]=\"tw-u3I%d-13\"%tvsn\n            self.stringIDs[15]=\"tw-u2I%d-15\"%fgsn\n            self.stringIDs[17]=\"tw-u2I%d-17\"%fgsn\n\n    def fetchBody(self):\n        body={}\n        if self.type==\"B\":\n            bfile=open(testdir+\"blunt-sgen-hp-new%d.txt\"%fgsn)\n        else:\n            bfile=open(testdir+\"blunt-sgen-new%d.txt\"%fgsn)\n        for line in bfile:\n            if len(line)>2: body[line.split(\"\\t\")[0]]=line.split(\"\\t\")[1].replace('\\n','')\n        return body\n\n    def fetchAllSticky(self,charlen):\n        allsticky={}\n        strandsd=allstrands(allstrandfile)\n        for key in strandsd.keys():\n            strand=strandsd[key]\n            strand=strand.replace(\" \",\"\")\n            strand=strand.replace(\"5'-\",\"\")\n            strand=strand.replace(\"-3'\",\"\")\n            strandsd[key]=strand\n\n        for tile in [\"A1\", \"B2\",\"B3\", \"A4\", \"B5\", \"A6\", \"B7\"]:\n            for i in [10,14,15,16,17,18]:\n                thisid=\"tw-%s-%02d\"%(tile,i)\n                try:\n                    allsticky[thisid]=strandsd[thisid][:16+charlen-1]\n                    if thisid==\"tw-B7-18\":\n                        allsticky[thisid+\"e\"]=strandsd[thisid][-(6+charlen-1):][::-1]\n                    if allsticky[thisid][:6]==\"TTTTTT\":\n                        allsticky[thisid]=allsticky[thisid][:6+charlen-1]\n                except KeyError:\n                    pass\n\n            for thisid in [\"tw-ICN4-11\",\"tw-ICN4-13\", \"tw-AA2-11\", \"tw-AA2-13\",\"tw-BB2-11\", \"tw-BB2-13\",\"tw-ICN4-03\",\"tw-ICN4-05\", \"tw-AA2-03\",\"tw-AA2-05\",\"tw-u3B-03\",\"tw-u3B-05\"]:\n                allsticky[thisid+\"b\"]=strandsd[thisid][:tvsn+charlen-1]\n                allsticky[thisid+\"e\"]=strandsd[thisid][-(tvsn+charlen-1):][::-1]\n\n            for thisid in [\"tw-u2ABn-01\",\"tw-u2ABn-02\",\"tw-u2ABn-06\",\"tw-u2ABn-07\",\"tw-u2ABn-08\",\"tw-u2ABn-09\",\"tw-u2ABn-10\",\"tw-u2ABn-14\",\"tw-u2ABn-15\",\"tw-u2ABn-16\",\"tw-u2ABn-17\",\"tw-u2ABn-18\"]:\n                allsticky[thisid]=strandsd[thisid][:fgsn+charlen-1]\n\n        return allsticky\n\n\n\n\nif __name__ == \"__main__\":\n\tpass\n\n#    repl={\"tw-BB8-11b\":\"AGTCAAGC\", \"tw-BB8-11e\":\"GCAGAGTT\", \"tw-BB8-13b\":'GAGGTTCC', \"tw-BB8-13e\":'ACCTGTCT', \"tw-AA8-11b\":'CTCCTACG', 'tw-AA8-11e':'GGTCCTTC', 'tw-AA8-13b':'TCTCTGCT', 'tw-AA8-13e':'TCCACCTT' }\n#    repl={\"tw-BB8-11b\":\"AGTCAAGC\", \"tw-BB8-11e\":\"GCAGAGTT\", \"tw-BB8-13b\":'GAGGTTCC', 'tw-BB8-13e':'CTTCACGA',\"tw-AA8-11b\":'CTCCTACG', 'tw-AA8-11e':'GGTCCTTC', 'tw-AA8-13b':'TCTCTGCT', 'tw-AA8-13e':'TCCACCTT', 'tw-ICN8-11b':'ATGACAGC',  'tw-ICN8-11e':'GACTCCAG', 'tw-ICN8-13b':'TCAAGACG', 'tw-ICN8-13e':'AGAGCAGA'}melting -Hdnadna -SAGTCAAGC -CTCAGTTCG -G12.5e-3 -P0.5e-7\n\n    ##repl={'tw-u2AB7-01':'CGTCTTA','tw-u2AB7-02':'TAAXACG', 'tw-u2AB7-06':'TATCACG', 'tw-u2AB7-07':'CGTXATA', 'tw-u2AB7-08':'ATTGGAC', 'tw-u2AB7-09':'GTCXAAT'}#1:14.81, 6:14.99, 8:14.38#wrong ones\n    #repl={'tw-u2AB7-01':'GTTCTCA','tw-u2AB7-02':'TCAXAAC', 'tw-u2AB7-06':'TCACTTC', 'tw-u2AB7-07':'GAAXTGA', 'tw-u2AB7-08':'TTCCTTG', 'tw-u2AB7-09':'CAAXGAA'}#1:14.38, 6:14.38, 8:14.48\n    #repl={'tw-u2AB5-01':'TCGTG','tw-u2AB5-02':'CAXGA', 'tw-u2AB5-06':'CGGTT', 'tw-u2AB5-07':'AAXCG', 'tw-u2AB5-08':'ACGTC', 'tw-u2AB5-09':'GAXGT'}#1:-1.28, 6:-1.73, 8:14.38\n    ###repl={'tw-u2AB5-01':'TTCGG','tw-u2AB5-02':'CCXAA', 'tw-u2AB5-06':'GTCGA', 'tw-u2AB5-07':'TCXAC', 'tw-u2AB5-08':'ATGGC', 'tw-u2AB5-09':'GCXAT'}#1:-2.98,6:-2.67, 8:-3.97#wrong ones\n    #fgsn=7\n\n#    repl={\"tw-A6-15\":\"ATGCCTCGCTCAATTG\",\n#      \"tw-B5-16\":\"CAATTGAGCGAGGCAT\",\n#      \"tw-A6-16\":\"ATCGTCATGTAGCACC\",#output100922c.txt\n#      \"tw-B7-15\":\"GGTGCTACATGACGAT\",\n#      \"tw-A1-16\":\"TCGTGTTCACAACACC\",#output100922d.txt\n#      \"tw-B2-15\":\"GGTGTTGTGAACACGA\",\n#      \"tw-B3-16\":\"AACTTGGTTCGGAACC\",#output100922e.txt\n#      \"tw-A4-15\":\"GGTTCCGAACCAAGTT\",\n#      \"tw-B3-18\":\"AGGTGGCAGAACAATG\",#output100922f.txt\n#      \"tw-A4-17\":\"CATTGTTCTGCCACCT\",\n#      \"tw-A6-14\":\"AATACTTGCGTGCGTG\",#output100922g.txt\n#      \"tw-B7-10\":\"CACGCACGCAAGTATT\"\n\n#    repl={\"tw-A6-15\":\"ATGCCTCGCTCAATTG\",\n#    \"tw-B5-16\":\"CAATTGAGCGAGGCAT\",\n#     \"tw-A6-16\":\"ATCGTCATGTAGCACC\",#output100922c.txt\n#     \"tw-B7-15\":\"GGTGCTACATGACGAT\",\n#     \"tw-A1-16\":\"TCGTGTTCACAACACC\",#output100922d.txt\n#     \"tw-B2-15\":\"GGTGTTGTGAACACGA\",\n#     \"tw-B3-16\":\"AACTTGGTTCGGAACC\",#output100922e.txt\n#     \"tw-A4-15\":\"GGTTCCGAACCAAGTT\",\n#     \"tw-B3-18\":\"AGGTGGCAGAACAATG\",#output100922f.txt\n#     \"tw-A4-17\":\"CATTGTTCTGCCACCT\",\n#     \"tw-A6-14\":\"AATACTTGCGTGCGTG\",#output100922g.txt\n#     \"tw-B7-10\":\"CACGCACGCAAGTATT\"}\n\n  #repl={\n  #\"tw-BB8-11b\":\"AGTAATCT\", \"tw-BB8-13b\":\"GAGAATAA\",\n  #\"tw-ICN8-11b\":\"TACCTTAA\", \"tw-ICN8-13b\":\"TATAATGC\",\n  #\"tw-AA8-11b\":\"GTAATTAC\", \"tw-AA8-13b\":\"TAGATTGA\",\n  #\"tw-BB8-03b\":\"AGATTACT\", \"tw-BB8-05b\":\"TTATTCTC\",\n  #\"tw-AA8-03b\":\"GTAATTAC\", \"tw-AA8-05b\":\"TCAATCTA\",\n  #\"tw-ICN8-03b\":\"TTAAGGTA\", \"tw-ICN8-05b\":\"GCATTATA\",\n  #\"tw-BB8-11e\":\"ATTCCATA\", \"tw-BB8-13e\":\"ACTAAGTA\",\n  #\"tw-ICN8-11e\":\"TATGTGTA\", \"tw-ICN8-13e\":\"AATAGTCA\",\n  #\"tw-AA8-11e\":\"TATTGGAA\", \"tw-AA8-13e\":\"CAAGTTAA\",\n  #\"tw-BB8-03e\":\"TATGGAAT\", \"tw-BB8-05e\":\"TACTTAGT\",\n  #\"tw-AA8-03e\":\"TTCCAATA\", \"tw-AA8-05e\":\"TTAACTTG\",\n  #\"tw-ICN8-03e\":\"TACACATA\", \"tw-ICN8-05e\":\"TGACTATT\"\n  #}\n  #thisrep=\"tw-ICN8-05e\"\n  #fgsn=7\n  #tvsn=8\n  #apr=newfgtile(\"B'\") \n  #cand=[]\n  #acand={}\n  #for i in range(100):\n    #new1=noRepetitions(apr.ReplaceSticky(thisrep,8, bm=7, sm=6,  nlim=80, tlim=80, verbose=False, replacements=repl),3)\n  #if len(new1)>0:  \n\t\t#cand=TMeltSelect(new1,(0,20),verbose=True, threads=4)\n\t\t#acand=dict(acand, **cand)\n  #else: print \"no strands found\"\n  #f=localtime()\n  #fil=open('/windows/D/NY/randomgel/sticky%s-%02d-%02d-%02d.%02d.log'%(str(f.tm_year)[-2:],f.tm_mon,f.tm_mday,f.tm_hour,f.tm_min),'w')\n  #f=open('scripts/cand%s-%02d-%02d-%02d.%02d.%02d.log'%(str(f.tm_year)[-2:],f.tm_mon,f.tm_mday,f.tm_hour,f.tm_min,f.tm_sec),'w')\n  #for item in repl.keys(): f.write('%s\\t%s\\n'%(item,repl[item]))\n  #f.write('\\n################%s################\\n\\n'%thisrep)\n  #for item in acand.keys(): f.write('%s\\t%.02f\\n'%(item,acand[item]))\n  #f.close()\n\n\n#########################stuff that shouldn't be in this module################\n\ndef nobranches(grey,cut,linelen):\n    bbin=grey>cut\n    blab=p.label(1-bbin)\n    blobs=p.blob(blab,'boundingbox','data')\n    nums={}\n    Image.fromarray(blab.astype(uint8)*(255/amax(blab))).show()\n    for num in arange(1,amax(blab)+1):\n        nums[num]=[]\n    for ang in arange(6)*30:\n        f=p.closeth(bbin,p.seline(linelen,ang))\n        ad= uniq(blab[(f==bbin).nonzero()])\n        for key in nums.keys():\n            if key in ad: nums[key].append(ang)\n    for key in nums.keys():\n        if logical_or(len(nums[key])==0, len(nums[key])>2):\n            blab[(blab==key).nonzero()]=0\n            print \"Blob removed: %d\"%key\n    Image.fromarray(blab.astype(uint8)*(255/amax(blab))).show()\n    bbin=blab>0\n    nblab=p.label(bbin)\n    blobs=p.blob(nblab,'boundingbox','data')\n    return (blobs,nums,blab)\n\nclass AFMpic:\n    \"\"\"Does things with AFM ascii exports\"\"\"\n    def __init__(self,fname):\n        self.file=fname\n        self.size=0\n        self.data=array([])\n        self.grey=array([])\n\n    def readData(self):\n        f=open(self.file)\n        b=f.read()\n        f.close()\n        c=b.find('\\Scan size:')\n        d=b.find(' nm',c)\n        self.size=float(b[c+11:d])\n        c=b.find('\\Exported image units: nm')\n        if c>-1:\n            temp=b[c+26:]\n            self.lengths=True\n        else:\n            c=b.find('\\*File list end\\r\\n')\n            temp=b[c+16:]\n            if verbose: print key\n            self.lengths=False\n        f=open('temp','w')\n        f.write(temp)\n        f.close()\n        self.data=loadtxt('temp')\n        self.grey=((self.data-amin(self.data))*255/(amax(self.data)-amin(self.data))).astype(uint8)\n        #u=Image.fromarray(self.grey)\n        #u.show()\n\n", "meta": {"hexsha": "792911b7ca813d9965b1fcbdc939ce6213f3d0aa", "size": 55615, "ext": "py", "lang": "Python", "max_stars_repo_path": "DNA.py", "max_stars_repo_name": "matanbz/conDNA", "max_stars_repo_head_hexsha": "03bf57decbb389493a4c86eb392c235cc787452d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DNA.py", "max_issues_repo_name": "matanbz/conDNA", "max_issues_repo_head_hexsha": "03bf57decbb389493a4c86eb392c235cc787452d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DNA.py", "max_forks_repo_name": "matanbz/conDNA", "max_forks_repo_head_hexsha": "03bf57decbb389493a4c86eb392c235cc787452d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.4209265176, "max_line_length": 491, "alphanum_fraction": 0.5319967635, "include": true, "reason": "from numpy", "num_tokens": 17190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3140505385717078, "lm_q1q2_score": 0.1837513325964526}}
{"text": "# Noel C. F. Codella\n# Example Triplet Loss Code for Keras / TensorFlow\n\n# Implementing Improved Triplet Loss from:\n# Zhang et al. \"Tracking Persons-of-Interest via Adaptive Discriminative Features\" ECCV 2016\n\n# Got help from multiple web sources, including:\n# 1) https://stackoverflow.com/questions/47727679/triplet-model-for-image-retrieval-from-the-keras-pretrained-network\n# 2) https://ksaluja15.github.io/Learning-Rate-Multipliers-in-Keras/\n# 3) https://keras.io/preprocessing/image/\n# 4) https://github.com/keras-team/keras/issues/3386\n# 5) https://github.com/keras-team/keras/issues/8130\n\n\nimport os, sys, socket\n# set directories depending on machine\nhostname = socket.gethostname()\nif hostname=='tianx-pc':\n    homeDir = '/analyse/cdhome/'\n    projDir = '/analyse/Project0257/'\nelif hostname[0:7]=='deepnet':\n    homeDir = '/home/chrisd/'\n    projDir = '/analyse/Project0257/'\n\n# GLOBAL DEFINES\nT_G_WIDTH = 224\nT_G_HEIGHT = 224\nT_G_NUMCHANNELS = 3\nT_G_SEED = 1337\n\nimport ssl # these two lines solved issues loading pretrained model\nssl._create_default_https_context = ssl._create_unverified_context\nimport numpy as np\nimport pandas as pd\nimport scipy.io\nnp.random.seed(T_G_SEED)\n\nimport tensorflow as tf\ntf.set_random_seed(T_G_SEED)\nimport keras\nimport keras.applications\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras import optimizers\nimport keras.layers as kl\nfrom keras.preprocessing import image\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.optimizers import SGD\nfrom keras.utils.np_utils import to_categorical\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler, TensorBoard, EarlyStopping, ProgbarLogger\ntf.logging.set_verbosity(tf.logging.ERROR)\n\n# get Tian's ResNet 10 architecture\nsys.path.append(os.path.abspath(homeDir+'dlfaceScripts/SchynsLabDNN/faceNets/'))\nfrom resnetTian import ResNet10Tian\n\n\n# Generator object for data augmentation.\n# Can change values here to affect augmentation style.\ndatagen = ImageDataGenerator(width_shift_range=0.05,\n                             height_shift_range=0.05,\n                             zoom_range=0.1)\n\n\n# generator function for data augmentation\ndef createDataGen(X1, X2, X3, Y, b):\n    local_seed = T_G_SEED\n    genX1 = datagen.flow(X1,Y, batch_size=b, seed=local_seed, shuffle=False)\n    genX2 = datagen.flow(X2,Y, batch_size=b, seed=local_seed, shuffle=False)\n    genX3 = datagen.flow(X3,Y, batch_size=b, seed=local_seed, shuffle=False)\n    while True:\n        X1i = genX1.next()\n        X2i = genX2.next()\n        X3i = genX3.next()\n        yield [X1i[0], X2i[0], X3i[0]], X1i[1]\n\n# beta generator\ndef createDataGenBeta(anchor_df, positive_df, negative_df, chunksize):\n    train_datagen = ImageDataGenerator(rescale=1./255)\n    anchor_generator = train_datagen.flow_from_dataframe(\n        dataframe=anchor_df,\n        target_size=(224,224),\n        shuffle=False,\n        directory='/',\n        x_col='filename',\n        y_col=None,\n        class_mode=None,\n        validate_filenames=False,\n        batch_size=chunksize)\n    positive_generator = train_datagen.flow_from_dataframe(\n        dataframe=positive_df,\n        target_size=(224,224),\n        shuffle=False,\n        directory='/',\n        x_col='filename',\n        y_col=None,\n        class_mode=None,\n        validate_filenames=False,\n        batch_size=chunksize)\n    negative_generator = train_datagen.flow_from_dataframe(\n        dataframe=negative_df,\n        target_size=(224,224),\n        shuffle=False,\n        directory='/',\n        x_col='filename',\n        y_col=None,\n        class_mode=None,\n        validate_filenames=False,\n        batch_size=chunksize)\n    while True:\n        thsAnchors = anchor_generator.next()\n        thsPositives = positive_generator.next()\n        thsNegatives = negative_generator.next()\n        dummY = np.random.randint(2, size=(1,2,thsAnchors.shape[0])).T\n        yield thsAnchors, thsPositives, thsNegatives, dummY\n\n# transforms three links to txt lists of anchors, positives and negatives to dataframes\ndef txt_to_df(txtPth, setName):\n    anchor_txt = txtPth+setName+'_Anchors.txt'\n    positive_txt = txtPth+setName+'_Positives.txt'\n    negative_txt = txtPth+setName+'_Negatives.txt'\n    \n    anchor_df = pd.read_csv(anchor_txt, delim_whitespace = True, header=None)\n    anchor_df.columns = ['filename']\n    positive_df = pd.read_csv(positive_txt, delim_whitespace = True, header=None)\n    positive_df.columns = ['filename']\n    negative_df = pd.read_csv(negative_txt, delim_whitespace = True, header=None)\n    negative_df.columns = ['filename']\n    \n    return anchor_df, positive_df, negative_df\n\n\ndef tripletLossModel(embSize, initialLr, decay=0.0005, momentum=.9):\n    \n    # Initialize a ResNet Model\n    resnet_input = kl.Input(shape=(T_G_WIDTH,T_G_HEIGHT,T_G_NUMCHANNELS))\n    #resnet_model = keras.applications.resnet50.ResNet50(weights='imagenet', include_top = False, input_tensor=resnet_input)\n    resnet_model = ResNet10Tian(include_top = False, input_tensor=resnet_input)\n    \n    # New Layers over Tian's ResNet10\n    net = resnet_model.output\n    net = kl.GlobalAveragePooling2D(name='gap')(net)\n    net = kl.Dense(embSize,activation='relu',name='t_emb_1')(net)\n    #net = kl.Flatten(name='flatten')(net)\n    #net = kl.Dense(512,activation='relu',name='t_emb_1')(net)\n\n    net = kl.Lambda(lambda  x: K.l2_normalize(x,axis=1), name='t_emb_1_l2norm')(net)\n    \n    # model creation\n    base_model = Model(resnet_model.input, net, name=\"base_model\")\n    \n    # triplet framework, shared weights\n    input_shape = (T_G_WIDTH,T_G_HEIGHT,T_G_NUMCHANNELS)\n    input_anchor = kl.Input(shape=input_shape, name='input_anchor')\n    input_positive = kl.Input(shape=input_shape, name='input_pos')\n    input_negative = kl.Input(shape=input_shape, name='input_neg')\n    \n    net_anchor = base_model(input_anchor)\n    net_positive = base_model(input_positive)\n    net_negative = base_model(input_negative)\n    \n    # The Lambda layer produces output using given function. Here it is Euclidean distance.\n    positive_dist = kl.Lambda(euclidean_distance, name='pos_dist')([net_anchor, net_positive])\n    negative_dist = kl.Lambda(euclidean_distance, name='neg_dist')([net_anchor, net_negative])\n    tertiary_dist = kl.Lambda(euclidean_distance, name='ter_dist')([net_positive, net_negative])\n    \n    # This lambda layer simply stacks outputs so both distances are available to the objective\n    stacked_dists = kl.Lambda(lambda vects: K.stack(vects, axis=1), name='stacked_dists')([positive_dist, negative_dist, tertiary_dist])\n    \n    model = Model([input_anchor, input_positive, input_negative], stacked_dists, name='triple_siamese')\n    \n    # Setting up optimizer designed for variable learning rate\n    \n    # Variable Learning Rate per Layers\n    lr_mult_dict = {}\n    last_layer = ''\n    for layer in resnet_model.layers:\n        # comment this out to refine earlier layers\n        # layer.trainable = False  \n        # print layer.name\n        lr_mult_dict[layer.name] = 1\n        # last_layer = layer.name\n    lr_mult_dict['t_emb_1'] = 100\n    \n    optimiser = SGD(lr=initialLr, decay=decay, momentum=momentum, nesterov=False)\n    \n    model.compile(optimizer=optimiser, loss=triplet_loss, metrics=[accuracy])\n    \n    return model\n\n\ndef triplet_loss(y_true, y_pred): # y_true is just a dummy, y_pred are actually distances (a-p, a-n, p-n)\n    margin = K.constant(1)\n    # \"SymTriplet\" considering all three distances simultaneously\n    return K.mean(K.maximum(K.constant(0), \n        K.square(y_pred[:,0,0]) - 0.5*(K.square(y_pred[:,1,0])+K.square(y_pred[:,2,0])) + margin))\n\ndef accuracy(y_true, y_pred): # y_true is just a dummy, y_pred are actually distances (a-p, a-n, p-n)\n    # percentage of anchor-positive distances shorter than anchor-negative distances\n    return K.mean(y_pred[:,0,0] < y_pred[:,1,0])\n\ndef l2Norm(x):\n    return  K.l2_normalize(x, axis=-1)\n\ndef euclidean_distance(vects):\n    x, y = vects\n    return K.sqrt(K.maximum(K.sum(K.square(x - y), axis=1, keepdims=True), K.epsilon()))\n\n\n# loads an image and preprocesses\ndef t_read_image(loc):\n    t_image = image.load_img(loc, target_size=(T_G_HEIGHT, T_G_WIDTH))\n    t_image = image.img_to_array(t_image)\n    t_image = keras.applications.resnet50.preprocess_input(t_image, data_format='channels_last')\n    \n    return t_image\n\n# loads a set of images from a text index file   \ndef t_read_image_list(flist, start, length):\n    \n    with open(flist) as f:\n        content = f.readlines() \n    content = [x.strip().split()[0] for x in content] \n    \n    datalen = length\n    if (datalen < 0):\n        datalen = len(content)\n    \n    if (start + datalen > len(content)):\n        datalen = len(content) - start\n     \n    imgset = np.zeros((datalen, T_G_HEIGHT, T_G_WIDTH, T_G_NUMCHANNELS))\n    \n    for i in range(start, start+datalen):\n        if ((i-start) < len(content)):\n            imgset[i-start] = t_read_image(content[i])\n    \n    return imgset\n\n\ndef file_numlines(fn):\n    with open(fn) as f:\n        return sum(1 for _ in f)\n\n\ndef loadPropagateModel(modelPath, epoch, trained=True):\n    \n    with open(modelPath + '.json', \"r\") as json_file:\n        model_json = json_file.read()\n    \n    loaded_model = keras.models.model_from_json(model_json)\n    \n    if trained:\n        loaded_model.load_weights(modelPath + '_epoch' + str(epoch) + '.h5')\n    \n    base_model = loaded_model.get_layer('base_model')\n    \n    # create a new single input\n    input_shape=(T_G_WIDTH,T_G_HEIGHT,T_G_NUMCHANNELS)\n    input_single = kl.Input(shape=input_shape, name='input_single')\n    \n    # create a new model without the triplet loss\n    net_single = base_model(input_single)\n    model = Model(input_single, net_single, name='embedding_net')\n    \n    return model\n\ndef loadPropagateBaseModel(modelPath, epoch, trained=True):\n    \n    with open(modelPath + '.json', \"r\") as json_file:\n        model_json = json_file.read()\n    \n    loaded_model = keras.models.model_from_json(model_json)\n    \n    if trained:\n        loaded_model.load_weights(modelPath + '_epoch' + str(epoch) + '.h5')\n    \n    base_model = loaded_model.get_layer('base_model')\n    \n    return base_model\n\n\ndef extractEmbeddings(modelPath, epoch, imgList):\n    \n    model = loadPropagateModel(modelPath,epoch)\n    chunksize = file_numlines(imgList)\n    imgs = t_read_image_list(imgList, 0, chunksize)\n    vals = model.predict(imgs)\n    \n    return vals\n\n\ndef learn(txtPth, outPth, embSize=64, batch=100, nBatchPerChunk=10, nTrainChunks=50, nValChunks=2, nEpochs=100, \n          preTrained=None, initialLr=.001):\n    \n    print('transforming txt lists to dataframes ... ')\n    # transform training anchors, postives and negatives from txt files into pandas dataframes\n    train_anchor_df, train_positive_df, train_negative_df = txt_to_df(txtPth, 'train')\n    # transform validation anchors, postives and negatives from txt files into pandas dataframes\n    val_anchor_df, val_positive_df, val_negative_df = txt_to_df(txtPth, 'val')\n    \n    # chunksize is the number of images we load from disk at a time\n    chunkSize = batch*nBatchPerChunk\n    \n    # create training and validation generators\n    print('building training generator ... ')\n    trainGenerator = createDataGenBeta(train_anchor_df, train_positive_df, train_negative_df, chunkSize)\n    print('building validation generator ... ')\n    valGenerator = createDataGenBeta(val_anchor_df, val_positive_df, val_negative_df, chunkSize)\n    \n    print('creating a model ...')\n    model = tripletLossModel(embSize, initialLr)\n    \n    if preTrained!=None:\n        print('loading weights: '+preTrained+' ...')\n        model.load_weights(preTrained)\n    \n    \n    # initialise previous validation results as infinite\n    val_res_prev = [float('inf'), float('inf')]\n    print('training loop ...')\n    \n    # manual loop over epochs to support very large sets of triplets\n    for e in range(0, nEpochs):\n        \n        for t in range(0, nTrainChunks):\n            \n            print('epoch ' + str(e+1) + ': train chunk ' + str(t+1) + '/ ' + str(nTrainChunks) + ' ...')\n            \n            print('reading image lists ...')\n            anchors_t, positives_t, negatives_t, dummY = next(trainGenerator)\n            \n            print('starting to fit ...')\n            # This method uses data augmentation\n            model.fit_generator(createDataGen(anchors_t,positives_t,negatives_t,dummY,batch), \n                steps_per_epoch=nBatchPerChunk, \n                epochs=1, \n                shuffle=False, \n                use_multiprocessing=True)\n        \n        # In case the validation images don't fit in memory, we load chunks from disk again. \n        val_res_all = np.zeros((nValChunks,2))\n        for v in range(0, nValChunks):\n            \n            print('Loading validation image lists ...')\n            print('val chunk ' + str(v+1) + '/ ' + str(nValChunks) + ' ...')\n            anchors_v, positives_v, negatives_v, dummY = next(valGenerator)\n            \n            thsVal = model.evaluate([anchors_v, positives_v, negatives_v], dummY, batch_size=batch)\n            val_res_all[v,:] = thsVal\n        \n        val_res = np.mean(val_res_all, axis=0)\n        \n        print('validation Results: ' + str(val_res))\n        \n        if (e==0) or (val_res[0] < val_res_prev[0]):\n            print('previous Validation Results: ' + str(val_res_prev))\n            print('Improvement to previous, saving model to '+outPth)\n            # Save the model and weights\n            model.save(outPth+'_epoch'+str(e)+'.h5')\n            \n            # save the model architecture as well\n            model_json = model.to_json()\n            with open(outPth + '.json', \"w\") as json_file:\n                json_file.write(model_json)\n        \n        # update previous validation results\n        val_res_prev = val_res\n\n\n#  separate triplet evaluation\ndef tripletEvaluationSeparate(thsAng, thsEpoch, batch=100, nBatchPerChunk=10, nValChunks=3, evalSet='val'):\n    \n    saveFilePth = projDir+'/tripletLossModels/separateAngles/refined/test'+str(thsAng)+'_epoch'+str(thsEpoch)\n    txtPth = projDir+'tripletTxtLists/m'+str(thsAng)+'_0_p'+str(thsAng)+'_triplet_txt/'\n    \n    # load trained model\n    model = tripletLossModel(64, .001) # emb size is hard coded\n    model.load_weights(saveFilePth+'.h5')\n    \n    # set evaluation parameters\n    chunksize = batch*nBatchPerChunk\n    \n    # load dataframes\n    eval_anchor_df, eval_positive_df, eval_negative_df = txt_to_df(txtPth, evalSet)\n    \n    # build validation generator\n    evalGenerator = createDataGenBeta(eval_anchor_df, eval_positive_df, eval_negative_df, chunksize)\n    \n    eval_res_all = np.zeros((nValChunks,2))\n    for v in range(0, nValChunks):\n        \n        print('Loading validation image lists ...')\n        print('eval chunk ' + str(v+1) + '/ ' + str(nValChunks) + ' ...')\n        anchors, positives, negatives, dummY = next(evalGenerator)\n        \n        thsEval = model.evaluate([anchors, positives, negatives], dummY, batch_size=batch)\n        eval_res_all[v,:] = thsEval\n        \n    return eval_res_all\n", "meta": {"hexsha": "3c086eb8ac64bb5f25f05c0c4a34944ad31b8b36", "size": 15108, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/tripletlossModel.py", "max_stars_repo_name": "cdaube/sharedFunctionalFeatures", "max_stars_repo_head_hexsha": "3b7e8b17973a7fef195626a34bed54517cfd3915", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-18T18:13:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T18:13:39.000Z", "max_issues_repo_path": "python/tripletlossModel.py", "max_issues_repo_name": "cdaube/sharedFunctionalFeatures", "max_issues_repo_head_hexsha": "3b7e8b17973a7fef195626a34bed54517cfd3915", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/tripletlossModel.py", "max_forks_repo_name": "cdaube/sharedFunctionalFeatures", "max_forks_repo_head_hexsha": "3b7e8b17973a7fef195626a34bed54517cfd3915", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6758104738, "max_line_length": 136, "alphanum_fraction": 0.6805003971, "include": true, "reason": "import numpy,import scipy", "num_tokens": 3813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.3140505321516081, "lm_q1q2_score": 0.18375132429589314}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html\n# Based on Copyright (C) 2016 Radim Rehurek <radimrehurek@seznam.cz>\n\n\n\"\"\"\n\nInspired by the Blei's original DTM code and paper.\nOriginal DTM C/C++ code: https://github.com/blei-lab/dtm\nDTM Paper: https://www.cs.princeton.edu/~blei/papers/BleiLafferty2006a.pdf\n\n\nTODO:\nThe next steps to take this forward would be:\n\n    1) Include DIM mode. Most of the infrastructure for this is in place.\n    2) See if LdaPost can be replaced by LdaModel completely without breaking anything.\n    3) Heavy lifting going on in the sslm class - efforts can be made to cythonise mathematical methods.\n        - in particular, update_obs and the optimization takes a lot time.\n    4) Try and make it distributed, especially around the E and M step.\n    5) Remove all C/C++ coding style/syntax.\n\"\"\"\n\nfrom gensim import utils, matutils\nfrom gensim.models import ldamodel\nimport numpy as np\nfrom scipy.special import digamma, gammaln\nfrom scipy import optimize\nimport logging\n\nlogger = logging.getLogger('gensim.models.ldaseqmodel')\n\n\nclass LdaSeqModel(utils.SaveLoad):\n    \"\"\"\n    The constructor estimates Dynamic Topic Model parameters based\n    on a training corpus.\n    If we have 30 documents, with 5 in the first time-slice, 10 in the second, and 15 in the third, we would\n    set up our model like this:\n\n    >>> ldaseq = LdaSeqModel(corpus=corpus, time_slice= [5, 10, 15], num_topics=5)\n\n    Model persistency is achieved through inheriting utils.SaveLoad.\n\n    >>> ldaseq.save(\"ldaseq\")\n\n    saves the model to disk.\n    \"\"\"\n\n    def __init__(self, corpus=None, time_slice=None, id2word=None, alphas=0.01, num_topics=10,\n                 initialize='gensim', sstats=None, lda_model=None, obs_variance=0.5, chain_variance=0.005, passes=10,\n                 random_state=None, lda_inference_max_iter=25, em_min_iter=6, em_max_iter=20, chunksize=100):\n        \"\"\"\n        `corpus` is any iterable gensim corpus\n\n        `time_slice` as described above is a list which contains the number of documents in each time-slice\n\n        `id2word` is a mapping from word ids (integers) to words (strings).\n        It is used to determine the vocabulary size and printing topics.\n\n        `alphas`  is a prior of your choice and should be a double or float value. default is 0.01\n\n        `num_topics` is the number of requested latent topics to be extracted from the training corpus.\n\n        `initalize` allows the user to decide how he wants to initialise the DTM model. Default is through gensim LDA.\n        You can use your own sstats of an LDA model previously trained as well by specifying 'own'\n        and passing a np matrix through sstats.\n        If you wish to just pass a previously used LDA model, pass it through `lda_model`\n        Shape of sstats is (vocab_len, num_topics)\n\n        `chain_variance` is a constant which dictates how the beta values evolve - it is a gaussian parameter\n        defined in the beta distribution.\n\n        `passes` is the number of passes of the initial LdaModel.\n\n        `random_state` can be a np.random.RandomState object or the seed for one, for the LdaModel.\n        \"\"\"\n        self.id2word = id2word\n        if corpus is None and self.id2word is None:\n            raise ValueError(\n                'at least one of corpus/id2word must be specified, to establish input space dimensionality'\n            )\n\n        if self.id2word is None:\n            logger.warning(\"no word id mapping provided; initializing from corpus, assuming identity\")\n            self.id2word = utils.dict_from_corpus(corpus)\n            self.vocab_len = len(self.id2word)\n        elif len(self.id2word) > 0:\n            self.vocab_len = len(self.id2word)\n        else:\n            self.vocab_len = 0\n\n        if corpus is not None:\n            try:\n                self.corpus_len = len(corpus)\n            except TypeError:\n                logger.warning(\"input corpus stream has no len(); counting documents\")\n                self.corpus_len = sum(1 for _ in corpus)\n\n        self.time_slice = time_slice\n        if self.time_slice is not None:\n            self.num_time_slices = len(time_slice)\n\n        max_doc_len = 0\n        for line_no, line in enumerate(corpus):\n            if len(line) > max_doc_len:\n                max_doc_len = len(line)\n        self.max_doc_len = max_doc_len\n\n        self.num_topics = num_topics\n        self.num_time_slices = len(time_slice)\n        self.alphas = np.full(num_topics, alphas)\n\n        # topic_chains contains for each topic a 'state space language model' object\n        # which in turn has information about each topic\n        # the sslm class is described below and contains information\n        # on topic-word probabilities and doc-topic probabilities.\n        self.topic_chains = []\n        for topic in range(0, num_topics):\n            sslm_ = sslm(\n                num_time_slices=self.num_time_slices, vocab_len=self.vocab_len, num_topics=self.num_topics,\n                chain_variance=chain_variance, obs_variance=obs_variance\n            )\n            self.topic_chains.append(sslm_)\n\n        # the following are class variables which are to be integrated during Document Influence Model\n        self.top_doc_phis = None\n        self.influence = None\n        self.renormalized_influence = None\n        self.influence_sum_lgl = None\n\n        # if a corpus and time_slice is provided, depending on the user choice of initializing LDA, we start DTM.\n        if corpus is not None and time_slice is not None:\n            if initialize == 'gensim':\n                lda_model = ldamodel.LdaModel(\n                    corpus, id2word=self.id2word, num_topics=self.num_topics,\n                    passes=passes, alpha=self.alphas, random_state=random_state,\n                    dtype=np.float64\n                )\n                self.sstats = np.transpose(lda_model.state.sstats)\n            if initialize == 'ldamodel':\n                self.sstats = np.transpose(lda_model.state.sstats)\n            if initialize == 'own':\n                self.sstats = sstats\n\n            # initialize model from sstats\n            self.init_ldaseq_ss(chain_variance, obs_variance, self.alphas, self.sstats)\n\n            # fit DTM\n            self.fit_lda_seq(corpus, lda_inference_max_iter, em_min_iter, em_max_iter, chunksize)\n\n    def init_ldaseq_ss(self, topic_chain_variance, topic_obs_variance, alpha, init_suffstats):\n        \"\"\"\n        Method to initialize State Space Language Model, topic wise.\n        \"\"\"\n        self.alphas = alpha\n        for k, chain in enumerate(self.topic_chains):\n            sstats = init_suffstats[:, k]\n            sslm.sslm_counts_init(chain, topic_obs_variance, topic_chain_variance, sstats)\n\n            # initialize the below matrices only if running DIM\n            # ldaseq.topic_chains[k].w_phi_l = np.zeros((ldaseq.vocab_len, ldaseq.num_time_slices))\n            # ldaseq.topic_chains[k].w_phi_sum = np.zeros((ldaseq.vocab_len, ldaseq.num_time_slices))\n            # ldaseq.topic_chains[k].w_phi_sq = np.zeros((ldaseq.vocab_len, ldaseq.num_time_slices))\n\n    def fit_lda_seq(self, corpus, lda_inference_max_iter, em_min_iter, em_max_iter, chunksize):\n        \"\"\"\n        fit an lda sequence model:\n            for each time period:\n                set up lda model with E[log p(w|z)] and \\alpha\n\n                for each document:\n                    perform posterior inference\n                    update sufficient statistics/likelihood\n\n            maximize topics\n\n       \"\"\"\n        LDASQE_EM_THRESHOLD = 1e-4\n        # if bound is low, then we increase iterations.\n        LOWER_ITER = 10\n        ITER_MULT_LOW = 2\n        MAX_ITER = 500\n\n        num_topics = self.num_topics\n        vocab_len = self.vocab_len\n        data_len = self.num_time_slices\n        corpus_len = self.corpus_len\n\n        bound = 0\n        convergence = LDASQE_EM_THRESHOLD + 1\n        iter_ = 0\n\n        while iter_ < em_min_iter or ((convergence > LDASQE_EM_THRESHOLD) and iter_ <= em_max_iter):\n\n            logger.info(\" EM iter %i\", iter_)\n            logger.info(\"E Step\")\n            # TODO: bound is initialized to 0\n            old_bound = bound\n\n            # initiate sufficient statistics\n            topic_suffstats = []\n            for topic in range(0, num_topics):\n                topic_suffstats.append(np.resize(np.zeros(vocab_len * data_len), (vocab_len, data_len)))\n\n            # set up variables\n            gammas = np.resize(np.zeros(corpus_len * num_topics), (corpus_len, num_topics))\n            lhoods = np.resize(np.zeros(corpus_len * num_topics + 1), (corpus_len, num_topics + 1))\n            # compute the likelihood of a sequential corpus under an LDA\n            # seq model and find the evidence lower bound. This is the E - Step\n            bound, gammas = \\\n                self.lda_seq_infer(corpus, topic_suffstats, gammas, lhoods, iter_, lda_inference_max_iter, chunksize)\n            self.gammas = gammas\n\n            logger.info(\"M Step\")\n\n            # fit the variational distribution. This is the M - Step\n            topic_bound = self.fit_lda_seq_topics(topic_suffstats)\n            bound += topic_bound\n\n            if (bound - old_bound) < 0:\n                # if max_iter is too low, increase iterations.\n                if lda_inference_max_iter < LOWER_ITER:\n                    lda_inference_max_iter *= ITER_MULT_LOW\n                logger.info(\"Bound went down, increasing iterations to %i\", lda_inference_max_iter)\n\n            # check for convergence\n            convergence = np.fabs((bound - old_bound) / old_bound)\n\n            if convergence < LDASQE_EM_THRESHOLD:\n\n                lda_inference_max_iter = MAX_ITER\n                logger.info(\"Starting final iterations, max iter is %i\", lda_inference_max_iter)\n                convergence = 1.0\n\n            logger.info(\"iteration %i iteration lda seq bound is %f convergence is %f\", iter_, bound, convergence)\n\n            iter_ += 1\n\n        return bound\n\n    def lda_seq_infer(self, corpus, topic_suffstats, gammas, lhoods,\n                      iter_, lda_inference_max_iter, chunksize):\n        \"\"\"\n        Inference or E- Step.\n        This is used to set up the gensim LdaModel to be used for each time-slice.\n        It also allows for Document Influence Model code to be written in.\n        \"\"\"\n        num_topics = self.num_topics\n        vocab_len = self.vocab_len\n        bound = 0.0\n\n        lda = ldamodel.LdaModel(num_topics=num_topics, alpha=self.alphas, id2word=self.id2word, dtype=np.float64)\n        lda.topics = np.array(np.split(np.zeros(vocab_len * num_topics), vocab_len))\n        ldapost = LdaPost(max_doc_len=self.max_doc_len, num_topics=num_topics, lda=lda)\n\n        model = \"DTM\"\n        if model == \"DTM\":\n            bound, gammas = self.inferDTMseq(\n                corpus, topic_suffstats, gammas, lhoods, lda,\n                ldapost, iter_, bound, lda_inference_max_iter, chunksize\n            )\n        elif model == \"DIM\":\n            self.InfluenceTotalFixed(corpus)\n            bound, gammas = self.inferDIMseq(\n                corpus, topic_suffstats, gammas, lhoods, lda,\n                ldapost, iter_, bound, lda_inference_max_iter, chunksize\n            )\n\n        return bound, gammas\n\n    def inferDTMseq(self, corpus, topic_suffstats, gammas, lhoods, lda,\n                    ldapost, iter_, bound, lda_inference_max_iter, chunksize):\n        \"\"\"\n        Computes the likelihood of a sequential corpus under an LDA seq model, and return the likelihood bound.\n        Need to pass the LdaSeq model, corpus, sufficient stats, gammas and lhoods matrices previously created,\n        and LdaModel and LdaPost class objects.\n        \"\"\"\n        doc_index = 0  # overall doc_index in corpus\n        time = 0  # current time-slice\n        doc_num = 0  # doc-index in current time-slice\n        lda = self.make_lda_seq_slice(lda, time)  # create lda_seq slice\n\n        time_slice = np.cumsum(np.array(self.time_slice))\n\n        for chunk_no, chunk in enumerate(utils.grouper(corpus, chunksize)):\n            # iterates chunk size for constant memory footprint\n            for doc in chunk:\n                # this is used to update the time_slice and create a new lda_seq slice every new time_slice\n                if doc_index > time_slice[time]:\n                    time += 1\n                    lda = self.make_lda_seq_slice(lda, time)  # create lda_seq slice\n                    doc_num = 0\n\n                gam = gammas[doc_index]\n                lhood = lhoods[doc_index]\n\n                ldapost.gamma = gam\n                ldapost.lhood = lhood\n                ldapost.doc = doc\n\n                # TODO: replace fit_lda_post with appropriate ldamodel functions, if possible.\n                if iter_ == 0:\n                    doc_lhood = LdaPost.fit_lda_post(\n                        ldapost, doc_num, time, None, lda_inference_max_iter=lda_inference_max_iter\n                    )\n                else:\n                    doc_lhood = LdaPost.fit_lda_post(\n                        ldapost, doc_num, time, self, lda_inference_max_iter=lda_inference_max_iter\n                    )\n\n                if topic_suffstats is not None:\n                    topic_suffstats = LdaPost.update_lda_seq_ss(ldapost, time, doc, topic_suffstats)\n\n                gammas[doc_index] = ldapost.gamma\n                bound += doc_lhood\n                doc_index += 1\n                doc_num += 1\n\n        return bound, gammas\n\n    def make_lda_seq_slice(self, lda, time):\n        \"\"\"\n        set up the LDA model topic-word values with that of ldaseq.\n        \"\"\"\n        for k in range(0, self.num_topics):\n            lda.topics[:, k] = np.copy(self.topic_chains[k].e_log_prob[:, time])\n\n        lda.alpha = np.copy(self.alphas)\n        return lda\n\n    def fit_lda_seq_topics(self, topic_suffstats):\n        \"\"\"\n        Fit lda sequence topic wise.\n        \"\"\"\n        lhood = 0\n\n        for k, chain in enumerate(self.topic_chains):\n            logger.info(\"Fitting topic number %i\", k)\n            lhood_term = sslm.fit_sslm(chain, topic_suffstats[k])\n            lhood += lhood_term\n\n        return lhood\n\n    def print_topic_times(self, topic, top_terms=20):\n        \"\"\"\n        Prints one topic showing each time-slice.\n        \"\"\"\n        topics = []\n        for time in range(0, self.num_time_slices):\n            topics.append(self.print_topic(topic, time, top_terms))\n\n        return topics\n\n    def print_topics(self, time=0, top_terms=20):\n        \"\"\"\n        Prints all topics in a particular time-slice.\n        \"\"\"\n        topics = []\n        for topic in range(0, self.num_topics):\n            topics.append(self.print_topic(topic, time, top_terms))\n        return topics\n\n    def print_topic(self, topic, time=0, top_terms=20):\n        \"\"\"\n        Topic is the topic number\n        Time is for a particular time_slice\n        top_terms is the number of terms to display\n        \"\"\"\n        topic = self.topic_chains[topic].e_log_prob\n        topic = np.transpose(topic)\n        topic = np.exp(topic[time])\n        topic = topic / topic.sum()\n        bestn = matutils.argsort(topic, top_terms, reverse=True)\n        beststr = [(self.id2word[id_], topic[id_]) for id_ in bestn]\n        return beststr\n\n    def doc_topics(self, doc_number):\n        \"\"\"\n        On passing the LdaSeqModel trained ldaseq object, the doc_number of your document in the corpus,\n        it returns the doc-topic probabilities of that document.\n        \"\"\"\n        doc_topic = np.copy(self.gammas)\n        doc_topic /= doc_topic.sum(axis=1)[:, np.newaxis]\n        return doc_topic[doc_number]\n\n    def dtm_vis(self, time, corpus):\n        \"\"\"\n        returns term_frequency, vocab, doc_lengths, topic-term distributions and doc_topic distributions,\n        specified by pyLDAvis format.\n        all of these are needed to visualise topics for DTM for a particular time-slice via pyLDAvis.\n        input parameter is the year to do the visualisation.\n        \"\"\"\n        doc_topic = np.copy(self.gammas)\n        doc_topic /= doc_topic.sum(axis=1)[:, np.newaxis]\n\n        topic_term = [\n            np.exp(np.transpose(chain.e_log_prob)[time]) / np.exp(np.transpose(chain.e_log_prob)[time]).sum()\n            for k, chain in enumerate(self.topic_chains)\n        ]\n\n        doc_lengths = [len(doc) for doc_no, doc in enumerate(corpus)]\n\n        term_frequency = np.zeros(self.vocab_len)\n        for doc_no, doc in enumerate(corpus):\n            for pair in doc:\n                term_frequency[pair[0]] += pair[1]\n\n        vocab = [self.id2word[i] for i in range(0, len(self.id2word))]\n        # returns np arrays for doc_topic proportions, topic_term proportions, and document_lengths, term_frequency.\n        # these should be passed to the `pyLDAvis.prepare` method to visualise one time-slice of DTM topics.\n        return doc_topic, np.array(topic_term), doc_lengths, term_frequency, vocab\n\n    def dtm_coherence(self, time):\n        \"\"\"\n        returns all topics of a particular time-slice without probabilitiy values for it to be used\n        for either \"u_mass\" or \"c_v\" coherence.\n        \"\"\"\n        coherence_topics = []\n        for topics in self.print_topics(time):\n            coherence_topic = []\n            for word, dist in topics:\n                coherence_topic.append(word)\n            coherence_topics.append(coherence_topic)\n\n        return coherence_topics\n\n    def __getitem__(self, doc):\n        \"\"\"\n        Similar to the LdaModel __getitem__ function, it returns topic proportions of a document passed.\n        \"\"\"\n        lda_model = \\\n            ldamodel.LdaModel(num_topics=self.num_topics, alpha=self.alphas, id2word=self.id2word, dtype=np.float64)\n        lda_model.topics = np.array(np.split(np.zeros(self.vocab_len * self.num_topics), self.vocab_len))\n        ldapost = LdaPost(num_topics=self.num_topics, max_doc_len=len(doc), lda=lda_model, doc=doc)\n\n        time_lhoods = []\n        for time in range(0, self.num_time_slices):\n            lda_model = self.make_lda_seq_slice(lda_model, time)  # create lda_seq slice\n            lhood = LdaPost.fit_lda_post(ldapost, 0, time, self)\n            time_lhoods.append(lhood)\n\n        doc_topic = ldapost.gamma / ldapost.gamma.sum()\n        # should even the likelihoods be returned?\n        return doc_topic\n\n\nclass sslm(utils.SaveLoad):\n    \"\"\"\n    The sslm class is the State Space Language Model for DTM and contains the following information:\n    `obs` values contain the doc - topic ratios\n    `e_log_prob` contains topic - word ratios\n    `mean`, `fwd_mean` contains the mean values to be used for inference for each word for a time_slice\n    `variance`, `fwd_variance` contains the variance values to be used for inference for each word in a time_slice\n    `fwd_mean`, `fwd_variance` are the forward posterior values.\n    `zeta` is an extra variational parameter with a value for each time-slice\n    \"\"\"\n\n    def __init__(self, vocab_len=None, num_time_slices=None, num_topics=None, obs_variance=0.5, chain_variance=0.005):\n        self.vocab_len = vocab_len\n        self.num_time_slices = num_time_slices\n        self.obs_variance = obs_variance\n        self.chain_variance = chain_variance\n        self.num_topics = num_topics\n\n        # setting up matrices\n        self.obs = np.array(np.split(np.zeros(num_time_slices * vocab_len), vocab_len))\n        self.e_log_prob = np.array(np.split(np.zeros(num_time_slices * vocab_len), vocab_len))\n        self.mean = np.array(np.split(np.zeros((num_time_slices + 1) * vocab_len), vocab_len))\n        self.fwd_mean = np.array(np.split(np.zeros((num_time_slices + 1) * vocab_len), vocab_len))\n        self.fwd_variance = np.array(np.split(np.zeros((num_time_slices + 1) * vocab_len), vocab_len))\n        self.variance = np.array(np.split(np.zeros((num_time_slices + 1) * vocab_len), vocab_len))\n        self.zeta = np.zeros(num_time_slices)\n\n        # the following are class variables which are to be integrated during Document Influence Model\n        self.m_update_coeff = None\n        self.mean_t = None\n        self.variance_t = None\n        self.influence_sum_lgl = None\n        self.w_phi_l = None\n        self.w_phi_sum = None\n        self.w_phi_l_sq = None\n        self.m_update_coeff_g = None\n\n    def update_zeta(self):\n        \"\"\"\n        Updates the Zeta Variational Parameter.\n        Zeta is described in the appendix and is equal\n        to sum (exp(mean[word] + Variance[word] / 2)), over every time-slice.\n        It is the value of variational parameter zeta which maximizes the lower bound.\n        \"\"\"\n        for j, val in enumerate(self.zeta):\n            self.zeta[j] = np.sum(np.exp(self.mean[:, j + 1] + self.variance[:, j + 1] / 2))\n        return self.zeta\n\n    def compute_post_variance(self, word, chain_variance):\n        \"\"\"\n        Based on the  Variational Kalman Filtering approach for Approximate Inference\n        [https://www.cs.princeton.edu/~blei/papers/BleiLafferty2006a.pdf]\n        This function accepts the word to compute variance for, along with the associated sslm class object,\n        and returns variance and fwd_variance\n        Computes Var[\\beta_{t,w}] for t = 1:T\n\n        :math::\n\n            fwd\\_variance[t] \\equiv E((beta_{t,w}-mean_{t,w})^2 |beta_{t}\\ for\\ 1:t) =\n             (obs\\_variance / fwd\\_variance[t - 1] + chain\\_variance + obs\\_variance ) *\n             (fwd\\_variance[t - 1] + obs\\_variance)\n\n        :math::\n\n            variance[t] \\equiv E((beta_{t,w}-mean\\_cap_{t,w})^2 |beta\\_cap_{t}\\ for\\ 1:t) =\n            fwd\\_variance[t - 1] + (fwd\\_variance[t - 1] / fwd\\_variance[t - 1] + obs\\_variance)^2 *\n            (variance[t - 1] - (fwd\\_variance[t-1] + obs\\_variance))\n\n        \"\"\"\n        INIT_VARIANCE_CONST = 1000\n\n        T = self.num_time_slices\n        variance = self.variance[word]\n        fwd_variance = self.fwd_variance[word]\n        # forward pass. Set initial variance very high\n        fwd_variance[0] = chain_variance * INIT_VARIANCE_CONST\n        for t in range(1, T + 1):\n            if self.obs_variance:\n                c = self.obs_variance / (fwd_variance[t - 1] + chain_variance + self.obs_variance)\n            else:\n                c = 0\n            fwd_variance[t] = c * (fwd_variance[t - 1] + chain_variance)\n\n        # backward pass\n        variance[T] = fwd_variance[T]\n        for t in range(T - 1, -1, -1):\n            if fwd_variance[t] > 0.0:\n                c = np.power((fwd_variance[t] / (fwd_variance[t] + chain_variance)), 2)\n            else:\n                c = 0\n            variance[t] = (c * (variance[t + 1] - chain_variance)) + ((1 - c) * fwd_variance[t])\n\n        return variance, fwd_variance\n\n    def compute_post_mean(self, word, chain_variance):\n        \"\"\"\n        Based on the Variational Kalman Filtering approach for Approximate Inference\n        [https://www.cs.princeton.edu/~blei/papers/BleiLafferty2006a.pdf]\n        This function accepts the word to compute mean for, along with the associated sslm class object,\n        and returns mean and fwd_mean\n        Essentially a forward-backward to compute E[\\beta_{t,w}] for t = 1:T.\n\n        Fwd_Mean(t) ≡  E(beta_{t,w} | beta_ˆ 1:t )\n        = (obs_variance / fwd_variance[t - 1] + chain_variance + obs_variance ) * fwd_mean[t - 1] +\n        (1 - (obs_variance / fwd_variance[t - 1] + chain_variance + obs_variance)) * beta\n\n        Mean(t) ≡ E(beta_{t,w} | beta_ˆ 1:T )\n        = fwd_mean[t - 1] + (obs_variance / fwd_variance[t - 1] + obs_variance) +\n        (1 - obs_variance / fwd_variance[t - 1] + obs_variance)) * mean[t]\n\n        \"\"\"\n        T = self.num_time_slices\n        obs = self.obs[word]\n        fwd_variance = self.fwd_variance[word]\n        mean = self.mean[word]\n        fwd_mean = self.fwd_mean[word]\n\n        # forward\n        fwd_mean[0] = 0\n        for t in range(1, T + 1):\n            c = self.obs_variance / (fwd_variance[t - 1] + chain_variance + self.obs_variance)\n            fwd_mean[t] = c * fwd_mean[t - 1] + (1 - c) * obs[t - 1]\n\n        # backward pass\n        mean[T] = fwd_mean[T]\n        for t in range(T - 1, -1, -1):\n            if chain_variance == 0.0:\n                c = 0.0\n            else:\n                c = chain_variance / (fwd_variance[t] + chain_variance)\n            mean[t] = c * fwd_mean[t] + (1 - c) * mean[t + 1]\n        return mean, fwd_mean\n\n    def compute_expected_log_prob(self):\n        \"\"\"\n        Compute the expected log probability given values of m.\n        The appendix describes the Expectation of log-probabilities in equation 5 of the DTM paper;\n        The below implementation is the result of solving the equation and is as implemented\n        in the original Blei DTM code.\n        \"\"\"\n        for (w, t), val in np.ndenumerate(self.e_log_prob):\n            self.e_log_prob[w][t] = self.mean[w][t + 1] - np.log(self.zeta[t])\n        return self.e_log_prob\n\n    def sslm_counts_init(self, obs_variance, chain_variance, sstats):\n        \"\"\"\n        Initialize State Space Language Model with LDA sufficient statistics.\n        Called for each topic-chain and initializes intial mean, variance and Topic-Word probabilities\n        for the first time-slice.\n        \"\"\"\n        W = self.vocab_len\n        T = self.num_time_slices\n\n        log_norm_counts = np.copy(sstats)\n        log_norm_counts = log_norm_counts / sum(log_norm_counts)\n        log_norm_counts = log_norm_counts + 1.0 / W\n        log_norm_counts = log_norm_counts / sum(log_norm_counts)\n        log_norm_counts = np.log(log_norm_counts)\n\n        # setting variational observations to transformed counts\n        self.obs = (np.repeat(log_norm_counts, T, axis=0)).reshape(W, T)\n        # set variational parameters\n        self.obs_variance = obs_variance\n        self.chain_variance = chain_variance\n\n        # compute post variance, mean\n        for w in range(0, W):\n            self.variance[w], self.fwd_variance[w] = self.compute_post_variance(w, self.chain_variance)\n            self.mean[w], self.fwd_mean[w] = self.compute_post_mean(w, self.chain_variance)\n\n        self.zeta = self.update_zeta()\n        self.e_log_prob = self.compute_expected_log_prob()\n\n    def fit_sslm(self, sstats):\n        \"\"\"\n        Fits variational distribution.\n        This is essentially the m-step.\n        Accepts the sstats for a particular topic for input and maximizes values for that topic.\n        Updates the values in the update_obs() and compute_expected_log_prob methods.\n        \"\"\"\n        W = self.vocab_len\n        bound = 0\n        old_bound = 0\n        sslm_fit_threshold = 1e-6\n        sslm_max_iter = 2\n        converged = sslm_fit_threshold + 1\n\n        # computing variance, fwd_variance\n        self.variance, self.fwd_variance = \\\n            (np.array(x) for x in list(zip(*[self.compute_post_variance(w, self.chain_variance) for w in range(0, W)])))\n\n        # column sum of sstats\n        totals = sstats.sum(axis=0)\n        iter_ = 0\n\n        model = \"DTM\"\n        if model == \"DTM\":\n            bound = self.compute_bound(sstats, totals)\n        if model == \"DIM\":\n            bound = self.compute_bound_fixed(sstats, totals)\n\n        logger.info(\"initial sslm bound is %f\", bound)\n\n        while converged > sslm_fit_threshold and iter_ < sslm_max_iter:\n            iter_ += 1\n            old_bound = bound\n            self.obs, self.zeta = self.update_obs(sstats, totals)\n\n            if model == \"DTM\":\n                bound = self.compute_bound(sstats, totals)\n            if model == \"DIM\":\n                bound = self.compute_bound_fixed(sstats, totals)\n\n            converged = np.fabs((bound - old_bound) / old_bound)\n            logger.info(\"iteration %i iteration lda seq bound is %f convergence is %f\", iter_, bound, converged)\n\n        self.e_log_prob = self.compute_expected_log_prob()\n        return bound\n\n    def compute_bound(self, sstats, totals):\n        \"\"\"\n        Compute log probability bound.\n        Forumula is as described in appendix of DTM by Blei. (formula no. 5)\n        \"\"\"\n        w = self.vocab_len\n        t = self.num_time_slices\n\n        term_1 = 0\n        term_2 = 0\n        term_3 = 0\n\n        val = 0\n        ent = 0\n\n        chain_variance = self.chain_variance\n        # computing mean, fwd_mean\n        self.mean, self.fwd_mean = \\\n            (np.array(x) for x in zip(*[self.compute_post_mean(w, self.chain_variance) for w in range(0, w)]))\n        self.zeta = self.update_zeta()\n\n        for w in range(0, w):\n            val += (self.variance[w][0] - self.variance[w][t]) / 2 * chain_variance\n\n        logger.info(\"Computing bound, all times\")\n\n        for t in range(1, t + 1):\n            term_1 = 0.0\n            term_2 = 0.0\n            ent = 0.0\n            for w in range(0, w):\n\n                m = self.mean[w][t]\n                prev_m = self.mean[w][t - 1]\n\n                v = self.variance[w][t]\n\n                # w_phi_l is only used in Document Influence Model; the values are aleays zero in this case\n                # w_phi_l = sslm.w_phi_l[w][t - 1]\n                # exp_i = np.exp(-prev_m)\n                # term_1 += (np.power(m - prev_m - (w_phi_l * exp_i), 2) / (2 * chain_variance)) -\n                # (v / chain_variance) - np.log(chain_variance)\n\n                term_1 += \\\n                    (np.power(m - prev_m, 2) / (2 * chain_variance)) - (v / chain_variance) - np.log(chain_variance)\n                term_2 += sstats[w][t - 1] * m\n                ent += np.log(v) / 2  # note the 2pi's cancel with term1 (see doc)\n\n            term_3 = -totals[t - 1] * np.log(self.zeta[t - 1])\n            val += term_2 + term_3 + ent - term_1\n\n        return val\n\n    def update_obs(self, sstats, totals):\n        \"\"\"\n        Function to perform optimization of obs. Parameters are suff_stats set up in the fit_sslm method.\n\n        TODO:\n        This is by far the slowest function in the whole algorithm.\n        Replacing or improving the performance of this would greatly speed things up.\n        \"\"\"\n\n        OBS_NORM_CUTOFF = 2\n        STEP_SIZE = 0.01\n        TOL = 1e-3\n\n        W = self.vocab_len\n        T = self.num_time_slices\n\n        runs = 0\n        mean_deriv_mtx = np.resize(np.zeros(T * (T + 1)), (T, T + 1))\n\n        norm_cutoff_obs = None\n        for w in range(0, W):\n            w_counts = sstats[w]\n            counts_norm = 0\n            # now we find L2 norm of w_counts\n            for i in range(0, len(w_counts)):\n                counts_norm += w_counts[i] * w_counts[i]\n\n            counts_norm = np.sqrt(counts_norm)\n\n            if counts_norm < OBS_NORM_CUTOFF and norm_cutoff_obs is not None:\n                obs = self.obs[w]\n                norm_cutoff_obs = np.copy(obs)\n            else:\n                if counts_norm < OBS_NORM_CUTOFF:\n                    w_counts = np.zeros(len(w_counts))\n\n                # TODO: apply lambda function\n                for t in range(0, T):\n                    mean_deriv = mean_deriv_mtx[t]\n                    mean_deriv = self.compute_mean_deriv(w, t, mean_deriv)\n                    mean_deriv_mtx[t] = mean_deriv\n\n                deriv = np.zeros(T)\n                args = self, w_counts, totals, mean_deriv_mtx, w, deriv\n                obs = self.obs[w]\n                model = \"DTM\"\n\n                if model == \"DTM\":\n                    # slowest part of method\n                    obs = optimize.fmin_cg(\n                        f=f_obs, fprime=df_obs, x0=obs, gtol=TOL, args=args, epsilon=STEP_SIZE, disp=0\n                    )\n                if model == \"DIM\":\n                    pass\n                runs += 1\n\n                if counts_norm < OBS_NORM_CUTOFF:\n                    norm_cutoff_obs = obs\n\n                self.obs[w] = obs\n\n        self.zeta = self.update_zeta()\n\n        return self.obs, self.zeta\n\n    def compute_mean_deriv(self, word, time, deriv):\n        \"\"\"\n        Used in helping find the optimum function.\n        computes derivative of E[\\beta_{t,w}]/d obs_{s,w} for t = 1:T.\n        put the result in deriv, allocated T+1 vector\n        \"\"\"\n\n        T = self.num_time_slices\n        fwd_variance = self.variance[word]\n\n        deriv[0] = 0\n\n        # forward pass\n        for t in range(1, T + 1):\n            if self.obs_variance > 0.0:\n                w = self.obs_variance / (fwd_variance[t - 1] + self.chain_variance + self.obs_variance)\n            else:\n                w = 0.0\n            val = w * deriv[t - 1]\n            if time == t - 1:\n                val += (1 - w)\n            deriv[t] = val\n\n        for t in range(T - 1, -1, -1):\n            if self.chain_variance == 0.0:\n                w = 0.0\n            else:\n                w = self.chain_variance / (fwd_variance[t] + self.chain_variance)\n            deriv[t] = w * deriv[t] + (1 - w) * deriv[t + 1]\n\n        return deriv\n\n    def compute_obs_deriv(self, word, word_counts, totals, mean_deriv_mtx, deriv):\n        \"\"\"\n        Derivation of obs which is used in derivative function [df_obs] while optimizing.\n        \"\"\"\n\n        # flag\n        init_mult = 1000\n\n        T = self.num_time_slices\n\n        mean = self.mean[word]\n        variance = self.variance[word]\n\n        # only used for DIM mode\n        # w_phi_l = self.w_phi_l[word]\n        # m_update_coeff = self.m_update_coeff[word]\n\n        # temp_vector holds temporary zeta values\n        self.temp_vect = np.zeros(T)\n\n        for u in range(0, T):\n            self.temp_vect[u] = np.exp(mean[u + 1] + variance[u + 1] / 2)\n\n        for t in range(0, T):\n            mean_deriv = mean_deriv_mtx[t]\n            term1 = 0\n            term2 = 0\n            term3 = 0\n            term4 = 0\n\n            for u in range(1, T + 1):\n                mean_u = mean[u]\n                mean_u_prev = mean[u - 1]\n                dmean_u = mean_deriv[u]\n                dmean_u_prev = mean_deriv[u - 1]\n\n                term1 += (mean_u - mean_u_prev) * (dmean_u - dmean_u_prev)\n                term2 += (word_counts[u - 1] - (totals[u - 1] * self.temp_vect[u - 1] / self.zeta[u - 1])) * dmean_u\n\n                model = \"DTM\"\n                if model == \"DIM\":\n                    # do some stuff\n                    pass\n\n            if self.chain_variance:\n                term1 = - (term1 / self.chain_variance)\n                term1 = term1 - (mean[0] * mean_deriv[0]) / (init_mult * self.chain_variance)\n            else:\n                term1 = 0.0\n\n            deriv[t] = term1 + term2 + term3 + term4\n\n        return deriv\n# endclass sslm\n\n\nclass LdaPost(utils.SaveLoad):\n\n    \"\"\"\n    Posterior values associated with each set of documents.\n    TODO: use **Hoffman, Blei, Bach: Online Learning for Latent Dirichlet Allocation, NIPS 2010.**\n    to update phi, gamma. End game would be to somehow replace LdaPost entirely with LdaModel.\n    \"\"\"\n\n    def __init__(self, doc=None, lda=None, max_doc_len=None, num_topics=None, gamma=None, lhood=None):\n\n        self.doc = doc\n        self.lda = lda\n        self.gamma = gamma\n        self.lhood = lhood\n        if self.gamma is None:\n            self.gamma = np.zeros(num_topics)\n        if self.lhood is None:\n            self.lhood = np.zeros(num_topics + 1)\n\n        if max_doc_len is not None and num_topics is not None:\n            self.phi = np.resize(np.zeros(max_doc_len * num_topics), (max_doc_len, num_topics))\n            self.log_phi = np.resize(np.zeros(max_doc_len * num_topics), (max_doc_len, num_topics))\n\n        # the following are class variables which are to be integrated during Document Influence Model\n\n        self.doc_weight = None\n        self.renormalized_doc_weight = None\n\n    def update_phi(self, doc_number, time):\n        \"\"\"\n        Update variational multinomial parameters, based on a document and a time-slice.\n        This is done based on the original Blei-LDA paper, where:\n        log_phi := beta * exp(Ψ(gamma)), over every topic for every word.\n\n        TODO: incorporate lee-sueng trick used in\n        **Lee, Seung: Algorithms for non-negative matrix factorization, NIPS 2001**.\n        \"\"\"\n        num_topics = self.lda.num_topics\n        # digamma values\n        dig = np.zeros(num_topics)\n\n        for k in range(0, num_topics):\n            dig[k] = digamma(self.gamma[k])\n\n        n = 0   # keep track of iterations for phi, log_phi\n        for word_id, count in self.doc:\n            for k in range(0, num_topics):\n                self.log_phi[n][k] = dig[k] + self.lda.topics[word_id][k]\n\n            log_phi_row = self.log_phi[n]\n            phi_row = self.phi[n]\n\n            # log normalize\n            v = log_phi_row[0]\n            for i in range(1, len(log_phi_row)):\n                v = np.logaddexp(v, log_phi_row[i])\n\n            # subtract every element by v\n            log_phi_row = log_phi_row - v\n            phi_row = np.exp(log_phi_row)\n            self.log_phi[n] = log_phi_row\n            self.phi[n] = phi_row\n            n += 1  # increase iteration\n\n        return self.phi, self.log_phi\n\n    def update_gamma(self):\n        \"\"\"\n        update variational dirichlet parameters as described in the original Blei LDA paper:\n        gamma = alpha + sum(phi), over every topic for every word.\n        \"\"\"\n        self.gamma = np.copy(self.lda.alpha)\n        n = 0  # keep track of number of iterations for phi, log_phi\n        for word_id, count in self.doc:\n            phi_row = self.phi[n]\n            for k in range(0, self.lda.num_topics):\n                self.gamma[k] += phi_row[k] * count\n            n += 1\n\n        return self.gamma\n\n    def init_lda_post(self):\n        \"\"\"\n        Initialize variational posterior, does not return anything.\n        \"\"\"\n        total = sum(count for word_id, count in self.doc)\n        self.gamma.fill(self.lda.alpha[0] + float(total) / self.lda.num_topics)\n        self.phi[:len(self.doc), :] = 1.0 / self.lda.num_topics\n        # doc_weight used during DIM\n        # ldapost.doc_weight = None\n\n    def compute_lda_lhood(self):\n        \"\"\"\n        compute the likelihood bound\n        \"\"\"\n        num_topics = self.lda.num_topics\n        gamma_sum = np.sum(self.gamma)\n\n        # to be used in DIM\n        # sigma_l = 0\n        # sigma_d = 0\n\n        lhood = gammaln(np.sum(self.lda.alpha)) - gammaln(gamma_sum)\n        self.lhood[num_topics] = lhood\n\n        # influence_term = 0\n        digsum = digamma(gamma_sum)\n\n        model = \"DTM\"  # noqa:F841\n        for k in range(0, num_topics):\n            # below code only to be used in DIM mode\n            # if ldapost.doc_weight is not None and (model == \"DIM\" or model == \"fixed\"):\n            #     influence_topic = ldapost.doc_weight[k]\n            #     influence_term = \\\n            #           - ((influence_topic * influence_topic + sigma_l * sigma_l) / 2.0 / (sigma_d * sigma_d))\n\n            e_log_theta_k = digamma(self.gamma[k]) - digsum\n            lhood_term = \\\n                (self.lda.alpha[k] - self.gamma[k]) * e_log_theta_k + \\\n                gammaln(self.gamma[k]) - gammaln(self.lda.alpha[k])\n            # TODO: check why there's an IF\n            n = 0\n            for word_id, count in self.doc:\n                if self.phi[n][k] > 0:\n                    lhood_term += \\\n                        count * self.phi[n][k] * (e_log_theta_k + self.lda.topics[word_id][k] - self.log_phi[n][k])\n                n += 1\n            self.lhood[k] = lhood_term\n            lhood += lhood_term\n            # in case of DIM add influence term\n            # lhood += influence_term\n\n        return lhood\n\n    def fit_lda_post(self, doc_number, time, ldaseq, LDA_INFERENCE_CONVERGED=1e-8,\n                    lda_inference_max_iter=25, g=None, g3_matrix=None, g4_matrix=None, g5_matrix=None):\n        \"\"\"\n        Posterior inference for lda.\n        g, g3, g4 and g5 are matrices used in Document Influence Model and not used currently.\n        \"\"\"\n\n        self.init_lda_post()\n        # sum of counts in a doc\n        total = sum(count for word_id, count in self.doc)\n\n        model = \"DTM\"\n        if model == \"DIM\":\n            # if in DIM then we initialise some variables here\n            pass\n\n        lhood = self.compute_lda_lhood()\n        lhood_old = 0\n        converged = 0\n        iter_ = 0\n\n        # first iteration starts here\n        iter_ += 1\n        lhood_old = lhood\n        self.gamma = self.update_gamma()\n\n        model = \"DTM\"\n\n        if model == \"DTM\" or sslm is None:\n            self.phi, self.log_phi = self.update_phi(doc_number, time)\n        elif model == \"DIM\" and sslm is not None:\n            self.phi, self.log_phi = self.update_phi_fixed(doc_number, time, sslm, g3_matrix, g4_matrix, g5_matrix)\n\n        lhood = self.compute_lda_lhood()\n        converged = np.fabs((lhood_old - lhood) / (lhood_old * total))\n\n        while converged > LDA_INFERENCE_CONVERGED and iter_ <= lda_inference_max_iter:\n\n            iter_ += 1\n            lhood_old = lhood\n            self.gamma = self.update_gamma()\n            model = \"DTM\"\n\n            if model == \"DTM\" or sslm is None:\n                self.phi, self.log_phi = self.update_phi(doc_number, time)\n            elif model == \"DIM\" and sslm is not None:\n                self.phi, self.log_phi = self.update_phi_fixed(doc_number, time, sslm, g3_matrix, g4_matrix, g5_matrix)\n\n            lhood = self.compute_lda_lhood()\n            converged = np.fabs((lhood_old - lhood) / (lhood_old * total))\n\n        return lhood\n\n    def update_lda_seq_ss(self, time, doc, topic_suffstats):\n        \"\"\"\n        Update lda sequence sufficient statistics from an lda posterior.\n        This is very similar to the update_gamma method and uses the same formula.\n        \"\"\"\n        num_topics = self.lda.num_topics\n\n        for k in range(0, num_topics):\n            topic_ss = topic_suffstats[k]\n            n = 0\n            for word_id, count in self.doc:\n                topic_ss[word_id][time] += count * self.phi[n][k]\n                n += 1\n            topic_suffstats[k] = topic_ss\n\n        return topic_suffstats\n\n\n# the following functions are used in update_obs as the function to optimize\ndef f_obs(x, *args):\n    \"\"\"\n    Function which we are optimising for minimizing obs.\n    \"\"\"\n    sslm, word_counts, totals, mean_deriv_mtx, word, deriv = args\n    # flag\n    init_mult = 1000\n\n    T = len(x)\n    val = 0\n    term1 = 0\n    term2 = 0\n\n    # term 3 and 4 for DIM\n    term3 = 0\n    term4 = 0\n\n    sslm.obs[word] = x\n    sslm.mean[word], sslm.fwd_mean[word] = sslm.compute_post_mean(word, sslm.chain_variance)\n\n    mean = sslm.mean[word]\n    variance = sslm.variance[word]\n\n    # only used for DIM mode\n    # w_phi_l = sslm.w_phi_l[word]\n    # m_update_coeff = sslm.m_update_coeff[word]\n\n    for t in range(1, T + 1):\n        mean_t = mean[t]\n        mean_t_prev = mean[t - 1]\n\n        val = mean_t - mean_t_prev\n        term1 += val * val\n        term2 += word_counts[t - 1] * mean_t - totals[t - 1] * np.exp(mean_t + variance[t] / 2) / sslm.zeta[t - 1]\n\n        model = \"DTM\"\n        if model == \"DIM\":\n            # stuff happens\n            pass\n\n    if sslm.chain_variance > 0.0:\n\n        term1 = - (term1 / (2 * sslm.chain_variance))\n        term1 = term1 - mean[0] * mean[0] / (2 * init_mult * sslm.chain_variance)\n    else:\n        term1 = 0.0\n\n    final = -(term1 + term2 + term3 + term4)\n\n    return final\n\n\ndef df_obs(x, *args):\n    \"\"\"\n    Derivative of function which optimises obs.\n    \"\"\"\n    sslm, word_counts, totals, mean_deriv_mtx, word, deriv = args\n\n    sslm.obs[word] = x\n    sslm.mean[word], sslm.fwd_mean[word] = sslm.compute_post_mean(word, sslm.chain_variance)\n\n    model = \"DTM\"\n    if model == \"DTM\":\n        deriv = sslm.compute_obs_deriv(word, word_counts, totals, mean_deriv_mtx, deriv)\n    elif model == \"DIM\":\n        deriv = sslm.compute_obs_deriv_fixed(p.word, p.word_counts, p.totals, p.sslm, p.mean_deriv_mtx, deriv)  # noqa:F821\n\n    return np.negative(deriv)\n", "meta": {"hexsha": "467ab47c6cee6ceeff65b627028122d3f961cd05", "size": 43899, "ext": "py", "lang": "Python", "max_stars_repo_path": "gensim/gensim/models/ldaseqmodel.py", "max_stars_repo_name": "Abas-Khan/thesis", "max_stars_repo_head_hexsha": "b733bd4382371203cc4992571890619a2e314047", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-11-27T06:30:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T15:56:32.000Z", "max_issues_repo_path": "gensim/gensim/models/ldaseqmodel.py", "max_issues_repo_name": "Abas-Khan/thesis", "max_issues_repo_head_hexsha": "b733bd4382371203cc4992571890619a2e314047", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-11-15T02:00:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T02:20:32.000Z", "max_forks_repo_path": "gensim/gensim/models/ldaseqmodel.py", "max_forks_repo_name": "Abas-Khan/thesis", "max_forks_repo_head_hexsha": "b733bd4382371203cc4992571890619a2e314047", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-04-04T12:38:47.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-04T12:38:47.000Z", "avg_line_length": 38.2062663185, "max_line_length": 123, "alphanum_fraction": 0.596095583, "include": true, "reason": "import numpy,from scipy", "num_tokens": 10851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.18359612086517296}}
{"text": "\"\"\"Code for FineNet in paper \"Robust Minutiae Extractor: Integrating Deep Networks and Fingerprint Domain Knowledge\" at ICB 2018\n  https://arxiv.org/pdf/1712.09401.pdf\n\n  If you use whole or partial function in this code, please cite paper:\n\n  @inproceedings{Nguyen_MinutiaeNet,\n    author    = {Dinh-Luan Nguyen and Kai Cao and Anil K. Jain},\n    title     = {Robust Minutiae Extractor: Integrating Deep Networks and Fingerprint Domain Knowledge},\n    booktitle = {The 11th International Conference on Biometrics, 2018},\n    year      = {2018},\n    }\n\"\"\"\n\n\nfrom functools import partial\nfrom multiprocessing import Pool\nfrom MinutiaeNet_utils import *\nfrom scipy import misc, ndimage, signal, sparse\nimport numpy as np\n\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.layers import Input\nfrom keras.layers.core import Lambda\nimport tensorflow as tf\n\ndef sub_load_data(data, img_size, aug):\n    img_name, dataset = data\n\n    img = misc.imread(dataset+'img_files/'+img_name+'.bmp', mode='L')\n\n\n    try:\n        seg = misc.imread(dataset + 'seg_files/' + img_name + '.bmp', mode='L')\n    except:\n        seg = np.ones_like(img)\n\n    try:\n        ali = misc.imread(dataset+'ori_files/'+img_name+'.jpg', mode='L')\n    except:\n        ali = np.zeros_like(img)\n    mnt = np.array(mnt_reader(dataset+'mnt_files/'+img_name+'.mnt'), dtype=float)\n\n    if any(img.shape != img_size):\n        # random pad mean values to reach required shape\n        if np.random.rand()<aug:\n            tra = np.int32(np.random.rand(2)*(np.array(img_size)-np.array(img.shape)))\n        else:\n            tra = np.int32(0.5*(np.array(img_size)-np.array(img.shape)))\n\n        img_t = np.ones(img_size)*np.mean(img)\n        seg_t = np.zeros(img_size)\n        ali_t = np.ones(img_size)*np.mean(ali)\n\n        img_t[tra[0]:tra[0]+img.shape[0],tra[1]:tra[1]+img.shape[1]] = img\n        seg_t[tra[0]:tra[0]+img.shape[0],tra[1]:tra[1]+img.shape[1]] = seg\n        ali_t[tra[0]:tra[0]+img.shape[0],tra[1]:tra[1]+img.shape[1]] = ali\n\n        img = img_t\n        seg = seg_t\n        ali = ali_t\n        mnt = mnt+np.array([tra[1],tra[0],0])\n\n    if np.random.rand()<aug:\n        # random rotation [0 - 360] & translation img_size / 4\n        rot = np.random.rand() * 360\n        tra = (np.random.rand(2)-0.5) / 2 * img_size\n        img = ndimage.rotate(img, rot, reshape=False, mode='reflect')\n        img = ndimage.shift(img, tra, mode='reflect')\n        seg = ndimage.rotate(seg, rot, reshape=False, mode='constant')\n        seg = ndimage.shift(seg, tra, mode='constant')\n        ali = ndimage.rotate(ali, rot, reshape=False, mode='reflect')\n        ali = ndimage.shift(ali, tra, mode='reflect')\n        mnt_r = point_rot(mnt[:, :2], rot/180*np.pi, img.shape, img.shape)\n        mnt = np.column_stack((mnt_r+tra[[1, 0]], mnt[:, 2]-rot/180*np.pi))\n\n    # only keep mnt that stay in pic & not on border\n    mnt = mnt[(8<=mnt[:,0])*(mnt[:,0]<img_size[1]-8)*(8<=mnt[:, 1])*(mnt[:,1]<img_size[0]-8), :]\n    return img, seg, ali, mnt\n\nuse_multiprocessing = False\ndef load_data(dataset, tra_ori_model, rand=False, aug=0.0, batch_size=1, sample_rate=None):\n\n    if type(dataset[0]) == str:\n        img_name, folder_name, img_size = get_maximum_img_size_and_names(dataset, sample_rate)\n    else:\n        img_name, folder_name, img_size = dataset\n\n    if rand:\n        rand_idx = np.arange(len(img_name))\n        np.random.shuffle(rand_idx)\n        img_name = img_name[rand_idx]\n        folder_name = folder_name[rand_idx]\n\n    if batch_size > 1 and use_multiprocessing==True:\n        p = Pool(batch_size)\n\n    p_sub_load_data = partial(sub_load_data, img_size=img_size, aug=aug)\n\n    for i in xrange(0,len(img_name), batch_size):\n        have_alignment = np.ones([batch_size, 1, 1, 1])\n        image = np.zeros((batch_size, img_size[0], img_size[1], 1))\n        segment = np.zeros((batch_size, img_size[0], img_size[1], 1))\n        alignment = np.zeros((batch_size, img_size[0], img_size[1], 1))\n\n        minutiae_w = np.zeros((batch_size, img_size[0]/8, img_size[1]/8, 1))-1\n        minutiae_h = np.zeros((batch_size, img_size[0]/8, img_size[1]/8, 1))-1\n        minutiae_o = np.zeros((batch_size, img_size[0]/8, img_size[1]/8, 1))-1\n\n        batch_name = [img_name[(i+j)%len(img_name)] for j in xrange(batch_size)]\n        batch_f_name = [folder_name[(i+j)%len(img_name)] for j in xrange(batch_size)]\n\n        if batch_size > 1 and use_multiprocessing==True:\n            results = p.map(p_sub_load_data, zip(batch_name, batch_f_name))\n        else:\n            results = map(p_sub_load_data, zip(batch_name, batch_f_name))\n\n        for j in xrange(batch_size):\n            img, seg, ali, mnt = results[j]\n            if np.sum(ali) == 0:\n                have_alignment[j, 0, 0, 0] = 0\n            image[j, :, :, 0] = img / 255.0\n            segment[j, :, :, 0] = seg / 255.0\n            alignment[j, :, :, 0] = ali / 255.0\n            minutiae_w[j, (mnt[:, 1]/8).astype(int), (mnt[:, 0]/8).astype(int), 0] = mnt[:, 0] % 8\n            minutiae_h[j, (mnt[:, 1]/8).astype(int), (mnt[:, 0]/8).astype(int), 0] = mnt[:, 1] % 8\n            minutiae_o[j, (mnt[:, 1]/8).astype(int), (mnt[:, 0]/8).astype(int), 0] = mnt[:, 2]\n\n        # get seg\n        label_seg = segment[:, ::8, ::8, :]\n        label_seg[label_seg>0] = 1\n        label_seg[label_seg<=0] = 0\n        minutiae_seg = (minutiae_o!=-1).astype(float)\n\n        # get ori & mnt\n        orientation = tra_ori_model.predict(alignment)\n        orientation = orientation/np.pi*180+90\n        orientation[orientation>=180.0] = 0.0 # orientation [0, 180)\n        minutiae_o = minutiae_o/np.pi*180+90 # [90, 450)\n        minutiae_o[minutiae_o>360] = minutiae_o[minutiae_o>360]-360 # to current coordinate system [0, 360)\n        minutiae_ori_o = np.copy(minutiae_o) # copy one\n        minutiae_ori_o[minutiae_ori_o>=180] = minutiae_ori_o[minutiae_ori_o>=180]-180 # for strong ori label [0,180)\n\n        # ori 2 gaussian\n        gaussian_pdf = signal.gaussian(361, 3)\n        y = np.reshape(np.arange(1, 180, 2), [1,1,1,-1])\n        delta = np.array(np.abs(orientation - y), dtype=int)\n        delta = np.minimum(delta, 180-delta)+180\n        label_ori = gaussian_pdf[delta]\n\n        # ori_o 2 gaussian\n        delta = np.array(np.abs(minutiae_ori_o - y), dtype=int)\n        delta = np.minimum(delta, 180-delta)+180\n        label_ori_o = gaussian_pdf[delta]\n\n        # mnt_o 2 gaussian\n        y = np.reshape(np.arange(1, 360, 2), [1,1,1,-1])\n        delta = np.array(np.abs(minutiae_o - y), dtype=int)\n        delta = np.minimum(delta, 360-delta)+180\n        label_mnt_o = gaussian_pdf[delta]\n\n        # w 2 gaussian\n        gaussian_pdf = signal.gaussian(17, 2)\n        y = np.reshape(np.arange(0, 8), [1,1,1,-1])\n        delta = (minutiae_w-y+8).astype(int)\n        label_mnt_w = gaussian_pdf[delta]\n\n        # h 2 gaussian\n        delta = (minutiae_h-y+8).astype(int)\n        label_mnt_h = gaussian_pdf[delta]\n\n        # mnt cls label -1:neg, 0:no care, 1:pos\n        label_mnt_s = np.copy(minutiae_seg)\n        label_mnt_s[label_mnt_s==0] = -1 # neg to -1\n        label_mnt_s = (label_mnt_s+ndimage.maximum_filter(label_mnt_s, size=(1,3,3,1)))/2 # around 3*3 pos -> 0\n\n        # apply segmentation\n        label_ori = label_ori * label_seg * have_alignment\n        label_ori_o = label_ori_o * minutiae_seg\n        label_mnt_o = label_mnt_o * minutiae_seg\n        label_mnt_w = label_mnt_w * minutiae_seg\n        label_mnt_h = label_mnt_h * minutiae_seg\n        yield image, label_ori, label_ori_o, label_seg, label_mnt_w, label_mnt_h, label_mnt_o, label_mnt_s, batch_name\n\n    if batch_size > 1 and use_multiprocessing==True:\n        p.close()\n        p.join()\n    return\n\ndef merge_mul(x):\n    return reduce(lambda x,y:x*y, x)\ndef merge_sum(x):\n    return reduce(lambda x,y:x+y, x)\ndef reduce_sum(x):\n    return K.sum(x,axis=-1,keepdims=True)\n\n# Group with depth\ndef merge_concat(x):\n    return K.tf.concat(x,3)\ndef select_max(x):\n    x = x / (K.max(x, axis=-1, keepdims=True)+K.epsilon())\n    x = K.tf.where(K.tf.greater(x, 0.999), x, K.tf.zeros_like(x)) # select the biggest one\n    x = x / (K.sum(x, axis=-1, keepdims=True)+K.epsilon()) # prevent two or more ori is selected\n    return x\n\n\nkernal2angle = np.reshape(np.arange(1, 180, 2, dtype=float), [1,1,1,90])/90.*np.pi #2angle = angle*2\nsin2angle, cos2angle = np.sin(kernal2angle), np.cos(kernal2angle)\ndef ori2angle(ori):\n    sin2angle_ori = K.sum(ori*sin2angle, -1, keepdims=True)\n    cos2angle_ori = K.sum(ori*cos2angle, -1, keepdims=True)\n    modulus_ori = K.sqrt(K.square(sin2angle_ori)+K.square(cos2angle_ori))\n    return sin2angle_ori, cos2angle_ori, modulus_ori\n\n\n# find highest peak using gaussian\ndef ori_highest_peak(y_pred, length=180):\n    glabel = gausslabel(length=length,stride=2).astype(np.float32)\n    y_pred = tf.convert_to_tensor(y_pred, np.float32)\n    ori_gau = K.conv2d(y_pred,glabel,padding='same')\n    return ori_gau\n\ndef ori_acc_delta_k(y_true, y_pred, k=10, max_delta=180):\n    # get ROI\n    label_seg = K.sum(y_true, axis=-1)\n    label_seg = K.tf.cast(K.tf.greater(label_seg, 0), K.tf.float32)\n    # get pred angle\n    angle = K.cast(K.argmax(ori_highest_peak(y_pred, max_delta), axis=-1), dtype=K.tf.float32)*2.0+1.0\n    # get gt angle\n    angle_t = K.cast(K.argmax(y_true, axis=-1), dtype=K.tf.float32)*2.0+1.0\n    # get delta\n    angle_delta = K.abs(angle_t - angle)\n    acc = K.tf.less_equal(K.minimum(angle_delta, max_delta-angle_delta), k)\n    acc = K.cast(acc, dtype=K.tf.float32)\n    # apply ROI\n    acc = acc*label_seg\n    acc = K.sum(acc) / (K.sum(label_seg)+K.epsilon())\n    return acc\ndef ori_acc_delta_10(y_true, y_pred):\n    return ori_acc_delta_k(y_true, y_pred, 10)\ndef ori_acc_delta_20(y_true, y_pred):\n    return ori_acc_delta_k(y_true, y_pred, 20)\ndef mnt_acc_delta_10(y_true, y_pred):\n    return ori_acc_delta_k(y_true, y_pred, 10, 360)\ndef mnt_acc_delta_20(y_true, y_pred):\n    return ori_acc_delta_k(y_true, y_pred, 20, 360)\n\ndef seg_acc_pos(y_true, y_pred):\n    y_true = K.tf.where(K.tf.less(y_true,0.0), K.tf.zeros_like(y_true), y_true)\n    acc = K.cast(K.equal(y_true, K.round(y_pred)), dtype=K.tf.float32)\n    acc = K.sum(acc * y_true) / (K.sum(y_true)+K.epsilon())\n    return acc\ndef seg_acc_neg(y_true, y_pred):\n    y_true = K.tf.where(K.tf.less(y_true,0.0), K.tf.zeros_like(y_true), y_true)\n    acc = K.cast(K.equal(y_true, K.round(y_pred)), dtype=K.tf.float32)\n    acc = K.sum(acc * (1-y_true)) / (K.sum(1-y_true)+K.epsilon())\n    return acc\ndef seg_acc_all(y_true, y_pred):\n    y_true = K.tf.where(K.tf.less(y_true,0.0), K.tf.zeros_like(y_true), y_true)\n    return K.mean(K.equal(y_true, K.round(y_pred)))\n\ndef mnt_mean_delta(y_true, y_pred):\n    # get ROI\n    label_seg = K.sum(y_true, axis=-1)\n    label_seg = K.tf.cast(K.tf.greater(label_seg, 0), K.tf.float32)\n    # get pred pos\n    pos = K.cast(K.argmax(y_pred, axis=-1), dtype=K.tf.float32)\n    # get gt pos\n    pos_t = K.cast(K.argmax(y_true, axis=-1), dtype=K.tf.float32)\n    # get delta\n    pos_delta = K.abs(pos_t - pos)\n    # apply ROI\n    pos_delta = pos_delta*label_seg\n    mean_delta = K.sum(pos_delta) / (K.sum(label_seg)+K.epsilon())\n    return mean_delta\n\n\n\n# currently can only produce one each time\ndef label2mnt(mnt_s_out, mnt_w_out, mnt_h_out, mnt_o_out, thresh=0.5):\n    mnt_s_out = np.squeeze(mnt_s_out)\n    mnt_w_out = np.squeeze(mnt_w_out)\n    mnt_h_out = np.squeeze(mnt_h_out)\n    mnt_o_out = np.squeeze(mnt_o_out)\n    assert len(mnt_s_out.shape)==2 and len(mnt_w_out.shape)==3 and len(mnt_h_out.shape)==3 and len(mnt_o_out.shape)==3\n\n    # get cls results\n    mnt_sparse = sparse.coo_matrix(mnt_s_out>thresh)\n    mnt_list = np.array(zip(mnt_sparse.row, mnt_sparse.col), dtype=np.int32)\n    if mnt_list.shape[0] == 0:\n        return np.zeros((0, 4))\n\n    # get regression results\n    mnt_w_out = np.argmax(mnt_w_out, axis=-1)\n    mnt_h_out = np.argmax(mnt_h_out, axis=-1)\n    mnt_o_out = np.argmax(mnt_o_out, axis=-1) # TODO: use ori_highest_peak(np version)\n\n    # get final mnt\n    mnt_final = np.zeros((len(mnt_list), 4))\n    mnt_final[:, 0] = mnt_sparse.col*8 + mnt_w_out[mnt_list[:,0], mnt_list[:,1]]\n    mnt_final[:, 1] = mnt_sparse.row*8 + mnt_h_out[mnt_list[:,0], mnt_list[:,1]]\n    mnt_final[:, 2] = (mnt_o_out[mnt_list[:,0], mnt_list[:,1]]*2-89.)/180*np.pi\n    mnt_final[mnt_final[:, 2]<0.0, 2] = mnt_final[mnt_final[:, 2]<0.0, 2]+2*np.pi\n    # New one\n    mnt_final[:, 2] = (-mnt_final[:, 2]) % (2*np.pi)\n    mnt_final[:, 3] = mnt_s_out[mnt_list[:,0], mnt_list[:, 1]]\n\n    return mnt_final\n\n\n# image normalization\ndef img_normalization(img_input, m0=0.0, var0=1.0):\n    m = K.mean(img_input, axis=[1,2,3], keepdims=True)\n    var = K.var(img_input, axis=[1,2,3], keepdims=True)\n    after = K.sqrt(var0*K.tf.square(img_input-m)/var)\n    image_n = K.tf.where(K.tf.greater(img_input, m), m0+after, m0-after)\n    return image_n\n\n# atan2 function\ndef atan2(y_x):\n    y, x = y_x[0], y_x[1]+K.epsilon()\n    atan = K.tf.atan(y/x)\n    angle = K.tf.where(K.tf.greater(x,0.0), atan, K.tf.zeros_like(x))\n    angle = K.tf.where(K.tf.logical_and(K.tf.less(x,0.0),  K.tf.greater_equal(y,0.0)), atan+np.pi, angle)\n    angle = K.tf.where(K.tf.logical_and(K.tf.less(x,0.0),  K.tf.less(y,0.0)), atan-np.pi, angle)\n    return angle\n\n# traditional orientation estimation\ndef orientation(image, stride=8, window=17):\n    with K.tf.name_scope('orientation'):\n        assert image.get_shape().as_list()[3] == 1, 'Images must be grayscale'\n        strides = [1, stride, stride, 1]\n        E = np.ones([window, window, 1, 1])\n        sobelx = np.reshape(np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=float), [3, 3, 1, 1])\n        sobely = np.reshape(np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]], dtype=float), [3, 3, 1, 1])\n        gaussian = np.reshape(gaussian2d((5, 5), 1), [5, 5, 1, 1])\n        with K.tf.name_scope('sobel_gradient'):\n            Ix = K.tf.nn.conv2d(image, sobelx, strides=[1,1,1,1], padding='SAME', name='sobel_x')\n            Iy = K.tf.nn.conv2d(image, sobely, strides=[1,1,1,1], padding='SAME', name='sobel_y')\n        with K.tf.name_scope('eltwise_1'):\n            Ix2 = K.tf.multiply(Ix, Ix, name='IxIx')\n            Iy2 = K.tf.multiply(Iy, Iy, name='IyIy')\n            Ixy = K.tf.multiply(Ix, Iy, name='IxIy')\n        with K.tf.name_scope('range_sum'):\n            Gxx = K.tf.nn.conv2d(Ix2, E, strides=strides, padding='SAME', name='Gxx_sum')\n            Gyy = K.tf.nn.conv2d(Iy2, E, strides=strides, padding='SAME', name='Gyy_sum')\n            Gxy = K.tf.nn.conv2d(Ixy, E, strides=strides, padding='SAME', name='Gxy_sum')\n        with K.tf.name_scope('eltwise_2'):\n            Gxx_Gyy = K.tf.subtract(Gxx, Gyy, name='Gxx_Gyy')\n            theta = atan2([2*Gxy, Gxx_Gyy]) + np.pi\n        # two-dimensional low-pass filter: Gaussian filter here\n        with K.tf.name_scope('gaussian_filter'):\n            phi_x = K.tf.nn.conv2d(K.tf.cos(theta), gaussian, strides=[1,1,1,1], padding='SAME', name='gaussian_x')\n            phi_y = K.tf.nn.conv2d(K.tf.sin(theta), gaussian, strides=[1,1,1,1], padding='SAME', name='gaussian_y')\n            theta = atan2([phi_y, phi_x])/2\n    return theta\n\ndef get_tra_ori():\n    img_input=Input(shape=(None, None, 1))\n    theta = Lambda(orientation)(img_input)\n    model = Model(inputs=[img_input,], outputs=[theta,])\n    return model\ntra_ori_model = get_tra_ori()\n\ndef get_maximum_img_size_and_names(dataset, sample_rate=None, max_size=None):\n\n    if isinstance(dataset, basestring):\n        dataset = [dataset]\n    if sample_rate is None:\n        sample_rate = [1]*len(dataset)\n    img_name, folder_name, img_size = [], [], []\n\n    for folder, rate in zip(dataset, sample_rate):\n        _, img_name_t = get_files_in_folder(folder, 'img_files/*'+'.bmp')\n        img_name.extend(img_name_t.tolist()*rate)\n        folder_name.extend([folder]*img_name_t.shape[0]*rate)\n\n        img_size.append(np.array(misc.imread(folder + 'img_files/' + img_name_t[0] + '.bmp', mode='L').shape))\n\n    img_name = np.asarray(img_name)\n    folder_name = np.asarray(folder_name)\n    img_size = np.max(np.asarray(img_size), axis=0)\n    # let img_size % 8 == 0\n    img_size = np.array(np.ceil(img_size / 8) * 8, dtype=np.int32)\n    return img_name, folder_name, img_size\n\n", "meta": {"hexsha": "93b03d6b398987f6f52362f374c4c0234cd443c0", "size": 16218, "ext": "py", "lang": "Python", "max_stars_repo_path": "CoarseNet/CoarseNet_utils.py", "max_stars_repo_name": "AlexBlack2202/MinutiaeNet", "max_stars_repo_head_hexsha": "af14e8cf4cf0dbed5372baa1be9ca926ba51b7ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-04T01:33:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-04T01:33:13.000Z", "max_issues_repo_path": "CoarseNet/CoarseNet_utils.py", "max_issues_repo_name": "miguelmedinaperez/MinutiaeNet", "max_issues_repo_head_hexsha": "08bc5f884a92d16591c6c3e11224e6c6398f8d63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CoarseNet/CoarseNet_utils.py", "max_forks_repo_name": "miguelmedinaperez/MinutiaeNet", "max_forks_repo_head_hexsha": "08bc5f884a92d16591c6c3e11224e6c6398f8d63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9069767442, "max_line_length": 128, "alphanum_fraction": 0.6335553089, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.18359610745431318}}
{"text": "\"\"\"a module that houses routines to solve for sequences of stellar models\n\"\"\"\n__author__ = \"Reed Essick (reed.essick@gmail.com)\"\n\n#-------------------------------------------------\n\nimport numpy as np\n\nfrom .ode import (standard, logenthalpy)\nfrom universality.utils import (io, utils)\n\n#-------------------------------------------------\n\nDEFAULT_MIN_NUM_MODELS = 2\n\nDEFAULT_INTERPOLATOR_RTOL = 1e-2 ### used to determine accuracy of interpolator for macroscopic properties\nDEFAULT_MIN_DPRESSUREC2_RTOL = 1e-2 ### used put a limit on how closely we space central pressures\n\nDEFAULT_INTEGRATION_RTOL = 1e-4\n\nKNOWN_FORMALISMS = [\n    'standard',\n    'standard_MR',\n    'standard_MRLambda',\n    'logenthalpy',\n    'logenthalpy_MR',\n    'logenthalpy_MRLambda',\n]\nDEFAULT_FORMALISM = KNOWN_FORMALISMS[0]\n\nDEFAULT_CENTRAL_COLUMN_TEMPLATE = 'central_%s'\n\nDEFAULT_PRESSUREC2_COLUMN = 'pressurec2'\nDEFAULT_ENERGY_DENSITYC2_COLUMN = 'energy_densityc2'\nDEFAULT_BARYON_DENSITY_COLUMN = 'baryon_density'\n\n#-------------------------------------------------\n\ndef process2sequences(\n        eos,\n        eostmp,\n        mactmp,\n        min_central_pressurec2,\n        max_central_pressurec2,\n        central_baryon_density_range=None,\n        central_energy_densityc2_range=None,\n        mod=1000,\n        pressurec2_column=DEFAULT_PRESSUREC2_COLUMN,\n        energy_densityc2_column=DEFAULT_ENERGY_DENSITYC2_COLUMN,\n        baryon_density_column=DEFAULT_BARYON_DENSITY_COLUMN,\n        cs2c2_column=None,\n        central_eos_column=[],\n        central_column_template=DEFAULT_CENTRAL_COLUMN_TEMPLATE,\n        formalism=DEFAULT_FORMALISM,\n        verbose=False,\n        Verbose=False,\n        **kwargs\n    ):\n    '''integrate stellar models for a whole set of EoS in a process\n    '''\n    verbose |= Verbose\n\n    for draw in eos:\n        tmp = {'draw':draw, 'moddraw':draw//mod}\n        eospath = eostmp%tmp\n\n        if verbose:\n            print('loading EoS data from: '+eospath)\n        cols = [pressurec2_column, energy_densityc2_column, baryon_density_column]\n        if cs2c2_column is not None:\n            cols.append(cs2c2_column)\n\n        data, cols = io.load(eospath, cols+central_eos_column) ### NOTE: this will not produce duplicated columns\n\n        pressurec2 = data[:,cols.index(pressurec2_column)]\n        energy_densityc2 = data[:,cols.index(energy_densityc2_column)]\n        baryon_density = data[:, cols.index(baryon_density_column)]\n\n        if cs2c2_column is not None:\n            cs2c2 = data[:,cols.index(cs2c2_column)]\n        else:\n            cs2c2 = utils.num_dfdx(energy_densityc2, pressurec2)\n\n        ### get local copy of bounds for just this EoS\n        max_central_pc2 = max_central_pressurec2\n        min_central_pc2 = min_central_pressurec2\n\n        ### sanity check that our integration range is compatible with the EoS data available\n        max_pressurec2 = np.max(pressurec2)\n        if max_central_pc2 > max_pressurec2:\n            if verbose:\n                print('limitting central_pressurec2 <= %.6e based on EoS data\\'s range'%max_pressurec2)\n            max_central_pc2 = max_pressurec2\n\n        min_pressurec2 = np.min(pressurec2)\n        if min_central_pc2 < min_pressurec2:\n            if verbose:\n                print('limitting central_pressurec2 >= %.6e based on EoS data\\'s range'%min_pressurec2)\n            min_central_pc2 = min_pressurec2\n\n        ### additionally check whether we're obeying the requested bounds on central baryon and energy densities\n        if central_baryon_density_range is not None:\n            min_baryon_density, max_baryon_density = central_baryon_density_range\n\n            # check minimum\n            min_pc2 = np.interp(min_baryon_density, baryon_density, pressurec2)\n            if min_pc2 > min_central_pc2:\n                if verbose:\n                    print('limitting central_pressurec2 >= %.6e based on min_baryon_density = %.6e'%(min_pc2, min_baryon_density))\n                min_central_pc2 = min_pc2\n\n            # check maximum\n            max_pc2 = np.interp(max_baryon_density, baryon_density, pressurec2)\n            if max_pc2 < max_central_pc2:\n                if verbose:\n                    print('limitting central_pressurec2 <= %.6e based on max_baryon_density = %.6e'%(max_pc2, max_baryon_density))\n                max_central_pc2 = max_pc2\n\n        if central_energy_densityc2_range is not None:\n            min_energy_densityc2, max_energy_densityc2 = central_energy_densityc2_range\n\n            # check minimum\n            min_pc2 = np.interp(min_energy_densityc2, energy_densityc2, pressurec2)\n            if min_pc2 > min_central_pc2:\n                if verbose:\n                    print('limitting central_pressurec2 >= %.6e based on min_energy_densityc2 = %.6e'%(min_pc2, min_energy_densityc2))\n                min_central_p2 = min_pc2\n\n            # check maximum\n            max_pc2 = np.interp(max_baryon_density, energy_densityc2, pressurec2)\n            if max_pc2 < max_central_pc2:\n                if verbose:\n                    print('limitting central_pressurec2 <= %.6e based on max_energy_densityc2 = %.6e'%(max_pc2, max_energy_densityc2))\n                max_central_pc2 = max_pc2\n\n        ### check to make sure the pressure bounds are sane, futz them if they are not\n        if max_central_pc2 < min_central_pc2:\n            if verbose:\n                print('''WARNING: central pressure bounds are out of order! Reverting to original bounds!\n    min_central_pressurec2 = %.6e\n    max_central_pressurec2 = %.6e'''%(min_central_pressurec2, max_central_pressurec2))\n            min_central_pc2, max_central_pc2 = min_central_pressurec2, max_central_pressurec2\n\n        if verbose:\n            print('''proceeding with central pressure bounds:\n    min_central_pressurec2 = %.6e\n    max_central_pressurec2 = %.6e'''%(min_central_pc2, max_central_pc2))\n\n        ### now compute the stellar sequence\n        if verbose:\n            print('solving for sequence of stellar models with formalism=%s'%formalism)\n        central_pressurec2, macro, macro_cols = stellar_sequence(\n            min_central_pc2,\n            max_central_pc2,\n            (pressurec2, energy_densityc2, baryon_density, cs2c2),\n            verbose=Verbose,\n            formalism=formalism,\n            **kwargs\n        )\n\n        if verbose:\n            print('    evaluated %d stellar models'%len(central_pressurec2))\n\n        sequence, columns = append_central_values(\n            central_pressurec2,\n            pressurec2,\n            data,\n            cols,\n            macro,\n            macro_cols,\n            central_eos_column=central_eos_column,\n            central_column_template=central_column_template,\n            verbose=verbose,\n        )\n\n        ### write the output\n        macpath = mactmp%tmp\n        if verbose:\n            print('writing stellar sequence to: '+macpath)\n        io.write(macpath, sequence, columns)\n\ndef append_central_values(\n        central_pressurec2,\n        pressurec2,\n        eosdata,\n        eoscols,\n        macdata,\n        maccols,\n        central_eos_column=[],\n        central_column_template=DEFAULT_CENTRAL_COLUMN_TEMPLATE,\n        verbose=False,\n    ):\n\n    ### figure out the central values of all the EoS columns\n    if verbose:\n        print('extracting central values of all EoS parameters')\n    Neos = len(central_eos_column)\n    Nmac = len(maccols)\n\n    sequence = np.empty((len(central_pressurec2), Neos+Nmac), dtype=float)\n    columns = []\n\n    # extract the central EoS parameters \n    for i, col in enumerate(central_eos_column):\n        sequence[:,i] = np.interp(central_pressurec2, pressurec2, eosdata[:,eoscols.index(col)])\n        columns.append(central_column_template%col)\n\n    # add in the macro properties\n    sequence[:,Neos:] = macdata\n    columns += maccols\n\n    return sequence, columns\n\ndef stellar_sequence(\n        min_central_pressurec2,\n        max_central_pressurec2,\n        eos,\n        min_num_models=DEFAULT_MIN_NUM_MODELS,\n        interpolator_rtol=DEFAULT_INTERPOLATOR_RTOL,\n        min_dpressurec2_rtol=DEFAULT_MIN_DPRESSUREC2_RTOL,\n        integration_rtol=DEFAULT_INTEGRATION_RTOL,\n        formalism=DEFAULT_FORMALISM,\n        verbose=False,\n        **kwargs\n    ):\n    \"\"\"solve for a sequence of stellar models such that the resulting interpolator has relative error less than \"interpolator_rtol\"\n    expect eos = (pressurec2, energy_densityc2, baryon_density, cs2c2)\n    \"\"\"\n    if 'logenthalpy' in formalism: ### logenthalpy is the integration coordinate\n        if formalism == 'logenthalpy':\n            integrate = logenthalpy.integrate\n            macro_cols = logenthalpy.MACRO_COLS\n\n        elif formalism == 'logenthalpy_MR':\n            integrate = logenthalpy.integrate_MR\n            macro_cols = logenthalpy.MACRO_COLS_MR\n\n        elif formalism == 'logenthalpy_MRLambda':\n            integrate = logenthalpy.integrate_MRLambda\n            macro_cols = logenthalpy.MACRO_COLS_MRLambda\n\n        else:\n            raise ValueError('logenthalpy-based formalism=%s not understood! Must be one of: %s'%(formalism, ', '.join(KNOWN_FORMALISMS)))\n\n        R_ind = None ### don't pass max_dr to integrate\n\n        ### compute the log(enthalpy per rest mass). Do this here so we only have to do it once\n        pc2, ec2, rho, cs2c2 = eos\n        logh = logenthalpy.eos2logh(pc2, ec2)\n        eos = (logh, pc2, ec2, rho, cs2c2)\n\n    elif 'standard' in formalism: ### radius is the integration coordinate\n        if formalism == 'standard':\n            integrate = standard.integrate\n            macro_cols = standard.MACRO_COLS\n\n        elif formalism == 'standard_MR':\n            integrate = standard.integrate_MR\n            macro_cols = standard.MACRO_COLS_MR\n\n        elif formalism == 'standard_MRLambda':\n            integrate = standard.integrate_MRLambda\n            macro_cols = standard.MACRO_COLS_MRLambda\n\n        else:\n            raise ValueError('standard formalism=%s not understood! Must be one of: %s'%(formalism, ', '.join(KNOWN_FORMALISMS)))\n\n        R_ind = macro_cols.index('R')\n\n    else: ### formalism not understood\n        raise ValueError('formalism=%s not understood! Must be one of: %s'%(formalism, ', '.join(KNOWN_FORMALISMS)))\n\n    ### determine the initial grid of central pressures\n    pressurec2 = eos[0]\n    central_pressurec2 = list(np.logspace(np.log10(min_central_pressurec2), np.log10(max_central_pressurec2), min_num_models))\n\n    ### recursively call integrator until interpolation is accurate enough\n    central_pc2 = [central_pressurec2[0]]\n    if verbose:\n        print('computing stellar model with central pressure/c2 = %.6e'%central_pc2[-1])\n\n    macro = [integrate(central_pc2[-1], eos, rtol=integration_rtol, **kwargs)]\n\n    ### perform recursive search to get a good interpolator\n    for max_pc2 in central_pressurec2[1:]:\n        new_central_pc2, new_macro = bisection_stellar_sequence(\n            central_pc2[-1],\n            max_pc2,\n            eos,\n            integrate,\n            min_pc2_macro=macro[-1],\n            interpolator_rtol=interpolator_rtol,\n            min_dpressurec2_rtol=min_dpressurec2_rtol,\n            integration_rtol=integration_rtol,\n            R_ind=R_ind,\n            verbose=verbose,\n        )\n\n        ### add the stellar models to the cumulative list\n        central_pc2 += new_central_pc2[1:]\n        macro += new_macro[1:]\n\n    ### return the results\n    return central_pc2, macro, macro_cols\n\ndef bisection_stellar_sequence(\n        min_pc2,\n        max_pc2,\n        eos,\n        foo,\n        min_pc2_macro=None,\n        max_pc2_macro=None,\n        interpolator_rtol=DEFAULT_INTERPOLATOR_RTOL,\n        min_dpressurec2_rtol=DEFAULT_MIN_DPRESSUREC2_RTOL,\n        integration_rtol=DEFAULT_INTEGRATION_RTOL,\n        R_ind=None,\n        verbose=False,\n        **kwargs\n    ):\n    '''recursively compute estimates of the interpolator error until it is below rtol\n    '''\n    if min_pc2_macro is None:\n        if verbose:\n            print('computing stellar model with central pressure/c2 = %.6e'%min_pc2)\n        min_pc2_macro = foo(min_pc2, eos, rtol=integration_rtol, **kwargs)\n    min_pc2_macro = np.array(min_pc2_macro)\n\n    if max_pc2_macro is None:\n        if verbose:\n            print('computing stellar model with central pressure/c2 = %.6e'%max_pc2)\n        if R_ind is not None:\n            ### scale max step size with what we expect for the radius\n            ### we need this to be pretty conservative, as this loop is is primarily entered when\n            ### we are just starting a segment and there could be wild changes in the radius\n            kwargs['max_dr'] = 0.001*min_pc2_macro[R_ind] * 1e5 ### convert from km -> cm\n\n        max_pc2_macro = foo(max_pc2, eos, rtol=integration_rtol, **kwargs)\n    max_pc2_macro = np.array(max_pc2_macro)\n\n    ### check to see whether central pressures are close enough\n    if 2*(max_pc2 - min_pc2) < min_dpressurec2_rtol * (max_pc2 + min_pc2):\n        return [min_pc2, max_pc2], [min_pc2_macro, max_pc2_macro]\n\n    ### integrate at the mid point\n    mid_pc2 = (min_pc2*max_pc2)**0.5\n    if verbose:\n        print('computing stellar model with central pressure/c2 = %.6e'%mid_pc2)\n    if R_ind is not None:\n        ### here we can be less stringent with max_dr since we're interpolating between models and have a better idea of the behavior\n        kwargs['max_dr'] = 0.1*min(min_pc2_macro[R_ind], max_pc2_macro[R_ind]) * 1e5 ### convert from km -> cm\n\n    mid_pc2_macro = np.array(foo(mid_pc2, eos, rtol=integration_rtol, **kwargs))\n\n    ### condition on whether we are accurate enough to determine recursive termination condition\n    # compute errors based on a linear interpolation\n    errors = mid_pc2_macro - (min_pc2_macro + (max_pc2_macro - min_pc2_macro) * (mid_pc2 - min_pc2) / (max_pc2 - min_pc2))\n\n    if np.all(np.abs(errors) < interpolator_rtol*mid_pc2_macro): ### interpolation is \"good enough\"\n        return [min_pc2, mid_pc2, max_pc2], [min_pc2_macro, mid_pc2_macro, max_pc2_macro]\n\n    else: # interpolation is not good enough, so we recurse to compute mid-points of sub-intervals\n        left_pc2, left_macro = bisection_stellar_sequence(\n            min_pc2,\n            mid_pc2,\n            eos,\n            foo,\n            min_pc2_macro=min_pc2_macro,\n            max_pc2_macro=mid_pc2_macro,\n            interpolator_rtol=interpolator_rtol,\n            min_dpressurec2_rtol=min_dpressurec2_rtol,\n            R_ind=R_ind,\n            integration_rtol=integration_rtol,\n            verbose=verbose,\n            **kwargs\n        )\n\n        right_pc2, right_macro = bisection_stellar_sequence(\n            mid_pc2,\n            max_pc2,\n            eos,\n            foo,\n            min_pc2_macro=mid_pc2_macro,\n            max_pc2_macro=max_pc2_macro,\n            interpolator_rtol=interpolator_rtol,\n            min_dpressurec2_rtol=min_dpressurec2_rtol,\n            R_ind=R_ind,\n            integration_rtol=integration_rtol,\n            verbose=verbose,\n            **kwargs\n        )\n\n        return left_pc2 + right_pc2[1:], left_macro + right_macro[1:] ### avoid returning repeated models\n", "meta": {"hexsha": "103d32a87244782875a991986ccce8b2d10bf58f", "size": 15136, "ext": "py", "lang": "Python", "max_stars_repo_path": "universality/tov/sequences.py", "max_stars_repo_name": "isaaclegred/universality", "max_stars_repo_head_hexsha": "9eac607a78b7cb67c1509ea68f4de631437f393a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-02T13:41:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T13:41:46.000Z", "max_issues_repo_path": "universality/tov/sequences.py", "max_issues_repo_name": "isaaclegred/universality", "max_issues_repo_head_hexsha": "9eac607a78b7cb67c1509ea68f4de631437f393a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2018-01-31T15:14:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-10T21:32:05.000Z", "max_forks_repo_path": "universality/tov/sequences.py", "max_forks_repo_name": "isaaclegred/universality", "max_forks_repo_head_hexsha": "9eac607a78b7cb67c1509ea68f4de631437f393a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-12-07T04:04:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T19:00:17.000Z", "avg_line_length": 38.5139949109, "max_line_length": 138, "alphanum_fraction": 0.6496432347, "include": true, "reason": "import numpy", "num_tokens": 3761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.18359610745431318}}
{"text": "import numpy as np\nimport torch\nimport sys\nfrom collections import deque\n# prob_thres = 0.5\n# # spatial_thres = 3\n# norm_thres = np.cos(np.deg2rad(30))\n# RADIUS =\n\nimport torch.nn.functional as F\n# from vPlaneRecover.util import coordinates\nimport trimesh\nfrom skimage import measure\n\n# grouping the 3 sigma region defined in prepare_data\nGROUPING_RADIUS =  {16: 1, 8: 2, 4: 3}\n\n#  window, blind, pillow, mirror, clothes, shower curtain, person, toilet, sink, lamp, bag\nNONE_PLANE_ID = [0, -1, 9, 13, 18, 19, 21, 28, 31, 33, 34,  35, 37 ]\n\n# for generating\nSTD =  {16: 1 ,8: 2, 4: 3 }\nADOPT_THRES = 0.03\nPI = torch.tensor(3.1415926)\nSQRT_2PI = 2.506628\n\nORTHOGONAL_THRES = np.cos(np.deg2rad(60))\n# for inference\nPLANE_MIN_N_VOXELS = {16: 25 ,8: 100, 4: 400 } #0.04**3*1600=0.1024 m3 -- marchine cube need at least 2\n\n# SEM_INS_MAP = {1:0, 2:1, 22:2, 30:3, 3:4, 4:5, 5:6, 6:7, 7:8, 8:9, 10:10,\n#                11:11, 12:12, 14:13, 16:14, 24:15, 28:16, 33:17, 36:18, 39:19}\n#\n# CLASS_LABELS = ['wall', 'floor', 'ceiling', 'whiteboard', 'cabinet', 'bed', 'chair', 'sofa', 'table', 'door',\n#                 'bookshelf', 'picture',  'counter', 'desk', 'curtain', 'refrigerator', 'shower curtain', 'toilet', 'bathtub', #'sink', 'window',\n#                 'otherfurniture']\n\n# SEM_INS_MAP = {1:0, 2:1, 3:2, 4:3, 5:4, 6:5, 7:6, 8:7, 9:8, 10:9,\n#                11:10, 12:11, 14:12, 16:13, 24:14,   33:15, 36:16, 39:17, 22:18, 30:19}\n#\n# CLASS_LABELS = ['wall', 'floor', 'cabinet', 'bed', 'chair', 'sofa', 'table', 'door', 'window',\n#                 'bookshelf', 'picture',  'counter', 'desk', 'curtain', 'refrigerator',   'toilet', 'bathtub', #'sink', 'window',\n#                 'otherfurniture', 'ceiling', 'whiteboard']\n\nSEM_INS_MAP = {1:0, 2:1, 22:2} # 8:2,\n\nCLASS_LABELS = ['wall', 'floor','ceiling'] #'door',\n\nLAYOUT_SEM = {1, 2,22, 30, 3, 7, 12, 14, 36}\n# ============= winner take all assignment (deprecated) ===========================\ndef get_centers(voxel_coord, voxel_norm, semsegs, center_prob_in, surface_mask, center_thres, radius, norm_thres, topk=5000):\n    # center_prob = center_prob.clamp(0, 1)\n\n    # pick top k, to save memory\n    center_prob = center_prob_in.reshape([-1])\n    _, indices = torch.sort(center_prob[surface_mask.reshape([-1])], descending=True)\n    ori_indx = surface_mask.reshape([-1]).nonzero(as_tuple=False)\n    _idx = indices[:topk]\n    idx = ori_indx[_idx]\n    valid_mask = torch.zeros_like(center_prob).type(torch.bool)\n    valid_mask[idx] = (center_prob[idx] > center_thres)\n    valid_mask = valid_mask.view(center_prob_in.size())\n\n    if valid_mask.sum() == 0:\n        return [], [], []\n\n    # get all inliners\n    inlier_coord, inlier_norm= voxel_coord[:, valid_mask.reshape([-1])], voxel_norm[:, valid_mask].reshape([3,-1])\n    inlier_semseg, inlier_prob = semsegs[valid_mask].reshape([-1]), center_prob[valid_mask.reshape([-1])]\n\n    # sort prob\n    desc_prob, indices = torch.sort(inlier_prob, descending=True)\n    tmp_indices = indices.clone()\n    norm_ignore_mask =  (torch.sum(inlier_norm[:, indices], dim=0) == 0)\n    sem_ignore_mask = (inlier_semseg[indices] == 0)\n    centers = []\n    center_segm_lst = []\n    center_norm_lst = []\n    idx = 0\n    while idx < tmp_indices.shape[0]:\n        if tmp_indices[idx] != -1:\n            cur_center = inlier_coord[:, tmp_indices[idx]].reshape([3,1])\n            center_norm = inlier_norm[:, tmp_indices[idx]].reshape([3,1])\n            center_semseg = inlier_semseg[tmp_indices[idx]].reshape([1])\n\n\n            # group the surrounding ones if they share same semantic label and the normal dist. < cos(30),\n            sp_dist = torch.sum((inlier_coord[:, indices] - cur_center) ** 2, dim=0)\n\n            # if no valid norm, we ingore the norm dist constrain\n            if (torch.sum(center_norm.abs(), dim=0) == 0):\n                norm_mask = torch.ones_like(center_semseg).type(torch.bool)\n            else:\n                norm_mask = (torch.sum((inlier_norm[:, indices] * center_norm), dim=0).abs()> norm_thres) | norm_ignore_mask\n\n            # if no valid semseg, we ingore the semseg dist\n            if center_semseg == 0:\n                semseg_mask = torch.ones_like(center_semseg).type(torch.bool)\n            else:\n                semseg_mask = ((center_semseg == inlier_semseg[indices])  | sem_ignore_mask)\n\n            center_mask = (sp_dist < radius * radius) & semseg_mask  & norm_mask\n            tmp_indices[center_mask] = -1      # nms\n\n            # set the center as the weighted sum of the highest one's surrounding --- this will cause center fell outside\n            # of the semantic area, just pick the highest on\n            # new_center =((inlier_coord[:, indices[center_mask]] * inlier_prob[indices[center_mask]]).sum(dim=-1) / \\\n            #              (inlier_prob[indices[center_mask]]).sum(dim=-1)).round().type(torch.int)\n\n            # find the nearest voxel has semantic and normal\n            # new_center_norm = voxel_norm[:, new_center[0], new_center[1], new_center[2]]\n            # new_center_semg = semsegs[new_center[0], new_center[1], new_center[2]]\n            # dist = torch.sum((inlier_coord[:, indices] - new_center.unsqueeze(1)) ** 2, dim=0)\n            _, new_idx = torch.sort(sp_dist) #acedend\n            new_center = cur_center.clone()\n            new_center_norm = center_norm.clone()\n            new_center_semg = center_semseg.clone()\n            cnt = 0\n            while ((torch.sum(new_center_norm.abs(), dim=0) == 0) or (new_center_semg == 0)) and (cnt < new_idx.shape[0]):\n                cur_idx = new_idx[cnt]\n                new_center = inlier_coord[:, indices][:, cur_idx].type(torch.long).view(cur_center.shape)\n                new_center_norm = voxel_norm[:, new_center[0], new_center[1], new_center[2]].view(center_norm.shape)\n                new_center_semg = semsegs[new_center[0], new_center[1], new_center[2]].view(center_semseg.shape)\n                cnt+=1\n\n            # if the whole ball is in empty space\n            if ((torch.sum(new_center_norm.abs(), dim=0) == 0) or (new_center_semg == 0)):\n                continue\n            else:\n                centers.append(new_center)\n                center_segm_lst.append(new_center_semg)\n                center_norm_lst.append(new_center_norm)\n\n            # debug\n            # if idx == 0:\n            #     vert_viz = np.concatenate([vert, inlier_coord.T.numpy()], axis=0)\n            #     vert_color, voxel_color = np.zeros([vert.shape[0], 3]), np.ones([inlier_coord.shape[1], 3])*255\n            #     voxel_color[:,2] = 0\n            # voxel_color[indices.numpy()[center_mask.numpy()]] =  np.array([0,0,255])\n            # print(center_mask.sum(), new_center.round().type(torch.int))\n            # color_viz = np.concatenate([vert_color, voxel_color], axis=0).astype(np.int)\n            # pld = trimesh.points.PointCloud(vertices=vert_viz,  colors=color_viz, process=False)\n            # pld.show()\n\n        idx += 1\n\n    return centers, center_segm_lst, center_norm_lst\n\ndef get_planeIns(tsdf, cfg):\n\n    voxel_size =  tsdf.voxel_size\n    normals =   tsdf.attribute_vols['plane_norm']\n    semIns = tsdf.attribute_vols['semseg']\n    center_prob = tsdf.attribute_vols['centroid_prob']\n\n    mask_surface = tsdf.tsdf_vol.abs() < 1\n\n\n    radius =  GROUPING_RADIUS[int(voxel_size * 100)]\n    norm_thres =  np.cos(np.deg2rad(cfg.MODEL.GROUPING.NORM_THRES))\n    prob_thres =  cfg.MODEL.GROUPING.PROB_THRES\n    topk_prob = cfg.MODEL.GROUPING.TOPK_PROB\n\n    coords = coordinates(center_prob.shape,device=tsdf.device)\n    centers, center_segms, center_norms = get_centers( coords, normals, semIns, center_prob, mask_surface,\n                                                     prob_thres, radius,norm_thres, topk_prob)\n\n    normals, semIns = normals.reshape([3, -1]), semIns.reshape([-1])\n    planeIns = torch.zeros_like(semIns)\n\n    for i, (center_coord, center_seg, center_norm) in enumerate(zip(centers, center_segms, center_norms)):\n        # semantic should be same\n        semseg_mask = (semIns == center_seg)\n\n        # normal should be similiar\n        norm_mask = (torch.sum((normals * center_norm), dim=0).abs() > norm_thres)\n\n        # distance to the plane should under threshold\n        planeD = (center_norm * center_coord).sum()\n        cluster_plane_dist = ((center_norm * coords).sum(dim=0) - planeD).abs()\n        spatial_mask = cluster_plane_dist <= radius\n\n        # only assign once with highest prob center\n        # note we do not prevent a center to be assigned to another center with higher prob, so planeIns.max()\n        # is not equal to the plane_num\n        available_mask = planeIns == 0\n\n        # assign plane instance to the picked voxels\n        cluster_mask = semseg_mask & norm_mask & spatial_mask & available_mask\n\n        # some center may do not have ins because of the limited number of inliner\n        if cluster_mask.sum() > PLANE_MIN_N_VOXELS[int(voxel_size * 100)]:\n            planeIns[cluster_mask] = (i + 1)\n            normals[:, cluster_mask] = center_norm\n        # print(cluster_mask.sum())\n\n    return planeIns, normals,  centers, center_segms, center_norms\n\n# ============= RANSAC based assignment =====================\ndef check_connection_bfs(mask, seed_idx, vol_shape):\n    # bfs to build connection mask --- deprecated too slow !!!\n    # vol_shape: h, w, d, where h w in 2D, d is the height dim\n    h, w, d = vol_shape\n    vol_mask = mask.view(vol_shape)\n\n    # set the seed\n    candidate_mask = torch.zeros_like(mask).bool()\n    candidate_mask[seed_idx] = True\n    candidate_mask = candidate_mask.view(vol_shape)\n    idx = (candidate_mask == True).nonzero(as_tuple=False).squeeze().cpu().numpy() #shape (1,3), x y z\n\n    # 6 direction search\n    x, y, z = idx[0], idx[1], idx[2]\n    queue = deque([(x, y, z)])\n    while len(queue) > 0:\n        cur_x, cur_y, cur_z = queue.popleft()\n        sys.stdout.write('\\r connection: {}/{}'.format(candidate_mask.sum(), mask.sum()))\n        sys.stdout.flush()\n\n        if cur_x - 1 >= 0 and vol_mask[cur_x-1, cur_y, cur_z] == True and candidate_mask[cur_x-1, cur_y, cur_z] == False:\n            candidate_mask[cur_x-1, cur_y, cur_z] = True\n            queue.append((cur_x-1, cur_y, cur_z))\n\n        if cur_x + 1 < h and vol_mask[cur_x +1, cur_y, cur_z] == True and candidate_mask[cur_x+1, cur_y, cur_z] == False:\n            candidate_mask[cur_x+1, cur_y, cur_z] = True\n            queue.append((cur_x +1, cur_y, cur_z))\n\n        if cur_y - 1 >= 0 and vol_mask[cur_x, cur_y - 1, cur_z] == True and candidate_mask[cur_x, cur_y-1, cur_z] == False:\n            candidate_mask[cur_x , cur_y -1, cur_z] = True\n            queue.append((cur_x, cur_y - 1, cur_z))\n\n        if cur_y + 1 < h and vol_mask[cur_x, cur_y + 1, cur_z] == True and candidate_mask[cur_x, cur_y+1, cur_z] == False:\n            candidate_mask[cur_x, cur_y + 1, cur_z] = True\n            queue.append((cur_x, cur_y + 1, cur_z))\n\n        if cur_z - 1 >= 0 and vol_mask[cur_x, cur_y, cur_z - 1] == True and candidate_mask[cur_x, cur_y, cur_z-1] == False:\n            candidate_mask[cur_x, cur_y, cur_z - 1] = True\n            queue.append((cur_x, cur_y, cur_z - 1))\n\n        if cur_z + 1 < h and vol_mask[cur_x, cur_y, cur_z + 1] == True and candidate_mask[cur_x, cur_y, cur_z+1] == False:\n            candidate_mask[cur_x , cur_y, cur_z + 1] = True\n            queue.append((cur_x, cur_y, cur_z + 1))\n\n    return candidate_mask.view(-1)\n\ndef check_connection(mask, seed_idx, vol_shape):\n    # use make pooling to keep update until it reach\n    vol_mask = mask.view(vol_shape).unsqueeze(0).unsqueeze(0)\n\n    # set the seed\n    candidate_mask = torch.zeros_like(mask).bool()\n    candidate_mask[seed_idx] = True\n    candidate_mask = candidate_mask.view(vol_shape).unsqueeze(0).unsqueeze(0)\n\n    memo_mat = candidate_mask.clone()\n    pre_mask = candidate_mask.clone()\n\n    # use 3D max pooling to propgate seed\n    for cnt in range(max(vol_shape)): # longest dist to flood fill equals to the largest dim\n        candidate_mask = F.max_pool3d(candidate_mask.float(), kernel_size=3, stride=1, padding=1).bool() & vol_mask\n        memo_mat = F.max_pool3d(memo_mat.float(), kernel_size=3, stride=1, padding=1)\n        if memo_mat.sum() >= vol_shape[0] * vol_shape[1] * vol_shape[2] or (candidate_mask == vol_mask).all()\\\n                or (pre_mask == candidate_mask).all():\n            break\n        pre_mask = candidate_mask.clone()\n        # sys.stdout.write('\\rflood fill step: {}'.format(cnt))\n        # sys.stdout.flush()\n    return candidate_mask.view(-1)\n\n\ndef seq_ransac(coords, normals, semLab, prob, planeIns, valid_mask, mask_surface,\n               norm_thres, radius, area_thres, cur_planeID,  vol_shape, n_iter=100):\n    # sequential one-point plane ransac, the principle is the same as onePoint_ransan in fit_plane/util,\n    # but the code is slightly different  because we do not have the instance level label,\n    # so we need consider semantic label consistency here\n\n    # sample the seeds w.r.t. their prob\n    prob[~valid_mask] = 0\n\n    # in case replacement == False, and n_iter > (prob > 0).sum(), it will return idx whose weight == 0\n    # therefore, we should make sure the n_iter is always < (prob>0).sum()\n    idxs = torch.multinomial(prob, min(n_iter, (prob > 0).sum()), replacement=False)\n\n    resume = False\n    n_inliers = 0\n    cnt = 0\n    best_mask = torch.zeros_like(semLab).type(torch.bool)\n    for i in idxs:\n        cnt += 1\n        sample_pnt = coords[:, i].unsqueeze(1)\n        sample_norm = normals[:, i].unsqueeze(1)\n        sample_semg = semLab[i]\n\n        sys.stdout.write('\\rprocessing: {}, assigning plane: {}, iter {}'.format(sample_semg.item(), cur_planeID, cnt))\n        sys.stdout.flush()\n\n        # semantic should be same\n        semseg_mask = (semLab == sample_semg)\n\n        # normal should be similiar\n        norm_mask = (torch.sum((normals * sample_norm), dim=0).abs() > norm_thres)\n\n        # distance to the plane should under threshold\n        planeD = (sample_norm * sample_pnt).sum()\n        cluster_plane_dist = ((sample_norm * coords).sum(dim=0) - planeD).abs()\n        spatial_mask = cluster_plane_dist <= radius\n\n        # only sign once\n        available_mask = planeIns == 0\n\n        # connection mask -- only if the voxel have path connected to the sample pnt can be assigned\n        cluster_mask = semseg_mask & norm_mask & spatial_mask & available_mask & mask_surface\n\n\n        # put all the masks together --- Ideally we should put connection mask here, but it is too slow, we do it in post process instead\n        # cluster_mask = cluster_mask & connection_mask\n\n        n =  cluster_mask.sum()\n        if n > n_inliers:\n            best_mask = cluster_mask.clone()\n            n_inliers = n\n            center_idx, center_coord, center_semseg, center_norm = i, sample_pnt, sample_semg, sample_norm\n\n    # best_mask = best_mask | (planeIns == cur_planeID) # for NN case\n    # ransac will stop if the best plane_area < area_thres\n    if n_inliers >= area_thres:\n        # break the mask if contain 2 seperate part\n        connection_mask = check_connection(best_mask, center_idx, vol_shape)\n        best_mask = connection_mask & best_mask\n\n        # only update label if the area is sufficent large\n        if best_mask.sum() < area_thres:\n            return planeIns, valid_mask, resume, normals, sample_pnt, sample_semg, sample_norm\n        # ======= debug========\n        # voxels = coords[:, mask_surface].T.cpu().numpy()\n        # voxel_color = np.zeros([voxels.shape[0], 3])\n        # voxel_color[best_mask.cpu().numpy()[mask_surface.cpu().numpy()]] =  np.array([0,0,255])\n        #\n        # pld = trimesh.points.PointCloud(vertices=voxels, colors=voxel_color, process=False)\n        # pld.show()\n        #\n        # best_mask = connection_mask & best_mask\n        # voxel_color[best_mask[mask_surface].cpu().numpy()] = np.array([255, 0, 0])\n        # pld = trimesh.points.PointCloud(vertices=voxels, colors=voxel_color, process=False)\n        # pld.show()\n\n        # -------- connect\n        # if sample_semg ==3:\n        #     pld = trimesh.points.PointCloud(vertices=voxels, colors=voxel_color, process=False)\n        #     pld.show()\n\n            # vol_mask = best_mask.view(vol_shape).unsqueeze(0).unsqueeze(0)\n            #\n            # # set the seed\n            # candidate_mask = torch.zeros_like(best_mask).bool()\n            # candidate_mask[center_idx] = True\n            # candidate_mask = candidate_mask.view(vol_shape).unsqueeze(0).unsqueeze(0)\n            #\n            # memo_mat = candidate_mask.clone()\n            # pre_mask = candidate_mask.clone()\n            # # use 3D max pooling to propgate seed\n            # for cnt in range(max(vol_shape)):  # longest dist to flood fill equals to the largest dim\n            #     candidate_mask = F.max_pool3d(candidate_mask.float(), kernel_size=3, stride=1, padding=1).bool() & vol_mask\n            #\n            #     connection_mask = candidate_mask.view(-1)\n            #     voxel_color[connection_mask[mask_surface].cpu().numpy()] = np.array([255, 0, 0])\n            #     pld = trimesh.points.PointCloud(vertices=voxels, colors=voxel_color, process=False)\n            #     pld.show()\n            #\n            #     memo_mat = F.max_pool3d(memo_mat.float(), kernel_size=3, stride=1, padding=1)\n            #     if memo_mat.sum() >= vol_shape[0] * vol_shape[1] * vol_shape[2] or (candidate_mask == vol_mask).all():\n            #         break\n\n        planeIns[best_mask] = cur_planeID\n        valid_mask[best_mask] = False # seed will only be assigned once as well\n        resume = True\n\n        # get weird result -- perform least square fit in the ininlier -- we should not change normal, because the voxel norm if from tsdf_grad\n        # it can be very different in the boundary\n\n        mean_center = torch.mean(coords[:,best_mask].float(), dim=1, keepdim=True)\n        dist = torch.sum((coords[:, best_mask].float() - mean_center).abs(), dim=0) # use l1 dist find nearest inliers to mean_center\n        new_idx = dist.argmin(dim=0)  # acedend\n        center_coord = coords[:,best_mask][:, new_idx].unsqueeze(1)\n        normals[:, best_mask] = center_norm\n    else:\n        center_coord, center_semseg, center_norm = sample_pnt, sample_semg, sample_norm # just return sth, will not be used\n\n    return planeIns, valid_mask, resume, normals,  center_coord, center_semseg, center_norm\n\ndef get_planeIns_RANSAC(tsdf, cfg):\n    # init necessary variables\n    voxel_size =  tsdf.voxel_size\n    normals =   tsdf.attribute_vols['plane_norm']\n    semLab = tsdf.attribute_vols['semseg']\n    center_prob = tsdf.attribute_vols['centroid_prob']\n\n    radius =  GROUPING_RADIUS[int(voxel_size * 100)]\n    norm_thres =  np.cos(np.deg2rad(cfg.MODEL.GROUPING.NORM_THRES))\n    prob_thres =  cfg.MODEL.GROUPING.PROB_THRES\n    area_thres =  PLANE_MIN_N_VOXELS[int(voxel_size * 100)]\n\n    coords = coordinates(center_prob.shape,device=tsdf.device)\n\n    normals, semLab = normals.reshape([3, -1]), semLab.reshape([-1])\n    planeIns = torch.zeros_like(semLab)\n\n    # pick valid center\n    mask_surface = tsdf.tsdf_vol.abs() < 1\n    center_prob_flat = center_prob.clone().reshape([-1])\n    seed_mask = (center_prob_flat > prob_thres) & mask_surface.reshape([-1])\n\n    # _, indices = torch.sort(center_prob_flat[seed_mask], descending=True)\n    # ori_indx = seed_mask.nonzero(as_tuple=False)\n    # idx_in_ori_idx = ori_indx[indices] # convert the valid set idx to the whole set idx\n\n    if seed_mask.sum() == 0:\n        return planeIns, normals, [], [], []\n\n    # start sequential RANSAC for each pred_semantic label\n    cur_planeId = 1\n    centers, center_segms, center_norms = [], [], []\n    for semid in torch.unique(semLab):\n        if semid <= 0: continue # ignore invalid semantic label\n        resume_ransac = True\n        tmp_valid_mask = seed_mask & (semLab == semid)\n        # if semid == 22:\n        #     print(123)\n        # Start seq_Ransac,\n        while resume_ransac:\n            if tmp_valid_mask.sum() == 0: #quit if no seeds exist\n                resume_ransac = False\n            else:\n                planeIns, tmp_valid_mask, resume_ransac,  normals, center_coord, center_semseg, center_norm  =\\\n                    seq_ransac(coords, normals, semLab, center_prob_flat.clone(), planeIns, tmp_valid_mask , mask_surface.reshape([-1]),\n                           norm_thres, radius,  area_thres, cur_planeId, vol_shape=center_prob.squeeze().shape, n_iter=500)\n\n                if resume_ransac:\n                    cur_planeId += 1\n                    centers.append(center_coord)\n                    center_segms.append(center_semseg)\n                    center_norms.append(center_norm)\n\n\n    return planeIns, normals,  centers, center_segms, center_norms\n\n\n# ============== NN association ===========\n\ndef seq_ransac_NN(coords, normals, semLab, planeIns, valid_mask, mask_surface,\n               norm_thres, radius, area_thres, cur_planeID,  vol_shape, n_iter=100):\n    # sequential one-point plane ransac, the principle is the same as onePoint_ransan in fit_plane/util,\n    # but the code is slightly different  because we do not have the instance level label,\n    # so we need consider semantic label consistency here\n\n    # sample the seeds w.r.t. their prob\n    prob = valid_mask.float().clone()\n\n    # in case replacement == False, and n_iter > (prob > 0).sum(), it will return idx whose weight == 0\n    # therefore, we should make sure the n_iter is always < (prob>0).sum()\n    idxs = torch.multinomial(prob, min(n_iter, (prob > 0).sum()), replacement=False)\n\n    resume = False\n    n_inliers = 0\n    cnt_iter = 0\n    best_mask = torch.zeros_like(semLab).type(torch.bool)\n    # ransac iter\n    for i in idxs:\n        cnt_iter += 1\n        sample_pnt = coords[:, i].unsqueeze(1)\n        sample_norm = normals[:, i].unsqueeze(1)\n        sample_semg = semLab[i]\n\n        sys.stdout.write('\\rprocessing: {}, assigning plane: {}, iter {}'.format(sample_semg.item(), cur_planeID, cnt_iter))\n        sys.stdout.flush()\n\n        # semantic should be same\n        semseg_mask = (semLab == sample_semg)\n\n        # normal should be similiar\n        norm_mask = (torch.sum((normals * sample_norm), dim=0).abs() > norm_thres)\n\n        # distance to the plane should under threshold\n        planeD = (sample_norm * sample_pnt).sum()\n        cluster_plane_dist = ((sample_norm * coords).sum(dim=0) - planeD).abs()\n        spatial_mask = cluster_plane_dist <= radius\n\n        # only sign once\n        available_mask = (planeIns == 0) #| cur_planeID\n\n        # connection mask -- only if the voxel have path connected to the sample pnt can be assigned\n        cluster_mask = semseg_mask & norm_mask & spatial_mask & available_mask & mask_surface\n\n\n        # put all the masks together --- Ideally we should put connection mask here, but it is too slow, we do it in post process instead\n        # cluster_mask = cluster_mask & connection_mask\n\n        n =  cluster_mask.sum()\n        if n > n_inliers:\n            best_mask = cluster_mask.clone()\n            n_inliers = n\n            center_idx, center_coord, center_semseg, center_norm = i, sample_pnt, sample_semg, sample_norm\n\n    # best_mask = best_mask | (planeIns == cur_planeID) # for NN case\n    # ransac will stop if the best plane_area < area_thres\n    if n_inliers >= area_thres:\n        print(\"{} assinged\".format(cur_planeID))\n        # break the mask if contain 2 seperate part\n        connection_mask = check_connection(best_mask | valid_mask, center_idx, vol_shape)\n        final_best_mask = connection_mask & best_mask\n\n        # only update label if the area is sufficent large\n        if final_best_mask.sum() < area_thres:\n            return planeIns, valid_mask, resume, normals, sample_pnt, sample_semg, sample_norm, final_best_mask\n        # ======= debug========\n        # voxels = coords[:, mask_surface].T.cpu().numpy()\n        # voxel_color = np.zeros([voxels.shape[0], 3])\n        # voxel_color[best_mask.cpu().numpy()[mask_surface.cpu().numpy()]] =  np.array([0,0,255])\n        #\n        # pld = trimesh.points.PointCloud(vertices=voxels, colors=voxel_color, process=False)\n        # pld.show()\n        #\n        # best_mask = connection_mask & best_mask\n        # voxel_color[best_mask[mask_surface].cpu().numpy()] = np.array([255, 0, 0])\n        # pld = trimesh.points.PointCloud(vertices=voxels, colors=voxel_color, process=False)\n        # pld.show()\n\n\n        planeIns[final_best_mask] = cur_planeID\n        # planeIns[torch.logical_xor(final_best_mask, best_mask)] = 0 # the discard note connected (if itone set to be 0\n        # valid_mask[final_best_mask] = True # add new added area for\n        resume = True\n\n        # get weird result -- perform least square fit in the ininlier -- we should not change normal, because the voxel norm if from tsdf_grad\n        # it can be very different in the boundary\n        mean_center = torch.mean(coords[:,best_mask].float(), dim=1, keepdim=True)\n        dist = torch.sum((coords[:, best_mask].float() - mean_center).abs(), dim=0) # use l1 dist find nearest inliers to mean_center\n        new_idx = dist.argmin(dim=0)  # acedend\n        center_coord = coords[:,best_mask][:, new_idx].unsqueeze(1)\n        normals[:, final_best_mask] = center_norm\n    else:\n        print(\"{} is too small, iliner {} not assinged\".format(cur_planeID, n_inliers))\n        center_coord, center_semseg, center_norm, final_best_mask = sample_pnt, sample_semg, sample_norm, best_mask # just return sth, will not be used\n\n    return planeIns, valid_mask, resume, normals,  center_coord, center_semseg, center_norm, final_best_mask\n\n\ndef FloodFill(mask, normals, semLab, norm_thres, seed_idx, vol_shape):\n\n    # set the seed\n    candidate_mask = torch.zeros_like(mask).bool()\n    candidate_mask[seed_idx] = True\n    ctr_semg = semLab[seed_idx]\n    # ctr_norm = normals[:, seed_idx]\n\n    if ctr_semg in NONE_PLANE_ID:\n        return candidate_mask.view(-1)\n\n    candidate_mask = candidate_mask.view(vol_shape).unsqueeze(0).unsqueeze(0)\n\n    pre_mask = candidate_mask.clone()\n\n    # use 3D max pooling to propgate seed\n    for cnt in range(max(vol_shape)): # longest dist to flood fill equals to the largest dim\n        candidate_mask = F.max_pool3d(candidate_mask.float(), kernel_size=3, stride=1, padding=1).bool()\n\n        # semantic should be same\n        semseg_mask = (semLab == ctr_semg)\n        # normal should be similiar\n        # norm_mask = (torch.sum((normals * ctr_norm), dim=0).abs() > ORTHOGONAL_THRES) # same as gt generate\n        # distance to the plane should under threshold -- emperical no difference\n\n        candidate_mask = (candidate_mask.view(-1) & semseg_mask &  mask).view(vol_shape).unsqueeze(0).unsqueeze(0)\n\n        if  (pre_mask == candidate_mask).all():\n            break\n\n        # new_mask = torch.logical_xor(pre_mask, candidate_mask) # the filled region in this iter\n        pre_mask = candidate_mask.clone()\n\n        # sys.stdout.write('\\rflood fill step: {}'.format(cnt))\n        # sys.stdout.flush()\n    return candidate_mask.view(-1)\n\n\ndef get_center_FloodFill(coords, normals, semLab, seed_mask, norm_thres, idx_in_ori_idx, vol_shape):\n    # center_prob is in vol_shape\n    vaild_mask = seed_mask.clone()\n    centers, center_segm_lst, center_norm_lst, center_ids, center_mask = [], [], [], [], []\n\n    for id in idx_in_ori_idx:\n        if vaild_mask[id]:\n            cur_seed_mask = FloodFill(seed_mask, normals, semLab, norm_thres, id, vol_shape)\n            if cur_seed_mask.sum() <= 4: continue # a instance center should have at least other 3 support\n\n            mean_center = torch.mean(coords[:, cur_seed_mask].float(), dim=1, keepdim=True)\n            dist = torch.sum((coords[:, cur_seed_mask].float() - mean_center).abs(), dim=0)\n\n            new_idx = dist.argmin(dim=0)  # acedend\n\n            # this normal update lead to wrong normal sometimes , but on average it leads to a bette results\n            norm = normals[:, cur_seed_mask]\n            if norm.shape[1] > 10000:   # to control the memory usage\n                mask =  torch.randperm(norm.shape[1])[:10000]\n                norm = norm[:, mask]\n            u, s, v = torch.svd((norm.T))\n            new_normal = v[:, 0].unsqueeze(1)\n            seed_norm = normals[:, cur_seed_mask][:, new_idx].unsqueeze(1)\n            new_normal = -new_normal if (new_normal*seed_norm).sum() < 0 else new_normal\n\n            # we cannot use least square, some slice mask will turn to change their normal direction\n            # new_normal, _ = torch.lstsq(torch.ones_like(coords[:1, cur_seed_mask]).float().T, coords[:, cur_seed_mask].float().T)\n            # new_normal = new_normal[:coords.shape[0]]/new_normal[:coords.shape[0]].norm()\n\n            centers.append(coords[:, cur_seed_mask][:, new_idx].unsqueeze(1))\n            center_norm_lst.append(new_normal)\n            # center_norm_lst.append(normals[:, cur_seed_mask][:, new_idx].unsqueeze(1))\n            center_segm_lst.append(semLab[cur_seed_mask][new_idx])\n            center_ids.append(id)\n            center_mask.append(cur_seed_mask)\n\n            vaild_mask[cur_seed_mask] = False\n\n    return centers, center_norm_lst, center_segm_lst, center_ids, center_mask\n\n\ndef get_planeIns_NN(tsdf, cfg, ransac=False):\n    # flood fill\n    voxel_size = tsdf.voxel_size\n    normals = tsdf.attribute_vols['plane_norm']\n    semLab = tsdf.attribute_vols['semseg']\n    plane_cls = tsdf.attribute_vols['plane_cls']\n    center_prob = tsdf.attribute_vols['centroid_prob']\n\n    radius = GROUPING_RADIUS[int(voxel_size * 100)]\n    norm_thres = np.cos(np.deg2rad(cfg.MODEL.GROUPING.NORM_THRES))\n    prob_thres = cfg.MODEL.GROUPING.PROB_THRES\n    area_thres = PLANE_MIN_N_VOXELS[int(voxel_size * 100)]\n\n    coords = coordinates(center_prob.shape, device=tsdf.device).type(torch.int16)\n\n    normals, semLab, plane_cls = normals.reshape([3, -1]).type(torch.float), semLab.reshape([-1]), plane_cls.reshape([4, -1])#.type(coords.dtype)\n    planeIns = torch.zeros_like(semLab).type(torch.int16)\n\n    # pick valid center\n    mask_surface = (tsdf.tsdf_vol.abs() < 1).reshape([-1]) & (plane_cls[0] > 0.5) #must be plane to be considered\n    center_prob_flat = center_prob.clone().reshape([-1])\n    seed_mask = (center_prob_flat > prob_thres) & mask_surface\n\n    center_pred = (coords + plane_cls[1:].round().type(coords.dtype))\n\n    if seed_mask.sum() == 0:\n        return planeIns, normals, [], [], []\n\n    # collect potential cluster center idx\n    _, indices = torch.sort(center_prob_flat[seed_mask], descending=True)\n    ori_indx = seed_mask.nonzero(as_tuple=False)\n    idx_in_ori_idx = ori_indx[indices] # convert the valid set idx to the whole set idx\n\n    # get center list\n    centers, center_norms, center_segms, center_ids, center_masks = \\\n        get_center_FloodFill(coords, normals, semLab, seed_mask, norm_thres,  idx_in_ori_idx, center_prob.shape)\n\n    n_ins = len(centers)\n    # planeIns_distance = torch.ones([semLab.shape[0], n_ins], dtype=torch.int16).to(semLab.device).cpu() * 10000 #no gpu memory if use int64, if the center is hugh amount like scene 500_00 still not enough\n\n\n    for i, (ctr_pnt, ctr_norm, ctr_semg, ctr_id, ctr_mask) in enumerate(zip(centers, center_norms, center_segms, center_ids, center_masks)):\n        # semantic should be same\n        cluster_mask = (semLab == ctr_semg) & mask_surface\n\n        # normal should be similiar\n        norm_mask = ((normals[:, cluster_mask] * ctr_norm).sum().abs() > norm_thres)\n        cluster_mask[cluster_mask] &= norm_mask\n\n        # distance to the plane should under threshold\n        # planeD = (ctr_norm * ctr_pnt).sum()\n        # cluster_plane_dist = ((coords * ctr_norm).sum(0) - planeD).abs()\n        # spatial_mask = (cluster_plane_dist <= radius)\n        # cluster_mask &= spatial_mask\n\n       # the predicted center of the current candidates voxel is within the center support mask\n        # https://stackoverflow.com/questions/41234161/check-common-elements-of-two-2d-numpy-arrays-either-row-or-column-wise\n        cur_center_pred = center_pred[:, cluster_mask].T\n        ctr_support_area = coords[:, ctr_mask].T\n        # print(cur_center_pred.shape, ctr_support_area.shape, prob_thres)\n        b_voted = (cur_center_pred[:, None] == ctr_support_area).all(-1).any(-1)\n        cluster_mask[cluster_mask] &= b_voted\n\n        # cluster_mask = check_connection(cluster_mask, ctr_id, center_prob.shape)\n        planeIns[cluster_mask] = i +1\n\n        # should associate to the cloest center instead of plane to preserve every instance\n        # planeIns_distance[cluster_mask, i] =(coords[:,cluster_mask] - ctr_pnt).abs().sum(dim=0).type(torch.int16).cpu() # cluster_plane_dist[cluster_mask].type(torch.int16) #\n\n    # discard very small instance\n    if ransac:\n        additional_id = 2\n        for x in range(n_ins+1):\n            cur_planeId = x + 1\n\n            # merge unassigned voxels to exising instance first, and then generate plane in other unassigned region\n            potentail_area_mask = (planeIns == cur_planeId) if x<n_ins else ((planeIns == 0) & mask_surface)  #center_mask[x] & (planeIns == 0)\n            # print(n_ins)\n            for semid in torch.unique(semLab[potentail_area_mask]): # for the planeIns case\n                if semid.item() in NONE_PLANE_ID:continue\n                resume_ransac = True\n                tmp_valid_mask = potentail_area_mask & (semLab == semid)\n                while resume_ransac:\n                    if tmp_valid_mask.sum() == 0:  # quit if no seeds exist\n                        resume_ransac = False\n                    else:\n\n\n                        planeIns, tmp_valid_mask, resume_ransac, normals, center_coord, center_semseg, center_norm, new_add_mask = \\\n                                seq_ransac_NN(coords, normals, semLab,  planeIns, tmp_valid_mask,\n                                           mask_surface,\n                                           norm_thres, radius, area_thres, cur_planeId, vol_shape=center_prob.squeeze().shape,\n                                           n_iter=500)\n                        # -------- debug -----------------\n                        # if x == n_ins :\n                        #     voxel_color[tmp_valid_mask[mask_surface.reshape([-1])].cpu().numpy()] = np.array([255, 0, 0])\n                        #     voxel_color[new_add_mask[mask_surface.reshape([-1])].cpu().numpy()] = np.array([0, 255, 0])\n                        #     print(resume_ransac)\n                        #     pld = trimesh.points.PointCloud(vertices=voxels, colors=voxel_color, process=False)\n                        #     pld.show()\n\n                        # offer more id for the unassigned region\n                        if cur_planeId >= n_ins + 1:\n                            if resume_ransac:\n                                centers.append(center_coord)\n                                center_norms.append(center_norm)\n                                center_segms.append(center_semseg)\n                                tmp_valid_mask ^= new_add_mask\n\n                            cur_planeId = n_ins + additional_id\n                            additional_id += 1\n                        else:\n                            # enlarge merging seed\n                            tmp_valid_mask |= new_add_mask\n\n\n\n    for cur_planeId in torch.unique(planeIns):\n        planeIns[planeIns == cur_planeId] = torch.where(planeIns[planeIns == cur_planeId].sum() < area_thres,\n                                                        torch.zeros_like(planeIns[planeIns == cur_planeId]),\n                                                        planeIns[planeIns == cur_planeId])\n\n\n    return planeIns, normals, centers, center_segms, center_norms\n\ndef expl(val, ord=8, verbose = False):\n    # approx the exp to speed up the process, as this part is done on cpu\n    # idea from  https://codingforspeed.com/using-faster-exponential-approximation/\n    # there is another brillant idea, but torch doest not support bit move >> or <<\n    #  w.r.t. http://perso.citi-lab.fr/fdedinec/recherche/publis/2005-FPT.pdf\n    x = 1. + val / (2**ord)\n    for _ in range(ord):\n        x *= x\n        if verbose:\n            print(x)\n    return  x\n\ndef get_heatmap( planeIns_vol, voxel_size, tsdf_vol_sz):\n    ## we expect flatten planeIns here\n    # todo: This will limited only 1 batch in one GPU, change this to enable multiple batch\n    coords_voxel = coordinates(tsdf_vol_sz[1:], device=planeIns_vol.device)\n    centroid_vol = torch.zeros(planeIns_vol.view(-1).shape, device=planeIns_vol.device)\n\n    # ====== build centroid heatmap =====\n    unique_id = torch.unique(planeIns_vol)\n    # centers = torch.zeros([3, len(unique_id)-1]).type(torch.long)\n    for k, id in enumerate(unique_id):\n        if id <= 0: continue  # none plane\n        heatmap_mask = (planeIns_vol == id)  # ensure only update once\n        cur_plane_voxels = coords_voxel[:, heatmap_mask]\n        # cur_plane_norm = normal_vol[planeIns_vol == id, :]\n        cur_center = torch.mean((cur_plane_voxels).type(torch.float), 1, keepdims=True)\n\n        # if we use the mean center directly, it can fall into some empty voxel, then we cannot use its normal and depth\n        # to generate plane proposal, therefore, we have to pick the one near to it and have the same plane normal\n        dist = torch.sum((cur_plane_voxels - cur_center).abs(), dim=0)\n        new_idx = torch.argmin(dist)\n        new_center = cur_plane_voxels[:, new_idx].type(torch.long)\n\n        dist = torch.sum((coords_voxel - new_center.unsqueeze(1).type(torch.float)) ** 2, dim=0)\n\n        # plane ins id start from 1\n        # only voxel belong to the instance can be update.\n        # For a voxel does not have instance id, it normal will be different from plane norm, and so cannot be used to\n        # propose the plane in the groupping stage\n\n        std = (heatmap_mask.sum() * ADOPT_THRES + STD[voxel_size]) / 3\n        # Gaussian_prob = torch.exp(-(dist / (2 * std))) / (torch.sqrt(std) * torch.sqrt(2 * PI))\n        Gaussian_prob = expl(-(dist / (2 * std)).clamp(0, 500)) / ( torch.sqrt(std) * SQRT_2PI)  # clamp the dist for numerical stable\n        Gaussian_prob[~heatmap_mask] = 0\n        # change one of the max value to ensure only one center after approx\n        max_val = Gaussian_prob.max()\n        top_mask = (Gaussian_prob == max_val)\n\n        if top_mask.sum() > 1:\n            idx = top_mask.nonzero(as_tuple=False)\n            Gaussian_prob[idx[0]] += 1e-4\n        assert (Gaussian_prob == Gaussian_prob.max()).sum() == 1, \"only one center for one instance\"\n        Gaussian_prob /= max_val  # normalize\n\n        # only update the voxels have the same plane ins or those not belong to any plane once\n        centroid_vol += Gaussian_prob\n    return  centroid_vol.view(tsdf_vol_sz)\n\n\n\ndef coordinates(voxel_dim, device=torch.device('cuda'), b_flat=True):\n    \"\"\" 3d meshgrid of given size.\n\n    Args:\n        voxel_dim: tuple of 3 ints (nx,ny,nz) specifying the size of the volume\n\n    Returns:\n        torch long tensor of size (3,nx*ny*nz)\n    \"\"\"\n\n    nx, ny, nz = voxel_dim\n    x = torch.arange(nx, dtype=torch.long, device=device)\n    y = torch.arange(ny, dtype=torch.long, device=device)\n    z = torch.arange(nz, dtype=torch.long, device=device)\n    x, y, z = torch.meshgrid(x, y, z)\n    if b_flat:\n        return torch.stack((x.flatten(), y.flatten(), z.flatten()))\n    else:\n        return torch.stack((x, y, z))\n\ndef find_closet(src_arr, tgt_arr):\n    # given 1D tgt_arr find closet val idx in src_arr\n    # https://stackoverflow.com/questions/20780017/vectorize-finding-closest-value-in-an-array-for-each-element-in-another-array\n    idx1 = torch.searchsorted(src_arr, tgt_arr).clamp(0, len(src_arr) -1)\n    idx2 = (idx1 - 1).clamp(0, len(src_arr) - 1)\n\n    diff1 = src_arr[idx1] - tgt_arr\n    diff2 = tgt_arr - src_arr[idx2]\n\n    final_idx = torch.where(diff1 <= diff2, idx1, idx2)\n    return final_idx\n\ndef Eud2sphere(norm, d, rhos, thetas, phis):\n    _rhos = d #param[3:, :]\n    rhoIdxs = find_closet(rhos, _rhos)\n\n    _thetas = torch.acos(norm[2]) #np.arccos(param[2:3, :])\n    thetaIdxs = find_closet(thetas, _thetas)\n\n    _phis = torch.acos(norm[0] / torch.sin(_thetas))\n    phiIdxs = find_closet(phis, _phis)\n\n    # ensure theta==0 only bring one activation\n    if thetaIdxs == 0:\n        phiIdxs = 0\n\n    return rhoIdxs, thetaIdxs, phiIdxs\n\ndef sphere2norm(theta, phi):\n    p_norm = torch.tensor([np.sin(theta) * np.cos(phi),\n                         np.sin(theta) * np.sin(phi),\n                         np.cos(theta)])\n    return p_norm / p_norm.norm()\n# ========================\n# from vPlaneRecover.tsdf import SEM_INS_MAP\n\ndef get_planeInsVert_frmHT(tsdf, voxel_sz, origin, semLab_in, param_htmap_in, vote_idx,  rhos, thetas, phis, cfg):\n\n    tsdf_vol = -tsdf.squeeze()\n\n    # don't close surfaces using unknown-empty boundry\n    tsdf_vol[tsdf_vol == -1] = 1\n\n    tsdf_vol = tsdf_vol.clamp(-1, 1).cpu().numpy()\n\n    semLab = semLab_in.squeeze()\n    param_htmap = param_htmap_in.squeeze()\n\n    verts_mc, faces, _, _ = measure.marching_cubes(tsdf_vol, level=0)\n    verts_ind = np.round(verts_mc).astype(int)\n    n_verts = verts_mc.shape[0]\n\n    # in sone weird case ind will exceede the range\n    d, h, w = semLab.shape\n    if np.any(verts_ind[:, 0] > d - 1) or np.any(verts_ind[:, 1] > h - 1) or np.any(verts_ind[:, 2] > w - 1) or \\\n            np.any(verts_ind[:, 0] < 0) or np.any(verts_ind[:, 1] < 0) or np.any(verts_ind[:, 2] < 0):\n        return trimesh.Trimesh(vertices=np.zeros((1, 3)))\n\n    verts = verts_mc * voxel_sz + origin.cpu().numpy() # n*3\n    verts_ind = np.round(verts_mc).astype(int)\n    tmp_mesh = trimesh.Trimesh(vertices=verts, faces=faces, process=False)\n    verts_norm = torch.from_numpy(tmp_mesh.vertex_normals).float().to(semLab.device) # n*3\n\n    semseg_vol = semLab_in.detach().cpu().numpy()\n    semseg_verts = semseg_vol[verts_ind[:, 0], verts_ind[:, 1], verts_ind[:, 2]]\n\n    voxel_coord_np = coordinates(semLab.shape, torch.device('cpu'), False).float().numpy() #semLab.device\n    # voxel_coord_np = (voxel_coord_np - np.array([semLab.shape]).T / 2.).reshape([3, d, h, w])\n    voxel_coord = torch.from_numpy(voxel_coord_np[:, verts_ind[:, 0], verts_ind[:, 1], verts_ind[:, 2]]).float()\n    voxel_coord = (voxel_coord -  torch.tensor([semLab.shape]).T / 2.).to(semLab.device)\n\n    prob_thres = cfg.MODEL.GROUPING.PROB_THRES\n    nms_r = 7\n    planeIns = np.zeros_like(semseg_verts)\n    ins_id = 1\n\n    uniq_sem = (torch.unique(semLab))\n    _param_htmap = F.threshold(param_htmap, prob_thres, 0)\n    for sem_id in uniq_sem:\n        # sys.stdout.write('\\r process:{}'.format(CLASS_LABELS[sem_id.item()]))\n        # sys.stdout.flush()\n        if sem_id.item() not in SEM_INS_MAP:\n            continue\n\n        # load htmap and voxels under current semantic\n        param_channel = SEM_INS_MAP[sem_id.item()]\n        tmp = _param_htmap[param_channel]\n        semseg_mask_np = (semseg_verts == sem_id.item())  # .view(-1)\n\n        # nms\n        nms_padding = (nms_r) // 2\n        tmp_pool = F.max_pool3d(tmp.unsqueeze(0).unsqueeze(0), kernel_size=nms_r, stride=1,\n                                padding=nms_padding).squeeze()\n        tmp[tmp != tmp_pool] = 0\n        params = tmp.nonzero(as_tuple=False)\n\n        # assign\n        h, w, d = semLab.shape\n        rho_tol = (cfg.MODEL.BACKBONE3D.RHO_STEP[-1] +1) #if sem_id.item() in LAYOUT_SEM else (cfg.MODEL.BACKBONE3D.RHO_STEP[-1] +1)\n        # componets = torch.arange(h*w*d).reshape([h,w,d]).to(semLab.device).float()\n        norm_score_glb = torch.zeros([n_verts]).float().to(semLab.device)\n        # tmp = torch.zeros_like(cur_param_htmap)\n        for param_id in params:\n            # tmp[param_id[0], param_id[1], param_id[2]] = 1.\n            cur_norm = sphere2norm(thetas[param_id[1]], phis[param_id[2]]).float().to(semLab.device)\n            cur_rho = torch.tensor(rhos[param_id[0]] * 2).float().to(semLab.device)\n\n            norm_score = (cur_norm.view(1, 3) * verts_norm).sum(dim=1).abs()\n            verts_norm_mask = norm_score > norm_score_glb\n\n            verts_in_mask = ((voxel_coord.T @ cur_norm - cur_rho).abs()) <= rho_tol\n\n            valid_pln_ins_mask = np.logical_and( (verts_in_mask & verts_norm_mask).detach().cpu().numpy(), semseg_mask_np )\n\n            if valid_pln_ins_mask.sum() < 4:\n                continue\n\n            planeIns[valid_pln_ins_mask] = ins_id\n            ins_id += 1\n            norm_score_glb[valid_pln_ins_mask] = torch.where((norm_score_glb < norm_score)[valid_pln_ins_mask], norm_score[valid_pln_ins_mask],\n                                                   norm_score_glb[valid_pln_ins_mask])\n\n    return planeIns\n\ndef get_planeIns_htmap(tsdf, voxel_sz, origin, semLab_in, param_htmap_in, plane_norm, vote_idx,  rhos, thetas, phis, cfg, upscale=2):\n    # voxel_size = tsdf.voxel_size\n    valid_tsdf= tsdf.abs().squeeze() < 1\n    semLab = semLab_in.squeeze()\n    param_htmap = param_htmap_in.squeeze()\n\n    verts_mc, faces, _, _ = measure.marching_cubes(tsdf, level=0)\n    verts_ind = np.round(verts_mc).astype(int)\n\n    verts = verts_mc * voxel_sz + origin.cpu().numpy()\n\n    prob_thres = cfg.MODEL.GROUPING.PROB_THRES\n    nms_r = 3\n    voxel_coord = coordinates(semLab.shape, semLab.device).float()\n    voxel_coord = voxel_coord - torch.tensor([semLab.shape]).to(semLab.device).T / 2.\n\n    planeIns = torch.zeros_like(semLab).float()\n    ins_id = 1\n    uniq_sem = (torch.unique(semLab))\n\n    _param_htmap = F.threshold(param_htmap, prob_thres, 0)\n\n    for sem_id in uniq_sem:\n\n        if sem_id.item() not in SEM_INS_MAP:\n            continue\n\n        # load htmap and voxels under current semantic\n        param_channel = SEM_INS_MAP[sem_id.item()]\n        tmp = _param_htmap[param_channel]\n        cur_mask = (semLab == sem_id) #.view(-1)\n\n        # nms\n        nms_padding = (nms_r - 1) // 2\n        tmp_pool = F.max_pool3d(tmp.unsqueeze(0).unsqueeze(0), kernel_size=nms_r, stride=1, padding=nms_padding).squeeze()\n        tmp[tmp != tmp_pool] = 0\n        params = tmp.nonzero(as_tuple=False)\n\n        # assign\n        valid_vlxs = valid_tsdf & cur_mask\n        h, w, d = semLab.shape\n        rho_tol = (cfg.MODEL.BACKBONE3D.RHO_STEP[-1] * 2 +1) if sem_id.item() in LAYOUT_SEM else (cfg.MODEL.BACKBONE3D.RHO_STEP[-1] +1)\n        componets = torch.arange(h*w*d).reshape([h,w,d]).to(semLab.device).float()\n        norm_score_glb = torch.zeros_like(semLab).float()\n\n        for param_id in params:\n            # tmp[param_id[0], param_id[1], param_id[2]] = 1.\n            cur_norm = sphere2norm(thetas[param_id[1]], phis[param_id[2]]).float().to(semLab.device)\n            cur_rho = torch.tensor(rhos[param_id[0]] * 2).float().to(semLab.device)\n\n            planes_in_vol = ((voxel_coord.T @ cur_norm - cur_rho).abs()).reshape(semLab.shape)<= rho_tol\n\n            norm_score = (cur_norm.view(3,1,1,1) * plane_norm).sum(dim=0).abs()\n            norm_mask =  norm_score > norm_score_glb\n\n\n            valid_planes_vlxs = norm_mask  &  planes_in_vol & valid_vlxs\n\n            if valid_planes_vlxs.sum()<8:\n                continue\n\n            # connected components with floodfill\n            comp = componets.clone()\n            comp[~valid_planes_vlxs] = 0\n            pre_comp = comp.clone()\n            for cnt in range(max(semLab.shape)):  # longest dist to flood fill equals to the largest dim\n                comp[valid_planes_vlxs] = F.max_pool3d(comp.unsqueeze(0).unsqueeze(0),\n                                              kernel_size=3, stride=1, padding=1).squeeze()[valid_planes_vlxs]\n                if (pre_comp == comp).all():\n                    break\n                else:\n                    pre_comp = comp.clone()\n\n            # assign label\n            uniq_ins = torch.unique(comp)\n            tmp_mask_sum = torch.zeros(len(uniq_ins))\n            for i, tmp_id in enumerate(uniq_ins):\n                if tmp_id < 1: continue\n                tmp_mask = (comp == tmp_id)\n                tmp_mask_sum[i] = tmp_mask.sum()\n\n            tmp_thres = tmp_mask_sum.max() * 0.1\n            for i, tmp_id in enumerate(uniq_ins):\n                if tmp_id < 1: continue\n                tmp_mask = (comp == tmp_id)\n                if tmp_mask_sum[i] < tmp_thres: continue # filter extremely small ones\n                planeIns[tmp_mask] = ins_id\n\n                ins_id += 1\n\n                # cancel the score if the voxel is not assigned\n                norm_score_glb[tmp_mask] = torch.where((norm_score_glb < norm_score)[tmp_mask], norm_score[tmp_mask],\n                                                         norm_score_glb[tmp_mask])\n\n    return planeIns.long()\n", "meta": {"hexsha": "a8cd5f5cf5b14ff20a4c927b859e13abdd75420e", "size": 48684, "ext": "py", "lang": "Python", "max_stars_repo_path": "vPlaneRecover/util.py", "max_stars_repo_name": "fuy34/indoorMVS", "max_stars_repo_head_hexsha": "440ba357de50d47e5868e6009bc608f8bcb9e9f6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-15T05:02:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T05:02:33.000Z", "max_issues_repo_path": "vPlaneRecover/util.py", "max_issues_repo_name": "fuy34/indoorMVS", "max_issues_repo_head_hexsha": "440ba357de50d47e5868e6009bc608f8bcb9e9f6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vPlaneRecover/util.py", "max_forks_repo_name": "fuy34/indoorMVS", "max_forks_repo_head_hexsha": "440ba357de50d47e5868e6009bc608f8bcb9e9f6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.2775665399, "max_line_length": 206, "alphanum_fraction": 0.6283173116, "include": true, "reason": "import numpy", "num_tokens": 12873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.26894141551050293, "lm_q1q2_score": 0.18357234979634396}}
{"text": "# Copyright (c) 2020, Soohwan Kim. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\nfrom speech_transformer.modules import Linear\nfrom torch import Tensor\nfrom typing import Optional, Tuple\n\n\nclass ScaledDotProductAttention(nn.Module):\n    \"\"\"\n    Scaled Dot-Product Attention proposed in \"Attention Is All You Need\"\n    Compute the dot products of the query with all keys, divide each by sqrt(dim),\n    and apply a softmax function to obtain the weights on the values\n\n    Args: dim, mask\n        dim (int): dimension of attention\n        mask (torch.Tensor): tensor containing indices to be masked\n\n    Inputs: query, key, value, mask\n        - **query** (batch, q_len, d_model): tensor containing projection vector for decoder.\n        - **key** (batch, k_len, d_model): tensor containing projection vector for encoder.\n        - **value** (batch, v_len, d_model): tensor containing features of the encoded input sequence.\n        - **mask** (-): tensor containing indices to be masked\n\n    Returns: context, attn\n        - **context**: tensor containing the context vector from attention mechanism.\n        - **attn**: tensor containing the attention (alignment) from the encoder outputs.\n    \"\"\"\n    def __init__(self, dim: int) -> None:\n        super(ScaledDotProductAttention, self).__init__()\n        self.sqrt_dim = np.sqrt(dim)\n\n    def forward(self, query: Tensor, key: Tensor, value: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:\n        score = torch.bmm(query, key.transpose(1, 2)) / self.sqrt_dim\n\n        if mask is not None:\n            score.masked_fill_(mask, -1e9)\n\n        attn = F.softmax(score, -1)\n        context = torch.bmm(attn, value)\n        return context, attn\n\n\nclass MultiHeadAttention(nn.Module):\n    \"\"\"\n    Multi-Head Attention proposed in \"Attention Is All You Need\"\n    Instead of performing a single attention function with d_model-dimensional keys, values, and queries,\n    project the queries, keys and values h times with different, learned linear projections to d_head dimensions.\n    These are concatenated and once again projected, resulting in the final values.\n    Multi-head attention allows the model to jointly attend to information from different representation\n    subspaces at different positions.\n\n    MultiHead(Q, K, V) = Concat(head_1, ..., head_h) · W_o\n        where head_i = Attention(Q · W_q, K · W_k, V · W_v)\n\n    Args:\n        d_model (int): The dimension of keys / values / quries (default: 512)\n        num_heads (int): The number of attention heads. (default: 8)\n\n    Inputs: query, key, value, mask\n        - **query** (batch, q_len, d_model): tensor containing projection vector for decoder.\n        - **key** (batch, k_len, d_model): tensor containing projection vector for encoder.\n        - **value** (batch, v_len, d_model): tensor containing features of the encoded input sequence.\n        - **mask** (-): tensor containing indices to be masked\n\n    Returns: output, attn\n        - **output** (batch, output_len, dimensions): tensor containing the attended output features.\n        - **attn** (batch * num_heads, v_len): tensor containing the attention (alignment) from the encoder outputs.\n    \"\"\"\n    def __init__(self, d_model: int = 512, num_heads: int = 8) -> None:\n        super(MultiHeadAttention, self).__init__()\n\n        assert d_model % num_heads == 0, \"hidden_dim % num_heads should be zero.\"\n\n        self.d_head = int(d_model / num_heads)\n        self.num_heads = num_heads\n        self.query_proj = Linear(d_model, self.d_head * num_heads)\n        self.key_proj = Linear(d_model, self.d_head * num_heads)\n        self.value_proj = Linear(d_model, self.d_head * num_heads)\n        self.sqrt_dim = np.sqrt(d_model)\n        self.scaled_dot_attn = ScaledDotProductAttention(self.d_head)\n\n    def forward(self, query: Tensor, key: Tensor, value: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:\n        batch_size = value.size(0)\n\n        query = self.query_proj(query).view(batch_size, -1, self.num_heads, self.d_head)  # BxQ_LENxNxD\n        key = self.key_proj(key).view(batch_size, -1, self.num_heads, self.d_head)        # BxK_LENxNxD\n        value = self.value_proj(value).view(batch_size, -1, self.num_heads, self.d_head)  # BxV_LENxNxD\n\n        query = query.permute(2, 0, 1, 3).contiguous().view(batch_size * self.num_heads, -1, self.d_head)  # BNxQ_LENxD\n        key = key.permute(2, 0, 1, 3).contiguous().view(batch_size * self.num_heads, -1, self.d_head)      # BNxK_LENxD\n        value = value.permute(2, 0, 1, 3).contiguous().view(batch_size * self.num_heads, -1, self.d_head)  # BNxV_LENxD\n\n        if mask is not None:\n            mask = mask.repeat(self.num_heads, 1, 1)\n\n        context, attn = self.scaled_dot_attn(query, key, value, mask)\n        context = context.view(self.num_heads, batch_size, -1, self.d_head)\n        context = context.permute(1, 2, 0, 3).contiguous().view(batch_size, -1, self.num_heads * self.d_head)  # BxTxND\n\n        return context, attn\n", "meta": {"hexsha": "307c46093f5ce1ceca11c63bf510059af191734c", "size": 5608, "ext": "py", "lang": "Python", "max_stars_repo_path": "speech_transformer/attention.py", "max_stars_repo_name": "sooftware/speech-transformer", "max_stars_repo_head_hexsha": "f072dc34585fa6c49a9c0fff86abf8604331a313", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2021-01-17T05:48:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T14:15:59.000Z", "max_issues_repo_path": "speech_transformer/attention.py", "max_issues_repo_name": "sooftware/Speech-Transformer", "max_issues_repo_head_hexsha": "f072dc34585fa6c49a9c0fff86abf8604331a313", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-02-14T08:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-28T14:39:58.000Z", "max_forks_repo_path": "speech_transformer/attention.py", "max_forks_repo_name": "sooftware/speech-transformer", "max_forks_repo_head_hexsha": "f072dc34585fa6c49a9c0fff86abf8604331a313", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-12-11T23:05:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T08:06:06.000Z", "avg_line_length": 47.5254237288, "max_line_length": 121, "alphanum_fraction": 0.6847360913, "include": true, "reason": "import numpy", "num_tokens": 1402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.18352966482251087}}
{"text": "import numpy as np\nimport pandas as pd\nimport networkx as nx\n\ndef m_time(pos1,pos2): #计算rgv在两点间运动的最短时间\n    d=abs(pos1-pos2)\n    if d==1:\n        return m1\n    elif d==2:\n        return m2\n    elif d==3:\n        return m3\n    elif d==0:\n        return 0\n#m1,m2,m3,p1,p21,p22,to,te,w=20,33,46,560,400,378,28,31,25\n#m1,m2,m3,p1,p21,p22,to,te,w=23,41,59,580,280,500,30,35,30\nm1,m2,m3,p1,p21,p22,to,te,w=18,32,46,545,455,182,27,32,25\nt=0\nv_pos = 1  # 初始位置为1，右侧依次为2、3、4\nv_sit = 0  # 0停止，1移动，2上料，3下料、上料、清洗\nrgv=np.array([[t,v_pos,v_sit]])\n\nc_sit=0 #表示cnc的作业状态，0为空闲且无孰料，1为空闲且有孰料，2为工作中\ncnc=[]\ncnc_inf=[]\nc_pos=0 #表示初始位置，无实际意义\nfor num in range(1,9):\n    if num==1 or num==2:\n        c_pos=1\n    elif num==3 or num==4:\n        c_pos=2\n    elif num==5 or num==6:\n        c_pos=3\n    elif num==7 or num==8:\n        c_pos=4\n    if num==1 or num==3 or num==5 or num==7:\n        tc=to\n    else:\n        tc=te\n    cnc.append(np.array([[t, num,c_pos,c_sit]]))\n    cnc_inf.append(np.array([num,p1,p21,p22,tc])) #储存了cnc的加工、上下料时间，是固定的信息\n\njudge_cnc=np.zeros((1,8),dtype=int) #初始cnc加工→休息判断矩阵\njudge_move=0\njudge_load=np.zeros((1,8),dtype=int)\njudge_layoff=np.zeros((1,8),dtype=int)\nload_num=0\nlayoff_num=0\nresult=np.array([[0,0,0,0]])\n\nprint(\"stop\")\n\nfor t in range(1,28800): #从第1秒到第5秒\n    #print(t)\n    #################################\n    rgv_new =np.array([t, rgv[t-1,1], rgv[t-1,2]])\n    rgv=np.vstack((rgv, rgv_new))#t改变，其他rgv参数复制上一秒的信息\n    for num in range(1, 9):\n        cnc_new=np.array([t, cnc[num-1][t-1,1],cnc[num-1][t-1,2],cnc[num-1][t-1,3]])\n        cnc[num-1]=np.vstack((cnc[num-1], cnc_new))#t改变，其他cnc参数复制上一秒的信息\n    #################################\n    for num in range(1, 9):\n        if cnc[num-1][t,3]==2 and t>=judge_cnc[0,num-1] and t<judge_cnc[0,num-1]+1: #cnc加工完成，给rgv发信号\n            cnc[num - 1][t, 3] = 1   #cnc从2（工作状态）到1（空闲，上有孰料状态）\n    #################################\n    if rgv[t,2]>0:    #如果rgv上一秒在运动\n        if t>=judge_move and t <judge_move+1:     #判断rgb移动是否完成\n            rgv[t,2]=0     #rgv瞬间进入移动后的等待状态，按照算法，这里应当立即对cnc进行操作\n            for num in range(1, 9):\n                if cnc[num - 1][t, 3] == 1:  # 如果cnc是空闲,上有孰料状态\n                    rgv[t, 2] = 3\n                    judge_layoff[0, num - 1] = t + cnc_inf[num - 1][4] + w\n                    load_num = load_num + 1\n                    layoff_num = layoff_num + 1\n                    print(\"第%d个CNC在第%d秒开始下第%d个料\" % (num, t, layoff_num))\n                    print(\"第%d个CNC在第%d秒开始上第%d个料\" % (num, t + cnc_inf[num - 1][4] / 2, load_num))\n                    result_new = np.array([load_num, num, t + cnc_inf[num - 1][4] / 2, 0])\n                    result = np.vstack((result, result_new))\n                    result[layoff_num, 3] = t\n                    break  # 一个时间rgv只能进入一种状态，这里进入了下料、上料、清洗状态\n                if cnc[num - 1][t, 3] == 0:  # 如果cnc也是空闲，无料状态（初始状态）\n                    rgv[t, 2] = 2  # rgv进入上料状态\n                    judge_load[0, num - 1] = t + cnc_inf[num - 1][4] / 2  # 假设空cnc上料时间为上下料时间的一半\n                    load_num = load_num + 1\n                    print(\"第%d个CNC在第%d秒开始上第%d个料\" % (num, t, load_num))\n                    result_new = np.array([load_num, num, t, 0])\n                    result = np.vstack((result, result_new))\n                    break  # 一个时间rgv只能进入一种状态，这里进入了上料状态\n        for num in range(1, 9):\n            if t>=judge_load[0,num-1] and t<judge_load[0,num-1]+1:       #这个情况只有在最开始的时候情况\n                cnc[num-1][t,3]=2   #cnc从0（空闲，上无料状态）到2（工作状态）\n                judge_cnc[0, num - 1] = t + cnc_inf[num - 1][1]  #当前时间加cnc工作时间，为cnc的预测空闲时间\n                rgv[t,2]=0       #rgv瞬间进入等待状态\n            if t>=judge_layoff[0,num-1] and t<judge_layoff[0,num-1]+1:     #上下料同时进行\n                cnc[num-1][t,3]=2 #cnc从1（空闲，上有孰料状态）到2（工作状态）\n                judge_cnc[0, num - 1] = t + cnc_inf[num - 1][1]  #当前时间加cnc工作时间，为cnc的预测空闲时间\n                rgv[t,2] = 0  # rgv瞬间进入等待状态,因为我们判断下料后一定会上料，这里要不要直接跳过搜索空闲cnc的过程？\n###################################################################\n    if rgv[t,2]==0:  #如果rgv空闲\n            cnc_stop_num=[]\n            for num in range(1, 9):\n                if cnc[num-1][t,3]==0 or cnc[num-1][t,3]==1:   #如果cnc也是空闲状态\n                    cnc_stop_num.append(cnc[num-1][t,1])   #调出空闲状态的cnc机号\n##########################################################################################################################################################\n            if cnc_stop_num == []:\n                continue  # 跳出大循环，表示rgv处于等候状态\n            elif len(cnc_stop_num)==1:  #如果只有一个机器发指令，直接接受指令\n                mov_pro=cnc_stop_num[0]\n            else:\n                G = nx.MultiDiGraph()\n                for s_num in cnc_stop_num:##########开始遍历第一层\n                    t_1=t\n                    G.add_edge(0,cnc[s_num - 1][t_1, 1], key=0, weight=m_time(cnc[s_num - 1][t_1, 2], rgv[t_1,1]) + cnc_inf[s_num - 1][4]+w)\n                    rgv_1 = np.array([[t_1, rgv[t_1,1], rgv[t_1,2]]])\n                    cnc_1 = []\n                    for num in range(1, 9):\n                        if num == 1 or num == 2:\n                            c_pos = 1\n                        elif num == 3 or num == 4:\n                            c_pos = 2\n                        elif num == 5 or num == 6:\n                            c_pos = 3\n                        elif num == 7 or num == 8:\n                            c_pos = 4\n                        cnc_1.append(np.array([[t_1, num, cnc[num-1][t_1,2], cnc[num-1][t_1,3]]]))\n                    judge_cnc_1 = np.zeros((1, 8), dtype=int)  # 初始cnc加工→休息判断矩阵\n                    judge_move_1 = 0\n                    judge_load_1 = np.zeros((1, 8), dtype=int)\n                    judge_layoff_1 = np.zeros((1, 8), dtype=int)\n                    load_num_1 = 0\n                    layoff_num_1 = 0\n                    #################################################\n                    mov_pro_1 = s_num\n                    mov_pos_1 = 0\n                    if mov_pro_1 == 1 or mov_pro_1 == 2:\n                        mov_pos_1 = 1\n                    elif mov_pro_1 == 3 or mov_pro_1 == 4:\n                        mov_pos_1 = 2\n                    elif mov_pro_1 == 5 or mov_pro_1 == 6:\n                        mov_pos_1 = 3\n                    elif mov_pro_1 == 7 or mov_pro_1 == 8:\n                        mov_pos_1 = 4  # 计算目标机位（mov_pro 1-8）所在的位置（mov_pos 1-4）\n                    if mov_pos_1 != rgv_1[0, 1]:  # 如果判断的移动位置和rgv所在位置不同，则立即进入移动状态\n                        rgv_1[0, 2] = 1  # 0停止，1移动，2上料，3下料、上料、清洗\n                        judge_move_1 = t_1 + m_time(mov_pos_1, rgv_1[0, 1])\n                        rgv_1[0, 1] = mov_pos_1  # 移动开始，未知参数就变为目标位置\n                    elif mov_pos_1 == rgv_1[0, 1]:  # 如果判断的移动位置和rgv所在位置相同，则立即进入 上料 或者 下料、上料、清洗 状态\n                        for num in range(1, 9):\n                            if cnc_1[num - 1][0, 3] == 1:  # 如果cnc是空闲,上有孰料状态\n                                rgv_1[0, 2] = 3\n                                judge_layoff_1[0, num - 1] = t_1 + cnc_inf[num - 1][4] + w\n                                load_num_1 = load_num_1 + 1\n                                layoff_num_1 = layoff_num_1 + 1\n                                break # 一个时间rgv只能进入一种状态，这里进入了下料、上料、清洗状态\n                            if cnc_1[num - 1][0, 3] == 0:  # 如果cnc也是空闲，无料状态（初始状态）\n                                rgv_1[0, 2] = 2  # rgv进入上料状态\n                                judge_load_1[0, num - 1] = t_1 + cnc_inf[num - 1][4] / 2  # 假设空cnc上料时间为上下料时间的一半\n                                load_num_1 = load_num_1 + 1\n                                break# 一个时间rgv只能进入一种状态，这里进入了上料状态\n                    a_1 = 0\n                    ###########################################################################\n                    while True:\n                        t_1=t_1+1\n                        a_1 = a_1 + 1\n                        #################################\n                        rgv_new_1 = np.array([t_1, rgv_1[a_1 - 1, 1], rgv_1[a_1 - 1, 2]])\n                        rgv_1 = np.vstack((rgv_1, rgv_new_1))  # t改变，其他rgv参数复制上一秒的信息\n                        for num in range(1, 9):\n                            cnc_new_1 = np.array([t_1, cnc_1[num - 1][a_1 - 1, 1], cnc_1[num - 1][a_1 - 1, 2], cnc_1[num - 1][a_1 - 1, 3]])\n                            cnc_1[num - 1] = np.vstack((cnc_1[num - 1], cnc_new_1))  # t改变，其他cnc参数复制上一秒的信息\n                        #################################\n                        for num in range(1, 9):\n                            if cnc_1[num - 1][a_1, 3] == 2 and t_1 >= judge_cnc_1[0, num - 1] and t_1 < judge_cnc_1[0, num - 1] + 1:  # cnc加工完成，给rgv发信号\n                                cnc_1[num - 1][a_1, 3] = 1  # cnc从2（工作状态）到1（空闲，上有孰料状态）\n                        #################################\n                        if rgv_1[a_1, 2] > 0:  # 如果rgv上一秒在运动\n                            if t_1 >= judge_move_1 and t_1 < judge_move_1 + 1:  # 判断rgb移动是否完成\n                                rgv_1[a_1, 2] = 0  # rgv瞬间进入移动后的等待状态，按照算法，这里应当立即对cnc进行操作\n                                for num in range(1, 9):\n                                    if cnc_1[num - 1][a_1, 3] == 1:  # 如果cnc是空闲,上有孰料状态\n                                        rgv_1[a_1, 2] = 3\n                                        judge_layoff_1[0, num - 1] = t_1 + cnc_inf[num - 1][4] + w\n                                        load_num_1 = load_num_1 + 1\n                                        layoff_num_1 = layoff_num_1 + 1\n                                        break  # 一个时间rgv只能进入一种状态，这里进入了下料、上料、清洗状态\n                                    if cnc_1[num - 1][a_1, 3] == 0:  # 如果cnc也是空闲，无料状态（初始状态）\n                                        rgv_1[a_1, 2] = 2  # rgv进入上料状态\n                                        judge_load_1[0, num - 1] = t_1 + cnc_inf[num - 1][4] / 2  # 假设空cnc上料时间为上下料时间的一半\n                                        load_num_1 = load_num_1 + 1\n                                        break  # 一个时间rgv只能进入一种状态，这里进入了上料状态\n                            for num in range(1, 9):\n                                if t_1 >= judge_load_1[0, num - 1] and t_1 < judge_load_1[0, num - 1] + 1:  # 这个情况只有在最开始的时候情况\n                                    cnc_1[num - 1][a_1, 3] = 2  # cnc从0（空闲，上无料状态）到2（工作状态）\n                                    judge_cnc_1[0, num - 1] = t_1 + cnc_inf[num - 1][1]  # 当前时间加cnc工作时间，为cnc的预测空闲时间\n                                    rgv_1[a_1, 2] = 0  # rgv瞬间进入等待状态\n                                if t_1 >= judge_layoff_1[0, num - 1] and t_1 < judge_layoff_1[0, num - 1] + 1:  # 上下料同时进行\n                                    cnc_1[num - 1][a_1, 3] = 2  # cnc从1（空闲，上有孰料状态）到2（工作状态）\n                                    judge_cnc_1[0, num - 1] = t_1 + cnc_inf[num - 1][1]  # 当前时间加cnc工作时间，为cnc的预测空闲时间\n                                    rgv_1[a_1, 2] = 0  # rgv瞬间进入等待状态,因为我们判断下料后一定会上料，这里要不要直接跳过搜索空闲cnc的过程？\n                        ###################################################################\n                        if rgv_1[a_1, 2] == 0:  # 如果rgv空闲 #直到运行到某时刻空闲，且有分叉，while才会停止\n                                cnc_stop_num_1 = []\n                                for num in range(1, 9):\n                                    if cnc_1[num - 1][a_1, 3] == 0 or cnc_1[num - 1][a_1, 3] == 1:  # 如果cnc也是空闲状态\n                                            cnc_stop_num_1.append(cnc_1[num - 1][a_1, 1])  # 调出空闲状态的cnc机号\n                                    ##################################################################################################################################\\\n                                if cnc_stop_num_1 == []:\n                                    continue  # 跳出大循环，表示rgv处于等候状态\n                                else:\n                                    for s_num_1 in cnc_stop_num_1:  ##########开始遍历第二层\n                                        t_2=t_1\n                                        G.add_edge(cnc[s_num - 1][t, 1], cnc_1[s_num_1 - 1][a_1, 1], key=1,weight=m_time(cnc_1[s_num_1 - 1][a_1, 2], rgv_1[a_1, 1]) + cnc_inf[s_num_1 - 1][4] + w)\n                                    break\n                GA_weight = []\n                GA_choice = []\n                for edge_0 in G.edges:\n                    if edge_0[2] == 0:  # 遍历所有边，取key为0的边：edge_0\n                        for edge_1 in G.edges:\n                            if edge_1[2] == 1 and edge_0[1] == edge_1[0] and edge_1[0]!=edge_1[1]:  # 遍历所有边，取key为1的边,且首尾相连的边,且非环的边（两个节点重复）：edge_1\n                                GA_weight.append(\n                                    G[edge_0[0]][edge_0[1]][edge_0[2]]['weight'] + G[edge_1[0]][edge_1[1]][edge_1[2]]['weight'])\n                                GA_choice.append(edge_0[1])  # 我们只关心下一步的点是哪个,这个点在1-8中\n                mov_pro=GA_choice[GA_weight.index(min(GA_weight))]\n                ##########结束遍历第一层\n                # 获得较好的空闲状态机号mov_pro，属于(1-8)\n\n            #返回一个1-4的数，是rgv到cnc距离和上料时间和最短的位置，进行移动和上料\n            mov_pos=0\n            if  mov_pro==1 or mov_pro==2:\n                mov_pos=1\n            elif mov_pro==3 or mov_pro==4:\n                mov_pos=2\n            elif mov_pro==5 or mov_pro==6:\n                mov_pos=3\n            elif mov_pro==7 or mov_pro==8:\n                mov_pos=4             #计算目标机位（mov_pro 1-8）所在的位置（mov_pos 1-4）\n            if mov_pos!=rgv[t,1]:  #如果判断的移动位置和rgv所在位置不同，则立即进入移动状态\n                rgv[t,2] = 1      # 0停止，1移动，2上料，3下料、上料、清洗\n                judge_move=t+m_time(mov_pos,rgv[t,1])\n                rgv[t, 1] = mov_pos  # 移动开始，未知参数就变为目标位置\n            elif mov_pos==rgv[t,1]:#如果判断的移动位置和rgv所在位置相同，则立即进入 上料 或者 下料、上料、清洗 状态\n                for num in range(1, 9):\n                    if cnc[num - 1][t,3] == 1:  # 如果cnc是空闲,上有孰料状态\n                        rgv[t, 2] = 3\n                        judge_layoff[0, num - 1] = t + cnc_inf[num - 1][4]+w\n                        load_num = load_num + 1\n                        layoff_num=layoff_num+1\n                        print(\"第%d个CNC在第%d秒开始下第%d个料\" % (num, t, layoff_num))\n                        print(\"第%d个CNC在第%d秒开始上第%d个料\" % (num, t+cnc_inf[num-1][4]/2, load_num))\n                        result_new=np.array([load_num,num,t+cnc_inf[num-1][4]/2,0])\n                        result = np.vstack((result, result_new))\n                        result[layoff_num,3]=t\n\n                        break  # 一个时间rgv只能进入一种状态，这里进入了下料、上料、清洗状态\n                    if cnc[num - 1][t,3] == 0:  # 如果cnc也是空闲，无料状态（初始状态）\n                        rgv[t, 2] = 2  #rgv进入上料状态\n                        judge_load[0,num-1]=t+cnc_inf[num-1][4]/2  #假设空cnc上料时间为上下料时间的一半\n                        load_num=load_num+1\n                        print(\"第%d个CNC在第%d秒开始上第%d个料\"%(num,t,load_num))\n                        result_new = np.array([load_num, num, t , 0])\n                        result = np.vstack((result, result_new))\n                        break #一个时间rgv只能进入一种状态，这里进入了上料状态\n\nresult_df = pd.DataFrame(result)\nwriter = pd.ExcelWriter('test.xlsx')\nresult_df.to_excel(writer,'page_1',float_format='%.5f') # float_format 控制精度\nwriter.save()\n", "meta": {"hexsha": "059709bc6f7e4df1c1778999c2c2ee6b4eb2d077", "size": 14902, "ext": "py", "lang": "Python", "max_stars_repo_path": "2018-CUMCM-B/test_GA.py", "max_stars_repo_name": "CarlossShi/mcm-shit-mountain", "max_stars_repo_head_hexsha": "f89e75f38a2f36a0182f75ac491115f3cae80ff5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-19T06:30:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T06:30:06.000Z", "max_issues_repo_path": "2018-CUMCM-B/test_GA.py", "max_issues_repo_name": "CarlossShi/MCM-shit-mountain", "max_issues_repo_head_hexsha": "f89e75f38a2f36a0182f75ac491115f3cae80ff5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2018-CUMCM-B/test_GA.py", "max_forks_repo_name": "CarlossShi/MCM-shit-mountain", "max_forks_repo_head_hexsha": "f89e75f38a2f36a0182f75ac491115f3cae80ff5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.6044776119, "max_line_length": 194, "alphanum_fraction": 0.4244396725, "include": true, "reason": "import numpy,import networkx", "num_tokens": 5647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.18352965758159076}}
{"text": "# -*- coding: UTF-8 -*-\n__author__ = 'Jens-Kristian Krogager'\n\nimport numpy as np\nimport VoigtFit\n\n\ndef print_T_model_pars(dataset, filename=None):\n    \"\"\"Print the turbulence and T parameters for physical model.\"\"\"\n    N_comp = len(dataset.components.values()[0])\n    print(\"\")\n    print(u\"  No:     Temperature [K]       Turbulence [km/s]\")\n    if filename:\n        out_file = open(filename, 'w')\n        out_file.write(u\"# No:     Temperature [K]       Turbulence [km/s] \\n\")\n\n    for comp_num in range(N_comp):\n        T_name = 'T_%i' % comp_num\n        turb_name = 'turb_%i' % comp_num\n        T_fit = dataset.best_fit[T_name]\n        turb_fit = dataset.best_fit[turb_name]\n        par_tuple = (comp_num, T_fit.value, T_fit.stderr,\n                     turb_fit.value, turb_fit.stderr)\n        print(u\"  %-3i   %.2e ± %.2e    %.2e ± %.2e\" % par_tuple)\n        if filename:\n            out_file.write(u\"  %-3i   %.2e ± %.2e    %.2e ± %.2e \\n\" % par_tuple)\n\n    print(\"\")\n    if filename:\n        out_file.close()\n\n\n# -- Fit DLA towards quasar Q1313+1441\n#    Observed in X-shooter P089.A-0068\n\nz_DLA = 0.00345\n\n# If log(NHI) is not known use:\nlogNHI = None\n\n# -- Load X-SHOOTER UVB and VIS data in ASCII format:\nfname = 'thermal_model_2comp.dat'\nres = 6.6\n\nwl, spec, err = np.loadtxt(fname, unpack=True)\n\n# -- Here you can load your data in any way you wish\n#    Only requirement is that wl, spec, and err have the same dimensions.\n\n# -- A dataset which has already been defined can be loaded like this:\n# dataset = VoigtFit.LoadDataSet('test_data.hdf5')\n\ndataset = VoigtFit.DataSet(z_DLA)\ndataset.set_name('test_2comp')\ndataset.verbose = True\ndataset.velspan = 150.\ndataset.cheb_order = -1\n\n# -- Add the data loaded from the\ndataset.add_data(wl, spec, res, err=err, normalized=True)\n\n# -- Define absorption lines:\ndataset.add_many_lines(['FeII_2344', 'FeII_2374', 'FeII_2382'])\ndataset.add_many_lines(['FeII_1608', 'FeII_1611'])\ndataset.add_line('FeII_2260')\ndataset.add_line('FeII_2249')\ndataset.add_line('CrII_2056')\ndataset.add_line('CrII_2066')\ndataset.add_line('CrII_2026')\ndataset.add_line('ZnII_2026')\ndataset.add_line('CrII_2062')\ndataset.add_line('ZnII_2062')\n# -- dataset.add_many_lines is equivalent to dataset.add_lines:\ndataset.add_many_lines(['CII_1036', 'CII_1334'])\ndataset.add_many_lines(['OI_1302', 'OI_1039', 'OI_1355'])\ndataset.add_many_lines(['SiII_1526', 'SiII_1808', 'SiII_1304'])\ndataset.add_many_lines(['SiII_1260', 'FeII_1260', 'SII_1259'])\ndataset.add_many_lines(['SII_1250', 'SII_1253'])\n\n\n# -- If a line has been defined, and you don't want to fit it\n#    it can either be removed from the dataset completely:\n# dataset.remove_line('CrII_2056')\n\n# -- or deactivated:\n# dataset.deactivate_line('FeII_2374')\n\n# -- Deactivated lines will not be included in the fit, but their line definitions\n#    and components remain in the dataset for future reference.\n\n# -- To use the physical model, make sure that all components are cleared:\ndataset.reset_components()\n\n# -- Add components for each ion:\n#                      ion    z         b   logN\ndataset.add_component('FeII', 0.003290, 5., 15.0, var_z=1, var_b=1)\ndataset.add_component('FeII', 0.003620, 5., 14.5, var_z=1, var_b=1)\n\n\n# -- The physical model requires that all ions have the same velocity structure:\n#    The default order is 'to' , 'from' :\n# dataset.copy_components('CrII', 'FeII')\n# -- But the ions can be specified using keywords to ease the call:\ndataset.copy_components(from_ion='FeII', to_ion='CrII', tie_b=False)\ndataset.copy_components(from_ion='FeII', to_ion='ZnII', tie_b=False)\ndataset.copy_components(from_ion='FeII', to_ion='SiII', tie_b=False)\ndataset.copy_components(from_ion='FeII', to_ion='SII', tie_b=False)\ndataset.copy_components(from_ion='FeII', to_ion='CII', tie_b=False)\ndataset.copy_components(from_ion='FeII', to_ion='OI', tie_b=False)\n\n# -- This copies the two components defined for FeII to the other ions and\n#    keeps the same pattern of initial guesses for column density scaled\n#    to the Solar abundance ratio.\n\n# -- Individual components which are not observed for weaker lines can be removed:\n# dataset.delete_component('ZnII', 1)\n# dataset.delete_component('ZnII', 0)\n#\n# NOTE - components should be deleted from last component to first component\n#        not the other way around as that messes up the component numbering.\n#        Components are zero-indexed!\n\n# -- Prepare the dataset: This will prompt the user for interactive\n#    masking and normalization, as well as initiating the Parameters:\ndataset.prepare_dataset(norm=False, mask=False)\n\n# -- Define masks for individual lines:\n# dataset.mask_line('ZnII_2026')\n\n# --- This is where the magic happens ----------------------------------------\n# Set up the thermal and turbulence parameters for each component:\ndataset.pars.add('turb_0', value=5., vary=True, min=0.)\ndataset.pars.add('turb_1', value=5., vary=True, min=0.)\n\ndataset.pars.add('T_0', value=5000., vary=1, min=0.)\ndataset.pars.add('T_1', value=5000., vary=1, min=0.)\n# -- This can be defined in a for loop assuming the same intial guess for T:\n# T_init = 1.e4\n# for comp_num in range(len(dataset.components.values()[0])):\n#     dataset.pars.add('T_%i'%comp_num, value=T_init, vary=True, min=0.)\n\n# -- Now set up the links for the 'b'-parameter of each component of each ion:\n# 2k_B/m_u in (km/s)^2 units:\nK = 0.0166287\nfor ion, comp in dataset.components.items():\n    N_comp = len(comp)\n    for comp_num in range(N_comp):\n        par_name = 'b%i_%s' % (comp_num, ion)\n        lines_for_ion = dataset.get_lines_for_ion(ion)\n        m_ion = lines_for_ion[0].mass\n        const = K/m_ion\n        T_num = dataset.pars['T_%i' % comp_num].value\n        b_eff = np.sqrt(5.**2 + K*T_num/m_ion)\n        model_constraint = 'sqrt((turb_%i)**2 + %.6f*T_%i)' % (comp_num,\n                                                               const,\n                                                               comp_num)\n        dataset.pars[par_name].set(expr=model_constraint, value=b_eff)\n\n# ---------------------------------------------------------------------------\n\n# -- Fit the dataset:\npopt, chi2 = dataset.fit(verbose=True, plot=False, factor=10.)\n\ndataset.plot_fit(filename=dataset.name)\n\n# -- Print total column densities\ndataset.print_total()\n\nif logNHI:\n    dataset.print_metallicity(*logNHI)\n\nprint_T_model_pars(dataset)\n\n# -- Save the dataset to file: taken from the dataset.name\ndataset.save()\n", "meta": {"hexsha": "e9fc4bc898dedf5ed6e21fa97056ba7b46231f66", "size": 6445, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/physical_model.py", "max_stars_repo_name": "jkrogager/VoigtFit", "max_stars_repo_head_hexsha": "ca84ff4b9e6827e2ca64cd03c9437ab5d4097f1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2018-03-06T02:06:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T05:24:35.000Z", "max_issues_repo_path": "scripts/physical_model.py", "max_issues_repo_name": "InspectorDidi/VoigtFit", "max_issues_repo_head_hexsha": "5f162179e27f1ccd5818f5c6c303835aaa2719ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2018-03-03T11:53:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T20:43:34.000Z", "max_forks_repo_path": "scripts/physical_model.py", "max_forks_repo_name": "InspectorDidi/VoigtFit", "max_forks_repo_head_hexsha": "5f162179e27f1ccd5818f5c6c303835aaa2719ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-05-16T03:34:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-30T02:38:17.000Z", "avg_line_length": 36.6193181818, "max_line_length": 82, "alphanum_fraction": 0.6690457719, "include": true, "reason": "import numpy", "num_tokens": 1783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.18352324558992222}}
{"text": "from functools import reduce\nimport jax.numpy as np\nimport jax.linear_util as lu\nfrom jax.util import unzip2, unzip3, safe_zip, safe_map, partial, WrapHashably\nfrom jax.abstract_arrays import ShapedArray\nfrom jax.experimental import stax\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters.batching import get_aval\nfrom jax.interpreters import batching\nfrom jax.api_util import (\n    wraps, pytree_to_jaxtupletree, pytree_fun_to_jaxtupletree_fun)\nimport jax.core as jc\nfrom jax import random\nfrom jax import lax\n\n\nzip = safe_zip\nmap = safe_map\n\n\ndef merge_params(params):\n    if len(params) > 0:\n        p = params[0]\n        for param in params[1:]:\n            p.update(param)\n        return p\n    else:\n        return {}\n\nclass Layer(jc.Primitive):\n    def __init__(self, name, init_fun, apply_fun):\n        self.init_fun = init_fun\n        self.apply_fun = apply_fun\n        super(Layer, self).__init__(name)\n        def layer_abstract_eval(*avals):\n            akey = ShapedArray((2,), 'uint32')\n            def init_and_apply(key, *inputs):\n                params = init_fun(key, *inputs)\n                return apply_fun(params, *inputs)\n            return pe.abstract_eval_fun(init_and_apply, akey, *avals)\n        self.def_abstract_eval(layer_abstract_eval)\n        def layer_batch(batched_args, batch_dims, **params):\n            # TODO: figure out batching/debatching for init_fun\n            batched_apply_fun = (\n                lambda params, *batch_inputs:\n                batching.batch(lu.wrap_init(partial(self.apply_fun, params)),\n                               batch_inputs, batch_dims, 0))\n            batched_layer = Layer(name, init_fun, batched_apply_fun)\n            return batched_layer.bind(*batched_args, **params), 0\n        batching.primitive_batchers[self] = layer_batch\n\ndef init_interpreter(rng, jaxpr, consts, freevar_vals, net_params, *args):\n    def read(v):\n        if type(v) is jc.Literal:\n            return v.val\n        else:\n            return env[v]\n\n    def write(v, val):\n        env[v] = val\n\n    env = {}\n    write(jc.unitvar, jc.unit)\n    jc.pat_fmap(write, jaxpr.constvars, consts)\n    jc.pat_fmap(write, jaxpr.invars, args)\n    jc.pat_fmap(write, jaxpr.freevars, freevar_vals)\n    for eqn in jaxpr.eqns:\n        rng, prim_rng = random.split(rng)\n        if not eqn.restructure:\n            in_vals = map(read, eqn.invars)\n        else:\n            in_vals = [pack(map(read, invars)) if type(invars) is tuple\n                       else read(invars) for invars in eqn.invars]\n        if eqn.bound_subjaxprs:\n            subjaxprs, sub_consts, sub_freevar_vals = unzip3([\n                (subjaxpr,\n                 map(read, const_vars),\n                 map(read, bound_vars))\n                for subjaxpr, const_vars, bound_vars in eqn.bound_subjaxprs])\n            ans, net_params = get_primitive_init(eqn.primitive)(\n                prim_rng, eqn.params, sub_consts, sub_freevar_vals, in_vals,\n                net_params)\n        else:\n            ans, net_params = get_primitive_init(eqn.primitive)(\n                prim_rng, net_params, *in_vals, **eqn.params)\n        outvals = list(ans) if eqn.destructure else [ans]\n        map(write, eqn.outvars, outvals)\n    return net_params\n\ninit_rules = {}\n\ndef layer_init(layer, rng, net_params, *inputs):\n    if layer.name not in net_params:\n        layer_params = layer.init_fun(rng, *inputs)\n        net_params[layer.name] = layer_params\n    return layer.apply_fun(net_params[layer.name], *inputs), net_params\n\ndef get_primitive_init(primitive):\n    if primitive in init_rules:\n        return primitive\n    elif isinstance(primitive, Layer):\n        return partial(layer_init, primitive)\n    else:\n        return (lambda _, net_params, *in_vals, **params:\n                (primitive.bind(*in_vals, **params), net_params))\n\ndef init_fun(net_fun, rng, *example_inputs, **kwargs):\n    net_fun = lu.wrap_init(net_fun)\n    def pv_like(x):\n        return pe.PartialVal((get_aval(x), jc.unit))\n    pvals = map(pv_like, example_inputs)\n    jaxpr, _, consts = pe.trace_to_jaxpr(net_fun, pvals, **kwargs)\n    return init_interpreter(rng, jaxpr, consts, [], {}, *example_inputs)\n\n\nclass ApplyTracer(jc.Tracer):\n    __slots__ = ['val', 'net_params']\n\n    def __init__(self, trace, net_params, val):\n        self.trace = trace\n        self.val = val\n        self.net_params = net_params\n\n    @property\n    def aval(self):\n        return jc.get_aval(self.val)\n\n    def unpack(self):\n        return tuple(self.val)\n\n    def full_lower(self):\n        return self\n\nclass ApplyTrace(jc.Trace):\n    def pure(self, val):\n        return ApplyTracer(self, {}, val)\n\n    def lift(self, val):\n        return ApplyTracer(self, {}, val)\n\n    def sublift(self, val):\n        return ApplyTracer(self, {}, val.val)\n\n    def process_primitive(self, primitive, tracers, params):\n        vals_in, net_params = unzip2((t.val, t.net_params) for t in tracers)\n        net_params = merge_params(net_params)\n        if isinstance(primitive, Layer):\n            apply_fun = primitive.apply_fun\n            layer_params = net_params[primitive.name]\n            return ApplyTracer(\n                self, net_params, apply_fun(layer_params, *vals_in))\n        else:\n            return ApplyTracer(\n                self, net_params, primitive.bind(*vals_in, **params))\n\n    def process_call(self, call_primitive, f, tracers, params):\n        if call_primitive in pe.map_primitives:\n            raise NotImplementedError\n        vals, net_params = unzip2((t.val, t.net_params) for t in tracers)\n        if any(net_params):\n            net_params = merge_params(net_params)\n            f = apply_subtrace(f, self.master, WrapHashably(net_params))\n            val_out = call_primitive.bind(f, *vals, **params)\n            return ApplyTracer(self, net_params, val_out)\n        else:\n            return call_primitive.bind(f, *vals, **params)\n\n\n@lu.transformation\ndef apply_transform(net_params, inputs):\n    with jc.new_master(ApplyTrace) as master:\n        trace = ApplyTrace(master, jc.cur_sublevel())\n        ans = yield map(partial(ApplyTracer, trace, net_params), inputs), {}\n        out_tracer = trace.full_raise(ans)\n        out_val = out_tracer.val\n        del master, out_tracer\n    yield out_val\n\n@lu.transformation\ndef apply_subtrace(master, net_params, *vals):\n    net_params = net_params.val\n    trace = ApplyTrace(master, jc.cur_sublevel())\n    ans = yield map(partial(ApplyTracer, trace, net_params), vals), {}\n    out_tracer = trace.full_raise(ans)\n    yield out_tracer.val\n\n\ndef apply_fun(net_fun, params, *inputs):\n    return apply_transform(lu.wrap_init(net_fun), params).call_wrapped(inputs)\n", "meta": {"hexsha": "3e6d313b88540cfce7dd19c16b234cd77fd76ba4", "size": 6686, "ext": "py", "lang": "Python", "max_stars_repo_path": "jaxnet/core.py", "max_stars_repo_name": "j-towns/pointy-stax", "max_stars_repo_head_hexsha": "72a4babdcced0548465a4e7b815b2831c24c0efa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jaxnet/core.py", "max_issues_repo_name": "j-towns/pointy-stax", "max_issues_repo_head_hexsha": "72a4babdcced0548465a4e7b815b2831c24c0efa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jaxnet/core.py", "max_forks_repo_name": "j-towns/pointy-stax", "max_forks_repo_head_hexsha": "72a4babdcced0548465a4e7b815b2831c24c0efa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1894736842, "max_line_length": 78, "alphanum_fraction": 0.6434340413, "include": true, "reason": "import jax,from jax", "num_tokens": 1633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.32423539245106087, "lm_q1q2_score": 0.18352323714662977}}
{"text": "import os\nfrom pathlib import Path\nfrom abc import ABCMeta, abstractmethod\nimport json\nfrom json import JSONEncoder\nimport numpy as np\nfrom pyflowline.classes.vertex import pyvertex\nfrom pyflowline.classes.edge import pyedge\nfrom pyflowline.classes.flowline import pyflowline\nfrom pyflowline.classes.confluence import pyconfluence\nfrom pyflowline.formats.read_flowline import read_flowline_geojson\nfrom pyflowline.formats.read_nhdplus_flowline_shapefile import read_nhdplus_flowline_shapefile_attribute\nfrom pyflowline.formats.read_nhdplus_flowline_shapefile import extract_nhdplus_flowline_shapefile_by_attribute\nfrom pyflowline.formats.read_nhdplus_flowline_shapefile import track_nhdplus_flowline\nfrom pyflowline.formats.convert_flowline_to_geojson import convert_flowline_to_geojson\nfrom pyflowline.formats.export_flowline import export_flowline_to_geojson\nfrom pyflowline.formats.export_vertex import export_vertex_to_geojson\nfrom pyflowline.algorithms.auxiliary.text_reader_string import text_reader_string\nfrom pyflowline.algorithms.split.find_flowline_vertex import find_flowline_vertex\nfrom pyflowline.algorithms.split.find_flowline_confluence import find_flowline_confluence\nfrom pyflowline.algorithms.split.split_flowline import split_flowline\nfrom pyflowline.algorithms.split.split_flowline_to_edge import split_flowline_to_edge\nfrom pyflowline.algorithms.merge.merge_flowline import merge_flowline\nfrom pyflowline.algorithms.direction.correct_flowline_direction import correct_flowline_direction\nfrom pyflowline.algorithms.loop.remove_flowline_loop import remove_flowline_loop\nfrom pyflowline.algorithms.simplification.remove_small_river import remove_small_river\nfrom pyflowline.algorithms.simplification.remove_returning_flowline import remove_returning_flowline\nfrom pyflowline.algorithms.simplification.remove_duplicate_flowline import remove_duplicate_flowline\nfrom pyflowline.algorithms.index.define_stream_order import define_stream_order\nfrom pyflowline.algorithms.index.define_stream_segment_index import define_stream_segment_index\nfrom pyflowline.algorithms.intersect.intersect_flowline_with_mesh import intersect_flowline_with_mesh\n\n\n\nclass BasinClassEncoder(JSONEncoder):\n    def default(self, obj):\n        if isinstance(obj, np.integer):\n            return int(obj)\n        if isinstance(obj, np.float32):\n            return float(obj)\n        if isinstance(obj, np.ndarray):\n            return obj.tolist()\n        if isinstance(obj, list):\n            pass  \n        if isinstance(obj, pyvertex):\n            return json.loads(obj.tojson()) #lVertexID\n        if isinstance(obj, pyedge):\n            return obj.lEdgeID        \n        if isinstance(obj, pyflowline):\n            return obj.lFlowlineID\n        if isinstance(obj, pyconfluence):\n            return obj.dAngle_upstream\n       \n            \n        return JSONEncoder.default(self, obj)\n\n\n\nclass pybasin(object):\n    lBasinID =1 \n    sBasinID=''\n    lCellID_outlet=-1\n    iFlag_debug = 0\n    iFlag_disconnected =0\n    iFlag_dam=0\n    dLongitude_outlet_degree = -9999.\n    dLatitude_outlet_degree = -9999.\n    dAccumulation_threshold= 100000.0\n    dThreshold_small_river = 10000\n    dLength_flowline_filtered = 0.0\n    dLength_flowline_simplified = 0.0\n    dLength_flowline_conceptual = 0.0\n\n    dArea_of_difference=0.0\n    dDistance_displace = 0.0\n    sWorkspace_output_basin=''\n    sFilename_flowline_raw=''    \n    sFilename_flowline_filter=''\n    sFilename_flowline_filter_geojson=''\n    sFilename_dam=''\n    sFilename_flowline_topo=''\n    #before intersect\n    sFilename_flowline_simplified=''\n    sFilename_flowline_segment_index_before_intersect=''\n    sFilename_flowline_conceptual=''\n    sFilename_flowline_edge=''\n    sFilename_basin_info=''\n    sFilename_flowline_simplified_info=''\n    sFilename_flowline_conceptual_info=''\n    sFilename_confluence_simplified_info=''\n    sFilename_confluence_conceptual_info=''    \n    aFlowline_basin_filtered=None\n    aFlowline_basin_simplified=None\n    aFlowline_basin_conceptual=None    \n    pVertex_outlet=None\n    aConfluence_basin_simplified= None\n    aConfluence_basin_conceptual= None\n    \n    def __init__(self, aParameter):\n\n        if 'lBasinID' in aParameter:            \n            self.lBasinID             = int(aParameter['lBasinID'])\n        else:\n            self.lBasinID   = 1\n        \n        \n        if 'lCellID_outlet' in aParameter:            \n            self.lCellID_outlet             = int(aParameter['lCellID_outlet'])\n        else:\n            self.lCellID_outlet   = -1\n\n        if 'iFlag_disconnected' in aParameter:            \n            self.iFlag_disconnected             = int(aParameter['iFlag_disconnected'])\n        else:\n            self.iFlag_disconnected   = 0\n        \n        if 'iFlag_dam' in aParameter:            \n            self.iFlag_dam             = int(aParameter['iFlag_dam'])\n        else:\n            self.iFlag_dam   = 0\n        \n        if 'iFlag_debug' in aParameter:            \n            self.iFlag_debug             = int(aParameter['iFlag_debug'])\n        else:\n            self.iFlag_debug   = 0\n        \n        if 'dLongitude_outlet_degree' in aParameter:            \n            self.dLongitude_outlet_degree             = float(aParameter['dLongitude_outlet_degree'])\n        else:\n            self.dLongitude_outlet_degree   = -9999.\n        \n        if 'dLatitude_outlet_degree' in aParameter:            \n            self.dLatitude_outlet_degree             = float(aParameter['dLatitude_outlet_degree'])\n        else:\n            self.dLatitude_outlet_degree   = -9999.\n        \n        if 'dThreshold_small_river' in aParameter:            \n            self.dThreshold_small_river             = float(aParameter['dThreshold_small_river'])\n        else:\n            self.dThreshold_small_river   = 10000.0\n\n        if 'dAccumulation_threshold' in aParameter:            \n            self.dAccumulation_threshold             = float(aParameter['dAccumulation_threshold'])\n        else:\n            self.dAccumulation_threshold = 100000.0   \n\n        if 'sFilename_flowline_raw' in aParameter:\n            self.sFilename_flowline_raw = aParameter['sFilename_flowline_raw']\n        else:\n            self.sFilename_flowline_raw   = ''\n       \n        if 'sFilename_flowline_filter' in aParameter:\n            self.sFilename_flowline_filter = aParameter['sFilename_flowline_filter']\n        else:\n            self.sFilename_flowline_filter   = ''\n\n        if 'sWorkspace_output_basin' in aParameter:\n            self.sWorkspace_output_basin = aParameter['sWorkspace_output_basin']\n        else:\n            self.sWorkspace_output_basin   = '.'\n            \n        Path(self.sWorkspace_output_basin).mkdir(parents=True, exist_ok=True)\n\n        self.sFilename_flowline_filter_geojson = os.path.join(str(self.sWorkspace_output_basin ), \"flowline_filter.geojson\"  )\n\n        if 'sFilename_dam' in aParameter:\n            self.sFilename_dam = aParameter['sFilename_dam']\n        else:\n            self.sFilename_dam   = ''\n\n        if 'sFilename_flowline_topo' in aParameter:\n            self.sFilename_flowline_topo = aParameter['sFilename_flowline_topo']\n        else:\n            self.sFilename_flowline_topo   =''\n\n        self.sBasinID = sBasinID = \"{:03d}\".format(self.lBasinID)\n\n        #geojson\n        self.sFilename_flowline_segment_index_before_intersect = 'flowline_segment_index_before_intersect.geojson'\n        self.sFilename_flowline_simplified = 'flowline_simplified.geojson'\n        self.sFilename_flowline_intersect  = 'flowline_intersect_mesh.geojson'\n        self.sFilename_flowline_conceptual = 'flowline_conceptual.geojson'\n        self.sFilename_flowline_edge = 'flowline_edge.geojson'\n        self.sFilename_area_of_difference = 'area_of_difference.geojson'\n\n        self.sFilename_basin_info = 'basin_info.json'\n        self.sFilename_flowline_conceptual_info = 'flowline_conceptual_info.json'\n        self.sFilename_flowline_simplified_info = 'flowline_simplified_info.json'\n        self.sFilename_confluence_conceptual_info = 'confluence_conceptual_info.json'\n        self.sFilename_confluence_simplified_info = 'confluence_simplified_info.json'\n        return\n        \n    def flowline_simplification(self):\n\n        \n        sFilename_flowline_filter = self.sFilename_flowline_filter\n        sFilename_flowline_filter_geojson = self.sFilename_flowline_filter_geojson\n        aFlowline_basin_filtered, pSpatial_reference = read_flowline_geojson( sFilename_flowline_filter_geojson )   \n        sWorkspace_output_basin = self.sWorkspace_output_basin\n        if self.iFlag_dam ==1:\n            sFilename_dam = self.sFilename_dam\n            aData_dam = text_reader_string(sFilename_dam, iSkipline_in =1,cDelimiter_in=',' )\n            sFilename_flowline_topo = self.sFilename_flowline_topo\n            aData_flowline_topo = text_reader_string(sFilename_flowline_topo, iSkipline_in =1,cDelimiter_in=',' )\n            aFromFlowline = aData_flowline_topo[:,1].astype(int).ravel()\n            aToFlowline = aData_flowline_topo[:,2].astype(int).ravel()\n            sFilename_flowline_raw = self.sFilename_flowline_raw\n            aNHDPlusID_filter = read_nhdplus_flowline_shapefile_attribute(sFilename_flowline_filter)\n            aNHDPlusID_raw = read_nhdplus_flowline_shapefile_attribute(sFilename_flowline_raw)\n            ndam = len(aData_dam)\n            aNHDPlusID_dams_headwater = list()\n            aNHDPlusID_dams_nonheadwater = list()\n            for j in range(0, ndam):\n                dLon = float(aData_dam[j][1])\n                dLat = float(aData_dam[j][0])\n                sDam = aData_dam[j][4]            \n                lNHDPlusID = int(aData_dam[j][5])\n                aNHDPlusID_dams_headwater.append(lNHDPlusID)\n                if lNHDPlusID in aNHDPlusID_filter:\n                    #remove by id\n                    for k in range(len(aFlowline_basin_filtered)):\n                        if aFlowline_basin_filtered[k].lNHDPlusID == lNHDPlusID:\n                            aFlowline_basin_filtered.pop(k)\n                            break\n                    pass\n                else:                                \n                    aNHDPlusID_dam_nonheadwater = track_nhdplus_flowline(aNHDPlusID_filter, aFromFlowline, aToFlowline, lNHDPlusID)\n                    aNHDPlusID_filter = aNHDPlusID_filter + aNHDPlusID_dams_headwater+ aNHDPlusID_dam_nonheadwater  \n                    aNHDPlusID_dams_nonheadwater = aNHDPlusID_dams_nonheadwater + aNHDPlusID_dam_nonheadwater\n            aFlowline_dams_headwater = extract_nhdplus_flowline_shapefile_by_attribute(sFilename_flowline_raw, aNHDPlusID_dams_headwater )\n            for i in range(len(aFlowline_dams_headwater)):\n                aFlowline_dams_headwater[i].iFlag_dam = 1\n            aFlowline_dams_nonheadwater = extract_nhdplus_flowline_shapefile_by_attribute(sFilename_flowline_raw, aNHDPlusID_dams_nonheadwater )\n            aFlowline_basin_filtered = aFlowline_basin_filtered + aFlowline_dams_headwater + aFlowline_dams_nonheadwater\n        else:\n            pass\n        if self.iFlag_disconnected == 1:\n            #not used anymore                \n            #aThreshold = np.full(2, 300.0, dtype=float)\n            #aFlowline_basin_filtered = connect_disconnect_flowline(aFlowline_basin_filtered, aVertex, aThreshold)\n            #sFilename_out = 'flowline_connect.geojson'\n            #sFilename_out = os.path.join(sWorkspace_output_basin, sFilename_out)    \n            #export_flowline_to_geojson(iFlag_projected, aFlowline_basin_filtered,pSpatial_reference_gcs, sFilename_out)\n            pass\n        else:\n            pass\n            \n        if self.iFlag_debug ==1:\n            sFilename_out = 'flowline_before_intersect.geojson'\n            sFilename_out = os.path.join(sWorkspace_output_basin, sFilename_out)            \n            self.export_flowline(aFlowline_basin_filtered, sFilename_out)\n        #calculate length\n        self.aFlowline_basin_filtered = aFlowline_basin_filtered\n        self.dLength_flowline_filtered = self.calculate_flowline_length(aFlowline_basin_filtered)\n\n        #simplification started\n        aVertex = find_flowline_vertex(aFlowline_basin_filtered)\n        if self.iFlag_debug ==1:\n            sFilename_out = 'flowline_vertex_without_confluence_before_intersect.geojson'\n            sFilename_out = os.path.join(sWorkspace_output_basin, sFilename_out)\n            export_vertex_to_geojson( aVertex, sFilename_out)\n        aFlowline_basin_simplified = split_flowline(aFlowline_basin_filtered, aVertex)\n        if self.iFlag_debug ==1:\n            sFilename_out = 'flowline_split_by_point_before_intersect.geojson'\n            sFilename_out = os.path.join(sWorkspace_output_basin, sFilename_out)\n            export_flowline_to_geojson(aFlowline_basin_simplified, sFilename_out)\n        #ues location to find outlet\n        point= dict()   \n        point['dLongitude_degree'] = self.dLongitude_outlet_degree\n        point['dLatitude_degree'] = self.dLatitude_outlet_degree\n        pVertex_outlet=pyvertex(point)\n        aFlowline_basin_simplified = correct_flowline_direction(aFlowline_basin_simplified,  pVertex_outlet )\n        pVertex_outlet = aFlowline_basin_simplified[0].pVertex_end\n        self.pVertex_outlet = pVertex_outlet\n        if self.iFlag_debug ==1:\n            sFilename_out = 'flowline_direction_before_intersect.geojson'\n            sFilename_out = os.path.join(sWorkspace_output_basin, sFilename_out)\n            export_flowline_to_geojson( aFlowline_basin_simplified,  sFilename_out)\n        #step 4: remove loops\n        aFlowline_basin_simplified = remove_flowline_loop(aFlowline_basin_simplified)    \n        if self.iFlag_debug ==1:\n            sFilename_out = 'flowline_loop_before_intersect.geojson'\n            sFilename_out = os.path.join(sWorkspace_output_basin, sFilename_out)\n            export_flowline_to_geojson( aFlowline_basin_simplified, sFilename_out)\n        #using loop to remove small river, here we use 5 steps\n        for i in range(3):\n            sStep = \"{:02d}\".format(i+1)\n            aFlowline_basin_simplified = remove_small_river(aFlowline_basin_simplified, self.dThreshold_small_river)\n            if self.iFlag_debug ==1:\n                sFilename_out = 'flowline_large_'+ sStep +'_before_intersect.geojson'\n                sFilename_out =os.path.join(sWorkspace_output_basin, sFilename_out)\n                export_flowline_to_geojson( aFlowline_basin_simplified,  sFilename_out)\n            aVertex, lIndex_outlet, aIndex_headwater,aIndex_middle, aIndex_confluence, aConnectivity = find_flowline_confluence(aFlowline_basin_simplified,  pVertex_outlet)\n            if self.iFlag_debug ==1:\n                sFilename_out = 'flowline_vertex_with_confluence_'+ sStep +'_before_intersect.geojson'\n                sFilename_out = os.path.join(sWorkspace_output_basin, sFilename_out)\n                export_vertex_to_geojson( aVertex,  sFilename_out, aAttribute_data=aConnectivity)\n            aFlowline_basin_simplified = merge_flowline( aFlowline_basin_simplified,aVertex, pVertex_outlet, aIndex_headwater,aIndex_middle, aIndex_confluence  )  \n            if self.iFlag_debug ==1:\n                sFilename_out = 'flowline_merge_'+ sStep +'_before_intersect.geojson'\n                sFilename_out = os.path.join(sWorkspace_output_basin, sFilename_out)\n                export_flowline_to_geojson( aFlowline_basin_simplified,  sFilename_out)\n            if len(aFlowline_basin_simplified) == 1:\n                break\n        \n        #the final vertex info\n        aVertex, lIndex_outlet, aIndex_headwater,aIndex_middle, aIndex_confluence, aConnectivity = find_flowline_confluence(aFlowline_basin_simplified,  pVertex_outlet)\n        sFilename_out = 'vertex_simplified.geojson'\n        sFilename_out = os.path.join(sWorkspace_output_basin, sFilename_out)\n        export_vertex_to_geojson( aVertex,  sFilename_out, aAttribute_data=aConnectivity)\n        \n        #self.dLength_flowline_simplified = self.calculate_flowline_length(aFlowline_basin_simplified)\n        aVertex = np.array(aVertex)\n        aIndex_confluence = np.array(aIndex_confluence)\n        if aIndex_confluence.size > 0:        \n            aVertex_confluence = aVertex[aIndex_confluence]\n            self.aConfluence_basin_simplified = self.build_confluence(aFlowline_basin_simplified, aVertex_confluence) \n        \n\n        #build segment index\n        aFlowline_basin_simplified, aStream_segment = define_stream_segment_index(aFlowline_basin_simplified)\n        if self.iFlag_debug ==1:\n            sFilename_out = self.sFilename_flowline_segment_index_before_intersect\n            sFilename_out = os.path.join(sWorkspace_output_basin, sFilename_out)\n            export_flowline_to_geojson(  aFlowline_basin_simplified, sFilename_out, \\\n                aAttribute_data=[aStream_segment], aAttribute_field=['iseg'], aAttribute_dtype=['int'])\n        #build stream order \n        aFlowline_basin_simplified, aStream_order = define_stream_order(aFlowline_basin_simplified)\n        sFilename_out = self.sFilename_flowline_simplified\n        sFilename_out = os.path.join(sWorkspace_output_basin, sFilename_out)\n        export_flowline_to_geojson(  aFlowline_basin_simplified, sFilename_out, \\\n                aAttribute_data=[aStream_segment, aStream_order], aAttribute_field=['iseg','iord'], aAttribute_dtype=['int','int'])\n        \n\n        self.aFlowline_basin_simplified= aFlowline_basin_simplified\n        return aFlowline_basin_simplified\n\n    def reconstruct_topological_relationship(self, iMesh_type, sFilename_mesh):\n        \n        sWorkspace_output_basin = self.sWorkspace_output_basin\n        sFilename_flowline = self.sFilename_flowline_simplified\n        sFilename_flowline_in = os.path.join(sWorkspace_output_basin, sFilename_flowline)\n        aFlowline_basin_simplified, pSpatial_reference = read_flowline_geojson( sFilename_flowline_in )   \n                \n        sFilename_flowline_intersect = self.sFilename_flowline_intersect\n        sFilename_flowline_intersect_out = os.path.join(sWorkspace_output_basin, sFilename_flowline_intersect)\n        aCell, aCell_intersect_basin, aFlowline_intersect_all = intersect_flowline_with_mesh(iMesh_type, sFilename_mesh, \\\n            sFilename_flowline_in, sFilename_flowline_intersect_out)\n        sFilename_flowline_filter_geojson = self.sFilename_flowline_filter\n        if self.iFlag_debug ==1:\n            sFilename_out = 'flowline_intersect_flowline_with_mesh.geojson'\n            sFilename_out = os.path.join(sWorkspace_output_basin, sFilename_out)  \n            export_flowline_to_geojson(aFlowline_intersect_all,  sFilename_out)\n        \n        point= dict()\n        point['dLongitude_degree'] = self.dLongitude_outlet_degree\n        point['dLatitude_degree'] = self.dLatitude_outlet_degree\n        pVertex_outlet_initial=pyvertex(point)\n\n        #from this point, aFlowline_basin is conceptual\n        #segment based\n        aFlowline_basin_conceptual, lCellID_outlet, pVertex_outlet = remove_returning_flowline(iMesh_type, aCell_intersect_basin, pVertex_outlet_initial)\n        if self.iFlag_debug ==1:\n            sFilename_out = 'flowline_simplified_after_intersect.geojson'\n            sFilename_out = os.path.join(sWorkspace_output_basin, sFilename_out)  \n            export_flowline_to_geojson(aFlowline_basin_conceptual,  sFilename_out)\n\n        #edge based\n        aFlowline_basin_conceptual, aEdge = split_flowline_to_edge(aFlowline_basin_conceptual)\n        if self.iFlag_debug ==1:\n            sFilename_out = 'flowline_edge_split_flowline_to_edge.geojson'\n            sFilename_out = os.path.join(sWorkspace_output_basin, sFilename_out)\n            export_flowline_to_geojson( aFlowline_basin_conceptual,  sFilename_out)\n        aFlowline_basin_conceptual = remove_duplicate_flowline(aFlowline_basin_conceptual)\n        if self.iFlag_debug ==1:\n            sFilename_out = 'flowline_edge_remove_duplicate_flowline.geojson'\n            sFilename_out = os.path.join(sWorkspace_output_basin, sFilename_out)\n            export_flowline_to_geojson( aFlowline_basin_conceptual,  sFilename_out)\n        aFlowline_basin_conceptual = correct_flowline_direction(aFlowline_basin_conceptual,  pVertex_outlet )\n        if self.iFlag_debug ==1:\n            sFilename_out = 'flowline_edge_correct_flowline_direction.geojson'\n            sFilename_out = os.path.join(sWorkspace_output_basin, sFilename_out)\n            export_flowline_to_geojson( aFlowline_basin_conceptual,  sFilename_out)\n        aFlowline_basin_conceptual = remove_flowline_loop(  aFlowline_basin_conceptual )  \n        if self.iFlag_debug ==1:\n            sFilename_out = 'flowline_edge_remove_flowline_loop.geojson'\n            sFilename_out = os.path.join(sWorkspace_output_basin, sFilename_out)\n            export_flowline_to_geojson( aFlowline_basin_conceptual,  sFilename_out)\n  \n        aVertex, lIndex_outlet, aIndex_headwater,aIndex_middle, aIndex_confluence, aConnectivity\\\n            = find_flowline_confluence(aFlowline_basin_conceptual,  pVertex_outlet)\n        if self.iFlag_debug ==1:\n            sFilename_out = 'flowline_vertex_with_confluence_after_intersect.geojson'\n            sFilename_out = os.path.join(sWorkspace_output_basin, sFilename_out)\n            export_vertex_to_geojson( aVertex,  sFilename_out, aAttribute_data=aConnectivity)\n        \n        #segment based\n        aFlowline_basin_conceptual = merge_flowline( aFlowline_basin_conceptual,aVertex, pVertex_outlet, aIndex_headwater,aIndex_middle, aIndex_confluence  )                          \n        aVertex, lIndex_outlet, aIndex_headwater,aIndex_middle, aIndex_confluence, aConnectivity\\\n            = find_flowline_confluence(aFlowline_basin_conceptual,  pVertex_outlet)        \n        aFlowline_basin_conceptual, aStream_segment = define_stream_segment_index(aFlowline_basin_conceptual)\n        aFlowline_basin_conceptual, aStream_order = define_stream_order(aFlowline_basin_conceptual)\n\n        #save confluence\n        aVertex = np.array(aVertex)\n        aIndex_confluence = np.array(aIndex_confluence)\n        if aIndex_confluence.size > 0:        \n            aVertex_confluence = aVertex[aIndex_confluence] \n            self.aConfluence_basin_conceptual = self.build_confluence(aFlowline_basin_conceptual, aVertex_confluence) \n          \n\n        #edge based\n        aFlowline_basin_edge, aEdge = split_flowline_to_edge(aFlowline_basin_conceptual)\n        sFilename_out = self.sFilename_flowline_edge\n        sFilename_out = os.path.join(sWorkspace_output_basin, sFilename_out)\n        export_flowline_to_geojson(  aFlowline_basin_edge, sFilename_out)\n\n        sFilename_out = self.sFilename_flowline_conceptual\n        sFilename_out = os.path.join(sWorkspace_output_basin, sFilename_out)\n        export_flowline_to_geojson(  aFlowline_basin_conceptual, sFilename_out, \\\n            aAttribute_data=[aStream_segment, aStream_order], aAttribute_field=['iseg','iord'], aAttribute_dtype=['int','int'])\n\n        self.aFlowline_basin_conceptual = aFlowline_basin_conceptual     \n        \n        self.lCellID_outlet = lCellID_outlet\n        self.dLongitude_outlet_degree = pVertex_outlet.dLongitude_degree\n        self.dLatitude_outlet_degree = pVertex_outlet.dLatitude_degree\n        \n\n        return aCell_intersect_basin\n\n    def build_confluence(self, aFlowline_basin_in, aVertex_confluence_in):    \n        #this can only be calculated for confluence\n        aConfluence_basin=list()\n        for pVertex in aVertex_confluence_in:   \n            aFlowline_upstream =list()\n            for pFlowline in aFlowline_basin_in:\n                pVertex_start = pFlowline.pVertex_start\n                pVertex_end = pFlowline.pVertex_end\n                if pVertex_end == pVertex:                 \n                    aFlowline_upstream.append(pFlowline)\n                    pass\n                if pVertex_start == pVertex:\n                    pFlowline_downstream=pFlowline\n\n            pConfluence = pyconfluence(pVertex, aFlowline_upstream, pFlowline_downstream)\n            aConfluence_basin.append(pConfluence)   \n        return aConfluence_basin\n\n    def analyze(self):      \n        if self.aFlowline_basin_filtered is None:\n            sFilename_flowline_filter = self.sFilename_flowline_filter\n            sFilename_flowline_filter_geojson = self.sFilename_flowline_filter_geojson\n            self.aFlowline_basin_filtered, pSpatial_reference = read_flowline_geojson( sFilename_flowline_filter_geojson )   \n            self.dLength_flowline_filtered = self.calculate_flowline_length(self.aFlowline_basin_filtered)\n        \n        point= dict()\n        point['dLongitude_degree'] = self.dLongitude_outlet_degree\n        point['dLatitude_degree'] = self.dLatitude_outlet_degree\n        pVertex_outlet_initial=pyvertex(point)\n        if self.aFlowline_basin_simplified is None:\n            sFilename_flowline = self.sFilename_flowline_simplified\n            sFilename_flowline_in = os.path.join(self.sWorkspace_output_basin, sFilename_flowline)\n            aFlowline_simplified,pSpatial_reference = read_flowline_geojson( sFilename_flowline_in )   \n            read_flowline_geojson\n            self.aFlowline_basin_simplified = aFlowline_simplified\n            aVertex, lIndex_outlet, aIndex_headwater,aIndex_middle, aIndex_confluence, aConnectivity\\\n            = find_flowline_confluence(self.aFlowline_basin_simplified,  pVertex_outlet_initial)  \n            aVertex = np.array(aVertex)\n            aIndex_confluence = np.array(aIndex_confluence)\n            if aIndex_confluence.size > 0:        \n                aVertex_confluence = aVertex[aIndex_confluence] \n                self.aConfluence_basin_simplified = self.build_confluence(self.aFlowline_basin_simplified, aVertex_confluence)\n\n        self.dLength_flowline_simplified = self.calculate_flowline_length(self.aFlowline_basin_simplified)\n\n        if self.aFlowline_basin_conceptual is None:\n            sFilename_flowline = self.sFilename_flowline_conceptual\n            sFilename_flowline_in = os.path.join(self.sWorkspace_output_basin, sFilename_flowline)\n            aFlowline_conceptual, pSpatial_reference = read_flowline_geojson( sFilename_flowline_in )   \n            self.aFlowline_basin_conceptual = aFlowline_conceptual\n            \n            aVertex, lIndex_outlet, aIndex_headwater,aIndex_middle, aIndex_confluence, aConnectivity\\\n            = find_flowline_confluence(self.aFlowline_basin_conceptual,  pVertex_outlet_initial)  \n            aVertex = np.array(aVertex)\n            aIndex_confluence = np.array(aIndex_confluence)\n            if aIndex_confluence.size > 0:        \n                aVertex_confluence = aVertex[aIndex_confluence] \n                self.aConfluence_basin_conceptual = self.build_confluence(self.aFlowline_basin_conceptual, aVertex_confluence)\n\n        self.dLength_flowline_conceptual = self.calculate_flowline_length(self.aFlowline_basin_conceptual)\n        self.calculate_river_sinuosity()\n        self.calculate_confluence_branching_angle()\n        return    \n    \n    def export(self):\n        self.export_basin_info_to_json()\n        self.export_flowline_info_to_json()\n        self.export_confluence_info_to_json()        \n        return\n\n    def export_flowline(self, aFlowline_in, sFilename_json_in,iFlag_projected_in = None,  pSpatial_reference_in = None):\n        export_flowline_to_geojson(aFlowline_in, sFilename_json_in,\\\n            iFlag_projected_in= iFlag_projected_in, \\\n            pSpatial_reference_in = pSpatial_reference_in)\n\n    def export_basin_info_to_json(self):\n        sFilename_json = self.sFilename_basin_info\n        sFilename_json = os.path.join(str(Path(self.sWorkspace_output_basin)  ) , sFilename_json  )\n\n        aSkip = ['aFlowline_basin_filtered', \\\n                'aFlowline_basin_simplified','aFlowline_basin_conceptual','aConfluence_basin_simplified',\n                'aConfluence_basin_conceptual']\n        obj = self.__dict__.copy()\n        for sKey in aSkip:\n            obj.pop(sKey, None)\n        with open(sFilename_json, 'w', encoding='utf-8') as f:\n            sJson = json.dumps(obj, default=lambda o: o.__dict__,\\\n            sort_keys=True, \\\n                indent = 4, \\\n                    ensure_ascii=True, \\\n                        cls=BasinClassEncoder)      \n            f.write(sJson)    \n            f.close()\n        return\n\n    def export_flowline_info_to_json(self):\n        iFlag_export_simplified=0\n        if iFlag_export_simplified==1:\n            sFilename_json = self.sFilename_flowline_simplified_info\n            sFilename_json = os.path.join(str(Path(self.sWorkspace_output_basin)  ) , sFilename_json  )\n            with open(sFilename_json, 'w', encoding='utf-8') as f:\n                sJson = json.dumps([json.loads(ob.tojson()) for ob in self.aFlowline_basin_simplified], indent = 4)        \n                f.write(sJson)    \n                f.close()\n\n        sFilename_json = self.sFilename_flowline_conceptual_info\n        sFilename_json = os.path.join(str(Path(self.sWorkspace_output_basin)  ) , sFilename_json  )\n\n        \n        with open(sFilename_json, 'w', encoding='utf-8') as f:\n            sJson = json.dumps([json.loads(ob.tojson()) for ob in self.aFlowline_basin_conceptual], indent = 4)        \n            f.write(sJson)    \n            f.close()\n        return\n\n    def export_confluence_info_to_json(self):\n        iFlag_export_confluence =0\n        if iFlag_export_confluence==1:\n            sFilename_json = self.sFilename_confluence_simplified_info\n            sFilename_json = os.path.join(str(Path(self.sWorkspace_output_basin)  ) , sFilename_json  )\n            with open(sFilename_json, 'w', encoding='utf-8') as f:\n                sJson = json.dumps([json.loads(ob.tojson()) for ob in self.aConfluence_basin_simplified], indent = 4)        \n                f.write(sJson)    \n                f.close()\n\n        sFilename_json = self.sFilename_confluence_conceptual_info\n        sFilename_json = os.path.join(str(Path(self.sWorkspace_output_basin)  ) , sFilename_json  )\n        \n        with open(sFilename_json, 'w', encoding='utf-8') as f:\n            sJson = json.dumps([json.loads(ob.tojson()) for ob in self.aConfluence_basin_conceptual], indent = 4)        \n            f.write(sJson)    \n            f.close()\n        return   \n\n    def tojson(self):\n        aSkip = ['aFlowline_basin_filtered', \\\n                'aFlowline_basin_simplified','aFlowline_basin_conceptual','aConfluence_basin_simplified',\n                'aConfluence_basin_conceptual']\n\n        obj = self.__dict__.copy()\n        for sKey in aSkip:\n            obj.pop(sKey, None)\n \n    \n        sJson = json.dumps(obj, \\\n            sort_keys=True, \\\n                indent = 4, \\\n                    ensure_ascii=True, \\\n                        cls=BasinClassEncoder)\n        return sJson\n    \n    def export_config_to_json(self, sFilename_output_in = None):\n        #single basin\n        if sFilename_output_in is not None:\n            sFilename_output = sFilename_output_in\n        else:\n            sFilename_output = os.path.join(self.sWorkspace_output_basin, 'configuration_basin.json' )\n\n        aSkip = ['aFlowline_basin_filtered', \\\n                'aFlowline_basin_simplified','aFlowline_basin_conceptual','aConfluence_basin_simplified',\n                'aConfluence_basin_conceptual']\n        obj = self.__dict__.copy()\n        for sKey in aSkip:\n            obj.pop(sKey, None)\n        with open(sFilename_output, 'w', encoding='utf-8') as f:\n            json.dump(obj, f,sort_keys=True, \\\n                ensure_ascii=False, \\\n                indent=4, \\\n                cls=BasinClassEncoder)\n        return\n\n    def convert_flowline_to_geojson(self):\n        sFilename_raw = self.sFilename_flowline_filter            \n        sFilename_out = self.sFilename_flowline_filter_geojson\n        print('This is the filtered flowline:', sFilename_raw )\n        convert_flowline_to_geojson(1, sFilename_raw, sFilename_out)\n        \n    def calculate_flowline_length(self, aFlowline_in):\n        dLength = 0.0\n        nflowline = len(aFlowline_in)\n        for i in range(nflowline):\n            pFlowline= aFlowline_in[i]\n            pFlowline.calculate_length()\n            dLength = dLength + pFlowline.dLength        \n        return dLength\n\n    def calculate_river_sinuosity(self):\n        for pFlowline in self.aFlowline_basin_simplified:\n            pFlowline.calculate_flowline_sinuosity() \n\n        for pFlowline in self.aFlowline_basin_conceptual:\n            pFlowline.calculate_flowline_sinuosity()    \n\n        return\n\n    def calculate_confluence_branching_angle(self):\n        for pConfluence in self.aConfluence_basin_simplified:\n            pConfluence.calculate_branching_angle()\n        for pConfluence in self.aConfluence_basin_conceptual:\n            pConfluence.calculate_branching_angle()    \n        return\n    ", "meta": {"hexsha": "98e16d1ad6ffe334c99d165bf431f2b71988f430", "size": 32945, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyflowline/classes/basin.py", "max_stars_repo_name": "changliao1025/pyflowline", "max_stars_repo_head_hexsha": "fb8677c5ebb3d0db8638f7fcc495ffb97376e00f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-03-23T12:10:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:41:16.000Z", "max_issues_repo_path": "pyflowline/classes/basin.py", "max_issues_repo_name": "changliao1025/pyflowline", "max_issues_repo_head_hexsha": "fb8677c5ebb3d0db8638f7fcc495ffb97376e00f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-24T16:08:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T16:08:35.000Z", "max_forks_repo_path": "pyflowline/classes/basin.py", "max_forks_repo_name": "changliao1025/pyflowline", "max_forks_repo_head_hexsha": "fb8677c5ebb3d0db8638f7fcc495ffb97376e00f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.0458135861, "max_line_length": 183, "alphanum_fraction": 0.6982850205, "include": true, "reason": "import numpy", "num_tokens": 7726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.35577490717496246, "lm_q1q2_score": 0.18344462765391784}}
{"text": "\"\"\"Classes representing different kinds of astronomical position.\"\"\"\n\nfrom numpy import array, arccos, clip, einsum, exp\n\nfrom .constants import RAD2DEG, tau\nfrom .data.spice import inertial_frames\nfrom .functions import dots, from_polar, length_of, to_polar, rot_z\nfrom .earthlib import compute_limb_angle, refract\nfrom .relativity import add_aberration, add_deflection\nfrom .timelib import Time\nfrom .units import Distance, Velocity, Angle, _interpret_angle\n\n_ECLIPJ2000 = inertial_frames['ECLIPJ2000']\n_GALACTIC = inertial_frames['GALACTIC']\n\n\ndef build_position(position_au, velocity_au_per_d=None, t=None,\n                   center=None, target=None, observer_data=None):\n    if center == 0:\n        cls = Barycentric\n    elif center == 399:\n        cls = Geocentric\n    elif observer_data is not None:\n        cls = Geometric\n    else:\n        cls = ICRF\n    return cls(position_au, velocity_au_per_d, t, center, target, observer_data)\n\n\nclass ICRF(object):\n    \"\"\"An (x, y, z) position and velocity oriented to the ICRF axes.\n\n    The ICRF is a permanent coordinate system that has superseded the\n    old series of equinox-based systems like B1900 and B1950.  Its axes\n    are aligned with the axes of J2000 to within 0.02 arcseconds, which\n    is tighter than the accuracy of J2000 itself.\n\n    \"\"\"\n    def __init__(self, position_au, velocity_au_per_d=None, t=None,\n                 center=None, target=None, observer_data=None):\n        self.t = t\n        self.position = Distance(position_au)\n        if velocity_au_per_d is None:\n            self.velocity = None\n        else:\n            self.velocity = Velocity(velocity_au_per_d)\n        # TODO: are center and target useful? Then why are they not\n        # propagated down to Astrometric and Apparent positions?\n        self.center = center\n        self.target = target\n        self.observer_data = observer_data\n\n    def __repr__(self):\n        return '<{0} position{1}{2}{3}{4}>'.format(\n            self.__class__.__name__,\n            '' if (self.velocity is None) else ' and velocity',\n            '' if self.t is None else ' at date t',\n            '' if self.center is None else ' center={0}'.format(self.center),\n            '' if self.target is None else ' target={0}'.format(self.target),\n        )\n\n    def __sub__(self, body):\n        \"\"\"Subtract two ICRF vectors to produce a third.\"\"\"\n        # TODO: set center and target of result\n        p = self.position.au - body.position.au\n        if self.velocity is None or body.velocity is None:\n            v = None\n        else:\n            v = body.velocity.au_per_d - self.velocity.au_per_d\n        return ICRF(p, v, self.t)\n\n    def distance(self):\n        \"\"\"Compute the distance from the origin to this position.\n\n        >>> v = ICRF([1, 1, 0])\n        >>> print(v.distance())\n        1.41421 au\n\n        \"\"\"\n        return Distance(length_of(self.position.au))\n\n    def speed(self):\n        \"\"\"Compute the magnitude of the velocity vector.\n\n        >>> v = ICRF([0, 0, 0], [1, 2, 3])\n        >>> print(v.speed())\n        3.74166 au/day\n\n        \"\"\"\n        return Velocity(length_of(self.velocity.au_per_d))\n\n    def radec(self, epoch=None):\n        r\"\"\"Compute equatorial (RA, declination, distance)\n\n        When called without a parameter, this returns standard ICRF\n        right ascension and declination:\n\n        >>> ra, dec, distance = ICRF([1, 2, 3]).radec()\n        >>> print(ra, dec, distance, sep='\\n')\n        04h 13m 44.39s\n        +53deg 18' 02.8\"\n        3.74166 au\n\n        If you instead want the coordinates referenced to the dynamical\n        system defined by the Earth's mean equator and equinox, provide\n        an epoch time.  To get J2000.0 coordinates, for example:\n\n        >>> ra, dec, distance = ICRF([1, 2, 3]).radec(ts.J2000)\n        >>> print(ra, dec, sep='\\n')\n        04h 13m 43.32s\n        +53deg 17' 55.1\"\n\n        \"\"\"\n        position_au = self.position.au\n        if epoch is not None:\n            if isinstance(epoch, Time):\n                pass\n            elif isinstance(epoch, float):\n                epoch = Time(None, tt=epoch)\n            elif epoch == 'date':\n                epoch = self.t\n            else:\n                raise ValueError('the epoch= must be a Time object,'\n                                 ' a floating point Terrestrial Time (TT),'\n                                 ' or the string \"date\" for epoch-of-date')\n            position_au = einsum('ij...,j...->i...', epoch.M, position_au)\n        r_au, dec, ra = to_polar(position_au)\n        return (Angle(radians=ra, preference='hours'),\n                Angle(radians=dec, signed=True),\n                Distance(r_au))\n\n    def separation_from(self, another_icrf):\n        \"\"\"Return the angle between this position and another.\n\n        >>> print(ICRF([1,0,0]).separation_from(ICRF([1,1,0])))\n        45deg 00' 00.0\"\n\n        You can also compute separations across an array of positions.\n\n        >>> directions = ICRF([[1,0,-1,0], [0,1,0,-1], [0,0,0,0]])\n        >>> directions.separation_from(ICRF([0,1,0])).degrees\n        array([  90.,    0.,   90.,  180.])\n\n        \"\"\"\n        p1 = self.position.au\n        p2 = another_icrf.position.au\n        u1 = p1 / length_of(p1)\n        u2 = p2 / length_of(p2)\n        if u2.ndim > 1:\n            if u1.ndim == 1:\n                u1 = u1[:,None]\n        elif u1.ndim > 1:\n            u2 = u2[:,None]\n        c = dots(u1, u2)\n        return Angle(radians=arccos(clip(c, -1.0, 1.0)))\n\n    def ecliptic_position(self):\n        \"\"\"Compute J2000 ecliptic coordinates (x, y, z)\"\"\"\n        vector = _ECLIPJ2000.dot(self.position.au)\n        return Distance(vector)\n\n    def ecliptic_latlon(self):\n        \"\"\"Compute J2000 ecliptic coordinates (lat, lon, distance)\"\"\"\n        vector = _ECLIPJ2000.dot(self.position.au)\n        d, lat, lon = to_polar(vector)\n        return (Angle(radians=lat, signed=True),\n                Angle(radians=lon),\n                Distance(au=d))\n\n    def galactic_position(self):\n        \"\"\"Compute galactic coordinates (x, y, z)\"\"\"\n        vector = _GALACTIC.dot(self.position.au)\n        return Distance(vector)\n\n    def galactic_latlon(self):\n        \"\"\"Compute galactic coordinates (lat, lon, distance)\"\"\"\n        vector = _GALACTIC.dot(self.position.au)\n        d, lat, lon = to_polar(vector)\n        return (Angle(radians=lat, signed=True),\n                Angle(radians=lon),\n                Distance(au=d))\n\n    def to_skycoord(self, unit=None):\n        \"\"\"Convert this distance to an AstroPy ``SkyCoord`` object.\"\"\"\n        from astropy.coordinates import SkyCoord\n        from astropy.units import au\n        x, y, z = self.position.au\n        return SkyCoord(representation='cartesian', x=x, y=y, z=z, unit=au)\n\n    def _to_spice_frame(self, name):\n        vector = self.position.au\n        vector = inertial_frames[name].dot(vector)\n        d, dec, ra = to_polar(vector)\n        return (Angle(radians=ra, preference='hours', signed=True),\n                Angle(radians=dec),\n                Distance(au=d))\n\n    def from_altaz(self, alt=None, az=None, alt_degrees=None, az_degrees=None):\n        \"\"\"Generate an Apparent position from an altitude and azimuth.\n\n        The altitude and azimuth can each be provided as an `Angle`\n        object, or else as a number of degrees provided as either a\n        float or a tuple of degrees, arcminutes, and arcseconds::\n\n            alt=Angle(...), az=Angle(...)\n            alt_degrees=23.2289, az_degrees=142.1161\n            alt_degrees=(23, 13, 44.1), az_degrees=(142, 6, 58.1)\n\n        \"\"\"\n        # TODO: should this method live on another class?\n        R = self.observer_data.altaz_rotation if self.observer_data else None\n        if R is None:\n            raise ValueError('only a position generated by a topos() call'\n                             ' knows the orientation of the horizon'\n                             ' and can understand altitude and azimuth')\n        alt = _interpret_angle('alt', alt, alt_degrees)\n        az = _interpret_angle('az', az, az_degrees)\n        r = 0.1  # close enough to make gravitational refraction irrelevant\n        p = from_polar(r, alt, az)\n        p = einsum('ji...,j...->i...', R, p)\n        return Apparent(p)\n\n\n# For compatibility with my original name for the class.  Not an\n# important enough change to warrant a deprecation error for users, so:\nICRS = ICRF\n\n\nclass Geometric(ICRF):\n    \"\"\"An (x,y,z) vector between two instantaneous position.\n\n    A geometric position is the difference between the Solar System\n    positions of two bodies at exactly the same instant.  It is *not*\n    corrected for the fact that, in real physics, it will take time for\n    light to travel from one position to the other.\n\n    \"\"\"\n    def altaz(self, temperature_C=None, pressure_mbar='standard'):\n        \"\"\"Compute (alt, az, distance) relative to the observer's horizon\n\n        The altitude returned is an `Angle` in degrees above the\n        horizon, while the azimuth is the compass direction in degrees\n        with north being 0 degrees and east being 90 degrees.\n\n        \"\"\"\n        return _to_altaz(self.position.au, self.observer_data,\n                         temperature_C, pressure_mbar)\n\n\nclass Barycentric(ICRF):\n    \"\"\"An (x, y, z) position measured from the Solar System barycenter.\n\n    Each barycentric position is an ICRS position vector, meaning that\n    the coordinate axes are defined by the high-precision ICRF that has\n    replaced the old J2000.0 reference frame, and the coordinate origin\n    is the BCRS gravitational center of the Solar System.\n\n    Skyfield generates a `Barycentric` position whenever you ask a Solar\n    System body for its location at a particular time:\n\n    >>> t = ts.utc(2003, 8, 29)\n    >>> mars.at(t)\n    <Barycentric position and velocity at date t center=0 target=499>\n\n    \"\"\"\n    def observe(self, body):\n        \"\"\"Compute the `Astrometric` position of a body from this location.\n\n        To compute the body's astrometric position, it is first asked\n        for its position at the time `t` of this position itself.  The\n        distance to the body is then divided by the speed of light to\n        find how long it takes its light to arrive.  Finally, the light\n        travel time is subtracted from `t` and the body is asked for a\n        series of increasingly exact positions to learn where it was\n        when it emitted the light that is now reaching this position.\n\n        >>> earth.at(t).observe(mars)\n        <Astrometric position and velocity at date t>\n\n        \"\"\"\n        p, v, light_time = body._observe_from_bcrs(self)\n        t = self.t\n        astrometric = Astrometric(p, v, t, observer_data=self.observer_data)\n        astrometric.light_time = light_time\n        return astrometric\n\n\n# TODO: pre-create a Barycentric object representing the SSB, and make\n# it possible for it to observe() a planet.\n\n\nclass Astrometric(ICRF):\n    \"\"\"An astrometric (x, y, z) position relative to a particular observer.\n\n    The *astrometric position* of a body is its position relative to an\n    observer, adjusted for light-time delay: the position of the body\n    back when it emitted (or reflected) the light that is now reaching\n    the observer's eyes or telescope.\n\n    Astrometric positions are usually generated in Skyfield by calling\n    the `Barycentric` method `observe()` to determine where a body will\n    appear in the sky relative to a specific observer.\n\n    \"\"\"\n    def apparent(self):\n        \"\"\"Compute an :class:`Apparent` position for this body.\n\n        This applies two effects to the position that arise from\n        relativity and shift slightly where the other body will appear\n        in the sky: the deflection that the image will experience if its\n        light passes close to large masses in the Solar System, and the\n        aberration of light caused by the observer's own velocity.\n\n        >>> earth.at(t).observe(mars).apparent()\n        <Apparent position at date t>\n\n        These transforms convert the position from the BCRS reference\n        frame of the Solar System barycenter and to the reference frame\n        of the observer.  In the specific case of an Earth observer, the\n        output reference frame is the GCRS.\n\n        \"\"\"\n        t = self.t\n        position_au = self.position.au.copy()\n        observer_data = self.observer_data\n        gcrs_position = observer_data.gcrs_position\n\n        if gcrs_position is None:\n            include_earth_deflection = array((False,))\n        else:\n            limb_angle, nadir_angle = compute_limb_angle(\n                position_au, gcrs_position)\n            include_earth_deflection = nadir_angle >= 0.8\n\n        add_deflection(position_au, observer_data.bcrs_position,\n                       observer_data.ephemeris, t, include_earth_deflection)\n\n        add_aberration(position_au, observer_data.bcrs_velocity,\n                       self.light_time)\n\n        return Apparent(position_au, t=t, observer_data=observer_data)\n\n\nclass Apparent(ICRF):\n    \"\"\"An apparent (x, y, z) position relative to a particular observer.\n\n    The *apparent position* of a body is its position relative to an\n    observer adjusted for light-time delay, deflection (light rays\n    bending as they pass large masses like the Sun or Jupiter), and\n    aberration (light slanting because of the observer's motion through\n    space).\n\n    Included in aberration is the relativistic transformation that takes\n    the position out of the BCRS centered on the solar system barycenter\n    and into the reference frame of the observer.  In the case of an\n    Earth observer, the transform takes the coordinate into the GCRS.\n\n    \"\"\"\n    def altaz(self, temperature_C=None, pressure_mbar='standard'):\n        \"\"\"Compute (alt, az, distance) relative to the observer's horizon\n\n        The altitude returned is an `Angle` in degrees above the\n        horizon, while the azimuth is the compass direction in degrees\n        with north being 0 degrees and east being 90 degrees.\n\n        \"\"\"\n        return _to_altaz(self.position.au, self.observer_data,\n                         temperature_C, pressure_mbar)\n\n\nclass Geocentric(ICRF):\n    \"\"\"An (x,y,z) position measured from the geocenter.\"\"\"\n\n\ndef _to_altaz(position_au, observer_data, temperature_C, pressure_mbar):\n    \"\"\"Compute (alt, az, distance) relative to the observer's horizon.\n\n    \"\"\"\n    elevation_m = observer_data.elevation_m\n    R = observer_data.altaz_rotation\n\n    if (elevation_m is None) or (R is None):\n        raise ValueError('to compute an altazimuth position, you must'\n                         ' observe from a specific Earth location that'\n                         ' you specify using a Topos instance')\n\n    # TODO: wobble\n\n    position_au = einsum('ij...,j...->i...', R, position_au)\n    r_au, alt, az = to_polar(position_au)\n\n    if temperature_C is None:\n        alt = Angle(radians=alt)\n    else:\n        if temperature_C == 'standard':\n            temperature_C = 10.0\n        if pressure_mbar == 'standard':\n            pressure_mbar = 1010.0 * exp(-elevation_m / 9.1e3)\n        alt = refract(alt * RAD2DEG, temperature_C, pressure_mbar)\n        alt = Angle(degrees=alt)\n\n    return alt, Angle(radians=az), Distance(r_au)\n\n\ndef ITRF_to_GCRS(t, rITRF):  # todo: velocity\n\n    # Todo: wobble\n\n    spin = rot_z(t.gast * tau / 24.0)\n    position = einsum('ij...,j...->i...', spin, array(rITRF))\n    return einsum('ij...,j...->i...', t.MT, position)\n", "meta": {"hexsha": "53083d8c97d71f45ed8996b727e3ec8c21ccdb0f", "size": 15470, "ext": "py", "lang": "Python", "max_stars_repo_path": "skyfield/positionlib.py", "max_stars_repo_name": "joernu76/python-skyfield", "max_stars_repo_head_hexsha": "835123f1d3280190d979810c1a44fd713c271822", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "skyfield/positionlib.py", "max_issues_repo_name": "joernu76/python-skyfield", "max_issues_repo_head_hexsha": "835123f1d3280190d979810c1a44fd713c271822", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "skyfield/positionlib.py", "max_forks_repo_name": "joernu76/python-skyfield", "max_forks_repo_head_hexsha": "835123f1d3280190d979810c1a44fd713c271822", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5485436893, "max_line_length": 80, "alphanum_fraction": 0.630833872, "include": true, "reason": "from numpy,from astropy", "num_tokens": 3835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.2845759920814681, "lm_q1q2_score": 0.18333100268983518}}
{"text": "# read snapshot and obtain multiple systems\nimport collections\nfrom scipy import spatial as sp\nfrom .base import *\nfrom .bse import *\n\nG_MSUN_PC_MYR=0.00449830997959438 # Msun, pc, myr\nG_HENON=1 # Henon unit\nHEADER_OFFSET=24 # header offset in bytes for snapshots with the BINARY format\nHEADER_OFFSET_WITH_CM=72 # header offset with center-of-the-mass data in bytes for snapshots with the BINARY format\n\nclass PeTarDataHeader():\n    \"\"\" Petar snapshot data header\n    members:\n        fid: int \n           file id\n        n: int \n           number of particles\n        time: float \n           time of snapshot\n        *pos_offset: list of float (length of 3)\n           position offset of particle system\n        *vel_offset: list of float (length of 3)\n           velocity offset of particle system\n  \n        pos_offset and vel_offset only exist when keyword argument 'external_mode' is not none\n    \"\"\"\n\n    def __init__(self, _filename=None, **kwargs):\n        \"\"\" Initial data header\n        \n        Parameters:\n        -----------\n        _filename: string\n            PeTar snapshot file name to read the header, if not provide, all members are initialized to zero (None)\n        kwargs: dict\n            Keyword arguments:\n            snapshot_format: string (ascii)\n                Data format of snapshot files: binary or ascii\n            external_mode: string (none)\n                PeTar external mode (set in configure): galpy, none \n                If not none, this option indicates the pos_offset and vel_offset exists \n        \"\"\"\n        self.fid = int(0)\n        self.n = int(0)\n        self.time = 0.0\n        if ('external_mode' in kwargs.keys()):\n            if (kwargs['external_mode']!='none'):\n                self.pos_offset=[0.0,0.0,0.0]\n                self.vel_offset=[0.0,0.0,0.0]\n        \n        if (_filename!=None): self.read(_filename,**kwargs)\n\n    def read(self, _filename, **kwargs):\n        \"\"\" Read snapshot file to obtain the header information\n\n        Parameters:\n        -----------\n        _filename: string\n            PeTar snapshot file name to read the header\n        kwargs: dict\n            Keyword arguments:\n            snapshot_format: string (ascii)\n                Data format of snapshot files: binary or ascii\n            external_mode: string (none)\n                PeTar external mode (set in configure): galpy, none \n                If not none, this option indicates the pos_offset and vel_offset exists \n        \"\"\"\n        snapshot_format='ascii'\n        if ('snapshot_format' in kwargs.keys()): snapshot_format=kwargs['snapshot_format']\n        offset_flag=False\n        if ('external_mode' in kwargs.keys()):\n            if (kwargs['external_mode']!='none'): offset_flag=True\n\n        if (snapshot_format=='ascii'):\n            fp = open(_filename, 'r')\n            header=fp.readline()\n            header_items=header.split()\n            if (offset_flag):\n                if (len(header_items)!=9):\n                    raise ValueError('Snapshot header item number mismatch! Need 9 (file_id, N, time, xcm, ycm, zcm, vxcm, vycm, vzcm), got %d. Make sure the external_mode keyword set correctly.' % len(header_items))\n\n                file_id, n_glb, t, x, y, z, vx, vy, vz = header_items\n                fp.close()\n\n                self.fid = int(file_id)\n                self.n = int(n_glb)\n                self.time = float(t)\n                self.pos_offset = [float(x),float(y),float(z)]\n                self.vel_offset = [float(vx),float(vy),float(vz)]\n            else:\n                if (len(header_items)!=3):\n                    raise ValueError('Snapshot header item number mismatch! Need 3 (file_id, N, time), got %d. Make sure the external_mode keyword set correctly.' % len(header_items))\n\n                file_id, n_glb, t = header_items\n                fp.close()\n\n                self.fid = int(file_id)\n                self.n = int(n_glb)\n                self.time = float(t)\n\n        elif (snapshot_format=='binary'):\n            if (offset_flag):\n                fp = np.fromfile(_filename, dtype=np.dtype([('file_id',np.int64),('n_glb',np.int64),('time',np.float64),('x',np.float64),('y',np.float64),('z',np.float64),('vx',np.float64),('vy',np.float64),('vz',np.float64)]),count=1)\n                self.file_id = fp['file_id'][0]\n                self.n_glb = fp['n_glb'][0]\n                self.time = fp['time'][0]\n                self.pos_offset = [fp['x'][0], fp['y'][0], fp['z'][0]]\n                self.vel_offset = [fp['vx'][0], fp['vy'][0], fp['vz'][0]]\n            else:\n                fp = np.fromfile(_filename, dtype=np.dtype([('file_id',np.int64),('n_glb',np.int64),('time',np.float64)]),count=1)\n                self.file_id = fp['file_id'][0]\n                self.n_glb = fp['n_glb'][0]\n                self.time = fp['time'][0]\n        else: \n            raise ValueError('Snapshot format unknown, should be binary or ascii, given', snapshot_format)\n\nclass SimpleParticle(DictNpArrayMix):\n    \"\"\" Simple particle class with only mass, postion, velocity\n    keys: (class members)\n        mass (1D): mass\n        pos (2D,3): postion x, y, z\n        vel (2D,3): velocity vx, vy, vz\n    \"\"\"\n    def __init__(self, _dat=None, _offset=int(0), _append=False, **kwargs):\n        \"\"\" DictNpArrayMix type initialzation, see help(DictNpArrayMix.__init__)\n        \"\"\"\n        keys = [['mass', np.float64], ['pos', (np.float64, 3)], ['vel', (np.float64, 3)]]\n        DictNpArrayMix.__init__(self, keys, _dat, _offset, _append, **kwargs)\n\n    def calcR2(self):\n        \"\"\" calculate distance square, r2, and add it as a class member\n        \"\"\"\n        if (not 'r2' in self.__dict__.keys()): \n            self.ncols += 1\n            self.keys.append(['r2',1])\n        self.r2 = vecDot(self.pos,self.pos)\n\n    def calcEkin(self):\n        \"\"\" calculate kinetic energy\n        \"\"\"\n        if (not 'ekin' in self.__dict__.keys()): \n            self.ncols += 1\n            self.keys.append(['ekin',1])\n        self.ekin = 0.5*vecDot(self.vel,self.vel)*self.mass\n\n    def correctCenter(self, cm_pos, cm_vel):\n        self.pos -= cm_pos\n        self.vel -= cm_vel\n\nclass Particle(SimpleParticle):\n    \"\"\" Particle class \n        The particle data of PeTar. Depending on the compile configuration of PeTar, \n        The data structures (columns) of the particle snapshots are different.\n        Using the correct keyword arguments in the initialization to control the member definition (Keys)\n\n    keys: (class members)\n        The final keys are a combination of sub keys depending on keyword arguments (kwargs) of initial function\n\n        Sub key list:\n\n        std: [inherit SimpleParticle]\n        bstat: binary_state: binary interruption state \n        se: radius:        (1D): radius for merger checker\n            dm:            (1D): mass loss\n            time_record    (1D): last time of interruption check\n            time_interrupt (1D): next interruption time\n        bse: star  (SSEStarParameter): BSE based stellar evolution parameters\n        ptcl: r_search (1D): searching radius\n              id       (1D): identification\n              mass_bk  (1D): artificial particle parameter 1 \n              status   (1D): artificial particle parameter 2\n              r_in     (1D): changeover function inner boundary\n              r_out    (1D): changeover function outer boundary\n        hermite: dt    (1D): time step\n                 time  (1D): current time\n                 acc   (2D,3): acceleration x, y, z\n                 jerk  (2D,3): acceleration derivative x, y, z\n                 pot   (1D): potential\n        soft: acc_soft (2D,3): long-range interaction acceleration (particle-tree) x, y, z\n              pot      (1D): total potential\n              pot_soft (1D): long-range interaction potential\n              *pot_ext  (1D): external potential (only exist when keyword argument 'external_mode' is not 'none')\n              n_nb:    (1D): number of neighbors (short-interaction)\n        hermite: dt   (1D): hermite time step size\n                 time (1D): current time of particle\n                 acc  (2D,3): acceleration \n                 jerk (2D,3): first derivates of acceleration\n                 pot  (1D): potential\n\n        ends: the end part of keys depends on kwargs['particle_type']:\n             hermite:   ptcl + hermite\n             hard:      ptcl\n             soft (default): ptcl + soft \n\n        final: the final combination of keys depends on kwargs['interrupt_mode']:\n             base:      std + bstat + se + ends\n             bse:       std + bstat + se + bse + ends\n             none (default): std + bstat + ends\n\n    \"\"\"\n\n    def __init__ (self, _dat=None, _offset=int(0), _append=False, **kwargs):\n        \"\"\" DictNpArrayMix type initialzation, see help(DictNpArrayMix.__init__)\n\n        Parameters\n        ----------\n        keyword arguments:\n            particle_type: string (soft)\n               basic particle type: hermite, hard, soft\n            interrupt_mode: string (none)\n               PeTar interrupt mode (set in configure): base, bse, mobse, none\n               This option indicates whether columns of stellar evolution exist\n            external_mode: string (none)\n               PeTar external mode (set in configure): galpy, none \n               This option indicates whether the column of externa potential exist\n        \"\"\"\n\n        keys_bstat = [['binary_state',np.int64]]\n        keys_se  = [['radius',np.float64],['dm',np.float64],['time_record',np.float64],['time_interrupt',np.float64]]\n        keys_ptcl_add = [['r_search',np.float64], ['id',np.int64], ['mass_bk',np.int64], ['status',np.int64], ['r_in',np.float64], ['r_out',np.float64]]\n        keys_hermite_add = [['dt',np.float64],['time',np.float64],['acc',(np.float64,3)],['jerk',(np.float64,3)],['pot',np.float64]]\n        keys_soft_add = [['acc_soft',(np.float64,3)], ['pot',np.float64], ['pot_soft',np.float64], ['n_nb',np.int64]]\n        if ('external_mode' in kwargs.keys()):\n            if (kwargs['external_mode']!='none'):\n                keys_soft_add = [['acc_soft',(np.float64,3)], ['pot',np.float64], ['pot_soft',np.float64], ['pot_ext',np.float64], ['n_nb',np.int64]]\n\n        keys_end =  keys_ptcl_add + keys_soft_add\n        if ('particle_type' in kwargs.keys()):\n            if (kwargs['particle_type']=='hermite'):\n                keys_end = keys_ptcl_add + keys_hermite_add\n            elif (kwargs['particle_type']=='hard'):\n                keys_end = keys_ptcl_add\n        keys=keys_bstat+keys_end\n        if ('interrupt_mode' in kwargs.keys()):\n            if (kwargs['interrupt_mode']=='base'):\n                keys = keys_bstat+keys_se+keys_end\n            elif ('bse' in kwargs['interrupt_mode']):\n                keys = keys_bstat+keys_se+[['star',SSEStarParameter]]+keys_end\n            \n        SimpleParticle.__init__(self, _dat, _offset, _append, **kwargs)\n        DictNpArrayMix.__init__(self, keys, _dat, _offset+self.ncols, True, **kwargs)\n\n    def calcEtot(self):\n        \"\"\" Calculate total energy and add it as the member, etot\n        \"\"\"\n        if (not 'etot' in self.__dict__.keys()): \n            self.ncols += 1\n            self.keys.append(['etot',np.float64])\n        self.etot = self.ekin + self.mass*self.pot\n\ndef calculateParticleCMDict(pcm, _p1, _p2):\n    \"\"\" Calculate the center-of-the-mass of two particle sets\n    \n    Parameters\n    ----------\n    _p1: inherited SimpleParticle\n        particle set 1\n    _p2: inherited SimpleParticle \n        particle set 2, should have the same size as _p1\n    pcm: dict \n        particle center-of-the-mass, should include keys: 'mass','pos','vel'.\n    \"\"\"\n    if (issubclass(type(_p1), SimpleParticle)) & (issubclass(type(_p2),SimpleParticle)):\n        pcm['mass'] = _p1.mass + _p2.mass\n        pcm['pos']  = np.array(list(map(lambda m1,x1,m2,x2:(m1*x1+m2*x2)/(m1+m2), _p1.mass, _p1.pos, _p2.mass, _p2.pos)))\n        pcm['vel']  = np.array(list(map(lambda m1,x1,m2,x2:(m1*x1+m2*x2)/(m1+m2), _p1.mass, _p1.vel, _p2.mass, _p2.vel)))\n    elif (isinstance(_p1, collections.OrderedDict)) & (isinstance(_p2,collections.OrderedDict)) | (isinstance(_p1, dict)) & (isinstance(_p2, dict)):\n        pcm['mass'] = _p1['mass'] + _p2['mass']\n        pcm['pos']  = np.array(list(map(lambda m1,x1,m2,x2:(m1*x1+m2*x2)/(m1+m2), _p1['mass'], _p1['pos'], _p2['mass'], _p2['pos'])))\n        pcm['vel']  = np.array(list(map(lambda m1,x1,m2,x2:(m1*x1+m2*x2)/(m1+m2), _p1['mass'], _p1['vel'], _p2['mass'], _p2['vel'])))\n    else:\n        raise ValueError('Initial fail, date type should be Particle or collections.OrderDict, given',type(_p1))\n\nclass Binary(SimpleParticle):\n    \"\"\" Binary class\n        The binary (tree) data. Depending on the definition of two members \n        (keyword argument member_particle_type(|_one|_two), \n        The binary can refer to any type of multiple system.\n\n    Keys:\n        The final keys depends on kwargs of initial function\n  \n        kwargs['simple_mode'] (bool)\n            True: (default)\n                mass (1D): total mass of two components\n                pos  (2D,3): c.m. position x, y, z\n                vel  (2D,3): c.m. velocity vx, vy, vz\n                rrel (1D): relative distance\n                semi (1D): semi-major axis\n                ecc  (1D): eccentricity\n                p1   (member_particle_type_one) component one\n                p2   (member_particle_type_two) component two\n            False:\n                mass (1D): total mass of two components\n                pos  (2D,3): c.m. position x, y, z\n                vel  (2D,3): c.m. velocity vx, vy, vz\n                m1   (1D): component 1 mass\n                m2   (1D): component 2 mass\n                rrel (1D): relative distance\n                semi (1D): semi-major axis\n                am   (2D,3): specific angular momemtum x, y, z\n                L    (2D,3): angular momemtum x, y, z\n                eccvec  (2D,3): eccentric vector\n                incline (1D): inclination\n                rot_horizon (1D): frame rotational angle in x-y plane (longitude of ascending node)\n                ecc  (1D): eccentricity\n                rot_self (1D): frame rotational angle in orbital plane (argument of periapsis)\n                ecca (1D): eccentric anomaly\n                period (1D): period\n                t_peri (1D): time to peri-center\n                p1 (member_particle_type_one) component one\n                p2 (member_particle_type_two) component two\n\n        The member_particle_type(|_one|_two) is given by keyword arguments:\n           'member_particle_type' (for both members),'member_particle_type_one','member_particle_type_two'.\n        In default, it is petar.SimpleParticle.\n        If a type (e.g., petar.Particle) is given, the member is a single star.\n        If a list with two members (e.g., [petar.Particle, petar.Particle]) is given, \n        the member is a binary with two single stars.\n        A hierarchical list can be provided, e.g., [petar.Particle, [petar.Particle, petar.Particle]]\n        to indicate a triple system.\n               \n    \"\"\"\n    def __init__ (self, _p1=None, _p2=None, _offset=int(0), _append=False, **kwargs):\n        \"\"\"\n        Parameters\n        ----------\n        _p1: inherited SimpleParticle | 2D numpy.ndarray | Binary | None\n            If the type is inherited SimpleParticle, it is the first component of binary (_p2 should be the same type).\n            If the type is Binary, the class instance is initialized by copy the data of _p1.\n            If it is None, initialize class with empty data\n        _p2: inherited SimpleParticle | None\n            If the type is inherited SimpleParticle, it is the second component of binary \n            If it is None, _p1 should be either 2D numpy.ndarray or Bina\n        _offset: int (0)\n            Reading column offset of _dat if it is 2D np.ndarray\n        _append: bool (False)\n            If true, append keys and ncols to the current class instead of create new class members\n\n        keyword arguments:\n            simple_mode: bool (True)\n                If True, only calculate semi and ecc, save computing time significantly\n            G: float (1.0)\n                Gravitational constant\n            member_particle_type: type or list (SimpleParticle)\n                Type of component particle (both)\n            member_particle_type_one: type or list (SimpleParticle)\n                Type of 1st component\n            member_particle_type_two: type or list (SimpleParticle)\n                Type of 2nd component \n        \"\"\"\n        G=1\n        simple_mode=True\n        member_particle_type=SimpleParticle\n        member_particle_type_one=member_particle_type\n        member_particle_type_two=member_particle_type\n        \n        if 'G' in kwargs.keys(): G=kwargs['G']\n        if 'simple_mode' in kwargs.keys(): simple_mode=kwargs['simple_mode']\n        if 'member_particle_type' in kwargs.keys(): \n            member_particle_type=kwargs['member_particle_type']\n            member_particle_type_one=member_particle_type\n            member_particle_type_two=member_particle_type\n        if 'member_particle_type_one' in kwargs.keys(): member_particle_type_one=kwargs['member_particle_type_one']\n        if 'member_particle_type_two' in kwargs.keys(): member_particle_type_two=kwargs['member_particle_type_two']\n\n        if (issubclass(type(_p1), SimpleParticle)) & (issubclass(type(_p2),SimpleParticle)):\n            if (simple_mode): \n                self.keys = [['mass',np.float64],['pos',(np.float64,3)],['vel',(np.float64,3)],['rrel',np.float64],['semi',np.float64],['ecc',np.float64],['p1',(type(_p1),_p1.initargs)], ['p2', (type(_p2),_p2.initargs)]]\n                self.particleToSemiEcc(_p1, _p2, G)\n                self.ncols= int(10)\n            else:\n                self.keys = [['mass',np.float64],['pos',(np.float64,3)],['vel',(np.float64,3)],['m1',np.float64],['m2',np.float64],['rrel',np.float64],['semi',np.float64],['am',(np.float64,3)],['L',(np.float64,3)],['eccvec',(np.float64,3)],['incline',np.float64],['rot_horizon',np.float64],['ecc',np.float64],['rot_self',np.float64],['ecca',np.float64],['period',np.float64],['t_peri',np.float64],['p1',(type(_p1),_p1.initargs)], ['p2', (type(_p2),_p2.initargs)]]\n                self.particleToBinary(_p1, _p2, G)\n                self.ncols= int(27)\n            self.p1 = _p1\n            self.p2 = _p2\n            self.size = _p1.size\n            self.ncols += self.p1.ncols + self.p2.ncols\n            self.initargs = kwargs.copy()\n            binary_tree = self.createMemberParticleTypeTree()\n            self.initargs['member_particle_type_one']=binary_tree[0]\n            self.initargs['member_particle_type_two']=binary_tree[1]\n        elif (_p2==None):\n            type_one = member_particle_type_one\n            if (type(member_particle_type_one) == list):\n                type_one = (Binary, {'member_particle_type_one':member_particle_type_one[0],'member_particle_type_two':member_particle_type_one[1]})\n            type_two = member_particle_type_two\n            if (type(member_particle_type_two) == list):\n                type_two = (Binary, {'member_particle_type_one':member_particle_type_two[0],'member_particle_type_two':member_particle_type_two[1]})\n            if (simple_mode):\n                keys = [['rrel',np.float64],['semi',np.float64],['ecc',np.float64],['p1',type_one], ['p2', type_two]]\n                SimpleParticle.__init__(self, _p1, _offset, _append, **kwargs)\n                DictNpArrayMix.__init__(self, keys, _p1, _offset+self.ncols, True, **kwargs)\n            else:\n                keys=[['m1',np.float64],['m2',np.float64],['rrel',np.float64],['semi',np.float64],['am',(np.float64,3)],['L',(np.float64,3)],['eccvec',(np.float64,3)],['incline',np.float64],['rot_horizon',np.float64],['ecc',np.float64],['rot_self',np.float64],['ecca',np.float64],['period',np.float64],['t_peri',np.float64],['p1', type_one],['p2', type_two]]\n                SimpleParticle.__init__(self, _p1, _offset, _append, **kwargs)\n                DictNpArrayMix.__init__(self, keys, _p1, _offset+self.ncols, True, **kwargs)\n            self.initargs = kwargs.copy()\n        else:\n            raise ValueError('Initial fail, date type should be Particle (2), Binary (1) or no argument (0)')\n\n    def calcEkin(self):\n        \"\"\" Calculate c.m. kinetic energy, ekin, and add it as a member\n        \"\"\"\n        ekin = 0.5*vecDot(self.vel,self.vel)*self.mass\n        self.addNewMember('ekin',ekin)\n\n    def calcEtot(self):\n        \"\"\" Calculate c.m. total energy (binary energy is excluded) , etot, and add it as a member\n        \"\"\"\n        etot = self.ekin + self.mass*self.pot\n        self.addNewMember('etot',etot)\n\n    def calcR2(self, member_also=False):\n        \"\"\" Calculate c.m. distance square, r2, and add it as a member\n        \"\"\"\n        r2 = vecDot(self.pos,self.pos)\n        self.addNewMember('r2',r2)\n        if (member_also):\n            ncols = self.p1.ncols + self.p2.ncols\n            self.p1.calcR2()\n            self.p2.calcR2()\n            ncols = self.p1.ncols + self.p2.ncols - ncols\n            self.ncols += ncols\n\n    def calcEbin(self):\n        \"\"\" Calculate binding energy, ebin, and add it as a member \n            Notice G should be given the correct value in initialization (keyword argument 'G')\n        \"\"\"\n        ebin = self.initargs['G']*self.p1.mass*self.p2.mass/(2*self.semi)\n        self.addNewMember('ebin',ebin)\n\n    def calcPot(self):\n        \"\"\" Calculate potential of c.m., pot, and add it as a member\n            Notice G should be given the correct value in initialization (keyword argument 'G')\n        \"\"\"\n        G = self.initargs['G']\n        pos_b1 = self.p1.pos\n        pos_b2 = self.p2.pos\n        m_b1 = self.p1.mass\n        m_b2 = self.p2.mass\n        dr = pos_b1-pos_b2\n        dr2 = vecDot(dr,dr)\n        invr = 1/np.sqrt(dr2)\n        pot_b1 = self.p1.pot + G*m_b2*invr\n        pot_b2 = self.p2.pot + G*m_b1*invr\n        pot = (m_b2*pot_b1 + m_b1*pot_b2)/self.mass\n        self.addNewMember('pot',pot)\n\n    def generateBinaryID(self):\n        \"\"\" Use CantorPairing to map two components id to one binary id\n            Add new member bid \n        \"\"\"\n        bid = cantorPairing(self.p1.id, self.p2.id)\n        self.addNewMember('bid',bid)\n            \n    def correctCenter(self, cm_pos, cm_vel):\n        \"\"\" Corrent c.m and component position and velocity by subtracting cm_pos and cm_vel\n        \"\"\"\n        self.pos -= cm_pos\n        self.vel -= cm_vel\n        self.p1.correctCenter(cm_pos, cm_vel)\n        self.p2.correctCenter(cm_pos, cm_vel)\n\n    def particleToSemiEcc(self, _p1, _p2, _G):\n        \"\"\" Calculate relative distance, semi-major axis and eccentricity from particle pairs\n\n        Parameters\n        ----------\n        _p1, _p2: inherited SimpleParticle\n            Particle pair data set\n        _G: float\n            Gravitational constant\n\n        \"\"\"\n        calculateParticleCMDict(self.__dict__, _p1, _p2)\n\n        dr = (_p1.pos - _p2.pos)\n        dv = (_p1.vel - _p2.vel)\n        \n        dr2  = (dr*dr).sum(axis=1)\n        dv2  = (dv*dv).sum(axis=1)\n        rvdot= (dr*dv).sum(axis=1)\n    \n        dr   = np.sqrt(dr2)\n        m    = (_p1.mass+_p2.mass)\n        semi = 1.0/(2.0/dr - dv2/(_G*m))\n\n        dr_semi = 1.0 - dr/semi\n        ecc = np.sqrt(dr_semi*dr_semi + rvdot*rvdot/(_G*m*semi))\n\n        self.rrel = dr\n        self.semi = semi\n        self.ecc  = ecc\n\n    def particleToBinary(self, _p1, _p2, _G):\n        \"\"\" Calculate binary orbit from particle pairs\n\n        Parameters\n        ----------\n        _p1, _p2: inherited SimpleParticle\n            Particle pair data set\n        _G: float\n            Gravitational constant\n\n        \"\"\"\n        binary=self.__dict__\n     \n        def regular_sign(_a,_a_err):\n            _a[(_a<0) & (_a>-_a_err)] *= -1\n     \n        f_err = 1e-2\n        calculateParticleCMDict(binary, _p1, _p2)\n\n        binary['m1'] = _p1.mass\n        binary['m2'] = _p2.mass\n        m_tot = binary['mass']\n        Gm_tot = _G*m_tot\n        \n        dx = _p1.pos-_p2.pos\n        dv = _p1.vel-_p2.vel\n        dr2  = vecDot(dx,dx)\n        dv2  = vecDot(dv,dv)\n        rvdot= vecDot(dx,dv)\n        dr   = np.sqrt(dr2)\n        binary['rrel'] = np.sqrt(dr2)\n     \n        inv_dr = 1.0 / binary['rrel']\n        binary['semi'] = 1.0 / (2.0*inv_dr - dv2 / Gm_tot)\n        binary['am'] = np.cross(dx,dv)\n        dp = _p1.vel*_p1.mass[:,None] - _p2.vel*_p2.mass[:,None]\n        binary['L'] = np.cross(dx,dp)\n        binary['eccvec'] = np.cross(dv,binary['am'])/Gm_tot[:,None]-dx/dr[:,None]\n     \n        binary['incline'] = np.arctan2(np.sqrt(binary['am'][:,0]*binary['am'][:,0]+binary['am'][:,1]*binary['am'][:,1]),binary['am'][:,2])\n        binary['rot_horizon'] = np.arctan2(binary['am'][:,0],-binary['am'][:,1])\n        regular_sign(binary['am'][:,0],f_err)\n        regular_sign(binary['am'][:,1],f_err)\n        #binary['rot_horizon'][binary['rot_horizon']<0] += np.pi\n        binary['rot_horizon'][binary['am'][:,1]==0.0]=0.0\n     \n        cosOMG = np.cos(binary['rot_horizon'])\n        sinOMG = np.sin(binary['rot_horizon'])\n        cosinc = np.cos(binary['incline'])\n        sininc = np.sin(binary['incline'])\n     \n        pos_bar_x =   dx[:,0]*cosOMG + dx[:,1]*sinOMG\n        pos_bar_y = (-dx[:,0]*sinOMG + dx[:,1]*cosOMG)*cosinc + dx[:,2]*sininc\n        pos_bar_z = 0.0\n        vel_bar_x =   dv[:,0]*cosOMG + dv[:,1]*sinOMG\n        vel_bar_y = (-dv[:,0]*sinOMG + dv[:,1]*cosOMG)*cosinc + dv[:,2]*sininc\n        vel_bar_z = 0.0\n     \n        h = np.sqrt(np.sum(binary['am']*binary['am'],axis=1))\n        ecccosomg =  h/Gm_tot*vel_bar_y - pos_bar_x*inv_dr\n        eccsinomg = -h/Gm_tot*vel_bar_x - pos_bar_y*inv_dr\n        binary['ecc'] = np.sqrt( ecccosomg*ecccosomg + eccsinomg*eccsinomg )\n        regular_sign(ecccosomg,f_err)\n        regular_sign(eccsinomg,f_err)\n        binary['rot_self'] = np.arctan2(eccsinomg,ecccosomg)\n        #binary['rot_self'][binary['rot_self']<-np.pi+1e-5] += 2*np.pi \n        #binary['rot_self'][binary['rot_self']>=np.pi-1e-5] -= 2*np.pi\n     \n        regular_sign(pos_bar_y,f_err)\n        regular_sign(pos_bar_x,f_err)\n        phi = np.arctan2(pos_bar_y, pos_bar_x)\n        #phi[phi<-np.pi+1e-5] += 2*np.pi\n        #phi[phi>=np.pi-1e-5] -= 2*np.pi\n     \n        f = phi - binary['rot_self']\n        binary['ecca'] = np.arctan(np.sin(f)*np.sqrt(np.abs(binary['ecc']*binary['ecc'] - 1.0))/(binary['ecc']+np.cos(f)))\n        n = np.sqrt(Gm_tot/np.abs(binary['semi']*binary['semi']*binary['semi']))\n        binary['period'] = 8.0*np.arctan(1.0)/n\n        l = binary['ecca'] - binary['ecc']*np.sin(binary['ecca'])\n        binary['t_peri'] = l / n\n\n    def createMemberParticleTypeTree(self):\n        \"\"\" scan the members to create the member particle type tree list\n            For example, if the binary structure is a triple: p1: single, p2: binary.\n            Then the returned tree list is [particle_typename, [particle_typename, particle_typename]]\n        \"\"\"\n        binary_tree=[None,None]\n        if (type(self.p1) == Binary):\n            binary_tree[0] = self.p1.createMemberParticleTypeTree()\n        else:\n            binary_tree[0] = type(self.p1)\n        if (type(self.p2) == Binary):\n            binary_tree[1] = self.p2.createMemberParticleTypeTree()\n        else:\n            binary_tree[1] = type(self.p2)\n        return binary_tree\n\ndef findPair(_dat, _G, _rmax, use_kdtree=False, simple_binary=True):\n    \"\"\"  Find binaries in a particle data set\n    The scipy.spatial.cKDTree is used to find pairs\n\n    Parameters\n    ----------\n    _dat: inhermited SimpleParticle\n        Particle data set\n    _G: float\n        Gravitational constant\n    _rmax: float\n        Maximum binary separation\n    use_kdtree: bool (False)\n        If True, use KDtree to find all binaries (slow); otherwise use information from PeTar, only hard binaries are detected (fast)\n    simple_binary: bool (True)\n        If True, only calculate semi and ecc (fast); otherwise calculating all binary parameters (slow)\n\n    Return\n    ----------\n    kdt: KDtree structure if use_kdtree=True\n    single: type of _dat\n        single particle data set\n    binary: Binary(simple_mode=simple_binary, member_particle_type=type(single), G=_G)\n        binary data set\n    \"\"\"\n    if (not issubclass(type(_dat), SimpleParticle)):\n        raise ValueError(\"Data type wrong\",type(_dat),\" should be subclass of \", SimpleParticle)\n\n    if (use_kdtree):\n        # create KDTree\n        #print('create KDTree')\n        kdt=sp.cKDTree(_dat.pos)\n     \n        # find all close pairs\n        #pairs=kdt.query_pairs(_rmax*AU2PC)\n            \n        # only check nearest index\n        #pair_index=np.unique(np.transpose(np.array([np.array([x[0],x[1]]) for x in pairs])),axis=0)\n         \n        # find pair index and distance\n        #print('Get index')\n        r,index=kdt.query(_dat.pos,k=2)\n        pair_index=np.transpose(np.unique(np.sort(index,axis=1),axis=0))\n        #pair_index = np.transpose(index)\n\n        #index = kdt.query_pairs(_rmax,output_type='ndarray')\n        #pair_index = np.transpose(index)\n     \n        # two members\n        p1 = _dat[pair_index[0]]\n        p2 = _dat[pair_index[1]]\n     \n        # check orbits\n        #print('Create binary')\n        binary = Binary(p1, p2, G=_G, simple_mode=simple_binary)\n        apo =binary.semi*(binary.ecc+1.0)\n     \n        bsel= ((binary.semi>0) & (apo<_rmax))\n        binary = binary[bsel]\n        \n        single_mask = np.ones(_dat.size).astype(bool)\n        single_mask[pair_index[0][bsel]]=False\n        single_mask[pair_index[1][bsel]]=False\n        single = _dat[single_mask]\n        return kdt, single, binary\n    else:\n        idx = _dat.status.argsort()\n        dat_sort = _dat[idx]\n        status, index, inverse, counts = np.unique(dat_sort.status, return_index=True, return_inverse=True, return_counts=True)\n        binary_i1 = index[counts==2]\n        binary_i2 = binary_i1+1\n        binary = Binary(dat_sort[binary_i1], dat_sort[binary_i2], _G)\n        single = dat_sort[index[-1]:]\n\n        return single, binary\n\ndef findMultiple(_single, _binary, _G, _rmax, simple_binary=True):\n    \"\"\"  Find triples and quadruples from single and binary data\n    The scipy.spatial.cKDTree is used to find pairs\n\n    Parameters\n    ----------\n    _single: inhermited SimpleParticle\n        Single particle data set\n    _binary: Binary\n        Binary data set\n    _G: float\n        Gravitational constant\n    _rmax: float\n        Maximum binary separation\n    simple_binary: bool (True)\n        If True, only calculate semi and ecc (fast); otherwise calculating all binary parameters (slow)\n\n    Return\n    ----------\n    kdt: KDtree structure if use_kdtree=True\n    single: type of _dat\n        single particle data set\n    binary: Binary(simple_mode=simple_binary, member_particle_type=type(single), G=_G)\n        binary data set\n    triple: Binary(p1: type(single), p2: type(binary), G=_G)\n        triple data set\n    quadruple: Binary(p1: type(binary), p2: type(binary), G=_G)\n        quadruple (binary-binary) data set\n    \"\"\"\n    if (not issubclass(type(_single), SimpleParticle)):\n        raise ValueError(\"Data type wrong\",type(_single),\" should be subclass of \", SimpleParticle)\n\n    single_sin = SimpleParticle(_single)\n    binary_sin = SimpleParticle(_binary)\n    all_sin = join(single_sin, binary_sin)\n\n    # create KDTree\n    kdt=sp.cKDTree(all_sin.pos)\n     \n    # find pair index and distance\n    r,index=kdt.query(all_sin.pos,k=2)\n    pair_index=np.transpose(np.unique(np.sort(index,axis=1),axis=0))\n\n    bout_i1 = pair_index[0]\n    bout_i2 = pair_index[1]\n\n    Ns = _single.size\n    Nb = _binary.size\n    quad_pre_sel= (bout_i1>=Ns) & (bout_i2>=Ns)\n    tri_pre_sel = (bout_i1<Ns) & (bout_i2>=Ns)\n    bin_pre_sel = (bout_i1<Ns) & (bout_i2<Ns)\n\n    n_quad_pre = quad_pre_sel.sum()\n    n_tri_pre = tri_pre_sel.sum()\n    n_bin_pre = bin_pre_sel.sum()\n    if (bout_i1.size != n_quad_pre + n_tri_pre + n_bin_pre):\n        raise ValueError('Error: multiple index selection size miss match: dat:',bout_i1.size,'quad:',n_quad_pre,'tri:',n_tri_pre,'bin:',n_bin_pre)\n\n    s_del_index=np.array([]).astype(int)\n    b_del_index=np.array([]).astype(int)\n\n    quadruple = Binary(member_particle_type = [type(_single), type(_single)], **{**_single.initargs, 'G':_G, 'simple_mode':simple_binary})\n    if (quad_pre_sel.sum()):\n        q1_index = bout_i1[quad_pre_sel]-Ns\n        q2_index = bout_i2[quad_pre_sel]-Ns\n        quad_pre = Binary(_binary[q1_index], _binary[q2_index], **{**_single.initargs, 'G':_G, 'simple_mode':simple_binary})\n        apo = quad_pre.semi*(quad_pre.ecc+1.0)\n        quad_sel = (quad_pre.semi>0) & (apo<_rmax)\n        quadruple = quad_pre[quad_sel]\n        b_del_index=np.append(q1_index[quad_sel],q2_index[quad_sel])\n\n    triple = Binary(member_particle_type_one = type(_single), \n                    member_particle_type_two = [type(_single), type(_single)], \n                    **{**_single.initargs, 'G':_G, 'simple_mode':simple_binary})\n    if (tri_pre_sel.sum()):\n        s_index = bout_i1[tri_pre_sel]\n        b_index = bout_i2[tri_pre_sel]-Ns\n        tri_pre = Binary(_single[s_index], _binary[b_index], **{**_single.initargs, 'G':_G, 'simple_mode':simple_binary})\n        apo = tri_pre.semi*(tri_pre.ecc+1.0)\n        tri_sel = (tri_pre.semi>0) & (apo<_rmax)\n        triple = tri_pre[tri_sel]\n        b_del_index=np.append(b_del_index,b_index[tri_sel])\n        s_del_index=s_index[tri_sel]\n        \n    bmask=np.ones(Nb).astype(bool)\n    if (b_del_index.size>0): bmask[b_del_index]=False;\n    binary = _binary[bmask]\n\n    if (bin_pre_sel.sum()):\n        s1_index = bout_i1[bin_pre_sel]\n        s2_index = bout_i2[bin_pre_sel]\n        bin_pre = Binary(_single[s1_index], _single[s2_index], **{**_single.initargs, 'G':_G, 'simple_mode':simple_binary})\n        apo = bin_pre.semi*(bin_pre.ecc+1.0)\n        bin_sel = (bin_pre.semi>0) & (apo<_rmax)\n        binary.append(bin_pre[bin_sel])\n        s_del_index = np.concatenate((s_del_index, s1_index[bin_sel], s2_index[bin_sel]))\n\n    smask=np.ones(Ns).astype(bool)\n    smask[s_del_index]=False\n    single = _single[smask]\n\n    return single, binary, triple, quadruple\n\n", "meta": {"hexsha": "4ffef859c22b0425568a7ab1cee267deb88fe8e8", "size": 34258, "ext": "py", "lang": "Python", "max_stars_repo_path": "tools/analysis/data.py", "max_stars_repo_name": "GiacobboNicola/PeTar", "max_stars_repo_head_hexsha": "ed40946abbe346e2b0e72ae836add7e38bf851c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tools/analysis/data.py", "max_issues_repo_name": "GiacobboNicola/PeTar", "max_issues_repo_head_hexsha": "ed40946abbe346e2b0e72ae836add7e38bf851c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/analysis/data.py", "max_forks_repo_name": "GiacobboNicola/PeTar", "max_forks_repo_head_hexsha": "ed40946abbe346e2b0e72ae836add7e38bf851c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2609819121, "max_line_length": 463, "alphanum_fraction": 0.5935547901, "include": true, "reason": "from scipy", "num_tokens": 9224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.1833231618894886}}
{"text": "import os\nimport sys\nimport subprocess\nimport datetime\nimport numpy as np\nfrom astropy.io import ascii\nfrom astropy.table import Table, Column, vstack\nfrom astropy.wcs import WCS\nfrom astropy.wcs.utils import proj_plane_pixel_scales\nfrom astropy.coordinates import SkyCoord, ICRS\nfrom astropy.stats import gaussian_fwhm_to_sigma, sigma_clipped_stats\nfrom scipy.stats import norm, f\nfrom scipy.odr import *\nfrom scipy.optimize import minimize\nfrom scipy.ndimage.filters import median_filter, gaussian_filter1d\nfrom photutils import detect_sources, Background\n\n# For debugging\nimport matplotlib.pyplot as plt\nimport pdb\n\n# Add the AstroImage class\nsys.path.append(\"C:\\\\Users\\\\Jordan\\\\Libraries\\\\python\\\\AstroImage\")\nfrom AstroImage import AstroImage\nimport image_tools\n\n# This script will read in the background level estimated for each on-target\n# image in the previous step. The background level in dimmest parts of the\n# on-target image will be directly computed, and the residual between the direct\n# estimate and the interpolation will be stored. The distribution of these\n# residual will be used to estimate which interpolated background levels can be\n# trusted.\n\n#==============================================================================\n# *********************** CUSTOM USER CODE ************************************\n# this is where the user specifies where the raw data is stored\n# and some of the subdirectory structure to find the actual .FITS images\n#==============================================================================\n\n# This is the location of all PPOL reduction directory\nPPOL_dir = 'C:\\\\Users\\\\Jordan\\\\FITS_data\\\\Mimir_data\\\\PPOL_reduced'\n\n# Build the path to the S3_Asotremtry files\nS3dir = os.path.join(PPOL_dir, 'S3_Astrometry')\n\n# This is the location where all pyPol data will be saved\npyPol_data = 'C:\\\\Users\\\\Jordan\\\\FITS_data\\\\Mimir_data\\\\pyPol_data'\n\n# This is the directory where the 2MASS tiles of the targets have been saved\n# Go to \"http://hachi.ipac.caltech.edu/\" to download 2MASS tiles\nTMASSdir  = \"C:\\\\Users\\\\Jordan\\\\Libraries\\\\python\\\\Mimir_pyPol\\\\2MASSimages\"\n\n# Setup new directory for background subtracted data\nbkgSubDir = os.path.join(pyPol_data, 'bkgSubtracted')\nif (not os.path.isdir(bkgSubDir)):\n    os.mkdir(bkgSubDir, 0o755)\n\n# Read in Kokopelli mask generated in previous step\nkokopelliMask = (AstroImage('kokopelliMask.fits').arr != 0)\n\n# Read in the indexFile data and select the filenames\nindexFile = os.path.join(pyPol_data, 'reducedFileIndex.csv')\nfileIndex = Table.read(indexFile, format='csv')\n\n# Grab the file basenames for later use\nfileIndexFileNames = np.array([os.path.basename(file1)\n    for file1 in fileIndex['Filename'].data])\n\n# Modify the fileIndex to include rejections by residual value\nif 'Background Cut' not in fileIndex.keys():\n    fileIndex.add_column(Column(name='Background Cut',\n                                data = np.repeat(0, len(fileIndex))))\n\n# Determine which parts of the fileIndex pertain to science images\nuseFiles = np.where(np.logical_and(fileIndex['Use'].data == 1,\n                                   fileIndex['Background'].data >= 0))\nskipFiles = np.where(np.logical_or(fileIndex['Use'].data == 0,\n                                   fileIndex['Background'].data < 0))\n\n# Cull the file index to only include files selected for use\nfileIndex1 = fileIndex[useFiles]\nfileIndex2 = fileIndex[skipFiles]\n\n# Group files by target and waveband\ngroupFileIndex = fileIndex1.group_by(['PPOL Name'])\n\nallFileList     = []\nallResidualList = []\n# Loop through all the usable images and comute their residuals\nfor group in groupFileIndex.groups:\n    # Grab the current target information\n    thisTarget   = str(np.unique(group['Target'].data)[0])\n    thisWaveband = str(np.unique(group['Waveband'].data)[0])\n    thisPPOLname = str(np.unique(group['PPOL Name'].data)[0])\n\n    # if thisPPOLname != 'NGC2023_H3': continue\n\n    print('\\nProcessing images for')\n    print('\\tPPOL Group : {0}'.format(thisPPOLname))\n    print('')\n\n    # Read in the 2MASS image\n    TMASSfile = os.path.join(TMASSdir, '_'.join([thisTarget, thisWaveband]) + '.fits')\n    TMASSimg  = AstroImage(TMASSfile)\n    TMASSwcs  = WCS(TMASSimg.header)\n\n    # Estimate the \"nebula free\" level\n    mean, median, stddev = sigma_clipped_stats(TMASSimg.arr.flatten())\n    bkgThresh = median - 0.5*stddev\n\n    # Find the \"nebula free\" pixels\n    bkgRegion = TMASSimg.arr < bkgThresh\n    neighborCount = np.zeros_like(bkgRegion, dtype=int)\n    for dx in range(-1,2):\n        for dy in range(-1,2):\n            neighborCount += np.roll(np.roll(bkgRegion, dy, axis = 0), dx, axis = 1)\n\n    # Find pixels with at least 3 neighbors (other than self)\n    bkgRegion = neighborCount > 4\n\n    groupFileList     = []\n    groupResidualList = []\n    for file1, interpBkg in zip(group['Filename'].data, group['Background'].data):\n        # Read in this image.\n        img = AstroImage(file1)\n\n        # See which pixels in this image map to background pixels\n        ny, nx = img.arr.shape\n        yy, xx = np.mgrid[0:ny, 0:nx]\n        wcs = WCS(img.header)\n        RAs, Decs = wcs.wcs_pix2world(xx, yy, 0)\n        Tx, Ty    = TMASSwcs.wcs_world2pix(RAs, Decs, 0)\n        Tx, Ty    = (Tx.round()).astype(int), (Ty.round()).astype(int)\n\n        # Grab the value of the TMASS background mask for each pixel\n        MimirBkgRegion = bkgRegion[Ty, Tx]\n\n        # Get the indices of the background pixel\n        bkgInds  = np.where(MimirBkgRegion)\n        bkgVals  = img.arr[bkgInds]\n\n        # Compute the direct estimate of background level\n        mean, median, stddev = sigma_clipped_stats(bkgVals)\n\n        # Compute the residual level and store it in the list\n        thisResidual = mean - interpBkg\n        groupFileList.append(os.path.basename(file1))\n        groupResidualList.append(thisResidual)\n\n    # Place this residual list in the final total residual list\n    allFileList.extend(groupFileList)\n    allResidualList.extend(groupResidualList)\n\n    # Convert the lists to arrays\n    groupFileList     = np.array(groupFileList)\n    groupResidualList = np.array(groupResidualList)\n\n    # Check for outliers and mark residuals 5-sigma outside this group's median\n    mean, median, stddev = sigma_clipped_stats(groupResidualList)\n    residMin, residMax = mean - 5*stddev, mean + 5*stddev\n    badInds = np.where(np.logical_or(groupResidualList < residMin,\n                                     groupResidualList > residMax))\n\n    # If some of these residuals are more than 5-sigma from the group mean, then\n    # mark them as bad background levels in the file index.\n    if len(badInds[0]) > 0:\n        # Select the file names of the bad backgrounds\n        badFiles = groupFileList[badInds]\n        # Grab the indices of these files in the fileIndex and mark them as bad\n        fileIndexInds = np.array([np.where(fileIndexFileNames == file1)[0][0]\n            for file1 in badFiles])\n        fileIndex['Background Cut'][fileIndexInds] = 1\n\n# Convert the lists to arrays\nallFileList     = np.array(allFileList)\nallResidualList = np.array(allResidualList)\n\n# Now that we have the residuals for each group, plot them up as histograms\n# # Start by parsing out the residuals for each group\n# Now create a plot with all groups clumpped together\nfig2 = plt.figure()\nax2  = fig2.add_subplot(1,1,1)\nax2.hist(allResidualList, 10, normed=1, histtype='stepfilled', stacked=True)\nplt.xlabel('Residual Counts')\nplt.ylabel('Fraction of Fields')\n\n# Prepare some statistical comments\nxmin, xmax = ax2.get_xlim()\nymin, ymax = ax2.get_ylim()\nmean, median, stddev = sigma_clipped_stats(allResidualList)\n\n# Mark the mean\nax2.axvline(mean, color='k', linewidth=2.0)\nax2.text(mean+0.02*(xmax-xmin), 0.95*ymax, 'mean', rotation='vertical')\n\n# Mark the median\nax2.axvline(median, color='k', linewidth=2.0)\nax2.text(median-0.04*(xmax-xmin), 0.95*ymax, 'median', rotation='vertical')\n\n# Mark the 3-sigma upper and lower limits\nax2.axvline(median - 5*stddev, color='k', linewidth=2.0)\nax2.axvline(median + 5*stddev, color='k', linewidth=2.0)\n\n# Prepare the limits of the acceptable residual range\nresidMin, residMax = mean - 5*stddev, mean + 5*stddev\n\n# Find any background levels that are outside the 5-sigma limits\nbadInds = np.where(np.logical_or(allResidualList < residMin,\n                                 allResidualList > residMax))\n\n# If some of these residuals are more than 5-sigma from the group mean, then\n# mark them as bad background levels in the file index.\nif len(badInds[0]) > 0:\n    # Select the file names of the bad backgrounds\n    badFiles = allFileList[badInds]\n    # Grab the indices of these files in the fileIndex and mark them as bad\n    fileIndexInds = np.array([np.where(fileIndexFileNames == file1)[0][0]\n        for file1 in badFiles])\n    fileIndex['Background Cut'][fileIndexInds] = 1\n\n# Then save to disk\nprint('*************************************')\nprint('Writing all background levels to disk')\nprint('*************************************')\npdb.set_trace()\nfileIndex.write(indexFile, format='csv')\n\nprint('Done!')\n", "meta": {"hexsha": "fb53c35a2b17547cb613862562db6bdf98ac1f86", "size": 9061, "ext": "py", "lang": "Python", "max_stars_repo_path": "oldCode/05_analyzeBackgroundLevels.py", "max_stars_repo_name": "jmontgom10/Mimir_pyPol", "max_stars_repo_head_hexsha": "cb45e78c5ee7b24233cc154c0f3666cd34e2420a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "oldCode/05_analyzeBackgroundLevels.py", "max_issues_repo_name": "jmontgom10/Mimir_pyPol", "max_issues_repo_head_hexsha": "cb45e78c5ee7b24233cc154c0f3666cd34e2420a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "oldCode/05_analyzeBackgroundLevels.py", "max_forks_repo_name": "jmontgom10/Mimir_pyPol", "max_forks_repo_head_hexsha": "cb45e78c5ee7b24233cc154c0f3666cd34e2420a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5676855895, "max_line_length": 86, "alphanum_fraction": 0.6873413531, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 2353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.1833231583115002}}
{"text": "#!/usr/bin/env python3\n#    Copyright (c) 2021 Michele Mancarella <michele.mancarella@unige.ch>\n#\n#    All rights reserved. Use of this source code is governed by a modified BSD\n#    license that can be found in the LICENSE file.\n\nfrom .ABSdata import Data, LVCData\n\nimport numpy as np\nimport astropy.units as u\nimport h5py\nimport os\nimport sys\n#from pesummary.io import read\n#import glob\n   \n\nPACKAGE_PARENT = '..'\nSCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))\nsys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))\n\nfrom astropy.cosmology import Planck15\nfrom cosmology.cosmo import Cosmo\n\nimport Globals\n\n     \nclass O1O2Data(LVCData):\n    \n    def __init__(self, fname, which_metadata='GWOSC',  **kwargs):#nObsUse=None, nSamplesUse=None, dist_unit=u.Gpc, events_use=None, which_spins='skip' ):\n        \n        self.post_file_extension='.hdf5'\n        import pandas as pd\n        if which_metadata=='GWOSC':\n            print('Using SNRS and far from the public version of the GWTC-3 catalog from the GWOSC')\n            self.metadata = pd.read_csv(os.path.join(fname, 'GWTC-1-confident.csv'))\n        else:\n            print('Using best SNRS and far from all pipelines as reported in the GWTC-3 catalog paper')\n            self.metadata = pd.read_csv(os.path.join(Globals.dataPath, 'all_metadata_pipelines_best.csv'))\n        \n        LVCData.__init__(self, fname, **kwargs) #nObsUse=nObsUse, nSamplesUse=nSamplesUse, dist_unit=dist_unit, events_use=events_use, which_spins=which_spins)\n        \n        \n        \n    def _set_Tobs(self):\n        # The first observing run (O1) ran from September 12th, 2015 to January 19th, 2016 --> 129 days\n        # From https://journals.aps.org/prx/pdf/10.1103/PhysRevX.6.041015: \n        # after data quality flags, the remaining coincident analysis time in O1 is 48.3 days with GSTLal analysis, 46.1 with pycbc\n        \n        # The second observing run (O2) ran from November 30th, 2016 to August 25th, 2017 --> 267 days\n        # During the O2 run the duty cycles were 62% for LIGO Hanford and 61% for LIGO Livingston, \n        # so that two detectors were in observing mode 46.4% of the time and at least one detector \n        # was in observing mode 75.6% of the time.\n        # From https://journals.aps.org/prx/pdf/10.1103/PhysRevX.9.031040 :\n        # During O2, the individual LIGO detectors had duty factors of approximately 60% with a LIGO \n        # network duty factor of about 45%. Times with significant instrumental disturbances are flagged and removed, \n        # resulting in about 118 days of data suitable for coincident analysis\n        \n        #self.Tobs= (48.3+118)/365.  # yrs\n        self.Tobs= (129+267)/365.  # yrs\n    \n    \n    def _get_not_BBHs(self):\n        return ['GW170817', ]\n        \n    \n    def _name_conditions(self, f ):\n        return ( ( 'prior' not in f.split('.')[0] ) &  (f.split('_')[0][:2]=='GW') )\n    \n    \n    def _get_name_from_fname(self, fname):\n        return fname.split('.')[0].split('_')[0]\n    \n    \n    def _load_data_event(self, fname, event, nSamplesUse, which_spins='skip'):\n        \n        data_path = os.path.join(fname,  event+'_GWTC-1'+self.post_file_extension)\n        \n        with h5py.File(data_path, 'r') as f:\n            \n            posterior_samples = f['Overall_posterior']\n            \n            m1z = posterior_samples['m1_detector_frame_Msun']\n            m2z = posterior_samples['m2_detector_frame_Msun']\n            dL = posterior_samples['luminosity_distance_Mpc']\n            try:\n                w = posterior_samples['weights_bin']\n            except Exception as e:\n                print(e)\n                w = np.ones(1)\n                \n            if which_spins=='skip':\n                spins=[]\n            elif which_spins=='chiEff':\n                #print('chi_p not available for O1-O2 data ! ')\n                s1 = posterior_samples['spin1']\n                s2 = posterior_samples['spin2']\n                cost1 = posterior_samples['costilt1']\n                cost2 = posterior_samples['costilt2']\n                sint1 = np.sqrt(1-cost1**2)\n                sint2 = np.sqrt(1-cost2**2)\n                chi1z = s1*cost1\n                chi2z = s2*cost2\n                q = m2z/m1z\n                chiEff = (chi1z+q*chi2z)/(1+q)\n                \n                chiP = np.max( np.array([s1*sint1, (4*q+3)/(4+3*q)*q*s2*sint2 ]) , axis=0 )\n                \n                spins=[chiEff, chiP]\n            elif which_spins=='s1s2':\n                raise NotImplementedError()\n                s1 = posterior_samples['spin1']\n                s2 = posterior_samples['spin2']\n                spins=[s1,s2]\n            \n        # Downsample if needed\n        #all_ds = self._downsample( [m1z, m2z, dL, w, *spins,], nSamplesUse)\n        \n        #m1z = all_ds[0]\n        #m2z= all_ds[1]\n        #dL =  all_ds[2]\n        #spins = all_ds[4:]\n        #ws = all_ds[3]\n        \n        return m1z, m2z, dL, spins, w\n    \n \n    \n \n    \n \n    \n \nclass O1O2InjectionsData(Data):\n    \n    def __init__(self, fname, nInjUse=None,  dist_unit=u.Gpc, ifar_th=1 , which_spins='skip', SNR_th=None ):\n        \n        self.dist_unit=dist_unit\n        self.m1z, self.m2z, self.dL, self.spins, self.log_weights_sel, self.N_gen, self.Tobs = self._load_data(fname, nInjUse, which_spins=which_spins )        \n        self.logN_gen = np.log(self.N_gen)\n        #self.log_weights_sel = np.log(self.weights_sel)\n        assert (self.m1z > 0).all()\n        assert (self.m2z > 0).all()\n        assert (self.dL > 0).all()\n        assert(self.m2z<self.m1z).all()\n        \n        #self.Tobs=0.5\n        self.chiEff = np.zeros(self.m1z.shape)\n        print('Obs time: %s yrs' %self.Tobs )\n        \n        self.ifar_th=ifar_th\n        #gstlal_ifar, pycbc_ifar, pycbc_bbh_ifar = conditions_arr\n        self.condition = np.full(self.m1z.shape, True) #(gstlal_ifar > ifar_th) | (pycbc_ifar > ifar_th) | (pycbc_bbh_ifar > ifar_th)\n        \n        \n    def get_theta(self):\n        return np.array( [self.m1z, self.m2z, self.dL  ] )  \n    \n    \n    def _load_data(self, fname, nInjUse, which_spins='skip'):\n        \n        with h5py.File(fname, 'r') as f:\n        \n            Tobs = (48.3+118)/365. #f.attrs['analysis_time_s']/(365.25*24*3600) # years\n            Ndraw = 7.1e07 #f.attrs['total_generated']\n    \n            m1 = np.array(f['mass1_source'])\n            m2 = np.array(f['mass2_source'])\n            z = np.array(f['redshift'])\n        #s1z = np.array(f['injections/spin1z'])\n        #s2z = np.array(f['injections/spin2z'])\n            if which_spins=='skip':\n                spins=[]\n            elif which_spins=='chiEff':\n                chi1z = np.array(f['spin1z'])\n                chi2z = np.array(f['spin2z'])   \n                q = m2/m1\n                chiEff = (chi1z+q*chi2z)/(1+q)\n                print('chi_p not available for O2 selection effects ! ')\n                spins=[chiEff, np.full(chiEff.shape, np.NaN)]\n                #raise NotImplementedError()\n            elif which_spins=='s1s2':\n                raise NotImplementedError()\n                s1 = np.array(f['spin1z'])\n                s2 = np.array(f['spin2z'])\n                spins=[s1,s2]\n    \n            p_draw = np.array(f['sampling_pdf'])\n            if which_spins=='skip':\n                print('Removing factor of 1/2 for each spin dimension from p_draw...')\n                p_draw *= 4\n            log_p_draw = np.log(p_draw)\n            #gstlal_ifar = np.array(f['injections/ifar_gstlal'])\n            #pycbc_ifar = np.array(f['injections/ifar_pycbc_full'])\n            #pycbc_bbh_ifar = np.array(f['injections/ifar_pycbc_bbh'])\n        \n            m1z = m1*(1+z)\n            m2z = m2*(1+z)\n            dL = np.array(Planck15.luminosity_distance(z).to(self.dist_unit).value)\n            #dL = np.array(f['injections/distance']) #in Mpc for GWTC2 !\n            #if self.dist_unit==u.Gpc:\n            #    dL*=1e-03\n        \n            print('Re-weighting p_draw to go to detector frame quantities...')\n            myCosmo = Cosmo(dist_unit=self.dist_unit)\n            #p_draw/=(1+z)**2\n            #p_draw/=myCosmo.ddL_dz(z, Planck15.H0.value, Planck15.Om0, -1., 1., 0) #z, H0, Om, w0, Xi0, n\n            log_p_draw -=2*np.log1p(z)\n            log_p_draw -= myCosmo.log_ddL_dz(z, Planck15.H0.value, Planck15.Om0, -1., 1., 0. )\n        \n\n            print('Number of total injections: %s' %Ndraw)\n            print('Number of injections that pass first threshold: %s' %p_draw.shape[0])\n            \n            self.max_z = np.max(z)\n            print('Max redshift of injections: %s' %self.max_z)\n            return m1z, m2z, dL , spins, log_p_draw , Ndraw, Tobs, #(gstlal_ifar, pycbc_ifar, pycbc_bbh_ifar)\n\n   \n", "meta": {"hexsha": "0adf762f55be5aa4d060cdb0a5432994fb6ec5e3", "size": 8801, "ext": "py", "lang": "Python", "max_stars_repo_path": "MGCosmoPop/dataStructures/O1O2data.py", "max_stars_repo_name": "CosmoStatGW/MGCosmoPop", "max_stars_repo_head_hexsha": "d2f23b9d06c6e4da3e720b4a82a02e2852029b6f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-01-31T02:00:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T08:00:00.000Z", "max_issues_repo_path": "MGCosmoPop/dataStructures/O1O2data.py", "max_issues_repo_name": "CosmoStatGW/MGCosmoPop", "max_issues_repo_head_hexsha": "d2f23b9d06c6e4da3e720b4a82a02e2852029b6f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MGCosmoPop/dataStructures/O1O2data.py", "max_forks_repo_name": "CosmoStatGW/MGCosmoPop", "max_forks_repo_head_hexsha": "d2f23b9d06c6e4da3e720b4a82a02e2852029b6f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-12-13T03:33:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:00:02.000Z", "avg_line_length": 40.0045454545, "max_line_length": 160, "alphanum_fraction": 0.5701624815, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 2453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.18332315115552342}}
{"text": "import itertools\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.io import wavfile\nfrom scipy.signal import detrend, lfilter, bilinear, spectrogram, filtfilt, resample, fftconvolve\nimport acoustics\n\nfrom acoustics.standards.iso_tr_25417_2007 import REFERENCE_PRESSURE\nfrom acoustics.standards.iec_61672_1_2013 import WEIGHTING_SYSTEMS\nfrom acoustics.standards.iec_61672_1_2013 import (NOMINAL_OCTAVE_CENTER_FREQUENCIES,\n                                                  NOMINAL_THIRD_OCTAVE_CENTER_FREQUENCIES)\n\n\nclass Signal(np.ndarray):\n    \"\"\"A signal consisting of samples (array) and a sample frequency (float).\n\n    \"\"\"\n\n    def __new__(cls, data, fs):\n        obj = np.asarray(data).view(cls)\n        obj.fs = fs\n        return obj\n\n    def __array_prepare__(self, array, context=None):\n        try:\n            a = context[1][0]\n            b = context[1][1]\n        except IndexError:\n            return array\n\n        if hasattr(a, 'fs') and hasattr(b, 'fs'):\n            if a.fs == b.fs:\n                return array\n            else:\n                raise ValueError(\"Sample frequencies do not match.\")\n        else:\n            return array\n\n    def __array_wrap__(self, out_arr, context=None):\n        return np.ndarray.__array_wrap__(self, out_arr, context)\n\n    def __array_finalize__(self, obj):\n        # see InfoArray.__array_finalize__ for comments\n        if obj is None:\n            return\n\n        self.fs = getattr(obj, 'fs', None)\n\n    def __reduce__(self):\n        # Get the parent's __reduce__ tuple\n        pickled_state = super(Signal, self).__reduce__()\n        # Create our own tuple to pass to __setstate__\n        new_state = pickled_state[2] + (self.fs, )\n        # Return a tuple that replaces the parent's __setstate__ tuple with our own\n        return (pickled_state[0], pickled_state[1], new_state)\n\n    def __setstate__(self, state):\n        self.fs = state[-1]  # Set the info attribute\n        # Call the parent's __setstate__ with the other tuple elements.\n        super(Signal, self).__setstate__(state[0:-1])\n\n    def __repr__(self):\n        return \"Signal({})\".format(str(self))\n\n    def _construct(self, x):\n        \"\"\"Construct signal like x.\"\"\"\n        return Signal(x, self.fs)\n\n    @property\n    def samples(self):\n        \"\"\"Amount of samples in signal.\"\"\"\n        return self.shape[-1]\n\n    @property\n    def channels(self):\n        \"\"\"Amount of channels.\n        \"\"\"\n        if self.ndim > 1:\n            return self.shape[-2]\n        else:\n            return 1\n\n    @property\n    def duration(self):\n        \"\"\"Duration of signal in seconds.\n        \"\"\"\n        return float(self.samples / self.fs)\n\n    @property\n    def values(self):\n        \"\"\"Return the values of this signal as an instance of :class:`np.ndarray`.\"\"\"\n        return np.array(self)\n\n    def calibrate_to(self, decibel, inplace=False):\n        \"\"\"Calibrate signal to value `decibel`.\n\n        :param decibel: Value to calibrate to.\n        :param inplace: Whether to perform inplace or not.\n        :returns: Calibrated signal.\n        :rtype: :class:`Signal`\n\n        Values of `decibel` are broadcasted. To set a value per channel, use `decibel[...,None]`.\n        \"\"\"\n        decibel = decibel * np.ones(self.shape)\n        gain = decibel - self.leq()[..., None]\n        return self.gain(gain, inplace=inplace)\n\n    def calibrate_with(self, other, decibel, inplace=False):\n        \"\"\"Calibrate signal with other signal.\n\n        :param other: Other signal/array.\n        :param decibel: Signal level of `other`.\n        :param inplace: Whether to perform inplace or not.\n        :returns: calibrated signal.\n        :rtype: :class:`Signal`\n        \"\"\"\n        if not isinstance(other, Signal):\n            other = Signal(other, self.fs)\n        gain = decibel - other.leq()\n        return self.gain(gain, inplace=inplace)\n\n    def decimate(self, factor, zero_phase=False, ftype='iir', order=None):\n        \"\"\"Decimate signal by integer `factor`. Before downsampling a low-pass filter is applied.\n\n        :param factor: Downsampling factor.\n        :param zero_phase: Prevent phase shift by filtering with ``filtfilt`` instead of ``lfilter``.\n        :param ftype: Filter type.\n        :param order: Filter order.\n        :returns: Decimated signal.\n        :rtype: :class:`Signal`\n\n        .. seealso:: :func:`scipy.signal.decimate`\n        .. seealso:: :meth:`resample`\n\n        \"\"\"\n        return Signal(\n            acoustics.signal.decimate(x=self, q=factor, n=order, ftype=ftype, zero_phase=zero_phase), self.fs / factor)\n\n    def resample(self, nsamples, times=None, axis=-1, window=None):\n        \"\"\"Resample signal.\n\n        :param samples: New amount of samples.\n        :param times: Times corresponding to samples.\n        :param axis: Axis.\n        :param window: Window.\n\n        .. seealso:: :func:`scipy.signal.resample`\n        .. seealso:: :meth:`decimate`\n\n        You might want to low-pass filter this signal before resampling.\n\n        \"\"\"\n        return Signal(resample(self, nsamples, times, axis, window), nsamples / self.samples * self.fs)\n\n    def upsample(self, factor, axis=-1):\n        \"\"\"Upsample signal with integer factor.\n\n        :param factor: Upsample factor.\n        :param axis: Axis.\n\n        .. seealso:: :meth:`resample`\n        \"\"\"\n        return self.resample(int(self.samples * factor), axis=axis)\n\n    def gain(self, decibel, inplace=False):\n        \"\"\"Apply gain of `decibel` decibels.\n\n        :param decibel: Decibels\n        :param inplace: In place\n        :returns: Amplified signal.\n        :rtype: :class:`Signal`\n        \"\"\"\n        factor = 10.0**(decibel / 20.0)\n        if inplace:\n            self *= factor\n            return self\n        else:\n            return self * factor\n\n    def pick(self, start=0.0, stop=None):\n        \"\"\"Get signal from start time to stop time.\n\n        :param start: Start time.\n        :type start: float\n        :param stop: End time.\n        :type stop: float\n        :returns: Selected part of the signal.\n        :rtype: :class:`Signal`\n\n        \"\"\"\n        if start is not None:\n            start = int(np.floor(start * self.fs))\n        if stop is not None:\n            stop = int(np.floor(stop * self.fs))\n        return self[..., start:stop]\n\n    def times(self):\n        \"\"\"Time vector.\n\n        :returns: A vector with a timestamp for each sample.\n        :rtype: :class:`np.ndarray`\n\n        \"\"\"\n        return np.arange(0, self.samples) / self.fs\n\n    def energy(self):\n        \"\"\"Signal energy.\n\n        :returns: Total energy per channel.\n        :rtype: :class:`np.ndarray`\n\n        .. math:: E = \\\\sum_{n=0}^{N-1} |x_n|^2\n\n        \"\"\"\n        return float((self * self).sum())\n\n    def power(self):\n        \"\"\"Signal power.\n\n        .. math:: P = \\\\frac{1}{N} \\\\sum_{n=0}^{N-1} |x_n|^2\n        \"\"\"\n        return self.energy() / len(self)\n\n    def ms(self):\n        \"\"\"Mean value squared of signal.\n\n        .. seealso:: :func:`acoustics.signal.ms`\n\n        \"\"\"\n        return acoustics.signal.ms(self)\n\n    def rms(self):\n        \"\"\"Root mean squared of signal.\n\n        .. seealso:: :func:`acoustics.signal.rms`\n\n        \"\"\"\n        return acoustics.signal.rms(self)\n        #return np.sqrt(self.power())\n\n    def weigh(self, weighting='A', zero_phase=False):\n        \"\"\"Apply frequency-weighting. By default 'A'-weighting is applied.\n\n        :param weighting: Frequency-weighting filter to apply.\n            Valid options are 'A', 'C' and 'Z'. Default weighting is 'A'.\n        :returns: Weighted signal.\n        :rtype: :class:`Signal`.\n\n        By default the weighting filter is applied using\n        :func:`scipy.signal.lfilter` causing a frequency-dependent delay. In case a\n        delay is undesired, the filter can be applied using :func:`scipy.signal.filtfilt`\n        by setting `zero_phase=True`.\n\n        \"\"\"\n        num, den = WEIGHTING_SYSTEMS[weighting]()\n        b, a = bilinear(num, den, self.fs)\n        func = filtfilt if zero_phase else lfilter\n        return self._construct(func(b, a, self))\n\n    def correlate(self, other=None, mode='full'):\n        \"\"\"Correlate signal with `other` signal. In case `other==None` this\n        method returns the autocorrelation.\n\n        :param other: Other signal.\n        :param mode: Mode.\n\n        .. seealso:: :func:`np.correlate`, :func:`scipy.signal.fftconvolve`\n\n        \"\"\"\n        if other is None:\n            other = self\n        if self.fs != other.fs:\n            raise ValueError(\"Cannot correlate. Sample frequencies are not the same.\")\n        if self.channels > 1 or other.channels > 1:\n            raise ValueError(\"Cannot correlate. Not supported for multichannel signals.\")\n        return self._construct(fftconvolve(self, other[::-1], mode=mode))\n\n    def amplitude_envelope(self):\n        \"\"\"Amplitude envelope.\n\n        :returns: Amplitude envelope of signal.\n        :rtype: :class:`Signal`\n\n        .. seealso:: :func:`acoustics.signal.amplitude_envelope`\n\n        \"\"\"\n        return self._construct(acoustics.signal.amplitude_envelope(self, self.fs))\n\n    def instantaneous_frequency(self):\n        \"\"\"Instantaneous frequency.\n\n        :returns: Instantaneous frequency of signal.\n        :rtype: :class:`Signal`\n\n        .. seealso:: :func:`acoustics.signal.instantaneous_frequency`\n\n        \"\"\"\n        return self._construct(acoustics.signal.instantaneous_frequency(self, self.fs))\n\n    def instantaneous_phase(self):\n        \"\"\"Instantaneous phase.\n\n        :returns: Instantaneous phase of signal.\n        :rtype: :class:`Signal`\n\n        .. seealso:: :func:`acoustics.signal.instantaneous_phase`\n\n        \"\"\"\n        return self._construct(acoustics.signal.instantaneous_phase(self, self.fs))\n\n    def detrend(self, **kwargs):\n        \"\"\"Detrend signal.\n\n        :returns: Detrended version of signal.\n        :rtype: :class:`Signal`\n\n        .. seealso:: :func:`scipy.signal.detrend`\n\n        \"\"\"\n        return self._construct(detrend(self, **kwargs))\n\n    def unwrap(self):\n        \"\"\"Unwrap signal in case the signal represents wrapped phase.\n\n        :returns: Unwrapped signal.\n        :rtype: :class:`Signal`\n\n        .. seealso:: :func:`np.unwrap`\n\n        \"\"\"\n        return self._construct(np.unwrap(self))\n\n    def complex_cepstrum(self, N=None):\n        \"\"\"Complex cepstrum.\n\n        :param N: Amount of bins.\n        :returns: Quefrency, complex cepstrum and delay in amount of samples.\n\n        .. seealso:: :func:`acoustics.cepstrum.complex_cepstrum`\n\n        \"\"\"\n        if N is not None:\n            times = np.linspace(0.0, self.duration, N, endpoint=False)\n        else:\n            times = self.times()\n        cepstrum, ndelay = acoustics.cepstrum.complex_cepstrum(self, n=N)\n        return times, cepstrum, ndelay\n\n    def real_cepstrum(self, N=None):\n        \"\"\"Real cepstrum.\n\n        :param N: Amount of bins.\n        :returns: Quefrency and real cepstrum.\n\n        .. seealso:: :func:`acoustics.cepstrum.real_cepstrum`\n\n        \"\"\"\n        if N is not None:\n            times = np.linspace(0.0, self.duration, N, endpoint=False)\n        else:\n            times = self.times()\n        return times, acoustics.cepstrum.real_cepstrum(self, n=N)\n\n    def power_spectrum(self, N=None):\n        \"\"\"Power spectrum.\n\n        :param N: Amount of bins.\n\n        .. seealso:: :func:`acoustics.signal.power_spectrum`\n\n        \"\"\"\n        return acoustics.signal.power_spectrum(self, self.fs, N=N)\n\n    def angle_spectrum(self, N=None):\n        \"\"\"Phase angle spectrum. Wrapped.\n\n        :param N: amount of bins.\n\n        .. seealso::\n\n            :func:`acoustics.signal.angle_spectrum`, :func:`acoustics.signal.phase_spectrum`\n            and :meth:`phase_spectrum`.\n\n        \"\"\"\n        return acoustics.signal.angle_spectrum(self, self.fs, N=N)\n\n    def phase_spectrum(self, N=None):\n        \"\"\"Phase spectrum. Unwrapped.\n\n        :param N: Amount of bins.\n\n        .. seealso::\n\n            :func:`acoustics.signal.phase_spectrum`, :func:`acoustics.signal.angle_spectrum`\n            and :meth:`angle_spectrum`.\n\n        \"\"\"\n        return acoustics.signal.phase_spectrum(self, self.fs, N=N)\n\n    def peak(self, axis=-1):\n        \"\"\"Peak sound pressure.\n\n        :param axis: Axis.\n\n        .. seealso::\n\n            :func:`acoustic.standards.iso_tr_25417_2007.peak_sound_pressure`\n\n        \"\"\"\n        return acoustics.standards.iso_tr_25417_2007.peak_sound_pressure(self, axis=axis)\n\n    def peak_level(self, axis=-1):\n        \"\"\"Peak sound pressure level.\n\n        :param axis: Axis.\n\n        .. seealso::\n\n            :func:`acoustics.standards.iso_tr_25417_2007.peak_sound_pressure_level`\n\n        \"\"\"\n        return acoustics.standards.iso_tr_25417_2007.peak_sound_pressure_level(self, axis=axis)\n\n    def min(self, axis=-1):\n        \"\"\"Return the minimum along a given axis.\n\n        Refer to `np.amin` for full documentation.\n        \"\"\"\n        return np.ndarray.min(self, axis=axis)\n\n    def max(self, axis=-1):\n        \"\"\"Return the minimum along a given axis.\n\n        Refer to `np.amax` for full documentation.\n        \"\"\"\n        return np.ndarray.max(self, axis=axis)\n\n    def max_level(self, axis=-1):\n        \"\"\"Maximum sound pressure level.\n\n        :param axis: Axis.\n\n        .. seealso:: :func:`acoustics.standards.iso_tr_25417_2007.max_sound_pressure_level`\n\n        \"\"\"\n        return acoustics.standards.iso_tr_25417_2007.max_sound_pressure_level(self, axis=axis)\n\n    def sound_exposure(self, axis=-1):\n        \"\"\"Sound exposure.\n\n        :param axis: Axis.\n\n        .. seealso:: :func:`acoustics.standards.iso_tr_25417_2007.sound_exposure`\n\n        \"\"\"\n        return acoustics.standards.iso_tr_25417_2007.sound_exposure(self, self.fs, axis=axis)\n\n    def sound_exposure_level(self, axis=-1):\n        \"\"\"Sound exposure level.\n\n        :param axis: Axis.\n\n        .. seealso:: :func:`acoustics.standards.iso_tr_25417_2007.sound_exposure_level`\n\n        \"\"\"\n        return acoustics.standards.iso_tr_25417_2007.sound_exposure_level(self, self.fs, axis=axis)\n\n    def plot_complex_cepstrum(self, N=None, **kwargs):\n        \"\"\"Plot complex cepstrum of signal.\n\n        Valid kwargs:\n\n        * xscale\n        * yscale\n        * xlim\n        * ylim\n        * frequency: Boolean indicating whether the x-axis should show time in seconds or quefrency\n        * xlabel_frequency: Label in case frequency is shown.\n\n        \"\"\"\n        params = {\n            'xscale': 'linear',\n            'yscale': 'linear',\n            'xlabel': \"$t$ in s\",\n            'ylabel': \"$C$\",\n            'title': 'Complex cepstrum',\n            'frequency': False,\n            'xlabel_frequency': \"$f$ in Hz\",\n        }\n        params.update(kwargs)\n\n        t, ceps, _ = self.complex_cepstrum(N=N)\n        if params['frequency']:\n            t = 1. / t\n            params['xlabel'] = params['xlabel_frequency']\n            t = t[::-1]\n            ceps = ceps[::-1]\n        return _base_plot(t, ceps, params)\n\n    def plot_real_cepstrum(self, N=None, **kwargs):\n        \"\"\"Plot real cepstrum of signal.\n\n        Valid kwargs:\n\n        * xscale\n        * yscale\n        * xlim\n        * ylim\n        * frequency: Boolean indicating whether the x-axis should show time in seconds or quefrency\n        * xlabel_frequency: Label in case frequency is shown.\n\n        \"\"\"\n        params = {\n            'xscale': 'linear',\n            'yscale': 'linear',\n            'xlabel': \"$t$ in s\",\n            'ylabel': \"$C$\",\n            'title': 'Real cepstrum',\n            'frequency': False,\n            'xlabel_frequency': \"$f$ in Hz\",\n        }\n        params.update(kwargs)\n\n        t, ceps = self.real_cepstrum(N=N)\n        if params['frequency']:\n            t = 1. / t\n            params['xlabel'] = params['xlabel_frequency']\n            t = t[::-1]\n            ceps = ceps[::-1]\n        return _base_plot(t, ceps, params)\n\n    def plot_power_spectrum(self, N=None, **kwargs):  #filename=None, scale='log'):\n        \"\"\"Plot spectrum of signal.\n\n        Valid kwargs:\n\n        * xscale\n        * yscale\n        * xlim\n        * ylim\n        * reference: Reference power\n\n        .. seealso:: :meth:`power_spectrum`\n\n        \"\"\"\n        params = {\n            'xscale': 'log',\n            'yscale': 'linear',\n            'xlabel': \"$f$ in Hz\",\n            'ylabel': \"$L_{p}$ in dB\",\n            'title': 'SPL',\n            'reference': REFERENCE_PRESSURE**2.0,\n        }\n        params.update(kwargs)\n\n        f, o = self.power_spectrum(N=N)\n        return _base_plot(f, 10.0 * np.log10(o / params['reference']), params)\n\n    def plot_angle_spectrum(self, N=None, **kwargs):\n        \"\"\"Plot phase angle spectrum of signal. Wrapped.\n\n        Valid kwargs:\n\n        * xscale\n        * yscale\n        * xlim\n        * ylim\n        * reference: Reference power\n\n        \"\"\"\n        params = {\n            'xscale': 'linear',\n            'yscale': 'linear',\n            'xlabel': \"$f$ in Hz\",\n            'ylabel': r\"$\\angle \\phi$\",\n            'title': 'Phase response (wrapped)',\n        }\n        params.update(kwargs)\n        f, o = self.angle_spectrum(N=N)\n        return _base_plot(f, o, params)\n\n    def plot_phase_spectrum(self, N=None, **kwargs):\n        \"\"\"Plot phase spectrum of signal. Unwrapped.\n\n        Valid kwargs:\n\n        * xscale\n        * yscale\n        * xlim\n        * ylim\n        * reference: Reference power\n\n        \"\"\"\n        params = {\n            'xscale': 'linear',\n            'yscale': 'linear',\n            'xlabel': \"$f$ in Hz\",\n            'ylabel': r\"$\\angle \\phi$\",\n            'title': 'Phase response (unwrapped)',\n        }\n        params.update(kwargs)\n        f, o = self.phase_spectrum(N=N)\n        return _base_plot(f, o, params)\n\n    def spectrogram(self, **kwargs):\n        \"\"\"Spectrogram of signal.\n\n        :returns: Spectrogram.\n\n        See :func:`scipy.signal.spectrogram`. Some of the default values have been changed.\n        The generated spectrogram consists by default of complex values.\n\n        \"\"\"\n        params = {\n            'nfft': 4096,\n            'noverlap': 128,\n            'mode': 'complex',\n        }\n        params.update(kwargs)\n\n        t, s, P = spectrogram(self, fs=self.fs, **params)\n\n        return t, s, P\n\n    def plot_spectrogram(self, **kwargs):\n        \"\"\"\n        Plot spectrogram of the signal.\n\n        Valid kwargs:\n\n        * xlim\n        * ylim\n        * clim\n        .. note:: This method only works for a single channel.\n\n        \"\"\"\n        # To do, use :meth:`spectrogram`.\n        params = {\n            'xlim': None,\n            'ylim': None,\n            'clim': None,\n            'NFFT': 4096,\n            'noverlap': 128,\n            'title': 'Spectrogram',\n            'xlabel': '$t$ in s',\n            'ylabel': '$f$ in Hz',\n            'clabel': 'SPL in dB',\n            'colorbar': True,\n        }\n        params.update(kwargs)\n\n        if self.channels > 1:\n            raise ValueError(\"Cannot plot spectrogram of multichannel signal. Please select a single channel.\")\n\n        # Check if an axes object is passed in. Otherwise, create one.\n        ax0 = params.get('ax', plt.figure().add_subplot(111))\n        ax0.set_title(params['title'])\n\n        data = np.squeeze(self)\n        try:\n            _, _, _, im = ax0.specgram(data, Fs=self.fs, noverlap=params['noverlap'], NFFT=params['NFFT'],\n                                       mode='magnitude', scale_by_freq=False)\n        except AttributeError:\n            raise NotImplementedError(\n                \"Your version of matplotlib is incompatible due to lack of support of the mode keyword argument to matplotlib.mlab.specgram.\"\n            )\n\n        if params['colorbar']:\n            cb = ax0.get_figure().colorbar(mappable=im)\n            cb.set_label(params['clabel'])\n\n        ax0.set_xlim(params['xlim'])\n        ax0.set_ylim(params['ylim'])\n        im.set_clim(params['clim'])\n\n        ax0.set_xlabel(params['xlabel'])\n        ax0.set_ylabel(params['ylabel'])\n\n        return ax0\n\n    def levels(self, time=0.125, method='average'):\n        \"\"\"Calculate sound pressure level as function of time.\n\n        :param time: Averaging time or integration time constant. Default value is 0.125 corresponding to FAST.\n        :param method: Use time `average` or time `weighting`. Default option is `average`.\n        :returns: sound pressure level as function of time.\n\n        .. seealso:: :func:`acoustics.standards.iec_61672_1_2013.time_averaged_sound_level`\n        .. seealso:: :func:`acoustics.standards.iec_61672_1_2013.time_weighted_sound_level`\n\n        \"\"\"\n        if method == 'average':\n            return acoustics.standards.iec_61672_1_2013.time_averaged_sound_level(self.values, self.fs, time)\n        elif method == 'weighting':\n            return acoustics.standards.iec_61672_1_2013.time_weighted_sound_level(self.values, self.fs, time)\n        else:\n            raise ValueError(\"Invalid method\")\n\n    def leq(self):\n        \"\"\"Equivalent level. Single-value number.\n\n        .. seealso:: :func:`acoustics.standards.iso_tr_25417_2007.equivalent_sound_pressure_level`\n\n        \"\"\"\n        return acoustics.standards.iso_tr_25417_2007.equivalent_sound_pressure_level(self.values)\n\n    def plot_levels(self, **kwargs):\n        \"\"\"Plot sound pressure level as function of time.\n\n        .. seealso:: :meth:`levels`\n\n        \"\"\"\n        params = {\n            'xscale': 'linear',\n            'yscale': 'linear',\n            'xlabel': '$t$ in s',\n            'ylabel': '$L_{p,F}$ in dB',\n            'title': 'SPL',\n            'time': 0.125,\n            'method': 'average',\n            'labels': None,\n        }\n        params.update(kwargs)\n        t, L = self.levels(params['time'], params['method'])\n        L_masked = np.ma.masked_where(np.isinf(L), L)\n        return _base_plot(t, L_masked, params)\n\n    #def octave(self, frequency, fraction=1):\n    #\"\"\"Determine fractional-octave `fraction` at `frequency`.\n\n    #.. seealso:: :func:`acoustics.signal.fractional_octaves`\n\n    #\"\"\"\n    #return acoustics.signal.fractional_octaves(self, self.fs, frequency,\n    #frequency, fraction, False)[1]\n\n    def bandpass(self, lowcut, highcut, order=8, zero_phase=False):\n        \"\"\"Filter signal with band-pass filter.\n\n        :param lowcut: Lower cornerfrequency.\n        :param highcut: Upper cornerfrequency.\n        :param order: Filter order.\n        :param zero_phase: Prevent phase error by filtering in both directions (filtfilt).\n\n        :returns: Band-pass filtered signal.\n        :rtype: :class:`Signal`.\n\n        .. seealso:: :func:`acoustics.signal.bandpass`\n        \"\"\"\n        return type(self)(acoustics.signal.bandpass(self, lowcut, highcut, self.fs, order=order, zero_phase=zero_phase),\n                          self.fs)\n\n    def bandstop(self, lowcut, highcut, order=8, zero_phase=False):\n        \"\"\"Filter signal with band-stop filter.\n\n        :param lowcut: Lower cornerfrequency.\n        :param highcut: Upper cornerfrequency.\n        :param order: Filter order.\n        :param zero_phase: Prevent phase error by filtering in both directions (filtfilt).\n\n        :returns: Band-pass filtered signal.\n        :rtype: :class:`Signal`.\n\n        .. seealso:: :func:`acoustics.signal.bandstop`\n        \"\"\"\n        return type(self)(acoustics.signal.bandstop(self, lowcut, highcut, self.fs, order=order, zero_phase=zero_phase),\n                          self.fs)\n\n    def highpass(self, cutoff, order=4, zero_phase=False):\n        \"\"\"Filter signal with high-pass filter.\n\n        :param cutoff: Cornerfrequency.\n        :param order: Filter order.\n        :param zero_phase: Prevent phase error by filtering in both directions (filtfilt).\n        :returns: High-pass filtered signal.\n        :rtype: :class:`Signal`.\n\n        .. seealso:: :func:`acoustics.signal.highpass`\n        \"\"\"\n        return type(self)(acoustics.signal.highpass(self, cutoff, self.fs, order=order, zero_phase=zero_phase), self.fs)\n\n    def lowpass(self, cutoff, order=4, zero_phase=False):\n        \"\"\"Filter signal with low-pass filter.\n\n        :param cutoff: Cornerfrequency.\n        :param order: Filter order.\n        :param zero_phase: Prevent phase error by filtering in both directions (filtfilt).\n        :returns: Low-pass filtered signal.\n        :rtype: :class:`Signal`.\n\n        .. seealso:: :func:`acoustics.signal.lowpass`\n        \"\"\"\n        return type(self)(acoustics.signal.lowpass(self, cutoff, self.fs, order=order, zero_phase=zero_phase), self.fs)\n\n    def octavepass(self, center, fraction, order=8, zero_phase=False):\n        \"\"\"Filter signal with fractional-octave band-pass filter.\n\n        :param center: Center frequency. Any value in the band will suffice.\n        :param fraction: Band designator.\n        :param order: Filter order.\n        :param zero_phase: Prevent phase error by filtering in both directions (filtfilt).\n        :returns: Band-pass filtered signal.\n        :rtype: :class:`Signal`.\n\n        .. seealso:: :func:`acoustics.signal.octavepass`\n        \"\"\"\n        return type(self)(acoustics.signal.octavepass(self, center, self.fs, fraction=fraction, order=order,\n                                                      zero_phase=zero_phase), self.fs)\n\n    def bandpass_frequencies(self, frequencies, order=8, purge=True, zero_phase=False):\n        \"\"\"Apply bandpass filters for frequencies.\n\n        :param frequencies: Band-pass filter frequencies.\n        :type frequencies: Instance of :class:`acoustics.signal.Frequencies`\n        :param order: Filter order.\n        :param purge: Discard bands of which the upper corner frequency is above the Nyquist frequency.\n        :param zero_phase: Prevent phase error by filtering in both directions (filtfilt).\n        :returns: Frequencies and band-pass filtered signal.\n\n        .. seealso:: :func:`acoustics.signal.bandpass_frequencies`\n        \"\"\"\n        frequencies, filtered = acoustics.signal.bandpass_frequencies(self, self.fs, frequencies, order, purge,\n                                                                      zero_phase=zero_phase)\n        return frequencies, type(self)(filtered, self.fs)\n\n    def octaves(self, frequencies=NOMINAL_OCTAVE_CENTER_FREQUENCIES, order=8, purge=True, zero_phase=False):\n        \"\"\"Apply 1/1-octaves bandpass filters.\n\n        :param frequencies: Band-pass filter frequencies.\n        :type frequencies: :class:`np.ndarray` with (approximate) center-frequencies or an instance of :class:`acoustics.signal.Frequencies`\n        :param order: Filter order.\n        :param purge: Discard bands of which the upper corner frequency is above the Nyquist frequency.\n        :param zero_phase: Prevent phase error by filtering in both directions (filtfilt).\n        :returns: Frequencies and band-pass filtered signal.\n\n        .. seealso:: :func:`acoustics.signal.bandpass_octaves`\n        \"\"\"\n        frequencies, octaves = acoustics.signal.bandpass_octaves(self, self.fs, frequencies, order, purge,\n                                                                 zero_phase=zero_phase)\n        return frequencies, type(self)(octaves, self.fs)\n\n    def third_octaves(self, frequencies=NOMINAL_THIRD_OCTAVE_CENTER_FREQUENCIES, order=8, purge=True, zero_phase=False):\n        \"\"\"Apply 1/3-octaves bandpass filters.\n\n        :param frequencies: Band-pass filter frequencies.\n        :type frequencies: :class:`np.ndarray` with (approximate) center-frequencies or an instance of :class:`acoustics.signal.Frequencies`\n        :param order: Filter order.\n        :param purge: Discard bands of which the upper corner frequency is above the Nyquist frequency.\n        :param zero_phase: Prevent phase error by filtering in both directions (filtfilt).\n        :returns: Frequencies and band-pass filtered signal.\n\n        .. seealso:: :func:`acoustics.signal.bandpass_third_octaves`\n        \"\"\"\n        frequencies, octaves = acoustics.signal.bandpass_third_octaves(self, self.fs, frequencies, order, purge,\n                                                                       zero_phase=zero_phase)\n        return frequencies, type(self)(octaves, self.fs)\n\n    def fractional_octaves(self, frequencies=None, fraction=1, order=8, purge=True, zero_phase=False):\n        \"\"\"Apply 1/N-octaves bandpass filters.\n\n        :param frequencies: Band-pass filter frequencies.\n        :type frequencies: Instance of :class:`acoustics.signal.Frequencies`\n        :param fraction: Default band-designator of fractional-octaves.\n        :param order: Filter order.\n        :param purge: Discard bands of which the upper corner frequency is above the Nyquist frequency.\n        :param zero_phase: Prevent phase error by filtering in both directions (filtfilt).\n        :returns: Frequencies and band-pass filtered signal.\n\n        .. seealso:: :func:`acoustics.signal.bandpass_fractional_octaves`\n        \"\"\"\n        if frequencies is None:\n            frequencies = acoustics.signal.OctaveBand(fstart=NOMINAL_THIRD_OCTAVE_CENTER_FREQUENCIES[0],\n                                                      fstop=self.fs / 2.0, fraction=fraction)\n        frequencies, octaves = acoustics.signal.bandpass_fractional_octaves(self, self.fs, frequencies, fraction, order,\n                                                                            purge, zero_phase=zero_phase)\n        return frequencies, type(self)(octaves, self.fs)\n\n    def plot_octaves(self, **kwargs):\n        \"\"\"Plot octaves.\n\n        .. seealso:: :meth:`octaves`\n\n        \"\"\"\n        params = {\n            'xscale': 'log',\n            'yscale': 'linear',\n            'xlabel': '$f$ in Hz',\n            'ylabel': '$L_{p}$ in dB',\n            'title': '1/1-Octaves SPL',\n        }\n        params.update(kwargs)\n        f, o = self.octaves()\n        print(len(f.center), len(o.leq()))\n        return _base_plot(f.center, o.leq().T, params)\n\n    def plot_third_octaves(self, **kwargs):\n        \"\"\"Plot 1/3-octaves.\n\n        .. seealso:: :meth:`third_octaves`\n\n        \"\"\"\n        params = {\n            'xscale': 'log',\n            'yscale': 'linear',\n            'xlabel': '$f$ in Hz',\n            'ylabel': '$L_{p}$ in dB',\n            'title': '1/3-Octaves SPL',\n        }\n        params.update(kwargs)\n        f, o = self.third_octaves()\n        return _base_plot(f.center, o.leq().T, params)\n\n    def plot_fractional_octaves(self, frequencies=None, fraction=1, order=8, purge=True, zero_phase=False, **kwargs):\n        \"\"\"Plot fractional octaves.\n        \"\"\"\n        title = '1/{}-Octaves SPL'.format(fraction)\n\n        params = {\n            'xscale': 'log',\n            'yscale': 'linear',\n            'xlabel': '$f$ in Hz',\n            'ylabel': '$L_p$ in dB',\n            'title': title,\n        }\n        params.update(kwargs)\n        f, o = self.fractional_octaves(frequencies=frequencies, fraction=fraction, order=order, purge=purge,\n                                       zero_phase=zero_phase)\n        return _base_plot(f.center, o.leq().T, params)\n\n    def plot(self, **kwargs):\n        \"\"\"Plot signal as function of time. By default the entire signal is plotted.\n\n        :param filename: Name of file.\n        :param start: First sample index.\n        :type start: Start time in seconds from start of signal.\n        :param stop: Last sample index.\n        :type stop: Stop time in seconds. from stop of signal.\n        \"\"\"\n        params = {\n            'xscale': 'linear',\n            'yscale': 'linear',\n            'xlabel': '$t$ in s',\n            'ylabel': '$x$ in -',\n            'title': 'Signal',\n        }\n        params.update(kwargs)\n        return _base_plot(self.times(), self, params)\n\n    #def plot_scalo(self, filename=None):\n    #\"\"\"\n    #Plot scalogram\n    #\"\"\"\n    #from scipy.signal import ricker, cwt\n\n    #wavelet = ricker\n    #widths = np.logspace(-1, 3.5, 10)\n    #x = cwt(self, wavelet, widths)\n\n    #interpolation = 'nearest'\n\n    #from matplotlib.ticker import LinearLocator, AutoLocator, MaxNLocator\n    #majorLocator = LinearLocator()\n    #majorLocator = MaxNLocator()\n\n    #fig = plt.figure()\n    #ax = fig.add_subplot(111)\n    #ax.set_title('Scaleogram')\n    ##ax.set_xticks(np.arange(0, x.shape[1])*self.fs)\n    ##ax.xaxis.set_major_locator(majorLocator)\n\n    ##ax.imshow(10.0 * np.log10(x**2.0), interpolation=interpolation, aspect='auto', origin='lower')#, extent=[0, 1, 0, len(x)])\n    #ax.pcolormesh(np.arange(0.0, x.shape[1])/self.fs, widths, 10.0*np.log(x**2.0))\n    #if filename:\n    #fig.savefig(filename)\n    #else:\n    #return fig\n\n    #def plot_scaleogram(self, filename):\n    #\"\"\"\n    #Plot scaleogram\n    #\"\"\"\n    #import pywt\n\n    #wavelet = 'dmey'\n    #level = pywt.dwt_max_level(len(self), pywt.Wavelet(wavelet))\n    #print level\n    #level = 20\n    #order = 'freq'\n    #interpolation = 'nearest'\n\n    #wp = pywt.WaveletPacket(self, wavelet, 'sym', maxlevel=level)\n    #nodes = wp.get_level(level, order=order)\n    #labels = [n.path for n in nodes]\n    #values = np.abs(np.array([n.data for n in nodes], 'd'))\n\n    #fig = plt.figure()\n    #ax = fig.add_subplot(111)\n    #ax.set_title('Scaleogram')\n    #ax.imshow(values, interpolation=interpolation, aspect='auto', origin='lower', extent=[0, 1, 0, len(values)])\n    ##ax.set_yticks(np.arange(0.5, len(labels) + 0.5))\n    ##ax.set_yticklabels(labels)\n\n    #fig.savefig(filename)\n\n    def normalize(self, gap=6.0, inplace=False):\n        \"\"\"Normalize signal.\n\n        :param gap: Gap between maximum value and ceiling in decibel.\n        :param inplace: Normalize signal in place.\n\n        The parameter `gap` can be understood as using `gap` decibels fewer for the dynamic range.\n        By default a 6 decibel gap is used.\n\n        \"\"\"\n        factor = (np.abs(self).max() * 10.0**(gap/20.0))\n        if inplace:\n            self /= factor[..., None]\n            return self\n        else:\n            return self / factor[..., None]\n\n    def to_wav(self, filename, depth=16):\n        \"\"\"Save signal as WAV file.\n\n        :param filename: Name of file to save to.\n        :param depth: If given, convert to integer with specified depth. Else, try to store using the original data type.\n\n        By default, this function saves a normalized 16-bit version of the signal with at least 6 dB range till clipping occurs.\n\n        \"\"\"\n        data = self\n        dtype = data.dtype if not depth else 'int' + str(depth)\n        if depth:\n            data = (data * 2**(depth - 1) - 1).astype(dtype)\n        wavfile.write(filename, int(self.fs), data.T)\n        #wavfile.write(filename, int(self.fs), self._data/np.abs(self._data).max() *  0.5)\n        #wavfile.write(filename, int(self.fs), np.int16(self._data/(np.abs(self._data).max()) * 32767) )\n\n    @classmethod\n    def from_wav(cls, filename, normalize=True):\n        \"\"\"\n        Create an instance of `Signal` from a WAV file.\n\n        :param filename: Filename\n        :param normalize: Whether to normalize the signal.\n\n        \"\"\"\n        fs, data = wavfile.read(filename)\n        data = data.astype(np.float32, copy=False).T\n        if normalize:\n            data /= np.max(np.abs(data))\n        return cls(data, fs=fs)\n\n\n_PLOTTING_PARAMS = {\n    'title': None,\n    'xlabel': None,\n    'ylabel': None,\n    'xscale': 'linear',\n    'yscale': 'linear',\n    'xlim': (None, None),\n    'ylim': (None, None),\n    'labels': None,\n    'linestyles': ['-', '-.', '--', ':'],\n}\n\n\ndef _get_plotting_params():\n    d = dict()\n    d.update(_PLOTTING_PARAMS)\n    return d\n\n\ndef _base_plot(x, y, given_params):\n    \"\"\"Common function for creating plots.\n\n    :returns: Axes object.\n    :rtype: :class:`matplotlib.Axes`\n    \"\"\"\n\n    params = _get_plotting_params()\n    params.update(given_params)\n\n    linestyles = itertools.cycle(iter(params['linestyles']))\n\n    # Check if an axes object is passed in. Otherwise, create one.\n    ax0 = params.get('ax', plt.figure().add_subplot(111))\n\n    ax0.set_title(params['title'])\n    if y.ndim > 1:\n        for channel in y:\n            ax0.plot(x, channel, linestyle=next(linestyles))\n    else:\n        ax0.plot(x, y)\n    ax0.set_xlabel(params['xlabel'])\n    ax0.set_ylabel(params['ylabel'])\n    ax0.set_xscale(params['xscale'])\n    ax0.set_yscale(params['yscale'])\n    ax0.set_xlim(params['xlim'])\n    ax0.set_ylim(params['ylim'])\n\n    if params['labels'] is None and y.ndim > 1:\n        params['labels'] = np.arange(y.shape[-2]) + 1\n    if params['labels'] is not None:\n        ax0.legend(labels=params['labels'])\n\n    return ax0\n\n\n__all__ = [\"Signal\"]\n", "meta": {"hexsha": "429ad08129ca60e33eeedcfd36f32ff0b718d53e", "size": 36444, "ext": "py", "lang": "Python", "max_stars_repo_path": "acoustics/_signal.py", "max_stars_repo_name": "cnheider/python-acoustics", "max_stars_repo_head_hexsha": "fbc87454422c41e1a39e282d7680126a6d8014dd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 371, "max_stars_repo_stars_event_min_datetime": "2015-02-21T19:16:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T03:36:56.000Z", "max_issues_repo_path": "acoustics/_signal.py", "max_issues_repo_name": "sky-enter/python-acoustics", "max_issues_repo_head_hexsha": "fbc87454422c41e1a39e282d7680126a6d8014dd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 80, "max_issues_repo_issues_event_min_datetime": "2015-01-03T09:48:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T23:09:11.000Z", "max_forks_repo_path": "acoustics/_signal.py", "max_forks_repo_name": "sky-enter/python-acoustics", "max_forks_repo_head_hexsha": "fbc87454422c41e1a39e282d7680126a6d8014dd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 109, "max_forks_repo_forks_event_min_datetime": "2015-01-26T01:46:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T06:41:42.000Z", "avg_line_length": 32.802880288, "max_line_length": 141, "alphanum_fraction": 0.5905498848, "include": true, "reason": "import numpy,from scipy", "num_tokens": 8787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.18331850902860514}}
{"text": "from typing import Dict, Optional, Sequence, Union\n\nimport numpy as np\nimport astropy.units as u\n\nfrom zodipy._astroquery import query_target_positions\nfrom zodipy._emissivities import get_emissivities\nfrom zodipy._integration_config import integration_config_registry\nfrom zodipy._simulation import instantaneous_emission, time_ordered_emission\nfrom zodipy.models import model_registry\n\n\nclass InterplanetaryDustModel:\n    \"\"\"The Zodipy simulation interface.\n\n    The Interplanetary Dust Model used by Zodipy is the Kelsall et al. (1998)\n    Interplanetary Dust Model, which includes five (six) Zodiacal components:\n        - The Diffuse Cloud (cloud)\n        - Three Asteroidal Bands (band1, band2, band3)\n        - The Circumsolar Ring (ring) + The Earth-trailing Feature (feature)\n\n    Optionally, it is possible to scale the K98 emission with component\n    specific emissivities, as done by the Planck Collaboration. This is\n    achieved by specifiying one of the following implemented models:\n        - Planck13 (all five Kelsall components + emissivity fits for each)\n        - Planck15 (cloud + bands + new emissivity fits)\n        - Planck18 (cloud + bands + the latest emissivity fits)\n\n    NOTE: No extrapolation is done when using the fitted emissivities, and as\n    such, these models can only be evaluated within the frequency range covered\n    by the Planck HFI Bands for which the emissivities were fitted.\n    \"\"\"\n\n    def __init__(self, model: str = \"K98\") -> None:\n        \"\"\"Initializes the interface given an Interplanetary Dust Model.\n\n        Parameters\n        ----------\n        model\n            The name of the model to initialize.\n        \"\"\"\n\n        self.model = model_registry.get_model(model)\n        integration_config = integration_config_registry.get_config(\"default\")\n        self.line_of_sights = [\n            line_of_sight for line_of_sight in integration_config.values()\n        ]\n\n    @u.quantity_input(freq_or_wavelength=(\"Hz\", \"m\", \"micron\"))\n    def get_instantaneous_emission(\n        self,\n        freq_or_wavelength: u.Quantity,\n        nside: int,\n        *,\n        observer: str = \"L2\",\n        epochs: Optional[Union[float, Sequence[float], Dict[str, str]]] = None,\n        return_comps: bool = False,\n        coord_out: str = \"E\",\n    ) -> Union[np.ndarray, Dict[str, np.ndarray]]:\n        \"\"\"Simulates and returns the instantaneous Zodiacal Emission [MJy/sr].\n\n        By instantaneous emission we mean the emission observed at an instant\n        in time. If multiple epochs are given, the returned emission will be\n        the mean of all simulated instantaneous observations.\n\n        The observer location, given by the parameter `observer` (and\n        optionally the location of the Earth if either of the Feature or the\n        Ring components are included in the selected Interplanetary Dust Model)\n        are queried from the Horizons JPL ephemerides, given some epoch defined\n        by the `epochs` parameter.\n\n        NOTE: This function returns the fullsky emission from at a single time.\n        This means that we in the simulation evaluate line-of-sights that\n        sometimes points directly towards the inner Solar System and through\n        the Sun, where the dust density increases exponentially. Such\n        line-of-sights are unlikely to be observed by an actual observer, and\n        as such, the simulated emission will appear very bright in these\n        regions.\n\n        Parameters\n        ----------\n        freq_or_wavelength\n            Frequency or wavelength at which to evaluate the Zodiacal emission.\n        nside\n            HEALPIX map resolution parameter of the returned emission map.\n        observer\n            The name of the observer for which we quiery its location given\n            the `epochs` parameter. Defaults to 'L2'.\n        epochs\n            The observeration times given as a single epoch, or a list of epochs\n            in JD or MJD format, or a dictionary defining a range of times and\n            dates; the range dictionary has to be of the form\n            {'start':'YYYY-MM-DD [HH:MM:SS]', 'stop':'YYYY-MM-DD [HH:MM:SS]',\n            'step':'n[y|d|h|m|s]'}. If no epochs are provided, the current time\n            is used in UTC.\n        return_comps\n            If True, the emission is returned component-wise in a dictionary.\n            Defaults to False.\n        coord_out\n            Coordinate frame of the output map. Defaults to 'E' (heliocentered\n            ecliptic coordinates).\n\n        Returns\n        -------\n        emission\n            Simulated (mean) instantaneous Zodiacal emission [MJy/sr].\n        \"\"\"\n\n        observer_positions = query_target_positions(observer, epochs)\n        if self.model.includes_earth_neighboring_components:\n            earth_positions = query_target_positions(\"earth\", epochs)\n        else:\n            earth_positions = observer_positions.copy()\n\n        emissivities = get_emissivities(\n            ν_or_λ=freq_or_wavelength,\n            emissivity=self.model.emissivities,\n            components=list(self.model.components.keys()),\n        )\n\n        freq = freq_or_wavelength.to(\"Hz\", equivalencies=u.spectral()).value\n        emission = instantaneous_emission(\n            nside=nside,\n            freq=freq,\n            components=list(self.model.components.values()),\n            emissivities=emissivities,\n            observer_positions=observer_positions,\n            earth_positions=earth_positions,\n            line_of_sights=self.line_of_sights,\n            coord_out=coord_out,\n        )\n\n        if return_comps:\n            return {\n                comp.value: emission[idx]\n                for idx, comp in enumerate(self.model.components)\n            }\n\n        return emission.sum(axis=0)\n\n    @u.quantity_input(freq_or_wavelength=(\"Hz\", \"m\", \"micron\"))\n    def get_time_ordered_emission(\n        self,\n        freq_or_wavelength: u.Quantity,\n        nside: int,\n        *,\n        pixels: np.ndarray,\n        observer_position: np.ndarray,\n        earth_position: Optional[np.ndarray] = None,\n        bin: bool = False,\n        return_comps: bool = False,\n        coord_out: str = \"E\",\n    ) -> Union[np.ndarray, Dict[str, np.ndarray]]:\n        \"\"\"Simulates and returns the Zodiacal emission [MJy/sr] in a timestream.\n\n        Given a sequence of time-ordered pixels, the Zodiacal emission is\n        evaluated from a constant location in space given by the\n        `observer_position`. The `earth_position` is required for Interplanetary\n        Dust models that include the Earth-trailing Feature and Circum-solar\n        Ring components.\n\n        Parameters\n        ----------\n        freq_or_wavelength\n            Frequency or wavelength at which to evaluate the Zodiacal emission.\n        nside\n            HEALPIX map resolution parameter of the returned emission map.\n        pixels\n            Sequence of time-ordered pixels.\n        observer_position\n            The heliocentric ecliptic cartesian position of the observer at \n            the time of observing the tods.\n        earth_position\n            The heliocentric ecliptic cartesian position of the Earth at the \n            time of observing the tods. If None, the observer is assumed to be \n            the Earth. Defaults to None.\n        bin\n            If True, the time-ordered sequence of emission per pixel is binned\n            into a HEALPIX map. Defaults to False.\n        return_comps\n            If True, the emission is returned component-wise in a dictionary.\n            Defaults to False.\n        coord_out\n            Coordinate frame of the output map. Defaults to 'E' (heliocentric \n            ecliptic coordinates).\n\n        Returns\n        -------\n        emission\n            Simulated timestream of Zodiacal emission [MJy/sr] (optionally\n            binned into a HEALPIX map).\n        \"\"\"\n\n        if earth_position is None:\n            earth_position = observer_position\n\n        emissivities = get_emissivities(\n            ν_or_λ=freq_or_wavelength,\n            emissivity=self.model.emissivities,\n            components=list(self.model.components.keys()),\n        )\n\n        freq = freq_or_wavelength.to(\"Hz\", equivalencies=u.spectral()).value\n        emission = time_ordered_emission(\n            nside=nside,\n            freq=freq,\n            components=list(self.model.components.values()),\n            emissivities=emissivities,\n            line_of_sights=self.line_of_sights,\n            observer_position=observer_position,\n            earth_position=earth_position,\n            pixel_chunk=pixels,\n            bin=bin,\n            coord_out=coord_out,\n        )\n\n        if return_comps:\n            return {\n                comp.value: emission[idx]\n                for idx, comp in enumerate(self.model.components)\n            }\n\n        return emission.sum(axis=0)\n\n    def __str__(self) -> str:\n        \"\"\"String representation of the InterplanetaryDustModel.\"\"\"\n\n        reprs = []\n        for label, component in self.model.components.items():\n            component_repr = f\"{component.__class__.__name__}\" + \"\\n\"\n            reprs.append(f\"({label.value}): {component_repr}\")\n\n        main_repr = \"InterplanetaryDustModel(\"\n        main_repr += f\"\\n  name: {self.model.name}\"\n        main_repr += \"\\n  components( \"\n        main_repr += \"\\n    \" + \"    \".join(reprs)\n        main_repr += \"  )\"\n        main_repr += \"\\n)\"\n\n        return main_repr", "meta": {"hexsha": "1e75fbb5b012216368a18442e4f2a3bcf1aa7b26", "size": 9450, "ext": "py", "lang": "Python", "max_stars_repo_path": "zodipy/core.py", "max_stars_repo_name": "MetinSa/zodipy", "max_stars_repo_head_hexsha": "44725b106d8f09412b24667caedc6c8fa081f786", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-08-16T08:11:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T09:06:28.000Z", "max_issues_repo_path": "zodipy/core.py", "max_issues_repo_name": "MetinSa/zodipy", "max_issues_repo_head_hexsha": "44725b106d8f09412b24667caedc6c8fa081f786", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "zodipy/core.py", "max_forks_repo_name": "MetinSa/zodipy", "max_forks_repo_head_hexsha": "44725b106d8f09412b24667caedc6c8fa081f786", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.375, "max_line_length": 80, "alphanum_fraction": 0.6372486772, "include": true, "reason": "import numpy,import astropy", "num_tokens": 2002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.28776782186926264, "lm_q1q2_score": 0.18331696419126578}}
{"text": "import os\nimport subprocess\nimport glob\nimport sys\n\nimport numpy as np\nfrom scipy.integrate import simps\nfrom natsort import natsorted\nfrom astropy import units, constants\n\npath_program = os.path.dirname( os.path.dirname( os.path.realpath(__file__) ) ) + '/'\n\nclass galaxy_sed(object):\n\n  def __init__(self,\n         params,\n         resolution = 'lr',\n         model_name = 'Padova1994',\n         library = 'BaSeL',\n         library_vs = 2003,\n         units = 'flambda',\n         w1lambda = '700',\n         w2lambda = '20000',\n         SFH_tt = 0,\n         SFH_sf = 0):\n\n    '''\n    metallicity:   Initial metallicity of the galaxy. Options\n             supported:\n             0.0001, 0.0004, 0.004, 0.008, 0.02, 0.05, 0.1 [Padova1994]\n             0.0004, 0.001, 0.004, 0.008, 0.019, 0.03 [Padova2000]\n    imf:       IMF options:\n              salpeter, chabrier, and kroupa\n    resolution:    Resolution of BC03 templates\n              - 'hr':     High resolution\n              - 'lr':     Low resolution\n    library:     Specify specific library (only valid for 2012 version) -- 'stelib','BaSeL'\n    library_vs: Specify which version of BC03 -- 2003, 2012\n    dust:      Dust attenuation embedded in GALAXEV or post-processing\n             Dictionary: \n             flag : 0 GALAXEV 1 post-processing\n             GALAXEV option (Bruzual & Fall 2000, BC03 eq.6)\n              tau_V : grid\n              tau_V from ISM : 0.3 with scatter\n             Post-processing\n              ext_law : calzetti, fitzpatrick07, fitzpatrick, odonnell, cardelli\n              reddening : grid\n    sed:       Return SED\n             flag Y or N\n              units Units to return the SEDs\n                'lnu':     ergs/s/Hz\n                'llambda':   ergs/s/Angs\n\n              W1, W2 wavelength range to compute the SED\n    '''\n\n    # check that all required keys are in params\n    required_keys = ['metallicity', \n                     'IMF',  \n                     'dust', \n                     'survey_filt',\n                     'flag_mag',\n                     'em_lines',\n                     'flag_IGM_ext',\n                     'cosmo',\n                     'seed',\n                     'work_dir']\n\n    for key in required_keys:\n      try:\n        val = params[key]\n      except KeyError:\n        raise Exception(key + ' is not defined in params')\n\n    path_one_lvl   = os.path.dirname(os.path.dirname(__file__)) + '/'\n    self.seed    = params['seed']\n    self.galaxev_dir = path_one_lvl + 'bc03/'\n    self.em_line_dir = path_one_lvl + 'gutkin/'\n    # self.work_dir  = path_one_lvl + 'runs/' + params['seed'] + '/'\n    self.work_dir  = params['work_dir']\n    self.survey_name = params['survey_filt']\n    self.survey_filt = path_one_lvl + 'filters/' + params['survey_filt'] + '/'\n         \n    self.metallicity   = params['metallicity']\n    self.imf       = params['IMF']\n    self.dust      = params['dust']\n    self.flag_mag    = params['flag_mag']\n    self.em_lines    = params['em_lines']\n    self.flag_IGM_ext  = params['flag_IGM_ext']\n\n    self.cosmo     = params['cosmo']\n    self.resolution  = resolution\n    self.model_name  = model_name\n    self.library   = library\n    self.library_vs  = library_vs\n    self.units     = units\n    self.w1lambda  = w1lambda\n    self.w2lambda  = w2lambda\n      \n    self.check_input()\n\n    if(self.imf == 'chab'):\n      self.imf2 = 'chabrier'\n    if(self.imf == 'kroup'):\n      self.imf2 = 'kroupa'\n    if(self.imf == 'salp'):\n      self.imf2 = 'salpeter'\n\n    self.input_ised = (self.galaxev_dir \n               + '/models/' \n               + self.model_name \n               + '/'\n               + self.imf2\n               +'/bc' \n               + str(library_vs) \n               + '_' \n               + self.resolution \n               + '_' \n               + self.library \n               + '_' \n               + self.metallicity_key[self.metallicity] \n               + '_' \n               + self.imf \n               + '_ssp.ised')\n\n    self.csp_output = self.work_dir + self.seed + '_csp_out'\n    self.gpl_output = self.work_dir + self.seed + '_gpl_out'\n\n    # select filters old_version\n    # self.select_filters()\n\n    # export everything that we need to run galaxev\n    self.define_env()\n\n    if(np.isscalar(SFH_tt)):\n\n      import pickle\n      file_SFH  = (path_one_lvl \n            + 'runs/SFHs/' \n            + 'SFHn_'\n            + 'gal_type_' \n            + params['gal_type']\n            + '.pkl')\n\n      dict_save =  pickle.load( open( file_SFH, \"rb\" ) )\n      aa = np.argmin( abs(params['mpeak'] - dict_save['arr_mpeak']) )\n      self.age_SFH = dict_save['arr_tt']\n      self.SFH = dict_save['arr_SFH'][aa,:].flatten()\n\n    else:\n      self.age_SFH = SFH_tt\n      self.SFH = SFH_sf\n    # st_mass = simps(self.SFH, self.age_SFH)\n\n    self.file_SFH = self.work_dir + self.seed + '_SFH.txt'\n    np.savetxt(self.file_SFH, np.transpose([self.age_SFH, self.SFH]))\n\n    # run CSP GALAXEV\n    self.run_galaxev_csp()\n\n\n  def check_input(self):\n\n    if(self.model_name == 'Padova1994'):\n      self.metallicity_key = {0.0001:'m22',\n                  0.0004:'m32',\n                  0.004:'m42',\n                  0.008:'m52',\n                  0.02:'m62',\n                  0.05:'m72',\n                  0.1:'m82'}\n    elif(self.model_name == 'Padova2000'):\n      self.metallicity_key = {0.0004:'m122',\n                  0.001:'m132',\n                  0.004:'m142',\n                  0.008:'m152',\n                  0.019:'m162',\n                  0.03:'m72'}\n\n    if self.metallicity not in self.metallicity_key.keys():\n      raise Exception('Incorrect metallicity provided: ' \n              + str(self.metallicity) + '\\n' +\n              'Please choose from:' + str(self.metallicity_key.keys()))\n\n    imf_keys = ['salp', 'chab', 'kroup']\n    if self.imf not in imf_keys:\n      raise Exception( 'Incorrect IMF provided: '+ self.imf +'\\n'\n              + 'Please choose from:' + imf_keys )\n\n    # gal_type_keys = ['sf', 'qs']\n    # if self.gal_type not in gal_type_keys:\n    #   raise Exception( 'Incorrect gal_type provided: '+ self.gal_type +'\\n'\n    #           + 'Please choose from:' + gal_type_keys )\n\n    ext_keys = ['N', 'galaxev', 'calzetti', 'fitzpatrick07', \n      'fitzpatrick', 'odonnell', 'cardelli']\n    if self.dust['flag'] not in ext_keys:\n      raise Exception('Dust flag not correct \\n' +\n              'Please choose from: ' + ext_keys)\n\n    dust_keys = ['tau_V', 'etau_V']\n    if(self.dust['flag'] == 'galaxev'):\n      if not all (key in self.dust.keys() for key in dust_keys):\n        raise Exception('Incorrect keys in dust,' +\n          'you have to include tau_V and etau_V')\n\n    dust_keys = ['Av']\n    if( (self.dust['flag'] != 'galaxev') & (self.dust['flag'] != 'N') ):\n      if not all (key in self.dust.keys() for key in dust_keys):\n        raise Exception('Incorrect keys in dust,' +\n          'you have to include Av')\n\n    if not os.path.isdir(self.survey_filt):\n      raise Exception('Filter directory not found at :' \n        + str(self.survey_filt) )\n\n    if os.path.isdir(self.work_dir) == False:\n      try:\n        os.makedirs(self.work_dir)\n      except:\n        raise(self.work_dir + ' cannot be created')\n\n    model_name_keys = ['Padova1994', 'Padova2000']\n    if self.model_name not in model_name_keys:\n      raise Exception('Incorrect model provided: '\n              + self.model_name +'\\n' +\n              'Please choose from:' + model_name_keys )\n\n    resolution_keys = ['hr', 'lr']\n    if self.resolution not in resolution_keys:\n      raise Exception('Incorrect resolution provided: '\n              +str(self.resolution)+'\\n' +\n              'Please choose from: ' + resolution_keys )\n\n    units_keys = ['flambda', 'fnu']\n    if self.units not in units_keys:\n      raise Exception('Incorrect flux units provided: ' \n              + str(self.units) + '\\n' +\n              'Please choose from: ' + units_keys )\n\n    library_vs_keys = [2003, 2012]\n    if self.library_vs not in library_vs_keys:\n      raise Exception('Invalid library_vs: '+ self.library_vs \n              + '\\n' + 'Please choose from: ' \n              + library_vs_keys)\n\n    library_keys = ['stelib', 'BaSeL']\n    if self.library not in library_keys:\n      raise Exception('Incorrect library choice: '\n              + library_keys +'\\n' +\n              'Please choose from: ' + library_keys)\n\n\n  def define_env(self):\n    ''' Needed to run GALAXEV. \n      Note: this is only working in Linux'''\n\n    self.env_string = ('export FILTERS=' \n              + self.galaxev_dir \n              + 'src/FILTERBIN.RES;' \n              + 'export A0VSED='\n              + self.galaxev_dir\n              + 'src/A0V_KURUCZ_92.SED;'\n              + 'export RF_COLORS_ARRAYS='\n              + self.galaxev_dir\n              + 'src/RF_COLORS.filters;' \n              + 'export SUNSED='\n              + self.galaxev_dir\n              + 'src/SUN_KURUCZ_92.SED;')\n\n\n  def run_galaxev_csp(self):\n\n    # In the presence of dust attenuation and emission lines, we need\n    # to run the code twice. This is because we introduce emission lines\n    # a posteriori, and we need to know the impact of dust attenuation\n    # on them. This is only true for the galaxev dust attenuation model,\n    # as it depends on the SFH. For other models it is not necessary\n\n    if((self.dust['flag'] == 'galaxev') & (self.em_lines['flag'] == 'Y')):\n      it = 2\n    else:\n      it = 1\n\n    for ii in range(it):\n      if(ii == 0):\n        if(self.dust['flag'] == 'galaxev'):\n          flag_dust = ('Y' \n                + '\\n' \n                + self.dust['tau_V'] \n                + '\\n' \n                + self.dust['etau_V'])\n        else:\n          flag_dust = 'N'\n        name_out = self.csp_output\n      else:\n        flag_dust = 'N'\n        name_out = self.csp_output + '_nd'\n\n      csp_input = (self.input_ised \n             + '\\n'\n             + flag_dust \n             + '\\n'\n             + '0\\n'\n             + '6\\n'\n             + self.file_SFH\n             + '\\n'\n             + name_out\n             + '\\n')\n    \n      csp_input_file = self.work_dir + self.seed + '_csp.in'\n      with open(csp_input_file, 'w') as file: \n        file.write(csp_input)\n\n      call_string = (self.env_string \n              + self.galaxev_dir \n              +'src/csp_galaxev < ' \n              + csp_input_file)\n\n      # call csp_galaxev\n      subprocess.call(call_string,\n              cwd = self.work_dir, \n              shell=True, \n              # stdout = open(self.work_dir+'aa.txt', 'w'), \n              # stderr = open(self.work_dir+'ab.txt', 'w'))\n              stdout=open(os.devnull,'w'), \n              stderr=open(os.devnull,'w'))\n\n\n\n  def run_galaxev_gpl(self, zz0):\n\n    # output zz, age, wav_em, lum_em\n\n    self.zz = []\n    self.age = []\n\n    if(len(zz0) <= 50):\n      zz = zz0\n      it = 1\n    else:\n      # 50 is the maximum number of outputs from galaxevpl\n      num = np.ceil(len(zz0)/50.)\n      zz_arr = np.array_split(zz0, num)\n      it = len(zz_arr)\n\n    if((self.dust['flag'] == 'galaxev') & (self.em_lines['flag'] == 'Y')):\n      it2 = 2\n    else:\n      it2 = 1\n\n    for ii in range(it):\n      if(len(zz0) > 50):\n        zz = zz_arr[ii]\n\n      age = np.array(self.cosmo.age(zz).value)\n      self.zz.append(zz)\n      self.age.append(np.around(age, decimals=3))\n      ages = ','.join(age.astype(str))\n\n      for jj in range(it2):\n        if(jj == 0):\n          infile = self.csp_output\n          outfile = self.gpl_output+str(ii)+'.dat'\n        else:\n          infile = self.csp_output + '_nd'\n          outfile = self.gpl_output+str(ii)+'_nd.dat'\n\n        # call galaxevpl        \n        gpl_input = (infile\n                   + '\\n'\n                   + ages\n                   + '\\n'\n                   + self.w1lambda\n                   + ','\n                   + self.w2lambda\n                   + '\\n'\n                   + outfile)\n\n        gpl_input_file = self.work_dir + self.seed + '_gpl.in'\n        with open(gpl_input_file, 'w') as file: \n          file.write(gpl_input)\n\n        verbose = 0\n        if(verbose == 0):\n          subprocess.call(self.galaxev_dir\n                  + 'src/galaxevpl < '\n                  + gpl_input_file,\n                  cwd = self.work_dir, \n                  shell = True, \n                  # stdout = open(self.work_dir+'aa.txt', 'w'), \n                  # stderr = open(self.work_dir+'ab.txt', 'w'))\n                  stdout = open(os.devnull, 'w'), \n                  stderr = open(os.devnull, 'w'))\n        else:\n          subprocess.call(self.galaxev_dir\n                  + 'src/galaxevpl < '\n                  + gpl_input_file,\n                  cwd = self.work_dir, \n                  shell = True, \n                  stdout = open(self.work_dir+'aa.txt', 'w'), \n                  stderr = open(self.work_dir+'ab.txt', 'w'))\n\n      self.read_gpl(it=ii)\n\n    # once we have read everything, we convert luminosities to\n    # fluxes and magnitudes\n    self.zz = np.concatenate(self.zz)\n    self.n_zz = len(self.zz)\n    self.age = np.concatenate(self.age)\n    self.lum_em = np.concatenate(self.lum_em, axis=1)\n\n    # apply dust attenuation now if model != galaxev\n    if( (self.dust['flag'] != 'galaxev') & (self.dust['flag'] != 'N') ):\n        self.apply_dust()\n\n    self.lum2fluxmag()\n\n\n  def read_gpl(self, it=0):\n\n    # read gpl output (luminosity), introduce emission lines, and\n    # apply IGM extinction\n    # output wav_em, lum_em\n\n    infile = self.gpl_output + str(it) + '.dat'\n    # I want to get F_lambda erg cm^-2 s^-1 A^-1\n    # The code is in Lsun/Angstrom\n    fil = np.loadtxt(infile)\n    if(it == 0):\n      # Angstrom\n      self.wav_em = fil[:, 0]\n      self.lum_em = []\n\n    # units Lsun/Angstrom\n    self.lum_em.append(fil[:, 1:])\n\n    # Introduce emission lines\n    if(self.em_lines['flag'] == 'Y'):\n      if(self.dust['flag'] == 'galaxev'):\n        infile_nd = self.gpl_output + str(it) + '_nd.dat'\n        fil_em = np.loadtxt(infile_nd)\n        dust_att = fil[:, 1:]/fil_em[:, 1:]\n      else:\n        # multiplicative factor\n        dust_att = 1\n\n      self.add_emlines(dust_att = dust_att,\n                       it = it,\n                       pmetal = self.em_lines['metal_line'],\n                       plogio = self.em_lines['log_io'])\n\n    # Apply IGM extinction\n    if(self.flag_IGM_ext == 'Y'):\n      self.igm_ext(it=it)\n\n\n  def lum2fluxmag(self, ini_wav=1300, out_wav=110000):\n\n    ind = np.where( (self.wav_em >= ini_wav) & (self.wav_em <= out_wav) )[0]\n    self.wav = self.wav_em[ind]\n    self.obv_sed = np.zeros((len(self.wav), self.n_zz))\n    \n    # flux_lambda_obs = Lum_lambda_em / (4 pi D_L^2 (1+z))\n    for ii in range(0, self.n_zz):\n      if(self.zz[ii] > 0):\n        # move sed to obs wav, interpolate, get results at the\n        # self.wav (we want all spectra with the same wav)\n        lum_at_obs = np.interp(self.wav, \n                     self.wav_em*(1+self.zz[ii]), \n                     self.lum_em[:, ii])\n\n        dist_lum = self.cosmo.luminosity_distance(self.zz[ii]).value #Mpc        \n        num = lum_at_obs * units.L_sun.to('erg/s') # units lum erg s^-1 A^-1\n        # BC03 Eq. 8 \n        #dist lum units Mpc -> cm\n        den = 4 * np.pi * (dist_lum * units.Mpc.to('cm'))**2 * (1 + self.zz[ii])\n        self.obv_sed[:, ii] = num/den\n\n    if(self.flag_mag == 'Y'):    \n    # read the filters where we are going to compute magnitudes\n      self.read_filters()\n      self.compute_obs_mags()\n\n\n  def compute_obs_mags(self, rest_frame=False):\n\n    # mag = -2.5 * log10 (i1/i2)\n    # i1 = dlambda lambda obv_sed * R(lambda)\n    # i2 = dlambda lambda C_lambda R(lambda)\n\n    clight = constants.c.to('Angstrom/s').value # A s^-1\n    sysAB_nu = 3.631e-20 # ergs s^-1 cm^-2 Hz^-1\n    # F_lambda erg cm^-2 s^-1 A^-1\n\n    self.obs_flux = np.zeros( (self.n_filters, self.n_zz) )\n    self.obs_mag = np.zeros( (self.n_filters, self.n_zz) )\n    if(rest_frame == True):\n        self.rest_mag = np.zeros( (self.n_filters, self.n_zz) )\n\n    for jj in range(0, self.n_filters):\n      xx = self.filters['wav_'+str(jj)]\n      yy0 = xx * self.filters['trans_'+str(jj)]\n\n      den_f = simps(yy0, xx)\n\n      sysAB_lambda = sysAB_nu * clight / xx**2\n      yy = sysAB_lambda * yy0\n      den_m = simps(yy, xx)\n\n      for ii in range(0, self.n_zz):\n        if(self.zz[ii] > 0):\n        \n          flux_at_band_wav = np.interp(self.filters['wav_'+str(jj)], \n                                       self.wav, \n                                       self.obv_sed[:, ii])\n                        \n          yy = flux_at_band_wav * yy0\n          num = simps(yy, xx)\n\n          self.obs_mag[jj, ii] = -2.5 * np.log10(num/den_m)\n          self.obs_flux[jj, ii] = num/den_f\n\n          if(rest_frame == True):\n              # rest frame mag for color ev. (amplitude wrong)\n              flux_at_band_wav = np.interp(self.filters['wav_'+str(jj)], \n                                           self.wav_em, \n                                           self.lum_em[:, ii])\n              yy = flux_at_band_wav * yy0\n              num = simps(yy, xx)\n              self.rest_mag[jj, ii] = -2.5 * np.log10(num/den_m)\n\n  # best-fit parameters to SDSS 7 data (0.04<z<0.2)\n  # standard model\n  # vary pmetal\n  def add_emlines(self,\n                  it = 0,\n                  dust_att = 0,\n                  pmetal = 0.014, \n                  plogio = -3.5,\n                  pd2m = 0.3,\n                  phden = 100, \n                  pC20 = 1., # C0 solar\n                  pIMF = 100):\n\n    # col 1 log ionization param\n    # keys_logio = -(np.arange(7)/2. + 1)\n    # -1, -4\n    # plogio = -1\n    # very important .44, .1, .2, .05\n\n    # col 2 dust-to-metal ratio\n    # keys_dust2metal = np.array([0.1, 0.3, 0.5])\n    # pd2m = 0.3\n    # important .2, .05\n\n    # col 3 hydrogen gas density (per cubic cm)\n    # keys_hden = np.array([100, 1000])\n    # phden = 100\n    # not very important .05, .06\n\n    # col 4 C/O ratio in units of solar value\n    # keys_C2O = np.array([0.10, 0.14, 0.20, 0.27, 0.38, 0.52, \n    #   0.72, 1.00, 1.40])\n    # pC20 = 0.38\n    # not important, less than .05\n\n    # col 5 cutoff IMF\n    # keys_IMF = np.array([100, 300])\n    # pIMF = 100\n    # important .24, .14, .1 \n\n    # col 6-23:\n\n    #[OII]3727 \n    # Hbeta \n    #[OIII]4959 \n    #[OIII]5007 \n    #[NII]6548 \n    #Halpha \n    #[NII]6584 \n    #[SII]6717 \n    #[SII]6731 \n    #NV1240 \n    #CIV1548 \n    #CIV1551 \n    #HeII1640 \n    #OIII]1661 \n    #OIII]1666 \n    #[SiIII]1883 \n    #SiIII]1888 \n    #CIII]1908\n\n    if(it == 0):\n      # Using line ratios from Gutkin et al. 2016\n      keys_metal = np.array([0.0001, 0.0002, 0.0005, 0.001, 0.002, 0.004, \n        0.006, 0.008, 0.010, 0.014, 0.017, 0.020, 0.030, 0.040])\n\n      ii = np.argmin( abs(pmetal - keys_metal) )\n      frac, _ = np.modf(keys_metal[ii])\n      str0 = str(frac)[2:]\n      if(len(str0) < 3):\n        str0 += '0'\n\n      self.line_wav = np.array([3727, 4862, 4959, 5007, 6548, 6564, \n        6584, 6717, 6731, 1240, 1548, 1551, 1640, 1661, 1666,\n        1883, 1888, 1908])\n      \n      file_in = 'nebular_emission_Z' + str0 + '.txt'\n      with open(self.em_line_dir + file_in, 'r') as file:\n        fil = np.loadtxt(file)\n      aa = np.where( (fil[:,0] == plogio) &\n               (fil[:,1] == pd2m) &\n               (fil[:,2] == phden) &\n               (fil[:,3] == pC20) &\n               (fil[:,4] == pIMF) )\n\n      # Lsun per unit SFR [Msun/yr]\n      self.line_rat = fil[aa, 5:].flatten()\n\n      \n\n    # Lyman alpha 1216\n    # Ly alpha to H alpha ratio 8.7 (Hu et al. 1998)\n    # From 9.1 to 11.6 Hummer & Storey et al. 1987\n    # due to absorption in the position of the line, we have to \n    # multiply the line intensity by a factor of a few to see a line!\n    # the problem is that we need to include nebular emission\n    # this is for the future\n    # lyabs = 1.e3\n    # self.line_wav = np.append(self.line_wav, [1216])\n    # self.line_rat = np.append(self.line_rat, [self.line_wav[5] * 8.7 * lyabs])\n    \n    \n    # position of lines\n    ind_lines = np.zeros(self.line_wav.shape[0], dtype=int)\n    # account for resolution of the spectrum\n    res_lambda = np.zeros(self.line_wav.shape[0])\n\n    # number of lines\n    nlines = len(self.line_wav)\n    for jj in range(0, nlines):\n      ind_lines[jj] = np.argmin( abs(self.line_wav[jj] - self.wav_em) )\n      res_lambda[jj] = abs(self.wav_em[ind_lines[jj]] - self.wav_em[ind_lines[jj]+1])\n\n    flag0 = np.isscalar(dust_att)\n    # introduce lines\n    len_arr = self.lum_em[it].shape[1]\n    for ii in range(0, len_arr):\n      ind = np.argmin( abs(self.age_SFH - self.age[it][ii]*1.e9) )\n      lum_lines = self.line_rat * self.SFH[ind]\n      if(flag0 == True):\n        self.lum_em[it][ind_lines, ii] += lum_lines / res_lambda\n      else:\n        self.lum_em[it][ind_lines, ii] += lum_lines * dust_att[ind_lines, ii] / res_lambda\n\n\n    # introduce properly lines only in high resolution spectra \n    # line_width 4 A\n    # sigma_line = 4\n    # for ii in range(0, self.n_zz):\n    #   ind = np.argmin( abs(self.age_SFH - self.age[ii]) )\n    #   SFR = self.SFH[ind]\n    #   lum_lines = self.line_rat * SFR\n    #   for jj in range(0, nlines):\n    #     norm = (1./np.sqrt(2*np.pi)/sigma_line) * lum_lines[jj]\n    #     line_prof = norm * np.exp(-0.5 * (self.wav_em - self.line_wav[jj])**2 / sigma_line**2)\n    #     self.lum_em[:, ii] += line_prof\n    \n\n\n  def read_filters(self):\n    # read filters\n    filter_files = glob.glob(self.survey_filt \n                 + self.survey_name \n                 + \"*\")\n    filter_files = natsorted(filter_files)\n\n    self.n_filters = len(filter_files)\n    self.filter_pivot = np.zeros(self.n_filters)\n    self.filters = {}\n\n    for ii, tempfile in enumerate(filter_files):\n      with open(tempfile, 'r') as file_temp:\n        fil = np.loadtxt(file_temp)\n        self.filters['wav_'+ str(ii)] = fil[:,0]\n        self.filters['trans_'+ str(ii)] = fil[:,1]\n        # pivot wavelength Eq. A11 Tokunaga & Vacca 2005\n        num = simps(fil[:,0] * fil[:,1], fil[:,0])\n        den = simps(fil[:,1] / fil[:,0], fil[:,0])\n        self.filter_pivot[ii] = np.sqrt(num/den)\n\n\n\n  def igm_ext(self, it=0):\n    # Becker et al. 2015\n    # Extinction shortward Lyman alpha\n    wav_LA = 1216.\n    sig_LA = 44.88\n\n    wav_LB = 1026.\n    sig_LB = 7.18\n\n    wav_LG = 972.\n    sig_LG = 2.50\n\n    len_arr = self.lum_em[it].shape[1]\n    for ii in range(0, len_arr):\n\n      # Barnett et al. 2017 Eq. 1\n      if(self.zz[it][ii] <= 5.5):\n        tauLA = 0.85 * ( (1.+self.zz[it][ii])/5. )**4.3\n      else:\n        tauLA = 2.63 * ( (1.+self.zz[it][ii])/6.5 )**11.\n      tauLB = sig_LB/sig_LA*tauLA\n      tauLG = sig_LG/sig_LA*tauLA\n      \n      extLA = np.exp(-tauLA)\n      extLB = np.exp(-tauLB)\n      extLG = np.exp(-tauLG)\n      \n      ind_LA = np.where(self.wav_em < wav_LA)[0]\n      ind_LB = np.where(self.wav_em < wav_LB)[0]\n      ind_LG = np.where(self.wav_em < wav_LG)[0]\n\n      self.lum_em[it][ind_LA, ii] *= extLA\n      self.lum_em[it][ind_LB, ii] *= extLB\n      self.lum_em[it][ind_LG, ii] *= extLG\n\n\n\n\n  def apply_dust(self):\n\n    import extinction\n\n    for ii in range(self.n_zz):\n      if self.dust['flag'] == 'calzetti':\n        self.lum_em[:, ii] = extinction.apply(extinction.calzetti00(self.wav_em, \n          self.dust['Av'], 4.05), self.lum_em[:, ii])\n      elif self.dust['flag'] == 'cardelli':\n        self.lum_em[:, ii] = extinction.apply(extinction.ccm89(self.wav_em, \n          self.dust['Av'], 4.05), self.lum_em[:, ii])\n      elif self.dust['flag'] == 'odonnell':\n        self.lum_em[:, ii] = extinction.apply(extinction.odonnell94(self.wav_em, \n          self.dust['Av'], 4.05), self.lum_em[:, ii])\n      elif self.dust['flag'] == 'fitzpatrick':\n        self.lum_em[:, ii] = extinction.apply(extinction.fitzpatrick99(self.wav_em, \n          self.dust['Av'], 3.1), self.lum_em[:, ii])\n      elif self.dust['flag'] == 'fitzpatrick07':\n        self.lum_em[:, ii] = extinction.apply(extinction.fm07(self.wav_em, \n          self.dust['Av']), self.lum_em[:, ii])\n\n\n    # for ii in range(0, self.n_zz):\n    #   if self.dust['flag'] == 'calzetti':\n    #     self.obv_sed[:, ii] = extinction.apply(extinction.calzetti00(self.wav, \n    #       self.dust['Av'], 4.05), self.obv_sed[:, ii])\n    #   elif self.dust['flag'] == 'cardelli':\n    #     self.obv_sed[:, ii] = extinction.apply(extinction.ccm89(self.wav, \n    #       self.dust['Av'], 4.05), self.obv_sed[:, ii])\n    #   elif self.dust['flag'] == 'odonnell':\n    #     self.obv_sed[:, ii] = extinction.apply(extinction.odonnell94(self.wav, \n    #       self.dust['Av'], 4.05), self.obv_sed[:, ii])\n    #   elif self.dust['flag'] == 'fitzpatrick':\n    #     self.obv_sed[:, ii] = extinction.apply(extinction.fitzpatrick99(self.wav, \n    #       self.dust['Av'], 3.1), self.obv_sed[:, ii])\n    #   elif self.dust['flag'] == 'fitzpatrick07':\n    #     self.obv_sed[:, ii] = extinction.apply(extinction.fm07(self.wav, \n    #       self.dust['Av']), self.obv_sed[:, ii])\n\n\n  # def select_filters_old(self):\n  #   # create new file by appending new filters at the end\n  #   # of filterfrm.res\n\n  #   file_name = 'filterfrm.res'\n\n  #   file_all_filt = self.galaxev_dir + 'src/' + file_name\n  #   file_all_filt_temp = self.work_dir + file_name\n  #   if os.path.isfile(file_all_filt):\n  #     shutil.copyfile(file_all_filt, file_all_filt_temp)\n  #   else:\n  #     raise Exception('The file ' + file_all_filt + ' does not exist')\n\n  #   filter_files = glob.glob(self.survey_filt + self.survey_name + \"*\")\n  #   filter_files = natsorted(filter_files)\n\n  #   with open(file_all_filt_temp, 'a+') as file:\n  #     for tempfile in filter_files:\n  #       with open(tempfile, 'r') as file_temp:\n  #         tempfile_name_ext = os.path.basename(tempfile)\n  #         t_name, t_ext = os.path.splitext(tempfile_name_ext)\n  #         file.write('# ' + t_name + '\\n')\n  #         file.write(file_temp.read())\n\n  #   input_string = (file_all_filt_temp \n  #           + '\\nn\\ny\\n'\n  #           + self.galaxev_dir \n  #           + 'src/FILTERBIN.RES')\n  #   input_file = self.work_dir + self.seed + '_filt.in'\n  #   with open(input_file, 'w') as file: \n  #     file.write(input_string)\n\n  #   subprocess.call(self.galaxev_dir \n  #           + 'src/add_filters < ' \n  #           + input_file, \n  #           cwd = self.work_dir, \n  #           shell = True)\n\n  #   file_name = 'filters.log'\n  #   shutil.copyfile(self.work_dir + file_name, \n  #           self.galaxev_dir + 'src/' + file_name)\n\n\n\n", "meta": {"hexsha": "514c803ca71e6ef4871b10a29506e55c16565bce", "size": 26452, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/galaxpy.py", "max_stars_repo_name": "jchavesmontero/galaxpy", "max_stars_repo_head_hexsha": "ef5eaffa8f5ec0418dae44b88cf212ca03814b57", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-29T02:26:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-15T22:22:35.000Z", "max_issues_repo_path": "src/galaxpy.py", "max_issues_repo_name": "jchavesmontero/galaxpy", "max_issues_repo_head_hexsha": "ef5eaffa8f5ec0418dae44b88cf212ca03814b57", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/galaxpy.py", "max_forks_repo_name": "jchavesmontero/galaxpy", "max_forks_repo_head_hexsha": "ef5eaffa8f5ec0418dae44b88cf212ca03814b57", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3769889841, "max_line_length": 96, "alphanum_fraction": 0.5383713897, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 7774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.18331218970714644}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Authors: James D. McClain\n#          Mario Motta\n#          Yang Gao\n#          Qiming Sun <osirpt.sun@gmail.com>\n#          Jason Yu\n#\n\nimport itertools\nimport time\nfrom functools import reduce\nimport numpy as np\nimport h5py\n\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf.pbc import scf\nfrom pyscf.cc import uccsd\nfrom pyscf.cc import eom_uccsd\nfrom pyscf.cc import eom_rccsd\nfrom pyscf.pbc.lib import kpts_helper\nfrom pyscf.lib.parameters import LOOSE_ZERO_TOL, LARGE_DENOM\nfrom pyscf.pbc.lib.kpts_helper import member, gamma_point\nfrom pyscf import __config__\nfrom pyscf.pbc.cc import kintermediates as imd\nfrom pyscf.pbc.cc.kccsd_rhf import _get_epq\nfrom pyscf.pbc.cc.kccsd_t_rhf import _get_epqr\nfrom pyscf.pbc.mp.kmp2 import (get_frozen_mask, get_nocc, get_nmo,\n                               padded_mo_coeff, padding_k_idx)\n\neinsum = lib.einsum\n\ndef kernel(eom, nroots=1, koopmans=False, guess=None, left=False,\n           eris=None, imds=None, partition=None, kptlist=None,\n           dtype=None, **kwargs):\n    '''Calculate excitation energy via eigenvalue solver\n\n    Kwargs:\n        nroots : int\n            Number of roots (eigenvalues) requested per k-point\n        koopmans : bool\n            Calculate Koopmans'-like (quasiparticle) excitations only, targeting via\n            overlap.\n        guess : list of ndarray\n            List of guess vectors to use for targeting via overlap.\n        left : bool\n            If True, calculates left eigenvectors rather than right eigenvectors.\n        eris : `object(uccsd._ChemistsERIs)`\n            Holds uccsd electron repulsion integrals in chemist notation.\n        imds : `object(_IMDS)`\n            Holds eom intermediates in chemist notation.\n        partition : bool or str\n            Use a matrix-partitioning for the doubles-doubles block.\n            Can be None, 'mp' (Moller-Plesset, i.e. orbital energies on the diagonal),\n            or 'full' (full diagonal elements).\n        kptlist : list\n            List of k-point indices for which eigenvalues are requested.\n        dtype : type\n            Type for eigenvectors.\n    '''\n    cput0 = (time.clock(), time.time())\n    log = logger.Logger(eom.stdout, eom.verbose)\n    if eom.verbose >= logger.WARN:\n        eom.check_sanity()\n    eom.dump_flags()\n\n    if imds is None:\n        imds = eom.make_imds(eris=eris)\n\n    size = eom.vector_size()\n    nroots = min(nroots,size)\n    nkpts = eom.nkpts\n\n    if kptlist is None:\n        kptlist = range(nkpts)\n\n    # Make the max number of roots the maximum number of occupied orbitals at any given\n    # kpoint in the list\n    for k, kshift in enumerate(kptlist):\n        frozen_orbs = eom.mask_frozen(np.zeros(size, dtype=int), kshift, const=1)\n        if isinstance(frozen_orbs, tuple):\n            nfrozen  = (np.sum(frozen_orbs[0]), np.sum(frozen_orbs[1]))\n            nroots = min(nroots, size - nfrozen[0])\n            nroots = min(nroots, size - nfrozen[1])\n        else:\n            nfrozen = np.sum(frozen_orbs)\n            nroots = min(nroots, size - nfrozen)\n\n    if dtype is None:\n        dtype = np.result_type(*imds.t1)\n\n    evals = np.zeros((len(kptlist),nroots), np.float)\n    evecs = np.zeros((len(kptlist),nroots,size), dtype)\n    convs = np.zeros((len(kptlist),nroots), dtype)\n\n    for k, kshift in enumerate(kptlist):\n        matvec, diag = eom.gen_matvec(kshift, imds, left=left, **kwargs)\n        diag = eom.mask_frozen(diag, kshift, const=LARGE_DENOM)\n\n        user_guess = False\n        if guess is not None:\n            user_guess = True\n            assert len(guess) == nroots\n            for g in guess:\n                assert g.size == size\n        else:\n            user_guess = False\n            guess = eom.get_init_guess(kshift, nroots, koopmans, diag)\n        for ig, g in enumerate(guess):\n            guess_norm = np.linalg.norm(g)\n            guess_norm_tol = LOOSE_ZERO_TOL\n            if guess_norm < guess_norm_tol:\n                raise ValueError('Guess vector (id=%d) with norm %.4g is below threshold %.4g.\\n'\n                                 'This could possibly be due to masking/freezing orbitals.\\n'\n                                 'Check your guess vector to make sure it has sufficiently large norm.'\n                                 % (ig, guess_norm, guess_norm_tol))\n\n        def precond(r, e0, x0):\n            return r/(e0-diag+1e-12)\n\n        eig = lib.davidson_nosym1\n        if user_guess or koopmans:\n            def pickeig(w, v, nroots, envs):\n                x0 = lib.linalg_helper._gen_x0(envs['v'], envs['xs'])\n                s = np.dot(np.asarray(guess).conj(), np.asarray(x0).T)\n                snorm = np.einsum('pi,pi->i', s.conj(), s)\n                idx = np.argsort(-snorm)[:nroots]\n                return lib.linalg_helper._eigs_cmplx2real(w, v, idx, real_eigenvectors=False)\n            conv_k, evals_k, evecs_k = eig(matvec, guess, precond, pick=pickeig,\n                                           tol=eom.conv_tol, max_cycle=eom.max_cycle,\n                                           max_space=eom.max_space, nroots=nroots, verbose=log)\n        else:\n            conv_k, evals_k, evecs_k = eig(matvec, guess, precond,\n                                           tol=eom.conv_tol, max_cycle=eom.max_cycle,\n                                           max_space=eom.max_space, nroots=nroots, verbose=log)\n\n        evals_k = evals_k.real\n        evals[k] = evals_k\n        evecs[k] = evecs_k\n        convs[k] = conv_k\n\n        for n, en, vn in zip(range(nroots), evals_k, evecs_k):\n            r1, r2 = eom.vector_to_amplitudes(vn, kshift=kshift)\n            if isinstance(r1, np.ndarray):\n                qp_weight = np.linalg.norm(r1)**2\n            else: # for EOM-UCCSD\n                r1 = np.hstack([x.ravel() for x in r1])\n                qp_weight = np.linalg.norm(r1)**2\n            logger.info(eom, 'EOM-CCSD root %d E = %.16g  qpwt = %0.6g',\n                        n, en, qp_weight)\n    log.timer('EOM-CCSD', *cput0)\n    return convs, evals, evecs\n\ndef enforce_2p_spin_doublet(r2, kconserv, kshift, orbspin, excitation):\n    '''Enforces condition that net spin can only change by +/- 1/2'''\n    assert(excitation in ['ip', 'ea'])\n    if excitation == 'ip':\n        nkpts, nocc, nvir = np.array(r2.shape)[[1, 3, 4]]\n    elif excitation == 'ea':\n        nkpts, nocc, nvir = np.array(r2.shape)[[1, 2, 3]]\n    else:\n        raise NotImplementedError\n\n    idxoa = [np.where(orbspin[k][:nocc] == 0)[0] for k in range(nkpts)]\n    idxob = [np.where(orbspin[k][:nocc] == 1)[0] for k in range(nkpts)]\n    idxva = [np.where(orbspin[k][nocc:] == 0)[0] for k in range(nkpts)]\n    idxvb = [np.where(orbspin[k][nocc:] == 1)[0] for k in range(nkpts)]\n\n    if excitation == 'ip':\n        for ki, kj in itertools.product(range(nkpts), repeat=2):\n            if ki > kj:  # Avoid double-counting of anti-symmetrization\n                continue\n            ka = kconserv[ki, kshift, kj]\n            idxoaa = idxoa[ki][:,None] * nocc + idxoa[kj]\n            idxoab = idxoa[ki][:,None] * nocc + idxob[kj]\n            idxoba = idxob[ki][:,None] * nocc + idxoa[kj]\n            idxobb = idxob[ki][:,None] * nocc + idxob[kj]\n\n            r2_tmp = 0.5 * (r2[ki, kj] - r2[kj, ki].transpose(1, 0, 2))\n            r2_tmp = r2_tmp.reshape(nocc**2, nvir)\n\n            # Zero out states with +/- 3 unpaired spins\n            r2_tmp[idxobb.ravel()[:, None], idxva[ka]] = 0.0\n            r2_tmp[idxoaa.ravel()[:, None], idxvb[ka]] = 0.0\n\n            r2[ki, kj] = r2_tmp.reshape(nocc, nocc, nvir)\n            r2[kj, ki] = -r2[ki, kj].transpose(1, 0, 2)  # Enforce antisymmetry\n    else:\n        for kj, ka in itertools.product(range(nkpts), repeat=2):\n            kb = kconserv[kshift, ka, kj]\n            if ka > kb:  # Avoid double-counting of anti-symmetrization\n                continue\n\n            idxvaa = idxva[ka][:,None] * nvir + idxva[kb]\n            idxvab = idxva[ka][:,None] * nvir + idxvb[kb]\n            idxvba = idxvb[ka][:,None] * nvir + idxva[kb]\n            idxvbb = idxvb[ka][:,None] * nvir + idxvb[kb]\n\n            r2_tmp = 0.5 * (r2[kj, ka] - r2[kj, kb].transpose(0, 2, 1))\n            r2_tmp = r2_tmp.reshape(nocc, nvir**2)\n\n            # Zero out states with +/- 3 unpaired spins\n            r2_tmp[idxoa[kshift], idxvbb.ravel()[:, None]] = 0.0\n            r2_tmp[idxob[kshift], idxvaa.ravel()[:, None]] = 0.0\n\n            r2[kj, ka] = r2_tmp.reshape(nocc, nvir, nvir)\n            r2[kj, kb] = -r2[kj, ka].transpose(0, 2, 1)  # Enforce antisymmetry\n    return r2\n\ndef get_padding_k_idx(eom, cc):\n    return padding_k_idx(cc, kind=\"split\")\n\n########################################\n# EOM-IP-CCSD\n########################################\n\ndef enforce_2p_spin_ip_doublet(r2, kconserv, kshift, orbspin):\n    return enforce_2p_spin_doublet(r2, kconserv, kshift, orbspin, 'ip')\n\ndef spin2spatial_ip_doublet(r1, r2, kconserv, kshift, orbspin):\n    '''Convert R1/R2 of spin orbital representation to R1/R2 of\n    spatial orbital representation '''\n    nkpts, nocc, nvir = np.array(r2.shape)[[1, 3, 4]]\n\n    idxoa = [np.where(orbspin[k][:nocc] == 0)[0] for k in range(nkpts)]\n    idxob = [np.where(orbspin[k][:nocc] == 1)[0] for k in range(nkpts)]\n    idxva = [np.where(orbspin[k][nocc:] == 0)[0] for k in range(nkpts)]\n    idxvb = [np.where(orbspin[k][nocc:] == 1)[0] for k in range(nkpts)]\n    nocc_a = len(idxoa[0])  # Assume nocc/nvir same for each k-point\n    nocc_b = len(idxob[0])\n    nvir_a = len(idxva[0])\n    nvir_b = len(idxvb[0])\n\n    r1a = r1[idxoa[kshift]]\n    r1b = r1[idxob[kshift]]\n\n    r2aaa = np.zeros((nkpts,nkpts,nocc_a,nocc_a,nvir_a), dtype=r2.dtype)\n    r2baa = np.zeros((nkpts,nkpts,nocc_b,nocc_a,nvir_a), dtype=r2.dtype)\n    r2abb = np.zeros((nkpts,nkpts,nocc_a,nocc_b,nvir_b), dtype=r2.dtype)\n    r2bbb = np.zeros((nkpts,nkpts,nocc_b,nocc_b,nvir_b), dtype=r2.dtype)\n    for ki, kj in itertools.product(range(nkpts), repeat=2):\n        ka = kconserv[ki, kshift, kj]\n        idxoaa = idxoa[ki][:,None] * nocc + idxoa[kj]\n        idxoab = idxoa[ki][:,None] * nocc + idxob[kj]\n        idxoba = idxob[ki][:,None] * nocc + idxoa[kj]\n        idxobb = idxob[ki][:,None] * nocc + idxob[kj]\n\n        r2_tmp = r2[ki, kj].reshape(nocc**2, nvir)\n        r2aaa_tmp = lib.take_2d(r2_tmp, idxoaa.ravel(), idxva[ka])\n        r2baa_tmp = lib.take_2d(r2_tmp, idxoba.ravel(), idxva[ka])\n        r2abb_tmp = lib.take_2d(r2_tmp, idxoab.ravel(), idxvb[ka])\n        r2bbb_tmp = lib.take_2d(r2_tmp, idxobb.ravel(), idxvb[ka])\n\n        r2aaa[ki, kj] = r2aaa_tmp.reshape(nocc_a, nocc_a, nvir_a)\n        r2baa[ki, kj] = r2baa_tmp.reshape(nocc_b, nocc_a, nvir_a)\n        r2abb[ki, kj] = r2abb_tmp.reshape(nocc_a, nocc_b, nvir_b)\n        r2bbb[ki, kj] = r2bbb_tmp.reshape(nocc_b, nocc_b, nvir_b)\n    return [r1a, r1b], [r2aaa, r2baa, r2abb, r2bbb]\n\ndef spatial2spin_ip_doublet(r1, r2, kconserv, kshift, orbspin=None):\n    '''Convert R1/R2 of spatial orbital representation to R1/R2 of\n    spin orbital representation '''\n    r1a, r1b = r1\n    r2aaa, r2baa, r2abb, r2bbb = r2\n    nkpts, nocc_a, nvir_a = np.array(r2aaa.shape)[[1, 3, 4]]\n    nkpts, nocc_b, nvir_b = np.array(r2bbb.shape)[[1, 3, 4]]\n\n    if orbspin is None:\n        orbspin = np.zeros((nkpts, nocc_a+nocc_b+nvir_a+nvir_b), dtype=int)\n        orbspin[:,1::2] = 1\n\n    nocc = nocc_a + nocc_b\n    nvir = nvir_a + nvir_b\n\n    idxoa = [np.where(orbspin[k][:nocc] == 0)[0] for k in range(nkpts)]\n    idxob = [np.where(orbspin[k][:nocc] == 1)[0] for k in range(nkpts)]\n    idxva = [np.where(orbspin[k][nocc:] == 0)[0] for k in range(nkpts)]\n    idxvb = [np.where(orbspin[k][nocc:] == 1)[0] for k in range(nkpts)]\n\n    r1 = np.zeros(nocc, dtype = r1a.dtype)\n    r1[idxoa[kshift]] = r1a\n    r1[idxob[kshift]] = r1b\n\n    r2 = np.zeros((nkpts, nkpts, nocc**2, nvir), dtype = r2aaa.dtype)\n    for ki, kj in itertools.product(range(nkpts), repeat=2):\n        ka = kconserv[ki, kshift, kj]\n        idxoaa = idxoa[ki][:,None] * nocc + idxoa[kj]\n        idxoab = idxoa[ki][:,None] * nocc + idxob[kj]\n        idxoba = idxob[ki][:,None] * nocc + idxoa[kj]\n        idxobb = idxob[ki][:,None] * nocc + idxob[kj]\n\n        r2aaa_tmp = r2aaa[ki,kj].reshape(nocc_a * nocc_a, nvir_a)\n        r2baa_tmp = r2baa[ki,kj].reshape(nocc_b * nocc_a, nvir_a)\n        r2abb_tmp = r2abb[ki,kj].reshape(nocc_a * nocc_b, nvir_b)\n        r2bbb_tmp = r2bbb[ki,kj].reshape(nocc_b * nocc_b, nvir_b)\n\n        lib.takebak_2d(r2[ki, kj], r2aaa_tmp, idxoaa.ravel(), idxva[ka])\n        lib.takebak_2d(r2[ki, kj], r2baa_tmp, idxoba.ravel(), idxva[ka])\n        lib.takebak_2d(r2[ki, kj], r2abb_tmp, idxoab.ravel(), idxvb[ka])\n        lib.takebak_2d(r2[ki, kj], r2bbb_tmp, idxobb.ravel(), idxvb[ka])\n\n        r2aba_tmp = - r2baa[kj,ki].reshape(nocc_a * nocc_b, nvir_a)\n        r2bab_tmp = - r2abb[kj,ki].reshape(nocc_a * nocc_b, nvir_b)\n\n        lib.takebak_2d(r2[ki, kj], r2aba_tmp, idxoab.T.ravel(), idxva[ka])\n        lib.takebak_2d(r2[ki, kj], r2bab_tmp, idxoba.T.ravel(), idxvb[ka])\n\n    r2 = r2.reshape(nkpts, nkpts, nocc, nocc, nvir)\n    return r1, r2\n\ndef vector_to_amplitudes_ip(vector, kshift, nkpts, nmo, nocc, kconserv):\n    nvir = nmo - nocc\n\n    r1 = vector[:nocc].copy()\n    r2_tril = vector[nocc:].copy().reshape(nkpts*nocc*(nkpts*nocc-1)//2,nvir)\n    idx, idy = np.tril_indices(nkpts*nocc, -1)\n    r2 = np.zeros((nkpts*nocc,nkpts*nocc,nvir), dtype=vector.dtype)\n    r2[idx, idy] = r2_tril\n    r2[idy, idx] = -r2_tril\n    r2 = r2.reshape(nkpts,nocc,nkpts,nocc,nvir).transpose(0,2,1,3,4)\n    return [r1,r2]\n\ndef amplitudes_to_vector_ip(r1, r2, kshift, kconserv):\n    nkpts, nocc, nvir = np.asarray(r2.shape)[[0,2,4]]\n    # From symmetry for aaa and bbb terms, only store lower\n    # triangular part (ki,i) < (kj,j)\n    idx, idy = np.tril_indices(nkpts*nocc, -1)\n    r2 = r2.transpose(0,2,1,3,4).reshape(nkpts*nocc,nkpts*nocc,nvir)\n    return np.hstack((r1, r2[idx,idy].ravel()))\n\ndef ipccsd_matvec(eom, vector, kshift, imds=None, diag=None):\n    '''2ph operators are of the form s_{ij}^{a }, i.e. 'ia' indices are coupled.\n    This differs from the restricted case that uses s_{ij}^{ b}.'''\n    if imds is None: imds = eom.make_imds()\n    nocc = eom.nocc\n    nmo = eom.nmo\n    nvir = nmo - nocc\n    nkpts = eom.nkpts\n    kconserv = imds.kconserv\n    r1, r2 = vector_to_amplitudes_ip(vector, kshift, nkpts, nmo, nocc, kconserv)\n\n    Hr1 = -np.einsum('mi,m->i', imds.Foo[kshift], r1)\n    for km in range(nkpts):\n        Hr1 += np.einsum('me,mie->i', imds.Fov[km], r2[km, kshift])\n        for kn in range(nkpts):\n            Hr1 += - 0.5 * np.einsum('nmie,mne->i', imds.Wooov[kn, km, kshift],\n                                     r2[km, kn])\n\n    Hr2 = np.zeros_like(r2)\n    for ki, kj in itertools.product(range(nkpts), repeat=2):\n        ka = kconserv[ki, kshift, kj]\n        Hr2[ki, kj] += lib.einsum('ae,ije->ija', imds.Fvv[ka], r2[ki, kj])\n\n        Hr2[ki, kj] -= lib.einsum('mi,mja->ija', imds.Foo[ki], r2[ki, kj])\n        Hr2[ki, kj] += lib.einsum('mj,mia->ija', imds.Foo[kj], r2[kj, ki])\n\n        Hr2[ki, kj] -= np.einsum('maji,m->ija', imds.Wovoo[kshift, ka, kj], r1)\n        for km in range(nkpts):\n            kn = kconserv[ki, km, kj]\n            Hr2[ki, kj] += 0.5 * lib.einsum('mnij,mna->ija',\n                                            imds.Woooo[km, kn, ki], r2[km, kn])\n\n    for ki, kj in itertools.product(range(nkpts), repeat=2):\n        ka = kconserv[ki, kshift, kj]\n        for km in range(nkpts):\n            ke = kconserv[km, kshift, kj]\n            Hr2[ki, kj] += lib.einsum('maei,mje->ija', imds.Wovvo[km, ka, ke],\n                                      r2[km, kj])\n\n            ke = kconserv[km, kshift, ki]\n            Hr2[ki, kj] -= lib.einsum('maej,mie->ija', imds.Wovvo[km, ka, ke],\n                                      r2[km, ki])\n\n    tmp = lib.einsum('xymnef,xymnf->e', imds.Woovv[:, :, kshift], r2[:, :])  # contract_{km, kn}\n    Hr2[:, :] += 0.5 * lib.einsum('e,yxjiea->xyija', tmp, imds.t2[:, :, kshift])  # sum_{ki, kj}\n\n    vector = amplitudes_to_vector_ip(Hr1, Hr2, kshift, kconserv)\n    return vector\n\ndef lipccsd_matvec(eom, vector, kshift, imds=None, diag=None):\n    '''2ph operators are of the form s_{ij}^{ b}, i.e. 'jb' indices are coupled.\n\n    See also `ipccsd_matvec`'''\n    if imds is None: imds = eom.make_imds()\n    nocc = eom.nocc\n    nmo = eom.nmo\n    nvir = nmo - nocc\n    nkpts = eom.nkpts\n    kconserv = imds.kconserv\n    r1, r2 = vector_to_amplitudes_ip(vector, kshift, nkpts, nmo, nocc, kconserv)\n    dtype = np.result_type(r1, r2)\n\n    Hr1 = -lib.einsum('mi,i->m', imds.Foo[kshift], r1)\n    for ki, kj in itertools.product(range(nkpts), repeat=2):\n        ka = kconserv[ki, kshift, kj]\n        Hr1 += -0.5 * lib.einsum('maji,ija->m', imds.Wovoo[kshift,ka,kj], r2[ki,kj])\n\n    Hr2 = np.zeros_like(r2)\n    for km, kn in itertools.product(range(nkpts), repeat=2):\n        ke = kconserv[km, kshift, kn]\n        Hr2[km,kn] += -lib.einsum('nmie,i->mne', imds.Wooov[kn,km,kshift], r1)\n        Hr2[km,kshift] += (km==ke)*lib.einsum('me,n->mne', imds.Fov[km], r1)\n        Hr2[kshift,kn] -= (kn==ke)*lib.einsum('ne,m->mne', imds.Fov[kn], r1)\n\n    for km, kn in itertools.product(range(nkpts), repeat=2):\n        ke = kconserv[km, kshift, kn]\n        Hr2[km,kn] += lib.einsum('ae,mna->mne', imds.Fvv[ke], r2[km,kn])\n        tmp1 = lib.einsum('mi,ine->mne', imds.Foo[km], r2[km,kn])\n        tmp1T = lib.einsum('ni,ime->mne', imds.Foo[kn], r2[kn,km])\n        Hr2[km,kn] += (-tmp1 + tmp1T)\n\n        for ki in range(nkpts):\n            kj = kconserv[km,ki,kn]\n            Hr2[km,kn] += 0.5 * lib.einsum('mnij,ije->mne', imds.Woooo[km,kn,ki], r2[ki,kj])\n\n            ka = kconserv[ke,km,ki]\n            tmp2 = lib.einsum('maei,ina->mne', imds.Wovvo[km,ka,ke], r2[ki,kn])\n            ka = kconserv[ke,kn,ki]\n            tmp2T = lib.einsum('naei,ima->mne', imds.Wovvo[kn,ka,ke], r2[ki,km])\n            Hr2[km,kn] += (tmp2 - tmp2T)\n\n    tmp = np.zeros(nvir, dtype=dtype)\n    for ki, kj in itertools.product(range(nkpts), repeat=2):\n        ka = kconserv[ki,kshift,kj]\n        kf = kshift\n        tmp += lib.einsum('ija,ijaf->f',r2[ki,kj],imds.t2[ki,kj,ka])\n\n    for km, kn in itertools.product(range(nkpts), repeat=2):\n        ke = kconserv[km, kshift, kn]\n        Hr2[km,kn] += 0.5 * lib.einsum('mnfe,f->mne', imds.Woovv[km,kn,kf], tmp)\n\n    vector = amplitudes_to_vector_ip(Hr1, Hr2, kshift, kconserv)\n    return vector\n\ndef ipccsd_diag(eom, kshift, imds=None):\n    if imds is None: imds = eom.make_imds()\n    t1, t2 = imds.t1, imds.t2\n    nkpts, nocc, nvir = t1.shape\n    kconserv = imds.kconserv\n\n    Hr1 = -np.diag(imds.Foo[kshift])\n    Hr2 = np.zeros((nkpts,nkpts,nocc,nocc,nvir), dtype=t1.dtype)\n    if eom.partition == 'mp':\n        foo = eom.eris.fock[:,:nocc,:nocc]\n        fvv = eom.eris.fock[:,nocc:,nocc:]\n        for ki in range(nkpts):\n            for kj in range(nkpts):\n                ka = kconserv[ki,kshift,kj]\n                Hr2[ki,kj] -= foo[ki].diagonal()[:,None,None]\n                Hr2[ki,kj] -= foo[kj].diagonal()[None,:,None]\n                Hr2[ki,kj] += fvv[ka].diagonal()[None,None,:]\n    else:\n        for ki in range(nkpts):\n            for kj in range(nkpts):\n                ka = kconserv[ki,kshift,kj]\n                Hr2[ki,kj] -= imds.Foo[ki].diagonal()[:,None,None]\n                Hr2[ki,kj] -= imds.Foo[kj].diagonal()[None,:,None]\n                Hr2[ki,kj] += imds.Fvv[ka].diagonal()[None,None,:]\n\n                if ki == kconserv[ki,kj,kj]:\n                    Hr2[ki,kj] += np.einsum('ijij->ij', imds.Woooo[ki, kj, ki])[:,:,None]\n\n                Hr2[ki, kj] += lib.einsum('iaai->ia', imds.Wovvo[ki, ka, ka])[:,None,:]\n                Hr2[ki, kj] += lib.einsum('jaaj->ja', imds.Wovvo[kj, ka, ka])[None,:,:]\n\n                Hr2[ki, kj] += lib.einsum('ijea,jiea->ija',imds.Woovv[ki,kj,kshift], imds.t2[kj,ki,kshift])\n\n    vector = amplitudes_to_vector_ip(Hr1, Hr2, kshift, kconserv)\n    return vector\n\n\ndef ipccsd_star_contract(eom, ipccsd_evals, ipccsd_evecs, lipccsd_evecs, kshift, imds=None):\n    \"\"\"\n    Returns:\n        e_star (list of float):\n            The IP-CCSD* energy.\n\n    Notes:\n        The user should check to make sure the right and left eigenvalues\n        before running the perturbative correction.\n\n        The 2hp right amplitudes are assumed to be of the form s^{a }_{ij}, i.e.\n        the (ia) indices are coupled.\n\n    Reference:\n        Saeh, Stanton \"...energy surfaces of radicals\" JCP 111, 8275 (1999)\n    \"\"\"\n    assert (eom.partition == None)\n    cpu1 = cpu0 = (time.clock(), time.time())\n    log = logger.Logger(eom.stdout, eom.verbose)\n    if imds is None:\n        imds = eom.make_imds()\n    t1, t2 = imds.t1, imds.t2\n    eris = imds.eris\n    fock = eris.fock\n    nkpts, nocc, nvir = t1.shape\n    nmo = nocc + nvir\n    dtype = np.result_type(t1, t2)\n    kconserv = eom.kconserv\n\n    fov = fock[:, :nocc, nocc:]\n    foo = [fock[ikpt, :nocc, :nocc].diagonal() for ikpt in range(nkpts)]\n    fvv = [fock[ikpt, nocc:, nocc:].diagonal() for ikpt in range(nkpts)]\n    mo_energy_occ = np.array([eris.mo_energy[ki][:nocc] for ki in range(nkpts)])\n    mo_energy_vir = np.array([eris.mo_energy[ki][nocc:] for ki in range(nkpts)])\n\n    mo_e_o = mo_energy_occ\n    mo_e_v = mo_energy_vir\n\n    ipccsd_evecs = np.array(ipccsd_evecs)\n    lipccsd_evecs = np.array(lipccsd_evecs)\n    e_star = []\n    ipccsd_evecs, lipccsd_evecs = [np.atleast_2d(x) for x in [ipccsd_evecs, lipccsd_evecs]]\n    ipccsd_evals = np.atleast_1d(ipccsd_evals)\n    for ip_eval, ip_evec, ip_levec in zip(ipccsd_evals, ipccsd_evecs, lipccsd_evecs):\n        # Enforcing <L|R> = 1\n        l1, l2 = vector_to_amplitudes_ip(ip_levec, kshift, nkpts, nmo, nocc, kconserv)\n        r1, r2 = vector_to_amplitudes_ip(ip_evec, kshift, nkpts, nmo, nocc, kconserv)\n        ldotr = np.dot(l1, r1) + 0.5 * np.dot(l2.ravel(), r2.ravel())\n\n        logger.info(eom, 'Left-right amplitude overlap : %14.8e + 1j %14.8e',\n                    ldotr.real, ldotr.imag)\n        if abs(ldotr) < 1e-7:\n            logger.warn(eom, 'Small %s left-right amplitude overlap. Results '\n                             'may be inaccurate.', ldotr)\n\n        l1 /= ldotr\n        l2 /= ldotr\n\n        deltaE = 0.0 + 1j*0.0\n        for ka, kb in itertools.product(range(nkpts), repeat=2):\n            lijkab = np.zeros((nkpts,nkpts,nocc,nocc,nocc,nvir,nvir),dtype=dtype)\n            rijkab = np.zeros((nkpts,nkpts,nocc,nocc,nocc,nvir,nvir),dtype=dtype)\n            kklist = kpts_helper.get_kconserv3(eom._cc._scf.cell, eom._cc.kpts,\n                          [ka,kb,kshift,range(nkpts),range(nkpts)])\n\n            for ki, kj in itertools.product(range(nkpts), repeat=2):\n                kk = kklist[ki,kj]\n                #TODO: can reduce size of ijkab arrays since `kk` fixed from other k-points\n\n                # lijkab update\n                if kk == kshift and kb == kconserv[ki,ka,kj]:\n                    lijkab[ki,kj] += lib.einsum('ijab,k->ijkab', eris.oovv[ki,kj,ka], l1)\n\n                km = kconserv[kj,ka,ki]\n                tmp = lib.einsum('jima,mkb->ijkab', eris.ooov[kj,ki,km], l2[km,kk])\n                km = kconserv[kj,kb,ki]\n                tmpT = lib.einsum('jimb,mka->ijkab', eris.ooov[kj,ki,km], l2[km,kk])\n                lijkab[ki,kj] += (-tmp + tmpT)\n\n                ke = kconserv[ka,ki,kb]\n                lijkab[ki,kj] += lib.einsum('ieab,jke->ijkab', eris.ovvv[ki,ke,ka], l2[kj,kk])\n\n                # rijkab update\n                tmp = lib.einsum('mbke,m->bke', eris.ovov[kshift,kb,kk], r1)\n                tmp = lib.einsum('bke,ijae->ijkab', tmp, t2[ki,kj,ka])\n                tmpT = lib.einsum('make,m->ake', eris.ovov[kshift,ka,kk], r1)\n                tmpT = lib.einsum('ake,ijbe->ijkab', tmpT, t2[ki,kj,kb])\n                rijkab[ki,kj] -= (tmp - tmpT)\n\n                km = kconserv[kj,kshift,kk]\n                tmp = lib.einsum('mnjk,n->mjk', eris.oooo[km,kshift,kj], r1)\n                tmp = lib.einsum('mjk,imab->ijkab', tmp, t2[ki,km,ka])\n                rijkab[ki,kj] += tmp\n\n                km = kconserv[kj,ka,ki]\n                tmp = lib.einsum('jima,mkb->ijkab', eris.ooov[kj,ki,km].conj(), r2[km,kk])\n                km = kconserv[kj,kb,ki]\n                tmpT = lib.einsum('jimb,mka->ijkab', eris.ooov[kj,ki,km].conj(), r2[km,kk])\n                rijkab[ki,kj] -= (tmp - tmpT)\n\n                ke = kconserv[ka,ki,kb]\n                rijkab[ki,kj] += lib.einsum('ieab,jke->ijkab', eris.ovvv[ki,ke,ka].conj(), r2[kj,kk])\n\n            eijk = np.zeros((nkpts,nkpts,nocc,nocc,nocc), dtype=dtype)\n            Plijkab = np.zeros_like(lijkab)\n            Prijkab = np.zeros_like(rijkab)\n            for ki, kj in itertools.product(range(nkpts), repeat=2):\n                kk = kklist[ki,kj]\n                # P(ijk)\n                Plijkab[ki,kj] = (lijkab[ki,kj] + lijkab[kj,kk].transpose(2,0,1,3,4) +\n                                                  lijkab[kk,ki].transpose(1,2,0,3,4))\n\n                Prijkab[ki,kj] = (rijkab[ki,kj] + rijkab[kj,kk].transpose(2,0,1,3,4) +\n                                                  rijkab[kk,ki].transpose(1,2,0,3,4))\n\n\n                eijk[ki,kj] = _get_epqr([0,nocc,ki,mo_e_o,eom.nonzero_opadding],\n                                        [0,nocc,kj,mo_e_o,eom.nonzero_opadding],\n                                        [0,nocc,kk,mo_e_o,eom.nonzero_opadding])\n\n            # Creating denominator\n            eab = _get_epq([0,nvir,ka,mo_e_v,eom.nonzero_vpadding],\n                           [0,nvir,kb,mo_e_v,eom.nonzero_vpadding],\n                           fac=[-1.,-1.])\n            eijkab = (eijk[:, :, :, :, :, None, None] +\n                      eab[None, None, None, None, None, :, :])\n            denom = eijkab + ip_eval\n            denom = 1. / denom\n\n            deltaE += lib.einsum('xyijkab,xyijkab,xyijkab', Plijkab, Prijkab, denom)\n\n        deltaE *= 1./12\n        deltaE = deltaE.real\n        logger.info(eom, \"Exc. energy, delta energy = %16.12f, %16.12f\",\n        ip_eval + deltaE, deltaE)\n        e_star.append(ip_eval + deltaE)\n    return e_star\n\n\ndef ipccsd(eom, nroots=1, koopmans=False, guess=None, left=False,\n           eris=None, imds=None, partition=None, kptlist=None,\n           dtype=None, **kwargs):\n    '''See `kernel()` for a description of arguments.'''\n    if partition:\n        eom.partition = partition.lower()\n        assert eom.partition in ['mp','full']\n        if eom.partition in ['mp', 'full']:\n            raise NotImplementedError\n    eom.converged, eom.e, eom.v \\\n            = kernel(eom, nroots, koopmans, guess, left, eris=eris, imds=imds,\n                     partition=partition, kptlist=kptlist, dtype=dtype)\n    return eom.e, eom.v\n\n\ndef perturbed_ccsd_kernel(eom, nroots=1, koopmans=False, right_guess=None,\n                          left_guess=None, eris=None, imds=None, partition=None,\n                          kptlist=None, dtype=None):\n    '''Wrapper for running perturbative excited-states that require both left\n    and right amplitudes.'''\n    from pyscf.cc.eom_rccsd import _sort_left_right_eigensystem\n    if imds is None:\n        imds = eom.make_imds(eris=eris)\n\n    e_star = []\n    for k, kshift in enumerate(kptlist):\n        # Right eigenvectors\n        r_converged, r_e, r_v = \\\n                   kernel(eom, nroots, koopmans=koopmans, guess=right_guess, left=False,\n                          eris=eris, imds=imds, partition=partition, kptlist=[kshift,], dtype=dtype)\n        # Left eigenvectors\n        l_converged, l_e, l_v = \\\n                   kernel(eom, nroots, koopmans=koopmans, guess=right_guess, left=True,\n                          eris=eris, imds=imds, partition=partition, kptlist=[kshift,], dtype=dtype)\n\n        ek, r_vk, l_vk = _sort_left_right_eigensystem(eom, r_converged[0], r_e[0], r_v[0],\n                                                      l_converged[0], l_e[0], l_v[0])\n        e_star.append(eom.ccsd_star_contract(ek, r_vk, l_vk, kshift, imds=imds))\n    return e_star\n\n\ndef ipccsd_star(eom, nroots=1, koopmans=False, right_guess=None, left_guess=None,\n           eris=None, imds=None, partition=None, kptlist=None,\n           dtype=None, **kwargs):\n    '''See `kernel()` for a description of arguments.'''\n    if partition:\n        raise NotImplementedError\n    return perturbed_ccsd_kernel(eom, nroots=nroots, koopmans=koopmans,\n                                 right_guess=right_guess, left_guess=left_guess, eris=eris,\n                                 imds=imds, partition=partition, kptlist=kptlist, dtype=dtype)\n\n\ndef mask_frozen_ip(eom, vector, kshift, const=LARGE_DENOM):\n    '''Replaces all frozen orbital indices of `vector` with the value `const`.'''\n    r1, r2 = eom.vector_to_amplitudes(vector, kshift=kshift)\n    nkpts = eom.nkpts\n    nocc, nmo = eom.nocc, eom.nmo\n    nvir = nmo - nocc\n    kconserv = eom.kconserv\n\n    # Get location of padded elements in occupied and virtual space\n    nonzero_opadding, nonzero_vpadding = eom.nonzero_opadding, eom.nonzero_vpadding\n\n    new_r1 = const * np.ones_like(r1)\n    new_r2 = const * np.ones_like(r2)\n\n    new_r1[nonzero_opadding[kshift]] = r1[nonzero_opadding[kshift]]\n    for ki in range(nkpts):\n        for kj in range(nkpts):\n            kb = kconserv[ki, kshift, kj]\n            idx = np.ix_([ki], [kj], nonzero_opadding[ki], nonzero_opadding[kj], nonzero_vpadding[kb])\n            new_r2[idx] = r2[idx]\n\n    return eom.amplitudes_to_vector(new_r1, new_r2, kshift, kconserv)\n\nclass EOMIP(eom_rccsd.EOMIP):\n    def __init__(self, cc):\n        self.kpts = cc.kpts\n        self.nonzero_opadding, self.nonzero_vpadding = self.get_padding_k_idx(cc)\n        self.kconserv = cc.khelper.kconserv\n        eom_rccsd.EOM.__init__(self, cc)\n\n    kernel = ipccsd\n    ipccsd = ipccsd\n    ipccsd_star = ipccsd_star\n    ccsd_star_contract = ipccsd_star_contract\n\n    get_diag = ipccsd_diag\n    matvec = ipccsd_matvec\n    l_matvec = lipccsd_matvec\n    mask_frozen = mask_frozen_ip\n    get_padding_k_idx = get_padding_k_idx\n\n    def ipccsd_star_contract(self, ipccsd_evals, ipccsd_evecs, lipccsd_evecs, kshift, imds=None):\n        return self.ccsd_star_contract(ipccsd_evals, ipccsd_evecs, lipccsd_evecs, kshift, imds=imds)\n\n    def get_init_guess(self, kshift, nroots=1, koopmans=False, diag=None):\n        size = self.vector_size()\n        dtype = getattr(diag, 'dtype', np.complex)\n        nroots = min(nroots, size)\n        guess = []\n        if koopmans:\n            for n in self.nonzero_opadding[kshift][::-1][:nroots]:\n                g = np.zeros(int(size), dtype=dtype)\n                g[n] = 1.0\n                g = self.mask_frozen(g, kshift, const=0.0)\n                guess.append(g)\n        else:\n            idx = diag.argsort()[:nroots]\n            for i in idx:\n                g = np.zeros(int(size), dtype=dtype)\n                g[i] = 1.0\n                g = self.mask_frozen(g, kshift, const=0.0)\n                guess.append(g)\n        return guess\n\n    @property\n    def nkpts(self):\n        return len(self.kpts)\n\n    def gen_matvec(self, kshift, imds=None, left=False, **kwargs):\n        if imds is None: imds = self.make_imds()\n        diag = self.get_diag(kshift, imds)\n        if left:\n            matvec = lambda xs: [self.l_matvec(x, kshift, imds, diag) for x in xs]\n        else:\n            matvec = lambda xs: [self.matvec(x, kshift, imds, diag) for x in xs]\n        return matvec, diag\n\n    def vector_to_amplitudes(self, vector, kshift=None, nkpts=None, nmo=None, nocc=None, kconserv=None):\n        if nmo is None: nmo = self.nmo\n        if nocc is None: nocc = self.nocc\n        if nkpts is None: nkpts = self.nkpts\n        if kconserv is None: kconserv = self.kconserv\n        return vector_to_amplitudes_ip(vector, kshift, nkpts, nmo, nocc, kconserv)\n\n    def amplitudes_to_vector(self, r1, r2, kshift, kconserv=None):\n        if kconserv is None: kconserv = self.kconserv\n        return amplitudes_to_vector_ip(r1, r2, kshift, kconserv)\n\n    def vector_size(self):\n        nocc = self.nocc\n        nvir = self.nmo - nocc\n        nkpts = self.nkpts\n        return nocc + nkpts*nocc*(nkpts*nocc-1)*nvir//2\n\n    def make_imds(self, eris=None):\n        imds = _IMDS(self._cc, eris=eris)\n        imds.make_ip()\n        return imds\n\nclass EOMIP_Ta(EOMIP):\n    '''Class for EOM IPCCSD(T)*(a) method by Matthews and Stanton.'''\n    def make_imds(self, eris=None):\n        imds = _IMDS(self._cc, eris=eris)\n        imds.make_t3p2_ip(self._cc)\n        return imds\n\n########################################\n# EOM-EA-CCSD\n########################################\n\ndef enforce_2p_spin_ea_doublet(r2, kconserv, kshift, orbspin):\n    return enforce_2p_spin_doublet(r2, kconserv, kshift, orbspin, 'ea')\n\ndef spin2spatial_ea_doublet(r1, r2, kconserv, kshift, orbspin):\n    '''Convert R1/R2 of spin orbital representation to R1/R2 of\n    spatial orbital representation'''\n    nkpts, nocc, nvir = np.array(r2.shape)[[1, 2, 3]]\n\n    idxoa = [np.where(orbspin[k][:nocc] == 0)[0] for k in range(nkpts)]\n    idxob = [np.where(orbspin[k][:nocc] == 1)[0] for k in range(nkpts)]\n    idxva = [np.where(orbspin[k][nocc:] == 0)[0] for k in range(nkpts)]\n    idxvb = [np.where(orbspin[k][nocc:] == 1)[0] for k in range(nkpts)]\n    nocc_a = len(idxoa[0])\n    nocc_b = len(idxob[0])\n    nvir_a = len(idxva[0])\n    nvir_b = len(idxvb[0])\n\n    r1a = r1[idxva[kshift]]\n    r1b = r1[idxvb[kshift]]\n\n    r2aaa = np.zeros((nkpts,nkpts,nocc_a,nvir_a,nvir_a), dtype=r2.dtype)\n    r2aba = np.zeros((nkpts,nkpts,nocc_a,nvir_b,nvir_a), dtype=r2.dtype)\n    r2bab = np.zeros((nkpts,nkpts,nocc_b,nvir_a,nvir_b), dtype=r2.dtype)\n    r2bbb = np.zeros((nkpts,nkpts,nocc_b,nvir_b,nvir_b), dtype=r2.dtype)\n    for kj, ka in itertools.product(range(nkpts), repeat=2):\n        kb = kconserv[kshift, ka, kj]\n        idxvaa = idxva[ka][:,None] * nvir + idxva[kb]\n        idxvab = idxva[ka][:,None] * nvir + idxvb[kb]\n        idxvba = idxvb[ka][:,None] * nvir + idxva[kb]\n        idxvbb = idxvb[ka][:,None] * nvir + idxvb[kb]\n\n        r2_tmp = r2[kj, ka].reshape(nocc, nvir**2)\n        r2aaa_tmp = lib.take_2d(r2_tmp, idxoa[kj], idxvaa.ravel())\n        r2aba_tmp = lib.take_2d(r2_tmp, idxoa[kj], idxvba.ravel())\n        r2bab_tmp = lib.take_2d(r2_tmp, idxob[kj], idxvab.ravel())\n        r2bbb_tmp = lib.take_2d(r2_tmp, idxob[kj], idxvbb.ravel())\n\n        r2aaa[kj, ka] = r2aaa_tmp.reshape(nocc_a, nvir_a, nvir_a)\n        r2aba[kj, ka] = r2aba_tmp.reshape(nocc_a, nvir_b, nvir_a)\n        r2bab[kj, ka] = r2bab_tmp.reshape(nocc_b, nvir_a, nvir_b)\n        r2bbb[kj, ka] = r2bbb_tmp.reshape(nocc_b, nvir_b, nvir_b)\n    return [r1a, r1b], [r2aaa, r2aba, r2bab, r2bbb]\n\ndef spatial2spin_ea_doublet(r1, r2, kconserv, kshift, orbspin=None):\n    '''Convert R1/R2 of spatial orbital representation to R1/R2 of\n    spin orbital representation'''\n    r1a, r1b = r1\n    r2aaa, r2aba, r2bab, r2bbb = r2\n\n    nkpts, nocc_a, nvir_a = np.array(r2aaa.shape)[[0, 2, 3]]\n    nkpts, nocc_b, nvir_b = np.array(r2bbb.shape)[[0, 2, 3]]\n\n    if orbspin is None:\n        orbspin = np.zeros((nocc_a+nvir_a)*2, dtype=int)\n        orbspin[1::2] = 1\n\n    nocc = nocc_a + nocc_b\n    nvir = nvir_a + nvir_b\n\n    idxoa = [np.where(orbspin[k][:nocc] == 0)[0] for k in range(nkpts)]\n    idxob = [np.where(orbspin[k][:nocc] == 1)[0] for k in range(nkpts)]\n    idxva = [np.where(orbspin[k][nocc:] == 0)[0] for k in range(nkpts)]\n    idxvb = [np.where(orbspin[k][nocc:] == 1)[0] for k in range(nkpts)]\n\n    r1 = np.zeros((nvir), dtype=r1a.dtype)\n    r1[idxva[kshift]] = r1a\n    r1[idxvb[kshift]] = r1b\n\n    r2 = np.zeros((nkpts,nkpts,nocc,nvir**2), dtype=r2aaa.dtype)\n    for kj, ka in itertools.product(range(nkpts), repeat=2):\n        kb = kconserv[kshift, ka, kj]\n        idxvaa = idxva[ka][:,None] * nvir + idxva[kb]\n        idxvab = idxva[ka][:,None] * nvir + idxvb[kb]\n        idxvba = idxvb[ka][:,None] * nvir + idxva[kb]\n        idxvbb = idxvb[ka][:,None] * nvir + idxvb[kb]\n\n        r2aaa_tmp = r2aaa[kj,ka].reshape(nocc_a, nvir_a*nvir_a)\n        r2aba_tmp = r2aba[kj,ka].reshape(nocc_a, nvir_b*nvir_a)\n        r2bab_tmp = r2bab[kj,ka].reshape(nocc_b, nvir_a*nvir_b)\n        r2bbb_tmp = r2bbb[kj,ka].reshape(nocc_b, nvir_b*nvir_b)\n\n        lib.takebak_2d(r2[kj,ka], r2aaa_tmp, idxoa[kj], idxvaa.ravel())\n        lib.takebak_2d(r2[kj,ka], r2aba_tmp, idxoa[kj], idxvba.ravel())\n        lib.takebak_2d(r2[kj,ka], r2bab_tmp, idxob[kj], idxvab.ravel())\n        lib.takebak_2d(r2[kj,ka], r2bbb_tmp, idxob[kj], idxvbb.ravel())\n\n        r2aab_tmp = -r2aba[kj,kb].reshape(nocc_a, nvir_b*nvir_a)\n        r2bba_tmp = -r2bab[kj,kb].reshape(nocc_b, nvir_a*nvir_b)\n        lib.takebak_2d(r2[kj,ka], r2bba_tmp, idxob[kj], idxvba.T.ravel())\n        lib.takebak_2d(r2[kj,ka], r2aab_tmp, idxoa[kj], idxvab.T.ravel())\n\n    r2 = r2.reshape(nkpts, nkpts, nocc, nvir, nvir)\n    return r1, r2\n\ndef amplitudes_to_vector_ea(r1, r2, kshift, kconserv):\n    nkpts, nocc, nvir = np.asarray(r2.shape)[[0,2,3]]\n    r2_tril = np.zeros((nocc*nkpts*nvir*(nkpts*nvir-1)//2), dtype=r2.dtype)\n    index = 0\n    for kj, ka in itertools.product(range(nkpts), repeat=2):\n        kb = kconserv[kshift,ka,kj]\n        if ka < kb:\n            idx, idy = np.tril_indices(nvir, 0)\n        else:\n            idx, idy = np.tril_indices(nvir, -1)\n        r2_tril[index:index + nocc*len(idy)] = r2[kj,ka,:,idx,idy].reshape(-1)\n        index = index + nocc*len(idy)\n    vector = np.hstack((r1, r2_tril))\n    return vector\n\ndef vector_to_amplitudes_ea(vector, kshift, nkpts, nmo, nocc, kconserv):\n    nvir = nmo - nocc\n\n    r1 = vector[:nvir].copy()\n    r2_tril = vector[nvir:].copy().reshape(nocc*nkpts*nvir*(nkpts*nvir-1)//2)\n    r2 = np.zeros((nkpts,nkpts,nocc,nvir,nvir), dtype=vector.dtype)\n\n    index = 0\n    for kj, ka in itertools.product(range(nkpts), repeat=2):\n        kb = kconserv[kshift,ka,kj]\n        if ka < kb:\n            idx, idy = np.tril_indices(nvir, 0)\n        else:\n            idx, idy = np.tril_indices(nvir, -1)\n        tmp = r2_tril[index:index + nocc*len(idy)].reshape(-1,nocc)\n        r2[kj,ka,:,idx,idy] = tmp\n        r2[kj,kb,:,idy,idx] = -tmp\n        index = index + nocc*len(idy)\n\n    return [r1,r2]\n\ndef eaccsd(eom, nroots=1, koopmans=False, guess=None, left=False,\n           eris=None, imds=None, partition=None, kptlist=None,\n           dtype=None):\n    '''See `ipccsd()` for a description of arguments.'''\n    return ipccsd(eom, nroots, koopmans, guess, left, eris, imds,\n                  partition, kptlist, dtype)\n\ndef eaccsd_matvec(eom, vector, kshift, imds=None, diag=None):\n    '''2hp operators are of the form s_{ j}^{ab}, i.e. 'jb' indices are coupled.'''\n    if imds is None: imds = eom.make_imds()\n    nocc = eom.nocc\n    nmo = eom.nmo\n    nvir = nmo - nocc\n    nkpts = eom.nkpts\n    kconserv = imds.kconserv\n    r1, r2 = vector_to_amplitudes_ea(vector, kshift, nkpts, nmo, nocc, kconserv)\n\n    Hr1 = np.einsum('ac,c->a', imds.Fvv[kshift], r1)\n    for kl in range(nkpts):\n        Hr1 += np.einsum('ld,lad->a', imds.Fov[kl], r2[kl, kshift])\n        for kc in range(nkpts):\n            Hr1 += 0.5*np.einsum('alcd,lcd->a', imds.Wvovv[kshift,kl,kc], r2[kl,kc])\n\n    Hr2 = np.zeros_like(r2)\n    for kj, ka in itertools.product(range(nkpts), repeat=2):\n        kb = kconserv[kshift,ka,kj]\n        Hr2[kj,ka] += np.einsum('abcj,c->jab', imds.Wvvvo[ka,kb,kshift], r1)\n        Hr2[kj,ka] += lib.einsum('ac,jcb->jab', imds.Fvv[ka], r2[kj,ka])\n        Hr2[kj,ka] -= lib.einsum('bc,jca->jab', imds.Fvv[kb], r2[kj,kb])\n        Hr2[kj,ka] -= lib.einsum('lj,lab->jab', imds.Foo[kj], r2[kj,ka])\n\n        for kd in range(nkpts):\n            kl = kconserv[kj, kb, kd]\n            Hr2[kj, ka] += lib.einsum('lbdj,lad->jab', imds.Wovvo[kl, kb, kd], r2[kl, ka])\n\n            # P(ab)\n            kl = kconserv[kj, ka, kd]\n            Hr2[kj, ka] -= lib.einsum('ladj,lbd->jab', imds.Wovvo[kl, ka, kd], r2[kl, kb])\n\n            kc = kconserv[ka, kd, kb]\n            Hr2[kj, ka] += 0.5 * lib.einsum('abcd,jcd->jab', imds.Wvvvv[ka, kb, kc], r2[kj, kc])\n\n    tmp = lib.einsum('xyklcd,xylcd->k', imds.Woovv[kshift, :, :], r2[:, :])  # contract_{kl, kc}\n    Hr2[:, :] -= 0.5*lib.einsum('k,xykjab->xyjab', tmp, imds.t2[kshift, :, :])  # sum_{kj, ka]\n\n    vector = eom.amplitudes_to_vector(Hr1, Hr2, kshift)\n    return vector\n\ndef leaccsd_matvec(eom, vector, kshift, imds=None, diag=None):\n    '''2hp operators are of the form s_{ j}^{ab}, i.e. 'jb' indices are coupled.\n\n    See also `eaccsd_matvec`'''\n    if imds is None: imds = eom.make_imds()\n    nocc = eom.nocc\n    nmo = eom.nmo\n    nvir = nmo - nocc\n    nkpts = eom.nkpts\n    kconserv = imds.kconserv\n    r1, r2 = vector_to_amplitudes_ea(vector, kshift, nkpts, nmo, nocc, kconserv)\n    dtype = np.result_type(r1, r2)\n\n    Hr1 = np.einsum('ca,c->a', imds.Fvv[kshift], r1)\n    for kj, kb in itertools.product(range(nkpts), repeat=2):\n        kc = kconserv[kshift,kb,kj]\n        Hr1 += 0.5*lib.einsum('cbaj,jcb->a',imds.Wvvvo[kc,kb,kshift],r2[kj,kc])\n\n    Hr2 = np.zeros_like(r2)\n    for kj, ka in itertools.product(range(nkpts), repeat=2):\n        kb = kconserv[kshift,ka,kj]\n        Hr2[kj,ka] += lib.einsum('cjab,c->jab',imds.Wvovv[kshift,kj,ka],r1)\n        Hr2[kj,kshift] += (kj==kb)*lib.einsum('jb,a->jab',imds.Fov[kj],r1)\n        Hr2[kj,ka] -= (kj==ka)*lib.einsum('ja,b->jab',imds.Fov[kj],r1)\n\n    for kj, ka in itertools.product(range(nkpts), repeat=2):\n        kb = kconserv[kshift,ka,kj]\n        tmp1 = lib.einsum('ca,jcb->jab',imds.Fvv[ka],r2[kj,ka])\n        tmp1T = lib.einsum('cb,jca->jab',imds.Fvv[kb],r2[kj,kb])\n        Hr2[kj,ka] += (tmp1 - tmp1T)\n        Hr2[kj,ka] += -lib.einsum('jl,lab->jab',imds.Foo[kj],r2[kj,ka])\n\n        for kd in range(nkpts):\n            km = kconserv[kj,kb,kd]\n            tmp2 = lib.einsum('jdbm,mad->jab',imds.Wovvo[kj,kd,kb],r2[km,ka])\n            km = kconserv[kj,ka,kd]\n            tmp2T = lib.einsum('jdam,mbd->jab',imds.Wovvo[kj,kd,ka],r2[km,kb])\n            Hr2[kj,ka] += (tmp2 - tmp2T)\n\n            kc = kconserv[ka,kd,kb]\n            Hr2[kj,ka] += 0.5*lib.einsum('cdab,jcd->jab',imds.Wvvvv[kc,kd,ka],r2[kj,kc])\n\n    tmp = np.zeros(nocc, dtype=dtype)\n    for kj, ka in itertools.product(range(nkpts), repeat=2):\n        kb = kconserv[kshift,ka,kj]\n        tmp += lib.einsum('jab,kjab->k',r2[kj,ka],imds.t2[kshift,kj,ka])\n\n    for kj, ka in itertools.product(range(nkpts), repeat=2):\n        kb = kconserv[kshift,ka,kj]\n        Hr2[kj,ka] += -0.5*lib.einsum('kjab,k->jab',imds.Woovv[kshift,kj,ka],tmp)\n\n    vector = eom.amplitudes_to_vector(Hr1, Hr2, kshift)\n    return vector\n\n\ndef eaccsd_diag(eom, kshift, imds=None):\n    if imds is None: imds = eom.make_imds()\n    t1, t2 = imds.t1, imds.t2\n    nkpts, nocc, nvir = t1.shape\n    kconserv = imds.kconserv\n\n    Hr1 = np.diag(imds.Fvv[kshift])\n    Hr2 = np.zeros((nkpts,nkpts,nocc,nvir,nvir), dtype=t1.dtype)\n    if eom.partition == 'mp': # This case is untested\n        foo = eom.eris.fock[:,:nocc,:nocc]\n        fvv = eom.eris.fock[:,nocc:,nocc:]\n        for kj in range(nkpts):\n            for ka in range(nkpts):\n                kb = kconserv[kshift,ka,kj]\n                Hr2[kj,ka] -= foo[kj].diagonal()[:,None,None]\n                Hr2[kj,ka] -= fvv[ka].diagonal()[None,:,None]\n                Hr2[kj,ka] += fvv[kb].diagonal()[None,None,:]\n    else:\n        for kj in range(nkpts):\n            for ka in range(nkpts):\n                kb = kconserv[kshift,ka,kj]\n                Hr2[kj,ka] -= imds.Foo[kj].diagonal()[:,None,None]\n                Hr2[kj,ka] += imds.Fvv[ka].diagonal()[None,:,None]\n                Hr2[kj,ka] += imds.Fvv[kb].diagonal()[None,None,:]\n\n                Hr2[kj,ka] += np.einsum('jbbj->jb', imds.Wovvo[kj,kb,kb])[:, None, :]\n                Hr2[kj,ka] += np.einsum('jaaj->ja', imds.Wovvo[kj,ka,ka])[:, :, None]\n\n                if ka == kconserv[ka,kb,kb]:\n                    Hr2[kj,ka] += np.einsum('abab->ab', imds.Wvvvv[ka,kb,ka])[None,:,:]\n\n                Hr2[kj,ka] -= np.einsum('kjab,kjab->jab',imds.Woovv[kshift,kj,ka],imds.t2[kshift,kj,ka])\n\n    vector = amplitudes_to_vector_ea(Hr1, Hr2, kshift, kconserv)\n    return vector\n\ndef eaccsd_star_contract(eom, eaccsd_evals, eaccsd_evecs, leaccsd_evecs, kshift, imds=None):\n    \"\"\"\n    Returns:\n        e_star (list of float):\n            The EA-CCSD* energy.\n\n    Notes:\n        The user should check to make sure the right and left eigenvalues\n        before running the perturbative correction.\n\n    Reference:\n        Saeh, Stanton \"...energy surfaces of radicals\" JCP 111, 8275 (1999)\n    \"\"\"\n    assert (eom.partition == None)\n    cpu1 = cpu0 = (time.clock(), time.time())\n    log = logger.Logger(eom.stdout, eom.verbose)\n    if imds is None:\n        imds = eom.make_imds()\n    t1, t2 = imds.t1, imds.t2\n    eris = imds.eris\n    fock = eris.fock\n    nkpts, nocc, nvir = t1.shape\n    nmo = nocc + nvir\n    dtype = np.result_type(t1, t2)\n    kconserv = eom.kconserv\n\n    fov = fock[:, :nocc, nocc:]\n    foo = [fock[ikpt, :nocc, :nocc].diagonal() for ikpt in range(nkpts)]\n    fvv = [fock[ikpt, nocc:, nocc:].diagonal() for ikpt in range(nkpts)]\n    mo_energy_occ = np.array([eris.mo_energy[ki][:nocc] for ki in range(nkpts)])\n    mo_energy_vir = np.array([eris.mo_energy[ki][nocc:] for ki in range(nkpts)])\n\n    mo_e_o = mo_energy_occ\n    mo_e_v = mo_energy_vir\n\n    eaccsd_evecs = np.array(eaccsd_evecs)\n    leaccsd_evecs = np.array(leaccsd_evecs)\n    e_star = []\n    eaccsd_evecs, leaccsd_evecs = [np.atleast_2d(x) for x in [eaccsd_evecs, leaccsd_evecs]]\n    eaccsd_evals = np.atleast_1d(eaccsd_evals)\n    for ea_eval, ea_evec, ea_levec in zip(eaccsd_evals, eaccsd_evecs, leaccsd_evecs):\n        # Enforcing <L|R> = 1\n        l1, l2 = vector_to_amplitudes_ea(ea_levec, kshift, nkpts, nmo, nocc, kconserv)\n        r1, r2 = vector_to_amplitudes_ea(ea_evec, kshift, nkpts, nmo, nocc, kconserv)\n        ldotr = np.dot(l1, r1) + 0.5 * np.dot(l2.ravel(), r2.ravel())\n\n        logger.info(eom, 'Left-right amplitude overlap : %14.8e + 1j %14.8e',\n                    ldotr.real, ldotr.imag)\n        if abs(ldotr) < 1e-7:\n            logger.warn(eom, 'Small %s left-right amplitude overlap. Results '\n                             'may be inaccurate.', ldotr)\n\n        l1 /= ldotr\n        l2 /= ldotr\n\n        deltaE = 0.0 + 1j*0.0\n        for ki, kj in itertools.product(range(nkpts), repeat=2):\n            lijabc = np.zeros((nkpts,nkpts,nocc,nocc,nvir,nvir,nvir),dtype=dtype)\n            rijabc = np.zeros((nkpts,nkpts,nocc,nocc,nvir,nvir,nvir),dtype=dtype)\n            kklist = kpts_helper.get_kconserv3(eom._cc._scf.cell, eom._cc.kpts,\n                          [ki,kj,kshift,range(nkpts),range(nkpts)])\n\n            for ka, kb in itertools.product(range(nkpts), repeat=2):\n                #TODO: can reduce size of ijabc arrays since `kc` fixed from other k-points\n                kc = kklist[ka,kb]\n\n                # lijabc update\n                if kc == kshift and kb == kconserv[ki,ka,kj]:\n                    lijabc[ka,kb] -= lib.einsum('ijab,c->ijabc', eris.oovv[ki,kj,ka], l1)\n\n                km = kconserv[kj,ka,ki]\n                lijabc[ka,kb] -= lib.einsum('jima,mbc->ijabc', eris.ooov[kj,ki,km], l2[km,kb])\n\n                ke = kconserv[ka,ki,kb]\n                tmp = lib.einsum('ieab,jce->ijabc', eris.ovvv[ki,ke,ka], l2[kj,kc])\n                ke = kconserv[ka,kj,kb]\n                tmpT = lib.einsum('jeab,ice->ijabc', eris.ovvv[kj,ke,ka], l2[ki,kc])\n                lijabc[ka,kb] -= (tmp - tmpT)\n\n                # rijabc update\n                ke = kconserv[kb,kshift,kc]\n                tmp = lib.einsum('bcef,f->bce', eris.vvvv[kb,kc,ke], r1)\n                tmp = lib.einsum('bce,ijae->ijabc', tmp, t2[ki,kj,ka])\n                rijabc[ka,kb] -= tmp\n\n                km = kconserv[kj,kc,kshift]\n                tmp = lib.einsum('mcje,e->mcj', eris.ovov[km,kc,kj], r1)\n                tmp = lib.einsum('mcj,imab->ijabc', tmp, t2[ki,km,ka])\n                km = kconserv[ki,kc,kshift]\n                tmpT = lib.einsum('mcie,e->mci', eris.ovov[km,kc,ki], r1)\n                tmpT = lib.einsum('mci,jmab->ijabc', tmpT, t2[kj,km,ka])\n                rijabc[ka,kb] += (tmp - tmpT)\n\n                km = kconserv[kj,ka,ki]\n                rijabc[ka,kb] += lib.einsum('jima,mcb->ijabc', eris.ooov[kj,ki,km].conj(), r2[km,kc])\n\n                ke = kconserv[ka,ki,kb]\n                tmp = lib.einsum('ieab,jce->ijabc', eris.ovvv[ki,ke,ka].conj(), r2[kj,kc])\n                ke = kconserv[ka,kj,kb]\n                tmpT = lib.einsum('jeab,ice->ijabc', eris.ovvv[kj,ke,ka].conj(), r2[ki,kc])\n                rijabc[ka,kb] -= (tmp - tmpT)\n\n            eabc = np.zeros((nkpts,nkpts,nvir,nvir,nvir), dtype=dtype)\n            Plijabc = np.zeros_like(lijabc)\n            Prijabc = np.zeros_like(rijabc)\n            for ka, kb in itertools.product(range(nkpts), repeat=2):\n                kc = kklist[ka,kb]\n                # P(abc)\n                Plijabc[ka,kb] = (lijabc[ka,kb] + lijabc[kb,kc].transpose(0,1,4,2,3) +\n                                                  lijabc[kc,ka].transpose(0,1,3,4,2))\n\n                Prijabc[ka,kb] = (rijabc[ka,kb] + rijabc[kb,kc].transpose(0,1,4,2,3) +\n                                                  rijabc[kc,ka].transpose(0,1,3,4,2))\n\n\n                eabc[ka,kb] = _get_epqr([0,nvir,ka,mo_e_v,eom.nonzero_vpadding],\n                                        [0,nvir,kb,mo_e_v,eom.nonzero_vpadding],\n                                        [0,nvir,kc,mo_e_v,eom.nonzero_vpadding],\n                                        fac=[-1.,]*3)\n\n            # Creating denominator\n            eij = _get_epq([0,nocc,ki,mo_e_o,eom.nonzero_opadding],\n                           [0,nocc,kj,mo_e_o,eom.nonzero_opadding])\n            eijabc = (eij[None, None, :, :, None, None, None] +\n                      eabc[:, :, None, None, :, :, :])\n            denom = eijabc + ea_eval\n            denom = 1. / denom\n\n            deltaE += lib.einsum('xyijabc,xyijabc,xyijabc', Plijabc, Prijabc, denom)\n\n        deltaE *= 1./12\n        deltaE = deltaE.real\n        logger.info(eom, \"Exc. energy, delta energy = %16.12f, %16.12f\",\n        ea_eval + deltaE, deltaE)\n        e_star.append(ea_eval + deltaE)\n    return e_star\n\ndef eaccsd_star(eom, nroots=1, koopmans=False, right_guess=None, left_guess=None,\n           eris=None, imds=None, partition=None, kptlist=None,\n           dtype=None, **kwargs):\n    '''See `kernel()` for a description of arguments.'''\n    if partition:\n        raise NotImplementedError\n    return perturbed_ccsd_kernel(eom, nroots=nroots, koopmans=koopmans,\n                                 right_guess=right_guess, left_guess=left_guess, eris=eris,\n                                 imds=imds, partition=partition, kptlist=kptlist, dtype=dtype)\n\n\ndef mask_frozen_ea(eom, vector, kshift, const=LARGE_DENOM):\n    '''Replaces all frozen orbital indices of `vector` with the value `const`.'''\n    r1, r2 = eom.vector_to_amplitudes(vector, kshift=kshift)\n    kconserv = eom.kconserv\n    nkpts = eom.nkpts\n    nocc, nmo = eom.nocc, eom.nmo\n    nvir = nmo - nocc\n\n    # Get location of padded elements in occupied and virtual space\n    nonzero_opadding, nonzero_vpadding = eom.nonzero_opadding, eom.nonzero_vpadding\n\n    new_r1 = const * np.ones_like(r1)\n    new_r2 = const * np.ones_like(r2)\n\n    new_r1[nonzero_vpadding[kshift]] = r1[nonzero_vpadding[kshift]]\n    for kj in range(nkpts):\n        for ka in range(nkpts):\n            kb = kconserv[kshift, ka, kj]\n            idx = np.ix_([kj], [ka], nonzero_opadding[kj], nonzero_vpadding[ka], nonzero_vpadding[kb])\n            new_r2[idx] = r2[idx]\n\n    return eom.amplitudes_to_vector(new_r1, new_r2, kshift, kconserv)\n\nclass EOMEA(eom_rccsd.EOMEA):\n    def __init__(self, cc):\n        self.kpts = cc.kpts\n        self.nonzero_opadding, self.nonzero_vpadding = self.get_padding_k_idx(cc)\n        self.kconserv = cc.khelper.kconserv\n        eom_rccsd.EOM.__init__(self, cc)\n\n    kernel = eaccsd\n    eaccsd = eaccsd\n    eaccsd_star = eaccsd_star\n    ccsd_star_contract = eaccsd_star_contract\n\n    get_diag = eaccsd_diag\n    matvec = eaccsd_matvec\n    l_matvec = leaccsd_matvec\n    mask_frozen = mask_frozen_ea\n    get_padding_k_idx = get_padding_k_idx\n\n    def eaccsd_star_contract(self, eaccsd_evals, eaccsd_evecs, leaccsd_evecs, kshift, imds=None):\n        return self.ccsd_star_contract(eaccsd_evals, eaccsd_evecs, leaccsd_evecs, kshift, imds=imds)\n\n    def get_init_guess(self, kshift, nroots=1, koopmans=False, diag=None):\n        size = self.vector_size()\n        dtype = getattr(diag, 'dtype', np.complex)\n        nroots = min(nroots, size)\n        guess = []\n        if koopmans:\n            for n in self.nonzero_vpadding[kshift][:nroots]:\n                g = np.zeros(int(size), dtype=dtype)\n                g[n] = 1.0\n                g = self.mask_frozen(g, kshift, const=0.0)\n                guess.append(g)\n        else:\n            idx = diag.argsort()[:nroots]\n            for i in idx:\n                g = np.zeros(int(size), dtype=dtype)\n                g[i] = 1.0\n                g = self.mask_frozen(g, kshift, const=0.0)\n                guess.append(g)\n        return guess\n\n    @property\n    def nkpts(self):\n        return len(self.kpts)\n\n    def gen_matvec(self, kshift, imds=None, left=False, **kwargs):\n        if imds is None: imds = self.make_imds()\n        diag = self.get_diag(kshift, imds)\n        if left:\n            matvec = lambda xs: [self.l_matvec(x, kshift, imds, diag) for x in xs]\n        else:\n            matvec = lambda xs: [self.matvec(x, kshift, imds, diag) for x in xs]\n        return matvec, diag\n\n    def vector_to_amplitudes(self, vector, kshift=None, nkpts=None, nmo=None, nocc=None, kconserv=None):\n        if nmo is None: nmo = self.nmo\n        if nocc is None: nocc = self.nocc\n        if nkpts is None: nkpts = self.nkpts\n        if kconserv is None: kconserv = self.kconserv\n        return vector_to_amplitudes_ea(vector, kshift, nkpts, nmo, nocc, kconserv)\n\n    def amplitudes_to_vector(self, r1, r2, kshift, kconserv=None):\n        if kconserv is None: kconserv = self.kconserv\n        return amplitudes_to_vector_ea(r1, r2, kshift, kconserv)\n\n    def vector_size(self):\n        nocc = self.nocc\n        nvir = self.nmo - nocc\n        nkpts = self.nkpts\n        return nvir + nocc*nkpts*nvir*(nkpts*nvir-1)//2\n\n    def make_imds(self, eris=None):\n        imds = _IMDS(self._cc, eris)\n        imds.make_ea()\n        return imds\n\nclass EOMEA_Ta(EOMEA):\n    '''Class for EOM EACCSD(T)*(a) method by Matthews and Stanton.'''\n    def make_imds(self, eris=None):\n        imds = _IMDS(self._cc, eris=eris)\n        imds.make_t3p2_ea(self._cc)\n        return imds\n\n########################################\n# EOM-EE-CCSD\n########################################\n\ndef kernel_ee(eom, nroots=1, koopmans=False, guess=None, left=False,\n           eris=None, imds=None, partition=None, kptlist=None,\n           dtype=None, **kwargs):\n    '''See `kernel()` for a description of arguments.\n\n    This method is merely a simplified version of kernel() with a few parts\n    removed, such as those involving `eom.mask_frozen()`. Slowly they will be\n    added back for the completion of program.\n    '''\n    cput0 = (time.clock(), time.time())\n    log = logger.Logger(eom.stdout, eom.verbose)\n    if eom.verbose >= logger.WARN:\n        eom.check_sanity()\n    eom.dump_flags()\n\n    if imds is None:\n        imds = eom.make_imds(eris=eris)\n\n    nkpts = eom.nkpts\n\n    if kptlist is None:\n        kptlist = range(nkpts)\n\n    # TODO mask frozen-orbital indices\n\n    if dtype is None:\n        dtype = np.result_type(*imds.t1)\n\n    # Note that vector_size may change with kshift. Thus we do not fix\n    # the length of each eval and evec\n    evals = [None]*len(kptlist)\n    evecs = [None]*len(kptlist)\n    convs = [None]*len(kptlist)\n\n    for k, kshift in enumerate(kptlist):\n        print(\"\\nkshift =\", kshift)\n        # vector size and thus, nroots depend on kshift in the case of even nkpts,\n        size = eom.vector_size(kshift)\n        nroots = min(nroots, size)\n\n        matvec, diag = eom.gen_matvec(kshift, imds, left=left, **kwargs)\n        if diag.size != size:\n            raise ValueError(\"Number of diagonal elements in effective H does not match R vector size\")\n        # TODO update `diag` in case of frozen orbitals\n\n        # TODO allow user provided guess vector\n        # Since vector_size may change with kshift, it is difficult for users to\n        # provide guesses. Similarly, `guess` from the previous `kshift` may not\n        # work for the current `kshift` due to different vector_size. Thus for\n        # now we keep `user_guess` false, and always compute `guess` on our own.\n        user_guess = False\n        guess = eom.get_init_guess(kshift, nroots, koopmans=koopmans, diag=diag, imds=imds)\n        for ig, g in enumerate(guess):\n            guess_norm = np.linalg.norm(g)\n            guess_norm_tol = LOOSE_ZERO_TOL\n            if guess_norm < guess_norm_tol:\n                raise ValueError('Guess vector (id=%d) with norm %.4g is below threshold %.4g.\\n'\n                                 'This could possibly be due to masking/freezing orbitals.\\n'\n                                 'Check your guess vector to make sure it has sufficiently large norm.'\n                                 % (ig, guess_norm, guess_norm_tol))\n\n        def precond(r, e0, x0):\n            return r/(e0-diag+1e-12)\n\n        eig = lib.davidson_nosym1\n        # TODO allow user provided guess vector or Koopmans\n        if user_guess or koopmans:\n            def pickeig(w, v, nr, envs):\n                x0 = lib.linalg_helper._gen_x0(envs['v'], envs['xs'])\n                idx = np.argmax( np.abs(np.dot(np.array(guess).conj(),np.array(x0).T)), axis=1 )\n                return lib.linalg_helper._eigs_cmplx2real(w, v, idx)\n            conv_k, evals_k, evecs_k = eig(matvec, guess, precond, pick=pickeig,\n                                           tol=eom.conv_tol, max_cycle=eom.max_cycle,\n                                           max_space=eom.max_space, max_memory=eom.max_memory,\n                                           nroots=nroots, verbose=eom.verbose)\n        else:\n            conv_k, evals_k, evecs_k = eig(matvec, guess, precond,\n                                           tol=eom.conv_tol, max_cycle=eom.max_cycle,\n                                           max_space=eom.max_space, max_memory=eom.max_memory,\n                                           nroots=nroots, verbose=eom.verbose)\n\n        evals_k = evals_k.real\n        evals[k] = evals_k\n        evecs[k] = evecs_k\n        convs[k] = conv_k\n\n        for n, en, vn in zip(range(nroots), evals_k, evecs_k):\n            r1, r2 = eom.vector_to_amplitudes(vn, kshift=kshift)\n            if isinstance(r1, np.ndarray):\n                qp_weight = np.linalg.norm(r1) ** 2\n            else:  # for EOM-UCCSD\n                r1 = np.hstack([x.ravel() for x in r1])\n                qp_weight = np.linalg.norm(r1) ** 2\n            logger.info(eom, 'EOM-CCSD root %d E = %.16g  qpwt = %0.6g',\n                        n, en, qp_weight)\n    log.timer('EOM-CCSD', *cput0)\n    return convs, evals, evecs\n\n\ndef eeccsd(eom, nroots=1, koopmans=False, guess=None, left=False,\n           eris=None, imds=None, partition=None, kptlist=None,\n           dtype=None):\n    '''See `kernel_ee()` for a description of arguments.'''\n    eom.converged, eom.e, eom.v \\\n            = kernel_ee(eom, nroots, koopmans, guess, left, eris=eris, imds=imds,\n                  partition=partition, kptlist=kptlist, dtype=dtype)\n    return eom.e, eom.v\n\n\ndef eeccsd_matvec(eom, vector, kshift, imds=None, diag=None):\n    '''Spin-orbital EOM-EE-CCSD equations with k points.'''\n    # Ref: Wang, Tu, and Wang, J. Chem. Theory Comput. 10, 5567 (2014) Eqs.(9)-(10)\n    # Note: Last line in Eq. (10) is superfluous.\n    # See, e.g. Gwaltney, Nooijen, and Barlett, Chem. Phys. Lett. 248, 189 (1996)\n    if imds is None: imds = eom.make_imds()\n    nocc = eom.nocc\n    nmo = eom.nmo\n    nvir = nmo - nocc\n    nkpts = eom.nkpts\n    kconserv = imds.kconserv\n    kconserv_r1 = eom.get_kconserv_ee_r1(kshift)\n    kconserv_r2 = eom.get_kconserv_ee_r2(kshift)\n    r1, r2 = vector_to_amplitudes_ee(vector, kshift, nkpts, nmo, nocc, kconserv_r2)\n\n    Hr1 = np.zeros_like(r1)\n    for ki in range(nkpts):\n        ka = kconserv_r1[ki]\n        Hr1[ki] += np.einsum('ae,ie->ia', imds.Fvv[ka], r1[ki])\n        Hr1[ki] -= np.einsum('mi,ma->ia', imds.Foo[ki], r1[ki])\n        for km in range(nkpts):\n            Hr1[ki] += np.einsum('me,imae->ia', imds.Fov[km], r2[ki, km, ka])\n            ke = kconserv_r1[km]\n            Hr1[ki] += np.einsum('maei,me->ia', imds.Wovvo[km, ka, ke], r1[km])\n            for kn in range(nkpts):\n                Hr1[ki] -= 0.5*np.einsum('mnie,mnae->ia', imds.Wooov[km, kn, ki], r2[km, kn, ka])\n                # Rename dummy index kn->ke\n                Hr1[ki] += 0.5*np.einsum('amef,imef->ia', imds.Wvovv[ka, km, kn], r2[ki, km, kn])\n\n    Hr2 = np.zeros_like(r2)\n    for ki, kj, ka in kpts_helper.loop_kkk(nkpts):\n        kb = kconserv_r2[ki, ka, kj]\n\n        # r_ijab <- P(ij) (-F_mj r_imab)\n        #   km - kj = G\n        # => km = kj\n        tmp_ij = np.einsum('mj,imab->ijab', -imds.Foo[kj], r2[ki, kj, ka])\n        # r_ijab <- P(ij) W_abej r_ie\n        ke = kconserv_r1[ki]\n        tmp_ij += np.einsum('abej,ie->ijab', imds.Wvvvo[ka, kb, ke], r1[ki])\n        Hr2[ki, kj, ka] += tmp_ij\n        Hr2[kj, ki, ka] -= tmp_ij.transpose(1, 0, 2, 3)\n\n        # r_ijab <- P(ab) F_be r_ijae\n        tmp_ab = np.einsum('be,ijae->ijab', imds.Fvv[kb], r2[ki, kj, ka])\n        # r_ijab <- P(ab) (- W_mbij r_ma)\n        #   km + kb - ki - kj = G\n        # => ki + kj - km - kb = G\n        km = kconserv[ki, kb, kj]\n        tmp_ab += np.einsum('mbij,ma->ijab', -imds.Wovoo[km, kb, ki], r1[km])\n        Hr2[ki, kj, ka] += tmp_ab\n        Hr2[ki, kj, kb] -= tmp_ab.transpose(0, 1, 3, 2)\n\n        # r_ijab <- 0.5 W_mnij r_mnab\n        tmpoooo = np.zeros((nocc, nocc, nvir, nvir), dtype=r2.dtype)\n        # r_ijab <- 0.5 W_abef r_ijef\n        tmpvvvv = np.zeros((nocc, nocc, nvir, nvir), dtype=r2.dtype)\n        for km in range(nkpts):\n            # km + kn - ki - kj = G (as in W_mnij)\n            kn = kconserv[ki, km, kj]\n            tmpoooo += 0.5*np.einsum('mnij,mnab->ijab', imds.Woooo[km, kn, ki], r2[km, kn, ka])\n            # Rename dummy index km->ke\n            tmpvvvv += 0.5*np.einsum('abef,ijef->ijab', imds.Wvvvv[ka, kb, km], r2[ki, kj, km])\n        Hr2[ki, kj, ka] += tmpoooo\n        Hr2[ki, kj, ka] += tmpvvvv\n\n        # r_ijab <- P(ij) P(ab) W_mbej r_imae\n        for km in range(nkpts):\n            # km + kb - ke - kj = G\n            ke = kconserv[km, kj, kb]\n            tmp = np.einsum('mbej,imae->ijab', imds.Wovvo[km, kb, ke], r2[ki, km, ka])\n            Hr2[ki, kj, ka] += tmp\n            Hr2[kj, ki, ka] -= tmp.transpose(1, 0, 2, 3)\n            Hr2[ki, kj, kb] -= tmp.transpose(0, 1, 3, 2)\n            Hr2[kj, ki, kb] += tmp.transpose(1, 0, 3, 2)\n\n    #\n    # r_ijab <- P(ab) (-0.5 W_mnef t_ijae r_mnbf)\n    # r_ijab <- P(ab) W_amfe t_ijfb r_me\n    # r_ijab <- P(ij) (-0.5 W_mnef t_imab r_jnef)\n    # r_ijab <- P(ij) W_mnie t_njab r_me\n    #\n    # Build intermediates M = W.r2 for the four terms above\n    tmp_eb = np.zeros((nkpts, nvir, nvir), dtype=r2.dtype)\n    tmp_fa = np.zeros_like(tmp_eb)\n    tmp_jm = np.zeros((nkpts, nocc, nocc), dtype=r2.dtype)\n    tmp_in = np.zeros_like(tmp_jm)\n    for ke in range(nkpts):\n        # M_eb = W_mnef r_mnbf (or equivalently, M_ea = W_mnef r_mnaf)\n        #   km + kn - ke - kf = G\n        #   km + kn - kb - kf = G + kshift\n        # => ke - kb = G + kshift\n        kb = kconserv_r1[ke]\n        # x: km, y: kn\n        tmp_eb[ke] += np.einsum('xymnef,xymnbf->eb', imds.Woovv[:, :, ke], r2[:, :, kb])\n\n        # M_fa = W_amfe r_me (or equivalently, M_fb = W_bmfe r_me)\n        kf = ke\n        #   ki + kj - ka - kb = G + kshift\n        #   ki + kj - kf - kb = G\n        # => kf - ka = G + kshift\n        ka = kconserv_r1[kf]\n        # x: km\n        tmp_fa[kf] += np.einsum('xamfe,xme->fa', imds.Wvovv[ka, :, kf], r1)\n\n        # M_jm = W_mnef r_jnef (or equivalently, M_im = W_mnef r_inef)\n        kj = ke\n        #   km + kn - ke - kf = G\n        #   kj + kn - ke - kf = G + kshift\n        # => kj - km = G + kshift\n        km = kconserv_r1[kj]\n        # x: kn, y: ke\n        tmp_jm[kj] += np.einsum('xymnef,xyjnef->jm', imds.Woovv[km], r2[kj])\n\n        # M_in = W_mnie r_me (or equivalently, M_jn = W_mnje r_me)\n        ki = ke\n        #   ki + kj - ka - kb = G + kshift\n        #   kn + kj - ka - kb = G\n        # => ki - kn = G + kshift\n        kn = kconserv_r1[ki]\n        # x: km\n        tmp_in[ki] += np.einsum('xmnie,xme->in', imds.Wooov[:, kn, ki], r1)\n\n    for ki, kj, ka in kpts_helper.loop_kkk(nkpts):\n        kb = kconserv_r2[ki, ka, kj]\n        # r_ijab <- P(ab) (-0.5 M_eb t_ijae)\n        #   ki + kj - ka - ke = G\n        ke = kconserv[ki, ka, kj]\n        tmp_ab = 0.5*np.einsum('eb,ijae->ijab', -tmp_eb[ke], imds.t2[ki, kj, ka])\n        # r_ijab <- P(ab) M_fa t_ijfb\n        #   ki + kj - kf - kb = G\n        kf = kconserv[ki, kb, kj]\n        tmp_ab += np.einsum('fa,ijfb->ijab', tmp_fa[kf], imds.t2[ki, kj, kf])\n        Hr2[ki, kj, ka] += tmp_ab\n        Hr2[ki, kj, kb] -= tmp_ab.transpose(0, 1, 3, 2)\n\n        # r_ijab <- P(ij) (-0.5 M_jm t_imab)\n        #   kj - km = G + kshift\n        km = kconserv_r1[kj]\n        tmp_ij = 0.5*np.einsum('jm,imab->ijab', -tmp_jm[kj], imds.t2[ki, km, ka])\n        # r_ijab <- P(ij) M_in t_njab\n        #   ki - kn = G + kshift\n        kn = kconserv_r1[ki]\n        tmp_ij += np.einsum('in,njab->ijab', tmp_in[ki], imds.t2[kn, kj, ka])\n        Hr2[ki, kj, ka] += tmp_ij\n        Hr2[kj, ki, ka] -= tmp_ij.transpose(1, 0, 2, 3)\n\n    vector = amplitudes_to_vector_ee(Hr1, Hr2, kshift, kconserv_r2)\n    return vector\n\n\ndef eeccsd_diag(eom, kshift, imds=None):\n    '''Diagonal elements of similarity-transformed Hamiltonian'''\n    if imds is None: imds = eom.make_imds()\n    t1, t2 = imds.t1, imds.t2\n    nkpts, nocc, nvir = t1.shape\n    kconserv = eom.kconserv\n    kconserv_r1 = eom.get_kconserv_ee_r1(kshift)\n    kconserv_r2 = eom.get_kconserv_ee_r2(kshift)\n\n    Hr1 = np.zeros((nkpts, nocc, nvir), dtype=t1.dtype)\n    for ki in range(nkpts):\n        ka = kconserv_r1[ki]\n        Hr1[ki] -= imds.Foo[ki].diagonal()[:, None]\n        Hr1[ki] += imds.Fvv[ka].diagonal()[None, :]\n        Hr1[ki] += np.einsum('iaai->ia', imds.Wovvo[ki, ka, ka])\n\n    Hr2 = np.zeros((nkpts, nkpts, nkpts, nocc, nocc, nvir, nvir),\n                   dtype=t1.dtype)\n    # TODO allow partition='mp'\n    if eom.partition == \"mp\":\n        raise NotImplementedError\n    else:\n        for ki, kj, ka in kpts_helper.loop_kkk(nkpts):\n            kb = kconserv_r2[ki, ka, kj]\n            Hr2[ki, kj, ka] -= imds.Foo[ki].diagonal()[:, None, None, None]\n            Hr2[ki, kj, ka] -= imds.Foo[kj].diagonal()[None, :, None, None]\n            Hr2[ki, kj, ka] += imds.Fvv[ka].diagonal()[None, None, :, None]\n            Hr2[ki, kj, ka] += imds.Fvv[kb].diagonal()[None, None, None, :]\n\n            Hr2[ki, kj, ka] += np.einsum('jbbj->jb', imds.Wovvo[kj, kb, kb])[None, :, None, :]\n            Hr2[ki, kj, ka] += np.einsum('ibbi->ib', imds.Wovvo[ki, kb, kb])[:, None, None, :]\n            Hr2[ki, kj, ka] += np.einsum('jaaj->ja', imds.Wovvo[kj, ka, ka])[None, :, :, None]\n            Hr2[ki, kj, ka] += np.einsum('iaai->ia', imds.Wovvo[ki, ka, ka])[:, None, :, None]\n\n            Hr2[ki, kj, ka] += np.einsum('ijij->ij', imds.Woooo[ki, kj, ki])[:, :, None, None]\n            Hr2[ki, kj, ka] += np.einsum('abab->ab', imds.Wvvvv[ka, kb, ka])[None, None, :, :]\n\n            # This is to make t2 are non-zero\n            # Note that `kconserv` is used instead of `kconserv_r2`\n            kk = kconserv[ka, kj, kb]\n            Hr2[ki, kj, ka] -= np.einsum('kjab,kjab->jab', imds.Woovv[kk, kj, ka], imds.t2[kk, kj, ka])[None, :, :, :]\n            kk = kconserv[ka, ki, kb]\n            Hr2[ki, kj, ka] -= np.einsum('kiab,kiab->iab', imds.Woovv[kk, ki, ka], imds.t2[kk, ka, ka])[:, None, :, :]\n\n            kc = kconserv[ki, kb, kj]\n            Hr2[ki, kj, ka] -= np.einsum('ijcb,ijcb->ijb', imds.Woovv[ki, kj, kc], imds.t2[ki, kj, kc])[:, :, None, :]\n            kc = kconserv[ki, ka, kj]\n            Hr2[ki, kj, ka] -= np.einsum('ijca,ijca->ija', imds.Woovv[ki, kj, kc], imds.t2[ki, kj, kc])[:, :, :, None]\n\n    # Make sure 4th argument you pass is `kconserv_r2`\n    vector = amplitudes_to_vector_ee(Hr1, Hr2, kshift, kconserv_r2)\n    return vector\n\n\ndef vector_to_amplitudes_ee(vector, kshift, nkpts, nmo, nocc, kconserv):\n    '''Transform 1-dimensional array to 3- and 7-dimensional arrays, r1 and r2.\n\n    For example:\n        vector: a 1-d array with all r1 elements, and r2 elements whose indices\n    satisfy (i k_i) > (j k_j) and (a k_a) > (b k_b)\n        return: [r1, r2], where\n        r1 = r_{i k_i}^{a k_a} is a 3-d array whose elements can be accessed via\n            r1[k_i, i, a].\n\n        r2 = r_{i k_i, j k_j}^{a k_a, b k_b} is a 7-d array whose elements can\n    be accessed via\n\n            r2[k_i, k_j, k_a, i, j, a, b]\n    '''\n    nvir = nmo - nocc\n\n    r1 = vector[:nkpts*nocc*nvir].copy().reshape(nkpts, nocc, nvir)\n\n    ki_i, kj_j = np.tril_indices(nkpts*nocc, -1)\n    ida, idb = np.tril_indices(nvir, -1)\n    r2 = np.zeros((nkpts*nocc, nkpts*nocc, nkpts, nvir, nvir), dtype=vector.dtype)\n\n    r2_tril = vector[nkpts*nocc*nvir:].copy()\n\n    offset = 0\n    nvir2_tril = nvir*(nvir-1)//2\n    nvir2 = nvir*nvir\n    for ij in range(len(ki_i)):\n        idx_ki_i = ki_i[ij]\n        idx_kj_j = kj_j[ij]\n        ki = idx_ki_i // nocc\n        kj = idx_kj_j // nocc\n        r2_ka_ab = np.zeros((nkpts, nvir, nvir), dtype=r2_tril.dtype)\n        for ka in range(nkpts):\n            kb = kconserv[ki, ka, kj]\n            if ka == kb:\n                tmp = r2_tril[offset:offset+nvir2_tril]\n                r2_ka_ab[ka, ida, idb] = tmp\n                r2_ka_ab[ka, idb, ida] = -tmp\n                offset += nvir2_tril\n            elif ka > kb:\n                tmp = r2_tril[offset:offset+nvir2].reshape(nvir, nvir)\n                r2_ka_ab[ka] = tmp\n                r2_ka_ab[kb] = -tmp.transpose()\n                offset += nvir2\n        r2[idx_ki_i, idx_kj_j] = r2_ka_ab\n        r2[idx_kj_j, idx_ki_i] = -r2_ka_ab\n\n    r2 = r2.reshape(nkpts, nocc, nkpts, nocc, nkpts, nvir, nvir).transpose(0, 2, 4, 1, 3, 5, 6)\n    return [r1, r2]\n\n\ndef amplitudes_to_vector_ee(r1, r2, kshift, kconserv):\n    '''Transform 3- and 7-dimensional arrays, r1 and r2, to a 1-dimensional\n    array with unique indices.\n\n    For example:\n        r1: t_{i k_i}^{a k_a}\n        r2: t_{i k_i, j k_j}^{a k_a, b k_b}\n        return: a vector with all r1 elements, and r2 elements whose indices\n    satisfy (i k_i) > (j k_j) and (a k_a) > (b k_b)\n    '''\n    # r1 indices: k_i, i, a\n    nkpts, nocc, nvir = np.asarray(r1.shape)[[0, 1, 2]]\n\n    # r2 indices (old): k_i, k_j, k_a, i, j, a, b\n    # r2 indices (new): (k_i, i), (k_j, j), (k_a, a, b)\n    r2 = r2.transpose(0, 3, 1, 4, 2, 5, 6).reshape(nkpts*nocc, nkpts*nocc, nkpts, nvir, nvir)\n\n    # Get (k_i, i) and (k_j, j) indices for the lower-triangle of r2\n    ki_i, kj_j = np.tril_indices(nkpts*nocc, -1)\n    ida, idb = np.tril_indices(nvir, -1)\n\n    vector = r1.ravel()\n    for ij in range(len(ki_i)):\n        ki = ki_i[ij] // nocc\n        kj = kj_j[ij] // nocc\n        r2ab = r2[ki_i[ij], kj_j[ij]]\n        for ka in range(nkpts):\n            kb = kconserv[ki, ka, kj]\n            if ka == kb:\n                vector = np.hstack((vector, r2ab[ka, ida, idb]))\n            elif ka > kb:\n                vector = np.hstack((vector, r2ab[ka].ravel()))\n\n    return vector\n\n\nclass EOMEE(eom_rccsd.EOM):\n    def __init__(self, cc):\n        self.kpts = cc.kpts\n        self.kconserv = cc.khelper.kconserv\n        # debug\n        self.debug_vals = np.array([None]*len(cc.kpts))\n        eom_rccsd.EOM.__init__(self, cc)\n\n    kernel = eeccsd\n    eeccsd = eeccsd\n    matvec = eeccsd_matvec\n    get_diag = eeccsd_diag\n\n    @property\n    def nkpts(self):\n        return len(self.kpts)\n\n    def vector_size(self, kshift=0):\n        '''Size of the linear excitation operator R vector based on spin-orbital basis.\n\n        Kwargs:\n            kshift : int\n                index of kpt in R(k)\n\n        Returns:\n            size (int): number of unique elements in linear excitation operator R\n\n        Notes:\n            The vector size is kshift-dependent if nkpts is an even number\n            '''\n        nocc = self.nocc  # alpha+beta\n        nvir = self.nmo-nocc  # alpha+beta\n        nkpts = self.nkpts\n\n        size_r1 = nkpts*nocc*nvir\n        if nkpts % 2 == 1:\n            size_r2 = nkpts*nocc*(nkpts*nocc-1)//2*nvir*(nkpts*nvir-1)//2\n        else:\n            size_oo = nocc*(nocc-1)//2  # When ki==kj, there are size_oo ways to create 2 holes\n            size_vv = nvir*(nvir-1)//2  # When ka==kb, there are size_vv ways to create 2 particles\n            size_r2 = 0\n            kconserv = self.get_kconserv_ee_r2(kshift)\n            # TODO Optimize this 3-layer for loop, or find an elegant solution\n            for ki, kj, ka in kpts_helper.loop_kkk(nkpts):\n                kb = kconserv[ki, ka, kj]\n                if ki == kj:\n                    if ka == kb:\n                        size_r2 += size_oo*size_vv\n                    elif ka > kb:\n                        size_r2 += size_oo*nvir**2\n                elif ki > kj:\n                    if ka == kb:\n                        size_r2 += nocc**2*size_vv\n                    elif ka > kb:\n                        size_r2 += nocc**2*nvir**2\n\n        return size_r1 + size_r2\n\n    def get_init_guess(self, kshift, nroots=1, koopmans=False, diag=None, **kwargs):\n        \"\"\"Initial guess vectors of R coefficients\"\"\"\n        size = self.vector_size(kshift)\n        dtype = getattr(diag, 'dtype', np.complex)\n        nroots = min(nroots, size)\n        guess = []\n        # TODO do Koopmans later\n        if koopmans:\n            raise NotImplementedError\n        else:\n            idx = diag.argsort()[:nroots]\n            for i in idx:\n                g = np.zeros(int(size), dtype=dtype)\n                g[i] = 1.0\n                # TODO do mask_frozen later\n                guess.append(g)\n        return guess\n\n    def gen_matvec(self, kshift, imds=None, left=False, **kwargs):\n        if imds is None: imds = self.make_imds()\n        diag = self.get_diag(kshift, imds)\n        if left:\n            # TODO allow left vectors to be computed\n            raise NotImplementedError\n        else:\n            matvec = lambda xs: [self.matvec(x, kshift, imds, diag) for x in xs]\n        return matvec, diag\n\n    def vector_to_amplitudes(self, vector, kshift=None, nkpts=None, nmo=None, nocc=None, kconserv=None):\n        if nmo is None: nmo = self.nmo\n        if nocc is None: nocc = self.nocc\n        if nkpts is None: nkpts = self.nkpts\n        if kconserv is None: kconserv = self.get_kconserv_ee_r2(kshift)\n        return vector_to_amplitudes_ee(vector, kshift, nkpts, nmo, nocc, kconserv)\n\n    def amplitudes_to_vector(self, r1, r2, kshift, kconserv=None):\n        if kconserv is None: kconserv = self.get_kconserv_ee_r2(kshift)\n        return amplitudes_to_vector_ee(r1, r2, kshift, kconserv)\n\n    def get_kconserv_ee_r1(self, kshift=0):\n        '''Get the momentum conservation array for a set of k-points.\n\n        Given k-point index m the array kconserv_r1[m] returns the index n that\n        satisfies momentum conservation,\n\n            (k(m) - k(n) - kshift) \\dot a = 2n\\pi\n\n        This is used for symmetry of 1p-1h excitation operator vector\n        R_{m k_m}^{n k_n} is zero unless n satisfies the above.\n\n        Note that this method is adapted from `kpts_helper.get_kconserv()`.\n        '''\n        kconserv_r1 = self.kconserv[:,kshift,0].copy()\n        return kconserv_r1\n\n    # TODO merge it with `kpts_helper.get_kconserv()`\n    def get_kconserv_ee_r2(self, kshift=0):\n        r'''Get the momentum conservation array for a set of k-points.\n\n        Given k-point indices (k, l, m) the array kconserv_r2[k,l,m] returns\n        the index n that satisfies momentum conservation,\n\n            (k(k) - k(l) + k(m) - k(n) - kshift) \\dot a = 2n\\pi\n\n        This is used for symmetry of 2p-2h excitation operator vector\n        R_{k k_k, m k_m}^{l k_l n k_n} is zero unless n satisfies the above.\n\n        Note that this method is adapted from `kpts_helper.get_kconserv()`.\n        '''\n        cell = self._cc._scf.cell\n        kpts = self.kpts\n        nkpts = kpts.shape[0]\n        a = cell.lattice_vectors() / (2 * np.pi)\n\n        kconserv_r2 = np.zeros((nkpts, nkpts, nkpts), dtype=int)\n        kvKLM = kpts[:, None, None, :] - kpts[:, None, :] + kpts\n        # Apply k shift\n        kvKLM = kvKLM - kpts[kshift]\n        for N, kvN in enumerate(kpts):\n            kvKLMN = np.einsum('wx,klmx->wklm', a, kvKLM - kvN)\n            # check whether (1/(2pi) k_{KLMN} dot a) is an integer\n            kvKLMN_int = np.rint(kvKLMN)\n            mask = np.einsum('wklm->klm', abs(kvKLMN - kvKLMN_int)) < 1e-9\n            kconserv_r2[mask] = N\n        return kconserv_r2\n\n    def make_imds(self, eris=None):\n        imds = _IMDS(self._cc, eris=eris)\n        imds.make_ee()\n        return imds\n\n\nclass _IMDS:\n    # Exactly the same as RCCSD IMDS except\n    # -- rintermediates --> gintermediates\n    # -- Loo, Lvv, cc_Fov --> Foo, Fvv, Fov\n    # -- One less 2-virtual intermediate\n    def __init__(self, cc, eris=None):\n        self._cc = cc\n        self.verbose = cc.verbose\n        self.kconserv = kpts_helper.get_kconserv(cc._scf.cell, cc.kpts)\n        self.stdout = cc.stdout\n        self.t1, self.t2 = cc.t1, cc.t2\n        if eris is None:\n            eris = cc.ao2mo()\n        self.eris = eris\n        self._made_shared = False\n        self.made_ip_imds = False\n        self.made_ea_imds = False\n        self.made_ee_imds = False\n\n    def _make_shared(self):\n        cput0 = (time.clock(), time.time())\n\n        kconserv = self.kconserv\n        t1, t2, eris = self.t1, self.t2, self.eris\n\n        self.Foo = imd.Foo(self._cc, t1, t2, eris, kconserv)\n        self.Fvv = imd.Fvv(self._cc, t1, t2, eris, kconserv)\n        self.Fov = imd.Fov(self._cc, t1, t2, eris, kconserv)\n\n        # 2 virtuals\n        self.Wovvo = imd.Wovvo(self._cc, t1, t2, eris, kconserv)\n        self.Woovv = eris.oovv\n\n        self._made_shared = True\n        logger.timer_debug1(self, 'EOM-CCSD shared intermediates', *cput0)\n        return self\n\n    def make_ip(self):\n        if not self._made_shared:\n            self._make_shared()\n\n        cput0 = (time.clock(), time.time())\n\n        kconserv = self.kconserv\n        t1, t2, eris = self.t1, self.t2, self.eris\n\n        # 0 or 1 virtuals\n        self.Woooo = imd.Woooo(self._cc, t1, t2, eris, kconserv)\n        self.Wooov = imd.Wooov(self._cc, t1, t2, eris, kconserv)\n        self.Wovoo = imd.Wovoo(self._cc, t1, t2, eris, kconserv)\n\n        self.made_ip_imds = True\n        logger.timer_debug1(self, 'EOM-CCSD IP intermediates', *cput0)\n        return self\n\n    def make_t3p2_ip(self, cc):\n        cput0 = (time.clock(), time.time())\n\n        t1, t2, eris = cc.t1, cc.t2, self.eris\n        delta_E_corr, pt1, pt2, Wovoo, Wvvvo = \\\n            imd.get_t3p2_imds_slow(cc, t1, t2, eris)\n        self.t1 = pt1\n        self.t2 = pt2\n\n        self._made_shared = False  # Force update\n        self.make_ip()  # Make after t1/t2 updated\n        self.Wovoo = self.Wovoo + Wovoo\n\n        self.made_ip_imds = True\n        logger.timer_debug1(self, 'EOM-CCSD(T)a IP intermediates', *cput0)\n        return self\n\n    def make_ea(self):\n        if not self._made_shared:\n            self._make_shared()\n\n        cput0 = (time.clock(), time.time())\n\n        kconserv = self.kconserv\n        t1, t2, eris = self.t1, self.t2, self.eris\n\n        # FIXME DELETE WOOOO\n        # 0 or 1 virtuals\n        self.Woooo = imd.Woooo(self._cc, t1, t2, eris, kconserv)\n        # 3 or 4 virtuals\n        self.Wvovv = imd.Wvovv(self._cc, t1, t2, eris, kconserv)\n        self.Wvvvv = imd.Wvvvv(self._cc, t1, t2, eris, kconserv)\n        self.Wvvvo = imd.Wvvvo(self._cc, t1, t2, eris, kconserv)\n\n        self.made_ea_imds = True\n        logger.timer_debug1(self, 'EOM-CCSD EA intermediates', *cput0)\n        return self\n\n    def make_t3p2_ea(self, cc):\n        cput0 = (time.clock(), time.time())\n\n        t1, t2, eris = cc.t1, cc.t2, self.eris\n        delta_E_corr, pt1, pt2, Wovoo, Wvvvo = \\\n            imd.get_t3p2_imds_slow(cc, t1, t2, eris)\n        self.t1 = pt1\n        self.t2 = pt2\n\n        self._made_shared = False  # Force update\n        self.make_ea()  # Make after t1/t2 updated\n        self.Wvvvo = self.Wvvvo + Wvvvo\n\n        self.made_ea_imds = True\n        logger.timer_debug1(self, 'EOM-CCSD(T)a EA intermediates', *cput0)\n        return self\n\n    def make_ee(self):\n        if not self._made_shared:\n            self._make_shared()\n\n        cput0 = (time.clock(), time.time())\n\n        kconserv = self.kconserv\n        t1, t2, eris = self.t1, self.t2, self.eris\n\n        if not self.made_ip_imds:\n            # 0 or 1 virtuals\n            self.Woooo = imd.Woooo(self._cc, t1, t2, eris, kconserv)\n            self.Wooov = imd.Wooov(self._cc, t1, t2, eris, kconserv)\n            self.Wovoo = imd.Wovoo(self._cc, t1, t2, eris, kconserv)\n        if not self.made_ea_imds:\n            # 3 or 4 virtuals\n            self.Wvovv = imd.Wvovv(self._cc, t1, t2, eris, kconserv)\n            self.Wvvvv = imd.Wvvvv(self._cc, t1, t2, eris, kconserv)\n            self.Wvvvo = imd.Wvvvo(self._cc, t1, t2, eris, kconserv, self.Wvvvv)\n\n        self.made_ee_imds = True\n        logger.timer(self, 'EOM-CCSD EE intermediates', *cput0)\n        return self\n\nif __name__ == '__main__':\n    from pyscf.pbc import gto, scf, cc\n\n    cell = gto.Cell()\n    cell.atom='''\n    C 0.000000000000   0.000000000000   0.000000000000\n    C 1.685068664391   1.685068664391   1.685068664391\n    '''\n    cell.basis = { 'C': [[0, (0.8, 1.0)],\n                         [1, (1.0, 1.0)]]}\n    cell.pseudo = 'gth-pade'\n    cell.a = '''\n    0.000000000, 3.370137329, 3.370137329\n    3.370137329, 0.000000000, 3.370137329\n    3.370137329, 3.370137329, 0.000000000'''\n    cell.unit = 'B'\n    cell.verbose = 5\n    cell.build()\n\n    # Running HF and CCSD with 1x1x2 Monkhorst-Pack k-point mesh\n    kmf = scf.KRHF(cell, kpts=cell.make_kpts([1,1,2]), exxdiv=None)\n    kmf.conv_tol_grad = 1e-8\n    ehf = kmf.kernel()\n\n    mycc = cc.KGCCSD(kmf)\n    mycc.conv_tol = 1e-12\n    mycc.conv_tol_normt = 1e-10\n    eris = mycc.ao2mo(mycc.mo_coeff)\n    ecc, t1, t2 = mycc.kernel()\n    print(ecc - -0.155298393321855)\n\n    eom = EOMIP(mycc)\n    e, v = eom.ipccsd(nroots=2, kptlist=[0])\n\n    eom = EOMEA(mycc)\n    eom.max_cycle = 100\n    e, v = eom.eaccsd(nroots=2, koopmans=True, kptlist=[0])\n", "meta": {"hexsha": "31c6467399c661377a470c0a288b98b239e09a86", "size": 83224, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/pbc/cc/eom_kccsd_ghf.py", "max_stars_repo_name": "LeonOtis/pyscf", "max_stars_repo_head_hexsha": "98ba8106396ac4c90dc65207059773ce048b0ebf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-03T12:32:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T08:19:02.000Z", "max_issues_repo_path": "pyscf/pbc/cc/eom_kccsd_ghf.py", "max_issues_repo_name": "LeonOtis/pyscf", "max_issues_repo_head_hexsha": "98ba8106396ac4c90dc65207059773ce048b0ebf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscf/pbc/cc/eom_kccsd_ghf.py", "max_forks_repo_name": "LeonOtis/pyscf", "max_forks_repo_head_hexsha": "98ba8106396ac4c90dc65207059773ce048b0ebf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-06-01T05:31:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T02:38:33.000Z", "avg_line_length": 40.8361138371, "max_line_length": 118, "alphanum_fraction": 0.5739330001, "include": true, "reason": "import numpy", "num_tokens": 28299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.29421497216298875, "lm_q1q2_score": 0.18313685068098504}}
{"text": "#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\nUtilities for working with models (the astrophysics complement to `mcmctools`).\n\"\"\"\n\nimport numpy as np\n\nfrom sedbot.photconv import abs_ab_mag_to_micro_jy\nfrom sedbot.zinterp import bracket_logz, interp_logz\n\n\ndef mock_dataset(sp, bands, d0, m0, logZZsol, mag_sigma, apply_errors=False):\n    \"\"\"Generate a mock SED given the FSPS stellar population model.\n\n    Parameters\n    ----------\n    sp : :class:`fsps.StellarPopulation`\n        A python-fsps StellarPopulation instance with parameters pre-set.\n    bands : iterable\n        A list of bandpass names, as strings (see python-fsps documentation.\n    d0 : float\n        Distance in parsecs.\n    m0 : float\n        Mass of stellar population (solar masses).\n    logZZsol : float\n        Metallicity of stellar population, :math:`log(Z/Z_\\odot)`. This\n        parameters, rather than the FSPS `zmet` parameter is used so that\n        a stellar population of an arbitrary metallicity can be logarithmically\n        interpolated from two bracketing isochrones.\n    mag_sigma : float or (nbands,) iterable\n        Photometric uncertainty of each bandpass, in magnitudes. If a single\n        float is passed then that uncertainty is used for each bandpass.\n        Otherwise, it must be an array of uncertainties matching the number\n        of bands.\n    apply_errors : bool\n        If true, then Gaussian errors, specified by `mag_sigma` will be applied\n        to the SED.\n\n    Returns\n    -------\n    mock_mjy : ndarray\n        SED, in micro-Janskies.\n    mock_sigma : ndarray\n        SED uncertainties, in micro-Janskies.\n    \"\"\"\n    zmet1, zmet2 = bracket_logz(logZZsol)\n    sp.params['zmet'] = zmet1\n    f1 = abs_ab_mag_to_micro_jy(sp.get_mags(tage=13.8, bands=bands), d0)\n    sp.params['zmet'] = zmet2\n    f2 = abs_ab_mag_to_micro_jy(sp.get_mags(tage=13.8, bands=bands), d0)\n    mock_mjy = m0 * interp_logz(zmet1, zmet2, logZZsol, f1, f2)\n    if isinstance(mag_sigma, float):\n        mag_sigma = np.ones(len(bands)) * mag_sigma\n    mock_sigma = (mock_mjy * mag_sigma) / 1.0875\n    if apply_errors:\n        nbands = len(bands)\n        mock_mjy += mock_sigma * np.random.normal(loc=0.0, scale=1.0,\n                                                  size=nbands)\n    return mock_mjy, mock_sigma\n", "meta": {"hexsha": "c66f5fc3ea229f00a00d906627e9e341ec58951f", "size": 2290, "ext": "py", "lang": "Python", "max_stars_repo_path": "sedbot/modeltools.py", "max_stars_repo_name": "jonathansick/sedbot", "max_stars_repo_head_hexsha": "3114ebb36a8618800b3b556fe1a63372b4b5e054", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sedbot/modeltools.py", "max_issues_repo_name": "jonathansick/sedbot", "max_issues_repo_head_hexsha": "3114ebb36a8618800b3b556fe1a63372b4b5e054", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sedbot/modeltools.py", "max_forks_repo_name": "jonathansick/sedbot", "max_forks_repo_head_hexsha": "3114ebb36a8618800b3b556fe1a63372b4b5e054", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5409836066, "max_line_length": 79, "alphanum_fraction": 0.668558952, "include": true, "reason": "import numpy", "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.29421495978593415, "lm_q1q2_score": 0.18313684709793313}}
{"text": "import numpy as np\nimport csv\nimport prob2020.python.utils as utils\nfrom ..cython import cutils\nimport prob2020.python.mutation_context as mc\nimport prob2020.python.scores as scores\n\n\ndef deleterious_permutation(obs_del,\n                            context_counts,\n                            context_to_mut,\n                            seq_context,\n                            gene_seq,\n                            num_permutations=10000,\n                            stop_criteria=100,\n                            pseudo_count=0,\n                            max_batch=25000):\n    \"\"\"Performs null-permutations for deleterious mutation statistics\n    in a single gene.\n\n    Parameters\n    ----------\n    context_counts : pd.Series\n        number of mutations for each context\n    context_to_mut : dict\n        dictionary mapping nucleotide context to a list of observed\n        somatic base changes.\n    seq_context : SequenceContext\n        Sequence context for the entire gene sequence (regardless\n        of where mutations occur). The nucleotide contexts are\n        identified at positions along the gene.\n    gene_seq : GeneSequence\n        Sequence of gene of interest\n    num_permutations : int, default: 10000\n        number of permutations to create for null\n    pseudo_count : int, default: 0\n        Pseudo-count for number of deleterious mutations for each\n        permutation of the null distribution. Increasing pseudo_count\n        makes the statistical test more stringent.\n\n    Returns\n    -------\n    del_count_list : list\n        list of deleterious mutation counts under the null\n    \"\"\"\n    mycontexts = context_counts.index.tolist()\n    somatic_base = [base\n                    for one_context in mycontexts\n                    for base in context_to_mut[one_context]]\n\n    # calculate the # of batches for simulations\n    max_batch = min(num_permutations, max_batch)\n    num_batches = num_permutations // max_batch\n    remainder = num_permutations % max_batch\n    batch_sizes = [max_batch] * num_batches\n    if remainder:\n        batch_sizes += [remainder]\n\n    num_sim = 0\n    null_del_ct = 0\n    for j, batch_size in enumerate(batch_sizes):\n        # stop iterations if reached sufficient precision\n        if null_del_ct >= stop_criteria:\n            #j = j - 1\n            break\n\n        # get random positions determined by sequence context\n        tmp_contxt_pos = seq_context.random_pos(context_counts.iteritems(),\n                                                batch_size)\n        tmp_mut_pos = np.hstack([pos_array for base, pos_array in tmp_contxt_pos])\n\n        # determine result of random positions\n        for i, row in enumerate(tmp_mut_pos):\n            # get info about mutations\n            tmp_mut_info = mc.get_aa_mut_info(row,\n                                              somatic_base,\n                                              gene_seq)\n\n            # calc deleterious mutation info\n            tmp_del_count = cutils.calc_deleterious_info(tmp_mut_info['Reference AA'],\n                                                         tmp_mut_info['Somatic AA'],\n                                                         tmp_mut_info['Codon Pos'])\n\n            # update empricial null distribution\n            if tmp_del_count >= obs_del: null_del_ct += 1\n\n            # stop if reach sufficient precision on p-value\n            if null_del_ct >= stop_criteria:\n                break\n        # update number of simulations\n        num_sim += i + 1\n\n    #num_sim = j*max_batch + i+1\n    del_pval = float(null_del_ct) / (num_sim)\n\n    return del_pval\n\n\ndef position_permutation(obs_stat,\n                         context_counts,\n                         context_to_mut,\n                         seq_context,\n                         gene_seq,\n                         gene_vest=None,\n                         num_permutations=10000,\n                         stop_criteria=100,\n                         pseudo_count=0,\n                         max_batch=25000):\n    \"\"\"Performs null-permutations for position-based mutation statistics\n    in a single gene.\n\n    Parameters\n    ----------\n    obs_stat : tuple, (recur ct, entropy, delta entropy, mean vest)\n        tuple containing the observed statistics\n    context_counts : pd.Series\n        number of mutations for each context\n    context_to_mut : dict\n        dictionary mapping nucleotide context to a list of observed\n        somatic base changes.\n    seq_context : SequenceContext\n        Sequence context for the entire gene sequence (regardless\n        of where mutations occur). The nucleotide contexts are\n        identified at positions along the gene.\n    gene_seq : GeneSequence\n        Sequence of gene of interest\n    num_permutations : int, default: 10000\n        number of permutations to create for null\n    stop_criteria : int\n        stop after stop_criteria iterations are more significant\n        then the observed statistic.\n    pseudo_count : int, default: 0\n        Pseudo-count for number of recurrent missense mutations for each\n        permutation for the null distribution. Increasing pseudo_count\n        makes the statistical test more stringent.\n\n    Returns\n    -------\n    num_recur_list : list\n        list of recurrent mutation counts under the null\n    entropy_list : list\n        list of position entropy values under the null\n    \"\"\"\n    # get contexts and somatic base\n    mycontexts = context_counts.index.tolist()\n    somatic_base = [base\n                    for one_context in mycontexts\n                    for base in context_to_mut[one_context]]\n\n    # calculate the # of batches for simulations\n    max_batch = min(num_permutations, max_batch)\n    num_batches = num_permutations // max_batch\n    remainder = num_permutations % max_batch\n    batch_sizes = [max_batch] * num_batches\n    if remainder:\n        batch_sizes += [remainder]\n\n    obs_recur, obs_ent, obs_delta_ent, obs_vest = obs_stat\n    num_sim = 0 # number of simulations\n    null_num_recur_ct, null_entropy_ct, null_delta_entropy_ct, null_vest_ct = 0, 0, 0, 0\n    for j, batch_size in enumerate(batch_sizes):\n        # stop iterations if reached sufficient precision\n        if null_vest_ct >= stop_criteria and null_entropy_ct >= stop_criteria:\n            break\n\n        # get random positions determined by sequence context\n        tmp_contxt_pos = seq_context.random_pos(context_counts.iteritems(),\n                                                batch_size)\n        tmp_mut_pos = np.hstack([pos_array for base, pos_array in tmp_contxt_pos])\n\n        # calculate position-based statistics as a result of random positions\n        for i, row in enumerate(tmp_mut_pos):\n            # get info about mutations\n            tmp_mut_info = mc.get_aa_mut_info(row,\n                                              somatic_base,\n                                              gene_seq)\n\n            # calculate position info\n            tmp_recur_ct, tmp_entropy, tmp_delta_entropy, _ = cutils.calc_pos_info(tmp_mut_info['Codon Pos'],\n                                                                                tmp_mut_info['Reference AA'],\n                                                                                tmp_mut_info['Somatic AA'],\n                                                                                pseudo_count=pseudo_count,\n                                                                                is_obs=0)\n            # get vest scores\n            if gene_vest:\n                tmp_vest = scores.compute_vest_stat(gene_vest,\n                                                    tmp_mut_info['Reference AA'],\n                                                    tmp_mut_info['Somatic AA'],\n                                                    tmp_mut_info['Codon Pos'])\n            else:\n                tmp_vest = 0.0\n\n            # update empirical null distribution counts\n            if tmp_entropy-utils.epsilon <= obs_ent: null_entropy_ct += 1\n            if tmp_vest+utils.epsilon >= obs_vest: null_vest_ct += 1\n\n            # stop iterations if reached sufficient precision\n            if null_vest_ct >= stop_criteria and null_entropy_ct >= stop_criteria:\n                break\n        # update the number of simulations\n        num_sim += i+1\n\n    # calculate p-value from empirical null-distribution\n    ent_pval = float(null_entropy_ct) / (num_sim)\n    vest_pval = float(null_vest_ct) / (num_sim)\n\n    return ent_pval, vest_pval\n\n\ndef hotmaps_permutation(obs_stat,\n                        context_counts,\n                        context_to_mut,\n                        seq_context,\n                        gene_seq,\n                        window,\n                        num_permutations=10000,\n                        stop_criteria=100,\n                        max_batch=25000,\n                        null_save_path=None):\n    \"\"\"Performs null-permutations for position-based mutation statistics\n    in a single gene.\n\n    Parameters\n    ----------\n    obs_stat : dict\n        dictionary mapping codons to the sum of mutations in a window\n    context_counts : pd.Series\n        number of mutations for each context\n    context_to_mut : dict\n        dictionary mapping nucleotide context to a list of observed\n        somatic base changes.\n    seq_context : SequenceContext\n        Sequence context for the entire gene sequence (regardless\n        of where mutations occur). The nucleotide contexts are\n        identified at positions along the gene.\n    gene_seq : GeneSequence\n        Sequence of gene of interest\n    window : int\n        Number of codons to the left/right of a mutated position to consider\n        in the window\n    num_permutations : int, default: 10000\n        number of permutations to create for null\n    stop_criteria : int\n        stop after stop_criteria iterations are more significant\n        then the observed statistic.\n    max_batch : int\n        maximum number of whole gene simulations to do at once.\n        For large number of simulations holding a matrix of M x N,\n        where M is the number of mutations and N is the number of simulations,\n        can get quite large.\n    null_save_path : str or None\n        File path to save null distribution. If None, don't save it.\n\n    Returns\n    -------\n    pvals : dict\n        Maps mutated codon position to the calculated p-value\n    \"\"\"\n    # get contexts and somatic base\n    mycontexts = context_counts.index.tolist()\n    somatic_base = [base\n                    for one_context in mycontexts\n                    for base in context_to_mut[one_context]]\n\n    # calculate the # of batches for simulations\n    max_batch = min(num_permutations, max_batch)\n    num_batches = num_permutations // max_batch\n    remainder = num_permutations % max_batch\n    batch_sizes = [max_batch] * num_batches\n    if remainder:\n        batch_sizes += [remainder]\n\n    # figure out which position has highest value\n    max_key = {w: max(obs_stat[w], key=(lambda key: obs_stat[w][key]))\n               for w in window}\n\n    # setup null dist counts\n    null_cts = {w: {k: 0 for k in obs_stat[w]}\n                for w in window }\n\n    # empirical null distribution (saved if file path provided)\n    empirical_null = {w: {} for w in window}\n\n    num_sim = 0 # number of simulations\n    for j, batch_size in enumerate(batch_sizes):\n        # stop iterations if reached sufficient precision\n        stop_flag = [(null_cts[w][max_key[w]]>=stop_criteria)\n                      for w in window]\n        if all(stop_flag):\n            break\n        #if null_cts[max_key] >= stop_criteria:\n            #break\n\n        # get random positions determined by sequence context\n        tmp_contxt_pos = seq_context.random_pos(context_counts.iteritems(),\n                                                batch_size)\n        tmp_mut_pos = np.hstack([pos_array for base, pos_array in tmp_contxt_pos])\n\n        # calculate position-based statistics as a result of random positions\n        for i, row in enumerate(tmp_mut_pos):\n            # get info about mutations\n            tmp_mut_info = mc.get_aa_mut_info(row,\n                                              somatic_base,\n                                              gene_seq)\n\n            # calculate position info\n            tmp_pos, tmp_sim = utils.calc_windowed_sum(tmp_mut_info['Codon Pos'],\n                                                 tmp_mut_info['Reference AA'],\n                                                 tmp_mut_info['Somatic AA'],\n                                                 window)\n\n            # update the counts when the empirical null passes the observed\n            for tmp_w in tmp_sim:\n                for tmp_key in tmp_sim[tmp_w]:\n                    # get mutation count for simulation\n                    val = tmp_sim[tmp_w][tmp_key]\n\n                    # add to empirical null distribution\n                    empirical_null[tmp_w].setdefault(val, 0)\n                    empirical_null[tmp_w][val] += 1\n\n                    # update counts used for p-value\n                    for key in null_cts[tmp_w]:\n                        if val >= obs_stat[tmp_w][key]:\n                            null_cts[tmp_w][key] += 1\n\n            # update the number of simulations\n            num_sim += len(tmp_pos)\n\n            # stop iterations if reached sufficient precision\n            stop_flag = [(null_cts[w][max_key[w]]>=stop_criteria)\n                         for w in window]\n            if all(stop_flag):\n                break\n\n    # calculate p-value from empirical null-distribution\n    pvals = {w: {k: float(null_cts[w][k]) / (num_sim) for k in obs_stat[w]}\n             for w in window}\n\n    # save empirical distribution\n    if null_save_path:\n        for w in window:\n            # create null distribution\n            output = [['mutation_count', 'p-value']]\n            sorted_cts = sorted(empirical_null[w].keys())\n            tmp_sum = 0\n            for i in range(len(sorted_cts)):\n                tmp_sum += empirical_null[w][sorted_cts[-(i+1)]]\n                tmp_pval = tmp_sum / float(num_sim)\n                output.append([sorted_cts[-(i+1)], tmp_pval])\n            # save output\n            with open(null_save_path.format(w), 'w') as handle:\n                mywriter = csv.writer(handle, delimiter='\\t', lineterminator='\\n')\n                mywriter.writerows(output)\n\n    return pvals\n\n\ndef protein_permutation(graph_score,\n                        num_codons_obs,\n                        context_counts,\n                        context_to_mut,\n                        seq_context,\n                        gene_seq,\n                        gene_graph,\n                        num_permutations=10000,\n                        stop_criteria=100,\n                        pseudo_count=0):\n    \"\"\"Performs null-simulations for position-based mutation statistics\n    in a single gene.\n\n    Parameters\n    ----------\n    graph_score : float\n        clustering score for observed data\n    num_codons_obs : int\n        number of codons with missense mutation in observed data\n    context_counts : pd.Series\n        number of mutations for each context\n    context_to_mut : dict\n        dictionary mapping nucleotide context to a list of observed\n        somatic base changes.\n    seq_context : SequenceContext\n        Sequence context for the entire gene sequence (regardless\n        of where mutations occur). The nucleotide contexts are\n        identified at positions along the gene.\n    gene_seq : GeneSequence\n        Sequence of gene of interest\n    num_permutations : int, default: 10000\n        number of permutations to create for null\n    stop_criteria : int\n        stop after stop_criteria iterations are more significant\n        then the observed statistic.\n\n    Returns\n    -------\n    protein_pval : float\n        p-value for clustering in neighbor graph constructure from protein\n        structures\n    \"\"\"\n    # get contexts and somatic base\n    mycontexts = context_counts.index.tolist()\n    somatic_base = [base\n                    for one_context in mycontexts\n                    for base in context_to_mut[one_context]]\n\n    # get random positions determined by sequence context\n    tmp_contxt_pos = seq_context.random_pos(context_counts.iteritems(),\n                                            num_permutations)\n    tmp_mut_pos = np.hstack([pos_array for base, pos_array in tmp_contxt_pos])\n\n    # calculate position-based statistics as a result of random positions\n    null_graph_entropy_ct = 0\n    coverage_list = []\n    num_mut_list = []\n    graph_entropy_list = []\n    for i, row in enumerate(tmp_mut_pos):\n        # calculate the expected value of the relative increase in coverage\n        if i == stop_criteria-1:\n            rel_inc = [coverage_list[k] / float(num_mut_list[k])\n                       for k in range(stop_criteria-1)\n                       if coverage_list[k]]\n            exp_rel_inc = np.mean(rel_inc)\n\n            # calculate observed statistic\n            if num_codons_obs:\n                obs_stat = graph_score / np.log2(exp_rel_inc*num_codons_obs)\n            else:\n                obs_stat = 1.0\n\n            # calculate statistics for simulated data\n            sim_stat_list = [ent / np.log2(exp_rel_inc*num_mut_list[l])\n                             for l, ent in enumerate(graph_entropy_list)]\n            null_graph_entropy_ct = len([s for s in sim_stat_list\n                                         if s-utils.epsilon <= obs_stat])\n\n        # get info about mutations\n        tmp_mut_info = mc.get_aa_mut_info(row,\n                                          somatic_base,\n                                          gene_seq)\n\n        # calculate position info\n        tmp_tuple = cutils.calc_pos_info(tmp_mut_info['Codon Pos'],\n                                         tmp_mut_info['Reference AA'],\n                                         tmp_mut_info['Somatic AA'],\n                                         pseudo_count=pseudo_count,\n                                         is_obs=0)\n        _, _, _, tmp_pos_ct = tmp_tuple\n\n        # record num of mut codons\n        if i < stop_criteria-1:\n            tmp_num_mut_codons = len(tmp_pos_ct)\n            num_mut_list.append(tmp_num_mut_codons)\n\n        # get entropy on graph-smoothed probability distribution\n        tmp_graph_entropy, tmp_coverage = scores.compute_ng_stat(gene_graph, tmp_pos_ct)\n\n        # record the \"coverage\" in the graph\n        if i < stop_criteria-1:\n            coverage_list.append(tmp_coverage)\n            graph_entropy_list.append(tmp_graph_entropy)\n\n        # update empirical null distribution counts\n        if i >= stop_criteria:\n            #if tmp_graph_entropy-utils.epsilon <= graph_score:\n            if tmp_num_mut_codons:\n                sim_stat = tmp_graph_entropy / np.log2(exp_rel_inc*tmp_num_mut_codons)\n            else:\n                sim_stat = 1.0\n\n            # add count\n            if sim_stat-utils.epsilon <= obs_stat:\n                null_graph_entropy_ct += 1\n\n        # stop iterations if reached sufficient precision\n        if null_graph_entropy_ct >= stop_criteria:\n            break\n\n    # calculate p-value from empirical null-distribution\n    protein_pval = float(null_graph_entropy_ct) / (i+1)\n\n    return protein_pval, obs_stat\n\n\ndef effect_permutation(context_counts,\n                       context_to_mut,\n                       seq_context,\n                       gene_seq,\n                       num_permutations=10000,\n                       pseudo_count=0):\n    \"\"\"Performs null-permutations for effect-based mutation statistics\n    in a single gene.\n\n    Parameters\n    ----------\n    context_counts : pd.Series\n        number of mutations for each context\n    context_to_mut : dict\n        dictionary mapping nucleotide context to a list of observed\n        somatic base changes.\n    seq_context : SequenceContext\n        Sequence context for the entire gene sequence (regardless\n        of where mutations occur). The nucleotide contexts are\n        identified at positions along the gene.\n    gene_seq : GeneSequence\n        Sequence of gene of interest\n    num_permutations : int, default: 10000\n        number of permutations to create for null\n    pseudo_count : int, default: 0\n        Pseudo-count for number of recurrent missense mutations for each\n        permutation for the null distribution. Increasing pseudo_count\n        makes the statistical test more stringent.\n\n    Returns\n    -------\n    effect_entropy_list : list\n        list of entropy of effect values under the null\n    recur_list : list\n        number of recurrent missense mutations\n    inactivating_list : list\n        number of inactivating mutations\n    \"\"\"\n    mycontexts = context_counts.index.tolist()\n    somatic_base = [base\n                    for one_context in mycontexts\n                    for base in context_to_mut[one_context]]\n\n    # get random positions determined by sequence context\n    tmp_contxt_pos = seq_context.random_pos(context_counts.iteritems(),\n                                            num_permutations)\n    tmp_mut_pos = np.hstack([pos_array for base, pos_array in tmp_contxt_pos])\n\n    # calculate position-based statistics as a result of random positions\n    effect_entropy_list, recur_list, inactivating_list = [], [], []\n    for row in tmp_mut_pos:\n        # get info about mutations\n        tmp_mut_info = mc.get_aa_mut_info(row,\n                                          somatic_base,\n                                          gene_seq)\n\n        # calculate position info\n        tmp_entropy, tmp_recur, tmp_inactivating = cutils.calc_effect_info(tmp_mut_info['Codon Pos'],\n                                                                           tmp_mut_info['Reference AA'],\n                                                                           tmp_mut_info['Somatic AA'],\n                                                                           pseudo_count=pseudo_count,\n                                                                           is_obs=0)\n        effect_entropy_list.append(tmp_entropy)\n        recur_list.append(tmp_recur)\n        inactivating_list.append(tmp_inactivating)\n\n    return effect_entropy_list, recur_list, inactivating_list\n\n\ndef non_silent_ratio_permutation(context_counts,\n                                 context_to_mut,\n                                 seq_context,\n                                 gene_seq,\n                                 num_permutations=10000):\n    \"\"\"Performs null-permutations for non-silent ratio across all genes.\n\n    Parameters\n    ----------\n    context_counts : pd.Series\n        number of mutations for each context\n    context_to_mut : dict\n        dictionary mapping nucleotide context to a list of observed\n        somatic base changes.\n    seq_context : SequenceContext\n        Sequence context for the entire gene sequence (regardless\n        of where mutations occur). The nucleotide contexts are\n        identified at positions along the gene.\n    gene_seq : GeneSequence\n        Sequence of gene of interest\n    num_permutations : int, default: 10000\n        number of permutations to create for null\n\n    Returns\n    -------\n    non_silent_count_list : list of tuples\n        list of non-silent and silent mutation counts under the null\n    \"\"\"\n    mycontexts = context_counts.index.tolist()\n    somatic_base = [base\n                    for one_context in mycontexts\n                    for base in context_to_mut[one_context]]\n\n    # get random positions determined by sequence context\n    tmp_contxt_pos = seq_context.random_pos(context_counts.iteritems(),\n                                            num_permutations)\n    tmp_mut_pos = np.hstack([pos_array for base, pos_array in tmp_contxt_pos])\n\n    # determine result of random positions\n    non_silent_count_list = []\n    for row in tmp_mut_pos:\n        # get info about mutations\n        tmp_mut_info = mc.get_aa_mut_info(row,\n                                          somatic_base,\n                                          gene_seq)\n\n        # calc deleterious mutation info\n        tmp_non_silent = cutils.calc_non_silent_info(tmp_mut_info['Reference AA'],\n                                                     tmp_mut_info['Somatic AA'],\n                                                     tmp_mut_info['Codon Pos'])\n        non_silent_count_list.append(tmp_non_silent)\n    return non_silent_count_list\n\n\ndef summary_permutation(context_counts,\n                        context_to_mut,\n                        seq_context,\n                        gene_seq,\n                        score_dir,\n                        num_permutations=10000,\n                        min_frac=0.0,\n                        min_recur=2,\n                        drop_silent=False):\n    \"\"\"Performs null-permutations and summarizes the results as features over\n    the gene.\n\n    Parameters\n    ----------\n    context_counts : pd.Series\n        number of mutations for each context\n    context_to_mut : dict\n        dictionary mapping nucleotide context to a list of observed\n        somatic base changes.\n    seq_context : SequenceContext\n        Sequence context for the entire gene sequence (regardless\n        of where mutations occur). The nucleotide contexts are\n        identified at positions along the gene.\n    gene_seq : GeneSequence\n        Sequence of gene of interest\n    num_permutations : int, default: 10000\n        number of permutations to create for null\n    drop_silent : bool, default=False\n        Flage on whether to drop all silent mutations. Some data sources\n        do not report silent mutations, and the simulations should match this.\n\n    Returns\n    -------\n    summary_info_list : list of lists\n        list of non-silent and silent mutation counts under the null along\n        with information on recurrent missense counts and missense positional\n        entropy.\n    \"\"\"\n    mycontexts = context_counts.index.tolist()\n    somatic_base = [base\n                    for one_context in mycontexts\n                    for base in context_to_mut[one_context]]\n\n    # get random positions determined by sequence context\n    tmp_contxt_pos = seq_context.random_pos(context_counts.iteritems(),\n                                            num_permutations)\n    tmp_mut_pos = np.hstack([pos_array for base, pos_array in tmp_contxt_pos])\n\n    # determine result of random positions\n    gene_name = gene_seq.bed.gene_name\n    gene_len = gene_seq.bed.cds_len\n    summary_info_list = []\n    for i, row in enumerate(tmp_mut_pos):\n        # get info about mutations\n        tmp_mut_info = mc.get_aa_mut_info(row,\n                                          somatic_base,\n                                          gene_seq)\n\n        # Get all metrics summarizing each gene\n        tmp_summary = cutils.calc_summary_info(tmp_mut_info['Reference AA'],\n                                               tmp_mut_info['Somatic AA'],\n                                               tmp_mut_info['Codon Pos'],\n                                               gene_name,\n                                               score_dir,\n                                               min_frac=min_frac,\n                                               min_recur=min_recur)\n\n        # drop silent if needed\n        if drop_silent:\n            # silent mutation count is index 1\n            tmp_summary[1] = 0\n\n        # limit the precision of floats\n        #pos_ent = tmp_summary[-1]\n        #tmp_summary[-1] = '{0:.5f}'.format(pos_ent)\n\n        summary_info_list.append([gene_name, i+1, gene_len]+tmp_summary)\n    return summary_info_list\n\n\ndef maf_permutation(context_counts,\n                    context_to_mut,\n                    seq_context,\n                    gene_seq,\n                    num_permutations=10000,\n                    drop_silent=False):\n    \"\"\"Performs null-permutations across all genes and records the results in\n    a format like a MAF file. This could be useful for examining the null\n    permutations because the alternative approaches always summarize the results.\n    With the simulated null-permutations, novel metrics can be applied to create\n    an empirical null-distribution.\n\n    Parameters\n    ----------\n    context_counts : pd.Series\n        number of mutations for each context\n    context_to_mut : dict\n        dictionary mapping nucleotide context to a list of observed\n        somatic base changes.\n    seq_context : SequenceContext\n        Sequence context for the entire gene sequence (regardless\n        of where mutations occur). The nucleotide contexts are\n        identified at positions along the gene.\n    gene_seq : GeneSequence\n        Sequence of gene of interest\n    num_permutations : int, default: 10000\n        number of permutations to create for null\n    drop_silent : bool, default=False\n        Flage on whether to drop all silent mutations. Some data sources\n        do not report silent mutations, and the simulations should match this.\n\n    Returns\n    -------\n    maf_list : list of tuples\n        list of null mutations with mutation info in a MAF like format\n    \"\"\"\n    mycontexts = context_counts.index.tolist()\n    somatic_base, base_context = zip(*[(base, one_context)\n                                       for one_context in mycontexts\n                                       for base in context_to_mut[one_context]])\n\n    # get random positions determined by sequence context\n    tmp_contxt_pos = seq_context.random_pos(context_counts.iteritems(),\n                                            num_permutations)\n    tmp_mut_pos = np.hstack([pos_array for base, pos_array in tmp_contxt_pos])\n\n    # info about gene\n    gene_name = gene_seq.bed.gene_name\n    strand = gene_seq.bed.strand\n    chrom = gene_seq.bed.chrom\n    gene_seq.bed.init_genome_coordinates()  # map seq pos to genome\n\n    # determine result of random positions\n    maf_list = []\n    for row in tmp_mut_pos:\n        # get genome coordinate\n        pos2genome = np.vectorize(lambda x: gene_seq.bed.seqpos2genome[x]+1)\n        genome_coord = pos2genome(row)\n\n        # get info about mutations\n        tmp_mut_info = mc.get_aa_mut_info(row,\n                                          somatic_base,\n                                          gene_seq)\n\n        # get string describing variant\n        var_class = cutils.get_variant_classification(tmp_mut_info['Reference AA'],\n                                                      tmp_mut_info['Somatic AA'],\n                                                      tmp_mut_info['Codon Pos'])\n\n        # prepare output\n        for k, mysomatic_base in enumerate(somatic_base):\n            # format DNA change\n            ref_nuc = tmp_mut_info['Reference Nuc'][k]\n            nuc_pos = row[k]\n            dna_change = 'c.{0}{1}>{2}'.format(ref_nuc, nuc_pos, mysomatic_base)\n\n            # format protein change\n            ref_aa = tmp_mut_info['Reference AA'][k]\n            somatic_aa = tmp_mut_info['Somatic AA'][k]\n            codon_pos = tmp_mut_info['Codon Pos'][k]\n            protein_change = 'p.{0}{1}{2}'.format(ref_aa, codon_pos, somatic_aa)\n\n            # reverse complement if on negative strand\n            if strand == '-':\n                ref_nuc = utils.rev_comp(ref_nuc)\n                mysomatic_base = utils.rev_comp(mysomatic_base)\n\n            # append results\n            if drop_silent and var_class[k].decode() == 'Silent': continue\n            maf_line = [gene_name, strand, chrom, genome_coord[k], genome_coord[k],\n                        ref_nuc, mysomatic_base, base_context[k], dna_change,\n                        protein_change, var_class[k].decode()]\n            maf_list.append(maf_line)\n\n    return maf_list\n", "meta": {"hexsha": "42e0c7ac9d4e3e967d0f72c1d968b160d4e4892a", "size": 31743, "ext": "py", "lang": "Python", "max_stars_repo_path": "prob2020/python/permutation.py", "max_stars_repo_name": "KarchinLab/probabilistic2020", "max_stars_repo_head_hexsha": "8e0b1b9578bd8189b1690dd2f17476c3305b98dc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2016-04-30T03:26:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T04:47:08.000Z", "max_issues_repo_path": "prob2020/python/permutation.py", "max_issues_repo_name": "KarchinLab/probabilistic2020", "max_issues_repo_head_hexsha": "8e0b1b9578bd8189b1690dd2f17476c3305b98dc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2016-08-18T15:19:04.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-17T18:16:52.000Z", "max_forks_repo_path": "prob2020/python/permutation.py", "max_forks_repo_name": "KarchinLab/probabilistic2020", "max_forks_repo_head_hexsha": "8e0b1b9578bd8189b1690dd2f17476c3305b98dc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-10-19T03:43:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T02:40:20.000Z", "avg_line_length": 40.5402298851, "max_line_length": 109, "alphanum_fraction": 0.5815140346, "include": true, "reason": "import numpy", "num_tokens": 6136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.35220178884745906, "lm_q1q2_score": 0.18297633893592383}}
{"text": "import textwrap\nimport warnings\nfrom functools import reduce, partial\n\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom hdxrate import k_int_from_sequence\nfrom numpy.lib.recfunctions import append_fields\nfrom scipy import constants\n\nimport pyhdx\nfrom pyhdx.alignment import align_dataframes\nfrom pyhdx.fileIO import dataframe_to_file\nfrom pyhdx.support import reduce_inter, fields_view\nfrom pyhdx.config import cfg\n\n\ndef protein_wrapper(func, *args, **kwargs):\n    metadata = kwargs.pop('metadata', {})\n    [metadata.update(arg.metadata) for arg in args if isinstance(arg, Protein)]\n\n    df_args = [arg.df if isinstance(arg, Protein) else arg for arg in args]\n    return_value = func(*df_args, **kwargs)\n    if isinstance(return_value, pd.DataFrame):\n        return Protein(return_value, **metadata)\n\n    return return_value\n\n\nclass Protein(object):\n    \"\"\"Object describing a protein\n\n    Protein objects are based on panda's DataFrame's with added functionality\n\n    Parameters\n    ----------\n    data : :class:`~numpy.ndarray` or :obj:`dict` or :class:`~pandas.DataFrame`\n        data object to initiate the protein object from\n    index : :obj:`str`, optional\n        Name of the column with the residue number (index column)\n\n    **metadata\n        Dictionary of optional metadata.\n\n\n    \"\"\"\n\n    def __init__(self, data, index=None, **metadata):\n        self.metadata = metadata\n        if isinstance(data, dict) or isinstance(data, np.ndarray):\n            self.df = pd.DataFrame(data)\n            self.df.set_index(index, inplace=True)\n        elif isinstance(data, pd.DataFrame):\n            self.df = data.copy()\n            if not self.df.index.is_integer():\n                raise ValueError(f\"Invalid index type {type(self.df.index)} for supplied DataFrame, must be integer index\")\n\n        if not self.df.index.is_unique:\n            raise ValueError(\"Protein dataframe indices must be unique\")\n\n        new_index = pd.RangeIndex(start=self.df.index.min(), stop=self.df.index.max() + 1, name='r_number')\n        self.df = self.df.reindex(new_index)\n\n    def __str__(self):\n        s = self.df.__str__()\n        try:\n            full_s = f\"Protein {self.metadata['name']}\\n\" + s\n            return full_s\n        except KeyError:\n            return s\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getattr__(self, item):\n        attr = getattr(self.df, item)\n        if callable(attr):\n            return partial(protein_wrapper, attr, metadata=self.metadata)\n        else:\n            return attr\n\n    def __getstate__(self):\n        return self.__dict__\n\n    def __setstate__(self, d):\n        self.__dict__.update(d)\n\n    def _make_protein(self, df_out, other):\n        \"\"\"Make a new :class:`~pyhdx.models.Protein` object and combine metadata with other metadata\"\"\"\n        metadata = {**self.metadata, **other.metadata}\n        protein_out = Protein(df_out, index=df_out.index.name, **metadata)\n        return protein_out\n\n    def to_file(self, file_path, include_version=True, include_metadata=True, fmt='csv', **kwargs):\n        \"\"\"\n        Write Protein data to file.\n\n\n        Parameters\n        ----------\n        file_path : :obj:`str`\n            File path to create and write to.\n        include_version : :obj:`bool`\n            Set ``True`` to include PyHDX version and current time/date\n        fmt : :obj:`str`\n            Formatting to use, options are 'csv' or 'pprint'\n        include_metadata : :obj:`bool`\n            If `True`, the objects' metadata is included\n        **kwargs : :obj:`dict`, optional\n            Optional additional keyword arguments passed to `df.to_csv`\n        Returns\n        -------\n        None\n\n        \"\"\"\n\n        metadata = self.metadata if include_metadata else include_metadata\n        dataframe_to_file(file_path, self.df, include_version=include_version, include_metadata=metadata, fmt=fmt, **kwargs)\n\n    def set_k_int(self, temperature, pH):\n        \"\"\"\n        Calculates the intrinsic rate of the sequence. Values of no coverage or prolines are assigned a value of -1\n        The rates run are for the first residue (1) up to the last residue that is covered by peptides\n\n        When the previous residue is unknown the current residue is also assigned a value of -1.g\n\n        Parameters\n        ----------\n        temperature : :obj:`float`\n            Temperature of the labelling reaction (Kelvin)\n        pH : :obj:`float`\n            pH of the labelling reaction\n\n        Returns\n        -------\n\n        k_int : :class:`~numpy.ndarray`\n            Array of intrisic exchange rates\n\n        \"\"\"\n\n        if 'sequence' not in self:\n            raise ValueError('No sequence data available to calculate intrinsic exchange rates.')\n\n        sequence = list(self['sequence'])  # Includes 'X' padding at cterm if cterm > last peptide\n        k_int = k_int_from_sequence(sequence, temperature, pH)\n\n        self.df['k_int'] = k_int\n        return np.array(k_int)\n\n    @property\n    def c_term(self):\n        return self.df.index.max()\n\n    @property\n    def n_term(self):\n        return self.df.index.min()\n\n    def __getitem__(self, item):\n        return self.df.__getitem__(item)\n\n    def __setitem__(self, index, value):\n        self.df.__setitem__(index, value)\n\n    def __contains__(self, item):\n        return self.df.__contains__(item)\n\n    def __sub__(self, other):\n        return protein_wrapper(self.df.subtract, other, metadata=self.metadata)\n\n    def __add__(self, other):\n        return protein_wrapper(self.df.add, other, metadata=self.metadata)\n\n    def __truediv__(self, other):\n        return protein_wrapper(self.df.truediv, other, metadata=self.metadata)\n\n    def __floordiv__(self, other):\n        return protein_wrapper(self.df.floordiv, other, metadata=self.metadata)\n\n    def __mul__(self, other):\n        return protein_wrapper(self.df.mul, other, metadata=self.metadata)\n\n\nclass PeptideMasterTable(object):\n    \"\"\"\n    Main peptide input object. The input pandas DataFrame `data` must have the following entires for each peptide:\n\n    start: Residue number of the first amino acid in the peptide\n    end: Residue number of the last amino acid in the peptide (inclusive)\n    sequence: Amino acid sequence of the peptide (one letter code)\n    exposure: Typically the time the sample was exposed to a deuterated solution. This can correspond to other times if\n        the kinetics of the experiment are set up differently\n    state: String describing to which state (experimental conditions) the peptide belongs\n    uptake: Number of deuteriums the peptide has taken up\n\n    The following fields are added to the `data` array upon initialization:\n\n    _start: Unmodified copy of initial start field\n    _end: Unmodified copy of initial end field\n    _sequence: Unmodified copy of initial sequence\n    ex_residues: Number of residues that undergo deuterium exchange. This number is calculated using the `drop_first` and\n        `ignore_prolines` parameters\n\n    N-terminal residues which are removed because they are either within `drop_first` or they are N-terminal prolines are\n    marked with 'x' in the `sequence` field. Prolines which are removed because they are in the middle of a peptide are\n    marked with a lower case 'p' in the sequence field.\n\n    The field `scores` is used in calculating exchange rates and can be set by either the `set_backexchange` or\n    `set_control` methods.\n\n\n    Parameters\n    ----------\n    data : :class:`~pandas.DataFrame`\n        Pandas DataFrame with peptide entries.\n    drop_first : :obj:`int`\n        Number of N-terminal amino acids to ignore. Default is 1.\n    d_percentage : :obj:`float`\n        Percentage of deuterium in the labelling solution.\n    ignore_prolines : :obj:`bool`\n        Boolean to toggle ignoring of proline residues. When True these residues are treated as if they're not present\n        in the protein.\n    sort : :obj:`bool`\n        Set to ``True`` to sort the input. Sort order is 'start', 'end', 'sequence', 'exposure', 'state'.\n    remove_nan : :obj:`bool`\n        Set to ``True`` to remove NaN entries in uptake\n\n    \"\"\"\n\n    def __init__(self, data, drop_first=1, ignore_prolines=True, d_percentage=100., sort=True, remove_nan=True):\n        assert np.all(data['start'] < data['end']), 'All `start` entries must be smaller than their `end` entries'\n        assert 0 <= d_percentage <= 100., 'Deuteration percentage must be between 0 and 100'\n        d_percentage /= 100.\n\n        self.data = data.copy().reset_index(drop=True)\n        self.data.index.name = 'peptide_index'\n\n        if remove_nan:\n            self.data = self.data.dropna(subset=['uptake'])\n        if sort:\n            self.data = self.data.sort_values(['start', 'end', 'sequence', 'state', 'exposure'])\n\n        for col in ['start', 'end', 'sequence']:\n            target = '_' + col\n            if target in self.data:\n                continue\n            else:\n                self.data[target] = self.data[col]\n\n        # Convert sequence to upper case if not so already\n        self.data['sequence'] = self.data['sequence'].str.upper()\n        # Mark ignored prolines with lower case letters\n        if ignore_prolines:\n            self.data['sequence'] = [s.replace('P', 'p') for s in self.data['sequence']]\n\n        # Find the total number of n terminal / c_terminal residues to remove\n        # Todo: edge cases such as pure prolines or overlap between c terminal prolines and drop_first section (issue 32)\n        n_term = np.array([len(seq) - len(seq[drop_first:].lstrip('p')) for seq in self.data['sequence']])\n        c_term = np.array([len(seq) - len(seq.rstrip('p')) for seq in self.data['sequence']])\n\n        # Mark removed n terminal residues with lower case x\n        self.data['sequence'] = ['x'*nt + s[nt:] for nt, s in zip(n_term, self.data['sequence'])]\n        self.data['start'] += n_term\n        self.data['end'] -= c_term\n\n        ex_residues = np.array([len(s) - s.count('x') - s.count('p') for s in self.data['sequence']]) * d_percentage\n        if 'ex_residues' not in self.data:\n            self.data['ex_residues'] = ex_residues\n\n    def __len__(self):\n        return self.data.shape[0]\n\n    def get_state(self, state):\n        \"\"\"\n        Returns entries in the table with state 'state'\n        Rows with NaN entries for 'uptake_corrected' are removed\n\n        Parameters\n        ----------\n        state : :obj:`str`\n\n\n        Returns\n        -------\n\n        \"\"\"\n\n        if not isinstance(state, str):\n            raise TypeError(f'State must be type `str`, got {type(state)}')\n        data = self.data.query(f'state == \"{state}\"').copy()\n        if 'uptake_corrected' in data.columns:\n            data.dropna(subset=['uptake_corrected'], inplace=True)\n\n        return data\n\n    def set_backexchange(self, back_exchange):\n        \"\"\"\n        Sets the normalized percentage of uptake through a fixed backexchange value for all peptides.\n\n        Parameters\n        ----------\n        back_exchange :  :obj:`float`\n            Percentage of back exchange\n\n        \"\"\"\n\n        back_exchange /= 100\n        rfu = self.data['uptake'] / ((1-back_exchange)*self.data['ex_residues'])\n\n        uptake_corrected = self.data['uptake'] / (1 - back_exchange)\n\n        self.data = append_fields(self.data, ['rfu', 'uptake_corrected'], data=[rfu, uptake_corrected], usemask=False)\n\n    def set_control(self, control_1, control_0=None):\n        \"\"\"\n        Apply a control dataset to this object. The column 'RFU' is added to the object by normalizing its uptake\n        value with respect to the control uptake value to one.\n        Optionally, ``control_zero`` can be specified which is a dataset whose uptake value will be used to zero\n        the uptake.\n\n        Nonmatching peptides are set to NaN\n\n        #todo insert math\n\n        Parameters\n        ----------\n        control_1 : :obj:`tuple`\n            tuple with (`state`, `exposure`) for peptides to use for normalization (FD control)\n        control_0 : :obj:`tuple`, optional\n            tuple with (`state`, `exposure`) for peptides to use for zeroing uptake values (ND control)\n\n        \"\"\"\n\n        try:\n            fd_df = self.get_data(*control_1)[['start', 'end', 'uptake']].set_index(['start', 'end'], verify_integrity=True)\n        except ValueError as e:\n            raise ValueError(\"FD control has duplicate entries\") from e\n\n        if fd_df.size == 0:\n            raise ValueError(f'No matching peptides with state {control_1[0]} and exposure {control_1[1]}')\n\n        try:\n            if control_0 is None:\n                nd_df = self.get_data(*control_1).copy()[['start', 'end', 'uptake']].set_index(['start', 'end'], verify_integrity=True)\n                nd_df['uptake'] = 0\n\n            else:\n                nd_df = self.get_data(*control_0)[['start', 'end', 'uptake']].set_index(['start', 'end'], verify_integrity=True)\n                if nd_df.size == 0:\n                    raise ValueError(f'No matching peptides with state {control_0[0]} and exposure {control_0[1]}')\n        except ValueError as e:\n            raise ValueError(\"ND control has duplicate entries\") from e\n\n        self.data.set_index(['start', 'end'], append=True, inplace=True)\n        self.data.reset_index(level=0, inplace=True)\n\n        self.data['rfu'] = (self.data['uptake'] - nd_df['uptake']) / (fd_df['uptake'] - nd_df['uptake'])\n        self.data['uptake_corrected'] = self.data['rfu'] * self.data['ex_residues']\n\n        self.data = self.data.set_index('peptide_index', append=True).reset_index(level=[0, 1])\n\n    def select(self, **kwargs):\n        \"\"\"\n        Select data based on column values.\n\n        Parameters\n        ----------\n        kwargs: :obj:`dict`\n            Column name, value pairs to select\n\n        Returns\n        -------\n        output_data : :class:`~pandas.DataFrame`\n            DataFrame with selected peptides\n\n        \"\"\"\n        masks = [self.data[k] == v for k, v in kwargs.items()]\n        m = np.logical_and.reduce(masks)\n\n        return self.data[m]\n\n    def get_data(self, state, exposure):\n        \"\"\"\n        Get all peptides matching `state` and `exposure`.\n\n        Parameters\n        ----------\n        state : :obj:`str`\n            Measurement state\n        exposure : :obj:`float`\n            Measurement exposure time\n\n        Returns\n        -------\n        output_data : :class:`~pandas.DataFrame`\n            DataFrame with selected peptides\n        \"\"\"\n\n        return self.select(state=state, exposure=exposure)\n\n    @property\n    def states(self):\n        \"\"\":class:`~numpy.ndarray` Array with unique states\"\"\"\n        return np.unique(self.data['state'])\n\n    @property\n    def exposures(self):\n        \"\"\":class:`~numpy.ndarray` Array with unique exposures\"\"\"\n        return np.unique(self.data['exposure'])\n\n\nclass Coverage(object):\n    \"\"\"\n    Object describing layout and coverage of peptides and generating the corresponding matrices. Peptides should all\n    belong to the same state and have the same exposure time.\n\n    Parameters\n    ----------\n    data : :class:`~pandas.DataFrame`\n        DataFrame with input peptides\n    c_term : :obj:`int`\n        Residue index number of the C-terminal residue (where first residue in index number 1)\n    n_term : :obj:`int`\n        Residue index of the N-terminal residue. Default value is 1, can be negative to accomodate for N-terminal\n        purification tags\n    sequence : :obj:`str`\n        Amino acid sequence of the protein in one-letter FASTA encoding. Optional, if not specified the amino acid sequence\n        from the peptide data is used to (partially) reconstruct the sequence. Supplied amino acid sequence must be\n        compatible with sequence information in the peptides.\n\n    Attributes\n    ----------\n\n    X : :class:`~numpy.ndarray`\n        N x M matrix where N is the number of peptides and M equal to `prot_len`.\n        Values are 1/(ex_residues) where there is coverage.\n    Z : :class:`~numpy.ndarray`\n        N x M matrix where N is the number of peptides and M equal to `prot_len`.\n        Values are 1/(ex_residues) where there is coverage,\n        #todo account for prolines: so that rows sum to 1 is currently not true\n\n    \"\"\"\n\n    def __init__(self, data, c_term=0, n_term=1, sequence=''):\n        assert len(np.unique(data['exposure'])) == 1, 'Exposure entries are not unique'\n        assert len(np.unique(data['state'])) == 1, 'State entries are not unique'\n        self.data = data.sort_values(['start', 'end'], axis=0)\n\n        start = self.data['_start'].min()\n        end = self.data['_end'].max()\n\n        if n_term:\n            start = min(start, n_term)\n        if sequence and not c_term:\n            c_term = len(sequence) + n_term - 1\n        if c_term:\n            if c_term + 1 < end:\n                raise ValueError(\"HDX data extends beyond c_term number, check 'sequence' or 'c_term'\")\n            end = c_term + 1  # c_term is inclusive, therefore plus one\n\n        r_number = pd.RangeIndex(start, end, name='r_number')  # r_number spanning the full protein range, not just the covered range\n        # Full sequence\n        _seq = pd.Series(index=r_number, dtype='U').fillna('X')  # Full sequence\n        # Sequence with lower case letters for no coverage due to n_terminal residues or prolines\n        seq = pd.Series(index=r_number, dtype='U').fillna('X')\n        for idx in self.data.index[::-1]:\n            start, end = self.data.loc[idx, '_start'], self.data.loc[idx, '_end']\n\n            _seq.loc[start: end-1] = list(self.data.loc[idx, '_sequence'])\n            seq.loc[start: end-1] = list(self.data.loc[idx, 'sequence'])# = list(d['sequence'])\n\n        if sequence:\n            for r, s1, s2 in zip(r_number, sequence, _seq):\n                if s2 != 'X' and s1 != s2:\n                    raise ValueError(\n                        f\"Mismatch in supplied sequence and peptides sequence at residue {r}, expected '{s2}', got '{s1}'\")\n            if len(sequence) != len(_seq):\n                raise ValueError(\"Invalid length of supplied sequence. Please check 'n_term' and 'c_term' parameters\")\n            _seq = list(sequence)\n\n        #todo check if this is always correctly determined (n terminal residues usw)\n        exchanges = [s.isupper() and (s != 'X') for s in seq]  # Boolean array True if residue exchanges, full length\n        coverage = seq != 'X'  # Boolean array for coverage\n        protein_df = pd.DataFrame({'sequence': _seq, 'coverage': coverage, 'exchanges': exchanges}, index=r_number)\n\n        # Inclusive, exclusive interval of peptides coverage across the whole protein\n        self.interval = (np.min(self.data['start']), np.max(self.data['end']))\n        self.protein = Protein(protein_df, index='r_number')\n\n        # matrix dimensions N_peptides N_residues, dtype for TF compatibility\n        _exchanges = self['exchanges']  # Array only on covered part\n        self.X = np.zeros((len(self.data), self.interval[1] - self.interval[0]), dtype=int)\n        self.Z = np.zeros_like(self.X, dtype=float)\n        for row, idx in enumerate(self.data.index):\n            start, end = self.data.loc[idx, 'start'], self.data.loc[idx, 'end']\n            i0, i1 = self.r_number.get_loc(start), self.r_number.get_loc(end - 1)\n            #i0, i1 = np.searchsorted(self.r_number, (entry['start'], entry['end']))\n            self.X[row][i0:i1+1] = 1\n            self.Z[row][i0:i1+1] = _exchanges[i0:i1+1]\n        self.Z = self.Z / self.data['ex_residues'].to_numpy()[:, np.newaxis]\n\n    def __len__(self):\n        return len(self.data)\n\n    def __getitem__(self, item):\n        pd_series = self.protein[item]\n        return self.apply_interval(pd_series)\n\n    def apply_interval(self, array_or_series):\n        \"\"\"\n        Given a Numpy array or Pandas series with a length equal to the full protein, returns the section of the array equal to the covered\n        region. Returned series length is equal to number of columns in the X matrix\n\n        Parameters\n        ----------\n        np.narray or pd.series\n\n        \"\"\"\n\n        if isinstance(array_or_series, np.ndarray):\n            series = pd.Series(array_or_series, index=self.protein.df.index)\n            assert len(array_or_series) == len(self.protein)\n        else:\n            series = array_or_series\n\n        # - 1 because interval is inclusive, exclusive and .loc slices inclusive, inclusive\n        covered_slice = series.loc[self.interval[0]:self.interval[1] - 1]\n\n        return covered_slice\n\n    @property\n    def percent_coverage(self):\n        \"\"\":obj:`float`: Percentage of residues covered by peptides\"\"\"\n        return 100*np.mean(self.protein['coverage'])\n\n    @property\n    def redundancy(self):\n        \"\"\":obj:`float`: Average redundancy of peptides in regions with at least 1 peptide\"\"\"\n        x_coverage = self.X[:, self['coverage']]\n        return np.mean(np.sum(x_coverage, axis=0))\n\n    @property\n    def Np(self):\n        \"\"\":obj:`int`: Number of peptides.\"\"\"\n        return self.X.shape[0]\n\n    @property\n    def Nr(self):\n        \"\"\":obj:`int`: Total number of residues spanned by the peptides.\"\"\"\n\n        return self.X.shape[1]\n\n    @property\n    def r_number(self):\n        \"\"\":class:`~pandas.RangeIndex`: Pandas index numbers corresponding to the part of the protein covered by peptides\"\"\"\n\n        return pd.RangeIndex(self.interval[0], self.interval[1], name='r_number')\n\n    @property\n    def index(self):\n        \"\"\":class:`~pandas.RangeIndex`: Pandas index numbers corresponding to the part of the protein covered by peptides\"\"\"\n        return self.r_number\n\n    @property\n    def block_length(self):\n        \"\"\":class:`~numpy.ndarary`: Lengths of unique blocks of residues in the peptides map,\n            along the `r_number` axis\"\"\"\n\n        # indices are start and stop values of blocks\n        indices = np.sort(np.concatenate([self.data['start'], self.data['end']]))\n        #indices of insertion into r_number vector gives us blocks with taking prolines into account.\n        diffs = np.diff(np.searchsorted(self.r_number, indices))\n\n        block_length = diffs[diffs != 0]\n        return block_length\n\n    @property\n    def X_norm(self):\n        \"\"\":class:`~numpy.ndarray`: `X` coefficient matrix normalized column wise.\"\"\"\n        return self.X / np.sum(self.X, axis=0)[np.newaxis, :]\n\n    @property\n    def Z_norm(self):\n        \"\"\":class:`~numpy.ndarray`: `Z` coefficient matrix normalized column wise.\"\"\"\n        with warnings.catch_warnings():\n            warnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n            z_norm = self.Z / np.sum(self.Z, axis=0)[np.newaxis, :]\n        return z_norm\n\n    def get_sections(self, gap_size=-1):\n        \"\"\"Get the intervals of independent sections of coverage.\n\n        Intervals are inclusive, exclusive.\n        Gaps are defined with `gap_size`, adjacent peptides with distances bigger than this value are considered not to\n        overlap. Set to -1 to treat touching peptides as belonging to the same section.\n\n        Parameters\n        ----------\n        gap_size : :obj:`int`\n            The size which defines a gap\n\n        \"\"\"\n        intervals = [(s, e) for s, e in zip(self.data['start'], self.data['end'])]\n        sections = reduce_inter(intervals, gap_size=gap_size)\n\n        return sections\n\n    def __eq__(self, other):\n        \"\"\"Coverage objects are considered equal if both objects fully match between their start, end and sequence fields\"\"\"\n        assert isinstance(other, Coverage), \"Other must be an instance of Coverage\"\n        return len(self.data) == len(other.data) and np.all(self.data['start'] == other.data['start']) and \\\n               np.all(self.data['end'] == other.data['end']) and np.all(self.data['sequence'] == other.data['sequence'])\n\n\nclass HDXMeasurement(object):\n    \"\"\"\n    Main HDX data object. This object has peptide data of a single state but with multiple timepoints.\n\n    Timepoint data is split into :class:`~pyhdx.models.PeptideMeasurements` objects for each timepoint\n    Supplied data is made 'uniform' such that all timepoints have the same peptides\n\n    Parameters\n    ----------\n    data : :class:`~pandas.DataFrame`\n        Pandas dataframe with all peptides belonging to a single state.\n    **metadata\n        Dictionary of optional metadata. By default, holds the `temperature` and `pH` parameters.\n\n\n    Attributes\n    ----------\n    data: :class:`~pandas.DataFrame`\n        Pandas dataframe with all peptides\n    state : :obj:`str`\n        State of the HDX measurement\n    timepoints : :class:`~numpy.ndarray`\n        Array with exposure times (sorted)\n    peptides : :obj:`list`\n        List of :class:`~pyhdx.models.PeptideMeasurements`, one list element per timepoint.\n    coverage : :class:`~pyhdx.models.Coverage`\n        Coverage object describing peptide layout.\n\n    \"\"\"\n    def __init__(self, data, **metadata):\n        self.metadata = metadata\n        assert len(data['state'].unique()) == 1\n        self.state = str(data['state'].iloc[0])\n        self.timepoints = np.sort(np.unique(data['exposure']))\n\n        # Obtain the intersection of peptides per timepoint\n        data_list = [(data[data['exposure'] == exposure]).set_index(['_start', '_end']) for exposure in self.timepoints]\n        index_intersection = reduce(pd.Index.intersection, [d.index for d in data_list])\n        intersected_data = [df.loc[index_intersection].reset_index() for df in data_list]\n\n        cov_kwargs = {kwarg: metadata.get(kwarg, default) for kwarg, default in zip(['c_term', 'n_term', 'sequence'], [0, 1, ''])}\n\n        self.peptides = [HDXTimepoint(df, **cov_kwargs) for df in intersected_data]\n\n        # Create coverage object from the first time point (as all are now equal)\n        self.coverage = Coverage(intersected_data[0], **cov_kwargs)\n\n        if self.temperature and self.pH:\n            self.coverage.protein.set_k_int(self.temperature, self.pH)\n\n        self.data = pd.concat(intersected_data, axis=0, ignore_index=True)\n        self.data.index.name = 'peptide_index'\n\n    def __str__(self):\n        \"\"\"\n        String representation of HDX measurement object.\n\n        Returns\n        -------\n        s : `obj`:str:\n            Multiline string describing this HDX Measurement object\n\n        \"\"\"\n\n        timepoints = ', '.join([f'{t:.2f}' for t in self.timepoints])\n\n        s = f\"\"\"\n        HDX Measurement: {self.name}\n        \n        Number of peptides:     {self.Np}\n        Number of residues:     {self.Nr} ({self.coverage.interval[0]} - {self.coverage.interval[1]})\n        Number of timepoints:   {self.Nt}\n        Timepoints:             {timepoints} seconds\n        Coverage Percentage:    {self.coverage.percent_coverage:.2f}\n        Average redundancy:     {self.coverage.redundancy:.2f}      \n        Temperature:            {self.temperature} K\n        pH:                     {self.pH}             \n        \"\"\"\n\n        return textwrap.dedent(s.lstrip('\\n'))\n\n    def _repr_markdown_(self):\n        s = str(self)\n        s = s.replace('\\n', '<br>')\n        return s\n\n    @property\n    def name(self):\n        \"\"\":obj:`str`: HDX Measurement name\"\"\"\n        return self.metadata.get('name', self.state)\n\n    @property\n    def temperature(self):\n        \"\"\":obj:`float`: Temperature of the H/D exchagne reaction (K).\"\"\"\n        return self.metadata.get('temperature', None)\n\n    @property\n    def pH(self):\n        \"\"\"pH of the H/D exchange reaction.\"\"\"\n        return self.metadata.get('pH', None)\n\n    @property\n    def Np(self):\n        \"\"\":obj:`int`: Number of peptides.\"\"\"\n        return self.coverage.Np\n\n    @property\n    def Nr(self):\n        \"\"\":obj:`int`: Total number of residues spanned by the peptides.\"\"\"\n        return self.coverage.Nr\n\n    @property\n    def Nt(self):\n        \"\"\":obj:`int`: Number of timepoints.\"\"\"\n        return len(self.timepoints)\n\n    def __len__(self):\n        import warnings\n        warnings.warn('Use hdxm.Nt instead', DeprecationWarning)\n        return len(self.timepoints)\n\n    def __iter__(self):\n        return self.peptides.__iter__()\n\n    def __getitem__(self, item):\n        return self.peptides.__getitem__(item)\n\n    @property\n    def rfu_residues(self):\n        \"\"\":class:`~pandas.DataFrame`: Relative fractional uptake per residue. Shape Nr x Nt\"\"\"\n        df = pd.concat([v.rfu_residues for v in self], keys=self.timepoints, axis=1)\n        df.columns.name = 'exposure'\n\n        return df\n\n    @property\n    def rfu_peptides(self):\n        \"\"\":class:`~pandas.DataFrame`: Relative fractional uptake per peptide. Shape Np x Nt\"\"\"\n        df = pd.concat([v.rfu_peptides for v in self], keys=self.timepoints, axis=1)\n        df.columns.name = 'exposure'\n        return df\n\n    @property\n    def d_exp(self):\n        \"\"\":class:`~pandas.DataFrame`: D-uptake values (corrected). Shape Np x Nt\"\"\"\n        df = pd.concat([v.d_exp for v in self], keys=self.timepoints, axis=1)\n        df.columns.name = 'exposure'\n        return df\n\n    def get_tensors(self, exchanges=False, dtype=None):\n        \"\"\"\n        Returns a dictionary of tensor variables for fitting to Linderstrøm-Lang kinetics.\n\n        Tensor variables are (shape):\n        Temperature (1 x 1)\n        X (Np x Nr)\n        k_int (Nr x 1)\n        timepoints (1 x Nt)\n        d_exp (D) (Np x Nt)\n\n        Parameters\n        ----------\n        exchanges : :obj:`bool`\n            If True only returns tensor data describing residues which exchange (ie have peptides and are not prolines)\n\n        Returns\n        -------\n\n        tensors : :obj:`dict`\n\n        \"\"\"\n\n        if 'k_int' not in self.coverage.protein:\n            raise ValueError(\"Unknown intrinsic rates of exchange, please supply pH and temperature parameters\")\n        try:\n            d_exp = self.d_exp\n        except ValueError:\n            raise ValueError(\"HDX data is not corrected for back exchange.\")\n\n        if exchanges:\n            #this could be a method on coverage object similar to apply_interval; select exchanging\n            bools = self.coverage['exchanges'].to_numpy()\n        else:\n            bools = np.ones(self.Nr, dtype=bool)\n\n        dtype = dtype or cfg.TORCH_DTYPE\n        device = cfg.TORCH_DEVICE\n\n        tensors = {\n            'temperature': torch.tensor([self.temperature], dtype=dtype, device=device).unsqueeze(-1),\n            'X': torch.tensor(self.coverage.X[:, bools], dtype=dtype, device=device),\n            'k_int': torch.tensor(self.coverage['k_int'].to_numpy()[bools], dtype=dtype, device=device).unsqueeze(-1),\n            'timepoints': torch.tensor(self.timepoints, dtype=dtype, device=device).unsqueeze(0),\n            'd_exp': torch.tensor(self.d_exp.to_numpy(), dtype=dtype, device=device)}\n\n        return tensors\n\n    def guess_deltaG(self, rates, crop=True):\n        \"\"\"\n        Obtain ΔG initial guesses from apparent H/D exchange rates.\n        Units of input rates are per second.\n\n        Parameters\n        ----------\n        rates : :class:`~pandas.Series`\n           Apparent exchange rate rates. Series index is protein residue number\n        crop : :obj:`bool`\n            If `True` the resulting :class:`~pandas.Series` is cropped to the residue interval covered by peptides.\n\n        Returns\n        -------\n        deltaG : :class:`~pandas.Series`\n            ΔG guess values\n\n        \"\"\"\n        if 'k_int' not in self.coverage.protein:\n            raise ValueError(\"Unknown intrinsic rates of exchange, please supply pH and temperature parameters\")\n        if not isinstance(rates, pd.Series):\n            raise TypeError(\"Rates input type is pandas.Series\")\n\n        p_guess = (self.coverage.protein['k_int'] / rates) - 1\n\n        p_guess.clip(0., None, inplace=True)  # Some initial guesses might have negative PF values\n        with np.errstate(divide='ignore'):\n            deltaG = np.log(p_guess) * constants.R * self.temperature\n\n        # https://stackoverflow.com/questions/9537543/replace-nans-in-numpy-array-with-closest-non-nan-value\n        bools = ~np.isfinite(deltaG)\n        deltaG[bools] = np.interp(np.flatnonzero(bools), np.flatnonzero(~bools), deltaG[~bools])\n\n        if crop:\n            return self.coverage.apply_interval(deltaG)\n        else:\n            return deltaG\n\n    def to_file(self, file_path, include_version=True, include_metadata=True, fmt='csv', **kwargs):\n        \"\"\"\n        Write the data in this HDX measurement to file.\n\n        Parameters\n        ----------\n        file_path : :obj:`str`\n            File path to create and write to.\n        include_version : :obj:`bool`\n            Set `True` to include PyHDX version and current time/date\n        fmt: :obj: `str`\n            Formatting to use, options are 'csv' or 'pprint'\n        include_metadata : :obj:`bool`\n            If `True`, the objects' metadata is included\n        **kwargs : :obj:`dict`, optional\n            Optional additional keyword arguments passed to `df.to_csv`\n        Returns\n        -------\n        None\n\n        \"\"\"\n\n        # requires testing dont think this works as intended\n        # should use self.metadata if include_metadata is the bool True otherwise if its a dict use that\n        metadata = self.metadata if include_metadata else include_metadata\n        df = self.data\n        dataframe_to_file(file_path, df, include_version=include_version, include_metadata=metadata, fmt=fmt, **kwargs)\n\n\nclass HDXTimepoint(Coverage):\n    \"\"\"\n    Class with subset of peptides corresponding to only one state and exposure\n\n    Parameters\n    ----------\n    data : :class:`~pandas.DataFrame`\n        Numpy structured array with input data\n\n    \"\"\"\n\n    def __init__(self, data, **kwargs):\n        assert len(np.unique(data['exposure'])) == 1, 'Exposure entries are not unique'\n        assert len(np.unique(data['state'])) == 1, 'State entries are not unique'\n\n        super(HDXTimepoint, self).__init__(data, **kwargs)\n\n        self.state = self.data['state'][0]\n        self.exposure = self.data['exposure'][0]\n\n    @property\n    def rfu_peptides(self):\n        \"\"\":class:`~pandas.Series`: Relative fractional uptake per peptide\"\"\"\n        return self.data['rfu']\n\n    @property\n    def d_exp(self):\n        \"\"\":class:`~pandas.Series`: Experimentally measured D-values (corrected)\"\"\"\n        return self.data['uptake_corrected']\n\n    @property\n    def name(self):\n        \"\"\":obj:`str`: Name of this peptidemeasurement\"\"\"\n        return self.state + '_' + str(self.exposure)\n\n    @property\n    def rfu_residues(self):\n        \"\"\":class:`~pandas.Series`: Relative fractional uptake (RFU) per residue. Obtained by weighted averaging\"\"\"\n        return self.weighted_average('rfu')\n\n    def calc_rfu(self, residue_rfu):\n        \"\"\"\n        Calculates RFU per peptide given an array of individual residue scores\n\n        Parameters\n        ----------\n        residue_rfu : :class:`~numpy.ndarray`\n            Array of rfu per residue of length `prot_len`\n\n        Returns\n        -------\n\n        rfu : :class:`~numpy.ndarray`\n            Array of rfu per peptide\n        \"\"\"\n\n        rfu = self.Z.dot(residue_rfu)\n        return rfu\n\n    def weighted_average(self, field):\n        \"\"\"\n        Calculate per-residue weighted average of values in data column\n\n        Parameters\n        ----------\n        field : :obj:`str`\n            Data field (column) to calculated weighted average of\n\n        Returns\n        -------\n\n\n        \"\"\"\n\n        array = self.Z_norm.T.dot(self.data[field])\n        series = pd.Series(array, index=self.index)\n        return series\n\n\nclass CoverageSet(object):\n    #todo perhaps this object should have X\n    def __init__(self, hdxm_list):\n        self.hdxm_list = hdxm_list\n\n        #todo create Coverage object for the 3d case\n        intervals = np.array([hdxm_list.coverage.interval for hdxm_list in self.hdxm_list])\n        self.interval = (intervals[:, 0].min(), intervals[:, 1].max())\n        self.r_number = np.arange(*self.interval)\n\n        self.Ns = len(self.hdxm_list)\n        self.Nr = len(self.r_number)\n        self.Np = np.max([hdxm.Np for hdxm in self.hdxm_list])\n        self.Nt = np.max([hdxm.Nt for hdxm in self.hdxm_list])\n\n    @property\n    def index(self):\n        \"\"\"pd index: \"\"\"\n        return pd.RangeIndex(self.interval[0], self.interval[1], name='r_number')\n\n    def apply_interval(self, array_or_series):\n        \"\"\"Given a Numpy array or Pandas series with a length equal to the full protein, returns the section of the array equal to the covered\n        region. Returned series length is equal to number of columns in the X matrix\n\n        \"\"\"\n        #todo testing and 2d array support\n        if isinstance(array_or_series, np.ndarray):\n            series = pd.Series(array_or_series, index=self.index)\n            assert len(array_or_series) == len(self.index)\n        else:\n            series = array_or_series\n\n        # - 1 because interval is inclusive, exclusive and .loc slices inclusive, inclusive\n        covered_slice = series.loc[self.interval[0]:self.interval[1] - 1]\n\n        return covered_slice\n\n    @property\n    def s_r_mask(self):\n        \"\"\"mask of shape NsxNr with True entries covered by hdx measurements (exluding gaps)\"\"\"\n        mask = np.zeros((self.Ns, self.Nr), dtype=bool)\n        for i, hdxm in enumerate(self.hdxm_list):\n            interval_sample = hdxm.coverage.interval\n            i0 = interval_sample[0] - self.interval[0]\n            i1 = interval_sample[1] - self.interval[0]\n\n            mask[i, i0:i1] = True\n\n        return mask\n\n    def get_masks(self):\n        \"\"\"mask of shape NsxNr with True entries covered by hdx measurements (exluding gaps)\"\"\"\n        sr_mask = np.zeros((self.Ns, self.Nr), dtype=bool)\n        st_mask = np.zeros((self.Ns, self.Nt), dtype=bool)\n        spr_mask = np.zeros((self.Ns, self.Np, self.Nr), dtype=bool)\n        spt_mask = np.zeros((self.Ns, self.Np, self.Nt), dtype=bool)\n        for i, hdxm in enumerate(self.hdxm_list):\n            interval_sample = hdxm.coverage.interval\n            i0 = interval_sample[0] - self.interval[0]\n            i1 = interval_sample[1] - self.interval[0]\n\n            sr_mask[i, i0:i1] = True\n            st_mask[i, -hdxm.Nt:] = True\n            spr_mask[i, 0: hdxm.Np, i0:i1] = True\n            spt_mask[i, 0: hdxm.Np, -hdxm.Nt:] = True\n\n        mask_dict = {'sr': sr_mask, 'st': st_mask, 'spr': spr_mask, 'spt': spt_mask}\n\n        return mask_dict\n\n\nclass HDXMeasurementSet(object):\n    \"\"\"\n    Set of multiple :class:`~pyhdx.models.HDXMeasurement`\n\n    Parameters\n    ----------\n    hdxm_list :  :obj:`list`\n        or list of :class:`~pyhdx.models.HDXMeasurement`\n\n    Attributes\n    ----------\n    timepoints : :class:`~numpy.ndarray`\n        Ns x Nt array of zero-padded timepoints\n    d_exp : :class:`~numpy.ndarray`\n        Ns x Np x Nt array with zero-padded measured D-uptake values\n    \"\"\"\n\n    def __init__(self, hdxm_list):\n        self.hdxm_list = hdxm_list\n\n        self.coverage = CoverageSet(hdxm_list)\n        self.masks = self.coverage.get_masks()\n\n        timepoints_values = np.concatenate([hdxm.timepoints for hdxm in self.hdxm_list])\n        self.timepoints = np.zeros((self.Ns, self.Nt))\n        self.timepoints[self.masks['st']] = timepoints_values\n\n        d_values = np.concatenate([hdxm.d_exp.to_numpy().flatten() for hdxm in self.hdxm_list])\n        self.d_exp = np.zeros((self.Ns, self.Np, self.Nt))\n        self.d_exp[self.masks['spt']] = d_values\n\n        # Index array of of shape Ns x y where indices apply to deltaG return aligned residues for\n        self.aligned_indices = None\n        self.aligned_dataframes = None\n\n    def __iter__(self):\n        return self.hdxm_list.__iter__()\n\n    @property\n    def Ns(self):\n        return len(self.hdxm_list)\n\n    @property\n    def Nr(self):\n        return self.coverage.Nr\n\n    @property\n    def Np(self):\n        return np.max([hdxm.Np for hdxm in self.hdxm_list])\n\n    @property\n    def Nt(self):\n        return np.max([hdxm.Nt for hdxm in self.hdxm_list])\n\n    @property\n    def temperature(self):\n        return np.array([hdxm.temperature for hdxm in self.hdxm_list])\n\n    @property\n    def names(self):\n        return [hdxm.name for hdxm in self.hdxm_list]\n\n    def guess_deltaG(self, rates_list):\n        \"\"\"\n        Create deltaG guesses from rates\n\n        Parameters\n        ----------\n        rates_list : :obj:`iterable`\n            list of pandas series with k_obs estimates\n\n        Returns\n        -------\n\n        deltaG_array: :class:`~numpy.ndarray`\n            ΔG guess values\n\n        \"\"\"\n\n        #todo pandify this?\n        assert len(rates_list) == self.Ns, \"Number of elements in 'rates_list' should be equal to number of samples\"\n\n        guesses = [hdxm.guess_deltaG(rates, crop=True).to_numpy() for rates, hdxm in zip(rates_list, self.hdxm_list)]\n        flat = np.concatenate(guesses)\n\n        deltaG_array = np.full((self.Ns, self.Nr), fill_value=np.nan)\n        deltaG_array[self.coverage.s_r_mask] = flat  # todo get this mask from dict?\n\n        for row in deltaG_array:\n            # https://stackoverflow.com/questions/9537543/replace-nans-in-numpy-array-with-closest-non-nan-value\n            bools = ~np.isfinite(row)\n            row[bools] = np.interp(np.flatnonzero(bools), np.flatnonzero(~bools), row[~bools])\n\n        return deltaG_array\n\n    def add_alignment(self, alignment, first_r_numbers=None):\n        \"\"\"\n\n        :param alignment: list\n        :param first_r_numbers:\n            default is [1, 1, ...] but specifiy here if alignments do not all start at residue 1\n        :return:\n        \"\"\"\n        dfs = [hdxm.coverage.protein.df for hdxm in self.hdxm_list]\n        self.aligned_dataframes = align_dataframes(dfs, alignment, first_r_numbers)\n\n        df = self.aligned_dataframes['r_number']\n\n        # Crop residue numbers to interval range\n        df = df[((self.coverage.interval[0] <= df) & (df < self.coverage.interval[1])).all(axis=1)]\n        df = df - self.coverage.interval[0]  # First residue in interval selected by index 0\n        df.dropna(how='any', inplace=True)  # Remove non-aligned residues\n\n        self.aligned_indices = df.to_numpy(dtype=int).T\n\n    def get_tensors(self, dtype=None):\n        #todo create correct shapes as per table X for all\n        temperature = np.array([kf.temperature for kf in self.hdxm_list])\n\n        X_values = np.concatenate([hdxm.coverage.X.flatten() for hdxm in self.hdxm_list])\n        X = np.zeros((self.Ns, self.Np, self.Nr))\n        X[self.masks['spr']] = X_values\n\n        k_int_values = np.concatenate([hdxm.coverage['k_int'].to_numpy() for hdxm in self.hdxm_list])\n        k_int = np.zeros((self.Ns, self.Nr))\n        k_int[self.masks['sr']] = k_int_values\n\n        dtype = dtype or cfg.TORCH_DTYPE\n        device = cfg.TORCH_DEVICE\n\n        tensors = {\n            'temperature': torch.tensor(temperature, dtype=dtype, device=device).reshape(self.Ns, 1, 1),\n            'X': torch.tensor(X, dtype=dtype, device=device),\n            'k_int': torch.tensor(k_int, dtype=dtype, device=device).reshape(self.Ns, self.Nr, 1),\n            'timepoints': torch.tensor(self.timepoints, dtype=dtype, device=device).reshape(self.Ns, 1, self.Nt),\n            'd_exp': torch.tensor(self.d_exp, dtype=dtype, device=device)  #todo this is called uptake_corrected/D/uptake\n        }\n\n        return tensors\n\n    @property\n    def exchanges(self):\n        values = np.concatenate([hdxm.coverage['exchanges'].to_numpy() for hdxm in self.hdxm_list])\n        exchanges = np.zeros((self.Ns, self.Nr), dtype=bool)\n        exchanges[self.masks['sr']] = values\n\n        return exchanges\n\n    def to_file(self, file_path, include_version=True, include_metadata=True, fmt='csv', **kwargs):\n        \"\"\"\n        Write the data in this HDX measurement set to file.\n\n        Parameters\n        ----------\n        file_path : :obj:`str`\n            File path to create and write to.\n        include_version : :obj:`bool`\n            Set ``True`` to include PyHDX version and current time/date\n        fmt: :obj: `str`\n            Formatting to use, options are 'csv' or 'pprint'\n        include_metadata : :obj:`bool`\n            If `True`, the objects' metadata is included\n        **kwargs : :obj:`dict`, optional\n            Optional additional keyword arguments passed to `df.to_csv`\n        Returns\n        -------\n        None\n\n        \"\"\"\n\n        dfs = []\n        metadata = {}\n        for hdxm in self.hdxm_list:\n            metadata[hdxm.name] = hdxm.metadata if include_metadata else include_metadata\n            dfs.append(hdxm.data)\n\n        full_df = pd.concat(dfs, axis=1, keys=self.names)\n        dataframe_to_file(file_path, full_df, include_version=include_version, include_metadata=metadata, fmt=fmt, **kwargs)\n\n\n#https://stackoverflow.com/questions/4494404/find-large-number-of-consecutive-values-fulfilling-condition-in-a-numpy-array\ndef contiguous_regions(condition):\n    \"\"\"Finds contiguous True regions of the boolean array \"condition\". Returns\n    a 2D array where the first column is the start index of the region and the\n    second column is the end index.\"\"\"\n\n    # Find the indicies of changes in \"condition\"\n    d = np.diff(condition)\n    idx, = d.nonzero()\n\n    # We need to start things after the change in \"condition\". Therefore,\n    # we'll shift the index by 1 to the right.\n    idx += 1\n\n    if condition[0]:\n        # If the start of condition is True prepend a 0\n        idx = np.r_[0, idx]\n\n    if condition[-1]:\n        # If the end of condition is True, append the length of the array\n        idx = np.r_[idx, condition.size] # Edit\n\n    # Reshape the result into two columns\n    idx.shape = (-1,2)\n    return idx\n\n\ndef hdx_intersection(hdx_list, fields=None):\n    \"\"\"\n    Finds the intersection between peptides in :class:`~pydhx.models.HDXMeasurement` and returns new objects such that\n    all peptides (coverage, exposure) between the measurements are identical.\n\n    Optionally intersections by custom fields can be made.\n\n    Parameters\n    ----------\n    hdx_list : :obj:`list`\n        Input list of :class:`~pyhdx.models.HDXMeasurement`\n    fields : :obj:`list`\n        By which fields to take the intersections. Default is ['_start', '_end', 'exposure']\n\n    Returns\n    -------\n    hdx_out : :obj:`list`\n        Output list of :class:`~pyhdx.models.HDXMeasurement`\n    \"\"\"\n\n    fields = fields or ['_start', '_end', 'exposure']\n\n    full_arrays = [data_obj.full_data for data_obj in hdx_list]\n    selected = array_intersection(full_arrays, fields=fields)\n\n    hdx_out = [HDXMeasurement(data, **data_obj.metadata) for data, data_obj in zip(selected, hdx_list)]\n    return hdx_out\n\n\ndef array_intersection(arrays_list, fields):\n    \"\"\"\n    Find and return the intersecting entries in multiple arrays.\n\n    Parameters\n    ----------\n    arrays_list : :obj:`iterable`\n        Iterable of input structured arrays\n    fields : :obj:`iterable` \n        Iterable of fields to use to decide if entires are intersecting\n\n    Returns\n    -------\n    selected : :obj:`iterable`\n        Output iterable of arrays with only intersecting entries.\n\n    \"\"\"\n    intersection = reduce(np.intersect1d, [fields_view(d, fields) for d in arrays_list])\n    selected = [elem[np.isin(fields_view(elem, fields), intersection)] for elem in arrays_list]\n\n    return selected\n", "meta": {"hexsha": "0d8cf8761f5c4db0ea28e0902f4022b05a4bc69d", "size": 47264, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyhdx/models.py", "max_stars_repo_name": "Jhsmit/PyHDX", "max_stars_repo_head_hexsha": "34bf653743008508bb14f24ccca21ee39b5b25e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2020-10-14T14:15:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:55:36.000Z", "max_issues_repo_path": "pyhdx/models.py", "max_issues_repo_name": "Jhsmit/PyHDX", "max_issues_repo_head_hexsha": "34bf653743008508bb14f24ccca21ee39b5b25e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 145, "max_issues_repo_issues_event_min_datetime": "2020-10-01T13:32:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T08:31:47.000Z", "max_forks_repo_path": "pyhdx/models.py", "max_forks_repo_name": "Jhsmit/PyHDX", "max_forks_repo_head_hexsha": "34bf653743008508bb14f24ccca21ee39b5b25e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-03-03T10:57:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-24T09:11:49.000Z", "avg_line_length": 36.7241647242, "max_line_length": 142, "alphanum_fraction": 0.6253173663, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 11146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.18297633540340258}}
{"text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport sys\nfrom pprint import pprint\nfrom datetime import datetime\nfrom datetime import timedelta\nimport pickle\nimport copy\nimport calendar\nimport mysql.connector\n\n\ntimezone = -8\ncalib_stability_uncertainty = 0.1\n\n#database connection\ncnx = mysql.connector.connect(user='root', password='Suresh15', host='localhost', database='black_carbon')\ncursor = cnx.cursor()\n\n#fire times\nfire_time1 = [datetime.strptime('2009/07/27 00:00', '%Y/%m/%d %H:%M'), datetime.strptime('2009/08/08 00:00', '%Y/%m/%d %H:%M')] #row_datetimes follwing Takahama et al (2011) doi:10.5194/acp-11-6367-2011 #PST\nfire_time2 = [datetime.strptime('2010/07/26 09:00', '%Y/%m/%d %H:%M'), datetime.strptime('2010/07/28 09:30', '%Y/%m/%d %H:%M')] #jason's BC clear report #PST\n\n#open cluslist and read into a python list\ncluslist = []\nCLUSLIST_file = 'C:/hysplit4/working/WHI/CLUSLIST_10'\nCLUSLIST_file = 'C:/Users/Sarah Hanna/Documents/Data/WHI long term record/HYSPLIT/clustering/CLUSLIST_10'\n\nwith open(CLUSLIST_file,'r') as f:\n\tfor line in f:\n\t\tnewline = line.split()\n\t\tcluster_no = int(newline[0])\n\t\ttraj_time = datetime(int(newline[2])+2000,int(newline[3]),int(newline[4]),int(newline[5]))+timedelta(hours = timezone)\n\t\tcluslist.append([traj_time,cluster_no])\n\n# sort cluslist by row_datetime in place\t\t\ncluslist.sort(key=lambda clus_info: clus_info[0])  \n\n\n#make a copy for sorting the GeosChem data and get rid of all early night points since we don't have GC data for the early night anyways\ncluslist_GC = []\ncluslist_copy = copy.copy(cluslist)\n\nfor line in cluslist_copy:\n\ttraj_datetime = line[0]\n\tcluster_no = line[1]\n\tif traj_datetime.hour == 5:\n\t\tcluslist_GC.append([traj_datetime,cluster_no])\n \n \n############Meaurements\n#get full rBC record (in PST and 10 min binned intervals) and put in dictionaries keyed by date \nrBC_24h_data = {} #does not include BB data\nrBC_BB_24h_data = {}\nrBC_FT_data_cluster_NPac = {}\nrBC_FT_data_cluster_SPac = {}\nrBC_FT_data_cluster_Cont = {}\nrBC_FT_data_cluster_LRT = {}\nrBC_FT_data_cluster_GBPS = {}\nrBC_FT_data_cluster_BB = {}\n\n\nwith open('C:/Users/Sarah Hanna/Documents/Data/WHI long term record/WHI_rBC_record_2009to2013-spikes_removed.rbcpckl', 'r') as f:  #this has only the data of interest, it has been truncated at May 31, 2012 also these row_datetimes are in PST\n\tfull_rBC_record = pickle.load(f)\n\n\tfor row in full_rBC_record:\n\t\trow_datetime = row[0] #in PST\n\t\trow_date = datetime(row_datetime.year, row_datetime.month, row_datetime.day)\n\t\trow_rBC_mass_conc = row[2]\n\t\trow_rBC_mass_conc_LL = row[3]\n\t\trow_rBC_mass_conc_UL = row[4]\n\t\t\n\t\tif np.isnan(row_rBC_mass_conc_LL):\n\t\t\trow_abs_err = np.nan\n\t\telse:\n\t\t\trow_abs_err = (row_rBC_mass_conc-row_rBC_mass_conc_LL)\n\t\t\n\t\t#get all 24hr data  (could make it less BB times if we this after the BB data extraction code\n\t\tcorrection_factor_for_massdistr = 1./0.4767\n\t\tmass_distr_correction_error = 0.016  #this is the uncertainty in the firt of the mass distribution for this period. from WHI_long_term_v2_size_distr_fitting_and_plotting.py\n\t\tcorrected_mass_conc = row_rBC_mass_conc*correction_factor_for_massdistr\n\t\trow_data = [corrected_mass_conc, row_abs_err+(corrected_mass_conc*(mass_distr_correction_error+calib_stability_uncertainty)) ]\n\t\tif row_date in rBC_24h_data:\n\t\t\trBC_24h_data[row_date].append(row_data)\n\t\telse:\n\t\t\trBC_24h_data[row_date] = [row_data]\n\t\n\t\t\t\n\t\t#if in a BB time, put this data in BB dict\n\t\tif (fire_time1[0] <= row_datetime <= fire_time1[1]) or (fire_time2[0] <= row_datetime <= fire_time2[1]):\n\t\t\tcorrection_factor_for_massdistr = 1./0.4153\n\t\t\tmass_distr_correction_error = 0.018  #this is the uncertainty in the firt of the mass distribution for this period. from WHI_long_term_v2_size_distr_fitting_and_plotting.py\n\t\t\tcorrected_mass_conc = row_rBC_mass_conc*correction_factor_for_massdistr\n\t\t\trow_data = [corrected_mass_conc, row_abs_err+(corrected_mass_conc*(mass_distr_correction_error+calib_stability_uncertainty)) ]\n\t\t\tif row_date in rBC_BB_24h_data:\n\t\t\t\trBC_BB_24h_data[row_date].append(row_data)\n\t\t\telse:\n\t\t\t\trBC_BB_24h_data[row_date] = [row_data]\n\n\t\t\n\t\t#pop off any cluslist times that are in the past\n\t\tcluslist_current_datetime = cluslist[0][0] #in PST\n\t\twhile row_datetime > (cluslist_current_datetime + timedelta(hours=3)):\n\t\t\tcluslist.pop(0)\n\t\t\tif len(cluslist):\n\t\t\t\tcluslist_current_datetime = cluslist[0][0]\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tbreak\n\t\t\t\t\n\t\t#get cluster no\n\t\tcluslist_current_cluster_no = cluslist[0][1]\n\t\t\n\t\t#add data to list in cluster dictionaries (1 list per cluster time early night/late night)\n\t\tif ((cluslist_current_datetime-timedelta(hours=3)) <= row_datetime <= (cluslist_current_datetime+timedelta(hours=3))):\n\t\t\n\t\t\t#if in a BB time,\n\t\t\tif (fire_time1[0] <= row_datetime <= fire_time1[1]) or (fire_time2[0] <= row_datetime <= fire_time2[1]):\n\t\t\t\tcorrection_factor_for_massdistr = 1./0.415\n\t\t\t\tmass_distr_correction_error = 0.018  #this is the uncertainty in the firt of the mass distribution for this period. from WHI_long_term_v2_size_distr_fitting_and_plotting.py\n\t\t\t\tcorrected_mass_conc = row_rBC_mass_conc*correction_factor_for_massdistr\n\t\t\t\trow_data = [corrected_mass_conc, row_abs_err+(corrected_mass_conc*(mass_distr_correction_error+calib_stability_uncertainty)) ]\n\t\t\t\tif cluslist_current_datetime in rBC_FT_data_cluster_BB:\n\t\t\t\t\trBC_FT_data_cluster_BB[cluslist_current_datetime].append(row_data)\n\t\t\t\telse:\n\t\t\t\t\trBC_FT_data_cluster_BB[cluslist_current_datetime] = [row_data] \n\t\t\t\t\n\t\t\t\tcontinue #do not go on to put this data into a cluster dictionary, since it's BB data\n\t\t\n\n\t\t\tif cluslist_current_cluster_no == 9:\n\t\t\t\tcorrection_factor_for_massdistr = 1./0.5411\n\t\t\t\tmass_distr_correction_error = 0.015  #this is the uncertainty in the firt of the mass distribution for this period. from WHI_long_term_v2_size_distr_fitting_and_plotting.py\n\t\t\t\tcorrected_mass_conc = row_rBC_mass_conc*correction_factor_for_massdistr\n\t\t\t\trow_data = [corrected_mass_conc, row_abs_err+(corrected_mass_conc*(mass_distr_correction_error+calib_stability_uncertainty)) ]\n\t\t\t\tif cluslist_current_datetime in rBC_FT_data_cluster_GBPS:\n\t\t\t\t\trBC_FT_data_cluster_GBPS[cluslist_current_datetime].append(row_data)\n\t\t\t\telse:\n\t\t\t\t\trBC_FT_data_cluster_GBPS[cluslist_current_datetime] = [row_data] \n\t\t\t\t\n\t\t\tif cluslist_current_cluster_no == 4:\n\t\t\t\tcorrection_factor_for_massdistr = 1./0.4028\n\t\t\t\tmass_distr_correction_error = 0.028  #this is the uncertainty in the firt of the mass distribution for this period. from WHI_long_term_v2_size_distr_fitting_and_plotting.py\n\t\t\t\tcorrected_mass_conc = row_rBC_mass_conc*correction_factor_for_massdistr\n\t\t\t\trow_data = [corrected_mass_conc, row_abs_err+(corrected_mass_conc*(mass_distr_correction_error+calib_stability_uncertainty)) ]\t\t\t\t\n\t\t\t\tif cluslist_current_datetime in rBC_FT_data_cluster_Cont:\n\t\t\t\t\trBC_FT_data_cluster_Cont[cluslist_current_datetime].append(row_data)\n\t\t\t\telse:\n\t\t\t\t\trBC_FT_data_cluster_Cont[cluslist_current_datetime] = [row_data]\n\t\t\t\t\t\n\t\t\tif cluslist_current_cluster_no in [6,8]:\n\t\t\t\tcorrection_factor_for_massdistr = 1./0.4626\n\t\t\t\tmass_distr_correction_error = 0.032  #this is the uncertainty in the firt of the mass distribution for this period. from WHI_long_term_v2_size_distr_fitting_and_plotting.py\n\t\t\t\tcorrected_mass_conc = row_rBC_mass_conc*correction_factor_for_massdistr\n\t\t\t\trow_data = [corrected_mass_conc, row_abs_err+(corrected_mass_conc*(mass_distr_correction_error+calib_stability_uncertainty)) ]\t\t\t\t\n\t\t\t\tif cluslist_current_datetime in rBC_FT_data_cluster_SPac:\n\t\t\t\t\trBC_FT_data_cluster_SPac[cluslist_current_datetime].append(row_data)\n\t\t\t\telse:\n\t\t\t\t\trBC_FT_data_cluster_SPac[cluslist_current_datetime] = [row_data]\n\t\t\t\t\t\n\t\t\tif cluslist_current_cluster_no in [2,7]:\n\t\t\t\tcorrection_factor_for_massdistr = 1./0.5280\n\t\t\t\tmass_distr_correction_error = 0.019  #this is the uncertainty in the firt of the mass distribution for this period. from WHI_long_term_v2_size_distr_fitting_and_plotting.py\n\t\t\t\tcorrected_mass_conc = row_rBC_mass_conc*correction_factor_for_massdistr\n\t\t\t\trow_data = [corrected_mass_conc, row_abs_err+(corrected_mass_conc*(mass_distr_correction_error+calib_stability_uncertainty)) ]\t\t\t\t\n\t\t\t\tif cluslist_current_datetime in rBC_FT_data_cluster_LRT:\n\t\t\t\t\trBC_FT_data_cluster_LRT[cluslist_current_datetime].append(row_data)\n\t\t\t\telse:\n\t\t\t\t\trBC_FT_data_cluster_LRT[cluslist_current_datetime] = [row_data]\n\t\t\t\t\t\n\t\t\tif cluslist_current_cluster_no in [1,3,5,10]:\n\t\t\t\tcorrection_factor_for_massdistr = 1./0.3525\n\t\t\t\tmass_distr_correction_error = 0.015  #this is the uncertainty in the firt of the mass distribution for this period. from WHI_long_term_v2_size_distr_fitting_and_plotting.py\n\t\t\t\tcorrected_mass_conc = row_rBC_mass_conc*correction_factor_for_massdistr\n\t\t\t\trow_data = [corrected_mass_conc, row_abs_err+(corrected_mass_conc*(mass_distr_correction_error+calib_stability_uncertainty)) ]\t\t\t\t\n\t\t\t\tif cluslist_current_datetime in rBC_FT_data_cluster_NPac:\n\t\t\t\t\trBC_FT_data_cluster_NPac[cluslist_current_datetime].append(row_data)\n\t\t\t\telse:\n\t\t\t\t\trBC_FT_data_cluster_NPac[cluslist_current_datetime] = [row_data]\n\t\n\n\t\n#24h rBC-meas avgs\nSP2_24h_FR = [] \nSP2_24h_BB = []\n\n\n#6h rBC-meas avgs (FT data)\nSP2_6h_NPac = [] \nSP2_6h_SPac = [] \nSP2_6h_Cont = [] \nSP2_6h_LRT  = [] \nSP2_6h_GBPS = [] \nSP2_6h_BB = [] \nSP2_6h_all_non_BB = []\n\t\t\n#24h avgd data \nfor date, mass_data in rBC_24h_data.iteritems():\n\tmass_concs = [row[0] for row in mass_data]\n\tmass_concs_abs_err = [row[1] for row in mass_data]\n\t\n\tdate_mean = np.mean(mass_concs)\n\tdate_mean_err = np.mean(mass_concs_abs_err)/date_mean\n\t\n\tSP2_24h_FR.append([date_mean,date_mean_err])\n\n\t\nfor date, mass_data in rBC_BB_24h_data.iteritems():\n\tmass_concs = [row[0] for row in mass_data]\n\tmass_concs_abs_err = [row[1] for row in mass_data]\n\t\n\tdate_mean = np.mean(mass_concs)\n\tdate_mean_err = np.mean(mass_concs_abs_err)/date_mean\n\t\n\tSP2_24h_BB.append([date_mean,date_mean_err])\n\n\n#6h avgd data\t\nfor date, mass_data in rBC_FT_data_cluster_NPac.iteritems():\n\tmass_concs = [row[0] for row in mass_data]\n\tmass_concs_abs_err = [row[1] for row in mass_data]\n\t\n\tdate_mean = np.mean(mass_concs)\n\tdate_mean_err = np.mean(mass_concs_abs_err)/date_mean\t\n\tSP2_6h_NPac.append([date_mean,date_mean_err])\n\tSP2_6h_all_non_BB.append([date_mean,date_mean_err])\n\t\nfor date, mass_data in rBC_FT_data_cluster_SPac.iteritems():\n\tmass_concs = [row[0] for row in mass_data]\n\tmass_concs_abs_err = [row[1] for row in mass_data]\n\t\n\tdate_mean = np.mean(mass_concs)\n\tdate_mean_err = np.mean(mass_concs_abs_err)/date_mean\t\n\tSP2_6h_SPac.append([date_mean,date_mean_err])\n\tSP2_6h_all_non_BB.append([date_mean,date_mean_err])\n\t\nfor date, mass_data in rBC_FT_data_cluster_Cont.iteritems():\n\tmass_concs = [row[0] for row in mass_data]\n\tmass_concs_abs_err = [row[1] for row in mass_data]\n\t\n\tdate_mean = np.mean(mass_concs)\n\tdate_mean_err = np.mean(mass_concs_abs_err)/date_mean\t\n\tSP2_6h_Cont.append([date_mean,date_mean_err])\n\tSP2_6h_all_non_BB.append([date_mean,date_mean_err])\n\nfor date, mass_data in rBC_FT_data_cluster_LRT.iteritems():\n\tmass_concs = [row[0] for row in mass_data]\n\tmass_concs_abs_err = [row[1] for row in mass_data]\n\t\n\tdate_mean = np.mean(mass_concs)\n\tdate_mean_err = np.mean(mass_concs_abs_err)/date_mean\t\n\tSP2_6h_LRT.append([date_mean,date_mean_err])\n\tSP2_6h_all_non_BB.append([date_mean,date_mean_err])\n\nfor date, mass_data in rBC_FT_data_cluster_GBPS.iteritems():\n\tmass_concs = [row[0] for row in mass_data]\n\tmass_concs_abs_err = [row[1] for row in mass_data]\n\t\n\tdate_mean = np.mean(mass_concs)\n\tdate_mean_err = np.mean(mass_concs_abs_err)/date_mean\t\n\tSP2_6h_GBPS.append([date_mean,date_mean_err])\t\n\tSP2_6h_all_non_BB.append([date_mean,date_mean_err])\n\t\nfor date, mass_data in rBC_FT_data_cluster_BB.iteritems():\n\tmass_concs = [row[0] for row in mass_data]\n\tmass_concs_abs_err = [row[1] for row in mass_data]\n\t\n\tdate_mean = np.mean(mass_concs)\n\tdate_mean_err = np.mean(mass_concs_abs_err)/date_mean\t\n\tSP2_6h_BB.append([date_mean,date_mean_err])\t\n\t\n###################GEOS-Chem\n\ndata_dir = 'C:/Users/Sarah Hanna/Documents/Data/WHI long term record/GOES-Chem/sarahWhistlerData'\nos.chdir(data_dir)\n\nlevel = 10 #1-47 #10 is closest to WHI avg P (WHI 95% CI = 770-793)\nlevel_up = level+1\nlevel_dn = level-1\n\nmolar_mass_BC = 12.0107 #in g/mol\nng_per_g = 10**9\nR = 8.3144621 # in m3*Pa/(K*mol)\nGEOS_Chem_factor = 10**-9\n\nGC_24h_FR = []\nGC_24h_BB = []\n\nfor file in os.listdir('.'):\n\tif file.endswith('24h.txt'):\n\t\t\n\t\twith open(file, 'r') as f:\n\t\t\t\n\t\t\twhile True:\n\t\t\t\t\n\t\t\t\tBCline_all = f.readline()\n\t\t\t\tTempline_all = f.readline()\n\t\t\t\tPressureline_all = f.readline()\n\t\t\t\tboxheightline_all = f.readline()\n\t\t\t\t\t\n\t\t\t\tif not (BCline_all and Templine_all and Pressureline_all and boxheightline_all):\n\t\t\t\t\tbreak\n\t\t\t\t\n\t\t\t\tBCline = BCline_all.split(',')\n\t\t\t\tTempline = Templine_all.split(',')\n\t\t\t\tPressureline = Pressureline_all.split(',')\n\t\t\t\t\n\t\t\t\tdate = datetime.strptime(BCline[0], '%Y%m%d')\n\t\t\t\t\n\t\t\t\tT = float(Templine[level]) # in K\n\t\t\t\tP = float(Pressureline[level])*100 #original data in hPa, this converts to Pa\n\n\t\t\t\tBC_conc_ppb = float(BCline[level]) # in molBC/molAIR \n\n\t\t\t\t#correction to STP\n\t\t\t\tvolume_ambient = (R*T)/(P)\n\t\t\t\tvolume_STP = volume_ambient*(P/101325)*(273/T)\n\t\t\t\tSTP_correction_factor =  volume_ambient/volume_STP\n\t\t\t\tBC_conc_ngm3 = STP_correction_factor*BC_conc_ppb*molar_mass_BC*ng_per_g*GEOS_Chem_factor/(R*T/P)  #this is per /m3 ambient so for STP must mult by vol_amb/vol_stp\t\n\t\t\t\t\n\t\t\t\t###get data for levels above and below curent\n\t\t\t\tT_up = float(Templine[level_up]) # in K\n\t\t\t\tP_up = float(Pressureline[level_up])*100 #original data in hPa, this converts to Pa\n\t\t\t\tBC_conc_ppb_up = float(BCline[level_up]) # in molBC/molAIR \n\t\t\t\tvolume_ambient_up = (R*T_up)/(P_up)\n\t\t\t\tvolume_STP_up = volume_ambient_up*(P_up/101325)*(273/T_up)\n\t\t\t\tSTP_correction_factor_up =  volume_ambient_up/volume_STP_up\n\t\t\t\tBC_conc_ngm3_up = STP_correction_factor_up*BC_conc_ppb_up*molar_mass_BC*ng_per_g*GEOS_Chem_factor/(R*T_up/P_up)  #this is per /m3 ambient so for STP must mult by vol_amb/vol_stp\n\t\t\t\t\n\t\t\t\tT_dn = float(Templine[level_dn]) # in K\n\t\t\t\tP_dn = float(Pressureline[level_dn])*100 #original data in hPa, this converts to Pa\n\t\t\t\tBC_conc_ppb_dn = float(BCline[level_dn]) # in molBC/molAIR \t\t\n\t\t\t\tvolume_ambient_dn = (R*T_dn)/(P_dn)\n\t\t\t\tvolume_STP_dn = volume_ambient_dn*(P_dn/101325)*(273/T_dn)\n\t\t\t\tSTP_correction_factor_dn =  volume_ambient_dn/volume_STP_dn\n\t\t\t\tBC_conc_ngm3_dn = STP_correction_factor_dn*BC_conc_ppb_dn*molar_mass_BC*ng_per_g*GEOS_Chem_factor/(R*T_dn/P_dn)  #this is per /m3 ambient so for STP must mult by vol_amb/vol_stp\n\t\t\t\t\n\t\t\t\tBC_conc_ngm3_lower_limit = min(BC_conc_ngm3_up,BC_conc_ngm3_dn,BC_conc_ngm3)\n\t\t\t\tBC_conc_ngm3_upper_limit = max(BC_conc_ngm3_up,BC_conc_ngm3_dn,BC_conc_ngm3)\n\t\t\t\tpos_y_err = BC_conc_ngm3_upper_limit - BC_conc_ngm3\n\t\t\t\tneg_y_err = BC_conc_ngm3 - BC_conc_ngm3_lower_limit\n\t\t\t\tmean_rel_err = ((pos_y_err+neg_y_err)/2)/BC_conc_ngm3\n\t\t\t\t\n\t\t\t\t#FR data\n\t\t\t\tif date >= datetime.strptime('20090628', '%Y%m%d') and date <= datetime.strptime('20090816', '%Y%m%d'):\n\t\t\t\t\tGC_24h_FR.append([BC_conc_ngm3,mean_rel_err])\n\t\t\t\tif date >= datetime.strptime('20100610', '%Y%m%d') and date <= datetime.strptime('20100727', '%Y%m%d'):\n\t\t\t\t\tGC_24h_FR.append([BC_conc_ngm3,mean_rel_err])\n\t\t\t\tif date >= datetime.strptime('20120405', '%Y%m%d') and date <= datetime.strptime('20120531', '%Y%m%d'):\n\t\t\t\t\tGC_24h_FR.append([BC_conc_ngm3,mean_rel_err])\n\t\t\t\t\t\n\t\t\t\t#BB data\n\t\t\t\tif (date >= datetime.strptime('2009/07/27', '%Y/%m/%d') and date < datetime.strptime('2009/08/08', '%Y/%m/%d')) or date == datetime.strptime('2010/07/26', '%Y/%m/%d') or date == datetime.strptime('2010/07/27', '%Y/%m/%d'):\n\t\t\t\t\tGC_24h_BB.append([BC_conc_ngm3,mean_rel_err])\n\n\nGC_6h_NPac = [] \nGC_6h_SPac = [] \nGC_6h_Cont = [] \nGC_6h_LRT  = [] \nGC_6h_GBPS = [] \t\nGC_6h_BB = []\t\nGC_6h_all_non_BB = []\t\t\t\n\n\n#query to add 6h GC mass ocnc data\nadd_6h_data = ('INSERT INTO whi_gc_v9_6h_mass_concs'\n              '(UNIX_UTC_6h_midtime,6h_midtime_string,cluster,GC_v9_default_mass_conc,GC_v9_default_rel_err)'\n              'VALUES (%(UNIX_ts)s,%(string_ts)s,%(cluster)s,%(GC_mass_conc)s,%(GC_rel_err)s)'\n\t\t\t  )\n\n\n\nfor file in os.listdir('.'):\n\tif file.endswith('N.txt'):  #these are the night files (2-4 and 5-7 PST)\n\n\t\twith open(file, 'r') as f:\n\t\t\t\n\t\t\twhile True:\n\t\t\t\tBCline_all = f.readline()\n\t\t\t\tTempline_all = f.readline()\n\t\t\t\tPressureline_all = f.readline()\n\t\t\t\tboxheightline_all = f.readline()\n\t\t\t\t\n\t\t\t\tif not (BCline_all and Templine_all and Pressureline_all and boxheightline_all):\n\t\t\t\t\tbreak\n\n\t\t\t\tBCline = BCline_all.split(',')\n\t\t\t\tTempline = Templine_all.split(',')\n\t\t\t\tPressureline = Pressureline_all.split(',')\n\t\t\t\t\n\t\t\t\tdate = datetime.strptime(BCline[0], '%Y%m%d')\n\t\t\t\t\n\t\t\t\tT = float(Templine[level]) # in K\n\t\t\t\tP = float(Pressureline[level])*100 #original data in hPa, this converts to Pa\n\t\t\t\tBC_conc_ppb = float(BCline[level]) # in molBC/molAIR \n\t\t\t\t#correction to STP\n\t\t\t\tvolume_ambient = (R*T)/(P)\n\t\t\t\tvolume_STP = volume_ambient*(P/101325)*(273/T)\n\t\t\t\tSTP_correction_factor =  volume_ambient/volume_STP\n\t\t\t\tBC_conc_ngm3 = STP_correction_factor*BC_conc_ppb*molar_mass_BC*ng_per_g*GEOS_Chem_factor/(R*T/P)  #this is per /m3 ambient so for STP must mult by vol_amb/vol_stp\t\n\t\t\t\n\t\t\t\t###get data for levels above and below curent\n\t\t\t\tT_up = float(Templine[level_up]) # in K\n\t\t\t\tP_up = float(Pressureline[level_up])*100 #original data in hPa, this converts to Pa\n\t\t\t\tBC_conc_ppb_up = float(BCline[level_up]) # in molBC/molAIR \n\t\t\t\tvolume_ambient_up = (R*T_up)/(P_up)\n\t\t\t\tvolume_STP_up = volume_ambient_up*(P_up/101325)*(273/T_up)\n\t\t\t\tSTP_correction_factor_up =  volume_ambient_up/volume_STP_up\n\t\t\t\tBC_conc_ngm3_up = STP_correction_factor_up*BC_conc_ppb_up*molar_mass_BC*ng_per_g*GEOS_Chem_factor/(R*T_up/P_up)  #this is per /m3 ambient so for STP must mult by vol_amb/vol_stp\n\t\t\t\t\n\t\t\t\tT_dn = float(Templine[level_dn]) # in K\n\t\t\t\tP_dn = float(Pressureline[level_dn])*100 #original data in hPa, this converts to Pa\n\t\t\t\tBC_conc_ppb_dn = float(BCline[level_dn]) # in molBC/molAIR \t\t\n\t\t\t\tvolume_ambient_dn = (R*T_dn)/(P_dn)\n\t\t\t\tvolume_STP_dn = volume_ambient_dn*(P_dn/101325)*(273/T_dn)\n\t\t\t\tSTP_correction_factor_dn =  volume_ambient_dn/volume_STP_dn\n\t\t\t\tBC_conc_ngm3_dn = STP_correction_factor_dn*BC_conc_ppb_dn*molar_mass_BC*ng_per_g*GEOS_Chem_factor/(R*T_dn/P_dn)  #this is per /m3 ambient so for STP must mult by vol_amb/vol_stp\n\t\t\t\t\n\t\t\t\tBC_conc_ngm3_lower_limit = min(BC_conc_ngm3_up,BC_conc_ngm3_dn,BC_conc_ngm3)\n\t\t\t\tBC_conc_ngm3_upper_limit = max(BC_conc_ngm3_up,BC_conc_ngm3_dn,BC_conc_ngm3)\n\t\t\t\tpos_y_err = BC_conc_ngm3_upper_limit - BC_conc_ngm3\n\t\t\t\tneg_y_err = BC_conc_ngm3 - BC_conc_ngm3_lower_limit\n\t\t\t\tmean_rel_err = ((pos_y_err+neg_y_err)/2)/BC_conc_ngm3\n\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\tif date > datetime.strptime('20120531', '%Y%m%d'):\n\t\t\t\t\tbreak\n                \n\t\t\t\t#pop off any cluslist times that are in the past\n\t\t\t\tcluslist_current_datetime = cluslist_GC[0][0] #in PST\n\t\t\t\tcluslist_current_date = datetime(cluslist_current_datetime.year, cluslist_current_datetime.month, cluslist_current_datetime.day)\n\n\t\t\t\twhile date > cluslist_current_date:\n\n\t\t\t\t\tcluslist_GC.pop(0)\n\t\t\t\t\tif len(cluslist_GC):\n\t\t\t\t\t\tcluslist_current_datetime = cluslist_GC[0][0]\n\t\t\t\t\t\tcluslist_current_date = datetime(cluslist_current_datetime.year, cluslist_current_datetime.month, cluslist_current_datetime.day)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\telse:\n\t\t\t\t\t\tbreak\n\n\t\t\t\t#get cluster no\n\t\t\t\tcluslist_current_cluster_no = cluslist_GC[0][1]\n\n\t\t\t\tif cluslist_current_date == date:\n\t\t\t\t\n\t\t\t\t\tif (fire_time1[0] <= cluslist_current_date <= fire_time1[1]) or (fire_time2[0] <= cluslist_current_date <= fire_time2[1]):\n\t\t\t\t\t\tGC_6h_BB.append([BC_conc_ngm3,mean_rel_err])\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\n\t\t\t\t\tif cluslist_current_cluster_no == 9:\n\t\t\t\t\t\tGC_6h_GBPS.append([BC_conc_ngm3,mean_rel_err])\n\t\t\t\t\t\tGC_6h_all_non_BB.append([BC_conc_ngm3,mean_rel_err])\n\t\t\t\t\t\tGC_cluster = 'GBPS'\n\t\t\t\t\t\t\t\n\t\t\t\t\tif cluslist_current_cluster_no == 4:\n\t\t\t\t\t\tGC_6h_Cont.append([BC_conc_ngm3,mean_rel_err])\n\t\t\t\t\t\tGC_6h_all_non_BB.append([BC_conc_ngm3,mean_rel_err])\n\t\t\t\t\t\tGC_cluster = 'Cont'\n\t\t\t\t\t\t\n\t\t\t\t\tif cluslist_current_cluster_no in [6,8]:\n\t\t\t\t\t\tGC_6h_SPac.append([BC_conc_ngm3,mean_rel_err])\n\t\t\t\t\t\tGC_6h_all_non_BB.append([BC_conc_ngm3,mean_rel_err])\n\t\t\t\t\t\tGC_cluster = 'SPac'\n\t\t\t\t\t\t\n\t\t\t\t\tif cluslist_current_cluster_no in [2,7]:\n\t\t\t\t\t\tGC_6h_LRT.append([BC_conc_ngm3,mean_rel_err])\n\t\t\t\t\t\tGC_6h_all_non_BB.append([BC_conc_ngm3,mean_rel_err])\n\t\t\t\t\t\tGC_cluster = 'LRT'\n\t\t\t\t\t\t\n\t\t\t\t\tif cluslist_current_cluster_no in [1,3,5,10]:\n\t\t\t\t\t\tGC_6h_NPac.append([BC_conc_ngm3,mean_rel_err])\n\t\t\t\t\t\tGC_6h_all_non_BB.append([BC_conc_ngm3,mean_rel_err])\n\t\t\t\t\t\tGC_cluster = 'NPac'\n\t\t\t\t\t\n\t\t\t\t\tperiod_midtime = datetime(date.year, date.month, date.day, 13, 0, 0)\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tBC_6h_data = {\n\t\t\t\t\t'UNIX_ts':float(calendar.timegm(period_midtime.utctimetuple())),\n\t\t\t\t\t'string_ts':datetime.strftime(period_midtime,'%Y%m%d %H:%M:%S'),\n\t\t\t\t\t'cluster':GC_cluster,\n\t\t\t\t\t'GC_mass_conc':BC_conc_ngm3,\n\t\t\t\t\t'GC_rel_err': mean_rel_err,\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tcursor.execute('DELETE FROM whi_gc_v9_6h_mass_concs WHERE UNIX_UTC_6h_midtime = %s and 6h_midtime_string = %s',(BC_6h_data['UNIX_ts'],BC_6h_data['string_ts']))\n\t\t\t\t\tcnx.commit()\n\t\t\t\t\tcursor.execute(add_6h_data, BC_6h_data)\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\n\t\t\t\n#print out percentile data and uncertainties\nstats_SP2 = {\n'SP2_24h_FR':[SP2_24h_FR],\n'SP2_24h_BB':[SP2_24h_BB],\n'SP2_6h_NPac':[SP2_6h_NPac],\n'SP2_6h_SPac':[SP2_6h_SPac],\n'SP2_6h_Cont':[SP2_6h_Cont],\n'SP2_6h_LRT':[SP2_6h_LRT],\n'SP2_6h_GBPS':[SP2_6h_GBPS],\n'SP2_6h_BB':[SP2_6h_BB],\n'SP2_6h_all_non_BB':[SP2_6h_all_non_BB],\n}\n\nfile_list = []\n\nprint 'SP2'\nfor key, value in stats_SP2.iteritems():\n\tmass_concs = [row[0] for row in value[0]]\n\tmass_concs_rel_errs = [row[1] for row in value[0]]\n\tprint key,'no. of samples: ', len(mass_concs)\n\tprint key,'mass concs', np.percentile(mass_concs, 10),np.percentile(mass_concs, 50), np.percentile(mass_concs, 90), np.mean(mass_concs) \n\tprint key,'errs',np.percentile(mass_concs_rel_errs, 50), np.mean(mass_concs_rel_errs)\t\n\tstats_SP2[key].append(np.percentile(mass_concs, 50))\n\tfile_list.append([key,np.percentile(mass_concs, 10),np.percentile(mass_concs, 50), np.percentile(mass_concs, 90), np.mean(mass_concs),np.mean(mass_concs_rel_errs)])\n\t\n#save stats to file \nos.chdir('C:/Users/Sarah Hanna/Documents/Data/WHI long term record/GOES-Chem/')\nfile = open('WHI_long_term_SP2_stats_by_cluster.txt', 'w')\nfile.write('mass conc stats in ng/m3 - stp' +'\\n')\nfile.write('cluster' + '\\t' +  '10th percentile' + '\\t' + '50th percentile' + '\\t' + '90th percentile' + '\\t' + 'mean' + '\\t' +'mean rel err' +'\\n')\nfor row in file_list:\n\tline = '\\t'.join(str(x) for x in row)\n\tfile.write(line + '\\n')\nfile.close()\t\n\nstats_GC = {\n'GC_24h_FR':[GC_24h_FR],\n'GC_24h_BB':[GC_24h_BB],\n'GC_6h_NPac':[GC_6h_NPac],\n'GC_6h_SPac':[GC_6h_SPac],\n'GC_6h_Cont':[GC_6h_Cont],\n'GC_6h_LRT':[GC_6h_LRT],\n'GC_6h_GBPS':[GC_6h_GBPS],\n'GC_6h_BB':[GC_6h_BB],\n'GC_6h_all_non_BB':[GC_6h_all_non_BB],\n}\n\t\n\t\nprint 'GC'\nfor key, value in stats_GC.iteritems():\n\tmass_concs = [row[0] for row in value[0]]\n\tmass_concs_rel_errs = [row[1] for row in value[0]]\n\tprint key,'mass concs', np.percentile(mass_concs, 10),np.percentile(mass_concs, 50), np.percentile(mass_concs, 90), np.mean(mass_concs) \n\tprint key,'rel err', np.mean(mass_concs_rel_errs)\t\n\tstats_GC[key].append(np.percentile(mass_concs, 50))\n\n\n\n\n###################plotting\nSP2_6h_NPac_m = [row[0] for row in SP2_6h_NPac]\nSP2_6h_SPac_m = [row[0] for row in SP2_6h_SPac]\nSP2_6h_Cont_m = [row[0] for row in SP2_6h_Cont]\nSP2_6h_LRT_m =  [row[0] for row in SP2_6h_LRT]\nSP2_6h_GBPS_m = [row[0] for row in SP2_6h_GBPS]\nSP2_6h_BB_m = [row[0] for row in SP2_6h_BB]\nSP2_6h_all_non_BB_m = [row[0] for row in SP2_6h_all_non_BB]\n\nSP2_24h_FR_m = [row[0] for row in SP2_24h_FR]\nSP2_24h_BB_m = [row[0] for row in SP2_24h_BB]\n\nGC_6h_NPac_m = [row[0] for row in GC_6h_NPac]\nGC_6h_SPac_m = [row[0] for row in GC_6h_SPac]\nGC_6h_Cont_m = [row[0] for row in GC_6h_Cont]\nGC_6h_LRT_m =  [row[0] for row in GC_6h_LRT]\nGC_6h_GBPS_m = [row[0] for row in GC_6h_GBPS]\nGC_6h_BB_m = [row[0] for row in GC_6h_BB]\nGC_6h_all_non_BB_m = [row[0] for row in GC_6h_all_non_BB]\n\nGC_24h_FR_m = [row[0] for row in GC_24h_FR]\nGC_24h_BB_m = [row[0] for row in GC_24h_BB]\n\nfig = plt.figure(figsize=(14, 6))\n\nbin_number = 22\nFT_UL = 280\nbin_range = (0,FT_UL)\nincr = 100\n\nax11 = plt.subplot2grid((2,6), (0,0), colspan=1,)\nax1 =  plt.subplot2grid((2,6), (0,1), colspan=1, sharey=ax11)\nax2 =  plt.subplot2grid((2,6), (0,2), colspan=1, sharey=ax11)\nax3 =  plt.subplot2grid((2,6), (0,3), colspan=1, sharey=ax11)\nax4 =  plt.subplot2grid((2,6), (0,4), colspan=1, sharey=ax11)\nax5 =  plt.subplot2grid((2,6), (0,5), colspan=1, sharey=ax11)\n                           \nax12 = plt.subplot2grid((2,6), (1,0), colspan=1, )\nax6 =  plt.subplot2grid((2,6), (1,1), colspan=1, sharey=ax12)\nax7 =  plt.subplot2grid((2,6), (1,2), colspan=1, sharey=ax12)\nax8 =  plt.subplot2grid((2,6), (1,3), colspan=1, sharey=ax12)\nax9 =  plt.subplot2grid((2,6), (1,4), colspan=1, sharey=ax12)\nax10 = plt.subplot2grid((2,6), (1,5), colspan=1, sharey=ax12)\n\n#SP2\nax1.hist(SP2_6h_NPac_m,bins = bin_number, range = bin_range)\nax1.xaxis.set_visible(True)\nax1.yaxis.set_visible(False)\nax1.text(0.25, 0.9,'N. Pacific', transform=ax1.transAxes)\n#ax1.set_ylim(0,40)\nax1.xaxis.tick_top()\nax1.xaxis.set_label_position('top') \nax1.xaxis.set_ticks(np.arange(0, FT_UL, incr))\nax1.axvline(stats_SP2['SP2_6h_NPac'][1], color= 'black', linestyle = '--')\n\n\nax2.hist(SP2_6h_SPac_m,bins = bin_number, range = bin_range)\nax2.xaxis.set_visible(True)\nax2.yaxis.set_visible(False)\nax2.text(0.25, 0.9,'S. Pacific', transform=ax2.transAxes)\nax2.xaxis.tick_top()\nax2.xaxis.set_label_position('top') \nax2.xaxis.set_ticks(np.arange(0, FT_UL, incr))\nax2.axvline(stats_SP2['SP2_6h_SPac'][1], color= 'black', linestyle = '--')\n\n\nax3.hist(SP2_6h_GBPS_m,bins = bin_number, range = bin_range)\nax3.xaxis.set_visible(True)\nax3.yaxis.set_visible(False)\nax3.text(0.2, 0.82,'Georgia Basin/\\nPuget Sound', transform=ax3.transAxes)\nax3.xaxis.tick_top()\nax3.xaxis.set_label_position('top') \nax3.xaxis.set_ticks(np.arange(0, FT_UL, incr))\nax3.axvline(stats_SP2['SP2_6h_GBPS'][1], color= 'black', linestyle = '--')\n\nax4.hist(SP2_6h_LRT_m,bins = bin_number, range = bin_range)\nax4.xaxis.set_visible(True)\nax4.yaxis.set_visible(False)\nax4.text(0.2, 0.9,'W. Pacific/Asia', transform=ax4.transAxes)\nax4.xaxis.tick_top()\nax4.xaxis.set_label_position('top') \nax4.xaxis.set_ticks(np.arange(0, FT_UL, incr))\nax4.axvline(stats_SP2['SP2_6h_LRT'][1], color= 'black', linestyle = '--')\n\n\nax5.hist(SP2_6h_Cont_m,bins = bin_number, range = bin_range)\nax5.xaxis.set_visible(True)\nax5.yaxis.set_visible(False)\nax5.text(0.25, 0.9,'N. Canada', transform=ax5.transAxes)\nax5.xaxis.tick_top()\nax5.xaxis.set_label_position('top')\nax5.xaxis.set_ticks(np.arange(0, FT_UL, incr))\nax5.axvline(stats_SP2['SP2_6h_Cont'][1], color= 'black', linestyle = '--')\n\nax11.hist(SP2_6h_all_non_BB_m,bins = bin_number, range = bin_range)\nax11.xaxis.set_visible(True)\nax11.yaxis.set_visible(True)\nax11.set_ylabel('frequency - Measurements')\nax11.text(0.4, 0.9,'All Data', transform=ax11.transAxes)\nax11.xaxis.tick_top()\nax11.xaxis.set_label_position('top')\nax11.xaxis.set_ticks(np.arange(0, FT_UL, incr))\nax11.axvline(stats_SP2['SP2_6h_Cont'][1], color= 'black', linestyle = '--')\n\n#GC\nax6.hist(GC_6h_NPac_m,bins = bin_number, range = bin_range, color = 'green')\nax6.xaxis.set_visible(True)\nax6.yaxis.set_visible(False)\nax6.xaxis.set_ticks(np.arange(0, FT_UL, incr))\nax6.axvline(stats_GC['GC_6h_NPac'][1], color= 'black', linestyle = '--')\n\nax7.hist(GC_6h_SPac_m,bins = bin_number, range = bin_range, color = 'green')\nax7.xaxis.set_visible(True)\nax7.yaxis.set_visible(False)\nax7.xaxis.set_ticks(np.arange(0, FT_UL, incr))\nax7.axvline(stats_GC['GC_6h_SPac'][1], color= 'black', linestyle = '--')\n\nax8.hist(GC_6h_GBPS_m,bins = bin_number, range = bin_range, color = 'green')\nax8.xaxis.set_visible(True)\nax8.yaxis.set_visible(False)\nax8.set_xlabel('6h rBC mass concentration (ng/m3 - STP)')\nax8.xaxis.set_ticks(np.arange(0, FT_UL, incr))\nax8.axvline(stats_GC['GC_6h_GBPS'][1], color= 'black', linestyle = '--')\n\nax9.hist(GC_6h_LRT_m,bins = bin_number, range = bin_range, color = 'green')\nax9.xaxis.set_visible(True)\nax9.yaxis.set_visible(False)\nax9.xaxis.set_ticks(np.arange(0, FT_UL, incr))\nax9.axvline(stats_GC['GC_6h_LRT'][1], color= 'black', linestyle = '--')\n\nax10.hist(GC_6h_Cont_m,bins = bin_number, range = bin_range, color = 'green')\nax10.xaxis.set_visible(True)\nax10.yaxis.set_visible(False)\nax10.xaxis.set_ticks(np.arange(0, FT_UL, incr))\nax10.axvline(stats_GC['GC_6h_Cont'][1], color= 'black', linestyle = '--')\n\nax12.hist(GC_6h_all_non_BB_m,bins = bin_number, range = bin_range, color = 'green')\nax12.xaxis.set_visible(True)\nax12.yaxis.set_visible(True)\nax12.set_ylabel('frequency - GEOS-Chem')\nax12.xaxis.set_ticks(np.arange(0, FT_UL, incr))\nax12.axvline(stats_GC['GC_6h_BB'][1], color= 'black', linestyle = '--')\n\nplt.subplots_adjust(hspace=0.0)\nplt.subplots_adjust(wspace=0.0)\n\nos.chdir('C:/Users/Sarah Hanna/Documents/Data/WHI long term record/GOES-Chem/')\nplt.savefig('histograms -clustered GEOS-Chem and measurements - 6h FT.png',bbox_inches='tight')\n\nplt.show()\nsys.exit()\n\t\n###################plotting 2\nfig = plt.figure(figsize=(10,8))\n\nbin_number_FR = 30\nUL_FR = 360\nbin_range_FR = (0,UL_FR)\n\nbin_number_BB = 26\nUL_BB = 610\nbin_range_BB = (0,UL_BB)\n\nax1 = plt.subplot2grid((2,2), (0,0), colspan=1)\nax2 = plt.subplot2grid((2,2), (0,1), colspan=1, sharey=ax1)\n\n\t\t\t\t\t\t\nax6 = plt.subplot2grid((2,2), (1,0), colspan=1)\nax7 = plt.subplot2grid((2,2), (1,1), colspan=1, sharey=ax6)\n\n\n\n#SP2\nax1.hist(SP2_24h_FR_m,bins = bin_number_FR, range = bin_range_FR)\nax1.xaxis.set_visible(True)\nax1.yaxis.set_visible(True)\nax1.set_ylabel('frequency - Measurements')\nax1.text(0.25, 0.80,'Full Record \\n(not including BB periods)', transform=ax1.transAxes)\n#ax1.set_ylim(0,40)\nax1.xaxis.tick_top()\nax1.xaxis.set_label_position('top') \nax1.xaxis.set_ticks(np.arange(0, UL_FR, 100))\nax1.axvline(stats_SP2['SP2_24h_FR'][1], color= 'black', linestyle = '--')\n\n\n\nax2.hist(SP2_24h_BB_m,bins = bin_number_BB, range = bin_range_BB)\nax2.xaxis.set_visible(True)\nax2.yaxis.set_visible(False)\nax2.text(0.25, 0.88,'Biomass Burning Periods', transform=ax2.transAxes)\nax2.xaxis.tick_top()\nax2.xaxis.set_label_position('top') \nax2.xaxis.set_ticks(np.arange(0, UL_BB, 100))\nax2.axvline(stats_SP2['SP2_24h_BB'][1], color= 'black', linestyle = '--')\n\n#GC\nax6.hist(GC_24h_FR_m,bins = bin_number_FR, range = bin_range_FR, color = 'green')\nax6.xaxis.set_visible(True)\nax6.yaxis.set_visible(True)\nax6.set_ylabel('frequency - GEOS-Chem')\nax6.xaxis.set_ticks(np.arange(0, UL_FR, 100))\nax6.axvline(stats_GC['GC_24h_FR'][1], color= 'black', linestyle = '--')\n\n\nax7.hist(GC_24h_BB_m,bins = bin_number_BB, range = bin_range_BB, color = 'green')\nax7.xaxis.set_visible(True)\nax7.yaxis.set_visible(False)\nax7.xaxis.set_ticks(np.arange(0, UL_BB, 100))\nax7.axvline(stats_GC['GC_24h_BB'][1], color= 'black', linestyle = '--')\n\nplt.figtext(0.35,0.06, '24h rBC mass concentration (ng/m3 - STP)')\n\nplt.subplots_adjust(hspace=0.07)\nplt.subplots_adjust(wspace=0.07)\n\nplt.savefig('histograms - GEOS-Chem and measurements - BB and FR(lessBB) - 24h.png')#,bbox_inches='tight')\n\nplt.show()\n\n###################plotting 3\nfig = plt.figure(figsize=(6,8))\n\nbin_number_all_FT = 30\nUL_all_FT = 300\nbin_range_all_FT = (0,UL_all_FT)\n\nax1 = plt.subplot2grid((2,1), (0,0), colspan=1)\t\t\t\t\nax2 = plt.subplot2grid((2,1), (1,0), colspan=1)\n\n\n\n\n#SP2\nax1.hist(SP2_6h_all_non_BB_m,bins = bin_number_all_FT, range = bin_range_all_FT)\nax1.xaxis.set_visible(True)\nax1.yaxis.set_visible(True)\nax1.set_ylabel('frequency - Measurements')\n#ax1.text(0.25, 0.80,'All nighttime measurements \\n(not including biomass burning periods)', transform=ax1.transAxes)\n#ax1.set_ylim(0,40)\nax1.xaxis.tick_top()\nax1.xaxis.set_label_position('top') \nax1.xaxis.set_ticks(np.arange(0, UL_all_FT, 50))\nax1.axvline(stats_SP2['SP2_6h_all_non_BB'][1], color= 'black', linestyle = '--')\n\n\n#GC\nax2.hist(GC_6h_all_non_BB_m,bins = bin_number_all_FT, range = bin_range_all_FT, color = 'green')\nax2.xaxis.set_visible(True)\nax2.yaxis.set_visible(True)\nax2.set_ylabel('frequency - GEOS-Chem')\nax2.xaxis.set_ticks(np.arange(0, UL_FR, 50))\nax2.axvline(stats_GC['GC_6h_all_non_BB'][1], color= 'black', linestyle = '--')\nax2.set_xlabel('6h rBC mass concentration (ng/m3 - STP)')\n\n#plt.figtext(0.35,0.06, '6h rBC mass concentration (ng/m3 - STP)')\n\nplt.subplots_adjust(hspace=0.07)\nplt.subplots_adjust(wspace=0.07)\n\nplt.savefig('histograms - GEOS-Chem and measurements - all non-BB FT - 6h.png',bbox_inches='tight')\n\nplt.show()\n\n\ncnx.close()\n", "meta": {"hexsha": "be3eb4fc6e33115a7cb3a43b9275569424d0c03a", "size": 32607, "ext": "py", "lang": "Python", "max_stars_repo_path": "WHI_long_term_v2_GEOSChem_and_meas_histograms_by_HYSPLIT_cluster_for_all_FT_sampling.py", "max_stars_repo_name": "annahs/atmos_research", "max_stars_repo_head_hexsha": "b5853c9b12e327492f8f8ba5069bca3fd2e981c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-08-17T15:25:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-17T16:50:00.000Z", "max_issues_repo_path": "WHI_long_term_v2_GEOSChem_and_meas_histograms_by_HYSPLIT_cluster_for_all_FT_sampling.py", "max_issues_repo_name": "annahs/atmos_research", "max_issues_repo_head_hexsha": "b5853c9b12e327492f8f8ba5069bca3fd2e981c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WHI_long_term_v2_GEOSChem_and_meas_histograms_by_HYSPLIT_cluster_for_all_FT_sampling.py", "max_forks_repo_name": "annahs/atmos_research", "max_forks_repo_head_hexsha": "b5853c9b12e327492f8f8ba5069bca3fd2e981c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7161997564, "max_line_length": 241, "alphanum_fraction": 0.7377250284, "include": true, "reason": "import numpy", "num_tokens": 10767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.18297633540340258}}
{"text": "from pathlib import Path\nfrom ctypes import Structure, POINTER, CDLL, c_long, c_double\n\nimport numpy as np\n\n\nclass Coord(Structure):\n    \"\"\"Cartesian coordinates\"\"\"\n    _fields_ = [\n        ('x', c_double),\n        ('y', c_double),\n        ('z', c_double),\n    ]\n\n\nclass Atom(Structure):\n    \"\"\"Atom: coordinates + proton number\"\"\"\n    _fields_ = [\n        ('x', c_double),\n        ('y', c_double),\n        ('z', c_double),\n        ('e', c_long),\n    ]\n\n\nclass H4Parameters(Structure):\n    \"\"\"H4 Parameters\"\"\"\n    _fields_ = [\n        ('para_oh_o', c_double),\n        ('para_oh_n', c_double),\n        ('para_nh_o', c_double),\n        ('para_nh_n', c_double),\n        ('multiplier_wh_o', c_double),\n        ('multiplier_nh4', c_double),\n        ('multiplier_coo', c_double),\n        ('hh_rep_k', c_double),\n        ('hh_rep_e', c_double),\n        ('hh_rep_r0', c_double),\n    ]\n\n\nclass H4Library(object):\n    def __init__(self):\n        self.library = CDLL(Path(__file__).parent.joinpath('libh4.so'))\n\n        self.library.energy_corr_h4.argtypes = [\n            c_long,\n            POINTER(Atom),\n            POINTER(Coord),\n            H4Parameters,\n        ]\n\n        self.library.energy_corr_h4.restype = c_double\n\n        self.library.energy_corr_hh_rep.argtypes = [\n            c_long,\n            POINTER(Atom),\n            POINTER(Coord),\n            H4Parameters,\n        ]\n\n        self.library.energy_corr_hh_rep.restype = c_double\n\n    def H4Correction(self, natoms, positions, numbers, parameters):\n\n        atom = np.zeros(natoms, dtype=[('x', c_double), ('y', c_double), ('z', c_double), ('e', c_long)])\n        atom['x'] = np.asarray(positions)[:, 0]\n        atom['y'] = np.asarray(positions)[:, 1]\n        atom['z'] = np.asarray(positions)[:, 2]\n        atom['e'] = np.asarray(numbers)\n        gradient = np.zeros((natoms, 3), dtype=c_double)\n\n        args = [\n            c_long(natoms),\n            atom.ctypes.data_as(POINTER(Atom)),\n            gradient.ctypes.data_as(POINTER(Coord)),\n            H4Parameters(**parameters),\n        ]\n\n        energy = self.library.energy_corr_h4(*args)\n\n        return energy, gradient\n\n    def HHRepulsion(self, natoms, positions, numbers, parameters):\n        atom = np.zeros(natoms, dtype=[('x', c_double), ('y', c_double), ('z', c_double), ('e', c_long)])\n        atom['x'] = np.asarray(positions)[:, 0]\n        atom['y'] = np.asarray(positions)[:, 1]\n        atom['z'] = np.asarray(positions)[:, 2]\n        atom['e'] = np.asarray(numbers)\n        gradient = np.zeros((natoms, 3), dtype=c_double)\n\n        args = [\n            c_long(natoms),\n            atom.ctypes.data_as(POINTER(Atom)),\n            gradient.ctypes.data_as(POINTER(Coord)),\n            H4Parameters(**parameters),\n        ]\n\n        energy = self.library.energy_corr_hh_rep(*args)\n\n        return energy, gradient\n\n    def H4Calculation(self, natoms, positions, numbers, parameters):\n        energy, gradient = self.H4Correction(natoms, positions, numbers, parameters)\n        energy2, gradient2 = self.HHRepulsion(natoms, positions, numbers, parameters)\n\n        return energy + energy2, gradient + gradient2\n", "meta": {"hexsha": "c6a6b91916a14e66676a63f90bee9e81a5bcb8d2", "size": 3140, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyh4/pyh4.py", "max_stars_repo_name": "panxl/pyh4", "max_stars_repo_head_hexsha": "8a96cf9decc357a71e370bcbe6c3cb3629da65c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyh4/pyh4.py", "max_issues_repo_name": "panxl/pyh4", "max_issues_repo_head_hexsha": "8a96cf9decc357a71e370bcbe6c3cb3629da65c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyh4/pyh4.py", "max_forks_repo_name": "panxl/pyh4", "max_forks_repo_head_hexsha": "8a96cf9decc357a71e370bcbe6c3cb3629da65c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0740740741, "max_line_length": 105, "alphanum_fraction": 0.5700636943, "include": true, "reason": "import numpy", "num_tokens": 790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.18297632833836014}}
{"text": "import numpy\nfrom pylab import *\nfrom scipy.optimize import curve_fit\nfrom scipy.stats import mstats\nimport sys\nimport matplotlib.pyplot as plt\nfrom astropy import wcs\nfrom astropy import coordinates\nfrom astropy import units as u\n\nimport good_cores_getsources\nimport good_protostars_getsources\nimport proto_core_cross_match\nimport make_catalog\nimport make_CMF\nimport make_DS9_region\nimport make_plots\n\ndef core_mass_fits(region_name = 'L1157', cloud_name = 'Cepheus', distance = 325, getsources_core_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1157/120115_flat/combo/+catalogs/L1157.sw.final.reliable.ok.cat', getsources_additional_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1157/120115_flat/combo/+catalogs/L1157.sw.final.reliable.add.ok.cat', YSO_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1157/120115_flat/combo_proto/+catalogs/L1157.sw.final.reliable.ok.cat', YSO_additional_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1157/120115_flat/combo_proto/+catalogs/L1157.sw.final.reliable.add.ok.cat', high_res_coldens_image = '/mnt/scratch-lustre/jkeown/Getsources/Prepare/Images/cep1157/080615/cep1157_255_mu.image.resamp.fits', SED_figure_directory = '/mnt/scratch-lustre/jkeown/DS9_regions/HGBS_pipeline/L1157/L1157_core_SED/', CSAR_catalog = '/mnt/scratch-lustre/jkeown/DS9_regions/L1157/CSAR/CEPl1157_CSAR.dat', Dunham_YSOs_file = 'Dunham_YSOs.dat'):\n\t# These are the values in each column of \"cores_array\" and \"protostar_array\"\n\t#NO,    XCO_P,   YCO_P,  WCS_ACOOR,  WCS_DCOOR,  SIG_GLOB,  FG,  GOOD, SIG_MONO01, FM01, FXP_BEST01, FXP_ERRO01, FXT_BEST01, FXT_ERRO01, AFWH01, BFWH01, THEP01, SIG_MONO02, FM02, FXP_BEST02, FXP_ERRO02, FXT_BEST02, FXT_ERRO02, AFWH02, BFWH02, THEP02, SIG_MONO03, FM03, FXP_BEST03, FXP_ERRO03, FXT_BEST03, FXT_ERRO03, AFWH03, BFWH03, THEP03, SIG_MONO04, FM04, FXP_BEST04, FXP_ERRO04, FXT_BEST04, FXT_ERRO04, AFWH04, BFWH04, THEP04, SIG_MONO05, FM05, FXP_BEST05, FXP_ERRO05, FXT_BEST05, FXT_ERRO05, AFWH05, BFWH05, THEP05, SIG_MONO06, FM06, FXP_BEST06, FXP_ERRO06, FXT_BEST06, FXT_ERRO06, AFWH06, BFWH06, THEP06, SIG_MONO07, FM07, FXP_BEST07, FXP_ERRO07, FXT_BEST07, FXT_ERRO07, AFWH07, BFWH07, THEP07\n\n\t# These are the values in each column of the \"additional\" \"cores_array\" and \"protostar_array\"\n\t# NO    XCO_P   YCO_P PEAK_SRC01 PEAK_BGF01 CONV_SRC01 CONV_BGF01 PEAK_SRC02 PEAK_BGF02 CONV_SRC02 CONV_BGF02 PEAK_SRC03 PEAK_BGF03 CONV_SRC03 CONV_BGF03 PEAK_SRC04 PEAK_BGF04 CONV_SRC04 CONV_BGF04 PEAK_SRC05 PEAK_BGF05 CONV_SRC05 CONV_BGF05 PEAK_SRC06 PEAK_BGF06 CONV_SRC06 CONV_BGF06 PEAK_SRC07 PEAK_BGF07 CONV_SRC07 CONV_BGF07\n\n\t# Import the raw getsources core catalog (includes \"bad\" sources that don't pass HGBS selection criteria)\n\tcores_array1 = numpy.loadtxt(getsources_core_catalog,comments='!')\n\t# Find the indices of the \"good\" cores that pass HGBS selection criteria\n\tgood_core_indices = good_cores_getsources.get_good_cores(getsources_core_catalog)\n\t# Create new array of only the \"good\" cores to be used for our analysis\n\tcores_array = cores_array1[numpy.array(good_core_indices)]\n\n\t# Import the raw \"additional\" getsources catalog\n\tadditional_cores_array1 = numpy.loadtxt(getsources_additional_catalog,comments='!')\n\t# Create another new array of only the \"good\" cores from the getsources \"additional\" catalog\n\tadditional_cores_array = additional_cores_array1[numpy.array(good_core_indices)]\n\t\n\t# Import the raw getsources protostar catalog\n\tprotostar_array1 = numpy.loadtxt(YSO_catalog,comments='!', unpack=True)\n\t# Find the indices of the \"good\" protostars that pass HGBS selection criteria\n\tgood_proto_indices = good_protostars_getsources.get_good_protostars(YSO_catalog)\n\t# Create new array of only the \"good\" protostars to be used for our analysis\n\t# Not sure why the transpose below is needed, but it seems the protostar_array1\n\t# is imported transposed.  This doesn't seem to be the case for the core_array1\n\tprotostar_array = protostar_array1.T[numpy.array(good_proto_indices)]\n\t# Pull the 70micron flux and error columns to be used later\n\tflux_70um = protostar_array[:,12]\n\tflux_70um_err = protostar_array[:,13]\n\n\t# Import the raw getsources protostar catalog\n\tadditional_protostar_array1 = numpy.loadtxt(YSO_additional_catalog,comments='!', unpack=True)\n\t# Create another new array of only the \"good\" YSOs from the getsources \"additional\" catalog\n\tadditional_protostar_array = additional_protostar_array1.T[numpy.array(good_proto_indices)]\n\n\t# Cross-match the good cores and protostars arrays to find protostars that fall within a core's ellipse\n\tprint \"Cross-matching Core and Protostar Catalogs:\"\n\tprotostellar_core_indices = proto_core_cross_match.cross_match(getsources_core_catalog, YSO_catalog, high_res_coldens_image)\n\t# The first column of protostellar_core_indices is the core's index in cores_array\n\tcross_matched_core_indices = numpy.array(protostellar_core_indices[:,0])\t\n\t# The second column of protostellar_core_indices is the protostar's index in protostar_array\n\tcross_matched_proto_indices = numpy.array(protostellar_core_indices[:,1])\n\n\t# Replace the 70 micron flux measurements of protostellar cores with the protostar extraction measurements\n\tif len(cross_matched_core_indices)>0:\n\t\tfor i,j in zip(cross_matched_core_indices, cross_matched_proto_indices):\n\t\t\tcores_array[i][10]=protostar_array[j][10]\n\t\t\tcores_array[i][11]=protostar_array[j][11]\n\t\t\tcores_array[i][12]=protostar_array[j][12]\n\t\t\tcores_array[i][13]=protostar_array[j][13]\n\n\t\t\tadditional_cores_array[i][3]=additional_protostar_array[j][3]\n\t\t\tadditional_cores_array[i][4]=additional_protostar_array[j][4]\n\t\t\tadditional_cores_array[i][5]=additional_protostar_array[j][5]\n\t\t\tadditional_cores_array[i][6]=additional_protostar_array[j][6]\t\n \n\t# Calculate the deconvolved core radii\n\tAFWH05 = cores_array[:,50]\n\tBFWH05 = cores_array[:,51]\n\tA = numpy.float64(((((AFWH05)/60.)/60.)*numpy.pi)/180.) #radians\n\tA1 = numpy.float64(numpy.tan(A/2.)*2.*distance) #pc\n\tB = numpy.float64(((((BFWH05)/60.)/60.)*numpy.pi)/180.) #radians\n\tB1 = numpy.float64(numpy.tan(B/2.)*2.*distance) #pc\n\tFWHM_mean = mstats.gmean([A1,B1])\n\tHPBW = numpy.float64(((((18.2)/60.)/60.)*numpy.pi)/180.) #radians\n\tHPBW1 = numpy.float64(numpy.tan(HPBW/2.)*2.*distance) #pc\n\tR_deconv = ((FWHM_mean**2.0) - (HPBW1**2.0))**0.5 #pc\n\n\tR_deconv = numpy.where(((FWHM_mean**2.0) - (HPBW1**2.0))<=0., FWHM_mean, R_deconv)\n\n\t# Calculate the Bonnor-Ebert masses of each core based on their R_deconvolved  \n\tc_s = 0.2 #km/s at 10K\n\tG = 4.302*10**-3 #pc/M_solar (km/s)^2\n\tM_BE = (2.4*R_deconv*(c_s**2.))/G #M_solar\n\t\n\tM_BE = numpy.where(((FWHM_mean**2.0) - (HPBW1**2.0))<0, 9999., M_BE)\n\n\t# Define a function that produces a Flux given wavelength, Temp, and Mass\n\t# We will input wavelength then find T and M using least squares minimization below\n\tdef core_mass(wavelength, T, M):\n\t\t#wavelength input in microns, Temp in Kelvin, Mass in M_solar\n\t\t#returns S_v (i.e., Flux) in units of Jy  \n\t\tD = distance #parsecs to cloud\n\t\twavelength_mm = numpy.array(wavelength)*10.**-3.\n\t\texponent = 1.439*(wavelength_mm**-1)*((T/10.)**-1)\n\t\taaa = (0.12*(numpy.exp(exponent)-1.0))**-1.0\n\t\tbbb = (0.1*((numpy.array(wavelength)/300.)**-2.0))/0.01\n\t\tccc = (D/100.)**-2\n\t\tddd = wavelength_mm**-3.\n\t\treturn M*aaa*bbb*ccc*ddd\n\n\t# Define another function that calculates Mass directly from wavelength, Temp, and Flux\n\t# This will be used to find the Mass of cores that don't have reliable least-squares fits\n\tdef core_mass_from_flux(wavelength, T, S_v):\n\t\t#wavelength input in microns, Temp in Kelvin, Mass in M_solar\n\t\t#returns S_v (i.e., Flux) in units of Jy  \n\t\tD = distance #parsecs to cloud\n\t\twavelength_mm = wavelength*10.**-3.\n\t\texponent = 1.439*(wavelength_mm**-1)*((T/10.)**-1)\n\t\taaa = 0.12*(numpy.exp(exponent)-1.0)\n\t\tbbb = ((0.1*((wavelength/300.)**-2.0))/0.01)**-1.0\n\t\tccc = (D/100.)**2.0\n\t\tddd = wavelength_mm**3.0\n\t\treturn S_v*aaa*bbb*ccc*ddd\n\n\t# Define another function that calculates Mass uncertainty due to temp\n\tdef core_mass_err_dT(wavelength, T, S_v, dT):\n\t\t#wavelength input in microns, Temp in Kelvin, Mass in M_solar\n\t\t#returns S_v (i.e., Flux) in units of Jy  \n\t\tD = distance #parsecs to cloud\n\t\twavelength_mm = wavelength*10.**-3.\n\t\texponent = 1.439*(wavelength_mm**-1)*((T/10.)**-1)\n\t\taaa = 0.12*(numpy.exp(exponent))\n\t\tbbb = ((0.1*((wavelength/300.)**-2.0))/0.01)**-1.0\n\t\tccc = (D/100.)**2.0\n\t\tddd = wavelength_mm**3.0\n\t\teee = 1.439*10*(wavelength_mm**-1)*(T**-2.)\n\t\treturn S_v*aaa*bbb*ccc*ddd*dT*eee\n\n\t# Define another function that calculates Mass uncertainty due to flux\n\tdef core_mass_err_dS_v(wavelength, T, S_v, dS_v):\n\t\t#wavelength input in microns, Temp in Kelvin, Mass in M_solar\n\t\t#returns S_v (i.e., Flux) in units of Jy  \n\t\tD = distance #parsecs to cloud\n\t\twavelength_mm = wavelength*10.**-3.\n\t\texponent = 1.439*(wavelength_mm**-1)*((T/10.)**-1)\n\t\taaa = 0.12*(numpy.exp(exponent)-1.0)\n\t\tbbb = ((0.1*((wavelength/300.)**-2.0))/0.01)**-1.0\n\t\tccc = (D/100.)**2.0\n\t\tddd = wavelength_mm**3.0\n\t\treturn aaa*bbb*ccc*ddd*dS_v\n\n\t# Create some empty arrays to which we will append accepted values\n\tTemps = []\n\tMasses = []\n\tTemps_err = []\n\tMasses_err = []\n\tcounter=0\n\tnot_accepted_counter = []\n\tprotostellar_core_counter = 0\n\tmean_dust_Temp = 10.0\n\tmean_dust_Temp_err = 4.0\n\t# Designate the initial Temp and Mass guess for the least-squares fitting below\n\tguess = (20.0, 0.7)\n\t\n\tprint \"Begin SED-fitting:\"\n\t# Loop through all the \"good\" cores\n\tfor NO,    XCO_P,   YCO_P,  WCS_ACOOR,  WCS_DCOOR,  SIG_GLOB,  FG,  GOOD, SIG_MONO01, FM01, FXP_BEST01, FXP_ERRO01, FXT_BEST01, FXT_ERRO01, AFWH01, BFWH01, THEP01, SIG_MONO02, FM02, FXP_BEST02, FXP_ERRO02, FXT_BEST02, FXT_ERRO02, AFWH02, BFWH02, THEP02, SIG_MONO03, FM03, FXP_BEST03, FXP_ERRO03, FXT_BEST03, FXT_ERRO03, AFWH03, BFWH03, THEP03, SIG_MONO04, FM04, FXP_BEST04, FXP_ERRO04, FXT_BEST04, FXT_ERRO04, AFWH04, BFWH04, THEP04, SIG_MONO05, FM05, FXP_BEST05, FXP_ERRO05, FXT_BEST05, FXT_ERRO05, AFWH05, BFWH05, THEP05, SIG_MONO06, FM06, FXP_BEST06, FXP_ERRO06, FXT_BEST06, FXT_ERRO06, AFWH06, BFWH06, THEP06, SIG_MONO07, FM07, FXP_BEST07, FXP_ERRO07, FXT_BEST07, FXT_ERRO07, AFWH07, BFWH07, THEP07 in cores_array:\n\t\tnot_accepted = False\n\t\tN_SED_counter = 0\n\t\n\t\tfig = plt.figure()\n\t\t\t\n\t\t# Proceed with starless core SED-fitting procedure\n\t\t# Determine how many bands the core has significant flux measurements\n\t\tif SIG_MONO01 > 5.0:\n\t\t\tN_SED_counter+=1\n\t\tif SIG_MONO02 > 5.0:\n\t\t\tN_SED_counter+=1\n\t\tif SIG_MONO04 > 5.0:\n\t\t\tN_SED_counter+=1\n\t\tif SIG_MONO06 > 5.0:\n\t\t\tN_SED_counter+=1\n\t\tif SIG_MONO07 > 5.0:\n\t\t\tN_SED_counter+=1\n\t\t# If the core has more than three bands in which it is significant, \n\t\t# and the 350um Flux is higher than the 500um flux, fit the SED\n\t\t# over the 70-500um bands\n\t\tif N_SED_counter>=3 and FXT_BEST06>FXT_BEST07:\n\t\t\tflux_run1 = [FXT_BEST01, FXT_BEST02, FXT_BEST04, FXT_BEST06, FXT_BEST07]\n\t\t\tflux_err_run1 = [FXT_ERRO01, FXT_ERRO02, FXT_ERRO04, FXT_ERRO06, FXT_ERRO07]\n\t\t\t\n\t\t\tflux_run2 = [FXT_BEST02, FXT_BEST04, FXT_BEST06, FXT_BEST07]\n\t\t\tflux_err_run2 = [FXT_ERRO02, FXT_ERRO04, FXT_ERRO06, FXT_ERRO07]\n\n\t\t\twavelength_run1=[70., 160.,250.,350.,500.]\n\t\t\twavelength_run2=[160.,250.,350.,500.]\n\t\t\ttry:\n\t\t\t\tpopt,pcov = curve_fit(core_mass, wavelength_run1, flux_run1, p0=guess, sigma=flux_err_run1)\n\t\t\texcept RuntimeError:\n\t\t\t\tpopt = [-9999., -9999.]\n\t\t\t# Perform a second round of least squares fitting (without 70um point)\n\t\t\ttry:\n\t\t\t\tpopt2, pcov2 = curve_fit(core_mass, wavelength_run2, flux_run2, p0=guess, sigma=flux_err_run2)\n\t\t\texcept RuntimeError:\n\t\t\t\tpopt2 = [-1., -1.]\n\t\t\t# If the best fit Mass from the two fits varies by more than a factor of 2,\n\t\t\t# calculate the mass from the flux of the longest wavelength with significant flux\n\t\t\tif (popt2[1]/popt[1]) > 2.0 or (popt2[1]/popt[1]) < 0.5:\n\t\t\t\tnot_accepted = True\n\t\t\t\tnot_accepted_counter.append(\"no_SED_fit\")\n\t\t\t\t# Store fillers for Mass and T\n\t\t\t\t# Will re-calculate these values below using a median core dust temp\n\t\t\t\t# from the reliable SED fits \n\t\t\t\tMasses.append(9999)\n\t\t\t\tTemps.append(9999)\n\t\t\t\tTemps_err.append(9999)\n\t\t\t\tMasses_err.append(9999)\n\t\t\telse:\n\t\t\t\tnot_accepted_counter.append(\" \")\n\t\t\t\t# This means the SED fit is reliable\n\t\t\t\t# Store the best-fit T and M (from second run) to corresponding arrays\n\t\t\t\tTemps.append(popt2[0])\n\t\t\t\tMasses.append(popt2[1])\n\t\t\t\t# Find the uncertainty on T and M from the square root of the diagonal \n\t\t\t\t# terms in the covariance matrix and store in arrays\n\t\t\t\tTemps_err.append(pcov2[0][0]**0.5)\n\t\t\t\tMasses_err.append(pcov2[1][1]**0.5)\n\t\t\t\t\n\t\telse:\n\t\t\t# This means the SED is not reliable and we will instead get the Mass\n\t\t\t# directly from the longest significant wavelength's flux measurement\n\t\t\tnot_accepted = True\n\t\t\tnot_accepted_counter.append(\"no_SED_fit\")\n\t\t\t\n\t\t\t# Store fillers for Mass and T\n\t\t\t# Will re-calculate these values below using a median core dust temp\n\t\t\t# from the reliable SED fits \n\t\t\tMasses.append(9999)\n\t\t\tTemps.append(9999)\n\t\t\tTemps_err.append(9999)\n\t\t\tMasses_err.append(9999)\n\t\t# Plot the fluxes of all Herschel bands regardless of significance\t\n\t\twavelength3=[70., 160.,250.,350.,500.]\n\t\tflux3 = [FXT_BEST01, FXT_BEST02, FXT_BEST04, FXT_BEST06, FXT_BEST07]\n\t\tflux_err3 = [FXT_ERRO01, FXT_ERRO02, FXT_ERRO04, FXT_ERRO06, FXT_ERRO07]\n\t\tplt.errorbar(wavelength3,flux3,yerr=flux_err3,ecolor='r',fmt='o')\n\t\tplt.yscale('log')\n\t\tplt.xscale('log')\n\t\tplt.xlabel(\"Wavelength ($\\mu$m)\")\n\t\tplt.ylabel(\"Flux density (Jy)\")\n\n\t\t# If the SED fit is reliable, also plot the best fit line to the SED points\n\t\twavelength2=[160.,250.,350.,500.]\n\t\tif not_accepted==False:\n\t\t\tplt.plot(np.linspace(wavelength2[0]-40,wavelength2[3]+100, 50),core_mass(np.linspace(wavelength2[0]-40,wavelength2[3]+100, 50), popt2[0], popt2[1]), color=\"green\")\n\t\t\tplt.title('Core ' + str(counter+1) + ' \\n' + 'T$_{dust}$ (K) = ' + str(\"{0:.2f}\".format(round(popt2[0],2))) + ' $\\pm$ ' + str(\"{0:.2f}\".format(round(pcov2[0][0],3))) + ', Mass (M$_\\odot$) = ' + str(\"{0:.2f}\".format(round(popt2[1],2))) + ' $\\pm$ ' + str(\"{0:.2f}\".format(round(pcov2[1][1],3))))\n\t\t\t# Save the plots as a PDF in specified SED_figure_directory\n\t\t\t# The core number (in terms of the \"good\" sources) is added to file name\n\t\t\tfig.savefig(SED_figure_directory + 'core' + str(counter+1) + '.pdf')\n\t\t\n\t\tplt.close(fig)\n\t\t# Keep track of the core's that have been fit\n\t\tcounter=counter+1\n\t\tprint \"Core Number \" + str(counter) + \" of \" + str(len(cores_array))\n\n\tredo_indices = numpy.where(numpy.array(Temps_err)==9999)\n\tprint \"Need to re-calculate Mass and Temp for \" + str(len(redo_indices[0])) + \" Cores\"\n\tTemps = numpy.array(Temps)\n\t\n\tmean_dust_Temp = numpy.median(numpy.delete(Temps, redo_indices))\n\tmean_dust_Temp_err = numpy.std(numpy.delete(Temps, redo_indices))\n\tprint \"We will assume a core Temp of \" + str(mean_dust_Temp) + \" +/- \" + str(mean_dust_Temp_err) + \" for those cores\"\n\t\n\tredo_indices = redo_indices[0]\n\tredo_counter = 0\n\tfor NO,    XCO_P,   YCO_P,  WCS_ACOOR,  WCS_DCOOR,  SIG_GLOB,  FG,  GOOD, SIG_MONO01, FM01, FXP_BEST01, FXP_ERRO01, FXT_BEST01, FXT_ERRO01, AFWH01, BFWH01, THEP01, SIG_MONO02, FM02, FXP_BEST02, FXP_ERRO02, FXT_BEST02, FXT_ERRO02, AFWH02, BFWH02, THEP02, SIG_MONO03, FM03, FXP_BEST03, FXP_ERRO03, FXT_BEST03, FXT_ERRO03, AFWH03, BFWH03, THEP03, SIG_MONO04, FM04, FXP_BEST04, FXP_ERRO04, FXT_BEST04, FXT_ERRO04, AFWH04, BFWH04, THEP04, SIG_MONO05, FM05, FXP_BEST05, FXP_ERRO05, FXT_BEST05, FXT_ERRO05, AFWH05, BFWH05, THEP05, SIG_MONO06, FM06, FXP_BEST06, FXP_ERRO06, FXT_BEST06, FXT_ERRO06, AFWH06, BFWH06, THEP06, SIG_MONO07, FM07, FXP_BEST07, FXP_ERRO07, FXT_BEST07, FXT_ERRO07, AFWH07, BFWH07, THEP07 in cores_array[redo_indices]:\n\t\t\n\t\t# Find the longest significant wavelength and corresponding flux\n\t\tif SIG_MONO07>5.0:\n\t\t\twave = 500.\t\t\t\t\n\t\t\tflux_fit = FXT_BEST07\n\t\t\tflux_fit_err = FXT_ERRO07\n\t\telif SIG_MONO06>5.0:\n\t\t\twave = 350.\n\t\t\tflux_fit = FXT_BEST06\n\t\t\tflux_fit_err = FXT_ERRO06\n\t\telif SIG_MONO04>5.0:\n\t\t\twave = 250.\n\t\t\tflux_fit = FXT_BEST04\n\t\t\tflux_fit_err = FXT_ERRO04\n\t\telif SIG_MONO02>5.0:\n\t\t\twave = 160.\n\t\t\tflux_fit = FXT_BEST02\n\t\t\tflux_fit_err = FXT_ERRO02\n\t\t# Find the mass corresponding to that flux measurement\n\t\t# ***This uses the median of the best-fit Temps from the cores with \n\t\t# reliable SED fits (i.e., those that pass the test above)\n\t\tMass_fit = core_mass_from_flux(wave, mean_dust_Temp, flux_fit)\n\t\t# Can add more uncertainties (e.g., calibration, etc.) below\n\t\tMass_error = (core_mass_err_dT(wave, mean_dust_Temp, flux_fit, mean_dust_Temp_err) + \n\t\t\t\t\tcore_mass_err_dS_v(wave, mean_dust_Temp, flux_fit, flux_fit_err)**2.0)**0.5\n\t\t# Store the Mass and T with uncertainties\n\t\t# Need to perform a more in-depth error analysis \n\t\tMasses[redo_indices[redo_counter]] = Mass_fit\n\t\tTemps[redo_indices[redo_counter]] = mean_dust_Temp\n\t\tTemps_err[redo_indices[redo_counter]] = mean_dust_Temp_err\n\t\tMasses_err[redo_indices[redo_counter]] = Mass_error\n\t\t\n\t\tfig = plt.figure()\n\t\twavelength3=[70., 160.,250.,350.,500.]\n\t\tflux3 = [FXT_BEST01, FXT_BEST02, FXT_BEST04, FXT_BEST06, FXT_BEST07]\n\t\tflux_err3 = [FXT_ERRO01, FXT_ERRO02, FXT_ERRO04, FXT_ERRO06, FXT_ERRO07]\n\t\tplt.errorbar(wavelength3,flux3,yerr=flux_err3,ecolor='r',fmt='o')\n\t\tplt.yscale('log')\n\t\tplt.xscale('log')\n\t\tplt.xlabel(\"Wavelength ($\\mu$m)\")\n\t\tplt.ylabel(\"Flux density (Jy)\")\n\t\tplt.title('Core ' + str(redo_indices[redo_counter]+1) + ' **Not Accepted** ' + ' \\n' + 'T$_{dust}$ (K) = ' + str(\"{0:.2f}\".format(round(mean_dust_Temp,2))) + \"$\\pm$\" + str(\"{0:.2f}\".format(round(mean_dust_Temp_err,2))) + ', Mass (M$_\\odot$) = ' + str(\"{0:.2f}\".format(round(Mass_fit,2))) + \"$\\pm$\" + str(\"{0:.2f}\".format(round(Mass_error,2))))\n\t\tfig.savefig(SED_figure_directory + 'core' + str(redo_indices[redo_counter]+1) + '_NA.pdf')\n\t\tplt.close(fig)\n\n\t\tredo_counter+=1\n\t\tprint \"Re-calculating Core \" + str(redo_counter) + \" of \" + str(len(redo_indices))\n\n\tunreliable = float(len(numpy.where(numpy.array(not_accepted_counter)==\"no_SED_fit\")[0]))\n\tprint 'Fraction of Unreliable SED fits: ' + str(round((unreliable/float(len(cores_array))),3))\n\tnot_accepted_counter = numpy.where(numpy.array(not_accepted_counter) == \"no_SED_fit\", not_accepted_counter, \"None\")\n\t\n\t#Replace nans if they exist in the M_BE array\n\twhere_are_nans = numpy.isnan(M_BE)\n\tM_BE[where_are_nans] = 9999\n\n\t# Calculate the alpha_BE ratio to determine prestellar cores\n\talpha_BE = numpy.array(M_BE)/numpy.array(Masses)\n\n\talpha_BE = numpy.where(((FWHM_mean**2.0) - (HPBW1**2.0))<0, 9999., alpha_BE)\n\t\n\t# Create an array indicating a core as candidate(1)/robust(2) prestellar\n\tcandidate_array = numpy.where(alpha_BE<=5.0, 1, 0)\n\trobust_candidate_array = numpy.where(alpha_BE<=2.0, 2, candidate_array)\n\t# Identify protostars in the array with the number (3)\n\tif len(cross_matched_core_indices)>0:\n\t\trobust_candidate_array[cross_matched_core_indices]=3\n\n\t# Remove protostars from the alpha_BE array and find the indices of the remaining \n\t# candidate/robust prestellar cores\n\trobust_prestellar_indices = numpy.where(numpy.delete(alpha_BE,cross_matched_core_indices)<=2.0)\n\tcandidate_prestellar_indices =  numpy.where(numpy.delete(alpha_BE,cross_matched_core_indices)<=5.0)\n\n\t# Remove protostars from the Mass and Radius arrays \n\t# (we only want to plot starless cores in the Mass vs. Radius plot)\n\tR_deconv_minus_protos=numpy.delete(R_deconv, cross_matched_core_indices)\n\tMasses_minus_protos=numpy.delete(Masses, cross_matched_core_indices)\n\n\t# Find the final list of prestellar candidate/robust Masses with protostars removed\n\tprestellar_candidates = Masses_minus_protos[numpy.array(candidate_prestellar_indices[0])]\n\tprestellar_robust = Masses_minus_protos[numpy.array(robust_prestellar_indices[0])]\n\tprint 'prestellar candidates: ' + str(len(prestellar_candidates))\n\tprint 'robust prestellar candidates: ' + str(len(prestellar_robust))\n\t\n\t# Plot Mass versus Radius and save the figure\n\tfig = plt.figure()\n\tplt.scatter(R_deconv_minus_protos,Masses_minus_protos, label='starless')\n\tplt.scatter(R_deconv_minus_protos[numpy.array(candidate_prestellar_indices[0])],prestellar_candidates, color='red', label='candidate')\n\tplt.scatter(R_deconv_minus_protos[numpy.array(robust_prestellar_indices[0])],prestellar_robust, color='green', label='robust')\n\tplt.yscale('log')\n\tplt.xscale('log')\n\t#plt.legend()\n\tplt.title(region_name + ' Cores')\n\tplt.ylabel(\"Mass, M (M$_\\odot$)\")\n\tplt.xlabel(\"Deconvolved FWHM size, R (pc)\")\n\tplt.xlim([10**-3, 2*10**-1])\n\tplt.ylim([10**-3, 10**2])\n\tfig.savefig(SED_figure_directory + 'mass_vs_radius_' + region_name + '.png')\n\n\t# Append the Radius, Mass, Temperature, alpha_BE, etc. arrays as columns \n\t# onto the \"good cores\" array and save as a .dat file\n\tnumpy.savetxt(SED_figure_directory + region_name +'_good_sources.dat', numpy.column_stack((cores_array,numpy.array(R_deconv),numpy.array(FWHM_mean),numpy.array(Masses), numpy.array(Masses_err),numpy.array(Temps), numpy.array(Temps_err),numpy.array(alpha_BE),numpy.array(robust_candidate_array))))\n\n\t# Save a text file with RA and Dec of the \"good\" cores\n\t# This is needed for the SIMBAD cross-match\n\tnumpy.savetxt(SED_figure_directory + region_name +'_SIMBAD_RA_DEC.dat', zip(cores_array[:,3],cores_array[:,4]))\n\t\n\t# Create the catalog of good cores; includes flux measurments, positions, etc.\n\tmake_catalog.make_catalog(region_name=region_name, cloud_name=cloud_name, distance=distance, additional_cores_array=additional_cores_array, good_cores_array = cores_array, cross_matched_core_indices=cross_matched_core_indices, cross_matched_proto_indices=cross_matched_proto_indices, alpha_BE=alpha_BE, getsources_core_catalog = getsources_core_catalog, R_deconv=R_deconv, FWHM_mean = FWHM_mean, Masses=Masses, Masses_err = Masses_err, Temps=Temps, Temps_err=Temps_err, not_accepted_counter = not_accepted_counter, CSAR_catalog = CSAR_catalog, high_res_coldens_image = high_res_coldens_image, SED_figure_directory=SED_figure_directory, Dunham_YSOs_file=Dunham_YSOs_file)\n\n\tmake_CMF.CMF_plotter(region=region_name, Masses_minus_protos=Masses_minus_protos, prestellar_candidates=prestellar_candidates, prestellar_robust=prestellar_robust, SED_figure_directory=SED_figure_directory)\n\n\t# Create plot of column density PDF\n\t#make_plots.coldense_vs_cores(region_name=region_name, SED_figure_directory=SED_figure_directory, high_res_coldens_image=high_res_coldens_image)\n\n\t# Create histogram of background column densities for the prestellar cores \n\tmake_plots.bg_coldense_plotter(region_name=region_name, SED_figure_directory=SED_figure_directory)\n\n\t# Create histogram of core dust temperatures from the cores with reliable SED fits\n\tmake_plots.core_temp_plotter(region_name=region_name, SED_figure_directory=SED_figure_directory)\n\n\t# Create histogram of core radii for the starless core population\n\tmake_plots.core_size_plotter(region_name=region_name, SED_figure_directory=SED_figure_directory)\n\n\t# Create DS9 region files for the good core and proto catalogs at all wavelengths\n\tmake_DS9_region.make_DS9_regions_good_cores(getsources_core_catalog=getsources_core_catalog, YSO_catalog = YSO_catalog, DS9_region_directory = SED_figure_directory, catalog_type='all_cores', cross_matched_core_indices=cross_matched_core_indices, candidate_prestellar_indices=candidate_prestellar_indices, robust_prestellar_indices=robust_prestellar_indices)\n\tmake_DS9_region.make_DS9_regions_good_cores(getsources_core_catalog=getsources_core_catalog, YSO_catalog = YSO_catalog, DS9_region_directory = SED_figure_directory, catalog_type='proto', cross_matched_core_indices=cross_matched_core_indices, candidate_prestellar_indices=candidate_prestellar_indices, robust_prestellar_indices=robust_prestellar_indices)\n\tmake_DS9_region.make_DS9_regions_good_cores(getsources_core_catalog=getsources_core_catalog, YSO_catalog = YSO_catalog, DS9_region_directory = SED_figure_directory, catalog_type='prestellar_candidates', cross_matched_core_indices=cross_matched_core_indices, candidate_prestellar_indices=candidate_prestellar_indices, robust_prestellar_indices=robust_prestellar_indices)\n\tmake_DS9_region.make_DS9_regions_good_cores(getsources_core_catalog=getsources_core_catalog, YSO_catalog = YSO_catalog, DS9_region_directory = SED_figure_directory, catalog_type='prestellar_robust', cross_matched_core_indices=cross_matched_core_indices, candidate_prestellar_indices=candidate_prestellar_indices, robust_prestellar_indices=robust_prestellar_indices)\n\tif len(cross_matched_core_indices)>0:\n\t\tmake_DS9_region.make_DS9_regions_good_cores(getsources_core_catalog=getsources_core_catalog, YSO_catalog = YSO_catalog, DS9_region_directory = SED_figure_directory, catalog_type='proto_cores', cross_matched_core_indices=cross_matched_core_indices, candidate_prestellar_indices=candidate_prestellar_indices, robust_prestellar_indices=robust_prestellar_indices)\n\t\tmake_DS9_region.make_DS9_regions_good_cores(getsources_core_catalog=getsources_core_catalog, YSO_catalog = YSO_catalog, DS9_region_directory = SED_figure_directory, catalog_type='starless_cores', cross_matched_core_indices=cross_matched_core_indices, candidate_prestellar_indices=candidate_prestellar_indices, robust_prestellar_indices=robust_prestellar_indices)\n\tmake_DS9_region.make_DS9_regions_CSAR(CSAR_catalog = CSAR_catalog, DS9_region_directory=SED_figure_directory)\n\t\n\t#plt.show()\n\n#core_mass_fits()\n#core_mass_fits(region_name ='L1172', distance = 288, getsources_core_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1172/120115_flat/combo/+catalogs/L1172.sw.final.reliable.ok.cat', getsources_additional_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1172/120115_flat/combo/+catalogs/L1172.sw.final.reliable.add.ok.cat', YSO_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1172/120115_flat/combo_proto/+catalogs/L1172.sw.final.reliable.ok.cat', YSO_additional_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1172/120115_flat/combo_proto/+catalogs/L1172.sw.final.reliable.add.ok.cat', high_res_coldens_image = '/mnt/scratch-lustre/jkeown/Getsources/Prepare/Images/cep1172/082315/cep1172_255_mu.image.resamp.fits', SED_figure_directory = '/mnt/scratch-lustre/jkeown/DS9_regions/HGBS_pipeline/L1172/L1172_core_SED/', CSAR_catalog = '/mnt/scratch-lustre/jkeown/DS9_regions/L1172/CSAR/CEPl1172_CSAR.dat')\n#core_mass_fits(region_name ='L1228', distance = 200, getsources_core_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1228/120115_flat/combo/+catalogs/L1228.sw.final.reliable.ok.cat', getsources_additional_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1228/120115_flat/combo/+catalogs/L1228.sw.final.reliable.add.ok.cat', YSO_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1228/120115_flat/combo_proto/+catalogs/L1228.sw.final.reliable.ok.cat',YSO_additional_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1228/120115_flat/combo_proto/+catalogs/L1228.sw.final.reliable.add.ok.cat', high_res_coldens_image = '/mnt/scratch-lustre/jkeown/Getsources/Prepare/Images/cep1228/082315/cep1228_255_mu.image.resamp.fits', SED_figure_directory = '/mnt/scratch-lustre/jkeown/DS9_regions/HGBS_pipeline/L1228/L1228_core_SED/', CSAR_catalog = '/mnt/scratch-lustre/jkeown/DS9_regions/L1228/CSAR/CEPl1228_CSAR.dat')\n#core_mass_fits(region_name ='L1241', distance = 300, getsources_core_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1241/120115_flat/combo/+catalogs/L1241.sw.final.reliable.ok.cat', getsources_additional_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1241/120115_flat/combo/+catalogs/L1241.sw.final.reliable.add.ok.cat', YSO_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1241/120115_flat/combo_proto/+catalogs/L1241.sw.final.reliable.ok.cat', YSO_additional_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1241/120115_flat/combo_proto/+catalogs/L1241.sw.final.reliable.add.ok.cat', high_res_coldens_image = '/mnt/scratch-lustre/jkeown/Getsources/Prepare/Images/cep1241/071415/cep1241_255_mu.image.resamp.fits', SED_figure_directory = '/mnt/scratch-lustre/jkeown/DS9_regions/HGBS_pipeline/L1241/L1241_core_SED/', CSAR_catalog = '/mnt/scratch-lustre/jkeown/DS9_regions/L1241/CSAR/CEPl1241_CSAR.dat')\n#core_mass_fits(region_name ='L1251', distance = 300, getsources_core_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1251/120115_flat/combo/+catalogs/L1251.sw.final.reliable.ok.cat', getsources_additional_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1251/120115_flat/combo/+catalogs/L1251.sw.final.reliable.add.ok.cat', YSO_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1251/120115_flat/combo_proto/+catalogs/L1251.sw.final.reliable.ok.cat', YSO_additional_catalog = '/mnt/scratch-lustre/jkeown/Getsources/Extract/cep1251/120115_flat/combo_proto/+catalogs/L1251.sw.final.reliable.add.ok.cat', high_res_coldens_image = '/mnt/scratch-lustre/jkeown/Getsources/Prepare/Images/cep1251/082315/cep1251_255_mu.image.resamp.fits', SED_figure_directory = '/mnt/scratch-lustre/jkeown/DS9_regions/HGBS_pipeline/L1251/L1251_core_SED/', CSAR_catalog = '/mnt/scratch-lustre/jkeown/DS9_regions/L1251/CSAR/CEPl1251_CSAR.dat')\n", "meta": {"hexsha": "a5d006f93824d8eefcf2c76848ce4530191cf753", "size": 28985, "ext": "py", "lang": "Python", "max_stars_repo_path": "get_core_masses.py", "max_stars_repo_name": "jakeown/HGBS_pipeline", "max_stars_repo_head_hexsha": "c49b71c3400b28a9e43a1c9f02e59f3d4c2ccff2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "get_core_masses.py", "max_issues_repo_name": "jakeown/HGBS_pipeline", "max_issues_repo_head_hexsha": "c49b71c3400b28a9e43a1c9f02e59f3d4c2ccff2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "get_core_masses.py", "max_forks_repo_name": "jakeown/HGBS_pipeline", "max_forks_repo_head_hexsha": "c49b71c3400b28a9e43a1c9f02e59f3d4c2ccff2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 69.3421052632, "max_line_length": 1017, "alphanum_fraction": 0.7748490599, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 9265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.18297014944422155}}
{"text": "#Need to Update Obstacle position for 150m \n\n\nimport numpy as np\nimport math\nimport copy\nimport dubins\nimport shapely.geometry as geom\nimport threading    \nfrom statistics import median \n\n\n\n\n#Change radius of curvature for 0.9\nfrom vel_acc_to_throttle import *\n\n\nlock = threading.Lock()\ninf = 1e20\nNo_of_threads = 11\n\nacc= {}\n# acc[0] = [-1.0, -0.5, 0.5, 1.0, 2.0, 4.0]\n# acc[1] = [-1.0, -0.5, 0.5, 1.0, 2.0, 4.0]\n# acc[2] = [-1.0, -0.5, 0.5, 1.0, 2.0, 4.0]\n# acc[3] = [-1.0, -0.5, 0.5, 1.0, 2.0, 4.0]\n# acc[4] = [-1.0, -0.5, 0.5, 1.0, 2.0, 4.0]\n# acc[5] = [-1.0, 0.0, 1.0, 2.0, 4.0]\n# acc[6] = [-1.0, 0.0, 1.0, 2.0, 4.0]\n# acc[7] = [-1.0, 0.0, 1.0, 2.0, 4.0]\n# acc[8] = [-1.0, 0.0, 1.0, 2.0, 4.0]\n# acc[9] =  [-3.0, -1.0, 0.0, 1.0, 2.0, 4.0]\n# acc[10] = [-3.0, -1.0, 0.0, 1.0, 2.0, 4.0]\n# acc[11] = [-3.0, -1.0, 0.0, 1.0, 2.0, 4.0]\n# acc[12] = [-3.0, -1.0, 0.0, 1.0, 2.0, 4.0]\n# acc[13] = [-3.0, -1.0, 0.0, 1.0, 2.0, 4.0]\n# acc[14] = [-3.0, -1.0, 0.0, 1.0, 2.0, 4.0]\n# acc[15] = [-3.0, -1.0, 0.0, 1.0, 2.0, 4.0]\n# acc[16] = [-5.0, -3.0, -1.0, 0.0, 1.5, 3.0]\n# acc[17] = [-5.0, -3.0, -1.0, 0.0, 1.5, 3.0]\n# acc[18] = [-5.0, -3.0, -1.0, 0.0, 1.5, 3.0]\n# acc[19] = [-5.0, -3.0, -1.0, 0.0, 1.5, 3.0]\n# acc[20] = [-5.0, -3.0, -1.0, 0.0, 1.5, 3.0]\n# acc[21] = [-5.0, -3.0, -1.0, 0.0, 1.5]\n# acc[22] = [-5.0, -3.0, -1.2, 0.0, 1.5]\n# acc[23] = [-5.0, -3.0, -1.2, 0.0, 1.0]\n# acc[24] = [-5.0, -3.0, -1.2, 0.0, 1.0]\n# acc[25] = [-5.0, -3.0, -1.2, 0.0, 1.0]\n# acc[26] = [-5.0, -3.0, -1.3, 0.0, 1.0]\n# acc[27] = [-5.0, -3.0, -1.4, 0.0, 1.0]\n# acc[28] = [-5.0, -3.0, -1.4, 0.0, 0.5]\n# acc[29] = [-5.0, -3.0, -1.4, 0.0, 0.5]\n# acc[30] = [-5.0, -3.0, -1.5, 0.0]\nacc[8.0] = [0.0]\n\ntotal_distance = 150.0\ngrid_points = []\n\nactual_vel = {} #key = (i,j,v,t)\nactual_tim = {} #key = (i,j,v,t)\nprev_acc = {} #key = (i,j,v,t)\nc = {} #key = (j,v,t)\np = {} #key = (i,j,v,t)\nvelocities = []\ntimes= []\n\n\n#Used for updation across different layers\ntemp_tim = {}\ntemp_vel = {}\ntemp_acc = {}\ntemp_c = {}\ntemp_p = {}\n\ntemp_theta = {}\ncur_theta = {}\n#-----------------------------------------\n\n\ny_step = 0.4\nx_step = 5.0\nw = 3.6\nobs_initial_pos = [2.0, 0.0]\nobs_vel = 5.0\n\ncorner_local_coords = [[-2.5, -1.1], [-2.5, 1.1], [2.5, 1.1], [2.5, -1.1]]\n\nRadius_of_road = 20.0\n    \ndef RadiusofCurvature(start_pt, end_pt, turn_radius=30.0, step_size=1.0):\n    \"\"\"Generate points along a Dubins path connecting start point to end point.\n    Format for input / output points: (x, y, angle)\"\"\"\n    min_turn_radius = min(0.1, turn_radius)\n    satisfied = False\n    configurations = [start_pt, end_pt]\n    while not satisfied:\n        dubins_path = dubins.shortest_path(start_pt, end_pt, turn_radius)\n        configurations, _ = dubins_path.sample_many(step_size)\n        cex_found = False\n        for configuration in configurations:\n            if not (min(start_pt[0], end_pt[0]) - 0.1 <= configuration[0] <= max(start_pt[0], end_pt[0]) + 0.1 and\n                    min(start_pt[1], end_pt[1]) - 0.1 <= configuration[1] <= max(start_pt[1], end_pt[1]) + 0.1):\n                cex_found = True\n                break\n        satisfied = not cex_found\n        if cex_found:\n            # Decrease radius until finding a satisfying result.\n            # We could do a binary search but that requires a termination condition.\n            turn_radius = turn_radius*0.8\n            if turn_radius < min_turn_radius:\n                break\n    if not satisfied:\n        return 0.1\n    return turn_radius\n\n\ndef rotate_point_cw(point, theta):\n    cos_theta = math.cos(theta)\n    sin_theta = math.sin(theta)\n    return np.dot(np.array([[cos_theta, sin_theta], [-sin_theta, cos_theta]]), point)\n\ndef ObsPosition(t):\n    Total_time = (1000.0 + 2*math.pi*20.0)/obs_vel\n    t = t - Total_time * int(t/Total_time)\n    offset = t * obs_vel\n    if( obs_initial_pos[0] - offset >=0):\n        return [obs_initial_pos[0]-offset,obs_initial_pos[1], math.pi]\n    elif( obs_initial_pos[0] - (offset - math.pi * Radius_of_road) >=0 ):\n        turned_theta = (offset - obs_initial_pos[0])/Radius_of_road\n        return [-Radius_of_road*math.sin(turned_theta), -Radius_of_road + Radius_of_road*math.cos(turned_theta), math.pi + turned_theta]\n    elif( offset <= obs_initial_pos[0] + 500.0 + Radius_of_road*math.pi):\n        return [offset - obs_initial_pos[0] - Radius_of_road*math.pi, -2*Radius_of_road, 0.0]\n    elif(offset <= 2*Radius_of_road*math.pi + obs_initial_pos[0]+500.0):\n        turned_theta = (offset - Radius_of_road*math.pi - 500.0 - obs_initial_pos[0])/Radius_of_road\n        return [500.0+Radius_of_road*math.sin(turned_theta),-Radius_of_road- Radius_of_road*math.cos(turned_theta), turned_theta]\n    else:\n        return [1000.0 - offset + 2*Radius_of_road*math.pi + obs_initial_pos[0], 0.0, math.pi]\n\ndef computeD(x1,x2,y1,y2,xp,yp):\n    D = (x2 - x1) * (yp - y1) - (xp - x1) * (y2 - y1)\n    return D\n\ndef check_colliding(pt2):\n    \n    # obstacle_position = [obs_initial_pos[0] - obs_vel*pt2[3],obs_initial_pos[1]]\n    obstacle_position =  ObsPosition(pt2[3])\n    car_corner_pos = []\n    for local_coord in corner_local_coords:\n        rotated_local_coord = \\\n            rotate_point_cw(point=np.transpose(np.array(local_coord)),\n                             theta=pt2[4])\n        \n        car_corner_pos.append([pt2[0][0]+rotated_local_coord[0],pt2[0][1]+rotated_local_coord[1]])\n\n    # print(car_corner_pos)\n\n    obs_corner_pos = []\n    for local_coord in corner_local_coords:\n        # rotated_local_coord = \\\n        #     rotate_point_ccw(point=np.transpose(np.array(local_coord)),\n        #                      rotation_angle=-detected_objects[obj_ind].object_yaw_angle)\n        rotated_local_coord = \\\n            rotate_point_cw(point=np.transpose(np.array(local_coord)),\n                             theta=pt2[0][2])\n        \n        obs_corner_pos.append([obstacle_position[0] + rotated_local_coord[0],\n                             obstacle_position[1] + rotated_local_coord[1]])\n\n    # print(obs_corner_pos)\n\n    collision = 0\n    for dx in np.arange(-max(pt2[2],10),max(pt2[2],10),4.9):\n        for pos in car_corner_pos:\n            x = pos[0] + dx*math.cos(pt2[4])\n            y = pos[1] + dx*math.sin(pt2[4])\n            D1 = computeD(obs_corner_pos[0][0],obs_corner_pos[1][0],obs_corner_pos[0][1],obs_corner_pos[1][1],x,y)\n            D2 = computeD(obs_corner_pos[2][0],obs_corner_pos[3][0],obs_corner_pos[2][1],obs_corner_pos[3][1],x,y)\n            D3 = computeD(obs_corner_pos[1][0],obs_corner_pos[2][0],obs_corner_pos[1][1],obs_corner_pos[2][1],x,y)\n            D4 = computeD(obs_corner_pos[3][0],obs_corner_pos[0][0],obs_corner_pos[3][1],obs_corner_pos[0][1],x,y)\n            if ( D1*D2 >=0 and D3*D4>=0): \n                collision=1\n                break\n    return collision    \n\ndef cost(c1, pt1,pt2, off=0.0):\n    # print(pt1)\n    # print(pt2)\n    # r = RadiusofCurvature(pt1[0],pt2[0])\n    R={}\n    R[(5,0)] = inf\n    # For straight line only\n\n    deltay = abs(pt2[0][1]-pt1[0][1])\n    deltax = abs(pt2[0][0]-pt1[0][0])\n    temp = (deltax,deltay)\n    if(temp in R):\n        r = R[temp]\n    else:\n        r = RadiusofCurvature([pt1[0][0],pt1[0][1],pt1[4]],[pt2[0][0],pt2[0][1],pt2[4]])\n        if(r==30):\n            r=inf\n        R[temp] = r\n\n    obstacle_position = [obs_initial_pos[0] - obs_vel*pt2[3],obs_initial_pos[1]]\n    \n    static_cost =  c1 + math.sqrt((pt2[0][0]-pt1[0][0])**2 + (pt2[0][1]-pt1[0][1])**2) + 10.0/r + 1.0*abs(off) + 0.1*math.exp(-0.1*math.sqrt((pt2[0][0]-obstacle_position[0])**2 + (pt2[0][1]-obstacle_position[1])**2))\n\n    dynamic_cost = 15.0*(pt2[3]-pt1[3]) + (pt2[2]**2)*0.0 + 0.0*(pt2[1]**2) + 1.7e-2*(((pt2[1]-pt1[1])/(pt2[3]-pt1[3]))**2) + 1.0*(((pt2[2])**2)/r)\n    \n    return static_cost + dynamic_cost + check_colliding(pt2)*inf\n    #1.7e0 to 1.7e-2\n    #off = 1 or 0.5\n\ndef Grid1(cur_pt,dist_to_cover):\n    global grid_points\n    x1 = round(cur_pt[0],2)\n    x2 = max(x1-dist_to_cover,300.0) ##path to travel in first part of the road\n    for i in np.arange(x1,x2,-x_step):\n        gp = []\n        for j in np.arange(w,-y_step,-y_step):\n            gp.append([i,round(j,2),math.pi])\n        grid_points.append(gp)\n    return dist_to_cover - (x1-x2)\n\n\n#left\ndef Grid2(cur_pt,dist_to_cover):\n    global grid_points\n    y1 = round(cur_pt[1],2)\n    y2 = max(y1+dist_to_cover,150.0) ##path to travel in first part of the road\n    for i in np.arange(y1,y2,x_step):\n        gp = []\n        for j in np.arange(w,-y_step,-y_step):\n            gp.append([300+round(j,2),i,math.pi/2.0])\n        grid_points.append(gp)\n    return dist_to_cover - (y2-y1)\n\n\n#front\ndef Grid3(cur_pt,dist_to_cover):\n    global grid_points\n    x1 = round(cur_pt[0],2)\n    x2 = max(x1-dist_to_cover,150.0) ##path to travel in first part of the road\n    for i in np.arange(x1,x2,-x_step):\n        gp = []\n        for j in np.arange(w,-y_step,-y_step):\n            gp.append([i,round(j,2),math.pi])\n        grid_points.append(gp)\n    return dist_to_cover - (x1-x2)\n\n\n#right\ndef Grid4(cur_pt,dist_to_cover):\n    global grid_points\n    y1 = round(cur_pt[1],2)\n    y2 = max(y1-dist_to_cover,-150.0) ##path to travel in first part of the road\n    for i in np.arange(y1,y2,-x_step):\n        gp = []\n        for j in np.arange(0,-w-y_step,-y_step):\n            gp.append([300+round(j,2),i,3*math.pi/2.0])\n        grid_points.append(gp)\n    return dist_to_cover - (y1-y2)\n\n\ndef calculate_grid(cur_pt,dist_to_cover):\n    global grid_points\n    grid_points = []\n    # if(cur_pt[0]>350.0 and cur_pt[0]<=500 and cur_pt[1]>-20.0):  ##check in first part of the road\n    #     remaining_dist = Grid1(cur_pt,dist_to_cover)\n    #     if(remaining_dist >= 5):\n    #         remaining_dist = Grid2([350.0,0.0],remaining_dist)\n    #     if(remaining_dist >= 5):\n    #         remaining_dist = Grid3([350.0,-2*Radius_of_road],remaining_dist)\n    #     if(remaining_dist >= 5):\n    #         remaining_dist = Grid4([500.0,-2*Radius_of_road],remaining_dist)\n    # elif(cur_pt[0]<=350.0):\n    #     remaining_dist = Grid2(cur_pt,dist_to_cover)\n    #     if(remaining_dist >= 5):\n    #         remaining_dist = Grid3([350.0,-2*Radius_of_road],remaining_dist)\n    #     if(remaining_dist >= 5):\n    #         remaining_dist = Grid4([500.0,-2*Radius_of_road],remaining_dist)\n    # elif(cur_pt[0]>=350.0 and cur_pt[0]<500 and cur_pt[1]<-20.0):\n    #     remaining_dist = Grid3(cur_pt,dist_to_cover)\n    #     if(remaining_dist >= 5):\n    #         remaining_dist = Grid4([500.0,-2*Radius_of_road],remaining_dist)\n    #     if(remaining_dist >= 5):\n    #         remaining_dist = Grid1([500.0,0.0],remaining_dist)\n    # else:\n    #     remaining_dist = Grid4(cur_pt,dist_to_cover)    \n    #     if(remaining_dist >= 5):\n    #         remaining_dist = Grid1([500.0,0.0],remaining_dist)\n    remaining_dist = Grid1(cur_pt, dist_to_cover)\n    if(remaining_dist >= 5):\n        remaining_dist = Grid2([300.0,0.0], remaining_dist)\n\n\ndef computeTargetPath(cur_pt, dist_to_cover):\n    \n    calculate_grid(cur_pt,dist_to_cover)\n    global grid_points\n    \n    global c\n    global p\n    global actual_vel\n    global actual_tim\n    global prev_acc\n    global cur_theta\n       \n    # print(grid_points)\n\n    ##########change from here\n    X = round((w+y_step)/y_step)\n    Y = len(grid_points)\n    \n\n\n    ind2 = -1\n    min_dist = inf\n    for j in range(X):\n        cur_dist = (grid_points[0][j][1]-cur_pt[1])**2 + (grid_points[0][j][0]-cur_pt[0])**2\n        if(cur_dist < min_dist):\n            min_dist = cur_dist\n            ind2 = j\n\n    #Initialisation\n    i3 = math.ceil(cur_pt[3])\n    i4 = math.ceil(cur_pt[4])\n    c[(ind2,i3,i4)] = 0.0\n    p[(0,ind2,i3,i4)] = -1\n    actual_tim[(0,ind2,i3,i4)] = cur_pt[4]\n    actual_vel[(0,ind2,i3,i4)] = cur_pt[3]\n    prev_acc[(0,ind2,i3,i4)] = cur_pt[2]\n    cur_theta[(0,ind2,i3,i4)] = cur_pt[5]\n\n    global velocities\n    global times\n    global temp_vel\n    global temp_c\n    global temp_tim\n    global temp_p\n    global temp_acc\n    global temp_theta\n\n\n    cf = inf\n    final_pos = -1\n    \n    for i in  range(Y-1):\n        t0= threading.Thread(target=parallel_func, args=(0,i,X,))\n        t1= threading.Thread(target=parallel_func, args=(1,i,X,))\n        t2= threading.Thread(target=parallel_func, args=(2,i,X,))\n        t3= threading.Thread(target=parallel_func, args=(3,i,X,))\n        t4= threading.Thread(target=parallel_func, args=(4,i,X,))\n        t5= threading.Thread(target=parallel_func, args=(5,i,X,))\n        t6= threading.Thread(target=parallel_func, args=(6,i,X,))\n        t7= threading.Thread(target=parallel_func, args=(7,i,X,))\n        t8= threading.Thread(target=parallel_func, args=(8,i,X,))\n        t9= threading.Thread(target=parallel_func, args=(9,i,X,))\n        t10= threading.Thread(target=parallel_func, args=(10,i,X,))\n        t0.start()\n        t1.start()\n        t2.start()\n        t3.start()\n        t4.start()\n        t5.start()\n        t6.start()\n        t7.start()\n        t8.start()\n        t9.start()\n        t10.start()\n        t0.join()\n        t1.join()\n        t2.join()\n        t3.join()\n        t4.join()\n        t5.join()\n        t6.join()\n        t7.join()\n        t8.join()\n        t9.join()\n        t10.join()\n\n        # print(velocities)\n        # print(\" \")\n        v_m = median(velocities)\n        t_m = median(times)\n        v_min = v_m-5\n        v_max = v_m+5\n        t_max = t_m+5\n        t_min = t_m-5\n\n        # print(c)\n        c = {}\n        for (j,v,t) in temp_c:\n            ind_v = math.ceil(v)\n            if(v > v_max):\n                ind_v = inf\n            if(v < v_min):\n                ind_v = v_min\n            ind_t = math.ceil(t)\n            if(t > t_max):\n                ind_t = inf\n            if(t < t_min):\n                ind_t = t_min\n            \n            if ((j,ind_v,ind_t) not in c) or (c[(j,ind_v,ind_t)] > temp_c[(j,v,t)] ):\n                c[(j,ind_v,ind_t)] = temp_c[(j,v,t)]\n                p[(i+1,j,ind_v,ind_t)] = temp_p[(i+1,j,v,t)]\n                actual_vel[(i+1,j,ind_v,ind_t)] = temp_vel[(i+1,j,v,t)]\n                actual_tim[(i+1,j,ind_v,ind_t)] = temp_tim[(i+1,j,v,t)]\n                prev_acc[(i+1,j,ind_v,ind_t)] = temp_acc[(i+1,j,v,t)]\n                cur_theta[(i+1,j,ind_v,ind_t)] = temp_theta[(j,v,t)]\n                if(i==Y-2) and (cf>c[(j,ind_v,ind_t)]):\n                    cf = c[(j,ind_v,ind_t)]\n                    final_pos = (i+1,j,ind_v,ind_t)\n\n\n\n\n        velocities = []\n        times = []\n        temp_c = {}\n        temp_vel = {}\n        temp_acc = {}\n        temp_p = {}\n        temp_tim = {}\n        temp_theta = {}\n\n\n\n    travel_path = []\n    (i,j,ind2,ind3) = final_pos\n    while ( (p[(i,j,ind2,ind3)]) != -1 ):\n        travel_path = [[float(grid_points[i][j][0]),float(grid_points[i][j][1]),prev_acc[(i,j,ind2,ind3)],actual_vel[(i,j,ind2,ind3)],actual_tim[(i,j,ind2,ind3)],cur_theta[(i,j,ind2,ind3)] ]] + travel_path\n        (i,j,ind2,ind3) = (p[(i,j,ind2,ind3)])\n    \n    return travel_path\n\n\n    \n\ndef parallel_func(ind4,i,X):\n    global c\n    global p\n    global actual_vel\n    global actual_tim\n    global prev_acc\n\n\n    global temp_c\n    global temp_p\n    global temp_acc\n    global temp_vel\n    global temp_tim\n    global temp_theta\n\n    global velocities\n    global times\n    global lock\n                \n    for (j,ind2,ind3) in c:\n\n        v_i = math.ceil(actual_vel[(i,j,ind2,ind3)])\n        if(ind4 < len(acc[v_i])):\n            m1 = max(0,j-1)\n            m2 = min(X-1,j+1)\n            for k in range(m1,m2+1):\n                a_f = acc[v_i][ind4]\n                cur_cost = 0\n                v_f = ( (actual_vel[(i,j,ind2,ind3)]**2) +2*a_f*x_step)\n                if(v_f < 0):\n                    continue\n                else:\n                    v_f = v_f ** 0.5\n                if(v_f > 30):\n                    continue\n                v_f = round(v_f,4)\n                \n                ind5 = math.ceil(v_f)\n                if v_f == actual_vel[(i,j,ind2,ind3)]:\n                    t_f = x_step/v_f + actual_tim[(i,j,ind2,ind3)]\n                else: \n                    t_f = (v_f-actual_vel[(i,j,ind2,ind3)])/a_f + actual_tim[(i,j,ind2,ind3)]\n                t_f = round(t_f,2)         \n                ind6 = math.ceil(t_f)\n                \n                x1 = grid_points[i][j][0]\n                y1 = grid_points[i][j][1]\n                x2 = grid_points[i+1][k][0]\n                y2 = grid_points[i+1][k][1]\n                if(x2 < x1):\n                    if(y2 >= y1):\n                        curtheta = math.pi + math.atan((y2-y1)/(x2-x1))\n                    else:\n                        curtheta = math.pi + math.atan((y2-y1)/(x2-x1))\n                elif(x2 > x1):\n                    if(y2 >= y1):\n                        curtheta = math.atan((y2-y1)/(x2-x1))\n                    else:\n                        curtheta = 2*math.pi + math.atan((y2-y1)/(x2-x1))\n                else:\n                    if(y2>y1):\n                        curtheta = math.pi/2.0\n                    else:\n                        curtheta = 1.5*math.pi\n\n\n\n                # curtheta = grid_points[i+1][k][2] - math.atan((k-j)*y_step/x_step)\n                \n                cur_cost = cost(c[(j,ind2,ind3)],(grid_points[i][j],prev_acc[(i,j,ind2,ind3)],actual_vel[(i,j,ind2,ind3)],actual_tim[(i,j,ind2,ind3)], cur_theta[(i,j,ind2,ind3)]),(grid_points[i+1][k],a_f,v_f,t_f,curtheta),off=abs(w-k*y_step))\n                if(cur_cost > inf):\n                    continue\n                velocities.append(v_f)\n                times.append(t_f)\n                lock.acquire(True)\n                if( (k,ind5,ind6) not in temp_c) or (temp_c[(k,ind5,ind6)] > cur_cost):\n                    temp_tim[(i+1,k,ind5,ind6)] = t_f\n                    temp_c[(k,ind5,ind6)] = cur_cost\n                    temp_vel[(i+1,k,ind5,ind6)] = v_f\n                    temp_acc[(i+1,k,ind5,ind6)] = a_f\n                    temp_p[(i+1,k,ind5,ind6)] = (i,j,ind2,ind3)\n                    temp_theta[(k,ind5,ind6)] = curtheta\n                lock.release()\n                \n\n\n\n\n\ntotal_distance_covered = 0\n# cur_pt = [16.77,0.0,0.5,34.45,26.0, math.pi]\ncur_pt =  [500.0, 0.0, 0.0, 8.0, 0.0, math.pi]\n# cur_pt =  [405.0, 0.0, 1.0, 22.6937, 7.14, 3.141592653589793]\n# cur_pt = [[405.0, 0.0, math.pi], 1.5, 16.583, 8.9, math.pi]\n# c = check_colliding(cur_pt)\n# print(c)\n\n\npath = [cur_pt]\nwhile(total_distance_covered < 50):\n    path = path + computeTargetPath(cur_pt,350)\n    total_distance_covered = 50 + total_distance_covered\n    cur_pt = path[-1]\n    actual_vel = {}\n    actual_tim = {}\n    prev_acc = {}\n    c = {}\n    p = {}\n    \n    # path = path + computeTargetPath(cur_pt,50+Radius_of_road*math.pi)\n    # total_distance_covered = 50 + total_distance_covered\n    # cur_pt = path[-1]\n    # actual_vel = {}\n    # actual_tim = {}\n    # prev_acc = {}\n    # c = {}\n    # p = {}\n    \n    # print(cur_pt)\n    # print(path)\n\n\n\noutput = path\n# output = [[500.0, 0.0, 0.0, 0.0, 0.0, 3.141592653589793], [495.0, 0.0, 4.0, 6.3246, 1.58], [490.0, 0.0, 4.0, 8.9443, 2.23], [485.0, 0.0, 4.0, 10.9545, 2.73], [480.0, 0.0, 4.0, 12.6492, 3.15], [475.0, 0.0, 4.0, 14.1422, 3.52], [470.0, 0.0, 4.0, 15.492, 3.86], [465.0, 0.0, 3.0, 16.4317, 4.17], [460.0, 0.0, 3.0, 17.3205, 4.47], [455.0, 0.0, 3.0, 18.1659, 4.75], [450.0, 0.0, 3.0, 18.9737, 5.02], [445.0, 0.0, 3.0, 19.7485, 5.28], [440.0, 0.0, 3.0, 20.494, 5.53], [435.0, 0.4, 1.5, 20.8568, 5.77], [430.0, 0.8, 1.5, 21.2133, 6.01], [425.0, 1.6, 1.5, 21.564, 6.24], [420.0, 2.4, 1.5, 21.909, 6.47], [415.0, 2.4, 1.5, 22.2487, 6.7], [410.0, 1.2, 1.0, 22.4723, 6.92], [405.0, 0.0, 1.0, 22.6937, 7.14], [400.0, 0.0, 1.0, 22.913, 7.36], [395.0, 0.0, 1.0, 23.1302, 7.58], [390.0, 0.0, 1.0, 23.3454, 7.8], [385.0, 0.0, 1.0, 23.5586, 8.01], [380.0, 0.0, 1.0, 23.7699, 8.22], [375.0, 0.0, 1.0, 23.9793, 8.43], [370.0, 0.0, 1.0, 24.1869, 8.64], [365.0, 0.0, 1.0, 24.3927, 8.85], [360.0, 0.0, 1.0, 24.5968, 9.05], [355.0, 0.0, 1.0, 24.7992, 9.25], [350.0, 0.0, 1.0, 25.0, 9.45], [345.0, 0.0, 1.0, 25.1992, 9.65], [340.0, 0.0, 1.0, 25.3968, 9.85], [335.0, 0.0, 1.0, 25.5929, 10.05], [330.0, 0.0, 1.0, 25.7875, 10.24], [325.0, 0.0, 1.0, 25.9807, 10.43], [320.0, 0.0, 1.0, 26.1724, 10.62], [315.0, 0.0, 1.0, 26.3627, 10.81], [310.0, 0.0, 1.0, 26.5517, 11.0], [305.0, 0.0, 1.0, 26.7393, 11.19], [300.0, 0.0, 1.0, 26.9256, 11.38], [295.0, 0.0, 1.0, 27.1107, 11.57], [290.0, 0.0, 0.5, 27.2028, 11.75], [285.0, 0.0, 0.5, 27.2945, 11.93], [280.0, 0.0, 0.5, 27.3859, 12.11], [275.0, 0.0, 0.5, 27.477, 12.29], [270.0, 0.0, 0.5, 27.5678, 12.47], [265.0, 0.0, 0.5, 27.6583, 12.65], [260.0, 0.0, 0.5, 27.7485, 12.83], [255.0, 0.0, 0.5, 27.8384, 13.01], [250.0, 0.0, 0.5, 27.9281, 13.19], [245.0, 0.0, 0.5, 28.0175, 13.37], [240.0, 0.0, 0.5, 28.1066, 13.55], [235.0, 0.0, 0.5, 28.1954, 13.73], [230.0, 0.0, 0.5, 28.2839, 13.91], [225.0, 0.0, 0.5, 28.3722, 14.09], [220.0, 0.0, 0.5, 28.4602, 14.27], [215.0, 0.0, 0.5, 28.5479, 14.45], [210.0, 0.0, 0.5, 28.6353, 14.62], [205.0, 0.0, 0.5, 28.7225, 14.79]]\n# output = [[500.0, 0.0, 0.0, 0.0, 0.0, 3.141592653589793], [495.0, 0.0, 4.0, 6.3246, 1.58], [490.0, 0.0, 4.0, 8.9443, 2.23], [485.0, 0.0, 4.0, 10.9545, 2.73], [480.0, 0.0, 4.0, 12.6492, 3.15], [475.0, 0.0, -3.0, 11.4019, 3.57], [470.0, 0.0, 1.0, 11.8323, 4.0], [465.0, 0.0, 2.0, 12.6492, 4.41], [460.0, 0.0, -1.0, 12.2475, 4.81], [455.0, 0.0, 4.0, 13.7841, 5.19], [450.0, 0.0, -3.0, 12.6492, 5.57], [445.0, 0.0, -1.0, 12.2475, 5.97], [440.0, 0.0, -3.0, 10.9545, 6.4], [435.0, 0.4, -3.0, 9.4869, 6.89], [430.0, 0.8, -3.0, 7.746, 7.47], [425.0, 1.2, 0.0, 7.746, 8.12], [420.0, 1.6, 1.0, 8.3666, 8.74], [415.0, 2.0, 4.0, 10.4881, 9.27], [410.0, 2.4, 4.0, 12.2475, 9.71], [405.0, 2.4, 1.0, 12.6492, 10.11], [400.0, 2.4, -3.0, 11.4019, 10.53], [395.0, 2.4, 1.0, 11.8323, 10.96], [390.0, 2.4, -3.0, 10.4882, 11.41], [385.0, 2.4, -3.0, 8.9444, 11.92], [380.0, 2.0, -3.0, 7.0712, 12.54], [375.0, 1.6, 0.0, 7.0712, 13.25], [370.0, 1.2, 4.0, 9.4869, 13.85], [365.0, 0.8, 4.0, 11.4018, 14.33], [360.0, 0.4, 2.0, 12.2475, 14.75], [355.0, 0.0, 4.0, 13.7841, 15.13], [350.0, 0.0, 2.0, 14.4914, 15.48], [345.0, 0.0, 4.0, 15.8114, 15.81], [340.0, 0.0, 1.5, 16.2788, 16.12], [335.0, 0.0, 1.5, 16.7332, 16.42], [330.0, 0.0, 1.5, 17.1756, 16.71], [325.0, 0.0, 3.0, 18.0278, 16.99], [320.0, 0.0, 1.5, 18.4391, 17.26], [315.0, 0.0, -1.0, 18.1659, 17.53], [310.0, 0.0, 1.5, 18.5742, 17.8], [305.0, 0.0, 3.0, 19.3649, 18.06], [300.0, 0.0, 3.0, 20.1246, 18.31], [295.0, 0.0, 1.5, 20.4939, 18.56], [290.0, 0.0, 0.0, 20.4939, 18.8], [285.0, 0.0, 0.0, 20.4939, 19.04], [280.0, 0.0, 0.0, 20.4939, 19.28], [275.0, 0.0, 0.0, 20.4939, 19.52], [270.0, 0.0, 0.0, 20.4939, 19.76], [265.0, 0.0, 0.0, 20.4939, 20.0], [260.0, 0.0, 0.0, 20.4939, 20.24], [255.0, 0.0, 0.0, 20.4939, 20.48], [250.0, 0.0, 0.0, 20.4939, 20.72], [245.0, 0.0, 0.0, 20.4939, 20.96], [240.0, 0.0, 0.0, 20.4939, 21.2], [235.0, 0.0, 0.0, 20.4939, 21.44], [230.0, 0.0, 0.0, 20.4939, 21.68], [225.0, 0.0, 0.0, 20.4939, 21.92], [220.0, 0.0, 0.0, 20.4939, 22.16], [215.0, 0.0, 0.0, 20.4939, 22.4], [210.0, 0.0, 0.0, 20.4939, 22.64], [205.0, 0.0, 0.0, 20.4939, 22.88]]\nprint(output)\nprint(\" \")\ntarget_path = []\n# v = []\nt = []\n# a= []\nthrottle = []\nprev = -1\n\n\nfor i in output:\n    target_path.append([i[0],i[1]])\n    # a.append(i[2])\n    # v.append(i[3])\n    \n    if(prev == -1):\n        prev = (i[3],i[2])\n    else:\n        t.append(i[4])\n        throttle.append(throttle_value( (i[3]+prev[0])/2.0,i[2]))\n        prev = (i[3],i[2])\n        \nprint(throttle)\nprint(\" \")\nprint(target_path)\nprint(\" \")\nprint(t)\n\n\n\n# r= RadiusofCurvature([5.0,0.0,math.pi],[0.0,0.25,math.pi])\n# print(r)", "meta": {"hexsha": "a27a581b5b015e9d22d05a583694b7dc5cb52d7a", "size": 23526, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Optimal path/optimalPath_crossing.py", "max_stars_repo_name": "SahilDhull/autonomous", "max_stars_repo_head_hexsha": "378fc7d6c5a9c34c4e915f080fb78ed5c11195d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-02-28T12:04:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T00:42:56.000Z", "max_issues_repo_path": "src/Optimal path/optimalPath_crossing.py", "max_issues_repo_name": "SahilDhull/autonomous", "max_issues_repo_head_hexsha": "378fc7d6c5a9c34c4e915f080fb78ed5c11195d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Optimal path/optimalPath_crossing.py", "max_forks_repo_name": "SahilDhull/autonomous", "max_forks_repo_head_hexsha": "378fc7d6c5a9c34c4e915f080fb78ed5c11195d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.21, "max_line_length": 2099, "alphanum_fraction": 0.5328147581, "include": true, "reason": "import numpy", "num_tokens": 9787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.18296454902429027}}
{"text": "import logging\nimport requests\nfrom astropy.coordinates import SkyCoord\nfrom astropy.wcs import WCS\nimport astropy.units as u\n\nfrom pyobs.images import Image\nfrom .astrometry import Astrometry\n\n\nlog = logging.getLogger(__name__)\n\n\nclass AstrometryDotNet(Astrometry):\n    \"\"\"Perform astrometry using astrometry.net\"\"\"\n    __module__ = 'pyobs.images.processors.astrometry'\n\n    def __init__(self, url: str, source_count: int = 50, radius: float = 3., *args, **kwargs):\n        # URL to web-service\n        self.url = url\n        self.source_count = source_count\n        self.radius = radius\n\n    def __call__(self, image: Image):\n        \"\"\"Find astrometric solution on given image.\n\n        Writes WCSERR=1 into FITS header on failure.\n\n        Args:\n            image: Image to analyse.\n        \"\"\"\n\n        # get catalog\n        cat = image.catalog\n\n        # nothing?\n        if cat is None or len(cat) < 3:\n            log.warning('Not enough sources for astrometry.')\n            image.header['WCSERR'] = 1\n            return\n\n        # sort it and take N brightest sources\n        cat.sort(['flux'], reverse=True)\n        cat = cat[:self.source_count]\n\n        # no CDELT1?\n        if 'CDELT1' not in image.header:\n            log.warning('No CDELT1 found in header.')\n            image.header['WCSERR'] = 1\n            return\n\n        # build request data\n        scale = abs(image.header['CDELT1']) * 3600\n        data = {\n            'ra': image.header['TEL-RA'],\n            'dec': image.header['TEL-DEC'],\n            'scale_low': scale * 0.9,\n            'scale_high': scale * 1.1,\n            'radius': self.radius,\n            'nx': image.header['NAXIS1'],\n            'ny': image.header['NAXIS2'],\n            'x': cat['x'].tolist(),\n            'y': cat['y'].tolist(),\n            'flux': cat['flux'].tolist()\n        }\n\n        # log it\n        ra_dec = SkyCoord(ra=data['ra'] * u.deg, dec=data['dec'] * u.deg, frame='icrs')\n        cx, cy = image.header['CRPIX1'], image.header['CRPIX2']\n        log.info('Found original RA=%s (%.4f), Dec=%s (%.4f) at pixel %.2f,%.2f.',\n                 ra_dec.ra.to_string(sep=':', unit=u.hour, pad=True), data['ra'],\n                 ra_dec.dec.to_string(sep=':', unit=u.deg, pad=True), data['dec'],\n                 cx, cy)\n\n        # send it\n        r = requests.post(self.url, json=data)\n\n        # success?\n        if r.status_code != 200 or 'error' in r.json():\n            # set error\n            image.header['WCSERR'] = 1\n            if 'error' in r.json():\n                # \"Could not find WCS file.\" is just an info, which means that WCS was not successful\n                if r.json()['error'] == 'Could not find WCS file.':\n                    log.info('Could not determine WCS.')\n                else:\n                    log.warning('Received error from astrometry service: %s', r.json()['error'])\n            else:\n                log.error('Could not connect to astrometry service.')\n            return\n\n        else:\n            # copy keywords\n            hdr = r.json()\n            header_keywords_to_update = ['CTYPE1', 'CTYPE2', 'CRPIX1', 'CRPIX2', 'CRVAL1',\n                                         'CRVAL2', 'CD1_1', 'CD1_2', 'CD2_1', 'CD2_2']\n            for keyword in header_keywords_to_update:\n                image.header[keyword] = hdr[keyword]\n\n            # astrometry.net gives a CD matrix, so we have to delete the PC matrix and the CDELT* parameters\n            for keyword in ['PC1_1', 'PC1_2', 'PC2_1', 'PC2_2', 'CDELT1', 'CDELT2']:\n                del image.header[keyword]\n\n            # calculate world coordinates for all sources in catalog\n            image_wcs = WCS(image.header)\n            ras, decs = image_wcs.all_pix2world(image.catalog['x'], image.catalog['y'], 1)\n\n            # set them\n            image.catalog['ra'] = ras\n            image.catalog['dec'] = decs\n\n            # RA/Dec at center pos\n            final_ra, final_dec = image_wcs.all_pix2world(cx, cy, 0)\n            ra_dec = SkyCoord(ra=final_ra * u.deg, dec=final_dec * u.deg, frame='icrs')\n\n            # log it\n            log.info('Found final RA=%s (%.4f), Dec=%s (%.4f) at pixel %.2f,%.2f.',\n                     ra_dec.ra.to_string(sep=':', unit=u.hour, pad=True), data['ra'],\n                     ra_dec.dec.to_string(sep=':', unit=u.deg, pad=True), data['dec'],\n                     cx, cy)\n\n            # success\n            image.header['WCSERR'] = 0\n\n\n__all__ = ['AstrometryDotNet']\n", "meta": {"hexsha": "8ce49ad5649703e62c156064041401553ddcd0aa", "size": 4465, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyobs/images/processors/astrometry/dotnet.py", "max_stars_repo_name": "pyobs/pyobs-core", "max_stars_repo_head_hexsha": "e3401e63eb31587c2bc535f7346b7e4ef69d64ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-02-14T10:50:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T04:15:06.000Z", "max_issues_repo_path": "pyobs/images/processors/astrometry/dotnet.py", "max_issues_repo_name": "pyobs/pyobs-core", "max_issues_repo_head_hexsha": "e3401e63eb31587c2bc535f7346b7e4ef69d64ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 60, "max_issues_repo_issues_event_min_datetime": "2020-09-14T09:10:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T17:51:42.000Z", "max_forks_repo_path": "pyobs/images/processors/astrometry/dotnet.py", "max_forks_repo_name": "pyobs/pyobs-core", "max_forks_repo_head_hexsha": "e3401e63eb31587c2bc535f7346b7e4ef69d64ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-14T09:34:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T09:35:57.000Z", "avg_line_length": 35.157480315, "max_line_length": 108, "alphanum_fraction": 0.5319148936, "include": true, "reason": "import astropy,from astropy", "num_tokens": 1152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.18294606601810168}}
{"text": "# This file is part of QuTiP: Quantum Toolbox in Python.\n#\n#    Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.\n#    All rights reserved.\n#\n#    Redistribution and use in source and binary forms, with or without\n#    modification, are permitted provided that the following conditions are\n#    met:\n#\n#    1. Redistributions of source code must retain the above copyright notice,\n#       this list of conditions and the following disclaimer.\n#\n#    2. Redistributions in binary form must reproduce the above copyright\n#       notice, this list of conditions and the following disclaimer in the\n#       documentation and/or other materials provided with the distribution.\n#\n#    3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names\n#       of its contributors may be used to endorse or promote products derived\n#       from this software without specific prior written permission.\n#\n#    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n#    \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n#    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n#    PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n#    HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n#    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n#    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n#    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n#    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n#    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n#    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n###############################################################################\nimport warnings\n\nimport numpy as np\n\nfrom qutip.operators import tensor, identity, destroy, sigmax, sigmaz\nfrom qutip.states import basis\nfrom qutip.qip.circuit import QubitCircuit, Gate\nfrom qutip.qip.device.processor import Processor\nfrom qutip.qip.device.modelprocessor import ModelProcessor\nfrom qutip.qip.operations import expand_operator\nfrom qutip.qobj import Qobj\nfrom qutip.qobjevo import QobjEvo\nfrom qutip.qip.pulse import Pulse\nfrom qutip.qip.compiler.gatecompiler import GateCompiler\nfrom qutip.qip.compiler import CavityQEDCompiler\n\n\n__all__ = ['DispersiveCavityQED']\n\n\nclass DispersiveCavityQED(ModelProcessor):\n    \"\"\"\n    The processor based on the physical implementation of\n    a dispersive cavity QED system.\n    The available Hamiltonian of the system is predefined.\n    For a given pulse amplitude matrix, the processor can\n    calculate the state evolution under the given control pulse,\n    either analytically or numerically.\n    (Only additional attributes are documented here, for others please\n    refer to the parent class :class:`qutip.qip.device.ModelProcessor`)\n\n    Parameters\n    ----------\n    N: int\n        The number of qubits in the system.\n\n    correct_global_phase: float, optional\n        Save the global phase, the analytical solution\n        will track the global phase.\n        It has no effect on the numerical solution.\n\n    num_levels: int, optional\n        The number of energy levels in the resonator.\n\n    deltamax: int or list, optional\n        The sigma-x paraicient for each of the qubits in the system.\n\n    epsmax: int or list, optional\n        The sigma-z paraicient for each of the qubits in the system.\n\n    w0: int, optional\n        The base frequency of the resonator.\n\n    eps: int or list, optional\n        The epsilon for each of the qubits in the system.\n\n    delta: int or list, optional\n        The epsilon for each of the qubits in the system.\n\n    g: int or list, optional\n        The interaction strength for each of the qubit with the resonator.\n\n    t1: list or float\n        Characterize the decoherence of amplitude damping for\n        each qubit. A list of size `N` or a float for all qubits.\n\n    t2: list of float\n        Characterize the decoherence of dephasing for\n        each qubit. A list of size `N` or a float for all qubits.\n\n    Attributes\n    ----------\n    sx_ops: list\n        A list of sigmax Hamiltonians for each qubit.\n\n    sz_ops: list\n        A list of sigmaz Hamiltonians for each qubit.\n\n    cavityqubit_ops: list\n        A list of interacting Hamiltonians between cavity and each qubit.\n\n    sx_u: array_like\n        Pulse matrix for sigmax Hamiltonians.\n\n    sz_u: array_like\n        Pulse matrix for sigmaz Hamiltonians.\n\n    g_u: array_like\n        Pulse matrix for interacting Hamiltonians\n        between cavity and each qubit.\n\n    wq: list of float\n        The frequency of the qubits calculated from\n        eps and delta for each qubit.\n\n    Delta: list of float\n        The detuning with repect to w0 calculated\n        from wq and w0 for each qubit.\n    \"\"\"\n\n    def __init__(self, N, correct_global_phase=True,\n                 num_levels=10, deltamax=1.0,\n                 epsmax=9.5, w0=10., wq=None, eps=9.5,\n                 delta=0.0, g=0.01, t1=None, t2=None):\n        super(DispersiveCavityQED, self).__init__(\n            N, correct_global_phase=correct_global_phase,\n            t1=t1, t2=t2)\n        self.correct_global_phase = correct_global_phase\n        self.spline_kind = \"step_func\"\n        self.num_levels = num_levels\n        self._paras = {}\n        self.set_up_params(\n            N=N, num_levels=num_levels, deltamax=deltamax,\n            epsmax=epsmax, w0=w0, wq=wq, eps=eps,\n            delta=delta, g=g)\n        self.set_up_ops(N)\n        self.dims = [num_levels] + [2] * N\n\n    @property\n    def ctrls(self):\n        result = []\n        for pulse in self.pulses:\n            result.append(pulse.get_ideal_qobj(self.dims))\n        return result\n\n    def set_up_ops(self, N):\n        \"\"\"\n        Generate the Hamiltonians for the spinchain model and save them in the\n        attribute `ctrls`.\n\n        Parameters\n        ----------\n        N: int\n            The number of qubits in the system.\n        \"\"\"\n        # single qubit terms\n        self.a = tensor(destroy(self.num_levels))\n        self.pulses.append(\n            Pulse(self.a.dag() * self.a, [0], spline_kind=self.spline_kind))\n        for m in range(N):\n            self.pulses.append(\n                Pulse(sigmax(), [m+1], spline_kind=self.spline_kind))\n        for m in range(N):\n            self.pulses.append(\n                Pulse(sigmaz(), [m+1], spline_kind=self.spline_kind))\n        # interaction terms\n        a_full = tensor([destroy(self.num_levels)] +\n                        [identity(2) for n in range(N)])\n        for n in range(N):\n            sm = tensor([identity(self.num_levels)] +\n                        [destroy(2) if m == n else identity(2)\n                         for m in range(N)])\n            self.pulses.append(\n                Pulse(a_full.dag() * sm + a_full * sm.dag(),\n                      list(range(N+1)), spline_kind=self.spline_kind))\n\n        self.psi_proj = tensor([basis(self.num_levels, 0)] +\n                               [identity(2) for n in range(N)])\n\n    def set_up_params(\n            self, N, num_levels, deltamax,\n            epsmax, w0, wq, eps, delta, g):\n        \"\"\"\n        Save the parameters in the attribute `params` and check the validity.\n\n        Parameters\n        ----------\n        N: int\n            The number of qubits in the system.\n\n        num_levels: int\n            The number of energy levels in the resonator.\n\n        deltamax: list\n            The sigma-x paraicient for each of the qubits in the system.\n\n        epsmax: list\n            The sigma-z paraicient for each of the qubits in the system.\n\n        wo: int\n            The base frequency of the resonator.\n\n        wq: list\n            The frequency of the qubits.\n\n        eps: list\n            The epsilon for each of the qubits in the system.\n\n        delta: list\n            The delta for each of the qubits in the system.\n\n        g: list\n            The interaction strength for each of the qubit with the resonator.\n\n        Notes\n        -----\n        All parameters will be multiplied by 2*pi for simplicity\n        \"\"\"\n        sx_para = super(DispersiveCavityQED, self)._para_list(deltamax, N)\n        self._paras[\"sx\"] = sx_para\n        sz_para = super(DispersiveCavityQED, self)._para_list(epsmax, N)\n        self._paras[\"sz\"] = sz_para\n        w0 = w0 * 2 * np.pi\n        self._paras[\"w0\"] = w0\n        eps = super(DispersiveCavityQED, self)._para_list(eps, N)\n        self._paras[\"eps\"] = eps\n        delta = super(DispersiveCavityQED, self)._para_list(delta, N)\n        self._paras[\"delta\"] = delta\n        g = super(DispersiveCavityQED, self)._para_list(g, N)\n        self._paras[\"g\"] = g\n\n        # computed\n        self.wq = [np.sqrt(eps[i]**2 + delta[i]**2) for i in range(N)]\n        self.Delta = [self.wq[i] - w0 for i in range(N)]\n\n        # rwa/dispersive regime tests\n        if any([g[i] / (w0 - self.wq[i]) > 0.05 for i in range(N)]):\n            warnings.warn(\"Not in the dispersive regime\")\n\n        if any([(w0 - self.wq[i])/(w0 + self.wq[i]) > 0.05 for i in range(N)]):\n            warnings.warn(\n                \"The rotating-wave approximation might not be valid.\")\n\n    @property\n    def sx_ops(self):\n        return self.ctrls[1: self.N + 1]\n\n    @property\n    def sz_ops(self):\n        return self.ctrls[self.N + 1: 2*self.N + 1]\n\n    @property\n    def cavityqubit_ops(self):\n        return self.ctrls[2*self.N + 1: 3*self.N + 1]\n\n    @property\n    def sx_u(self):\n        return self.coeffs[1: self.N + 1]\n\n    @property\n    def sz_u(self):\n        return self.coeffs[self.N + 1: 2*self.N + 1]\n\n    @property\n    def g_u(self):\n        return self.coeffs[2*self.N + 1: 3*self.N + 1]\n\n    def get_ops_labels(self):\n        \"\"\"\n        Get the labels for each Hamiltonian.\n        \"\"\"\n        return ([r\"$a^\\dagger a$\"] +\n                [r\"$\\sigma_x^%d$\" % n for n in range(self.N)] +\n                [r\"$\\sigma_z^%d$\" % n for n in range(self.N)] +\n                [r\"$g_{%d}$\" % (n) for n in range(self.N)])\n\n    def optimize_circuit(self, qc):\n        \"\"\"\n        Take a quantum circuit/algorithm and convert it into the\n        optimal form/basis for the desired physical system.\n\n        Parameters\n        ----------\n        qc: :class:`qutip.QubitCircuit`\n            Takes the quantum circuit to be implemented.\n\n        Returns\n        -------\n        qc: :class:`qutip.QubitCircuit`\n            The circuit representation with elementary gates\n            that can be implemented in this model.\n        \"\"\"\n        self.qc0 = qc\n        self.qc1 = self.qc0.resolve_gates(\n            basis=[\"SQRTISWAP\", \"ISWAP\", \"RX\", \"RZ\"])\n        return self.qc1\n\n    def eliminate_auxillary_modes(self, U):\n        \"\"\"\n        Eliminate the auxillary modes like the cavity modes in cqed.\n        \"\"\"\n        return self.psi_proj.dag() * U * self.psi_proj\n\n    def load_circuit(self, qc):\n        \"\"\"\n        Decompose a :class:`qutip.QubitCircuit` in to the control\n        amplitude generating the corresponding evolution.\n\n        Parameters\n        ----------\n        qc: :class:`qutip.QubitCircuit`\n            Takes the quantum circuit to be implemented.\n\n        Returns\n        -------\n        tlist: array_like\n            A NumPy array specifies the time of each coefficient\n\n        coeffs: array_like\n            A 2d NumPy array of the shape (len(ctrls), len(tlist)). Each\n            row corresponds to the control pulse sequence for\n            one Hamiltonian.\n        \"\"\"\n        gates = self.optimize_circuit(qc).gates\n\n        dec = CavityQEDCompiler(\n            self.N, self._paras, self.wq, self.Delta,\n            global_phase=0., num_ops=len(self.ctrls))\n        tlist, self.coeffs, self.global_phase = dec.decompose(gates)\n        for i in range(len(self.pulses)):\n            self.pulses[i].tlist = tlist\n        # TODO The amplitude of the first control a.dag()*a\n        # was set to zero before I made this refactoring.\n        # It is probably due to the fact that\n        # it contributes only a constant (N) and can be neglected.\n        # but change the below line to np.ones leads to test error.\n        self.coeffs[0] = self._paras[\"w0\"] * np.zeros(len(tlist))\n        return tlist, self.coeffs\n", "meta": {"hexsha": "1c7462ac2ebca53e614a9f49be009f39542eb73c", "size": 12314, "ext": "py", "lang": "Python", "max_stars_repo_path": "qutip/qip/device/cavityqed.py", "max_stars_repo_name": "MartinSandeCosta/qutip", "max_stars_repo_head_hexsha": "308624c12a9c9c629a80e6233b864e3efa3eb784", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-02-09T14:27:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-09T15:19:03.000Z", "max_issues_repo_path": "qutip/qip/device/cavityqed.py", "max_issues_repo_name": "MartinSandeCosta/qutip", "max_issues_repo_head_hexsha": "308624c12a9c9c629a80e6233b864e3efa3eb784", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qutip/qip/device/cavityqed.py", "max_forks_repo_name": "MartinSandeCosta/qutip", "max_forks_repo_head_hexsha": "308624c12a9c9c629a80e6233b864e3efa3eb784", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0826210826, "max_line_length": 79, "alphanum_fraction": 0.616046776, "include": true, "reason": "import numpy", "num_tokens": 3037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.1829460538705099}}
{"text": "#!/usr/bin/env python\n\n\"\"\"\n    The purpose of this script is to edit the topology file of a system containing molecules which have a benzene ring\n    in order to create your choice of two things:\n    (1) An artificial dipole which will act as electron clouds participating in a pi bond. The dipole is\n        created by centering two virtual sites above and below the plane of the benzene ring and assigning them\n        appropriate charges values.\n    (2) Add position restraints with a given force constant to chosen atoms w.r.t. to a specified axis or axes\n\"\"\"\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nimport argparse\nimport numpy as np\nimport warnings\nimport os\nfrom LLC_Membranes.llclib import file_rw, topology\nimport mdtraj as md\n\nlocation = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))  # Location of this script\n\n\ndef initialize():\n\n    parser = argparse.ArgumentParser(description='Duplicate points periodically in the x-y directions')\n\n    parser.add_argument('-g', '--gro', default='initial.gro', type=str, help='Coordinate file')\n    parser.add_argument('-o', '--out', default='dipole.itp', type=str, help='Name of output topology file')\n    parser.add_argument('-f', '--f_const', nargs='+', default=[1000, 1000, 1000], type=float, help='Force constant')\n    parser.add_argument('-a', '--atoms', nargs='+', default=['C', 'C1', 'C2', 'C3', 'C4', 'C5'], type=str, help='Name of carbons in ring')\n    parser.add_argument('-d', '--distance', default=0.1, help='Distance to offset dipole from ring (Angstroms)')\n    parser.add_argument('-m', '--monomer', default='NAcarb11V', help='Which monomer topology is being used')\n    parser.add_argument('-A', '--axis', default='xy', help='Axis to restrain along with position restraints')\n    ######## These parameters are not implemented yet but left here since they will have some use in the future ########\n    parser.add_argument('--xlink', help='Specify this flag if the system is being crosslinked while restrained',\n                        action=\"store_true\")\n    parser.add_argument('--append', help='Specify this to prevent the topology from being re-written, and instead, add '\n                                         'restraints to the topology for other atoms', action=\"store_true\")\n    parser.add_argument('-i', '--input', type=str, default='dipole.itp', help='Name of topology file to be edited if '\n                                                                              'you use the option --append')\n    ####################################################################################################################\n    parser.add_argument('-dr', '--dihedral_restraints', action='append', nargs='+',\n                        help='Specify atom names of dihedral to be restrained, followed by angle at which to restrain'\n                             'them, the deviation from that angle allowed and the force constant to apply. For example:'\n                             '\"restrain.py -dr C1 C C6 O4 90 0 1000\" means to keep the angle between the planes formed'\n                             'by C1-C-C6 and C-C6-O4 90 degrees apart with 0 degrees of leeway and a force constant of '\n                             '1000')\n    parser.add_argument('-com', '--center_of_mass', action=\"store_true\", help=\"Add position restraints at the center of\"\n                                                                              \"mass of args.atoms\")\n    parser.add_argument('-v', '--virtual_site_parameters', nargs='+', default=['3fd', 'C', 'C2', 'C4', '.5', '.14'],\n                        help='A list in the following order : virtual site construction type, atoms to use to build '\n                             'virtual site, required length parameters (i.e. a, b, c or d) in the order specified in'\n                             'GROMACS documentation')\n    parser.add_argument('-b', '--bond_restraints', default=[.37, 1000], nargs='+', help='Bond restraint pararmeters. A'\n                        'list where the first entry is the equilibrium distance (nm) and the second entry is the force'\n                        'constant for a harmonic potential (kJ/mol/nm^2)')\n\n    args = parser.parse_args()\n\n    return args\n\n\nwarnings.filterwarnings(\"error\")  # This makes it so numpy warnings are treated as real errors\n\n\ndef virtual_sites(all_coords, monomers, valence, a, b, c, funct):\n\n    n_atoms = np.shape(all_coords)[1] - (1 / valence) * monomers\n    atoms_per_molecule = n_atoms / monomers  # subtract valence to exclude counterion\n\n    n_vsites = monomers * 2  # number of virtual sites need to create a dipole (2 per ring)\n    vsites = np.zeros([8, n_vsites])\n    vsites[4, :] = funct\n    vsites[5, :] = a  # all a and b values are the same\n    vsites[6, :] = b\n\n    for i in range(monomers):\n        for j in range(2):\n            vsites[0, i * 2 + j] = n_atoms + i * 2 + j + 1  # new atoms were placed at the end of the .gro file\n            vsites[1:4, i * 2 + j] = [i * atoms_per_molecule + 1, i * atoms_per_molecule + 3,\n                              i * atoms_per_molecule + 5]\n            vsites[7, i * 2 + j] = (-1)**j * c\n\n    return vsites\n\n\ndef exclusions(coord_file, monomers, valence, toplines, atoms, n_atoms, vsites):\n    \"\"\"\n    :param coord_file: the original .gro file stored in a list\n    :param monomers: number of monomers\n    :param valence: charge on ions\n    :param atoms: the names of the atoms which should be excluded\n    :param n_atoms: the number of atoms total\n    :return: a list of exclusions\n    \"\"\"\n    n_atoms = np.shape(all_coords)[1] - (1 / valence) * monomers\n    atoms_per_molecule = n_atoms / monomers  # subtract valence to exclude counterion (includes new PI atoms)\n\n    n_excluded = len(atoms) + 1  # number of atoms excluded. +1 because it will be excluded from it complementary vsite\n\n    n_exclusions = monomers * 2  # number of exclusions to be specified (one for each vsite)\n    exclusions = np.zeros([n_excluded + 1, n_exclusions])  # the first entry is the virtual site itself\n\n    for i in range(np.shape(vsites)[1]):\n        exclusions[0, i] = vsites[0, i]\n        # add exclusion from the complementary vsite. This is pretty specific to the format and will likely need to be\n        # re-written eventually\n        if i % 2 == 0:\n            exclusions[1, i] = vsites[0, i + 1]\n        elif i % 2 == 1:\n            exclusions[1, i] = vsites[0, i - 1]\n\n    x = 0\n    for i in range(monomers):\n        a = 2\n        for j in range(atoms_per_molecule):\n            line = i*atoms_per_molecule + j + toplines\n            if str.strip(coord_file[line][10:15]) in atoms:\n                exclusions[a, x] = int(coord_file[line][15:20])\n                exclusions[a, x + 1] = int(coord_file[line][15:20])\n                a += 1\n        x += 2\n\n    return exclusions\n\n\ndef dihedral_restraints(file, atoms):\n    \"\"\"\n    This function needs to be moved into the class\n    \"\"\"\n\n    ndihedrals = len(atoms)\n\n    all_restraints = np.zeros([0, 8])\n    for n in range(ndihedrals):\n\n        atom_numbers = []\n        d = np.zeros([4])\n        count = 0\n        for line in file:\n            atom = str.strip(line[10:15])  # name of atom at that line\n            if atom in atoms[n]:\n                d[atoms[n].index(atom)] = int(line[15:20])  # atom number placed in d in order that dihedral was passed\n                if np.count_nonzero(d) == 4:  # and len(atom_numbers) % 8 == 0:\n                    if count % 2 == 1:\n                        for i in range(4):\n                            atom_numbers.append(d[i])\n                    d = np.zeros([4])\n                    count += 1\n\n        restraints = np.zeros([len(atom_numbers)//4, 8])\n        for i in range(len(atom_numbers)//4):\n            d = 4 * i\n            restraints[i, :] = [atom_numbers[d], atom_numbers[d + 1], atom_numbers[d + 2], atom_numbers[d + 3], 1, atoms[n][4],\n                                atoms[n][5], atoms[n][6]]\n\n        all_restraints = np.concatenate((all_restraints, restraints))\n\n    return all_restraints\n\n\nclass RestrainedTopology(object):\n\n    def __init__(self, gro, res, atoms, name='restrained', com=False, xlink=False,\n                 vparams=None):\n        \"\"\" Write topology to restrain one or more residues with position restraints in GROMACS\n\n        :param gro: coordinate file where restraints will be placed\n        :param res: name of residue where position restraints are being added\n        :param atoms: name of atoms to be restrained in res\n        :param name: name of output topology file\n        :param com: restrain center of mass of atoms instead of individual atoms\n        :param xlink : whether or not the system is in the process of being crosslinked\n        :param vparams: A list in the following order : virtual site construction type, atoms to use to build virtual\n               site, required length parameters (i.e. a, b, c or d) in the order specified in GROMACS documentation\n        \"\"\"\n\n        topology.fix_resnumbers(gro)\n        t = md.load(gro)\n\n        if type(res) is str:\n            res = [res]\n            atoms = [atoms]\n\n        self.all_coords = t.xyz[0, :, :]  # all coordinates for system\n        self.atom_numbers = []\n        for i in range(len(atoms)):\n            self.atom_numbers.append([a.index + 1 for a in t.topology.atoms if a.name in atoms[i] and a.residue.name ==\n                                      res[i]])\n\n        self.atoms = t.n_atoms  # number of atoms in full system\n        self.nmon = [len(self.atom_numbers[i]) // len(atoms[i]) for i in range(len(atoms))]  # number of monomer residues\n        self.name = name  # name of output files (.itp, .gro if you are using centers of masses)\n        self.residue = res  # name of residue(s) to which position restraints are being applied\n        self.LC = [topology.LC('%s' % r) for r in self.residue]  # everything we can know about the residue\n        self.com = com\n\n        # self.keep = np.array([a.index for a in t.topology.atoms if a.name in atoms])  # atoms to keep\n        # self.atom_numbers = self.keep + 1  # numbers (not indices) of atoms to keep\n        # self.coords = self.all_coords[self.keep, :]  # coordinates of atoms in keep\n\n        if self.com:  # add center of mass virtual site\n\n            # These things are only needed for center of mass virtual site construction\n            self.ids = [a.name for a in t.topology.atoms]  # names of all atoms in system\n            self.res = [a.residue.name for a in t.topology.atoms]  # residue names of all atoms in system\n            self.vparams = vparams\n            self.vatoms_numbers = [a.index + 1 for a in t.topology.atoms if a.name in vparams]\n            self.box = t.unitcell_vectors[0, :, :]  # box vectors in mdtraj formate\n            self.box_gromacs = [self.box[0, 0], self.box[1, 1], self.box[2, 2], self.box[0, 1], self.box[2, 0],\n                                self.box[1, 0], self.box[0, 2], self.box[1, 2],\n                                self.box[2, 0]]  # gromacs format box vects\n\n            with open('%s/../top/Monomer_Tops/%s.itp' % (location, self.residue), 'r') as f:\n                residue_top = []\n                for line in f:\n                    residue_top.append(line)\n\n            atoms_index = 0\n            while residue_top[atoms_index].count('[ atoms ]') == 0:\n                atoms_index += 1\n\n            while residue_top[atoms_index] != '\\n':\n                atoms_index += 1\n\n            residue_top.insert(atoms_index, '{:>6d}{:>5s}{:>6d}{:>6s}{:>6s}{:>5d}{:>13.6f}{:>13.6f}\\n'.format(\n                self.LC.natoms + 1, 'hc_d', 1, self.LC.residues[0], 'HD', self.LC.natoms + 1, 0, 0))\n\n            if self.vparams[0] == '3fd':\n                # 'a' = 0.5 and 'b' = 0.14 (aromatic carbon bond length (nm)) puts a vsite in the middle of benzene\n                # if the constructor atoms are 3 non-adjacent carbons from the ring\n                residue_top.append('[ virtual_sites3 ]\\n')\n                residue_top.append('{:<6d}{:<6d}{:<6d}{:<6d}{:<6d}{:<8.4f}{:<8.4f}\\n'.format(self.LC.natoms + 1,\n                                    self.vatoms_numbers[0], self.vatoms_numbers[1], self.vatoms_numbers[2], 2,\n                                    float(self.vparams[-2]), float(self.vparams[-1])))\n            else:\n                print('Your choice of virtual site has not yet been implemented')\n                exit()\n\n            # groups = np.reshape(self.coords, (len(self.keep) // len(atoms), len(atoms), 3))\n            # centers_of_mass = np.mean(groups, axis=1)\n            # self.coords = centers_of_mass  # redefine coordinates as centers of mass\n\n            file_rw.write_assembly(residue_top, '%s.itp' % self.name, self.nmon, xlink=xlink)\n\n            # now the dummies need to be added to the .gro file. They are placed at the end of the residue section\n            # This loop works for a single virtual site per monomer. It will need to be modified if multiple sites\n            # are to be constructed.\n            insert_ndx = self.LC.natoms\n            self.atom_numbers = []  # redefine this since everything is renumbered\n            for i in range(self.nmon):\n                ndx = (i + 1)*insert_ndx + i\n                self.ids.insert(ndx, 'HD')\n                self.res.insert(ndx, 'HII')  # should make this more general\n                self.all_coords = np.insert(self.all_coords, ndx, np.array([0, 0, 0]), axis=0)\n                self.atom_numbers.append(ndx + 1)\n\n            file_rw.write_gro_pos(self.all_coords, '%s.gro' % self.name, ids=self.ids, res=self.res, box=self.box_gromacs)\n        else:\n\n            file_rw.write_assembly(res, '%s.itp' % self.name, self.nmon, xlink=xlink)\n\n        with open('%s.itp' % self.name, 'r') as f:\n            self.topology = []\n            for line in f:\n                self.topology.append(line)\n\n    def add_position_restraints(self, axis, f_const):\n        \"\"\"\n        Restrain the selected atoms in desired directions\n        :param axis: which direction to restrain (xyz, xy, z, xz .. etc.)\n        :param f_const: force constant in each direction. Order of force constants matches that of axis argument\n        :return: an array of position restraints formatted for easy writing into the topology (.itp)\n        \"\"\"\n\n        self.topology.append(\"\\n[ position_restraints ]\\n\")\n\n        fc = np.zeros([3])\n        for i, a in enumerate(axis):\n            if a == 'x':\n                fc[0] = f_const[i]\n            if a == 'y':\n                fc[1] = f_const[i]\n            if a == 'z':\n                fc[2] = f_const[i]\n\n        atom_numbers = []\n        for i in self.atom_numbers:\n            atom_numbers += i\n\n        restraints = np.zeros([5, len(atom_numbers)])  # organize them into a list which can be translated to a topology\n        for i in range(len(atom_numbers)):\n            restraints[:, i] = [atom_numbers[i], 1, fc[0], fc[1], fc[2]]  # See: http://www.gromacs.org/Documentation/How-tos/Position_Restraints\n            self.topology.append('{:6d}{:6d}{:1s}{:9f}{:1s}{:9f}{:1s}{:9f}\\n'.format(int(restraints[0, i]),\n                                int(restraints[1, i]),'', restraints[2, i], '', restraints[3, i], '', restraints[4, i]))\n\n    def add_distance_restraint_columns(self, b0, kb, layers=20, pores=4):\n        \"\"\"\n        Add distance constraints to centers of mass of monomer head groups. This is a function specialized for an\n        HII system built with build.py (without the flag -columns).\n        :param b0 : equilibrium distance\n        :param kb : force constant for harmonic potential\n        :param layers : layers per pore\n        :param pores : number of pore columns\n        \"\"\"\n\n        self.topology.append(\"\\n[ bonds ]\\n\")\n        mpl = int(self.nmon / 4 / layers)  # monomers per layer\n\n        for p in range(pores):\n            for l in range(layers):\n                for m in range(mpl):\n                    if l == (layers - 1):  # handles periodicity\n                        self.topology.append('{:<6d}{:<6d}{:<6d}{:<6.1f}{:<6.1f}\\n'.format(self.atom_numbers[layers*mpl*p\n                                             + l*mpl + m], self.atom_numbers[layers*mpl*p + m], 6, b0, kb))\n                    else:\n                        self.topology.append('{:<6d}{:<6d}{:<6d}{:<6.1f}{:<6.1f}\\n'.format(self.atom_numbers[layers*mpl*p\n                                             + l*mpl + m], self.atom_numbers[layers*mpl*p + (l + 1)*mpl + m], 6, b0, kb))\n\n        # Tether together columns (this is temporary so variables are hard coded)\n        b0 = 2*0.6*np.sin(36*np.pi/180)\n        kb = 1000\n        for p in range(pores):\n            for l in range(layers):\n                for m in range(mpl):\n                    if m == (mpl - 1):  # handles periodicity\n                        self.topology.append('{:<6d}{:<6d}{:<6d}{:<6.3f}{:<6.1f}\\n'.format(self.atom_numbers[layers*mpl*p\n                                             + l*mpl + m], self.atom_numbers[layers*mpl*p + l*mpl], 6, b0, kb))\n                    else:\n                        self.topology.append('{:<6d}{:<6d}{:<6d}{:<6.3f}{:<6.1f}\\n'.format(self.atom_numbers[layers*mpl*p\n                                             + l*mpl + m], self.atom_numbers[layers*mpl*p + l*mpl + m + 1], 6, b0, kb))\n\n    def write_topology(self):\n        with open('%s.itp' % self.name, 'w') as f:\n            for line in self.topology:\n                f.write(line)\n\n\nif __name__ == \"__main__\":\n\n    args = initialize()\n\n    top = RestrainedTopology(args.gro, args.monomer, args.atoms, com=args.center_of_mass,\n                             vparams=args.virtual_site_parameters)\n    # top.add_distance_restraint_columns(float(args.bond_restraints[0]), float(args.bond_restraints[1]))\n    top.add_position_restraints(args.axis, args.f_const)\n    top.write_topology()\n", "meta": {"hexsha": "4fbffeefd2b740350592b5fc106bf0c4ac1e75b1", "size": 17877, "ext": "py", "lang": "Python", "max_stars_repo_path": "LLC_Membranes/setup/restrain.py", "max_stars_repo_name": "shirtsgroup/LLC_Membranes", "max_stars_repo_head_hexsha": "e94694f298909352d7e9d912625314a1e46aa5b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-06-18T15:26:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-11T18:57:39.000Z", "max_issues_repo_path": "LLC_Membranes/setup/restrain.py", "max_issues_repo_name": "shirtsgroup/LLC_Membranes", "max_issues_repo_head_hexsha": "e94694f298909352d7e9d912625314a1e46aa5b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-08-22T20:11:46.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T22:35:17.000Z", "max_forks_repo_path": "LLC_Membranes/setup/restrain.py", "max_forks_repo_name": "shirtsgroup/LLC_Membranes", "max_forks_repo_head_hexsha": "e94694f298909352d7e9d912625314a1e46aa5b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-07-06T15:41:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T17:59:13.000Z", "avg_line_length": 51.223495702, "max_line_length": 145, "alphanum_fraction": 0.5786765117, "include": true, "reason": "import numpy", "num_tokens": 4546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.3345894545235253, "lm_q1q2_score": 0.18293282003973224}}
{"text": "\"\"\" Clustered Hierarchical Entropy-scaling Manifold Mapping.\n\n# TODO: https://docs.python.org/3/whatsnew/3.8.html#f-strings-support-for-self-documenting-expressions-and-debugging\n\"\"\"\nimport logging\nimport pickle\nimport random\nfrom collections import deque\nfrom operator import itemgetter\nfrom queue import Queue\nfrom threading import Thread\nfrom typing import Set, Dict, Iterable, BinaryIO, List, Union\n\nimport numpy as np\nfrom scipy.spatial.distance import pdist, cdist\n\nfrom chess.types import Data, Radius, Vector, Metric\n\nSUBSAMPLE_LIMIT = 100\nBATCH_SIZE = 10_000\nLOG_LEVEL = logging.INFO\n\nlogging.basicConfig(\n    level=LOG_LEVEL,\n    format=\"%(asctime)s:%(levelname)s:%(name)s:%(module)s.%(funcName)s:%(message)s\"\n)\n\n\nclass Cluster:\n    \"\"\" A cluster of points.\n\n    Clusters maintain references to their their children, the manifold to which they belong,\n    the indices of the points they are responsible for, and neighbors (clusters with which they overlap).\n\n    You can compare clusters, hash them, partition them, perform tree search, prune them, and more.\n    In general, they implement methods that create and utilize the underlying tree structure used by Manifold.\n    \"\"\"\n\n    def __init__(self, manifold: 'Manifold', argpoints: Vector, name: str, **kwargs):\n        \"\"\"\n        A Cluster needs to know the manifold it belongs to and the indexes of the points it contains.\n        The name of a Cluster indicated its position in the tree.\n\n        :param manifold: The manifold to which the cluster belongs.\n        :param argpoints: A list of indexes of the points that belong to the cluster.\n        :param name: The name of the cluster indicating its position in the tree.\n        \"\"\"\n        logging.debug(f\"Cluster(name={name}, argpoints={argpoints})\")\n        self.manifold: 'Manifold' = manifold\n        self.argpoints: Vector = argpoints\n        self.name: str = name\n\n        # TODO: Consider relying on Graph.edges instead of having neighbors be a member of Cluster.\n        self.neighbors: Dict['Cluster', float] = dict()  # key is neighbor, value is distance to neighbor\n        self.children: Set['Cluster'] = set()\n\n        self.__dict__.update(**kwargs)\n\n        # This is used during Cluster.from_json().\n        if not argpoints and self.children:\n            self.argpoints = [p for child in self.children for p in child.argpoints]\n        elif not argpoints:\n            raise ValueError(f\"Cluster {name} needs argpoints.\")\n        return\n\n    def __eq__(self, other: 'Cluster') -> bool:\n        \"\"\" Two clusters are identical if they have the same name and the same set of points. \"\"\"\n        return all((\n            self.name == other.name,\n            set(self.argpoints) == set(other.argpoints),\n        ))\n\n    def __hash__(self):\n        \"\"\" Be careful to use this only with other clusters. \"\"\"\n        return hash(self.name)\n\n    def __str__(self) -> str:\n        return self.name or 'root'\n\n    def __repr__(self) -> str:\n        return ','.join([self.name, ';'.join(map(str, self.argpoints))])\n\n    def __len__(self) -> int:\n        \"\"\" Returns cardinality of the set of points.\n        TODO: Consider deprecating __len__ and providing Cluster().cardinality\n        \"\"\"\n        return len(self.argpoints)\n\n    def __iter__(self) -> Vector:\n        # Iterates in batches, instead of by element.\n        for i in range(0, len(self), BATCH_SIZE):\n            yield self.argpoints[i:i + BATCH_SIZE]\n\n    def __contains__(self, point: Data) -> bool:\n        \"\"\" Check weather the given point could be inside this cluster. \"\"\"\n        return self.overlaps(point=point, radius=0.)\n\n    @property\n    def metric(self) -> str:\n        \"\"\" The metric used in the manifold. \"\"\"\n        return self.manifold.metric\n\n    @property\n    def depth(self) -> int:\n        \"\"\" The depth in the tree at which the cluster exists. \"\"\"\n        return len(self.name)\n\n    @property\n    def points(self) -> Data:\n        \"\"\" An iterator, in batches, over the points in the Clusters. \"\"\"\n        for i in range(0, len(self), BATCH_SIZE):\n            yield self.manifold.data[self.argpoints[i:i + BATCH_SIZE]]\n\n    @property\n    def samples(self) -> Data:\n        \"\"\" Returns the samples from the cluster. Samples are used in computing approximate centers and poles.\n        \"\"\"\n        return self.manifold.data[self.argsamples]\n\n    @property\n    def argsamples(self) -> Vector:\n        \"\"\" Indices used to retrieve samples.\n\n        Ensures that there are at least 2 different points in samples,\n        otherwise returns a single sample that represents the entire cluster.\n        i.e., if len(argsamples) == 1, the cluster contains only duplicates.\n        \"\"\"\n        if '_argsamples' not in self.__dict__:\n            logging.debug(f\"building cache for {self}\")\n            if len(self) <= SUBSAMPLE_LIMIT:\n                n = len(self.argpoints)\n                indices = self.argpoints\n            else:\n                n = int(np.sqrt(len(self)))\n                indices = list(np.random.choice(self.argpoints, n, replace=False))\n\n            # Handle Duplicates.\n            if pdist(self.manifold.data[indices], self.metric).max(initial=0.) == 0.:\n                indices = np.unique(self.manifold.data[self.argpoints], return_index=True, axis=0)[1]\n                indices = [self.argpoints[i] for i in indices][:n]\n\n            # Cache it.\n            self.__dict__['_argsamples'] = indices\n        return self.__dict__['_argsamples']\n\n    @property\n    def nsamples(self) -> int:\n        \"\"\" The number of samples for the cluster. \"\"\"\n        return len(self.argsamples)\n\n    @property\n    def centroid(self) -> Data:\n        \"\"\" The Geometric Mean of the cluster. \"\"\"\n        return np.average(self.samples, axis=0)\n\n    @property\n    def medoid(self) -> Data:\n        \"\"\" The Geometric Median of the cluster. \"\"\"\n        return self.manifold.data[self.argmedoid]\n\n    @property\n    def argmedoid(self) -> int:\n        \"\"\" The index used to retrieve the medoid. \"\"\"\n        if '_argmedoid' not in self.__dict__:\n            logging.debug(f\"building cache for {self}\")\n            _argmedoid = np.argmin(cdist(self.samples, self.samples, self.metric).sum(axis=1))\n            self.__dict__['_argmedoid'] = self.argsamples[int(_argmedoid)]\n        return self.__dict__['_argmedoid']\n\n    @property\n    def radius(self) -> Radius:\n        \"\"\" The radius of the cluster.\n\n        Computed as distance from medoid to the farthest point in the cluster.\n        \"\"\"\n        if '_min_radius' in self.__dict__:\n            logging.debug(f'taking min_radius from {self}')\n            return self.__dict__['_min_radius']\n        elif '_radius' not in self.__dict__:\n            logging.debug(f'building cache for {self}')\n            _ = self.argradius\n        return self.__dict__['_radius']\n\n    @property\n    def argradius(self) -> int:\n        \"\"\" The index used to retrieve the point which is farthest from the medoid. \"\"\"\n        if ('_argradius' not in self.__dict__) or ('_radius' not in self.__dict__):\n            logging.debug(f'building cache for {self}')\n\n            def argmax_max(b):\n                distances = self.distance(self.manifold.data[b])\n                argmax = int(np.argmax(distances))\n                return b[argmax], distances[argmax]\n\n            argradii_radii = [argmax_max(batch) for batch in iter(self)]\n            _argradius, _radius = max(argradii_radii, key=itemgetter(1))\n            self.__dict__['_argradius'], self.__dict__['_radius'] = int(_argradius), float(_radius)\n        return self.__dict__['_argradius']\n\n    @property\n    def local_fractal_dimension(self) -> float:\n        \"\"\" The local fractal dimension of the cluster. \"\"\"\n        # TODO: Consider computing by using search.\n        if '_local_fractal_dimension' not in self.__dict__:\n            logging.debug(f'building cache for {self}')\n            if self.nsamples == 1:\n                return 0.\n            count = [d <= (self.radius / 2)\n                     for batch in self\n                     for d in self.distance(self.manifold.data[batch])]\n            count = np.sum(count)\n            self.__dict__['_local_fractal_dimension'] = count if count == 0. else np.log2(len(self.argpoints) / count)\n        return self.__dict__['_local_fractal_dimension']\n\n    def clear_cache(self) -> None:\n        \"\"\" Clears the cache for the cluster. \"\"\"\n        logging.debug(f'clearing cache for {self}')\n        for prop in ['_argsamples', '_argmedoid', '_argradius', '_radius', '_local_fractal_dimension']:\n            try:\n                del self.__dict__[prop]\n            except KeyError:\n                pass\n\n    def tree_search(self, point: Data, radius: Radius, depth: int) -> Dict['Cluster', Radius]:\n        \"\"\" Searches down the tree for clusters that overlap point with radius at depth. \"\"\"\n        logging.debug(f'tree_search(point={point}, radius={radius}, depth={depth}')\n        if depth == -1:\n            depth = len(self.manifold.graphs)\n        if depth < self.depth:\n            raise ValueError('depth must not be less than cluster.depth')  # TODO: Cover\n\n        results: Dict['Cluster', Radius] = dict()\n        if self.depth == depth:\n            results = {self: self.distance(np.asarray([point]))[0]}  # TODO: Cover\n        elif self.overlaps(point, radius):\n            results = self._tree_search(point, radius, depth)\n\n        return results\n\n    def _tree_search(self, point: Data, radius: Radius, depth: int) -> Dict['Cluster', Radius]:\n        distance = self.distance(np.asarray([point]))[0]\n        assert distance <= radius + self.radius, f'_tree_search was started with no overlap.'\n        assert self.depth < depth, f'_tree_search needs to have depth ({depth}) > self.depth ({self.depth}). '\n\n        # results and candidates ONLY contain clusters that have overlap with point\n        results: Dict['Cluster', Radius] = dict()\n        candidates: Dict['Cluster', Radius] = {self: distance}\n        for d_ in range(self.depth, depth):\n            # if cluster was not partitioned any further, add it to results.\n            results.update({c: d for c, d in candidates.items() if len(c.children) < 2})\n\n            # filter out only those candidates that were partitioned.\n            candidates = {c: d for c, d in candidates.items() if len(c.children) > 1}\n\n            # proceed down th tree\n            children: List[Cluster] = [c for candidate in candidates.keys() for c in candidate.children]\n            if len(children) == 0:\n                break\n\n            # filter out clusters that are too far away to possibly contain any hits.\n            centers = np.asarray([c.medoid for c in children])\n            distances = cdist(np.expand_dims(point, 0), centers, self.metric)[0]\n            radii = [radius + c.radius for c in children]\n            candidates = {c: d for c, d, r in zip(children, distances, radii) if d <= r}\n            if len(candidates) == 0:\n                break  # TODO: Cover\n\n        assert all((depth >= r.depth for r in results))\n        assert all((depth == c.depth for c in candidates))\n\n        # put all potential clusters in one dictionary.\n        results.update(candidates)\n        return results\n\n    def partition(self, *criterion) -> Iterable['Cluster']:\n        \"\"\" Partitions the cluster into 1 or 2 children.\n\n        2 children are produced if the cluster can be split, otherwise 1 child is produced.\n        \"\"\"\n        if not all((\n                len(self.argpoints) > 1,\n                len(self.argsamples) > 1,\n                *(c(self) for c in criterion),\n        )):\n            # TODO: Can this be made more efficient? In the context of the larger manifold and graph\n            logging.debug(f'{self} did not partition.')\n            self.children = {\n                Cluster(\n                    self.manifold,\n                    self.argpoints,\n                    self.name + '0',\n                    _argsamples=self.argsamples,\n                    _argmedoid=self.argmedoid,\n                    _argradius=self.argradius,\n                    _radius=self.radius,\n                    _local_fractal_dimension=self.local_fractal_dimension,\n                )\n            }\n            return self.children\n\n        farthest = self.argsamples[int(np.argmax(cdist(\n            np.expand_dims(self.manifold.data[self.argradius], 0),\n            self.samples,\n            self.metric,\n        )[0]))]\n        poles = np.stack([\n            self.manifold.data[self.argradius],\n            self.manifold.data[farthest],\n        ])\n\n        p1_idx, p2_idx = list(), list()\n        [(p1_idx if p1 < p2 else p2_idx).append(i)\n         for batch in iter(self)\n         for i, p1, p2 in zip(batch, *cdist(poles, self.manifold.data[batch], self.metric))]\n\n        # Ensure that p1 contains fewer points than p2\n        p1_idx, p2_idx = (p1_idx, p2_idx) if len(p1_idx) < len(p2_idx) else (p2_idx, p1_idx)\n        self.children = {\n            Cluster(self.manifold, p1_idx, self.name + '1'),\n            Cluster(self.manifold, p2_idx, self.name + '2'),\n        }\n        logging.debug(f'{self} was partitioned.')\n        return self.children\n\n    def distance(self, points: Data) -> List[Radius]:\n        \"\"\" Returns the distance from self.medoid to every point in points. \"\"\"\n        return cdist(np.expand_dims(self.medoid, 0), points, self.metric)[0]\n\n    def overlaps(self, point: Data, radius: Radius) -> bool:\n        \"\"\" Checks if point is within radius + self.radius of cluster. \"\"\"\n        return self.distance(np.expand_dims(point, axis=0))[0] <= (self.radius + radius)\n\n    def json(self):\n        data = {\n            'name': self.name,\n            'argpoints': None,  # Do not save argpoints until at leaves.\n            'children': [],\n            'neighbors': {c.name: d for c, d in self.neighbors.items()},\n            '_radius': self.radius,\n            '_argradius': self.argradius,\n            '_argsamples': self.argsamples,\n            '_argmedoid': self.argmedoid,\n            '_local_fractal_dimension': self.local_fractal_dimension,\n        }\n        if self.children:\n            data['children'] = [c.json() for c in self.children]\n        else:\n            data['argpoints'] = self.argpoints\n        return data\n\n    @staticmethod\n    def from_json(manifold, data):\n        children = set([Cluster.from_json(manifold, c) for c in data.pop('children', [])])\n        return Cluster(manifold, children=children, **data)\n\n\nclass Graph:\n    \"\"\" A Graph is comprised of clusters. All constituent clusters must be at the same depth in the tree.\n\n    Nodes in the Graph are Clusters. .Two clusters have an edge if they have overlapping volumes.\n    The Graph class is responsible for handling operations that occur solely within a layer of Manifold.graphs.\n    \"\"\"\n\n    def __init__(self, *clusters):\n        logging.debug(f'Graph(clusters={[str(c) for c in clusters]})')\n        assert all(isinstance(c, Cluster) for c in clusters)\n        assert all([c.depth == clusters[0].depth for c in clusters[1:]])\n\n        # self.clusters is a dictionary of the clusters in the graph and the connected component subgraph that the cluster belongs to.\n        self.clusters: Dict[Cluster: 'Graph'] = {c: None for c in clusters}\n        return\n\n    def __eq__(self, other: 'Graph') -> bool:\n        \"\"\" Two graphs are identical if they are composed of the same clusters. \"\"\"\n        return self.clusters.keys() == other.clusters.keys()\n\n    def __iter__(self) -> Iterable[Cluster]:\n        \"\"\" An iterator over the clusters in the graph. \"\"\"\n        yield from self.clusters.keys()\n\n    def __len__(self) -> int:\n        # TODO: Consider deprecating __len__ for Graph().cardinality\n        return len(self.clusters.keys())\n\n    def __str__(self) -> str:\n        return ';'.join(sorted([str(c) for c in self.clusters.keys()]))\n\n    def __repr__(self) -> str:\n        return '\\t'.join(sorted([repr(c) for c in self.clusters.keys()]))\n\n    def __hash__(self):\n        return hash(str(self))\n\n    def __contains__(self, cluster: 'Cluster') -> bool:\n        return cluster in self.clusters.keys()\n\n    @property\n    def manifold(self) -> 'Manifold':\n        return next(iter(self.clusters.keys())).manifold\n\n    @property\n    def depth(self) -> int:\n        return next(iter(self.clusters.keys())).depth\n\n    @property\n    def metric(self) -> Metric:\n        return next(iter(self.clusters.keys())).metric\n\n    def _build_edges_matrix(self) -> None:\n        \"\"\" Calculates overlap for clusters in self in the naive way. \"\"\"\n        # TODO: Calculate memory cost of the distance matrix here.\n        clusters: List[Cluster] = list(self.clusters.keys())\n\n        centers = np.asarray([c.medoid for c in clusters], dtype=np.float64)\n        radii = np.asarray([c.radius for c in clusters], dtype=np.float64)\n\n        distances = cdist(centers, centers, self.metric)\n        differences = (distances.T - radii).T - radii\n        left, right = tuple(map(list, np.where(differences <= 0.)))\n\n        [clusters[l_].neighbors.update({clusters[r_]: distances[l_, r_]}) for l_, r_ in zip(left, right) if l_ != r_]\n        return\n\n    def build_edges(self) -> None:\n        \"\"\" Calculates edges for the Graph. \"\"\"\n        return self._build_edges_matrix()\n\n    @property\n    def edges(self) -> Dict[Set['Cluster'], float]:\n        \"\"\" Returns all edges within the graph. \"\"\"\n        if '_edges' not in self.__dict__:\n            logging.debug(f'building cache for {self}')\n            self.__dict__['_edges'] = {frozenset([c, n]): d for c in self.clusters.keys() for n, d in c.neighbors.items()}\n        return self.__dict__['_edges']\n\n    @property\n    def subgraphs(self) -> Set['Graph']:\n        \"\"\" Returns all subgraphs within the graph. \"\"\"\n        if any((s is None for s in self.clusters.values())):\n            unvisited = {c for c, s in self.clusters.items() if s is None}\n            while unvisited:\n                cluster = unvisited.pop()\n                component = self.bft(cluster)\n                unvisited -= component\n                subgraph = Graph(*component)\n                self.clusters.update({c: subgraph for c in subgraph})\n        return set(self.clusters.values())\n\n    def subgraph(self, cluster: 'Cluster') -> 'Graph':\n        \"\"\" Returns the subgraph to which the cluster belongs. \"\"\"\n        if cluster not in self.clusters.keys():\n            raise ValueError(f'Cluster {cluster} not a member of {self}')\n\n        if self.clusters[cluster] is None:\n            component = self.bft(cluster)\n            subgraph = Graph(*component)\n            self.clusters.update({c: subgraph for c in subgraph})\n\n        return self.clusters[cluster]\n\n    def clear_cache(self) -> None:\n        \"\"\" Clears the cache of the graph. \"\"\"\n        for prop in ['_edges']:\n            logging.debug(str(self.clusters))\n            try:\n                del self.__dict__[prop]\n            except KeyError:\n                pass\n        # Clear all cached subgraphs.\n        self.clusters = {c: None for c in self.clusters.keys()}\n        return\n\n    def random_walk(self, steps: int = 5, walks: int = 1) -> Dict[Cluster, int]:\n        \"\"\" Performs a random walk, returning a modified graph instance.\n\n        :param int steps: number of steps per walk\n        :param int walks: number of walks to perform\n        :returns a Dict of cluster names to visit counts\n        \"\"\"\n        # TODO: Consider changing the type of parallelism here to not have to rely on lists.\n        clusters = list(self.clusters.keys())\n        results = {c: list() for c in clusters}\n\n        def walk(cluster):\n            for _ in range(steps):\n                results[cluster].append(1)\n                if not cluster.neighbors:\n                    break  # TODO: Cover\n                cluster = random.sample(cluster.neighbors.keys(), 1)[0]\n\n        # Perform random walks in parallel.\n        starts = random.sample(clusters, min(walks, len(clusters)))\n        threads = [Thread(target=walk, args=(s,)) for s in starts]\n        [t.start() for t in threads]\n        [t.join() for t in threads]\n\n        # Gather the results.\n        results = {k: len(v) for k, v in results.items()}\n        return results\n\n    @staticmethod\n    def bft(start: 'Cluster'):\n        \"\"\" Breadth-First Traversal starting at start. \"\"\"\n        logging.debug(f'starting from {start}')\n        visited = set()\n        queue = deque([start])\n        while queue:\n            c = queue.popleft()\n            if c not in visited:\n                visited.add(c)\n                [queue.append(neighbor) for neighbor in c.neighbors.keys()]\n        return visited\n\n    @staticmethod\n    def dft(start: 'Cluster'):\n        \"\"\" Depth-First Traversal starting at start. \"\"\"\n        logging.debug(f'starting from {start}')\n        visited = set()\n        stack: List[Cluster] = [start]\n        while stack:\n            c = stack.pop()\n            if c not in visited:\n                visited.add(c)\n                stack.extend(c.neighbors.keys())\n        return visited\n\n\nclass Manifold:\n    \"\"\" Manifold of varying resolution.\n\n    The Manifold class' main job is to organize the underlying Clusters ang Graphs.\n    It does this by providing the ability to reset the build the Cluster-tree, and from them the Graph-stack.\n    With this Cluster-tree and Graph-stack, Manifold provides utilities for rho-nearest neighbors search, k-nearest neighbors search.\n    \"\"\"\n    # TODO: Bring in anomaly detection from experiments.\n\n    def __init__(self, data: Data, metric: Metric, argpoints: Union[Vector, float] = None, **kwargs):\n        \"\"\" A Manifold needs the data to learn the manifold for, and a distance metric to use while doing so.\n\n        :param data: The data to learn. This could be a numpy.ndarray or a numpy.memmap.\n        :param metric: The distance metric to use for the data. Any metric allowed by scipy.spatial.distance is allowed here.\n        :param argpoints: Optional. List of indexes or portion of data to which to restrict Manifold.\n        \"\"\"\n        logging.debug(f'Manifold(data={data.shape}, metric={metric}, argpoints={argpoints})')\n        self.data: Data = data\n        self.metric: Metric = metric\n\n        if argpoints is None:\n            self.argpoints = list(range(self.data.shape[0]))\n        elif type(argpoints) is list:\n            self.argpoints = list(map(int, argpoints))\n        elif type(argpoints) is float:\n            self.argpoints = np.random.choice(self.data.shape[0], int(self.data.shape[0] * argpoints), replace=False)\n            self.argpoints = list(map(int, self.argpoints))\n        else:\n            raise ValueError(f\"Invalid argument to argpoints. {argpoints}\")\n\n        self.graphs: List['Graph'] = [Graph(Cluster(self, self.argpoints, ''))]\n\n        self.__dict__.update(**kwargs)\n        return\n\n    def __eq__(self, other: 'Manifold') -> bool:\n        \"\"\" Two manifolds are identical if they have the same metric and the same leaf-clusters. \"\"\"\n        return all((\n            self.metric == other.metric,\n            self.graphs[-1] == other.graphs[-1],\n        ))\n\n    def __getitem__(self, depth: int) -> 'Graph':\n        return self.graphs[depth]\n\n    def __iter__(self) -> Iterable[Graph]:\n        yield from self.graphs\n\n    def __str__(self) -> str:\n        return '\\t'.join([self.metric, str(self.graphs[-1])])\n\n    def __repr__(self) -> str:\n        return '\\n'.join([self.metric, repr(self.graphs[-1])])\n\n    @property\n    def depth(self) -> int:\n        return len(self.graphs) - 1\n\n    def find_points(self, point: Data, radius: Radius) -> Dict[int, Radius]:\n        \"\"\" Returns all indices of points that are within radius of point. \"\"\"\n        # TODO: Need a default depth argument?\n        # TODO: Consider returning results as a sorted list of tuples.\n        candidates: List[int] = [p for c in self.find_clusters(point, radius, len(self.graphs)).keys() for p in c.argpoints]\n        results: Dict[int, Radius] = dict()\n        point = np.expand_dims(point, axis=0)\n        for i in range(0, len(candidates), BATCH_SIZE):\n            batch = candidates[i:i + BATCH_SIZE]\n            distances = cdist(point, self.data[batch], self.metric)[0]\n            results.update({p: d for p, d in zip(batch, distances) if d <= radius})\n        return results\n\n    def find_clusters(self, point: Data, radius: Radius, depth: int) -> Dict['Cluster', Radius]:\n        \"\"\" Returns all clusters that contain points within radius of point at depth. \"\"\"\n        return {r: d for c in self.graphs[0] for r, d in c.tree_search(point, radius, depth).items()}\n\n    def find_knn(self, point: Data, k: int) -> Dict[Data, Radius]:\n        \"\"\" Finds and returns the k-nearest neighbors of point. \"\"\"\n        # TODO: Consider returning results as a sorted list of tuples.\n        radius: Radius = np.float64(np.mean([c.radius for c in self.graphs[-1].clusters]))\n        radius = np.float64(max(radius, 1e-16))\n        results = self.find_points(point, radius)\n        while len(results.keys()) < k:\n            radius *= 2\n            results = self.find_points(point, radius)\n\n        sorted_results = sorted([(d, p) for p, d in results.items()])[:k]\n        results = {p: d for d, p in sorted_results}\n        return results\n\n    def build(self, *criterion) -> 'Manifold':\n        \"\"\" Rebuilds the Cluster-tree and the Graph-stack. \"\"\"\n        self.graphs = [Graph(Cluster(self, self.argpoints, ''))]\n        self.build_tree(*criterion)\n        self.build_graphs()\n        return self\n\n    def build_tree(self, *criterion) -> 'Manifold':\n        \"\"\" Builds the Cluster-tree. \"\"\"\n        while True:\n            logging.info(f'current depth: {len(self.graphs) - 1}')\n            clusters = self._partition_threaded(criterion)\n            if len(self.graphs[-1]) < len(clusters):\n                g = Graph(*clusters)\n                self.graphs.append(g)\n            else:\n                [c.children.clear() for c in self.graphs[-1]]\n                break\n        return self\n\n    def build_graphs(self) -> 'Manifold':\n        \"\"\" Builds the Graph-stack. \"\"\"\n        [g.build_edges() for g in self.graphs]\n        return self\n\n    def build_graph(self, depth: int) -> 'Manifold':\n        \"\"\" Builds the graph at a given depth. \"\"\"\n        if depth > self.depth:\n            raise ValueError(f'depth must not be greater than {self.depth}. Got {depth}.')\n        self.graphs[depth].build_edges()\n        return self\n\n    def subgraph(self, cluster: Union[str, Cluster]) -> Graph:\n        \"\"\" Returns the subgraph to which cluster belongs. \"\"\"\n        cluster = self.select(cluster) if type(cluster) is str else cluster\n        return self.graphs[cluster.depth].subgraph(cluster)\n\n    def graph(self, cluster: Union[str, Cluster]) -> Graph:\n        \"\"\" Returns the graph to which cluster belongs. \"\"\"\n        cluster = self.select(cluster) if type(cluster) is str else cluster\n        return self.graphs[cluster.depth]\n\n    def _partition_single(self, criterion):\n        return [child for cluster in self.graphs[-1] for child in cluster.partition(*criterion)]\n\n    def _partition_threaded(self, criterion):\n        queue = Queue()\n        threads = [\n            Thread(\n                target=lambda cluster: [queue.put(c) for c in cluster.partition(*criterion)],\n                args=(c,),\n                name=c.name\n            )\n            for c in self.graphs[-1]]\n        [t.start() for t in threads]\n        [t.join() for t in threads]\n        clusters = []\n        while not queue.empty():\n            clusters.append(queue.get())\n        return clusters\n\n    def select(self, name: str) -> Cluster:\n        \"\"\" Returns the cluster with the given name. \"\"\"\n        if len(name) > self.depth:\n            raise ValueError(f'depth of requested cluster must not be greater than depth of cluster-tree. Got {name}, max-depth: {self.depth}')\n\n        # TODO: Consider how to change this for forests.\n        cluster: Cluster = next(iter(self.graphs[0]))\n        for depth in range(len(name) + 1):\n            partial_name = name[:depth]\n            for child in cluster.children:\n                if child.name == partial_name:\n                    cluster = child\n                    break\n\n        assert name == cluster.name, f'wanted {name} but got {cluster.name}.'\n        return cluster\n\n    def dump(self, fp: BinaryIO) -> None:  # TODO: Cover\n        # TODO: Consider hoe to remove argpoints from this and just rebuild from leaves.\n        pickle.dump({\n            'metric': self.metric,\n            'argpoints': self.argpoints,\n            'root': [c.json() for c in self.graphs[0]],\n        }, fp)\n        return\n\n    @staticmethod\n    def load(fp: BinaryIO, data: Data) -> 'Manifold':\n        d = pickle.load(fp)\n        manifold = Manifold(data, metric=d['metric'], argpoints=d['argpoints'])\n        graphs = [  # TODO: Cover\n            Graph(*[Cluster.from_json(manifold, r) for r in d['root']])\n        ]\n        while True:\n            layer = Graph(*(child for cluster in graphs[-1] for child in cluster.children))\n            if not layer:\n                break\n            else:\n                graphs.append(layer)\n\n        manifold.graphs = graphs\n        for graph in graphs:\n            for cluster in graph.clusters.keys():\n                cluster.neighbors = {manifold.select(n): d for n, d in cluster.__dict__['neighbors'].items()}\n        return manifold\n", "meta": {"hexsha": "412968b6ff7541b89b4f0693e46d4d83f6cbf987", "size": 29413, "ext": "py", "lang": "Python", "max_stars_repo_path": "chess/manifold.py", "max_stars_repo_name": "nishaq503/CHESS", "max_stars_repo_head_hexsha": "6f84e7e98d328150170141621cc095dfa80ef67e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-14T16:06:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T16:06:17.000Z", "max_issues_repo_path": "chess/manifold.py", "max_issues_repo_name": "nishaq503/CHESS", "max_issues_repo_head_hexsha": "6f84e7e98d328150170141621cc095dfa80ef67e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2019-11-16T17:04:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-12T22:21:29.000Z", "max_forks_repo_path": "chess/manifold.py", "max_forks_repo_name": "nishaq503/CHESS", "max_forks_repo_head_hexsha": "6f84e7e98d328150170141621cc095dfa80ef67e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-14T13:44:40.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-14T13:44:40.000Z", "avg_line_length": 40.6818810512, "max_line_length": 143, "alphanum_fraction": 0.6029306769, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.33458944788835565, "lm_q1q2_score": 0.18293281641203182}}
{"text": "#! /usr/bin/env python\nimport sys\nimport os\nimport argparse\nimport numpy as np\nimport pandas as pd\nimport json\nfrom ctdcal import process_ctd\nimport ctdcal.report_ctd as report_ctd\nimport ctdcal.fit_ctd as fit_ctd\nimport configparser\n#import matplotlib.pyplot as plt\nfrom scipy.optimize import leastsq\nimport gsw\n\nDEBUG = False\n\n#File extension to use for output files (csv-formatted)\nFILE_EXT = 'csv'\nPKL_EXT = 'pkl'\n\n#File extension to use for output files (csv-formatted)\nXML_EXT = 'XMLCON'\n\n#File extension to use for output files (csv-formatted)\nHEX_EXT = 'hex'\n\n#File extension to use for raw output\nBTL_SUFFIX = '_btl'\n\n#File extension to use for raw output\nFIT_SUFFIX = '_fit'\n\n#File extension to use for raw output\nMEAN_SUFFIX = '_mean'\n\n#File extension to use for raw output\nTIME_SUFFIX = '_time'\n\n#File extension to use for output files (csv-formatted)\nUPDT_SUFFIX = '_updt'\n\n#File extension to use for converted output\nCONVERTED_SUFFIX = '_cnv'\n\ndef debugPrint(*args, **kwargs):\n    if DEBUG:\n        errPrint(*args, **kwargs)\n\ndef errPrint(*args, **kwargs):\n    print(*args, file=sys.stderr, **kwargs)\n\n# -------------------------------------------------------------------------------------\n# Main function of the script should it be run as a stand-alone utility.\n# -------------------------------------------------------------------------------------\ndef main(argv):\n\n    parser = argparse.ArgumentParser(description='Convert SBE raw data to a converted, csv-formatted text file')\n    parser.add_argument('timeFile', metavar='time_file', help='the .csv data file to fit by bottle data')\n\n    # debug messages\n    parser.add_argument('-d', '--debug', action='store_true', help='display debug messages')\n\n    # raw output\n    parser.add_argument('-pres', '--pressure', action='store_true', help='Fit pressure data')\n\n    # raw output\n    parser.add_argument('-temp', '--temperature', action='store_true', help='Fit temperture data')\n\n    # raw output\n    parser.add_argument('-cond', '--conductivity', action='store_true', help='Fit conductivity data')\n\n    # raw output\n    parser.add_argument('-oxy', '--oxygen', type=argparse.FileType('r'), help='return the oxygen data file')\n\n    # Process Command-line args\n    args = parser.parse_args()\n    if args.debug:\n        global DEBUG\n        DEBUG = True\n        debugPrint(\"Running in debug mode\")\n\n    # Verify hex file exists\n    if not os.path.isfile(args.timeFile):\n        errPrint('ERROR: Input time dependent .csv file:', args.timeFile, 'not found\\n')\n        sys.exit(1)\n\n    # Used later for building output file names\n    filename_ext = os.path.basename(args.timeFile) # original filename with ext\n    filename_base = os.path.splitext(filename_ext)[0] # original filename w/o ext\n\n    if '_' in filename_base:\n        filename_base = filename_base.split('_')[0]\n\n    #Import Cruise Configuration File\n    iniFile = 'data/ini-files/configuration.ini'\n    config = configparser.RawConfigParser()\n    config.read(iniFile)\n\n    #Initialise Configuration Parameters\n    expocode = config['cruise']['expocode']\n    sectionID = config['cruise']['sectionid']\n    raw_directory = config['ctd_processing']['raw_data_directory']\n    time_directory = config['ctd_processing']['time_data_directory']\n    pressure_directory = config['ctd_processing']['pressure_data_directory']\n    oxygen_directory = config['ctd_processing']['oxygen_directory']\n    btl_directory = config['ctd_processing']['bottle_directory']\n    o2flask_file = config['ctd_processing']['o2flask_file']\n    log_directory = config['ctd_processing']['log_directory']\n    sample_rate = config['ctd_processing']['sample_rate']\n    search_time = config['ctd_processing']['roll_filter_time']\n    ctd = config['ctd_processing']['ctd_serial']\n\n    time_zone = config['inputs']['time_zone']\n    p_col = config['analytical_inputs']['p']\n    p_btl_col = config['inputs']['p']\n    t_col = config['analytical_inputs']['t']\n    t_btl_col = config['inputs']['t']\n    t1_col = config['analytical_inputs']['t1']\n    t1_btl_col = config['inputs']['t1']\n    t2_col = config['analytical_inputs']['t2']\n    t2_btl_col = config['inputs']['t2']\n    c_col = config['analytical_inputs']['c']\n    c1_col = config['analytical_inputs']['c1']\n    c1_btl_col = config['inputs']['c1']\n    c2_col = config['analytical_inputs']['c2']\n    c2_btl_col = config['inputs']['c2']\n    sal_col = config['analytical_inputs']['salt']\n    sal_btl_col = config['inputs']['salt']\n    btl_sal_col = config['analytical_inputs']['btl_salt']\n    dov_col = config['analytical_inputs']['dov']\n    dov_btl_col = config['inputs']['dov']\n    dopl_col = config['analytical_inputs']['dopl']\n    dopl_btl_col = config['inputs']['dopl']\n    dopkg_col = config['analytical_inputs']['dopkg']\n    btl_oxy_col = config['analytical_inputs']['btl_oxy']\n    xmis_col = config['analytical_inputs']['xmis']\n    fluor_col = config['analytical_inputs']['fluor']\n    timedate = config['analytical_inputs']['datetime']\n    lat_col = config['analytical_inputs']['lat']\n    lat_btl_col = config['inputs']['lat']\n    lon_col = config['analytical_inputs']['lon']\n    lon_btl_col = config['inputs']['lon']\n    reft_col = config['inputs']['reft']\n    btl_num_col = config['inputs']['btl_num']\n\n    #time_column_data = config['time_series_output']['data_names'].split(',')\n    time_column_data = config['time_series_output']['data_output']\n    time_column_names = config['time_series_output']['column_name'].split(',')\n    time_column_units = config['time_series_output']['column_units'].split(',')\n    time_column_format = config['time_series_output']['format']\n\n    #pressure_column_data = config['time_series_output']['data_names'].split(',')\n    p_column_data = config['pressure_series_output']['data'].split(',')\n    p_column_names = config['pressure_series_output']['column_name'].split(',')\n    p_column_units = config['pressure_series_output']['column_units'].split(',')\n    p_column_format = config['pressure_series_output']['format']\n    p_column_qual = config['pressure_series_output']['qual_columns'].split(',')\n    p_column_one = list(config['pressure_series_output']['q1_columns'].split(','))\n\n    #bottle_data outputs\n    btl_dtype = config['bottle_series_output']['dtype']\n\n    hexfileName = str(filename_base + '.' + HEX_EXT)\n    hexfilePath = os.path.join(raw_directory, hexfileName)\n\n    xmlfileName = str(filename_base + '.' + XML_EXT)\n    xmlfilePath = os.path.join(raw_directory, xmlfileName)\n\n    outtimefileName = str(filename_base + TIME_SUFFIX + '.' + PKL_EXT)\n    outtimefilePath = os.path.join(time_directory, outtimefileName)\n\n    # pressfileName = str(filename_base + FIT_SUFFIX + '.' + FILE_EXT)\n    # pressfilePath = os.path.join(pressure_directory, pressfileName)\n\n    btlfileName = str(filename_base + BTL_SUFFIX + MEAN_SUFFIX + '.' + PKL_EXT)\n    btlfilePath = os.path.join(btl_directory, btlfileName)\n\n    # Get bottle data\n    btl_data = process_ctd.dataToNDarray(btlfilePath,float,True,',',0)\n    #import pdb; pdb.set_trace()\n    #btl_data = btl_data[:][1:]\n\n    # Get procesed time data\n    time_data = process_ctd.dataToNDarray(args.timeFile,float,True,',',1)\n    #btm = np.argmax(time_data[p_col][1:])\n    #time_data = time_data[:][1:btm]\n    time_data = pd.DataFrame.from_records(time_data)\n    time_data = time_data.loc[:time_data['CTDPRS'].idxmax()]\n    time_data = time_data.to_records(index=False)\n\n    if args.pressure:\n        print('In -pres flag fit condition')\n        print(filename_base)\n        pfileName = str('poffset' + '.' + FILE_EXT)\n        pfilePath = os.path.join(log_directory, pfileName)\n        poff_data = process_ctd.dataToNDarray(pfilePath,str,None,',',None)\n\n        for line in poff_data:\n            if filename_base in line[0]:\n                for val in line:\n                    if 'offset' in val:\n                        offset = float(str.split(val, ':')[1])\n            continue\n\n        # Pressure offset\n        btl_data[p_btl_col] = fit_ctd.offset(offset, btl_data[p_btl_col])\n        time_data[p_col] = fit_ctd.offset(offset, time_data[p_col])\n        # End pressure if condition\n\n    if args.temperature:\n        print('In -temp flag fit condition')\n        print(filename_base)\n        coef1 = []\n        coef2 = []\n        # Get descrete ref temp data\n        t1fileName = str('fitting_t1' + '.' + FILE_EXT)\n        t1filePath = os.path.join(log_directory, t1fileName)\n        t1_coef = process_ctd.dataToNDarray(t1filePath,str,None,',',None)\n\n        for line in t1_coef:\n            if filename_base in line[0]:\n                val = line[1:]\n                for i in range(0,len(val)):\n                    if 'coef' in val[i]:\n                        coef1.append(float(str.split(val[i], ':')[1]))\n                    else:\n                        coef1.append(float(val[i]))\n            continue\n        btl_data[t1_btl_col] = fit_ctd.temperature_polyfit(coef1, btl_data[p_btl_col], btl_data[t1_btl_col])\n        time_data[t1_col] = fit_ctd.temperature_polyfit(coef1, time_data[p_col], time_data[t1_col])\n\n        t2fileName = str('fitting_t2' + '.' + FILE_EXT)\n        t2filePath = os.path.join(log_directory, t2fileName)\n        t2_coef = process_ctd.dataToNDarray(t2filePath,str,None,',',None)\n\n        for line in t2_coef:\n            if filename_base in line[0]:\n                val = line[1:]\n                for i in range(0,len(val)):\n                    if 'coef' in val[i]:\n                        coef2.append(float(str.split(val[i], ':')[1]))\n                    else:\n                        coef2.append(float(val[i]))\n            continue\n        btl_data[t2_btl_col] = fit_ctd.temperature_polyfit(coef2, btl_data[p_btl_col], btl_data[t2_btl_col])\n        time_data[t2_col] = fit_ctd.temperature_polyfit(coef2, time_data[p_col], time_data[t2_col])\n\n    if args.conductivity:\n        print('In -cond flag fit condition')\n        print(filename_base)\n        coef1 = []\n        coef2 = []\n\n        # Get descrete cond data\n\n        c1fileName = str('fitting_c1' + '.' + FILE_EXT)\n        c1filePath = os.path.join(log_directory, c1fileName)\n        if os.path.exists(c1filePath):\n            c1_coef = process_ctd.dataToNDarray(c1filePath,str,None,',',None)\n\n            for line in c1_coef:\n                if filename_base in line[0]:\n                    val = line[1:]\n                    for i in range(0,len(val)):\n                        if 'coef' in val[i]:\n                            coef1.append(float(str.split(val[i], ':')[1]))\n                        else:\n                            coef1.append(float(val[i]))\n                continue\n            btl_data[c1_btl_col] = fit_ctd.conductivity_polyfit(coef1, btl_data[p_btl_col], btl_data[t1_btl_col], btl_data[c1_btl_col])\n            time_data[c1_col] = fit_ctd.conductivity_polyfit(coef1, time_data[p_col], time_data[c1_col], time_data[c1_col])\n\n        c2fileName = str('fitting_c2' + '.' + FILE_EXT)\n        c2filePath = os.path.join(log_directory, c2fileName)\n        if os.path.exists(c2filePath):\n            c2_coef = process_ctd.dataToNDarray(c2filePath,str,None,',',None)\n\n            for line in c2_coef:\n                if filename_base in line[0]:\n                    val = line[1:]\n                    for i in range(0,len(val)):\n                        if 'coef' in val[i]:\n                            coef2.append(float(str.split(val[i], ':')[1]))\n                        else:\n                            coef2.append(float(val[i]))\n                continue\n            btl_data[c2_btl_col] = fit_ctd.conductivity_polyfit(coef2, btl_data[p_btl_col], btl_data[t2_btl_col], btl_data[c2_btl_col])\n            time_data[c2_col] = fit_ctd.conductivity_polyfit(coef2, time_data[p_col], time_data[c2_col], time_data[c2_col])\n\n        time_data[sal_col] = gsw.SP_from_C(time_data[c_col],time_data[t_col],time_data[p_col])\n\n    if args.oxygen:\n        print('In -oxy flag fit condition')\n        print(filename_base)\n        # Get Analytical Oxygen data\n        o2pkg_btl, o2pl_btl = fit_ctd.o2_calc(o2flask_file,args.oxygen.name,btl_data[btl_num_col],btl_data[sal_btl_col])\n\n        kelvin = []\n        for i in range(0,len(time_data[t_col])):\n            kelvin.append(time_data[t_col][i] + 273.15)\n\n        # Find New Oxygen Coef\n        oxy_coef = fit_ctd.find_oxy_coef(o2pl_btl['OXYGEN'], btl_data[p_btl_col], btl_data[t_btl_col], btl_data[sal_btl_col], btl_data[dov_btl_col], hexfilePath, xmlfilePath)\n\n        # Convert CTD Oxygen Voltage Data with New DO Coef\n        time_data[dopl_col] = fit_ctd.oxy_dict(oxy_coef, time_data[p_col], kelvin, time_data[t_col], time_data[sal_col], time_data[dov_col])\n        # End oxygen flag fitting if condition\n\n    # Find Isopycnal Down Trace Bottle Trip Equivalent\n    # Write bottle data to file\n    report_ctd.report_btl_data(btlfilePath, btl_dtype, btl_data)\n\n    # Write time data to file\n    report_ctd.report_time_series_data(filename_base, time_directory, expocode, time_column_names, time_column_units, time_column_names, time_column_format, time_data)\n\n    # Pressure Sequence\n    pressure_seq_data = process_ctd.pressure_sequence(filename_base, p_col, timedate, 2.0, -1.0, 0.0, 'down', int(sample_rate), int(search_time), time_data)\n\n    # Convert dissolved oxygen from ml/l to umol/kg\n    dopkg = process_ctd.o2pl2pkg(p_col, t1_col, sal_col, dopl_col, dopkg_col, lat_col, lon_col, pressure_seq_data)\n\n    # Add quality codes to data\n    qual_pseq_data = process_ctd.ctd_quality_codes(dopkg_col, None, None, True, p_column_qual, p_column_one, pressure_seq_data)\n\n    # Collect Cast Details from Log\n    logfileName = str('cast_details' + '.' + FILE_EXT)\n    logfilePath = os.path.join(log_directory, logfileName)\n\n    cast_details = process_ctd.dataToNDarray(logfilePath,str,None,',',0)\n    for line in cast_details:\n        if filename_base in line[0]:\n            for val in line:\n                if 'at_depth' in val: btime = float(str.split(val, ':')[1])\n                if 'latitude' in val: btm_lat = float(str.split(val, ':')[1])\n                if 'longitude' in val: btm_lon = float(str.split(val, ':')[1])\n                if 'altimeter_bottom' in val: btm_alt = float(str.split(val, ':')[1])\n            break\n\n    # Write time data to file\n    depth = -999\n    #import pdb; pdb.set_trace()\n    report_ctd.report_pressure_series_data(filename_base, expocode, sectionID, btime, btm_lat, btm_lon, depth, btm_alt, ctd, pressure_directory, p_column_names, p_column_units, p_column_data, qual_pseq_data, dopkg, pressure_seq_data)\n\n    #plt.plot(o2pl_btl['OXYGEN'], btl_data[p_btl_col], color='b', marker='o')\n    #plt.plot(tmpo2, time_data[p_col], color='g', label='raw')\n    #plt.plot(time_data[dopl_col], time_data[p_col], color='b', label='raw')\n    #plt.plot(pressure_seq_data[dopl_col], pressure_seq_data[p_col], color='r', label='raw')\n    #plt.plot(pressure_seq_data[t2_col], pressure_seq_data[p_col], color='r', label='raw')\n    #plt.plot(btl_data[t_btl_col], time_data[p_col], color='r', label='raw')\n    #plt.plot(o2pl_btl['OXYGEN'], btl_data[p_btl_col], color='g', marker='o', label='raw')\n    #plt.plot(pressure_seq_data[do_col], pressure_seq_data[p_col], color='b', label='raw')\n    #plt.gca().invert_yaxis()\n    #plt.axis()\n    #plt.show()\n\n    debugPrint('Done!')\n\n# -------------------------------------------------------------------------------------\n# Required python code for running the script as a stand-alone utility\n# -------------------------------------------------------------------------------------\nif __name__ == '__main__':\n    main(sys.argv[1:])", "meta": {"hexsha": "4fc6157ec72ba7e55ae93594799cf9e8df59e416", "size": 15560, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/odf_fit_ctd.py", "max_stars_repo_name": "k3jackson/odf-ctd-proc", "max_stars_repo_head_hexsha": "a556e4ddc24b0c19085dc9657e5e844c279eb1e2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-12-21T19:05:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-31T15:49:43.000Z", "max_issues_repo_path": "scripts/odf_fit_ctd.py", "max_issues_repo_name": "k3jackson/odf-ctd-proc", "max_issues_repo_head_hexsha": "a556e4ddc24b0c19085dc9657e5e844c279eb1e2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2017-10-22T14:14:01.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-15T18:54:50.000Z", "max_forks_repo_path": "scripts/odf_fit_ctd.py", "max_forks_repo_name": "k3jackson/odf-ctd-proc", "max_forks_repo_head_hexsha": "a556e4ddc24b0c19085dc9657e5e844c279eb1e2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-07-17T21:46:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-23T17:12:18.000Z", "avg_line_length": 42.8650137741, "max_line_length": 233, "alphanum_fraction": 0.6423521851, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.1829328091566311}}
{"text": "import os\nimport numpy as np\nimport pandas as pd\n\nfrom excalibur.constants import Ryd, u\n\ndef det_broad(input_directory):\n    '''\n    Determine the type of broadening that should be used in the case that the user specifies\n    'default' broadening. Order of preference is: 1) H2-He, 2) air, 3) SB07\n\n    Parameters\n    ----------\n    input_directory : String\n        Local directory where the broadening file will be stored.\n\n    Returns\n    -------\n    broadening : String\n        The type of broadening being used.\n\n    '''\n\n    # Molecular hydrogen + helium broadening is first choice\n    if 'H2.broad' in os.listdir(input_directory) and 'He.broad' in os.listdir(input_directory):\n        broadening = 'H2-He'\n\n    # If no H2 + He boradening files, search for an air boradening file\n    elif 'air.broad' in os.listdir(input_directory):\n        broadening = 'air'\n\n    # If neither of the above are available (e.g. for most metal oxides), fall back to Sharp & Burrows (2007)\n    else:\n        broadening = 'SB07'\n        if not 'SB07.broad' in os.listdir(input_directory):\n            create_SB07(input_directory)\n\n    return broadening\n\n\ndef create_SB07(input_directory):\n    '''\n    Create a broadening file according to Eq. 15 of Sharp & Burrows (2007),\n    and add it to the input_directory.\n\n    Note: S&B (2007) state Eq. 15 gives the FWHM. Personal communication from\n    Richard Freedman indicates the equation actually gives the HWHM.\n\n    Parameters\n    ----------\n    input_directory : String\n         Local directory where the broadening file will be stored.\n\n    Returns\n    -------\n    None.\n\n    '''\n\n    SB07_file = input_directory + 'SB07.broad'\n\n    # Initialise total arrays\n    J = np.arange(31.0)          # Total angular momentum\n    gamma_L_0 = np.zeros(31)     # Lorentizian HWHM at P_ref and T_ref\n    n_L = np.zeros(31)           # Temperature exponent\n\n    # Implement Eq. 15 from S&B07 (wihout division by 2, as already HWHM)\n    for i in range(len(J)):\n        gamma_L_0[i] = (0.1 - min(J[i], 30) * 0.002) / 1.01325\n\n    # Write broadening output file\n    f_out = open(SB07_file, 'w')\n\n    f_out.write('J | gamma_L_0 | n_L \\n')\n\n    for i in range(len(J)):\n        f_out.write('%.1f %.4f %.3f \\n' %(J[i], gamma_L_0[i], n_L[i]))\n\n    f_out.close()\n\n\ndef read_H2_He(input_directory):\n    '''\n    Read the H2 and He broadening files from the input directory\n\n    Parameters\n    ----------\n    input_directory : TYPE\n        DESCRIPTION.\n\n    Returns\n    -------\n    J_max : TYPE\n        DESCRIPTION.\n    gamma_0_H2 : TYPE\n        DESCRIPTION.\n    n_L_H2 : TYPE\n        DESCRIPTION.\n    gamma_0_He : TYPE\n        DESCRIPTION.\n    n_L_He : TYPE\n        DESCRIPTION.\n\n    '''\n\n    # Read in H2 broadening file\n    broad_file_H2 = pd.read_csv(input_directory + 'H2.broad',\n                                sep = ' ', header=None, skiprows=1)\n    J_max_H2 = int(np.max(np.array(broad_file_H2[0])))\n    gamma_0_H2 = np.array(broad_file_H2[1])\n    n_L_H2 = np.array(broad_file_H2[2])\n\n    # Read in He broadening file\n    broad_file_He = pd.read_csv(input_directory + 'He.broad',\n                                sep = ' ', header=None, skiprows=1)\n    J_max_He = int(np.max(np.array(broad_file_He[0])))\n    gamma_0_He = np.array(broad_file_He[1])\n    n_L_He = np.array(broad_file_He[2])\n\n    # Take maximum J'' value for which broadening is a function of J to be lowest for which complete data available\n    J_max = np.max(np.array([J_max_H2, J_max_He]))\n\n    # If broadening files not of same length, extend shortest file to same length as longest\n    if (J_max_H2 < J_max):\n\n        for i in range (J_max_H2, J_max):\n\n            gamma_0_H2 = np.append(gamma_0_H2, gamma_0_H2[-1])    # Extended values equal to final value\n            n_L_H2 = np.append(n_L_H2, n_L_H2[-1])                # Extended values equal to final value\n\n    if (J_max_He < J_max):\n\n        for i in range (J_max_He, J_max):\n\n            gamma_0_He = np.append(gamma_0_He, gamma_0_He[-1])    # Extended values equal to final value\n            n_L_He = np.append(n_L_He, n_L_He[-1])                # Extended values equal to final value\n\n    return J_max, gamma_0_H2, n_L_H2, gamma_0_He, n_L_He\n\n\ndef read_air(input_directory):\n    '''\n    Read the air broadening file from the input directory\n\n    Parameters\n    ----------\n    input_directory : String\n         Local directory where the broadening file will be stored.\n\n    Returns\n    -------\n    J_max : TYPE\n        DESCRIPTION.\n    gamma_0_air : TYPE\n        DESCRIPTION.\n    n_L_air : TYPE\n        DESCRIPTION.\n\n    '''\n\n    # Read in air broadening file\n    broad_file_air = pd.read_csv(input_directory + 'air.broad',\n                                 sep = ' ', header=None, skiprows = 1)\n    J_max = int(np.max(np.array(broad_file_air[0])))\n    gamma_0_air = np.array(broad_file_air[1])\n    n_L_air = np.array(broad_file_air[2])\n\n    return J_max, gamma_0_air, n_L_air\n\n\ndef read_SB07(input_directory):\n    '''\n    Read the Burrows broadening file from the input directory\n\n    Parameters\n    ----------\n    input_directory : TYPE\n        DESCRIPTION.\n\n    Returns\n    -------\n    J_max : TYPE\n        DESCRIPTION.\n    gamma_0_SB07 : TYPE\n        DESCRIPTION.\n\n    '''\n\n    # Read in Sharp & Burrows (2007) broadening file\n    broad_file_SB07 = pd.read_csv(input_directory + 'SB07.broad',\n                                           sep = ' ', header=None, skiprows=1)\n    J_max = int(np.max(np.array(broad_file_SB07[0])))\n    gamma_0_SB07 = np.array(broad_file_SB07[1])\n    #n_L_SB07 = np.array(broad_file_SB07[2])       # Not really needed, as temperature exponent = 0 for all J''\n\n    return J_max, gamma_0_SB07\n\n\ndef read_custom(input_directory):\n    '''\n    Read a user-provided broadening file from the input directory\n\n    Parameters\n    ----------\n    input_directory : TYPE\n        DESCRIPTION.\n\n    Returns\n    -------\n    J_max : TYPE\n        DESCRIPTION.\n    gamma_0_air : TYPE\n        DESCRIPTION.\n    n_L_air : TYPE\n        DESCRIPTION.\n\n    '''\n\n    # Read in custom broadening file\n    broad_file_custom = pd.read_csv(input_directory + 'custom.broad',\n                                    sep = ' ', header=None, skiprows = 1)\n    J_max = int(np.max(np.array(broad_file_custom[0])))\n    gamma_0_air = np.array(broad_file_custom[1])\n    n_L_air = np.array(broad_file_custom[2])\n\n    return J_max, gamma_0_air, n_L_air\n\n\ndef gamma_L_VALD(gamma_vdw, m_s, broadener):\n    '''\n    Computes Lorentzian HWHM at 296K and 1 bar for a given broadener from a\n    tabulated VALD van der Waals broadening constant.\n\n    Parameters\n    ----------\n    gamma_vdw : float\n        van der Waals parameter from VALD.\n    m_s : float\n        mass of species whose spectral line is being broadened (u).\n    broadener : str\n        identity of broadening species (H2 or He).\n\n    Returns\n    -------\n    gamma_L_0 : float\n        Lorentzian HWHM at reference T (296K) and P (1 bar).\n    n_L : float\n        Temperature exponent (fixed to -0.7 for van der Waals theory).\n\n    '''\n\n    alpha_H = 0.666793  # Polarisability of atomic hydrogen (A^-3)\n    m_H = 1.007825      # Mass of atomic hydrogen (u)\n\n    if (broadener == 'H2'):\n        alpha_p = 0.805000  # Polarisability of molecular hydrogen (A^-3)\n        m_p = 2.01565       # Mass of molecular hydrogen (u)\n\n    elif (broadener == 'He'):\n        alpha_p = 0.205052  # Polarisability of helium (A^-3)\n        m_p = 4.002603      # Mass of helium (u)\n\n    else: print (\"Invalid broadener for VALD!\")\n\n    # Compute Lorentzian HWHM\n    gamma_L_0 = (2.2593427e7 * gamma_vdw * np.power(((m_H*(m_s+m_p))/(m_p*(m_s+m_H))), (3.0/10.0)) *\n                                           np.power((alpha_p/alpha_H), (2.0/5.0)))\n\n    # Temperature exponent\n    n_L = 0.7\n\n    return gamma_L_0, n_L\n\n\ndef gamma_L_impact(E_low, E_up, l_low, l_up, species, m_s, broadener):\n    '''\n    Computes Lorentzian HWHM at 296K and 1 bar for a given broadener using\n    van der Waals impact theory.\n\n    Parameters\n    ----------\n    E_low : float\n        Lower level energy (cm^-1).\n    E_up : float\n        Upper level energy (cm^-1).\n    l_low : int\n        Lower level orbital angular momentum.\n    l_up : int\n        Upper level orbital angular momentum.\n    species : str\n        Identity of species whose spectral line is being broadened.\n    m_s : float\n        Mass of species whose spectral line is being broadened (u).\n    broadener : str\n        Identity of broadening species (H2 or He).\n\n    Returns\n    -------\n    gamma_L_0 : float\n        Lorentzian HWHM at reference T (296K) and P (1 bar).\n    n_L : float\n        Temperature exponent (fixed to -0.7 for van der Waals theory).\n\n    '''\n\n    alpha_H = 0.666793  # Polarisability of atomic hydrogen (A^-3)\n\n    E_inf_eV = {'Li': 5.3917, 'Na': 5.1391, 'K': 4.3407, 'Rb': 4.1771, 'Cs': 3.8939}    # Ionisation energy (eV)\n    E_inf = E_inf_eV[species] * 8065.547574991239  # convert from eV to cm^-1\n\n    if (species in ['Li', 'Na','K', 'Cs', 'Rb']):\n        Z = 0   # Ion charge\n\n    if (broadener == 'H2'):\n        alpha_p = 0.805000  # Polarisability of molecular hydrogen (A^-3)\n        m_p = 2.01565       # Mass of molecular hydrogen (u)\n\n    elif (broadener == 'He'):\n        alpha_p = 0.205052  # Polarisability of helium (A^-3)\n        m_p = 4.002603      # Mass of helium (u)\n\n    else: print (\"Invalid broadener for VALD!\")\n\n    # Evaluate effective principal quantum number for lower and upper levels\n    n_low_sq = ((Ryd/100.0) * (Z + 1.0)**2)/(E_inf - E_low)\n    n_up_sq =  ((Ryd/100.0) * (Z + 1.0)**2)/(E_inf - E_up)\n\n    # Evaluate mean square orbital radius for lower and upper levels (in Bohr radii)\n    r_low_sq = (n_low_sq/(2.0*(Z+1)**2)) * (5.0*n_low_sq + 1.0 - (3.0*l_low*(l_low + 1.0)))\n    r_up_sq = (n_up_sq/(2.0*(Z+1)**2)) * (5.0*n_up_sq + 1.0 - (3.0*l_up*(l_up + 1.0)))\n\n    # For lines where the Hydrogenic approximation breaks down, return zero vdw line width\n    if (r_up_sq < r_low_sq):\n        return 0.0, 0.7   # Reference HWHM | temperature exponent (dummy in this case)\n\n    # Compute Lorentzian HWHM\n    gamma_L_0 = (0.1972 * np.power(((m_s+m_p)/(m_s*m_p)), (3.0/10.0)) *\n                          np.power((alpha_p/alpha_H), (2.0/5.0)) *\n                          np.power((r_up_sq - r_low_sq), (2.0/5.0)))\n\n    # Temperature exponent\n    n_L = 0.7\n\n    return gamma_L_0, n_L\n\n\ndef read_atom(species, nu_0, gf, E_low, E_up, J_low, l_low, l_up,\n              gamma_nat, gamma_vdw, alkali, m):\n\n    if alkali:  # Special treatments for alkali Van der Waals widths\n\n        gamma_0_H2 = np.zeros(len(nu_0))\n        gamma_0_He = np.zeros(len(nu_0))\n        n_L_H2 = np.zeros(len(nu_0))\n        n_L_He = np.zeros(len(nu_0))\n\n        for i in range(len(nu_0)):\n\n            if (gamma_vdw[i] != 0.0):  # For transitions with a VALD broadening value\n\n                gamma_0_H2[i], n_L_H2[i] = gamma_L_VALD(gamma_vdw[i], (m/u), 'H2')\n                gamma_0_He[i], n_L_He[i] = gamma_L_VALD(gamma_vdw[i], (m/u), 'He')\n\n            elif (gamma_vdw[i] == 0.0):  # For transitions without a VALD broadening value\n\n                gamma_0_H2[i], n_L_H2[i] = gamma_L_impact(E_low[i], E_up[i], l_low[i], l_up[i], species, (m/u), 'H2')\n                gamma_0_He[i], n_L_He[i] = gamma_L_impact(E_low[i], E_up[i], l_low[i], l_up[i], species, (m/u), 'He')\n\n    else:  # For non-alkali species\n\n        gamma_0_H2, n_L_H2 = gamma_L_VALD(gamma_vdw, (m/u), 'H2')\n        gamma_0_He, n_L_He = gamma_L_VALD(gamma_vdw, (m/u), 'He')\n\n    return gamma_0_H2, n_L_H2, gamma_0_He, n_L_He\n\n\ndef compute_H2_He(gamma_0_H2, T_ref, T, n_L_H2, P, P_ref, X_H2, gamma_0_He, n_L_He, X_He):\n    gamma = (gamma_0_H2 * np.power((T_ref/T), n_L_H2) * (P/P_ref) * X_H2 +   # H2+He Lorentzian HWHM for given T, P, and J (ang. mom.)\n             gamma_0_He * np.power((T_ref/T), n_L_He) * (P/P_ref) * X_He)    # Note that these are only a function of J''\n\n    return gamma\n\ndef compute_air(gamma_0_air, T_ref, T, n_L_air, P, P_ref):\n    gamma = (gamma_0_air * np.power((T_ref/T), n_L_air) * (P/P_ref))      # Air-broadened Lorentzian HWHM for given T, P, and J (ang. mom.)\n\n    return gamma\n\ndef compute_SB07(gamma_0_SB07, P, P_ref):\n    gamma = (gamma_0_SB07 * (P/P_ref))      # Equation (15) in Sharp & Burrows (2007)\n\n    return gamma\n", "meta": {"hexsha": "0deb4cfbfd32326316699b08f01576d314eb525c", "size": 12270, "ext": "py", "lang": "Python", "max_stars_repo_path": "excalibur/broadening.py", "max_stars_repo_name": "arnav-agrawal/excalibur-alpha", "max_stars_repo_head_hexsha": "0e77341b310147caeba52aea00ccf2dccf7feb72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "excalibur/broadening.py", "max_issues_repo_name": "arnav-agrawal/excalibur-alpha", "max_issues_repo_head_hexsha": "0e77341b310147caeba52aea00ccf2dccf7feb72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-23T07:39:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-23T07:39:17.000Z", "max_forks_repo_path": "excalibur/broadening.py", "max_forks_repo_name": "arnav-agrawal/excalibur-alpha", "max_forks_repo_head_hexsha": "0e77341b310147caeba52aea00ccf2dccf7feb72", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3010204082, "max_line_length": 139, "alphanum_fraction": 0.608801956, "include": true, "reason": "import numpy", "num_tokens": 3696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.18290242931817688}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'''\nQSDsan: Quantitative Sustainable Design for sanitation and resource recovery systems\nCopyright (C) 2020, Quantitative Sustainable Design Group\n\nThis module is developed by:\n    Lewis Rowles <stetsonsc@gmail.com>\n    \n\nThis module is under the University of Illinois/NCSA Open Source License.\nPlease refer to https://github.com/QSD-Group/QSDsan/blob/master/LICENSE.txt\nfor license details.\n'''\n# %%\n\n\nimport numpy as np\nfrom qsdsan import SanUnit, Construction\nfrom qsdsan.utils.loading import load_data, data_path\nimport os\n__all__ = ('StruvitePrecipitation',)\n\n#path to csv with all the inputs\n#data_path = '/Users/lewisrowles/opt/anaconda3/lib/python3.8/site-packages/exposan/biogenic_refinery/_struvite_precipitation.csv' \ndata_path += 'sanunit_data/_struvite_precipitation.tsv'\n\n### \nclass StruvitePrecipitation(SanUnit):\n    '''\n    Stuvite Precipitation for P recovery from liquid stream. Solid stuvite is recovered.\n\n    \n    Reference documents\n    -------------------\n    N/A\n    \n    Parameters\n    ----------\n    ins : WasteStream (liquid), MagnesiumHydroxide, MagnesiumCarbonate, FilterBag\n        \n    outs : WasteStream, Struvite\n        \n\n        \n    References\n    ----------\n    .. Lohman et al., Advancing Sustainable Sanitation and Agriculture \n    through Investments in Human-Derived Nutrient Systems. \n    Environ. Sci. Technol. 2020, 54, (15), 9217-9227.\n    https://dx.doi.org/10.1021/acs.est.0c03764\n    \n    .. Tarpeh et al., Evaluating ion exchange for nitrogen recovery from \n    source-separated urine in Nairobi, Kenya. Development Engineering. 2018, \n    3, 188–195.\n    https://doi.org/10.1016/j.deveng.2018.07.002\n    \n    '''\n    \n\n    def __init__(self, ID='', ins=None, outs=(), **kwargs):\n        \n        SanUnit.__init__(self, ID, ins, outs)\n\n# load data from csv each name will be self.name    \n        data = load_data(path=data_path)\n        for para in data.index:\n            value = float(data.loc[para]['expected'])\n            setattr(self, para, value)\n        del data\n        \n        for attr, value in kwargs.items():\n            setattr(self, attr, value)\n\n\n\n\n        \n# define the number of influent and effluent streams    \n    _N_ins = 4\n    _N_outs = 2\n\n# in _run: define influent and effluent streams and treatment processes \n    def _run(self):\n        waste, magnesium_hydroxide, magnesium_carbonate, bag_filter = self.ins\n        treated, struvite = self.outs\n        treated.copy_like(self.ins[0])\n        magnesium_hydroxide.phase = 's'\n        magnesium_carbonate.phase = 's'\n        bag_filter = 's'\n        struvite.phase = 's'\n    \n        # recovery of N, K, P\n        N_recovered = (waste.imass['P'] * self.P_rec_1 / self.MW_P \n                       * self.N_P_ratio_struvite * self.MW_N)  # (kg N/hr) total N recovered\n        P_recovered = waste.imass['P'] * self.P_rec_1  # (kg P/hr) total P recovered\n        K_recovered = waste.imass['K'] * self.K_rec_1 # (kg K/hr) total K recovered\n        treated.imass['NH3'] =  waste.imass['NH3'] - N_recovered # kg N / hr\n        treated.imass['P'] =  waste.imass['P'] - P_recovered # kg P / hr\n        treated.imass['K'] =  waste.imass['K'] - K_recovered # kg K / hr\n        \n        # set values needed for _design and _cost as attributes\n        self.volume_treated = waste.F_vol * 1000 * 24 # L liq / d \n        self.quantity_tanks = np.ceil(self.volume_treated / self.cycles_per_day \n                                      / self.reactor_volume) # number of tanks\n        \n        # !!! add MagnesiumHydroxide, MagnesiumCarbonate, FilterBag as influent streams and Struvite as effluent\n        magnesium_hydroxide_demand_time = (waste.imass['P'] / self.MW_P / self.Mg_dose \n                                           * self.Mg_MgOH2_ratio * self.MW_MgOH2) # (kg Mg(OH)2 per hr)\n        magnesium_hydroxide.imass['MagnesiumHydroxide'] = magnesium_hydroxide_demand_time\n        \n        magnesium_carbonate_demand_time = (waste.imass['P'] / self.MW_P / self.Mg_dose \n                                           * self.Mg_MgCO3_ratio * self.MW_MgCO3)  # (kg MgCO3 per hr)\n        magnesium_carbonate.imass['MagnesiumCarbonate'] = magnesium_carbonate_demand_time\n        \n        struvite_production_time = P_recovered / self.MW_P * self.MW_struvite # kg (NH4)MgPO4•6(H2O) / hr\n        struvite.imass['Struvite'] = struvite_production_time\n\n        filter_bag_demand_time = self.quantity_tanks * self.cycles_per_day / self.filter_reuse / 24 # bags/hr\n        self.ins[3].imass['FilterBag'] = filter_bag_demand_time # used in place of line below, not sure why its not working\n        #bag_filter.imass['FilterBag'] = filter_bag_demand_time          \n  \n     \n    #_design will include all the construction or captial impacts  \n    def _design(self):\n        design = self.design_results\n        # defining the quantities of materials/items\n        # note that these items to be to be in the _impacts_items.xlsx\n        \n        \n\n        design['StainlessSteel'] = SS_quant = self.quantity_tanks * self.reactor_weight # kg SS\n        design['PVC'] = PVC_quant = self.quantity_tanks * self.material_P_pipe * self.pvc_mass  # kg PVC\n     \n\n        \n        self.construction = (\n            Construction(item='StainlessSteel', quantity = SS_quant, quantity_unit = 'kg'),\n            Construction(item='PVC', quantity = PVC_quant, quantity_unit = 'kg'),\n            )\n        self.add_construction()\n        \n    \n    #_cost based on amount of steel and stainless plus individual components\n    def _cost(self):\n        #purchase_costs is used for capital costs\n        #can use quantities from above (e.g., self.design_results['StainlessSteel'])\n        #can be broken down as specific items within purchase_costs or grouped (e.g., 'Misc. parts')\n        self.purchase_costs['Reactor'] = (self.quantity_tanks * self.cost_P_reactor)\n        self.purchase_costs['Stirrer'] = (self.quantity_tanks * self.cost_P_stirrer)\n        self.purchase_costs['PVC'] = (self.quantity_tanks * self.material_P_pipe * self.cost_P_pipe)\n         \n        self._BM = dict.fromkeys(self.purchase_costs.keys(), 1)\n        \n        #certain parts need to be replaced based on an expected lifefime\n        #the cost of these parts is considered along with the cost of the labor to replace them\n        struvite_replacement_parts_annual_cost = 0 # USD/yr only accounts for time running\n        \n        struvite_annual_maintenance = 0 #USD/yr only accounts for time running\n        \n        self.add_OPEX =  (struvite_replacement_parts_annual_cost + struvite_annual_maintenance) / (365 * 24) # USD/hr (all items are per hour)\n        \n        # costs associated with full time opperators can be added in the TEA as staff\n      \n\n\n", "meta": {"hexsha": "a77137cd129dbf90c2bd498af54dfe9863e34a90", "size": 6816, "ext": "py", "lang": "Python", "max_stars_repo_path": "qsdsan/sanunits/_struvite_precipitation.py", "max_stars_repo_name": "stetsonrowles/QSDsan", "max_stars_repo_head_hexsha": "a74949fcf9e6ff91e9160a75bedaf6fab2191efb", "max_stars_repo_licenses": ["NCSA", "CNRI-Python", "FTL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "qsdsan/sanunits/_struvite_precipitation.py", "max_issues_repo_name": "stetsonrowles/QSDsan", "max_issues_repo_head_hexsha": "a74949fcf9e6ff91e9160a75bedaf6fab2191efb", "max_issues_repo_licenses": ["NCSA", "CNRI-Python", "FTL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qsdsan/sanunits/_struvite_precipitation.py", "max_forks_repo_name": "stetsonrowles/QSDsan", "max_forks_repo_head_hexsha": "a74949fcf9e6ff91e9160a75bedaf6fab2191efb", "max_forks_repo_licenses": ["NCSA", "CNRI-Python", "FTL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8596491228, "max_line_length": 142, "alphanum_fraction": 0.6490610329, "include": true, "reason": "import numpy", "num_tokens": 1758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.18290242931817688}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# Copyright 2020 Félix Chénier\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n#     http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nProvide functions to process kinetic data from instrumented wheelchair wheels.\n\"\"\"\n\n__author__ = \"Félix Chénier\"\n__copyright__ = \"Copyright (C) 2020 Félix Chénier\"\n__email__ = \"chenier.felix@uqam.ca\"\n__license__ = \"Apache 2.0\"\n\n\nimport kineticstoolkit.filters as filters\nimport kineticstoolkit.cycles as cycles\nfrom kineticstoolkit import TimeSeries\nfrom kineticstoolkit.decorators import unstable, dead, directory\n\nimport numpy as np\nfrom numpy import sin, cos, pi\nimport pandas as pd\nimport warnings\nimport struct  # to unpack binary data from SmartWheels' txt files\nfrom typing import Union, Optional, List\n\n\ndef read_file(filename: str, /, file_format: str = '') -> TimeSeries:\n    \"\"\"\n    Read a file containing pushrim kinetics data.\n\n    Parameters\n    ----------\n    filename\n        Name of the file to open\n    file_format\n        Format of the file. Can be either:\n\n        - 'smartwheel' (SmartWheel CSV file)\n        - 'smartwheeltxt' (SmartWheel SD-Card TXT file)\n        - 'racingwheel' (will change)\n\n    \"\"\"\n    if file_format == '':\n        warnings.warn(\"file_format will need to be explicitely specified in \"\n                      \"future versions. Now using 'smartwheel'.\",\n                      FutureWarning)\n        file_format = 'smartwheel'\n\n    if file_format == 'smartwheel':\n\n        dataframe = pd.read_csv(filename, delimiter=None, header=None)\n        if dataframe.shape[1] == 1:  # Retry with ; as separator\n            dataframe = pd.read_csv(filename, delimiter=';', header=None)\n\n        data = dataframe.to_numpy()\n        index = data[:, 1]\n        time = np.arange(0, len(index)) / 240\n        channels = data[:, 6:12]\n        forces = data[:, 18:21]\n        moments = data[:, 21:24]\n        angle_deg = data[:, 3]\n        angle_rad = np.unwrap(np.deg2rad(angle_deg))\n\n        ts = TimeSeries(time=time)\n\n        ts.data['Index'] = index\n        ts.data['Channels'] = channels\n        ts.data['Forces'] = np.block([[forces, np.zeros((len(index), 1))]])\n        ts.data['Moments'] = np.block([[moments, np.zeros((len(index), 1))]])\n        ts.data['Angle'] = angle_rad\n\n        ts.add_data_info('Channels', 'Unit', 'raw')\n        ts.add_data_info('Forces', 'Unit', 'N')\n        ts.add_data_info('Moments', 'Unit', 'Nm')\n        ts.add_data_info('Angle', 'Unit', 'rad')\n\n    elif file_format == 'racingwheel':\n\n        dataframe = pd.read_csv(filename, delimiter=',')\n        data = dataframe.to_numpy()\n        time = data[:, 0]\n        channels = data[:, 1:7]\n        battery = data[:, 8]\n\n        ts = TimeSeries(time=time)\n\n        ts.data['Channels'] = channels\n        ts.add_data_info('Channels', 'Unit', 'raw')\n\n        ts.data['Battery'] = battery\n        ts.add_data_info('Battery', 'Unit', 'raw')\n\n    elif file_format == 'smartwheeltxt':\n\n        data = {'ch1': [], 'ch2': [], 'ch3': [],\n                'ch4': [], 'ch5': [], 'ch6': [], 'angle_ticks': []}\n\n        length = 0\n        with open(filename, 'rb') as fid:\n\n            while True:\n                try:\n                    _ = fid.read(2)\n                    data['ch1'].append(struct.unpack('h', fid.read(2))[0])\n                    data['ch2'].append(struct.unpack('h', fid.read(2))[0])\n                    data['ch3'].append(struct.unpack('h', fid.read(2))[0])\n                    data['ch4'].append(struct.unpack('h', fid.read(2))[0])\n                    data['ch5'].append(struct.unpack('h', fid.read(2))[0])\n                    data['ch6'].append(struct.unpack('h', fid.read(2))[0])\n                    data['angle_ticks'].append(\n                        struct.unpack('i', fid.read(4))[0])\n                    _ = fid.read(8)\n                    length += 1\n                except Exception:\n                    break\n\n        ch1 = np.array(data['ch1'][1:length])  # Remove 1st sample to be\n        ch2 = np.array(data['ch2'][1:length])  # consistent with CSV file\n        ch3 = np.array(data['ch3'][1:length])\n        ch4 = np.array(data['ch4'][1:length])\n        ch5 = np.array(data['ch5'][1:length])\n        ch6 = np.array(data['ch6'][1:length])\n        angle_ticks = np.array(data['angle_ticks'][1:length])\n\n        # Keep only 12 least significant bytes\n        ch1 = np.mod(ch1, 2 ** 12)\n        ch2 = np.mod(ch2, 2 ** 12)\n        ch3 = np.mod(ch3, 2 ** 12)\n        ch4 = np.mod(ch4, 2 ** 12)\n        ch5 = np.mod(ch5, 2 ** 12)\n        ch6 = np.mod(ch6, 2 ** 12)\n\n        # Convert angle in radian\n        angle = angle_ticks / 4096 * 2 * np.pi\n\n        ts = TimeSeries(\n            time=np.linspace(0, (length - 1) / 240, length - 1))\n        ts.data['Channels'] = np.concatenate(\n            [ch1[:, np.newaxis],\n             ch2[:, np.newaxis],\n             ch3[:, np.newaxis],\n             ch4[:, np.newaxis],\n             ch5[:, np.newaxis],\n             ch6[:, np.newaxis]], axis=1)\n        ts.data['Angle'] = angle\n\n        ts.add_data_info('Channels', 'Unit', 'raw')\n        ts.add_data_info('Angle', 'Unit', 'rad')\n\n    else:\n        raise ValueError('Unknown file format.')\n\n    return ts\n\n\n@unstable\ndef find_recovery_indices(Mz: np.ndarray, /) -> np.ndarray:\n    \"\"\"\n    Find recovery indices based on a vector of propulsion moments.\n\n    This function analyzes the Mz moments to find which data correspond to\n    pushes and which data correspond to recoveries. The method is very\n    conservative on what could be considered as a recovery, so that every\n    index returned by this function is almost certain to correspond to a\n    recovery. This function is used by `pushrimkinetics.remove_sinusoids`\n    to identify the instants with no hand contact. It should not be used to\n    isolate the push and recovery phases (use `ktk.cycles.detect_cycles()`\n    instead).\n\n    Parameters\n    ----------\n    Mz\n        Array that contains the propulsion moments in Nm.\n\n    Returns\n    -------\n    np.ndarray\n        Array of bools where each True represents recovery.\n\n    See Also\n    --------\n    ktk.cycles.detect_cycles\n\n    \"\"\"\n    Mz = Mz.copy()\n\n    threshold = 2.24  # (Nm): max tolerance for the remaining values.\n\n    while np.nanmax(Mz) - np.nanmin(Mz) > threshold:\n\n        # Remove 1% of data that are the farthest to the median:\n\n        # Sort data\n        index_to_remove = np.argsort(np.abs(Mz - np.nanmedian(Mz)))\n        sorted_Mz = Mz[index_to_remove]\n        index_to_remove = index_to_remove[~np.isnan(sorted_Mz)]\n\n        # Remove the 1% upper.\n        index_to_remove = index_to_remove[\n            int(0.99*len(index_to_remove))-1:]\n\n        # Assign nan to these data\n        Mz[index_to_remove] = np.nan\n\n    index = ~np.isnan(Mz)\n\n    return index\n\n\ndef remove_offsets(\n        kinetics: TimeSeries,\n        baseline_kinetics: Optional[TimeSeries] = None\n) -> TimeSeries:\n    \"\"\"\n    Remove dynamic offsets in forces and moments.\n\n    Parameters\n    ----------\n    kinetics\n        TimeSeries that contains at least Forces, Moments and Angle data.\n    baseline_kinetics\n        Optional. TimeSeries that contains at least Forces and Moments data.\n        This TimeSeries contains a baseline trial, where the wheelchair must be\n        pushed by an operator and where no external force must be applied on\n        the pushrims. If no baseline is provided, the baseline is calculated\n        based on a detection of recoveries in the supplied kinetics\n        TimeSeries.\n\n    Returns\n    -------\n    TimeSeries\n        A copy of the input TimeSeries, where sinusoids are removed from\n        Forces and Moments data.\n\n    References\n    ----------\n    F. Chénier, R. Aissaoui, C. Gauthier, and D. H. Gagnon,\n    \"Wheelchair pushrim kinetics measurement: A method to cancel\n    inaccuracies due to pushrim weight and wheel camber,\" Medical\n    Engineering and Physics, vol. 40, pp. 75--86, 2017.\n\n    \"\"\"\n    kinetics = kinetics.copy()\n\n    if baseline_kinetics is None:\n        # Create baseline kinetics.\n        recovery_index = find_recovery_indices(kinetics.data['Moments'][:, 2])\n        f_ofs = np.hstack((kinetics.data['Forces'][recovery_index, 0:3],\n                           kinetics.data['Moments'][recovery_index, 0:3]))\n        theta_baseline = kinetics.data['Angle'][recovery_index]\n\n    else:\n        # Use baseline kinetics.\n        f_ofs = np.hstack((baseline_kinetics.data['Forces'][:, 0:3],\n                           baseline_kinetics.data['Moments'][:, 0:3]))\n        theta_baseline = baseline_kinetics.data['Angle'][:]\n\n    # Do the regression\n    theta_baseline = theta_baseline[:, np.newaxis]\n    q = np.hstack((\n        np.sin(theta_baseline),\n        np.cos(theta_baseline),\n        np.ones((len(theta_baseline), 1))\n    ))\n    A = np.linalg.lstsq(q, f_ofs, rcond=None)\n    A = A[0]\n\n    # Apply the regression to forces and moments\n    theta = kinetics.data['Angle']\n    theta = theta[:, np.newaxis]\n\n    f = np.hstack((kinetics.data['Forces'][:, 0:3],\n                   kinetics.data['Moments'][:, 0:3]))\n\n    q = np.hstack((\n        np.sin(theta),\n        np.cos(theta),\n        np.ones((len(theta), 1))\n    ))\n\n    f = f - q @ A\n\n    # Make the output timeseries\n    kinetics.data['Forces'][:, 0:3] = f[:, 0:3]\n    kinetics.data['Moments'][:, 0:3] = f[:, 3:6]\n\n    return kinetics\n\n\ndef calculate_forces_and_moments(\n        kinetics: TimeSeries, /,\n        gains: Union[np.ndarray, str],\n        offsets: np.ndarray = np.zeros((6)), *,\n        transducer: str = 'force_cell',\n        reference_frame: str = 'wheel') -> TimeSeries:\n    \"\"\"\n    Calculate pushrim forces and moments based on raw channel values.\n\n    For standard force cells (with each channel being a raw value\n    corresponding to Fx, Fy, Fz, Mx, My, Mz, respectively), calculates\n    the forces and moments using a sensitivity matrix (gains) and an\n    offset vector (offsets):\n\n    ``[Fx, Fy, Fz, Mx, My, Mz] = gains @ channels + offsets``\n\n    For SmartWheel, calculates the forces and moments using a gain\n    vector (gains) and an offset vector (offsets).\n\n    Parameters\n    ----------\n    kinetics\n        Input TimeSeries that must contain a 'Channels' key in its data dict.\n    gains\n        6x6 gain matrix (force_cell) or gain vector of length 6 (smartwheel).\n    offsets\n        Optional. Offset vector of length 6.\n    transducer\n        Optional. 'force_cell' or 'smartwheel'.\n    reference_frame\n        Optional. 'wheel' or 'hub'. 'wheel' to report the forces and moments\n        into the local wheel's reference frame; 'hub' to compensate for the\n        wheel rotation and match the reference frame used by the SmartWheel:\n        x anteroposterior, y in the wheel plane, upward for non-camberred\n        wheels, and z perpendicular to the wheel plane, outward.\n\n    Returns\n    -------\n    TimeSeries\n        A copy of the input TimeSeries, with the added 'Forces'\n        and 'Moments' data keys.\n\n    Note\n    ----\n    Some calibration matrices are provided as examples in the\n    ``pushrimkinetics.CALIBRATION_MATRICES`` dictionary. This dictionary can\n    be used directly using dict unpacking. For example::\n\n        ktk.pushrimkinetics.calculate_force_and_moments(\n            kinetics,\n            **ktk.pushrimkinetics.CALIBRATION_MATRICES['SmartWheel_123'],\n            reference_frame='level'\n        )\n\n    \"\"\"\n    # Calculate the forces and moments and add to the output\n    if transducer == 'smartwheel':\n\n        # Calculate the rotation angle to apply to the calculated kinetics\n        if reference_frame == 'wheel':\n            theta = np.array([0.0])\n        elif reference_frame == 'hub':\n            theta = kinetics.data['Angle']\n        else:\n            raise ValueError(\"reference_frame must be 'wheel' or 'hub'\")\n\n        # Extract channels and angle\n        ch = kinetics.data['Channels'] - 2048\n\n        # Calculate the forces and moments\n        Fx = gains[0] * (\n            ch[:, 0] * sin(theta) +\n            ch[:, 2] * sin(theta + 2 * pi / 3) +\n            ch[:, 4] * sin(theta + 4 * pi / 3)) + offsets[0]\n\n        Fy = gains[1] * (\n            ch[:, 0] * cos(theta) +\n            ch[:, 2] * cos(theta + 2 * pi / 3) +\n            ch[:, 4] * cos(theta + 4 * pi / 3)) + offsets[1]\n\n        Fz = gains[2] * (ch[:, 1] + ch[:, 3] + ch[:, 5]) + offsets[2]\n\n        Mx = gains[3] * (\n            ch[:, 1] * sin(theta) +\n            ch[:, 3] * sin(theta + 2 * pi / 3) +\n            ch[:, 5] * sin(theta + 4 * pi / 3)) + offsets[3]\n\n        My = gains[4] * (\n            ch[:, 1] * cos(theta) +\n            ch[:, 3] * cos(theta + 2 * pi / 3) +\n            ch[:, 5] * cos(theta + 4 * pi / 3)) + offsets[4]\n\n        Mz = gains[5] * (ch[:, 0] + ch[:, 2] + ch[:, 4]) + offsets[5]\n        forces_moments = np.block([Fx[:, np.newaxis],\n                                   Fy[:, np.newaxis],\n                                   Fz[:, np.newaxis],\n                                   Mx[:, np.newaxis],\n                                   My[:, np.newaxis],\n                                   Mz[:, np.newaxis]])\n\n    elif transducer == 'force_cell':\n\n        # Calculate the rotation angle to apply to the calculated kinetics\n        if reference_frame == 'wheel':\n            theta = np.array([0.0])\n        elif reference_frame == 'hub':\n            raise NotImplementedError(\"hub reference_frame not implemented yet\"\n                                      \"for force_cell transducers.\")\n        else:\n            raise ValueError(\"reference_frame must be 'wheel' or 'hub'\")\n\n        n_frames = kinetics.data['Channels'].shape[0]\n\n        forces_moments = np.empty((n_frames, 6))\n        for i_frame in range(n_frames):\n            forces_moments[i_frame] = (gains @\n                                       kinetics.data['Channels'][i_frame] +\n                                       offsets)\n\n    # Format these data in the output timeseries\n    kinetics = kinetics.copy()\n\n    kinetics.data['Forces'] = np.concatenate(\n        [forces_moments[:, 0:3], np.zeros((forces_moments.shape[0], 1))],\n        axis=1)\n    kinetics.add_data_info('Forces', 'Unit', 'N')\n\n    kinetics.data['Moments'] = np.concatenate(\n        [forces_moments[:, 3:6], np.zeros((forces_moments.shape[0], 1))],\n        axis=1)\n    kinetics.add_data_info('Moments', 'Unit', 'Nm')\n\n    return(kinetics)\n\n\ndef calculate_velocity(tsin: TimeSeries, /) -> TimeSeries:\n    \"\"\"\n    Calculate velocity based on wheel angle.\n\n    The velocity is calculated by deriving the angle using a 2nd order\n    Savitzky-Golay filter of length 21. This filter has been experimentally\n    validated to maximize the signal-to-noise ratio for a SmartWheel recording\n    at 240 Hz. This function may change signature in the future to include\n    other filtering options. To manually get the velocity using a custom\n    filter, please see the ``ktk.filters`` module.\n\n    Parameters\n    ----------\n    tsin\n        TimeSeries that contains at least the data key 'Angle'.\n\n    Returns\n    -------\n    TimeSeries\n                A copy of the TimeSeries with the added data key 'Velocity'.\n\n    See Also\n    --------\n    ktk.filters.butter : Butterworth filter for TimeSeries\n    ktk.filters.savgol : Savitsky-golay filter for TimeSeries\n    ktk.filters.deriv : Derivative filter for TimeSeries\n\n    \"\"\"\n    tsangle = TimeSeries()\n    tsangle.time = tsin.time\n    tsangle.data['Angle'] = tsin.data['Angle']\n    tsvelocity = filters.savgol(tsangle, window_length=21,\n                                poly_order=2, deriv=1)\n    tsout = tsin.copy()\n    tsout.data['Velocity'] = tsvelocity.data['Angle']\n    try:\n        tsout.add_data_info('Velocity', 'Unit',\n                            tsout.data_info['Angle']['Unit'] + '/s')\n    except KeyError:\n        pass\n    return tsout\n\n\ndef calculate_power(tsin: TimeSeries, /) -> TimeSeries:\n    \"\"\"\n    Calculate power based on wheel velocity and moment.\n\n    Parameters\n    ----------\n    tsin\n        TimeSeries that contains at least the data keys 'Velocity' and\n        'Moments'. The units must be consistent (e.g., rad/s and Nm)\n\n    Returns\n    -------\n    TimeSeries\n        A copy of the TimeSeries with the added data key 'Power'.\n\n    \"\"\"\n    tsout = tsin.copy()\n    tsout.data['Power'] = (tsout.data['Velocity'] *\n                           tsout.data['Moments'][:, 2])\n    tsout.add_data_info('Power', 'Unit', 'W')\n    return tsout\n\n\n#--- Deprecated functions ---#\n@dead(since=\"October 2020\",\n      until=\"December 2021\",\n      details=\"Please use ktk.cycles.detect_cycles instead.\")\ndef detect_pushes(\n        tsin: TimeSeries, /, *,\n        push_threshold: float = 5.0,\n        recovery_threshold: float = 2.0,\n        min_push_time: float = 0.1,\n        min_push_force: float = 30.0) -> TimeSeries:\n    \"\"\"\n    Detect pushes and recoveries automatically.\n\n    Parameters\n    ----------\n    tsin\n        Input TimeSeries that must contain a 'Forces' key in its data dict.\n    push_threshold\n        Optional. The total force over which a push phase is triggered, in\n        newton.\n    recovery_threshold\n        Optional. The total force under which a recovery phase is triggered,\n        in newton.\n    min_push_time\n        Optional. The minimum time required for a push time, in seconds.\n        Detected pushes that last less than this minimum time are removed from\n        the push analysis.\n    min_recovery_time\n        Optional. The minimum time required for a recovery time, in seconds.\n        Detected recoveries that last less than this minimum time are removed\n        from the push analysis.\n    min_push_force\n        Optional. The minimum total push force in N under which the detected\n        push is discarded. For example, if the user puts their hands on the\n        pushrim before starting propelling, this may be detected as a push.\n        Using a minimum push force removes these misdetected pushes.\n\n    Returns\n    -------\n    TimeSeries\n        A copy of tsin with the following added events:\n        - 'push'\n        - 'recovery'\n\n    \"\"\"\n    # Calculate the total force\n    f_tot = np.sqrt(np.sum(tsin.data['Forces']**2, axis=1))\n    ts_force = TimeSeries(time=tsin.time, data={'Ftot': f_tot})\n    ts_force.events = tsin.events\n\n    # Smooth the total force to avoid detecting pushes on glitches\n    ts_force = filters.smooth(ts_force, 11)\n\n    # Remove the median if it existed\n    ts_force.data['Ftot'] = \\\n        ts_force.data['Ftot'] - np.median(ts_force.data['Ftot'])\n\n    # Find the pushes\n    ts_force = cycles.detect_cycles(\n        ts_force, 'Ftot',\n        event_name1='push',\n        event_name2='recovery',\n        threshold1=push_threshold,\n        threshold2=recovery_threshold,\n        min_duration1=min_push_time,\n        min_peak_height1=min_push_force)\n\n    # Form the output timeseries\n    tsout = tsin.copy()\n    tsout.events = ts_force.events\n\n    return tsout\n\n\n@dead(since=\"October 2020\",\n      until=\"December 2021\",\n      details=\"Please use ktk.pushrimkinetics.remove_offsets instead.\")\ndef remove_sinusoids(\n        kinetics: TimeSeries,\n        baseline_kinetics: Optional[TimeSeries] = None) -> TimeSeries:\n    \"\"\"Remove offsets.\"\"\"\n    return remove_offsets(kinetics, baseline_kinetics)\n\n\n#--- Some calibration matrices ---#\nCALIBRATION_MATRICES = {}\nCALIBRATION_MATRICES['SmartWheel_93'] = {\n    'gains': np.array([-0.1080, 0.1080, 0.0930, 0.0222, -0.0222, 0.0234999]),\n    'offsets': np.array([0.0, 10.0, 0.0, 0.0, 0.0, 0.0]),\n    'transducer': 'smartwheel',\n}\nCALIBRATION_MATRICES['SmartWheel_94'] = {\n    'gains': np.array([-0.1070, 0.1070, 0.0960, 0.0222, -0.0222, 0.0230]),\n    'offsets': np.array([0.0, 10.0, 0.0, 0.0, 0.0, 0.0]),\n    'transducer': 'smartwheel',\n}\nCALIBRATION_MATRICES['SmartWheel_123'] = {\n    'gains': np.array([-0.106, 0.106, 0.094, 0.022, -0.022, 0.0234999]),\n    'offsets': np.array([0.0, 10.0, 0.0, 0.0, 0.0, 0.0]),\n    'transducer': 'smartwheel',\n}\nCALIBRATION_MATRICES['SmartWheel_124'] = {\n    'gains': np.array([-0.106, 0.106, 0.0949999, 0.0215, -0.0215, 0.0225]),\n    'offsets': np.array([0.0, 10.0, 0.0, 0.0, 0.0, 0.0]),\n    'transducer': 'smartwheel',\n}\nCALIBRATION_MATRICES['SmartWheel_125'] = {\n    'gains': np.array([-0.104, 0.104, 0.0979999, 0.0215, -0.0215, 0.0225]),\n    'offsets': np.array([0.0, 10.0, 0.0, 0.0, 0.0, 0.0]),\n    'transducer': 'smartwheel',\n}\nCALIBRATION_MATRICES['SmartWheel_126'] = {\n    'gains': np.array([-0.1059999, 0.1059999, 0.086, 0.021, -0.021, 0.023]),\n    'offsets': np.array([0.0, 10.0, 0.0, 0.0, 0.0, 0.0]),\n    'transducer': 'smartwheel',\n}\nCALIBRATION_MATRICES['SmartWheel_126_S18'] = {\n    'gains': np.array([-0.1083, 0.1109, 0.0898, 0.0211, -0.0194, 0.0214]),\n    'offsets': np.array([0.0, 10.0, 0.0, 0.0, 0.0, 0.0]),\n    'transducer': 'smartwheel',\n}\nCALIBRATION_MATRICES['SmartWheel_179_S18'] = {\n    'gains': np.array([-0.1399, 0.1091, 0.0892, 0.0240, -0.0222, 0.0241]),\n    'offsets': np.array([0.0, 10.0, 0.0, 0.0, 0.0, 0.0]),\n    'transducer': 'smartwheel',\n}\nCALIBRATION_MATRICES['SmartWheel_180_S18'] = {\n    'gains': np.array([-0.1069, 0.1091, 0.0932, 0.0240, -0.0226, 0.0238]),\n    'offsets': np.array([0.0, 10.0, 0.0, 0.0, 0.0, 0.0]),\n    'transducer': 'smartwheel',\n}\nCALIBRATION_MATRICES['SmartWheel_181_S18'] = {\n    'gains': np.array([-0.1152, 0.1095, 0.0791, 0.0229, -0.0197, 0.0220]),\n    'offsets': np.array([0.0, 10.0, 0.0, 0.0, 0.0, 0.0]),\n    'transducer': 'smartwheel',\n}\nCALIBRATION_MATRICES['MOSA_Racing_1'] = {\n    'gains': (np.array([\n        [201.027, 1.387, 2.077, -3.852, -1.837, -1.519],\n        [-0.840, 201.396, 2.119, 0.083, -6.877, 4.482],\n        [-1.935, -1.643, 402.286, 1.687, 0.897, -23.616],\n        [0.213, 0.122, 0.120, 25.190, -0.013, 0.147],\n        [-0.072, 0.286, 0.076, 0.012, 25.430, 0.146],\n        [0.016, -0.015, 0.046, -0.099, -0.076, 25.206]])  # Cell calibration\n        / (2.**15) / 10  # ADC gains\n        / np.array([-2., -2., -2., -2., -4., -4.])  # Board gains\n    ),\n    'offsets': [-111.3874, -63.3298, -8.6596, 1.8089, 1.5761, -0.8869],\n    'transducer': 'force_cell',\n}\n\n\nmodule_locals = locals()\n\n\ndef __dir__():  # pragma: no cover\n    return directory(module_locals)\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    import doctest\n    doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)\n", "meta": {"hexsha": "ec1e57986b1308b7426ca1f200d158e2e1e4c885", "size": 22714, "ext": "py", "lang": "Python", "max_stars_repo_path": "kineticstoolkit/pushrimkinetics.py", "max_stars_repo_name": "alcantarar/kineticstoolkit", "max_stars_repo_head_hexsha": "d73f6a1102ca40376e52a8ab8575d7fa9591834f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2020-10-08T12:53:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T17:20:15.000Z", "max_issues_repo_path": "kineticstoolkit/pushrimkinetics.py", "max_issues_repo_name": "alcantarar/kineticstoolkit", "max_issues_repo_head_hexsha": "d73f6a1102ca40376e52a8ab8575d7fa9591834f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 81, "max_issues_repo_issues_event_min_datetime": "2020-10-08T11:49:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T23:26:18.000Z", "max_forks_repo_path": "kineticstoolkit/pushrimkinetics.py", "max_forks_repo_name": "alcantarar/kineticstoolkit", "max_forks_repo_head_hexsha": "d73f6a1102ca40376e52a8ab8575d7fa9591834f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-14T02:59:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T02:59:04.000Z", "avg_line_length": 34.0539730135, "max_line_length": 79, "alphanum_fraction": 0.5937747645, "include": true, "reason": "import numpy,from numpy", "num_tokens": 6321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.36296920551961687, "lm_q1q2_score": 0.18290242237337295}}
{"text": "\"\"\"\nModule for rover perception.\n\nContains functions for processing rover's front camera image frames\nand updating rover state.\n\nObjective:\nTurn rover camera 3D images into a 2D perspective world-view of the\nrover environment that identifies regions of interests (ROIs), and\nsuperimpose this view on the ground truth worldmap.\n\nNOTE:\n\nUnits:\ntime -- seconds\ndistance -- meters\nvelocity -- meters/second\nangle, heading -- degrees\nyaw, pitch, roll -- degrees\n\nShort Forms:\npixpts -- pixel points\nnav -- navigable terrain pixels\nobs -- obstacle pixels\nrock -- rock pixels\n\nAbbreviations:\nROI -- Regions of interest\npf -- perspective frame\nrf -- rover frame\nwf -- world frame\n\n\"\"\"\n\n__author__ = 'Salman Hashmi, Ryan Keenan'\n__license__ = 'BSD License'\n\n\nfrom collections import namedtuple\n\nimport numpy as np\nimport cv2\n\n\ndef color_thresh(input_img, rgb_thresh=(160, 160, 160),\n                 low_bound=(75, 130, 130), upp_bound=(255, 255, 255)):\n    \"\"\"\n    Apply color thresholds to extract pixels of navigable/obstacles/rocks.\n\n    Keyword arguments:\n    input_img -- numpy image on which RGB threshold is applied\n    rgb_thresh -- RGB thresh tuple above which only ground pixels are detected\n    low/up_bounds -- HSV tuples defining color range of gold rock samples\n\n    Return value:\n    thresh_imgs -- namedtuple of binary images identifying nav/obs/rock pixels\n\n    \"\"\"\n    # Create arrays of zeros same xy size as input_img, but single channel\n    nav_img = np.zeros_like(input_img[:, :, 0])\n    obs_img = np.zeros_like(input_img[:, :, 0])\n\n    # Convert BGR input_img to HSV for rock samples\n    hsv_img = cv2.cvtColor(input_img, cv2.COLOR_BGR2HSV)\n\n    # Require that each of the R(0), G(1), B(2) pixels be above all three\n    # rgb_thresh values such that pixpts_above_thresh will now contain a\n    # boolean array with \"True\" where threshold was met\n    pixpts_above_thresh = ((input_img[:, :, 0] > rgb_thresh[0])\n                           & (input_img[:, :, 1] > rgb_thresh[1])\n                           & (input_img[:, :, 2] > rgb_thresh[2]))\n\n    pixpts_nonzero = ((input_img[:, :, 0] > 0)\n                      & (input_img[:, :, 1] > 0)\n                      & (input_img[:, :, 2] > 0))\n\n    # obstacle pixels are those non-zero pixels where rgb_thresh was not met\n    obs_pixpts = np.logical_and(\n        pixpts_nonzero, np.logical_not(pixpts_above_thresh)\n        )\n    # Index the array of zeros with the boolean array and set to 1\n    # those pixels where ROI threshold was met\n    nav_img[pixpts_above_thresh] = 1\n    obs_img[obs_pixpts] = 1\n\n    # Threshold the HSV image to get only colors for gold rock samples\n    rock_img = cv2.inRange(hsv_img, low_bound, upp_bound)\n\n    # Return the threshed binary images\n    ThreshedImages = namedtuple('ThreshedImages', 'nav obs rock')\n    thresh_imgs = ThreshedImages(nav_img, obs_img, rock_img)\n\n    return thresh_imgs\n\n\ndef perspect_transform(src_img, dst_grid=10, bottom_offset=6):\n    \"\"\"\n    Apply a perspective transformation to input 3D image.\n\n    Keyword arguments:\n    src_img -- 3D numpy image on which perspective transform is applied\n    dst_grid -- size of 2D output image box of 10x10 pixels equaling 1 Sq m\n    bottom_offset -- bottom of cam image is some distance in front of rover\n\n    Return value:\n    dst_img -- 2D warped numpy image with overhead view\n\n    \"\"\"\n    # Dimension of source image from rover camera\n    height, width = src_img.shape[0], src_img.shape[1]\n\n    # Numpy array of four source points defining a grid on input 3D image\n    # acquired from calibration data in test notebook\n    src_x1, src_y1 = 14, 140\n    src_x2, src_y2 = 301, 140\n    src_x3, src_y3 = 200, 96\n    src_x4, src_y4 = 118, 96\n\n    # Corresponding destination points on output 2D overhead image\n    dst_x1, dst_y1 = (width/2 - dst_grid/2), (height-bottom_offset)\n    dst_x2, dst_y2 = (width/2 + dst_grid/2), (height-bottom_offset)\n    dst_x3, dst_y3 = (width/2 + dst_grid/2), (height-dst_grid-bottom_offset)\n    dst_x4, dst_y4 = (width/2 - dst_grid/2), (height-dst_grid-bottom_offset)\n\n    src_points_3d = np.float32([[src_x1, src_y1],\n                                [src_x2, src_y2],\n                                [src_x3, src_y3],\n                                [src_x4, src_y4]])\n\n    dst_points_2d = np.float32([[dst_x1, dst_y1],\n                                [dst_x2, dst_y2],\n                                [dst_x3, dst_y3],\n                                [dst_x4, dst_y4]])\n\n    transform_matrix = cv2.getPerspectiveTransform(src_points_3d,\n                                                   dst_points_2d)\n    # Keep same size as source image\n    dst_img = cv2.warpPerspective(src_img, transform_matrix, (width, height))\n\n    return dst_img\n\n\ndef perspect_to_rover(binary_img):\n    \"\"\"\n    Transform pixel points from perspective frame to rover frame.\n\n    Keyword arguments:\n    binary_img -- single channel 2D warped numpy image in perspective frame\n\n    Return value:\n    pixpts_rf -- tuple of numpy arrays of pixel x,y points in rover frame\n\n    \"\"\"\n    # Dimension of input image\n    height, width = binary_img.shape[0], binary_img.shape[1]\n\n    # Identify all nonzero pixel coords in the binary image\n    ypix_pts_pf, xpix_pts_pf = binary_img.nonzero()\n\n    # Calculate pixel positions with reference to rover's coordinate\n    # frame given that rover front camera itself is at center bottom\n    # of the photographed image\n    xpix_pts_rf = -(ypix_pts_pf - height).astype(np.float)\n    ypix_pts_rf = -(xpix_pts_pf - width/2).astype(np.float)\n    pixpts_rf = xpix_pts_rf, ypix_pts_rf\n\n    return pixpts_rf\n\n\ndef to_polar_coords(pixpts):\n    \"\"\"\n    Convert cartesian coordinates of pixels to polar coordinates.\n\n    Keyword arguments:\n    pixpts -- tuple of numpy arrays of pixel x,y points\n\n    Return value:\n    dists, angles -- distance(m) and angles(deg) to pixpts\n\n    \"\"\"\n    rad2deg = 180./np.pi\n    xpix_pts, ypix_pts = pixpts\n\n    dists = np.sqrt(xpix_pts**2 + ypix_pts**2)\n    angles = np.arctan2(ypix_pts, xpix_pts)*rad2deg\n\n    return dists, angles\n\n\ndef rotate_pixpts(pixpts, angle):\n    \"\"\"\n    Geometrically rotate pixel points by specified angle.\n\n    Keyword arguments:\n    pixpts -- tuple of numpy arrays of pixel x,y points\n    angle -- rotation angle\n\n    Return value:\n    pixpts_rot -- namedtuple of numpy arrays of pixel x,y points rotated\n\n    \"\"\"\n    deg2rad = np.pi/180.\n    angle_rad = angle*deg2rad\n    xpix_pts, ypix_pts = pixpts\n\n    xpix_pts_rotated = xpix_pts*np.cos(angle_rad) - ypix_pts*np.sin(angle_rad)\n    ypix_pts_rotated = xpix_pts*np.sin(angle_rad) + ypix_pts*np.cos(angle_rad)\n\n    PixPointsRot = namedtuple('PixPointsRot', 'x y')\n    pixpts_rot = PixPointsRot(xpix_pts_rotated, ypix_pts_rotated)\n\n    return pixpts_rot\n\n\ndef translate_pixpts(pixpts_rot, translation, scale_factor=10):\n    \"\"\"\n    Geometrically translate rotated pixel points by rover position.\n\n    Keyword arguments:\n    pixpts_rot -- namedtuple of numpy arrays of pixel x,y points rotated\n    translation -- tuple of displacements along x,y in world frame\n    scale_factor -- between world and rover frame pixels\n\n    Return value:\n    pixpts_tran -- namedtuple of numpy arrays of pixel x,y points translated\n\n    \"\"\"\n    translation_x, translation_y = translation\n\n    xpix_pts_translated = pixpts_rot.x/scale_factor + translation_x\n    ypix_pts_translated = pixpts_rot.y/scale_factor + translation_y\n\n    PixPointsTran = namedtuple('PixPointsTran', 'x y')\n    pixpts_tran = PixPointsTran(xpix_pts_translated, ypix_pts_translated)\n\n    return pixpts_tran\n\n\ndef rover_to_world(pixpts_rf, rover_pos, rover_yaw, world_size=200):\n    \"\"\"\n    Transform pixel points of ROIs from rover frame to world frame.\n\n    Keyword arguments:\n    pixpts_rf -- tuple of numpy arrays of x,y pixel points in rover frame\n    rover_pos -- tuple of rover x,y position in world frame\n    rover_yaw -- rover yaw angle in world frame\n    world_size -- integer length of square world map of 200 x 200 pixels\n\n    Return value:\n    pixpts_wf -- namedtuple of numpy arrays of pixel x,y points in world frame\n\n    \"\"\"\n    # Apply rotation and translation\n    pixpts_rot = rotate_pixpts(pixpts_rf, rover_yaw)\n    pixpts_tran = translate_pixpts(pixpts_rot, rover_pos)\n\n    # Clip pixels to be within world size\n    xpix_pts_wf = np.clip(np.int_(pixpts_tran.x), 0, world_size-1)\n    ypix_pts_wf = np.clip(np.int_(pixpts_tran.y), 0, world_size-1)\n\n    # Define a named tuple for the points of the three ROIs\n    PixPointsWf = namedtuple('PixPointsWf', 'x y')\n    pixpts_wf = PixPointsWf(xpix_pts_wf, ypix_pts_wf)\n\n    return pixpts_wf\n\n\ndef inv_translate_pixpts(pixpts_wf, translation, scale_factor=10):\n    \"\"\"\n    Inverse translate pixel points from world frame.\n\n    Keyword arguments:\n    pixpts_wf -- tuple of numpy arrays of x,y pixel points in world frame\n    translation -- tuple of displacements along x,y in world frame\n    scale_factor -- between world and rover frame pixels\n\n    Return value:\n    pixpts_rot -- namedtuple of numpy arrays of pixel x,y points in prior\n                  rotated positions\n    \"\"\"\n    translation_x, translation_y = translation\n    xpix_pts_wf, ypix_pts_wf = pixpts_wf\n\n    xpix_pts_rotated = (xpix_pts_wf - translation_x)*scale_factor\n    ypix_pts_rotated = (ypix_pts_wf - translation_y)*scale_factor\n\n    PixPointsRot = namedtuple('PixPointsRot', 'x y')\n    pixpts_rot = PixPointsRot(xpix_pts_rotated, ypix_pts_rotated)\n\n    return pixpts_rot\n\n\ndef inv_rotate_pixpts(pixpts_rot, angle):\n    \"\"\"\n    Inverse rotate rotated pixel points to their original positions.\n\n    Keyword arguments:\n    pixpts_rot -- namedtuple of numpy arrays of x,y pixel points rotated\n    angle -- rotation angle in degrees\n\n    Return value:\n    pixpts -- namedtuple of numpy arrays of pixel x,y points in\n              original positions\n    \"\"\"\n    deg2rad = np.pi/180.\n    angle_rad = angle*deg2rad\n\n    xpix_pts = pixpts_rot.x*np.cos(angle_rad) + pixpts_rot.y*np.sin(angle_rad)\n    ypix_pts = -pixpts_rot.x*np.sin(angle_rad) + pixpts_rot.y*np.cos(angle_rad)\n\n    PixPoints = namedtuple('PixPoints', 'x y')\n    pixpts = PixPoints(xpix_pts, ypix_pts)\n\n    return pixpts\n\n\ndef world_to_rover(pixpts_wf, rover_pos, rover_yaw):\n    \"\"\"\n    Transform pixel points of ROIs from world frame to rover frame.\n\n    Keyword arguments:\n    pixpts_wf -- tuple of numpy arrays of x,y pixel points in world frame\n    rover_pos -- tuple of rover x,y position in world frame\n    rover_yaw -- rover yaw angle in world frame\n\n    Return value:\n    pixpts_rf -- namedtuple of numpy arrays of pixel x,y points in rover frame\n\n    \"\"\"\n    # Apply inverse translation and rotation\n    pixpts_rot = inv_translate_pixpts(pixpts_wf, rover_pos)\n    pixpts_rf = inv_rotate_pixpts(pixpts_rot, rover_yaw)\n\n    return pixpts_rf\n\n\ndef perception_step(Rover, R=0, G=1, B=2):\n    \"\"\"\n    Sense environment with rover camera and update rover state accordingly.\n\n    Keyword arguments:\n    Rover -- instance of RoverTelemetry class\n    R,G,B -- indexes representing the RGB color channels in a numpy image\n\n    \"\"\"\n    # Apply perspective transform to get 2D overhead view of rover cam\n    warped_img = perspect_transform(Rover.img)\n\n    # Apply color thresholds to extract pixels of navigable/obstacles/rocks\n    thresh_pixpts_pf = color_thresh(warped_img)\n\n    # Update rover vision image with each ROI assigned to one of\n    # the RGB color channels (to be displayed on left side of sim screen)\n    VISION_R_VAL, VISION_G_VAL, VISION_B_VAL = 135, 1, 175\n    Rover.vision_image[:, :, R] = thresh_pixpts_pf.obs * VISION_R_VAL\n    Rover.vision_image[:, :, G] = thresh_pixpts_pf.rock * VISION_G_VAL\n    Rover.vision_image[:, :, B] = thresh_pixpts_pf.nav * VISION_B_VAL\n\n    # Transform pixel coordinates from perspective frame to rover frame\n    nav_pixpts_rf = perspect_to_rover(thresh_pixpts_pf.nav)\n    obs_pixpts_rf = perspect_to_rover(thresh_pixpts_pf.obs)\n    rock_pixpts_rf = perspect_to_rover(thresh_pixpts_pf.rock)\n\n    # Convert above cartesian coordinates to polar coordinates\n    Rover.nav_dists, Rover.nav_angles = to_polar_coords(nav_pixpts_rf)\n    Rover.obs_dists, Rover.obs_angles = to_polar_coords(obs_pixpts_rf)\n    Rover.rock_dists = to_polar_coords(rock_pixpts_rf)[0]\n\n    # Extract subset of nav_angles that are left of rover heading\n    Rover.nav_angles_left = Rover.nav_angles[Rover.nav_angles > 0]\n\n    # Only include pixels within certain distances from rover (for fidelity)\n    nav_pixpts_rf = [pts[Rover.nav_dists < 60] for pts in nav_pixpts_rf]\n    obs_pixpts_rf = [pts[Rover.obs_dists < 80] for pts in obs_pixpts_rf]\n    rock_pixpts_rf = [pts[Rover.rock_dists < 70] for pts in rock_pixpts_rf]\n\n    # Convert rock cartesian coords to polar coords\n    Rover.rock_angles = to_polar_coords(rock_pixpts_rf)[1]\n\n    # Transform pixel points of ROIs from rover frame to world frame\n    nav_pixpts_wf = rover_to_world(nav_pixpts_rf, Rover.pos, Rover.yaw)\n    obs_pixpts_wf = rover_to_world(obs_pixpts_rf, Rover.pos, Rover.yaw)\n    rock_pixpts_wf = rover_to_world(rock_pixpts_rf, Rover.pos, Rover.yaw)\n\n    # Only update worldmap (displayed on right) if rover has a stable drive\n    # High pitch/rolls cause inaccurate 3D to 2D mapping and low fidelity\n    is_stable = ((Rover.pitch > 359 or Rover.pitch < 0.25)\n                 and (Rover.roll > 359 or Rover.roll < 0.37))\n\n    if is_stable:  # Update map with each ROI assigned to an RGB color channel\n        MAP_R_VAL, MAP_G_VAL, MAP_B_VAL = 255, 255, 255\n        Rover.worldmap[obs_pixpts_wf.y, obs_pixpts_wf.x, R] += MAP_R_VAL\n        Rover.worldmap[rock_pixpts_wf.y, rock_pixpts_wf.x, G] += MAP_G_VAL\n        Rover.worldmap[nav_pixpts_wf.y, nav_pixpts_wf.x, B] += MAP_B_VAL\n\n    return Rover\n", "meta": {"hexsha": "d278f4e40f091f91d8e9e48502b804570fdcbdbf", "size": 13730, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/perception.py", "max_stars_repo_name": "Salman-H/mars-search-robot", "max_stars_repo_head_hexsha": "1611801b8ef5146e0f3212d6e9243be30910a91c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2018-02-24T03:50:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T12:15:27.000Z", "max_issues_repo_path": "code/perception.py", "max_issues_repo_name": "Salman-H/mars-search-robot", "max_issues_repo_head_hexsha": "1611801b8ef5146e0f3212d6e9243be30910a91c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/perception.py", "max_forks_repo_name": "Salman-H/mars-search-robot", "max_forks_repo_head_hexsha": "1611801b8ef5146e0f3212d6e9243be30910a91c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-01-18T22:34:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T07:16:42.000Z", "avg_line_length": 34.5843828715, "max_line_length": 79, "alphanum_fraction": 0.6994901675, "include": true, "reason": "import numpy", "num_tokens": 3551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.36296920551961687, "lm_q1q2_score": 0.18290242237337292}}
{"text": "# -*- coding: UTF-8 -*-\n\"\"\"\nA compilation of molecular data and labels as well as a functions to calculate\nionization diagrams and occupation rates.\nThe variables `H2` and `CO` are dictionaries containing the lines associated\nto each molecular band, e.g., AX(1-0) for CO or BX(0-0) for H2 Lyman band.\n\"\"\"\n__author__ = 'Jens-Kristian Krogager'\n\nimport numpy as np\n\n\nCO_full_labels = {\n    'AX(0-0)': \"${\\\\rm CO\\ A}^1\\\\Pi(0) \\\\leftarrow {\\\\rm X}^1\\\\Sigma^+(\\\\nu=0)$\",\n    'AX(1-0)': \"${\\\\rm CO\\ A}^1\\\\Pi(1) \\\\leftarrow {\\\\rm X}^1\\\\Sigma^+(\\\\nu=0)$\",\n    'AX(2-0)': \"${\\\\rm CO\\ A}^1\\\\Pi(2) \\\\leftarrow {\\\\rm X}^1\\\\Sigma^+(\\\\nu=0)$\",\n    'AX(3-0)': \"${\\\\rm CO\\ A}^1\\\\Pi(3) \\\\leftarrow {\\\\rm X}^1\\\\Sigma^+(\\\\nu=0)$\",\n    'AX(4-0)': \"${\\\\rm CO\\ A}^1\\\\Pi(4) \\\\leftarrow {\\\\rm X}^1\\\\Sigma^+(\\\\nu=0)$\",\n    'AX(5-0)': \"${\\\\rm CO\\ A}^1\\\\Pi(5) \\\\leftarrow {\\\\rm X}^1\\\\Sigma^+(\\\\nu=0)$\",\n    'AX(6-0)': \"${\\\\rm CO\\ A}^1\\\\Pi(6) \\\\leftarrow {\\\\rm X}^1\\\\Sigma^+(\\\\nu=0)$\",\n    'AX(7-0)': \"${\\\\rm CO\\ A}^1\\\\Pi(7) \\\\leftarrow {\\\\rm X}^1\\\\Sigma^+(\\\\nu=0)$\",\n    'AX(8-0)': \"${\\\\rm CO\\ A}^1\\\\Pi(8) \\\\leftarrow {\\\\rm X}^1\\\\Sigma^+(\\\\nu=0)$\",\n    'AX(9-0)': \"${\\\\rm CO\\ A}^1\\\\Pi(9) \\\\leftarrow {\\\\rm X}^1\\\\Sigma^+(\\\\nu=0)$\",\n    'AX(10-0)': \"${\\\\rm CO\\ A}^1\\\\Pi(10) \\\\leftarrow {\\\\rm X}^1\\\\Sigma^+(\\\\nu=0)$\",\n    'AX(11-0)': \"${\\\\rm CO\\ A}^1\\\\Pi(11) \\\\leftarrow {\\\\rm X}^1\\\\Sigma^+(\\\\nu=0)$\",\n    'CX(0-0)': \"${\\\\rm CO\\ C}^1\\\\Sigma(0) \\\\leftarrow {\\\\rm X}^1\\\\Sigma^+(\\\\nu=0)$\",\n    'dX(5-0)': \"${\\\\rm CO\\ d}^3\\\\Delta(5) \\\\leftarrow {\\\\rm X}^1\\\\Sigma^+(\\\\nu=0)$\",\n    'eX(1-0)': \"${\\\\rm CO\\ e}^3\\\\Sigma^-(1) \\\\leftarrow {\\\\rm X}^1\\\\Sigma^+(\\\\nu=0)$\"\n}\n\nCO_labels = {'COJ0_1544.44': 'AX(0-0)',\n             'COJ0_1509.74': 'AX(1-0)',\n             'COJ0_1477.56': 'AX(2-0)',\n             'COJ0_1447.35': 'AX(3-0)',\n             'COJ0_1419.04': 'AX(4-0)',\n             'COJ0_1392.52': 'AX(5-0)',\n             'COJ0_1367.62': 'AX(6-0)',\n             'COJ0_1344.18': 'AX(7-0)',\n             'COJ0_1322.15': 'AX(8-0)',\n             'COJ0_1301.40': 'AX(9-0)',\n             'COJ0_1281.86': 'AX(10-0)',\n             'COJ0_1263.43': 'AX(11-0)',\n             'COJ0_1087.86': 'CX(0-0)',\n             'COJ0_1510.34': 'dX(5-0)',\n             'COJ0_1543.17': 'eX(1-0)',\n             'COJ0_1543.00': 'eX(1-0)'\n             }\n\nH2_full_labels = {\n    'BX(0-0)': \"${\\\\rm H_2\\ B}^1\\\\Sigma_u^+(0) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'BX(1-0)': \"${\\\\rm H_2\\ B}^1\\\\Sigma_u^+(1) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'BX(2-0)': \"${\\\\rm H_2\\ B}^1\\\\Sigma_u^+(2) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'BX(3-0)': \"${\\\\rm H_2\\ B}^1\\\\Sigma_u^+(3) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'BX(4-0)': \"${\\\\rm H_2\\ B}^1\\\\Sigma_u^+(4) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'BX(5-0)': \"${\\\\rm H_2\\ B}^1\\\\Sigma_u^+(5) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'BX(6-0)': \"${\\\\rm H_2\\ B}^1\\\\Sigma_u^+(6) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'BX(7-0)': \"${\\\\rm H_2\\ B}^1\\\\Sigma_u^+(7) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'BX(8-0)': \"${\\\\rm H_2\\ B}^1\\\\Sigma_u^+(8) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'BX(9-0)': \"${\\\\rm H_2\\ B}^1\\\\Sigma_u^+(9) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'BX(10-0)': \"${\\\\rm H_2\\ B}^1\\\\Sigma_u^+(10) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'BX(11-0)': \"${\\\\rm H_2\\ B}^1\\\\Sigma_u^+(11) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'BX(12-0)': \"${\\\\rm H_2\\ B}^1\\\\Sigma_u^+(12) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'BX(13-0)': \"${\\\\rm H_2\\ B}^1\\\\Sigma_u^+(13) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'BX(14-0)': \"${\\\\rm H_2\\ B}^1\\\\Sigma_u^+(14) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'BX(15-0)': \"${\\\\rm H_2\\ B}^1\\\\Sigma_u^+(15) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'BX(16-0)': \"${\\\\rm H_2\\ B}^1\\\\Sigma_u^+(16) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'BX(17-0)': \"${\\\\rm H_2\\ B}^1\\\\Sigma_u^+(17) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'BX(18-0)': \"${\\\\rm H_2\\ B}^1\\\\Sigma_u^+(18) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'BX(19-0)': \"${\\\\rm H_2\\ B}^1\\\\Sigma_u^+(19) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'CX(0-0)': \"${\\\\rm H_2\\ C}^1\\\\Pi_u(0) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'CX(1-0)': \"${\\\\rm H_2\\ C}^1\\\\Pi_u(1) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'CX(2-0)': \"${\\\\rm H_2\\ C}^1\\\\Pi_u(2) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'CX(3-0)': \"${\\\\rm H_2\\ C}^1\\\\Pi_u(3) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'CX(4-0)': \"${\\\\rm H_2\\ C}^1\\\\Pi_u(4) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n    'CX(5-0)': \"${\\\\rm H_2\\ C}^1\\\\Pi_u(5) \\\\leftarrow {\\\\rm X}^1\\\\Sigma_g^+(\\\\nu=0)$\",\n}\n\nH2_labels = {'H2J0_917.25': 'BX(18-0)',\n             'H2J0_1092.20': 'BX(1-0)',\n             'H2J0_929.53': 'CX(4-0)',\n             'H2J0_946.17': 'BX(14-0)',\n             'H2J0_971.99': 'BX(11-0)',\n             'H2J0_964.98': 'CX(2-0)',\n             'H2J0_1049.37': 'BX(4-0)',\n             'H2J0_1012.81': 'BX(7-0)',\n             'H2J0_1001.82': 'BX(8-0)',\n             'H2J0_981.44': 'BX(10-0)',\n             'H2J0_985.63': 'CX(1-0)',\n             'H2J0_931.06': 'BX(16-0)',\n             'H2J0_1077.14': 'BX(2-0)',\n             'H2J0_910.82': 'BX(19-0)',\n             'H2J0_938.47': 'BX(15-0)',\n             'H2J0_954.41': 'BX(13-0)',\n             'H2J0_914.40': 'CX(5-0)',\n             'H2J0_1062.88': 'BX(3-0)',\n             'H2J0_1036.55': 'BX(5-0)',\n             'H2J0_946.43': 'CX(3-0)',\n             'H2J0_991.38': 'BX(9-0)',\n             'H2J0_1008.55': 'CX(0-0)',\n             'H2J0_1108.13': 'BX(0-0)',\n             'H2J0_1024.37': 'BX(6-0)',\n             'H2J0_923.98': 'BX(17-0)',\n             'H2J0_962.98': 'BX(12-0)'\n             }\n\n\nH2 = {'BX(0-0)': [['H2J0_1108.13'],\n                  ['H2J1_1110.06', 'H2J1_1108.63'],\n                  ['H2J2_1112.50', 'H2J2_1110.12'],\n                  ['H2J3_1115.90', 'H2J3_1112.58'],\n                  ['H2J4_1120.25', 'H2J4_1116.01'],\n                  ['H2J5_1125.54', 'H2J5_1120.40'],\n                  ['H2J6_1131.75', 'H2J6_1125.73'],\n                  ['H2J7_1151.64']],\n\n      'BX(1-0)': [['H2J0_1092.20'],\n                  ['H2J1_1094.05', 'H2J1_1092.73'],\n                  ['H2J2_1096.44', 'H2J2_1094.24'],\n                  ['H2J3_1099.79', 'H2J3_1096.73'],\n                  ['H2J4_1104.08', 'H2J4_1100.16'],\n                  ['H2J5_1109.31', 'H2J5_1104.55'],\n                  ['H2J6_1115.46', 'H2J6_1109.86'],\n                  ['H2J7_1134.90']],\n\n      'BX(2-0)': [['H2J0_1077.14'],\n                  ['H2J1_1078.93', 'H2J1_1077.70'],\n                  ['H2J2_1081.27', 'H2J2_1079.23'],\n                  ['H2J3_1084.56', 'H2J3_1081.71'],\n                  ['H2J4_1088.80', 'H2J4_1085.15'],\n                  ['H2J5_1093.95', 'H2J5_1089.51'],\n                  ['H2J6_1100.02', 'H2J6_1094.80'],\n                  ['H2J7_1119.03']],\n\n      'BX(3-0)': [['H2J0_1062.88'],\n                  ['H2J1_1064.61', 'H2J1_1063.46'],\n                  ['H2J2_1066.90', 'H2J2_1064.99'],\n                  ['H2J3_1070.14', 'H2J3_1067.48'],\n                  ['H2J4_1074.31', 'H2J4_1070.90'],\n                  ['H2J5_1079.40', 'H2J5_1075.24'],\n                  ['H2J6_1085.38', 'H2J6_1080.49'],\n                  ['H2J7_1103.98']],\n\n      'BX(4-0)': [['H2J0_1049.37'],\n                  ['H2J1_1051.03', 'H2J1_1049.96'],\n                  ['H2J2_1053.28', 'H2J2_1051.50'],\n                  ['H2J3_1056.47', 'H2J3_1053.98'],\n                  ['H2J4_1060.58', 'H2J4_1057.38'],\n                  ['H2J5_1065.60', 'H2J5_1061.70'],\n                  ['H2J6_1071.50', 'H2J6_1066.91'],\n                  ['H2J7_1089.71']],\n\n      'BX(5-0)': [['H2J0_1036.55'],\n                  ['H2J1_1038.16', 'H2J1_1037.15'],\n                  ['H2J2_1040.37', 'H2J2_1038.69'],\n                  ['H2J3_1043.50', 'H2J3_1041.16'],\n                  ['H2J4_1047.55', 'H2J4_1044.54'],\n                  ['H2J5_1052.50', 'H2J5_1048.83'],\n                  ['H2J6_1058.32', 'H2J6_1054.00'],\n                  ['H2J7_1076.16']],\n\n      'BX(6-0)': [['H2J0_1024.37'],\n                  ['H2J1_1025.94', 'H2J1_1024.99'],\n                  ['H2J2_1028.11', 'H2J2_1026.53'],\n                  ['H2J3_1031.19', 'H2J3_1028.99'],\n                  ['H2J4_1035.18', 'H2J4_1032.35'],\n                  ['H2J5_1040.06', 'H2J5_1036.60'],\n                  ['H2J6_1045.80', 'H2J6_1041.73'],\n                  ['H2J7_1063.29']],\n\n      'BX(7-0)': [['H2J0_1012.81'],\n                  ['H2J1_1014.33', 'H2J1_1013.44'],\n                  ['H2J2_1016.46', 'H2J2_1014.98'],\n                  ['H2J3_1019.50', 'H2J3_1017.42'],\n                  ['H2J4_1023.44', 'H2J4_1020.77'],\n                  ['H2J5_1028.25', 'H2J5_1024.99'],\n                  ['H2J6_1033.92', 'H2J6_1030.07'],\n                  ['H2J7_1051.07']],\n\n      'BX(8-0)': [['H2J0_1001.82'],\n                  ['H2J1_1003.30', 'H2J1_1002.45'],\n                  ['H2J2_1005.39', 'H2J2_1003.99'],\n                  ['H2J3_1008.39', 'H2J3_1006.41'],\n                  ['H2J4_1012.26', 'H2J4_1009.72'],\n                  ['H2J5_1017.00', 'H2J5_1013.71'],\n                  ['H2J6_1022.59', 'H2J6_1019.02'],\n                  ['H2J7_1039.21']],\n\n      'BX(9-0)': [['H2J0_991.38'],\n                  ['H2J1_992.81', 'H2J1_992.02'],\n                  ['H2J2_994.87', 'H2J2_993.55'],\n                  ['H2J3_997.83', 'H2J3_995.97'],\n                  ['H2J4_1001.66', 'H2J4_999.27'],\n                  ['H2J5_1006.34', 'H2J5_1003.43'],\n                  ['H2J6_1011.87', 'H2J6_1008.43'],\n                  ['H2J7_1028.41']],\n\n      'BX(10-0)': [['H2J0_981.44'],\n                   ['H2J1_982.84', 'H2J1_982.07'],\n                   ['H2J2_984.86', 'H2J2_983.59'],\n                   ['H2J3_987.77', 'H2J3_985.96'],\n                   ['H2J4_991.53', 'H2J4_989.56'],\n                   ['H2J5_996.12', 'H2J5_993.49'],\n                   ['H2J6_1001.91', 'H2J6_998.43'],\n                   ['H2J7_1017.98']],\n\n      'BX(11-0)': [['H2J0_971.99'],\n                   ['H2J1_973.34', 'H2J1_972.63'],\n                   ['H2J2_975.35', 'H2J2_974.16'],\n                   ['H2J3_978.22', 'H2J3_976.55'],\n                   ['H2J4_981.95', 'H2J4_979.81'],\n                   ['H2J5_986.52', 'H2J5_983.90'],\n                   ['H2J6_991.92', 'H2J6_988.81'],\n                   ['H2J7_998.11']],\n\n      'BX(12-0)': [['H2J0_962.98'],\n                   ['H2J1_964.31', 'H2J1_963.61'],\n                   ['H2J2_966.28', 'H2J2_965.05'],\n                   ['H2J3_969.09', 'H2J3_967.68'],\n                   ['H2J4_972.69', 'H2J4_970.84'],\n                   ['H2J5_977.46', 'H2J5_974.89'],\n                   ['H2J6_982.73', 'H2J6_979.76'],\n                   ['H2J7_988.84']],\n\n      'BX(13-0)': [['H2J0_954.41'],\n                   ['H2J1_955.71', 'H2J1_955.07'],\n                   ['H2J2_957.65', 'H2J2_956.58'],\n                   ['H2J3_960.45', 'H2J3_958.95'],\n                   ['H2J4_964.09', 'H2J4_962.15'],\n                   ['H2J5_968.56', 'H2J5_966.18'],\n                   ['H2J6_973.83', 'H2J6_971.00'],\n                   ['H2J7_989.32']],\n\n      'BX(14-0)': [['H2J0_946.17'],\n                   ['H2J1_947.51', 'H2J1_946.98'],\n                   ['H2J2_949.35', 'H2J2_948.47'],\n                   ['H2J3_952.27', 'H2J3_950.82'],\n                   ['H2J4_955.85', 'H2J4_954.00'],\n                   ['H2J5_960.27', 'H2J5_958.01'],\n                   ['H2J6_965.48', 'H2J6_962.82'],\n                   ['H2J7_980.76']],\n\n      'BX(15-0)': [['H2J0_938.47'],\n                   ['H2J1_939.71', 'H2J1_939.12'],\n                   ['H2J2_941.60', 'H2J2_940.63'],\n                   ['H2J3_944.33', 'H2J3_942.96'],\n                   ['H2J4_947.89', 'H2J4_946.12'],\n                   ['H2J5_952.25', 'H2J5_950.07'],\n                   ['H2J6_957.41', 'H2J6_954.70'],\n                   ['H2J7_972.44']],\n\n      'BX(16-0)': [['H2J0_931.06'],\n                   ['H2J1_932.27', 'H2J1_931.73'],\n                   ['H2J2_934.14', 'H2J2_933.24'],\n                   ['H2J3_936.86', 'H2J3_935.58'],\n                   ['H2J4_940.39', 'H2J4_938.73'],\n                   ['H2J5_944.72', 'H2J5_942.69'],\n                   ['H2J6_949.84', 'H2J6_947.43'],\n                   ['H2J7_964.70']],\n\n      'BX(17-0)': [['H2J0_923.98'],\n                   ['H2J1_925.17', 'H2J1_924.64'],\n                   ['H2J2_927.02', 'H2J2_926.13'],\n                   ['H2J3_929.69', 'H2J3_928.44'],\n                   ['H2J4_933.17', 'H2J4_931.54'],\n                   ['H2J5_937.44', 'H2J5_935.32'],\n                   ['H2J6_942.48', 'H2J6_940.49'],\n                   ['H2J7_956.99']],\n\n      'BX(18-0)': [['H2J0_917.25'],\n                   ['H2J1_918.41', 'H2J1_917.92'],\n                   ['H2J2_920.24', 'H2J2_919.42'],\n                   ['H2J3_922.89', 'H2J3_921.73'],\n                   ['H2J4_926.35', 'H2J4_924.85'],\n                   ['H2J5_930.61', 'H2J5_928.76'],\n                   ['H2J6_935.63', 'H2J6_933.44'],\n                   ['H2J7_950.12']],\n\n      'BX(19-0)': [['H2J0_910.82'],\n                   ['H2J1_911.97', 'H2J1_911.48'],\n                   ['H2J2_913.77', 'H2J2_912.95'],\n                   ['H2J3_916.38', 'H2J3_915.21'],\n                   ['H2J4_919.79', 'H2J4_918.15'],\n                   ['H2J5_923.96', 'H2J5_922.48'],\n                   ['H2J6_928.78', 'H2J6_927.05'],\n                   ['H2J7_943.55']],\n\n      'CX(0-0)': [['H2J0_1008.55'],\n                  ['H2J1_1009.77', 'H2J1_1008.50'],\n                  ['H2J2_1012.17', 'H2J2_1010.94', 'H2J2_1009.02'],\n                  ['H2J3_1014.50', 'H2J3_1012.68', 'H2J3_1010.13'],\n                  ['H2J4_1017.39', 'H2J4_1014.98', 'H2J4_1011.81'],\n                  ['H2J5_1020.80', 'H2J5_1017.83', 'H2J5_1014.24'],\n                  ['H2J6_1024.73', 'H2J6_1021.21', 'H2J6_1016.74'],\n                  ['H2J7_1039.77', 'H2J7_1035.43']],\n\n      'CX(1-0)': [['H2J0_985.63'],\n                  ['H2J1_986.80', 'H2J1_985.64'],\n                  ['H2J2_989.09', 'H2J2_987.97', 'H2J2_986.24'],\n                  ['H2J3_991.38', 'H2J3_989.73', 'H2J3_987.45'],\n                  ['H2J4_994.23', 'H2J4_992.05', 'H2J4_988.87'],\n                  ['H2J5_997.64', 'H2J5_994.92', 'H2J5_991.37'],\n                  ['H2J6_1001.21', 'H2J6_998.33', 'H2J6_994.26'],\n                  ['H2J7_1015.75', 'H2J7_1012.13']],\n\n      'CX(2-0)': [['H2J0_964.98'],\n                  ['H2J1_966.10', 'H2J1_965.06'],\n                  ['H2J2_968.30', 'H2J2_967.28', 'H2J2_965.80'],\n                  ['H2J3_970.56', 'H2J3_969.05', 'H2J3_966.78'],\n                  ['H2J4_973.45', 'H2J4_971.39', 'H2J4_968.67'],\n                  ['H2J5_976.55', 'H2J5_974.29', 'H2J5_971.07'],\n                  ['H2J6_980.50', 'H2J6_977.73', 'H2J6_974.05'],\n                  ['H2J7_994.45', 'H2J7_991.16']],\n\n      'CX(3-0)': [['H2J0_946.43'],\n                  ['H2J1_947.42', 'H2J1_946.38'],\n                  ['H2J2_949.61', 'H2J2_948.62', 'H2J2_947.11'],\n                  ['H2J3_951.67', 'H2J3_950.40', 'H2J3_948.42'],\n                  ['H2J4_954.47', 'H2J4_952.76', 'H2J4_950.32'],\n                  ['H2J5_957.82', 'H2J5_955.68', 'H2J5_952.80'],\n                  ['H2J6_961.70', 'H2J6_959.15', 'H2J6_955.98'],\n                  ['H2J7_975.30', 'H2J7_972.27']],\n\n      'CX(4-0)': [['H2J0_929.53'],\n                  ['H2J1_930.58', 'H2J1_929.69'],\n                  ['H2J2_932.60', 'H2J2_931.78', 'H2J2_930.45'],\n                  ['H2J3_934.79', 'H2J3_933.58', 'H2J3_931.81'],\n                  ['H2J4_937.55', 'H2J4_935.96', 'H2J4_933.79'],\n                  ['H2J5_940.88', 'H2J5_938.91', 'H2J5_936.47'],\n                  ['H2J6_944.78', 'H2J6_942.42', 'H2J6_939.11'],\n                  ['H2J7_958.19', 'H2J7_955.26']],\n\n      'CX(5-0)': [['H2J0_914.40'],\n                  ['H2J1_915.40', 'H2J1_914.61'],\n                  ['H2J2_917.37', 'H2J2_916.62', 'H2J2_915.43'],\n                  ['H2J3_919.54', 'H2J3_918.43', 'H2J3_916.88'],\n                  ['H2J4_922.31', 'H2J4_920.83', 'H2J4_919.05'],\n                  ['H2J5_925.66', 'H2J5_923.82', 'H2J5_921.22'],\n                  ['H2J6_929.70', 'H2J6_927.36', 'H2J6_924.50'],\n                  ['H2J7_942.23', 'H2J7_939.98']]\n      }\n\nCO = {\n    # Nu=0:\n    'AX(0-0)': [['COJ0_1544.44'],  # J=0\n                ['COJ1_1544.54', 'COJ1_1544.38'],  # J=1\n                ['COJ2_1544.72', 'COJ2_1544.57', 'COJ2_1544.34'],  # J=2\n                ['COJ3_1544.84', 'COJ3_1544.61', 'COJ3_1544.31'],  # J=3\n                ['COJ4_1544.98', 'COJ4_1544.68', 'COJ4_1544.30'],  # J=4\n                ['COJ5_1545.14', 'COJ5_1544.76', 'COJ5_1544.31']],   # J=5\n    # Nu=1:\n    'AX(1-0)': [['COJ0_1509.74'],\n                ['COJ1_1509.83', 'COJ1_1509.69'],\n                ['COJ2_1510.01', 'COJ2_1509.87', 'COJ2_1509.66'],\n                ['COJ3_1510.13', 'COJ3_1509.92', 'COJ3_1509.64'],\n                ['COJ4_1510.27', 'COJ4_1509.99', 'COJ4_1509.64']],\n    # Nu=2:\n    'AX(2-0)': [['COJ0_1477.56'],\n                ['COJ1_1477.64', 'COJ1_1477.51'],\n                ['COJ2_1477.81', 'COJ2_1477.68', 'COJ2_1477.47'],\n                ['COJ3_1477.93', 'COJ3_1477.72', 'COJ3_1477.45'],\n                ['COJ4_1478.06', 'COJ4_1477.79', 'COJ4_1477.45']],\n    # Nu=3:\n    'AX(3-0)': [['COJ0_1447.35'],\n                ['COJ1_1447.43', 'COJ1_1447.30'],\n                ['COJ2_1447.59', 'COJ2_1447.46', 'COJ2_1447.27'],\n                ['COJ3_1447.70', 'COJ3_1447.51', 'COJ3_1447.25'],\n                ['COJ4_1447.83', 'COJ4_1447.58', 'COJ4_1447.25']],\n    # Nu=4:\n    'AX(4-0)': [['COJ0_1419.04'],\n                ['COJ1_1419.12', 'COJ1_1419.00'],\n                ['COJ2_1419.27', 'COJ2_1419.15', 'COJ2_1418.97'],\n                ['COJ3_1419.38', 'COJ3_1419.20', 'COJ3_1418.96'],\n                ['COJ4_1419.51', 'COJ4_1419.27', 'COJ4_1418.97']],\n    # Nu=5:\n    'AX(5-0)': [['COJ0_1392.52'],\n                ['COJ1_1392.60', 'COJ1_1392.48'],\n                ['COJ2_1392.74', 'COJ2_1392.63', 'COJ2_1392.46'],\n                ['COJ3_1392.85', 'COJ3_1392.68', 'COJ3_1392.45'],\n                ['COJ4_1392.98', 'COJ4_1392.75', 'COJ4_1392.46']],\n    # Nu=6:\n    'AX(6-0)': [['COJ0_1367.62'],\n                ['COJ1_1367.69', 'COJ1_1367.58'],\n                ['COJ2_1367.83', 'COJ2_1367.73', 'COJ2_1367.56'],\n                ['COJ3_1367.94', 'COJ3_1367.78', 'COJ3_1367.56'],\n                ['COJ4_1368.07', 'COJ4_1367.85', 'COJ4_1367.58'],\n                ['COJ5_1368.21', 'COJ5_1367.94', 'COJ5_1367.61']],\n    # Nu=7:\n    'AX(7-0)': [['COJ0_1344.18'],\n                ['COJ1_1344.25', 'COJ1_1344.15'],\n                ['COJ2_1344.39', 'COJ2_1344.29', 'COJ2_1344.13'],\n                ['COJ3_1344.49', 'COJ3_1344.34', 'COJ3_1344.13'],\n                ['COJ4_1344.62', 'COJ4_1344.41', 'COJ4_1344.15'],\n                ['COJ5_1344.76', 'COJ5_1344.49', 'COJ5_1344.18']],\n    # Nu=8:\n    'AX(8-0)': [['COJ0_1322.15'],\n                ['COJ1_1322.21', 'COJ1_1322.11'],\n                ['COJ2_1322.35', 'COJ2_1322.25', 'COJ2_1322.10'],\n                ['COJ3_1322.45', 'COJ3_1322.30', 'COJ3_1322.10'],\n                ['COJ4_1322.57', 'COJ4_1322.37', 'COJ4_1322.13'],\n                ['COJ5_1322.71', 'COJ5_1322.46', 'COJ5_1322.17']],\n    # Nu=9:\n    'AX(9-0)': [['COJ0_1301.40'],\n                ['COJ1_1301.46', 'COJ1_1301.37'],\n                ['COJ2_1301.59', 'COJ2_1301.50', 'COJ2_1301.36'],\n                ['COJ3_1301.70', 'COJ3_1301.55', 'COJ3_1301.37'],\n                ['COJ4_1301.82', 'COJ4_1301.63', 'COJ4_1301.39'],\n                ['COJ5_1301.95', 'COJ5_1301.72', 'COJ5_1301.43']],\n    # Nu=10:\n    'AX(10-0)': [['COJ0_1281.86'],\n                 ['COJ1_1281.92', 'COJ1_1281.83'],\n                 ['COJ2_1282.05', 'COJ2_1281.96', 'COJ2_1281.83'],\n                 ['COJ3_1282.15', 'COJ3_1282.02', 'COJ3_1281.84'],\n                 ['COJ4_1282.27', 'COJ4_1282.09', 'COJ4_1281.84'],\n                 ['COJ5_1282.40', 'COJ5_1282.18', 'COJ5_1281.91']],\n    # Nu=11:\n    'AX(11-0)': [['COJ0_1263.43'],\n                 ['COJ1_1263.49', 'COJ1_1263.40'],\n                 ['COJ2_1263.61', 'COJ2_1263.53', 'COJ2_1263.40'],\n                 ['COJ3_1263.71', 'COJ3_1263.58', 'COJ3_1263.41'],\n                 ['COJ4_1263.83', 'COJ4_1263.66', 'COJ4_1263.44'],\n                 ['COJ5_1263.96', 'COJ5_1263.75', 'COJ5_1263.49']],\n\n    'eX(1-0)': [['COJ0_1543.17', 'COJ0_1543.00'],\n                ['COJ1_1543.20', 'COJ1_1542.91', 'COJ1_1543.17'],\n                ['COJ2_1543.26', 'COJ2_1543.44', 'COJ2_1542.85', 'COJ2_1543.27', 'COJ2_1543.23'],\n                ['COJ3_1543.35', 'COJ3_1543.66', 'COJ3_1542.83', 'COJ3_1543.37', 'COJ3_1543.33'],\n                ['COJ4_1543.48', 'COJ4_1543.90', 'COJ4_1542.83', 'COJ4_1543.49', 'COJ4_1543.45']],\n\n    'CX(0-0)': [['COJ0_1087.86'],\n                ['COJ1_1087.95', 'COJ1_1087.82'],\n                ['COJ2_1088.00', 'COJ2_1087.77'],\n                ['COJ3_1088.04', 'COJ3_1087.72'],\n                ['COJ4_1088.09', 'COJ4_1087.67']],\n\n    'dX(5-0)': [['COJ0_1510.34'],\n                ['COJ1_1510.42', 'COJ1_1510.30'],\n                ['COJ2_1510.60', 'COJ2_1510.48', 'COJ2_1510.29'],\n                ['COJ3_1510.74', 'COJ3_1510.56', 'COJ3_1510.31'],\n                ['COJ4_1510.91', 'COJ4_1510.66', 'COJ4_1510.36']]\n}\n\n\n# --- Rotatinal Constants in units of cm^-1\n#     E = hc * B * J(J + 1)\nrotational_constant = {'H2': 60.853,\n                       'CO': 1.9313,\n                       'HD': 45.655\n                       }\n\n# Centrifugal constants in units of cm^-1:\ncentrifugal_constant = {'H2': 4.71e-2,\n                        'CO': 6.12e-6\n                        }\n\nhc = 1.2398e-4         # eV.cm\nk_B = 8.6173e-5        # eV/K\n\n\ndef energy_of_level(element, J):\n    \"\"\"\n    Calculate the energy of a given rotational level, `J`\n    for the given molecule with correction for centrigual\n    expansion.\n    E(J) = B_e * J * (J+1)\n\n    Returns\n    =======\n    E : float\n        The energy of the given level in units of K.\n    \"\"\"\n    B_e = rotational_constant[element]\n    D_e = centrifugal_constant[element]\n    E = B_e * hc/k_B * J * (J+1) - hc*D_e * J**2 * (J+1)**2\n    return E\n\n\ndef population_of_level(element, T, J):\n    \"\"\"\n    Calculate the population of the Jth level relative to the J=0 level.\n    The distribution is assumed to be an isothermal Boltzmann distribution:\n\n    n(J) \\\\propto g(J) e^(-E(J) / kT)\n    \"\"\"\n    if element not in rotational_constant.keys():\n        print(\" Element is not in database! \")\n        print(\" All elements in database are: \" + \", \".join(rotational_constant.keys()))\n        return None\n\n    if element == 'H2':\n        def g(J):\n            Ij = J % 2\n            return (2*J + 1)*(2*Ij + 1)\n    elif element == 'CO':\n        def g(J):\n            return 2*J + 1\n\n    E = energy_of_level(element, J)\n    n_J = g(J) * np.exp(-E/T)\n    return n_J\n\n\ndef calculate_T(element, logN1, logN2, J1, J2):\n    \"\"\"\n    Calculate the isothermal temperature for two given column densities.\n    \"\"\"\n    if element == 'H2':\n        def g(J):\n            Ij = J % 2\n            return (2*J + 1)*(2*Ij + 1)\n    elif element == 'CO':\n        def g(J):\n            return 2*J + 1\n\n    E1 = energy_of_level(element, J1)\n    E2 = energy_of_level(element, J2)\n    E12 = E2-E1\n    T = -E12/(np.log(10**(logN2 - logN1) * g(J1)/g(J2)))\n    return T\n", "meta": {"hexsha": "363c53497bb26234b924a3e16242b7e9f593214a", "size": 23257, "ext": "py", "lang": "Python", "max_stars_repo_path": "VoigtFit/utils/molecules.py", "max_stars_repo_name": "jkrogager/VoigtFit", "max_stars_repo_head_hexsha": "ca84ff4b9e6827e2ca64cd03c9437ab5d4097f1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2018-03-06T02:06:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T05:24:35.000Z", "max_issues_repo_path": "VoigtFit/utils/molecules.py", "max_issues_repo_name": "jkrogager/VoigtFit", "max_issues_repo_head_hexsha": "ca84ff4b9e6827e2ca64cd03c9437ab5d4097f1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2018-03-03T11:53:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T20:43:34.000Z", "max_forks_repo_path": "VoigtFit/utils/molecules.py", "max_forks_repo_name": "jkrogager/VoigtFit", "max_forks_repo_head_hexsha": "ca84ff4b9e6827e2ca64cd03c9437ab5d4097f1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-05-16T03:34:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-30T02:38:17.000Z", "avg_line_length": 44.8111753372, "max_line_length": 98, "alphanum_fraction": 0.4424044374, "include": true, "reason": "import numpy", "num_tokens": 10307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.36296920551961687, "lm_q1q2_score": 0.18290242237337292}}
{"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nForked in Hydra IMF from Hydra/MUSE on Feb 19, 2018\r\n\r\n@author: Carlos Eduardo Barbosa\r\n\r\nRun pPXF in data\r\n\"\"\"\r\nimport os\r\nimport yaml\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom astropy.io import fits\r\nfrom astropy import constants\r\nfrom astropy.table import Table, vstack, hstack\r\n\r\nfrom ppxf import ppxf, ppxf_util\r\n\r\nimport context\r\nimport misc\r\nfrom der_snr import DER_SNR\r\n\r\ndef run_ppxf(specs, templates_file, outdir, velscale=None, redo=False,\r\n             degree=-1, mdegree=15, clean=False, V0=None):\r\n    \"\"\" Running pPXF. \"\"\"\r\n    velscale = context.velscale if velscale is None else velscale\r\n    ssp_templates = fits.getdata(templates_file, extname=\"SSPS\").T\r\n    nssps = ssp_templates.shape[1]\r\n    logwave_temp = Table.read(templates_file, hdu=2)[\"loglam\"].data\r\n    wave_temp = np.exp(logwave_temp)\r\n    V0 = context.V if V0 is None else V0\r\n    start0 = [V0, 100., 0., 0.]\r\n    bounds = [[[V0 - 2000., V0 + 2000], [3., 800.]],\r\n               [[V0 - 2000., V0 + 2000], [3., 800.]]]\r\n    if not os.path.exists(outdir):\r\n        os.mkdir(outdir)\r\n    for spec in specs:\r\n        # Reading the data in the files\r\n        name = spec.replace(\".fits\", \"\")\r\n        outyaml = os.path.join(outdir, \"{}.yaml\".format(name))\r\n        if os.path.exists(outyaml) and not redo:\r\n            continue\r\n        print(\"Processing spectrum {}\".format(name))\r\n        table = Table.read(spec)\r\n        wave = table[\"wave\"]\r\n        flux = table[\"flam\"]\r\n        fluxerr = table[\"flamerr\"]\r\n        ###################################################################\r\n        # Trim spectra to conform to the wavelenght range of the templates\r\n        idx = np.argwhere(np.logical_and(\r\n                          wave > wave_temp[0],\r\n                          wave < wave_temp[-1]))\r\n        wave = wave[idx].T[0]\r\n        flux = flux[idx].T[0]\r\n        fluxerr = fluxerr[idx].T[0]\r\n        ####################################################################\r\n        # Rebinning the data to a logarithmic scale for ppxf\r\n        wave_range = [wave[0], wave[-1]]\r\n        galaxy, logLam, vtemp = ppxf_util.log_rebin(wave_range,\r\n                                               flux, velscale=velscale)\r\n        noise = ppxf_util.log_rebin(wave_range, fluxerr,\r\n                               velscale=velscale)[0]\r\n        ####################################################################\r\n        # Setting up the gas templates\r\n        gas_templates, line_names, line_wave = \\\r\n            ppxf_util.emission_lines(logwave_temp,\r\n                                     [wave[0], wave[-1]], 2.95)\r\n        ngas = gas_templates.shape[1]\r\n        # Preparing the fit\r\n        start = [start0[:2], start0[:2]]\r\n        dv = (logwave_temp[0] - logLam[0]) * \\\r\n             constants.c.to(\"km/s\").value\r\n        templates = np.column_stack((ssp_templates, gas_templates))\r\n        components = np.hstack((np.zeros(nssps), np.ones(ngas))).astype(np.int)\r\n        gas_component = components > 0\r\n        ########################################################################\r\n        # # Masking bad pixels\r\n        # skylines = np.array([4785, 5577, 5889, 6300, 6863])\r\n        # goodpixels = np.arange(len(wave))\r\n        # for line in skylines:\r\n        #     sky = np.argwhere((wave < line - 15) | (wave > line + 15)).ravel()\r\n        #     goodpixels = np.intersect1d(goodpixels, sky)\r\n        # print(len(wave), len(goodpixels))\r\n        # input()\r\n        ###################################################################\r\n        # Fitting with two components\r\n        pp = ppxf.ppxf(templates, galaxy, noise, velscale=velscale,\r\n                  plot=True, moments=[2,2], start=start, vsyst=dv,\r\n                  lam=np.exp(logLam), component=components, degree=degree,\r\n                  gas_component=gas_component, gas_names=line_names,\r\n                  quiet=False, mdegree=mdegree, bounds=bounds, clean=clean)\r\n        plt.savefig(os.path.join(outdir, \"{}.png\".format(name)), dpi=250)\r\n        plt.close()\r\n        pp.name = name\r\n        pp.fit_sn = float(np.nanmedian(pp.galaxy) / \\\r\n                      np.nanstd(pp.galaxy - pp.bestfit))\r\n        pp.der_sn = float(misc.snr(flux)[2])\r\n        # Saving results and plot\r\n        save(pp, outdir)\r\n\r\ndef save(pp, outdir):\r\n    \"\"\" Save results from pPXF into files excluding fitting arrays. \"\"\"\r\n    array_keys = [\"lam\", \"galaxy\", \"noise\", \"bestfit\", \"gas_bestfit\",\r\n                  \"mpoly\", \"apoly\"]\r\n    array_keys = [_ for _ in array_keys if isinstance(getattr(pp, _),\r\n                                                      np.ndarray)]\r\n    table = Table([getattr(pp, key) for key in array_keys], names=array_keys)\r\n    table.write(os.path.join(outdir, \"{}_bestfit.fits\".format(pp.name)),\r\n                overwrite=True)\r\n    ppdict = {}\r\n    save_keys = [\"name\", \"regul\", \"degree\", \"mdegree\", \"reddening\", \"clean\",\r\n                 \"ncomp\", \"chi2\", \"der_sn\", \"fit_sn\"]\r\n    # Chi2 is a astropy.unit.quantity object, we have to make it a scalar\r\n    pp.chi2 = float(pp.chi2)\r\n    for key in save_keys:\r\n        ppdict[key] = getattr(pp, key)\r\n    klist = [\"V\", \"sigma\"]\r\n    for j, sol in enumerate(pp.sol):\r\n        for i in range(len(sol)):\r\n            ppdict[\"{}_{}\".format(klist[i], j)] = float(sol[i])\r\n            ppdict[\"{}err_{}\".format(klist[i], j)] = float(pp.error[j][i])\r\n\r\n    with open(os.path.join(outdir, \"{}.yaml\".format(pp.name)), \"w\") as f:\r\n        yaml.dump(ppdict, f, default_flow_style=False)\r\n\r\ndef make_table(direc, output):\r\n    \"\"\" Read all yaml files in a ppf directory to one make table for all\r\n    bins. \"\"\"\r\n    filenames = sorted([_ for _ in os.listdir(direc) if _.endswith(\".yaml\")])\r\n    keys = [\"name\", \"V_0\", \"Verr_0\", \"sigma_0\", \"sigmaerr_0\", \"der_sn\"]\r\n    names = {\"name\": \"spec\", \"V_0\": \"V\", \"Verr_0\": \"Verr\",\r\n             \"sigma_0\": \"sigma\", \"sigmaerr_0\": \"sigmaerr\", \"der_sn\": \"SNR\"}\r\n    outtable = []\r\n    for fname in filenames:\r\n        with open(os.path.join(direc, fname)) as f:\r\n            props = yaml.load(f)\r\n        data = Table([[props[k]] for k in keys], names=[names[k] for k in keys])\r\n        outtable.append(data)\r\n    outtable = vstack(outtable)\r\n    outtable.write(output, format=\"fits\", overwrite=True)\r\n\r\ndef run_ngc3311():\r\n    targetSN = 250\r\n    w1 = 4500\r\n    w2 = 10000\r\n    sample = \"kinematics\"\r\n    velscale = context.velscale\r\n    dataset = \"MUSE\"\r\n    tempfile = os.path.join(context.home, \"templates\",\r\n               \"emiles_muse_vel{}_w{}_{}_{}_fwhm2.95.fits\".format(int(velscale),\r\n                w1, w2, sample))\r\n    fields = context.fields[:1]\r\n    for field in fields:\r\n        wdir = os.path.join(context.get_data_dir(dataset), field,\r\n                            \"sn{}/sci\".format(targetSN))\r\n        os.chdir(wdir)\r\n        specs = sorted([_ for _ in os.listdir(\".\") if _.endswith(\".fits\")])\r\n        outdir = os.path.join(os.path.split(os.getcwd())[0],\r\n                              \"ppxf_vel{}_w{}_{}_{}\".format(int(velscale),\r\n                                                            w1, w2, sample))\r\n        run_ppxf(specs, tempfile, outdir, redo=False)\r\n        outtable = os.path.join(os.path.split(wdir)[0], \\\r\n            \"ppxf_vel{}_w{}_{}_{}.fits\".format(int(velscale), w1, w2, sample))\r\n        make_table(outdir, outtable)\r\n\r\ndef run_m87():\r\n    targetSN = 500\r\n    w1 = 4500\r\n    w2 = 10000\r\n    sample = \"kinematics\"\r\n    velscale = context.velscale\r\n    tempfile = os.path.join(context.home, \"templates\",\r\n               \"emiles_muse_vel{}_w{}_{}_{}_fwhm2.95.fits\".format(int(velscale),\r\n                w1, w2, sample))\r\n    imgname, cubename = context.get_img_cube_m87()\r\n    wdir = os.path.join(os.path.split(imgname)[0],\r\n                        \"sn{}/sci\".format(targetSN))\r\n    os.chdir(wdir)\r\n    specs = sorted([_ for _ in os.listdir(\".\") if _.endswith(\".fits\")])\r\n    outdir = os.path.join(os.path.split(os.getcwd())[0],\r\n                          \"ppxf_vel{}_w{}_{}_{}\".format(int(velscale),\r\n                                                        w1, w2, sample))\r\n    run_ppxf(specs, tempfile, outdir, redo=True, degree=10, mdegree=-1, V0=1284)\r\n    outtable = os.path.join(os.path.split(wdir)[0], \\\r\n        \"ppxf_vel{}_w{}_{}_{}.fits\".format(int(velscale), w1, w2, sample))\r\n    make_table(outdir, outtable)\r\n\r\n\r\nif __name__ == '__main__':\r\n    # run_ngc3311()\r\n    run_m87()", "meta": {"hexsha": "e9ca604d602fe14650390584b4ef9e724b0f68ad", "size": 8426, "ext": "py", "lang": "Python", "max_stars_repo_path": "run_ppxf.py", "max_stars_repo_name": "cebarbosa/hydraimf", "max_stars_repo_head_hexsha": "0aaa333f69e7bf374c2129757ba76d8079a43650", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "run_ppxf.py", "max_issues_repo_name": "cebarbosa/hydraimf", "max_issues_repo_head_hexsha": "0aaa333f69e7bf374c2129757ba76d8079a43650", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "run_ppxf.py", "max_forks_repo_name": "cebarbosa/hydraimf", "max_forks_repo_head_hexsha": "0aaa333f69e7bf374c2129757ba76d8079a43650", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.8854166667, "max_line_length": 81, "alphanum_fraction": 0.5303821505, "include": true, "reason": "import numpy,from astropy", "num_tokens": 2184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.1829024223733729}}
{"text": "# The MIT License (MIT)\n#\n# Copyright (c) 2011, 2013 OpenWorm.\n# http://openworm.org\n#\n# All rights reserved. This program and the accompanying materials\n# are made available under the terms of the MIT License\n# which accompanies this distribution, and is available at\n# http://opensource.org/licenses/MIT\n#\n# Contributors:\n#      OpenWorm - http://openworm.org/people.html\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n# USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfrom __future__ import with_statement\n\"\"\"\nSimulation of C.Elegans muscle cell with three currents\nand one calcium pump.\n\nThis is still at a very early stage, being optimized on\nCamGrid using neuronoptimizer. The model represented\nhere requires the publically-unavailable nrntools\nmodule from the nrndev library. Please email\nauthor (vellamike@gmail.com) for these libraries.\n\nAuthor:Mike Vella\nemail:mv333@cam.ac.uk\n\nWARNING: Not under development as of 29/8/12. Development focus has shifted\nto the pyramidal implementation.\n\"\"\"\n\nfrom neuron import h\nimport neuron\nimport numpy as np\nfrom matplotlib import pyplot as plt\n#from nrndev import nrntools\n\ndef set_section_mechanism(sec, mech, mech_attribute, mech_value): #Is this passing by reference, do you need to state that explicitly in Python?\n    for seg in sec:\n        setattr(getattr(seg, mech), mech_attribute, mech_value)\n\n# Create muscle cell body\nmuscle=h.Section()\n\n# XXX Placeholder values - check dimensions\n# Using dimensions from ../NeuroML2/SingleCompMuscle.cell.nml\n# Dimensions are in um\nmuscle.diam = 5\nmuscle.L = 20\n\nmuscle.insert('na')\nmuscle.insert('kv')\nmuscle.insert('canrgc')\nmuscle.insert('cad2')\n\n# set conductance density\nset_section_mechanism(muscle,'canrgc','gbar',0.1)\nset_section_mechanism(muscle,'kv','gbar',20)\nset_section_mechanism(muscle,'na','gbar',100)\n\n\n# Loop to connect muscle arms\nnum_arms = 5 # Number of arms per cell\nnum_compartments = 10 # Number of compartments per arm\narms = []\nfor i in range(num_arms):\n    arms.append([])\n    arm_compartment = None\n    prev_compartment = muscle\n\n    # Connect 10 compartments per arm\n    for j in range(num_compartments):\n        arm_compartment = h.Section()\n\n        # Set dimensions\n        arm_compartment.diam = 0.75\n        arm_compartment.L = 1\n\n        arm_compartment.cm = 1   # uF/cm2\n        arm_compartment.Ra = 100 # Ohm-cm\n\n        # Set currents\n        arm_compartment.insert('pas')\n        set_section_mechanism(arm_compartment, 'pas', 'g', 0.000022222)\n\n        arm_compartment.connect(prev_compartment)\n        arms[i].append(arm_compartment)\n        prev_compartment = arm_compartment\n\n    # Set up stimulus at end of each muscle arm\n    stim=h.IClamp(arms[i][num_compartments-1](0.5))\n    stim.delay=100\n    stim.amp=0.02\n    stim.dur=200\n\n\n# Set the recording section - middle of muscle cell:\nrec_t=h.Vector()\nrec_t.record(h._ref_t)\nrec_v=h.Vector()\n#rec_v.record(arms[0][9](0.5)._ref_v)\nrec_v.record(muscle(0.5)._ref_v)\n\nrec_ina = h.Vector()\nrec_ina.record(muscle(0.5)._ref_ina)\n\nrec_ik = h.Vector()\nrec_ik.record(muscle(0.5)._ref_ik)\n\nrec_ica = h.Vector()\nrec_ica.record(muscle(0.5)._ref_ica)\n\nh.dt=0.05\nh.finitialize(-70.0)\nneuron.init()\nsim_time=500\n\nif sim_time:\n    neuron.run(sim_time)\nelse:\n    neuron.run(sim_time)\n\n\nx=np.array(rec_t)\ny=np.array(rec_v)\nplt.figure(1)\nplt.subplot(411)\nplt.plot(x,y)\n\nna=np.array(rec_ina)\nplt.subplot(412)\nplt.plot(x,na)\n\nk=np.array(rec_ik)\nplt.subplot(413)\nplt.plot(x,k)\n\nca=np.array(rec_ica)\nplt.subplot(414)\nplt.plot(x,ca)\n\nplt.show()\n\n##if using nrntools, much of the above can be accomplished as follows:\n#sim=nrntools.Simulation(muscle,sim_time=2200,v_init=-70.0)\n#sim.set_IClamp(100, 0.2, 2000)\n#sim.go()\n#sim.show()\n", "meta": {"hexsha": "a2c4aad670f10e3eb854d92d8d470779432209a7", "size": 4654, "ext": "py", "lang": "Python", "max_stars_repo_path": "neuron_implementation/main.py", "max_stars_repo_name": "rayner/muscle_model", "max_stars_repo_head_hexsha": "8f5aaba9bac07989dd9c5766a6b859796852cdae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "neuron_implementation/main.py", "max_issues_repo_name": "rayner/muscle_model", "max_issues_repo_head_hexsha": "8f5aaba9bac07989dd9c5766a6b859796852cdae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "neuron_implementation/main.py", "max_forks_repo_name": "rayner/muscle_model", "max_forks_repo_head_hexsha": "8f5aaba9bac07989dd9c5766a6b859796852cdae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8682634731, "max_line_length": 144, "alphanum_fraction": 0.7400085948, "include": true, "reason": "import numpy", "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.18290241890097095}}
{"text": "\"\"\"\nEnvironment for Intergrated Energy System.\nYou can customize this script in a way you want.\n\nRequirement:\npyglet >= 1.2.4\nnumpy >= 1.12.1\n\"\"\"\nimport numpy as np\n\n\nclass CHPEnv(object):\n    GB_bound = [0.2, 1]\n    GT_bound = [0, 1]\n    TST_bound = [- 0.1, 0.2]\n    Grid_bound = [-1, 1]\n    action_bound = [-0.2, 0.2]\n    action_dim = 4\n    state_dim = 14\n    dt = .1  # refresh rate\n    get_point = False\n    grab_counter = 0\n\n    def __init__(self):\n        self.device_info = np.zeros((4, 4))\n        self.device_info[0, 0] = 5000\n        self.device_info[1, 0] = 5000\n        self.device_info[2, 0] = 5000\n        self.device_info[3, 0] = 2000\n        self.he_q = 0\n        self.cost = 0\n        self.realcost = 0\n        self.total_p = 0\n        self.wind = 0\n        self.rtp = 0\n        self.point_info = np.squeeze(np.array([3500, 8500]))\n        self.point_l = 0.075\n        self.center = np.squeeze(np.array([2500, 8500]))\n        self.point_info_init = self.point_info.copy()\n        self.tank_info = 2000\n\n    def step(self, action):\n        # action = (node1 angular v, node2 angular v)\n        gt_action = np.clip(action[0], *self.action_bound)\n        gb_action = np.clip(action[1], *self.action_bound)\n        tst_action = np.clip(action[2], *self.action_bound)\n        grid_action = np.clip(action[3], *self.action_bound)\n\n        self.device_info[0, 1] += gt_action * self.dt\n        self.device_info[0, 1] = np.clip(self.device_info[0, 1], 0.2, 1)\n        self.device_info[1, 1] += gb_action * self.dt\n        self.device_info[1, 1] = np.clip(self.device_info[1, 1], 0, 1)\n        self.device_info[2, 1] += tst_action * self.dt\n        self.device_info[2, 1] = np.clip(self.device_info[2, 1], (self.tank_info - 500)/5000, (self.tank_info + 1000)/5000)\n        self.device_info[2, 1] = np.clip(self.device_info[2, 1], 0, 1)\n        self.device_info[3, 1] += grid_action * self.dt\n        self.device_info[3, 1] = np.clip(self.device_info[3, 1], -1, 1)\n\n        gt_p = self.device_info[0, 1]*self.device_info[0, 0]\n        self.device_info[0, 2] = gt_p\n        gt_q = gt_p*2.3*0.75\n        self.device_info[0, 3] = gt_q\n        gb_q = self.device_info[1, 1]*self.device_info[1, 0]\n        self.device_info[1, 3] = gb_q\n        tst_q = np.clip((self.device_info[2, 1]*self.device_info[2, 0] - self.tank_info), -500, 1000)\n        self.device_info[2, 3] = tst_q\n\n        # gb_q = self.point_info[1] - gt_q + tst_q\n        # self.device_info[1, 1] = np.clip(gb_q / 5000, 0, 1)\n        # gb_q = self.device_info[1, 1] * self.device_info[3, 0]\n        # buy_p = self.point_info[0] - gt_p - self.wind\n        # self.device_info[3, 1] = np.clip(buy_p/2000, -1, 1)\n        buy_p = self.device_info[3, 1]*self.device_info[3, 0]\n        self.device_info[3, 2] = buy_p\n\n        self.he_q = (gt_q + gb_q - tst_q)  # 换热站总热量\n        self.total_p = gt_p + buy_p + self.wind  # 总产生电量\n\n        self.cost = (0.345 * gt_q * 2.3*0.75/(1+2.3*0.75) + 0.345 * gb_q/0.9)/self.point_info[1] +\\\n                    (buy_p * self.rtp + 0.345 * gt_q * 1/(1+2.3*0.75))/self.point_info[0]\n\n        self.realcost = 0.345 * gt_q * 2.3*0.75 + 0.345 * gb_q/0.9 + buy_p * self.rtp\n\n        s, p_distance, q_distance = self._get_state()\n        r = self._r_func(p_distance, q_distance, tst_q)\n\n        return s, r, self.get_point\n\n    def reset(self):\n        self.get_point = False\n        self.grab_counter = 0\n        # price = np.array([0.427, 0.427, 0.427, 0.427, 0.427, 0.427, 0.527, 0.527, 0.627, 0.627, 0.627,\n        #                 0.527, 0.527, 0.527, 0.527, 0.527, 0.527, 0.627, 0.627, 0.627, 0.627, 0.627,\n        #                 0.427, 0.427])\n        # wind_power = np.array([875, 1234, 1390, 1392, 1336, 1223, 1173, 1136, 1158, 1312, 1369,\n        #                       1376, 1315, 1301, 1343, 1310, 1208, 1055, 896, 773, 672, 626,\n        #                       624, 703])\n\n        # temperature = 2*np.array([4800, 4896, 4953.6, 4992, 4896, 4800, 4560, 4320, 4128,\n        #                           3984, 3888, 3801.6, 3758.4, 3744, 3748.8, 3772.8, 3820.8,\n        #                           3888, 4032, 4224, 4416, 4608, 4752, 4800])\n#\n        # e_load = np.array([2178.0, 2009, 1873, 1755, 1704, 1839, 2517, 4211, 5397, 5375,\n        #                    5651, 5481, 5227, 5176, 5143, 5227, 5909, 6417, 6545, 6206,\n        #                   5698, 4510, 4025, 2093])\n\n        p = np.random.uniform(1500, 7000)\n        q = np.random.uniform(5000, 11000)\n        t = np.random.uniform(200, 2000)\n        rtp = np.random.uniform(0.4, 0.7)\n        tank = np.random.uniform(1000, 3000)\n        self.point_info[0] = p\n        self.point_info[1] = q\n        self.wind = t\n        self.rtp = rtp\n        self.tank_info = tank\n        return self._get_state()[0]\n\n    def set(self):\n        self.get_point = False\n        self.grab_counter = 0\n        self.point_info[0] = 2000\n        self.point_info[1] = 9000\n        self.wind = 700\n        self.rtp = 0.627\n        self.tank_info = 1000\n        return self._get_state()[0]\n\n    def render(self):\n        s = self._get_state()\n        print(s, self.realcost)\n\n    def sample_action(self):\n        return np.random.uniform(*self.action_bound, size=self.action_dim)\n\n    def _get_state(self):\n        # return the distance (dx, dy) between arm finger point with blue point\n        he_q = self.he_q\n        total_p = self.total_p\n        t_p = total_p - self.point_info[0]\n        t_q = he_q - self.point_info[1]\n        # dis = self.point_info[1]/self.point_info[0]\n        # ratio = self.device_info[0, 1] - self.device_info[1, 1]\n        p_gt = self.device_info[0, 2]/self.point_info[0]\n        q_gt = self.device_info[0, 3]/self.point_info[1]\n        q_gb = self.device_info[1, 3]/self.point_info[1]\n        q_tst = self.device_info[2, 3]/self.point_info[1]\n        p_grid = self.device_info[3, 2]/self.point_info[0]\n        p_wind = self.wind/self.point_info[0]\n        cen_dis_p = (self.center[0] - self.point_info[0])/5000\n        cen_dis_q = (self.center[1] - self.point_info[1])/5000\n        in_point = 1 if self.grab_counter > 0 else 0\n        return np.hstack([in_point, t_p/5000,  t_q/5000, cen_dis_p, cen_dis_q, p_gt, q_gt,\n                          q_gb, q_tst, p_grid, p_wind, self.device_info[2, 1], self.tank_info/5000, self.rtp\n                          # arm1_distance_p, arm1_distance_b,\n                          ]), t_p/5000, t_q/5000\n\n    def _r_func(self, p_distance, q_distance, tst_q):\n        t = 30\n        abs_distance = np.sqrt(np.square(p_distance)+np.square(q_distance))\n        r = - abs_distance - self.cost - 0.1*np.abs(self.device_info[2, 1] - 0.4)\n        # print(0.1*np.abs(self.device_info[2, 1] - 0.4))\n        # print(-self.cost)\n        # print(tst_q*(self.rtp-self.rtp_m)/1000)\n        if abs_distance < self.point_l and (not self.get_point):\n            r += 1\n            self.grab_counter += 1\n            if self.grab_counter > t:\n                r += 10.\n                self.get_point = True\n        elif abs_distance > self.point_l:\n            self.grab_counter = 0\n            self.get_point = False\n        return r\n\n\nif __name__ == '__main__':\n    env = CHPEnv()\n    action = env.sample_action()\n    print(action)\n    env.reset()\n    print(env.tank_info)\n    s, r, env.get_point = env.step(action)\n    print(env.device_info)\n", "meta": {"hexsha": "fff0f16c75f582d5694a3bc7a524c8f6880960ed", "size": 7334, "ext": "py", "lang": "Python", "max_stars_repo_path": "CHP_MODEL.py", "max_stars_repo_name": "BeardHealth/Combined-Heat-and-Power-System-Economic-Dispatch", "max_stars_repo_head_hexsha": "378127d6304e9b9979f87ccc20004ddd222de8dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2020-01-02T11:22:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T02:01:26.000Z", "max_issues_repo_path": "CHP_MODEL.py", "max_issues_repo_name": "shengrenhou/Combined-Heat-and-Power-System-Economic-Dispatch", "max_issues_repo_head_hexsha": "378127d6304e9b9979f87ccc20004ddd222de8dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-03-13T13:55:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T09:33:35.000Z", "max_forks_repo_path": "CHP_MODEL.py", "max_forks_repo_name": "shengrenhou/Combined-Heat-and-Power-System-Economic-Dispatch", "max_forks_repo_head_hexsha": "378127d6304e9b9979f87ccc20004ddd222de8dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-03-23T08:04:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T08:49:31.000Z", "avg_line_length": 39.6432432432, "max_line_length": 123, "alphanum_fraction": 0.5625852195, "include": true, "reason": "import numpy", "num_tokens": 2540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.18282087260553717}}
{"text": "#!/usr/bin/env python3\n#PYTHON_ARGCOMPLETE_OK\n\n\nimport logging\nimport itertools\nfrom dataclasses import dataclass\nfrom simple_parsing import Serializable\nfrom typing import Union, Tuple\n\nimport numpy as np\nimport torch as th\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision.utils import save_image\n\ntry:\n    from pytorch3d.structures import Pointclouds, Meshes\n    from pytorch3d.transforms.transform3d import Transform3d\n    from pytorch3d.renderer import (\n        look_at_view_transform,\n        FoVPerspectiveCameras,\n        PointsRasterizationSettings,\n        PointsRenderer,\n        PointsRasterizer,\n        RasterizationSettings,\n        MeshRasterizer,\n        PointLights,\n        MeshRenderer,\n        SoftPhongShader,\n        AlphaCompositor,\n        TexturesVertex\n    )\nexcept ImportError:\n    logging.warn(\n        'pytorch3d import has failed, colored cube dataset will be disabled.')\nfrom top.run.torch_util import resolve_device\nfrom top.run.app_util import update_settings\nfrom top.data.schema import Schema\n\n\nclass ColoredCubeDataset(th.utils.data.IterableDataset):\n    \"\"\"Toy generative dataset for 3D object detection: vertices of an oriented\n    unit cube rendered as a point cloud. Intended to be an \"easy\" baseline.\n\n    # FIXME(ycho): I realized that the cube length is actually 2\n    \"\"\"\n\n    @dataclass\n    class Settings(Serializable):\n        batch_size: int = 1\n        aspect: float = 1.0  # pixel aspect ratio, max_x/max_y\n        fov: float = 60  # full vertical field of view, in degrees.\n        znear: float = 0.1\n        zfar: float = 100.0\n        min_distance: float = 0.1\n        max_distance: float = 10.0\n        image_size: Tuple[int, int] = (256, 256)  # Order: H W\n        # Unstack output tensors, for compatibility with Objectron.\n        unstack: bool = True\n        use_mesh: bool = False\n\n    def __init__(self, opts: Settings, device: th.device = '', transform=None):\n        super().__init__()\n        self.opts = opts\n        self.device = resolve_device(device)\n        self.xfm = transform\n        # TODO(ycho): Consider support for multiple \"objects\".\n        # TODO(ycho): Consider support for *animated* objects through time.\n\n        self.cloud = self._get_cube_cloud()\n        self.clouds = self.cloud.extend(self.opts.batch_size)\n        self.mesh = self._get_cube_mesh()\n        self.meshes = self.mesh.extend(self.opts.batch_size)\n\n        self.renderer = self._setup_render()\n        self.tan_half_fov = np.tan(np.deg2rad(0.5 * self.opts.fov))\n\n        self.min_distance = np.maximum(\n            opts.min_distance,\n            (0.5 * np.sqrt(3)) / self.tan_half_fov)\n\n    def _setup_render(self):\n        # Unpack options ...\n        opts = self.opts\n\n        # Initialize a camera.\n        # TODO(ycho): Alternatively, specify the intrinsic matrix `K` instead.\n        cameras = FoVPerspectiveCameras(\n            znear=opts.znear,\n            zfar=opts.zfar,\n            aspect_ratio=opts.aspect,\n            fov=opts.fov,\n            degrees=True,\n            device=self.device\n        )\n\n        # Define the settings for rasterization and shading.\n        # As we are rendering images for visualization purposes only we will set faces_per_pixel=1\n        # and blur_radius=0.0. Refer to raster_points.py for explanations of\n        # these parameters.\n        # points_per_pixel (Optional): We will keep track of this many points per\n        # pixel, returning the nearest points_per_pixel points along the z-axis\n\n        # Create a points renderer by compositing points using an alpha compositor (nearer points\n        # are weighted more heavily). See [1] for an explanation.\n        if self.opts.use_mesh:\n            raster_settings = RasterizationSettings(\n                image_size=opts.image_size,\n                blur_radius=0.0,  # hmm...\n                faces_per_pixel=1\n            )\n            rasterizer = MeshRasterizer(cameras=cameras,\n                                        raster_settings=raster_settings)\n            lights = PointLights(device=self.device,\n                                 location=[[0.0, 0.0, -3.0]])\n\n            renderer = MeshRenderer(\n                rasterizer=rasterizer,\n                shader=SoftPhongShader(\n                    device=self.device,\n                    cameras=cameras,\n                    lights=lights\n                )\n            )\n        else:\n            raster_settings = PointsRasterizationSettings(\n                image_size=opts.image_size,\n                radius=0.1,\n                points_per_pixel=8\n            )\n            rasterizer = PointsRasterizer(\n                cameras=cameras, raster_settings=raster_settings)\n            renderer = PointsRenderer(\n                rasterizer=rasterizer,\n                compositor=AlphaCompositor()\n            )\n        return renderer\n\n    def _get_cube_cloud(self):\n        \"\"\"Get vertices of a unit-cube, with colors assigned according to\n        vertex coordinates.\"\"\"\n        vertices = list(itertools.product(\n            *zip([-0.5, -0.5, -0.5], [0.5, 0.5, 0.5])))\n        vertices = np.insert(vertices, 0, [0, 0, 0], axis=0)\n        vertices = th.as_tensor(vertices, dtype=th.float32, device=self.device)\n\n        # Map vertices to colors. =RGB(0.25~0.75)\n        colors = (0.5 + 0.5 * vertices)\n        cloud = Pointclouds(points=vertices[None], features=colors[None])\n        return cloud\n\n    def _get_cube_mesh(self):\n        # NOTE(ycho): duplicated from _get_cube_cloud()\n        vertices = list(itertools.product(\n            *zip([-0.5, -0.5, -0.5], [0.5, 0.5, 0.5])))\n        vertices = np.insert(vertices, 0, [0, 0, 0], axis=0)\n        vertices = th.as_tensor(\n            vertices, dtype=th.float32, device=self.device)\n\n        # FIXME(ycho): Hardcoded face indices.\n        # (We can't use Box.FACE since we need triangulated faces)\n        faces = [[7, 3, 5],\n                 [5, 3, 1],\n                 [5, 1, 6],\n                 [6, 1, 2],\n                 [6, 2, 8],\n                 [8, 2, 4],\n                 [8, 4, 7],\n                 [7, 4, 3],\n                 [3, 4, 1],\n                 [1, 4, 2],\n                 [8, 7, 6],\n                 [6, 7, 5]]\n        face_indices = th.as_tensor(\n            faces, dtype=th.int32, device=self.device).reshape(-1, 3, 3)\n        textures = TexturesVertex(\n            verts_features=(\n                0.5 + 0.5 * vertices)[None])\n        mesh = Meshes(\n            verts=vertices[None],\n            faces=face_indices[None],\n            textures=textures\n        )\n\n        return mesh\n\n    def _render(self):\n        \"\"\"Render the unit cube at various camera poses.\n\n        We deliberately sample the camera poses such that all vertices\n        of the cube are always in view.\n        \"\"\"\n        opts = self.opts\n\n        # TODO(ycho): is `no_grad()` here necessary?\n        with th.no_grad():\n            # Sample a Unit-ray viewing direction.\n            ray = th.randn(size=(opts.batch_size, 3), device=self.device)\n            ray /= th.norm(ray, dim=1, keepdim=True)\n\n            # Compute distance along the ray according to constraints.\n            distance = (self.min_distance +\n                        (opts.max_distance - self.min_distance) *\n                        th.rand(size=(opts.batch_size, 1), device=self.device))\n\n            # NOTE(ycho): `sqrt(3)/2` here comes from max radius of unit cube.\n            # The generic thing to do would be to compute the radius of our\n            # cloud. We're not explicitly taking the cube into account.\n            max_tangential_offset = th.clamp(\n                distance *\n                self.tan_half_fov -\n                (0.5 * np.sqrt(3)),\n                min=0.0)\n\n            # NOTE(ycho): We're sampling an offset orthogonal to the view ray.\n            # The constraint here is to be visible within the view plane.\n            offset = th.randn(size=(opts.batch_size, 3), device=self.device)\n            offset = offset - th.einsum('...a,...a->...',\n                                        offset, ray)[:, None] * ray\n            offset *= (max_tangential_offset /\n                       th.norm(offset, dim=1, keepdim=True))\n\n            # Finally, we have the full definition of the ray.\n            at = offset\n            pos = offset + ray * distance\n\n            # Compose the `lookat` camera transform according to this position\n            R, T = look_at_view_transform(\n                eye=pos, at=at, device=self.device)\n            if self.opts.use_mesh:\n                # NOTE(ycho): Ignoring alpha dimension\n                img = self.renderer(\n                    self.meshes, R=R, T=T\n                )[..., :3]\n            else:\n                img = self.renderer(\n                    point_clouds=self.clouds, R=R, T=T\n                )\n\n            # pytorch3d uses `NHWC` convension, convert to NCHW.\n            img = img.permute(0, 3, 1, 2)\n\n            # pytorch3d uses a `float` tensor for representing images,\n            # whereas we'd like for the image to come out as `uint8` ONLY for\n            # compatibility with the output from the `Objectron` dataset.\n            img = img.mul_(255.0).to(dtype=th.uint8)\n\n        return (img, R, T)\n\n    def __iter__(self):\n        while True:\n            (img, R, T) = self._render()\n            points_2d = self.renderer.rasterizer.cameras.transform_points(\n                self.clouds.points_padded(), R=R, T=T)\n\n            # Convert `points` to UV coordinates.\n            # This is to be consistent with the objectron dataset convention.\n            if not isinstance(points_2d, th.Tensor):\n                points_2d = points_2d.points_padded()\n            points_2d[..., :2] *= -0.5\n            points_2d[..., :2] += 0.5\n\n            # Add an axis indicating num_instance == 0\n            points_2d = points_2d[:, None]\n\n            # Projection matrix maps to -1 ~ 1 NDC coordinates.\n            P = self.renderer.rasterizer.cameras.get_projection_transform()\n            P = P.get_matrix()\n\n            # NOTE(ycho): Permute projection matrix to fit objectron\n            # convention.\n            # TODO(ycho): Verify if this keeps +z-axis sign convention\n            # consistent.\n            permutation = th.as_tensor([\n                [0, 1, 0, 0],\n                [1, 0, 0, 0],\n                [0, 0, -1, 0],\n                [0, 0, 0, 1]], dtype=th.float32, device=self.device)\n            projection = permutation @ P.transpose(2, 1)\n\n            # NOTE(ycho): Swap conventions here...\n            # rotation matrix : rmul -> lmul\n            # NOTE(ycho): Also, return flattened output as in `Objectron`.\n            translation = T.reshape(self.opts.batch_size, 1, 3)\n            scale = th.full_like(translation, 1.0)\n            orientation = (\n                R.transpose(\n                    2, 1).reshape(\n                    self.opts.batch_size, 1, -1))\n            print('scale', scale.shape)\n\n            # TODO(ycho): Figure out a way to unify these formats.\n            # see ai604-video-object-pose#10\n            out = {\n                Schema.IMAGE: img,\n                # NOTE(ycho): For now, only have `1` object per image.\n                Schema.CLASS: th.zeros((self.opts.batch_size, 1), dtype=th.int32,\n                                       device=self.device),\n                Schema.ORIENTATION: orientation,\n                Schema.TRANSLATION: translation,\n                Schema.SCALE: scale,\n                Schema.KEYPOINT_2D: points_2d,\n                Schema.INSTANCE_NUM: th.ones(\n                    self.opts.batch_size,\n                    device=self.device),\n                Schema.PROJECTION: projection.repeat(self.opts.batch_size, 1, 1),\n            }\n\n            # Unstack the batched render into a set of images, for compatibility with Objectron.\n            # NOTE(ycho): See if this results in a significant performance hit.\n            if self.opts.unstack:\n                for i in range(self.opts.batch_size):\n                    out_i = {k: v[i] for k, v in out.items()}\n                    if self.xfm is not None:\n                        out_i = self.xfm(out_i)\n                    yield out_i\n            else:\n                if self.xfm is not None:\n                    out = self.xfm(out)\n                yield out\n\n\ndef main():\n    opts = ColoredCubeDataset.Settings(batch_size=32, unstack=False)\n    opts = update_settings(opts)\n\n    device = resolve_device()\n    dataset = ColoredCubeDataset(opts, device,)\n    for data in dataset:\n        print({k: v.shape for k, v in data.items()})\n        save_image(data[Schema.IMAGE] / 255.0, F'/tmp/img.png')\n        break\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "55a54aa5fba4f25710d672ed1f3806f5c93ee4b7", "size": 12725, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/top/data/colored_cube_dataset.py", "max_stars_repo_name": "yycho0108/ai604-video-object-pose", "max_stars_repo_head_hexsha": "7067f36281038272b0e39166d8f9718076bb6e75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/top/data/colored_cube_dataset.py", "max_issues_repo_name": "yycho0108/ai604-video-object-pose", "max_issues_repo_head_hexsha": "7067f36281038272b0e39166d8f9718076bb6e75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2021-04-13T04:58:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T04:58:07.000Z", "max_forks_repo_path": "src/top/data/colored_cube_dataset.py", "max_forks_repo_name": "yycho0108/ai604-video-object-pose", "max_forks_repo_head_hexsha": "7067f36281038272b0e39166d8f9718076bb6e75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6479289941, "max_line_length": 98, "alphanum_fraction": 0.5554420432, "include": true, "reason": "import numpy", "num_tokens": 2962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.18282086890504126}}
{"text": "\"\"\"\nClass interface to the model calculator.\n\nCalling a model is somewhat non-trivial since the functions called depend\non the data type.  For 1D data the *Iq* kernel needs to be called, for\n2D data the *Iqxy* kernel needs to be called, and for SESANS data the\n*Iq* kernel needs to be called followed by a Hankel transform.  Before\nthe kernel is called an appropriate *q* calculation vector needs to be\nconstructed.  This is not the simple *q* vector where you have measured\nthe data since the resolution calculation will require values beyond the\nrange of the measured data.  After the calculation the resolution calculator\nmust be called to return the predicted value for each measured data point.\n\n:class:`DirectModel` is a callable object that takes *parameter=value*\nkeyword arguments and returns the appropriate theory values for the data.\n\n:class:`DataMixin` does the real work of interpreting the data and calling\nthe model calculator.  This is used by :class:`DirectModel`, which uses\ndirect parameter values and by :class:`bumps_model.Experiment` which wraps\nthe parameter values in boxes so that the user can set fitting ranges, etc.\non the individual parameters and send the model to the Bumps optimizers.\n\"\"\"\nfrom __future__ import print_function\n\nimport numpy as np  # type: ignore\n\n# TODO: fix sesans module\nfrom . import sesans  # type: ignore\nfrom . import weights\nfrom . import resolution\nfrom . import resolution2d\nfrom .details import make_kernel_args, dispersion_mesh\nfrom .product import RADIUS_MODE_ID\n\n# pylint: disable=unused-import\ntry:\n    from typing import Optional, Dict, Tuple\nexcept ImportError:\n    pass\nelse:\n    from .data import Data\n    from .kernel import Kernel, KernelModel\n    from .modelinfo import Parameter, ParameterSet\n# pylint: enable=unused-import\n\ndef call_kernel(calculator, pars, cutoff=0., mono=False):\n    # type: (Kernel, ParameterSet, float, bool) -> np.ndarray\n    \"\"\"\n    Call *kernel* returned from *model.make_kernel* with parameters *pars*.\n\n    *cutoff* is the limiting value for the product of dispersion weights used\n    to perform the multidimensional dispersion calculation more quickly at a\n    slight cost to accuracy. The default value of *cutoff=0* integrates over\n    the entire dispersion cube.  Using *cutoff=1e-5* can be 50% faster, but\n    with an error of about 1%, which is usually less than the measurement\n    uncertainty.\n\n    *mono* is True if polydispersity should be set to none on all parameters.\n    \"\"\"\n    mesh = get_mesh(calculator.info, pars, dim=calculator.dim, mono=mono)\n    #print(\"in call_kernel: pars:\", list(zip(*mesh))[0])\n    call_details, values, is_magnetic = make_kernel_args(calculator, mesh)\n    #print(\"in call_kernel: values:\", values)\n    return calculator(call_details, values, cutoff, is_magnetic)\n\ndef call_Fq(calculator, pars, cutoff=0., mono=False):\n    # type: (Kernel, ParameterSet, float, bool) -> np.ndarray\n    \"\"\"\n    Like :func:`call_kernel`, but returning F, F^2, R_eff, V_shell, V_form/V_shell.\n\n    For solid objects V_shell is equal to V_form and the volume ratio is 1.\n\n    Use parameter *radius_effective_mode* to select the effective radius\n    calculation to use amongst the *radius_effective_modes* list given in the\n    model.\n    \"\"\"\n    R_eff_type = int(pars.pop(RADIUS_MODE_ID, 1.0))\n    mesh = get_mesh(calculator.info, pars, dim=calculator.dim, mono=mono)\n    #print(\"in call_Fq: pars\", list(zip(*mesh))[0])\n    call_details, values, is_magnetic = make_kernel_args(calculator, mesh)\n    #print(\"in call_Fq: values:\", values)\n    return calculator.Fq(call_details, values, cutoff, is_magnetic, R_eff_type)\n\ndef call_profile(model_info, pars=None):\n    # type: (ModelInfo, ParameterSet) -> Tuple[np.ndarray, np.ndarray, Tuple[str, str]]\n    \"\"\"\n    Returns the profile *x, y, (xlabel, ylabel)* representing the model.\n    \"\"\"\n    if pars is None:\n        pars = {}\n    args = {}\n    for p in model_info.parameters.kernel_parameters:\n        if p.length > 1:\n            value = np.array([pars.get(p.id+str(j), p.default)\n                              for j in range(1, p.length+1)])\n        else:\n            value = pars.get(p.id, p.default)\n        args[p.id] = value\n    x, y = model_info.profile(**args)\n    return x, y, model_info.profile_axes\n\ndef get_mesh(model_info, values, dim='1d', mono=False):\n    # type: (ModelInfo, Dict[str, float], str, bool) -> List[Tuple[float, np.ndarray, np.ndarry]]\n    \"\"\"\n    Retrieve the dispersity mesh described by the parameter set.\n\n    Returns a list of *(value, dispersity, weights)* with one tuple for each\n    parameter in the model call parameters.  Inactive parameters return the\n    default value with a weight of 1.0.\n    \"\"\"\n    parameters = model_info.parameters\n    if mono:\n        active = lambda name: False\n    elif dim == '1d':\n        active = lambda name: name in parameters.pd_1d\n    elif dim == '2d':\n        active = lambda name: name in parameters.pd_2d\n    else:\n        active = lambda name: True\n\n    #print(\"in get_mesh: pars:\",[p.id for p in parameters.call_parameters])\n    mesh = [_get_par_weights(p, values, active(p.name))\n            for p in parameters.call_parameters]\n    return mesh\n\n\ndef _get_par_weights(parameter, values, active=True):\n    # type: (Parameter, Dict[str, float]) -> Tuple[float, np.ndarray, np.ndarray]\n    \"\"\"\n    Generate the distribution for parameter *name* given the parameter values\n    in *pars*.\n\n    Uses \"name\", \"name_pd\", \"name_pd_type\", \"name_pd_n\", \"name_pd_sigma\"\n    from the *pars* dictionary for parameter value and parameter dispersion.\n    \"\"\"\n    value = float(values.get(parameter.name, parameter.default))\n    npts = values.get(parameter.name+'_pd_n', 0)\n    width = values.get(parameter.name+'_pd', 0.0)\n    relative = parameter.relative_pd\n    if npts == 0 or width == 0.0 or not active:\n        # Note: orientation parameters have the viewing angle as the parameter\n        # value and the jitter in the distribution, so be sure to set the\n        # empty pd for orientation parameters to 0.\n        pd = [value if relative or not parameter.polydisperse else 0.0], [1.0]\n    else:\n        limits = parameter.limits\n        disperser = values.get(parameter.name+'_pd_type', 'gaussian')\n        nsigma = values.get(parameter.name+'_pd_nsigma', 3.0)\n        pd = weights.get_weights(disperser, npts, width, nsigma,\n                                 value, limits, relative)\n    return value, pd[0], pd[1]\n\n\ndef _vol_pars(model_info, values):\n    # type: (ModelInfo, ParameterSet) -> Tuple[np.ndarray, np.ndarray]\n    vol_pars = [_get_par_weights(p, values)\n                for p in model_info.parameters.call_parameters\n                if p.type == 'volume']\n    #import pylab; pylab.plot(vol_pars[0][0],vol_pars[0][1]); pylab.show()\n    dispersity, weight = dispersion_mesh(model_info, vol_pars)\n    return dispersity, weight\n\n\ndef _make_sesans_transform(data):\n    from sas.sascalc.data_util.nxsunit import Converter\n\n    # Pre-compute the Hankel matrix (H)\n    SElength = Converter(data._xunit)(data.x, \"A\")\n\n    theta_max = Converter(\"radians\")(data.sample.zacceptance)[0]\n    q_max = 2 * np.pi / np.max(data.source.wavelength) * np.sin(theta_max)\n    zaccept = Converter(\"1/A\")(q_max, \"1/\" + data.source.wavelength_unit),\n\n    Rmax = 10000000\n    hankel = sesans.SesansTransform(data.x, SElength,\n                                    data.source.wavelength,\n                                    zaccept, Rmax)\n    return hankel\n\n\nclass DataMixin(object):\n    \"\"\"\n    DataMixin captures the common aspects of evaluating a SAS model for a\n    particular data set, including calculating Iq and evaluating the\n    resolution function.  It is used in particular by :class:`DirectModel`,\n    which evaluates a SAS model parameters as key word arguments to the\n    calculator method, and by :class:`bumps_model.Experiment`, which wraps the\n    model and data for use with the Bumps fitting engine.  It is not\n    currently used by :class:`sasview_model.SasviewModel` since this will\n    require a number of changes to SasView before we can do it.\n\n    :meth:`_interpret_data` initializes the data structures necessary\n    to manage the calculations.  This sets attributes in the child class\n    such as *data_type* and *resolution*.\n\n    :meth:`_calc_theory` evaluates the model at the given control values.\n\n    :meth:`_set_data` sets the intensity data in the data object,\n    possibly with random noise added.  This is useful for simulating a\n    dataset with the results from :meth:`_calc_theory`.\n    \"\"\"\n    def _interpret_data(self, data, model):\n        # type: (Data, KernelModel) -> None\n        # pylint: disable=attribute-defined-outside-init\n\n        self._data = data\n        self._model = model\n\n        # interpret data\n        if hasattr(data, 'isSesans') and data.isSesans:\n            self.data_type = 'sesans'\n        elif hasattr(data, 'qx_data'):\n            self.data_type = 'Iqxy'\n        elif getattr(data, 'oriented', False):\n            self.data_type = 'Iq-oriented'\n        else:\n            self.data_type = 'Iq'\n\n        if self.data_type == 'sesans':\n            res = _make_sesans_transform(data)\n            index = slice(None, None)\n            if data.y is not None:\n                Iq, dIq = data.y, data.dy\n            else:\n                Iq, dIq = None, None\n        elif self.data_type == 'Iqxy':\n            #if not model.info.parameters.has_2d:\n            #    raise ValueError(\"not 2D without orientation or magnetic parameters\")\n            q = np.sqrt(data.qx_data**2 + data.qy_data**2)\n            qmin = getattr(data, 'qmin', 1e-16)\n            qmax = getattr(data, 'qmax', np.inf)\n            accuracy = getattr(data, 'accuracy', 'Low')\n            index = (data.mask == 0) & (q >= qmin) & (q <= qmax)\n            if data.data is not None:\n                index &= ~np.isnan(data.data)\n                Iq = data.data[index]\n                dIq = data.err_data[index]\n            else:\n                Iq, dIq = None, None\n            res = resolution2d.Pinhole2D(data=data, index=index,\n                                         nsigma=3.0, accuracy=accuracy)\n        elif self.data_type == 'Iq':\n            index = (data.x >= data.qmin) & (data.x <= data.qmax)\n            mask = getattr(data, 'mask', None)\n            if mask is not None:\n                index &= (mask == 0)\n            if data.y is not None:\n                index &= ~np.isnan(data.y)\n                Iq = data.y[index]\n                dIq = data.dy[index]\n            else:\n                Iq, dIq = None, None\n            if getattr(data, 'dx', None) is not None:\n                q, dq = data.x[index], data.dx[index]\n                if (dq > 0).any():\n                    res = resolution.Pinhole1D(q, dq)\n                else:\n                    res = resolution.Perfect1D(q)\n            elif (getattr(data, 'dxl', None) is not None\n                  and getattr(data, 'dxw', None) is not None):\n                res = resolution.Slit1D(data.x[index],\n                                        qx_width=data.dxl[index],\n                                        qy_width=data.dxw[index])\n            else:\n                res = resolution.Perfect1D(data.x[index])\n        elif self.data_type == 'Iq-oriented':\n            index = (data.x >= data.qmin) & (data.x <= data.qmax)\n            if data.y is not None:\n                index &= ~np.isnan(data.y)\n                Iq = data.y[index]\n                dIq = data.dy[index]\n            else:\n                Iq, dIq = None, None\n            if (getattr(data, 'dxl', None) is None\n                    or getattr(data, 'dxw', None) is None):\n                raise ValueError(\"oriented sample with 1D data needs slit resolution\")\n\n            res = resolution2d.Slit2D(data.x[index],\n                                      qx_width=data.dxw[index],\n                                      qy_width=data.dxl[index])\n        else:\n            raise ValueError(\"Unknown data type\") # never gets here\n\n        # Remember function inputs so we can delay loading the function and\n        # so we can save/restore state\n        self._kernel = None\n        self.Iq, self.dIq, self.index = Iq, dIq, index\n        self.resolution = res\n        self.results = None  # type: Optional[Callable[[], OrderedDict]\n\n    def _set_data(self, Iq, noise=None):\n        # type: (np.ndarray, Optional[float]) -> None\n        # pylint: disable=attribute-defined-outside-init\n        if noise is not None:\n            self.dIq = Iq*noise*0.01\n        dy = self.dIq\n        y = Iq + np.random.randn(*dy.shape) * dy\n        self.Iq = y\n        if self.data_type in ('Iq', 'Iq-oriented'):\n            if self._data.y is None:\n                self._data.y = np.empty(len(self._data.x), 'd')\n            if self._data.dy is None:\n                self._data.dy = np.empty(len(self._data.x), 'd')\n            self._data.dy[self.index] = dy\n            self._data.y[self.index] = y\n        elif self.data_type == 'Iqxy':\n            if self._data.data is None:\n                self._data.data = np.empty_like(self._data.qx_data, 'd')\n            if self._data.err_data is None:\n                self._data.err_data = np.empty_like(self._data.qx_data, 'd')\n            self._data.data[self.index] = y\n            self._data.err_data[self.index] = dy\n        elif self.data_type == 'sesans':\n            if self._data.y is None:\n                self._data.y = np.empty(len(self._data.x), 'd')\n            self._data.y[self.index] = y\n        else:\n            raise ValueError(\"Unknown model\")\n\n    def _calc_theory(self, pars, cutoff=0.0):\n        # type: (ParameterSet, float) -> np.ndarray\n        if self._kernel is None:\n            # TODO: change interfaces so that resolution returns kernel inputs\n            # Maybe have resolution always return a tuple, or maybe have\n            # make_kernel accept either an ndarray or a pair of ndarrays.\n            kernel_inputs = self.resolution.q_calc\n            if isinstance(kernel_inputs, np.ndarray):\n                kernel_inputs = (kernel_inputs,)\n            self._kernel = self._model.make_kernel(kernel_inputs)\n\n        # Need to pull background out of resolution for multiple scattering\n        default_background = self._model.info.parameters.common_parameters[1].default\n        background = pars.get('background', default_background)\n        pars = pars.copy()\n        pars['background'] = 0.\n\n        Iq_calc = call_kernel(self._kernel, pars, cutoff=cutoff)\n        self.results = getattr(self._kernel, 'results', None)\n        # Storing the calculated Iq values so that they can be plotted.\n        # Only applies to oriented USANS data for now.\n        # TODO: extend plotting of calculate Iq to other measurement types\n        # TODO: refactor so we don't store the result in the model\n        self.Iq_calc = Iq_calc\n        result = self.resolution.apply(Iq_calc)\n        if hasattr(self.resolution, 'nx'):\n            self.Iq_calc = (\n                self.resolution.qx_calc, self.resolution.qy_calc,\n                np.reshape(Iq_calc, (self.resolution.ny, self.resolution.nx))\n            )\n        return result + background\n\n\nclass DirectModel(DataMixin):\n    \"\"\"\n    Create a calculator object for a model.\n\n    *data* is 1D SAS, 2D SAS or SESANS data\n\n    *model* is a model calculator return from :func:`generate.load_model`\n\n    *cutoff* is the polydispersity weight cutoff.\n    \"\"\"\n    def __init__(self, data, model, cutoff=1e-5):\n        # type: (Data, KernelModel, float) -> None\n        self.model = model\n        self.cutoff = cutoff\n        # Note: _interpret_data defines the model attributes\n        self._interpret_data(data, model)\n\n    def __call__(self, **pars):\n        # type: (**float) -> np.ndarray\n        return self._calc_theory(pars, cutoff=self.cutoff)\n\n    def simulate_data(self, noise=None, **pars):\n        # type: (Optional[float], **float) -> None\n        \"\"\"\n        Generate simulated data for the model.\n        \"\"\"\n        Iq = self.__call__(**pars)\n        self._set_data(Iq, noise=noise)\n\n    def profile(self, **pars):\n        # type: (**float) -> None\n        \"\"\"\n        Generate a plottable profile.\n        \"\"\"\n        return call_profile(self.model.info, pars)\n\ndef main():\n    # type: () -> None\n    \"\"\"\n    Program to evaluate a particular model at a set of q values.\n    \"\"\"\n    import sys\n    from .data import empty_data1D, empty_data2D\n    from .core import load_model_info, build_model\n\n    if len(sys.argv) < 3:\n        print(\"usage: python -m sasmodels.direct_model modelname (q|qx,qy) par=val ...\")\n        sys.exit(1)\n    model_name = sys.argv[1]\n    call = sys.argv[2].upper()\n    try:\n        values = [float(v) for v in call.split(',')]\n    except ValueError:\n        values = []\n    if len(values) == 1:\n        q, = values\n        data = empty_data1D([q])\n    elif len(values) == 2:\n        qx, qy = values\n        data = empty_data2D([qx], [qy])\n    else:\n        print(\"use q or qx,qy\")\n        sys.exit(1)\n\n    model_info = load_model_info(model_name)\n    model = build_model(model_info)\n    calculator = DirectModel(data, model)\n    pars = dict((k, (float(v) if not k.endswith(\"_pd_type\") else v))\n                for pair in sys.argv[3:]\n                for k, v in [pair.split('=')])\n    Iq = calculator(**pars)\n    print(Iq[0])\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "e6b11dcec5f38a2632a61a5f91b68f238a6bdbd6", "size": 17388, "ext": "py", "lang": "Python", "max_stars_repo_path": "sasmodels/direct_model.py", "max_stars_repo_name": "zattala/sasmodels", "max_stars_repo_head_hexsha": "a547aa73d43145b3bd34770b0ea27ba8882170a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sasmodels/direct_model.py", "max_issues_repo_name": "zattala/sasmodels", "max_issues_repo_head_hexsha": "a547aa73d43145b3bd34770b0ea27ba8882170a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sasmodels/direct_model.py", "max_forks_repo_name": "zattala/sasmodels", "max_forks_repo_head_hexsha": "a547aa73d43145b3bd34770b0ea27ba8882170a3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6261682243, "max_line_length": 97, "alphanum_fraction": 0.6193926846, "include": true, "reason": "import numpy", "num_tokens": 4243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.1827520113474326}}
{"text": "#!/usr/bin/python\n\n# imports\nimport sys\nimport os\nsys.path.append(os.path.join('..', 'core'))\nsys.path.append(os.path.join('..', 'utils'))\nimport numpy as np\nfrom datetime import datetime\n# import my classes\nfrom project import Project\n#from dataReaderATS import DataReaderATS\n#from dataReaderSpam import DataReaderSPAM\n#from dataReaderInternal import DataReaderInternal\nfrom calibrator import Calibrator\nfrom decimationParameters import DecimationParams\nfrom windowParameters import WindowParams\nfrom decimator import Decimator\nfrom windower import Windower\nfrom spectrumCalculator import SpectrumCalculator\nfrom spectrumWriter import SpectrumWriter\n# utilities\nfrom utilsPlotter import *\nfrom utilsProcess import *\n\n\n# calculate spectra for the project\n# the philosophy here is that spectra is calculated out for all data\n# and then later limited using statistics and time constraints\ndef projectSpecCalc(proj, **kwargs):\n\tgeneralPrint(\"ProjectSpecCalc\", \"Calculating spectra for project with options: {}\".format(kwargs))\n\t# default options\n\toptions = parseKeywords(getDefaultOptions(proj), kwargs)\n\n\t# calculate the spectra\n\t# get the reference time\n\tdatetimeRef = proj.getRefTime()\t\n\t# prepare the calibrator\n\tcal = Calibrator(proj.getCalDataPath())\n\tif options[\"calibrate\"]:\n\t\tcal.printInfo()\t\t\t\n\n\t# loop over sites\n\tfor s in options[\"sites\"]:\n\t\t# print site info\n\t\tproj.printSiteInfo(s)\n\n\t\t# get measurement directories for site s\n\t\ttimeMeas = proj.getSiteTimeFiles(s)\n\n\t\t# loop over measurement folders and calculate spectra for each one\n\t\tfor meas in timeMeas:\n\t\t\t# get measurement sample frequency\n\t\t\tfs = proj.getMeasSampleFreq(s, meas)\n\t\t\t# check to see if in given frequency list\n\t\t\tif int(fs) not in options[\"freqs\"]:\n\t\t\t\tcontinue\n\t\t\t\n\t\t\t# print measurement info\n\t\t\tproj.printMeasInfo(s, meas)\n\n\t\t\t# get measurement start and end times\n\t\t\tdatetimeStart = proj.getMeasStartTime(s, meas)\n\t\t\tdatetimeEnd = proj.getMeasEndTime(s, meas)\t\t\t\n\n\t\t\t# get data, sensor info, serial info, chopper info for calibration\n\t\t\treader = proj.getMeasDataReader(s, meas)\n\t\t\t# get data start and end times - these may not be equal to startDate and endDate\n\t\t\t# there is the issue of ats data recording end time as one sample late\n\t\t\t# hence get the actual end time\n\t\t\tdataStartTime, dataEndTime = reader.getDataTimes(datetimeStart, datetimeEnd)\t\t\t\t\n\t\t\tdataChans = reader.getChannels()\n\t\t\tif len(options[\"chans\"]) > 0:\n\t\t\t\tdataChans = options[\"chans\"]\n\t\t\t# alternatively, could simply do getPhysicalSamples() and get all data that way\n\t\t\tdata = reader.getPhysicalData(dataStartTime, dataEndTime, chans=dataChans)\n\t\t\t\n\t\t\tif options[\"calibrate\"]:\n\t\t\t\t# do the calibration here\t\t\t\t\n\t\t\t\tsensors = reader.getSensors(dataChans)\n\t\t\t\tserials = reader.getSerials(dataChans)\n\t\t\t\tchoppers = reader.getChoppers(dataChans)\t\n\t\t\t\tdata = cal.calibrate(data, fs, sensors, serials, choppers)\n\n\t\t\t# notch filter if required\n\t\t\tfor n in options[\"notch\"]:\n\t\t\t\tfor c in data:\n\t\t\t\t\tdata[c] = notchFilter(data[c], fs, n, n/5.0)\t\t\t\t\n\n\t\t\t# define decimation parameters\n\t\t\tdecParams = DecimationParams(fs)\n\t\t\tif len(options[\"evalfreq\"]) == 0:\n\t\t\t\tdecParams.setDecimationParams(options[\"declevels\"], options[\"freqlevel\"])\n\t\t\telse:\n\t\t\t\tdecParams.setFrequencyParams(options[\"evalfreq\"], options[\"declevels\"], options[\"freqlevel\"])\n\t\t\tdecParams.printInfo()\n\t\t\tnumLevels = decParams.getNumLevels()\n\n\t\t\t# now do window parameters\n\t\t\twinParams = WindowParams(decParams)\n\t\t\t# winParams.printInfo()\n\n\t\t\t# create the decimator\n\t\t\tdec = Decimator(data, fs, decParams)\n\t\t\t# dec.printInfo()\n\n\t\t\t# loop through decimation levels\n\t\t\tfor iDec in xrange(0, numLevels):\t\n\t\t\t\t# get the data for the current level\n\t\t\t\tcheck = dec.incrementLevel()\n\t\t\t\tif not check:\n\t\t\t\t\tbreak # not enough data\n\t\t\t\t#dec.printInfo()\n\t\t\t\tdata = dec.getData()\n\n\t\t\t\t# create the windower and give it window parameters for current level\n\t\t\t\tfsDec = dec.getSampleFreq()\n\t\t\t\twin = Windower(datetimeRef, dataStartTime, data, fsDec, winParams.getWindowSize(iDec), winParams.getOverlap(iDec))\n\t\t\t\tnumWindows = win.getNumWindows()\t\n\t\t\t\t# win.printInfo()\n\t\t\t\tif numWindows < 2:\n\t\t\t\t\tbreak # do no more decimation\t\n\n\t\t\t\t# create the spectrum calculator and statistics calculators\n\t\t\t\tspecCalc = SpectrumCalculator(fsDec, winParams.getWindowSize(iDec))\t\n\t\t\t\t\n\t\t\t\t# get ready a file to save the spectra\n\t\t\t\tspecWrite = SpectrumWriter(proj.getSpecDataPathMeas(s, meas), datetimeRef)\n\t\t\t\tspecWrite.openBinaryForWriting(\"spectra\", iDec, fsDec, winParams.getWindowSize(iDec), \n\t\t\t\t\twinParams.getOverlap(iDec), win.getGlobalWindowOffset(), numWindows, dataChans)\n\n\t\t\t\t# loop though windows, calculate spectra and save\n\t\t\t\tfor iW in xrange(0, numWindows):\n\t\t\t\t\t# get the window data\n\t\t\t\t\twinData = win.getData(iW)\t\t\t\n\n\t\t\t\t\t# calculate spectra\n\t\t\t\t\tf, specData = specCalc.calcFourierCoeff(winData)\n\n\t\t\t\t\t# write out spectra\n\t\t\t\t\tspecWrite.writeBinary(specData, iW)\n\t\t\t\t\n\t\t\t\t# close spectra and stat files\n\t\t\t\tspecWrite.closeFile()\n\ndef getDefaultOptions(proj):\n\t# default options\n\tdefault = {}\n\tdefault[\"sites\"] = proj.getAllSites()\n\tdefault[\"freqs\"] = proj.getAllSampleFreq()\t\n\tdefault[\"chans\"] = []\n\tdefault[\"evalfreq\"] = []\n\tdefault[\"declevels\"] = 7\n\tdefault[\"freqlevel\"] = 6\n\tdefault[\"calibrate\"] = True\n\tdefault[\"notch\"] = []\n\treturn default\n\ndef parseKeywords(default, keywords):\n\t# check user options\n\tfor w in default:\n\t\tif w in keywords:\n\t\t\tdefault[w] = keywords[w]\t\n\treturn default\n\n", "meta": {"hexsha": "18f5409f3eb5d853eb2e30a0ccef2adff84b301f", "size": 5397, "ext": "py", "lang": "Python", "max_stars_repo_path": "inbuilt/projectSpecCalc.py", "max_stars_repo_name": "geobook2015/magPy", "max_stars_repo_head_hexsha": "af0f31fc931786ac6f8d69a5290366418035859d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-19T18:29:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-19T18:29:15.000Z", "max_issues_repo_path": "inbuilt/projectSpecCalc.py", "max_issues_repo_name": "geobook2015/magPy", "max_issues_repo_head_hexsha": "af0f31fc931786ac6f8d69a5290366418035859d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inbuilt/projectSpecCalc.py", "max_forks_repo_name": "geobook2015/magPy", "max_forks_repo_head_hexsha": "af0f31fc931786ac6f8d69a5290366418035859d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-03T01:59:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-03T07:47:10.000Z", "avg_line_length": 32.5120481928, "max_line_length": 118, "alphanum_fraction": 0.7265147304, "include": true, "reason": "import numpy", "num_tokens": 1360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.18275200800421965}}
{"text": "import os\nimport ctypes as ct\nimport numpy as np\nfrom gsl_wrappers import GSLSpline, GSLSpline2d, BICUBIC, BILINEAR\nimport sys\n\nc_dbl_array = np.ctypeslib.ndpointer(dtype=np.float64, ndim=1, flags=\"C_CONTIGUOUS\")\nc_int_array = np.ctypeslib.ndpointer(dtype=np.int, ndim=1, flags=\"C_CONTIGUOUS\")\n\nif sys.version_info[0] < 3:\n    ascii_string = ct.c_char_p\nelse:\n    class ascii_string(object):\n        @classmethod\n        def from_param(cls, value):\n            if isinstance(value, bytes):\n                return value\n            else:\n                return value.encode('ascii')\n\n\nclass c_limber_config(ct.Structure):\n    _fields_ = [\n        (\"xlog\", ct.c_bool),\n        (\"ylog\", ct.c_bool),\n        (\"n_ell\", ct.c_int),\n        (\"ell\", ct.POINTER(ct.c_double)),\n        (\"prefactor\", ct.c_double),\n        (\"status\", ct.c_int),\n       #(\"absolute_tolerance\", ct.c_double),\n        #(\"relative_tolerance\", ct.c_double),\n]\n\n\nLIMBER_STATUS_OK =  0\nLIMBER_STATUS_ZERO =  1\nLIMBER_STATUS_NEGATIVE =  2\nLIMBER_STATUS_ERROR =  3\n\nc_gsl_spline = ct.c_void_p\n\ndirname = os.path.split(__file__)[0]\n#lib = ct.cdll.LoadLibrary(os.path.join(dirname, \"../../shear/spectra/interface.so\"))\nlib = ct.cdll.LoadLibrary(os.path.join(dirname, \"src/spec_tools.so\"))\nlib.get_named_w_spline.restype = c_gsl_spline\nlib.get_named_w_spline.argtypes = [ct.c_size_t, ascii_string, ct.c_int, c_dbl_array, ct.c_double, ct.c_void_p]\n\nlib.get_named_w2_spline.restype = c_gsl_spline #Assign a ctypes type to specify the result type of the foreign function. Use None for void, a function not returning anything.\nlib.get_named_w2_spline.argtypes = [ct.c_size_t, ascii_string, ct.c_int, c_dbl_array, ct.c_double, ct.c_void_p] #Assign a tuple of ctypes types to specify the argument types that the function accepts\n\nlib.get_named_w3_spline.restype = c_gsl_spline #Assign a ctypes type to specify the result type of the foreign function. Use None for void, a function not returning anything.\nlib.get_named_w3_spline.argtypes = [ct.c_size_t, ascii_string, ct.c_int, c_dbl_array, ct.c_double, ct.c_void_p] #Assign a tuple of ctypes types to specify the argument types that the function accepts\n\nlib.get_named_nchi_spline.restype = c_gsl_spline\nlib.get_named_nchi_spline.argtypes = [ct.c_size_t, ascii_string, ct.c_int, c_dbl_array, ct.c_void_p, ct.c_void_p]\n\n#lib.get_named_Dchi_spline.restype = c_gsl_spline\n#lib.get_named_Dchi_spline.argtypes = [ct.c_size_t, ascii_string, ct.c_int, c_dbl_array, ct.c_void_p, ct.c_void_p]\n\n#lib.get_reduced_kernel.restype = c_gsl_spline\n#lib.get_reduced_kernel.argtypes = [ct.c_void_p, ct.c_void_p]\n\nlib.cmb_wl_kappa_kernel.restype = c_gsl_spline\nlib.cmb_wl_kappa_kernel.argtypes = [ct.c_double, ct.c_double, c_gsl_spline]\n\nlib.get_kernel_peak.restype = ct.c_double\nlib.get_kernel_peak.argtypes = [ct.c_void_p, ct.c_void_p, ct.c_int]\n\n#lib.limber_integral.restype = ct.c_int\n#lib.limber_integral.argtypes = [ct.POINTER(c_limber_config), ct.c_void_p, ct.c_void_p, \n#                                ct.c_void_p, ct.c_void_p, ct.c_int, c_dbl_array]\n\nlib.limber_integral.restype = c_gsl_spline\n#lib.limber_integral.restype = ct.c_int\n#for f(k,z)\n#lib.limber_integral.argtypes = [ct.POINTER(c_limber_config), ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p] \n# for D(k,z) and f(k,z) \n#lib.limber_integral.argtypes = [ct.POINTER(c_limber_config), ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p] \n# for D(k,z) and f(k,z) and b(k,z)\n#lib.limber_integral.argtypes = [ct.POINTER(c_limber_config), ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p]\nlib.limber_integral.argtypes = [ct.POINTER(c_limber_config), ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p] \n\n#lib.limber_integral_rsd.restype = ct.c_int\n#lib.limber_integral_rsd.argtypes = [ct.POINTER(c_limber_config), ct.c_void_p, ct.c_void_p, \n#                                    ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, \n#                                    ct.c_int, ct.c_int, c_dbl_array]\n\nlib.load_interpolator_chi.restype = ct.c_void_p\nlib.load_interpolator_chi.argtypes = [ct.c_size_t, ct.c_void_p, ascii_string, ascii_string, ascii_string, ascii_string]\n\n#for f(k,z)\n\nlib.load_interpolator_chi2.restype = ct.c_void_p\nlib.load_interpolator_chi2.argtypes = [ct.c_size_t, ct.c_void_p, ct.c_void_p, ascii_string, ascii_string, ascii_string, ascii_string]\n\n#for D(k,z)\n\nlib.load_interpolator_chi3.restype = ct.c_void_p\nlib.load_interpolator_chi3.argtypes = [ct.c_size_t, ct.c_void_p, ct.c_void_p, ascii_string, ascii_string, ascii_string, ascii_string]\n\n\n#for b(k,z)\n\nlib.load_interpolator_chi4.restype = ct.c_void_p\nlib.load_interpolator_chi4.argtypes = [ct.c_size_t, ct.c_void_p, ct.c_void_p, ascii_string, ascii_string, ascii_string, ascii_string]\n\n\nc_power_scaling_function = ct.CFUNCTYPE(ct.c_double, ct.c_double, \n    ct.c_double, ct.c_double, ct.c_voidp)\n\nlib.load_interpolator_chi_function.restype = ct.c_void_p\nlib.load_interpolator_chi_function.argtypes = [ct.c_size_t, ct.c_void_p, \nascii_string, ascii_string, ascii_string, ascii_string, c_power_scaling_function, ct.c_void_p]\n\n#for f(k,z)\n\nlib.load_interpolator_chi_function2.restype = ct.c_void_p\nlib.load_interpolator_chi_function2.argtypes = [ct.c_size_t, ct.c_void_p, ct.c_void_p, \nascii_string, ascii_string, ascii_string, ascii_string, c_power_scaling_function, ct.c_void_p]\n\n\n#for D(k,z)\n\nlib.load_interpolator_chi_function3.restype = ct.c_void_p\nlib.load_interpolator_chi_function3.argtypes = [ct.c_size_t, ct.c_void_p, ct.c_void_p, \nascii_string, ascii_string, ascii_string, ascii_string, c_power_scaling_function, ct.c_void_p]\n\n#for b(k,z)\n\nlib.load_interpolator_chi_function4.restype = ct.c_void_p\nlib.load_interpolator_chi_function4.argtypes = [ct.c_size_t, ct.c_void_p, ct.c_void_p, \nascii_string, ascii_string, ascii_string, ascii_string, c_power_scaling_function, ct.c_void_p]\n\n\nlib.interp_2d.restype = ct.c_double\nlib.interp_2d.argtypes = [ct.c_double, ct.c_double, ct.c_void_p]\n\nlib.destroy_interp_2d.restype = None\nlib.destroy_interp_2d.argtypes = [ct.c_void_p]\n\n\ndef get_cmb_kappa_spline(chi_max, chi_star, a_of_chi):\n    \"Compute the CMB WL kernel W_cmb(chi) spline\"\n    return GSLSpline(lib.cmb_wl_kappa_kernel(chi_max, chi_star, a_of_chi))\n\ndef evaluate_power(power, k, z):\n    return lib.interp_2d(k,z,power)\n\ndef free_power(power):\n    try:\n        lib.destroy_interp_2d(power)\n    except ct.ArgumentError as e:\n        power.__del__()\n\n\ndef get_named_nchi_spline(block, section, nbin, z, a_of_chi, chi_of_z):\n    return GSLSpline(lib.get_named_nchi_spline(block._ptr, section, nbin, z, a_of_chi, chi_of_z))\n\n#def get_named_Dchi_spline(block, section, nbin, z, a_of_chi, chi_of_z):\n#    return GSLSpline(lib.get_named_Dchi_spline(block._ptr, section, nbin, z, a_of_chi, chi_of_z))\n\n\ndef get_named_w_spline(block, section, bin, z, chi_max, a_of_chi):\n    \"Compute a galcl kernel W(chi) spline\"\n    return GSLSpline(lib.get_named_w_spline(block._ptr, section, bin, z, chi_max, a_of_chi))\n\ndef get_named_w2_spline(block, section, bin, z, chi_max, a_of_chi):\n    \"Compute a galcl kernel W2(chi) spline\"\n    return GSLSpline(lib.get_named_w2_spline(block._ptr, section, bin, z, chi_max, a_of_chi))\n\ndef get_named_w3_spline(block, section, bin, z, chi_max, a_of_chi):\n    \"Compute a galcl kernel W3(chi) spline\"\n    return GSLSpline(lib.get_named_w3_spline(block._ptr, section, bin, z, chi_max, a_of_chi))\n\n\n\ndef load_power_chi(block, chi_of_z, section, k_name, z_name, p_name):\n    \"Load P(k,z) and convert z -> chi\"\n    r = lib.load_interpolator_chi(block._ptr, chi_of_z, section, k_name, z_name, p_name)\n    if not r:\n        raise ValueError(\"Could not load power spectrum from section {0} (k:{1} z:{2} p:{3})\".format(section, k_name, z_name, p_name))\n    return r\n\n\ndef load_power_chi2(block, chi_of_z, z_of_chi, section, k_name, z_name, t_name):\n    \"Load T(k,z) and convert z -> chi -> z(chi)\"\n    rr = lib.load_interpolator_chi2(block._ptr, chi_of_z, z_of_chi, section, k_name, z_name, t_name)\n    if not rr:\n        raise ValueError(\"Could not load growth rate f from section {0} (k:{1} z:{2} p:{3})\".format(section, k_name, z_name, t_name))\n    return rr\n\ndef load_power_chi3(block, chi_of_z, z_of_chi, section, k_name, z_name, p_name):\n    \"Load p(k,z) and convert z -> chi -> z(chi)\"\n    rrr = lib.load_interpolator_chi3(block._ptr, chi_of_z, z_of_chi, section, k_name, z_name, p_name)\n    if not rrr:\n        raise ValueError(\"Could not load growth factor D from section {0} (k:{1} z:{2} p:{3})\".format(section, k_name, z_name, p_name))\n    return rrr\n\n\ndef load_power_chi4(block, chi_of_z, z_of_chi, section, k_name, z_name, p_name):\n    \"Load p(k,z) and convert z -> chi -> z(chi)\"\n    rrrr = lib.load_interpolator_chi4(block._ptr, chi_of_z, z_of_chi, section, k_name, z_name, p_name)\n    if not rrrr:\n        raise ValueError(\"Could not load galaxy bias b from section {0} (k:{1} z:{2} p:{3})\".format(section, k_name, z_name, p_name))\n    return rrrr\n\n\ndef load_power_chi_function(block, chi_of_z, section, k_name, z_name, p_name, function, args):\n    \"Load P(k,z) and convert z -> chi and scale P->f(k,z)*P\"\n    r = lib.load_interpolator_chi_function(block._ptr, chi_of_z, section, k_name, z_name, p_name, function, args)\n    if not r:\n        raise ValueError(\"Could not load scaled power spectrum from section {0} (k:{1} z:{2} p:{3})\".format(section, k_name, z_name, p_name))\n    return r\n\ndef load_power_chi_function2(block, chi_of_z, z_of_chi, section, k_name, z_name, t_name, function, args):\n    \"Load T(k,z) and convert z -> chi and scale T->f(k,z)*T\"\n    rr = lib.load_interpolator_chi_function2(block._ptr, chi_of_z, z_of_chi, section, k_name, z_name, t_name, function, args)\n    if not rr:\n        raise ValueError(\"Could not load scaled growth rate f from section {0} (k:{1} z:{2} p:{3})\".format(section, k_name, z_name, t_name))\n    return rr\n\ndef load_power_chi_function3(block, chi_of_z, z_of_chi, section, k_name, z_name, p_name, function, args):\n    \"Load pnl(k,z) and convert z -> chi and scale pnl->f(k,z)*pnl\"\n    rrr = lib.load_interpolator_chi_function3(block._ptr, chi_of_z, z_of_chi, section, k_name, z_name, p_name, function, args)\n    if not rrr:\n        raise ValueError(\"Could not load scaled growth factor D from section {0} (k:{1} z:{2} p:{3})\".format(section, k_name, z_name, p_name))\n    return rrr\n\n\ndef load_power_chi_function4(block, chi_of_z, z_of_chi, section, k_name, z_name, p_name, function, args):\n    \"Load pnl(k,z) and convert z -> chi and scale pnl->f(k,z)*pnl\"\n    rrrr = lib.load_interpolator_chi_function4(block._ptr, chi_of_z, z_of_chi, section, k_name, z_name, p_name, function, args)\n    if not rrrr:\n        raise ValueError(\"Could not load scaled galaxy bias b from section {0} (k:{1} z:{2} p:{3})\".format(section, k_name, z_name, p_name))\n    return rrrr\n\n\n\ndef get_kernel_peak(WbX, WbY, nchi=500): #changed but not used\n    \"Get chi of maximum of kernel\"\n    return lib.get_kernel_peak(WbX, WbY, nchi)\n\n\ndef limber(WbX, WfX, WmX, WbY, WfY, WmY, P, fk, Dk, Bk, xlog, ylog, ell, prefactor):\n    config = c_limber_config()\n    config.xlog = xlog\n    config.ylog = ylog\n    config.n_ell = len(ell)\n    config.ell = np.ctypeslib.as_ctypes(ell)\n    config.prefactor = prefactor\n    config.status = 0\n    spline_ptr = lib.limber_integral(ct.byref(config), WbX, WfX, WmX, WbY, WfY, WmY, P, fk, Dk, Bk)\n    if config.status == LIMBER_STATUS_ZERO:\n        ylog = False\n    elif config.status == LIMBER_STATUS_NEGATIVE:\n        ylog = False\n    spline = GSLSpline(spline_ptr, xlog=xlog, ylog=ylog)\n    return spline\n", "meta": {"hexsha": "69a84289994bbf067a5cbdd3cf1f90ab69d79393", "size": 11718, "ext": "py", "lang": "Python", "max_stars_repo_path": "cosmosis-standard-library/structure/projection/limber.py", "max_stars_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_stars_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-15T10:10:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T10:10:26.000Z", "max_issues_repo_path": "cosmosis-standard-library/structure/projection/limber.py", "max_issues_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_issues_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cosmosis-standard-library/structure/projection/limber.py", "max_forks_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_forks_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-11T15:29:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T15:29:43.000Z", "avg_line_length": 45.2432432432, "max_line_length": 199, "alphanum_fraction": 0.7321215224, "include": true, "reason": "import numpy", "num_tokens": 3560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.18255855615429248}}
{"text": "#!/usr/bin/env python3\n\n\"\"\"Module dedicated to classifying molecules into point groups.\"\"\"\n\n\nfrom __future__ import annotations\n\n__all__ = [\"find_point_group\", \"symmetry_number\"]\n\n\nimport logging\nimport re\n\nimport numpy as np\nfrom scipy.cluster.hierarchy import fcluster, linkage\nfrom scipy.spatial import cKDTree as KDTree\nfrom scipy.spatial.distance import pdist, squareform\nfrom scipy.spatial.transform import Rotation\n\nimport overreact as rx\nfrom overreact import _constants as constants\n\nlogger = logging.getLogger(__name__)\n\n\n# TODO(schneiderfelipe): alpha should depend on temperature?\ndef get_molecular_volume(\n    atomnos,\n    atomcoords,\n    full_output=False,\n    environment=\"water\",\n    method=\"garza\",\n    temperature=298.15,\n    pressure=constants.atm,\n    alpha=1.2,\n    num=250,\n    trials=3,\n):\n    \"\"\"Calculate van der Waals volumes.\n\n    Volume estimation is done through Quasi-Monte Carlo integration. As such,\n    the computed volume is accurate to about two significant figures. This is\n    sufficient to most applications.\n\n    Parameters\n    ----------\n    atomnos : array-like\n    atomcoords : array-like\n    full_output : bool, optional\n        If True, return an estimate of the cavity volume and an estimate on the\n        error as well.\n    method : str, optional\n        This is a placeholder for future functionality.\n        There are plans to implement more sophisticated methods for calculating\n        entropies such as in\n        [*Phys. Chem. Chem. Phys.*, **2019**, 21, 18920-18929](https://doi.org/10.1039/C9CP03226F)\n        and\n        [*J. Chem. Theory Comput.* **2019**, 15, 5, 3204–3214](https://doi.org/10.1021/acs.jctc.9b00214).\n        Head over to the\n        [discussions](https://github.com/geem-lab/overreact/discussions) if\n        you're interested and would like to contribute.\n        Leave this as \"standard\" for now.\n    environment : str, optional\n    temperature : array-like, optional\n        Absolute temperature in Kelvin.\n    pressure : array-like, optional\n        Reference gas pressure.\n    alpha : float, optional\n    num, trials : int, optional\n\n    Returns\n    -------\n    vdw_volume : float\n    cav_volume, err : float, optional\n        Volumes returned are in Å³ per molecule.\n\n    Raises\n    ------\n    ValueError\n        If `method` is not recognized.\n\n    Notes\n    -----\n    For \"izato\", see equation 3 of DOI:10.1039/C9CP03226F for the conceptual\n    details. There is theoretical support for the equation in the work of\n    Eyring (DOI:10.1021/j150380a007).\n\n    Examples\n    --------\n    >>> from overreact import _datasets as datasets\n\n    >>> data = datasets.logfiles[\"symmetries\"][\"dihydrogen\"]\n    >>> get_molecular_volume(data.atomnos, data.atomcoords)\n    8.4\n    >>> get_molecular_volume(data.atomnos, data.atomcoords, method=\"izato\",\n    ...                      full_output=True)\n    (8.4, 13.7, 0.1)\n    >>> get_molecular_volume(data.atomnos, data.atomcoords, full_output=True)\n    (8.4, 61., 0.1)\n\n    >>> data = datasets.logfiles[\"symmetries\"][\"water\"]\n    >>> get_molecular_volume(data.atomnos, data.atomcoords)\n    18.\n    >>> get_molecular_volume(data.atomnos, data.atomcoords, method=\"izato\",\n    ...                      full_output=True)\n    (18., 29., 0.1)\n    >>> get_molecular_volume(data.atomnos, data.atomcoords, full_output=True)\n    (18., 92., 0.1)\n    >>> get_molecular_volume(data.atomnos, data.atomcoords, full_output=True,\n    ...                      environment=\"benzene\")\n    (18., 301., 0.1)\n\n    >>> data = datasets.logfiles[\"symmetries\"][\"benzene\"]\n    >>> get_molecular_volume(data.atomnos, data.atomcoords)\n    80.\n    >>> get_molecular_volume(data.atomnos, data.atomcoords, method=\"izato\",\n    ...                      full_output=True)\n    (80., 115., 0.1)\n    >>> get_molecular_volume(data.atomnos, data.atomcoords, full_output=True)\n    (80., 240., 0.1)\n    >>> get_molecular_volume(data.atomnos, data.atomcoords, full_output=True,\n    ...                      environment=\"benzene\")\n    (80., 593., 0.1)\n    \"\"\"\n    atomnos = np.atleast_1d(atomnos)\n    _, _, atomcoords = inertia(np.ones_like(atomnos), atomcoords)\n    vdw_radii = constants.vdw_radius(atomnos)\n\n    v1 = atomcoords.min(axis=0) - alpha * vdw_radii.max()\n    v2 = atomcoords.max(axis=0) + alpha * vdw_radii.max()\n    box_volume = np.prod(v2 - v1)\n    n = int(num * box_volume)\n\n    vdw_volumes = []\n    if full_output and method == \"izato\":\n        cav_volumes = []\n    for _ in range(trials):\n        points = rx._misc.halton(n, 3)\n        points = v1 + points * (v2 - v1)\n        tree = KDTree(points)\n\n        within_vdw = set()\n        if full_output and method == \"izato\":\n            within_cav = set()\n        for i, atomcoord in enumerate(atomcoords):\n            within_vdw.update(tree.query_ball_point(atomcoord, vdw_radii[i]))\n            if full_output and method == \"izato\":\n                within_cav.update(\n                    tree.query_ball_point(atomcoord, alpha * vdw_radii[i])\n                )\n\n        vdw_volumes.append((len(within_vdw) / n) * box_volume)\n        if full_output and method == \"izato\":\n            cav_volumes.append((len(within_cav) / n) * box_volume)\n\n    vdw_volume = np.mean(vdw_volumes)\n    vdw_err = np.std(vdw_volumes)\n    logger.info(f\"van der Waals volume = {vdw_volume} ± {vdw_err} Å³\")\n    if full_output:\n        if method == \"izato\":\n            cav_volume = np.mean(cav_volumes)\n            cav_err = np.std(cav_volumes)\n            logger.debug(f\"Izato cavity volume = {cav_volume} ± {cav_err} Å³\")\n            return (vdw_volume, cav_volume, max(vdw_err, cav_err))\n        elif method == \"garza\":\n            # TODO(schneiderfelipe): test for the following solvents: water,\n            # pentane, hexane, heptane and octane.\n\n            cav_volume = _garza(\n                vdw_volume, environment, temperature=temperature, pressure=pressure\n            )\n            logger.debug(f\"Garza cavity volume = {cav_volume} Å³\")\n            return (vdw_volume, cav_volume, vdw_err)\n        else:\n            raise ValueError(f\"unavailable method: '{method}'\")\n    return vdw_volume\n\n\ndef _garza(\n    vdw_volume,\n    environment=\"water\",\n    full_output=False,\n    temperature=298.15,\n    pressure=constants.atm,\n):\n    \"\"\"Calculate cavity attributes according to A. Garza.\n\n    This is mainly a helper function for calculating solvation entropy\n    according to DOI:10.1021/acs.jctc.9b00214.\n\n    Parameters\n    ----------\n    vdw_volume : float\n    environment : str, optional\n    full_output : bool, optional\n        If True, return all model estimates.\n    temperature : array-like, optional\n        Absolute temperature in Kelvin.\n    pressure : array-like, optional\n        Reference gas pressure.\n\n    Returns\n    -------\n    cav_volume : float\n    N_cav : float, optional\n    ratio : float, optional\n\n    Examples\n    --------\n    >>> _garza(1.0)\n    24.3195400621484\n    >>> _garza(1.0, full_output=True)\n    (24.3195400621484, 1.81525614083525, 0.3507458151874175)\n    >>> _garza(10.0)\n    66.51277879776\n    >>> _garza(10.0, full_output=True)\n    (66.51277879776, 1.0, 0.755658951623284)\n    >>> _garza(100.0)\n    279.576566152594\n    >>> _garza(100.0, full_output=True)\n    (279.576566152594, 1.0, 1.628017859210329)\n\n    >>> _garza(1.0, environment=\"benzene\")\n    131.\n    >>> _garza(1.0, full_output=True, environment=\"benzene\")\n    (131., 3.35, 0.2317882509934295)\n    >>> _garza(10.0, environment=\"benzene\")\n    243.\n    >>> _garza(10.0, full_output=True, environment=\"benzene\")\n    (243., 3.29, 0.499372648682062)\n    >>> _garza(100.0, environment=\"benzene\")\n    665.\n    >>> _garza(100.0, full_output=True, environment=\"benzene\")\n    (665., 1.0, 1.07586575757374)\n    \"\"\"\n    solvent = rx._misc._get_chemical(environment, temperature, pressure)\n\n    # TODO(schneiderfelipe): things to do:\n    # 1. check correctness of this function,\n    # 2. check it is called correctly everywhere,\n    # 3. transfer the following commented code to get_chemical (it will become\n    # a complete abstraction of the solvent/molecular properties):\n    #\n    # data_S = datasets.logfiles[solvent.name]\n    # solvent_volume = coords.get_molecular_volume(data_S.atomnos,\n    #                                              data_S.atomcoords)\n    solvent_volume = solvent.Van_der_Waals_volume / (\n        constants.angstrom ** 3 * constants.N_A\n    )\n    r_free = np.cbrt(\n        solvent.Vm / (constants.angstrom ** 3 * constants.N_A) - solvent_volume\n    )\n    r_M = np.cbrt(vdw_volume)\n\n    cav_volume = (r_M + r_free) ** 3\n    if not full_output:\n        return cav_volume\n    r_S = np.cbrt(solvent_volume)\n    ratio = r_M / r_S\n\n    area_free = r_free ** 2\n    area_S_total = r_S ** 2 + area_free\n\n    x = max(area_free - r_M ** 2, 0.0) / area_S_total\n    if np.isclose(x, 0.0):\n        return cav_volume, 1.0, ratio\n\n    N_x = 4.0 * np.cbrt(cav_volume) ** 2 / area_S_total\n    return cav_volume, 1.0 + N_x * x / (1.0 - x), ratio\n\n\ndef symmetry_number(point_group):\n    \"\"\"Return rotational symmetry number for point group.\n\n    This function has a set of the most common point groups precomputed, but is\n    able to calculate the symmetry number if it is not found in known tables.\n    Most precomputed values are from\n    [*Theor Chem Account* **2007** 118, 813–826](https://doi.org/10.1007/s00214-007-0328-0).\n\n    Parameters\n    ----------\n    point_group : str\n        Point group symbol.\n\n    Returns\n    -------\n    int\n        Rotational symmetry number.\n\n    Raises\n    ------\n    ValueError\n        If point group is not found in precomputed values.\n\n    Examples\n    --------\n    >>> symmetry_number(\"C4\")\n    4\n    >>> symmetry_number(\"C4\") == symmetry_number(\"C4h\")\n    True\n    >>> symmetry_number(\"C6\")\n    6\n    >>> symmetry_number(\"C6\") == symmetry_number(\"C6v\")\n    True\n    >>> symmetry_number(\"C6\") == symmetry_number(\"C6h\")\n    True\n    >>> symmetry_number(\"D2\") == symmetry_number(\"Vh\")\n    True\n    >>> symmetry_number(\"D4\")\n    8\n    >>> symmetry_number(\"D6\")\n    12\n    >>> symmetry_number(\"D6\") == symmetry_number(\"D6d\")\n    True\n    >>> symmetry_number(\"S6\")\n    3\n    >>> symmetry_number(\"T\")\n    12\n    \"\"\"\n    point_group = point_group.strip().lower()\n\n    if point_group in {\"c1\", \"ci\", \"cs\", \"c∞v\", \"k\", \"r3\"}:\n        symmetry_number = 1\n    elif point_group in {\"c2\", \"c2v\", \"c2h\", \"d∞h\", \"s4\"}:\n        symmetry_number = 2\n    elif point_group in {\"c4\", \"c4v\", \"c4h\", \"d2\", \"d2d\", \"d2h\", \"s8\", \"vh\"}:\n        symmetry_number = 4\n    elif point_group in {\"c12\", \"c12v\", \"c12h\", \"d6\", \"d6d\", \"d6h\", \"s24\", \"t\", \"td\"}:\n        symmetry_number = 12\n    elif point_group in {\"c24\", \"c24v\", \"c24h\", \"d12\", \"d12d\", \"d12h\", \"s48\", \"oh\"}:\n        symmetry_number = 24\n    elif point_group in {\"c60\", \"c60v\", \"c60h\", \"d30\", \"d30d\", \"d30h\", \"s120\", \"ih\"}:\n        symmetry_number = 60\n    else:\n        pieces = re.match(\n            r\"(?P<letter>[^\\s]+)(?P<number>\\d+)(?P<type>[^\\s]+)?\", point_group\n        ).groupdict()\n\n        if pieces[\"letter\"] == \"c\":\n            symmetry_number = int(pieces[\"number\"])\n        elif pieces[\"letter\"] == \"d\":\n            symmetry_number = 2 * int(pieces[\"number\"])\n        elif pieces[\"letter\"] == \"s\":\n            symmetry_number = int(pieces[\"number\"]) // 2\n        else:\n            raise ValueError(f\"unknown point group: '{point_group}'\")\n\n    logger.info(f\"symmetry number = {symmetry_number}\")\n    return symmetry_number\n\n\ndef find_point_group(atommasses, atomcoords, proper_axes=None, rtol=0.0, atol=1.0e-2):\n    \"\"\"Determine point group of structure.\n\n    Parameters\n    ----------\n    atommasses : array-like\n        Atomic masses in atomic mass units (amu).\n    atomcoords : array-like\n        Atomic coordinates.\n    proper_axes : sequence of tuples of int, array-like, optional\n        Proper symmetry axes of rotation.\n    rtol : float, optional\n        The relative tolerance parameter (see `numpy.isclose`).\n    atol : float, optional\n        The absolute tolerance parameter (see `numpy.isclose`).\n\n    Returns\n    -------\n    str\n        Point group symbol.\n\n    Examples\n    --------\n    >>> find_point_group([1], [[0, 0, 1]])\n    'K'\n    >>> find_point_group([1, 1], [[0, 0, 1], [0, 0, 0]])\n    'D∞h'\n    >>> find_point_group([1.008, 35.45], [[0, 0, 1], [0, 0, 0]])\n    'C∞v'\n    >>> find_point_group([16, 12, 16], [[1, 0, 1], [1, 0, 0], [1, 0, -1]])\n    'D∞h'\n    >>> find_point_group([16, 12, 32], [[1, 1, 1], [1, 1, 0], [1, 1, -1]])\n    'C∞v'\n    >>> find_point_group([12, 12, 12, 12], [[1, 0, 0],\n    ...                                     [0, 1, 0],\n    ...                                     [0, 0, 0],\n    ...                                     [1, 1, 0]])\n    'D4h'\n\n    \"\"\"\n    if len(atommasses) == 1:  # atom\n        point_group = \"K\"\n    elif len(atommasses) == 2:  # diatomic molecule\n        if atommasses[0] == atommasses[1]:\n            point_group = \"D∞h\"\n        else:\n            point_group = \"C∞v\"\n    else:\n        groups = _equivalent_atoms(atommasses, atomcoords)\n        moments, axes, atomcoords = inertia(atommasses, atomcoords)\n        rotor_class = _classify_rotor(moments)\n\n        if rotor_class[1] == \"linear\":\n            point_group = _find_point_group_linear(\n                atomcoords, groups, rtol=rtol, atol=atol\n            )\n        else:\n            if proper_axes is None:\n                proper_axes = _get_proper_axes(\n                    atomcoords, groups, axes, rotor_class, rtol=rtol, atol=atol\n                )\n\n            if rotor_class[0] == \"asymmetric\" or not proper_axes:\n                point_group = _find_point_group_asymmetric(\n                    atomcoords,\n                    groups,\n                    axes,\n                    rotor_class,\n                    proper_axes,\n                    rtol=rtol,\n                    atol=atol,\n                )\n            elif rotor_class[0] == \"spheric\":\n                point_group = _find_point_group_spheric(\n                    atomcoords,\n                    groups,\n                    axes,\n                    rotor_class,\n                    proper_axes,\n                    rtol=rtol,\n                    atol=atol,\n                )\n            else:  # symmetric\n                point_group = _find_point_group_symmetric(\n                    atomcoords,\n                    groups,\n                    axes,\n                    rotor_class,\n                    proper_axes,\n                    rtol=rtol,\n                    atol=atol,\n                )\n\n    logger.info(f\"point group = {point_group}\")\n    return point_group\n\n\ndef _find_point_group_linear(atomcoords, groups, rtol=0.0, atol=1.0e-2):\n    \"\"\"Find point group for linear rotors.\n\n    Point groups searched for are: D∞h, C∞v.\n\n    See find_point_group for information on parameters and return values.\n    \"\"\"\n    if _has_inversion_center(atomcoords, groups, rtol=rtol, atol=atol):\n        return \"D∞h\"\n    else:\n        return \"C∞v\"\n\n\ndef _find_point_group_spheric(\n    atomcoords, groups, axes, rotor_class, proper_axes=None, rtol=0.0, atol=1.0e-2\n):\n    \"\"\"Find point group for spheric tops.\n\n    Point groups searched for are: Td, Oh, Ih.\n    I might eventually search for T, Th, O in the future.\n\n    See find_point_group for information on parameters and return values.\n    \"\"\"\n    if not _has_inversion_center(atomcoords, groups, rtol=rtol, atol=atol):\n        return \"Td\"\n\n    if proper_axes is None:\n        proper_axes = _get_proper_axes(\n            atomcoords, groups, axes, rotor_class, rtol=rtol, atol=atol\n        )\n\n    for n, _ in proper_axes:\n        if n == 5:\n            return \"Ih\"\n        elif n < 5:\n            break\n    return \"Oh\"\n\n    # see https://www.chem.uci.edu/~lawm/9-28.pdf for more about high\n    # symmetry groups\n    # see too\n    # http://web.mit.edu/5.03/www/readings/point_groups/point_groups.pdf\n\n    # the following workflow is loosely inspired by some articles:\n    # 1. DOI:10.1016/0097-8485(76)80004-6\n    #     elif _has_3_C4(atomcoords):\n    #         if _has_center_of_inversion(atomcoords):\n    #             return \"oh\"\n    #         else:\n    #             return \"o\"\n    #     elif _has_3_S4_parallel_to_C2(atomcoords):\n    #         return \"td\"\n    #     elif _has_center_of_inversion(atomcoords):\n    #         return \"th\"\n    #     else:\n    #         return \"t\"\n\n\ndef _find_point_group_asymmetric(\n    atomcoords, groups, axes, rotor_class, proper_axes=None, rtol=0.0, atol=1.0e-2\n):\n    \"\"\"Find point group for asymmetric tops.\n\n    Point groups searched for here are: C1, Ci, Cs.\n    Point groups delegated are: Cn, Cnh, Cnv, Dn, Dnh, Dnd, Sn.\n\n    See find_point_group for information on parameters and return values.\n    \"\"\"\n    if proper_axes is None:\n        proper_axes = _get_proper_axes(\n            atomcoords, groups, axes, rotor_class, rtol=rtol, atol=atol\n        )\n\n    if proper_axes:\n        return _find_point_group_symmetric(\n            atomcoords, groups, axes, rotor_class, proper_axes, rtol=rtol, atol=atol\n        )\n    elif rotor_class[1] in {\"regular planar\", \"irregular planar\"} or _get_mirror_planes(\n        atomcoords, groups, axes, rotor_class, proper_axes, rtol=rtol, atol=atol\n    ):\n        return \"Cs\"\n    elif _has_inversion_center(atomcoords, groups, rtol=rtol, atol=atol):\n        return \"Ci\"\n    return \"C1\"\n\n\ndef _find_point_group_symmetric(\n    atomcoords, groups, axes, rotor_class, proper_axes=None, rtol=0.0, atol=1.0e-2\n):\n    \"\"\"Find point group for symmetric tops.\n\n    Point groups delegated are: Cn, Cnh, Cnv, Dn, Dnh, Dnd, Sn.\n\n    See find_point_group for information on parameters and return values.\n    \"\"\"\n    if proper_axes is None:\n        proper_axes = _get_proper_axes(\n            atomcoords, groups, axes, rotor_class, rtol=rtol, atol=atol\n        )\n    n_principal = proper_axes[0][0]\n\n    count_twofold = 0\n    for n, _ in proper_axes:\n        if n == 2:\n            count_twofold += 1\n        if n_principal == count_twofold:\n            return _find_point_group_symmetric_dihedral(\n                atomcoords, groups, axes, rotor_class, proper_axes, rtol=rtol, atol=atol\n            )\n        if n < 2:\n            break\n    return _find_point_group_symmetric_nondihedral(\n        atomcoords, groups, axes, rotor_class, proper_axes, rtol=rtol, atol=atol\n    )\n\n    # the following workflow is loosely inspired by some articles:\n    # 1. DOI:10.1016/0097-8485(76)80004-6\n    # if _has_proper_ax_of_highest_order(atomcoords):\n    #     if _has_proper_ax_larger_than_2_or_3_C2_perpendicular(\n    #         atomcoords\n    #     ):\n    #         if _has_S2n_parallel_to_Cn(atomcoords):\n    #             if _has_n_sigma_d(atomcoords):\n    #                 return \"dnd\"\n    #             else:\n    #                 return \"s2n\"\n    #         elif _has_nC2_perpendicular_to_Cn(atomcoords):\n    #             if _has_sigma_h(atomcoords):\n    #                 return \"dnh\"\n    #             else:\n    #                 return \"dn\"\n    #         elif _has_n_sigma_v(atomcoords):\n    #             return \"cnv\"\n    #         elif _has_sigma_h(atomcoords):\n    #             return \"cnh\"\n    #         else:\n    #             return \"cn\"\n\n\ndef _find_point_group_symmetric_dihedral(\n    atomcoords, groups, axes, rotor_class, proper_axes=None, rtol=0.0, atol=1.0e-2\n):\n    \"\"\"Find a dihedral point group for symmetric tops.\n\n    Point groups searched for are: Dn, Dnh, Dnd.\n\n    See find_point_group for information on parameters and return values.\n    \"\"\"\n    if proper_axes is None:\n        proper_axes = _get_proper_axes(\n            atomcoords, groups, axes, rotor_class, rtol=rtol, atol=atol\n        )\n    mirror_axes = _get_mirror_planes(\n        atomcoords, groups, axes, rotor_class, proper_axes, rtol=rtol, atol=atol\n    )\n\n    if mirror_axes:\n        if mirror_axes[0][0] == \"h\":\n            return f\"D{proper_axes[0][0]}h\"\n        elif len([v for c, v in mirror_axes if c == \"v\"]) == proper_axes[0][0]:\n            # all vertical mirror planes are dihedral for Dnd point groups\n            return f\"D{proper_axes[0][0]}d\"\n    return f\"D{proper_axes[0][0]}\"\n\n\ndef _find_point_group_symmetric_nondihedral(\n    atomcoords, groups, axes, rotor_class, proper_axes=None, rtol=0.0, atol=1.0e-2\n):\n    \"\"\"Find a nondihedral point group for symmetric tops.\n\n    Point groups searched for are: Cn, Cnh, Cnv, Sn.\n\n    See find_point_group for information on parameters and return values.\n    \"\"\"\n    if proper_axes is None:\n        proper_axes = _get_proper_axes(\n            atomcoords, groups, axes, rotor_class, rtol=rtol, atol=atol\n        )\n    mirror_axes = _get_mirror_planes(\n        atomcoords, groups, axes, rotor_class, proper_axes, rtol=rtol, atol=atol\n    )\n\n    if mirror_axes:\n        if mirror_axes[0][0] == \"h\":\n            return f\"C{proper_axes[0][0]}h\"\n        elif len([v for c, v in mirror_axes if c == \"v\"]) == proper_axes[0][0]:\n            return f\"C{proper_axes[0][0]}v\"\n\n    improper_axes = _get_improper_axes(\n        atomcoords, groups, axes, rotor_class, proper_axes, rtol=rtol, atol=atol\n    )\n    if improper_axes:\n        return f\"S{improper_axes[0][0]}\"\n    return f\"C{proper_axes[0][0]}\"\n\n\ndef _update_proper_axes(\n    ax,\n    axes,  # found axes\n    atomcoords,\n    groups,\n    orders,\n    rtol,\n    atol,\n    nondeg_axes=None,\n    normalize=False,\n):\n    \"\"\"Update axes with ax, and return it with added order (or None).\n\n    Helper function for _get_proper_axes.\n    \"\"\"\n    if nondeg_axes is None:\n        nondeg_axes = list()\n\n    if normalize:\n        norm = np.linalg.norm(ax)\n        if np.isclose(norm, 0.0, rtol=rtol, atol=atol):\n            return axes, None\n        ax = ax / norm\n\n    if not all(\n        np.isclose(ax @ v, 0.0, rtol=rtol, atol=atol) for v in nondeg_axes\n    ) or any(np.isclose(np.abs(ax @ v), 1.0, rtol=rtol, atol=atol) for o, v in axes):\n        return axes, None\n\n    for order in orders[::-1]:\n        if all(\n            _is_symmetric(\n                atomcoords[group],\n                _operation(\"c\", order=order, axis=ax),\n                rtol=rtol,\n                atol=atol,\n            )\n            for group in groups[::-1]\n        ):\n            axes.append((order, tuple(ax)))\n            return axes, order\n\n    return axes, None\n\n\ndef _get_proper_axes(\n    atomcoords, groups, axes, rotor_class, rtol=0.0, atol=1.0e-2, slack=0.735\n):\n    \"\"\"Get proper symmetry axes and their orders.\n\n    Parameters\n    ----------\n    atomcoords : array-like\n        Atomic coordinates centered at the center of mass.\n    groups : sequence of sequence of int\n        Groups of symmetry equivalent atoms, in ascending order of size.\n    axes : array-like\n        Normalized principal axes of inertia.\n    rotor_class : tuple of str\n        Rigid rotor classification.\n    rtol : float, optional\n        The relative tolerance parameter (see `numpy.isclose`).\n    atol : float, optional\n        The absolute tolerance parameter (see `numpy.isclose`).\n    slack : float, optional\n        Number to multiply rtol and atol prior comparisons.\n\n    Returns\n    -------\n    sequence of tuples of int, array-like\n        Ordered sequence of tuples in the format ``(order, (x, y, z))``.\n\n    Notes\n    -----\n    This function has some limitations. First, no C1 axis is never returned.\n    Second, an empty list is returned if the structure has a single atom. And\n    third, the largest symmetry axis found has order not greater than the\n    maximum number of symmetry equivalent atoms, which particularly impacts\n    linear rotors (for instance, the largest axis found for the hydrogen\n    molecule is twofold, while no axis is found for hydrogen chloride).\n    Furthermore, linear rotors are considered symmetric prolate tops, which\n    means a single axis is returned (no perpendicular axes). Either way, this\n    should be of little impact, as only cases whose groups can easily be\n    inferred with no or little knowledge of symmetry axis are affected.\n\n    Examples\n    --------\n    >>> from overreact import _datasets as datasets\n\n    >>> data = datasets.logfiles[\"symmetries\"][\"diborane\"]\n    >>> groups = _equivalent_atoms(data.atommasses, data.atomcoords)\n    >>> moments, axes, atomcoords = inertia(data.atommasses, data.atomcoords)\n    >>> rotor_class = _classify_rotor(moments)\n    >>> _get_proper_axes(atomcoords, groups, axes, rotor_class)\n    [(2, (1.0, ...)),\n     (2, (...)),\n     (2, (...))]\n    \"\"\"\n    rtol, atol = slack * rtol, slack * atol\n\n    if rotor_class[1] == \"atomic\" or len(atomcoords) == 1:\n        return list()\n\n    axes = np.asarray(axes)\n    atomcoords = np.asarray(atomcoords)\n    orders = _guess_orders(groups, rotor_class)\n\n    found_axes = list()\n    nondeg_axes = list()\n    if rotor_class[0] == \"symmetric prolate\":\n        nondeg_axes = [axes[:, 0]]\n        found_axes, order = _update_proper_axes(\n            axes[:, 0],\n            found_axes,\n            atomcoords=atomcoords,\n            groups=groups,\n            orders=orders,\n            rtol=rtol,\n            atol=atol,\n        )\n    elif rotor_class[0] == \"symmetric oblate\":\n        nondeg_axes = [axes[:, 2]]\n        found_axes, order = _update_proper_axes(\n            axes[:, 2],\n            found_axes,\n            atomcoords=atomcoords,\n            groups=groups,\n            orders=orders,\n            rtol=rtol,\n            atol=atol,\n        )\n    elif rotor_class[0] == \"asymmetric\":\n        for ax in axes.T:\n            found_axes, order = _update_proper_axes(\n                ax,\n                found_axes,\n                atomcoords=atomcoords,\n                groups=groups,\n                orders=orders,\n                rtol=rtol,\n                atol=atol,\n            )\n        return sorted(found_axes, reverse=True)\n\n    for group in groups:\n        for i, a in enumerate(group):\n            through_ax = atomcoords[a]\n            found_axes, order = _update_proper_axes(\n                through_ax,\n                found_axes,\n                atomcoords=atomcoords,\n                groups=groups,\n                orders=orders,\n                rtol=rtol,\n                atol=atol,\n                nondeg_axes=nondeg_axes,\n                normalize=True,\n            )\n            if rotor_class[0] == \"spheric\" and order == 5:\n                return sorted(found_axes, reverse=True)\n\n            for b in group[:i]:\n                midpoint_ax = atomcoords[a] + atomcoords[b]\n                found_axes, order = _update_proper_axes(\n                    midpoint_ax,\n                    found_axes,\n                    atomcoords=atomcoords,\n                    groups=groups,\n                    orders=orders,\n                    rtol=rtol,\n                    atol=atol,\n                    nondeg_axes=nondeg_axes,\n                    normalize=True,\n                )\n                if rotor_class[0] == \"spheric\" and order == 5:\n                    return sorted(found_axes, reverse=True)\n\n    if rotor_class[0] == \"spheric\":\n        twofold_axes = [ax for o, ax in found_axes if o == 2]\n        for i, ax_a in enumerate(twofold_axes):\n            for ax_b in twofold_axes[:i]:\n                ax = np.cross(ax_a, ax_b)\n                found_axes, order = _update_proper_axes(\n                    ax,\n                    found_axes,\n                    atomcoords=atomcoords,\n                    groups=groups,\n                    orders=orders,\n                    rtol=rtol,\n                    atol=atol,\n                    nondeg_axes=nondeg_axes,\n                    normalize=True,\n                )\n                if order == 5:\n                    return sorted(found_axes, reverse=True)\n\n    return sorted(found_axes, reverse=True)\n\n\ndef _guess_orders(groups, rotor_class):\n    \"\"\"Guess possible group orders based on groups.\n\n    The guess consists of the numbers two to n, where n is the number of\n    elements in the largest group. For cubic groups, n is taken to be at most\n    five. The trivial order one is never guessed.\n\n    Parameters\n    ----------\n    groups : sequence of sequence of int\n        Groups of symmetry equivalent atoms, in ascending order of size.\n    rotor_class : tuple of str\n        Rigid rotor classification.\n\n    Returns\n    -------\n    sequence of int\n\n    Examples\n    --------\n    >>> _guess_orders([[0], [1, 2, 3, 4], [5, 6, 7, 8]],\n    ...               (\"symmetric prolate\", \"nonplanar\"))\n    range(2, 5)\n    >>> _guess_orders([[0], [1, 2, 3, 4], [5, 6, 7, 8]],\n    ...               (\"spheric\", \"nonplanar\"))\n    range(2, 5)\n    >>> _guess_orders([[0], [1, 2, 3, 4], [5, 6, 7, 8, 9, 10]],\n    ...               (\"symmetric prolate\", \"nonplanar\"))\n    range(2, 7)\n    >>> _guess_orders([[0], [1, 2, 3, 4], [5, 6, 7, 8, 9, 10]],\n    ...               (\"spheric\", \"nonplanar\"))\n    range(2, 6)\n    \"\"\"\n    max_order = len(groups[-1])\n    if rotor_class[0] == \"spheric\":\n        max_order = min(max_order, 5)\n    return range(2, max_order + 1)\n\n\ndef _update_improper_axes(\n    n, ax, axes, atomcoords, groups, rtol, atol, normalize=False  # found axes\n):\n    \"\"\"Update axes with ax and return it.\n\n    Helper function for _get_improper_axes.\n    \"\"\"\n    if normalize:\n        norm = np.linalg.norm(ax)\n        if np.isclose(norm, 0.0, rtol=rtol, atol=atol):\n            return axes\n        ax = ax / norm\n\n    for order in [2 * n, n]:\n        if all(\n            _is_symmetric(\n                atomcoords[group],\n                _operation(\"s\", order=order, axis=ax),\n                rtol=rtol,\n                atol=atol,\n            )\n            for group in groups[::-1]\n        ):\n            axes.append((order, tuple(ax)))\n            break\n\n    return axes\n\n\ndef _get_improper_axes(\n    atomcoords,\n    groups,\n    axes,\n    rotor_class,\n    proper_axes=None,\n    rtol=0.0,\n    atol=1.0e-2,\n    slack=1.888,\n):\n    \"\"\"Get improper symmetry axes and their orders.\n\n    Parameters\n    ----------\n    atomcoords : array-like\n        Atomic coordinates centered at the center of mass.\n    groups : sequence of sequence of int\n        Groups of symmetry equivalent atoms, in ascending order of size.\n    axes : array-like\n        Normalized principal axes of inertia.\n    rotor_class : tuple of str\n        Rigid rotor classification.\n    proper_axes : sequence of tuples of int, array-like, optional\n        Proper symmetry axes of rotation.\n    rtol : float, optional\n        The relative tolerance parameter (see `numpy.isclose`).\n    atol : float, optional\n        The absolute tolerance parameter (see `numpy.isclose`).\n    slack : float, optional\n        Number to multiply rtol and atol prior comparisons.\n\n    Returns\n    -------\n    sequence of tuples of int, array-like\n\n    Examples\n    --------\n    >>> from overreact import _datasets as datasets\n\n    >>> data = datasets.logfiles[\"tanaka1996\"][\"methane@UMP2/cc-pVTZ\"]\n    >>> groups = _equivalent_atoms(data.atommasses, data.atomcoords)\n    >>> moments, axes, atomcoords = inertia(data.atommasses, data.atomcoords)\n    >>> rotor_class = _classify_rotor(moments)\n    >>> _get_improper_axes(atomcoords, groups, axes, rotor_class)\n    [(4, (0.0, 0.0, -1.0)),\n     (4, (0.0, -1.0, 0.0)),\n     (4, (-1.0, 0.0, 0.0))]\n    \"\"\"\n    rtol, atol = slack * rtol, slack * atol\n\n    if rotor_class[1] == \"atomic\" or len(atomcoords) == 1:\n        return list()\n\n    axes = np.asarray(axes)\n    atomcoords = np.asarray(atomcoords)\n\n    if proper_axes is None:\n        proper_axes = _get_proper_axes(\n            atomcoords, groups, axes, rotor_class, rtol=rtol, atol=atol\n        )\n\n    found_axes = list()\n    for n, ax in proper_axes:\n        found_axes = _update_improper_axes(\n            n,\n            ax,\n            found_axes,\n            atomcoords=atomcoords,\n            groups=groups,\n            rtol=rtol,\n            atol=atol,\n        )\n    return sorted(found_axes, reverse=True)\n\n\ndef _update_mirror_axes(\n    ax,\n    axes,  # found axes\n    atomcoords,\n    groups,\n    rtol,\n    atol,\n    proper_axes,\n    nondeg_axes=None,\n    normalize=False,\n):\n    \"\"\"Update axes with ax and return it.\n\n    Helper function for _get_mirror_planes.\n    \"\"\"\n    if nondeg_axes is None:\n        nondeg_axes = list()\n\n    if normalize:\n        norm = np.linalg.norm(ax)\n        if np.isclose(norm, 0.0, rtol=rtol, atol=atol):\n            return axes\n        ax = ax / norm\n\n    if not all(\n        np.isclose(ax @ v, 0.0, rtol=rtol, atol=atol) for v in nondeg_axes\n    ) or any(np.isclose(np.abs(ax @ v), 1.0, rtol=rtol, atol=atol) for c, v in axes):\n        return axes\n\n    if all(\n        _is_symmetric(atomcoords[group], _operation(\"σ\", axis=ax), rtol=rtol, atol=atol)\n        for group in groups[::-1]\n    ):\n        class_ = \"\"\n        if any(\n            np.isclose(np.abs(ax @ v), 1.0, rtol=rtol, atol=atol)\n            for n, v in proper_axes\n            if proper_axes[0][0] == n\n        ):\n            class_ = \"h\"\n        elif any(\n            np.isclose(ax @ v, 0.0, rtol=rtol, atol=atol)\n            for n, v in proper_axes\n            if proper_axes[0][0] == n\n        ):\n            class_ = \"v\"\n        axes.append((class_, tuple(ax)))\n\n    return axes\n\n\ndef _get_mirror_planes(\n    atomcoords,\n    groups,\n    axes,\n    rotor_class,\n    proper_axes=None,\n    rtol=0.0,\n    atol=1.0e-2,\n    slack=2.020,\n):\n    \"\"\"Get (and attempt to classify) mirror plane normal axes.\n\n    Parameters\n    ----------\n    atomcoords : array-like\n        Atomic coordinates centered at the center of mass.\n    groups : sequence of sequence of int\n        Groups of symmetry equivalent atoms, in ascending order of size.\n    axes : array-like\n        Normalized principal axes of inertia.\n    rotor_class : tuple of str\n        Rigid rotor classification.\n    proper_axes : sequence of tuples of int, array-like, optional\n        Proper symmetry axes of rotation.\n    rtol : float, optional\n        The relative tolerance parameter (see `numpy.isclose`).\n    atol : float, optional\n        The absolute tolerance parameter (see `numpy.isclose`).\n    slack : float, optional\n        Number to multiply rtol and atol prior comparisons.\n\n    Returns\n    -------\n    sequence of tuples of str, array-like\n\n    Notes\n    -----\n    This function only classifies horizontal and vertical planes. Besides,\n    horizontal classification always takes precedence. Unclassified planes are\n    associated with an empty string. This is all that is needed for point group\n    classification.\n\n    This function has some limitations. First, an empty list is always returned\n    if the structure has a single atom. Second, an empty list is returned for\n    C∞v as well. And third, since classifications are made against proper\n    symmetry axes, no classification can be made for point groups having no\n    proper symmetry axes (e.g., the mirror plane in Cs is not classified).\n\n    This should be of little impact, as only cases whose groups can easily be\n    inferred with no or little knowledge of mirror planes are affected.\n\n    Examples\n    --------\n    >>> from overreact import _datasets as datasets\n\n    >>> data = datasets.logfiles[\"symmetries\"][\"1-iodo-2-chloroethylene\"]\n    >>> groups = _equivalent_atoms(data.atommasses, data.atomcoords)\n    >>> moments, axes, atomcoords = inertia(data.atommasses, data.atomcoords)\n    >>> rotor_class = _classify_rotor(moments)\n    >>> _get_mirror_planes(atomcoords, groups, axes, rotor_class)\n    [('', (0.0, 0.0, 1.0))]\n    \"\"\"\n    rtol, atol = slack * rtol, slack * atol\n\n    if rotor_class[1] == \"atomic\" or len(atomcoords) == 1:\n        return list()\n\n    axes = np.asarray(axes)\n    atomcoords = np.asarray(atomcoords)\n\n    if proper_axes is None:\n        proper_axes = _get_proper_axes(\n            atomcoords, groups, axes, rotor_class, rtol=rtol, atol=atol\n        )\n\n    def _kf(x):\n        \"\"\"Order function for returned list.\"\"\"\n        c, v = x\n        if c:\n            return -ord(c), v\n        else:\n            return 0, v\n\n    found_axes = list()\n    nondeg_axes = list()\n    if rotor_class[0] == \"symmetric prolate\":\n        nondeg_axes = [axes[:, 0]]\n        found_axes = _update_mirror_axes(\n            axes[:, 0],\n            found_axes,\n            atomcoords=atomcoords,\n            groups=groups,\n            rtol=rtol,\n            atol=atol,\n            proper_axes=proper_axes,\n        )\n    elif rotor_class[0] == \"symmetric oblate\":\n        nondeg_axes = [axes[:, 2]]\n        found_axes = _update_mirror_axes(\n            axes[:, 2],\n            found_axes,\n            atomcoords=atomcoords,\n            groups=groups,\n            rtol=rtol,\n            atol=atol,\n            proper_axes=proper_axes,\n        )\n    elif rotor_class[0] == \"asymmetric\":\n        for ax in axes.T:\n            found_axes = _update_mirror_axes(\n                ax,\n                found_axes,\n                atomcoords=atomcoords,\n                groups=groups,\n                rtol=rtol,\n                atol=atol,\n                proper_axes=proper_axes,\n            )\n        return sorted(found_axes, reverse=True, key=_kf)\n\n    for group in groups:\n        for i, a in enumerate(group):\n            for b in group[:i]:\n                ab_ax = atomcoords[b] - atomcoords[a]\n                found_axes = _update_mirror_axes(\n                    ab_ax,\n                    found_axes,\n                    atomcoords=atomcoords,\n                    groups=groups,\n                    rtol=rtol,\n                    atol=atol,\n                    proper_axes=proper_axes,\n                    nondeg_axes=nondeg_axes,\n                    normalize=True,\n                )\n\n    return sorted(found_axes, reverse=True, key=_kf)\n\n\ndef _has_inversion_center(atomcoords, groups, rtol=0.0, atol=1.0e-2, slack=1.888):\n    \"\"\"Check whether the molecule has an inversion center.\n\n    Parameters\n    ----------\n    atomcoords : array-like\n        Atomic coordinates centered at the center of mass.\n    groups : sequence of sequence of int\n        Groups of symmetry equivalent atoms, in ascending order of size.\n    rtol : float, optional\n        The relative tolerance parameter (see `numpy.isclose`).\n    atol : float, optional\n        The absolute tolerance parameter (see `numpy.isclose`).\n    slack : float, optional\n        Number to multiply rtol and atol prior comparisons.\n\n    Returns\n    -------\n    bool\n\n    Examples\n    --------\n    >>> _has_inversion_center([[0, 0, -1], [0, 0, 1]], [[0, 1]])\n    True\n    >>> _has_inversion_center([[0, 0, -1],\n    ...                        [0, 0,  1],\n    ...                        [1, 1,  1]], [[0, 1], [2]])\n    False\n    \"\"\"\n    rtol, atol = slack * rtol, slack * atol\n\n    atomcoords = np.asarray(atomcoords)\n    return all(\n        _is_symmetric(atomcoords[group], _operation(\"i\"), rtol=rtol, atol=atol)\n        for group in groups[::-1]\n    )\n\n\ndef _is_symmetric(atomcoords, op, rtol=0.0, atol=1.0e-2, slack=10.256):\n    \"\"\"Check if structure satisfies symmetry.\n\n    Parameters\n    ----------\n    atomcoords : array-like\n        Atomic coordinates centered at the center of mass.\n    op : array-like\n        Symmetry operator matrix.\n    rtol : float, optional\n        The relative tolerance parameter (see `numpy.isclose`).\n    atol : float, optional\n        The absolute tolerance parameter (see `numpy.isclose`).\n    slack : float, optional\n        Number to multiply rtol and atol prior comparisons.\n\n    Returns\n    -------\n    bool\n\n    Examples\n    --------\n    >>> _is_symmetric([[1, 0, 0],\n    ...               [0, 1, 0],\n    ...               [0, 0, 0]], _operation(\"c\", order=4, axis=[0, 0, 1]))\n    False\n    >>> _is_symmetric([[1, 0, 0],\n    ...               [0, 1, 0],\n    ...               [0, 0, 0]], _operation(\"c\", order=2, axis=[1, 1, 0]))\n    True\n    >>> _is_symmetric([[1, 0, 0],\n    ...               [0, 1, 0],\n    ...               [0, 0, 0]], _operation(\"sigma\", axis=[0, 0, 1]))\n    True\n    >>> _is_symmetric([[1, 0, 0],\n    ...               [0, 1, 0],\n    ...               [0, 0, 0],\n    ...               [-1, 0, 0]], _operation(\"c\", order=4, axis=[0, 0, 1]))\n    False\n    >>> _is_symmetric([[1, 0, 0],\n    ...               [0, 1, 0],\n    ...               [0, 0, 0],\n    ...               [-1, 0, 0]], _operation(\"sigma\", axis=[1, 0, 0]))\n    True\n    >>> _is_symmetric([[1, 0, 0],\n    ...               [0, 1, 0],\n    ...               [0, 0, 0],\n    ...               [-1, 0, 0],\n    ...               [0, -1, 0]], _operation(\"c\", order=4, axis=[0, 0, 1]))\n    True\n    >>> _is_symmetric([[1, 0, 0],\n    ...               [0, 1, 0],\n    ...               [0, 0, 0],\n    ...               [-1, 0, 0],\n    ...               [0, -1, 0]], _operation(\"i\"))\n    True\n    \"\"\"\n    rtol, atol = slack * rtol, slack * atol\n    inner_slack = 1.055\n\n    tree = KDTree(atomcoords)\n    d, i = tree.query(atomcoords @ op.T)\n\n    return (\n        set(i) == set(range(len(atomcoords)))\n        and np.allclose(d.mean(), 0.0, rtol=rtol, atol=atol)\n        and np.allclose(d.max(), 0.0, rtol=inner_slack * rtol, atol=inner_slack * atol)\n    )\n\n\ndef _operation(name, order=2, axis=None):\n    \"\"\"Calculate a symmetry _operation.\n\n    Parameters\n    ----------\n    name : str\n        Operation symbol (see examples below).\n    order : int, optional\n        Operation order.\n    axis : array-like, optional\n        Operation axis.\n\n    Returns\n    -------\n    array-like\n\n    Raises\n    ------\n    ValueError\n        If the operation is not recognized.\n\n    Examples\n    --------\n    >>> _operation(\"e\")\n    array([[1., 0., 0.],\n           [0., 1., 0.],\n           [0., 0., 1.]])\n    >>> _operation(\"i\")\n    array([[-1., -0., -0.],\n           [-0., -1., -0.],\n           [-0., -0., -1.]])\n    >>> _operation(\"c\", order=4, axis=[0, 0, 1])\n    array([[ 0., -1., 0.],\n           [ 1.,  0., 0.],\n           [ 0.,  0., 1.]])\n    >>> _operation(\"σ\", axis=[0, 0, 1])\n    array([[ 1., 0.,  0.],\n           [ 0., 1.,  0.],\n           [ 0., 0., -1.]])\n    >>> _operation(\"σ\", axis=[0, 1, 0])\n    array([[ 1.,  0., 0.],\n           [ 0., -1., 0.],\n           [ 0.,  0., 1.]])\n    >>> _operation(\"σ\", axis=[1, 0, 0])\n    array([[-1., 0., 0.],\n           [ 0., 1., 0.],\n           [ 0., 0., 1.]])\n    >>> _operation(\"s\", order=4, axis=[0, 0, 1])\n    array([[ 0., -1.,  0.],\n           [ 1.,  0.,  0.],\n           [ 0.,  0., -1.]])\n    >>> _operation(\"s\", order=4, axis=[0, 1, 0])\n    array([[ 0.,  0., 1.],\n           [ 0., -1., 0.],\n           [-1.,  0., 0.]])\n    >>> _operation(\"s\", order=4, axis=[1, 0, 0])\n    array([[-1., 0.,  0.],\n           [ 0., 0., -1.],\n           [ 0., 1.,  0.]])\n    \"\"\"\n    if axis is None:\n        axis = np.array([0, 0, 1])\n\n    if name == \"i\":\n        return -np.eye(3)\n    elif name == \"e\":\n        return np.eye(3)\n    elif name in {\"c\", \"σ\", \"sigma\", \"s\"}:  # normalize axis\n        axis = np.asarray(axis)\n        axis = axis / np.linalg.norm(axis)\n\n        if name in {\"c\", \"s\"}:\n            rotation = Rotation.from_rotvec(2.0 * np.pi * axis / order).as_matrix()\n        if name in {\"σ\", \"sigma\", \"s\"}:\n            reflection = np.eye(3) - 2.0 * np.outer(axis, axis)\n        if name == \"c\":\n            return rotation\n        elif name in {\"σ\", \"sigma\"}:\n            return reflection\n        elif name == \"s\":\n            return rotation @ reflection\n    raise ValueError(f\"unknown operation: '{name}'\")\n\n\ndef _classify_rotor(moments, rtol=0.0, atol=1.0e-2, slack=0.870):\n    \"\"\"Classify rotors based on moments of inertia.\n\n    See DOI:10.1002/jcc.23493.\n\n    Parameters\n    ----------\n    moments : array-like\n        Primary moments of inertia in ascending order. Units are in amu·Å².\n    rtol : float, optional\n        The relative tolerance parameter (see `numpy.isclose`).\n    atol : float, optional\n        The absolute tolerance parameter (see `numpy.isclose`).\n    slack : float, optional\n        Number to multiply rtol and atol prior comparisons.\n\n    Return\n    ------\n    top, shape : str\n\n    Notes\n    -----\n    Moments are actually compared by their ratios such that the \"aspect ratio\"\n    of the molecule is what is compared.\n\n    Examples\n    --------\n    Do examples from\n    <https://www.tau.ac.il/~tsirel/dump/Static/knowino.org/wiki/Classification_of_rigid_rotors.html>.\n\n    The idea behind this function is, among other things, to help in\n    classifying point groups. For instance, there are the following\n    possibilities for atoms or linear molecules:\n\n    >>> _classify_rotor([0, 0, 0])\n    ('spheric', 'atomic')\n    >>> _classify_rotor([0, 1, 1])\n    ('symmetric prolate', 'linear')\n\n    Spheric tops can be any cubic group:\n\n    >>> _classify_rotor([1, 1, 1])\n    ('spheric', 'nonplanar')\n\n    Asymmetric tops can be a lot of different groups, the ones lacking proper\n    axis of symmetry (C1, Ci, Cs) being exclusively found in asymmetric tops.\n    Furthermore, any group found for symmetric tops can be found for asymmetric\n    tops as well, which complicates things a bit.\n\n    >>> _classify_rotor([1, 2, 4])\n    ('asymmetric', 'nonplanar')\n\n    Symmetric tops can be found in a subset of the ones found in asymmetric\n    tops and they always have a proper axis of symmetry. I further classify\n    them here into smaller groups (I believe that this subclassification and\n    its relationship with possible point groups can be further improved). For\n    instance, planar symmetric tops are always oblate and have a plane of\n    symmetry:\n\n    >>> _classify_rotor([1, 1, 2])\n    ('symmetric oblate', 'regular planar')\n\n    >>> _classify_rotor([1, 3, 4])\n    ('asymmetric', 'irregular planar')\n\n    >>> _classify_rotor([1, 1, 3])\n    ('symmetric oblate', 'nonplanar')\n\n    >>> _classify_rotor([1, 2, 2])\n    ('symmetric prolate', 'nonplanar')\n    \"\"\"\n    rtol, atol = slack * rtol, slack * atol\n    inner_slack = 2.130\n\n    if np.isclose(moments[2], 0.0, rtol=inner_slack * rtol, atol=inner_slack * atol):\n        return \"spheric\", \"atomic\"\n    moments = np.asarray(moments) / moments[2]\n\n    # basic tests for tops\n    is_oblate = np.isclose(\n        moments[0], moments[1], rtol=inner_slack * rtol, atol=inner_slack * atol\n    )\n    is_spheric = np.isclose(\n        moments[0], moments[2], rtol=inner_slack * rtol, atol=inner_slack * atol\n    )\n    is_prolate = np.isclose(\n        moments[1], moments[2], rtol=inner_slack * rtol, atol=inner_slack * atol\n    )\n\n    # basic tests for shapes\n    fits_line = np.isclose(\n        moments[0], 0.0, rtol=inner_slack * rtol, atol=inner_slack * atol\n    )\n    fits_plane = np.isclose(moments[0] + moments[1], moments[2], rtol=rtol, atol=atol)\n\n    is_spheric = is_spheric and is_oblate and is_prolate\n    if is_spheric:\n        top = \"spheric\"\n    elif is_oblate:\n        top = \"symmetric oblate\"\n    elif is_prolate:\n        top = \"symmetric prolate\"\n    else:\n        top = \"asymmetric\"\n\n    fits_line = fits_line and is_prolate\n    if fits_line:\n        shape = \"linear\"\n    elif fits_plane:\n        if is_oblate:\n            shape = \"regular planar\"\n        else:\n            shape = \"irregular planar\"\n    else:\n        shape = \"nonplanar\"\n\n    return top, shape\n\n\ndef gyradius(atommasses, atomcoords, method=\"iupac\"):\n    \"\"\"Calculate the radius of gyration (or gyradius) of the molecule.\n\n    Parameters\n    ----------\n    atommasses : array-like\n        Atomic masses in atomic mass units (amu).\n    atomcoords : array-like\n        Atomic coordinates.\n    method : str, optional\n\n    Returns\n    -------\n    array-like\n\n    Raises\n    ------\n    ValueError\n        If `method` is not recognized.\n\n    Examples\n    --------\n    >>> from overreact import _datasets as datasets\n\n    >>> data = datasets.logfiles[\"tanaka1996\"][\"CH3·@UMP2/cc-pVTZ\"]\n    >>> gyradius(data.atommasses, data.atomcoords)\n    0.481\n    >>> gyradius(data.atommasses, data.atomcoords, method=\"mean\")\n    0.93\n\n    >>> data = datasets.logfiles[\"symmetries\"][\"water\"]\n    >>> gyradius(data.atommasses, data.atomcoords)\n    0.31915597673891866\n    >>> gyradius(np.ones_like(data.atommasses), data.atomcoords)\n    0.6833818299241241\n    >>> gyradius(np.ones_like(data.atommasses), data.atomcoords, method=\"mean\")\n    0.6833818299241241\n    >>> gyradius(data.atommasses, data.atomcoords, method=\"mean\")\n    0.7637734749747612\n    \"\"\"\n    com = np.average(atomcoords, axis=0, weights=atommasses)\n    atomcoords = atomcoords - com\n    if method == \"iupac\":\n        return np.sqrt(\n            np.average(np.diag(atomcoords @ atomcoords.T), weights=atommasses)\n        )\n    elif method == \"mean\":\n        return np.sqrt(np.mean(np.diag(atomcoords @ atomcoords.T)))\n    else:\n        raise ValueError(f\"unavailable method: '{method}'\")\n\n\ndef inertia(atommasses, atomcoords, align=True):\n    r\"\"\"Calculate primary moments and axes from the inertia tensor.\n\n    Parameters\n    ----------\n    atommasses : array-like\n        Atomic masses in atomic mass units (amu).\n    atomcoords : array-like\n        Atomic coordinates.\n    align : bool, optional\n        If true, the returned coordinates are aligned to the primary axes of\n        inertia. The returned axes correspond to the aligned coordinates as\n        well.\n\n    Returns\n    -------\n    moments, axes : array-like\n        Primary moments of inertia in ascending order and associated normalized\n        axes. Axes are column vectors and always correspond to returned atomic\n        coordinates. Units are in amu·Å².\n    atomcoords : array-like\n        Coordinates centered at the center of mass and, if align was set to\n        True, rotated to the primary axes of inertia.\n\n    Examples\n    --------\n    >>> atommasses = np.array([12.011,  1.008,  1.008,  1.008])  # CH3·\n    >>> atomcoords = np.array([[ 0.      ,  0.      , -1.      ],\n    ...                        [ 1.07883 ,  0.      , -1.      ],\n    ...                        [-0.539415,  0.934294, -1.      ],\n    ...                        [-0.539415, -0.934294, -1.      ]])\n    >>> moments, axes, atomcoords = inertia(atommasses, atomcoords)\n    >>> moments\n    array([1.75977704, 1.75977774, 3.51955478])\n    >>> axes\n    array([[1., 0., 0.],\n           [0., 1., 0.],\n           [0., 0., 1.]])\n    >>> atomcoords\n    array([[ 0.      ,  0.      ,  0.      ],\n           [ 1.07883 ,  0.      ,  0.      ],\n           [-0.539415,  0.934294,  0.      ],\n           [-0.539415, -0.934294,  0.      ]])\n\n    This allows one to calculate the rotational constants in cm-1:\n\n    >>> constants.h * constants.centi \\\n    ...     / (8 * np.pi ** 2 * constants.c \\\n    ...     * moments * constants.atomic_mass * constants.angstrom ** 2)\n    array([9.5794, 9.5794, 4.7897])\n    \"\"\"\n    atommasses = np.atleast_1d(atommasses)\n    com = np.average(atomcoords, axis=0, weights=atommasses)\n    atomcoords = atomcoords - com\n\n    w_coords = np.sqrt(atommasses)[:, np.newaxis] * atomcoords\n    squared_w_coords = w_coords ** 2\n\n    i_xx = np.sum(squared_w_coords[:, 1] + squared_w_coords[:, 2])\n    i_yy = np.sum(squared_w_coords[:, 0] + squared_w_coords[:, 2])\n    i_zz = np.sum(squared_w_coords[:, 0] + squared_w_coords[:, 1])\n\n    i_xy = -np.sum(w_coords[:, 0] * w_coords[:, 1])\n    i_xz = -np.sum(w_coords[:, 0] * w_coords[:, 2])\n    i_yz = -np.sum(w_coords[:, 1] * w_coords[:, 2])\n\n    inertia_tensor = np.array(\n        [[i_xx, i_xy, i_xz], [i_xy, i_yy, i_yz], [i_xz, i_yz, i_zz]]\n    )\n    moments, axes = np.linalg.eigh(inertia_tensor)\n    if align:\n        return inertia(atommasses, atomcoords @ axes, align=False)\n    logger.debug(f\"moments = {moments} amu·Å²\")\n    # logger.debug(f\"axes = {axes} Å\")\n    # logger.debug(f\"atomcoords = {atomcoords} Å\")\n    return moments, axes, atomcoords\n\n\n# TODO(schneiderfelipe): this needs rework, see\n# https://chemistry.stackexchange.com/questions/74639/how-to-calculate-wavenumbers-of-normal-modes-from-the-eigenvalues-of-the-cartesi/74923#74923\n# Ideally, the same Eckart transformation that make this work will also work\n# in calc_vibfreqs, so one thing leads to the other.\ndef calc_hessian(atommasses, atomcoords, vibfreqs, vibdisps):\n    \"\"\"Compute the Hessian matrix from normal modes and frequencies.\n\n    This function does the inverse of what is described in\n    https://gaussian.com/vib/.\n\n    Parameters\n    ----------\n    atommasses : array-like\n        Atomic masses in atomic mass units (amu).\n    atomcoords : array-like\n        Atomic coordinates.\n    vibfreqs : array-like\n        Frequency magnitudes in cm-1.\n    vibdisps : array-like\n        Normal modes in cartesian coordinates.\n\n    Returns\n    -------\n    array-like\n        Complete Hessian matrix in cartesian coordinates.\n\n    Notes\n    -----\n    This is a work in progress!\n\n    Examples\n    --------\n    >>> from overreact import _datasets as datasets\n\n    >>> data = datasets.logfiles[\"symmetries\"][\"water\"]\n    >>> H = calc_hessian(data.atommasses, data.atomcoords, data.vibfreqs, data.vibdisps)\n    >>> calc_vibfreqs(H, data.atommasses)  # doctest: +SKIP\n    array([1619.1, 3671.7, 3769.1])\n    >>> H  # this is probably incorrect\n    array([[ 0.25035519,  0.17924759, -0.21923846, -0.22425124, -0.15503866,\n             0.20261806, -0.02610273, -0.02420995,  0.01662027],\n           [ 0.17924759,  0.39097884,  0.13979548, -0.12659242, -0.11407083,\n             0.08438083, -0.05265485, -0.27690678, -0.2241771 ],\n           [-0.21923846,  0.13979548,  0.52730855,  0.23475659,  0.13230333,\n            -0.2460061 , -0.01551983, -0.2720957 , -0.28130313],\n           [-0.22425124, -0.12659242,  0.23475659,  0.22086973,  0.13025443,\n            -0.22492564,  0.00337999, -0.00366091, -0.00983096],\n           [-0.15503866, -0.11407083,  0.13230333,  0.13025443,  0.10037856,\n            -0.10602169,  0.02478367,  0.01369292, -0.02628153],\n           [ 0.20261806,  0.08438083, -0.2460061 , -0.22492564, -0.10602169,\n             0.25914009,  0.02230951,  0.02163974, -0.01313383],\n           [-0.02610273, -0.05265485, -0.01551983,  0.00337999,  0.02478367,\n             0.02230951,  0.02272304,  0.0278711 , -0.00678954],\n           [-0.02420995, -0.27690678, -0.2720957 , -0.00366091,  0.01369292,\n             0.02163974,  0.0278711 ,  0.26321199,  0.25045664],\n           [ 0.01662027, -0.2241771 , -0.28130313, -0.00983096, -0.02628153,\n            -0.01313383, -0.00678954,  0.25045664,  0.29443748]])\n    \"\"\"\n    dof = 3 * len(atommasses)\n    L_cart = np.asarray(vibdisps).reshape((len(vibfreqs), dof)).T\n    # this function is correct until here\n\n    L_cart = np.linalg.qr(L_cart, mode=\"complete\")[0]\n\n    atommasses_sqrt = np.sqrt([mass for mass in atommasses for _ in range(3)])\n    D = eckart_transform(atommasses, atomcoords)\n    M = np.diag(1.0 / atommasses_sqrt)\n    L = np.linalg.solve(M @ D, L_cart)\n\n    assert np.allclose(M @ D @ L, L_cart), \"L_cart is not orthogonal\"\n\n    # this function is correct from here\n    nu = np.asarray(vibfreqs) * constants.c / constants.centi\n    eigenvalues = (\n        (2.0 * np.pi * nu) ** 2\n        * (constants.atomic_mass * constants.bohr ** 2)\n        / constants.hartree\n    )\n    eigenvalues = np.block([eigenvalues, np.zeros(dof - len(eigenvalues))])\n\n    f_int = L @ np.diag(eigenvalues) @ L.T\n    f_mwc = D @ f_int @ D.T\n    return f_mwc * np.outer(atommasses_sqrt, atommasses_sqrt)\n\n\n# TODO(schneiderfelipe): correct this function and project out translations\n# and rotations, see\n# https://chemistry.stackexchange.com/questions/74639/how-to-calculate-wavenumbers-of-normal-modes-from-the-eigenvalues-of-the-cartesi/74923#74923\ndef calc_vibfreqs(hessian, atommasses):\n    \"\"\"Calculate vibrational frequencies.\n\n    This is described in https://gaussian.com/vib/.\n\n    Parameters\n    ----------\n    hessian : array-like\n    atommasses : array-like\n        Atomic masses in atomic mass units (amu).\n    atomcoords : array-like\n        Atomic coordinates.\n\n    Returns\n    -------\n    vibfreqs : array-like\n        Frequency magnitudes in cm-1.\n\n    Examples\n    --------\n    >>> from overreact import _datasets as datasets\n\n    >>> data = datasets.logfiles[\"symmetries\"][\"water\"]\n    >>> calc_vibfreqs(data.hessian, data.atommasses)\n    array([1619.1, 3671.7, 3769.1])\n    \"\"\"\n    atommasses_sqrt = np.sqrt([mass for mass in atommasses for _ in range(3)])\n\n    # mass-weighted Hessian\n    hessian = np.asarray(hessian) / np.outer(atommasses_sqrt, atommasses_sqrt)\n\n    eigenvalues = np.linalg.eigvals(hessian)\n\n    # TODO(schneiderfelipe): the following probably misses some linear\n    # molecules and transition states.\n    eigenvalues = np.real(eigenvalues[eigenvalues > 0])[::-1]\n    nu = np.sqrt(\n        eigenvalues * constants.hartree / (constants.atomic_mass * constants.bohr ** 2)\n    ) / (2.0 * np.pi)\n    return nu * constants.centi / constants.c\n\n\n# TODO(schneiderfelipe): ensure this is correct\n# https://chemistry.stackexchange.com/questions/74639/how-to-calculate-wavenumbers-of-normal-modes-from-the-eigenvalues-of-the-cartesi/74923#74923\ndef eckart_transform(atommasses, atomcoords):\n    \"\"\"Compute the Eckart transform.\n\n    This transform is described in https://gaussian.com/vib/.\n\n    Parameters\n    ----------\n    atommasses : array-like\n        Atomic masses in atomic mass units (amu).\n    atomcoords : array-like\n        Atomic coordinates.\n\n    Returns\n    -------\n    array-like\n\n    Examples\n    --------\n    >>> from overreact import _datasets as datasets\n\n    >>> data = datasets.logfiles[\"tanaka1996\"][\"Cl·@UMP2/cc-pVTZ\"]\n    >>> eckart_transform(data.atommasses, data.atomcoords)\n    array([[1., 0., 0.],\n           [0., 1., 0.],\n           [0., 0., 1.]])\n    >>> data = datasets.logfiles[\"symmetries\"][\"dihydrogen\"]\n    >>> eckart_transform(data.atommasses, data.atomcoords)\n    array([[...]])\n    >>> data = datasets.logfiles[\"symmetries\"][\"water\"]\n    >>> eckart_transform(data.atommasses, data.atomcoords)\n    array([[-9.42386999e-01,  0.00000000e+00,  0.00000000e+00,\n             2.99716727e-01, -2.86166258e-06, -7.42376895e-02,\n            -1.19022276e-02,  4.33736541e-03, -1.28081683e-01],\n           [-0.00000000e+00, -9.42386999e-01,  0.00000000e+00,\n             1.40934586e-02, -1.34562803e-07,  1.01850683e-01,\n            -1.52466204e-01, -2.78628770e-01, -2.13218735e-02],\n           [-0.00000000e+00, -0.00000000e+00, -9.42386999e-01,\n            -1.47912143e-01,  1.41224899e-06, -1.40724409e-01,\n            -3.86450545e-02, -1.77596105e-02, -2.61565554e-01],\n           [-2.36544652e-01, -0.00000000e+00, -0.00000000e+00,\n            -5.97037403e-01, -6.33525274e-01,  2.70812665e-02,\n            -2.34354970e-01,  8.09905642e-02,  3.52169811e-01],\n           [-0.00000000e+00, -2.36544652e-01, -0.00000000e+00,\n            -2.80742485e-02, -2.97900030e-02, -6.93753868e-01,\n             5.78451116e-01,  2.06337502e-01,  2.89647600e-01],\n           [-0.00000000e+00, -0.00000000e+00, -2.36544652e-01,\n             2.94641819e-01,  3.12648820e-01, -1.12274948e-02,\n            -4.19760855e-01,  1.83772848e-01,  7.41205673e-01],\n           [-2.36544652e-01, -0.00000000e+00, -0.00000000e+00,\n            -5.97025305e-01,  6.33536675e-01,  2.68679525e-01,\n             2.81773098e-01, -9.82705016e-02,  1.58103880e-01],\n           [-0.00000000e+00, -2.36544652e-01, -0.00000000e+00,\n            -2.80736797e-02,  2.97905391e-02,  2.87983715e-01,\n             2.89697972e-02,  9.03711399e-01, -2.04701877e-01],\n           [-0.00000000e+00, -0.00000000e+00, -2.36544652e-01,\n             2.94635849e-01, -3.12654446e-01,  5.71869440e-01,\n             5.73721626e-01, -1.13019078e-01,  3.00863871e-01]])\n    \"\"\"\n    atommasses = np.asarray(atommasses)\n    natom = len(atommasses)\n    dof = 3 * natom\n\n    moments, axes, atomcoords = inertia(atommasses, atomcoords, align=False)\n\n    x = np.block(\n        [\n            np.ones(natom)[:, np.newaxis],\n            np.zeros(natom)[:, np.newaxis],\n            np.zeros(natom)[:, np.newaxis],\n        ]\n    )\n    y = np.block(\n        [\n            np.zeros(natom)[:, np.newaxis],\n            np.ones(natom)[:, np.newaxis],\n            np.zeros(natom)[:, np.newaxis],\n        ]\n    )\n    z = np.block(\n        [\n            np.zeros(natom)[:, np.newaxis],\n            np.zeros(natom)[:, np.newaxis],\n            np.ones(natom)[:, np.newaxis],\n        ]\n    )\n    x *= np.sqrt(atommasses[:, np.newaxis])\n    y *= np.sqrt(atommasses[:, np.newaxis])\n    z *= np.sqrt(atommasses[:, np.newaxis])\n\n    D_trans = np.block([x.reshape(1, dof).T, y.reshape(1, dof).T, z.reshape(1, dof).T])\n    D_rot = np.array(\n        [\n            np.cross((atomcoords @ axes)[i], axes[:, j]) / np.sqrt(atommasses[i])\n            for i in range(natom)\n            for j in range(3)\n        ]\n    )\n    D = np.block([D_trans, D_rot])\n    return np.linalg.qr(D, mode=\"complete\")[0]\n\n\n# thresh >= 0.106\ndef _equivalent_atoms(\n    atommasses, atomcoords, method=\"cluster\", thresh=0.106, plot=False\n):\n    \"\"\"Generate groups of symmetry equivalent atoms.\n\n    Parameters\n    ----------\n    atommasses : array-like\n        Atomic masses in atomic mass units (amu).\n    atomcoords : array-like\n        Atomic coordinates.\n    method : str, optional\n        Method of partitioning: \"atommass\" (same atoms same groups), \"cluster\".\n    thresh : int, optional\n        Threshold to consider atom clusters.\n\n    Returns\n    -------\n    groups : sequence of sequence of int\n        Groups of symmetry equivalent atoms, in ascending order of size. Each\n        element in the list is a sequence of indices, one list for each group\n        of equivalent atoms. See examples below.\n\n    Raises\n    ------\n    ValueError\n        If `method` is not recognized.\n\n    Notes\n    -----\n    This function works for up to ten thousand randomly placed atoms and finds\n    the equivalent groups in less than a second. As such, the function performs\n    sufficiently well for the current use.\n\n    Examples\n    --------\n    >>> atommasses = [12.011,  1.008,  1.008,  1.008]  # CH3·\n    >>> atomcoords = np.array([[ 0.      ,  0.      , -1.      ],\n    ...                        [ 1.07883 ,  0.      , -1.      ],\n    ...                        [-0.539415,  0.934294, -1.      ],\n    ...                        [-0.539415, -0.934294, -1.      ]])\n    >>> for indices in _equivalent_atoms(atommasses, atomcoords):\n    ...     indices\n    [0]\n    [1, 2, 3]\n\n    >>> atommasses = np.array([14.007, 1.008, 1.008, 1.008])  # ammonia\n    >>> atomcoords = np.array(\n    ...     [\n    ...         [0.0, 0.0, 0.07878],\n    ...         [0.0, 0.98569, -0.18381],\n    ...         [0.85363, -0.49284, -0.18381],\n    ...         [-0.85363, -0.49284, -0.18381],\n    ...     ]\n    ... )\n    >>> for indices in _equivalent_atoms(atommasses, atomcoords):\n    ...     indices\n    [0]\n    [1, 2, 3]\n\n    \"\"\"\n    if len(atommasses) == 1:  # atom\n        return [[0]]\n    elif len(atommasses) == 2:  # diatomic molecule\n        if atommasses[0] == atommasses[1]:\n            return [[0, 1]]\n        return [[0], [1]]\n\n    groups = list()\n\n    def _update_groups_with_condition(condition, groups):\n        # condition is assumed to be an array-like of bool\n        groups.append(sorted(np.nonzero(condition)[0]))\n        return groups\n\n    if method == \"cluster\":\n        D = squareform(pdist(atomcoords))\n        # mu = np.outer(atommasses, atommasses) / np.add.outer(\n        #     atommasses, atommasses\n        # )  # reduced masses\n        # D = mu * D  # does this help?\n\n        omega = np.mean(D, axis=0)\n        sigma = np.std(D, axis=0)\n        delta = np.sqrt(np.sum(D ** 2, axis=0))\n\n        criteria = np.block([[omega], [sigma], [delta]]).T\n        Z = linkage(pdist(criteria), method=\"single\")\n        clusters = fcluster(Z, thresh, criterion=\"distance\")\n\n        # TODO(schneiderfelipe): this was for debug and should eventually be removed.\n        if plot:\n            import matplotlib.pyplot as plt\n\n            plt.clf()\n            for cluster in np.unique(clusters):\n                plt.scatter(\n                    criteria[clusters == cluster, 0], criteria[clusters == cluster, 1]\n                )\n            for i, (atommass, _) in enumerate(zip(atommasses, clusters)):\n                plt.annotate(atommass, (criteria[i, 0], criteria[i, 1]))\n            plt.xlabel(\"omega\")\n            plt.ylabel(\"sigma\")\n            plt.show()\n\n        for mass in np.unique(atommasses):\n            mass_condition = atommasses == mass\n            for cluster in np.unique(clusters[mass_condition]):\n                groups = _update_groups_with_condition(\n                    mass_condition & (clusters == cluster), groups\n                )\n    elif method == \"atommass\":\n        for mass in np.unique(atommasses):\n            groups = _update_groups_with_condition(atommasses == mass, groups)\n    else:\n        raise ValueError(f\"unavailable method: '{method}'\")\n\n    return sorted(groups, key=len)\n", "meta": {"hexsha": "0aad33c83e02ca3c9feb5218fc25db9835307563", "size": 64617, "ext": "py", "lang": "Python", "max_stars_repo_path": "overreact/coords.py", "max_stars_repo_name": "geem-lab/overreact", "max_stars_repo_head_hexsha": "4f2c0d4a28c9f9a0fd12dca061483348ecdcd86e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2021-08-11T20:18:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T18:22:35.000Z", "max_issues_repo_path": "overreact/coords.py", "max_issues_repo_name": "Leticia-maria/overreact", "max_issues_repo_head_hexsha": "eede50a45df5bfae942b3251f04b80ca8cd8f9c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 73, "max_issues_repo_issues_event_min_datetime": "2021-10-15T17:21:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T12:28:36.000Z", "max_forks_repo_path": "overreact/coords.py", "max_forks_repo_name": "Leticia-maria/overreact", "max_forks_repo_head_hexsha": "eede50a45df5bfae942b3251f04b80ca8cd8f9c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-10-13T23:43:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T19:45:55.000Z", "avg_line_length": 32.8005076142, "max_line_length": 146, "alphanum_fraction": 0.5760094093, "include": true, "reason": "import numpy,from scipy", "num_tokens": 18305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.18255855242226868}}
{"text": "\"\"\"spectral Electrical Impedance Tomography (sEIT) container\n\"\"\"\n# import functools\nimport os\nfrom numbers import Number\n\nimport numpy as np\n\nfrom reda.main.logger import LoggingClass\nfrom reda.containers.ERT import ImportersBase\nimport reda.importers.eit_fzj as eit_fzj\nimport reda.importers.radic_sip256c as reda_sip256c\nimport reda.importers.crtomo as reda_crtomo_exporter\nimport reda.utils.eit_fzj_utils as eit_fzj_utils\nimport reda.utils.geometric_factors as geometric_factors\nfrom reda.utils.fix_sign_with_K import fix_sign_with_K\nimport reda.eis.plots as eis_plot\n\nfrom reda.utils.decorators_and_managers import append_doc_of\nfrom reda.utils.decorators_and_managers import LogDataChanges\n\nimport reda.exporters.crtomo as exporter_crtomo\n\nimport reda.plotters.pseudoplots as PS\nimport reda.plotters.histograms as HS\n\nimport reda.utils.mpl\nplt, mpl = reda.utils.mpl.setup()\n\n\nclass importers(ImportersBase):\n    \"\"\"This class provides wrappers for most of the importer functions, and is\n    meant to be inherited by the data containers\n    \"\"\"\n    @append_doc_of(reda_crtomo_exporter.load_seit_data)\n    def import_crtomo(self, directory, frequency_file='frequencies.dat',\n                      data_prefix='volt_', **kwargs):\n        \"\"\"CRTomo importer\"\"\"\n        timestep = kwargs.get('timestep', None)\n        if 'timestep' in kwargs:\n            del (kwargs['timestep'])\n\n        # we get no electrode positions (dummy1) and no topography data\n        # (dummy2)\n        data, dummy1, dumm2 = reda_crtomo_exporter.load_seit_data(\n            directory, frequency_file, data_prefix, **kwargs)\n        if timestep is not None:\n            data['timestep'] = timestep\n        self._add_to_container(data)\n\n        print('Summary:')\n        self._describe_data(data)\n\n    def import_sip256c(self, filename, settings=None, reciprocal=None,\n                       **kwargs):\n        \"\"\"Radic SIP256c data import\"\"\"\n        timestep = kwargs.get('timestep', None)\n        if 'timestep' in kwargs:\n            del (kwargs['timestep'])\n        if settings is None:\n            settings = {}\n        # we get not electrode positions (dummy1) and no topography data\n        # (dummy2)\n        data, dummy1, dummy2 = reda_sip256c.parse_radic_file(\n            filename, settings, reciprocal=reciprocal, **kwargs)\n        if timestep is not None:\n            data['timestep'] = timestep\n        self._add_to_container(data)\n\n        print('Summary:')\n        self._describe_data(data)\n\n    def import_eit_fzj(self, filename, configfile, correction_file=None,\n                       timestep=None, **kwargs):\n        \"\"\"EIT data import for FZJ Medusa systems\"\"\"\n        # we get not electrode positions (dummy1) and no topography data\n        # (dummy2)\n        df_emd, dummy1, dummy2 = eit_fzj.read_3p_data(\n            filename,\n            configfile,\n            **kwargs\n        )\n        if correction_file is not None:\n            eit_fzj_utils.apply_correction_factors(df_emd, correction_file)\n\n        if timestep is not None:\n            df_emd['timestep'] = timestep\n\n        self._add_to_container(df_emd)\n\n        print('Summary:')\n        self._describe_data(df_emd)\n\n\nclass sEIT(LoggingClass, importers):\n\n    def __init__(self, dataframe=None):\n        self.setup_logger()\n        if dataframe is not None:\n            self.check_dataframe(dataframe)\n        # normal data (or full data, if reciprocals are not sorted\n        self.data = dataframe\n\n        self.required_data_columns = ['r', 'rpha']\n\n    def check_dataframe(self, dataframe):\n        \"\"\"Check the given dataframe for the required columns\n        \"\"\"\n        required_columns = (\n            'a',\n            'b',\n            'm',\n            'n',\n            'r',\n        )\n        for column in required_columns:\n            if column not in dataframe:\n                raise Exception('Required column not in dataframe: {0}'.format(\n                    column\n                ))\n\n    @property\n    def abmn(self):\n        return self.data.groupby(['a', 'b', 'm', 'n'])\n\n    def subquery(self, subset, filter, inplace=True):\n        \"\"\"\n\n        Examples\n        --------\n\n        ::\n\n            subquery(\n                'timestep == 2',\n                'R > 4',\n            )\n\n        \"\"\"\n        # build the full query\n        full_query = ''.join((\n            'not (',\n            subset,\n            ') or not (',\n            filter,\n            ')',\n        ))\n        result = self.data.query(full_query, inplace=inplace)\n        return result\n\n    def query(self, query, inplace=True):\n        \"\"\"State what you want to keep\n\n        \"\"\"\n        # TODO: add to queue\n        result = self.data.query(query, inplace=inplace)\n        return result\n\n    def filter(self, query, inplace=True):\n        \"\"\"Use a query statement to filter data. Note that you specify the data\n        to be removed!\n\n        Parameters\n        ----------\n        query : string\n            The query string to be evaluated. Is directly provided to\n            pandas.DataFrame.query\n        inplace : bool\n            if True, change the container dataframe in place (defaults to True)\n\n        Returns\n        -------\n        result : :py:class:`pandas.DataFrame`\n            DataFrame that contains the result of the filter application\n\n        \"\"\"\n        with LogDataChanges(self, filter_action='filter', filter_query=query):\n            result = self.data.query(\n                'not ({0})'.format(query),\n                inplace=inplace,\n            )\n        return result\n\n    def remove_frequencies(self, fmin, fmax):\n        \"\"\"Remove frequencies from the dataset\n        \"\"\"\n        self.data.query(\n            'frequency > {0} and frequency < {1}'.format(fmin, fmax),\n            inplace=True\n        )\n        g = self.data.groupby('frequency')\n        print('Remaining frequencies:')\n        print(sorted(g.groups.keys()))\n\n    def compute_K_analytical(self, spacing):\n        \"\"\"Assuming an equal electrode spacing, compute the K-factor over a\n        homogeneous half-space.\n\n        For more complex grids, please refer to the module:\n        reda.utils.geometric_factors\n\n        Parameters\n        ----------\n        spacing: float\n            Electrode spacing\n\n        \"\"\"\n        assert isinstance(spacing, Number)\n        K = geometric_factors.compute_K_analytical(self.data, spacing)\n        self.data = geometric_factors.apply_K(self.data, K)\n        fix_sign_with_K(self.data)\n\n    @append_doc_of(fix_sign_with_K)\n    def fix_sign_with_K(self):\n        \"\"\" \"\"\"\n        fix_sign_with_K(self.data)\n\n    def scatter_norrec(self, filename=None, individual=False):\n        \"\"\"Create a scatter plot for all diff pairs\n\n        Parameters\n        ----------\n\n        filename : string, optional\n            if given, save plot to file\n        individual : bool, optional\n            if set to True, return one figure for each row\n\n        Returns\n        -------\n        fig : matplotlib.Figure or list of :py:class:`matplotlib.Figure.Figure`\n            objects the figure object\n        axes : list of matplotlib.axes\n            the individual axes\n\n        \"\"\"\n        # if not otherwise specified, use these column pairs:\n        std_diff_labels = {\n            'r': 'rdiff',\n            'rpha': 'rphadiff',\n        }\n\n        diff_labels = std_diff_labels\n\n        # check which columns are present in the data\n        labels_to_use = {}\n        for key, item in diff_labels.items():\n            # only use if BOTH columns are present\n            if key in self.data.columns and item in self.data.columns:\n                labels_to_use[key] = item\n\n        g_freq = self.data.groupby('frequency')\n        frequencies = list(sorted(g_freq.groups.keys()))\n\n        if individual:\n            figures = {}\n            axes_all = {}\n        else:\n            Nx = len(labels_to_use.keys())\n            Ny = len(frequencies)\n            fig, axes = plt.subplots(\n                Ny, Nx,\n                figsize=(Nx * 2.5, Ny * 2.5)\n            )\n\n        for row, (name, item) in enumerate(g_freq):\n            if individual:\n                fig, axes_row = plt.subplots(\n                    1, 2, figsize=(16 / 2.54, 6 / 2.54))\n            else:\n                axes_row = axes[row, :]\n            # loop over the various columns\n            for col_nr, (key, diff_column) in enumerate(\n                    sorted(labels_to_use.items())):\n                indices = np.where(~np.isnan(item[diff_column]))[0]\n                ax = axes_row[col_nr]\n                ax.scatter(\n                    item[key],\n                    item[diff_column],\n                )\n                ax.set_xlabel(key)\n                ax.set_ylabel(diff_column)\n                ax.set_title('N: {}'.format(len(indices)))\n            if individual:\n                fig.tight_layout()\n                figures[name] = fig\n                axes_all[name] = axes_row\n\n        if individual:\n            return figures, axes_all\n        else:\n            fig.tight_layout()\n            return fig, axes\n\n    def filter_incomplete_spectra(self, flimit=1000, percAccept=85):\n        \"\"\"Remove all data points that belong to spectra that did not retain at\n        least **percAccept** percent of the number of data points.\n\n        ..warning::\n\n            This function does not honor additional dimensions (e.g.,\n            timesteps) yet!\n\n        \"\"\"\n        assert percAccept > 0 and percAccept < 100\n\n        def _retain_only_complete_spectra(item, fmax, acceptN):\n            \"\"\"Function called using pd.filter, applied to all spectra in the\n            data set. Return true if the number of data points <= **fmax** in\n            item is equal, or larger, than **acceptN**.\n\n            Parameters\n            ----------\n            item : :py:class:`pandas.DataFrame`\n                dataframe containing one spectrum\n            fmax : float\n                maximum frequency up to which data points are counted\n            acceptN : int\n                the number of data points required to pass this test\n\n            Returns\n            -------\n            true : bool\n                if enough data points are present\n            false : bool\n                if not enough data points are present\n            \"\"\"\n            frequencies = item['frequency'].loc[item['frequency'] < fmax]\n            fN = frequencies.size\n            if fN >= acceptN:\n                return True\n            return False\n\n        group_abmn = self.data.groupby(['a', 'b', 'm', 'n'])\n        frequencies = np.array(\n            list(sorted(self.data.groupby('frequency').groups.keys()))\n        )\n        assert frequencies.size > 0\n        assert flimit >= frequencies.min() and flimit <= frequencies.max()\n        Nlimit = len(np.where(frequencies <= flimit)[0])\n        Naccept = np.ceil(Nlimit * percAccept / 100.0)\n        self.data = group_abmn.filter(\n            _retain_only_complete_spectra, fmax=flimit, acceptN=Naccept\n        ).copy()\n\n    def get_spectrum(self, nr_id=None, abmn=None, plot_filename=None):\n        \"\"\"Return a spectrum and its reciprocal counter part, if present in the\n        dataset. Optimally, refer to the spectrum by its normal-reciprocal id.\n\n        Returns\n        -------\n        spectrum_nor : :py:class:`reda.eis.plots.sip_response`\n            Normal spectrum. None if no normal spectrum is available\n        spectrum_rec : :py:class:`reda.eis.plots.sip_response` or None\n            Reciprocal spectrum. None if no reciprocal spectrum is available\n        fig : :py:class:`matplotlib.Figure.Figure` , optional\n            Figure object (only if plot_filename is set)\n\n        \"\"\"\n        assert nr_id is None or abmn is None\n        # determine nr_id for given abmn tuple\n        if abmn is not None:\n            subdata = self.data.query(\n                'a == {} and b == {} and m == {} and n == {}'.format(*abmn)\n            ).sort_values('frequency')\n            if subdata.shape[0] == 0:\n                return None, None\n\n            # determine the norrec-id of this spectrum\n            nr_id = subdata['id'].iloc[0]\n\n        # get spectra\n        subdata_nor = self.data.query(\n            'id == {} and norrec==\"nor\"'.format(nr_id)\n        ).sort_values('frequency')\n\n        subdata_rec = self.data.query(\n            'id == {} and norrec==\"rec\"'.format(nr_id)\n        ).sort_values('frequency')\n\n        # create spectrum objects\n        spectrum_nor = None\n        spectrum_rec = None\n\n        if subdata_nor.shape[0] > 0:\n            spectrum_nor = eis_plot.sip_response(\n                frequencies=subdata_nor['frequency'].values,\n                rmag=subdata_nor['r'],\n                rpha=subdata_nor['rpha'],\n            )\n        if subdata_rec.shape[0] > 0:\n            spectrum_rec = eis_plot.sip_response(\n                frequencies=subdata_rec['frequency'].values,\n                rmag=subdata_rec['r'],\n                rpha=subdata_rec['rpha'],\n            )\n        if plot_filename is not None:\n            if spectrum_nor is not None:\n                fig = spectrum_nor.plot(\n                    plot_filename,\n                    reciprocal=spectrum_rec,\n                    return_fig=True,\n                    title='a: {} b: {} m: {}: n: {}'.format(\n                        *subdata_nor[['a', 'b', 'm', 'n']].values[0, :]\n                    )\n                )\n                return spectrum_nor, spectrum_rec, fig\n        return spectrum_nor, spectrum_rec\n\n    def plot_all_spectra(self, outdir):\n        r\"\"\"This is a convenience function to plot ALL spectra currently\n        stored in the container. It is useful to asses whether data filters\n        do perform correctly.\n\n        Note that the function just iterates over all ids and plots the\n        corresponding spectra, thus it is slow.\n\n        Spectra a named using the format: \\%.2i_spectrum_id_\\{\\}.png.\n\n        Parameters\n        ----------\n        outdir : string\n            Output directory to store spectra in. Created if it does not\n            exist.\n        \"\"\"\n        os.makedirs(outdir, exist_ok=True)\n\n        g = self.data.groupby('id')\n        for nr, (name, item) in enumerate(g):\n            print(\n                'Plotting spectrum with id {} ({} / {})'.format(\n                    name, nr, len(g.groups.keys()))\n            )\n            plot_filename = ''.join((\n                outdir + os.sep,\n                '{:04}_spectrum_id_{}.png'.format(nr, name)\n            ))\n            spec_nor, spec_rec, spec_fig = self.get_spectrum(\n                nr_id=name,\n                plot_filename=plot_filename\n            )\n            plt.close(spec_fig)\n\n    def plot_pseudosections(self, column, filename=None, return_fig=False):\n        \"\"\"Create a multi-plot with one pseudosection for each frequency.\n\n        Parameters\n        ----------\n        column : string\n            which column to plot\n        filename : None|string\n            output filename. If set to None, do not write to file. Default:\n            None\n        return_fig : bool\n            if True, return the generated figure object, also if filename is\n            set. Default: False\n\n        Returns\n        -------\n        fig : None|matplotlib.Figure\n            if return_fig is set to True or filename is None, return the\n            generated Figure object\n        \"\"\"\n        assert column in self.data.columns\n\n        g = self.data.groupby('frequency')\n        fig, axes = plt.subplots(\n            4, 2,\n            figsize=(15 / 2.54, 20 / 2.54),\n            sharex=True, sharey=True\n        )\n        for ax, (key, item) in zip(axes.flat, g):\n            fig, ax, cb = PS.plot_pseudosection_type2(\n                item, ax=ax, column=column\n            )\n            ax.set_title('f: {:.3f} Hz'.format(key))\n        fig.tight_layout()\n        if filename is not None:\n            fig.savefig(filename, dpi=300)\n\n        if return_fig or filename is None:\n            return fig\n        else:\n            plt.close(fig)\n\n    def export_to_crtomo_multi_frequency(self, directory, norrec='norrec'):\n        \"\"\"Export the sEIT data into data files that can be read by CRTomo.\n\n        Parameters\n        ----------\n        directory : string\n            output directory. will be created if required\n        norrec : string (nor|rec|norrec)\n            Which data to export. Default: norrec\n\n        \"\"\"\n        exporter_crtomo.write_files_to_directory(\n            self.data, directory, norrec=norrec\n        )\n\n    def export_to_crtomo_one_frequency(\n            self, volt_file, frequency, norrec='norrec'):\n        \"\"\"Export one frequency into a CRTomo volt.dat file\n\n        Parameters\n        ----------\n        volt_file : string\n            output file. Will be overwritten if it exists\n        frequency : float\n            frequency to export\n        norrec : str (nor|rec|norrec)\n            Which data to export. Default: norrec\n        \"\"\"\n        assert isinstance(frequency, float)\n        frequency_data = self.data.query('frequency == {}'.format(frequency))\n        exporter_crtomo.save_block_to_crt(\n            volt_file, frequency_data, norrec=norrec\n        )\n\n    def export_to_crtomo_seit_manager(self, grid, norrec='norrec'):\n        \"\"\"Return a ready-initialized seit-manager object from the CRTomo\n        tools. This function only works if the crtomo_tools are installed.\n\n        WARNING: Not timestep aware!\n\n        Parameters\n        ----------\n        grid : crtomo.crt_grid\n            A CRTomo grid instance\n        norrec : str (nor|rec|norrec)\n            Which data to export. Default: norrec (all)\n\n        \"\"\"\n        import crtomo\n        subdata = self.data.query('norrec == \"{}\"'.format(norrec))\n        g = subdata.groupby('frequency')\n        seit_data = {}\n        for name, item in g:\n            print(name, item.shape, item.size)\n            if item.shape[0] > 0:\n                seit_data[name] = item[\n                    ['a', 'b', 'm', 'n', 'r', 'rpha']\n                ].values\n        seit = crtomo.eitMan(grid=grid, seit_data=seit_data)\n        return seit\n\n    def export_to_crtomo_td_manager(self, grid, frequency, norrec='norrec'):\n        \"\"\"Return a ready-initialized tdman object from the CRTomo tools. Use\n        the given frequency data to initialize it.\n\n        WARNING: Not timestep aware!\n\n        Parameters\n        ----------\n        grid : crtomo.crt_grid\n            A CRTomo grid instance\n        frequency : float\n            The frequency to export data for\n        norrec : str (nor|rec|norrec)\n            Which data to export. Default: norrec (all)\n        \"\"\"\n        subdata = self.data.query('norrec == \"{}\"'.format(norrec))\n        import crtomo\n        data = subdata.query('frequency == {}'.format(frequency))[\n            ['a', 'b', 'm', 'n', 'r', 'rpha']\n        ]\n        tdman = crtomo.tdMan(grid=grid, volt_data=data)\n        return tdman\n\n    def plot_histograms(\n            self, column='r', primary_dim=None, filename=None, **kwargs):\n        \"\"\"Plot a histograms for all frequencies of one data column\n\n        Parameters\n        ----------\n        column : str, optional\n            data column to plot. defaults to \"r\" for resistance\n        primary_dim : None|str\n            ???\n        filename : None|str\n            Prefix for filename\n        **kwargs : dict\n            ???\n\n        TODO: Check saving to file for more than one secondary dimension\n        Parameters\n        ----------\n        \"\"\"\n        dict_dimension, figs = HS.plot_histograms_extra_dims(\n            self.data, column, primary_dim, **kwargs)\n        if filename is not None:\n            for key, item in figs.items():\n                item.savefig(\n                    filename + '_{}.jpg'.format(key.replace('_', '-')), dpi=300\n                )\n        return dict_dimension, figs\n\n    @property\n    def nr_frequencies(self):\n        \"\"\"Return the number of frequencies in the data set\"\"\"\n        if self.data is None:\n            return 0\n        group_f = self.data.groupby('frequency')\n        return group_f.ngroups\n\n    @property\n    def Nf(self):\n        \"\"\"Shortcut for self.nr_frequencies\"\"\"\n        return self.nr_frequencies()\n\n    @property\n    def frequencies(self):\n        \"\"\"Return the frequencies contained in the data set\"\"\"\n        if self.data is None:\n            return 0\n        frequencies = sorted(self.data.groupby('frequency').groups.keys())\n        return frequencies\n\n    @property\n    def nr_timesteps(self):\n        \"\"\"Return the number of timesteps registered with this container\"\"\"\n        if self.data is None or 'timestep' not in self.data:\n            return 0\n        group_ts = self.data.groupby('timestep')\n        return group_ts.ngroups\n", "meta": {"hexsha": "f0fd22ed51c1af33d42c4a0161a83788cbf72e3a", "size": 20752, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/reda/containers/sEIT.py", "max_stars_repo_name": "j-gallistl/reda", "max_stars_repo_head_hexsha": "13b1f9e1cda92bbbbafc5c28be2c691d3b722740", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/reda/containers/sEIT.py", "max_issues_repo_name": "j-gallistl/reda", "max_issues_repo_head_hexsha": "13b1f9e1cda92bbbbafc5c28be2c691d3b722740", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/reda/containers/sEIT.py", "max_forks_repo_name": "j-gallistl/reda", "max_forks_repo_head_hexsha": "13b1f9e1cda92bbbbafc5c28be2c691d3b722740", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1501597444, "max_line_length": 79, "alphanum_fraction": 0.5616808019, "include": true, "reason": "import numpy", "num_tokens": 4580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.1824893799930208}}
{"text": "#! /usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\n__author__ = 'Alan Loh, Julien Girard'\n__copyright__ = 'Copyright 2019, nenupytv'\n__credits__ = ['Alan Loh', 'Julien Girard']\n__maintainer__ = 'Alan'\n__email__ = 'alan.loh@obspm.fr'\n__status__ = 'Production'\n__all__ = [\n    'nenufar_loc',\n    'lst',\n    'lha',\n    'ho_zenith',\n    'eq_zenith',\n    'radec',\n    'radec_hd',\n    'eq_coord',\n    'to_radec',\n    'to_altaz',\n    'to_gal',\n    'to_lmn',\n    'rephase',\n    'rotz',\n    'wavelength',\n    'ref_location',\n    'radio_sources',\n    'ateam',\n    'AstroPlot',\n    'astro_image'\n    ]\n\n\nfrom os import path\nimport numpy as np\nfrom astropy.time import Time\nfrom astropy import units as u\nfrom astropy.coordinates import (\n    EarthLocation,\n    Angle,\n    SkyCoord,\n    AltAz,\n    Galactic,\n    ICRS,\n    get_body,\n    solar_system_ephemeris\n)\nfrom astropy.constants import c as lspeed\nfrom astropy.wcs import WCS\nfrom astropy.io import fits\n\nimport nenupytv\n\n# ============================================================= #\n# ------------------------ nenufar_loc ------------------------ #\n# ============================================================= #\ndef nenufar_loc():\n    \"\"\"\n    \"\"\"\n    return EarthLocation(\n        lat=47.375944 * u.deg,\n        lon=2.193361 * u.deg,\n        height=136.195 * u.m\n    )\n# ============================================================= #\n\n\n# ============================================================= #\n# ---------------------------- lst ---------------------------- #\n# ============================================================= #\ndef lst(time, location=None):\n    \"\"\" Local sidereal time\n\n        Parameters\n        ----------\n        time : `astropy.time.Time`\n            UTC time\n        location : `astropy.coord.EarthLocation`\n            Location of the instrument\n\n        Returns\n        -------\n        lst : float\n            Local sidereal time in degrees\n    \"\"\"\n    if not isinstance(time, Time):\n        raise TypeError(\n            'time is not an astropy Time.'\n            )\n    if location is None:\n        location = nenufar_loc()\n    if not isinstance(location, EarthLocation):\n        raise TypeError(\n            'time is not an astropy EarthLocation.'\n            )\n    lon = location.to_geodetic().lon\n    lst = time.sidereal_time('apparent', lon)\n    return lst.deg#.hourangle\n# ============================================================= #\n\n\n# ============================================================= #\n# ---------------------------- lha ---------------------------- #\n# ============================================================= #\ndef lha(time, ra, location=None):\n    \"\"\" Local hour angle of an object in the observer's sky\n\n        Parameters\n        ----------\n        time : `astropy.time.Time`\n            UTC time\n        ra : float\n            Right Ascension in degrees\n        location : `astropy.coord.EarthLocation`, optional\n            Location of the instrument\n\n        Returns\n        -------\n        lha : float\n            Local hour angle in degrees\n    \"\"\"\n    ra = Angle(ra * u.deg).deg#.hourangle\n    ha = lst(time, location) - ra\n    if ha < 0:\n        ha += 360.\n    elif ha > 360:\n        ha -= 360.\n    return ha\n# ============================================================= #\n\n\n# ============================================================= #\n# ------------------------- ho_zenith ------------------------- #\n# ============================================================= #\ndef ho_zenith(time, location=None):\n    \"\"\" Horizontal coordinates of zenith\n    \"\"\"\n    if location is None:\n        location = nenufar_loc()\n    if not isinstance(location, EarthLocation):\n        raise TypeError(\n            'time is not an astropy EarthLocation.'\n            )\n    altaz = AltAz(\n        az=0.*u.deg,\n        alt=90.*u.deg,\n        location=location,\n        obstime=time\n    )\n    return altaz\n# ============================================================= #\n\n\n# ============================================================= #\n# ------------------------- eq_zenith ------------------------- #\n# ============================================================= #\ndef eq_zenith(time, location=None):\n    \"\"\" Get the ra dec coordinates of the zenith\n        \n        Parameters\n        ----------\n        time : `astropy.time.Time`\n            UTC time\n        location : `astropy.coord.EarthLocation`\n            Location of the instrument\n\n        Returns\n        -------\n        ra : float\n            Right Ascension in degrees\n        dec : float\n            Declination in degrees\n    \"\"\"\n    if location is None:\n        location = nenufar_loc()\n    if not isinstance(location, EarthLocation):\n        raise TypeError(\n            'time is not an astropy EarthLocation.'\n            )\n\n    zen_alt = 90*u.deg\n    zen_az = 0*u.deg\n    azel = SkyCoord(\n        alt=zen_alt,\n        az=zen_az,\n        obstime=time,\n        location=location,\n        frame='altaz'\n        )\n    eq = azel.icrs\n    return eq.ra.deg, eq.dec.deg\n# ============================================================= #\n\n\n# ============================================================= #\n# --------------------------- radec --------------------------- #\n# ============================================================= #\ndef radec(ra, dec):\n    \"\"\" Equatorial coordinates\n        \n        :param ra:\n            Right ascension in degrees\n        :type ra: float\n        :param dec:\n            Declination in degrees\n        :type dec: float\n\n        :returns: :class:`astropy.coordinates.ICRS` object\n        :rtype: :class:`astropy.coordinates.ICRS`\n\n        :Example:\n        \n        >>> from nenupysim.astro import eq_coord\n        >>> radec = eq_coord(\n                ra=51,\n                dec=39,\n            )\n    \"\"\"\n    return ICRS(\n        ra=ra*u.deg,\n        dec=dec*u.deg\n    )\n# ============================================================= #\n\n\n# ============================================================= #\n# ------------------------- radec_hd -------------------------- #\n# ============================================================= #\ndef radec_hd(hms_dms):\n    \"\"\"\n    \"\"\"\n    return SkyCoord(\n        hms_dms,\n        unit=[u.hourangle, u.deg]\n    )\n# ============================================================= #\n\n\n# ============================================================= #\n# ------------------------- eq_coord -------------------------- #\n# ============================================================= #\ndef eq_coord(ra, dec):\n    \"\"\" Equatorial coordinates\n        \n        :param ra:\n            Right ascension in degrees\n        :type ra: float\n        :param dec:\n            Declination in degrees\n        :type dec: float\n\n        :returns: :class:`astropy.coordinates.ICRS` object\n        :rtype: :class:`astropy.coordinates.ICRS`\n\n        :Example:\n        \n        >>> from nenupysim.astro import eq_coord\n        >>> radec = eq_coord(\n                ra=51,\n                dec=39,\n            )\n    \"\"\"\n    eq = radec(\n        ra=ra*u.deg,\n        dec=dec*u.deg\n    )\n    return eq.ra.deg, eq.dec.deg\n# ============================================================= #\n\n\n# ============================================================= #\n# ------------------------- eq_zenith ------------------------- #\n# ============================================================= #\ndef to_radec(alt, az, time, location=None):\n    \"\"\" Get the ra dec coordinates of the a altaz pointing\n        \n        Parameters\n        ----------\n        alt : float\n            Elevation in degrees\n        az : float\n            Azimuth in degrees\n        time : `astropy.time.Time`\n            UTC time\n        location : `astropy.coord.EarthLocation`\n            Location of the instrument\n\n        Returns\n        -------\n        ra : float\n            Right Ascension in degrees\n        dec : float\n            Declination in degrees\n    \"\"\"\n    if location is None:\n        location = nenufar_loc()\n    if not isinstance(location, EarthLocation):\n        raise TypeError(\n            'time is not an astropy EarthLocation.'\n            )\n\n    zen_alt = alt*u.deg\n    zen_az = az*u.deg\n    azel = SkyCoord(\n        alt=zen_alt,\n        az=zen_az,\n        obstime=time,\n        location=location,\n        frame='altaz'\n        )\n    eq = azel.icrs\n    return eq.ra.deg, eq.dec.deg\n# ============================================================= #\n\n\n# ============================================================= #\n# ------------------------- to_altaz -------------------------- #\n# ============================================================= #\ndef to_altaz(ra, dec, time, location=None):\n    \"\"\" Transform altaz coordinates to ICRS equatorial system\n        \n        :param radec:\n            Equatorial coordinates\n        :type altaz: :class:`astropy.coordinates.ICRS`\n        :param time:\n            Time at which the local coordinates should be \n            computed. It can either be provided as an \n            :class:`astropy.time.Time` object or a string in ISO\n            or ISOT format.\n        :type time: str, :class:`astropy.time.Time`\n\n        :returns: :class:`astropy.coordinates.AltAz` object\n        :rtype: :class:`astropy.coordinates.AltAz`\n\n        :Example:\n        \n        >>> from nenupysim.astro import eq_coord\n        >>> radec = eq_coord(\n                ra=51,\n                dec=39,\n            )\n    \"\"\"\n    if location is None:\n        location = nenufar_loc()\n    if not isinstance(location, EarthLocation):\n        raise TypeError(\n            'time is not an astropy EarthLocation.'\n            )\n\n    altaz_frame = AltAz(\n        obstime=time,\n        location=location\n    )\n    eq = ICRS(\n        ra=ra*u.deg,\n        dec=dec*u.deg\n    )\n    altaz = eq.transform_to(altaz_frame)\n    return altaz\n# ============================================================= #\n\n\n# ============================================================= #\n# -------------------------- to_gal --------------------------- #\n# ============================================================= #\ndef to_gal(src):\n    \"\"\" Convert an astorpy source to galactic cooridnates\n    \"\"\"\n    return src.transform_to(Galactic)\n# ============================================================= #\n\n\n# ============================================================= #\n# -------------------------- to_gal --------------------------- #\n# ============================================================= #\ndef to_lmn(ra, dec, ra_0, dec_0):\n    \"\"\"\n    \"\"\"\n    ra = np.radians(ra)\n    dec = np.radians(dec)\n    ra_0 = np.radians(ra_0)\n    dec_0 = np.radians(dec_0)\n    ra_delta = ra - ra_0\n    l = np.cos(dec)*np.sin(ra_delta)\n    m = np.sin(dec)*np.cos(dec_0) - np.cos(dec)*np.sin(dec_0)*np.cos(ra_delta)\n    n = np.sqrt(1 - l**2 - m**2)\n    return l, m, n\n# ============================================================= #\n\n\n# ============================================================= #\n# -------------------------- rephase -------------------------- #\n# ============================================================= #\ndef rephase(ra, dec, time, loc, dw=False):\n    \"\"\"\n    \"\"\"\n    raz, decz = eq_zenith(\n        time=time,\n        location=loc\n        )\n    def rotMatrix(r, d):\n        \"\"\" r: ra in radians\n            d: dec in radians\n        \"\"\"\n        w = np.array([\n            [  np.sin(r)*np.cos(d) ,  np.cos(r)*np.cos(d) , np.sin(d) ]\n        ]).T\n        v = np.array([\n            [ -np.sin(r)*np.sin(d) , -np.cos(r)*np.sin(d) , np.cos(d) ]\n        ]).T\n        u = np.array([\n            [  np.cos(r)           , -np.sin(r)           , 0.        ]\n        ]).T\n        rot_matrix = np.concatenate([u, v, w], axis=-1)\n        return rot_matrix, w\n    final_trans, wnew = rotMatrix(\n        r=np.radians(ra),\n        d=np.radians(dec)\n    )\n    original_trans, wold = rotMatrix(\n        r=np.radians(raz),\n        d=np.radians(decz)\n    )\n    total_trans = np.dot(final_trans.T, original_trans)\n\n    if dw:\n        return total_trans, original_trans, final_trans, wold-wnew\n    else:\n        return total_trans\n# ============================================================= #\n\n\n# ============================================================= #\n# --------------------------- rotz ---------------------------- #\n# ============================================================= #\ndef rotz(array, angle):\n    \"\"\" Rotate the 3D array by an angle along z-axis\n    \"\"\"\n    ang = np.radians(angle)\n    cosa = np.cos(ang)\n    sina = np.sin(ang)\n    rot = np.array([\n            [cosa, -sina, 0],\n            [sina,  cosa, 0],\n            [   0,     0, 1]\n        ])\n    return np.dot(array, rot)\n# ============================================================= #\n\n\n# ============================================================= #\n# ------------------------ wavelength ------------------------- #\n# ============================================================= #\ndef wavelength(freq):\n    \"\"\" Convert between MHz and wavelength in meters\n\n        Returns\n        -------\n        wavelength : `np.ndarray`\n            Wavelength in meters\n    \"\"\"\n    if not hasattr(freq, '__len__'):\n        freq = [freq]\n    if not isinstance(freq, np.ndarray):\n        freq = np.array(freq)\n    freq *= u.MHz\n    freq = freq.to(u.Hz)\n    wavel = lspeed.value / freq.value\n    return wavel\n# ============================================================= #\n\n\n# ============================================================= #\n# ------------------------ ref_location ----------------------- #\n# ============================================================= #\ndef ref_location():\n    \"\"\"\n    \"\"\"\n    return EarthLocation(\n        lat=0*u.deg,\n        lon=-90*u.deg,\n        height=0*u.m\n    )\n# ============================================================= #\n\n\n# ============================================================= #\n# ----------------------- radio_sources ----------------------- #\n# ============================================================= #\ndef radio_sources(time):\n    \"\"\"\n    \"\"\"\n    if not isinstance(time, Time):\n        time = Time(time)\n\n    def solarsyst_eq(src, time):\n        src = get_body(\n            src,\n            time,\n            nenufar_loc()\n        )\n        return src.ra.deg, src.dec.deg\n\n    with solar_system_ephemeris.set('builtin'):\n        src_radec = {\n            'vir a': (187.70593075, +12.39112331),\n            'cyg a': (299.86815263, +40.73391583),\n            'cas a': (350.850000, +58.815000),\n            'her a': (252.783433, +04.993031),\n            'hyd a': (139.523546, -12.095553),\n            'tau a': (83.63308, +22.01450),\n            '3c 380': (277.3824220006990, +48.7461552266057),\n            'sun': solarsyst_eq('sun', time),\n            'moon': solarsyst_eq('moon', time),\n            'jupiter': solarsyst_eq('jupiter', time),\n        }\n    return src_radec\n# ============================================================= #\n\n\n# ============================================================= #\n# --------------------------- ateam --------------------------- #\n# ============================================================= #\ndef ateam():\n    \"\"\"\n    \"\"\"\n    src_radec = {\n        'vir a': (187.70593075, +12.39112331),\n        'cyg a': (299.86815263, +40.73391583),\n        'cas a': (350.850000, +58.815000),\n        'her a': (252.783433, +04.993031),\n        'hyd a': (139.523546, -12.095553),\n        'tau a': (83.63308, +22.01450),\n        '3c 380' : (277.3824220006990, +48.7461552266057)\n    }\n    return src_radec\n# ============================================================= #\n\n\n# ============================================================= #\n# ------------------------- AstroPlot ------------------------- #\n# ============================================================= #\nclass AstroPlot(object):\n    \"\"\"\n    \"\"\"\n    def __init__(self, image, center, resol):\n        self.npix_x = None\n        self.npix_y = None\n        self.image = image\n        self.center = center\n        self.resol = resol\n\n        self.wcs = WCS(naxis=2)\n        self.wcs.wcs.crpix = [self.npix_x/2, self.npix_y/2]\n        self.wcs.wcs.cdelt = np.array([self.resol, self.resol])\n        self.wcs.wcs.crval = [self.center[0], self.center[1]]\n        #self.wcs.wcs.ctype = ['RA---AIR', 'DEC--AIR']\n        self.wcs.wcs.ctype = ['RA---TAN', 'DEC--TAN']\n\n    @property\n    def image(self):\n        return self._image\n    @image.setter\n    def image(self, i):\n        if not len(i.shape) == 2:\n            raise ValueError(\n                'Weird image format.'\n            )\n        self.npix_x = i.shape[0]\n        self.npix_y = i.shape[1]\n        self._image = i\n        return\n\n    @property\n    def center(self):\n        return self._center\n    @center.setter\n    def center(self, c):\n        if not isinstance(c, tuple):\n            raise TypeError(\n                'center should be a tuple'\n            )\n        if not len(c) == 2:\n            raise ValueError(\n                'center should be a length-2 tuple'\n            )\n        self._center = c\n        return\n\n    def plot(self, title='', cblabel='', sources=True, time=None, filename=None, circle=None, **kwargs):\n        \"\"\"\n        \"\"\"\n        if 'cmap' not in kwargs.keys():\n            kwargs['cmap'] = 'YlGnBu_r'\n        if 'vmin' not in kwargs.keys():\n            kwargs['vmin'] = self.image.min()\n        if 'vmax' not in kwargs.keys():\n            kwargs['vmax'] = self.image.max()\n        \n        cbar = True\n        if 'cbar' in kwargs.keys():\n            cbar = kwargs['cbar']\n            del kwargs['cbar']\n\n        import matplotlib.pyplot as plt\n        from matplotlib.colorbar import ColorbarBase\n        from matplotlib.ticker import LinearLocator\n        from matplotlib.colors import Normalize\n        from matplotlib.cm import get_cmap\n        from mpl_toolkits.axes_grid1.inset_locator import inset_axes\n        from astropy.visualization.wcsaxes import SphericalCircle\n        \n        fig = plt.figure(figsize=(7, 7))\n        ax = plt.subplot(projection=self.wcs)\n        im = ax.imshow(\n            self.image,\n            origin='lower',\n            interpolation='nearest',\n            **kwargs\n        )\n\n        ax.coords.grid(True, color='white', ls='solid', alpha=0.5)\n        axra = ax.coords[0]\n        axdec = ax.coords[1]\n        axra.set_axislabel('RA')\n        axra.set_major_formatter('d')\n        axra.set_ticks(number=10)\n        axdec.set_axislabel('Dec')\n        axdec.set_major_formatter('d')\n        axdec.set_ticks(number=10)\n\n        if cbar:\n            cax = inset_axes(ax,\n               width='5%',\n               height='100%',\n               loc='lower left',\n               bbox_to_anchor=(1.05, 0., 1, 1),\n               bbox_transform=ax.transAxes,\n               borderpad=0,\n               )\n            cb = ColorbarBase(\n                cax,\n                cmap=get_cmap(name='YlGnBu_r'),\n                orientation='vertical',\n                norm=Normalize(vmin=kwargs['vmin'], vmax=kwargs['vmax']),\n                ticks=LinearLocator()\n            )\n            cb.solids.set_edgecolor('face')\n            cb.set_label(cblabel)\n            cb.formatter.set_powerlimits((0, 0))\n\n        if sources:\n            phase_center = radec(\n                ra=self.center[0],\n                dec=self.center[1]\n            )\n            if time is None:\n                time = Time.now()\n            srcs = radio_sources(time=time)\n            for k in srcs.keys():\n                src = radec(\n                    ra=srcs[k][0],\n                    dec=srcs[k][1]\n                )\n                if phase_center.separation(src).deg > self.npix_x/2 * self.resol:\n                    # Source not in FoV\n                    continue\n                ax.text(\n                    src.ra.deg,\n                    src.dec.deg,\n                    k.title(),\n                    transform=ax.get_transform('icrs'),\n                    color='white'\n                )\n\n        if circle is not None:\n            r1 = SphericalCircle(\n               center=(circle[0] * u.deg, circle[1] * u.deg),\n               radius=circle[2]/2 * u.deg,\n               resolution=100,\n               edgecolor='white',\n               facecolor='none',\n               transform=ax.get_transform('icrs')\n            )\n            ax.add_patch(r1)\n            r2 = SphericalCircle(\n               center=(circle[0] * u.deg, circle[1] * u.deg),\n               radius=circle[2] * u.deg,\n               resolution=100,\n               edgecolor='white',\n               linestyle=':',\n               facecolor='none',\n               transform=ax.get_transform('icrs')\n            )\n            ax.add_patch(r2)\n\n        ax.set_title(title)\n        # plt.tight_layout()\n        \n        if filename is None:\n            plt.show()\n        else:\n            plt.savefig(filename, dpi=300)\n        return\n\n    def savefits(self, fitsname, time=None, freq=None):\n        \"\"\"\n        \"\"\"\n        header = self.wcs.to_header()\n        hdu = fits.PrimaryHDU(self.image.data, header=header)\n        hdu.writeto(fitsname, overwrite=True)\n        fits.setval(fitsname, 'INSTRU', value='NenuFAR')\n        fits.setval(fitsname, 'SOFTWARE', value='nenupytv')\n        fits.setval(fitsname, 'VERSION', value=nenupytv.__version__)\n        fits.setval(fitsname, 'TIME', value=time.isot, comment='Time in UTC')\n        fits.setval(fitsname, 'FREQUENC', value=freq, comment='Mean frequency in MHz')\n        fits.setval(fitsname, 'STOKES', value='I')\n        fits.setval(fitsname, 'CONTACT', value='alan.loh@obspm.fr')\n        return\n\n# ============================================================= #\n\n\n    \n\n# ============================================================= #\n# ------------------------ astro_image ------------------------ #\n# ============================================================= #\ndef astro_image(\n        image,\n        center,\n        npix,\n        resol,\n        time,\n        freq=None,\n        pngfile=None,\n        fitsfile=None,\n        show_sources=False,\n        colorbar=False,\n        gal_plane=False,\n        **kwargs):\n    \"\"\"\n    \"\"\"\n    import matplotlib.pyplot as plt\n    # if 'vmin' not in kwargs.keys():\n    #     kwargs['vmin'] = np.percentile(specdata.amp, 5)\n    # if 'vmax' not in kwargs.keys():\n    #     kwargs['vmax'] = np.percentile(specdata.amp, 95)\n    if 'cmap' not in kwargs.keys():\n        kwargs['cmap'] = 'YlGnBu_r'\n\n    w = WCS(naxis=2)\n    w.wcs.crpix = [npix/2, npix/2]\n    w.wcs.cdelt = np.array([resol, resol])\n    w.wcs.crval = [center[0], center[1]]\n    w.wcs.ctype = ['RA---AIR', 'DEC--AIR']\n\n    fig = plt.figure(figsize=(10, 10))\n    ax = plt.subplot(projection=w)\n    im = ax.imshow(\n        image,\n        origin='lower',\n        aspect='equal',\n        interpolation='none',\n        **kwargs\n    )\n    if colorbar:\n        plt.colorbar(im, ax=ax)\n\n    ax.coords.grid(True, color='white', ls='solid', alpha=0.5)\n    axra = ax.coords[0]\n    axdec = ax.coords[1]\n    axra.set_axislabel('RA')\n    axra.set_major_formatter('d')\n    axra.set_ticks(number=10)\n    axdec.set_axislabel('Dec')\n    axdec.set_major_formatter('d')\n    axdec.set_ticks(number=10)\n\n    # if sources:\n    #     from astroquery.vizier import Vizier\n    #     from astropy.coordinates import SkyCoord\n    #     import astropy.units as un\n    #     Vizier.ROW_LIMIT = -1\n    #     catalog_list = Vizier.find_catalogs('VIII/1A')\n    #     catalogs = Vizier.get_catalogs(catalog_list.keys())\n    #     cat_3c = catalogs[0]\n    #     ra_zen = center[0]\n    #     dec_zen = center[1]\n    #     zenith = SkyCoord(ra_zen * un.deg, dec_zen * un.deg)\n    #     maxjy = np.max(np.log10(cat_3c['S159MHz']))\n    #     for i in range(len(cat_3c)):\n    #         src_3c = SkyCoord(\n    #             cat_3c['RA1950'][i],\n    #             cat_3c['DE1950'][i],\n    #             unit=(un.hourangle, un.deg),\n    #             equinox='B1950'\n    #         )\n    #         if zenith.separation(src_3c).deg < 32:\n    #             ax.scatter(\n    #                 src_3c.ra.deg,\n    #                 src_3c.dec.deg,\n    #                 transform=ax.get_transform('icrs'),\n    #                 s=np.log10(cat_3c['S159MHz'][i])/maxjy * 500,\n    #                 edgecolor='white',\n    #                 facecolor='none',\n    #                 #alpha=np.log10(cat_3c['S159MHz'][i])/maxjy\n    #             )\n    if show_sources:\n        phase_center = radec(\n            ra=center[0],\n            dec=center[1]\n        )\n\n        srcs = radio_sources(time=time)\n\n        for k in srcs.keys():\n            src = radec(\n                ra=srcs[k][0],\n                dec=srcs[k][1]\n            )\n            if phase_center.separation(src).deg > npix/2 * resol:\n                # Source not in FoV\n                continue\n            # ax.scatter(\n            #     src.ra.deg,\n            #     src.dec.deg,\n            #     s=100,\n            #     transform=ax.get_transform('icrs'),\n            #     edgecolor='white',\n            #     facecolor='none',\n            # )\n            ax.text(\n                src.ra.deg,\n                src.dec.deg,\n                k.title(),\n                transform=ax.get_transform('icrs'),\n                color='white'\n            )\n\n    if pngfile is None:\n        plt.show()\n    else:\n        plt.title('{}'.format(time.iso))\n        #plt.tight_layout()\n        plt.savefig(pngfile, **kwargs)\n\n    if fitsfile is not None:\n        fitsfile = path.join(fitsfile, 'nenufartv_{}.fits'.format(time.isot.split('.')[0].replace(':', '-')))\n        header = w.to_header()\n        hdu = fits.PrimaryHDU(image, header=header)\n        hdu.writeto(fitsfile, overwrite=True)\n        fits.setval(fitsfile, 'INSTRU', value='NenuFAR')\n        fits.setval(fitsfile, 'SOFTWARE', value='nenupytv')\n        fits.setval(fitsfile, 'VERSION', value=nenupytv.__version__)\n        fits.setval(fitsfile, 'TIME', value=time.isot, comment='Time in UTC')\n        fits.setval(fitsfile, 'FREQUENC', value=freq, comment='Mean frequency in MHz')\n        fits.setval(fitsfile, 'STOKES', value='I')\n        fits.setval(fitsfile, 'CONTACT', value='alan.loh@obspm.fr')\n# ============================================================= #\n\n", "meta": {"hexsha": "b8296dce10a2bbda25b0b9c87878f8abfdb7bf50", "size": 26285, "ext": "py", "lang": "Python", "max_stars_repo_path": "nenupytv/astro/astro.py", "max_stars_repo_name": "AlanLoh/nenupy-tv", "max_stars_repo_head_hexsha": "9c33652521293eaba726f02fdb2331ae32dda6f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nenupytv/astro/astro.py", "max_issues_repo_name": "AlanLoh/nenupy-tv", "max_issues_repo_head_hexsha": "9c33652521293eaba726f02fdb2331ae32dda6f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2019-11-12T09:48:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-28T17:02:54.000Z", "max_forks_repo_path": "nenupytv/astro/astro.py", "max_forks_repo_name": "AlanLoh/nenupy-tv", "max_forks_repo_head_hexsha": "9c33652521293eaba726f02fdb2331ae32dda6f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-09T17:40:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-09T17:40:58.000Z", "avg_line_length": 30.4577056779, "max_line_length": 109, "alphanum_fraction": 0.4182233213, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 5904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.182489376508854}}
{"text": "#!/usr/bin/env python\n#\n# correlate.py - The CorrelateAction class.\n#\n# Author: Paul McCarthy <pauldmccarthy@gmail.com>\n#\n\"\"\"This module provides the :class:`.PearsonCorrelateAction` class, which is\nan :class:`.Action` that calculates seed-based correlation on 4D\n:class:`.Image` overlays.\n\"\"\"\n\n\nimport threading\nimport logging\n\nimport numpy                  as np\nimport scipy.spatial.distance as spd\n\nimport fsl.data.image               as fslimage\nimport fsl.utils.idle               as idle\nimport fsleyes_props                as props\nimport fsleyes.views.orthopanel     as orthopanel\nimport fsleyes_widgets.utils.status as fslstatus\nimport fsleyes.strings              as strings\nimport fsleyes.actions.base         as base\n\n\nlog = logging.getLogger(__name__)\n\n\nclass CorrelateAction(base.Action):\n    \"\"\"The ``CorrelateAction`` is a base class for the\n    :class:`PearsonCorrelateAction` and :class:`PCACorrelateAction` classes,\n    which manages adding/removing correlation overlays to/from the\n    :class:`.OverlayList`, and manages execution of the correlation.\n\n\n    When a 4D :class:`.Image` is selected and the ``CorrelateAction`` is\n    invoked, a new 3D :class:`.Image` is created and added to the\n    :class:`.OverlayList` - this image is referred to as a *correlate overlay*,\n    and is used to store and display the correlation values.\n    \"\"\"\n\n\n    @staticmethod\n    def supportedViews():\n        \"\"\"The ``CorrelateAction`` is restricted for use with\n        :class:`.OrthoPanel` views.\n        \"\"\"\n        return [orthopanel.OrthoPanel]\n\n\n    @staticmethod\n    def ignoreTool():\n        \"\"\"Tells the FSLeyes plugin system not to add the ``CorrelateAction``\n        class as an option to the FSLeyes toolsmenu.  Instead, the\n        :class:`PearsonCorrelateAction` action (and other potential future\n        sub-classes) is added.\n        \"\"\"\n        return True\n\n\n    def __init__(self, overlayList, displayCtx, panel):\n        \"\"\"Create a ``CorrelateAction``.\n\n        :arg overlayList: The :class:`.OverlayList`.\n        :arg displayCtx:  The :class:`.DisplayContext`.\n        :arg panel:       The :class:`.OrthoPanel` that owns this action.\n        \"\"\"\n\n        base.Action.__init__(\n            self, overlayList, displayCtx, self.__runCorrelateAction)\n\n        self.__panel = panel\n        self.__name  = '{}_{}'.format(type(self).__name__, id(self))\n\n        displayCtx .addListener('selectedOverlay',\n                                self.__name,\n                                self.__selectedOverlayChanged)\n        overlayList.addListener('overlays',\n                                self.__name,\n                                self.__overlayListChanged)\n\n        # TODO Use a single data structure -\n        #      using two dicts is fragile\n        self.__correlateOverlays = {}\n        self.__overlayCorrelates = {}\n\n        # The runCorrelateAction cannot be called\n        # more than once at a time - this is used\n        # as a semaphore to ensure that this is\n        # enforced.\n        self.__correlateFlag = threading.Event()\n\n        self.__selectedOverlayChanged()\n\n\n    def destroy(self):\n        \"\"\"Removes listeners from the :class:`.DisplayContext` and\n        :class:`.OverlayList`, and calls :meth:`.Action.destroy`.\n        \"\"\"\n        if self.destroyed:\n            return\n\n        self.displayCtx .removeListener('selectedOverlay', self.__name)\n        self.overlayList.removeListener('overlays',        self.__name)\n        base.Action.destroy(self)\n\n        self.__correlateOverlays = None\n        self.__overlayCorrelates = None\n\n\n    def __selectedOverlayChanged(self, *a):\n        \"\"\"Called when the selected overlay, or overlay list, changes.\n\n        Enables/disables this action depending on the nature of the selected\n        overlay.\n        \"\"\"\n\n        ovl          = self.displayCtx.getSelectedOverlay()\n        isCorrOvl    = ovl in self.__overlayCorrelates\n\n        self.enabled = isCorrOvl or  \\\n                       ((ovl is not None)               and\n                        isinstance(ovl, fslimage.Image) and\n                        ovl.ndim > 3)\n\n\n    def __overlayListChanged(self, *a):\n        \"\"\"Called when the :class:`.OverlayList` changes. Makes sure that\n        there are no obsolete correlate overlays in the list, and calls\n        :meth:`__selectedOverlayChanged`.\n        \"\"\"\n        self.__clearCorrelateOverlays()\n        self.__selectedOverlayChanged()\n\n\n    def __clearCorrelateOverlays(self):\n        \"\"\"Called by :meth:`__overlayListChanged`. Clears internal references\n        to any obsolete correlate overlays.\n        \"\"\"\n\n        for overlay, corrOvl in list(self.__correlateOverlays.items()):\n            if overlay not in self.overlayList or \\\n               corrOvl not in self.overlayList:\n                self.__correlateOverlays.pop(overlay)\n                self.__overlayCorrelates.pop(corrOvl)\n\n\n    def __createCorrelateOverlay(self, overlay, data):\n        \"\"\"Creates a *correlate* overlay for the given ``overlay``, adds\n        it to the :class:`.OverlayList`, and initialises some display\n        properties.\n        \"\"\"\n\n        display = self.displayCtx.getDisplay(overlay)\n        name    = '{}/correlation'.format(display.name)\n        corrOvl = fslimage.Image(data, name=name, header=overlay.header)\n\n        self.overlayList.append(corrOvl, overlayType='volume')\n        self.__correlateOverlays[overlay] = corrOvl\n        self.__overlayCorrelates[corrOvl] = overlay\n\n        corrOpts = self.displayCtx.getOpts(corrOvl)\n\n        with props.suppressAll(corrOpts), \\\n             props.suppressAll(display):\n            corrOpts.cmap              = 'red-yellow'\n            corrOpts.negativeCmap      = 'blue-lightblue'\n            corrOpts.useNegativeCmap   = True\n            corrOpts.displayRange      = [0.05, 1]\n            corrOpts.clippingRange.xlo = 0.05\n\n        return corrOvl\n\n\n    def __runCorrelateAction(self):\n        \"\"\"Called when this :class:`.Action` is invoked. Calculates correlation\n        values from the voxel at the current :attr:`.DisplayContext.location`\n        (relative to the currently selected overlay) to all other voxels, and\n        updates the correlate overlay.\n\n        The correlation calculation and overlay update is performed on a\n        separate thread (via :meth:`.idle.run`), with a call to\n        :meth:`calculateCorrelation`.\n        \"\"\"\n\n        # Because of the multi-threaded/asynchronous\n        # way that this function does its job,\n        # allowing it to be called multiple times\n        # before prior calls have completed would be\n        # very dangerous indeed.\n        if self.__correlateFlag.is_set():\n            log.debug('Correlate action is already '\n                      'running - ignoring request')\n            return\n\n        # See if a correlate overlay already exists\n        # for the currently selected overlay\n        ovl     = self.displayCtx.getSelectedOverlay()\n        corrOvl = self.__correlateOverlays.get(ovl, None)\n\n        # If not, check to see if it is a correlate\n        # overlay that is selected and, if it is,\n        # look up the corresponding source overlay.\n        if corrOvl is None:\n            if ovl in self.__overlayCorrelates:\n                corrOvl = ovl\n                ovl     = self.__overlayCorrelates[corrOvl]\n\n        # If corrOvl is still None, it means that\n        # there is no correlate overlay for the\n        # currently selected overlay. In this case,\n        # we'll create a new correlate overlay and\n        # add it to the overlay list after the\n        # correlation values have been calculated.\n\n        opts = self.displayCtx.getOpts(ovl)\n        xyz  = opts.getVoxel(vround=True)\n\n        if xyz is None:\n            return\n\n        data = ovl.data[opts.index(atVolume=False)]\n\n        # The correlation calculation is performed\n        # on a separate thread. This thread then\n        # schedules a function on idle.idle to\n        # update the correlation overlay back on the\n        # main thread.\n        def calcCorr():\n\n            correlations = self.calculateCorrelation(xyz, data)\n\n            # The correlation overlay is updated/\n            # created on the main thread.\n            def update():\n\n                try:\n\n                    # A correlation overlay already\n                    # exists for the source overlay\n                    # - update its data\n                    if corrOvl is not None:\n                        corrOvl[:] = correlations\n\n                    # The correlation overlay hasn't\n                    # been created yet - create a\n                    # new overlay with the correlation\n                    # values.\n                    else:\n                        self.__createCorrelateOverlay(ovl, correlations)\n\n                finally:\n                    fslstatus.clearStatus()\n                    self.__correlateFlag.clear()\n\n            idle.idle(update)\n\n        # Protect against more calls\n        # while this job is running.\n        self.__correlateFlag.set()\n        fslstatus.update(strings.messages[self, 'calculating'].format(*xyz))\n        idle.run(calcCorr)\n\n\n    def calculateCorrelation(self, seed, data):\n        \"\"\"Calculates correlation values between the given ``seed`` voxel (an\n        ``(x, y, z)`` tuple) and all other voxels. This method must be\n        implemented by sub-classes.\n\n        :arg seed: An ``(x, y, z)`` tuple specifying the seed voxel\n\n        :arg data: A 4D ``numpy`` array containing all of the data.\n\n        :returns:  A 3D ``numpy`` array containing the correlation values.\n        \"\"\"\n        raise NotImplementedError('calculateCorrelation must be '\n                                  'implemented by sub-classes')\n\n\nclass PearsonCorrelateAction(CorrelateAction):\n    \"\"\"The ``PearsonCorrelateAction`` is a :class:`CorrelateAction` which\n    calculates Pearson correlation coefficient values between the seed voxel\n    and all other voxels.\n    \"\"\"\n\n    def calculateCorrelation(self, seed, data):\n        \"\"\"Calculates Pearson correlation between the data at the specified\n        seed voxel, and all other voxels.\n        \"\"\"\n        return pearsonCorrelation(seed, data)\n\n\ndef pearsonCorrelation(seed, data):\n    \"\"\"Calculates Pearson correlation between the data at the specified\n    seed voxel, and all other voxels.\n    \"\"\"\n\n    x, y, z = seed\n    npoints = data.shape[3]\n\n    # the scipy.spatial.distance.cdist\n    # function can be used to calculate\n    # one-to-many correlation values.\n    with np.errstate(invalid='ignore'):\n        correlations = 1 - spd.cdist(\n            data[x, y, z, :].reshape( 1, npoints),\n            data            .reshape(-1, npoints),\n            metric='correlation')\n\n    # Set any nans to 0\n    correlations[np.isnan(correlations)] = 0\n\n    return correlations.reshape(data.shape[:3])\n", "meta": {"hexsha": "b6ea8b71a7bcd079110905a495d603bb3ed56b2f", "size": 10873, "ext": "py", "lang": "Python", "max_stars_repo_path": "fsleyes/plugins/tools/correlate.py", "max_stars_repo_name": "pauldmccarthy/fsleyes", "max_stars_repo_head_hexsha": "453a6b91ec7763c39195814d635257e3766acf83", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2018-05-05T01:36:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T20:44:08.000Z", "max_issues_repo_path": "fsleyes/plugins/tools/correlate.py", "max_issues_repo_name": "pauldmccarthy/fsleyes", "max_issues_repo_head_hexsha": "453a6b91ec7763c39195814d635257e3766acf83", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 97, "max_issues_repo_issues_event_min_datetime": "2018-05-05T02:17:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T14:58:42.000Z", "max_forks_repo_path": "fsleyes/plugins/tools/correlate.py", "max_forks_repo_name": "pauldmccarthy/fsleyes", "max_forks_repo_head_hexsha": "453a6b91ec7763c39195814d635257e3766acf83", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-12-09T09:02:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-05T18:55:13.000Z", "avg_line_length": 34.4082278481, "max_line_length": 79, "alphanum_fraction": 0.6128943254, "include": true, "reason": "import numpy,import scipy", "num_tokens": 2430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.18248796547631738}}
{"text": "#Copyright (c) 2009,2010 George Dahl\n\nimport numpy as num\n\nimport cudamat as cm\nfrom cudamat import reformat\nfrom singleSoftmax import maskedSingleSoftmax\n\ndef getFilteringDist(net, data, index, preSigmoid = False):\n    \"\"\"\n    We use this name to correspond more closely to Graham's matlab\n    code.  This function sends the visible data stored in data through\n    net to produce hidden unit activations for every valid position of\n    net.  The valid positions are given by index.\n    \"\"\"\n    assert(len(index.shape)==1)\n    pred = []\n    \n    numcases = index.shape[0]\n    num_mini_batches = numcases / net.mbsz\n    excess = numcases - num_mini_batches*net.mbsz\n    \n    for mb in range(num_mini_batches):\n        mbIdx = index[ mb*net.mbsz:(mb+1)*net.mbsz ]\n        net.vis = cm.CUDAMatrix(reformat(data[:,mbIdx]))\n        net.past = [ cm.CUDAMatrix(reformat(data[:,mbIdx-i-1])) for i in range(net.numPrev) ]\n\n        if preSigmoid:\n            net.hidNetInpts()\n        else:\n            net.hidActProbs()\n        net.hActProbs.copy_to_host()\n        pred.append(net.hActProbs.numpy_array.copy())\n    if excess > 0:\n        batch = num.zeros(net.vis.shape)\n        mbIdx = index[ num_mini_batches*net.mbsz:]\n        batch[:,:excess] = data[:,mbIdx]\n        net.vis = cm.CUDAMatrix(reformat(batch))\n        net.past = []\n        for i in range(net.numPrev):\n            batch[:,:excess] = data[:,mbIdx-i-1]\n            net.past.append(cm.CUDAMatrix(reformat(batch)))\n        if preSigmoid:\n            net.hidNetInpts()\n        else:\n            net.hidActProbs()\n        net.hActProbs.copy_to_host()\n        pred.append(net.hActProbs.numpy_array.copy()[:,:excess])\n            \n    return num.hstack(pred)\n\nclass GaussianCRBM(object):\n    def __init__(self, numVis, numHid, prevFrames, initHidBias = 0.0):\n        self.numVis, self.numHid, self.numPrev = numVis, numHid, prevFrames\n        self._mbsz = 256\n        \n        self.visToHid = 0.1*num.random.randn(numVis, numHid)\n        self.visBias = num.zeros((numVis, 1))\n        self.hidBias = num.zeros((numHid, 1)) + initHidBias\n        \n        #self.A[0] and self.B[0] are the weights from the most recent frame\n        self.A = [0.01*num.random.randn(numVis, numVis) for i in range(self.numPrev)]\n        self.B = [0.01*num.random.randn(numVis, numHid)  for i in range(self.numPrev)]\n        \n        self.init_weight_storage()\n        \n        self.initTemporary()\n\n        #will be used for L1 reg and allocated at that point\n        self.signVisToHid = None\n        self.signA = None\n        self.signB = None\n        \n        #set default learning parameters:\n        self.setLearningParams()\n        \n        #total GPU storage costs excluding input data (self.past and self.vis):\n        # 2W + 2*numHid*mbsz+2*numVis*mbsz\n        #where W is the total space cost of all the weights of the model\n\n    def setLearningParams(self, learnRate = 0.001, momentum = 0.9, weightCost = 0, regType = \"L2\", cdSteps = 1, \\\n                          pastNoise = 0, arWeightCost = None):\n        self.learnRate = learnRate\n        self.momentum = momentum\n        self.weightCost = weightCost\n        self.regType = regType\n        self.cdSteps = cdSteps\n        self.pastNoise = pastNoise\n        self.arWeightCost = arWeightCost\n    \n    def getMBSZ(self):\n        return self._mbsz\n    \n    def setMBSZ(self, newMBSZ):\n        self._mbsz = newMBSZ\n        self.initTemporary()\n    mbsz = property(getMBSZ,setMBSZ)\n    \n    def initTemporary(self):\n        self.hActs = cm.CUDAMatrix(reformat(num.zeros((self.numHid, self.mbsz))))\n        self.hActProbs = cm.CUDAMatrix(reformat(num.zeros((self.numHid, self.mbsz))))\n        self.negVis = cm.CUDAMatrix(reformat(num.zeros((self.numVis, self.mbsz))))\n        self.tempVisMB = cm.CUDAMatrix(reformat(num.zeros((self.numVis, self.mbsz))))\n        self.dynamicHidBias = cm.CUDAMatrix(reformat(num.zeros((self.numHid, self.mbsz))))\n        self.dynamicVisBias = cm.CUDAMatrix(reformat(num.zeros((self.numVis, self.mbsz))))\n    \n    def init_weight_storage(self):\n        \"\"\"\n        Initialize storage for gradients and gradient steps and build a list of\n        weight/gradient/energy gradient/step tuples.\n        \"\"\"\n        for name in self.weightVariableNames():\n            w = self.__dict__[name]\n            if not isinstance(w, list):\n                self.__dict__[name] = cm.CUDAMatrix(reformat(w))\n                self.__dict__[\"d\"+name] = cm.CUDAMatrix(reformat(0.0 * w))\n            else:\n                self.__dict__[name] = [cm.CUDAMatrix(reformat(x)) for x in w]\n                self.__dict__[\"d\"+name] = [cm.CUDAMatrix(reformat(0.0*part)) for part in w]\n    \n    def scaleDerivs(self, factor):\n        \"\"\"\n        Scales all weight derivatives by factor (used to apply\n        momentum or clear the weight derivatives).\n        \"\"\"\n        for name in self.weightVariableNames():\n            w = self.__dict__[name]\n            if not isinstance(w, list):\n                self.__dict__[\"d\"+name].mult_by_scalar(factor)\n            else:\n                for i in range(len(w)):\n                    self.__dict__[\"d\"+name][i].mult_by_scalar(factor)\n    \n    def pack_weights(self):\n        w_dict = {}\n        for w_name in self.weightVariableNames():\n            w = self.__dict__[w_name]\n            if isinstance(w, list):\n                for part in w:\n                    part.copy_to_host()\n                w_dict[w_name] = [part.numpy_array for part in w]\n            else:\n                w.copy_to_host()\n                w_dict[w_name] = w.numpy_array\n        return w_dict\n\n    def loadWeights(self, wDict):\n        \"\"\"\n        This code is terrible.\n        \"\"\"\n        assert(all(wName in wDict for wName in self.weightVariableNames()))\n        for w_name in wDict:\n            if w_name in self.weightVariableNames():\n                w = wDict[w_name]\n                if isinstance(w, list) or w_name in [\"A\",\"B\"]:\n                    assert( all(self.__dict__[w_name][i].numpy_array.shape == wDict[w_name][i].shape for i in range(len(wDict[w_name])) ) )\n                    self.__dict__[w_name] = [cm.CUDAMatrix(reformat(part)) for part in w]\n                else:\n                    assert( self.__dict__[w_name].numpy_array.shape == wDict[w_name].shape )\n                    self.__dict__[w_name] = cm.CUDAMatrix(reformat(w))\n    \n    def curRecErr(self):\n        self.vis.subtract(self.negVis, target = self.tempVisMB)\n        return self.tempVisMB.euclid_norm()**2\n    \n    def allWeightsMatlabFormat(self):\n        weights = self.pack_weights()\n        d = {}\n        d[\"w\"] = weights[\"visToHid\"].transpose()\n        d[\"bi\"] = weights[\"visBias\"]\n        d[\"bj\"] = weights[\"hidBias\"]\n\n        #this chunk of code depends on scipy version >= 8 so savemat works right\n        d[\"A\"] = num.empty( (self.numVis, self.numVis, self.numPrev) )\n        d[\"B\"] = num.empty( (self.numHid, self.numVis, self.numPrev) )\n        for i in range(self.numPrev):\n            d[\"A\"][:,:,i] = weights[\"A\"][i].transpose()\n            d[\"B\"][:,:,i] = weights[\"B\"][i].transpose()\n\n        \n        #for i in range(self.numPrev):\n        #    d[\"A%d\" % i] = weights[\"A\"][i].transpose()\n        #    d[\"B%d\" % i] = weights[\"B\"][i].transpose()\n\n        return d\n    \n    def sampleHiddens(self, hActProbsOnGPU = None):\n        if hActProbsOnGPU == None:\n            hActProbsOnGPU = self.hActProbs\n        self.hActs.fill_with_rand()\n        self.hActs.less_than(hActProbsOnGPU, target = self.hActs)\n\n    def hidNetInpts(self, recomputeDynamicBias = True, targ = None, vis = None):\n        \"\"\"\n        targ had better be on the gpu or None\n        \"\"\"\n        if recomputeDynamicBias:\n            self.updateDynamicHidBias()\n\n        if targ == None:\n            targ = self.hActProbs\n        if vis == None:\n            vis = self.vis\n        \n        cm.dot( self.visToHid.T, vis, target = targ)\n        targ.add(self.dynamicHidBias)\n        targ.add_col_vec(self.hidBias)\n\n    def hidActProbs(self, recomputeDynamicBias = True, targ = None, vis = None):\n        \"\"\"\n        targ had better be on the gpu or None\n        \"\"\"\n        if targ == None:\n            targ = self.hActProbs\n        self.hidNetInpts(recomputeDynamicBias, targ, vis)\n        targ.apply_sigmoid()\n    \n    def updateDynamicHidBias(self):\n        self.dynamicHidBias.mult_by_scalar(0.0)\n        for i in range(len(self.B)):\n            #self.past[i] is the (i+1)-steps delayed frame of history\n            #self.past[i] is numVis by mbsz\n            #self.B[i] is numVis by numHid\n            self.dynamicHidBias.add_dot(self.B[i].T, self.past[i])\n        \n    def updateDynamicVisBias(self):\n        self.dynamicVisBias.mult_by_scalar(0.0)\n        for i in range(len(self.A)):\n            self.dynamicVisBias.add_dot(self.A[i].T, self.past[i])\n    \n    def visActProbs(self, recomputeDynamicBias):\n        \n        if recomputeDynamicBias:\n            self.updateDynamicVisBias()\n        \n        cm.dot( self.visToHid, self.hActs, target = self.negVis)\n        self.negVis.add(self.dynamicVisBias)\n        self.negVis.add_col_vec(self.visBias)\n        \n    def weightVariableNames(self):\n        \"\"\"\n        Returns the names of the variables for the weights that define\n        this model in a cannonical order.  The order must match up\n        with the way weight derivatives get returned from CDn.\n        \"\"\"\n        return \"visToHid\", \"hidBias\", \"visBias\", \"A\", \"B\"\n    \n    def CDStats(self, vis, past, hid, posPhase):\n        \"\"\"\n        hid should be self.numHid by mbsz and exist on the GPU\n        vis should be self.numVis by mbsz and exist on the GPU\n        past should be a length self.numPrev list of variables like vis\n\n        This function depends on self.dynamicVisBias being up to date!!\n\n        We modify self.d$WEIGHT_NAME as a side effect and clobber self.tempVisMB.\n        \"\"\"\n        vis.subtract(self.dynamicVisBias, target = self.tempVisMB)\n        self.tempVisMB.add_col_mult(self.visBias, -1.0) #so we are subtracting, not adding\n\n        multiplier = 1.0 if posPhase else -1.0\n        \n        self.dhidBias.add_sums(hid, 1, mult = multiplier)\n        self.dvisBias.add_sums(vis, 1, mult = multiplier)\n        \n        if posPhase:    \n            self.dvisToHid.add_dot(vis, hid.T)\n            \n            for i in range(self.numPrev):\n                self.dA[i].add_dot( past[i], self.tempVisMB.T )\n                self.dB[i].add_dot( past[i], hid.T )\n        else:\n            self.dvisToHid.subtract_dot(vis, hid.T)\n            \n            for i in range(self.numPrev):\n                self.dA[i].subtract_dot( past[i], self.tempVisMB.T )\n                self.dB[i].subtract_dot( past[i], hid.T )\n        \n            \n    def CDn(self):\n        \"\"\"\n        After this function runs we will have the negative data in\n        self.negVis and self.hActProbs will hold the final hidden\n        activation probabilities conditioned on the negative data.\n        \n        This function updates the weight derivative variables.\n        \"\"\"\n        #we depend on the following two learning parameters\n        n = self.cdSteps\n        momentum = self.momentum\n\n        #apply momentum\n        self.scaleDerivs(momentum)\n        \n        #stores hidden activation probabilities in self.hActProbs and sets dynamic hidden biases \n        self.hidActProbs()\n\n        self.updateDynamicVisBias() #CDStats depends on self.dynamicVisBias being correct\n        \n        #compute positive phase statistics and add them to gradient variables\n        self.CDStats(self.vis, self.past, self.hActProbs, True)\n        \n        \n        for i in range(n):\n            #updates self.hActs\n            self.sampleHiddens(self.hActProbs)\n            \n            #updates self.negVis and if i == 0 computes self.dynamicVisBias\n            self.visActProbs(False) #no need to recompute self.dynamicVisBias\n            \n            #stores recomputed (based on self.negVis) hidden act probs in self.hActProbs\n            self.hidActProbs(False, vis = self.negVis)\n\n        #compute negative phase statistics and subtract them from gradient variables\n        self.CDStats(self.negVis, self.past, self.hActProbs, False)\n        \n    \n    def reformatLearningRates(self, learnRate):\n        if isinstance(learnRate, dict):\n            assert( all(name in learnRate for name in self.weightVariableNames() ) )\n            return learnRate\n        rates = {}\n        assert( type(learnRate) == float or type(learnRate) == int )\n        for name in self.weightVariableNames():\n            rates[name] = learnRate\n        return rates\n\n    def updateSignOfWeights(self):\n        \"\"\"\n        We need the sign of the weights for L1 regularization.  Since\n        we work on the GPU it is convenient to just allocate storage\n        for these things once and periodically update the sign\n        variables when the weights they depend on have changed and we\n        need to know the signs.\n        \"\"\"\n        if self.signVisToHid == None or self.signA == None or self.signB == None:\n            self.signVisToHid = cm.CUDAMatrix(reformat(num.zeros((self.numVis, self.numHid))))\n            self.signA = [cm.CUDAMatrix(reformat(num.zeros((self.numVis, self.numVis)))) for i in range(self.numPrev)]\n            self.signB = [cm.CUDAMatrix(reformat(num.zeros((self.numVis, self.numHid)))) for i in range(self.numPrev)]\n        self.visToHid.sign(target = self.signVisToHid)\n        for i in range(self.numPrev):\n            self.A[i].sign(target = self.signA[i])\n            self.B[i].sign(target = self.signB[i])        \n        \n    def decay(self):\n        \"\"\"\n        Weight decay during pretraining.  LearningRates should be a\n        dictionary with keys self.weightVariableNames() that holds the\n        learning rate for each weight.\n        \"\"\"\n        #here are the learning parameters this method depends on\n        decayRate = self.weightCost\n        arDecayRate = self.arWeightCost if self.arWeightCost != None else decayRate\n        learningRates = self.reformatLearningRates(self.learnRate) # we reformat in case self.learnRate isn't a dict\n        regType = self.regType\n        \n        if decayRate > 0: #hopefully this saves time when decayRate == 0\n            #really for L1+bias mode we should allow different weight costs for the L1 part and the bias sparsity\n            assert( regType in [\"L2\",\"L1\",\"bias\",\"L1+bias\", \"L2+bias\"] )\n            if \"L2\" in regType:\n                self.visToHid.mult_by_scalar( 1-decayRate*learningRates['visToHid'] )\n                for i in range(self.numPrev):\n                    self.A[i].mult_by_scalar( 1-arDecayRate*learningRates['A'] )\n                    self.B[i].mult_by_scalar( 1-arDecayRate*learningRates['B'] )\n            if \"L1\" in regType:\n                self.updateSignOfWeights()\n                self.visToHid.subtract_mult(self.signVisToHid, decayRate*learningRates['visToHid'])\n                for i in range(self.numPrev):\n                    self.A[i].subtract_mult(self.signA[i], arDecayRate*learningRates['A'])\n                    self.B[i].subtract_mult(self.signB[i], arDecayRate*learningRates['B'])\n            if \"bias\" in regType:\n                self.hidBias.add_scalar( -decayRate*learningRates['hidBias'] )\n    \n    def step(self, data, past):\n        \"\"\"\n        This function sets references in self.vis and self.past to\n        point to data and past.\n        \"\"\"\n        self.vis = data\n        self.past = past\n        self.CDn()\n        rates = self.reformatLearningRates(self.learnRate)\n        self.decay() #needs dictionary of learning rates, but it will reformat the rates again on its own\n        for j, wname in enumerate(self.weightVariableNames()):\n            if type(self.__dict__[wname]) == list:\n                for i in range(self.numPrev):\n                    self.__dict__[wname][i].add_mult( self.__dict__[\"d\"+wname][i], rates[wname]/self.mbsz )\n            else: #we assume it is a numpy array\n                self.__dict__[wname].add_mult( self.__dict__[\"d\"+wname], rates[wname]/self.mbsz )    \n\n    def trainLowMemory(self, data, index, numEpochs, reportMB = False):\n        assert(data.dtype == num.dtype('float32'))\n        numcases = len(index)\n        \n        num_mini_batches = numcases / self.mbsz\n        indexPerm = num.random.permutation(range(numcases))\n\n        noise = cm.CUDAMatrix(reformat(num.zeros((self.numVis, self.mbsz))))\n        for ep in range(numEpochs):\n            recErr = 0\n            for mb in range(num_mini_batches):\n                mbIndex = index[ indexPerm[mb*self.mbsz:(mb+1)*self.mbsz] ]\n\n                curInputsMB_CPU = data[:, mbIndex]\n                curPastMB_CPU = [data[:, mbIndex-i-1] for i in range(self.numPrev)]\n                curInputsMB = cm.CUDAMatrix(reformat(curInputsMB_CPU))\n                curPastMB = [cm.CUDAMatrix(reformat(p)) for p in curPastMB_CPU]\n                if self.pastNoise > 0:\n                    for i in range(self.numPrev):\n                        noise.fill_with_randn()\n                        curPastMB[i].add_mult(noise, self.pastNoise)\n                \n                self.step(curInputsMB, curPastMB)\n                recErr += self.curRecErr()\n                if reportMB:\n                    yield (mb, num_mini_batches)\n            yield recErr\n    \n    def oneLayerReconstructions(self, inputs, past, sample = False):\n        #inputs and past should be on the CPU\n        hiddens = self.predictions(inputs, past, sample)\n        recons = self.reconstructions(past, hiddens, False)\n        return recons[:,:inputs.shape[1]]\n\n    def predictions(self, inp, past, sample = False):\n        \n        \"\"\"\n        This function assumes inp and past reside on the cpu.  It\n        returns a numpy array.\n\n        We assume an integer number of minibatches and any cases\n        beyond mbsz*floor(numcases/mbsz) are ignored.\n        \"\"\"\n        #we return an array numHid by floor(numcases/mbsz)\n        pred = []\n        \n        numcases = inp.shape[1]\n        num_mini_batches = numcases / self.mbsz\n        \n        for i in range(num_mini_batches):\n            idx = i*self.mbsz\n            self.vis = cm.CUDAMatrix(reformat(inp[:,idx:idx+self.mbsz]))\n            self.past = [ cm.CUDAMatrix(reformat(p[:,idx:idx+self.mbsz])) for p in past ]\n            \n            self.hidActProbs()\n            if sample:\n                self.sampleHiddens(self.hActProbs)\n                self.hActs.copy_to_host()\n                pred.append(self.hActs.numpy_array.copy())\n            else:\n                self.hActProbs.copy_to_host()\n                pred.append(self.hActProbs.numpy_array.copy())\n        return num.hstack(pred)\n    \n    def reconstructions(self, past, hiddens, onGPU = False):\n        \"\"\"\n        We assume we have an integer number of\n        minibatches.\n        \"\"\"\n        #we return an array numVis by floor(numcases/mbsz)\n        if onGPU:\n            pastGPU = past\n            hiddensGPU = hiddens\n        else:\n            pastGPU = [cm.CUDAMatrix(reformat(p)) for p in past]\n            hiddensGPU = cm.CUDAMatrix(reformat(hiddens))\n\n        numcases = hiddensGPU.numpy_array.shape[1]\n        num_mini_batches = numcases / self.mbsz\n\n        recons = []\n        for i in range(num_mini_batches):\n            self.past = [p.slice(i*self.mbsz, (i+1)*self.mbsz) for p in pastGPU]\n            self.hActs = hiddensGPU.slice(i*self.mbsz, (i+1)*self.mbsz)\n            self.visActProbs(True)\n            self.negVis.copy_to_host()\n            recons.append(self.negVis.numpy_array.copy())\n\n        return num.hstack(recons)\n    \n\n\ndef padToMinibatch(matrixOnCPU, mbsz):\n    if matrixOnCPU.shape[1] % mbsz == 0:\n        return matrixOnCPU, 0\n    pad_num = mbsz - matrixOnCPU.shape[1] % mbsz\n    return num.hstack( (matrixOnCPU, num.zeros((matrixOnCPU.shape[0], pad_num))) ), pad_num\n\nclass BinaryCRBM(GaussianCRBM):\n    def visActProbs(self, recomputeDynamicBias):\n        GaussianCRBM.visActProbs(self, recomputeDynamicBias)\n        self.negVis.apply_sigmoid()\n\n    def setLearningParams(self, learnRate = 0.04, momentum = 0.9, weightCost = 0, regType = \"L2\", cdSteps = 1, \\\n                          pastNoise = 0, arWeightCost = None, samplePast = False):\n        self.learnRate = learnRate\n        self.momentum = momentum\n        self.weightCost = weightCost\n        self.regType = regType\n        self.cdSteps = cdSteps\n        self.pastNoise = pastNoise\n        self.samplePast = samplePast\n        self.arWeightCost = arWeightCost\n        \n    def trainLowMemory(self, data, index, numEpochs, reportMB = False):\n        assert(data.dtype == num.dtype('float32'))\n        numcases = len(index)\n        \n        num_mini_batches = numcases / self.mbsz\n        indexPerm = num.random.permutation(range(numcases))\n\n        noise = cm.CUDAMatrix(reformat(num.zeros((self.numVis, self.mbsz))))\n        noiseThresh = cm.CUDAMatrix(reformat(num.zeros((self.numVis, self.mbsz))))\n        noiseThresh.assign_scalar(1.0-self.pastNoise)\n        for ep in range(numEpochs):\n            recErr = 0\n            for mb in range(num_mini_batches):\n                mbIndex = index[ indexPerm[mb*self.mbsz:(mb+1)*self.mbsz] ]\n                \n                curInputsMB_CPU = data[:, mbIndex]\n                curPastMB_CPU = [data[:, mbIndex-i-1] for i in range(self.numPrev)]\n                curInputsMB = cm.CUDAMatrix(reformat(curInputsMB_CPU))\n                curPastMB = [cm.CUDAMatrix(reformat(p)) for p in curPastMB_CPU]\n                for i in range(self.numPrev):\n                    if self.pastNoise > 0 and not self.samplePast:\n                        noise.fill_with_rand()\n                        noise.less_than(noiseThresh, target = noise)\n                        curPastMB[i].mult(noise)\n                    if self.samplePast:\n                        noise.fill_with_rand()\n                        noise.less_than(curPastMB[i], target = curPastMB[i])\n                \n                self.step(curInputsMB, curPastMB)\n                recErr += self.curRecErr()\n                if reportMB:\n                    yield (mb, num_mini_batches)\n            yield recErr\n\nclass HybridCRBM(GaussianCRBM):\n    \"\"\"\n    This class implements a hybrid crbm with a single softmax unit and\n    some gaussian units for the visible units.\n    \"\"\"\n    def __init__(self, numVis, numHid, prevFrames, smsz, initHidBias = 0.0):\n        assert(0 <= smsz <= numVis)\n        self.smsz = smsz\n        GaussianCRBM.__init__(self, numVis, numHid, prevFrames, initHidBias)\n        \n    def initTemporary(self):\n        self.hActs = cm.CUDAMatrix(reformat(num.zeros((self.numHid, self.mbsz))))\n        self.hActProbs = cm.CUDAMatrix(reformat(num.zeros((self.numHid, self.mbsz))))\n        self.negVis = cm.CUDAMatrix(reformat(num.zeros((self.numVis, self.mbsz))))\n        self.tempVisMB = cm.CUDAMatrix(reformat(num.zeros((self.numVis, self.mbsz))))\n        self.dynamicHidBias = cm.CUDAMatrix(reformat(num.zeros((self.numHid, self.mbsz))))\n        self.dynamicVisBias = cm.CUDAMatrix(reformat(num.zeros((self.numVis, self.mbsz))))\n\n        self.sMask = num.zeros((self.numVis, self.mbsz))\n        self.sMask[:self.smsz,:] = 1\n        self.gaussMask = 1-self.sMask\n        \n        self.onesCol = cm.CUDAMatrix(reformat(num.ones((self.numVis,1))))\n        self.sMask = cm.CUDAMatrix(reformat(self.sMask))\n        self.gaussMask = cm.CUDAMatrix(reformat(self.gaussMask))\n        self.tempRow = cm.CUDAMatrix(reformat(num.zeros((1, self.mbsz))))\n        #self.tempBinVisMB = cm.CUDAMatrix(reformat(num.zeros((self.numVis, self.mbsz))))\n        \n    def setLearningParams(self, learnRate = 0.001, momentum = 0.9, weightCost = 0, regType = \"L2\", cdSteps = 1, \\\n                          pastNoise = 0, arWeightCost = None, pastNoiseSM = 0):\n        GaussianCRBM.setLearningParams(self, learnRate, momentum, weightCost, regType, cdSteps, pastNoise, arWeightCost)\n        self.pastNoiseSM = pastNoiseSM\n    \n    def visActProbs(self, recomputeDynamicBias):\n        GaussianCRBM.visActProbs(self, recomputeDynamicBias)\n        maskedSingleSoftmax(self.negVis, self.tempVisMB, self.sMask, self.gaussMask, self.onesCol, self.tempRow)\n\n    def trainLowMemory(self, data, index, numEpochs, reportMB = False):\n        assert(data.dtype == num.dtype('float32'))\n        numcases = len(index)\n        \n        num_mini_batches = numcases / self.mbsz\n        indexPerm = num.random.permutation(range(numcases))\n        \n        noise = cm.CUDAMatrix(reformat(num.zeros((self.numVis, self.mbsz))))\n        for ep in range(numEpochs):\n            recErr = 0\n            for mb in range(num_mini_batches):\n                mbIndex = index[ indexPerm[mb*self.mbsz:(mb+1)*self.mbsz] ]\n                \n                curInputsMB_CPU = data[:, mbIndex]\n                curPastMB_CPU = [data[:, mbIndex-i-1] for i in range(self.numPrev)]\n                if self.pastNoiseSM > 0:\n                    for i in range(self.numPrev):\n                        smNoise = (self.pastNoiseSM/self.smsz)*num.random.rand(self.smsz, self.mbsz)\n                        #smNoise[0,:] = 0\n                        #smNoise /= self.smsz-1\n                        curPastMB_CPU[i][:self.smsz,:] = (curPastMB_CPU[i][:self.smsz,:] + smNoise)/(1+self.pastNoiseSM)\n                        \n                curInputsMB = cm.CUDAMatrix(reformat(curInputsMB_CPU))\n                curPastMB = [cm.CUDAMatrix(reformat(p)) for p in curPastMB_CPU]\n                if self.pastNoise > 0:\n                    for i in range(self.numPrev):\n                        noise.fill_with_randn()\n                        noise.mult(self.gaussMask)\n                        curPastMB[i].add_mult(noise, self.pastNoise)\n                \n                self.step(curInputsMB, curPastMB)\n                recErr += self.curRecErr()\n                if reportMB:\n                    yield (mb, num_mini_batches)\n            yield recErr\n\n\ndef gpu_batches(data, past, mbs, transpose = True):\n    \"\"\"\n    We assume that the first dimension of the data is the number of cases.\n\n    We generate minibatches of data and delayed data of the appropriate size transposed for use on the GPU.\n\n    If we can't fill the last minibatch, we discard that data.\n    \"\"\"\n    numCases, numDims = data.shape\n    numBatches = numCases/mbs\n    for i in range(numBatches):\n        if transpose:\n            yield (data[i*mbs:(i+1)*mbs,:].transpose(), [p[i*mbs:(i+1)*mbs,:].transpose() for p in past])\n        else:\n            yield (data[i*mbs:(i+1)*mbs,:], [p[i*mbs:(i+1)*mbs,:] for p in past])\n\n\n\ndef main1():\n    net = BinaryCRBM(10,16,2)\n    data = loadmat(\"brazilRainfall.mat\")[\"batchdata\"]\n    chunks = [(data[i*90+2:(i+1)*90,:], [data[i*90+1:(i+1)*90-1,:], data[i*90:(i+1)*90-2,:]]) for i in range(24)]\n    \n    data = num.vstack( [c[0] for c in chunks] )\n    past = [ num.vstack( [c[1][i] for c in chunks] ) for i in range(2)]\n\n    data = data.transpose()\n    past = [p.transpose() for p in past]\n\n    print data.shape\n    print data.shape[1]/64\n    for p in past:\n        print p.shape\n\n    net.learnRate = 0.002\n    net.momentum = 0.9\n    net.weightCost = 0\n    for j,err in enumerate(net.trainXFerEnMasse(data, past, 100)):\n        print j+1, err\n    \n\n    ex = cm.CUDAMatrix(reformat(num.array([[1,1],[2,3]])))\n    print ex.euclid_norm()\n    \n\ndef main2():\n    pass\n\nfrom scipy.io import loadmat\n\nif __name__ == \"__main__\":\n    print \"export LD_LIBRARY_PATH=/u/gdahl/cudaLearn/\"\n    print \"export CUDAMATDIR=/u/gdahl/cudaLearn\"\n    \n    devId = cm.cuda_get_free_device()\n    cm.cuda_set_device(devId)\n    \n    cm.cublas_init()\n    cm.CUDAMatrix.init_random(1)\n    main1()\n    cm.cublas_shutdown()\n\n", "meta": {"hexsha": "beed3c8dc6ae493b1dddcd486695a13cfdcea354", "size": 27693, "ext": "py", "lang": "Python", "max_stars_repo_path": "crbm.py", "max_stars_repo_name": "evelkey/cudalearn", "max_stars_repo_head_hexsha": "fbf9c18b2e6f4a8febd04557a7b2eacbe8957cf4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "crbm.py", "max_issues_repo_name": "evelkey/cudalearn", "max_issues_repo_head_hexsha": "fbf9c18b2e6f4a8febd04557a7b2eacbe8957cf4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "crbm.py", "max_forks_repo_name": "evelkey/cudalearn", "max_forks_repo_head_hexsha": "fbf9c18b2e6f4a8febd04557a7b2eacbe8957cf4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0266666667, "max_line_length": 139, "alphanum_fraction": 0.5930379518, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1824879635752646}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2020 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#\n\nimport numpy\nimport h5py\nfrom pyscf import lib\nfrom pyscf import gto\nfrom pyscf.ao2mo.outcore import balance_segs\nfrom pyscf.pbc.lib.kpts_helper import gamma_point, unique, KPT_DIFF_TOL\nfrom pyscf.pbc.df.incore import wrap_int3c\n\nlibpbc = lib.load_library('libpbc')\n\n\ndef aux_e1(cell, auxcell, erifile, intor='int3c2e', aosym='s2ij', comp=None,\n           kptij_lst=None, dataname='eri_mo', shls_slice=None, max_memory=2000,\n           verbose=0):\n    r'''3-center AO integrals (L|ij) with double lattice sum:\n    \\sum_{lm} (L[0]|i[l]j[m]), where L is the auxiliary basis.\n    Three-index integral tensor (kptij_idx, naux, nao_pair) or four-index\n    integral tensor (kptij_idx, comp, naux, nao_pair) are stored on disk.\n\n    Args:\n        kptij_lst : (*,2,3) array\n            A list of (kpti, kptj)\n    '''\n    intor, comp = gto.moleintor._get_intor_and_comp(cell._add_suffix(intor), comp)\n\n    if isinstance(erifile, h5py.Group):\n        feri = erifile\n    elif h5py.is_hdf5(erifile):\n        feri = h5py.File(erifile, 'a')\n    else:\n        feri = h5py.File(erifile, 'w')\n    if dataname in feri:\n        del(feri[dataname])\n    if dataname+'-kptij' in feri:\n        del(feri[dataname+'-kptij'])\n\n    if kptij_lst is None:\n        kptij_lst = numpy.zeros((1,2,3))\n    feri[dataname+'-kptij'] = kptij_lst\n\n    if shls_slice is None:\n        shls_slice = (0, cell.nbas, 0, cell.nbas, 0, auxcell.nbas)\n\n    ao_loc = cell.ao_loc_nr()\n    aux_loc = auxcell.ao_loc_nr(auxcell.cart or 'ssc' in intor)[:shls_slice[5]+1]\n    ni = ao_loc[shls_slice[1]] - ao_loc[shls_slice[0]]\n    nj = ao_loc[shls_slice[3]] - ao_loc[shls_slice[2]]\n    naux = aux_loc[shls_slice[5]] - aux_loc[shls_slice[4]]\n    nkptij = len(kptij_lst)\n\n    nii = (ao_loc[shls_slice[1]]*(ao_loc[shls_slice[1]]+1)//2 -\n           ao_loc[shls_slice[0]]*(ao_loc[shls_slice[0]]+1)//2)\n    nij = ni * nj\n\n    kpti = kptij_lst[:,0]\n    kptj = kptij_lst[:,1]\n    aosym_ks2 = abs(kpti-kptj).sum(axis=1) < KPT_DIFF_TOL\n    j_only = numpy.all(aosym_ks2)\n    #aosym_ks2 &= (aosym[:2] == 's2' and shls_slice[:2] == shls_slice[2:4])\n    aosym_ks2 &= aosym[:2] == 's2'\n    for k, kptij in enumerate(kptij_lst):\n        key = '%s/%d' % (dataname, k)\n        if gamma_point(kptij):\n            dtype = 'f8'\n        else:\n            dtype = 'c16'\n        if aosym_ks2[k]:\n            nao_pair = nii\n        else:\n            nao_pair = nij\n        if comp == 1:\n            shape = (naux,nao_pair)\n        else:\n            shape = (comp,naux,nao_pair)\n        feri.create_dataset(key, shape, dtype)\n    if naux == 0:\n        feri.close()\n        return erifile\n\n    if j_only and aosym[:2] == 's2':\n        assert(shls_slice[2] == 0)\n        nao_pair = nii\n    else:\n        nao_pair = nij\n\n    if gamma_point(kptij_lst):\n        dtype = numpy.double\n    else:\n        dtype = numpy.complex128\n\n    buflen = max(8, int(max_memory*1e6/16/(nkptij*ni*nj*comp)))\n    auxdims = aux_loc[shls_slice[4]+1:shls_slice[5]+1] - aux_loc[shls_slice[4]:shls_slice[5]]\n    auxranges = balance_segs(auxdims, buflen)\n    buflen = max([x[2] for x in auxranges])\n    buf = numpy.empty(nkptij*comp*ni*nj*buflen, dtype=dtype)\n    buf1 = numpy.empty(ni*nj*buflen, dtype=dtype)\n\n    int3c = wrap_int3c(cell, auxcell, intor, aosym, comp, kptij_lst)\n\n    naux0 = 0\n    for istep, auxrange in enumerate(auxranges):\n        sh0, sh1, nrow = auxrange\n        sub_slice = (shls_slice[0], shls_slice[1],\n                     shls_slice[2], shls_slice[3],\n                     shls_slice[4]+sh0, shls_slice[4]+sh1)\n        mat = numpy.ndarray((nkptij,comp,nao_pair,nrow), dtype=dtype, buffer=buf)\n        mat = int3c(sub_slice, mat)\n\n        for k, kptij in enumerate(kptij_lst):\n            h5dat = feri['%s/%d'%(dataname,k)]\n            for icomp, v in enumerate(mat[k]):\n                v = lib.transpose(v, out=buf1)\n                if gamma_point(kptij):\n                    v = v.real\n                if aosym_ks2[k] and v.shape[1] == ni**2:\n                    v = lib.pack_tril(v.reshape(-1,ni,ni))\n                if comp == 1:\n                    h5dat[naux0:naux0+nrow] = v\n                else:\n                    h5dat[icomp,naux0:naux0+nrow] = v\n        naux0 += nrow\n\n    if not isinstance(erifile, h5py.Group):\n        feri.close()\n    return erifile\n\n\ndef _aux_e2(cell, auxcell, erifile, intor='int3c2e', aosym='s2ij', comp=None,\n            kptij_lst=None, dataname='eri_mo', shls_slice=None, max_memory=2000,\n            verbose=0):\n    r'''3-center AO integrals (ij|L) with double lattice sum:\n    \\sum_{lm} (i[l]j[m]|L[0]), where L is the auxiliary basis.\n    Three-index integral tensor (kptij_idx, nao_pair, naux) or four-index\n    integral tensor (kptij_idx, comp, nao_pair, naux) are stored on disk.\n\n    **This function should be only used by df and mdf initialization function\n    _make_j3c**\n\n    Args:\n        kptij_lst : (*,2,3) array\n            A list of (kpti, kptj)\n    '''\n    intor, comp = gto.moleintor._get_intor_and_comp(cell._add_suffix(intor), comp)\n\n    if isinstance(erifile, h5py.Group):\n        feri = erifile\n    elif h5py.is_hdf5(erifile):\n        feri = h5py.File(erifile, 'a')\n    else:\n        feri = h5py.File(erifile, 'w')\n    if dataname in feri:\n        del(feri[dataname])\n    if dataname+'-kptij' in feri:\n        del(feri[dataname+'-kptij'])\n\n    if kptij_lst is None:\n        kptij_lst = numpy.zeros((1,2,3))\n    feri[dataname+'-kptij'] = kptij_lst\n\n    if shls_slice is None:\n        shls_slice = (0, cell.nbas, 0, cell.nbas, 0, auxcell.nbas)\n\n    ao_loc = cell.ao_loc_nr()\n    aux_loc = auxcell.ao_loc_nr(auxcell.cart or 'ssc' in intor)[:shls_slice[5]+1]\n    ni = ao_loc[shls_slice[1]] - ao_loc[shls_slice[0]]\n    nj = ao_loc[shls_slice[3]] - ao_loc[shls_slice[2]]\n    nkptij = len(kptij_lst)\n\n    nii = (ao_loc[shls_slice[1]]*(ao_loc[shls_slice[1]]+1)//2 -\n           ao_loc[shls_slice[0]]*(ao_loc[shls_slice[0]]+1)//2)\n    nij = ni * nj\n\n    kpti = kptij_lst[:,0]\n    kptj = kptij_lst[:,1]\n    aosym_ks2 = abs(kpti-kptj).sum(axis=1) < KPT_DIFF_TOL\n    j_only = numpy.all(aosym_ks2)\n    #aosym_ks2 &= (aosym[:2] == 's2' and shls_slice[:2] == shls_slice[2:4])\n    aosym_ks2 &= aosym[:2] == 's2'\n\n    if j_only and aosym[:2] == 's2':\n        assert(shls_slice[2] == 0)\n        nao_pair = nii\n    else:\n        nao_pair = nij\n\n    if gamma_point(kptij_lst):\n        dtype = numpy.double\n    else:\n        dtype = numpy.complex128\n\n    buflen = max(8, int(max_memory*.47e6/16/(nkptij*ni*nj*comp)))\n    auxdims = aux_loc[shls_slice[4]+1:shls_slice[5]+1] - aux_loc[shls_slice[4]:shls_slice[5]]\n    auxranges = balance_segs(auxdims, buflen)\n    buflen = max([x[2] for x in auxranges])\n    buf = numpy.empty(nkptij*comp*ni*nj*buflen, dtype=dtype)\n    buf1 = numpy.empty_like(buf)\n\n    int3c = wrap_int3c(cell, auxcell, intor, aosym, comp, kptij_lst)\n\n    kptis = kptij_lst[:,0]\n    kptjs = kptij_lst[:,1]\n    kpt_ji = kptjs - kptis\n    uniq_kpts, uniq_index, uniq_inverse = unique(kpt_ji)\n# sorted_ij_idx: Sort and group the kptij_lst according to the ordering in\n# df._make_j3c to reduce the data fragment in the hdf5 file.  When datasets\n# are written to hdf5, they are saved sequentially. If the integral data are\n# saved as the order of kptij_lst, removing the datasets in df._make_j3c will\n# lead to holes that can not be reused.\n    sorted_ij_idx = numpy.hstack([numpy.where(uniq_inverse == k)[0]\n                                  for k, kpt in enumerate(uniq_kpts)])\n    tril_idx = numpy.tril_indices(ni)\n    tril_idx = tril_idx[0] * ni + tril_idx[1]\n    def save(istep, mat):\n        for k in sorted_ij_idx:\n            v = mat[k]\n            if gamma_point(kptij_lst[k]):\n                v = v.real\n            if aosym_ks2[k] and nao_pair == ni**2:\n                v = v[:,tril_idx]\n            feri['%s/%d/%d' % (dataname,k,istep)] = v\n\n    with lib.call_in_background(save) as bsave:\n        for istep, auxrange in enumerate(auxranges):\n            sh0, sh1, nrow = auxrange\n            sub_slice = (shls_slice[0], shls_slice[1],\n                         shls_slice[2], shls_slice[3],\n                         shls_slice[4]+sh0, shls_slice[4]+sh1)\n            mat = numpy.ndarray((nkptij,comp,nao_pair,nrow), dtype=dtype, buffer=buf)\n            bsave(istep, int3c(sub_slice, mat))\n            buf, buf1 = buf1, buf\n\n    if not isinstance(erifile, h5py.Group):\n        feri.close()\n    return erifile\n\n\n", "meta": {"hexsha": "4617aeff5f0fe30c5b1e0a0edf55479b0cdab077", "size": 9064, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/pbc/df/outcore.py", "max_stars_repo_name": "shufay/pyscf", "max_stars_repo_head_hexsha": "c7ea840b012a59fce5fa4114ef3274a7cf00165e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-12T11:55:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T11:55:25.000Z", "max_issues_repo_path": "pyscf/pbc/df/outcore.py", "max_issues_repo_name": "shufay/pyscf", "max_issues_repo_head_hexsha": "c7ea840b012a59fce5fa4114ef3274a7cf00165e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2018-08-22T19:44:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-09T10:02:36.000Z", "max_forks_repo_path": "pyscf/pbc/df/outcore.py", "max_forks_repo_name": "shufay/pyscf", "max_forks_repo_head_hexsha": "c7ea840b012a59fce5fa4114ef3274a7cf00165e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-02-14T16:28:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-12T16:40:30.000Z", "avg_line_length": 35.5450980392, "max_line_length": 93, "alphanum_fraction": 0.6129744042, "include": true, "reason": "import numpy", "num_tokens": 2980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3486451353339458, "lm_q1q2_score": 0.18248795839144583}}
{"text": "# Copyright (c) 2018, Henrique Miranda\n# All rights reserved.\n#\n# This file is part of the yambopy project\n#\nfrom __future__ import print_function, division\nfrom yambopy import *\nfrom itertools import product\nfrom netCDF4 import Dataset\n\nclass YamboExcitonWeight(YamboSaveDB):\n    \"\"\"\n    Class to read the excitonic weight writen by ypp\n    \"\"\"\n\n    def __init__(self,filename,save='SAVE',path='.'):\n        #read save database\n\n        # ! I have commented line 20 because is was broken. Pls check\n\n        ysave = YamboSaveDB.from_db_file(folder=save,filename='ns.db1')\n        self.sym_car  = ysave.sym_car\n        self.kpts_car = ysave.car_kpoints #kpts_car\n        self.lat = ysave.lat\n\n        #super(YamboSaveDB,self).from_db_file(folder=save,filename='ns.db1')\n\n        #read excitons file\n        self.excitons = np.loadtxt(filename)\n\n        self.weights = None\n\n    def write_irr(self,filename=\"irr.dat\"):\n        \"\"\" write the list of kpoints from the irreducible brillouin zone\n        \"\"\"\n        f = open(\"irr.dat\",'w')\n        for k in self.kpts_car:\n            f.write((\"%12.8lf\"*3)%(k[1],k[0],k[2])+\"\\n\")\n        f.close()\n\n    def write_full(self,filename=\"full.dat\"):\n        \"\"\" write the list of kpoints in the full brillouin zone\n        \"\"\"\n        #generate all the possible points\n        kpoints = self.kpts_car\n        kpts = []\n        for k in self.kpts_car:\n            for sym in self.sym_car:\n                kpts.append(np.dot(sym,k))\n\n        f = open(\"full.dat\",'w')\n        for q in kpts:\n            f.write((\"%12.8lf \"*3)%tuple(q)+\"\\n\")\n        f.close()\n\n    def get_data(self):\n        qpts, weights, transitions = self.calc_kpts_weights()\n        return { \"qpts\": qpts,\n                 \"weights\": weights,\n                 \"lattice\": self.lat,\n                 \"reciprocal_lattice\": self.rlat,\n                 \"transitions\": transitions\n                 }\n\n    def calc_kpts_weights(self,repx=list(range(-1,2)),repy=list(range(-1,2)),repz=list(range(-1,2))):\n        \"\"\" Calculate the weights and kpoints of the excitons\n        \"\"\"\n        self.weights     = dict()\n\n        #first run set everything to zero\n        for line in self.excitons:\n            v,c,k,sym,w,e = line\n            self.weights[(int(k),int(sym))] = 0\n\n        #add weights\n        for line in self.excitons:\n            v,c,k,sym,w,e = line\n            self.weights[(int(k),int(sym))] += w\n\n        #rename symmetries and kpoints\n        sym = self.sym_car\n        kpoints = self.kpts_car\n\n        qpts     = []\n        kidx     = []\n        weights  = []\n\n        for r in product(repx,repy,repz):\n          for k,s in list(self.weights.keys()):\n            w   = self.weights[(k,s)]\n            weights.append( w )\n            qpt = np.dot(sym[s-1],kpoints[k-1])+red_car([r],self.rlat)[0]\n            qpts.append( qpt )\n            kidx.append( k )\n\n        return np.array(qpts), np.array(weights)\n\n    def calc_kpts_transitions(self,repx=list(range(-1,2)),repy=list(range(-1,2)),repz=list(range(-1,2)),debug=False):\n        \"\"\" Calculate the transitions and kpoints of the excitons\n        \"\"\"\n        self.weights     = dict()\n        self.transitions = dict()\n        self.transitions_v_to_c = dict()\n\n        #first run set everything to zero\n        for line in self.excitons:\n            v,c,k,sym,w,e = line\n            self.weights[(int(k),int(sym))] = 0\n            self.transitions[(int(v),int(c),int(k),int(sym))] = 0\n            self.transitions_v_to_c[(int(v),int(c))] = 0\n\n        #add weights\n        for line in self.excitons:\n            v,c,k,sym,w,e = line\n            self.weights[(int(k),int(sym))] += w\n\n        #add transitions\n        for line in self.excitons:\n            v,c,k,sym,w,e = line\n            self.transitions[(int(v),int(c),int(k),int(sym))] += w\n\n        #add percentage of a given v => c transition\n        norm = sum(self.excitons[:,4])\n        for v,c,k,s in list(self.transitions.keys()):\n          self.transitions_v_to_c[(int(v),int(c))] += self.transitions[(v,c,k,s)]\n        if debug: print('transitions (valence > condution):')\n        for v,c in self.transitions_v_to_c:\n          self.transitions_v_to_c[(v,c)] = self.transitions_v_to_c[(v,c)]/norm\n          if debug: print('%3d > %3d'%(v,c))\n\n        #rename symmetries and kpoints\n        sym = self.sym_car\n        kpoints = self.kpts_car\n\n        qpts     = []\n        kidx     = []\n        t_v_c    = []\n\n        for r in product(repx,repy,repz):\n          for k,s in list(self.weights.keys()):\n            qpt = np.dot(sym[s-1],kpoints[k-1])+red_car([r],self.rlat)[0]\n            qpts.append( qpt )\n            kidx.append( k )\n            #print (v_ref,c_ref,k,s)\n            #aux.append(self.transitions[(v_ref,c_ref,k,s)])\n\n        for v_ref,c_ref in list(self.transitions_v_to_c.keys()):\n          aux = []\n          for r in product(repx,repy,repz):\n            for k,s in list(self.weights.keys()):\n              aux.append(self.transitions[(v_ref,c_ref,k,s)])\n          t_v_c.append(np.array(aux))\n\n        return np.array(qpts), t_v_c, np.array(kidx)\n\n    def plot_contour(self,resX=500,resY=500):\n        \"\"\" plot a contour\n            idea taken from http://stackoverflow.com/questions/18764814/make-contour-of-scatter\n        \"\"\"\n        kpts, z = self.calc_kpts_weights()\n        x,y = kpts[:,0],kpts[:,1]\n        xi = np.linspace(min(x), max(x), resX)\n        yi = np.linspace(min(y), max(y), resY)\n        Z = griddata(x, y, z, xi, yi, interp='cubic')\n        X, Y = np.meshgrid(xi, yi)\n\n        plt.contourf(X, Y, Z, cmap='gist_heat_r')\n        plt.show()\n\n    def plot_weights(self,ax,size=20,marker='H',set_origin=0.0,lim=0.2,cmap='viridis',log_scale=False,set_maximum=1.0):\n        \"\"\"\n\n        Plot the weights in a scatter plot of this exciton (1st version tuned by A. Molina-Sanchez)\n        Options:\n        cmap : colormap. Default viridis \n        log_scale : Logarithmic scale for the intensity (True or False)\n        set_maximum : Only applied for linear scale. Apply a cut for a selected intensity (values between 0 and 1)\n        Further development: Option for the colorbar\n \n        \"\"\"\n        from numpy import sqrt\n        import matplotlib.pyplot as plt\n        import matplotlib.colors as colors\n\n        \"\"\"\n        These options can be decided by the user. In this first version we just:\n        remove axis\n        \"\"\"\n        ax.set_aspect('equal')\n        ax.set_xlim(-lim,lim)\n        ax.set_ylim(-lim,lim)\n        ax.axes.get_xaxis().set_visible(False)\n        ax.axes.get_yaxis().set_visible(False)\n\n        \n        kpts, weights = self.calc_kpts_weights()\n\n        if log_scale == True:\n           norm = colors.LogNorm(vmin=weights.min(),vmax=weights.max())\n        else:\n           if abs(set_maximum)>1.:\n              set_maximum = 1.\n           norm = colors.Normalize(vmin=weights.min(),vmax=abs(set_maximum)*weights.max())\n\n        cmap = plt.get_cmap(cmap)\n\n        ax.scatter(kpts[:,0]-set_origin, kpts[:,1]-set_origin, s=size, marker=marker, color=cmap(norm(weights)))\n\n    def __str__(self):\n        s = \"\"\n        s += \"reciprocal lattice:\\n\"\n        s += \"\\n\".join([(\"%12.8lf \"*3)%tuple(r) for r in self.rlat])+\"\\n\"\n        s += \"lattice:\\n\"\n        s += \"\\n\".join([(\"%12.8lf \"*3)%tuple(r) for r in self.lat])+\"\\n\"\n        s += \"alat:\\n\"\n        s += (\"%12.8lf \"*3)%tuple(self.alat)+\"\\n\"\n        return s\n\n    def plot_transitions(self,size=30,lim=0.2):\n        \"\"\"\n        Plot the weight of a given transition in a scatter plot of this exciton.\n        My idea is to associate for each transition a color and to plot in a different plot\n        \"\"\"\n\n        from numpy import sqrt\n        cmap = plt.get_cmap(\"gist_heat_r\")\n\n        fig = plt.figure(figsize=(10,10))\n        kpts, t_v_c, _ = self.calc_kpts_transitions()\n        for individual in t_v_c:\n          plt.scatter(kpts[:,0], kpts[:,1], s=size, marker='H', color=[cmap(sqrt(c)) for c in individual])\n\n        plt.xlim([-lim,lim])\n        plt.ylim([-lim,lim])\n        ax = plt.axes()\n        ax.set_aspect('equal')\n        plt.show()\n\n    def plot_exciton_bs(self,ax,path,nbands='all',space='transition',color='#1f77b4'):\n        \"\"\"\n        Plot the excitonic weights of a given transition in the band-structure\n        \"\"\"\n        kpts, t_v_c, kidx = self.calc_kpts_transitions(repx=list(range(1)),repy=list(range(1)),repz=list(range(1)))\n        t_v_c = np.array(t_v_c)\n\n        #get_path is provided by savedb\n        bands_kpoints, bands_indexes, path_car = self.get_path(path,kpts=kpts)\n\n        #calculate distances\n        bands_distances = [0]\n        distance = 0\n        for nk in range(1,len(bands_kpoints)):\n            distance += np.linalg.norm(bands_kpoints[nk-1]-bands_kpoints[nk])\n            bands_distances.append(distance)\n\n        #get energies at these k-points\n        eig = self.eigenvalues[kidx-1]\n        eig = eig[bands_indexes]\n        transition_weight  = t_v_c[:,bands_indexes]\n        if nbands == 'all': nbands = self.nbands\n        for tw,t in zip(transition_weight,list(self.transitions_v_to_c.keys())):\n            v,c = t\n            if space == 'transition':\n                ax.plot(bands_distances,eig[:,c-1]-eig[:,v-1])\n                ax.scatter(bands_distances,eig[:,c-1]-eig[:,v-1],s=tw*1e4)\n            else:\n                ax.plot(bands_distances,eig[:,c-1],c=color)\n                ax.plot(bands_distances,eig[:,v-1],c=color)\n                ax.scatter(bands_distances,eig[:,c-1],s=tw*1e4,c=color)\n                ax.scatter(bands_distances,eig[:,v-1],s=tw*1e4,c=color)\n\n    def __str__(self):\n        s = \"\"\n        s += \"reciprocal lattice:\\n\"\n        s += \"\\n\".join([(\"%12.8lf \"*3)%tuple(r) for r in self.rlat])+\"\\n\"\n        s += \"lattice:\\n\"\n        s += \"\\n\".join([(\"%12.8lf \"*3)%tuple(r) for r in self.lat])+\"\\n\"\n        s += \"alat:\\n\"\n        s += (\"%12.8lf \"*3)%tuple(self.alat)+\"\\n\"\n        return s\n\nif __name__ == \"__main__\":\n    ye = YamboExciton('o-yambo.exc_weights_at_1_02')\n    print(ye)\n    ye.write_irr()\n    ye.write_full()\n    #ye.plot_contour()\n    ye.plot_weights()\n", "meta": {"hexsha": "f608cccd6fae1b04bc73fcfec30b623368798931", "size": 10088, "ext": "py", "lang": "Python", "max_stars_repo_path": "yambopy/bse/excitonweight.py", "max_stars_repo_name": "QU-XIAO/yambopy", "max_stars_repo_head_hexsha": "ff65a4f90c1bfefe642ebc61e490efe781709ff9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2016-04-07T20:53:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T08:06:02.000Z", "max_issues_repo_path": "yambopy/bse/excitonweight.py", "max_issues_repo_name": "alexmoratalla/yambopy", "max_issues_repo_head_hexsha": "8ec0e1e18868ccaadb3eab36c55e6a47021e257d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2016-06-14T22:29:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-16T15:36:26.000Z", "max_forks_repo_path": "yambopy/bse/excitonweight.py", "max_forks_repo_name": "alexmoratalla/yambopy", "max_forks_repo_head_hexsha": "8ec0e1e18868ccaadb3eab36c55e6a47021e257d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2016-06-14T18:40:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-07T13:17:43.000Z", "avg_line_length": 34.9065743945, "max_line_length": 119, "alphanum_fraction": 0.5633425852, "include": true, "reason": "from numpy", "num_tokens": 2712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1824879583914458}}
{"text": "# coding: utf-8\nimport copy\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom flearn.client.datasets.get_data import DictDataset, get_dataloader\nfrom flearn.common.distiller import KDLoss\nfrom flearn.common.strategy import ParentStrategy\nfrom flearn.common.strategy.df import DF, DFDistiller\nfrom flearn.common.trainer import Trainer\n\n\nclass MyDFDistiller(DFDistiller):\n    def multi(\n        self, teacher_lst, student, method=\"avg_logits\", weight_lst=None, **kwargs\n    ):\n        self._init_kd(teacher_lst, student, **kwargs)\n        if weight_lst == None:\n            self.weight_lst = [1 / len(teacher_lst)] * len(teacher_lst)\n        else:\n            self.weight_lst = weight_lst\n\n        for _ in range(self.epoch):\n            for _, (x, _) in enumerate(self.kd_loader):\n                x = x.to(self.device)\n                _, _, output = self.student(x)\n\n                soft_target_lst = []\n                for teacher in self.teacher_lst:\n                    with torch.no_grad():\n                        _, _, soft_target = teacher(x)\n                        soft_target_lst.append(soft_target)\n\n                loss = self.multi_loss(method, soft_target_lst, output)\n\n                self.optimizer.zero_grad()\n                loss.backward()\n                self.optimizer.step()\n                # print(\"train_loss_fine_tuning\", loss.data)\n        return student.state_dict()\n\n\nclass MyDF(DF):\n    def server_post_processing(self, ensemble_params_lst, ensemble_params, **kwargs):\n        w_glob = ensemble_params[\"w_glob\"]\n        agg_weight_lst, w_local_lst = self.server_pre_processing(ensemble_params_lst)\n\n        teacher_lst = []\n        for w_local in w_local_lst:\n            self.model_base.load_state_dict(w_local)\n            teacher_lst.append(copy.deepcopy(self.model_base))\n\n        self.model_base.load_state_dict(w_glob)\n        student = copy.deepcopy(self.model_base)\n\n        kd_loader, device = kwargs.pop(\"kd_loader\"), kwargs.pop(\"device\")\n        temperature = kwargs.pop(\"T\")\n        distiller = MyDFDistiller(\n            kd_loader,\n            device,\n            kd_loss=KDLoss(temperature),\n        )\n\n        molecular = np.sum(agg_weight_lst)\n        weight_lst = [w / molecular for w in agg_weight_lst]\n        # agg_weight_lst：应该依照每个模型在验证集上的性能来进行分配\n        ensemble_params[\"w_glob\"] = distiller.multi(\n            teacher_lst, student, kwargs.pop(\"method\"), weight_lst=weight_lst, **kwargs\n        )\n        return ensemble_params\n\n\nclass CCVR(ParentStrategy):\n    \"\"\"\n    Federated learning via Classifier Calibration with Virtual Representations\n\n    [1] Luo M, Chen F, Hu D, et al. No Fear of Heterogeneity: Classifier Calibration for Federated Learning with Non-IID Data[J]. arXiv preprint arXiv:2106.05001, 2021.\n    \"\"\"\n\n    def __init__(self, head_model_base, strategy):\n        super().__init__(strategy)\n        self.head_model_base = head_model_base\n\n    @staticmethod\n    def client_mean_feat(feat_lst, label_lst):\n        sum_ = 0\n        # 按照类别提取特征\n        d = {}\n        for h_l, label_l in zip(feat_lst, label_lst):\n            sum_ += len(h_l)\n            for h, label in zip(h_l, label_l):\n                label = int(label.cpu())\n                if label not in d.keys():\n                    d[label] = [h]\n                else:\n                    d[label].append(h)\n        # label_len = len(d.keys())\n\n        # 计算mu, sigma\n        upload_d = {}\n        for k, v in d.items():\n            v_item = torch.stack(v).detach().cpu()\n            # 考虑样本数量过少不上传的情况\n            if len(v_item) < 10:\n                continue\n            # if len(v_item) * label_len * 2 < sum_:\n            #     continue\n            mu, sigma = v_item.mean(dim=0), v_item.var(dim=0)\n            upload_d[k] = {\"mu\": mu, \"sigma\": sigma, \"N\": len(v)}\n        return upload_d\n\n    def client(self, trainer, agg_weight=1.0):\n        w_shared = super().client(trainer, agg_weight)\n        w_shared[\"fd\"] = self.client_mean_feat(trainer.feat_lst, trainer.label_lst)\n        return w_shared\n\n    @staticmethod\n    def load_model(model_base, new_model_dict):\n        model_base_dict = model_base.state_dict()\n        model_base_dict.update(new_model_dict)\n        model_base.load_state_dict(model_base_dict)\n        return model_base\n\n    def server_mean_feat(self, fd_lst):\n        # 获取每个客户端的标签，集成一起\n        label_lst = []\n        for x in fd_lst:\n            label_lst += list(x.keys())\n        label_lst = list(set(label_lst))\n        print(\"labels: \", label_lst)\n\n        fd_d = {}\n        # 统计每个标签的特征分布\n        for l in label_lst:\n            # 客户端不一定具备所有的标签，异质\n            labeled_fd_lst = [x for x in fd_lst if l in x.keys()]\n            sum_n = sum(x[l][\"N\"] for x in labeled_fd_lst)\n\n            mu_lst = [fd[l][\"mu\"] * fd[l][\"N\"] / sum_n for fd in labeled_fd_lst]\n            mu = torch.stack(mu_lst).sum(dim=0)\n\n            sigma1 = torch.stack(\n                [fd[l][\"mu\"] * (fd[l][\"N\"] - 1) / (sum_n - 1) for fd in labeled_fd_lst]\n            ).sum(dim=0)\n            sigma2 = torch.stack(\n                [\n                    fd[l][\"mu\"] * fd[l][\"mu\"].T * fd[l][\"N\"] / (sum_n - 1)\n                    for fd in labeled_fd_lst\n                ]\n            ).sum(dim=0)\n\n            sigma = sigma1 + sigma2 - sum_n / (sum_n - 1) * mu * mu.T\n\n            # 生成batchsize为200的数据样本，总共有10类，所以就是2k个样本\n            dist_c = np.random.normal(mu, sigma, size=(200, mu.size()[0]))\n            fd_d[l] = torch.tensor(dist_c)\n\n        return fd_d\n\n    def server_post_processing(self, ensemble_params_lst, ensemble_params, **kwargs):\n        # 特征参数提取\n        fd_lst = self.extract_lst(ensemble_params_lst, \"fd\")\n        fd_d = self.server_mean_feat(fd_lst)\n\n        # 准备好数据集，模型、优化器等等\n        trainset = DictDataset(fd_d)\n        trainloader, _ = get_dataloader(trainset, trainset, batch_size=64)\n        optimizer = optim.SGD(\n            self.head_model_base.parameters(), lr=1e-2, momentum=0.9, weight_decay=0.05\n        )\n        criterion = nn.CrossEntropyLoss()\n        self.glob_model_base = self.load_model(\n            self.head_model_base, ensemble_params[\"w_glob\"]\n        )\n\n        # 重新训练分类器\n        trainer = Trainer(\n            self.head_model_base, optimizer, criterion, kwargs[\"device\"], False\n        )\n        trainer.train(trainloader, epochs=1)\n        w_train = trainer.weight\n\n        for k in w_train.keys():\n            ensemble_params[\"w_glob\"][k] = w_train[k].cpu()\n\n        return ensemble_params\n\n    def server(self, ensemble_params_lst, round_, **kwargs):\n        ensemble_params = super().server(ensemble_params_lst, round_)\n        return self.server_post_processing(\n            ensemble_params_lst, ensemble_params, **kwargs\n        )\n\n\nclass DFCCVR(CCVR):\n    def __init__(self, model_base, head_model_base, strategy):\n        super().__init__(head_model_base, strategy)\n        self.model_base = model_base\n        self.df = MyDF(model_base, strategy)\n\n    def server(self, ensemble_params_lst, round_, **kwargs):\n        # 先DF后CCVR\n        ensemble_params = self.df.server(ensemble_params_lst, round_, **kwargs)\n        return self.server_post_processing(\n            ensemble_params_lst, ensemble_params, **kwargs\n        )\n", "meta": {"hexsha": "c3e324d3815d6012bfec8fe94566b8b88c5a3f76", "size": 7237, "ext": "py", "lang": "Python", "max_stars_repo_path": "example/MOON_reproduction/MyStrategys.py", "max_stars_repo_name": "wnma3mz/flearn", "max_stars_repo_head_hexsha": "df3c837bb164ec81736a3a64aaa85f574e7f67fa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-11-11T15:09:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:15:06.000Z", "max_issues_repo_path": "example/MOON_reproduction/MyStrategys.py", "max_issues_repo_name": "wnma3mz/flearn", "max_issues_repo_head_hexsha": "df3c837bb164ec81736a3a64aaa85f574e7f67fa", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/MOON_reproduction/MyStrategys.py", "max_forks_repo_name": "wnma3mz/flearn", "max_forks_repo_head_hexsha": "df3c837bb164ec81736a3a64aaa85f574e7f67fa", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4619047619, "max_line_length": 168, "alphanum_fraction": 0.5934779605, "include": true, "reason": "import numpy", "num_tokens": 1803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1824879583914458}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nReferences\n----------\n-   :cite:`Meng2015c` : Meng, J., Simon, F., Hanika, J., & Dachsbacher, C.\n    (2015). Physically Meaningful Rendering using Tristimulus Colours. Computer\n    Graphics Forum, 34(4), 31-40. doi:10.1111/cgf.12676\n-   :cite:`Smits1999a` : Smits, B. (1999). An RGB-to-Spectrum Conversion for\n    Reflectances. Journal of Graphics Tools, 4(4), 11-22.\n    doi:10.1080/10867651.1999.10487511\n\"\"\"\n\nfrom __future__ import absolute_import\n\nfrom colour.utilities import (CaseInsensitiveMapping, as_float_array,\n                              filter_kwargs)\n\nfrom .dataset import *  # noqa\nfrom . import dataset\nfrom .meng2015 import XYZ_to_sd_Meng2015\nfrom .smits1999 import RGB_to_sd_Smits1999\n\n__all__ = []\n__all__ += dataset.__all__\n__all__ += ['XYZ_to_sd_Meng2015']\n__all__ += ['RGB_to_sd_Smits1999']\n\nXYZ_TO_SD_METHODS = CaseInsensitiveMapping({\n    'Meng 2015': XYZ_to_sd_Meng2015,\n    'Smits 1999': RGB_to_sd_Smits1999,\n})\nXYZ_TO_SD_METHODS.__doc__ = \"\"\"\nSupported spectral distribution recovery methods.\n\nReferences\n----------\n:cite:`Meng2015c`, :cite:`Smits1999a`\n\nXYZ_TO_SD_METHODS : CaseInsensitiveMapping\n    **{'Meng 2015', 'Smits 1999'}**\n\"\"\"\n\n\ndef XYZ_to_sd(XYZ, method='Meng 2015', **kwargs):\n    \"\"\"\n    Recovers the spectral distribution of given *CIE XYZ* tristimulus\n    values using given method.\n\n    Parameters\n    ----------\n    XYZ : array_like\n        *CIE XYZ* tristimulus values to recover the spectral distribution\n        from.\n    method : unicode, optional\n        **{'Meng 2015', 'Smits 1999'}**,\n        Computation method.\n\n    Other Parameters\n    ----------------\n    cmfs : XYZ_ColourMatchingFunctions\n        {:func:`colour.recovery.XYZ_to_sd_Meng2015`},\n        Standard observer colour matching functions.\n    interval : numeric, optional\n        {:func:`colour.recovery.XYZ_to_sd_Meng2015`},\n        Wavelength :math:`\\\\lambda_{i}` range interval in nm. The smaller\n        ``interval`` is, the longer the computations will be.\n    optimisation_parameters : dict_like, optional\n        {:func:`colour.recovery.XYZ_to_sd_Meng2015`},\n        Parameters for :func:`scipy.optimize.minimize` definition.\n\n    Returns\n    -------\n    SpectralDistribution\n        Recovered spectral distribution.\n\n    Notes\n    -----\n\n    +------------+-----------------------+---------------+\n    | **Domain** | **Scale - Reference** | **Scale - 1** |\n    +============+=======================+===============+\n    | ``XYZ``    | [0, 1]                | [0, 1]        |\n    +------------+-----------------------+---------------+\n\n    -   *Smits (1999)* method will internally convert given *CIE XYZ*\n        tristimulus values to *RGB* colourspace array assuming equal energy\n        illuminant *E*.\n\n    References\n    ----------\n    :cite:`Meng2015c`, :cite:`Smits1999a`\n\n    Examples\n    --------\n\n    *Meng (2015)* reflectance recovery:\n\n    >>> import numpy as np\n    >>> from colour.utilities import numpy_print_options\n    >>> from colour.colorimetry import (\n    ...     STANDARD_OBSERVERS_CMFS, SpectralShape, sd_to_XYZ_integration)\n    >>> XYZ = np.array([0.21781186, 0.12541048, 0.04697113])\n    >>> cmfs = (\n    ...     STANDARD_OBSERVERS_CMFS['CIE 1931 2 Degree Standard Observer'].\n    ...     copy().align(SpectralShape(360, 780, 10))\n    ... )\n    >>> sd = XYZ_to_sd(XYZ, cmfs=cmfs)\n    >>> with numpy_print_options(suppress=True):\n    ...     # Doctests skip for Python 2.x compatibility.\n    ...     sd  # doctest: +SKIP\n    SpectralDistribution([[ 360.        ,    0.0780114...],\n                          [ 370.        ,    0.0780316...],\n                          [ 380.        ,    0.0780471...],\n                          [ 390.        ,    0.0780351...],\n                          [ 400.        ,    0.0779702...],\n                          [ 410.        ,    0.0778033...],\n                          [ 420.        ,    0.0770958...],\n                          [ 430.        ,    0.0748008...],\n                          [ 440.        ,    0.0693230...],\n                          [ 450.        ,    0.0601136...],\n                          [ 460.        ,    0.0477407...],\n                          [ 470.        ,    0.0334964...],\n                          [ 480.        ,    0.0193352...],\n                          [ 490.        ,    0.0074858...],\n                          [ 500.        ,    0.0001225...],\n                          [ 510.        ,    0.       ...],\n                          [ 520.        ,    0.       ...],\n                          [ 530.        ,    0.       ...],\n                          [ 540.        ,    0.0124896...],\n                          [ 550.        ,    0.0389831...],\n                          [ 560.        ,    0.0775105...],\n                          [ 570.        ,    0.1247947...],\n                          [ 580.        ,    0.1765339...],\n                          [ 590.        ,    0.2281918...],\n                          [ 600.        ,    0.2751347...],\n                          [ 610.        ,    0.3140115...],\n                          [ 620.        ,    0.3433561...],\n                          [ 630.        ,    0.3635777...],\n                          [ 640.        ,    0.3765428...],\n                          [ 650.        ,    0.3841726...],\n                          [ 660.        ,    0.3883633...],\n                          [ 670.        ,    0.3905415...],\n                          [ 680.        ,    0.3916742...],\n                          [ 690.        ,    0.3922554...],\n                          [ 700.        ,    0.3925427...],\n                          [ 710.        ,    0.3926783...],\n                          [ 720.        ,    0.3927330...],\n                          [ 730.        ,    0.3927586...],\n                          [ 740.        ,    0.3927548...],\n                          [ 750.        ,    0.3927681...],\n                          [ 760.        ,    0.3927813...],\n                          [ 770.        ,    0.3927840...],\n                          [ 780.        ,    0.3927536...]],\n                         interpolator=SpragueInterpolator,\n                         interpolator_args={},\n                         extrapolator=Extrapolator,\n                         extrapolator_args={...})\n    >>> sd_to_XYZ_integration(sd) / 100  # doctest: +ELLIPSIS\n    array([ 0.2178545...,  0.1254141...,  0.0470095...])\n\n    *Smits (1999)* reflectance recovery:\n\n    >>> sd = XYZ_to_sd(XYZ, method='Smits 1999')\n    >>> with numpy_print_options(suppress=True):\n    ...     sd  # doctest: +ELLIPSIS\n    SpectralDistribution([[ 380.        ,    0.07691923],\n                          [ 417.7778    ,    0.0587005 ],\n                          [ 455.5556    ,    0.03943195],\n                          [ 493.3333    ,    0.03024978],\n                          [ 531.1111    ,    0.02750692],\n                          [ 568.8889    ,    0.02808645],\n                          [ 606.6667    ,    0.34298985],\n                          [ 644.4444    ,    0.41185795],\n                          [ 682.2222    ,    0.41185795],\n                          [ 720.        ,    0.41180754]],\n                         interpolator=LinearInterpolator,\n                         interpolator_args={},\n                         extrapolator=Extrapolator,\n                         extrapolator_args={...})\n    >>> sd_to_XYZ_integration(sd) / 100  # doctest: +ELLIPSIS\n    array([ 0.2004523...,  0.1105627...,  0.0420964...])\n    \"\"\"\n\n    a = as_float_array(XYZ)\n\n    function = XYZ_TO_SD_METHODS[method]\n\n    if function is RGB_to_sd_Smits1999:\n        from colour.recovery.smits1999 import XYZ_to_RGB_Smits1999\n\n        a = XYZ_to_RGB_Smits1999(XYZ)\n\n    return function(a, **filter_kwargs(function, **kwargs))\n\n\n__all__ += ['XYZ_TO_SD_METHODS', 'XYZ_to_sd']\n", "meta": {"hexsha": "d4ea8f050d3a77ed92633d7b47d480c983791647", "size": 7825, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/recovery/__init__.py", "max_stars_repo_name": "sobotka/colour", "max_stars_repo_head_hexsha": "aa3fe95fba83ffc0f3ce1eb6aca85e6d8f3bde51", "max_stars_repo_licenses": ["Cube", "BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-03T20:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-09T18:19:06.000Z", "max_issues_repo_path": "colour/recovery/__init__.py", "max_issues_repo_name": "sobotka/colour", "max_issues_repo_head_hexsha": "aa3fe95fba83ffc0f3ce1eb6aca85e6d8f3bde51", "max_issues_repo_licenses": ["Cube", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/recovery/__init__.py", "max_forks_repo_name": "sobotka/colour", "max_forks_repo_head_hexsha": "aa3fe95fba83ffc0f3ce1eb6aca85e6d8f3bde51", "max_forks_repo_licenses": ["Cube", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7208121827, "max_line_length": 79, "alphanum_fraction": 0.4391054313, "include": true, "reason": "import numpy", "num_tokens": 2131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.1824879513065744}}
{"text": "import torch\nimport numpy as np\n\n\ndef torch_nms(tlbr, scores, classes=None, thresh=.5, bias=0, fast=False):\n    \"\"\"\n    Non maximum suppression implemented with pytorch tensors\n\n    CURRENTLY NOT WORKING\n\n    Args:\n        tlbr (Tensor): Bounding boxes of one image in the format (tlbr)\n        scores (Tensor): Scores of each box\n        classes (Tensor, optional): the classes of each box. If specified nms is applied to each class separately.\n        thresh (float): iou threshold\n\n    Returns:\n        ByteTensor: keep: boolean array indicating which boxes were not pruned.\n\n    Example:\n        >>> # DISABLE_DOCTEST\n        >>> import torch\n        >>> import numpy as np\n        >>> tlbr = torch.FloatTensor(np.array([\n        >>>     [0, 0, 100, 100],\n        >>>     [100, 100, 10, 10],\n        >>>     [10, 10, 100, 100],\n        >>>     [50, 50, 100, 100],\n        >>>     [100, 100, 130, 130],\n        >>>     [100, 100, 130, 130],\n        >>>     [100, 100, 130, 130],\n        >>> ], dtype=np.float32))\n        >>> scores = torch.FloatTensor(np.array([.1, .5, .9, .1, .3, .5, .4]))\n        >>> classes = torch.FloatTensor(np.array([0, 0, 0, 0, 0, 0]))\n        >>> thresh = .5\n        >>> keep = torch_nms(tlbr, scores, classes, thresh)\n        >>> bboxes[keep]\n\n    Example:\n        >>> # DISABLE_DOCTEST\n        >>> import torch\n        >>> import numpy as np\n        >>> # Test to check that conflicts are correctly resolved\n        >>> tlbr = torch.FloatTensor(np.array([\n        >>>     [100, 100, 150, 101],\n        >>>     [120, 100, 180, 101],\n        >>>     [150, 100, 200, 101],\n        >>> ], dtype=np.float32))\n        >>> scores = torch.FloatTensor(np.linspace(.8, .9, len(tlbr)))\n        >>> classes = None\n        >>> thresh = .3\n        >>> keep = torch_nms(tlbr, scores, classes, thresh, fast=False)\n        >>> bboxes[keep]\n    \"\"\"\n    if tlbr.numel() == 0:\n        return []\n\n    # Sort coordinates by descending score\n    ordered_scores, order = scores.sort(0, descending=True)\n\n    from netharn import util\n    boxes = util.Boxes(tlbr[order], 'tlbr')\n    ious = boxes.ious(boxes, bias=bias)\n\n    # if False:\n    #     x1, y1, x2, y2 = tlbr[order].split(1, 1)\n\n    #     # Compute dx and dy between each pair of boxes (these mat contain every pair twice...)\n    #     dx = (x2.min(x2.t()) - x1.max(x1.t())).clamp_(min=0)\n    #     dy = (y2.min(y2.t()) - y1.max(y1.t())).clamp_(min=0)\n\n    #     # Compute iou\n    #     intersections = dx * dy\n    #     areas = (x2 - x1) * (y2 - y1)\n    #     unions = (areas + areas.t()) - intersections\n    #     ious = intersections / unions\n\n    # Filter based on iou (and class)\n    conflicting = (ious > thresh).triu(1)\n\n    if classes is not None:\n        ordered_classes = classes[order]\n        same_class = (ordered_classes.unsqueeze(0) == ordered_classes.unsqueeze(1))\n        conflicting = (conflicting & same_class)\n    # Now we have a 2D matrix where conflicting[i, j] indicates if box[i]\n    # conflicts with box[j]. For each box[i] we want to only keep the first\n    # one that does not conflict with any other box[j].\n\n    # Find out how many conflicts each ordered box has with other boxes that\n    # have higher scores than it does. In other words...\n    # n_conflicts[i] is the number of conflicts box[i] has with other boxes\n    # that have a **higher score** than box[i] does. We will definately\n    # keep any box where n_conflicts is 0, but we need to postprocess because\n    # we might actually keep some boxes currently marked as conflicted.\n    n_conflicts = conflicting.sum(0).byte()\n\n    if not fast:\n        # It is not enought to simply use all places where there are no\n        # conflicts. Say we have boxes A, B, and C, where A conflicts with B,\n        # B conflicts with C but A does not conflict with C. The fact that we\n        # use A should mean that C is not longer conflicted.\n\n        if True:\n            # Marginally faster. best=618.2 us\n            ordered_keep = np.zeros(len(conflicting), dtype=np.uint8)\n            supress = np.zeros(len(conflicting), dtype=np.bool)\n            for i, row in enumerate(conflicting.cpu().numpy() > 0):\n                if not supress[i]:\n                    ordered_keep[i] = 1\n                    supress[row] = 1\n            ordered_keep = torch.ByteTensor(ordered_keep).to(tlbr.device)\n        else:\n            # Marginally slower: best=1.382 ms,\n            n_conflicts_post = n_conflicts.cpu()\n            conflicting = conflicting.cpu()\n\n            keep_len = len(n_conflicts_post) - 1\n            for i in range(1, keep_len):\n                if n_conflicts_post[i] > 0:\n                    n_conflicts_post -= conflicting[i]\n\n            n_conflicts = n_conflicts_post.to(n_conflicts.device)\n            ordered_keep = (n_conflicts == 0)\n    else:\n        # Now we can simply keep any box that has no conflicts.\n        ordered_keep = (n_conflicts == 0)\n\n    # Unsort, so keep is aligned with input boxes\n    keep = ordered_keep.new(*ordered_keep.size())\n    keep.scatter_(0, order, ordered_keep)\n    return keep\n\n\ndef test_class_torch():\n    import numpy as np\n    import torch\n    import netharn as nh\n    import ubelt as ub\n    # from netharn.util.nms.torch_nms import torch_nms\n    # from netharn.util import non_max_supression\n\n    thresh = .5\n\n    num = 500\n    rng = nh.util.ensure_rng(0)\n    cpu_boxes = nh.util.Boxes.random(num, scale=400.0, rng=rng, format='tlbr', tensor=True)\n    cpu_tlbr = cpu_boxes.to_tlbr().data\n    # cpu_scores = torch.Tensor(rng.rand(len(cpu_tlbr)))\n    # make all scores unique to ensure comparability\n    cpu_scores = torch.Tensor(np.linspace(0, 1, len(cpu_tlbr)))\n    cpu_cls = torch.LongTensor(rng.randint(0, 10, len(cpu_tlbr)))\n\n    tlbr = cpu_boxes.to_tlbr().data.to('cuda')\n    scores = cpu_scores.to('cuda')\n    classes = cpu_cls.to('cuda')\n\n    keep1 = []\n    for idxs in ub.group_items(range(len(classes)), classes.cpu().numpy()).values():\n        # cls_tlbr = tlbr.take(idxs, axis=0)\n        # cls_scores = scores.take(idxs, axis=0)\n        cls_tlbr = tlbr[idxs]\n        cls_scores = scores[idxs]\n        cls_keep = torch_nms(cls_tlbr, cls_scores, thresh=thresh, bias=0)\n        keep1.extend(list(ub.compress(idxs, cls_keep.cpu().numpy())))\n    keep1 = sorted(keep1)\n\n    keep_ = torch_nms(tlbr, scores, classes=classes, thresh=thresh, bias=0)\n    keep2 = np.where(keep_.cpu().numpy())[0].tolist()\n\n    keep3 = nh.util.non_max_supression(tlbr.cpu().numpy(),\n                                       scores.cpu().numpy(),\n                                       classes=classes.cpu().numpy(),\n                                       thresh=thresh, bias=0, impl='gpu')\n\n    print(len(keep1))\n    print(len(keep2))\n    print(len(keep3))\n\n    print(set(keep1) - set(keep2))\n    print(set(keep2) - set(keep1))\n\n\ndef _benchmark():\n    \"\"\"\n    python -m netharn.util.nms.torch_nms _benchmark --show\n\n    SeeAlso:\n        PJR Darknet NonMax supression\n        https://github.com/pjreddie/darknet/blob/master/src/box.c\n\n        Lightnet NMS\n        https://gitlab.com/EAVISE/lightnet/blob/master/lightnet/data/transform/_postprocess.py#L116\n\n    \"\"\"\n    import torch\n    import numpy as np\n    import netharn as nh\n    from netharn.util.nms.torch_nms import torch_nms\n    from netharn.util import non_max_supression\n    import ubelt as ub\n    import itertools as it\n\n    N = 100\n    bestof = 10\n\n    ydata = ub.ddict(list)\n    # xdata = [10, 20, 40, 80, 100, 200, 300, 400, 500, 600, 700, 1000, 1500, 2000]\n\n    # max number of boxes yolo will spit out at a time\n    max_boxes = 19 * 19 * 5\n\n    xdata = [10, 20, 40, 80, 100, 200, 300, 400, 500, 600, 700, 1000, 1500, max_boxes]\n    # xdata = [10, 20, 40, 80, 100, 200, 300, 400, 500]\n    xdata = [10, 100, 500]\n\n    rng = nh.util.ensure_rng(0)\n\n    thresh = 0.5\n\n    for num in xdata:\n        print('\\n\\n---- number of boxes = {} ----\\n'.format(num))\n\n        outputs = {}\n\n        # Build random test boxes and scores\n        cpu_boxes = nh.util.Boxes.random(num, scale=10.0, rng=rng, format='tlbr', tensor=True)\n        cpu_tlbr = cpu_boxes.to_tlbr().data\n        # cpu_scores = torch.Tensor(rng.rand(len(cpu_tlbr)))\n        # make all scores unique to ensure comparability\n        cpu_scores = torch.Tensor(np.linspace(0, 1, len(cpu_tlbr)))\n        cpu_cls = torch.LongTensor(rng.randint(0, 10, len(cpu_tlbr)))\n\n        # Format boxes in lightnet format\n        cpu_ln_boxes = torch.cat([cpu_boxes.to_cxywh().data, cpu_scores[:, None], cpu_cls.float()[:, None]], dim=-1)\n\n        # Move boxes to numpy\n        np_tlbr = cpu_tlbr.numpy()\n        np_scores = cpu_scores.numpy()\n        np_cls = cpu_cls.numpy()  # NOQA\n\n        gpu = torch.device('cuda', 0)\n\n        measure_gpu = torch.cuda.is_available()\n        measure_cpu = False or not torch.cuda.is_available()\n\n        def _ln_output_to_keep(ln_output, ln_boxes):\n            keep = []\n            for row in ln_output:\n                # Find the index that we kept\n                idxs = np.where(np.all(np.isclose(ln_boxes, row), axis=1))[0]\n                assert len(idxs) == 1\n                keep.append(idxs[0])\n            assert np.all(np.isclose(ln_boxes[keep], ln_output))\n            return keep\n\n        if measure_gpu:\n            # Move boxes to the GPU\n            gpu_tlbr = cpu_tlbr.to(gpu)\n            gpu_scores = cpu_scores.to(gpu)\n            gpu_cls = cpu_cls.to(gpu)  # NOQA\n            gpu_ln_boxes = cpu_ln_boxes.to(gpu)\n\n            t1 = ub.Timerit(N, bestof=bestof, label='torch(gpu)')\n            for timer in t1:\n                with timer:\n                    keep = torch_nms(gpu_tlbr, gpu_scores, thresh=thresh)\n                    torch.cuda.synchronize()\n            ydata[t1.label].append(t1.min())\n            outputs[t1.label] = np.where(keep.cpu().numpy())[0]\n\n            t1 = ub.Timerit(N, bestof=bestof, label='cython(gpu)')\n            for timer in t1:\n                with timer:\n                    keep = non_max_supression(np_tlbr, np_scores, thresh=thresh, impl='gpu')\n                    torch.cuda.synchronize()\n            ydata[t1.label].append(t1.min())\n            outputs[t1.label] = sorted(keep)\n\n            from lightnet.data.transform._postprocess import NonMaxSupression\n            t1 = ub.Timerit(N, bestof=bestof, label='lightnet-slow(gpu)')\n            for timer in t1:\n                with timer:\n                    ln_output = NonMaxSupression._nms(gpu_ln_boxes, nms_thresh=thresh, class_nms=False, fast=False)\n                    torch.cuda.synchronize()\n            # convert lightnet NMS output to keep for consistency\n            keep = _ln_output_to_keep(ln_output, gpu_ln_boxes)\n            ydata[t1.label].append(t1.min())\n            outputs[t1.label] = sorted(keep)\n\n            if False:\n                t1 = ub.Timerit(N, bestof=bestof, label='lightnet-fast(gpu)')\n                for timer in t1:\n                    with timer:\n                        ln_output = NonMaxSupression._nms(gpu_ln_boxes, nms_thresh=thresh, class_nms=False, fast=True)\n                        torch.cuda.synchronize()\n                # convert lightnet NMS output to keep for consistency\n                keep = _ln_output_to_keep(ln_output, gpu_ln_boxes)\n                ydata[t1.label].append(t1.min())\n                outputs[t1.label] = sorted(keep)\n\n        if measure_cpu:\n            t1 = ub.Timerit(N, bestof=bestof, label='torch(cpu)')\n            for timer in t1:\n                with timer:\n                    keep = torch_nms(cpu_tlbr, cpu_scores, thresh=thresh)\n            ydata[t1.label].append(t1.min())\n            outputs[t1.label] = np.where(keep.cpu().numpy())[0]\n\n        if True:\n            t1 = ub.Timerit(N, bestof=bestof, label='cython(cpu)')\n            for timer in t1:\n                with timer:\n                    keep = non_max_supression(np_tlbr, np_scores, thresh=thresh, impl='cpu')\n            ydata[t1.label].append(t1.min())\n            outputs[t1.label] = sorted(keep)\n\n            t1 = ub.Timerit(N, bestof=bestof, label='numpy(cpu)')\n            for timer in t1:\n                with timer:\n                    keep = non_max_supression(np_tlbr, np_scores, thresh=thresh, impl='py')\n            ydata[t1.label].append(t1.min())\n            outputs[t1.label] = sorted(keep)\n\n        # Check that all kept boxes do not have more than `threshold` ious\n        for key, idxs in outputs.items():\n            ious = nh.util.box_ious(np_tlbr[idxs], np_tlbr[idxs])\n            max_iou = (np.tril(ious) - np.eye(len(ious))).max()\n            if max_iou > thresh:\n                print('{} produced a bad result with max_iou={}'.format(key, max_iou))\n\n        # Check result consistency:\n        print('\\nResult stats:')\n        for key in sorted(outputs.keys()):\n            print('    * {:<20}: num={}'.format(key, len(outputs[key])))\n\n        print('\\nResult overlaps (method1, method2: jaccard):')\n        datas = []\n        for k1, k2 in it.combinations(sorted(outputs.keys()), 2):\n            idxs1 = set(outputs[k1])\n            idxs2 = set(outputs[k2])\n            jaccard = len(idxs1 & idxs2) / len(idxs1 | idxs2)\n            datas.append((k1, k2, jaccard))\n        datas = sorted(datas, key=lambda x: -x[2])\n        for k1, k2, jaccard in datas:\n            print('    * {:<20}, {:<20}: {:0.4f}'.format(k1, k2, jaccard))\n\n    nh.util.mplutil.autompl()\n    nh.util.mplutil.multi_plot(xdata, ydata, xlabel='num boxes', ylabel='seconds')\n    nh.util.show_if_requested()\n\n\nif __name__ == '__main__':\n    \"\"\"\n    CommandLine:\n        python -m netharn.util.nms.torch_nms all\n    \"\"\"\n    import xdoctest\n    xdoctest.doctest_module(__file__)\n", "meta": {"hexsha": "f742e89cac944a35042578518a26b101bfb90ce9", "size": 13637, "ext": "py", "lang": "Python", "max_stars_repo_path": "netharn/util/nms/torch_nms.py", "max_stars_repo_name": "angiemsu/netharn", "max_stars_repo_head_hexsha": "728cb40aad299baf62c689430d07b29c67d8cf21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "netharn/util/nms/torch_nms.py", "max_issues_repo_name": "angiemsu/netharn", "max_issues_repo_head_hexsha": "728cb40aad299baf62c689430d07b29c67d8cf21", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "netharn/util/nms/torch_nms.py", "max_forks_repo_name": "angiemsu/netharn", "max_forks_repo_head_hexsha": "728cb40aad299baf62c689430d07b29c67d8cf21", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9860724234, "max_line_length": 118, "alphanum_fraction": 0.5762264428, "include": true, "reason": "import numpy", "num_tokens": 3663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.30404168127272885, "lm_q1q2_score": 0.18248227782979332}}
{"text": "import numpy as np\nimport netCDF4 as nc\nimport csv\nfrom hurp.RDConverter import * #RDWGSConverter\nconv = RDWGSConverter()\nimport matplotlib.pyplot as plt\nfrom scipy.interpolate import griddata\nfrom sys import platform\n#from mpl_toolkits.basemap import interp as mapinterp\nfrom itertools import product\nfrom os.path import exists\nimport cPickle\n\ndef msg(string,type=2):\n    import sys\n\n    if type == 1: print(string),\n    if type == 2: print(string)\n    \n    sys.stdout.flush()\n    return\n\ndef nei2wrf(NEIpath, wrfchemipath, wrfoutpath, Times, month):\n    '''\n    The purpose of this script is to write WRF-Chem emission files for HURP.\n    There are three input sources:\n    - NEI - Netherlands Emission Inventory: a list of area sources of CO2, NOx and PM10, with RD coordinates\n            This data needs to be gridded.\n    - wrfout - contains the information of the domains in HURP, one wrfout file for each domain. The coordinates are in WGS84 lat/lon, and spaced at fixed distance (km) intervals.\n\n    Four wrfchemi output files will be written, one for each domain, containing the gridded emission data projected on the WRF grids.\n    '''\n    #--- settings\n    FS               = 8 # FontSize\n    domains          = ['d04','d03','d02','d01']\n    kg2mol           = dict()\n    kg2mol['CO2']    = 1000./44. # 1 kmol = 44 kg       | 1/44 kmol = 1 kg | 1 kg = 1000/44 mol\n    kg2mol['NOx']    = 1000./30.8 # 1 kmol = 44 kg       | 1/44 kmol = 1 kg | 1 kg = 1000/44 mol\n    kg2mol['PM10']   = 1.\n    yr2hr            = 1./(365.*24.)\n    Nsnaps           = 14 # 13 SNAPS + 1 for road traffic\n    zTimes           = ['00z','12z']\n    tracers          = ['NOx','PM10','CO2']\n    selectedtracers  = tracers[:2]\n    dows             = ('Mon','Tue','Wed','Thu','Fri','Sat','Sun')\n    moys             = ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')\n\n                                    # in NER output file                                 # In Ingrid Super's file\n    SNAPnames                    = [ [ '01: Afvalverwijdering                       '  ],   #SNAP9='waste treatment and disposal';\n                                    [ '02: Bouw                                    '  ],   # \n                                    [ '03: Chemische Industrie                     '  ],   #SNAP6='solvents and other product use';\n                                    [ '04: Consumenten                             '  ],   # \n                                    [ '05: Drinkwatervoorziening                   '  ],   # \n                                    [ '06: Energiesector                           '  ],   #SNAP1='combustion in energy and transformation industries';\n                                    [ '07: Handel, Diensten en Overheid (HDO)      '  ],   # SNAP2='non-industrial combustion plants';\n                                    [ '08: Landbouw                                '  ],   #SNAP10='agriculture'\n                                    [ '09: Natuur                                  '  ],   # \n                                    [ '10: Overige industrie                       '  ],   #SNAP3='combustion in manufacturing industry'; SNAP4='production processes'\n                                    [ '11: Raffinaderijen                          '  ],   #SNAP5='extraction and distribution of fossil fuels and geothermal energy';\n                                    [ '12: Riolering en waterzuiveringsinstallaties'  ],   #\n                                    [ '13: Verkeer en vervoer - Except road traffic'  ],   #SNAP8='other mobile sources and machinery'\n                                    [ '14: Verkeer en vervoer - Wegverkeer         '  ] ]  #SNAP7='road transport';\n                            \n                        \n    # 01: Afvalverwerking                          = SNAP  9 'waste treatment and disposal';\n    # 02: Bouw                                     = SNAP  3 'combustion in manufacturing industry'; SNAP4='production processes' : SNAP 3 & 4 combined                                                                                                                                     \n    # 03: Chemische industrie                      = SNAP  6 'solvents and other product use';\n    # 04: Consumenten                              = SNAP  3 'combustion in manufacturing industry'; SNAP4='production processes' : SNAP 3 & 4 combined                                                                                                                                   \n    # 05: Drinkwatervoorziening                    = Constant genomen\n    # 06: Energiesector                            = SNAP  1 'combustion in energy and transformation industries';\n    # 07: Handel, Diensten en Overheid (HDO)       = SNAP 7 'road transport'\n    # 08: Landbouw                                 = SNAP 10 'agriculture'             \n    # 09: Natuur                                   = Constant genomen                                                                                                                      \n    # 10: Overige industrie                        = SNAP3='combustion in manufacturing industry'; SNAP4='production processes' : SNAP 3 & 4 combined\n    # 11: Raffinaderijen                           = SNAP  5 'extraction and distribution of fossil fuels and geothermal energy';                  \n    # 12: Riolering en waterzuiveringsinstallaties = Constant genomen\n    # 13: Verkeer en vervoer - Except road traffic = SNAP  8 'other mobile sources and machinery'\n    # 14: Verkeer en vervoer - Wegverkeer          = SNAP  7 'road transport'        \n    TP_moy = dict() # Month of Year\n    TP_dow = dict() # Day of Week\n    TP_hod = dict() # Hour of Day\n\n    # SNAP                      1      2      3      4      5      6      7      8      9     10     11     12     13     14\n    TP_moy['Jan'] = np.array([1.000, 1.060, 0.950, 1.060, 1.000, 1.200, 0.880, 0.450, 1.000, 1.060, 1.200, 1.000, 0.880, 0.880])\n    TP_moy['Feb'] = np.array([1.000, 1.047, 0.960, 1.047, 1.000, 1.150, 0.920, 1.300, 1.000, 1.047, 1.200, 1.000, 0.920, 0.920])\n    TP_moy['Mar'] = np.array([1.000, 1.035, 1.020, 1.035, 1.000, 1.050, 0.980, 2.350, 1.000, 1.035, 1.200, 1.000, 0.980, 0.980])\n    TP_moy['Apr'] = np.array([1.000, 1.010, 1.000, 1.010, 1.000, 1.000, 1.030, 1.700, 1.000, 1.010, 0.800, 1.000, 1.030, 1.030])\n    TP_moy['May'] = np.array([1.000, 0.985, 1.010, 0.985, 1.000, 0.900, 1.050, 0.850, 1.000, 0.985, 0.800, 1.000, 1.050, 1.050])\n    TP_moy['Jun'] = np.array([1.000, 0.960, 1.030, 0.960, 1.000, 0.850, 1.060, 0.850, 1.000, 0.960, 0.800, 1.000, 1.060, 1.060])\n    TP_moy['Jul'] = np.array([1.000, 0.965, 1.030, 0.965, 1.000, 0.800, 1.010, 0.850, 1.000, 0.965, 0.800, 1.000, 1.010, 1.010])\n    TP_moy['Aug'] = np.array([1.000, 0.935, 1.010, 0.935, 1.000, 0.875, 1.020, 1.000, 1.000, 0.935, 0.800, 1.000, 1.020, 1.020])\n    TP_moy['Sep'] = np.array([1.000, 0.995, 1.040, 0.995, 1.000, 0.950, 1.060, 1.100, 1.000, 0.995, 0.800, 1.000, 1.060, 1.060])\n    TP_moy['Oct'] = np.array([1.000, 1.010, 1.030, 1.010, 1.000, 1.000, 1.050, 0.650, 1.000, 1.010, 1.200, 1.000, 1.050, 1.050])\n    TP_moy['Nov'] = np.array([1.000, 1.023, 1.010, 1.023, 1.000, 1.075, 1.010, 0.450, 1.000, 1.023, 1.200, 1.000, 1.010, 1.010])\n    TP_moy['Dec'] = np.array([1.000, 0.975, 0.910, 0.975, 1.000, 1.150, 0.930, 0.450, 1.000, 0.975, 1.200, 1.000, 0.930, 0.930])\n\n    TP_dow['Mon'] = np.array([1.000, 1.050, 1.200, 1.050, 1.000, 1.060, 1.020, 1.000, 1.000, 1.050, 1.000, 1.000, 1.000, 1.020])\n    TP_dow['Tue'] = np.array([1.000, 1.050, 1.200, 1.050, 1.000, 1.060, 1.060, 1.000, 1.000, 1.050, 1.000, 1.000, 1.000, 1.060])\n    TP_dow['Wed'] = np.array([1.000, 1.050, 1.200, 1.050, 1.000, 1.060, 1.080, 1.000, 1.000, 1.050, 1.000, 1.000, 1.000, 1.080])\n    TP_dow['Thu'] = np.array([1.000, 1.050, 1.200, 1.050, 1.000, 1.060, 1.100, 1.000, 1.000, 1.050, 1.000, 1.000, 1.000, 1.100])\n    TP_dow['Fri'] = np.array([1.000, 1.050, 1.200, 1.050, 1.000, 1.060, 1.140, 1.000, 1.000, 1.050, 1.000, 1.000, 1.000, 1.140])\n    TP_dow['Sat'] = np.array([1.000, 0.910, 0.500, 0.910, 1.000, 0.850, 0.810, 1.000, 1.000, 0.910, 1.000, 1.000, 1.000, 0.810])\n    TP_dow['Sun'] = np.array([1.000, 0.840, 0.500, 0.840, 1.000, 0.850, 0.790, 1.000, 1.000, 0.840, 1.000, 1.000, 1.000, 0.790])\n\n    TP_hod['00']  = np.array([1.000, 0.875, 0.500, 0.875, 1.000, 0.790, 0.190, 0.600, 1.000, 0.875, 1.000, 1.000, 1.000, 0.190])\n    TP_hod['01']  = np.array([1.000, 0.875, 0.350, 0.875, 1.000, 0.720, 0.090, 0.600, 1.000, 0.875, 1.000, 1.000, 1.000, 0.090])\n    TP_hod['02']  = np.array([1.000, 0.890, 0.200, 0.890, 1.000, 0.720, 0.060, 0.600, 1.000, 0.890, 1.000, 1.000, 1.000, 0.060])\n    TP_hod['03']  = np.array([1.000, 0.910, 0.100, 0.910, 1.000, 0.710, 0.050, 0.600, 1.000, 0.910, 1.000, 1.000, 1.000, 0.050])\n    TP_hod['04']  = np.array([1.000, 0.940, 0.100, 0.940, 1.000, 0.740, 0.090, 0.600, 1.000, 0.940, 1.000, 1.000, 1.000, 0.090])\n    TP_hod['05']  = np.array([1.000, 0.975, 0.200, 0.975, 1.000, 0.800, 0.220, 0.650, 1.000, 0.975, 1.000, 1.000, 1.000, 0.220])\n    TP_hod['06']  = np.array([1.000, 1.010, 0.750, 1.010, 1.000, 0.920, 0.860, 0.750, 1.000, 1.010, 1.000, 1.000, 1.000, 0.860])\n    TP_hod['07']  = np.array([1.000, 1.045, 1.250, 1.045, 1.000, 1.080, 1.840, 0.900, 1.000, 1.045, 1.000, 1.000, 1.000, 1.840])\n    TP_hod['08']  = np.array([1.000, 1.080, 1.400, 1.080, 1.000, 1.190, 1.860, 1.100, 1.000, 1.080, 1.000, 1.000, 1.000, 1.860])\n    TP_hod['09']  = np.array([1.000, 1.110, 1.500, 1.110, 1.000, 1.220, 1.410, 1.350, 1.000, 1.110, 1.000, 1.000, 1.000, 1.410])\n    TP_hod['10']  = np.array([1.000, 1.140, 1.500, 1.140, 1.000, 1.210, 1.240, 1.450, 1.000, 1.140, 1.000, 1.000, 1.000, 1.240])\n    TP_hod['11']  = np.array([1.000, 1.150, 1.500, 1.150, 1.000, 1.210, 1.200, 1.600, 1.000, 1.150, 1.000, 1.000, 1.000, 1.200])\n    TP_hod['12']  = np.array([1.000, 1.110, 1.500, 1.110, 1.000, 1.170, 1.320, 1.650, 1.000, 1.110, 1.000, 1.000, 1.000, 1.320])\n    TP_hod['13']  = np.array([1.000, 1.120, 1.500, 1.120, 1.000, 1.150, 1.440, 1.750, 1.000, 1.120, 1.000, 1.000, 1.000, 1.440])\n    TP_hod['14']  = np.array([1.000, 1.125, 1.500, 1.125, 1.000, 1.140, 1.450, 1.700, 1.000, 1.125, 1.000, 1.000, 1.000, 1.450])\n    TP_hod['15']  = np.array([1.000, 1.080, 1.500, 1.080, 1.000, 1.130, 1.590, 1.550, 1.000, 1.080, 1.000, 1.000, 1.000, 1.590])\n    TP_hod['16']  = np.array([1.000, 1.040, 1.500, 1.040, 1.000, 1.100, 2.030, 1.350, 1.000, 1.040, 1.000, 1.000, 1.000, 2.030])\n    TP_hod['17']  = np.array([1.000, 1.005, 1.400, 1.005, 1.000, 1.070, 2.080, 1.100, 1.000, 1.005, 1.000, 1.000, 1.000, 2.080])\n    TP_hod['18']  = np.array([1.000, 0.975, 1.250, 0.975, 1.000, 1.040, 1.510, 0.900, 1.000, 0.975, 1.000, 1.000, 1.000, 1.510])\n    TP_hod['19']  = np.array([1.000, 0.950, 1.100, 0.950, 1.000, 1.020, 1.060, 0.750, 1.000, 0.950, 1.000, 1.000, 1.000, 1.060])\n    TP_hod['20']  = np.array([1.000, 0.925, 1.000, 0.925, 1.000, 1.020, 0.740, 0.650, 1.000, 0.925, 1.000, 1.000, 1.000, 0.740])\n    TP_hod['21']  = np.array([1.000, 0.905, 0.900, 0.905, 1.000, 1.010, 0.620, 0.600, 1.000, 0.905, 1.000, 1.000, 1.000, 0.620])\n    TP_hod['22']  = np.array([1.000, 0.890, 0.800, 0.890, 1.000, 0.960, 0.610, 0.600, 1.000, 0.890, 1.000, 1.000, 1.000, 0.610])\n    TP_hod['23']  = np.array([1.000, 0.875, 0.700, 0.875, 1.000, 0.880, 0.440, 0.600, 1.000, 0.875, 1.000, 1.000, 1.000, 0.440])\n                        \n    #--- input\n    if not 'progress' in globals(): progress = list()\n    if not 'NEIloaded' in progress:\n        #--- init\n        msg('Loading gridded NEI files: ',type=1)\n        E_nei             = dict()\n        for tracer in selectedtracers: \n            NEIncfilename = '%s/NEI_%s.nc'%(NEIpath,tracer)\n            msg('%s...'%NEIncfilename,type=1)\n            NEIncfile     = nc.Dataset(NEIncfilename,'r')\n            E_nei[tracer] = NEIncfile.variables['E_%s'%tracer][:] # kg per area \n            if not 'xnei' in globals():\n                xnei      = NEIncfile.variables['Longitude'][:]\n                ynei      = NEIncfile.variables['Latitude' ][:]\n                Xnei,Ynei = np.meshgrid(xnei,ynei)\n                ny,nx     = Xnei.shape\n            NEIncfile.close()\n        progress.append('NEIloaded')\n        \n    if not 'WRFOUTloaded' in progress:\n        msg('Loading lat/lon from wrfout...',type=1)\n        xlat = dict()\n        xlon = dict()\n        for domain in domains:\n            wrfoutfilename = '%s/wrfinput_%s'%(wrfoutpath,domain)\n            wrfoutfile     = nc.Dataset(wrfoutfilename,'r')       \n            xlat[domain]   = wrfoutfile.variables['XLAT' ][0,:] # centerpoints\n            xlon[domain]   = wrfoutfile.variables['XLONG'][0,:] # centerpoints\n            wrfoutfile.close()\n        progress.append('WRFOUTloaded')\n        msg('done.')\n        \n        \n    if not 'NEIinterpolatedToWRF' in progress:\n        Xwrf             = dict()\n        Ywrf             = dict()\n        E_wrf            = dict()\n        for tracer in selectedtracers:\n            picklefilename = '%s/E_wrf_%s.pickle'%(wrfoutpath,tracer)\n            if exists(picklefilename):\n                msg('Loading pre-cooked %s'%picklefilename,type=1)\n                pickledata = cPickle.load(open(picklefilename,'r'))\n                Xwrf,Ywrf,E_wrf_tmp,domains,tracers = pickledata\n                for domain in domains:\n                    E_wrf[domain,tracer] = E_wrf_tmp[domain,tracer]\n                del(E_wrf_tmp)\n            else:\n\n                # Note: d04 has a higher resolution than NEI --? interpolate or nearest neighbor\n                #       d03 has the same resolution as NEI, but may be shifted in x or y direction --> nearest neighbour regridding\n                #       d02 has a coarser resolution than NEI (but still fits in the NEI coverage?) --> mass conservative interpolation\n                #       d01 has a coarser resolution than NEI and also extends beyond the NEI domain --> Use MACC (how about MACC resolution?)\n                msg('Interpolating...',type=1)\n                for domain in domains:\n                    nlat,nlon    = xlat[domain].shape\n                    if (tracer == selectedtracers[0]):\n                        msg('Converting (lon,lat) in (x,y) for %s'%domain,type=1) \n                        Xwrf[domain] = np.empty((nlat,nlon))\n                        Ywrf[domain] = np.empty((nlat,nlon))\n                        for ilat,ilon in product(range(nlat), range(nlon)):\n                            x,y   = conv.fromWgsToRd([xlat[domain][ilat,ilon],xlon[domain][ilat,ilon]])\n            #               msg xlon[domain][ilat,ilon], xlat[domain][ilat,ilon], x, y\n                            Xwrf[domain][ilat,ilon] = x\n                            Ywrf[domain][ilat,ilon] = y\n                        \n                    msg('Interpolating %s...'%tracer,type=1)\n                    E_wrf[domain,tracer] = np.zeros((Nsnaps,nlat,nlon))\n                    for isnap in range(Nsnaps):\n                        msg('snap %02d...'%isnap,type=1) \n                        E_wrf[domain,tracer][isnap,:,:] = griddata((Xnei.flatten(),Ynei.flatten()),E_nei[tracer][isnap].flatten() , (Xwrf[domain],Ywrf[domain]),method='nearest')\n                    # of\n                    # sst_smooth = basemap.interp(sst_coarse, lons_sub[0,:], lats_sub[:,0], *np.meshgrid(lons, lats), order=1)\n                    #E_NOx_wrf [domain] = mapinterp(E_NOx_nei [Isnaps].sum(axis=0),xnei,ynei, Xwrf[domain],Ywrf[domain],order=0) # order 0:Nearest\n                    #E_PM10_wrf[domain] = mapinterp(E_PM10_nei[Isnaps].sum(axis=0),xnei,ynei, Xwrf[domain],Ywrf[domain],order=0) # order 1: bilinear\n\n                E_wrf_tmp = {}\n                for domain in domains:\n                    E_wrf_tmp[domain,tracer] = E_wrf[domain,tracer]\n                    pickledata     = (Xwrf,Ywrf,E_wrf_tmp,domains,tracers)\n                    cPickle.dump(pickledata,open(picklefilename,'wb'))\n                del(E_wrf_tmp)\n            \n        progress.append('NEIinterpolatedToWRF')\n        msg('done.')\n\n    moy = moys[month-1]\n    if not 'wrfchemi_written' in progress:\n        for domain,zTime,dow in product(domains,zTimes,dows):\n            print('Writing wrfchemifile for %s %s %s %s'%(domain,zTime,moy,dow))\n            #its = range(12) if zTime == '00z' else range(12,24)\n            zTimeOffset = 12 if zTime == '12z' else 0\n        \n            \n            wrfoutfilename            = '%s/wrfinput_%s'%(wrfoutpath,domain)\n            wrfoutfile                = nc.Dataset(wrfoutfilename,'r')\n            wrfchemifilename          = '%s/NEI_wrfchemi_%s_%s_%s_%s'%(wrfchemipath,zTime,domain,moy,dow)\n            wrfchemifile              = nc.Dataset(wrfchemifilename, 'w',format = 'NETCDF3_CLASSIC' )\n        \n            nz                        =  1\n            nlat,nlon                 = xlat[domain].shape\n\n            wrfchemifile.createDimension('Time',        None) # will be 12\n            wrfchemifile.createDimension('bottom_top' , nz)\n            wrfchemifile.createDimension('south_north', nlat)\n            wrfchemifile.createDimension('west_east'  , nlon)\n            wrfchemifile.createDimension('DateStrLen' , 19)\n        \n            ncTimes                   = wrfchemifile.createVariable('Times'               ,'c',dimensions=('Time','DateStrLen'))\n            ncXLAT                    = wrfchemifile.createVariable('XLAT'                ,'d',dimensions=('south_north','west_east'))\n            ncXLONG                   = wrfchemifile.createVariable('XLONG'               ,'d',dimensions=('south_north','west_east'))\n            ncE_NOx_stat              = wrfchemifile.createVariable('E_NOx_stat'          ,'d',dimensions=('Time','bottom_top','south_north','west_east'),fill_value = -1.e34)\n            ncE_NOx_traf              = wrfchemifile.createVariable('E_NOx_traf'          ,'d',dimensions=('Time','bottom_top','south_north','west_east'),fill_value = -1.e34)\n            ncE_PM10_stat             = wrfchemifile.createVariable('E_PM10_stat'         ,'d',dimensions=('Time','bottom_top','south_north','west_east'),fill_value = -1.e34)\n            ncE_PM10_traf             = wrfchemifile.createVariable('E_PM10_traf'         ,'d',dimensions=('Time','bottom_top','south_north','west_east'),fill_value = -1.e34)\n\n            ncTimes                   = Times[zTime]\n            ncXLAT.FieldType          = 104.\n            ncXLAT.MemoryOrder        = 'XY'\n            ncXLAT.description        = 'LATITUDE, SOUTH IS NEGATIVE'\n            ncXLAT.units              = 'degree_north'\n            ncXLAT.stagger            = ' ' \n            ncXLAT.coordinates        = 'XLONG XLAT'\n            ncXLAT[:]                 = xlat[domain]\n            ncXLONG.FieldType         = 104.\n            ncXLONG.MemoryOrder       = 'XY'\n            ncXLONG.description       = 'LONGGITUDE, WEST IS NEGATIVE'\n            ncXLONG.units             = 'degree_north'\n            ncXLONG.stagger           = ' ' \n            ncXLONG.coordinates       = 'XLONG XLAT'\n            ncXLONG[:]                = xlon[domain]\n\n            ncE_NOx_stat.FieldType    = 104.\n            ncE_NOx_stat.MemoryOrder  = 'XYZ'\n            ncE_NOx_stat.description  = 'NOx emissions from stationary sources'\n            ncE_NOx_stat.units        = 'mole/km2/hr'\n            ncE_NOx_stat.stagger      = ' ' \n            ncE_NOx_stat.coordinates  = 'XLONG XLAT'   \n            Isnap                     = range(13)\n            for it in range(12):     \n                TP                    = TP_hod['%02d'%(it+zTimeOffset)][Isnap] * TP_dow[dow][Isnap] * TP_moy[moy][Isnap]\n                TP2                   = np.tile(TP[...,np.newaxis,np.newaxis],(1,nlat,nlon))\n                ncE_NOx_stat[it,0,:,:]= (TP2 * E_wrf[domain,'NOx'][Isnap,:,:]).sum(axis=0)\n    #           ncE_NOx_stat[it,:]    = (TP2 * E_wrf[domain,'NOx'][Isnap]).sum(axis=0)     \n        \n            ncE_NOx_traf.FieldType    = 104.\n            ncE_NOx_traf.MemoryOrder  = 'XYZ'\n            ncE_NOx_traf.description  = 'NOx emissions from road traffic'\n            ncE_NOx_traf.units        = 'mole/km2/hr'\n            ncE_NOx_traf.stagger      = ' ' \n            ncE_NOx_traf.coordinates  = 'XLONG XLAT'   \n            Isnap                     = 13\n            for it in range(12):     \n                TP                    = TP_hod['%02d'%(it+zTimeOffset)][Isnap] * TP_dow[dow][Isnap] * TP_moy[moy][Isnap]\n                ncE_NOx_traf[it,0,:,:] = TP*E_wrf[domain,'NOx'][Isnap,:,:]\n    #           TP2                   = np.tile(TP[...,np.newaxis,np.newaxis],(1,nlat,nlon))            \n\n            ncE_PM10_stat.FieldType   = 104.\n            ncE_PM10_stat.MemoryOrder = 'XYZ'\n            ncE_PM10_stat.description = 'PM10 emissions from stationary sources'\n            ncE_PM10_stat.units       = 'kg/km2/hr'\n            ncE_PM10_stat.stagger     = ' ' \n            ncE_PM10_stat.coordinates = 'XLONG XLAT'  \n            Isnap                     = range(13)\n            for it in range(12):     \n                TP                    = TP_hod['%02d'%(it+zTimeOffset)][Isnap] * TP_dow[dow][Isnap] * TP_moy[moy][Isnap]\n                TP2                   = np.tile(TP[...,np.newaxis,np.newaxis],(1,nlat,nlon))\n                ncE_PM10_stat[it,0,:,:]= (TP2 * E_wrf[domain,'PM10'][Isnap,:,:]).sum(axis=0)\n\n            ncE_PM10_traf.FieldType   = 104.\n            ncE_PM10_traf.MemoryOrder = 'XYZ'\n            ncE_PM10_traf.description = 'PM10 emissions from road traffic'\n            ncE_PM10_traf.units       = 'kg/km2/hr'\n            ncE_PM10_traf.stagger     = ' ' \n            ncE_PM10_traf.coordinates = 'XLONG XLAT'  \n            Isnap                     = 13\n            for it in range(12):     \n                TP                    = TP_hod['%02d'%(it+zTimeOffset)][Isnap] * TP_dow[dow][Isnap] * TP_moy[moy][Isnap]\n    #           TP2                   = np.tile(TP[...,np.newaxis,np.newaxis],(1,nlat,nlon))\n                ncE_PM10_traf[it,0,:,:]   = TP*E_wrf[domain,'PM10'][Isnap,:,:]\n                \n            wrfchemifile.CEN_LAT      = wrfoutfile.getncattr('CEN_LAT')\n            wrfchemifile.CEN_LON      = wrfoutfile.getncattr('CEN_LON')\n            wrfchemifile.TRUELAT1     = wrfoutfile.getncattr('TRUELAT1')\n            wrfchemifile.TRUELAT2     = wrfoutfile.getncattr('TRUELAT2') \n            wrfchemifile.MOAD_CEN_LAT = wrfoutfile.getncattr('MOAD_CEN_LAT')\n            wrfchemifile.STAND_LON    = wrfoutfile.getncattr('STAND_LON')\n            wrfchemifile.POLE_LAT     = wrfoutfile.getncattr('POLE_LAT') \n            wrfchemifile.POLE_LON     = wrfoutfile.getncattr('POLE_LON')\n            wrfchemifile.GMT          = wrfoutfile.getncattr('GMT')  \n            wrfchemifile.JULYR        = wrfoutfile.getncattr('JULYR')\n            wrfchemifile.JULDAY       = wrfoutfile.getncattr('JULDAY')\n            wrfchemifile.MAP_PROJ     = wrfoutfile.getncattr('MAP_PROJ')\n            wrfchemifile.MMINLU       = wrfoutfile.getncattr('MMINLU')\n            wrfchemifile.NUM_LAND_CAT = wrfoutfile.getncattr('NUM_LAND_CAT')\n            wrfchemifile.ISWATER      = wrfoutfile.getncattr('ISWATER')\n            wrfchemifile.ISLAKE       = wrfoutfile.getncattr('ISLAKE')   \n            wrfchemifile.ISICE        = wrfoutfile.getncattr('ISICE')    \n            wrfchemifile.ISURBAN      = wrfoutfile.getncattr('ISURBAN')     \n            wrfchemifile.ISOILWATER   = wrfoutfile.getncattr('ISOILWATER')\n            \n            wrfchemifile.close()\n            progress.append('wrfchemi_written')\n\n    #--- output\n    if not 'dofig' in globals(): dofig = [None, False, True, False]\n    dofig = 4*(False,)\n    #E_CO2_nei = np.ma.masked_where(E_CO2_nei == 0, E_CO2_nei)\n    #E_NOx_nei = np.ma.masked_where(E_NOx_nei == 0, E_NOx_nei)\n    if dofig[1]:\n        tracer = 'NOx'\n        f = plt.figure(1)   \n        f.clf()\n        ax = f.add_subplot(111)\n        ax.scatter(data[tracer][:,0],data[tracer][:,1],s=20,c=np.log10(data[tracer][:,5]),marker='.',edgecolors=None)   \n        msg('fig 1 done.')\n    plt.show()\n        \n    if dofig[2]:\n        Isnap = range(14)\n        tracer = 'NOx'\n        f = plt.figure(2)\n        f.clf()\n        ax = f.add_subplot(111)\n        Z = E_nei[tracer][Isnap,:].sum(axis=0); Z = np.ma.masked_where(Z == 0, Z)\n        h=ax.pcolor(Xnei,Ynei,np.log10(Z))\n        for domain in domains[:3]:\n            xwrf = Xwrf[domain]\n            ywrf = Ywrf[domain]\n            ax.plot([xwrf.min(), xwrf.max(), xwrf.max(),xwrf.min(),xwrf.min()],[ywrf.min(),ywrf.min(),ywrf.max(),ywrf.max(),ywrf.min()],'k-')\n            cb = f.colorbar(h,orientation='vertical')   \n            pow = list()\n            for YTL in cb.ax.get_ymajorticklabels(): pow.append(np.double(YTL.get_text().replace(u'\\N{MINUS SIGN}', '-')))\n            cb.ax.set_yticklabels(np.power(10,pow),fontsize=FS)\n\n        msg('fig 2 done.')\n        dofig[2] = False\n\n    if dofig[3]:\n        msg('Doing figure 3...',type=1)\n        f = plt.figure(3)\n        f.clf()\n        for domain in domains[::-1]:\n            tracer = 'NOx'\n        \n            ax= f.add_subplot(111)\n            Z = E_wrf_stat[domain,tracer]+E_wrf_traf[domain,tracer]; Z = np.ma.masked_where(Z == 0, Z)\n            h=ax.pcolor(Xwrf[domain],Ywrf[domain],np.log10(Z),vmin=0,vmax=np.log10(2000))\n            xwrf = Xwrf[domain]\n            ywrf = Ywrf[domain]\n            ax.plot([xwrf.min(), xwrf.max(), xwrf.max(),xwrf.min(),xwrf.min()],[ywrf.min(),ywrf.min(),ywrf.max(),ywrf.max(),ywrf.min()],'k-')\n\n        cb = f.colorbar(h,orientation='vertical')   \n        pow = list()\n        for YTL in cb.ax.get_ymajorticklabels(): pow.append(np.double(YTL.get_text().replace(u'\\N{MINUS SIGN}', '-')))\n        cb.ax.set_yticklabels(np.power(10,pow),fontsize=FS)\n        \n        msg('Done figure 3.')\n\n\nif __name__==\"__main__\":\n    if platform == 'win32':\n        NEIpath      = 'U:/AMS_Stimulus_2016/Data_share/Emissions/NEI'\n        wrfchemipath = 'U:/AMS_Stimulus_2016/Data_share/Emissions/wrfchemi'\n        wrfoutpath   = 'S:/data/HURP/Adam_wrfout'\n    elif (platform == 'darwin' and exists('/Users/molen050/mnt/promise')): # CapeGrim\n        NEIpath      = '/Users/molen050/mnt/promise/WRF/michiel/HURP/Data_share/Emissions/NEI'\n        wrfchemipath = '/Users/molen050/mnt/promise/WRF/michiel/HURP/Data_share/Emissions/wrfchemi'\n        wrfoutpath   = '/Users/molen050/mnt/promise/WRF/michiel/HURP/Data_share/Domains'\n    elif (platform == 'linux2' ): # Cartesius\n        print('Setting env for Cartesius.')\n        NEIpath      = '/projects/0/aams/wrfv3/Data_share/Emissions/NEI'\n        wrfchemipath = '/projects/0/aams/wrfv3/Data_share/Emissions/wrfchemi'\n        wrfoutpath   = '/projects/0/aams/wrfv3/OutputMichiel/HURP_20150630-20150704'    \n    else:  # maunaloa\n        NEIpath      = '/Storage/WRF/michiel/HURP/Data_share/Emissions/NEI'\n        wrfchemipath = '/Storage/WRF/michiel/HURP/Data_share/Emissions/wrfchemi'\n        wrfoutpath   = '/Storage/WRF/michiel/HURP/Data_share/Domains'\n        \n    Times            = dict()\n    Times['00z']     = [['2014-01-01_00:00:00'],['2014-01-01_01:00:00'],['2014-01-01_02:00:00'],['2014-01-01_03:00:00'],\n                        ['2014-01-01_04:00:00'],['2014-01-01_05:00:00'],['2014-01-01_06:00:00'],['2014-01-01_07:00:00'],\n                        ['2014-01-01_08:00:00'],['2014-01-01_09:00:00'],['2014-01-01_10:00:00'],['2014-01-01_11:00:00']]\n                        \n    Times['12z']     = [['2014-01-01_12:00:00'],['2014-01-01_13:00:00'],['2014-01-01_14:00:00'],['2014-01-01_15:00:00'],\n                        ['2014-01-01_16:00:00'],['2014-01-01_17:00:00'],['2014-01-01_18:00:00'],['2014-01-01_19:00:00'],\n                        ['2014-01-01_20:00:00'],['2014-01-01_21:00:00'],['2014-01-01_22:00:00'],['2014-01-01_23:00:00']]\n    nei2wrf(NEIpath, wrfchemipath, wrfoutpath, Times)\n", "meta": {"hexsha": "ec07189d63905effd8fb0ae01d64946592f5be3a", "size": 27804, "ext": "py", "lang": "Python", "max_stars_repo_path": "hurp/NEI2WRF.py", "max_stars_repo_name": "ERA-URBAN/hurp", "max_stars_repo_head_hexsha": "8e5c3051dc779fca7f77105e32d2e4453ec06e13", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hurp/NEI2WRF.py", "max_issues_repo_name": "ERA-URBAN/hurp", "max_issues_repo_head_hexsha": "8e5c3051dc779fca7f77105e32d2e4453ec06e13", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hurp/NEI2WRF.py", "max_forks_repo_name": "ERA-URBAN/hurp", "max_forks_repo_head_hexsha": "8e5c3051dc779fca7f77105e32d2e4453ec06e13", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.6762589928, "max_line_length": 284, "alphanum_fraction": 0.5248165732, "include": true, "reason": "import numpy,from scipy", "num_tokens": 9648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.3040416686603661, "lm_q1q2_score": 0.18248226591133235}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport numpy as np\nfrom astropy.coordinates import SkyOffsetFrame\nfrom gammapy.data import FixedPointingInfo\nfrom gammapy.irf import EDispMap, PSFMap\nfrom gammapy.maps import Map, WcsNDMap\nfrom gammapy.modeling.models import PowerLawSpectralModel\nfrom gammapy.utils.coordinates import sky_to_fov\n\n__all__ = [\n    \"make_map_background_irf\",\n    \"make_edisp_map\",\n    \"make_edisp_kernel_map\",\n    \"make_psf_map\",\n    \"make_map_exposure_true_energy\",\n]\n\n\ndef make_map_exposure_true_energy(pointing, livetime, aeff, geom):\n    \"\"\"Compute exposure map.\n\n    This map has a true energy axis, the exposure is not combined\n    with energy dispersion.\n\n    Parameters\n    ----------\n    pointing : `~astropy.coordinates.SkyCoord`\n        Pointing direction\n    livetime : `~astropy.units.Quantity`\n        Livetime\n    aeff : `~gammapy.irf.EffectiveAreaTable2D`\n        Effective area\n    geom : `~gammapy.maps.WcsGeom`\n        Map geometry (must have an energy axis)\n\n    Returns\n    -------\n    map : `~gammapy.maps.WcsNDMap`\n        Exposure map\n    \"\"\"\n    offset = geom.separation(pointing)\n    energy = geom.get_axis_by_name(\"energy_true\").center\n\n    exposure = aeff.data.evaluate(\n        offset=offset, energy_true=energy[:, np.newaxis, np.newaxis]\n    )\n    # TODO: Improve IRF evaluate to preserve energy axis if length 1\n    # For now, we handle that case via this hack:\n    if len(exposure.shape) < 3:\n        exposure = np.expand_dims(exposure.value, 0) * exposure.unit\n\n    exposure = (exposure * livetime).to(\"m2 s\")\n\n    return WcsNDMap(geom, exposure.value.reshape(geom.data_shape), unit=exposure.unit)\n\n\ndef _map_spectrum_weight(map, spectrum=None):\n    \"\"\"Weight a map with a spectrum.\n\n    This requires map to have an \"energy\" axis.\n    The weights are normalised so that they sum to 1.\n    The mean and unit of the output image is the same as of the input cube.\n\n    At the moment this is used to get a weighted exposure image.\n\n    Parameters\n    ----------\n    map : `~gammapy.maps.Map`\n        Input map with an \"energy\" axis.\n    spectrum : `~gammapy.modeling.models.SpectralModel`\n        Spectral model to compute the weights.\n        Default is power-law with spectral index of 2.\n\n    Returns\n    -------\n    map_weighted : `~gammapy.maps.Map`\n        Weighted image\n    \"\"\"\n    if spectrum is None:\n        spectrum = PowerLawSpectralModel(index=2.0)\n\n    # Compute weights vector\n    energy_edges = map.geom.get_axis_by_name(\"energy_true\").edges\n    weights = spectrum.integral(\n        emin=energy_edges[:-1], emax=energy_edges[1:], intervals=True\n    )\n    weights /= weights.sum()\n    shape = np.ones(len(map.geom.data_shape))\n    shape[0] = -1\n    return map * weights.reshape(shape.astype(int))\n\n\ndef make_map_background_irf(pointing, ontime, bkg, geom, oversampling=None):\n    \"\"\"Compute background map from background IRFs.\n\n    Parameters\n    ----------\n    pointing : `~gammapy.data.FixedPointingInfo` or `~astropy.coordinates.SkyCoord`\n        Observation pointing\n\n        - If a ``FixedPointingInfo`` is passed, FOV coordinates are properly computed.\n        - If a ``SkyCoord`` is passed, FOV frame rotation is not taken into account.\n    ontime : `~astropy.units.Quantity`\n        Observation ontime. i.e. not corrected for deadtime\n        see https://gamma-astro-data-formats.readthedocs.io/en/stable/irfs/full_enclosure/bkg/index.html#notes)\n    bkg : `~gammapy.irf.Background3D`\n        Background rate model\n    geom : `~gammapy.maps.WcsGeom`\n        Reference geometry\n    oversampling: int\n        Oversampling factor in energy, used for the background model evaluation.\n\n    Returns\n    -------\n    background : `~gammapy.maps.WcsNDMap`\n        Background predicted counts sky cube in reco energy\n    \"\"\"\n    # TODO:\n    #  This implementation can be improved in two ways:\n    #  1. Create equal time intervals between TSTART and TSTOP and sum up the\n    #  background IRF for each interval. This is instead of multiplying by\n    #  the total ontime. This then handles the rotation of the FoV.\n    #  2. Use the pointing table (does not currently exist in CTA files) to\n    #  obtain the RA DEC and time for each interval. This then considers that\n    #  the pointing might change slightly over the observation duration\n\n    # Get altaz coords for map\n    if oversampling is not None:\n        geom = geom.upsample(factor=oversampling, axis=\"energy\")\n\n    map_coord = geom.to_image().get_coord()\n    sky_coord = map_coord.skycoord\n\n    if isinstance(pointing, FixedPointingInfo):\n        altaz_coord = sky_coord.transform_to(pointing.altaz_frame)\n\n        # Compute FOV coordinates of map relative to pointing\n        fov_lon, fov_lat = sky_to_fov(\n            altaz_coord.az, altaz_coord.alt, pointing.altaz.az, pointing.altaz.alt\n        )\n    else:\n        # Create OffsetFrame\n        frame = SkyOffsetFrame(origin=pointing)\n        pseudo_fov_coord = sky_coord.transform_to(frame)\n        fov_lon = pseudo_fov_coord.lon\n        fov_lat = pseudo_fov_coord.lat\n\n    energies = geom.get_axis_by_name(\"energy\").edges\n\n    bkg_de = bkg.evaluate_integrate(\n        fov_lon=fov_lon,\n        fov_lat=fov_lat,\n        energy_reco=energies[:, np.newaxis, np.newaxis],\n    )\n\n    d_omega = geom.to_image().solid_angle()\n    data = (bkg_de * d_omega * ontime).to_value(\"\")\n    bkg_map = WcsNDMap(geom, data=data)\n\n    if oversampling is not None:\n        bkg_map = bkg_map.downsample(factor=oversampling, axis=\"energy\")\n\n    return bkg_map\n\n\ndef make_psf_map(psf, pointing, geom, exposure_map=None):\n    \"\"\"Make a psf map for a single observation\n\n    Expected axes : rad and true energy in this specific order\n    The name of the rad MapAxis is expected to be 'rad'\n\n    Parameters\n    ----------\n    psf : `~gammapy.irf.PSF3D`\n        the PSF IRF\n    pointing : `~astropy.coordinates.SkyCoord`\n        the pointing direction\n    geom : `~gammapy.maps.Geom`\n        the map geom to be used. It provides the target geometry.\n        rad and true energy axes should be given in this specific order.\n    exposure_map : `~gammapy.maps.Map`, optional\n        the associated exposure map.\n        default is None\n\n    Returns\n    -------\n    psfmap : `~gammapy.cube.PSFMap`\n        the resulting PSF map\n    \"\"\"\n    energy_axis = geom.get_axis_by_name(\"energy_true\")\n    energy = energy_axis.center\n\n    rad_axis = geom.get_axis_by_name(\"theta\")\n    rad = rad_axis.center\n\n    # Compute separations with pointing position\n    offset = geom.separation(pointing)\n\n    # Compute PSF values\n    # TODO: allow broadcasting in PSF3D.evaluate()\n    psf_values = psf._interpolate(\n        (\n            rad[:, np.newaxis, np.newaxis],\n            offset,\n            energy[:, np.newaxis, np.newaxis, np.newaxis],\n        )\n    )\n\n    # TODO: this probably does not ensure that probability is properly normalized in the PSFMap\n    # Create Map and fill relevant entries\n    data = psf_values.to_value(\"sr-1\")\n    psfmap = Map.from_geom(geom, data=data, unit=\"sr-1\")\n    return PSFMap(psfmap, exposure_map)\n\n\ndef make_edisp_map(edisp, pointing, geom, exposure_map=None):\n    \"\"\"Make a edisp map for a single observation\n\n    Expected axes : migra and true energy in this specific order\n    The name of the migra MapAxis is expected to be 'migra'\n\n    Parameters\n    ----------\n    edisp : `~gammapy.irf.EnergyDispersion2D`\n        the 2D Energy Dispersion IRF\n    pointing : `~astropy.coordinates.SkyCoord`\n        the pointing direction\n    geom : `~gammapy.maps.Geom`\n        the map geom to be used. It provides the target geometry.\n        migra and true energy axes should be given in this specific order.\n    exposure_map : `~gammapy.maps.Map`, optional\n        the associated exposure map.\n        default is None\n\n    Returns\n    -------\n    edispmap : `~gammapy.cube.EDispMap`\n        the resulting EDisp map\n    \"\"\"\n    energy_axis = geom.get_axis_by_name(\"energy_true\")\n    energy = energy_axis.center\n\n    migra_axis = geom.get_axis_by_name(\"migra\")\n    migra = migra_axis.center\n\n    # Compute separations with pointing position\n    offset = geom.separation(pointing)\n\n    # Compute EDisp values\n    edisp_values = edisp.data.evaluate(\n        offset=offset,\n        energy_true=energy[:, np.newaxis, np.newaxis, np.newaxis],\n        migra=migra[:, np.newaxis, np.newaxis],\n    )\n\n    # Create Map and fill relevant entries\n    data = edisp_values.to_value(\"\")\n    edispmap = Map.from_geom(geom, data=data, unit=\"\")\n    return EDispMap(edispmap, exposure_map)\n\n\ndef make_edisp_kernel_map(edisp, pointing, geom, exposure_map=None):\n    \"\"\"Make a edisp kernel map for a single observation\n\n    Expected axes : (reco) energy and true energy in this specific order\n    The name of the reco energy MapAxis is expected to be 'energy'.\n    The name of the true energy MapAxis is expected to be 'energy_true'.\n\n    Parameters\n    ----------\n    edisp : `~gammapy.irf.EnergyDispersion2D`\n        the 2D Energy Dispersion IRF\n    pointing : `~astropy.coordinates.SkyCoord`\n        the pointing direction\n    geom : `~gammapy.maps.Geom`\n        the map geom to be used. It provides the target geometry.\n        energy and true energy axes should be given in this specific order.\n    exposure_map : `~gammapy.maps.Map`, optional\n        the associated exposure map.\n        default is None\n\n    Returns\n    -------\n    edispmap : `~gammapy.cube.EDispKernelMap`\n        the resulting EDispKernel map\n    \"\"\"\n    # Use EnergyDispersion2D migra axis.\n    migra_axis = edisp.data.axis(\"migra\")\n\n    # Create temporary EDispMap Geom\n    new_geom = geom.to_image().to_cube(\n        [migra_axis, geom.get_axis_by_name(\"energy_true\")]\n    )\n\n    edisp_map = make_edisp_map(edisp, pointing, new_geom, exposure_map)\n\n    return edisp_map.to_edisp_kernel_map(geom.get_axis_by_name(\"energy\"))\n", "meta": {"hexsha": "2fdcc0a02e45dbd196848254f57d0ecef3c135de", "size": 9870, "ext": "py", "lang": "Python", "max_stars_repo_path": "gammapy/makers/utils.py", "max_stars_repo_name": "vikasj78/gammapy", "max_stars_repo_head_hexsha": "46deb872bbcbf36748df71e659dc3fa592f6dc27", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gammapy/makers/utils.py", "max_issues_repo_name": "vikasj78/gammapy", "max_issues_repo_head_hexsha": "46deb872bbcbf36748df71e659dc3fa592f6dc27", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gammapy/makers/utils.py", "max_forks_repo_name": "vikasj78/gammapy", "max_forks_repo_head_hexsha": "46deb872bbcbf36748df71e659dc3fa592f6dc27", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1208053691, "max_line_length": 111, "alphanum_fraction": 0.6772036474, "include": true, "reason": "import numpy,from astropy", "num_tokens": 2483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.1823169711481739}}
{"text": "import torch\nimport torch.nn.functional as F\nfrom torch.distributions.normal import Normal\nimport numpy as np\n\n\nclass PolicyNet(torch.nn.Module):\n    \"\"\"\n    Gaussian Policy\n    \"\"\"\n    def __init__(self, state_dim, hidden_dim, action_dim, action_bound):\n        super(PolicyNet, self).__init__()\n        self.fc1 = torch.nn.Linear(state_dim, hidden_dim)\n        self.fc_mu = torch.nn.Linear(hidden_dim, action_dim)\n        self.fc_std = torch.nn.Linear(hidden_dim, action_dim)\n        self.action_bound = action_bound\n\n    def forward(self, x):\n        x = F.relu(self.fc1(x))\n        mu = self.fc_mu(x)\n        std = F.softplus(self.fc_std(x))\n        dist = Normal(mu, std)\n        normal_sample = dist.rsample()  # rsample()是重参数化采样函数\n        log_prob = dist.log_prob(normal_sample)\n        action = torch.tanh(normal_sample)  # 计算tanh_normal分布的对数概率密度\n        log_prob = log_prob - torch.log(1 - torch.tanh(action).pow(2) + 1e-7)\n        action = action * self.action_bound\n        return action, log_prob\n\n\nclass QValueNet(torch.nn.Module):\n    def __init__(self, state_dim, hidden_dim, action_dim):\n        super(QValueNet, self).__init__()\n        self.fc1 = torch.nn.Linear(state_dim + action_dim, hidden_dim)\n        self.fc2 = torch.nn.Linear(hidden_dim, 1)\n\n    def forward(self, x, a):\n        cat = torch.cat([x, a], dim=1)  # 拼接状态和动作\n        x = F.relu(self.fc1(cat))\n        return self.fc2(x)\n\n\nclass SAC:\n    \"\"\"处理连续动作的SAC算法\"\"\"\n    def __init__(self, state_dim, hidden_dim, action_dim, action_bound,\n                 actor_lr, critic_lr, alpha_lr, target_entropy, tau, gamma, device):\n        self.actor = PolicyNet(state_dim, hidden_dim, action_dim,\n                               action_bound).to(device)  # 策略网络\n        # 第一个Q网络\n        self.critic_1 = QValueNet(state_dim, hidden_dim, action_dim).to(device)\n        # 第二个Q网络\n        self.critic_2 = QValueNet(state_dim, hidden_dim, action_dim).to(device)\n        self.target_critic_1 = QValueNet(state_dim, hidden_dim,\n                                         action_dim).to(device)  # 第一个目标Q网络\n        self.target_critic_2 = QValueNet(state_dim, hidden_dim,\n                                         action_dim).to(device)  # 第二个目标Q网络\n        # 令目标Q网络的初始参数和Q网络一样\n        self.target_critic_1.load_state_dict(self.critic_1.state_dict())\n        self.target_critic_2.load_state_dict(self.critic_2.state_dict())\n        self.actor_optimizer = torch.optim.Adam(self.actor.parameters(),\n                                                lr=actor_lr)\n        self.critic_1_optimizer = torch.optim.Adam(self.critic_1.parameters(),\n                                                   lr=critic_lr)\n        self.critic_2_optimizer = torch.optim.Adam(self.critic_2.parameters(),\n                                                   lr=critic_lr)\n        # 使用alpha的log值,可以使训练结果比较稳定\n        self.log_alpha = torch.tensor(np.log(0.01), dtype=torch.float)\n        self.log_alpha.requires_grad = True  # 可以对alpha求梯度\n        self.log_alpha_optimizer = torch.optim.Adam([self.log_alpha],\n                                                    lr=alpha_lr)\n        self.target_entropy = target_entropy  # 目标熵的大小\n        self.gamma = gamma\n        self.tau = tau\n        self.device = device\n\n    def take_action(self, state):\n        state = torch.tensor([state], dtype=torch.float).to(self.device)\n        action = self.actor(state)[0]\n        return [action.item()]\n\n    def calc_target(self, rewards, next_states, dones):  # 计算目标Q值\n        next_actions, log_prob = self.actor(next_states)\n        entropy = -log_prob\n        q1_value = self.target_critic_1(next_states, next_actions)\n        q2_value = self.target_critic_2(next_states, next_actions)\n        next_value = torch.min(q1_value,\n                               q2_value) + self.log_alpha.exp() * entropy\n        td_target = rewards + self.gamma * next_value * (1 - dones)\n        return td_target\n\n    def soft_update(self, net, target_net):\n        for param_target, param in zip(target_net.parameters(),\n                                       net.parameters()):\n            param_target.data.copy_(param_target.data * (1.0 - self.tau) +\n                                    param.data * self.tau)\n\n    def update(self, transition_dict):\n        states = torch.tensor(transition_dict['states'],\n                              dtype=torch.float).to(self.device)\n        actions = torch.tensor(transition_dict['actions'],\n                               dtype=torch.float).view(-1, 1).to(self.device)\n        rewards = torch.tensor(transition_dict['rewards'],\n                               dtype=torch.float).view(-1, 1).to(self.device)\n        next_states = torch.tensor(transition_dict['next_states'],\n                                   dtype=torch.float).to(self.device)\n        dones = torch.tensor(transition_dict['dones'],\n                             dtype=torch.float).view(-1, 1).to(self.device)\n        rewards = (rewards + 8.0) / 8.0  # 对倒立摆环境的奖励进行重塑\n\n        # 更新两个Q网络\n        td_target = self.calc_target(rewards, next_states, dones)\n        critic_1_loss = torch.mean(\n            F.mse_loss(self.critic_1(states, actions), td_target.detach()))\n        critic_2_loss = torch.mean(\n            F.mse_loss(self.critic_2(states, actions), td_target.detach()))\n        self.critic_1_optimizer.zero_grad()\n        critic_1_loss.backward()\n        self.critic_1_optimizer.step()\n        self.critic_2_optimizer.zero_grad()\n        critic_2_loss.backward()\n        self.critic_2_optimizer.step()\n\n        # 更新策略网络\n        new_actions, log_prob = self.actor(states)\n        entropy = -log_prob\n        q1_value = self.critic_1(states, new_actions)\n        q2_value = self.critic_2(states, new_actions)\n        actor_loss = torch.mean(-self.log_alpha.exp() * entropy -\n                                torch.min(q1_value, q2_value))\n        self.actor_optimizer.zero_grad()\n        actor_loss.backward()\n        self.actor_optimizer.step()\n\n        # 更新alpha值\n        alpha_loss = torch.mean(\n            (entropy - self.target_entropy).detach() * self.log_alpha.exp())\n        self.log_alpha_optimizer.zero_grad()\n        alpha_loss.backward()\n        self.log_alpha_optimizer.step()\n\n        self.soft_update(self.critic_1, self.target_critic_1)\n        self.soft_update(self.critic_2, self.target_critic_2)\n", "meta": {"hexsha": "33e0992f972818dfdf9c483c1886443360b01918", "size": 6320, "ext": "py", "lang": "Python", "max_stars_repo_path": "model_free/SAC/sac.py", "max_stars_repo_name": "sherlockHSY/Reinforcement_learning_with_pytorch", "max_stars_repo_head_hexsha": "90c4f302b588bbf8be7962aaaa7f61c0234fb8d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-11-15T05:32:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T08:38:07.000Z", "max_issues_repo_path": "model_free/SAC/sac.py", "max_issues_repo_name": "sherlockHSY/Reinforcement_learning_with_pytorch", "max_issues_repo_head_hexsha": "90c4f302b588bbf8be7962aaaa7f61c0234fb8d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model_free/SAC/sac.py", "max_forks_repo_name": "sherlockHSY/Reinforcement_learning_with_pytorch", "max_forks_repo_head_hexsha": "90c4f302b588bbf8be7962aaaa7f61c0234fb8d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.1958041958, "max_line_length": 84, "alphanum_fraction": 0.6028481013, "include": true, "reason": "import numpy", "num_tokens": 1535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635841117624, "lm_q2_score": 0.28457601635158564, "lm_q1q2_score": 0.18230959559730078}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function\n\n\"\"\"\nEmpirical XMM background model.\nWritten by Zhu Liu, adapted by Torben Simm and Johannes Buchner\n(C) 2013-2016\nFor example usage, see examples/sherpa/background/xmm/fit.py\n\"\"\"\n\nimport os\nimport logging\n\nimport numpy\n\nif \"MAKESPHINXDOC\" not in os.environ:\n    import sherpa.astro.ui as ui\n    from sherpa.stats import Cash, CStat\n    from sherpa.models.parameter import Parameter\n    from sherpa.models import ArithmeticModel, CompositeModel\n    from sherpa.astro.ui import *\n    from sherpa.astro.instrument import RSPModelNoPHA, RMFModelNoPHA\nelse:\n    CompositeModel, ArithmeticModel = object, object\n\nfrom bxa.sherpa.background.xmm import get_embedded_file\n\n# print(\n#     \"\"\"\n# Using XMM empirical background model originally by Richard Sturm.\n# Please reference Maggi P., et al., 2014, A&A, 561, AA76.\n# \"\"\"\n# )\n\n\n# def get_embedded_file(filename):\n#     \"\"\"\n#     Gets the path of a file in the same folder as this script\n#     \"\"\"\n#     return os.path.join(os.path.dirname(__file__), filename)\n\ndef get_unitrmf(rmf):\n    \"\"\"\n    Returns a unit response matrix with the same properties\n    (channels, energies, etc) as the original rmf\n    \"\"\"\n    urmf = unpack_rmf(rmf.name)\n    urmf.matrix = numpy.array([1.0] * urmf.detchans)\n    urmf.f_chan = numpy.array(range(urmf.detchans), dtype=numpy.uint32)\n    urmf.n_chan = numpy.array([1] * urmf.detchans, dtype=numpy.uint32)\n    urmf.offset = 0\n    urmf._rsp = numpy.array([1.0] * urmf.detchans)\n    urmf._fch = numpy.array(range(urmf.detchans), dtype=numpy.uint32)\n    urmf._nch = numpy.array([1] * urmf.detchans, dtype=numpy.uint32)\n\n    return urmf\n\n\ndef get_pn_bkg_model(i, galabs, fit=False, fix_response=False):\n    # =================================================================\n    # Parameters:\n    # i = sherpa ID of data set\n    # galabs = name of model for galactic absorption\n    # pnbrsp = response model of bkg data set\n    # fit: True = fit bkg spectrum; False = just set_bkg_full_model\n    # returns unit response for bkg model\n    # =================================================================\n    # get instrument response model for bkg spectrum\n    if fix_response:\n        if get_rmf(i).energ_lo[0] == 0:\n            get_rmf(i).energ_lo[0] = 0.001\n\n        if get_arf(i).energ_lo[0] == 0:\n            get_arf(i).energ_lo[0] = 0.001\n\n    pnbrsp = get_response(i, bkg_id=1)\n    pnscale = get_bkg_scale(i)  # get background scaling factor\n\n    # create unit response\n    dia_pn_rmf=get_embedded_file('pn_dia.rmf')\n    dia_pn_arf=get_embedded_file('pn_dia.arf')\n    copy_data(i,1000+2)\n    load_bkg_rmf(1000+2, dia_pn_rmf) #load diagonal bkg matrices\n    load_bkg_arf(1000+2, dia_pn_arf)\n    pnbunitrsp = get_response(1000+2, bkg_id=1)\n    delete_data(1000+2)\n\n    # gaussian line center energy, line width, and initial normalization; for *PN background*\n    pncenters = [\n        1.49165,\n        1.49165,\n        4.53177,\n        5.42516,\n        6.38155,\n        7.48675,\n        8.04087,\n        8.04087,\n        8.60924,\n        8.89395,\n        9.56160,\n    ]\n    pnlinewidth = [\n        5.73813e-02,\n        3.63469e-02,\n        6.10487e-02,\n        7.08380e-02,\n        9.59053e-02,\n        6.52422e-02,\n        9.48594e-02,\n        6.26174e-05,\n        0.120893,\n        0.114254,\n        0.108717,\n    ]\n    pnlinenorm = [\n        7.81356e-03,\n        3.96601e-03,\n        7.30727e-04,\n        4.96413e-04,\n        5.31295e-9,\n        6.84796e-04,\n        3.01564e-02,\n        1.41847e-04,\n        8.87887e-03,\n        5.75592e-03,\n        1.71367e-03,\n    ]\n\n    # model component prefix\n    bkg_prefix = \"bkg{}_pn\".format(i)\n\n    (\n        pnbkgcons,\n        pnbkgspline1,\n        pnbkgexpdec,\n        pnbkgsmedge1,\n        pnbkgsmedge2,\n        pnbkgspline2,\n        pnbkginspl,\n        pnbkgline1,\n        pnbkgline2,\n        pnbkgline3,\n        pnbkgline4,\n        pnbkgline5,\n        pnbkgline6,\n        pnbkgline7,\n        pnbkgline8,\n        pnbkgline9,\n        pnbkgline10,\n        pnbkgline11,\n        pnbkgpl,\n        pnbkgapec,\n        pnbkglcapec,\n    ) = (\n        xsconstant(bkg_prefix + \"cons\"),\n        xsspline(bkg_prefix + \"spline1\"),\n        xsexpdec(bkg_prefix + \"expdec\"),\n        xssmedge(bkg_prefix + \"smedge1\"),\n        xssmedge(bkg_prefix + \"smedge2\"),\n        xsspline(bkg_prefix + \"spline2\"),\n        xspowerlaw(bkg_prefix + \"bkpl\"),\n        xsgaussian(bkg_prefix + \"gau1\"),\n        xsgaussian(bkg_prefix + \"gau2\"),\n        xsgaussian(bkg_prefix + \"gau3\"),\n        xsgaussian(bkg_prefix + \"gau4\"),\n        xsgaussian(bkg_prefix + \"gau5\"),\n        xsgaussian(bkg_prefix + \"gau6\"),\n        xsgaussian(bkg_prefix + \"gau7\"),\n        xsgaussian(bkg_prefix + \"gau8\"),\n        xsgaussian(bkg_prefix + \"gau9\"),\n        xsgaussian(bkg_prefix + \"gau10\"),\n        xsgaussian(bkg_prefix + \"gau11\"),\n        xspowerlaw(bkg_prefix + \"expl\"),\n        xsapec(bkg_prefix + \"apec\"),\n        xsapec(bkg_prefix + \"lcapec\"),\n    )\n\n    pnlines = [\n        pnbkgline1,\n        pnbkgline2,\n        pnbkgline3,\n        pnbkgline4,\n        pnbkgline5,\n        pnbkgline6,\n        pnbkgline7,\n        pnbkgline8,\n        pnbkgline9,\n        pnbkgline10,\n        pnbkgline11,\n    ]\n    pnfixwid = [\n        pnbkgline2,\n        pnbkgline3,\n        pnbkgline4,\n        pnbkgline5,\n        pnbkgline6,\n        pnbkgline8,\n        pnbkgline11,\n    ]\n    pnfree = [pnbkgline1, pnbkgline7, pnbkgline9, pnbkgline10]\n\n    # define PN background model\n    pn_bkg = pnbunitrsp(\n        pnbkgcons\n        * (\n            pnbkgspline1 * pnbkgexpdec\n            + pnbkgsmedge1\n            * pnbkgsmedge2\n            * (\n                pnbkgspline2 * pnbkginspl\n                + pnbkgline1\n                + pnbkgline2\n                + pnbkgline3\n                + pnbkgline4\n                + pnbkgline5\n                + pnbkgline6\n                + pnbkgline7\n                + pnbkgline8\n                + pnbkgline9\n                + pnbkgline10\n                + pnbkgline11\n            )\n        )\n    ) + pnbrsp(galabs * (pnbkgpl + pnbkgapec) + pnbkglcapec)\n\n    for l, c in zip(pnlines, pncenters):\n        l.LineE = c\n        l.LineE.min = c - 0.05\n        l.LineE.max = c + 0.05\n\n    pnbkgline2.LineE = pnbkgline1.LineE\n    pnbkgline8.LineE = pnbkgline7.LineE\n\n    for l, s in zip(pnlines, pnlinewidth):\n        l.Sigma = s\n\n    for l in pnfree:\n        l.Sigma.min = 1e-5\n        l.Sigma.max = 0.2\n\n    for l in pnfixwid:\n        l.Sigma.freeze()\n\n    for l, n in zip(pnlines, pnlinenorm):\n        l.norm = n\n        l.norm.min = 1e-10\n        l.norm.max = 1e10\n\n    # Scaling constant\n    pnbkgcons.factor = 1.0\n    pnbkgcons.factor.freeze()\n\n    # thermal radiation\n    pnbkgapec.kT = 0.286928\n    pnbkgapec.kT.min = 0.008\n    pnbkgapec.kT.max = 64\n    pnbkgapec.Abundanc = 1.0\n    pnbkgapec.Abundanc.freeze()\n    pnbkgapec.Redshift = 0.0\n    pnbkgapec.Redshift.freeze()\n    pnbkgapec.norm = 5.58410e-05\n    pnbkgapec.norm.min = 1e-10\n    pnbkgapec.norm.max = 1e10\n\n    # local thermal radiation\n    pnbkglcapec.kT = 0.1\n    pnbkglcapec.kT.freeze()\n    pnbkglcapec.Abundanc = 1.0\n    pnbkglcapec.Abundanc.freeze()\n    pnbkglcapec.Redshift = 0.0\n    pnbkglcapec.Redshift.freeze()\n    pnbkglcapec.norm = 3.89164e-05\n    pnbkglcapec.norm.min = 1e-10\n    pnbkglcapec.norm.max = 1e10\n\n    # exponential decay\n    pnbkgexpdec.factor = 44.3418\n    pnbkgexpdec.factor.min = 0\n    pnbkgexpdec.factor.max = 100\n    pnbkgexpdec.norm = 6830.89\n    pnbkgexpdec.norm.freeze()\n\n    # Smear function\n    pnbkgsmedge1.edgeE = 0.538408\n    pnbkgsmedge1.edgeE.freeze()\n    pnbkgsmedge1.MaxTau = 1.40238\n    pnbkgsmedge1.MaxTau.min = 0\n    pnbkgsmedge1.MaxTau.max = 10\n    pnbkgsmedge1.index = -2.67000\n    pnbkgsmedge1.index.freeze()\n    pnbkgsmedge1.width = 0.313365\n    pnbkgsmedge1.width.min = 0.01\n    pnbkgsmedge1.width.max = 100\n\n    pnbkgsmedge2.edgeE = 1.38826\n    pnbkgsmedge2.edgeE.freeze()\n    pnbkgsmedge2.MaxTau.min = 0\n    pnbkgsmedge2.MaxTau.max = 10\n    pnbkgsmedge2.MaxTau = 9.37167\n    pnbkgsmedge2.index = -2.67000\n    pnbkgsmedge2.index.freeze()\n    pnbkgsmedge2.width = 5.7642\n    pnbkgsmedge2.width.min = 0.01\n    pnbkgsmedge2.width.max = 100\n\n    # Spline funtion\n    pnbkgspline1.Estart = 0.200000\n    pnbkgspline1.Estart.freeze()\n    pnbkgspline1.Ystart = -1.31506\n    pnbkgspline1.Ystart.min = -1e6\n    pnbkgspline1.Ystart.max = 1e6\n    pnbkgspline1.Yend = 1064.16\n    pnbkgspline1.Yend.min = -1e6\n    pnbkgspline1.Yend.max = 1e6\n    pnbkgspline1.YPstart = -106.183\n    pnbkgspline1.YPstart.min = -1e6\n    pnbkgspline1.YPstart.max = 1e6\n    pnbkgspline1.YPend = -366.092\n    pnbkgspline1.YPend.min = -1e6\n    pnbkgspline1.YPend.max = 1e6\n    pnbkgspline1.Eend = 1.74715\n    pnbkgspline1.Eend.min = 0\n    pnbkgspline1.Eend.max = 100\n\n    pnbkgspline2.Estart = 3.29056\n    pnbkgspline2.Ystart = 1.00643\n    pnbkgspline2.Ystart.min = -1e6\n    pnbkgspline2.Ystart.max = 1e6\n    pnbkgspline2.Yend = 0.887026\n    pnbkgspline2.Yend.min = -1e6\n    pnbkgspline2.Yend.max = 1e6\n    pnbkgspline2.YPstart = -0.278401\n    pnbkgspline2.YPstart.min = -1e6\n    pnbkgspline2.YPstart.max = 1e6\n    pnbkgspline2.YPend = 4.84809e-03\n    pnbkgspline2.YPend.min = -1e6\n    pnbkgspline2.YPend.max = 1e6\n    pnbkgspline2.Eend = 7.32701\n    pnbkgspline2.Eend.min = 0\n    pnbkgspline2.Eend.max = 100\n\n    # Background power law\n    pnbkginspl.PhoIndex = 0.279\n    pnbkginspl.PhoIndex.min = -2\n    pnbkginspl.PhoIndex.max = 9\n    pnbkginspl.norm = 8.23614e-03\n    pnbkginspl.norm.min = 1e-10\n    pnbkginspl.norm.max = 1e6\n\n    # Extragalactic background\n    pnbkgpl.PhoIndex = 1.46\n    pnbkgpl.PhoIndex.freeze()\n    pnbkgpl.norm = 1.25288e-05\n    pnbkgpl.norm.min = 1e-10\n    pnbkgpl.norm.max = 1e3\n\n    if fit:\n        set_bkg_full_model(\n            i,\n            pnbunitrsp(\n                pnbkgcons\n                * (\n                    pnbkgspline1 * pnbkgexpdec\n                    + pnbkgsmedge1 * pnbkgsmedge2 * (pnbkgspline2 * pnbkginspl)\n                )\n            ),\n        )\n        logging.info(\"Fitting (1/8)...\")\n        fit_bkg(i)\n        set_bkg_full_model(\n            i,\n            pnbunitrsp(\n                pnbkgcons\n                * (\n                    pnbkgspline1 * pnbkgexpdec\n                    + pnbkgsmedge1\n                    * pnbkgsmedge2\n                    * (pnbkgspline2 * pnbkginspl + pnbkgline2)\n                )\n            ),\n        )\n        logging.info(\"Fitting (2/8)...\")\n        fit_bkg(i)\n        set_bkg_full_model(\n            i,\n            pnbunitrsp(\n                pnbkgcons\n                * (\n                    pnbkgspline1 * pnbkgexpdec\n                    + pnbkgsmedge1\n                    * pnbkgsmedge2\n                    * (pnbkgspline2 * pnbkginspl + pnbkgline1 + pnbkgline2)\n                )\n            ),\n        )\n        logging.info(\"Fitting (3/8)...\")\n        fit_bkg(i)\n        set_bkg_full_model(\n            i,\n            pnbunitrsp(\n                pnbkgcons\n                * (\n                    pnbkgspline1 * pnbkgexpdec\n                    + pnbkgsmedge1\n                    * pnbkgsmedge2\n                    * (\n                        pnbkgspline2 * pnbkginspl\n                        + pnbkgline1\n                        + pnbkgline2\n                        + pnbkgline7\n                        + pnbkgline8\n                    )\n                )\n            ),\n        )\n        logging.info(\"Fitting (4/8)...\")\n        fit_bkg(i)\n        set_bkg_full_model(\n            i,\n            pnbunitrsp(\n                pnbkgcons\n                * (\n                    pnbkgspline1 * pnbkgexpdec\n                    + pnbkgsmedge1\n                    * pnbkgsmedge2\n                    * (\n                        pnbkgspline2 * pnbkginspl\n                        + pnbkgline1\n                        + pnbkgline2\n                        + pnbkgline7\n                        + pnbkgline8\n                        + pnbkgline9\n                        + pnbkgline10\n                    )\n                )\n            ),\n        )\n        logging.info(\"Fitting (5/8)...\")\n        fit_bkg(i)\n        set_bkg_full_model(\n            i,\n            pnbunitrsp(\n                pnbkgcons\n                * (\n                    pnbkgspline1 * pnbkgexpdec\n                    + pnbkgsmedge1\n                    * pnbkgsmedge2\n                    * (\n                        pnbkgspline2 * pnbkginspl\n                        + pnbkgline1\n                        + pnbkgline2\n                        + pnbkgline3\n                        + pnbkgline4\n                        + pnbkgline5\n                        + pnbkgline6\n                        + pnbkgline7\n                        + pnbkgline8\n                        + pnbkgline9\n                        + pnbkgline10\n                        + pnbkgline11\n                    )\n                )\n            ),\n        )\n        logging.info(\"Fitting (6/8)...\")\n        fit_bkg(i)\n        set_bkg_full_model(\n            i,\n            pnbunitrsp(\n                pnbkgcons\n                * (\n                    pnbkgspline1 * pnbkgexpdec\n                    + pnbkgsmedge1\n                    * pnbkgsmedge2\n                    * (\n                        pnbkgspline2 * pnbkginspl\n                        + pnbkgline1\n                        + pnbkgline2\n                        + pnbkgline3\n                        + pnbkgline4\n                        + pnbkgline5\n                        + pnbkgline6\n                        + pnbkgline7\n                        + pnbkgline8\n                        + pnbkgline9\n                        + pnbkgline10\n                        + pnbkgline11\n                    )\n                )\n            )\n            + pnbrsp(galabs * (pnbkgapec)),\n        )\n        logging.info(\"Fitting (7/8)...\")\n        fit_bkg(i)\n        set_bkg_full_model(\n            i,\n            pnbunitrsp(\n                pnbkgcons\n                * (\n                    pnbkgspline1 * pnbkgexpdec\n                    + pnbkgsmedge1\n                    * pnbkgsmedge2\n                    * (\n                        pnbkgspline2 * pnbkginspl\n                        + pnbkgline1\n                        + pnbkgline2\n                        + pnbkgline3\n                        + pnbkgline4\n                        + pnbkgline5\n                        + pnbkgline6\n                        + pnbkgline7\n                        + pnbkgline8\n                        + pnbkgline9\n                        + pnbkgline10\n                        + pnbkgline11\n                    )\n                )\n            )\n            + pnbrsp(galabs * (pnbkgapec + pnbkgpl)),\n        )\n        logging.info(\"Fitting (8/8)...\")\n        fit_bkg(i)\n        set_bkg_full_model(\n            i,\n            pnbunitrsp(\n                pnbkgcons\n                * (\n                    pnbkgspline1 * pnbkgexpdec\n                    + pnbkgsmedge1\n                    * pnbkgsmedge2\n                    * (\n                        pnbkgspline2 * pnbkginspl\n                        + pnbkgline1\n                        + pnbkgline2\n                        + pnbkgline3\n                        + pnbkgline4\n                        + pnbkgline5\n                        + pnbkgline6\n                        + pnbkgline7\n                        + pnbkgline8\n                        + pnbkgline9\n                        + pnbkgline10\n                        + pnbkgline11\n                    )\n                )\n            )\n            + pnbrsp(galabs * (pnbkgapec + pnbkgpl) + pnbkglcapec),\n        )\n        fit_bkg(i)\n\n        freeze(\n            pnbkgcons,\n            pnbkgspline1,\n            pnbkgexpdec,\n            pnbkgsmedge1,\n            pnbkgsmedge2,\n            pnbkgspline2,\n            pnbkginspl,\n            pnbkgline1,\n            pnbkgline2,\n            pnbkgline3,\n            pnbkgline4,\n            pnbkgline5,\n            pnbkgline6,\n            pnbkgline7,\n            pnbkgline8,\n            pnbkgline9,\n            pnbkgline10,\n            pnbkgline11,\n            galabs,\n            pnbkgapec,\n            pnbkgpl,\n            pnbkglcapec,\n        )\n        logging.info(\"PN background model set up and fitted\")\n        logging.info(\"Please double-check that it is a good fit\")\n    else:\n        set_bkg_full_model(\n            i,\n            pnbunitrsp(\n                pnbkgcons\n                * (\n                    pnbkgspline1 * pnbkgexpdec\n                    + pnbkgsmedge1\n                    * pnbkgsmedge2\n                    * (\n                        pnbkgspline2 * pnbkginspl\n                        + pnbkgline1\n                        + pnbkgline2\n                        + pnbkgline3\n                        + pnbkgline4\n                        + pnbkgline5\n                        + pnbkgline6\n                        + pnbkgline7\n                        + pnbkgline8\n                        + pnbkgline9\n                        + pnbkgline10\n                        + pnbkgline11\n                    )\n                )\n            )\n            + pnbrsp(galabs * (pnbkgapec + pnbkgpl) + pnbkglcapec),\n        )\n        logging.info(\"PN background model set up\")\n\n    return pnscale * (\n        pnbunitrsp(\n            pnbkgcons\n            * (\n                pnbkgspline1 * pnbkgexpdec\n                + pnbkgsmedge1\n                * pnbkgsmedge2\n                * (\n                    pnbkgspline2 * pnbkginspl\n                    + pnbkgline1\n                    + pnbkgline2\n                    + pnbkgline3\n                    + pnbkgline4\n                    + pnbkgline5\n                    + pnbkgline6\n                    + pnbkgline7\n                    + pnbkgline8\n                    + pnbkgline9\n                    + pnbkgline10\n                    + pnbkgline11\n                )\n            )\n        )\n        + pnbrsp(galabs * (pnbkgapec + pnbkgpl) + pnbkglcapec)\n    )\n\n\ndef get_mos_bkg_model(i, galabs, fit=False, fix_response=False):\n    # =================================================================\n    # Parameters:\n    # i = sherpa ID of data set\n    # galabs = name of model for galactic absorption\n    # fit: True = fit bkg spectrum; False = just set_bkg_full_model\n    # returns unit response for bkg model\n    # =================================================================\n    # get instrument response model for bkg spectrum\n    if fix_response:\n        if get_rmf(i).energ_lo[0] == 0:\n            get_rmf(i).energ_lo[0] = 0.001\n        if get_arf(i).energ_lo[0] == 0:\n            get_arf(i).energ_lo[0] = 0.001\n\n    mosbrsp = get_response(i, bkg_id=1)\n    mosscale = get_bkg_scale(i)  # get background scaling factor\n\n    # create unit response\n    dia_mos_rmf=get_embedded_file('mos_dia.rmf')\n    dia_mos_arf=get_embedded_file('mos_dia.arf')\n    copy_data(i,1000+2)\n    load_bkg_rmf(1000+2, dia_mos_rmf) #load diagonal bkg matrices\n    load_bkg_arf(1000+2, dia_mos_arf)\n    mosbunitrsp = get_response(1000+2, bkg_id=1)\n    delete_data(1000+2)\n\n\n    # gaussian line center energy, line width, and initial normalization; for *MOS background*\n    moscenters = [1.48600, 1.48700, 1.74000, 5.41000, 5.89500, 6.42000, 9.71000]\n    moslinewidth = [\n        3.84602e-02,\n        0.165816,\n        3.54985e-02,\n        9.77018e-02,\n        7.45076e-02,\n        7.42365e-02,\n        9.04855e-02,\n    ]\n    moslinenorm = [\n        9.93119e-03,\n        1.67028e-03,\n        1.75461e-03,\n        2.86358e-04,\n        2.07525e-04,\n        3.07555e-04,\n        4.58115e-04,\n    ]\n\n    # model component prefix\n    bkg_prefix = \"bkg{}_mos\".format(i)\n\n    (\n        mosbkgcons,\n        mosbkgsmedge,\n        mosbkgspline,\n        mosbkgbknpl,\n        mosbkgline1,\n        mosbkgline2,\n        mosbkgline3,\n        mosbkgline4,\n        mosbkgline5,\n        mosbkgline6,\n        mosbkgline7,\n        mosbkgpl,\n        mosbkgapec,\n        mosbkglcapec,\n    ) = (\n        xsconstant(bkg_prefix + \"cons\"),\n        xssmedge(bkg_prefix + \"smedge\"),\n        xsspline(bkg_prefix + \"spline\"),\n        xsbknpower(bkg_prefix + \"bknpl\"),\n        xsgaussian(bkg_prefix + \"gau1\"),\n        xsgaussian(bkg_prefix + \"gau2\"),\n        xsgaussian(bkg_prefix + \"gau3\"),\n        xsgaussian(bkg_prefix + \"gau4\"),\n        xsgaussian(bkg_prefix + \"gau5\"),\n        xsgaussian(bkg_prefix + \"gau6\"),\n        xsgaussian(bkg_prefix + \"gau7\"),\n        xspowerlaw(bkg_prefix + \"expl\"),\n        xsapec(bkg_prefix + \"apec\"),\n        xsapec(bkg_prefix + \"lcapec\"),\n    )\n\n    moslines = [\n        mosbkgline1,\n        mosbkgline2,\n        mosbkgline3,\n        mosbkgline4,\n        mosbkgline5,\n        mosbkgline6,\n        mosbkgline7,\n    ]\n\n    # define MOS background model\n    mos_bkg = mosbunitrsp(\n        mosbkgcons * mosbkgsmedge * mosbkgspline * mosbkgbknpl\n        + mosbkgline1\n        + mosbkgline2\n        + mosbkgline3\n        + mosbkgline4\n        + mosbkgline5\n        + mosbkgline6\n        + mosbkgline7\n    ) + mosbrsp(galabs * (mosbkgpl + mosbkgapec) + mosbkglcapec)\n\n    for l, c in zip(moslines, moscenters):\n        l.LineE = c\n        l.LineE.min = c - 0.05\n        l.LineE.max = c + 0.05\n\n    for l, s in zip(moslines, moslinewidth):\n        l.Sigma = s\n        l.Sigma.min = 1e-4\n        l.Sigma.max = 0.2\n    mosbkgline1.Sigma.min = 1e-4\n    mosbkgline1.Sigma.max = 1e-1\n\n    for l, n in zip(moslines, moslinenorm):\n        l.norm = n\n        l.norm.min = 1e-10\n        l.norm.max = 1e10\n\n    # Constant factor\n    mosbkgcons.factor = 1.0\n    mosbkgcons.factor.freeze()\n\n    # Smear function\n    mosbkgsmedge.edgeE = 0.538408\n    mosbkgsmedge.edgeE.freeze()\n    mosbkgsmedge.MaxTau = 0.246633\n    mosbkgsmedge.MaxTau.min = 0.0\n    mosbkgsmedge.MaxTau.max = 10.0\n    mosbkgsmedge.index = -2.67\n    mosbkgsmedge.index.freeze()\n    mosbkgsmedge.width = 1e-02\n    mosbkgsmedge.width.min = 1e-02\n    mosbkgsmedge.width.max = 1e2\n\n    # Spline funtion\n    mosbkgspline.Estart = 3.08175\n    mosbkgspline.Ystart = 1.00984\n    mosbkgspline.Yend = 1.99144\n    mosbkgspline.YPstart = -2.90195e-02\n    mosbkgspline.YPend = 5.49102e-02\n    mosbkgspline.Estart.freeze()\n    mosbkgspline.Ystart.freeze()\n    mosbkgspline.Yend.freeze()\n    mosbkgspline.YPstart.freeze()\n    mosbkgspline.YPend.freeze()\n    mosbkgspline.Eend = 13.6492\n    mosbkgspline.Eend.min = 0\n    mosbkgspline.Eend.max = 100\n\n    # Broken power law\n    mosbkgbknpl.PhoIndx1 = 1.48636\n    mosbkgbknpl.PhoIndx1.min = -2\n    mosbkgbknpl.PhoIndx1.max = 9\n    mosbkgbknpl.BreakE = 0.415173\n    mosbkgbknpl.PhoIndx2 = 0.315615\n    mosbkgbknpl.BreakE.freeze()\n    mosbkgbknpl.PhoIndx2.freeze()\n    mosbkgbknpl.norm = 2.90071e-03\n    mosbkgbknpl.norm.min = 1e-10\n    mosbkgbknpl.norm.max = 1e10\n\n    # Extragalactic background\n    mosbkgpl.PhoIndex = 1.46\n    mosbkgpl.PhoIndex.freeze()\n    mosbkgpl.norm = 4.58115e-04\n    mosbkgpl.norm.min = 1e-10\n    mosbkgpl.norm.max = 1e10\n\n    # thermal radiation\n    mosbkgapec.kT = 0.286928\n    mosbkgapec.kT.min = 0.008\n    mosbkgapec.kT.max = 64\n    mosbkgapec.Abundanc = 1.0\n    mosbkgapec.Abundanc.freeze()\n    mosbkgapec.Redshift = 0.0\n    mosbkgapec.Redshift.freeze()\n    mosbkgapec.norm = 5.58410e-05\n    mosbkgapec.norm.min = 1e-10\n    mosbkgapec.norm.max = 1e10\n\n    # local thermal radiation\n    mosbkglcapec.kT = 0.1\n    mosbkglcapec.kT.freeze()\n    mosbkglcapec.Abundanc = 1.0\n    mosbkglcapec.Abundanc.freeze()\n    mosbkglcapec.Redshift = 0.0\n    mosbkglcapec.Redshift.freeze()\n    mosbkglcapec.norm = 3.89164e-05\n    mosbkglcapec.norm.min = 1e-10\n    mosbkglcapec.norm.max = 1e10\n\n    if fit:  # fit bkg\n        set_bkg_full_model(\n            i, mosbunitrsp(\n                mosbkgcons * mosbkgsmedge * mosbkgspline * mosbkgbknpl\n            )\n        )\n        logging.info(\"Fitting (1/8)...\")\n        fit_bkg(i)\n        set_bkg_full_model(\n            i,\n            mosbunitrsp(\n                mosbkgcons * mosbkgsmedge * mosbkgspline * mosbkgbknpl\n                + mosbkgline2\n            ),\n        )\n        logging.info(\"Fitting (2/8)...\")\n        fit_bkg(i)\n        set_bkg_full_model(\n            i,\n            mosbunitrsp(\n                mosbkgcons * mosbkgsmedge * mosbkgspline * mosbkgbknpl\n                + mosbkgline2\n                + mosbkgline3\n            ),\n        )\n        logging.info(\"Fitting (3/8)...\")\n        fit_bkg(i)\n        set_bkg_full_model(\n            i,\n            mosbunitrsp(\n                mosbkgcons * mosbkgsmedge * mosbkgspline * mosbkgbknpl\n                + mosbkgline1\n                + mosbkgline2\n                + mosbkgline3\n            ),\n        )\n        logging.info(\"Fitting (4/8)...\")\n        fit_bkg(i)\n        set_bkg_full_model(\n            i,\n            mosbunitrsp(\n                mosbkgcons * mosbkgsmedge * mosbkgspline * mosbkgbknpl\n                + mosbkgline1\n                + mosbkgline2\n                + mosbkgline3\n                + mosbkgline4\n                + mosbkgline5\n                + mosbkgline6\n                + mosbkgline7\n            ),\n        )\n        logging.info(\"Fitting (5/8)...\")\n        fit_bkg(i)\n        set_bkg_full_model(\n            i,\n            mosbunitrsp(\n                mosbkgcons * mosbkgsmedge * mosbkgspline * mosbkgbknpl\n                + mosbkgline1\n                + mosbkgline2\n                + mosbkgline3\n                + mosbkgline4\n                + mosbkgline5\n                + mosbkgline6\n                + mosbkgline7\n            )\n            + mosbrsp(galabs * (mosbkgapec)),\n        )\n        logging.info(\"Fitting (6/8)...\")\n        fit_bkg(i)\n        set_bkg_full_model(\n            i,\n            mosbunitrsp(\n                mosbkgcons * mosbkgsmedge * mosbkgspline * mosbkgbknpl\n                + mosbkgline1\n                + mosbkgline2\n                + mosbkgline3\n                + mosbkgline4\n                + mosbkgline5\n                + mosbkgline6\n                + mosbkgline7\n            )\n            + mosbrsp(galabs * (mosbkgapec + mosbkgpl)),\n        )\n        logging.info(\"Fitting (7/8)...\")\n        fit_bkg(i)\n        set_bkg_full_model(\n            i,\n            mosbunitrsp(\n                mosbkgcons * mosbkgsmedge * mosbkgspline * mosbkgbknpl\n                + mosbkgline1\n                + mosbkgline2\n                + mosbkgline3\n                + mosbkgline4\n                + mosbkgline5\n                + mosbkgline6\n                + mosbkgline7\n            )\n            + mosbrsp(galabs * (mosbkgapec + mosbkgpl) + mosbkglcapec),\n        )\n        logging.info(\"Fitting (8/8)...\")\n        fit_bkg(i)\n        freeze(\n            mosbkgcons,\n            mosbkgsmedge,\n            mosbkgspline,\n            mosbkgbknpl,\n            mosbkgline1,\n            mosbkgline2,\n            mosbkgline3,\n            mosbkgline4,\n            mosbkgline5,\n            mosbkgline6,\n            mosbkgline7,\n            mosbkgpl,\n            mosbkgapec,\n            mosbkglcapec,\n        )\n        logging.info(\"MOS background model set up and fitted\")\n        logging.info(\"Please double-check that it is a good fit\")\n    else:\n        set_bkg_full_model(\n            i,\n            mosbunitrsp(\n                mosbkgcons * mosbkgsmedge * mosbkgspline * mosbkgbknpl\n                + mosbkgline1\n                + mosbkgline2\n                + mosbkgline3\n                + mosbkgline4\n                + mosbkgline5\n                + mosbkgline6\n                + mosbkgline7\n            )\n            + mosbrsp(galabs * (mosbkgapec + mosbkgpl) + mosbkglcapec),\n        )\n        logging.info(\"MOS background model set up\")\n\n    return mosscale * (\n        mosbunitrsp(\n            mosbkgcons * mosbkgsmedge * mosbkgspline * mosbkgbknpl\n            + mosbkgline1\n            + mosbkgline2\n            + mosbkgline3\n            + mosbkgline4\n            + mosbkgline5\n            + mosbkgline6\n            + mosbkgline7\n        )\n        + mosbrsp(galabs * (mosbkgapec + mosbkgpl) + mosbkglcapec)\n    )\n\n\ndef get_mos_bkg_model_cached(i, galabs):\n    filename = get_bkg(i).name + \".bkgpars\"\n    if os.path.exists(filename):\n        bkgmodel = get_mos_bkg_model(i, galabs, fit=False)\n        for p, v in zip(bkgmodel.pars, numpy.loadtxt(filename)):\n            p.val = v\n    else:\n        bkgmodel = get_mos_bkg_model(i, galabs, fit=True)\n        numpy.savetxt(filename, [p.val for p in bkgmodel.pars])\n    for p in bkgmodel.pars:\n        p.freeze()\n\n    return bkgmodel\n\n\ndef get_pn_bkg_model_cached(i, galabs):\n    filename = get_bkg(i).name + \".bkgpars\"\n    if os.path.exists(filename):\n        bkgmodel = get_pn_bkg_model(i, galabs, fit=False)\n        for p, v in zip(bkgmodel.pars, numpy.loadtxt(filename)):\n            p.val = v\n    else:\n        bkgmodel = get_pn_bkg_model(i, galabs, fit=True)\n        numpy.savetxt(filename, [p.val for p in bkgmodel.pars])\n    for p in bkgmodel.pars:\n        p.freeze()\n\n    return bkgmodel", "meta": {"hexsha": "506a802900dc12fd968879a22118e48833c64a76", "size": 28865, "ext": "py", "lang": "Python", "max_stars_repo_path": "xmm_backgrounds.py", "max_stars_repo_name": "ruizca/bxaagnfitter", "max_stars_repo_head_hexsha": "b26ed61e8fa88b70901b59f7e742a1aed5228b13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "xmm_backgrounds.py", "max_issues_repo_name": "ruizca/bxaagnfitter", "max_issues_repo_head_hexsha": "b26ed61e8fa88b70901b59f7e742a1aed5228b13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xmm_backgrounds.py", "max_forks_repo_name": "ruizca/bxaagnfitter", "max_forks_repo_head_hexsha": "b26ed61e8fa88b70901b59f7e742a1aed5228b13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6359126984, "max_line_length": 94, "alphanum_fraction": 0.5054217911, "include": true, "reason": "import numpy", "num_tokens": 9086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.182277517305651}}
{"text": "#!/usr/bin/env python\n\n\"\"\"\nspecter.throughput\n==================\n\nA class for tracking throughput.\n\nHacks:\n\n- Doesn't support  spatial variation of input sources.\n- Doesn't support per-fiber throughput.\n- Do I really want to impose a clumsy ObjType ENUM?\n\nHow to handle fiber size and sky units?\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport sys\nimport os\nimport warnings\nimport numbers\nimport numpy as np\nfrom astropy.io import fits\nfrom specter import util\n\n#- ObjType enum\nclass ObjType:\n    STAR   = 'STAR'\n    STD    = 'STD'\n    GALAXY = 'GALAXY'   #- pretty meaningless for fiberloss, ok for others\n    ELG    = 'ELG'\n    LRG    = 'LRG'\n    QSO    = 'QSO'\n    SKY    = 'SKY'\n    CALIB  = 'CALIB'\n\ndef load_throughput(filename):\n    \"\"\"\n    Create Throughput object from FITS file with EXTNAME=THROUGHPUT HDU\n    \"\"\"\n    #- memmap=False so that fits will really close the file upon fx.close()\n    fx = fits.open(filename, memmap=False)\n    thru = fx['THROUGHPUT'].data\n    hdr =  fx['THROUGHPUT'].header\n\n    #- Check for FIBERINPUT HDU\n    if 'FIBERINPUT' in fx:\n        tmp = fx['FIBERINPUT'].data\n        assert(len(tmp) == len(thru))\n        fiberinput = dict()\n        for key in tmp.dtype.names:\n            fiberinput[key.upper()] = tmp[key]\n    else:\n        print(\"no FIBERINPUT extention found\")\n        fiberinput = thru['fiberinput']\n\n    if 'wavelength' in thru.dtype.names:\n        w = thru['wavelength']\n    elif 'loglam' in thru.dtype.names:\n        w = 10**thru['loglam']\n    else:\n        fx.close()\n        raise ValueError('throughput must include wavelength or loglam')\n\n    if 'GEOMAREA' in hdr:\n        area = hdr['GEOMAREA']\n    elif 'EFFAREA' in hdr:\n        area = hdr['EFFAREA']  #- misnomer, but for backwards compatibility\n    elif 'AREA' in hdr:\n        area = hdr['AREA']\n    else:\n        fx.close()\n        raise ValueError(\"throughput file missing GEOMAREA keyword\")\n\n    fx.close()\n\n    return Throughput(\n        wave = w,\n        throughput = thru['throughput'],\n        extinction = thru['extinction'],\n        fiberinput = fiberinput,\n        exptime    = hdr['EXPTIME'],\n        area       = area,\n        fiberdia   = hdr['FIBERDIA'],\n        )\n\nclass Throughput:\n    def __init__(self, wave, throughput, extinction,\n        exptime, area, fiberdia, fiberinput=None):\n        \"\"\"\n        Create Throughput object\n\n        Inputs\n        ------\n        wave : wavelength array [Angstroms]\n        throughput : array of system throughput for elements which apply to\n            all types of sources, e.g. mirrors, lenses, CCD efficiency\n        extinction : atmospheric extinction array [mags/airmass]\n\n        exptime:  float, default exposure time [sec]\n        area:     float, input geometric area [cm^2]\n        fiberdia: float, fiber diameter [arcsec]\n\n        Optional Inputs\n        ---------------\n        fiberinput : float, array, or dictionary of arrays keyed by objtype.\n            Geometric throughput due to finite sized fiber input.\n            Default to no loss = 1.0.\n\n        Notes\n        -----\n        fiberinput is a placeholder, since it really depends upon the\n        spatial extent of the object and the seeing.\n        \"\"\"\n        self._wave = np.copy(wave)\n        self._thru = np.copy(throughput)\n        self._extinction  = np.copy(extinction)\n\n        self.exptime = float(exptime)\n        self.area = float(area)\n        self.fiberdia = float(fiberdia)\n\n        #- Flux -> photons conversion constant\n        #-         h [erg s]      * c [m/s]      * [1e10 A/m] = [erg A]\n        self._hc = 6.62606957e-27 * 2.99792458e8 * 1e10\n\n        #- Create fiber input dict keyed by object type, including 'default'\n        if fiberinput is not None:\n            if isinstance(fiberinput, numbers.Real):\n                self._fiberinput = dict(default=np.ones(len(wave)) * fiberinput)\n            elif isinstance(fiberinput, np.ndarray):\n                self._fiberinput = dict(default=np.copy(fiberinput))\n            elif isinstance(fiberinput, dict):\n                self._fiberinput = fiberinput\n                if 'default' not in fiberinput:\n                    self._fiberinput['default'] = np.ones(len(wave))\n            else:\n                raise ValueError('Unrecognized type for fiberinput: {}'.format(type(fiberinput)))\n        else:\n            self._fiberinput = dict(default=np.ones(len(wave)))\n\n        #- special cases: QSO and STD are STAR for fiber input losses\n        if 'STAR' in self._fiberinput and 'STD' not in self._fiberinput:\n            self._fiberinput['STD'] = self._fiberinput['STAR']\n        if 'STAR' in self._fiberinput and 'QSO' not in self._fiberinput:\n            self._fiberinput['QSO'] = self._fiberinput['STAR']\n\n\n    @property\n    def fiberarea(self):\n        \"\"\"Average fiber area [arcsec^2] used for fiber input calculations\"\"\"\n        return np.pi * self.fiberdia**2 / 4.0\n\n    def extinction(self, wavelength):\n        \"\"\"\n        Return atmospheric extinction [magnitudes/airmass]\n        evaluated at wavelength (float or array)\n        \"\"\"\n        return np.interp(wavelength, self._wave, self._extinction)\n\n    def atmospheric_throughput(self, wavelength, airmass=1.0):\n        \"\"\"\n        Return atmospheric throughput [0 - 1] at given airmass,\n        evaluated at wavelength (float or array)\n        \"\"\"\n        ext = self.extinction(wavelength)\n        return 10**(-0.4 * airmass * ext)\n\n    def fiberinput_throughput(self, wavelength=None, objtype=ObjType.STAR):\n        \"\"\"\n        Return fiber input geometric throughput [0 - 1]\n        evaluated at wavelength (float or array).\n        If wavelength is None, do not interpolate.\n        \"\"\"\n        if objtype in self._fiberinput:\n            t = self._fiberinput[objtype]\n        else:\n            msg = 'Unknown objtype {}; using default fiber input loss'.format(objtype)\n            msg += '\\nKnown objtypes are '+str(list(self._fiberinput.keys()))\n            warnings.warn(msg)\n            t = self._fiberinput['default']\n\n        if wavelength is None:\n            return t\n        else:\n            return np.interp(wavelength, self._wave, t)\n\n    def hardware_throughput(self, wavelength):\n        \"\"\"\n        Return hardware throughput (optics, fiber run, CCD, but\n        not including atmosphere or geometric fiber input losses)\n        evaluated at wavelength (float or array)\n        \"\"\"\n        return np.interp(wavelength, self._wave, self._thru, left=0.0, right=0.0)\n\n    def _throughput(self, objtype=ObjType.STAR, airmass=1.0):\n        \"\"\"\n        Returns system throughput for this object type and airmass\n        at the native wavelengths of this Throughput object (self._wave)\n\n        objtype may be any of the ObjType enumerated types\n            CALIB : atmospheric extinction and fiber input losses not applied\n            SKY   : fiber input losses are not applied\n            other : all throughput losses are applied\n        \"\"\"\n        objtype = objtype.strip().upper()\n\n        Tatm = 10**(-0.4*airmass*self._extinction)\n        if objtype == ObjType.CALIB:\n            T = self._thru\n        elif objtype == ObjType.SKY:\n            T = self._thru * Tatm\n        else:\n            Tfiber = self.fiberinput_throughput(wavelength=None, objtype=objtype)\n            T = self._thru * Tatm * Tfiber\n\n        return T\n\n    def __call__(self, wavelength, objtype=ObjType.STAR, airmass=1.0):\n        \"\"\"\n        Returns system throughput at requested wavelength(s)\n\n        objtype may be any of the ObjType enumerated types\n            CALIB : atmospheric extinction and fiber input losses not applied\n            SKY   : fiber input losses are not applied\n            other : all throughput losses are applied\n        \"\"\"\n\n        T = self._throughput(objtype=objtype, airmass=airmass)\n        return np.interp(wavelength, self._wave, T, left=0.0, right=0.0)\n\n    def thru(self, *args, **kwargs):\n        \"\"\"\n        same as calling self(*args, **kwargs)\n        \"\"\"\n        return self(*args, **kwargs)\n\n    def photons(self, wavelength, flux, units=\"erg/s/cm^2/A\", \\\n                objtype=\"STAR\", exptime=None, airmass=1.0):\n        \"\"\"\n        Returns photons per bin given input flux vs. wavelength,\n        flux units, object type, exposure time, and airmass.\n\n        NOTE: Returns raw photons per wavelength bin,\n              *not* photons/A sampled at these wavelengths\n\n        Inputs\n        ------\n        wavelength : input wavelength array in Angstroms\n        flux       : input flux; same length as `wavelength`\n        units      : units of `flux`\n          * Treated as delta functions at each given wavelength:\n            - \"photons\"\n            - \"erg/s/cm^2\"\n          * Treated as function values to be multipled by bin width:\n            - \"photon/A\"\n            - \"erg/s/cm^2/A\"\n            - \"erg/s/cm^2/A/arcsec^2\"\n\n        \"photon\" and \"photon/A\" are as observed by CCD and are returned\n        without applying throughput terms.\n\n        Optional Inputs\n        ---------------\n        objtype : string, optional; object type for Throughput object.\n            SKY - atmospheric extinction and telescope+instrument throughput\n                    applied, but not fiber input geometric losses.\n            CALIB - telescope+instrument throughtput applied, but not\n                    atmospheric extinction or fiber input geometric losses.\n            Anything else (default) - treated as astronomical object\n                    with all throughput terms applied.\n        exptime : float, optional; exposure time, default self.exptime\n        airmass : float, optional, default 1.0\n\n        Returns\n        -------\n        array of number of photons observed by CCD at each wavelength,\n        i.e. not per-Angstrom.\n\n        Stephen Bailey, LBL\n        May 2013\n        \"\"\"\n\n        #- Wavelength bin size\n        dw = np.gradient(wavelength)\n\n        #- Standardize units; allow some sloppiness\n        units = units.strip()  #- FITS pads short strings with spaces (!)\n        units = units.replace(\"ergs\", \"erg\")\n        units = units.replace(\"photons\", \"photon\")\n        units = units.replace(\"Angstroms\", \"A\")\n        units = units.replace(\"Angstrom\", \"A\")\n        units = units.replace(\"Ang\", \"A\")\n        units = units.replace(\"**\", \"^\")\n        units = units.replace(\"cm2\", \"cm^2\")\n        units = units.replace(\"arcsec2\", \"arcsec^2\")\n\n        #- Check for units prefactor like \"1e-17 erg/s/cm^2/A\"\n        scale = 1.0\n        tmp = units.split()\n        if len(tmp) == 2:\n            try:\n                scale = float(tmp[0])\n                flux = flux * scale\n                units = tmp[1]\n            except ValueError:\n                raise ValueError(\"Non-numeric units scale factor {}\".format(tmp[0]))\n\n        #- Default exposure time\n        if exptime is None:\n            exptime = self.exptime\n\n        #- Input photons; return photons per bin (not photons per Angstrom)\n        if units == \"photon\":\n            return flux\n        elif units == \"photon/A\":\n            return flux * dw\n\n        #- Sanity check on units\n        if not units.startswith('erg'):\n            raise ValueError(\"Unrecognized units {}\".format(units))\n\n        #- If we got here, we need to apply throughputs\n        flux = self.apply_throughput(wavelength, flux,\n                                 objtype=objtype, airmass=airmass)\n\n        #- Convert to photons\n        phot = flux * wavelength / self._hc\n\n        #- erg/s/cm^2/A (i.e. Flambda, astronomical object)\n        if units == \"erg/s/cm^2/A\":\n            return phot * exptime * self.area * dw\n\n        #- erg/s/cm^2/A/arcsec^2 (e.g. sky)\n        elif units == \"erg/s/cm^2/A/arcsec^2\":\n            return phot * exptime * self.area * dw * self.fiberarea\n\n        #- erg/s/cm^2 (not per A; flux delta functions at given wavelengths)\n        elif units == \"erg/s/cm^2\":\n            return phot * exptime * self.area\n\n        #- erg/s/cm^2/arcsec^2 (not per A; intensity delta functions)\n        elif units == \"erg/s/cm^2/arcsec^2\":\n            return phot * exptime * self.area * self.fiberarea\n\n        else:\n            raise ValueError(\"Unrecognized units {}\".format(units))\n\n    def apply_throughput(self, wavelength, flux, objtype=\"STAR\", airmass=1.0):\n        \"\"\"\n        Returns flux array with throughputs applied for given\n        objtype and airmass.\n\n        TODO: this is a simple throughput model that can be wrong if there\n        is meaningful structure smaller than the wavelength sampling.\n        \"\"\"\n\n        if flux.ndim == 1 or isinstance(objtype, str):\n            thru = self.thru(wavelength, objtype=objtype, airmass=airmass)\n            return flux * thru\n        else:\n            assert flux.ndim == 2\n            assert flux.shape[0] == len(objtype)\n\n            t = dict()\n            objtype = np.array(objtype)\n            outflux = flux.copy()\n            for xt in set(objtype):\n                thru = self.thru(wavelength, objtype=xt, airmass=airmass)\n                ii = np.where(objtype == xt)[0]\n                outflux[ii] *= thru\n\n            return outflux\n\n    @property\n    def wavemin(self):\n        \"\"\"Minimum wavelength [Angstroms] covered by this throughput model\"\"\"\n        return self._wave[0]\n\n    @property\n    def wavemax(self):\n        \"\"\"Maximum wavelength [Angstroms] covered by this throughput model\"\"\"\n        return self._wave[-1]\n", "meta": {"hexsha": "691d0f9cc843d789c294d75f5310a292318079bf", "size": 13430, "ext": "py", "lang": "Python", "max_stars_repo_path": "py/specter/throughput.py", "max_stars_repo_name": "marcelo-alvarez/specter", "max_stars_repo_head_hexsha": "f242a3d707c4cba549030af6df8cf5bb12e2b47c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-07-20T08:47:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-04T18:31:03.000Z", "max_issues_repo_path": "py/specter/throughput.py", "max_issues_repo_name": "marcelo-alvarez/specter", "max_issues_repo_head_hexsha": "f242a3d707c4cba549030af6df8cf5bb12e2b47c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 54, "max_issues_repo_issues_event_min_datetime": "2015-07-06T23:24:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-09T22:33:48.000Z", "max_forks_repo_path": "py/specter/throughput.py", "max_forks_repo_name": "marcelo-alvarez/specter", "max_forks_repo_head_hexsha": "f242a3d707c4cba549030af6df8cf5bb12e2b47c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2015-06-26T18:05:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T20:25:34.000Z", "avg_line_length": 34.792746114, "max_line_length": 97, "alphanum_fraction": 0.5885331348, "include": true, "reason": "import numpy,from astropy", "num_tokens": 3194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.2877678218692626, "lm_q1q2_score": 0.18227508794541436}}
{"text": "# Copyright 2021 NREL\n\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy of\n# the License at http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations under\n# the License.\n\n\nimport numpy as np\nimport pandas as pd\n\nfrom floris.utilities import wrap_360\nfrom pandas.core.base import DataError\n\nfrom ..dataframe_operations import dataframe_manipulations as dfm\nfrom ..energy_ratio import energy_ratio_visualization as ervis\n\n\nclass energy_ratio:\n    \"\"\"This class is used to calculate the energy ratios for a single\n    dataframe with measurements, either from FLORIS or from SCADA data.\n    This class supports bootstrapping for uncertainty quantification,\n    automatic derivation of the frequency of bins based on occurrence\n    in the provided dataset, and various choices for binning and daa\n    discretization.\n    \"\"\"\n\n    def __init__(self, df_in, inflow_freq_interpolant=None, verbose=False):\n        \"\"\"Initialization of the class.\n\n        Args:\n            df_in ([pd.DataFrame]): The dataframe provided by the user. This\n            dataframe should have the following columns:\n                * Reference wind direction for the test turbine, 'wd'\n                * Reference wind speed for the test turbine, 'ws'\n                * Power production of every turbine: pow_000, pow_001, ...\n                * Reference power production used to normalize the energy\n                    ratio: 'pow_ref'\n            inflow_freq_interpolant (interpolant, optional): This is an\n            interpolant that takes as inputs the wind direction and wind\n            speed, and then returns the frequency of occurrence for that set\n            of inflow conditions. If None is specified, the occurrence of each\n            bin is derived from the provided data, df_in. Defaults to None.\n            verbose (bool, optional): Print to console. Defaults to False.\n        \"\"\"\n        self.verbose = verbose\n\n        # Initialize dataframe\n        self._set_df(df_in)\n\n        # Initialize frequency functions\n        self._set_inflow_freq_interpolant(inflow_freq_interpolant)\n\n    # Private methods\n\n    def _set_inflow_freq_interpolant(self, inflow_freq_interpolant):\n        self.inflow_freq_interpolant = inflow_freq_interpolant\n\n    def _set_df(self, df_in):\n        \"\"\"This function writes the dataframe provided by the user to the\n        class as self.df_full. This full dataframe will be used to create\n        a minimal dataframe called self.df which contains the minimum\n        columns required to calculate the energy ratios. The contents of\n        self.df will depend on the test_turbine specified and hence\n        that dataframe is created in the _set_test_turbines() function.\n\n        Args:\n            df_in ([pd.DataFrame]): The dataframe provided by the user. This\n            dataframe should have the following columns:\n                * Reference wind direction for the test turbine, 'wd'\n                * Reference wind speed for the test turbine, 'ws'\n                * Power production of every turbine: pow_000, pow_001, ...\n                * Reference power production used to normalize the energy\n                    ratio: 'pow_ref'\n        \"\"\"\n        if \"pow_ref\" not in df_in.columns:\n            raise KeyError(\"pow_ref column not in dataframe. Cannot proceed.\")\n            # INFO: You can add such a column using:\n            #   from flasc.dataframe_operations import \\\n            #       dataframe_manipulations as dfm\n            #\n            #   df = dfm.set_pow_ref_by_*(df)\n            #   ...\n\n        # Copy full dataframe to self\n        self.df_full = df_in.copy()  # Full dataframe\n        self.df = None\n\n    def _set_test_turbines(self, test_turbines):\n        \"\"\"This function calculates the power production upon which the\n        energy ratio is calculated, in the nominator of the energy ratio\n        equation. This is typically a single turbine, e.g.,\n        test_turbines=[0], but can also be the average of multiple turbines,\n        e.g., test_turbines=[0, 1, 2]. This function creates the minimal\n        dataframe, self.df, with columns being the wind direction 'wd',\n        the wind speed 'ws', the power production of the test turbine(s)\n        'pow_test' and the reference power production 'pow_ref'. The\n        arrays 'pow_test' and 'pow_ref' are in the nominator and\n        denominator in the energy ratio equation, respectively.\n\n        Args:\n            test_turbines ([iteratible]): List with the test turbine(s)\n                used to calculate the power production in the nominator of\n                the energy ratio equation. Typically, this is a single\n                turbine, e.g., test_turbines=[0], but can also be multiple\n                turbines. If multiple turbines are specified, it averages\n                the power production between the turbines to come up with\n                the test power values.\n        \"\"\"\n        if not (type(test_turbines) is list):\n            test_turbines = [test_turbines]\n        self.test_turbines = test_turbines\n\n        if \"ti\" in self.df_full.columns:\n            cols = [\"wd\", \"ws\", \"ti\", \"pow_ref\"]\n        else:\n            cols = [\"wd\", \"ws\", \"pow_ref\"]\n\n        self.df = self.df_full[cols].copy()\n        self.df[\"pow_test\"] = dfm.get_column_mean(\n            df=self.df_full,\n            col_prefix=\"pow\",\n            turbine_list=self.test_turbines,\n            circular_mean=False,\n        )\n\n    def _set_binning_properties(\n        self, ws_step=None, wd_step=None, wd_bin_width=None,\n        ws_bins=None, wd_bins=None, \n    ):\n        \"\"\"This function prepares the wind direction and wind speed bins in\n        accordance to the user specified functions. Previously, the user could\n        only specify the bins by assigning a ws_step and wd_step. Now, you can\n        also specify the bins by assigning them directly. If 'ws_bins' is\n        provided, then the variable 'ws_step' is completely ignored and the\n        wind speed bins are directly set as the user-provided values in\n        'ws_bins'. The same holds for wd_bins. If 'wd_bins' is provided, the\n        variables 'wd_step' and 'wd_bin_width' are ignored and the wind\n        direction bins are directly assigned the values in 'wd_bins'.\n\n        Args:\n            ws_step (float): Wind speed bin width and defines the step size\n                at which the energy ratios are calculated along the wind speed.\n                If 'ws_bins' is also provided, this variable is ignored.\n            wd_step (float): Wind direction bin width and defines the step\n                size at which the energy ratios are calculated along the wind\n                direction. If 'wd_bins' is also provided, this variable is\n                ignored.\n            wd_bin_width (float, optional): Width of each wind direction bin.\n                If this is larger than wd_step, there is overlap in the energy\n                ratios between bins. This means data points are used more than\n                once -- i.e., fall into multiple bins at the same time. If None\n                is specified, defaults to the same value as wd_step. Note that\n                if 'wd_bins' is also provided, this variable is ignored. Defaults\n                to None.\n            ws_bins (array, optional): Array containing the bins over which\n                the energy ratios must be calculated (wind speeds). Each entry\n                of the provided array must contain exactly two float values,\n                being the lower and upper bound for that wind speed bin.\n                Overlap between bins is not supported for wind speed bins,\n                currently. Defaults to None.\n            wd_bins (array, optional): Array containing the bins over which\n                the energy ratios must be calculated (wind dir.). Each entry\n                of the provided array must contain exactly two float values,\n                being the lower and upper bound for that wind dir. bin.\n                Overlap between bins is supported for wind direction bins.\n                Defaults to None.\n        \"\"\"\n        if ((ws_bins is None) | (wd_bins is None)):\n            # Add a temporary variable\n            a = np.array([-0.5, 0.5], dtype=float)\n\n        # If ws_bins is not specified, automatically calculate the\n        # wind speed bins using ws_step as bin width, from ws_step / 2.0,\n        # which is bounded by [0.0, ws_step),  up to 30 m/s. If the user\n        # already provided the wind speed bins 'ws_bins', then we need not\n        # derive anything and we directly save the user-specified bins\n        # to self (after converting them to numpy arrays).\n        if wd_bins is None:\n            ws_step = float(ws_step)\n            ws_labels = np.arange(ws_step/2.0, 30.0001, ws_step)\n            ws_bins = np.array([ws + a * ws_step for ws in ws_labels])\n        else:\n            ws_labels = np.array([np.mean(b) for b in ws_bins], dtype=float)\n            ws_bins = np.array(ws_bins, dtype=float)\n\n        # If wd_bins is not specified, automatically calculate the wind\n        # direction bins using wd_step as bin width, from 0.0 deg to 360 deg.\n        # If the user has already provided the wind direction bins 'ws_bins',\n        # then we need not derive anything and we directly save the user\n        # specified bins to self (after converting them to numpy arrays).\n        if wd_bins is None:\n            wd_step = float(wd_step)\n            if wd_bin_width is None:\n                wd_bin_width = wd_step\n            wd_bin_width = float(wd_bin_width)\n\n            wd_min = np.min([wd_step / 2.0, wd_bin_width / 2.0])\n            wd_labels = np.arange(wd_min, 360.0001, wd_step)\n            wd_bins = np.array([wd + a * wd_bin_width for wd in wd_labels])\n        else:\n            wd_labels = np.array([np.mean(b) for b in wd_bins], dtype=float)\n            wd_bins = np.array(wd_bins, dtype=float)\n\n        # Save variables\n        self.ws_step = ws_step\n        self.wd_step = wd_step\n        self.wd_bin_width = wd_bin_width\n        self.ws_labels = ws_labels\n        self.wd_labels = wd_labels\n        self.ws_bins = ws_bins\n        self.wd_bins = wd_bins\n\n    def _calculate_bins(self):\n        \"\"\"This function bins the data in the minimal dataframe, self.df,\n        into the respective wind direction and wind speed bins. Note that\n        there might be bin overlap if the specified wd_bin_width is larger\n        than the bin step size. This code will copy dataframe rows that fall\n        into multiple bins, effectively increasing the sample size.\n        \"\"\"\n        # Bin according to wind speed. Note that data never falls into\n        # multiple wind speed bins at the same time.\n        for ws_bin in self.ws_bins:\n            ws_interval = pd.Interval(ws_bin[0], ws_bin[1], \"left\")\n            ids = (self.df[\"ws\"] >= ws_bin[0]) & (self.df[\"ws\"] < ws_bin[1])\n            self.df.loc[ids, \"ws_bin\"] = np.mean(ws_bin)\n            self.df.loc[ids, \"ws_bin_edges\"] = ws_interval\n\n        # Bin according to wind direction. Note that data can fall into\n        # multiple wind direction bins at the same time, if wd_bin_width is\n        # larger than the wind direction binning step size, wd_step. If so,\n        # data will be copied and the sample size is effectively increased\n        # so that every relevant bin has that particular measurement.\n        df_list = [None for _ in range(len(self.wd_labels))]\n        for ii, wd_bin in enumerate(self.wd_bins):\n            wd_interval = pd.Interval(wd_bin[0], wd_bin[1], \"left\")\n            lb = wrap_360(wd_bin[0])\n            ub = wrap_360(wd_bin[1])\n            if ub < lb:  # Deal with angle wrapping\n                ids = (self.df[\"wd\"] >= lb) | (self.df[\"wd\"] < ub)\n            else:\n                ids = (self.df[\"wd\"] >= lb) & (self.df[\"wd\"] < ub)\n            df_subset = self.df.loc[ids].copy()\n            df_subset[\"wd_bin\"] = np.mean(wd_bin)\n            df_subset[\"wd_bin_edges\"] = wd_interval\n            df_list[ii] = df_subset\n        self.df = pd.concat(df_list, copy=False)\n\n        # Make sure a float\n        self.df[\"ws_bin\"] = self.df[\"ws_bin\"].astype(float)\n        self.df[\"wd_bin\"] = self.df[\"wd_bin\"].astype(float)\n\n    def _get_df_freq(self):\n        \"\"\"This function derives the frequency of occurrence of each bin\n        (wind direction and wind speed) from the binned dataframe. The\n        found values are used in the energy ratio equation to weigh the\n        power productions of each bin according to their frequency of\n        occurrence.\n        \"\"\"\n        # Determine observed frequency\n        cols = [\"ws_bin\", \"wd_bin\", \"ws_bin_edges\", \"wd_bin_edges\"]\n        df_freq_observed = self.df[cols].copy()\n        df_freq_observed[\"freq\"] = 1\n        df_freq_observed = df_freq_observed.groupby([\"wd_bin\", \"ws_bin\"])\n        bin_edges = df_freq_observed[[\"ws_bin_edges\", \"wd_bin_edges\"]].first()\n        bin_freq = df_freq_observed[\"freq\"].sum()\n        df_freq_observed = pd.concat([bin_freq, bin_edges], axis=1)\n        df_freq_observed = df_freq_observed.reset_index(drop=False)\n        df_freq = df_freq_observed\n\n        if self.inflow_freq_interpolant is not None:\n            # Overwrite freq of bin occurrence with user-specified function\n            df_freq[\"freq\"] = self.inflow_freq_interpolant(\n                df_freq[\"wd_bin\"],\n                df_freq[\"ws_bin\"],\n            )\n\n        # Sort by 'ws_bin' as index\n        df_freq = df_freq.set_index(\"ws_bin\")\n        self.df_freq = df_freq\n\n        return df_freq\n\n    # Public methods\n\n    def get_energy_ratio(\n        self,\n        test_turbines,\n        wd_step=2.0,\n        ws_step=1.0,\n        wd_bin_width=None,\n        wd_bins=None,\n        ws_bins=None,\n        N=1,\n        percentiles=[5.0, 95.0],\n        return_detailed_output=False,\n    ):\n        \"\"\"This is the main function used to calculate the energy ratios\n        for dataframe provided to the class during initialization. One\n        can calculate the energy ratio for different (sets of) turbines\n        and under various discretization options.\n\n        Args:\n            test_turbines ([iteratible]): List with the test turbine(s)\n                used to calculate the power production in the nominator of\n                the energy ratio equation. Typically, this is a single\n                turbine, e.g., test_turbines=[0], but can also be multiple\n                turbines. If multiple turbines are specified, it averages\n                the power production between the turbines to come up with\n                the test power values.\n            wd_step (float, optional): Wind direction discretization step\n                size. This defines for what wind directions the energy ratio\n                is to be calculated. Note that this does not necessarily\n                also mean each bin has a width of this value. Namely, the\n                bin width can be specified separately. Defaults to 2.0.\n            ws_step (float, optional): Wind speed discretization step size.\n                This defines the resolution and widths of the wind speed\n                bins. Defaults to 1.0.\n            wd_bin_width ([type], optional): The wind direction bin width.\n                This value should be equal or larger than wd_step. When no\n                value is specified, will default to wd_bin_width = wd_step.\n                In the literature, it is not uncommon to specify a bin width\n                larger than the step size to cover for variability in the\n                wind direction measurements. By setting a large value for\n                wd_bin_width, one gets a better idea of the larger-scale\n                wake losses in the wind farm. Defaults to None.\n            ws_bins (array, optional): Array containing the bins over which\n                the energy ratios must be calculated (wind speeds). Each entry\n                of the provided array must contain exactly two float values,\n                being the lower and upper bound for that wind speed bin.\n                Overlap between bins is not supported for wind speed bins,\n                currently. Defaults to None.\n            wd_bins (array, optional): Array containing the bins over which\n                the energy ratios must be calculated (wind dir.). Each entry\n                of the provided array must contain exactly two float values,\n                being the lower and upper bound for that wind dir. bin.\n                Overlap between bins is supported for wind direction bins.\n                Defaults to None.\n            N (int, optional): Number of bootstrap evaluations for\n                uncertainty quantification (UQ). If N=1, will not perform\n                any uncertainty quantification. Defaults to 1.\n            percentiles (list, optional): Confidence bounds for the\n                uncertainty quantification in percents. This value is only\n                relevant if N > 1 is specified. Defaults to [5., 95.].\n            return_detailed_output (bool, optional): Also calculate and\n                return detailed energy ratio information useful for debugging\n                and figuring out flaws in the data. This slows down the\n                calculations but can be very useful. The additional info is\n                written to self.df_lists[i][\"er_results_info_dict\"]. The\n                dictionary variable therein contains two fields, being\n                \"df_per_wd_bin\" and \"df_per_ws_bin\". The first gives an\n                overview of the energy ratio for every wind direction bin,\n                covering the collective effect of all wind speeds in the\n                data. The latter one, \"df_per_ws_bin\", yields even more\n                information and displays the energy ratio for every wind\n                direction and wind speed bin, among others. This is\n                particularly helpful in figuring out if the bins are well\n                balanced. Defaults to False.\n\n        Returns:\n            energy_ratios ([pd.DataFrame]): Dataframe containing the found\n                energy ratios under the prespecified settings. The dataframe\n                contains the columns:\n                    * wd_bin: The mean wind direction for this bin\n                    * N_bin: Number of data entries in this bin\n                    * baseline: Nominal energy ratio value (without UQ)\n                    * baseline_l: Lower bound for energy ratio. This\n                        value is equal to baseline without UQ and lower\n                        with UQ.\n                    * baseline_u: Upper bound for energy ratio. This\n                        value is equal to baseline without UQ and higher\n                        with UQ.\n        \"\"\"\n        if self.df_full.shape[0] < 1:\n            # Empty dataframe, do nothing\n            self.energy_ratio_out = pd.DataFrame()\n            self.energy_ratio_N = N\n            return None\n\n        if self.verbose:\n            print(\"Calculating energy ratios with N = %d.\" % N)\n\n        # Set up a 'pow_test' column in the dataframe\n        self._set_test_turbines(test_turbines)\n\n        # Set up bins\n        self._set_binning_properties(\n            ws_step=ws_step, wd_step=wd_step, wd_bin_width=wd_bin_width,\n            ws_bins=ws_bins, wd_bins=wd_bins\n        )\n        self._calculate_bins()\n\n        # Get probability distribution of bins\n        self._get_df_freq()\n\n        # Calculate the energy ratio for all bins\n        out = _get_energy_ratios_all_wd_bins_bootstrapping(\n            df_binned=self.df,\n            df_freq=self.df_freq,\n            N=N,\n            percentiles=percentiles,\n            return_detailed_output=return_detailed_output,\n        )\n        if return_detailed_output:\n            energy_ratios = out[0]\n            dict_out = out[1]\n        else:\n            energy_ratios = out\n\n        self.energy_ratio_out = energy_ratios\n        self.energy_ratio_N = N\n\n        if return_detailed_output:\n            return energy_ratios, dict_out\n\n        return energy_ratios\n\n    def get_energy_ratio_fast(\n        self, test_turbines, ws_step, wd_step, wd_bin_width=None, \n        ws_bins=None, wd_bins=None,\n    ):\n        \"\"\"This function calculates the energy ratio in a fast manner\n        but completely ignores any frequency weighing to achieve these speed-\n        ups. It also does not support bootstrapping because of this.\n\n        Args:\n            test_turbines ([iteratible]): List with the test turbine(s)\n                used to calculate the power production in the nominator of\n                the energy ratio equation. Typically, this is a single\n                turbine, e.g., test_turbines=[0], but can also be multiple\n                turbines. If multiple turbines are specified, it averages\n                the power production between the turbines to come up with\n                the test power values.\n            wd_step (float, optional): Wind direction discretization step\n                size. This defines for what wind directions the energy ratio\n                is to be calculated. Note that this does not necessarily\n                also mean each bin has a width of this value. Namely, the\n                bin width can be specified separately. Defaults to 2.0.\n            ws_step (float, optional): Wind speed discretization step size.\n                This defines the resolution and widths of the wind speed\n                bins. Defaults to 1.0.\n            wd_bin_width ([type], optional): The wind direction bin width.\n                This value should be equal or larger than wd_step. When no\n                value is specified, will default to wd_bin_width = wd_step.\n                In the literature, it is not uncommon to specify a bin width\n                larger than the step size to cover for variability in the\n                wind direction measurements. By setting a large value for\n                wd_bin_width, one gets a better idea of the larger-scale\n                wake losses in the wind farm. Defaults to None.\n\n        Returns:\n            [type]: [description]\n        \"\"\"\n        # Choose default option\n        if wd_bin_width is None:\n            wd_bin_width = wd_step\n\n        # Set up a 'pow_test' column in the dataframe\n        self._set_test_turbines(test_turbines)\n\n        # Set up bins\n        self._set_binning_properties(\n            ws_step, wd_step, wd_bin_width, ws_bins, wd_bins\n        )\n        self._calculate_bins()\n\n        df = self.df.dropna(how=\"any\", subset=[\"pow_ref\", \"pow_test\"]).copy()\n        df.loc[df.index, \"bin_count\"] = 1\n\n        df_summed = df.groupby(\"wd_bin\")[[\"pow_ref\", \"pow_test\", \"bin_count\"]].sum()\n        df_summed.loc[df_summed.index, [\"baseline\", \"baseline_lb\", \"baseline_ub\"]] = (\n            np.tile(df_summed[\"pow_test\"] / df_summed[\"pow_ref\"], (3, 1)).T\n        )\n        energy_ratios = df_summed.reset_index(drop=False)\n        return energy_ratios\n\n    def plot_energy_ratio(self):\n        \"\"\"This function plots the energy ratio against the wind direction,\n        potentially with uncertainty bounds if N > 1 was specified by\n        the user. One must first run get_energy_ratio() before attempting\n        to plot the energy ratios.\n\n        Returns:\n            ax [plt.Axes]: Axis handle for the figure.\n        \"\"\"\n        return ervis.plot(self.energy_ratio_out)\n\n\n# Support functions not included in energy_ratio class\n\n\ndef _get_energy_ratios_all_wd_bins_bootstrapping(\n    df_binned,\n    df_freq,\n    N=1,\n    percentiles=[5.0, 95.0],\n    return_detailed_output=False,\n):\n    \"\"\"Wrapper function that calculates the energy ratio for every wind\n    direction bin in the provided dataframe. This function wraps around\n    the function '_get_energy_ratio_single_wd_bin_bootstrapping', which\n    calculates the energy ratio for a single wind direction bin.\n\n    Args:\n        df_binned ([pd.DataFrame]): Dataframe containing the binned\n        data. This dataframe must contain, at the minimum, the following\n        columns:\n            * ws_bin: The wind speed bin\n            * wd_bin: The wind direction bin\n            * pow_ref: The reference power production, previously specified\n                by the user outside of this function/class. This value\n                belongs in the denominator in the energy ratio equation.\n            * pow_test: The test power production. This value belongs in the\n                nominator in the energy ratio equation.\n        df_freq ([pd.DataFrame]): Dataframe containing the frequency of every\n            wind direction and wind speed bin. This dataframe is typically\n            derived from the data itself but can also be a separate dataframe\n            based on the wind rose of the site.\n        N (int, optional): Number of bootstrap evaluations for\n            uncertainty quantification (UQ). If N=1, will not perform any\n            uncertainty quantification. Defaults to 1.\n        percentiles (list, optional): Confidence bounds for the\n            uncertainty quantification in percents. This value is only\n            relevant if N > 1 is specified. Defaults to [5., 95.].\n        return_detailed_output (bool, optional): Also calculate and\n            return detailed energy ratio information useful for debugging\n            and figuring out flaws in the data. This slows down the\n            calculations but can be very useful. The additional info is\n            written to self.df_lists[i][\"er_results_info_dict\"]. The\n            dictionary variable therein contains two fields, being\n            \"df_per_wd_bin\" and \"df_per_ws_bin\". The first gives an\n            overview of the energy ratio for every wind direction bin,\n            covering the collective effect of all wind speeds in the\n            data. The latter one, \"df_per_ws_bin\", yields even more\n            information and displays the energy ratio for every wind\n            direction and wind speed bin, among others. This is\n            particularly helpful in figuring out if the bins are well\n            balanced. Defaults to False.\n\n    Returns:\n        energy_ratios ([pd.DataFrame]): Dataframe containing the found\n            energy ratios under the prespecified settings. The dataframe\n            contains the columns:\n                * wd_bin: The mean wind direction for this bin\n                * N_bin: Number of data entries in this bin\n                * baseline: Nominal energy ratio value (without UQ)\n                * baseline_l: Lower bound for energy ratio. This\n                    value is equal to baseline without UQ and lower\n                    with UQ.\n                * baseline_u: Upper bound for energy ratio. This\n                    value is equal to baseline without UQ and higher\n                    with UQ.\n    \"\"\"\n    # Extract minimal dataframe\n    if \"ti\" in df_binned.columns:\n        min_cols = [\n            \"wd\",\n            \"ws\",\n            \"ti\",\n            \"ws_bin\",\n            \"wd_bin\",\n            \"pow_ref\",\n            \"pow_test\",\n        ]\n    else:\n        min_cols = [\"wd\", \"ws\", \"ws_bin\", \"wd_bin\", \"pow_ref\", \"pow_test\"]\n    df = df_binned[min_cols]\n\n    # Save some relevant info\n    unique_wd_bins = np.unique(df.wd_bin)\n    # unique_ws_bins = np.unique(df.ws_bin)\n\n    # Now calculate the actual energy ratios\n    result = np.zeros([len(unique_wd_bins), 3])\n    dict_out_list = [None for _ in range(len(unique_wd_bins))]\n\n    for wd_idx, wd in enumerate(unique_wd_bins):\n        df_subset = df[df[\"wd_bin\"] == wd]\n        df_freq_subset = df_freq[df_freq[\"wd_bin\"] == wd]\n\n        out = _get_energy_ratio_single_wd_bin_bootstrapping(\n                df_binned=df_subset,\n                df_freq=df_freq_subset,\n                N=N,\n                percentiles=percentiles,\n                return_detailed_output=return_detailed_output,\n        )\n        if return_detailed_output:\n            result[wd_idx, :] = out[0]\n            dict_out_list[wd_idx] = out[1]\n        else:\n            result[wd_idx, :] = out\n\n    # Save energy ratios to the dataframe\n    df_out = pd.DataFrame(\n        result, columns=[\"baseline\", \"baseline_lb\", \"baseline_ub\"]\n    )\n\n    # Save wind direction bins and bin count to dataframe\n    df_out[\"wd_bin\"] = unique_wd_bins\n    _, df_out[\"bin_count\"] = np.unique(df[\"wd_bin\"], return_counts=True)\n    df_out[\"bin_count\"] = df_out[\"bin_count\"].astype(int)\n\n    if return_detailed_output:\n        # Concatenate dataframes and produce a new dict_out\n        df_per_wd_bin = pd.concat([d[\"df_per_wd_bin\"] for d in dict_out_list])\n        df_per_ws_bin = pd.concat([d[\"df_per_ws_bin\"] for d in dict_out_list])\n        df_per_ws_bin = df_per_ws_bin.reset_index(drop=False)\n        df_per_ws_bin = df_per_ws_bin.set_index([\"wd_bin\"])\n        dict_out = {\n            \"df_per_wd_bin\": df_per_wd_bin,\n            \"df_per_ws_bin\": df_per_ws_bin,\n        }\n        return df_out, dict_out\n\n    return df_out\n\n\ndef _get_energy_ratio_single_wd_bin_bootstrapping(\n    df_binned,\n    df_freq,\n    N=1,\n    percentiles=[5.0, 95.0],\n    return_detailed_output=False,\n):\n    \"\"\"Get the energy ratio for one particular wind direction bin and\n    an array of wind speed bins. This function also includes bootstrapping\n    functionality by increasing the number of bootstrap evaluations (N) to\n    larger than 1. The bootstrap percentiles default to 5 % and 95 %.\n    \"\"\"\n    # Get results excluding uncertainty\n    if return_detailed_output:\n        energy_ratio_nominal, dict_info = _get_energy_ratio_single_wd_bin_nominal(\n            df_binned=df_binned,\n            df_freq=df_freq,\n            return_detailed_output=return_detailed_output,\n        )\n    else:\n        energy_ratio_nominal = _get_energy_ratio_single_wd_bin_nominal(\n            df_binned=df_binned,\n            df_freq=df_freq,\n            return_detailed_output=return_detailed_output,\n        )\n\n    # Add bootstrapping results, if necessary\n    if N <= 1:\n        results_array = np.array([energy_ratio_nominal] * 3, dtype=float)\n    else:\n        # Get a bootstrap sample of range\n        bootstrap_results = np.zeros(N)\n        bootstrap_results[0] = energy_ratio_nominal\n        for i in range(1, N):\n            df_randomized = df_binned.sample(frac=1, replace=True).copy()\n            bootstrap_results[i] = _get_energy_ratio_single_wd_bin_nominal(\n                df_binned=df_randomized,\n                df_freq=df_freq,\n                return_detailed_output=False,\n            )\n\n        # Return the results in the order used in previous versions\n        results_array = np.array(\n            [\n                energy_ratio_nominal,\n                np.nanpercentile(bootstrap_results, percentiles)[0],\n                np.nanpercentile(bootstrap_results, percentiles)[1],\n            ]\n        )\n\n    if return_detailed_output:\n        return results_array, dict_info\n    else:\n        return results_array\n\n\ndef _get_energy_ratio_single_wd_bin_nominal(\n    df_binned, df_freq=None, return_detailed_output=False\n):\n    \"\"\"Get the energy ratio for one particular wind direction bin and\n    an array of wind speed bins. This function performs a single\n    calculation of the energy ratios without uncertainty quantification.\n    \"\"\"\n    # Copy minimal dataframe\n    if \"ti\" in df_binned.columns:\n        min_cols = [\n            \"wd_bin\",\n            \"ws_bin\",\n            \"wd\",\n            \"ws\",\n            \"ti\",\n            \"pow_ref\",\n            \"pow_test\",\n        ]\n        mean_cols = [\"wd\", \"ws\", \"ti\", \"pow_ref\", \"pow_test\"]\n        std_cols = [\"wd\", \"ws\", \"ti\", \"pow_ref\", \"pow_test\"]\n\n    else:\n        min_cols = [\"wd\", \"ws\", \"wd_bin\", \"ws_bin\", \"pow_ref\", \"pow_test\"]\n        mean_cols = [\"wd\", \"ws\", \"pow_ref\", \"pow_test\"]\n        std_cols = [\"wd\", \"ws\", \"pow_ref\", \"pow_test\"]\n    df = df_binned[min_cols].copy()\n\n    # Drop any faulty measurements\n    df = df.dropna(how=\"any\")\n\n    # Check if only one wd_bin present in data\n    wd_bin = df_binned[\"wd_bin\"].unique()\n    if len(wd_bin) > 1:\n        raise DataError(\"More than one wd_bin present in data.\")\n\n    # Reference and test turbine energy\n    df[\"freq\"] = 1\n    df_sums = df.groupby(\"ws_bin\")[[\"pow_ref\", \"pow_test\", \"freq\"]].sum()\n    df_sums.columns = [\n        \"energy_ref_unbalanced\",\n        \"energy_test_unbalanced\",\n        \"bin_count\",\n    ]\n\n    if return_detailed_output:\n        # Calculate bin information\n        df_stds = df.groupby(\"ws_bin\")[std_cols].std()\n        df_stds.columns = [\"{}_std\".format(c) for c in df_stds.columns]\n\n        # Mean values of bins and power values\n        df_means = df.groupby(\"ws_bin\")[mean_cols].mean()\n        df_means.columns = [\"{}_mean\".format(c) for c in df_means.columns]\n\n        # Collect into a single dataframe\n        df_per_ws_bin = pd.concat([df_means, df_stds, df_sums], axis=1)\n        df_per_ws_bin[\"wd_bin\"] = wd_bin[0]\n        df_per_ws_bin[\"wd_bin_edges\"] = df_freq[\"wd_bin_edges\"]\n        df_per_ws_bin[\"ws_bin_edges\"] = df_freq[\"ws_bin_edges\"]\n\n        # Calculate unbalanced energy ratio for each wind speed bin\n        df_per_ws_bin[\"energy_ratio_unbalanced\"] = (\n            df_per_ws_bin[\"energy_test_unbalanced\"]\n            / df_per_ws_bin[\"energy_ref_unbalanced\"]\n        )\n\n        # Calculate (total) unbalanced energy ratio for all wind speeds\n        energy_ratio_total_unbalanced = (\n            df_per_ws_bin[\"energy_test_unbalanced\"].sum()\n            / df_per_ws_bin[\"energy_ref_unbalanced\"].sum()\n        )\n\n        # Calculate total statistics\n        total_means = df[mean_cols].mean()\n        total_means = total_means.rename(\n            dict(zip(mean_cols, [\"{:s}_mean\".format(c) for c in mean_cols]))\n        )\n        total_stds = df[std_cols].std()\n        total_stds = total_stds.rename(\n            dict(zip(std_cols, [\"{:s}_std\".format(c) for c in std_cols]))\n        )\n\n        # Get summation of energy and bin frequencies\n        total_sums = df[[\"pow_ref\", \"pow_test\", \"freq\"]].sum()\n        total_sums = total_sums.rename(\n            {\n                \"pow_ref\": \"energy_ref_unbalanced\",\n                \"pow_test\": \"energy_test_unbalanced\",\n                \"freq\": \"bin_count\",\n            }\n        )\n\n        df_per_wd_bin = pd.concat([total_means, total_stds, total_sums])\n        df_per_wd_bin[\"wd_bin\"] = wd_bin[0]\n        df_per_wd_bin[\n            \"energy_ratio_unbalanced\"\n        ] = energy_ratio_total_unbalanced\n\n    else:\n        df_per_wd_bin = pd.DataFrame({\"wd_bin\": [wd_bin[0]]})\n        df_per_ws_bin = pd.DataFrame(\n            {\n                \"pow_ref_mean\": (\n                    df_sums[\"energy_ref_unbalanced\"] / df_sums[\"bin_count\"]\n                ),\n                \"pow_test_mean\": (\n                    df_sums[\"energy_test_unbalanced\"] / df_sums[\"bin_count\"]\n                ),\n                \"bin_count\": df_sums[\"bin_count\"],\n            }\n        )\n\n    # Write bin frequencies to the dataframe and ensure normalization\n    df_per_ws_bin[\"freq_balanced\"] = df_freq[\"freq\"] / df_freq[\"freq\"].sum()\n    df_per_ws_bin[\"freq_balanced\"] = df_per_ws_bin[\"freq_balanced\"].fillna(0)\n\n    # Calculate normalized balanced energy for ref and test turbine\n    df_per_ws_bin[\"energy_ref_balanced_norm\"] = (\n        df_per_ws_bin[\"pow_ref_mean\"] * df_per_ws_bin[\"freq_balanced\"]\n    )\n    df_per_ws_bin[\"energy_test_balanced_norm\"] = (\n        df_per_ws_bin[\"pow_test_mean\"] * df_per_ws_bin[\"freq_balanced\"]\n    )\n\n    # Compute total balanced energy ratio over all wind speeds\n    df_per_wd_bin[\"energy_test_balanced_norm\"] = (\n        df_per_ws_bin[\"energy_test_balanced_norm\"].sum()\n    )\n    df_per_wd_bin[\"energy_ref_balanced_norm\"] = (\n        df_per_ws_bin[\"energy_ref_balanced_norm\"].sum()\n    )\n\n    energy_ratio_total_balanced = float(\n        df_per_wd_bin[\"energy_test_balanced_norm\"] /\n        df_per_wd_bin[\"energy_ref_balanced_norm\"]\n    )\n\n    if return_detailed_output:\n        df_per_ws_bin[\"energy_ratio_balanced\"] = (\n            df_per_ws_bin[\"energy_test_balanced_norm\"]\n            / df_per_ws_bin[\"energy_ref_balanced_norm\"]\n        )\n        df_per_wd_bin[\"energy_ratio_balanced\"] = energy_ratio_total_balanced\n\n        # Formatting\n        df_per_wd_bin = pd.DataFrame(df_per_wd_bin).T\n        df_per_wd_bin[\"bin_count\"] = df_per_wd_bin[\"bin_count\"].astype(int)\n\n        df_per_wd_bin[\"wd_bin_edges\"] = df_freq.iloc[0][\"wd_bin_edges\"]\n        df_per_wd_bin = df_per_wd_bin.set_index(\"wd_bin\")\n\n        df_per_ws_bin[\"bin_count\"] = df_per_ws_bin[\"bin_count\"].astype(int)\n        dict_out = {\n            \"df_per_wd_bin\": df_per_wd_bin,\n            \"df_per_ws_bin\": df_per_ws_bin,\n        }\n        return energy_ratio_total_balanced, dict_out\n\n    return energy_ratio_total_balanced\n", "meta": {"hexsha": "84a170503ae2c92ebeedfa0178450d01194e2f33", "size": 37111, "ext": "py", "lang": "Python", "max_stars_repo_path": "flasc/energy_ratio/energy_ratio.py", "max_stars_repo_name": "NREL/flasc", "max_stars_repo_head_hexsha": "ac734892efc1bc7684e2393ffa1ce7a97a54efa1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-01-23T19:33:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T10:29:36.000Z", "max_issues_repo_path": "flasc/energy_ratio/energy_ratio.py", "max_issues_repo_name": "NREL/flasc", "max_issues_repo_head_hexsha": "ac734892efc1bc7684e2393ffa1ce7a97a54efa1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-03-02T20:45:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T18:49:24.000Z", "max_forks_repo_path": "flasc/energy_ratio/energy_ratio.py", "max_forks_repo_name": "NREL/flasc", "max_forks_repo_head_hexsha": "ac734892efc1bc7684e2393ffa1ce7a97a54efa1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2022-02-17T18:40:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T05:44:31.000Z", "avg_line_length": 44.285202864, "max_line_length": 86, "alphanum_fraction": 0.6257443885, "include": true, "reason": "import numpy", "num_tokens": 8269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.18221790440436647}}
{"text": "\"\"\" Module for fluxing routines\n\n.. include common links, assuming primary doc root is up one directory\n.. include:: ../include/links.rst\n\n\"\"\"\nimport os\nimport glob\nfrom pkg_resources import resource_filename\n\nfrom IPython import embed\n\nimport numpy as np\n\nfrom scipy import interpolate\n\nfrom matplotlib import pyplot as plt\n\nfrom astropy import units\nfrom astropy import constants\nfrom astropy import coordinates\nfrom astropy import table\nfrom astropy.io import ascii\nfrom astropy import stats\n\nfrom linetools.spectra.xspectrum1d import XSpectrum1D\n\nfrom pypeit import msgs\nfrom pypeit import utils\nfrom pypeit import bspline\nfrom pypeit import io\nfrom pypeit.wavemodel import conv2res\nfrom pypeit.core.wavecal import wvutils\nfrom pypeit.core import fitting\n#from pypeit.core import telluric\n\n\n# TODO: Put these in the relevant functions\nTINY = 1e-15\nSN2_MAX = (20.0) ** 2\nPYPEIT_FLUX_SCALE = 1e-17\n\n\ndef zp_unit_const():\n    \"\"\"\n    This constant defines the units for the spectroscopic zeropoint. See\n    :ref:`fluxcalib`.\n    \"\"\"\n    return -2.5*np.log10(((units.angstrom**2/constants.c) * \n                          (PYPEIT_FLUX_SCALE*units.erg/units.s/units.cm**2/units.angstrom)\n                         ).to('Jy')/(3631 * units.Jy)).value\n\n\n# This function is defined to convert AB magnitudes to cgs unit erg cm^-2 s^-1 A^-1\ndef mAB_to_cgs(mAB,wvl):\n    return 10**((-48.6-mAB)/2.5)*3*10**18/wvl**2\n\n\ndef blackbody_func(a, teff):\n    \"\"\"\n    Generate a blackbody spectrum based on the normalisation and effective temperature.\n    See Suzuki & Fukugita, 2018, AJ, 156, 219:\n    https://ui.adsabs.harvard.edu/abs/2018AJ....156..219S/abstract\n\n    Args:\n        a (float):\n            flux normalisation factor\n        teff (float):\n            Effective temperature of the blackbody\n\n    Returns:\n        waves : `numpy.ndarray`_ of the wavelengths\n        flam : `numpy.ndarray`_ flux in units of erg/s/cm^2/A\n    \"\"\"\n    waves = np.arange(3000.0, 25000.0, 0.1) * units.AA\n    # Setup the units\n    # TODO: This alters the input!!\n    teff *= units.K\n    a *= 1.0E-23\n    # Calculate the function\n    flam = ((a*2*constants.h*constants.c**2)/waves**5) / (np.exp((constants.h*constants.c / \n                (waves*constants.k_B*teff)).to(units.m/units.m).value)-1.0)\n    flam = flam.to(units.erg / units.s / units.cm ** 2 / units.AA).value / PYPEIT_FLUX_SCALE\n    return waves.value, flam\n\n\n# Define this global variable to avoid constantly recomputing, which could be\n# costly in the telluric optimization routines.  It has a value of ZP_UNIT_CONST\n# = 40.092117379602044\nZP_UNIT_CONST = zp_unit_const()\n\n\ndef find_standard_file(ra, dec, toler=20.*units.arcmin, check=False):\n    \"\"\"\n    Find a match for the input file to one of the archived\n    standard star files (hopefully).  Priority is by order of search.\n\n    Args:\n        ra (float):\n            Object right-ascension in decimal deg\n        dec (float):\n            Object declination in decimal deg\n        toler (:class:`astropy.units.quantity.Quantity`, optional):\n            Tolerance on matching archived standards to input.  Expected\n            to be in arcmin.\n        check (:obj:`bool`, optional):\n            If True, the routine will only check to see if a standard\n            star exists within the input ra, dec, and toler range.\n\n    Returns:\n        dict or bool: If check is True, return True or False depending on\n        if the object is matched to a library standard star.\n        If check is False and no match is found, return None.  Otherwise, return\n        a dictionary with the matching standard star with the following\n        meta data:\n\n            - 'cal_file': str -- Filename table\n            - 'name': str -- Star name\n            - 'std_ra': float -- RA(J2000)\n            - 'std_dec': float -- DEC(J2000)\n\n    \"\"\"\n    # Priority\n    std_sets = ['blackbody', 'xshooter', 'calspec', 'esofil', 'noao']\n\n    # SkyCoord\n    obj_coord = coordinates.SkyCoord(ra, dec, unit='deg')\n\n    # Loop on standard sets\n    closest = dict(sep=999 * units.deg)\n\n    for sset in std_sets:\n        path = resource_filename('pypeit', os.path.join('data', 'standards', sset))\n        star_file =  os.path.join(path, '{0}_info.txt'.format(sset))\n        if not os.path.isfile(star_file):\n            msgs.warn('File does not exist!: {0}'.format(star_file))\n            continue\n\n        star_tbl = table.Table.read(star_file, comment='#', format='ascii')\n        star_coords = coordinates.SkyCoord(star_tbl['RA_2000'], star_tbl['DEC_2000'],\n                                           unit=(units.hourangle, units.deg))\n        idx, d2d, d3d = coordinates.match_coordinates_sky(obj_coord, star_coords, nthneighbor=1)\n\n        if d2d < toler:\n            if check:\n                # Found one so return\n                return True\n\n            # Generate a dict\n            _idx = int(idx)\n            std_dict = dict(cal_file=os.path.join(path, star_tbl[_idx]['File']),\n                            name=star_tbl[_idx]['Name'],\n#                            std_ra=star_tbl[_idx]['RA_2000'],\n#                            std_dec=star_tbl[_idx]['DEC_2000'])\n                            # Force the coordinates to be decimal degrees\n                            std_ra=star_coords.ra[_idx].value,\n                            std_dec=star_coords.dec[_idx].value)\n\n            if not os.path.isfile(star_file):\n                # TODO: Error or warn?\n                msgs.error(\"No standard star file found: {:s}\".format(star_file))\n\n            # TODO: Does this need to be globbed? Why isn't the file\n            # name exact?\n            fil = glob.glob(std_dict['cal_file'] + '*')\n            if len(fil) == 0:\n                # TODO: Error or warn?\n                msgs.error(\"No standard star file: {:s}\".format(std_dict['cal_file']))\n\n            fil = fil[0]\n            msgs.info(\"Loading standard star file: {:s}\".format(fil))\n            # TODO: Put this stuf in a method, like `read_standard`\n            if sset == 'xshooter':\n                # TODO let's add the star_mag here and get a uniform set of tags in the std_dict\n                std_spec = table.Table.read(fil, format='ascii')\n                std_dict['std_source'] = sset\n                std_dict['wave'] = std_spec['col1'] * units.AA\n                std_dict['flux'] = std_spec['col2'] / PYPEIT_FLUX_SCALE * \\\n                                   units.erg / units.s / units.cm ** 2 / units.AA\n            elif sset == 'calspec':\n                std_dict['std_source'] = sset\n                std_spec = io.fits_open(fil)[1].data\n                std_dict['wave'] = std_spec['WAVELENGTH'] * units.AA\n                std_dict['flux'] = std_spec['FLUX'] / PYPEIT_FLUX_SCALE \\\n                                   * units.erg / units.s / units.cm ** 2 / units.AA\n            elif sset == 'esofil':\n                fil_basename = os.path.basename(fil)\n                if not fil_basename.startswith('f'):\n                    msgs.error(\"The ESO reference standard filename must start with the string `f`;  make sure it is the case. Also make sure that the flux units in the file are in 10**(-16) erg/s/cm2/AA.\")\n                # TODO let's add the star_mag here and get a uniform set of tags in the std_dict\n                std_spec = table.Table.read(fil, format='ascii')\n                std_dict['std_source'] = sset\n                std_dict['wave'] = std_spec['col1'] * units.AA\n                std_dict['flux'] = std_spec['col2']*1e-16/PYPEIT_FLUX_SCALE * \\\n                                   units.erg / units.s / units.cm ** 2 / units.AA\n                # At this low resolution, best to throw out entries affected by A and B-band absorption\n                mask = (std_dict['wave'].value > 7551.) & (std_dict['wave'].value < 7749.)\n                std_dict['wave'] = std_dict['wave'][np.logical_not(mask)]\n                std_dict['flux'] = std_dict['flux'][np.logical_not(mask)]\n            elif sset == 'noao': #mostly copied from 'esofil', need to convert the flux units\n                # TODO let's add the star_mag here and get a uniform set of tags in the std_dict\n                std_spec = table.Table.read(fil, format='ascii')\n                std_dict['std_source'] = sset\n                std_dict['wave'] = std_spec['col1'] * units.AA\n                std_dict['flux'] = mAB_to_cgs(std_spec['col2'],std_spec['col1']) / PYPEIT_FLUX_SCALE * \\\n                                   units.erg / units.s / units.cm ** 2 / units.AA\n                # At this low resolution, best to throw out entries affected by A and B-band absorption\n                mask = (std_dict['wave'].value > 7551.) & (std_dict['wave'].value < 7749.)\n                std_dict['wave'] = std_dict['wave'][np.logical_not(mask)]\n                std_dict['flux'] = std_dict['flux'][np.logical_not(mask)]\n            elif sset == 'blackbody':\n                # TODO let's add the star_mag here and get a uniform set of tags in the std_dict\n                waves, flam = blackbody_func(star_tbl[_idx]['a_x10m23'], star_tbl[_idx]['T_K'])\n                std_dict['std_source'] = sset\n                std_dict['wave'] = waves * units.AA\n                std_dict['flux'] = flam * units.erg / units.s / units.cm ** 2 / units.AA\n            else:\n                msgs.error('Do not know how to parse {0} file.'.format(sset))\n            msgs.info(\"Fluxes are flambda, normalized to 1e-17\")\n            return std_dict\n\n        # Save closest found so far\n        imind2d = np.argmin(d2d)\n        mind2d = d2d[imind2d]\n        if mind2d < closest['sep']:\n            closest['sep'] = mind2d\n            # TODO: Is this right? Do we need to use the imind2d from\n            # above?\n            _idx = int(idx)\n            closest.update(dict(name=star_tbl[_idx]['Name'],\n#                                ra=star_tbl[int(idx)]['RA_2000'],\n#                                dec=star_tbl[int(idx)]['DEC_2000']))\n                                # Force the coordinates to be decimal degrees\n                                std_ra=star_coords.ra[_idx].value,\n                                std_dec=star_coords.dec[_idx].value))\n\n    # Standard star not found\n    if check:\n        return False\n\n    msgs.error(\"No standard star was found within a tolerance of {:g}\".format(toler) + msgs.newline()\n               + \"Closest standard was {:s} at separation {:g}\".format(closest['name'], closest['sep'].to('arcmin')))\n\n    return None\n\ndef stellar_model(V, sptype):\n    \"\"\"\n    Parse Kurucz SED given T and g.  Also convert absolute/apparent\n    magnitudes\n\n    Parameters\n    ----------\n    V: float\n        Apparent magnitude of the telluric star\n    sptype: str\n        Spectral type of the telluric star\n\n    Returns\n    -------\n    loglam: `numpy.ndarray`_\n        log wavelengths\n    flux: `numpy.ndarray`_\n        SED f_lambda (cgs units, I think, probably per Ang)\n    \"\"\"\n\n    # Grab telluric star parameters\n    # log(g) of the Sun\n    logg_sol = np.log10(6.67259e-8) + np.log10(1.989e33) - 2.0 * np.log10(6.96e10)\n\n    # Load Schmidt-Kaler (1982) table\n    sk82_file = resource_filename('pypeit', 'data/standards/kurucz93/schmidt-kaler_table.txt')\n    sk82_tab = ascii.read(sk82_file, names=('Sp', 'logTeff', 'Teff', '(B-V)_0', 'M_V', 'B.C.', 'M_bol', 'L/L_sol'))\n\n    # TODO, currently this only works on select stellar types. Add ability to interpolate across types.\n    # Match input type.\n    mti = np.where(sptype == sk82_tab['Sp'])[0]\n    if len(mti) != 1:\n        raise ValueError('Not ready to interpolate yet.')\n\n    # Calculate final quantities\n    # Relation between radius, temp, and bolometric luminosity\n    logR = 0.2 * (42.26 - sk82_tab['M_bol'][mti[0]] - 10.0 * sk82_tab['logTeff'][mti[0]])\n\n    # Mass-bolometric luminosity relation from schimdt-kaler p28 valid for M_bol < 7.5\n    logM = 0.46 - 0.10 * sk82_tab['M_bol'][mti[0]]\n    logg = logM - 2.0 * logR + logg_sol\n    M_V = sk82_tab['M_V'][mti[0]]\n    Teff = sk82_tab['Teff'][mti[0]]\n\n    # Flux factor (absolute/apparent V mag)\n    # Define constants\n    parsec = constants.pc.cgs  # 3.086e18\n    R_sol = constants.R_sun.cgs  # 6.96e10\n\n    # Distance modulus\n    logd = 0.2 * (V - M_V) + 1.0\n    D = parsec * 10. ** logd\n    R = R_sol * 10. ** logR\n\n    # Factor converts the kurucz surface flux densities to flux observed on Earth\n    flux_factor = (R / D.value) ** 2\n\n    # Grab closest T in Kurucz SEDs\n    T1 = 3000. + np.arange(28) * 250\n    T2 = 10000. + np.arange(6) * 500\n    T3 = 13000. + np.arange(22) * 1000\n    T4 = 35000. + np.arange(7) * 2500\n    Tk = np.concatenate([T1, T2, T3, T4])\n    indT = np.argmin(np.abs(Tk - Teff))\n\n    # Grab closest g in Kurucz SEDs\n    loggk = np.arange(11) * 0.5\n    indg = np.argmin(np.abs(loggk - logg))\n\n    # Grab Kurucz filename\n    std_file = resource_filename('pypeit', '/data/standards/kurucz93/kp00/kp00_{:d}.fits.gz'.format(int(Tk[indT])))\n    std = table.Table.read(std_file)\n\n    # Grab specific spectrum\n    loglam = np.array(np.log10(std['WAVELENGTH']))\n    gdict = {0: 'g00', 1: 'g05', 2: 'g10', 3: 'g15', 4: 'g20',\n             5: 'g25', 6: 'g30', 7: 'g35', 8: 'g40', 9: 'g45',\n             10: 'g50'}\n    flux = std[gdict[indg]]\n\n    # scale the model to the V-band magnitude\n    star_lam = 10 ** loglam\n    star_flux = flux.data * flux_factor\n    # Generate a dict matching the output of find_standard_file\n    std_dict = dict(cal_file='KuruczTelluricModel', name=sptype, Vmag=V, std_ra=None, std_dec=None)\n    std_dict['std_source'] = 'KuruczTelluricModel'\n    std_dict['wave'] = star_lam * units.AA\n    std_dict['flux'] = star_flux / PYPEIT_FLUX_SCALE * units.erg / units.s / units.cm ** 2 / units.AA\n\n    return std_dict\n\n\ndef get_standard_spectrum(star_type=None, star_mag=None, ra=None, dec=None):\n    \"\"\"\n    Get the standard spetrum using given information of your standard/telluric star.\n\n    Args:\n        star_type (str):\n            Spectral type of your standard/telluric star\n        star_mag (float):\n            Apparent magnitude of the telluric star\n        ra (float):\n            Standard right-ascension in hh:mm:ss string format (e.g.,'05:06:36.6').\n        dec (float):\n            Object declination in dd:mm:ss string format (e.g., 52:52:01.0')\n\n    Returns:\n        dict: Dictionary containing the information you provided and the\n        standard/telluric spectrum.\n    \"\"\"\n    # Create star model\n    if (ra is not None) and (dec is not None) and (star_mag is None) and (star_type is None):\n        # Pull star spectral model from archive\n        msgs.info(\"Getting archival standard spectrum\")\n        # Grab closest standard within a tolerance\n        std_dict = find_standard_file(ra, dec)\n\n    elif (star_mag is not None) and (star_type is not None):\n        ## using vega spectrum\n        if 'A0' in star_type:\n            msgs.info('Getting vega spectrum')\n            ## Vega model from TSPECTOOL\n            vega_file = resource_filename('pypeit', '/data/standards/vega_tspectool_vacuum.dat')\n            vega_data = table.Table.read(vega_file, comment='#', format='ascii')\n            std_dict = dict(cal_file='vega_tspectool_vacuum', name=star_type, Vmag=star_mag,\n                            std_ra=ra, std_dec=dec)\n            std_dict['std_source'] = 'VEGA'\n            std_dict['wave'] = vega_data['col1'] * units.AA\n\n            # vega is V=0.03\n            std_dict['flux'] = vega_data['col2'] * 10**(0.4*(0.03-star_mag)) / PYPEIT_FLUX_SCALE * \\\n                               units.erg / units.s / units.cm ** 2 / units.AA\n        ## using Kurucz stellar model\n        else:\n            # Create star spectral model\n            msgs.info(\"Getting kurucz+93 stellar model\")\n            std_dict = stellar_model(star_mag, star_type)\n            std_dict['std_ra'] = ra\n            std_dict['std_dec'] = dec\n    else:\n        msgs.error('Insufficient information provided for fluxing. '\n                   'Either the coordinates of the standard or a stellar type and magnitude are needed.')\n\n    return std_dict\n\n\ndef load_extinction_data(longitude, latitude, toler=5. * units.deg):\n    \"\"\"\n    Find the best extinction file to use, based on longitude and latitude\n    Loads it and returns a Table\n\n    Parameters\n    ----------\n    longitude, latitude: Geocentric coordinates in degrees (floats).\n    toler : Angle, optional\n        Tolerance for matching detector to site (5 deg)\n\n    Returns\n    -------\n    ext_file : Table\n        astropy Table containing the 'wavelength', 'extinct' data for AM=1.\n    \"\"\"\n    # Mosaic coord\n    mosaic_coord = coordinates.SkyCoord(longitude, latitude, frame='gcrs', unit=units.deg)\n    # Read list\n    extinct_path = resource_filename('pypeit', '/data/extinction/')\n    extinct_summ = extinct_path + 'README'\n    extinct_files = table.Table.read(extinct_summ, comment='#', format='ascii')\n    # Coords\n    ext_coord = coordinates.SkyCoord(extinct_files['Lon'], extinct_files['Lat'], frame='gcrs',\n                                     unit=units.deg)\n    # Match\n    idx, d2d, d3d = coordinates.match_coordinates_sky(mosaic_coord, ext_coord, nthneighbor=1)\n    if d2d < toler:\n        extinct_file = extinct_files[int(idx)]['File']\n        msgs.info(\"Using {:s} for extinction corrections.\".format(extinct_file))\n    else:\n        msgs.warn(\"No file found for extinction corrections.  Applying none\")\n        msgs.warn(\"You should generate a site-specific file\")\n        return None\n    # Read\n    extinct = table.Table.read(extinct_path + extinct_file, comment='#', format='ascii',\n                               names=('iwave', 'mag_ext'))\n    wave = table.Column(np.array(extinct['iwave']) * units.AA, name='wave')\n    extinct.add_column(wave)\n    # Return\n    return extinct[['wave', 'mag_ext']]\n\ndef extinction_correction(wave, airmass, extinct):\n    \"\"\"\n    Derive extinction correction\n    Based on algorithm in LowRedux (long_extinct)\n\n    Parameters\n    ----------\n    wave (`numpy.ndarray`_):\n        Wavelengths for interpolation. Should be sorted.\n        Assumes angstroms.\n    airmass : float\n        Airmass\n    extinct : Table\n        Table of extinction values\n\n    Returns:\n    -------\n    `numpy.ndarray`_:\n        Multiplucative flux correction factors\n        at the input wavelengths.\n        i.e. true_flux = correction_factor*observed_flux\n\n    \"\"\"\n    # Checks\n    if airmass < 1.:\n        msgs.error(\"Bad airmass value in extinction_correction\")\n    # Interpolate\n    f_mag_ext = interpolate.interp1d(extinct['wave'], extinct['mag_ext'], bounds_error=False,\n                                     fill_value=0.)\n    mag_ext = f_mag_ext(wave)#.to('AA').value)\n\n    # Deal with outside wavelengths\n    gdv = np.where(mag_ext > 0.)[0]\n\n    if len(gdv) == 0:\n        msgs.warn(\"No valid extinction data available at this wavelength range. Extinction correction not applied\")\n    elif gdv[0] != 0:  # Low wavelengths\n        mag_ext[0:gdv[0]] = mag_ext[gdv[0]]\n        msgs.warn(\"Extrapolating at low wavelengths using last valid value\")\n    elif gdv[-1] != (mag_ext.size - 1):  # High wavelengths\n        mag_ext[gdv[-1] + 1:] = mag_ext[gdv[-1]]\n        msgs.warn(\"Extrapolating at high wavelengths using last valid value\")\n    else:\n        msgs.info(\"Extinction data covered the whole spectra. Applying correction...\")\n    # Evaluate\n    flux_corr = 10.0 ** (0.4 * mag_ext * airmass)\n    # Return\n    return flux_corr\n\n\n### Routines for standard sensfunc started from here\ndef find_standard(specobj_list):\n    \"\"\"\n    Take the median boxcar and then the max object as the standard\n\n    Parameters\n    ----------\n    specobj_list : list\n\n    Returns\n    -------\n    mxix : int\n        Index of the standard star\n\n    \"\"\"\n    # Repackage as necessary (some backwards compatability)\n    # Do it\n    medfx = []\n    for indx, spobj in enumerate(specobj_list):\n        if spobj is None:\n            medfx.append(0.)\n        else:\n            medfx.append(np.median(spobj.BOX_COUNTS))\n    try:\n        mxix = np.argmax(np.array(medfx))\n    except:\n        embed()\n    msgs.info(\"Putative standard star {} has a median boxcar count of {}\".format(specobj_list[mxix],\n                                                                                 np.max(medfx)))\n    # Return\n    return mxix\n\n#def apply_standard_sens(spec_obj, sens_dict, airmass, exptime, extinct_correct=True, telluric_correct = False,\n#                        longitude=None, latitude=None):\n#    \"\"\" Apply the sensitivity function to the data\n#    We also correct for extinction.\n#\n#    Parameters\n#    ----------\n#    spec_obj : dict\n#        SpecObj\n#    sens_dict : dict\n#        Sens Function dict\n#    airmass : float\n#        Airmass\n#    exptime : float\n#        Exposure time in seconds\n#    longitude : float\n#        longitude in degree for observatory\n#    latitude: float\n#        latitude in degree for observatory. Used for extinction\n#        correction\n#    \"\"\"\n\ndef sensfunc(wave, counts, counts_ivar, counts_mask, exptime, airmass, std_dict, longitude, latitude, ech_orders=None,\n             mask_abs_lines=True, polyorder=4, balm_mask_wid=10.0, nresln=20., resolution=3000.,\n             trans_thresh=0.9,polycorrect=True, polyfunc=False, debug=False):\n    \"\"\"\n    Function to generate the sensitivity function. This function fits\n    a bspline to the 2.5*log10(flux_std/flux_counts). The break\n    points spacing, which determines the scale of variation of the\n    sensitivity function is determined by the nresln parameter. This\n    code can work in different regimes, but NOTE THAT TELLURIC MODE\n    IS DEPRECATED, use telluric.sensfunc_telluric instead\n\n    Args:\n        wave (`numpy.ndarray`_):\n            Wavelength of the star. Shape (nspec,) or (nspec, norders)\n        counts (ndarray):\n            Flux (in counts) of the star. Shape (nspec,) or (nspec, norders)\n        counts_ivar (`numpy.ndarray`_):\n            Inverse variance of the star counts. Shape (nspec,) or (nspec, norders)\n        counts_mask (`numpy.ndarray`_):\n            Good pixel mask for the counts. Shape (nspec,) or (nspec, norders)\n        exptime (float):\n            Exposure time in seconds\n        airmass (float):\n            Airmass\n        std_dict (dict):\n            Dictionary containing information about the standard star returned by flux_calib.get_standard_spectrum\n        longitude (float):\n            Telescope longitude, used for extinction correction.\n        latitude (float):\n            Telescope latitude, used for extinction correction\n        ech_orders (int `numpy.ndarray`_):\n            If passed the echelle orders will be added to the meta_table. ech_orders must be a numpy array of integers\n            with the shape (norders,) giving the order numbers\n        mask_abs_lines (bool):\n            If True, mask stellar absorption lines before fitting sensitivity function. Default = True\n        balm_mask_wid (float):\n            Parameter describing the width of the mask for or stellar absorption lines (i.e. mask_abs_lines=True). A region\n            equal to balm_mask_wid*resln is masked where resln is the estimate for the spectral resolution in pixels\n            per resolution element.\n        polycorrect (bool):\n            Whether you want to interpolate the sensfunc with polynomial in the stellar absortion line regions before\n            fitting with the bspline\n        nresln (float):\n            Parameter governing the spacing of the bspline breakpoints. default = 20.0\n        resolution (float):\n            Expected resolution of the standard star spectrum. This should probably be determined from the grating, but is\n            currently hard wired. default=3000.0\n        trans_thresh (float):\n            Parameter for selecting telluric regions which are masked. Locations below this transmission value are masked.\n            If you have significant telluric absorption you should be using telluric.sensnfunc_telluric. default = 0.9\n\n    Returns:\n        Tuple: Returns:\n\n            - meta_table (astropy.Table) -- Table containing meta data\n              for the sensitivity function\n            - out_table (astropy.Table) -- Table containing the\n              sensitivity function\n\n    \"\"\"\n\n    wave_arr, counts_arr, ivar_arr, mask_arr, nspec, norders = utils.spec_atleast_2d(wave, counts, counts_ivar, counts_mask)\n    zeropoint_data = np.zeros_like(wave_arr)\n    zeropoint_data_gpm = np.zeros_like(wave_arr, dtype=bool)\n    zeropoint_fit = np.zeros_like(wave_arr)\n    zeropoint_fit_gpm = np.zeros_like(wave_arr, dtype=bool)\n    #mask_sens = np.ones_like(mask_arr)\n    wave_min = np.zeros(norders)\n    wave_max = np.zeros(norders)\n\n    for iord in range(norders):\n        zeropoint_data[:, iord], zeropoint_data_gpm[:, iord], zeropoint_fit[:, iord], zeropoint_fit_gpm[:, iord], = fit_zeropoint(\n            wave_arr[:,iord], counts_arr[:,iord], ivar_arr[:,iord], mask_arr[:,iord], exptime, airmass, std_dict,\n            longitude, latitude, mask_abs_lines=mask_abs_lines, polyorder=polyorder,\n            balm_mask_wid=balm_mask_wid, nresln=nresln, resolution=resolution, trans_thresh=trans_thresh,\n            polycorrect=polycorrect, polyfunc=polyfunc, debug=debug)\n        wave_min[iord] = wave_arr[wave_arr[:,iord] > 1.0, iord].min()\n        wave_max[iord] = wave_arr[wave_arr[:,iord] > 1.0, iord].max()\n\n    # Allocate the meta parameter table, ext=1\n    meta_table = table.Table(meta={'name': 'Parameter Values'})\n    meta_table['EXPTIME'] = [exptime]\n    meta_table['AIRMASS'] = [airmass]\n    meta_table['STD_RA'] = [std_dict['std_ra']]\n    meta_table['STD_DEC'] = [std_dict['std_dec']]\n    meta_table['STD_NAME'] = [std_dict['name']]\n    meta_table['CAL_FILE'] = [std_dict['cal_file']]\n    if ech_orders is not None:\n        meta_table['ECH_ORDERS'] = [ech_orders]\n    # Allocate the output table, ext=2\n    out_table = table.Table(meta={'name': 'Sensitivity Function'})\n    # These are transposed because we need to store them in an astropy table, with number of rows = norders\n    out_table['SENS_WAVE'] = wave_arr.T\n    out_table['SENS_COUNTS_PER_ANG'] = counts_arr.T\n    out_table['SENS_ZEROPOINT'] = zeropoint_data.T\n    out_table['SENS_ZEROPOINT_GPM'] = zeropoint_data_gpm.T\n    out_table['SENS_ZEROPOINT_FIT'] = zeropoint_fit.T\n    out_table['SENS_ZEROPOINT_FIT_GPM'] = zeropoint_fit_gpm.T\n    out_table['WAVE_MIN'] = wave_min\n    out_table['WAVE_MAX'] = wave_max\n\n    return meta_table, out_table\n\ndef get_sensfunc_factor(wave, wave_zp, zeropoint, exptime, tellmodel=None, extinct_correct=False,\n                         airmass=None, longitude=None, latitude=None, extrap_sens=False):\n    \"\"\"\n    Get the final sensitivity function factor that will be multiplied into a spectrum in units of counts to flux calibrate it.\n    This code interpolates the sensitivity function and can also multiply in extinction and telluric corrections.\n\n    FLAM, FLAM_SIG, and FLAM_IVAR are generated\n\n    Args:\n        wave (float `numpy.ndarray`_): shape = (nspec,)\n           Senstivity\n        wave_zp (float `numpy.ndarray`_):\n           Zerooint wavelength vector shape = (nsens,)\n        zeropoint (float `numpy.ndarray`_): shape = (nsens,)\n           Zeropoint, i.e. sensitivity function\n        exptime (float):\n        tellmodel (float  `numpy.ndarray`_, optional): shape = (nspec,)\n           Apply telluric correction if it is passed it. Note this is deprecated.\n        extinct_correct (bool, optional)\n           If True perform an extinction correction. Deafult = False\n        airmass (float, optional):\n           Airmass used if extinct_correct=True. This is required if extinct_correct=True\n        longitude (float, optional):\n            longitude in degree for observatory\n            Required for extinction correction\n        latitude:\n            latitude in degree for observatory\n            Required  for extinction correction\n        extrap_sens (bool, optional):\n            Extrapolate the sensitivity function (instead of crashing out)\n\n    Returns:\n        sensfunc_factor (`numpy.ndarray`_): shape = (nspec,)\n            This quantity is defined to be sensfunc_interp/exptime/delta_wave\n\n    \"\"\"\n\n    zeropoint_obs = np.zeros_like(wave)\n    wave_mask = wave > 1.0  # filter out masked regions or bad wavelengths\n    delta_wave = wvutils.get_delta_wave(wave, wave_mask)\n\n#    print(f'get_sensfunc_factor: {np.amin(wave_zp):.1f}, {np.amax(wave_zp):.1f}, '\n#          f'{np.amin(wave[wave_mask]):.1f}, {np.amax(wave[wave_mask]):.1f}')\n\n    try:\n        zeropoint_obs[wave_mask] \\\n                = interpolate.interp1d(wave_zp, zeropoint, bounds_error=True)(wave[wave_mask])\n    except ValueError:\n        if extrap_sens:\n            zeropoint_obs[wave_mask] \\\n                    = interpolate.interp1d(wave_zp, zeropoint, bounds_error=False)(wave[wave_mask])\n            msgs.warn(\"Your data extends beyond the bounds of your sensfunc. You should be \"\n                      \"adjusting the par['sensfunc']['extrap_blu'] and/or \"\n                      \"par['sensfunc']['extrap_red'] to extrapolate further and recreate your \"\n                      \"sensfunc. But we are extrapolating per your direction. Good luck!\")\n        else:\n            msgs.error(\"Your data extends beyond the bounds of your sensfunc. \" + msgs.newline() +\n                       \"Adjust the par['sensfunc']['extrap_blu'] and/or \"\n                       \"par['sensfunc']['extrap_red'] to extrapolate further and recreate \"\n                       \"your sensfunc.\")\n\n    # This is the S_lam factor required to convert N_lam = counts/sec/Ang to\n    # F_lam = 1e-17 erg/s/cm^2/Ang, i.e.  F_lam = S_lam*N_lam\n    sensfunc_obs = Nlam_to_Flam(wave, zeropoint_obs)\n\n    # TODO Telluric corrections via this method are deprecated\n    # Did the user request a telluric correction?\n    if tellmodel is not None:\n        # This assumes there is a separate telluric key in this dict.\n        msgs.info('Applying telluric correction')\n        sensfunc_obs = sensfunc_obs * (tellmodel > 1e-10) / (tellmodel + (tellmodel < 1e-10))\n\n\n    if extinct_correct:\n        if longitude is None or latitude is None:\n            msgs.error('You must specify longitude and latitude if we are extinction correcting')\n        # Apply Extinction if optical bands\n        msgs.info(\"Applying extinction correction\")\n        msgs.warn(\"Extinction correction applyed only if the spectra covers <10000Ang.\")\n        extinct = load_extinction_data(longitude, latitude)\n        ext_corr = extinction_correction(wave * units.AA, airmass, extinct)\n        senstot = sensfunc_obs * ext_corr\n    else:\n        senstot = sensfunc_obs.copy()\n\n    # senstot is the conversion from N_lam to F_lam, and the division by exptime and delta_wave are to convert\n    # the spectrum in counts/pixel into units of N_lam = counts/sec/angstrom\n    return senstot/exptime/delta_wave\n\n\n# JFH TODO This code needs to be cleaned up. The telluric option should probably be removed. Logic is not easy to follow.\ndef fit_zeropoint(wave, counts, counts_ivar, counts_mask, exptime, airmass, std_dict, longitude, latitude,\n                  mask_abs_lines=True, polyorder=4, balm_mask_wid=10.0, nresln=20., resolution=3000.,\n                  trans_thresh=0.9, polycorrect=True, polyfunc=False, debug=False):\n\n    \"\"\"\n\n    Function to generate the sensitivity function. This function fits\n    a bspline to the 2.5*log10(flux_std/flux_counts). The break\n    points spacing, which determines the scale of variation of the\n    sensitivity function is determined by the nresln parameter. This\n    code can work in different regimes, but NOTE THAT TELLURIC MODE\n    IS DEPRECATED, use telluric.sensfunc_telluric instead.\n\n        - If telluric=False, a sensfunc is generated by fitting a\n          bspline to the using nresln=20.0 and masking out telluric\n          regions.\n\n        - If telluric=True, sensfunc is a pixelized sensfunc (not\n          smooth) for correcting both throughput and telluric lines.\n          if you set polycorrect=True, the sensfunc in the Hydrogen\n          recombination line region (often seen in star spectra) will\n          be replaced by a smoothed polynomial function.\n\n    Args:\n        wave (`numpy.ndarray`_):\n            Wavelength of the star. Shape (nspec,)\n        counts (`numpy.ndarray`_):\n            Flux (in counts) of the star. Shape (nspec,)\n        counts_ivar (`numpy.ndarray`_):\n            Inverse variance of the star counts. Shape (nspec,)\n        counts_mask (`numpy.ndarray`_):\n            Good pixel mask for the counts.\n        exptime (float):\n            Exposure time in seconds\n        airmass (float):\n            Airmass\n        std_dict (dict):\n            Dictionary containing information about the standard star returned by flux_calib.get_standard_spectrum\n        longitude (float):\n            Telescope longitude, used for extinction correction.\n        latitude (float):\n            Telescope latitude, used for extinction correction\n        mask_abs_lines (bool):\n            If True, mask stellar absorption lines before fitting sensitivity function. Default = True\n        balm_mask_wid (float):\n            Parameter describing the width of the mask for or stellar absorption lines (i.e. mask_abs_lines=True). A region\n            equal to balm_mask_wid*resln is masked where resln is the estimate for the spectral resolution in pixels\n            per resolution element.\n        polycorrect: bool\n            Whether you want to interpolate the zeropoint with polynomial in the stellar absortion line regions before\n            fitting with the bspline\n        nresln (float):\n            Parameter governing the spacing of the bspline breakpoints. default = 20.0\n        resolution (float):\n            Expected resolution of the standard star spectrum. This should probably be determined from the grating, but is\n            currently hard wired. default=3000.0\n        trans_thresh (float):\n            Parameter for selecting telluric regions which are masked. Locations below this transmission value are masked.\n            If you have significant telluric absorption you should be using telluric.sensnfunc_telluric. default = 0.9\n\n    Returns:\n            zeropoint (`numpy.ndarray`_): Sensitivity function with same shape as wave (nspec,)\n            mask_sens (`numpy.ndarray`_): Good pixel mask for sensitivity function with same shape as wave (nspec,)\n\n    \"\"\"\n    # Create copy of the arrays to avoid modification and convert to\n    # Nlam = electrons/s/Angstrom\n    delta_wave = wvutils.get_delta_wave(wave, (wave > 1.0))\n    Nlam_star = counts/exptime/delta_wave\n    Nlam_ivar_star = delta_wave**2*counts_ivar*exptime**2\n\n    # Extinction correction\n    msgs.info(\"Applying extinction correction\")\n    extinct = load_extinction_data(longitude,latitude)\n    ext_corr = extinction_correction(wave * units.AA, airmass, extinct)\n    # Correct for extinction\n    Nlam_star = Nlam_star * ext_corr\n    Nlam_ivar_star = Nlam_ivar_star / ext_corr ** 2\n    gpm_star = counts_mask\n\n    # Interpolate the standard star onto the current set of observed wavelengths\n    flux_true = interpolate.interp1d(std_dict['wave'], std_dict['flux'], bounds_error=False,\n                                     fill_value='extrapolate')(wave)\n    # Do we need to extrapolate? TODO Replace with a model or a grey body?\n    ## TODO This is an ugly hack. Why are we only triggering this if the extrapolated star is negative.\n    if np.min(flux_true) <= 0.:\n        msgs.warn('Your spectrum extends beyond calibrated standard star, extrapolating the spectra with polynomial.')\n        mask_model = flux_true <= 0\n        pypeitFit = fitting.robust_fit(std_dict['wave'].value, std_dict['flux'].value,8,function='polynomial',\n                                                    maxiter=50, lower=3.0, upper=3.0, maxrej=3,\n                                                    grow=0, sticky=True, use_mad=True)\n        star_poly = pypeitFit.eval(wave)\n        #flux_true[mask_model] = star_poly[mask_model]\n        flux_true = star_poly.copy()\n        if debug:\n            plt.plot(std_dict['wave'], std_dict['flux'],'bo',label='Raw Star Model')\n            plt.plot(std_dict['wave'],  pypeitFit.eval(std_dict['wave'].value),\n                     'k-',label='robust_poly_fit')\n            plt.plot(wave,flux_true,'r-',label='Your Final Star Model used for sensfunc')\n            plt.show()\n\n    # Get masks from observed star spectrum. True = Good pixels\n    mask_bad, mask_balm, mask_tell = get_mask(wave, Nlam_star, Nlam_ivar_star, gpm_star, mask_abs_lines=mask_abs_lines,\n                                              mask_telluric=True, balm_mask_wid=balm_mask_wid, trans_thresh=trans_thresh)\n\n    # Get zeropoint\n    zeropoint_data, zeropoint_data_gpm, zeropoint_fit, zeropoint_fit_gpm = standard_zeropoint(\n        wave, Nlam_star, Nlam_ivar_star, mask_bad, flux_true, mask_balm=mask_balm,\n        mask_tell=mask_tell, maxiter=35, upper=3.0, lower=3.0, polyorder=polyorder,\n        balm_mask_wid=balm_mask_wid, nresln=nresln, resolution=resolution,\n        polycorrect=polycorrect, polyfunc=polyfunc, debug=debug, show_QA=False)\n\n    if debug:\n        sensfactor = Nlam_to_Flam(wave, zeropoint_fit)\n        plt.plot(wave[zeropoint_fit_gpm], flux_true[zeropoint_fit_gpm], color='k',lw=2, label='Reference Star')\n        plt.plot(wave[zeropoint_fit_gpm], Nlam_star[zeropoint_fit_gpm]*sensfactor[zeropoint_fit_gpm], color='r', label='Fluxed Observed Star')\n        plt.xlabel(r'Wavelength [$\\AA$]')\n        plt.ylabel('Flux [erg/s/cm2/Ang.]')\n        plt.legend(fancybox=True, shadow=True)\n        plt.show()\n\n\n    return zeropoint_data, zeropoint_data_gpm, zeropoint_fit, zeropoint_fit_gpm\n\n\n\n\ndef get_mask(wave_star,flux_star, ivar_star, mask_star, mask_abs_lines=True, mask_telluric=True, balm_mask_wid=10., trans_thresh=0.9):\n    '''\n    Get a couple of masks from your observed standard spectrum.\n\n    Args:\n      wave_star: numpy array\n        wavelength array of your spectrum\n      flux_star: numpy array\n        flux array of your spectrum\n      ivar_star:\n        ivar array of your spectrum\n      mask_star: bool\n        whether you need to mask Hydrogen recombination line region. If False, the returned msk_star are all good.\n      mask_tell: bool\n        whether you need to mask telluric region. If False, the returned msk_tell are all good.\n      trans_thresh: float\n        parameter for selecting telluric regions.\n\n    Returns:\n      msk_bad: bool type numpy array\n        mask for bad pixels.\n      msk_star: bool type numpy array\n        mask for recombination lines in star spectrum.\n      msk_tell: bool type numpy array\n        mask for telluric regions.\n    '''\n\n    # Mask (True = good pixels)\n    # mask for recombination lines\n    mask_balm = np.ones_like(flux_star).astype(bool)\n    # mask for telluric regions\n    mask_tell = np.ones_like(flux_star).astype(bool)\n\n    # masking bad entries\n    msgs.info(\" Masking bad pixels\")\n    mask_bad = mask_star.copy()\n    mask_bad[ivar_star <= 0.] = False\n    mask_bad[flux_star <= 0.] = False\n    # Mask edges\n    msgs.info(\" Masking edges\")\n    mask_bad[[0, -1]] = False\n    # Mask Atm. cutoff\n    msgs.info(\" Masking Below the atmospheric cutoff\")\n    atms_cutoff = wave_star <= 3000.0\n    mask_bad[atms_cutoff] = False\n\n    # TODO JFH replace with mask_star_lines from telluric.py\n    if mask_abs_lines:\n        # Mask Balmer, Paschen, Brackett, and Pfund recombination lines\n        msgs.info(\"Masking recombination lines:\")\n        # Mask Balmer\n        msgs.info(\" Masking Balmer\")\n        lines_balm = np.array([3836.4, 3969.6, 3890.1, 4102.8, 4102.8, 4341.6, 4862.7, 5407.0,\n                               6564.6, 8224.8, 8239.2])\n        for line_balm in lines_balm:\n            ibalm = np.abs(wave_star - line_balm) <= balm_mask_wid\n            mask_balm[ibalm] = False\n        # Mask Paschen\n        msgs.info(\" Masking Paschen\")\n        # air wavelengths from:\n        # https://www.subarutelescope.org/Science/Resources/lines/hi.html\n        lines_pasc = np.array([8203.6, 8440.3, 8469.6, 8504.8, 8547.7, 8600.8, 8667.4, 8752.9,\n                               8865.2, 9017.4, 9229.0, 9546.0, 10049.4, 10938.1,\n                               12818.1, 18751.0])\n        for line_pasc in lines_pasc:\n            ipasc = np.abs(wave_star - line_pasc) <= balm_mask_wid\n            mask_balm[ipasc] = False\n        # Mask Brackett\n        msgs.info(\" Masking Brackett\")\n        # air wavelengths from:\n        # https://www.subarutelescope.org/Science/Resources/lines/hi.html\n        lines_brac = np.array([14584.0, 18174.0, 19446.0, 21655.0,26252.0, 40512.0])\n        for line_brac in lines_brac:\n            ibrac = np.abs(wave_star - line_brac) <= balm_mask_wid\n            mask_balm[ibrac] = False\n        # Mask Pfund\n        msgs.info(\" Masking Pfund\")\n        # air wavelengths from:\n        # https://www.subarutelescope.org/Science/Resources/lines/hi.html\n        lines_pfund = np.array([22788.0, 32961.0, 37395.0, 46525.0,74578.0])\n        for line_pfund in lines_pfund:\n            ipfund = np.abs(wave_star - line_pfund) <= balm_mask_wid\n            mask_balm[ipfund] = False\n\n    if mask_telluric:\n        ## Mask telluric region in the optical\n        tell_opt = np.any([((wave_star >= 6270.00) & (wave_star <= 6290.00)), # H2O\n                       ((wave_star >= 6850.00) & (wave_star <= 6960.00)), #O2 telluric band\n                       ((wave_star >= 7580.00) & (wave_star <= 7750.00)), #O2 telluric band\n                       ((wave_star >= 7160.00) & (wave_star <= 7340.00)), #H2O\n                       ((wave_star >= 8150.00) & (wave_star <= 8250.00))],axis=0) #H2O\n        mask_tell[tell_opt] = False\n        ## Mask near-infrared telluric region\n        if np.max(wave_star)>9100.0:\n            # ToDo: should use the specific atmosphere transmission after FBD get the grid.\n            ## Read atmosphere transmission\n            #\n            #if watervp <1.5:\n            #    skytrans_file = resource_filename('pypeit', '/data/skisim/'+'mktrans_zm_10_10.dat')\n            #elif (watervp>=1.5 and watervp<2.3):\n            #    skytrans_file = resource_filename('pypeit', '/data/skisim/'+'mktrans_zm_16_10.dat')\n            #elif (watervp>=2.3 and watervp<4.0):\n            #    skytrans_file = resource_filename('pypeit', '/data/skisim/' + 'mktrans_zm_30_10.dat')\n            #else:\n            #    skytrans_file = resource_filename('pypeit', '/data/skisim/' + 'mktrans_zm_50_10.dat')\n            #\n            skytrans_file = resource_filename('pypeit', '/data/skisim/' + 'mktrans_zm_10_10.dat')\n            skytrans = ascii.read(skytrans_file)\n            wave_trans, trans = skytrans['wave'].data*10000.0, skytrans['trans'].data\n            trans_use = (wave_trans>=np.min(wave_star)-100.0) & (wave_trans<=np.max(wave_star)+100.0)\n            # Estimate the resolution of your spectra.\n            # I assumed 3 pixels per resolution. This gives an approximate right resolution at the middle point.\n            resolution = np.median(wave_star) / np.median(wave_star - np.roll(wave_star, 1)) / 3\n            trans_convolved, px_sigma, px_bin = conv2res(wave_trans[trans_use], trans[trans_use], resolution,\n                                                         central_wl='midpt', debug=False)\n            trans_final = interpolate.interp1d(wave_trans[trans_use], trans_convolved,\n                                               bounds_error=False,\n                                               fill_value='extrapolate')(wave_star)\n            tell_nir = (trans_final<trans_thresh) & (wave_star>9100.0)\n            mask_tell[tell_nir] = False\n        else:\n            msgs.info('Your spectrum is bluer than 9100A, only optical telluric regions are masked.')\n\n    return mask_bad, mask_balm, mask_tell\n\n\n# These are physical limits on the allowed values of the zeropoint in magnitudes\n\ndef Nlam_to_Flam(wave, zeropoint, zp_min=5.0, zp_max=30.0):\n    \"\"\"\n    The factor that when multiplied into N_lam converts to F_lam, i.e. S_lam where S_lam \\equiv F_lam/N_lam\n\n    Parameters\n    ----------\n    wave (`numpy.ndarray`_):\n       Wavelength vector for zeropoint\n    zeropoint (`numpy.ndarray`_):\n       zeropoint\n    zp_min (float, optional):\n       Minimum allowed value of the ZP. For smaller values the S_lam factor is set to zero\n    zp_max (float, optional):\n       Maximum allowed value of the ZP. For larger values the S_lam factor is set to zero\n\n    Returns\n    -------\n\n    \"\"\"\n    gpm = (wave > 1.0) & (zeropoint > zp_min) & (zeropoint < zp_max)\n    factor = np.zeros_like(wave)\n    factor[gpm] = np.power(10.0, -0.4*(zeropoint[gpm] - ZP_UNIT_CONST))/np.square(wave[gpm])\n    return factor\n\ndef Flam_to_Nlam(wave, zeropoint, zp_min=5.0, zp_max=30.0):\n    \"\"\"\n    The factor that when multiplied into F_lam converts to N_lam, i.e. 1/S_lam where S_lam \\equiv F_lam/N_lam\n\n\n    Parameters\n    ----------\n    wave (`numpy.ndarray`_):\n       Wavelength array, float, shape (nspec,)\n    zeropoint (`numpy.ndarray`_):\n       zeropoint array, float, shape (nspec,)\n\n    Returns:\n    --------\n    `numpy.ndarray`_:\n        Factor that when multiplied into F_lam converts to N_lam\n\n    \"\"\"\n    gpm = (wave > 1.0) & (zeropoint > zp_min) & (zeropoint < zp_max)\n    factor = np.zeros_like(wave)\n    factor[gpm] = np.power(10.0, 0.4*(zeropoint[gpm] - ZP_UNIT_CONST))*np.square(wave[gpm])\n    return factor\n\n\ndef compute_zeropoint(wave, N_lam, N_lam_gpm, flam_std_star, tellmodel=None):\n    \"\"\"\n    Routine to compute the zeropoint and zeropoint_gpm from the N_lam (counts/s/A) of a standard star\n\n\n    Parameters\n    ----------\n    wave (`numpy.ndarray`_):\n        Wavelength array, float, shape (nspec,)\n    N_lam (`numpy.ndarray`_):\n        N_lam spectrum of standard star, float, shape (nspec,)\n    N_lam_gpm (`numpy.ndarray`_):\n        N_lam mask, good pixel mask, boolean, shape (nspec,)\n    flam_std_star (`numpy.ndarray`_):\n        True standard star spectrum units set of PYPEIT_FLUX_SCALE erg/s/cm^2/sm/Angstrom\n    tellmodel (`numpy.ndarray`_):\n        Telluric absorption model, optional, shape (nspec,)\n\n    Returns:\n    --------\n    zeropoint (`numpy.ndarray`_):\n        Spectroscopic zeropoint, float, shape (nspec,)\n    zeropoint_gpm (`numpy.ndarray`_):\n        Zeropoint good pixel mask, bool, shape  (nspec,)\n    \"\"\"\n\n    tellmodel = np.ones_like(N_lam) if tellmodel is None else tellmodel\n    S_nu_dimless = np.square(wave)*tellmodel*flam_std_star*utils.inverse(N_lam)\n    zeropoint = -2.5*np.log10(S_nu_dimless + (S_nu_dimless <= 0.0)) + ZP_UNIT_CONST\n    zeropoint_gpm = N_lam_gpm & np.isfinite(zeropoint) & (N_lam > 0.0) & (S_nu_dimless > 0.0) & \\\n                    np.isfinite(flam_std_star) & (wave > 1.0)\n    return zeropoint, zeropoint_gpm\n\n#def throughput_from_sensfile(sensfile):\n#\n#    wave, zeropoint, meta_table, out_table, header_sens = sensfunc.SensFunc.load(sensfile)\n#    spectrograph = util.load_spectrograph(header_sens['PYP_SPEC'])\n#    throughput = zeropoint_to_thru(wave, zeropoint, spectrograph.telescope.eff_aperture())\n#    return wave, throughput\n\n\ndef zeropoint_to_throughput(wave, zeropoint, eff_aperture):\n    \"\"\"\n    Routine to compute the spectrograph throughput from the zeropoint and effective aperture.\n\n    Parameters\n    ----------\n    wave (`numpy.ndarray`_):\n         Wavelength array shape (nspec,) or (nspec, norders)\n    zeropoint (`numpy.ndarray`_):\n         Zeropoint array shape (nspec,) or (nspec, norders)\n    eff_aperture (float):\n         Effective aperture of the telescope in m^2. See spectrograph object\n\n    Returns\n    -------\n       throughput (`numpy.ndarray`_):\n           Throughput of the spectroscopic setup. Same shape as wave and zeropoint\n\n    \"\"\"\n\n    eff_aperture_m2 = eff_aperture*units.m**2\n    S_lam_units = 1e-17*units.erg/units.cm**2\n    # Set the throughput to be -1 in places where it is not defined.\n    throughput = np.full_like(zeropoint, -1.0)\n    zeropoint_gpm = (zeropoint > 5.0) & (zeropoint < 30.0) & (wave > 1.0)\n    inv_S_lam = Flam_to_Nlam(wave[zeropoint_gpm], zeropoint[zeropoint_gpm])/S_lam_units\n    inv_wave = utils.inverse(wave[zeropoint_gpm])/units.angstrom\n    thru = ((constants.h*constants.c)*inv_wave/eff_aperture_m2*inv_S_lam).decompose()\n    throughput[zeropoint_gpm] = thru\n    return throughput\n\n\ndef zeropoint_qa_plot(wave, zeropoint_data, zeropoint_data_gpm, zeropoint_fit, zeropoint_fit_gpm, title='Zeropoint QA', axis=None, show=False):\n    \"\"\"\n    QA plot for zeropoint plotting\n\n    Parameters\n    ----------\n    wave\n    zeropoint_data\n    zeropoint_data_gpm\n    zeropoint_fit\n    zeropoint_fit_gpm\n    title\n    order\n    axis\n    show\n\n    Returns\n    -------\n\n    \"\"\"\n\n    wv_gpm = wave > 1.0\n    if axis is None:\n        plt.close()\n        fig = plt.figure(figsize=(12,8))\n        axis = fig.add_axes([0.1, 0.1, 0.8, 0.8])\n\n    rejmask = zeropoint_data_gpm[wv_gpm] & np.logical_not(zeropoint_fit_gpm[wv_gpm])\n    axis.plot(wave[wv_gpm], zeropoint_data[wv_gpm], label='Zeropoint estimated', drawstyle='steps-mid', color='k', alpha=0.7, zorder=5, linewidth=1.0)\n    axis.plot(wave[wv_gpm], zeropoint_fit[wv_gpm], label='Zeropoint fit', color='red', linewidth=2.0, zorder=7, alpha=0.7)\n    axis.plot(wave[wv_gpm][rejmask], zeropoint_data[wv_gpm][rejmask], 's', zorder=10, mfc='None', mec='blue', mew=0.7, label='rejected pixels')\n    axis.plot(wave[wv_gpm][np.logical_not(zeropoint_data_gpm[wv_gpm])], zeropoint_data[wv_gpm][np.logical_not(zeropoint_data_gpm[wv_gpm])], 'v',\n             zorder=9, mfc='None', mec='orange', mew=0.7, label='originally masked')\n    med_filt_mask = zeropoint_data_gpm[wv_gpm] & np.isfinite(zeropoint_data[wv_gpm])\n    zp_med_filter = utils.fast_running_median(zeropoint_data[wv_gpm][med_filt_mask], 11)\n    axis.set_ylim(0.95 * zp_med_filter.min(), 1.05 * zp_med_filter.max())\n    axis.legend()\n    axis.set_xlabel('Wavelength')\n    axis.set_ylabel('Zeropoint (AB mag)')\n    axis.set_title(title, fontsize=12)\n    if show:\n        plt.show()\n\n\ndef standard_zeropoint(wave, Nlam, Nlam_ivar, Nlam_gpm, flam_true, mask_balm=None, mask_tell=None,\n                       maxiter=35, upper=3.0, lower=3.0, func = 'polynomial', polyorder=5, balm_mask_wid=50.,\n                       nresln=20., resolution=2700., polycorrect=True, debug=False, polyfunc=False, show_QA=False):\n    \"\"\"\n    Generate a sensitivity function based on observed flux and standard spectrum.\n\n    Parameters\n    ----------\n    wave : `numpy.ndarray`_\n      wavelength as observed\n    Nlam : `numpy.ndarray`_\n      counts/s/Angstrom as observed\n    Nlam_ivar : `numpy.ndarray`_\n      inverse variance of counts/s/Angstrom\n    flam_true : Quantity array\n      standard star true flux (erg/s/cm^2/A)\n    msk_bad : `numpy.ndarray`_\n      mask for bad pixels. True is good.\n    msk_star: `numpy.ndarray`_\n      mask for hydrogen recombination lines. True is good.\n    msk_tell: `numpy.ndarray`_\n      mask for telluric regions. True is good.\n    maxiter : integer\n      maximum number of iterations for polynomial fit\n    upper : integer\n      number of sigma for rejection in polynomial\n    lower : integer\n      number of sigma for rejection in polynomial\n    polyorder : integer\n      order of polynomial fit\n    balm_mask_wid: float\n      in units of angstrom\n      Mask parameter for Balmer absorption. A region equal to\n      balm_mask_wid is masked.\n    resolution: integer/float.\n      spectra resolution\n      This paramters should be removed in the future. The resolution should be estimated from spectra directly.\n    debug : bool\n      if True shows some dubugging plots\n\n    Returns\n    -------\n    zeropoint ( `numpy.ndarray`_):\n      Spectroscopic zeropoint.\n    \"\"\"\n    if np.any(np.invert(np.isfinite(Nlam_ivar))):\n        msgs.warn(\"NaN are present in the inverse variance\")\n\n    # check masks\n    if mask_tell is None:\n        mask_tell = np.ones_like(wave,dtype=bool)\n    if mask_balm is None:\n        mask_balm = np.ones_like(wave, dtype=bool)\n\n    #S_nu_dimless = np.square(wave)*flam_true*utils.inverse(Nlam)*(Nlam > 0.0)\n    #zeropoint_data = -2.5*np.log10(S_nu_dimless) + telluric.zp_unit_const()\n    # zeropoint_gpm is the pixels for which zp is not defined, zeropoint_fitmask includes additional Balmer/Telluric masking for polyfit\n    #zeropoint_gpm = Nlam_gpm & np.isfinite(zeropoint_data) & (Nlam > 0.0) & np.isfinite(flam_true) & (wave > 1.0)\n    zeropoint_data, zeropoint_data_gpm = compute_zeropoint(wave, Nlam, Nlam_gpm, flam_true)\n\n\n    zeropoint_fitmask = zeropoint_data_gpm & mask_tell & mask_balm\n    wave_min = wave[wave > 1.0].min()\n    wave_max = wave[wave > 1.0].max()\n\n    pypeitFit = fitting.robust_fit(wave, zeropoint_data, polyorder, function=func,\n                                minx=wave_min, maxx=wave_max, in_gpm=zeropoint_fitmask,\n                                lower=lower, upper=upper, groupbadpix=False,\n                                grow=0, sticky=True, use_mad=True)\n\n    zeropoint_poly = pypeitFit.eval(wave)\n    # Robustly characterize the stanarad deviation for the b-spline fitting.\n    zp_dev_mean, zp_dev_median, zp_std = stats.sigma_clipped_stats(zeropoint_data - zeropoint_poly, np.invert(zeropoint_fitmask),\n                                                                   cenfunc='median', stdfunc=utils.nan_mad_std,\n                                                                   maxiters=10, sigma_lower=lower, sigma_upper=upper)\n    zeropoint_ivar = np.ones_like(zeropoint_data)/zp_std**2\n\n    ZP_MAX = 40.0\n    ZP_MIN = 5.0\n\n    zeropoint_clean = zeropoint_data.copy()\n    zeropoint_clean_gpm = zeropoint_data_gpm.copy()\n    # Polynomial corrections on Hydrogen Recombination lines\n    if ((np.sum(zeropoint_fitmask) > 0.5 * len(zeropoint_fitmask)) & polycorrect):\n        ## Only correct Hydrogen Recombination lines with polyfit in the telluric free region\n        balmer_clean = np.zeros_like(wave, dtype=bool)\n        # Commented out the bluest recombination lines since they are weak for spectroscopic standard stars.\n        #836.4, 3969.6, 3890.1, 4102.8, 4102.8, 4341.6, 4862.7,   \\\n        lines_hydrogen = np.array([5407.0, 6564.6, 8224.8, 8239.2, 8203.6, 8440.3, 8469.6, 8504.8, 8547.7, 8600.8, \\\n                                   8667.4, 8752.9, 8865.2, 9017.4, 9229.0, 10049.4, 10938.1, 12818.1, 21655.0])\n        for line_hydrogen in lines_hydrogen:\n            ihydrogen = np.abs(wave - line_hydrogen) <= balm_mask_wid\n            balmer_clean[ihydrogen] = True\n        # Clean pixels which hit Balmer lines or which have the zeropoint_data outside the min/max range\n        # AND have polynomial values inside the min/max range\n        msk_clean = ((balmer_clean) | (zeropoint_clean > ZP_MAX) | (zeropoint_clean < ZP_MIN)) & \\\n                    (zeropoint_poly > ZP_MIN) & (zeropoint_poly < ZP_MAX)\n        zeropoint_clean[msk_clean] = zeropoint_poly[msk_clean]\n        gpm = np.isfinite(Nlam_ivar) & (Nlam_ivar > 0)\n        zeropoint_clean[np.invert(gpm)] = zeropoint_poly[np.invert(gpm)]\n    else:\n        ## if half more than half of your spectrum is masked (or polycorrect=False) then do not correct it with polyfit\n        msgs.warn('No polynomial corrections performed on Hydrogen Recombination line regions')\n\n    # ToDo\n    # Compute an effective resolution for the standard. This could be improved\n    # to setup an array of breakpoints based on the resolution. At the\n    # moment we are using only one number\n    msgs.work(\"Should pull resolution from arc line analysis\")\n    msgs.work(\"At the moment the resolution is taken as the PixelScale\")\n    msgs.work(\"This needs to be changed!\")\n    std_pix = np.median(np.abs(wave - np.roll(wave, 1)))\n    std_res = np.median(wave/resolution) # median resolution in units of Angstrom.\n    if (nresln * std_res) < std_pix:\n        msgs.warn(\"Bspline breakpoints spacing shoud be larger than 1pixel\")\n        msgs.warn(\"Changing input nresln to fix this\")\n        nresln = std_res / std_pix\n\n    # Fit zeropoint with bspline\n    kwargs_bspline = {'bkspace': std_res * nresln}\n    kwargs_reject = {'maxrej': 5}\n    msgs.info(\"Initialize bspline for flux calibration\")\n    init_bspline = bspline.bspline(wave, bkspace=kwargs_bspline['bkspace'])\n    fullbkpt = init_bspline.breakpoints\n\n    # remove masked regions from breakpoints\n    msk_bkpt = interpolate.interp1d(wave, zeropoint_clean_gpm, kind='nearest', fill_value='extrapolate')(fullbkpt)\n    init_breakpoints = fullbkpt[msk_bkpt > 0.999]\n\n    # init_breakpoints = fullbkpt\n    msgs.info(\"Bspline fit on zeropoint. \")\n    bset1, bmask = fitting.iterfit(wave, zeropoint_clean, invvar=zeropoint_ivar, inmask=zeropoint_fitmask, upper=upper, lower=lower,\n                                fullbkpt=init_breakpoints, maxiter=maxiter, kwargs_bspline=kwargs_bspline,\n                                kwargs_reject=kwargs_reject)\n    zeropoint_bspl, zeropoint_fit_gpm = bset1.value(wave)\n    zeropoint_bspl_bkpt, _ = bset1.value(init_breakpoints)\n\n    if debug:\n        # Check for calibration\n        plt.figure(1)\n        plt.plot(wave, zeropoint_data, drawstyle='steps-mid', color='black', label='Zeropoint Data')\n        plt.plot(wave, zeropoint_bspl, color='cornflowerblue', label='Bspline fit')\n        plt.plot(wave[np.invert(zeropoint_fitmask)], zeropoint_data[np.invert(zeropoint_fitmask)], '+', color='red', markersize=5.0,\n                 label='masked zeropoint')\n        plt.plot(wave[np.invert(zeropoint_fitmask)], zeropoint_bspl[np.invert(zeropoint_fitmask)], '+', color='red', markersize=5.0,\n                 label='masked zeropoint_bspl_fit')\n        plt.plot(init_breakpoints, zeropoint_bspl_bkpt, '.', color='green', markersize=4.0, label='breakpoints')\n        plt.plot(init_breakpoints, np.interp(init_breakpoints, wave, zeropoint_data), '.', color='green',\n                 markersize=4.0,\n                 label='data interpolated onto breakpoints')\n        plt.plot(wave, 1.0 / np.sqrt(zeropoint_ivar), color='orange', label='sigma used for fits')\n        plt.legend()\n        plt.xlabel('Wavelength [ang]')\n        med_filt_mask = zeropoint_data_gpm & np.isfinite(zeropoint_data)\n        zp_med_filter = utils.fast_running_median(zeropoint_data[med_filt_mask], 11)\n        plt.ylim(0.95 * zp_med_filter.min(), 1.05 * zp_med_filter.max())\n        plt.title('Bspline fit')\n        plt.show()\n\n    if ((np.sum(zeropoint_fitmask) > 0.5 * len(zeropoint_fitmask)) & polycorrect):\n        msk_clean = ((balmer_clean) | (zeropoint_data > ZP_MAX) | (zeropoint_data < ZP_MIN)) & \\\n                    (zeropoint_poly > ZP_MIN) & (zeropoint_poly < ZP_MAX)\n        zeropoint_bspl_clean = zeropoint_bspl.copy()\n        zeropoint_bspl_clean[msk_clean] = zeropoint_poly[msk_clean]\n        msk_badpix = np.isfinite(Nlam_ivar) & (Nlam_ivar>0)\n        zeropoint_bspl_clean[np.invert(msk_badpix)] = zeropoint_poly[np.invert(msk_badpix)]\n    else:\n        ## if half more than half of your spectrum is masked (or polycorrect=False) then do not correct it with polyfit\n        zeropoint_bspl_clean = zeropoint_bspl.copy()\n        msgs.warn('No polynomial corrections performed on Hydrogen Recombination line regions')\n\n    # Calculate zeropoint\n    zeropoint_fit = zeropoint_poly if polyfunc else zeropoint_bspl_clean\n\n\n    # TODO Should we return the bspline fitmask here?\n    return zeropoint_data, zeropoint_data_gpm, zeropoint_fit, zeropoint_fit_gpm\n\ndef load_filter_file(filter):\n    \"\"\"\n    Load a system response curve for a given filter\n\n    Args:\n        filter (str): Name of filter\n\n    Returns:\n        `numpy.ndarray`_: wavelength, instrument throughput\n\n\n    # Optical filters\n    BASS_MZLS_filters = ['BASS-MZLS-{}'.format(i) for i in ['G', 'R','Z']]\n    CFHT_filters = ['CFHT-{}'.format(i) for i in ['U', 'G', 'R', 'I', 'Z']]\n    DECAM_filters = ['DECAM-{}'.format(i) for i in ['U', 'G', 'R', 'I', 'Z', 'Y']]\n    HSC_filters = ['HSC-{}'.format(i) for i in ['G', 'R', 'I', 'Z', 'Y']]\n    LSST_filters = ['LSST-{}'.format(i) for i in ['U', 'G', 'R', 'I', 'Z', 'Y']]\n    PS1_filters = ['PS1-{}'.format(i) for i in ['G', 'R', 'I', 'Z', 'Y']]\n    SDSS_filters = ['SDSS-{}'.format(i) for i in ['U', 'G', 'R', 'I', 'Z']]\n\n    # NIR filters\n    UKIDSS_filters = ['UKIRT-{}'.format(i) for i in ['Y', 'J', 'H', 'K']]\n    VISTA_filters = ['VISTA-{}'.format(i) for i in ['Z', 'Y', 'J', 'H', 'K']]\n    TMASS_filters = ['TMASS-{}'.format(i) for i in ['J', 'H', 'K']]\n\n    # Other filters\n    GAIA_filters = ['GAIA-{}'.format(i) for i in ['G', 'B', 'R']]\n    GALEX_filters = ['GALEX-{}'.format(i) for i in ['F', 'N']]\n    WISE_filters = ['WISE-{}'.format(i) for i in ['W1', 'W2', 'W3', 'W4']]\n\n    allowed_options = BASS_MZLS_filters + CFHT_filters + DECAM_filters + HSC_filters \\\n                      + LSST_filters + PS1_filters + SDSS_filters + UKIDSS_filters\\\n                      + VISTA_filters + TMASS_filters + GAIA_filters + GALEX_filters + WISE_filters\n    \"\"\"\n\n    filter_file = resource_filename('pypeit', os.path.join('data', 'filters', 'filter_list.ascii'))\n    tbl = table.Table.read(filter_file, format='ascii')\n\n    allowed_options = tbl['filter'].data\n\n    # Check\n    if filter not in allowed_options:\n        msgs.error(\"PypeIt is not ready for filter = {}\".format(filter))\n\n    trans_file = resource_filename('pypeit', os.path.join('data', 'filters', 'filtercurves.fits'))\n    trans = io.fits_open(trans_file)\n    wave = trans[filter].data['lam']  # Angstroms\n    instr = trans[filter].data['Rlam']  # Am keeping in atmospheric terms\n    keep = instr > 0.\n    # Parse\n    wave = wave[keep]\n    instr = instr[keep]\n\n    # Return\n    return wave, instr\n\n# TODO Replace this stuff wth calls to the astropy speclite package.\ndef scale_in_filter(wave, flux, gpm, scale_dict):\n    \"\"\"\n    Scale spectra to input magnitude in given filter\n\n    scale_dict has data model:\n      - 'filter' (str): name of filter\n      - 'mag' (float): magnitude\n      - 'mag_type' (str, optional): type of magnitude.  Assumed 'AB'\n      - 'masks' (list, optional): Wavelength ranges to mask in calculation\n\n    Args:\n        wave (`numpy.ndarray`_):\n        flux (`numpy.ndarray`_):\n        gpm (`numpy.ndarray`_):\n            True is good\n        scale_dict (dict like):\n            Usually is a Coadd1DPar() object\n            Requires mag_type, filter, filter_mag, and filter_mask\n\n    Returns:\n        float: scale value for the flux, i.e. newflux = flux * scale\n    \"\"\"\n\n    # Mask further?\n    if scale_dict['filter_mask'] is not None:\n        # Funny formatting\n        if isinstance(scale_dict['filter_mask'], str):\n            regions = scale_dict['filter_mask'].split(',')\n        else:\n            regions = scale_dict['filter_mask']\n        for region in regions:\n            mask = region.split(':')\n            gpm[(wave > float(mask[0])) & (wave < float(mask[1]))] = False\n    mag_type = scale_dict['mag_type']\n\n    # Parse the spectrum\n    wave = wave[gpm]\n    flux = flux[gpm]\n\n    # Grab the instrument response function\n    msgs.info(\"Integrating spectrum in filter: {}\".format(scale_dict['filter']))\n    fwave, trans = load_filter_file(scale_dict['filter'])\n    tfunc = interpolate.interp1d(fwave, trans, bounds_error=False, fill_value=0.)\n\n    # TODO this expression below is incorrect for irregular gridded wavelengths. FIX\n    # Convolve\n    allt = tfunc(wave)\n    wflam = np.sum(flux*allt)/np.sum(allt)* PYPEIT_FLUX_SCALE*units.erg/units.s/units.cm**2/units.AA\n\n    mean_wv = np.sum(fwave*trans)/np.sum(trans) * units.AA\n\n    #\n    if mag_type == 'AB':\n        # Convert flam to AB magnitude\n        fnu = wflam * mean_wv**2 / constants.c\n        # Apparent AB\n        AB = -2.5 * np.log10(fnu.to('erg/s/cm**2/Hz').value) - 48.6\n        # Scale factor\n        Dm = AB - scale_dict['filter_mag']\n        scale = np.power(10.0,(Dm/2.5))\n        msgs.info(\"Scaling spectrum by {}\".format(scale))\n    else:\n        msgs.error(\"Bad magnitude type\")\n\n    return scale\n\n", "meta": {"hexsha": "3daa65a24180d713f05fb350962759a1e4bec6f2", "size": 63898, "ext": "py", "lang": "Python", "max_stars_repo_path": "pypeit/core/flux_calib.py", "max_stars_repo_name": "brackham/PypeIt", "max_stars_repo_head_hexsha": "8769f06ae8e8f18d3a55d12b01dd3dde50b98040", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 107, "max_stars_repo_stars_event_min_datetime": "2018-08-06T07:07:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T14:33:42.000Z", "max_issues_repo_path": "pypeit/core/flux_calib.py", "max_issues_repo_name": "brackham/PypeIt", "max_issues_repo_head_hexsha": "8769f06ae8e8f18d3a55d12b01dd3dde50b98040", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 889, "max_issues_repo_issues_event_min_datetime": "2018-07-26T12:14:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T22:49:42.000Z", "max_forks_repo_path": "pypeit/core/flux_calib.py", "max_forks_repo_name": "brackham/PypeIt", "max_forks_repo_head_hexsha": "8769f06ae8e8f18d3a55d12b01dd3dde50b98040", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 74, "max_forks_repo_forks_event_min_datetime": "2018-09-25T17:03:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T23:59:24.000Z", "avg_line_length": 43.9766001376, "max_line_length": 206, "alphanum_fraction": 0.6362953457, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 17245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.33807713748839185, "lm_q1q2_score": 0.18221790440436644}}
{"text": "#! /usr/bin/env python\n\n\"\"\"\nby A. Greenbaum & A. Sivaramakrishnan \nApril 2016 agreenba@pha.jhu.edu\n\nContains \n\nFringeFitter - fit fringe phases and amplitudes to data in the image plane\n\nCalibrate - Calibrate target data with calibrator data\n\nBinaryAnalyze - Detection, mcmc modeling, visualization tools\n                Much of this section is based on tools in the pymask code\n                by F. Martinache, B. Pope, and A. Cheetham\n                We especially thank A. Cheetham for help and advising for\n                developing the analysis tools in this package. \n\n    LG++ anand@stsci.edu nrm_core changes:\n        Removed use of 'centering' parameter, switch to psf_offsets, meant to be uniformly ds9-compatible \n        offsets from array center (regardless of even/odd array sizes).\n\n            nrm_core.fit_image(): refslice UNTESTED w/ new utils.centroid()\n            nrm_core.fit_image(): hold_centering UNTESTED w/ new utils.centroid()\n\n\"\"\"\n\n\nfrom __future__ import print_function\n# Standard imports\nimport os, sys, time\nimport numpy as np\nfrom astropy.io import fits\nfrom scipy.special import comb\nfrom scipy.stats import sem, mstats\nimport pickle as pickle\nimport matplotlib.pyplot as plt\n\n\n# Module imports\nfrom nrm_analysis.fringefitting.LG_Model import NRM_Model\nfrom nrm_analysis.misctools import utils  # AS LG++\nfrom nrm_analysis.misctools import implane2oifits \nfrom nrm_analysis.modeling.binarymodel import model_cp_uv, model_allvis_uv, model_v2_uv, model_t3amp_uv\nfrom nrm_analysis.modeling.multimodel import model_bispec_uv\n\nfrom multiprocessing import Pool\n\nclass FringeFitter:\n    def __init__(self, instrument_data, **kwargs):\n        \"\"\"\n        Fit fringes in the image plane\n\n        Takes an instance of the appropriate instrument class\n        Various options can be set\n\n        kwarg options:\n        weighted - least squares fit uses weighting by 1 / photon noise variance\n        oversample - model oversampling (also how fine to measure the centering)\n        psf_offset - If you already know the subpixel centering of your data, \n                     give it here (not recommended except when debugging with\n                     perfectly known image placement))\n        oitdir - Where text observables, derived fits files will get saved.  No default.\n        oifdir - Where raw oifits files will get saved.  No default.\n        npix - How many pixels of your data do you want to use? \n               Default is the shape of a data [slice or frame].  Typically odd?\n        debug - will plot the FT of your data next to the FT of a reference PSF.\n                Needs poppy package to run\n        verbose_save - saves more than the standard files\n        interactive - default True, prompts user to overwrite/create directory.  \n                      False will overwrite files where necessary.\n        find_rotation - will find the best pupil rotation that matches the data\n        verbose - T/F\n\n        main method:\n        * fit_fringes\n\n\n        \"\"\"\n        self.instrument_data = instrument_data\n\n        #######################################################################\n        # Options\n        # setting a default oversample value\n        # - fast, not necessarily  the most accurate... \n        # ok to ~1e-3 binary contrast (given other systematic limits, 2021 end)??\n        self.weighted = False\n        if \"weighted\" in kwargs:\n            self.weighted = kwargs[\"weighted\"]\n\n        self.oversample = 3  \n        if \"oversample\" in kwargs:\n            self.oversample = kwargs[\"oversample\"]\n\n        self.find_rotation = False\n        if \"find_rotation\" in kwargs:\n            # can be True/False or 1/0\n            self.find_rotation = kwargs[\"find_rotation\"]\n\n        self.psf_offset_ff = None #find center of image in data\n        if \"psf_offset_ff\" in kwargs: # if so do not find center of image in data\n            self.psf_offset_ff = kwargs[\"psf_offset_ff\"]         \n\n        ###############################\n        # restructured output directories, with backward compatibility\n        #\n        # write OI text files here, [diagnostic images fits]. Was 'savedir'\n        if \"oitdir\" in kwargs:\n            self.oitdir = kwargs[\"oitdir\"]\n        elif 'savedir' in kwargs:\n            self.oitdir = kwargs[\"savedir\"]\n            print(\"nrm_core.FringeFitter: savedir deprecated but will be used for oitdir variable.\")\n        else:\n            sys.exit(\"FringeFitter: Fatal: no oitdir (or deprecated savedir) specified.\")\n\n        if self.oitdir[-1] != '/': self.oitdir = self.oitdir + '/'\n\n        if \"oifdir\" in kwargs:  # write OIFITS files here.  New parameter 2021/05\n            self.oifdir = kwargs[\"oifdir\"]\n        elif 'savedir' in kwargs:\n            self.oifdir = kwargs[\"savedir\"]\n            print(\"nrm_core.FringeFitter: savedir deprecated, but oifdir wil be set to savedir\")\n            print(\"nrm_core.FringeFitter: new drivers should initialize with oifdir\")\n        else:\n            sys.exit(\"FringeFitter: Fatal: no oifdir / deprecated savedir) specified.\")\n        if self.oifdir[-1] != '/': self.oifdir = self.oifdir + '/'\n        #\n        ###############################\n\n        self.npix = 'default'\n        if \"npix\" in kwargs:\n            self.npix = kwargs[\"npix\"]\n\n        self.debug=False\n        if \"debug\" in kwargs:\n            self.debug=kwargs[\"debug\"]\n\n        self.verbose_save = False\n        if \"verbose_save\" in kwargs:\n            self.verbose_save = kwargs[\"verbose_save\"]\n\n        self.interactive = True\n        if 'interactive' in kwargs:\n            self.interactive = kwargs['interactive']\n\n        self.save_txt_only = False\n        if \"save_txt_only\" in kwargs:\n            self.save_txt_only = kwargs[\"save_txt_only\"]\n\n        self.verbose = False\n        if \"verbose\" in kwargs:\n            self.verbose = kwargs[\"verbose\"]\n        #######################################################################\n\n\n        #######################################################################\n        # Create OI text & oifits directories if they don't already exist\n        try:\n            os.makedirs(self.oitdir)\n        except:\n            if self.interactive is True:\n                print(self.oitdir+\" Already exists, rewrite its contents? (y/n)\")\n                ans = input()\n                if ans == \"y\":\n                    pass\n                elif ans == \"n\":\n                    sys.exit(\"use alternative save directory with kwarg 'oitdir' when calling FringeFitter\")\n                else:\n                    sys.exit(\"Invalid answer. Stopping.\")\n            else:\n                pass\n        try:\n            os.makedirs(self.oifdir)\n        except FileExistsError:\n            pass\n\n    ###\n    # May 2017 J Sahlmann updates: parallelized fringe-fitting\n    # Feb 2021 Dec 2021 anand added dqmask to fringe fitting, removed bpdata use\n    ###\n\n    def fit_fringes(self, fns, threads = 0):\n        if type(fns) == str:\n            fns = [fns, ]\n\n        # Can get fringes for images in parallel\n        store_dict = [{\"object\":self, \"file\":fn,\"id\":jj} \\\n                        for jj,fn in enumerate(fns)]\n\n        t2 = time.time()\n        for jj, fn in enumerate(fns):\n            fit_fringes_parallel({\"object\":self, \"file\":fn,\\\n                                  \"id\":jj}, threads)\n        t3 = time.time()\n        print(\"Parallel with {0} threads took {1:.2f}s to fit all fringes\".format(\\\n               threads, t3-t2))\n        # If a JWST file name, strip the 'calints' suffix from it\n        # if it doesn't contain '_calints' nothing will happen\n        oifn_out = self.instrument_data.rootfn.split('_calints')[0]+'.oifits'\n\n        # Read in all relevant text observables and save to oifits file...\n        dct = implane2oifits.oitxt2oif(nh=7, oitdir=self.oitdir+self.instrument_data.rootfn+'/',\n                                             oifn=oifn_out,\n                                             oifdir=self.oifdir,\n                                             verbose=self.verbose,\n                                             )\n\n        \n\n    def save_output(self, slc, nrm):\n        # cropped & centered PSF\n        self.datapeak = self.ctrd.max()\n        #TBD: Keep only n_*.fits files after testing is done and before doing ImPlaneIA delivery\n        if self.save_txt_only == False:\n            fits.PrimaryHDU(data=self.ctrd, \\\n                    header=self.scihdr).writeto(self.oitdir+\\\n                    self.instrument_data.rootfn+\"/centered_{0}.fits\".format(slc), \\\n                    overwrite=True)\n            fits.PrimaryHDU(data=self.ctrd/self.datapeak, \\\n                    header=self.scihdr).writeto(self.oitdir+\\\n                    self.instrument_data.rootfn+\"/n_centered_{0}.fits\".format(slc), \\\n                    overwrite=True)\n\n            model, modelhdu = nrm.plot_model(fits_true=1)\n            # save to fits files\n            fits.PrimaryHDU(data=nrm.residual).writeto(self.oitdir+\\\n                            self.instrument_data.rootfn+\\\n                            \"/residual_{0:02d}.fits\".format(slc), \\\n                            overwrite=True)\n            fits.PrimaryHDU(data=nrm.residual/self.datapeak).writeto(self.oitdir+\\\n                            self.instrument_data.rootfn+\\\n                            \"/n_residual_{0:02d}.fits\".format(slc), \\\n                            overwrite=True)\n            modelhdu.writeto(self.oitdir+\\\n                             self.instrument_data.rootfn+\\\n                             \"/modelsolution_{0:02d}.fits\".format(slc),\\\n                             overwrite=True)\n            fits.PrimaryHDU(data=model/self.datapeak, \\\n                            header=modelhdu.header).writeto(self.oitdir+\\\n                            self.instrument_data.rootfn+\\\n                            \"/n_modelsolution_{0:02d}.fits\".format(slc), \\\n                            overwrite=True)\n            try: # if there's an appropriately trimmed bad pixel map write it out\n                fits.PrimaryHDU(data=self.ctrb, \\\n                    header=self.scihdr).writeto(self.oitdir+\\\n                    self.instrument_data.rootfn+\"/bp_{0}.fits\".format(slc), \\\n                    overwrite=True)\n            except: AttributeError\n                \n\n        # default save to text files\n        np.savetxt(self.oitdir+self.instrument_data.rootfn + \\\n                   \"/solutions_{0:02d}.txt\".format(slc), nrm.soln)\n        np.savetxt(self.oitdir+self.instrument_data.rootfn + \\\n                   \"/phases_{0:02d}.txt\".format(slc), nrm.fringephase)\n        np.savetxt(self.oitdir+self.instrument_data.rootfn + \\\n                   \"/amplitudes_{0:02d}.txt\".format(slc), nrm.fringeamp)\n        np.savetxt(self.oitdir+self.instrument_data.rootfn + \\\n                   \"/CPs_{0:02d}.txt\".format(slc), nrm.redundant_cps)\n        np.savetxt(self.oitdir+self.instrument_data.rootfn + \\\n                   \"/CAs_{0:02d}.txt\".format(slc), nrm.redundant_cas)\n        np.savetxt(self.oitdir+self.instrument_data.rootfn + \\\n                  \"/fringepistons_{0:02d}.txt\".format(slc), nrm.fringepistons)\n\n        # write info that oifits wants only when writing out first slice.\n        # this will relevant to all slices... so no slice number here.\n        if slc == 0:\n            pfn = self.oitdir+self.instrument_data.rootfn + \"/info4oif_dict.pkl\"\n            pfd = open(pfn, 'wb')\n            pickle.dump(self.instrument_data.info4oif_dict, pfd)\n            pfd.close()\n\n        # optional save outputs\n        if self.verbose_save:\n            np.savetxt(self.oitdir+self.instrument_data.rootfn+\\\n                       \"/condition_{0:02d}.txt\".format(slc), nrm.cond)\n            np.savetxt(self.oitdir+self.instrument_data.rootfn+\\\n                       \"/flux_{0:02d}.txt\".format(slc), nrm.flux)\n          \n\n    def save_auto_figs(self, slc, nrm):\n        \n        # rotation\n        if self.find_rotation==True:\n            plt.figure()\n            plt.plot(nrm.rots, nrm.corrs)\n            plt.vlines(nrm.rot_measured, nrm.corrs[0],\n                        nrm.corrs[-1], linestyles='--', color='r')\n            plt.text(nrm.rots[1], nrm.corrs[1], \n                     \"best fit at {0}\".format(nrm.rot_measured))\n            plt.savefig(self.oitdir+self.instrument_data.rootfn+\\\n                        \"/rotationcorrelation_{0:02d}.png\".format(slc))\n\ndef fit_fringes_parallel(args, threads):\n    self = args['object']\n    filename = args['file']\n    id_tag = args['id']\n    self.prihdr, self.scihdr, self.scidata, self.dqmask = \\\n        self.instrument_data.read_data(filename)\n\n    try:\n        os.makedirs(self.oitdir+self.instrument_data.rootfn)\n    except:\n        pass\n\n    store_dict = [{\"object\":self, \"slc\":slc} for slc in \\\n                  range(self.instrument_data.nwav)]\n\n    if threads>0:\n        pool = Pool(processes=threads)\n        print(\"Running fit_fringes in parallel with {0} threads\".format(threads))\n        pool.map(fit_fringes_single_integration, store_dict)\n        pool.close()\n        pool.join()\n    else:\n        for slc in range(self.instrument_data.nwav):\n            fit_fringes_single_integration({\"object\":self, \"slc\":slc})\n\ndef fit_fringes_single_integration(args):\n    self = args[\"object\"]\n    slc = args[\"slc\"]  # indexes each slice of 3D stack of images\n    id_tag = args[\"slc\"]\n    nrm = NRM_Model(mask=self.instrument_data.mask,\n                    pixscale=self.instrument_data.pscale_rad,\n                    holeshape=self.instrument_data.holeshape,\n                    affine2d=self.instrument_data.affine2d,\n                    over = self.oversample)\n\n    # for image data from single filter, this is the filter bandpass.\n    # otherwise it's the IFU wavelength slice.\n    nrm.bandpass = self.instrument_data.wls[slc]\n\n    if self.npix == 'default':\n        self.npix = self.scidata[slc,:,:].shape[0]\n    \n    # New or modified in LG++\n    # center the image on its peak pixel:\n    # AS subtract 1 from \"r\" below  for testing >1/2 pixel offsets\n    # AG 03-2019 -- is above comment still relevant?\n    \n    # Where appropriate, the slice under consideration is centered, and processed\n    if self.instrument_data.arrname==\"jwst_g7s6c\":\n        # get the cropped image and identically-cropped bad pixel data:\n        self.ctrd, self.dqslice = utils.center_imagepeak(\n                                    self.scidata[slc,:,:], \n                                    dqm=self.dqmask[slc,:,:]) \n    else:\n        self.ctrd = utils.center_imagepeak(self.scidata[slc,:,:])  \n    \n\n    # store the 2D cropped image centered on the brightest pixel, \n    # bad pixels smoothed over\n\n    if self.psf_offset_ff is None:\n        # returned values have offsets x-y flipped:\n        # Finding centroids the Fourier way assumes no bad pixels case \n        #   - Fourier domain mean slope\n\n        # offsets from brightest pixel ctr\n        centroid = utils.find_centroid(self.ctrd, self.instrument_data.threshold)\n        # use flipped centroids to update centroid of image for JWST \n        # pixel coordinates: - note the flip of [0] and [1] to match DS9 view\n        image_center = utils.centerpoint(self.ctrd.shape) + \\\n                            np.array((centroid[1], centroid[0])) # info only, unused\n        nrm.xpos = centroid[1]  # flip 0 and 1 to convert\n        nrm.ypos = centroid[0]  # flip 0 and 1\n        nrm.psf_offset = nrm.xpos, nrm.ypos  # renamed .bestcenter to .psf_offset\n        if self.debug: \n            print(\"nrm.core.fit_fringes_single_integration: utils.find_centroid() -> nrm.psf_offset\")\n    else:\n        # user-provided psf_offset python-style offsets from array center are here.\n        nrm.psf_offset = self.psf_offset_ff \n\n\n    nrm.make_model(fov=self.ctrd.shape[0], \n                   bandpass=nrm.bandpass, \n                   over=self.oversample,\n                   psf_offset=nrm.psf_offset,  \n                   pixscale=nrm.pixel)\n\n    # again, fit just one slice...\n    if self.instrument_data.arrname==\"jwst_g7s6c\":\n        nrm.fit_image(self.ctrd, \n                      modelin=nrm.model, \n                      psf_offset=nrm.psf_offset,\n                      dqm=self.dqslice,\n                      weighted=self.weighted)\n    else:\n        nrm.fit_image(self.ctrd,\n                      modelin=nrm.model,\n                      psf_offset=nrm.psf_offset,\n                      weighted=self.weighted)\n\n    \"\"\"\n    Attributes now stored in nrm object:\n\n    -----------------------------------------------------------------------------\n    soln            --- resulting sin/cos coefficients from least squares fitting\n    fringephase     --- baseline phases in radians\n    fringeamp       --- baseline amplitudes (flux normalized)\n    redundant_cps   --- closure phases in radians\n    redundant_cas   --- closure amplitudes\n    residual        --- fit residuals [data - model solution]\n    cond            --- matrix condition for inversion\n    fringepistons   --- zero-mean piston opd in radians on each hole (eigenphases)\n    -----------------------------------------------------------------------------\n    For jwst_g7s6 cropped-to-match-data bad pixel array 'ctrb' is also stored\n    \"\"\"\n\n    self.save_output(slc, nrm)  # Please elucidate what this is for\n    self.nrm = nrm # store  extracted values here\n    return None\n", "meta": {"hexsha": "697e8060b68d8ffc1c2d60d39544afe0d8eb941a", "size": 17358, "ext": "py", "lang": "Python", "max_stars_repo_path": "nrm_analysis/nrm_core.py", "max_stars_repo_name": "vandalt/ImPlaneIA", "max_stars_repo_head_hexsha": "72b22e487ef45a8a665e4a6a88a91e99e382fdd0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nrm_analysis/nrm_core.py", "max_issues_repo_name": "vandalt/ImPlaneIA", "max_issues_repo_head_hexsha": "72b22e487ef45a8a665e4a6a88a91e99e382fdd0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nrm_analysis/nrm_core.py", "max_forks_repo_name": "vandalt/ImPlaneIA", "max_forks_repo_head_hexsha": "72b22e487ef45a8a665e4a6a88a91e99e382fdd0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.0290556901, "max_line_length": 108, "alphanum_fraction": 0.5769097822, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 4013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.3380771308191989, "lm_q1q2_score": 0.18221790080978328}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"02-ppo.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n    https://colab.research.google.com/drive/1GXTVkhpJyQQsUWn6tGQAWPmstw9adAzj\n\n# PPO for transformer models\n> A Pytorch implementation of Proximal Policy Optimization for transfomer models.\n\nThis follows the language model approach proposed in paper [\"Fine-Tuning Language Models from Human Preferences\"](\nhttps://arxiv.org/pdf/1909.08593.pdf) and is similar to the [original implementation](https://github.com/openai/lm-human-preferences). The two main differences are 1) the method is implemented in Pytorch and 2) works with the `transformer` library by Hugging Face.\n\"\"\"\n\n# default_exp ppo\n\n# export\nimport numpy as np\nimport torch.nn.functional as F\nfrom torch.optim import Adam\nimport torch\nimport collections\nimport time\nimport random\n\nfrom trl.core import (logprobs_from_logits,\n                         whiten,\n                         clip_by_value,\n                         entropy_from_logits,\n                         flatten_dict,\n                         average_torch_dicts,\n                         stats_to_np,\n                         stack_dicts,\n                         add_suffix)\n\n\"\"\"## KL-controllers\nTo ensure that the learned policy does not deviate to much from the original language model the KL divergence between the policy and a reference policy (the language model before PPO training) is used as an additional reward signal. Large KL-divergences are punished and staying close to the reference is rewarded.\n\nTwo controllers are presented in the paper: an adaptive log-space proportional controller and a fixed controller.\n\"\"\"\n\n# exports\n\nclass AdaptiveKLController:\n    \"\"\"\n    Adaptive KL controller described in the paper:\n    https://arxiv.org/pdf/1909.08593.pdf\n    \"\"\"\n    def __init__(self, init_kl_coef, target, horizon):\n        self.value = init_kl_coef\n        self.target = target\n        self.horizon = horizon\n\n    def update(self, current, n_steps):\n        target = self.target\n        proportional_error = np.clip(current / target - 1, -0.2, 0.2)\n        mult = 1 + proportional_error * n_steps / self.horizon\n        self.value *= mult\n\n# exports \n\nclass FixedKLController:\n    \"\"\"Fixed KL controller.\"\"\"\n    def __init__(self, kl_coef):\n        self.value = kl_coef\n\n    def update(self, current, n_steps):\n        pass\n\n# exports \n\nclass PPOTrainer:\n    \"\"\"\n    The PPO_trainer uses Proximal Policy Optimization to optimise language models.\n    \"\"\"\n    \n    default_params = {\n        \"lr\": 1.41e-5,\n        \"adap_kl_ctrl\": True, \n        \"init_kl_coef\":0.2,\n        \"target\": 6,\n        \"horizon\":10000,\n        \"gamma\":1,\n        \"lam\":0.95,\n        \"cliprange\": .2,\n        \"cliprange_value\":.2,\n        \"vf_coef\":.1,\n        \"batch_size\": 256,\n        \"forward_batch_size\": 16,\n        \"ppo_epochs\": 4,    \n    } \n    \n    def __init__(self, model, ref_model, **ppo_params):\n        \"\"\"\n        Initialize PPOTrainer.\n        \n        Args:\n            model (torch.model): Hugging Face transformer GPT2 model with value head\n            ref_model (torch.model): Hugging Face transformer GPT2 refrence model used for KL penalty\n            ppo_params (dict or None): PPO parameters for training. Can include following keys:\n                'lr' (float): Adam learning rate, default: 1.41e-5\n                'batch_size' (int): Number of samples per optimisation step, default: 256\n                'forward_batch_size' (int): Number of samples forward passed through model at a time, default: 16\n                'ppo_epochs' (int): Number of optimisation epochs per batch of samples, default: 4\n                'gamma' (float)): Gamma parameter for advantage calculation, default: 1.\n                'lam' (float): Lambda parameter for advantage calcualation, default: 0.95\n                'cliprange_value' (float): Range for clipping values in loss calculation, default: 0.2\n                'cliprange' (float): Range for clipping in PPO policy gradient loss, default: 0.2\n                'vf_coef' (float): Scaling factor for value loss, default: 0.1\n                'adap_kl_ctrl' (bool): Use adaptive KL control, otherwise linear, default: True\n                'init_kl_coef' (float): Initial KL penalty coefficient (used for adaptive and linear control), default: 0.2\n                'target' (float): Target KL value for adaptive KL control, default: 6.0\n                'horizon' (float): Horizon for adaptive KL control, default: 10000\n                \n        \"\"\"\n        self.ppo_params = self.default_params\n        self.ppo_params.update(ppo_params)\n        \n        self.ref_model = ref_model\n        self.model = model\n        self.optimizer = Adam(model.parameters(), lr=self.ppo_params['lr'])\n     \n        self.kl_ctl = AdaptiveKLController(self.ppo_params['init_kl_coef'],\n                                           self.ppo_params['target'],\n                                           self.ppo_params['horizon'])\n\n\n    def step(self, query, response, scores):\n        \"\"\"\n        Run a PPO optimisation step.\n        \n        args:\n            query (torch.tensor): tensor containing the encoded queries, shape [batch_size, query_length]\n            response (torch.tensor): tensor containing the encoded responses, shape [batch_size, response_length]\n            scores (torch.tensor): tensor containing the scores, shape [batch_size]\n            \n        returns:\n            train_stats (dict): a summary of the training statistics\n        \"\"\"\n\n        bs = self.ppo_params['batch_size']\n        timing = dict()\n        t0 = time.time()\n        \n        gen_len = response.shape[1]\n        model_input = torch.cat((query, response), axis=1)\n        \n        t = time.time()\n        logprobs, ref_logprobs, values = self.batched_forward_pass(model_input, gen_len)\n        timing['time/ppo/forward_pass'] = time.time()-t\n\n        t = time.time()\n        rewards, non_score_reward, kl_coef = self.compute_rewards(scores, logprobs, ref_logprobs)\n        timing['time/ppo/compute_rewards'] = time.time()-t \n        \n        t = time.time() \n        all_stats = []\n        idxs = list(range(bs))\n        for _ in range(self.ppo_params['ppo_epochs']):\n            random.shuffle(idxs)\n            for i in range(bs):\n                idx = idxs[i]\n                train_stats = self.train_minibatch(logprobs[idx:idx+1], values[idx:idx+1],\n                                                   rewards[idx:idx+1], query[idx:idx+1],\n                                                   response[idx:idx+1], model_input[idx:idx+1])\n                all_stats.append(train_stats)\n        timing['time/ppo/optimize_step'] = time.time()-t\n        \n        t = time.time()\n        train_stats = stack_dicts(all_stats)\n        \n        # reshape advantages/ratios such that they are not averaged.\n        train_stats['policy/advantages'] = torch.flatten(train_stats['policy/advantages']).unsqueeze(0)\n        train_stats['policy/ratio'] = torch.flatten(train_stats['policy/ratio']).unsqueeze(0)\n        \n        stats = self.record_step_stats(scores=scores, logprobs=logprobs, ref_logprobs=ref_logprobs,\n                                       non_score_reward=non_score_reward, train_stats=train_stats,\n                                       kl_coef=kl_coef)\n        stats = stats_to_np(stats)\n        timing['time/ppo/calc_stats'] = time.time()-t\n\n        self.kl_ctl.update(stats['objective/kl'], self.ppo_params['batch_size'])\n\n        timing['time/ppo/total'] = time.time()-t0\n        stats.update(timing)\n        return stats\n\n    def batched_forward_pass(self, model_input, gen_len):\n        \"\"\"Calculate model outputs in multiple batches.\"\"\"\n        bs = self.ppo_params['batch_size']\n        fbs = self.ppo_params['forward_batch_size']\n        logprobs = []\n        ref_logprobs = []\n        values = []\n        \n        for i in range(int(self.ppo_params['batch_size']/fbs)):\n            m_input = model_input[i*fbs:(i+1)*fbs]\n            logits, _, v = self.model(m_input)\n            ref_logits, _, _ = self.ref_model(m_input)\n            \n            values.append(v[:, -gen_len-1:-1].detach())\n            logprobs.append(logprobs_from_logits(logits[:,:-1,:], m_input[:,1:])[:, -gen_len:].detach())\n            ref_logprobs.append(logprobs_from_logits(ref_logits[:,:-1,:], m_input[:,1:])[:, -gen_len:].detach())\n   \n        return torch.cat(logprobs), torch.cat(ref_logprobs), torch.cat(values)\n    \n    def train_minibatch(self, logprobs, values, rewards, query, response, model_input):\n        \"\"\"Train one PPO minibatch\"\"\"\n        loss_p, loss_v, train_stats  = self.loss(logprobs, values, rewards, query, response, model_input)\n        loss = loss_p + loss_v\n        self.optimizer.zero_grad()\n        loss.backward()\n        self.optimizer.step()\n        return train_stats\n    \n    def compute_rewards(self, scores, logprobs, ref_logprobs):\n        \"\"\"Compute per token rewards from scores and KL-penalty.\"\"\"\n        kl = logprobs - ref_logprobs\n        non_score_reward = -self.kl_ctl.value * kl\n        rewards = non_score_reward.clone().detach()\n        rewards[:, -1] += scores\n        return rewards, non_score_reward, self.kl_ctl.value\n\n    def loss(self, old_logprobs, values, rewards, query, response, model_input):\n        \"\"\"Calculate policy and value losses.\"\"\"\n        lastgaelam = 0\n        advantages_reversed = []\n        gen_len = response.shape[1]\n\n        for t in reversed(range(gen_len)):\n            nextvalues = values[:, t + 1] if t < gen_len - 1 else 0.0\n            delta = rewards[:, t] + self.ppo_params['gamma'] * nextvalues - values[:, t]\n            lastgaelam = delta + self.ppo_params['gamma'] * self.ppo_params['lam'] * lastgaelam\n            advantages_reversed.append(lastgaelam)\n        advantages = torch.stack(advantages_reversed[::-1]).transpose(0, 1)\n\n        returns = advantages + values\n        advantages = whiten(advantages)\n        advantages = advantages.detach()\n\n        logits, _, vpred = self.model(model_input)\n        logprob = logprobs_from_logits(logits[:,:-1,:], model_input[:, 1:])\n        \n        #only the generation part of the values/logprobs is needed\n        logprob, vpred = logprob[:, -gen_len:], vpred[:,-gen_len-1:-1]\n\n        vpredclipped = clip_by_value(vpred,\n                                     values - self.ppo_params[\"cliprange_value\"],\n                                     values + self.ppo_params[\"cliprange_value\"])\n\n        vf_losses1 = (vpred - returns)**2\n        vf_losses2 = (vpredclipped - returns)**2\n        vf_loss = .5 * torch.mean(torch.max(vf_losses1, vf_losses2))\n        vf_clipfrac =  torch.mean(torch.gt(vf_losses2, vf_losses1).double())\n\n        ratio = torch.exp(logprob - old_logprobs)\n        \n        pg_losses = -advantages * ratio\n        pg_losses2 = -advantages * torch.clamp(ratio,\n                                               1.0 - self.ppo_params['cliprange'],\n                                               1.0 + self.ppo_params['cliprange'])\n\n        pg_loss = torch.mean(torch.max(pg_losses, pg_losses2))\n        pg_clipfrac = torch.mean(torch.gt(pg_losses2, pg_losses).double())\n        \n        loss = pg_loss + self.ppo_params['vf_coef'] * vf_loss\n\n        entropy = torch.mean(entropy_from_logits(logits))\n        approxkl = .5 * torch.mean((logprob - old_logprobs)**2)\n        policykl = torch.mean(logprob - old_logprobs)\n        return_mean, return_var = torch.mean(returns), torch.var(returns)\n        value_mean, value_var = torch.mean(values), torch.var(values)\n\n        stats = dict(\n            loss=dict(policy=pg_loss, value=vf_loss, total=loss),\n            policy=dict(entropy=entropy, approxkl=approxkl,policykl=policykl, clipfrac=pg_clipfrac,\n                        advantages=advantages, advantages_mean=torch.mean(advantages), ratio=ratio),\n            returns=dict(mean=return_mean, var=return_var),\n            val=dict(vpred=torch.mean(vpred), error=torch.mean((vpred - returns) ** 2),\n                     clipfrac=vf_clipfrac, mean=value_mean, var=value_var),\n        )\n        return pg_loss, self.ppo_params['vf_coef'] * vf_loss, flatten_dict(stats)\n\n\n    def record_step_stats(self, kl_coef, **data):\n        \"\"\"Record training step statistics.\"\"\"\n        kl = data['logprobs'] - data['ref_logprobs']\n        mean_kl = torch.mean(torch.sum(kl, axis=-1))\n        mean_entropy = torch.mean(torch.sum(-data['logprobs'], axis=1))\n        mean_non_score_reward =torch.mean(torch.sum(data['non_score_reward'], axis=1))\n        stats = {\n            'objective/kl': mean_kl,\n            'objective/kl_dist': kl,\n            'objective/logprobs': data['logprobs'],\n            'objective/ref_logprobs': data['ref_logprobs'],\n            'objective/kl_coef': kl_coef,\n            'objective/entropy': mean_entropy,\n            'ppo/mean_non_score_reward': mean_non_score_reward,\n        }\n\n        for k, v in data['train_stats'].items():\n            stats[f'ppo/{k}'] = torch.mean(v, axis=0)\n        stats['ppo/val/var_explained'] = 1 - stats['ppo/val/error'] / stats['ppo/returns/var']\n        return stats\n\n\"\"\"## Tensor shapes and contents\n\nDebugging tensor shapes and contents usually involves inserting a lot of print statements in the code. To avoid this in the future I add a list of the tensor shapes and contents for reference. If the tensors are sliced or reshaped I list the last shape.\n\n| Name  | Shape   | Content |\n|-------|---------|---------|\n| `query` | `[batch_size, query_length]`| contains token ids of query|\n| `response`| `[batch_size, response_length]`| contains token ids of responses|\n| `scores`| `[batch_size]`| rewards of each query/response pair|\n| `model_input`| `[batch_size, query_length + response_length]`| combined query and response tokens|\n| `m_input`|`[forward_batch_size, query_length + response_length]`| small forward batch of model_input|\n| `logits` | `[forward_batch_size, query_length + response_length, vocab_size]`| logits from model outputs|\n| `ref_logits`|`[forward_batch_size, query_length + response_length, vocab_size]`| logits from ref_model outputs|\n| `logprobs`| `[batch_size, response_length]`| log-probabilities of response tokens |\n| `ref_logprobs`| `[batch_size, response_length]`| reference log-probabilities of response tokens |\n| `rewards`| `[batch_size, response_length]`| the model rewards incl. kl-score for each token|\n| `non_score_reward`| `[batch_size, response_length]`| the model kl-score for each token|\n\n## Model output alignments\nSome notes on output alignments, since I spent a considerable time debugging this. All model outputs are shifted by 1 to the model inputs. That means that the logits are shifted by one as well as values. For this reason the logits and values are always shifted one step to the left. This also means we don't have logits for the first input element and so we delete the first input token when calculating the softmax, since we don't have logits predictions. The same applies for the values and we shift them by index one to the left.\n\n## KL-divergence\nOne question that came up during the implementation was \"Why is the KL-divergence just the difference of the log-probs? Where is the probability in front of the log term?\". The answer can be found in Sergey Levine's [lecture slides](http://rll.berkeley.edu/deeprlcourse/docs/week_3_lecture_1_dynamics_learning.pdf): To calculate the KL divergence we calculate the expected value of the log term. The probability usually in front of the log-term comes from that expected value and for a set of trajectories we can simply take the mean over the sampled trajectories.\n\"\"\"", "meta": {"hexsha": "058753427b8d12d1061f42dc505d9be81b5a17ea", "size": 15639, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/02_ppo.py", "max_stars_repo_name": "grzegorzwojdyga/trl", "max_stars_repo_head_hexsha": "1921e71a7465a43dcc135d97821aa8b03bfebf8c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/02_ppo.py", "max_issues_repo_name": "grzegorzwojdyga/trl", "max_issues_repo_head_hexsha": "1921e71a7465a43dcc135d97821aa8b03bfebf8c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/02_ppo.py", "max_forks_repo_name": "grzegorzwojdyga/trl", "max_forks_repo_head_hexsha": "1921e71a7465a43dcc135d97821aa8b03bfebf8c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.3909090909, "max_line_length": 564, "alphanum_fraction": 0.6325852037, "include": true, "reason": "import numpy", "num_tokens": 3662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.18221789721520015}}
{"text": "\"\"\"Functions for metric learning for the face recognition network.\n\"\"\"\n# MIT License\n#### copyright at Auther: mingzuheng, 25/03/2019 #########\n\n\n# pylint: disable=missing-docstring\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nfrom subprocess import Popen, PIPE\nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\nimport numpy as np\nfrom scipy import misc\nimport matplotlib.pyplot as plt\nfrom scipy import interpolate\nfrom tensorflow.python.training import training\nimport random\nimport re\nfrom collections import Counter\nimport matplotlib.pyplot as plt\nimport cv2\nimport python_getdents \nfrom scipy import spatial\nfrom sklearn.decomposition import PCA\nfrom itertools import islice\nimport itertools\n\n#import h5py\n\n\n\n  \ndef center_loss(features, label, alfa, nrof_classes):\n    \"\"\"Center loss based on the paper \"A Discriminative Feature Learning Approach for Deep Face Recognition\"\n       (http://ydwen.github.io/papers/WenECCV16.pdf)\n\n\n    \"\"\"\n     #nrof_features = features.get_shape()[1]\n     #centers = tf.get_variable('centers', [nrof_classes, nrof_features], dtype=tf.float32,\n     #    initializer=tf.constant_initializer(0), trainable=False)\n     #label = tf.reshape(label, [-1])\n     #centers_batch = tf.gather(centers, label)\n     #diff = (1 - alfa) * (centers_batch - features)\n     #diff = alfa * (centers_batch - features)\n     #centers = tf.scatter_sub(centers, label, diff)\n    # loss = tf.nn.l2_loss(features - centers_batch)\n    # return loss, centers, diff, centers_batch\n\n    \"\"\"Center loss based on the paper \"A Discriminative Feature Learning Approach for Deep Face Recognition\"\n       (http://ydwen.github.io/papers/WenECCV16.pdf)\n       -- mzh 15/02/2017\n       -- Correcting the center updating, center updates/shifts towards to the center of the correponding class with a weight:\n       -- centers = centers- (1-alpha)(centers-sum(Xi)/Nj), where Xi is the elements of the class j, Nj is the number of the elements of class Nj\n       -- code has been tested by the test script '../test/center_loss_test.py'\n    \"\"\"\n    nrof_features = features.get_shape()[1]\n    centers = tf.get_variable('centers', [nrof_classes, nrof_features], dtype=tf.float32, initializer=tf.constant_initializer(0), trainable=False)\n    centers_cts = tf.get_variable('centers_cts', [nrof_classes], dtype=tf.float32, initializer=tf.constant_initializer(0), trainable=False)\n    #centers_cts_init = tf.zeros_like(nrof_classes, tf.float32)\n    label = tf.reshape(label, [-1])\n    centers_batch = tf.gather(centers, label) #get the corresponding center of each element in features, the list of the centers is in the same order as the features\n    loss_n = tf.reduce_sum(tf.square(features - centers_batch)/2, 1)\n    loss = tf.nn.l2_loss(features - centers_batch)\n    diff = (1 - alfa) * (centers_batch - features)\n\n    ## update the centers\n    label_unique, idx = tf.unique(label)\n    zeros = tf.zeros_like(label_unique, tf.float32)\n    ## calculation the repeat time of same label\n    nrof_elements_per_class_clean = tf.scatter_update(centers_cts, label_unique, zeros)\n    ones = tf.ones_like(label, tf.float32)\n    ## counting the number elments in each class, the class is in the order of the [0,1,2,3,....] as initialzation\n    nrof_elements_per_class_update = tf.scatter_add(nrof_elements_per_class_clean, label, ones)\n    ## nrof_elements_per_class_list is the number of the elements in each class in the batch\n    nrof_elements_per_class_batch = tf.gather(nrof_elements_per_class_update, label)\n    nrof_elements_per_class_batch_reshape = tf.reshape(nrof_elements_per_class_batch, [-1, 1])## reshape the matrix as 1 coloum no matter the dimension of the row (-1)\n    diff_mean = tf.div(diff, nrof_elements_per_class_batch_reshape)\n    centers = tf.scatter_sub(centers, label, diff_mean)\n\n    #return loss, centers, label, centers_batch, diff, centers_cts, centers_cts_batch, diff_mean,center_cts_clear, nrof_elements_per_class_batch_reshape\n    return loss, loss_n, centers, nrof_elements_per_class_clean, nrof_elements_per_class_batch_reshape,diff_mean # facenet_expression_addcnns_simple_joint_v4_dynamic.py\n    #return loss, centers, nrof_elements_per_class_clean, nrof_elements_per_class_batch_reshape,diff_mean ### facenet_train_classifier_expression_pretrainExpr_multidata_addcnns_simple.py\n\ndef center_loss_similarity(features, label, alfa, nrof_classes):\n    ## center_loss on cosine distance =1 - similarity instead of the L2 norm, i.e. Euclidian distance\n\n    ## normalisation as the embedding vectors in order to similarity distance\n    features = tf.nn.l2_normalize(features, 1, 1e-10, name='feat_emb')\n\n    nrof_features = features.get_shape()[1]\n    centers = tf.get_variable('centers', [nrof_classes, nrof_features], dtype=tf.float32, initializer=tf.constant_initializer(0), trainable=False)\n    centers_cts = tf.get_variable('centers_cts', [nrof_classes], dtype=tf.float32, initializer=tf.constant_initializer(0), trainable=False)\n    #centers_cts_init = tf.zeros_like(nrof_classes, tf.float32)\n    label = tf.reshape(label, [-1])\n    centers_batch = tf.gather(centers, label) #get the corresponding center of each element in features, the list of the centers is in the same order as the features\n    #loss = tf.nn.l2_loss(features - centers_batch) ## 0.5*(L2 norm)**2, L2 norm is the Euclidian distance\n    similarity_all = tf.matmul(features, tf.transpose(tf.nn.l2_normalize(centers_batch, 1, 1e-10))) ## dot prodoct, cosine distance, similarity of x and y\n    similarity_self = tf.diag_part(similarity_all)\n    loss_x = tf.subtract(1.0, similarity_self)\n    loss = tf.reduce_sum(loss_x) ## sum the cosine distance of each vector/tensor\n    diff = (1 - alfa) * (centers_batch - features)\n    ones = tf.ones_like(label, tf.float32)\n    centers_cts = tf.scatter_add(centers_cts, label, ones) # counting the number of each class, the class is in the order of the [0,1,2,3,....] as initialzation\n    centers_cts_batch = tf.gather(centers_cts, label)\n    #centers_cts_batch_ext = tf.tile(centers_cts_batch, nrof_features)\n    #centers_cts_batch_reshape = tf.reshape(centers_cts_batch_ext,[-1, nrof_features])\n    centers_cts_batch_reshape = tf.reshape(centers_cts_batch, [-1,1])\n    diff_mean = tf.div(diff, centers_cts_batch_reshape)\n    centers = tf.scatter_sub(centers, label, diff_mean)\n    zeros = tf.zeros_like(label, tf.float32)\n    center_cts_clear = tf.scatter_update(centers_cts, label, zeros)\n    #return loss, centers, label, centers_batch, diff, centers_cts, centers_cts_batch, diff_mean,center_cts_clear, centers_cts_batch_reshape\n    #return loss, centers, loss_x, similarity_all, similarity_self\n    return loss, centers\n\n\n\n\ndef center_inter_loss_tf(features, nrof_features, label, alfa, nrof_classes): # tensorflow version\n    \"\"\" center_inter_loss = center_loss/||Xi - centers(0,1,2,...i-1,i+1,i+2,...)||\n        --mzh 22022017\n    \"\"\"\n    # dim_features = features.get_shape()[1]\n    # nrof_features = features.get_shape()[0]\n    dim_features = features.get_shape()[1].value\n    #nrof_features = features.get_shape()[0].value\n    # dim_features = features.shape[1]\n    # nrof_features = features.shape[0]\n    centers = tf.get_variable('centers', [nrof_classes, dim_features], dtype=tf.float32,\n                              initializer=tf.constant_initializer(0), trainable=False)\n    centers_cts = tf.get_variable('centers_cts', [nrof_classes], dtype=tf.float32,\n                                  initializer=tf.constant_initializer(0), trainable=False)\n    ## center_loss calculation\n    label = tf.reshape(label, [-1])\n    centers_batch = tf.gather(centers,label)  # get the corresponding center of each element in features, the list of the centers is in the same order as the features\n    dist_centers = features - centers_batch\n    dist_centers_sum = tf.reduce_sum(dist_centers**2,1)/2\n    loss_center = tf.nn.l2_loss(dist_centers)\n\n    ## calculation the repeat time of same label\n    ones = tf.ones_like(label, tf.float32)\n    centers_cts = tf.scatter_add(centers_cts, label, ones)  # counting the number of each class, the class is in the order of the [0,1,2,3,....] as initialzation\n    centers_cts_batch = tf.gather(centers_cts, label)\n\n\n    ## inter_center_loss calculation\n    #label_unique, label_idx = tf.unique(label)\n    #centers_batch1 = tf.gather(centers,label_unique)\n    #nrof_classes_batch = centers_batch.get_shape()[0].value\n    #centers_1D = tf.reshape(centers_batch1, [1, nrof_classes_batch * dim_features])\n    centers_batch1 = tf.gather(centers,label)\n    centers_1D = tf.reshape(centers_batch1, [1, nrof_features * dim_features])\n    centers_2D = tf.tile(centers_1D, [nrof_features, 1])\n    centers_3D = tf.reshape(centers_2D,[nrof_features, nrof_features, dim_features])\n    features_3D = tf.reshape(features, [nrof_features, 1, dim_features])\n    dist_inter_centers = features_3D - centers_3D\n    dist_inter_centers_sum_dim = tf.reduce_sum(dist_inter_centers**2,2)/2\n    centers_cts_batch_1D = tf.tile(centers_cts_batch,[nrof_features])\n    centers_cts_batch_2D = tf.reshape(centers_cts_batch_1D, [nrof_features, nrof_features])\n    dist_inter_centers_sum_unique = tf.div(dist_inter_centers_sum_dim, centers_cts_batch_2D)\n    dist_inter_centers_sum_all = tf.reduce_sum(dist_inter_centers_sum_unique, 1)\n    dist_inter_centers_sum = dist_inter_centers_sum_all - dist_centers_sum\n    loss_inter_centers = tf.reduce_mean(dist_inter_centers_sum)\n\n    ## total loss\n    loss = tf.div(loss_center, loss_inter_centers)\n\n    ## update centers\n    diff = (1 - alfa) * (centers_batch - features)\n#    ones = tf.ones_like(label, tf.float32)\n#   centers_cts = tf.scatter_add(centers_cts, label, ones)  # counting the number of each class\n#    centers_cts_batch = tf.gather(centers_cts, label)\n    centers_cts_batch_reshape = tf.reshape(centers_cts_batch, [-1, 1])\n    diff_mean = tf.div(diff, centers_cts_batch_reshape)\n    centers = tf.scatter_sub(centers, label, diff_mean)\n    zeros = tf.zeros_like(label, tf.float32)\n    center_cts_clear = tf.scatter_update(centers_cts, label, zeros)\n    # return loss, centers, label, centers_batch, diff, centers_cts, centers_cts_batch, diff_mean,center_cts_clear, centers_cts_batch_reshape\n    return loss, centers,  loss_center, loss_inter_centers, center_cts_clear\n    #return loss, centers, loss_center, loss_inter_centers, dist_inter_centers_sum_dim, centers_cts_batch_2D, dist_inter_centers_sum_unique, dist_inter_centers_sum_all, dist_inter_centers_sum, dist_inter_centers_sum, center_cts_clear\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n  \n\n\n  \n\n\n\n\n\n\n\n  \n\n\n\n\n\n\n\n\n\n\n  \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "51195ce616758b942e7cef8c00c5c74fd1cc2788", "size": 10657, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/metrics_loss.py", "max_stars_repo_name": "hengxyz/Dynamic_multi-task-learning", "max_stars_repo_head_hexsha": "57a047d56b8a0c4f43d99e1371524bd0f728515b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2019-12-05T13:15:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T04:36:56.000Z", "max_issues_repo_path": "src/metrics_loss.py", "max_issues_repo_name": "hengxyz/Dynamic_multi-task-learning", "max_issues_repo_head_hexsha": "57a047d56b8a0c4f43d99e1371524bd0f728515b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-11-26T02:45:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-07T15:38:05.000Z", "max_forks_repo_path": "src/metrics_loss.py", "max_forks_repo_name": "hengxyz/Dynamic_multi-task-learning", "max_forks_repo_head_hexsha": "57a047d56b8a0c4f43d99e1371524bd0f728515b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-11-11T05:51:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T23:14:25.000Z", "avg_line_length": 42.4581673307, "max_line_length": 233, "alphanum_fraction": 0.745800882, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.18221789362061705}}
{"text": "import numpy as np\nimport astropy.wcs as pywcs\nimport os\nfrom collections import defaultdict\nfrom regions import PixCoord\nimport warnings\n\nfrom soxs.events import write_event_file\nfrom soxs.instrument_registry import instrument_registry\nfrom soxs.psf import psf_model_registry\nfrom soxs.response import AuxiliaryResponseFile, RedistributionMatrixFile\nfrom soxs.simput import read_simput_catalog, SimputPhotonList\nfrom soxs.utils import mylog, parse_prng, parse_value, \\\n    get_rot_mat, create_region, get_data_file, ensure_numpy_array\n\n\ndef perform_dither(t, dither_dict):\n    if dither_dict[\"dither_on\"]:\n        a = 2.0*np.pi/dither_dict[\"x_period\"]\n        b = 2.0*np.pi/dither_dict[\"y_period\"]\n        A = dither_dict[\"x_amp\"]/dither_dict[\"plate_scale\"]\n        B = dither_dict[\"y_amp\"]/dither_dict[\"plate_scale\"]\n        x_offset = A*np.sin(a*t)\n        y_offset = B*np.sin(b*t)\n    else:\n        x_offset = np.zeros(t.size)\n        y_offset = np.zeros(t.size)\n    return x_offset, y_offset\n\n\ndef generate_events(source, exp_time, instrument, sky_center, \n                    no_dither=False, dither_params=None, \n                    roll_angle=0.0, subpixel_res=False, \n                    aimpt_shift=None, prng=None):\n    \"\"\"\n    Take unconvolved events and convolve them with instrumental responses. This \n    function does the following:\n\n    1. Determines which events are observed using the ARF\n    2. Pixelizes the events, applying PSF effects and dithering\n    3. Determines energy channels using the RMF\n\n    This function is not meant to be called by the end-user but is used by\n    the :func:`~soxs.instrument.instrument_simulator` function.\n\n    Parameters\n    ----------\n    input_events : string, dict, or None\n        The unconvolved events to be used as input. Can be one of the\n        following:\n        1. The name of a SIMPUT catalog file.\n        2. A Python dictionary containing the following items:\n        \"ra\": A NumPy array of right ascension values in degrees.\n        \"dec\": A NumPy array of declination values in degrees.\n        \"energy\": A NumPy array of energy values in keV.\n        \"flux\": The flux of the entire source, in units of erg/cm**2/s.\n    out_file : string\n        The name of the event file to be written.\n    exp_time : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`\n        The exposure time to use, in seconds. \n    instrument : string\n        The name of the instrument to use, which picks an instrument\n        specification from the instrument registry. \n    sky_center : array, tuple, or list\n        The center RA, Dec coordinates of the observation, in degrees.\n    no_dither : boolean, optional\n        If True, turn off dithering entirely. Default: False\n    dither_params : array-like of floats, optional\n        The parameters to use to control the size and period of the dither\n        pattern. The first two numbers are the dither amplitude in x and y\n        detector coordinates in arcseconds, and the second two numbers are\n        the dither period in x and y detector coordinates in seconds. \n        Default: [8.0, 8.0, 1000.0, 707.0].\n    roll_angle : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`, optional\n        The roll angle of the observation in degrees. Default: 0.0\n    subpixel_res : boolean, optional\n        If True, event positions are not randomized within the pixels \n        within which they are detected. Default: False\n    aimpt_shift : array-like, optional\n        A two-float array-like object which shifts the aimpoint on the \n        detector from the nominal position. Units are in arcseconds.\n        Default: None, which results in no shift from the nominal aimpoint. \n    prng : :class:`~numpy.random.RandomState` object, integer, or None\n        A pseudo-random number generator. Typically will only \n        be specified if you have a reason to generate the same \n        set of random numbers, such as for a test. Default is None, \n        which sets the seed based on the system time. \n    \"\"\"\n    exp_time = parse_value(exp_time, \"s\")\n    roll_angle = parse_value(roll_angle, \"deg\")\n    prng = parse_prng(prng)\n    if source is None:\n        source_list = []\n    elif isinstance(source, dict):\n        parameters = {}\n        for key in [\"flux\", \"emin\", \"emax\", \"src_names\"]:\n            parameters[key] = source[key]\n        source_list = []\n        for i in range(len(parameters[\"flux\"])):\n            phlist = SimputPhotonList(source[\"ra\"][i], source[\"dec\"][i],\n                                      source[\"energy\"][i], parameters['flux'][i],\n                                      parameters['src_names'][i])\n            source_list.append(phlist)\n    elif isinstance(source, str):\n        # Assume this is a SIMPUT catalog\n        source_list, parameters = read_simput_catalog(source)\n\n    try:\n        instrument_spec = instrument_registry[instrument]\n    except KeyError:\n        raise KeyError(f\"Instrument {instrument} is not in the instrument registry!\")\n    if not instrument_spec[\"imaging\"]:\n        raise RuntimeError(f\"Instrument '{instrument_spec['name']}' is not \"\n                           f\"designed for imaging observations!\")\n\n    arf_file = get_data_file(instrument_spec[\"arf\"])\n    rmf_file = get_data_file(instrument_spec[\"rmf\"])\n    arf = AuxiliaryResponseFile(arf_file)\n    rmf = RedistributionMatrixFile(rmf_file)\n\n    nx = instrument_spec[\"num_pixels\"]\n    plate_scale = instrument_spec[\"fov\"]/nx/60. # arcmin to deg\n    plate_scale_arcsec = plate_scale * 3600.0\n\n    if aimpt_shift is None:\n        aimpt_shift = np.zeros(2)\n    aimpt_shift = ensure_numpy_array(aimpt_shift).astype('float64')\n    aimpt_shift /= plate_scale_arcsec\n\n    if not instrument_spec[\"dither\"]:\n        dither_on = False\n    else:\n        dither_on = not no_dither\n    if dither_params is None:\n        dither_params = [8.0, 8.0, 1000.0, 707.0]\n    dither_dict = {\"x_amp\": dither_params[0],\n                   \"y_amp\": dither_params[1],\n                   \"x_period\": dither_params[2],\n                   \"y_period\": dither_params[3],\n                   \"dither_on\": dither_on,\n                   \"plate_scale\": plate_scale_arcsec}\n\n    event_params = {\"exposure_time\": exp_time,\n                    \"arf\": arf.filename,\n                    \"sky_center\": sky_center,\n                    \"pix_center\": np.array([0.5*(2*nx+1)]*2),\n                    \"num_pixels\": nx,\n                    \"plate_scale\": plate_scale,\n                    \"rmf\": rmf.filename,\n                    \"channel_type\": rmf.chan_type.upper(),\n                    \"telescope\": rmf.header[\"TELESCOP\"],\n                    \"instrument\": instrument_spec['name'],\n                    \"mission\": rmf.header.get(\"MISSION\", \"\"),\n                    \"nchan\": rmf.n_ch,\n                    \"roll_angle\": roll_angle,\n                    \"fov\": instrument_spec[\"fov\"],\n                    \"chan_lim\": [rmf.cmin, rmf.cmax],\n                    \"chips\": instrument_spec[\"chips\"],\n                    \"dither_params\": dither_dict,\n                    \"aimpt_coords\": instrument_spec[\"aimpt_coords\"],\n                    \"aimpt_shift\": aimpt_shift}\n\n    # Set up WCS\n\n    w = pywcs.WCS(naxis=2)\n    w.wcs.crval = event_params[\"sky_center\"]\n    w.wcs.crpix = event_params[\"pix_center\"]\n    w.wcs.cdelt = [-plate_scale, plate_scale]\n    w.wcs.ctype = [\"RA---TAN\",\"DEC--TAN\"]\n    w.wcs.cunit = [\"deg\"]*2\n\n    # Determine rotation matrix\n    rot_mat = get_rot_mat(roll_angle)\n\n    # Set up PSF\n    psf_type = instrument_spec[\"psf\"][0]\n    psf_class = psf_model_registry[psf_type]\n    psf = psf_class(instrument_spec, prng=prng)\n\n    all_events = defaultdict(list)\n\n    for i, src in enumerate(source_list):\n\n        mylog.info(f\"Detecting events from source {parameters['src_names'][i]}\")\n\n        # Step 1: Use ARF to determine which photons are observed\n\n        mylog.info(f\"Applying energy-dependent effective area from \"\n                   f\"{os.path.split(arf.filename)[-1]}.\")\n        refband = [parameters[\"emin\"][i], parameters[\"emax\"][i]]\n        if src.src_type == \"phlist\":\n            events = arf.detect_events_phlist(src.events.copy(), exp_time,\n                                              parameters[\"flux\"][i], \n                                              refband, prng=prng)\n        elif src.src_type.endswith(\"spectrum\"):\n            events = arf.detect_events_spec(src, exp_time, refband, prng=prng)\n\n        n_evt = events[\"energy\"].size\n\n        if n_evt == 0:\n            mylog.warning(\"No events were observed for this source!!!\")\n        else:\n\n            # Step 2: Assign pixel coordinates to events. Apply dithering and\n            # PSF. Clip events that don't fall within the detection region.\n\n            mylog.info(\"Pixeling events.\")\n\n            # Convert RA, Dec to pixel coordinates\n            xpix, ypix = w.wcs_world2pix(events[\"ra\"], events[\"dec\"], 1)\n\n            xpix -= event_params[\"pix_center\"][0]\n            ypix -= event_params[\"pix_center\"][1]\n\n            events.pop(\"ra\")\n            events.pop(\"dec\")\n\n            n_evt = xpix.size\n\n            # Rotate physical coordinates to detector coordinates\n\n            det = np.dot(rot_mat, np.array([xpix, ypix]))\n            detx = det[0, :] + event_params[\"aimpt_coords\"][0] + aimpt_shift[0]\n            dety = det[1, :] + event_params[\"aimpt_coords\"][1] + aimpt_shift[1]\n\n            # Add times to events\n            events['time'] = prng.uniform(size=n_evt, low=0.0,\n                                          high=event_params[\"exposure_time\"])\n\n            # Apply dithering\n\n            x_offset, y_offset = perform_dither(events[\"time\"], dither_dict)\n\n            detx -= x_offset\n            dety -= y_offset\n\n            # PSF scattering of detector coordinates\n\n            mylog.info(f\"Scattering events with a {psf}-based PSF.\")\n            detx, dety = psf.scatter(detx, dety, events[\"energy\"])\n\n            # Convert detector coordinates to chip coordinates.\n            # Throw out events that don't fall on any chip.\n\n            cx = np.trunc(detx)+0.5*np.sign(detx)\n            cy = np.trunc(dety)+0.5*np.sign(dety)\n\n            events[\"chip_id\"] = -np.ones(n_evt, dtype='int')\n            for i, chip in enumerate(event_params[\"chips\"]):\n                rtype = chip[0]\n                args = chip[1:]\n                r, _ = create_region(rtype, args, 0.0, 0.0)\n                inside = r.contains(PixCoord(cx, cy))\n                events[\"chip_id\"][inside] = i\n            keep = events[\"chip_id\"] > -1\n\n            mylog.info(f\"{n_evt-keep.sum()} events were rejected because \"\n                       f\"they do not fall on any CCD.\")\n            n_evt = keep.sum()\n\n            if n_evt == 0:\n                mylog.warning(\"No events are within the field \"\n                              \"of view for this source!!!\")\n            else:\n\n                # Keep only those events which fall on a chip\n\n                for key in events:\n                    events[key] = events[key][keep]\n\n                # Convert chip coordinates back to detector coordinates,\n                # unless the user has specified that they want subpixel\n                # resolution\n\n                if subpixel_res:\n                    events[\"detx\"] = detx[keep]\n                    events[\"dety\"] = dety[keep]\n                else:\n                    events[\"detx\"] = cx[keep] + \\\n                                     prng.uniform(low=-0.5, high=0.5, size=n_evt)\n                    events[\"dety\"] = cy[keep] + \\\n                                     prng.uniform(low=-0.5, high=0.5, size=n_evt)\n\n                # Convert detector coordinates back to pixel coordinates by\n                # adding the dither offsets back in and applying the rotation\n                # matrix again\n\n                det = np.array([events[\"detx\"] + x_offset[keep] -\n                                event_params[\"aimpt_coords\"][0] -\n                                aimpt_shift[0],\n                                events[\"dety\"] + y_offset[keep] -\n                                event_params[\"aimpt_coords\"][1] -\n                                aimpt_shift[1]])\n                pix = np.dot(rot_mat.T, det)\n\n                events[\"xpix\"] = pix[0,:] + event_params['pix_center'][0]\n                events[\"ypix\"] = pix[1,:] + event_params['pix_center'][1]\n\n        if n_evt > 0:\n            for key in events:\n                all_events[key] = np.concatenate([all_events[key], events[key]])\n\n    if len(all_events[\"energy\"]) == 0:\n        mylog.warning(\"No events from any of the sources in \"\n                      \"the catalog were detected!\")\n        for key in [\"xpix\", \"ypix\", \"detx\", \"dety\", \"time\", \n                    \"chip_id\", event_params[\"channel_type\"]]:\n            all_events[key] = np.array([])\n    else:\n        # Step 4: Scatter energies with RMF\n        mylog.info(f\"Scattering energies with \"\n                   f\"RMF {os.path.split(rmf.filename)[-1]}.\")\n        all_events = rmf.scatter_energies(all_events, prng=prng)\n\n    return all_events, event_params\n\n\ndef make_background(exp_time, instrument, sky_center, foreground=True,\n                    ptsrc_bkgnd=True, instr_bkgnd=True, no_dither=False,\n                    dither_params=None, roll_angle=0.0, subpixel_res=False,\n                    input_pt_sources=None, aimpt_shift=None, prng=None,\n                    **kwargs):\n    \"\"\"\n    Make background events.\n\n    Parameters\n    ----------\n    exp_time : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`\n        The exposure time to use, in seconds. \n    instrument : string\n        The name of the instrument to use, which picks an instrument\n        specification from the instrument registry. \n    sky_center : array, tuple, or list\n        The center RA, Dec coordinates of the observation, in degrees.\n    foreground : boolean, optional\n        Whether or not to include the Galactic foreground. Default: True\n    instr_bkgnd : boolean, optional\n        Whether or not to include the instrumental background. Default: True\n    no_dither : boolean, optional\n        If True, turn off dithering entirely. Default: False\n    dither_params : array-like of floats, optional\n        The parameters to use to control the size and period of the dither\n        pattern. The first two numbers are the dither amplitude in x and y\n        detector coordinates in arcseconds, and the second two numbers are\n        the dither period in x and y detector coordinates in seconds. \n        Default: [8.0, 8.0, 1000.0, 707.0].\n    ptsrc_bkgnd : boolean, optional\n        Whether or not to include the point-source background. Default: True\n    roll_angle : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`, optional\n        The roll angle of the observation in degrees. Default: 0.0\n    subpixel_res: boolean, optional\n        If True, event positions are not randomized within the pixels \n        within which they are detected. Default: False\n    input_pt_sources : string, optional\n        If set to a filename, input the point source positions, fluxes,\n        and spectral indices from an ASCII table instead of generating\n        them. Default: None\n    aimpt_shift : array-like, optional\n        A two-float array-like object which shifts the aimpoint on the \n        detector from the nominal position. Units are in arcseconds.\n        Default: None, which results in no shift from the nominal aimpoint. \n    prng : :class:`~numpy.random.RandomState` object, integer, or None\n        A pseudo-random number generator. Typically will only \n        be specified if you have a reason to generate the same \n        set of random numbers, such as for a test. Default is None, \n        which sets the seed based on the system time. \n    \"\"\"\n    if \"nH\" in kwargs or \"absorb_model\" in kwargs:\n        warnings.warn(\"The 'nH' and 'absorb_model' keyword arguments\"\n                      \"have been omitted. Please set the 'bkgnd_nH' \"\n                      \"and 'bkgnd_absorb_model' values in the SOXS\"\n                      \"configuration file if you want to change these \"\n                      \"values. \",\n                      DeprecationWarning)\n    from soxs.background import make_diffuse_background, \\\n        make_ptsrc_background\n    prng = parse_prng(prng)\n    exp_time = parse_value(exp_time, \"s\")\n    roll_angle = parse_value(roll_angle, \"deg\")\n    try:\n        instrument_spec = instrument_registry[instrument]\n    except KeyError:\n        raise KeyError(f\"Instrument {instrument} is not in the \"\n                       f\"instrument registry!\")\n    if not instrument_spec[\"imaging\"]:\n        raise RuntimeError(f\"Instrument '{instrument_spec['name']}' is not \"\n                           f\"designed for imaging observations!\")\n    fov = instrument_spec[\"fov\"]\n\n    input_events = defaultdict(list)\n\n    arf_file = get_data_file(instrument_spec[\"arf\"])\n    arf = AuxiliaryResponseFile(arf_file)\n    rmf_file = get_data_file(instrument_spec[\"rmf\"])\n    rmf = RedistributionMatrixFile(rmf_file)\n\n    if ptsrc_bkgnd:\n        mylog.info(\"Adding in point-source background.\")\n        ptsrc_events = make_ptsrc_background(exp_time, fov, sky_center,\n                                             area=1.2*arf.max_area,\n                                             input_sources=input_pt_sources,\n                                             prng=prng)\n        for key in [\"ra\", \"dec\", \"energy\"]:\n            input_events[key].append(ptsrc_events[key])\n        input_events[\"flux\"].append(ptsrc_events[\"flux\"])\n        input_events[\"emin\"].append(ptsrc_events[\"energy\"].min())\n        input_events[\"emax\"].append(ptsrc_events[\"energy\"].max())\n        input_events[\"src_names\"].append(\"ptsrc_bkgnd\")\n        events, event_params = generate_events(input_events, exp_time,\n                                               instrument, sky_center,\n                                               no_dither=no_dither,\n                                               dither_params=dither_params,\n                                               roll_angle=roll_angle,\n                                               subpixel_res=subpixel_res,\n                                               aimpt_shift=aimpt_shift,\n                                               prng=prng)\n        mylog.info(f\"Generated {events['energy'].size} photons from \"\n                   f\"the point-source background.\")\n    else:\n        nx = instrument_spec[\"num_pixels\"]\n        plate_scale = instrument_spec[\"fov\"]/nx/60.0\n        plate_scale_arcsec = plate_scale*3600.0\n        if aimpt_shift is None:\n            aimpt_shift = np.zeros(2)\n        aimpt_shift = ensure_numpy_array(aimpt_shift).astype('float64')\n        aimpt_shift /= plate_scale_arcsec\n        events = defaultdict(list)\n        if not instrument_spec[\"dither\"]:\n            dither_on = False\n        else:\n            dither_on = not no_dither\n        if dither_params is None:\n            dither_params = [8.0, 8.0, 1000.0, 707.0]\n        dither_dict = {\"x_amp\": dither_params[0],\n                       \"y_amp\": dither_params[1],\n                       \"x_period\": dither_params[2],\n                       \"y_period\": dither_params[3],\n                       \"dither_on\": dither_on,\n                       \"plate_scale\": instrument_spec[\"fov\"]/nx*60.0}\n        event_params = {\"exposure_time\": exp_time, \n                        \"fov\": instrument_spec[\"fov\"],\n                        \"num_pixels\": nx,\n                        \"pix_center\": np.array([0.5*(2*nx+1)]*2),\n                        \"channel_type\": rmf.header[\"CHANTYPE\"].upper(),\n                        \"sky_center\": sky_center,\n                        \"dither_params\": dither_dict,\n                        \"plate_scale\": plate_scale,\n                        \"chan_lim\": [rmf.cmin, rmf.cmax],\n                        \"rmf\": rmf_file, \"arf\": arf_file,\n                        \"telescope\": rmf.header[\"TELESCOP\"],\n                        \"instrument\": instrument_spec['name'],\n                        \"mission\": rmf.header.get(\"MISSION\", \"\"),\n                        \"nchan\": rmf.n_ch,\n                        \"roll_angle\": roll_angle,\n                        \"aimpt_coords\": instrument_spec[\"aimpt_coords\"],\n                        \"aimpt_shift\": aimpt_shift}\n\n    if \"chips\" not in event_params:\n        event_params[\"chips\"] = instrument_spec[\"chips\"]\n\n    instr_bkgnd &= instrument_spec[\"bkgnd\"] is not None\n\n    if foreground or instr_bkgnd:\n        bkg_events = make_diffuse_background(foreground, instr_bkgnd,\n            instrument_spec, event_params, arf, rmf, prng=prng)\n        for key in bkg_events:\n            events[key] = np.concatenate([events[key], bkg_events[key]])\n\n    return events, event_params\n\n\ndef make_background_file(out_file, exp_time, instrument, sky_center,\n                         overwrite=False, foreground=True, instr_bkgnd=True,\n                         ptsrc_bkgnd=True, no_dither=False, dither_params=None,\n                         subpixel_res=False, input_pt_sources=None, \n                         prng=None, **kwargs):\n    \"\"\"\n    Make an event file consisting entirely of background events. This will be \n    useful for creating backgrounds that can be added to simulations of sources.\n\n    Parameters\n    ----------\n    exp_time : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`\n        The exposure time to use, in seconds. \n    instrument : string\n        The name of the instrument to use, which picks an instrument\n        specification from the instrument registry. \n    sky_center : array, tuple, or list\n        The center RA, Dec coordinates of the observation, in degrees.\n    overwrite : boolean, optional\n        Whether or not to overwrite an existing file with the same name.\n        Default: False\n    foreground : boolean, optional\n        Whether or not to include the Galactic foreground. Default: True\n    instr_bkgnd : boolean, optional\n        Whether or not to include the instrumental background. Default: True\n    ptsrc_bkgnd : boolean, optional\n        Whether or not to include the point-source background. Default: True\n    no_dither : boolean, optional\n        If True, turn off dithering entirely. Default: False\n    dither_params : array-like of floats, optional\n        The parameters to use to control the size and period of the dither\n        pattern. The first two numbers are the dither amplitude in x and y\n        detector coordinates in arcseconds, and the second two numbers are\n        the dither period in x and y detector coordinates in seconds. \n        Default: [8.0, 8.0, 1000.0, 707.0].\n    subpixel_res: boolean, optional\n        If True, event positions are not randomized within the pixels \n        within which they are detected. Default: False\n    input_pt_sources : string, optional\n        If set to a filename, input the point source positions, fluxes,\n        and spectral indices from an ASCII table instead of generating\n        them. Default: None\n    prng : :class:`~numpy.random.RandomState` object, integer, or None\n        A pseudo-random number generator. Typically will only \n        be specified if you have a reason to generate the same \n        set of random numbers, such as for a test. Default is None, \n        which sets the seed based on the system time. \n    \"\"\"\n    if \"nH\" in kwargs or \"absorb_model\" in kwargs:\n        warnings.warn(\"The 'nH' and 'absorb_model' keyword arguments\"\n                      \"have been omitted. Please set the 'bkgnd_nH' \"\n                      \"and 'bkgnd_absorb_model' values in the SOXS\"\n                      \"configuration file if you want to change these \"\n                      \"values. \",\n                      DeprecationWarning)\n    if \"input_sources\" in kwargs:\n        warnings.warn(\"The 'input_sources' keyword argument has been changed \"\n                      \"to 'input_pt_sources' and is deprecated.\", \n                      DeprecationWarning)\n        input_pt_sources = kwargs.pop(\"input_sources\")\n    prng = parse_prng(prng)\n    events, event_params = make_background(exp_time, instrument, sky_center, \n                                           ptsrc_bkgnd=ptsrc_bkgnd, \n                                           foreground=foreground, \n                                           instr_bkgnd=instr_bkgnd,\n                                           no_dither=no_dither,\n                                           dither_params=dither_params, \n                                           subpixel_res=subpixel_res,\n                                           input_pt_sources=input_pt_sources,\n                                           prng=prng)\n    write_event_file(events, event_params, out_file, overwrite=overwrite)\n\n\ndef instrument_simulator(input_events, out_file, exp_time, instrument,\n                         sky_center, overwrite=False, instr_bkgnd=True, \n                         foreground=True, ptsrc_bkgnd=True, \n                         bkgnd_file=None, no_dither=False, \n                         dither_params=None, roll_angle=0.0, \n                         subpixel_res=False, aimpt_shift=None,\n                         input_pt_sources=None, prng=None):\n    \"\"\"\n    Take unconvolved events and create an event file from them. This\n    function calls generate_events to do the following:\n\n    1. Determines which events are observed using the ARF\n    2. Pixelizes the events, applying PSF effects and dithering\n    3. Determines energy channels using the RMF\n\n    and then calls make_background to add instrumental and astrophysical\n    backgrounds, unless a background file is provided, in which case\n    the background events are read from this file. The events are\n    then written out to a file.\n\n    Parameters\n    ----------\n    input_events : string, dict, or None\n        The unconvolved events to be used as input. Can be one of the\n        following:\n        1. The name of a SIMPUT catalog file.\n        2. A Python dictionary containing the following items:\n        \"ra\": A NumPy array of right ascension values in degrees.\n        \"dec\": A NumPy array of declination values in degrees.\n        \"energy\": A NumPy array of energy values in keV.\n        \"flux\": The flux of the entire source, in units of erg/cm**2/s.\n    out_file : string\n        The name of the event file to be written.\n    exp_time : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`\n        The exposure time to use, in seconds. \n    instrument : string\n        The name of the instrument to use, which picks an instrument\n        specification from the instrument registry. \n    sky_center : array, tuple, or list\n        The center RA, Dec coordinates of the observation, in degrees.\n    overwrite : boolean, optional\n        Whether or not to overwrite an existing file with the same name.\n        Default: False\n    instr_bkgnd : boolean, optional\n        Whether or not to include the instrumental/particle background. \n        Default: True\n    foreground : boolean, optional\n        Whether or not to include the local foreground. \n        Default: True\n    ptsrc_bkgnd : boolean, optional\n        Whether or not to include the point-source background. \n        Default: True\n    bkgnd_file : string, optional\n        If set, backgrounds will be loaded from this file and not generated\n        on the fly. Default: None\n    no_dither : boolean, optional\n        If True, turn off dithering entirely. Default: False\n    dither_params : array-like of floats, optional\n        The parameters to use to control the size and period of the dither\n        pattern. The first two numbers are the dither amplitude in x and y\n        detector coordinates in arcseconds, and the second two numbers are\n        the dither period in x and y detector coordinates in seconds. \n        Default: [8.0, 8.0, 1000.0, 707.0].\n    roll_angle : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`, optional\n        The roll angle of the observation in degrees. Default: 0.0\n    subpixel_res: boolean, optional\n        If True, event positions are not randomized within the pixels \n        within which they are detected. Default: False\n    aimpt_shift : array-like, optional\n        A two-float array-like object which shifts the aimpoint on the \n        detector from the nominal position. Units are in arcseconds.\n        Default: None, which results in no shift from the nominal aimpoint. \n    input_pt_sources : string, optional\n        If set to a filename, input the point source positions, fluxes,\n        and spectral indices from an ASCII table instead of generating\n        them. Default: None\n    prng : :class:`~numpy.random.RandomState` object, integer, or None\n        A pseudo-random number generator. Typically will only \n        be specified if you have a reason to generate the same \n        set of random numbers, such as for a test. Default is None, \n        which sets the seed based on the system time. \n\n    Examples\n    --------\n    >>> instrument_simulator(\"sloshing_simput.fits\", \"sloshing_evt.fits\", \n    ...                      300000.0, \"lynx_hdxi\", [30., 45.], overwrite=True)\n    \"\"\"\n    from soxs.background import add_background_from_file\n    if not out_file.endswith(\".fits\"):\n        out_file += \".fits\"\n    mylog.info(f\"Making observation of source in {out_file}.\")\n    # Make the source first\n    events, event_params = generate_events(input_events, exp_time, instrument, sky_center,\n                                           no_dither=no_dither, dither_params=dither_params, \n                                           roll_angle=roll_angle, subpixel_res=subpixel_res, \n                                           aimpt_shift=aimpt_shift, prng=prng)\n    # If the user wants backgrounds, either make the background or add an already existing\n    # background event file. It may be necessary to reproject events to a new coordinate system.\n    if bkgnd_file is None:\n        if not instr_bkgnd and not ptsrc_bkgnd and not foreground:\n            mylog.info(\"No backgrounds will be added to this observation.\")\n        else:\n            mylog.info(\"Adding background events.\")\n            bkg_events, _ = make_background(\n                exp_time, instrument, sky_center, foreground=foreground,\n                instr_bkgnd=instr_bkgnd, no_dither=no_dither,\n                dither_params=dither_params, ptsrc_bkgnd=ptsrc_bkgnd, prng=prng,\n                subpixel_res=subpixel_res, roll_angle=roll_angle,\n                aimpt_shift=aimpt_shift, input_pt_sources=input_pt_sources)\n            for key in events:\n                events[key] = np.concatenate([events[key], bkg_events[key]])\n    else:\n        mylog.info(f\"Adding background events from the file {bkgnd_file}.\")\n        if not os.path.exists(bkgnd_file):\n            raise IOError(f\"Cannot find the background event file {bkgnd_file}!\")\n        events = add_background_from_file(events, event_params, bkgnd_file)\n    if len(events[\"energy\"]) == 0:\n        mylog.warning(\"No events were detected from source or background!! We \"\n                      \"will not write an event file.\")\n    else:\n        write_event_file(events, event_params, out_file, overwrite=overwrite)\n    mylog.info(\"Observation complete.\")\n\n\ndef simulate_spectrum(spec, instrument, exp_time, out_file,\n                      instr_bkgnd=False, foreground=False,\n                      ptsrc_bkgnd=False, bkgnd_area=None,\n                      overwrite=False, prng=None, **kwargs):\n    \"\"\"\n    Generate a PI or PHA spectrum from a :class:`~soxs.spectra.Spectrum`\n    by convolving it with responses. To be used if one wants to \n    create a spectrum without worrying about spatial response. Similar\n    to XSPEC's \"fakeit\".\n\n    Parameters\n    ----------\n    spec : :class:`~soxs.spectra.Spectrum`\n        The spectrum to be convolved. If None is supplied, only backgrounds\n        will be simulated (if they are turned on).\n    instrument : string\n        The name of the instrument to use, which picks an instrument\n        specification from the instrument registry.\n    exp_time : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`\n        The exposure time in seconds.\n    out_file : string\n        The file to write the spectrum to.\n    instr_bkgnd : boolean, optional\n        Whether or not to include the instrumental/particle background. \n        Default: False\n    foreground : boolean, optional\n        Whether or not to include the local foreground.\n        Default: False\n    ptsrc_bkgnd : boolean, optional\n        Whether or not to include the unresolved point-source background. \n        Default: False\n    bkgnd_area : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`\n        The area on the sky for the background components, in square arcminutes.\n        Default: None, necessary to specify if any of the background components\n        are turned on. \n    overwrite : boolean, optional\n        Whether or not to overwrite an existing file. Default: False\n    prng : :class:`~numpy.random.RandomState` object, integer, or None\n        A pseudo-random number generator. Typically will only \n        be specified if you have a reason to generate the same \n        set of random numbers, such as for a test. Default is None, \n        which sets the seed based on the system time. \n\n    Examples\n    --------\n    >>> spec = soxs.Spectrum.from_file(\"my_spectrum.txt\")\n    >>> soxs.simulate_spectrum(spec, \"lynx_lxm\", 100000.0, \n    ...                        \"my_spec.pi\", overwrite=True)\n    \"\"\"\n    from soxs.events import _write_spectrum\n    from soxs.response import RedistributionMatrixFile, \\\n        AuxiliaryResponseFile\n    from soxs.spectra import ConvolvedSpectrum\n    from soxs.background.spectra import BackgroundSpectrum\n    from soxs.background.diffuse import read_instr_spectrum, \\\n        make_frgnd_spectrum, generate_channel_spectrum\n    from soxs.utils import soxs_cfg\n    if \"nH\" in kwargs or \"absorb_model\" in kwargs:\n        warnings.warn(\"The 'nH' and 'absorb_model' keyword arguments\"\n                      \"have been omitted. Please set the 'bkgnd_nH' \"\n                      \"and 'bkgnd_absorb_model' values in the SOXS\"\n                      \"configuration file if you want to change these \"\n                      \"values. \",\n                      DeprecationWarning)\n    prng = parse_prng(prng)\n    exp_time = parse_value(exp_time, \"s\")\n    try:\n        instrument_spec = instrument_registry[instrument]\n    except KeyError:\n        raise KeyError(f\"Instrument {instrument} is not in the instrument registry!\")\n    if foreground or instr_bkgnd or ptsrc_bkgnd:\n        if instrument_spec[\"grating\"]:\n            raise NotImplementedError(\"Backgrounds cannot be included in simulations \"\n                                      \"of gratings spectra at this time!\")\n        if bkgnd_area is None:\n            raise RuntimeError(\"The 'bkgnd_area' argument must be set if one wants \"\n                               \"to simulate backgrounds! Specify a value in square \"\n                               \"arcminutes.\")\n        bkgnd_area = np.sqrt(parse_value(bkgnd_area, \"arcmin**2\"))\n    elif spec is None:\n        raise RuntimeError(\"You have specified no source spectrum and no backgrounds!\")\n    arf_file = get_data_file(instrument_spec[\"arf\"])\n    rmf_file = get_data_file(instrument_spec[\"rmf\"])\n    arf = AuxiliaryResponseFile(arf_file)\n    rmf = RedistributionMatrixFile(rmf_file)\n\n    event_params = {\"RESPFILE\": os.path.split(rmf.filename)[-1],\n                    \"ANCRFILE\": os.path.split(arf.filename)[-1],\n                    \"TELESCOP\": rmf.header[\"TELESCOP\"],\n                    \"INSTRUME\": rmf.header[\"INSTRUME\"],\n                    \"MISSION\": rmf.header.get(\"MISSION\", \"\")}\n\n    out_spec = np.zeros(rmf.n_ch)\n\n    if spec is not None:\n        cspec = ConvolvedSpectrum.convolve(spec, arf)\n        out_spec += rmf.convolve_spectrum(cspec, exp_time, prng=prng)\n\n    fov = None if bkgnd_area is None else np.sqrt(bkgnd_area)\n\n    if foreground:\n        mylog.info(\"Adding in astrophysical foreground.\")\n        frgnd_spec = rmf.convolve_spectrum(make_frgnd_spectrum(arf, rmf),\n            exp_time, noisy=False, rate=True)\n        out_spec += generate_channel_spectrum(frgnd_spec, exp_time, bkgnd_area,\n                                              prng=prng)\n    if instr_bkgnd and instrument_spec[\"bkgnd\"] is not None:\n        mylog.info(\"Adding in instrumental background.\")\n        bkgnd_spec = instrument_spec[\"bkgnd\"]\n        # Temporary hack for ACIS-S\n        if \"aciss\" in instrument_spec[\"name\"]:\n            bkgnd_spec = bkgnd_spec[1]\n        bkgnd_spec = read_instr_spectrum(bkgnd_spec[0], bkgnd_spec[1])\n        out_spec += generate_channel_spectrum(bkgnd_spec, exp_time, bkgnd_area,\n                                              prng=prng)\n    if ptsrc_bkgnd:\n        mylog.info(\"Adding in background from unresolved point-sources.\")\n        bkgnd_nH = float(soxs_cfg.get(\"soxs\", \"bkgnd_nH\"))\n        absorb_model = soxs_cfg.get(\"soxs\", \"bkgnd_absorb_model\")\n        spec_plaw = BackgroundSpectrum.from_powerlaw(1.52, 0.0, 2.0e-7, emin=0.01,\n                                                     emax=10.0, nbins=300000)\n        spec_plaw.apply_foreground_absorption(bkgnd_nH, model=absorb_model)\n        cspec_plaw = ConvolvedSpectrum.convolve(spec_plaw.to_spectrum(fov), arf)\n        out_spec += rmf.convolve_spectrum(cspec_plaw, exp_time, prng=prng)\n\n    bins = (np.arange(rmf.n_ch)+rmf.cmin).astype(\"int32\")\n\n    _write_spectrum(bins, out_spec, exp_time, rmf.header[\"CHANTYPE\"], \n                    event_params, out_file, overwrite=overwrite)\n", "meta": {"hexsha": "d4f3f9115c498677847f3c056b42517ca5ca0cbb", "size": 37627, "ext": "py", "lang": "Python", "max_stars_repo_path": "soxs/instrument.py", "max_stars_repo_name": "jzuhone/sox", "max_stars_repo_head_hexsha": "034f973c8b66cd07ee904c414411a76759d9730a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "soxs/instrument.py", "max_issues_repo_name": "jzuhone/sox", "max_issues_repo_head_hexsha": "034f973c8b66cd07ee904c414411a76759d9730a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "soxs/instrument.py", "max_forks_repo_name": "jzuhone/sox", "max_forks_repo_head_hexsha": "034f973c8b66cd07ee904c414411a76759d9730a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1516290727, "max_line_length": 96, "alphanum_fraction": 0.6091902092, "include": true, "reason": "import numpy,import astropy", "num_tokens": 8528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241911813151, "lm_q2_score": 0.2909808723634538, "lm_q1q2_score": 0.18219016335780103}}
{"text": "import flavio\nfrom wilson import Wilson, wcxf\nfrom flavio.statistics.likelihood import Likelihood, FastLikelihood\nfrom flavio.statistics.probability import NormalDistribution\nfrom flavio.statistics.functions import pull, pvalue\nimport warnings\nimport pandas as pd\nimport numpy as np\nfrom collections import OrderedDict\nfrom math import ceil\nfrom .util import tree, get_datapath, multithreading_map\nfrom .ckm import get_ckm_schemes\nfrom multipledispatch import dispatch\nfrom copy import copy\nimport os\nfrom functools import partial\nfrom operator import itemgetter\nfrom numbers import Number\nimport inspect\nfrom flavio.math.optimize import minimize_robust\nfrom smelli import _flavio_up_to_date\nfrom itertools import chain\n\n\n# by default, smelli uses leading log accuracy for SMEFT running!\nWilson.set_default_option('smeft_accuracy', 'leadinglog')\n\n\nclass GlobalLikelihood(object):\n    \"\"\"Class that provides a global likelihood in SMEFT Wilson\n    coefficient space.\n\n    User methods:\n\n    - `log_likelihood`: return an instance of LieklihoodResult\n    given a dictionary of Wilson coefficients at a given scale\n    - `log_likelihood_wcxf`: return an instance of LieklihoodResult\n    given the path to a WCxf file\n    - `log_likelihood_wilson`: return an instance of LieklihoodResult+\n    given an instance of `wilson.Wilson`\n\n    Utility methods:\n\n    - `make_measurement`: compute the SM covariances. Note that it is only\n    necessary to call this method when changes to the default\n    parameters/uncertainties have been made\n    - `save_sm_covariances`, `load_sm_covariances`: Save the calculated SM\n    covariances or load them from data files\n    - `save_exp_covariances`, `load_exp_covariances`: Save the calculated\n    experimental central values and covariances or load them from data files\n\n    \"\"\"\n\n    _default_bases = {'SMEFT': 'Warsaw', 'WET': 'flavio'}\n\n    _fast_likelihoods_yaml_fixckm = [\n        'fast_likelihood_quarks_fixckm.yaml',\n        'fast_likelihood_leptons.yaml'\n    ]\n\n    _fast_likelihoods_yaml = [\n        'fast_likelihood_quarks.yaml',\n        'fast_likelihood_leptons.yaml'\n    ]\n\n    _likelihoods_yaml = [\n        'likelihood_ewpt.yaml',\n        'likelihood_eeww.yaml',\n        'likelihood_lept.yaml',\n        'likelihood_rd_rds.yaml',\n        'likelihood_lfu_fccc.yaml',\n        'likelihood_lfu_fcnc.yaml',\n        'likelihood_bcpv.yaml',\n        'likelihood_bqnunu.yaml',\n        'likelihood_lfv.yaml',\n        'likelihood_zlfv.yaml',\n        'likelihood_higgs.yaml',\n    ]\n\n    def __init__(self, eft='SMEFT', basis=None,\n                 par_dict=None,\n                 include_likelihoods=None,\n                 exclude_likelihoods=None,\n                 Nexp=5000,\n                 exp_cov_folder=None,\n                 sm_cov_folder=None,\n                 custom_likelihoods=None,\n                 fix_ckm=False,\n                 ckm_scheme='CKMSchemeRmuBtaunuBxlnuDeltaM'):\n        \"\"\"Initialize the likelihood.\n\n        Optionally, a dictionary of parameters can be passed as `par_dict`.\n        If not given (or not complete), flavio default parameter values will\n        be used. Note that the CKM elements in `par_dict` will be ignored as\n        the \"true\" CKM elements will be extracted for each parameter point\n        from the measurement of four input observables:\n        - `'RKpi(P+->munu)'`\n        - `'BR(B+->taunu)'`\n        - `'BR(B->Xcenu)'`\n        - `'DeltaM_d/DeltaM_s'`\n\n        Parameters:\n\n        - eft: a WCxf EFT, must be one of 'SMEFT' (default) or 'WET'.\n        - basis: a WCxf basis, defaults to 'Warsaw' for SMEFT and 'flavio'\n          for WET.\n        - include_likelihoods: a list of strings specifying the likelihoods\n          to be included (default: all of them). Note that this cannot be used\n          to add likelihoods.\n        - exclude_likelihoods: a list of strings specifying the likelihoods\n          to be excluded (default: none of them).\n        - Nexp: number of random evaluations of the experimental likelihood\n          used to extract the covariance matrix for \"fast likelihood\"\n          instances. Defaults to 5000.\n        - exp_cov_folder: directory containing saved expererimental\n          covariances. The data files have to be in the format exported by\n          `save_exp_covariances`.\n        - sm_cov_folder: directory containing saved SM\n          covariances. The data files have to be in the format exported by\n          `save_sm_covariances`.\n        - custom_likelihoods: a dictionary in which each value is a list of\n          observables and each key is a string that serves as user-defined\n          name. For each item of the dictionary, a custom likelihood will be\n          computed.\n        - fix_ckm: If False (default), automatically determine the CKM elements\n          in the presence of new physics in processes used to determine these\n          elements in the SM. If set to True, the CKM elements are fixed to\n          their SM values, which can lead to inconsistent results, but also\n          to a significant speedup in specific cases.\n        - ckm_scheme: A string with the name of the class defining the CKM\n          scheme.\n        \"\"\"\n        self.eft = eft\n        self.basis = basis or self._default_bases[self.eft]\n        par_dict = par_dict or {}  # initialize empty if not given\n        # take missing parameters from flavio defaults\n        self.par_dict_default = flavio.default_parameters.get_central_all()\n        self.par_dict_default.update(par_dict)\n        self._par_dict_sm = None\n        self._observables = None\n        self.fix_ckm = fix_ckm\n        if self.fix_ckm:\n            self._fast_likelihoods_yaml = self._fast_likelihoods_yaml_fixckm\n        try:\n            self._ckm_scheme = get_ckm_schemes()[ckm_scheme]\n            self._ckm_scheme_name = ckm_scheme\n        except:\n            raise ValueError(\"CKM scheme '{}' is not defined.\".format(ckm_scheme))\n        self.likelihoods = {}\n        self.fast_likelihoods = {}\n        self._custom_likelihoods_dict = custom_likelihoods or {}\n        self.custom_likelihoods = {}\n        self._load_likelihoods(include_likelihoods=include_likelihoods,\n                               exclude_likelihoods=exclude_likelihoods)\n        self._all_likelihoods = {\n            'global': _global_llh(self),\n            **self.fast_likelihoods,\n            **self.likelihoods,\n            **self.custom_likelihoods,\n        }\n        self._Nexp = Nexp\n        if exp_cov_folder is not None:\n            self.load_exp_covariances(exp_cov_folder)\n        self._sm_cov_loaded = False\n        try:\n            if sm_cov_folder is None:\n                self.load_sm_covariances(get_datapath('smelli', 'data/cache'))\n            else:\n                self.load_sm_covariances(sm_cov_folder)\n            self._sm_cov_loaded = True\n            self.make_measurement()\n        except (KeyboardInterrupt, SystemExit):\n            raise\n        except:\n            warnings.warn(\"There was a problem loading the SM covariances. \"\n                          \"Please recompute them with `make_measurement`.\")\n        self._log_likelihood_sm = None\n        self._obstable_sm = None\n\n    def _load_likelihoods(self,\n                          include_likelihoods=None,\n                          exclude_likelihoods=None):\n        if include_likelihoods is not None and exclude_likelihoods is not None:\n            raise ValueError(\"include_likelihoods and exclude_likelihoods \"\n                             \"should not be specified simultaneously.\")\n        for argument_name, argument in [('exclude_likelihoods', exclude_likelihoods), ('include_likelihoods',include_likelihoods)]:\n            if argument:\n                unknown_likelihoods = set(argument) - set(self._fast_likelihoods_yaml + self._likelihoods_yaml)\n                if unknown_likelihoods:\n                    raise ValueError(\"{} contains unknown likelihoods: {}\".format(argument_name,unknown_likelihoods))\n        # load ckm parameters for given CKM scheme\n        par_ckm_file = 'par_ckm_{}.yaml'.format(self._ckm_scheme_name)\n        with open(self._get_yaml_path(par_ckm_file), 'r') as f:\n            par_ckm_dict = flavio.io.yaml.load_include(f)\n        for fn in self._fast_likelihoods_yaml:\n            if include_likelihoods is not None and fn not in include_likelihoods:\n                continue\n            if exclude_likelihoods is not None and fn in exclude_likelihoods:\n                continue\n            with open(self._get_yaml_path(fn), 'r') as f:\n                yaml_dict = flavio.io.yaml.load_include(f)\n                if not self.fix_ckm:\n                    yaml_dict['par_obj'] = par_ckm_dict\n                try:\n                    L = FastLikelihood.load_dict(yaml_dict)\n                    meas_yaml = set(yaml_dict['include_measurements'])\n                    meas_loaded = set(L.full_measurement_likelihood.get_measurements)\n                    meas_missing = meas_yaml-meas_loaded\n                except AssertionError as e:\n                    to_upgrade = 'smelli' if _flavio_up_to_date else 'flavio'\n                    raise AssertionError('{}. Please upgrade {} to the latest version.'.format(e,to_upgrade))\n                if meas_missing:\n                    to_upgrade = 'smelli' if _flavio_up_to_date else 'flavio'\n                    raise AssertionError('The measurements {} have not been found. Please upgrade {} to the latest version.'.format(meas_missing,to_upgrade))\n            self.fast_likelihoods[fn] = L\n        for fn in self._likelihoods_yaml:\n            if include_likelihoods is not None and fn not in include_likelihoods:\n                continue\n            if exclude_likelihoods is not None and fn in exclude_likelihoods:\n                continue\n            if self.eft != 'SMEFT' and fn in ['likelihood_ewpt.yaml',\n                                              'likelihood_eeww.yaml',\n                                              'likelihood_zlfv.yaml',\n                                              'likelihood_higgs.yaml',]:\n                continue\n            with open(self._get_yaml_path(fn), 'r') as f:\n                yaml_dict = flavio.io.yaml.load_include(f)\n                try:\n                    L = Likelihood.load_dict(yaml_dict)\n                    meas_yaml = set(yaml_dict['include_measurements'])\n                    meas_loaded = set(L.measurement_likelihood.get_measurements)\n                    meas_missing = meas_yaml-meas_loaded\n                except AssertionError as e:\n                    to_upgrade = 'smelli' if _flavio_up_to_date else 'flavio'\n                    raise AssertionError('{}. Please upgrade {} to the latest version.'.format(e,to_upgrade))\n                if meas_missing:\n                    to_upgrade = 'smelli' if _flavio_up_to_date else 'flavio'\n                    raise AssertionError('The measurements {} have not been found. Please upgrade {} to the latest version.'.format(meas_missing,to_upgrade))\n            self.likelihoods[fn] = L\n        for name, observables in self._custom_likelihoods_dict.items():\n            L = CustomLikelihood(self, observables)\n            self.custom_likelihoods['custom_' + name] = L\n\n    def _get_yaml_path(self, name):\n        \"\"\"Return a path for the YAML file specified by `name`.\n        If a YAML file with that name is found in the package's data\n        directory, that is used. Otherwise, `name` is assumed to be a path.\n\n        Raises `FileNotFoundError` if path does not exists.\n        \"\"\"\n        path = get_datapath('smelli', 'data/yaml/' + name)\n        if os.path.exists(path):\n            return path\n        path = get_datapath('smelli', 'data/yaml/' + name + '.yaml')\n        if os.path.exists(path):\n            return path\n        if os.path.exists(name):\n            return name\n        if os.path.exists(name + '.yaml'):\n            return name + '.yaml'\n        else:\n            raise FileNotFoundError(\"Likelihood YAML file '{}' was not found\".format(name))\n\n    def make_measurement(self, *args, **kwargs):\n        \"\"\"Initialize the likelihood by producing a pseudo-measurement containing both\n        experimental uncertainties as well as theory uncertainties stemming\n        from nuisance parameters.\n\n        Optional parameters:\n\n        - `N`: number of random computations for the SM covariance (computing\n          time is proportional to it; more means less random fluctuations.)\n        - `Nexp`: number of random computations for the experimental covariance.\n          This is much less expensive than the theory covariance, so a large\n          number can be afforded (default: 5000).\n        - `threads`: number of parallel threads for the SM\n          covariance computation. Defaults to 1 (no parallelization).\n        - `force`: if True, will recompute SM covariance even if it\n          already has been computed. Defaults to False.\n        - `force_exp`: if True, will recompute experimental central values and\n          covariance even if they have already been computed. Defaults to False.\n        \"\"\"\n        if 'Nexp' not in kwargs:\n            kwargs['Nexp'] = self._Nexp\n        for name, flh in self.fast_likelihoods.items():\n            flh.make_measurement(*args, **kwargs)\n        self._sm_cov_loaded = True\n\n    def save_sm_covariances(self, folder):\n        for name, flh in self.fast_likelihoods.items():\n            if self.fix_ckm:\n                name = name + '_fix_ckm'\n            else:\n                name = name + '_' + self._ckm_scheme_name\n            filename = os.path.join(folder, name + '.p')\n            flh.sm_covariance.save(filename)\n\n    def load_sm_covariances(self, folder):\n        for name, flh in self.fast_likelihoods.items():\n            if self.fix_ckm:\n                name = name + '_fix_ckm'\n            else:\n                name = name + '_' + self._ckm_scheme_name\n            filename = os.path.join(folder, name + '.p')\n            flh.sm_covariance.load(filename)\n\n    def save_exp_covariances(self, folder):\n        for name, flh in self.fast_likelihoods.items():\n            filename = os.path.join(folder, name + '.p')\n            flh.exp_covariance.save(filename)\n\n    def load_exp_covariances(self, folder):\n        for name, flh in self.fast_likelihoods.items():\n            filename = os.path.join(folder, name + '.p')\n            flh.exp_covariance.load(filename)\n\n    @property\n    def observables(self):\n        if self._observables is None:\n            self._observables = set.union(*(\n                set(lh.observables) for lh in chain(\n                    self.fast_likelihoods.values(),\n                    self.likelihoods.values()\n                )\n            ))\n        return self._observables\n\n    @property\n    def log_likelihood_sm(self):\n        if self._log_likelihood_sm is None:\n            self._log_likelihood_sm = self._log_likelihood(self.par_dict_sm, flavio.WilsonCoefficients())\n        return self._log_likelihood_sm\n\n    def _check_sm_cov_loaded(self):\n        \"\"\"Check if the SM covariances have been computed or loaded.\"\"\"\n        if not self._sm_cov_loaded:\n            raise ValueError(\"Please load or compute the SM covariances first\"\n                             \" by calling `make_measurement`.\")\n\n    def get_ckm_sm(self):\n        Vus, Vcb, Vub, delta = self._ckm_scheme.ckm_np(w=None)\n        return {'Vus': Vus, 'Vcb': Vcb, 'Vub': Vub, 'delta': delta}\n\n    @property\n    def par_dict_sm(self):\n        \"\"\"Return the dictionary of parameters where the four CKM parameters\n        `Vus`, `Vcb`, `Vub`, `delta` have been replaced by their\n        \"true\" values extracted assuming the SM.\n        They should be almost (but not exactly) equal to the default\n        flavio CKM parameters.\n\n        Note that if `fix_ckm` is set to `True`, this method actually\n        returns the default parameter values.\n        \"\"\"\n        if self.fix_ckm:\n            return self.par_dict_default\n        if self._par_dict_sm is None:\n            par_dict_sm = self.par_dict_default.copy()\n            par_dict_sm.update(self.get_ckm_sm())\n            self._par_dict_sm = par_dict_sm\n        return self._par_dict_sm\n\n    @property\n    def obstable_sm(self):\n        self._check_sm_cov_loaded()\n        if self._obstable_sm is None:\n            info = tree()  # nested dict\n            for flh_name, flh in self.fast_likelihoods.items():\n                # loop over fast likelihoods: they only have a single \"measurement\"\n                m = flh.pseudo_measurement\n                ml = flh.full_measurement_likelihood\n                pred_sm = ml.get_predictions_par(self.par_dict_sm,\n                                                 flavio.WilsonCoefficients())\n                sm_cov = flh.sm_covariance.get(force=False)\n                _, exp_cov = flh.exp_covariance.get(force=False)\n                inspire_dict = self._get_inspire_dict(flh.observables, ml)\n                for i, obs in enumerate(flh.observables):\n                    info[obs]['lh_name'] = flh_name\n                    info[obs]['name'] = obs if isinstance(obs, str) else obs[0]\n                    info[obs]['th. unc.'] = np.sqrt(sm_cov[i, i])\n                    info[obs]['experiment'] = m.get_central(obs)\n                    info[obs]['exp. unc.'] = np.sqrt(exp_cov[i, i])\n                    info[obs]['exp. PDF'] = NormalDistribution(m.get_central(obs), np.sqrt(exp_cov[i, i]))\n                    info[obs]['inspire'] = sorted(set(inspire_dict[obs]))\n                    info[obs]['ll_sm'] = m.get_logprobability_single(obs, pred_sm[obs])\n                    info[obs]['ll_central'] = m.get_logprobability_single(obs, m.get_central(obs))\n            for lh_name, lh in self.likelihoods.items():\n                # loop over \"normal\" likelihoods\n                ml = lh.measurement_likelihood\n                pred_sm = ml.get_predictions_par(self.par_dict_sm,\n                                                 flavio.WilsonCoefficients())\n                inspire_dict = self._get_inspire_dict(lh.observables, ml)\n                for i, obs in enumerate(lh.observables):\n                    obs_dict = flavio.Observable.argument_format(obs, 'dict')\n                    obs_name = obs_dict.pop('name')\n                    with warnings.catch_warnings():\n                        warnings.simplefilter(\"ignore\")\n                        p_comb = flavio.combine_measurements(\n                            obs_name,\n                            include_measurements=ml.get_measurements,\n                            **obs_dict)\n                    info[obs]['experiment'] = p_comb.central_value\n                    info[obs]['exp. unc.'] = max(p_comb.error_left, p_comb.error_right)\n                    info[obs]['exp. PDF'] = p_comb\n                    info[obs]['inspire'] = sorted(set(inspire_dict[obs]))\n                    info[obs]['th. unc.'] = 0\n                    info[obs]['lh_name'] = lh_name\n                    info[obs]['name'] = obs if isinstance(obs, str) else obs[0]\n                    info[obs]['ll_sm'] = p_comb.logpdf([pred_sm[obs]])\n                    if info[obs]['ll_sm'] == -np.inf:\n                        info[obs]['ll_sm'] = -1e100\n                    info[obs]['ll_central'] = p_comb.logpdf([p_comb.central_value])\n            self._obstable_sm = info\n        return self._obstable_sm\n\n    def get_wilson(self, wc_dict, scale):\n        return Wilson(wc_dict, scale=scale, eft=self.eft, basis=self.basis)\n\n    def _log_likelihood(self, par_dict, w):\n        \"\"\"Return the log-likelihood as a dictionary for an instance of\n        `wilson.Wilson`.\"\"\"\n        ll = {}\n        for name, flh in self.fast_likelihoods.items():\n            ll[name] = flh.log_likelihood(par_dict, w, delta=True)\n        for name, lh in self.likelihoods.items():\n            ll[name] = lh.log_likelihood(par_dict, w, delta=True)\n        for name, clh in self.custom_likelihoods.items():\n            ll[name] = clh.log_likelihood(par_dict, w, delta=True)\n        return ll\n\n    @dispatch(dict)\n    def parameter_point(self, wc_dict, scale=None):\n        \"\"\"Choose a point in parameter space by providing a dictionary of\n        Wilson coefficient values (with keys corresponding to WCxf Wilson\n        coefficient names) and the input scale.\"\"\"\n        if not scale:\n            raise ValueError(\"You need to provide a scale\")\n        w = self.get_wilson(wc_dict, scale)\n        return GlobalLikelihoodPoint(self, w, fix_ckm=self.fix_ckm)\n\n    @dispatch(dict, (int, float))\n    def parameter_point(self, wc_dict, scale):\n        \"\"\"Choose a point in parameter space by providing a dictionary of\n        Wilson coefficient values (with keys corresponding to WCxf Wilson\n        coefficient names) and the input scale.\"\"\"\n        w = self.get_wilson(wc_dict, scale)\n        return GlobalLikelihoodPoint(self, w, fix_ckm=self.fix_ckm)\n\n    @dispatch(str)\n    def parameter_point(self, filename):\n        \"\"\"Choose a point in parameter space by providing the path to a WCxf\n        file.\"\"\"\n        with open(filename, 'r') as f:\n            wc = wcxf.WC.load(f)\n        w = Wilson.from_wc(wc)\n        return GlobalLikelihoodPoint(self, w, fix_ckm=self.fix_ckm)\n\n    @dispatch(Wilson)\n    def parameter_point(self, w):\n        \"\"\"Choose a point in parameter space by providing an instance\n        of `wilson.Wilson`.\"\"\"\n        return GlobalLikelihoodPoint(self, w, fix_ckm=self.fix_ckm)\n\n    @staticmethod\n    def _get_inspire_dict(observables, ml):\n        inspire_dict = {}\n        obs_set = set(observables)\n        for m_name in ml.get_measurements:\n            m_obj = flavio.Measurement[m_name]\n            for obs in set(m_obj.all_parameters) & obs_set:\n                if obs in inspire_dict:\n                    inspire_dict[obs].append(m_obj.inspire)\n                else:\n                    inspire_dict[obs]=[m_obj.inspire]\n        return inspire_dict\n\n    def number_observations_dict(self, exclude_observables=None):\n        \"\"\"Get a dictionary of the number of \"observations\" for each\n        sublikelihood.\n\n        Here, an \"observation\" is defined as an individual measurment\n        of an observable. Thus, the number of observations is always\n        >= the number of observables.\n        \"\"\"\n        nobs_dict = {}\n        for name, flh in self.fast_likelihoods.items():\n            nobs_dict[name] = len(set(flh.observables) - set(exclude_observables or []))\n        for name, lh in self.likelihoods.items():\n            ml =  lh.measurement_likelihood\n            nobs_dict[name] = ml.get_number_observations(\n                exclude_observables=exclude_observables\n            )\n        for name, clh in self.custom_likelihoods.items():\n            nobs_dict[name] = clh.get_number_observations()\n        nobs_dict['global'] = sum([v for k, v in nobs_dict.items() if 'custom_' not in k])\n        return nobs_dict\n\n    def plot_data_2d(self,\n                     wc_fct,\n                     scale,\n                     x_min, x_max, y_min, y_max,\n                     x_log=False, y_log=False,\n                     steps=20,\n                     threads=1,\n                     pool=None):\n        \"\"\"Compute the likelihood on a grid of two non-zero Wilson coefficients.\n\n        This method is meant for producing contour plots with `flavio.plots`\n        and `matplotlib` in the plane of two Wilson coefficients.\n\n        Parameters:\n\n        - `wc_fct`: function with two arguments x and y returning a dictionary\n                    with Wilson coefficients\n        - `scale`: either a function with two arguments x and y returning the\n                   renormalization scale in GeV, or a numerical value fixing the\n                   scale\n        - `x_min`: minimum value of Wilson coefficient on x axis\n        - `x_max`: maximum value of Wilson coefficient on x axis\n        - `y_min`: minimum value of Wilson coefficient on y axis\n        - `y_max`: maximum value of Wilson coefficient on y axis\n        - `x_log`: boolean specifying whether logspace should be used for x\n                   values (default: False)\n        - `y_log`: boolean specifying whether logspace should be used for y\n                   values (default: False)\n        - `steps`: number of steps in each direction. The computing time scales\n                   with the square of this number. (default: 20)\n        - `threads`: number of threads for parallel computation (default: 1)\n        - `pool`: either `None` or `pool` object for parallel computation. If\n                  `pool` object is provided, `threads` is ignored.\n                  (default: None)\n\n        Returns:\n\n        A dictionary of the  form\n        `{'likelihood_A': dat_A, 'likelihood_B': dat_B, ...}`\n        where `'likelihood_A'` etc. are the names of the sub- and custom\n        likelihoods (as return by `GlobalLikelihoodPoint.log_likelihood_dict`)\n        and `dat_A` etc. are dictionaries with the keys `x`, `y`, `z`, that\n        can be directly fed to the `flavio.plots.contour` plot function.\n        \"\"\"\n        if x_log:\n            _x = np.logspace(x_min, x_max, steps)\n        else:\n            _x = np.linspace(x_min, x_max, steps)\n        if y_log:\n            _y = np.logspace(y_min, y_max, steps)\n        else:\n            _y = np.linspace(y_min, y_max, steps)\n        x, y = np.meshgrid(_x, _y)\n        xy = np.array([x, y]).reshape(2, steps**2).T\n        xy_enumerated = list(enumerate(xy))\n        if isinstance(scale,Number):\n            scale_fct = partial(_scale_fct_fixed, scale=scale)\n        else:\n            scale_fct = scale\n        ll = partial(_log_likelihood_2d, gl=self, wc_fct=wc_fct, scale_fct=scale_fct)\n        ll_dict_list_enumerated = multithreading_map(ll, xy_enumerated,\n            threads=threads, pool=pool)\n        ll_dict_list = [\n            ll_dict[1] for ll_dict in\n            sorted(ll_dict_list_enumerated, key=itemgetter(0))\n        ]\n        plotdata = {}\n        keys = ll_dict_list[0].keys()  # look at first dict to fix keys\n        for k in keys:\n            z = -2 * np.array([ll_dict[k] for ll_dict in ll_dict_list]).reshape((steps, steps))\n            plotdata[k] = {'x': x, 'y': y, 'z': z}\n        return plotdata\n\n    def chi2_min(self,\n                 wc_fct,\n                 scale,\n                 methods = ('SLSQP', 'MIGRAD', 'L-BFGS-B'),\n                 include_likelihoods=None,\n                 exclude_likelihoods=None,\n                 plotdata=None,\n                 initial_guesses=None,\n                 n=None,\n                 threads=1,\n                 pool=None):\n        \"\"\"Find the minimum of -2*log-likelihood for a given function of Wilson\n           coefficients and a scale.\n\n        Parameters:\n\n        - `wc_fct`: function with either n>=1 arguments or one argument being\n          an array of length n>1 and which returns a dictionary with Wilson\n          coefficients.\n        - `scale`: either a function returning the renormalization scale in GeV,\n          or a numerical value fixing the scale. If it is a function, it must\n          have either n>=1 arguments or one argument being an array of length\n          n>1.\n        - methods: tuple of methods to try consecutively. (default:\n          `('SLSQP', 'MIGRAD', 'L-BFGS-B')`)\n        - include_likelihoods: a list of strings specifying the likelihoods\n          to be included (default: all of them).\n        - exclude_likelihoods: a list of strings specifying the likelihoods to\n          be excluded (default: none of them).\n        - `plotdata`: the result of `plot_data_2d` that will be used for\n          extracting the initial guesses for the minimization in the 2D case\n          (default: None)\n        - `initial_guesses`: a dictionary with initial guesses for the\n          minimization. The keys are strings with the names of the individual\n          likelihoods, the values are arrays (or lists) of length n. This\n          overrides initial guesses extracted from `plotdata` (default: None)\n        - `n`: number of variables. Has to be provided only if `wc_fct` has a\n           single argument (an array of length n) and neither `plotdata` nor\n          `initial_guesses` is given. (default: None)\n        - `threads`: number of threads for parallel computation (default: 1)\n        - `pool`: either `None` or `pool` object for parallel computation. If\n          `pool` object is provided, `threads` is ignored. (default: None)\n\n        Returns:\n\n        A dictionary of the  form\n        `{'likelihood_A': dat_A, 'likelihood_B': dat_B, ...}`\n        where `'likelihood_A'` etc. are the names of the sub- and custom\n        likelihoods (as return by `GlobalLikelihoodPoint.log_likelihood_dict`)\n        and `dat_A` etc. are dictionaries with the keys `z_min`, `coords_min`,\n        where the values of `z_min` and `coords_min` are a number and an array\n        of length n, respectively.\n        \"\"\"\n        if include_likelihoods is not None and exclude_likelihoods is not None:\n            raise ValueError(\"include_likelihoods and exclude_likelihoods \"\n                             \"should not be specified simultaneously.\")\n        if isinstance(scale,Number):\n            scale_fct = partial(_scale_fct_fixed, scale=scale)\n        else:\n            scale_fct = scale\n        likelihoods = {\n            k for k in self._all_likelihoods.keys()\n            if ((include_likelihoods is None and exclude_likelihoods is None)\n            or (include_likelihoods is not None and k in include_likelihoods)\n            or (exclude_likelihoods is not None and k not in exclude_likelihoods))\n        }\n        n_fct = len(inspect.getfullargspec(wc_fct).args)\n        if plotdata is not None:\n            n_args = 2\n            if n is not None:\n                warnings.warn(f\"Since `plotdata` is provided, `n={n}` \"\n                              \" is ignored.\")\n            _initial_guesses = {k: np.zeros(n_args) for k in likelihoods}\n            for k in _initial_guesses.keys():\n                x,y,z = (plotdata[k][i] for i in 'xyz')\n                minimum = (z == np.min(z))\n                _initial_guesses[k] = [np.median(x[minimum]), np.median(y[minimum])]\n            if initial_guesses is not None:\n                _initial_guesses.update(initial_guesses)\n        elif initial_guesses is not None:\n            if n is not None:\n                warnings.warn(f\"Since `initial_guesses` is provided, `n={n}` \"\n                              \" is ignored.\")\n            n_args = len(next(iter(initial_guesses.values())))\n            _initial_guesses = {k: np.zeros(n_args) for k in likelihoods}\n            _initial_guesses.update(initial_guesses)\n        elif n_fct > 1:\n            n_args = n_fct\n            if n is not None:\n                warnings.warn(f\"Since `wc_fct` has {n_fct} arguments, `n={n}` \"\n                              \" is ignored.\")\n            _initial_guesses = {k: np.zeros(n_args) for k in likelihoods}\n        elif n is not None:\n            n_args = n\n            _initial_guesses = {k: np.zeros(n_args) for k in likelihoods}\n        else:\n            raise ValueError(\n                'The number of variables `n` has to be provided as an argument '\n                'if `wc_fct` has a single argument (which can be an array of '\n                'length n) and neither `plotdata` nor `initial_guesses` is '\n                'given.'\n            )\n        _initial_guesses = list(_initial_guesses.items())\n\n        array_input = n_args != n_fct\n        best_fit_point = partial(\n            _best_fit_point,\n            gl=self,\n            wc_fct=wc_fct,\n            scale_fct=scale_fct,\n            array_input=array_input,\n            methods=methods,\n        )\n        bf_list = multithreading_map(best_fit_point, _initial_guesses,\n            threads=threads, pool=pool)\n        bf_dict = dict(list(bf_list))\n        return bf_dict\n\n\ndef _scale_fct_fixed(*args, scale=0):\n    \"\"\"\n    This is a helper function that is necessary because multiprocessing requires\n    a picklable (i.e. top-level) object for parallel computation.\n    \"\"\"\n    return scale\n\ndef _log_likelihood_2d(xy_enumerated, gl, wc_fct, scale_fct):\n    \"\"\"Compute the likelihood on a 2D grid of 2 Wilson coefficients.\n\n    This function is necessary because multiprocessing requires a picklable\n    (i.e. top-level) object for parallel computation.\n    \"\"\"\n    number, (x, y) = xy_enumerated\n    pp = gl.parameter_point(wc_fct(x, y), scale_fct(x, y))\n    ll_dict = pp.log_likelihood_dict()\n    return (number, ll_dict)\n\ndef _best_fit_point(initial_guess, gl, wc_fct, scale_fct, array_input, methods):\n    llh_name, x0 = initial_guess\n    llh = (gl.fast_likelihoods.get(llh_name)\n           or gl.likelihoods.get(llh_name)\n           or gl.custom_likelihoods.get(llh_name)\n           or (_global_llh(gl) if llh_name == 'global' else None))\n    llh_sm = (0 if llh_name == 'global' else gl.log_likelihood_sm[llh_name])\n    if array_input:\n        def chi2(x):\n            w = gl.get_wilson(wc_fct(x), scale_fct(x))\n            gp = gl.parameter_point(w)\n            try:\n                res = -2*(llh.log_likelihood(gp.par_dict_np, w, delta=True)-llh_sm)\n            except ValueError as e:\n                if (\n                    'The extraction of CKM elements failed.' in str(e)\n                    or\n                    'math domain error' in str(e)\n                ):\n                    res = np.inf\n                else:\n                    raise\n            return res\n    else:\n        def chi2(x):\n            w = gl.get_wilson(wc_fct(*x), scale_fct(*x))\n            gp = gl.parameter_point(w)\n            try:\n                res = -2*(llh.log_likelihood(gp.par_dict_np, w, delta=True)-llh_sm)\n            except ValueError as e:\n                if (\n                    'The extraction of CKM elements failed.' in str(e)\n                    or\n                    'math domain error' in str(e)\n                ):\n                    res = np.inf\n                else:\n                    raise\n            return res\n    try:\n        res = minimize_robust(chi2, x0, methods=methods)\n        if not res.success:\n            x = [np.nan]*len(x0)\n            z = np.nan\n            warnings.warn(\"Optimization failed during computation of best-fit point of {}: {}\"\n            ''.format(llh_name, res.message))\n        else:\n            x = res.x\n            z = res.fun\n    except Exception as e:\n        x = [np.nan]*len(x0)\n        z = np.nan\n        warnings.warn('\\nERROR during computation of best-fit point of {}:\\n{}'\n                      ''.format(llh_name,e))\n    return (llh_name, {'coords_min':np.array(x), 'z_min':z})\n\n\nclass _global_llh(object):\n    def __init__(self, gl):\n        self.gl = gl\n    def log_likelihood(self, par_dict, w, delta):\n        gp = self.gl.parameter_point(w)\n        return gp.log_likelihood_global()\n\n\nclass CustomLikelihood(object):\n    def __init__(self, likelihood, observables):\n        if set(observables) - likelihood.observables:\n            raise ValueError(\n                'The following observables are not part of any included '\n                '(fast)likelihood and thus cannot be used in a custom '\n                'likelihood: {}.'.format(', '.join(\n                    str(obs) for obs\n                    in set(observables) - likelihood.observables\n                ))\n            )\n        self.likelihood = likelihood\n        self.observables = set(observables)\n        self.exclude_obs = self._get_exclude_obs_dict()\n\n    def _get_exclude_obs_dict(self):\n        \"\"\"Get a dictionary with observables to be excluded from each\n        (Fast)Likelihood instance.\"\"\"\n        exclude_obs = {}\n        for lhs_or_flhs in (self.likelihood.likelihoods,\n                            self.likelihood.fast_likelihoods):\n            for lh_name, lh in lhs_or_flhs.items():\n                exclude_observables = set(lh.observables) - self.observables\n                if set(lh.observables) != exclude_observables:\n                    exclude_obs[lh_name] = exclude_observables\n        return exclude_obs\n\n    def log_likelihood(self, par_dict, wc_obj, delta=False):\n        custom_log_likelihood = 0\n        for lh_name, exclude_observables in self.exclude_obs.items():\n            lh = (self.likelihood.fast_likelihoods.get(lh_name)\n                  or self.likelihood.likelihoods.get(lh_name))\n            custom_log_likelihood += lh.log_likelihood(\n                par_dict, wc_obj, delta=delta,\n                exclude_observables=exclude_observables\n            )\n        return custom_log_likelihood\n\n    def get_number_observations(self):\n        \"\"\"Get the number of observations, defined as individual measurements\n        of observables.\"\"\"\n        nobs = 0\n        for llh_name, exclude_observables in self.exclude_obs.items():\n            if llh_name in self.likelihood.fast_likelihoods:\n                flh = self.likelihood.fast_likelihoods[llh_name]\n                nobs += len(set(flh.observables) - set(exclude_observables or []))\n            else:\n                lh = self.likelihood.likelihoods[llh_name]\n                ml =  lh.measurement_likelihood\n                nobs += ml.get_number_observations(\n                    exclude_observables=exclude_observables)\n        return nobs\n\n\nclass GlobalLikelihoodPoint(object):\n    \"\"\"Class representing the properties of the likelihood function at a\n    specific point in parameter space.\n\n    Attributes:\n\n    - `log_likelihood_dict`: dictionary with individual contributions\n    to the log-likelihood\n    - `value`: Return the numerical values of the global log-likelihood\n    compared to the SM value (can also be acessed with `float(self)`)\n\n    Methods:\n\n    - `get_obstable`: return a pandas data frame with the values and pulls\n    for each individual observable, given the Wilson coefficients\n    \"\"\"\n\n    def __init__(self, likelihood, w,\n                 fix_ckm=False):\n        \"\"\"Initialize the `GlobalLikelihoodPoint` instance.\n\n        Parameters:\n        - likelihood: an instance of `GlobalLikelihood`\n        - w: an instance of `wilson.Wilson`\n        - fix_ckm: If False (default), automatically determine the CKM elements\n          in the presence of new physics in processes used to determine these\n          elements in the SM. If set to True, the CKM elements are fixed to\n          their SM values, which can lead to inconsistent results, but also\n          to a significant speedup in specific cases.\n        \"\"\"\n        self.likelihood = likelihood\n        likelihood._check_sm_cov_loaded()\n        self.w_input = w\n        self.fix_ckm = fix_ckm\n        self._w = None\n        self._obstable_tree_cache = None\n        self._log_likelihood_dict = None\n        self._par_dict_np = None\n\n    @property\n    def w(self):\n        if self._w is None:\n            w = self.w_input\n            opt = w.get_option('parameters')\n            par = self.par_dict_np\n            for p in ['Vus', 'Vcb', 'Vub', 'delta']:\n                opt[p] = par[p]\n            w.set_option('parameters', opt)\n            self._w = w\n        return self._w\n\n    def get_ckm_np(self):\n        \"\"\"return the values of the four \"true\" CKM parameters\n        `Vus`, `Vcb`, `Vub`, `delta`, extracted from the four input observables\n        for this parameter point in Wilson coefficient space.\"\"\"\n        scheme = self.likelihood._ckm_scheme\n        try:\n            Vus, Vcb, Vub, delta = scheme.ckm_np(self.w_input)\n        except ValueError:\n            # this happens mostly when the formulas result in |cos(delta)| > 1\n            raise ValueError(\"The extraction of CKM elements failed. Too large NP effects?\")\n        return {'Vus': Vus, 'Vcb': Vcb, 'Vub': Vub, 'delta': delta}\n\n    @property\n    def par_dict_np(self):\n        \"\"\"Return the dictionary of parameters where the four CKM parameters\n        `Vus`, `Vcb`, `Vub`, `delta` have been replaced by their\n        \"true\" values as extracted from the four input observables.\n\n        Note that if `fix_ckm` is set to `True`, this method actually\n        returns the SM values.\"\"\"\n        if self.fix_ckm:\n            return self.likelihood.par_dict_sm\n        if self._par_dict_np is None:\n            par_dict_np = self.likelihood.par_dict_default.copy()\n            par_dict_np.update(self.get_ckm_np())\n            self._par_dict_np = par_dict_np\n        return self._par_dict_np\n\n    def _delta_log_likelihood(self):\n        \"\"\"Compute the delta log likelihood for the individual likelihoods\"\"\"\n        ll = self.likelihood._log_likelihood(self.par_dict_np, self.w)\n        for name in ll:\n            ll[name] -= self.likelihood.log_likelihood_sm[name]\n        ll['global'] = sum([v for k, v in ll.items() if 'custom_' not in k])\n        return ll\n\n    def log_likelihood_dict(self):\n        \"\"\"Return a dictionary with the delta log likelihood values\n        for the individual contributions.\n\n        Cached after the first call.\"\"\"\n        if self._log_likelihood_dict is None:\n            self._log_likelihood_dict = self._delta_log_likelihood()\n        return self._log_likelihood_dict\n\n    def log_likelihood_global(self):\n        \"\"\"Return the value of the global delta log likelihood.\n\n        Cached after the first call. Corresponds to the `global` key of\n        the dictionary returned by `log_likelihood_dict`.\"\"\"\n        return self.log_likelihood_dict()['global']\n\n    def pvalue_dict(self, n_par=0):\n        r\"\"\"Dictionary of $p$ values of sublikelihoods given the number `n_par`\n        of free parameters (default 0).\"\"\"\n        nobs = self.likelihood.number_observations_dict()\n        chi2 = self.chi2_dict()\n        return {k: pvalue(chi2[k], dof=max(1, nobs[k] - n_par)) for k in chi2}\n\n    def chi2_dict(self):\n        r\"\"\"Dictionary of total $\\chi^2$ values of each sublikelihood.\n\n        $$\\chi^2 = -2 (\\ln L + \\ln L_\\text{SM})$$\n        \"\"\"\n        ll = self.log_likelihood_dict()\n        llsm = self.likelihood._log_likelihood_sm.copy()\n        llsm['global'] = sum([v for k, v in llsm.items() if 'custom_' not in k])\n        return {k: -2 * (ll[k] + llsm[k]) for k in ll}\n\n    @property\n    def _obstable_tree(self):\n        if not self._obstable_tree_cache:\n            llh = self.likelihood\n            info = copy(llh.obstable_sm)\n            for flh_name, flh in llh.fast_likelihoods.items():\n                # loop over fast likelihoods: they only have a single \"measurement\"\n                m = flh.pseudo_measurement\n                ml = flh.full_measurement_likelihood\n                pred = ml.get_predictions_par(self.par_dict_np, self.w)\n                for i, obs in enumerate(flh.observables):\n                    info[obs]['theory'] = pred[obs]\n                    ll_central = info[obs]['ll_central']\n                    ll_sm = info[obs]['ll_sm']\n                    ll = m.get_logprobability_single(obs, pred[obs])\n                    # DeltaChi2 is -2*DeltaLogLikelihood\n                    info[obs]['pull exp.'] = pull(-2 * (ll - ll_central), dof=1)\n                    s = -1 if ll > ll_sm else 1\n                    info[obs]['pull SM'] = s * pull(-2 * (ll - ll_sm), dof=1)\n            for lh_name, lh in llh.likelihoods.items():\n                # loop over \"normal\" likelihoods\n                ml = lh.measurement_likelihood\n                pred = ml.get_predictions_par(self.par_dict_np, self.w)\n                for i, obs in enumerate(lh.observables):\n                    info[obs]['theory'] = pred[obs]\n                    ll_central = info[obs]['ll_central']\n                    ll_sm = info[obs]['ll_sm']\n                    p_comb = info[obs]['exp. PDF']\n                    ll = p_comb.logpdf([pred[obs]])\n                    if ll == -np.inf:\n                        ll = -1e100\n                    info[obs]['pull exp.'] = pull(-2 * (ll - ll_central), dof=1)\n                    s = -1 if ll > ll_sm else 1\n                    info[obs]['pull SM'] = s * pull(-2 * (ll - ll_sm), dof=1)\n            self._obstable_tree_cache = info\n        return self._obstable_tree_cache\n\n    def obstable(self, min_pull_exp=0, sort_by='pull exp.', ascending=None,\n                 min_val=None, max_val=None):\n        r\"\"\"Return a pandas data frame with the central values and uncertainties\n        as well as the pulls with respect to the experimental and the SM values for each observable.\n\n        The pull is defined is $\\sqrt(|-2\\ln L|)$. Note that the global\n        likelihood is *not* simply proportional to the sum of squared pulls\n        due to correlations.\n        \"\"\"\n        sort_keys = ['name', 'exp. unc.', 'experiment', 'pull SM', 'pull exp.',\n                     'th. unc.', 'theory']\n        if sort_by not in sort_keys:\n            raise ValueError(\n                \"'{}' is not an allowed value for sort_by. Allowed values are \"\n                \"'{}', and '{}'.\".format(sort_by, \"', '\".join(sort_keys[:-1]),\n                                         sort_keys[-1])\n            )\n        info = self._obstable_tree\n        subset = None\n        if sort_by == 'pull exp.':\n            # if sorted by pull exp., use descending order as default\n            if ascending is None:\n                ascending = False\n            if min_val is not None:\n                min_val = max(min_pull_exp, min_val)\n            else:\n                min_val = min_pull_exp\n        elif min_pull_exp != 0:\n            subset = lambda row: row['pull exp.'] >= min_pull_exp\n        # if sorted not by pull exp., use ascending order as default\n        if ascending is None:\n            ascending = True\n        info = self._obstable_filter_sort(info, sortkey=sort_by,\n                                          ascending=ascending,\n                                          min_val=min_val, max_val=max_val,\n                                          subset=subset)\n        # create DataFrame\n        df = pd.DataFrame(info).T\n        # if df has length 0 (e.g. if min_pull is very large) there are no\n        # columns that could be removed\n        if len(df) >0:\n            # remove columns that are only used internal and should not be\n            # included in obstable\n            del(df['inspire'])\n            del(df['lh_name'])\n            del(df['name'])\n            del(df['exp. PDF'])\n            del(df['ll_central'])\n            del(df['ll_sm'])\n        return df\n\n    @staticmethod\n    def _obstable_filter_sort(info, sortkey='name', ascending=True,\n                              min_val=None, max_val=None,\n                              subset=None, max_rows=None):\n        # impose min_val and max_val\n        if min_val is not None:\n            info = {obs:row for obs,row in info.items()\n                    if row[sortkey] >= min_val}\n        if max_val is not None:\n            info = {obs:row for obs,row in info.items()\n                    if row[sortkey] <= max_val}\n        # get only subset:\n        if subset is not None:\n            info = {obs:row for obs,row in info.items() if subset(row)}\n        # sort\n        info = OrderedDict(sorted(info.items(), key=lambda x: x[1][sortkey],\n                                  reverse=(not ascending)))\n        # restrict number of rows per tabular to max_rows\n        if max_rows is None or len(info)<=max_rows:\n            return info\n        else:\n            info_list = []\n            for n in range(ceil(len(info)/max_rows)):\n                info_n = OrderedDict((obs,row)\n                                    for i,(obs,row) in enumerate(info.items())\n                                    if i>=n*max_rows and i<(n+1)*max_rows)\n                info_list.append(info_n)\n            return info_list\n", "meta": {"hexsha": "8a582864cd93881a2c0e4f61f730bfaa230ba826", "size": 47554, "ext": "py", "lang": "Python", "max_stars_repo_path": "smelli/classes.py", "max_stars_repo_name": "nsahoo/smelli", "max_stars_repo_head_hexsha": "b2858e8857a5845955fb7c9ae74b43e60b755d4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "smelli/classes.py", "max_issues_repo_name": "nsahoo/smelli", "max_issues_repo_head_hexsha": "b2858e8857a5845955fb7c9ae74b43e60b755d4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "smelli/classes.py", "max_forks_repo_name": "nsahoo/smelli", "max_forks_repo_head_hexsha": "b2858e8857a5845955fb7c9ae74b43e60b755d4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.73565381, "max_line_length": 157, "alphanum_fraction": 0.5935567986, "include": true, "reason": "import numpy", "num_tokens": 10706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.29098085391781303, "lm_q1q2_score": 0.18219014774847983}}
{"text": "\"\"\"Anchor utils modified from https://github.com/biubug6/Pytorch_Retinaface\"\"\"\nimport math\nimport tensorflow as tf\nimport numpy as np\nfrom itertools import product as product\n\n\n###############################################################################\n#   Tensorflow / Numpy                                                 #\n###############################################################################\ndef decode(labels, priors, variances=[0.1, 0.2]):\n    \"\"\"tensorflow decoding\"\"\"\n    bbox = _decode_bbox(labels[:, :4], priors, variances)\n    landm = _decode_landm(labels[:, 4:14], priors, variances)\n    landm_valid = labels[:, 14][:, np.newaxis]\n    conf = labels[:, 15][:, np.newaxis]\n\n    return np.concatenate([bbox, landm, landm_valid, conf], axis=1)\n\n\ndef _decode_bbox(pre, priors, variances=[0.1, 0.2]):\n    \"\"\"Decode locations from predictions using priors to undo\n    the encoding we did for offset regression at train time.\n    Args:\n        pre (tensor): location predictions for loc layers,\n            Shape: [num_priors,4]\n        priors (tensor): Prior boxes in center-offset form.\n            Shape: [num_priors,4].\n        variances: (list[float]) Variances of priorboxes\n    Return:\n        decoded bounding box predictions\n    \"\"\"\n    centers = priors[:, :2] + pre[:, :2] * variances[0] * priors[:, 2:]\n    sides = priors[:, 2:] * np.exp(pre[:, 2:] * variances[1])\n\n    return np.concatenate([centers - sides / 2, centers + sides / 2], axis=1)\n\n\ndef _decode_landm(pre, priors, variances=[0.1, 0.2]):\n    \"\"\"Decode landm from predictions using priors to undo\n    the encoding we did for offset regression at train time.\n    Args:\n        pre (tensor): landm predictions for loc layers,\n            Shape: [num_priors,10]\n        priors (tensor): Prior boxes in center-offset form.\n            Shape: [num_priors,4].\n        variances: (list[float]) Variances of priorboxes\n    Return:\n        decoded landm predictions\n    \"\"\"\n    landms = np.concatenate(\n        [priors[:, :2] + pre[:, :2] * variances[0] * priors[:, 2:],\n         priors[:, :2] + pre[:, 2:4] * variances[0] * priors[:, 2:],\n         priors[:, :2] + pre[:, 4:6] * variances[0] * priors[:, 2:],\n         priors[:, :2] + pre[:, 6:8] * variances[0] * priors[:, 2:],\n         priors[:, :2] + pre[:, 8:10] * variances[0] * priors[:, 2:]], axis=1)\n    return landms\n\n\n\"\"\"\ndef prior_box(image_sizes, min_sizes, steps, clip=False):\n    # import pdb;pdb.set_trace()\n    image_sizes = np.array(image_sizes).astype(np.float32)\n    min_sizes = np.array(min_sizes)\n    steps = np.array(steps).astype(np.float32)\n\n    feature_maps = np.ceil(image_sizes.reshape([1, 2]) / steps.reshape([-1, 1])).astype(np.int)\n\n    anchors = []\n    for k in range(len(min_sizes)):\n        grid_x, grid_y = np.meshgrid(range(feature_maps[k][1]),\n                                      range(feature_maps[k][0]))\n        cx = (grid_x + 0.5) * steps[k] / image_sizes[1]\n        cy = (grid_y + 0.5) * steps[k] / image_sizes[0]\n        cxcy = np.stack([cx, cy], axis=-1)\n        cxcy = cxcy.reshape([-1, 2])\n        cxcy = np.repeat(cxcy, repeats=min_sizes[k].shape[0], axis=0)\n\n        sx = min_sizes[k] / image_sizes[1]\n        sy = min_sizes[k] / image_sizes[0]\n        sxsy = np.stack([sx, sy], 1)\n        sxsy = np.repeat(sxsy[np.newaxis],\n                         repeats=grid_x.shape[0] * grid_x.shape[1],\n                         axis=0)\n        sxsy = np.reshape(sxsy, [-1, 2])\n\n        anchors.append(np.concatenate([cxcy, sxsy], 1))\n\n    output = np.concatenate(anchors, axis=0)\n\n    if clip:\n        output = np.clip(output, 0, 1)\n\n    return output\n\"\"\"\n\n\ndef prior_box(image_sizes, min_sizes, steps, clip=False):\n    \"\"\"prior box\"\"\"\n    feature_maps = [\n        [math.ceil(image_sizes[0] / step), math.ceil(image_sizes[1] / step)]\n        for step in steps]\n\n    anchors = []\n    for k, f in enumerate(feature_maps):\n        for i, j in product(range(f[0]), range(f[1])):\n            for min_size in min_sizes[k]:\n                s_kx = min_size / image_sizes[1]\n                s_ky = min_size / image_sizes[0]\n                cx = (j + 0.5) * steps[k] / image_sizes[1]\n                cy = (i + 0.5) * steps[k] / image_sizes[0]\n                anchors += [cx, cy, s_kx, s_ky]\n\n    output = np.asarray(anchors).reshape([-1, 4])\n\n    if clip:\n        output = np.clip(output, 0, 1)\n\n    return output\n\n\ndef prior_box_tf(image_sizes, min_sizes, steps, clip=False):\n    \"\"\"prior box\"\"\"\n    image_sizes = tf.cast(tf.convert_to_tensor(image_sizes), tf.float32)\n    feature_maps = tf.math.ceil(\n        tf.reshape(image_sizes, [1, 2]) /\n        tf.reshape(tf.cast(steps, tf.float32), [-1, 1]))\n\n    anchors = []\n    for k in range(len(min_sizes)):\n        grid_x, grid_y = _meshgrid_tf(tf.range(feature_maps[k][1]),\n                                      tf.range(feature_maps[k][0]))\n        cx = (grid_x + 0.5) * steps[k] / image_sizes[1]\n        cy = (grid_y + 0.5) * steps[k] / image_sizes[0]\n        cxcy = tf.stack([cx, cy], axis=-1)\n        cxcy = tf.reshape(cxcy, [-1, 2])\n        cxcy = tf.repeat(cxcy, repeats=tf.shape(min_sizes[k])[0], axis=0)\n\n        sx = min_sizes[k] / image_sizes[1]\n        sy = min_sizes[k] / image_sizes[0]\n        sxsy = tf.stack([sx, sy], 1)\n        sxsy = tf.repeat(sxsy[tf.newaxis],\n                         repeats=tf.shape(grid_x)[0] * tf.shape(grid_x)[1],\n                         axis=0)\n        sxsy = tf.reshape(sxsy, [-1, 2])\n\n        anchors.append(tf.concat([cxcy, sxsy], 1))\n\n    output = tf.concat(anchors, axis=0)\n\n    if clip:\n        output = tf.clip_by_value(output, 0, 1)\n\n    return output\n\n\ndef _meshgrid_tf(x, y):\n    \"\"\" workaround solution of the tf.meshgrid() issue:\n        https://github.com/tensorflow/tensorflow/issues/34470\"\"\"\n    grid_shape = [tf.shape(y)[0], tf.shape(x)[0]]\n    grid_x = tf.broadcast_to(tf.reshape(x, [1, -1]), grid_shape)\n    grid_y = tf.broadcast_to(tf.reshape(y, [-1, 1]), grid_shape)\n    return grid_x, grid_y\n\n\n###############################################################################\n#   Tensorflow Encoding                                                       #\n###############################################################################\ndef encode_tf(labels, priors, match_thresh, ignore_thresh,\n              variances=[0.1, 0.2]):\n    \"\"\"tensorflow encoding\"\"\"\n    assert ignore_thresh <= match_thresh\n    priors = tf.cast(priors, tf.float32)\n    bbox = labels[:, :4]\n    landm = labels[:, 4:-1]\n    landm_valid = labels[:, -1]  # 1: with landm, 0: w/o landm.\n\n    # jaccard index\n    overlaps = _jaccard(bbox, _point_form(priors))\n\n    # (Bipartite Matching)\n    # [num_objects] best prior for each ground truth\n    best_prior_overlap, best_prior_idx = tf.math.top_k(overlaps, k=1)\n    best_prior_overlap = best_prior_overlap[:, 0]\n    best_prior_idx = best_prior_idx[:, 0]\n\n    # [num_priors] best ground truth for each prior\n    overlaps_t = tf.transpose(overlaps)\n    best_truth_overlap, best_truth_idx = tf.math.top_k(overlaps_t, k=1)\n    best_truth_overlap = best_truth_overlap[:, 0]\n    best_truth_idx = best_truth_idx[:, 0]\n\n    # ensure best prior\n    def _loop_body(i, bt_idx, bt_overlap):\n        bp_mask = tf.one_hot(best_prior_idx[i], tf.shape(bt_idx)[0])\n        bp_mask_int = tf.cast(bp_mask, tf.int32)\n        new_bt_idx = bt_idx * (1 - bp_mask_int) + bp_mask_int * i\n        bp_mask_float = tf.cast(bp_mask, tf.float32)\n        new_bt_overlap = bt_overlap * (1 - bp_mask_float) + bp_mask_float * 2\n        return tf.cond(best_prior_overlap[i] > match_thresh,\n                       lambda: (i + 1, new_bt_idx, new_bt_overlap),\n                       lambda: (i + 1, bt_idx, bt_overlap))\n    _, best_truth_idx, best_truth_overlap = tf.while_loop(\n        lambda i, bt_idx, bt_overlap: tf.less(i, tf.shape(best_prior_idx)[0]),\n        _loop_body, [tf.constant(0), best_truth_idx, best_truth_overlap])\n\n    matches_bbox = tf.gather(bbox, best_truth_idx)  # [num_priors, 4]\n    matches_landm = tf.gather(landm, best_truth_idx)  # [num_priors, 10]\n    matches_landm_v = tf.gather(landm_valid, best_truth_idx)  # [num_priors]\n\n    loc_t = _encode_bbox(matches_bbox, priors, variances)\n    landm_t = _encode_landm(matches_landm, priors, variances)\n    landm_valid_t = tf.cast(matches_landm_v > 0, tf.float32)\n    conf_t = tf.cast(best_truth_overlap > match_thresh, tf.float32)\n    conf_t = tf.where(\n        tf.logical_and(best_truth_overlap < match_thresh,\n                       best_truth_overlap > ignore_thresh),\n        tf.ones_like(conf_t) * -1, conf_t)    # 1: pos, 0: neg, -1: ignore\n\n    return tf.concat([loc_t, landm_t, landm_valid_t[..., tf.newaxis],\n                      conf_t[..., tf.newaxis]], axis=1)\n\n\ndef _encode_bbox(matched, priors, variances):\n    \"\"\"Encode the variances from the priorbox layers into the ground truth\n    boxes we have matched (based on jaccard overlap) with the prior boxes.\n    Args:\n        matched: (tensor) Coords of ground truth for each prior in point-form\n            Shape: [num_priors, 4].\n        priors: (tensor) Prior boxes in center-offset form\n            Shape: [num_priors,4].\n        variances: (list[float]) Variances of priorboxes\n    Return:\n        encoded boxes (tensor), Shape: [num_priors, 4]\n    \"\"\"\n\n    # dist b/t match center and prior's center\n    g_cxcy = (matched[:, :2] + matched[:, 2:]) / 2 - priors[:, :2]\n    # encode variance\n    g_cxcy /= (variances[0] * priors[:, 2:])\n    # match wh / prior wh\n    g_wh = (matched[:, 2:] - matched[:, :2]) / priors[:, 2:]\n    g_wh = tf.math.log(g_wh) / variances[1]\n    # return target for smooth_l1_loss\n    return tf.concat([g_cxcy, g_wh], 1)  # [num_priors,4]\n\n\ndef _encode_landm(matched, priors, variances):\n    \"\"\"Encode the variances from the priorbox layers into the ground truth\n    boxes we have matched (based on jaccard overlap) with the prior boxes.\n    Args:\n        matched: (tensor) Coords of ground truth for each prior in point-form\n            Shape: [num_priors, 10].\n        priors: (tensor) Prior boxes in center-offset form\n            Shape: [num_priors,4].\n        variances: (list[float]) Variances of priorboxes\n    Return:\n        encoded landm (tensor), Shape: [num_priors, 10]\n    \"\"\"\n\n    # dist b/t match center and prior's center\n    matched = tf.reshape(matched, [tf.shape(matched)[0], 5, 2])\n    priors = tf.broadcast_to(\n        tf.expand_dims(priors, 1), [tf.shape(matched)[0], 5, 4])\n    g_cxcy = matched[:, :, :2] - priors[:, :, :2]\n    # encode variance\n    g_cxcy /= (variances[0] * priors[:, :, 2:])\n    # g_cxcy /= priors[:, :, 2:]\n    g_cxcy = tf.reshape(g_cxcy, [tf.shape(g_cxcy)[0], -1])\n    # return target for smooth_l1_loss\n    return g_cxcy\n\n\ndef _point_form(boxes):\n    \"\"\" Convert prior_boxes to (xmin, ymin, xmax, ymax)\n    representation for comparison to point form ground truth data.\n    Args:\n        boxes: (tensor) center-size default boxes from priorbox layers.\n    Return:\n        boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.\n    \"\"\"\n    return tf.concat((boxes[:, :2] - boxes[:, 2:] / 2,\n                      boxes[:, :2] + boxes[:, 2:] / 2), axis=1)\n\n\ndef _intersect(box_a, box_b):\n    \"\"\" We resize both tensors to [A,B,2]:\n    [A,2] -> [A,1,2] -> [A,B,2]\n    [B,2] -> [1,B,2] -> [A,B,2]\n    Then we compute the area of intersect between box_a and box_b.\n    Args:\n      box_a: (tensor) bounding boxes, Shape: [A,4].\n      box_b: (tensor) bounding boxes, Shape: [B,4].\n    Return:\n      (tensor) intersection area, Shape: [A,B].\n    \"\"\"\n    A = tf.shape(box_a)[0]\n    B = tf.shape(box_b)[0]\n    max_xy = tf.minimum(\n        tf.broadcast_to(tf.expand_dims(box_a[:, 2:], 1), [A, B, 2]),\n        tf.broadcast_to(tf.expand_dims(box_b[:, 2:], 0), [A, B, 2]))\n    min_xy = tf.maximum(\n        tf.broadcast_to(tf.expand_dims(box_a[:, :2], 1), [A, B, 2]),\n        tf.broadcast_to(tf.expand_dims(box_b[:, :2], 0), [A, B, 2]))\n    inter = tf.maximum((max_xy - min_xy), tf.zeros_like(max_xy - min_xy))\n    return inter[:, :, 0] * inter[:, :, 1]\n\n\ndef _jaccard(box_a, box_b):\n    \"\"\"Compute the jaccard overlap of two sets of boxes.  The jaccard overlap\n    is simply the intersection over union of two boxes.  Here we operate on\n    ground truth boxes and default boxes.\n    E.g.:\n        A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B)\n    Args:\n        box_a: (tensor) Ground truth bounding boxes, Shape: [num_objects,4]\n        box_b: (tensor) Prior boxes from priorbox layers, Shape: [num_priors,4]\n    Return:\n        jaccard overlap: (tensor) Shape: [box_a.size(0), box_b.size(0)]\n    \"\"\"\n    inter = _intersect(box_a, box_b)\n    area_a = tf.broadcast_to(\n        tf.expand_dims(\n            (box_a[:, 2] - box_a[:, 0]) * (box_a[:, 3] - box_a[:, 1]), 1),\n        tf.shape(inter))  # [A,B]\n    area_b = tf.broadcast_to(\n        tf.expand_dims(\n            (box_b[:, 2] - box_b[:, 0]) * (box_b[:, 3] - box_b[:, 1]), 0),\n        tf.shape(inter))  # [A,B]\n    union = area_a + area_b - inter\n    return inter / union  # [A,B]\n\n\n###############################################################################\n#   Tensorflow Decoding                                                       #\n###############################################################################\ndef decode_tf(labels, priors, variances=[0.1, 0.2]):\n    \"\"\"tensorflow decoding\"\"\"\n    bbox = _decode_bbox_tf(labels[:, :4], priors, variances)\n    landm = _decode_landm_tf(labels[:, 4:14], priors, variances)\n    landm_valid = labels[:, 14][:, tf.newaxis]\n    conf = labels[:, 15][:, tf.newaxis]\n\n    return tf.concat([bbox, landm, landm_valid, conf], axis=1)\n\n\ndef _decode_bbox_tf(pre, priors, variances=[0.1, 0.2]):\n    \"\"\"Decode locations from predictions using priors to undo\n    the encoding we did for offset regression at train time.\n    Args:\n        pre (tensor): location predictions for loc layers,\n            Shape: [num_priors,4]\n        priors (tensor): Prior boxes in center-offset form.\n            Shape: [num_priors,4].\n        variances: (list[float]) Variances of priorboxes\n    Return:\n        decoded bounding box predictions\n    \"\"\"\n    centers = priors[:, :2] + pre[:, :2] * variances[0] * priors[:, 2:]\n    sides = priors[:, 2:] * tf.math.exp(pre[:, 2:] * variances[1])\n\n    return tf.concat([centers - sides / 2, centers + sides / 2], axis=1)\n\n\ndef _decode_landm_tf(pre, priors, variances=[0.1, 0.2]):\n    \"\"\"Decode landm from predictions using priors to undo\n    the encoding we did for offset regression at train time.\n    Args:\n        pre (tensor): landm predictions for loc layers,\n            Shape: [num_priors,10]\n        priors (tensor): Prior boxes in center-offset form.\n            Shape: [num_priors,4].\n        variances: (list[float]) Variances of priorboxes\n    Return:\n        decoded landm predictions\n    \"\"\"\n    landms = tf.concat(\n        [priors[:, :2] + pre[:, :2] * variances[0] * priors[:, 2:],\n         priors[:, :2] + pre[:, 2:4] * variances[0] * priors[:, 2:],\n         priors[:, :2] + pre[:, 4:6] * variances[0] * priors[:, 2:],\n         priors[:, :2] + pre[:, 6:8] * variances[0] * priors[:, 2:],\n         priors[:, :2] + pre[:, 8:10] * variances[0] * priors[:, 2:]], axis=1)\n    return landms\n", "meta": {"hexsha": "3fed627985cdd7127f2527c8efd1c3c97604ffca", "size": 15194, "ext": "py", "lang": "Python", "max_stars_repo_path": "modules/anchor.py", "max_stars_repo_name": "akinoriosamura/retinaface-tf2", "max_stars_repo_head_hexsha": "94b6a3cd925124ad92b4ea26139a6f4ebf71e920", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/anchor.py", "max_issues_repo_name": "akinoriosamura/retinaface-tf2", "max_issues_repo_head_hexsha": "94b6a3cd925124ad92b4ea26139a6f4ebf71e920", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/anchor.py", "max_forks_repo_name": "akinoriosamura/retinaface-tf2", "max_forks_repo_head_hexsha": "94b6a3cd925124ad92b4ea26139a6f4ebf71e920", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5677083333, "max_line_length": 95, "alphanum_fraction": 0.5725286297, "include": true, "reason": "import numpy", "num_tokens": 4303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.3073580295544412, "lm_q1q2_score": 0.18216083834461314}}
{"text": "import numpy as np\nimport astropy.units as u\nfrom astropy.table import QTable\nfrom .stddata import fiber_fraction\nfrom .rebin import rebin_1d_flux_box,rebin_1d_trans_box\n\nclass Exposure:\n    '''Simulate exposures\n\n    After initialization and filling with object and background (sky)\n    flux, the basic properties for a specified exposure time can be\n    calculated.\n\n    Parameters\n    ----------\n    spectrograph : :class:`.Gamaica`\n        Spectrograph object, with attributes wavelength, readout_noise,\n        dark_flux,, and others.\n\n    Examples\n    --------\n\n    Do a full ETC run\n\n        >>> from etc.exposure import Exposure\n        >>> from etc.instrument import Gamaica\n        >>> from etc.atmosphere import Atmosphere\n        >>> from etc.seds import SEDtemplate\n        >>> from etc.functions import save_and_see\n        >>> \n        >>> \n        >>>## instrument\n        >>>instrument = Gamaica(1200)\n        >>>\n        >>>## atmosphere\n        >>>atm = Atmosphere.caha()\n        >>>sky_emission = atm.emission(21.5,'johnson,v')\n        >>>sky_transmission = atm.transmission(airmass=1.2)\n        >>>\n        >>># target to observe\n        >>>HII_region = SEDtemplate('orion')\n        >>>HII_region.scale_to_mag(20.0,'johnson,v')\n        >>>\n        >>>\n        >>># set up exposure\n        >>>exp = Exposure(instrument)\n        >>>\n        >>># add object to observe\n        >>>exp.add_object(HII_region)\n        >>>\n        >>># add sky emission, optional\n        >>>exp.add_sky_emission(sky_emission)\n        >>>\n        >>># add atmospheric transmission (optional)\n        >>>exp.add_sky_transmission(sky_transmission)\n        >>>\n        >>># expose\n        >>>exptime = 60. # seconds\n        >>>result = exp.expose(exptime)\n        >>>\n        >>># save result, look at plots\n        >>>save_and_see(result)\n    '''\n\n    def __init__(self, spectrograph):\n        self.spectrograph = spectrograph\n        #self.object_flux = np.zeros(self.spectrograph.wavelength.shape) * (\n        #    u.electron * u.s**-1)\n        #self.sky_flux = np.zeros(self.spectrograph.wavelength.shape) * (\n        #    u.electron * u.s**-1)\n\n        self.nobj_A = np.zeros(self.spectrograph.wavelength_perpix.shape) * ( u.photon/u.second/u.m**2/u.AA)\n            \n        self.nobj_fib = np.zeros(self.spectrograph.wavelength_perpix.shape) *( u.photon/u.second/u.AA)\n        self.nobj_pix = np.zeros(self.spectrograph.wavelength_perpix.shape) *( u.photon/u.second)\n        self.nobj_photlam = np.zeros(self.spectrograph.wavelength_perpix.shape) *( u.photon/u.second/u.cm**2/u.AA)\n        \n        self.nsky_A = np.zeros(self.spectrograph.wavelength_perpix.shape) * ( u.photon/u.second/u.m**2/u.AA)\n        self.nsky_fib = np.zeros(self.spectrograph.wavelength_perpix.shape) *( u.photon/u.second/u.AA)\n        self.nsky_pix = np.zeros(self.spectrograph.wavelength_perpix.shape) *( u.photon/u.second)\n        self.nsky_photlam = np.zeros(self.spectrograph.wavelength_perpix.shape) *(  u.photon/u.second/u.cm**2/u.AA)\n        self.total_efficiency = np.ones(self.spectrograph.wavelength_perpix.shape)\n        \n    def add_object(self, sed, wavelength=None):\n        '''Add some object flux\n\n        Parameters\n        ----------\n        sed : :class:`SEDtemplate`\n            object flux density in [flam] as a function of wavelength in [A]\n\n        wavelength : :class:`astropy.units.Quantity`\n            Wavelength bins for the flux. If not given, then the \n            flam is not rebinned and the wavelengths of each bin must \n            correspond to the wavelength bins of the GAMAICA transmission\n        '''\n\n        \n        ## conversions\n        sed.sed.convert('photlam')\n        ''' this conversion seems to strip sed.sed.flux from its units\n        but not sed.sed.wave! Inconvenient.\n        Probably best to replace pysynphot with own code.\n        '''\n\n\n        # rebin incoming sed to instrument dispersion\n        # rebin doesn't handle units, resulting in errors.\n        # avoid by stripping arrays of units\n        if isinstance(sed.sed.flux,np.ndarray):\n            flux_perpix = rebin_1d_flux_box(sed.sed.flux.value,sed.sed.wave.value,self.wavelength.value)* u.photon/u.second/u.cm**2/u.AA\n        elif isinstance(sed.sed.flux,u.quantity.Quantity):\n            flux_perpix = rebin_1d_flux_box(sed.sed.flux.value,sed.sed.wave.value,self.wavelength.value)* u.photon/u.second/u.cm**2/u.AA\n        else:\n            print('Cannot add object. ****not implemented****')\n            return\n        nobj_A = flux_perpix.to('ph s**-1 m**-2 AA**-1')\n        nobj_fib = nobj_A * self.spectrograph.A_tel * fiber_fraction\n\n\n        ## this formula below for nobj_pix needs checking. I assume that 1 AA = 1/ldisp pixels. Correct?\n        nobj_pix = nobj_fib * self.spectrograph.ldisp\n        \n        ## find index of wavelength element closest to pivot position\n        idx = abs(self.wavelength.to('AA').value - sed.pivot_wave).argmin()\n        \n        print(f'\\nAt pivot wavelength {self.wavelength[idx]:.0f} of filter:')\n        print(f'Object flam:           {sed.sed.flux[idx].value:.5e} erg / (Angstrom cm2 s)' )\n        print(f'Object photons/m2:     {nobj_A[idx]:.5e} ')\n        print(f'Spatial sampling:      {self.spectrograph.fib_area:.3f}')\n        #print(f'fraction of star/fiber: {(self.spectrograph.fib_diam/fwhm)**2)}')\n        print(f'Object photons/fiber:  {nobj_fib[idx]:.5e}')\n        print(f'Object photons/pixel:  {nobj_pix[idx]:.5e}')\n\n        self.nobj_photlam += flux_perpix\n        self.nobj_A += nobj_A\n        self.nobj_fib += nobj_fib\n        #self.fiber_frac = (fib/fwhm)**2\n        self.nobj_pix += nobj_pix\n        \n        if wavelength is not None:\n            print('rebinning of target flux ***Not implemented yet***')\n        #    flux = self.spectrograph.rebin(wavelength, flux)\n        \n\n    def add_sky_emission(self, sed, wavelength=None):\n        '''Add some sky flux\n\n        Parameters\n        ----------\n        sed : :class:`pysynphot.spectrum.CompositeSourceSpectrum` or\n                     `pysynphot.spectrum.SourceSpectrum`\n            surface brightness of sky in erg/s/cm2/AA/acrsec2.\n\n        wavelength : :class:`astropy.units.Quantity`\n            Wavelength bins for the flux. If not given, then the \n            flam is not rebinned and the wavelengths of each bin must \n            correspond to the wavelength bins of the GAMAICA transmission\n\n        '''\n        \n        sed.convert('photlam')\n        ''' this conversion seems to strip sed.sed.flux from its units\n        but not sed.sed.wave! Inconvenient.'''\n\n        \n        # rebin incoming sky sed to instrument dispersion\n        # rebin doesn't handle units, resulting in errors.\n        # avoid by stripping arrays of units\n        if isinstance(sed.flux,np.ndarray):\n            flux_perpix = rebin_1d_flux_box(sed.flux.value,sed.wave.value,self.wavelength.value)* u.photon/u.second/u.cm**2/u.AA\n        elif isinstance(sed.flux,u.quantity.Quantity):\n            flux_perpix = rebin_1d_flux_box(sed.flux.value,sed.wave.value,self.wavelength.value)* u.photon/u.second/u.cm**2/u.AA\n        else:\n            print('Cannot add sky emission. ****not implemented****')\n            return\n\n        # convert\n        nsky_A = flux_perpix.to('ph s**-1 m**-2 AA**-1') ## silent 'per arcsec2' here\n        nsky_fib = nsky_A * self.spectrograph.A_tel * self.spectrograph.fib_area.value # fib_area stripped of units because 'per arcsec2' is silent\n\n        ## this formula below for nobj_pix needs checking. I assume that 1 AA = 1/ldisp pixels. Correct?\n        nsky_pix = nsky_fib * self.spectrograph.ldisp\n        \n        ## print result for default Vband for now\n        ## find index of wavelength element closest to pivot position\n        idx = abs(self.wavelength.to('AA').value - 5479.35188).argmin()\n\n        print(f'\\nAt pivot wavelength 5479 Angstrom of Vband:')\n        print(f'Sky flam:           {sed.flux[idx].value:.5e} erg / (Angstrom cm2 s)' )\n        print(f'Sky photons/m2:     {nsky_A[idx]:.5e} ')\n        print(f'Spatial sampling:   {self.spectrograph.fib_area:.3f}')\n        #print(f'fraction of sky/fiber: {(self.spectrograph.fib_diam/fwhm)**2)}')\n        print(f'Sky photons/fiber:  {nsky_fib[idx]:.5e}')\n        print(f'Sky photons/pixel:  {nsky_pix[idx]:.5e}')\n\n\n        self.nsky_photlam += flux_perpix\n        self.nsky_A += nsky_A\n        self.nsky_fib += nsky_fib\n        self.nsky_pix += nsky_pix\n        \n        \n        if wavelength is not None:\n            print('rebinning of sky flux ***Not implemented yet***')\n        #    flux = self.spectrograph.rebin(wavelength, flux)\n        \n\n    def add_sky_transmission(self, trans, wavelength=None):\n        '''Add some sky flux\n\n        Parameters\n        ----------\n        trans : :class:`pysynphot.spectrum.CompositeSpectralElement` or\n                       `pysynphot.spectrum.ArraySpectralElement`\n            atmospheric transmission at the user-specified airmass\n            \n\n        wavelength : :class:`astropy.units.Quantity`\n            Wavelength bins for the transmission. If not given, then it\n            is not rebinned and the wavelengths of each bin must \n            correspond to the wavelength bins of the GAMAICA wavelength vector\n\n        '''\n        \n        ## TODO:\n        # 1. decide on rebinning\n        # 2. get values at pivot wavelength\n        \n        \n\n        # rebin incoming sky sed to instrument dispersion\n        trans_perpix = rebin_1d_trans_box(trans.throughput,trans.wave.value,self.wavelength.value)\n        \n        if wavelength is not None:\n            print('rebinning of sky flux ***Not implemented yet***')\n        #    flux = self.spectrograph.rebin(wavelength, flux)\n        \n        # add atmospheric transmission to tel+instr transmission\n        self.total_efficiency = self.spectrograph.efficiency_perpix * trans_perpix\n\n\n    def expose(self, texp, nexp=1, xbin=4,ybin=4):\n        '''Calculate the result of one exposure\n\n        WARNING: Seeing calculation is not included. This means all of the\n        target's flux is assumed to enter the fiber.\n\n\n        This basically scales the object and sky fluxes by the\n        exposure time, adds dark and readout noise, and calculates the\n        signal-to-noise ratio. The result is returned as a\n        :class:`astropy.table.Qtable`.\n\n        The noise is calculated by the formula\n        :math:`\\\\sqrt{(N_{obj} + N_{sky} + N_{dark}) ⋅ t_{exp} \\\n              + N_{ron}^2 ⋅ n_{exp}}`,\n        where all values are in electrons.\n\n\n        Parameters\n        ----------\n        texp : :class:`astropy.units.Quantity`\n            Total exposure time [s]\n\n        nexp : int\n            Number of exposures. Defaults to 1.\n\n        xbin : int\n            Binning in x direction\n\n        ybin : int\n            Binning in y direction\n\n        Returns\n        -------\n        :class:`astropy.table.QTable` (if no columns were specified)\n            Resulting table with the following columns:\n\n              * ``wavelength``: Wavelength [AA]\n              * ``ldisp``: Dispersion per pixel [AA]\n              * ``exptime``: exposure time [s]\n              * ``object``: Object count [e-]\n              * ``sky``: Sky background count [e-]\n              * ``dark``: CCD dark current [e-]\n              * ``ron``: CCD readout noise [e-]\n              * ``noise``: Noise count [e-]\n\n        '''\n\n        texp *= u.second\n        \n        #--- compute number of photons per pixel ------------------------\n        # counts per pixel over total exposure: projected fiber image on (un)binned\n        # CCD, system efficiency, reciprocal linear dispersion, exposure time\n\n        ## binning. Currently no binning\n        nobj_pix = self.nobj_pix * xbin *ybin /16.0\n\n        ## total_efficiency = tel+instr+atmo throughput (Q.E. included)\n        nobj_pix = nobj_pix * self.total_efficiency * texp\n        \n        ## binning. Currently no binning\n        nsky_pix = self.nsky_pix * xbin *ybin /16.0\n        \n        ## total_efficiency = tel+instr+atmo throughput (Q.E. included)\n        nsky_pix = nsky_pix * self.total_efficiency * texp\n\n        # summarize noise contributions\n\n        #shotnoise contributions per pixel\n        shotn_obj  = np.sqrt(nobj_pix)\n        shotn_sky  = np.sqrt(nsky_pix)\n\n        #dark current\n        ndark_pix   = self.spectrograph.dark_current * xbin * ybin * texp\n        shotn_dark   = np.sqrt(ndark_pix)\n        \n        # noise total\n        noise_pix = np.sqrt((shotn_obj**2).to_value(u.electron) +\n                            (shotn_sky**2).to_value(u.electron) +\n                            (shotn_dark**2).to_value(u.electron) +\n                            self.spectrograph.ron.to_value(u.electron)**2 ) *u.electron\n\n\n\n        #--- Signal-to-Noise per wavelength bin ------------\n        nwbin = 4/ybin\t# number of pixels to sum-up for one wavelength bin\n        \n        signal = nwbin * nobj_pix\n        backgr = nwbin * nsky_pix\n        #cal_noise =  backgr  * cal_limit\n        \n        \n        #noise  = sqrt( nwbin * (noise_pix)**2 + (cal_noise)**2 )\n        noise  = np.sqrt( nexp * nwbin * (noise_pix)**2 )\n        s2n    = (nexp*signal)/noise\n\n\n        return QTable({'wavelength': self.wavelength,\n                       'ldisp':np.repeat(self.spectrograph.ldisp,\n                                         len(self.wavelength)),\n                       #'gain': np.repeat(self.spectrograph.gain,\n                       #                  len(self.wavelength)),\n                       'exptime':np.repeat(texp,\n                                         len(self.wavelength)),\n                       'object': nobj_pix,\n                       'sky': nsky_pix,\n                       'dark': np.repeat(ndark_pix,len(self.wavelength)),\n                       'ron': np.repeat(np.sqrt(nexp) * self.spectrograph.ron, len(self.wavelength)),\n                       'noise': noise,\n                       'snr': s2n * u.pixel**-1})\n\n    @property\n    def wavelength(self):\n        return self.spectrograph.wavelength_perpix\n", "meta": {"hexsha": "4122270993ac08aff1e0bed440e5be75bc00021d", "size": 14069, "ext": "py", "lang": "Python", "max_stars_repo_path": "etc/exposure.py", "max_stars_repo_name": "genovevahx/gamaica", "max_stars_repo_head_hexsha": "43f4c0240cb14371033b14afc998a8d6edc04c5c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-04T12:34:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-04T12:34:56.000Z", "max_issues_repo_path": "etc/exposure.py", "max_issues_repo_name": "genovevahx/gamaica", "max_issues_repo_head_hexsha": "43f4c0240cb14371033b14afc998a8d6edc04c5c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "etc/exposure.py", "max_forks_repo_name": "genovevahx/gamaica", "max_forks_repo_head_hexsha": "43f4c0240cb14371033b14afc998a8d6edc04c5c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-04T09:13:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-04T09:13:25.000Z", "avg_line_length": 39.4089635854, "max_line_length": 147, "alphanum_fraction": 0.5890965954, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 3521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.3073580295544412, "lm_q1q2_score": 0.1821608339219369}}
{"text": "#!/usr/bin/env python\n\n#everything is needed to perform the script and maybe something else\nfrom numpy import *\nfrom scipy import *\nfrom scipy import integrate\nfrom scipy.interpolate import interp1d\nimport pyfits\nimport os,sys,string,shutil,math\nfrom pylab import *\nfrom scipy.optimize import curve_fit\nimport s3 #import metadata \nfrom s3.utilities import *  #import definitions\n# pre-set plot parameters, resolution untouched since it is not needed (default=80 dpi) \nfrom pylab import rcParams\nrcParams['figure.figsize'] = 11, 8\nrcParams['figure.subplot.top'] = 0.95\nrcParams['figure.subplot.right'] = 0.95\nrcParams['figure.subplot.left'] = 0.11\n###########################################\npypath = os.path.expandvars('$HOME')           # it copies login.cl if it is not in the same directory\nif not os.path.isfile('login.cl'):\n    shutil.copyfile(pypath+'/iraf/login.cl','login.cl')\n###########################################\n\n################### for the help ##################\nfrom optparse import OptionParser\n\ndescription = \" K-correction script for a single, flux calibrated spectrum \"\nusage = \"%prog \"\nif __name__ == \"__main__\":\n    parser = OptionParser(usage=usage, description=description, version=\"%prog \" + str(s3.__version__))\n    parser.add_option(\"-v\", \"--verbose\",dest=\"verbose\",\\\n                  action=\"store_true\",default=False,\n                  help='Print tasks description')\n    parser.add_option(\"-r\", \"--redshifterr\",dest=\"redshifterr\", action=\"store\", type=\"float\" ,default=None,\n                  help='Change the default error on your redshift (+/- 0.005) to estimate the K-correction errors')\n    option,args = parser.parse_args()\n\n###### moved here because OptionParser --version conflicts with pyraf version########\n#what we need from iraf\nfrom pyraf import iraf\n\n########### Options that can be changed thanks to option parser #########\nif option.redshifterr == None:\n    _redshifterr = 0.005\nelse:\n    _redshifterr = option.redshifterr\n################ internal description #############\n\nh=\"######################################################################\\n\"+\\\n  \"#########  SuperNova Algorithm for K-correction Evaluation  ##########\\n\"+\\\n  \"##################           S.N.A.K.E.           ####################\\n\"+\\\n  \"##########          C. Inserra  v1.1.0 29/10/2015          ###########\\n\"+\\\n  \"######################################################################\\n\"+\\\n  \" K-correction based on the formula m(x) = M(y) + DM + K(y,x)\\n\"+\\\n  \" BE SURE that the spectrum is flux calibrated  \\n\"+ \\\n  \" If you use this code and find it useful, please give a thought \\n\"+ \\\n  \" to cite it. \\n\"+ \\\n  \" The reference is Inserra et al. 2015, ApJ submitted \\n\"+\\\n  \"######################################################################\\n\"\n\nprint h \n\n#the path where the metatabs data are\nfilterdir=s3.__path__[0]+'/metadata/' # To set the directory where are the synphot tabs created\n\n# cleaning process\nos.system('rm -rf sn.txt')\nos.system('rm -rf sn.fits')\nos.system('rm -rf sn_xbbody.txt')\nos.system('rm -rf sn_dez_xbbody.txt')\nos.system('rm -rf sn_dez_xbbody_err1.txt')\nos.system('rm -rf sn_dez_xbbody_err2.txt')\nos.system('rm -rf bbody_sn_dez_fit.dat')\nos.system('rm -rf bbody_sn_dez_fit_err1.dat')\nos.system('rm -rf bbody_sn_dez_fit_err2.dat')\nos.system('rm -rf bbody_sn_dez_fit.fits')\nos.system('rm -rf bbody_sn_dez_fit_err1.fits')\nos.system('rm -rf bbody_sn_dez_fit_err2.fits')\nos.system('rm -rf bbody_sn_fit.fits')\nos.system('rm -rf bbody_sn_fit.dat')\nos.system('rm -rf sn_dez.txt')\nos.system('rm -rf sn_dez_err1.txt')\nos.system('rm -rf sn_dez_err2.txt')\nos.system('rm -rf sn_dez.fits')\nos.system('rm -rf sn_dez_err1.fits')\nos.system('rm -rf sn_dez_err2.fits')\nos.system('rm -rf sn_dez_dered.fits')\nos.system('rm -rf sn_dez_dered_err1.fits')\nos.system('rm -rf sn_dez_dered_err2.fits')\nos.system('rm -rf sn_dez_dered.txt')\nos.system('rm -rf sn_dez_dered_err1.txt')\nos.system('rm -rf sn_dez_dered_err2.txt')\nos.system('rm -rf sn_galdered_dez.fits')\nos.system('rm -rf sn_galdered_dez_err1.fits')\nos.system('rm -rf sn_galdered_dez_err2.fits')\nos.system('rm -rf sn_galdered.fits')\nos.system('rm -rf bsn_combo_dez.fits')\nos.system('rm -rf bsn_combo_dez_err1.fits')\nos.system('rm -rf bsn_combo_dez_err2.fits')\nos.system('rm -rf bsn_combo_dez.txt')\nos.system('rm -rf bsn_combo_dez_err1.txt')\nos.system('rm -rf bsn_combo_dez_err2.txt')\nos.system('rm -rf bsn_combo.fits')\nos.system('rm -rf bsn_combo.txt')\n\n\n#######################################################\n# Variable definitions\n#######################################################\n\nprint ''\nprint '#################################'\nprint '#   Available filters and ID    #'\nprint '#-------------------------------#'\nprint '# BESSEL:  U  B  V  R  I        #'\nprint '# SLOAN:   us gs rs is zs       #'\nprint '# UV:  NUV  FUV  uw2  um2  uw1  #'\nprint '# NIR:     J  H  K              #' \nprint '#################################'\nprint ''  \n\n\nfilter1 = raw_input('Which is the observed filter FUV,NUV,uvw2,uvm2,uvw1,U,B,V,R,I,us,gs,rs,is,zs,J,H,K [rs] ? ')\nif not filter1:\n    filter1 = 'rs'\n\nprint ''\n\nif filter1 == 'K' or filter1 == 'uvw1' or filter1 == 'uvw2' or filter1 == 'uvm2' or filter1 == 'H' or filter1 =='J':\n    questionsys1 = raw_input('Do you want to use the Vega or the AB system ([vega],ab) ? ')\n    if not questionsys1:\n        questionsys1 = 'vega'\n\n    if questionsys1 == 'ab': #assign the new file with the ZP in AB magnitude\n        if filter1 == 'K':\n            filter1 = 'K_ab'\n        elif filter1 == 'J':\n            filter1 = 'J_ab'\n        elif filter1 == 'H':\n            filter1 = 'H_ab'\n        elif filter1 == 'uvw1':\n            filter1 = 'uvw1_ab'\n        elif filter1 == 'uvw2':\n            filter1 = 'uvw2_ab'\n        elif filter1 == 'uvm2':\n            filter1 ='uvm2_ab'\n\nprint ''\n_redshift = raw_input('What is the redshift [0.1] ? ')\nif not _redshift:\n    redshift = 0.1\nelse: \n    redshift = float(_redshift)\n\nprint ''\n\n#######################################################\n# Filter1 and its definitions\n#######################################################\nlcf = open(filterdir+filter1+'.txt','r')      # defintion of the file\nriga = lcf.readlines()             # list of lines\nriga1 = riga[4:len(riga)]  #list of lines where the wave and transmission are stored\nlcf.close()\nzp_ef = float(riga[0]) #zero point in energy flux (erg/cm^2/s)\nzp_ef_err = zp_ef * 1.0075\nfilter_ew = riga[1] #equivalent width of the filter\npeak_wave = float(riga[2]) # peak wavelength of the filter\nsystem = riga[3] # system used: vega or ab\nwavefilter, wavefilter_dmod, transmission= [], [], []\nfor line in riga1:\n    p = line.split()\n    wavefilter.append(float(p[0]))\n    wavefilter_dmod.append(float(p[0])/(1+float(redshift)))\n    transmission.append(float(p[1]))\n\nwavefilterv = array(wavefilter)\nwavefilter_dmodv = array(wavefilter_dmod) #plotting purpose\ntransmissionv = array(transmission)\ntransmission_initv = array(transmission) #plotting purpose\nwavefilter_initv = array(wavefilter) #plotting purpose\nfil_obs_min= min(wavefilterv)\nfil_obs_max= int(max(wavefilterv)) #integer is needed for a sharper cut-off\n#############################################################\n\nband=[1941,2246,2604.57,3561.8,4718.9,6185.2,7499.8,8961.5,3652,4448,5505,6555,7900.4,1524,2320,12370,16471,22126]\nfilist=['uvw2','uvm2','uvw1','us','gs','rs','is','zs','U','B','V','R','I','FUV','NUV','J','H','K']\n\nprint ''\nprint '##########################################################################'\nprint 'NB: in a cross K-correction the filter shapes (observed and rest-frame) are the most similar. As a first approximation a wise cross K-correction minimises the difference between the redshifted peak wavelength of the observed filter (value reported in the table below) and the peak wavelength of the rest-frame filter. This programm will evaluate the errors on th K-correction based on those on the redshift, the zero points for the observed and rest-frame filters and the use of a blackbody function instead of a proper spectrum (only if this function is used by the programme). The propagation of the erros is treated as reported in Inserra et al. (2015), ApJ submitted '\nprint '##########################################################################'\nprint 'UV GALEX FUV=',band[13], 'NUV=', band[14]\nprint 'UV Swift+UVOT uvw2=',band[0], 'uvm2=', band[1], 'uvw1=', band[2]\nprint 'SLOAN  us=',band[3],'gs=',band[4],'rs=',band[5],'is=',band[6],'zs=',band[7]\nprint 'BESSEL U=',band[8],'B=',band[9],'V=',band[10],'R=',band[11],'I=',band[12]\nprint 'NIR   J=',band[15],'H=',band[16],'K=',band[17]\nprint '##########################################################################' \nprint ''\nprint '\\033[34mChoose your preferred rest-frame band (cross K-correction is suggested) \\033[0m'\nprint ''\n\nprint '\\033[34mCentral wavelength rest-frame filter >>> \\033[0m', peak_wave/(1+float(redshift))\nb = array(band) - peak_wave/(1+redshift)\nprint '\\033[34mFilter suggested for the cross K-correction >>> \\033[0m', filist[argmin(abs(b))]\nprint ''\n\nfilter2 = raw_input('To which rest-filter do you want to convert the mangitude FUV,NUV,uvw2,uvm2,uvw1,U,B,V,R,I,us,gs,rs,is,zs,J,H,K [rs] ? ')\nif not filter2:\n    filter2 = 'rs'\n\nprint ''\n\nif filter2 == 'K' or filter2 == 'uvw1' or filter2 == 'uvw2' or filter2 == 'uvm2' or filter2 == 'H' or filter2 =='J':\n    questionsys2 = raw_input('Do you want to use the Vega or the AB system ([vega],ab) ? ')\n    if not questionsys2:\n        questionsys2 = 'vega'\n\n    if questionsys2 == 'ab': #assign the new file with the ZP in AB magnitude\n        if filter2 == 'K':\n            filter2 = 'K_ab'\n        elif filter2 == 'J':\n            filter2 = 'J_ab'\n        elif filter2 == 'H':\n            filter2 = 'H_ab'\n        elif filter2 == 'uvw1':\n            filter2 = 'uvw1_ab'\n        elif filter2 == 'uvw2':\n            filter2 = 'uvw2_ab'\n        elif filter2 == 'uvm2':\n            filter2 ='uvm2_ab'\n\nprint ''\n#######################################################\n# Filter2 and its definitions\n#######################################################\nlcfr = open(filterdir+filter2+'.txt','r')      # defintion of the file\nrigar = lcfr.readlines()             # list of lines\nrigar1 = rigar[4:len(rigar)]  #list of lines where wavelength and transmission are stored\nlcfr.close()\nzp_ef_rest = float(rigar[0]) #zero point in energy flux (erg/cm^2/s)\nzp_ef_rest_err = zp_ef_rest * 1.0075\nfilter_ew_rest = rigar[1] #equivalent width of the filter\npeak_wave_rest = float(rigar[2]) # peak wavelength of the filter\nsystem_rest = rigar[3] # system used: vega or ab\nwavefilter_rest, transmission_rest= [], []\nfor line in rigar1:\n    p = line.split()\n    wavefilter_rest.append(float(p[0]))\n    transmission_rest.append(float(p[1]))\n\nwavefilter_restv = array(wavefilter_rest)\ntransmission_restv = array(transmission_rest)\ntransmission_restinitv = array(transmission_rest) #plotting purpose\nwavefilter_restinitv = array(wavefilter_rest) #plotting purpose\nfil_rest_min= min(wavefilter_restv)\nfil_rest_max= int(max(wavefilter_restv)) #integer is needed for a sharper cut-off\n#############################################################\n\n_ebvg = raw_input('What is the galactic E(B-V) [0.0] ? ')\nif not _ebvg:\n    ebvg = 0.0\nelse: \n    ebvg = float(_ebvg)\nprint ''\n\n_ebvh = raw_input('What is the host E(B-V) [0.0] ? ')\nif not _ebvh:\n    ebvh = 0.0\nelse: \n    ebvh = float(_ebvh)\nprint ''\n\n_sn = raw_input('What SN spectrum ( e.g. 2011ke_) ? ')\n\n#### it recognizes automatically the extension of your file and convert to fits\nfileName, fileExtension = os.path.splitext(_sn)\nif fileExtension == '.txt' or fileExtension == '.dat' or fileExtension == '.asci' or fileExtension == '.ascii':\n    iraf.rspec(_sn,fileName+'.fits',flux='no',dtype='interp')\n    sn = fileName+'.fits'\nelse:\n    sn = _sn\n\n\n#############################\n# Magnitude system definitions and check avriable\n#############################\n\nprint ''\nprint '#############################################'\nprint 'Observed frame magnitude system = ',system\nprint 'Rest frame magnitude system = ',system_rest\nprint 'Observed passband = ',filter1\nprint 'Output filter (rest-frame) = ',filter2\nprint 'SN redshift = ',redshift,'+/-',_redshifterr\nprint 'E(B-V) galactic = ',ebvg\nprint 'E(B-V) host = ',ebvh\nprint '#############################################'\nprint ''\nconfort = raw_input('Are you happy with those entries ? ([yes],no) ')\nif not confort:\n    confort = 'yes'\nif confort == 'no' or confort == 'n':\n    sys.exit(\"Bye Bye\")\nprint ''\n###################################\n##### Mananging the spectrum\n###################################\n\nredserrspace1 = redshift+_redshifterr\nredserrspace2 = redshift-_redshifterr\nspec = sn + \"[*,1,1]\"            # generally multidimension\niraf.imcopy(sn+'[*,1,1]','sn.fits',verbose='no')             # to create a onedimension fit to use during the script\n\n# redshift correction without absorption                \nprint '\\033[34m*** correcting the spectrum for redshift without Milky Way absorption *** \\033[0m'\ntry:\n    iraf.dopcor('sn.fits','sn_dez.fits', redshift=redshift, isveloc='no', flux='no',factor=3)\n    iraf.dopcor('sn.fits','sn_dez_err1.fits', redshift=redserrspace1, isveloc='no', flux='no',factor=3)\n    iraf.dopcor('sn.fits','sn_dez_err2.fits', redshift=redserrspace2, isveloc='no', flux='no',factor=3)\nexcept:\n    print ' WARNING: Problem to redshift the spectrum'\n\nif ebvh == 0.0:\n    # galaxy and host reddening correction\n    print '\\033[31m'+'*** correcting spectrum for galactic reddening ***\\033[0m'\n    ebv = ebvg+ebvh\n    print '\\033[31m Total E(B-V) = galactic E(B-V) = \\033[0m',ebv\n    try:\n            iraf.unlearn(\"deredden\")\n            iraf.dered('sn_dez.fits',\"sn_dez_dered.fits\", value=ebv, R=3.1, type='E(B-V)',overrid='yes',uncorre='no')\n            iraf.dered('sn_dez_err1.fits',\"sn_dez_dered_err1.fits\", value=ebv, R=3.1, type='E(B-V)',overrid='yes',uncorre='no')\n            iraf.dered('sn_dez_err2.fits',\"sn_dez_dered_err2.fits\", value=ebv, R=3.1, type='E(B-V)',overrid='yes',uncorre='no')\n    except:\n            print 'WARNING: it is not possible to correct the spectrum for galactic reddenning '\n            try:\n                iraf.unlearn(\"scopy\")\n                iraf.scopy('sn_dez.fits',\"sn_dez_dered.fits\", w1='INDEF', w2='INDEF',format='multispec')\n                iraf.scopy('sn_dez_err1.fits',\"sn_dez_dered_err1.fits\", w1='INDEF', w2='INDEF',format='multispec')\n                iraf.scopy('sn_dez_err2.fits',\"sn_dez_dered_err2.fits\", w1='INDEF', w2='INDEF',format='multispec')\n            except:\n                print 'WARNING: problem to copy the spectrum or with the spectrum fits format'\n\nelse:\n    #Galaxy reddening correction\n    print '\\033[31m'+'*** correcting spectrum for galactic reddening ***\\033[0m'\n    try:\n            iraf.dered(sn + '[*,1,1]',\"sn_galdered.fits\", value=ebvg, R=3.1, type='E(B-V)')\n    except:\n            print ' WARNING: it is not possible to correct the spectrum for galactic reddenning '\n            try:\n                iraf.scopy(sn + '[*,1,1]',\"sn_galdered.fits\", w1='INDEF', w2='INDEF',format='multispec')\n            except:\n                print ' WARNING: a problem is appeared to copy the spectrum, problems with the spectrum fits format'\n    \n    print '\\033[34m*** correcting the spectrum for redshift ***\\033[0m'\n    try:\n            iraf.dopcor('sn_galdered.fits','sn_galdered_dez.fits', redshift=redshift, isveloc='no', flux='no',factor=3)\n            iraf.dopcor('sn_galdered.fits','sn_galdered_dez_err1.fits', redshift=redserrspace1, isveloc='no', flux='no',factor=3)\n            iraf.dopcor('sn_galdered.fits','sn_galdered_dez_err2.fits', redshift=redserrspace2, isveloc='no', flux='no',factor=3)\n    except:\n            print ' WARNING: Problem to redshift the spectrum'\n    \n    # host reddening correction\n    print '\\033[31m*** correcting spectrum for host reddening ***\\033[0m'\n    ebv = ebvg+ebvh\n    print '\\033[31m NOW total E(B-V) = \\033[0m',ebv\n    iraf.hedit(\"sn_galdered_dez.fits\", 'DEREDDEN', add='no', addonly='no', delete='yes', verify ='no', show='no')\n    iraf.hedit(\"sn_galdered_dez_err1.fits\", 'DEREDDEN', add='no', addonly='no', delete='yes', verify ='no', show='no')\n    iraf.hedit(\"sn_galdered_dez_err2.fits\", 'DEREDDEN', add='no', addonly='no', delete='yes', verify ='no', show='no')\n    iraf.dered('sn_galdered_dez.fits',\"sn_dez_dered.fits\", value=ebvh, R=3.1, type='E(B-V)',overrid='yes')\n    iraf.dered('sn_galdered_dez_err1.fits',\"sn_dez_dered_err1.fits\", value=ebvh, R=3.1, type='E(B-V)',overrid='yes')\n    iraf.dered('sn_galdered_dez_err2.fits',\"sn_dez_dered_err2.fits\", value=ebvh, R=3.1, type='E(B-V)',overrid='yes')\n\n#################################################################\n#### Preparation for wavelength check\n#################################################################\n\n\nspectrum=iraf.wspec(\"sn.fits\",\"sn_xbbody.txt\", header='no')\nlcf = open('sn_xbbody.txt','r')      \nriga = lcf.readlines()             \nlcf.close()\nwave,flux= [],[]\nfor line in riga:\n    p = line.split()\n    wave.append(float(p[0]))\n    flux.append(float(p[1]))\n\nwavev = array(wave)\nfluxv = array(flux)\nwaveobs_min= min(wavev)\nwaveobs_max= max(wavev)\n\nspectrum=iraf.wspec(\"sn_dez.fits\",\"sn_dez_xbbody.txt\", header='no')\nlcf = open('sn_dez_xbbody.txt','r')      \nriga = lcf.readlines()             \nlcf.close()\nwave,flux= [],[]\nfor line in riga:\n    p = line.split()\n    wave.append(float(p[0]))\n    flux.append(float(p[1]))\n\nwavedezv = array(wave)\nfluxdezv = array(flux)\nwaverest_min= min(wavedezv)\nwaverest_max= max(wavedezv)\n\nspectrum=iraf.wspec(\"sn_dez_err1.fits\",\"sn_dez_xbbody_err1.txt\", header='no')\nlcf = open('sn_dez_xbbody_err1.txt','r')      \nriga = lcf.readlines()             \nlcf.close()\nwave,flux= [],[]\nfor line in riga:\n    p = line.split()\n    wave.append(float(p[0]))\n    flux.append(float(p[1]))\n\nwavedezv_err1 = array(wave)\nfluxdezv_err1 = array(flux)\n\nspectrum=iraf.wspec(\"sn_dez_err2.fits\",\"sn_dez_xbbody_err2.txt\", header='no')\nlcf = open('sn_dez_xbbody_err1.txt','r')      \nriga = lcf.readlines()             \nlcf.close()\nwave,flux= [],[]\nfor line in riga:\n    p = line.split()\n    wave.append(float(p[0]))\n    flux.append(float(p[1]))\n\nwavedezv_err2 = array(wave)\nfluxdezv_err2 = array(flux)\n\n################################\n### Define the different cases for K-correction\n################################\nsplit = 0\n\nif ((waveobs_min-fil_obs_min) > 50) or ((fil_obs_max-waveobs_max) > 50):\n    print ''\n    if (waveobs_min-fil_obs_min) > 50:\n        print waveobs_min-fil_obs_min,' Angstrom not covered by the observed spectrum in the blue' \n        waveout = waveobs_min-fil_obs_min\n    if (fil_obs_max-waveobs_max) > 50:\n        print fil_obs_max-waveobs_max,' Angstrom not covered by the observed spectrum in the red'\n        waveout = fil_obs_max-waveobs_max\n        ############################################\n        # Prevent small exceptions for blue bands or the extreme of the NIR\n        ############################################\n    if filter1 != 'U' or filter1 != 'us' or filter1 != 'K' or filter1 != 'uvw1' or filter1 != 'uvw2' or filter1 != 'uvm2' or filter1 != 'NUV' or filter1 != 'FUV' or filter1 != 'uvw1_ab' or filter1 != 'uvw2_ab' or filter1 != 'uvm2_ab' or filter1 != 'K_ab':\n\n        ###############################\n        ### BBody evaluation of the observed spectrum\n        ###############################\n        BBparams, covar = curve_fit(bbody,wavev,fluxv,p0=(10000,1E-16)) #intial guess\n        T= BBparams[0]\n        Area = BBparams[1]\n        print '\\nBlackbody temperature observed spectrum = %.0f +\\- %.0f K\\n' % (T,np.sqrt(covar[0,0]))\n        outputname = \"bbody_sn_fit.dat\" #% T\n        file = open(outputname,\"w\")\n        file.write(\"# Blackbody temperature = %.0f +\\- %.0f K\\n\" % (T,np.sqrt(covar[0,0])))\n        w,f = [],[]\n        for wav in range(900,24005):\n            file.write(\"%g\\t%g\\n\" % (wav,bbody(wav,T,Area)))\n            w.append(wav)\n            f.append(bbody(wav,T,Area))\n\n        iraf.rspec('bbody_sn_fit.dat','bbody_sn_fit.fits', title='bbodyfit',flux='no',dtype='interp',crval1=900,cdelt1=1)\n        iraf.scombine('bbody_sn_fit.fits,sn.fits,sn.fits,sn.fits', 'bsn_combo.fits',combine='median')\n        subplot(211)\n        plot(wavev,fluxv,'k-',w,f,'r--')\n        ylabel('Flux', size=12)\n        subplot(212)\n        iraf.wspec('bsn_combo.fits','bsn_combo.txt',header='no')\n        lcf = open('bsn_combo.txt','r')\n        riga = lcf.readlines()\n        lcf.close()\n        wave,flux= [],[]\n        for line in riga[:len(riga)-5]:\n            p = line.split()\n            wave.append(float(p[0]))\n            flux.append(float(p[1]))\n\n        wavev = array(wave)\n        fluxv = array(flux)\n        wavesp_min= min(wavev)\n        wavesp_max= int(max(wavev)) #needed to avoid problems with interp1d\n        plot(wave,flux,'k-')\n        ylabel('Flux', size=12)\n        print '#######################################'\n        print '\\033[4mDO THAT IS TOO RISKY!!\\033[0m I have created for you a \\033[1mbbody_sn_fit.fits\\033[0m file with the blackbody fit of your observed spectrum. I would suggest to try with a template covering that wavelength region! However, if you like to gamble we can continue using the spectrum on the bottom plot (NB: You have to close the window to continue).'\n        print '#######################################'\n        show()\n        answer = raw_input('Do you want to continue ? ([yes],no) ')\n        if not answer:\n            answer = 'yes'\n        if answer == 'no' or answer =='n':\n            sys.exit(\"Bye Bye\")\n\n        elif answer == 'yes':\n            print '#######################################'\n            print 'OK, but have in mind that the value could be unreasonable. Thus I would suggest you to also use a template and compare the K-correction values between the two methods.'\n            print '#######################################'   \n            print '\\033[31m\\033[7m***BBODY version activated***\\033[0m'\n\n        lcf = open('bsn_combo.txt','r')\n        riga = lcf.readlines()\n        lcf.close()\n        wave,flux= [],[]\n        for line in riga:\n            p = line.split()\n            if float(line.split()[0]) >= fil_obs_min and float(line.split()[0]) <= fil_obs_max: #to match the spectrum wavelegnths to those of the filter\n                wave.append(float(p[0]))\n                flux.append(float(p[1]))\n            \n        wavev = array(wave)\n        fluxv = array(flux)\n        wavesp_min= min(wavev)\n        wavesp_max= int(max(wavev)) #needed to avoid problems with interp1d\n\n        # interpolating the two responses to match the length and sampling coverage\n        conf = conv(wavev,fluxv,wavefilterv,transmissionv,wavesp_min,wavesp_max,fil_obs_min,fil_obs_max)\n\n        ##################################\n        ### Evaluating the magnitudes\n        ##################################\n        flux_obs = max(integrate.cumtrapz(conf[0],conf[1])) # using trapezoidal rule to integrate\n        flux_obs_err = flux_obs * (1+(waveout-50)*0.0001)\n\n        print 'Apparent magnitude in observed frame ('+filter1+') = ', -2.5*log10(flux_obs/zp_ef)\n        iraf.dopcor('bsn_combo.fits','bsn_combo_dez.fits', redshift=redshift, isveloc='no', flux='no',factor=3)\n        iraf.dopcor('bsn_combo.fits','bsn_combo_dez_err1.fits', redshift=redserrspace1, isveloc='no', flux='no',factor=3)\n        iraf.dopcor('bsn_combo.fits','bsn_combo_dez_err2.fits', redshift=redserrspace2, isveloc='no', flux='no',factor=3)\n        iraf.wspec('bsn_combo_dez.fits','bsn_combo_dez.txt',header='no')\n        iraf.wspec('bsn_combo_dez_err1.fits','bsn_combo_dez_err1.txt',header='no')\n        iraf.wspec('bsn_combo_dez_err2.fits','bsn_combo_dez_err2.txt',header='no')\n\n        lcf = open('bsn_combo_dez.txt','r')\n        riga = lcf.readlines()\n        lcf.close()\n        rwave,rflux= [],[]\n        for line in riga:\n            p = line.split()\n            if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n                rwave.append(float(p[0]))\n                rflux.append(float(p[1]))\n            \n        wave_dezv = array(rwave)\n        flux_dezv = array(rflux)\n        wavesp_dez_min= min(wave_dezv)\n        wavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n\n        # interpolating the two responses in the rest wavelength to match the length and sampling coverage\n        conf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n\n        flux_rest = max(integrate.cumtrapz(conf[0],conf[1]))\n\n        ###### doing that again for the errors  ############################################################\n        lcf = open('bsn_combo_dez_err1.txt','r')\n        riga = lcf.readlines()\n        lcf.close()\n        rwave,rflux= [],[]\n        for line in riga:\n            p = line.split()\n            if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n                rwave.append(float(p[0]))\n                rflux.append(float(p[1]))\n            \n        wave_dezv = array(rwave)\n        flux_dezv = array(rflux)\n        wavesp_dez_min= min(wave_dezv)\n        wavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n\n        conf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n\n        flux_rest_err1 = max(integrate.cumtrapz(conf[0],conf[1]))\n\n        lcf = open('bsn_combo_dez_err2.txt','r')\n        riga = lcf.readlines()\n        lcf.close()\n        rwave,rflux= [],[]\n        for line in riga:\n            p = line.split()\n            if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n                rwave.append(float(p[0]))\n                rflux.append(float(p[1]))\n            \n        wave_dezv = array(rwave)\n        flux_dezv = array(rflux)\n        wavesp_dez_min= min(wave_dezv)\n        wavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n\n        conf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n\n        flux_rest_err2 = max(integrate.cumtrapz(conf[0],conf[1]))\n        ##################################################################################################\n\n        print 'Apparent magnitude in rest frame ('+filter2+') = ', -2.5*log10(flux_rest/zp_ef_rest)\n    \n        ##################################\n        ### Recap of what parameters have been used\n        ##################################\n\n        print \"\\033[32m\"+'Observed passband = ',filter1\n        print \"\\033[32m\"+'Output filter (rest-frame)= ',filter2\n        print \"\\033[32m\"+'SN redshift = ',redshift,'+/-',_redshifterr\n        print '\\033[32mBlackbody temperature (observed) = %.0f +\\- %.0f K' % (T,np.sqrt(covar[0,0]))\n        print \"\\033[32m\"+'NONE reddening has been used in this version\\033[0m'\n    \n        ##################################\n        ### K-correction evaluation\n        ##################################\n        kcorrrest_bb_wor=-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest)) +(2.5*log10(1+redshift))\n        \n        kcorrrest_bb_wor_err1=-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest_err1/zp_ef_rest)) +(2.5*log10(1+redserrspace1))\n        kcorrrest_bb_wor_err2=-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest_err2/zp_ef_rest)) +(2.5*log10(1+redserrspace2))\n        kcorrerror_bb_wor=(abs(kcorrrest_bb_wor_err1 - kcorrrest_bb_wor) + abs(kcorrrest_bb_wor_err2 - kcorrrest_bb_wor))/2\n        kcorrerrfilt_obs = abs((-2.5*log10(flux_obs/zp_ef_err) - (-2.5*log10(flux_rest/zp_ef_rest)))-(-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest))))\n        kcorrerrfilt_rest = abs((-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest_err)))-(-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest))))\n        Kcorrerr_bb = abs((-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest)) +(2.5*log10(1+redshift)))-(-2.5*log10(flux_obs_err/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest)) +(2.5*log10(1+redshift))))\n        kcorrerr = sqrt((kcorrerror_bb_wor**2 + kcorrerrfilt_obs**2 + kcorrerrfilt_rest**2 + Kcorrerr_bb**2)/4)\n\n        print '#######################################' \n        print '\\033[4m'+'K-correction TOTALLY based on an hybrid (if you want to add this value to the observed mag, you have to flip the sign)\\033[0m, without reddening and from observed filter '+filter1+' on the hybrid (SN+observed blackbody) observed spectrum to rest-frame filter '+filter2+' on the hybrid (SN+blackbody) = %0.4f' % (kcorrrest_bb_wor),'+/- %0.4f' % (kcorrerr)\n        print '#######################################'\n        split = 1\n\n    elif filter1 == 'U' or filter1 == 'us' or filter1 == 'uvw1' or filter1 == 'uvw2' or filter1 == 'uvm2' or filter1 == 'NUV' or filter1 == 'FUV' or filter1 == 'uvw1_ab' or filter1 == 'uvw2_ab' or filter1 == 'uvm2_ab':\n        print waveobs_min-fil_obs_min,' Angstrom not covered by the observed spectrum in the blue'\n        print ''\n        print '#######################################'\n        print '\\033[4mARE YOU SURE ABOUT THAT?\\033[0m You are actually using a filter that does not cover your observed spectrum and is too blue (U, us or UV filter). Use a template spectrum, it is better and safer!!'\n        print '#######################################'\n        sys.exit(\"Bye Bye\")\n\n    elif filter1 == 'K' or filter1 == 'K_ab':\n        print fil_obs_max-waveobs_max,' Angstrom not covered by the observed spectrum in the red'\n        print ''\n        print '#######################################'\n        print '\\033[4mARE YOU SURE ABOUT THAT?\\033[0m You are actually using a filter that does not cover your observed spectrum and is too red (K). Use a template spectrum, it is better and safer!!'\n        print '#######################################'\n        sys.exit(\"Bye Bye\")\n\nif split == 0:\n\n    if ((waverest_min-fil_rest_min) > 50) or ((fil_rest_max-waverest_max) > 50):\n        print ''\n        if (waverest_min-fil_rest_min) > 50:\n            print waverest_min-fil_rest_min,' Angstrom not covered by the restframe spectrum in the blue'\n            waveout = waverest_min-fil_rest_min\n        elif (fil_rest_max-waverest_max) > 50:\n            print fil_rest_max-waverest_max,' Angstrom not covered by the restframe spectrum in the red'\n            waveout = fil_rest_max-waverest_max\n    \n        print ''\n    \n        ###################\n        ### BBody of the rest frame spectrum\n        ###################\n    \n        BBparams, covar = curve_fit(bbody,wavedezv,fluxdezv,p0=(10000,1E-16)) #initial guess\n        T= BBparams[0]\n        Area = BBparams[1]\n        print '\\nBlackbody temperature = %.0f +\\- %.0f K\\n' % (T,np.sqrt(covar[0,0]))\n        outputname = \"bbody_sn_dez_fit.dat\" #% T\n        file = open(outputname,\"w\")\n        file.write(\"# Blackbody temperature = %.0f +\\- %.0f K\\n\" % (T,np.sqrt(covar[0,0])))\n        w,f = [],[]\n        for wav in range(900,24005):\n           file.write(\"%g\\t%g\\n\" % (wav,bbody(wav,T,Area)))\n           w.append(wav)\n           f.append(bbody(wav,T,Area))\n    \n        ######### BBody for the error spectra ################################################\n        BBparams, covar = curve_fit(bbody,wavedezv_err1,fluxdezv_err1,p0=(10000,1E-16)) #initial guess\n        T= BBparams[0]\n        Area = BBparams[1]\n        outputname = \"bbody_sn_dez_fit_err1.dat\" #% T\n        file = open(outputname,\"w\")\n        file.write(\"# Blackbody temperature = %.0f +\\- %.0f K\\n\" % (T,np.sqrt(covar[0,0])))\n        w,f = [],[]\n        for wav in range(900,24005):\n           file.write(\"%g\\t%g\\n\" % (wav,bbody(wav,T,Area)))\n           w.append(wav)\n           f.append(bbody(wav,T,Area))\n\n        BBparams, covar = curve_fit(bbody,wavedezv_err2,fluxdezv_err2,p0=(10000,1E-16)) #initial guess\n        T= BBparams[0]\n        Area = BBparams[1]\n        outputname = \"bbody_sn_dez_fit_err2.dat\" #% T\n        file = open(outputname,\"w\")\n        file.write(\"# Blackbody temperature = %.0f +\\- %.0f K\\n\" % (T,np.sqrt(covar[0,0])))\n        w,f = [],[]\n        for wav in range(900,24005):\n           file.write(\"%g\\t%g\\n\" % (wav,bbody(wav,T,Area)))\n           w.append(wav)\n           f.append(bbody(wav,T,Area))\n        ########################################################################################   \n\n        iraf.rspec('bbody_sn_dez_fit.dat','bbody_sn_dez_fit.fits', title='bbodyfit',flux='no',dtype='interp',crval1=900,cdelt1=1)\n        iraf.rspec('bbody_sn_dez_fit_err1.dat','bbody_sn_dez_fit_err1.fits', title='bbodyfit',flux='no',dtype='interp',crval1=900,cdelt1=1)\n        iraf.rspec('bbody_sn_dez_fit_err2.dat','bbody_sn_dez_fit_err2.fits', title='bbodyfit',flux='no',dtype='interp',crval1=900,cdelt1=1)\n        iraf.scombine('bbody_sn_dez_fit.fits,sn_dez.fits,sn_dez.fits,sn_dez.fits', 'bsn_combo_dez.fits',combine='median')\n        iraf.scombine('bbody_sn_dez_fit_err1.fits,sn_dez_err1.fits,sn_dez_err1.fits,sn_dez_err1.fits', 'bsn_combo_dez_err1.fits',combine='median')\n        iraf.scombine('bbody_sn_dez_fit_err2.fits,sn_dez_err2.fits,sn_dez_err2.fits,sn_dez_err2.fits', 'bsn_combo_dez_err2.fits',combine='median')\n        subplot(211)\n        plot(wavedezv,fluxdezv,'k-',w,f,'r--')\n        ylabel('Flux', size=12)\n        subplot(212)\n        iraf.wspec('bsn_combo_dez.fits','bsn_combo_dez.txt',header='no')\n        iraf.wspec('bsn_combo_dez_err1.fits','bsn_combo_dez_err1.txt',header='no')\n        iraf.wspec('bsn_combo_dez_err2.fits','bsn_combo_dez_err2.txt',header='no')\n        lcf = open('bsn_combo_dez.txt','r')\n        riga = lcf.readlines()\n        lcf.close()\n        wave,flux= [],[]\n        for line in riga[:len(riga)-5]:\n            p = line.split()\n            wave.append(float(p[0]))\n            flux.append(float(p[1]))\n    \n        wavev = array(wave)\n        fluxv = array(flux)\n        plot(wavev,flux,'k-')\n        ylabel('Flux', size=12)\n        print '#######################################'\n        print '\\033[4mDO THAT IS TOO RISKY\\033[0m (your uncertainties could be bigger than the result)! I have created for you a \\033[1mbbody_sn_dez_fit.fits\\033[0m file with the blackbody fit of your redshifted (but not dereddened) spectrum. I would suggest to try another iteration with this one! However, if you like to gamble we can continue using the spectrum on the bottom plot (NB: You have to close the window to continue).'\n        print '#######################################'\n        show()\n        answer = raw_input('Do you want to continue ? ([yes],no) ')\n        if not answer:\n            answer = 'yes'\n        if answer == 'no' or answer =='n':\n            sys.exit(\"Bye Bye\")\n    \n        elif answer == 'yes':\n            print '#######################################'\n            print 'OK, but have in mind that the values could be unreasonable. Thus I would suggest you to also use the blackbody and compare the K-correction values between the two methods.'\n            print '#######################################'   \n            print '\\033[31m\\033[7m***BBODY version activated***\\033[0m'\n    \n            ##################################\n            ### Evaluating the magnitudes\n            ##################################\n            iraf.wspec(\"sn.fits\",\"sn.txt\", header='no')\n            lcf = open('sn.txt','r')\n            riga = lcf.readlines()\n            lcf.close()\n            wave,flux= [],[]\n            for line in riga:\n                p = line.split()\n                if float(line.split()[0]) >= fil_obs_min and float(line.split()[0]) <= fil_obs_max: #to match the spectrum wavelegnths to those of the filter\n                    wave.append(float(p[0]))\n                    flux.append(float(p[1]))\n                \n            wavev = array(wave)\n            fluxv = array(flux)\n            wavesp_min= min(wavev)\n            wavesp_max= int(max(wavev)) #needed to avoid problems with interp1d\n\n            conf = conv(wavev,fluxv,wavefilterv,transmissionv,wavesp_min,wavesp_max,fil_obs_min,fil_obs_max)\n    \n            flux_obs = max(integrate.cumtrapz(conf[0],conf[1])) # using trapezoidal rule to integrate\n            print 'Apparent magnitude in observed frame ('+filter1+') = ', -2.5*log10(flux_obs/zp_ef)\n\n            lcf = open('bsn_combo_dez.txt','r')\n            riga = lcf.readlines()\n            lcf.close()\n            rwave,rflux= [],[]\n            for line in riga:\n                p = line.split()\n                if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n                    rwave.append(float(p[0]))\n                    rflux.append(float(p[1]))\n                \n            wave_dezv = array(rwave)\n            flux_dezv = array(rflux)\n            wavesp_dez_min= min(wave_dezv)\n            wavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n    \n            # interpolating the two responses in the rest wavelength to match the length and sampling coverage\n            conf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n\n            flux_rest = max(integrate.cumtrapz(conf[0],conf[1]))\n            flux_rest_err = flux_rest * (1+(waveout-50)*0.0001)\n            print 'Apparent magnitude in rest-frame ('+filter2+') = ', -2.5*log10(flux_rest/zp_ef_rest)\n\n            ############ Errors #########################################################################\n            lcf = open('bsn_combo_dez_err1.txt','r')\n            riga = lcf.readlines()\n            lcf.close()\n            rwave,rflux= [],[]\n            for line in riga:\n                p = line.split()\n                if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n                    rwave.append(float(p[0]))\n                    rflux.append(float(p[1]))\n                \n            wave_dezv = array(rwave)\n            flux_dezv = array(rflux)\n            wavesp_dez_min= min(wave_dezv)\n            wavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n\n            conf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n\n            flux_rest_err1 = max(integrate.cumtrapz(conf[0],conf[1]))\n\n            lcf = open('bsn_combo_dez_err2.txt','r')\n            riga = lcf.readlines()\n            lcf.close()\n            rwave,rflux= [],[]\n            for line in riga:\n                p = line.split()\n                if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n                    rwave.append(float(p[0]))\n                    rflux.append(float(p[1]))\n                \n            wave_dezv = array(rwave)\n            flux_dezv = array(rflux)\n            wavesp_dez_min= min(wave_dezv)\n            wavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n\n            conf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n\n            flux_rest_err2 = max(integrate.cumtrapz(conf[0],conf[1]))\n            #############################################################################################    \n            ##################################\n            ### Recap of what parameters have been used\n            ##################################\n    \n            print ''\n            print \"\\033[32m\"+'Observed passband = ',filter1\n            print \"\\033[32m\"+'Output filter (rest-frame) = ',filter2\n            print \"\\033[32m\"+'SN redshift = ',redshift,'+/-',_redshifterr\n            print '\\033[32mBlackbody temperature = %.0f +\\- %.0f K' % (T,np.sqrt(covar[0,0]))\n            print \"\\033[32m\"+'NO reddening has been used in this version\\033[0m'\n            print ''\n    \n            ##################################\n            ### K-correction evaluation\n            ##################################\n    \n            kcorrrest_bb_wor=-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest))+(2.5*log10(1+redshift))\n            kcorrrest_bb_wor_err1=-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest_err1/zp_ef_rest))+(2.5*log10(1+redserrspace1))\n            kcorrrest_bb_wor_err2=-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest_err2/zp_ef_rest))+(2.5*log10(1+redserrspace2))\n            kcorrerror_bb_wor=(abs(kcorrrest_bb_wor_err1 - kcorrrest_bb_wor) + abs(kcorrrest_bb_wor_err2 - kcorrrest_bb_wor))/2\n            kcorrerrfilt_obs = abs((-2.5*log10(flux_obs/zp_ef_err) - (-2.5*log10(flux_rest/zp_ef_rest)))-(-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest))))\n            kcorrerrfilt_rest = abs((-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest_err)))-(-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest))))\n            Kcorrerr_bb = abs((-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest)) +(2.5*log10(1+redshift)))-(-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest_err/zp_ef_rest)) +(2.5*log10(1+redshift))))\n            kcorrerr = sqrt((kcorrerror_bb_wor**2 + kcorrerrfilt_obs**2 + kcorrerrfilt_rest**2 + Kcorrerr_bb**2)/4)\n\n\n            print '#######################################' \n            print '\\033[4m'+'K-correction based on an hybrid (if you want to add this value to the observed mag, you have to flip the sign)\\033[0m, without reddening and from observed filter '+filter1+' on the SN observed spectrum to rest-frame filter '+filter2+' on the hybrid (SN+blackbody) = %0.4f' % (kcorrrest_bb_wor),'+/- %0.4f' % (kcorrerr)\n            print '#######################################' \n\n##################################\n### Evaluating the magnitudes\n##################################\n\n    else:\n        iraf.wspec(\"sn.fits\",\"sn.txt\", header='no')\n        lcf = open('sn.txt','r')\n        riga = lcf.readlines()\n        lcf.close()\n        wave,flux= [],[]\n        for line in riga:\n            p = line.split()\n            if float(line.split()[0]) >= fil_obs_min and float(line.split()[0]) <= fil_obs_max: #to match the spectrum wavelegnths to those of the filter\n                wave.append(float(p[0]))\n                flux.append(float(p[1]))\n            \n        wavev = array(wave)\n        fluxv = array(flux)\n        wavesp_min= min(wavev)\n        wavesp_max= int(max(wavev)) #needed to avoid problems with interp1d\n\n        conf = conv(wavev,fluxv,wavefilterv,transmissionv,wavesp_min,wavesp_max,fil_obs_min,fil_obs_max)\n\n        flux_obs = max(integrate.cumtrapz(conf[0],conf[1])) # using trapezoidal rule to integrate\n        print 'Apparent magnitude in observed frame ('+filter1+') = ', -2.5*log10(flux_obs/zp_ef)\n        phot_filtobs_sn = -2.5*log10(flux_obs/zp_ef)\n\n        iraf.wspec(\"sn_dez_dered.fits\",\"sn_dez_dered.txt\", header='no')\n        lcf = open('sn_dez_dered.txt','r')\n        riga = lcf.readlines()\n        lcf.close()\n        rwave,rflux= [],[]\n        for line in riga:\n            p = line.split()\n            if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n                rwave.append(float(p[0]))\n                rflux.append(float(p[1]))\n            \n        wave_dezv = array(rwave)\n        flux_dezv = array(rflux)\n        wavesp_dez_min= min(wave_dezv)\n        wavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n\n        conf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n\n        flux_rest = max(integrate.cumtrapz(conf[0],conf[1]))\n        print 'Apparent magnitude in rest-frame ('+filter2+') with reddening applied = ', -2.5*log10(flux_rest/zp_ef_rest)\n        phot_filtrest_sn_dez_dered=-2.5*log10(flux_rest/zp_ef_rest)\n\n        #######    Errors  ######################################################################################\n        iraf.wspec(\"sn_dez_dered_err1.fits\",\"sn_dez_dered_err1.txt\", header='no')\n        lcf = open('sn_dez_dered_err1.txt','r')\n        riga = lcf.readlines()\n        lcf.close()\n        rwave,rflux= [],[]\n        for line in riga:\n            p = line.split()\n            if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n                rwave.append(float(p[0]))\n                rflux.append(float(p[1]))\n            \n        wave_dezv = array(rwave)\n        flux_dezv = array(rflux)\n        wavesp_dez_min= min(wave_dezv)\n        wavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n\n        conf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n        flux_rest_err1 = max(integrate.cumtrapz(conf[0],conf[1]))\n\n        iraf.wspec(\"sn_dez_dered_err2.fits\",\"sn_dez_dered_err2.txt\", header='no')\n        lcf = open('sn_dez_dered_err2.txt','r')\n        riga = lcf.readlines()\n        lcf.close()\n        rwave,rflux= [],[]\n        for line in riga:\n            p = line.split()\n            if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n                rwave.append(float(p[0]))\n                rflux.append(float(p[1]))\n            \n        wave_dezv = array(rwave)\n        flux_dezv = array(rflux)\n        wavesp_dez_min= min(wave_dezv)\n        wavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n    \n        # interpolating the two responses in the rest wavelength to match the length and sampling coverage\n        conf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n        flux_rest_err2 = max(integrate.cumtrapz(conf[0],conf[1]))\n        ######################################################################################################\n        phot_filtrest_sn_dez_dered_err1=-2.5*log10(flux_rest_err1/zp_ef_rest)\n        phot_filtrest_sn_dez_dered_err2=-2.5*log10(flux_rest_err2/zp_ef_rest)\n        \n        iraf.wspec(\"sn_dez.fits\",\"sn_dez.txt\", header='no')\n        lcf = open('sn_dez.txt','r')\n        riga = lcf.readlines()\n        lcf.close()\n        rwave,rflux= [],[]\n        for line in riga:\n            p = line.split()\n            if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n                rwave.append(float(p[0]))\n                rflux.append(float(p[1]))\n            \n        wave_dezv = array(rwave)\n        flux_dezv = array(rflux)\n        wavesp_dez_min= min(wave_dezv)\n        wavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n    \n        # interpolating the two responses in the rest wavelength to match the length and sampling coverage\n        conf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n        flux_rest = max(integrate.cumtrapz(conf[0],conf[1]))\n\n        print 'Apparent magnitude in rest-frame ('+filter2+') = ', -2.5*log10(flux_rest/zp_ef_rest)        \n        phot_filtrest_sn_dez=-2.5*log10(flux_rest/zp_ef_rest)\n\n        ##################### Errors ######################################################################\n        iraf.wspec(\"sn_dez_err1.fits\",\"sn_dez_err1.txt\", header='no')\n        lcf = open('sn_dez_err1.txt','r')\n        riga = lcf.readlines()\n        lcf.close()\n        rwave,rflux= [],[]\n        for line in riga:\n            p = line.split()\n            if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n                rwave.append(float(p[0]))\n                rflux.append(float(p[1]))\n            \n        wave_dezv = array(rwave)\n        flux_dezv = array(rflux)\n        wavesp_dez_min= min(wave_dezv)\n        wavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n    \n        # interpolating the two responses in the rest wavelength to match the length and sampling coverage\n        conf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n        flux_rest_err1 = max(integrate.cumtrapz(conf[0],conf[1]))\n\n        iraf.wspec(\"sn_dez_err2.fits\",\"sn_dez_err2.txt\", header='no')\n        lcf = open('sn_dez_err2.txt','r')\n        riga = lcf.readlines()\n        lcf.close()\n        rwave,rflux= [],[]\n        for line in riga:\n            p = line.split()\n            if float(line.split()[0]) >= fil_rest_min and float(line.split()[0]) <= fil_rest_max:\n                rwave.append(float(p[0]))\n                rflux.append(float(p[1]))\n            \n        wave_dezv = array(rwave)\n        flux_dezv = array(rflux)\n        wavesp_dez_min= min(wave_dezv)\n        wavesp_dez_max= int(max(wave_dezv)) #needed to avoid problems with interp1d\n    \n        # interpolating the two responses in the rest wavelength to match the length and sampling coverage\n        conf = conv(wave_dezv,flux_dezv,wavefilter_restv,transmission_restv,wavesp_dez_min,wavesp_dez_max,fil_rest_min,fil_rest_max)\n        flux_rest_err2 = max(integrate.cumtrapz(conf[0],conf[1]))\n        ####################################################################################################\n        phot_filtrest_sn_dez_err1=-2.5*log10(flux_rest_err1/zp_ef_rest)\n        phot_filtrest_sn_dez_err2=-2.5*log10(flux_rest_err2/zp_ef_rest)\n        ##################################\n        ### Recap of what parameters have been used\n        ##################################\n    \n        print ''\n        print \"\\033[32m\"+'Observed passband = ',filter1\n        print \"\\033[32m\"+'Output filter (rest-frame) = ',filter2\n        print \"\\033[32m\"+'SN redshift = ',redshift,'+/-',_redshifterr\n        print \"\\033[32m\"+'E(B-V) galactic = ',ebvg\n        print \"\\033[32m\"+'E(B-V) host = ',ebvh\n        print '\\033[0m'  \n    \n        ##################################\n        ### Evaluation of K-correction and its errors\n        ##################################\n    \n        kcorrrest_wr=(float(phot_filtobs_sn)-float(phot_filtrest_sn_dez_dered))+(2.5*log10(1+redshift))\n        kcorrrest_wr_err1=(float(phot_filtobs_sn)-float(phot_filtrest_sn_dez_dered_err1))+(2.5*log10(1+redserrspace1))\n        kcorrrest_wr_err2=(float(phot_filtobs_sn)-float(phot_filtrest_sn_dez_dered_err2))+(2.5*log10(1+redserrspace2))\n        kcorrerror_wr=(abs(kcorrrest_wr_err1 - kcorrrest_wr) + abs(kcorrrest_wr_err2 - kcorrrest_wr))/2\n\n        kcorrrest_wor=(float(phot_filtobs_sn)-float(phot_filtrest_sn_dez))+(2.5*log10(1+redshift))\n        kcorrrest_wor_err1=(float(phot_filtobs_sn)-float(phot_filtrest_sn_dez_err1))+(2.5*log10(1+redserrspace1))\n        kcorrrest_wor_err2=(float(phot_filtobs_sn)-float(phot_filtrest_sn_dez_err2))+(2.5*log10(1+redserrspace2))\n        kcorrerror_wor=(abs(kcorrrest_wor_err1 - kcorrrest_wor) + abs(kcorrrest_wor_err2 - kcorrrest_wor))/2\n\n        kcorrerrfilt_obs = abs((-2.5*log10(flux_obs/zp_ef_err) - (-2.5*log10(flux_rest/zp_ef_rest)))-(-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest))))\n        kcorrerrfilt_rest = abs((-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest_err)))-(-2.5*log10(flux_obs/zp_ef) - (-2.5*log10(flux_rest/zp_ef_rest))))\n        \n        kcorrerr_wor = sqrt((kcorrerror_wor**2 + kcorrerrfilt_obs**2 + kcorrerrfilt_rest**2)/3)\n        kcorrerr_wr = sqrt((kcorrerror_wr**2 + kcorrerrfilt_obs**2 + kcorrerrfilt_rest**2)/3)\n        \n        print '#######################################' \n        print '\\033[4m'+'THE REAL K-correction (if you want to add this value to the observed mag, you have to flip the sign) \\033[0m is that without reddening from observed filter '+filter1+' to rest-frame filter '+filter2+' = \\033[0m %0.4f' % (kcorrrest_wor),'+/- %0.4f' % (kcorrerr_wor)\n        print 'K-correction with reddening from observed filter '+filter1+' to rest-frame filter '+filter2+' = %0.4f' % (kcorrrest_wr),'+/- %0.4f' % (kcorrerr_wr)\n        print '#######################################'\n\n##################################\n### Plotting section\n##################################\n\nif (waveobs_min-fil_obs_min) > 50 or (fil_obs_max-waveobs_max) > 50:\n     subplot(211)\n     listasp= ['bsn_combo.txt','bsn_combo_dez.txt']\n     i = 0\n     while i != len(listasp):\n         wave,flux =[],[]\n         lcf = open(listasp[i],'r')\n         riga = lcf.readlines()\n         lcf.close()\n         wave,flux= [],[]\n         for line in riga[:len(riga)-5]:\n             p = line.split()\n             wave.append(float(p[0]))\n             flux.append(float(p[1]))\n         wavev = array(wave)\n         fluxv = array(flux)\n         \n         # plotting\n         spess = ['1','1']   # thikness plot\n         tintatipo =['-','-']\n         col =['grey','brown']\n         plot(wavev,fluxv,color=col[i], ls=tintatipo[i],lw=float(spess[i]))\n         legend(['observed','redshifted'],ncol=1,numpoints=1)\n         i = i+1\n     \n     ylabel('Flux', size=14)\n     #plot bands and normalized spectra\n     subplot(212)\n     listasp= ['bsn_combo.txt','bsn_combo_dez.txt']\n     i = 0\n     while i != len(listasp):\n         wave,flux =[],[]\n         lcf = open(listasp[i],'r')\n         riga = lcf.readlines()\n         lcf.close()\n         wave,flux= [],[]\n         for line in riga[:len(riga)-5]:\n             p = line.split()\n             wave.append(float(p[0]))\n             flux.append(float(p[1]))\n         wavev = array(wave)\n         fluxv = array(flux)\n         normflux = fluxv/max(fluxv)\n         # plotting\n\n         spess = ['1','1']   # thikness plot\n         tintatipo =['-','-']\n         col =['grey','brown']\n         plot(wavev,normflux,color=col[i], ls=tintatipo[i],lw=float(spess[i]))\n         legend(['observed','redshifted'],ncol=1,numpoints=1)\n         i = i+1\n    \n     #  observed pass-band\n     \n     plot(wavefilter_initv,transmission_initv,'k:')\n     fill_between(wavefilter_initv,transmission_initv,0,where=None,alpha=0.5,color='g')\n     \n     #  observed pass-band after redshift\n     \n     plot(wavefilter_dmodv,transmission_initv,'k:')\n     fill_between(wavefilter_dmodv,transmission_initv,0,where=None,alpha=0.5,color='yellow')        \n     \n     #  restframe pass-band\n\n     plot(wavefilter_restinitv,transmission_restinitv,'k:')\n     fill_between(wavefilter_restinitv,transmission_restinitv,0,where=None,alpha=0.5,color='c')  \n\n     xlabel('Green ='+filter1+' obs filter, Yellow ='+filter1+' redshifted obs filter, Cyan ='+filter2+' rest filter', size=14)\n     ylabel('Normalized Flux', size=14)\n\nelif ((waverest_min-fil_rest_min) > 50) or ((fil_rest_max-waverest_max) > 50):\n    subplot(211)\n    listasp= ['sn.txt','bsn_combo_dez.txt']\n    i = 0\n    while i != len(listasp):\n        wave,flux =[],[]\n        lcf = open(listasp[i],'r')\n        riga = lcf.readlines()\n        lcf.close()\n        wave,flux= [],[]\n        for line in riga[:len(riga)-5]:\n            p = line.split()\n            wave.append(float(p[0]))\n            flux.append(float(p[1]))\n        wavev = array(wave)\n        fluxv = array(flux)\n        \n        # plotting\n        spess = ['1','1']   # thikness plot\n        tintatipo =['-','-'] #style\n        col =['k','orange'] #colours\n        plot(wavev,fluxv,color=col[i], ls=tintatipo[i],lw=float(spess[i])) #plot\n        legend(['observed','redshifted'],ncol=1,numpoints=1) #legend\n        i = i+1\n\n    ylabel('Flux', size=14)\n    #plot bands and normalized spectra\n    subplot(212)\n    listasp= ['sn.txt','bsn_combo_dez.txt']\n    i = 0\n    while i != len(listasp):\n        wave,flux =[],[]\n        lcf = open(listasp[i],'r')\n        riga = lcf.readlines()\n        lcf.close()\n        wave,flux= [],[]\n        for line in riga[:len(riga)-5]:\n            p = line.split()\n            wave.append(float(p[0]))\n            flux.append(float(p[1]))\n        wavev = array(wave)\n        fluxv = array(flux)\n        normflux = fluxv/max(fluxv)\n        # plotting\n        spess = ['1','1']   # thikness plot\n        tintatipo =['-','-'] #style\n        col =['k','orange'] #colours\n        plot(wavev,normflux,color=col[i], ls=tintatipo[i],lw=float(spess[i])) #plot\n        legend(['observed','redshifted'],ncol=1,numpoints=1) #legend\n        i = i+1\n\n    #  observed pass-band \n\n    plot(wavefilter_initv,transmission_initv,'k:')\n    fill_between(wavefilter_initv,transmission_initv,0,where=None,alpha=0.5,color='g')    \n\n    #  observed pass-band after redshift\n\n    plot(wavefilter_dmodv,transmission_initv,'k:')\n    fill_between(wavefilter_dmodv,transmission_initv,0,where=None,alpha=0.5,color='yellow')       \n    \n    #  restframe pass-band\n    \n    plot(wavefilter_restinitv,transmission_restinitv,'k:')\n    fill_between(wavefilter_restinitv,transmission_restinitv,0,where=None,alpha=0.5,color='c')  \n    xlabel('Green ='+filter1+' obs filter, Yellow ='+filter1+' redshifted obs filter, Cyan ='+filter2+' rest filter', size=14)\n    ylabel('Normalized Flux', size=14)\n\n    \nelse:\n    subplot(211)\n    listasp= ['sn.txt','sn_dez_dered.txt','sn_dez.txt']\n    i = 0\n    while i != len(listasp):\n        wave,flux =[],[]\n        lcf = open(listasp[i],'r')\n        riga = lcf.readlines()\n        lcf.close()\n        wave,flux= [],[]\n        for line in riga:\n            p = line.split()\n            wave.append(float(p[0]))\n            flux.append(float(p[1]))\n        wavev = array(wave)\n        fluxv = array(flux)\n    \n        spess = ['1','1','1']   # thikness plot\n        tintatipo =['k-','r-','b-']\n        plot(wavev,fluxv, tintatipo[i],lw=float(spess[i]))\n        legend(['observed','redshifted+dered','redshifted'],ncol=1,numpoints=1)\n        i = i+1\n\n    ylabel('Flux', size=14)\n    #plot bands and normalized spectra\n    subplot(212)\n    listasp= ['sn.txt','sn_dez_dered.txt','sn_dez.txt']\n    i = 0\n    while i != len(listasp):\n        wave,flux =[],[]\n        lcf = open(listasp[i],'r')\n        riga = lcf.readlines()\n        lcf.close()\n        wave,flux= [],[]\n        for line in riga:\n            p = line.split()\n            wave.append(float(p[0]))\n            flux.append(float(p[1]))\n        wavev = array(wave)\n        fluxv = array(flux)\n        normflux = fluxv/max(fluxv)\n        # plotting\n\n        spess = ['1','1','1']   # thikness plot\n        tintatipo =['k-','r-','b-']\n        plot(wavev,normflux, tintatipo[i],lw=float(spess[i]))\n        legend(['observed','redshifted+dered','redshifted'],ncol=1,numpoints=1)\n        i = i+1\n    \n    #  observed pass-band \n\n    plot(wavefilter_initv,transmission_initv,'k:')\n    fill_between(wavefilter_initv,transmission_initv,0,where=None,alpha=0.5,color='g')      \n    \n    #  observed pass-band after redshift\n\n    plot(wavefilter_dmodv,transmission_initv,'k:')\n    fill_between(wavefilter_dmodv,transmission_initv,0,where=None,alpha=0.5,color='yellow')      \n    \n    #  restframe pass-band\n\n    plot(wavefilter_restinitv,transmission_restinitv,'k:')\n    fill_between(wavefilter_restinitv,transmission_restinitv,0,where=None,alpha=0.5,color='c')      \n    xlabel('Green ='+filter1+' obs filter, Yellow ='+filter1+' redshifted obs filter, Cyan ='+filter2+' rest filter', size=14)\n    ylabel('Normalized Flux', size=14)\n\n\n#second cleaning process (necessary only for the first time)\nos.system('rm -rf sn.txt')\nos.system('rm -rf sn.fits')\nos.system('rm -rf sn_xbbody.txt')\nos.system('rm -rf sn_dez_xbbody.txt')\nos.system('rm -rf sn_dez_xbbody_err1.txt')\nos.system('rm -rf sn_dez_xbbody_err2.txt')\nos.system('rm -rf bbody_sn_dez_fit.dat')\nos.system('rm -rf bbody_sn_dez_fit_err1.dat')\nos.system('rm -rf bbody_sn_dez_fit_err2.dat')\nos.system('rm -rf bbody_sn_dez_fit.fits')\nos.system('rm -rf bbody_sn_dez_fit_err1.fits')\nos.system('rm -rf bbody_sn_dez_fit_err2.fits')\nos.system('rm -rf bbody_sn_fit.fits')\nos.system('rm -rf bbody_sn_fit.dat')\nos.system('rm -rf sn_dez.txt')\nos.system('rm -rf sn_dez_err1.txt')\nos.system('rm -rf sn_dez_err2.txt')\nos.system('rm -rf sn_dez.fits')\nos.system('rm -rf sn_dez_err1.fits')\nos.system('rm -rf sn_dez_err2.fits')\nos.system('rm -rf sn_dez_dered.fits')\nos.system('rm -rf sn_dez_dered_err1.fits')\nos.system('rm -rf sn_dez_dered_err2.fits')\nos.system('rm -rf sn_dez_dered.txt')\nos.system('rm -rf sn_dez_dered_err1.txt')\nos.system('rm -rf sn_dez_dered_err2.txt')\nos.system('rm -rf sn_galdered_dez.fits')\nos.system('rm -rf sn_galdered_dez_err1.fits')\nos.system('rm -rf sn_galdered_dez_err2.fits')\nos.system('rm -rf sn_galdered.fits')\nos.system('rm -rf bsn_combo_dez.fits')\nos.system('rm -rf bsn_combo_dez_err1.fits')\nos.system('rm -rf bsn_combo_dez_err2.fits')\nos.system('rm -rf bsn_combo_dez.txt')\nos.system('rm -rf bsn_combo_dez_err1.txt')\nos.system('rm -rf bsn_combo_dez_err2.txt')\nos.system('rm -rf bsn_combo.fits')\nos.system('rm -rf bsn_combo.txt')\n\nshow()\n", "meta": {"hexsha": "f66b166b1470eef9facf239a76e2c10a85415a2c", "size": 60688, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/s3/SNAKE.py", "max_stars_repo_name": "cinserra/S3", "max_stars_repo_head_hexsha": "eefc12265bd7824204dc5cbbd648e3ff8b291273", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-07-24T17:35:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-05T15:40:45.000Z", "max_issues_repo_path": "src/s3/SNAKE.py", "max_issues_repo_name": "cinserra/S3", "max_issues_repo_head_hexsha": "eefc12265bd7824204dc5cbbd648e3ff8b291273", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-24T10:46:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-24T10:46:26.000Z", "max_forks_repo_path": "src/s3/SNAKE.py", "max_forks_repo_name": "cinserra/S3", "max_forks_repo_head_hexsha": "eefc12265bd7824204dc5cbbd648e3ff8b291273", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-12T13:03:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-12T13:03:05.000Z", "avg_line_length": 46.4686064319, "max_line_length": 679, "alphanum_fraction": 0.5851239125, "include": true, "reason": "from numpy,from scipy", "num_tokens": 17222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.18210059452593524}}
{"text": "from .ransac import ransac\nfrom .utils import dist_matrix, orientation_diff\nimport numpy as np\nimport torch\n\n\ndef select_seeds(dist1: torch.Tensor, R1: float, scores1: torch.Tensor, fnn12: torch.Tensor, mnn: torch.Tensor):\n    \"\"\"\n        Select seed correspondences among the set of available matches.\n\n        dist1: Precomputed distance matrix between keypoints in image I_1\n        R1: Base radius of neighborhoods in image I_1\n        scores1: Confidence scores on the putative_matches. Usually holds Lowe's ratio scores.\n        fnn12: Matches between keypoints of I_1 and I_2.\n               The i-th entry of fnn12 is j if and only if keypoint k_i in image I_1 is matched to keypoint k_j in image I_2\n        mnn: A mask indicating which putative matches are also mutual nearest neighbors. See documentation on 'force_seed_mnn' in the DEFAULT_CONFIG.\n             If None, it disables the mutual nearest neighbor filtering on seed point selection.\n             Expected a bool tensor with shape (num_keypoints_in_source_image,)\n\n        Returns:\n            Indices of seed points.\n\n            im1seeds: Keypoint index of chosen seeds in image I_1\n            im2seeds: Keypoint index of chosen seeds in image I_2\n    \"\"\"\n    im1neighmap = dist1 < R1**2  # (n1, n1)\n    # find out who scores higher than whom\n    im1scorescomp = scores1.unsqueeze(1) > scores1.unsqueeze(0)  # (n1, n1)\n    # find out who scores higher than all of its neighbors: seed points\n    if mnn is not None:\n        im1bs = (~torch.any(im1neighmap & im1scorescomp & mnn.unsqueeze(0),\n                            dim=1)) & mnn & (scores1 < 0.8**2)  # (n1,)\n    else:\n        im1bs = (~torch.any(im1neighmap & im1scorescomp, dim=1)) & (scores1 <\n                                                                    0.8**2)\n\n    # collect all seeds in both images and the 1NN of the seeds of the other image\n    im1seeds = torch.where(im1bs)[0]  # (n1bs) index format\n    im2seeds = fnn12[im1bs]  # (n1bs) index format\n    return im1seeds, im2seeds\n\n\ndef extract_neighborhood_sets(\n        o1: torch.Tensor, o2: torch.Tensor, s1: torch.Tensor, s2: torch.Tensor,\n        dist1: torch.Tensor, im1seeds: torch.Tensor, im2seeds: torch.Tensor,\n        k1: torch.Tensor, k2: torch.Tensor, R1: float, R2: float,\n        fnn12: torch.Tensor, ORIENTATION_THR: float, SCALE_RATE_THR: float,\n        SEARCH_EXP: float, MIN_INLIERS: float):\n    \"\"\"\n        Assign keypoints to seed points. This checks both the distance and\n        the agreement of the local transformation if available.\n\n        o1: Orientations of keypoints in image I_1\n        o2: Orientations of keypoints in image I_2\n        s1: Scales of keypoints in image I_1\n        s2: Scales of keypoints in image I_2\n        dist1: Precomputed distance matrix between keypoints in image I_1\n        im1seeds: Keypoint index of chosen seeds in image I_1\n        im2seeds: Keypoint index of chosen seeds in image I_2\n        k1: Keypoint locations in image I_1\n        k2: Keypoint locations in image I_2\n        R1: Base radius of neighborhoods in image I_1\n        R2: Base radius of neighborhoods in image I_2\n        fnn12: Matches between keypoints of I_1 and I_2.\n               The i-th entry of fnn12 is j if and only if keypoint k_i in image I_1 is matched to keypoint k_j in image I_2\n        ORIENTATION_THR: Maximum deviation of orientation with respect to seed S_i to keep a keypoint in i-th neighborhood\n        SCALE_RATE_THR: Maximum deviation of scale with respect to seed S_i to keep a keypoint in i-th neighborhood\n        SEARCH_EXP: Expansion rate for both radii R1 and R2 to consider inclusion of neighboring keypoints\n        MIN_INLIERS: Minimum number of inliers to keep a seed point. This is used as an early filter here\n                     to remove already seeds with not enough samples to ever pass this threshold.\n\n        Returns:\n            Local neighborhoods assignments:\n\n            local_neighs_mask: Boolean matrix of size (num_seeds, num_keypoints).\n                               Entry (i, j) is True iff keypoint j was assigned to seed i.\n            rdims: Number of keypoints included in the neighborhood for each seed\n            im1seeds: Keypoint index of chosen seeds in image I_1\n            im2seeds: Keypoint index of chosen seeds in image I_2\n\n    \"\"\"\n    dst1 = dist1[im1seeds, :]\n    dst2 = dist_matrix(k2[fnn12[im1seeds]], k2[fnn12])\n\n    # initial candidates are matches which are close to the same seed in both images\n    local_neighs_mask = (dst1 < (SEARCH_EXP * R1) ** 2) \\\n                        & (dst2 < (SEARCH_EXP * R2) ** 2)\n\n    # If requested, also their orientation delta should be compatible with that of the corresponding seed\n    if ORIENTATION_THR is not None and ORIENTATION_THR < 180:\n        relo = orientation_diff(o1, o2[fnn12])\n        orientation_diffs = torch.abs(\n            orientation_diff(relo.unsqueeze(0), relo[im1seeds].unsqueeze(1)))\n        local_neighs_mask = local_neighs_mask & (orientation_diffs <\n                                                 ORIENTATION_THR)\n\n    # If requested, also their scale delta should be compatible with that of the corresponding seed\n    if SCALE_RATE_THR is not None and SCALE_RATE_THR < 10:\n        rels = s2[fnn12] / s1\n        scale_rates = rels[im1seeds].unsqueeze(1) / rels.unsqueeze(0)\n        local_neighs_mask = local_neighs_mask & (scale_rates < SCALE_RATE_THR) \\\n                            & (scale_rates > 1 / SCALE_RATE_THR)  # (ns, n1)\n\n    # count how many keypoints ended up in each neighborhood\n    numn1 = torch.sum(local_neighs_mask, dim=1)\n    # and only keep the ones that have enough points\n    valid_seeds = numn1 >= MIN_INLIERS\n\n    local_neighs_mask = local_neighs_mask[valid_seeds, :]\n\n    rdims = numn1[valid_seeds]\n\n    return local_neighs_mask, rdims, im1seeds[valid_seeds], im2seeds[\n        valid_seeds]\n\n\ndef extract_local_patterns(\n        fnn12: torch.Tensor,\n        fnn_to_seed_local_consistency_map_corr: torch.Tensor, k1: torch.Tensor,\n        k2: torch.Tensor, im1seeds: torch.Tensor, im2seeds: torch.Tensor,\n        scores: torch.Tensor):\n    \"\"\"\n        Prepare local neighborhoods around each seed for the parallel RANSACs. This involves two steps:\n            1) Collect all selected keypoints and refer them with respect to their seed point\n            2) Sort keypoints by score for the progressive sampling to pick the best samples first\n\n        fnn12: Matches between keypoints of I_1 and I_2.\n               The i-th entry of fnn12 is j if and only if keypoint k_i in image I_1 is matched to keypoint k_j in image I_2\n        fnn_to_seed_local_consistency_map_corr: Boolean matrix of size (num_seeds, num_keypoints).\n                                                Entry (i, j) is True iff keypoint j was assigned to seed i.\n        k1: Keypoint locations in image I_1\n        k2: Keypoint locations in image I_2\n        im1seeds: Keypoint index of chosen seeds in image I_1\n        im2seeds: Keypoint index of chosen seeds in image I_2\n        scores: Scores to rank correspondences by confidence.\n                Lower scores are assumed to be more confident, consistently with Lowe's ratio scores.\n                Note: scores should be between 0 and 1 for this function to work as expected.\n\n        Returns:\n            All information required for running the parallel RANSACs.\n            Data is formatted so that all inputs for different RANSACs are concatenated\n                along the same dimension to support different input sizes.\n\n            im1loc: Keypoint locations in image I_1 for each RANSAC sample.\n            im2loc: Keypoint locations in image I_2 for each RANSAC sample.\n            ransidx: Integer identifier of the RANSAC problem.\n                     This allows to distinguish inputs belonging to the same problem.\n            tokp1: Index of the original keypoint in image I_1 for each RANSAC sample.\n            tokp2: Index of the original keypoint in image I_2 for each RANSAC sample.\n    \"\"\"\n    # first get an indexing representation of the assignments:\n    # - ransidx holds the index of the seed for each assignment\n    # - tokp1 holds the index of the keypoint in image I_1 for each assignment \n    ransidx, tokp1 = torch.where(fnn_to_seed_local_consistency_map_corr)\n    # - and of course tokp2 holds the index of the corresponding keypoint in image I_2\n    tokp2 = fnn12[tokp1]\n\n    # Now take the locations in the image of each considered keypoint ... \n    im1abspattern = k1[tokp1]\n    im2abspattern = k2[tokp2]\n\n    # ... and subtract the location of its corresponding seed to get relative coordinates\n    im1loc = im1abspattern - k1[im1seeds[ransidx]]\n    im2loc = im2abspattern - k2[im2seeds[ransidx]]\n\n    # Finally we need to sort keypoints by scores in a way that assignments to the same seed are close together\n    # To achieve this we assume scores lie in (0, 1) and add the integer index of the corresponding seed\n    expanded_local_scores = scores[tokp1] + ransidx.type(scores.dtype)\n\n    sorting_perm = torch.argsort(expanded_local_scores)\n\n    im1loc = im1loc[sorting_perm]\n    im2loc = im2loc[sorting_perm]\n    tokp1 = tokp1[sorting_perm]\n    tokp2 = tokp2[sorting_perm]\n\n    return im1loc, im2loc, ransidx, tokp1, tokp2\n\n\ndef adalam_core(k1: torch.Tensor,\n                k2: torch.Tensor,\n                fnn12: torch.Tensor,\n                scores1: torch.Tensor,\n                config: dict,\n                mnn: torch.Tensor = None,\n                im1shape: tuple = None,\n                im2shape: tuple = None,\n                o1: torch.Tensor = None,\n                o2: torch.Tensor = None,\n                s1: torch.Tensor = None,\n                s2: torch.Tensor = None):\n    \"\"\"\n        Call the core functionality of AdaLAM, i.e. just outlier filtering. No sanity check is performed on the inputs.\n\n        Inputs:\n            k1: keypoint locations in the source image, in pixel coordinates.\n                Expected a float32 tensor with shape (num_keypoints_in_source_image, 2).\n            k2: keypoint locations in the destination image, in pixel coordinates.\n                Expected a float32 tensor with shape (num_keypoints_in_destination_image, 2).\n            fn12: Initial set of putative matches to be filtered.\n                  The current implementation assumes that these are unfiltered nearest neighbor matches,\n                  so it requires this to be a list of indices a_i such that the source keypoint i is associated to the destination keypoint a_i.\n                  For now to use AdaLAM on different inputs a workaround on the input format is required.\n                  Expected a long tensor with shape (num_keypoints_in_source_image,).\n            scores1: Confidence scores on the putative_matches. Usually holds Lowe's ratio scores.\n            mnn: A mask indicating which putative matches are also mutual nearest neighbors. See documentation on 'force_seed_mnn' in the DEFAULT_CONFIG.\n                 If None, it disables the mutual nearest neighbor filtering on seed point selection.\n                 Expected a bool tensor with shape (num_keypoints_in_source_image,)\n            im1shape: Shape of the source image. If None, it is inferred from keypoints max and min, at the cost of wasted runtime. So please provide it.\n                      Expected a tuple with (width, height) or (height, width) of source image\n            im2shape: Shape of the destination image. If None, it is inferred from keypoints max and min, at the cost of wasted runtime. So please provide it.\n                      Expected a tuple with (width, height) or (height, width) of destination image\n            o1/o2: keypoint orientations in degrees. They can be None if 'orientation_difference_threshold' in config is set to None.\n                   See documentation on 'orientation_difference_threshold' in the DEFAULT_CONFIG.\n                   Expected a float32 tensor with shape (num_keypoints_in_source/destination_image,)\n            s1/s2: keypoint scales. They can be None if 'scale_rate_threshold' in config is set to None.\n                   See documentation on 'scale_rate_threshold' in the DEFAULT_CONFIG.\n                   Expected a float32 tensor with shape (num_keypoints_in_source/destination_image,)\n\n        Returns:\n            Filtered putative matches.\n            A long tensor with shape (num_filtered_matches, 2) with indices of corresponding keypoints in k1 and k2.\n    \"\"\"\n    AREA_RATIO = config['area_ratio']\n    SEARCH_EXP = config['search_expansion']\n    RANSAC_ITERS = config['ransac_iters']\n    MIN_INLIERS = config['min_inliers']\n    MIN_CONF = config['min_confidence']\n    ORIENTATION_THR = config['orientation_difference_threshold']\n    SCALE_RATE_THR = config['scale_rate_threshold']\n    REFIT = config['refit']\n\n    if im1shape is None:\n        k1mins, _ = torch.min(k1, dim=0)\n        k1maxs, _ = torch.max(k1, dim=0)\n        im1shape = (k1maxs - k1mins).cpu().numpy()\n    if im2shape is None:\n        k2mins, _ = torch.min(k2, dim=0)\n        k2maxs, _ = torch.max(k2, dim=0)\n        im2shape = (k2maxs - k2mins).cpu().numpy()\n\n    # Compute seed selection radii to be invariant to image rescaling\n    R1 = np.sqrt(np.prod(im1shape[:2]) / AREA_RATIO / np.pi)\n    R2 = np.sqrt(np.prod(im2shape[:2]) / AREA_RATIO / np.pi)\n\n    # Precompute the inner distances of keypoints in image I_1\n    dist1 = dist_matrix(k1, k1)\n\n    # Select seeds\n    im1seeds, im2seeds = select_seeds(dist1, R1, scores1, fnn12, mnn)\n\n    # Find the neighboring and coherent keyopints consistent with each seed\n    local_neighs_mask, rdims, im1seeds, im2seeds = extract_neighborhood_sets(\n        o1, o2, s1, s2, dist1, im1seeds, im2seeds, k1, k2, R1, R2, fnn12,\n        ORIENTATION_THR, SCALE_RATE_THR, SEARCH_EXP, MIN_INLIERS)\n\n    if rdims.shape[0] == 0:\n        # No seed point survived. Just output ratio-test matches. This should happen very rarely.\n        absolute_im1idx = torch.where(scores1 < 0.8**2)[0]\n        absolute_im2idx = fnn12[absolute_im1idx]\n        return torch.stack([absolute_im1idx, absolute_im2idx], dim=1)\n\n    # Format neighborhoods for parallel RANSACs\n    im1loc, im2loc, ransidx, tokp1, tokp2 = extract_local_patterns(\n        fnn12, local_neighs_mask, k1, k2, im1seeds, im2seeds, scores1)\n    im1loc = im1loc / (R1 * SEARCH_EXP)\n    im2loc = im2loc / (R2 * SEARCH_EXP)\n\n    # Run the parallel confidence-based RANSACs to perform local affine verification\n    inlier_idx, _, \\\n    inl_confidence, inlier_counts = ransac(xsamples=im1loc,\n                                           ysamples=im2loc,\n                                           rdims=rdims, iters=RANSAC_ITERS,\n                                           refit=REFIT, config=config)\n\n    conf = inl_confidence[ransidx[inlier_idx]]\n    cnt = inlier_counts[ransidx[inlier_idx]].float()\n    passed_inliers_mask = (conf >= MIN_CONF) & (cnt * (1 - 1/conf) >= MIN_INLIERS)\n    accepted_inliers = inlier_idx[passed_inliers_mask]\n\n    absolute_im1idx = tokp1[accepted_inliers]\n    absolute_im2idx = tokp2[accepted_inliers]\n\n    final_matches = torch.stack([absolute_im1idx, absolute_im2idx], dim=1)\n    if final_matches.shape[0] > 1:\n        return torch.unique(final_matches, dim=0)\n    return final_matches\n", "meta": {"hexsha": "af13d1d6b87df780b25a1174beb372bc3eec71f7", "size": 15304, "ext": "py", "lang": "Python", "max_stars_repo_path": "adalam/core.py", "max_stars_repo_name": "happylin0427/AdaLAM", "max_stars_repo_head_hexsha": "5d7748fda7f76683e60c7053a0792a2ae9ef8800", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-12T15:56:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-12T15:56:33.000Z", "max_issues_repo_path": "adalam/core.py", "max_issues_repo_name": "happylin0427/AdaLAM", "max_issues_repo_head_hexsha": "5d7748fda7f76683e60c7053a0792a2ae9ef8800", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "adalam/core.py", "max_forks_repo_name": "happylin0427/AdaLAM", "max_forks_repo_head_hexsha": "5d7748fda7f76683e60c7053a0792a2ae9ef8800", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.1388888889, "max_line_length": 158, "alphanum_fraction": 0.6688447465, "include": true, "reason": "import numpy", "num_tokens": 3886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18205592054778091}}
{"text": "\"\"\"Simulator for bulk datasets\"\"\"\n\n\nimport matplotlib\nimport matplotlib.pyplot\nimport torch\nimport pyro\nimport anndata\nimport numpy as np\nimport pandas as pd\nfrom typing import Dict, Optional\nfrom ternadecov.stats_helpers import NegativeBinomialAltParam\nfrom ternadecov.dataset import SingleCellDataset\nfrom anndata import AnnData\n\n\ndef generate_anndata_from_sim(sim_res: Dict, sc_dataset: SingleCellDataset) -> AnnData:\n    \"\"\"Generate AnnData object from the simulation results \n\n    :param sim_res: Simulation results dictonary\n    :param sc_dataset: A single-cell dataset object (for the gene names)\n    \n    :return: AnnData object with simulated data\n    \"\"\"\n\n    var_tmp = pd.DataFrame({\"gene\": list(sc_dataset.sc_anndata.var.index)})\n    var_tmp = var_tmp.set_index(\"gene\")\n\n    return AnnData(\n        X=sim_res[\"x_ng\"].numpy(),\n        var=var_tmp,\n        obs=pd.DataFrame({\"time\": sim_res[\"t_m\"]}),\n    )\n\n\ndef plot_simulated_proportions(\n    sim_res,\n    dataset,\n    show_sample_proportions=True,\n    show_trajectories=True,\n    figsize=(20, 10),\n):\n    \"\"\"Plot simulated proportion results\n\n    :param sim_res: simulation results objects\n    :dataset: \n    :param show_sample_proportions: show the generated proportions plot\n    :param show_trajectories: show underlying trajectories plot\n    \n    :return: matplotlib axes\n    \"\"\"\n\n    true_trajectories = sim_res[\"trajectory_params\"][\"trajectories_cm\"]\n    trajectory_type = sim_res[\"trajectory_params\"][\"type\"]\n\n    # Order the time axis\n    o = torch.argsort(sim_res[\"t_m\"])\n\n    fig, ax = matplotlib.pyplot.subplots(\n        sum((show_sample_proportions, show_trajectories)), figsize=figsize\n    )\n\n    if show_trajectories:\n        # Get time range and initialize tensor\n        n_samples = 1000\n        t_min = torch.min(sim_res[\"t_m\"]).item()\n        t_max = torch.max(sim_res[\"t_m\"]).item()\n        t_m = np.linspace(t_min, t_max, n_samples)\n        trajectories_cm = torch.zeros(dataset.num_cell_types, n_samples)\n\n        if trajectory_type == \"linear\":\n            a = sim_res[\"trajectory_params\"][\"a\"]\n            b = sim_res[\"trajectory_params\"][\"b\"]\n            for i in range(dataset.num_cell_types):\n                trajectories_cm[i, :] = torch.Tensor(list(a[i] * x + b[i] for x in t_m))\n            #trajectories_cm = torch.nn.functional.softmax(trajectories_cm, dim=0)\n        elif trajectory_type == \"sigmoid\":\n            effect_size = sim_res[\"trajectory_params\"][\"effect_size\"]\n            shift = sim_res[\"trajectory_params\"][\"shift\"]\n            for i in range(dataset.num_cell_types):\n                trajectories_cm[i, :] = torch.Tensor(\n                    list(sigmoid(effect_size[i] * x + shift[i]) for x in t_m)\n                )\n            #trajectories_cm = torch.nn.functional.softmax(trajectories_cm, dim=0)\n        elif trajectory_type == \"periodic\":\n            a = sim_res[\"trajectory_params\"][\"a\"]\n            b = sim_res[\"trajectory_params\"][\"b\"]\n            c = sim_res[\"trajectory_params\"][\"c\"]\n            for i in range(dataset.num_cell_types):\n                trajectories_cm[i, :] = torch.Tensor(\n                    list(a[i] * torch.sin(b[i] * x + c[i]) for x in t_m)\n                )\n            #trajectories_cm = torch.nn.functional.softmax(trajectories_cm, dim=0)\n        else:\n            raise ValueError(f\"Unknown trajectory type {trajectory_type}\")\n\n        # Normalize trajectories_cm\n        trajectories_cm = torch.nn.functional.softmax(trajectories_cm, dim=0)\n\n        # Do plotting\n        ax[0].plot(\n            t_m, trajectories_cm.T,\n        )\n        ax[0].legend(dataset.cell_type_str_list)\n        ax[0].set_title(\"True simulated trajectories\")\n        ax[0].set_xlabel(\"Set time\")\n        ax[0].set_ylabel(\"Proportions\")\n\n    if show_sample_proportions:\n        for i in range(sim_res[\"cell_pop_cm\"].shape[0]):\n            ax[1].scatter(sim_res[\"t_m\"][o], sim_res[\"cell_pop_cm\"][i, o])\n        ax[1].set_title(\"Simulated proportions in samples\")\n        ax[1].set_xlabel(\"Set time\")\n        ax[1].set_ylabel(\"Proportions\")\n\n    return ax\n\n\ndef simulate_data(\n    w_hat_gc,\n    start_time=-5,\n    end_time=5,\n    num_samples=100,\n    lib_size_mean=1e6,\n    lib_size_std=2e5,\n    use_betas=False,\n    dirichlet_alpha=1000,\n    trajectory_type=\"sigmoid\",\n    trajectory_coef=None,\n    phi_mean=0.15,\n    phi_std=0.05,\n    beta_mean=1.0,\n    beta_std=0.1,\n    trajectory_sample_params={},\n    seed=None,\n):\n    \"\"\"Simulate bulk data with compositional changes\n\n    :param w_hat_gc: reference matrix\n    :param start_time: time start\n    :param end_time: time end\n    :param num_samples: number of samples to simulate\n    :param lib_size_mean: mean library size\n    :param lib_size_std: library size standard deviation\n    :param use_betas: use beta values from the reference model\n    :param dirichlet_alpha: global dirichlet alpha coefficient\n    :param trajectory_type: type of trajectory ('sigmoid','linear','periodic')\n    :param trajectory_coef: predefined trajectory coefficients, if not provided they are sampled\n    :param phi_mean: $\\phi_{mean}$ value\n    :param phi_std: $\\phi_{std}$ values\n    :param beta_mean: $\\beta_{mean}$ values\n    :param beta_std: $\\beta_{std}$ values\n    :param trajectory_sample_params: Dictionary of trajectory sample parameters\n    :param seed: seed for trajectory sampling (optional)\n\n    :return: dictionary of simulated values and underlying coefficients\n    \"\"\"\n\n    num_genes = w_hat_gc.shape[0]\n    num_cell_types = w_hat_gc.shape[1]\n\n    # Get equidistant time samples\n    t_m = torch.linspace(0.0, 1.0, num_samples) * (end_time - start_time) + start_time\n\n    if trajectory_type == \"sigmoid\":\n        proportions_sample = sample_sigmoid_proportions(\n            num_cell_types=num_cell_types,\n            num_samples=num_samples,\n            t_m=t_m,\n            dirichlet_alpha=dirichlet_alpha,\n            trajectory_coefficients=trajectory_coef,\n            trajectory_sample_params=trajectory_sample_params,\n            seed=seed,\n        )\n    elif trajectory_type == \"periodic\":\n        proportions_sample = sample_periodic_proportions(\n            num_cell_types=num_cell_types,\n            num_samples=num_samples,\n            t_m=t_m,\n            dirichlet_alpha=dirichlet_alpha,\n            trajectory_coefficients=trajectory_coef,\n            trajectory_sample_params=trajectory_sample_params,\n            seed=seed,\n        )\n    elif trajectory_type == \"linear\":\n        proportions_sample = sample_linear_proportions(\n            num_cell_types,\n            num_samples,\n            t_m,\n            dirichlet_alpha,\n            trajectory_coef,\n            trajectory_sample_params=trajectory_sample_params,\n            seed=seed,\n        )\n    else:\n        raise Exception(\"Unkown Trajectory Type\")\n\n    cell_pop_cm = proportions_sample[\"cell_pop_cm\"]\n    phi_g = (\n        torch.distributions.normal.Normal(\n            loc=torch.full((num_genes,), phi_mean),\n            scale=torch.full((num_genes,), phi_std),\n        )\n        .sample()\n        .abs()\n    )\n    beta_g = (\n        torch.distributions.normal.Normal(\n            loc=torch.full((num_genes,), beta_mean),\n            scale=torch.full((num_genes,), beta_std),\n        )\n        .sample()\n        .abs()\n    )\n\n    # Get celltype profiles from the model\n    if use_betas:\n        unnorm_w_hat_gc = w_hat_gc * beta_g[:, None]\n    else:\n        unnorm_w_hat_gc = w_hat_gc\n\n    # Normalize\n    w_gc = unnorm_w_hat_gc / unnorm_w_hat_gc.sum(0)\n\n    # Sample library sizes\n    lib_sizes_m = torch.normal(\n        mean=torch.full([num_samples], lib_size_mean),\n        std=torch.full([num_samples], lib_size_std),\n    )\n\n    mu_mg = lib_sizes_m[:, None] * torch.matmul(cell_pop_cm.T, w_gc.transpose(-1, -2))\n\n    # Sample a full matrix using phis from main model\n    x_ng = NegativeBinomialAltParam(mu=mu_mg, phi=phi_g).sample()\n\n    return {\n        \"cell_pop_cm\": cell_pop_cm,\n        \"t_m\": t_m,\n        \"x_ng\": x_ng,\n        \"trajectory_params\": proportions_sample[\"trajectory_params\"],\n    }\n\n\ndef sample_trajectories(type, num_cell_types, seed = None):\n    \"\"\"Generate a random trajectory\n\n    :param type: trajectory type (linear, sigmoid, periodical)\n    :param num_cell_types: number of cell types in the trajectory\n    \n    :return simulated trajectories:\n    \"\"\"\n    if type == \"linear\":\n        return sample_linear_trajectories(num_cell_types, seed=seed)\n    elif type == \"periodic\":\n        return sample_periodic_trajectories(num_cell_types, seed=seed)\n    elif type == \"sigmoid\":\n        return sample_sigmoid_trajectories(num_cell_types, seed=seed)\n\n\n######################################################\n# Linear\n######################################################\n\n\ndef sample_linear_trajectories(\n    num_cell_types: int,\n    seed: Optional[int] = None,\n    a_min: float = 0.0,\n    a_max: float = 10.0,\n    b_min: float = -10.0,\n    b_max: float = 10.0,\n) -> Dict:\n    \"\"\"\n    Generate a sample of linear trajectory coefficients\n    \n    :param num_cell_types: number of cell types in trajectories\n    :param seed: Random seed (for reproducibility)\n    :param a_min: minimum value for a coefficient\n    :param a_max: maximum values for a coefficient\n    :param b_min: minimum value for b coefficient\n    :param b_max: maximum value for b coefficient\n    \n    :return: Dictionary coefficient and their values\n    \"\"\"\n    if seed is not None:\n        torch.manual_seed(seed)\n\n    # y = ax+b\n    a = torch.rand(num_cell_types) * (a_max - a_min) + a_min\n    b = torch.rand(num_cell_types) * (b_max - b_min) + b_min\n\n    return {\"a\": a, \"b\": b}\n\n\ndef sample_linear_proportions(\n    num_cell_types,\n    num_samples,\n    t_m,\n    dirichlet_alpha=1e4,\n    trajectory_coef=None,\n    trajectory_sample_params=None,\n    seed=None,\n):\n    \"\"\"Generate a sample of linear proportions\n\n    :param num_cell_types: number of cell types to simulate\n    :param num_samples: number of samples\n    :param t_m: torch tensor of times\n    :param dirichlet_alpha: multiplier for normalized dirichlet coefficients\n\n    :return: Dictionary of coefficients\n    \"\"\"\n\n    if trajectory_coef is None:\n        trajectory_coef = sample_linear_trajectories(\n            num_cell_types, seed=seed, **trajectory_sample_params\n        )\n\n    a = trajectory_coef[\"a\"]\n    b = trajectory_coef[\"b\"]\n\n    trajectories_cm = torch.zeros(num_cell_types, num_samples)\n    for i in range(num_cell_types):\n        trajectories_cm[i, :] = torch.Tensor(list(a[i] * x + b[i] for x in t_m))\n\n    # Normalize trajectories_cm\n    trajectories_cm = torch.nn.functional.softmax(trajectories_cm, dim=0)\n\n    # For every sample, sample proportions from trajectory\n    cell_pop_cm = torch.zeros(num_cell_types, num_samples)\n    for j in range(num_samples):\n        cell_pop_cm[:, j] = torch.distributions.dirichlet.Dirichlet(\n            trajectories_cm[:, j] * dirichlet_alpha\n        ).sample()\n\n    return {\n        \"trajectory_params\": {\n            \"type\": \"linear\",\n            \"a\": a,\n            \"b\": b,\n            \"trajectories_cm\": trajectories_cm,\n        },\n        \"cell_pop_cm\": cell_pop_cm,\n    }\n\n\n######################################################\n# Periodic\n######################################################\n\n\ndef sample_periodic_trajectories(\n    num_cell_types: int,\n    seed: Optional[int] = None,\n    a_min: float = -3.0,\n    a_max: float = 3.0,\n    b_min: float = 0.25,\n    b_max: float = 1.0,\n    c_min: float = 0.0,\n    c_max: float = 5.0,\n) -> Dict:\n    \"\"\"Get a sample of coefficients for periodic trajectories\n    \n    :param num_cell_types: Number of celltypes\n    :param seed: Seed for reproducibility\n    :param a_min: min value for a\n    :param a_max: max value for a\n    :param b_min: min value for b\n    :param b_max: max value for b\n    :param c_min: min value for c\n    :param c_max: max value for c\n    \n    :return: Dictionary of coefficients\n    \"\"\"\n\n    if seed is not None:\n        torch.manual_seed(seed)\n\n    # y = a sin(b*x+c)\n    a = torch.rand(num_cell_types) * (a_max - a_min) + a_min\n    b = torch.rand(num_cell_types) * (b_max - b_min) + b_min\n    c = torch.rand(num_cell_types) * (c_max - c_min) + c_min\n\n    return {\"a\": a, \"b\": b, \"c\": c}\n\n\ndef sample_periodic_proportions(\n    num_cell_types,\n    num_samples,\n    t_m,\n    dirichlet_alpha=1e4,\n    trajectory_coefficients=None,\n    trajectory_sample_params=None,\n    seed=None,\n):\n    \"\"\"Get a sample of periodic cell proportions, optionally from a given trajectory\n\n    :param num_cell_types: number of cell types to simulate\n    :param num_samples: number of samples to simulate\n    :param t_m: time points to simulate results for\n    :param dirichlet_alpha: global diriechlet concentration\n    :param trajectory_coefficients: trajectory, if not provided a random trajectory is drawn\n    :param trajectory_sample_params: optional parameter dictionary for sampling trajectories\n    :param seed: optional seed for drawing coefficients\n    \n    \"\"\"\n    if trajectory_coefficients is None:\n        trajectory_coefficients = sample_periodic_trajectories(\n            num_cell_types=num_cell_types, seed=seed, **trajectory_sample_params\n        )\n\n    a = trajectory_coefficients[\"a\"]\n    b = trajectory_coefficients[\"b\"]\n    c = trajectory_coefficients[\"c\"]\n\n    trajectories_cm = torch.zeros(num_cell_types, num_samples)\n    for i in range(num_cell_types):\n        trajectories_cm[i, :] = torch.Tensor(\n            list(a[i] * torch.sin(b[i] * x + c[i]) for x in t_m)\n        )\n\n    trajectories_cm = torch.nn.functional.softmax(trajectories_cm, dim=0)\n\n    # For every sample, sample proportions from trajectory\n    cell_pop_cm = torch.zeros(num_cell_types, num_samples)\n    for j in range(num_samples):\n        cell_pop_cm[:, j] = torch.distributions.dirichlet.Dirichlet(\n            trajectories_cm[:, j] * dirichlet_alpha\n        ).sample()\n\n    return {\n        \"trajectory_params\": {\n            \"type\": \"periodic\",\n            \"a\": a,\n            \"b\": b,\n            \"c\": c,\n            \"trajectories_cm\": trajectories_cm,\n        },\n        \"cell_pop_cm\": cell_pop_cm,\n    }\n\n\n######################################################\n# Sigmoid\n######################################################\n\n\ndef sigmoid(x):\n    \"\"\"Return sigmoid function value\"\"\"\n    return 1.0 / (1.0 + np.exp(-x))\n\n\ndef sample_sigmoid_trajectories(\n    num_cell_types,\n    seed=None,\n    effect_size_min=-1,\n    effect_size_max=1,\n    shift_min=-2,\n    shift_max=2,\n):\n    \"\"\"Return sigmoid trajectory param dictionary\"\"\"\n\n    if seed is not None:\n        torch.manual_seed(seed)\n\n    effect_size = (\n        torch.rand(num_cell_types) * (effect_size_max - effect_size_min)\n        + effect_size_min\n    )\n    shift = torch.rand(num_cell_types) * (shift_max - shift_min) + shift_min\n\n    return {\"effect_size\": effect_size, \"shift\": shift}\n\n\ndef sample_sigmoid_proportions(\n    num_cell_types,\n    num_samples,\n    t_m,\n    dirichlet_alpha=1e4,\n    trajectory_coefficients=None,\n    trajectory_sample_params={},\n    seed=None,\n):\n    \"\"\"Generate a sample of sigmoid proportions\n\n    :param num_cell_types: number of cell types to simulate\n    :param num_samples: number of samples\n    :param t_m: torch tensor of times\n    :param dirichlet_alpha: multiplier for normalized dirichlet coefficients\n\n    :return: Dictionary of coefficients\n    \"\"\"\n    if trajectory_coefficients is None:\n        trajectory_coefficients = sample_sigmoid_trajectories(\n            num_cell_types=num_cell_types, seed=seed, **trajectory_sample_params,\n        )\n\n    effect_size = trajectory_coefficients[\"effect_size\"]\n    shift = trajectory_coefficients[\"shift\"]\n\n    # Generate trajectories_cm\n    trajectories_cm = torch.zeros(num_cell_types, num_samples)\n    for i in range(num_cell_types):\n        trajectories_cm[i, :] = torch.Tensor(\n            list(sigmoid(effect_size[i] * x + shift[i]) for x in t_m)\n        )\n\n    trajectories_cm = torch.nn.functional.softmax(trajectories_cm, dim=0)\n\n    # For every sample, sample proportions from trajectory\n    cell_pop_cm = torch.zeros(num_cell_types, num_samples)\n    for j in range(num_samples):\n        cell_pop_cm[:, j] = torch.distributions.dirichlet.Dirichlet(\n            trajectories_cm[:, j] * dirichlet_alpha\n        ).sample()\n\n    return {\n        \"trajectory_params\": {\n            \"type\": \"sigmoid\",\n            \"effect_size\": effect_size,\n            \"shift\": shift,\n            \"trajectories_cm\": trajectories_cm,\n        },\n        \"cell_pop_cm\": cell_pop_cm,\n    }\n\n\ndef calculate_sample_prediction_error(sim_res, pseudo_time_reg_deconv_sim) -> Dict:\n    \"\"\"Calculate the error at the level of individual sample proportion prediction\n    \n    :param sim_res: Simulation results to use as base truth\n    :param pseudo_time_reg_deconv_sim: The trained object to simulate\n    \n    :return: Dictionary of errors\n    \"\"\"\n\n    # Ground Truth\n    ground_truth_cell_pop_cm = sim_res[\"cell_pop_cm\"]\n    estimated_cell_pop_cm = (\n        pyro.param(\"cell_pop_posterior_loc_mc\").clone().detach().cpu().T\n    )\n\n    l1_error = (ground_truth_cell_pop_cm - estimated_cell_pop_cm).abs().sum([0, 1])\n    l1_error_norm = l1_error / estimated_cell_pop_cm.shape[-1]\n\n    return {\"l1_error\": l1_error, \"l1_error_norm\": l1_error_norm}\n\n\ndef calculate_trajectory_prediction_error(\n    sim_res, pseudo_time_reg_deconv_sim, n_intervals=1000\n):\n    \"\"\"Calculate the prediction error of a deconvolution on simulated results\n\n    :param sim_res: results of a simulation\n    :param pseudo_time_reg_deconv_sim: the deconvolution object to evaluate\n    :n_intervals: number of intervals over which to evaluate the results\n    \n    :return: Dictionary of results\n    \"\"\"\n\n    start_time = -5\n    end_time = 5\n    step = (end_time - start_time) / n_intervals\n\n    t_m = torch.arange(start_time, end_time, step)\n    num_samples = t_m.shape[0]\n\n    # Get the ground truth\n    if sim_res[\"trajectory_params\"][\"type\"] == \"sigmoid\":\n        shift = sim_res[\"trajectory_params\"][\"shift\"]\n        effect_size = sim_res[\"trajectory_params\"][\"effect_size\"]\n        num_cell_types = sim_res[\"trajectory_params\"][\"effect_size\"].shape[0]\n\n        cell_pop_cm = torch.zeros(num_cell_types, num_samples)\n        for i in range(num_cell_types):\n            cell_pop_cm[i, :] = torch.Tensor(\n                list(sigmoid(effect_size[i] * x + shift[i]) for x in t_m)\n            )\n        ground_truth_proportions_cm = torch.nn.functional.softmax(cell_pop_cm, dim=0)\n    elif sim_res[\"trajectory_params\"][\"type\"] == \"linear\":\n        a = sim_res[\"trajectory_params\"][\"a\"]\n        b = sim_res[\"trajectory_params\"][\"b\"]\n        num_cell_types = sim_res[\"trajectory_params\"][\"trajectories_cm\"].shape[0]\n\n        cell_pop_cm = torch.zeros(num_cell_types, num_samples)\n        for i in range(num_cell_types):\n            cell_pop_cm[i, :] = torch.Tensor(list(a[i] * x + b[i] for x in t_m))\n        ground_truth_proportions_cm = torch.nn.functional.softmax(cell_pop_cm, dim=0)\n    elif sim_res[\"trajectory_params\"][\"type\"] == \"periodic\":\n        a = sim_res[\"trajectory_params\"][\"a\"]\n        b = sim_res[\"trajectory_params\"][\"b\"]\n        c = sim_res[\"trajectory_params\"][\"c\"]\n        num_cell_types = sim_res[\"trajectory_params\"][\"trajectories_cm\"].shape[0]\n\n        cell_pop_cm = torch.zeros(num_cell_types, num_samples)\n        for i in range(num_cell_types):\n            cell_pop_cm[i, :] = torch.Tensor(\n                list(a[i] * torch.sin(b[i] * x + c[i]) for x in t_m)\n            )\n        ground_truth_proportions_cm = torch.nn.functional.softmax(cell_pop_cm, dim=0)\n    else:\n        raise Exception(\n            f'Unknown trajectory type { sim_res[\"trajectory_params\"][\"type\"] }'\n        )\n\n    # Get the predictions\n    traj = pseudo_time_reg_deconv_sim.population_proportion_model.get_composition_trajectories(\n        dataset=pseudo_time_reg_deconv_sim.dataset, n_intervals=n_intervals\n    )\n    ret_vals = traj\n\n    predicted_composition_cm = ret_vals[\"norm_comp_tc\"].T\n\n    # Calculate L1 and L2 losses\n    L1_error = (\n        (ground_truth_proportions_cm - predicted_composition_cm).abs().sum([0, 1])\n    )\n    L1_error_norm = L1_error / n_intervals\n    L2_error = (\n        (ground_truth_proportions_cm - predicted_composition_cm)\n        .pow(2)\n        .sum([0, 1])\n        .sqrt()\n    )\n    L2_error_norm = L2_error / n_intervals\n\n    # Calculate L1 and L2 losses on the trajectory shapes\n\n    # Normalize by cell type summing to 1\n    ground_truth_proportions_norm_cm = (\n        ground_truth_proportions_cm / ground_truth_proportions_cm.sum(-2)\n    )\n    predicted_composition_norm_cm = (\n        predicted_composition_cm / predicted_composition_cm.sum(-2)\n    )\n\n    shape_L1_error = (\n        (ground_truth_proportions_norm_cm - predicted_composition_norm_cm)\n        .abs()\n        .sum([0, 1])\n    )\n\n    return {\n        \"L1_error\": L1_error,\n        \"L1_error_norm\": L1_error_norm,\n        \"L2_error\": L2_error,\n        \"L2_error_norm\": L2_error_norm,\n        \"shape_L1_error\": shape_L1_error,\n    }\n", "meta": {"hexsha": "3b996ff13f99ad73c4f738cd656aee9ff362cc03", "size": 21041, "ext": "py", "lang": "Python", "max_stars_repo_path": "ternadecov/simulator.py", "max_stars_repo_name": "broadinstitute/temporal-rna-seq-deconvolution", "max_stars_repo_head_hexsha": "f9d1282753b79be86db7d60d8b1eb60da10b0d78", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ternadecov/simulator.py", "max_issues_repo_name": "broadinstitute/temporal-rna-seq-deconvolution", "max_issues_repo_head_hexsha": "f9d1282753b79be86db7d60d8b1eb60da10b0d78", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2022-03-02T01:05:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T15:51:02.000Z", "max_forks_repo_path": "ternadecov/simulator.py", "max_forks_repo_name": "broadinstitute/temporal-rna-seq-deconvolution", "max_forks_repo_head_hexsha": "f9d1282753b79be86db7d60d8b1eb60da10b0d78", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3707692308, "max_line_length": 96, "alphanum_fraction": 0.6458343235, "include": true, "reason": "import numpy", "num_tokens": 5016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3557748935136304, "lm_q1q2_score": 0.1820559205477809}}
{"text": "from pydca.contact_visualizer.contact_visualizer import DCAVisualizer\nfrom pydca.meanfield_dca.meanfield_dca import MeanFieldDCA\nfrom pydca.plmdca.plmdca import PlmDCA \nfrom pydca.fasta_reader import fasta_reader\nfrom pydca.sequence_backmapper import scoring_matrix\nfrom pydca.plmdca.plmdca import PlmDCA as PseudoLikelihoodMaxDCA\nfrom pydca.main import configure_logging\nfrom Bio import pairwise2\nimport matplotlib.pyplot as plt \nfrom scipy.optimize import minimize as scipy_minimize\nfrom  .convolution import Convolution\nfrom .inputreader import InputReader\nfrom .cmdargs import CmdArgs\nimport subprocess\nimport numpy as np\nimport logging \nimport os, errno\nimport glob \nfrom datetime import datetime\nimport pickle\nimport random\nfrom pathlib import Path\nfrom argparse import ArgumentParser\nimport sys \n\n\nlogger = logging.getLogger(__name__)\n\nclass CocoNetException(Exception):\n    \"\"\"Raise exceptions related to CocoNet computation.\n    \"\"\"\n\nclass CoCoNet:\n    \"\"\"Implements RNA contact prediction using direct coupling analysis enhanced by\n    a simple convolutional neural network.\n    \"\"\"\n\n    def __init__(self, data_dir, linear_dist=None, contact_dist=None):\n        \"\"\"Initializes CocoNet instance. \n\n        Parameters\n        ----------\n            self : CocoNet\n                An instance of CocoNet class.\n            dir_msa_files : str\n                Path to directory containing the MSA files. \n            dir_pdb_file : str\n                Path to the directory containing the PDB files.\n            dir_refseq_files : str\n                Path to the directory containing reference sequence files.\n            linear_dist : int \n                Distance between sites in reference sequence \n            contact_dist : float\n                Maximum distance between two residues in PDB file to be considered\n                contacts. \n        \"\"\"\n        self.__data_dir = os.path.abspath(data_dir) \n        self.__linear_dist = linear_dist if linear_dist is not None else 4\n        self.__contact_dist = contact_dist if contact_dist is not None else 10.0\n     \n        pdb_chains_list_file = os.path.join(self.__data_dir, 'CCNListOfPDBChains.txt')\n        msa_files_list_file = os.path.join(self.__data_dir, 'CCNListOfMSAFiles.txt')\n        pdb_files_list_file = os.path.join(self.__data_dir, 'CCNListOfPDBFiles.txt')\n        input_reader = InputReader()\n        self.__msa_file_names_list = input_reader.read_from_one_column_text_file(msa_files_list_file)\n        self.__pdb_chains_list = input_reader.read_from_one_column_text_file(pdb_chains_list_file)\n        self.__pdb_file_names_list = input_reader.read_from_one_column_text_file(pdb_files_list_file)\n        self.__msa_files_dir = os.path.join(self.__data_dir, 'MSA')\n        self.__refseqs_dir = os.path.join(self.__data_dir, 'sequences')\n        self.__pdb_files_dir = os.path.join(self.__data_dir, 'PDBFiles')\n        self.__secstruct_files_dir = os.path.join(self.__data_dir, 'secstruct')\n        self.__msa_files_list  = [\n            os.path.abspath(os.path.join(self.__msa_files_dir, msa_file + '.faclean')) for msa_file in self.__msa_file_names_list\n        ]\n\n        self.__refseqs = self.get_refseqs()\n        self.__refseqs_len = self.get_refseqs_len()\n\n        logmsg  = \"\"\"\n            Data directory          : {},\n            PDB chains list file    : {},\n            MSA files list file     : {},\n            PDB files list file     : {},\n        \"\"\".format(self.__data_dir, pdb_chains_list_file, \n            msa_files_list_file, pdb_files_list_file,\n        )\n        \n        logger.info(logmsg)\n        return None \n\n    \n    @property \n    def pdb_file_names_list(self):\n        return self.__pdb_file_names_list\n\n    @property \n    def msa_file_names_list(self):\n        return self.__msa_file_names_list\n\n    @property \n    def pdb_chains_list(self):\n        return self.__pdb_chains_list\n\n    \n    def map_pdb_id_to_family(self):\n        \"\"\"Mapps PDB ID to family name.\n\n        Parameters\n        ----------\n            self : CocoNet(self, data_dir, linear_dist=None, contact_dist=None)\n        \n        Returns\n        -------\n            pdb_id_to_fam_name : dict\n                pdb_id_to_fam_name[pdb_id]=fam_name\n        \"\"\"\n        pdb_id_to_fam_name = dict()\n        for pdb_id, fam_name in zip(self.__pdb_file_names_list, self.__msa_file_names_list):\n            pdb_id_to_fam_name[pdb_id] = fam_name\n        return pdb_id_to_fam_name\n\n    \n    @staticmethod \n    def _to_dict(files_list):\n        \"\"\"Puts a list of file paths into a dictionary \n\n        Parameters\n        ----------\n            files_list : list\n                A list of file paths\n        \n        Returns\n        -------\n            files_dict : dict \n                A dictionary whose keys are basenames of files and values file path.\n        \"\"\"\n        files_dict = dict()\n        for f in files_list:\n            basename, _ = os.path.splitext(os.path.basename(f))\n            files_dict[basename] = f \n        return files_dict\n\n\n    def get_refseq_files_list(self):\n        \"\"\"\n        \"\"\"\n        refseq_files_list = [\n            os.path.join(self.__refseqs_dir, pdb_file[:4] + '.fa') for pdb_file in self.__pdb_file_names_list\n        ]\n        return tuple(refseq_files_list)\n\n    \n    def get_pdb_files_list(self):\n        \"\"\"\n        \"\"\"\n        pdb_files_list = [\n            os.path.join(self.__pdb_files_dir, pdb_file + '.pdb') for pdb_file in self.__pdb_file_names_list\n        ]\n        return tuple(pdb_files_list)\n\n\n    def create_directories(self, dir_path):\n        \"\"\"Creates (nested) directory given path.\n\n        Parameters\n        ----------\n            self : CocoNet \n                An instance of CocoNet class.\n            dir_path : str \n                Directory path.\n\n        Returns\n        -------\n            None : None \n        \"\"\"\n        \n        try:\n            os.makedirs(dir_path)\n        except OSError as e:\n            if e.errno !=errno.EEXIST:\n                logger.error('Unable to create directory using path {}'.format(\n                    dir_path)\n                )\n                raise\n        return None \n\n    \n    def recompute_dca_data(self, msa_files_list=None, pickled_data=None):\n        \"\"\"Checks the last modification time of MSA files and pickled DCA data.\n        If any of the MSA files are modified recently compared to pickled DCA\n        data or pickled data does not exist, return values is True else False.\n\n        Parameters\n        ----------\n            self : CocoNet \n                An instance of CocoNet class.\n            msa_files_list : list \n                A list of RNA MSA files.\n            pickled_data : str \n                Pickled DCA data \n\n        Returns\n        -------\n            True or False : bool\n        \"\"\"\n    \n        if any([msa_files_list, pickled_data]) is None:\n            logger.error('\\n\\tYou need to supply all keyword arguments')\n            raise CocoNetException\n        if not os.path.exists(pickled_data): return True \n        mtime_msa_files = max([os.path.getmtime(f) for f in msa_files_list])\n        mtime_pickled_data = os.path.getmtime(pickled_data)\n        if mtime_msa_files > mtime_pickled_data:\n            return True \n        return False\n\n    \n    def compute_mfdca_DI_scores(self):\n        \"\"\"Computes the mean-field DCA score of all the RNA families in the directory\n        Parameters\n        ----------\n            self : CocoNet\n                An instance of CocoNet class\n\n        Returns \n        -------\n            all_dca_data : dict \n        \"\"\"\n        all_dca_data = dict()\n        for msa_file in self.__msa_files_list:\n            logger.info('\\n\\tMSA file: {}'.format(msa_file))\n            famname, _ext = os.path.splitext(os.path.basename(msa_file))\n            logger.info('\\n\\tFamily name: {}'.format(famname))\n            try:\n                mfdca = MeanFieldDCA(msa_file, 'rna')\n                dca_data = mfdca.compute_sorted_DI_APC()\n            except Exception:\n                raise \n            else:\n                all_dca_data[famname] = dca_data\n        # The DCA scores are in a list of tuples. Lets convert them to a dict\n        all_dca_data_dict = dict()\n        for rna_fam in all_dca_data:\n            all_dca_data_dict[rna_fam] = dict((pair, score) for pair, score in all_dca_data[rna_fam])\n        return all_dca_data_dict\n\n    \n    def compute_plmdca_FN_APC_scores(self, max_iterations=500000, num_threads=1, verbose=False):\n        \"\"\"\n        \"\"\"\n        all_dca_data = dict()\n        for msa_file in self.__msa_files_list:\n            logger.info('\\n\\tMSA file: {}'.format(msa_file))\n            famname, _ext = os.path.splitext(os.path.basename(msa_file))\n            logger.info('\\n\\tFamily name: {}'.format(famname))\n            try:\n                plmdca_inst = PseudoLikelihoodMaxDCA(msa_file, 'rna', max_iterations=max_iterations, verbose=verbose, num_threads=num_threads)\n                dca_data = plmdca_inst.compute_sorted_FN_APC()\n            except Exception:\n                raise \n            else:\n                all_dca_data[famname] = dca_data\n        # The DCA scores are in a list of tuples. Lets convert them to a dict\n        all_dca_data_dict = dict()\n        for rna_fam in all_dca_data:\n            all_dca_data_dict[rna_fam] = dict((pair, score) for pair, score in all_dca_data[rna_fam])\n        return all_dca_data_dict\n       \n    \n    def get_pdb_data(self):\n        \"\"\"Computes mapped PDB contacts for multiple RNA families. The computed \n        mapped PDB data is pickled and only recomputed if any of reference sequence \n        files, PDB files or PDB chain metadata file is updated.\n\n        Parameters\n        ----------\n            self : CocoNet \n                An instance of CocoNet class\n        \n        Returns\n        -------\n            mapped_pdb_data : dict \n                A dictionary whose keys are RNA familiy names and values dictionaries \n                that have site pair keys and PDB data values. \n        \"\"\"\n        refseq_files_list = self.get_refseq_files_list()\n        pdb_files_list = self.get_pdb_files_list()\n    \n        logger.info('\\n\\tObtaining mapped PDB data')\n        txtfreader = InputReader()\n        mapped_pdb_data = dict()\n        for chain_id, pdb_file, refseq_file, msa_file in zip(self.__pdb_chains_list, pdb_files_list, refseq_files_list, self.__msa_file_names_list):\n            curr_pdb_data, _missing, _refseq_len = txtfreader.get_mapped_pdb_data(pdb_chain_id=chain_id, \n                refseq_file=refseq_file, pdb_file=pdb_file, linear_dist=self.__linear_dist, \n                contact_dist=self.__contact_dist\n            )\n            # self.__msa_file_names_list  contains the list of MSA files, not the full path of the files\n            famname, _ext =  os.path.splitext(msa_file)\n            mapped_pdb_data[famname] = curr_pdb_data\n        return mapped_pdb_data\n\n\n    def get_refseqs(self):\n        \"\"\"Obtains reference sequences of several RNA famlies from fasta formatted file. \n\n        Parameters\n        ----------\n            self : CocoNet \n                An instance of CocoNet class\n        \n        Returns\n        -------\n            reference_sequenes_dict : dict()\n            reference_sequences_dict[FAMILY_NAME] = sequence \n        \"\"\"\n        \n        refseq_files_list = self.get_refseq_files_list()\n        logger.info('\\n\\tObtaining reference sequences from FASTA files')\n        reference_sequences_dict = dict()\n        for refseq_file, msa_file_basename in zip(refseq_files_list, self.__msa_file_names_list):\n            # if reference sequence file contains multiple sequences, take the first one.\n            reference_sequences_dict[msa_file_basename.strip()] = fasta_reader.get_alignment_from_fasta_file(refseq_file)[0].strip()\n        return reference_sequences_dict\n\n    \n    def get_refseqs_len(self):\n        \"\"\"Obtains length of reference sequence for each RNA family\n\n        Parameters \n        ----------\n            self : CocoNet \n                An instance of CocoNet class\n        \n        Returns \n        -------\n            refseqs_len_dict : dict()\n                refseqs_len_dict[FAMILY_NAME] = refseq_length\n        \"\"\"\n        refseqs_dict = self.__refseqs\n        logger.info('\\n\\tObtaining length of reference sequences for {} RNA families'.format(len(refseqs_dict)))\n\n        refseqs_len_dict = {\n            fam : len(refseqs_dict[fam]) for fam in refseqs_dict\n        }\n        return refseqs_len_dict   \n\n    \n    def objective_function(self, weight_matrix, dca_data_train, pdb_data_train):\n        \"\"\"Computes the total objective function (for the entire training data set)\n\n        Parameters\n        ----------\n            self : CocoNet \n                An instance of CocoNet class.\n            weight_matrix : np.array\n                A 1d numpy array of weights\n            dca_data_train : dict \n                DCA data for training.\n            pdb_data_train : dict \n                PDB data for training. \n\n        Returns\n        -------\n            total_cost : float \n                Total value of the objective/error function.\n        \"\"\"\n        fm_dim_size = int(np.sqrt(weight_matrix.size))\n        assert fm_dim_size * fm_dim_size == weight_matrix.size\n        conv_inst = Convolution(fm_dim_size)\n        total_cost = 0.0\n        logger.info('\\n\\tComputing objective function using filter matrix of size: {}'.format(weight_matrix.size))\n        for fam in dca_data_train:\n            fam_dca_scores = dca_data_train[fam]\n            fam_pdb_contacts = pdb_data_train[fam]\n            fam_refseq_len = self.__refseqs_len[fam]\n            fam_cost = conv_inst.objective_function(fam_pdb_contacts, fam_dca_scores, weight_matrix, fam_refseq_len)\n            total_cost += fam_cost\n        return total_cost\n\n    \n    def objective_function_WC_and_NONWC_pairs(self, weight_matrix, dca_data_train, pdb_data_train):\n        \"\"\"Computes value of cost function when contacts are categorized as WC and non-WC nucleotide \n        pairs.\n\n        Parameters\n        ----------\n            self :CocoNet  \n                CocoNet(self, data_dir, linear_dist=None, contact_dist=None) \n            weight_matrix : np.array()\n                1d numpy array of weights. Its size must be twice the size of \n                the filter matrix used so as to accommodate WC and non-WC weights\n                together. \n            dca_data_train : dict()\n                DCA data for training set families. \n            pdb_data_train : dict()\n                PDB data for training set families. \n\n        Returns\n        -------\n            total_cost : float \n                value of cost function for at a particular iteration (value of weight matrix).\n        \"\"\"\n\n        fm_dim_size = int(np.sqrt((weight_matrix.size/2)))\n        assert weight_matrix.size == 2*fm_dim_size * fm_dim_size\n        conv_inst = Convolution(fm_dim_size)\n        total_cost = 0.0\n        logger.info('\\n\\tComputing objective function for WC and non-WC residue pairs using filter matrix of size: {}'.format(weight_matrix.size))\n        for fam in dca_data_train:\n            fam_dca_scores = dca_data_train[fam]\n            fam_pdb_contacts = pdb_data_train[fam]\n            fam_refseq = self.__refseqs[fam]\n            fam_cost = conv_inst.objective_function_WC_and_NONWC_pairs(fam_pdb_contacts, fam_dca_scores, weight_matrix, fam_refseq)\n            total_cost += fam_cost\n        return total_cost\n\n    \n    def total_gradients(self, weight_matrix, dca_data_train, pdb_data_train):\n        \"\"\"Computes the total gradient of the error function. That is, for more than\n        one RNA family.\n\n        Parameters\n        ----------\n            self : CocoNet \n                An instance of CocoNet class.\n            weight_matrix : np.array\n                A 1d numpy array of weights\n            dca_data_train : dict \n                DCA data for training.\n            pdb_data_train : dict \n                PDB data for training. \n        \n        Returns\n        -------\n        total_gradients : np.array\n            A 1d numpy array of the total gradient\n\n        \"\"\"\n        logger.info('\\n\\tFilter Matrix\\n{}'.format(weight_matrix))\n        fm_dim_size = int(np.sqrt(weight_matrix.size)) \n        assert fm_dim_size * fm_dim_size == weight_matrix.size\n        conv_inst = Convolution(fm_dim_size)\n        total_gradients = 0.0 # will be promoted to numpy array when added to another array\n        for fam in dca_data_train:\n            fam_dca_scores = dca_data_train[fam]\n            fam_pdb_contacts = pdb_data_train[fam]\n            fam_refseq_len = self.__refseqs_len[fam]\n            fam_gradient = conv_inst.gradients(fam_pdb_contacts, fam_dca_scores, weight_matrix, fam_refseq_len)\n            total_gradients += fam_gradient\n        return total_gradients \n\n    \n    def total_gradients_WC_and_NONWC_pairs(self, weight_matrix, dca_data_train, pdb_data_train):\n        \"\"\"Computes the total gradient of the error function for WC and non-WC contact \n        pair classification for test RNA families. \n\n        Parameters\n        ----------\n            self : CocoNet \n                An instance of CocoNet class.\n            weight_matrix : np.array\n                A 1d numpy array of weights\n            dca_data_train : dict \n                DCA data for training.\n            pdb_data_train : dict \n                PDB data for training. \n        \n        Returns\n        -------\n        total_gradients : np.array\n            A 1d numpy array of the total gradient\n\n        \"\"\"\n    \n        logger.info('\\n\\tFilter Matrix\\n{}'.format(weight_matrix))\n        fm_dim_size = int(np.sqrt(weight_matrix.size/2)) \n        assert weight_matrix.size == 2*fm_dim_size * fm_dim_size \n        conv_inst = Convolution(fm_dim_size)\n        total_gradients = 0.0 # will be promoted to numpy array when added to another array\n        for fam in dca_data_train:\n            fam_dca_scores = dca_data_train[fam]\n            fam_pdb_contacts = pdb_data_train[fam]\n            fam_refseq = self.__refseqs[fam]\n            fam_gradient = conv_inst.gradients_WC_and_NONWC_pairs(fam_pdb_contacts, fam_dca_scores, weight_matrix, fam_refseq)\n            total_gradients += fam_gradient\n        return total_gradients \n\n    \n    def train(self, initial_weight_matrix, dca_data_train, pdb_data_train):\n        \"\"\"Performs gradient decent using scipy.optimize.minimize\n\n        Parameters\n        ----------\n            self : CocoNet \n                An instance of CocoNet class.\n            initial_weight_matrix : np.array\n                A 1d numpy array of initial weights.\n            dca_data_train : dict \n                DCA data for training.\n            pdb_data_train : dict \n                PDB data for training.\n\n        Returns\n        -------\n            result_lbfgs :  scipy.optimize.optimize.OptimizeResult\n                A instance of scipy.optimize.optimize.OptimizeResult class. It has\n                the following attributes:\n                result_lbfgs.fun  : float \n                    Value of minimized  objective function \n                result_lbfgs.jac : np.array\n                    A 1d numpy array of the hessian inverse\n                result_lbfgs.nit : int \n                    The number of minimization iterations. \n                result_lbfgs.success : bool\n                    Success status of minimization \n                result_lbfgs.x : np.array\n                    A 1d numpy array of optimized weights.\n                Note: there are more attributes that can be displayed using, for \n                example, print(result_lbfgs_b)\n        \"\"\"\n        result_lbfgs = scipy_minimize(self.objective_function, initial_weight_matrix, \n            method='L-BFGS-B', jac=self.total_gradients,\n            args=(dca_data_train, pdb_data_train)\n        )\n        if not result_lbfgs.success: raise CocoNetException('Iteration not converged') \n        return result_lbfgs\n\n    \n    def train_3x3(self, dca_data_train, pdb_data_train):\n        \"\"\"Computes a 3x3 trained filter matrix.\n\n        Parameters\n        ----------\n            self : CocoNet \n                An instance of CocoNet class.\n            dca_data_train : dict \n                Training DCA data.\n            pdb_data_train : dict \n                Training PDB data.\n        \n        Returns\n        -------\n            lbfgs_result.x : np.array\n                A 1d numpy array of trained filter matrix elements.\n        \"\"\"\n        weight_matrix = np.zeros(shape=(9, ), dtype=np.float64)\n\n        lbfgs_result = self.train(weight_matrix, dca_data_train, pdb_data_train)\n        return lbfgs_result.x\n\n    \n    def train_5x5(self, dca_data_train, pdb_data_train):\n        \"\"\"Computes a 5x5 trained filter matrix.\n\n        Parameters\n        ----------\n            self : CocoNet \n                An instance of CocoNet class.\n            dca_data_train : dict \n                Training DCA data.\n            pdb_data_train : dict\n                Training PDB data.\n        \n        Returns\n        -------\n            lbfgs_result.x : np.array\n                A 1d numpy array of trained filter matrix elements.\n        \"\"\"\n        weight_matrix = np.zeros(shape=(25, ), dtype=np.float64)\n        lbfgs_result = self.train(weight_matrix, dca_data_train, pdb_data_train)\n        return lbfgs_result.x\n\n    \n    def train_7x7(self, dca_data_train, pdb_data_train):\n        \"\"\"Computes a 7x7 trained filter matrix.\n\n        Parameters\n        ----------\n            self : CocoNet \n                An instance of CocoNet class.\n            dca_data_train : dict \n                Training DCA data.\n            pdb_data_train : dict\n                Training DCA data.\n    \n        Returns\n        -------\n            lbfgs_results.x : np.array\n                A 1d numpy array of trained filter matrix elements.\n        \"\"\"\n        weight_matrix = np.zeros(shape=(49, ), dtype=np.float64)\n        lbfgs_result = self.train(weight_matrix, dca_data_train, pdb_data_train)\n        return lbfgs_result.x\n\n    \n    def train_WC_and_NONWC(self, initial_weight_matrix, dca_data_train, pdb_data_train):\n        \"\"\"\n        \"\"\"\n        result_lbfgs = scipy_minimize(self.objective_function_WC_and_NONWC_pairs, \n            initial_weight_matrix, method='L-BFGS-B', \n            jac=self.total_gradients_WC_and_NONWC_pairs, \n            args=(dca_data_train, pdb_data_train)\n        )\n        if not result_lbfgs.success: raise CocoNetException('Iteration not converged')\n        return result_lbfgs\n\n    \n    def train_WC_and_NONWC_3x3(self, dca_data_train, pdb_data_train):\n        \"\"\"\n        \"\"\"\n        weight_matrix = np.zeros(shape=(18, ), dtype=np.float64)\n        lbfgs_result = self.train_WC_and_NONWC(weight_matrix, dca_data_train, pdb_data_train)\n        return lbfgs_result.x\n\n    \n    def train_WC_and_NONWC_5X5(self, dca_data_train, pdb_data_train):\n        \"\"\"\n        \"\"\"\n        weight_matrix = np.zeros(shape=(50, ), dtype=np.float64)\n        lbfgs_result =  self.train_WC_and_NONWC(weight_matrix, dca_data_train, pdb_data_train)\n        return lbfgs_result.x \n\n    \n    def train_WC_and_NONWC_7x7(self, dca_data_train, pdb_data_train):\n        \"\"\"\n        \"\"\"\n        weight_matrix = np.zeros(shape=(98, ), dtype=np.float64)\n        lbfgs_result = self.train_WC_and_NONWC(weight_matrix, dca_data_train, pdb_data_train)\n        return lbfgs_result.x \n\n    def cross_validation_single_matrix(self, matrix_size=None, wc_and_nwc=False, num_batches=5, output_dir=None, on_plm=False,\n            verbose=False, num_threads=None, max_iterations=None, num_trials=1):\n        \"\"\"Performs cross validation of CocoNet \n        \"\"\"\n        \n\n        pdb_data = self.get_pdb_data() \n        if on_plm:\n            dca_data=  self.compute_plmdca_FN_APC_scores(max_iterations=max_iterations, num_threads=num_threads, verbose=verbose)\n            if wc_and_nwc and output_dir is None:\n                output_dir = f'CoCoNet_plmDCA_CrossValidation_Output_2x{matrix_size}x{matrix_size}-' + datetime.now().strftime('%Y-%m-%d-%H_%M_%S')\n            if wc_and_nwc is False and output_dir is None:\n                output_dir = f'CoCoNet_plmDCA_CrossValidation_Output_{matrix_size}x{matrix_size}-' + datetime.now().strftime('%Y-%m-%d-%H_%M_%S')\n        \n        else: # uses mean-field DCA\n            dca_data = self.compute_mfdca_DI_scores() \n            if wc_and_nwc and output_dir is None:\n                output_dir = f'CoCoNet_mfDCA_CrossValidation_Output_2x{matrix_size}x{matrix_size}-' + datetime.now().strftime('%Y-%m-%d-%H_%M_%S')\n            if wc_and_nwc is False and output_dir is None:\n                output_dir = f'CoCoNet_mfDCA_CrossValidation_Output_{matrix_size}x{matrix_size}-' + datetime.now().strftime('%Y-%m-%d-%H_%M_%S')\n        \n\n        fams_in_DCA = list(dca_data.keys())\n        fams_in_PDB = list(pdb_data.keys())\n        for fam in fams_in_DCA: assert fam in fams_in_PDB\n        batch_len = len(fams_in_PDB)//num_batches\n\n        for i in range(num_trials):\n            # create output destination directories\n            \n            trial_dir = 'trial_{}'.format(i + 1) \n            trial_output_dir =  os.path.join(output_dir, trial_dir)\n            # shuffle the list of RNAs \n            random.shuffle(fams_in_PDB)\n            #divide families into batches\n            for j in range(num_batches):\n                trial_batch_output_dir = os.path.join(trial_output_dir, 'fold_{}'.format(j + 1))\n                self.create_directories(trial_batch_output_dir)\n                lower_bound = j * batch_len \n                upper_bound = lower_bound + batch_len\n                batch_j = fams_in_PDB[lower_bound:upper_bound] if j < (num_batches - 1) else fams_in_PDB[lower_bound:]\n                # take batch_j as a test set \n                testset_fams = batch_j \n                training_fams = [fam for fam in fams_in_PDB if fam not in testset_fams]\n                dca_data_train_j = { fam : dca_data[fam] for fam in training_fams }\n                pdb_data_train_j = {fam : pdb_data[fam] for fam in training_fams}\n                \n                metadata_file = os.path.join(trial_batch_output_dir, 'metadata_fold_{}.txt'.format(j + 1)) \n                \n                with open(metadata_file, 'w') as fh: \n                    fh.write('Testset RNA Families \\n')\n                    for counter, fam in enumerate(testset_fams, start=1): fh.write('{}\\t{}\\n'.format(counter, fam))\n                    fh.write('Training RNA Families\\n') \n                    for counter, fam in enumerate(training_fams, start=1): fh.write('{}\\t{}\\n'.format(counter, fam))\n                # perform training\n                base_header = 'Coconet cross validation result for {} filter matrix.\\nTotal number of training families: {}'\n                # 3x3 \n                if matrix_size == 3 and not wc_and_nwc:\n                    mat_3x3 = self.train_3x3(dca_data_train_j, pdb_data_train_j)\n                    outfile_3x3 = os.path.join(trial_batch_output_dir, 'params_3x3.txt')\n                    header_mat_3x3 = base_header.format('3x3', len(training_fams))\n                    np.savetxt(outfile_3x3, mat_3x3, header=header_mat_3x3)\n                if matrix_size == 3 and wc_and_nwc:\n                    mat_WCNWC_3x3 = self.train_WC_and_NONWC_3x3(dca_data_train_j, pdb_data_train_j)\n                    outfile_WCNWC_3x3 = os.path.join(trial_batch_output_dir, 'params_WCNWC_3x3.txt')\n                    header_mat_WCNWC_3x3 = base_header.format('WCNWC 3x3', len(training_fams))\n                    np.savetxt(outfile_WCNWC_3x3, mat_WCNWC_3x3, header=header_mat_WCNWC_3x3)\n                # 5x5 \n                if matrix_size == 5 and not wc_and_nwc:\n                    mat_5x5 = self.train_5x5(dca_data_train_j, pdb_data_train_j)\n                    outfile_5x5 = os.path.join(trial_batch_output_dir, 'params_5x5.txt')\n                    header_mat_5x5 = base_header.format('5x5', len(training_fams))\n                    np.savetxt(outfile_5x5, mat_5x5, header=header_mat_5x5)\n                if matrix_size == 5 and wc_and_nwc:\n                    mat_WCNWC_5x5 = self.train_WC_and_NONWC_5X5(dca_data_train_j, pdb_data_train_j)\n                    outfile_WCNWC_5x5 = os.path.join(trial_batch_output_dir, 'params_WCNWC_5x5.txt')\n                    header_mat_WCNWC_5x5 = base_header.format('WCNWC 5x5', len(training_fams))\n                    np.savetxt(outfile_WCNWC_5x5, mat_WCNWC_5x5, header=header_mat_WCNWC_5x5)\n                # 7x7\n                if matrix_size == 7 and not wc_and_nwc:\n                    mat_7x7 = self.train_7x7(dca_data_train_j, pdb_data_train_j)\n                    outfile_7x7 = os.path.join(trial_batch_output_dir, 'params_7x7.txt')\n                    header_mat_7x7 = base_header.format('7x7', len(training_fams))\n                    np.savetxt(outfile_7x7, mat_7x7, header=header_mat_7x7)\n                if matrix_size == 7 and wc_and_nwc:\n                    mat_WCNWC_7x7 = self.train_WC_and_NONWC_7x7(dca_data_train_j, pdb_data_train_j)\n                    outfile_WCNWC_7x7 = os.path.join(trial_batch_output_dir, 'params_WCNWC_7x7.txt')\n                    header_mat_WCNWC_7x7 = base_header.format('WCNWC 7x7', len(training_fams))\n                    np.savetxt(outfile_WCNWC_7x7, mat_WCNWC_7x7, header=header_mat_WCNWC_7x7)\n        return None \n\n\n    def cross_validation_all_matrices(self, num_batches=5, ouput_dir=None, on_plm=False, num_threads=1, \n            num_trials=1, max_iterations=None, verbose=False):\n        \"\"\"\n        \"\"\"\n        logger.info('\\n\\tTraining CoCoNet for all filter matrices, i.e., for 3x3, 2x3x3, 5x5, 2x5x5, 7x7 and 2x7x7')\n\n        pdb_data = self.get_pdb_data() \n        if on_plm:\n            dca_data=  self.compute_plmdca_FN_APC_scores(max_iterations=max_iterations, num_threads=num_threads, verbose=verbose)\n            output_dir = f'CoCoNet_plmDCA_CrossValidation_Output_All_Matrices-' + datetime.now().strftime('%Y-%m-%d-%H_%M_%S')\n        \n        else: # uses mean-field DCA\n            dca_data = self.compute_mfdca_DI_scores() \n            output_dir = f'CoCoNet_mfDCA_CrossValidation_Output_All_Matrices-' + datetime.now().strftime('%Y-%m-%d-%H_%M_%S')\n            \n        fams_in_DCA = list(dca_data.keys())\n        fams_in_PDB = list(pdb_data.keys())\n        for fam in fams_in_DCA: assert fam in fams_in_PDB\n        batch_len = len(fams_in_PDB)//num_batches\n\n        for i in range(num_trials):\n            # create output destination directories\n            \n            trial_dir = 'trial_{}'.format(i + 1) \n            trial_output_dir =  os.path.join(output_dir, trial_dir)\n            # shuffle the list of RNAs \n            random.shuffle(fams_in_PDB)\n            #divide families into batches\n            for j in range(num_batches):\n                trial_batch_output_dir = os.path.join(trial_output_dir, 'fold_{}'.format(j + 1))\n                self.create_directories(trial_batch_output_dir)\n                lower_bound = j * batch_len \n                upper_bound = lower_bound + batch_len\n                batch_j = fams_in_PDB[lower_bound:upper_bound] if j < (num_batches - 1) else fams_in_PDB[lower_bound:]\n                # take batch_j as a test set \n                testset_fams = batch_j \n                training_fams = [fam for fam in fams_in_PDB if fam not in testset_fams]\n                dca_data_train_j = { fam : dca_data[fam] for fam in training_fams }\n                pdb_data_train_j = {fam : pdb_data[fam] for fam in training_fams}\n                \n                metadata_file = os.path.join(trial_batch_output_dir, 'metadata_fold_{}.txt'.format(j + 1)) \n                \n                with open(metadata_file, 'w') as fh: \n                    fh.write('Testset RNA Families \\n')\n                    for counter, fam in enumerate(testset_fams, start=1): fh.write('{}\\t{}\\n'.format(counter, fam))\n                    fh.write('Training RNA Families\\n') \n                    for counter, fam in enumerate(training_fams, start=1): fh.write('{}\\t{}\\n'.format(counter, fam))\n                # perform training\n                base_header = 'Coconet cross validation result for {} filter matrix.\\nTotal number of training families: {}'\n                # 3x3\n                mat_3x3 = self.train_3x3(dca_data_train_j, pdb_data_train_j)\n                outfile_3x3 = os.path.join(trial_batch_output_dir, 'params_3x3.txt')\n                header_mat_3x3 = base_header.format('3x3', len(training_fams))\n                np.savetxt(outfile_3x3, mat_3x3, header=header_mat_3x3)\n                \n                # 2x3x3\n                mat_WCNWC_3x3 = self.train_WC_and_NONWC_3x3(dca_data_train_j, pdb_data_train_j)\n                outfile_WCNWC_3x3 = os.path.join(trial_batch_output_dir, 'params_WCNWC_3x3.txt')\n                header_mat_WCNWC_3x3 = base_header.format('WCNWC 3x3', len(training_fams))\n                np.savetxt(outfile_WCNWC_3x3, mat_WCNWC_3x3, header=header_mat_WCNWC_3x3)\n                # 5x5 \n                mat_5x5 = self.train_5x5(dca_data_train_j, pdb_data_train_j)\n                outfile_5x5 = os.path.join(trial_batch_output_dir, 'params_5x5.txt')\n                header_mat_5x5 = base_header.format('5x5', len(training_fams))\n                np.savetxt(outfile_5x5, mat_5x5, header=header_mat_5x5)\n                \n                # 2x5x5\n                mat_WCNWC_5x5 = self.train_WC_and_NONWC_5X5(dca_data_train_j, pdb_data_train_j)\n                outfile_WCNWC_5x5 = os.path.join(trial_batch_output_dir, 'params_WCNWC_5x5.txt')\n                header_mat_WCNWC_5x5 = base_header.format('WCNWC 5x5', len(training_fams))\n                np.savetxt(outfile_WCNWC_5x5, mat_WCNWC_5x5, header=header_mat_WCNWC_5x5)\n                # 7x7\n                mat_7x7 = self.train_7x7(dca_data_train_j, pdb_data_train_j)\n                outfile_7x7 = os.path.join(trial_batch_output_dir, 'params_7x7.txt')\n                header_mat_7x7 = base_header.format('7x7', len(training_fams))\n                np.savetxt(outfile_7x7, mat_7x7, header=header_mat_7x7)\n                \n                # 2x7x7\n                mat_WCNWC_7x7 = self.train_WC_and_NONWC_7x7(dca_data_train_j, pdb_data_train_j)\n                outfile_WCNWC_7x7 = os.path.join(trial_batch_output_dir, 'params_WCNWC_7x7.txt')\n                header_mat_WCNWC_7x7 = base_header.format('WCNWC 7x7', len(training_fams))\n                np.savetxt(outfile_WCNWC_7x7, mat_WCNWC_7x7, header=header_mat_WCNWC_7x7)\n                \n        return None \n\n        \n# end of class CoCoNet \n\ndef execute_from_command_line(matrix_size=None, wc_and_nwc=False, num_trials=1,\n        on_plm=False, verbose=False, output_dir=None, max_iterations=None, num_threads=None, for_all_matrices=False):\n    \"\"\"\n    \"\"\"\n    if matrix_size is None: matrix_size = 3 # use this default values to annotate do ouput \n    #directory names consistent with the default values in argparser.\n    \n    if verbose: configure_logging()\n    logger.info('\\n\\tTraining CoCoNet')\n    dataset_dir = Path(__file__).parent.parent / 'RNA_DATASET'\n    coconet_inst = CoCoNet(dataset_dir)\n    if for_all_matrices:\n        coconet_inst.cross_validation_all_matrices(on_plm = on_plm, max_iterations = max_iterations, num_threads = num_threads,\n            verbose = verbose, num_trials = num_trials\n        )\n    else:\n        coconet_inst.cross_validation_single_matrix(matrix_size, num_threads = num_threads, wc_and_nwc = wc_and_nwc, \n            on_plm = on_plm, verbose = verbose, max_iterations = max_iterations, num_trials = num_trials\n        )\n    \n    return None \n\n\ndef train_coconet():\n    \"\"\"\n    \"\"\"\n    parser = ArgumentParser() \n\n    # This argument is added to help run help message when no positional argument is supplied\n    parser.add_argument('run', help='Execute CoCoNet training')\n    parser.add_argument(CmdArgs.verbose_optional, help=CmdArgs.verbose_optional_help, action='store_true')\n    parser.add_argument(CmdArgs.matrix_size, help=CmdArgs.matrix_size_help,  type=int, choices=(3, 5, 7), default=3)\n    parser.add_argument(CmdArgs.wc_and_nwc_optional, help=CmdArgs.wc_and_nwc_optional_help, action='store_true')\n    parser.add_argument(CmdArgs.max_iterations_optional, help=CmdArgs.max_iterations_help, type=int, default=500000)\n    parser.add_argument(CmdArgs.num_threads_optional, help=CmdArgs.num_threads_help, type=int, default=1)\n    parser.add_argument(CmdArgs.on_plm_optional, help=CmdArgs.on_plm_optional_help, action='store_true')\n    parser.add_argument(CmdArgs.num_trials_optional, help=CmdArgs.num_trials_optional_help, type=int, default=1)\n    parser.add_argument(CmdArgs.for_all_matrices_optional, help=CmdArgs.for_all_matrices_optional_help, action = 'store_true')\n\n    args = parser.parse_args(args = None if sys.argv[1:] else ['--help']) \n    args_dict = vars(args)\n\n    execute_from_command_line(\n        args_dict.get(CmdArgs.matrix_size[2:]),\n        wc_and_nwc = args_dict.get(CmdArgs.wc_and_nwc_optional.strip()[2:]),\n        verbose = args_dict.get(CmdArgs.verbose_optional.strip()[2:]),\n        max_iterations = args_dict.get(CmdArgs.max_iterations_optional.strip()[2:]),\n        num_threads = args_dict.get(CmdArgs.num_threads_optional.strip()[2:]),\n        on_plm = args_dict.get(CmdArgs.on_plm_optional.strip()[2:]),\n        num_trials = args_dict.get(CmdArgs.num_trials_optional.strip()[2:]),\n        for_all_matrices = args_dict.get(CmdArgs.for_all_matrices_optional.strip()[2:]),\n    )\n\n\nif __name__ =='__main__':\n    train_coconet()\n\n", "meta": {"hexsha": "681474d6d790c420919a20b15536f02872855368", "size": 37582, "ext": "py", "lang": "Python", "max_stars_repo_path": "coconet/train.py", "max_stars_repo_name": "KIT-MBS/coconet", "max_stars_repo_head_hexsha": "5716c0818eabab30d5ef9fbf31f43705815f5645", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-08-20T07:56:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T20:47:04.000Z", "max_issues_repo_path": "coconet/train.py", "max_issues_repo_name": "KIT-MBS/coconet", "max_issues_repo_head_hexsha": "5716c0818eabab30d5ef9fbf31f43705815f5645", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-03T13:53:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-03T13:53:15.000Z", "max_forks_repo_path": "coconet/train.py", "max_forks_repo_name": "KIT-MBS/coconet", "max_forks_repo_head_hexsha": "5716c0818eabab30d5ef9fbf31f43705815f5645", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-10T17:49:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T01:45:26.000Z", "avg_line_length": 43.297235023, "max_line_length": 148, "alphanum_fraction": 0.6215209409, "include": true, "reason": "import numpy,from scipy", "num_tokens": 8939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117165898111866, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.18205590825850276}}
{"text": "\"\"\"\nRepresentation of the quantites, that can be added by the WSMs:\n\nretrievalAddAbsSpecies\nretrievalAddFreqShift\nretrievalAddFreqStretch\nretrievalAddConstantVMRAbsSpecies\nretrievalAddCatalogParameter\nretrievalAddCatalogParameters\nretrievalAddMagField\nretrievalAddPointingZa\nretrievalAddPolyfit\nretrievalAddScatSpecies\nretrievalAddSinefit\nretrievalAddSpecialSpecies\nretrievalAddWind\nretrievalAddSurfaceQuantity\nretrievalAddTemperature\n\"\"\"\n\nimport numpy as np\nfrom scipy import sparse\nimport xarray as xr\nimport pandas as pd\nfrom contextlib import contextmanager\n\nfrom .boilerplate import set_variable_by_xml\n\nfrom retrievals.arts import boilerplate\nfrom retrievals.arts.atmosphere import p2z_simple, z2p_simple\nfrom retrievals import level2\n\nimport warnings\n\n\n@contextmanager\ndef retrieval_def(ws):\n    \"\"\"Context manager for the RetrievalDef[Init/Close] context.\"\"\"\n    ws.covmat_block = []\n    ws.covmat_inv_block = []\n\n    ws.retrievalDefInit()\n    yield ws\n    ws.retrievalDefClose()\n\n\ndef _covmat_shape(g1, g2, g3):\n    n = len(g1) * len(g2) * len(g3)\n    return (n, n)\n\n\ndef _jqs_sizes(jqs):\n    \"\"\"Get the total size of the jacobian quantities.\"\"\"\n    jq_size = list()\n    for jq in jqs:\n        sz = 1\n        for g in jq.grids:\n            sz *= len(g)\n        jq_size.append(sz)\n    return jq_size\n\n\ndef _sizes_to_slices(jq_size):\n    \"\"\"Convert the sizes to start and end indices.\"\"\"\n    jq_start = [0] + list(np.cumsum(jq_size)[:-1])\n    jq_slices = [slice(start, start + size) for start, size in zip(jq_start, jq_size)]\n    return jq_slices\n\n\ndef _jqs_slices(jqs):\n    \"\"\"Get the start and end indices of jacobian quantities.\"\"\"\n    return _sizes_to_slices(_jqs_sizes(jqs))\n\n\nclass RetrievalQuantity:\n    \"\"\"A generic retrieval quantity.\"\"\"\n\n    def __init__(self, kind, covmat, **kwargs):\n        \"\"\"\n        :param kind: The kind is used to identify the corresponding WSMs, for example for a kind of `Sinefit` the WSM\n                     `retrievalAddSinefit` would be called upon apply with the keyword arguments.\n        :param covmat: The covariance matrix for the retrieval.\n        :param kwargs: Arguments to the `retrievalAdd...` WSM.\n        \"\"\"\n        self._kind = kind\n        self._covmat = covmat\n        self._args = kwargs\n\n        self._is_applied = False\n        self._sequence_id = None  # index inside jacobian quantities of workspace\n        self._jacobian_quantity = None\n        self._slice = None  # Holds the start and end indices for this quantity\n        self._ws = None  # Associated workspace\n\n        self._xa = None\n        self._x = None\n        self._avkm = None\n        self._eo = None\n        self._es = None\n\n    def apply(self, ws):\n        \"\"\"\n        Add this retrieval quantity to a Workspace and extract the indices from the jacobian quantities.\n        \"\"\"\n        if self._is_applied:\n            raise Exception('Same retrieval quantity cannot be added twice to the same workspace.')\n\n        self._ws = ws\n        self.apply_retrieval()\n        self.apply_covmat()\n\n        jqs = ws.jacobian_quantities.value\n        self._sequence_id = len(jqs) - 1\n        self._jacobian_quantity = jqs[self._sequence_id]\n        self._slice = _jqs_slices(jqs)[self._sequence_id]\n        self._is_applied = True\n\n    def apply_retrieval(self):\n        \"\"\"Calls the corresponding `retrievalAdd...()` WSM of the workspace.\"\"\"\n        ws = self.ws\n        boilerplate.clear_sparse(ws, ws.covmat_block)\n        boilerplate.clear_sparse(ws, ws.covmat_inv_block)\n        retrieval_add_wsm = getattr(ws, 'retrievalAdd' + self.kind)\n        retrieval_add_wsm(**self.args)\n\n    def apply_covmat(self):\n        \"\"\"Add the corresponding covmat block to the Workspace.\"\"\"\n        ws = self.ws\n        set_variable_by_xml(ws, ws.covmat_block, self.covmat)\n        ws.covmat_sxAddBlock(block=ws.covmat_block)\n\n    def extract_apriori(self, xa=None):\n        \"\"\"\n        Extract the a priori values. Call WSM `xaStandard()` before calling this function!\n        :param xa: The values in the `xa` vector just before the inversion. If None, copy from Workspace.\n        \"\"\"\n        ws = self._ws\n        if xa is None:\n            xa = ws.xa.value\n        self._xa = xa[self._slice]\n\n    def extract_result(self, x=None, avk=None, eo=None, es=None):\n        \"\"\"\n        Extract the result and the corresponding values form the Workspace.\n        If the arguments are `None`, the variables are copied from the associated Workspace.\n        \"\"\"\n        ws = self._ws\n        if x is None:\n            x = ws.x.value\n        if avk is None:\n            avk = ws.avk.value\n        if eo is None:\n            eo = ws.retrieval_eo.value\n        if es is None:\n            es = ws.retrieval_ss.value\n\n        self._x = x[self._slice]\n        self._avkm = avk[self._slice, self._slice]\n        self._eo = eo[self._slice]\n        self._es = es[self._slice]\n\n    def to_xarray(self):\n        \"\"\"\n        Export this retrieval quantity.\n\n        :rtype: xarray.Dataset\n        \"\"\"\n        if '-' in self.slug or ' ' in self.slug or ',' in self.slug:\n            prefix = self.slug.replace(' ','_')\n            prefix = prefix.replace(',','_')\n            prefix = prefix.replace('-','_')\n            prefix = prefix.replace('__','_')\n            prefix = prefix + '_'\n        else:\n            prefix = self.slug + '_'\n        shape = self.shape\n        grid_names = [prefix + gn for gn in self.grid_names]\n        grids = self.grids\n        flat_grid_name = prefix + 'grid' if self.dimensions > 1 else grid_names[0]\n\n        coords = {n: c for n, c in zip(grid_names, grids)}\n\n        ds = xr.Dataset(\n            data_vars={\n                prefix + 'x': (grid_names, np.reshape(self.x, shape, order='F')),\n                prefix + 'xa': (grid_names, np.reshape(self.xa, shape, order='F')),\n                prefix + 'mr': (grid_names, np.reshape(self.mr, shape, order='F')),\n                prefix + 'eo': (grid_names, np.reshape(self.eo, shape, order='F')),\n                prefix + 'es': (grid_names, np.reshape(self.es, shape, order='F')),\n                prefix + 'avkm': ((flat_grid_name, flat_grid_name + '_avk'), self.avkm),\n            },\n            coords=coords,\n            attrs={\n                'maintag': self._jacobian_quantity.maintag,\n                'subtag': self._jacobian_quantity.subtag,\n                'subsubtag': self._jacobian_quantity.subsubtag,\n                'analytical': self._jacobian_quantity.analytical,\n                'mode': self._jacobian_quantity.mode,\n                'perturbation': self._jacobian_quantity.perturbation,\n            }\n        )\n        return ds\n\n    @property\n    def kind(self):\n        return self._kind\n\n    @property\n    def covmat(self):\n        return self._covmat\n\n    @property\n    def args(self):\n        \"\"\"The arguments for the `retrievalAdd...` WSM.\"\"\"\n        return self._args\n\n    @property\n    def num_elem(self):\n        \"\"\"Number of elements, product of all grid lengths.\"\"\"\n        return self.covmat.shape[0]\n\n    @property\n    def grids(self):\n        \"\"\"Associated grids.\"\"\"\n        return self._jacobian_quantity.grids\n\n    @property\n    def grid_names(self):\n        \"\"\"Names of the grids.\"\"\"\n        return ['grid' + str(i + 1) for i in range(len(self.shape))]\n\n    @property\n    def shape(self):\n        \"\"\"Shape of grids.\"\"\"\n        return tuple(map(len, self.grids))\n\n    @property\n    def dimensions(self):\n        return len(list(filter(lambda x: x > 1, self.shape)))\n\n    @property\n    def ws(self):\n        \"\"\"Associated workspace. Set by :py:meth:`apply`.\"\"\"\n        return self._ws\n\n    def __str__(self):\n        return self.kind\n\n    @property\n    def slug(self):\n        \"\"\"A slug according to the kind of this retrieval quantity, useful for serialisation.\"\"\"\n        jq = self._jacobian_quantity\n        if jq.maintag == 'Absorption species':\n            return str.lower(jq.subtag)  # this is the species e.g. O3\n        elif jq.maintag == 'Wind':\n            return 'wind_' + str.lower(jq.subtag)  # component u, v, w\n        elif jq.maintag == 'Polynomial baseline fit':\n            return 'polyfit'  # Same for all coefficients\n        else:\n            return str.lower('_'.join((jq.maintag, jq.subtag, jq.subsubtag))).replace(' ', '-')\n\n    @property\n    def x(self):\n        \"\"\"The retrieved values. Available after :py:meth:`extract_results`.\"\"\"\n        return self._x\n\n    @property\n    def xa(self):\n        \"\"\"The a priori values. Available after :py:meth:`extract_apriori`.\"\"\"\n        return self._xa\n\n    @property\n    def avkm(self):\n        \"\"\"The averaging kernel matrix. Available after :py:meth:`extract_results`.\"\"\"\n        return self._avkm\n\n    @property\n    def mr(self):\n        \"\"\"The measurement response. Available after :py:meth:`extract_results`.\"\"\"\n        return level2.avkm_mr(self._avkm)\n\n    @property\n    def eo(self):\n        \"\"\"The retrieval error associated with the observational system. Available after :py:meth:`extract_results`.\"\"\"\n        return self._eo\n\n    @property\n    def es(self):\n        \"\"\"The smoothing error. Available after :py:meth:`extract_results`.\"\"\"\n        return self._es\n\n\nclass GriddedRetrievalQuantity(RetrievalQuantity):\n    \"\"\"Retrieval quantity that is retrieved on a spatial grid.\"\"\"\n\n    def __init__(self, kind, p_grid, lat_grid, lon_grid, covmat, **kwargs):\n        \"\"\"\n        :param kind: The kind is used to identify the corresponding WSMs, for example for a kind of `Sinefit` the WSM\n                     `retrievalAddSinefit` would be called upon apply with the keyword arguments.\n        :param p_grid: Pressure grid\n        :param lat_grid: Latitude grid\n        :param lon_grid: Longitude grid\n        :param covmat: The covariance matrix for the retrieval.\n        :param kwargs: Arguments to the `retrievalAdd...` WSM.\n        \"\"\"\n        kwargs['g1'] = p_grid\n        kwargs['g2'] = lat_grid\n        kwargs['g3'] = lon_grid\n        if not covmat.shape == _covmat_shape(p_grid, lat_grid, lon_grid):\n            expected = _covmat_shape(p_grid, lat_grid, lon_grid)\n            raise ValueError(\n                f'Covariance matrix must have shape according to retrieval grid elements: {expected[0]} x {expected[1]}')\n        super().__init__(kind, covmat, **kwargs)\n\n    def to_xarray(self):\n        prefix = self.slug + '_'\n        shape = self.shape\n        grid_names = [prefix + gn for gn in self.grid_names]\n\n        ds = super().to_xarray()\n\n        if self.dimensions == 1:\n            ds[prefix + 'z'] = (grid_names[0], self.z_grid)\n            ds[prefix + 'fwhm'] = (grid_names, np.reshape(self.fwhm, shape, order='F'))\n            ds[prefix + 'offset'] = (grid_names, np.reshape(self.offset, shape, order='F'))\n\n        return ds\n\n    @property\n    def shape(self):\n        return tuple(map(len, (self.args['g1'], self.args['g2'], self.args['g3'])))\n\n    @property\n    def num_elem(self):\n        shape = self.shape\n        return shape[0] * shape[1] * shape[2]\n\n    @property\n    def p_grid(self):\n        return self._args['g1']\n\n    @property\n    def z_grid(self):\n        if self.dimensions > 1:\n            warnings.warn('Z grid extraction not supported for multi dim retrieval grids. Using simple conversion.')\n            return p2z_simple(self.p_grid)\n\n        atmosphere_dim = self._ws.atmosphere_dim.value\n        lat_grid = self._ws.lat_grid.value\n        lon_grid = self._ws.lon_grid.value\n        if atmosphere_dim > 1:\n            if self.lat_grid[0] not in lat_grid or self.lon_grid[0] not in lon_grid:\n                warnings.warn('Z grid extraction not supported for arbitrary retrieval grids. Using simple conversion.')\n                return p2z_simple(self.p_grid)\n\n        z_field = self._ws.z_field.value\n\n        if atmosphere_dim == 1:\n            i_lat = i_lon = 0\n        elif atmosphere_dim == 2:\n            i_lon = 0\n            i_lat = np.searchsorted(lat_grid, self.lat_grid[0])\n        else:\n            i_lat = np.searchsorted(lat_grid, self.lat_grid[0])\n            i_lon = np.searchsorted(lon_grid, self.lon_grid[0])\n        z_grid1 = z_field[:, i_lat, i_lon]\n        p_grid1 = self._ws.p_grid.value\n        idx = np.argsort(p_grid1)\n        z_grid = np.interp(np.log(self.p_grid), np.log(p_grid1[idx]), z_grid1[idx])\n        return z_grid\n\n    @property\n    def lat_grid(self):\n        return self._args['g2']\n\n    @property\n    def lon_grid(self):\n        return self._args['g3']\n\n    @property\n    def grid_names(self):\n        return 'p', 'lat', 'lon'\n\n    @property\n    def fwhm(self):\n        if self.dimensions > 1:\n            raise NotImplementedError('FWHM not implemented for multi dim retrieval grids.')\n        return level2.avkm_fwhm(self.z_grid, self.avkm)\n\n    @property\n    def offset(self):\n        if self.dimensions > 1:\n            raise NotImplementedError('Offset not implemented for multi dim retrieval grids.')\n        return level2.avkm_offset(self.z_grid, self.avkm)\n\n\nclass AbsSpecies(GriddedRetrievalQuantity):\n    \"\"\"Absorption species.\"\"\"\n\n    # def __init__(self, species, p_grid, lat_grid, lon_grid, covmat,\n    #              method='analytical', unit='rel', for_species_tag=1, dx=0.001):\n    def __init__(self, species, p_grid, lat_grid, lon_grid, covmat,\n                 unit='rel', for_species_tag=1):\n        super().__init__('AbsSpecies',\n                         p_grid=p_grid,\n                         lat_grid=lat_grid,\n                         lon_grid=lon_grid,\n                         covmat=covmat,\n                         species=species,\n                         #method=method,\n                         unit=unit,\n                         for_species_tag=for_species_tag)#,\n                         #dx=dx)\n\n    @property\n    def species(self):\n        return self.args['species']\n\n    @property\n    def slug(self):\n        return self.species.lower()\n\n\nclass Wind(GriddedRetrievalQuantity):\n    \"\"\"Wind.\"\"\"\n\n    def __init__(self, component, p_grid, lat_grid, lon_grid, covmat, dfrequency=0.1):\n        super().__init__('Wind',\n                         p_grid=p_grid,\n                         lat_grid=lat_grid,\n                         lon_grid=lon_grid,\n                         covmat=covmat,\n                         component=component,\n                         dfrequency=dfrequency)\n\n    @property\n    def component(self):\n        return self.args['component']\n\n    @property\n    def slug(self):\n        return 'wind_' + self.component.lower()\n\n\nclass FreqShift(RetrievalQuantity):\n    \"\"\"Backend frequency shift.\"\"\"\n\n    def __init__(self, var, df=100e3):\n        covmat = np.array([var ** 2])\n        super().__init__('FreqShift', covmat, df=df)\n\n    def apply_covmat(self):\n        ws = self.ws\n        ws.covmat_block = sparse.bsr_matrix(self.covmat)\n        ws.covmat_sxAddBlock(block=ws.covmat_block)\n\n    @property\n    def num_elem(self):\n        return 1\n\n    @property\n    def slug(self):\n        return 'freq_shift'\n\n\nclass Polyfit(RetrievalQuantity):\n    \"\"\"Polynomial baseline fit.\"\"\"\n\n    def __init__(self, poly_order, covmats, pol_variation=True, los_variation=True, mblock_variation=True):\n        if len(covmats) != poly_order + 1:\n            raise ValueError('Must provide (poly_order + 1) covariance matrices.')\n        for covmat in covmats:\n            if covmat.ndim != 2:\n                raise ValueError('Covariance matrices must have ndim=2, but got {}.'.format(covmat.ndim))\n\n        self._covmats = covmats\n        super().__init__('Polyfit', None,\n                         poly_order=poly_order,\n                         no_pol_variation=0 if pol_variation else 1,\n                         no_los_variation=0 if los_variation else 1,\n                         no_mblock_variation=0 if mblock_variation else 1)\n\n    def apply(self, ws):\n        if self._is_applied:\n            raise Exception('Same retrieval quantity cannot be added twice to the same workspace.')\n\n        self._ws = ws\n        self.apply_retrieval()\n        self.apply_covmat()\n\n        n_jqs = self.poly_order + 1\n        jqs = ws.jacobian_quantities.value\n        self._sequence_id = slice(len(jqs) - n_jqs, len(jqs))\n        self._jacobian_quantity = jqs[self._sequence_id]\n        self._slice = _jqs_slices(jqs)[self._sequence_id]\n        self._is_applied = True\n\n    def apply_retrieval(self):\n        ws = self.ws\n        boilerplate.clear_sparse(ws, ws.covmat_block)\n        boilerplate.clear_sparse(ws, ws.covmat_inv_block)\n        ws.retrievalAddPolyfit(**self.args)\n\n    def apply_covmat(self):\n        for covmat in self._covmats:\n            self.ws.covmat_sxAddBlock(block=covmat)\n\n    def extract_apriori(self, xa=None):\n        \"\"\"\n        Extract the a priori values. Call WSM `xaStandard()` before calling this function!\n        :param xa: The values in the `xa` vector just before the inversion. If None, copy from Workspace.\n        \"\"\"\n        ws = self._ws\n        if xa is None:\n            xa = ws.xa.value\n        self._xa = [xa[s] for s in self._slice]  # Always 0, but we implement it anyways.\n\n    def extract_result(self, x=None, avk=None, eo=None, es=None):\n        \"\"\"Extract the result and the corresponding values form the Workspace.\"\"\"\n        ws = self._ws\n        if x is None:\n            x = ws.x.value\n        if avk is None:\n            avk = ws.avk.value\n        if eo is None:\n            eo = ws.retrieval_eo.value\n        if es is None:\n            es = ws.retrieval_ss.value\n\n        self._x = [x[s] for s in self._slice]\n        self._avkm = [avk[s, s] for s in self._slice]\n        self._eo = [eo[s] for s in self._slice]\n        self._es = [es[s] for s in self._slice]\n\n    def to_xarray(self):\n        prefix = self.slug + '_'\n        grid_names = ('poly_order', 'observation')\n        grids = self.grids\n        flat_grid_name = prefix + 'grid'\n\n        coords = {n: c for n, c in zip(grid_names, grids)}\n\n        ds = xr.Dataset(\n            data_vars={\n                prefix + 'x': (grid_names, np.stack(self.x)),\n                prefix + 'xa': (grid_names, np.stack(self.xa)),\n                prefix + 'mr': (grid_names, np.stack(self.mr)),\n                prefix + 'eo': (grid_names, np.stack(self.eo)),\n                prefix + 'es': (grid_names, np.stack(self.es)),\n                prefix + 'avkm': ((grid_names[0], flat_grid_name, flat_grid_name + '_avk'), np.stack(self.avkm)),\n            },\n            coords=coords,\n            attrs={\n                'maintag': self._jacobian_quantity[0].maintag,\n                'subtag': '',\n                'subsubtag': '',\n                'analytical': self._jacobian_quantity[0].analytical,\n                'mode': self._jacobian_quantity[0].mode,\n                'perturbation': self._jacobian_quantity[0].perturbation,\n            }\n        )\n        return ds\n\n    @property\n    def slug(self):\n        return 'poly_fit'\n\n    @property\n    def grids(self):\n        jq_grids = self._jacobian_quantity[0].grids\n        if len(jq_grids[0]) > 1 or len(jq_grids[1]) > 1 or len(jq_grids[2]) > 1:\n            raise NotImplementedError()\n        return [np.arange(self.poly_order + 1), np.array(jq_grids[-1], dtype=np.int)]\n\n    @property\n    def covmat(self):\n        return sparse.diags(self._covmats)\n\n    @property\n    def poly_order(self):\n        return self.args['poly_order']\n\n    @property\n    def mr(self):\n        return [level2.avkm_mr(a) for a in self._avkm]\n\nclass Sinefit(RetrievalQuantity):\n    \"\"\"Sinusoidal baseline fit.\"\"\"\n\n    def __init__(self, periods, covmats, pol_variation=True, los_variation=True, mblock_variation=True):\n        # if len(covmats) != poly_order + 1:\n        #     raise ValueError('Must provide (poly_order + 1) covariance matrices.')\n        # for covmat in covmats:\n        #     if covmat.ndim != 2:\n        #         raise ValueError('Covariance matrices must have ndim=2, but got {}.'.format(covmat.ndim))\n\n        self._covmats = covmats\n        super().__init__('Sinefit', None,\n                         periods=periods,\n                         no_pol_variation=0 if pol_variation else 1,\n                         no_los_variation=0 if los_variation else 1,\n                         no_mblock_variation=0 if mblock_variation else 1)\n\n    def apply(self, ws):\n        if self._is_applied:\n            raise Exception('Same retrieval quantity cannot be added twice to the same workspace.')\n\n        self._ws = ws\n        self.apply_retrieval()\n        self.apply_covmat()\n\n        n_jqs = self.poly_order + 1\n        jqs = ws.jacobian_quantities.value\n        self._sequence_id = slice(len(jqs) - n_jqs, len(jqs))\n        self._jacobian_quantity = jqs[self._sequence_id]\n        self._slice = _jqs_slices(jqs)[self._sequence_id]\n        self._is_applied = True\n\n    def apply_retrieval(self):\n        ws = self.ws\n        boilerplate.clear_sparse(ws, ws.covmat_block)\n        boilerplate.clear_sparse(ws, ws.covmat_inv_block)\n        ws.retrievalAddSinefit(**self.args)\n\n    def apply_covmat(self):\n        for covmat in self._covmats:\n            self.ws.covmat_sxAddBlock(block=covmat)\n\n    def extract_apriori(self, xa=None):\n        \"\"\"\n        Extract the a priori values. Call WSM `xaStandard()` before calling this function!\n        :param xa: The values in the `xa` vector just before the inversion. If None, copy from Workspace.\n        \"\"\"\n        ws = self._ws\n        if xa is None:\n            xa = ws.xa.value\n        self._xa = [xa[s] for s in self._slice]  # Always 0, but we implement it anyways.\n\n    def extract_result(self, x=None, avk=None, eo=None, es=None):\n        \"\"\"Extract the result and the corresponding values form the Workspace.\"\"\"\n        ws = self._ws\n        if x is None:\n            x = ws.x.value\n        if avk is None:\n            avk = ws.avk.value\n        if eo is None:\n            eo = ws.retrieval_eo.value\n        if es is None:\n            es = ws.retrieval_ss.value\n\n        self._x = [x[s] for s in self._slice]\n        self._avkm = [avk[s, s] for s in self._slice]\n        self._eo = [eo[s] for s in self._slice]\n        self._es = [es[s] for s in self._slice]\n\n    def to_xarray(self):\n        prefix = self.slug + '_'\n        grid_names = ('poly_order', 'observation')\n        grids = self.grids\n        flat_grid_name = prefix + 'grid'\n\n        coords = {n: c for n, c in zip(grid_names, grids)}\n\n        ds = xr.Dataset(\n            data_vars={\n                prefix + 'x': (grid_names, np.stack(self.x)),\n                prefix + 'xa': (grid_names, np.stack(self.xa)),\n                prefix + 'mr': (grid_names, np.stack(self.mr)),\n                prefix + 'eo': (grid_names, np.stack(self.eo)),\n                prefix + 'es': (grid_names, np.stack(self.es)),\n                prefix + 'avkm': ((grid_names[0], flat_grid_name, flat_grid_name + '_avk'), np.stack(self.avkm)),\n            },\n            coords=coords,\n            attrs={\n                'maintag': self._jacobian_quantity[0].maintag,\n                'subtag': '',\n                'subsubtag': '',\n                'analytical': self._jacobian_quantity[0].analytical,\n                'mode': self._jacobian_quantity[0].mode,\n                'perturbation': self._jacobian_quantity[0].perturbation,\n            }\n        )\n        return ds\n\n    @property\n    def slug(self):\n        return 'poly_fit'\n\n    @property\n    def grids(self):\n        jq_grids = self._jacobian_quantity[0].grids\n        if len(jq_grids[0]) > 1 or len(jq_grids[1]) > 1 or len(jq_grids[2]) > 1:\n            raise NotImplementedError()\n        return [np.arange(self.poly_order + 1), np.array(jq_grids[-1], dtype=np.int)]\n\n    @property\n    def covmat(self):\n        return sparse.diags(self._covmats)\n\n    @property\n    def poly_order(self):\n        return self.args['poly_order']\n\n    @property\n    def mr(self):\n        return [level2.avkm_mr(a) for a in self._avkm]\n\n\nclass SlicedArray:\n    def __init__(self, values, slugs_to_slices):\n        self._values = values\n        self.slugs = slugs_to_slices\n\n    def __getitem__(self, item):\n        if isinstance(item, tuple):\n            if len(item) == len(self._values.shape):\n                idx = tuple(slice(*self.slugs[it]) for it in item)\n                return self.values[idx]\n            else:\n                raise ValueError('Number of indexers must be one or be equal to number of dimensions.')\n        else:\n            a, b = self.slugs[item]\n            n_dims = len(self._values.shape)\n            return self._values[tuple(n_dims * [slice(a, b)])]\n\n    @property\n    def values(self):\n        return self._values\n", "meta": {"hexsha": "fe1751173320177fb70f96f20db5d8bec207b1fc", "size": 24524, "ext": "py", "lang": "Python", "max_stars_repo_path": "retrievals/arts/retrieval.py", "max_stars_repo_name": "leric2/pyretrievals", "max_stars_repo_head_hexsha": "3cae0afc9951ce079a44aa093689867b17a11060", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "retrievals/arts/retrieval.py", "max_issues_repo_name": "leric2/pyretrievals", "max_issues_repo_head_hexsha": "3cae0afc9951ce079a44aa093689867b17a11060", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "retrievals/arts/retrieval.py", "max_forks_repo_name": "leric2/pyretrievals", "max_forks_repo_head_hexsha": "3cae0afc9951ce079a44aa093689867b17a11060", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6406035665, "max_line_length": 121, "alphanum_fraction": 0.5917060838, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.18197971168146884}}
{"text": "\"\"\"\ncombustion_thermodynamics:\n--------------------------\n\nCombustion reaction thermodynamical properties.\n\nMRodriguez 2020\n\n\"\"\"\nfrom pyturb.gas_models.thermo_properties import ThermoProperties\nfrom pyturb.gas_models.perfect_ideal_gas import PerfectIdealGas\nfrom pyturb.gas_models.semiperfect_ideal_gas import SemiperfectIdealGas\nimport numpy as np\nimport warnings\n\n#TODO: Update gases:\noxidizers = ['Air', 'O', 'O2', 'O3', 'O2(L)', 'O3(L)']\n\nfuels = ['hydrocarbon', 'C8H18,isooctane', \n         'CH4', 'C2H6', 'C3H8', 'C4H10', 'C5H12', 'C6H14', 'C7H16', 'C8H18',\n         'CH4O', 'CH3OCH3',\n         'H2']\n\ninert_gases = ['He', 'Ar', 'N2',\n               'CO2', 'CO']\n\nclass Combustion(object):\n    \"\"\"\n    Combustion:\n    -----------\n\n\n    \"\"\"\n\n    def __init__(self, fuel, oxidizer):\n        \"\"\"\n        \"\"\"\n\n        if not(isinstance(fuel, PerfectIdealGas) or isinstance(fuel, SemiperfectIdealGas) or isinstance(fuel, IdealLiquid)):\n            # Check the flow is a Perfect or a Semiperfect gas fom pyturb\n            raise TypeError(\"Object must be PerfectIdealGas, SemiperfectIdealGas or PerfectLiquid. Instead received {}\".format(fluid))\n\n\n        if not(isinstance(fuel, PerfectIdealGas) or isinstance(fuel, SemiperfectIdealGas) or isinstance(fuel, IdealLiquid)):\n            # Check the flow is a Perfect or a Semiperfect gas from pyturb\n            raise TypeError(\"Object must be PerfectIdealGas, SemiperfectIdealGas or PerfectLiquid. Instead received {}\".format(fluid))\n\n        \n        self.oxidizer_list = oxidizers\n        self.fuel_list = fuels\n\n\n        self.fuel = fuel\n        self.oxidizer = oxidizer\n\n\n        reactants_status = self._classify_reactants()\n\n        if not reactants_status:\n            raise ValueError(\"Unknown fuel and oxidizer\")\n        else:\n            self._alpha = 0\n            self._beta = 0\n            self._gamma = 0\n            self._delta = 0\n\n\n        return\n\n\n    # Class properties for combustion thermodynamics\n    @property\n    def reactants(self):\n        \"\"\"\n        Reactants of the combustion reaction.\n        \"\"\"\n        return self._reactants\n\n\n    @property\n    def products(self):\n        \"\"\"\n        Products of the combustion reaction.\n        \"\"\"\n        return self._products\n\n\n    # Class properties for combustion thermodynamics\n    @property\n    def reactants_dictionary(self):\n        \"\"\"\n        Reactants dictionary [gas_species]: moles\n        \"\"\"\n        return self._reactants_dictionary\n\n\n    @property\n    def products_dictionary(self):\n        \"\"\"\n        Products dictionary [gas_species]: molesProducts of the combustion reaction.\n        \"\"\"\n        return self._products_dictionary\n\n\n    @property\n    def stoichiometric_reaction(self):\n        \"\"\"\n        Stoichiometric reaction of the combustion reaction.\n        \"\"\"\n        return self._stoichiometric_reaction\n\n\n    @property\n    def alpha(self):\n        \"\"\"\n        Moles of carbon present in the fuel molecule, per mole of fuel.\n        \"\"\"\n        return self._alpha\n\n    \n    @property\n    def beta(self):\n        \"\"\"\n        Moles of hydrogen present in the fuel molecule, per mole of fuel.\n        \"\"\"\n        return self._beta\n\n\n    @property\n    def gamma(self):\n        \"\"\"\n        Moles of oxygen present in the fuel molecule, per mole of fuel.\n        \"\"\"\n        return self._gamma\n\n\n    @property\n    def delta(self):\n        \"\"\"\n        Nytrogen present in the oxyder. 1 if true, 0 if false.\n        \"\"\"\n        return self._delta\n\n\n    @property\n    def oxidizer_fuel_ratio(self):\n        \"\"\"\n        Oxidizer to fuel stoichiometric molar ratio.\n        \"\"\"\n        return self._oxidizer_fuel_ratio\n\n\n    @property\n    def stoich_far(self):\n        \"\"\"\n        Stoichiometric fuel-air ratio.\n        \"\"\"\n        return self._stoich_far\n\n    \n    @property\n    def LHV(self):\n        \"\"\"\n        Lower heating value. [J/kg]\n        \"\"\"\n        return self._LHV\n\n\n    @property\n    def HHV(self):\n        \"\"\"\n        Higher heating value. [J/kg]\n        \"\"\"\n        return self._HHV\n\n\n    @property\n    def hcomb_l(self):\n        \"\"\"\n        Combustion Enthalpy, considering all products are condensed. [J/mol]\n        \"\"\"\n        return self._hcomb_l\n\n\n    @property\n    def hcomb_g(self):\n        \"\"\"\n        Combustion Enthalpy, considered all products are vaporized. [J/mol]\n        \"\"\"\n        return self._hcomb_g\n\n\n    def _classify_reactants(self):\n        \"\"\"\n        Check fuel and oxidizer species.\n        \"\"\"\n\n        if not (self.oxidizer.gas_species in self.oxidizer_list or self.oxidizer.gas_species == \"mixture\"):\n            warnings.warn(\"Requested oxidizer ({0}) not available. Available oxidizers: {1}\".format(self.oxidizer.gas_species, self.oxidizer_list))\n            return False\n    \n        if not (self.fuel.gas_species in self.fuel_list or self.fuel.gas_species == \"mixture\"):\n            warnings.warn(\"Requested fuel ({0}) not available. Available fuels: {1}\".format(self.fuel.gas_species, self.fuel_list))\n            return False\n\n        return True\n\n\n    def _combustion_stoichiometry_simple_reaction(self):\n        \"\"\"\n        Stoichiometric reaction of a combustion with one molecule of fuel and an oxidizer.\n        \"\"\"\n\n        has_carbon = False\n        has_hydrogen = False\n        has_oxygen = False\n\n        reactants = \"\"\n        products = \"\"\n        inerts = \"\"\n        products_dictionary = {}\n        reactants_dictionary = {}\n\n        alpha = 0\n        beta = 0\n        gamma = 0\n        delta = 0\n       \n\n        # TODO: Fuel mixtures will need a rework of alpha, beta, gamma coefficients\n\n        # Reactants:\n        # Stoichiometric combustion are calculated per unit mole of fuel. Quantity is adjusted afterwards.\n        reactants_dictionary[self.fuel.gas_species] = 1\n\n        for element in self.fuel.thermo_prop.chemical_formula:\n            if element == \"C\":\n                alpha = self.fuel.thermo_prop.chemical_formula[element]\n                reactants += \"C{0:1.0f}\".format(alpha) if not alpha==0 else reactants\n                has_carbon = True\n\n            elif element == \"H\":\n                beta = self.fuel.thermo_prop.chemical_formula[element]\n                reactants += \"H{0:1.0f}\".format(beta) if not beta==0 else reactants\n                has_hydrogen = True\n\n            \n            elif element == \"O\":\n                gamma = self.fuel.thermo_prop.chemical_formula[element]\n                reactants += \"O{0:1.0f}\".format(gamma) if not gamma==0 else reactants\n                has_oxygen = True\n        \n\n        # Oxidizer to fuel ratio depending on C, H, O atoms, assuming O2 as oxidizer\n        self._oxidizer_fuel_ratio = alpha + beta/4 - gamma/2\n\n        # TODO: Rework products. Mixtures must be accepted...\n        # Oxidizer\n        if self.oxidizer.gas_species == \"Air\":\n            delta = 1\n            has_oxygen = True\n            reactants += \" + {0:1.3f}(O2 + 79/21 N2)\".format(self.oxidizer_fuel_ratio)\n            reactants_dictionary[\"Air\"] = self.oxidizer_fuel_ratio\n\n        elif self.oxidizer.gas_species == \"O2\" or self.oxidizer.gas_species == \"O2(L)\":\n            delta = 0\n            for element in self.oxidizer.thermo_prop.chemical_formula:\n                if element == \"O\":\n                    has_oxygen = True\n                    reactants += \" + {0:1.3f} O{1:1.0f}\".format(self.oxidizer_fuel_ratio, self.oxidizer.thermo_prop.chemical_formula[element])\n                    reactants_dictionary[\"Air\"] = self.oxidizer_fuel_ratio\n\n        elif self.oxidizer.gas_species == \"O3\" or self.oxidizer.gas_species == \"O3(L)\":\n            self._oxidizer_fuel_ratio = self.oxidizer_fuel_ratio * 2/3\n            if element == \"O\":\n                has_oxygen = True\n                reactants += \" + {0:1.3f} O{1:1.0f}\".format(self.oxidizer_fuel_ratio, self.oxidizer.thermo_prop.chemical_formula[element])\n            reactants_dictionary[\"O3\"] = self.oxidizer_fuel_ratio\n\n        elif self.oxidizer.gas_species == \"O\":\n            self._oxidizer_fuel_ratio = self.oxidizer_fuel_ratio * 2\n            if element == \"O\":\n                has_oxygen = True\n                reactants += \" + {0:1.3f} O{1:1.0f}\".format(self.oxidizer_fuel_ratio, self.oxidizer.thermo_prop.chemical_formula[element])\n            reactants_dictionary[\"O\"] = self.oxidizer_fuel_ratio\n\n        else:\n            if self.oxidizer.gas_species == \"mixture\":\n                a = b = c = d = 0\n                delta = 0\n                for ii, gases in enumerate(self.oxidizer.mixture_gases['gas_species']):\n                    if gases == \"O\":\n                        has_oxygen = True\n                        a = self.oxidizer.mixture_gases.loc[ii]['Ng']\n\n                    elif gases == \"O2\":\n                        has_oxygen = True\n                        b = self.oxidizer.mixture_gases.loc[ii]['Ng']\n\n                    elif gases == \"O3\":\n                        has_oxygen = True\n                        c = self.oxidizer.mixture_gases.loc[ii]['Ng']\n\n\n                self._oxidizer_fuel_ratio = self.oxidizer_fuel_ratio * 2 / (a + 2*b + 3*c)\n                if a!=0:\n                    reactants += \" + {0:1.3f} O\".format(a*self.oxidizer_fuel_ratio)\n                    reactants_dictionary[\"O\"] = a*self.oxidizer_fuel_ratio\n                if b!=0:\n                    reactants_dictionary[\"O2\"] = b*self.oxidizer_fuel_ratio\n                if c!=0:\n                    reactants += \" + {0:1.3f} O3\".format(c*self.oxidizer_fuel_ratio)\n                    reactants_dictionary[\"O3\"] = c*self.oxidizer_fuel_ratio\n\n\n                for ii, gases in enumerate(self.oxidizer.mixture_gases['gas_species']):\n                    if gases in inert_gases:\n                        delta = 1\n                        d = self.oxidizer.mixture_gases.loc[ii]['Ng'] * self._oxidizer_fuel_ratio\n                        inerts += \" + {0:1.0f}{1}\".format(d, gases)\n                        reactants += inerts\n\n\n        # Products:\n        if has_oxygen:\n            # Hydrocarbon and hydorgen case:\n            if has_carbon and not has_hydrogen: \n                products += \"{0:1.0f}CO2\".format(alpha)\n                products_dictionary['CO2'] = alpha\n\n            elif not has_carbon and has_hydrogen:\n                products += \"{0:1.0f}H2O\".format(beta/2)\n                products_dictionary['H2O'] = beta/2\n            \n            elif has_carbon and has_hydrogen:\n                products += \"{0:1.0f}CO2 + {1:1.0f}H2O\".format(alpha, beta/2)\n                products_dictionary['CO2'] = alpha\n                products_dictionary['H2O'] = beta/2\n\n        #else:        \n            # TODO: Complete with other ozidizers in the future\n\n        # Nytrogen present:        \n        if delta == 1:\n            if self.oxidizer.gas_species == \"Air\":\n                products += \" + {0:1.3f}(79/21 N2)\".format(self.oxidizer_fuel_ratio)\n\n            else:\n                products += inerts\n\n       \n        # Combustion reaction:\n        self._stoichiometric_reaction = reactants + \" --> \" + products\n        self._reactants = reactants\n        self._products = products\n        self._reactants_dictionary_monofuel = reactants_dictionary\n        self._products_dictionary_monofuel = products_dictionary\n        \n\n        # Coefficients:\n        self._alpha += alpha\n        self._beta += beta\n        self._gamma += gamma\n        self._delta = delta if delta == 1 else self._delta\n\n\n        # TODO: Must be an independent function, otherwise the FAR of a full reaction wont make sense\n        # Fuel/Air ratio:\n        if self.oxidizer.gas_species == \"Air\":\n            self._stoich_far = self.fuel.thermo_prop.Mg / (self.oxidizer_fuel_ratio/0.21*self.oxidizer.Mg)\n        \n        else:\n            self._stoich_far = np.nan\n\n\n    def combustion_stoichiometry(self):\n        \"\"\"\n        Stoichiometric reaction of the combustion process. If the fuel is a mixture,\n        the combustion is decomposed in simple reactions with one molecule of fuel\n        each. The global reaction stoichiometry is calculated adding up the \n        stoichiometric coefficients of the simpler reaction.\n        \"\"\"\n\n        if self.fuel.gas_species == \"mixture\":\n            # TODO\n            print(\"mixture\")\n        else:\n            self._combustion_stoichiometry_simple_reaction()\n            self._reactants_dictionary = self._reactants_dictionary_monofuel\n            self._products_dictionary = self._products_dictionary_monofuel\n\n        return\n        \n    \n    def heat_of_combustion(self):\n        \"\"\"\n        Calculates the heat of a combustion under the model of constant pressure\n        combustor:\n            -qp = Sum_i(N_i*h_fi) - Sum_j(N_j*h_fj) [J/mol]\n        Heat of combustion is calculated per unit of mole of fuel and then it is \n        scaled to the mole quantity of fuel present in the reaction.\n\n        If the products contain water, the heat of combustion is calculated assuming\n        all water is condensed (l) and vaporized (g), providing two different values\n        of the heat of combustion:\n            - hcomb_g: heat of combustion with H2O(g) vaporized [J/mol]\n            - hcomb_l: heat of combustion with H2O(l) condensed [J/mol]\n\n        With the heat of combustion per unit mole, the Higher Heating Value and Lower\n        Heating Value may be calculated:\n            HHV = LHV + NH2O*MH2O*hfg / (Nfuel*Mfuel) [MJ/kg]\n            LHV = hcomb_g / Mfuel * 1e3 g/kg * 1e-6 MJ/J [MJ/kg]\n        \"\"\"\n        \n        # Loop for calculating the formation enthalpies of the reactants:\n        qp_r = 0\n        reactants = self.reactants_dictionary.keys()\n        \n        for element in reactants:\n            if element == \"Air\":\n                # Air is excluded from the thermodynamic_properties call, its heat of formation is negligible\n                qp_r += 0\n            else:\n                thermo_prop = ThermoProperties(element)\n                qp_r += thermo_prop.deltaHf_ref * self.reactants_dictionary[element]\n        \n\n        # Loop for calculating the formation enthalpies of the products\n        products = self.products_dictionary.keys()\n\n        qp_pl = 0\n        qp_pg = 0\n        for element in products:\n            print(element)\n            if element == \"Air\":\n                # Air is excluded from the thermodynamic_properties call, its heat of formation is negligible\n                qp_pl += 0\n                qp_pg += 0\n            else:\n                if element == 'H2O':\n                    thermo_prop = ThermoProperties('H2O(L)')\n                    qp_pl += thermo_prop.deltaHf_ref * self.products_dictionary[element]\n\n                    thermo_prop = ThermoProperties('H2O')\n                    qp_pg += thermo_prop.deltaHf_ref * self.products_dictionary[element]\n                else:\n                    thermo_prop = ThermoProperties(element)\n                    qp_pl += thermo_prop.deltaHf_ref * self.products_dictionary[element]\n                    qp_pg += thermo_prop.deltaHf_ref * self.products_dictionary[element]\n        \n        \n        self._hcomb_g = qp_r - qp_pg\n        self._hcomb_l = qp_r - qp_pl\n\n        self._HHV = self.hcomb_l / self.fuel.Mg * 1e3\n        self._LHV = self.hcomb_g / self.fuel.Mg * 1e3\n\n        # TODO: calculate heat of combustion as -Qp (heat of combustion by definition). If water is formed, \n        # calculate both condensed and vapor water\n\n        # TODO: With the heat of combustion calculated, obtain the HHV and LHV\n\n        return\n", "meta": {"hexsha": "451e92c356092b266367f56367063bfc5abc818d", "size": 15468, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/pyturb/combustion/combustion_thermodynamics.py", "max_stars_repo_name": "MRod5/pyturb", "max_stars_repo_head_hexsha": "08b4016528fc50733fff58d967d1000bf1e634c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2017-04-13T12:25:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T01:23:19.000Z", "max_issues_repo_path": "src/pyturb/combustion/combustion_thermodynamics.py", "max_issues_repo_name": "sergiodobler/pyturb", "max_issues_repo_head_hexsha": "248ea0ddc939c6d6f2c8d6b3f9a3d13976c22910", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2017-11-13T23:19:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-28T20:18:28.000Z", "max_forks_repo_path": "src/pyturb/combustion/combustion_thermodynamics.py", "max_forks_repo_name": "sergiodobler/pyturb", "max_forks_repo_head_hexsha": "248ea0ddc939c6d6f2c8d6b3f9a3d13976c22910", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2017-05-06T20:05:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T13:31:52.000Z", "avg_line_length": 33.3362068966, "max_line_length": 147, "alphanum_fraction": 0.5790018102, "include": true, "reason": "import numpy", "num_tokens": 3722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.18197971168146881}}
{"text": "\"\"\"\nModule for describing a RH-Neutrino which couples only with a single active\nneutrino through a Yukawa interaction with the SM Higgs.\n\"\"\"\nfrom abc import ABC, abstractmethod\nfrom functools import partial\nfrom typing import Callable, Dict, List, Optional, Tuple, Union\n\nimport numpy as np\nfrom hazma.rh_neutrino import RHNeutrino as _HazmaRhNeutrino  # type: ignore\n\nfrom storm.constants import LEPTON_MASSES\nfrom storm.models.simple._spectra import dndx_l_u_d as _dndx_l_u_d\nfrom storm.models.simple._spectra import dndx_l_w as _dndx_l_w\nfrom storm.models.simple._spectra import dndx_vl_d_d as _dndx_vl_d_d\nfrom storm.models.simple._spectra import dndx_vl_h as _dndx_vl_h\nfrom storm.models.simple._spectra import dndx_vl_l_l as _dndx_vl_l_l\nfrom storm.models.simple._spectra import dndx_vl_lp_lp as _dndx_vl_lp_lp\nfrom storm.models.simple._spectra import dndx_vl_u_u as _dndx_vl_u_u\nfrom storm.models.simple._spectra import dndx_vl_z as _dndx_vl_z\nfrom storm.models.simple._spectra import dndx_vlp_lp_l as _dndx_vlp_lp_l\nfrom storm.models.simple._widths import width_l_u_d as _width_l_u_d\nfrom storm.models.simple._widths import width_l_w as _width_l_w\nfrom storm.models.simple._widths import width_vl_d_d as _width_vl_d_d\nfrom storm.models.simple._widths import width_vl_h as _width_vl_h\nfrom storm.models.simple._widths import width_vl_l_l as _width_vl_l_l\nfrom storm.models.simple._widths import width_vl_lp_lp as _width_vl_lp_lp\nfrom storm.models.simple._widths import width_vl_u_u as _width_vl_u_u\nfrom storm.models.simple._widths import width_vl_vl_vl as _width_vl_vl_vl\nfrom storm.models.simple._widths import width_vl_z as _width_vl_z\nfrom storm.models.simple._widths import width_vlp_lp_l as _width_vlp_lp_l\n\n# Type of the final states: ('s1', 's2', ...)\nStateType = Tuple[str, ...]\n\n_PRODUCT_NAME_TO_ID = {\n    \"photon\": 22,\n    \"electron\": 11,\n    \"positron\": -11,\n    \"electron-neutrino\": 12,\n    \"muon-neutrino\": 14,\n    \"tau-neutrino\": 16,\n    \"neutron\": 2112,\n    \"proton\": 2212,\n    \"anti-proton\": -2212,\n}\n\nAVAILIBLE_PRODUCTS = _PRODUCT_NAME_TO_ID.keys()\n\n# Type of the underlying c++ functions.\n_SPECTRUM_CALLABLE = Callable[\n    [float, float, int, int, Tuple[float, float], int, int],\n    Tuple[List[float], List[float]],\n]\n\n\nclass SimpleRhNeutrinoPythia(SimpleRhNeutrinoBase):\n    \"\"\"\"\"\"\n\n    def __init__(self, mvr: float, theta: float, lep: str):\n        super().__init__(mvr, theta, lep)\n\n        # Dictionary of functions to compute the partial widths of a given\n        # final state.\n        self._width_dispatch: Dict[Tuple[str, ...],\n                                   Callable[..., float]] = dict()\n        # Dictionary of functions to compute the spectra of from the decay into\n        # a given final state.\n        self._dndx_dispatch: Dict[\n            Tuple[str, ...],\n            Callable[..., Tuple[np.ndarray, np.ndarray]]] = dict()\n        # List of tuples specifying all decay modes\n        self._decay_final_states: List[Tuple[str, ...]] = list()\n        # Dictionary specifying to conjugate of a given final state.\n        self._conj_map: Dict[Tuple[str, ...], Tuple[str, ...]] = dict()\n\n        self.__create_states_and_dispatch_tables()\n\n    def __create_states_and_dispatch_tables(self):\n        \"\"\"\n        Create the dispatch tables for the partial width and spectrum\n        functions.\n        \"\"\"\n        lep = self._lep\n        genl = self._genl\n        dt = {\n            (f\"v{lep}\", \"h\"): partial(_width_vl_h, genl=genl),\n            (f\"v{lep}\", \"z\"): partial(_width_vl_z, genl=genl),\n            (f\"{lep}\", \"w\"): partial(_width_l_w, genl=genl),\n            (f\"{lep}bar\", \"wbar\"): partial(_width_l_w, genl=genl),\n            (f\"v{lep}\", f\"v{lep}\", f\"v{lep}\"):\n                partial(_width_vl_vl_vl, genl=genl),\n            (f\"v{lep}\", f\"{lep}\", f\"{lep}bar\"):\n                partial(_width_vl_l_l, genl=genl),\n        }\n        sdt = {\n            (f\"v{lep}\", \"h\"): partial(_dndx_vl_h, genl=genl),\n            (f\"v{lep}\", \"z\"): partial(_dndx_vl_z, genl=genl),\n            (f\"{lep}\", \"w\"): partial(_dndx_l_w, genl=genl, anti=False),\n            (f\"{lep}bar\", \"wbar\"): partial(_dndx_l_w, genl=genl, anti=True),\n            (f\"v{lep}\", f\"{lep}\", f\"{lep}bar\"):\n                partial(_dndx_vl_l_l, genl=genl),\n        }\n\n        self._conj_map = {(f\"{lep}bar\", \"wbar\"): (f\"{lep}\", \"w\")}\n\n        # Add states of the form vl + q + qbar and l + u + dbar\n        for i, (u, d) in enumerate([(\"u\", \"d\"), (\"c\", \"s\"), (\"t\", \"b\")]):\n            state = (f\"v{lep}\", u, f\"{u}bar\")\n            dt[state] = partial(_width_vl_u_u, genl=genl, genq=i)\n            sdt[state] = partial(_dndx_vl_u_u, genl=genl, genq=i)\n\n            state = (f\"v{lep}\", d, f\"{d}bar\")\n            dt[state] = partial(_width_vl_d_d, genl=genl, genq=i)\n            sdt[state] = partial(_dndx_vl_d_d, genl=genl, genq=i)\n\n            state = (f\"{lep}\", u, f\"{d}bar\")\n            dt[state] = partial(_width_l_u_d, genl=genl, genq=i)\n            sdt[state] = partial(_dndx_l_u_d, genl=genl, genq=i, anti=False)\n\n            state = (f\"{lep}bar\", f\"{u}bar\", f\"{d}\")\n            dt[state] = partial(_width_l_u_d, genl=genl, genq=i)\n            sdt[state] = partial(_dndx_l_u_d, genl=genl, genq=i, anti=True)\n\n            self._conj_map[state] = (f\"{lep}\", u, f\"{d}bar\")\n\n        for i, ell in enumerate([\"e\", \"mu\", \"tau\"]):\n            if ell != lep:\n                state = (f\"v{lep}\", f\"{ell}\", f\"{ell}bar\")\n                dt[state] = partial(_width_vl_lp_lp, genl=genl, genlp=i)\n                sdt[state] = partial(_dndx_vl_lp_lp, genl=genl, genlp=i)\n\n                state = (f\"v{ell}\", f\"{ell}\", f\"{lep}bar\")\n                dt[state] = partial(_width_vlp_lp_l, genl=genl, genlp=i)\n                sdt[state] = partial(\n                    _dndx_vlp_lp_l, genl=genl, genlp=i, anti=False)\n\n                state = (f\"v{ell}\", f\"{lep}\", f\"{ell}bar\")\n                dt[state] = partial(_width_vlp_lp_l, genl=genl, genlp=i)\n                sdt[state] = partial(\n                    _dndx_vlp_lp_l, genl=genl, genlp=i, anti=True)\n\n                self._conj_map[state] = (f\"v{ell}\", f\"{ell}\", f\"{lep}bar\")\n\n        self._width_dispatch = dt\n        self._dndx_dispatch = sdt\n        self._decay_final_states = list(dt.keys())\n\n    @property\n    def lep(self) -> str:\n        return self._lep\n\n    @lep.setter\n    def lep(self, lep: str) -> None:\n        self._lep = lep\n        self.__create_states_and_dispatch_tables()\n\n    @property\n    def decay_final_states(self) -> List[StateType]:\n        return self._decay_final_states\n\n    @decay_final_states.setter\n    def decay_final_states(self, val: List[StateType]) -> None:\n        raise AttributeError('Cannot set \"decay final states.\"')\n\n    def partial_width(self, state: StateType, **kwargs) -> float:\n        \"\"\"\n        Compute the partial width for a right-handed neutrino to decay into a\n        particular final state.\n\n        Parameters\n        ----------\n        state: Tuple[str, ...]\n            A tuple of strings representing the final state. For example,\n            state=('ve', 'h') will return the partial width for vr -> ve + h.\n            See `decay_final_states` for a list of all final states.\n\n        Returns\n        -------\n        pw: float\n            The partial decay width.\n        \"\"\"\n        if state in self._width_dispatch.keys():\n            return self._width_dispatch[state](self._mvr, self._theta)\n        raise ValueError(f\"Invalid state: {state}\")\n\n    def partial_widths(self, **kwargs) -> Dict[StateType, float]:\n        \"\"\"\n        Compute the partial width for a right-handed neutrino to decay into all\n        possible final states.\n\n        Parameters\n        ----------\n        remove_conjugates: Optional[bool]\n            If true, the conjugate states are removed and their partial widths\n            are added into the unconjugated state.\n\n        Returns\n        -------\n        pws: Dict[str, float]\n            Dictionary containing all partial decay widths from the decay of a\n            right-handed neutrino.\n        \"\"\"\n        pws = {\n            key: func(self._mvr, self._theta)\n            for key, func in self._width_dispatch.items()\n        }\n\n        if \"remove_conjugates\" in kwargs:\n            for key, val in self._conj_map.items():\n                pws[val] += pws[key]\n                del pws[key]\n\n        pws[(\"total\",)] = sum(pws.values())\n        return pws\n\n    def branching_fractions(self, **kwargs) -> Dict[StateType, float]:\n        \"\"\"\n        Compute the branching fractions for a right-handed neutrino to decay\n        into a all availible final states.\n\n        Parameters\n        ----------\n        remove_conjugates: Optional[bool]\n            If true, the conjugate states are removed and their partial widths\n            are added into the unconjugated state.\n\n        Returns\n        -------\n        bf: Dict[str, float]\n            Dictionary containing all branching fractions from the decay of a\n            right-handed neutrino.\n        \"\"\"\n        remove_conjugates = kwargs.get(\"remove_conjugates\")\n        if remove_conjugates is None:\n            remove_conjugates = True\n\n        pws = self.partial_widths(remove_conjugates=remove_conjugates)\n        return {\n            key: val / pws[(\"total\",)]\n            for key, val in pws.items() if key != (\"total\",)\n        }\n\n    def dndx_single_state(\n        self,\n        x: np.ndarray,\n        product: int,\n        state: StateType,\n        **kwargs\n    ) -> Tuple[np.ndarray, np.ndarray]:\n        \"\"\"\n        Compute the spectrum of a specified product from the decay of a\n        right-handed neutrino into all availible final states of a specified\n        final state.\n\n        Parameters\n        ----------\n        product: int,\n            PDG code of the product to compute spectrum for. For example, to\n            compute the photon spectrum, use `22`.\n        xbounds: Tuple[float, float]\n            Bounds on `x = 2*E/mvr`.\n        nevents: Optional[int]\n            Number of Pythia events to use in generating the spectrum. Default\n            is 10_000.\n        state: Optional[Tuple[str, ...]]\n            A tuple of strings representing the final state. For example,\n            state=('ve', 'h') will return the partial width for vr -> ve + h.\n            See `decay_final_states` for a list of all final states.\n\n        Returns\n        -------\n        dndx:\n            If a state was specified, the return is the x and spectrum values.\n            Otherwise, the x values are returns along with a dictionary of the\n            spectra for all posible final states.\n        \"\"\"\n\n        nevents = kwargs[\"nevents\"] if \"nevents\" in kwargs else 10_000\n\n        # Set the arguments to pass to c++ functions\n        _kwargs = {\n            \"mvr\": self._mvr,\n            \"theta\": self._theta,\n            \"product\": product,\n            \"xbounds\": (np.min(x), np.max(x)),\n            \"nbins\": len(x),\n            \"nevents\": nevents,\n        }\n\n        if state in self._dndx_dispatch.keys():\n            return self._dndx_dispatch[state](**_kwargs)\n        raise ValueError(f\"Invalid state: {state}\")\n\n    def dndx(\n            self,\n            x: np.ndarray,\n            product: int,\n            **kwargs\n    ) -> Tuple[np.ndarray, Dict[StateType, np.ndarray]]:\n        \"\"\"\n        Compute the spectrum of a specified product from the decay of a\n        right-handed neutrino into all availible final states of a specified\n        final state.\n\n        Parameters\n        ----------\n        product: int,\n            PDG code of the product to compute spectrum for. For example, to\n            compute the photon spectrum, use `22`.\n        xbounds: Tuple[float, float]\n            Bounds on `x = 2*E/mvr`.\n        nevents: Optional[int]\n            Number of Pythia events to use in generating the spectrum. Default\n            is 10_000.\n        state: Optional[Tuple[str, ...]]\n            A tuple of strings representing the final state. For example,\n            state=('ve', 'h') will return the partial width for vr -> ve + h.\n            See `decay_final_states` for a list of all final states.\n\n        Returns\n        -------\n        dndx:\n            If a state was specified, the return is the x and spectrum values.\n            Otherwise, the x values are returns along with a dictionary of the\n            spectra for all posible final states.\n        \"\"\"\n\n        nevents = kwargs[\"nevents\"] if \"nevents\" in kwargs else 10_000\n\n        # Set the arguments to pass to c++ functions\n        _kwargs = {\n            \"mvr\": self._mvr,\n            \"theta\": self._theta,\n            \"product\": product,\n            \"xbounds\": (np.min(x), np.max(x)),\n            \"nbins\": len(x),\n            \"nevents\": nevents,\n        }\n\n        dndx = {key: np.zeros_like(x) for key in self._dndx_dispatch.keys()}\n        # Use the first state to get xs\n        first_state = list(self._dndx_dispatch.keys())[0]\n        xs, dndx[first_state] = self._dndx_dispatch[first_state](**_kwargs)\n\n        # Compute spectra for all other states\n        dndx = {\n            key: func(**_kwargs)[1]\n            for key, func in self._dndx_dispatch.items()\n            if key != first_state\n        }\n\n        # Apply branching fractions and compute total spectrum\n        total = np.zeros_like(xs)\n        bfs = self.branching_fractions(remove_conjugates=False)\n        for key in dndx.keys():\n            dndx[key] *= bfs[key]\n            total += dndx[key]\n        dndx[(\"total\",)] = total\n\n        return xs, dndx\n\n\nclass SimpleRhNeutrinoHazma(SimpleRhNeutrinoBase):\n    \"\"\"\n    Model of a right-handed neutrino with a mass less than 1 GeV that mixes\n    with a single active neutrino.\n    \"\"\"\n\n    def __init__(self, mvr, theta, lep):\n        super().__init__(mvr, theta, lep)\n\n        self._hazma = _HazmaRhNeutrino(mvr, theta, lep, include_3body=True)\n\n        # Dictionary of functions to compute the partial widths of a given\n        # final state.\n        self._width_dispatch: Dict[Tuple[str, ...],\n                                   Callable[..., float]] = dict()\n        # Dictionary of functions to compute the spectra of from the decay into\n        # a given final state.\n        self._dnde_dispatch: Dict[\n            Tuple[str, ...],\n            Callable[..., Tuple[np.ndarray, np.ndarray]]] = dict()\n        # List of tuples specifying all decay modes\n        self._decay_final_states: List[Tuple[str, ...]] = list()\n        # Dictionary specifying to conjugate of a given final state.\n        self._conj_map: Dict[Tuple[str, ...], Tuple[str, ...]] = dict()\n\n    def __create_states_and_dispatch_tables(self):\n        lep = self._lep\n\n        self._width_dispatch = {\n            (f\"{lep}\", \"pi\"): self._hazma.width_pi_l,\n            (f\"{lep}\", \"k\"): self._hazma.width_k_l(),\n            (f\"v{lep}\", \"pi0\"): self._hazma.width_pi0_nu,\n            (f\"v{lep}\", \"g\"): self._hazma.width_nu_gamma,\n            (f\"v{lep}\", \"pi\", \"pi\"): self._hazma.width_nu_pi_pi,\n            (f\"{lep}\", \"pi\", \"pi0\"): self._hazma.width_l_pi_pi0(),\n            (f\"v{lep}\", f\"{lep}\", f\"{lep}\"): self._hazma.width_nu_l_l,\n            (f\"v{lep}\", f\"v{lep}\", f\"v{lep}\"): self._hazma.width_nu_nu_nu,\n            (f\"v{lep}\", \"g\", \"g\"): self._hazma.width_nu_g_g,\n        }\n\n        self._dnde_dispatch = {\n            (f\"{lep}\", \"pi\"): self._hazma.dnde_pi_l,\n            (f\"{lep}\", \"k\"): self._hazma.dnde_k_l,\n            (f\"v{lep}\", \"pi0\"): self._hazma.dnde_nu_pi0,\n            # (f\"v{lep}\", \"g\"): self._hazma.dnde_,\n            (f\"v{lep}\", \"pi\", \"pi\"): self._hazma.dnde_nu_pi_pi,\n            (f\"{lep}\", \"pi\", \"pi0\"): self._hazma.dnde_l_pi_pi0,\n            (f\"v{lep}\", f\"{lep}\", f\"{lep}\"): self._hazma.dnde_nu_l_l,\n            (f\"v{lep}\", \"g\", \"g\"): self._hazma.dnde_nu_g_g,\n        }\n\n        self._decay_final_states = list(self._width_dispatch.keys())\n\n        self._conj_map = {\n            (f\"{lep}\", \"pi\"): (f\"{lep}bar\", \"pibar\"),\n            (f\"{lep}\", \"k\"): (f\"{lep}bar\", \"kbar\"),\n            (f\"{lep}\", \"pi\", \"pi0\"): (f\"{lep}bar\", \"pibar\", \"pi0\"),\n        }\n\n    def partial_width(self, state: StateType, **kwargs) -> float:\n        if state in self._decay_final_states:\n            return self._width_dispatch[state]()\n        else:\n            raise ValueError(f\"Invalid state: {state}\")\n\n    def partial_widths(self, **kwargs) -> Dict[StateType, float]:\n        widths = dict()\n        for key, func in self._width_dispatch.items():\n            if key not in self._conj_map:\n                widths[key] = func()\n\n        remove_conjugate = kwargs.get('remove_conjugate')\n        if remove_conjugate is None:\n            if not remove_conjugate:\n                for state, conj in self._conj_map.items():\n                    widths[state] /= 2.0\n                    widths[conj] = widths[state]\n\n        return {key: func() for key, func in self._width_dispatch.items()}\n\n    def dndx(self, x: np.ndarray, product: int, **kwargs) -> float:\n        \"\"\"\n        Compute the spectrum of a specified product from the decay of a\n        right-handed neutrino into all availible final states of a specified\n        final state.\n\n        Parameters\n        ----------\n        product: int,\n            PDG code of the product to compute spectrum for. For example, to\n            compute the photon spectrum, use `22`.\n        xbounds: Tuple[float, float]\n            Bounds on `x = 2*E/mvr`.\n        state: Optional[Tuple[str, ...]]\n            A tuple of strings representing the final state. For example,\n            state=('ve', 'h') will return the partial width for vr -> ve + h.\n            See `decay_final_states` for a list of all final states.\n\n        Returns\n        -------\n        dndx:\n            If a state was specified, the return is the x and spectrum values.\n            Otherwise, the x values are returns along with a dictionary of the\n            spectra for all posible final states.\n        \"\"\"\n        if not product == \"photon\" or not product == 22:\n            raise NotImplementedError(\n                \"Only the photon spectrum has been implemented.\")\n        pf = self._mvr / 2.0\n        egams = pf * xs\n\n        # Check if `state` was passed in\n        state = kwargs[\"state\"] if \"state\" in kwargs else None\n        if state is not None:\n            if state in self._dnde_dispatch:\n                return pf * self._dnde_dispatch[state](egams)\n            raise ValueError(f\"Invalid state: {state}\")\n\n        spectra = dict()\n        for state, func in self._dnde_dispatch.items():\n            spectra[state] = pf * func(egams)\n\n        return spectra\n", "meta": {"hexsha": "3bd102fd926b403b3bfb23cb0886a9d53e750c7b", "size": 18594, "ext": "py", "lang": "Python", "max_stars_repo_path": "storm/models/simple/__init__.py", "max_stars_repo_name": "LoganAMorrison/Storm", "max_stars_repo_head_hexsha": "b189f276064a904d1792a10249fa3555237e3062", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "storm/models/simple/__init__.py", "max_issues_repo_name": "LoganAMorrison/Storm", "max_issues_repo_head_hexsha": "b189f276064a904d1792a10249fa3555237e3062", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "storm/models/simple/__init__.py", "max_forks_repo_name": "LoganAMorrison/Storm", "max_forks_repo_head_hexsha": "b189f276064a904d1792a10249fa3555237e3062", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.180698152, "max_line_length": 79, "alphanum_fraction": 0.5815316769, "include": true, "reason": "import numpy", "num_tokens": 4892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.1819797116814688}}
{"text": "# Copyright (c) 2020 NVIDIA CORPORATION.\n# Copyright (c) 2018-2020 Chris Choy (chrischoy@ai.stanford.edu).\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n# of the Software, and to permit persons to whom the Software is furnished to do\n# so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# Please cite \"4D Spatio-Temporal ConvNets: Minkowski Convolutional Neural\n# Networks\", CVPR'19 (https://arxiv.org/abs/1904.08755) if you use any part\n# of the code.\nimport math\nfrom collections import Sequence, namedtuple\nfrom functools import reduce\nimport numpy as np\nfrom typing import Union\n\nimport torch\nfrom MinkowskiCommon import convert_to_int_list\nfrom MinkowskiEngineBackend._C import CoordinateMapKey, RegionType\nfrom MinkowskiCoordinateManager import CoordinateManager\n\n\ndef get_kernel_volume(region_type, kernel_size, region_offset, axis_types, dimension):\n    \"\"\"\n    when center is True, the custom region_offset will be centered at the\n    origin. Currently, for HYPER_CUBE, HYPER_CROSS with odd kernel sizes cannot\n    use center=False.\n    \"\"\"\n    if region_type == RegionType.HYPER_CUBE:\n        assert reduce(\n            lambda k1, k2: k1 > 0 and k2 > 0, kernel_size\n        ), \"kernel_size must be positive\"\n        assert (\n            region_offset is None\n        ), \"Region offset must be None when region_type is given\"\n        assert axis_types is None, \"Axis types must be None when region_type is given\"\n        # Typical convolution kernel\n\n        # Convolution kernel with even numbered kernel size not defined.\n        kernel_volume = torch.prod(torch.IntTensor(kernel_size)).item()\n\n    elif region_type == RegionType.HYPER_CROSS:\n        assert reduce(\n            lambda k1, k2: k1 > 0 and k2 > 0, kernel_size\n        ), \"kernel_size must be positive\"\n        assert (\n            torch.IntTensor(kernel_size) % 2\n        ).prod().item() == 1, \"kernel_size must be odd for region_type HYPER_CROSS\"\n        # 0th: itself, (1, 2) for 0th dim neighbors, (3, 4) for 1th dim ...\n        kernel_volume = (torch.sum(torch.IntTensor(kernel_size) - 1) + 1).item()\n\n    # elif region_type == RegionType.HYBRID:\n    #     assert reduce(\n    #         lambda k1, k2: k1 > 0 and k2 > 0, kernel_size\n    #     ), \"kernel_size must be positive\"\n    #     assert (\n    #         region_offset is None\n    #     ), \"region_offset must be None when region_type is HYBRID\"\n    #     kernel_size_list = kernel_size.tolist()\n    #     kernel_volume = 1\n    #     # First HYPER_CUBE\n    #     for axis_type, curr_kernel_size, d in zip(\n    #         axis_types, kernel_size_list, range(dimension)\n    #     ):\n    #         if axis_type == RegionType.HYPER_CUBE:\n    #             kernel_volume *= curr_kernel_size\n\n    #     # Second, HYPER_CROSS\n    #     for axis_type, curr_kernel_size, d in zip(\n    #         axis_types, kernel_size_list, range(dimension)\n    #     ):\n    #         if axis_type == RegionType.HYPER_CROSS:\n    #             kernel_volume += curr_kernel_size - 1\n\n    elif region_type == RegionType.CUSTOM:\n        assert (\n            region_offset.numel() > 0\n        ), \"region_offset must be non empty when region_type is CUSTOM\"\n        assert (\n            region_offset.size(1) == dimension\n        ), \"region_offset must have the same dimension as the network\"\n        kernel_volume = int(region_offset.size(0))\n\n    else:\n        raise NotImplementedError()\n\n    return kernel_volume\n\n\ndef convert_region_type(\n    region_type: RegionType,\n    tensor_stride: Union[Sequence, np.ndarray, torch.IntTensor],\n    kernel_size: Union[Sequence, np.ndarray, torch.IntTensor],\n    up_stride: Union[Sequence, np.ndarray, torch.IntTensor],\n    dilation: Union[Sequence, np.ndarray, torch.IntTensor],\n    region_offset: Union[Sequence, np.ndarray, torch.IntTensor],\n    axis_types: Union[Sequence, np.ndarray, torch.IntTensor],\n    dimension: int,\n    center: bool = True,\n):\n    \"\"\"\n    when center is True, the custom region_offset will be centered at the\n    origin. Currently, for HYPER_CUBE, HYPER_CROSS with odd kernel sizes cannot\n    use center=False.\n\n    up_stride: stride for conv_transpose, otherwise set it as 1\n    \"\"\"\n    if region_type == RegionType.HYPER_CUBE:\n        if isinstance(region_offset, torch.Tensor):\n            assert (\n                region_offset.numel() == 0\n            ), \"Region offset must be empty when region_type is given\"\n        else:\n            assert (\n                region_offset is None\n            ), \"Region offset must be None when region_type is given\"\n\n        assert axis_types is None, \"Axis types must be None when region_type is given\"\n        # Typical convolution kernel\n        assert reduce(\n            lambda k1, k2: k1 > 0 and k2 > 0, kernel_size\n        ), \"kernel_size must be positive\"\n        # assert torch.unique(dilation).numel() == 1\n        kernel_volume = reduce(lambda k1, k2: k1 * k2, kernel_size)\n\n    elif region_type == RegionType.HYPER_CROSS:\n        assert reduce(\n            lambda k1, k2: k1 > 0 and k2 > 0, kernel_size\n        ), \"kernel_size must be positive\"\n        assert (\n            kernel_size % 2\n        ).prod() == 1, \"kernel_size must be odd for region_type HYPER_CROSS\"\n        # 0th: itself, (1, 2) for 0th dim neighbors, (3, 4) for 1th dim ...\n        kernel_volume = (\n            reduce(lambda k1, k2: k1 + k2, map(lambda k: k - 1, kernel_size)) + 1\n        )\n\n    elif region_type == RegionType.HYBRID:\n        assert reduce(\n            lambda k1, k2: k1 > 0 and k2 > 0, kernel_size\n        ), \"kernel_size must be positive\"\n        if isinstance(region_offset, torch.Tensor):\n            assert (\n                region_offset.numel() == 0\n            ), \"Region offset must be empty when region_type is given\"\n        else:\n            assert (\n                region_offset is None\n            ), \"Region offset must be None when region_type is given\"\n\n        region_offset = [\n            [\n                0,\n            ]\n            * dimension\n        ]\n        kernel_size_list = kernel_size.tolist()\n        # First HYPER_CUBE\n        for axis_type, curr_kernel_size, d in zip(\n            axis_types, kernel_size_list, range(dimension)\n        ):\n            new_offset = []\n            if axis_type == RegionType.HYPER_CUBE:\n                for offset in region_offset:\n                    for curr_offset in range(curr_kernel_size):\n                        off_center = (\n                            int(math.floor((curr_kernel_size - 1) / 2)) if center else 0\n                        )\n                        offset = offset.copy()  # Do not modify the original\n                        # Exclude the coord (0, 0, ..., 0)\n                        if curr_offset == off_center:\n                            continue\n                        offset[d] = (\n                            (curr_offset - off_center)\n                            * dilation[d]\n                            * (tensor_stride[d] / up_stride[d])\n                        )\n                        new_offset.append(offset)\n            region_offset.extend(new_offset)\n\n        # Second, HYPER_CROSS\n        for axis_type, curr_kernel_size, d in zip(\n            axis_types, kernel_size_list, range(dimension)\n        ):\n            new_offset = []\n            if axis_type == RegionType.HYPER_CROSS:\n                for curr_offset in range(curr_kernel_size):\n                    off_center = (\n                        int(math.floor((curr_kernel_size - 1) / 2)) if center else 0\n                    )\n                    offset = [\n                        0,\n                    ] * dimension\n                    # Exclude the coord (0, 0, ..., 0)\n                    if curr_offset == off_center:\n                        continue\n                    offset[d] = (\n                        (curr_offset - off_center)\n                        * dilation[d]\n                        * (tensor_stride[d] / up_stride[d])\n                    )\n                    new_offset.append(offset)\n            region_offset.extend(new_offset)\n\n        # Convert to CUSTOM type\n        region_type = RegionType.CUSTOM\n        region_offset = torch.IntTensor(region_offset)\n        kernel_volume = int(region_offset.size(0))\n\n    elif region_type == RegionType.CUSTOM:\n        assert (\n            region_offset.numel() > 0\n        ), \"region_offset must be non empty when region_type is CUSTOM\"\n        assert (\n            region_offset.size(1) == dimension\n        ), \"region_offset must have the same dimension as the network\"\n        kernel_volume = int(region_offset.size(0))\n        assert isinstance(\n            region_offset.dtype, torch.IntTensor\n        ), \"region_offset must be a torch.IntTensor.\"\n    else:\n        raise NotImplementedError()\n\n    if region_offset is None:\n        region_offset = torch.IntTensor()\n\n    return region_type, region_offset, kernel_volume\n\n\nclass KernelGenerator:\n    __slots__ = (\n        \"cache\",\n        \"kernel_size\",\n        \"kernel_stride\",\n        \"kernel_dilation\",\n        \"region_type\",\n        \"region_offsets\",\n        \"axis_types\",\n        \"dimension\",\n        \"kernel_volume\",\n        \"requires_strided_coordinates\",\n        \"expand_coordinates\",\n    )\n\n    def __init__(\n        self,\n        kernel_size=-1,\n        stride=1,\n        dilation=1,\n        is_transpose: bool = False,\n        region_type: RegionType = RegionType.HYPER_CUBE,\n        region_offsets: torch.Tensor = None,\n        expand_coordinates: bool = False,\n        axis_types=None,\n        dimension=-1,\n    ):\n        r\"\"\"\n        :attr:`region_type` (RegionType, optional): defines the kernel\n        shape. Please refer to MinkowskiEngine.Comon for details.\n\n        :attr:`region_offset` (torch.IntTensor, optional): when the\n        :attr:`region_type` is :attr:`RegionType.CUSTOM`, the convolution\n        kernel uses the provided `region_offset` to define offsets. It\n        should be a matrix of size :math:`N \\times D` where :math:`N` is\n        the number of offsets and :math:`D` is the dimension of the\n        space.\n\n        :attr:`axis_types` (list of RegionType, optional): If given, it\n        uses different methods to create a kernel for each axis. e.g., when\n        it is `[RegionType.HYPER_CUBE, RegionType.HYPER_CUBE,\n        RegionType.HYPER_CROSS]`, the kernel would be rectangular for the\n        first two dimensions and cross shaped for the thrid dimension.\n        \"\"\"\n        assert dimension > 0\n        assert isinstance(region_type, RegionType)\n\n        kernel_size = convert_to_int_list(kernel_size, dimension)\n        kernel_stride = convert_to_int_list(stride, dimension)\n        kernel_dilation = convert_to_int_list(dilation, dimension)\n\n        self.cache = {}\n        self.kernel_size = kernel_size\n        self.kernel_stride = kernel_stride\n        self.kernel_dilation = kernel_dilation\n        self.region_type = region_type\n        self.region_offsets = region_offsets if region_offsets else torch.IntTensor()\n        self.axis_types = axis_types\n        self.dimension = dimension\n        self.kernel_volume = get_kernel_volume(\n            region_type, kernel_size, region_offsets, axis_types, dimension\n        )\n        self.requires_strided_coordinates = reduce(\n            lambda s1, s2: s1 == 1 and s2 == 1, kernel_stride\n        )\n        self.expand_coordinates = expand_coordinates\n\n    def get_kernel(self, tensor_stride, is_transpose):\n        assert len(tensor_stride) == self.dimension\n        if tuple(tensor_stride) not in self.cache:\n            up_stride = (\n                self.stride\n                if is_transpose\n                else torch.Tensor(\n                    [\n                        1,\n                    ]\n                    * self.dimension\n                )\n            )\n\n            self.cache[tuple(tensor_stride)] = convert_region_type(\n                self.region_type,\n                tensor_stride,\n                self.kernel_size,\n                up_stride,\n                self.kernel_dilation,\n                self.region_offsets,\n                self.axis_types,\n                self.dimension,\n            )\n\n        return self.cache[tuple(tensor_stride)]\n\n    def __repr__(self):\n        return (\n            self.__class__.__name__\n            + f\"(kernel_size={self.kernel_size}, kernel_stride={self.kernel_stride}, kernel_dilation={self.kernel_dilation}, \"\n            + f\"region_type={self.region_type}, expand_coordinates={self.expand_coordinates}, dimension={self.dimension})\"\n        )\n\n\nclass KernelRegion(\n    namedtuple(\n        \"KernelRegion\",\n        (\n            \"kernel_size\",\n            \"kernel_stride\",\n            \"kernel_dilation\",\n            \"region_type\",\n            \"offset\",\n            \"D\",\n        ),\n    )\n):\n    \"\"\"adding functionality to a named tuple\"\"\"\n\n    __slots__ = ()\n\n    def __init__(\n        self,\n        kernel_size,\n        kernel_stride,\n        kernel_dilation,\n        region_type,\n        offset,\n        dimension,\n    ):\n        kernel_size = convert_to_int_list(kernel_size, dimension)\n        kernel_stride = convert_to_int_list(kernel_stride, dimension)\n        kernel_dilation = convert_to_int_list(kernel_dilation, dimension)\n        super(KernelRegion, self).__init__(\n            kernel_size, kernel_stride, kernel_dilation, region_type, offset, dimension\n        )\n\n    def __str__(self):\n        return \"kernel_size:{self.kernel_size}, kernel_stride:{self.kernel_stride}, region_type:{self.region_type}\"\n\n\ndef save_ctx(\n    ctx,  # function object context\n    kernel_generator: KernelGenerator,\n    in_coords_key: CoordinateMapKey,\n    out_coords_key: CoordinateMapKey,\n    coordinate_manager: CoordinateManager,\n):\n    ctx.kernel_generator = kernel_generator\n    ctx.in_coordinate_map_key = in_coords_key\n    ctx.out_coordinate_map_key = out_coords_key\n    ctx.coordinate_manager = coordinate_manager\n    return ctx\n", "meta": {"hexsha": "409c813d8acadcb97d9f035fdc124702a4d05940", "size": 14779, "ext": "py", "lang": "Python", "max_stars_repo_path": "MinkowskiEngine/MinkowskiKernelGenerator.py", "max_stars_repo_name": "NNstorm/MinkowskiEngine", "max_stars_repo_head_hexsha": "443b37a58c379b2482b5d160d9e874b356b4bf2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 851, "max_stars_repo_stars_event_min_datetime": "2020-07-09T21:35:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:35:57.000Z", "max_issues_repo_path": "MinkowskiEngine/MinkowskiKernelGenerator.py", "max_issues_repo_name": "NNstorm/MinkowskiEngine", "max_issues_repo_head_hexsha": "443b37a58c379b2482b5d160d9e874b356b4bf2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 301, "max_issues_repo_issues_event_min_datetime": "2020-07-09T21:51:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:23:24.000Z", "max_forks_repo_path": "MinkowskiEngine/MinkowskiKernelGenerator.py", "max_forks_repo_name": "NNstorm/MinkowskiEngine", "max_forks_repo_head_hexsha": "443b37a58c379b2482b5d160d9e874b356b4bf2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 151, "max_forks_repo_forks_event_min_datetime": "2020-07-15T09:22:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T21:32:47.000Z", "avg_line_length": 37.4151898734, "max_line_length": 126, "alphanum_fraction": 0.6073482644, "include": true, "reason": "import numpy", "num_tokens": 3251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.1819797045779331}}
{"text": "# This source code is part of the Biotite package and is distributed\n# under the 3-Clause BSD License. Please see 'LICENSE.rst' for further\n# information.\n\nimport warnings\nimport numpy as np\nfrom .seqtypes import NucleotideSequence, ProteinSequence, GeneralSequence\nfrom .alphabet import LetterAlphabet\nfrom .align.alignment import get_codes\n\n__name__ = \"biotite.sequence\"\n__author__ = \"Maximilian Greil\"\n__all__ = [\"SequenceProfile\"]\n\n# Abbreviations\n_NUC_DNA_ALPH = NucleotideSequence.alphabet_unamb\n_NUC_RNA_ALPH = LetterAlphabet([\"A\", \"C\", \"G\", \"U\"])\n_PROT_ALPH = ProteinSequence.alphabet\n\n\ndef _determine_common_alphabet(alphabets):\n    \"\"\"\n    Determine the common alphabet from a list of alphabets, that\n    extends all alphabets.\n    \"\"\"\n    common_alphabet = alphabets[0]\n    for alphabet in alphabets[1:]:\n        if not common_alphabet.extends(alphabet):\n            if alphabet.extends(common_alphabet):\n                common_alphabet = alphabet\n            else:\n                raise ValueError(\n                    \"There is no common alphabet that extends all alphabets\"\n                )\n    return common_alphabet\n\n\ndef _codes_to_iupac(frequency, codes, maxes, row):\n    \"\"\"\n    Returns IUPAC code for a row of 'symbols' with none, one or\n    multiple maximum positions.\n    \"\"\"\n    if np.sum(frequency) == 0:\n        raise ValueError(\n            f\"There is an empty column in the 'symbols' frequency table. \"\n            f\"This doesn't make sense in context of an alignment. \"\n            f\"Please check the 'symbols' frequency table in row {row}.\"\n        )\n    key = tuple(np.where(frequency == maxes)[0])\n    return codes[key]\n\n\nclass SequenceProfile(object):\n    \"\"\"\n    A :class:`SequenceProfile` object stores information about a\n    sequence profile of aligned sequences.\n    It is possible to calculate and return its consensus sequence.\n\n    This class saves the position frequency matrix\n    (position count matrix) 'symbols' of the occurrences of each\n    alphabet symbol at each position.\n    It also saves the number of gaps at each position in the array\n    'gaps'.\n\n    With :meth:`probability_matrix()` the position probability matrix\n    can be created based on 'symbols' and a pseudocount.\n\n    With :meth:`log_odds_matrix()` the position weight matrix can\n    be created based on the before calculated position probability\n    matrix and the background frequencies.\n\n    With :meth:`from_alignment()` a :class:`SequenceProfile` object can\n    be created from an indefinite number of aligned sequences.\n\n    With :meth:`sequence_probability_from_matrix()` the probability of a\n    sequence can be calculated based on the before calculated position \n    probability matrix of this instance of object SequenceProfile.\n\n    With :meth:`sequence_score_from_matrix()` the score of a sequence\n    can be calculated based on the before calculated position weight\n    matrix of this instance of object SequenceProfile.\n\n    All attributes of this class are publicly accessible.\n\n    Parameters\n    ----------\n    symbols : ndarray, dtype=int, shape=(n,k)\n        This matrix simply saves for each position how often absolutely\n        each symbol is present.\n    gaps : ndarray, dtype=int, shape=n\n        Array which indicates the number of gaps at each position.\n    alphabet : Alphabet, length=k\n        Alphabet of sequences of sequence profile\n\n    Attributes\n    ----------\n    symbols : ndarray, dtype=int, shape=(n,k)\n        This matrix simply saves for each position how often absolutely\n        each symbol is present.\n    gaps : ndarray, dtype=int, shape=n\n        Array which indicates the number of gaps at each position.\n    alphabet : Alphabet, length=k\n        Alphabet of sequences of sequence profile\n    \"\"\"\n\n    def __init__(self, symbols, gaps, alphabet):\n        self._symbols = symbols\n        self._gaps = gaps\n        self._alphabet = alphabet\n\n        if len(alphabet) != symbols.shape[1]:\n            raise ValueError(\n                f\"The given alphabet doesn't have the same length \"\n                f\"({len(alphabet)}) as the number of columns \"\n                f\"({symbols.shape[1]}) in the 'symbols' frequency table.\"\n            )\n\n        if gaps.shape[0] != symbols.shape[0]:\n            raise ValueError(\n                f\"The given 'gaps' position matrix doesn't have the same \"\n                f\"length ({gaps.shape[0]}) as the 'symbols' \"\n                f\"frequency table ({symbols.shape[0]})\"\n            )\n\n    @property\n    def symbols(self):\n        return self._symbols\n\n    @property\n    def gaps(self):\n        return self._gaps\n\n    @property\n    def alphabet(self):\n        return self._alphabet\n\n    @symbols.setter\n    def symbols(self, new_symbols):\n        if not new_symbols.shape == self.symbols.shape:\n            raise ValueError(\n                f\"New ndarray 'symbols' must be of same shape \"\n                f\"{self.symbols.shape} as the old one\"\n            )\n        self._symbols = new_symbols\n\n    @gaps.setter\n    def gaps(self, new_gaps):\n        if not new_gaps.shape == self.gaps.shape:\n            raise ValueError(\n                f\"New ndarray 'gaps' must be of same shape \"\n                f\"{self.gaps.shape} as the old one\"\n            )\n        self._gaps = new_gaps\n\n    def __repr__(self):\n        \"\"\"Represent SequenceProfile as a string for debugging.\"\"\"\n        return f\"SequenceProfile(np.{np.array_repr(self.symbols)}, \" \\\n               f\"np.{np.array_repr(self.gaps)}, Alphabet({self.alphabet}))\"\n\n    def __eq__(self, item):\n        if not isinstance(item, SequenceProfile):\n            return False\n        if not np.array_equal(self.symbols, item.symbols):\n            return False\n        if not np.array_equal(self.gaps, item.gaps):\n            return False\n        if not self.alphabet == item.alphabet:\n            return False\n        return True\n\n    @staticmethod\n    def from_alignment(alignment, alphabet=None):\n        \"\"\"\n        Get an object of :class:`SequenceProfile` from an object of\n        :class:`Alignment`.\n\n        Based on the sequences of the alignment, the SequenceProfile\n        parameters symbols and gaps are calculated.\n\n        Parameters\n        ----------\n        alignment : Alignment\n            An Alignment object to create the SequenceProfile object\n            from.\n        alphabet : bool\n            This alphabet will be used when creating the SequenceProfile\n            object. If no alphabet is selected, the alphabet for this\n            SequenceProfile\n            object will be calculated from the sequences of object\n            Alignment.\n            (Default: None).\n\n        Returns\n        -------\n        profile: SequenceProfile\n            The created SequenceProfile object\n        \"\"\"\n        sequences = get_codes(alignment)\n        if alphabet is None:\n            alphabet = _determine_common_alphabet(\n                [seq.alphabet for seq in alignment.sequences]\n            )\n        else:\n            for alph in (seq.alphabet for seq in alignment.sequences):\n                if not alphabet.extends(alph):\n                    raise ValueError(\n                        f\"The given alphabet is incompatible with a least one \"\n                        \"alphabet of the given sequences\"\n                    )\n        symbols = np.zeros((len(sequences[0]), len(alphabet)), dtype=int)\n        gaps = np.zeros(len(sequences[0]), dtype=int)\n        sequences = np.transpose(sequences)\n        for i in range(len(sequences)):\n            row = np.where(sequences[i, ] == -1, len(alphabet), sequences[i, ])\n            count = np.bincount(row, minlength=len(alphabet) + 1)\n            symbols[i, ] = count[0:len(alphabet)]\n            gaps[i] = count[-1]\n        return SequenceProfile(symbols, gaps, alphabet)\n\n    def to_consensus(self, as_general=False):\n        \"\"\"\n        Get the consensus sequence for this SequenceProfile object.\n\n        Parameters\n        ----------\n        as_general : bool\n            If true, returns consensus sequence as GeneralSequence\n            object.\n            Otherwise, the consensus sequence object type is chosen\n            based on the alphabet of this SequenceProfile object\n            (Default: False).\n\n        Returns\n        -------\n        consensus: Sequence\n            The calculated consensus sequence\n        \"\"\"\n        # https://en.wikipedia.org/wiki/International_Union_of_Pure_and_Applied_Chemistry#Amino_acid_and_nucleotide_base_codes\n        if as_general:\n            return self._general_to_consensus()\n        elif self.alphabet == _NUC_DNA_ALPH:\n            return NucleotideSequence(self._dna_to_consensus())\n        elif self.alphabet == _NUC_RNA_ALPH:\n            return NucleotideSequence(self._rna_to_consensus())\n        elif self.alphabet == _PROT_ALPH:\n            return self._prot_to_consensus()\n        return self._general_to_consensus()\n\n    def _dna_to_consensus(self):\n        codes = {\n            (0,): 'A', (1,): 'C', (2,): 'G', (3,): 'T',\n            (0, 2): 'R', (1, 3): 'Y', (1, 2): 'S', (0, 3): 'W', (2, 3): 'K', (0, 1): 'M',\n            (1, 2, 3): 'B', (0, 2, 3): 'D', (0, 1, 3): 'H', (0, 1, 2): 'V',\n            (0, 1, 2, 3): 'N'\n        }\n        consensus = \"\"\n        maxes = np.max(self.symbols, axis=1)\n        for i in range(len(self.symbols)):\n            consensus += _codes_to_iupac(self.symbols[i, :], codes, maxes[i], i)\n        return consensus\n\n    def _rna_to_consensus(self):\n        codes = {\n            (0,): 'A', (1,): 'C', (2,): 'G', (3,): 'U',\n            (0, 2): 'R', (1, 3): 'Y', (1, 2): 'S', (0, 3): 'W', (2, 3): 'K', (0, 1): 'M',\n            (1, 2, 3): 'B', (0, 2, 3): 'D', (0, 1, 3): 'H', (0, 1, 2): 'V',\n            (0, 1, 2, 3): 'N'\n        }\n        consensus = \"\"\n        maxes = np.max(self.symbols, axis=1)\n        for i in range(len(self.symbols)):\n            consensus += _codes_to_iupac(self.symbols[i, :], codes, maxes[i], i)\n        return consensus\n\n    def _prot_to_consensus(self):\n        \"\"\"\n        In case there is more than one symbol with the same maximal\n        occurrences, the alphabetically sorted first symbol will be\n        taken for the consensus sequence.\n        \"\"\"\n        consensus = ProteinSequence()\n        consensus.code = np.argmax(self.symbols, axis=1)\n        consensus.code = np.where(\n            np.sum(self.symbols, axis=1) == 0, 23, consensus.code\n        )  # _PROT_ALPH[23] = 'X'\n        return consensus\n\n    def _general_to_consensus(self):\n        \"\"\"\n        In case there is more than one symbol with the same maximal\n        occurrences, the alphabetically sorted first symbol will be\n        taken for the consensus sequence.\n        In case the sum of occurrences of all symbols at a position is\n        zero, the alphabetically sorted first symbol will be taken for\n        the consensus sequence.\n        \"\"\"\n        consensus = GeneralSequence(self.alphabet)\n        consensus.code = np.argmax(self.symbols, axis=1)\n        return consensus\n\n    def probability_matrix(self, pseudocount=0):\n        r\"\"\"\n        Calculate the position probability matrix (PPM) based on\n        'symbols' and the given pseudocount.\n        This new matrix has the same shape as 'symbols'.\n\n        .. math::\n\n            P(S) = \\frac {C_S + \\frac{c_p}{k}} {\\sum_{i} C_i + c_p}\n        \n        :math:`S`: The symbol.\n\n        :math:`C_S`: The count of symbol :math:`S` at the sequence\n        position.\n\n        :math:`c_p`: The pseudocount.\n\n        :math:`k`: Length of the alphabet.\n\n        Parameters\n        ----------\n        pseudocount: int, optional\n            Amount added to the number of observed cases in order to\n            change the expected probability of the PPM.\n            (Default: 0)\n\n        Returns\n        -------\n        ppm: ndarray, dtype=float, shape=(n,k)\n            The calculated the position probability matrix.\n        \"\"\"\n        if pseudocount < 0:\n            raise ValueError(\n                f\"Pseudocount can not be smaller than zero.\"\n            )\n        return (self.symbols + pseudocount / self.symbols.shape[1]) / \\\n               (np.sum(self.symbols, axis=1)[:, np.newaxis] + pseudocount)\n\n    def log_odds_matrix(self, background_frequencies=None, pseudocount=0):\n        r\"\"\"\n        Calculate the position weight matrix (PWM) based on the\n        position probability matrix (PPM) (with given pseudocount) and\n        background_frequencies.\n        This new matrix has the same shape as 'symbols'.\n\n        .. math::\n\n            W(S) = \\log_2 \\left( \\frac{P(S)}{B_S} \\right)\n        \n        :math:`S`: The symbol.\n\n        :math:`P(S)`: The probability of symbol :math:`S` at the\n        sequence position.\n\n        :math:`c_p`: The background frequency of symbol :math:`S`.\n\n        Parameters\n        ----------\n        pseudocount: int, optional\n            Amount added to the number of observed cases in order to change\n            the expected probability of the PPM.\n            (Default: 0)\n        background_frequencies: ndarray, shape=(k,), dtype=float, optional\n            The background frequencies for each symbol in the alphabet.\n            By default, a uniform distribution is assumed.\n            \n        Returns\n        -------\n        pwm: ndarray, dtype=float, shape=(n,k)\n            The calculated the position weight matrix.\n        \"\"\"\n        if background_frequencies is None:\n            background_frequencies = 1 / len(self.alphabet)\n        ppm = self.probability_matrix(pseudocount=pseudocount)\n        # Catch warning that appears, if a symbol is missing at any\n        # position in the profile\n        with warnings.catch_warnings():\n            warnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n            return np.log2(ppm / background_frequencies)\n\n    def sequence_probability(self, sequence, pseudocount=0):\n        r\"\"\"\n        Calculate probability of a sequence based on the\n        position probability matrix (PPM).\n\n        The sequence probability is the product of the probability of \n        the respective symbol over all sequence positions.\n\n        Parameters\n        ----------\n        sequence : Sequence\n           The input sequence.\n        pseudocount: int, optional\n            Amount added to the number of observed cases in order to change\n            the expected probability of the PPM.\n            (Default: 0)\n\n        Returns\n        -------\n        probability: float\n           The calculated probability for the input sequence based on\n           the PPM.\n        \"\"\"\n        ppm = self.probability_matrix(pseudocount=pseudocount)\n        if len(sequence) != len(ppm):\n            raise ValueError(\n                f\"The given sequence has a different length ({len(sequence)}) than \"\n                f\"the position probability matrix ({len(ppm)}).\"\n            )\n        if not ppm.shape == self.symbols.shape:\n            raise ValueError(\n                f\"Position probability matrix {ppm.shape} must be of same shape \"\n                f\"as 'symbols' {self.symbols.shape}\"\n            )\n        return np.prod(ppm[np.arange(len(sequence)), sequence.code])\n\n    def sequence_score(self, sequence, background_frequencies=None, pseudocount=0):\n        \"\"\"\n        Calculate score of a sequence based on the\n        position weight matrix (PWM).\n\n        The score is the sum of weights (log-odds scores) of \n        the respective symbol over all sequence positions.\n\n        Parameters\n        ----------\n        sequence : Sequence\n           The input sequence.\n        pseudocount: int, optional\n            Amount added to the number of observed cases in order to change\n            the expected probability of the PPM.\n            (Default: 0)\n        background_frequencies: ndarray, shape=(k,), dtype=float, optional\n            The background frequencies for each symbol in the alphabet.\n            By default a uniform distribution is assumed.\n\n        Returns\n        -------\n        score: float\n           The calculated score for the input sequence based on\n           the PWM.\n        \"\"\"\n        if background_frequencies is None:\n            background_frequencies = 1 / len(self.alphabet)\n        pwm = self.log_odds_matrix(background_frequencies=background_frequencies, pseudocount=pseudocount)\n        if len(sequence) != len(pwm):\n            raise ValueError(\n                f\"The given sequence has a different length ({len(sequence)}) than \"\n                f\"the position weight matrix ({len(pwm)}).\"\n            )\n        if not pwm.shape == self.symbols.shape:\n            raise ValueError(\n                f\"Position weight matrix {pwm.shape} must be of same shape \"\n                f\"as 'symbols' {self.symbols.shape}\"\n            )\n        return np.sum(pwm[np.arange(len(sequence)), sequence.code])\n", "meta": {"hexsha": "1a140e1f900a4b11fb40fa6b7763be85da380673", "size": 16813, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/biotite/sequence/profile.py", "max_stars_repo_name": "alex123012/biotite", "max_stars_repo_head_hexsha": "5702c6eb4e9a577954177788815b0f517c111c12", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 208, "max_stars_repo_stars_event_min_datetime": "2018-04-20T15:59:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T07:47:12.000Z", "max_issues_repo_path": "src/biotite/sequence/profile.py", "max_issues_repo_name": "alex123012/biotite", "max_issues_repo_head_hexsha": "5702c6eb4e9a577954177788815b0f517c111c12", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 121, "max_issues_repo_issues_event_min_datetime": "2017-11-15T14:52:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T16:31:41.000Z", "max_forks_repo_path": "src/biotite/sequence/profile.py", "max_forks_repo_name": "alex123012/biotite", "max_forks_repo_head_hexsha": "5702c6eb4e9a577954177788815b0f517c111c12", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 49, "max_forks_repo_forks_event_min_datetime": "2018-07-19T09:06:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T17:21:34.000Z", "avg_line_length": 36.7899343545, "max_line_length": 126, "alphanum_fraction": 0.5991792066, "include": true, "reason": "import numpy", "num_tokens": 3779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.18197970457793308}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n\n:copyright:\n    Nienke Brinkman (nienke.brinkman@erdw.ethz.ch), 2020\n:license:\n    None\n\"\"\"\n\nimport obspy\nimport instaseis\nfrom typing import Union as _Union\nimport numpy as np\n\nimport SS_MTI.SourceTimeFunction as _STF\n\n\ndef make_GF(\n    or_time: obspy.UTCDateTime,\n    lat_src: float,\n    lon_src: float,\n    depth: float,\n    distance: float,\n    rec: instaseis.Receiver,\n    db: instaseis.open_db,\n    dt: float,\n    comp: str,\n    tstar: _Union[float, str] = None,\n    LQT: bool = False,\n    inc: float = None,\n    baz: float = None,\n    M0: float = 1e14,\n) -> obspy.Stream:\n    \"\"\"\n    Create stream of different source components\n    :param or_time: origin time\n    :param lat_src: source latitude\n    :param lon_src: source longitude\n    :param depth: depth of event in km\n    :param distance: the epicentral distance in degrees\n    :param rec: instaseis.Receiver object of the single station\n    :param db: instaseis database\n    :param dt: timestep\n    :param comp: component\n    :param tstar: tstar value \n    :param LQT: set to true if component system is LQT\n    :param inc: inclination angle in degrees (needed when LQT = TRUE)\n    :param baz: backazimuth angle in degrees (needed when LQT = TRUE)\n    :param M0: scalar moment\n    \"\"\"\n\n    if tstar is not None and not isinstance(tstar, str):\n        stf_len_sec = 30.0\n        stf = _STF.stf_tstar(\n            tstar=tstar, dt=db.info.dt, npts=int(stf_len_sec / db.info.dt), nfft=db.info.nfft\n        )[0]\n        # from obspy.signal.filter import highpass, lowpass\n\n        # stf = highpass(stf, df=1 / db.info.dt, freq=0.1, corners=4, zerophase=False)\n        # stf = highpass(stf, df=1 / db.info.dt, freq=0.1, corners=4, zerophase=False)\n        # stf = lowpass(stf, df=1 / db.info.dt, freq=0.7, corners=4, zerophase=False)\n        # stf = lowpass(stf, df=1 / db.info.dt, freq=0.7, corners=4, zerophase=False)\n    elif isinstance(tstar, str):\n        stf = _STF.Create_stf_from_file(tstar, db.info.dt)\n    mts = [\n        [M0, 0.0, 0.0, 0.0, 0.0, 0.0],\n        [0.0, M0, 0.0, 0.0, 0.0, 0.0],\n        [0.0, 0.0, M0, 0.0, 0.0, 0.0],\n        [0.0, 0.0, 0.0, M0, 0.0, 0.0],\n        [0.0, 0.0, 0.0, 0.0, M0, 0.0],\n        [0.0, 0.0, 0.0, 0.0, 0.0, M0],\n    ]\n\n    st = obspy.Stream()\n\n    for mt in mts:\n        src = instaseis.Source(\n            latitude=lat_src,\n            longitude=lon_src,\n            depth_in_m=depth * 1e3,\n            origin_time=or_time,\n            m_rr=mt[0],\n            m_tt=mt[1],\n            m_pp=mt[2],\n            m_rt=mt[3],\n            m_rp=mt[4],\n            m_tp=mt[5],\n        )\n\n        reconvolve_stf = False\n        remove_source_shift = True\n        if tstar is not None and not isinstance(tstar, str):\n            reconvolve_stf = True\n            remove_source_shift = False\n            src.set_sliprate(stf, dt=db.info.dt)\n            # src.set_sliprate_lp(dt=db.info.dt, nsamp=50, freq=0.7)\n        elif isinstance(tstar, str):\n            reconvolve_stf = True\n            remove_source_shift = False\n            src.set_sliprate(stf, dt=db.info.dt, normalize=True)\n\n        if LQT:\n            st_rot = db.get_seismograms(\n                src,\n                rec,\n                dt=dt,\n                components=\"ZNE\",\n                kind=\"displacement\",\n                reconvolve_stf=reconvolve_stf,\n                remove_source_shift=remove_source_shift,\n            )\n            st_rot.rotate(method=\"ZNE->LQT\", back_azimuth=baz, inclination=inc)\n            tr_rot = st_rot.select(channel=\"BX\" + comp[0])[0]\n            st += tr_rot\n        else:\n            st += db.get_seismograms(\n                src,\n                rec,\n                dt=dt,\n                components=comp,\n                kind=\"displacement\",\n                reconvolve_stf=reconvolve_stf,\n                remove_source_shift=remove_source_shift,\n            )[0]\n    return st\n\n\ndef convert_SDR(strike: float, dip: float, rake: float, M0: float = 1e14):\n    phi = np.deg2rad(strike)\n    delta = np.deg2rad(dip)\n    lambd = np.deg2rad(rake)\n\n    m_rr = (np.sin(2.0 * delta) * np.sin(lambd)) * M0\n\n    m_pp = (\n        np.sin(delta) * np.cos(lambd) * np.sin(2.0 * phi)\n        - np.sin(2.0 * delta) * np.cos(phi) ** 2.0 * np.sin(lambd)\n    ) * M0\n\n    m_tt = (\n        -np.sin(delta) * np.cos(lambd) * np.sin(2.0 * phi)\n        - np.sin(2.0 * delta) * np.sin(phi) ** 2.0 * np.sin(lambd)\n    ) * M0\n\n    m_rp = (\n        -np.cos(phi) * np.sin(lambd) * np.cos(2.0 * delta)\n        + np.cos(delta) * np.cos(lambd) * np.sin(phi)\n    ) * M0\n\n    m_rt = (\n        -np.sin(lambd) * np.sin(phi) * np.cos(2.0 * delta)\n        - np.cos(delta) * np.cos(lambd) * np.cos(phi)\n    ) * M0\n\n    m_tp = (\n        -np.sin(delta) * np.cos(lambd) * np.cos(2.0 * phi)\n        - np.sin(2.0 * delta) * np.sin(2.0 * phi) * np.sin(lambd) / 2.0\n    ) * M0\n\n    MT = [m_rr, m_tt, m_pp, m_rt, m_rp, m_tp]\n    return MT\n\n\ndef from_GF(st_in: obspy.Stream, focal_mech: [float], M0: float):\n    \"\"\" Generate synthetic waveforms \n    :param st_in: \n    :param focal_mech: strike,dip,rake or m_rr, m_pp, m_tt, m_rp, m_rt, m_tp\n    :param M0: scalar moment\n    \"\"\"\n\n    if len(focal_mech) == 3:\n        focal_mech = convert_SDR(focal_mech[0], focal_mech[1], focal_mech[2], M0)\n\n    m_rr = focal_mech[0]  # / M0\n    m_tt = focal_mech[1]  # / M0\n    m_pp = focal_mech[2]  # / M0\n    m_rt = focal_mech[3]  # / M0\n    m_rp = focal_mech[4]  # / M0\n    m_tp = focal_mech[5]  # / M0\n\n    data = (\n        st_in[0].data * m_rr\n        + st_in[1].data * m_tt\n        + st_in[2].data * m_pp\n        + st_in[3].data * m_rt\n        + st_in[4].data * m_rp\n        + st_in[5].data * m_tp\n    )\n\n    tr = st_in[0].copy()\n    tr.data = data\n\n    return tr\n\n\ndef from_GF_get_G(st_in: obspy.Stream, az: float, comp: str):\n    m_rr = st_in[0].data\n    m_tt = st_in[1].data\n    m_pp = st_in[2].data\n    m_rt = st_in[3].data\n    m_rp = st_in[4].data\n    m_tp = st_in[5].data\n\n    m1 = -1.0 * m_tp\n    m2 = 1.0 * m_tt + -1.0 * m_pp\n    m3 = -1.0 * m_rp\n    m4 = 1.0 * m_rt\n    m6 = 1.0 * m_rr + 1.0 * m_tt + 1.0 * m_pp\n    cl = 2.0 * m_rr + -1.0 * m_tt + -1.0 * m_pp\n\n    # if ba < 0 or ba > 360:\n    #     raise ValueError(\"Back Azimuth should be between 0 and 360 degrees.\")\n    # baz = np.deg2rad(360.0 - ba)\n    # N = -T * np.sin(baz) - R * np.cos(baz)\n    # E = -T * np.cos(baz) + R * np.sin(baz)\n\n    if comp == \"Z\" or comp == \"R\" or comp == \"L\" or comp == \"Q\":\n        SS = m2\n        DS = m4\n        DD = cl\n        EP = m6  # Explosion term\n\n        G = np.zeros((len(SS), 5))\n        G[:, 0] = SS * (0.5) * np.cos(2 * np.deg2rad(az)) - DD / 2.0\n        G[:, 1] = -SS * (0.5) * np.cos(2 * np.deg2rad(az)) - DD / 2.0\n        G[:, 2] = SS * np.sin(2 * np.deg2rad(az))\n        G[:, 3] = -DS * np.cos(np.deg2rad(az))\n        G[:, 4] = -DS * np.sin(np.deg2rad(az))\n\n    elif comp == \"T\":\n        SS = m1\n        DS = m3\n\n        G = np.zeros((len(SS), 5))\n        G[:, 0] = -SS * (0.5) * np.sin(2 * np.deg2rad(az))\n        G[:, 1] = SS * (0.5) * np.sin(2 * np.deg2rad(az))\n        G[:, 2] = SS * np.cos(2 * np.deg2rad(az))\n        G[:, 3] = DS * np.sin(np.deg2rad(az))\n        G[:, 4] = -DS * np.cos(np.deg2rad(az))\n    else:\n        raise ValueError(\"Component is not correctly specified\")\n    return G\n\n", "meta": {"hexsha": "508842350dea3b688f103c5f84fbdb20491a5052", "size": 7303, "ext": "py", "lang": "Python", "max_stars_repo_path": "SS_MTI/GreensFunctions.py", "max_stars_repo_name": "nienkebrinkman/SS_MTI", "max_stars_repo_head_hexsha": "2632214f7df9caaa53d33432193ba0602470d21a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SS_MTI/GreensFunctions.py", "max_issues_repo_name": "nienkebrinkman/SS_MTI", "max_issues_repo_head_hexsha": "2632214f7df9caaa53d33432193ba0602470d21a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SS_MTI/GreensFunctions.py", "max_forks_repo_name": "nienkebrinkman/SS_MTI", "max_forks_repo_head_hexsha": "2632214f7df9caaa53d33432193ba0602470d21a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8081632653, "max_line_length": 93, "alphanum_fraction": 0.5299192113, "include": true, "reason": "import numpy", "num_tokens": 2554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.31069438959712015, "lm_q1q2_score": 0.18178765045333337}}
{"text": "\"\"\"\nIntegrator classes to deal with interpolation and integration of input spectral\nbins.  Currently only supports Cloudy and APEC-style data.\n\n\n\n\"\"\"\n\n#-----------------------------------------------------------------------------\n# Copyright (c) 2013, yt Development Team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n#-----------------------------------------------------------------------------\n\nimport h5py\nimport numpy as np\nimport os\n\nfrom yt.funcs import \\\n     download_file, \\\n     mylog, \\\n     only_on_root\n\nfrom yt.utilities.exceptions import YTFieldNotFound\nfrom yt.utilities.exceptions import YTException\nfrom yt.utilities.linear_interpolators import \\\n    UnilinearFieldInterpolator, BilinearFieldInterpolator\nfrom yt.utilities.physical_constants import \\\n    hcgs, mp\nfrom yt.units.yt_array import YTArray, YTQuantity\nfrom yt.utilities.physical_ratios import \\\n    primordial_H_mass_fraction, erg_per_keV\n\nxray_data_version = 1\n\ndef _get_data_file(data_file=None):\n    if data_file is None:\n        data_file = \"cloudy_emissivity.h5\"\n    data_url = \"http://yt-project.org/data\"\n    if \"YT_DEST\" in os.environ and \\\n      os.path.isdir(os.path.join(os.environ[\"YT_DEST\"], \"data\")):\n        data_dir = os.path.join(os.environ[\"YT_DEST\"], \"data\")\n    else:\n        data_dir = \".\"\n    data_path = os.path.join(data_dir, data_file)\n    if not os.path.exists(data_path):\n        mylog.info(\"Attempting to download supplementary data from %s to %s.\" % \n                   (data_url, data_dir))\n        fn = download_file(os.path.join(data_url, data_file), data_path)\n        if fn != data_path:\n            raise RuntimeError(\"Failed to download supplementary data.\")\n    return data_path\n\nclass EnergyBoundsException(YTException):\n    def __init__(self, lower, upper):\n        self.lower = lower\n        self.upper = upper\n\n    def __str__(self):\n        return \"Energy bounds are %e to %e keV.\" % \\\n          (self.lower, self.upper)\n\nclass ObsoleteDataException(YTException):\n    def __str__(self):\n        return \"X-ray emissivity data is out of date.\\n\" + \\\n               \"Download the latest data from http://yt-project.org/data/cloudy_emissivity.h5 and move it to %s.\" % \\\n          os.path.join(os.environ[\"YT_DEST\"], \"data\", \"cloudy_emissivity.h5\")\n          \nclass EmissivityIntegrator(object):\n    r\"\"\"Class for making X-ray emissivity fields with hdf5 data tables \n    from Cloudy.\n    \n    Initialize an EmissivityIntegrator object.\n\n    Parameters\n    ----------\n    filename: string, default None\n        Path to data file containing emissivity values.  If None,\n        a file called \"cloudy_emissivity.h5\" is used, for photoionized\n        plasmas. A second option, for collisionally ionized plasmas, is\n        in the file \"apec_emissivity.h5\", available at http://yt-project.org/data.\n        These files contain emissivity tables for primordial elements and\n        for metals at solar metallicity for the energy range 0.1 to 100 keV.\n        Default: None.\n        \n    \"\"\"\n    def __init__(self, filename=None):\n\n        default_filename = False\n        if filename is None:\n            filename = _get_data_file()\n            default_filename = True\n\n        if not os.path.exists(filename):\n            mylog.warning(\"File %s does not exist, will attempt to find it.\" % filename)\n            filename = _get_data_file(data_file=filename)\n        only_on_root(mylog.info, \"Loading emissivity data from %s.\" % filename)\n        in_file = h5py.File(filename, \"r\")\n        if \"info\" in in_file.attrs:\n            only_on_root(mylog.info, in_file.attrs[\"info\"])\n        if default_filename and \\\n          in_file.attrs[\"version\"] < xray_data_version:\n            raise ObsoleteDataException()\n        else:\n            only_on_root(mylog.info, \"X-ray emissivity data version: %s.\" % \\\n                         in_file.attrs[\"version\"])\n\n        for field in [\"emissivity_primordial\", \"emissivity_metals\",\n                      \"log_nH\", \"log_T\", \"log_E\"]:\n            if field in in_file:\n                setattr(self, field, in_file[field][:])\n        in_file.close()\n\n        E_diff = np.diff(self.log_E)\n        self.E_bins = \\\n                  YTArray(np.power(10, np.concatenate([self.log_E[:-1] - 0.5 * E_diff,\n                                                      [self.log_E[-1] - 0.5 * E_diff[-1],\n                                                       self.log_E[-1] + 0.5 * E_diff[-1]]])),\n                          \"keV\")\n        self.dnu = (np.diff(self.E_bins)/hcgs).in_units(\"Hz\")\n\n    def get_interpolator(self, data, e_min, e_max):\n        e_min = YTQuantity(e_min, \"keV\")\n        e_max = YTQuantity(e_max, \"keV\")\n        if (e_min - self.E_bins[0]) / e_min < -1e-3 or \\\n          (e_max - self.E_bins[-1]) / e_max > 1e-3:\n            raise EnergyBoundsException(self.E_bins[0], self.E_bins[-1])\n        e_is, e_ie = np.digitize([e_min, e_max], self.E_bins)\n        e_is = np.clip(e_is - 1, 0, self.E_bins.size - 1)\n        e_ie = np.clip(e_ie, 0, self.E_bins.size - 1)\n\n        my_dnu = self.dnu[e_is: e_ie].copy()\n        # clip edge bins if the requested range is smaller\n        my_dnu[0] -= ((e_min - self.E_bins[e_is])/hcgs).in_units(\"Hz\")\n        my_dnu[-1] -= ((self.E_bins[e_ie] - e_max)/hcgs).in_units(\"Hz\")\n\n        interp_data = (data[..., e_is:e_ie] * my_dnu).sum(axis=-1)\n        if len(data.shape) == 2:\n            emiss = UnilinearFieldInterpolator(np.log10(interp_data),\n                                               [self.log_T[0],  self.log_T[-1]],\n                                               \"log_T\", truncate=True)\n        else:\n            emiss = BilinearFieldInterpolator(np.log10(interp_data),\n                                              [self.log_nH[0], self.log_nH[-1],\n                                               self.log_T[0],  self.log_T[-1]],\n                                              [\"log_nH\", \"log_T\"], truncate=True)\n\n        return emiss\n\ndef add_xray_emissivity_field(ds, e_min, e_max,\n                              filename=None,\n                              with_metals=True,\n                              constant_metallicity=None):\n    r\"\"\"Create X-ray emissivity fields for a given energy range.\n\n    Parameters\n    ----------\n    e_min: float\n        the minimum energy in keV for the energy band.\n    e_min: float\n        the maximum energy in keV for the energy band.\n    filename: string, optional\n        Path to data file containing emissivity values.  If None,\n        a file called \"cloudy_emissivity.h5\" is used, for photoionized\n        plasmas. A second option, for collisionally ionized plasmas, is\n        in the file \"apec_emissivity.h5\", available at http://yt-project.org/data.\n        These files contain emissivity tables for primordial elements and\n        for metals at solar metallicity for the energy range 0.1 to 100 keV.\n        Default: None.\n    with_metals: bool, optional\n        If True, use the metallicity field to add the contribution from \n        metals.  If False, only the emission from H/He is considered.\n        Default: True.\n    constant_metallicity: float, optional\n        If specified, assume a constant metallicity for the emission \n        from metals.  The *with_metals* keyword must be set to False \n        to use this.\n        Default: None.\n\n    This will create three fields:\n\n    \"xray_emissivity_{e_min}_{e_max}_keV\" (erg s^-1 cm^-3)\n    \"xray_luminosity_{e_min}_{e_max}_keV\" (erg s^-1)\n    \"xray_photon_emissivity_{e_min}_{e_max}_keV\" (photons s^-1 cm^-3)\n\n    Examples\n    --------\n\n    >>> from yt.mods import *\n    >>> from yt.analysis_modules.spectral_integrator.api import *\n    >>> ds = load(dataset)\n    >>> add_xray_emissivity_field(ds, 0.5, 2)\n    >>> p = ProjectionPlot(ds, 'x', \"xray_emissivity_0.5_2_keV\")\n    >>> p.save()\n\n    \"\"\"\n\n    if with_metals:\n        try:\n            ds._get_field_info(\"metal_density\")\n        except YTFieldNotFound:\n            raise RuntimeError(\"Your dataset does not have a \\\"metal_density\\\" field! \" +\n                               \"Perhaps you should specify a constant metallicity?\")\n\n    my_si = EmissivityIntegrator(filename=filename)\n\n    em_0 = my_si.get_interpolator(my_si.emissivity_primordial, e_min, e_max)\n    em_Z = None\n    if with_metals or constant_metallicity is not None:\n        em_Z = my_si.get_interpolator(my_si.emissivity_metals, e_min, e_max)\n\n    energy_erg = np.power(10, my_si.log_E) * erg_per_keV\n    emp_0 = my_si.get_interpolator((my_si.emissivity_primordial[..., :] / energy_erg),\n                                   e_min, e_max)\n    emp_Z = None\n    if with_metals or constant_metallicity is not None:\n        emp_Z = my_si.get_interpolator((my_si.emissivity_metals[..., :] / energy_erg),\n                                       e_min, e_max)\n\n    try:\n        ds._get_field_info(\"H_number_density\")\n    except YTFieldNotFound:\n        mylog.warning(\"Could not find a field for \\\"H_number_density\\\". Assuming primordial H \" +\n                      \"mass fraction.\")\n        def _nh(field, data):\n            return primordial_H_mass_fraction*data[\"gas\",\"density\"]/mp\n        ds.add_field((\"gas\", \"H_number_density\"), function=_nh, units=\"cm**-3\")\n\n    def _emissivity_field(field, data):\n        dd = {\"log_nH\" : np.log10(data[\"gas\",\"H_number_density\"]),\n              \"log_T\"   : np.log10(data[\"gas\",\"temperature\"])}\n\n        my_emissivity = np.power(10, em_0(dd))\n        if em_Z is not None:\n            if with_metals:\n                my_Z = data[\"gas\",\"metallicity\"]\n            elif constant_metallicity is not None:\n                my_Z = constant_metallicity\n            my_emissivity += my_Z * np.power(10, em_Z(dd))\n\n        return data[\"gas\",\"H_number_density\"]**2 * \\\n            YTArray(my_emissivity, \"erg*cm**3/s\")\n\n    emiss_name = \"xray_emissivity_%s_%s_keV\" % (e_min, e_max)\n    ds.add_field((\"gas\", emiss_name), function=_emissivity_field,\n                 display_name=r\"\\epsilon_{X}\\ (%s-%s\\ keV)\" % (e_min, e_max),\n                 units=\"erg/cm**3/s\")\n\n    def _luminosity_field(field, data):\n        return data[emiss_name] * data[\"cell_volume\"]\n\n    lum_name = \"xray_luminosity_%s_%s_keV\" % (e_min, e_max)\n    ds.add_field((\"gas\", lum_name), function=_luminosity_field,\n                 display_name=r\"\\rm{L}_{X}\\ (%s-%s\\ keV)\" % (e_min, e_max),\n                 units=\"erg/s\")\n\n    def _photon_emissivity_field(field, data):\n        dd = {\"log_nH\" : np.log10(data[\"gas\",\"H_number_density\"]),\n              \"log_T\"   : np.log10(data[\"gas\",\"temperature\"])}\n\n        my_emissivity = np.power(10, emp_0(dd))\n        if emp_Z is not None:\n            if with_metals:\n                my_Z = data[\"gas\",\"metallicity\"]\n            elif constant_metallicity is not None:\n                my_Z = constant_metallicity\n            my_emissivity += my_Z * np.power(10, emp_Z(dd))\n\n        return data[\"gas\",\"H_number_density\"]**2 * \\\n            YTArray(my_emissivity, \"photons*cm**3/s\")\n\n    phot_name = \"xray_photon_emissivity_%s_%s_keV\" % (e_min, e_max)\n    ds.add_field((\"gas\", phot_name), function=_photon_emissivity_field,\n                 display_name=r\"\\epsilon_{X}\\ (%s-%s\\ keV)\" % (e_min, e_max),\n                 units=\"photons/cm**3/s\")\n\n    return emiss_name, lum_name, phot_name\n", "meta": {"hexsha": "95bf4ecbc8b8e5d211587a53f5f7b7a753d7bc82", "size": 11338, "ext": "py", "lang": "Python", "max_stars_repo_path": "yt/analysis_modules/spectral_integrator/spectral_frequency_integrator.py", "max_stars_repo_name": "danielgrassinger/yt_new_frontend", "max_stars_repo_head_hexsha": "5f91d2fb8721c4c5da0af543a6256ed979cd9fc9", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "yt/analysis_modules/spectral_integrator/spectral_frequency_integrator.py", "max_issues_repo_name": "danielgrassinger/yt_new_frontend", "max_issues_repo_head_hexsha": "5f91d2fb8721c4c5da0af543a6256ed979cd9fc9", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-04-05T22:30:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-05T22:30:14.000Z", "max_forks_repo_path": "yt/analysis_modules/spectral_integrator/spectral_frequency_integrator.py", "max_forks_repo_name": "danielgrassinger/yt_new_frontend", "max_forks_repo_head_hexsha": "5f91d2fb8721c4c5da0af543a6256ed979cd9fc9", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-05T05:51:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-05T05:51:09.000Z", "avg_line_length": 40.4928571429, "max_line_length": 117, "alphanum_fraction": 0.5949020991, "include": true, "reason": "import numpy", "num_tokens": 2830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.3106943832145539, "lm_q1q2_score": 0.18178764671888636}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport math\n\nSTEP_TIME = 0.1\nL, W = 4.0, 1.8\nLANE_WIDTH = 3.75\nLANE_NUMBER = 3\nCROSSROAD_SIZE = 50\n\n\nVEHICLE_MODE_DICT = dict(\n    #left=dict(dl=2, du=2, ud=2, ul=2),\n    left  = dict(dl=1, du=0, ud=2, ul=0),\n                         straight=dict(dl=1, du=2, ud=2, ru=2, ur=2),\n                         right=dict(dr=1, ur=2, lr=2))\n\n\ndef dict2flat(inp):\n    out = []\n    for key, val in inp.items():\n        out.extend([key]*val)\n    return out\n\n\ndef dict2num(inp):\n    out = 0\n    for _, val in inp.items():\n        out += val\n    return out\n\n\nVEH_NUM = dict(left=dict2num(VEHICLE_MODE_DICT['left']),\n               straight=dict2num(VEHICLE_MODE_DICT['straight']),\n               right=dict2num(VEHICLE_MODE_DICT['right']))\n\nVEHICLE_MODE_LIST = dict(left=dict2flat(VEHICLE_MODE_DICT['left']),\n                         straight=dict2flat(VEHICLE_MODE_DICT['straight']),\n                         right=dict2flat(VEHICLE_MODE_DICT['right']))\n# Things related to lane number: static path generation (which further influences obs initialization),\n# observation formulation (especially other vehicles selection and number), rewards formulation\n# other vehicle prediction\n# feasibility judgement\n# the sumo files, obviously,\n# the render func,\n# it is hard to unify them using one set of code, better be a case-by-case setting.\n\nROUTE2MODE = {('1o', '2i'): 'dr', ('1o', '3i'): 'du', ('1o', '4i'): 'dl',\n              ('2o', '1i'): 'rd', ('2o', '3i'): 'ru', ('2o', '4i'): 'rl',\n              ('3o', '1i'): 'ud', ('3o', '2i'): 'ur', ('3o', '4i'): 'ul',\n              ('4o', '1i'): 'ld', ('4o', '2i'): 'lr', ('4o', '3i'): 'lu'}\n\nMODE2TASK = {'dr': 'right', 'du': 'straight', 'dl': 'left',\n             'rd': 'left', 'ru': 'right', 'rl': ' straight',\n             'ud': 'straight', 'ur': 'left', 'ul': 'right',\n             'ld': 'right', 'lr': 'straight', 'lu': 'left'}\n\n\ndef judge_feasible(orig_x, orig_y, task):  # map dependant\n    def is_in_straight_before1(orig_x, orig_y):\n        return 0 < orig_x < LANE_WIDTH and orig_y <= -CROSSROAD_SIZE / 2\n\n    def is_in_straight_before2(orig_x, orig_y):\n        return LANE_WIDTH < orig_x < LANE_WIDTH * 2 and orig_y <= -CROSSROAD_SIZE / 2\n\n    def is_in_straight_before3(orig_x, orig_y):\n        return LANE_WIDTH * 2 < orig_x < LANE_WIDTH * 3 and orig_y <= -CROSSROAD_SIZE / 2\n\n    def is_in_straight_after(orig_x, orig_y):\n        return 0 < orig_x < LANE_WIDTH * LANE_NUMBER and orig_y >= CROSSROAD_SIZE / 2\n\n    def is_in_left(orig_x, orig_y):\n        return 0 < orig_y < LANE_WIDTH * LANE_NUMBER and orig_x < -CROSSROAD_SIZE / 2\n\n    def is_in_right(orig_x, orig_y):\n        return -LANE_WIDTH * LANE_NUMBER < orig_y < 0 and orig_x > CROSSROAD_SIZE / 2\n\n    def is_in_middle(orig_x, orig_y):\n        return True if -CROSSROAD_SIZE / 2 < orig_y < CROSSROAD_SIZE / 2 and -CROSSROAD_SIZE / 2 < orig_x < CROSSROAD_SIZE / 2 else False\n\n    if task == 'left':\n        return True if is_in_straight_before1(orig_x, orig_y) or is_in_left(orig_x, orig_y) \\\n                       or is_in_middle(orig_x, orig_y) else False\n    elif task == 'straight':\n        return True if is_in_straight_before2(orig_x, orig_y) or is_in_straight_after(\n            orig_x, orig_y) or is_in_middle(orig_x, orig_y) else False\n    else:\n        assert task == 'right'\n        return True if is_in_straight_before3(orig_x, orig_y) or is_in_right(orig_x, orig_y) \\\n                       or is_in_middle(orig_x, orig_y) else False\n\n\ndef shift_coordination(orig_x, orig_y, coordi_shift_x, coordi_shift_y):\n    '''\n    :param orig_x: original x\n    :param orig_y: original y\n    :param coordi_shift_x: coordi_shift_x along x axis\n    :param coordi_shift_y: coordi_shift_y along y axis\n    :return: shifted_x, shifted_y\n    '''\n    shifted_x = orig_x - coordi_shift_x\n    shifted_y = orig_y - coordi_shift_y\n    return shifted_x, shifted_y\n\n\ndef rotate_coordination(orig_x, orig_y, orig_d, coordi_rotate_d):\n    \"\"\"\n    :param orig_x: original x\n    :param orig_y: original y\n    :param orig_d: original degree\n    :param coordi_rotate_d: coordination rotation d, positive if anti-clockwise, unit: deg\n    :return:\n    transformed_x, transformed_y, transformed_d(range:(-180 deg, 180 deg])\n    \"\"\"\n\n    coordi_rotate_d_in_rad = coordi_rotate_d * math.pi / 180\n    transformed_x = orig_x * math.cos(coordi_rotate_d_in_rad) + orig_y * math.sin(coordi_rotate_d_in_rad)\n    transformed_y = -orig_x * math.sin(coordi_rotate_d_in_rad) + orig_y * math.cos(coordi_rotate_d_in_rad)\n    transformed_d = orig_d - coordi_rotate_d\n    if transformed_d > 180:\n        while transformed_d > 180:\n            transformed_d = transformed_d - 360\n    elif transformed_d <= -180:\n        while transformed_d <= -180:\n            transformed_d = transformed_d + 360\n    else:\n        transformed_d = transformed_d\n    return transformed_x, transformed_y, transformed_d\n\n\ndef shift_and_rotate_coordination(orig_x, orig_y, orig_d, coordi_shift_x, coordi_shift_y, coordi_rotate_d):\n    shift_x, shift_y = shift_coordination(orig_x, orig_y, coordi_shift_x, coordi_shift_y)\n    transformed_x, transformed_y, transformed_d \\\n        = rotate_coordination(shift_x, shift_y, orig_d, coordi_rotate_d)\n    return transformed_x, transformed_y, transformed_d\n\n\ndef rotate_and_shift_coordination(orig_x, orig_y, orig_d, coordi_shift_x, coordi_shift_y, coordi_rotate_d):\n    shift_x, shift_y, transformed_d \\\n        = rotate_coordination(orig_x, orig_y, orig_d, coordi_rotate_d)\n    transformed_x, transformed_y = shift_coordination(shift_x, shift_y, coordi_shift_x, coordi_shift_y)\n\n    return transformed_x, transformed_y, transformed_d\n\n\ndef cal_info_in_transform_coordination(filtered_objects, x, y, rotate_d):  # rotate_d is positive if anti\n    results = []\n    for obj in filtered_objects:\n        orig_x = obj['x']\n        orig_y = obj['y']\n        orig_v = obj['v']\n        orig_heading = obj['phi']\n        width = obj['w']\n        length = obj['l']\n        route = obj['route']\n        shifted_x, shifted_y = shift_coordination(orig_x, orig_y, x, y)\n        trans_x, trans_y, trans_heading = rotate_coordination(shifted_x, shifted_y, orig_heading, rotate_d)\n        trans_v = orig_v\n        results.append({'x': trans_x,\n                        'y': trans_y,\n                        'v': trans_v,\n                        'phi': trans_heading,\n                        'w': width,\n                        'l': length,\n                        'route': route,})\n    return results\n\n\ndef cal_ego_info_in_transform_coordination(ego_dynamics, x, y, rotate_d):\n    orig_x, orig_y, orig_a, corner_points = ego_dynamics['x'], ego_dynamics['y'], ego_dynamics['phi'], ego_dynamics['Corner_point']\n    shifted_x, shifted_y = shift_coordination(orig_x, orig_y, x, y)\n    trans_x, trans_y, trans_a = rotate_coordination(shifted_x, shifted_y, orig_a, rotate_d)\n    trans_corner_points = []\n    for corner_x, corner_y in corner_points:\n        shifted_x, shifted_y = shift_coordination(corner_x, corner_y, x, y)\n        trans_corner_x, trans_corner_y, _ = rotate_coordination(shifted_x, shifted_y, orig_a, rotate_d)\n        trans_corner_points.append((trans_corner_x, trans_corner_y))\n    ego_dynamics.update(dict(x=trans_x,\n                             y=trans_y,\n                             phi=trans_a,\n                             Corner_point=trans_corner_points))\n    return ego_dynamics\n\n\ndef xy2_edgeID_lane(x, y):\n    if y < -CROSSROAD_SIZE/2:\n        edgeID = '1o'\n        lane = int((LANE_NUMBER-1)-int(x/LANE_WIDTH))\n    elif x < -CROSSROAD_SIZE/2:\n        edgeID = '4i'\n        lane = int((LANE_NUMBER-1)-int(y/LANE_WIDTH))\n    elif y > CROSSROAD_SIZE/2:\n        edgeID = '3i'\n        lane = int((LANE_NUMBER-1)-int(x/LANE_WIDTH))\n    elif x > CROSSROAD_SIZE/2:\n        edgeID = '2i'\n        lane = int((LANE_NUMBER-1)-int(-y/LANE_WIDTH))\n    else:\n        edgeID = '0'\n        lane = 0\n    return edgeID, lane\n\n\ndef _convert_car_coord_to_sumo_coord(x_in_car_coord, y_in_car_coord, a_in_car_coord, car_length):  # a in deg\n    x_in_sumo_coord = x_in_car_coord + car_length / 2 * math.cos(math.radians(a_in_car_coord))\n    y_in_sumo_coord = y_in_car_coord + car_length / 2 * math.sin(math.radians(a_in_car_coord))\n    a_in_sumo_coord = -a_in_car_coord + 90.\n    return x_in_sumo_coord, y_in_sumo_coord, a_in_sumo_coord\n\n\ndef _convert_sumo_coord_to_car_coord(x_in_sumo_coord, y_in_sumo_coord, a_in_sumo_coord, car_length):\n    a_in_car_coord = - a_in_sumo_coord + 90.\n    x_in_car_coord = x_in_sumo_coord - (math.cos(a_in_car_coord / 180. * math.pi) * car_length / 2)\n    y_in_car_coord = y_in_sumo_coord - (math.sin(a_in_car_coord / 180. * math.pi) * car_length / 2)\n    return x_in_car_coord, y_in_car_coord, deal_with_phi(a_in_car_coord)\n\n\ndef deal_with_phi(phi):\n    return np.mod(phi+180,2*180)-180.\n\nif __name__ == '__main__':\n    pass", "meta": {"hexsha": "e02ba3fa270cefb88acbda69735c8fa3307cce15", "size": 8897, "ext": "py", "lang": "Python", "max_stars_repo_path": "Env_utils.py", "max_stars_repo_name": "molumitu/crossroad_mpc", "max_stars_repo_head_hexsha": "65e45e84de44ac4dc0b5ad9c4a9cfb0ee13d4d11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Env_utils.py", "max_issues_repo_name": "molumitu/crossroad_mpc", "max_issues_repo_head_hexsha": "65e45e84de44ac4dc0b5ad9c4a9cfb0ee13d4d11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Env_utils.py", "max_forks_repo_name": "molumitu/crossroad_mpc", "max_forks_repo_head_hexsha": "65e45e84de44ac4dc0b5ad9c4a9cfb0ee13d4d11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.71875, "max_line_length": 137, "alphanum_fraction": 0.6519051366, "include": true, "reason": "import numpy", "num_tokens": 2515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.31069438959712015, "lm_q1q2_score": 0.18178764595774338}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n  femagtools.dxfsl.area\n  ~~~~~~~~~~~~~~~~~~~~~\n\n  areas are regions surrounded by a collection of shapes\n\n  Authors: Ronald Tanner, beat Holm\n\"\"\"\nfrom __future__ import print_function\nimport sys\nimport numpy as np\nimport networkx as nx\nimport logging\nfrom .functions import less_equal, less, greater_equal, greater\nfrom .functions import distance, alpha_angle, alpha_line, min_angle, max_angle\nfrom .functions import point, line_m, line_n, intersect_point, points_are_close\nfrom .functions import middle_angle, part_of_circle, is_same_angle\nfrom .functions import area_size\nfrom .shape import Element, Shape, Line, Arc, Circle, is_Circle\n\nlogger = logging.getLogger('femagtools.area')\n\n\n#############################\n#            Area           #\n#############################\n\narea_number = 0\n\n\nclass Area(object):\n    def __init__(self, area, center, sym_tolerance):\n        self.area = area\n        self.type = 0  # material\n        self.phi = 0.0\n        self.min_angle = 0.0\n        self.max_angle = 0.0\n        self.min_air_angle = 0.0\n        self.max_air_angle = 0.0\n        self.close_to_ag = False\n        self.close_to_startangle = False\n        self.close_to_endangle = False\n        self.mag_rectangle = False\n        self.min_dist = 99999.0\n        self.max_dist = 0.0\n        self.height = 0.0\n        self.alpha = 0.0\n        self.count = 1\n        self.equal_areas = []\n        self.delta = 0.0\n        self.start = 0.0\n        self.sym_startangle = 0.0\n        self.sym_endangle = 0.0\n        self.sym_type = 0\n        self.symmetry = 0\n        self.sym_tolerance = sym_tolerance\n        self.calc_signature(center)\n        self.surface = 0.0\n        global area_number\n        area_number += 1\n        self.id = area_number\n        self.areas_inside = {}\n\n    def identifier(self):\n        return \"{}-{}\".format(self.id, self.type)\n\n    def get_id(self):\n        return self.id\n\n    def number_of_elements(self):\n        return len(self.area)\n\n    def elements(self):\n        return self.area\n\n    def list_of_nodes(self):\n        if len(self.area) < 2:\n            return\n\n        e0 = self.area[0]\n        e1 = self.area[1]\n        try:\n            if e1.get_node_number(e0.n1, override=True) == 0:\n                nx = e0.n2\n            else:\n                nx = e0.n1\n            yield nx\n\n            for e1 in self.area[1:]:\n                if e1.get_node_number(nx) == 1:\n                    nx = e1.n2\n                else:\n                    nx = e1.n1\n                yield nx\n        except ValueError as e:\n            logger.error(\"list_of_nodes(): FATAL ERROR: %s\", e)\n            return\n        except Exception as e:\n            return\n\n    def list_of_elements(self):\n        if len(self.area) < 2:\n            return\n\n        e0 = self.area[0]\n        e1 = self.area[1]\n        try:\n            if e1.get_node_number(e0.n1, override=True) == 0:\n                n1 = e0.n1\n                n2 = e0.n2\n            else:\n                n1 = e0.n2\n                n2 = e0.n1\n            yield n1, n2, e0\n\n            for e1 in self.area[1:]:\n                if e1.get_node_number(n2) == 1:\n                    n1 = e1.n1\n                    n2 = e1.n2\n                else:\n                    n1 = e1.n2\n                    n2 = e1.n1\n                yield n1, n2, e1\n        except ValueError as e:\n            logger.error(\"list_of_elements(): FATAL ERROR: %s\", e)\n            return\n        except Exception as e:\n            return\n\n    def virtual_nodes(self, render=False):\n        if len(self.area) < 2:\n            return\n\n        prev_nodes = [n for n in self.area[0].get_nodes(parts=64,\n                                                        render=render)]\n        next_nodes = [n for n in self.area[1].get_nodes(parts=64,\n                                                        render=render)]\n        if points_are_close(prev_nodes[0], next_nodes[0], 1e-03, 1e-01):\n            prev_nodes = prev_nodes[::-1]\n        elif points_are_close(prev_nodes[0], next_nodes[-1], 1e-03, 1e-01):\n            prev_nodes = prev_nodes[::-1]\n            next_nodes = next_nodes[::-1]\n        elif points_are_close(prev_nodes[-1], next_nodes[-1], 1e-03, 1e-01):\n            next_nodes = next_nodes[::-1]\n        elif not points_are_close(prev_nodes[-1], next_nodes[0], 1e-03, 1e-01):\n            assert(False)\n        last_point = next_nodes[-1]\n        for n in prev_nodes:\n            yield n\n        for n in next_nodes:\n            yield n\n\n        for e in self.area[2::]:\n            next_nodes = [n for n in e.get_nodes(parts=64, render=render)]\n\n            if points_are_close(next_nodes[-1], last_point, 1e-03, 1e-01):\n                next_nodes = next_nodes[::-1]\n            for n in next_nodes:\n                yield n\n            last_point = next_nodes[-1]\n\n    def legend(self):\n        if self.type == 1:\n            return 'Iron'\n        if self.type == 2:\n            return 'Windings'\n        if self.type == 3 or self.type == 4:\n            return 'Magnet'\n        if self.type == 5:\n            return 'Yoke'\n        if self.type == 6:\n            return 'Tooth'\n        if self.type == 10:\n            return 'Shaft'\n        return ''\n\n    def name(self):\n        if self.type == 1:\n            return 'Iron'\n        if self.type == 2:\n            return 'Wndg'\n        if self.type == 3 or self.type == 4:\n            return 'Mag'\n        if self.type == 5:\n            return 'StJo'\n        if self.type == 6:\n            return 'StZa'\n        if self.type == 10:\n            return 'Shft'\n        return ''\n\n    def color(self):\n        if self.type == 1:\n            return 'cyan'\n        if self.type == 2:\n            return 'green'\n        if self.type == 3 or self.type == 4:\n            return 'red'\n        if self.type == 5:\n            return 'cyan'\n        if self.type == 6:\n            return 'skyblue'\n        if self.type == 10:\n            return 'lightgrey'\n        return 'white'\n\n    def color_alpha(self):\n        if self.type == 1:\n            return 0.3\n        if self.type == 2:\n            return 1.0\n        if self.type == 3 or self.type == 4:\n            return 1.0\n        if self.type == 5:\n            return 0.5\n        if self.type == 6:\n            return 1.0\n        if self.type == 10:\n            return 0.8\n        return 1.0\n\n    def is_iron(self):\n        return self.type == 1 or self.type == 5 or self.type == 6\n\n    def is_stator_iron_yoke(self):\n        return self.type == 5\n\n    def is_stator_iron_tooth(self):\n        return self.type == 6\n\n    def is_rotor_iron(self):\n        return self.type == 1\n\n    def is_winding(self):\n        return self.type == 2\n\n    def is_magnet(self):\n        return self.type == 3 or self.type == 4\n\n    def is_shaft(self):\n        return self.type == 10\n\n    def is_air(self):\n        return self.type == 0\n\n    def set_type(self, t):\n        self.type = t\n\n    def calc_signature(self, center):\n        if not self.area:\n            return\n\n        s = self.area[0]\n        mm_angle = s.minmax_angle_from_center(center)\n        self.min_angle = mm_angle[0]\n        self.max_angle = mm_angle[1]\n\n        for s in self.area:\n            mm_dist = s.minmax_from_center(center)\n            self.min_dist = min(self.min_dist, mm_dist[0])\n            self.max_dist = max(self.max_dist, mm_dist[1])\n            self.height = self.max_dist - self.min_dist\n\n            mm_angle = s.minmax_angle_from_center(center)\n            self.min_angle = min_angle(self.min_angle, mm_angle[0])\n            self.max_angle = max_angle(self.max_angle, mm_angle[1])\n\n        self.alpha = round(alpha_angle(self.min_angle, self.max_angle), 3)\n\n    def minmax_angle_dist_from_center(self, center, dist):\n        circ = Circle(Element(center=center, radius=dist))\n        s = self.area[0]\n        my_min_angle = self.max_angle\n        my_max_angle = self.min_angle\n        mm_angle = None\n        for s in self.area:\n            mm_angle = s.minmax_angle_dist_from_center(my_min_angle,\n                                                       my_max_angle,\n                                                       center, circ)\n            if mm_angle:\n                my_min_angle = min_angle(my_min_angle, mm_angle[0])\n                my_max_angle = max_angle(my_max_angle, mm_angle[1])\n        return (my_min_angle, my_max_angle)\n\n    def is_inside(self, area):\n        if less_equal(area.min_dist, self.min_dist):\n            return False\n        if greater_equal(area.max_dist, self.max_dist):\n            return False\n        if less_equal(area.min_angle, self.min_angle):\n            return False\n        if greater_equal(area.max_angle, self.max_angle):\n            return False\n        return True\n\n    def is_touching(self, area):\n        for n in self.list_of_nodes():\n            x = [p for p in area.list_of_nodes() if points_are_close(n, p)]\n            if x:\n                return True\n        return False\n\n    def is_touching_both_sides(self):\n        return (self.close_to_startangle and self.close_to_endangle)\n\n    def has_connection(self, geom, a, ndec):\n        assert(self.area)\n        assert(a.area)\n        n1 = self.area[0].node1(ndec)\n        if not geom.g.has_node(n1):\n            n = geom.find_nodes(n1)\n            if not n:\n                logger.warn(\"FATAL: node {} not available\".format(n1))\n                return False\n            n1 = n[0]\n\n        n2 = a.area[0].node2(ndec)\n        if not geom.g.has_node(n2):\n            n = geom.find_nodes(n2)\n            if not n:\n                logger.warn(\"FATAL: node {} not available\".format(n2))\n                return False\n            n2 = n[0]\n\n        try:\n            return nx.has_path(geom.g, n1, n2)\n        except nx.NetworkXError:\n            logger.warn(\"has_path() failed\")\n            return False\n\n    def get_lowest_gap_list(self, a, center, radius, rightangle, leftangle):\n        gap_list = []\n        if a.get_id() < self.get_id():\n            dist_id = '{}-{}'.format(a.get_id(), self.get_id())\n        else:\n            dist_id = '{}-{}'.format(self.get_id(), a.get_id())\n\n        for p1 in self.list_of_nodes():\n            for p2 in a.list_of_nodes():\n                d = distance(p1, p2)\n                gap_list.append((d, (p1, p2), dist_id))\n\n        d, p1, p2 = a.get_nearest_point(center, radius, rightangle)\n        gap_list.append((d, (p1, p2), dist_id))\n        d, p1, p2 = a.get_nearest_point(center, radius, leftangle)\n        gap_list.append((d, (p1, p2), dist_id))\n        gap_list.sort()\n        return [gap_list[0]]\n\n    def get_nearest_point(self, center, radius, angle):\n        axis_p = point(center, radius, angle)\n        axis_m = line_m(center, axis_p)\n        axis_n = line_n(center, axis_m)\n\n        the_area_p = None\n        the_axis_p = None\n        dist = 99999\n        for n in self.list_of_nodes():\n            p = intersect_point(n, center, axis_m, axis_n)\n            d = distance(n, p)\n            if d < dist:\n                dist = d\n                the_area_p = n\n                the_axis_p = p\n\n        return (dist,\n                (the_axis_p[0], the_axis_p[1]),\n                (the_area_p[0], the_area_p[1]))\n\n    def is_equal(self, a, sym_tolerance):\n        if sym_tolerance > 0.0:\n            if np.isclose(round(self.min_dist, 4),\n                          round(a.min_dist, 4),\n                          1e-03, sym_tolerance) and \\\n               np.isclose(round(self.max_dist, 4),\n                          round(a.max_dist, 4),\n                          1e-03, sym_tolerance) and \\\n               np.isclose(round(self.alpha, 3),\n                          round(a.alpha, 3),\n                          1e-02, 0.01):\n                return True\n        else:\n            if np.isclose(round(self.min_dist, 2),\n                          round(a.min_dist, 2)) and \\\n               np.isclose(round(self.max_dist, 2),\n                          round(a.max_dist, 2)) and \\\n               np.isclose(round(self.alpha, 3),\n                          round(a.alpha, 3), 1e-02, 0.001):\n                return True\n        return False\n\n    def is_identical(self, area):\n        if np.isclose(self.min_dist, area.min_dist) and \\\n           np.isclose(self.max_dist, area.max_dist) and \\\n           np.isclose(self.alpha, area.alpha) and \\\n           np.isclose(self.min_angle, area.min_angle) and \\\n           np.isclose(self.max_angle, area.max_angle):\n            return True\n        return False\n\n    def increment(self, a):\n        if self.is_identical(a):\n            return\n\n        for area in self.equal_areas:\n            if area.is_identical(a):\n                return\n\n        self.count += 1\n        self.equal_areas.append(a)\n\n    def set_delta(self):\n        logger.debug(\"begin set_delta of {}\".format(self.id))\n        self.delta = 0.0\n        self.symmetry = 0\n\n        if len(self.equal_areas) < 2:\n            # Mit zwei Objekten lässt sich das Teil nur noch halbieren. Das\n            # wird zum Schluss sowieso versucht.\n            logger.debug(\"end set_delta: zuwenig Gleiche\")\n            return\n\n        sorted_areas = []\n        sorted_areas.append((self.min_angle, self))\n        for a in self.equal_areas:\n            sorted_areas.append((a.min_angle, a))\n        sorted_areas.sort()\n\n        delta = {}\n        prev_angle = sorted_areas[0][0]\n        for angle, area in sorted_areas[1:]:\n            d = round(alpha_angle(prev_angle, angle), 2)\n            if d in delta:\n                delta[d] += 1\n            else:\n                delta[d] = 1\n            prev_angle = angle\n\n        delta_sorted = list([v, k] for (k, v) in delta.items())\n        logger.debug(\" - delta: {}\".format(delta_sorted))\n\n        if len(delta_sorted) == 1:\n            # simple case: all have the same angle\n            self.delta = alpha_angle(sorted_areas[0][1].min_angle,\n                                     sorted_areas[1][1].min_angle)\n            self.start = middle_angle(sorted_areas[0][1].max_angle,\n                                      sorted_areas[1][1].min_angle)\n            self.sym_type = 3\n            self.symmetry = part_of_circle(0.0, self.delta, 1)\n            logger.debug(\"end set_delta: simple case\")\n            return\n\n        logger.debug(\"end set_delta: {} deltas, {} areas\"\n                     .format(len(delta_sorted), len(self.equal_areas)))\n\n        if len(delta_sorted) > 2:\n            # Mehr als 2 Winkel untersuchen wir (noch) nicht. Wir brechen\n            # die Suche nach dem richtigen Winkel ab.\n            logger.debug(\"end set_delta: zuviele Winkel\")\n            return\n\n        # Bei 2 verschiedenen Winkeln werden die näher beieinander liegenden\n        # Objekte zusammen genommen.\n\n        if len(self.equal_areas) < 4:\n            # Wenn nicht mehr als 4 Objekte vorhanden sind, brechen wir auch\n            # ab.\n            logger.debug(\"end set_delta: zuwenig areas\")\n            return\n\n        if np.isclose(delta_sorted[1][1],\n                      delta_sorted[0][1]*2, atol=0.01):\n            # Lets hope we have unreqognised areas inbetween\n            percent = 1.0\n        else:\n            percent = delta_sorted[0][0] / (len(self.equal_areas)+1)\n\n        if percent > 0.75:\n            # lets assume we only have one angle\n            self.delta = alpha_angle(sorted_areas[0][1].min_angle,\n                                     sorted_areas[1][1].min_angle)\n            self.start = middle_angle(sorted_areas[0][1].max_angle,\n                                      sorted_areas[1][1].min_angle)\n            self.sym_type = 2\n            self.symmetry = part_of_circle(0.0, self.delta, 1)\n            logger.debug(\"end set_delta: {} Prozent gleiche deltas\"\n                         .format(percent))\n            return\n\n        # Lets hope the distances are changing\n        self.delta = alpha_angle(sorted_areas[0][1].min_angle,\n                                 sorted_areas[2][1].min_angle)\n        self.sym_type = 1\n        self.symmetry = part_of_circle(0.0, self.delta, 1)\n        delta_1 = alpha_angle(sorted_areas[0][1].min_angle,\n                              sorted_areas[1][1].min_angle)\n        delta_2 = alpha_angle(sorted_areas[1][1].min_angle,\n                              sorted_areas[2][1].min_angle)\n\n        if np.isclose(delta_1, delta_2):\n            # Hm. the distances are not changing\n            self.delta = 0.0\n            logger.debug(\"end set_delta: the distances are not changing\")\n            return\n\n        if delta_1 < delta_2:\n            self.start = middle_angle(sorted_areas[1][1].max_angle,\n                                      sorted_areas[2][1].min_angle)\n        else:\n            self.start = middle_angle(sorted_areas[0][1].max_angle,\n                                      sorted_areas[1][1].min_angle)\n        logger.debug(\"end set_delta: delta wechselt: delta={}\"\n                     .format(self.delta))\n\n    def symmetry_lines(self, startangle, endangle):\n        logger.debug(\"begin symmetry_lines of {} ({}, {})\"\n                     .format(self.id,\n                             startangle,\n                             endangle))\n        if less_equal(endangle, startangle):\n            endangle += 2*np.pi\n\n        angle = self.start\n        while less(angle, startangle):\n            angle += self.delta\n        while greater(angle, startangle+self.delta):\n            angle -= self.delta\n\n        # Damit man anschliessend ohne Umstände schneiden kann.\n        self.sym_startangle = angle\n        self.sym_endangle = angle + self.delta\n        logger.debug(\" - delta: {}, sym start: {}, end: {}\"\n                     .format(self.sym_startangle,\n                             self.delta,\n                             self.sym_endangle))\n        while angle < endangle:\n            yield angle\n            angle += self.delta\n        logger.debug(\"end symmetry_lines\")\n\n    def minmax(self):\n        mm = [99999, -99999, 99999, -99999]\n\n        for e in self.area:\n            n = e.minmax()\n            mm[0] = min(mm[0], n[0])\n            mm[1] = max(mm[1], n[1])\n            mm[2] = min(mm[2], n[2])\n            mm[3] = max(mm[3], n[3])\n        return mm\n\n    def intersect_line(self, line):\n        for e in self.area:\n            if e.intersect_line(line):\n                return True\n        return False\n\n    def is_point_inside(self, pt):\n        for e in self.area:\n            if e.is_point_inside(pt, include_end=True):\n                return True\n        return False\n\n    def get_best_point_inside(self, geom):\n        mm = self.minmax()\n        px1 = mm[0]-5\n        px2 = mm[1]+5\n\n        y_dist = mm[3] - mm[2]\n        step = y_dist / 6\n        y_list = np.arange(mm[2] + step*0.3, mm[3] - step*0.3, step)\n\n        lines = []\n        for y in y_list:\n            p1 = (px1, y)\n            p2 = (px2, y)\n            line = Line(Element(start=p1, end=p2))\n            lines.append({'line': line,\n                          'pts': [],\n                          'y': y,\n                          'x': []})\n\n        for e in self.area:\n            points = []\n            for line in lines:\n                line['pts'] += e.intersect_line(line['line'],\n                                                geom.rtol,\n                                                geom.atol,\n                                                True)\n        for line in lines:\n            x_sorted = [p[0] for p in line['pts']]\n            x_sorted.sort()\n            if x_sorted:\n                line['start_x'] = x_sorted[0]\n                line['end_x'] = x_sorted[-1]\n\n        for e in geom.elements(Shape):\n            for line in lines:\n                if line.get('start_x', None) is None:\n                    continue\n                points = e.intersect_line(line['line'],\n                                          geom.rtol,\n                                          geom.atol,\n                                          True)\n\n                for p in points:\n                    if greater(p[0],\n                               line['start_x'],\n                               rtol=1e-8):\n                        if less(p[0],\n                                line['end_x'],\n                                rtol=1e-8):\n                            line['x'].append(p[0])\n\n        points = []\n        for line in lines:\n            if line.get('start_x', None) is None:\n                continue\n            line['x'].sort()\n            x1 = line['start_x']\n            x2 = line['end_x']\n            if line['x']:\n                x = line['x'][0]  # first point\n                line['x_dist'] = x - x1\n                points.append((line['x_dist'], (x1+x)/2, line['y']))\n\n                x = line['x'][-1]  # last point\n                line['x_dist'] = x2 - x\n                points.append((line['x_dist'], (x+x2)/2, line['y']))\n            else:\n                line['x_dist'] = x2 - x1  # no points between\n                points.append((line['x_dist'], (x1+x2)/2, line['y']))\n\n        points.sort()\n        return (points[-1][1], points[-1][2])\n\n    def get_point_inside(self, geom):\n        \"\"\"return point inside area\"\"\"\n        mm = self.minmax()\n        y = (mm[2]+mm[3])/2\n        p1 = (mm[0]-5, y)\n        p2 = (mm[1]+5, y)\n        line = Line(Element(start=p1, end=p2))\n\n        points = []\n        for e in self.area:\n            points += e.intersect_line(line, geom.rtol, geom.atol, True)\n\n        if len(points) < 2:\n            logger.debug(\"WARNING: get_point_inside() failed ({})\".\n                         format(len(points)))\n            return None\n\n        assert(len(points) > 1)\n\n        my_points_sorted = [(p[0], p) for p in points]\n        my_points_sorted.sort()\n        my_p1 = my_points_sorted[0][1]   # Startpoint\n        my_p2 = my_points_sorted[-1][1]  # Endpoint\n\n        all_points_sorted = []\n        for e in geom.elements(Shape):\n            points = e.intersect_line(line, geom.rtol, geom.atol, True)\n            for p in points:\n                if greater(p[0], my_p1[0], rtol=1e-8):\n                    if less(p[0], my_p2[0], rtol=1e-8):\n                        all_points_sorted.append((p[0], p))\n\n        if len(all_points_sorted) == 0:\n            p_inside = ((my_p1[0]+my_p2[0])/2, y)\n            if self.is_air():\n                return self.get_best_point_inside(geom)\n            return p_inside\n\n        all_points_sorted.sort()\n        all_p1 = all_points_sorted[0][1]\n        all_p2 = all_points_sorted[-1][1]\n        d1 = all_p1[0] - my_p1[0]\n        d2 = my_p2[0] - all_p2[0]\n        if d1 > d2:\n            p_inside = ((my_p1[0]+all_p1[0])/2, y)\n        else:\n            p_inside = ((my_p2[0]+all_p2[0])/2, y)\n\n        if self.is_air():\n            return self.get_best_point_inside(geom)\n        return p_inside\n\n    def render(self, renderer, color='black', with_nodes=False, fill=True):\n        if fill:\n            if self.render_fill(renderer):\n                color = 'black'\n\n        for e in self.area:\n            e.render(renderer, color, with_nodes)\n        return\n\n    def render_fill(self, renderer):\n        color = self.color()\n        if not color:\n            return False\n        alpha = self.color_alpha()\n\n        if self.is_circle():\n            e = self.area[0]\n            renderer.fill_circle(e.center, e.radius, color, alpha)\n        else:\n            nodes = [n for n in self.virtual_nodes(render=True)]\n            x = [n[0] for n in nodes]\n            y = [n[1] for n in nodes]\n            renderer.fill(x, y, color, alpha)\n        return True\n\n    def render_legend(self, renderer):\n        return renderer.new_legend_handle(self.color(),\n                                          self.color_alpha(),\n                                          self.legend())\n\n    def remove_edges(self, g, ndec):\n        for e in self.area:\n            try:\n                g.remove_edge(e.node1(ndec), e.node2(ndec))\n            except Exception:\n                continue\n\n    def is_circle(self):\n        e = self.area[0]\n        if len(self.area) == 1:\n            return is_Circle(e)\n\n        if isinstance(e, Arc):\n            c = e.center\n            r = e.radius\n            a = 0.0\n            for e in self.area:\n                if not isinstance(e, Arc):\n                    return False\n                if not points_are_close(c, e.center):\n                    return False\n                if not np.isclose(r, e.radius):\n                    return False\n                a += e.get_angle_of_arc()\n            return np.isclose(a, 2.0*np.pi)\n\n        return False\n\n    def is_half_circle(self, center, angle):\n        for e in self.area:\n            if isinstance(e, Line):\n                if not np.isclose(angle, alpha_line(center, e.p1)):\n                    return False\n                if not np.isclose(angle, alpha_line(center, e.p2)):\n                    return False\n            elif isinstance(e, Arc):\n                if not np.isclose(angle, alpha_line(center, e.center)):\n                    return False\n            else:\n                return False\n        return True\n\n    def has_round_edges(self):\n        arcs = 0\n        for e in self.area:\n            # if isinstance(e, Line):\n            #    if not np.isclose(angle, alpha_line(center, e.p1)):\n            #        return False\n            #    if not np.isclose(angle, alpha_line(center, e.p2)):\n            #        return False\n            if isinstance(e, Arc):\n                arcs += 1\n\n        return arcs > 0\n\n    def is_shaft_area(self, center):\n        logger.debug(\"Begin of check shaft\")\n\n        if not self.is_touching_both_sides():\n            logger.debug(\"End of check shaft: don't touch both sides\")\n            return False\n\n        for n in self.list_of_nodes():\n            a = alpha_line(center, n)\n            if np.isclose(self.min_angle, a):\n                continue\n            if np.isclose(self.max_angle, a):\n                continue\n            d = distance(center, n)\n            if np.isclose(d, self.min_dist, atol=0.05):\n                continue\n            if np.isclose(d, self.max_dist, atol=0.05):\n                continue\n            logger.debug(\"End of check shaft: no\")\n            return False\n        logger.debug(\"End of check shaft: ok\")\n        return True\n\n    def is_rectangle(self):\n        lines = [[c, e.m(99999.0), e.length()]\n                 for c, e in enumerate(self.area)\n                 if isinstance(e, Line)]\n        lines.sort()\n\n        line_count = 1\n        m_first = 0.0\n        m_prev = 999.999999\n        c_prev = -99\n        m_all = []\n        for c, m, l in lines:\n            if c_prev >= 0:\n                if np.isclose(m_prev, m, atol=0.001):\n                    if c_prev+1 != c:\n                        # Gleiche Steigung, aber keine Verlängerung\n                        line_count += 1\n                        m_all.append(m_prev)\n                else:\n                    line_count += 1\n                    m_all.append(m_prev)\n            else:\n                m_first = m\n\n            m_prev = m\n            c_prev = c\n\n        m_all.append(m_prev)\n\n        if np.isclose(m_prev, m_first, atol=0.001):\n            line_count -= 1\n\n        if line_count == 4:\n            logger.debug(\"is_rectangle: m={}\".format(m_all))\n            if not np.isclose(m_all[0], m_all[2], atol=0.001):\n                return False\n            if not np.isclose(m_all[1], m_all[3], atol=0.001):\n                return False\n            return True\n\n        return False\n\n    def is_mag_rectangle(self):\n        lines_ceml = [[c, e, e.m(99999.0), e.length()]\n                      for c, e in enumerate(self.area)]\n        # c = Count\n        # e = Element\n        # m = Steigung\n        # l = Länge\n        # L = class Line\n        if len(lines_ceml) < 4:\n            return False\n\n        logger.debug(\"=== BEGIN OF is_mag_rectangle() [{} lines]\"\n                     .format(len(lines_ceml)))\n\n        c_prev = lines_ceml[0][0]\n        a_prev = 999\n        p = None\n\n        e0 = lines_ceml[0][1]\n        e0_p1 = e0.p1\n        e0_p2 = e0.p2\n        L_prev = isinstance(e0, Line)\n        l_prev = lines_ceml[0][3]\n        m_prev = lines_ceml[0][2]\n\n        e1 = lines_ceml[1][1]\n        e1_p1 = e1.p1\n        e1_p2 = e1.p2\n\n        if (points_are_close(e0_p2, e1_p1, atol=1e-02) or\n                points_are_close(e0_p2, e1_p2, atol=1e-02)):\n            a_prev = alpha_line(e0_p1, e0_p2)\n            p = e0_p2\n        elif (points_are_close(e0_p1, e1_p1, atol=1e-02) or\n              points_are_close(e0_p1, e1_p2, atol=1e-02)):\n            a_prev = alpha_line(e0_p2, e0_p1)\n            p = e0_p1\n        else:\n            logger.error(\n                \"ERROR: is_mag_rectangle(): points are not close together\")\n            logger.error(\"       e0 p1={}, p2={}\".format(e0_p1, e0_p2))\n            logger.error(\"       e1 p1={}, p2={}\".format(e1_p1, e1_p2))\n            return False\n\n        def alpha_current(p, e):\n            if points_are_close(p, e.p1, atol=1e-02):\n                return e.p2, alpha_line(e.p1, e.p2), isinstance(e, Line)\n            if points_are_close(p, e.p2, atol=1e-02):\n                return e.p1, alpha_line(e.p2, e.p1), isinstance(e, Line)\n            logger.error(\n                \"ERROR: is_mag_rectangle(): points are not close together\")\n            logger.error(\"       p={}, p1={}, p2={}\".format(p, e.p1, e.p2))\n            return None, None, False\n\n        lines_clamL = []\n        for c, e, m, l in lines_ceml[1:]:\n            p, a_curr, L_curr = alpha_current(p, e)\n            if not p:\n                return False\n\n            if is_same_angle(a_prev, a_curr, atol=0.01):\n                # its the same angle and both are Lines\n                # assert(np.isclose(m_prev, m, atol=0.001))\n                if c_prev+1 != c:\n                    logger.debug(\" - ok, but not an extension\")\n                    # ..., but not an extension\n                    lines_clamL.append([c_prev, l_prev, a_prev, m])\n                    l_prev = e.length()\n                else:\n                    # ... and an extension\n                    l_prev += e.length()\n                    logger.debug(\" - ok, it's an extension\")\n            else:\n                # it's a different angle\n                logger.debug(\" - diff, angle {} and {} not equal \"\n                             .format(a_prev, a_curr))\n                lines_clamL.append([c_prev, l_prev, a_prev, m_prev, L_prev])\n                l_prev = e.length()\n\n            a_prev = a_curr\n            L_prev = L_curr\n            m_prev = m\n            c_prev = c\n\n        lines_clamL.append([c_prev, l_prev, a_prev, m_prev, L_prev])\n        if np.isclose(lines_clamL[0][2], lines_clamL[-1][2], atol=0.001):\n            # Gleicher Winkel am Anfang und am Ende\n            lines_clamL[0][1] += lines_clamL[-1][1]  # length\n            del lines_clamL[-1]\n            logger.debug(\" > last entry deleted\")\n\n        if len(lines_clamL) < 4:\n            logger.debug(\"=== END OF is_mag_rectangle(): NO RECTANGLE #1\")\n            return False\n\n        lines_lmcL = [[l, m, c, L] for c, l, a, m, L in lines_clamL]\n        lines_lmcL.sort(reverse=True)\n\n        if not np.isclose(lines_lmcL[0][1], lines_lmcL[1][1], atol=0.05):\n            # Die Steigungen der zwei längsten Linien müssen gleich sein\n            logger.debug(\"--- m %s <> %s ---\",\n                         lines_lmcL[0][1],\n                         lines_lmcL[1][1])\n            logger.debug(\"--- l %s, %s, %s ---\",\n                         lines_lmcL[0][0],\n                         lines_lmcL[1][0],\n                         lines_lmcL[2][0])\n            logger.debug(\"=== END OF is_mag_rectangle(): NO RECTANGLE #2\")\n            return False\n\n        def excursion_to_same_direction(clam):\n            if len(clam) < 4:\n                return False\n\n            alpha = alpha_angle(clam[0][2], clam[1][2])\n            clockwise = not alpha < np.pi\n\n            angle_prev = clam[1][2]\n            for c, l, angle_curr, m, t in clam[2:]:\n                alpha = alpha_angle(angle_prev, angle_curr)\n                if clockwise:\n                    if alpha < np.pi:\n                        return False\n                else:\n                    if alpha > np.pi:\n                        return False\n                angle_prev = angle_curr\n            return True  # end of all_lines_with_same_direction()\n\n        lines_cmL = [[c, m, L] for l, m, c, L in lines_lmcL[0:4]]\n        lines_cmL.sort()\n\n        if np.isclose(lines_cmL[0][1], lines_cmL[2][1], atol=0.001):\n            if not (lines_cmL[0][2] and lines_cmL[2][2]):\n                logger.debug(\"=== END OF is_mag_rectangle(): not 2 lines #1\")\n                return False\n            ok = excursion_to_same_direction(lines_clamL)\n            logger.debug(\"=== END OF is_mag_rectangle(): OK = {} #1\"\n                         .format(ok))\n            return ok\n        if np.isclose(lines_cmL[1][1], lines_cmL[3][1], atol=0.001):\n            if not (lines_cmL[1][2] and lines_cmL[3][2]):\n                logger.debug(\"=== END OF is_mag_rectangle(): not 2 lines #2\")\n                return False\n\n            ok = excursion_to_same_direction(lines_clamL)\n            logger.debug(\"=== END OF is_mag_rectangle(): OK = {} #2\"\n                         .format(ok))\n            return ok\n\n        logger.debug(\"=== END OF is_mag_rectangle(): NO RECTANGLE #3\")\n        return False\n\n    def get_mag_orient_rectangle(self):\n        lines = [[e.m(99999.0), e.length(), alpha_line(e.p1, e.p2)]\n                 for e in self.area\n                 if isinstance(e, Line)]\n        lines.sort()\n\n        m_prev = 999.999999\n        a_prev = 0.0\n        l_total = 0.0\n        line_length = []\n        for m, l, a in lines:\n            if np.isclose(m_prev, m):\n                l_total += l\n            else:\n                if l_total > 0.0:\n                    line_length.append((l_total, m_prev, a_prev))\n                l_total = l\n                m_prev = m\n                a_prev = a\n\n        if l_total > 0.0:\n            line_length.append((l_total, m_prev, a_prev))\n        line_length.sort(reverse=True)\n\n        alpha = line_length[0][2]\n        if alpha < 0.0:\n            alpha += np.pi\n        alpha = alpha + np.pi/2\n        if alpha > np.pi:\n            alpha = alpha - np.pi\n        return alpha\n\n    def get_mag_orientation(self):\n        if self.mag_rectangle:\n            return self.get_mag_orient_rectangle()\n\n        if self.close_to_endangle:\n            if self.close_to_startangle:\n                return middle_angle(self.min_angle, self.max_angle)\n            else:\n                return self.max_angle\n        else:\n            return middle_angle(self.min_angle, self.max_angle)\n\n    def around_windings(self, areas):\n        for a in areas:\n            if a.is_winding():\n                if not self.is_identical(a):\n                    if self.is_inside(a):\n                        return True\n                    elif self.is_touching(a):\n                        return True\n        return False\n\n    def mark_stator_subregions(self,\n                               is_inner,\n                               stator_size,\n                               mirrored,\n                               alpha,\n                               center,\n                               r_in,\n                               r_out):\n        alpha = round(alpha, 6)\n\n        if self.is_circle():\n            self.type = 0  # air\n            return self.type\n\n        ag_delta = (r_out - r_in) / 500.0\n        if is_inner:\n            self.close_to_ag = greater_equal(self.max_dist + ag_delta, r_out)\n            close_to_opposition = np.isclose(r_in, self.min_dist)\n            airgap_radius = r_out\n            opposite_radius = r_in\n            airgap_toleranz = -(self.max_dist - self.min_dist) / 50.0  # 2%\n        else:\n            self.close_to_ag = less_equal(self.min_dist - ag_delta, r_in)\n            close_to_opposition = np.isclose(r_out, self.max_dist)\n            airgap_radius = r_in\n            opposite_radius = r_out\n            airgap_toleranz = (self.max_dist - self.min_dist) / 50.0  # 2%\n\n        self.close_to_startangle = np.isclose(self.min_angle, 0.0,\n                                              1e-04, 1e-04)\n        self.close_to_endangle = np.isclose(self.max_angle, alpha,\n                                            1e-04, 1e-04)\n        self.surface = self.area_size()\n\n        logger.debug(\"\\n***** mark_stator_subregions [{}] *****\"\n                     .format(self.id))\n        logger.debug(\" - close_to_ag        : %s\", self.close_to_ag)\n        logger.debug(\" - close_to_opposition: %s\", close_to_opposition)\n        logger.debug(\" - airgap_radius      : %3.12f\", airgap_radius)\n        logger.debug(\" - airgap_toleranz    : %3.12f\", airgap_toleranz)\n        logger.debug(\" - opposite radius    : %3.12f\", opposite_radius)\n        logger.debug(\" - close_to_startangle: %s\", self.close_to_startangle)\n        logger.debug(\" - close_to_endangle  : %s\", self.close_to_endangle)\n        logger.debug(\" - alpha              : %3.12f\", alpha)\n        logger.debug(\" - min_angle          : %3.12f\", self.min_angle)\n        logger.debug(\" - max_angle          : %3.12f\", self.max_angle)\n        logger.debug(\" - min_dist           : %3.12f\", self.min_dist)\n        logger.debug(\" - max_dist           : %3.12f\", self.max_dist)\n        logger.debug(\" - surface size       : %3.12f\", self.surface)\n\n        if is_inner:\n            # looking for shaft\n            if close_to_opposition and not self.close_to_ag:\n                if self.is_shaft_area(center):\n                    self.type = 10  # shaft\n                    logger.debug(\"***** shaft (close to opposition)\\n\")\n                    return self.type\n\n        if close_to_opposition:\n            self.type = 5  # iron yoke (Joch)\n            logger.debug(\"***** iron yoke #1\\n\")\n            return self.type\n\n        if self.close_to_startangle and self.close_to_endangle:\n            self.type = 5  # iron yoke (Joch)\n            logger.debug(\"***** iron yoke #2\\n\")\n            return self.type\n\n        if self.close_to_ag:  # close to airgap\n            mm = self.minmax_angle_dist_from_center(center,\n                                                    airgap_radius +\n                                                    airgap_toleranz)\n            self.min_air_angle = mm[0]\n            self.max_air_angle = mm[1]\n            air_alpha = round(alpha_angle(mm[0], mm[1]), 3)\n            logger.debug(\" - min_air_alpha      : {}\".format(mm[0]))\n            logger.debug(\" - max_air_alpha      : {}\".format(mm[1]))\n            logger.debug(\" - air_alpha          : {}\".format(air_alpha))\n\n            if self.alpha / air_alpha > 2:\n                logger.debug(\"***** windings near airgap\\n\")\n                self.type = 2  # windings\n            else:\n                self.type = 9  # air or iron near windings and near airgap?\n                logger.debug(\"***** air or iron ??\\n\")\n            return self.type\n\n        if self.close_to_startangle:\n            if self.is_half_circle(center, self.min_angle):\n                self.type = 0  # air\n                logger.debug(\"***** air (part of a circle)\\n\")\n                return self.type\n\n        if self.close_to_endangle:\n            if self.is_half_circle(center, self.max_angle):\n                self.type = 0  # air\n                logger.debug(\"***** air (part of a circle)\\n\")\n                return self.type\n\n        if self.min_angle > 0.001:\n            if self.max_angle < alpha - 0.001:\n                self.type = 2  # windings\n                logger.debug(\"***** windings #1\\n\")\n                return self.type\n            if mirrored:\n                self.type = 2  # windings\n                logger.debug(\"***** windings #2\\n\")\n                return self.type\n\n            self.type = 0  # air\n            logger.debug(\"***** air #2\")\n\n        if self.close_to_startangle or self.close_to_endangle:\n            f = self.surface / stator_size\n            if f < 0.02:  # area_size less then 2 percent of stator size\n                # Luftloch\n                self.type = 0  # air\n                logger.debug(\"***** small area => air\\n\")\n            else:\n                self.type = 9  # air or iron near windings and near airgap?\n                logger.debug(\"***** air or iron close to border\\n\")\n            return self.type\n\n        logger.debug(\"***** air #3\\n\")\n        return 0\n\n    def mark_rotor_subregions(self, is_inner, mirrored, alpha,\n                              center, r_in, r_out):\n        logger.debug(\"mark_rotor_subregions\")\n\n        alpha = round(alpha, 6)\n\n        if self.is_circle():\n            self.type = 0  # air\n            logger.debug(\">>> air is a circle\")\n            return self.type\n\n        if is_inner:\n            self.close_to_ag = np.isclose(r_out, self.max_dist, atol=0.005)\n            close_to_opposition = greater_equal(r_in * 1.05, self.min_dist)\n            airgap_radius = r_out\n            opposite_radius = r_in\n            airgap_toleranz = -(self.max_dist - self.min_dist) / 50.0  # 2%\n        else:\n            self.close_to_ag = np.isclose(r_in, self.min_dist, atol=0.005)\n            close_to_opposition = greater_equal(self.max_dist * 1.05, r_out)\n            airgap_radius = r_in\n            opposite_radius = r_out\n            airgap_toleranz = (self.max_dist - self.min_dist) / 50.0  # 2%\n\n        self.close_to_startangle = np.isclose(self.min_angle, 0.0,\n                                              1e-04, 1e-04)\n        self.close_to_endangle = np.isclose(self.max_angle, alpha,\n                                            1e-04, 1e-04)\n\n        logger.debug(\"\\n***** mark_rotor_subregions [{}] *****\"\n                     .format(self.id))\n        logger.debug(\" - close_to_ag        : %s\", self.close_to_ag)\n        logger.debug(\" - close_to_opposition: %s\", close_to_opposition)\n        logger.debug(\" - min dist           : %3.12f\", self.min_dist)\n        logger.debug(\" - max dist           : %3.12f\", self.max_dist)\n        logger.debug(\" - airgap radius      : %3.12f\", airgap_radius)\n        logger.debug(\" - opposite radius    : %3.12f\", opposite_radius)\n        logger.debug(\" - close_to_startangle: %s\", self.close_to_startangle)\n        logger.debug(\" - close_to_endangle  : %s\", self.close_to_endangle)\n        logger.debug(\" - alpha              : %3.12f\", alpha)\n        logger.debug(\" - min_angle          : %3.12f\", self.min_angle)\n        logger.debug(\" - max_angle          : %3.12f\", self.max_angle)\n\n        if is_inner:\n            # looking for shaft\n            if close_to_opposition and not self.close_to_ag:\n                if self.is_shaft_area(center):\n                    self.type = 10  # shaft\n                    logger.debug(\"***** shaft (close to opposition)\\n\")\n                    return self.type\n\n        if close_to_opposition:\n            self.type = 1  # iron\n            logger.debug(\"***** iron (close to opposition)\\n\")\n            return self.type\n\n        if self.close_to_startangle and self.close_to_endangle:\n            self.type = 1  # iron\n            logger.debug(\"***** iron (close to both sides)\\n\")\n            return self.type\n\n        self.mag_rectangle = self.is_mag_rectangle()\n\n        if self.close_to_ag:\n            mm = self.minmax_angle_dist_from_center(center,\n                                                    airgap_radius +\n                                                    airgap_toleranz)\n            air_alpha = round(alpha_angle(mm[0], mm[1]), 3)\n            logger.debug(\" - air_alpha          : {}\".format(air_alpha))\n\n            if air_alpha / alpha < 0.2:\n                self.phi = self.get_mag_orientation()\n                self.type = 8  # air or magnet ?\n                logger.debug(\"***** air #1 (close to airgap)\\n\")\n                return self.type\n\n            if air_alpha / alpha > 0.6:\n                self.phi = self.get_mag_orientation()\n                self.type = 3  # magnet\n                logger.debug(\"***** magnet (close to airgap)\\n\")\n            else:\n                self.phi = self.get_mag_orientation()\n                self.type = 9  # iron or magnet ?\n                logger.debug(\"***** iron or magnet(close to airgap)\\n\")\n            return self.type\n\n        if self.mag_rectangle:\n            self.phi = self.get_mag_orientation()\n            self.type = 4  # magnet embedded\n            logger.debug(\"***** magnet (embedded, phi={})\\n\".format(\n                self.phi))\n            return self.type\n\n        if not (self.close_to_startangle or self.close_to_endangle):\n            self.type = 0  # air\n            logger.debug(\"***** air (somewhere)\\n\")\n            return self.type\n\n        if self.close_to_startangle:\n            if self.is_half_circle(center, self.min_angle):\n                self.type = 0  # air\n                logger.debug(\"***** air (part of a circle)\\n\")\n                return self.type\n\n        if self.close_to_endangle:\n            if self.is_half_circle(center, self.max_angle):\n                self.type = 0  # air\n                logger.debug(\"***** air (part of a circle)\\n\")\n                return self.type\n\n        self.type = 0  # air\n        logger.debug(\"***** air (remains)\\n\")\n        return self.type\n\n    def mark_unknown_subregions(self, mirrored, alpha,\n                                center, r_in, r_out):\n        logger.debug(\"mark_unknown_subregions\")\n\n        if self.is_circle():\n            self.type = 0  # air\n            logger.debug(\">>> air is a circle\")\n            return self.type\n\n        self.close_to_startangle = np.isclose(self.min_angle, 0.0)\n        self.close_to_endangle = np.isclose(self.max_angle, alpha)\n\n        if self.is_mag_rectangle():\n            self.type = 4  # magnet embedded\n            logger.debug(\">>> magnet embedded\")\n            self.phi = self.get_mag_orient_rectangle()\n            return self.type\n\n        close_to_max_radius = np.isclose(r_out, self.max_dist)\n        close_to_min_radius = np.isclose(r_in, self.min_dist)\n\n        if close_to_max_radius and close_to_min_radius:\n            self.type = 1  # iron\n            logger.debug(\">>> iron close to min- and max-radius\")\n            return self.type\n\n        if self.close_to_startangle and self.close_to_endangle:\n            self.type = 1  # iron\n            logger.debug(\">>> iron close to start- and end-angle\")\n            return self.type\n\n        self.type = 0  # air\n        logger.debug(\">>> air remains\")\n        return self.type\n\n    def area_size(self):\n        nodes = [n for n in self.list_of_nodes()]\n        return area_size(nodes)\n\n    def set_surface(self, mirrored):\n        self.surface = self.area_size()\n        if self.close_to_endangle and mirrored:\n            self.surface = self.area_size() * 2.0\n        else:\n            self.surface = self.area_size()\n\n    def print_area(self):\n        center = [0.0, 0.0]\n        for s in self.area:\n            mm = s.minmax_angle_from_center(center)\n            print(\" --- angle min={}, max={}\".format(mm[0], mm[1]))\n\n    def __lt__(self, a):\n        if self.symmetry != a.symmetry:\n            return self.symmetry > a.symmetry\n\n        if self.sym_type != a.sym_type:\n            return self.sym_type > a.sym_type\n\n        if self.count != a.count:\n            return self.count > a.count\n\n        if not np.isclose(self.height, a.height):\n            return self.height > a.height\n\n        if self.sym_tolerance > 0.0:\n            if not np.isclose(round(self.min_dist, 4),\n                              round(a.min_dist, 4), 1e-03,\n                              self.sym_tolerance):\n                return less_equal(self.min_dist, a.min_dist)\n            if not np.isclose(round(self.max_dist, 4),\n                              round(a.max_dist, 4), 1e-03,\n                              self.sym_tolerance):\n                return less_equal(self.max_dist, a.max_dist)\n            if not np.isclose(round(self.alpha, 2),\n                              round(a.alpha, 2), 1e-01, 1e-01):\n                return less_equal(self.alpha, a.alpha)\n        else:\n            if not np.isclose(round(self.min_dist, 2),\n                              round(a.min_dist, 2)):\n                return less_equal(self.min_dist, a.min_dist)\n            if not np.isclose(round(self.max_dist, 2),\n                              round(a.max_dist, 2)):\n                return less_equal(self.max_dist, a.max_dist)\n            if not np.isclose(round(self.alpha, 2),\n                              round(a.alpha, 2), 1e-01, 1e-02):\n                return less_equal(self.alpha, a.alpha)\n\n        return self.min_angle < a.min_angle\n\n    def nested_areas_inside(self):\n        for id, a in self.areas_inside.items():\n            yield id\n            for i in a.nested_areas_inside():\n                yield i\n\n    def list_of_nested_areas_inside(self):\n        for id, a in self.areas_inside.items():\n            for i in a.nested_areas_inside():\n                yield i\n\n    def crunch_area(self, geom):\n        n1_prev = None\n        e_prev = None\n        logger.debug(\"crunch area %s\", self.identifier())\n\n        if self.is_circle():\n            return 0\n\n        c = 0\n        for n1, n2, e in self.list_of_elements():\n            if e_prev is not None:\n                if len([nbr for nbr in geom.g.neighbors(n1)]) == 2:\n                    e_new = e_prev.concatenate(n1_prev, n2, e)\n                    if e_new is not None:\n                        e_prev_dict = geom.g.get_edge_data(n1_prev, n1)\n                        e_dict = geom.g.get_edge_data(n1, n2)\n\n                        logger.debug(\"--> remove from %s to %s [%s, %s, %s]\",\n                                     n1_prev,\n                                     n1,\n                                     e_prev_dict[0],\n                                     e_prev_dict[1],\n                                     e_prev_dict[2])\n                        logger.debug(\"    remove %s\", e_prev)\n                        geom.remove_edge(e_prev)\n\n                        logger.debug(\"--> remove from %s to %s [%s, %s, %s]\",\n                                     n1,\n                                     n2,\n                                     e_dict[0],\n                                     e_dict[1],\n                                     e_dict[2])\n                        logger.debug(\"    remove %s\", e)\n                        if e.get_node_number(n1) == 1:\n                            flag1 = e_dict[1]\n                            flag2 = e_dict[2]\n                        else:\n                            flag1 = e_dict[2]\n                            flag2 = e_dict[1]\n                        geom.remove_edge(e)\n\n                        logger.debug(\"--> add from %s to %s\",\n                                     n1_prev,\n                                     n2)\n                        logger.debug(\"    add %s\", e_new)\n                        geom.add_edge(n1_prev, n2, e_new)\n\n                        e_new_dict = geom.g.get_edge_data(n1_prev, n2)\n                        e_new_dict[0] = True\n                        if e_new.get_node_number(n1_prev) == 1:\n                            e_new_dict[1] = flag1\n                            e_new_dict[2] = flag2\n                        else:\n                            e_new_dict[1] = flag2\n                            e_new_dict[2] = flag1\n\n                        logger.debug(\"    new dict: [%s, %s, %s]\",\n                                     e_new_dict[0],\n                                     e_new_dict[1],\n                                     e_new_dict[2])\n                        e_prev = e_new\n                        c += 1\n                        continue\n\n            n1_prev = n1\n            e_prev = e\n        return c\n\n    def __str__(self):\n        return \"Area {}\\n\".format(self.id) + \\\n            \"distance: from {} to {}\\n\".\\\n            format(round(self.min_dist, 4), round(self.max_dist, 4)) + \\\n            \"height..: {}\\n\".format(self.height) + \\\n            \"alpha...: {}\\n\".format(self.alpha) + \\\n            \"angle...: from {} to {}\\n\".\\\n            format(round(self.min_angle, 6), round(self.max_angle, 6)) + \\\n            \"delta...: {}\\n\".format(self.delta) + \\\n            \"number..: {}\\n\".format(self.count) + \\\n            \"equal...: {}\\n\".format(len(self.equal_areas)) + \\\n            \"symmetry: {}\\n\".format(self.symmetry) + \\\n            \"sym_type: {}\".format(self.sym_type)\n", "meta": {"hexsha": "1ed1f911ec4d3a75bd6835f5b5a827f04e1b073e", "size": 52496, "ext": "py", "lang": "Python", "max_stars_repo_path": "femagtools/dxfsl/area.py", "max_stars_repo_name": "dapu/femagtools", "max_stars_repo_head_hexsha": "95eaf750adc2013232cdf482e523b3900ac6eb08", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2016-09-07T12:17:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T11:43:24.000Z", "max_issues_repo_path": "femagtools/dxfsl/area.py", "max_issues_repo_name": "dapu/femagtools", "max_issues_repo_head_hexsha": "95eaf750adc2013232cdf482e523b3900ac6eb08", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 63, "max_issues_repo_issues_event_min_datetime": "2016-09-11T12:04:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T13:22:16.000Z", "max_forks_repo_path": "femagtools/dxfsl/area.py", "max_forks_repo_name": "dapu/femagtools", "max_forks_repo_head_hexsha": "95eaf750adc2013232cdf482e523b3900ac6eb08", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2017-07-12T13:05:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-08T11:43:26.000Z", "avg_line_length": 35.7358747447, "max_line_length": 79, "alphanum_fraction": 0.4893515696, "include": true, "reason": "import numpy,import networkx", "num_tokens": 12505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.1816823999335448}}
{"text": "\"\"\"\nModule for making output to gadget, spectra from a gadget file\n\"\"\"\nfrom __future__ import print_function, absolute_import\nfrom numpy import vstack, float64, arange, uint32, array, zeros, load, cumsum, hstack, float32, empty\nimport pickle\nfrom iccpy.gadget import binary_snapshot_io, load_ICsnapshot\nfrom .log import null_log\nfrom . import grid\n\nMAX_REC_BYTES = 2**31 - 1 # dont write ICs with too many bytes in the record\n\ndef gadget(a,H0,boxsize,omegaM,omegaL,particle_file,out_name='out/IC.dat',use_double=True, dm_only=False, log=null_log):\n    \"\"\" Create a gadget initial conditions file \"\"\"\n    \n    out_dtype = {True:float64,False:float32}[use_double]\n\n    print('Reading', particle_file, file=log)\n    f = open(particle_file, 'rb')\n    dm_nums = load(f)\n    print('%d different masses of DM particles found'%len(dm_nums), file=log)\n    if len(dm_nums)>4:\n        print('Cannot make gadget files with more than 4 dm masses, we need',file=log)\n        print('2 for gas+stars, and only 6 available slots!', file=log)\n        raise Exception('Too many dm masses')\n\n                              \n    print('Reading masses', file=log)\n    if not dm_only:\n        gas_mass = float(load(f))\n    dm_mass = load(f)\n\n    print('Reading positions', file=log)\n    if dm_only:\n        dm_pos = load(f)\n        print('Scaling positions to kpc/h', file=log)\n        pos = (dm_pos * 1e3).astype(out_dtype) # Convert to kpc/h\n        print('pos', pos.shape, 'in', pos.min(), pos.max(), file=log)\n        num_particles = [0] + list(dm_nums)\n\n        mass_header = [0] + [mass*1e-10 for mass in dm_mass]\n    else:\n        gas_pos = load(f)\n        dm_pos = load(f)\n\n        print('Scaling positions to kpc/h', file=log)\n        pos = (vstack((gas_pos, dm_pos)) * 1e3).astype(out_dtype) # Convert to kpc/h\n        print('pos', pos.shape, 'in', pos.min(), pos.max(), file=log)\n        num_particles = [gas_pos.shape[0]] + list(dm_nums)\n        mass_header = [gas_mass*1e-10] + [mass*1e-10 for mass in dm_mass]\n    \n    ids = arange(1,pos.shape[0]+1).astype(uint32) # TODO: One day we will have more than 4 billion particles...\n    print('Reading velocities', file=log)\n    if dm_only:\n        dm_vel = load(f)\n        vel = dm_vel.astype(out_dtype)\n    else:\n        gas_vel = load(f)\n        dm_vel = load(f)\n        vel = vstack((gas_vel, dm_vel)).astype(out_dtype)\n\n    f.close()\n\n    if len(mass_header)==5:\n        # Account for stars  (type 4)\n        mass_header = array(mass_header[:4] + [0] + mass_header[4:5])\n        num_particles = array(num_particles[:4] + [0] + num_particles[4:5])\n    else:\n        # need 6 particle types for gadget\n        pad_to_6 = [0]*(6-len(mass_header))\n        mass_header = array(mass_header+pad_to_6)\n        num_particles = array(num_particles + pad_to_6)\n\n    print('Particle masses', mass_header, file=log)\n    print('Number of particles', num_particles, file=log)\n\n    gas_temp = zeros(num_particles[0], dtype=out_dtype)\n\n    flag_double = {True:1,False:0}[use_double]\n\n    # Largest arrays are the coordinates (and velocities). Check that they meet array bounds (64 bit floats)\n    if pos.size * 4 *(1+flag_double) > MAX_REC_BYTES:\n        num_files = int((pos.size * 4 * (1+flag_double)) / MAX_REC_BYTES) + 1\n        print('Too many particles for a single gadget file, splitting into', num_files, 'files', file=log)\n\n        for i,(num_particles_thisfile, segments) in enumerate(split_particles(num_particles, num_files)):\n            # Particle data just for this file\n            pos_i = vstack([pos[i0:i1] for i0,i1 in segments])\n            vel_i = vstack([vel[i0:i1] for i0,i1 in segments])\n            ids_i = hstack([ids[i0:i1] for i0,i1 in segments])\n            if num_particles_thisfile[0]>0:\n                # Have gas\n                gas_temp_thisfile = zeros(num_particles_thisfile[0], dtype=out_dtype)\n                extra_data = [gas_temp_thisfile]\n            else:\n                extra_data = []\n            print('Number of particles in this file', num_particles_thisfile, file=log)\n            \n            mass_i = array(mass_header).copy()\n            for ptype,np in enumerate(num_particles_thisfile):\n                if np==0:\n                    mass_i[ptype]=0\n\n            header = dict((('num_particles', num_particles_thisfile),\n                           ('mass', mass_i), ('time',float(a)), ('redshift',float(1.0/a - 1)), \n                           ('flag_sfr',0) , ('flag_feedback',0), \n                           ('num_particles_total', num_particles), \n                           ('flag_cooling',0), ('num_files',num_files), ('boxsize',float(boxsize*1000)), \n                           ('omega0', float(omegaM)), ('omegaLambda', float(omegaL)), ('hubble0', float(H0/100.0)), ('flag_stellarage',0), \n                           ('buffer', [0]*56), ('flag_metals', 0), ('npartTotalHighWord', [0,0,0,0,0,0]), \n                           ('flag_entropy_instead_u', 0), ('flag_doubleprecision', flag_double)))\n        \n            out_i = out_name + '.%d'%i\n            print('Writing gadget snapshot', out_i, file=log)\n            binary_snapshot_io.write_snapshot_file(out_i, header, pos_i, vel_i, ids_i, None, extra_data)\n\n    else:\n        \n        header = dict((('num_particles', num_particles),\n                       ('mass', mass_header), ('time',float(a)), ('redshift',float(1.0/a - 1)), \n                       ('flag_sfr',0) , ('flag_feedback',0), \n                       ('num_particles_total', num_particles), \n                       ('flag_cooling',0), ('num_files',1), ('boxsize',float(boxsize*1000)), \n                       ('omega0', float(omegaM)), ('omegaLambda', float(omegaL)), ('hubble0', float(H0/100.0)), ('flag_stellarage',0), \n                       ('buffer', [0]*56), ('flag_metals', 0), ('npartTotalHighWord', [0,0,0,0,0,0]), \n                       ('flag_entropy_instead_u', 0), ('flag_doubleprecision', flag_double)))\n        \n        print('Writing gadget snapshot', out_name, file=log)\n        binary_snapshot_io.write_snapshot_file(out_name, header, pos, vel, ids, None, [gas_temp])\n        \n\ndef split_particles(num_particles, num_files):\n    \"\"\"\n    num_particles - number of particles in each type\n    num_files -\n\n    returns iterable of (numparts_thisfile, segments) for each file\n    \"\"\"\n    npi = []\n    parts_per_file = [p/num_files + 1 for p in num_particles]\n    \n\n    for i in range(num_files):\n        segments = []\n        np_thisfile = []\n        for ptype, np_ptype in enumerate(num_particles):\n            if np_ptype==0:\n                np_thisfile.append(0)\n                continue\n            i0 = i * parts_per_file[ptype]\n            i1 = min((i+1) * parts_per_file[ptype], np_ptype)\n            np_thisfile.append(i1-i0)\n            istart = i0 + sum(num_particles[:ptype])\n            iend = i1 +  sum(num_particles[:ptype])\n            segments.append((istart,iend))\n\n        \n        yield tuple(np_thisfile), segments\n        continue\n\n                \n                \ndef _IC_matterspec(InitCondFile, grid_n, log):\n    \"\"\"\n\n    Find the Fourier modes of the matter distribution of a Gadget format 1\n    IC snapshot (e.g. produced by the gadget function above).\n\n    InitCondFile - Name of the format 1 IC file\n    grid_n       - n modes (e.g. 32 for a 32^3 FFT)\n    \n    returns\n    modes -  cubic array of modes (complex)\n    box_size - the width of the box\n\n    \"\"\"\n    snap = load_ICsnapshot(InitCondFile)\n\n    boxsize = float(snap.header.boxsize)\n    redshift = float(snap.header.redshift)\n\n    a = float(snap.header.time)\n    print('Expansion factor', a, file=log)\n    print('Box size (kpc/h)', boxsize, file=log)\n    print('Redshift', redshift, file=log)\n\n    num_parts = snap.header.num_particles_total\n    total_parts = sum(num_parts)\n\n    print('Number of particles', total_parts, num_parts, file=log)\n\n    prec = float64\n    \n    pos = empty((3,total_parts), dtype=prec)\n    mass = empty((total_parts,), dtype=prec)\n    idx = cumsum(num_parts)\n    idx0 = idx - num_parts\n\n    for ptype in range(6):\n        print('Reading', num_parts[ptype], 'particles of type', ptype, file=log)\n        \n\n\n        smass = snap.mass[ptype]\n\n        mass[idx0[ptype]:idx[ptype]] = smass\n        spos = snap.pos[ptype]\n        for i in range(3):\n            pos[i][idx0[ptype]:idx[ptype]] = spos[:,i]\n\n    print('Pos in', pos.min(axis=0), pos.max(axis=0), file=log)\n    print('Mass in', mass.min(), mass.max(), file=log)\n\n    print('Building CIC modes', file=log)\n    modes = grid.cic_modes(pos, boxsize, grid_n, mass)\n\n    # convert box size to Mpc/h\n    boxsize = boxsize * 1e-3\n    return modes, boxsize, a\n\n                \ndef make_spec_from_ICs(InitCondFile, spec_name, ngrid=64, log=null_log):\n    \"\"\" Find the matter power spectrum for the given IC file \"\"\"\n    print('Reading IC file', file=log)\n    modes, boxsize, expansion = _IC_matterspec(InitCondFile, ngrid, log)\n    print('Making power spectrum bins for box size', boxsize, file=log)\n\n    kmin, kmax, kvol, kmid_bins, powerspec, p_err = grid.modes_to_pspec(modes, boxsize)\n\n    print('Writing power spectrum to', spec_name, file=log)\n    f = open(spec_name, 'w')\n    f.write('#ICs = %s\\n'%(InitCondFile,))\n    f.write('#Expansion factor = %.5f\\n'%expansion)\n    f.write('#\\n#k values in h Mpc^-1, P(k) in Mpc^3 h^-1 (although note factor (2pi)^-3 compared to other power spectrum definitions)\\n')\n    f.write('#k_bin_min k_bin_max k_bin_vol Power power_error\\n')\n    for l,h,vol,p,er in zip(kmin, kmax, kvol, powerspec, p_err):\n        f.write('%8.5f %8.5f %6.5e %6.5e %6.5e\\n'%(l,h,vol,p,er))\n    f.close()\n\n    print('Finished writing spectrum to', spec_name, file=log)\n            \n        \n\n", "meta": {"hexsha": "604dd01a2ebd6e428c3f7c6d630baf881a149d6d", "size": 9687, "ext": "py", "lang": "Python", "max_stars_repo_path": "lizard/gadget.py", "max_stars_repo_name": "pec27/lizard", "max_stars_repo_head_hexsha": "5bfd0dae3b02c0c12eb72b71b6ef2b47ae0c83dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-09T13:21:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-09T13:21:47.000Z", "max_issues_repo_path": "lizard/gadget.py", "max_issues_repo_name": "pec27/lizard", "max_issues_repo_head_hexsha": "5bfd0dae3b02c0c12eb72b71b6ef2b47ae0c83dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lizard/gadget.py", "max_forks_repo_name": "pec27/lizard", "max_forks_repo_head_hexsha": "5bfd0dae3b02c0c12eb72b71b6ef2b47ae0c83dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-11-06T12:52:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-04T16:10:11.000Z", "avg_line_length": 39.7008196721, "max_line_length": 139, "alphanum_fraction": 0.6017342831, "include": true, "reason": "from numpy", "num_tokens": 2585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.1816823951088544}}
{"text": "from .experiment import Experiment, lindhard_quenching_factor, _get_nr_resolution\nimport dddm\nimport numpy as np\nfrom functools import partial\nfrom abc import ABC\n\nexport, __all__ = dddm.exporter()\n\n\nclass _BaseXenonNt(Experiment, ABC):\n    target_material = 'Xe'\n    exposure_tonne_year = 20  # https://arxiv.org/pdf/2007.08796.pdf\n    location = \"XENON\"\n\n    # https://arxiv.org/abs/1608.05381\n    _energy_parameters = {'k': 0.1735, 'Z': 54}\n\n\n@export\nclass XenonNtNr(_BaseXenonNt):\n    detector_name = 'XENONnT_NR'\n    __version__ = '0.0.0'\n\n    # Use https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.126.091301\n    energy_threshold_kev = 1.6  # keVnr\n\n    # Combined cut & detection efficiency as in\n    # https://arxiv.org/pdf/2007.08796.pdf\n    cut_efficiency = 0.83\n    detection_efficiency = 1\n\n    interaction_type = 'SI'\n\n    def background_function(self, energies_in_kev):\n        \"\"\"\n        :return: NR background for Xe detector in events/keV/t/yr\n        \"\"\"\n        # From https://arxiv.org/pdf/2007.08796.pdf\n        bg_rate = 2.2e-3  # 1/(keV * t * yr)\n\n        # Assume flat background over entire energy range\n        # True to first order below 200 keV\n        if (e_min := energies_in_kev[0]) > (e_max := energies_in_kev[-1]) or e_max > 200:\n            mes = f'Assume flat background only below 200 keV ({e_min}, {e_max})'\n            raise ValueError(mes)\n        return self._flat_background(len(energies_in_kev), bg_rate)\n\n    def resolution(self, energies_in_kev):\n        \"\"\"\n        Use _get_nr_resolution to calculate the energy resolution.\n\n        :param energies_in_kev: NR energies to evaluate the resolution\n            function at\n        :return:\n        \"\"\"\n        energy_nr_to_energy_ee_function = partial(energy_nr_to_energy_ee,\n                                                  **self._energy_parameters)\n\n        # Now get e_ee and sigma_ee based on that we can calculate the\n        # energy resolution for the NRs\n        energy_ee = energy_nr_to_energy_ee_function(energies_in_kev)\n        energy_res_ee = xenon_1t_er_resolution(energy_ee)\n\n        return _get_nr_resolution(energies_in_kev,\n                                  energy_nr_to_energy_ee_function,\n                                  base_resolution=energy_res_ee,\n                                  )\n\n\n@export\nclass XenonNtMigdal(_BaseXenonNt):\n    detector_name = 'XENONnT_Migdal'\n    __version__ = '0.0.0'\n\n    # assume https://arxiv.org/abs/2006.09721\n    energy_threshold_kev = 1  # keVer\n\n    # Combined cut & detection efficiency as in\n    # https://arxiv.org/pdf/2007.08796.pdf\n    cut_efficiency = 0.82\n    detection_efficiency = 1\n\n    interaction_type = 'migdal_SI'\n\n    def resolution(self, energies_in_kev):\n        \"\"\"Assume the same as the 1T resolution\"\"\"\n        return xenon_1t_er_resolution(energies_in_kev)\n\n    def background_function(self, energies_in_kev):\n        \"\"\"\n        :return: ER background for Xe detector in events/keV/t/yr\n        \"\"\"\n        # From https://arxiv.org/pdf/2007.08796.pdf\n        bg_rate = 12.3  # 1/(keV * t * yr)\n\n        # Assume flat background over entire energy range\n        # True to first order below 200 keV\n        if (e_min := energies_in_kev[0]) > (e_max := energies_in_kev[-1]) or e_max > 200:\n            mes = f'Assume flat background only below 200 keV ({e_min}, {e_max})'\n            raise ValueError(mes)\n        return self._flat_background(len(energies_in_kev), bg_rate)\n\n\ndef xenon_1t_er_resolution(energies_in_kev_ee):\n    \"\"\"\n    Detector resolution of XENON1T. See e.g. 1 of\n        https://journals.aps.org/prd/pdf/10.1103/PhysRevD.102.072004\n    :param energies_in_kev_ee: energy in keVee\n    :return: resolution at energies_in_kev\n    \"\"\"\n    a = 0.310\n    b = 0.0037\n    return a * np.sqrt(energies_in_kev_ee) + b * energies_in_kev_ee\n\n\ndef energy_nr_to_energy_ee(energy_nr, k, Z):\n    return energy_nr * lindhard_quenching_factor(energy_nr, k=k, atomic_number_z=Z)\n", "meta": {"hexsha": "0c60393bc4876283a89d5c3e7fda753be5b6674e", "size": 3959, "ext": "py", "lang": "Python", "max_stars_repo_path": "dddm/detectors/xenon_nt.py", "max_stars_repo_name": "JoranAngevaare/dddm", "max_stars_repo_head_hexsha": "3461e37984bac4d850beafecc9d1881b84fb226c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dddm/detectors/xenon_nt.py", "max_issues_repo_name": "JoranAngevaare/dddm", "max_issues_repo_head_hexsha": "3461e37984bac4d850beafecc9d1881b84fb226c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 85, "max_issues_repo_issues_event_min_datetime": "2021-09-20T12:08:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:48:06.000Z", "max_forks_repo_path": "dddm/detectors/xenon_nt.py", "max_forks_repo_name": "JoranAngevaare/dddm", "max_forks_repo_head_hexsha": "3461e37984bac4d850beafecc9d1881b84fb226c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5508474576, "max_line_length": 89, "alphanum_fraction": 0.651174539, "include": true, "reason": "import numpy", "num_tokens": 1139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.1816363140424382}}
{"text": "\n# Copyright (C) 2012 Victor Semionov\n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#  * Redistributions of source code must retain the above copyright notice, this\n#    list of conditions and the following disclaimer.\n#  * Redistributions in binary form must reproduce the above copyright notice,\n#    this list of conditions and the following disclaimer in the documentation\n#    and/or other materials provided with the distribution.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\nimport os\n\nimport math\n\nimport copy\n\nimport numpy as np\n\nimport model\n\nimport params\nimport core\nimport plot\nimport output\nimport unitconv\n\n\ndef _set_geom(rm, rb):\n    old_geom = params.medium_radius, params.beam_radius\n    try:\n        params.medium_radius, params.beam_radius = rm, rb\n        return old_geom\n    except:\n        params.medium_radius, params.beam_radius = old_geom\n        raise\n\ndef _ref_signal_fluence(active_medium, (rho, phi), (integrator, amp), count_t, ref_pulse, lower_decay):\n    pulse_count = params.train_pulse_count\n    \n    upper = np.vectorize(active_medium.initial_inversion.inversion)(rho, phi, amp.Z)\n    lower = np.zeros(len(amp.Z))\n    population = (upper, lower)\n    \n    amp._init_time(ref_pulse, count_t)\n    input_density = np.vectorize(ref_pulse.density)(amp.T)\n    \n    pulse_fluences = np.empty(pulse_count)\n    \n    for pnum in range(pulse_count):\n        density_out, population_final = amp.amplify(rho, phi, None, None, T=amp.T, initial_population=population, input_density=input_density)\n        \n        upper = np.copy(population_final[0])\n        lower = population_final[1] * lower_decay\n        population = (upper, lower)\n        \n        fluence_out = integrator.integrate(amp.T, density_out) * active_medium.light_speed\n        pulse_fluences[pnum] = fluence_out\n    \n    fluence_out = pulse_fluences[::-1].sum()\n    fluence_out = model.energy.energy(params.lasing_wavelen, fluence_out)\n    \n    return fluence_out\n\n\ndef compare_depop_models(dirname):\n    filename = lambda name: os.path.join(dirname, name)\n    \n    if not params.ext_depop_models:\n        return\n    \n    print output.div_line\n    print \"comparing depopulation models\"\n    \n    active_medium = core.create_medium(None)\n    pump_system = model.pump.PumpSystem(params.pump_wavelen, params.pump_duration, params.pump_power, params.pump_efficiency)\n    data = []\n    for depop_model_class in params.ext_depop_models:\n        depop_model_label = depop_model_class.descr\n        print depop_model_label\n        depop_model = core.create_depop_model(active_medium, depop_model_class)\n        inv = params.inverter_class(active_medium, pump_system, depop_model)\n        inv.invert(params.inversion_rtol, params.inversion_min_count_t)\n        depop_rate = np.vectorize(depop_model.rate)(inv.inversion) / active_medium.volume\n        data.append((inv.T, inv.inversion, depop_rate, depop_model_class.descr, depop_model_class))\n        ref_inversion = inv.inversion[-1]\n        \n        unitconv.print_result(\"population inversion [{}]: {}\", (\"cm^-3\",), (ref_inversion,))\n        unitconv.print_result(\"depopulation rate [{}]: {}\", (\"cm^-3 s^-1\",), (depop_rate[-1],))\n    \n    if params.graphs:\n        print output.status_writing\n        dirname = os.path.join(dirname, output.models_rel_path)\n        dirname = output.init_dir(dirname)\n        data.sort(key = lambda x: x[1][-1], reverse=True)\n        Ts, inversions, depop_rates, labels, depop_model_classes = zip(*data)\n        plot.plot_data(filename(\"inversions_evo\"), \"Population Inversion Evolution\", (Ts, None, None, output.t_pump_label), (inversions, None, None, output.inversion_abs_label), labels)\n        pump_rate = pump_system.effective_pump_rate / active_medium.volume\n        abs_rate_ylim = None #(0.0, pump_rate * 1.25)\n        non_zero_Ts = [T[1:] for T in Ts]\n        non_zero_inversions = [inversion[1:] for inversion in inversions]\n        non_zero_rates = [depop_rate[1:] for depop_rate in depop_rates]\n        rel_depop_rates = [depop_rate / inversion for depop_rate, inversion in zip(non_zero_rates, non_zero_inversions)]\n        plot.plot_data(filename(\"depop_rates\"), \"Depopulation Rate\", (inversions, None, None, output.inversion_abs_label), (depop_rates, None, abs_rate_ylim, output.rate_label), labels, yvals=[(pump_rate, \"pump rate\")])\n        plot.plot_data(filename(\"depop_rates_alt\"), \"Depopulation Rate to Inversion Ratio\", (non_zero_inversions, None, None, output.inversion_abs_label), (rel_depop_rates, None, None, output.rate_rel_label), labels)\n        plot.plot_data(filename(\"depop_rates_evo\"), \"Depopulation Rate Evolution\", (Ts, None, None, output.t_pump_label), (depop_rates, None, abs_rate_ylim, output.rate_label), labels, yvals=[(pump_rate, \"pump rate\")])\n        plot.plot_data(filename(\"depop_rates_alt_evo\"), \"Depopulation Rate to Inversion Ratio Evolution\", (non_zero_Ts, None, None, output.t_pump_label), (rel_depop_rates, None, None, output.rate_rel_label), labels)\n        \n        if params.ext_alt_depop_model not in depop_model_classes:\n            return\n        alt_model_idx = depop_model_classes.index(params.ext_alt_depop_model)\n        alt_T = Ts[alt_model_idx]\n        alt_inversion = inversions[alt_model_idx]\n        altinvs = []\n        aTs = []\n        altinv_inversion_rdiffs = []\n        for cls, T, inversion in zip(depop_model_classes, Ts, inversions):\n            if cls is params.ext_alt_depop_model:\n                continue\n            uT = set(list(T) + list(alt_T))\n            aT = np.array(sorted(list(uT)))\n            altinv = np.interp(aT, alt_T, alt_inversion)[1:]\n            inv = np.interp(aT, T, inversion)[1:]\n            rdiff = np.fabs(inv - altinv) / np.fmin(inv, altinv)\n            aTs.append(aT[1:])\n            altinvs.append(altinv)\n            altinv_inversion_rdiffs.append(rdiff)\n        non_alt_labels = [label for i, label in enumerate(labels) if i != alt_model_idx]\n        plot.plot_data(filename(\"inversions_rdiff_inv\"), \"Inversion Relative Difference\", (altinvs, None, None, output.inversion_abs_label), (altinv_inversion_rdiffs, None, None, output.inversion_rdiff_label), non_alt_labels)\n        plot.plot_data(filename(\"inversions_rdiff_evo\"), \"Inversion Relative Difference Evolution\", (aTs, None, None, output.t_pump_label), (altinv_inversion_rdiffs, None, None, output.inversion_rdiff_label), non_alt_labels)\n\ndef _inversion_pump_dependence_task((i, j), (tau, pwr), active_medium, (depop_model1, depop_model2)):\n    output.show_status((i, j), params.extended_status_strides, False)\n    \n    pump_system = model.pump.PumpSystem(params.pump_wavelen, tau, pwr, params.pump_efficiency)\n    \n    inv1 = params.inverter_class(active_medium, pump_system, depop_model1)\n    inv2 = params.inverter_class(active_medium, pump_system, depop_model2)\n    \n    inversion1 = inv1.invert(params.inversion_rtol, params.inversion_min_count_t)\n    inversion2 = inv2.invert(params.inversion_rtol, params.inversion_min_count_t)\n    \n    gain_coef1 = inversion1 * active_medium.doping_agent.xsection\n    gain_coef2 = inversion2 * active_medium.doping_agent.xsection\n    \n    gain1 = math.exp(gain_coef1 * active_medium.length)\n    gain2 = math.exp(gain_coef2 * active_medium.length)\n    \n    inversion_rdiff = abs((inversion1 - inversion2) / min(inversion1, inversion2))\n    gain_rdiff = abs((gain1 - gain2) / min(gain1, gain2))\n    \n    return inversion1, inversion2, gain1, gain2, inversion_rdiff, gain_rdiff\n\ndef compute_inversion_pump_dependence(task_pool, dirname):\n    filename = lambda name: os.path.join(dirname, name)\n    \n    print output.div_line\n    print \"computing inversion dependence on pumping parameters\"\n    \n    active_medium = core.create_medium(None)\n    \n    count_tau = params.ext_opt_pump_resolution[0]\n    count_pwr = params.ext_opt_pump_resolution[1]\n    \n    Tau = np.linspace(params.ext_opt_pump_duration[0], params.ext_opt_pump_duration[1], count_tau)\n    Pwr = np.linspace(params.ext_opt_pump_power[0], params.ext_opt_pump_power[1], count_pwr)\n    \n    depop_model_class1 = params.depop_model_class\n    depop_model_class2 = params.ext_alt_depop_model\n    \n    depop_model1 = core.create_depop_model(active_medium, params.depop_model_class)\n    depop_model2 = core.create_depop_model(active_medium, params.ext_alt_depop_model)\n    \n    inversions1, inversions2, gains1, gains2, inversion_rdiffs, gain_rdiffs = task_pool.parallel_task(_inversion_pump_dependence_task, (Tau, Pwr), (), (active_medium, (depop_model1, depop_model2)))\n    \n    output.show_status((count_tau, count_pwr), params.extended_status_strides, True)\n    \n    pump_energies = np.prod(np.array(np.meshgrid(Tau, Pwr)), axis=0).T\n    stored_energies1 = model.energy.energy(params.lasing_wavelen, inversions1 * active_medium.volume)\n    stored_energies2 = model.energy.energy(params.lasing_wavelen, inversions2 * active_medium.volume)\n    \n    if params.graphs:\n        print output.status_writing\n        dirname = os.path.join(dirname, output.opt_pump_rel_path)\n        inversion_rdiff_max = params.ext_opt_inversion_rdiff_max\n        zlim = None #(0.0, inversion_rdiff_max)\n        depop_contours = [inversion_rdiff_max]\n        ref_pump_energy = params.pump_duration * params.pump_power\n        ref_pump_contours = [(pump_energies.T, ref_pump_energy, \"const. pump energy\")]\n        graph_types = [\n            (dirname, Pwr, output.pump_power_label),\n            (os.path.join(dirname, output.alt_plot_rel_path), Pwr * params.pump_efficiency / active_medium.volume, output.eff_power_density_label),\n        ]\n        for dirname, Y, ylabel in graph_types:\n            dirname = output.init_dir(dirname)\n            plot.plot_color(filename(\"energy_pump\"), \"Pump Energy\", (Tau, None, None, output. pump_duration_label), (Y, None, None, ylabel), (pump_energies.T, None, output.energy_abs_pump_label), params.out_num_auto_contours)\n            plot.plot_color(filename(\"inversion\"), \"Inversion (%s)\" % depop_model_class1.descr, (Tau, None, None, output.pump_duration_label), (Y, None, None, ylabel), (inversions1.T, None, output.inversion_abs_label), params.out_num_auto_contours, extra_contours=ref_pump_contours)\n            plot.plot_color(filename(\"inversion_alt\"), \"Inversion (%s)\" % depop_model_class2.descr, (Tau, None, None, output.pump_duration_label), (Y, None, None, ylabel), (inversions2.T, None, output.inversion_abs_label), params.out_num_auto_contours, extra_contours=ref_pump_contours)\n            plot.plot_color(filename(\"ss_gain\"), \"Small Signal Gain (%s)\" % depop_model_class1.descr, (Tau, None, None, output.pump_duration_label), (Y, None, None, ylabel), (gains1.T, None, output.gain_label), params.out_num_auto_contours, extra_contours=ref_pump_contours)\n            plot.plot_color(filename(\"ss_gain_alt\"), \"Small Signal Gain (%s)\" % depop_model_class2.descr, (Tau, None, None, output.pump_duration_label), (Y, None, None, ylabel), (gains2.T, None, output.gain_label), params.out_num_auto_contours, extra_contours=ref_pump_contours)\n            plot.plot_color(filename(\"energy_stored\"), \"Stored Energy (%s)\" % depop_model_class1.descr, (Tau, None, None, output.pump_duration_label), (Y, None, None, ylabel), (stored_energies1.T, None, output.energy_abs_stored_label), params.out_num_auto_contours, extra_contours=ref_pump_contours)\n            plot.plot_color(filename(\"energy_stored_alt\"), \"Stored Energy (%s)\" % depop_model_class2.descr, (Tau, None, None, output.pump_duration_label), (Y, None, None, ylabel), (stored_energies2.T, None, output.energy_abs_stored_label), params.out_num_auto_contours, extra_contours=ref_pump_contours)\n            plot.plot_color(filename(\"inversion_rdiff\"), \"Inversion Relative Difference\", (Tau, None, None, output.pump_duration_label), (Y, None, None, ylabel), (inversion_rdiffs.T, zlim, output.inversion_rdiff_label), params.out_num_auto_contours, depop_contours)\n            plot.plot_color(filename(\"ss_gain_rdiff\"), \"Small Signal Gain Relative Difference\", (Tau, None, None, output.pump_duration_label), (Y, None, None, ylabel), (gain_rdiffs.T, zlim, output.gain_rdiff_label), params.out_num_auto_contours, depop_contours)\n    \n    return inversions1, inversion_rdiffs\n\ndef _inversion_geom_dependence_task(i, rm, pump_system, (depop_model_class1, depop_model_class2)):\n    output.show_status((i, None), params.extended_status_strides, False)\n    \n    orig_geom = _set_geom(rm, params.beam_radius)\n    try:\n        active_medium = core.create_medium(None)\n        \n        depop_model1 = core.create_depop_model(active_medium, depop_model_class1)\n        depop_model2 = core.create_depop_model(active_medium, depop_model_class2)\n        \n        inv1 = params.inverter_class(active_medium, pump_system, depop_model1)\n        inv2 = params.inverter_class(active_medium, pump_system, depop_model2)\n        \n        inversion1 = inv1.invert(params.inversion_rtol, params.inversion_min_count_t)\n        inversion2 = inv2.invert(params.inversion_rtol, params.inversion_min_count_t)\n        \n        gain_coef1 = inversion1 * active_medium.doping_agent.xsection\n        gain_coef2 = inversion2 * active_medium.doping_agent.xsection\n        \n        gain1 = math.exp(gain_coef1 * active_medium.length)\n        gain2 = math.exp(gain_coef2 * active_medium.length)\n        \n        stored_energy1 = model.energy.energy(params.lasing_wavelen, inversion1 * active_medium.volume)\n        stored_energy2 = model.energy.energy(params.lasing_wavelen, inversion2 * active_medium.volume)\n        \n        inversion_rdiff = abs((inversion1 - inversion2) / min(inversion1, inversion2))\n        gain_rdiff = abs((gain1 - gain2) / min(gain1, gain2))\n    finally:\n        _set_geom(*orig_geom)\n    \n    return inversion1, inversion2, gain1, gain2, stored_energy1, stored_energy2, inversion_rdiff, gain_rdiff\n\ndef compute_inversion_geom_dependence(task_pool, dirname):\n    filename = lambda name: os.path.join(dirname, name)\n    \n    print output.div_line\n    print \"computing inversion dependence on geometry parameters\"\n    \n    pump_system = model.pump.PumpSystem(params.pump_wavelen, params.pump_duration, params.pump_power, params.pump_efficiency)\n    \n    min_medium_radius = params.ext_opt_geom_mediumradius[0]\n    \n    count_rm = params.ext_opt_geom_resolution[0]\n    \n    Rm = np.linspace(min_medium_radius, params.ext_opt_geom_mediumradius[1], count_rm)\n    \n    depop_model_class1 = params.depop_model_class\n    depop_model_class2 = params.ext_alt_depop_model\n    \n    inversions1, inversions2, gains1, gains2, stored_energies1, stored_energies2, inversion_rdiffs, gain_rdiffs = task_pool.parallel_task(_inversion_geom_dependence_task, (Rm,), (), (pump_system, (depop_model_class1, depop_model_class2)))\n    \n    output.show_status((count_rm, None), params.extended_status_strides, True)\n    \n    if params.graphs:\n        print output.status_writing\n        dirname = os.path.join(dirname, output.opt_geom_rel_path)\n        dirname = output.init_dir(dirname)\n        inversion_rdiff_max = params.ext_opt_inversion_rdiff_max\n        pump_energy = params.pump_duration * params.pump_power\n        energy_ylim = (0.0, pump_energy * 1.25)\n        labels = [cls.descr for cls in [depop_model_class1, depop_model_class2]]\n        plot.plot_data(filename(\"inversion\"), \"Inversion (%s)\" % depop_model_class1.descr, (Rm, None, None, output.medium_radius_label), (inversions1, None, None, output.inversion_abs_label))\n        plot.plot_data(filename(\"inversion_alt\"), \"Inversion (%s)\" % depop_model_class2.descr, (Rm, None, None, output.medium_radius_label), (inversions2, None, None, output.inversion_abs_label))\n        plot.plot_data(filename(\"inversions\"), \"Population Inversion\", ([Rm]*2, None, None, output.medium_radius_label), ([inversions1, inversions2], None, None, output.inversion_abs_label), legend=labels)\n        plot.plot_data(filename(\"ss_gain\"), \"Small Signal Gain (%s)\" % depop_model_class1.descr, (Rm, None, None, output.medium_radius_label), (gains1, None, None, output.gain_label))\n        plot.plot_data(filename(\"ss_gain_alt\"), \"Small Signal Gain (%s)\" % depop_model_class2.descr, (Rm, None, None, output.medium_radius_label), (gains2, None, None, output.gain_label))\n        plot.plot_data(filename(\"ss_gains\"), \"Small Signal Gain\", ([Rm]*2, None, None, output.medium_radius_label), ([gains1, gains2], None, None, output.gain_label), legend=labels)\n        plot.plot_data(filename(\"energy_stored\"), \"Stored Energy (%s)\" % depop_model_class1.descr, (Rm, None, None, output.medium_radius_label), (stored_energies1, None, energy_ylim, output.energy_abs_stored_label), yvals=[(pump_energy, \"pump energy\")])\n        plot.plot_data(filename(\"energy_stored_alt\"), \"Stored Energy (%s)\" % depop_model_class2.descr, (Rm, None, None, output.medium_radius_label), (stored_energies2, None, energy_ylim, output.energy_abs_stored_label), yvals=[(pump_energy, \"pump energy\")])\n        plot.plot_data(filename(\"energies_stored\"), \"Stored Energy\", ([Rm]*2, None, None, output.medium_radius_label), ([stored_energies1, stored_energies2], None, energy_ylim, output.energy_abs_stored_label), legend=labels, yvals=[(pump_energy, \"pump energy\")])\n        plot.plot_data(filename(\"inversion_rdiff\"), \"Inversion Relative Difference\", (Rm, None, None, output.medium_radius_label), (inversion_rdiffs, None, None, output.inversion_rdiff_label), yvals=[(inversion_rdiff_max, None)])\n        plot.plot_data(filename(\"ss_gain_rdiff\"), \"Small Signal Gain Relative Difference\", (Rm, None, None, output.medium_radius_label), (gain_rdiffs, None, None, output.gain_rdiff_label), yvals=[(inversion_rdiff_max, None)])\n    \n    return inversions1, inversion_rdiffs\n\ndef _fluence_pump_dependence_task((i, j), (tau, pwr), inversion, active_medium, (rho, phi), (int_type, amp_type), (count_z, count_t), ref_pulse, lower_decay):\n    output.show_status((i, j), params.extended_status_strides, False)\n    \n    initial_inversion = model.inversion.UniformInversion(inversion)\n    active_medium.initial_inversion = initial_inversion\n    \n    integrator = model.integrator.DomainIntegrator(int_type)\n    amp = amp_type(active_medium, count_z)\n    \n    fluence_out = _ref_signal_fluence(active_medium, (rho, phi), (integrator, amp), count_t, ref_pulse, lower_decay)\n    return fluence_out\n\ndef compute_fluence_pump_dependence(task_pool, dirname, inversions, (int_type, amp_type), (count_z, count_t)):\n    filename = lambda name: os.path.join(dirname, name)\n    \n    print output.div_line\n    print \"computing fluence dependence on pumping parameters\"\n    \n    active_medium = core.create_medium(None)\n    input_beam = core.create_beam()\n    ref_pulse = core.create_pulse(active_medium, input_beam, input_beam.rho_ref, input_beam.phi_ref)\n    pulse_train = core.create_train(ref_pulse)\n    \n    lower_decay = model.amplifier.lower_state_decay(active_medium, pulse_train)\n    \n    count_tau = params.ext_opt_pump_resolution[0]\n    count_pwr = params.ext_opt_pump_resolution[1]\n    \n    Tau = np.linspace(params.ext_opt_pump_duration[0], params.ext_opt_pump_duration[1], count_tau)\n    Pwr = np.linspace(params.ext_opt_pump_power[0], params.ext_opt_pump_power[1], count_pwr)\n    \n    rho, phi = input_beam.rho_ref, input_beam.phi_ref\n    fluences = task_pool.parallel_task(_fluence_pump_dependence_task, (Tau, Pwr), (inversions,), (active_medium, (rho, phi), (int_type, amp_type), (count_z, count_t), ref_pulse, lower_decay))\n    \n    output.show_status((count_tau, count_pwr), params.extended_status_strides, True)\n    \n    if params.graphs:\n        print output.status_writing\n        dirname = os.path.join(dirname, output.opt_pump_rel_path)\n        fluence_max = params.ext_opt_fluence_max\n        zlim = None #(0.0, fluence_max)\n        contours = [fluence_max]\n        graph_types = [\n            (dirname, Pwr, output.pump_power_label),\n            (os.path.join(dirname, output.alt_plot_rel_path), Pwr * params.pump_efficiency / active_medium.volume, output.eff_power_density_label),\n        ]\n        for dirname, Y, ylabel in graph_types:\n            dirname = output.init_dir(dirname)\n            plot.plot_color(filename(\"fluence_out_max\"), \"Maximum Output Fluence\", (Tau, None, None, output.pump_duration_label), (Y, None, None, ylabel), (fluences.T, zlim, output.fluence_abs_label_energy), params.out_num_auto_contours, contours)\n    \n    return fluences\n\ndef _fluence_geom_dependence_task((i, j), (rm, rb), inversion, (int_type, amp_type), (count_z, count_t)):\n    output.show_status((i, j), params.extended_status_strides, False)\n    \n    orig_geom = _set_geom(rm, rb)\n    try:\n        active_medium = core.create_medium(inversion)\n        input_beam = core.create_beam()\n        rho, phi = input_beam.rho_ref, input_beam.phi_ref\n        ref_pulse = core.create_pulse(active_medium, input_beam, rho, phi)\n        pulse_train = core.create_train(ref_pulse)\n        \n        lower_decay = model.amplifier.lower_state_decay(active_medium, pulse_train)\n        \n        integrator = model.integrator.DomainIntegrator(int_type)\n        amp = amp_type(active_medium, count_z)\n        \n        fluence_out = _ref_signal_fluence(active_medium, (rho, phi), (integrator, amp), count_t, ref_pulse, lower_decay)\n    finally:\n        _set_geom(*orig_geom)\n    \n    return fluence_out\n\ndef compute_fluence_geom_dependence(task_pool, dirname, inversions, (int_type, amp_type), (count_z, count_t)):\n    filename = lambda name: os.path.join(dirname, name)\n    \n    print output.div_line\n    print \"computing fluence dependence on geometry parameters\"\n    \n    min_medium_radius = params.ext_opt_geom_mediumradius[0]\n    min_beam_radius = params.ext_opt_geom_beamradius[0]\n    \n    count_rm = params.ext_opt_geom_resolution[0]\n    count_rb = params.ext_opt_geom_resolution[1]\n    \n    Rm = np.linspace(min_medium_radius, params.ext_opt_geom_mediumradius[1], count_rm)\n    Rb = np.linspace(min_beam_radius, params.ext_opt_geom_beamradius[1], count_rb)\n    \n    inversions = np.meshgrid(inversions, Rb)[0].T\n    fluences = task_pool.parallel_task(_fluence_geom_dependence_task, (Rm, Rb), (inversions,), ((int_type, amp_type), (count_z, count_t)))\n    \n    output.show_status((count_rm, count_rb), params.extended_status_strides, True)\n    \n    if params.graphs:\n        print output.status_writing\n        dirname = os.path.join(dirname, output.opt_geom_rel_path)\n        dirname = output.init_dir(dirname)\n        fluence_max = params.ext_opt_fluence_max\n        zlim = None #(0.0, fluence_max)\n        contours = [fluence_max]\n        plot.plot_color(filename(\"fluence_out_max\"), \"Maximum Output Fluence\", (Rm, None, None, output.medium_radius_label), (Rb, None, None, output.beam_radius_label), (fluences.T, zlim, output.fluence_abs_label_energy), params.out_num_auto_contours, contours)\n    \n    return fluences\n\ndef compute_pump_constraints(dirname, inversion_rdiffs, max_fluences):\n    filename = lambda name: os.path.join(dirname, name)\n    \n    print output.div_line\n    print \"computing pumping parameters domain constraints\"\n    \n    active_medium = core.create_medium(None)\n    \n    count_tau = params.ext_opt_pump_resolution[0]\n    count_pwr = params.ext_opt_pump_resolution[1]\n    \n    Tau = np.linspace(params.ext_opt_pump_duration[0], params.ext_opt_pump_duration[1], count_tau)\n    Pwr = np.linspace(params.ext_opt_pump_power[0], params.ext_opt_pump_power[1], count_pwr)\n    \n    inversion_rdiff_max = params.ext_opt_inversion_rdiff_max\n    fluence_max = params.ext_opt_fluence_max\n    contours = [\n        (inversion_rdiffs.T, inversion_rdiff_max, \"depopulation\"),\n        (max_fluences.T, fluence_max, \"damage\"),\n    ]\n    contour_comps = [1.0, 1.0]\n    \n    if params.graphs:\n        print output.status_writing\n        dirname = os.path.join(dirname, output.opt_pump_rel_path)\n        graph_types = [\n            (dirname, Pwr,output. pump_power_label),\n            (os.path.join(dirname, output.alt_plot_rel_path), Pwr * params.pump_efficiency / active_medium.volume, output.eff_power_density_label),\n        ]\n        for dirname, Y, ylabel in graph_types:\n            dirname = output.init_dir(dirname)\n            plot.plot_contour(filename(\"constraints\"), \"Pumping Parameters Domain Constraints\", (Tau, None, None, output.pump_duration_label), (Y, None, None, ylabel), contours)\n    \n    return (contours, None, None), (contour_comps, None, None)\n\ndef compute_geom_constraints(dirname, inversion_rdiffs, max_fluences):\n    filename = lambda name: os.path.join(dirname, name)\n    \n    print output.div_line\n    print \"computing geometry parameters domain constraints\"\n    \n    count_rm = params.ext_opt_geom_resolution[0]\n    count_rb = params.ext_opt_geom_resolution[1]\n    \n    Rm = np.linspace(params.ext_opt_geom_mediumradius[0], params.ext_opt_geom_mediumradius[1], count_rm)\n    Rb = np.linspace(params.ext_opt_geom_beamradius[0], params.ext_opt_geom_beamradius[1], count_rb)\n    \n    inversion_rdiff_max = params.ext_opt_inversion_rdiff_max\n    fluence_max = params.ext_opt_fluence_max\n    contours = [\n        (max_fluences.T, fluence_max, \"damage\"),\n    ]\n    contour_comps = [1.0]\n    \n    rm_depop = np.interp(inversion_rdiff_max, inversion_rdiffs[::-1], Rm[::-1])\n    xvals = [(rm_depop, \"depopulation\")]\n    xval_comps = [-1.0]\n    \n    if params.graphs:\n        print output.status_writing\n        dirname = os.path.join(dirname, output.opt_geom_rel_path)\n        dirname = output.init_dir(dirname)\n        plot.plot_contour(filename(\"constraints\"), \"Geometry Parameters Domain Constraints\", (Rm, None, None, output.medium_radius_label), (Rb, None, None, output.beam_radius_label), contours, xvals=xvals)\n    \n    return (contours, xvals, None), (contour_comps, xval_comps, None)\n\ndef optimize_output(domain, outputs, limits, comparisons, price):\n    params1, params2 = domain\n    contours, xvals, yvals = limits\n    contour_comps, xval_comps, yval_comps = comparisons\n    optimum = None\n    for i, p1 in enumerate(params1):\n        for j, p2 in enumerate(params2):\n            safe = True\n            if contours:\n                for limit, comp in zip(contours, contour_comps):\n                    Z, zmax, _ = limit\n                    Z = Z.T\n                    if Z[i, j] * comp > zmax * comp:\n                        safe = False\n                        break\n            if xvals:\n                for limit, comp in zip(xvals, xval_comps):\n                    val, _ = limit\n                    if p1 * comp > val * comp:\n                        safe = False\n                        break\n            if yvals:\n                for limit, comp in zip(yvals, yval_comps):\n                    val, _ = limit\n                    if p2 *comp > val * comp:\n                        safe = False\n                        break\n            if not safe:\n                continue\n            if not optimum:\n                optimum = (i, j)\n            else:\n                output = outputs[i, j]\n                optimum_output = outputs[optimum]\n                if output > optimum_output:\n                    optimum = (i, j)\n                elif output == optimum_output:\n                    current_price = price(p1, p2)\n                    optimum_price = price(params1[optimum[0]], params2[optimum[1]])\n                    if current_price < optimum_price:\n                        optimum = (i, j)\n    return optimum\n\ndef _energy_pump_dependence_task((i, j), (tau, pwr), inversion, num_types, counts):\n    output.show_status((i, j), params.extended_status_strides, False)\n    _, _, output_energy, rel_gain_decrease = core.amplify_train(None, num_types, counts, inversion, quiet=True)\n    return output_energy, rel_gain_decrease\n\ndef compute_energy_pump_dependence(task_pool, dirname, inversions, constraints, num_types, counts):\n    filename = lambda name: os.path.join(dirname, name)\n    \n    print output.div_line\n    print \"computing energy dependence on pumping parameters\"\n    \n    active_medium = core.create_medium(None)\n    input_beam = core.create_beam()\n    \n    input_photon_count = input_beam.fluence_integral(active_medium.radius)\n    input_energy = model.energy.energy(params.lasing_wavelen, input_photon_count)\n    input_energy *= params.train_pulse_count\n    \n    count_tau = params.ext_opt_pump_resolution[0]\n    count_pwr = params.ext_opt_pump_resolution[1]\n    \n    Tau = np.linspace(params.ext_opt_pump_duration[0], params.ext_opt_pump_duration[1], count_tau)\n    Pwr = np.linspace(params.ext_opt_pump_power[0], params.ext_opt_pump_power[1], count_pwr)\n    \n    output_energies, rel_gain_decreases = task_pool.parallel_task(_energy_pump_dependence_task, (Tau, Pwr), (inversions,), (num_types, counts))\n    \n    output.show_status((count_tau, count_pwr), params.extended_status_strides, True)\n    \n    pump_energies = np.prod(np.array(np.meshgrid(Tau, Pwr)), axis=0).T\n    stored_energies = model.energy.energy(params.lasing_wavelen, inversions * active_medium.volume)\n    energy_gains = output_energies / input_energy\n    added_energies = output_energies - input_energy\n    extraction_effs = added_energies / stored_energies\n    total_effs = added_energies / pump_energies\n    \n    limits, comparisons = constraints\n    price = lambda tau, pwr: tau * pwr\n    \n    unitconv.print_result(\"input energy [{}]: {}\", (\"mJ\",), (input_energy,))\n    \n    optimum = optimize_output((Tau, Pwr), output_energies, limits, comparisons, price)\n    output_energy_optimum_params = (Tau[optimum[0]], Pwr[optimum[1]]) if optimum else (None, None)\n    unitconv.print_result(\"max. output energy [{}]: {}\", (\"mJ\",), (output_energies[optimum] if optimum else None,))\n    unitconv.print_result(\"optimum pumping parameters (duration [{}], power [{}]): ({}, {})\", (\"us\", \"W\"), output_energy_optimum_params)\n    \n    optimum = optimize_output((Tau, Pwr), energy_gains, limits, comparisons, price)\n    energy_gain_optimum_params = (Tau[optimum[0]], Pwr[optimum[1]]) if optimum else (None, None)\n    unitconv.print_result(\"max. energy gain: {}\", (), (energy_gains[optimum] if optimum else None,))\n    unitconv.print_result(\"optimum pumping parameters (duration [{}], power [{}]): ({}, {})\", (\"us\", \"W\"), energy_gain_optimum_params)\n    \n    optimum = optimize_output((Tau, Pwr), extraction_effs, limits, comparisons, price)\n    extraction_eff_optimum_params = (Tau[optimum[0]], Pwr[optimum[1]]) if optimum else (None, None)\n    unitconv.print_result(\"max. extraction efficiency [{}]: {}\", (\"%\",), (extraction_effs[optimum] if optimum else None,))\n    unitconv.print_result(\"optimum pumping parameters (duration [{}], power [{}]): ({}, {})\", (\"us\", \"W\"), extraction_eff_optimum_params)\n    \n    optimum = optimize_output((Tau, Pwr), total_effs, limits, comparisons, price)\n    total_eff_optimum_params = (Tau[optimum[0]], Pwr[optimum[1]]) if optimum else (None, None)\n    unitconv.print_result(\"max. opt.-opt. efficiency [{}]: {}\", (\"%\",), (total_effs[optimum] if optimum else None,))\n    unitconv.print_result(\"optimum pumping parameters (duration [{}], power [{}]): ({}, {})\", (\"us\", \"W\"), total_eff_optimum_params)\n    \n    optimum = optimize_output((Tau, Pwr), -rel_gain_decreases, limits, comparisons, price)\n    rel_gain_decrease_optimum_params = (Tau[optimum[0]], Pwr[optimum[1]]) if optimum else (None, None)\n    unitconv.print_result(\"min. rel. gain decrease [{}]: {}\", (\"%\",), (rel_gain_decreases[optimum] if optimum else None,))\n    unitconv.print_result(\"optimum pumping parameters (duration [{}], power [{}]): ({}, {})\", (\"us\", \"W\"), rel_gain_decrease_optimum_params)\n    \n    if params.graphs:\n        print output.status_writing\n        extra_contours, xvals, yvals = limits\n        dirname = os.path.join(dirname, output.opt_pump_rel_path)\n        graph_types = [\n            (dirname, Pwr, output.pump_power_label),\n            (os.path.join(dirname, output.alt_plot_rel_path), Pwr * params.pump_efficiency / active_medium.volume, output.eff_power_density_label),\n        ]\n        for dirname, Y, ylabel in graph_types:\n            dirname = output.init_dir(dirname)\n            plot.plot_color(filename(\"energy_out\"), \"Output Energy\", (Tau, None, None, output.pump_duration_label), (Y, None, None, ylabel), (output_energies.T, None, output.energy_abs_pulse_label), params.out_num_auto_contours, extra_contours=extra_contours, xvals=xvals, yvals=yvals)\n            plot.plot_color(filename(\"energy_gain\"), \"Energy Gain\", (Tau, None, None, output.pump_duration_label), (Y, None, None, ylabel), (energy_gains.T, None, output.energy_rel_label), params.out_num_auto_contours, extra_contours=extra_contours, xvals=xvals, yvals=yvals)\n            plot.plot_color(filename(\"efficiency_extr\"), \"Extraction Efficiency\", (Tau, None, None, output.pump_duration_label), (Y, None, None, ylabel), (extraction_effs.T, None, output.extraction_eff_label), params.out_num_auto_contours, extra_contours=extra_contours, xvals=xvals, yvals=yvals)\n            plot.plot_color(filename(\"efficiency_opt2\"), \"Optical to Optical Efficiency\", (Tau, None, None, output.pump_duration_label), (Y, None, None, ylabel), (total_effs.T, None, output.total_eff_label), params.out_num_auto_contours, extra_contours=extra_contours, xvals=xvals, yvals=yvals)\n            if params.train_pulse_count > 1:\n                plot.plot_color(filename(\"gain_decrease\"), \"Gain Decrease\", (Tau, None, None, output.pump_duration_label), (Y, None, None, ylabel), (rel_gain_decreases.T, None, output.rel_gain_decrease_label), params.out_num_auto_contours, extra_contours=extra_contours, xvals=xvals, yvals=yvals)\n\ndef _energy_geom_dependence_task((i, j), (rm, rb), inversion, num_types, counts):\n    output.show_status((i, j), params.extended_status_strides, False)\n    \n    orig_geom = _set_geom(rm, rb)\n    try:\n        active_medium = core.create_medium(None)\n        input_beam = core.create_beam()\n        stored_energy = model.energy.energy(params.lasing_wavelen, inversion * active_medium.volume)\n        input_photon_count = input_beam.fluence_integral(active_medium.radius)\n        input_energy = model.energy.energy(params.lasing_wavelen, input_photon_count)\n        input_energy *= params.train_pulse_count\n        \n        _, _, output_energy, rel_gain_decrease = core.amplify_train(None, num_types, counts, inversion, quiet=True)\n    finally:\n        _set_geom(*orig_geom)\n    \n    return stored_energy, input_energy, output_energy, rel_gain_decrease\n\ndef compute_energy_geom_dependence(task_pool, dirname, inversions, constraints, num_types, counts):\n    filename = lambda name: os.path.join(dirname, name)\n    \n    print output.div_line\n    print \"computing energy dependence on geometry parameters\"\n    \n    min_medium_radius = params.ext_opt_geom_mediumradius[0]\n    min_beam_radius = params.ext_opt_geom_beamradius[0]\n    \n    count_rm = params.ext_opt_geom_resolution[0]\n    count_rb = params.ext_opt_geom_resolution[1]\n    \n    Rm = np.linspace(min_medium_radius, params.ext_opt_geom_mediumradius[1], count_rm)\n    Rb = np.linspace(min_beam_radius, params.ext_opt_geom_beamradius[1], count_rb)\n    \n    inversions = np.meshgrid(inversions, Rb)[0].T\n    stored_energies, input_energies, output_energies, rel_gain_decreases = task_pool.parallel_task(_energy_geom_dependence_task, (Rm, Rb), (inversions,), (num_types, counts))\n    \n    output.show_status((count_rm, count_rb), params.extended_status_strides, True)\n    \n    pump_energy = params.pump_duration * params.pump_power\n    energy_gains = output_energies / input_energies\n    added_energies = output_energies - input_energies\n    extraction_effs = added_energies / stored_energies\n    total_effs = added_energies / pump_energy\n    \n    limits, comparisons = constraints\n    price = lambda rm, rb: 1.0 / (rm * rb)\n    \n    optimum = optimize_output((Rm, Rb), output_energies, limits, comparisons, price)\n    output_energy_optimum_params = (Rm[optimum[0]], Rb[optimum[1]]) if optimum else (None, None)\n    unitconv.print_result(\"max. output energy [{}]: {}\", (\"mJ\",), (output_energies[optimum] if optimum else None,))\n    unitconv.print_result(\"optimum geometry parameters (medium diameter [{}], beam diameter [{}]): ({}, {})\", (\"mm\", \"mm\"), output_energy_optimum_params)\n    \n    optimum = optimize_output((Rm, Rb), energy_gains, limits, comparisons, price)\n    energy_gain_optimum_params = (Rm[optimum[0]], Rb[optimum[1]]) if optimum else (None, None)\n    unitconv.print_result(\"max. energy gain: {}\", (), (energy_gains[optimum] if optimum else None,))\n    unitconv.print_result(\"optimum geometry parameters (medium diameter [{}], beam diameter [{}]): ({}, {})\", (\"mm\", \"mm\"), energy_gain_optimum_params)\n    \n    optimum = optimize_output((Rm, Rb), extraction_effs, limits, comparisons, price)\n    extraction_eff_optimum_params = (Rm[optimum[0]], Rb[optimum[1]]) if optimum else (None, None)\n    unitconv.print_result(\"max. extraction efficiency [{}]: {}\", (\"%\",), (extraction_effs[optimum] if optimum else None,))\n    unitconv.print_result(\"optimum geometry parameters (medium diameter [{}], beam diameter [{}]): ({}, {})\", (\"mm\", \"mm\"), extraction_eff_optimum_params)\n    \n    optimum = optimize_output((Rm, Rb), total_effs, limits, comparisons, price)\n    total_eff_optimum_params = (Rm[optimum[0]], Rb[optimum[1]]) if optimum else (None, None)\n    unitconv.print_result(\"max. opt.-opt. efficiency [{}]: {}\", (\"%\",), (total_effs[optimum] if optimum else None,))\n    unitconv.print_result(\"optimum geometry parameters (medium diameter [{}], beam diameter [{}]): ({}, {})\", (\"mm\", \"mm\"), total_eff_optimum_params)\n    \n    optimum = optimize_output((Rm, Rb), -rel_gain_decreases, limits, comparisons, price)\n    rel_gain_decrease_optimum_params = (Rm[optimum[0]], Rb[optimum[1]]) if optimum else (None, None)\n    unitconv.print_result(\"min. rel. gain decrease [{}]: {}\", (\"%\",), (rel_gain_decreases[optimum] if optimum else None,))\n    unitconv.print_result(\"optimum geometry parameters (medium diameter [{}], beam diameter [{}]): ({}, {})\", (\"mm\", \"mm\"), rel_gain_decrease_optimum_params)\n    \n    if params.graphs:\n        print output.status_writing\n        extra_contours, xvals, yvals = limits\n        dirname = os.path.join(dirname, output.opt_geom_rel_path)\n        dirname = output.init_dir(dirname)\n        plot.plot_color(filename(\"energy_in\"), \"Input Energy\", (Rm, None, None, output.medium_radius_label), (Rb, None, None, output.beam_radius_label), (input_energies.T, None, output.energy_abs_pulse_label), params.out_num_auto_contours, extra_contours=extra_contours, xvals=xvals, yvals=yvals)\n        plot.plot_color(filename(\"energy_out\"), \"Output Energy\", (Rm, None, None, output.medium_radius_label), (Rb, None, None, output.beam_radius_label), (output_energies.T, None, output.energy_abs_pulse_label), params.out_num_auto_contours, extra_contours=extra_contours, xvals=xvals, yvals=yvals)\n        plot.plot_color(filename(\"energy_gain\"), \"Energy Gain\", (Rm, None, None, output.medium_radius_label), (Rb, None, None, output.beam_radius_label), (energy_gains.T, None, output.energy_rel_label), params.out_num_auto_contours, extra_contours=extra_contours, xvals=xvals, yvals=yvals)\n        plot.plot_color(filename(\"efficiency_extr\"), \"Extraction Efficiency\", (Rm, None, None, output.medium_radius_label), (Rb, None, None, output.beam_radius_label), (extraction_effs.T, None, output.extraction_eff_label), params.out_num_auto_contours, extra_contours=extra_contours, xvals=xvals, yvals=yvals)\n        plot.plot_color(filename(\"efficiency_opt2\"), \"Optical to Optical Efficiency\", (Rm, None, None, output.medium_radius_label), (Rb, None, None, output.beam_radius_label), (total_effs.T, None, output.total_eff_label), params.out_num_auto_contours, extra_contours=extra_contours, xvals=xvals, yvals=yvals)\n        if params.train_pulse_count > 1:\n            plot.plot_color(filename(\"gain_decrease\"), \"Gain Decrease\", (Rm, None, None, output.medium_radius_label), (Rb, None, None, output.beam_radius_label), (rel_gain_decreases.T, None, output.rel_gain_decrease_label), params.out_num_auto_contours, extra_contours=extra_contours, xvals=xvals, yvals=yvals)\n\ndef compare_lower_lifetimes(dirname, ref_inversion, (int_types, amp_types), numerics):\n    filename = lambda name: os.path.join(dirname, name)\n    \n    print output.div_line\n    print \"comparing lower state lifetimes\"\n    \n    if numerics is None:\n        numerics, _ = core.select_methods((int_types, amp_types), ref_inversion, quiet=True)\n    num_types, counts = numerics\n    \n    lower_lifetime = params.dopant_lower_lifetime\n    \n    active_medium = core.create_medium(ref_inversion)\n    active_medium_3 = copy.deepcopy(active_medium)\n    active_medium_3.doping_agent.lower_lifetime = float(\"inf\")\n    active_medium_4 = copy.deepcopy(active_medium)\n    active_medium_4.doping_agent.lower_lifetime = 0.0\n    \n    input_beam = core.create_beam()\n    \n    ref_pulse = core.create_pulse(active_medium, input_beam, input_beam.rho_ref, input_beam.phi_ref)\n    \n    (int_type, amp_type), (_, _, count_z, count_t) = num_types, counts\n    \n    integrator = model.integrator.DomainIntegrator(int_type)\n    \n    amp = amp_type(active_medium, count_z)\n    amp_3 = model.amplifier.ExactOutputAmplifier(active_medium_3, count_z)\n    amp_4 = model.amplifier.ExactOutputAmplifier(active_medium_4, count_z)\n    amplify_args = (input_beam.rho_ref, input_beam.phi_ref, ref_pulse, count_t)\n    \n    print \"zero\"\n    density_out_4, _ = amp_4.amplify(*amplify_args)\n    fluence_out_4 = integrator.integrate(amp_4.T, density_out_4) * active_medium_4.light_speed\n    fluence_gain_4 = fluence_out_4 / input_beam.ref_fluence\n    unitconv.print_result(\"fluence gain: {}\", (), (fluence_gain_4,))\n    \n    lsl_output_label = \"finite\"\n    if lower_lifetime == 0.0:\n        lsl_output_label = \"zero\"\n    elif math.isinf(lower_lifetime):\n        lsl_output_label = \"infinite\"\n    print lsl_output_label\n    density_out, _ = amp.amplify(*amplify_args)\n    fluence_out = integrator.integrate(amp.T, density_out) * active_medium.light_speed\n    fluence_gain = fluence_out / input_beam.ref_fluence\n    unitconv.print_result(\"fluence gain: {}\", (), (fluence_gain,))\n    \n    print \"infinite\"\n    density_out_3, _ = amp_3.amplify(*amplify_args)\n    fluence_out_3 = integrator.integrate(amp_3.T, density_out_3) * active_medium_3.light_speed\n    fluence_gain_3 = fluence_out_3 / input_beam.ref_fluence\n    unitconv.print_result(\"fluence gain: {}\", (), (fluence_gain_3,))\n    \n    if params.graphs:\n        print output.status_writing\n        dirname = os.path.join(dirname, output.ref_pulse_rel_path)\n        dirname = output.init_dir(dirname)\n        T = amp.T\n        if params.output_rel_time:\n            T = T / params.pulse_duration\n        out_t_label = output.norm_t_label if params.output_rel_time else output.t_amp_label\n        tlim = (T[0], T[-1])\n        Ts = (T,) * 3\n        ref_density = ref_pulse.ref_density\n        densities = (density_out_4 / ref_density, density_out / ref_density, density_out_3 / ref_density)\n        lifetime_scale = unitconv.units[output.lower_lifetime_unit]\n        lsl_graph_label_fmt = (r\"%g \\, %s\" % (lower_lifetime/lifetime_scale, output.lower_lifetime_unit))\n        if lower_lifetime == 0.0:\n            lsl_graph_label_fmt = \"0\"\n        elif math.isinf(lower_lifetime):\n            lsl_graph_label_fmt = \"\\\\infty\"\n        labels = (output.lower_lifetime_legend % \"0\", output.lower_lifetime_legend % lsl_graph_label_fmt, output.lower_lifetime_legend % \"\\\\infty\")\n        plot.plot_data(filename(\"lsl_effects\"), \"Effects of Lower State Lifetime\", (Ts, None, tlim, out_t_label), (densities, None, None, output.density_rel_label), labels)\n\ndef select_methods(perform_opt_pump, perform_opt_geom, (int_types, amp_types), inversions_pump, inversions_geom):\n    print output.div_line\n    print \"determining extended mode method combinations\"\n    \n    (num_types_pump, counts_pump), (num_types_geom, counts_geom) = (None, None), (None, None)\n    \n    if perform_opt_pump:\n        print \"pumping\"\n        max_inversion_pump = inversions_pump[-1, -1]\n        (num_types_pump, counts_pump), _ = core.select_methods((int_types, amp_types), max_inversion_pump, quiet=True)\n    \n    if perform_opt_geom:\n        print \"geometry\"\n        max_medium_radius = params.ext_opt_geom_mediumradius[1]\n        min_beam_radius = params.ext_opt_geom_beamradius[0]\n        \n        orig_geom = _set_geom(max_medium_radius, min_beam_radius)\n        try:\n            max_inversion_geom = inversions_geom[0]\n            (num_types_geom, counts_geom), _ = core.select_methods((int_types, amp_types), max_inversion_geom, quiet=True)\n        finally:\n            _set_geom(*orig_geom)\n    \n    return (num_types_pump, counts_pump), (num_types_geom, counts_geom)\n\ndef extended_mode(task_pool, dirname, ref_inversion, (int_types, amp_types), numerics):\n    if params.amplification:\n        compare_lower_lifetimes(dirname, ref_inversion, (int_types, amp_types), numerics)\n    \n    if not params.initial_inversion:\n        compare_depop_models(dirname)\n        \n        perform_opt_pump = min(params.ext_opt_pump_resolution) > 1\n        perform_opt_geom = min(params.ext_opt_geom_resolution) > 1\n        perform_opt = perform_opt_pump or perform_opt_geom\n        \n        if perform_opt:\n            inversions_pump, inversions_geom = None, None\n            if perform_opt_pump:\n                inversions_pump, inversion_rdiffs_pump = compute_inversion_pump_dependence(task_pool, dirname)\n            if perform_opt_geom:\n                inversions_geom, inversion_rdiffs_geom = compute_inversion_geom_dependence(task_pool, dirname)\n            \n            if params.amplification:\n                (num_types_pump, counts_pump), (num_types_geom, counts_geom) = select_methods(perform_opt_pump, perform_opt_geom, (int_types, amp_types), inversions_pump, inversions_geom)\n                \n                if perform_opt_pump:\n                    _, _, count_z_pump, count_t_pump = counts_pump\n                    max_fluences_pump = compute_fluence_pump_dependence(task_pool, dirname, inversions_pump, num_types_pump, (count_z_pump, count_t_pump))\n                if perform_opt_geom:\n                    _, _, count_z_geom, count_t_geom = counts_geom\n                    max_fluences_geom = compute_fluence_geom_dependence(task_pool, dirname, inversions_geom, num_types_geom, (count_z_geom, count_t_geom))\n                \n                if perform_opt_pump:\n                    pump_constraints = compute_pump_constraints(dirname, inversion_rdiffs_pump, max_fluences_pump)\n                if perform_opt_geom:\n                    geom_constraints = compute_geom_constraints(dirname, inversion_rdiffs_geom, max_fluences_geom)\n                \n                if perform_opt_pump:\n                    compute_energy_pump_dependence(task_pool, dirname, inversions_pump, pump_constraints, num_types_pump, counts_pump)\n                if perform_opt_geom:\n                    compute_energy_geom_dependence(task_pool, dirname, inversions_geom, geom_constraints, num_types_geom, counts_geom)\n", "meta": {"hexsha": "74fb836e6e5b67a6eb54f25415963b3c821af287", "size": 47812, "ext": "py", "lang": "Python", "max_stars_repo_path": "npamp/ext.py", "max_stars_repo_name": "vsemionov/npamp", "max_stars_repo_head_hexsha": "b1eb07c7fe8204f4e316a26b56b12caa9b54d0b2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2016-03-18T16:02:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T00:59:28.000Z", "max_issues_repo_path": "npamp/ext.py", "max_issues_repo_name": "vsemionov/npamp", "max_issues_repo_head_hexsha": "b1eb07c7fe8204f4e316a26b56b12caa9b54d0b2", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "npamp/ext.py", "max_forks_repo_name": "vsemionov/npamp", "max_forks_repo_head_hexsha": "b1eb07c7fe8204f4e316a26b56b12caa9b54d0b2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-09-22T08:11:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T00:59:27.000Z", "avg_line_length": 58.7371007371, "max_line_length": 310, "alphanum_fraction": 0.7105956664, "include": true, "reason": "import numpy", "num_tokens": 12034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.3007455789412415, "lm_q1q2_score": 0.18162983326278553}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2021 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n'''\nspin-free X2C correction for extended systems (experimental feature)\n'''\n\n\nfrom functools import reduce\nimport copy\nimport numpy\nimport scipy.linalg\nfrom pyscf import lib\nfrom pyscf.gto import mole\nfrom pyscf.lib import logger\nfrom pyscf.x2c import x2c\nfrom pyscf.pbc import gto as pbcgto\nfrom pyscf.pbc import tools\nfrom pyscf.pbc.df import aft\nfrom pyscf.pbc.df import aft_jk\nfrom pyscf.pbc.df import ft_ao\nfrom pyscf.pbc.scf import ghf\nfrom pyscf import __config__\n\n\ndef sfx2c1e(mf):\n    '''Spin-free X2C.\n    For the given SCF object, update the hcore constructor.\n\n    Args:\n        mf : an SCF object\n\n    Returns:\n        An SCF object\n\n    Examples:\n\n    >>> mol = gto.M(atom='H 0 0 0; F 0 0 1', basis='ccpvdz', verbose=0)\n    >>> mf = scf.RHF(mol).sfx2c1e()\n    >>> mf.scf()\n\n    >>> mol.symmetry = 1\n    >>> mol.build(0, 0)\n    >>> mf = scf.UHF(mol).sfx2c1e()\n    >>> mf.scf()\n    '''\n    if isinstance(mf, x2c._X2C_SCF):\n        if mf.with_x2c is None:\n            return mf.__class__(mf)\n        else:\n            return mf\n\n    mf_class = mf.__class__\n    if mf_class.__doc__ is None:\n        doc = ''\n    else:\n        doc = mf_class.__doc__\n    class SFX2C1E_SCF(mf_class, x2c._X2C_SCF):\n        __doc__ = doc + '''\n        Attributes for spin-free X2C:\n            with_x2c : X2C object\n        '''\n        def __init__(self, mf):\n            self.__dict__.update(mf.__dict__)\n            self.with_x2c = SpinFreeX2C(mf.mol)\n            self._keys = self._keys.union(['with_x2c'])\n\n        def get_hcore(self, cell=None, kpts=None, kpt=None):\n            if cell is None: cell = self.cell\n            if kpts is None:\n                if getattr(self, 'kpts', None) is not None:\n                    kpts = self.kpts\n                else:\n                    if kpt is None:\n                        kpts = self.kpt\n                    else:\n                        kpts = kpt\n            if self.with_x2c:\n                hcore = self.with_x2c.get_hcore(cell, kpts)\n                if isinstance(self, ghf.GHF):\n                    if kpts.ndim == 1:\n                        hcore = scipy.linalg.block_diag(hcore, hcore)\n                    else:\n                        hcore = [scipy.linalg.block_diag(h, h) for h in hcore]\n                return hcore\n            else:\n                return mf_class.get_hcore(self, cell, kpts)\n\n    return SFX2C1E_SCF(mf)\n\nsfx2c = sfx2c1e\n\nclass X2C(x2c.X2C):\n\n    exp_drop = getattr(__config__, 'pbc_x2c_X2C_exp_drop', 0.2)\n    approx = getattr(__config__, 'pbc_x2c_X2C_approx', 'atom1e')\n    xuncontract = getattr(__config__, 'pbc_x2c_X2C_xuncontract', True)\n    basis = getattr(__config__, 'pbc_x2c_X2C_basis', None)\n\n    def __init__(self, cell, kpts=None):\n        self.cell = cell\n        x2c.X2C.__init__(self, cell)\n\nclass SpinFreeX2C(X2C):\n    def get_hcore(self, cell=None, kpts=None):\n        if cell is None: cell = self.cell\n        if kpts is None:\n            kpts_lst = numpy.zeros((1,3))\n        else:\n            kpts_lst = numpy.reshape(kpts, (-1,3))\n\n        xcell, contr_coeff = self.get_xmol(cell)\n        with_df = aft.AFTDF(xcell)\n        c = lib.param.LIGHT_SPEED\n        assert('1E' in self.approx.upper())\n        if 'ATOM' in self.approx.upper():\n            atom_slices = xcell.offset_nr_by_atom()\n            nao = xcell.nao_nr()\n            x = numpy.zeros((nao,nao))\n            vloc = numpy.zeros((nao,nao))\n            wloc = numpy.zeros((nao,nao))\n            for ia in range(xcell.natm):\n                ish0, ish1, p0, p1 = atom_slices[ia]\n                shls_slice = (ish0, ish1, ish0, ish1)\n                t1 = xcell.intor('int1e_kin', shls_slice=shls_slice)\n                s1 = xcell.intor('int1e_ovlp', shls_slice=shls_slice)\n                with xcell.with_rinv_at_nucleus(ia):\n                    z = -xcell.atom_charge(ia)\n                    v1 = z * xcell.intor('int1e_rinv', shls_slice=shls_slice)\n                    w1 = z * xcell.intor('int1e_prinvp', shls_slice=shls_slice)\n                vloc[p0:p1,p0:p1] = v1\n                wloc[p0:p1,p0:p1] = w1\n                x[p0:p1,p0:p1] = x2c._x2c1e_xmatrix(t1, v1, w1, s1, c)\n        else:\n            raise NotImplementedError\n\n        t = xcell.pbc_intor('int1e_kin', 1, lib.HERMITIAN, kpts_lst)\n        s = xcell.pbc_intor('int1e_ovlp', 1, lib.HERMITIAN, kpts_lst)\n        v = with_df.get_nuc(kpts_lst)\n        #w = get_pnucp(with_df, kpts_lst)\n        if self.basis is not None:\n            s22 = s\n            s21 = pbcgto.intor_cross('int1e_ovlp', xcell, cell, kpts=kpts_lst)\n\n        h1_kpts = []\n        for k in range(len(kpts_lst)):\n            # The treatment of pnucp local part has huge effects to hcore\n            #h1 = x2c._get_hcore_fw(t[k], vloc, wloc, s[k], x, c) - vloc + v[k]\n            #h1 = x2c._get_hcore_fw(t[k], v[k], w[k], s[k], x, c)\n            h1 = x2c._get_hcore_fw(t[k], v[k], wloc, s[k], x, c)\n            if self.basis is not None:\n                c = lib.cho_solve(s22[k], s21[k])\n                h1 = reduce(numpy.dot, (c.T, h1, c))\n            if self.xuncontract and contr_coeff is not None:\n                h1 = reduce(numpy.dot, (contr_coeff.T, h1, contr_coeff))\n            h1_kpts.append(h1)\n\n        if kpts is None or numpy.shape(kpts) == (3,):\n            h1_kpts = h1_kpts[0]\n        return lib.asarray(h1_kpts)\n\n    def get_xmat(self, cell=None, kpts=None):\n        if cell is None: cell = self.cell\n        xcell, contr_coeff = self.get_xmol(cell)\n        c = lib.param.LIGHT_SPEED\n        assert('1E' in self.approx.upper())\n        if 'ATOM' in self.approx.upper():\n            atom_slices = xcell.offset_nr_by_atom()\n            nao = xcell.nao_nr()\n            x = numpy.zeros((nao,nao))\n            for ia in range(xcell.natm):\n                ish0, ish1, p0, p1 = atom_slices[ia]\n                shls_slice = (ish0, ish1, ish0, ish1)\n                t1 = xcell.intor('int1e_kin', shls_slice=shls_slice)\n                s1 = xcell.intor('int1e_ovlp', shls_slice=shls_slice)\n                with xcell.with_rinv_at_nucleus(ia):\n                    z = -xcell.atom_charge(ia)\n                    v1 = z * xcell.intor('int1e_rinv', shls_slice=shls_slice)\n                    w1 = z * xcell.intor('int1e_prinvp', shls_slice=shls_slice)\n                x[p0:p1,p0:p1] = x2c._x2c1e_xmatrix(t1, v1, w1, s1, c)\n        else:\n            raise NotImplementedError\n        return x\n\n\n# Use Ewald-like technique to compute spVsp.\n# spVsp may not be divergent because the numerator spsp and the denominator\n# in Coulomb kernel 4pi/G^2 are likely cancelled.  Even a real space lattice\n# sum can converge to a finite value, it's difficult to accurately converge\n# this value, i.e., large number of images in lattice summation is required.\ndef get_pnucp(mydf, kpts=None):\n    cell = mydf.cell\n    if kpts is None:\n        kpts_lst = numpy.zeros((1,3))\n    else:\n        kpts_lst = numpy.reshape(kpts, (-1,3))\n\n    log = logger.Logger(mydf.stdout, mydf.verbose)\n    t1 = (logger.process_clock(), logger.perf_counter())\n\n    nkpts = len(kpts_lst)\n    nao = cell.nao_nr()\n    nao_pair = nao * (nao+1) // 2\n\n    Gv, Gvbase, kws = cell.get_Gv_weights(mydf.mesh)\n    charge = -cell.atom_charges()\n    kpt_allow = numpy.zeros(3)\n    coulG = tools.get_coulG(cell, kpt_allow, mesh=mydf.mesh, Gv=Gv)\n    coulG *= kws\n    if mydf.eta == 0:\n        wj = numpy.zeros((nkpts,nao_pair), dtype=numpy.complex128)\n        SI = cell.get_SI(Gv)\n        vG = numpy.einsum('i,ix->x', charge, SI) * coulG\n        wj = numpy.zeros((nkpts,nao_pair), dtype=numpy.complex128)\n\n    else:\n        nuccell = copy.copy(cell)\n        half_sph_norm = .5/numpy.sqrt(numpy.pi)\n        norm = half_sph_norm/mole.gaussian_int(2, mydf.eta)\n        chg_env = [mydf.eta, norm]\n        ptr_eta = cell._env.size\n        ptr_norm = ptr_eta + 1\n        chg_bas = [[ia, 0, 1, 1, 0, ptr_eta, ptr_norm, 0] for ia in range(cell.natm)]\n        nuccell._atm = cell._atm\n        nuccell._bas = numpy.asarray(chg_bas, dtype=numpy.int32)\n        nuccell._env = numpy.hstack((cell._env, chg_env))\n\n        wj = lib.asarray(mydf._int_nuc_vloc(nuccell, kpts_lst, 'int3c2e_pvp1'))\n        t1 = log.timer_debug1('pnucp pass1: analytic int', *t1)\n\n        aoaux = ft_ao.ft_ao(nuccell, Gv)\n        vG = numpy.einsum('i,xi->x', charge, aoaux) * coulG\n        if cell.dimension == 3:\n            nucbar = sum([z/nuccell.bas_exp(i)[0] for i,z in enumerate(charge)])\n            nucbar *= numpy.pi/cell.vol\n\n            ovlp = cell.pbc_intor('int1e_kin', 1, lib.HERMITIAN, kpts_lst)\n            for k in range(nkpts):\n                s = lib.pack_tril(ovlp[k])\n                # *2 due to the factor 1/2 in T\n                wj[k] -= nucbar*2 * s\n\n    max_memory = max(2000, mydf.max_memory-lib.current_memory()[0])\n    for aoaoks, p0, p1 in mydf.ft_loop(mydf.mesh, kpt_allow, kpts_lst,\n                                       max_memory=max_memory, aosym='s2',\n                                       intor='GTO_ft_pdotp'):\n        for k, aoao in enumerate(aoaoks):\n            if aft_jk.gamma_point(kpts_lst[k]):\n                wj[k] += numpy.einsum('k,kx->x', vG[p0:p1].real, aoao.real)\n                wj[k] += numpy.einsum('k,kx->x', vG[p0:p1].imag, aoao.imag)\n            else:\n                wj[k] += numpy.einsum('k,kx->x', vG[p0:p1].conj(), aoao)\n    t1 = log.timer_debug1('contracting pnucp', *t1)\n\n    wj_kpts = []\n    for k, kpt in enumerate(kpts_lst):\n        if aft_jk.gamma_point(kpt):\n            wj_kpts.append(lib.unpack_tril(wj[k].real.copy()))\n        else:\n            wj_kpts.append(lib.unpack_tril(wj[k]))\n\n    if kpts is None or numpy.shape(kpts) == (3,):\n        wj_kpts = wj_kpts[0]\n    return numpy.asarray(wj_kpts)\n\n\nif __name__ == '__main__':\n    from pyscf.pbc import scf\n    cell = pbcgto.Cell()\n    cell.build(unit = 'B',\n               a = numpy.eye(3)*4,\n               mesh = [11]*3,\n               atom = 'H 0 0 0; H 0 0 1.8',\n               verbose = 4,\n               basis='sto3g')\n    lib.param.LIGHT_SPEED = 2\n    mf = scf.RHF(cell)\n    mf.with_df = aft.AFTDF(cell)\n    enr = mf.kernel()\n    print('E(NR) = %.12g' % enr)\n\n    mf = sfx2c1e(mf)\n    esfx2c = mf.kernel()\n    print('E(SFX2C1E) = %.12g' % esfx2c)\n\n    mf = scf.KRHF(cell)\n    mf.with_df = aft.AFTDF(cell)\n    mf.kpts = cell.make_kpts([2,2,1])\n    enr = mf.kernel()\n    print('E(k-NR) = %.12g' % enr)\n\n    mf = sfx2c1e(mf)\n    esfx2c = mf.kernel()\n    print('E(k-SFX2C1E) = %.12g' % esfx2c)\n\n#    cell = pbcgto.M(unit = 'B',\n#               a = numpy.eye(3)*4,\n#               atom = 'H 0 0 0; H 0 0 1.8',\n#               mesh = None,\n#               dimension = 2,\n#               basis='sto3g')\n#    with_df = aft.AFTDF(cell)\n#    w0 = get_pnucp(with_df, cell.make_kpts([2,2,1]))\n#    with_df = aft.AFTDF(cell)\n#    with_df.eta = 0\n#    w1 = get_pnucp(with_df, cell.make_kpts([2,2,1]))\n#    print(abs(w0-w1).max())\n", "meta": {"hexsha": "b936f6c94095076091d073f27a165659ed73e9f3", "size": 11486, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/pbc/x2c/sfx2c1e.py", "max_stars_repo_name": "umamibeef/pyscf", "max_stars_repo_head_hexsha": "1263d54b02914caf4476a3ed9a2de5e0c848954c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 501, "max_stars_repo_stars_event_min_datetime": "2018-12-06T23:48:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:53:18.000Z", "max_issues_repo_path": "pyscf/pbc/x2c/sfx2c1e.py", "max_issues_repo_name": "fabijan5/pyscf", "max_issues_repo_head_hexsha": "09834c8f5a4f5320cdde29d285b6ccd89b3263e0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 710, "max_issues_repo_issues_event_min_datetime": "2018-11-26T22:04:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:53:12.000Z", "max_forks_repo_path": "pyscf/pbc/x2c/sfx2c1e.py", "max_forks_repo_name": "fabijan5/pyscf", "max_forks_repo_head_hexsha": "09834c8f5a4f5320cdde29d285b6ccd89b3263e0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 273, "max_forks_repo_forks_event_min_datetime": "2018-11-26T10:10:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:25:28.000Z", "avg_line_length": 35.89375, "max_line_length": 85, "alphanum_fraction": 0.5692146962, "include": true, "reason": "import numpy,import scipy", "num_tokens": 3610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.3007455852086006, "lm_q1q2_score": 0.1816298327600166}}
{"text": "#!/usr/bin/env python\n\nimport sys, time,ast\nfrom copy import copy, deepcopy\nimport numpy as np\nimport argparse\nimport gc \nimport cPickle as pickle\n\nclass alchemy:\n   def getpair(self, sa, sb):\n      if len(self.rules)==0: # special case when the alchemical matrix is default\n         if sa==sb: return 1\n         else: return 0  \n      else:\n          if sa<=sb and (sa,sb) in self.rules:            \n             return self.rules[(sa,sb)]\n          elif sa>sb and (sb,sa) in self.rules:\n             return self.rules[(sb,sa)] \n          else: \n             if sa==sb: return 1\n             else: return 0  \n   \n   def __init__(self, rules={}, mu=0):            \n      self.rules = rules.copy()\n      self.mu = mu\n\nclass alchemy_mendeleev:\n   def getpair(self, sa, sb):\n      if sa<=sb and (sa,sb) in self.rules:\n         return self.rules[(sa,sb)]\n      elif sa>sb and (sb,sa) in self.rules:\n         return self.rules[(sb,sa)]\n      else:\n         Elec_neg={1: 2.2, 2: 0, 3: 0.98, 4: 1.57, 5: 2.04, 6: 2.55, 7: 3.04, 8: 3.44, 9: 3.98, 10: 0, 11: 0.93, 12: 1.31, 13: 1.5, 14: 1.8, 15: 2.19, 16: 2.58, 17: 3.16, 18: 0, 19: 0.82, 20: 1, 21: 1.36, 22: 1.54, 23: 1.63, 24: 1.66, 25: 1.55, 26: 1.83, 27: 1.88, 28: 1.91, 29: 1.9, 30: 1.65, 31: 1.81, 32: 2.01, 33: 2.18, 34: 2.55, 35: 2.96, 36: 0, 37: 0.82, 38: 0.95, 39: 1.22, 40: 1.33, 41: 1.6, 42: 2.16, 43: 1.9, 44: 2.2, 45: 2.28, 46: 2.2, 47: 1.93, 48: 1.69, 49: 1.78, 50: 1.96, 51: 2.05, 52: 2.1, 53: 2.66, 54: 0, 55: 0.79, 56: 0.89, 57: 1.1, 58: 1.12, 59: 1.13, 60: 1.14, 61: 1.13, 62: 1.17, 63: 1.2, 64: 1.2, 65: 1.2, 66: 1.22, 67: 1.23, 68: 1.24, 69: 1.25, 70: 1.1, 71: 1.27, 72: 1.3, 73: 1.5, 74: 2.36, 75: 1.9, 76: 2.2, 77: 2.2, 78: 2.28, 79: 2.54, 80: 2, 81: 2.04, 82: 2.33, 83: 2.02, 84: 2, 85: 2.2, 86: 0, 87: 0.7, 88: 0.9, 89: 1.1, 90: 1.3, 91: 1.5, 92: 1.38, 93: 1.36, 94: 1.28, 95: 1.3, 96: 1.3, 97: 1.3, 98: 1.3, 99: 1.3, 100: 1.3, 101: 1.3, 102: 1.3, 103: 10.0, 104: 10.0, 105:10.0, 106: 10.0, 107: 10.0, 108: 10.0, 109: 10.0}\n         Elec_aff={1: 0.75420375, 2: 0.0, 3: 0.618049, 4: 0.0, 5: 0.279723, 6: 1.262118, 7: -0.07, 8: 1.461112, 9: 3.4011887, 10: 0.0, 11: 0.547926, 12: 0.0, 13: 0.43283, 14: 1.389521, 15: 0.7465, 16: 2.0771029, 17: 3.612724, 18: 0.0, 19: 0.501459, 20: 0.02455, 21: 0.188, 22: 0.084, 23: 0.525, 24: 0.67584, 25: 0.0, 26: 0.151, 27: 0.6633, 28: 1.15716, 29: 1.23578, 30: 0.0, 31: 0.41, 32: 1.232712, 33: 0.814, 34: 2.02067, 35: 3.363588, 36: 0.0, 37: 0.485916, 38: 0.05206, 39: 0.307, 40: 0.426, 41: 0.893, 42: 0.7472, 43: 0.55, 44: 1.04638, 45: 1.14289, 46: 0.56214, 47: 1.30447, 48: 0.0, 49: 0.404, 50: 1.112066, 51: 1.047401, 52: 1.970875, 53: 3.059038, 54: 0.0, 55: 0.471626, 56: 0.14462, 57: 0.47, 58: 0.5, 59: 0.5, 60: 0.5, 61: 0.5, 62: 0.5, 63: 0.5, 64: 0.5, 65: 0.5, 66: 0.5, 67: 0.5, 68: 0.5, 69: 0.5, 70: 0.5, 71: 0.5, 72: 0.0, 73: 0.322, 74: 0.815, 75: 0.15, 76: 1.0778, 77: 1.56436, 78: 2.1251, 79: 2.30861, 80: 0.0, 81: 0.377, 82: 0.364, 83: 0.942363, 84: 1.9, 85: 2.8, 86: 0.0, 87: 0.0, 88: 0.0, 89: 0.0, 90: 0.0, 91: 0.0, 92: 0.0, 93: 0.0, 94: 0.0, 95: 0.0, 96: 0.0, 97: 0.0, 98: 0.0, 99: 0.0, 100: 0.0, 101: 0.0, 102: 0.0, 103: 0.0, 104: 0.0, 105: 0.0, 106: 0.0, 107: 0.0, 108: 0.0, 109: 0.0}\n         Ion_nrg={1: 13.5984, 2: 24.5874, 3: 5.3917, 4: 9.3227, 5: 8.298, 6: 11.2603, 7: 14.5341, 8: 13.6181, 9: 17.4228, 10: 21.5645, 11: 5.1391, 12: 7.6462, 13: 5.9858, 14: 8.1517, 15: 10.4867, 16: 10.36, 17: 12.9676, 18: 15.7596, 19: 4.3407, 20: 6.1132, 21: 6.5615, 22: 6.8281, 23: 6.7462, 24: 6.7665, 25: 7.434, 26: 7.9024, 27: 7.881, 28: 7.6398, 29: 7.7264, 30: 9.3942, 31: 5.9993, 32: 7.8994, 33: 9.7886, 34: 9.7524, 35: 11.8138, 36: 13.9996, 37: 4.1771, 38: 5.6949, 39: 6.2173, 40: 6.6339, 41: 6.7589, 42: 7.0924, 43: 7.28, 44: 7.3605, 45: 7.4589, 46: 8.3369, 47: 7.5762, 48: 8.9938, 49: 5.7864, 50: 7.3439, 51: 8.6084, 52: 9.0096, 53: 10.4513, 54: 12.1298, 55: 3.8939, 56: 5.2117, 57: 5.5769, 58: 5.5387, 59: 5.473, 60: 5.525, 61: 5.582, 62: 5.6437, 63: 5.6704, 64: 6.1498, 65: 5.8638, 66: 5.9389, 67: 6.0215, 68: 6.1077, 69: 6.1843, 70: 6.2542, 71: 5.4259, 72: 6.8251, 73: 7.5496, 74: 7.864, 75: 7.8335, 76: 8.4382, 77: 8.967, 78: 8.9588, 79: 9.2255, 80: 10.4375, 81: 6.1082, 82: 7.4167, 83: 7.2855, 84: 8.414, 85: -1, 86: 10.7485, 87: 4.0727, 88: 5.2784, 89: 5.17, 90: 6.3067, 91: 5.89, 92: 6.1941, 93: 6.2657, 94: 6.026, 95: 5.9738, 96: 5.9914, 97: 6.1979, 98: 6.2817, 99: 6.42, 100: 6.5, 101: 6.58, 102: 6.65, 103: 4.9, 104: 6.0, 105: -1, 106: -1, 107: -1, 108: -1, 109: -1}\n         DEN=Elec_neg[sa] -Elec_neg[sb]\n         DEA=Elec_aff[sa] -Elec_aff[sb]\n         DIE=Ion_nrg[sa] - Ion_nrg[sb]\n         p=1\n         if self.deltaEN>0: p*=np.exp(-0.5*(DEN/self.deltaEN)**2)\n         if self.deltaEA>0: p*=np.exp(-0.5*(DEA/self.deltaEA)**2)\n         if self.deltaIE>0: p*=np.exp(-0.5*(DIE/self.deltaIE)**2)\n         return p\n   def __init__(self, rules={},deltaEN=1e100, deltaEA=1e100, deltaIE=1e100, mu=0):            \n      self.rules = rules.copy()\n      self.mu = mu\n      self.deltaEA= deltaEA\n      self.deltaIE= deltaIE\n      self.deltaEN= deltaEN            \n\ndef main(deltaEN,deltaEA,deltaIE,splist,alchemyrules):\n   if (alchemyrules==\"none\"):\n      alchem=alchemy_mendeleev(deltaEN=deltaEN,deltaIE=deltaIE,deltaEA=deltaEA,rules={})\n   else:\n       r=alchemyrules.replace('\"', '').strip()\n       r=alchemyrules.replace(\"'\", '').strip()\n       r=ast.literal_eval(r)\n       print >> sys.stderr, \"Using Alchemy rules: \", r,\"\\n\"\n       alchem=alchemy_mendelev(deltaEN=deltaEN,deltaIE=deltaIE,deltaEA=deltaEA,rules=r)\n   rule={}\n   for sa in splist:\n      for sb in splist:\n        if (sb >sa): \n           rule[(sa,sb)]=alchem.getpair(sa,sb)\n   print rule\n   f=\"alchemy\"\n   if deltaEN > 0: f+=\"_dEN\"+str(deltaEN)\n   if deltaEA > 0: f+=\"_dEA\"+str(deltaEA)\n   if deltaIE > 0: f+=\"_dIE\"+str(deltaIE)\n   f+=\".pickle\"\n   file = open(f,\"wb\")\n   gc.disable()\n   pickle.dump(rule, file,protocol=pickle.HIGHEST_PROTOCOL) # HIGHEST_PROTOCOL is 2 in py 2.7\n   file.close()\n   gc.enable()\nif __name__ == '__main__':\n      parser = argparse.ArgumentParser(description=\"\"\"Utility code to generate alchemy rules based on atomic properties.\"\"\")\n\n      parser.add_argument(\"--deltaEN\",type=float,default=\"-1\", help=\"Delta value for electronegativity\")\n      parser.add_argument(\"--deltaEA\",type=float,default=\"-1\", help=\"Delta value for electron affinity [eV]\")\n      parser.add_argument(\"--deltaIE\",type=float,default=\"-1\", help=\"Delta value for ionization energy [eV]\")            \n      parser.add_argument(\"--species\", type=str, default=\"all\", help=\"list of species (e.g. --species 1,6  for H and C )\")\n      parser.add_argument(\"--rules\", type=str, default=\"none\", help='Dictionary-style rule specification in quote (e.g. --rules \"{(6,7):1,(6,8):1}\"')\n      args = parser.parse_args()\n      if args.species == \"all\":\n         splist = []\n         for i in range(1,109):\n            splist.append(i)\n      else:\n         splist = sorted(map(int,args.species.split(',')))\n      main(deltaEN=args.deltaEN,deltaIE=args.deltaIE,deltaEA=args.deltaEA,splist=splist,alchemyrules=args.rules)\n", "meta": {"hexsha": "9c2cd9d7b329c5f4e1490b3ce907fb67b6fdabd1", "size": 7086, "ext": "py", "lang": "Python", "max_stars_repo_path": "tools/alchemy_rules.py", "max_stars_repo_name": "cosmo-epfl/glosim", "max_stars_repo_head_hexsha": "930998b7249adc0ac3e48308314233341de6e73f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2017-04-19T14:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T13:37:23.000Z", "max_issues_repo_path": "tools/alchemy_rules.py", "max_issues_repo_name": "lab-cosmo/glosim", "max_issues_repo_head_hexsha": "930998b7249adc0ac3e48308314233341de6e73f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-05-23T10:30:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-05T06:43:04.000Z", "max_forks_repo_path": "tools/alchemy_rules.py", "max_forks_repo_name": "lab-cosmo/glosim", "max_forks_repo_head_hexsha": "930998b7249adc0ac3e48308314233341de6e73f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2017-05-01T14:37:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T14:00:12.000Z", "avg_line_length": 75.3829787234, "max_line_length": 1286, "alphanum_fraction": 0.5692915608, "include": true, "reason": "import numpy", "num_tokens": 3747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.3007455789412415, "lm_q1q2_score": 0.1816298246871323}}
{"text": "#!/usr/bin/env python\n'''\nThis script performs the t-test validation for non-bit-for-bit results for the\nCICE model.\n\nWritten by: Matthew Turner\nDate: October, 2017\n'''\n\nimport os\nimport sys\nimport logging\nimport numpy as np\nimport numpy.ma as ma\nimport netCDF4 as nc\n\ndef maenumerate(marr):\n    '''\n    This function provides the enumerate functionality for masked arrays\n    '''\n    mask = ~marr.mask.ravel()\n    try:   # Python 2\n        import itertools\n        for i, m in itertools.izip(np.ndindex(marr.shape[-2:]), mask):\n            if m: yield i\n    except:  # Python 3\n        for i, m in zip(np.ndindex(marr.shape[-2:]), mask):\n            if m: yield i\n\ndef gen_filenames(base_dir, test_dir):\n    '''\n    This function is passed the directories of the baseline and test history\n    files and generates a list of filenames for each.\n    '''\n    # The path to output files for simulation 'a' (the '-bc' simulation)\n    if base_dir.endswith(('history', 'history/')):\n        path_a = base_dir\n    else:\n        path_a = base_dir + '/history/'\n\n    # The path to output files for simulation 'b' (the test simulation)\n    if test_dir.endswith(('history', 'history/')):\n        path_b = test_dir\n    else:\n        path_b = test_dir + '/history/'\n\n    # Find the number of output files to be read in\n    files_a = [i for i in os.listdir(path_a+'/') if i.startswith('iceh_inst.')]\n    files_b = [i for i in os.listdir(path_b+'/') if i.startswith('iceh_inst.')]\n\n    if not len(files_a) == len(files_b):\n        logger.error(\"Number of output files for baseline simulation does not match the number\" + \\\n              \" of files for the test simulation.  Exiting...\\n\" + \\\n              \"Baseline directory: {}\\n\".format(path_a) + \\\n              \"   # of files: {}\\n\".format(len(files_a)) + \\\n              \"Test directory: {}\\n\".format(path_b) + \\\n              \"   # of files: {}\".format(len(files_b)))\n        sys.exit(-1)\n\n    logger.info(\"Number of files: %d\", len(files_a))\n\n    return path_a, path_b, files_a, files_b\n\ndef get_geom(path, file):\n    '''\n    This function reads the ni, nj, tlat, and tlon variables from a netcdf file\n    '''\n    fid = nc.Dataset(\"{}/{}\".format(path, file), 'r')\n    tlat = fid.variables['TLAT'][:]\n    tlon = fid.variables['TLON'][:]\n    ni = fid.dimensions['ni'].size\n    nj = fid.dimensions['nj'].size\n    fid.close()\n\n    return ni, nj, tlat, tlon\n\ndef read_data(path_a, path_b, files_a, files_b, ni, nj):\n    '''\n    Read the baseline and test data for sea ice thickness.  The calculate\n    the difference for all locations where sea ice thickness is greater\n    than 0.01 meters.\n    '''\n    def fill_data_array(path, files, nj, ni):\n        '''Function to fill the data arrays'''\n        # Initialize the data array\n        data = np.zeros((len(files), nj, ni),dtype=np.float32)\n        # Read in the data\n        logger.debug('Reading in data for files in %s', path)\n        cnt = 0\n        for fname in sorted(files):\n            nfid = nc.Dataset(\"{}/{}\".format(path, fname), 'r')\n            fill_value = nfid.variables[var]._FillValue\n            data[cnt, :, :] = nfid.variables[var][:]\n            cnt += 1\n            nfid.close()\n        data[data == fill_value] = 0.0\n\n        return data\n\n    def calc_diff(data_a, data_b):\n        '''\n        Calculate the difference and mask the points where the the difference at\n        every timestep is 0, or the sea ice thickness for every timestep is < 0.01 meters\n        for data_a or data_b\n        '''\n        data_d = data_a - data_b\n        mask_d = np.logical_or(\\\n                      np.logical_or(\\\n                           np.all(np.equal(data_d, 0.), axis=0), np.all(data_a < 0.01, axis=0))\\\n                      , np.all(data_b < 0.01, axis=0))\n        mask_array_a = np.zeros_like(data_d)\n\n        for x, value in np.ndenumerate(mask_d):\n            i, j = x\n            mask_array_a[:, i, j] = value\n        del mask_d\n\n        data_a = ma.masked_array(data_a, mask=mask_array_a)\n        data_b = ma.masked_array(data_b, mask=mask_array_a)\n        data_d = ma.masked_array(data_d, mask=mask_array_a)\n\n        del mask_array_a\n\n        return data_a, data_b, data_d\n\n    var = 'hi'\n\n    data_a = fill_data_array(path_a, files_a, nj, ni)\n    data_b = fill_data_array(path_b, files_b, nj, ni)\n\n    data_a, data_b, data_d = calc_diff(data_a, data_b)\n\n    return data_a, data_b, data_d\n\ndef two_stage_test(data_a, num_files, data_d, fname, path):\n    '''\n    This function performs the Two-Stage Paired Thickness Test\n    '''\n    def stage_one(data_d, num_files, mean_d, variance_d):\n        logger.debug('Running step 1 of 2-stage test')\n\n        # Calculate the mean from 1:end-1 and 2:end\n        mean_nm1_d = np.mean(data_d[:-1, :, :], axis=0)\n        mean_2n_d = np.mean(data_d[1:, :, :], axis=0)\n\n        # Calculate equation (5) for both simulations\n        r1_num = np.zeros_like(mean_d)\n        r1_den1 = np.zeros_like(mean_d)\n        r1_den2 = np.zeros_like(mean_d)\n        for i in np.arange(np.size(data_a, axis=0)-1):\n            r1_num = r1_num + (data_d[i, :, :]-mean_nm1_d[:, :])*(data_d[i+1, :, :]-mean_2n_d[:, :])\n            r1_den1 = r1_den1 + np.square(data_d[i, :, :]-mean_nm1_d[:, :])\n\n        for i in np.arange(1, np.size(data_a, axis=0)):\n            r1_den2 = r1_den2 + np.square(data_d[i, :, :] - mean_2n_d[:, :])\n\n        r1 = r1_num / np.sqrt(r1_den1*r1_den2)\n\n        # Calculate the effective sample size\n        n_eff = num_files * ((1.-r1) / (1.+r1))\n        n_eff[n_eff < 2] = 2\n        n_eff[n_eff > num_files] = num_files\n\n        # Calculate the t-statistic with n_eff\n        t_val = mean_d / np.sqrt(variance_d / n_eff)\n\n        # Effective degrees of freedom\n        df = n_eff - 1\n\n        # Read in t_crit table\n        nfid = nc.Dataset(\"configuration/scripts/tests/QC/CICE_t_critical_p0.8.nc\", 'r')\n        df_table = nfid.variables['df'][:]\n        t_crit_table = nfid.variables['tcrit'][:]\n        nfid.close()\n        t_crit = np.zeros_like(t_val)\n\n        # Calculate critical t-value for each grid cell, based on the t_crit table\n        for x in maenumerate(data_d):\n            min_val = np.min(np.abs(df[x]-df_table))\n            idx = np.where(np.abs(df[x]-df_table) == min_val)\n            # Handle the cases where the data point falls exactly half way between\n            # 2 critical T-values (i.e., idx has more than 1 value in it)\n            while True:\n                try:\n                    idx = idx[0]\n                except:\n                    break\n            t_crit[x] = t_crit_table[idx]\n\n        # Create an array of Pass / Fail values for each grid cell\n        H1 = np.abs(t_val) > t_crit\n\n        return n_eff, H1, r1, t_crit\n\n    # Calculate the mean of the difference\n    mean_d = np.mean(data_d, axis=0)\n\n    # Loop through each timestep and calculate the square of the difference.\n    # This is required (instead of just np.square(data_d - mean_d) to reduce\n    # the memory footprint of the script.\n    tmp1 = np.zeros_like(data_d)\n    for i in np.arange(np.shape(data_d)[0]):\n        tmp1[i,:,:] = np.square(data_d[i,:,:] - mean_d[:,:])\n    variance_d = np.sum(tmp1) / float(num_files - 1)\n\n    n_eff, H1, r1, t_crit = stage_one(data_d, num_files, mean_d, variance_d)\n\n    if np.all(H1 == False) and np.all(n_eff >= 30):\n        # H0 confirmed in all cells, and all effective sample size >= 30\n        logger.debug('H0 confirmed in all cells, and all effective sample size >= 30')\n        logger.info('2 stage test passed')\n        return True, H1\n\n    elif np.all(H1):\n        # H1 in every grid cell\n        logger.debug('H1 in all cells')\n        logger.info('2 stage test failed')\n        return False, H1\n\n########### H0 confirmed for some grid cells with n_eff < 30 ############\n    logger.debug('Number of H1 grid cells after stage 1 = %d', np.sum(H1))\n\n    logger.debug('Running step 2 of 2-stage test')\n\n    # Find the indices where n_eff is less than 30, and H0 is confirmed\n    tmp_idx = np.where(n_eff < 30) and np.where(H1 == False)\n\n    # Calculate the T-statistic using actual sample size\n    t_val = mean_d / np.sqrt(variance_d / num_files)\n\n    # Find t_crit from the nearest value on the Lookup Table Test\n    nfid = nc.Dataset(\"configuration/scripts/tests/QC/CICE_Lookup_Table_p0.8_n1825.nc\", 'r')\n    r1_table = nfid.variables['r1'][:]\n    t_crit_table = nfid.variables['tcrit'][:]\n    nfid.close()\n\n    # Fill t_crit based on lookup table\n    for x in maenumerate(data_d):\n        min_val = np.min(np.abs(r1[x]-r1_table))\n        idx = np.where(np.abs(r1[x]-r1_table) == min_val)\n        # Handle the cases where the data point falls exactly half way between\n        # 2 critical T-values (i.e., idx has more than 1 value in it)\n        while True:\n            try:\n                idx = idx[0]\n            except:\n                break\n        t_crit[x] = t_crit_table[idx]\n\n    # Create an array showing locations of Pass / Fail grid cells\n    H1[tmp_idx] = abs(t_val[tmp_idx]) > t_crit[tmp_idx]\n\n    logger.debug('Number of H1 grid cells after stage 2 = %d', np.sum(H1))\n\n    if np.all(H1):\n        # H1 in all grid cells\n        logger.debug('H1 in all cells, stage 2')\n        logger.info('2 Stage Test Failed')\n        return False, H1\n\n    elif np.all(H1 == False):\n        # H0 confirmed in all grid cells\n        logger.debug('H0 confirmed in all cells with n_eff < 30')\n        logger.info('2 Stage Test Passed')\n        return True, H1\n\n####### Some grid cells have H0 confirmed, and some do not ######\n\n    # Calculate the area-weighted fraction of the test region that failed (f_val).\n    #   If f_val is greater than or equal to the critical fraction, the test fails\"\n    f_val = critical_fraction(data_a, H1, fname, path)\n    f_crit = 0.5\n    if f_val >= f_crit:\n        logger.info('2 Stage Test Failed')\n        logger.debug('Area-weighted fraction of failures is greater than ' + \\\n                    'critical fraction.  Test failed.')\n        logger.debug('Area-weighted fraction of failures = %f', f_val)\n        return False, H1\n    else:\n        logger.info('2 Stage Test Passed')\n        logger.debug('Area-weighted fraction of failures = %f', f_val)\n        return True, H1\n\ndef critical_fraction(data_a, failures, fname, path_a):\n    '''\n    This function calculates the area-weighted average of cells where H1 is true.\n    '''\n    logger.debug('Calculating area-weighted average of H1 cells')\n    # First calculate the weight attributed to each grid point (based on Area)\n    nfid = nc.Dataset(\"{}/{}\".format(path_a, fname), 'r')\n    tarea = nfid.variables['tarea'][:]\n    nfid.close()\n    tarea = ma.masked_array(tarea, mask=data_a[0, :, :].mask)\n    area_weight = tarea / np.sum(tarea)\n\n    # Calculate the area weight of the failing grid cells\n    weight_tot = 0\n    weight_fail = 0\n    for x in maenumerate(data_a):\n        weight_tot += area_weight[x]\n        if failures[x]:\n            weight_fail += area_weight[x]\n\n    return weight_fail/weight_tot\n\ndef skill_test(path_a, fname, data_a, data_b, num_files, hemisphere):\n    '''Calculate Taylor Skill Score'''\n    # First calculate the weight attributed to each grid point (based on Area)\n    nfid = nc.Dataset(\"{}/{}\".format(path_a, fname), 'r')\n    tarea = nfid.variables['tarea'][:]\n    nfid.close()\n    tarea = ma.masked_array(tarea, mask=data_a[0, :, :].mask)\n    area_weight = tarea / np.sum(tarea)\n\n    weighted_mean_a = 0\n    weighted_mean_b = 0\n    for i in np.arange(num_files):\n        weighted_mean_a = weighted_mean_a + np.sum(area_weight*data_a[i, :, :])\n        weighted_mean_b = weighted_mean_b + np.sum(area_weight*data_b[i, :, :])\n\n    weighted_mean_a = weighted_mean_a / num_files\n    weighted_mean_b = weighted_mean_b / num_files\n\n    nonzero_weights = np.count_nonzero(area_weight)\n    area_var_a = 0\n    area_var_b = 0\n    for t in np.arange(num_files):\n        area_var_a = area_var_a + np.sum(area_weight*np.square(data_a[t, :, :]-weighted_mean_a))\n        area_var_b = area_var_b + np.sum(area_weight*np.square(data_b[t, :, :]-weighted_mean_b))\n\n    area_var_a = nonzero_weights / (num_files * nonzero_weights - 1.) * area_var_a\n    area_var_b = nonzero_weights / (num_files * nonzero_weights - 1.) * area_var_b\n    std_a = np.sqrt(area_var_a)\n    std_b = np.sqrt(area_var_b)\n\n    combined_cov = 0\n    for i in np.arange(num_files):\n        combined_cov = combined_cov + np.sum(area_weight*(data_a[i, :, :]-weighted_mean_a)*\\\n                                            (data_b[i, :, :]-weighted_mean_b))\n\n    combined_cov = nonzero_weights / (num_files * nonzero_weights - 1.) * combined_cov\n\n    weighted_r = combined_cov / (std_a*std_b)\n\n    s = np.square((1+weighted_r)*(std_a*std_b)/\\\n                 (area_var_a + area_var_b))\n\n    logger.debug('%s Hemisphere skill score = %f', hemisphere, s)\n\n    s_crit = 0.99\n    if s < 0 or s > 1:\n        logger.error('Skill score out of range for %s Hemisphere', hemisphere)\n        return False\n    elif s > s_crit:\n        logger.info('Quadratic Skill Test Passed for %s Hemisphere', hemisphere)\n        return True\n    else:\n        logger.info('Quadratic Skill Test Failed for %s Hemisphere', hemisphere)\n        return False\n\ndef plot_data(data, lat, lon, units, case, plot_type):\n    '''This function plots CICE data and creates a .png file.'''\n\n    try:\n        # Load the necessary plotting libraries\n        import matplotlib.pyplot as plt\n        from mpl_toolkits.basemap import Basemap\n        from mpl_toolkits.axes_grid1 import make_axes_locatable\n    except ImportError:\n        logger.warning('Error loading necessary Python modules in plot_data function')\n        return\n\n    # Suppress Matplotlib deprecation warnings\n    import warnings\n    warnings.filterwarnings(\"ignore\", category=UserWarning)\n\n    # Create the figure and axis\n    fig, axes = plt.subplots(nrows=1, ncols=2,figsize=(14, 8))\n\n    # Plot the northern hemisphere data as a scatter plot\n    # Create the basemap, and draw boundaries\n    plt.sca(axes[0])\n    m = Basemap(projection='npstere', boundinglat=35,lon_0=270, resolution='l')\n    m.drawcoastlines()\n    m.fillcontinents()\n    m.drawcountries()\n\n    if plot_type == 'scatter':\n        x, y = m(lon,lat)\n        sc = m.scatter(x, y, c=data, cmap='jet', lw=0, s=4)\n    else:\n        # Create new arrays to add 1 additional longitude value to prevent a \n        # small amount of whitespace around longitude of 0/360 degrees.\n        lon_cyc = np.zeros((lon.shape[0],lon.shape[1]+1))\n        mask = np.zeros((data.shape[0],data.shape[1]+1))\n        lat_cyc = np.zeros((lat.shape[0],lat.shape[1]+1))\n\n        mask[:,0:-1] = data.mask[:,:]\n        mask[:,-1] = data.mask[:,0]\n        lon_cyc[:,0:-1] = lon[:,:]; lon_cyc[:,-1] = lon[:,0]\n        lat_cyc[:,0:-1] = lat[:,:]; lat_cyc[:,-1] = lat[:,0]\n\n        lon1 = np.ma.masked_array(lon_cyc, mask=mask)\n        lat1 = np.ma.masked_array(lat_cyc, mask=mask)\n\n        d = np.zeros((data.shape[0],data.shape[1]+1))\n        d[:,0:-1] = data[:,:]\n        d[:,-1] = data[:,0]\n        d1 = np.ma.masked_array(d,mask=mask)\n\n        x, y = m(lon1.data, lat1.data)\n\n        if plot_type == 'contour':\n            sc = m.contourf(x, y, d1, cmap='jet')\n        else:  # pcolor\n            sc = m.pcolor(x, y, d1, cmap='jet')\n\n    m.drawparallels(np.arange(-90.,120.,15.),labels=[1,0,0,0]) # draw parallels\n    m.drawmeridians(np.arange(0.,420.,30.),labels=[1,1,1,1]) # draw meridians\n\n    # Plot the southern hemisphere data as a scatter plot\n    plt.sca(axes[1])\n    m = Basemap(projection='spstere', boundinglat=-45,lon_0=270, resolution='l')\n    m.drawcoastlines()\n    m.fillcontinents()\n    m.drawcountries()\n\n    if plot_type == 'scatter':\n        x, y = m(lon,lat)\n        sc = m.scatter(x, y, c=data, cmap='jet', lw=0, s=4)\n    else:\n        x, y = m(lon1.data, lat1.data)\n\n        # Bandaid for a bug in the version of Basemap used during development\n        outside = (x <= m.xmin) | (x >= m.xmax) | (y <= m.ymin) | (y >= m.ymax)\n        tmp = np.ma.masked_where(outside,d1)\n\n        if plot_type == 'contour':\n            sc = m.contourf(x, y, tmp, cmap='jet')\n        else:  # pcolor\n            sc = m.pcolor(x, y, tmp, cmap='jet')\n\n    m.drawparallels(np.arange(-90.,120.,15.),labels=[1,0,0,0]) # draw parallels\n    m.drawmeridians(np.arange(0.,420.,30.),labels=[1,1,1,1]) # draw meridians\n\n    plt.suptitle('CICE Mean Ice Thickness\\n{}'.format(case), y=0.95)\n\n    # Make some room at the bottom of the figure, and create a colorbar\n    fig.subplots_adjust(bottom=0.2)\n    cbar_ax = fig.add_axes([0.11,0.1,0.8,0.05])\n    if '\\n- ' in case:\n      # If making a difference plot, use scientific notation for colorbar\n      cb = plt.colorbar(sc, cax=cbar_ax, orientation=\"horizontal\", format=\"%.2e\")\n    else:\n      # If plotting non-difference data, do not use scientific notation for colorbar\n      cb = plt.colorbar(sc, cax=cbar_ax, orientation=\"horizontal\", format=\"%.2f\")\n    cb.set_label(units, x=1.0)\n\n    outfile = 'ice_thickness_{}.png'.format(case.replace('\\n- ','_minus_'))\n    logger.info('Creating map of the data ({})'.format(outfile))\n    plt.savefig(outfile, dpi=300, bbox_inches='tight')\n\ndef plot_two_stage_failures(data, lat, lon):\n    '''This function plots each grid cell and whether or not it Passed or Failed\n       the two-stage test.  It then either creates a .png file\n       (two_stage_test_failure_map.png), or saves the failure locations to a\n       text file.\n    '''\n\n    # Convert the boolean array (data) to an integer array\n    int_data = data.astype(int)\n\n    try:\n        logger.info('Creating map of the failures (two_stage_test_failure_map.png)')\n        # Load the necessary plotting libraries\n        import matplotlib.pyplot as plt\n        from mpl_toolkits.basemap import Basemap\n        from mpl_toolkits.axes_grid1 import make_axes_locatable\n        from matplotlib.colors import LinearSegmentedColormap\n\n        # Suppress Matplotlib deprecation warnings\n        import warnings\n        warnings.filterwarnings(\"ignore\", category=UserWarning)\n\n        # Create the figure and axis\n        fig = plt.figure(figsize=(12, 8))\n        ax = fig.add_axes([0.05, 0.08, 0.9, 0.9])\n\n        # Create the basemap, and draw boundaries\n        m = Basemap(projection='moll', lon_0=0., resolution='l')\n        m.drawmapboundary(fill_color='white')\n        m.drawcoastlines()\n        m.drawcountries()\n\n        # Create the custom colormap\n        colors = [(0, 0, 1), (1, 0, 0)]  # Blue, Red\n        cmap_name = 'RB_2bins'\n        cm = LinearSegmentedColormap.from_list(cmap_name, colors, N=2)\n\n        # Plot the data as a scatter plot\n        x, y = m(lon, lat)\n        sc = m.scatter(x, y, c=int_data, cmap=cm, lw=0, vmin=0, vmax=1, s=4)\n\n        m.drawmeridians(np.arange(0, 360, 60), labels=[0, 0, 0, 1], fontsize=10)\n        m.drawparallels(np.arange(-90, 90, 30), labels=[1, 0, 0, 0], fontsize=10)\n\n        plt.title('CICE Two-Stage Test Failures')\n\n        # Create the colorbar and add Pass / Fail labels\n        divider = make_axes_locatable(ax)\n        cax = divider.append_axes(\"bottom\", size=\"5%\", pad=0.5)\n        cb = plt.colorbar(sc, cax=cax, orientation=\"horizontal\", format=\"%.0f\")\n        cb.set_ticks([])\n        cb.ax.text(-0.01, -0.5, 'PASS')\n        cb.ax.text(0.99, -0.5, 'FAIL')\n\n        plt.savefig('two_stage_test_failure_map.png', dpi=300)\n    except:\n        logger.warning('')\n        logger.warning('Unable to plot the data.  Saving latitude and longitude')\n        logger.warning('for ONLY failures to two_stage_failure_locations.txt')\n\n        # Create a file and write the failures only to the file\n        f = open('two_stage_failure_locations.txt', 'w')\n        f.write('# CICE Two-stage test failures\\n')\n        f.write('# Longitude,Latitude\\n')\n        for i in range(data.shape[0]):\n            for j in range(data.shape[1]):\n                if (not data.mask[i, j]) and data[i, j]:\n                    f.write('{},{}\\n'.format(lon[i, j], lat[i, j]))\n\n        f.close()\n\ndef main():\n    import argparse\n    parser = argparse.ArgumentParser(description='This script performs the T-test for \\\n                           CICE simulations that should be bit-for-bit, but are not.')\n    parser.add_argument('base_dir', \\\n                help='Path to the baseline history (iceh_inst*) files.  REQUIRED')\n    parser.add_argument('test_dir', \\\n                help='Path to the test history (iceh_inst*) files.  REQUIRED')\n    parser.add_argument('-v', '--verbose', dest='verbose', help='Print debug output?', \\\n                        action='store_true')\n    parser.add_argument('-pt','--plot_type', dest='plot_type', help='Specify type of plot \\\n                        to create', choices=['scatter','contour','pcolor'])\n\n    parser.set_defaults(verbose=False)\n    parser.set_defaults(plot_type='pcolor')\n\n    # If no arguments are provided, print the help message\n    if len(sys.argv) == 1:\n        parser.print_help()\n        sys.exit(1)\n\n    args = parser.parse_args()\n\n    # Set up the logger\n    global logger\n    if args.verbose:\n        logging.basicConfig(level=logging.DEBUG)\n    else:\n        logging.basicConfig(level=logging.INFO)\n    # Log to log file as well as stdout\n    fh = logging.FileHandler(r'qc_log.txt', 'w')\n    logger = logging.getLogger(__name__)\n    logger.addHandler(fh)\n\n    logger.info('Running QC test on the following directories:')\n    logger.info('  {}'.format(args.base_dir))\n    logger.info('  {}'.format(args.test_dir))\n\n    dir_a, dir_b, files_base, files_test = gen_filenames(args.base_dir, args.test_dir)\n\n    nfiles = len(files_base)\n\n    nlon, nlat, t_lat, t_lon = get_geom(dir_a, files_base[0])\n\n    data_base, data_test, data_diff = read_data(dir_a, dir_b, files_base, files_test, nlon, nlat)\n\n    if np.ma.all(data_diff.mask):\n        logger.info(\"Data is bit-for-bit.  No need to run QC test\")\n        sys.exit(0)\n\n    # Run the two-stage test\n    PASSED, H1_array = two_stage_test(data_base, nfiles, data_diff, files_base[0], dir_a)\n\n    # Delete arrays that are no longer necessary\n    del data_diff\n\n    # If test failed, attempt to create a plot of the failure locations\n    if not PASSED:\n        plot_two_stage_failures(H1_array, t_lat, t_lon)\n        \n        # Create plots of mean ice thickness\n        baseDir = os.path.abspath(args.base_dir).rstrip('history/').rstrip(\\\n                                                        'history').split('/')[-1]\n        testDir = os.path.abspath(args.test_dir).rstrip('history/').rstrip( \\\n                                                        'history').split('/')[-1]\n        plot_data(np.mean(data_base,axis=0), t_lat, t_lon, 'm', baseDir, args.plot_type)\n        plot_data(np.mean(data_test,axis=0), t_lat, t_lon, 'm', testDir, args.plot_type)\n        plot_data(np.mean(data_base-data_test,axis=0), t_lat, t_lon, 'm', '{}\\n- {}'.\\\n                  format(baseDir,testDir), args.plot_type)\n\n        logger.error('Quality Control Test FAILED')\n        sys.exit(-1)\n\n    # Create a northern hemisphere and southern hemisphere mask\n    mask_tlat = t_lat < 0\n    mask_nh = np.zeros_like(data_base)\n    mask_sh = np.zeros_like(data_base)\n    for (a, b), val in np.ndenumerate(mask_tlat):\n        mask_nh[:, a, b] = val\n        mask_sh[:, a, b] = not val\n\n    # Run skill test on northern hemisphere\n    data_nh_a = ma.masked_array(data_base, mask=mask_nh)\n    data_nh_b = ma.masked_array(data_test, mask=mask_nh)\n    if np.ma.all(data_nh_a.mask) and np.ma.all(data_nh_b.mask):\n        logger.info(\"Northern Hemisphere data is bit-for-bit\")\n        PASSED_NH = True\n    else:\n        PASSED_NH = skill_test(dir_a, files_base[0], data_nh_a, data_nh_b, nfiles, 'Northern')\n\n    # Run skill test on southern hemisphere\n    data_sh_a = ma.masked_array(data_base, mask=mask_sh)\n    data_sh_b = ma.masked_array(data_test, mask=mask_sh)\n    if np.ma.all(data_sh_a.mask) and np.ma.all(data_sh_b.mask):\n        logger.info(\"Southern Hemisphere data is bit-for-bit\")\n        PASSED_SH = True\n    else:\n        PASSED_SH = skill_test(dir_a, files_base[0], data_sh_a, data_sh_b, nfiles, 'Southern')\n\n    PASSED_SKILL = PASSED_NH and PASSED_SH\n\n    # Plot the ice thickness data for the base and test cases\n    baseDir = os.path.abspath(args.base_dir).rstrip('history/').rstrip( \\\n                                                    'history').split('/')[-1]\n    testDir = os.path.abspath(args.test_dir).rstrip('history/').rstrip( \\\n                                                    'history').split('/')[-1]\n    plot_data(np.mean(data_base,axis=0), t_lat, t_lon, 'm', baseDir, args.plot_type)\n    plot_data(np.mean(data_test,axis=0), t_lat, t_lon, 'm', testDir, args.plot_type)\n    plot_data(np.mean(data_base-data_test,axis=0), t_lat, t_lon, 'm', '{}\\n- {}'.\\\n              format(baseDir,testDir), args.plot_type)\n\n    logger.info('')\n    if not PASSED_SKILL:\n        logger.error('Quality Control Test FAILED')\n        sys.exit(1)  # exit with an error return code\n    else:\n        logger.info('Quality Control Test PASSED')\n        sys.exit(0)  # exit with successfull return code\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "9871752451373ebe2946d5cb085bd4990a958f92", "size": 25143, "ext": "py", "lang": "Python", "max_stars_repo_path": "CICE-interface/CICE/configuration/scripts/tests/QC/cice.t-test.py", "max_stars_repo_name": "minsukji/ci-debug", "max_stars_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_stars_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CICE-interface/CICE/configuration/scripts/tests/QC/cice.t-test.py", "max_issues_repo_name": "minsukji/ci-debug", "max_issues_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_issues_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CICE-interface/CICE/configuration/scripts/tests/QC/cice.t-test.py", "max_forks_repo_name": "minsukji/ci-debug", "max_forks_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_forks_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.386259542, "max_line_length": 100, "alphanum_fraction": 0.6146840075, "include": true, "reason": "import numpy", "num_tokens": 6668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096343, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.1816022654321094}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport numpy as np\nimport astropy.units as u\nfrom astropy.io import fits\nfrom astropy.table import Table\nfrom gammapy.maps import MapAxis\nfrom gammapy.maps.utils import edges_from_lo_hi\nfrom gammapy.utils.nddata import NDDataArray\nfrom gammapy.utils.scripts import make_path\n\n__all__ = [\"EffectiveAreaTable\", \"EffectiveAreaTable2D\"]\n\n\nclass EffectiveAreaTable:\n    \"\"\"Effective area table.\n\n    TODO: Document\n\n    Parameters\n    ----------\n    energy_lo, energy_hi : `~astropy.units.Quantity`\n        Energy axis bin edges\n    data : `~astropy.units.Quantity`\n        Effective area\n\n    Examples\n    --------\n    Plot parametrized effective area for HESS, HESS2 and CTA.\n\n    .. plot::\n        :include-source:\n\n        import numpy as np\n        import matplotlib.pyplot as plt\n        import astropy.units as u\n        from gammapy.irf import EffectiveAreaTable\n\n        energy = np.logspace(-3, 3, 100) * u.TeV\n\n        for instrument in ['HESS', 'HESS2', 'CTA']:\n            aeff = EffectiveAreaTable.from_parametrization(energy, instrument)\n            ax = aeff.plot(label=instrument)\n\n        ax.set_yscale('log')\n        ax.set_xlim([1e-3, 1e3])\n        ax.set_ylim([1e3, 1e12])\n        plt.legend(loc='best')\n        plt.show()\n\n    Find energy where the effective area is at 10% of its maximum value\n\n    >>> import numpy as np\n    >>> import astropy.units as u\n    >>> from gammapy.irf import EffectiveAreaTable\n    >>> energy = np.logspace(-1, 2) * u.TeV\n    >>> aeff_max = aeff.max_area\n    >>> print(aeff_max).to('m2')\n    156909.413371 m2\n    >>> energy_threshold = aeff.find_energy(0.1 * aeff_max)\n    >>> print(energy_threshold)\n    0.185368478744 TeV\n    \"\"\"\n\n    def __init__(self, energy_lo, energy_hi, data, meta=None):\n\n        e_edges = edges_from_lo_hi(energy_lo, energy_hi)\n        energy_axis = MapAxis.from_edges(e_edges, interp=\"log\", name=\"energy\")\n\n        interp_kwargs = {\"extrapolate\": False, \"bounds_error\": False}\n        self.data = NDDataArray(\n            axes=[energy_axis], data=data, interp_kwargs=interp_kwargs\n        )\n        self.meta = meta or {}\n\n    @property\n    def energy(self):\n        return self.data.axis(\"energy\")\n\n    def plot(self, ax=None, energy=None, show_energy=None, **kwargs):\n        \"\"\"Plot effective area.\n\n        Parameters\n        ----------\n        ax : `~matplotlib.axes.Axes`, optional\n            Axis\n        energy : `~astropy.units.Quantity`\n            Energy nodes\n        show_energy : `~astropy.units.Quantity`, optional\n            Show energy, e.g. threshold, as vertical line\n\n        Returns\n        -------\n        ax : `~matplotlib.axes.Axes`\n            Axis\n        \"\"\"\n        import matplotlib.pyplot as plt\n\n        ax = plt.gca() if ax is None else ax\n\n        kwargs.setdefault(\"lw\", 2)\n\n        if energy is None:\n            energy = self.energy.center\n\n        eff_area = self.data.evaluate(energy=energy)\n\n        xerr = (\n            (energy - self.energy.edges[:-1]).value,\n            (self.energy.edges[1:] - energy).value,\n        )\n\n        ax.errorbar(energy.value, eff_area.value, xerr=xerr, **kwargs)\n        if show_energy is not None:\n            ener_val = u.Quantity(show_energy).to_value(self.energy.unit)\n            ax.vlines(ener_val, 0, 1.1 * self.max_area.value, linestyles=\"dashed\")\n        ax.set_xscale(\"log\")\n        ax.set_xlabel(f\"Energy [{self.energy.unit}]\")\n        ax.set_ylabel(f\"Effective Area [{self.data.data.unit}]\")\n\n        return ax\n\n    @classmethod\n    def from_parametrization(cls, energy, instrument=\"HESS\"):\n        r\"\"\"Create parametrized effective area.\n\n        Parametrizations of the effective areas of different Cherenkov\n        telescopes taken from Appendix B of Abramowski et al. (2010), see\n        https://ui.adsabs.harvard.edu/abs/2010MNRAS.402.1342A .\n\n        .. math::\n            A_{eff}(E) = g_1 \\left(\\frac{E}{\\mathrm{MeV}}\\right)^{-g_2}\\exp{\\left(-\\frac{g_3}{E}\\right)}\n\n        Parameters\n        ----------\n        energy : `~astropy.units.Quantity`\n            Energy binning, analytic function is evaluated at log centers\n        instrument : {'HESS', 'HESS2', 'CTA'}\n            Instrument name\n        \"\"\"\n        energy = u.Quantity(energy)\n        # Put the parameters g in a dictionary.\n        # Units: g1 (cm^2), g2 (), g3 (MeV)\n        # Note that whereas in the paper the parameter index is 1-based,\n        # here it is 0-based\n        pars = {\n            \"HESS\": [6.85e9, 0.0891, 5e5],\n            \"HESS2\": [2.05e9, 0.0891, 1e5],\n            \"CTA\": [1.71e11, 0.0891, 1e5],\n        }\n\n        if instrument not in pars.keys():\n            ss = f\"Unknown instrument: {instrument}\\n\"\n            ss += \"Valid instruments: HESS, HESS2, CTA\"\n            raise ValueError(ss)\n\n        xx = MapAxis.from_edges(energy, interp=\"log\").center.to_value(\"MeV\")\n\n        g1 = pars[instrument][0]\n        g2 = pars[instrument][1]\n        g3 = -pars[instrument][2]\n\n        value = g1 * xx ** (-g2) * np.exp(g3 / xx)\n        data = u.Quantity(value, \"cm2\", copy=False)\n\n        return cls(energy_lo=energy[:-1], energy_hi=energy[1:], data=data)\n\n    @classmethod\n    def from_constant(cls, energy, value):\n        \"\"\"Create constant value effective area.\n\n        Parameters\n        ----------\n        energy : `~astropy.units.Quantity`\n            Energy binning, analytic function is evaluated at log centers\n        value : `~astropy.units.Quantity`\n            Effective area\n        \"\"\"\n        data = np.ones((len(energy) - 1)) * u.Quantity(value)\n        return cls(energy_lo=energy[:-1], energy_hi=energy[1:], data=data)\n\n    @classmethod\n    def from_table(cls, table):\n        \"\"\"Create from `~astropy.table.Table` in ARF format.\n\n        Data format specification: :ref:`gadf:ogip-arf`\n        \"\"\"\n        energy_lo = table[\"ENERG_LO\"].quantity\n        energy_hi = table[\"ENERG_HI\"].quantity\n        data = table[\"SPECRESP\"].quantity\n        return cls(energy_lo=energy_lo, energy_hi=energy_hi, data=data)\n\n    @classmethod\n    def from_hdulist(cls, hdulist, hdu=\"SPECRESP\"):\n        \"\"\"Create from `~astropy.io.fits.HDUList`.\"\"\"\n        return cls.from_table(Table.read(hdulist[hdu]))\n\n    @classmethod\n    def read(cls, filename, hdu=\"SPECRESP\"):\n        \"\"\"Read from file.\"\"\"\n        filename = make_path(filename)\n        with fits.open(filename, memmap=False) as hdulist:\n            try:\n                return cls.from_hdulist(hdulist, hdu=hdu)\n            except KeyError:\n                raise ValueError(\n                    f\"File {filename} contains no HDU {hdu!r}\\n\"\n                    f\"Available: {[_.name for _ in hdulist]}\"\n                )\n\n    def to_table(self):\n        \"\"\"Convert to `~astropy.table.Table` in ARF format.\n\n        Data format specification: :ref:`gadf:ogip-arf`\n        \"\"\"\n        table = Table()\n        table.meta = {\n            \"EXTNAME\": \"SPECRESP\",\n            \"hduclass\": \"OGIP\",\n            \"hduclas1\": \"RESPONSE\",\n            \"hduclas2\": \"SPECRESP\",\n        }\n\n        energy = self.energy.edges\n        table[\"ENERG_LO\"] = energy[:-1]\n        table[\"ENERG_HI\"] = energy[1:]\n        table[\"SPECRESP\"] = self.evaluate_fill_nan()\n        return table\n\n    def to_hdulist(self, name=None, use_sherpa=False):\n        \"\"\"Convert to `~astropy.io.fits.HDUList`.\"\"\"\n        table = self.to_table()\n\n        if use_sherpa:\n            table[\"ENERG_HI\"] = table[\"ENERG_HI\"].quantity.to(\"keV\")\n            table[\"ENERG_LO\"] = table[\"ENERG_LO\"].quantity.to(\"keV\")\n            table[\"SPECRESP\"] = table[\"SPECRESP\"].quantity.to(\"cm2\")\n\n        return fits.HDUList([fits.PrimaryHDU(), fits.BinTableHDU(table, name=name)])\n\n    def write(self, filename, use_sherpa=False, **kwargs):\n        \"\"\"Write to file.\"\"\"\n        filename = make_path(filename)\n        self.to_hdulist(use_sherpa=use_sherpa).writeto(filename, **kwargs)\n\n    def evaluate_fill_nan(self, **kwargs):\n        \"\"\"Modified evaluate function.\n\n        Calls :func:`gammapy.utils.nddata.NDDataArray.evaluate` and replaces\n        possible nan values. Below the finite range the effective area is set\n        to zero and above to value of the last valid note. This is needed since\n        other codes, e.g. sherpa, don't like nan values in FITS files. Make\n        sure that the replacement happens outside of the energy range, where\n        the `~gammapy.irf.EffectiveAreaTable` is used.\n        \"\"\"\n        retval = self.data.evaluate(**kwargs)\n        idx = np.where(np.isfinite(retval))[0]\n        retval[np.arange(idx[0])] = 0\n        retval[np.arange(idx[-1], len(retval))] = retval[idx[-1]]\n        return retval\n\n    @property\n    def max_area(self):\n        \"\"\"Maximum effective area.\"\"\"\n        cleaned_data = self.data.data[np.where(~np.isnan(self.data.data))]\n        return cleaned_data.max()\n\n    def find_energy(self, aeff, emin=None, emax=None):\n        \"\"\"Find energy for a given effective area.\n\n        In case the solution is not unique, provide the `emin` or `emax` arguments\n        to limit the solution to the given range. By default the peak energy of the\n        effective area is chosen as `emax`.\n\n        Parameters\n        ----------\n        aeff : `~astropy.units.Quantity`\n            Effective area value\n        emin : `~astropy.units.Quantity`\n            Lower bracket value in case solution is not unique.\n        emax : `~astropy.units.Quantity`\n            Upper bracket value in case solution is not unique.\n\n        Returns\n        -------\n        energy : `~astropy.units.Quantity`\n            Energy corresponding to the given aeff.\n        \"\"\"\n        from gammapy.modeling.models import TemplateSpectralModel\n\n        energy = self.energy.center\n\n        if emin is None:\n            emin = energy[0]\n        if emax is None:\n            # use the peak effective area as a default for the energy maximum\n            emax = energy[np.argmax(self.data.data)]\n\n        aeff_spectrum = TemplateSpectralModel(energy, self.data.data)\n        return aeff_spectrum.inverse(aeff, emin=emin, emax=emax)\n\n\nclass EffectiveAreaTable2D:\n    \"\"\"2D effective area table.\n\n    Data format specification: :ref:`gadf:aeff_2d`\n\n    Parameters\n    ----------\n    energy_lo, energy_hi : `~astropy.units.Quantity`\n        Energy binning\n    offset_lo, offset_hi : `~astropy.units.Quantity`\n        Field of view offset angle.\n    data : `~astropy.units.Quantity`\n        Effective area\n\n    Examples\n    --------\n    Here's an example you can use to learn about this class:\n\n    >>> from gammapy.irf import EffectiveAreaTable2D\n    >>> filename = '$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits'\n    >>> aeff = EffectiveAreaTable2D.read(filename, hdu='EFFECTIVE AREA')\n    >>> print(aeff)\n    EffectiveAreaTable2D\n    NDDataArray summary info\n    energy         : size =    42, min =  0.014 TeV, max = 177.828 TeV\n    offset         : size =     6, min =  0.500 deg, max =  5.500 deg\n    Data           : size =   252, min =  0.000 m2, max = 5371581.000 m2\n\n    Here's another one, created from scratch, without reading a file:\n\n    >>> from gammapy.irf import EffectiveAreaTable2D\n    >>> import astropy.units as u\n    >>> import numpy as np\n    >>> energy = np.logspace(0,1,11) * u.TeV\n    >>> offset = np.linspace(0,1,4) * u.deg\n    >>> data = np.ones(shape=(10,3)) * u.cm * u.cm\n    >>> aeff = EffectiveAreaTable2D(energy_lo=energy[:-1], energy_hi=energy[1:], offset_lo=offset[:-1],\n    >>>                             offset_hi=offset[1:], data= data)\n    >>> print(aeff)\n    Data array summary info\n    energy         : size =    11, min =  1.000 TeV, max = 10.000 TeV\n    offset         : size =     4, min =  0.000 deg, max =  1.000 deg\n    Data           : size =    30, min =  1.000 cm2, max =  1.000 cm2\n    \"\"\"\n\n    default_interp_kwargs = dict(bounds_error=False, fill_value=None)\n    \"\"\"Default Interpolation kwargs for `~NDDataArray`. Extrapolate.\"\"\"\n\n    def __init__(\n        self,\n        energy_lo,\n        energy_hi,\n        offset_lo,\n        offset_hi,\n        data,\n        meta=None,\n        interp_kwargs=None,\n    ):\n\n        if interp_kwargs is None:\n            interp_kwargs = self.default_interp_kwargs\n\n        e_edges = edges_from_lo_hi(energy_lo, energy_hi)\n        energy_axis = MapAxis.from_edges(e_edges, interp=\"log\", name=\"energy\")\n\n        # TODO: for some reason the H.E.S.S. DL3 files contain the same values for offset_hi and offset_lo\n        if np.allclose(offset_lo.to_value(\"deg\"), offset_hi.to_value(\"deg\")):\n            offset_axis = MapAxis.from_nodes(offset_lo, interp=\"lin\", name=\"offset\")\n        else:\n            offset_edges = edges_from_lo_hi(offset_lo, offset_hi)\n            offset_axis = MapAxis.from_edges(offset_edges, interp=\"lin\", name=\"offset\")\n\n        self.data = NDDataArray(\n            axes=[energy_axis, offset_axis], data=data, interp_kwargs=interp_kwargs\n        )\n        self.meta = meta or {}\n\n    def __str__(self):\n        ss = self.__class__.__name__\n        ss += f\"\\n{self.data}\"\n        return ss\n\n    @property\n    def low_threshold(self):\n        \"\"\"Low energy threshold\"\"\"\n        return self.meta[\"LO_THRES\"] * u.TeV\n\n    @property\n    def high_threshold(self):\n        \"\"\"High energy threshold\"\"\"\n        return self.meta[\"HI_THRES\"] * u.TeV\n\n    @classmethod\n    def from_table(cls, table):\n        \"\"\"Read from `~astropy.table.Table`.\"\"\"\n        return cls(\n            energy_lo=table[\"ENERG_LO\"].quantity[0],\n            energy_hi=table[\"ENERG_HI\"].quantity[0],\n            offset_lo=table[\"THETA_LO\"].quantity[0],\n            offset_hi=table[\"THETA_HI\"].quantity[0],\n            data=table[\"EFFAREA\"].quantity[0].transpose(),\n            meta=table.meta,\n        )\n\n    @classmethod\n    def from_hdulist(cls, hdulist, hdu=\"EFFECTIVE AREA\"):\n        \"\"\"Create from `~astropy.io.fits.HDUList`.\"\"\"\n        return cls.from_table(Table.read(hdulist[hdu]))\n\n    @classmethod\n    def read(cls, filename, hdu=\"EFFECTIVE AREA\"):\n        \"\"\"Read from file.\"\"\"\n        with fits.open(make_path(filename), memmap=False) as hdulist:\n            return cls.from_hdulist(hdulist, hdu=hdu)\n\n    def to_effective_area_table(self, offset, energy=None):\n        \"\"\"Evaluate at a given offset and return `~gammapy.irf.EffectiveAreaTable`.\n\n        Parameters\n        ----------\n        offset : `~astropy.coordinates.Angle`\n            Offset\n        energy : `~astropy.units.Quantity`\n            Energy axis bin edges\n        \"\"\"\n        if energy is None:\n            energy = self.data.axis(\"energy\").edges\n\n        area = self.data.evaluate(\n            offset=offset, energy=MapAxis.from_edges(energy, interp=\"log\").center\n        )\n\n        return EffectiveAreaTable(\n            energy_lo=energy[:-1], energy_hi=energy[1:], data=area\n        )\n\n    def plot_energy_dependence(self, ax=None, offset=None, energy=None, **kwargs):\n        \"\"\"Plot effective area versus energy for a given offset.\n\n        Parameters\n        ----------\n        ax : `~matplotlib.axes.Axes`, optional\n            Axis\n        offset : `~astropy.coordinates.Angle`\n            Offset\n        energy : `~astropy.units.Quantity`\n            Energy axis\n        kwargs : dict\n            Forwarded tp plt.plot()\n\n        Returns\n        -------\n        ax : `~matplotlib.axes.Axes`\n            Axis\n        \"\"\"\n        import matplotlib.pyplot as plt\n\n        ax = plt.gca() if ax is None else ax\n\n        if offset is None:\n            off_min, off_max = self.data.axis(\"offset\").center[[0, -1]]\n            offset = np.linspace(off_min.value, off_max.value, 4) * off_min.unit\n\n        if energy is None:\n            energy = self.data.axis(\"energy\").center\n\n        for off in offset:\n            area = self.data.evaluate(offset=off, energy=energy)\n            label = f\"offset = {off:.1f}\"\n            ax.plot(energy, area.value, label=label, **kwargs)\n\n        ax.set_xscale(\"log\")\n        ax.set_xlabel(f\"Energy [{self.data.axis('energy').unit}]\")\n        ax.set_ylabel(f\"Effective Area [{self.data.data.unit}]\")\n        ax.set_xlim(min(energy.value), max(energy.value))\n        ax.legend(loc=\"upper left\")\n\n        return ax\n\n    def plot_offset_dependence(self, ax=None, offset=None, energy=None, **kwargs):\n        \"\"\"Plot effective area versus offset for a given energy.\n\n        Parameters\n        ----------\n        ax : `~matplotlib.axes.Axes`, optional\n            Axis\n        offset : `~astropy.coordinates.Angle`\n            Offset axis\n        energy : `~astropy.units.Quantity`\n            Energy\n\n        Returns\n        -------\n        ax : `~matplotlib.axes.Axes`\n            Axis\n        \"\"\"\n        import matplotlib.pyplot as plt\n\n        ax = plt.gca() if ax is None else ax\n\n        if energy is None:\n            e_min, e_max = np.log10(self.data.axis(\"energy\").center.value[[0, -1]])\n            energy = np.logspace(e_min, e_max, 4) * self.data.axis(\"energy\").unit\n\n        if offset is None:\n            offset = self.data.axis(\"offset\").center\n\n        for ee in energy:\n            area = self.data.evaluate(offset=offset, energy=ee)\n            area /= np.nanmax(area)\n            if np.isnan(area).all():\n                continue\n            label = f\"energy = {ee:.1f}\"\n            ax.plot(offset, area, label=label, **kwargs)\n\n        ax.set_ylim(0, 1.1)\n        ax.set_xlabel(f\"Offset ({self.data.axis('offset').unit})\")\n        ax.set_ylabel(\"Relative Effective Area\")\n        ax.legend(loc=\"best\")\n\n        return ax\n\n    def plot(self, ax=None, add_cbar=True, **kwargs):\n        \"\"\"Plot effective area image.\"\"\"\n        import matplotlib.pyplot as plt\n\n        ax = plt.gca() if ax is None else ax\n\n        energy = self.data.axis(\"energy\").edges\n        offset = self.data.axis(\"offset\").edges\n        aeff = self.data.evaluate(offset=offset, energy=energy[:, np.newaxis])\n\n        vmin, vmax = np.nanmin(aeff.value), np.nanmax(aeff.value)\n\n        kwargs.setdefault(\"cmap\", \"GnBu\")\n        kwargs.setdefault(\"edgecolors\", \"face\")\n        kwargs.setdefault(\"vmin\", vmin)\n        kwargs.setdefault(\"vmax\", vmax)\n\n        caxes = ax.pcolormesh(energy.value, offset.value, aeff.value.T, **kwargs)\n\n        ax.set_xscale(\"log\")\n        ax.set_ylabel(f\"Offset ({offset.unit})\")\n        ax.set_xlabel(f\"Energy ({energy.unit})\")\n\n        xmin, xmax = energy.value.min(), energy.value.max()\n        ax.set_xlim(xmin, xmax)\n\n        if add_cbar:\n            label = f\"Effective Area ({aeff.unit})\"\n            ax.figure.colorbar(caxes, ax=ax, label=label)\n\n        return ax\n\n    def peek(self, figsize=(15, 5)):\n        \"\"\"Quick-look summary plots.\"\"\"\n        import matplotlib.pyplot as plt\n\n        fig, axes = plt.subplots(nrows=1, ncols=3, figsize=figsize)\n        self.plot(ax=axes[2])\n        self.plot_energy_dependence(ax=axes[0])\n        self.plot_offset_dependence(ax=axes[1])\n        plt.tight_layout()\n\n    def to_table(self):\n        \"\"\"Convert to `~astropy.table.Table`.\"\"\"\n        meta = self.meta.copy()\n\n        energy = self.data.axis(\"energy\").edges\n        theta = self.data.axis(\"offset\").edges\n\n        table = Table(meta=meta)\n        table[\"ENERG_LO\"] = energy[:-1][np.newaxis]\n        table[\"ENERG_HI\"] = energy[1:][np.newaxis]\n        table[\"THETA_LO\"] = theta[:-1][np.newaxis]\n        table[\"THETA_HI\"] = theta[1:][np.newaxis]\n        table[\"EFFAREA\"] = self.data.data.T[np.newaxis]\n        return table\n\n    def to_fits(self, name=\"EFFECTIVE AREA\"):\n        \"\"\"Convert to `~astropy.io.fits.BinTableHDU`.\"\"\"\n        return fits.BinTableHDU(self.to_table(), name=name)\n", "meta": {"hexsha": "0a2553b024d2dfee2747a299eacb9c543ed4e4ba", "size": 19566, "ext": "py", "lang": "Python", "max_stars_repo_path": "gammapy/irf/effective_area.py", "max_stars_repo_name": "QRemy/gammapy", "max_stars_repo_head_hexsha": "fe799e8a8e792d216fdb11fb7abcb64d58f273dd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gammapy/irf/effective_area.py", "max_issues_repo_name": "QRemy/gammapy", "max_issues_repo_head_hexsha": "fe799e8a8e792d216fdb11fb7abcb64d58f273dd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gammapy/irf/effective_area.py", "max_forks_repo_name": "QRemy/gammapy", "max_forks_repo_head_hexsha": "fe799e8a8e792d216fdb11fb7abcb64d58f273dd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5034246575, "max_line_length": 106, "alphanum_fraction": 0.5887764489, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 4919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.18160226018901554}}
{"text": "# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\n\"\"\"\nImplement octree.\n\"\"\"\n\nimport numpy as np\n\n\ndef int2node_data(value):\n    data = np.zeros(8, dtype=np.int)\n    value_vector = np.repeat(value, 8)\n    tmp = np.floor(value_vector / [1, 2, 4, 8, 16, 32, 64, 128])\n    data = np.mod(tmp, 2)\n    return data.astype(int)\n\n\nclass OctreeBranchNode:\n    def __init__(self, depth, parent, position, size, octant):\n        \"\"\"\n        Here we use number to simply eight branches\n        + here means greater then the center, vice versa\n        branch: 0 1 2 3 4 5 6 7\n        x:      - - - - + + + +\n        y:      - - + + - - + +\n        z:      - + - + - + - +\n\n        Parameters\n        ----------\n        position: ndarray\n            center of voxel/node\n        \"\"\"\n        self.attribute = \"branch\"\n        self.depth = depth\n        self.size = size\n        self.position = position\n        self.parent = parent\n        self.data = np.zeros(8, dtype=np.int)\n        self.branches = [None, None, None, None, None, None, None, None]\n        self.octant = octant\n\n    def __str__(self):\n        return u\"position: {0}, size: {1}, depth: {2} parent: {3}, data: {4}\".format(\n            self.position, self.size, self.depth, self.parent, self.data)\n\n\nclass OctreeLeafNode:\n\n    def __init__(self, depth, parent, position_gt, size):\n        \"\"\"\n        leafnode do not need branch and data\n        Different with position in the branch, position_gt here is not the center of voxel bur ground truth xyz\n        \"\"\"\n        self.attribute = \"leaf\"\n        self.depth = depth\n        self.size = size\n        self.position_center = None\n        self.position_gt = position_gt\n        self.parent = parent\n\n\nclass Octree:\n\n    def __init__(self, max_range, precision, origin=(0, 0, 0)):\n        \"\"\"\n        Parameters\n        ----------\n        max_range:\n            the size of whole octree\n        origin:\n            the position of octree root node\n        leaf_num:\n            number of lead nodes, aka the number of points after converting into octree\n        \"\"\"\n        self.attribute = \"root\"\n        self.size = max_range\n        self.precision = precision\n        self.depth = 0\n        self.max_depth = int(np.log2(max_range / precision)) + 1\n        self.position = origin\n        self.data = np.zeros(8, dtype=np.int)\n        self.branches = [None, None, None, None, None, None, None, None]\n        self.leaf_num = 0\n\n\n    @staticmethod\n    def find_branch(root, position):\n        \"\"\"\n        helper function\n        returns an index corresponding to a branch\n        pointing in the direction we want to go\n        \"\"\"\n        index = 0\n        if position[0] >= root.position[0]:\n            index |= 4\n        if position[1] >= root.position[1]:\n            index |= 2\n        if position[2] >= root.position[2]:\n            index |= 1\n        return index\n\n    def insert_node(self, root, size, parent, position, depth):\n        if depth == self.max_depth:\n            if root is None:\n                self.leaf_num += 1\n            return OctreeLeafNode(depth, parent, position, size)\n\n        if depth < self.max_depth:\n            branch = self.find_branch(root, position)\n            branch_size = root.size / 2\n            root.data[branch] = 1\n\n            if (root.branches[branch] is None) and (depth != self.max_depth - 1):\n                pos = root.position\n                offset = size / 2\n                new_center = (0, 0, 0)\n                if branch == 0:\n                    new_center = (pos[0] - offset, pos[1] - offset, pos[2] - offset)\n                elif branch == 1:\n                    new_center = (pos[0] - offset, pos[1] - offset, pos[2] + offset)\n                elif branch == 2:\n                    new_center = (pos[0] - offset, pos[1] + offset, pos[2] - offset)\n                elif branch == 3:\n                    new_center = (pos[0] - offset, pos[1] + offset, pos[2] + offset)\n                elif branch == 4:\n                    new_center = (pos[0] + offset, pos[1] - offset, pos[2] - offset)\n                elif branch == 5:\n                    new_center = (pos[0] + offset, pos[1] - offset, pos[2] + offset)\n                elif branch == 6:\n                    new_center = (pos[0] + offset, pos[1] + offset, pos[2] - offset)\n                elif branch == 7:\n                    new_center = (pos[0] + offset, pos[1] + offset, pos[2] + offset)\n                root.branches[branch] = OctreeBranchNode(depth + 1, root, new_center, branch_size, branch)\n\n            root.branches[branch] = self.insert_node(root.branches[branch], branch_size, root, position, depth + 1)\n        return root\n\n    def serialize_depth_first(self):\n        def extract_data(node):\n            if node and node.attribute != \"leaf\":\n                values.append(node_data2int(node.data))\n                # vals.append(node.data)\n                for branch_id in range(8):\n                    extract_data(node.branches[branch_id])\n\n        values = []\n        extract_data(self)\n        return values\n\n\ndef deserialize_depth_first(values, max_depth, octree):\n    def reconstruct_tree(root):\n        value = next(values)\n        node_data = int2node_data(value)\n        root.data = node_data\n        for branch in range(8):\n            if node_data[branch] == 0:\n                root.branches[branch] = None\n            else:\n                depth = root.depth\n                pos = root.position\n                offset = root.size / 2\n                new_center = (0, 0, 0)\n\n                if branch == 0:\n                    new_center = (pos[0] - offset, pos[1] - offset, pos[2] - offset)\n                elif branch == 1:\n                    new_center = (pos[0] - offset, pos[1] - offset, pos[2] + offset)\n                elif branch == 2:\n                    new_center = (pos[0] - offset, pos[1] + offset, pos[2] - offset)\n                elif branch == 3:\n                    new_center = (pos[0] - offset, pos[1] + offset, pos[2] + offset)\n                elif branch == 4:\n                    new_center = (pos[0] + offset, pos[1] - offset, pos[2] - offset)\n                elif branch == 5:\n                    new_center = (pos[0] + offset, pos[1] - offset, pos[2] + offset)\n                elif branch == 6:\n                    new_center = (pos[0] + offset, pos[1] + offset, pos[2] - offset)\n                elif branch == 7:\n                    new_center = (pos[0] + offset, pos[1] + offset, pos[2] + offset)\n\n                if depth < max_depth - 1:\n                    node = OctreeBranchNode(depth + 1, root, new_center, offset, branch)\n                    root.branches[branch] = node\n                    reconstruct_tree(root.branches[branch])\n                else:\n                    node = OctreeLeafNode(depth + 1, root, 0, offset)\n                    node.position_center = new_center\n                    recon_points.append(new_center)\n                    root.branches[branch] = node\n        return root\n    recon_points = []\n    return reconstruct_tree(octree), recon_points\n", "meta": {"hexsha": "7ee3df5215c45d75ffe4087c28e63fa3a56c659b", "size": 7661, "ext": "py", "lang": "Python", "max_stars_repo_path": "official/cv/octsqueeze/src/tools/octree_base.py", "max_stars_repo_name": "mindspore-ai/models", "max_stars_repo_head_hexsha": "9127b128e2961fd698977e918861dadfad00a44c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 77, "max_stars_repo_stars_event_min_datetime": "2021-10-15T08:32:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:09:11.000Z", "max_issues_repo_path": "official/cv/octsqueeze/src/tools/octree_base.py", "max_issues_repo_name": "mindspore-ai/models", "max_issues_repo_head_hexsha": "9127b128e2961fd698977e918861dadfad00a44c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-10-30T14:44:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T06:57:57.000Z", "max_forks_repo_path": "official/cv/octsqueeze/src/tools/octree_base.py", "max_forks_repo_name": "mindspore-ai/models", "max_forks_repo_head_hexsha": "9127b128e2961fd698977e918861dadfad00a44c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2021-10-15T08:32:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T18:45:20.000Z", "avg_line_length": 37.0096618357, "max_line_length": 115, "alphanum_fraction": 0.528129487, "include": true, "reason": "import numpy", "num_tokens": 1875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.18160225668302213}}
{"text": "# Copyright 2020 Makani Technologies LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Scoring functions relating to aerodynamics.\"\"\"\n\nfrom makani.analysis.aero import aero_ssam\nfrom makani.analysis.aero import apparent_wind_util\nfrom makani.analysis.log_analysis import loop_averager\nfrom makani.control import system_types\nfrom makani.lib.python import c_helpers\nfrom makani.lib.python.batch_sim import scoring_functions\nfrom makani.lib.python.h5_utils import numpy_utils\nfrom makani.system import labels as system_labels\n\nimport numpy as np\nfrom scipy import interpolate\nimport scoring_functions_util as scoring_util\n\n_FLAP_LABEL_HELPER = c_helpers.EnumHelper('FlapLabel', system_labels,\n                                          prefix='kFlap')\n_WING_MODEL_HELPER = c_helpers.EnumHelper('WingModel', system_types)\n_WING_SERIAL_HELPER = c_helpers.EnumHelper('WingSerial', system_types)\n\n\nclass AirspeedMaxScoringFunction(\n    scoring_functions.SingleSidedLimitScoringFunction):\n  \"\"\"Tests if the airspeed falls outside of acceptable limits.\"\"\"\n\n  def __init__(self, good_limit, bad_limit, severity):\n    super(AirspeedMaxScoringFunction, self).__init__(\n        'Max Airspeed', 'm/s', good_limit, bad_limit, severity)\n\n  def GetSystemLabels(self):\n    return ['controls']\n\n  def GetValue(self, output):\n    return output['airspeed_max']\n\n  def GetOutput(self, timeseries):\n    return {'airspeed_max': np.max(timeseries['airspeed'])}\n\n  def GetTimeSeries(self, params, sim, control):\n    airspeed = self._SelectTelemetry(sim, control, 'airspeed')\n    return {'airspeed': airspeed}\n\n\nclass AirspeedMinScoringFunction(\n    scoring_functions.SingleSidedLimitScoringFunction):\n  \"\"\"Tests if the airspeed falls outside of acceptable limits.\"\"\"\n\n  def __init__(self, good_limit, bad_limit, severity):\n    super(AirspeedMinScoringFunction, self).__init__(\n        'Min Airspeed', 'm/s', good_limit, bad_limit, severity)\n\n  def GetSystemLabels(self):\n    return ['controls']\n\n  def GetValue(self, output):\n    return output['airspeed_min']\n\n  def GetOutput(self, timeseries):\n    return {'airspeed_min': np.min(timeseries['airspeed'])}\n\n  def GetTimeSeries(self, params, sim, control):\n    airspeed = self._SelectTelemetry(sim, control, 'airspeed')\n    return {'airspeed': airspeed}\n\n\nclass MainWingAlphaScoringFunction(\n    scoring_functions.DoubleSidedLimitScoringFunction):\n  \"\"\"Tests if angle of attack on the main wing exceeds a limit.\"\"\"\n\n  def __init__(self, bad_lower_limit, good_lower_limit, good_upper_limit,\n               bad_upper_limit, severity, airspeed_threshold=1.0,\n               steady_flight=False):\n    super(MainWingAlphaScoringFunction, self).__init__(\n        'Main Wing SSAM AoA%s' % (' (w/o initial transients)' if steady_flight\n                                  else ''),\n        'deg', bad_lower_limit, good_lower_limit,\n        good_upper_limit, bad_upper_limit, severity)\n    assert airspeed_threshold > 0.0\n    self._airspeed_threshold = airspeed_threshold\n\n  def GetSystemLabels(self):\n    return ['aero']\n\n  def GetValue(self, output):\n    return np.array([output['wing_alpha_min'], output['wing_alpha_max']])\n\n  def GetFailureCount(self, timeseries):\n    if timeseries is None:\n      return None\n    # Confirm that the arrays have the same size.\n    assert len(timeseries['alphas_min']) == len(timeseries['alphas_max'])\n    # Confirm that at any index, alphas_max is going to be greater than\n    # alphas_min.\n    assert np.all(timeseries['alphas_max'] >= timeseries['alphas_min'])\n    return np.logical_or(\n        timeseries['alphas_min'] < self._bad_lower_limit,\n        timeseries['alphas_max'] > self._bad_upper_limit).sum()\n\n  def GetIndexOfFirstFailure(self, timeseries):\n    if timeseries is None:\n      return None\n    if self.GetFailureCount(timeseries) == 0:\n      return -1\n    else:\n      return np.argmax(\n          np.logical_or(timeseries['alphas_min'] < self._bad_lower_limit,\n                        timeseries['alphas_max'] > self._bad_upper_limit))\n\n  def GetOutput(self, timeseries):\n    return {\n        'wing_alpha_min': np.min(timeseries['alphas_min']),\n        'wing_alpha_max': np.max(timeseries['alphas_max'])\n    }\n\n  def GetTimeSeries(self, params, sim, control):\n    airspeeds, angular_rates, app_wind_b = self._SelectTelemetry(\n        sim, control, ['airspeed', 'body_rates', 'apparent_wind_vector'])\n\n    # Converts the indices into an (n,) sized array for 2D array masking.\n    data_indices = np.reshape(\n        np.argwhere(airspeeds > self._airspeed_threshold), -1)\n\n    if data_indices.size == 0:\n      wing_alphas_max = np.array([float('nan')])\n      wing_alphas_min = np.array([float('nan')])\n\n    else:\n      # Mask the body rates for telemetry that crosses the threshold.\n      omega_b = numpy_utils.Vec3ToArray(angular_rates)[data_indices]\n\n      # Mask the cartesian wind for telemetry that crosses the threshold.\n      wind_b = numpy_utils.Vec3ToArray(app_wind_b)[data_indices]\n\n      # Compute the kinematic-based local values of alpha.\n      # TODO: Wing_model should be mapped to enumerate wing models.\n      wing_model = _WING_MODEL_HELPER.ShortName(\n          int(params['system_params']['wing_model'][0]))\n      wing_serial = _WING_SERIAL_HELPER.Name(int(\n          params['system_params']['wing_serial'][0]))\n      ssam = aero_ssam.SSAMModel(wing_model, wing_serial)\n      wing_alphas_deg = ssam.GetMainWingAlphas(omega_b, wind_b)\n\n      # Provide telemetry of maximum alphas anywhere along the main wing.\n      # As per GetMainWingAlphas the expected size of wing_alphas_deg is (n, m)\n      # where m is the number of wing panels and n is the number of elements in\n      # the time series.\n      wing_alphas_max = np.amax(wing_alphas_deg, axis=1)\n      wing_alphas_min = np.amin(wing_alphas_deg, axis=1)\n\n    return {'alphas_max': wing_alphas_max, 'alphas_min': wing_alphas_min}\n\n\nclass AlphaDegScoringFunction(\n    scoring_functions.DoubleSidedLimitScoringFunction):\n  \"\"\"Tests if the angle-of-attack exceeds a limit when airspeed is high.\"\"\"\n\n  def __init__(self, bad_lower_limit, good_lower_limit, good_upper_limit,\n               bad_upper_limit, severity, airspeed_threshold=1.0,\n               steady_flight=False):\n    super(AlphaDegScoringFunction, self).__init__(\n        'Angle-of-attack%s' % (' (w/o initial transients)' if steady_flight\n                               else ''),\n        'deg', bad_lower_limit, good_lower_limit,\n        good_upper_limit, bad_upper_limit, severity)\n    assert airspeed_threshold > 0.0\n    self._airspeed_threshold = airspeed_threshold\n\n  def GetSystemLabels(self):\n    return ['aero']\n\n  def GetValue(self, output):\n    return np.array([output['alpha_min'], output['alpha_max']])\n\n  def GetOutput(self, timeseries):\n    alpha = timeseries['alpha']\n    return {\n        'alpha_max': np.max(alpha),\n        'alpha_min': np.min(alpha)\n    }\n\n  def GetTimeSeries(self, params, sim, control):\n    airspeeds, alpha, time = self._SelectTelemetry(\n        sim, control, ['airspeed', 'alpha', 'time'])\n    data_indices = np.argwhere(airspeeds > self._airspeed_threshold)\n    if data_indices.size == 0:\n      alpha = np.array([float('nan')])\n    else:\n      chord = params['system_params']['wing']['c']\n      # Choose 5 main wing flow-over time constants, 2 sigma for peak rejection\n      alpha = scoring_util.FilterByWindowAveraging(\n          time[data_indices], alpha[data_indices], airspeeds[data_indices],\n          chord, num_tau=5, num_sigma=2)\n\n    return {'alpha': np.rad2deg(alpha)}\n\n\nclass MinAlphaDegScoringFunction(\n    scoring_functions.DoubleSidedLimitScoringFunction):\n  \"\"\"Tests if the angle-of-attack exceeds a limit when airspeed is high.\"\"\"\n\n  def __init__(self, bad_lower_limit, good_lower_limit, good_upper_limit,\n               bad_upper_limit, severity, airspeed_threshold=1.0):\n    super(MinAlphaDegScoringFunction, self).__init__(\n        'Min. Angle-of-attack', 'deg', bad_lower_limit, good_lower_limit,\n        good_upper_limit, bad_upper_limit, severity)\n    assert airspeed_threshold > 0.0\n    self._airspeed_threshold = airspeed_threshold\n\n  def GetSystemLabels(self):\n    return ['controls']\n\n  def GetValue(self, output):\n    return output['min_alpha']\n\n  def GetOutput(self, timeseries):\n    return {'min_alpha': np.min(timeseries['alpha'])}\n\n  def GetTimeSeries(self, params, sim, control):\n    # TODO: Review if this scoring function is working as\n    # intended. Update/remove as needed.\n    airspeeds, alpha, time = self._SelectTelemetry(\n        sim, control, ['airspeed', 'alpha', 'time'])\n    data_indices = np.argwhere(airspeeds > self._airspeed_threshold)\n    if data_indices.size == 0:\n      alpha = np.array([float('nan')])\n    else:\n      chord = params['system_params']['wing']['c']\n      # Choose 5 main wing flow-over time constants, 2 sigma for peak rejection\n      alpha = scoring_util.FilterByWindowAveraging(\n          time[data_indices], alpha[data_indices], airspeeds[data_indices],\n          chord, num_tau=5, num_sigma=2)\n\n    return {'alpha': np.rad2deg(alpha)}\n\n\nclass BetaDegScoringFunction(scoring_functions.DoubleSidedLimitScoringFunction):\n  \"\"\"Tests if the side-slip exceeds a limit when airspeed is high.\"\"\"\n\n  def __init__(self, bad_lower_limit, good_lower_limit,\n               good_upper_limit, bad_upper_limit, severity,\n               airspeed_threshold=1.0, steady_flight=False):\n    super(BetaDegScoringFunction, self).__init__(\n        'Side-slip%s' % (' (w/o initial transients)' if steady_flight else ''),\n        'deg', bad_lower_limit, good_lower_limit,\n        good_upper_limit, bad_upper_limit, severity)\n    assert airspeed_threshold > 0.0\n    self._airspeed_threshold = airspeed_threshold\n\n  def GetSystemLabels(self):\n    return ['aero']\n\n  def GetValue(self, output):\n    return np.array([output['beta_min'], output['beta_max']])\n\n  def GetOutput(self, timeseries):\n    beta = timeseries['beta']\n    return {\n        'beta_max': np.max(beta),\n        'beta_min': np.min(beta)\n    }\n\n  def GetTimeSeries(self, params, sim, control):\n    airspeeds, beta, time = self._SelectTelemetry(\n        sim, control, ['airspeed', 'beta', 'time'])\n    data_indices = np.argwhere(airspeeds > self._airspeed_threshold)\n    if data_indices.size == 0:\n      beta = np.array([float('nan')])\n    else:\n      chord = params['system_params']['wing']['c']\n      # Choose 5 main wing flow-over time constants, 2 sigma for peak rejection\n      beta = scoring_util.FilterByWindowAveraging(\n          time[data_indices], beta[data_indices], airspeeds[data_indices],\n          chord, num_tau=5, num_sigma=2)\n\n    return {'beta': np.rad2deg(beta)}\n\n\nclass AlphaDegErrorScoringFunction(\n    scoring_functions.SingleSidedLimitScoringFunction):\n  \"\"\"Tests if the angle-of-attack error in crosswind flight is small enough.\"\"\"\n\n  def __init__(self, good_limit, bad_limit, severity,\n               airspeed_threshold=1.0, steady_flight=False):\n    super(AlphaDegErrorScoringFunction, self).__init__(\n        'Angle-of-attack Error%s' % (' (w/o initial transients)'\n                                     if steady_flight else ''),\n        'deg', good_limit, bad_limit, severity)\n    assert airspeed_threshold > 0.0\n    self._airspeed_threshold = airspeed_threshold\n    self.SetSourcePriority(['control'])\n\n  def GetSystemLabels(self):\n    return ['controls']\n\n  def GetValue(self, output):\n    return output['alpha_error_max']\n\n  def GetOutput(self, timeseries):\n    return {'alpha_error_max': np.max(timeseries['alpha_error'])}\n\n  def GetTimeSeries(self, params, sim, control):\n    airspeeds, alphas, alpha_cmds, time = self._SelectTelemetry(\n        sim, control, ['airspeed', 'alpha', 'alpha_cmd', 'time'])\n\n    data_indices = np.argwhere(airspeeds > self._airspeed_threshold)\n    if data_indices.size == 0:\n      alpha_error = np.array([float('nan')])\n    else:\n      chord = params['system_params']['wing']['c']\n      # Choose 5 main wing flow-over time constants, 2 sigma for peak rejection\n      alphas = scoring_util.FilterByWindowAveraging(\n          time[data_indices], alphas[data_indices], airspeeds[data_indices],\n          chord, num_tau=5, num_sigma=2)\n      alpha_error = np.fabs(alphas - alpha_cmds[data_indices])\n\n    return {'alpha_error': np.rad2deg(alpha_error)}\n\n\nclass BetaDegErrorScoringFunction(\n    scoring_functions.SingleSidedLimitScoringFunction):\n  \"\"\"Tests if the sideslip angle error in crosswind flight is small enough.\"\"\"\n\n  def __init__(self, good_limit, bad_limit, severity,\n               airspeed_threshold=1.0, steady_flight=False):\n    super(BetaDegErrorScoringFunction, self).__init__(\n        'Sideslip Error%s' % (' (w/o initial transients)'\n                              if steady_flight else ''),\n        'deg', good_limit, bad_limit, severity)\n    assert airspeed_threshold > 0.0\n    self._airspeed_threshold = airspeed_threshold\n    self.SetSourcePriority(['control'])\n\n  def GetSystemLabels(self):\n    return ['controls']\n\n  def GetValue(self, output):\n    return output['beta_error_max']\n\n  def GetOutput(self, timeseries):\n    return {'beta_error_max': np.max(timeseries['beta_error'])}\n\n  def GetTimeSeries(self, params, sim, control):\n    airspeeds, betas, beta_cmds, time = self._SelectTelemetry(\n        sim, control, ['airspeed', 'beta', 'beta_cmd', 'time'])\n\n    data_indices = np.argwhere(airspeeds > self._airspeed_threshold)\n    if data_indices.size == 0:\n      beta_error = np.array([float('nan')])\n    else:\n      chord = params['system_params']['wing']['c']\n      # Choose 5 main wing flow-over time constants, 2 sigma for peak rejection\n      betas = scoring_util.FilterByWindowAveraging(\n          time[data_indices], betas[data_indices], airspeeds[data_indices],\n          chord, num_tau=5, num_sigma=2)\n      beta_error = np.fabs(betas - beta_cmds[data_indices])\n\n    return {'beta_error': np.rad2deg(beta_error)}\n\n\n# TODO: Alpha, Beta and Airspeed RMS error scoring functions\n# should be evaluated on per loop basis. The GetTimeseries method should be like\n# the one in SurfaceSaturationScoringFunction.\nclass AlphaRmsScoringFunction(\n    scoring_functions.SingleSidedLimitScoringFunction):\n  \"\"\"RMS angle-of-attack error.\"\"\"\n\n  def __init__(self, good_limit, bad_limit, severity):\n    super(AlphaRmsScoringFunction, self).__init__(\n        'AoA RMS', 'deg', good_limit, bad_limit, severity)\n    self.SetSourcePriority(['control'])\n\n  def GetSystemLabels(self):\n    return ['experimental', 'controls']\n\n  def GetValue(self, output):\n    return output['alpha_rms']\n\n  def GetOutput(self, timeseries):\n    return {'alpha_rms': np.rad2deg(timeseries['alpha_rms'])}\n\n  def GetTimeSeries(self, params, sim, control):\n    alphas, alpha_cmds = self._SelectTelemetry(\n        sim, control, ['alpha', 'alpha_cmd'])\n    return {\n        'alpha_rms': np.mean((alphas - alpha_cmds)**2.0)**0.5\n        }\n\n\nclass BetaRmsScoringFunction(\n    scoring_functions.SingleSidedLimitScoringFunction):\n  \"\"\"RMS side-slip error.\"\"\"\n\n  def __init__(self, good_limit, bad_limit, severity):\n    super(BetaRmsScoringFunction, self).__init__(\n        'Side-slip RMS', 'deg', good_limit, bad_limit, severity)\n    self.SetSourcePriority(['control'])\n\n  def GetSystemLabels(self):\n    return ['experimental', 'controls']\n\n  def GetValue(self, output):\n    return output['beta_rms']\n\n  def GetOutput(self, timeseries):\n    return {'beta_rms': np.rad2deg(timeseries['beta_rms'])}\n\n  def GetTimeSeries(self, params, sim, control):\n    betas, beta_cmds = self._SelectTelemetry(\n        sim, control, ['beta', 'beta_cmd'])\n    return {\n        'beta_rms': np.mean((betas - beta_cmds)**2.0)**0.5\n        }\n\n\nclass AirspeedRmsScoringFunction(\n    scoring_functions.SingleSidedLimitScoringFunction):\n  \"\"\"RMS airspeed error.\"\"\"\n\n  def __init__(self, good_limit, bad_limit, severity):\n    super(AirspeedRmsScoringFunction, self).__init__(\n        'Airspeed RMS', 'm/s', good_limit, bad_limit, severity)\n    self.SetSourcePriority(['control'])\n\n  def GetSystemLabels(self):\n    return ['experimental', 'controls']\n\n  def GetValue(self, output):\n    return output['airspeed_rms']\n\n  def GetOutput(self, timeseries):\n    return {'airspeed_rms': timeseries['airspeed_rms']}\n\n  def GetTimeSeries(self, params, sim, control):\n    airspeeds, airspeed_cmds = self._SelectTelemetry(\n        sim, control, ['airspeed', 'airspeed_cmd'])\n    return {\n        'airspeed_rms': np.mean((airspeeds - airspeed_cmds)**2.0)**0.5\n        }\n\n\nclass SurfaceSaturationScoringFunction(\n    scoring_functions.SingleSidedLimitScoringFunction):\n  \"\"\"Tests for the percent time the control surface is saturated.\n\n     If the saturation scoring function is activated during a crosswind flight\n     mode, then the characteristic percentage time corresponds to the maximum\n     percentage time a surface was saturated during any particular single loop.\n\n     If the saturation scoring function is activated during a non-crosswind\n     flight mode, then the characteristic percentage time corresponds to the\n     maximum saturation percentage achieved on all the telemetry data for\n     that flight mode.\n  \"\"\"\n\n  def __init__(self, flap_labels, good_limit, bad_limit, severity):\n    self._flap_indices = [_FLAP_LABEL_HELPER.Value(l) for l in flap_labels]\n    super(SurfaceSaturationScoringFunction, self).__init__(\n        '%s %% Saturated' % '/'.join(flap_labels), '% time',\n        good_limit, bad_limit, severity)\n\n  def GetSystemLabels(self):\n    return ['aero', 'controls']\n\n  def GetValue(self, output):\n    return output['percent_time_sat']\n\n  def GetOutput(self, timeseries):\n    largest_saturation_loop_mask = timeseries['largest_saturation_loop_mask']\n    if largest_saturation_loop_mask is None:\n      return {'percent_time_sat': float('nan')}\n    saturation_counter = np.where(largest_saturation_loop_mask)[0]\n    return {\n        'percent_time_sat': float(np.size(saturation_counter)) /\n                            np.size(largest_saturation_loop_mask) * 100.0\n    }\n\n  def GetTimeSeries(self, params, sim, control):\n    # \"_i\" is used to denote the as-imported variable.\n    (omega_i, airspeed_i, alpha_i, beta_i, flaps, loop_angles) = (\n        self._SelectTelemetry(sim, control, [\n            'body_rates', 'airspeed', 'alpha', 'beta', 'flaps', 'loop_angle']))\n    if not scoring_util.IsSelectionValid(flaps):\n      return {'saturation_mask': None, 'largest_saturation_loop_mask': None}\n    deflections = np.rad2deg(flaps[:, self._flap_indices])\n\n    # Observations of actual control surface deflections show that when\n    # saturated, they are not exactly at the control limit. Adding or\n    # subtracting 0.25 degrees from the limit allows for most saturations\n    # to be flagged by the criteria. A4 and A5 are often very close to the\n    # upper limit of zero with very small magnitudes of deflection. An offset\n    # of only 0.005 degrees is applied to the upper flap limit for flaps A4\n    # and A5 to prevent normal operation from being flagged erroneously.\n    # The deflection limits of the rudder are altered to account for the\n    # wing-fuselage junction loads limit, per b/112267831.\n    lower_deflection_limit = (\n        np.rad2deg(np.array(params['control_params']['crosswind']['output']\n                            ['lower_flap_limits'][0, self._flap_indices]))\n        + 0.25)\n    if (self._flap_indices == [system_labels.kFlapA4] or\n        self._flap_indices == [system_labels.kFlapA5]):\n      upper_deflection_limit = (np.rad2deg(np.array(\n          params['control_params']['crosswind']['output']\n          ['upper_flap_limits'][0, self._flap_indices])) - 0.005)\n\n    elif self._flap_indices == [system_labels.kFlapRud]:\n      # Check if body rates data exist. These may not exist if the relevant\n      # flight modes do not exist.\n      if not scoring_util.IsSelectionValid(omega_i):\n        return {'saturation_mask': float('nan')}\n      # Position [m] of the vtail aerodynamic center. Only the x-coordinate is\n      # relevant here.\n      # TODO: Add position of aerodynamic center to params in the h5 log.\n      r_vtail = np.array([-7.0, 0.0, 0.0])\n\n      vapp = np.array(airspeed_i)\n      alpha = np.array(alpha_i)\n      beta = np.array(beta_i)\n\n      omega = np.array([omega_i['x'],\n                        omega_i['y'],\n                        omega_i['z']])\n      # Account for motion of empennage relative to kite origin as it affects\n      # apparent wind, alpha, beta.\n      v_kite = apparent_wind_util.ApparentWindSphToCart(vapp, alpha, beta).T\n      v_omega = np.cross(omega, r_vtail, axis=0)\n      vapp, alpha, beta = (\n          apparent_wind_util.ApparentWindCartToSph((v_kite + v_omega).T))\n      rudder_limits = self._GetRudderLimits(beta, vapp)\n      lower_deflection_limit = rudder_limits['lower_limit']\n      upper_deflection_limit = rudder_limits['upper_limit']\n\n      # Check that there is not a dimension problem coming out of the rudder\n      # deflection limit table. Deflections is expected shape (N,1). The rudder\n      # table uses the apparent_wind_util that may create arrays of shape (N,).\n      if np.shape(lower_deflection_limit) != np.shape(deflections):\n        lower_deflection_limit = np.reshape(lower_deflection_limit,\n                                            np.shape(deflections))\n      if np.shape(upper_deflection_limit) != np.shape(deflections):\n        upper_deflection_limit = np.reshape(upper_deflection_limit,\n                                            np.shape(deflections))\n\n    else:\n      upper_deflection_limit = (np.rad2deg(np.array(\n          params['control_params']['crosswind']['output']\n          ['upper_flap_limits'][0, self._flap_indices])) - 0.25)\n\n    # Fraction of a limit at which a surface is considered nearly saturated.\n    saturation_fraction = 0.9\n    new_upper_limit = saturation_fraction * upper_deflection_limit\n    new_lower_limit = saturation_fraction * lower_deflection_limit\n\n    is_saturated_upper = np.greater_equal(deflections, new_upper_limit)\n    is_saturated_lower = np.less_equal(deflections, new_lower_limit)\n    saturation_mask = np.logical_or(is_saturated_upper, is_saturated_lower)\n    largest_saturation_loop_mask = saturation_mask\n\n    # Identify the number of loops in the data and cycle over them to find which\n    # loop has the highest percentage of saturation. If there are no loops then\n    # simply take all the data as the scoring function is likely operating in a\n    # non-crosswind mode, e.g. hover.\n    endloop_indices = loop_averager.GetEndLoopIndices(loop_angles)\n    if np.size(endloop_indices):\n      # Go through each independent loop to find the mask array that contains\n      # the largest amount of masked values and return that array for scoring.\n      for i, endloop_indx in enumerate(endloop_indices):\n        if i == 0:\n          start_loop_indx = 0\n          largest_pct_saturated = 0.0\n          largest_saturation_loop_mask = saturation_mask[start_loop_indx:\n                                                         endloop_indx+1]\n        else:\n          start_loop_indx = endloop_indices[i-1]\n\n        # Figure out how long the surface has been saturated during this loop.\n        this_loop_mask = saturation_mask[start_loop_indx:endloop_indx + 1]\n\n        saturation_counter = np.where(this_loop_mask)[0]\n        percent_saturated = (float(np.size(saturation_counter)) /\n                             np.size(this_loop_mask) * 100.0)\n\n        if percent_saturated > largest_pct_saturated:\n          largest_saturation_loop_mask = this_loop_mask\n          largest_pct_saturated = percent_saturated\n\n    return {'saturation_mask': saturation_mask,\n            'largest_saturation_loop_mask': largest_saturation_loop_mask}\n\n  def GetFailureCount(self, timeseries):\n    \"\"\"Returns the counts of True in the `saturation_mask` array.\"\"\"\n    if timeseries is None:\n      return None\n    return np.sum(timeseries['saturation_mask'])\n\n  def GetIndexOfFirstFailure(self, timeseries):\n    \"\"\"Returns the index of the first True in the `saturation_mask` array.\"\"\"\n    if timeseries is None:\n      return None\n    if self.GetFailureCount(timeseries) == 0:\n      return -1\n    else:\n      return np.where(timeseries['saturation_mask'])[0][0]\n\n  def _GetRudderLimits(self, beta, airspeed):\n    # Tables below are copied from https://goo.gl/BmyhAe. See spreadsheet for\n    # description of how the tables are derived.\n    betas = np.array([-20.0, -10.0, 0.0, 10.0, 20.0])\n    airspeeds = np.array([50.0, 55.0, 60.0, 65.0, 70.0, 75.0,\n                          80.0, 85.0, 90.0, 95.0, 100.0])\n    rudder_limit_lower = np.array([[-22.00, -22.00, -22.00, -22.00, -22.00],\n                                   [-22.00, -22.00, -22.00, -22.00, -22.00],\n                                   [-22.00, -22.00, -22.00, -22.00, -16.42],\n                                   [-22.00, -22.00, -22.00, -22.00, -10.57],\n                                   [-22.00, -22.00, -22.00, -19.54, -5.92],\n                                   [-22.00, -22.00, -22.00, -15.72, -2.16],\n                                   [-22.00, -22.00, -22.00, -12.59, 0.91],\n                                   [-22.00, -22.00, -22.00, -10.00, 3.45],\n                                   [-22.00, -22.00, -21.31, -7.83, 5.58],\n                                   [-22.00, -22.00, -19.49, -5.99, 7.39],\n                                   [-22.00, -22.00, -17.94, -4.43, 8.93]])\n    rudder_limit_upper = np.array([[22.00, 22.00, 22.00, 22.00, 22.00],\n                                   [17.67, 22.00, 22.00, 22.00, 22.00],\n                                   [9.87, 22.00, 22.00, 22.00, 22.00],\n                                   [3.80, 17.64, 22.00, 22.00, 22.00],\n                                   [-1.02, 12.83, 22.00, 22.00, 22.00],\n                                   [-4.91, 8.94, 21.97, 22.00, 22.00],\n                                   [-8.09, 5.76, 18.88, 22.00, 22.00],\n                                   [-10.73, 3.12, 16.32, 22.00, 22.00],\n                                   [-12.94, 0.91, 14.17, 22.00, 22.00],\n                                   [-14.81, -0.96, 12.35, 22.00, 22.00],\n                                   [-16.40, -2.55, 10.80, 22.00, 22.00]])\n\n    lower_limit_lookup = interpolate.interp2d(\n        betas, airspeeds, rudder_limit_lower, kind='linear')\n    upper_limit_lookup = interpolate.interp2d(\n        betas, airspeeds, rudder_limit_upper, kind='linear')\n\n    lower_limit = np.zeros(len(beta))\n    upper_limit = np.zeros(len(beta))\n    for ii in range(len(beta)):\n      lower_limit[ii] = lower_limit_lookup(\n          np.rad2deg(beta[ii]), airspeed[ii]) + 0.25\n      upper_limit[ii] = upper_limit_lookup(\n          np.rad2deg(beta[ii]), airspeed[ii]) - 0.25\n\n    return {\n        'lower_limit': lower_limit,\n        'upper_limit': upper_limit\n    }\n", "meta": {"hexsha": "e31bc68a4bf7fc9ed539eb000a94abe6617340f7", "size": 27237, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/python/batch_sim/scoring_functions/aero.py", "max_stars_repo_name": "leozz37/makani", "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1178, "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_issues_repo_path": "lib/python/batch_sim/scoring_functions/aero.py", "max_issues_repo_name": "leozz37/makani", "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_forks_repo_path": "lib/python/batch_sim/scoring_functions/aero.py", "max_forks_repo_name": "leozz37/makani", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 107, "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "avg_line_length": 41.0814479638, "max_line_length": 80, "alphanum_fraction": 0.6685758343, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.1816022531770288}}
{"text": "\"\"\"\n  Performs several operations and manipulations of geometries\n\"\"\"\n\nimport numpy\nfrom phydat import phycon\nimport automol.create.geom\nfrom automol import util\nfrom automol.geom import _base as geom_base\nfrom automol.graph.geom import center_of_mass\nfrom automol.graph.geom import translate as _translate\nfrom automol.graph.geom import geometry_join as _geometry_join\n\nAXIS_DCT = {'x': 0, 'y': 1, 'z': 2}\n\n\n# General transformation functions\ndef transform(geo, func, idxs=None):\n    \"\"\" Transform the coordinates of a geometry by a function.\n        A set of `idxs` can be supplied to transform a subset of coordinates.\n\n        :param geo: molecular geometry\n        :type geo: automol geometry data structure\n        :param func: transformation function\n        :type func: function object\n        :param idxs: indices representing the subset of atoms\n        :type idxs: tuple(int)\n    \"\"\"\n\n    idxs = list(range(geom_base.count(geo))) if idxs is None else idxs\n    symbs = geom_base.symbols(geo)\n    xyzs = geom_base.coordinates(geo)\n    xyzs = [func(xyz) if idx in idxs else xyz for idx, xyz in enumerate(xyzs)]\n\n    return automol.create.geom.from_data(symbs, xyzs)\n\n\ndef transform_by_matrix(geo, mat):\n    \"\"\" Transform the coordinates of a molecular geometry by multiplying\n        it by some input transfomration matrix.\n\n        :param geo: molecular geometry\n        :type geo: automol molecular geometry data structure\n        :param mat: transformation matrix\n        :type mat: tuple(tuple(float))\n        :rtype: automol moleculer geometry data structure\n    \"\"\"\n\n    symbs = geom_base.symbols(geo)\n    xyzs = geom_base.coordinates(geo)\n    xyzs = numpy.dot(xyzs, numpy.transpose(mat))\n\n    return automol.create.geom.from_data(symbs, xyzs)\n\n\n# transformations\ndef remove_coordinates(geo, idxs=()):\n    \"\"\" Remove atoms by from the molecular geometry by their indices.\n\n        :param geo: molecular geometry\n        :type geo: automol molecular geometry data structure\n        :param idxs: indices of atoms to remove\n        :type idxs: tuple(int)\n        :rtype: automol molecular geometry data structure\n    \"\"\"\n    return tuple(row for i, row in enumerate(geo) if i not in idxs)\n\n\ndef join(geo1, geo2,\n         dist_cutoff=3.0*phycon.ANG2BOHR, theta=0.0, phi=0.0):\n    \"\"\" Join two molecular geometries together where the intermolecular\n        separation and orientation can be specified.\n\n        :param geo1: molecular geometry 1\n        :type geo1: automol molecular geometry data structure\n        :param geo2: molecular geometry 2\n        :type geo2: automol molecular geometry data structure\n        :param dist_cutoff: threshhold for center-of-mass distance\n        :type: dist_cutoff: float\n        :param theta: theta angle for intermolecular orientation\n        :type theta: float\n        :param phi: phi angle for intermolecular orientation\n        :type phi: float\n        :rtype: automol molecular geometry data structure\n    \"\"\"\n    return _geometry_join(\n        geo1, geo2, dist_cutoff=dist_cutoff, theta=theta, phi=phi)\n\n\ndef reorder_coordinates(geo, idx_dct):\n    \"\"\" Reorder the atoms of a molecular geometry using\n        the mapping of an input dictionary.\n\n        :param geo: The geometry\n        :param idx_dct: The new order of the atoms, by index\n        :type idx_dct: dict\n        :rtype: automol geometry data structure\n    \"\"\"\n\n    symbs = geom_base.symbols(geo)\n    xyzs = geom_base.coordinates(geo)\n\n    idxs = [idx for idx, _ in sorted(idx_dct.items(), key=lambda x: x[1])]\n    assert len(symbs) == len(xyzs) == len(idxs)\n\n    symbs = [symbs[idx] for idx in idxs]\n    xyzs = [xyzs[idx] for idx in idxs]\n\n    return automol.create.geom.from_data(symbs, xyzs)\n\n\ndef move_atom(geo, idx1, idx2):\n    \"\"\" Move an atom to a different position in the geometry\n\n        :param geo: molecular geometry\n        :type geo: automol molecular geometry data structure\n        :param idx1: index of the atom to be moved\n        :type idx1: int\n        :param idx2: new position that the atom should be moved to\n        :type idx2: int\n        :returns: the transformed geometry\n        :rtype: molecular geometry\n    \"\"\"\n    symbs = list(geom_base.symbols(geo))\n    xyzs = list(geom_base.coordinates(geo))\n    symbs.insert(idx2, symbs.pop(idx1))\n    xyzs.insert(idx2, xyzs.pop(idx1))\n    return automol.create.geom.from_data(symbs, xyzs)\n\n\ndef swap_coordinates(geo, idx1, idx2):\n    \"\"\" Swap the order of the coordinates of two atoms in a molecular geometry.\n\n        :param geo: molecular geometry\n        :type geo: automol molecular geometry data structure\n        :param idx1: index for one atom to swap coordinates\n        :type idx1: int\n        :param idx2: index for one atom to swap coordinates\n        :type idx2: int\n        :rtype: molecular geometry\n    \"\"\"\n\n    geo = [list(x) for x in geo]\n    geo[idx1], geo[idx2] = geo[idx2], geo[idx1]\n    geo_swp = tuple(tuple(x) for x in geo)\n\n    return geo_swp\n\n\ndef insert(geo, symb, xyz, idx=None, angstrom=False):\n    \"\"\" Insert an atom into a molecular geometry.\n\n        :param geo: molecular geometry\n        :type geo: automol molecular geometry data structure\n        :param symb: symbol of atom to add\n        :type symb: str\n        :param xyz: xyz coordinates of atom to add\n        :type xyz: tuple(float)\n        :param idx: index of geometry to place atom\n        :type idx: int\n        :rtype: automol geometry date structure\n    \"\"\"\n\n    return automol.convert.geom.insert(\n        geo, symb, xyz, idx=idx, angstrom=angstrom)\n\n\ndef insert_dummies(geo, dummy_key_dct, dist=1., tol=5.):\n    \"\"\" Insert dummy atoms over atoms in a geometry in a particular order.\n\n        :param geo: the geometry\n        :type geo: automol molecular geometry data structure\n        :param dummy_key_dct: the linear atoms and the desired positions of the\n            dummy atoms for each; linear atom indexing should follow what they\n            *will* be after the dummy atoms are moved to the appropriate\n            positions\n        :param dummy_key_dct: dict\n        :param dist: distance of dummy atom from the linear atom, in angstroms\n        :type dist: float\n        :param tol: the tolerance threshold for linearity, in degrees\n        :type tol: float\n        :returns: geometry with dummy atoms inserted, along with a dictionary\n            mapping the linear atoms onto their associated dummy atoms\n        :rtype: automol molecular geometry data structure\n    \"\"\"\n    lin_keys, dum_keys = zip(\n        *sorted(dummy_key_dct.items(), key=lambda x: x[1]))\n    dum_keys = numpy.array(list(dum_keys))\n    lin_idxs = [k-sum(k > dum_keys) for k in lin_keys]\n    geo, orig_dummy_key_dct = insert_dummies_on_linear_atoms(\n        geo, lin_idxs=lin_idxs, dist=dist, tol=tol)\n\n    for lin_idx, lin_key in zip(lin_idxs, lin_keys):\n        orig_idx = orig_dummy_key_dct[lin_idx]\n        new_idx = dummy_key_dct[lin_key]\n        geo = move_atom(geo, orig_idx, new_idx)\n\n    return geo\n\n\ndef insert_dummies_on_linear_atoms(geo, lin_idxs=None, gra=None, dist=1.,\n                                   tol=5.):\n    \"\"\" Insert dummy atoms over linear atoms in the geometry.\n\n        :param geo: the geometry\n        :type geo: automol molecular geometry data structure\n        :param lin_idxs: the indices of the linear atoms; if None, indices are\n            automatically determined from the geometry based on the graph\n        :type lin_idxs: tuple(int)\n        :param gra: the graph describing connectivity; if None, a connectivity\n            graph will be generated using default distance thresholds\n        :type gra: automol molecular graph data structure\n        :param dist: distance of dummy atom from the linear atom, in angstroms\n        :type dist: float\n        :param tol: the tolerance threshold for linearity, in degrees\n        :type tol: float\n        :returns: geometry with dummy atoms inserted, along with a dictionary\n            mapping the linear atoms onto their associated dummy atoms\n        :rtype: automol molecular geometry data structure\n    \"\"\"\n    return automol.convert.geom.insert_dummies_on_linear_atoms(\n        geo, lin_idxs=lin_idxs, gra=gra, dist=dist, tol=tol)\n\n\ndef displace(geo, xyzs):\n    \"\"\" Displace the coordinates of a geometry along a vector.\n\n        :param geo: molecular geometry\n        :type geo: automol molecular geometry data structure\n        :param xyzs: vector to displace along\n        :type xyzs: tuple(float)\n        :rtype: automol molecular geometry data structure\n    \"\"\"\n\n    symbs = geom_base.symbols(geo)\n    orig_xyzs = geom_base.coordinates(geo)\n    xyzs = numpy.add(orig_xyzs, xyzs)\n\n    return automol.create.geom.from_data(symbs, xyzs)\n\n\n# redundant with above\ndef translate(geo, xyz):\n    \"\"\" Translate the coordinates of a molecular geometry along\n        a three-dimensiona vector.\n\n        :param geo: molecular geometry\n        :type geo: automol molecular geometry data structure\n        :param xyz: vector to translate along\n        :type xyz: tuple(float)\n        :rtype: automol molecular geometry data structure\n    \"\"\"\n    return _translate(geo, xyz)\n\n\ndef perturb(geo, atm_idx, pert_xyz):\n    \"\"\" Perturb the position of one atom by\n        changing the value of an xyz coord by some amount.\n    \"\"\"\n\n    # Get the xyz coordinates of the atom to perturb\n    atm_coords = list(geom_base.coordinates(geo)[atm_idx])\n\n    # Get the perturbed set of atomic coordinates\n    for idx, val in enumerate(pert_xyz):\n        atm_coords[idx] += val\n    pert_dct = {atm_idx: atm_coords}\n\n    # Perturb the coordinates of the atom\n    pert_geo = geom_base.set_coordinates(geo, pert_dct)\n\n    return pert_geo\n\n\ndef mass_centered(geo):\n    \"\"\" Generate a new geometry where the coordinates of the input geometry\n        have been translated to the center-of-mass.\n\n        :param geo: molecular geometry\n        :type geo: automol geometry data structure\n        :rtype: tuple(float)\n    \"\"\"\n    return translate(geo, numpy.negative(center_of_mass(geo)))\n\n\ndef rotate(geo, axis, angle, orig_xyz=None, idxs=None):\n    \"\"\" Rotate the coordinates of a molecular geometry about\n        an axis by a specified angle. A set of `idxs` can be supplied\n        to transform a subset of coordinates.\n\n        :param geo: molecular geometry\n        :type geo: automol geometry data structure\n        :param axis: axis to rotate about\n        :type axis: tuple(float)\n        :param angle: angle of rotation\n        :type angle: float\n        :param orig_xyz: xyz coordinates of the origin\n        :type orig_xyz: tuple(float)\n        :param idxs: indices of atoms whose coordinates are to be rotated\n        :type idxs: tuple(int)\n    \"\"\"\n\n    func = util.vec.rotater(axis, angle, orig_xyz=orig_xyz)\n\n    return transform(geo, func, idxs=idxs)\n\n\ndef euler_rotate(geo, theta, phi, psi):\n    \"\"\" Rotate the coordinates of a molecular geometry about\n        the three Euler angles.\n\n        :param geo: molecular geometry\n        :type geo: automol geometry data structure\n        :param theta: angle to rotate about z-axis\n        :type theta: float\n        :param phi: angle to rotate about x'-axis\n        :type phi: float\n        :param psi: angle to rotate about z'-axis\n        :type psi: float\n        :rtype: automol geometry data structure\n    \"\"\"\n\n    mat = util.mat.euler_rotation_matrix(theta, phi, psi)\n\n    return transform_by_matrix(geo, mat)\n\n\ndef shift_atom_position(geo, idx1, idx2):\n    \"\"\" Move the atom at position idx1 to idx2, shifting all other atoms.\n\n        :param geo: molecular geometry\n        :type geo: automol geometry data structure\n        :param idx1: index of atom 1 in the pair to be measured\n        :type idx1: int\n        :param idx2: index of atom 2 in the pair to be measured\n        :type idx2: int\n        :rtype: automol geometry data structure\n    \"\"\"\n\n    # Get the coordinates at idx1 that are to be moved\n    geo = [list(x) for x in geo]\n    moving_coords = geo[idx1]\n\n    # move the coordinates to idx2\n    geo.remove(moving_coords)\n    geo.insert(idx2, moving_coords)\n    geo_move = tuple(tuple(x) for x in geo)\n\n    return geo_move\n\n\ndef reflect_coordinates(geo, idxs, axes):\n    \"\"\" Reflect a specified set of coordinates of a molecular geometry\n        about some each of the requested axes.\n\n        A set of `idxs` can be supplied to transform a subset of coordinates.\n\n        :param geo: molecular geometry\n        :type geo: automol geometry data structure\n        :param idxs: indices of atoms whose coordinates are to be reflected\n        :type idxs: tuple(int)\n        :param axes: axes to reflect about\n        :type axes: tuple(str)\n        :rtype: automol geometry data structure\n    \"\"\"\n\n    # check input\n    assert all(idx < len(geo) for idx in idxs)\n    assert all(axis in ('x', 'y', 'z') for axis in axes)\n\n    # get coords\n    coords = geom_base.coordinates(geo)\n\n    # convert x,y,z to nums\n    axes = [AXIS_DCT[axis] for axis in axes]\n\n    # build set atom dct with relected coords\n    reflect_dct = {}\n    for idx in idxs:\n        coord_lst = list(coords[idx])\n        for axis in axes:\n            coord_lst[axis] *= -1.0\n        reflect_dct[idx] = coord_lst\n\n    # Reflect coords with dct\n    geo_reflected = geom_base.set_coordinates(geo, reflect_dct)\n\n    return geo_reflected\n", "meta": {"hexsha": "098e9f50960dd06730b96221451ed5e96e68f793", "size": 13299, "ext": "py", "lang": "Python", "max_stars_repo_path": "automol/geom/_trans.py", "max_stars_repo_name": "sjklipp/autochem", "max_stars_repo_head_hexsha": "ac343a4bc5ff8c9a75e75d7ed717ea2db659b7a0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "automol/geom/_trans.py", "max_issues_repo_name": "sjklipp/autochem", "max_issues_repo_head_hexsha": "ac343a4bc5ff8c9a75e75d7ed717ea2db659b7a0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "automol/geom/_trans.py", "max_forks_repo_name": "sjklipp/autochem", "max_forks_repo_head_hexsha": "ac343a4bc5ff8c9a75e75d7ed717ea2db659b7a0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1876606684, "max_line_length": 79, "alphanum_fraction": 0.6681705391, "include": true, "reason": "import numpy", "num_tokens": 3229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.18160224616504209}}
{"text": "import os\nimport os.path as osp\nimport json\nfrom tqdm import tqdm\nimport pandas as pd\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch_geometric.data import Data, InMemoryDataset\nfrom itertools import repeat\nfrom rdkit import Chem\nfrom rdkit.Chem import AllChem\nfrom rdkit import DataStructs\nfrom chem import *\n\n\nclass MultiGraphData(Data):\n    def __init__(self, x=None, edge_index=None, edge_attr=None,\n                 fg_x=None, fg_edge_index=None, atom2fg_index=None,\n                 **kwargs):\n        super(MultiGraphData, self).__init__(x=x, edge_index=edge_index, edge_attr=edge_attr)\n        self.fg_x = fg_x\n        self.fg_edge_index = fg_edge_index\n        self.num_fgs = fg_x.size(0) if fg_x is not None else None\n        self.atom2fg_index = atom2fg_index\n        for key, value in kwargs.items():\n            setattr(self, key, value)\n\n    def __inc__(self, key, value):\n        r\"\"\"Returns the incremental count to cumulatively increase the value\n        of the next attribute of :obj:`key` when creating batches.\n\n        .. note::\n\n            This method is for internal use only, and should only be overridden\n            if the batch concatenation process is corrupted for a specific data\n            attribute.\n        \"\"\"\n        # Only `*index*` and `*face*` attributes should be cumulatively summed\n        # up when creating batches.\n        if key == 'fg_edge_index':\n            return self.fg_x.size(0)\n        elif key == 'atom2fg_index':\n            return torch.tensor([[self.num_nodes], [self.fg_x.size(0)]])\n        else:\n            return super(MultiGraphData, self).__inc__(key, value)\n\n\nclass PretrainDataset(InMemoryDataset):\n    def __init__(self, root='data/ZINC15',\n                 mol_filename='zinc15_250k.txt',\n                 fg_corpus_filename='fg_corpus.txt',\n                 mol2fgs_filename='mol2fgs_list.json',\n                 ):\n        self.mol_fn = mol_filename\n        self.corpus_fn = fg_corpus_filename\n        self.mol2fgs_fn = mol2fgs_filename\n        super().__init__(root=root)\n\n        self.data, self.slices = torch.load(self.processed_paths[0])\n\n    @property\n    def raw_dir(self):\n        return self.root\n\n    @property\n    def raw_file_names(self):\n        return [self.mol_fn, self.corpus_fn, self.mol2fgs_fn]\n\n    @property\n    def processed_file_names(self):\n        return osp.splitext(self.raw_file_names[0])[0] + '.pt'\n\n    def get(self, idx):\n        data = self.data.__class__()\n        if hasattr(self.data, '__num_nodes__'):\n            data.num_nodes = self.data.__num_nodes__[idx]\n\n        for key in self.data.keys:\n            item, slices = self.data[key], self.slices[key]\n            start, end = slices[idx].item(), slices[idx + 1].item()\n            if torch.is_tensor(item):\n                s = list(repeat(slice(None), item.dim()))\n                s[self.data.__cat_dim__(key, item)] = slice(start, end)\n            elif start + 1 == end:\n                s = slices[start]\n            else:\n                s = slice(start, end)\n            data[key] = item[s]\n\n        return data\n\n    def process(self):\n        with open(self.raw_paths[0], 'r') as f:\n            smiles_list = f.read().splitlines()\n        with open(self.raw_paths[1], 'r') as f:\n            fg_corpus = f.read().splitlines()\n        with open(self.raw_paths[2], 'r') as f:\n            mol2fgs = json.load(f)\n        print(f\"# mol: {len(smiles_list)}   # corpus: {len(fg_corpus)}\")\n\n        data_list = []\n        for smiles, fgs in tqdm(zip(smiles_list, mol2fgs)):\n            mol = Chem.MolFromSmiles(smiles)\n            atom_features, bond_list, bond_features, fg_features, fg_edge_list, fg_edge_features, atom2fg_list = mol_to_graphs(mol)\n            fp = AllChem.GetMorganFingerprintAsBitVect(mol, radius=2, nBits=1024)\n            fpvec = np.zeros(0)\n            DataStructs.ConvertToNumpyArray(fp, fpvec)\n            fgvec = np.zeros(len(fg_corpus))\n            idx = []\n            for fg in fgs:\n                try:\n                    idx.append(fg_corpus.index(fg))\n                except:\n                    pass\n            fgvec[idx] = 1\n            data = MultiGraphData(x=torch.Tensor(atom_features),\n                                  edge_index=torch.LongTensor(bond_list).reshape(-1, 2).transpose(1, 0),\n                                  edge_attr=torch.Tensor(bond_features).reshape(-1, BOND_DIM),\n                                  fg_x=torch.Tensor(fg_features),\n                                  fg_edge_index=torch.LongTensor(fg_edge_list).reshape(-1, 2).transpose(1, 0),\n                                  fg_edge_attr=torch.Tensor(fg_edge_features).reshape(-1, FG_EDGE_DIM),\n                                  atom2fg_index=torch.LongTensor(atom2fg_list).reshape(-1, 2).transpose(1, 0),\n                                  fp=torch.Tensor(fpvec).reshape(1, -1),\n                                  fg=torch.Tensor(fgvec).reshape(1, -1))\n            data_list.append(data)\n\n        data, slices = self.collate(data_list)\n        torch.save((data, slices), self.processed_paths[0])\n\n\nclass MoleculeNetDataset():\n    def __init__(self, dataset):\n        self.dataset = dataset\n\n    def __getitem__(self, index):\n        atom_features, bond_list, bond_features, fg_features, fg_edge_list, fg_edge_features, atom2fg_list, y, w = self.dataset[index]\n        data = MultiGraphData(x=torch.Tensor(atom_features),\n                              edge_index=torch.LongTensor(bond_list).reshape(-1, 2).transpose(1, 0),\n                              edge_attr=torch.Tensor(bond_features).reshape(-1, BOND_DIM),\n                              fg_x=torch.Tensor(fg_features),\n                              fg_edge_index=torch.LongTensor(fg_edge_list).reshape(-1, 2).transpose(1, 0),\n                              fg_edge_attr=torch.Tensor(fg_edge_features).reshape(-1, FG_EDGE_DIM),\n                              atom2fg_index=torch.LongTensor(atom2fg_list).reshape(-1, 2).transpose(1, 0),\n                              y=torch.Tensor(y),\n                              w=torch.Tensor(w))\n        return data\n\n    def __len__(self):\n        return len(self.dataset)\n\n\nclass DDIDataset(InMemoryDataset):\n    def __init__(self, root='data/DDI/ZhangDDI',\n                 drug_filename='drug_list_zhang.csv',\n                 ddi_filename='ZhangDDI_train.csv'):\n        self.drug_fn = drug_filename\n        self.ddi_fn = ddi_filename\n        super().__init__(root=root)\n\n        self.drugs = torch.load(self.processed_paths[0])\n        df = pd.read_csv(os.path.join(self.root, self.ddi_fn), usecols=['smiles_1', 'smiles_2', 'label'])\n        self.ddi = df.values\n\n    @property\n    def raw_dir(self):\n        return self.root\n\n    @property\n    def raw_file_names(self):\n        return self.drug_fn\n\n    @property\n    def processed_file_names(self):\n        return osp.splitext(self.raw_file_names)[0] + '.pt'\n\n    def __getitem__(self, idx):\n        id1, id2, label = self.ddi[idx]\n        return self.drugs[id1], self.drugs[id2], torch.Tensor([float(label)])\n\n    def __len__(self):\n        return len(self.ddi)\n\n    def process(self):\n        df = pd.read_csv(self.raw_paths[0], usecols=['drugbank_id', 'smiles'])\n        print(f\"# drugs: {len(df)}\")\n\n        data_dict = {}\n        for _, drug in tqdm(df.iterrows()):\n            id, smiles = drug['drugbank_id'], drug['smiles']\n            mol = Chem.MolFromSmiles(smiles)\n            atom_features, bond_list, bond_features, fg_features, fg_edge_list, fg_edge_features, atom2fg_list = mol_to_graphs(mol)\n            if fg_features == []:  # C\n                print(f\"{smiles} cannot be converted to FG graph\")\n                continue\n            data = MultiGraphData(x=torch.Tensor(atom_features),\n                                  edge_index=torch.LongTensor(bond_list).reshape(-1, 2).transpose(1, 0),\n                                  edge_attr=torch.Tensor(bond_features).reshape(-1, BOND_DIM),\n                                  fg_x=torch.Tensor(fg_features),\n                                  fg_edge_index=torch.LongTensor(fg_edge_list).reshape(-1, 2).transpose(1, 0),\n                                  fg_edge_attr=torch.Tensor(fg_edge_features).reshape(-1, FG_EDGE_DIM),\n                                  atom2fg_index=torch.LongTensor(atom2fg_list).reshape(-1, 2).transpose(1, 0))\n            data_dict[smiles] = data\n\n        torch.save(data_dict, self.processed_paths[0])\n\n\nif __name__ == '__main__':\n    dataset = PretrainDataset(mol_filename='zinc15_250k.txt',\n                              fg_corpus_filename='fg_corpus.txt',\n                              mol2fgs_filename='mol2fgs_list.json')\n    data = dataset[0]", "meta": {"hexsha": "c029cbad7da67380730f3366d21a0951fd300a96", "size": 8699, "ext": "py", "lang": "Python", "max_stars_repo_path": "loader.py", "max_stars_repo_name": "Meteor-han/ReLMole", "max_stars_repo_head_hexsha": "ec8f2d3ec7b8edb6cd34aede36a980bab3dc35c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-19T03:12:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T03:12:21.000Z", "max_issues_repo_path": "loader.py", "max_issues_repo_name": "Meteor-han/ReLMole", "max_issues_repo_head_hexsha": "ec8f2d3ec7b8edb6cd34aede36a980bab3dc35c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "loader.py", "max_forks_repo_name": "Meteor-han/ReLMole", "max_forks_repo_head_hexsha": "ec8f2d3ec7b8edb6cd34aede36a980bab3dc35c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.8403755869, "max_line_length": 134, "alphanum_fraction": 0.5838602138, "include": true, "reason": "import numpy", "num_tokens": 2044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.18159080642804995}}
{"text": "# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\nimport abc\nimport numpy as np\nfrom warnings import warn\nfrom sklearn.base import clone\nfrom sklearn.model_selection import GroupKFold\nfrom scipy.stats import norm\nfrom sklearn.linear_model import (ElasticNetCV, LassoCV, LogisticRegressionCV)\nfrom ...sklearn_extensions.linear_model import (StatsModelsLinearRegression, WeightedLassoCVWrapper)\nfrom ...sklearn_extensions.model_selection import WeightedStratifiedKFold\nfrom ...dml.dml import _FirstStageWrapper, _FinalWrapper\nfrom ..._cate_estimator import TreatmentExpansionMixin, LinearModelFinalCateEstimatorMixin\nfrom ..._ortho_learner import _OrthoLearner\nfrom ...utilities import (_deprecate_positional, add_intercept,\n                          broadcast_unit_treatments, check_high_dimensional,\n                          cross_product, deprecated, fit_with_groups,\n                          hstack, inverse_onehot, ndim, reshape,\n                          reshape_treatmentwise_effects, shape, transpose,\n                          get_feature_names_or_default, check_input_arrays,\n                          filter_none_kwargs)\n\n\ndef _get_groups_period_filter(groups, n_periods):\n    group_counts = {}\n    group_period_filter = {i: [] for i in range(n_periods)}\n    for i, g in enumerate(groups):\n        if g not in group_counts:\n            group_counts[g] = 0\n        group_period_filter[group_counts[g]].append(i)\n        group_counts[g] += 1\n    return group_period_filter\n\n\nclass _DynamicModelNuisance:\n    \"\"\"\n    Nuisance model fits the model_y and model_t at fit time and at predict time\n    calculates the residual Y and residual T based on the fitted models and returns\n    the residuals as two nuisance parameters.\n    \"\"\"\n\n    def __init__(self, model_y, model_t, n_periods):\n        self._model_y = model_y\n        self._model_t = model_t\n        self.n_periods = n_periods\n\n    def fit(self, Y, T, X=None, W=None, sample_weight=None, groups=None):\n        \"\"\"Fit a series of nuisance models for each period or period pairs.\"\"\"\n        assert Y.shape[0] % self.n_periods == 0, \\\n            \"Length of training data should be an integer multiple of time periods.\"\n        period_filters = _get_groups_period_filter(groups, self.n_periods)\n        self._model_y_trained = {}\n        self._model_t_trained = {j: {} for j in np.arange(self.n_periods)}\n        for t in np.arange(self.n_periods):\n            self._model_y_trained[t] = clone(self._model_y, safe=False).fit(\n                self._index_or_None(X, period_filters[t]),\n                self._index_or_None(\n                    W, period_filters[t]),\n                Y[period_filters[self.n_periods - 1]])\n            for j in np.arange(t, self.n_periods):\n                self._model_t_trained[j][t] = clone(self._model_t, safe=False).fit(\n                    self._index_or_None(X, period_filters[t]),\n                    self._index_or_None(W, period_filters[t]),\n                    T[period_filters[j]])\n        return self\n\n    def predict(self, Y, T, X=None, W=None, sample_weight=None, groups=None):\n        \"\"\"Calculate nuisances for each period or period pairs.\n\n        Returns\n        -------\n        Y_res : (n, d_y) matrix or vector of length n\n            Y residuals for each period in panel format.\n            This shape is required for _OrthoLearner's crossfitting.\n        T_res : (n, d_t, n_periods) matrix\n            T residuals for pairs of periods (t, j), where the data is in panel format for t\n            and in index form for j. For example, the residuals for (t, j) can be retrieved via\n            T_res[np.arange(n) % n_periods == t, ..., j]. For t < j, the entries of this\n            matrix are np.nan.\n            This shape is required for _OrthoLearner's crossfitting.\n        \"\"\"\n        assert Y.shape[0] % self.n_periods == 0, \\\n            \"Length of training data should be an integer multiple of time periods.\"\n        period_filters = _get_groups_period_filter(groups, self.n_periods)\n        Y_res = np.full(Y.shape, np.nan)\n        T_res = np.full(T.shape + (self.n_periods, ), np.nan)\n        shape_formatter = self._get_shape_formatter(X, W)\n        for t in np.arange(self.n_periods):\n            Y_slice = Y[period_filters[self.n_periods - 1]]\n            Y_pred = self._model_y_trained[t].predict(\n                self._index_or_None(X, period_filters[t]),\n                self._index_or_None(W, period_filters[t]))\n            Y_res[period_filters[t]] = Y_slice\\\n                - shape_formatter(Y_slice, Y_pred)\n            for j in np.arange(t, self.n_periods):\n                T_slice = T[period_filters[j]]\n                T_pred = self._model_t_trained[j][t].predict(\n                    self._index_or_None(X, period_filters[t]),\n                    self._index_or_None(W, period_filters[t]))\n                T_res[period_filters[j], ..., t] = T_slice\\\n                    - shape_formatter(T_slice, T_pred)\n        return Y_res, T_res\n\n    def score(self, Y, T, X=None, W=None, sample_weight=None, groups=None):\n        assert Y.shape[0] % self.n_periods == 0, \\\n            \"Length of training data should be an integer multiple of time periods.\"\n        period_filters = _get_groups_period_filter(groups, self.n_periods)\n        if hasattr(self._model_y, 'score'):\n            Y_score = np.full((self.n_periods, ), np.nan)\n            for t in np.arange(self.n_periods):\n                Y_score[t] = self._model_y_trained[t].score(\n                    self._index_or_None(X, period_filters[t]),\n                    self._index_or_None(W, period_filters[t]),\n                    Y[period_filters[self.n_periods - 1]])\n        else:\n            Y_score = None\n        if hasattr(self._model_t, 'score'):\n            T_score = np.full((self.n_periods, self.n_periods), np.nan)\n            for t in np.arange(self.n_periods):\n                for j in np.arange(t, self.n_periods):\n                    T_score[j][t] = self._model_t_trained[j][t].score(\n                        self._index_or_None(X, period_filters[t]),\n                        self._index_or_None(W, period_filters[t]),\n                        T[period_filters[j]])\n        else:\n            T_score = None\n        return Y_score, T_score\n\n    def _get_shape_formatter(self, X, W):\n        if (X is None) and (W is None):\n            return lambda x, x_pred: np.tile(x_pred.reshape(1, -1), (x.shape[0], 1)).reshape(x.shape)\n        return lambda x, x_pred: x_pred.reshape(x.shape)\n\n    def _index_or_None(self, X, filter_idx):\n        return None if X is None else X[filter_idx]\n\n\nclass _DynamicModelFinal:\n    \"\"\"\n    Final model at fit time, fits a residual on residual regression with a heterogeneous coefficient\n    that depends on X, i.e.\n\n        .. math ::\n            Y - E[Y | X, W] = \\\\theta(X) \\\\cdot (T - E[T | X, W]) + \\\\epsilon\n\n    and at predict time returns :math:`\\\\theta(X)`. The score method returns the MSE of this final\n    residual on residual regression.\n    Assumes model final is parametric with no intercept.\n    \"\"\"\n    # TODO: update docs\n\n    def __init__(self, model_final, n_periods):\n        self._model_final = model_final\n        self.n_periods = n_periods\n        self._model_final_trained = {k: clone(self._model_final, safe=False) for k in np.arange(n_periods)}\n\n    def fit(self, Y, T, X=None, W=None, Z=None, nuisances=None, sample_weight=None, sample_var=None, groups=None):\n        # NOTE: sample weight, sample var are not passed in\n        period_filters = _get_groups_period_filter(groups, self.n_periods)\n        Y_res, T_res = nuisances\n        self._d_y = Y.shape[1:]\n        for t in np.arange(self.n_periods - 1, -1, -1):\n            Y_adj = Y_res[period_filters[t]].copy()\n            if t < self.n_periods - 1:\n                Y_adj -= np.sum(\n                    [self._model_final_trained[j].predict_with_res(\n                        X[period_filters[0]] if X is not None else None,\n                        T_res[period_filters[j], ..., t]\n                    ) for j in np.arange(t + 1, self.n_periods)], axis=0)\n            self._model_final_trained[t].fit(\n                X[period_filters[0]] if X is not None else None, T[period_filters[t]],\n                T_res[period_filters[t], ..., t], Y_adj)\n\n        return self\n\n    def predict(self, X=None):\n        \"\"\"\n        Return shape: m x dy x (p*dt)\n        \"\"\"\n        d_t_tuple = self._model_final_trained[0]._d_t\n        d_t = d_t_tuple[0] if d_t_tuple else 1\n        x_dy_shape = (X.shape[0] if X is not None else 1, ) + \\\n            self._model_final_trained[0]._d_y\n        preds = np.zeros(\n            x_dy_shape +\n            (self.n_periods * d_t, )\n        )\n        for t in range(self.n_periods):\n            preds[..., t * d_t: (t + 1) * d_t] = \\\n                self._model_final_trained[t].predict(X).reshape(\n                x_dy_shape + (d_t, )\n            )\n        return preds\n\n    def score(self, Y, T, X=None, W=None, Z=None, nuisances=None, sample_weight=None, sample_var=None, groups=None):\n        assert Y.shape[0] % self.n_periods == 0, \\\n            \"Length of training data should be an integer multiple of time periods.\"\n        Y_res, T_res = nuisances\n        scores = np.full((self.n_periods, ), np.nan)\n        period_filters = _get_groups_period_filter(groups, self.n_periods)\n        for t in np.arange(self.n_periods - 1, -1, -1):\n            Y_adj = Y_res[period_filters[t]].copy()\n            if t < self.n_periods - 1:\n                Y_adj -= np.sum(\n                    [self._model_final_trained[j].predict_with_res(\n                        X[period_filters[0]] if X is not None else None,\n                        T_res[period_filters[j], ..., t]\n                    ) for j in np.arange(t + 1, self.n_periods)], axis=0)\n            Y_adj_pred = self._model_final_trained[t].predict_with_res(\n                X[period_filters[0]] if X is not None else None,\n                T_res[period_filters[t], ..., t])\n            if sample_weight is not None:\n                scores[t] = np.mean(np.average((Y_adj - Y_adj_pred)**2, weights=sample_weight, axis=0))\n            else:\n                scores[t] = np.mean((Y_adj - Y_adj_pred) ** 2)\n        return scores\n\n\nclass _LinearDynamicModelFinal(_DynamicModelFinal):\n    \"\"\"Wrapper for the DynamicModelFinal with StatsModelsLinearRegression final model.\n\n    The final model is a linear model with (d_t*n_periods) coefficients.\n    This model is defined after the coefficients and covariance are calculated.\n    \"\"\"\n\n    def __init__(self, model_final, n_periods):\n        super().__init__(model_final, n_periods)\n        self.model_final_ = StatsModelsLinearRegression(fit_intercept=False)\n\n    def fit(self, Y, T, X=None, W=None, Z=None, nuisances=None, sample_weight=None, sample_var=None, groups=None):\n        super().fit(Y, T, X=X, W=W, Z=Z, nuisances=nuisances,\n                    sample_weight=sample_weight, sample_var=sample_var, groups=groups)\n        # Compose final model\n        cov = self._get_cov(nuisances, X, groups)\n        coef = self._get_coef_()\n        self.model_final_._n_out = self._d_y[0] if self._d_y else 0\n        self.model_final_._param_var = cov / (Y.shape[0] / self.n_periods)\n        self.model_final_._param = coef.T if self.model_final_._n_out else coef\n\n    def _get_coef_(self):\n        period_coefs = np.array([self._model_final_trained[t]._model.coef_ for t in range(self.n_periods)])\n        if self._d_y:\n            return np.array([\n                np.array([period_coefs[k, i, :] for k in range(self.n_periods)]).flatten()\n                for i in range(self._d_y[0])\n            ])\n        return period_coefs.flatten()\n\n    def _get_cov(self, nuisances, X, groups):\n        if self._d_y:\n            return np.array(\n                [self._fit_single_output_cov((nuisances[0][:, i], nuisances[1]), X, i, groups)\n                 for i in range(self._d_y[0])]\n            )\n        return self._fit_single_output_cov(nuisances, X, -1, groups)\n\n    def _fit_single_output_cov(self, nuisances, X, y_index, groups):\n        \"\"\" Calculates the covariance (n_periods*n_treatments)\n            x (n_periods*n_treatments) matrix for a single outcome.\n        \"\"\"\n        Y_res, T_res = nuisances\n        # Calculate auxiliary quantities\n        period_filters = _get_groups_period_filter(groups, self.n_periods)\n        # X ⨂ T_res\n        XT_res = np.array([\n            [\n                self._model_final_trained[0]._combine(\n                    X[period_filters[0]] if X is not None else None,\n                    T_res[period_filters[t], ..., j],\n                    fitting=False\n                )\n                for j in range(self.n_periods)\n            ]\n            for t in range(self.n_periods)\n        ])\n        d_xt = XT_res.shape[-1]\n        # sum(model_final.predict(X, T_res))\n        Y_diff = np.array([\n            np.sum([\n                self._model_final_trained[j].predict_with_res(\n                    X[period_filters[0]] if X is not None else None,\n                    T_res[period_filters[j], ..., t]\n                ) for j in np.arange(t, self.n_periods)],\n                axis=0\n            )\n            for t in np.arange(self.n_periods)\n        ])\n        J = np.zeros((self.n_periods * d_xt,\n                      self.n_periods * d_xt))\n        Sigma = np.zeros((self.n_periods * d_xt,\n                          self.n_periods * d_xt))\n        for t in np.arange(self.n_periods):\n            res_epsilon_t = (Y_res[period_filters[t]] -\n                             (Y_diff[t][:, y_index] if y_index >= 0 else Y_diff[t])\n                             ).reshape(-1, 1, 1)\n            resT_t = XT_res[t][t]\n            for j in np.arange(self.n_periods):\n                # Calculating the (t, j) block entry (of size n_treatments x n_treatments) of matrix Sigma\n                res_epsilon_j = (Y_res[period_filters[j]] -\n                                 (Y_diff[j][:, y_index] if y_index >= 0 else Y_diff[j])\n                                 ).reshape(-1, 1, 1)\n                resT_j = XT_res[j][j]\n                cov_resT_tj = resT_t.reshape(-1, d_xt, 1) @ resT_j.reshape(-1, 1, d_xt)\n                sigma_tj = np.mean((res_epsilon_t * res_epsilon_j) * cov_resT_tj, axis=0)\n                Sigma[t * d_xt:(t + 1) * d_xt,\n                      j * d_xt:(j + 1) * d_xt] = sigma_tj\n                if j >= t:\n                    # Calculating the (t, j) block entry (of size n_treatments x n_treatments) of matrix J\n                    m_tj = np.mean(\n                        XT_res[j][t].reshape(-1, d_xt, 1) @ resT_t.reshape(-1, 1, d_xt),\n                        axis=0)\n                    J[t * d_xt:(t + 1) * d_xt,\n                      j * d_xt:(j + 1) * d_xt] = m_tj\n        return np.linalg.inv(J) @ Sigma @ np.linalg.inv(J).T\n\n\nclass _DynamicFinalWrapper(_FinalWrapper):\n\n    def predict_with_res(self, X, T_res):\n        fts = self._combine(X, T_res, fitting=False)\n        prediction = self._model.predict(fts)\n        if self._intercept is not None:\n            prediction -= self._intercept\n        return reshape(prediction, (prediction.shape[0],) + self._d_y)\n\n\nclass DynamicDML(LinearModelFinalCateEstimatorMixin, _OrthoLearner):\n    \"\"\"CATE estimator for dynamic treatment effect estimation.\n\n    This estimator is an extension of the Double ML approach for treatments assigned sequentially\n    over time periods.\n\n    The estimator is a special case of an :class:`_OrthoLearner` estimator, so it follows the two\n    stage process, where a set of nuisance functions are estimated in the first stage in a crossfitting\n    manner and a final stage estimates the CATE model. See the documentation of\n    :class:`._OrthoLearner` for a description of this two stage process.\n\n    Parameters\n    ----------\n    model_y: estimator or 'auto', optional (default is 'auto')\n        The estimator for fitting the response to the features. Must implement\n        `fit` and `predict` methods.\n        If 'auto' :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV` will be chosen.\n\n    model_t: estimator or 'auto', optional (default is 'auto')\n        The estimator for fitting the treatment to the features.\n        If estimator, it must implement `fit` and `predict` methods;\n        If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV` will be applied for discrete treatment,\n        and :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV`\n        will be applied for continuous treatment.\n\n    featurizer : :term:`transformer`, optional, default None\n        Must support fit_transform and transform. Used to create composite features in the final CATE regression.\n        It is ignored if X is None. The final CATE will be trained on the outcome of featurizer.fit_transform(X).\n        If featurizer=None, then CATE is trained on X.\n\n    fit_cate_intercept : bool, optional, default True\n        Whether the linear CATE model should have a constant term.\n\n    linear_first_stages: bool\n        Whether the first stage models are linear (in which case we will expand the features passed to\n        `model_y` accordingly)\n\n    discrete_treatment: bool, optional (default is ``False``)\n        Whether the treatment values should be treated as categorical, rather than continuous, quantities\n\n    categories: 'auto' or list, default 'auto'\n        The categories to use when encoding discrete treatments (or 'auto' to use the unique sorted values).\n        The first category will be treated as the control treatment.\n\n    cv: int, cross-validation generator or an iterable, optional (Default=2)\n        Determines the cross-validation splitting strategy.\n        Possible inputs for cv are:\n\n        - None, to use the default 3-fold cross-validation,\n        - integer, to specify the number of folds.\n        - :term:`CV splitter`\n        - An iterable yielding (train, test) splits as arrays of indices.\n          Iterables should make sure a group belongs to a single split.\n\n        For integer/None inputs, :class:`~sklearn.model_selection.GroupKFold` is used\n\n        Unless an iterable is used, we call `split(X, T, groups)` to generate the splits.\n\n    mc_iters: int, optional (default=None)\n        The number of times to rerun the first stage models to reduce the variance of the nuisances.\n\n    mc_agg: {'mean', 'median'}, optional (default='mean')\n        How to aggregate the nuisance value for each sample across the `mc_iters` monte carlo iterations of\n        cross-fitting.\n\n    random_state: int, :class:`~numpy.random.mtrand.RandomState` instance or None, optional (default=None)\n        If int, random_state is the seed used by the random number generator;\n        If :class:`~numpy.random.mtrand.RandomState` instance, random_state is the random number generator;\n        If None, the random number generator is the :class:`~numpy.random.mtrand.RandomState` instance used\n        by :mod:`np.random<numpy.random>`.\n\n    Examples\n    --------\n    A simple example with default models:\n\n    .. testcode::\n        :hide:\n\n        import numpy as np\n        np.set_printoptions(suppress=True)\n\n    .. testcode::\n\n        from econml.dynamic.dml import DynamicDML\n\n        np.random.seed(123)\n\n        n_panels = 100  # number of panels\n        n_periods = 3  # number of time periods per panel\n        n = n_panels * n_periods\n        groups = np.repeat(a=np.arange(n_panels), repeats=n_periods, axis=0)\n        X = np.random.normal(size=(n, 1))\n        T = np.random.normal(size=(n, 2))\n        y = np.random.normal(size=(n, ))\n        est = DynamicDML()\n        est.fit(y, T, X=X, W=None, groups=groups, inference=\"auto\")\n\n    >>> est.const_marginal_effect(X[:2])\n    array([[-0.336..., -0.048..., -0.061...,  0.042..., -0.204...,\n         0.00667271],\n        [-0.101...,  0.433...,  0.054..., -0.217..., -0.101...,\n         -0.159...]])\n    >>> est.effect(X[:2], T0=0, T1=1)\n    array([-0.601..., -0.091...])\n    >>> est.effect(X[:2], T0=np.zeros((2, n_periods*T.shape[1])), T1=np.ones((2, n_periods*T.shape[1])))\n    array([-0.601..., -0.091...])\n    >>> est.coef_\n    array([[ 0.112...],\n       [ 0.231...],\n       [ 0.055...],\n       [-0.125...],\n       [ 0.049...],\n       [-0.079...]])\n    >>> est.coef__interval()\n    (array([[-0.063...],\n           [-0.009...],\n           [-0.114...],\n           [-0.413...],\n           [-0.117...],\n           [-0.262...]]), array([[0.289...],\n           [0.471...],\n           [0.225...],\n           [0.163...],\n           [0.216...],\n           [0.103...]]))\n    \"\"\"\n\n    def __init__(self, *,\n                 model_y='auto', model_t='auto',\n                 featurizer=None,\n                 fit_cate_intercept=True,\n                 linear_first_stages=False,\n                 discrete_treatment=False,\n                 categories='auto',\n                 cv=2,\n                 mc_iters=None,\n                 mc_agg='mean',\n                 random_state=None):\n        self.fit_cate_intercept = fit_cate_intercept\n        self.linear_first_stages = linear_first_stages\n        self.featurizer = clone(featurizer, safe=False)\n        self.model_y = clone(model_y, safe=False)\n        self.model_t = clone(model_t, safe=False)\n        super().__init__(discrete_treatment=discrete_treatment,\n                         discrete_instrument=False,\n                         categories=categories,\n                         cv=GroupKFold(cv) if isinstance(cv, int) else cv,\n                         mc_iters=mc_iters,\n                         mc_agg=mc_agg,\n                         random_state=random_state)\n\n    def _gen_featurizer(self):\n        return clone(self.featurizer, safe=False)\n\n    def _gen_model_y(self):\n        if self.model_y == 'auto':\n            model_y = WeightedLassoCVWrapper(random_state=self.random_state)\n        else:\n            model_y = clone(self.model_y, safe=False)\n        return _FirstStageWrapper(model_y, True, self._gen_featurizer(),\n                                  self.linear_first_stages, self.discrete_treatment)\n\n    def _gen_model_t(self):\n        if self.model_t == 'auto':\n            if self.discrete_treatment:\n                model_t = LogisticRegressionCV(cv=WeightedStratifiedKFold(random_state=self.random_state),\n                                               random_state=self.random_state)\n            else:\n                model_t = WeightedLassoCVWrapper(random_state=self.random_state)\n        else:\n            model_t = clone(self.model_t, safe=False)\n        return _FirstStageWrapper(model_t, False, self._gen_featurizer(),\n                                  self.linear_first_stages, self.discrete_treatment)\n\n    def _gen_model_final(self):\n        return StatsModelsLinearRegression(fit_intercept=False)\n\n    def _gen_ortho_learner_model_nuisance(self, n_periods):\n        return _DynamicModelNuisance(\n            model_t=self._gen_model_t(),\n            model_y=self._gen_model_y(),\n            n_periods=n_periods)\n\n    def _gen_ortho_learner_model_final(self, n_periods):\n        wrapped_final_model = _DynamicFinalWrapper(\n            StatsModelsLinearRegression(fit_intercept=False),\n            fit_cate_intercept=self.fit_cate_intercept,\n            featurizer=self.featurizer,\n            use_weight_trick=False)\n        return _LinearDynamicModelFinal(wrapped_final_model, n_periods=n_periods)\n\n    def _prefit(self, Y, T, *args, groups=None, only_final=False, **kwargs):\n        u_periods = np.unique(np.unique(groups, return_counts=True)[1])\n        if len(u_periods) > 1:\n            raise AttributeError(\n                \"Imbalanced panel. Method currently expects only panels with equal number of periods. Pad your data\")\n        self._n_periods = u_periods[0]\n        # generate an instance of the final model\n        self._ortho_learner_model_final = self._gen_ortho_learner_model_final(self._n_periods)\n        if not only_final:\n            # generate an instance of the nuisance model\n            self._ortho_learner_model_nuisance = self._gen_ortho_learner_model_nuisance(self._n_periods)\n        TreatmentExpansionMixin._prefit(self, Y, T, *args, **kwargs)\n\n    def _postfit(self, Y, T, *args, **kwargs):\n        super()._postfit(Y, T, *args, **kwargs)\n        # Set _d_t to effective number of treatments\n        self._d_t = (self._n_periods * self._d_t[0], ) if self._d_t else (self._n_periods, )\n\n    def _strata(self, Y, T, X=None, W=None, Z=None,\n                sample_weight=None, sample_var=None, groups=None,\n                cache_values=False, only_final=False, check_input=True):\n        # Required for bootstrap inference\n        return groups\n\n    def fit(self, Y, T, *, X=None, W=None, sample_weight=None, sample_var=None, groups,\n            cache_values=False, inference='auto'):\n        \"\"\"Estimate the counterfactual model from data, i.e. estimates function :math:`\\\\theta(\\\\cdot)`.\n\n        The input data must contain groups with the same size corresponding to the number\n        of time periods the treatments were assigned over.\n\n        The data should be preferably in panel format, with groups clustered together.\n        If group members do not appear together, the following is assumed:\n\n        * the first instance of a group in the dataset is assumed to correspond to the first period of that group\n        * the second instance of a group in the dataset is assumed to correspond to the\n          second period of that group\n\n        ...etc.\n\n        Only the value of the features X at the first period of each unit are used for\n        heterogeneity. The value of X in subseuqnet periods is used as a time-varying control\n        but not for heterogeneity.\n\n        Parameters\n        ----------\n        Y: (n, d_y) matrix or vector of length n\n            Outcomes for each sample (required: n = n_groups * n_periods)\n        T: (n, d_t) matrix or vector of length n\n            Treatments for each sample (required: n = n_groups * n_periods)\n        X: optional(n, d_x) matrix or None (Default=None)\n            Features for each sample (Required: n = n_groups * n_periods). Only first\n            period features from each unit are used for heterogeneity, the rest are\n            used as time-varying controls together with W\n        W: optional(n, d_w) matrix or None (Default=None)\n            Controls for each sample (Required: n = n_groups * n_periods)\n        sample_weight: optional(n,) vector or None (Default=None)\n            Weights for each samples\n        sample_var: optional(n,) vector or None (Default=None)\n            Sample variance for each sample\n        groups: (n,) vector, required\n            All rows corresponding to the same group will be kept together during splitting.\n            If groups is not None, the `cv` argument passed to this class's initializer\n            must support a 'groups' argument to its split method.\n        cache_values: bool, default False\n            Whether to cache inputs and first stage results, which will allow refitting a different final model\n        inference: string,:class:`.Inference` instance, or None\n            Method for performing inference.  This estimator supports 'bootstrap'\n            (or an instance of :class:`.BootstrapInference`) and 'auto'\n            (or an instance of :class:`.LinearModelFinalInference`).\n\n        Returns\n        -------\n        self: DynamicDML instance\n        \"\"\"\n        if sample_weight is not None or sample_var is not None:\n            warn(\"This CATE estimator does not yet support sample weights and sample variance. \"\n                 \"These inputs will be ignored during fitting.\",\n                 UserWarning)\n        return super().fit(Y, T, X=X, W=W,\n                           sample_weight=None, sample_var=None, groups=groups,\n                           cache_values=cache_values,\n                           inference=inference)\n\n    def score(self, Y, T, X=None, W=None, sample_weight=None, *, groups):\n        \"\"\"\n        Score the fitted CATE model on a new data set. Generates nuisance parameters\n        for the new data set based on the fitted residual nuisance models created at fit time.\n        It uses the mean prediction of the models fitted by the different crossfit folds.\n        Then calculates the MSE of the final residual Y on residual T regression.\n\n        If model_final does not have a score method, then it raises an :exc:`.AttributeError`\n\n        Parameters\n        ----------\n        Y: (n, d_y) matrix or vector of length n\n            Outcomes for each sample (required: n = n_groups * n_periods)\n        T: (n, d_t) matrix or vector of length n\n            Treatments for each sample (required: n = n_groups * n_periods)\n        X: optional(n, d_x) matrix or None (Default=None)\n            Features for each sample (Required: n = n_groups * n_periods)\n        W: optional(n, d_w) matrix or None (Default=None)\n            Controls for each sample (Required: n = n_groups * n_periods)\n        groups: (n,) vector, required\n            All rows corresponding to the same group will be kept together during splitting.\n\n        Returns\n        -------\n        score: float\n            The MSE of the final CATE model on the new data.\n        \"\"\"\n        if not hasattr(self._ortho_learner_model_final, 'score'):\n            raise AttributeError(\"Final model does not have a score method!\")\n        Y, T, X, W, groups = check_input_arrays(Y, T, X, W, groups)\n        self._check_fitted_dims(X)\n        X, T = super()._expand_treatments(X, T)\n        n_iters = len(self._models_nuisance)\n        n_splits = len(self._models_nuisance[0])\n\n        # for each mc iteration\n        for i, models_nuisances in enumerate(self._models_nuisance):\n            # for each model under cross fit setting\n            for j, mdl in enumerate(models_nuisances):\n                nuisance_temp = mdl.predict(Y, T, **filter_none_kwargs(X=X, W=W, groups=groups))\n                if not isinstance(nuisance_temp, tuple):\n                    nuisance_temp = (nuisance_temp,)\n\n                if i == 0 and j == 0:\n                    nuisances = [np.zeros((n_iters * n_splits,) + nuis.shape) for nuis in nuisance_temp]\n\n                for it, nuis in enumerate(nuisance_temp):\n                    nuisances[it][i * n_iters + j] = nuis\n\n        for it in range(len(nuisances)):\n            nuisances[it] = np.mean(nuisances[it], axis=0)\n        return self._ortho_learner_model_final.score(Y, T, nuisances=nuisances,\n                                                     **filter_none_kwargs(X=X, W=W,\n                                                                          sample_weight=sample_weight, groups=groups))\n\n    def cate_treatment_names(self, treatment_names=None):\n        \"\"\"\n        Get treatment names for each time period.\n\n        If the treatment is discrete, it will return expanded treatment names.\n\n        Parameters\n        ----------\n        treatment_names: list of strings of length T.shape[1] or None\n            The names of the treatments. If None and the T passed to fit was a dataframe,\n            it defaults to the column names from the dataframe.\n\n        Returns\n        -------\n        out_treatment_names: list of strings\n            Returns (possibly expanded) treatment names.\n        \"\"\"\n        slice_treatment_names = super().cate_treatment_names(treatment_names)\n        treatment_names_out = []\n        for k in range(self._n_periods):\n            treatment_names_out += [f\"({t})$_{k}$\" for t in slice_treatment_names]\n        return treatment_names_out\n\n    def cate_feature_names(self, feature_names=None):\n        \"\"\"\n        Get the output feature names.\n\n        Parameters\n        ----------\n        feature_names: list of strings of length X.shape[1] or None\n            The names of the input features. If None and X is a dataframe, it defaults to the column names\n            from the dataframe.\n\n        Returns\n        -------\n        out_feature_names: list of strings or None\n            The names of the output features :math:`\\\\phi(X)`, i.e. the features with respect to which the\n            final constant marginal CATE model is linear. It is the names of the features that are associated\n            with each entry of the :meth:`coef_` parameter. Not available when the featurizer is not None and\n            does not have a method: `get_feature_names(feature_names)`. Otherwise None is returned.\n        \"\"\"\n        if self._d_x is None:\n            # Handles the corner case when X=None but featurizer might be not None\n            return None\n        if feature_names is None:\n            feature_names = self._input_names[\"feature_names\"]\n        if self.original_featurizer is None:\n            return feature_names\n        return get_feature_names_or_default(self.original_featurizer, feature_names)\n\n    def _expand_treatments(self, X, *Ts):\n        # Expand treatments for each time period\n        outTs = []\n        base_expand_treatments = super()._expand_treatments\n        for T in Ts:\n            if ndim(T) == 0:\n                one_T = base_expand_treatments(X, T)[1]\n                one_T = one_T.reshape(-1, 1) if ndim(one_T) == 1 else one_T\n                T = np.tile(one_T, (1, self._n_periods, ))\n            else:\n                assert (T.shape[1] == self._n_periods if self.transformer else T.shape[1] == self._d_t[0]), \\\n                    f\"Expected a list of time period * d_t, instead got a treatment array of shape {T.shape}.\"\n                if self.transformer:\n                    T = np.hstack([\n                        base_expand_treatments(\n                            X, T[:, [t]])[1] for t in range(self._n_periods)\n                    ])\n            outTs.append(T)\n        return (X,) + tuple(outTs)\n\n    @property\n    def bias_part_of_coef(self):\n        return self.ortho_learner_model_final_._model_final._fit_cate_intercept\n\n    @property\n    def fit_cate_intercept_(self):\n        return self.ortho_learner_model_final_._model_final._fit_cate_intercept\n\n    @property\n    def original_featurizer(self):\n        # NOTE: important to use the _ortho_learner_model_final_ attribute instead of the\n        #       attribute so that the trained featurizer will be passed through\n        return self.ortho_learner_model_final_._model_final_trained[0]._original_featurizer\n\n    @property\n    def featurizer_(self):\n        # NOTE This is used by the inference methods and has to be the overall featurizer. intended\n        # for internal use by the library\n        return self.ortho_learner_model_final_._model_final_trained[0]._featurizer\n\n    @property\n    def model_final_(self):\n        # NOTE This is used by the inference methods and is more for internal use to the library\n        #      We need to use the _ortho_learner's copy to retain the information from fitting\n        return self.ortho_learner_model_final_.model_final_\n\n    @property\n    def model_final(self):\n        return self._gen_model_final()\n\n    @model_final.setter\n    def model_final(self, model):\n        if model is not None:\n            raise ValueError(\"Parameter `model_final` cannot be altered for this estimator!\")\n\n    @property\n    def models_y(self):\n        return [[mdl._model_y for mdl in mdls] for mdls in super().models_nuisance_]\n\n    @property\n    def models_t(self):\n        return [[mdl._model_t for mdl in mdls] for mdls in super().models_nuisance_]\n\n    @property\n    def nuisance_scores_y(self):\n        return self.nuisance_scores_[0]\n\n    @property\n    def nuisance_scores_t(self):\n        return self.nuisance_scores_[1]\n\n    @property\n    def residuals_(self):\n        \"\"\"\n        A tuple (y_res, T_res, X, W), of the residuals from the first stage estimation\n        along with the associated X and W. Samples are not guaranteed to be in the same\n        order as the input order.\n        \"\"\"\n        if not hasattr(self, '_cached_values'):\n            raise AttributeError(\"Estimator is not fitted yet!\")\n        if self._cached_values is None:\n            raise AttributeError(\"`fit` was called with `cache_values=False`. \"\n                                 \"Set to `True` to enable residual storage.\")\n        Y_res, T_res = self._cached_values.nuisances\n        return Y_res, T_res, self._cached_values.X, self._cached_values.W\n", "meta": {"hexsha": "94605fd10b35907dc82167292303c695a97d7777", "size": 36308, "ext": "py", "lang": "Python", "max_stars_repo_path": "econml/dynamic/dml/_dml.py", "max_stars_repo_name": "imatiach-msft/EconML", "max_stars_repo_head_hexsha": "289c5412f4492035b794c2833e7f6f6f48807dd1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1846, "max_stars_repo_stars_event_min_datetime": "2019-05-06T21:14:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:52:21.000Z", "max_issues_repo_path": "econml/dynamic/dml/_dml.py", "max_issues_repo_name": "imatiach-msft/EconML", "max_issues_repo_head_hexsha": "289c5412f4492035b794c2833e7f6f6f48807dd1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 393, "max_issues_repo_issues_event_min_datetime": "2019-05-08T00:55:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:26:16.000Z", "max_forks_repo_path": "econml/dynamic/dml/_dml.py", "max_forks_repo_name": "imatiach-msft/EconML", "max_forks_repo_head_hexsha": "289c5412f4492035b794c2833e7f6f6f48807dd1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 414, "max_forks_repo_forks_event_min_datetime": "2019-05-14T03:51:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T09:32:17.000Z", "avg_line_length": 45.7856242119, "max_line_length": 118, "alphanum_fraction": 0.6103338107, "include": true, "reason": "import numpy,from scipy", "num_tokens": 8462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.18159080642804995}}
{"text": "#Standard python libraries\nimport os\nimport warnings\nimport copy\nimport time\nimport itertools\nimport functools\n\n#Dependencies - numpy, scipy, matplotlib, pyfftw\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pyfftw\nfrom pyfftw.interfaces.numpy_fft import fft, fftshift, ifft, ifftshift, fftfreq\nfrom scipy.interpolate import interp1d as sinterp1d\nimport scipy\nfrom scipy.sparse import save_npz, load_npz, eye, csr_matrix\nfrom scipy.sparse.linalg import eigs\n\nfrom ufss import DiagramGenerator\nfrom scipy.integrate import RK45\n\nclass RK_rho_container:\n    def __init__(self,t,rho,pulse_number,manifold_key,*,interp_kind='linear',\n                 optical_gap = 0):\n        self.pulse_number = pulse_number\n        self.n, self.M = rho.shape\n        self.manifold_key = manifold_key\n        self.optical_gap = optical_gap\n        if t.size == 1:\n            self.M = self.M+2\n            self.t = np.array([-1,0,1],dtype='float') * np.spacing(t[0]) + t[0]\n            rho_new = np.zeros((self.n,3),dtype='complex')\n            rho_new[:,0] = 0\n            rho_new[:,1] = 0.5 * rho[:,0]\n            rho_new[:,2] = rho[:,0]\n            self.rho = rho_new\n            \n            self.interp = self.make_interpolant(kind='zero')\n            \n        else:\n            self.t = t\n            self.rho = rho\n\n            self.interp = self.make_interpolant(kind=interp_kind)\n\n        self.t_checkpoint = t\n        self.rho_checkpoint = rho\n\n    def make_interpolant(self,*, kind='cubic'):\n        \"\"\"Interpolates density matrix\n\"\"\"\n        return sinterp1d(self.t,self.rho,fill_value = (0,np.nan),bounds_error = False,\n                         assume_sorted=True,kind=kind)\n\n    def one_time_step(self,rho0,t0,tf,*,find_best_starting_time = True):\n        if find_best_starting_time and tf < self.t_checkpoint[-1]:\n            diff1 = tf - t0\n\n            diff2 = tf - self.t[-1]\n\n            closest_t_checkpoint_ind = np.argmin(np.abs(self.t_checkpoint - tf))\n            closest_t_checkpoint = self.t_checkpoint[closest_t_checkpoint_ind]\n            diff3 = tf - closest_t_checkpoint\n\n            rho0s = [rho0,self.rho[:,-1],self.rho_checkpoint[:,closest_t_checkpoint_ind]]\n            \n            neighbor_ind = closest_t_checkpoint_ind - 1\n            if neighbor_ind >= 0:\n                neighbor = self.t_checkpoint[closest_t_checkpoint_ind-1]\n                diff4 = tf - neighbor\n                rho0s.append(self.rho_checkpoint[:,neighbor_ind])\n            else:\n                neighbor = np.nan\n                diff4 = np.inf\n                \n\n            t0s = np.array([t0,self.t[-1],closest_t_checkpoint,neighbor])\n            diffs = np.array([diff1,diff2,diff3,diff4])\n            \n            for i in range(diffs.size):\n                if diffs[i] < 0:\n                    diffs[i] = np.inf\n            \n            if np.allclose(diffs,np.inf):\n                raise ValueError('Method extend is only valid for times after the pulse has ended')\n            \n            t0 = t0s[np.argmin(diffs)]\n            rho0 = rho0s[np.argmin(diffs)]\n            \n        elif find_best_starting_time and tf > self.t_checkpoint[-1]:\n            if self.t_checkpoint[-1] > t0:\n                t0 = self.t_checkpoint[-1]\n                rho0 = self.rho_checkpoint[:,-1]\n            else:\n                pass\n            \n        else:\n            pass\n        # RWA_gap = self.manifold.dot(np.array([1,-1])) * self.optical_gap\n        return self.one_time_step_function(rho0,t0,tf,manifold_key=self.manifold_key)#,RWA_gap = RWA_gap)\n\n    def extend(self,t):\n        ans = np.zeros((self.n,t.size),dtype='complex')\n        \n        if t[0] >= self.t_checkpoint[0]:\n\n            t_intersect, t_inds, t_checkpoint_inds = np.intersect1d(t,self.t_checkpoint,return_indices=True)\n\n            ans[:,t_inds] = self.rho_checkpoint[:,t_checkpoint_inds]\n\n            if t_inds.size == t.size:\n                return ans\n            else:\n                all_t_inds = np.arange(t.size)\n                other_t_inds = np.setdiff1d(all_t_inds,t_inds)\n                t0 = self.t_checkpoint[-1]\n                rho0 = self.rho_checkpoint[:,-1]\n                if t[other_t_inds[0]] >= t0:\n                    find_best_starting_time = False\n                else:\n                    find_best_starting_time = True\n                for t_ind in other_t_inds:\n                    tf = t[t_ind]\n                    ans[:,t_ind] = self.one_time_step(rho0,t0,tf,find_best_starting_time = find_best_starting_time)\n                    t0 = tf\n                    rho0 = ans[:,t_ind]\n            \n        elif t[0] >= self.t[-1]:\n            t0 = self.t[-1]\n            rho0 = self.rho[:,-1]\n            for i in range(len(t)):\n                ans[:,i] = self.one_time_step(rho0,t0,t[i],find_best_starting_time = True)\n                t0 = t[i]\n                rho0 = ans[:,i]\n        else:\n            raise ValueError('Method extend is only valid for times after the pulse has ended')\n\n        self.rho_checkpoint = ans\n        self.t_checkpoint = t\n        return ans\n\n    def __call__(self,t):\n        \"\"\"Assumes t is sorted \"\"\"\n        if type(t) is np.ndarray:\n            pass\n        elif type(t) is list:\n            t = np.array(t)\n        else:\n            t = np.array([t])\n        extend_inds = np.where(t>self.t[-1])\n        interp_inds = np.where(t<=self.t[-1])\n        ta = t[interp_inds]\n        tb = t[extend_inds]\n        if ta.size > 0:\n            ans_a_flag = True\n            if ta.size == self.M and np.allclose(ta,self.t):\n                ans_a = self.rho\n            else:\n                ans_a = self.interp(ta)\n        else:\n            ans_a_flag = False\n        if tb.size > 0:\n            ans_b = self.extend(tb)\n            ans_b_flag = True\n        else:\n            ans_b_flag = False\n            \n        if ans_a_flag and ans_b_flag:\n            ans = np.hstack((ans_a,ans_b))\n        elif ans_a_flag:\n            ans = ans_a\n        elif ans_b_flag:\n            ans = ans_b\n        else:\n            ans = None\n        return ans\n\n    def __getitem__(self,inds):\n        return self.rho[:,inds]\n\nclass RKE_DensityMatrices(DiagramGenerator):\n    \"\"\"This class is designed to calculate perturbative wavepackets in the\n        light-matter interaction given the eigenvalues of the unperturbed \n        hamiltonian and the material dipole operator evaluated in the\n        eigenbasis of the unperturbed hamiltonian.\n\n    Args:\n        file_path (string): path to folder containing eigenvalues and the\n            dipole operator for the system Hamiltonian\n        detection_type (string): options are 'polarization' (default) or 'fluorescence'\n\n\"\"\"\n    def __init__(self,file_path,*,detection_type = 'polarization',\n                 conserve_memory=False):\n        self.slicing_time = 0\n        self.interpolation_time = 0\n        self.expectation_time = 0\n        self.RK45_step_time = 0\n        self.dipole_dot_rho_time = 0\n        self.dipole_time = 0\n        self.automation_time = 0\n        self.diagram_to_signal_time = 0\n        \n        self.base_path = file_path\n\n        self.undersample_factor = 1\n\n        self.gamma_res = 6.91\n\n        self.sparsity_threshold = 0.1\n\n        self.conserve_memory = conserve_memory\n\n        self.load_L()\n\n        self.set_rho_shapes()\n\n        if not self.conserve_memory:\n            self.load_mu()\n\n        try:\n            self.load_H_mu()\n            # more efficient if H_mu is available\n            self.dipole_down = self.dipole_down_H_mu\n\n        except:\n            # generally less efficient - mostly here for backwards compatibility\n            self.dipole_down = self.dipole_down_L_mu\n\n        self.optical_gap = 0\n\n        self.atol = 1E-6\n        self.rtol = 1E-5\n\n        if detection_type == 'polarization':\n            self.rho_to_signal = self.polarization_detection_rho_to_signal\n            self.return_complex_signal = False\n            \n        elif detection_type == 'complex_polarization':\n            self.rho_to_signal = self.polarization_detection_rho_to_signal\n            self.return_complex_signal = True\n            detection_type = 'polarization'\n            \n        elif detection_type == 'integrated_polarization':\n            raise Exception('detection_type: Integrated polarization is not implemented for Open RKE')\n            self.rho_to_signal = self.integrated_polarization_detection_rho_to_signal\n            \n        elif detection_type == 'fluorescence':\n            self.rho_to_signal = self.fluorescence_detection_rho_to_signal\n\n        DiagramGenerator.__init__(self,detection_type=detection_type)\n        self.KB_dict = {'Bu':self.bra_up,'Ku':self.ket_up,'Kd':self.ket_down,'Bd':self.bra_down}\n\n        # Code will not actually function until the following three empty lists are set by the user\n        self.efields = [] #initialize empty list of electric field shapes\n        self.efield_times = [] #initialize empty list of times assoicated with each electric field shape\n        self.dts = [] #initialize empty list of time spacings associated with each electric field shape\n        self.polarization_sequence = [] #initialize empty polarization sequence\n        self.pulse_times = [] #initialize empty list of pulse arrival times\n        self.centers = [] #initialize empty list of pulse center frequencies\n        self.efield_wavevectors = []\n        self.rhos = dict()\n        \n        # Initialize unperturbed wavefunction\n        self.set_rho0_auto()\n\n    def set_pulse_delays(self,all_delays):\n        \"\"\"Must be a list of numpy arrays, where each array is a\n            list of delay times between pulses\n\"\"\"\n        self.all_pulse_delays = all_delays\n        num_delays = len(self.all_pulse_delays)\n        num_pulses = len(self.efields)\n        \n        if num_delays == num_pulses - 1:\n            pass\n        elif num_delays == num_pulses - 2 and self.detection_type == 'polarization':\n            # If there is a local oscillator, it arrives simultaneously with the last pulse\n            self.all_pulse_delays.append(np.array([0]))\n        elif num_delays <= num_pulses -2:\n            raise Exception('There are not enough delay times')\n        elif num_delays >= num_pulses:\n            raise Exception('There are too many delay times')\n\n    def calculate_diagrams_all_delays(self,diagrams):\n        t0 = time.time()\n        num_delays = len(self.all_pulse_delays)\n        num_pulses = len(self.efields)\n\n        all_delay_combinations = list(itertools.product(*self.all_pulse_delays))\n        \n        signal_shape = [delays.size for delays in self.all_pulse_delays]\n        if self.detection_type == 'polarization':\n            signal = np.zeros((len(all_delay_combinations),self.w.size),dtype='complex')\n            if len(signal_shape) == self.pdc.shape[0]:\n                # get rid of the \"delay\" between the last pulse and the local oscillator\n                signal_shape[-1] = self.w.size\n            elif len(signal_shape) == self.pdc.shape[0] - 1:\n                # append the shape of the polariation-detection axis\n                signal_shape.append(self.w.size)\n            else:\n                raise Exception('Cannot automatically determine final signal shape')\n        else:\n            signal = np.zeros((len(all_delay_combinations)),dtype='complex')\n\n        counter = 0\n        for delays in all_delay_combinations:\n            arrival_times = [0]\n            for delay in delays:\n                arrival_times.append(arrival_times[-1]+delay)\n\n            if self.detection_type == 'polarization':\n                signal[counter,:] = self.calculate_diagrams(diagrams,arrival_times)\n            else:\n                signal[counter] = self.calculate_diagrams(diagrams,arrival_times)\n            counter += 1\n\n        self.signal = signal.reshape(signal_shape)\n        self.calculation_time = time.time() - t0\n        \n        return self.signal\n\n    def save_timing(self):\n        save_dict = {'RKE_calculation_time':self.calculation_time}\n        np.savez(os.path.join(self.base_path,'RKE_calculation_time.npz'),**save_dict)\n        \n    def calculate_signal_all_delays(self):\n        t0 = time.time()\n        num_delays = len(self.all_pulse_delays)\n        num_pulses = len(self.efields)\n\n        all_delay_combinations = list(itertools.product(*self.all_pulse_delays))\n        \n        signal_shape = [delays.size for delays in self.all_pulse_delays]\n        if self.detection_type == 'polarization':\n            signal = np.zeros((len(all_delay_combinations),self.w.size),dtype='complex')\n            if len(signal_shape) == self.pdc.shape[0]:\n                # get rid of the \"delay\" between the last pulse and the local oscillator\n                signal_shape[-1] = self.w.size\n            elif len(signal_shape) == self.pdc.shape[0] - 1:\n                # append the shape of the polariation-detection axis\n                signal_shape.append(self.w.size)\n            else:\n                raise Exception('Cannot automatically determine final signal shape')\n        else:\n            signal = np.zeros((len(all_delay_combinations)),dtype='complex')\n\n        counter = 0\n        for delays in all_delay_combinations:\n            arrival_times = [0]\n            for delay in delays:\n                arrival_times.append(arrival_times[-1]+delay)\n\n            if self.detection_type == 'polarization':\n                signal[counter,:] = self.calculate_signal(arrival_times)\n            else:\n                signal[counter] = self.calculate_signal(arrival_times)\n            counter += 1\n\n        self.signal = signal.reshape(signal_shape)\n        self.calculation_time = time.time() - t0\n        return self.signal\n\n    def set_t(self,optical_dephasing_rate,*,dt='auto'):\n        \"\"\"Sets the time grid upon which all frequency-detected signals will\nbe calculated on\n\"\"\"\n        max_pos_t = int(self.gamma_res/optical_dephasing_rate)\n        if dt == 'auto':\n            dt = self.dts[-1] # signal detection bandwidth determined by local oscillator\n        self.t = np.arange(-max_pos_t,max_pos_t+dt/2,dt)\n        # if self.t.size % 2:\n        #     self.t = self.t[:-1]\n        self.w = fftshift(fftfreq(self.t.size,d=dt)*2*np.pi)\n\n    def execute_diagram(self,instructions):\n        r = self.rho0\n        name = ''\n        for i in range(len(instructions)):\n            key, num = instructions[i]\n            name += key+str(num)\n            # Try to re-use previous calculations, if they exist\n            try:\n                new_r = self.rhos[name]\n            except KeyError:\n                new_r = self.KB_dict[key](r,pulse_number=num)\n                self.rhos[name] = new_r\n            r = new_r\n        sig = self.rho_to_signal(r)\n        return sig\n\n    def remove_rhos_by_pulse_number(self,pulse_number):\n        num = str(pulse_number)\n        keys = self.rhos.keys()\n        keys_to_remove = []\n        for key in keys:\n            flag = key.find(num)\n            if flag >= 0:\n                keys_to_remove.append(key)\n        for key in keys_to_remove:\n            self.rhos.pop(key)\n\n    def calculate_signal(self,arrival_times):\n        t0 = time.time()\n        try:\n            old_pulse_times = self.pulse_times\n            for i in range(len(old_pulse_times)):\n                if old_pulse_times[i] != arrival_times[i]:\n                    self.remove_rhos_by_pulse_number(i)\n        except AttributeError:\n            pass\n        \n        self.pulse_times = arrival_times\n        if self.detection_type == 'polarization':\n            times = [self.efield_times[i] + arrival_times[i] for i in range(len(arrival_times)-1)]\n        elif self.detection_type == 'integrated_polarization':\n            times = [self.efield_times[i] + arrival_times[i] for i in range(len(arrival_times)-1)]\n        elif self.detection_type == 'fluorescence':\n            times = [self.efield_times[i] + arrival_times[i] for i in range(len(arrival_times))]\n        \n        efield_permutations = self.relevant_permutations(times)\n        \n        diagram_instructions = []\n        for perm in efield_permutations:\n            diagram_instructions += self.instructions_from_permutation(perm)\n        self.current_instructions = diagram_instructions\n\n        t1 = time.time()\n        try:\n            instructions = diagram_instructions[0]\n            signal = self.execute_diagram(instructions)\n            for instructions in diagram_instructions[1:]:\n                signal += self.execute_diagram(instructions)\n        except IndexError:\n            signal = 0\n\n        t2 = time.time()\n        self.automation_time += t1-t0\n        self.diagram_to_signal_time += t2-t1\n        return signal\n\n    def calculate_diagrams(self,diagram_instructions,arrival_times):\n        try:\n            old_pulse_times = self.pulse_times\n            for i in range(len(old_pulse_times)):\n                if old_pulse_times[i] != arrival_times[i]:\n                    self.remove_rhos_by_pulse_number(i)\n        except AttributeError:\n            pass\n        \n        self.pulse_times = arrival_times\n            \n        self.current_instructions = diagram_instructions\n        instructions = diagram_instructions[0]\n        signal = self.execute_diagram(instructions)\n        for instructions in diagram_instructions[1:]:\n            signal += self.execute_diagram(instructions)\n        return signal\n\n    def polarization_detection_rho_to_signal(self,rho):    \n        p_of_t = self.dipole_expectation(rho,pulse_number=-1,ket_flag=True)\n        return self.polarization_to_signal(p_of_t,local_oscillator_number=-1)\n\n    def integrated_polarization_detection_rho_to_signal(self,rho):    \n        p = self.integrated_dipole_expectation(rho,ket_flag=True)\n        return self.integrated_polarization_to_signal(p,local_oscillator_number=-1)\n\n    # def fluorescence_detection_rho_to_signal(self,rho):\n    #     L_size = self.eigenvalues[0].size\n    #     H_size = int(np.sqrt(L_size))\n\n    #     # reshape rho into a normal density matrix representation\n    #     rho = rho.reshape((H_size,H_size))\n\n    #     fluorescence_yield = np.array([0,1,1,self.f_yield])\n\n    #     signal = np.dot(np.diagonal(rho),fluorescence_yield)\n        \n    #     return signal\n\n    def set_efields(self,times_list,efields_list,centers_list,phase_discrimination,*,reset_rhos = True,\n                    plot_fields = False):\n        self.efield_times = times_list\n        self.efields = efields_list\n        self.centers = centers_list\n        self.set_phase_discrimination(phase_discrimination)\n        self.dts = []\n        self.efield_frequencies = []\n        if reset_rhos:\n            self.rhos = dict()\n        for t in times_list:\n            if t.size == 1:\n                dt = 1\n                w = np.array([0])\n            else:\n                dt = t[1] - t[0]\n                w = fftshift(fftfreq(t.size,d=dt))*2*np.pi\n            self.dts.append(dt)\n            self.efield_frequencies.append(w)\n\n        self.dt = self.dts[0]\n\n        if self.detection_type == 'polarization':\n            try:\n                self.local_oscillator = self.efields[-1].copy()\n            except:\n                self.local_oscillator = copy.deepcopy(self.efields[-1])\n\n        for field in self.efields:\n            if len(field) == 1:\n                # M = 1 is the impulsive limit\n                pass\n            else:\n                self.check_efield_resolution(field,plot_fields = plot_fields)\n\n    def check_efield_resolution(self,efield,*,plot_fields = False):\n        efield_tail = np.max(np.abs([efield[0],efield[-1]]))\n\n\n        if efield_tail > np.max(np.abs(efield))/100:\n            warnings.warn('Consider using larger num_conv_points, pump does not decay to less than 1% of maximum value in time domain')\n            \n        efield_fft = fftshift(fft(ifftshift(efield)))*self.dt\n        efield_fft_tail = np.max(np.abs([efield_fft[0],efield_fft[-1]]))\n        \n        if efield_fft_tail > np.max(np.abs(efield_fft))/100:\n            warnings.warn('''Consider using smaller value of dt, pump does not decay to less than 1% of maximum value in frequency domain''')\n\n        if plot_fields:\n            fig, axes = plt.subplots(1,2)\n            l1,l2, = axes[0].plot(self.efield_t,np.real(efield),self.efield_t,np.imag(efield))\n            plt.legend([l1,l2],['Real','Imag'])\n            axes[1].plot(self.efield_w,np.real(efield_fft),self.efield_w,np.imag(efield_fft))\n\n            axes[0].set_ylabel('Electric field Amp')\n            axes[0].set_xlabel('Time ($\\omega_0^{-1})$')\n            axes[1].set_xlabel('Frequency ($\\omega_0$)')\n\n            fig.suptitle('Check that efield is well-resolved in time and frequency')\n            plt.show()\n\n    def set_local_oscillator_phase(self,phase):\n        self.efields[-1] = np.exp(1j*phase) * self.local_oscillator\n\n    def get_closest_index_and_value(self,value,array):\n        \"\"\"Given an array and a desired value, finds the closest actual value\nstored in that array, and returns that value, along with its corresponding \narray index\n\"\"\"\n        index = np.argmin(np.abs(array - value))\n        value = array[index]\n        return index, value\n\n    def load_L(self):\n        \"\"\"Load in known eigenvalues. Must be stored as a numpy archive file,\nwith keys: GSM, SEM, and optionally DEM.  The eigenvalues for each manifold\nmust be 1d arrays, and are assumed to be ordered by increasing energy. The\nenergy difference between the lowest energy ground state and the lowest \nenergy singly-excited state should be set to 0\n\"\"\"\n        L_save_name = os.path.join(self.base_path,'L.npz')\n        try:\n            with np.load(L_save_name,allow_pickle=True) as L_archive:\n                self.L = dict()\n                for key in L_archive.keys():\n                    L = L_archive[key]\n                    if L.dtype == np.dtype('O'):\n                        self.L[key] = L[()]\n                    else:\n                        if self.check_sparsity(L):\n                            self.L[key] = csr_matrix(L)\n                        else:\n                            self.L[key] = L\n        except:\n            self.L = {'all_manifolds':load_npz(L_save_name)}\n        self.manifolds = list(self.L.keys())\n\n    def check_sparsity(self,mat):\n        csr_mat = csr_matrix(mat)\n        sparsity = csr_mat.nnz / (csr_mat.shape[0]*csr_mat.shape[1])\n        if sparsity < self.sparsity_threshold:\n            return True\n        else:\n            return False\n        \n    def dL(self,t,rho):\n        try:\n            L = self.L['all_manifolds']\n        except KeyError:\n            L = self.L[rho.manifold_key]\n        return L.dot(rho)\n\n    def get_dL_manual(self,manifold_key):\n        try:\n            L = self.L['all_manifolds']\n        except KeyError:\n            L = self.L[manifold_key]\n\n        def L_fun(t,rho):\n            return L.dot(rho)\n\n        return L_fun\n\n    def one_time_step_function(self,rho0,t0,tf,*,manifold_key = None):\n        num_steps = 0\n        if manifold_key == None:\n            rk45 = RK45(self.dL,t0,rho0,tf,atol=self.atol,rtol=self.rtol)\n        else:\n            dL = self.get_dL_manual(manifold_key)\n            rk45 = RK45(dL,t0,rho0,tf,atol=self.atol,rtol=self.rtol)\n        while rk45.t < tf:\n            rk45.step()\n            num_steps += 1\n        rho_final = rk45.y\n        return rho_final\n\n    def get_bottom_eigenvector(self):\n        try:\n            L = self.L['all_manifolds']\n        except KeyError:\n            L = self.L['00']\n        if L.shape == (1,1):\n            e = L[0,0]\n            ev = np.array([[1]])\n        else:\n            e, ev = eigs(L,k=1,which='SM',maxiter=10000)\n        if e.size == 1 and np.allclose(e,0):\n            pass\n        else:\n            raise Exception('Smallest magnitude eigenvalue of L is {}. L must have a single stationary state for this code to work'.format(e))\n        v = ev[:,0]\n        H_size = int(np.sqrt(v.size))\n        rho = v.reshape((H_size,H_size))\n        trace = rho.trace()\n        v = v/trace # Need to start with a trace 1 object\n        return v\n\n    def set_rho0_auto(self):\n        try:\n            rho0 = np.load(os.path.join(self.base_path,'rho0.npy'))\n        except FileNotFoundError:\n            rho0 = self.get_bottom_eigenvector()\n        t = np.array([-np.inf,0,np.inf])\n        rho0 = rho0[:,np.newaxis] * np.ones((rho0.size,t.size))\n        pulse_number = None\n        manifold_key = '00'\n        self.rho0 = RK_rho_container(t,rho0,pulse_number,manifold_key,\n                                     interp_kind = 'zero',optical_gap = self.optical_gap)\n\n    def set_rho_shapes(self):\n        self.rho_shapes = dict()\n        if 'all_manifolds' in self.manifolds:\n            L_size = self.L['all_manifolds'].size\n            H_size = int(np.sqrt(L_size))\n            self.rho_shapes['all_manifolds'] = (H_size,H_size)\n        else:\n            H_sizes = dict()\n            for key in self.manifolds:\n                ket_key, bra_key = key\n                if ket_key == bra_key:\n                    L_size = self.L[key].shape[0]\n                    H_size = int(np.sqrt(L_size))\n                    H_sizes[ket_key] = H_size\n            for key in self.manifolds:\n                ket_key, bra_key = key\n                ket_size = H_sizes[ket_key]\n                bra_size = H_sizes[bra_key]\n                self.rho_shapes[key] = (ket_size,bra_size)\n\n    def load_mu(self):\n        \"\"\"Load the precalculated dipole overlaps.  The dipole operator must\n            be stored as a .npz file, and must contain at least one array, each with three \n            indices: (new manifold index, old manifold eigenfunction, \n            cartesian coordinate).\"\"\"\n        try:\n            file_name = os.path.join(self.base_path,'mu_site_basis.npz')\n            with np.load(file_name) as mu_archive:\n                self.mu = {key:mu_archive[key] for key in mu_archive.keys()}\n        except FileNotFoundError:\n            try:\n                file_name = os.path.join(self.base_path,'mu_original_L_basis.npz')\n                with np.load(file_name) as mu_archive:\n                    self.mu = {key:mu_archive[key] for key in mu_archive.keys()}\n            except FileNotFoundError:\n                file_name = os.path.join(self.base_path,'mu.npz')\n                with np.load(file_name) as mu_archive:\n                    self.mu = {key:mu_archive[key] for key in mu_archive.keys()}\n        sparse_flags = []\n        for key in self.mu.keys():\n            mu_2D = np.sum(np.abs(self.mu[key])**2,axis=-1)\n            sparse_flags.append(self.check_sparsity(mu_2D))\n        sparse_flags = np.array(sparse_flags)\n        if np.allclose(sparse_flags,True):\n            self.sparse_mu_flag = True\n        else:\n            self.sparse_mu_flag = False\n\n        for key in self.mu.keys():\n            mu_x = self.mu[key][...,0]\n            mu_y = self.mu[key][...,1]\n            mu_z = self.mu[key][...,2]\n\n            if self.sparse_mu_flag:\n                self.mu[key] = [csr_matrix(mu_x),csr_matrix(mu_y),csr_matrix(mu_z)]\n            else:\n                self.mu[key] = [mu_x,mu_y,mu_z]\n\n        print('RKE_sparse_mu_flag',self.sparse_mu_flag)\n        \n    ### Setting the electric field to be used\n\n    def set_polarization_sequence(self,polarization_list,*,reset_rhos=True):\n        \"\"\"Sets the sequences used for either parallel or crossed pump and probe\n        \n        Args:\n            polarization_list (list): list of four strings, can be 'x','y' or 'z'\n        Returns:\n            None: sets the attribute polarization sequence\n\"\"\"\n\n        x = np.array([1,0,0])\n        y = np.array([0,1,0])\n        z = np.array([0,0,1])\n        pol_options = {'x':x,'y':y,'z':z}\n\n        self.polarization_sequence = [pol_options[pol] for pol in polarization_list]\n\n        if reset_rhos:\n            self.rhos = dict()\n\n\n    ### Tools for recursively calculating perturbed density maatrices using TDPT\n\n    def dipole_matrix(self,pulse_number,key,ket_flag=True,up_flag=True):\n        \"\"\"Calculates the dipole matrix given the electric field polarization vector,\n            if ket_flag = False then uses the bra-interaction\"\"\"\n        t0 = time.time()\n        pol = self.polarization_sequence[pulse_number]\n\n        x = np.array([1,0,0])\n        y = np.array([0,1,0])\n        z = np.array([0,0,1])\n        try:\n            mu = self.mu[key]\n        except KeyError:\n            if ket_flag:\n                key = 'ket'\n            else:\n                key = 'bra'\n            if up_flag:\n                key += '_up'\n            else:\n                key += '_down'\n            mu = self.mu[key]\n            \n        if np.all(pol == x):\n            overlap_matrix = mu[0]#.copy()\n        elif np.all(pol == y):\n            overlap_matrix = mu[1]#.copy()\n        elif np.all(pol == z):\n            overlap_matrix = mu[2]#.copy()\n        else:\n            overlap_matrix = mu[0]*pol[0] + mu[1]*pol[1] + mu[2]*pol[2]\n\n        # if self.sparse_mu_flag:\n        #     to_return = csr_matrix(overlap_matrix)\n        # else:\n        #     to_return = overlap_matrix\n\n        t1 = time.time()\n        self.dipole_time += t1-t0\n\n        return overlap_matrix\n\n    def manifold_key_to_array(self,key):\n        \"\"\"Key must be a string of exactly 2 integers, the first describing\n            the ket manifold, the second the bra manifold.  If the density \n            matrix is represented in the full space, rather than being divided\n            into manifolds, the first integer reperesents the total number of\n            excitations to the ket side, and the second integers represents \n            the sum of all excitations to the bra side.\"\"\"\n        if len(key) != 2:\n            raise Exception('manifold key must be a string of exactly two intgers')\n        return np.array([int(char) for char in key],dtype=int)\n    \n    def manifold_array_to_key(self,manifold):\n        \"\"\"Inverse of self.manifold_key_to_array\"\"\"\n        if manifold.size != 2 or manifold.dtype != int:\n            raise Exception('manifold array must contain exactly 2 integer') \n        return str(manifold[0]) + str(manifold[1])\n\n    def next_order(self,rho_in,*,ket_flag=True,up_flag=True,pulse_number = 0):\n        \"\"\"This function connects psi_p to psi+pj^(*) using the Euler Method.\n\n        Args:\n            rho_in (rho_container): input density matrix\n            pulse_number (int): index of optical pulse (0,1,2,...)\n        \n        Return:\n            rho_dict (rho_container): next-order density matrix\n\"\"\"     \n        pulse_time = self.pulse_times[pulse_number]\n        t = self.efield_times[pulse_number] + pulse_time\n        old_manifold_key = rho_in.manifold_key\n        if up_flag:\n            change = 1\n        else:\n            change = -1\n        if ket_flag:\n            manifold_change = np.array([change,0],dtype=int)\n        else:\n            manifold_change = np.array([0,change],dtype=int)\n        old_manifold = self.manifold_key_to_array(old_manifold_key)\n        new_manifold = old_manifold + manifold_change\n        new_manifold_key = self.manifold_array_to_key(new_manifold)\n        mu_key = old_manifold_key + '_to_' + new_manifold_key\n        \n        if ket_flag == up_flag:\n            # Rotating term excites the ket and de-excites the bra\n            conjugate_flag = False\n        else:\n            # Counter-rotating term\n            conjugate_flag = True\n\n        if conjugate_flag:\n            center = -self.centers[pulse_number]\n        else:\n            center = self.centers[pulse_number]\n\n        M = t.size\n        old_rho = rho_in(t)\n\n        if self.conserve_memory:\n            # move back to the basis the Liouvillian was written in\n            if 'all_manifolds' in self.manifolds:\n                ket_size,bra_size = self.rho_shapes['all_manifolds']\n            else:\n                ket_size,bra_size = self.rho_shapes[old_manifold_key]\n                \n            old_rho = old_rho.reshape(ket_size,bra_size,M)\n\n            if ket_flag:\n                old_ket_key = old_manifold_key[0]\n                new_ket_key = new_manifold_key[0]\n                if up_flag:\n                    H_mu_key = old_ket_key + '_to_' + new_ket_key\n                else:\n                    H_mu_key = new_ket_key + '_to_' + old_ket_key\n\n                mu_up_flag = up_flag\n            else:\n                old_bra_key = old_manifold_key[1]\n                new_bra_key = new_manifold_key[1]\n                if up_flag:\n                    H_mu_key = old_bra_key + '_to_' + new_bra_key\n                else:\n                    H_mu_key = new_bra_key + '_to_' + old_bra_key\n                mu_up_flag = not up_flag\n\n            overlap_matrix = self.get_H_mu(pulse_number,H_mu_key,up_flag=mu_up_flag)\n            \n            ta = time.time()\n            if ket_flag:\n                mu_old_rho = np.einsum('ij,jkl',overlap_matrix,old_rho)\n            else:\n                mu_old_rho = np.einsum('ijl,jk',old_rho,overlap_matrix)\n            tb = time.time()\n            \n            rho_vec_size = mu_old_rho.shape[0]*mu_old_rho.shape[1]\n            mu_old_rho = mu_old_rho.reshape(rho_vec_size,M)\n\n        else:\n            overlap_matrix = self.dipole_matrix(pulse_number,mu_key,ket_flag=ket_flag,up_flag=up_flag)\n        \n        \n            ta = time.time()\n            mu_old_rho = overlap_matrix.dot(old_rho)\n            tb = time.time()\n            \n        self.dipole_dot_rho_time += tb - ta\n        next_rho = np.zeros(mu_old_rho.shape,dtype='complex')\n\n        if M == 1:\n            next_rho[:,0] = self.efields[pulse_number] * mu_old_rho\n        else:\n            if conjugate_flag:\n                efield = self.efields[pulse_number]*np.exp(-1j*center*t)\n            else:\n                efield = np.conjugate(self.efields[pulse_number])*np.exp(-1j*center*t)\n\n\n            ############\n            # This 1j vs -1j needs to be derived!!! #####\n            ############\n            if ket_flag:\n                efield = 1j * efield\n            else:\n                efield = -1j * efield\n            ###########\n            ###########\n            \n            dt = self.dts[pulse_number]\n            next_rho[:,0] = efield[0] * mu_old_rho[:,0] * dt\n            for i in range(1,t.size):\n                rho0 = next_rho[:,i-1]\n                t0 = t[i-1]\n                ta = time.time()\n                next_rho[:,i] = self.one_time_step_function(rho0,t0,t[i],manifold_key=new_manifold_key)\n\n                tb = time.time()\n                self.RK45_step_time += tb - ta\n        \n                next_rho[:,i] += efield[i] * mu_old_rho[:,i] * dt\n\n        # # i/hbar Straight from perturbation theory\n        # if ket_flag:\n        #     rho *= 1j\n        # else:\n        #     rho *= -1j\n\n        rho_out = RK_rho_container(t,next_rho,pulse_number,new_manifold_key,\n                                   optical_gap = self.optical_gap)\n        rho_out.one_time_step_function = self.one_time_step_function\n    \n        return rho_out\n            \n    def ket_up(self,rho_in,*,pulse_number = 0):\n        \"\"\"This method connects psi_p to psi_pj where the next order psi\n            is one manifold above the current manifold.\n\n        Args:\n            rho_in (rho_container): input density matrix\n            pulse_number (int): index of optical pulse (0,1,2,...)\n\n        Returns:\n            (rho_container): output from method next_order\n\"\"\"\n        return self.next_order(rho_in,ket_flag=True,up_flag=True,\n                               pulse_number = pulse_number)\n\n    def ket_down(self,rho_in,*,pulse_number = 0):\n        \"\"\"This method connects psi_p to psi_pj where the next order psi\n            is one manifold above the current manifold.\n\n        Args:\n            rho_in (rho_container): input density matrix\n            pulse_number (int): index of optical pulse (0,1,2,...)\n\n        Returns:\n            (rho_container): output from method next_order\n\"\"\"\n        return self.next_order(rho_in,ket_flag=True,up_flag=False,\n                               pulse_number = pulse_number)\n\n    def bra_up(self,rho_in,*,pulse_number = 0):\n        \"\"\"This method connects psi_p to psi_pj where the next order psi\n            is one manifold above the current manifold.\n\n        Args:\n            rho_in (rho_container): input density matrix\n            pulse_number (int): index of optical pulse (0,1,2,...)\n\n        Returns:\n            (rho_container): output from method next_order\n\"\"\"\n        return self.next_order(rho_in,ket_flag=False,up_flag=True,\n                               pulse_number = pulse_number)\n\n    def bra_down(self,rho_in,*,pulse_number = 0):\n        \"\"\"This method connects psi_p to psi_pj where the next order psi\n            is one manifold above the current manifold.\n\n        Args:\n            rho_in (rho_container): input density matrix\n            pulse_number (int): index of optical pulse (0,1,2,...)\n\n        Returns:\n            (rho_container): output from method next_order\n\"\"\"\n        return self.next_order(rho_in,ket_flag=False,up_flag=False,\n                               pulse_number = pulse_number)\n\n    ### Tools for taking the expectation value of the dipole operator with perturbed density matrices\n\n    def dipole_down_H_mu(self,rho,manifold_key,*,new_manifold_mask = None,pulse_number = -1,\n                    ket_flag=True):\n        \"\"\"This method is similar to the method down, but does not involve \n            the electric field shape or convolutions. It is the action of the \n            dipole operator on the ket-side without TDPT effects.  It also includes\n            the dot product of the final electric field polarization vector.\"\"\"\n        \n        if not ket_flag:\n            raise Exception('Not implemented for bra-side')\n        old_manifold_key = manifold_key\n        old_ket_key = old_manifold_key[0]\n        new_ket_key = str(int(old_ket_key)-1)\n        mu_key = new_ket_key + '_to_' + old_ket_key\n\n        if ket_flag:\n            center = - self.centers[pulse_number]\n            conjugate_flag = True\n        else:\n            center = self.centers[pulse_number]\n            conjugate_flag = False\n\n        t_size = rho.shape[-1]\n        \n        if 'all_manifolds' in self.L.keys():\n            L_size = rho.size\n            H_size = int(np.sqrt(L_size))\n            rho = rho.reshape(H_size,H_size,t_size)\n        else:\n            ket_manifold_key = old_manifold_key[0] + old_manifold_key[0]\n            ket_L_manifold_size = self.L[ket_manifold_key].shape[0]\n            ket_H_size = int(np.sqrt(ket_L_manifold_size))\n\n            bra_manifold_key = old_manifold_key[1] + old_manifold_key[1]\n            bra_L_manifold_size = self.L[bra_manifold_key].shape[0]\n            bra_H_size = int(np.sqrt(bra_L_manifold_size))\n\n            rho = rho.reshape(ket_H_size,bra_H_size,t_size)\n        \n        overlap_matrix = self.get_H_mu(pulse_number,mu_key,ket_flag=ket_flag,up_flag=False)\n\n        t0 = time.time()\n        polarization_field = np.einsum('ij,jik',overlap_matrix,rho)\n                \n        t1 = time.time()\n\n        return polarization_field\n\n    def dipole_down_L_mu(self,rho,manifold_key,*,new_manifold_mask = None,\n                         pulse_number = -1,ket_flag=True):\n        \"\"\"This method is similar to the method down, but does not involve \n            the electric field shape or convolutions. It is the action of the \n            dipole operator on the ket-side without TDPT effects.  It also includes\n            the dot product of the final electric field polarization vector.\"\"\"\n        old_manifold_key = manifold_key\n        change = -1\n        if ket_flag:\n            manifold_change = np.array([change,0])\n        else:\n            manifold_change = np.array([0,change])\n\n        old_manifold = self.manifold_key_to_array(old_manifold_key)\n        new_manifold = old_manifold + manifold_change\n        new_manifold_key = self.manifold_array_to_key(new_manifold)\n        mu_key = old_manifold_key + '_to_' + new_manifold_key\n        \n        if ket_flag:\n            center = - self.centers[pulse_number]\n            conjugate_flag = True\n        else:\n            center = self.centers[pulse_number]\n            conjugate_flag = False\n\n        rho_in = rho\n        \n        overlap_matrix = self.dipole_matrix(pulse_number,mu_key,ket_flag=True,up_flag=False)\n\n        t0 = time.time()\n        rho = overlap_matrix.dot(rho_in)\n                \n        t1 = time.time()\n\n        L_size = rho.shape[0]\n        H_size = int(np.sqrt(L_size))\n\n        # reshape rho into a normal density matrix representation\n        rho = rho.reshape((H_size,H_size,rho.shape[-1]))\n\n        polarization_field = np.einsum('iij',rho)\n\n        return polarization_field\n\n    def load_H_mu(self):\n        parent_dir = os.path.split(self.base_path)[0]\n        file_name = os.path.join(parent_dir,'closed','mu.npz')\n\n        with np.load(file_name) as mu_archive:\n            self.H_mu = {key:mu_archive[key] for key in mu_archive.keys()}\n\n    def get_H_mu(self,pulse_number,key,ket_flag=True,up_flag=True):\n        \"\"\"Calculates the dipole matrix given the electric field polarization vector,\n            if ket_flag = False then uses the bra-interaction\"\"\"\n        t0 = time.time()\n        pol = self.polarization_sequence[pulse_number]\n\n        x = np.array([1,0,0])\n        y = np.array([0,1,0])\n        z = np.array([0,0,1])\n        try:\n            mu = self.H_mu[key]\n        except KeyError:\n            try:\n                key = 'up'\n                mu = self.H_mu[key]\n            except KeyError:\n                key = 'ket_up'\n                mu = self.H_mu[key]\n            \n        if np.all(pol == x):\n            overlap_matrix = mu[:,:,0].copy()\n        elif np.all(pol == y):\n            overlap_matrix = mu[:,:,1].copy()\n        elif np.all(pol == z):\n            overlap_matrix = mu[:,:,2].copy()\n        else:\n            overlap_matrix = np.tensordot(mu,pol,axes=(-1,0))\n\n        if not up_flag:\n            overlap_matrix = overlap_matrix.T\n\n        t1 = time.time()\n        self.dipole_time += t1-t0\n\n        return overlap_matrix\n\n    def set_undersample_factor(self,frequency_resolution):\n        \"\"\"dt is set by the pulse. However, the system dynamics may not require such a \n            small dt.  Therefore, this allows the user to set a requested frequency\n            resolution for any spectrally resolved signals.\"\"\"\n        # f = pi/dt\n        dt = np.pi/frequency_resolution\n        u = int(np.floor(dt/self.dt))\n        self.undersample_factor = max(u,1)\n        \n    def dipole_expectation(self,rho_in,*,pulse_number = -1,ket_flag=True):\n        \"\"\"Computes the expectation value of the dipole operator\"\"\"\n        t0 = time.time()\n\n        pulse_number = -1\n        \n        pulse_time = self.pulse_times[pulse_number]\n        \n        efield_t = self.efield_times[pulse_number] + pulse_time\n\n        if ket_flag:\n            center = - self.centers[pulse_number]\n        else:\n            center = self.centers[pulse_number]\n        \n        # The signal is zero before the final pulse arrives, and persists\n        # until it decays. Therefore we avoid taking the sum at times\n        # where the signal is zero.\n        t = self.t + pulse_time\n\n        pulse_start_ind = np.argmin(np.abs(t-efield_t[0]))\n        if efield_t[0] < t[pulse_start_ind]:\n            pulse_start_ind -= 1\n        pulse_end_ind = np.argmin(np.abs(t-efield_t[-1]))\n        if efield_t[-1] > t[pulse_end_ind]:\n            pulse_end_ind += 1\n        \n        t_slice = slice(pulse_start_ind,None,None)\n        t1_slice = slice(pulse_start_ind,pulse_end_ind,None)\n        u = self.undersample_factor\n        t2_slice = slice(pulse_end_ind,None,u)\n\n        t = self.t[t_slice] + pulse_time\n        t1 = self.t[t1_slice] + pulse_time\n        t2 = self.t[t2_slice] + pulse_time\n\n        rho1 = rho_in(t1)\n        rho2 = rho_in(t2)\n\n        rho1 *= np.exp(-1j * center * t1[np.newaxis,:])\n\n        rho2 *= np.exp(-1j * center * t2[np.newaxis,:])\n\n        # _u is an abbreviation for undersampled\n        t_u = np.hstack((t1,t2))\n        rho_u = np.hstack((rho1,rho2))\n        \n        tb = time.time()\n        self.slicing_time += tb-t0\n\n        t0 = time.time()\n        exp_val_u = self.dipole_down(rho_u,rho_in.manifold_key,pulse_number = pulse_number,\n                                     ket_flag = ket_flag)\n        \n        tb = time.time()\n        self.expectation_time += tb-t0\n\n        t0 = time.time()\n\n        # Interpolate expectation value back onto the full t-grid\n        if u != 1:\n            # Often must extrapolate the final point\n            exp_val_interp = scipy.interpolate.interp1d(t_u,exp_val_u,kind='cubic',fill_value='extrapolate')\n            exp_val = exp_val_interp(t)\n        else:\n            exp_val = exp_val_u\n        # print(exp_val.size/exp_val_u.size)\n        tb = time.time()\n        self.interpolation_time += tb-t0\n        \n        # Initialize return array with zeros\n        ret_val = np.zeros(self.t.size,dtype='complex')\n        \n        # set non-zero values using t_slice\n        ret_val[pulse_start_ind:] = exp_val\n        return ret_val\n\n    def integrated_dipole_expectation(self,rho_in,*,ket_flag=True):\n        \"\"\"Computes the expectation value of the dipole operator\"\"\"\n        \n        pulse_number = -1\n        \n        pulse_time = self.pulse_times[pulse_number]\n        t = pulse_time + self.efield_times[pulse_number]\n\n        if ket_flag:\n            center = - self.centers[pulse_number]\n        else:\n            center = self.centers[pulse_number]\n\n        rho = rho_in(t)\n\n        rho_nonzero = rho_in.bool_mask\n        try:\n            ev = self.eigenvalues['all_manifolds'][rho_nonzero]\n        except KeyError:\n            ev = self.eigenvalues[rho_in.manifold_key][rho_nonzero]\n\n        rho = rho * np.exp((ev[:,np.newaxis] - 1j*center)*t)\n\n        rho_dict = {'bool_mask':rho_nonzero,'rho':rho,'manifold_key':rho_in.manifold_key}\n\n        t0 = time.time()\n        exp_val = self.dipole_down(rho_dict,pulse_number = pulse_number,\n                                     ket_flag = ket_flag)\n        \n        tb = time.time()\n        self.expectation_time += tb-t0\n\n        return exp_val\n\n    def get_local_oscillator(self):\n        local_oscillator_number = -1\n        efield_t = self.efield_times[local_oscillator_number]\n        efield = self.efields[local_oscillator_number]\n\n        if efield_t.size == 1:\n            # Impulsive limit: delta in time is flat in frequency\n            efield_ft = np.ones(self.w.size)*efield\n            return efield_ft\n        \n        e_dt = efield_t[1] - efield_t[0]\n        dt = self.t[1] - self.t[0]\n            \n        if (np.isclose(e_dt,dt) and efield_t[-1] <= self.t[-1]):\n            full_efield = np.zeros(self.t.size,dtype='complex')\n\n            # the local oscillator sets the \"zero\" on the clock\n            pulse_time_ind = np.argmin(np.abs(self.t))\n\n            pulse_start_ind = pulse_time_ind - efield_t.size//2\n            pulse_end_ind = pulse_time_ind + efield_t.size//2 + efield_t.size%2\n\n            t_slice = slice(pulse_start_ind, pulse_end_ind,None)\n            \n            full_efield[t_slice] = efield\n            efield_ft = fftshift(ifft(ifftshift(full_efield)))*full_efield.size * dt\n        else:\n            efield_ft = fftshift(ifft(ifftshift(efield))) * efield.size * e_dt\n            efield_w = fftshift(fftfreq(efield_t.size,d=e_dt)) * 2 * np.pi\n            fill_value = (efield_ft[0],efield_ft[-1])\n            f = sinterp1d(efield_w,efield_ft,fill_value = fill_value,\n                          bounds_error=False,kind='quadratic')\n            efield_ft = f(self.w)\n\n        return efield_ft\n    \n    def polarization_to_signal(self,P_of_t_in,*,\n                                local_oscillator_number = -1,undersample_factor = 1):\n        \"\"\"This function generates a frequency-resolved signal from a polarization field\n           local_oscillator_number - usually the local oscillator will be the last pulse \n                                     in the list self.efields\"\"\"\n        undersample_slice = slice(None,None,undersample_factor)\n        P_of_t = P_of_t_in[undersample_slice].copy()\n        t = self.t[undersample_slice]\n        dt = t[1] - t[0]\n        pulse_time = self.pulse_times[local_oscillator_number]\n        efield_t = self.efield_times[local_oscillator_number]\n        \n        pulse_time_ind = np.argmin(np.abs(self.t))\n        \n        efield = self.get_local_oscillator()\n\n        halfway = self.w.size//2\n        pm = self.w.size//(2*undersample_factor)\n        efield_min_ind = halfway - pm\n        efield_max_ind = halfway + pm + self.w.size%2\n        efield = efield[efield_min_ind:efield_max_ind]\n\n        P_of_w = fftshift(ifft(ifftshift(P_of_t)))*len(P_of_t)*dt#/np.sqrt(2*np.pi)\n\n        signal = P_of_w * np.conjugate(efield)\n        if not self.return_complex_signal:\n            return np.imag(signal)\n        else:\n            return 1j*signal\n\n    def integrated_polarization_to_signal(self,P,*,\n                                local_oscillator_number = -1):\n        \"\"\"This function generates a frequency-resolved signal from a polarization field\n           local_oscillator_number - usually the local oscillator will be the last pulse \n                                     in the list self.efields\"\"\"\n        efield_t = self.efield_times[local_oscillator_number]\n\n        efield = self.efields[local_oscillator_number]\n\n        signal = np.trapz(P * np.conjugate(efield),x=efield_t)\n        return np.imag(signal)\n\n    def save(self,file_name,pulse_delay_names,*,use_base_path=True):\n        if use_base_path:\n            file_name = os.path.join(self.base_path,file_name)\n        save_dict = {}\n        for name,delays in zip(pulse_delay_names,self.all_pulse_delays):\n            save_dict[name] = delays\n        if self.detection_type == 'polarization':\n            save_dict['wt'] = self.w\n        save_dict['signal'] = self.signal\n        save_dict['signal_calculation_time'] = self.calculation_time\n        np.savez(file_name,**save_dict)\n", "meta": {"hexsha": "36a804108281fb0bd93eafcae02d0a1e3dc4b3d5", "size": 50051, "ext": "py", "lang": "Python", "max_stars_repo_path": "ufss/RKE/RKE_open_core.py", "max_stars_repo_name": "peterarose/UFSS", "max_stars_repo_head_hexsha": "1dded9c94493b8d681cd8620d45d883a79e41ae3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-08-18T12:19:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T17:33:47.000Z", "max_issues_repo_path": "ufss/RKE/RKE_open_core.py", "max_issues_repo_name": "peterarose/UFSS", "max_issues_repo_head_hexsha": "1dded9c94493b8d681cd8620d45d883a79e41ae3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-09-03T11:43:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T04:13:41.000Z", "max_forks_repo_path": "ufss/RKE/RKE_open_core.py", "max_forks_repo_name": "peterarose/UFSS", "max_forks_repo_head_hexsha": "1dded9c94493b8d681cd8620d45d883a79e41ae3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-08-18T12:19:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-14T00:58:58.000Z", "avg_line_length": 37.6890060241, "max_line_length": 142, "alphanum_fraction": 0.5831451919, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 11795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.18145182548206984}}
{"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 29 10:52:50 2019\n\n@author: daniel\n\"\"\"\nfrom pylab import *\nimport os\nimport numpy as np\nimport cobra\nimport networkx as nx\nfrom Env_ball_class import Env_ball\n\ndef apply_environment(mdl, env_vec,transporters):\n    for i in range(len(transporters)):\n        try:\n            mdl.reactions.get_by_id(transporters[i]).lower_bound=-env_vec[i]\n            mdl.reactions.get_by_id(transporters[i]).upper_bound=1000.\n        except KeyError:\n            pass\n    sol_m=mdl.optimize()\n    return sol_m.objective_value\n\ndef buid_bipartite_graph(model):\n    G=nx.MultiDiGraph()\n    \n    for met in model.metabolites:\n        G.add_node(met.id, name=met.name, nodeType = 'metabolite')\n    \n    \n    for reac in model.reactions:\n        if not reac.reversibility:\n            G.add_node(reac.id, name=reac.name, nodeType = 'reaction')\n            \n            for met in reac.reactants:\n                G.add_edge(met.id, reac.id, name = reac.id)\n            for met in reac.products:\n                G.add_edge(reac.id, met.id, name = reac.id)\n        \n        else:\n            G.add_node(reac.id + '_r', name=reac.name, nodeType = 'reaction')\n            G.add_node(reac.id + '_f', name=reac.name, nodeType = 'reaction')\n            \n            for met in reac.reactants:\n                G.add_edge(met.id, reac.id + '_f', name = reac.id)\n                G.add_edge(reac.id + '_r',met.id, name = reac.id)\n            for met in reac.products:\n                G.add_edge(reac.id + '_f', met.id, name = reac.id)\n                G.add_edge(met.id,reac.id + '_r', name = reac.id)\n    \n    return G\n\n\nclass panEFM_run:\n    def __init__(self, file_path, file_name):\n        print(file_path, file_name)\n        \n        self.file_name=file_name\n        self.file_path = file_path\n        self.file_ = os.path.join(file_path, file_name)\n        \n        self.environment=self.__get_environment(file_name)\n        self.reactome=None\n        self.binary_m=None\n        self.freq_t=None\n        \n        self.__parse_run_file(self.file_)\n    \n    def __get_environment(self, file_name):\n        return file_name.split(\".\")[0].split('_')[-1]\n    \n    def __parse_run_file(self, file_):\n        with open(file_) as f:\n        \n            reactome = np.array(f.readline().strip().split('\\t'))\n            \n            dt=[]\n            sorter = np.argsort(reactome)\n            \n            self.reactome = reactome[sorter]\n            \n            for line in f:\n                a=line.strip().split('\\t')\n                d = [*map(float, a)]\n                d=np.array(d)\n                dt.append(d[sorter])\n            self.binary_m = np.array(dt).T\n            \n            self.freq_t = np.sum(self.binary_m, axis=1)/self.binary_m.shape[1]\n    \n    \n\n\nclass panEFM_family:\n    def __init__(self, family_name, file_path, model_path):\n        self.family = family_name\n        self.file_path = file_path\n        self.model_path = model_path\n        \n        self.model = cobra.io.read_sbml_model(os.path.join(self.model_path, self.family,self.family+'.ensembl.sbml'))\n        \n        \n        self.file_path_fam = os.path.join(self.file_path, self.family)\n        self.model_path_fam = os.path.join(self.model_path, self.family, 'gapfilled')\n        \n        self.files = os.listdir(self.file_path_fam)\n        self.model_files= os.listdir(self.model_path_fam)\n        \n        \n        self.environments=None\n        self.reactome=None\n        self.freq_m=None\n        \n        self.model_reac_freq=None\n        self.gene_counts = None\n        \n        self.panEFM=None\n        \n        self.include_reactome = None\n        \n        self.model_reactomes = None\n        \n        self.__parse_run_files()\n        self.__get_model_reac_freq()\n        self.__get_include_reactome()\n        \n        \n    \n    def __parse_run_files(self):\n        panEFM1= panEFM_run(self.file_path_fam, self.files[0])\n        \n        \n        \n        \n        \n        #sorter = np.argsort(panEFM1.reactome)\n        self.reactome = panEFM1.reactome.copy()\n        \n        self.panEFM={}\n        self.panEFM[panEFM1.environment]=panEFM1.binary_m.copy()\n        \n        \n        self.environments = np.zeros(len(self.files))\n        self.freq_m = np.zeros((len(self.files), len(self.reactome)))\n        \n        for i in range(len(self.files)):\n            print (self.files[i])\n            panEFM= panEFM_run(self.file_path_fam, self.files[i])\n            \n            self.environments[i] = float(panEFM.environment)\n            self.freq_m[i]=panEFM.freq_t\n            \n            \n            self.panEFM[panEFM.environment]=panEFM.binary_m.copy()\n        \n        \n        \n        env_sorter = np.argsort(self.environments)\n        self.environments=self.environments[env_sorter]\n        self.freq_m = self.freq_m[env_sorter] \n    \n    def __get_model_reac_freq(self):\n        '''\n        Obtain binary vectors indicating the presence of reactions in specific models.\n        Summarize these vectors by their frequency.\n\n        Returns\n        -------\n        None.\n\n        '''\n        models_n = len(self.model_files)\n        reactions_n = len(self.reactome)\n        \n        v =np.zeros((models_n, reactions_n))\n        freq= np.zeros(reactions_n)\n        gene_counts = np.zeros(reactions_n)\n        for i,name in enumerate(self.model_files):\n            mod=cobra.io.read_sbml_model(os.path.join(self.model_path_fam, name))\n            for r in range(reactions_n):\n                if mod.reactions.has_id(self.reactome[r]):\n                    freq[r]+=(1.0/models_n)\n                    gene_counts[r]+=len(mod.reactions.get_by_id(self.reactome[r]).genes)\n                    v[i][r] = 1.0\n        self.model_reac_freq=freq\n        self.gene_counts = gene_counts\n        self.model_reactomes = v\n    \n    def __get_include_reactome(self):\n        '''\n        reactions that are compared. The rules are:\n            1) Are associated to a gene in any of the models;\n            2) Are connected to the biomass reaction in a bipartite graph;\n            3) Are not lethal to the model, as defined by flux variability analysis.\n        '''\n        \n        index = np.zeros(len(self.reactome))\n        \n        fva = cobra.flux_analysis.flux_variability_analysis(self.model)\n        \n        g = buid_bipartite_graph(self.model)\n        \n        \n        \n        for i, name in enumerate(self.reactome):\n            if self.gene_counts[i]>0:#condition 1)\n                \n                #condition 3)    \n                if fva.loc[name]['minimum']<0:\n                    index[i]=1\n                elif fva.loc[name]['maximum']>0:\n                    index[i]=1\n                \n                #condition 2)\n                if self.model.reactions.get_by_id(name).reversibility:\n                    if nx.has_path(g, source=name+'_f', target='bio1'):\n                        index[i]=1\n                    elif nx.has_path(g, source=name+'_r', target='bio1'):\n                        index[i]=1\n                else:\n                    if nx.has_path(g, source=name, target='bio1'):\n                        index[i]=1\n                    \n                    \n        self.include_reactome = index.astype(np.bool)\n                    \n \nev =Env_ball(1000)\n        \n#families = os.listdir(pathToFamilyEFMs)\n\n#fam_mfs={}\n\n#for i in [families[0]]:\n#    fam_panEFM[i]=panEFM_family(i, pathToFamilyEFMs,pathToModels)\n                \n", "meta": {"hexsha": "18676a3fad7a0235d22659a81901d5701785a175", "size": 7479, "ext": "py", "lang": "Python", "max_stars_repo_path": "Scripts/parse_panEFM_class.py", "max_stars_repo_name": "danielriosgarza/NutritionOrNature", "max_stars_repo_head_hexsha": "8e2aca72f1009f1fa71e340a1de27cb583611819", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Scripts/parse_panEFM_class.py", "max_issues_repo_name": "danielriosgarza/NutritionOrNature", "max_issues_repo_head_hexsha": "8e2aca72f1009f1fa71e340a1de27cb583611819", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Scripts/parse_panEFM_class.py", "max_forks_repo_name": "danielriosgarza/NutritionOrNature", "max_forks_repo_head_hexsha": "8e2aca72f1009f1fa71e340a1de27cb583611819", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4243697479, "max_line_length": 117, "alphanum_fraction": 0.5486027544, "include": true, "reason": "import numpy,import networkx", "num_tokens": 1728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.1814518254820698}}
{"text": "__author__ = \"Xinqiang Ding <xqding@umich.edu>\"\n__date__ = \"2017/10/16 02:50:08\"\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset\nfrom torch.distributions.categorical import Categorical\n\n\nclass MSA_Dataset(Dataset):\n    '''\n    Dataset class for multiple sequence alignment.\n    '''\n\n    def __init__(self, seq_msa_binary, seq_weight, seq_keys):\n        '''\n        seq_msa_binary: a two dimensional np.array.\n                        size: [num_of_sequences, length_of_msa*num_amino_acid_types]\n        seq_weight: one dimensional array.\n                    size: [num_sequences].\n                    Weights for sequences in a MSA.\n                    The sum of seq_weight has to be equal to 1 when training latent space models using VAE\n        seq_keys: name of sequences in MSA\n        '''\n        super(MSA_Dataset).__init__()\n        self.seq_msa_binary = seq_msa_binary\n        self.seq_weight = seq_weight\n        self.seq_keys = seq_keys\n\n    def __len__(self):\n        assert(self.seq_msa_binary.shape[0] == len(self.seq_weight))\n        assert(self.seq_msa_binary.shape[0] == len(self.seq_keys))\n        return self.seq_msa_binary.shape[0]\n\n    def __getitem__(self, idx):\n        return self.seq_msa_binary[idx, :], self.seq_weight[idx], self.seq_keys[idx]\n\n\nclass VAE(nn.Module):\n    def __init__(self, num_aa_type, dim_latent_vars, dim_msa_vars, num_hidden_units):\n        super(VAE, self).__init__()\n\n        # num of amino acid types\n        self.num_aa_type = num_aa_type\n\n        # dimension of latent space\n        self.dim_latent_vars = dim_latent_vars\n\n        # dimension of binary representation of sequences\n        self.dim_msa_vars = dim_msa_vars\n\n        # num of hidden neurons in encoder and decoder networks\n        self.num_hidden_units = num_hidden_units\n\n        # encoder\n        self.encoder_linears = nn.ModuleList()\n        self.encoder_linears.append(nn.Linear(dim_msa_vars, num_hidden_units[0]))\n        for i in range(1, len(num_hidden_units)):\n            self.encoder_linears.append(nn.Linear(num_hidden_units[i - 1], num_hidden_units[i]))\n        self.encoder_mu = nn.Linear(num_hidden_units[-1], dim_latent_vars, bias=True)\n        self.encoder_logsigma = nn.Linear(num_hidden_units[-1], dim_latent_vars, bias=True)\n\n        # decoder\n        self.decoder_linears = nn.ModuleList()\n        self.decoder_linears.append(nn.Linear(dim_latent_vars, num_hidden_units[0]))\n        for i in range(1, len(num_hidden_units)):\n            self.decoder_linears.append(nn.Linear(num_hidden_units[i - 1], num_hidden_units[i]))\n        self.decoder_linears.append(nn.Linear(num_hidden_units[-1], dim_msa_vars))\n\n    def encoder(self, x):\n        '''\n        encoder transforms x into latent space z\n        '''\n\n        h = x\n        for T in self.encoder_linears:\n            h = T(h)\n            h = torch.tanh(h)\n        mu = self.encoder_mu(h)\n        sigma = torch.exp(self.encoder_logsigma(h))\n        return mu, sigma\n\n    def decoder(self, z):\n        '''\n        decoder transforms latent space z into p, which is the log probability  of x being 1.\n        '''\n\n        h = z\n        for i in range(len(self.decoder_linears) - 1):\n            h = self.decoder_linears[i](h)\n            h = torch.tanh(h)\n        h = self.decoder_linears[-1](h)\n\n        fixed_shape = tuple(h.shape[0:-1])\n        h = torch.unsqueeze(h, -1)\n        h = h.view(fixed_shape + (-1, self.num_aa_type))\n\n        # h = torch.reshape(h, fixed_shape + (-1, self.num_aa_type))\n        log_p = F.log_softmax(h, dim=-1)\n        log_p = log_p.view(fixed_shape + (-1,))\n\n        # h = h.view(h.size(0), -1, self.num_aa_type)\n        # log_p = F.log_softmax(h, dim = 2)\n        # log_p = log_p.view(log_p.size(0), -1)\n\n        return log_p\n\n    def compute_weighted_elbo(self, x, weight):\n        # sample z from q(z|x)\n        mu, sigma = self.encoder(x)\n        eps = torch.randn_like(sigma)\n        z = mu + sigma * eps\n\n        # compute log p(x|z)\n        log_p = self.decoder(z)\n        log_PxGz = torch.sum(x * log_p, -1)\n\n        # compute elbo\n        elbo = log_PxGz - torch.sum(0.5 * (sigma**2 + mu**2 - 2 * torch.log(sigma) - 1), -1)\n        weight = weight / torch.sum(weight)\n        elbo = torch.sum(elbo * weight)\n\n        return elbo\n\n    def compute_p_importance_sampling(self, x, nsamples):\n\n        with torch.no_grad():\n            x = x.expand(nsamples, x.shape[0], x.shape[1])\n            mu, sigma = self.encoder(x)\n            eps = torch.randn_like(mu)\n            z = mu + sigma * eps\n            log_Pz = torch.sum(-0.5 * z**2 - 0.5 * torch.log(2 * z.new_tensor(np.pi)), -1)\n            log_p = self.decoder(z)\n            log_PxGz = torch.sum(x * log_p, -1)\n            log_Pxz = log_Pz + log_PxGz\n\n            log_QzGx = torch.sum(-0.5 * (eps)**2 -\n                                 0.5 * torch.log(2 * z.new_tensor(np.pi))\n                                 - torch.log(sigma), -1)        \n\n            log_Px = torch.logsumexp(log_Pxz - log_QzGx, 0) - torch.log(torch.tensor(nsamples))\n\n        return log_Px\n\n    def compute_p(self, x, nsamples):\n\n        with torch.no_grad():\n            # sample z from prior\n            z = torch.randn((x.shape[0], nsamples, self.dim_latent_vars), device=x.device)\n\n            # compute log p(x|z)\n            log_p = self.decoder(z)\n            log_PxGz = torch.sum(x.unsqueeze(1).expand(-1, nsamples, -1) * log_p, -1)\n\n        return torch.mean(log_PxGz, -1)\n\n\n    def compute_elbo_no_grad(self, x):\n        with torch.no_grad():\n            # sample z from q(z|x)\n            mu, sigma = self.encoder(x)\n            eps = torch.randn_like(sigma)\n            z = mu + sigma * eps\n\n            # compute log p(x|z)\n            log_p = self.decoder(z)\n            log_PxGz = torch.sum(x * log_p, -1)\n\n            # compute elbo\n            elbo = log_PxGz - torch.sum(0.5 * (sigma**2 + mu**2 - 2 * torch.log(sigma) - 1), -1)\n\n        return elbo\n\n    def sample(self, nsamples):\n\n        # sample z from prior\n        device = next(self.parameters()).device\n        z = torch.randn((nsamples, self.dim_latent_vars), device=device)\n        log_p = self.decoder(z)\n\n        dist = Categorical(logits=log_p.reshape(nsamples, -1, self.num_aa_type))\n\n        data = dist.sample()\n\n        return data\n\n    def compute_elbo(self, x):\n        # sample z from q(z|x)\n        mu, sigma = self.encoder(x)\n        eps = torch.randn_like(sigma)\n        z = mu + sigma * eps\n\n        # compute log p(x|z)\n        log_p = self.decoder(z)\n        log_PxGz = torch.sum(x * log_p, -1)\n\n        # compute elbo\n        elbo = log_PxGz - torch.sum(0.5 * (sigma**2 + mu**2 - 2 * torch.log(sigma) - 1), -1)\n\n        return elbo\n\n    def compute_elbo_with_multiple_samples(self, x, num_samples):\n        with torch.no_grad():\n            x = x.expand(num_samples, x.shape[0], x.shape[1])\n            mu, sigma = self.encoder(x)\n            eps = torch.randn_like(mu)\n            z = mu + sigma * eps\n            log_Pz = torch.sum(-0.5 * z**2 - 0.5 * torch.log(2 * z.new_tensor(np.pi)), -1)\n            log_p = self.decoder(z)\n            log_PxGz = torch.sum(x * log_p, -1)\n            log_Pxz = log_Pz + log_PxGz\n\n            log_QzGx = torch.sum(-0.5 * (eps)**2 -\n                                 0.5 * torch.log(2 * z.new_tensor(np.pi))\n                                 - torch.log(sigma), -1)\n            log_weight = (log_Pxz - log_QzGx).detach().data\n            log_weight_max = torch.max(log_weight, 0)[0]\n            log_weight = log_weight - log_weight_max\n            weight = torch.exp(log_weight)\n            elbo = torch.log(torch.mean(weight, 0)) + log_weight_max\n            return elbo\n\n    def sample_latent_var(self, mu, sigma):\n        eps = torch.ones_like(sigma).normal_()\n        z = mu + sigma * eps\n        return z\n\n    def forward(self, x):\n        mu, sigma = self.encoder(x)\n        z = self.sample_latent_var(mu, sigma)\n        p = self.decoder(z)\n        return mu, sigma, p\n", "meta": {"hexsha": "f347b3b8076872ff4e550c9376b821885802a647", "size": 8036, "ext": "py", "lang": "Python", "max_stars_repo_path": "vae/VAE_model.py", "max_stars_repo_name": "christophfeinauer/PairwiseDistillations", "max_stars_repo_head_hexsha": "54793b0d9efcd97ba679754c9ae7ca6ae630376b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-25T13:43:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T13:43:24.000Z", "max_issues_repo_path": "vae/VAE_model.py", "max_issues_repo_name": "christophfeinauer/PairwiseDistillations", "max_issues_repo_head_hexsha": "54793b0d9efcd97ba679754c9ae7ca6ae630376b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vae/VAE_model.py", "max_forks_repo_name": "christophfeinauer/PairwiseDistillations", "max_forks_repo_head_hexsha": "54793b0d9efcd97ba679754c9ae7ca6ae630376b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1957446809, "max_line_length": 106, "alphanum_fraction": 0.5740418118, "include": true, "reason": "import numpy", "num_tokens": 2105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.18136273416684706}}
{"text": "\nimport torch\nimport torch.nn as nn\nimport numpy as np\n\n# Constants\nN_PAIR = 'n-pair'\nANGULAR = 'angular'\nN_PAIR_ANGULAR = 'n-pair-angular'\nMAIN_LOSS_CHOICES = (N_PAIR, ANGULAR, N_PAIR_ANGULAR)\n\nCROSS_ENTROPY = 'cross-entropy'\n\n\nclass BlendedLoss(object):\n    def __init__(self, main_loss_type, cross_entropy_flag):\n        super(BlendedLoss, self).__init__()\n        self.main_loss_type = main_loss_type\n        assert main_loss_type in MAIN_LOSS_CHOICES, \"invalid main loss: %s\" % main_loss_type\n\n        self.metrics = []\n        if self.main_loss_type == N_PAIR:\n            self.main_loss_fn = NPairLoss()\n        elif self.main_loss_type == ANGULAR:\n            self.main_loss_fn = AngularLoss()\n        elif self.main_loss_type == N_PAIR_ANGULAR:\n            self.main_loss_fn = NPairAngularLoss()\n        else:\n            raise ValueError\n\n        self.cross_entropy_flag = cross_entropy_flag\n        self.lambda_blending = 0\n        if cross_entropy_flag:\n            self.cross_entropy_loss_fn = nn.CrossEntropyLoss()\n            self.lambda_blending = 0.3\n\n    def calculate_loss(self, target, output_embedding, output_cross_entropy=None):\n        if target is not None:\n            target = (target, )\n\n        loss_dict = {}\n        blended_loss = 0\n        if self.cross_entropy_flag:\n            assert output_cross_entropy is not None, \"Outputs for cross entropy loss is needed\"\n\n            loss_inputs = self._gen_loss_inputs(target, output_cross_entropy)\n            cross_entropy_loss = self.cross_entropy_loss_fn(*loss_inputs)\n            blended_loss += self.lambda_blending * cross_entropy_loss\n            loss_dict[CROSS_ENTROPY + '-loss'] = [cross_entropy_loss.item()]\n\n        loss_inputs = self._gen_loss_inputs(target, output_embedding)\n        main_loss_outputs = self.main_loss_fn(*loss_inputs)\n        main_loss = main_loss_outputs[0] if type(main_loss_outputs) in (tuple, list) else main_loss_outputs\n        blended_loss += (1 - self.lambda_blending) * main_loss\n        loss_dict[self.main_loss_type + '-loss'] = [main_loss.item()]\n\n        for metric in self.metrics:\n            metric(output_embedding, target, main_loss_outputs)\n\n        return blended_loss, loss_dict\n\n    @staticmethod\n    def _gen_loss_inputs(target, embedding):\n        if type(embedding) not in (tuple, list):\n            embedding = (embedding, )\n        loss_inputs = embedding\n        if target is not None:\n            if type(target) not in (tuple, list):\n                target = (target, )\n            loss_inputs += target\n        return loss_inputs\n\n\nclass NPairLoss(nn.Module):\n    \"\"\"\n    N-Pair loss\n    Sohn, Kihyuk. \"Improved Deep Metric Learning with Multi-class N-pair Loss Objective,\" Advances in Neural Information\n    Processing Systems. 2016.\n    http://papers.nips.cc/paper/6199-improved-deep-metric-learning-with-multi-class-n-pair-loss-objective\n    \"\"\"\n    def __init__(self, l2_reg=0.02, **kwargs):\n        super(NPairLoss, self).__init__()\n        self.l2_reg = l2_reg\n\n    def forward(self, embeddings, target):\n        n_pairs, n_negatives = self.get_n_pairs(target)\n\n        if embeddings.is_cuda:\n            n_pairs = n_pairs.cuda()\n            n_negatives = n_negatives.cuda()\n\n        anchors = embeddings[n_pairs[:, 0]]  # (n, embedding_size)\n        positives = embeddings[n_pairs[:, 1]]  # (n, embedding_size)\n        negatives = embeddings[n_negatives]  # (n, n-1, embedding_size)\n\n        losses = self.n_pair_loss(anchors, positives, negatives) \\\n            + self.l2_reg * self.l2_loss(anchors, positives)\n\n        return losses\n\n    @staticmethod\n    def get_n_pairs(labels):\n        \"\"\"\n        Get index of n-pairs and n-negatives\n        :param labels: label vector of mini-batch\n        :return: A tuple of n_pairs (n, 2)\n                        and n_negatives (n, n-1)\n        \"\"\"\n        labels = labels.cpu().data.numpy()\n        n_pairs = []\n        for label in set(labels):\n            label_mask = (labels == label)\n            label_indices = np.where(label_mask)[0]\n            if len(label_indices) < 2:\n                continue\n            anchor, positive = np.random.choice(label_indices, 2, replace=False)\n            n_pairs.append([anchor, positive])\n\n        n_pairs = np.array(n_pairs)\n        n_negatives = []\n        for i in range(len(n_pairs)):\n            negative = np.concatenate([n_pairs[:i, 1], n_pairs[i + 1:, 1]])\n            n_negatives.append(negative)\n\n        n_negatives = np.array(n_negatives)\n        return torch.LongTensor(n_pairs), torch.LongTensor(n_negatives)\n\n    @staticmethod\n    def n_pair_loss(anchors, positives, negatives):\n        \"\"\"\n        Calculates N-Pair loss\n        :param anchors: A torch.Tensor, (n, embedding_size)\n        :param positives: A torch.Tensor, (n, embedding_size)\n        :param negatives: A torch.Tensor, (n, n-1, embedding_size)\n        :return: A scalar\n        \"\"\"\n        anchors = torch.unsqueeze(anchors, dim=1)  # (n, 1, embedding_size)\n        positives = torch.unsqueeze(positives, dim=1)  # (n, 1, embedding_size)\n\n        x = torch.matmul(anchors, (negatives - positives).transpose(1, 2))  # (n, 1, n-1)\n        x = torch.sum(torch.exp(x), 2)  # (n, 1)\n        loss = torch.mean(torch.log(1 + x))\n        return loss\n\n    @staticmethod\n    def l2_loss(anchors, positives):\n        \"\"\"\n        Calculates L2 norm regularization loss\n        :param anchors: A torch.Tensor, (n, embedding_size)\n        :param positives: A torch.Tensor, (n, embedding_size)\n        :return: A scalar\n        \"\"\"\n        return torch.sum(anchors**2 + positives**2) / anchors.shape[0]\n\n\nclass AngularLoss(NPairLoss):\n    \"\"\"\n    Angular loss\n    Wang, Jian. \"Deep Metric Learning with Angular Loss,\" CVPR, 2017\n    https://arxiv.org/pdf/1708.01682.pdf\n    \"\"\"\n    def __init__(self, l2_reg=0.02, angle_bound=1., lambda_ang=2, **kwargs):\n        super(AngularLoss, self).__init__()\n        self.l2_reg = l2_reg\n        self.angle_bound = angle_bound\n        self.lambda_ang = lambda_ang\n        self.softplus = nn.Softplus()\n\n    def forward(self, embeddings, target):\n        n_pairs, n_negatives = self.get_n_pairs(target)\n        if embeddings.is_cuda:\n            n_pairs = n_pairs.cuda()\n            n_negatives = n_negatives.cuda()\n\n        anchors = embeddings[n_pairs[:, 0]]  # (n, embedding_size)\n        positives = embeddings[n_pairs[:, 1]]  # (n, embedding_size)\n        negatives = embeddings[n_negatives]  # (n, n-1, embedding_size)\n\n        losses = self.angular_loss(anchors, positives, negatives, self.angle_bound) \\\n                 + self.l2_reg * self.l2_loss(anchors, positives)\n\n        return losses, 0, 0, 0\n\n    @staticmethod\n    def angular_loss(anchors, positives, negatives, angle_bound=1.):\n        \"\"\"\n        Calculates angular loss\n        :param anchors: A torch.Tensor, (n, embedding_size)\n        :param positives: A torch.Tensor, (n, embedding_size)\n        :param negatives: A torch.Tensor, (n, n-1, embedding_size)\n        :param angle_bound: tan^2 angle\n        :return: A scalar\n        \"\"\"\n        print(anchors, positives, negatives);exit(1)\n        anchors = torch.unsqueeze(anchors, dim=1)  # (n, 1, embedding_size)\n        positives = torch.unsqueeze(positives, dim=1)  # (n, 1, embedding_size)\n\n        x = 4. * angle_bound * torch.matmul((anchors + positives), negatives.transpose(1, 2)) \\\n            - 2. * (1. + angle_bound) * torch.matmul(anchors, positives.transpose(1, 2))  # (n, 1, n-1)\n\n        # Preventing overflow\n        with torch.no_grad():\n            t = torch.max(x, dim=2)[0]\n\n        x = torch.exp(x - t.unsqueeze(dim=1))\n        x = torch.log(torch.exp(-t) + torch.sum(x, 2))\n        loss = torch.mean(t + x)\n\n        return loss\n\n\nclass NPairAngularLoss(AngularLoss):\n    \"\"\"\n    Angular loss\n    Wang, Jian. \"Deep Metric Learning with Angular Loss,\" CVPR, 2017\n    https://arxiv.org/pdf/1708.01682.pdf\n    \"\"\"\n    def __init__(self, l2_reg=0.02, angle_bound=1., lambda_ang=2, **kwargs):\n        super(NPairAngularLoss, self).__init__()\n        self.l2_reg = l2_reg\n        self.angle_bound = angle_bound\n        self.lambda_ang = lambda_ang\n\n    def forward(self, embeddings, target):\n        n_pairs, n_negatives = self.get_n_pairs(target)\n\n        if embeddings.is_cuda:\n            n_pairs = n_pairs.cuda()\n            n_negatives = n_negatives.cuda()\n\n        anchors = embeddings[n_pairs[:, 0]]  # (n, embedding_size)\n        positives = embeddings[n_pairs[:, 1]]  # (n, embedding_size)\n        negatives = embeddings[n_negatives]  # (n, n-1, embedding_size)\n\n        losses = self.n_pair_angular_loss(anchors, positives, negatives, self.angle_bound) \\\n            + self.l2_reg * self.l2_loss(anchors, positives)\n\n        return losses, 0, 0, 0\n\n    def n_pair_angular_loss(self, anchors, positives, negatives, angle_bound=1.):\n        \"\"\"\n        Calculates N-Pair angular loss\n        :param anchors: A torch.Tensor, (n, embedding_size)\n        :param positives: A torch.Tensor, (n, embedding_size)\n        :param negatives: A torch.Tensor, (n, n-1, embedding_size)\n        :param angle_bound: tan^2 angle\n        :return: A scalar, n-pair_loss + lambda * angular_loss\n        \"\"\"\n        n_pair = self.n_pair_loss(anchors, positives, negatives)\n        angular = self.angular_loss(anchors, positives, negatives, angle_bound)\n\n        return (n_pair + self.lambda_ang * angular) / (1 + self.lambda_ang)", "meta": {"hexsha": "e1ed94b7db4157ffd592ef8c4d478ff0554092ad", "size": 9400, "ext": "py", "lang": "Python", "max_stars_repo_path": "train/losses/angular.py", "max_stars_repo_name": "srvCodes/continual-learning-benchmark", "max_stars_repo_head_hexsha": "faa074bd241a5929ca1d5ae185f67e62945b6180", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40, "max_stars_repo_stars_event_min_datetime": "2020-08-28T10:47:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T02:02:38.000Z", "max_issues_repo_path": "train/losses/angular.py", "max_issues_repo_name": "srvCodes/continual-learning-benchmark", "max_issues_repo_head_hexsha": "faa074bd241a5929ca1d5ae185f67e62945b6180", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-08-01T15:18:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-01T15:18:39.000Z", "max_forks_repo_path": "train/losses/angular.py", "max_forks_repo_name": "srvCodes/continual-learning-benchmark", "max_forks_repo_head_hexsha": "faa074bd241a5929ca1d5ae185f67e62945b6180", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-08-01T16:55:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T06:05:17.000Z", "avg_line_length": 37.3015873016, "max_line_length": 120, "alphanum_fraction": 0.6262765957, "include": true, "reason": "import numpy", "num_tokens": 2348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3140505321516081, "lm_q1q2_score": 0.18136272675169146}}
{"text": "# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n'''neighbor list update'''\nfrom mindspore import numpy as np\nfrom mindspore import ops, Tensor\nfrom .common import get_periodic_displacement, get_range_tensor, get_neighbour_index\nfrom .crd_to_uint_crd import crd_to_uint_crd\n\nstep = Tensor(1, np.int32)\n\ndef not_excluded_mask(atom_numbers, excluded_list_start, excluded_list, excluded_numbers):\n    not_excluded = np.full((atom_numbers, atom_numbers), True, np.bool_)\n    for i, v in enumerate(excluded_list_start):\n        if excluded_numbers[i] > 0:\n            excluded_serial = excluded_list[ops.tensor_range(v, v + excluded_numbers[i], step)]\n            not_excluded[i, excluded_serial] = False\n    return not_excluded\n\n\ndef find_atom_neighbors(atom_numbers, uint_crd, uint_dr_to_dr_cof, cutoff_skin_square):\n    dr = get_periodic_displacement(uint_crd, np.expand_dims(uint_crd, -2), uint_dr_to_dr_cof)\n    dr2 = np.sum(dr ** 2, -1)\n    atom_idx = get_range_tensor(atom_numbers)\n    nl_mask = np.logical_and(atom_idx.reshape(-1, 1) < atom_idx, dr2 < cutoff_skin_square)\n    return nl_mask\n\n\ndef delete_excluded_atoms_serial_in_neighbor_list(\n        atom_numbers, max_neighbor_numbers, nl_mask, not_excluded):\n    mask = np.logical_and(nl_mask, not_excluded)\n    serial_idx = get_neighbour_index(atom_numbers, atom_numbers)\n    nl_serial = np.where(mask, serial_idx, atom_numbers)\n    nl_serial = np.sort(nl_serial, -1)[:, : max_neighbor_numbers]\n    nl_numbers = np.sum(mask, -1)\n    return nl_numbers, nl_serial\n\n\ndef crd_periodic_map(crd, box_length):\n    crd = np.where(crd < 0, crd + box_length, crd)\n    crd = np.where(crd > box_length, crd - box_length, crd)\n    return crd\n\n\ndef find_atom_in_grid_serial(grid_length_inverse, crd, grid_N, Nxy, atom_in_grid_serial):\n    grid_idx = (crd * grid_length_inverse).astype(np.int32)\n    grid_idx = np.where(grid_idx < grid_N, grid_idx, 0)\n    atom_in_grid_serial = grid_idx[..., 2] * Nxy + grid_idx[..., 1] * grid_N[0] + grid_idx[..., 0]\n    return atom_in_grid_serial\n\n\ndef neighbor_list_update(\n        grid_numbers, atom_numbers, not_first_time, Nxy, excluded_atom_numbers,\n        cutoff_square, half_skin_square, cutoff_with_skin, half_cutoff_with_skin, cutoff_with_skin_square,\n        refresh_interval, cutoff, skin, max_atom_in_grid_numbers, max_neighbor_numbers,\n        atom_numbers_in_grid_bucket, bucket, crd, box_length, grid_N, grid_length_inverse, atom_in_grid_serial,\n        old_crd, crd_to_uint_crd_cof, uint_crd, gpointer, nl_atom_numbers, nl_atom_serial, uint_dr_to_dr_cof,\n        not_excluded, need_refresh_flag, refresh_count):\n    \"\"\"\n    Update (or construct if first time) the Verlet neighbor list for the\n    calculation of short-ranged force. Assume the number of atoms is n,\n    the number of grids divided is G, the maximum number of atoms in one\n    grid is m, the maximum number of atoms in single atom's neighbor list\n    is L, and the number of total atom in excluded list is E.\n\n    Args:\n        grid_numbers (int32): the total number of grids divided.\n        not_first_time (int32): whether to construct the neighbor\n            list first time or not.\n        Nxy (int32): the total number of grids divided in xy plane.\n        excluded_atom_numbers (int32): the total atom numbers in the excluded list.\n        cutoff (float32): the cutoff distance for short-range force calculation. Default: 10.0.\n        skin (float32): the overflow value of cutoff to maintain a neighbor list. Default: 2.0.\n        cutoff_square (float32): the suqare value of cutoff.\n        half_skin_square (float32): skin*skin/4, indicates the maximum\n            square value of the distance atom allowed to move between two updates.\n        cutoff_with_skin (float32): cutoff + skin, indicates the\n            radius of the neighbor list for each atom.\n        half_cutoff_with_skin (float32): cutoff_with_skin/2.\n        cutoff_with_skin_square (float32): the square value of cutoff_with_skin.\n        refresh_interval (int32): the number of iteration steps between two updates of neighbor\n            list. Default: 20.\n        max_atom_in_grid_numbers (int32): the maximum number of atoms in one grid. Default: 64.\n        max_neighbor_numbers (int32): The maximum number of neighbors. Default: 800.\n        atom_numbers_in_grid_bucket (Tensor, int32) - [G,], the number of atoms in each grid bucket.\n        bucket (Tensor, int32) - (Tensor,int32) - [G, m], the atom indices in each grid bucket.\n        crd (Tensor, float32) - [n,], the coordinates of each atom.\n        box_length (Tensor, float32) - [3,], the length of 3 dimensions of the simulation box.\n        grid_n (Tensor, int32) - [3,], the number of grids divided of 3 dimensions of the\n            simulation box.\n        grid_length_inverse (float32) - the inverse value of grid length.\n        atom_in_grid_serial (Tensor, int32) - [n,], the grid index for each atom.\n        old_crd (Tensor, float32) - [n, 3], the coordinates before update of each atom.\n        crd_to_uint_crd_cof (Tensor, float32) - [3,], the scale factor\n            between the unsigned int value and the real space coordinates.\n        uint_crd (Tensor, uint32) - [n, 3], the unsigned int coordinates value fo each atom.\n        gpointer (Tensor, int32) - [G, 125], the 125 nearest neighbor grids (including self) of each\n            grid. G is the number of nearest neighbor grids.\n        nl_atom_numbers (Tensor, int32) - [n,], the number of atoms in neighbor list of each atom.\n        nl_atom_serial (Tensor, int32) - [n, L], the indices of atoms in neighbor list of each atom.\n        uint_dr_to_dr_cof (Tensor, float32) - [3,], the scale factor between\n            the real space coordinates and the unsigned int value.\n        excluded_list_start (Tensor, int32) - [n,], the start excluded index in excluded list for\n            each atom.\n        excluded_numbers (Tensor, int32) - [n,], the number of atom excluded in excluded list for\n            each atom.\n        not_excluded (Tensor, bool) - [n, n], marking the excluded atoms for each atom, where each\n            element ij indicates whether atom j is not excluded for atom i.\n        need_refresh_flag (Tensor, int32) - [n,], whether the neighbor list of each atom need update\n            or not.\n        refresh_count (Tensor, int32) - [1,], count how many iteration steps have passed since last\n            update.\n\n    Outputs:\n        nl_atom_numbers (Tensor, int32) - [n,], the number of atoms in neighbor list of each atom.\n        nl_atom_serial (Tensor, int32) - [n, L], the indices of atoms in neighbor list of each atom.\n        crd (Tensor, float32) - [n,], the coordinates of each atom.\n        old_crd (Tensor, float32) - [n, 3], the coordinates before update of each atom.\n        need_refresh_flag (Tensor, int32) - [n,], whether the neighbor list of each atom need update\n            or not.\n        refresh_count (Tensor, int32) - [1,], count how many iteration steps have passed since last\n            update.\n\n    Supported Platforms:\n        ``GPU``\n    \"\"\"\n    half_crd_to_uint_crd_cof = 0.5 * crd_to_uint_crd_cof\n    if not_first_time:\n        if refresh_interval > 0:\n            refresh_cond = (refresh_count % refresh_interval) == 0\n            trans_vec = np.full(3, -skin, np.float32)\n            crd = np.where(refresh_cond, crd + trans_vec, crd)\n            crd = np.where(refresh_cond, crd_periodic_map(crd, box_length), crd)\n            crd = np.where(refresh_cond, crd - trans_vec, crd)\n            old_crd = np.where(refresh_cond, crd, old_crd)\n\n            uint_crd = np.where(refresh_cond,\n                                crd_to_uint_crd(half_crd_to_uint_crd_cof, crd).astype(np.int32),\n                                uint_crd.astype(np.int32)).astype(np.uint32)\n\n            nl_mask = find_atom_neighbors(\n                atom_numbers, uint_crd, uint_dr_to_dr_cof, cutoff_square)\n\n            nl_atom_numbers_updated, nl_atom_serial_updated = delete_excluded_atoms_serial_in_neighbor_list(\n                atom_numbers, max_neighbor_numbers, nl_mask, not_excluded)\n            nl_atom_numbers = np.where(refresh_cond, nl_atom_numbers_updated, nl_atom_numbers)\n            nl_atom_serial = np.where(refresh_cond, nl_atom_serial_updated, nl_atom_serial)\n\n            refresh_count += 1\n        else:\n            r1 = crd - old_crd\n            r1_2 = np.sum(r1, -1)\n            if (r1_2 > half_skin_square).any():\n                trans_vec = np.full(3, skin, np.float32)\n                crd += trans_vec\n                crd = crd_periodic_map(crd, box_length)\n                crd -= trans_vec\n                old_crd[...] = crd\n\n                uint_crd = crd_to_uint_crd(half_crd_to_uint_crd_cof, crd)\n\n                nl_mask = find_atom_neighbors(\n                    atom_numbers, uint_crd, uint_dr_to_dr_cof, cutoff_with_skin_square)\n\n                nl_atom_numbers, nl_atom_serial = delete_excluded_atoms_serial_in_neighbor_list(\n                    atom_numbers, max_neighbor_numbers, nl_mask, not_excluded)\n\n                need_refresh_flag[0] = 0\n    else:\n        trans_vec = np.full(3, skin, np.float32)\n        crd = crd_periodic_map(crd, box_length)\n        crd += trans_vec\n        old_crd[...] = crd\n\n        uint_crd = crd_to_uint_crd(half_crd_to_uint_crd_cof, crd)\n\n        nl_mask = find_atom_neighbors(\n            atom_numbers, uint_crd, uint_dr_to_dr_cof, cutoff_with_skin_square)\n\n        nl_atom_numbers, nl_atom_serial = delete_excluded_atoms_serial_in_neighbor_list(\n            atom_numbers, max_neighbor_numbers, nl_mask, not_excluded)\n\n    return nl_atom_numbers, nl_atom_serial, crd, old_crd, need_refresh_flag, refresh_count\n", "meta": {"hexsha": "eda9ac250e012667f4254aea2cb48b90782836a4", "size": 10292, "ext": "py", "lang": "Python", "max_stars_repo_path": "MindSPONGE/mindsponge/md/functions/neighbor_list_update.py", "max_stars_repo_name": "mindspore-ai/mindscience", "max_stars_repo_head_hexsha": "b5269245915695de2d99fb290fef662c241db189", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-11-10T06:17:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T14:25:30.000Z", "max_issues_repo_path": "MindSPONGE/mindsponge/md/functions/neighbor_list_update.py", "max_issues_repo_name": "mindspore-ai/mindscience", "max_issues_repo_head_hexsha": "b5269245915695de2d99fb290fef662c241db189", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MindSPONGE/mindsponge/md/functions/neighbor_list_update.py", "max_forks_repo_name": "mindspore-ai/mindscience", "max_forks_repo_head_hexsha": "b5269245915695de2d99fb290fef662c241db189", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-05T11:41:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-05T11:41:29.000Z", "avg_line_length": 52.7794871795, "max_line_length": 111, "alphanum_fraction": 0.6815001943, "include": true, "reason": "import numpy", "num_tokens": 2545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.30404168127272885, "lm_q1q2_score": 0.1813405365570801}}
{"text": "#This class is exactly like neural transfer however within a class\n\"\"\"\nCreated on Sun Jul 12 21:53:59 2020\n@author: kun-je, Adanna Obibuaku\nNST project in spyder\nThisis project is done using \"A Neural Algorithm of Artistic Style\nby. Leon A. Gatys,  Alexander S. Ecker, Matthias Bethge\" as a reference\n\"\"\"\nimport os\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow.keras.preprocessing.image as img\nfrom tensorflow.keras.applications.vgg19 import decode_predictions\nfrom tensorflow.keras.applications.vgg19 import VGG19\nfrom tensorflow.keras.applications.vgg19 import preprocess_input\n\n\nPATH =  os.path.dirname(__file__)\nMAIN_PATH =  os.path.join(PATH, \"static/utils/\")\nMODEL = VGG19()\nIMG_WIDTH = 224\nIMG_HEIGHT = 224\nLEARNING_RATE = 0.2\nCHANNEL = 3\n\nclass Neural():\n\n    def __init__(self, alpha, beta, content_layers, style_layers, style_path, content_path, **kwargs):\n        self.alpha = alpha\n        self.beta = beta\n        self.content_layers = content_layers\n        self.style_layers = style_layers\n        self.content_path = content_path\n        self.style_path = style_path\n    \n        self.style_path = os.path.join(MAIN_PATH, self.style_path)\n        self.content_path = os.path.join(MAIN_PATH, 'input', self.content_path)\n        self.c_image, self.g_image, self.s_image = self.tensor_inputs(self.content_path, self.content_path, self.style_path)\n        \n    def load_image(self, image_path):\n        \"\"\"\n            Description:\n                As we are using a pre-trained version VGG16 we have to resize and normalise\n                the inputs.\n            Args:\n                image_path (str): This takes a given an image path\n            Returns:\n                <class 'numpy.ndarray'> : This would convert the given image into array\n                <class 'PIL.Image.Image'>: This would convert the given image into PIL format\n        \"\"\"\n        image_array = img.load_img(image_path, target_size=(IMG_HEIGHT, IMG_WIDTH))\n        image = img.img_to_array(image_array)\n        image = image.reshape((1, IMG_HEIGHT, IMG_WIDTH, CHANNEL))\n        image = preprocess_input(image)\n        return tf.convert_to_tensor(image), image_array\n\n    def tensor_inputs(self, c_image_path, g_image_path, s_image_path):\n        \"\"\"\n            Description:\n                This is used to take return the tensor image of our content image,\n                generate image and style image\n            Args:\n                c_image_path ():\n                g_image_path ():\n                s_image_path ():\n            Returns:\n        \"\"\"\n        c_image = self.load_image(c_image_path)[0]\n        g_image = self.load_image(g_image_path)[0]\n        s_image = self.load_image(s_image_path)[0]\n        return c_image, g_image, s_image\n    \n    def deprocess_img(self, image):\n        \"\"\"\n            Description:\n                This is used to reverse the depressing of the image. This is used in order\n                to get the image.\n            Args:\n                image (<class 'numpy.ndarray'>) : Take in the given image in a preprocess format\n            Returns:\n        \"\"\"\n        temp_image = image\n        temp_image = temp_image[0] # Gets one image, from samples\n        temp_image = temp_image.reshape((IMG_HEIGHT, IMG_WIDTH, CHANNEL)) # converts it into 3-dimentions\n        temp_image[:,:,0] += 103.939 #This adds the mean rgb back to the image, which the preprocess to off\n        temp_image[:,:,1] += 116.779\n        temp_image[:,:,2] += 123.68\n        temp_image = temp_image[:,:,::-1]\n        temp_image = np.clip(temp_image, 0, 255)\n        return temp_image.astype('uint8')\n\n    def save_image(self, file_name, array_image):\n        \"\"\"\n            Description:\n                This saves a given tensor image and saves the generated file into\n                an output folder\n            Args:\n                file_name (string): This takes in the given file name\n                array_image (): This takes in the given array\n        \"\"\"\n        file_name = os.path.join(MAIN_PATH, \"output/\", file_name)\n        img.save_img(file_name, self.deprocess_img(array_image))\n        return True\n\n    def MSE(self, matrix_content, matrix_generated):\n        \"\"\"\n            Args:\n                matrix_content (<class 'numpy.ndarray'>):\n                matrix_generated (<class 'numpy.ndarray'>):\n            Returns:\n                int: A number made by perform substraction operation from each matrix (tensor), followed by\n                    squared operation with each substraction operation. The operation reduce mean is then applied.\n        \"\"\"\n        return tf.reduce_mean(tf.square(matrix_content - matrix_generated))\n    \n    def get_layer(self, c_image, s_image, g_image, layer_name):\n        \"\"\"\n            Description:\n                This returns the activation of the input image.\n            Args:\n                image (<class 'numpy.ndarray'>): A given image array\n                layer_name (str): A given layer name within the cnn model\n            Returns:\n\n                <class 'numpy.ndarray'> :\n        \"\"\"\n        tensor_image = tf.concat([c_image, s_image, g_image], axis = 0) #put images within one array\n        layer = tf.keras.Model(inputs=MODEL.inputs, outputs=MODEL.get_layer(layer_name).output)\n        feature = layer(tensor_image) #This will return the activations of the function\n        return feature\n\n    def get_feature(self, c_image, s_image, g_image, layer_name):\n        \"\"\"\n            Description:\n                This function takes in the tensor repersentations c_image, s_image and g_image\n                and returns their feauture activations.\n            Args:\n                c_image (): This is a tensor repersentation of the content image\n                s_image (): This is a tensor repersentation of the style image\n                g_image (): This is a tensor repersentation of the generated image\n            Returns:\n                : features of content image\n                : features of style image\n                : features of generated image\n\n\n        \"\"\"\n        layer_feature = self.get_layer(c_image, s_image, g_image, layer_name)\n        c_feature = layer_feature[0, :, :, :]\n        s_feature = layer_feature[1, :, :, :]\n        g_feature = layer_feature[2, :, :, :]\n        return c_feature, s_feature, g_feature\n\n\n    def content_loss_function(self, c_feature, g_feature):\n        #todo need to change doc string as type was changed\n        \"\"\"\n            Args:\n                layer_name (str): To take in the layer name\n\n            Returns:\n                int: The loss content. A low integer denotes the content is similar\n                to the generated image. A high integer denotes the content is not similar\n                to the generated image\n        \"\"\"\n        WEIGHT = 0.5\n        loss = self.MSE(g_feature, c_feature)\n        return WEIGHT*loss\n\n\n    def gram_matrix(self, tensor):\n        \"\"\"\n            Args:\n                tensor (tensor): take 3D tensor\n            Returns:\n                gram (tensor) : gram matrix which is 2D array of the multiplication\n                of the reshape matrix and its transpose\n        \"\"\"\n        m_shape = []\n        m_shape.append(tensor.shape[2])\n        m_shape.append(tensor.shape[0]*tensor.shape[1])\n        tensor = tf.reshape(tensor,m_shape)\n        gram = tf.matmul(tensor,tf.transpose(tensor))\n        return gram\n\n\n\n    def style_loss_function(self, s_feature, g_feature):\n        \"\"\"\n            Args:\n                c_image_path (str): To take the style image path\n                g_image_path (str): To take the generate image path\n            Returns:\n                int: The loss content. A low integer denotes the content is similar\n                to the generated image. A high integer denotes the content is not similar\n                to the generated image\n        \"\"\"\n\n        #finding gram matrix of s and g image from perticular layer\n        generated_gram = self.gram_matrix(g_feature)\n        style_gram = self.gram_matrix(s_feature)\n\n        img_size = IMG_HEIGHT * IMG_WIDTH\n\n        loss = self.MSE(generated_gram, style_gram)/(4*(CHANNEL**2)*(img_size**2))\n        return loss\n\n    def total_loss_function(self, c_image,s_image,g_image,alpha,beta):\n        \"\"\"\n            Args:\n                c_image_path (str): To take the content image path\n                s_image_path (str): To take the style image path\n                g_image_path (str): To take the generate image path\n            Returns:\n                int: The totoal loss of style and content.\n        \"\"\"\n        content_loss = 0\n        c_feature, s_feature, g_feature = self.get_feature(c_image, s_image, g_image, self.content_layers[0]) \n        content_loss += self.content_loss_function(c_feature, g_feature)\n\n        style_loss = 0\n        for layer in self.style_layers:\n            c_feature, s_feature, g_feature = self.get_feature(c_image, s_image, g_image, layer) \n            style_loss += self.style_loss_function(s_feature, g_feature)\n\n        content_loss *= alpha\n        style_loss *= beta\n\n        #total loss\n        loss = style_loss + content_loss\n        return loss\n\n    def gradient_total_loss(self, c_image, s_image, g_image, alpha, beta):\n        \"\"\"\n            Description:\n                The purpose of this function is to find the current gradient at \n                the generate image variable (g_image),\n            Args:\n                c_image ():\n                s_image ():\n                g_image ():\n            Returns:    \n        \"\"\"\n        with tf.GradientTape() as tape:\n            tape.watch(g_image)\n            loss =  self.total_loss_function(c_image,s_image,g_image,alpha,beta)\n        dy_dx = tape.gradient(loss, g_image)\n        return loss, dy_dx\n\n    def regression_total_loss(self):\n            \"\"\"\n                Description:\n                    The purpose of this is to use an optimization algorthium called gradient \n                    descent to minimise our loss function (total loss function) in the direction\n                    of the steepest descent. In other words where the graph is at its lowest point.\n                    In this circumstances we want c_image, s_image to remain static while within \n                    every loop we countisouly change g_image to minimise the loss of our total loss function.\n                Args:\n                    c_image ()\n                    s_image ()\n                    g_image ()\n                Returns \n\n            \"\"\"\n            opt = tf.keras.optimizers.Adam(learning_rate=0.2)\n            self.g_image  = tf.Variable(self.g_image) \n            iteration = 8000\n            for _ in range(iteration+1):\n                loss, dy_dx = self.gradient_total_loss(self.c_image, self.s_image, self.g_image, self.alpha, self.beta)\n                print(\"\\t Iteration: %d\\t Loss: %f\" % (_, loss)) \n                opt.apply_gradients([(dy_dx, self.g_image)]) # Apply gradient to varaiable\n                if _ % 10 == 0:\n                    fname = \"img_%d.jpg\" % (_)\n                    self.save_image(fname, self.g_image.numpy())\n", "meta": {"hexsha": "f81b212c8357e92afb4a14554cfa4ec4d710a74c", "size": 11130, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/style_transfer.py", "max_stars_repo_name": "runnily/Style-transfer-django", "max_stars_repo_head_hexsha": "75dbc049ea7c357b94ec2be599a06bda9f491fac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-08T21:38:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-08T21:38:13.000Z", "max_issues_repo_path": "utils/style_transfer.py", "max_issues_repo_name": "runnily/Style-transfer-django", "max_issues_repo_head_hexsha": "75dbc049ea7c357b94ec2be599a06bda9f491fac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-10-11T13:13:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-21T23:46:34.000Z", "max_forks_repo_path": "utils/style_transfer.py", "max_forks_repo_name": "runnily/Style-Transfer-Django", "max_forks_repo_head_hexsha": "75dbc049ea7c357b94ec2be599a06bda9f491fac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4727272727, "max_line_length": 124, "alphanum_fraction": 0.5977538185, "include": true, "reason": "import numpy", "num_tokens": 2355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.1811285886329533}}
{"text": "#  MINLP written by GAMS Convert at 04/21/18 13:52:42\n#  \n#  Equation counts\n#      Total        E        G        L        N        X        C        B\n#        318      234        0       84        0        0        0        0\n#  \n#  Variable counts\n#                   x        b        i      s1s      s2s       sc       si\n#      Total     cont   binary  integer     sos1     sos2    scont     sint\n#        352      184      168        0        0        0        0        0\n#  FX      0        0        0        0        0        0        0        0\n#  \n#  Nonzero counts\n#      Total    const       NL      DLL\n#       3385      521     2864        0\n# \n#  Reformulation has removed 1 variable and 1 equation\n\n\nfrom pyomo.environ import *\n\nmodel = m = ConcreteModel()\n\n\nm.x1 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x2 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x3 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x4 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x5 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x6 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x7 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x8 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x9 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x10 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x11 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x12 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x13 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x14 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x15 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x16 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x17 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x18 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x19 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x20 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x21 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x22 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x23 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x24 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x25 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x26 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x27 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x28 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x29 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x30 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x31 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x32 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x33 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x34 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x35 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x36 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x37 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x38 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x39 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x40 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x41 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x42 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x43 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x44 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x45 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x46 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x47 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x48 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x49 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x50 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x51 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x52 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x53 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x54 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x55 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x56 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x57 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x58 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x59 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x60 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x61 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x62 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x63 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x64 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x65 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x66 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x67 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x68 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x69 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x70 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x71 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x72 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x73 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x74 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x75 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x76 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x77 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x78 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x79 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x80 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x81 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x82 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x83 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x84 = Var(within=Reals,bounds=(0,None),initialize=0.0892857142857143)\nm.x85 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x86 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x87 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x88 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x89 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x90 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x91 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x92 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x93 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x94 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x95 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x96 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x97 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x98 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x99 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x100 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x101 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x102 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x103 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x104 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x105 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x106 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x107 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x108 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x109 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x110 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x111 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x112 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x113 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x114 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x115 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x116 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x117 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x118 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x119 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x120 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x121 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x122 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x123 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x124 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x125 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x126 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x127 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x128 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x129 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x130 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x131 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x132 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x133 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x134 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x135 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x136 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x137 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x138 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x139 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x140 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x141 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x142 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x143 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x144 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x145 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x146 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x147 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x148 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x149 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x150 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x151 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x152 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x153 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x154 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x155 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x156 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x157 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x158 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x159 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x160 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x161 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x162 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x163 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x164 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x165 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x166 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x167 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x168 = Var(within=Reals,bounds=(0,None),initialize=1.25)\nm.x169 = Var(within=Reals,bounds=(0,None),initialize=0.956145)\nm.x170 = Var(within=Reals,bounds=(0,None),initialize=0.956145)\nm.x171 = Var(within=Reals,bounds=(0,None),initialize=0.956145)\nm.x172 = Var(within=Reals,bounds=(0,None),initialize=0.956145)\nm.x173 = Var(within=Reals,bounds=(0,None),initialize=0.956145)\nm.x174 = Var(within=Reals,bounds=(0,None),initialize=0.956145)\nm.b175 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b176 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b177 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b178 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b179 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b180 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b181 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b182 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b183 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b184 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b185 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b186 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b187 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b188 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b189 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b190 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b191 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b192 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b193 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b194 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b195 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b196 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b197 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b198 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b199 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b200 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b201 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b202 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b203 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b204 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b205 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b206 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b207 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b208 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b209 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b210 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b211 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b212 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b213 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b214 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b215 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b216 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b217 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b218 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b219 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b220 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b221 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b222 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b223 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b224 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b225 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b226 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b227 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b228 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b229 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b230 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b231 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b232 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b233 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b234 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b235 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b236 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b237 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b238 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b239 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b240 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b241 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b242 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b243 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b244 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b245 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b246 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b247 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b248 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b249 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b250 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b251 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b252 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b253 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b254 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b255 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b256 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b257 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b258 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b259 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b260 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b261 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b262 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b263 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b264 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b265 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b266 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b267 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b268 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b269 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b270 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b271 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b272 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b273 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b274 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b275 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b276 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b277 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b278 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b279 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b280 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b281 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b282 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b283 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b284 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b285 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b286 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b287 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b288 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b289 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b290 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b291 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b292 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b293 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b294 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b295 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b296 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b297 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b298 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b299 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b300 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b301 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b302 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b303 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b304 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b305 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b306 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b307 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b308 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b309 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b310 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b311 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b312 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b313 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b314 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b315 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b316 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b317 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b318 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b319 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b320 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b321 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b322 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b323 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b324 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b325 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b326 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b327 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b328 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b329 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b330 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b331 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b332 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b333 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b334 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b335 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b336 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b337 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b338 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b339 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b340 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b341 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.b342 = Var(within=Binary,bounds=(0,1),initialize=0.0714285714285714)\nm.x344 = Var(within=Reals,bounds=(None,None),initialize=0)\nm.x345 = Var(within=Reals,bounds=(None,None),initialize=0)\nm.x346 = Var(within=Reals,bounds=(None,None),initialize=0)\nm.x347 = Var(within=Reals,bounds=(None,None),initialize=0)\nm.x348 = Var(within=Reals,bounds=(None,None),initialize=0)\nm.x349 = Var(within=Reals,bounds=(None,None),initialize=0)\nm.x350 = Var(within=Reals,bounds=(None,None),initialize=0)\nm.x351 = Var(within=Reals,bounds=(None,None),initialize=0)\nm.x352 = Var(within=Reals,bounds=(None,None),initialize=0)\n\nm.obj = Objective(expr= - m.x174, sense=minimize)\n\nm.c2 = Constraint(expr=   0.5*m.b175 + m.b187 + m.b199 + m.b211 + m.b223 + m.b235 + 0.5*m.b247 + m.b259 + m.b271\n                        + m.b283 + 0.5*m.b295 + m.b307 + m.b319 + 0.5*m.b331 == 1)\n\nm.c3 = Constraint(expr=   0.5*m.b176 + m.b188 + m.b200 + m.b212 + m.b224 + m.b236 + 0.5*m.b248 + m.b260 + m.b272\n                        + m.b284 + 0.5*m.b296 + m.b308 + m.b320 + 0.5*m.b332 == 1)\n\nm.c4 = Constraint(expr=   0.5*m.b177 + m.b189 + m.b201 + m.b213 + m.b225 + m.b237 + 0.5*m.b249 + m.b261 + m.b273\n                        + m.b285 + 0.5*m.b297 + m.b309 + m.b321 + 0.5*m.b333 == 1)\n\nm.c5 = Constraint(expr=   0.5*m.b178 + m.b190 + m.b202 + m.b214 + m.b226 + m.b238 + 0.5*m.b250 + m.b262 + m.b274\n                        + m.b286 + 0.5*m.b298 + m.b310 + m.b322 + 0.5*m.b334 == 1)\n\nm.c6 = Constraint(expr=   0.5*m.b179 + m.b191 + m.b203 + m.b215 + m.b227 + m.b239 + 0.5*m.b251 + m.b263 + m.b275\n                        + m.b287 + 0.5*m.b299 + m.b311 + m.b323 + 0.5*m.b335 == 1)\n\nm.c7 = Constraint(expr=   0.5*m.b180 + m.b192 + m.b204 + m.b216 + m.b228 + m.b240 + 0.5*m.b252 + m.b264 + m.b276\n                        + m.b288 + 0.5*m.b300 + m.b312 + m.b324 + 0.5*m.b336 == 1)\n\nm.c8 = Constraint(expr=   0.5*m.b181 + m.b193 + m.b205 + m.b217 + m.b229 + m.b241 + 0.5*m.b253 + m.b265 + m.b277\n                        + m.b289 + 0.5*m.b301 + m.b313 + m.b325 + 0.5*m.b337 == 1)\n\nm.c9 = Constraint(expr=   0.5*m.b182 + m.b194 + m.b206 + m.b218 + m.b230 + m.b242 + 0.5*m.b254 + m.b266 + m.b278\n                        + m.b290 + 0.5*m.b302 + m.b314 + m.b326 + 0.5*m.b338 == 1)\n\nm.c10 = Constraint(expr=   0.5*m.b183 + m.b195 + m.b207 + m.b219 + m.b231 + m.b243 + 0.5*m.b255 + m.b267 + m.b279\n                         + m.b291 + 0.5*m.b303 + m.b315 + m.b327 + 0.5*m.b339 == 1)\n\nm.c11 = Constraint(expr=   0.5*m.b184 + m.b196 + m.b208 + m.b220 + m.b232 + m.b244 + 0.5*m.b256 + m.b268 + m.b280\n                         + m.b292 + 0.5*m.b304 + m.b316 + m.b328 + 0.5*m.b340 == 1)\n\nm.c12 = Constraint(expr=   0.5*m.b185 + m.b197 + m.b209 + m.b221 + m.b233 + m.b245 + 0.5*m.b257 + m.b269 + m.b281\n                         + m.b293 + 0.5*m.b305 + m.b317 + m.b329 + 0.5*m.b341 == 1)\n\nm.c13 = Constraint(expr=   0.5*m.b186 + m.b198 + m.b210 + m.b222 + m.b234 + m.b246 + 0.5*m.b258 + m.b270 + m.b282\n                         + m.b294 + 0.5*m.b306 + m.b318 + m.b330 + 0.5*m.b342 == 1)\n\nm.c14 = Constraint(expr=   m.b175 + m.b176 + m.b177 + m.b178 + m.b179 + m.b180 + m.b181 + m.b182 + m.b183 + m.b184\n                         + m.b185 + m.b186 == 1)\n\nm.c15 = Constraint(expr=   m.b187 + m.b188 + m.b189 + m.b190 + m.b191 + m.b192 + m.b193 + m.b194 + m.b195 + m.b196\n                         + m.b197 + m.b198 == 1)\n\nm.c16 = Constraint(expr=   m.b199 + m.b200 + m.b201 + m.b202 + m.b203 + m.b204 + m.b205 + m.b206 + m.b207 + m.b208\n                         + m.b209 + m.b210 == 1)\n\nm.c17 = Constraint(expr=   m.b211 + m.b212 + m.b213 + m.b214 + m.b215 + m.b216 + m.b217 + m.b218 + m.b219 + m.b220\n                         + m.b221 + m.b222 == 1)\n\nm.c18 = Constraint(expr=   m.b223 + m.b224 + m.b225 + m.b226 + m.b227 + m.b228 + m.b229 + m.b230 + m.b231 + m.b232\n                         + m.b233 + m.b234 == 1)\n\nm.c19 = Constraint(expr=   m.b235 + m.b236 + m.b237 + m.b238 + m.b239 + m.b240 + m.b241 + m.b242 + m.b243 + m.b244\n                         + m.b245 + m.b246 == 1)\n\nm.c20 = Constraint(expr=   m.b247 + m.b248 + m.b249 + m.b250 + m.b251 + m.b252 + m.b253 + m.b254 + m.b255 + m.b256\n                         + m.b257 + m.b258 == 1)\n\nm.c21 = Constraint(expr=   m.b259 + m.b260 + m.b261 + m.b262 + m.b263 + m.b264 + m.b265 + m.b266 + m.b267 + m.b268\n                         + m.b269 + m.b270 == 1)\n\nm.c22 = Constraint(expr=   m.b271 + m.b272 + m.b273 + m.b274 + m.b275 + m.b276 + m.b277 + m.b278 + m.b279 + m.b280\n                         + m.b281 + m.b282 == 1)\n\nm.c23 = Constraint(expr=   m.b283 + m.b284 + m.b285 + m.b286 + m.b287 + m.b288 + m.b289 + m.b290 + m.b291 + m.b292\n                         + m.b293 + m.b294 == 1)\n\nm.c24 = Constraint(expr=   m.b295 + m.b296 + m.b297 + m.b298 + m.b299 + m.b300 + m.b301 + m.b302 + m.b303 + m.b304\n                         + m.b305 + m.b306 == 1)\n\nm.c25 = Constraint(expr=   m.b307 + m.b308 + m.b309 + m.b310 + m.b311 + m.b312 + m.b313 + m.b314 + m.b315 + m.b316\n                         + m.b317 + m.b318 == 1)\n\nm.c26 = Constraint(expr=   m.b319 + m.b320 + m.b321 + m.b322 + m.b323 + m.b324 + m.b325 + m.b326 + m.b327 + m.b328\n                         + m.b329 + m.b330 == 1)\n\nm.c27 = Constraint(expr=   m.b331 + m.b332 + m.b333 + m.b334 + m.b335 + m.b336 + m.b337 + m.b338 + m.b339 + m.b340\n                         + m.b341 + m.b342 == 1)\n\nm.c28 = Constraint(expr=-(m.b178*m.x344 + m.b179*m.x345 + m.b180*m.x346 + m.b181*m.x347 + m.b182*m.x348 + m.b183*m.x349\n                         + m.b184*m.x350 + m.b185*m.x351 + m.b186*m.x352) + m.x85 - 1.25*m.b175 - 1.25*m.b176\n                         - 1.25*m.b177 == 0)\n\nm.c29 = Constraint(expr=-(m.b190*m.x344 + m.b191*m.x345 + m.b192*m.x346 + m.b193*m.x347 + m.b194*m.x348 + m.b195*m.x349\n                         + m.b196*m.x350 + m.b197*m.x351 + m.b198*m.x352) + m.x91 - 1.25*m.b187 - 1.25*m.b188\n                         - 1.25*m.b189 == 0)\n\nm.c30 = Constraint(expr=-(m.b202*m.x344 + m.b203*m.x345 + m.b204*m.x346 + m.b205*m.x347 + m.b206*m.x348 + m.b207*m.x349\n                         + m.b208*m.x350 + m.b209*m.x351 + m.b210*m.x352) + m.x97 - 1.25*m.b199 - 1.25*m.b200\n                         - 1.25*m.b201 == 0)\n\nm.c31 = Constraint(expr=-(m.b214*m.x344 + m.b215*m.x345 + m.b216*m.x346 + m.b217*m.x347 + m.b218*m.x348 + m.b219*m.x349\n                         + m.b220*m.x350 + m.b221*m.x351 + m.b222*m.x352) + m.x103 - 1.25*m.b211 - 1.25*m.b212\n                         - 1.25*m.b213 == 0)\n\nm.c32 = Constraint(expr=-(m.b226*m.x344 + m.b227*m.x345 + m.b228*m.x346 + m.b229*m.x347 + m.b230*m.x348 + m.b231*m.x349\n                         + m.b232*m.x350 + m.b233*m.x351 + m.b234*m.x352) + m.x109 - 1.25*m.b223 - 1.25*m.b224\n                         - 1.25*m.b225 == 0)\n\nm.c33 = Constraint(expr=-(m.b238*m.x344 + m.b239*m.x345 + m.b240*m.x346 + m.b241*m.x347 + m.b242*m.x348 + m.b243*m.x349\n                         + m.b244*m.x350 + m.b245*m.x351 + m.b246*m.x352) + m.x115 - 1.25*m.b235 - 1.25*m.b236\n                         - 1.25*m.b237 == 0)\n\nm.c34 = Constraint(expr=-(m.b250*m.x344 + m.b251*m.x345 + m.b252*m.x346 + m.b253*m.x347 + m.b254*m.x348 + m.b255*m.x349\n                         + m.b256*m.x350 + m.b257*m.x351 + m.b258*m.x352) + m.x121 - 1.25*m.b247 - 1.25*m.b248\n                         - 1.25*m.b249 == 0)\n\nm.c35 = Constraint(expr=-(m.b262*m.x344 + m.b263*m.x345 + m.b264*m.x346 + m.b265*m.x347 + m.b266*m.x348 + m.b267*m.x349\n                         + m.b268*m.x350 + m.b269*m.x351 + m.b270*m.x352) + m.x127 - 1.25*m.b259 - 1.25*m.b260\n                         - 1.25*m.b261 == 0)\n\nm.c36 = Constraint(expr=-(m.b274*m.x344 + m.b275*m.x345 + m.b276*m.x346 + m.b277*m.x347 + m.b278*m.x348 + m.b279*m.x349\n                         + m.b280*m.x350 + m.b281*m.x351 + m.b282*m.x352) + m.x133 - 1.25*m.b271 - 1.25*m.b272\n                         - 1.25*m.b273 == 0)\n\nm.c37 = Constraint(expr=-(m.b286*m.x344 + m.b287*m.x345 + m.b288*m.x346 + m.b289*m.x347 + m.b290*m.x348 + m.b291*m.x349\n                         + m.b292*m.x350 + m.b293*m.x351 + m.b294*m.x352) + m.x139 - 1.25*m.b283 - 1.25*m.b284\n                         - 1.25*m.b285 == 0)\n\nm.c38 = Constraint(expr=-(m.b298*m.x344 + m.b299*m.x345 + m.b300*m.x346 + m.b301*m.x347 + m.b302*m.x348 + m.b303*m.x349\n                         + m.b304*m.x350 + m.b305*m.x351 + m.b306*m.x352) + m.x145 - 1.25*m.b295 - 1.25*m.b296\n                         - 1.25*m.b297 == 0)\n\nm.c39 = Constraint(expr=-(m.b310*m.x344 + m.b311*m.x345 + m.b312*m.x346 + m.b313*m.x347 + m.b314*m.x348 + m.b315*m.x349\n                         + m.b316*m.x350 + m.b317*m.x351 + m.b318*m.x352) + m.x151 - 1.25*m.b307 - 1.25*m.b308\n                         - 1.25*m.b309 == 0)\n\nm.c40 = Constraint(expr=-(m.b322*m.x344 + m.b323*m.x345 + m.b324*m.x346 + m.b325*m.x347 + m.b326*m.x348 + m.b327*m.x349\n                         + m.b328*m.x350 + m.b329*m.x351 + m.b330*m.x352) + m.x157 - 1.25*m.b319 - 1.25*m.b320\n                         - 1.25*m.b321 == 0)\n\nm.c41 = Constraint(expr=-(m.b334*m.x344 + m.b335*m.x345 + m.b336*m.x346 + m.b337*m.x347 + m.b338*m.x348 + m.b339*m.x349\n                         + m.b340*m.x350 + m.b341*m.x351 + m.b342*m.x352) + m.x163 - 1.25*m.b331 - 1.25*m.b332\n                         - 1.25*m.b333 == 0)\n\nm.c42 = Constraint(expr=0.701*m.x85*m.x1 + 0.2*m.x91*m.x7 + 0.023*m.x97*m.x13 + 0.007*m.x103*m.x19 + 0.039*m.x121*m.x37\n                         + 0.02*m.x127*m.x43 + 0.003*m.x145*m.x61 - m.x1*m.x169 == 0)\n\nm.c43 = Constraint(expr=0.701*m.x86*m.x2 + 0.2*m.x92*m.x8 + 0.023*m.x98*m.x14 + 0.007*m.x104*m.x20 + 0.039*m.x122*m.x38\n                         + 0.02*m.x128*m.x44 + 0.003*m.x146*m.x62 - m.x2*m.x170 == 0)\n\nm.c44 = Constraint(expr=0.701*m.x87*m.x3 + 0.2*m.x93*m.x9 + 0.023*m.x99*m.x15 + 0.007*m.x105*m.x21 + 0.039*m.x123*m.x39\n                         + 0.02*m.x129*m.x45 + 0.003*m.x147*m.x63 - m.x3*m.x171 == 0)\n\nm.c45 = Constraint(expr=0.701*m.x88*m.x4 + 0.2*m.x94*m.x10 + 0.023*m.x100*m.x16 + 0.007*m.x106*m.x22 + 0.039*m.x124*\n                        m.x40 + 0.02*m.x130*m.x46 + 0.003*m.x148*m.x64 - m.x4*m.x172 == 0)\n\nm.c46 = Constraint(expr=0.701*m.x89*m.x5 + 0.2*m.x95*m.x11 + 0.023*m.x101*m.x17 + 0.007*m.x107*m.x23 + 0.039*m.x125*\n                        m.x41 + 0.02*m.x131*m.x47 + 0.003*m.x149*m.x65 - m.x5*m.x173 == 0)\n\nm.c47 = Constraint(expr=0.701*m.x90*m.x6 + 0.2*m.x96*m.x12 + 0.023*m.x102*m.x18 + 0.007*m.x108*m.x24 + 0.039*m.x126*\n                        m.x42 + 0.02*m.x132*m.x48 + 0.003*m.x150*m.x66 - m.x6*m.x174 == 0)\n\nm.c48 = Constraint(expr=0.1*m.x85*m.x1 + 0.662*m.x91*m.x7 + 0.088*m.x97*m.x13 + 0.015*m.x103*m.x19 + 0.007*m.x109*m.x25\n                         + 0.071*m.x121*m.x37 + 0.037*m.x127*m.x43 + 0.01*m.x133*m.x49 + 0.007*m.x145*m.x61 + 0.003*\n                        m.x151*m.x67 - m.x7*m.x169 == 0)\n\nm.c49 = Constraint(expr=0.1*m.x86*m.x2 + 0.662*m.x92*m.x8 + 0.088*m.x98*m.x14 + 0.015*m.x104*m.x20 + 0.007*m.x110*m.x26\n                         + 0.071*m.x122*m.x38 + 0.037*m.x128*m.x44 + 0.01*m.x134*m.x50 + 0.007*m.x146*m.x62 + 0.003*\n                        m.x152*m.x68 - m.x8*m.x170 == 0)\n\nm.c50 = Constraint(expr=0.1*m.x87*m.x3 + 0.662*m.x93*m.x9 + 0.088*m.x99*m.x15 + 0.015*m.x105*m.x21 + 0.007*m.x111*m.x27\n                         + 0.071*m.x123*m.x39 + 0.037*m.x129*m.x45 + 0.01*m.x135*m.x51 + 0.007*m.x147*m.x63 + 0.003*\n                        m.x153*m.x69 - m.x9*m.x171 == 0)\n\nm.c51 = Constraint(expr=0.1*m.x88*m.x4 + 0.662*m.x94*m.x10 + 0.088*m.x100*m.x16 + 0.015*m.x106*m.x22 + 0.007*m.x112*\n                        m.x28 + 0.071*m.x124*m.x40 + 0.037*m.x130*m.x46 + 0.01*m.x136*m.x52 + 0.007*m.x148*m.x64 + 0.003\n                        *m.x154*m.x70 - m.x10*m.x172 == 0)\n\nm.c52 = Constraint(expr=0.1*m.x89*m.x5 + 0.662*m.x95*m.x11 + 0.088*m.x101*m.x17 + 0.015*m.x107*m.x23 + 0.007*m.x113*\n                        m.x29 + 0.071*m.x125*m.x41 + 0.037*m.x131*m.x47 + 0.01*m.x137*m.x53 + 0.007*m.x149*m.x65 + 0.003\n                        *m.x155*m.x71 - m.x11*m.x173 == 0)\n\nm.c53 = Constraint(expr=0.1*m.x90*m.x6 + 0.662*m.x96*m.x12 + 0.088*m.x102*m.x18 + 0.015*m.x108*m.x24 + 0.007*m.x114*\n                        m.x30 + 0.071*m.x126*m.x42 + 0.037*m.x132*m.x48 + 0.01*m.x138*m.x54 + 0.007*m.x150*m.x66 + 0.003\n                        *m.x156*m.x72 - m.x12*m.x174 == 0)\n\nm.c54 = Constraint(expr=0.015*m.x85*m.x1 + 0.102*m.x91*m.x7 + 0.619*m.x97*m.x13 + 0.085*m.x103*m.x19 + 0.015*m.x109*\n                        m.x25 + 0.007*m.x115*m.x31 + 0.036*m.x121*m.x37 + 0.064*m.x127*m.x43 + 0.029*m.x133*m.x49 + 0.01\n                        *m.x139*m.x55 + 0.008*m.x145*m.x61 + 0.007*m.x151*m.x67 + 0.003*m.x157*m.x73 - m.x13*m.x169\n                         == 0)\n\nm.c55 = Constraint(expr=0.015*m.x86*m.x2 + 0.102*m.x92*m.x8 + 0.619*m.x98*m.x14 + 0.085*m.x104*m.x20 + 0.015*m.x110*\n                        m.x26 + 0.007*m.x116*m.x32 + 0.036*m.x122*m.x38 + 0.064*m.x128*m.x44 + 0.029*m.x134*m.x50 + 0.01\n                        *m.x140*m.x56 + 0.008*m.x146*m.x62 + 0.007*m.x152*m.x68 + 0.003*m.x158*m.x74 - m.x14*m.x170\n                         == 0)\n\nm.c56 = Constraint(expr=0.015*m.x87*m.x3 + 0.102*m.x93*m.x9 + 0.619*m.x99*m.x15 + 0.085*m.x105*m.x21 + 0.015*m.x111*\n                        m.x27 + 0.007*m.x117*m.x33 + 0.036*m.x123*m.x39 + 0.064*m.x129*m.x45 + 0.029*m.x135*m.x51 + 0.01\n                        *m.x141*m.x57 + 0.008*m.x147*m.x63 + 0.007*m.x153*m.x69 + 0.003*m.x159*m.x75 - m.x15*m.x171\n                         == 0)\n\nm.c57 = Constraint(expr=0.015*m.x88*m.x4 + 0.102*m.x94*m.x10 + 0.619*m.x100*m.x16 + 0.085*m.x106*m.x22 + 0.015*m.x112*\n                        m.x28 + 0.007*m.x118*m.x34 + 0.036*m.x124*m.x40 + 0.064*m.x130*m.x46 + 0.029*m.x136*m.x52 + 0.01\n                        *m.x142*m.x58 + 0.008*m.x148*m.x64 + 0.007*m.x154*m.x70 + 0.003*m.x160*m.x76 - m.x16*m.x172\n                         == 0)\n\nm.c58 = Constraint(expr=0.015*m.x89*m.x5 + 0.102*m.x95*m.x11 + 0.619*m.x101*m.x17 + 0.085*m.x107*m.x23 + 0.015*m.x113*\n                        m.x29 + 0.007*m.x119*m.x35 + 0.036*m.x125*m.x41 + 0.064*m.x131*m.x47 + 0.029*m.x137*m.x53 + 0.01\n                        *m.x143*m.x59 + 0.008*m.x149*m.x65 + 0.007*m.x155*m.x71 + 0.003*m.x161*m.x77 - m.x17*m.x173\n                         == 0)\n\nm.c59 = Constraint(expr=0.015*m.x90*m.x6 + 0.102*m.x96*m.x12 + 0.619*m.x102*m.x18 + 0.085*m.x108*m.x24 + 0.015*m.x114*\n                        m.x30 + 0.007*m.x120*m.x36 + 0.036*m.x126*m.x42 + 0.064*m.x132*m.x48 + 0.029*m.x138*m.x54 + 0.01\n                        *m.x144*m.x60 + 0.008*m.x150*m.x66 + 0.007*m.x156*m.x72 + 0.003*m.x162*m.x78 - m.x18*m.x174\n                         == 0)\n\nm.c60 = Constraint(expr=0.022*m.x91*m.x7 + 0.085*m.x97*m.x13 + 0.616*m.x103*m.x19 + 0.085*m.x109*m.x25 + 0.015*m.x115*\n                        m.x31 + 0.01*m.x121*m.x37 + 0.039*m.x127*m.x43 + 0.064*m.x133*m.x49 + 0.029*m.x139*m.x55 + 0.008\n                        *m.x151*m.x67 + 0.007*m.x157*m.x73 - m.x19*m.x169 == 0)\n\nm.c61 = Constraint(expr=0.022*m.x92*m.x8 + 0.085*m.x98*m.x14 + 0.616*m.x104*m.x20 + 0.085*m.x110*m.x26 + 0.015*m.x116*\n                        m.x32 + 0.01*m.x122*m.x38 + 0.039*m.x128*m.x44 + 0.064*m.x134*m.x50 + 0.029*m.x140*m.x56 + 0.008\n                        *m.x152*m.x68 + 0.007*m.x158*m.x74 - m.x20*m.x170 == 0)\n\nm.c62 = Constraint(expr=0.022*m.x93*m.x9 + 0.085*m.x99*m.x15 + 0.616*m.x105*m.x21 + 0.085*m.x111*m.x27 + 0.015*m.x117*\n                        m.x33 + 0.01*m.x123*m.x39 + 0.039*m.x129*m.x45 + 0.064*m.x135*m.x51 + 0.029*m.x141*m.x57 + 0.008\n                        *m.x153*m.x69 + 0.007*m.x159*m.x75 - m.x21*m.x171 == 0)\n\nm.c63 = Constraint(expr=0.022*m.x94*m.x10 + 0.085*m.x100*m.x16 + 0.616*m.x106*m.x22 + 0.085*m.x112*m.x28 + 0.015*m.x118*\n                        m.x34 + 0.01*m.x124*m.x40 + 0.039*m.x130*m.x46 + 0.064*m.x136*m.x52 + 0.029*m.x142*m.x58 + 0.008\n                        *m.x154*m.x70 + 0.007*m.x160*m.x76 - m.x22*m.x172 == 0)\n\nm.c64 = Constraint(expr=0.022*m.x95*m.x11 + 0.085*m.x101*m.x17 + 0.616*m.x107*m.x23 + 0.085*m.x113*m.x29 + 0.015*m.x119*\n                        m.x35 + 0.01*m.x125*m.x41 + 0.039*m.x131*m.x47 + 0.064*m.x137*m.x53 + 0.029*m.x143*m.x59 + 0.008\n                        *m.x155*m.x71 + 0.007*m.x161*m.x77 - m.x23*m.x173 == 0)\n\nm.c65 = Constraint(expr=0.022*m.x96*m.x12 + 0.085*m.x102*m.x18 + 0.616*m.x108*m.x24 + 0.085*m.x114*m.x30 + 0.015*m.x120*\n                        m.x36 + 0.01*m.x126*m.x42 + 0.039*m.x132*m.x48 + 0.064*m.x138*m.x54 + 0.029*m.x144*m.x60 + 0.008\n                        *m.x156*m.x72 + 0.007*m.x162*m.x78 - m.x24*m.x174 == 0)\n\nm.c66 = Constraint(expr=0.015*m.x97*m.x13 + 0.085*m.x103*m.x19 + 0.616*m.x109*m.x25 + 0.085*m.x115*m.x31 + 0.007*m.x121*\n                        m.x37 + 0.01*m.x127*m.x43 + 0.036*m.x133*m.x49 + 0.064*m.x139*m.x55 + 0.003*m.x145*m.x61 + 0.008\n                        *m.x157*m.x73 - m.x25*m.x169 == 0)\n\nm.c67 = Constraint(expr=0.015*m.x98*m.x14 + 0.085*m.x104*m.x20 + 0.616*m.x110*m.x26 + 0.085*m.x116*m.x32 + 0.007*m.x122*\n                        m.x38 + 0.01*m.x128*m.x44 + 0.036*m.x134*m.x50 + 0.064*m.x140*m.x56 + 0.003*m.x146*m.x62 + 0.008\n                        *m.x158*m.x74 - m.x26*m.x170 == 0)\n\nm.c68 = Constraint(expr=0.015*m.x99*m.x15 + 0.085*m.x105*m.x21 + 0.616*m.x111*m.x27 + 0.085*m.x117*m.x33 + 0.007*m.x123*\n                        m.x39 + 0.01*m.x129*m.x45 + 0.036*m.x135*m.x51 + 0.064*m.x141*m.x57 + 0.003*m.x147*m.x63 + 0.008\n                        *m.x159*m.x75 - m.x27*m.x171 == 0)\n\nm.c69 = Constraint(expr=0.015*m.x100*m.x16 + 0.085*m.x106*m.x22 + 0.616*m.x112*m.x28 + 0.085*m.x118*m.x34 + 0.007*m.x124\n                        *m.x40 + 0.01*m.x130*m.x46 + 0.036*m.x136*m.x52 + 0.064*m.x142*m.x58 + 0.003*m.x148*m.x64 + \n                        0.008*m.x160*m.x76 - m.x28*m.x172 == 0)\n\nm.c70 = Constraint(expr=0.015*m.x101*m.x17 + 0.085*m.x107*m.x23 + 0.616*m.x113*m.x29 + 0.085*m.x119*m.x35 + 0.007*m.x125\n                        *m.x41 + 0.01*m.x131*m.x47 + 0.036*m.x137*m.x53 + 0.064*m.x143*m.x59 + 0.003*m.x149*m.x65 + \n                        0.008*m.x161*m.x77 - m.x29*m.x173 == 0)\n\nm.c71 = Constraint(expr=0.015*m.x102*m.x18 + 0.085*m.x108*m.x24 + 0.616*m.x114*m.x30 + 0.085*m.x120*m.x36 + 0.007*m.x126\n                        *m.x42 + 0.01*m.x132*m.x48 + 0.036*m.x138*m.x54 + 0.064*m.x144*m.x60 + 0.003*m.x150*m.x66 + \n                        0.008*m.x162*m.x78 - m.x30*m.x174 == 0)\n\nm.c72 = Constraint(expr=0.015*m.x103*m.x19 + 0.085*m.x109*m.x25 + 0.616*m.x115*m.x31 + 0.007*m.x127*m.x43 + 0.01*m.x133*\n                        m.x49 + 0.036*m.x139*m.x55 + 0.003*m.x151*m.x67 - m.x31*m.x169 == 0)\n\nm.c73 = Constraint(expr=0.015*m.x104*m.x20 + 0.085*m.x110*m.x26 + 0.616*m.x116*m.x32 + 0.007*m.x128*m.x44 + 0.01*m.x134*\n                        m.x50 + 0.036*m.x140*m.x56 + 0.003*m.x152*m.x68 - m.x32*m.x170 == 0)\n\nm.c74 = Constraint(expr=0.015*m.x105*m.x21 + 0.085*m.x111*m.x27 + 0.616*m.x117*m.x33 + 0.007*m.x129*m.x45 + 0.01*m.x135*\n                        m.x51 + 0.036*m.x141*m.x57 + 0.003*m.x153*m.x69 - m.x33*m.x171 == 0)\n\nm.c75 = Constraint(expr=0.015*m.x106*m.x22 + 0.085*m.x112*m.x28 + 0.616*m.x118*m.x34 + 0.007*m.x130*m.x46 + 0.01*m.x136*\n                        m.x52 + 0.036*m.x142*m.x58 + 0.003*m.x154*m.x70 - m.x34*m.x172 == 0)\n\nm.c76 = Constraint(expr=0.015*m.x107*m.x23 + 0.085*m.x113*m.x29 + 0.616*m.x119*m.x35 + 0.007*m.x131*m.x47 + 0.01*m.x137*\n                        m.x53 + 0.036*m.x143*m.x59 + 0.003*m.x155*m.x71 - m.x35*m.x173 == 0)\n\nm.c77 = Constraint(expr=0.015*m.x108*m.x24 + 0.085*m.x114*m.x30 + 0.616*m.x120*m.x36 + 0.007*m.x132*m.x48 + 0.01*m.x138*\n                        m.x54 + 0.036*m.x144*m.x60 + 0.003*m.x156*m.x72 - m.x36*m.x174 == 0)\n\nm.c78 = Constraint(expr=0.046*m.x85*m.x1 + 0.128*m.x91*m.x7 + 0.065*m.x97*m.x13 + 0.013*m.x103*m.x19 + 0.007*m.x109*\n                        m.x25 + 0.56*m.x121*m.x37 + 0.119*m.x127*m.x43 + 0.016*m.x133*m.x49 + 0.029*m.x145*m.x61 + 0.014\n                        *m.x151*m.x67 + 0.003*m.x163*m.x79 - m.x37*m.x169 == 0)\n\nm.c79 = Constraint(expr=0.046*m.x86*m.x2 + 0.128*m.x92*m.x8 + 0.065*m.x98*m.x14 + 0.013*m.x104*m.x20 + 0.007*m.x110*\n                        m.x26 + 0.56*m.x122*m.x38 + 0.119*m.x128*m.x44 + 0.016*m.x134*m.x50 + 0.029*m.x146*m.x62 + 0.014\n                        *m.x152*m.x68 + 0.003*m.x164*m.x80 - m.x38*m.x170 == 0)\n\nm.c80 = Constraint(expr=0.046*m.x87*m.x3 + 0.128*m.x93*m.x9 + 0.065*m.x99*m.x15 + 0.013*m.x105*m.x21 + 0.007*m.x111*\n                        m.x27 + 0.56*m.x123*m.x39 + 0.119*m.x129*m.x45 + 0.016*m.x135*m.x51 + 0.029*m.x147*m.x63 + 0.014\n                        *m.x153*m.x69 + 0.003*m.x165*m.x81 - m.x39*m.x171 == 0)\n\nm.c81 = Constraint(expr=0.046*m.x88*m.x4 + 0.128*m.x94*m.x10 + 0.065*m.x100*m.x16 + 0.013*m.x106*m.x22 + 0.007*m.x112*\n                        m.x28 + 0.56*m.x124*m.x40 + 0.119*m.x130*m.x46 + 0.016*m.x136*m.x52 + 0.029*m.x148*m.x64 + 0.014\n                        *m.x154*m.x70 + 0.003*m.x166*m.x82 - m.x40*m.x172 == 0)\n\nm.c82 = Constraint(expr=0.046*m.x89*m.x5 + 0.128*m.x95*m.x11 + 0.065*m.x101*m.x17 + 0.013*m.x107*m.x23 + 0.007*m.x113*\n                        m.x29 + 0.56*m.x125*m.x41 + 0.119*m.x131*m.x47 + 0.016*m.x137*m.x53 + 0.029*m.x149*m.x65 + 0.014\n                        *m.x155*m.x71 + 0.003*m.x167*m.x83 - m.x41*m.x173 == 0)\n\nm.c83 = Constraint(expr=0.046*m.x90*m.x6 + 0.128*m.x96*m.x12 + 0.065*m.x102*m.x18 + 0.013*m.x108*m.x24 + 0.007*m.x114*\n                        m.x30 + 0.56*m.x126*m.x42 + 0.119*m.x132*m.x48 + 0.016*m.x138*m.x54 + 0.029*m.x150*m.x66 + 0.014\n                        *m.x156*m.x72 + 0.003*m.x168*m.x84 - m.x42*m.x174 == 0)\n\nm.c84 = Constraint(expr=0.01*m.x85*m.x1 + 0.044*m.x91*m.x7 + 0.078*m.x97*m.x13 + 0.032*m.x103*m.x19 + 0.01*m.x109*m.x25\n                         + 0.007*m.x115*m.x31 + 0.056*m.x121*m.x37 + 0.589*m.x127*m.x43 + 0.056*m.x133*m.x49 + 0.008*\n                        m.x139*m.x55 + 0.056*m.x145*m.x61 + 0.037*m.x151*m.x67 + 0.007*m.x157*m.x73 + 0.007*m.x163*m.x79\n                         - m.x43*m.x169 == 0)\n\nm.c85 = Constraint(expr=0.01*m.x86*m.x2 + 0.044*m.x92*m.x8 + 0.078*m.x98*m.x14 + 0.032*m.x104*m.x20 + 0.01*m.x110*m.x26\n                         + 0.007*m.x116*m.x32 + 0.056*m.x122*m.x38 + 0.589*m.x128*m.x44 + 0.056*m.x134*m.x50 + 0.008*\n                        m.x140*m.x56 + 0.056*m.x146*m.x62 + 0.037*m.x152*m.x68 + 0.007*m.x158*m.x74 + 0.007*m.x164*m.x80\n                         - m.x44*m.x170 == 0)\n\nm.c86 = Constraint(expr=0.01*m.x87*m.x3 + 0.044*m.x93*m.x9 + 0.078*m.x99*m.x15 + 0.032*m.x105*m.x21 + 0.01*m.x111*m.x27\n                         + 0.007*m.x117*m.x33 + 0.056*m.x123*m.x39 + 0.589*m.x129*m.x45 + 0.056*m.x135*m.x51 + 0.008*\n                        m.x141*m.x57 + 0.056*m.x147*m.x63 + 0.037*m.x153*m.x69 + 0.007*m.x159*m.x75 + 0.007*m.x165*m.x81\n                         - m.x45*m.x171 == 0)\n\nm.c87 = Constraint(expr=0.01*m.x88*m.x4 + 0.044*m.x94*m.x10 + 0.078*m.x100*m.x16 + 0.032*m.x106*m.x22 + 0.01*m.x112*\n                        m.x28 + 0.007*m.x118*m.x34 + 0.056*m.x124*m.x40 + 0.589*m.x130*m.x46 + 0.056*m.x136*m.x52 + \n                        0.008*m.x142*m.x58 + 0.056*m.x148*m.x64 + 0.037*m.x154*m.x70 + 0.007*m.x160*m.x76 + 0.007*m.x166\n                        *m.x82 - m.x46*m.x172 == 0)\n\nm.c88 = Constraint(expr=0.01*m.x89*m.x5 + 0.044*m.x95*m.x11 + 0.078*m.x101*m.x17 + 0.032*m.x107*m.x23 + 0.01*m.x113*\n                        m.x29 + 0.007*m.x119*m.x35 + 0.056*m.x125*m.x41 + 0.589*m.x131*m.x47 + 0.056*m.x137*m.x53 + \n                        0.008*m.x143*m.x59 + 0.056*m.x149*m.x65 + 0.037*m.x155*m.x71 + 0.007*m.x161*m.x77 + 0.007*m.x167\n                        *m.x83 - m.x47*m.x173 == 0)\n\nm.c89 = Constraint(expr=0.01*m.x90*m.x6 + 0.044*m.x96*m.x12 + 0.078*m.x102*m.x18 + 0.032*m.x108*m.x24 + 0.01*m.x114*\n                        m.x30 + 0.007*m.x120*m.x36 + 0.056*m.x126*m.x42 + 0.589*m.x132*m.x48 + 0.056*m.x138*m.x54 + \n                        0.008*m.x144*m.x60 + 0.056*m.x150*m.x66 + 0.037*m.x156*m.x72 + 0.007*m.x162*m.x78 + 0.007*m.x168\n                        *m.x84 - m.x48*m.x174 == 0)\n\nm.c90 = Constraint(expr=0.01*m.x91*m.x7 + 0.043*m.x97*m.x13 + 0.064*m.x103*m.x19 + 0.029*m.x109*m.x25 + 0.01*m.x115*\n                        m.x31 + 0.008*m.x121*m.x37 + 0.063*m.x127*m.x43 + 0.563*m.x133*m.x49 + 0.056*m.x139*m.x55 + \n                        0.029*m.x145*m.x61 + 0.056*m.x151*m.x67 + 0.029*m.x157*m.x73 + 0.008*m.x163*m.x79 - m.x49*m.x169\n                         == 0)\n\nm.c91 = Constraint(expr=0.01*m.x92*m.x8 + 0.043*m.x98*m.x14 + 0.064*m.x104*m.x20 + 0.029*m.x110*m.x26 + 0.01*m.x116*\n                        m.x32 + 0.008*m.x122*m.x38 + 0.063*m.x128*m.x44 + 0.563*m.x134*m.x50 + 0.056*m.x140*m.x56 + \n                        0.029*m.x146*m.x62 + 0.056*m.x152*m.x68 + 0.029*m.x158*m.x74 + 0.008*m.x164*m.x80 - m.x50*m.x170\n                         == 0)\n\nm.c92 = Constraint(expr=0.01*m.x93*m.x9 + 0.043*m.x99*m.x15 + 0.064*m.x105*m.x21 + 0.029*m.x111*m.x27 + 0.01*m.x117*\n                        m.x33 + 0.008*m.x123*m.x39 + 0.063*m.x129*m.x45 + 0.563*m.x135*m.x51 + 0.056*m.x141*m.x57 + \n                        0.029*m.x147*m.x63 + 0.056*m.x153*m.x69 + 0.029*m.x159*m.x75 + 0.008*m.x165*m.x81 - m.x51*m.x171\n                         == 0)\n\nm.c93 = Constraint(expr=0.01*m.x94*m.x10 + 0.043*m.x100*m.x16 + 0.064*m.x106*m.x22 + 0.029*m.x112*m.x28 + 0.01*m.x118*\n                        m.x34 + 0.008*m.x124*m.x40 + 0.063*m.x130*m.x46 + 0.563*m.x136*m.x52 + 0.056*m.x142*m.x58 + \n                        0.029*m.x148*m.x64 + 0.056*m.x154*m.x70 + 0.029*m.x160*m.x76 + 0.008*m.x166*m.x82 - m.x52*m.x172\n                         == 0)\n\nm.c94 = Constraint(expr=0.01*m.x95*m.x11 + 0.043*m.x101*m.x17 + 0.064*m.x107*m.x23 + 0.029*m.x113*m.x29 + 0.01*m.x119*\n                        m.x35 + 0.008*m.x125*m.x41 + 0.063*m.x131*m.x47 + 0.563*m.x137*m.x53 + 0.056*m.x143*m.x59 + \n                        0.029*m.x149*m.x65 + 0.056*m.x155*m.x71 + 0.029*m.x161*m.x77 + 0.008*m.x167*m.x83 - m.x53*m.x173\n                         == 0)\n\nm.c95 = Constraint(expr=0.01*m.x96*m.x12 + 0.043*m.x102*m.x18 + 0.064*m.x108*m.x24 + 0.029*m.x114*m.x30 + 0.01*m.x120*\n                        m.x36 + 0.008*m.x126*m.x42 + 0.063*m.x132*m.x48 + 0.563*m.x138*m.x54 + 0.056*m.x144*m.x60 + \n                        0.029*m.x150*m.x66 + 0.056*m.x156*m.x72 + 0.029*m.x162*m.x78 + 0.008*m.x168*m.x84 - m.x54*m.x174\n                         == 0)\n\nm.c96 = Constraint(expr=0.01*m.x97*m.x13 + 0.036*m.x103*m.x19 + 0.064*m.x109*m.x25 + 0.029*m.x115*m.x31 + 0.015*m.x127*\n                        m.x43 + 0.056*m.x133*m.x49 + 0.56*m.x139*m.x55 + 0.007*m.x145*m.x61 + 0.032*m.x151*m.x67 + 0.056\n                        *m.x157*m.x73 - m.x55*m.x169 == 0)\n\nm.c97 = Constraint(expr=0.01*m.x98*m.x14 + 0.036*m.x104*m.x20 + 0.064*m.x110*m.x26 + 0.029*m.x116*m.x32 + 0.015*m.x128*\n                        m.x44 + 0.056*m.x134*m.x50 + 0.56*m.x140*m.x56 + 0.007*m.x146*m.x62 + 0.032*m.x152*m.x68 + 0.056\n                        *m.x158*m.x74 - m.x56*m.x170 == 0)\n\nm.c98 = Constraint(expr=0.01*m.x99*m.x15 + 0.036*m.x105*m.x21 + 0.064*m.x111*m.x27 + 0.029*m.x117*m.x33 + 0.015*m.x129*\n                        m.x45 + 0.056*m.x135*m.x51 + 0.56*m.x141*m.x57 + 0.007*m.x147*m.x63 + 0.032*m.x153*m.x69 + 0.056\n                        *m.x159*m.x75 - m.x57*m.x171 == 0)\n\nm.c99 = Constraint(expr=0.01*m.x100*m.x16 + 0.036*m.x106*m.x22 + 0.064*m.x112*m.x28 + 0.029*m.x118*m.x34 + 0.015*m.x130*\n                        m.x46 + 0.056*m.x136*m.x52 + 0.56*m.x142*m.x58 + 0.007*m.x148*m.x64 + 0.032*m.x154*m.x70 + 0.056\n                        *m.x160*m.x76 - m.x58*m.x172 == 0)\n\nm.c100 = Constraint(expr=0.01*m.x101*m.x17 + 0.036*m.x107*m.x23 + 0.064*m.x113*m.x29 + 0.029*m.x119*m.x35 + 0.015*m.x131\n                         *m.x47 + 0.056*m.x137*m.x53 + 0.56*m.x143*m.x59 + 0.007*m.x149*m.x65 + 0.032*m.x155*m.x71 + \n                         0.056*m.x161*m.x77 - m.x59*m.x173 == 0)\n\nm.c101 = Constraint(expr=0.01*m.x102*m.x18 + 0.036*m.x108*m.x24 + 0.064*m.x114*m.x30 + 0.029*m.x120*m.x36 + 0.015*m.x132\n                         *m.x48 + 0.056*m.x138*m.x54 + 0.56*m.x144*m.x60 + 0.007*m.x150*m.x66 + 0.032*m.x156*m.x72 + \n                         0.056*m.x162*m.x78 - m.x60*m.x174 == 0)\n\nm.c102 = Constraint(expr=0.003*m.x85*m.x1 + 0.014*m.x91*m.x7 + 0.016*m.x97*m.x13 + 0.014*m.x103*m.x19 + 0.006*m.x109*\n                         m.x25 + 0.029*m.x121*m.x37 + 0.112*m.x127*m.x43 + 0.058*m.x133*m.x49 + 0.007*m.x139*m.x55 + \n                         0.56*m.x145*m.x61 + 0.112*m.x151*m.x67 + 0.016*m.x157*m.x73 + 0.029*m.x163*m.x79 - m.x61*m.x169\n                          == 0)\n\nm.c103 = Constraint(expr=0.003*m.x86*m.x2 + 0.014*m.x92*m.x8 + 0.016*m.x98*m.x14 + 0.014*m.x104*m.x20 + 0.006*m.x110*\n                         m.x26 + 0.029*m.x122*m.x38 + 0.112*m.x128*m.x44 + 0.058*m.x134*m.x50 + 0.007*m.x140*m.x56 + \n                         0.56*m.x146*m.x62 + 0.112*m.x152*m.x68 + 0.016*m.x158*m.x74 + 0.029*m.x164*m.x80 - m.x62*m.x170\n                          == 0)\n\nm.c104 = Constraint(expr=0.003*m.x87*m.x3 + 0.014*m.x93*m.x9 + 0.016*m.x99*m.x15 + 0.014*m.x105*m.x21 + 0.006*m.x111*\n                         m.x27 + 0.029*m.x123*m.x39 + 0.112*m.x129*m.x45 + 0.058*m.x135*m.x51 + 0.007*m.x141*m.x57 + \n                         0.56*m.x147*m.x63 + 0.112*m.x153*m.x69 + 0.016*m.x159*m.x75 + 0.029*m.x165*m.x81 - m.x63*m.x171\n                          == 0)\n\nm.c105 = Constraint(expr=0.003*m.x88*m.x4 + 0.014*m.x94*m.x10 + 0.016*m.x100*m.x16 + 0.014*m.x106*m.x22 + 0.006*m.x112*\n                         m.x28 + 0.029*m.x124*m.x40 + 0.112*m.x130*m.x46 + 0.058*m.x136*m.x52 + 0.007*m.x142*m.x58 + \n                         0.56*m.x148*m.x64 + 0.112*m.x154*m.x70 + 0.016*m.x160*m.x76 + 0.029*m.x166*m.x82 - m.x64*m.x172\n                          == 0)\n\nm.c106 = Constraint(expr=0.003*m.x89*m.x5 + 0.014*m.x95*m.x11 + 0.016*m.x101*m.x17 + 0.014*m.x107*m.x23 + 0.006*m.x113*\n                         m.x29 + 0.029*m.x125*m.x41 + 0.112*m.x131*m.x47 + 0.058*m.x137*m.x53 + 0.007*m.x143*m.x59 + \n                         0.56*m.x149*m.x65 + 0.112*m.x155*m.x71 + 0.016*m.x161*m.x77 + 0.029*m.x167*m.x83 - m.x65*m.x173\n                          == 0)\n\nm.c107 = Constraint(expr=0.003*m.x90*m.x6 + 0.014*m.x96*m.x12 + 0.016*m.x102*m.x18 + 0.014*m.x108*m.x24 + 0.006*m.x114*\n                         m.x30 + 0.029*m.x126*m.x42 + 0.112*m.x132*m.x48 + 0.058*m.x138*m.x54 + 0.007*m.x144*m.x60 + \n                         0.56*m.x150*m.x66 + 0.112*m.x156*m.x72 + 0.016*m.x162*m.x78 + 0.029*m.x168*m.x84 - m.x66*m.x174\n                          == 0)\n\nm.c108 = Constraint(expr=0.003*m.x91*m.x7 + 0.007*m.x97*m.x13 + 0.015*m.x103*m.x19 + 0.003*m.x115*m.x31 + 0.007*m.x121*\n                         m.x37 + 0.037*m.x127*m.x43 + 0.063*m.x133*m.x49 + 0.032*m.x139*m.x55 + 0.056*m.x145*m.x61 + \n                         0.589*m.x151*m.x67 + 0.056*m.x157*m.x73 + 0.056*m.x163*m.x79 - m.x67*m.x169 == 0)\n\nm.c109 = Constraint(expr=0.003*m.x92*m.x8 + 0.007*m.x98*m.x14 + 0.015*m.x104*m.x20 + 0.003*m.x116*m.x32 + 0.007*m.x122*\n                         m.x38 + 0.037*m.x128*m.x44 + 0.063*m.x134*m.x50 + 0.032*m.x140*m.x56 + 0.056*m.x146*m.x62 + \n                         0.589*m.x152*m.x68 + 0.056*m.x158*m.x74 + 0.056*m.x164*m.x80 - m.x68*m.x170 == 0)\n\nm.c110 = Constraint(expr=0.003*m.x93*m.x9 + 0.007*m.x99*m.x15 + 0.015*m.x105*m.x21 + 0.003*m.x117*m.x33 + 0.007*m.x123*\n                         m.x39 + 0.037*m.x129*m.x45 + 0.063*m.x135*m.x51 + 0.032*m.x141*m.x57 + 0.056*m.x147*m.x63 + \n                         0.589*m.x153*m.x69 + 0.056*m.x159*m.x75 + 0.056*m.x165*m.x81 - m.x69*m.x171 == 0)\n\nm.c111 = Constraint(expr=0.003*m.x94*m.x10 + 0.007*m.x100*m.x16 + 0.015*m.x106*m.x22 + 0.003*m.x118*m.x34 + 0.007*m.x124\n                         *m.x40 + 0.037*m.x130*m.x46 + 0.063*m.x136*m.x52 + 0.032*m.x142*m.x58 + 0.056*m.x148*m.x64 + \n                         0.589*m.x154*m.x70 + 0.056*m.x160*m.x76 + 0.056*m.x166*m.x82 - m.x70*m.x172 == 0)\n\nm.c112 = Constraint(expr=0.003*m.x95*m.x11 + 0.007*m.x101*m.x17 + 0.015*m.x107*m.x23 + 0.003*m.x119*m.x35 + 0.007*m.x125\n                         *m.x41 + 0.037*m.x131*m.x47 + 0.063*m.x137*m.x53 + 0.032*m.x143*m.x59 + 0.056*m.x149*m.x65 + \n                         0.589*m.x155*m.x71 + 0.056*m.x161*m.x77 + 0.056*m.x167*m.x83 - m.x71*m.x173 == 0)\n\nm.c113 = Constraint(expr=0.003*m.x96*m.x12 + 0.007*m.x102*m.x18 + 0.015*m.x108*m.x24 + 0.003*m.x120*m.x36 + 0.007*m.x126\n                         *m.x42 + 0.037*m.x132*m.x48 + 0.063*m.x138*m.x54 + 0.032*m.x144*m.x60 + 0.056*m.x150*m.x66 + \n                         0.589*m.x156*m.x72 + 0.056*m.x162*m.x78 + 0.056*m.x168*m.x84 - m.x72*m.x174 == 0)\n\nm.c114 = Constraint(expr=0.003*m.x97*m.x13 + 0.007*m.x103*m.x19 + 0.008*m.x109*m.x25 + 0.007*m.x127*m.x43 + 0.036*m.x133\n                         *m.x49 + 0.056*m.x139*m.x55 + 0.008*m.x145*m.x61 + 0.063*m.x151*m.x67 + 0.563*m.x157*m.x73 + \n                         0.029*m.x163*m.x79 - m.x73*m.x169 == 0)\n\nm.c115 = Constraint(expr=0.003*m.x98*m.x14 + 0.007*m.x104*m.x20 + 0.008*m.x110*m.x26 + 0.007*m.x128*m.x44 + 0.036*m.x134\n                         *m.x50 + 0.056*m.x140*m.x56 + 0.008*m.x146*m.x62 + 0.063*m.x152*m.x68 + 0.563*m.x158*m.x74 + \n                         0.029*m.x164*m.x80 - m.x74*m.x170 == 0)\n\nm.c116 = Constraint(expr=0.003*m.x99*m.x15 + 0.007*m.x105*m.x21 + 0.008*m.x111*m.x27 + 0.007*m.x129*m.x45 + 0.036*m.x135\n                         *m.x51 + 0.056*m.x141*m.x57 + 0.008*m.x147*m.x63 + 0.063*m.x153*m.x69 + 0.563*m.x159*m.x75 + \n                         0.029*m.x165*m.x81 - m.x75*m.x171 == 0)\n\nm.c117 = Constraint(expr=0.003*m.x100*m.x16 + 0.007*m.x106*m.x22 + 0.008*m.x112*m.x28 + 0.007*m.x130*m.x46 + 0.036*\n                         m.x136*m.x52 + 0.056*m.x142*m.x58 + 0.008*m.x148*m.x64 + 0.063*m.x154*m.x70 + 0.563*m.x160*\n                         m.x76 + 0.029*m.x166*m.x82 - m.x76*m.x172 == 0)\n\nm.c118 = Constraint(expr=0.003*m.x101*m.x17 + 0.007*m.x107*m.x23 + 0.008*m.x113*m.x29 + 0.007*m.x131*m.x47 + 0.036*\n                         m.x137*m.x53 + 0.056*m.x143*m.x59 + 0.008*m.x149*m.x65 + 0.063*m.x155*m.x71 + 0.563*m.x161*\n                         m.x77 + 0.029*m.x167*m.x83 - m.x77*m.x173 == 0)\n\nm.c119 = Constraint(expr=0.003*m.x102*m.x18 + 0.007*m.x108*m.x24 + 0.008*m.x114*m.x30 + 0.007*m.x132*m.x48 + 0.036*\n                         m.x138*m.x54 + 0.056*m.x144*m.x60 + 0.008*m.x150*m.x66 + 0.063*m.x156*m.x72 + 0.563*m.x162*\n                         m.x78 + 0.029*m.x168*m.x84 - m.x78*m.x174 == 0)\n\nm.c120 = Constraint(expr=0.007*m.x109*m.x25 + 0.003*m.x121*m.x37 + 0.014*m.x127*m.x43 + 0.016*m.x133*m.x49 + 0.007*\n                         m.x139*m.x55 + 0.029*m.x145*m.x61 + 0.112*m.x151*m.x67 + 0.058*m.x157*m.x73 + 0.56*m.x163*m.x79\n                          - m.x79*m.x169 == 0)\n\nm.c121 = Constraint(expr=0.007*m.x110*m.x26 + 0.003*m.x122*m.x38 + 0.014*m.x128*m.x44 + 0.016*m.x134*m.x50 + 0.007*\n                         m.x140*m.x56 + 0.029*m.x146*m.x62 + 0.112*m.x152*m.x68 + 0.058*m.x158*m.x74 + 0.56*m.x164*m.x80\n                          - m.x80*m.x170 == 0)\n\nm.c122 = Constraint(expr=0.007*m.x111*m.x27 + 0.003*m.x123*m.x39 + 0.014*m.x129*m.x45 + 0.016*m.x135*m.x51 + 0.007*\n                         m.x141*m.x57 + 0.029*m.x147*m.x63 + 0.112*m.x153*m.x69 + 0.058*m.x159*m.x75 + 0.56*m.x165*m.x81\n                          - m.x81*m.x171 == 0)\n\nm.c123 = Constraint(expr=0.007*m.x112*m.x28 + 0.003*m.x124*m.x40 + 0.014*m.x130*m.x46 + 0.016*m.x136*m.x52 + 0.007*\n                         m.x142*m.x58 + 0.029*m.x148*m.x64 + 0.112*m.x154*m.x70 + 0.058*m.x160*m.x76 + 0.56*m.x166*m.x82\n                          - m.x82*m.x172 == 0)\n\nm.c124 = Constraint(expr=0.007*m.x113*m.x29 + 0.003*m.x125*m.x41 + 0.014*m.x131*m.x47 + 0.016*m.x137*m.x53 + 0.007*\n                         m.x143*m.x59 + 0.029*m.x149*m.x65 + 0.112*m.x155*m.x71 + 0.058*m.x161*m.x77 + 0.56*m.x167*m.x83\n                          - m.x83*m.x173 == 0)\n\nm.c125 = Constraint(expr=0.007*m.x114*m.x30 + 0.003*m.x126*m.x42 + 0.014*m.x132*m.x48 + 0.016*m.x138*m.x54 + 0.007*\n                         m.x144*m.x60 + 0.029*m.x150*m.x66 + 0.112*m.x156*m.x72 + 0.058*m.x162*m.x78 + 0.56*m.x168*m.x84\n                          - m.x84*m.x174 == 0)\n\nm.c126 = Constraint(expr=-(m.x85 - 0.15288*m.x85*m.x1) + m.x86 == 0)\n\nm.c127 = Constraint(expr=-(m.x86 - 0.15288*m.x86*m.x2) + m.x87 == 0)\n\nm.c128 = Constraint(expr=-(m.x87 - 0.15288*m.x87*m.x3) + m.x88 == 0)\n\nm.c129 = Constraint(expr=-(m.x88 - 0.15288*m.x88*m.x4) + m.x89 == 0)\n\nm.c130 = Constraint(expr=-(m.x89 - 0.15288*m.x89*m.x5) + m.x90 == 0)\n\nm.c131 = Constraint(expr=-(m.x91 - 0.15288*m.x91*m.x7) + m.x92 == 0)\n\nm.c132 = Constraint(expr=-(m.x92 - 0.15288*m.x92*m.x8) + m.x93 == 0)\n\nm.c133 = Constraint(expr=-(m.x93 - 0.15288*m.x93*m.x9) + m.x94 == 0)\n\nm.c134 = Constraint(expr=-(m.x94 - 0.15288*m.x94*m.x10) + m.x95 == 0)\n\nm.c135 = Constraint(expr=-(m.x95 - 0.15288*m.x95*m.x11) + m.x96 == 0)\n\nm.c136 = Constraint(expr=-(m.x97 - 0.15288*m.x97*m.x13) + m.x98 == 0)\n\nm.c137 = Constraint(expr=-(m.x98 - 0.15288*m.x98*m.x14) + m.x99 == 0)\n\nm.c138 = Constraint(expr=-(m.x99 - 0.15288*m.x99*m.x15) + m.x100 == 0)\n\nm.c139 = Constraint(expr=-(m.x100 - 0.15288*m.x100*m.x16) + m.x101 == 0)\n\nm.c140 = Constraint(expr=-(m.x101 - 0.15288*m.x101*m.x17) + m.x102 == 0)\n\nm.c141 = Constraint(expr=-(m.x103 - 0.15288*m.x103*m.x19) + m.x104 == 0)\n\nm.c142 = Constraint(expr=-(m.x104 - 0.15288*m.x104*m.x20) + m.x105 == 0)\n\nm.c143 = Constraint(expr=-(m.x105 - 0.15288*m.x105*m.x21) + m.x106 == 0)\n\nm.c144 = Constraint(expr=-(m.x106 - 0.15288*m.x106*m.x22) + m.x107 == 0)\n\nm.c145 = Constraint(expr=-(m.x107 - 0.15288*m.x107*m.x23) + m.x108 == 0)\n\nm.c146 = Constraint(expr=-(m.x109 - 0.15288*m.x109*m.x25) + m.x110 == 0)\n\nm.c147 = Constraint(expr=-(m.x110 - 0.15288*m.x110*m.x26) + m.x111 == 0)\n\nm.c148 = Constraint(expr=-(m.x111 - 0.15288*m.x111*m.x27) + m.x112 == 0)\n\nm.c149 = Constraint(expr=-(m.x112 - 0.15288*m.x112*m.x28) + m.x113 == 0)\n\nm.c150 = Constraint(expr=-(m.x113 - 0.15288*m.x113*m.x29) + m.x114 == 0)\n\nm.c151 = Constraint(expr=-(m.x115 - 0.15288*m.x115*m.x31) + m.x116 == 0)\n\nm.c152 = Constraint(expr=-(m.x116 - 0.15288*m.x116*m.x32) + m.x117 == 0)\n\nm.c153 = Constraint(expr=-(m.x117 - 0.15288*m.x117*m.x33) + m.x118 == 0)\n\nm.c154 = Constraint(expr=-(m.x118 - 0.15288*m.x118*m.x34) + m.x119 == 0)\n\nm.c155 = Constraint(expr=-(m.x119 - 0.15288*m.x119*m.x35) + m.x120 == 0)\n\nm.c156 = Constraint(expr=-(m.x121 - 0.15288*m.x121*m.x37) + m.x122 == 0)\n\nm.c157 = Constraint(expr=-(m.x122 - 0.15288*m.x122*m.x38) + m.x123 == 0)\n\nm.c158 = Constraint(expr=-(m.x123 - 0.15288*m.x123*m.x39) + m.x124 == 0)\n\nm.c159 = Constraint(expr=-(m.x124 - 0.15288*m.x124*m.x40) + m.x125 == 0)\n\nm.c160 = Constraint(expr=-(m.x125 - 0.15288*m.x125*m.x41) + m.x126 == 0)\n\nm.c161 = Constraint(expr=-(m.x127 - 0.15288*m.x127*m.x43) + m.x128 == 0)\n\nm.c162 = Constraint(expr=-(m.x128 - 0.15288*m.x128*m.x44) + m.x129 == 0)\n\nm.c163 = Constraint(expr=-(m.x129 - 0.15288*m.x129*m.x45) + m.x130 == 0)\n\nm.c164 = Constraint(expr=-(m.x130 - 0.15288*m.x130*m.x46) + m.x131 == 0)\n\nm.c165 = Constraint(expr=-(m.x131 - 0.15288*m.x131*m.x47) + m.x132 == 0)\n\nm.c166 = Constraint(expr=-(m.x133 - 0.15288*m.x133*m.x49) + m.x134 == 0)\n\nm.c167 = Constraint(expr=-(m.x134 - 0.15288*m.x134*m.x50) + m.x135 == 0)\n\nm.c168 = Constraint(expr=-(m.x135 - 0.15288*m.x135*m.x51) + m.x136 == 0)\n\nm.c169 = Constraint(expr=-(m.x136 - 0.15288*m.x136*m.x52) + m.x137 == 0)\n\nm.c170 = Constraint(expr=-(m.x137 - 0.15288*m.x137*m.x53) + m.x138 == 0)\n\nm.c171 = Constraint(expr=-(m.x139 - 0.15288*m.x139*m.x55) + m.x140 == 0)\n\nm.c172 = Constraint(expr=-(m.x140 - 0.15288*m.x140*m.x56) + m.x141 == 0)\n\nm.c173 = Constraint(expr=-(m.x141 - 0.15288*m.x141*m.x57) + m.x142 == 0)\n\nm.c174 = Constraint(expr=-(m.x142 - 0.15288*m.x142*m.x58) + m.x143 == 0)\n\nm.c175 = Constraint(expr=-(m.x143 - 0.15288*m.x143*m.x59) + m.x144 == 0)\n\nm.c176 = Constraint(expr=-(m.x145 - 0.15288*m.x145*m.x61) + m.x146 == 0)\n\nm.c177 = Constraint(expr=-(m.x146 - 0.15288*m.x146*m.x62) + m.x147 == 0)\n\nm.c178 = Constraint(expr=-(m.x147 - 0.15288*m.x147*m.x63) + m.x148 == 0)\n\nm.c179 = Constraint(expr=-(m.x148 - 0.15288*m.x148*m.x64) + m.x149 == 0)\n\nm.c180 = Constraint(expr=-(m.x149 - 0.15288*m.x149*m.x65) + m.x150 == 0)\n\nm.c181 = Constraint(expr=-(m.x151 - 0.15288*m.x151*m.x67) + m.x152 == 0)\n\nm.c182 = Constraint(expr=-(m.x152 - 0.15288*m.x152*m.x68) + m.x153 == 0)\n\nm.c183 = Constraint(expr=-(m.x153 - 0.15288*m.x153*m.x69) + m.x154 == 0)\n\nm.c184 = Constraint(expr=-(m.x154 - 0.15288*m.x154*m.x70) + m.x155 == 0)\n\nm.c185 = Constraint(expr=-(m.x155 - 0.15288*m.x155*m.x71) + m.x156 == 0)\n\nm.c186 = Constraint(expr=-(m.x157 - 0.15288*m.x157*m.x73) + m.x158 == 0)\n\nm.c187 = Constraint(expr=-(m.x158 - 0.15288*m.x158*m.x74) + m.x159 == 0)\n\nm.c188 = Constraint(expr=-(m.x159 - 0.15288*m.x159*m.x75) + m.x160 == 0)\n\nm.c189 = Constraint(expr=-(m.x160 - 0.15288*m.x160*m.x76) + m.x161 == 0)\n\nm.c190 = Constraint(expr=-(m.x161 - 0.15288*m.x161*m.x77) + m.x162 == 0)\n\nm.c191 = Constraint(expr=-(m.x163 - 0.15288*m.x163*m.x79) + m.x164 == 0)\n\nm.c192 = Constraint(expr=-(m.x164 - 0.15288*m.x164*m.x80) + m.x165 == 0)\n\nm.c193 = Constraint(expr=-(m.x165 - 0.15288*m.x165*m.x81) + m.x166 == 0)\n\nm.c194 = Constraint(expr=-(m.x166 - 0.15288*m.x166*m.x82) + m.x167 == 0)\n\nm.c195 = Constraint(expr=-(m.x167 - 0.15288*m.x167*m.x83) + m.x168 == 0)\n\nm.c196 = Constraint(expr=0.5*m.x85*m.x1 + m.x91*m.x7 + m.x97*m.x13 + m.x103*m.x19 + m.x109*m.x25 + m.x115*m.x31 + 0.5*\n                         m.x121*m.x37 + m.x127*m.x43 + m.x133*m.x49 + m.x139*m.x55 + 0.5*m.x145*m.x61 + m.x151*m.x67 + \n                         m.x157*m.x73 + 0.5*m.x163*m.x79 == 1)\n\nm.c197 = Constraint(expr=0.5*m.x86*m.x2 + m.x92*m.x8 + m.x98*m.x14 + m.x104*m.x20 + m.x110*m.x26 + m.x116*m.x32 + 0.5*\n                         m.x122*m.x38 + m.x128*m.x44 + m.x134*m.x50 + m.x140*m.x56 + 0.5*m.x146*m.x62 + m.x152*m.x68 + \n                         m.x158*m.x74 + 0.5*m.x164*m.x80 == 1)\n\nm.c198 = Constraint(expr=0.5*m.x87*m.x3 + m.x93*m.x9 + m.x99*m.x15 + m.x105*m.x21 + m.x111*m.x27 + m.x117*m.x33 + 0.5*\n                         m.x123*m.x39 + m.x129*m.x45 + m.x135*m.x51 + m.x141*m.x57 + 0.5*m.x147*m.x63 + m.x153*m.x69 + \n                         m.x159*m.x75 + 0.5*m.x165*m.x81 == 1)\n\nm.c199 = Constraint(expr=0.5*m.x88*m.x4 + m.x94*m.x10 + m.x100*m.x16 + m.x106*m.x22 + m.x112*m.x28 + m.x118*m.x34 + 0.5*\n                         m.x124*m.x40 + m.x130*m.x46 + m.x136*m.x52 + m.x142*m.x58 + 0.5*m.x148*m.x64 + m.x154*m.x70 + \n                         m.x160*m.x76 + 0.5*m.x166*m.x82 == 1)\n\nm.c200 = Constraint(expr=0.5*m.x89*m.x5 + m.x95*m.x11 + m.x101*m.x17 + m.x107*m.x23 + m.x113*m.x29 + m.x119*m.x35 + 0.5*\n                         m.x125*m.x41 + m.x131*m.x47 + m.x137*m.x53 + m.x143*m.x59 + 0.5*m.x149*m.x65 + m.x155*m.x71 + \n                         m.x161*m.x77 + 0.5*m.x167*m.x83 == 1)\n\nm.c201 = Constraint(expr=0.5*m.x90*m.x6 + m.x96*m.x12 + m.x102*m.x18 + m.x108*m.x24 + m.x114*m.x30 + m.x120*m.x36 + 0.5*\n                         m.x126*m.x42 + m.x132*m.x48 + m.x138*m.x54 + m.x144*m.x60 + 0.5*m.x150*m.x66 + m.x156*m.x72 + \n                         m.x162*m.x78 + 0.5*m.x168*m.x84 == 1)\n\nm.c202 = Constraint(expr=m.x85*m.x1 <= 0.15)\n\nm.c203 = Constraint(expr=m.x86*m.x2 <= 0.15)\n\nm.c204 = Constraint(expr=m.x87*m.x3 <= 0.15)\n\nm.c205 = Constraint(expr=m.x88*m.x4 <= 0.15)\n\nm.c206 = Constraint(expr=m.x89*m.x5 <= 0.15)\n\nm.c207 = Constraint(expr=m.x90*m.x6 <= 0.15)\n\nm.c208 = Constraint(expr=m.x91*m.x7 <= 0.15)\n\nm.c209 = Constraint(expr=m.x92*m.x8 <= 0.15)\n\nm.c210 = Constraint(expr=m.x93*m.x9 <= 0.15)\n\nm.c211 = Constraint(expr=m.x94*m.x10 <= 0.15)\n\nm.c212 = Constraint(expr=m.x95*m.x11 <= 0.15)\n\nm.c213 = Constraint(expr=m.x96*m.x12 <= 0.15)\n\nm.c214 = Constraint(expr=m.x97*m.x13 <= 0.15)\n\nm.c215 = Constraint(expr=m.x98*m.x14 <= 0.15)\n\nm.c216 = Constraint(expr=m.x99*m.x15 <= 0.15)\n\nm.c217 = Constraint(expr=m.x100*m.x16 <= 0.15)\n\nm.c218 = Constraint(expr=m.x101*m.x17 <= 0.15)\n\nm.c219 = Constraint(expr=m.x102*m.x18 <= 0.15)\n\nm.c220 = Constraint(expr=m.x103*m.x19 <= 0.15)\n\nm.c221 = Constraint(expr=m.x104*m.x20 <= 0.15)\n\nm.c222 = Constraint(expr=m.x105*m.x21 <= 0.15)\n\nm.c223 = Constraint(expr=m.x106*m.x22 <= 0.15)\n\nm.c224 = Constraint(expr=m.x107*m.x23 <= 0.15)\n\nm.c225 = Constraint(expr=m.x108*m.x24 <= 0.15)\n\nm.c226 = Constraint(expr=m.x109*m.x25 <= 0.15)\n\nm.c227 = Constraint(expr=m.x110*m.x26 <= 0.15)\n\nm.c228 = Constraint(expr=m.x111*m.x27 <= 0.15)\n\nm.c229 = Constraint(expr=m.x112*m.x28 <= 0.15)\n\nm.c230 = Constraint(expr=m.x113*m.x29 <= 0.15)\n\nm.c231 = Constraint(expr=m.x114*m.x30 <= 0.15)\n\nm.c232 = Constraint(expr=m.x115*m.x31 <= 0.15)\n\nm.c233 = Constraint(expr=m.x116*m.x32 <= 0.15)\n\nm.c234 = Constraint(expr=m.x117*m.x33 <= 0.15)\n\nm.c235 = Constraint(expr=m.x118*m.x34 <= 0.15)\n\nm.c236 = Constraint(expr=m.x119*m.x35 <= 0.15)\n\nm.c237 = Constraint(expr=m.x120*m.x36 <= 0.15)\n\nm.c238 = Constraint(expr=m.x121*m.x37 <= 0.15)\n\nm.c239 = Constraint(expr=m.x122*m.x38 <= 0.15)\n\nm.c240 = Constraint(expr=m.x123*m.x39 <= 0.15)\n\nm.c241 = Constraint(expr=m.x124*m.x40 <= 0.15)\n\nm.c242 = Constraint(expr=m.x125*m.x41 <= 0.15)\n\nm.c243 = Constraint(expr=m.x126*m.x42 <= 0.15)\n\nm.c244 = Constraint(expr=m.x127*m.x43 <= 0.15)\n\nm.c245 = Constraint(expr=m.x128*m.x44 <= 0.15)\n\nm.c246 = Constraint(expr=m.x129*m.x45 <= 0.15)\n\nm.c247 = Constraint(expr=m.x130*m.x46 <= 0.15)\n\nm.c248 = Constraint(expr=m.x131*m.x47 <= 0.15)\n\nm.c249 = Constraint(expr=m.x132*m.x48 <= 0.15)\n\nm.c250 = Constraint(expr=m.x133*m.x49 <= 0.15)\n\nm.c251 = Constraint(expr=m.x134*m.x50 <= 0.15)\n\nm.c252 = Constraint(expr=m.x135*m.x51 <= 0.15)\n\nm.c253 = Constraint(expr=m.x136*m.x52 <= 0.15)\n\nm.c254 = Constraint(expr=m.x137*m.x53 <= 0.15)\n\nm.c255 = Constraint(expr=m.x138*m.x54 <= 0.15)\n\nm.c256 = Constraint(expr=m.x139*m.x55 <= 0.15)\n\nm.c257 = Constraint(expr=m.x140*m.x56 <= 0.15)\n\nm.c258 = Constraint(expr=m.x141*m.x57 <= 0.15)\n\nm.c259 = Constraint(expr=m.x142*m.x58 <= 0.15)\n\nm.c260 = Constraint(expr=m.x143*m.x59 <= 0.15)\n\nm.c261 = Constraint(expr=m.x144*m.x60 <= 0.15)\n\nm.c262 = Constraint(expr=m.x145*m.x61 <= 0.15)\n\nm.c263 = Constraint(expr=m.x146*m.x62 <= 0.15)\n\nm.c264 = Constraint(expr=m.x147*m.x63 <= 0.15)\n\nm.c265 = Constraint(expr=m.x148*m.x64 <= 0.15)\n\nm.c266 = Constraint(expr=m.x149*m.x65 <= 0.15)\n\nm.c267 = Constraint(expr=m.x150*m.x66 <= 0.15)\n\nm.c268 = Constraint(expr=m.x151*m.x67 <= 0.15)\n\nm.c269 = Constraint(expr=m.x152*m.x68 <= 0.15)\n\nm.c270 = Constraint(expr=m.x153*m.x69 <= 0.15)\n\nm.c271 = Constraint(expr=m.x154*m.x70 <= 0.15)\n\nm.c272 = Constraint(expr=m.x155*m.x71 <= 0.15)\n\nm.c273 = Constraint(expr=m.x156*m.x72 <= 0.15)\n\nm.c274 = Constraint(expr=m.x157*m.x73 <= 0.15)\n\nm.c275 = Constraint(expr=m.x158*m.x74 <= 0.15)\n\nm.c276 = Constraint(expr=m.x159*m.x75 <= 0.15)\n\nm.c277 = Constraint(expr=m.x160*m.x76 <= 0.15)\n\nm.c278 = Constraint(expr=m.x161*m.x77 <= 0.15)\n\nm.c279 = Constraint(expr=m.x162*m.x78 <= 0.15)\n\nm.c280 = Constraint(expr=m.x163*m.x79 <= 0.15)\n\nm.c281 = Constraint(expr=m.x164*m.x80 <= 0.15)\n\nm.c282 = Constraint(expr=m.x165*m.x81 <= 0.15)\n\nm.c283 = Constraint(expr=m.x166*m.x82 <= 0.15)\n\nm.c284 = Constraint(expr=m.x167*m.x83 <= 0.15)\n\nm.c285 = Constraint(expr=m.x168*m.x84 <= 0.15)\n\nm.c286 = Constraint(expr=-(0.5*m.b175*m.x90 + m.b187*m.x96 + m.b199*m.x102 + m.b211*m.x108 + m.b223*m.x114 + m.b235*\n                         m.x120 + 0.5*m.b247*m.x126 + m.b259*m.x132 + m.b271*m.x138 + m.b283*m.x144 + 0.5*m.b295*m.x150\n                          + m.b307*m.x156 + m.b319*m.x162 + 0.5*m.b331*m.x168) + m.x344 == 0)\n\nm.c287 = Constraint(expr=-(0.5*m.b176*m.x90 + m.b188*m.x96 + m.b200*m.x102 + m.b212*m.x108 + m.b224*m.x114 + m.b236*\n                         m.x120 + 0.5*m.b248*m.x126 + m.b260*m.x132 + m.b272*m.x138 + m.b284*m.x144 + 0.5*m.b296*m.x150\n                          + m.b308*m.x156 + m.b320*m.x162 + 0.5*m.b332*m.x168) + m.x345 == 0)\n\nm.c288 = Constraint(expr=-(0.5*m.b177*m.x90 + m.b189*m.x96 + m.b201*m.x102 + m.b213*m.x108 + m.b225*m.x114 + m.b237*\n                         m.x120 + 0.5*m.b249*m.x126 + m.b261*m.x132 + m.b273*m.x138 + m.b285*m.x144 + 0.5*m.b297*m.x150\n                          + m.b309*m.x156 + m.b321*m.x162 + 0.5*m.b333*m.x168) + m.x346 == 0)\n\nm.c289 = Constraint(expr=-(0.5*m.b178*m.x90 + m.b190*m.x96 + m.b202*m.x102 + m.b214*m.x108 + m.b226*m.x114 + m.b238*\n                         m.x120 + 0.5*m.b250*m.x126 + m.b262*m.x132 + m.b274*m.x138 + m.b286*m.x144 + 0.5*m.b298*m.x150\n                          + m.b310*m.x156 + m.b322*m.x162 + 0.5*m.b334*m.x168) + m.x347 == 0)\n\nm.c290 = Constraint(expr=-(0.5*m.b179*m.x90 + m.b191*m.x96 + m.b203*m.x102 + m.b215*m.x108 + m.b227*m.x114 + m.b239*\n                         m.x120 + 0.5*m.b251*m.x126 + m.b263*m.x132 + m.b275*m.x138 + m.b287*m.x144 + 0.5*m.b299*m.x150\n                          + m.b311*m.x156 + m.b323*m.x162 + 0.5*m.b335*m.x168) + m.x348 == 0)\n\nm.c291 = Constraint(expr=-(0.5*m.b180*m.x90 + m.b192*m.x96 + m.b204*m.x102 + m.b216*m.x108 + m.b228*m.x114 + m.b240*\n                         m.x120 + 0.5*m.b252*m.x126 + m.b264*m.x132 + m.b276*m.x138 + m.b288*m.x144 + 0.5*m.b300*m.x150\n                          + m.b312*m.x156 + m.b324*m.x162 + 0.5*m.b336*m.x168) + m.x349 == 0)\n\nm.c292 = Constraint(expr=-(0.5*m.b181*m.x90 + m.b193*m.x96 + m.b205*m.x102 + m.b217*m.x108 + m.b229*m.x114 + m.b241*\n                         m.x120 + 0.5*m.b253*m.x126 + m.b265*m.x132 + m.b277*m.x138 + m.b289*m.x144 + 0.5*m.b301*m.x150\n                          + m.b313*m.x156 + m.b325*m.x162 + 0.5*m.b337*m.x168) + m.x350 == 0)\n\nm.c293 = Constraint(expr=-(0.5*m.b182*m.x90 + m.b194*m.x96 + m.b206*m.x102 + m.b218*m.x108 + m.b230*m.x114 + m.b242*\n                         m.x120 + 0.5*m.b254*m.x126 + m.b266*m.x132 + m.b278*m.x138 + m.b290*m.x144 + 0.5*m.b302*m.x150\n                          + m.b314*m.x156 + m.b326*m.x162 + 0.5*m.b338*m.x168) + m.x351 == 0)\n\nm.c294 = Constraint(expr=-(0.5*m.b183*m.x90 + m.b195*m.x96 + m.b207*m.x102 + m.b219*m.x108 + m.b231*m.x114 + m.b243*\n                         m.x120 + 0.5*m.b255*m.x126 + m.b267*m.x132 + m.b279*m.x138 + m.b291*m.x144 + 0.5*m.b303*m.x150\n                          + m.b315*m.x156 + m.b327*m.x162 + 0.5*m.b339*m.x168) + m.x352 == 0)\n\nm.c295 = Constraint(expr=   m.b175 - m.b247 == 0)\n\nm.c296 = Constraint(expr=   m.b176 - m.b248 == 0)\n\nm.c297 = Constraint(expr=   m.b177 - m.b249 == 0)\n\nm.c298 = Constraint(expr=   m.b178 - m.b250 == 0)\n\nm.c299 = Constraint(expr=   m.b179 - m.b251 == 0)\n\nm.c300 = Constraint(expr=   m.b180 - m.b252 == 0)\n\nm.c301 = Constraint(expr=   m.b181 - m.b253 == 0)\n\nm.c302 = Constraint(expr=   m.b182 - m.b254 == 0)\n\nm.c303 = Constraint(expr=   m.b183 - m.b255 == 0)\n\nm.c304 = Constraint(expr=   m.b184 - m.b256 == 0)\n\nm.c305 = Constraint(expr=   m.b185 - m.b257 == 0)\n\nm.c306 = Constraint(expr=   m.b186 - m.b258 == 0)\n\nm.c307 = Constraint(expr=   m.b295 - m.b331 == 0)\n\nm.c308 = Constraint(expr=   m.b296 - m.b332 == 0)\n\nm.c309 = Constraint(expr=   m.b297 - m.b333 == 0)\n\nm.c310 = Constraint(expr=   m.b298 - m.b334 == 0)\n\nm.c311 = Constraint(expr=   m.b299 - m.b335 == 0)\n\nm.c312 = Constraint(expr=   m.b300 - m.b336 == 0)\n\nm.c313 = Constraint(expr=   m.b301 - m.b337 == 0)\n\nm.c314 = Constraint(expr=   m.b302 - m.b338 == 0)\n\nm.c315 = Constraint(expr=   m.b303 - m.b339 == 0)\n\nm.c316 = Constraint(expr=   m.b304 - m.b340 == 0)\n\nm.c317 = Constraint(expr=   m.b305 - m.b341 == 0)\n\nm.c318 = Constraint(expr=   m.b306 - m.b342 == 0)\n", "meta": {"hexsha": "bd5724102cb213534474e1849f224e9ab90ef39a", "size": 75248, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/examples/minlplib/nuclearve.py", "max_stars_repo_name": "ouyang-w-19/decogo", "max_stars_repo_head_hexsha": "52546480e49776251d4d27856e18a46f40c824a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-07-03T13:19:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T10:48:13.000Z", "max_issues_repo_path": "tests/examples/minlplib/nuclearve.py", "max_issues_repo_name": "ouyang-w-19/decogo", "max_issues_repo_head_hexsha": "52546480e49776251d4d27856e18a46f40c824a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-04T14:52:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-15T10:17:11.000Z", "max_forks_repo_path": "tests/examples/minlplib/nuclearve.py", "max_forks_repo_name": "ouyang-w-19/decogo", "max_forks_repo_head_hexsha": "52546480e49776251d4d27856e18a46f40c824a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.9717868339, "max_line_length": 120, "alphanum_fraction": 0.6025143525, "include": true, "reason": "from pyomo", "num_tokens": 30409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213070736461, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.18112858344565497}}
{"text": "\n#python trRosetta.py T1008.npz T1008.fasta model.pdb\n\n#adapting trRosetta PyRosetta scripts to run as functions - generating SKEMPI chain predicted PDBs\nimport numpy as np\nimport random\nimport json\nimport tempfile\nfrom pyrosetta import *\nfrom pyrosetta.rosetta.protocols.minimization_packing import MinMover\nimport os\nimport time\n\ndef gen_rst(npz, tmpdir, params):\n    #generate restraints\n    dist,omega,theta,phi = npz['dist'][0],npz['omega'][0],npz['theta'][0],npz['phi'][0]\n    print (\"dist: \", dist.shape)\n    print (\"omega: \", omega.shape)\n    print (\"theta: \", theta.shape)\n    print (\"phi: \", phi.shape)\n    # dictionary to store Rosetta restraints\n    rst = {'dist' : [], 'omega' : [], 'theta' : [], 'phi' : [], 'rep' : []}\n\n    ########################################################\n    # assign parameters\n    ########################################################\n    PCUT  = 0.05 #params['PCUT']\n    PCUT1 = params['PCUT1']\n    EBASE = params['EBASE']\n    EREP  = params['EREP']\n    DREP  = params['DREP']\n    PREP  = params['PREP']\n    SIGD  = params['SIGD']\n    SIGM  = params['SIGM']\n    MEFF  = params['MEFF']\n    DCUT  = params['DCUT']\n    ALPHA = params['ALPHA']\n\n    DSTEP = params['DSTEP']\n    ASTEP = np.deg2rad(params['ASTEP'])\n\n    seq = params['seq']\n    print (\"number res: \", len(seq))\n    ########################################################\n    # repultion restraints\n    ########################################################\n    #cbs = ['CA' if a=='G' else 'CB' for a in params['seq']]\n    '''\n    prob = np.sum(dist[:,:,5:], axis=-1)\n    i,j = np.where(prob<PREP)\n    prob = prob[i,j]\n    for a,b,p in zip(i,j,prob):\n        if b>a:\n            name=tmpdir.name+\"/%d.%d_rep.txt\"%(a+1,b+1)\n            rst_line = 'AtomPair %s %d %s %d SCALARWEIGHTEDFUNC %.2f SUMFUNC 2 CONSTANTFUNC 0.5 SIGMOID %.3f %.3f\\n'%('CB',a+1,'CB',b+1,-0.5,SIGD,SIGM)\n            rst['rep'].append([a,b,p,rst_line])\n    print(\"rep restraints:   %d\"%(len(rst['rep'])))\n    '''\n\n\n    ########################################################\n    # dist: 0..20A\n    ########################################################\n    nres = dist.shape[0]\n    #print (\"number res: \", nres)\n    bins = np.array([4.25+DSTEP*i for i in range(32)])\n    #print (\"bins: \", bins.shape)\n    prob = np.sum(dist[:,:,5:], axis=-1)\n    #print (\"prob: \", prob.shape)\n    bkgr = np.array((bins/DCUT)**ALPHA)\n    #print (\"bkgr: \", bkgr.shape)\n    attr = -np.log((dist[:,:,5:]+MEFF)/(dist[:,:,-1][:,:,None]*bkgr[None,None,:]))+EBASE\n    repul = np.maximum(attr[:,:,0],np.zeros((nres,nres)))[:,:,None]+np.array(EREP)[None,None,:]\n    dist = np.concatenate([repul,attr], axis=-1)\n    bins = np.concatenate([DREP,bins])\n    i,j = np.where(prob>PCUT)\n    prob = prob[i,j]\n    nbins = 35\n    step = 0.5\n    for a,b,p in zip(i,j,prob):\n        if b>a:\n            name=tmpdir.name+\"/%d.%d.txt\"%(a+1,b+1)\n            with open(name, \"w\") as f:\n                f.write('x_axis'+'\\t%.3f'*nbins%tuple(bins)+'\\n')\n                f.write('y_axis'+'\\t%.3f'*nbins%tuple(dist[a,b])+'\\n')\n                f.close()\n            rst_line = 'AtomPair %s %d %s %d SPLINE TAG %s 1.0 %.3f %.5f'%('CB',a+1,'CB',b+1,name,1.0,step)\n            rst['dist'].append([a,b,p,rst_line])\n    print(\"dist restraints:  %d\"%(len(rst['dist'])))\n\n\n    ########################################################\n    # omega: -pi..pi\n    ########################################################\n    nbins = omega.shape[2]-1+4\n    bins = np.linspace(-np.pi-1.5*ASTEP, np.pi+1.5*ASTEP, nbins)\n    prob = np.sum(omega[:,:,1:], axis=-1)\n    i,j = np.where(prob>PCUT)\n    prob = prob[i,j]\n    omega = -np.log((omega+MEFF)/(omega[:,:,-1]+MEFF)[:,:,None])\n    omega = np.concatenate([omega[:,:,-2:],omega[:,:,1:],omega[:,:,1:3]],axis=-1)\n    for a,b,p in zip(i,j,prob):\n        if b>a:\n            name=tmpdir.name+\"/%d.%d_omega.txt\"%(a+1,b+1)\n            with open(name, \"w\") as f:\n                f.write('x_axis'+'\\t%.5f'*nbins%tuple(bins)+'\\n')\n                f.write('y_axis'+'\\t%.5f'*nbins%tuple(omega[a,b])+'\\n')\n                f.close()\n            rst_line = 'Dihedral CA %d CB %d CB %d CA %d SPLINE TAG %s 1.0 %.3f %.5f'%(a+1,a+1,b+1,b+1,name,1.0,ASTEP)\n            rst['omega'].append([a,b,p,rst_line])\n    print(\"omega restraints: %d\"%(len(rst['omega'])))\n\n\n    ########################################################\n    # theta: -pi..pi\n    ########################################################\n    prob = np.sum(theta[:,:,1:], axis=-1)\n    i,j = np.where(prob>PCUT)\n    prob = prob[i,j]\n    theta = -np.log((theta+MEFF)/(theta[:,:,-1]+MEFF)[:,:,None])\n    theta = np.concatenate([theta[:,:,-2:],theta[:,:,1:],theta[:,:,1:3]],axis=-1)\n    for a,b,p in zip(i,j,prob):\n        if b!=a:\n            name=tmpdir.name+\"/%d.%d_theta.txt\"%(a+1,b+1)\n            with open(name, \"w\") as f:\n                f.write('x_axis'+'\\t%.3f'*nbins%tuple(bins)+'\\n')\n                f.write('y_axis'+'\\t%.3f'*nbins%tuple(theta[a,b])+'\\n')\n                f.close()\n            rst_line = 'Dihedral N %d CA %d CB %d CB %d SPLINE TAG %s 1.0 %.3f %.5f'%(a+1,a+1,a+1,b+1,name,1.0,ASTEP)\n            rst['theta'].append([a,b,p,rst_line])\n            #if a==0 and b==9:\n            #    with open(name,'r') as f:\n            #        print(f.read())\n    print(\"theta restraints: %d\"%(len(rst['theta'])))\n\n\n    ########################################################\n    # phi: 0..pi\n    ########################################################\n    nbins = phi.shape[2]-1+4\n    bins = np.linspace(-1.5*ASTEP, np.pi+1.5*ASTEP, nbins)\n    prob = np.sum(phi[:,:,1:], axis=-1)\n    i,j = np.where(prob>PCUT)\n    prob = prob[i,j]\n    phi = -np.log((phi+MEFF)/(phi[:,:,-1]+MEFF)[:,:,None])\n    phi = np.concatenate([np.flip(phi[:,:,1:3],axis=-1),phi[:,:,1:],np.flip(phi[:,:,-2:],axis=-1)], axis=-1)\n    for a,b,p in zip(i,j,prob):\n        if b!=a:\n            name=tmpdir.name+\"/%d.%d_phi.txt\"%(a+1,b+1)\n            with open(name, \"w\") as f:\n                f.write('x_axis'+'\\t%.3f'*nbins%tuple(bins)+'\\n')\n                f.write('y_axis'+'\\t%.3f'*nbins%tuple(phi[a,b])+'\\n')\n                f.close()\n            rst_line = 'Angle CA %d CB %d CB %d SPLINE TAG %s 1.0 %.3f %.5f'%(a+1,a+1,b+1,name,1.0,ASTEP)\n            rst['phi'].append([a,b,p,rst_line])\n            #if a==0 and b==9:\n            #    with open(name,'r') as f:\n            #        print(f.read())\n\n    print(\"phi restraints:   %d\"%(len(rst['phi'])))\n\n    return rst\n\ndef set_random_dihedral(pose):\n    nres = pose.total_residue()\n    for i in range(1, nres):\n        phi,psi=random_dihedral()\n        pose.set_phi(i,phi)\n        pose.set_psi(i,psi)\n        pose.set_omega(i,180)\n\n    return(pose)\n\n\n#pick phi/psi randomly from:\n#-140  153 180 0.135 B\n# -72  145 180 0.155 B\n#-122  117 180 0.073 B\n# -82  -14 180 0.122 A\n# -61  -41 180 0.497 A\n#  57   39 180 0.018 L\ndef random_dihedral():\n    phi=0\n    psi=0\n    r=random.random()\n    if(r<=0.135):\n        phi=-140\n        psi=153\n    elif(r>0.135 and r<=0.29):\n        phi=-72\n        psi=145\n    elif(r>0.29 and r<=0.363):\n        phi=-122\n        psi=117\n    elif(r>0.363 and r<=0.485):\n        phi=-82\n        psi=-14\n    elif(r>0.485 and r<=0.982):\n        phi=-61\n        psi=-41\n    else:\n        phi=57\n        psi=39\n    return(phi, psi)\n\n\ndef read_fasta(file):\n    fasta=\"\"\n    with open(file, \"r\") as f:\n        for line in f:\n            if(line[0] == \">\"):\n                continue\n            else:\n                line=line.rstrip()\n                fasta = fasta + line;\n    return fasta\n\n\ndef remove_clash(scorefxn, mover, pose):\n    for _ in range(0, 5):\n        if float(scorefxn(pose)) < 10:\n            break\n        mover.apply(pose)\n\n\ndef add_rst(pose, rst, sep1, sep2, params, nogly=False):\n\n    pcut=params['PCUT']\n    seq = params['seq']\n\n    array=[]\n\n    if nogly==True:\n        array += [line for a,b,p,line in rst['dist'] if abs(a-b)>=sep1 and abs(a-b)<sep2 and seq[a]!='G' and seq[b]!='G' and p>=pcut]\n        if params['USE_ORIENT'] == True:\n            array += [line for a,b,p,line in rst['omega'] if abs(a-b)>=sep1 and abs(a-b)<sep2 and seq[a]!='G' and seq[b]!='G' and p>=pcut+0.5] #0.5\n            array += [line for a,b,p,line in rst['theta'] if abs(a-b)>=sep1 and abs(a-b)<sep2 and seq[a]!='G' and seq[b]!='G' and p>=pcut+0.5] #0.5\n            array += [line for a,b,p,line in rst['phi'] if abs(a-b)>=sep1 and abs(a-b)<sep2 and seq[a]!='G' and seq[b]!='G' and p>=pcut+0.6] #0.6\n    else:\n        array += [line for a,b,p,line in rst['dist'] if abs(a-b)>=sep1 and abs(a-b)<sep2 and p>=pcut]\n        if params['USE_ORIENT'] == True:\n            array += [line for a,b,p,line in rst['omega'] if abs(a-b)>=sep1 and abs(a-b)<sep2 and p>=pcut+0.5]\n            array += [line for a,b,p,line in rst['theta'] if abs(a-b)>=sep1 and abs(a-b)<sep2 and p>=pcut+0.5]\n            array += [line for a,b,p,line in rst['phi'] if abs(a-b)>=sep1 and abs(a-b)<sep2 and p>=pcut+0.6] #0.6\n\n\n    if len(array) < 1:\n        return\n\n    random.shuffle(array)\n\n    # save to file\n    tmpname = params['TDIR']+'/minimize.cst'\n    with open(tmpname,'w') as f:\n        for line in array:\n            f.write(line+'\\n')\n        f.close()\n\n    # add to pose\n    constraints = rosetta.protocols.constraint_movers.ConstraintSetMover()\n    constraints.constraint_file(tmpname)\n    constraints.add_constraints(True)\n    constraints.apply(pose)\n\n    os.remove(tmpname)\n\ndef generatePDB(fasta, npz, out):\n\n    ########################################################\n    # process inputs\n    ########################################################\n\n    # read params\n    #scriptdir = os.path.dirname(os.path.realpath(__file__))\n    with open('./trRosettaPyRosetta/data/params.json') as jsonfile:\n        params = json.load(jsonfile)\n\n    args = {'pcut':params['PCUT'], 'mode':2,  'wdir':params['WDIR'], 'steps':1000, 'use_orient':True, 'fast_relax':True}\n    #set FASTA, NPZ, OUT\n    args['FASTA'] = fasta\n    args['NPZ'] = npz\n    args['OUT'] = out\n    params['PCUT'] = args['pcut']\n    params['USE_ORIENT'] = args['use_orient']\n    # init PyRosetta\n    init('-hb_cen_soft -relax:default_repeats 5 -default_max_cycles 200 -out:level 100')\n\n    # Create temp folder to store all the restraints\n    tmpdir = tempfile.TemporaryDirectory(prefix=args['wdir']+'/')\n    params['TDIR'] = tmpdir.name\n    print('temp folder:     ', tmpdir.name)\n\n    # read and process restraints & sequence\n    npz = np.load(args['NPZ'])\n    print (type(npz))\n    seq = read_fasta(args['FASTA'])\n    L = len(seq)\n    print (L)\n    params['seq'] = seq\n    rst = gen_rst(npz,tmpdir,params)\n    seq_polyala = 'A'*len(seq)\n\n\n    ########################################################\n    # Scoring functions and movers\n    ########################################################\n    sf = ScoreFunction()\n    sf.add_weights_from_file('./trRosettaPyRosetta/data/scorefxn.wts')\n\n    sf1 = ScoreFunction()\n    sf1.add_weights_from_file('./trRosettaPyRosetta/data/scorefxn1.wts')\n\n    sf_vdw = ScoreFunction()\n    sf_vdw.add_weights_from_file('./trRosettaPyRosetta/data/scorefxn_vdw.wts')\n\n    sf_cart = ScoreFunction()\n    sf_cart.add_weights_from_file('./trRosettaPyRosetta/data/scorefxn_cart.wts')\n\n    mmap = MoveMap()\n    mmap.set_bb(True)\n    mmap.set_chi(False)\n    mmap.set_jump(True)\n\n    min_mover = MinMover(mmap, sf, 'lbfgs_armijo_nonmonotone', 0.0001, True)\n    min_mover.max_iter(1000)\n\n    min_mover1 = MinMover(mmap, sf1, 'lbfgs_armijo_nonmonotone', 0.0001, True)\n    min_mover1.max_iter(1000)\n\n    min_mover_vdw = MinMover(mmap, sf_vdw, 'lbfgs_armijo_nonmonotone', 0.0001, True)\n    min_mover_vdw.max_iter(500)\n\n    min_mover_cart = MinMover(mmap, sf_cart, 'lbfgs_armijo_nonmonotone', 0.0001, True)\n    min_mover_cart.max_iter(1000)\n    min_mover_cart.cartesian(True)\n\n    repeat_mover = RepeatMover(min_mover, 3)\n\n\n    ########################################################\n    # initialize pose\n    ########################################################\n    pose = pose_from_sequence(seq, 'centroid' )\n\n    # mutate GLY to ALA\n    for i,a in enumerate(seq):\n        if a == 'G':\n            mutator = rosetta.protocols.simple_moves.MutateResidue(i+1,'ALA')\n            mutator.apply(pose)\n            print('mutation: G%dA'%(i+1))\n\n    set_random_dihedral(pose)\n    remove_clash(sf_vdw, min_mover_vdw, pose)\n\n    ########################################################\n    # minimization\n    ########################################################\n\n    if args['mode'] == 0:\n\n        # short\n        print('short')\n        add_rst(pose, rst, 1, 12, params)\n        repeat_mover.apply(pose)\n        min_mover_cart.apply(pose)\n        remove_clash(sf_vdw, min_mover1, pose)\n\n        # medium\n        print('medium')\n        add_rst(pose, rst, 12, 24, params)\n        repeat_mover.apply(pose)\n        min_mover_cart.apply(pose)\n        remove_clash(sf_vdw, min_mover1, pose)\n\n        # long\n        print('long')\n        add_rst(pose, rst, 24, len(seq), params)\n        repeat_mover.apply(pose)\n        min_mover_cart.apply(pose)\n        remove_clash(sf_vdw, min_mover1, pose)\n\n    elif args['mode'] == 1:\n\n        # short + medium\n        print('short + medium')\n        add_rst(pose, rst, 3, 24, params)\n        repeat_mover.apply(pose)\n        min_mover_cart.apply(pose)\n        remove_clash(sf_vdw, min_mover1, pose)\n\n        # long\n        print('long')\n        add_rst(pose, rst, 24, len(seq), params)\n        repeat_mover.apply(pose)\n        min_mover_cart.apply(pose)\n        remove_clash(sf_vdw, min_mover1, pose)\n\n    elif args['mode'] == 2: #default behavior\n\n        # short + medium + long\n        print('short + medium + long')\n        add_rst(pose, rst, 1, len(seq), params)\n        repeat_mover.apply(pose)\n        min_mover_cart.apply(pose)\n        remove_clash(sf_vdw, min_mover1, pose)\n\n\n    # mutate ALA back to GLY\n    for i,a in enumerate(seq):\n        if a == 'G':\n            mutator = rosetta.protocols.simple_moves.MutateResidue(i+1,'GLY')\n            mutator.apply(pose)\n            print('mutation: A%dG'%(i+1))\n\n\n    ########################################################\n    # full-atom refinement\n    ########################################################\n\n    if args['fast_relax'] == True:\n\n        sf_fa = create_score_function('ref2015')\n        sf_fa.set_weight(rosetta.core.scoring.atom_pair_constraint, 5)\n        sf_fa.set_weight(rosetta.core.scoring.dihedral_constraint, 1)\n        sf_fa.set_weight(rosetta.core.scoring.angle_constraint, 1)\n\n        mmap = MoveMap()\n        mmap.set_bb(True)\n        mmap.set_chi(True)\n        mmap.set_jump(True)\n\n        relax = rosetta.protocols.relax.FastRelax()\n        relax.set_scorefxn(sf_fa)\n        relax.max_iter(200)\n        relax.dualspace(True)\n        relax.set_movemap(mmap)\n\n        pose.remove_constraints()\n        switch = SwitchResidueTypeSetMover(\"fa_standard\")\n        switch.apply(pose)\n\n        print('relax...')\n        params['PCUT'] = 0.15\n        add_rst(pose, rst, 1, len(seq), params, True)\n        relax.apply(pose)\n\n    ########################################################\n    # save final model\n    ########################################################\n    pose.dump_pdb(args['OUT'])\n\n\ndef runOnDirectories():\n    #generate test PDBs for trRosetta predictions currently done\n\n    #for each MSA, attempt trRosetta structural prediction\n    #for cutoffLevel in cutoffs:\n    predDir = \"./SKEMPI_CHAIN_FILES/trRosettaOutputs/\"\n    fastaDir = \"./SKEMPI_CHAIN_FILES/fastaFiles/\"\n    pdbDir = \"./SKEMPI_CHAIN_FILES/pdbStructures/\"\n\n    allFiles = os.listdir(predDir)\n    print (len(os.listdir(predDir)))\n    failedFiles = []\n    for i in range(0,len(allFiles)):\n        print (\"ON \", i , \" OUT OF \", len(allFiles))\n        fileName = allFiles[i]\n        try:\n            nameComps = fileName.replace(\"_keras_xaa.npz\",\"\").split(\"_\") #need recombine all but last list entry\n            actualName = \"_\".join(nameComps[0:len(nameComps)-1])\n            pdbName = \"_\".join(nameComps[0:len(nameComps)])\n            print (fileName, actualName)\n            fastaFile = fastaDir + actualName + \".fasta\"\n            npzFile = predDir +fileName\n            pdbName = pdbDir + pdbName + \".pdb\"\n            print (\"PDB: \", pdbName)\n            print (\"NPZ: \", npzFile)\n            print (\"FASTA: \", fastaFile)\n            if not os.path.isfile(pdbName) and os.path.isfile(npzFile):\n                #if str(cutoffLevel) in fileName:\n                generatePDB(fastaFile, npzFile, pdbName)\n            else:\n                print (\"pdb exists\")\n        except:\n            print (\"attempt failed, problem with trRosetta output?\")\n            failedFiles.append(fileName)\n\n    allPDBs = os.listdir(pdbDir)\n    print (len(allPDBs))\n    print (\"Failed files: \")\n    print (failedFiles)\n\nif __name__ == '__main__':\n    fasta = \"./TR015032_results/negative_279.fasta\"\n    predNPZ = \"./TR015032_results/seq.npz\"\n    startTime = time.time()\n    generatePDB(fasta, predNPZ, \"trRosettaPredV1.pdb\")\n    print (\"OVERALL TIME: \")\n    print (time.time() - startTime)\n", "meta": {"hexsha": "bd1d751aff5d1ac8db435a67ddbbff2aa843047c", "size": 17098, "ext": "py", "lang": "Python", "max_stars_repo_path": "runPyRosettaAWS.py", "max_stars_repo_name": "lafleur1/rgnModified", "max_stars_repo_head_hexsha": "56ffbcefa48d314326f98a5d90e3050aa0d33157", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "runPyRosettaAWS.py", "max_issues_repo_name": "lafleur1/rgnModified", "max_issues_repo_head_hexsha": "56ffbcefa48d314326f98a5d90e3050aa0d33157", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "runPyRosettaAWS.py", "max_forks_repo_name": "lafleur1/rgnModified", "max_forks_repo_head_hexsha": "56ffbcefa48d314326f98a5d90e3050aa0d33157", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.196, "max_line_length": 151, "alphanum_fraction": 0.5215814715, "include": true, "reason": "import numpy", "num_tokens": 5031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.29098087851200094, "lm_q1q2_score": 0.18112376303110816}}
{"text": "import numpy as np\n\nfrom astropy import units as u, constants as c\nfrom astropy.io import fits\n\nfrom importer import *\nimport utils as ut\nfrom spectrophot import Spec2Phot\nimport regrid\n\nimport manga_tools as m\nfrom manga_elines import get_emline_qty\nimport spec_tools\n\nfrom elines import (balmer_low, balmer_high, helium, bright_metal, faint_metal)\nfrom itertools import chain\n\nclass MaNGA_deredshift(object):\n    '''\n    class to deredshift reduced MaNGA data based on velocity info from DAP\n\n    preserves cube information, in general\n\n    also builds in a check on velocity coverage, and computes a mask\n    '''\n\n    spaxel_side = 0.5 * u.arcsec\n\n    def __init__(self, drp_hdulist, dap_hdulist, drpall_row,\n                 max_vel_unc=500. * u.Unit('km/s'), drp_dlogl=None):\n        self.drp_hdulist = drp_hdulist\n        self.dap_hdulist = dap_hdulist\n        self.drpall_row = drpall_row\n        self.plateifu = self.drp_hdulist[0].header['PLATEIFU']\n\n        self.vel = dap_hdulist['STELLAR_VEL'].data * u.Unit('km/s')\n        self.vel_ivar = dap_hdulist['STELLAR_VEL_IVAR'].data * u.Unit(\n            'km-2s2')\n\n        self.z = drpall_row['nsa_z']\n\n        # mask all the spaxels that have high stellar velocity uncertainty\n        self.vel_ivar_mask = (1. / np.sqrt(self.vel_ivar)) > max_vel_unc\n        self.vel_mask = m.mask_from_maskbits(\n            self.dap_hdulist['STELLAR_VEL_MASK'].data, [30])\n\n        self.drp_l = drp_hdulist['WAVE'].data\n        self.drp_logl = np.log10(self.drp_l)\n        if drp_dlogl is None:\n            drp_dlogl = ut.determine_dlogl(self.drp_logl)\n        self.drp_dlogl = drp_dlogl\n\n        flux_hdu, ivar_hdu, l_hdu = (drp_hdulist['FLUX'], drp_hdulist['IVAR'],\n                                     drp_hdulist['WAVE'])\n\n        self.flux = flux_hdu.data\n        self.ivar = ivar_hdu.data\n\n        self.units = {'l': u.AA, 'flux': u.Unit('1e-17 erg s-1 cm-2 AA-1')}\n\n        self.S2P = Spec2Phot(lam=(self.drp_l * self.units['l']),\n                             flam=(self.flux * self.units['flux']))\n\n        self.DONOTUSE = m.mask_from_maskbits(drp_hdulist['MASK'].data, [10])\n\n        self.ivar *= ~self.DONOTUSE\n\n    @classmethod\n    def from_plateifu(cls, plate, ifu, MPL_v, kind, row=None,\n                      **kwargs):\n        '''\n        load a MaNGA galaxy from a plateifu specification\n        '''\n\n        plate, ifu = str(plate), str(ifu)\n\n        if row is None:\n            drpall = m.load_drpall(MPL_v, index='plateifu')\n            row = drpall.loc['{}-{}'.format(plate, ifu)]\n\n        drp_hdulist = m.load_drp_logcube(plate, ifu, MPL_v)\n        dap_hdulist = m.load_dap_maps(plate, ifu, MPL_v, kind)\n        return cls(drp_hdulist, dap_hdulist, row, **kwargs)\n\n    @classmethod\n    def from_fakedata(cls, plate, ifu, MPL_v, basedir='fakedata', row=None,\n                      kind='SPX-MILESHC-MILESHC', **kwargs):\n        '''\n        load fake data based on a particular already-observed galaxy\n        '''\n\n        plate, ifu = str(plate), str(ifu)\n\n        if row is None:\n            drpall = m.load_drpall(MPL_v, index='plateifu')\n            row = drpall.loc['{}-{}'.format(plate, ifu)]\n\n        drp_hdulist = fits.open(\n            os.path.join(basedir, '{}-{}_drp.fits'.format(plate, ifu)))\n        dap_hdulist = fits.open(\n            os.path.join(basedir, '{}-{}_dap.fits'.format(plate, ifu)))\n\n        return cls(drp_hdulist, dap_hdulist, row, **kwargs)\n\n    def transform_to_restframe(self, l, f, ivar):\n        '''\n        bring cube into rest frame\n        '''\n\n        # shift into restframe\n        l_rest, f_rest, ivar_rest = ut.redshift(\n            l=l, f=f, ivar=ivar, z_in=self.z_map, z_out=0.)\n\n        return l_rest, f_rest, ivar_rest\n\n    def correct_and_match(self, template_logl, template_dlogl=None,\n                          method='drizzle', dered_kwargs={}):\n        '''\n        gets datacube ready for PCA analysis:\n            - take out galactic extinction\n            - compute per-spaxel redshifts\n            - deredshift observed spectra\n            - raise alarms where templates don't cover enough l range\n            - return subarrays of flam, ivar\n\n        (this does not perform any fancy interpolation, just \"shifting\")\n        (nor are emission line features masked--that must be done in post-)\n        '''\n        if template_dlogl is None:\n            template_dlogl = spec_tools.determine_dlogl(template_logl)\n\n        if template_dlogl != self.drp_dlogl:\n            raise csp.TemplateCoverageError(\n                'template and input spectra must have same dlogl: ' +\n                'template\\'s is {}; input spectra\\'s is {}'.format(\n                    template_dlogl, self.drp_dlogl))\n\n        # correct for MW extinction\n        r_v = 3.1\n        EBV = self.drp_hdulist[0].header['EBVGAL']\n        f_mwcorr, ivar_mwcorr = ut.extinction_correct(\n            l=self.drp_l * u.AA, f=self.flux,\n            ivar=self.ivar, r_v=r_v, EBV=EBV)\n\n        l_rest, f_rest, ivar_rest = self.transform_to_restframe(\n            self.drp_l, f_mwcorr, ivar_mwcorr)\n\n        # and make photometric object to reflect rest-frame spectroscopy\n        ctr = [i // 2 for i in self.z_map.shape]\n        # approximate rest wavelength of whole cube as rest wavelength\n        # of central spaxel\n        l_rest_ctr = l_rest[:, ctr[0], ctr[1]]\n        self.S2P_rest = Spec2Phot(lam=(l_rest_ctr * self.units['l']),\n                                  flam=(f_rest * self.units['flux']))\n\n        self.regrid = regrid.Regridder(\n            loglgrid=template_logl, loglrest=np.log10(l_rest),\n            frest=f_rest, ivarfrest=ivar_rest, dlogl=template_dlogl)\n\n        # call appropriate regridder method\n        flux_regr, ivar_regr = getattr(\n            self.regrid, method)(**dered_kwargs)\n\n        spax_mask = np.logical_or.reduce((\n            self.vel_mask, self.vel_ivar_mask))\n\n        self.flux_regr, self.ivar_regr, self.spax_mask = flux_regr, ivar_regr, spax_mask\n\n        return flux_regr, ivar_regr, spax_mask\n\n    def compute_eline_mask(self, template_logl, template_dlogl=None, ix_eline=7,\n                           half_dv=300. * u.Unit('km/s')):\n\n        el_l_air = [balmer_low, balmer_high, helium, bright_metal, faint_metal]\n\n        # find mask width for all spaxels\n        mask_velwidth = determine_eline_mask_dv(\n            self.dap_hdulist, minimum_value=half_dv.value, n_times_sigma=1.5)\n\n        if template_dlogl is None:\n            template_dlogl = spec_tools.determine_dlogl(template_logl)\n\n        EW = self.eline_EW(ix=ix_eline)\n\n        add_balmer_low = (EW >= 0. * u.AA)\n        add_balmer_high = (EW >= 2. * u.AA)\n        add_helium = (EW >= 10. * u.AA)\n        add_brightmetal = (EW >= 0. * u.AA)\n        add_faintmetal = (EW >= 10. * u.AA)\n        linelistflags = [add_balmer_low, add_balmer_high, add_helium,\n                         add_brightmetal, add_faintmetal]\n        # full list of mask flags: one corresponds to each line in each eline dict\n        useflags = list(chain(*map(lambda a: [a[0]] * len(a[1]),\n                                   zip(linelistflags, el_l_air))))\n\n        temlogl = template_logl\n        teml = 10.**temlogl\n        temlogel = np.log(teml)\n\n        #full_mask = np.zeros((len(temlogl),) + EW.shape, dtype=bool)\n\n        el_lel_vac = np.concatenate(list(map(\n            lambda d: np.log(spec_tools.air2vac(np.array(list(d.values())),\n                                                u.AA).value), el_l_air)))\n\n        # iterate through eline types\n        full_mask = np.logical_or.reduce(\n            [masked_around_line(\n                 line_logel=lel, dv_map=mask_velwidth, obs_logel=temlogel) * \\\n                     flag[None, :, :]\n            for flag, lel in zip(useflags, el_lel_vac)])\n\n        return full_mask\n\n    def eline_EW(self, ix):\n        return self.dap_hdulist['EMLINE_SEW'].data[ix] * u.Unit('AA')\n\n    def coadd(self, tem_l, good=None):\n        '''\n        return coadded spectrum and ivar\n\n        params:\n         - good: map of good spaxels\n        '''\n\n        if good is None:\n            good = np.ones_like(self.flux_regr[0, ...])\n\n        ivar = self.ivar_regr * good[None, ...]\n\n        flux, ivar = ut.coadd(f=self.flux_regr, ivar=ivar)\n        lam, flux, ivar = (tem_l[:, None, None], flux[:, None, None],\n                           ivar[:, None, None])\n\n        return lam, flux, ivar\n\n    # =====\n    # properties\n    # =====\n\n    @property\n    def z_map(self):\n        # prepare to de-redshift\n        # total redshift of each spaxel\n        z_map = (1. + self.z) * (1. + (self.vel / c.c).to('').value) - 1.\n        z_map[self.vel_mask] = self.z\n        return z_map\n\n    @property\n    def SB_map(self):\n        # RIMG gives nMgy/pix\n        return self.drp_hdulist['RIMG'].data * \\\n            1.0e-9 * m.Mgy / self.spaxel_side**2.\n\n    @property\n    def Reff(self):\n        r_ang = self.dap_hdulist['SPX_ELLCOO'].data[0, ...]\n        Re_ang = self.drpall_row['nsa_elpetro_th50_r']\n        return r_ang / Re_ang\n\n    # =====\n    # staticmethods\n    # =====\n\n    @staticmethod\n    def a_map(f, logl, dlogl):\n        lllims = 10.**(logl - 0.5 * dlogl)\n        lulims = 10.**(logl + 0.5 * dlogl)\n        dl = (lulims - lllims)[:, np.newaxis, np.newaxis]\n        return np.mean(f * dl, axis=0)\n\n\ndef determine_eline_mask_dv(dap_hdulist, minimum_value=300., n_times_sigma=2.5):\n    '''\n    determine the velocity mask width for MaNGA cube\n    '''\n    sigma = get_emline_qty(dap_hdulist, qty='GSIGMA', key='Ha-6564',\n                           sn_th=3., maskbits=range(32))\n    # where (sigma < minimum_value) or mask is True, use minimum_value\n    dv = (n_times_sigma * sigma.data).clip(min=minimum_value)\n    return dv * (u.km / u.s)\n\n\ndef masked_around_line(line_logel, dv_map, obs_logel):\n    '''\n    make cube mask for a single line\n    '''\n    dlogel_map = (dv_map / c.c).decompose().value\n    logel_mask_l = line_logel - dlogel_map[None, :, :]\n    logel_mask_u = line_logel + dlogel_map[None, :, :]\n    ismasked = np.logical_and(\n        (obs_logel[:, None, None] >= logel_mask_l),\n        (obs_logel[:, None, None] <= logel_mask_u))\n    return ismasked\n", "meta": {"hexsha": "5f43cf1e2487fc0c9f4c87b334ea45a660a4033d", "size": 10165, "ext": "py", "lang": "Python", "max_stars_repo_path": "rectify.py", "max_stars_repo_name": "CSwigg/stellarmass_pca", "max_stars_repo_head_hexsha": "6d7f3e8e4d3d637432d1bac6ed17a837c0ca9c75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-19T16:47:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-19T16:47:10.000Z", "max_issues_repo_path": "rectify.py", "max_issues_repo_name": "zpace/stellarmass_pca", "max_issues_repo_head_hexsha": "81a2cec022c9eef83646020ff22a2d56e584826e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2016-06-19T05:39:10.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-02T01:14:23.000Z", "max_forks_repo_path": "rectify.py", "max_forks_repo_name": "zpace/pcay", "max_forks_repo_head_hexsha": "81a2cec022c9eef83646020ff22a2d56e584826e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-23T14:13:17.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-23T14:13:17.000Z", "avg_line_length": 34.4576271186, "max_line_length": 88, "alphanum_fraction": 0.5920314806, "include": true, "reason": "import numpy,from astropy", "num_tokens": 2883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.18112374747358678}}
{"text": "import sys\nfrom pylab import *\nbase = '../'\nsys.path.append(base+\"utils/Continuum\")\nsys.path.append(base+\"utils/Correlation\")\nsys.path.append(base+\"utils/OptExtract\")\nsys.path.append(base+\"utils/GLOBALutils\")\n\nbaryc_dir= base+'utils/SSEphem/'\nsys.path.append(baryc_dir)\nephemeris='DEc403'\n\nimport matplotlib\nmatplotlib.use(\"Agg\") \nimport matplotlib.pyplot as plt\n\n# ceres modules\nimport continuum\nimport correlation\nimport Marsh\nimport arcesutils\nimport GLOBALutils\n\n# other useful modules\nimport pyfits\nimport pickle\nimport os\nimport numpy as np\nimport scipy\nimport scipy.interpolate\nimport string\nimport argparse\nfrom math import radians as rad\nfrom matplotlib.backends.backend_pdf import PdfPages\nimport ephem\nimport jplephem\n\nimport statsmodels.api as sm\nlowess = sm.nonparametric.lowess\n\nparser = argparse.ArgumentParser()\nparser.add_argument('directorio')\nparser.add_argument('-ofind', default='last')\nparser.add_argument('-o2do',default='all')\nparser.add_argument('-just_extract', action=\"store_true\", default=False)\nparser.add_argument('-do_class', action=\"store_true\", default=False)\nparser.add_argument('-avoid_plot', action=\"store_true\", default=False)\nparser.add_argument('-npools', default=1)\nparser.add_argument('-reffile',default='default')\nparser.add_argument('-dirout',default='default')\n\nargs = parser.parse_args()\n\ndirin       = args.directorio\nstst        = args.ofind\nobject2do   = args.o2do\nJustExtract = args.just_extract\navoid_plot  = args.avoid_plot\nnpools      = int(args.npools)\nreffile     = args.reffile\ndirout      = args.dirout\nDoClass     = args.do_class\n\nif dirin[-1] != '/':\n    dirin = dirin + '/'\n\nif dirout == 'default':\n    dirout = dirin[:-1]+'_red/'\n\nif not os.access(dirout,os.F_OK):\n    os.system('mkdir '+dirout)\nif os.access(dirout+'proc',os.F_OK):\n    os.system('rm -r '+dirout+'proc')\nos.system('mkdir '+dirout+'proc')\n\nf_res = open(dirout+'proc/'+'results.txt','w')\n\nif reffile == 'default':\n    reffile = dirin+'reffile.txt'\n\n####### GLOBAL VARIABLES #####\nforce_pre_process  = False\nforce_flat\t   = False\nforce_P            = False\nforce_flat_extract = False\nforce_thar_extract = False\nforce_thar_wavcal  = False\nforce_sci_extract  = False\nforce_bkg          = False\nforce_spectral_file_build = True\nforce_stellar_pars = True\ndumpargon          = False\nminlines_glob      = 500\nInverse_m          = True\nuse_cheby          = True\nMRMS               = 100   # max rms in m/s, global wav solution\n\ntrace_degree       = 5\nMarsh_alg          = 0\next_aperture       = 5\nNSigma_Marsh       = 30\nNCosmic_Marsh      = 10\nS_Marsh            = 0.4\nN_Marsh            = 3      # grado polinomio \nmin_extract_col    = 200\nmax_extract_col    = 1847\n\nncoef_x            = 4\nncoef_m            = 6\nnpar_wsol = (min(ncoef_x,ncoef_m) + 1) * (2*max(ncoef_x,ncoef_m) - min(ncoef_x,ncoef_m) + 2) / 2\nmodels_path = base+\"data/COELHO_MODELS/R_40000b/\"\norder_dir   = base+\"arces/wavcals/\"\n\nn_useful = 90    # up to which order do we care?\nbinning = 1\n\n#############################\nlog = dirout+'night.log'\n\nprint \"\\n\\n\\tARCES APO3.5m  PIPELINE\\n\"\nprint \"\\tRAW data is in \",dirin\nprint \"\\tProducts of reduction will be in\",dirout\nprint '\\n'\nbiases, quartzB, quartzR, science, thars, thar_dates, obnames, exptimes = arcesutils.FileClassify(dirin,log,binning)\nnightlog = open(log,'r')\nloglines = nightlog.readlines()\nprint \"\\tThese are all the images to proccess:\"\nfor line in loglines:\n\tprint '\\t'+line[:-1]\nprint '\\n'\nif stst == 'last':\n\tif os.access(dirout+'findstar.txt',os.F_OK):\n\t\tfst = open(dirout+'findstar.txt','r')\n\t\tstst = fst.readline()\n\t\tfst.close()\n\telse:\n\t\traise ValueError(\"There is not a previously defined standard star file!!! You have to enter one (i.e. -ofind pfs0001.fits).\\n\")\nelse:\n\tfst = open(dirout+'findstar.txt','w')\n\tfst.write(stst+'\\n')\n\tfst.close()\n\nif (     (os.access(dirout+'FlatB.fits',       os.F_OK) == False)\tor \\\n\t (os.access(dirout+'FlatR.fits',       os.F_OK) == False)\tor \\\n         (os.access(dirout+'MasterBias.fits', os.F_OK) == False)\tor \\\n         (os.access(dirout+'trace.pkl',       os.F_OK) == False)\tor \\\n         (force_pre_process) ):\n    print \"\\tNo previous pre-processing files or found\"\n    pre_process = 1\nelse:\n    print \"\\tPre-processing files found, going straight to extraction\"\n    pre_process = 0\n\nif (pre_process == 1):\n    # median combine Biases\n    print \"\\tGenerating Master calibration frames...\"\n\n    if len(biases)!=0:\n\tMasterBias, RO_bias, GA_bias = arcesutils.MedianCombine(biases)\n\tprint \"\\t\\t-> Masterbias: done!\"\n    else:\n\tMasterBias, RO_bias, GA_bias = np.zeros((2048,2048)),0,1\n\tprint \"\\t\\t\\tWarning: 0 biases\"\n    hdu = pyfits.PrimaryHDU( MasterBias )\n    if (os.access(dirout+'MasterBias.fits',os.F_OK)):\n\t    os.remove(dirout+'MasterBias.fits')\n    hdu.writeto(dirout+'MasterBias.fits')\n\n    # median combine list of ob flats\n    FlatR, RO_flatR, GA_flatR = arcesutils.MedianCombine(quartzR, bias = MasterBias)\n    FlatB, RO_flatB, GA_flatB = arcesutils.MedianCombine(quartzB, bias = MasterBias)\n    print \"\\t\\t-> Masterflats: done!\"\n\n    # save this file for later reference\n    hdu = pyfits.PrimaryHDU( FlatR )\n    if (os.access(dirout+'FlatR.fits',os.F_OK)):\n        os.remove(dirout+'FlatR.fits')\n    hdu.writeto(dirout+'FlatR.fits')\n    hdu = pyfits.PrimaryHDU( FlatB )\n    if (os.access(dirout+'FlatB.fits',os.F_OK)):\n        os.remove(dirout+'FlatB.fits')\n    hdu.writeto(dirout+'FlatB.fits')\n    \n    # Find orders & traces\n    print \"\\tTracing echelle orders...\"\n    c_all, nord = GLOBALutils.get_them( FlatB + FlatR, ext_aperture, trace_degree, maxords=-1,mode=1 )\n    print \"\\t\\t\\t\", nord, 'orders found ...'\n\n    trace_dict = {'c_all':c_all, 'nord':nord, 'GA_bias': GA_bias, 'RO_bias': RO_bias, \\\n                  'GA_flatB': GA_flatB, 'RO_flatB': RO_flatB, 'GA_flatR': GA_flatR, 'RO_flatR': RO_flatR}\n    pickle.dump( trace_dict, open( dirout+\"trace.pkl\", 'w' ) )\n\n\nelse:\n    print '\\tLoading Masterbias, Masterflat and traces'\n    trace_dict = pickle.load( open( dirout+\"trace.pkl\", 'r' ) )\n    c_all = trace_dict['c_all']\n    nord = trace_dict['nord']\n    GA_bias = trace_dict['GA_bias']\n    RO_bias = trace_dict['RO_bias']\n    GA_flatR = trace_dict['GA_flatR']\n    RO_flatR = trace_dict['RO_flatR']\n    GA_flatB = trace_dict['GA_flatB']\n    RO_flatB = trace_dict['RO_flatB']\n    # recover flats & master bias\n    h = pyfits.open(dirout+'FlatR.fits')\n    FlatR = h[0].data\n    h = pyfits.open(dirout+'FlatB.fits')\n    FlatB = h[0].data\n    h = pyfits.open(dirout+'MasterBias.fits')\n    MasterBias = h[0].data\n\nPref_fits = dirout + 'P_ref.fits'\nforce_Pref = False\nif ( os.access(Pref_fits,os.F_OK) == False ) or (force_Pref):\n\tprint \"\\n\\tDetermining reference weights for optimal extraction...\"\n\th = pyfits.open(dirin+stst)[0]\n\tron  = h.header['RDNOISE']\n\tgain = h.header['GAIN']\n\thth = pyfits.getheader(dirin+stst)\n\td = h.data\n\td = arcesutils.OverscanTrim(d)\n\td = arcesutils.bad_col_corr(d)\n\td -= MasterBias\n\tc_alls = c_all.copy()\n\tCenters = np.zeros((len(c_alls),d.shape[1]))\n\tfor i in range(nord):\n\t\tCenters[i,:]=scipy.polyval(c_alls[i,:],np.arange(len(Centers[i,:])))\n\tbkg_obj_fits = dirout + 'BKG_' + 'Pref.fits'\n\tif ( os.access(bkg_obj_fits,os.F_OK) == False or force_bkg):\n\t\tbkg = GLOBALutils.get_scat(d,Centers,span=4)\n\t\tif (os.access(bkg_obj_fits,os.F_OK)):\n\t\t\tos.remove( bkg_obj_fits )\n\t\thdu = pyfits.PrimaryHDU( bkg )\n\t\thdu.writeto( bkg_obj_fits )\n\telse:\n\t\tbkg = pyfits.getdata(bkg_obj_fits)\n\td -= bkg\n\tif os.access(Pref_fits,os.F_OK) == False or force_P:\n\t\tP_ref = np.zeros( d.shape )\n\t\tfor i in range(nord):\t\n\t\t\tP_marsh = GLOBALutils.PCoeff( d, c_alls[i,:], ext_aperture, ron, gain, NSigma_Marsh, S_Marsh, N_Marsh, Marsh_alg , min_extract_col, max_extract_col )\n\t\t\tP_ref += P_marsh\n\t\t\n\t\tif (os.access(Pref_fits,os.F_OK)):\n\t\t\tos.remove( Pref_fits )\n\t\thdu = pyfits.PrimaryHDU( P_ref )\n\t\thdu.writeto( Pref_fits )\nelse:\n\tprint \"\\tWeights for optimal extraction loaded...\"\n\tP_ref = pyfits.getdata(Pref_fits)\n\n# Extract Flat\nprint '\\n\\tExtraction of Flat calibration frames:'\nFlat_spec_fits = dirout + 'Flat_spec.fits'\nP_fits = dirout + 'P_flat.fits'\nif ( os.access(Flat_spec_fits,os.F_OK) == False ) or (force_flat_extract):\n\tprint \"\\t\\tNo previous Flat extracted or extraction forced, extracting and saving...\"\n\tc_alls = c_all.copy()\n\tCenters = np.zeros((len(c_alls),FlatB.shape[1]))\n\n\tif os.access(P_fits,os.F_OK) == False or force_P:\n\t\tP = np.zeros( FlatB.shape )\n\t\tfor i in range(nord):\n\t\t\tP_marsh = GLOBALutils.PCoeff( FlatR+FlatB, c_alls[i,:], ext_aperture,\\\n                                  RO_flatR, GA_flatR, NSigma_Marsh*10, S_Marsh, 2, Marsh_alg,\\\n                                  min_extract_col, max_extract_col )\n\t\t\tP += P_marsh\n\t\tif (os.access(P_fits,os.F_OK)):\n\t\t\tos.remove( P_fits )\n\t\thdu = pyfits.PrimaryHDU( P )\n\t\thdu.writeto( P_fits )\n\telse:\n\t\tP = pyfits.getdata(P_fits)\n\n\tflat_S  = GLOBALutils.optimal_extraction(FlatB+FlatR,P,c_all,ext_aperture,RO_flatB,GA_flatB,\\\n                                       S_Marsh,10*NCosmic_Marsh,min_extract_col,max_extract_col,npools) \n\n\tfor i in range(nord):\n\t\tflat_S[i,1,:] = flat_S[i,1,:][::-1]\n\t\tflat_S[i,2,:] = flat_S[i,2,:][::-1]\n\t\t\t\n        if (os.access(Flat_spec_fits,os.F_OK)):\n            os.remove( Flat_spec_fits )\n\thdu = pyfits.PrimaryHDU( flat_S )\n        hdu.writeto( Flat_spec_fits )\nelse: \n\tprint \"\\tExtracted flat found, loading...\"\n\tflat_S = pyfits.getdata( Flat_spec_fits )\n\nthar_az,thar_al  = [],[]\nthar_ra,thar_dec = [],[]\nprint '\\n\\tExtraction of ThAr calibration frames:'\n# Extract all ThAr files\nfor fsim in thars:\n    hthar = pyfits.open( fsim )[0]\n    dthar = arcesutils.OverscanTrim( hthar.data )\n    dthar = arcesutils.bad_col_corr(dthar) - MasterBias\n    thar_az.append(hthar.header['TELAZ'])\n    thar_al.append(hthar.header['TELALT'])\n    ra  = hthar.header['RA']\n    ra  = float(ra.split(':')[0]) + float(ra.split(':')[1])/60. + float(ra.split(':')[2])/3600.\n    ra  = ra * 360. / 24.\n    dec = hthar.header['DEC']\n    dec = float(dec.split(':')[0]) + float(dec.split(':')[1])/60. + float(dec.split(':')[2])/3600.\n    thar_ra.append(ra)\n    thar_dec.append(dec)\n    hd = pyfits.getheader(fsim)\n    thar_fits = dirout + 'ARCES_' + hthar.header['DATE-OBS'] + '.ThAr.spec.fits'\n\n    if ( os.access(thar_fits,os.F_OK) == False ) or (force_thar_extract):\n        print \"\\t\\tNo previous extraction or extraction forced for ThAr file\", fsim, \"extracting...\"\n        thar_S = np.zeros( (nord,dthar.shape[1]) )\n\tthar_S  = GLOBALutils.simple_extraction(dthar,c_all,ext_aperture,min_extract_col,max_extract_col,npools)\n        for i in range(nord):\n            thar_S[i]  = thar_S[i][::-1]\n            \n        # save as fits file\n        if (os.access(thar_fits,os.F_OK)):\n            os.remove( thar_fits )\n        hdu = pyfits.PrimaryHDU( thar_S )\n        hdu.writeto( thar_fits )\n    else:\n        print \"\\t\\tThAr file\", fsim, \"all ready extracted, loading...\"\n\nthar_az, thar_al = np.array(thar_az), np.array(thar_al)\n# Compute wavelength calibration of ThAr\nprint '\\n\\tWavelength solution of ThAr calibration spectra:'\nsorted_thar_dates = np.argsort( thar_dates )\nbadind = []\nfor i in range(len(thars)):\n    index = sorted_thar_dates[i]\n    hthar = pyfits.open( thars[index] )\n    wavsol_pkl = dirout + 'ARCES_' + '_' + hthar[0].header['DATE-OBS']+'.wavsolpars.pkl'\n    if ( os.access(wavsol_pkl,os.F_OK) == False ) or (force_thar_wavcal):\n        print \"\\t\\tWorking on initial ThAr file\", thars[index] \n        \n        mjd, mjd0 = arcesutils.mjd_fromheader( hthar )\n        thar_fits = dirout + 'ARCES_' + hthar[0].header['DATE-OBS'] + '.ThAr.spec.fits'\n        thar_S = pyfits.getdata( thar_fits )\n\thd = pyfits.getheader(thar_fits)\n\tthar_out = dirout + 'ARCES_' + hthar[0].header['DATE-OBS'] + '.ThAr.wav.fits'\n\n\tthar_data = np.zeros((2,n_useful,thar_S.shape[1]))\n\n        lines_thar  = thar_S.copy()\n        \n        All_Pixel_Centers = np.array([])\n        All_Wavelengths   = np.array([])\n        All_Orders        = np.array([])\n        All_Centroids     = np.array([])\n        All_Sigmas        = np.array([])\n        All_Intensities   = np.array([])\n\n\tforce_corr = True\n\tif os.access(dirout+'id_orders.pkl',os.F_OK) == False or force_corr:\n\t\tmaxes = 0\n\t\tor41 = 0\n\t\tfor order in range(len(lines_thar)):\n\t\t\tccf_max, shift = GLOBALutils.cor_thar(lines_thar[order],span=10,filename=order_dir+'arces_order41.dat')\n\t\t\tif ccf_max > maxes:\n\t\t\t\tmaxes       = ccf_max\n\t\t\t\trough_shift = shift\n\t\t\t\tor41        =  order\n\t\tprint '\\t\\t\\tThe real echelle order 41 is order',or41\n\t\tprint '\\t\\t\\tShift in pixels:',rough_shift\n\t\tor0 = or41 - 41\n\t\tor10 = 10 + or0\n\t\t\t\n\t\tif or0 >= 0:\n\t\t\torwa = 0\n\t\telse:\n\t\t\torwa = - or0\n\t\t\tor0  = 0\n\t\tif os.access(dirout+'id_orders.pkl',os.F_OK):\n\t\t\tos.remove(dirout+'id_orders.pkl')\n\t\t\t\n\t\tpdict = {'or0':or0, 'orwa':orwa, 'or10':or10, 'rough_shift':rough_shift}\n\t\tpickle.dump( pdict, open(dirout+'id_orders.pkl', 'w' ) )\n\telse:\n\t\tpdict = pickle.load(open(dirout+'id_orders.pkl','r'))\n\t\tor10 = pdict['or10']\n\t\n\t\t\n\torder = or10\n\tworder = 10\n\tmedl = []\n        while order <= or10 + n_useful:\n            order_s = str(worder)\n            if (worder < 10):\n                order_s = '0'+str(worder)\n            \n            thar_order_orig = lines_thar[order,:]\n            thar_order      = thar_order_orig - scipy.signal.medfilt(thar_order_orig, 21)\n\t    \n            coeffs_pix2wav, coeffs_pix2sigma, pixel_centers, wavelengths, rms_ms, residuals, centroids, sigmas, intensities \\\n                = GLOBALutils.Initial_Wav_Calibration(order_dir+'arces_order'+order_s+'.dat', thar_order, order, np.ones(len(thar_order)),rmsmax=1000, minlines=4,FixEnds=False,Dump_Argon=dumpargon,Dump_AllLines=True, Cheby=use_cheby,porder=3,rough_shift=rough_shift)\n\t    medl.append(GLOBALutils.Cheby_eval(coeffs_pix2wav,.5*len(thar_order),len(thar_order)))\n\n            if (worder == 55): \n                if (use_cheby):\n                    Global_ZP = GLOBALutils.Cheby_eval( coeffs_pix2wav, 0.5*len(thar_order), len(thar_order))\n                else:\n                    Global_ZP = scipy.polyval( coeffs_pix2wav, 0.0 )\n\n            All_Pixel_Centers = np.append( All_Pixel_Centers, pixel_centers )\n            All_Wavelengths   = np.append( All_Wavelengths, wavelengths )\n            All_Orders        = np.append( All_Orders, np.zeros( len(pixel_centers) ) + worder )\n            All_Centroids     = np.append( All_Centroids, centroids)\n            All_Sigmas        = np.append( All_Sigmas, sigmas)\n            All_Intensities   = np.append( All_Intensities, intensities )\n\t   \n\t    order +=1\n\t    worder +=1\n\n        p0 = np.zeros( npar_wsol )\n        p0[0] =  (55+52) * Global_ZP \n        p1, G_pix, G_ord, G_wav, II, rms_ms, G_res = \\\n            GLOBALutils.Fit_Global_Wav_Solution(All_Pixel_Centers,All_Wavelengths,All_Orders,\\\n                                                     np.ones(All_Intensities.shape),p0,Cheby=use_cheby,\\\n                                                     maxrms=100, Inv=Inverse_m,minlines=minlines_glob,order0=52,\\\n\t\t\t\t\t\t     ntotal=n_useful,npix=len(thar_order),nx=ncoef_x,nm=ncoef_m)\n\n\tequis = np.arange( thar_S.shape[1] )\n\torder = 0\n\twhile order < n_useful:\n            m = order + 52 + 10\n            chebs = GLOBALutils.Calculate_chebs(equis, m, order0=52, ntotal=n_useful,\\\n\t\t\t\t\t\tnpix=thar_S.shape[1],Inverse=Inverse_m,nx=ncoef_x,nm=ncoef_m)\n            WavSol = (1./m) * GLOBALutils.Joint_Polynomial_Cheby(p1,chebs,ncoef_x,ncoef_m)   \n            thar_data[0,order] = WavSol\n\t    thar_data[1,order] = lines_thar[order+or10,:]\n\t    order  += 1\n\n\tif (os.access(thar_out,os.F_OK)):\n            os.remove( thar_out )\n            \n        hdu = pyfits.PrimaryHDU( thar_data )\n        hdu.writeto( thar_out )\n\n        pdict = {'p1':p1,'mjd':mjd, 'G_pix':G_pix, 'Gobname_ord':G_ord, 'G_wav':G_wav, 'II':II, 'rms_ms':rms_ms,\\\n                     'G_res':G_res, 'All_Centroids':All_Centroids, 'All_Orders':All_Orders, 'All_Sigmas':All_Sigmas}\n        pickle.dump( pdict, open( wavsol_pkl, 'w' ) )\n\n    else:\n        print \"\\t\\tUsing previously computed wavelength solution in file\",wavsol_pkl\n        pdict           = pickle.load(open(wavsol_pkl,'r'))\n    \n    if pdict['rms_ms']/np.sqrt(float(len(pdict['II']))) > 10:\n\tbadind.append(index)\n\npditct2 = pickle.load(open(dirout+'id_orders.pkl','r'))\nor10 = pditct2['or10']\nthars = np.array(thars)\nthar_dates = np.array(thar_dates)\nif len(badind)>0:\n\tthars = np.delete(thars,badind)\n\tthar_dates = np.delete(thar_dates,badind)\n\tthar_ra = np.delete(thar_ra,badind)\n\tthar_dec = np.delete(thar_dec,badind)\n\nprint '\\n\\tStarting science frame reductions'\n\n### start of science frame reductions ###\nnew_list = []\nnew_list_obnames = []\nnew_list_texp = []\nfor i in range(len(science)):\n    fsim   = science[i]\n    obname = obnames[i]\n    texp   = exptimes[i]\n    if (object2do == 'all'):\n        new_list.append(fsim)\n        new_list_obnames.append( obname )\n        new_list_texp.append( texp )\n    else:\n        if (obname == object2do):\n            new_list.append(fsim)\n            new_list_obnames.append( obname )\n            new_list_texp.append( texp )\n\n# Does any image have a special requirement for dealing with the moonlight?\nif os.access(dirin + 'moon_corr.txt', os.F_OK):\n    fmoon = open(dirin + 'moon_corr.txt','r')\n    moon_lns = fmoon.readlines()\n    spec_moon = []\n    use_moon = []\n    for line in moon_lns:\n        spec_moon.append(line.split()[0])\n        if line.split()[1] == '0':\n            use_moon.append(False)\n        else:\n            use_moon.append(True)\nelse:\n    spec_moon = []\n    use_moon = []\n\nspec_moon = np.array(spec_moon)\nuse_moon  = np.array(use_moon)\n\n\nfor nlisti in range(len(new_list)):\n    fsim   = new_list[ nlisti ]\n    obname = new_list_obnames[ nlisti ]\n    TEXP   =  new_list_texp[ nlisti ]\n\n    know_moon = False\n    if fsim.split('/')[-1] in spec_moon:\n        I = np.where(fsim.split('/')[-1] == spec_moon)[0]\n        know_moon = True\n        here_moon = use_moon[I]\n\n    h = pyfits.open(fsim)\n\n    print \"\\n\\t-->\\tWorking on image: \", fsim\n\n    # get mjd and mjd0\n    mjd,mjd0 = arcesutils.mjd_fromheader(h)\n\n    #  get gain and readnoise of object \n    ronoise = h[0].header['RDNOISE']\n    gain    = h[0].header['GAIN']\n\n    print \"\\t\\tObject name:\",obname\n\n    # Find lambda_bary/lambda_topo using baryc\n    altitude    = 2788.\n    latitude    = h[0].header['LATITUDE']\n    longitude   = h[0].header['LONGITUD']\n    ra          = h[0].header['RA']\n    ra  = float(ra.split(':')[0]) + float(ra.split(':')[1])/60. + float(ra.split(':')[2])/3600.\n    ra  = ra * 360. / 24.\n    dec         = h[0].header['DEC']\n    dec = float(dec.split(':')[0]) + float(dec.split(':')[1])/60. + float(dec.split(':')[2])/3600.\t\n    epoch       = h[0].header['EQUINOX']\n\n    ra2,dec2 = GLOBALutils.getcoords(obname,mjd,filen=reffile)\n    if ra2 !=0 and dec2 != 0:\n        ra = ra2\n        dec = dec2\n    else:\n        print '\\t\\tUsing the coordinates found in the image header.'\n\n    iers          = GLOBALutils.JPLiers( baryc_dir, mjd-999.0, mjd+999.0 )\n    obsradius, R0 = GLOBALutils.JPLR0( latitude, altitude)\n    obpos         = GLOBALutils.obspos( longitude, obsradius, R0 )\n    jplephem.set_ephemeris_dir( baryc_dir , ephemeris )\n    jplephem.set_observer_coordinates( obpos[0], obpos[1], obpos[2] )\n\n    res = jplephem.doppler_fraction(ra/15.0, dec, int(mjd), mjd%1, 1, 0.0)\n    lbary_ltopo = 1.0 + res['frac'][0]\n    bcvel_baryc = ( lbary_ltopo - 1.0 ) * 2.99792458E5\n    print '\\t\\tBarycentric velocity:', bcvel_baryc\n    res = jplephem.pulse_delay(ra/15.0, dec, int(mjd), mjd%1, 1, 0.0)\n    mbjd = mjd + res['delay'][0] / (3600.0 * 24.0)\n\n    # Moon Phase Calculations\n    gobs = ephem.Observer()  \n    gobs.name='APO3.5'  \n    gobs.lat=rad(latitude)  # lat/long in decimal degrees  \n    gobs.long=rad(longitude)\n\n    DDATE = h[0].header['DATE-OBS'].split('T')[0]\n    HHOUR = h[0].header['DATE-OBS'].split('T')[1]\n    Mho = HHOUR[:2]\n    Mmi = HHOUR[3:5]\n    Mse = HHOUR[6:]\n    gobs.date = str(DDATE[:4]) + '-' +  str(DDATE[5:7]) + '-' + str(DDATE[8:]) + ' ' +  Mho + ':' + Mmi +':' + Mse\n    mephem = ephem.Moon()\n    mephem.compute(gobs)\n    #print \"Barycentric moon velocity:\", bcvel_baryc_moon, mjd\n    Mcoo = jplephem.object_track(\"Moon\", int(mjd), float(mjd%1), 1, 0.0)\n    Mp = jplephem.barycentric_object_track(\"Moon\", int(mjd), float(mjd%1), 1, 0.0)\n    Sp = jplephem.barycentric_object_track(\"Sun\", int(mjd), float(mjd%1), 1, 0.0)\n    res  = jplephem.object_doppler(\"Moon\", int(mjd), mjd%1, 1, 0.0)\n    lunation,moon_state,moonsep,moonvel = GLOBALutils.get_lunar_props(ephem,gobs,Mcoo,Mp,Sp,res,ra,dec)\n    refvel = bcvel_baryc + moonvel\n    print '\\t\\tRadial Velocity of sacttered moonlight:',refvel\n\n    sorted_indices = np.argsort( np.abs( np.array(thar_dates) - mjd ) )\n\n    # optimally and simply extract spectra\n    sci_fits = dirout + 'ARCES_' + h[0].header['DATE-OBS'] + '.' + obname +'.spec.fits'\n    sci_fits_simple = dirout + 'ARCES_' + h[0].header['DATE-OBS'] +'.'+ obname +'.spec.simple.fits'\n    P_fits = dirout + 'P_' +  h[0].header['DATE-OBS'] +'.'+ obname +'.fits'\n\n    # Open file, trim, overscan subtract and MasterBias subtract\n    data = h[0].data\n    data = arcesutils.OverscanTrim(data)\n    data = arcesutils.bad_col_corr(data)\n\n    if ( os.access(sci_fits,os.F_OK) == False ) or ( os.access(sci_fits_simple,os.F_OK) == False ) or (force_sci_extract):\n        data -= MasterBias\n        #print '\\t\\t\\tRecentering traces...'\n        c_alls = c_all.copy()\n        c_alls, pshift = GLOBALutils.retrace( data, c_all, span=5 )\n\n        Centers = np.zeros((len(c_alls),data.shape[1]))\n        for i in range(nord):\n            Centers[i,:]=scipy.polyval(c_alls[i,:],np.arange(len(Centers[i,:])))\n        bkg_obj_fits = dirout + 'BKG_' + h[0].header['DATE-OBS'] +'.'+ obname +'.fits'\n        if ( os.access(bkg_obj_fits,os.F_OK) == False or force_bkg):\n            bkg = GLOBALutils.get_scat(data,Centers,span=4)\n\n            if (os.access(bkg_obj_fits,os.F_OK)):\n                os.remove( bkg_obj_fits )\n            hdu = pyfits.PrimaryHDU( bkg )\n            hdu.writeto( bkg_obj_fits )\n        else:\n            bkg = pyfits.getdata(bkg_obj_fits)\n        data -= bkg\n\n        print '\\t\\tExtraction:'\n\t    #print '\\t\\tComputing weights...'\n\n        if os.access(P_fits,os.F_OK) == False or force_P:\n            P = GLOBALutils.obtain_P(data,c_alls,ext_aperture,ronoise,\\\n                        gain,NSigma_Marsh, S_Marsh, N_Marsh, Marsh_alg, min_extract_col, max_extract_col, npools)\n\n            if (os.access(P_fits,os.F_OK)):\n                os.remove( P_fits )\n            hdu = pyfits.PrimaryHDU( P )\n            hdu.writeto( P_fits )\n        else:\n            P = pyfits.getdata(P_fits)\n\n        print \"\\t\\t\\tNo previous extraction or extraction forced for science file\", fsim, \"extracting...\"\n\n        sci_Ss = GLOBALutils.simple_extraction(data,c_alls,ext_aperture,\\\n                                                  min_extract_col,max_extract_col,npools)\n        sci_S  = GLOBALutils.optimal_extraction(data,P,c_alls,ext_aperture,\\\n                                                   ronoise,gain,S_Marsh,NCosmic_Marsh,\\\n                                                   min_extract_col,max_extract_col,npools)\n\n        for i in range(nord):\n            sci_S[i,1,:] = sci_S[i,1,:][::-1]\n            sci_S[i,2,:] = sci_S[i,2,:][::-1]\n            sci_Ss[i,:]  = sci_Ss[i][::-1]\n\n        # save as fits file\n        if (os.access(sci_fits,os.F_OK)):\n            os.remove( sci_fits )\n        if (os.access(sci_fits_simple,os.F_OK)):\n            os.remove( sci_fits_simple )\n\n        hdu = pyfits.PrimaryHDU( sci_S )\n        hdu.writeto( sci_fits )\n        hdu = pyfits.PrimaryHDU( sci_Ss )\n        hdu.writeto( sci_fits_simple )\n\n    else:\n        print '\\t\\t'+fsim, \"has already been extracted, reading in product fits files...\"\n        sci_S = pyfits.getdata( sci_fits )\n        sci_Ss = pyfits.getdata( sci_fits_simple )\n\n    fout = 'proc/'+ obname + '_' + h[0].header['DATE-OBS'] + '_' + 'sp.fits'\n\n    #Build spectra\n    if ( os.access(dirout+fout ,os.F_OK) == False ) or (force_spectral_file_build):\n        # initialize file that will have the spectra\n        spec = np.zeros((11, n_useful, data.shape[1]))\n        hdu = pyfits.PrimaryHDU( spec )\n        hdu = GLOBALutils.update_header(hdu,'HIERARCH MJD', mjd)\n        hdu = GLOBALutils.update_header(hdu,'HIERARCH MBJD', mbjd)\n        hdu = GLOBALutils.update_header(hdu,'HIERARCH SHUTTER START DATE', h[0].header['DATE-OBS'].split('T')[0] )\n        hdu = GLOBALutils.update_header(hdu,'HIERARCH SHUTTER START UT',  h[0].header['DATE-OBS'].split('T')[1])\n        hdu = GLOBALutils.update_header(hdu,'HIERARCH TEXP (S)',h[0].header['EXPTIME'])\n        hdu = GLOBALutils.update_header(hdu,'HIERARCH BARYCENTRIC CORRECTION (KM/S)', bcvel_baryc)\n        hdu = GLOBALutils.update_header(hdu,'HIERARCH (LAMBDA_BARY / LAMBDA_TOPO)', lbary_ltopo)    \n        hdu = GLOBALutils.update_header(hdu,'HIERARCH TARGET NAME', obname)\n        hdu = GLOBALutils.update_header(hdu,'HIERARCH RA',h[0].header['RA'])\n        hdu = GLOBALutils.update_header(hdu,'HIERARCH DEC',h[0].header['DEC'])\n        hdu = GLOBALutils.update_header(hdu,'HIERARCH RA BARY',ra)\n        hdu = GLOBALutils.update_header(hdu,'HIERARCH DEC BARY',dec)\n        hdu = GLOBALutils.update_header(hdu,'HIERARCH EQUINOX',h[0].header['EQUINOX'])\n        hdu = GLOBALutils.update_header(hdu,'HIERARCH OBS LATITUDE',h[0].header['LATITUDE'])\n        hdu = GLOBALutils.update_header(hdu,'HIERARCH OBS LONGITUDE',h[0].header['LONGITUD'])\n        hdu = GLOBALutils.update_header(hdu,'HIERARCH OBS ALTITUDE',2788.)\n        hdu = GLOBALutils.update_header(hdu,'HIERARCH TARG AIRMASS',h[0].header['AIRMASS'])\n\n        print '\\t\\tWavelength calibration:'\n        # get ThAr closest in time and position\n        if len(sorted_indices)>1:\n            indice1 = sorted_indices[0]\n            indice2 = sorted_indices[1]\n            dist1ra = np.absolute( thar_ra[indice1] - ra )\n            dist2ra = np.absolute( thar_ra[indice2] - ra )\n            if dist1ra > 180:\n                dist1ra = 360 - dist1ra\n            if dist2ra > 180:\n                dist2ra = 360 - dist2ra\n            dist1 = (dist1ra)**2 + (thar_dec[indice1] - dec)**2\n            dist2 = (dist2ra)**2 + (thar_dec[indice2] - dec)**2\n            indice = indice1\n            if dist2 < dist1:\n                indice = indice2\n        else:\n            indice = sorted_indices[0]\n\n        hthar = pyfits.open(thars[indice])\n        thar_fits_ob = dirout + 'ARCES_' +  hthar[0].header['DATE-OBS'] +'.ThAr.spec.fits'\n        pkl_wsol = dirout + 'ARCES__' + hthar[0].header['DATE-OBS'] +'.wavsolpars.pkl'\n        print \"\\t\\t\\tUnpickling wavelength solution from\", pkl_wsol, \" ...\"\n        wsol_dict = pickle.load(open(pkl_wsol,'r'))\n\n        # Apply new wavelength solution including barycentric correction\n        equis = np.arange( data.shape[1] )        \n        #print '\\t\\tMaking final output...' \n        for order in range(n_useful):\n            m = order + 10 + 52\n            chebs = GLOBALutils.Calculate_chebs(equis, m, npix=data.shape[1], order0=52, ntotal=n_useful, Inverse=Inverse_m,nx=ncoef_x,nm=ncoef_m)\n            WavSol = lbary_ltopo * (1.0/m) * GLOBALutils.Joint_Polynomial_Cheby(wsol_dict['p1'],chebs,ncoef_x,ncoef_m)   \n            spec[0,order,:] = GLOBALutils.ToVacuum(WavSol)\n            spec[1,order,:] = sci_S[order+or10,1, :]\n            spec[2,order,:] = sci_S[order+or10,2, :]\n            I = np.where(flat_S[order+or10,1]!=0)[0]\n            spec[3,order,I] = spec[1,order,I] / flat_S[order+or10,1,I]\n            spec[4,order,I] = spec[2,order,I] * flat_S[order+or10,1,I] ** 2\n            nJ = np.where(np.isnan(spec[3,order])==True)[0]\n            nJ2 = np.where(np.isinf(spec[3,order])==True)[0]\n            spec[3,order,nJ] = 1.\n            spec[3,order,nJ2] = 1.\n            IJJ = np.where(spec[3,order]!=0)[0]\n            if len(IJJ)>0:\n                cont_coef = GLOBALutils.get_cont_single(spec[0,order],spec[3,order],spec[4,order],ll=1.5,lu=5,nc=3)   \n                ratio = np.polyval(cont_coef, spec[0,order,:])\n            else:\n                ratio = np.ones(len(spec[3,order]))\n            L  = np.where( spec[1,order,:] != 0 )\n            spec[5,order,:][L] = spec[3,order,:][L] / ratio[L]\n            nJ = np.where(np.isnan(spec[5,order])==True)[0]\n            nJ2 = np.where(np.isinf(spec[5,order])==True)[0]\n            spec[5,order,nJ] = 1.0\n            spec[5,order,nJ2] = 1.0\n            rI = np.where(spec[5,order] > 1. + 8./spec[8,order])\n            spec[5,order,rI] = 1.\n            spec[6,order,:][L] = spec[4,order,:][L] * (ratio[L] ** 2 )\n            spec[7,order,:][L] = ratio[L]\n            spec[8,order,:][L] = ratio[L] * flat_S[order,1][L] / np.sqrt( ratio[L] * flat_S[order,1][L] / gain + (ronoise/gain)**2 )\n            spl           = scipy.interpolate.splrep(np.arange(WavSol.shape[0]), WavSol,k=3)\n            dlambda_dx    = scipy.interpolate.splev(np.arange(WavSol.shape[0]), spl, der=1)\n            NN            = np.average(dlambda_dx)\n            dlambda_dx    /= NN\n\n            spec[9,order,:][L] = spec[5,order,:][L] * (dlambda_dx[L] ** 1) \n            spec[10,order,:][L] = spec[6,order,:][L] / (dlambda_dx[L] ** 2)\n\n    else:\n        spec = pyfits.getdata(dirout+fout)\n\n    imax,oMg = 0,0\n    for i in range(spec.shape[1]):\n        IM = np.where((spec[0,i]>5160)&(spec[0,i]<5200))[0]\n        if len(IM)>imax:\n            imax = len(IM)\n            oMg  = i\n    SNR_5130 = np.median(spec[8,oMg,1000:1101] )\n\n    JustExtract = False\n    if (not JustExtract):\n        if DoClass:\n            print '\\t\\tSpectral Analysis:'\n            # spectral analysis\n            query_success = False\n            query_success,sp_type_query = GLOBALutils.simbad_query_obname(obname)\n            if (not query_success):\n                query_success,sp_type_query = GLOBALutils.simbad_query_coords('12:00:00','00:00:00')\n            print \"\\t\\t\\tSpectral type returned by SIMBAD query:\",sp_type_query\n\n            hdu = GLOBALutils.update_header(hdu,'HIERARCH SIMBAD SPTYP', sp_type_query)\n            pars_file = dirout + 'ARCES_' + h[0].header['DATE-OBS'] + '.' + obname +'_stellar_pars.txt'\n\n            if os.access(pars_file,os.F_OK) == False or force_stellar_pars:\n                print \"\\t\\t\\tEstimating atmospheric parameters:\"\n                T_eff, logg, Z, vsini, vel0, ccf = correlation.CCF(spec,model_path=models_path,npools=npools)\n                line = \"%6d %4.1f %4.1f %8.1f %8.1f\\n\" % (T_eff,logg, Z, vsini, vel0)\n                f = open(pars_file,'w')\n                f.write(line)\n                f.close()\n            else:\n                print \"\\t\\t\\tAtmospheric parameters loaded from file:\"\n                T_eff, logg, Z, vsini, vel0 = np.loadtxt(pars_file,unpack=True)\n\n            print \"\\t\\t\\t\\tT_eff=\",T_eff,\"log(g)=\",logg,\"Z=\",Z,\"vsin(i)=\",vsini,\"vel0\",vel0\n\n        else:\n            T_eff, logg, Z, vsini, vel0 = -999,-999,-999,-999,-999\n\n        # store the parameters measured for this epoch\n        T_eff_epoch = T_eff\n        logg_epoch  = logg\n        Z_epoch     = Z\n        vsini_epoch = vsini\n        vel0_epoch  = vel0\n\n        hdu = GLOBALutils.update_header(hdu,'HIERARCH TEFF', float(T_eff))\n        hdu = GLOBALutils.update_header(hdu,'HIERARCH LOGG', float(logg))\n        hdu = GLOBALutils.update_header(hdu,'HIERARCH Z', Z)\n        hdu = GLOBALutils.update_header(hdu,'HIERARCH VSINI', vsini)\n        hdu = GLOBALutils.update_header(hdu,'HIERARCH VEL0', vel0)\n\n        print \"\\t\\tRadial Velocity analysis:\"\n        # assign mask\n        sp_type, mask = GLOBALutils.get_mask_reffile(obname,reffile=reffile,base='../data/xc_masks/')\n        print \"\\t\\t\\tWill use\",sp_type,\"mask for CCF.\"\n        # Read in mask\n        # make mask larger accounting for factor ~3 lower res in Arces w/r to HARPS\n        ml, mh, weight = np.loadtxt(mask,unpack=True)\n        ml_v = GLOBALutils.ToVacuum( ml )\n        mh_v = GLOBALutils.ToVacuum( mh )\n        av_m = 0.5*( ml_v + mh_v )\n        ml_v -= 2.*(av_m - ml_v)\n        mh_v += 2.*(mh_v - av_m)\n\n        mask_hw_kms = (GLOBALutils.Constants.c/1e3) * 0.5*(mh_v - ml_v) / av_m\n        disp = GLOBALutils.get_disp(obname, reffile=reffile)\n        if disp == 0:\n            known_sigma = False\n            if vsini != -999 and vsini != 0.:\n                disp = vsini\n            else:\n                disp = 3.\n        else:\n            known_sigma = True\n\n        mask_hw_wide = av_m * disp / (GLOBALutils.Constants.c/1.0e3)\n        ml_v = av_m - mask_hw_wide\n        mh_v = av_m + mask_hw_wide \n\n        print '\\t\\t\\tComputing the CCF...'\n        cond = True\n        while (cond):\n            # first rough correlation to find the minimum\n            vels, xc_full, sn, nlines_ccf, W_ccf = \\\n                    GLOBALutils.XCor(spec, ml_v, mh_v, weight, 0, lbary_ltopo, vel_width=300,vel_step=3,\\\n                                          spec_order=9,iv_order=10,sn_order=8,max_vel_rough=300)\n            xc_av = GLOBALutils.Average_CCF(xc_full, sn, sn_min=3.0, Simple=True, W=W_ccf)\n            # Normalize the continuum of the CCF robustly with R     \n            yy = scipy.signal.medfilt(xc_av,11)\n            I = np.where(np.isnan(yy))[0]\n            if len(I)==0:\n                pred = lowess(yy, vels,frac=0.4,it=10,return_sorted=False)\n                tck1 = scipy.interpolate.splrep(vels,pred,k=1)\n                xc_av_orig = xc_av.copy()\n                xc_av /= pred\n                vel0_xc = vels[ np.argmin( xc_av ) ] \n                rvels, rxc_av, rpred, rxc_av_orig, rvel0_xc = vels.copy(), xc_av.copy(), pred.copy(), xc_av_orig.copy(), vel0_xc\n                xc_av_rough = xc_av\n                vels_rough  = vels\n\n                vel_width = np.maximum( 20.0, 6*disp )\n                vels, xc_full, sn, nlines_ccf, W_ccf =\\\n\t\t            GLOBALutils.XCor(spec, ml_v, mh_v, weight, vel0_xc, lbary_ltopo, vel_width=vel_width,vel_step=0.3,\\\n\t\t                                  spec_order=9,iv_order=10,sn_order=8,max_vel_rough=300)\n\n                xc_av = GLOBALutils.Average_CCF(xc_full, sn, sn_min=3.0, Simple=True, W=W_ccf)\n                pred = scipy.interpolate.splev(vels,tck1)\n                xc_av /= pred\n\n                if sp_type == 'M5':\n                    moon_sig = 2.5\n                elif sp_type == 'K5':\n                    moon_sig = 3.3\n                else:\n                    moon_sig = 4.5\n\n                p1,XCmodel,p1gau,XCmodelgau,Ls2 = GLOBALutils.XC_Final_Fit( vels, xc_av , sigma_res = 4, horder=8, moonv = refvel, moons = moon_sig, moon = False)\n                p1_m,XCmodel_m,p1gau_m,XCmodelgau_m,Ls2_m = p1,XCmodel,p1gau,XCmodelgau,Ls2\n\n                confused = False\n                ismoon = False\n                moon_flag = 0\n\n                bspan = GLOBALutils.calc_bss(vels,xc_av)\n                SP = bspan[0]\n\n                moonmatters = False\n                if (know_moon and here_moon):\n                    moonmatters = True\n                    ismoon = True\n                    confused = False\n                    p1_m,XCmodel_m,p1gau_m,XCmodelgau_m,Ls2_m = GLOBALutils.XC_Final_Fit( vels, xc_av , sigma_res = 4, horder=8, moonv = refvel, moons = moon_sig, moon = True)\n                    moon_flag = 1\n\n                else:\n                    confused = False\n                    ismoon = False\n                    p1_m,XCmodel_m,p1gau_m,XCmodelgau_m,Ls2_m = p1,XCmodel,p1gau,XCmodelgau,Ls2\n                    moon_flag = 0\n\n                if (not known_sigma):\n                    disp = np.floor(p1gau[2])\n                    if (disp < 3.0): \n                        disp = 3.0\n                    mask_hw_wide = av_m * disp / (GLOBALutils.Constants.c/1.0e3)\n                    ml_v = av_m - mask_hw_wide\n                    mh_v = av_m + mask_hw_wide            \n                    known_sigma = True\n                else:\n                    cond = False\n                problem = False\n            else:\n                p1,p1gau = 0.,[0,0,0]\n                problem = True\n                cond = False\n\n        if not problem:\n\n            xc_dict = {'vels':vels,'xc_av':xc_av,'XCmodelgau':XCmodelgau,'Ls2':Ls2,'refvel':refvel,\\\n\t\t\t       'rvels':rvels,'rxc_av':rxc_av,'rpred':rpred,'rxc_av_orig':rxc_av_orig,\\\n\t\t\t       'rvel0_xc':rvel0_xc,'xc_full':xc_full, 'p1':p1, 'sn':sn, 'p1gau':p1gau,\\\n\t\t\t       'p1_m':p1_m,'XCmodel_m':XCmodel_m,'p1gau_m':p1gau_m,'Ls2_m':Ls2_m,\\\n\t\t\t       'XCmodelgau_m':XCmodelgau_m}\n\n            moon_dict = {'moonmatters':moonmatters,'moon_state':moon_state,'moonsep':moonsep,\\\n\t\t\t\t 'lunation':lunation,'mephem':mephem,'texp':h[0].header['EXPTIME']}\n\n            pkl_xc = dirout + fsim.split('/')[-1][:-8]+obname+'_XC_'+sp_type+'.pkl'\n            pickle.dump( xc_dict, open( pkl_xc, 'w' ) )\n\n            ccf_pdf = dirout + 'proc/' + fsim.split('/')[-1][:-4] + obname + '_XCs_' + sp_type + '.pdf'\n            if not avoid_plot:\n                GLOBALutils.plot_CCF(xc_dict,moon_dict,path=ccf_pdf)\n\n            airmass  = h[0].header['AIRMASS']\n            seeing   = -999\n\n            if sp_type == 'G2':\n                A = 0.06544\n                B = 0.00146\n                D = 0.24416\n                C = 0.00181\n            elif  sp_type == 'K5':\n                A = 0.05348\n                B = 0.00147\t\n                D = 0.20695\n                C = 0.00321\n            else:\n                A = 0.05348\n                B = 0.00147\t\n                D = 0.20695\n                C = 0.00321\n\n\n            BSerr = D / float(np.round(SNR_5130)) + C\n            RVerr2 = 0.5\n            RV     = np.around(p1gau_m[1],3)  \n            BS     = np.around(SP,3) \n            BSerr = np.around(BSerr,4)\n\n            print '\\t\\t\\tRV = '+str(RV)+' +- '+str(RVerr2)\n            print '\\t\\t\\tBS = '+str(BS)+' +- '+str(BSerr)\n\n            bjd_out = 2400000.5 + mbjd\n            T_eff_err = 100\n            logg_err = 0.5\n            Z_err = 0.5\n            vsini_err = 2\n            XC_min = np.abs(np.around(np.min(XCmodel),2))\n\n            SNR_5130 = np.around(SNR_5130)\n            SNR_5130_R = np.around(SNR_5130*np.sqrt(2.5))\n\n            disp_epoch = np.around(p1gau_m[2],1)\n            hdu = GLOBALutils.update_header(hdu,'RV', RV)\n            hdu = GLOBALutils.update_header(hdu,'RV_E', RVerr2)\n            hdu = GLOBALutils.update_header(hdu,'BS', BS)\n            hdu = GLOBALutils.update_header(hdu,'BS_E', BSerr)\n            hdu = GLOBALutils.update_header(hdu,'DISP', disp_epoch)\n            hdu = GLOBALutils.update_header(hdu,'SNR', SNR_5130)\n            hdu = GLOBALutils.update_header(hdu,'SNR_R', SNR_5130_R)\n            hdu = GLOBALutils.update_header(hdu,'INST', 'ARCES')\n            hdu = GLOBALutils.update_header(hdu,'RESOL', '40000')\n            hdu = GLOBALutils.update_header(hdu,'PIPELINE', 'CERES')\n            hdu = GLOBALutils.update_header(hdu,'XC_MIN', XC_min)\n            hdu = GLOBALutils.update_header(hdu,'BJD_OUT', bjd_out)\n\n            line_out = \"%-15s %18.8f %8.3f %5.3f %5.3f %5.3f arces ceres  40000 %6d %4.1f %4.1f %5.1f %3.1f %3.1f %6.1f %4d %s\\n\"%\\\n                      (obname, bjd_out, RV, RVerr2, BS, BSerr, T_eff_epoch, logg_epoch, Z_epoch, vsini_epoch, XC_min, disp_epoch,\\\n\t\t       TEXP, SNR_5130_R, ccf_pdf)\n            f_res.write(line_out)\n\n    if (os.access( dirout + fout,os.F_OK)):\n        os.remove( dirout + fout)\n    hdu.writeto( dirout + fout )\n\nf_res.close()\n", "meta": {"hexsha": "dbab1761d1a4f6226f4dcbf8ab000c4a383d5142", "size": 39436, "ext": "py", "lang": "Python", "max_stars_repo_path": "arces/arcespipe.py", "max_stars_repo_name": "nespinoza/ceres", "max_stars_repo_head_hexsha": "e5426067bc5855b0f690e4a51b7d6fd2a48471c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "arces/arcespipe.py", "max_issues_repo_name": "nespinoza/ceres", "max_issues_repo_head_hexsha": "e5426067bc5855b0f690e4a51b7d6fd2a48471c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arces/arcespipe.py", "max_forks_repo_name": "nespinoza/ceres", "max_forks_repo_head_hexsha": "e5426067bc5855b0f690e4a51b7d6fd2a48471c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9149797571, "max_line_length": 266, "alphanum_fraction": 0.5970686682, "include": true, "reason": "import numpy,import scipy,import statsmodels", "num_tokens": 12123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.1810858171278222}}
{"text": "\"\"\"\nDefines cages made from building blocks with 3 functional groups.\n\n\"\"\"\n\nimport numpy as np\n\nfrom .base import Cage,  _CageVertex\nfrom ..topology_graph import Edge\n\n\nclass _OnePlusOneVertex(_CageVertex):\n    def __init__(self, x, y, z, edge_normal, use_bonder_placement=True):\n        \"\"\"\n        Initialize a :class:`_CageVertex`.\n\n        Parameters\n        ----------\n        x : :class:`float`\n            The x coordinate.\n\n        y : :class:`float`\n            The y coordinate.\n\n        z : :class:`float`\n            The z coordinate.\n\n        edge_normal : :class:`list` of :class:`int`\n            The edge plane normal to use.\n\n        use_bonder_placement : :class:`bool`, optional\n            If ``True``the position of the vertex will be updated such\n            that it is in the middle of the neighboring bonder\n            centroids, rather than in the middle of the neighboring\n            vertices.\n\n        \"\"\"\n\n        self._edge_normal = edge_normal\n        super().__init__(x, y, z, use_bonder_placement)\n\n    def clone(self, clear_edges=False):\n        \"\"\"\n        Create a clone of the instance.\n\n        Parameters\n        ----------\n        clear_edges : :class:`bool`, optional\n            If ``True`` the :attr:`edges` attribute of the clone will\n            be empty.\n\n        Returns\n        -------\n        :class:`Vertex`\n            A clone with the same position but not connected to any\n            :class:`.Edge` objects.\n\n        \"\"\"\n\n        clone = super().clone(clear_edges)\n        clone._edge_normal = list(self._edge_normal)\n        return clone\n\n    def _place_nonlinear_building_block(self, building_block):\n        \"\"\"\n        Place `building_block` on the :class:`.Vertex`.\n\n        Parameters\n        ----------\n        building_block : :class:`.BuildingBlock`\n            The building block molecule which is to be placed on the\n            vertex.\n\n        Returns\n        -------\n        :class:`numpy.nadarray`\n            The position matrix of `building_block` after being\n            placed.\n\n        \"\"\"\n\n        building_block.set_centroid(\n            position=self._position,\n            atom_ids=building_block.get_bonder_ids()\n        )\n        building_block.apply_rotation_between_vectors(\n            start=building_block.get_bonder_plane_normal(),\n            target=self._edge_normal,\n            origin=self._position\n        )\n        fg_bonder_centroid = building_block.get_centroid(\n            atom_ids=building_block.func_groups[0].get_bonder_ids()\n        )\n        start = fg_bonder_centroid - self._position\n        edge_coord = self.aligner_edge.get_position()\n        target = edge_coord - self._get_edge_centroid()\n        building_block.apply_rotation_to_minimize_angle(\n            start=start,\n            target=target,\n            axis=self._edge_normal,\n            origin=self._position\n        )\n        return building_block.get_position_matrix()\n\n\nclass OnePlusOne(Cage):\n    \"\"\"\n    Represents a capsule cage topology graph.\n\n    See :class:`.Cage` for more details and examples.\n\n    Attributes\n    ----------\n    vertices : :class:`tuple` of :class:`.Vertex`\n        The vertices which make up the topology graph.\n\n    edges : :class:`tuple` of :class:`.Edge`\n        The edges which make up the topology graph.\n\n    \"\"\"\n\n    _x = 1\n    vertices = (\n        _OnePlusOneVertex(_x, 0., 0., [1, 0, 0], False),\n        _OnePlusOneVertex(-_x, 0., 0., [-1, 0, 0], False),\n\n    )\n    edges = (\n        Edge(\n            vertices[0], vertices[1], position=np.array([0., 1., 0.])\n        ),\n        Edge(\n            vertices[0], vertices[1], position=np.array([0., -1., 1.])\n        ),\n        Edge(\n            vertices[0], vertices[1], position=np.array([0., -1., -1.])\n        )\n    )\n\n    num_windows = 3\n    num_window_types = 1\n\n\nclass TwoPlusTwo(Cage):\n    \"\"\"\n    Represents a tetrahedron cage topology graph.\n\n    See :class:`.Cage` for more details and examples.\n\n    Attributes\n    ----------\n    vertices : :class:`tuple` of :class:`.Vertex`\n        The vertices which make up the topology graph.\n\n    edges : :class:`tuple` of :class:`.Edge`\n        The edges which make up the topology graph.\n\n    \"\"\"\n\n    _x = 1\n    vertices = (\n        _CageVertex(_x, 0, -_x/np.sqrt(2), False),\n        _CageVertex(-_x, 0, -_x/np.sqrt(2), False),\n        _CageVertex(0, _x, _x/np.sqrt(2), False),\n        _CageVertex(0, -_x, _x/np.sqrt(2), False)\n    )\n\n    edges = (\n        Edge(vertices[0], vertices[1]),\n        Edge(vertices[0], vertices[2]),\n        Edge(vertices[0], vertices[3]),\n\n        Edge(vertices[1], vertices[2]),\n        Edge(vertices[1], vertices[3]),\n\n        Edge(vertices[2], vertices[3])\n    )\n\n    num_windows = 4\n    num_window_types = 1\n\n\nclass FourPlusFour(Cage):\n    \"\"\"\n    Represents a cube cage topology graph.\n\n    See :class:`.Cage` for more details and examples.\n\n    Attributes\n    ----------\n    vertices : :class:`tuple` of :class:`.Vertex`\n        The vertices which make up the topology graph.\n\n    edges : :class:`tuple` of :class:`.Edge`\n        The edges which make up the topology graph.\n\n    \"\"\"\n\n    _x = 1\n    vertices = (\n        _CageVertex(-_x, _x, -_x, False),\n        _CageVertex(-_x, -_x, -_x, False),\n        _CageVertex(_x, _x, -_x, False),\n        _CageVertex(_x, -_x, -_x, False),\n\n        _CageVertex(-_x, _x, _x, False),\n        _CageVertex(-_x, -_x, _x, False),\n        _CageVertex(_x, _x, _x, False),\n        _CageVertex(_x, -_x, _x, False)\n    )\n\n    edges = (\n        Edge(vertices[0], vertices[1]),\n        Edge(vertices[0], vertices[2]),\n        Edge(vertices[0], vertices[4]),\n        Edge(vertices[1], vertices[3]),\n        Edge(vertices[1], vertices[5]),\n        Edge(vertices[2], vertices[6]),\n        Edge(vertices[2], vertices[3]),\n        Edge(vertices[3], vertices[7]),\n        Edge(vertices[4], vertices[6]),\n        Edge(vertices[4], vertices[5]),\n        Edge(vertices[5], vertices[7]),\n        Edge(vertices[6], vertices[7])\n    )\n\n    num_windows = 6\n    num_window_types = 1\n", "meta": {"hexsha": "84c7d9b37cd9fbbade2cf728c533dec36315a4d1", "size": 6040, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/stk/molecular/topology_graphs/cage/three_plus_three.py", "max_stars_repo_name": "fiszczyp/stk", "max_stars_repo_head_hexsha": "56e75c493a472d98ccbf3af14cc9ce7f12cbe3d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/stk/molecular/topology_graphs/cage/three_plus_three.py", "max_issues_repo_name": "fiszczyp/stk", "max_issues_repo_head_hexsha": "56e75c493a472d98ccbf3af14cc9ce7f12cbe3d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stk/molecular/topology_graphs/cage/three_plus_three.py", "max_forks_repo_name": "fiszczyp/stk", "max_forks_repo_head_hexsha": "56e75c493a472d98ccbf3af14cc9ce7f12cbe3d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3755458515, "max_line_length": 72, "alphanum_fraction": 0.5658940397, "include": true, "reason": "import numpy", "num_tokens": 1528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.35936415202123906, "lm_q1q2_score": 0.18108581367045293}}
{"text": "from pandas.core.indexing import is_nested_tuple\nimport pygplates\nimport numpy as np\nimport pandas as _pd\nimport geopandas as _gpd\n#from shapely.geometry.point import Point\nimport os\n\n\ndef vgp_to_dataframe(vgp_feature_collection, as_geodataframe=True, return_feature_id=False):\n    '''\n    Read a gpml file containing virtual geomagnetic poles to a (geo)pandas dataframe\n    options: \n    input can be either a pygplates FeatureCollection or a \n    as_geodataframe [Bool]: If True (default), returns geopandas geodataframe. If False, \n                            returns a pandas dataframe\n    return_feature_id [Bool]: If True, include a column with GPlates unique feature ids \n                              (default False)                       \n    TODO allow .vgp files to also be read\n    TODO handle cases where mean age or age ranges could be inferred from one another\n    '''\n    \n    if os.path.isfile(vgp_feature_collection):\n        feature_collection = pygplates.FeatureCollection(vgp_feature_collection)\n    elif isinstance(vgp_feature_collection, pygplates.FeatureCollection):\n        feature_collection = vgp_feature_collection\n    else:\n        raise ValueError('Unable to load {:s} as vgp input'.format(vgp_feature_collection))\n\n\n    DataFrameTemplate = ['AverageSampleSiteLongitude','AverageSampleSiteLatitude',\n                         'Name','Description','PoleLongitude','PoleLatitude','PoleA95',\n                         'AverageAge','MaximumAge','MinimumAge','PlateID']\n    if return_feature_id:\n        DataFrameTemplate.append('Feature_ID')\n    \n    # Get attribute (other than coordinate) names from first feature\n    for feature in feature_collection: \n        if feature.get_shapefile_attributes() is not None:\n            for attribute in feature.get_shapefile_attributes():\n                DataFrameTemplate.append(attribute) \n            break\n\n    vgps = []\n    for feature in feature_collection:\n        vgp = []\n        \n        # default columns\n        average_sample_site_position = feature.get(pygplates.PropertyName.create_gpml('averageSampleSitePosition')).get_value().get_geometry().to_lat_lon()\n        #print(type(average_sample_site_position.to_lat_lon()))\n        vgp.append(float(average_sample_site_position[1]))\n        vgp.append(float(average_sample_site_position[0]))\n        vgp.append(str(feature.get_name()))\n        vgp.append(str(feature.get_description()))\n        pole_position = feature.get_geometry().to_lat_lon()\n        vgp.append(float(pole_position[1]))\n        vgp.append(float(pole_position[0]))\n        if feature.get(pygplates.PropertyName.create_gpml('poleA95')):\n            vgp.append(float(feature.get(pygplates.PropertyName.create_gpml('poleA95')).get_value().get_double()))\n        if feature.get(pygplates.PropertyName.create_gpml('averageAge')):\n            vgp.append(float(feature.get(pygplates.PropertyName.create_gpml('averageAge')).get_value().get_double()))\n        feature_valid_time = feature.get_valid_time()\n        vgp.append(float(feature_valid_time[0]))\n        vgp.append(float(feature_valid_time[1]))\n        vgp.append(int(feature.get_reconstruction_plate_id()))\n        \n        # optional\n        if return_feature_id:\n            vgp.append(str(feature.get_feature_id()))\n            \n        # depending on input file\n        if feature.get_shapefile_attributes() is not None:\n            for attribute in feature.get_shapefile_attributes():\n                vgp.append(feature.get_shapefile_attribute(attribute))\n            \n        vgps.append(vgp)\n        \n    if as_geodataframe:\n        df = _pd.DataFrame(vgps,columns=DataFrameTemplate)\n        return _gpd.GeoDataFrame(df, geometry=_gpd.points_from_xy(df.AverageSampleSiteLongitude, \n                                                                  df.AverageSampleSiteLatitude), crs=4326)\n    \n    else:\n        return _pd.DataFrame(vgps,columns=DataFrameTemplate)\n\n\ndef assign_plate_ids(vgps, reconstruction_model):\n    '''\n    assign plate ids to Virtual Geomagnetic Poles (vgps), which is a special case\n    of plate partitioning where we must use the 'AverageSampleSitePosition' rather than\n    the feature geometry\n    The input type can be a geodataframe or a pygplates FeatureCollection. The output type\n    will match the input \n    '''\n\n    plate_partitioner = pygplates.PlatePartitioner(reconstruction_model.static_polygons, \n                                                   reconstruction_model.rotation_model)\n\n    if isinstance(vgps, _gpd.GeoDataFrame):\n        partition_plate_ids = []\n        for i,row in vgps.iterrows():\n            partition_polygon = plate_partitioner.partition_point(pygplates.PointOnSphere(row.geometry.y,\n                                                                                          row.geometry.x))\n            partition_plate_ids.append(partition_polygon.get_feature().get_reconstruction_plate_id())\n\n        vgps['PlateID'] = partition_plate_ids\n\n        return vgps\n\n    elif isinstance(vgps, (pygplates.FeatureCollection, list)):\n        if isinstance(vgps, list):\n            vgps = pygplates.FeatureCollection(vgps)\n        partitioned_vgps = []\n        for vgp in vgps:\n            partition_polygon = plate_partitioner.partition_point(vgp.get(pygplates.PropertyName.gpml_average_sample_site_position).get_value().get_geometry())\n            vgp.set_reconstruction_plate_id(partition_polygon.get_feature().get_reconstruction_plate_id())\n            partitioned_vgps.append(vgp)\n\n        return pygplates.FeatureCollection(partitioned_vgps)\n\n    else:\n        raise TypeError('Unexpected type {:} for vgp input'.format(type(vgps)))\n\n\ndef rotate_to_common_reference(vgps, reconstruction_model, reference_plate_id=701):\n    '''\n    Rotate a collection of vgps to a common reference plate\n    '''\n\n    if isinstance(vgps, _gpd.GeoDataFrame):\n        rotated_vgps = []\n        for i,row in vgps.iterrows():\n            vgp_geometry = pygplates.PointOnSphere(row.PoleLatitude,row.PoleLongitude)\n            feature_rotation = reconstruction_model.rotation_model.get_rotation(row.AverageAge, \n                                                                                row.PlateID, \n                                                                                anchor_plate_id=reference_plate_id)\n\n            reconstructed_geometry = feature_rotation * vgp_geometry\n            rotated_vgps.append(reconstructed_geometry.to_lat_lon())\n\n        vgps.PoleLatitude = list(zip(*rotated_vgps))[0]\n        vgps.PoleLongitude = list(zip(*rotated_vgps))[1]\n\n        return vgps\n        \n\n    elif isinstance(vgps, pygplates.FeatureCollection):\n        rotated_vgps = []\n        for vgp in vgps:\n            feature_rotation = reconstruction_model.rotation_model.get_rotation(vgp.get(pygplates.PropertyName.gpml_average_age).get_value().get_double(), \n                                                                                vgp.get_reconstruction_plate_id(), \n                                                                                anchor_plate_id=reference_plate_id)\n            reconstructed_geometry = feature_rotation * vgp.get_geometry()\n            vgp.set_geometry(reconstructed_geometry)\n            vgp.set_reconstructed_plate_id(reference_plate_id)\n            rotated_vgps.append(vgp)\n\n        return pygplates.FeatureCollection(rotated_vgps)\n\n\ndef generate_running_mean_path(vgps,time_list,time_window=20,right=True):\n\n    import pmagpy.ipmag as ipmag\n\n    running_mean_path = []\n\n    if isinstance(vgps, _gpd.GeoDataFrame):\n        vgps_df = vgps[['PoleLatitude', 'PoleLongitude', 'AverageAge', 'PoleA95']]\n    elif isinstance(vgps, pygplates.FeatureCollection):\n        vgp_list = []\n        for vgp in vgps:\n            vgp_list.append((vgp.get_geometry().to_lat_lon()[0],\n                             vgp.get_geometry().to_lat_lon()[1],\n                             float(vgp.get(pygplates.PropertyName.create_gpml('averageAge')).get_value().get_double()),\n                             float(vgp.get(pygplates.PropertyName.create_gpml('poleA95')).get_value().get_double())))\n        vgps_df = _pd.DataFrame(vgp_list, columns=['PoleLatitude', 'PoleLongitude', 'AverageAge','PoleA95'])\n    else:\n        raise TypeError('Unexpected type {:s} for vgp input'.format(type(vgps)))\n        \n    for mean_pole_age in time_list:\n        if right:\n            vgps_window = vgps_df[(vgps_df['AverageAge']>=mean_pole_age-time_window/2.) \n                                & (vgps_df['AverageAge']<=mean_pole_age+time_window/2.)]\n        else:\n            vgps_window = vgps_df[(vgps_df['AverageAge']>=mean_pole_age-time_window/2.) \n                                & (vgps_df['AverageAge']<mean_pole_age+time_window/2.)]\n        \n        if vgps_window.empty:\n            running_mean_path.append((mean_pole_age,np.nan,np.nan,np.nan))\n\n        elif len(vgps_window)==1:\n            running_mean_path.append((mean_pole_age, np.array(vgps_window['PoleLongitude'])[0], \n                                      np.array(vgps_window['PoleLatitude'])[0], np.array(vgps_window['PoleA95'])[0]))\n\n        else:\n            #print(vgps_window)\n            mean_pole = ipmag.fisher_mean(np.array(vgps_window.PoleLongitude), \n                                          np.array(vgps_window.PoleLatitude))\n            #print(mean_pole)\n\n            running_mean_path.append((mean_pole_age, mean_pole['dec'],\n                                      mean_pole['inc'],mean_pole['alpha95']))\n        \n\n    return _pd.DataFrame(running_mean_path, columns=['Age','PoleLongitude','PoleLatitude','PoleA95'])\n\n\ndef write_vgp_feature(vgp, mapping, half_time_range = 10.):\n    '''\n    Create a vgp feature from one row of a dataframe\n    TODO handle cases where some fields (e.g. description) are not present\n    '''\n    other_properties = [(pygplates.PropertyName.create_gpml('poleA95'), pygplates.XsDouble(vgp[mapping['PoleA95']])),\n                        (pygplates.PropertyName.create_gpml('averageAge'), pygplates.XsDouble(vgp[mapping['AverageAge']]))]\n    if 'geometry' in vgp:\n        other_properties.append(\n            (pygplates.PropertyName.create_gpml('averageSampleSitePosition'),\n            pygplates.GmlPoint(pygplates.PointOnSphere([float(float(vgp.geometry.y)), \n                                                        float(float(vgp.geometry.x))])))\n        )\n\n    vgpFeature = pygplates.Feature.create_reconstructable_feature(\n                 pygplates.FeatureType.create_gpml('VirtualGeomagneticPole'),\n                 pygplates.PointOnSphere([vgp[mapping['PoleLatitude']], vgp[mapping['PoleLongitude']]]),\n                 name = str(vgp[mapping['Name']]),\n                 description = str(vgp[mapping['Description']]),\n                 valid_time=(float(vgp[mapping['AverageAge']])+half_time_range, float(vgp[mapping['AverageAge']])-half_time_range),\n                 other_properties = other_properties)\n\n    if 'ReconstructionPlateID' in mapping:\n        vgpFeature.set_reconstruction_plate_id(int(vgp[mapping['ReconstructionPlateID']]))\n\n    return vgpFeature\n\n\ndef dataframe_to_vgps(gdf, mapping={'Name':'Name',\n                                    'Description':'Description',\n                                    'PoleLongitude':'PoleLongitude',\n                                    'PoleLatitude':'PoleLatitude',\n                                    'PoleA95':'PoleA95',\n                                    'AverageAge':'AverageAge'}):\n    \n    vpgFeatureCollection = []\n\n    for i,row in gdf.iterrows():\n\n        vgpFeature = write_vgp_feature(row, mapping)\n        \n        # Add newly created feature to existing Feature Collection\n        vpgFeatureCollection.append(vgpFeature)\n    \n    return pygplates.FeatureCollection(vpgFeatureCollection)\n\n", "meta": {"hexsha": "32d9e0a4d47d5ac6d8be52a8596788ebcb4cacc2", "size": 11779, "ext": "py", "lang": "Python", "max_stars_repo_path": "gprm/utils/pmag.py", "max_stars_repo_name": "siwill22/GPlatesClassStruggle", "max_stars_repo_head_hexsha": "713a87ff4f054d3a493ec09e5f310aa3036d3bc5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gprm/utils/pmag.py", "max_issues_repo_name": "siwill22/GPlatesClassStruggle", "max_issues_repo_head_hexsha": "713a87ff4f054d3a493ec09e5f310aa3036d3bc5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gprm/utils/pmag.py", "max_forks_repo_name": "siwill22/GPlatesClassStruggle", "max_forks_repo_head_hexsha": "713a87ff4f054d3a493ec09e5f310aa3036d3bc5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.374015748, "max_line_length": 159, "alphanum_fraction": 0.6326513286, "include": true, "reason": "import numpy", "num_tokens": 2461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.359364131437828, "lm_q1q2_score": 0.18108580329834512}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"\nAstronomical and physics constants for Astropy v2.0.\nSee :mod:`astropy.constants` for a complete listing of constants defined\nin Astropy.\n\"\"\"\nimport warnings\n\nfrom astropy.utils import find_current_module\n\nfrom . import codata2014, iau2015\nfrom . import utils as _utils\n\ncodata = codata2014\niaudata = iau2015\n\n_utils._set_c(codata, iaudata, find_current_module())\n\n# Overwrite the following for consistency.\n# https://github.com/astropy/astropy/issues/8920\nwith warnings.catch_warnings():\n    warnings.filterwarnings('ignore', 'Constant .*already has a definition')\n\n    # Solar mass (derived from mass parameter and gravitational constant)\n    M_sun = iau2015.IAU2015(\n        'M_sun', \"Solar mass\", iau2015.GM_sun.value / codata2014.G.value,\n        'kg', ((codata2014.G.uncertainty / codata2014.G.value) *\n               (iau2015.GM_sun.value / codata2014.G.value)),\n        f\"IAU 2015 Resolution B 3 + {codata2014.G.reference}\", system='si')\n\n    # Jupiter mass (derived from mass parameter and gravitational constant)\n    M_jup = iau2015.IAU2015(\n        'M_jup', \"Jupiter mass\", iau2015.GM_jup.value / codata2014.G.value,\n        'kg', ((codata2014.G.uncertainty / codata2014.G.value) *\n               (iau2015.GM_jup.value / codata2014.G.value)),\n        f\"IAU 2015 Resolution B 3 + {codata2014.G.reference}\", system='si')\n\n    # Earth mass (derived from mass parameter and gravitational constant)\n    M_earth = iau2015.IAU2015(\n        'M_earth', \"Earth mass\",\n        iau2015.GM_earth.value / codata2014.G.value,\n        'kg', ((codata2014.G.uncertainty / codata2014.G.value) *\n               (iau2015.GM_earth.value / codata2014.G.value)),\n        f\"IAU 2015 Resolution B 3 + {codata2014.G.reference}\", system='si')\n\n# Clean up namespace\ndel warnings\ndel find_current_module\ndel _utils\n", "meta": {"hexsha": "62f0e0d7eead8bab10c2f01cd93e410f667f6a5c", "size": 1864, "ext": "py", "lang": "Python", "max_stars_repo_path": "astropy/constants/astropyconst20.py", "max_stars_repo_name": "MatiasRepetto/astropy", "max_stars_repo_head_hexsha": "689f9d3b063145150149e592a879ee40af1fac06", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-11T12:26:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-11T12:26:49.000Z", "max_issues_repo_path": "astropy/constants/astropyconst20.py", "max_issues_repo_name": "MatiasRepetto/astropy", "max_issues_repo_head_hexsha": "689f9d3b063145150149e592a879ee40af1fac06", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-10-09T18:54:27.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T18:54:27.000Z", "max_forks_repo_path": "astropy/constants/astropyconst20.py", "max_forks_repo_name": "MatiasRepetto/astropy", "max_forks_repo_head_hexsha": "689f9d3b063145150149e592a879ee40af1fac06", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.28, "max_line_length": 76, "alphanum_fraction": 0.6995708155, "include": true, "reason": "from astropy", "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.18108580329834503}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"Minichess Board Parsing Utility\"\"\"\n\nfrom collections import OrderedDict\n\nimport numpy as np\n\n__author__ = \"Michael Lane\"\n__email__ = \"mikelane@gmail.com\"\n__copyright__ = \"Copyright 2017, Michael Lane\"\n__license__ = \"MIT\"\n\n# Some setup and convenience dicts\npositions = [(r, c) for r in range(6) for c in range(5)]\nstrings = ['{}{}'.format(c, r) for r in range(6, 0, -1) for c in 'abcde']\nints = [1 << i for i in range(29, -1, -1)]\n\npos_to_str = {p: s for p, s in zip(positions, strings)}\npos_to_int = {p: i for p, i in zip(positions, ints)}\nstr_to_pos = {s: p for s, p in zip(strings, positions)}\nstr_to_int = {s: i for s, i in zip(strings, ints)}\nint_to_str = {i: s for i, s in zip(ints, strings)}\nint_to_pos = {i: p for i, p in zip(ints, positions)}\n\nopponent_color = {'B': 'W', 'W': 'B'}\nplayer_number = {'W': 1, 'B': 2}\npiece_types = {'B': 'kqbnrp', 'W': 'PRNBQK'}\n\n\ndef arr_to_int(parsed_board, piece_types):\n    \"\"\"\n    Given a parsed board and a string of piece types, return an integer that represents\n    those locations. Location a6 is bit 29, a6 is bit 28, ... , E1 is bit 1.\n    \n    Parameters\n    ----------\n    parsed_board: A 2d numpy ndarray of strings.\n    piece_types:  A string of allowed piece types similar to 'kqbnrp' or 'KQBNRP' or '.'\n\n    Returns\n    -------\n    An integer that corresponds to the parsed board.\n    \"\"\"\n    result = np.zeros(parsed_board.shape, dtype=np.int)\n    for piece_type in piece_types:\n        result |= (parsed_board == piece_type)  # Numpy makes this task easy\n    # Stringify the flattened array, index out the brackets, remove the spaces and\n    # let python evaluate the binary string.\n    return eval('0b{}'.format(str(result.astype(np.int).ravel())[1:-1].replace(' ', '')))\n\n\ndef get_opponent_locations(parsed_board, color_of_opponent):\n    \"\"\"\n    A utility function that uses arr_to_int to return the appropriate value\n    \n    Parameters\n    ----------\n    parsed_board : The numpy ndarray of strings that represents the board.\n    color_of_opponent: The color of the opponent.\n\n    Returns\n    -------\n    An integer that represents the opponent locations of the parsed bitboard.\n\n    \"\"\"\n    assert color_of_opponent in 'BW'\n    return arr_to_int(parsed_board, piece_types[color_of_opponent])\n\n\ndef get_empty_locations(parsed_board):\n    \"\"\"\n    A wrapper for arr_to_int that passes the empty cell string, '.'\n    Parameters\n    ----------\n    parsed_board: The numpy ndarray of strings that represents the board.\n\n    Returns\n    -------\n    An integer that represents the empty cells of the parsed bitboard\n    \"\"\"\n    return arr_to_int(parsed_board, '.')\n\n\ndef parse_board(board, time_left):\n    \"\"\"\n    Take a board as a string similar to this:\n    \n        1 B\n        kqb.r\n        ppq.q\n        Q....\n        ..N..\n        .PPP.\n        R.BQK\n    \n    and convert it into a list of 25 integers that make up a minichess bitboard.\n    \n    Parameters\n    ----------\n    board: This is the string value of the board\n    time_left: An int of the number of milliseconds left to go.\n\n    Returns\n    -------\n    List of length 24 where the 24 elements represent the following:\n    - The first 20 integers are the locations of the piece types in this order\n      (where lowercase is black, uppercase is white):\n        k, q, b, n, r, p, p, p, p, p, P, P, P, P, P, R, N, B, Q, K\n    - The 21st integer is the move number of the game\n    - The 22nd integer represents the color of the player on move, 1 for white, 2 for black\n    - the 23rd integer is the location of all of the opponents of the player on move\n    - the 24th integer is the location of all the empty cells\n    \"\"\"\n\n    # Set up an intermediate container\n    black_pieces = OrderedDict()  # Python2's dicts aren't ordered. :-P\n    for piece_type in piece_types['B']:\n        black_pieces[piece_type] = None\n\n    white_pieces = OrderedDict()\n    for piece_type in piece_types['W']:\n        white_pieces[piece_type] = None\n\n    # Do the initial parsing of the board string\n    # move_number, on_move_color, *board = board.split()\n    split_board = board.split()\n    move_number, on_move_color, split_board = split_board[0], split_board[1], split_board[2:]\n    move_number = int(move_number)\n    parsed_board = np.array([list(row) for row in split_board])  # numpy makes it all worth it.\n\n    # Get the 23rd and 24th values of the return list\n    opponent_locations = get_opponent_locations(parsed_board, opponent_color[on_move_color])\n    empty_locations = get_empty_locations(parsed_board)\n\n    # Start filling in the intermediate container for black\n    for piece in 'kqbnrp':\n        positions = np.argwhere(parsed_board == piece)  # Returns an array of 2d array locations\n        if positions.size:\n            black_pieces[piece] = np.apply_along_axis(lambda p: pos_to_int[tuple(p)], 1, positions)\n        else:  # Need to have 0 if the piece isn't there.\n            black_pieces[piece] = np.array([0])\n\n    # Handle the case of pawns that have been promoted\n    if black_pieces['q'].size > 1:\n        black_pieces['q'], black_promoted_pawns = np.split(black_pieces['q'], (1,))\n        # Promoted pawns live in the pawn locations in the returned list but with a flag at bit 30\n        black_promoted_pawns = np.apply_along_axis(lambda i: i | (1 << 30), 0, black_promoted_pawns)\n        black_pieces['p'] = np.append(black_promoted_pawns, black_pieces['p'])\n\n    # We have to make sure that all 20 spots in the piece list are filled. Pad 0 when pawns are missing\n    if black_pieces['p'].size < 5:\n        black_pieces['p'] = np.pad(black_pieces['p'], (0, 5 - black_pieces['p'].size), 'constant', constant_values=0)\n\n    # Second verse, same as the first. All the above, but for white.\n    for piece in 'PRNBQK':\n        positions = np.argwhere(parsed_board == piece)\n        if positions.size:\n            white_pieces[piece] = np.apply_along_axis(lambda p: pos_to_int[tuple(p)], 1, positions)\n        else:\n            white_pieces[piece] = np.array([0])\n\n    if white_pieces['Q'].size > 1:\n        white_pieces['Q'], white_promoted_pawns = np.split(white_pieces['Q'], (1,))\n        white_promoted_pawns = np.apply_along_axis(lambda i: i | (1 << 30), 0, white_promoted_pawns)\n        white_pieces['P'] = np.append(white_promoted_pawns, white_pieces['P'])\n\n    if white_pieces['P'].size < 5:\n        white_pieces['P'] = np.pad(white_pieces['P'], (0, 5 - white_pieces['P'].size), 'constant', constant_values=0)\n\n    # Concatenate the lists into one long list and return it.\n    return ' '.join(\n        list(map(str, list(\n            np.append(\n                np.concatenate(tuple(black_pieces.values())),\n                np.concatenate(tuple(white_pieces.values())))) + [move_number,\n                                                                  player_number[on_move_color],\n                                                                  opponent_locations,\n                                                                  empty_locations,\n                                                                  time_left])))\n\n\nif __name__ == '__main__':\n    board = '''2 W\nkqb.r\nppppp\n..n..\nP....\n.PPPP\nRNBQK'''\n    parsed_board = parse_board(board, 268327)\n    print(parsed_board)\n", "meta": {"hexsha": "a450e22607860a8180fe458af010a618bb4f1ed5", "size": 7270, "ext": "py", "lang": "Python", "max_stars_repo_path": "minichess/parse.py", "max_stars_repo_name": "mikelane/minichess", "max_stars_repo_head_hexsha": "b341581ec7055d3a9396d4a54d623f692e5dec3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-05-17T00:30:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-21T03:07:15.000Z", "max_issues_repo_path": "minichess/parse.py", "max_issues_repo_name": "mikelane/minichess", "max_issues_repo_head_hexsha": "b341581ec7055d3a9396d4a54d623f692e5dec3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "minichess/parse.py", "max_forks_repo_name": "mikelane/minichess", "max_forks_repo_head_hexsha": "b341581ec7055d3a9396d4a54d623f692e5dec3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-05-25T17:08:30.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-25T17:08:30.000Z", "avg_line_length": 37.4742268041, "max_line_length": 117, "alphanum_fraction": 0.6332874828, "include": true, "reason": "import numpy", "num_tokens": 1857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.18108580329834503}}
{"text": "####################################################################################################\n###                                                                                              ###\n###                             Functions for simulating spectra                                 ###\n###                               Author: Manuel Cordova (EPFL)                                  ###\n###                                Last modified: 03.09.2021                                     ###\n###                                                                                              ###\n####################################################################################################\n\n# Import libraries\nimport numpy as np\nimport networkx as nx\n\n# Set criterion for equivalent nodes\nnm = nx.algorithms.isomorphism.categorical_node_match(\"elem\", \"X\")\n\n# Set criterion for equivalent edges\nem = nx.algorithms.isomorphism.categorical_edge_match(\"w\", -1)\n\n\n\ndef cleanup_methyl_protons(labels, Gs, envs, shifts, errs, ws, crysts, inds, atoms, bonds):\n    \"\"\"\n    Gather methyl proton shifts into only one per methyl group\n    \n    Inputs:     - labels        List of labels for each distribution\n                - Gs            Graph of each distribution\n                - envs          Environment of each graph\n                - shifts        Predicted shifts in each distribution\n                - errs          Prediction errors in each distribution\n                - ws            Maximum depth for each distribution\n                - crysts        Crystals in each distribution\n                - inds          Indices of the atoms in each distribution\n                - atoms         List of atoms in the molecule\n                - bonds         Bonded atoms for each atom in the molecule (by index)\n    \n    Outputs:    - new_labels    Cleaned list of labels for each distribution\n                - new_Gs        Cleaned list of graphs\n                - new_shifts    Cleaned list of predicted shifts in each distribution\n                - new_errs      Cleaned list of prediction errors in each distribution\n                - new_ws        Cleaned list of maximum depth for each distribution\n                - new_crysts    Cleaned array of crystals in each distribution\n                - new_inds      Cleaned array of indices of the atoms in each distribution\n    \"\"\"\n    \n    # Initialize new arrays\n    new_labels = []\n    new_Gs = []\n    new_envs = []\n    new_shifts = []\n    new_errs = []\n    new_ws = []\n    new_crysts = []\n    new_inds = []\n    \n    # Array to store already identified methyl groups\n    methyls = []\n    \n    # Loop over all graphs\n    for l, G, env, sh, er, w, cryst, ind in zip(labels, Gs, envs, shifts, errs, ws, crysts, inds):\n        \n        # Get the index of the central node\n        i = G.nodes[0][\"ind\"]\n        # Check that there is only one neighbour (H should be linked to only one atom\n        if len(bonds[i]) == 1:\n            j = bonds[i][0]\n            \n            # Check if there are at least three protons linked to the neighbour\n            nH = [atoms[k] for k in bonds[j]].count(\"H\")\n            \n            if nH >= 3:\n                # If we find a new methyl proton, add it,\n                #   otherwise skip it if it is part of an already known methyl\n                if j not in methyls:\n                    methyls.append(j)\n                    new_labels.append(l)\n                    new_Gs.append(G)\n                    new_envs.append(env)\n                    new_shifts.append(sh)\n                    new_errs.append(er)\n                    new_ws.append(w)\n                    new_crysts.append(cryst)\n                    new_inds.append(ind)\n            \n            # If this is not a methyl proton, add it\n            else:\n                new_labels.append(l)\n                new_Gs.append(G)\n                new_envs.append(env)\n                new_shifts.append(sh)\n                new_errs.append(er)\n                new_ws.append(w)\n                new_crysts.append(cryst)\n                new_inds.append(ind)\n        \n        # If the proton is bonded to more than one atom, add it\n        else:\n            new_labels.append(l)\n            new_Gs.append(G)\n            new_envs.append(env)\n            new_shifts.append(sh)\n            new_errs.append(er)\n            new_ws.append(w)\n            new_crysts.append(cryst)\n            new_inds.append(ind)\n    \n    return new_labels, new_Gs, new_envs, new_shifts, new_errs, new_ws, new_crysts, new_inds\n\n\n\ndef cleanup_methyls(labels, shifts, errs, ws, crysts, inds, hashes, atoms, bonds):\n    \"\"\"\n    Gather methyl 2D shifts\n    \n    Inputs:     - labels        List of labels for each distribution\n                - shifts        Predicted shifts in each distribution\n                - errs          Prediction errors in each distribution\n                - ws            Maximum depth for each distribution\n                - crysts        Crystals in each distribution\n                - inds          Indices of the atoms in each distribution\n                - hashes        List of hashes for each graph\n                - atoms         List of atoms in the molecule\n                - bonds         Bonded atoms for each atom in the molecule (by index)\n    \n    Outputs:    - new_labels    Cleaned list of labels for each distribution\n                - new_Gs        Cleaned list of graphs\n                - new_shifts    Cleaned list of predicted shifts in each distribution\n                - new_errs      Cleaned list of prediction errors in each distribution\n                - new_ws        Cleaned list of maximum depth for each distribution\n                - new_crysts    Cleaned array of crystals in each distribution\n                - new_inds      Cleaned array of indices of the atoms in each distribution\n    \"\"\"\n    \n    # Initialize the updated lists\n    new_labels = []\n    new_shifts = []\n    new_errs = []\n    new_ws = []\n    new_crysts = []\n    new_inds = []\n    new_hashes = []\n    \n    # Array to store already identified methyl groups\n    methyls = []\n    \n    # Get element\n    elem = \"\"\n    for c in labels[0]:\n        if c.isdigit():\n            break\n        elem += c\n    \n    # Loop over all distributions\n    for l, sh, er, w, cryst, ind, h in zip(labels, shifts, errs, ws, crysts, inds, hashes):\n    \n        # Get the index of the central node\n        ind = int(l.split(\"-\")[0].split(elem)[1]) - 1\n        i = [k for k, e in enumerate(atoms) if e == elem][ind]\n    \n        # Check if there are at least three protons linked to the atom\n        nH = [atoms[k] for k in bonds[i]].count(\"H\")\n        \n        if nH >= 3:\n            \n            # If we find a new methyl proton, add it,\n            #   otherwise skip it if it is part of an already known methyl\n            if i not in methyls:\n                methyls.append(i)\n                new_labels.append(l)\n                new_shifts.append(sh)\n                new_errs.append(er)\n                new_ws.append(w)\n                new_crysts.append(cryst)\n                new_inds.append(ind)\n                new_hashes.append(h)\n        \n        # If this is not a methyl, add it\n        else:\n            new_labels.append(l)\n            new_shifts.append(sh)\n            new_errs.append(er)\n            new_ws.append(w)\n            new_crysts.append(cryst)\n            new_inds.append(ind)\n            new_hashes.append(h)\n        \n    return new_labels, new_shifts, new_errs, new_ws, new_crysts, new_inds, new_hashes\n\n\n\ndef cleanup_equivalent(labels, shifts, errs, ws, crysts, inds, hashes):\n    \"\"\"\n    Gather equivalent graphs (identified by their shift distributions)\n    \n    Inputs:     - labels        List of labels of the distributions\n                - shifts        List of predicted shifts in each distribution\n                - errs          List of predicted errors in each distribution\n                - ws            List of weights of the distributions\n                - crysts        List of crystals in each distribution\n                - inds          List of the atoms in each distribution\n                - hashes        List of hashes for each graph\n                \n    Outputs:    - new_labels    Updated list of labels of the distributions\n                - new_shifts    Updated list of predicted shifts in each distribution\n                - new_errs      Updated list of predicted errors in each distribution\n                - new_ws        Updated list of weights of the distributions\n                - new_crysts    Updated list of crystals in each distribution\n                - new_inds      Updated list of the atoms in each distribution\n    \"\"\"\n    \n    # Initialize the updated lists\n    new_labels = []\n    new_shifts = []\n    new_errs = []\n    new_ws = []\n    new_crysts = []\n    new_inds = []\n    new_hashes = []\n    \n    # Loop over all the distributions\n    for l, sh, er, w, cr, ind, h in zip(labels, shifts, errs, ws, crysts, inds, hashes):\n        \n        # If the distribution is already found, modify the label\n        if h in new_hashes:\n            i = new_hashes.index(h)\n            new_labels[i] += \"/{}\".format(l)\n        \n        # Otherwise, append the distribution to the updated list\n        else:\n            new_labels.append(l)\n            new_shifts.append(sh)\n            new_errs.append(er)\n            new_ws.append(w)\n            new_crysts.append(cr)\n            new_inds.append(ind)\n            new_hashes.append(h)\n    \n    return new_labels, new_shifts, new_errs, new_ws, new_crysts, new_inds, new_hashes\n\n\n\ndef get_lims_1D(all_shifts, all_errs, extend=0.1, dx=\"rms\"):\n    \"\"\"\n    Get the limits for a predicted 1D spectrum: obtain furthest peaks ± err to determine range, extend by a factor\n\n    Inputs: - all_shifts    List of shifts in the distributions\n            - all_errs      List of predicted errors in the distributions\n            - extend        How much to extend the range (fraction of the original range, applied to both sides)\n            - dx            How the error is incorporated to the minimum/maximum shift:\n                                \"sel\": use the error of the minimum and maximum peaks\n                                \"max\": use the maximum error\n                                \"mean\": use the mean error\n                                \"rms\": use the rms error\n\n    Output: - lx            Limits in the x-dimension\n    \"\"\"\n\n    # Initialize limits\n    lx = np.ones(2) * np.mean(all_shifts[0])\n\n    # Get minimum and maximum peak of each distribution\n    for shifts, errs in zip(all_shifts, all_errs):\n\n        # Get indices of the minimum and maximum peaks\n        imin = np.argmin(shifts)\n        imax = np.argmax(shifts)\n\n        # Add the corresponding errors to the minimum and maximum peaks\n        if dx == \"sel\":\n            min_x = shifts[imin] - errs[imin]\n            max_x = shifts[imax] + errs[imax]\n        # Add the maximum error to the minimum and maximum peaks\n        elif dx == \"max\":\n            m = np.max(errs)\n            min_x = shifts[imin] - m\n            max_x = shifts[imax] + m\n        # Add the mean error to the minimum and maximum peaks\n        elif dx == \"mean\":\n            m = np.mean(errs)\n            min_x = shifts[imin] - m\n            max_x = shifts[imax] + m\n        # Add the rms error to the minimum and maximum peaks\n        elif dx == \"rms\":\n            m = np.sqrt(np.mean(np.square(errs)))\n            min_x = shifts[imin] - m\n            max_x = shifts[imax] + m\n        else:\n            raise ValueError(\"Unknown dx: {}\".format(dx))\n\n        # Get the limits\n        lx[0] = min(lx[0], min_x)\n        lx[1] = max(lx[1], max_x)\n\n    # Get the range\n    r = lx[1] - lx[0]\n\n    # Extend the limits by a fraction of the range\n    lx[0] -= extend * r\n    lx[1] += extend * r\n\n    return lx\n\n\n\ndef get_lims_2D(all_shifts, all_errs, extend=0.1, dx=\"rms\"):\n    \"\"\"\n    Get the limits for a predicted 1D spectrum: obtain furthest peaks ± err to determine range, extend by a factor\n\n    Inputs:     - all_shifts    List of all shifts in the distributions\n                - all_errs      List of predicted errors in the distributions\n                - extend        How much to extend the range (fraction of the original range, applied to both sides)\n                - dx            How the error is incorporated to the minimum/maximum shift:\n                                    \"sel\": use the error of the minimum and maximum peaks\n                                    \"max\": use the maximum error\n                                    \"mean\": use the mean error\n                                    \"rms\": use the rms error\n\n    Outputs:    - lx            Limits in the x-dimension\n                - ly            Limits in the y-dimension\n    \"\"\"\n\n    # Initialize limits\n    lx = np.ones(2) * np.mean(all_shifts[0][:,0])\n    ly = np.ones(2) * np.mean(all_shifts[0][:,1])\n\n\n    # Get minimum and maximum peak of each distribution in each dimension\n    for shifts, errs in zip(all_shifts, all_errs):\n        imin_x = np.argmin(shifts[:,0])\n        imax_x = np.argmax(shifts[:,0])\n        imin_y = np.argmin(shifts[:,1])\n        imax_y = np.argmax(shifts[:,1])\n\n        # Add the corresponding errors to the minimum and maximum peaks\n        if dx == \"sel\":\n            min_x = shifts[imin_x, 0] - errs[imin_x, 0]\n            max_x = shifts[imax_x, 0] + errs[imax_x, 0]\n            min_y = shifts[imin_y, 1] - errs[imin_y, 1]\n            max_y = shifts[imax_y, 1] + errs[imax_y, 1]\n        # Add the maximum error to the minimum and maximum peaks\n        elif dx == \"max\":\n            mx = np.max(errs[:, 0])\n            my = np.max(errs[:, 1])\n            min_x = shifts[imin_x, 0] - mx\n            max_x = shifts[imax_x, 0] + mx\n            min_y = shifts[imin_y, 1] - my\n            max_y = shifts[imax_y, 1] + my\n        # Add the mean error to the minimum and maximum peaks\n        elif dx == \"mean\":\n            mx = np.mean(errs[:, 0])\n            my = np.mean(errs[:, 1])\n            min_x = shifts[imin_x, 0] - mx\n            max_x = shifts[imax_x, 0] + mx\n            min_y = shifts[imin_y, 1] - my\n            max_y = shifts[imax_y, 1] + my\n        # Add the rms error to the minimum and maximum peaks\n        elif dx == \"rms\":\n            mx = np.sqrt(np.mean(np.square(errs[:, 0])))\n            my = np.sqrt(np.mean(np.square(errs[:, 1])))\n            min_x = shifts[imin_x, 0] - mx\n            max_x = shifts[imax_x, 0] + mx\n            min_y = shifts[imin_y, 1] - my\n            max_y = shifts[imax_y, 1] + my\n        else:\n            raise ValueError(\"Unknown dx: {} (accepted values: 'sel', 'max', 'mean', 'rms')\".format(dx))\n\n        # Get the limits\n        lx[0] = min(lx[0], min_x)\n        lx[1] = max(lx[1], max_x)\n        ly[0] = min(ly[0], min_y)\n        ly[1] = max(ly[1], max_y)\n\n        # Get the ranges\n        rx = lx[1] - lx[0]\n        ry = ly[1] - ly[0]\n\n    # Extend the limits by a fraction of the ranges\n    lx[0] -= extend * rx\n    lx[1] += extend * rx\n    ly[0] -= extend * ry\n    ly[1] += extend * ry\n\n    return np.array([lx, ly])\n\n\n\ndef make_1D_distribution(x, shifts, errs, norm=None, max_shifts=None, seed=None):\n    \"\"\"\n    Generate 1D distribution of chemical shifts from an array of shifts and errors\n\n    Inputs: - x             Points in the x-axis to draw the Gaussians on\n            - shifts        List of shifts in the distribution\n            - errs          List of predicted errors in the distribution\n            - norm          Distribution normalization to apply\n                                None: no normalization\n                                \"max\": top of the distribution set to 1\n            - max_shifts    Maximum number of shifts to consider when constructing the distribution\n            - seed          Seed for the random selection of shifts\n\n    Output: - y         Value of the distribution at each point of x\n    \"\"\"\n\n    # Initialize y array\n    y = np.zeros_like(x)\n\n    # If there are too many shifts, randomly select a subset of length max_shifts\n    if max_shifts is not None and max_shifts < len(shifts):\n        if seed is not None:\n            np.random.seed(seed)\n            \n        inds = np.random.choice(len(shifts), max_shifts, replace=False)\n        \n        # Add the Gaussians\n        for x0, w in zip(shifts[inds], errs[inds]):\n            y += 1. / (w * np.sqrt(2. * np.pi)) * np.exp(np.square(x - x0)/(-2. * np.square(w)))\n\n    # Otherwise, use all shifts\n    else:\n        # Add the Gaussians\n        for x0, w in zip(shifts, errs):\n            y += 1. / (w * np.sqrt(2. * np.pi)) * np.exp(np.square(x - x0)/(-2. * np.square(w)))\n\n    # Return the non-normalized sum\n    if norm is None:\n        return y\n    # Normalize the maximum value to one\n    elif norm == \"max\":\n        return y/np.max(y)\n    else:\n        raise ValueError(\"Unknown normalization: {}\".format(norm))\n\n\n\ndef make_1D_distributions(lims, n_points, all_shifts, all_errs, norm=None, max_shifts=None, seed=None):\n    \"\"\"\n    Generate 1D distributions of chemical shifts from arrays of shifts and errors of each distribution\n    \n    Inputs:     - lims          Limits of the distributions\n                - n_points      Number of points in the distributions\n                - all_shifts    Array of shifts for each distribution\n                - all_errs      Array of predicted error for each distribution\n                - norm          Distribution normalization to apply\n                                    None: no normalization\n                                    \"max\": top of each distribution set to 1\n                - max_shifts    Maximum number of shifts to consider when constructing the distribution\n                - seed          Seed for the random selection of shifts\n    \n    Outputs:    - x             Array of shielding values to plot the distributions against\n                - ys            List of distributions\n    \"\"\"\n    \n    # Construct the array of shielding values\n    x = np.linspace(lims[0], lims[1], n_points)\n    \n    # Generate the distributions\n    ys = []\n    for i, (sh, er) in enumerate(zip(all_shifts, all_errs)):\n        print(\"  Constructing distribution {}/{}...\".format(i+1, len(all_shifts)))\n        ys.append(make_1D_distribution(x, sh, er, norm=norm, max_shifts=max_shifts, seed=seed))\n        print(\"  Distribution constructed!\\n\")\n\n    return x, ys\n    \n    \n    \ndef make_2D_distribution(x, y, shifts, errs, norm=None, max_shifts=None, seed=None):\n    \"\"\"\n    \n    Inputs: - x             Array of x-values to draw the Gaussians on\n            - y             Array of y-values to draw the Gaussians on\n            - shifts        List of shifts in the distribution\n            - errs          List of predicted errors in the distribution\n            - norm          Distribution normalization to apply\n                                None: no normalization\n                                \"max\": top of the distribution set to 1\n            - max_shifts    Maximum number of shifts to consider when constructing the distribution\n            - seed          Seed for the random selection of shifts\n    \n    Output: - Z             Value of the distribution at each point of the X-Y grid\n    \"\"\"\n    \n    # Initialize Z array\n    Z = np.zeros((y.shape[0], x.shape[0]))\n    \n    # If there are too many shifts, randomly select a subset of length max_shifts\n    if max_shifts is  not None and max_shifts < len(shifts):\n        if seed is not None:\n            np.random.seed(seed)\n        \n        inds = np.random.choice(len(shifts), max_shifts, replace=False)\n        \n        # Add the 2D Gaussians\n        for [x0, y0], [wx, wy] in zip(shifts[inds], errs[inds]):\n            gx = np.exp(np.square(x - x0) / (-2. * np.square(wx))) / wx\n            gy = np.exp(np.square(y - y0) / (-2. * np.square(wy))) / wy\n            Z += np.outer(gy, gx) / (2. * np.pi)\n    \n    # Otherwise, use all shifts\n    else:\n        # Add the 2D Gaussians\n        for [x0, y0], [wx, wy] in zip(shifts, errs):\n            gx = np.exp(np.square(x - x0) / (-2. * np.square(wx))) / wx\n            gy = np.exp(np.square(y - y0) / (-2. * np.square(wy))) / wy\n            Z += np.outer(gy, gx) / (2. * np.pi)\n    \n    if norm is None:\n        return Z\n    elif norm == \"max\":\n        return Z / np.max(Z)\n    else:\n        raise ValueError(\"Unknown normalization: {}\".format(norm))\n\n\n\ndef make_2D_distributions(lims, n_points, all_shifts, all_errs, norm=None, max_shifts=None, seed=None):\n    \"\"\"\n    Generate 2D distributions of chemical shifts from arrays of shifts and errors of each distribution\n    \n    Inputs:     - lims          Limits of the distributions\n                - n_points      Number of points in the distributions\n                - all_shifts    Array of shifts for each distribution\n                - all_errs      Array of predicted error for each distribution\n                - norm          Distribution normalization to apply\n                                    None: no normalization\n                                    \"max\": top of each distribution set to 1\n                - max_shifts    Maximum number of shifts to consider when constructing the distribution\n                - seed          Seed for the random selection of shifts\n    \n    Outputs:    - X             Grid of shielding values (first dimension) to plot the distributions against\n                - Y             Grid of shielding values (second dimension) to plot the distributions against\n                - Zs            List of distributions\n    \"\"\"\n    \n    # Generate grid of X and Y values\n    x = np.linspace(lims[0,0], lims[0,1], n_points)\n    y = np.linspace(lims[1,0], lims[1,1], n_points)\n    X, Y = np.meshgrid(x, y)\n    \n    # Generate the distributions\n    Zs = []\n    for i, (sh, er) in enumerate(zip(all_shifts, all_errs)):\n        print(\"  Constructing distribution {}/{}...\".format(i+1, len(all_shifts)))\n        Zs.append(make_2D_distribution(x, y, sh, er, norm=norm, max_shifts=max_shifts, seed=seed))\n        print(\"  Distribution constructed!\\n\")\n    \n    return X, Y, Zs\n\n\n\ndef get_distribution_max_1D(x, ys):\n    \"\"\"\n    Obtain the maximum of each distribution\n    \n    Inputs: - x         Array of shielding values to plot the distributions against\n            - ys        List of distributions\n    \n    Output: - centers   Maximum of each distribution\n    \"\"\"\n    \n    # Initialize array of centers\n    centers = []\n    \n    # Get the center of each distribution (withing the set of shielding values considered)\n    for i, y in enumerate(ys):\n        inds = np.where(y == np.max(y))[0]\n        \n        if 0 in inds or (len(y) - 1) in inds:\n            msg = \"    WARNING: the maximum of distribution {} is at the edge of the\"\n            msg += \" chemical shielding range! Consider expanding the range!\".format(i+1)\n            print(msg)\n        \n        centers.append(x[inds[0]])\n    \n    return np.array(centers)\n\n\n\ndef get_distribution_max_2D(X, Y, Zs):\n    \"\"\"\n    Obtain the maximum of each distribution\n\n    Inputs: - X         Grid of shielding values of the first element to plot the distribution against\n            - Y         Grid of shielding values of the second element to plot the distribution against\n            - Zs        List of distributions\n\n    Output: - centers   Maximum of the distributions\n    \"\"\"\n\n    #Initialize array of centers\n    centers = []\n\n    # Get the center of each distribution (within the set X and Y values)\n    for i, Z in enumerate(Zs):\n    \n        inds_x, inds_y = np.where(Z == np.max(Z))\n        \n        if 0 in inds_x or 0 in inds_y or (Z.shape[0] - 1) in inds_x or (Z.shape[1] - 1) in inds_y:\n            msg = \"    WARNING: the maximum of distribution {} is at the edge of the\"\n            msg += \" chemical shielding range! Consider expanding the range!\".format(i+1)\n            print(msg)\n        \n        centers.append([X[inds_x[0], inds_y[0]], Y[inds_x[0], inds_y[0]]])\n\n    return np.array(centers)\n\n\n\ndef compute_scores_1D(exp, shifts, errs, conv, max_shifts=None, seed=None, acc=None, N=101):\n    \"\"\"\n    Compute the scores for every possible assignment. If the variable \"acc\" is set to None, the probability density\n    at the experimental shift yields the score. If \"acc\" is set to a value, the probability between\n    the experimental shift e - acc and e + acc (computed as the numerical integral) is used as the score.\n    \n    Inputs: - exp           List of experimental shifts\n            - shifts        List of shifts in each distribution\n            - errs          List of errors in each distribution\n            - conv          Conversion factors [slope, offset] from shielding to shift\n            - max_shifts    Maximum number of shifts to select to construct the distribution\n            - seed          Seed for random selection of shifts\n            - acc           Accuracy of the shifts\n            - N             Number of points in each shift if an accuracy is set\n    \n    Output: - scores    Matrix of scores for all possible assignments\n    \"\"\"\n    \n    # Initialize array of scores\n    scores = np.zeros((len(shifts), len(exp)))\n    \n    # If no accuracy is set, take the shifts as elements of the array x\n    if acc is None:\n        x = np.array(exp)\n    # Otherwise, append the array of N element between e - acc and e + acc to x, for each shift e\n    else:\n        x = []\n        for e in exp:\n            x.extend(list(np.linspace(e-acc, e+acc, N)))\n        x = np.array(x)\n    \n    # Loop over all distributions\n    for i, (sh, er) in enumerate(zip(shifts, errs)):\n        print(\"  Evaluating distribution {}/{}...\".format(i+1, len(shifts)))\n        # Compute the values of the distribution on the array x\n        y = make_1D_distribution(x, sh*conv[0]+conv[1], er, max_shifts=max_shifts, seed=seed)\n        \n        # If an accuracy is set, get the integral\n        if acc is not None:\n            y2 = []\n            for j in range(len(exp)):\n                y2.append(np.trapz(y[j*N:(j+1)*N], x=x[j*N:(j+1)*N]))\n            y = np.array(y2)\n        \n        # Append the scores of this distribution\n        if np.sum(y) < 1e-6:\n            print(\"    WARNING: Distribution {} does not seem to match any experimental shift\".format(i+1))\n        scores[i] = y / np.sum(y)\n        print(\"  Done!\\n\")\n    \n    return scores\n\n\n\ndef compute_scores_2D(exp, shifts, errs, conv_x, conv_y, max_shifts=None, seed=None, acc_x=None, acc_y=None, N=101):\n    \"\"\"\n    Compute the scores for every possible assignment. If the variable \"acc_x/acc_y\" is set to None, the probability density\n    at the experimental shift yields the score. If \"acc_x/acc_y\" are set to numerical values, the probability between\n    the experimental shift e - acc and e + acc in each dimension (computed as the numerical integral) is used as the score.\n\n    Inputs: - exp           List of experimental shifts\n            - shifts        List of shifts in each distribution\n            - errs          List of errors in each distribution\n            - conv_x        Conversion factors [slope, offset] from shielding to shift in the x-axis\n            - conv_y        Conversion factors [slope, offset] from shielding to shift in the y-axis\n            - max_shifts    Maximum number of shifts to select to construct the distribution\n            - seed          Seed for random selection of shifts\n            - acc_x         Accuracy of the shifts in the x dimension\n            - acc_y         Accuracy of the shifts in the y dimension\n            - N             Number of points in each shift (along each axis) if an accuracy is set\n\n    Output: - scores        Matrix of scores for all possible assignments\n    \"\"\"\n\n    # Initialize matrix of scores\n    scores = np.zeros((len(shifts), len(exp)))\n\n    # If no accuracy is set, set x- and y-axes as the experimental shifts\n    if acc_x is None and acc_y is None:\n        x = np.array(exp)[:,0]\n        y = np.array(exp)[:,1]\n            \n    # Accuracy set only in the x-axis\n    elif acc_y is None:\n        x = []\n        for e in exp:\n            x.extend(list(np.linspace(e[0]-acc_x, e[0]+acc_x, N)))\n        x = np.array(x)\n        y = np.array(exp)[:,1]\n    \n    # Accuracy set only in the y-axis\n    elif acc_x is None:\n        y = []\n        for e in exp:\n            y.extend(list(np.linspace(e[1]-acc_y, e[1]+acc_y, N)))\n        y = np.array(y)\n        x = np.array(exp)[:,0]\n        \n    # Accuracy set in both axes\n    else:\n        x = []\n        y = []\n        for e in exp:\n            x.extend(list(np.linspace(e[0]-acc_x, e[0]+acc_x, N)))\n            y.extend(list(np.linspace(e[1]-acc_y, e[1]+acc_y, N)))\n        x = np.array(x)\n        y = np.array(y)\n\n    # Loop over all distributions\n    for i, (s, er) in enumerate(zip(shifts, errs)):\n    \n        print(\"  Evaluating distribution {}/{}...\".format(i+1, len(shifts)))\n        \n        conv_shifts = np.zeros_like(s)\n        conv_shifts[:,0] = s[:,0]*conv_x[0]+conv_x[1]\n        conv_shifts[:,1] = s[:,1]*conv_y[0]+conv_y[1]\n    \n        # If no accuracy is set, Compute the values of the distribution on the grid of experimental shifts\n        if acc_x is None and acc_y is None:\n            Z = make_2D_distribution(x, y, conv_shifts, er, max_shifts=max_shifts, seed=seed)\n            these_scores = np.diag(Z)\n        \n        # If accuracy is set only along the x-axis, integrate over the range set\n        elif acc_y is None:\n            these_scores = np.zeros(len(exp))\n            for j in range(len(exp)):\n                Z = make_2D_distribution(x[j*N:(j+1)*N], y, conv_shifts, er, max_shifts=max_shifts, seed=seed)\n                these_scores[j] = np.trapz(Z[j], x=x[j*N:(j+1)*N])\n        \n        # If accuracy is set only along the y-axis, integrate over the range set\n        elif acc_x is None:\n            these_scores = np.zeros(len(exp))\n            for j in range(len(exp)):\n                Z = make_2D_distribution(x, y[j*N:(j+1)*N], conv_shifts, er, max_shifts=max_shifts, seed=seed)\n                these_scores[j] = np.trapz(Z[:, j], x=y[j*N:(j+1)*N])\n        \n        # If accuracy is set along both axes, integrate over the rectangle set\n        else:\n            these_scores = np.zeros(len(exp))\n            for j in range(len(exp)):\n                Z = make_2D_distribution(x[j*N:(j+1)*N], y[j*N:(j+1)*N], conv_shifts, er, max_shifts=max_shifts, seed=seed)\n                these_scores[j] = np.trapz(np.trapz(Z, x=x[j*N:(j+1)*N]), x=y[j*N:(j+1)*N])\n        \n        if np.sum(these_scores) < 1e-6:\n            print(\"    WARNING: Distribution {} does not seem to match any experimental shift\".format(i+1))\n        scores[i] = these_scores / np.sum(these_scores)\n        print(\"  Done!\\n\")\n    \n    return scores\n", "meta": {"hexsha": "0ae6ca3ee2f6817bebae3853ec10b76f2c61b68a", "size": 30820, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/sim.py", "max_stars_repo_name": "manucordova/ProbAsn", "max_stars_repo_head_hexsha": "c6c4ee3223fa8283b8f9ec88ed8d2257d7fe0182", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-11-27T11:37:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T11:17:28.000Z", "max_issues_repo_path": "src/sim.py", "max_issues_repo_name": "manucordova/ProbAsn", "max_issues_repo_head_hexsha": "c6c4ee3223fa8283b8f9ec88ed8d2257d7fe0182", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sim.py", "max_forks_repo_name": "manucordova/ProbAsn", "max_forks_repo_head_hexsha": "c6c4ee3223fa8283b8f9ec88ed8d2257d7fe0182", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.7671957672, "max_line_length": 123, "alphanum_fraction": 0.5489292667, "include": true, "reason": "import numpy,import networkx", "num_tokens": 7236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.18103578242182383}}
{"text": "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom __future__ import annotations\n\nfrom collections import defaultdict\nfrom functools import partial\nfrom typing import (\n    TYPE_CHECKING,\n    Callable,\n    Dict,\n    List,\n    MutableMapping,\n    Optional,\n    Tuple,\n    Union,\n)\n\nimport numpy as np\nimport torch\nfrom ax.core.base_trial import TrialStatus\nfrom ax.core.batch_trial import BatchTrial\nfrom ax.core.experiment import Experiment\nfrom ax.core.objective import MultiObjective, Objective, ScalarizedObjective\nfrom ax.core.observation import Observation, ObservationData, ObservationFeatures\nfrom ax.core.optimization_config import MultiObjectiveOptimizationConfig, TRefPoint\nfrom ax.core.outcome_constraint import (\n    ComparisonOp,\n    OutcomeConstraint,\n    ScalarizedOutcomeConstraint,\n)\nfrom ax.core.parameter import ChoiceParameter, ParameterType, RangeParameter\nfrom ax.core.parameter_constraint import ParameterConstraint\nfrom ax.core.search_space import SearchSpace, SearchSpaceDigest\nfrom ax.core.trial import Trial\nfrom ax.core.types import TBounds, TCandidateMetadata\nfrom ax.modelbridge.transforms.base import Transform\nfrom ax.models.torch.frontier_utils import (\n    get_weighted_mc_objective_and_objective_thresholds,\n    get_default_frontier_evaluator,\n)\nfrom ax.utils.common.logger import get_logger\nfrom ax.utils.common.typeutils import (\n    checked_cast,\n    checked_cast_optional,\n    not_none,\n    checked_cast_to_tuple,\n)\nfrom botorch.utils.multi_objective.hypervolume import Hypervolume\nfrom torch import Tensor\n\nlogger = get_logger(__name__)\n\n\nif TYPE_CHECKING:\n    # import as module to make sphinx-autodoc-typehints happy\n    from ax import modelbridge as modelbridge_module  # noqa F401  # pragma: no cover\n\n\ndef extract_parameter_constraints(\n    parameter_constraints: List[ParameterConstraint], param_names: List[str]\n) -> Optional[TBounds]:\n    \"\"\"Extract parameter constraints.\"\"\"\n    if len(parameter_constraints) > 0:\n        A = np.zeros((len(parameter_constraints), len(param_names)))\n        b = np.zeros((len(parameter_constraints), 1))\n        for i, c in enumerate(parameter_constraints):\n            b[i, 0] = c.bound\n            for name, val in c.constraint_dict.items():\n                A[i, param_names.index(name)] = val\n        linear_constraints: TBounds = (A, b)\n    else:\n        linear_constraints = None\n    return linear_constraints\n\n\ndef extract_search_space_digest(\n    search_space: SearchSpace, param_names: List[str]\n) -> SearchSpaceDigest:\n    \"\"\"Extract basic parameter prpoerties from a search space.\"\"\"\n    bounds: List[Tuple[Union[int, float], Union[int, float]]] = []\n    ordinal_features: List[int] = []\n    categorical_features: List[int] = []\n    discrete_choices: Dict[int, List[Union[int, float]]] = {}\n    task_features: List[int] = []\n    fidelity_features: List[int] = []\n    target_fidelities: Dict[int, Union[int, float]] = {}\n\n    for i, p_name in enumerate(param_names):\n        p = search_space.parameters[p_name]\n        if isinstance(p, ChoiceParameter):\n            if p.is_task:\n                task_features.append(i)\n            elif p.is_ordered:\n                ordinal_features.append(i)\n            else:\n                categorical_features.append(i)\n            # at this point we can assume that values are numeric due to transforms\n            discrete_choices[i] = p.values  # pyre-ignore [6]\n            bounds.append((min(p.values), max(p.values)))  # pyre-ignore [6]\n        elif isinstance(p, RangeParameter):\n            if p.log_scale:\n                raise ValueError(f\"{p} is log scale\")\n            if p.parameter_type == ParameterType.INT:\n                ordinal_features.append(i)\n                d_choices = list(range(int(p.lower), int(p.upper) + 1))\n                discrete_choices[i] = d_choices  # pyre-ignore [6]\n            bounds.append((p.lower, p.upper))\n        else:\n            raise ValueError(f\"Unknown parameter type {type(p)}\")\n        if p.is_fidelity:\n            if not isinstance(not_none(p.target_value), (int, float)):\n                raise NotImplementedError(\"Only numerical target values are supported.\")\n            target_fidelities[i] = checked_cast_to_tuple((int, float), p.target_value)\n            fidelity_features.append(i)\n\n    return SearchSpaceDigest(\n        feature_names=param_names,\n        bounds=bounds,\n        ordinal_features=ordinal_features,\n        categorical_features=categorical_features,\n        discrete_choices=discrete_choices,\n        task_features=task_features,\n        fidelity_features=fidelity_features,\n        target_fidelities=target_fidelities,\n    )\n\n\ndef extract_objective_thresholds(\n    objective_thresholds: TRefPoint,\n    objective: Objective,\n    outcomes: List[str],\n) -> Optional[np.ndarray]:\n    \"\"\"Extracts objective thresholds' values, in the order of `outcomes`.\n\n    Will return None if no objective thresholds, otherwise the extracted tensor\n    will be the same length as `outcomes`.\n\n    If one objective threshold is specified, they must be specified for every\n    metric in the objective.\n\n    Outcomes that are not part of an objective will be given a threshold of 0\n    in this tensor, under the assumption that its value will not be used. Note\n    that setting it to 0 for an outcome that is part of the objective would be\n    incorrect, hence we validate that all objective metrics are represented.\n\n    Args:\n        objective_thresholds: Objective thresholds to extract values from.\n        objective: The corresponding Objective, for validation purposes.\n        outcomes: n-length list of names of metrics.\n\n    Returns:\n        (n,) array of thresholds\n    \"\"\"\n    if len(objective_thresholds) == 0:\n        return None\n\n    objective_threshold_dict = {}\n    for ot in objective_thresholds:\n        if ot.relative:\n            raise ValueError(\n                f\"Objective {ot.metric.name} has a relative threshold that is not \"\n                f\"supported here.\"\n            )\n        objective_threshold_dict[ot.metric.name] = ot.bound\n\n    if len(objective_threshold_dict) != len(objective.metrics):\n        raise ValueError(\n            \"Objective thresholds do not match number of objective metrics.\"\n        )\n    # Initialize these to be nan to make sure that objective thresholds for\n    # non-objective metrics are never used\n    obj_t = np.full(len(outcomes), float(\"nan\"))\n    for metric in objective.metrics:\n        if metric.name not in objective_threshold_dict:\n            raise ValueError(\n                f\"Objective threshold not specified for {metric.name}. Thresholds must \"\n                f\"be specified for all objective metrics or for none.\"\n            )\n        obj_t[outcomes.index(metric.name)] = objective_threshold_dict[metric.name]\n    return obj_t\n\n\ndef extract_objective_weights(objective: Objective, outcomes: List[str]) -> np.ndarray:\n    \"\"\"Extract a weights for objectives.\n\n    Weights are for a maximization problem.\n\n    Give an objective weight to each modeled outcome. Outcomes that are modeled\n    but not part of the objective get weight 0.\n\n    In the single metric case, the objective is given either +/- 1, depending\n    on the minimize flag.\n\n    In the multiple metric case, each objective is given the input weight,\n    multiplied by the minimize flag.\n\n    Args:\n        objective: Objective to extract weights from.\n        outcomes: n-length list of names of metrics.\n\n    Returns:\n        n-length list of weights.\n\n    \"\"\"\n    objective_weights = np.zeros(len(outcomes))\n    if isinstance(objective, ScalarizedObjective):\n        s = -1.0 if objective.minimize else 1.0\n        for obj_metric, obj_weight in objective.metric_weights:\n            objective_weights[outcomes.index(obj_metric.name)] = obj_weight * s\n    elif isinstance(objective, MultiObjective):\n        for obj, obj_weight in objective.objective_weights:\n            s = -1.0 if obj.minimize else 1.0\n            objective_weights[outcomes.index(obj.metric.name)] = obj_weight * s\n    else:\n        s = -1.0 if objective.minimize else 1.0\n        objective_weights[outcomes.index(objective.metric.name)] = s\n    return objective_weights\n\n\ndef extract_outcome_constraints(\n    outcome_constraints: List[OutcomeConstraint], outcomes: List[str]\n) -> TBounds:\n    # Extract outcome constraints\n    if len(outcome_constraints) > 0:\n        A = np.zeros((len(outcome_constraints), len(outcomes)))\n        b = np.zeros((len(outcome_constraints), 1))\n        for i, c in enumerate(outcome_constraints):\n            s = 1 if c.op == ComparisonOp.LEQ else -1\n            if isinstance(c, ScalarizedOutcomeConstraint):\n                for c_metric, c_weight in c.metric_weights:\n                    j = outcomes.index(c_metric.name)\n                    A[i, j] = s * c_weight\n            else:\n                j = outcomes.index(c.metric.name)\n                A[i, j] = s\n            b[i, 0] = s * c.bound\n        outcome_constraint_bounds: TBounds = (A, b)\n    else:\n        outcome_constraint_bounds = None\n    return outcome_constraint_bounds\n\n\ndef validate_and_apply_final_transform(\n    objective_weights: np.ndarray,\n    outcome_constraints: Optional[Tuple[np.ndarray, np.ndarray]],\n    linear_constraints: Optional[Tuple[np.ndarray, np.ndarray]],\n    pending_observations: Optional[List[np.ndarray]],\n    objective_thresholds: Optional[np.ndarray] = None,\n    final_transform: Callable[[np.ndarray], Tensor] = torch.tensor,\n) -> Tuple[\n    Tensor,\n    Optional[Tuple[Tensor, Tensor]],\n    Optional[Tuple[Tensor, Tensor]],\n    Optional[List[Tensor]],\n    Optional[Tensor],\n]:\n    # TODO: use some container down the road (similar to\n    # SearchSpaceDigest) to limit the return arguments\n    # pyre-fixme[35]: Target cannot be annotated.\n    objective_weights: Tensor = final_transform(objective_weights)\n    if outcome_constraints is not None:  # pragma: no cover\n        # pyre-fixme[35]: Target cannot be annotated.\n        outcome_constraints: Tuple[Tensor, Tensor] = (\n            final_transform(outcome_constraints[0]),\n            final_transform(outcome_constraints[1]),\n        )\n    if linear_constraints is not None:  # pragma: no cover\n        # pyre-fixme[35]: Target cannot be annotated.\n        linear_constraints: Tuple[Tensor, Tensor] = (\n            final_transform(linear_constraints[0]),\n            final_transform(linear_constraints[1]),\n        )\n    if pending_observations is not None:  # pragma: no cover\n        # pyre-fixme[35]: Target cannot be annotated.\n        pending_observations: List[Tensor] = [\n            final_transform(pending_obs) for pending_obs in pending_observations\n        ]\n    if objective_thresholds is not None:\n        # pyre-fixme[35]: Target cannot be annotated.\n        objective_thresholds: Tensor = final_transform(objective_thresholds)\n    return (\n        objective_weights,\n        outcome_constraints,\n        linear_constraints,\n        pending_observations,\n        objective_thresholds,\n    )\n\n\ndef get_fixed_features(\n    fixed_features: ObservationFeatures, param_names: List[str]\n) -> Optional[Dict[int, float]]:\n    \"\"\"Reformat a set of fixed_features.\"\"\"\n    fixed_features_dict = {}\n    for p_name, val in fixed_features.parameters.items():\n        # These all need to be floats at this point.\n        # pyre-ignore[6]: All float here.\n        val_ = float(val)\n        fixed_features_dict[param_names.index(p_name)] = val_\n    fixed_features_dict = fixed_features_dict if len(fixed_features_dict) > 0 else None\n    return fixed_features_dict\n\n\ndef pending_observations_as_array(\n    pending_observations: Dict[str, List[ObservationFeatures]],\n    outcome_names: List[str],\n    param_names: List[str],\n) -> Optional[List[np.ndarray]]:\n    \"\"\"Re-format pending observations.\n\n    Args:\n        pending_observations: List of raw numpy pending observations.\n        outcome_names: List of outcome names.\n        param_names: List fitted param names.\n\n    Returns:\n        Filtered pending observations data, by outcome and param names.\n    \"\"\"\n    if len(pending_observations) == 0:\n        pending_array: Optional[List[np.ndarray]] = None\n    else:\n        pending_array = [np.array([]) for _ in outcome_names]\n        for metric_name, po_list in pending_observations.items():\n            # It is possible that some metrics attached to the experiment should\n            # not be included in pending features for a given model. For example,\n            # if a model is fit to the initial data that is missing some of the\n            # metrics on the experiment or if a model just should not be fit for\n            # some of the metrics attached to the experiment, so metrics that\n            # appear in pending_observations (drawn from an experiment) but not\n            # in outcome_names (metrics, expected for the model) are filtered out.ß\n            if metric_name not in outcome_names:\n                continue\n            pending_array[outcome_names.index(metric_name)] = np.array(\n                [[po.parameters[p] for p in param_names] for po in po_list]\n            )\n    return pending_array\n\n\ndef parse_observation_features(\n    X: np.ndarray,\n    param_names: List[str],\n    candidate_metadata: Optional[List[TCandidateMetadata]] = None,\n) -> List[ObservationFeatures]:\n    \"\"\"Re-format raw model-generated candidates into ObservationFeatures.\n\n    Args:\n        param_names: List of param names.\n        X: Raw np.ndarray of candidate values.\n        candidate_metadata: Model's metadata for candidates it produced.\n\n    Returns:\n        List of candidates, represented as ObservationFeatures.\n    \"\"\"\n    if candidate_metadata and len(candidate_metadata) != len(X):\n        raise ValueError(  # pragma: no cover\n            \"Observations metadata list provided is not of \"\n            \"the same size as the number of candidates.\"\n        )\n    observation_features = []\n    for i, x in enumerate(X):\n        observation_features.append(\n            ObservationFeatures(\n                parameters=dict(zip(param_names, x)),\n                metadata=candidate_metadata[i] if candidate_metadata else None,\n            )\n        )\n    return observation_features\n\n\ndef transform_callback(\n    param_names: List[str], transforms: MutableMapping[str, Transform]\n) -> Callable[[np.ndarray], np.ndarray]:\n    \"\"\"A closure for performing the `round trip` transformations.\n\n    The function round points by de-transforming points back into\n    the original space (done by applying transforms in reverse), and then\n    re-transforming them.\n    This function is specifically for points which are formatted as numpy\n    arrays. This function is passed to _model_gen.\n\n    Args:\n        param_names: Names of parameters to transform.\n        transforms: Ordered set of transforms which were applied to the points.\n\n    Returns:\n        a function with for performing the roundtrip transform.\n    \"\"\"\n\n    def _roundtrip_transform(x: np.ndarray) -> np.ndarray:\n        \"\"\"Inner function for performing aforementioned functionality.\n\n        Args:\n            x: points in the transformed space (e.g. all transforms have been applied\n                to them)\n\n        Returns:\n            points in the transformed space, but rounded via the original space.\n        \"\"\"\n        # apply reverse terminal transform to turn array to ObservationFeatures\n        observation_features = [\n            ObservationFeatures(\n                parameters={p: float(x[i]) for i, p in enumerate(param_names)}\n            )\n        ]\n        # reverse loop through the transforms and do untransform\n        for t in reversed(transforms.values()):\n            observation_features = t.untransform_observation_features(\n                observation_features\n            )\n        # forward loop through the transforms and do transform\n        for t in transforms.values():\n            observation_features = t.transform_observation_features(\n                observation_features\n            )\n        # parameters are guaranteed to be float compatible here, but pyre doesn't know\n        new_x: List[float] = [\n            # pyre-fixme[6]: Expected `Union[_SupportsIndex, bytearray, bytes, str,\n            #  typing.SupportsFloat]` for 1st param but got `Union[None, bool, float,\n            #  int, str]`.\n            float(observation_features[0].parameters[p])\n            for p in param_names\n        ]\n        # turn it back into an array\n        return np.array(new_x)\n\n    return _roundtrip_transform\n\n\ndef get_pending_observation_features(\n    experiment: Experiment, include_failed_as_pending: bool = False\n) -> Optional[Dict[str, List[ObservationFeatures]]]:\n    \"\"\"Computes a list of pending observation features (corresponding to arms that\n    have been generated and deployed in the course of the experiment, but have not\n    been completed with data or to arms that have been abandoned or belong to\n    abandoned trials).\n\n    NOTE: Pending observation features are passed to the model to\n    instruct it to not generate the same points again.\n\n    Args:\n        experiment: Experiment, pending features on which we seek to compute.\n        include_failed_as_pending: Whether to include failed trials as pending\n            (for example, to avoid the model suggesting them again).\n\n    Returns:\n        An optional mapping from metric names to a list of observation features,\n        pending for that metric (i.e. do not have evaluation data for that metric).\n        If there are no pending features for any of the metrics, return is None.\n    \"\"\"\n    pending_features = {}\n    # Note that this assumes that if a metric appears in fetched data, the trial is\n    # not pending for the metric. Where only the most recent data matters, this will\n    # work, but may need to add logic to check previously added data objects, too.\n    for trial_index, trial in experiment.trials.items():\n        dat = trial.lookup_data()\n        for metric_name in experiment.metrics:\n            if metric_name not in pending_features:\n                pending_features[metric_name] = []\n            include_since_failed = include_failed_as_pending and trial.status.is_failed\n            if isinstance(trial, BatchTrial):\n                if trial.status.is_abandoned or (\n                    (trial.status.is_deployed or include_since_failed)\n                    and metric_name not in dat.df.metric_name.values\n                    and trial.arms is not None\n                ):\n                    for arm in trial.arms:\n                        not_none(pending_features.get(metric_name)).append(\n                            ObservationFeatures.from_arm(\n                                arm=arm, trial_index=np.int64(trial_index)\n                            )\n                        )\n                abandoned_arms = trial.abandoned_arms\n                for abandoned_arm in abandoned_arms:\n                    not_none(pending_features.get(metric_name)).append(\n                        ObservationFeatures.from_arm(\n                            arm=abandoned_arm, trial_index=np.int64(trial_index)\n                        )\n                    )\n\n            if isinstance(trial, Trial):\n                if trial.status.is_abandoned or (\n                    (trial.status.is_deployed or include_since_failed)\n                    and metric_name not in dat.df.metric_name.values\n                    and trial.arm is not None\n                ):\n                    not_none(pending_features.get(metric_name)).append(\n                        ObservationFeatures.from_arm(\n                            arm=not_none(trial.arm), trial_index=np.int64(trial_index)\n                        )\n                    )\n    return pending_features if any(x for x in pending_features.values()) else None\n\n\ndef get_pending_observation_features_based_on_trial_status(\n    experiment: Experiment,\n) -> Optional[Dict[str, List[ObservationFeatures]]]:\n    \"\"\"A faster analogue of ``get_pending_observation_features`` that makes\n    assumptions about trials in experiment in order to speed up extraction\n    of pending points.\n\n    Assumptions:\n\n    * All arms in all trials in ``STAGED,`` ``RUNNING`` and ``ABANDONED`` statuses\n      are to be considered pending for all outcomes.\n    * All arms in all trials in other statuses are to be considered not pending for\n      all outcomes.\n\n    This entails:\n\n    * No actual data-fetching for trials to determine whether arms in them are pending\n      for specific outcomes.\n    * Even if data is present for some outcomes in ``RUNNING`` trials, their arms will\n      still be considered pending for those outcomes.\n\n    NOTE: This function should not be used to extract pending features in field\n    experiments, where arms in running trials should not be considered pending if\n    there is data for those arms.\n\n    Args:\n        experiment: Experiment, pending features on which we seek to compute.\n\n    Returns:\n        An optional mapping from metric names to a list of observation features,\n        pending for that metric (i.e. do not have evaluation data for that metric).\n        If there are no pending features for any of the metrics, return is None.\n    \"\"\"\n    pending_features = defaultdict(list)\n    for status in [TrialStatus.STAGED, TrialStatus.RUNNING, TrialStatus.ABANDONED]:\n        for trial in experiment.trials_by_status[status]:\n            for metric_name in experiment.metrics:\n                pending_features[metric_name].extend(\n                    ObservationFeatures.from_arm(\n                        arm=arm, trial_index=np.int64(trial.index)\n                    )\n                    for arm in trial.arms\n                )\n\n    return dict(pending_features) if any(x for x in pending_features.values()) else None\n\n\ndef clamp_observation_features(\n    observation_features: List[ObservationFeatures], search_space: SearchSpace\n) -> List[ObservationFeatures]:\n    range_parameters = [\n        p for p in search_space.parameters.values() if isinstance(p, RangeParameter)\n    ]\n    for obsf in observation_features:\n        for p in range_parameters:\n            if p.name not in obsf.parameters:\n                continue\n            if p.parameter_type == ParameterType.FLOAT:\n                val = checked_cast(float, obsf.parameters[p.name])\n            else:\n                val = checked_cast(int, obsf.parameters[p.name])\n            if val < p.lower:\n                logger.info(\n                    f\"Untransformed parameter {val} \"\n                    f\"less than lower bound {p.lower}, clamping\"\n                )\n                obsf.parameters[p.name] = p.lower\n            elif val > p.upper:\n                logger.info(\n                    f\"Untransformed parameter {val} \"\n                    f\"greater than upper bound {p.upper}, clamping\"\n                )\n                obsf.parameters[p.name] = p.upper\n    return observation_features\n\n\ndef get_pareto_frontier_and_transformed_configs(\n    modelbridge: modelbridge_module.array.ArrayModelBridge,\n    observation_features: List[ObservationFeatures],\n    observation_data: Optional[List[ObservationData]] = None,\n    objective_thresholds: Optional[TRefPoint] = None,\n    optimization_config: Optional[MultiObjectiveOptimizationConfig] = None,\n    arm_names: Optional[List[Optional[str]]] = None,\n    use_model_predictions: bool = True,\n) -> Tuple[List[Observation], Tensor, Tensor, Optional[Tensor]]:\n    \"\"\"Helper that applies transforms and calls frontier_evaluator.\n\n    Returns transformed configs in addition to the Pareto observations.\n\n    Args:\n        modelbridge: Modelbridge used to predict metrics outcomes.\n        observation_features: observation features to predict, if provided and\n            use_model_predictions is True.\n        observation_data: data for computing the Pareto front, unless features\n            are provided and model_predictions is True.\n        objective_thresholds: metric values bounding the region of interest in\n            the objective outcome space.\n        optimization_config: Optimization config.\n        arm_names: Arm names for each observation.\n        use_model_predictions: If True, will use model predictions at\n            observation_features to compute Pareto front, if provided. If False,\n            will use observation_data directly to compute Pareto front, regardless\n            of whether observation_features are provided.\n\n    Returns:\n        frontier_observations: Observations of points on the pareto frontier.\n        f: n x m tensor representation of the Pareto frontier values where n is the\n        length of frontier_observations and m is the number of metrics.\n        obj_w: m tensor of objective weights.\n        obj_t: m tensor of objective thresholds corresponding to Y, or None if no\n        objective thresholds used.\n    \"\"\"\n\n    array_to_tensor = partial(_array_to_tensor, modelbridge=modelbridge)\n    X = (\n        modelbridge.transform_observation_features(observation_features)\n        if use_model_predictions\n        else None\n    )\n    X = array_to_tensor(X) if X is not None else None\n    Y, Yvar = (None, None)\n    if observation_data is not None:\n        Y, Yvar = modelbridge.transform_observation_data(observation_data)\n        Y, Yvar = (array_to_tensor(Y), array_to_tensor(Yvar))\n    if arm_names is None:\n        arm_names = [None] * len(observation_features)\n\n    # Optimization_config\n    mooc = optimization_config or checked_cast_optional(\n        MultiObjectiveOptimizationConfig, modelbridge._optimization_config\n    )\n    if not mooc:\n        raise ValueError(\n            (\n                \"Experiment must have an existing optimization_config \"\n                \"of type `MultiObjectiveOptimizationConfig` \"\n                \"or `optimization_config` must be passed as an argument.\"\n            )\n        )\n    if not isinstance(mooc, MultiObjectiveOptimizationConfig):\n        mooc = not_none(MultiObjectiveOptimizationConfig.from_opt_conf(mooc))\n    if objective_thresholds:\n        mooc = mooc.clone_with_args(objective_thresholds=objective_thresholds)\n\n    optimization_config = mooc\n\n    # Transform OptimizationConfig.\n    optimization_config = modelbridge.transform_optimization_config(\n        optimization_config=optimization_config,\n        fixed_features=ObservationFeatures(parameters={}),\n    )\n    # Extract weights, constraints, and objective_thresholds\n    objective_weights = extract_objective_weights(\n        objective=optimization_config.objective, outcomes=modelbridge.outcomes\n    )\n    outcome_constraints = extract_outcome_constraints(\n        outcome_constraints=optimization_config.outcome_constraints,\n        outcomes=modelbridge.outcomes,\n    )\n    obj_t = extract_objective_thresholds(\n        objective_thresholds=optimization_config.objective_thresholds,\n        objective=optimization_config.objective,\n        outcomes=modelbridge.outcomes,\n    )\n    obj_t = array_to_tensor(obj_t)\n    # Transform to tensors.\n    obj_w, oc_c, _, _, _ = validate_and_apply_final_transform(\n        objective_weights=objective_weights,\n        outcome_constraints=outcome_constraints,\n        linear_constraints=None,\n        pending_observations=None,\n        final_transform=array_to_tensor,\n    )\n    frontier_evaluator = get_default_frontier_evaluator()\n    # pyre-ignore[28]: Unexpected keyword `modelbridge` to anonymous call\n    f, cov, indx = frontier_evaluator(\n        model=modelbridge.model,\n        X=X,\n        Y=Y,\n        Yvar=Yvar,\n        objective_thresholds=obj_t,\n        objective_weights=obj_w,\n        outcome_constraints=oc_c,\n    )\n    f, cov = f.detach().cpu().clone(), cov.detach().cpu().clone()\n    indx = indx.tolist()\n    frontier_observation_data = array_to_observation_data(\n        f=f.numpy(), cov=cov.numpy(), outcomes=not_none(modelbridge.outcomes)\n    )\n    # Untransform observations\n    for t in reversed(modelbridge.transforms.values()):  # noqa T484\n        frontier_observation_data = t.untransform_observation_data(\n            frontier_observation_data, []\n        )\n    # Construct observations\n    frontier_observations = []\n    for i, obsd in enumerate(frontier_observation_data):\n        frontier_observations.append(\n            Observation(\n                features=observation_features[indx[i]],\n                data=obsd,\n                arm_name=arm_names[indx[i]],\n            )\n        )\n    return frontier_observations, f, obj_w.cpu(), obj_t.cpu()\n\n\ndef pareto_frontier(\n    modelbridge: modelbridge_module.array.ArrayModelBridge,\n    observation_features: List[ObservationFeatures],\n    observation_data: Optional[List[ObservationData]] = None,\n    objective_thresholds: Optional[TRefPoint] = None,\n    optimization_config: Optional[MultiObjectiveOptimizationConfig] = None,\n    arm_names: Optional[List[Optional[str]]] = None,\n    use_model_predictions: bool = True,\n) -> List[Observation]:\n    \"\"\"Helper that applies transforms and calls frontier_evaluator.\n\n    Args:\n        modelbridge: Modelbridge used to predict metrics outcomes.\n        observation_features: observation features to predict, if provided and\n            use_model_predictions is True.\n        observation_data: data for computing the Pareto front, unless features\n            are provided and model_predictions is True.\n        objective_thresholds: metric values bounding the region of interest in\n            the objective outcome space.\n        optimization_config: Optimization config.\n        arm_names: Arm names for each observation.\n        use_model_predictions: If True, will use model predictions at\n            observation_features to compute Pareto front, if provided. If False,\n            will use observation_data directly to compute Pareto front, regardless\n            of whether observation_features are provided.\n\n    Returns:\n        frontier_observations: Observations of points on the pareto frontier.\n    \"\"\"\n    return get_pareto_frontier_and_transformed_configs(\n        modelbridge=modelbridge,\n        observation_features=observation_features,\n        observation_data=observation_data,\n        objective_thresholds=objective_thresholds,\n        optimization_config=optimization_config,\n        arm_names=arm_names,\n        use_model_predictions=use_model_predictions,\n    )[0]\n\n\ndef predicted_pareto_frontier(\n    modelbridge: modelbridge_module.array.ArrayModelBridge,\n    objective_thresholds: Optional[TRefPoint] = None,\n    observation_features: Optional[List[ObservationFeatures]] = None,\n    optimization_config: Optional[MultiObjectiveOptimizationConfig] = None,\n) -> List[Observation]:\n    \"\"\"Generate a pareto frontier based on the posterior means of given\n    observation features.\n\n    Given a model and features to evaluate use the model to predict which points\n    lie on the pareto frontier.\n\n    Args:\n        modelbridge: Modelbridge used to predict metrics outcomes.\n        objective_thresholds: metric values bounding the region of interest in\n            the objective outcome space.\n        observation_features: observation features to predict. Model's training\n            data used by default if unspecified.\n        optimization_config: Optimization config\n\n    Returns:\n        Observations representing points on the pareto frontier.\n    \"\"\"\n    if observation_features is None:\n        observation_features = []\n        arm_names = []\n        for obs in modelbridge.get_training_data():\n            observation_features.append(obs.features)\n            arm_names.append(obs.arm_name)\n    else:\n        arm_names = None\n    if not observation_features:\n        raise ValueError(\n            \"Must receive observation_features as input or the model must \"\n            \"have training data.\"\n        )\n\n    pareto_observations = pareto_frontier(\n        modelbridge=modelbridge,\n        objective_thresholds=objective_thresholds,\n        observation_features=observation_features,\n        optimization_config=optimization_config,\n        arm_names=arm_names,\n    )\n    return pareto_observations\n\n\ndef observed_pareto_frontier(\n    modelbridge: modelbridge_module.array.ArrayModelBridge,\n    objective_thresholds: Optional[TRefPoint] = None,\n    optimization_config: Optional[MultiObjectiveOptimizationConfig] = None,\n) -> List[Observation]:\n    \"\"\"Generate a pareto frontier based on observed data.\n\n    Given observed data, return those outcomes in the pareto frontier.\n\n    Args:\n        modelbridge: Modelbridge that holds previous training data.\n        objective_thresholds: metric values bounding the region of interest in\n            the objective outcome space.\n        optimization_config: Optimization config\n\n    Returns:\n        Data representing points on the pareto frontier.\n    \"\"\"\n    # Get observation_data from current training data\n    observation_data = []\n    observation_features = []\n    arm_names = []\n    for obs in modelbridge.get_training_data():\n        observation_data.append(obs.data)\n        observation_features.append(obs.features)\n        arm_names.append(obs.arm_name)\n\n    pareto_observations = pareto_frontier(\n        modelbridge=modelbridge,\n        objective_thresholds=objective_thresholds,\n        observation_data=observation_data,\n        observation_features=observation_features,\n        optimization_config=optimization_config,\n        arm_names=arm_names,\n        use_model_predictions=False,\n    )\n    return pareto_observations\n\n\ndef hypervolume(\n    modelbridge: modelbridge_module.array.ArrayModelBridge,\n    observation_features: List[ObservationFeatures],\n    objective_thresholds: Optional[TRefPoint] = None,\n    observation_data: Optional[List[ObservationData]] = None,\n    optimization_config: Optional[MultiObjectiveOptimizationConfig] = None,\n    use_model_predictions: bool = True,\n) -> float:\n    \"\"\"Helper function that computes hypervolume of a given list of outcomes.\"\"\"\n    # Get Pareto front\n    observations, f, obj_w, obj_t = get_pareto_frontier_and_transformed_configs(\n        modelbridge=modelbridge,\n        objective_thresholds=objective_thresholds,\n        observation_features=observation_features,\n        observation_data=observation_data,\n        optimization_config=optimization_config,\n        use_model_predictions=use_model_predictions,\n    )\n    if obj_t is None:\n        raise ValueError(\n            \"Cannot compute hypervolume without having objective thresholds specified.\"\n        )\n    # Apply appropriate weights and thresholds\n    obj, obj_t = get_weighted_mc_objective_and_objective_thresholds(\n        objective_weights=obj_w, objective_thresholds=obj_t\n    )\n    f_t = obj(f)\n    hv = Hypervolume(ref_point=obj_t)\n    return hv.compute(f_t)\n\n\ndef predicted_hypervolume(\n    modelbridge: modelbridge_module.array.ArrayModelBridge,\n    objective_thresholds: Optional[TRefPoint] = None,\n    observation_features: Optional[List[ObservationFeatures]] = None,\n    optimization_config: Optional[MultiObjectiveOptimizationConfig] = None,\n) -> float:\n    \"\"\"Calculate hypervolume of a pareto frontier based on the posterior means of\n    given observation features.\n\n    Given a model and features to evaluate calculate the hypervolume of the pareto\n    frontier formed from their predicted outcomes.\n\n    Args:\n        modelbridge: Modelbridge used to predict metrics outcomes.\n        objective_thresholds: point defining the origin of hyperrectangles that\n            can contribute to hypervolume.\n        observation_features: observation features to predict. Model's training\n            data used by default if unspecified.\n        optimization_config: Optimization config\n\n    Returns:\n        calculated hypervolume.\n    \"\"\"\n    observation_features = (\n        observation_features\n        if observation_features is not None\n        else [obs.features for obs in modelbridge.get_training_data()]\n    )\n    if not observation_features:\n        raise ValueError(\n            \"Must receive observation_features as input or the model must \"\n            \"have training data.\"\n        )\n\n    return hypervolume(\n        modelbridge=modelbridge,\n        objective_thresholds=objective_thresholds,\n        observation_features=observation_features,\n        optimization_config=optimization_config,\n    )\n\n\ndef observed_hypervolume(\n    modelbridge: modelbridge_module.array.ArrayModelBridge,\n    objective_thresholds: Optional[TRefPoint] = None,\n    optimization_config: Optional[MultiObjectiveOptimizationConfig] = None,\n) -> float:\n    \"\"\"Calculate hypervolume of a pareto frontier based on observed data.\n\n    Given observed data, return the hypervolume of the pareto frontier formed from\n    those outcomes.\n\n    Args:\n        modelbridge: Modelbridge that holds previous training data.\n        objective_thresholds: point defining the origin of hyperrectangles that\n            can contribute to hypervolume.\n        observation_features: observation features to predict. Model's training\n            data used by default if unspecified.\n        optimization_config: Optimization config\n\n    Returns:\n        (float) calculated hypervolume.\n    \"\"\"\n    # Get observation_data from current training data.\n    observation_data = [obs.data for obs in modelbridge.get_training_data()]\n    observation_features = [obs.features for obs in modelbridge.get_training_data()]\n\n    return hypervolume(\n        modelbridge=modelbridge,\n        objective_thresholds=objective_thresholds,\n        observation_features=observation_features,\n        observation_data=observation_data,\n        optimization_config=optimization_config,\n        use_model_predictions=False,\n    )\n\n\ndef array_to_observation_data(\n    f: np.ndarray, cov: np.ndarray, outcomes: List[str]\n) -> List[ObservationData]:\n    \"\"\"Convert arrays of model predictions to a list of ObservationData.\n\n    Args:\n        f: An (n x m) array\n        cov: An (n x m x m) array\n        outcomes: A list of d outcome names\n\n    Returns: A list of n ObservationData\n    \"\"\"\n    observation_data = []\n    for i in range(f.shape[0]):\n        observation_data.append(\n            ObservationData(\n                metric_names=list(outcomes),\n                means=f[i, :].copy(),\n                covariance=cov[i, :, :].copy(),\n            )\n        )\n    return observation_data\n\n\ndef observation_data_to_array(\n    outcomes: List[str],\n    observation_data: List[ObservationData],\n) -> Tuple[np.ndarray, np.ndarray]:\n    \"\"\"Convert a list of Observation data to arrays.\n\n    Args:\n        observation_data: A list of n ObservationData\n\n    Returns:\n        An array of n ObservationData, each containing\n            - f: An (n x m) array\n            - cov: An (n x m x m) array\n    \"\"\"\n    means = []\n    cov = []\n    for obsd in observation_data:\n        metric_idxs = np.array([obsd.metric_names.index(m) for m in outcomes])\n        means.append(obsd.means[metric_idxs])\n        cov.append(obsd.covariance[metric_idxs][:, metric_idxs])\n    return np.array(means), np.array(cov)\n\n\ndef observation_features_to_array(\n    parameters: List[str], obsf: List[ObservationFeatures]\n) -> np.ndarray:\n    \"\"\"Convert a list of Observation features to arrays.\"\"\"\n    return np.array([[of.parameters[p] for p in parameters] for of in obsf])\n\n\ndef _array_to_tensor(\n    array: Union[np.ndarray, List[float]],\n    modelbridge: Optional[modelbridge_module.base.ModelBridge] = None,\n) -> Tensor:\n    if modelbridge and hasattr(modelbridge, \"_array_to_tensor\"):\n        # pyre-ignore[16]: modelbridge does not have attribute `_array_to_tensor`\n        return modelbridge._array_to_tensor(array)\n    else:\n        return torch.tensor(array)\n", "meta": {"hexsha": "86e31bf94a42d3e9b6fd022b646d32a314130bcf", "size": 39730, "ext": "py", "lang": "Python", "max_stars_repo_path": "ax/modelbridge/modelbridge_utils.py", "max_stars_repo_name": "josalhor/Ax", "max_stars_repo_head_hexsha": "45311efbc65b5cd1e4636dfb9ce51bd1f77b673a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-18T10:07:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T10:07:18.000Z", "max_issues_repo_path": "ax/modelbridge/modelbridge_utils.py", "max_issues_repo_name": "josalhor/Ax", "max_issues_repo_head_hexsha": "45311efbc65b5cd1e4636dfb9ce51bd1f77b673a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ax/modelbridge/modelbridge_utils.py", "max_forks_repo_name": "josalhor/Ax", "max_forks_repo_head_hexsha": "45311efbc65b5cd1e4636dfb9ce51bd1f77b673a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6506986028, "max_line_length": 88, "alphanum_fraction": 0.6813491065, "include": true, "reason": "import numpy", "num_tokens": 8066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891307678319, "lm_q2_score": 0.30735802955444114, "lm_q1q2_score": 0.1809998028588284}}
{"text": "\"\"\"Module to hold our forward models that until now have been floating in the\nweb application.\n\nRight now this includes database interaction and model rescaling software.\n\n\nAuthors\n-------\nJules Fowler, April 2019\nNatasha Batalha\nHannah Wakeford\n\n\nUse\n---\nThis is meant to be run through the Flask application, or can be run manually\nwith a provided list or arguments.\n\"\"\"\n\n## -- IMPORTS\nimport os\n\nimport astropy.constants as constants\nfrom six.moves import StringIO\nimport astropy.table as at\nimport astropy.units as u\nfrom bokeh.resources import INLINE\nfrom bokeh.util.string import encode_utf8\nfrom bokeh.embed import components\nfrom bokeh.models import Range1d\nfrom bokeh.models.widgets import Panel, Tabs\nfrom bokeh.plotting import figure, output_file, save\nimport h5py\nimport numpy as np\nimport pandas as pd\nfrom sqlalchemy import create_engine\n\nfrom exoctk.utils import get_env_variables\n\n## -- FUNCTIONS\n\ndef fortney_grid(args, write_plot=False, write_table=False):\n    \"\"\"\n    Function to grab a Fortney Grid model, plot it, and make a table.\n\n    Parameters\n    ----------\n    args : dict\n        Dictionary of arguments for the Fortney Grid. Must include :\n        temp\n        chem\n        cloud\n        pmass\n        m_unit\n        reference_radius\n        r_unit\n        rstar\n        rstar_unit\n    write_plot : bool, optional\n        Whether or not to save the bokeh plot, defaults to False.\n    write_table : bool, optional\n        Whether or not to save the ascii table, defaults to False.\n\n    Returns\n    -------\n    fig : bokeh object\n        The unsaved bokeh plot.\n    fh : ascii table object\n        The unsaved ascii table.\n    temp_out : list of str of int\n        The list of temperatures in the model grid.\n    \"\"\"\n\n    # Check for Fortney Grid database\n    print(os.path.join(get_env_variables()['exoctk_data'], 'fortney/fortney_models.db'))\n    try:\n        db = create_engine('sqlite:///' +\n                os.path.join(get_env_variables()['exoctk_data'], 'fortney/fortney_models.db'))\n        header = pd.read_sql_table('header', db)\n    except:\n        raise Exception('Fortney Grid File Path is incorrect, or not initialized')\n\n    if args:\n        rstar = float(args['rstar'])\n        rstar = (rstar * u.Unit(args['rstar_unit'])).to(u.km)\n        reference_radius = float(args['reference_radius'])\n        rplan = (reference_radius * u.Unit(args['r_unit'])).to(u.km)\n        temp = float(args['temp'])\n        # clouds\n        cloud = args['cloud']\n        if cloud.find('flat') != -1:\n            flat = int(cloud[4:])\n            ray = 0\n        elif cloud.find('ray') != -1:\n            ray = int(cloud[3:])\n            flat = 0\n        elif int(cloud) == 0:\n            flat = 0\n            ray = 0\n        else:\n            flat = 0\n            ray = 0\n            print('No cloud parameter not specified, default no clouds added')\n\n        # chemistry\n        chem = args['chem']\n        if chem == 'noTiO':\n            noTiO = True\n        if chem == 'eqchem':\n            noTiO = False\n            # grid does not allow clouds for cases with TiO\n            flat = 0\n            ray = 0\n\n        fort_grav = 25.0 * u.m / u.s**2\n\n        df = header.loc[(header.gravity == fort_grav) & (header.temp == temp) &\n                        (header.noTiO == noTiO) & (header.ray == ray) &\n                        (header.flat == flat)]\n\n        wave_planet = np.array(pd.read_sql_table(df['name'].values[0], db)['wavelength'])[::-1]\n        r_lambda = np.array(pd.read_sql_table(df['name'].values[0], db)['radius']) * u.km\n\n        # All fortney models have fixed 1.25 radii\n        z_lambda = r_lambda - (1.25 * u.R_jup).to(u.km)\n\n        # Scale with planetary mass\n        pmass = float(args['pmass'])\n        mass = (pmass * u.Unit(args['m_unit'])).to(u.kg)\n\n        # Convert radius to m for gravity units\n        gravity = constants.G * (mass) / (rplan.to(u.m))**2.0\n\n        # Scale lambbda (this technically ignores the fact that scaleheight\n        # is altitude dependent) therefore, it will not be valide for very\n        # very low gravities\n        z_lambda = z_lambda * fort_grav / gravity\n\n        # Create new wavelength dependent R based on scaled ravity\n        r_lambda = z_lambda + rplan\n\n        # Finally compute (rp/r*)^2\n        flux_planet = np.array(r_lambda**2 / rstar**2)\n\n        x = wave_planet\n        y = flux_planet[::-1]\n\n    else:\n        df = pd.read_sql_table('t1000g25_noTiO', db)\n        x, y = df['wavelength'], df['radius']**2.0 / 7e5**2.0\n\n    tab = at.Table(data=[x, y])\n    fh = StringIO()\n    tab.write(fh, format='ascii.no_header')\n\n    if write_table:\n        tab.write('fortney.dat', format='ascii.no_header')\n\n    fig = figure(plot_width=1100, plot_height=400)\n    fig.line(x, 1e6 * (y - np.mean(y)), color='Black', line_width=0.5)\n    fig.xaxis.axis_label = 'Wavelength (um)'\n    fig.yaxis.axis_label = 'Rel. Transit Depth (ppm)'\n\n    if write_plot:\n        output_file('fortney.html')\n        save(fig)\n\n    # Return temperature list for the fortney grid page\n    temp_out = list(map(str, header.temp.unique()))\n\n    return fig, fh, temp_out\n\n\ndef generic_grid(input_args, write_plot=False, write_table=False):\n    \"\"\"\n    Build a plot and table from the generic grid results.\n\n    Parameters\n    ----------\n    input_args : dict\n        A dictionary of the form output from the generic grid form.\n        If manual input must include :\n        r_star : The radius of the star.\n        r_planet : The radius of the planet.\n        gravity : The gravity.\n        temperature : The temperature.\n        condensation : local or rainout\n        metallicity\n        c_o : carbon/oxygen ratio\n        haze\n        cloud\n    write_plot : bool, optional\n        Whether to write the plot out. Defaults to False.\n    write_table : bool, optional\n        Whether to write the table out. Defaults to Fals.\n\n    Returns\n    -------\n    plot : bokeh object\n        Unsaved bokeh plot.\n    table : ascii table object\n        Unsaved ascii table.\n    closest_match : dict\n        A dictionary with the parameters/model name of the closest\n        match in the grid.\n    error_message : str\n        An error message, or lack therof.\n    \"\"\"\n\n    try:\n        str_args = {}\n        for key, value in input_args.items():\n            str_args[key] = value[0]\n        input_args=str_args\n    except:\n        pass\n        #this attempts to convert passed arguments from list to string, and does nothing if the arguments are not lists\n\n    # Find path to the database.\n    database_path = os.path.join(get_env_variables()['exoctk_data'], 'generic/generic_grid_db.hdf5')\n    # Build rescaled model\n    solution, inputs, closest_match, error_message = rescale_generic_grid(input_args, database_path)\n\n    # Build file out\n    tab = at.Table(data=[solution['wv'], solution['spectra']])\n    fh = StringIO()\n    tab.write(fh, format='ascii.no_header')\n\n    if write_table:\n        tab.write('generic.dat')\n\n    # Plot\n    fig = figure(title='Rescaled Generic Grid Transmission Spectra'.upper(), plot_width=1100, plot_height=400)\n    fig.x_range.start = 0.3\n    fig.x_range.end = 5\n    fig.line(solution['wv'], solution['spectra'], color='Black', line_width=1)\n    fig.xaxis.axis_label = 'Wavelength (um)'\n    fig.yaxis.axis_label = 'Transit Depth (Rp/R*)^2'\n\n    if write_plot:\n        output_file('generic.html')\n        save(fig)\n\n    return fig, fh, closest_match, error_message\n\n\ndef rescale_generic_grid(input_args, database_path):\n    \"\"\" Pulls a model from the generic grid, rescales it,\n    and returns the model and wavelength.\n\n    Parameters\n    ----------\n    input_args : dict\n        A dictionary of the form output from the generic grid form.\n        If manual input must include :\n        r_star : The radius of the star.\n        r_planet : The radius of the planet.\n        gravity : The gravity.\n        temperature : The temperature.\n        condensation : local or rainout\n        metallicity\n        c_o : carbon/oxygen ratio\n        haze\n        cloud\n    database_path : str\n        Path to the generic grid database.\n\n    Returns\n    -------\n    wv : np.array\n        Array of wavelength bins.\n    spectra : np.array\n        Array of the planetary model spectrum.\n    inputs : dict\n        The dictionary of inputs given to the function.\n    closest_match : dict\n        A dictionary with the parameters/model name of the closest\n        match in the grid.\n    error_message : bool, str\n        Either False, for no error, or a message about what went wrong.\n    \"\"\"\n    error_message = ''\n    try:\n        # Parameter validation\n        # Set up some nasty tuples first\n        scaling_space = [('r_star', [0.05, 10000]),\n                         ('r_planet', [0.0,  10000]),\n                         ('gravity', [.5, 50]),\n                         ('temperature', [400, 2600])]\n\n        inputs = {}\n        # First check the scaling\n        for tup in scaling_space:\n            key, space = tup\n            val = float(input_args[key])\n            if val >= space[0] and val <= space[1]:\n                inputs[key] = val\n            else:\n                error_message = 'One of the scaling parameters was out of range: {}.'.format(key)\n                break\n\n        # Map to nearest model key\n        temp_range = np.arange(600, 2700, 100)\n        grav_range = np.array([5, 10, 20, 50])\n        sort_temp = (np.abs(inputs['temperature'] - temp_range)).argmin()\n        sort_grav = (np.abs(inputs['gravity'] - grav_range)).argmin()\n        model_temp = temp_range[sort_temp]\n        input_args['model_temperature'] = '0{}'.format(model_temp)[-4:]\n        model_grav = grav_range[sort_grav]\n        input_args['model_gravity'] = '0{}'.format(model_grav)[-2:]\n\n        # Check the model parameters\n        str_temp_range = ['0400'] + ['0{}'.format(elem)[-4:] for elem in temp_range]\n        model_space = [('condensation', ['local', 'rainout']),\n                        ('RCF', ['0.25', '0.50', '0.75', '1.00']),\n                       ('model_temperature', str_temp_range),\n                       ('model_gravity', ['05', '10', '20', '50']),\n                       ('metallicity', ['+0.0', '+1.0', '+1.7', '+2.0', '+2.3']),\n                       ('c_o', ['0.35', '0.56', '0.70', '1.00']),\n                       ('haze', ['0001', '0010', '0150', '1100']),\n                       ('cloud', ['0.00', '0.06', '0.20','1.00'])]\n\n        model_key = ''\n        for tup in model_space:\n            key, space = tup\n            if input_args[key] in space:\n                inputs[key] = input_args[key]\n                model_key += '{}_'.format(inputs[key])\n            else:\n                error_message = 'One of the model parameters was out of range.'\n                break\n        model_key = model_key[:-1]\n\n\n        # Define constants\n        boltzmann = 1.380658E-16 # gm*cm^2/s^2 * Kelvin\n        permitivity = 1.6726E-24 * 2.3 #g  cgs  Hydrogen + Helium Atmosphere\n        optical_depth = 0.56\n        r_sun = 69580000000 # cm\n        r_jupiter = 6991100000 # cm\n\n        closest_match = {'model_key': model_key, 'model_gravity': model_grav,\n                         'model_temperature': model_temp}\n\n        with h5py.File(database_path, 'r') as f:\n            # Can't use the final NaN value\n            model_wv = f['/wavelength'][...][:-1]\n            model_spectra = f['/spectra/{}'.format(model_key)][...][:-1]\n\n        radius_ratio = np.sqrt(model_spectra) * inputs['r_planet']/inputs['r_star']\n        r_star = inputs['r_star'] * r_sun\n        r_planet = inputs['r_planet'] * r_jupiter\n        model_grav = model_grav * 1e2\n        inputs['gravity'] = inputs['gravity'] * 1e2\n\n        # Start with baseline based on model parameters\n        scale_height = (boltzmann * model_temp) / (permitivity * model_grav)\n        r_planet_base = np.sqrt(radius_ratio) * r_sun\n        altitude = r_planet_base - (np.sqrt(radius_ratio[2000])*r_sun)\n        opacity = optical_depth * np.sqrt((boltzmann * model_temp * permitivity * model_grav) / \\\n                                          (2 * np.pi * r_planet_base)) * \\\n                                  np.exp(altitude / scale_height)\n        # Now rescale from baseline\n        solution = {}\n        solution['scale_height'] = (boltzmann * inputs['temperature']) / (permitivity * inputs['gravity'])\n        solution['altitude'] = solution['scale_height'] * \\\n                               np.log10(opacity/optical_depth * \\\n                                        np.sqrt((2 * np.pi * r_planet) / \\\n                                                (boltzmann * inputs['temperature'] * inputs['gravity'])))\n        solution['radius'] = solution['altitude'] + r_planet\n\n        # Sort data\n        sort = np.argsort(model_wv)\n        solution['wv'] = model_wv[sort]\n        solution['radius'] = solution['radius'][sort]\n        solution['spectra'] = (solution['radius']/r_star)**2\n\n    except (KeyError, ValueError) as e:\n        error_message = 'One of the parameters to make up the model was missing or out of range.'\n        model_key = 'rainout_0400_50_+0.0_0.70_0010_1.00'\n        solution = {}\n        with h5py.File(database_path) as f:\n            solution['wv'] = f['/wavelength'][...][:-1]\n            solution['spectra'] = f['/spectra/{}'.format(model_key)][...][:-1]\n        closest_match = {'model_key': model_key, 'model_temperature': 400,\n                'model_gravity': 50}\n        inputs = input_args\n\n    return solution, inputs, closest_match, error_message\n", "meta": {"hexsha": "65d2b105e81aa08f7e71e6059afaa74228ac599a", "size": 13515, "ext": "py", "lang": "Python", "max_stars_repo_path": "exoctk/forward_models/forward_models.py", "max_stars_repo_name": "dzhan27/exocsi", "max_stars_repo_head_hexsha": "f3eb204f6587954d9532d3ad9bdc8dd4a12f567c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exoctk/forward_models/forward_models.py", "max_issues_repo_name": "dzhan27/exocsi", "max_issues_repo_head_hexsha": "f3eb204f6587954d9532d3ad9bdc8dd4a12f567c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exoctk/forward_models/forward_models.py", "max_forks_repo_name": "dzhan27/exocsi", "max_forks_repo_head_hexsha": "f3eb204f6587954d9532d3ad9bdc8dd4a12f567c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6538461538, "max_line_length": 119, "alphanum_fraction": 0.582981872, "include": true, "reason": "import numpy,import astropy", "num_tokens": 3376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.3073580295544412, "lm_q1q2_score": 0.18099979842358804}}
{"text": "import numpy as np\nfrom astropy.io import fits\nfrom astropy.table import Table, vstack\nfrom astropy.wcs import WCS\nimport os\nimport argparse\nimport logging, traceback\nimport time\nimport pandas as pd\n\nfrom bkg_rate_estimation import rate_obj_from_sqltab\nfrom sqlite_funcs import get_conn, write_result, write_results,\\\n                        timeID2time_dur, write_results_fromSigImg,\\\n                        update_square_stat, write_square_res_line,\\\n                        write_square_results\nfrom dbread_funcs import get_rate_fits_tab, guess_dbfname, get_twinds_tab,\\\n                    get_seeds_tab, get_info_tab, get_files_tab,\\\n                    get_square_tab, get_full_sqlite_table_as_df\nfrom config import EBINS0, EBINS1, solid_angle_dpi_fname, fp_dir\nfrom flux_models import Plaw_Flux\nfrom minimizers import NLLH_ScipyMinimize_Wjacob, imxy_grid_miner, NLLH_ScipyMinimize\nfrom drm_funcs import DRMs\nfrom ray_trace_funcs import RayTraces, FootPrints\nfrom LLH import LLH_webins\nfrom models import Bkg_Model_wSA, Point_Source_Model, Point_Source_Model_Wuncoded,\\\n            CompoundModel, Bkg_Model_wFlatA, Point_Source_Model_Binned_Rates\nfrom do_intllh_scan import kum_mode, kum_pdf, kum_logpdf, kum_deriv_logpdf, deriv2_kum_logpdf\n\n# need to read rate fits from DB\n# and read twinds\n# and read/get event, dmask, and ebins\n# then get bkg_llh_obj and a minimizer\n# then loop over all time windows\n# minimizing nllh and recording bf params\n\ndef cli():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--evfname', type=str,\\\n            help=\"Event data file\",\n            default=None)\n    parser.add_argument('--dmask', type=str,\\\n            help=\"Detmask fname\",\n            default=None)\n    parser.add_argument('--job_id', type=int,\\\n            help=\"ID to tell it what seeds to do\",\\\n            default=-1)\n    parser.add_argument('--Njobs', type=int,\\\n            help=\"Total number of jobs submitted\",\\\n            default=64)\n    parser.add_argument('--dbfname', type=str,\\\n            help=\"Name to save the database to\",\\\n            default=None)\n    parser.add_argument('--rt_dir', type=str,\\\n            help=\"Directory with ray traces\",\\\n            default=None)\n    parser.add_argument('--pcfname', type=str,\\\n            help=\"partial coding file name\",\\\n            default='pc_2.img')\n    parser.add_argument('--job_fname', type=str,\\\n            help=\"File name for table with what imx/y square for each job\",\\\n            default='job_table2.csv')\n    parser.add_argument('--rate_fname', type=str,\\\n            help=\"Rate results file name\",\\\n            default='rate_seeds2.csv')\n    parser.add_argument('--bkg_fname', type=str,\\\n            help=\"Name of the file with the bkg fits\",\\\n            default='bkg_estimation.csv')\n    parser.add_argument('--pix_fname', type=str,\\\n            help=\"Name of the file with good imx/y coordinates\",\\\n            default='good_pix2scan.npy')\n    parser.add_argument('--sim_dir', type=str,\\\n            help=\"Name of the simulation directory\",\\\n            default=None)\n    parser.add_argument('--log_fname', type=str,\\\n            help=\"Name for the log file\",\\\n            default='llh_sim')\n    parser.add_argument('--dur_min', type=float,\\\n            help=\"Min duration to use\",\n            default=0.5)\n    parser.add_argument('--dur_max', type=float,\\\n            help=\"Max duration to use\",\n            default=4.096)\n    parser.add_argument('--dt_min', type=float,\\\n            help=\"Min time from trig time to use\",\n            default=-6.144)\n    parser.add_argument('--dt_max', type=float,\\\n            help=\"Max time from trig time to use\",\n            default=4.096)\n    args = parser.parse_args()\n    return args\n\n\ndef parse_bkg_csv(bkg_fname, solid_angle_dpi, ebins0, ebins1, bl_dmask, rt_dir):\n\n    bkg_df = pd.read_csv(bkg_fname)\n    col_names = bkg_df.columns\n    nebins = len(ebins0)\n\n    PSnames = []\n    for name in col_names:\n        if '_imx' in name:\n            PSnames.append(name.split('_')[0])\n    print PSnames\n    Nsrcs = len(PSnames)\n    if Nsrcs > 0:\n        bkg_name = 'Background_'\n    else:\n        bkg_name = ''\n\n\n    bkg_mod = Bkg_Model_wFlatA(bl_dmask, solid_angle_dpi, nebins, use_deriv=True)\n\n    ps_mods = []\n\n    if Nsrcs > 0:\n        rt_obj = RayTraces(rt_dir)\n        for i in range(Nsrcs):\n            name = PSnames[i]\n            imx = bkg_df[name+'_imx'][0]\n            imy = bkg_df[name+'_imy'][0]\n            mod = Point_Source_Model_Binned_Rates(imx, imy, 0.1,\\\n                                                  [ebins0,ebins1], rt_obj, bl_dmask,\\\n                                                  use_deriv=True, name=name)\n            ps_mods.append(mod)\n\n    return bkg_df, bkg_name, PSnames, bkg_mod, ps_mods\n\n\n\n\ndef do_analysis(sim_params_df, sim_tab, twind_df,\\\n                pl_flux, drm_obj, rt_dir, fp_dir,\\\n                ev_data, bl_dmask, ebins0, ebins1,\\\n                conn, db_fname, trigger_time,\\\n                work_dir, sim_dir,\\\n                bkg_fname, TSwrite=4.5):\n\n    conn.close()\n\n    nebins = len(ebins0)\n\n    solid_ang_dpi = np.load(solid_angle_dpi_fname)\n\n    bkg_miner = NLLH_ScipyMinimize('')\n    sig_miner = NLLH_ScipyMinimize_Wjacob('')\n\n    bkg_df, bkg_name, PSnames, bkg_mod, ps_mods =\\\n            parse_bkg_csv(bkg_fname, solid_ang_dpi,\\\n                        ebins0, ebins1, bl_dmask, rt_dir)\n\n    bkg_mod.has_deriv = False\n    bkg_mod_list = [bkg_mod]\n    Nsrcs = len(ps_mods)\n    if Nsrcs > 0:\n        bkg_mod_list += ps_mods\n        for ps_mod in ps_mods:\n            ps_mod.has_deriv = False\n        bkg_mod = CompoundModel(bkg_mod_list)\n\n\n\n    for sim_param_ind, sim_param_row in sim_params_df.iterrows():\n\n        logging.info(\"Starting params_id: %d\"%(sim_param_row['params_id']))\n\n        bl = (sim_tab['params_id']==sim_param_row['params_id'])\n        sim_df = sim_tab[bl]\n\n        rt_obj = RayTraces(rt_dir, max_nbytes=6e9)\n        fp_obj = FootPrints(fp_dir)\n\n        res_dfs2write = []\n\n        for sim_ind, sim_row in sim_df.iterrows():\n\n            logging.debug(\"Starting simid: %d, table index: %d\"\\\n                        %(sim_row['simid'],sim_ind))\n            tstart = sim_row['tstart']\n            tstop = tstart + sim_row['dur']\n            dur = sim_row['dur']\n\n            imx_sim = sim_row['imx']\n            imy_sim = sim_row['imy']\n\n            ev_sim_tab = Table.read(sim_row['fname'])\n\n            evdata_ = ev_data.copy()\n            evdata = vstack([evdata_, ev_sim_tab])\n            evdata.sort('TIME')\n\n            bkg_llh_obj = LLH_webins(evdata, ebins0, ebins1, bl_dmask)\n            sig_llh_obj = LLH_webins(evdata, ebins0, ebins1, bl_dmask)\n\n\n\n            xax = np.linspace(-1e-3, 1e-3, 2+1) + imx_sim\n            yax = np.linspace(-1e-3, 1e-3, 2+1) + imy_sim\n            grids = np.meshgrid(xax, yax)\n            imxs = grids[0].ravel()\n            imys = grids[1].ravel()\n            Npix = len(imxs)\n\n            bl = (twind_df['time']<(tstop-.1*dur))&\\\n            ((twind_df['duration']+twind_df['time'])>(tstart+.1*dur))\n            tgrps = twind_df[bl].groupby('timeID')\n            logging.debug(\"%d timeIDs to do\"%(len(tgrps)))\n\n            res_dicts = []\n\n            for timeID, tdf in tgrps:\n\n                res_dict = {}\n                res_dict['params_id'] = sim_param_row['params_id']\n                res_dict['simid'] = sim_row['simid']\n                res_dict['timeID'] = timeID\n\n                t0 = tdf['time'].values[0]\n                dt = tdf['duration'].values[0]\n                tmid = t0 + dt/2.\n                t1 = t0 + dt\n                res_dict['time'] = t0\n                res_dict['duration'] = dt\n\n                bkg_llh_obj.set_time(t0, t1)\n                sig_llh_obj.set_time(t0, t1)\n\n                bkg_row = bkg_df.iloc[np.argmin(np.abs(tmid - bkg_df['time']))]\n\n                bkg_llh_obj.set_model(bkg_mod)\n\n                bkg_miner.set_llh(bkg_llh_obj)\n\n                bkg_params = {pname:bkg_row[pname] for pname in\\\n                            bkg_llh_obj.model.param_names}\n                # bkg_miner.set_fixed_params(bkg_llh_obj.model.param_names)\n                bkg_miner.set_fixed_params(bkg_params.keys(), values=bkg_params.values())\n\n                # bkg_params = {pname:bkg_llh_obj.model.param_dict[pname]['val'] for\\\n                #                 pname in bkg_llh_obj.model.param_names}\n                bkg_nllh = -bkg_llh_obj.get_llh(bkg_params)\n                res_dict['bkg_nllh'] = bkg_nllh\n                logging.debug(\"bkg_param_dict: \")\n                logging.debug(bkg_miner.param_info_dict)\n                logging.debug(\"bkg_nllh: %.3f\" %(bkg_nllh))\n                imx_, imy_ = np.nanmean(imxs), np.nanmean(imys)\n\n                # sig_mod = Point_Source_Model(imx_,\\\n                #                         imy_, 0.3,\\\n                #                         pl_flux, drm_obj,\\\n                #                         [ebins0,ebins1], rt_obj, bl_dmask,\\\n                #                         use_deriv=True)\n\n                sig_mod = Point_Source_Model_Wuncoded(imx_, imy_, 0.3,\\\n                                    pl_flux, drm_obj, [ebins0,ebins1],\\\n                                    rt_obj, fp_obj, bl_dmask, use_deriv=True)\n\n                sig_mod.drm_im_update = .2\n                comp_mod = CompoundModel([bkg_mod, sig_mod])\n                sig_llh_obj.set_model(comp_mod)\n                sig_miner.set_llh(sig_llh_obj)\n                fixed_pars = [pname for pname in sig_miner.param_names if\\\n                            ('A' not in pname) or ('gamma' not in pname)]\n                sig_miner.set_fixed_params(fixed_pars)\n                sig_miner.set_fixed_params(['Signal_A', 'Signal_gamma'], fixed=False)\n\n                TSs = np.zeros(Npix)\n                sig_nllhs = np.zeros(Npix)\n                As = np.zeros(Npix)\n                gammas = np.zeros(Npix)\n\n\n                for ii in range(Npix):\n                    try:\n                        sig_miner.set_fixed_params(['Signal_imx', 'Signal_imy'], [imxs[ii],imys[ii]])\n                        pars, nllh, res = sig_miner.minimize()\n                        TS = np.sqrt(2.*(bkg_nllh - nllh[0]))\n                        # if TS >= TS_min:\n                        if np.isnan(TS):\n                            TS = 0.0\n                        TSs[ii] = TS\n                        sig_nllhs[ii] = nllh[0]\n                        As[ii] = pars[0][0]\n                        gammas[ii] = pars[0][1]\n\n                    except Exception as E:\n                        logging.error(E)\n                        logging.error(traceback.format_exc())\n                        logging.error(\"Failed to minimize seed: \")\n                        logging.error((imxs[ii],imys[ii]))\n\n                logging.debug(\"Max TS: %.2f\" %(np.nanmax(TSs)))\n\n                best_ind = np.nanargmax(TSs)\n                res_dict['TS'] = TSs[best_ind]\n                res_dict['imx'] = imxs[best_ind]\n                res_dict['imy'] = imys[best_ind]\n                res_dict['A'] = As[best_ind]\n                res_dict['ind'] = gammas[best_ind]\n                res_dict['sig_nllh'] = sig_nllhs[best_ind]\n                res_dicts.append(res_dict)\n                # fname = os.path.join(work_dir,\\\n                #         'res_%d_%d_.fits' %(res_dict['timeID'],\\\n                #         res_dict['squareID']))\n\n\n                # TSbl = (TSs>=TSwrite)\n                # if np.sum(TSbl) > 0:\n                #     logging.info(\"%d above TS of %.1f\"%(np.sum(TSbl),TSwrite))\n                #     res_dict['TS'] = TSs[TSbl]\n                #     res_dict['imx'] = imxs[TSbl]\n                #     res_dict['imy'] = imys[TSbl]\n                #     res_dict['A'] = As[TSbl]\n                #     res_dict['ind'] = gammas[TSbl]\n                #     res_dict['sig_nllh'] = sig_nllhs[TSbl]\n                #     # res_dict['fname'] = fname\n                #     res_dfs2write.append(pd.DataFrame(res_dict))\n\n            res_df = pd.DataFrame(res_dicts)\n            res_dfs2write.append(res_df)\n\n        fname = os.path.join(sim_dir,\\\n                'res_paramsID_%d_.csv' %(sim_param_row['params_id']))\n\n        res_df = pd.concat(res_dfs2write, ignore_index=True)\n        res_df.to_csv(fname, index=False)\n        logging.info(\"Saved results to\")\n        logging.info(fname)\n\n\n\n\n\ndef main(args):\n\n    # fname = 'llh_analysis_from_rate_seeds_' + str(args.job_id)\n    fname = args.log_fname + '_' + str(args.job_id)\n\n    logging.basicConfig(filename=fname+'.log', level=logging.DEBUG,\\\n                    format='%(asctime)s-' '%(levelname)s- %(message)s')\n\n    t_0 = time.time()\n\n    if args.dbfname is None:\n        db_fname = guess_dbfname()\n        if isinstance(db_fname, list):\n            db_fname = db_fname[0]\n    else:\n        db_fname = args.dbfname\n\n    logging.info('Connecting to DB')\n    conn = get_conn(db_fname)\n\n    info_tab = get_info_tab(conn)\n    logging.info('Got info table')\n\n    files_tab = get_files_tab(conn)\n    logging.info('Got files table')\n\n    trigtime = info_tab['trigtimeMET'][0]\n\n    evfname = files_tab['evfname'][0]\n    # ev_data = fits.open(evfname)[1].data\n    ev_data = Table.read(evfname)\n    dmask_fname = files_tab['detmask'][0]\n    dmask = fits.open(dmask_fname)[0].data\n    bl_dmask = (dmask==0.0)\n    logging.debug('Opened up event and detmask files')\n\n    bkg_fits_df = pd.read_csv(args.bkg_fname)\n\n    sim_params_df = pd.read_csv(os.path.join(args.sim_dir, 'sim_param_table.csv'))\n    sim_tab = pd.read_csv(os.path.join(args.sim_dir, 'sim_table.csv'))\n\n    bl = (sim_params_df['im_id']==args.job_id)\n    sim_params_df = sim_params_df[bl]\n    Nsims = len(sim_params_df)\n\n    # rate_fits_df = get_rate_fits_tab(conn)\n    # bkg_rates_obj = rate_obj_from_sqltab(rate_fits_df, 0, 1)\n\n    time_starting = time.time()\n    proc_num = args.job_id\n    # init classes up here\n\n    drm_dir = files_tab['drmDir'][0]\n    if args.rt_dir is None:\n        rt_dir = files_tab['rtDir'][0]\n    else:\n        rt_dir = args.rt_dir\n    drm_obj = DRMs(drm_dir)\n    # rt_obj = RayTraces(rt_dir, max_nbytes=1e10)\n    work_dir = files_tab['workDir'][0]\n\n    pl_flux = Plaw_Flux()\n\n    ebins0 = np.array(EBINS0)\n    ebins1 = np.array(EBINS1)\n    logging.debug(\"ebins0\")\n    logging.debug(ebins0)\n    logging.debug(\"ebins1\")\n    logging.debug(ebins1)\n\n\n    twind_df = get_twinds_tab(conn)\n\n    bl = ((twind_df['time']-trigtime)>=args.dt_min)&\\\n    ((twind_df['duration']+twind_df['time']-trigtime)<args.dt_max)&\\\n    (twind_df['duration']>=args.dur_min)&(twind_df['duration']<=args.dur_max)\n\n    twind_df = twind_df[bl]\n    logging.info(\"Got TimeWindows table\")\n\n\n    do_analysis(sim_params_df, sim_tab, twind_df, pl_flux,\\\n                    drm_obj, rt_dir, fp_dir,\\\n                    ev_data, bl_dmask, ebins0, ebins1,\\\n                    conn, db_fname, trigtime,\\\n                    work_dir, args.sim_dir, args.bkg_fname)\n    # do_analysis(square_tab, rate_res_tab, good_pix['imx'], good_pix['imy'], pl_flux,\\\n    #                 drm_obj, rt_dir,\\\n    #                 bkg_llh_obj, sig_llh_obj,\\\n    #                 conn, db_fname, trigtime, work_dir,bkg_fits_df)\n    conn.close()\n\n\n\nif __name__ == \"__main__\":\n\n    args = cli()\n\n    main(args)\n", "meta": {"hexsha": "f053a1cd6fe3f280a69466d30a4911b1740c4bde", "size": 15253, "ext": "py", "lang": "Python", "max_stars_repo_path": "archive/do_llh_forSims.py", "max_stars_repo_name": "g3-raman/NITRATES", "max_stars_repo_head_hexsha": "b636e22d49d5d656d651b4972193f4bf9ccfa902", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2021-11-01T23:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T09:18:44.000Z", "max_issues_repo_path": "archive/do_llh_forSims.py", "max_issues_repo_name": "g3-raman/NITRATES", "max_issues_repo_head_hexsha": "b636e22d49d5d656d651b4972193f4bf9ccfa902", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-11-03T17:25:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T18:44:27.000Z", "max_forks_repo_path": "archive/do_llh_forSims.py", "max_forks_repo_name": "g3-raman/NITRATES", "max_forks_repo_head_hexsha": "b636e22d49d5d656d651b4972193f4bf9ccfa902", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-17T00:40:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T13:59:34.000Z", "avg_line_length": 35.3078703704, "max_line_length": 101, "alphanum_fraction": 0.5621189274, "include": true, "reason": "import numpy,from astropy", "num_tokens": 3965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.1809997953863099}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#\n\nimport warnings\nimport ctypes\nimport numpy\nimport scipy.linalg\nfrom pyscf import lib\nfrom pyscf.lib import logger\ntry:\n    from pyscf.dft import libxc\nexcept (ImportError, OSError):\n    try:\n        from pyscf.dft import xcfun\n        libxc = xcfun\n    except (ImportError, OSError):\n        import warnings\n        warnings.warn('XC functional libraries (libxc or XCfun) are not available.')\n        from pyscf.dft import xc\n        libxc = xc\n\nfrom pyscf.dft.gen_grid import make_mask, BLKSIZE\nfrom pyscf import __config__\n\nlibdft = lib.load_library('libdft')\nOCCDROP = getattr(__config__, 'dft_numint_OCCDROP', 1e-12)\n# The system size above which to consider the sparsity of the density matrix.\n# If the number of AOs in the system is less than this value, all tensors are\n# treated as dense quantities and contracted by dgemm directly.\nSWITCH_SIZE = getattr(__config__, 'dft_numint_SWITCH_SIZE', 800)\n\ndef eval_ao(mol, coords, deriv=0, shls_slice=None,\n            non0tab=None, out=None, verbose=None):\n    '''Evaluate AO function value on the given grids.\n\n    Args:\n        mol : an instance of :class:`Mole`\n\n        coords : 2D array, shape (N,3)\n            The coordinates of the grids.\n\n    Kwargs:\n        deriv : int\n            AO derivative order.  It affects the shape of the return array.\n            If deriv=0, the returned AO values are stored in a (N,nao) array.\n            Otherwise the AO values are stored in an array of shape (M,N,nao).\n            Here N is the number of grids, nao is the number of AO functions,\n            M is the size associated to the derivative deriv.\n        relativity : bool\n            No effects.\n        shls_slice : 2-element list\n            (shl_start, shl_end).\n            If given, only part of AOs (shl_start <= shell_id < shl_end) are\n            evaluated.  By default, all shells defined in mol will be evaluated.\n        non0tab : 2D bool array\n            mask array to indicate whether the AO values are zero.  The mask\n            array can be obtained by calling :func:`make_mask`\n        out : ndarray\n            If provided, results are written into this array.\n        verbose : int or object of :class:`Logger`\n            No effects.\n\n    Returns:\n        2D array of shape (N,nao) for AO values if deriv = 0.\n        Or 3D array of shape (:,N,nao) for AO values and AO derivatives if deriv > 0.\n        In the 3D array, the first (N,nao) elements are the AO values,\n        followed by (3,N,nao) for x,y,z compoents;\n        Then 2nd derivatives (6,N,nao) for xx, xy, xz, yy, yz, zz;\n        Then 3rd derivatives (10,N,nao) for xxx, xxy, xxz, xyy, xyz, xzz, yyy, yyz, yzz, zzz;\n        ...\n\n    Examples:\n\n    >>> mol = gto.M(atom='O 0 0 0; H 0 0 1; H 0 1 0', basis='ccpvdz')\n    >>> coords = numpy.random.random((100,3))  # 100 random points\n    >>> ao_value = eval_ao(mol, coords)\n    >>> print(ao_value.shape)\n    (100, 24)\n    >>> ao_value = eval_ao(mol, coords, deriv=1, shls_slice=(1,4))\n    >>> print(ao_value.shape)\n    (4, 100, 7)\n    >>> ao_value = eval_ao(mol, coords, deriv=2, shls_slice=(1,4))\n    >>> print(ao_value.shape)\n    (10, 100, 7)\n    '''\n    comp = (deriv+1)*(deriv+2)*(deriv+3)//6\n    if mol.cart:\n        feval = 'GTOval_cart_deriv%d' % deriv\n    else:\n        feval = 'GTOval_sph_deriv%d' % deriv\n    return mol.eval_gto(feval, coords, comp, shls_slice, non0tab, out=out)\n\n#TODO: \\nabla^2 rho and tau = 1/2 (\\nabla f)^2\ndef eval_rho(mol, ao, dm, non0tab=None, xctype='LDA', hermi=0, verbose=None):\n    r'''Calculate the electron density for LDA functional, and the density\n    derivatives for GGA functional.\n\n    Args:\n        mol : an instance of :class:`Mole`\n\n        ao : 2D array of shape (N,nao) for LDA, 3D array of shape (4,N,nao) for GGA\n            or (5,N,nao) for meta-GGA.  N is the number of grids, nao is the\n            number of AO functions.  If xctype is GGA, ao[0] is AO value\n            and ao[1:3] are the AO gradients.  If xctype is meta-GGA, ao[4:10]\n            are second derivatives of ao values.\n        dm : 2D array\n            Density matrix\n\n    Kwargs:\n        non0tab : 2D bool array\n            mask array to indicate whether the AO values are zero.  The mask\n            array can be obtained by calling :func:`make_mask`\n        xctype : str\n            LDA/GGA/mGGA.  It affects the shape of the return density.\n        hermi : bool\n            dm is hermitian or not\n        verbose : int or object of :class:`Logger`\n            No effects.\n\n    Returns:\n        1D array of size N to store electron density if xctype = LDA;  2D array\n        of (4,N) to store density and \"density derivatives\" for x,y,z components\n        if xctype = GGA;  (6,N) array for meta-GGA, where last two rows are\n        \\nabla^2 rho and tau = 1/2(\\nabla f)^2\n\n    Examples:\n\n    >>> mol = gto.M(atom='O 0 0 0; H 0 0 1; H 0 1 0', basis='ccpvdz')\n    >>> coords = numpy.random.random((100,3))  # 100 random points\n    >>> ao_value = eval_ao(mol, coords, deriv=0)\n    >>> dm = numpy.random.random((mol.nao_nr(),mol.nao_nr()))\n    >>> dm = dm + dm.T\n    >>> rho, dx_rho, dy_rho, dz_rho = eval_rho(mol, ao, dm, xctype='LDA')\n    '''\n    xctype = xctype.upper()\n    if xctype == 'LDA' or xctype == 'HF':\n        ngrids, nao = ao.shape\n    else:\n        ngrids, nao = ao[0].shape\n\n    if non0tab is None:\n        non0tab = numpy.ones(((ngrids+BLKSIZE-1)//BLKSIZE,mol.nbas),\n                             dtype=numpy.uint8)\n    if not hermi:\n        # (D + D.T)/2 because eval_rho computes 2*(|\\nabla i> D_ij <j|) instead of\n        # |\\nabla i> D_ij <j| + |i> D_ij <\\nabla j| for efficiency\n        dm = (dm + dm.conj().T) * .5\n\n    shls_slice = (0, mol.nbas)\n    ao_loc = mol.ao_loc_nr()\n    if xctype == 'LDA' or xctype == 'HF':\n        c0 = _dot_ao_dm(mol, ao, dm, non0tab, shls_slice, ao_loc)\n        #:rho = numpy.einsum('pi,pi->p', ao, c0)\n        rho = _contract_rho(ao, c0)\n    elif xctype in ('GGA', 'NLC'):\n        rho = numpy.empty((4,ngrids))\n        c0 = _dot_ao_dm(mol, ao[0], dm, non0tab, shls_slice, ao_loc)\n        #:rho[0] = numpy.einsum('pi,pi->p', c0, ao[0])\n        rho[0] = _contract_rho(c0, ao[0])\n        for i in range(1, 4):\n            #:rho[i] = numpy.einsum('pi,pi->p', c0, ao[i])\n            rho[i] = _contract_rho(c0, ao[i])\n            rho[i] *= 2 # *2 for +c.c. in the next two lines\n            #c1 = _dot_ao_dm(mol, ao[i], dm, non0tab, shls_slice, ao_loc)\n            #rho[i] += numpy.einsum('pi,pi->p', c1, ao[0])\n    else: # meta-GGA\n        # rho[4] = \\nabla^2 rho, rho[5] = 1/2 |nabla f|^2\n        rho = numpy.empty((6,ngrids))\n        c0 = _dot_ao_dm(mol, ao[0], dm, non0tab, shls_slice, ao_loc)\n        #:rho[0] = numpy.einsum('pi,pi->p', ao[0], c0)\n        rho[0] = _contract_rho(ao[0], c0)\n        rho[5] = 0\n        for i in range(1, 4):\n            #:rho[i] = numpy.einsum('pi,pi->p', c0, ao[i]) * 2 # *2 for +c.c.\n            rho[i] = _contract_rho(c0, ao[i]) * 2\n            c1 = _dot_ao_dm(mol, ao[i], dm.T, non0tab, shls_slice, ao_loc)\n            #:rho[5] += numpy.einsum('pi,pi->p', c1, ao[i])\n            rho[5] += _contract_rho(c1, ao[i])\n        XX, YY, ZZ = 4, 7, 9\n        ao2 = ao[XX] + ao[YY] + ao[ZZ]\n        #:rho[4] = numpy.einsum('pi,pi->p', c0, ao2)\n        rho[4] = _contract_rho(c0, ao2)\n        rho[4] += rho[5]\n        rho[4] *= 2\n        rho[5] *= .5\n    return rho\n\ndef eval_rho2(mol, ao, mo_coeff, mo_occ, non0tab=None, xctype='LDA',\n              verbose=None):\n    r'''Calculate the electron density for LDA functional, and the density\n    derivatives for GGA functional.  This function has the same functionality\n    as :func:`eval_rho` except that the density are evaluated based on orbital\n    coefficients and orbital occupancy.  It is more efficient than\n    :func:`eval_rho` in most scenario.\n\n    Args:\n        mol : an instance of :class:`Mole`\n\n        ao : 2D array of shape (N,nao) for LDA, 3D array of shape (4,N,nao) for GGA\n            or (5,N,nao) for meta-GGA.  N is the number of grids, nao is the\n            number of AO functions.  If xctype is GGA, ao[0] is AO value\n            and ao[1:3] are the AO gradients.  If xctype is meta-GGA, ao[4:10]\n            are second derivatives of ao values.\n        dm : 2D array\n            Density matrix\n\n    Kwargs:\n        non0tab : 2D bool array\n            mask array to indicate whether the AO values are zero.  The mask\n            array can be obtained by calling :func:`make_mask`\n        xctype : str\n            LDA/GGA/mGGA.  It affects the shape of the return density.\n        verbose : int or object of :class:`Logger`\n            No effects.\n\n    Returns:\n        1D array of size N to store electron density if xctype = LDA;  2D array\n        of (4,N) to store density and \"density derivatives\" for x,y,z components\n        if xctype = GGA;  (6,N) array for meta-GGA, where last two rows are\n        \\nabla^2 rho and tau = 1/2(\\nabla f)^2\n    '''\n    xctype = xctype.upper()\n    if xctype == 'LDA' or xctype == 'HF':\n        ngrids, nao = ao.shape\n    else:\n        ngrids, nao = ao[0].shape\n\n    if non0tab is None:\n        non0tab = numpy.ones(((ngrids+BLKSIZE-1)//BLKSIZE,mol.nbas),\n                             dtype=numpy.uint8)\n    shls_slice = (0, mol.nbas)\n    ao_loc = mol.ao_loc_nr()\n    pos = mo_occ > OCCDROP\n    if pos.sum() > 0:\n        cpos = numpy.einsum('ij,j->ij', mo_coeff[:,pos], numpy.sqrt(mo_occ[pos]))\n        if xctype == 'LDA' or xctype == 'HF':\n            c0 = _dot_ao_dm(mol, ao, cpos, non0tab, shls_slice, ao_loc)\n            #:rho = numpy.einsum('pi,pi->p', c0, c0)\n            rho = _contract_rho(c0, c0)\n        elif xctype in ('GGA', 'NLC'):\n            rho = numpy.empty((4,ngrids))\n            c0 = _dot_ao_dm(mol, ao[0], cpos, non0tab, shls_slice, ao_loc)\n            #:rho[0] = numpy.einsum('pi,pi->p', c0, c0)\n            rho[0] = _contract_rho(c0, c0)\n            for i in range(1, 4):\n                c1 = _dot_ao_dm(mol, ao[i], cpos, non0tab, shls_slice, ao_loc)\n                #:rho[i] = numpy.einsum('pi,pi->p', c0, c1) * 2 # *2 for +c.c.\n                rho[i] = _contract_rho(c0, c1) * 2\n        else: # meta-GGA\n            # rho[4] = \\nabla^2 rho, rho[5] = 1/2 |nabla f|^2\n            rho = numpy.empty((6,ngrids))\n            c0 = _dot_ao_dm(mol, ao[0], cpos, non0tab, shls_slice, ao_loc)\n            #:rho[0] = numpy.einsum('pi,pi->p', c0, c0)\n            rho[0] = _contract_rho(c0, c0)\n            rho[5] = 0\n            for i in range(1, 4):\n                c1 = _dot_ao_dm(mol, ao[i], cpos, non0tab, shls_slice, ao_loc)\n                #:rho[i] = numpy.einsum('pi,pi->p', c0, c1) * 2 # *2 for +c.c.\n                #:rho[5] += numpy.einsum('pi,pi->p', c1, c1)\n                rho[i] = _contract_rho(c0, c1) * 2\n                rho[5] += _contract_rho(c1, c1)\n            XX, YY, ZZ = 4, 7, 9\n            ao2 = ao[XX] + ao[YY] + ao[ZZ]\n            c1 = _dot_ao_dm(mol, ao2, cpos, non0tab, shls_slice, ao_loc)\n            #:rho[4] = numpy.einsum('pi,pi->p', c0, c1)\n            rho[4] = _contract_rho(c0, c1)\n            rho[4] += rho[5]\n            rho[4] *= 2\n\n            rho[5] *= .5\n    else:\n        if xctype == 'LDA' or xctype == 'HF':\n            rho = numpy.zeros(ngrids)\n        elif xctype in ('GGA', 'NLC'):\n            rho = numpy.zeros((4,ngrids))\n        else:\n            rho = numpy.zeros((6,ngrids))\n\n    neg = mo_occ < -OCCDROP\n    if neg.sum() > 0:\n        cneg = numpy.einsum('ij,j->ij', mo_coeff[:,neg], numpy.sqrt(-mo_occ[neg]))\n        if xctype == 'LDA' or xctype == 'HF':\n            c0 = _dot_ao_dm(mol, ao, cneg, non0tab, shls_slice, ao_loc)\n            #:rho -= numpy.einsum('pi,pi->p', c0, c0)\n            rho -= _contract_rho(c0, c0)\n        elif xctype == 'GGA':\n            c0 = _dot_ao_dm(mol, ao[0], cneg, non0tab, shls_slice, ao_loc)\n            #:rho[0] -= numpy.einsum('pi,pi->p', c0, c0)\n            rho[0] -= _contract_rho(c0, c0)\n            for i in range(1, 4):\n                c1 = _dot_ao_dm(mol, ao[i], cneg, non0tab, shls_slice, ao_loc)\n                #:rho[i] -= numpy.einsum('pi,pi->p', c0, c1) * 2 # *2 for +c.c.\n                rho[i] -= _contract_rho(c0, c1) * 2 # *2 for +c.c.\n        else:\n            c0 = _dot_ao_dm(mol, ao[0], cneg, non0tab, shls_slice, ao_loc)\n            #:rho[0] -= numpy.einsum('pi,pi->p', c0, c0)\n            rho[0] -= _contract_rho(c0, c0)\n            rho5 = 0\n            for i in range(1, 4):\n                c1 = _dot_ao_dm(mol, ao[i], cneg, non0tab, shls_slice, ao_loc)\n                #:rho[i] -= numpy.einsum('pi,pi->p', c0, c1) * 2 # *2 for +c.c.\n                #:rho5 += numpy.einsum('pi,pi->p', c1, c1)\n                rho[i] -= _contract_rho(c0, c1) * 2 # *2 for +c.c.\n                rho5 += _contract_rho(c1, c1)\n            XX, YY, ZZ = 4, 7, 9\n            ao2 = ao[XX] + ao[YY] + ao[ZZ]\n            c1 = _dot_ao_dm(mol, ao2, cneg, non0tab, shls_slice, ao_loc)\n            #:rho[4] -= numpy.einsum('pi,pi->p', c0, c1) * 2\n            rho[4] -= _contract_rho(c0, c1) * 2\n            rho[4] -= rho5 * 2\n\n            rho[5] -= rho5 * .5\n    return rho\n\ndef _vv10nlc(rho,coords,vvrho,vvweight,vvcoords,nlc_pars):\n    thresh=1e-8\n\n    #output\n    exc=numpy.zeros(rho[0,:].size)\n    vxc=numpy.zeros([2,rho[0,:].size])\n\n    #outer grid needs threshing\n    threshind=rho[0,:]>=thresh\n    coords=coords[threshind]\n    R=rho[0,:][threshind]\n    Gx=rho[1,:][threshind]\n    Gy=rho[2,:][threshind]\n    Gz=rho[3,:][threshind]\n    G=Gx**2.+Gy**2.+Gz**2.\n\n    #threshed output\n    excthresh=numpy.zeros(R.size)\n    vxcthresh=numpy.zeros([2,R.size])\n\n    #inner grid needs threshing\n    innerthreshind=vvrho[0,:]>=thresh\n    vvcoords=vvcoords[innerthreshind]\n    vvweight=vvweight[innerthreshind]\n    Rp=vvrho[0,:][innerthreshind]\n    RpW=Rp*vvweight\n    Gxp=vvrho[1,:][innerthreshind]\n    Gyp=vvrho[2,:][innerthreshind]\n    Gzp=vvrho[3,:][innerthreshind]\n    Gp=Gxp**2.+Gyp**2.+Gzp**2.\n\n    #constants and parameters\n    Pi=numpy.pi\n    Pi43=4.*Pi/3.\n    Bvv, Cvv = nlc_pars\n    Kvv=Bvv*1.5*Pi*((9.*Pi)**(-1./6.))\n    Beta=((3./(Bvv*Bvv))**(0.75))/32.\n\n    #inner grid\n    W0p=Gp/(Rp*Rp)\n    W0p=Cvv*W0p*W0p\n    W0p=(W0p+Pi43*Rp)**0.5\n    Kp=Kvv*(Rp**(1./6.))\n\n    #outer grid\n    W0tmp=G/(R**2)\n    W0tmp=Cvv*W0tmp*W0tmp\n    W0=(W0tmp+Pi43*R)**0.5\n    dW0dR=(0.5*Pi43*R-2.*W0tmp)/W0\n    dW0dG=W0tmp*R/(G*W0)\n    K=Kvv*(R**(1./6.))\n    dKdR=(1./6.)*K\n\n    for i in range(R.size):\n        DX=vvcoords[:,0]-coords[i,0]\n        DY=vvcoords[:,1]-coords[i,1]\n        DZ=vvcoords[:,2]-coords[i,2]\n        R2=DX*DX+DY*DY+DZ*DZ\n        gp=R2*W0p+Kp\n        g=R2*W0[i]+K[i]\n        gt=g+gp\n        T=RpW/(g*gp*gt)\n        F=numpy.sum(T)\n        T*=(1./g+1./gt)\n        U=numpy.sum(T)\n        W=numpy.sum(T*R2)\n        F*=-1.5\n        #excthresh is multiplied by Rho later\n        excthresh[i]=Beta+0.5*F\n        vxcthresh[0,i]=Beta+F+1.5*(U*dKdR[i]+W*dW0dR[i])\n        vxcthresh[1,i]=1.5*W*dW0dG[i]\n    exc[threshind]=excthresh\n    vxc[0,threshind]=vxcthresh[0,:]\n    vxc[1,threshind]=vxcthresh[1,:]\n\n    return exc,vxc\n\ndef eval_mat(mol, ao, weight, rho, vxc,\n             non0tab=None, xctype='LDA', spin=0, verbose=None):\n    r'''Calculate XC potential matrix.\n\n    Args:\n        mol : an instance of :class:`Mole`\n\n        ao : ([4/10,] ngrids, nao) ndarray\n            2D array of shape (N,nao) for LDA,\n            3D array of shape (4,N,nao) for GGA\n            or (10,N,nao) for meta-GGA.\n            N is the number of grids, nao is the number of AO functions.\n            If xctype is GGA, ao[0] is AO value and ao[1:3] are the real space\n            gradients.  If xctype is meta-GGA, ao[4:10] are second derivatives\n            of ao values.\n        weight : 1D array\n            Integral weights on grids.\n        rho : ([4/6,] ngrids) ndarray\n            Shape of ((*,N)) for electron density (and derivatives) if spin = 0;\n            Shape of ((*,N),(*,N)) for alpha/beta electron density (and derivatives) if spin > 0;\n            where N is number of grids.\n            rho (*,N) are ordered as (den,grad_x,grad_y,grad_z,laplacian,tau)\n            where grad_x = d/dx den, laplacian = \\nabla^2 den, tau = 1/2(\\nabla f)^2\n            In spin unrestricted case,\n            rho is ((den_u,grad_xu,grad_yu,grad_zu,laplacian_u,tau_u)\n                    (den_d,grad_xd,grad_yd,grad_zd,laplacian_d,tau_d))\n        vxc : ([4,] ngrids) ndarray\n            XC potential value on each grid = (vrho, vsigma, vlapl, vtau)\n            vsigma is GGA potential value on each grid.\n            If the kwarg spin != 0, a list [vsigma_uu,vsigma_ud] is required.\n\n    Kwargs:\n        xctype : str\n            LDA/GGA/mGGA.  It affects the shape of `ao` and `rho`\n        non0tab : 2D bool array\n            mask array to indicate whether the AO values are zero.  The mask\n            array can be obtained by calling :func:`make_mask`\n        spin : int\n            If not 0, the returned matrix is the Vxc matrix of alpha-spin.  It\n            is computed with the spin non-degenerated UKS formula.\n\n    Returns:\n        XC potential matrix in 2D array of shape (nao,nao) where nao is the\n        number of AO functions.\n    '''\n    xctype = xctype.upper()\n    if xctype == 'LDA' or xctype == 'HF':\n        ngrids, nao = ao.shape\n    else:\n        ngrids, nao = ao[0].shape\n\n    if non0tab is None:\n        non0tab = numpy.ones(((ngrids+BLKSIZE-1)//BLKSIZE,mol.nbas),\n                             dtype=numpy.uint8)\n    shls_slice = (0, mol.nbas)\n    ao_loc = mol.ao_loc_nr()\n    transpose_for_uks = False\n    if xctype == 'LDA' or xctype == 'HF':\n        if not isinstance(vxc, numpy.ndarray) or vxc.ndim == 2:\n            vrho = vxc[0]\n        else:\n            vrho = vxc\n        # *.5 because return mat + mat.T\n        #:aow = numpy.einsum('pi,p->pi', ao, .5*weight*vrho)\n        aow = _scale_ao(ao, .5*weight*vrho)\n        mat = _dot_ao_ao(mol, ao, aow, non0tab, shls_slice, ao_loc)\n    else:\n        #wv = weight * vsigma * 2\n        #aow  = numpy.einsum('pi,p->pi', ao[1], rho[1]*wv)\n        #aow += numpy.einsum('pi,p->pi', ao[2], rho[2]*wv)\n        #aow += numpy.einsum('pi,p->pi', ao[3], rho[3]*wv)\n        #aow += numpy.einsum('pi,p->pi', ao[0], .5*weight*vrho)\n        vrho, vsigma = vxc[:2]\n        wv = numpy.empty((4,ngrids))\n        if spin == 0:\n            assert(vsigma is not None and rho.ndim==2)\n            wv[0]  = weight * vrho * .5\n            wv[1:4] = rho[1:4] * (weight * vsigma * 2)\n        else:\n            rho_a, rho_b = rho\n            wv[0]  = weight * vrho * .5\n            try:\n                wv[1:4] = rho_a[1:4] * (weight * vsigma[0] * 2)  # sigma_uu\n                wv[1:4]+= rho_b[1:4] * (weight * vsigma[1])      # sigma_ud\n            except ValueError:\n                warnings.warn('Note the output of libxc.eval_xc cannot be '\n                              'directly used in eval_mat.\\nvsigma from eval_xc '\n                              'should be restructured as '\n                              '(vsigma[:,0],vsigma[:,1])\\n')\n                transpose_for_uks = True\n                vsigma = vsigma.T\n                wv[1:4] = rho_a[1:4] * (weight * vsigma[0] * 2)  # sigma_uu\n                wv[1:4]+= rho_b[1:4] * (weight * vsigma[1])      # sigma_ud\n        #:aow = numpy.einsum('npi,np->pi', ao[:4], wv)\n        aow = _scale_ao(ao[:4], wv)\n        mat = _dot_ao_ao(mol, ao[0], aow, non0tab, shls_slice, ao_loc)\n\n# JCP, 138, 244108\n# JCP, 112, 7002\n    if xctype == 'MGGA':\n        vlapl, vtau = vxc[2:]\n\n        if vlapl is None:\n            vlapl = 0\n        else:\n            if spin != 0:\n                if transpose_for_uks:\n                    vlapl = vlapl.T\n                vlapl = vlapl[0]\n            XX, YY, ZZ = 4, 7, 9\n            ao2 = ao[XX] + ao[YY] + ao[ZZ]\n            #:aow = numpy.einsum('pi,p->pi', ao2, .5 * weight * vlapl, out=aow)\n            aow = _scale_ao(ao2, .5 * weight * vlapl, out=aow)\n            mat += _dot_ao_ao(mol, ao[0], aow, non0tab, shls_slice, ao_loc)\n\n        if spin != 0:\n            if transpose_for_uks:\n                vtau = vtau.T\n            vtau = vtau[0]\n        wv = weight * (.25*vtau + vlapl)\n        #:aow = numpy.einsum('pi,p->pi', ao[1], wv, out=aow)\n        aow = _scale_ao(ao[1], wv, out=aow)\n        mat += _dot_ao_ao(mol, ao[1], aow, non0tab, shls_slice, ao_loc)\n        #:aow = numpy.einsum('pi,p->pi', ao[2], wv, out=aow)\n        aow = _scale_ao(ao[2], wv, out=aow)\n        mat += _dot_ao_ao(mol, ao[2], aow, non0tab, shls_slice, ao_loc)\n        #:aow = numpy.einsum('pi,p->pi', ao[3], wv, out=aow)\n        aow = _scale_ao(ao[3], wv, out=aow)\n        mat += _dot_ao_ao(mol, ao[3], aow, non0tab, shls_slice, ao_loc)\n\n    return mat + mat.T.conj()\n\n\ndef _dot_ao_ao(mol, ao1, ao2, non0tab, shls_slice, ao_loc, hermi=0):\n    '''return numpy.dot(ao1.T, ao2)'''\n    ngrids, nao = ao1.shape\n    if nao < SWITCH_SIZE:\n        return lib.dot(ao1.T.conj(), ao2)\n\n    if not ao1.flags.f_contiguous:\n        ao1 = lib.transpose(ao1)\n    if not ao2.flags.f_contiguous:\n        ao2 = lib.transpose(ao2)\n    if ao1.dtype == ao2.dtype == numpy.double:\n        fn = libdft.VXCdot_ao_ao\n    else:\n        fn = libdft.VXCzdot_ao_ao\n        ao1 = numpy.asarray(ao1, numpy.complex128)\n        ao2 = numpy.asarray(ao2, numpy.complex128)\n\n    if non0tab is None or shls_slice is None or ao_loc is None:\n        pnon0tab = pshls_slice = pao_loc = lib.c_null_ptr()\n    else:\n        pnon0tab    = non0tab.ctypes.data_as(ctypes.c_void_p)\n        pshls_slice = (ctypes.c_int*2)(*shls_slice)\n        pao_loc     = ao_loc.ctypes.data_as(ctypes.c_void_p)\n\n    vv = numpy.empty((nao,nao), dtype=ao1.dtype)\n    fn(vv.ctypes.data_as(ctypes.c_void_p),\n       ao1.ctypes.data_as(ctypes.c_void_p),\n       ao2.ctypes.data_as(ctypes.c_void_p),\n       ctypes.c_int(nao), ctypes.c_int(ngrids),\n       ctypes.c_int(mol.nbas), ctypes.c_int(hermi),\n       pnon0tab, pshls_slice, pao_loc)\n    return vv\n\ndef _dot_ao_dm(mol, ao, dm, non0tab, shls_slice, ao_loc, out=None):\n    '''return numpy.dot(ao, dm)'''\n    ngrids, nao = ao.shape\n    if nao < SWITCH_SIZE:\n        return lib.dot(dm.T, ao.T).T\n\n    if not ao.flags.f_contiguous:\n        ao = lib.transpose(ao)\n    if ao.dtype == dm.dtype == numpy.double:\n        fn = libdft.VXCdot_ao_dm\n    else:\n        fn = libdft.VXCzdot_ao_dm\n        ao = numpy.asarray(ao, numpy.complex128)\n        dm = numpy.asarray(dm, numpy.complex128)\n\n    if non0tab is None or shls_slice is None or ao_loc is None:\n        pnon0tab = pshls_slice = pao_loc = lib.c_null_ptr()\n    else:\n        pnon0tab    = non0tab.ctypes.data_as(ctypes.c_void_p)\n        pshls_slice = (ctypes.c_int*2)(*shls_slice)\n        pao_loc     = ao_loc.ctypes.data_as(ctypes.c_void_p)\n\n    vm = numpy.ndarray((ngrids,dm.shape[1]), dtype=ao.dtype, order='F', buffer=out)\n    dm = numpy.asarray(dm, order='C')\n    fn(vm.ctypes.data_as(ctypes.c_void_p),\n       ao.ctypes.data_as(ctypes.c_void_p),\n       dm.ctypes.data_as(ctypes.c_void_p),\n       ctypes.c_int(nao), ctypes.c_int(dm.shape[1]),\n       ctypes.c_int(ngrids), ctypes.c_int(mol.nbas),\n       pnon0tab, pshls_slice, pao_loc)\n    return vm\n\ndef _scale_ao(ao, wv, out=None):\n    #:aow = numpy.einsum('npi,np->pi', ao[:4], wv)\n    if wv.ndim == 2:\n        ao = ao.transpose(0,2,1)\n    else:\n        ngrids, nao = ao.shape\n        ao = ao.T.reshape(1,nao,ngrids)\n        wv = wv.reshape(1,ngrids)\n\n    wv = numpy.asarray(wv, order='C')\n    comp, nao, ngrids = ao.shape\n    aow = numpy.ndarray((nao,ngrids), dtype=ao.dtype, buffer=out).T\n\n    if not ao.flags.c_contiguous:\n        aow = numpy.einsum('nip,np->pi', ao, wv)\n    elif aow.dtype == numpy.double:\n        libdft.VXC_dscale_ao(aow.ctypes.data_as(ctypes.c_void_p),\n                             ao.ctypes.data_as(ctypes.c_void_p),\n                             wv.ctypes.data_as(ctypes.c_void_p),\n                             ctypes.c_int(comp), ctypes.c_int(nao),\n                             ctypes.c_int(ngrids))\n    elif aow.dtype == numpy.complex128:\n        libdft.VXC_zscale_ao(aow.ctypes.data_as(ctypes.c_void_p),\n                             ao.ctypes.data_as(ctypes.c_void_p),\n                             wv.ctypes.data_as(ctypes.c_void_p),\n                             ctypes.c_int(comp), ctypes.c_int(nao),\n                             ctypes.c_int(ngrids))\n    else:\n        aow = numpy.einsum('nip,np->pi', ao, wv)\n    return aow\n\ndef _contract_rho(bra, ket):\n    #:rho  = numpy.einsum('pi,pi->p', bra.real, ket.real)\n    #:rho += numpy.einsum('pi,pi->p', bra.imag, ket.imag)\n    bra = bra.T\n    ket = ket.T\n    nao, ngrids = bra.shape\n    rho = numpy.empty(ngrids)\n\n    if not (bra.flags.c_contiguous and ket.flags.c_contiguous):\n        rho  = numpy.einsum('ip,ip->p', bra.real, ket.real)\n        rho += numpy.einsum('ip,ip->p', bra.imag, ket.imag)\n    elif bra.dtype == numpy.double and ket.dtype == numpy.double:\n        libdft.VXC_dcontract_rho(rho.ctypes.data_as(ctypes.c_void_p),\n                                 bra.ctypes.data_as(ctypes.c_void_p),\n                                 ket.ctypes.data_as(ctypes.c_void_p),\n                                 ctypes.c_int(nao), ctypes.c_int(ngrids))\n    elif bra.dtype == numpy.complex128 and ket.dtype == numpy.complex128:\n        libdft.VXC_zcontract_rho(rho.ctypes.data_as(ctypes.c_void_p),\n                                 bra.ctypes.data_as(ctypes.c_void_p),\n                                 ket.ctypes.data_as(ctypes.c_void_p),\n                                 ctypes.c_int(nao), ctypes.c_int(ngrids))\n    else:\n        rho  = numpy.einsum('ip,ip->p', bra.real, ket.real)\n        rho += numpy.einsum('ip,ip->p', bra.imag, ket.imag)\n    return rho\n\ndef nr_vxc(mol, grids, xc_code, dms, spin=0, relativity=0, hermi=0,\n           max_memory=2000, verbose=None):\n    '''\n    Evaluate RKS/UKS XC functional and potential matrix on given meshgrids\n    for a set of density matrices.  See :func:`nr_rks` and :func:`nr_uks`\n    for more details.\n\n    Args:\n        mol : an instance of :class:`Mole`\n\n        grids : an instance of :class:`Grids`\n            grids.coords and grids.weights are needed for coordinates and weights of meshgrids.\n        xc_code : str\n            XC functional description.\n            See :func:`parse_xc` of pyscf/dft/libxc.py for more details.\n        dms : 2D array or a list of 2D arrays\n            Density matrix or multiple density matrices\n\n    Kwargs:\n        hermi : int\n            Input density matrices symmetric or not\n        max_memory : int or float\n            The maximum size of cache to use (in MB).\n\n    Returns:\n        nelec, excsum, vmat.\n        nelec is the number of electrons generated by numerical integration.\n        excsum is the XC functional value.  vmat is the XC potential matrix in\n        2D array of shape (nao,nao) where nao is the number of AO functions.\n\n    Examples:\n\n    >>> from pyscf import gto, dft\n    >>> mol = gto.M(atom='H 0 0 0; H 0 0 1.1')\n    >>> grids = dft.gen_grid.Grids(mol)\n    >>> grids.coords = numpy.random.random((100,3))  # 100 random points\n    >>> grids.weights = numpy.random.random(100)\n    >>> nao = mol.nao_nr()\n    >>> dm = numpy.random.random((2,nao,nao))\n    >>> nelec, exc, vxc = dft.numint.nr_vxc(mol, grids, 'lda,vwn', dm, spin=1)\n    '''\n    ni = NumInt()\n    return ni.nr_vxc(mol, grids, xc_code, dms, spin, relativity,\n                     hermi, max_memory, verbose)\n\ndef nr_rks(ni, mol, grids, xc_code, dms, relativity=0, hermi=0,\n           max_memory=2000, verbose=None):\n    '''Calculate RKS XC functional and potential matrix on given meshgrids\n    for a set of density matrices\n\n    Args:\n        ni : an instance of :class:`NumInt`\n\n        mol : an instance of :class:`Mole`\n\n        grids : an instance of :class:`Grids`\n            grids.coords and grids.weights are needed for coordinates and weights of meshgrids.\n        xc_code : str\n            XC functional description.\n            See :func:`parse_xc` of pyscf/dft/libxc.py for more details.\n        dms : 2D array or a list of 2D arrays\n            Density matrix or multiple density matrices\n\n    Kwargs:\n        hermi : int\n            Input density matrices symmetric or not\n        max_memory : int or float\n            The maximum size of cache to use (in MB).\n\n    Returns:\n        nelec, excsum, vmat.\n        nelec is the number of electrons generated by numerical integration.\n        excsum is the XC functional value.  vmat is the XC potential matrix in\n        2D array of shape (nao,nao) where nao is the number of AO functions.\n\n    Examples:\n\n    >>> from pyscf import gto, dft\n    >>> mol = gto.M(atom='H 0 0 0; H 0 0 1.1')\n    >>> grids = dft.gen_grid.Grids(mol)\n    >>> grids.coords = numpy.random.random((100,3))  # 100 random points\n    >>> grids.weights = numpy.random.random(100)\n    >>> nao = mol.nao_nr()\n    >>> dm = numpy.random.random((nao,nao))\n    >>> ni = dft.numint.NumInt()\n    >>> nelec, exc, vxc = ni.nr_rks(mol, grids, 'lda,vwn', dm)\n    '''\n    xctype = ni._xc_type(xc_code)\n    make_rho, nset, nao = ni._gen_rho_evaluator(mol, dms, hermi)\n\n    shls_slice = (0, mol.nbas)\n    ao_loc = mol.ao_loc_nr()\n\n    nelec = numpy.zeros(nset)\n    excsum = numpy.zeros(nset)\n    if isinstance(dms, numpy.ndarray):\n        vmat = numpy.zeros((nset,nao,nao), dtype=dms.dtype)\n    else:\n        vmat = numpy.zeros((nset,nao,nao), dtype=numpy.result_type(*dms))\n    aow = None\n    if xctype == 'LDA':\n        ao_deriv = 0\n        for ao, mask, weight, coords \\\n                in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):\n            aow = numpy.ndarray(ao.shape, order='F', buffer=aow)\n            for idm in range(nset):\n                rho = make_rho(idm, ao, mask, 'LDA')\n                exc, vxc = ni.eval_xc(xc_code, rho, 0, relativity, 1,\n                                      verbose=verbose)[:2]\n                vrho = vxc[0]\n                den = rho * weight\n                nelec[idm] += den.sum()\n                excsum[idm] += numpy.dot(den, exc)\n                # *.5 because vmat + vmat.T\n                #:aow = numpy.einsum('pi,p->pi', ao, .5*weight*vrho, out=aow)\n                aow = _scale_ao(ao, .5*weight*vrho, out=aow)\n                vmat[idm] += _dot_ao_ao(mol, ao, aow, mask, shls_slice, ao_loc)\n                rho = exc = vxc = vrho = None\n    elif xctype == 'GGA':\n        ao_deriv = 1\n        for ao, mask, weight, coords \\\n                in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):\n            ngrid = weight.size\n            aow = numpy.ndarray(ao[0].shape, order='F', buffer=aow)\n            for idm in range(nset):\n                rho = make_rho(idm, ao, mask, 'GGA')\n                exc, vxc = ni.eval_xc(xc_code, rho, 0, relativity, 1,\n                                      verbose=verbose)[:2]\n                den = rho[0] * weight\n                nelec[idm] += den.sum()\n                excsum[idm] += numpy.dot(den, exc)\n# ref eval_mat function\n                wv = _rks_gga_wv0(rho, vxc, weight)\n                #:aow = numpy.einsum('npi,np->pi', ao, wv, out=aow)\n                aow = _scale_ao(ao, wv, out=aow)\n                vmat[idm] += _dot_ao_ao(mol, ao[0], aow, mask, shls_slice, ao_loc)\n                rho = exc = vxc = wv = None\n    elif xctype == 'NLC':\n        nlc_pars = ni.nlc_coeff(xc_code[:-6])\n        if nlc_pars == [0,0]:\n            raise NotImplementedError('VV10 cannot be used with %s. '\n                                      'The supported functionals are %s' %\n                                      (xc_code[:-6], ni.libxc.VV10_XC))\n        ao_deriv = 1\n        vvrho=numpy.empty([nset,4,0])\n        vvweight=numpy.empty([nset,0])\n        vvcoords=numpy.empty([nset,0,3])\n        for ao, mask, weight, coords \\\n                in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):\n            rhotmp = numpy.empty([0,4,weight.size])\n            weighttmp = numpy.empty([0,weight.size])\n            coordstmp = numpy.empty([0,weight.size,3])\n            for idm in range(nset):\n                rho = make_rho(idm, ao, mask, 'GGA')\n                rho = numpy.expand_dims(rho,axis=0)\n                rhotmp = numpy.concatenate((rhotmp,rho),axis=0)\n                weighttmp = numpy.concatenate((weighttmp,numpy.expand_dims(weight,axis=0)),axis=0)\n                coordstmp = numpy.concatenate((coordstmp,numpy.expand_dims(coords,axis=0)),axis=0)\n                rho = None\n            vvrho=numpy.concatenate((vvrho,rhotmp),axis=2)\n            vvweight=numpy.concatenate((vvweight,weighttmp),axis=1)\n            vvcoords=numpy.concatenate((vvcoords,coordstmp),axis=1)\n            rhotmp = weighttmp = coordstmp = None\n        for ao, mask, weight, coords \\\n                in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):\n            ngrid = weight.size\n            aow = numpy.ndarray(ao[0].shape, order='F', buffer=aow)\n            for idm in range(nset):\n                rho = make_rho(idm, ao, mask, 'GGA')\n                exc, vxc = _vv10nlc(rho,coords,vvrho[idm],vvweight[idm],vvcoords[idm],nlc_pars)\n                den = rho[0] * weight\n                nelec[idm] += den.sum()\n                excsum[idm] += numpy.dot(den, exc)\n# ref eval_mat function\n                wv = _rks_gga_wv0(rho, vxc, weight)\n                #:aow = numpy.einsum('npi,np->pi', ao, wv, out=aow)\n                aow = _scale_ao(ao, wv, out=aow)\n                vmat[idm] += _dot_ao_ao(mol, ao[0], aow, mask, shls_slice, ao_loc)\n                rho = exc = vxc = wv = None\n        vvrho = vvweight = vvcoords = None\n    elif xctype == 'MGGA':\n        if (any(x in xc_code.upper() for x in ('CC06', 'CS', 'BR89', 'MK00'))):\n            raise NotImplementedError('laplacian in meta-GGA method')\n        ao_deriv = 2\n        for ao, mask, weight, coords \\\n                in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):\n            ngrid = weight.size\n            aow = numpy.ndarray(ao[0].shape, order='F', buffer=aow)\n            for idm in range(nset):\n                rho = make_rho(idm, ao, mask, 'MGGA')\n                exc, vxc = ni.eval_xc(xc_code, rho, 0, relativity, 1,\n                                      verbose=verbose)[:2]\n                vrho, vsigma, vlapl, vtau = vxc[:4]\n                den = rho[0] * weight\n                nelec[idm] += den.sum()\n                excsum[idm] += numpy.dot(den, exc)\n\n                wv = _rks_gga_wv0(rho, vxc, weight)\n                #:aow = numpy.einsum('npi,np->pi', ao[:4], wv, out=aow)\n                aow = _scale_ao(ao[:4], wv, out=aow)\n                vmat[idm] += _dot_ao_ao(mol, ao[0], aow, mask, shls_slice, ao_loc)\n\n# FIXME: .5 * .5   First 0.5 for v+v.T symmetrization.\n# Second 0.5 is due to the Libxc convention tau = 1/2 \\nabla\\phi\\dot\\nabla\\phi\n                wv = (.5 * .5 * weight * vtau).reshape(-1,1)\n                vmat[idm] += _dot_ao_ao(mol, ao[1], wv*ao[1], mask, shls_slice, ao_loc)\n                vmat[idm] += _dot_ao_ao(mol, ao[2], wv*ao[2], mask, shls_slice, ao_loc)\n                vmat[idm] += _dot_ao_ao(mol, ao[3], wv*ao[3], mask, shls_slice, ao_loc)\n\n                rho = exc = vxc = vrho = vsigma = wv = None\n\n    for i in range(nset):\n        vmat[i] = vmat[i] + vmat[i].conj().T\n    if nset == 1:\n        nelec = nelec[0]\n        excsum = excsum[0]\n        vmat = vmat[0]\n    return nelec, excsum, vmat\n\ndef nr_uks(ni, mol, grids, xc_code, dms, relativity=0, hermi=0,\n           max_memory=2000, verbose=None):\n    '''Calculate UKS XC functional and potential matrix on given meshgrids\n    for a set of density matrices\n\n    Args:\n        mol : an instance of :class:`Mole`\n\n        grids : an instance of :class:`Grids`\n            grids.coords and grids.weights are needed for coordinates and weights of meshgrids.\n        xc_code : str\n            XC functional description.\n            See :func:`parse_xc` of pyscf/dft/libxc.py for more details.\n        dms : a list of 2D arrays\n            A list of density matrices, stored as (alpha,alpha,...,beta,beta,...)\n\n    Kwargs:\n        hermi : int\n            Input density matrices symmetric or not\n        max_memory : int or float\n            The maximum size of cache to use (in MB).\n\n    Returns:\n        nelec, excsum, vmat.\n        nelec is the number of (alpha,beta) electrons generated by numerical integration.\n        excsum is the XC functional value.\n        vmat is the XC potential matrix for (alpha,beta) spin.\n\n    Examples:\n\n    >>> from pyscf import gto, dft\n    >>> mol = gto.M(atom='H 0 0 0; H 0 0 1.1')\n    >>> grids = dft.gen_grid.Grids(mol)\n    >>> grids.coords = numpy.random.random((100,3))  # 100 random points\n    >>> grids.weights = numpy.random.random(100)\n    >>> nao = mol.nao_nr()\n    >>> dm = numpy.random.random((2,nao,nao))\n    >>> ni = dft.numint.NumInt()\n    >>> nelec, exc, vxc = ni.nr_uks(mol, grids, 'lda,vwn', dm)\n    '''\n    xctype = ni._xc_type(xc_code)\n    if xctype == 'NLC':\n        dms_sf = dms[0] + dms[1]\n        nelec, excsum, vmat = nr_rks(ni, mol, grids, xc_code, dms_sf, relativity, hermi,\n                                     max_memory, verbose)\n        return [nelec,nelec], excsum, numpy.asarray([vmat,vmat])\n\n    shls_slice = (0, mol.nbas)\n    ao_loc = mol.ao_loc_nr()\n\n    dma, dmb = _format_uks_dm(dms)\n    nao = dma.shape[-1]\n    make_rhoa, nset = ni._gen_rho_evaluator(mol, dma, hermi)[:2]\n    make_rhob       = ni._gen_rho_evaluator(mol, dmb, hermi)[0]\n\n    nelec = numpy.zeros((2,nset))\n    excsum = numpy.zeros(nset)\n    vmat = numpy.zeros((2,nset,nao,nao), dtype=numpy.result_type(dma, dmb))\n    aow = None\n    if xctype == 'LDA':\n        ao_deriv = 0\n        for ao, mask, weight, coords \\\n                in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):\n            aow = numpy.ndarray(ao.shape, order='F', buffer=aow)\n            for idm in range(nset):\n                rho_a = make_rhoa(idm, ao, mask, xctype)\n                rho_b = make_rhob(idm, ao, mask, xctype)\n                exc, vxc = ni.eval_xc(xc_code, (rho_a, rho_b),\n                                      1, relativity, 1, verbose=verbose)[:2]\n                vrho = vxc[0]\n                den = rho_a * weight\n                nelec[0,idm] += den.sum()\n                excsum[idm] += numpy.dot(den, exc)\n                den = rho_b * weight\n                nelec[1,idm] += den.sum()\n                excsum[idm] += numpy.dot(den, exc)\n\n                # *.5 due to +c.c. in the end\n                #:aow = numpy.einsum('pi,p->pi', ao, .5*weight*vrho[:,0], out=aow)\n                aow = _scale_ao(ao, .5*weight*vrho[:,0], out=aow)\n                vmat[0,idm] += _dot_ao_ao(mol, ao, aow, mask, shls_slice, ao_loc)\n                #:aow = numpy.einsum('pi,p->pi', ao, .5*weight*vrho[:,1], out=aow)\n                aow = _scale_ao(ao, .5*weight*vrho[:,1], out=aow)\n                vmat[1,idm] += _dot_ao_ao(mol, ao, aow, mask, shls_slice, ao_loc)\n                rho_a = rho_b = exc = vxc = vrho = None\n    elif xctype == 'GGA':\n        ao_deriv = 1\n        for ao, mask, weight, coords \\\n                in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):\n            ngrid = weight.size\n            aow = numpy.ndarray(ao[0].shape, order='F', buffer=aow)\n            for idm in range(nset):\n                rho_a = make_rhoa(idm, ao, mask, xctype)\n                rho_b = make_rhob(idm, ao, mask, xctype)\n                exc, vxc = ni.eval_xc(xc_code, (rho_a, rho_b),\n                                      1, relativity, 1, verbose=verbose)[:2]\n                den = rho_a[0]*weight\n                nelec[0,idm] += den.sum()\n                excsum[idm] += numpy.dot(den, exc)\n                den = rho_b[0]*weight\n                nelec[1,idm] += den.sum()\n                excsum[idm] += numpy.dot(den, exc)\n\n                wva, wvb = _uks_gga_wv0((rho_a,rho_b), vxc, weight)\n                #:aow = numpy.einsum('npi,np->pi', ao, wva, out=aow)\n                aow = _scale_ao(ao, wva, out=aow)\n                vmat[0,idm] += _dot_ao_ao(mol, ao[0], aow, mask, shls_slice, ao_loc)\n                #:aow = numpy.einsum('npi,np->pi', ao, wvb, out=aow)\n                aow = _scale_ao(ao, wvb, out=aow)\n                vmat[1,idm] += _dot_ao_ao(mol, ao[0], aow, mask, shls_slice, ao_loc)\n                rho_a = rho_b = exc = vxc = wva = wvb = None\n    elif xctype == 'MGGA':\n        if (any(x in xc_code.upper() for x in ('CC06', 'CS', 'BR89', 'MK00'))):\n            raise NotImplementedError('laplacian in meta-GGA method')\n        ao_deriv = 2\n        for ao, mask, weight, coords \\\n                in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):\n            ngrid = weight.size\n            aow = numpy.ndarray(ao[0].shape, order='F', buffer=aow)\n            for idm in range(nset):\n                rho_a = make_rhoa(idm, ao, mask, xctype)\n                rho_b = make_rhob(idm, ao, mask, xctype)\n                exc, vxc = ni.eval_xc(xc_code, (rho_a, rho_b),\n                                      1, relativity, 1, verbose=verbose)[:2]\n                vrho, vsigma, vlapl, vtau = vxc[:4]\n                den = rho_a[0]*weight\n                nelec[0,idm] += den.sum()\n                excsum[idm] += numpy.dot(den, exc)\n                den = rho_b[0]*weight\n                nelec[1,idm] += den.sum()\n                excsum[idm] += numpy.dot(den, exc)\n\n                wva, wvb = _uks_gga_wv0((rho_a,rho_b), vxc, weight)\n                #:aow = numpy.einsum('npi,np->pi', ao[:4], wva, out=aow)\n                aow = _scale_ao(ao[:4], wva, out=aow)\n                vmat[0,idm] += _dot_ao_ao(mol, ao[0], aow, mask, shls_slice, ao_loc)\n                #:aow = numpy.einsum('npi,np->pi', ao[:4], wvb, out=aow)\n                aow = _scale_ao(ao[:4], wvb, out=aow)\n                vmat[1,idm] += _dot_ao_ao(mol, ao[0], aow, mask, shls_slice, ao_loc)\n\n# FIXME: .5 * .5   First 0.5 for v+v.T symmetrization.\n# Second 0.5 is due to the Libxc convention tau = 1/2 \\nabla\\phi\\dot\\nabla\\phi\n                wv = (.25 * weight * vtau[:,0]).reshape(-1,1)\n                vmat[0,idm] += _dot_ao_ao(mol, ao[1], wv*ao[1], mask, shls_slice, ao_loc)\n                vmat[0,idm] += _dot_ao_ao(mol, ao[2], wv*ao[2], mask, shls_slice, ao_loc)\n                vmat[0,idm] += _dot_ao_ao(mol, ao[3], wv*ao[3], mask, shls_slice, ao_loc)\n                wv = (.25 * weight * vtau[:,1]).reshape(-1,1)\n                vmat[1,idm] += _dot_ao_ao(mol, ao[1], wv*ao[1], mask, shls_slice, ao_loc)\n                vmat[1,idm] += _dot_ao_ao(mol, ao[2], wv*ao[2], mask, shls_slice, ao_loc)\n                vmat[1,idm] += _dot_ao_ao(mol, ao[3], wv*ao[3], mask, shls_slice, ao_loc)\n                rho_a = rho_b = exc = vxc = vrho = vsigma = wva = wvb = None\n\n    for i in range(nset):\n        vmat[0,i] = vmat[0,i] + vmat[0,i].conj().T\n        vmat[1,i] = vmat[1,i] + vmat[1,i].conj().T\n    if isinstance(dma, numpy.ndarray) and dma.ndim == 2:\n        vmat = vmat[:,0]\n        nelec = nelec.reshape(2)\n        excsum = excsum[0]\n    return nelec, excsum, vmat\n\ndef _format_uks_dm(dms):\n    if isinstance(dms, numpy.ndarray) and dms.ndim == 2:  # RHF DM\n        dma = dmb = dms * .5\n    else:\n        dma, dmb = dms\n    if getattr(dms, 'mo_coeff', None) is not None:\n        mo_coeff = dms.mo_coeff\n        mo_occ = dms.mo_occ\n        if mo_coeff[0].ndim < dma.ndim: # handle ROKS\n            mo_occa = numpy.array(mo_occ> 0, dtype=numpy.double)\n            mo_occb = numpy.array(mo_occ==2, dtype=numpy.double)\n            dma = lib.tag_array(dma, mo_coeff=mo_coeff, mo_occ=mo_occa)\n            dmb = lib.tag_array(dmb, mo_coeff=mo_coeff, mo_occ=mo_occb)\n        else:\n            dma = lib.tag_array(dma, mo_coeff=mo_coeff[0], mo_occ=mo_occ[0])\n            dmb = lib.tag_array(dmb, mo_coeff=mo_coeff[1], mo_occ=mo_occ[1])\n    return dma, dmb\n\nnr_rks_vxc = nr_rks\nnr_uks_vxc = nr_uks\n\ndef nr_rks_fxc(ni, mol, grids, xc_code, dm0, dms, relativity=0, hermi=0,\n               rho0=None, vxc=None, fxc=None, max_memory=2000, verbose=None):\n    '''Contract RKS XC (singlet hessian) kernel matrix with given density matrices\n\n    Args:\n        ni : an instance of :class:`NumInt`\n\n        mol : an instance of :class:`Mole`\n\n        grids : an instance of :class:`Grids`\n            grids.coords and grids.weights are needed for coordinates and weights of meshgrids.\n        xc_code : str\n            XC functional description.\n            See :func:`parse_xc` of pyscf/dft/libxc.py for more details.\n        dms : 2D array a list of 2D arrays\n            Density matrix or multiple density matrices\n\n    Kwargs:\n        hermi : int\n            Input density matrices symmetric or not\n        max_memory : int or float\n            The maximum size of cache to use (in MB).\n        rho0 : float array\n            Zero-order density (and density derivative for GGA).  Giving kwargs rho0,\n            vxc and fxc to improve better performance.\n        vxc : float array\n            First order XC derivatives\n        fxc : float array\n            Second order XC derivatives\n\n    Returns:\n        nelec, excsum, vmat.\n        nelec is the number of electrons generated by numerical integration.\n        excsum is the XC functional value.  vmat is the XC potential matrix in\n        2D array of shape (nao,nao) where nao is the number of AO functions.\n\n    Examples:\n\n    '''\n    xctype = ni._xc_type(xc_code)\n\n    make_rho, nset, nao = ni._gen_rho_evaluator(mol, dms, hermi)\n    if ((xctype == 'LDA' and fxc is None) or\n        (xctype == 'GGA' and rho0 is None)):\n        make_rho0 = ni._gen_rho_evaluator(mol, dm0, 1)[0]\n\n    shls_slice = (0, mol.nbas)\n    ao_loc = mol.ao_loc_nr()\n\n    if isinstance(dms, numpy.ndarray):\n        vmat = numpy.zeros((nset,nao,nao), dtype=dms.dtype)\n    else:\n        vmat = numpy.zeros((nset,nao,nao), dtype=numpy.result_type(*dms))\n    aow = None\n    if xctype == 'LDA':\n        ao_deriv = 0\n        ip = 0\n        for ao, mask, weight, coords \\\n                in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):\n            ngrid = weight.size\n            aow = numpy.ndarray(ao.shape, order='F', buffer=aow)\n            if fxc is None:\n                rho = make_rho0(0, ao, mask, 'LDA')\n                fxc0 = ni.eval_xc(xc_code, rho, 0, relativity, 2,\n                                  verbose=verbose)[2]\n                frr = fxc0[0]\n            else:\n                frr = fxc[0][ip:ip+ngrid]\n                ip += ngrid\n\n            for i in range(nset):\n                rho1 = make_rho(i, ao, mask, 'LDA')\n                #:aow = numpy.einsum('pi,p->pi', ao, weight*frr*rho1, out=aow)\n                aow = _scale_ao(ao, weight*frr*rho1, out=aow)\n                vmat[i] += _dot_ao_ao(mol, aow, ao, mask, shls_slice, ao_loc)\n                rho1 = None\n\n    elif xctype == 'GGA':\n        ao_deriv = 1\n        ip = 0\n        for ao, mask, weight, coords \\\n                in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):\n            ngrid = weight.size\n            aow = numpy.ndarray(ao[0].shape, order='F', buffer=aow)\n            if rho0 is None:\n                rho = make_rho0(0, ao, mask, 'GGA')\n            else:\n                rho = numpy.asarray(rho0[:,ip:ip+ngrid], order='C')\n            if vxc is None or fxc is None:\n                vxc0, fxc0 = ni.eval_xc(xc_code, rho, 0, relativity, 2,\n                                        verbose=verbose)[1:3]\n            else:\n                vxc0 = (None, vxc[1][ip:ip+ngrid])\n                fxc0 = (fxc[0][ip:ip+ngrid], fxc[1][ip:ip+ngrid], fxc[2][ip:ip+ngrid])\n                ip += ngrid\n\n            for i in range(nset):\n                rho1 = make_rho(i, ao, mask, 'GGA')\n                wv = _rks_gga_wv1(rho, rho1, vxc0, fxc0, weight)\n                #:aow = numpy.einsum('npi,np->pi', ao, wv, out=aow)\n                aow = _scale_ao(ao, wv, out=aow)\n                vmat[i] += _dot_ao_ao(mol, aow, ao[0], mask, shls_slice, ao_loc)\n                rho1 = sigma1 = None\n\n        for i in range(nset):  # for (\\nabla\\mu) \\nu + \\mu (\\nabla\\nu)\n            vmat[i] = vmat[i] + vmat[i].T.conj()\n\n    elif xctype == 'NLC':\n        raise NotImplementedError('NLC')\n    elif xctype == 'MGGA':\n        raise NotImplementedError('meta-GGA')\n\n    if isinstance(dms, numpy.ndarray) and dms.ndim == 2:\n        vmat = vmat[0]\n    return vmat\n\ndef nr_rks_fxc_st(ni, mol, grids, xc_code, dm0, dms_alpha, relativity=0, singlet=True,\n                  rho0=None, vxc=None, fxc=None, max_memory=2000, verbose=None):\n    '''Associated to singlet or triplet Hessian\n    Note the difference to nr_rks_fxc, dms_alpha is the response density\n    matrices of alpha spin, alpha+/-beta DM is applied due to singlet/triplet\n    coupling\n\n    Ref. CPL, 256, 454\n    '''\n    xctype = ni._xc_type(xc_code)\n\n    make_rho, nset, nao = ni._gen_rho_evaluator(mol, dms_alpha, hermi=0)\n    if ((xctype == 'LDA' and fxc is None) or\n        (xctype == 'GGA' and rho0 is None)):\n        make_rho0 = ni._gen_rho_evaluator(mol, dm0, hermi=1)[0]\n\n    shls_slice = (0, mol.nbas)\n    ao_loc = mol.ao_loc_nr()\n\n    if isinstance(dms_alpha, numpy.ndarray):\n        vmat = numpy.zeros((nset,nao,nao), dtype=dms_alpha.dtype)\n    else:\n        vmat = numpy.zeros((nset,nao,nao), dtype=numpy.result_type(*dms_alpha))\n    aow = None\n    if xctype == 'LDA':\n        ao_deriv = 0\n        ip = 0\n        for ao, mask, weight, coords \\\n                in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):\n            ngrid = weight.size\n            aow = numpy.ndarray(ao.shape, order='F', buffer=aow)\n            if fxc is None:\n                rho = make_rho0(0, ao, mask, 'LDA')\n                rho *= .5  # alpha density\n                fxc0 = ni.eval_xc(xc_code, (rho,rho), 1, deriv=2)[2]\n                u_u, u_d, d_d = fxc0[0].T\n            else:\n                if fxc[0].ndim == 1:\n                    raise RuntimeError('cached (rho, vxc, fxc) need to be '\n                                       'generated by cache_xc_kernel with flag spin=1')\n                u_u, u_d, d_d = fxc[0][ip:ip+ngrid].T\n                ip += ngrid\n            if singlet:\n                frho = u_u + u_d\n                if 0:\n                    rho = ni.eval_rho2(mol, ao, mo_coeff, mo_occ, mask, 'LDA')\n                    fxc_test = ni.eval_xc(xc_code, rho, 0, deriv=2)[2]\n                    assert(numpy.linalg.norm(fxc_test[0]*2-frho) < 1e-4)\n            else:\n                frho = u_u - u_d\n\n            for i in range(nset):\n                rho1 = make_rho(i, ao, mask, 'LDA')\n                #:aow = numpy.einsum('pi,p->pi', ao, weight*frho*rho1, out=aow)\n                aow = _scale_ao(ao, weight*frho*rho1, out=aow)\n                vmat[i] += _dot_ao_ao(mol, aow, ao, mask, shls_slice, ao_loc)\n                rho1 = None\n\n    elif xctype == 'GGA':\n        ao_deriv = 1\n        ip = 0\n        for ao, mask, weight, coords \\\n                in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):\n            ngrid = weight.size\n            aow = numpy.ndarray(ao[0].shape, order='F', buffer=aow)\n            if vxc is None or fxc is None:\n                rho = make_rho0(0, ao, mask, 'GGA')\n                rho *= .5  # alpha density\n                vxc0, fxc0 = ni.eval_xc(xc_code, (rho,rho), 1, deriv=2)[1:3]\n\n                vsigma = vxc0[1].T\n                u_u, u_d, d_d = fxc0[0].T  # v2rho2\n                u_uu, u_ud, u_dd, d_uu, d_ud, d_dd = fxc0[1].T  # v2rhosigma\n                uu_uu, uu_ud, uu_dd, ud_ud, ud_dd, dd_dd = fxc0[2].T  # v2sigma2\n            else:\n                if rho0[0].ndim == 1:\n                    raise RuntimeError('cached (rho, vxc, fxc) need to be '\n                                       'generated by cache_xc_kernel with flag spin=1')\n                rho = rho0[0][:,ip:ip+ngrid]\n                vsigma = vxc[1][ip:ip+ngrid].T\n                u_u, u_d, d_d = fxc[0][ip:ip+ngrid].T  # v2rho2\n                u_uu, u_ud, u_dd, d_uu, d_ud, d_dd = fxc[1][ip:ip+ngrid].T  # v2rhosigma\n                uu_uu, uu_ud, uu_dd, ud_ud, ud_dd, dd_dd = fxc[2][ip:ip+ngrid].T  # v2sigma2\n                ip += ngrid\n\n            # Factorization differs to CPL, 256, 454, to use _rks_gga_wv1 function\n            if singlet:\n                fgamma = vsigma[0] + vsigma[1] * .5\n                frho = u_u + u_d\n                fgg = uu_uu + .5*ud_ud + 2*uu_ud + uu_dd\n                frhogamma = u_uu + u_dd + u_ud\n            else:\n                fgamma = vsigma[0] - vsigma[1] * .5\n                frho = u_u - u_d\n                fgg = uu_uu - uu_dd\n                frhogamma = u_uu - u_dd\n\n            for i in range(nset):\n                # rho1[0 ] = |b><j| z_{bj}\n                # rho1[1:] = \\nabla(|b><j|) z_{bj}\n                rho1 = make_rho(i, ao, mask, 'GGA')\n                wv = _rks_gga_wv1(rho, rho1, (None,fgamma), (frho,frhogamma,fgg), weight)\n                #:aow = numpy.einsum('npi,np->pi', ao, wv, out=aow)\n                aow = _scale_ao(ao, wv, out=aow)\n                vmat[i] += _dot_ao_ao(mol, aow, ao[0], mask, shls_slice, ao_loc)\n                rho1 = sigma1 = None\n\n        for i in range(nset):  # for (\\nabla\\mu) \\nu + \\mu (\\nabla\\nu)\n            vmat[i] = vmat[i] + vmat[i].T.conj()\n\n    elif xctype == 'NLC':\n        raise NotImplementedError('NLC')\n    elif xctype == 'MGGA':\n        raise NotImplementedError('meta-GGA')\n\n    if isinstance(dms_alpha, numpy.ndarray) and dms_alpha.ndim == 2:\n        vmat = vmat[0]\n    return vmat\n\ndef _rks_gga_wv0(rho, vxc, weight):\n    vrho, vgamma = vxc[:2]\n    ngrid = vrho.size\n    wv = numpy.empty((4,ngrid))\n    wv[0]  = weight * vrho\n    wv[1:] = (weight * vgamma * 2) * rho[1:4]\n    wv[0] *= .5  # v+v.T should be applied in the caller\n    return wv\n\ndef _rks_gga_wv1(rho0, rho1, vxc, fxc, weight):\n    vgamma = vxc[1]\n    frho, frhogamma, fgg = fxc[:3]\n    # sigma1 ~ \\nabla(\\rho_\\alpha+\\rho_\\beta) dot \\nabla(|b><j|) z_{bj}\n    sigma1 = numpy.einsum('xi,xi->i', rho0[1:4], rho1[1:4])\n    ngrid = vgamma.size\n    wv = numpy.empty((4,ngrid))\n    wv[0]  = frho * rho1[0]\n    wv[0] += frhogamma * sigma1 * 2\n    wv[1:] = (fgg * sigma1 * 4 + frhogamma * rho1[0] * 2) * rho0[1:4]\n    wv[1:]+= vgamma * rho1[1:4] * 2\n    wv *= weight\n    wv[0] *= .5  # v+v.T should be applied in the caller\n    return wv\n\ndef _rks_gga_wv2(rho0, rho1, fxc, kxc, weight):\n    frr, frg, fgg = fxc[:3]\n    frrr, frrg, frgg, fggg = kxc\n    sigma1 = numpy.einsum('xi,xi->i', rho0[1:], rho1[1:])\n    r1r1 = rho1[0]**2\n    s1s1 = sigma1**2\n    r1s1 = rho1[0] * sigma1\n    sigma2 = numpy.einsum('xi,xi->i', rho1[1:], rho1[1:])\n    ngrid = frrr.size\n    wv = numpy.empty((4,ngrid))\n    wv[0]  = frrr * r1r1\n    wv[0] += 4 * frrg * r1s1\n    wv[0] += 4 * frgg * s1s1\n    wv[0] += 2 * frg * sigma2\n    wv[1:]  = 2 * frrg * r1r1 * rho0[1:]\n    wv[1:] += 8 * frgg * r1s1 * rho0[1:]\n    wv[1:] += 4 * frg * rho1[0] * rho1[1:]\n    wv[1:] += 4 * fgg * sigma2 * rho0[1:]\n    wv[1:] += 8 * fgg * sigma1 * rho1[1:]\n    wv[1:] += 8 * fggg * s1s1 * rho0[1:]\n    wv *= weight\n    wv[0]*=.5  # v+v.T should be applied in the caller\n    return wv\n\ndef nr_uks_fxc(ni, mol, grids, xc_code, dm0, dms, relativity=0, hermi=0,\n               rho0=None, vxc=None, fxc=None, max_memory=2000, verbose=None):\n    '''Contract UKS XC kernel matrix with given density matrices\n\n    Args:\n        ni : an instance of :class:`NumInt`\n\n        mol : an instance of :class:`Mole`\n\n        grids : an instance of :class:`Grids`\n            grids.coords and grids.weights are needed for coordinates and weights of meshgrids.\n        xc_code : str\n            XC functional description.\n            See :func:`parse_xc` of pyscf/dft/libxc.py for more details.\n        dms : 2D array a list of 2D arrays\n            Density matrix or multiple density matrices\n\n    Kwargs:\n        hermi : int\n            Input density matrices symmetric or not\n        max_memory : int or float\n            The maximum size of cache to use (in MB).\n        rho0 : float array\n            Zero-order density (and density derivative for GGA).  Giving kwargs rho0,\n            vxc and fxc to improve better performance.\n        vxc : float array\n            First order XC derivatives\n        fxc : float array\n            Second order XC derivatives\n\n    Returns:\n        nelec, excsum, vmat.\n        nelec is the number of electrons generated by numerical integration.\n        excsum is the XC functional value.  vmat is the XC potential matrix in\n        2D array of shape (nao,nao) where nao is the number of AO functions.\n\n    Examples:\n\n    '''\n    xctype = ni._xc_type(xc_code)\n\n    dma, dmb = _format_uks_dm(dms)\n    nao = dms.shape[-1]\n    make_rhoa, nset = ni._gen_rho_evaluator(mol, dma, hermi)[:2]\n    make_rhob       = ni._gen_rho_evaluator(mol, dmb, hermi)[0]\n\n    if ((xctype == 'LDA' and fxc is None) or\n        (xctype == 'GGA' and rho0 is None)):\n        make_rho0 = ni._gen_rho_evaluator(mol, _format_uks_dm(dm0), 1)[0]\n\n    shls_slice = (0, mol.nbas)\n    ao_loc = mol.ao_loc_nr()\n\n    vmat = numpy.zeros((2,nset,nao,nao), dtype=numpy.result_type(dma, dmb))\n    aow = None\n    if xctype == 'LDA':\n        ao_deriv = 0\n        ip = 0\n        for ao, mask, weight, coords \\\n                in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):\n            ngrid = weight.size\n            aow = numpy.ndarray(ao.shape, order='F', buffer=aow)\n            if fxc is None:\n                rho0a = make_rho0(0, ao, mask, xctype)\n                rho0b = make_rho0(1, ao, mask, xctype)\n                fxc0 = ni.eval_xc(xc_code, (rho0a,rho0b), 1, relativity, 2,\n                                  verbose=verbose)[2]\n                u_u, u_d, d_d = fxc0[0].T\n            else:\n                u_u, u_d, d_d = fxc[0][ip:ip+ngrid].T\n                ip += ngrid\n\n            for i in range(nset):\n                rho1a = make_rhoa(i, ao, mask, xctype)\n                rho1b = make_rhob(i, ao, mask, xctype)\n                wv = u_u * rho1a + u_d * rho1b\n                wv *= weight\n                #:aow = numpy.einsum('pi,p->pi', ao, wv, out=aow)\n                aow = _scale_ao(ao, wv, out=aow)\n                vmat[0,i] += _dot_ao_ao(mol, aow, ao, mask, shls_slice, ao_loc)\n                wv = u_d * rho1a + d_d * rho1b\n                wv *= weight\n                #:aow = numpy.einsum('pi,p->pi', ao, wv, out=aow)\n                aow = _scale_ao(ao, wv, out=aow)\n                vmat[1,i] += _dot_ao_ao(mol, aow, ao, mask, shls_slice, ao_loc)\n\n    elif xctype == 'GGA':\n        ao_deriv = 1\n        ip = 0\n        for ao, mask, weight, coords \\\n                in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):\n            ngrid = weight.size\n            aow = numpy.ndarray(ao[0].shape, order='F', buffer=aow)\n            if rho0 is None:\n                rho0a = make_rho0(0, ao, mask, xctype)\n                rho0b = make_rho0(1, ao, mask, xctype)\n            else:\n                rho0a = rho0[0][:,ip:ip+ngrid]\n                rho0b = rho0[1][:,ip:ip+ngrid]\n            if vxc is None or fxc is None:\n                vxc0, fxc0 = ni.eval_xc(xc_code, (rho0a,rho0b), 1, relativity, 2,\n                                        verbose=verbose)[1:3]\n            else:\n                vxc0 = (None, vxc[1][ip:ip+ngrid])\n                fxc0 = (fxc[0][ip:ip+ngrid], fxc[1][ip:ip+ngrid], fxc[2][ip:ip+ngrid])\n                ip += ngrid\n\n            for i in range(nset):\n                rho1a = make_rhoa(i, ao, mask, xctype)\n                rho1b = make_rhob(i, ao, mask, xctype)\n                wva, wvb = _uks_gga_wv1((rho0a,rho0b), (rho1a,rho1b), vxc0, fxc0, weight)\n                #:aow = numpy.einsum('npi,np->pi', ao, wva, out=aow)\n                aow = _scale_ao(ao, wva, out=aow)\n                vmat[0,i] += _dot_ao_ao(mol, aow, ao[0], mask, shls_slice, ao_loc)\n                #:aow = numpy.einsum('npi,np->pi', ao, wvb, out=aow)\n                aow = _scale_ao(ao, wvb, out=aow)\n                vmat[1,i] += _dot_ao_ao(mol, aow, ao[0], mask, shls_slice, ao_loc)\n\n        for i in range(nset):  # for (\\nabla\\mu) \\nu + \\mu (\\nabla\\nu)\n            vmat[0,i] = vmat[0,i] + vmat[0,i].T.conj()\n            vmat[1,i] = vmat[1,i] + vmat[1,i].T.conj()\n\n    elif xctype == 'NLC':\n        raise NotImplementedError('NLC')\n    elif xctype == 'MGGA':\n        raise NotImplementedError('meta-GGA')\n\n    if isinstance(dma, numpy.ndarray) and dma.ndim == 2:\n        vmat = vmat[:,0]\n    return vmat\n\ndef _uks_gga_wv0(rho, vxc, weight):\n    rhoa, rhob = rho\n    vrho, vsigma = vxc[:2]\n    ngrid = vrho.shape[0]\n    wva = numpy.empty((4,ngrid))\n    wva[0]  = weight * vrho[:,0] * .5  # v+v.T should be applied in the caller\n    wva[1:] = rhoa[1:4] * (weight * vsigma[:,0] * 2)  # sigma_uu\n    wva[1:]+= rhob[1:4] * (weight * vsigma[:,1])      # sigma_ud\n    wvb = numpy.empty((4,ngrid))\n    wvb[0]  = weight * vrho[:,1] * .5  # v+v.T should be applied in the caller\n    wvb[1:] = rhob[1:4] * (weight * vsigma[:,2] * 2)  # sigma_dd\n    wvb[1:]+= rhoa[1:4] * (weight * vsigma[:,1])      # sigma_ud\n    return wva, wvb\n\ndef _uks_gga_wv1(rho0, rho1, vxc, fxc, weight):\n    uu, ud, dd = vxc[1].T\n    u_u, u_d, d_d = fxc[0].T\n    u_uu, u_ud, u_dd, d_uu, d_ud, d_dd = fxc[1].T\n    uu_uu, uu_ud, uu_dd, ud_ud, ud_dd, dd_dd = fxc[2].T\n    ngrid = uu.size\n\n    rho0a, rho0b = rho0\n    rho1a, rho1b = rho1\n    a0a1 = numpy.einsum('xi,xi->i', rho0a[1:4], rho1a[1:4])\n    a0b1 = numpy.einsum('xi,xi->i', rho0a[1:4], rho1b[1:4])\n    b0a1 = numpy.einsum('xi,xi->i', rho0b[1:4], rho1a[1:4])\n    b0b1 = numpy.einsum('xi,xi->i', rho0b[1:4], rho1b[1:4])\n\n    wva = numpy.empty((4,ngrid))\n    wvb = numpy.empty((4,ngrid))\n    # alpha = alpha-alpha * alpha\n    wva[0]  = u_u * rho1a[0]\n    wva[0] += u_uu * a0a1 * 2\n    wva[0] += u_ud * b0a1\n    wva[1:] = uu * rho1a[1:4] * 2\n    wva[1:]+= u_uu * rho1a[0] * rho0a[1:4] * 2\n    wva[1:]+= u_ud * rho1a[0] * rho0b[1:4]\n    wva[1:]+= uu_uu * a0a1 * rho0a[1:4] * 4\n    wva[1:]+= uu_ud * a0a1 * rho0b[1:4] * 2\n    wva[1:]+= uu_ud * b0a1 * rho0a[1:4] * 2\n    wva[1:]+= ud_ud * b0a1 * rho0b[1:4]\n\n    # alpha = alpha-beta  * beta\n    wva[0] += u_d * rho1b[0]\n    wva[0] += u_ud * a0b1\n    wva[0] += u_dd * b0b1 * 2\n    wva[1:]+= ud * rho1b[1:4]\n    wva[1:]+= d_uu * rho1b[0] * rho0a[1:4] * 2\n    wva[1:]+= d_ud * rho1b[0] * rho0b[1:4]\n    wva[1:]+= uu_ud * a0b1 * rho0a[1:4] * 2\n    wva[1:]+= ud_ud * a0b1 * rho0b[1:4]\n    wva[1:]+= uu_dd * b0b1 * rho0a[1:4] * 4\n    wva[1:]+= ud_dd * b0b1 * rho0b[1:4] * 2\n    wva *= weight\n    wva[0] *= .5  # v+v.T should be applied in the caller\n\n    # beta = beta-alpha * alpha\n    wvb[0]  = u_d * rho1a[0]\n    wvb[0] += d_ud * b0a1\n    wvb[0] += d_uu * a0a1 * 2\n    wvb[1:] = ud * rho1a[1:4]\n    wvb[1:]+= u_dd * rho1a[0] * rho0b[1:4] * 2\n    wvb[1:]+= u_ud * rho1a[0] * rho0a[1:4]\n    wvb[1:]+= ud_dd * b0a1 * rho0b[1:4] * 2\n    wvb[1:]+= ud_ud * b0a1 * rho0a[1:4]\n    wvb[1:]+= uu_dd * a0a1 * rho0b[1:4] * 4\n    wvb[1:]+= uu_ud * a0a1 * rho0a[1:4] * 2\n\n    # beta = beta-beta  * beta\n    wvb[0] += d_d * rho1b[0]\n    wvb[0] += d_dd * b0b1 * 2\n    wvb[0] += d_ud * a0b1\n    wvb[1:]+= dd * rho1b[1:4] * 2\n    wvb[1:]+= d_dd * rho1b[0] * rho0b[1:4] * 2\n    wvb[1:]+= d_ud * rho1b[0] * rho0a[1:4]\n    wvb[1:]+= dd_dd * b0b1 * rho0b[1:4] * 4\n    wvb[1:]+= ud_dd * b0b1 * rho0a[1:4] * 2\n    wvb[1:]+= ud_dd * a0b1 * rho0b[1:4] * 2\n    wvb[1:]+= ud_ud * a0b1 * rho0a[1:4]\n    wvb *= weight\n    wvb[0] *= .5  # v+v.T should be applied in the caller\n    return wva, wvb\n\ndef _uks_gga_wv2(rho0, rho1, fxc, kxc, weight):\n    u_u, u_d, d_d = fxc[0].T\n    u_uu, u_ud, u_dd, d_uu, d_ud, d_dd = fxc[1].T\n    uu_uu, uu_ud, uu_dd, ud_ud, ud_dd, dd_dd = fxc[2].T\n    u_u_u, u_u_d, u_d_d, d_d_d = kxc[0].T\n    u_u_uu, u_u_ud, u_u_dd, u_d_uu, u_d_ud, u_d_dd, d_d_uu, \\\n            d_d_ud, d_d_dd = kxc[1].T\n    u_uu_uu, u_uu_ud, u_uu_dd, u_ud_ud, u_ud_dd, u_dd_dd, d_uu_uu, d_uu_ud, \\\n            d_uu_dd, d_ud_ud, d_ud_dd, d_dd_dd = kxc[2].T\n    uu_uu_uu, uu_uu_ud, uu_uu_dd, uu_ud_ud, uu_ud_dd, uu_dd_dd, ud_ud_ud, \\\n            ud_ud_dd, ud_dd_dd, dd_dd_dd = kxc[3].T\n    ngrid = u_u.size\n\n    rho0a, rho0b = rho0\n    rho1a, rho1b = rho1\n    a0a1 = numpy.einsum('xi,xi->i', rho0a[1:4], rho1a[1:4])\n    a0b1 = numpy.einsum('xi,xi->i', rho0a[1:4], rho1b[1:4])\n    b0a1 = numpy.einsum('xi,xi->i', rho0b[1:4], rho1a[1:4])\n    b0b1 = numpy.einsum('xi,xi->i', rho0b[1:4], rho1b[1:4])\n    a1a1 = numpy.einsum('xi,xi->i', rho1a[1:4], rho1a[1:4])\n    a1b1 = numpy.einsum('xi,xi->i', rho1a[1:4], rho1b[1:4])\n    b1a1 = a1b1\n    b1b1 = numpy.einsum('xi,xi->i', rho1b[1:4], rho1b[1:4])\n    a0a1_a0a1 = numpy.einsum('i,i->i', a0a1, a0a1)\n    a0a1_a0b1 = numpy.einsum('i,i->i', a0a1, a0b1)\n    a0a1_b0a1 = numpy.einsum('i,i->i', a0a1, b0a1)\n    a0a1_b0b1 = numpy.einsum('i,i->i', a0a1, b0b1)\n    a0b1_a0a1 = a0a1_a0b1\n    a0b1_a0b1 = numpy.einsum('i,i->i', a0b1, a0b1)\n    a0b1_b0a1 = numpy.einsum('i,i->i', a0b1, b0a1)\n    a0b1_b0b1 = numpy.einsum('i,i->i', a0b1, b0b1)\n    b0a1_a0a1 = a0a1_b0a1\n    b0a1_a0b1 = a0b1_b0a1\n    b0a1_b0a1 = numpy.einsum('i,i->i', b0a1, b0a1)\n    b0a1_b0b1 = numpy.einsum('i,i->i', b0a1, b0b1)\n    b0b1_a0a1 = a0a1_b0b1\n    b0b1_a0b1 = a0b1_b0b1\n    b0b1_b0a1 = b0a1_b0b1\n    b0b1_b0b1 = numpy.einsum('i,i->i', b0b1, b0b1)\n\n    wva = numpy.zeros((4,ngrid))\n    wva[0] += numpy.einsum('i,i,i->i', u_u_u, rho1a[0], rho1a[0])\n    wva[0] += numpy.einsum('i,i,i->i', u_u_d, rho1a[0], rho1b[0]) * 2\n    wva[0] += numpy.einsum('i,i,i->i', u_d_d, rho1b[0], rho1b[0])\n    wva[0] += numpy.einsum('i,i->i', u_uu, a1a1) * 2\n    wva[0] += numpy.einsum('i,i->i', u_ud, a1b1) * 2\n    wva[0] += numpy.einsum('i,i->i', u_dd, b1b1) * 2\n    wva[1:] += numpy.einsum('i,i,xi->xi', u_uu, rho1a[0], rho1a[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,xi->xi', d_uu, rho1b[0], rho1a[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,xi->xi', u_ud, rho1a[0], rho1b[1:]) * 2\n    wva[1:] += numpy.einsum('i,i,xi->xi', d_ud, rho1b[0], rho1b[1:]) * 2\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_uu, a0a1, rho1a[1:]) * 8\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_ud, a0a1, rho1b[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_ud, a0b1, rho1a[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,xi->xi', ud_ud, a0b1, rho1b[1:]) * 2\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_ud, b0a1, rho1a[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_dd, b0b1, rho1a[1:]) * 8\n    wva[1:] += numpy.einsum('i,i,xi->xi', ud_ud, b0a1, rho1b[1:]) * 2\n    wva[1:] += numpy.einsum('i,i,xi->xi', ud_dd, b0b1, rho1b[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_uu, a1a1, rho0a[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_ud, a1b1, rho0a[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_dd, b1b1, rho0a[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_ud, a1a1, rho0b[1:]) * 2\n    wva[1:] += numpy.einsum('i,i,xi->xi', ud_ud, a1b1, rho0b[1:]) * 2\n    wva[1:] += numpy.einsum('i,i,xi->xi', ud_dd, b1b1, rho0b[1:]) * 2\n    wva[0] += numpy.einsum('i,i,i->i', u_u_uu, rho1a[0], a0a1) * 4\n    wva[0] += numpy.einsum('i,i,i->i', u_d_uu, rho1b[0], a0a1) * 4\n    wva[0] += numpy.einsum('i,i,i->i', u_u_ud, rho1a[0], a0b1) * 2\n    wva[0] += numpy.einsum('i,i,i->i', u_d_ud, rho1b[0], a0b1) * 2\n    wva[0] += numpy.einsum('i,i,i->i', u_u_ud, rho1a[0], b0a1) * 2\n    wva[0] += numpy.einsum('i,i,i->i', u_d_ud, rho1b[0], b0a1) * 2\n    wva[0] += numpy.einsum('i,i,i->i', u_u_dd, rho1a[0], b0b1) * 4\n    wva[0] += numpy.einsum('i,i,i->i', u_d_dd, rho1b[0], b0b1) * 4\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', u_u_uu, rho1a[0], rho1a[0], rho0a[1:]) * 2\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', u_d_uu, rho1a[0], rho1b[0], rho0a[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', d_d_uu, rho1b[0], rho1b[0], rho0a[1:]) * 2\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', u_u_ud, rho1a[0], rho1a[0], rho0a[1:])\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', u_d_ud, rho1a[0], rho1b[0], rho0a[1:]) * 2\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', d_d_ud, rho1b[0], rho1b[0], rho0a[1:])\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', u_uu_uu, rho1a[0], a0a1, rho0a[1:]) * 8\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', d_uu_uu, rho1b[0], a0a1, rho0a[1:]) * 8\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', u_uu_ud, rho1a[0], a0b1, rho0a[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', d_uu_ud, rho1b[0], a0b1, rho0a[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', u_uu_ud, rho1a[0], b0a1, rho0a[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', d_uu_ud, rho1b[0], b0a1, rho0a[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', u_uu_dd, rho1a[0], b0b1, rho0a[1:]) * 8\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', d_uu_dd, rho1b[0], b0b1, rho0a[1:]) * 8\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', u_uu_ud, rho1a[0], a0a1, rho0b[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', d_uu_ud, rho1b[0], a0a1, rho0b[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', u_ud_ud, rho1a[0], a0b1, rho0b[1:]) * 2\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', d_ud_ud, rho1b[0], a0b1, rho0b[1:]) * 2\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', u_ud_ud, rho1a[0], b0a1, rho0b[1:]) * 2\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', d_ud_ud, rho1b[0], b0a1, rho0b[1:]) * 2\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', u_ud_dd, rho1a[0], b0b1, rho0b[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,i,xi->xi', d_ud_dd, rho1b[0], b0b1, rho0b[1:]) * 4\n    wva[0] += numpy.einsum('i,i->i', u_uu_uu, a0a1_a0a1) * 4\n    wva[0] += numpy.einsum('i,i->i', u_uu_ud, a0a1_a0b1) * 2\n    wva[0] += numpy.einsum('i,i->i', u_uu_ud, a0b1_a0a1) * 2\n    wva[0] += numpy.einsum('i,i->i', u_ud_ud, a0b1_a0b1)\n    wva[0] += numpy.einsum('i,i->i', u_uu_ud, a0a1_b0a1) * 4\n    wva[0] += numpy.einsum('i,i->i', u_ud_ud, a0b1_b0a1) * 2\n    wva[0] += numpy.einsum('i,i->i', u_uu_dd, a0a1_b0b1) * 8\n    wva[0] += numpy.einsum('i,i->i', u_ud_dd, a0b1_b0b1) * 4\n    wva[0] += numpy.einsum('i,i->i', u_ud_ud, b0a1_b0a1)\n    wva[0] += numpy.einsum('i,i->i', u_ud_dd, b0a1_b0b1) * 2\n    wva[0] += numpy.einsum('i,i->i', u_ud_dd, b0b1_b0a1) * 2\n    wva[0] += numpy.einsum('i,i->i', u_dd_dd, b0b1_b0b1) * 4\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_uu_uu, a0a1_a0a1, rho0a[1:]) * 8\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_uu_ud, a0a1_a0b1, rho0a[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_uu_ud, a0b1_a0a1, rho0a[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_ud_ud, a0b1_a0b1, rho0a[1:]) * 2\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_uu_ud, a0a1_a0a1, rho0b[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_ud_ud, a0a1_a0b1, rho0b[1:]) * 2\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_ud_ud, a0b1_a0a1, rho0b[1:]) * 2\n    wva[1:] += numpy.einsum('i,i,xi->xi', ud_ud_ud, a0b1_a0b1, rho0b[1:])\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_uu_ud, a0a1_b0a1, rho0a[1:]) * 8\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_ud_ud, a0b1_b0a1, rho0a[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_uu_dd, a0a1_b0b1, rho0a[1:]) * 16\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_ud_dd, a0b1_b0b1, rho0a[1:]) * 8\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_ud_ud, a0a1_b0a1, rho0b[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,xi->xi', ud_ud_ud, a0b1_b0a1, rho0b[1:]) * 2\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_ud_dd, a0a1_b0b1, rho0b[1:]) * 8\n    wva[1:] += numpy.einsum('i,i,xi->xi', ud_ud_dd, a0b1_b0b1, rho0b[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_ud_ud, b0a1_b0a1, rho0a[1:]) * 2\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_ud_dd, b0b1_b0a1, rho0a[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_ud_dd, b0a1_b0b1, rho0a[1:]) * 4\n    wva[1:] += numpy.einsum('i,i,xi->xi', uu_dd_dd, b0b1_b0b1, rho0a[1:]) * 8\n    wva[1:] += numpy.einsum('i,i,xi->xi', ud_ud_ud, b0a1_b0a1, rho0b[1:])\n    wva[1:] += numpy.einsum('i,i,xi->xi', ud_ud_dd, b0b1_b0a1, rho0b[1:]) * 2\n    wva[1:] += numpy.einsum('i,i,xi->xi', ud_ud_dd, b0a1_b0b1, rho0b[1:]) * 2\n    wva[1:] += numpy.einsum('i,i,xi->xi', ud_dd_dd, b0b1_b0b1, rho0b[1:]) * 4\n    wva *= weight\n    wva[0]*=.5  # v+v.T should be applied in the caller\n\n    wvb = numpy.zeros((4,ngrid))\n    wvb[0] += numpy.einsum('i,i,i->i', d_d_d, rho1b[0], rho1b[0])\n    wvb[0] += numpy.einsum('i,i,i->i', u_d_d, rho1b[0], rho1a[0]) * 2\n    wvb[0] += numpy.einsum('i,i,i->i', u_u_d, rho1a[0], rho1a[0])\n    wvb[0] += numpy.einsum('i,i->i', d_dd, b1b1) * 2\n    wvb[0] += numpy.einsum('i,i->i', d_ud, b1a1) * 2\n    wvb[0] += numpy.einsum('i,i->i', d_uu, a1a1) * 2\n    wvb[1:] += numpy.einsum('i,i,xi->xi', d_dd, rho1b[0], rho1b[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,xi->xi', u_dd, rho1a[0], rho1b[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,xi->xi', d_ud, rho1b[0], rho1a[1:]) * 2\n    wvb[1:] += numpy.einsum('i,i,xi->xi', u_ud, rho1a[0], rho1a[1:]) * 2\n    wvb[1:] += numpy.einsum('i,i,xi->xi', dd_dd, b0b1, rho1b[1:]) * 8\n    wvb[1:] += numpy.einsum('i,i,xi->xi', ud_dd, b0b1, rho1a[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,xi->xi', ud_dd, b0a1, rho1b[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,xi->xi', ud_ud, b0a1, rho1a[1:]) * 2\n    wvb[1:] += numpy.einsum('i,i,xi->xi', ud_dd, a0b1, rho1b[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,xi->xi', uu_dd, a0a1, rho1b[1:]) * 8\n    wvb[1:] += numpy.einsum('i,i,xi->xi', ud_ud, a0b1, rho1a[1:]) * 2\n    wvb[1:] += numpy.einsum('i,i,xi->xi', uu_ud, a0a1, rho1a[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,xi->xi', dd_dd, b1b1, rho0b[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,xi->xi', ud_dd, b1a1, rho0b[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,xi->xi', uu_dd, a1a1, rho0b[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,xi->xi', ud_dd, b1b1, rho0a[1:]) * 2\n    wvb[1:] += numpy.einsum('i,i,xi->xi', ud_ud, b1a1, rho0a[1:]) * 2\n    wvb[1:] += numpy.einsum('i,i,xi->xi', uu_ud, a1a1, rho0a[1:]) * 2\n    wvb[0] += numpy.einsum('i,i,i->i', d_d_dd, rho1b[0], b0b1) * 4\n    wvb[0] += numpy.einsum('i,i,i->i', u_d_dd, rho1a[0], b0b1) * 4\n    wvb[0] += numpy.einsum('i,i,i->i', d_d_ud, rho1b[0], b0a1) * 2\n    wvb[0] += numpy.einsum('i,i,i->i', u_d_ud, rho1a[0], b0a1) * 2\n    wvb[0] += numpy.einsum('i,i,i->i', d_d_ud, rho1b[0], a0b1) * 2\n    wvb[0] += numpy.einsum('i,i,i->i', u_d_ud, rho1a[0], a0b1) * 2\n    wvb[0] += numpy.einsum('i,i,i->i', d_d_uu, rho1b[0], a0a1) * 4\n    wvb[0] += numpy.einsum('i,i,i->i', u_d_uu, rho1a[0], a0a1) * 4\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', d_d_dd, rho1b[0], rho1b[0], rho0b[1:]) * 2\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', u_d_dd, rho1b[0], rho1a[0], rho0b[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', u_u_dd, rho1a[0], rho1a[0], rho0b[1:]) * 2\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', d_d_ud, rho1b[0], rho1b[0], rho0b[1:])\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', u_d_ud, rho1b[0], rho1a[0], rho0b[1:]) * 2\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', u_u_ud, rho1a[0], rho1a[0], rho0b[1:])\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', d_dd_dd, rho1b[0], b0b1, rho0b[1:]) * 8\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', u_dd_dd, rho1a[0], b0b1, rho0b[1:]) * 8\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', d_ud_dd, rho1b[0], b0a1, rho0b[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', u_ud_dd, rho1a[0], b0a1, rho0b[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', d_ud_dd, rho1b[0], a0b1, rho0b[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', u_ud_dd, rho1a[0], a0b1, rho0b[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', d_uu_dd, rho1b[0], a0a1, rho0b[1:]) * 8\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', u_uu_dd, rho1a[0], a0a1, rho0b[1:]) * 8\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', d_ud_dd, rho1b[0], b0b1, rho0a[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', u_ud_dd, rho1a[0], b0b1, rho0a[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', d_ud_ud, rho1b[0], b0a1, rho0a[1:]) * 2\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', u_ud_ud, rho1a[0], b0a1, rho0a[1:]) * 2\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', d_ud_ud, rho1b[0], a0b1, rho0a[1:]) * 2\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', u_ud_ud, rho1a[0], a0b1, rho0a[1:]) * 2\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', d_uu_ud, rho1b[0], a0a1, rho0a[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,i,xi->xi', u_uu_ud, rho1a[0], a0a1, rho0a[1:]) * 4\n    wvb[0] += numpy.einsum('i,i->i', d_dd_dd, b0b1_b0b1) * 4\n    wvb[0] += numpy.einsum('i,i->i', d_ud_dd, b0b1_b0a1) * 2\n    wvb[0] += numpy.einsum('i,i->i', d_ud_dd, b0a1_b0b1) * 2\n    wvb[0] += numpy.einsum('i,i->i', d_ud_ud, b0a1_b0a1)\n    wvb[0] += numpy.einsum('i,i->i', d_ud_dd, b0b1_a0b1) * 4\n    wvb[0] += numpy.einsum('i,i->i', d_ud_ud, b0a1_a0b1) * 2\n    wvb[0] += numpy.einsum('i,i->i', d_uu_dd, b0b1_a0a1) * 8\n    wvb[0] += numpy.einsum('i,i->i', d_uu_ud, b0a1_a0a1) * 4\n    wvb[0] += numpy.einsum('i,i->i', d_ud_ud, a0b1_a0b1)\n    wvb[0] += numpy.einsum('i,i->i', d_uu_ud, a0b1_a0a1) * 2\n    wvb[0] += numpy.einsum('i,i->i', d_uu_ud, a0a1_a0b1) * 2\n    wvb[0] += numpy.einsum('i,i->i', d_uu_uu, a0a1_a0a1) * 4\n    wvb[1:] += numpy.einsum('i,i,xi->xi', dd_dd_dd, b0b1_b0b1, rho0b[1:]) * 8\n    wvb[1:] += numpy.einsum('i,i,xi->xi', ud_dd_dd, b0b1_b0a1, rho0b[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,xi->xi', ud_dd_dd, b0a1_b0b1, rho0b[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,xi->xi', ud_ud_dd, b0a1_b0a1, rho0b[1:]) * 2\n    wvb[1:] += numpy.einsum('i,i,xi->xi', ud_dd_dd, b0b1_b0b1, rho0a[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,xi->xi', ud_ud_dd, b0b1_b0a1, rho0a[1:]) * 2\n    wvb[1:] += numpy.einsum('i,i,xi->xi', ud_ud_dd, b0a1_b0b1, rho0a[1:]) * 2\n    wvb[1:] += numpy.einsum('i,i,xi->xi', ud_ud_ud, b0a1_b0a1, rho0a[1:])\n    wvb[1:] += numpy.einsum('i,i,xi->xi', ud_dd_dd, b0b1_a0b1, rho0b[1:]) * 8\n    wvb[1:] += numpy.einsum('i,i,xi->xi', ud_ud_dd, b0a1_a0b1, rho0b[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,xi->xi', uu_dd_dd, b0b1_a0a1, rho0b[1:]) * 16\n    wvb[1:] += numpy.einsum('i,i,xi->xi', uu_ud_dd, b0a1_a0a1, rho0b[1:]) * 8\n    wvb[1:] += numpy.einsum('i,i,xi->xi', ud_ud_dd, b0b1_a0b1, rho0a[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,xi->xi', ud_ud_ud, b0a1_a0b1, rho0a[1:]) * 2\n    wvb[1:] += numpy.einsum('i,i,xi->xi', uu_ud_dd, b0b1_a0a1, rho0a[1:]) * 8\n    wvb[1:] += numpy.einsum('i,i,xi->xi', uu_ud_ud, b0a1_a0a1, rho0a[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,xi->xi', ud_ud_dd, a0b1_a0b1, rho0b[1:]) * 2\n    wvb[1:] += numpy.einsum('i,i,xi->xi', uu_ud_dd, a0a1_a0b1, rho0b[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,xi->xi', uu_ud_dd, a0b1_a0a1, rho0b[1:]) * 4\n    wvb[1:] += numpy.einsum('i,i,xi->xi', uu_uu_dd, a0a1_a0a1, rho0b[1:]) * 8\n    wvb[1:] += numpy.einsum('i,i,xi->xi', ud_ud_ud, a0b1_a0b1, rho0a[1:])\n    wvb[1:] += numpy.einsum('i,i,xi->xi', uu_ud_ud, a0a1_a0b1, rho0a[1:]) * 2\n    wvb[1:] += numpy.einsum('i,i,xi->xi', uu_ud_ud, a0b1_a0a1, rho0a[1:]) * 2\n    wvb[1:] += numpy.einsum('i,i,xi->xi', uu_uu_ud, a0a1_a0a1, rho0a[1:]) * 4\n    wvb *= weight\n    wvb[0]*=.5\n\n    return wva, wvb\n\ndef nr_fxc(mol, grids, xc_code, dm0, dms, spin=0, relativity=0, hermi=0,\n           rho0=None, vxc=None, fxc=None, max_memory=2000, verbose=None):\n    r'''Contract XC kernel matrix with given density matrices\n\n    ... math::\n\n            a_{pq} = f_{pq,rs} * x_{rs}\n\n    '''\n    ni = NumInt()\n    return ni.nr_fxc(mol, grids, xc_code, dm0, dms, spin, relativity,\n                     hermi, rho0, vxc, fxc, max_memory, verbose)\n\n\ndef cache_xc_kernel(ni, mol, grids, xc_code, mo_coeff, mo_occ, spin=0,\n                    max_memory=2000):\n    '''Compute the 0th order density, Vxc and fxc.  They can be used in TDDFT,\n    DFT hessian module etc.\n    '''\n    xctype = ni._xc_type(xc_code)\n    ao_deriv = 0\n    if xctype == 'GGA':\n        ao_deriv = 1\n    elif xctype == 'NLC':\n        raise NotImplementedError('NLC')\n    elif xctype == 'MGGA':\n        raise NotImplementedError('meta-GGA')\n\n    if spin == 0:\n        nao = mo_coeff.shape[0]\n        rho = []\n        for ao, mask, weight, coords \\\n                in ni.block_loop(mol, grids, nao, ao_deriv, max_memory=max_memory):\n            rho.append(ni.eval_rho2(mol, ao, mo_coeff, mo_occ, mask, xctype))\n        rho = numpy.hstack(rho)\n    else:\n        nao = mo_coeff[0].shape[0]\n        rhoa = []\n        rhob = []\n        for ao, mask, weight, coords \\\n                in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):\n            rhoa.append(ni.eval_rho2(mol, ao, mo_coeff[0], mo_occ[0], mask, xctype))\n            rhob.append(ni.eval_rho2(mol, ao, mo_coeff[1], mo_occ[1], mask, xctype))\n        rho = (numpy.hstack(rhoa), numpy.hstack(rhob))\n    vxc, fxc = ni.eval_xc(xc_code, rho, spin, 0, 2, 0)[1:3]\n    return rho, vxc, fxc\n\ndef get_rho(ni, mol, dm, grids, max_memory=2000):\n    '''Density in real space\n    '''\n    make_rho, nset, nao = ni._gen_rho_evaluator(mol, dm, 1)\n    assert(nset == 1)\n    rho = numpy.empty(grids.weights.size)\n    p1 = 0\n    for ao, mask, weight, coords \\\n            in ni.block_loop(mol, grids, nao, 0, max_memory):\n        p0, p1 = p1, p1 + weight.size\n        rho[p0:p1] = make_rho(0, ao, mask, 'LDA')\n    return rho\n\n\nclass NumInt(object):\n    def __init__(self):\n        self.libxc = libxc\n        self.omega = None  # RSH paramter\n\n    @lib.with_doc(nr_vxc.__doc__)\n    def nr_vxc(self, mol, grids, xc_code, dms, spin=0, relativity=0, hermi=0,\n               max_memory=2000, verbose=None):\n        if spin == 0:\n            return self.nr_rks(mol, grids, xc_code, dms, relativity, hermi,\n                               max_memory, verbose)\n        else:\n            return self.nr_uks(mol, grids, xc_code, dms, relativity, hermi,\n                               max_memory, verbose)\n\n    @lib.with_doc(nr_fxc.__doc__)\n    def nr_fxc(self, mol, grids, xc_code, dm0, dms, spin=0, relativity=0, hermi=0,\n               rho0=None, vxc=None, fxc=None, max_memory=2000, verbose=None):\n        if spin == 0:\n            return self.nr_rks_fxc(mol, grids, xc_code, dm0, dms, relativity,\n                                   hermi, rho0, vxc, fxc, max_memory, verbose)\n        else:\n            return self.nr_uks_fxc(mol, grids, xc_code, dm0, dms, relativity,\n                                   hermi, rho0, vxc, fxc, max_memory, verbose)\n\n    nr_rks = nr_rks\n    nr_uks = nr_uks\n    nr_rks_fxc = nr_rks_fxc\n    nr_uks_fxc = nr_uks_fxc\n    cache_xc_kernel  = cache_xc_kernel\n    get_rho = get_rho\n\n    @lib.with_doc(eval_ao.__doc__)\n    def eval_ao(self, mol, coords, deriv=0, shls_slice=None,\n                non0tab=None, out=None, verbose=None):\n        return eval_ao(mol, coords, deriv, shls_slice, non0tab, out, verbose)\n\n    @lib.with_doc(make_mask.__doc__)\n    def make_mask(self, mol, coords, relativity=0, shls_slice=None,\n                  verbose=None):\n        return make_mask(mol, coords, relativity, shls_slice, verbose)\n\n    @lib.with_doc(eval_rho2.__doc__)\n    def eval_rho2(self, mol, ao, mo_coeff, mo_occ, non0tab=None, xctype='LDA',\n                  verbose=None):\n        return eval_rho2(mol, ao, mo_coeff, mo_occ, non0tab, xctype, verbose)\n\n    @lib.with_doc(eval_rho.__doc__)\n    def eval_rho(self, mol, ao, dm, non0tab=None, xctype='LDA', hermi=0, verbose=None):\n        return eval_rho(mol, ao, dm, non0tab, xctype, hermi, verbose)\n\n    def block_loop(self, mol, grids, nao, deriv=0, max_memory=2000,\n                   non0tab=None, blksize=None, buf=None):\n        '''Define this macro to loop over grids by blocks.\n        '''\n        if grids.coords is None:\n            grids.build(with_non0tab=True)\n        ngrids = grids.coords.shape[0]\n        comp = (deriv+1)*(deriv+2)*(deriv+3)//6\n# NOTE to index grids.non0tab, the blksize needs to be the integer multiplier of BLKSIZE\n        if blksize is None:\n            blksize = int(max_memory*1e6/(comp*2*nao*8*BLKSIZE))*BLKSIZE\n            blksize = max(BLKSIZE, min(blksize, ngrids, BLKSIZE*1200))\n        if non0tab is None:\n            non0tab = grids.non0tab\n        if non0tab is None:\n            non0tab = numpy.ones(((ngrids+BLKSIZE-1)//BLKSIZE,mol.nbas),\n                                 dtype=numpy.uint8)\n        if buf is None:\n            buf = numpy.empty((comp,blksize,nao))\n        for ip0 in range(0, ngrids, blksize):\n            ip1 = min(ngrids, ip0+blksize)\n            coords = grids.coords[ip0:ip1]\n            weight = grids.weights[ip0:ip1]\n            non0 = non0tab[ip0//BLKSIZE:]\n            ao = self.eval_ao(mol, coords, deriv=deriv, non0tab=non0, out=buf)\n            yield ao, non0, weight, coords\n\n    def _gen_rho_evaluator(self, mol, dms, hermi=0):\n        if getattr(dms, 'mo_coeff', None) is not None:\n#TODO: test whether dm.mo_coeff matching dm\n            mo_coeff = dms.mo_coeff\n            mo_occ = dms.mo_occ\n            if isinstance(dms, numpy.ndarray) and dms.ndim == 2:\n                mo_coeff = [mo_coeff]\n                mo_occ = [mo_occ]\n            nao = mo_coeff[0].shape[0]\n            ndms = len(mo_occ)\n            def make_rho(idm, ao, non0tab, xctype):\n                return self.eval_rho2(mol, ao, mo_coeff[idm], mo_occ[idm],\n                                      non0tab, xctype)\n        else:\n            if isinstance(dms, numpy.ndarray) and dms.ndim == 2:\n                dms = [dms]\n            if not hermi:\n# For eval_rho when xctype==GGA, which requires hermitian DMs\n                dms = [(dm+dm.conj().T)*.5 for dm in dms]\n            nao = dms[0].shape[0]\n            ndms = len(dms)\n            def make_rho(idm, ao, non0tab, xctype):\n                return self.eval_rho(mol, ao, dms[idm], non0tab, xctype, hermi=1)\n        return make_rho, ndms, nao\n\n####################\n# Overwrite following functions to use custom XC functional\n\n    def hybrid_coeff(self, xc_code, spin=0):\n        return self.libxc.hybrid_coeff(xc_code, spin)\n\n    def nlc_coeff(self, xc_code):\n        return self.libxc.nlc_coeff(xc_code)\n\n    def rsh_coeff(self, xc_code):\n        return self.libxc.rsh_coeff(xc_code)\n\n    def eval_xc(self, xc_code, rho, spin=0, relativity=0, deriv=1, omega=None,\n                verbose=None):\n        if omega is None: omega = self.omega\n        return self.libxc.eval_xc(xc_code, rho, spin, relativity, deriv,\n                                  omega, verbose)\n    eval_xc.__doc__ = libxc.eval_xc.__doc__\n\n    def _xc_type(self, xc_code):\n        return self.libxc.xc_type(xc_code)\n\n    def rsh_and_hybrid_coeff(self, xc_code, spin=0):\n        '''Range-separated parameter and HF exchange components: omega, alpha, beta\n\n        Exc_RSH = c_SR * SR_HFX + c_LR * LR_HFX + (1-c_SR) * Ex_SR + (1-c_LR) * Ex_LR + Ec\n                = alpha * HFX + beta * SR_HFX + (1-c_SR) * Ex_SR + (1-c_LR) * Ex_LR + Ec\n                = alpha * LR_HFX + hyb * SR_HFX + (1-c_SR) * Ex_SR + (1-c_LR) * Ex_LR + Ec\n\n        SR_HFX = < pi | e^{-omega r_{12}}/r_{12} | iq >\n        LR_HFX = < pi | (1-e^{-omega r_{12}})/r_{12} | iq >\n        alpha = c_LR\n        beta = c_SR - c_LR\n        '''\n        omega, alpha, beta = self.rsh_coeff(xc_code)\n        if self.omega is not None:\n            omega = self.omega\n\n        if abs(omega) > 1e-10:\n            hyb = alpha + beta\n        else:\n            hyb = self.hybrid_coeff(xc_code, spin)\n        return omega, alpha, hyb\n_NumInt = NumInt\n\n\nif __name__ == '__main__':\n    import time\n    from pyscf import gto\n    from pyscf import dft\n\n    mol = gto.M(\n        atom = [\n        [\"O\" , (0. , 0.     , 0.)],\n        [1   , (0. , -0.757 , 0.587)],\n        [1   , (0. , 0.757  , 0.587)] ],\n        basis = '6311g**',)\n    mf = dft.RKS(mol)\n    mf.grids.atom_grid = {\"H\": (30, 194), \"O\": (30, 194),}\n    mf.grids.prune = None\n    mf.grids.build()\n    dm = mf.get_init_guess(key='minao')\n\n    numpy.random.seed(1)\n    dm1 = numpy.random.random((dm.shape))\n    dm1 = lib.hermi_triu(dm1)\n    print(time.clock())\n    res = mf._numint.nr_vxc(mol, mf.grids, mf.xc, dm1, spin=0)\n    print(res[1] - -37.084047825971282)\n    res = mf._numint.nr_vxc(mol, mf.grids, mf.xc, (dm1,dm1), spin=1)\n    print(res[1] - -92.436362308687094)\n    res = mf._numint.nr_vxc(mol, mf.grids, mf.xc, dm, spin=0)\n    print(res[1] - -8.6313329288394947)\n    res = mf._numint.nr_vxc(mol, mf.grids, mf.xc, (dm,dm), spin=1)\n    print(res[1] - -21.520301399504582)\n    print(time.clock())\n", "meta": {"hexsha": "600034df8993e0a6dec31ad9872ac9be3f1db5ae", "size": 88342, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/dft/numint.py", "max_stars_repo_name": "tmash/pyscf", "max_stars_repo_head_hexsha": "89c101c1c963e8247808635c61cd165bffab42d6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-05T13:50:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T13:50:50.000Z", "max_issues_repo_path": "pyscf/dft/numint.py", "max_issues_repo_name": "tmash/pyscf", "max_issues_repo_head_hexsha": "89c101c1c963e8247808635c61cd165bffab42d6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscf/dft/numint.py", "max_forks_repo_name": "tmash/pyscf", "max_forks_repo_head_hexsha": "89c101c1c963e8247808635c61cd165bffab42d6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.518226601, "max_line_length": 98, "alphanum_fraction": 0.5491159358, "include": true, "reason": "import numpy,import scipy", "num_tokens": 32199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.18090455003753936}}
{"text": "import copy\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.tensorboard import SummaryWriter\n\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n\nimport copy\nfrom collections import OrderedDict\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.utils.rnn as rnn_utils\n\n\n# from .model import Actor, Critic, lstmActor, lstmCritic\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nclass lstmActor(nn.Module):\n\tdef __init__(self, state_dim, action_dim, max_action=None, hidden_dim=256, lstm_layer=1, GRU=False, **kwargs):\n\t\t# state_dim = observation_dim + action_dim\n\t\tsuper(lstmActor, self).__init__()\n\t\tself.state_dim = state_dim + action_dim\n\t\tself.action_dim = action_dim\n\t\tself.hidden_dim = hidden_dim\n\t\tdropout = 0 if lstm_layer == 1 else 0.2\n\n\t\trnn_type = nn.LSTM if not GRU else nn.GRU\n\n\t\tself.l1 = rnn_type(input_size=self.state_dim,  \n\t\t\t\t\t\t  hidden_size=hidden_dim, \n\t\t\t\t\t\t  num_layers=lstm_layer,\n\t\t\t\t\t\t  bias=True, batch_first=True, dropout=dropout)\n\n\t\tself.l2 = nn.Linear(hidden_dim, hidden_dim)\n\t\t# self.l3_throttle = nn.Linear(hidden_dim, 1)\n\t\t# self.l3_else = nn.Linear(hidden_dim, action_dim-1)\n\t\tself.l3 = nn.Linear(hidden_dim, action_dim)\n\n\n\t\tself.max_action = max_action or torch.ones(action_dim).to(\"cuda\")\n\n\n\n\tdef forward(self, *args, **kwargs):\n\t\ta, hc = self._forward(*args, **kwargs)\n\t\treturn a\n\n\tdef _forward(self, x, hc=None):\n\t\t\n\t\t# lstm_out, hc = self.l1(x, hc)\n\t\tlstm_out, hc = self.l1(x, hc)\n\n\t\tif type(x) is torch.Tensor:\n\t\t\tlstm_out = lstm_out.view((-1, self.hidden_dim))\n\t\telse:\n\t\t\tlstm_out_tmp, out_len = rnn_utils.pad_packed_sequence(lstm_out, batch_first=True)\n\t\t\tbs = lstm_out_tmp.shape[0]\n\t\t\tlstm_out = torch.zeros((bs, self.hidden_dim)).cuda()\n\t\t\tfor i, length in enumerate(out_len):\n\t\t\t\tlstm_out[i] = lstm_out_tmp[i, length-1, :].clone()\n\n\t\t# lstm_out = F.relu(lstm_out)\n\t\tlstm_out = F.relu(lstm_out.clone())\n\t\ta = F.relu(self.l2(lstm_out))\n\t\t# output = torch.cat( [F.softsign(self.l3_else(a)), torch.sigmoid(self.l3_throttle(a))], 1)\n\t\t# output = torch.tanh(self.l3(a))\n\t\t# print('original out_put',output)\n\n\t\t# output = self.max_action * output\n\t\t# print('max_action',self.max_action)\n\t\t# print('output:',output)\n\t\toutput = self.max_action * torch.tanh(self.l3(a))\n\t\treturn output, hc\n\n\tdef flatten_parameters(self):\n\t\tself.l1.flatten_parameters()\n\n\nclass lstmCritic(nn.Module):\n\tdef __init__(self, state_dim, action_dim, hidden_dim=256, lstm_layer=1, dropout=0., GRU=False, **kwargs):\n\t\tsuper(lstmCritic, self).__init__()\n\t\tself.state_dim = state_dim + action_dim\n\t\tself.action_dim = action_dim\n\t\tself.hidden_dim = hidden_dim\n\t\t\n\t\t\n\t\trnn_type = nn.LSTM if not GRU else nn.GRU\n\t\tself.q1l1 = rnn_type(input_size=self.state_dim,  \n\t\t\t\t\t\t  hidden_size=hidden_dim, \n\t\t\t\t\t\t  num_layers=lstm_layer,\n\t\t\t\t\t\t  bias=True, batch_first=True, dropout=dropout)\n\t\tself.q1ax = nn.Linear(action_dim, hidden_dim)\n\t\tself.q1l2 = nn.Linear(hidden_dim, hidden_dim)\n\t\tself.q1l3 = nn.Linear(hidden_dim, 1)\n\n\n\t\tself.q2l1 = rnn_type(input_size=self.state_dim,  \n\t\t\t\t\t\t  hidden_size=hidden_dim, \n\t\t\t\t\t\t  num_layers=lstm_layer,\n\t\t\t\t\t\t  bias=True, batch_first=True, dropout=dropout)\n\t\tself.q2ax = nn.Linear(action_dim, hidden_dim)\n\t\tself.q2l2 = nn.Linear(hidden_dim, hidden_dim)\n\t\tself.q2l3 = nn.Linear(hidden_dim, 1)\n\t\t\n\tdef forward(self, *args, **kwargs):\n\t\tq1, q2, hc1, hc2 = self._forward(*args, **kwargs)\n\t\treturn q1, q2\n\n\tdef _forward(self, x, a, hc1=None, hc2=None):\n\t\tq1, hc1 = self.Q1(x, a, hc1)\n\t\tq2, hc2 = self.Q2(x, a, hc2)\n\t\treturn q1, q2, hc1, hc2\n\n\tdef flatten_parameters(self):\n\t\tself.q1l1.flatten_parameters()\n\t\tself.q2l1.flatten_parameters()\n\n\tdef Q1(self, x, a, hc=None):\n\t\t# print('hc.shape',hc.shape)\n\t\tq1, hc = self.q1l1(x, hc)\n\t\tif type(x) is torch.Tensor:\n\t\t\tq1 = q1.view((-1, self.hidden_dim))\n\t\telse:\n\t\t\tlstm_out_tmp, out_len = rnn_utils.pad_packed_sequence(q1, batch_first=True)\n\t\t\tbs = lstm_out_tmp.shape[0]\n\t\t\tq1 = torch.zeros((bs, self.hidden_dim)).cuda()\n\t\t\tfor i, length in enumerate(out_len):\n\t\t\t\tq1[i] = lstm_out_tmp[i, length-1, :].clone()\n\n\t\tq1a = self.q1ax(a)\n\t\t# q1 = F.relu(q1 + q1a)\n\t\tq1 = F.relu(q1.clone() + q1a)\n\t\t# q1 = F.relu(self.q1l2(q1))\n\t\tq1_f = q1.clone()\n\t\tq1 = F.relu(self.q1l2(q1_f))\n\t\t# q1 = self.q1l3(q1)\n\t\tq1_ff = q1.clone()\n\t\tq1 = self.q1l3(q1_ff)\n\n\t\treturn q1, hc\n\n\tdef Q2(self, x, a, hc=None):\n\t\tq2, hc = self.q2l1(x, hc)\n\t\tif type(x) is torch.Tensor:\n\t\t\tq2 = q2.view((-1, self.hidden_dim))\n\t\telse:\n\t\t\tlstm_out_tmp, out_len = rnn_utils.pad_packed_sequence(q2, batch_first=True)\n\t\t\tbs = lstm_out_tmp.shape[0]\n\t\t\tq2 = torch.zeros((bs, self.hidden_dim)).cuda()\n\t\t\tfor i, length in enumerate(out_len):\n\t\t\t\tq2[i] = lstm_out_tmp[i, length-1, :].clone()\n\n\t\tq2a = self.q2ax(a)\n\t\t# q2 = F.relu(q2) + F.relu(q2a)\n\t\tq2 = F.relu(q2.clone()) + F.relu(q2a)\n\t\t# q2 = F.relu(self.q2l2(q2))\n\t\tq2 = F.relu(self.q2l2(q2.clone()))\n\t\t# q2 = self.q2l3(q2)\n\t\tq2 = self.q2l3(q2.clone())\n\n\t\treturn q2, hc\n\n\n\n\nclass TD3(object):\n\tdef __init__(\n\t\tself,\n\t\tstate_dim,\n\t\taction_dim,\n\t\tmax_action,\n\t\thidden_dim=256,\n\t\tdiscount=0.99,\n\t\ttau=0.005,\n\t\tpolicy_noise=0.2,\n\t\tnoise_clip=0.5,\n\t\tpolicy_freq=2,\n\t\trnn = True,\n\t\tlr_a=1e-3,\n\t\tlr_c=1e-3,\n\t\tJ_lambda=1,\n\t\tweight_decay=0,\n\t\tfreeze_actor=False \n\t):\n\n\t\tself.rnn = rnn\n\n\t\tactor_model = Actor if not self.rnn else lstmActor \n\t\tcritic_model = Critic if not self.rnn else lstmCritic\n\n\t\tself.actor = actor_model(state_dim, action_dim, max_action, hidden_dim=hidden_dim, GRU=self.rnn in ['gru', 'GRU', 'Gru']).to(device)\n\t\tself.actor_target = copy.deepcopy(self.actor)\n\t\tself.actor_optimizer = torch.optim.Adam(self.actor.parameters(), lr=lr_a, weight_decay=weight_decay)\n\n\t\tself.critic = critic_model(state_dim, action_dim, hidden_dim=hidden_dim, GRU=self.rnn in ['gru', 'GRU', 'Gru']).to(device)\n\t\tself.critic_target = copy.deepcopy(self.critic)\n\t\tself.critic_optimizer = torch.optim.Adam(self.critic.parameters(), lr=lr_c, weight_decay=weight_decay)\n\n\t\tself.action_dim = action_dim\n\t\tself.max_action = max_action\n\t\tself.discount = discount\n\t\tself.tau = tau\n\t\tself.policy_noise = policy_noise\n\t\tself.noise_clip = noise_clip\n\t\tself.policy_freq = policy_freq\n\t\tself.J_lambda = J_lambda\n\n\t\tself.total_it = 0\n\t\tself.reset()\n\t\tself.actor_loss = 0\n\t\tself.critic_loss = 0\n\n\n\tdef reset(self):\n\t\tif self.rnn:\n\t\t\tself.hc = None\n\t\t\tself.last_action = torch.zeros(1, self.action_dim).to(device)\n\n\tdef select_action(self, state):\n\t\tstate = torch.FloatTensor(state.reshape(1, -1)).to(device)\n\t\tif not self.rnn:\n\t\t\treturn self.actor(state).cpu().data.numpy().flatten()\n\t\telse:\n\t\t\tstate = torch.cat([state, self.last_action], dim=1).reshape(1, 1, -1)\n\t\t\taction, self.hc = self.actor._forward(state, self.hc)\n\t\t\tself.last_action = action.clone()\n\t\t\treturn action.cpu().data.numpy().flatten()\n\n\n\tdef get_loss(self, replay_buffer, batch_size=100, replay_expert=False):\n\t\t# Sample replay buffer \n\t\tstate, action, next_state, reward, not_done = replay_buffer.sample(batch_size)\n\t\tbatch_size = reward.shape[0]\n\n\t\twith torch.no_grad():\n\t\t\t# Select action according to policy and add clipped noise\n\t\t\tnoise = (\n\t\t\t\ttorch.randn_like(action) * self.policy_noise\n\t\t\t).clamp(-self.noise_clip, self.noise_clip)\n\t\t\t\n\t\t\tif not self.rnn:\n\t\t\t\tnext_action = (\n\t\t\t\t\tself.actor_target(next_state) + noise\n\t\t\t\t).clamp(-self.max_action, self.max_action)\n\t\t\telse:\n\t\t\t\tself.actor_target.flatten_parameters()\n\t\t\t\tnext_action, hc = self.actor_target._forward(state)\n\t\t\t\tself.actor_target.flatten_parameters()\n\t\t\t\tnext_action = (\n\t\t\t\t\tself.actor_target(next_state.reshape(batch_size, 1, -1), hc) + noise\n\t\t\t\t).clamp(-self.max_action, self.max_action)\n\n\t\t\t# Compute the target Q value\n\t\t\tif not self.rnn:\n\t\t\t\ttarget_Q1, target_Q2 = self.critic_target(next_state, next_action)\n\t\t\telse:\n\t\t\t\tself.critic_target.flatten_parameters()\n\t\t\t\ttarget_Q1, target_Q2, hc1, hc2 = self.critic_target._forward(state, action)  # actions doesnot matter here.\n\t\t\t\ttarget_Q1, target_Q2 = self.critic_target(next_state.reshape(batch_size, 1, -1), next_action, hc1, hc2)\n\n\t\t\ttarget_Q = torch.min(target_Q1, target_Q2)\n\t\t\t# target_Q = reward + not_done * self.discount * target_Q\n\t\t\ttarget_Q = reward + not_done * self.discount * target_Q.clone()\n\n\t\t# Get current Q estimates\n\t\tif self.rnn:\n\t\t\tself.critic.flatten_parameters()\n\t\tcurrent_Q1, current_Q2 = self.critic(state, action)\n\n\t\t# Compute critic loss\n\t\tcritic_loss = F.mse_loss(current_Q1, target_Q) + F.mse_loss(current_Q2, target_Q)\n\n\t\tif not replay_expert:\n\t\t\t\n\t\t\t# Compute actor losses\n\t\t\tif not self.rnn:\n\t\t\t\tactor_loss = - self.critic.Q1(state, self.actor(state)).mean() * self.J_lambda\n\t\t\telse:\n\t\t\t\tself.critic.flatten_parameters()\n\t\t\t\tactor_loss = - self.critic.Q1(state, self.actor(state))[0].mean() * self.J_lambda\n\t\t\t\t# print('actor_loss.shape',self.critic.Q1(state, self.actor(state))[0].shape)\n\t\t\t\t# actor_loss_ = -self.critic.Q1(state, self.actor(state))#.mean()\n\t\t\t\t# print('actor_loss_:')\n\t\t\t\t# print(self.critic.Q1(state, self.actor(state)))\n\n\n\n\t\t\treturn critic_loss, actor_loss\n\n\t\telse:\n\t\t\t# Compute Behavior Cloning Loss if needed\n\t\t\n\t\t\tstate, action, next_state, reward, not_done = replay_buffer.sample(self.buffer_size_expert)\n\t\t\tbatch_size = reward.shape[0]\n\t\t\t# action = torch.clamp(action, -1, 1)\n\t\t\taction = torch.clamp(action.clone(), -1, 1)\n\t\t\tif self.rnn: self.actor_target.flatten_parameters()\n\t\t\tpred_action = self.actor_target(state)\n\n\t\t\t# Q Filter \n\t\t\tif self.rnn: self.critic_target.flatten_parameters()\n\t\t\tQ_expert = torch.min(*self.critic_target(state, action))\n\t\t\tif self.rnn: self.critic_target.flatten_parameters()\n\t\t\tQ_pred = torch.min(*self.critic_target(state, pred_action))\n\t\t\tmask = (Q_expert<Q_pred).clone()\n\t\t\tQ_expert[mask] = 0\n\t\t\tQ_pred[mask] = 0\n\n\t\t\tbc_loss = F.mse_loss(Q_expert, Q_pred) * self.bc_lambda\n\n\t\t\treturn critic_loss, bc_loss, torch.sum(mask==1).item()/self.buffer_size_expert\n\n\tdef train(self, replay_buffer, batch_size=100, freeze_actor_update=False):\n\t\t# with torch.autograd.set_detect_anomaly(True):\n\n\t\tself.total_it += 1\n\n\t\tif hasattr(self, 'demonstration_buffer'):\n\t\t\tcritic_loss_, actor_loss_ = self.get_loss(replay_buffer, batch_size)\t\n\t\t\texp_critic_loss, bc_loss, Qfilted_ratio = self.get_loss(self.demonstration_buffer, self.buffer_size_expert, replay_expert=True)\n\t\t\tloss_dict = OrderedDict({\n\t\t\t\t\t\t\t'actorLoss': actor_loss_.item(), \n\t\t\t\t\t\t\t'bcLoss': bc_loss.item(), \n\t\t\t\t\t\t\t'actorLoss_total': actor_loss_.item() + bc_loss.item(),\n\t\t\t\t\t\t\t'actorQfiltedRatio': Qfilted_ratio,\n\t\t\t\t\t\t\t'criticLoss': critic_loss_.item(),\n\t\t\t\t\t\t\t'criticLossExpert': exp_critic_loss.item(),\n\t\t\t\t\t\t\t'criticLoss_total': critic_loss_.item() + exp_critic_loss.item()\n\t\t\t\t\t\t})\n\t\t\tactor_loss = actor_loss_ + bc_loss\n\t\t\tcritic_loss = critic_loss_ + exp_critic_loss\n\t\telse:\n\t\t\tcritic_loss, actor_loss = self.get_loss(replay_buffer, batch_size)\n\t\t\tloss_dict = OrderedDict({'actorLoss': actor_loss.item() ,'criticLoss': critic_loss.item()})\n\t\tself.actor_loss = actor_loss\n\t\tself.critic_loss = critic_loss\n\t\t# # Optimize the critic\n\t\t# self.critic_optimizer.zero_grad()\n\t\t# # We set retain grad = true here\n\t\t# # critic_loss.backward()\n\t\t# critic_loss.backward()\n\t\t# self.critic_optimizer.step()\n\n\t\t# Delayed policy updates\n\t\tif self.total_it % self.policy_freq == 0:\n\n\t\t\tif not freeze_actor_update:\n\t\t\t\t# Optimize the critic\n\t\t\t\tself.critic_optimizer.zero_grad()\n\t\t\t\tself.actor_optimizer.zero_grad()\n\n\t\t\t\t# We set retain grad = true here\n\t\t\t\t# critic_loss.backward()\n\t\t\t\t# critic_loss.backward(retain_graph = True)\n\t\t\t\tcritic_loss.backward()\n\t\t\t\t# Optimize the actor \n\n\t\t\t\tactor_loss.backward()\n\t\t\t\tself.critic_optimizer.step()\n\t\t\t\tself.actor_optimizer.step()\n\n\t\t\t\t# Update the frozen target models\n\t\t\t\tfor param, target_param in zip(self.actor.parameters(), self.actor_target.parameters()):\n\t\t\t\t\ttarget_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data)\n\n\t\t\tfor param, target_param in zip(self.critic.parameters(), self.critic_target.parameters()):\n\t\t\t\ttarget_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data)\n\t\telse:\n\t\t\t# Optimize the critic\n\t\t\tself.critic_optimizer.zero_grad()\n\t\t\t# We set retain grad = true here\n\t\t\t# critic_loss.backward()\n\t\t\tcritic_loss.backward()\n\t\t\tself.critic_optimizer.step()\n\n\n\t\treturn loss_dict\n\n\n\tdef load_demonstration_buffer(self, demon_buffer, buffer_size_expert, bc_lambda):\n\t\tself.demonstration_buffer = demon_buffer\n\t\tself.buffer_size_expert = buffer_size_expert\n\t\tself.bc_lambda = bc_lambda\n\n\tdef pretrain(self, replay_buffer, batch_size=4096, no_update=False):\n\t\tstate, action, next_state, reward, not_done = replay_buffer.sample(batch_size)\n\t\tbatch_size = reward.shape[0]\n\t\taction = torch.clamp(action, -1, 1)\n\n\t\tif self.rnn:\n\t\t\tself.actor.flatten_parameters()\n\t\n\t\tpred_action = self.actor(state)\n\t\n\t\tactor_loss = F.mse_loss(pred_action, action)\n\n\t\tif not no_update:\n\t\t\tself.actor_optimizer.zero_grad()\n\t\t\tactor_loss.backward()\n\t\t\tself.actor_optimizer.step()\n\n\t\treturn actor_loss.item()\n\n\tdef hard_update_target(self):\n\t\tfor param, target_param in zip(self.actor.parameters(), self.actor_target.parameters()):\n\t\t\ttarget_param.data.copy_(param.data)\n\n\tdef save(self, filename):\n\t\ttorch.save(self.critic.state_dict(), filename + \"_critic\")\n\t\ttorch.save(self.critic_optimizer.state_dict(), filename + \"_critic_optimizer\")\n\t\t\n\t\ttorch.save(self.actor.state_dict(), filename + \"_actor\")\n\t\ttorch.save(self.actor_optimizer.state_dict(), filename + \"_actor_optimizer\")\n\n\n\tdef load(self, filename):\n\t\tself.critic.load_state_dict(torch.load(filename + \"_critic\"))\n\t\tself.critic_optimizer.load_state_dict(torch.load(filename + \"_critic_optimizer\"))\n\t\tself.critic_target = copy.deepcopy(self.critic)\n\n\t\tself.actor.load_state_dict(torch.load(filename + \"_actor\"))\n\t\tself.actor_optimizer.load_state_dict(torch.load(filename + \"_actor_optimizer\"))\n\t\tself.actor_target = copy.deepcopy(self.actor)\n\n\n\n\n\n\n\n\n'''\nclass Actor(nn.Module):\n\tdef __init__(self, state_dim, action_dim, max_action):\n\t\tsuper(Actor, self).__init__()\n\n\t\tself.l1 = nn.Linear(state_dim, 256)\n\t\tself.l2 = nn.Linear(256, 256)\n\t\tself.l3 = nn.Linear(256, action_dim)\n\n\t\tself.max_action = max_action\n\n\n\tdef forward(self, state):\n\t\ta = F.tanh(self.l1(state))\n\t\ta = F.tanh(self.l2(a))\n\t\treturn self.max_action * torch.tanh(self.l3(a))\n\n\nclass Critic(nn.Module):\n\tdef __init__(self, state_dim, action_dim):\n\t\tsuper(Critic, self).__init__()\n\n\t\t# Q1 architecture\n\t\tself.l1 = nn.Linear(state_dim + action_dim, 256)\n\t\tself.l2 = nn.Linear(256, 256)\n\t\tself.l3 = nn.Linear(256, 1)\n\n\t\t# Q2 architecture\n\t\tself.l4 = nn.Linear(state_dim + action_dim, 256)\n\t\tself.l5 = nn.Linear(256, 256)\n\t\tself.l6 = nn.Linear(256, 1)\n\n\n\tdef forward(self, state, action):\n\t\tsa = torch.cat([state, action], 1)\n\n\t\tq1 = F.relu(self.l1(sa))\n\t\tq1 = F.relu(self.l2(q1))\n\t\tq1 = self.l3(q1)\n\n\t\tq2 = F.relu(self.l4(sa))\n\t\tq2 = F.relu(self.l5(q2))\n\t\tq2 = self.l6(q2)\n\t\treturn q1, q2\n\n\n\tdef Q1(self, state, action):\n\t\tsa = torch.cat([state, action], 1)\n\n\t\tq1 = F.relu(self.l1(sa))\n\t\tq1 = F.relu(self.l2(q1))\n\t\tq1 = self.l3(q1)\n\t\treturn q1\n\n\nclass TD3(object):\n\tdef __init__(\n\t\tself,\n\t\tstate_dim,\n\t\taction_dim,\n\t\tmax_action,\n\t\tdiscount=0.99,\n\t\ttau=0.005,\n\t\tpolicy_noise=0.2,\n\t\tnoise_clip=0.5,\n\t\tpolicy_freq=2,\n\t\tfreeze_actor = 15000\n\t):\n\n\t\tself.actor = Actor(state_dim, action_dim, max_action).to(device)\n\t\tself.actor_target = copy.deepcopy(self.actor)\n\t\tself.actor_optimizer = torch.optim.Adam(self.actor.parameters(), lr=3e-4)\n\n\t\tself.critic = Critic(state_dim, action_dim).to(device)\n\t\tself.critic_target = copy.deepcopy(self.critic)\n\t\tself.critic_optimizer = torch.optim.Adam(self.critic.parameters(), lr=3e-4)\n\n\t\tself.max_action = max_action\n\t\tself.discount = discount\n\t\tself.tau = tau\n\t\tself.policy_noise = policy_noise\n\t\tself.noise_clip = noise_clip\n\t\tself.policy_freq = policy_freq\n\n\t\tself.total_it = 0\n\t\tself.freeze_actor = freeze_actor\n\n\t\t# TensorBoard Record parameter\n\t\tself.actor_loss = 0\n\t\tself.critic_loss = 0\n\n\tdef select_action(self, state):\n\t\tstate = torch.FloatTensor(state.reshape(1, -1)).to(device)\n\t\treturn self.actor(state).cpu().data.numpy().flatten()\n\n\n\tdef train(self, replay_buffer, batch_size=100):\n\t\tself.total_it += 1\n\n\t\t# Sample replay buffer\n\t\tstate, action, next_state, reward, not_done = replay_buffer.sample(batch_size)\n\n\t\twith torch.no_grad():\n\t\t\t# Select action according to policy and add clipped noise\n\t\t\tnoise = (\n\t\t\t\ttorch.randn_like(action) * self.policy_noise\n\t\t\t).clamp(-self.noise_clip, self.noise_clip)\n\n\t\t\tnext_action = (\n\t\t\t\tself.actor_target(next_state) + noise\n\t\t\t).clamp(-self.max_action, self.max_action)\n\n\t\t\t# Compute the target Q value\n\t\t\ttarget_Q1, target_Q2 = self.critic_target(next_state, next_action)\n\t\t\ttarget_Q = torch.min(target_Q1, target_Q2)\n\t\t\ttarget_Q = reward + not_done * self.discount * target_Q\n\n\t\t# Get current Q estimates\n\t\tcurrent_Q1, current_Q2 = self.critic(state, action)\n\n\t\t# Compute critic loss\n\t\tcritic_loss = F.mse_loss(current_Q1, target_Q) + F.mse_loss(current_Q2, target_Q)\n\t\tself.critic_loss = critic_loss\n\n\t\t# Optimize the critic\n\t\tself.critic_optimizer.zero_grad()\n\t\tcritic_loss.backward()\n\t\tself.critic_optimizer.step()\n\n\t\t# Delayed policy updates\n\t\tif self.total_it % self.policy_freq == 0 and self.total_it > self.freeze_actor:\n\n\t\t\t# Compute actor losse\n\t\t\tactor_loss = -self.critic.Q1(state, self.actor(state)).mean()\n\t\t\tself.actor_loss = actor_loss\n\n\t\t\t# Optimize the actor\n\t\t\tself.actor_optimizer.zero_grad()\n\t\t\tactor_loss.backward()\n\t\t\tself.actor_optimizer.step()\n\n\t\t\t# Update the frozen target models\n\t\t\tfor param, target_param in zip(self.critic.parameters(), self.critic_target.parameters()):\n\t\t\t\ttarget_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data)\n\n\t\t\tfor param, target_param in zip(self.actor.parameters(), self.actor_target.parameters()):\n\t\t\t\ttarget_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data)\n\n\n\tdef save(self, filename):\n\t\ttorch.save(self.critic.state_dict(), filename + \"_critic\")\n\t\ttorch.save(self.critic_optimizer.state_dict(), filename + \"_critic_optimizer\")\n\n\t\ttorch.save(self.actor.state_dict(), filename + \"_actor\")\n\t\ttorch.save(self.actor_optimizer.state_dict(), filename + \"_actor_optimizer\")\n\n\n\tdef load(self, filename):\n\t\tself.critic.load_state_dict(torch.load(filename + \"_critic\"))\n\t\tself.critic_optimizer.load_state_dict(torch.load(filename + \"_critic_optimizer\"))\n\t\tself.critic_target = copy.deepcopy(self.critic)\n\n\t\tself.actor.load_state_dict(torch.load(filename + \"_actor\"))\n\t\tself.actor_optimizer.load_state_dict(torch.load(filename + \"_actor_optimizer\"))\n\t\tself.actor_target = copy.deepcopy(self.actor)\n\t\tprint(\"Load model: \"+filename)\n\n'''\n\n", "meta": {"hexsha": "12d8ab6d56dfa6fd3d9682e28cf32358f1d252db", "size": 18584, "ext": "py", "lang": "Python", "max_stars_repo_path": "agent/TD3/RTD3.py", "max_stars_repo_name": "codevideo/Airsim_Test", "max_stars_repo_head_hexsha": "0b47665c67ba674d277fc8de58739a59648bb7eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "agent/TD3/RTD3.py", "max_issues_repo_name": "codevideo/Airsim_Test", "max_issues_repo_head_hexsha": "0b47665c67ba674d277fc8de58739a59648bb7eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "agent/TD3/RTD3.py", "max_forks_repo_name": "codevideo/Airsim_Test", "max_forks_repo_head_hexsha": "0b47665c67ba674d277fc8de58739a59648bb7eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5155993432, "max_line_length": 134, "alphanum_fraction": 0.7094812742, "include": true, "reason": "import numpy", "num_tokens": 5276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.18090454145594667}}
{"text": "import cv2\nimport numpy as np\nfrom queue import Queue\n#脊波变换-->用于图像增强\n#def ridgelet_transform(img):\n#截取矩形兴趣域\ndef get_ROI(img):\n    #去除部分无关区域\n    img=img[30:226,50:380]\n    # cv2.imshow('quchu',img)\n    #提取边缘\n    bimg1=cv2.Canny(img,20,240)\n    # cv2.imshow('canny提取边缘', bimg1)\n    h,w=bimg1.shape\n    y1=0\n    y2=0\n    for k in range(w):\n        for i in range(h//2,0,-1):\n            if(bimg1[i][k]==255):\n                y1+=i\n        for j in range(h//2,h):\n            if(bimg1[j][k]==255):\n                y2+=j\n    y1=y1//(w)\n    y2=y2//(w)\n    roi_img=img[y1:y2,:]\n    #尺度归一化\n    # print(roi_img.shape)\n    print(roi_img.shape)\n    if roi_img.shape[0]==0 or roi_img.shape[1]==0:\n        roi_img=img[:,50:202]\n    roi_unimg=cv2.resize(roi_img,(330,144),cv2.INTER_LINEAR)\n    # cv2.imshow('uni', roi_unimg)\n    return roi_unimg\n\n\n#截取矩形兴趣域\ndef get_ROI0(img):\n    #去除部分无关区域\n    img=img[0:320,200:460]\n    # clahe = cv2.createCLAHE(clipLimit=4.0, tileGridSize=(8, 8))\n    # img = clahe.apply(img)\n    img=cv2.medianBlur(img,3)\n    cv2.imshow('caij',img)\n    #提取边缘\n    bimg=cv2.Canny(img,20,120)\n    cv2.imshow('tst', bimg)\n    # cv2.waitKey(0)\n    # cv2.destroyAllWindows()\n    #裁剪：分为左右两部分，分别计算平均边缘坐标\n    h,w=bimg.shape\n    x1=0\n    x2=0\n    for k in range(h):\n        for i in range(w//2,0,-1):\n            if(bimg[k][i]==255):\n                x1+=i\n        for j in range(w//2,w):\n            if(bimg[k][j]==255):\n                x2+=j\n    x1=x1//h\n    x2=x2//h\n    # print(x1)\n    # print(x2)\n    roi_img=img[:,x1:x2]\n    if roi_img[1]==0:\n        roi_img=img[:,50:202]\n    #尺度归一化\n    roi_unimg=cv2.resize(roi_img,(150,320),cv2.INTER_LINEAR)\n    # print(\"???\")\n    # print(roi_img.shape)\n    return roi_unimg\n\n#图像增强\ndef clahe_gabor(roi_img):\n    #CLAHE:限制对比度的自适应直方图均衡\n    clahe = cv2.createCLAHE(clipLimit=4.0, tileGridSize=(5,5))\n    clahe_img=clahe.apply(roi_img)\n    # cv2.imwrite('D:/finger_vein_recognition/clahe_roi_img.jpg',clahe_img)\n    #Gabor滤波和融合都没有调试好\n    # res=np.zeros(roi_img.shape,np.uint8)\n    # for i in range(4):\n    #     gabor = cv2.getGaborKernel(ksize=(5, 5), sigma=20, theta=i*45, lambd=30, gamma=0.375)\n    #     gabor_img = cv2.filter2D(src=clahe_img, ddepth=cv2.CV_8UC3, kernel=gabor)\n    #     cv2.imwrite('D:/finger_vein_recognition/'+str(i)+'.jpg', gabor_img)\n    #     # gabor_img=cv2.GaussianBlur(gabor_img,ksize=(3,3),sigmaX=0.8)\n    #     # cv2.imshow('1', gabor_img)\n    #     # ret,bimg=cv2.threshold(gabor_img,30,255,cv2.THRESH_BINARY)\n    #     # cv2.imshow('2',bimg)\n    #     # res=cv2.add(res,bimg)\n\n    return clahe_img\n'''\nsigma_x:标准差\ndnum:方向的数目\ns:尺度\nL:tje length od y-direction\n'''\n\n#得到多尺度匹配滤波核\ndef getMultiMatchFilterKernel(sigma,L,theta,s):\n    width=int(np.sqrt((6*sigma+1)**2+L**2))\n    mutilMatchFilter=np.zeros((width,width))\n    if np.mod(width,2)==0:\n        width=width+1\n    halfL=int((width-1)/2)\n    row=1\n    for y in range(halfL,-halfL,-1):\n        col=1\n        for x in range(-halfL,halfL):\n            p=x*np.cos(theta)+y*np.sin(theta)\n            q=x*np.cos(theta)-y*np.sin(theta)\n            if np.abs(p)>3*sigma or np.abs(q)>s*L/2:\n                mutilMatchFilter[row][col]=0\n            else:\n                # mutilMatchFilter[row][col]=-np.exp(-(p**2)/(s*sigma**2))\n                mutilMatchFilter[row][col] = -np.exp(-5*(p/sigma)**2/(np.sqrt(2*np.pi)*sigma*s))\n            col=col+1\n        row=row+1\n    mean=np.sum(mutilMatchFilter)/np.count_nonzero(mutilMatchFilter)\n    mutilMatchFilter[mutilMatchFilter!=0]=mutilMatchFilter[mutilMatchFilter!=0]-mean\n    return mutilMatchFilter\ndef applyMultiMatchFilter(img,sigma_x,L,dnum,s):\n    h,w=img.shape\n    mf_img=np.zeros((h,w,dnum),dtype=np.uint8)\n    # res = np.zeros((h, w, dnum), dtype=np.uint8)\n    for i in range(dnum):\n        multiMatchFilter=getMultiMatchFilterKernel(sigma_x,L,(np.pi/dnum)*i,s)\n        # print(multiMatchFilter)\n        mf_img[:,:,i]=cv2.filter2D(img,ddepth=cv2.CV_8UC3,kernel=multiMatchFilter)\n    # print(mf_img.shape)\n    res=np.max(mf_img,axis=2)\n    return res\n\ndef MMF(enhance_img):\n    # 应用多尺度匹配滤波提取静脉纹路\n    mutil_img1 = applyMultiMatchFilter(enhance_img, 5, 5, 12, 0.03)\n    # cv2.imshow('s=0.03 filter response', mutil_img1)\n    # cv2.imwrite('D:/finger_vein_recognition/003.jpg',mutil_img1)\n    mutil_img2 = applyMultiMatchFilter(enhance_img, 5, 5, 12, 0.06)\n    # cv2.imshow('0.06 filter response', mutil_img2)\n    # cv2.imwrite('D:/finger_vein_recognition/006.jpg',mutil_img2)\n    mutil_img3 = applyMultiMatchFilter(enhance_img, 5, 5, 12, 0.09)\n    # cv2.imshow('0.09 filter response', mutil_img3)\n    # 三个尺度加权乘积\n    res = cv2.multiply(mutil_img1, mutil_img2, scale=0.1)\n    res = cv2.multiply(res, mutil_img3, scale=0.1)\n    #进行形态学处理\n    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\n    res = cv2.morphologyEx(res, cv2.MORPH_CLOSE, kernel, iterations=1)\n    res = cv2.medianBlur(res, 5)\n    # cv2.imshow('multi-scale matched filter response', res)\n    #二值化\n    ret, res = cv2.threshold(res, 40, 255, cv2.THRESH_BINARY)\n    res = cv2.morphologyEx(res, cv2.MORPH_CLOSE, kernel, iterations=1)\n    # cv2.imshow('bi', res)\n    return res\n\n#细化 zhng-suen细化算法\n# 定义像素点周围的8邻域\n#                P9 P2 P3\n#                P8 P1 P4\n#                P7 P6 P5\ndef neighbours(x, y, image):\n    img = image\n    x_1, y_1, x1, y1 = x - 1, y - 1, x + 1, y + 1\n    return [img[x_1][y], img[x_1][y1], img[x][y1], img[x1][y1],  # P2,P3,P4,P5\n            img[x1][y], img[x1][y_1], img[x][y_1], img[x_1][y_1]]  # P6,P7,P8,P9\n\n# 计算邻域像素从0变化到1的次数\ndef transitions(neighbours):\n    n = neighbours + neighbours[0:1]  # P2,P3,...,P8,P9,P2\n    return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))  # (P2,P3),(P3,P4),...,(P8,P9),(P9,P2)\n\ndef delete(img,flag):\n    rows, cols = img.shape\n    for y in range(cols):\n        for x in range(rows):\n            if flag[x][y]==1:\n                img[x,y]=0\n    return img\n\ndef ZhangSuen(img):\n    flag = np.zeros(img.shape)\n    rows,cols=img.shape\n    #step one\n    for y in range(1,cols-1):\n        for x in range(1,rows-1):\n            if img[x][y]==1:#前景点\n                P2, P3, P4, P5, P6, P7, P8, P9 = n = neighbours(x, y, img)\n                if(2<=sum(n)<=6 and transitions(n)==1 and\n                        P2*P4*P6==0 and  P4*P6*P8==0):\n                    flag[x,y]=1\n    if np.sum(flag)>0:\n        img=delete(img,flag)\n        #flag清零\n        flag = np.zeros(img.shape)\n        #step two\n        for y in range(1,cols -1) :\n            for x in range(1,rows -1):\n                if img[x][y] == 1:  # 前景点\n                    P2, P3, P4, P5, P6, P7, P8, P9 = n = neighbours(x, y, img)\n                    if (2 <= sum(n) <= 6 and transitions(n) == 1 and\n                            P2 * P4 * P8 == 0 and P2 * P6 * P8 == 0):\n                        flag[x, y] = 1\n        if np.sum(flag)>0:\n            img=delete(img,flag)\n            img=ZhangSuen(img)\n            return img\n        else:\n            return img\n    else:\n        return img\n\n\ndef findBurr(img,i,j,q):\n    if q.full():\n        while(not q.empty()):\n            index=q.get()\n            img[index[0]][index[1]]=1\n        # print(q.empty())\n        return img\n    else:\n        n = neighbours(i, j, img)\n        if sum(n) > 1:\n            return img\n        else:\n            if sum(n) == 0:\n                img[i][j] = 0\n                return img\n            else:\n                q.put([i, j])\n                img[i][j] = 0\n                for x in range(i - 1, i + 2):\n                    for y in range(j - 1, j + 2):\n                        if img[x][y] == 1:\n                            i = x\n                            j = y\n                            img=findBurr(img,i,j,q)\n                            return img\n#细化的毛刺去除\ndef removeBurr(img):\n    rows,cols=img.shape\n    # print(rows,cols)\n    thresh=25\n    q = Queue(thresh)\n    for i in range(1,rows-1):\n        for j in range(1,cols-1):\n            # print(img[i][j])\n            # print(i,j)\n            if img[i][j]==1:\n                img=findBurr(img,i,j,q)\n                while (not (q.empty())):\n                    q.get()\n                # n = neighbours(i, j, img)\n                # if sum(n)>1:\n                #     continue\n                # else :\n                #     if sum(n)==0:\n                #         img[i][j]=0\n                #     else:\n                #         L=L+1\n                #         q.put([i,j])\n                #         img[i][j]=0\n                #         for x in range(i-1,i+2):\n                #             for y in range(j-1,j+2):\n                #                 if img[x][y]==1:\n                #                     i=x\n                #                     j=y\n    img = black(img)\n    return img\n\n#\n# #先进先出队列\n# q=Queue(maxsize=5)\n\n#四周全黑\ndef black(img):\n    rows,cols=img.shape\n    for i in range(rows):\n        img[i][0]=0\n        img[i][cols-1]=0\n    for j in range(cols):\n        img[0][j]=0\n        img[rows-1][j]=0\n    return img\n\ndef enhanceImage(filename):\n    img = cv2.imread(filename, 0)\n    roi_img = get_ROI(img)\n    # 使用clahe图像增强并中值滤波\n    enhance_img = clahe_gabor(roi_img)\n    enhance_img = cv2.medianBlur(enhance_img, 3)\n    # cv2.imshow('enhance', enhance_img)\n    return enhance_img\n\ndef preImgge(filename):\n    img = cv2.imread(filename, 0)\n    roi_img = get_ROI(img)\n    # 使用clahe图像增强并中值滤波\n    enhance_img = clahe_gabor(roi_img)\n    enhance_img = cv2.medianBlur(enhance_img, 3)\n    # cv2.imshow('enhance', enhance_img)\n    #多尺度匹配滤波\n    res = MMF(enhance_img)\n    res = res / 255\n    #细化\n    xihua = ZhangSuen(res)\n    # cv2.imshow('Zhangsuen', xihua)\n    #细化毛刺去除\n    remove = removeBurr(xihua)\n    # cv2.imshow('remove', remove)\n    # cv2.imwrite('D:/finger_vein_recognition/remove.jpg', remove * 255)\n    # cv2.waitKey(0)\n    # cv2.destroyAllWindows()\n    return remove*255\n\n# preImgge(\"./data/115.bmp\")\n\n\n################代码调试######################\n# img=cv2.imread('./data/115.bmp',0)\n# # equ = cv2.equalizeHist(img)\n# # cv2.imshow('test',equ)\n# # print(img)\n# # gray_normalization(img)\n# #得到ROI\n# roi_img=get_ROI(img)\n#\n# #\n# # print('ROI')\n# # cv2.imshow('roi',roi_img)\n# # print(roi_img.shape)\n# #使用clahe图像增强并中值滤波\n# enhance_img=clahe_gabor(roi_img)\n# enhance_img=cv2.medianBlur(enhance_img,3)\n# cv2.imshow('enhance',enhance_img)\n# # cv2.imwrite('D:/finger_vein_recognition/enhance1.jpg',enhance_img)\n# # enhance_img=roi_img\n# res=MMF(enhance_img)\n# # #应用多尺度匹配滤波提取静脉纹路\n# # mutil_img1=applyMultiMatchFilter(enhance_img,5,5,12,0.03)\n# # cv2.imshow('s=0.03 filter response',mutil_img1)\n# # # cv2.imwrite('D:/finger_vein_recognition/003.jpg',mutil_img1)\n# # mutil_img2=applyMultiMatchFilter(enhance_img,5,5,12,0.06)\n# # cv2.imshow('0.06 filter response',mutil_img2)\n# # # cv2.imwrite('D:/finger_vein_recognition/006.jpg',mutil_img2)\n# # mutil_img3=applyMultiMatchFilter(enhance_img,5,5,12,0.09)\n# # cv2.imshow('0.09 filter response',mutil_img3)\n# # # cv2.imwrite('D:/finger_vein_recognition/009.jpg',mutil_img3)\n# # # res=np.multiply(mutil_img1,mutil_img2)\n# # # res=mutil_img1+mutil_img2+mutil_img3\n# # # for i in range(141):\n# # #     for j in range(350):\n# # #         temp=mutil_img3[i][j]*mutil_img2[i][j]*mutil_img1[i][j]\n# # #         if temp>255:\n# # #             res[i][j]=255\n# # #         if temp<0:\n# # #             res[i][j]=0\n# #\n# # # res=np.multiply(mutil_img3,res)\n# # #三个尺度加权乘积\n# # res=cv2.multiply(mutil_img1,mutil_img2,scale=0.1)\n# # res=cv2.multiply(res,mutil_img3,scale=0.1)\n# # kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\n# # kernel2 = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))\n# # # res=cv2.erode(res,kernel,iterations=2)\n# #\n# # # res=cv2.dilate(res,kernel)\n# # # res=cv2.erode(res,kernel,iterations=2)\n# # # res = cv2.morphologyEx(res, cv2.MORPH_OPEN, kernel, iterations=2)\n# # res = cv2.morphologyEx(res, cv2.MORPH_CLOSE, kernel, iterations=1)\n# # res=cv2.medianBlur(res,5)\n# # cv2.imshow('multi-scale matched filter response',res)\n# # # cv2.imwrite('D:/finger_vein_recognition/mutil.jpg',res)\n# #\n# # # ret2,res = cv2.threshold(res,24,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n# # ret,res=cv2.threshold(res,40,255,cv2.THRESH_BINARY)\n# #\n# #\n# # res = cv2.morphologyEx(res, cv2.MORPH_CLOSE, kernel2, iterations=1)\n# # # res=cv2.erode(res,kernel,iterations=1)\n# #\n# res=res/255\n# #\n# # cv2.imshow('binarization',res)\n#\n#\n#\n#\n# xihua=ZhangSuen(res)\n# cv2.imshow('Zhangsuen',xihua)\n# # # cv2.imwrite('D:/finger_vein_recognition/xihua.jpg',xihua)\n# remove=removeBurr(xihua)\n# # # res=res*255\n# # # res=np.uint8(res)\n# # # print(np.max(res))\n# # # print(type(res))\n# # # res = res.astype(np.uint8)\n# # # print(np.max(res))\n#\n# # # cv2.imwrite('D:/finger_vein_recognition/remove.jpg',remove*255)\n# cv2.imshow('remove',remove)\n# #\n#\n#\n# cv2.waitKey(0)\n# cv2.destroyAllWindows()", "meta": {"hexsha": "dea08c621a24435aa95971222cb8849cc8c4d794", "size": 12724, "ext": "py", "lang": "Python", "max_stars_repo_path": "pretreatment.py", "max_stars_repo_name": "takiee/finger-vein-recognition", "max_stars_repo_head_hexsha": "bf433428a29acc0708398d4566c270d5b43bd69f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-05-11T06:55:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T02:46:01.000Z", "max_issues_repo_path": "pretreatment.py", "max_issues_repo_name": "takiee/finger-vein-recognition", "max_issues_repo_head_hexsha": "bf433428a29acc0708398d4566c270d5b43bd69f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pretreatment.py", "max_forks_repo_name": "takiee/finger-vein-recognition", "max_forks_repo_head_hexsha": "bf433428a29acc0708398d4566c270d5b43bd69f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1862745098, "max_line_length": 101, "alphanum_fraction": 0.5624017605, "include": true, "reason": "import numpy", "num_tokens": 4539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.180904537887272}}
{"text": "import warnings\n\nimport numpy as np\nfrom .lib.coordinates import LocalCoord\n\n# From https://gpsd.gitlab.io/gpsd/NMEA.html - Satellite IDs section\nNMEA_ID_RANGES = (\n  {\n    'range': (1, 32),\n    'constellation': 'GPS'\n  },\n  {\n    'range': (33, 54),\n    'constellation': 'SBAS'\n  },\n  {\n    'range': (55, 64),\n    'constellation': 'SBAS'\n  },\n  {\n    'range': (65, 88),\n    'constellation': 'GLONASS'\n  },\n  {\n    'range': (89, 96),\n    'constellation': 'GLONASS'\n  },\n  {\n    'range': (120, 151),\n    'constellation': 'SBAS'\n  },\n  {\n    'range': (152, 158),\n    'constellation': 'SBAS'\n  },\n  {\n    'range': (173, 182),\n    'constellation': 'IMES'\n  },\n  {\n    'range': (193, 197),\n    'constellation': 'QZNSS'\n  },\n  {\n    'range': (198, 200),\n    'constellation': 'QZNSS'\n  },\n  {\n    'range': (201, 235),\n    'constellation': 'BEIDOU'\n  },\n  {\n    'range': (301, 336),\n    'constellation': 'GALILEO'\n  },\n  {\n    'range': (401, 437),\n    'constellation': 'BEIDOU'\n  }\n)\n\n# Source: RINEX 3.04\nRINEX_CONSTELLATION_IDENTIFIERS = {\n  'GPS': 'G',\n  'GLONASS': 'R',\n  'SBAS': 'S',\n  'GALILEO': 'E',\n  'BEIDOU': 'C',\n  'QZNSS': 'J',\n  'IRNSS': 'I'\n}\n# Make above dictionary bidirectional map:\n# Now you can ask for constellation using:\n# >>> RINEX_CONSTELLATION_IDENTIFIERS['R']\n#     \"GLONASS\"\nRINEX_CONSTELLATION_IDENTIFIERS.update(\n  dict([reversed(i) for i in RINEX_CONSTELLATION_IDENTIFIERS.items()])  # type: ignore\n)\n\n\ndef get_el_az(pos, sat_pos):\n  converter = LocalCoord.from_ecef(pos)\n  sat_ned = converter.ecef2ned(sat_pos)\n  sat_range = np.linalg.norm(sat_ned)\n\n  el = np.arcsin(-sat_ned[2]/sat_range)  # pylint: disable=unsubscriptable-object\n  az = np.arctan2(sat_ned[1], sat_ned[0])  # pylint: disable=unsubscriptable-object\n  return el, az\n\n\ndef get_closest(time, candidates, recv_pos=None):\n  if recv_pos is None:\n    # Takes a list of object that have an epoch(GPSTime) value\n    # and return the one that is closest the given time (GPSTime)\n    tdiff = np.inf\n    closest = None\n    for candidate in candidates:\n      if abs(time - candidate.epoch) < tdiff:\n        closest = candidate\n        tdiff = abs(time - candidate.epoch)\n    return closest\n  else:\n    pdiff = np.inf\n    closest = None\n    for candidate in candidates:\n      cand_diff = np.linalg.norm(recv_pos - candidate.pos)\n      if cand_diff < pdiff and candidate.valid(time, recv_pos):\n        pdiff = cand_diff\n        closest = candidate\n    return closest\n\n\ndef get_constellation(prn):\n  identifier = prn[0]\n\n  if identifier in RINEX_CONSTELLATION_IDENTIFIERS:\n    return RINEX_CONSTELLATION_IDENTIFIERS[identifier]\n  else:\n    warnings.warn(\"Unknown constellation for PRN %s\" % prn)\n    return None\n\n\ndef get_unknown_prn_from_nmea_id(nmea_id):\n  return \"?%d\" % nmea_id\n\n\ndef get_nmea_id_from_unknown_prn(prn):\n  return int(prn[1:])\n\n\ndef is_unknown_prn(prn):\n  return prn[0] == '?'\n\n\ndef get_prn_from_nmea_id(nmea_id):\n  constellation_offsets = {}\n\n  for entry in NMEA_ID_RANGES:\n    start, end = entry['range']\n    constellation = entry['constellation']\n\n    if nmea_id < start:\n      warnings.warn(\"RINEX PRN for nmea id %i not known\" % nmea_id)\n      return get_unknown_prn_from_nmea_id(nmea_id)\n\n    constellation_offset = constellation_offsets.get(constellation, 0)\n\n    if nmea_id <= end:\n      if constellation is None:\n        warnings.warn(\"Constellation for nmea id \"\n                      \"%i not known\" % nmea_id)\n        return get_unknown_prn_from_nmea_id(nmea_id)\n\n      identifier = RINEX_CONSTELLATION_IDENTIFIERS.get(constellation)\n      if identifier is None:\n        warnings.warn(\"RINEX3 constellation identifier for \"\n                      \"constellation %s is not known\" % constellation)\n        return get_unknown_prn_from_nmea_id(nmea_id)\n\n      number = nmea_id - start + 1 + constellation_offset\n      return \"%s%02d\" % (identifier, number)\n    else:\n      range_width = end - start + 1\n      constellation_offsets[constellation] = constellation_offset + range_width\n\n  warnings.warn(\"RINEX PRN for nmea id %i not known\" % nmea_id)\n  return get_unknown_prn_from_nmea_id(nmea_id)\n\n\ndef get_nmea_id_from_prn(prn):\n  if is_unknown_prn(prn):\n    return get_nmea_id_from_unknown_prn(prn)\n\n  prn_constellation = get_constellation(prn)\n  satellite_id = int(prn[1:])\n  if satellite_id < 1:\n    raise ValueError(\"PRN must contains number greater then 0\")\n  constellation_offset = 0\n  for entry in NMEA_ID_RANGES:\n    start, end = entry['range']\n    constellation = entry['constellation']\n    if constellation != prn_constellation:\n      continue\n    range_width = end - start + 1\n    index_in_range = satellite_id - constellation_offset - 1\n    if range_width > index_in_range:\n      return start + index_in_range\n    else:\n      constellation_offset += range_width\n  raise NotImplementedError(\"NMEA ID not found for PRN %s\" % prn)\n\n\ndef rinex3_obs_from_rinex2_obs(observable):\n  if observable == 'P2':\n    return 'C2P'\n  if len(observable) == 2:\n    return observable + 'C'\n  else:\n      raise NotImplementedError(\"Don't know this: \" + observable)\n\n\nclass TimeRangeHolder:\n  '''Class to support test if date is in any of the multiple, sparse ranges'''\n  def __init__(self):\n    # Sorted list\n    self._ranges = []\n\n  def _previous_and_contains_index(self, time):\n    prev = None\n    current = None\n\n    for idx, (start, end) in enumerate(self._ranges):\n      # Time may be in next range\n      if time > end:\n        continue\n\n      # Time isn't in any next range\n      if time < start:\n        prev = idx - 1\n        current = None\n      # Time is in current range\n      else:\n        prev = idx - 1\n        current = idx\n      break\n\n    # Break in last loop\n    if prev is None:\n      prev = len(self._ranges) - 1\n\n    return prev, current\n\n  def add(self, start_time, end_time):\n    prev_start, current_start = self._previous_and_contains_index(start_time)\n    _, current_end = self._previous_and_contains_index(end_time)\n\n    # Merge ranges\n    if current_start is not None and current_end is not None:\n      # If ranges are different then merge\n      if current_start != current_end:\n        new_start, _ = self._ranges[current_start]\n        _, new_end = self._ranges[current_end]\n        new_range = (new_start, new_end)\n        # Required reversed order to correct remove\n        del self._ranges[current_end]\n        del self._ranges[current_start]\n        self._ranges.insert(current_start, new_range)\n    # Extend range - left\n    elif current_start is not None:\n      new_start, _ = self._ranges[current_start]\n      new_range = (new_start, end_time)\n      del self._ranges[current_start]\n      self._ranges.insert(current_start, new_range)\n    # Extend range - right\n    elif current_end is not None:\n      _, new_end = self._ranges[current_end]\n      new_range = (start_time, new_end)\n      del self._ranges[current_end]\n      self._ranges.insert(prev_start + 1, new_range)\n    # Create new range\n    else:\n      new_range = (start_time, end_time)\n      self._ranges.insert(prev_start + 1, new_range)\n\n  def __contains__(self, time):\n    for start, end in self._ranges:\n      # Time may be in next range\n      if time > end:\n        continue\n\n      # Time isn't in any next range\n      if time < start:\n        return False\n      # Time is in current range\n      else:\n        return True\n      return False\n", "meta": {"hexsha": "92f04f1f682539b2794aa15a7499a33f293675c1", "size": 7327, "ext": "py", "lang": "Python", "max_stars_repo_path": "laika/helpers.py", "max_stars_repo_name": "MGNute/laika", "max_stars_repo_head_hexsha": "46a8ebf06e8b6c136bda15ec0d463f663270d877", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-01T07:23:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-01T07:23:56.000Z", "max_issues_repo_path": "laika/helpers.py", "max_issues_repo_name": "MGNute/laika", "max_issues_repo_head_hexsha": "46a8ebf06e8b6c136bda15ec0d463f663270d877", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "laika/helpers.py", "max_forks_repo_name": "MGNute/laika", "max_forks_repo_head_hexsha": "46a8ebf06e8b6c136bda15ec0d463f663270d877", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3561151079, "max_line_length": 86, "alphanum_fraction": 0.6537464174, "include": true, "reason": "import numpy", "num_tokens": 2064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.18090453074992266}}
{"text": "#\n#   Darknet RegionLoss\n#   Copyright EAVISE\n#\n\nimport logging\nimport math\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom distutils.version import LooseVersion\n\ntry:\n    import pandas as pd\nexcept ModuleNotFoundError:\n    pd = None\n\n\n__all__ = ['RegionLoss']\nlog = logging.getLogger(__name__)\ntorchversion = LooseVersion(torch.__version__)\nversion120 = LooseVersion(\"1.2.0\")\n\n\nclass RegionLoss(nn.modules.loss._Loss):\n    \"\"\" Computes region loss from darknet network output and target annotation (yoloV2).\n\n    Args:\n        num_classes (int): number of classes to detect\n        anchors (list): 2D list representing anchor boxes (see :class:`lightnet.network.Darknet`)\n        stride (optional, int): The downsampling factor of the network (input_dimension / output_dimension); Default **32**\n        seen (optional, torch.Tensor): How many images the network has already been trained on; Default **0**\n        coord_scale (optional, float): weight of bounding box coordinates; Default **1.0**\n        noobject_scale (optional, float): weight of regions without target boxes; Default **1.0**\n        object_scale (optional, float): weight of regions with target boxes; Default **5.0**\n        class_scale (optional, float): weight of categorical predictions; Default **1.0**\n        thresh (optional, float): minimum iou between a predicted box and ground truth for them to be considered matching; Default **0.6**\n        coord_prefill (optional, int): This parameter controls for how many training samples the network will prefill the target coordinates, biassing the network to predict the center at **.5,.5**; Default **12800**\n    \"\"\"\n    def __init__(self, num_classes, anchors, stride=32, seen=0, coord_scale=1.0, noobject_scale=1.0, object_scale=5.0, class_scale=1.0, thresh=0.6, coord_prefill=12800):\n        super().__init__()\n        self.num_classes = num_classes\n        self.stride = stride\n        self.num_anchors = len(anchors)\n        self.anchor_step = len(anchors[0])\n        self.anchors = torch.tensor(anchors, dtype=torch.float, requires_grad=False)\n        self.register_buffer('seen', torch.tensor(seen))\n\n        self.coord_scale = coord_scale\n        self.noobject_scale = noobject_scale\n        self.object_scale = object_scale\n        self.class_scale = class_scale\n        self.thresh = thresh\n        self.coord_prefill = coord_prefill\n\n        self.mse = nn.MSELoss(reduction='sum')\n        self.cel = nn.CrossEntropyLoss(reduction='sum')\n\n        self.loss_total = torch.tensor(0.0)\n        self.loss_conf = torch.tensor(0.0)\n        self.loss_coord = torch.tensor(0.0)\n        self.loss_class = torch.tensor(0.0)\n\n    @property\n    def values(self):\n        \"\"\" Return detached sub-losses in a dictionary.\n\n        Note:\n            You can access the individual loss values directly as ``object.loss_<name>`` as well. |br|\n            This will return the actual loss tensor with its attached computational graph and gives you full freedom for modifying this loss prior to the backward pass.\n        \"\"\"\n        return {\n            'total': self.loss_total.detach(),\n            'conf':  self.loss_conf.detach(),\n            'coord': self.loss_coord.detach(),\n            'class': self.loss_class.detach(),\n        }\n\n    @property\n    def loss(self):\n        log.deprecated('The \"loss\" attribute is deprecated in favor for \"loss_total\"')\n        return self.loss_total\n\n    def extra_repr(self):\n        repr_str = f'classes={self.num_classes}, stride={self.stride}, threshold={self.thresh}, seen={self.seen.item()}\\n'\n        repr_str += f'coord_scale={self.coord_scale}, object_scale={self.object_scale}, noobject_scale={self.noobject_scale}, class_scale={self.class_scale}\\n'\n        repr_str += f'anchors='\n        for a in self.anchors:\n            repr_str += f'[{a[0]:.5g}, {a[1]:.5g}] '\n        return repr_str\n\n    def forward(self, output, target, seen=None):\n        \"\"\" Compute Region loss.\n\n        Args:\n            output (torch.autograd.Variable): Output from the network\n            target (brambox annotation dataframe or torch.Tensor): Brambox annotations or tensor containing the annotation targets (see :class:`lightnet.data.BramboxToTensor`)\n            seen (int, optional): How many images the network has already been trained on; Default **Add batch_size to previous seen value**\n\n        Note:\n            If using a target tensor, it should have the dimensions `[num_batch, num_anno, 5]` and following format per image:\n\n            .. math::\n\n                \\\\begin{bmatrix}\n                    class\\\\_idx & x\\\\_center & y\\\\_center & width & height \\\\\\\\\n                    class\\\\_idx & x\\\\_center & y\\\\_center & width & height \\\\\\\\\n                    ... \\\\\\\\\n                    -1 & 0 & 0 & 0 & 0 \\\\\\\\\n                    -1 & 0 & 0 & 0 & 0 \\\\\\\\\n                    ...\n                \\\\end{bmatrix}\n\n            With all coordinates being relative to the image size. |br|\n            Since the annotations from all images of a batch should be made of the same length, you can pad them with: `[-1, 0, 0, 0, 0]`.\n\n        Note:\n            Besides being easier to work with, brambox dataframes have the added benefit that\n            this loss function will also consider the ``ignore`` flag of annotations and ignore detections that match with it.\n            This allows you to have annotations that will not influence the loss in any way,\n            as opposed to having them removed and counting them as false detections.\n        \"\"\"\n        # Parameters\n        nB = output.data.size(0)\n        nA = self.num_anchors\n        nC = self.num_classes\n        nH = output.data.size(2)\n        nW = output.data.size(3)\n        nPixels = nH * nW\n        device = output.device\n        if seen is not None:\n            self.seen = torch.tensor(seen)\n        elif self.training:\n            self.seen += nB\n\n        # Get x,y,w,h,conf,cls\n        output = output.view(nB, nA, -1, nPixels)\n        coord = torch.zeros_like(output[:, :, :4])\n        coord[:, :, :2] = output[:, :, :2].sigmoid()    # tx,ty\n        coord[:, :, 2:4] = output[:, :, 2:4]            # tw,th\n        conf = output[:, :, 4].sigmoid()\n        if nC > 1:\n            cls = output[:, :, 5:].contiguous().view(nB*nA, nC, nPixels).transpose(1, 2).contiguous().view(-1, nC)\n\n        # Create prediction boxes\n        pred_boxes = torch.FloatTensor(nB*nA*nPixels, 4)\n        lin_x = torch.linspace(0, nW-1, nW).repeat(nH, 1).view(nPixels).to(device)\n        lin_y = torch.linspace(0, nH-1, nH).view(nH, 1).repeat(1, nW).view(nPixels).to(device)\n        anchor_w = self.anchors[:, 0].contiguous().view(nA, 1).to(device)\n        anchor_h = self.anchors[:, 1].contiguous().view(nA, 1).to(device)\n\n        pred_boxes[:, 0] = (coord[:, :, 0].detach() + lin_x).view(-1)\n        pred_boxes[:, 1] = (coord[:, :, 1].detach() + lin_y).view(-1)\n        pred_boxes[:, 2] = (coord[:, :, 2].detach().exp() * anchor_w).view(-1)\n        pred_boxes[:, 3] = (coord[:, :, 3].detach().exp() * anchor_h).view(-1)\n        pred_boxes = pred_boxes.cpu()\n\n        # Get target values\n        coord_mask, conf_mask, cls_mask, tcoord, tconf, tcls = self.build_targets(pred_boxes, target, nB, nH, nW)\n        coord_mask = coord_mask.expand_as(tcoord).to(device).sqrt()\n        conf_mask = conf_mask.to(device).sqrt()\n        tcoord = tcoord.to(device)\n        tconf = tconf.to(device)\n        if nC > 1:\n            tcls = tcls[cls_mask].view(-1).long().to(device)\n            cls_mask = cls_mask.view(-1, 1).repeat(1, nC).to(device)\n            cls = cls[cls_mask].view(-1, nC)\n\n        # Compute losses\n        self.loss_coord = self.coord_scale * self.mse(coord*coord_mask, tcoord*coord_mask) / (2 * nB)\n        self.loss_conf = self.mse(conf*conf_mask, tconf*conf_mask) / (2 * nB)\n        if nC > 1:\n            if tcls.numel() > 0:\n                self.loss_class = self.class_scale * self.cel(cls, tcls) / nB\n            else:\n                self.loss_class = torch.tensor(0.0, device=device)\n        else:\n            self.loss_class = torch.tensor(0.0, device=device)\n\n        self.loss_total = self.loss_coord + self.loss_conf + self.loss_class\n        return self.loss_total\n\n    def build_targets(self, pred_boxes, ground_truth, nB, nH, nW):\n        \"\"\" Compare prediction boxes and targets, convert targets to network output tensors \"\"\"\n        if torch.is_tensor(ground_truth):\n            return self.__build_targets_tensor(pred_boxes, ground_truth, nB, nH, nW)\n        elif pd is not None and isinstance(ground_truth, pd.DataFrame):\n            return self.__build_targets_brambox(pred_boxes, ground_truth, nB, nH, nW)\n        else:\n            raise TypeError(f'Unkown ground truth format [{type(ground_truth)}]')\n\n    def __build_targets_tensor(self, pred_boxes, ground_truth, nB, nH, nW):\n        \"\"\" Compare prediction boxes and ground truths, convert ground truths to network output tensors \"\"\"\n        # Parameters\n        nT = ground_truth.size(1)\n        nA = self.num_anchors\n        nAnchors = nA*nH*nW\n        nPixels = nH*nW\n\n        # Tensors\n        coord_mask = torch.zeros(nB, nA, nH, nW, requires_grad=False)\n        conf_mask = torch.ones(nB, nA, nH, nW, requires_grad=False) * self.noobject_scale\n        if torchversion >= version120:\n            cls_mask = torch.zeros(nB, nA, nH, nW, dtype=torch.bool, requires_grad=False)\n        else:\n            cls_mask = torch.zeros(nB, nA, nH, nW, requires_grad=False).byte()\n        tcoord = torch.zeros(nB, nA, 4, nH, nW, requires_grad=False)\n        tconf = torch.zeros(nB, nA, nH, nW, requires_grad=False)\n        tcls = torch.zeros(nB, nA, nH, nW, requires_grad=False)\n\n        if self.training and self.seen < self.coord_prefill:\n            coord_mask.fill_(math.sqrt(.01 / self.coord_scale))\n            if self.anchor_step == 4:\n                tcoord[:, :, 0] = self.anchors[:, 2].contiguous().view(1, nA, 1, 1).repeat(nB, 1, 1, nPixels)\n                tcoord[:, :, 1] = self.anchors[:, 3].contiguous().view(1, nA, 1, 1).repeat(nB, 1, 1, nPixels)\n            else:\n                tcoord[:, :, 0].fill_(0.5)\n                tcoord[:, :, 1].fill_(0.5)\n\n        # Anchors\n        if self.anchor_step == 4:\n            anchors = self.anchors.clone()\n            anchors[:, :2] = 0\n        else:\n            anchors = torch.cat([torch.zeros_like(self.anchors), self.anchors], 1)\n\n        # Loop over GT\n        for b in range(nB):\n            gt = ground_truth[b][(ground_truth[b, :, 0] >= 0)[:, None].expand_as(ground_truth[b])].view(-1, 5)\n            if gt.numel() == 0:     # No gt for this image\n                continue\n\n            # Build up tensors\n            cur_pred_boxes = pred_boxes[b*nAnchors:(b+1)*nAnchors]\n            gt = gt[:, 1:]\n            gt[:, ::2] *= nW\n            gt[:, 1::2] *= nH\n\n            # Set confidence mask of matching detections to 0\n            iou_gt_pred = bbox_ious(gt, cur_pred_boxes)\n            mask = (iou_gt_pred > self.thresh).sum(0) >= 1\n            conf_mask[b][mask.view_as(conf_mask[b])] = 0\n\n            # Find best anchor for each gt\n            iou_gt_anchors = bbox_wh_ious(gt, anchors)\n            _, best_anchors = iou_gt_anchors.max(1)\n\n            # Set masks and target values for each gt\n            nGT = gt.shape[0]\n            gi = gt[:, 0].clamp(0, nW-1).long()\n            gj = gt[:, 1].clamp(0, nH-1).long()\n\n            conf_mask[b, best_anchors, gj, gi] = self.object_scale\n            tconf[b, best_anchors, gj, gi] = iou_gt_pred.view(nGT, nA, nH, nW)[torch.arange(nGT), best_anchors, gj, gi]\n            coord_mask[b, best_anchors, gj, gi] = 2 - (gt[:, 2] * gt[:, 3]) / nPixels\n            tcoord[b, best_anchors, 0, gj, gi] = gt[:, 0] - gi.float()\n            tcoord[b, best_anchors, 1, gj, gi] = gt[:, 1] - gj.float()\n            tcoord[b, best_anchors, 2, gj, gi] = (gt[:, 2] / self.anchors[best_anchors, 0]).log()\n            tcoord[b, best_anchors, 3, gj, gi] = (gt[:, 3] / self.anchors[best_anchors, 1]).log()\n            cls_mask[b, best_anchors, gj, gi] = 1\n            tcls[b, best_anchors, gj, gi] = ground_truth[b, torch.arange(nGT), 0]\n\n        return (\n            coord_mask.view(nB, nA, 1, nPixels),\n            conf_mask.view(nB, nA, nPixels),\n            cls_mask.view(nB, nA, nPixels),\n            tcoord.view(nB, nA, 4, nPixels),\n            tconf.view(nB, nA, nPixels),\n            tcls.view(nB, nA, nPixels)\n        )\n\n    def __build_targets_brambox(self, pred_boxes, ground_truth, nB, nH, nW):\n        \"\"\" Compare prediction boxes and ground truths, convert ground truths to network output tensors \"\"\"\n        # Parameters\n        nA = self.num_anchors\n        nAnchors = nA*nH*nW\n        nPixels = nH*nW\n\n        # Tensors\n        coord_mask = torch.zeros(nB, nA, nH, nW, requires_grad=False)\n        conf_mask = torch.ones(nB, nA, nH, nW, requires_grad=False) * self.noobject_scale\n        if torchversion >= version120:\n            cls_mask = torch.zeros(nB, nA, nH, nW, dtype=torch.bool, requires_grad=False)\n        else:\n            cls_mask = torch.zeros(nB, nA, nH, nW, requires_grad=False).byte()\n        tcoord = torch.zeros(nB, nA, 4, nH, nW, requires_grad=False)\n        tconf = torch.zeros(nB, nA, nH, nW, requires_grad=False)\n        tcls = torch.zeros(nB, nA, nH, nW, requires_grad=False)\n\n        if self.training and self.seen < self.coord_prefill:\n            coord_mask.fill_(math.sqrt(.01 / self.coord_scale))\n            if self.anchor_step == 4:\n                tcoord[:, :, 0] = self.anchors[:, 2].contiguous().view(1, nA, 1, 1).repeat(nB, 1, 1, nPixels)\n                tcoord[:, :, 1] = self.anchors[:, 3].contiguous().view(1, nA, 1, 1).repeat(nB, 1, 1, nPixels)\n            else:\n                tcoord[:, :, 0].fill_(0.5)\n                tcoord[:, :, 1].fill_(0.5)\n\n        # Anchors\n        if self.anchor_step == 4:\n            anchors = self.anchors.clone()\n            anchors[:, :2] = 0\n        else:\n            anchors = torch.cat([torch.zeros_like(self.anchors), self.anchors], 1)\n\n        # Loop over GT\n        for b, gt_filtered in ground_truth.groupby('batch_number', sort=False):\n            cur_pred_boxes = pred_boxes[b*nAnchors:(b+1)*nAnchors]\n\n            # Create ground_truth tensor\n            gt = torch.empty((gt_filtered.shape[0], 4), requires_grad=False)\n            gt[:, 2] = torch.from_numpy(gt_filtered.width.values).float() / self.stride\n            gt[:, 3] = torch.from_numpy(gt_filtered.height.values).float() / self.stride\n            gt[:, 0] = torch.from_numpy(gt_filtered.x_top_left.values).float() / self.stride + (gt[:, 2] / 2)\n            gt[:, 1] = torch.from_numpy(gt_filtered.y_top_left.values).float() / self.stride + (gt[:, 3] / 2)\n\n            # Set confidence mask of matching detections to 0\n            iou_gt_pred = bbox_ious(gt, cur_pred_boxes)\n            mask = (iou_gt_pred > self.thresh).sum(0) >= 1\n            conf_mask[b][mask.view_as(conf_mask[b])] = 0\n\n            # Find best anchor for each gt\n            iou_gt_anchors = bbox_wh_ious(gt, anchors)\n            _, best_anchors = iou_gt_anchors.max(1)\n\n            # Set masks and target values for each gt\n            nGT = gt.shape[0]\n            gi = gt[:, 0].clamp(0, nW-1).long()\n            gj = gt[:, 1].clamp(0, nH-1).long()\n\n            conf_mask[b, best_anchors, gj, gi] = self.object_scale\n            tconf[b, best_anchors, gj, gi] = iou_gt_pred.view(nGT, nA, nH, nW)[torch.arange(nGT), best_anchors, gj, gi]\n            coord_mask[b, best_anchors, gj, gi] = 2 - (gt[:, 2] * gt[:, 3]) / nPixels\n            tcoord[b, best_anchors, 0, gj, gi] = gt[:, 0] - gi.float()\n            tcoord[b, best_anchors, 1, gj, gi] = gt[:, 1] - gj.float()\n            tcoord[b, best_anchors, 2, gj, gi] = (gt[:, 2] / self.anchors[best_anchors, 0]).log()\n            tcoord[b, best_anchors, 3, gj, gi] = (gt[:, 3] / self.anchors[best_anchors, 1]).log()\n            cls_mask[b, best_anchors, gj, gi] = 1\n            tcls[b, best_anchors, gj, gi] = torch.from_numpy(gt_filtered.class_id.values).float()\n\n            # Set masks of ignored to zero\n            if gt_filtered.ignore.any():\n                if torchversion >= version120:\n                    ignore_mask = torch.from_numpy(gt_filtered.ignore.values)\n                else:\n                    ignore_mask = torch.from_numpy(gt_filtered.ignore.values.astype(np.uint8))\n                gi = gi[ignore_mask]\n                gj = gj[ignore_mask]\n                best_anchors = best_anchors[ignore_mask]\n\n                conf_mask[b, best_anchors, gj, gi] = 0\n                coord_mask[b, best_anchors, gj, gi] = 0\n                cls_mask[b, best_anchors, gj, gi] = 0\n\n        return (\n            coord_mask.view(nB, nA, 1, nPixels),\n            conf_mask.view(nB, nA, nPixels),\n            cls_mask.view(nB, nA, nPixels),\n            tcoord.view(nB, nA, 4, nPixels),\n            tconf.view(nB, nA, nPixels),\n            tcls.view(nB, nA, nPixels)\n        )\n\n\ndef bbox_ious(boxes1, boxes2):\n    \"\"\" Compute IOU between all boxes from ``boxes1`` with all boxes from ``boxes2``.\n\n    Args:\n        boxes1 (torch.Tensor): List of bounding boxes\n        boxes2 (torch.Tensor): List of bounding boxes\n\n    Returns:\n        torch.Tensor[len(boxes1) X len(boxes2)]: IOU values\n\n    Note:\n        Tensor format: [[xc, yc, w, h],...]\n    \"\"\"\n    b1x1, b1y1 = (boxes1[:, :2] - (boxes1[:, 2:4] / 2)).split(1, 1)\n    b1x2, b1y2 = (boxes1[:, :2] + (boxes1[:, 2:4] / 2)).split(1, 1)\n    b2x1, b2y1 = (boxes2[:, :2] - (boxes2[:, 2:4] / 2)).split(1, 1)\n    b2x2, b2y2 = (boxes2[:, :2] + (boxes2[:, 2:4] / 2)).split(1, 1)\n\n    dx = (b1x2.min(b2x2.t()) - b1x1.max(b2x1.t())).clamp(min=0)\n    dy = (b1y2.min(b2y2.t()) - b1y1.max(b2y1.t())).clamp(min=0)\n    intersections = dx * dy\n\n    areas1 = (b1x2 - b1x1) * (b1y2 - b1y1)\n    areas2 = (b2x2 - b2x1) * (b2y2 - b2y1)\n    unions = (areas1 + areas2.t()) - intersections\n\n    return intersections / unions\n\n\ndef bbox_wh_ious(boxes1, boxes2):\n    \"\"\" Shorter version of :func:`lightnet.network.loss._regionloss.bbox_ious`\n    for when we are only interested in W/H of the bounding boxes and not X/Y.\n\n    Args:\n        boxes1 (torch.Tensor): List of bounding boxes\n        boxes2 (torch.Tensor): List of bounding boxes\n\n    Returns:\n        torch.Tensor[len(boxes1) X len(boxes2)]: IOU values when discarding X/Y offsets (aka. as if they were zero)\n\n    Note:\n        Tensor format: [[xc, yc, w, h],...]\n    \"\"\"\n    b1w = boxes1[:, 2].unsqueeze(1)\n    b1h = boxes1[:, 3].unsqueeze(1)\n    b2w = boxes2[:, 2]\n    b2h = boxes2[:, 3]\n\n    intersections = b1w.min(b2w) * b1h.min(b2h)\n    unions = (b1w * b1h) + (b2w * b2h) - intersections\n\n    return intersections / unions\n", "meta": {"hexsha": "ab4711080ac0a9ab169da7d15ae47871935ba874", "size": 18689, "ext": "py", "lang": "Python", "max_stars_repo_path": "lightnet/network/loss/_regionloss.py", "max_stars_repo_name": "eavise-kul/lightnet", "max_stars_repo_head_hexsha": "d2d5d3fff8f929c3683c34f176217649375b98e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T05:42:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T04:59:29.000Z", "max_issues_repo_path": "lightnet/network/loss/_regionloss.py", "max_issues_repo_name": "eavise-kul/lightnet", "max_issues_repo_head_hexsha": "d2d5d3fff8f929c3683c34f176217649375b98e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lightnet/network/loss/_regionloss.py", "max_forks_repo_name": "eavise-kul/lightnet", "max_forks_repo_head_hexsha": "d2d5d3fff8f929c3683c34f176217649375b98e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-01-25T20:16:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-29T13:02:34.000Z", "avg_line_length": 44.8177458034, "max_line_length": 216, "alphanum_fraction": 0.5866017443, "include": true, "reason": "import numpy", "num_tokens": 5277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.3174262655876759, "lm_q1q2_score": 0.18088620371133296}}
{"text": "#!/usr/bin/env python\n#import numpypy\nimport sys\nimport os\nimport numpy as np\nimport shutil\nimport random\nimport gzip\nimport math\n\nDelta_PW_warning = 0.1\nROOMT = 298.15\nPH2KCAL = 1.364\nKCAL2KT = 1.688\nKJ2KCAL = 0.239\n\nclass Env:\n    def __init__(self):\n        # Hard coded values\n        self.runprm = \"run.prm\"\n        self.version = \"PyMCCE 1.0\"\n        self.fn_conflist1 = \"head1.lst\"\n        self.fn_conflist2 = \"head2.lst\"\n        self.fn_conflist3 = \"head3.lst\"\n        self.energy_table = \"energies\"\n        self.mc_states = \"microstates\"\n        self.prm = self.load_runprm()\n        self.tpl = {}\n        self.read_extra()\n        return\n\n    def load_runprm(self):\n        float_values = [\"EPSILON_PROT\", \"TITR_PH0\", \"TITR_PHD\", \"TITR_EH0\", \"TITR_EHD\", \"CLASH_DISTANCE\",\n                        \"BIG_PAIRWISE\", \"MONTE_T\", \"MONTE_REDUCE\"]\n        int_values = [\"TITR_STEPS\", \"MONTE_RUNS\", \"MONTE_TRACE\", \"MONTE_NITER\", \"MONTE_NEQ\",\n                      \"MONTE_NSTART\", \"MONTE_FLIPS\", \"NSTATE_MAX\", \"MONTE_NEQ\"]\n        prm = {}\n        print(\"   Loading %s\" % self.runprm)\n        lines = open(self.runprm).readlines()\n        # Sample line: \"t        step 1: pre-run, pdb-> mcce pdb                    (DO_PREMCCE)\"\n        for line in lines:\n            line = line.strip()\n            line = line.split(\"#\")[0]  # This cuts off everything after #\n            left_p = line.rfind(\"(\")\n            right_p = line.rfind(\")\")\n            if left_p > 0 and right_p > left_p + 1:\n                key = line[left_p + 1:right_p]\n                fields = line[:left_p].split()\n                if len(fields) >= 1:\n                    value = fields[0]\n                    if key in float_values:\n                        prm[key] = float(value)\n                    elif key in int_values:\n                        prm[key] = int(value)\n                    else:\n                        prm[key] = value\n        return prm\n\n    def print_runprm(self):\n        for key in self.prm.keys():\n            print(\"%-25s:%s\" % (key, str(self.prm[key])))\n        return\n\n    def load_ftpl(self, file):\n        \"\"\"Load a tpl file.\"\"\"\n        float_values = [\"EXTRA\", \"SCALING\"]\n        int_values = []\n\n        print(\"   Loading ftpl file %s\" % file)\n        lines = open(file).readlines()\n        for line in lines:\n            line = line.split(\"#\")[0]\n            fields = line.split(\":\")\n            if len(fields) != 2:\n                continue\n\n            key_string = fields[0].strip()\n            keys = key_string.split(\",\")\n            keys = [x.strip().strip(\"\\\"\") for x in keys]\n            keys = [x for x in keys if x]\n            keys = tuple(keys)\n\n            value_string = fields[1].strip()\n            if keys[0] in float_values:\n                self.tpl[keys] = float(value_string)\n            elif keys[0] in int_values:\n                self.tpl[keys] = int(value_string)\n            else:\n                self.tpl[keys] = value_string\n\n        return\n\n\n    def load_tpl(self, file):\n        \"\"\"Load a tpl file.\"\"\"\n        print(\"   Loading tpl file %s\" % file)\n        float_values = [\"EXTRA\", \"SCALING\"]\n        int_values = []\n\n        lines = open(file).readlines()\n        for line in lines:\n            line = line.split(\"#\")[0]\n            if len(line) < 21:\n                continue\n            keys = [line[:9], line[9:14], line[15:19]]\n            value_string = line[20:].strip()\n\n            keys = [x for x in keys if x]\n            keys = tuple(keys)\n\n            if keys[0] in float_values:\n                self.tpl[keys] = float(value_string)\n            elif keys[0] in int_values:\n                self.tpl[keys] = int(value_string)\n            else:\n                self.tpl[keys] = value_string\n\n        return\n\n\n    def read_extra(self):\n        \"\"\"Read extra.tpl.\"\"\"\n        fname = self.prm[\"EXTRA\"]\n\n        print(\"   Extra tpl parameters in file %s\" % fname)\n        if os.path.isfile(fname):\n            if fname[-5:] == \".ftpl\":\n                self.load_ftpl(fname)\n            elif fname[-4:] == \".tpl \":\n                self.load_tpl(fname)\n\n        default_values_keys = [(\"SCALING\", \"VDW0\"),\n                               (\"SCALING\", \"VDW1\"),\n                               (\"SCALING\", \"VDW\"),\n                               (\"SCALING\", \"TORS\"),\n                               (\"SCALING\", \"ELE\"),\n                               (\"SCALING\", \"DSOLV\")]\n        for element in default_values_keys:\n            if element not in self.tpl:\n                print(\"      Set to default: %s = 1.0\" % \",\".join(element))\n                self.tpl[element] = 1.0\n\n        return\n\n    def print_scaling(self):\n        \"\"\"Print scaling factors.\"\"\"\n        # print self.param\n        print(\"      Scaling factors:\")\n        print(\"      VDW0  = %.3f\" % self.tpl[(\"SCALING\", \"VDW0\")])\n        print(\"      VDW1  = %.3f\" % self.tpl[(\"SCALING\", \"VDW1\")])\n        print(\"      VDW   = %.3f\" % self.tpl[(\"SCALING\", \"VDW\")])\n        print(\"      TORS  = %.3f\" % self.tpl[(\"SCALING\", \"TORS\")])\n        print(\"      ELE   = %.3f\" % self.tpl[(\"SCALING\", \"ELE\")])\n        print(\"      DSOLV = %.3f\" % self.tpl[(\"SCALING\", \"DSOLV\")])\n        return\n\n\nclass Conformer:\n    def __init__(self, fields):\n        # directly from head3.lst\n        self.iConf = int(fields[0])\n        self.confname = fields[1]\n        self.flag = fields[2].lower()\n        self.on = False\n        self.occ = float(fields[3])\n        self.crg = float(fields[4])\n        self.em0 = float(fields[5])\n        self.pk0 = float(fields[6])\n        self.ne = int(fields[7])\n        self.nh = int(fields[8])\n        self.vdw0 = float(fields[9]) * env.tpl[(\"SCALING\", \"VDW0\")]\n        self.vdw1 = float(fields[10]) * env.tpl[(\"SCALING\", \"VDW1\")]\n        self.tors = float(fields[11]) * env.tpl[(\"SCALING\", \"TORS\")]\n        self.epol = float(fields[12]) * env.tpl[(\"SCALING\", \"ELE\")]\n        self.dsolv = float(fields[13]) * env.tpl[(\"SCALING\", \"DSOLV\")]\n        self.extra = float(fields[14])\n        self.history = fields[15]\n        # needed by MC process\n        self.E_self = 0.0  # self energy in head3.lst\n        self.E_self_mfe = 0.0  # self energy including pairwise contribution from fixed residues\n        return\n\n    def printme(self):\n        print(\"%05d %s %c %4.2f %6.3f %5d %5.2f %2d %2d %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f %s\" % (self.iConf,\n                                                                                                   self.confname,\n                                                                                                   self.flag,\n                                                                                                   self.occ,\n                                                                                                   self.crg,\n                                                                                                   self.em0,\n                                                                                                   self.pk0,\n                                                                                                   self.ne,\n                                                                                                   self.nh,\n                                                                                                   self.vdw0,\n                                                                                                   self.vdw1,\n                                                                                                   self.tors,\n                                                                                                   self.epol,\n                                                                                                   self.dsolv,\n                                                                                                   self.extra,\n                                                                                                   self.history))\n\n\nclass MC_Protein:\n    \"\"\"Monte Carlo Protein data structure.\"\"\"\n\n    def __init__(self):\n        print(\"\\n   Reading and interpreting input energy and conformer list.\")\n        self.head3list, self.confnames = self.read_head3list()\n        self.pairwise = self.read_pairwise()\n        self.fixed_conformers, self.free_residues, self.biglist = self.group_conformers()\n        self.report_residues()\n        return\n\n    def read_head3list(self):\n        head3list = []\n        fname = env.fn_conflist3\n        print(\"      Loading confomer self energy from %s\" % fname)\n\n        lines = open(fname).readlines()\n        lines.pop(0)\n        for line in lines:\n            fields = line.split()\n            if len(fields) >= 16:\n                conf = Conformer(fields)\n                if conf.flag == \"t\":\n                    conf.on = False\n                else:\n                    conf.on = True\n                head3list.append(conf)\n\n        # validate\n        confnames = [x.confname for x in head3list]\n        for name in confnames:\n            if len(name) != 14:\n                print(\"      ERROR: %s is not a conformer name.\")\n                sys.exit()\n            occurrence = confnames.count(name)\n            if occurrence > 1:\n                print(\"      ERROR: Conformer %s occurred %d times\" % (name, occurrence))\n                sys.exit()\n        return head3list, confnames\n\n    def print_headlist(self):\n        for conf in self.head3list:\n            print(\"%05d %s %c %4.2f %6.3f %5d %5.2f %2d %2d %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f %s\" % (conf.iConf,\n                                                                                                       conf.confname,\n                                                                                                       conf.flag,\n                                                                                                       conf.occ,\n                                                                                                       conf.crg,\n                                                                                                       conf.em0,\n                                                                                                       conf.pk0,\n                                                                                                       conf.ne,\n                                                                                                       conf.nh,\n                                                                                                       conf.vdw0,\n                                                                                                       conf.vdw1,\n                                                                                                       conf.tors,\n                                                                                                       conf.epol,\n                                                                                                       conf.dsolv,\n                                                                                                       conf.extra,\n                                                                                                       conf.history))\n        return\n\n    def read_pairwise(self):\n        \"\"\"Read pairwise interactions from opp files in folder.\"\"\"\n        folder = env.energy_table\n        print(\"      Loading pairwise interactions from opp files in folder %s ...\" % folder)\n        n_size = len(self.confnames)\n        pairwise = np.zeros((n_size, n_size))\n        for i in range(n_size):\n            conf = self.head3list[i]\n            oppfile = \"%s/%s.opp\" % (folder, conf.confname)\n            resid_i = conf.confname[:3] + conf.confname[5:11]\n            if os.path.isfile(oppfile):\n                lines = open(oppfile)\n                for line in lines:\n                    fields = line.split()\n                    if len(fields) < 6:\n                        continue\n                    confname = fields[1]\n                    j = self.confnames.index(confname)\n                    if j < 0:\n                        print(\"      Warning: %s in file %s is not a conformer\" % (confname, oppfile))\n                        continue\n\n                    resid_j = confname[:3] + confname[5:11]\n                    if resid_i != resid_j:  # not within a residue\n                        ele = float(fields[2])\n                        vdw = float(fields[3])\n                        pw = ele * env.tpl[(\"SCALING\", \"ELE\")] + vdw * env.tpl[(\"SCALING\", \"VDW\")]\n                        pairwise[i][j] = pw\n\n        # Average pairwise after loading\n        for i in range(n_size - 1):\n            for j in range(i + 1, n_size):\n                pw1 = pairwise[i][j]\n                pw2 = pairwise[j][i]\n                if abs(pw1 - pw2) > Delta_PW_warning:\n                    print(\"         Warning: big pairwise difference between %s: %.3f and %s: %.3f\" % (\n                        self.confnames[i],\n                        pw1,\n                        self.confnames[j],\n                        pw2))\n                pairwise[i][j] = pairwise[j][i] = (pw1 + pw2) / 2\n\n        return pairwise\n\n    def group_conformers(self):\n        fixed_conformers = []\n        free_residues = []\n        residue_ids = []\n        for confname in self.confnames:\n            resid = confname[:3] + confname[5:11]\n            if resid not in residue_ids:\n                residue_ids.append(resid)\n        self.residues = [[] for i in range(len(residue_ids))]  # residue stores indices to conformers\n        for i in range(len(self.confnames)):\n            confname = self.confnames[i]\n            resid = confname[:3] + confname[5:11]\n            index = residue_ids.index(resid)\n            self.residues[index].append(i)\n\n        # Verify head3list flag and occ; Find free and fixed residues\n        # if total occ of \"t\" flagged conformers is 1:\n        # the rest conformers will be set to \"t 0.00\", and this residue is \"fixed\"\n        # else if total occ of \"t\" flagged conformers is 0:\n        # if only one conformer is left:\n        # the lone conformer is set to \"t 1.00\", and this conformer and this residue will be \"fixed\"\n        # else:\n        # this residue is \"free\" and occ of conformers is 0.\n        # otherwise:\n        #    partial fixed occupancy not allowed\n\n        print(\"      Grouping conformers ...\")\n        # Verify flags\n        # Group conformers\n        for res in self.residues:\n            socc = 0.0\n            n_freeconf = len(res)\n            for i in res:\n                if not self.head3list[i].on:\n                    socc += self.head3list[i].occ\n                    n_freeconf -= 1\n                elif abs(self.head3list[i].occ) > 0.001:  # free residue has non-0 occ\n                    print(\"         %s %c %4.2f -> %s f  0.00 (free conformer initial occ = 0)\" % (\n                        self.head3list[i].confname,\n                        self.head3list[i].flag,\n                        self.head3list[i].occ, self.head3list[i].confname))\n                    self.head3list[i].occ = 0.0\n            if abs(socc - 1.0) < 0.001:  # total occ of fixed conformers are 1.0\n                for i in res:\n                    fixed_conformers.append(i)\n                    if self.head3list[i].on:\n                        print(\"         %s %c %4.2f -> %s t  0.00 (fixed conformers already have occ 1.0)\" % (\n                            self.head3list[i].confname,\n                            self.head3list[i].flag, self.head3list[i].occ, self.head3list[i].confname))\n                        self.head3list[i].occ = 0.0\n                        self.head3list[i].on = False\n                        self.head3list[i].flag = \"t\"\n            elif abs(socc) < 0.001:  # total occ is 0\n                if n_freeconf == 1:\n                    for i in res:\n                        if self.head3list[i].on:\n                            print(\"         %s %c %4.2f -> %s t  1.00 (single conformer of the residue)\" % (\n                                self.head3list[\n                                    i].confname,\n                                self.head3list[\n                                    i].flag,\n                                self.head3list[i].occ,\n                                self.head3list[\n                                    i].confname))\n                            self.head3list[i].on = False\n                            self.head3list[i].occ = 1.0\n                            self.head3list[i].flag = \"t\"\n                            fixed_conformers.append(i)\n                            break  # because only one \"f\"\n                else:\n                    free_conformers = []\n                    for i in res:\n                        if not self.head3list[i].on:\n                            fixed_conformers.append(i)\n                        else:\n                            free_conformers.append(i)\n                    free_residues.append(free_conformers)\n            else:  # total occ is neither 0 or 1\n                print(\"      Error: Total residue occupancy is %.2f, 0.00 or 1.00 expected.\" % socc)\n                for i in res:\n                    self.head3list[i].printme()\n                print(\"      Exiting ...\")\n                sys.exit()\n\n        # Make big list. A big list is the size of free residues. It contains other free residue index numbers that\n        # have big interactions\n        bigpw = env.prm[\"BIG_PAIRWISE\"]\n        biglist = [[] for i in range(len(free_residues))]\n        for ir in range(len(free_residues)):\n            for jr in range(ir + 1, len(free_residues)):\n                next_jr = False\n                for ic in free_residues[ir]:\n                    if next_jr:\n                        break\n                    for jc in free_residues[jr]:\n                        if next_jr:\n                            break\n                        pw = self.pairwise[ic][jc]\n                        if abs(pw) >bigpw:\n                            biglist[ir].append(jr)\n                            biglist[jr].append(ir)\n                            next_jr = True\n\n        return fixed_conformers, free_residues, biglist\n\n    def update_energy(self, T=298.15, ph=7.0, eh=0.0):\n        # get self energy\n        for ic in range(len(self.head3list)):\n            conf = self.head3list[ic]\n            E_ph = T / ROOMT * conf.nh * (ph - conf.pk0) * PH2KCAL\n            E_eh = T / ROOMT * conf.ne * (eh - conf.em0) * PH2KCAL / 58.0\n            self.head3list[\n                ic].E_self = conf.vdw0 + conf.vdw1 + conf.epol + conf.tors + conf.dsolv + conf.extra + E_ph + E_eh\n\n            # mfe from fixed conformer\n            mfe = 0.0\n            for jc in self.fixed_conformers:\n                mfe += self.pairwise[ic][jc] * self.head3list[jc].occ\n\n            self.head3list[ic].E_self_mfe = self.head3list[ic].E_self + mfe\n\n    def report_biglist(self):\n        fname = \"biglist.info\"\n        lines = [\"iRes iRes_with_big_interactions\\n\"]\n        for ires in range(len(self.biglist)):\n            biglist = \",\".join([\"%d\" % x for x in self.biglist[ires]])\n            if biglist:\n                lines.append(\"%4d %s\\n\" % (ires, biglist))\n        open(fname, \"w\").writelines(lines)\n        return\n\n    def report_residues(self):\n        fname = \"fixed_conformers.info\"\n        lines = [\"iConf CONFORMER     FL  occ    crg ne nH\\n\"]\n        for ic in self.fixed_conformers:\n            conf = self.head3list[ic]\n            lines.append(\"%5d %s %s %4.2f %6.3f %2d %2d\\n\" % (ic, conf.confname, conf.flag, conf.occ,\n                                                               conf.crg, conf.ne, conf.nh))\n        open(fname, \"w\").writelines(lines)\n\n        fname = \"free_residues.info\"\n        lines = [\"iRes iConf CONFORMER     FL    crg ne nH\\n\"]\n        ires = 0\n        for res in self.free_residues:\n            for ic in res:\n                conf = self.head3list[ic]\n                lines.append(\"%4d %5d %s %s %6.3f %2d %2d\\n\" % (ires, ic, conf.confname, conf.flag,\n                                                               conf.crg, conf.ne, conf.nh))\n            lines.append(\"%s\\n\" % (\".\"*35))\n            ires += 1\n\n        open(fname, \"w\").writelines(lines)\n        return\n\ndef mc_prepdir():\n    # prepare mc folder\n    if os.path.exists(env.mc_states):\n        if os.path.isdir(env.mc_states):\n            shutil.rmtree(env.mc_states)\n        else:\n            os.remove(env.mc_states)\n\n    os.mkdir(env.mc_states)\n\n    return\n\n\ndef mc_sample(prot, T=298.15, ph=7.0, eh=0.0):\n    print(\"   Titration at T = %.2f, ph = %5.2f and eh = %.0f mv\" % (T, ph, eh))\n\n    b = -KCAL2KT / (T / ROOMT)\n    n_free = len(prot.free_residues)\n    nflips = env.prm[\"MONTE_FLIPS\"]\n\n    # get ph and eh patched self energy\n    prot.update_energy(T=T, ph=ph, eh=eh)\n\n    # loop independent runs\n    n_conf = sum([len(x) for x in prot.free_residues])\n    runs = env.prm[\"MONTE_RUNS\"]\n    for i in range(runs):\n        fname = \"ph%.1f-eh%.0f-run%02d.ms\" % (ph, eh, i)\n        #fh = open(fname, \"w\")\n        fh = gzip.open(\"%s.gz\" % fname, \"wb\")\n\n        # randomize a state\n        state = [random.choice(x) for x in prot.free_residues]\n\n        # obtain a complete state\n        line = \"T=%f, ph=%f, eh=%f\\n\" % (T, ph, eh)\n        fh.write(line.encode())\n        E = get_state_energy(prot, state)\n        line = \"%.3f: %s\\n\" % (E, \",\".join([\"%d\" % x for x in state]))\n        fh.write(line.encode())\n\n        # MC sampling\n\n        for iterations in range((env.prm[\"MONTE_NITER\"])*n_conf):\n            old_state = list(state)\n\n            # choose new state\n            ires = random.randrange(n_free)\n            #ires = np.random.randint(n_free)\n            while True:\n                new_conf = random.choice(prot.free_residues[ires])\n                if new_conf != state[ires]:\n                    break\n\n            old_conf = state[ires]\n            state[ires] = new_conf\n\n            dE = prot.head3list[new_conf].E_self_mfe - prot.head3list[old_conf].E_self_mfe\n            for j in range(n_free):\n                dE += prot.pairwise[new_conf][state[j]] - prot.pairwise[old_conf][state[j]]\n\n            # multiflip\n            if prot.biglist[ires]:\n                flip_probablity = 0.5\n                flip_counter = nflips\n                while flip_counter > 0:\n                    if random.random() < flip_probablity:\n                        iflip = random.choice(prot.biglist[ires])\n                        old_conf = state[iflip]\n                        new_conf = random.choice(prot.free_residues[iflip])\n                        state[iflip] = new_conf\n\n                        dE += prot.head3list[new_conf].E_self_mfe - prot.head3list[old_conf].E_self_mfe\n                        for j in range(n_free):\n                            dE += prot.pairwise[new_conf][state[j]] - prot.pairwise[old_conf][state[j]]\n\n                    flip_counter -= 1\n                    flip_probablity = flip_probablity / 2.0\n\n            # evaluate\n            if dE < 0.0:\n                flip = True\n            elif random.random() < math.exp(b*dE):\n                flip = True\n            else:\n                flip = False\n\n            if flip:\n                new = set(state)\n                old = set(old_state)\n                on_confs = new - old\n                off_confs = old - new\n                E += dE\n                line = \"%.3f:\" % E + \",\".join([\"-%d\"%x for x in off_confs])+\",\"+ \",\".join([\"%d\"%x for x in\n                                                                                          on_confs])+\"\\n\"\n                fh.write(line.encode())\n            else:\n                state = old_state\n                fh.write(\"\\n\".encode())\n\n        fh.close()\n\n    return\n\ndef validate_state(prot, state):\n    # each conf in state is in free_residues\n    # each res in free_residues has one and only one conf in state\n    # This makes sure the state is free residues only and garauntees correct energy\n    counters = [0 for x in prot.free_residues]  # on conf occurance in each residue, should be all 1\n    outsiders = []  # on conf not in free residues, should be empty\n\n    for ic in state:\n        found = False\n        for ir in range(len(prot.free_residues)):\n            if ic in prot.free_residues[ir]:\n                counters[ir] += 1\n                found = True\n        if not found:\n            outsiders.append(ic)\n\n    matched = True\n    for ir in range(len(counters)):\n        if counters[ir] == 0:\n            i_1stconf = prot.free_residues[ir][0]\n            confname = prot.confnames[i_1stconf]\n            resid = confname[:3] + confname[5:11]\n            print(\"Free residue %s doesn't have any on-conformer in microstate.\" % resid )\n            matched = False\n        elif counters[ir] > 1:\n            i_1stconf = prot.free_residues[ir][0]\n            confname = prot.confnames[i_1stconf]\n            resid = confname[:3] + confname[5:11]\n            print(\"Free residue %s has multiple on-conformers in microstate.\" % resid )\n            matched = False\n\n    return matched\n\n\ndef get_state_energy(prot, state):\n    E = 0.0\n\n    # all fixed self energy\n    for ic in prot.fixed_conformers:\n        E += prot.head3list[ic].E_self_mfe * prot.head3list[ic].occ\n\n    # minus one side of pw fixed to fixed\n    n_fixed_conformers = len(prot.fixed_conformers)\n    for i in range(n_fixed_conformers -1):\n        ic = prot.fixed_conformers[i]\n        for j in range(i+1, n_fixed_conformers):\n            jc = prot.fixed_conformers[j]\n            E -= prot.pairwise[ic][jc]*prot.head3list[ic].occ*prot.head3list[jc].occ\n\n    # plus self on-conformers\n    for ic in state:\n        E += prot.head3list[ic].E_self_mfe\n\n    # plus pw on-conformer to on-conformer\n    for kc in range(len(state) - 1):\n        ic = state[kc]\n        for lc in range(kc+1, len(state)):\n            jc = state[lc]\n            E += prot.pairwise[ic][jc]\n\n    return E\n\n\ndef get_state_energy_details(prot, state):\n    E = 0.0\n\n    #print(\"Microstate: %s\" % \",\".join([\"%d\" % x for x in state]))\n    # all fixed self energy\n    for ic in prot.fixed_conformers:\n        E += prot.head3list[ic].E_self_mfe * prot.head3list[ic].occ\n        #print(\"%s %.3f\" % (prot.head3list[ic].confname, prot.head3list[ic].occ))\n\n    # minus one side of pw fixed to fixed\n    n_fixed_conformers = len(prot.fixed_conformers)\n    for i in range(n_fixed_conformers -1):\n        ic = prot.fixed_conformers[i]\n        for j in range(i+1, n_fixed_conformers):\n            jc = prot.fixed_conformers[j]\n            E -= prot.pairwise[ic][jc]*prot.head3list[ic].occ*prot.head3list[jc].occ\n\n    #print(state, prot.fixed_conformers)\n    state = list(set(state) - set(prot.fixed_conformers))\n    state.sort()\n    print(state)\n\n    # plus self on-conformers\n    for ic in state:\n        E += prot.head3list[ic].E_self_mfe\n\n    # plus pw on-conformer to on-conformer\n    for kc in range(len(state) - 1):\n        ic = state[kc]\n        for lc in range(kc+1, len(state)):\n            jc = state[lc]\n            E += prot.pairwise[ic][jc]\n\n    return E\n\n\ndef deltaE(prot, state, off_confs, on_confs):\n    \"\"\"\n    Calculate delta E based on conformer difference, state is not altered\n    \"\"\"\n    dE = 0.0\n    for ic in off_confs:\n        dE -= prot.head3list[ic].E_self_mfe\n        state = state - {ic}\n        for jc in list(state):\n            dE -= prot.pairwise[ic][jc]\n    for ic in on_confs:\n        dE += prot.head3list[ic].E_self_mfe\n        for jc in list(state):\n            dE += prot.pairwise[ic][jc]\n        state = state.add(ic)\n\n    return dE\n\n\nenv = Env()\n\nif __name__ == \"__main__\":\n    print(\"This is pymcce module.\")\n    print(\"Use pymonte.py to run mcce step 4.\")\n    prot = MC_Protein()\n    prot.report_biglist()", "meta": {"hexsha": "85abaa8a962fbf2f3d81ba73499958acfc3e29be", "size": 27850, "ext": "py", "lang": "Python", "max_stars_repo_path": "bin/pymccelib.py", "max_stars_repo_name": "caixiuhong/mcce-toolbox", "max_stars_repo_head_hexsha": "de79c8ef6f46b92d0d538a8014fa1d66a4e00f9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bin/pymccelib.py", "max_issues_repo_name": "caixiuhong/mcce-toolbox", "max_issues_repo_head_hexsha": "de79c8ef6f46b92d0d538a8014fa1d66a4e00f9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2019-06-13T18:56:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-25T06:15:34.000Z", "max_forks_repo_path": "bin/pymccelib.py", "max_forks_repo_name": "caixiuhong/mcce-toolbox", "max_forks_repo_head_hexsha": "de79c8ef6f46b92d0d538a8014fa1d66a4e00f9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-06-12T19:27:40.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-24T17:56:40.000Z", "avg_line_length": 40.4796511628, "max_line_length": 117, "alphanum_fraction": 0.449048474, "include": true, "reason": "import numpy", "num_tokens": 6556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.1808861990736315}}
{"text": "import os\nfrom pathlib import Path\nimport fnmatch\nimport subprocess\nfrom collections import namedtuple\nimport tarfile\nimport logging\n\nfrom ..handler import add_handler\n\nimport numpy as np\nimport xarray as xr\nimport rasterio as rio\nfrom rasterio.crs import CRS\n# from rasterio.warp import reproject, Resampling\nfrom affine import Affine\nimport xml.etree.ElementTree as ET\n\ntry:\n    import cv2\n    OPENCV_INSTALLED = True\nexcept:\n    OPENCV_INSTALLED = False\n\n\nlogger = logging.getLogger(__name__)\nlogger = add_handler(logger)\n\n\ndef shift_objects(data,\n                  solar_za,\n                  solar_az,\n                  sensor_za,\n                  sensor_az,\n                  h,\n                  num_workers):\n\n    \"\"\"\n    Shifts objects along x and y dimensions\n\n    Args:\n        data (DataArray): The data to shift.\n        solar_za (DataArray): The solar zenith angle.\n        solar_az (DataArray): The solar azimuth angle.\n        sensor_za (DataArray): The sensor, or view, zenith angle.\n        sensor_az (DataArray): The sensor, or view, azimuth angle.\n        h (float): The object height.\n        num_workers (Optional[int]): The number of dask workers.\n\n    Returns:\n        ``xarray.DataArray``\n    \"\"\"\n\n    # Scale the angles to degrees\n    sza = solar_za * 0.01\n    sza.coords['band'] = [1]\n\n    saa = solar_az * 0.01\n    saa.coords['band'] = [1]\n\n    vza = sensor_za * 0.01\n    vza.coords['band'] = [1]\n\n    vaa = sensor_az * 0.01\n    vaa.coords['band'] = [1]\n\n    # Convert to radians\n    rad_sza = np.deg2rad(sza)\n    rad_saa = np.deg2rad(saa)\n    rad_vza = np.deg2rad(vza)\n    rad_vaa = np.deg2rad(vaa)\n\n    apparent_solar_az = np.pi + np.arctan((np.sin(rad_saa) * np.tan(rad_sza) - np.sin(rad_vaa) * np.tan(rad_vza)) /\n                                          (np.cos(rad_saa) * np.tan(rad_sza) - np.cos(rad_vaa) * np.tan(rad_vza)))\n\n    # Maximum horizontal distance\n    d = (h**2 * ((np.sin(rad_saa) * np.tan(rad_sza) - np.sin(rad_vaa) * np.tan(rad_vza))**2 +\n                 (np.cos(rad_saa) * np.tan(rad_sza) - np.cos(rad_vaa) * np.tan(rad_vza))**2))**0.5\n\n    # Convert the polar angle to cartesian offsets\n    x = int((np.cos(apparent_solar_az) * d).max(skipna=True).data.compute(num_workers=num_workers))\n    y = int((np.sin(apparent_solar_az) * d).max(skipna=True).data.compute(num_workers=num_workers))\n\n    return data.shift(shifts={'x': x, 'y': y}, fill_value=0)\n\n\ndef estimate_cloud_shadows(data,\n                           clouds,\n                           solar_za,\n                           solar_az,\n                           sensor_za,\n                           sensor_az,\n                           heights=None,\n                           num_workers=1):\n\n    \"\"\"\n    Estimates shadows from a cloud mask and adds to the existing mask\n\n    Args:\n        data (DataArray): The wavelengths, scaled 0-1.\n        clouds (DataArray): The cloud mask, where clouds=1 and clear sky=0.\n        solar_za (DataArray): The solar zenith angle.\n        solar_az (DataArray): The solar azimuth angle.\n        sensor_za (DataArray): The sensor, or view, zenith angle.\n        sensor_az (DataArray): The sensor, or view, azimuth angle.\n        heights (Optional[list]): The cloud heights, in kilometers.\n        num_workers (Optional[int]): The number of dask workers.\n\n    Returns:\n        ``xarray.DataArray``\n\n    References:\n\n        For the angle offset calculations, see :cite:`fisher_2014`.\n        For the shadow test, see :cite:`sun_etal_2018`.\n    \"\"\"\n\n    attrs = data.attrs.copy()\n\n    if not heights:\n        heights = list(range(200, 1400, 200))\n\n    shadows = None\n\n    for h in heights:\n\n        potential_shadows = shift_objects(clouds,\n                                          solar_za,\n                                          solar_az,\n                                          sensor_za,\n                                          sensor_az,\n                                          h,\n                                          num_workers)\n\n        if not isinstance(shadows, xr.DataArray):\n            shadows = xr.where((data.sel(band='nir') < 0.25) & (data.sel(band='swir1') < 0.11) & (potential_shadows.sel(band='mask') == 1), 1, 0)\n        else:\n            shadows = xr.where(((data.sel(band='nir') < 0.25) & (data.sel(band='swir1') < 0.11) & (potential_shadows.sel(band='mask') == 1)) | shadows.sel(band='mask') == 1, 1, 0)\n\n        shadows = shadows.expand_dims(dim='band')\n\n    # Add the shadows to the cloud mask\n    data = xr.where(clouds.sel(band='mask') == 1, 1, xr.where(shadows.sel(band='mask') == 1, 2, 0))\n    data = data.expand_dims(dim='band')\n    data.attrs = attrs\n\n    return data\n\n\ndef scattering_angle(cos_sza, cos_vza, sin_sza, sin_vza, cos_raa):\n\n    \"\"\"\n    Calculates the scattering angle\n\n    Args:\n        cos_sza (DataArray): The cosine of the solar zenith angle.\n        cos_vza (DataArray): The cosine of the view zenith angle.\n        sin_sza (DataArray): The sine of the solar zenith angle.\n        sin_vza (DataArray): The sine of the view zenith angle.\n        cos_raa (DataArray): The cosine of the relative azimuth angle.\n\n    Equation:\n\n        .. math::\n\n            \\Theta = scattering angle\n\n            \\theta_0 = solar zenith angle\n\n            \\theta_S = sensor zenith angle\n\n            \\zeta = relative azimuth angle\n\n            \\Theta_s = \\arccos{- \\cos{\\theta_0} \\cos{\\theta_S} - \\sin{\\theta_0} \\sin{\\theta_S} \\cos{\\zeta}}\n\n    References:\n        scattering angle = the angle between the direction of incident and scattered radiation\n        Liu, CH and Liu GR (2009) AEROSOL OPTICAL DEPTH RETRIEVAL FOR SPOT HRV IMAGES, Journal of Marine Science and Technology\n        http://stcorp.github.io/harp/doc/html/algorithms/derivations/scattering_angle.html\n\n    Returns:\n        Scattering angle (in radians) as an ``xarray.DataArray``\n    \"\"\"\n\n    scattering_angle = xr.ufuncs.arccos(-cos_sza * cos_vza - sin_sza * sin_vza * cos_raa)\n\n    return xr.ufuncs.cos(scattering_angle) ** 2\n\n\ndef relative_azimuth(saa, vaa):\n\n    \"\"\"\n    Calculates the relative azimuth angle\n\n    Args:\n        saa (DataArray): The solar azimuth angle (in degrees).\n        vaa (DataArray): The view azimuth angle (in degrees).\n\n    Reference:\n        http://stcorp.github.io/harp/doc/html/algorithms/derivations/relative_azimuth_angle.html\n\n    Returns:\n        Relative azimuth (in degrees) as an ``xarray.DataArray``\n    \"\"\"\n\n    # Relative azimuth (in radians)\n    raa = xr.ufuncs.deg2rad(saa - vaa)\n\n    # Create masks\n    raa_plus = xr.where(raa >= 2.0*np.pi, 1, 0)\n    raa_minus = xr.where(raa < 0, 1, 0)\n\n    # raa = xr.where(raa_plus == 1, raa + (2.0*np.pi), raa)\n    # raa = xr.where(raa_minus == 1, raa - (2.0*np.pi), raa)\n\n    raa = xr.where(raa_plus == 1, raa - (2.0 * np.pi), raa)\n    raa = xr.where(raa_minus == 1, raa + (2.0 * np.pi), raa)\n\n    return xr.ufuncs.fabs(xr.ufuncs.rad2deg(raa))\n\n\ndef get_sentinel_sensor(metadata):\n\n    # Parse the XML file\n    tree = ET.parse(metadata)\n    root = tree.getroot()\n\n    for child in root:\n\n        if 'general_info' in child.tag[-14:].lower():\n            general_info = child\n\n    for ginfo in general_info:\n\n        if ginfo.tag == 'TILE_ID':\n            file_name = ginfo.text\n\n    return file_name[:3].lower()\n\n\ndef parse_sentinel_angles(metadata, proc_angles, nodata):\n\n    \"\"\"\n    Gets the Sentinel-2 solar angles from metadata\n\n    Args:\n        metadata (str): The metadata file.\n        proc_angles (str): The angles to parse. Choices are ['solar', 'view'].\n        nodata (int or float): The 'no data' value.\n\n    Returns:\n        zenith and azimuth angles as a ``tuple`` of 2d ``numpy`` arrays\n    \"\"\"\n\n    if proc_angles == 'view':\n\n        zenith_values = np.zeros((13, 23, 23), dtype='float64') + nodata\n        azimuth_values = np.zeros((13, 23, 23), dtype='float64') + nodata\n\n    else:\n\n        zenith_values = np.zeros((23, 23), dtype='float64') + nodata\n        azimuth_values = np.zeros((23, 23), dtype='float64') + nodata\n\n    view_tag = 'Sun_Angles_Grid' if proc_angles == 'solar' else 'Viewing_Incidence_Angles_Grids'\n\n    # Parse the XML file\n    tree = ET.parse(metadata)\n    root = tree.getroot()\n\n    # Find the angles\n    for child in root:\n\n        if child.tag.split('}')[-1] == 'Geometric_Info':\n            geoinfo = child\n            break\n\n    for segment in geoinfo:\n\n        if segment.tag == 'Tile_Angles':\n            angles = segment\n\n    for angle in angles:\n\n        if angle.tag == view_tag:\n\n            if proc_angles == 'view':\n                band_id = int(angle.attrib['bandId'])\n\n            for bset in angle:\n\n                if bset.tag == 'Zenith':\n                    zenith = bset\n                if bset.tag == 'Azimuth':\n                    azimuth = bset\n\n            for field in zenith:\n\n                if field.tag == 'Values_List':\n                    zvallist = field\n\n            for field in azimuth:\n\n                if field.tag == 'Values_List':\n                    avallist = field\n\n            for rindex in range(len(zvallist)):\n\n                zvalrow = zvallist[rindex]\n                avalrow = avallist[rindex]\n                zvalues = zvalrow.text.split(' ')\n                avalues = avalrow.text.split(' ')\n                values = list(zip(zvalues, avalues))\n\n                for cindex in range(len(values)):\n\n                    if (values[cindex][0].lower() != 'nan') and (values[cindex][1].lower() != 'nan'):\n\n                        ze = float(values[cindex][0])\n                        az = float(values[cindex][1])\n\n                        if proc_angles == 'view':\n\n                            zenith_values[band_id, rindex, cindex] = ze\n                            azimuth_values[band_id, rindex, cindex] = az\n\n                        else:\n\n                            zenith_values[rindex, cindex] = ze\n                            azimuth_values[rindex, cindex] = az\n\n    return zenith_values, azimuth_values\n\n\ndef sentinel_pixel_angles(metadata,\n                          ref_file,\n                          outdir='.',\n                          nodata=-32768,\n                          overwrite=False,\n                          verbose=0):\n\n    \"\"\"\n    Generates Sentinel pixel angle files\n\n    Args:\n        metadata (str): The metadata file.\n        ref_file (str): A reference image to use for geo-information.\n        outdir (Optional[str])): The output directory to save the angle files to.\n        nodata (Optional[int or float]): The 'no data' value.\n        overwrite (Optional[bool]): Whether to overwrite existing angle files.\n        verbose (Optional[int]): The verbosity level.\n\n    References:\n        https://www.sentinel-hub.com/faq/how-can-i-access-meta-data-information-sentinel-2-l2a\n        https://github.com/marujore/sentinel_angle_bands/blob/master/sentinel2_angle_bands.py\n\n    Returns:\n        zenith and azimuth angles as a ``namedtuple`` of angle file names\n    \"\"\"\n\n    if not OPENCV_INSTALLED:\n        logger.exception('OpenCV must be installed.')\n\n    AngleInfo = namedtuple('AngleInfo', 'vza vaa sza saa sensor')\n\n    sza, saa = parse_sentinel_angles(metadata, 'solar', nodata)\n    vza, vaa = parse_sentinel_angles(metadata, 'view', nodata)\n\n    sensor_name = get_sentinel_sensor(metadata)\n\n    with rio.open(ref_file) as src:\n\n        profile = src.profile.copy()\n\n        ref_height = src.height\n        ref_width = src.width\n        ref_extent = src.bounds\n\n        profile.update(transform=Affine(src.res[0], 0.0, ref_extent.left, 0.0, -src.res[1], ref_extent.top),\n                       height=ref_height,\n                       width=ref_width,\n                       nodata=-32768,\n                       dtype='int16',\n                       count=1,\n                       driver='GTiff',\n                       tiled=True,\n                       compress='lzw')\n\n    ref_base = '_'.join(os.path.basename(ref_file).split('_')[:-1])\n\n    opath = Path(outdir)\n\n    opath.mkdir(parents=True, exist_ok=True)\n\n    # Set output angle file names.\n    sensor_azimuth_file = opath.joinpath(ref_base + '_sensor_azimuth.tif').as_posix()\n    sensor_zenith_file = opath.joinpath(ref_base + '_sensor_zenith.tif').as_posix()\n    solar_azimuth_file = opath.joinpath(ref_base + '_solar_azimuth.tif').as_posix()\n    solar_zenith_file = opath.joinpath(ref_base + '_solar_zenith.tif').as_posix()\n\n    for angle_array, angle_file in zip([vaa,\n                                        vza,\n                                        saa,\n                                        sza],\n                                       [sensor_azimuth_file,\n                                        sensor_zenith_file,\n                                        solar_azimuth_file,\n                                        solar_zenith_file]):\n\n        pfile = Path(angle_file)\n\n        if overwrite:\n\n            if pfile.is_file():\n                pfile.unlink()\n\n        if not pfile.is_file():\n\n            # TODO: write data for each band?\n            if len(angle_array.shape) > 2:\n                angle_array = angle_array.mean(axis=0)\n\n            with rio.open(angle_file, mode='w', **profile) as dst:\n\n                if verbose > 0:\n                    logger.info('  Writing {} to file ...'.format(angle_file))\n\n                # Resample and scale\n                angle_array_resamp = np.int16(cv2.resize(angle_array,\n                                                         (0, 0),\n                                                         fy=ref_height / angle_array.shape[0],\n                                                         fx=ref_width / angle_array.shape[1],\n                                                         interpolation=cv2.INTER_LINEAR) / 0.01)\n\n                dst.write(angle_array_resamp, indexes=1)\n\n    return AngleInfo(vaa=str(sensor_azimuth_file),\n                     vza=str(sensor_zenith_file),\n                     saa=str(solar_azimuth_file),\n                     sza=str(solar_zenith_file),\n                     sensor=sensor_name)\n\n\n# Potentially useful for angle creation\n# https://github.com/gee-community/gee_tools/blob/master/geetools/algorithms.py\n\n# def slope_between(a, b):\n#     return (a[1] - b[1]) / (a[0] - b[0])\n#\n#\n# @nb.jit\n# def _calc_sensor_angles(data,\n#                         zenith_angles,\n#                         azimuth_angles,\n#                         yvalues,\n#                         xvalues,\n#                         celly,\n#                         cellx,\n#                         satellite_height,\n#                         nodata,\n#                         acquisition_date):\n#\n#     \"\"\"\n#     Calculates sensor zenith and azimuth angles\n#     \"\"\"\n#\n#     slope = slope_between(np.array([data.gw.meta.right + ((data.gw.ncols/2.0)*data.gw.cellx), data.gw.meta.top]),\n#                           np.array([data.gw.meta.left, data.gw.meta.top - ((data.gw.nrows / 2.0) * data.gw.celly)]))\n#\n#     slope_perc = -1.0 / slope\n#\n#     view_az = (math.pi / 2.0) - math.arctan(slope_perc)\n#\n#     for i in range(0, yvalues.shape[0]):\n#\n#         for j in range(0, xvalues.shape[0]):\n#\n#             if data_band[i, j] != nodata:\n#\n#                 # TODO: calculate satellite drift angle\n#                 dist_from_nadir = None\n#\n#                 # Calculate the distance from the current location to the satellite\n#                 dist_to_satellite = np.hypot(satellite_height, dist_from_nadir)\n#\n#                 # Calculate the view angle\n#\n#                 zenith_angles[i, j]\n#\n#                 # Solar zenith angle = 90 - elevation angle scaled to integer range\n#                 zenith_angles[i, j] = (90.0 - get_altitude_fast(xvalues[j], yvalues[i], acquisition_date)) / 0.01\n#\n#                 # Solar azimuth angle\n#                 azimuth_angles[i, j] = float(get_azimuth_fast(xvalues[j], yvalues[i], acquisition_date)) / 0.01\n#\n#     return zenith_angles, azimuth_angles\n\n\n# @nb.jit\n# def _calc_solar_angles(data_band, zenith_angles, azimuth_angles, yvalues, xvalues, nodata, acquisition_date):\n#\n#     \"\"\"\n#     Calculates solar zenith and azimuth angles\n#     \"\"\"\n#\n#     for i in range(0, yvalues):\n#\n#         for j in range(0, xvalues):\n#\n#             if data_band[i, j] != nodata:\n#\n#                 # Solar zenith angle = 90 - elevation angle scaled to integer range\n#                 zenith_angles[i, j] = (90.0 - get_altitude_fast(xvalues[j], yvalues[i], acquisition_date)) / 0.01\n#\n#                 # Solar azimuth angle\n#                 azimuth_angles[i, j] = float(get_azimuth_fast(xvalues[j], yvalues[i], acquisition_date)) / 0.01\n#\n#     return zenith_angles, azimuth_angles\n\n\n# def pixel_angles(data, band, nodata, meta):\n#\n#     \"\"\"\n#     Generates pixel zenith and azimuth angles\n#\n#     Args:\n#         data (Xarray): The data with coordinate and transform attributes.\n#         band (int or str): The ``data`` band to use for masking.\n#         nodata (int or float): The 'no data' value in ``data``.\n#         meta (namedtuple): The metadata file. Should have image acquisition year, month, day and hour attributes.\n#     \"\"\"\n#\n#     acquisition_date = dtime(meta.year, meta.month, meta.day, meta.hour, 0, 0, 0, tzinfo=datetime.timezone.utc)\n#\n#     yvalues = data.y.values\n#     xvalues = data.x.values\n#\n#     data_band = data.sel(band=band).data.compute()\n#     sze = np.zeros((data.gw.nrows, data.gw.ncols), dtype='int16') - 32768\n#     saa = np.zeros((data.gw.nrows, data.gw.ncols), dtype='int16') - 32768\n#\n#     sze, saa = _calc_solar_angles(data_band, sze, saa, yvalues, xvalues, nodata, acquisition_date)\n#\n#     sze_attrs = data.attrs.copy()\n#     saa_attrs = data.attrs.copy()\n#\n#     sze_attrs['values'] = 'Solar zenith angle'\n#     sze_attrs['scale_factor'] = 0.01\n#\n#     saa_attrs['values'] = 'Solar azimuth angle'\n#     sze_attrs['scale_factor'] = 0.01\n#\n#     szex = xr.DataArray(data=da.from_array(sze[np.newaxis, :, :],\n#                                            chunks=(1, data.gw.row_chunks, data.gw.col_chunks)),\n#                         coords={'band': 'sze',\n#                                 'y': data.y,\n#                                 'x': data.x},\n#                         dims=('band', 'y', 'x'),\n#                         attrs=sze_attrs)\n#\n#     saax = xr.DataArray(data=da.from_array(saa[np.newaxis, :, :],\n#                                            chunks=(1, data.gw.row_chunks, data.gw.col_chunks)),\n#                         coords={'band': 'saa',\n#                                 'y': data.y,\n#                                 'x': data.x},\n#                         dims=('band', 'y', 'x'),\n#                         attrs=saa_attrs)\n#\n#     return szex, saax\n\n\ndef landsat_pixel_angles(angles_file,\n                         ref_file,\n                         out_dir,\n                         sensor,\n                         l57_angles_path=None,\n                         l8_angles_path=None,\n                         subsample=1,\n                         resampling='bilinear',\n                         num_threads=1,\n                         verbose=0):\n\n    \"\"\"\n    Generates Landsat pixel angle files\n\n    Args:\n        angles_file (str): The angles file.\n        ref_file (str): A reference file.\n        out_dir (str): The output directory.\n        sensor (str): The sensor.\n        l57_angles_path (str): The path to the Landsat 5 and 7 angles bin.\n        l8_angles_path (str): The path to the Landsat 8 angles bin.\n        subsample (Optional[int]): The sub-sample factor when calculating the angles.\n        resampling (Optional[str]): The resampling method if ``filename`` is a ``list``.\n            Choices are ['average', 'bilinear', 'cubic', 'cubic_spline', 'gauss', 'lanczos', 'max', 'med', 'min', 'mode', 'nearest'].\n        num_threads (Optional[int]): The number of threads to pass to ``rasterio.warp.reproject``.\n        verbose (Optional[int]): The verbosity level.\n\n    Returns:\n        zenith and azimuth angles as a ``namedtuple`` of angle file names\n    \"\"\"\n\n    if not l57_angles_path:\n\n        gw_bin = os.path.realpath(os.path.dirname(__file__))\n\n        gw_out = os.path.realpath(Path(gw_bin).joinpath('../bin').as_posix())\n        gw_tar = os.path.realpath(Path(gw_bin).joinpath('../bin/ESPA.tar.gz').as_posix())\n\n        if not Path(gw_bin).joinpath('../bin/ESPA').is_dir():\n\n            with tarfile.open(gw_tar, mode='r:gz') as tf:\n                tf.extractall(gw_out)\n\n        l57_angles_path = Path(gw_out).joinpath('ESPA/landsat_angles').as_posix()\n        l8_angles_path = Path(gw_out).joinpath('ESPA/l8_angles').as_posix()\n\n    AngleInfo = namedtuple('AngleInfo', 'vza vaa sza saa')\n\n    # Setup the angles name.\n    # example file = LE07_L1TP_225098_20160911_20161008_01_T1_sr_band1.tif\n\n    with rio.open(ref_file) as src:\n\n        ref_res = src.res\n        ref_height = src.height\n        ref_width = src.width\n        ref_extent = src.bounds\n\n    ref_base = '_'.join(os.path.basename(ref_file).split('_')[:-1])\n\n    opath = Path(out_dir)\n\n    opath.mkdir(parents=True, exist_ok=True)\n\n    # Set output angle file names.\n    sensor_azimuth_file = opath.joinpath(ref_base + '_sensor_azimuth.tif').as_posix()\n    sensor_zenith_file = opath.joinpath(ref_base + '_sensor_zenith.tif').as_posix()\n    solar_azimuth_file = opath.joinpath(ref_base + '_solar_azimuth.tif').as_posix()\n    solar_zenith_file = opath.joinpath(ref_base + '_solar_zenith.tif').as_posix()\n\n    if not Path(sensor_azimuth_file).is_file():\n\n        # Setup the command.\n        if sensor.lower() in ['l5', 'l7']:\n\n            angle_command = '{PATH} {META} -s {SUBSAMP:d} -b 1'.format(PATH=str(Path(l57_angles_path).joinpath('landsat_angles')),\n                                                                       META=angles_file,\n                                                                       SUBSAMP=subsample)\n\n            # 1=zenith, 2=azimuth\n            out_order = dict(azimuth=2, zenith=1)\n            # out_order = [2, 1, 2, 1]\n\n        else:\n\n            angle_command = '{PATH} {META} BOTH {SUBSAMP:d} -f -32768 -b 4'.format(PATH=str(Path(l8_angles_path).joinpath('l8_angles')),\n                                                                                   META=angles_file,\n                                                                                   SUBSAMP=subsample)\n\n            # 1=azimuth, 2=zenith\n            out_order = dict(azimuth=1, zenith=2)\n            # out_order = [1, 2, 1, 2]\n\n        os.chdir(out_dir)\n\n        if verbose > 0:\n            logger.info('  Generating pixel angles ...')\n\n        # Create the angle files.\n        subprocess.call(angle_command, shell=True)\n\n        # Get angle data from 1 band.\n        sensor_angles = fnmatch.filter(os.listdir(out_dir), '*sensor_B04.img')[0]\n        solar_angles = fnmatch.filter(os.listdir(out_dir), '*solar_B04.img')[0]\n\n        sensor_angles_fn_in = opath.joinpath(sensor_angles).as_posix()\n        solar_angles_fn_in = opath.joinpath(solar_angles).as_posix()\n\n        # Convert the data\n        for in_angle, out_angle, band_pos in zip([sensor_angles_fn_in,\n                                                  sensor_angles_fn_in,\n                                                  solar_angles_fn_in,\n                                                  solar_angles_fn_in],\n                                                 [sensor_azimuth_file,\n                                                  sensor_zenith_file,\n                                                  solar_azimuth_file,\n                                                  solar_zenith_file],\n                                                 ['azimuth',\n                                                  'zenith',\n                                                  'azimuth',\n                                                  'zenith']):\n\n            new_res = subsample*ref_res[0]\n\n            # Update the .hdr file\n            with open(in_angle + '.hdr', mode='r') as txt:\n\n                lines = txt.readlines()\n\n                for lidx, line in enumerate(lines):\n                    if line.startswith('map info'):\n                        lines[lidx] = line.replace('30.000, 30.000', f'{new_res:.3f}, {new_res:.3f}')\n\n            Path(in_angle + '.hdr').unlink()\n\n            with open(in_angle + '.hdr', mode='w') as txt:\n                txt.writelines(lines)\n\n            with rio.open(in_angle) as src:\n\n                profile = src.profile.copy()\n\n                epsg = src.crs.to_epsg()\n\n                # Adjust Landsat images in the Southern hemisphere\n                if str(epsg).startswith('326') and (ref_extent.top < 0):\n\n                    transform = Affine(new_res, 0.0, ref_extent.left, 0.0, -new_res, ref_extent.top+10_000_000.0)\n                    crs = CRS.from_epsg(f'327{str(epsg)[3:]}')\n\n                else:\n\n                    transform = Affine(new_res, 0.0, ref_extent.left, 0.0, -new_res, ref_extent.top)\n                    crs = src.crs\n\n                profile.update(transform=transform,\n                               crs=crs,\n                               height=src.height,\n                               width=src.width,\n                               nodata=-32768,\n                               dtype='int16',\n                               count=1,\n                               driver='GTiff',\n                               tiled=True,\n                               compress='lzw')\n\n                # src_band = rio.Band(src, out_order[band_pos], 'int16', (src.height, src.width))\n\n                with rio.open(out_angle, mode='w', **profile) as dst:\n\n                    dst.write(src.read(out_order[band_pos]),\n                              indexes=1)\n\n                    # dst_band = rio.Band(dst, 1, 'int16', (dst.height, dst.width))\n                    #\n                    # reproject(src_band,\n                    #           destination=dst_band,\n                    #           resampling=getattr(Resampling, resampling),\n                    #           num_threads=num_threads)\n\n    os.chdir(os.path.expanduser('~'))\n\n    return AngleInfo(vaa=str(sensor_azimuth_file),\n                     vza=str(sensor_zenith_file),\n                     saa=str(solar_azimuth_file),\n                     sza=str(solar_zenith_file))\n", "meta": {"hexsha": "a7d26817043dff4bd8b961f279454bbd1befd678", "size": 26266, "ext": "py", "lang": "Python", "max_stars_repo_path": "geowombat/radiometry/angles.py", "max_stars_repo_name": "jgrss/geowombat", "max_stars_repo_head_hexsha": "e691102a3dcce13b272810b43bc9586681ae6934", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2020-01-13T22:45:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:44:35.000Z", "max_issues_repo_path": "geowombat/radiometry/angles.py", "max_issues_repo_name": "jgrss/geowombat", "max_issues_repo_head_hexsha": "e691102a3dcce13b272810b43bc9586681ae6934", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2020-01-27T00:57:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T19:52:20.000Z", "max_forks_repo_path": "geowombat/radiometry/angles.py", "max_forks_repo_name": "jgrss/geowombat", "max_forks_repo_head_hexsha": "e691102a3dcce13b272810b43bc9586681ae6934", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-01-14T19:27:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-23T03:08:37.000Z", "avg_line_length": 34.6517150396, "max_line_length": 179, "alphanum_fraction": 0.5326277317, "include": true, "reason": "import numpy", "num_tokens": 6265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.31742625913050115, "lm_q1q2_score": 0.18088619539399342}}
{"text": "import logging_setup\nimport logging\nimport numpy as np\nimport openfermion as of\nimport os\nimport qiskit as qk\nimport qiskit.opflow as qk_opflow\nimport qiskit.quantum_info as qk_qi\nimport uccsd_evolution\nimport scipy.linalg as spla\nimport warnings\n\ntry:\n    from hubbard_bqskit import BQSKit_Hubbard_Optimizer\nexcept ImportError:\n    pass\n\n__all__ = [\n    'EnergyObjective',\n    'hamiltonian_matrix',\n    'hamiltonian_qiskit',\n    'small_model',\n    'medium_model',\n    'clear_circuit_cache',\n    'get_cached_circuit',\n]\n\nlogger = logging.getLogger('hubbard')\n\n\n# Allow caching of the trotterized opflow, post-BQSKit, for noise studies\n_cached_circuit = None\n\ndef clear_circuit_cache():\n    global _cached_circuit\n    _cached_circuit = None\n\ndef get_cached_circuit():\n   return _cached_circuit\n\n\nclass EnergyObjective:\n    def __init__(self, hamiltonian, n_electrons_up, n_electrons_down,\n                 trotter_steps=2, noise_model=None, shots=-1,\n                 run_bqskit=False, save_evals=None):\n        \"\"\"\\\n        Create an energy estimater for the given Hamiltonian\n\n        Args:\n            hamiltonian(opflow): Hamiltonian operator\n            n_electrons_up(int): number of spin-up electrons in the physical system\n            n_electrons_down(int): number of spin-down electrons in the physical system\n            trotter_steps(int): number of Trotter time slices for the evolution\n            noise_model(NoiseModel): Qiskit noise model to apply\n            shots(int): number of shots to sample and average over\n            run_bqskit(bool): whether to run the bqskit stack on the evolution operator\n            save_evals(str): file name to store evaluations or None\n        \"\"\"\n\n        self._hamiltonian = hamiltonian\n        self._n_qubits         = hamiltonian.num_qubits\n        self._n_electrons      = n_electrons_up + n_electrons_down\n\n        try:\n            self._fermion_transform = hamiltonian._fermion_transform\n        except AttributeError as a:\n            self._fermion_transform = 'jordan-wigner'\n\n      # Create initial state and add electrons by setting qubits to |1> (i.e., occupied)\n        reg = qk.QuantumCircuit(self._n_qubits)\n        if self._fermion_transform == 'bravyi-kitaev':\n            if self._n_electrons:\n              # fill out the mapping of electrons\n                m = [0]*self._n_qubits\n                for i in range(n_electrons_up):\n                    m[i*2] = 1\n                for i in range(n_electrons_down):\n                    m[i*2+1] = 1\n\n                for i in range(self._n_qubits):\n                    if i % 2:                              # odd\n                        if sum(m[:i+1]) % 2: reg.x(i)\n                    elif m[i]:                             # even\n                        reg.x(i)\n\n        elif self._fermion_transform == 'jordan-wigner':\n            for i in range(n_electrons_up):\n                reg.x(i*2)\n            for i in range(n_electrons_down):\n                reg.x(i*2+1)\n\n        self._state_in = qk_opflow.CircuitStateFn(reg)\n\n      # Create an observable from the Hamiltonian\n        self._meas_op = qk_opflow.StateFn(self._hamiltonian, is_measurement=True)\n\n      # Number of Trotter steps to use in the evolution operator (see __call__)\n        self._trotter_steps = trotter_steps\n\n      # Create the simulator\n        self._expectation = qk_opflow.PauliExpectation()\n        if shots <= 0 and noise_model is None:\n            self._simulator = None\n            self._meas_components = None\n        else:\n            if noise_model is None:\n                backend = qk.Aer.get_backend('qasm_simulator')\n            else:\n              # nominally, options should pass through kwargs of get_backend, however,\n              # this does not appear to work for Aer, so set the noise_model option\n              # explicitly on the retrieved backend\n                if type(noise_model) == str:\n                  # use an existing, named, IBM backend from the qiskit test suite to\n                  # create a realistic noise model; if 'realistic' default to Montreal\n                    if noise_model.lower() == 'realistic':\n                        noise_model = 'Montreal'\n\n                    import qiskit.test.mock as qk_mock\n                    import qiskit.providers.aer as qk_aer_provides\n\n                    fake_backend = 'Fake'+noise_model[0].upper()+noise_model[1:]\n                    fake_device  = getattr(qk_mock, fake_backend)()\n\n                    backend = qk_aer_provides.AerSimulator.from_backend(fake_device)\n                else:\n                    backend = qk.Aer.get_backend('aer_simulator', noise_model=noise_model)\n                    backend.set_options(noise_model=noise_model)\n\n                if shots <= 0:\n                  # if not simulating sampling, use the AerPauliExpectation, which computes\n                  # the expectation value given the noise (effectively \"infinite\" sampling);\n                  # it also passes a special \"instruction\" to the sampler to ignore shots\n                     self._expectation = qk_opflow.AerPauliExpectation()\n                     shots = 2**20          # i.e. large enough not to contribute\n\n            self._simulator = qk_opflow.CircuitSampler(backend=backend)\n            self._simulator.quantum_instance.run_config.shots = shots\n\n          # split measurement components to prevent fake coherent errors\n            primitive = self._meas_op.primitive\n            try:\n                while 1: primitive = primitive.primitive\n            except AttributeError:\n                pass\n\n            self._meas_components = list()\n            for ops, coeff in primitive.to_list():\n                self._meas_components.append(qk_opflow.StateFn(\n                    qk_opflow.PauliOp(qk.quantum_info.Pauli(ops), coeff), is_measurement=True))\n\n      # Flag to toggle running the BQSKit optimizer on the evolution operator (see __call__)\n        self.bqskit_opt = BQSKit_Hubbard_Optimizer(run_bqskit=='full') if run_bqskit else None\n\n      # File name to store evaluations, if requested\n        if save_evals:\n            self._save_evals = type(save_evals) == str and save_evals or 'pointlog.txt'\n            try:\n                os.remove(self._save_evals)\n            except Exception:\n                pass\n        else:\n            self._save_evals = None\n\n    def npar(self):\n        \"\"\"\\\n        Number of independent parameters for the optimizer\n\n        Returns:\n           npar(int): number of parameters for the optimizer\n        \"\"\"\n\n        return uccsd_evolution.singlet_paramsize(self._n_qubits, self._n_electrons)\n\n    def generate_evolution_op(self, packed_amplitudes):\n        \"\"\"\\\n        Construct the evolution operator\n\n        Returns:\n            trotterized_ev_op (opflow): (trotterized, optimized) evolution operator\n        \"\"\"\n\n      # Build the state preparation evolution operator\n        if self._fermion_transform == 'bravyi-kitaev':\n            def bk_with_qubits(fop):\n                return of.transforms.bravyi_kitaev(fop, self._n_qubits)\n            fermion_transform = bk_with_qubits\n        elif self._fermion_transform == 'jordan-wigner':\n            fermion_transform = of.transforms.jordan_wigner\n\n        evolution_op = uccsd_evolution.singlet_evolution(\n                           packed_amplitudes, self._n_qubits, self._n_electrons,\n                           fermion_transform=fermion_transform)\n\n      # Trotterize the evolution operator flow to be able to construct a circuit (the\n      # choice of 2 slices was empirically determined; it may not fit all cases)\n        if 0 < self._trotter_steps:\n            num_time_slices = self._trotter_steps\n            trotterized_ev_op = qk_opflow.PauliTrotterEvolution(\n                trotter_mode='trotter', reps=num_time_slices).convert(evolution_op)\n\n          # Run bqskit circuit optimizers as requested (only works on the trotterized\n          # evolution operator as the normal time evolution is not unitary)\n            if self.bqskit_opt is not None:\n                trotterized_ev_op = self.bqskit_opt.optimize_evolution(trotterized_ev_op)\n\n        else:\n            trotterized_ev_op = evolution_op\n\n        return trotterized_ev_op\n\n    def generate_circuit(self, packed_amplitudes):\n        \"\"\"\\\n        Construct the circuit for the current parameters\n\n        For the given packed_amplitudes, return the circuit to execute if this\n        was a step in a VQE algorithm. The measurements are left out, because\n        calculating a single Hamilitonian requires measurement Pauli-strings,\n        many of which are independent.\n\n        Args:\n            packed_amplitudes(ndarray): compact array storing the unique single\n                and double excitation amplitudes for a singlet UCCSD opflow.\n                The ordering lists unique single excitations before double\n                excitations\n\n        Returns:\n            circuit (QuantumCircuit): circuit for the current parameters\n        \"\"\"\n\n      # Build the state preparation evolution operator\n        trotterized_ev_op = self.generate_evolution_op(packed_amplitudes)\n\n      # Combine with initializer and evolution\n        expect_op = self._expectation.convert(\n                            trotterized_ev_op @ self._state_in\n                    )\n\n      # Convert to QuantumCircuit\n        circuit = (trotterized_ev_op @ self._state_in).to_circuit()\n\n        return circuit\n\n    def __call__(self, packed_amplitudes, use_cached_circuit=None):\n        \"\"\"\\\n        Calculate the energy expectation for the given parameters\n\n        Args:\n            packed_amplitudes(ndarray): compact array storing the unique single\n                and double excitation amplitudes for a singlet UCCSD opflow.\n                The ordering lists unique single excitations before double\n                excitations\n            use_cached_circuit(bool): use an existing cached circuit, or cache\n                the currently calculated circuit\n\n        Returns:\n            energy(float): energy estimate\n        \"\"\"\n\n      # Build the state preparation evolution operator\n        global _cached_circuit\n        if use_cached_circuit and _cached_circuit is not None:\n            trotterized_ev_op = _cached_circuit\n        elif isinstance(use_cached_circuit, qk_opflow.operator_base.OperatorBase):\n            trotterized_ev_op = use_cached_circuit\n        else:\n            trotterized_ev_op = self.generate_evolution_op(packed_amplitudes)\n            if use_cached_circuit:\n                _cached_circuit = trotterized_ev_op\n\n      # Run full simulation. If there are no errors, take a short cut and evaluate\n      # the hamiltonian directly. Otherwise, to prevent unrealistic coherent errors,\n      # calculate the energy from its components\n        if self._simulator is None:\n          # exact calculation\n            expect_op = self._expectation.convert(\n                            self._meas_op @ trotterized_ev_op @ self._state_in\n                        )\n            energy = np.real(expect_op.eval())\n\n        else:\n          # sampled calculation from components\n\n          # Note, sampling of the full hamiltonian would look like:\n          #     sampled_op = self._simulator.convert(\n          #                      self._expectation.convert(\n          #                          self._meas_op @ trotterized_ev_op @ self._state_in\n          #                      )\n          #                  )\n          #     energy = np.real(sampled_op.eval())\n\n          # use measurement components to prevent fake coherent errors\n            energy = 0.\n            for meas_op in self._meas_components:\n                sampled_op = self._simulator.convert(\n                                 self._expectation.convert(\n                                     meas_op @ trotterized_ev_op @ self._state_in\n                                 )\n                             )\n                energy += np.real(sampled_op.eval())\n\n        logger.info('objective: %.5f @ %s', energy, packed_amplitudes)\n\n        if self._save_evals:\n          # store parameter values and energy in log file\n            f = open(self._save_evals, \"a+\")\n            for ii in range(len(packed_amplitudes)):\n                f.write(\"%f  \" % (packed_amplitudes[ii]))\n            f.write(\"%f \\n\" % (energy))\n            f.close()\n\n        return energy\n\n\ndef _to_qiskit(of_qop, n_qubits):\n    \"\"\"Convert OpenFermion QubitOperators to Qiskit equivalent\"\"\"\n\n    opflow = list()\n    for paulis, coeff in sorted(of_qop.terms.items()):\n        ops = ['I']*n_qubits\n        for term in paulis:\n            ops[term[0]] = term[1]\n\n        ops.reverse()\n\n        opflow1 = coeff*getattr(qk_opflow, ops[0])\n        for i in range(1, n_qubits):\n            opflow1 ^= getattr(qk_opflow, ops[i])\n        opflow.append(opflow1)\n\n    return sum(opflow)\n\n\ndef _hubbard_qubit(x_dimension, y_dimension, tunneling, coulomb,\n        chemical_potential = 0.00, magnetic_field = 0.0, periodic = True, spinless = False,\n        fermion_transform='bravyi-kitaev'):\n    \"\"\"Create Fermi-Hubbard model with OpenFermion\"\"\"\n\n    _fermion_transform = fermion_transform.lower()\n    known_transforms = ['jordan-wigner', 'bravyi-kitaev']\n    if not _fermion_transform in known_transforms:\n        raise ValueError(\"unknown transform '%s'\" % fermion_transform)\n\n    # Hubbard Hamiltonian expressed in FermionOperators, i.e. creation and annihilation\n    # operators. Each FermionOperator consists of the site it operates on (expressed as\n    # an \"index\") and whether it raises (1) or lowers (0; expressed asn an \"action\"),\n    # multiplied by a coefficient.\n    hubbard_fermion = of.fermi_hubbard(\n        x_dimension        = x_dimension,\n        y_dimension        = y_dimension,\n        tunneling          = tunneling,\n        coulomb            = coulomb,\n        chemical_potential = chemical_potential,\n        magnetic_field     = magnetic_field,\n        periodic           = periodic,\n        spinless           = spinless)\n\n    # Hubbard Hamiltonian expressed in QubitOperators, i.e. Pauli's (X, Y, Z) operators.\n    # Each QubitOperator consists of the qubit it operates on (expressed as an \"index\")\n    # and which Pauli is applied (expressed as an \"action\") multiplied by a coefficient.\n    if _fermion_transform == 'bravyi-kitaev':\n        n_qubits = x_dimension * y_dimension * (spinless and 1 or 2)\n        hubbard_qubit = of.transforms.bravyi_kitaev(hubbard_fermion, n_qubits)\n    elif _fermion_transform == 'jordan-wigner':\n        hubbard_qubit = of.transforms.jordan_wigner(hubbard_fermion)\n\n    # Remove terms below floating point epsilon\n    hubbard_qubit.compress()\n\n    return hubbard_qubit\n\n\ndef hamiltonian_matrix(x_dimension, y_dimension, tunneling, coulomb,\n        chemical_potential = 0.00, magnetic_field = 0.0, periodic = True, spinless = False):\n    \"\"\"Create Fermi-Hubbard model Hamiltonian represented in matrix form\"\"\"\n\n    hubbard_qubit = _hubbard_qubit(\n        x_dimension        = x_dimension,\n        y_dimension        = y_dimension,\n        tunneling          = tunneling,\n        coulomb            = coulomb,\n        chemical_potential = chemical_potential,\n        magnetic_field     = magnetic_field,\n        periodic           = periodic,\n        spinless           = spinless)\n\n    return of.linalg.get_sparse_operator(hubbard_qubit).todense()\n\n\ndef hamiltonian_qiskit(x_dimension, y_dimension, tunneling, coulomb,\n        chemical_potential = 0.00, magnetic_field = 0.0, periodic = True, spinless = False,\n        fermion_transform='bravyi-kitaev'):\n    \"\"\"Create Fermi-Hubbard model Hamiltonian represented in matrix form\"\"\"\n\n    hubbard_qubit = _hubbard_qubit(\n        x_dimension        = x_dimension,\n        y_dimension        = y_dimension,\n        tunneling          = tunneling,\n        coulomb            = coulomb,\n        chemical_potential = chemical_potential,\n        magnetic_field     = magnetic_field,\n        periodic           = periodic,\n        spinless           = spinless,\n        fermion_transform  = fermion_transform)\n\n    n_qubits = x_dimension * y_dimension * (spinless and 1 or 2)\n\n    hubbard_qiskit = _to_qiskit(hubbard_qubit, n_qubits)\n\n  # store the used fermion transform with the hamiltonian to ensure that\n  # the objective function later uses the same transform\n    hubbard_qiskit._fermion_transform = fermion_transform\n\n    return hubbard_qiskit\n\n\nclass Model(object):\n    \"\"\"Convenience class to capture module parameters\"\"\"\n\n    def __init__(self, xdim, ydim, t, U, chem=0.0, mag=0.0, periodic=True, spinless=False, precalc={}):\n        self.x_dimension = xdim\n        self.y_dimension = ydim\n        self.tunneling   = t\n        self.coulomb     = U\n        self.chemical_potential = chem\n        self.magnetic_field     = mag\n        self.periodic = periodic\n        self.spinless = spinless\n        self._precalc = precalc\n\n    def __call__(self):\n        \"\"\"Generate the model\"\"\"\n\n        return self.x_dimension, self.y_dimension, self.tunneling, self.coulomb, \\\n               self.chemical_potential, self.magnetic_field, \\\n               self.periodic, self.spinless\n\n    def initial(self, n_electrons_up, n_electrons_down, npar, transform='bravyi-kitaev', good=False):\n        \"\"\"\\\n        Provide a (good) initial and tight bounds for a given configuration\n\n        Args:\n            n_electrons_up(int): number of electrons with spin-up\n            n_electrons_down(int): number of electrons with spin-down\n            transform(str): for which fermion transform the initial applies\n            good(bool): whether to return an initial close to the optimal\n\n        Returns:\n            initial(tuple): array of (good) initial parameters and an array of bounds\n        \"\"\"\n\n        if good:\n            at_opt = self.optimal(n_electrons_up, n_electrons_down, transform)\n            if at_opt is not None:\n                close = np.round(at_opt, npar <= 4 and 1 or 2)\n                bounds = np.zeros((len(close), 2))\n                bounds[:,0] = np.subtract(close, 0.1)\n                bounds[:,1] = np.add(     close, 0.1)\n                return close, bounds\n\n        if npar <= 0:\n            raise RuntimeError(\"not an optimizable configuration (%d parameters)\" % npar)\n\n        rng = np.random.default_rng(42)     # for reproducibility while debugging\n        initial_amplitudes = np.array(-0.05+0.1*rng.random(size=npar))\n        bounds = np.array([(-1.0, 1.0)]*npar)\n\n        return initial_amplitudes, bounds\n\n    def optimal(self, n_electrons_up, n_electrons_down, transform='bravyi-kitaev'):\n        \"\"\"\\\n        Lookup the pre-calculated optimal paramters\n\n        Args:\n            n_electrons_up(int): number of electrons with spin-up\n            n_electrons_down(int): number of electrons with spin-down\n            transform(str): for which fermion transform the initial applies\n\n        Returns:\n            optimum(tuple): array of parameters for the global minimum or None\n        \"\"\"\n\n        try:\n            return self._precalc[(n_electrons_up, n_electrons_down)]\n        except KeyError:\n            pass\n\n        warnings.warn(\"No pre-calculated initial for configuration (%d, %d)\" %\\\n                      (n_electrons_up, n_electrons_down))\n\n        return None\n\nsmall_model  = Model(2, 1, t=1.0, U=2.0,\n    precalc={\n        (1, 0) : np.array([-0.78536064,  0.89994575]),\n        (0, 1) : np.array([-0.78536609, -0.25647772]),\n        (1, 1) : np.array([-0.86866234,  0.18526051]),\n    })\n\nmedium_model = Model(2, 2, t=1.0, U=2.0,\n    precalc={\n        (1, 1) : np.array([ 0.22048886, 0.22048479,  0.27563475,\n                            0.22178354, 0.22177972,  0.24547588,\n                            0.6276739,  0.60108877,  0.60108406]),\n        (2, 2) : np.array([-0.81965099,  0.4858986 , -0.4858995,  0.76993761,\n                            0.10298091, -0.03832318, -0.03832113, 0.64542339,\n                            0.00399792, -0.00399722,  0.11716964, 0.32792626,\n                           -0.06136483,  0.06136485]),\n        (3, 3) : np.array([ 0.64501004, -0.6305074 , -0.63050858,\n                            0.08473441,  0.06774534,  0.06774663,\n                           -0.0411103 , -0.0411079 , -0.01508739])\n    })\n\n\ndef exact(hubbard_hamiltonian, n_electrons_up, n_electrons_down):\n    \"\"\"Return the exact solution for the given Hubbard Model Hamiltonian\"\"\"\n\n    n_qubits = hubbard_hamiltonian.num_qubits\n\n  # JW has one-to-one mapping and thus the fermion operator's matrix can be used\n  # directly; not so for other transformations\n    spin_up_op   = sum([of.FermionOperator(((i, 1), (i, 0))) for i in range(0, n_qubits, 2)])\n    spin_down_op = sum([of.FermionOperator(((i, 1), (i, 0))) for i in range(1, n_qubits, 2)])\n\n    if hubbard_hamiltonian._fermion_transform == 'bravyi-kitaev':\n        spin_up_op   = of.transforms.bravyi_kitaev(spin_up_op, n_qubits)\n        spin_down_op = of.transforms.bravyi_kitaev(spin_down_op, n_qubits)\n    elif hubbard_hamiltonian._fermion_transform == 'jordan-wigner':\n        spin_up_op   = of.transforms.jordan_wigner(spin_up_op)\n        spin_down_op = of.transforms.jordan_wigner(spin_down_op)\n\n    spin_up_op   = _to_qiskit(spin_up_op, n_qubits)\n    spin_down_op = _to_qiskit (spin_down_op, n_qubits)\n\n  # get the matrix representations; note that the up_matrix will be 2x smaller if\n  # n_qubits is even; same for down_matrix if odd\n    hm_matrix   = hubbard_hamiltonian.to_matrix()\n    up_matrix   = spin_up_op.to_matrix()\n    down_matrix = spin_down_op.to_matrix()\n\n    eigenvalues, eigenvectors = spla.eigh(hm_matrix)\n    for i in range(hm_matrix.shape[0]):\n        v = eigenvectors[:,i]\n        n_up = float(np.real(v.T.dot(up_matrix).dot(v)))\n        if not round(n_up, 3).is_integer() or not round(n_up) == n_electrons_up:\n            continue\n\n        n_down = float(np.real(v.T.dot(down_matrix).dot(v)))\n        if not round(n_down, 3).is_integer() or not round(n_down) == n_electrons_down:\n            continue\n\n        return float(np.real(v.T.dot(hm_matrix).dot(v)))\n\n    raise RuntimeError('configuration %d up, %d down not found' % (n_electrons_up, n_electrons_down))\n", "meta": {"hexsha": "088752520977bc5465901f8076ecd5a121991def", "size": 22169, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorials/hubbard.py", "max_stars_repo_name": "scikit-quant/scikit-quant", "max_stars_repo_head_hexsha": "397ab0b6287f3815e9bcadbfadbe200edbee5a23", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2019-02-05T16:39:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T23:14:11.000Z", "max_issues_repo_path": "tutorials/hubbard.py", "max_issues_repo_name": "scikit-quant/scikit-quant", "max_issues_repo_head_hexsha": "397ab0b6287f3815e9bcadbfadbe200edbee5a23", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2020-04-13T09:22:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-16T16:14:13.000Z", "max_forks_repo_path": "tutorials/hubbard.py", "max_forks_repo_name": "scikit-quant/scikit-quant", "max_forks_repo_head_hexsha": "397ab0b6287f3815e9bcadbfadbe200edbee5a23", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-04-21T17:43:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-10T04:12:34.000Z", "avg_line_length": 40.0162454874, "max_line_length": 103, "alphanum_fraction": 0.6210474085, "include": true, "reason": "import numpy,import scipy", "num_tokens": 5409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.18088619443593004}}
{"text": "import os.path\nimport logging\nimport numpy    as np\nfrom   typing   import Union\n\nimport PyMieSim\nfrom PyMieSim.Tools.LPModes     import GetFarFieldLP\nfrom PyMieSim.Tools.Mesh        import FibonacciMesh\nfrom PyMieSim.Tools.BaseClasses import BaseDetector, MeshProperty\nfrom PyMieSim.Tools.ErrorMsg    import *\nfrom PyMieSim.Tools.utils       import NA2Angle, LoadLPMode, IO\nfrom PyMieSim.bin.LMTScatterer  import BindedPhotodiode, BindedLPMode\n\n\nclass Photodiode(BaseDetector, MeshProperty):\n    \"\"\"\n    .. note::\n        Detector type class representing a photodiode, light coupling is\n        thus independant of the phase of the latter.\n\n    Parameters\n    ----------\n    NA : :class:`float`\n        Numerical aperture of imaging system.\n    Sampling : :class:`int`\n        Number of sampling points for the mode (inside NA).\n    GammaOffset : :class:`float`\n        Angle offset of detector in the direction perpendicular to polarization.\n    PhiOffset : :class:`float`\n        Angle offset of detector in the direction parallel to polarization.\n    Filter : :class:`float`\n        Angle of polarization filter in front of detector. Default is \"None\"\n    CouplingMode : :class:`str`\n        Methode for computing mode coupling. Either Point or Mean.\n\n    \"\"\"\n\n    def __init__(self,\n                 NA           : Union[int, float],\n                 Sampling     : int                      = 400,\n                 CouplingMode : str                      = 'Point',\n                 GammaOffset  : Union[int, float]        = 0,\n                 PhiOffset    : Union[int, float]        = 0,\n                 Filter       : Union[int, float, bool]  = None):\n\n        self.CouplingMode = CouplingMode\n        self._Filter      = Filter\n        self._PhiOffset   = PhiOffset\n        self._GammaOffset = GammaOffset\n        self._NA          = NA\n        self._Sampling    = Sampling\n        self.ScalarField  = np.ones(Sampling)\n\n        self.GetBinding()\n\n\n    def GetBinding(self):\n        self.Mesh = FibonacciMesh(MaxAngle    = NA2Angle(self._NA).Radian,\n                                  Sampling    = self._Sampling,\n                                  PhiOffset   = self._PhiOffset,\n                                  GammaOffset = self._GammaOffset)\n\n        self.Bind = BindedPhotodiode(NA       = self._NA,\n                                     Phi      = np.deg2rad(self._PhiOffset),\n                                     Gamma    = np.deg2rad(self._GammaOffset),\n                                     Filter   = np.deg2rad(self._Filter) if self._Filter else float(4242),\n                                     Sampling = self._Sampling)\n\n    def GetScalarField(self, Sampling, Structured=False):\n        if Structured:\n            return np.ones([Sampling, Sampling])\n        else:\n            return np.ones(Sampling)\n\n\n    def __str__(self):\n        return self.Name\n\n\n    def __repr__(self):\n\n        return IO( f\"\"\"\n        Photodiode detector\n        Coupling Mode: Intensity\n        Numerical aperture:  {self.NA:.4f}\n        Sampling:            {self.Mesh.Sampling}\n        Gamma offset:        {self.Mesh.GammaOffset}\n        Phi offset:          {self.Mesh.PhiOffset}\n        \"\"\" )\n\n\n\n\n\nclass IntegratingSphere(Photodiode):\n    \"\"\"\n    .. note::\n        Detector type class representing a photodiode, light coupling is\n        thus independant of the phase of the latter.\n\n    Parameters\n    ----------\n    NA : :class:`float`\n        Numerical aperture of imaging system.\n    Sampling : :class:`int`\n        Number of sampling points for the mode (inside NA).\n    GammaOffset : :class:`float`\n        Angle offset of detector in the direction perpendicular to polarization.\n    PhiOffset : :class:`float`\n        Angle offset of detector in the direction parallel to polarization.\n    Filter : :class:`float`\n        Angle of polarization filter in front of detector. Default is \"None\"\n    CouplingMode : :class:`str`\n        Methode for computing mode coupling. Either Point or Mean.\n\n    \"\"\"\n\n    def __init__(self,\n                 Sampling     : int                      = 400,\n                 CouplingMode : str                      = 'Point',\n                 Filter       : Union[int, float, bool]  = None):\n\n\n        self.CouplingMode = CouplingMode\n        self._Filter      = Filter\n        self._PhiOffset   = 0\n        self._GammaOffset = 0\n        self._NA          = 2.0\n        self._Sampling    = Sampling\n        self.ScalarField  = np.ones(Sampling)\n\n        self.GetBinding()\n\n    def GetBinding(self):\n        self.Mesh = FibonacciMesh(MaxAngle    = NA2Angle(self._NA).Radian,\n                                  Sampling    = self._Sampling,\n                                  PhiOffset   = self._PhiOffset,\n                                  GammaOffset = self._GammaOffset)\n\n        self.Bind = BindedPhotodiode(Sampling = self._Sampling,\n                                     NA       = self._NA,\n                                     Phi      = np.deg2rad(self._PhiOffset),\n                                     Gamma    = np.deg2rad(self._GammaOffset),\n                                     Filter   = np.deg2rad(self._Filter) if self._Filter else float(4242)\n                                     )\n\n    def GetScalarField(self, Sampling, Structured=False):\n        if Structured:\n            return np.ones([Sampling, Sampling])\n        else:\n            return np.ones(Sampling)\n\n\n    def __repr__(self):\n\n        return IO( f\"\"\"\n        Integrating sphere\n        Coupling Mode: Intensity\n        Sampling:      {self.Mesh.Sampling}\n        \"\"\" )\n\n    def __str__(self):\n        return self.Name\n\n\n\nclass LPmode(BaseDetector, MeshProperty):\n    \"\"\"\n    .. note::\n        Detector type class representing a fiber LP mode, light coupling is\n        thus dependant of the phase of the latter.\n\n    Parameters\n    ----------\n    Mode : :class:`tuple`\n        LP mode index l, m.\n    NA : :class:`float`\n        Numerical aperture of imaging system.\n    Sampling : :class:`int`\n        Number of sampling points for the mode (inside NA).\n    InterpSampling : :class:`int`\n        Number of sampling point for interpolation of FarField mode.\n    GammaOffset : :class:`float`\n        Angle offset of detector in the direction perpendicular to polarization.\n    PhiOffset : :class:`float`\n        Angle offset of detector in the direction parallel to polarization.\n    Filter : :class:`float`\n        Angle of polarization filter in front of detector. Default is \"None\"\n    CouplingMode : :class:`str`\n        Methode for computing mode coupling. Either [Point or Mean].\n\n    \"\"\"\n\n    def __init__(self,\n                 Mode         : Union[tuple, list],\n                 NA           : float,\n                 Rotation     : Union[int, float]        = 0,\n                 Sampling     : int                      = 401,\n                 GammaOffset  : Union[int, float]        = 0,\n                 PhiOffset    : Union[int, float]        = 0,\n                 Filter       : Union[int, float, bool]  =  None,\n                 CouplingMode : str                      = 'Point'):\n\n        assert CouplingMode in ['Point','Mean'], Error_MeanCentered\n\n        if NA > 1 or NA < 0: logging.warning(warning_NAHigh)\n\n\n        self.ModeNumber   = Mode\n        self.CouplingMode = CouplingMode\n        self._Filter      = Filter\n        self._PhiOffset   = PhiOffset\n        self._GammaOffset = GammaOffset\n        self._NA          = NA\n        self._Sampling    = Sampling\n\n        self.GetBinding()\n\n\n    def GetBinding(self):\n        self.Mesh = FibonacciMesh(MaxAngle    = NA2Angle(self._NA).Radian,\n                                  Sampling    = self._Sampling,\n                                  PhiOffset   = self._PhiOffset,\n                                  GammaOffset = self._GammaOffset)\n\n        self.ScalarField  = GetFarFieldLP(Mode     = self.ModeNumber,\n                                          MaxAngle = NA2Angle(self._NA).Radian,\n                                          Sampling = self._Sampling)\n\n        self.Bind = BindedLPMode(ScalarField = self.ScalarField,\n                                 Sampling    = self._Sampling,\n                                 NA          = self._NA,\n                                 Phi         = np.deg2rad(self._PhiOffset),\n                                 Gamma       = np.deg2rad(self._GammaOffset),\n                                 Filter      = np.deg2rad(self._Filter) if self._Filter else float(4242)\n                                 )\n\n\n    def GetScalarField(self, Sampling, Structured=False):\n\n        return GetFarFieldLP(Mode       = self.ModeNumber,\n                             MaxAngle   = NA2Angle(self._NA).Radian,\n                             Sampling   = Sampling,\n                             Structured = Structured)\n\n    def __str__(self):\n        return self.Name\n\n\n\n    def __repr__(self):\n        return IO( f\"\"\"\n        LP mode detector\n        Coupling Mode: Amplitude\n        LP Mode:             {self.ModeNumber}\n        Numerical aperture:  {self.NA:.4f}\n        Sampling:            {self.Mesh.Sampling}\n        Gamma offset:        {self.Mesh.GammaOffset}\n        Phi offset:          {self.Mesh.PhiOffset}\n        \"\"\" )\n\n\n# -\n", "meta": {"hexsha": "a360e1d0d36bdf05eaa24772bedd158592130805", "size": 9241, "ext": "py", "lang": "Python", "max_stars_repo_path": "PyMieSim/Detector.py", "max_stars_repo_name": "MartinPdS/PyMieSim", "max_stars_repo_head_hexsha": "2560c7f4009df5d05bcb0ce8e929aa7baa7be8de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-02-11T17:53:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T20:20:01.000Z", "max_issues_repo_path": "PyMieSim/Detector.py", "max_issues_repo_name": "MartinPdS/PyMieSim", "max_issues_repo_head_hexsha": "2560c7f4009df5d05bcb0ce8e929aa7baa7be8de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-05-12T04:33:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-14T05:25:19.000Z", "max_forks_repo_path": "PyMieSim/Detector.py", "max_forks_repo_name": "MartinPdS/PyMieSim", "max_forks_repo_head_hexsha": "2560c7f4009df5d05bcb0ce8e929aa7baa7be8de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-05-10T19:46:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T19:52:14.000Z", "avg_line_length": 35.0037878788, "max_line_length": 106, "alphanum_fraction": 0.5321934856, "include": true, "reason": "import numpy", "num_tokens": 1956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3174262526733264, "lm_q1q2_score": 0.18088619171435522}}
{"text": "\"\"\"Keep track of spacecraft jitter.\"\"\"\nimport settings\nimport numpy as np\nimport astropy.table\nimport os.path\nimport zachopy.utils\nimport matplotlib.pylab as plt\nimport scipy.interpolate\nimport logging\nimport matplotlib.gridspec as gridspec\nfrom settings import log_file_handler\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(log_file_handler)\n\n\ndef makeCartoon(seed=1):\n    \"\"\"Create a cartoon jitter timeseries\"\"\"\n\n    np.random.seed(seed)\n    rmsat2s = 2.0 / 3.0\n    rmsat120s = 0.21\n\n    # share across two dimensions\n    rmsat120s1d = rmsat120s / np.sqrt(2)\n    rmsat2s1d = rmsat2s / np.sqrt(2)\n\n    cadence = 2.0\n    smoothscale = 10.0\n    nsmooth = int(smoothscale / cadence)\n    t = np.arange(0, 30 * 24 * 60 * 60, 2)\n    n = len(t)\n    d = {}\n    d['t'] = t\n    for k in ['x', 'y']:\n        v = np.random.normal(0, 1, n)\n        for i in range(2):\n            v = np.convolve(v, np.ones(nsmooth), mode='same')\n        d[k] = v / np.std(v) * rmsat2s1d\n\n    table = astropy.table.Table(d, names=['t', 'x', 'y'])\n    table.write(os.path.join(settings.inputs, 'cartoon.jitter'), format='ascii.fixed_width', bookend=False, overwrite=True)\n\n\nclass Jitter(object):\n    def __init__(self, camera=None, jitterrms=None, rawjitterbasename=\"AttErrTimeArcsec_80k.dat\",\n                 nsubpixelsperpixel=None,\n                 amplifyinterexposurejitter=1.0):\n\n\n        # set an extra directory specifically for this object\n        self.directory = 'jitter/'\n\n        # store the input camera\n        self.camera = camera\n\n        # set up the initial raw jitter file\n        # (this one cam from Roland, some time ago)\n        self.rawfile = os.path.join(settings.inputs, rawjitterbasename)\n\n        # what do you want the RMS to be rescaled to?\n        self.jitterrms = jitterrms\n\n        # how much should the exposure to exposure jitter be amplified\n        self.amplifyinterexposurejitter = amplifyinterexposurejitter\n\n        # (for creating map that will be used to convolve with the psf)\n        self.nsubpixelsperpixel = nsubpixelsperpixel\n\n        # update the jitterball to one that has been binned to this cadence\n        self.load()\n\n    def load(self, remake=False):\n        \"\"\"make sure that a jitterball (timeseries of roll,pitch,yaw) has\n      been loaded and binned to the appropriate exposure times\"\"\"\n\n        try:\n            # if the jitterball is already loaded into memory\n            #  *and* of the correct cadence, we're all set!\n            self.jitterball\n\n            # make sure the we're using the right jitterball for this cadence\n            assert (self.jittercadence == self.camera.cadence)\n\n            # make sure we're not trying to remake the jitterball\n            assert (remake == False)\n\n        except (AttributeError, AssertionError):\n            # load the processed jitterball\n            self.loadProcessedJitterball()\n\n    @property\n    def basename(self):\n        cadencestatement = '.cadence{:.0f}s'.format(self.camera.cadence)\n\n        if self.jitterrms is not None:\n            jitterstatement = '.rescaledto{:0.2f}arcsec'.format(self.jitterrms)\n        else:\n            jitterstatement = '.unscaled'\n\n        return os.path.basename(self.rawfile) + cadencestatement + jitterstatement\n\n    @property\n    def processedfile(self):\n        \"\"\"determine what the processed filename should be (based on rawfile)\"\"\"\n\n        # store the processed files in the intermediates directory\n        directory = settings.intermediates + self.directory\n\n        # make sure a jitter directory actually exists\n        zachopy.utils.mkdir(directory)\n\n        # define the filename\n        return os.path.join(directory, self.basename + '.processed.npy')\n\n    def loadProcessedJitterball(self):\n        \"\"\"load a pre-processed jitterball, from the intermediates directory\"\"\"\n\n        # if not, populate the jitterball for this cadence\n        logger.info(\n            'populating the jitterball for {0:.0f} second cadence, '\n            'based on the raw jitter file {1}.'.format(\n                self.camera.cadence,\n                self.basename))\n\n        try:\n            # if a processed file already exists, load it\n            self.jitterball, self.jittermap = np.load(self.processedfile)\n            self.jittercadence = self.camera.cadence\n        except IOError:\n\n            logger.info('no processed jitter file was found for {}'.format(\n                self.basename))\n\n            self.loadUnprocessedJitterball()\n\n    def loadUnprocessedJitterball(self):\n        \"\"\"load from a raw jitter file, process, and save\"\"\"\n\n        # otherwise, create a binned jitter structure\n        logger.info('loading raw jitter from {}'.format(self.rawfile))\n\n        # load the raw file\n        if 'AttErrTimeArcsec' in self.rawfile:\n            self.rawdata = astropy.io.ascii.read(self.rawfile,\n                                                 names=['t', 'x', 'y', 'z'])\n        else:\n            self.rawdata = astropy.io.ascii.read(self.rawfile, names=['t', 'x', 'y'])\n\n        # subtract means\n        self.rawdata['x'] -= np.mean(self.rawdata['x'])\n        self.rawdata['y'] -= np.mean(self.rawdata['y'])\n\n        # scale jitterball to requirements (should be inflation by ~1.5)\n        if self.jitterrms is not None:\n            # STILL A KLUDGE! NEED ROLL, PITCH, YAW!\n            original_rms = np.sqrt(np.mean(self.rawdata['x'] ** 2 +\n                                           self.rawdata['y'] ** 2))\n            self.rawdata['x'] *= self.jitterrms / original_rms\n            self.rawdata['y'] *= self.jitterrms / original_rms\n\n        # smooth them to the required cadence\n        logger.info(\"smoothing the jitter to {0}s cadence\".format(\n            self.camera.cadence))\n\n        #  figure out the time-spacing of the jitter timeseries\n        spacings = self.rawdata['t'][1:] - self.rawdata['t'][:-1]\n        spacing = np.median(spacings)\n\n        # make sure that the jitter timeseries is evenly spaced\n        aboutright = 0.01\n        assert ((np.abs(spacings - spacing) < spacing * aboutright).all())\n\n        # create a convolution filter, to smooth to camera's cadence\n        n = np.long(self.camera.cadence / spacing)\n        filter = np.ones(n) / n\n\n        # construct smoothed timeseries, sampled at raw time resolution\n        smoothed_t = np.convolve(self.rawdata['t'], filter, mode='valid')\n        smoothed_x = np.convolve(self.rawdata['x'], filter, mode='valid')\n        smoothed_y = np.convolve(self.rawdata['y'], filter, mode='valid')\n\n        # sample smoothed timeseries at the camera's cadence\n        t = smoothed_t[::n]\n        x = smoothed_x[::n]\n        y = smoothed_y[::n]\n\n        # plot each dimension separately\n        logger.info('saving binned jitter timeseries plot')\n\n\n        # create the plot of the timeseries\n        plotdirectory = os.path.join(settings.plots, self.directory)\n        zachopy.utils.mkdir(plotdirectory)\n        bkw = dict(alpha=0.5, color='black')\n        rkw = dict(linewidth=2, alpha=0.5, marker='o', color='red')\n        fi, ax = plt.subplots(2, 1, sharey=True, sharex=True)\n        ax[0].plot(self.rawdata['t'], self.rawdata['x'], **bkw)\n        ax[0].plot(t, x, **rkw)\n        ax[1].plot(self.rawdata['t'], self.rawdata['y'], **bkw)\n        ax[1].plot(t, y, **rkw)\n        ax[0].set_xlim(0, self.camera.cadence * 10)\n        ax[0].set_title('TESS Pointing Jitter for \\n{}\\nfor {}s Cadence'.format(self.basename, self.camera.cadence),\n                        fontsize=6)\n        ax[0].set_ylabel('x (\")')\n        ax[1].set_ylabel('y (\")')\n        ax[1].set_xlabel('Time (seconds)')\n        fi.savefig(os.path.join(plotdirectory,\n                                self.basename + '_timeseries.pdf'))\n\n        # make interpolators to keep track of the running smooth means\n        ikw = dict(kind='nearest', fill_value=0, bounds_error=False)\n        xip = scipy.interpolate.interp1d(smoothed_t, smoothed_x, **ikw)\n        yip = scipy.interpolate.interp1d(smoothed_t, smoothed_y, **ikw)\n\n        # assign the jittermap here, in units of subpixels, to be used for convolution in the PSF code\n        arcsectosubpixels = 1.0 / self.camera.pixelscale * self.nsubpixelsperpixel\n        xoff = (self.rawdata['x'] - xip(self.rawdata['t'])) * arcsectosubpixels\n        yoff = (self.rawdata['y'] - yip(self.rawdata['t'])) * arcsectosubpixels\n\n        npixelsfromcenter = 1\n        nbins = np.maximum(np.max(np.abs(np.sqrt(xoff ** 2 + yoff ** 2))),\n                           1)  # npixelsfromcenter*self.nsubpixelsperpixel\n        limits = [[-nbins, nbins], [-nbins, nbins]]\n\n        # define the jittermap as a 2D histrogram for convolution within exps\n        self.jittermap = np.histogram2d(xoff, yoff,\n                                        bins=nbins,\n                                        range=limits,\n                                        normed=True)\n\n        # define the binned jitterball, for nudges between exps\n        self.jitterball = (x, y)\n\n        # keep track of the jitter cadence associated with this\n        self.jittercadence = self.camera.cadence\n\n        logger.info('saving jittermap plots')\n\n        # plot the adopted jitterball, as more useful binning\n        plothist2d(self.jittermap, scale=1.0 / self.nsubpixelsperpixel,\n                   title='TESS Pointing Jitter over {0}s'.format(\n                       self.camera.cadence),\n                   xtitle='Pixels', ytitle='Pixels',\n                   filename=os.path.join(plotdirectory, self.basename + '_jittermap.pdf'))\n\n        # save the necessary jitter files\n        logger.info('saving the jitter files to {0}'.format(self.processedfile))\n        np.save(self.processedfile, (self.jitterball, self.jittermap))\n\n    @property\n    def x(self):\n        return self.amplifyinterexposurejitter * self.jitterball[0]\n\n    @property\n    def y(self):\n        return self.amplifyinterexposurejitter * self.jitterball[1]\n\n    def writeNudges(self, outfile='jitter.txt'):\n\n        counters = np.arange(len(self.x))\n        bjds = self.camera.counterToBJD(counters)\n        time = bjds - np.min(bjds)\n        plt.figure('jitter timeseries')\n        gs = gridspec.GridSpec(2, 1, hspace=0.15)\n        kw = dict(linewidth=2)\n        ax = None\n\n        for i, what in enumerate((self.x, self.y)):\n            ax = plt.subplot(gs[i], sharex=ax, sharey=ax)\n            ax.plot(time, what, **kw)\n            ax.set_ylabel(['dRA (arcsec)', 'dDec (arcsec)'][i])\n            if i == 0:\n                ax.set_title('Jitter Timeseries from\\n{}'.format(self.basename))\n\n        plt.xlabel('Time from Observation Start (days)')\n        plt.xlim(np.min(time), np.max(time))\n        plt.draw()\n        plt.savefig(outfile.replace('.txt', '.pdf'))\n\n        data = [counters, bjds, self.x, self.y]\n        names = ['imagenumber', 'bjd', 'arcsecnudge_ra', 'arcsecnudge_dec']\n\n        t = astropy.table.Table(data=data, names=names)\n        t.write(outfile.replace('.txt', '_amplifiedby{}.txt'.format(self.amplifyinterexposurejitter)),\n                format='ascii.fixed_width', delimiter=' ', overwrite=True)\n        logger.info(\"save jitter nudge timeseries to {0}\".format(outfile))\n\n    def applyNudge(self,\n                   counter=None,  # which row to use from jitterball?\n                   dx=None, dy=None,  # custom nudges, in arcsec\n                   header=None,  # the FITS header in which to record nudges\n                   ):\n\n        \"\"\"jitter the camera by a little bit,\n      by introducing nudges draw from a\n      (cadence-appropriate) jitterball timeseries.\"\"\"\n\n        # make sure the jitterball has been populated\n        self.load()\n        n = len(self.x)\n\n        # should we be applying a custom offset?\n        usecustom = (counter is None)\n        if usecustom:\n            self.camera.nudge['x'] = dx\n            self.camera.nudge['y'] = dy\n        else:\n            # if we're over the counter, loop back\n            i = counter % n\n            self.camera.nudge['x'] = self.x[i]\n            self.camera.nudge['y'] = self.y[i]\n\n        # if possible, write the details to the supplied FITS header\n        try:\n            header['MOTION'] = ''\n            header['MOTNOTE'] = ('',\n                                 'properties of the image motion applied')\n            header['JITTERX'] = (self.camera.nudge['x'],\n                                 '[\"] jitter-induced nudge')\n            header['JITTERY'] = (self.camera.nudge['y'],\n                                 '[\"] jitter-induced nudge')\n            header['JITPFILE'] = (self.basename,\n                                  'processed jitter filename')\n            header['JITSCALE'] = (self.amplifyinterexposurejitter, 'jitter magnified by ? relative to file')\n            header['JITCOUNT'] = (i, 'which row of jitter file was applied?')\n\n            logger.info('updated header keywords')\n        except TypeError:\n            logger.info('no header was found to update')\n\n        # move the camera, using the updated nudge values\n        logger.info(\"nudged the camera to {x},{y}\"\n                   \" away from nominal pointing.\".format(**self.camera.nudge))\n\n\ndef plothist2d(hist, title=None, log=False, scale=1.0,\n               xtitle=None, ytitle=None, filename=None):\n    \"\"\"Plot a 2D histogram.\"\"\"\n    map = hist[0]\n    x = (hist[1][1:] + (hist[1][0] - hist[1][1]) / 2.0) * scale\n    y = (hist[2][1:] + (hist[2][0] - hist[2][1]) / 2.0) * scale\n    fig = plt.figure(figsize=(10, 10))\n    plt.clf()\n    plt.subplots_adjust(hspace=0, wspace=0)\n    ax_map = fig.add_subplot(2, 2, 3)\n    ax_vert = fig.add_subplot(2, 2, 4, sharey=ax_map)\n    ax_hori = fig.add_subplot(2, 2, 1, sharex=ax_map)\n\n    ax_hori.plot(x, np.sum(map, 0) / np.sum(map), marker='o', color='black', linewidth=3)\n    ax_vert.plot(np.sum(map, 1) / np.sum(map), y, marker='o', color='black', linewidth=3)\n    if log:\n        ax_vert.semilogx()\n        ax_hori.semilogy()\n    if log:\n        bottom = np.min(map[map > 0]) / np.maximum(np.sum(map, 0).max(), np.sum(map, 1).max())\n    else:\n        bottom = 0\n    top = 1\n    ax_hori.set_ylim(bottom, top)\n    ax_vert.set_xlim(bottom, top)\n\n    ax_vert.tick_params(labelleft=False)\n    ax_hori.tick_params(labelbottom=False)\n    if title is not None:\n        ax_hori.set_title(title)\n    if xtitle is not None:\n        ax_map.set_xlabel(xtitle)\n    if ytitle is not None:\n        ax_map.set_ylabel(ytitle)\n\n    try:\n        xhalf, yhalf = (x[1] - x[0]) / 2.0, (y[1] - y[0]) / 2.0\n    except IndexError:\n        xhalf, yhalf = 0.5, 0.5\n\n    kw = dict(cmap='gray_r',\n              extent=[x.min() - xhalf, x.max() + xhalf,\n                      y.min() - yhalf, y.max() + yhalf],\n              interpolation='nearest')\n    if log:\n        y = np.log(map)\n    else:\n        y = map\n    ax_map.imshow(y, **kw)\n    if filename is not None:\n        fig.savefig(filename)\n", "meta": {"hexsha": "7a5f025e084929f1e62bc3e7b8a442e0e40ed102", "size": 14847, "ext": "py", "lang": "Python", "max_stars_repo_path": "Jitter.py", "max_stars_repo_name": "zkbt/spyffi", "max_stars_repo_head_hexsha": "2d6e40b9fdf6074b1bd732be38a7a29985292781", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-22T16:14:54.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-22T16:14:54.000Z", "max_issues_repo_path": "Jitter.py", "max_issues_repo_name": "zkbt/SPyFFI", "max_issues_repo_head_hexsha": "2d6e40b9fdf6074b1bd732be38a7a29985292781", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Jitter.py", "max_forks_repo_name": "zkbt/SPyFFI", "max_forks_repo_head_hexsha": "2d6e40b9fdf6074b1bd732be38a7a29985292781", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-16T10:40:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-16T10:40:37.000Z", "avg_line_length": 38.2654639175, "max_line_length": 123, "alphanum_fraction": 0.5909611369, "include": true, "reason": "import numpy,import scipy,import astropy", "num_tokens": 3804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.18088619075629198}}
{"text": "\"\"\"Implement the GeometricProgram class\"\"\"\nfrom __future__ import print_function\n# unicode_literals here interfere with the boundschecking example\nimport sys\nfrom time import time\nfrom collections import defaultdict\nimport numpy as np\nfrom ..nomials import NomialData\nfrom ..small_classes import CootMatrix, SolverLog, Numbers, FixedScalar\nfrom ..keydict import KeyDict\nfrom ..small_scripts import mag\nfrom ..solution_array import SolutionArray\nfrom .costed import CostedConstraintSet\nfrom ..exceptions import InvalidPosynomial\n\n\nDEFAULT_SOLVER_KWARGS = {\"cvxopt\": {\"kktsolver\": \"ldl\"}}\nSOLUTION_TOL = {\"cvxopt\": 1e-3, \"mosek_cli\": 1e-4, \"mosek\": 1e-5,\n                'mosek_conif': 1e-3}\n\n\ndef _get_solver(solver, kwargs):\n    \"\"\"Get the solverfn and solvername associated with solver\"\"\"\n    if solver is None:\n        from .. import settings\n        solver = settings.get(\"default_solver\", None)\n        if not solver:\n            raise ValueError(\n                \"No solver was given; perhaps gpkit was not properly\"\n                \" installed, or found no solvers during the\"\n                \" installation process.\")\n\n    if solver == \"cvxopt\":\n        from .._cvxopt import cvxoptimize\n        solverfn = cvxoptimize\n    elif solver == \"mosek_cli\":\n        from .._mosek import cli_expopt\n        solverfn = cli_expopt.imize_fn(**kwargs)\n    elif solver == \"mosek\":\n        from .._mosek import expopt\n        solverfn = expopt.imize\n    elif solver == 'mosek_conif':\n        from .._mosek import mosek_conif\n        solverfn = mosek_conif.mskoptimize\n    elif hasattr(solver, \"__call__\"):\n        solverfn = solver\n        solver = solver.__name__\n    else:\n        raise ValueError(\"Unknown solver '%s'.\" % solver)\n    return solverfn, solver\n\n\nclass GeometricProgram(CostedConstraintSet, NomialData):\n    # pylint: disable=too-many-instance-attributes\n    \"\"\"Standard mathematical representation of a GP.\n\n    Attributes with side effects\n    ----------------------------\n    `solver_out` and `solver_log` are set during a solve\n    `result` is set at the end of a solve if solution status is optimal\n\n    Examples\n    --------\n    >>> gp = gpkit.geometric_program.GeometricProgram(\n                        # minimize\n                        x,\n                        [   # subject to\n                            1/x  # <= 1, implicitly\n                        ], {})\n    >>> gp.solve()\n    \"\"\"\n    def __init__(self, cost, constraints, substitutions,\n                 allow_missingbounds=False):\n        # pylint:disable=super-init-not-called\n        # initialize attributes modified by internal methods\n        self._result = None\n        self.v_ss = None\n        self.nu_by_posy = None\n        self.solver_log = None\n        self.solver_out = None\n        self.__bare_init__(cost, constraints, substitutions, varkeys=False)\n        for key, sub in self.substitutions.items():\n            if isinstance(sub, FixedScalar):\n                sub = sub.value\n                if hasattr(sub, \"units\"):\n                    sub = sub.to(key.units or \"dimensionless\").magnitude\n                self.substitutions[key] = sub\n            # only allow Numbers and ndarrays\n            if not isinstance(sub, (Numbers, np.ndarray)):\n                raise ValueError(\"substitution {%s: %s} with value type %s is\"\n                                 \" not allowed in .substitutions.\"\n                                 % (key, sub, type(sub)))\n        try:\n            self.posynomials = [cost.sub(self.substitutions)]\n        except InvalidPosynomial:\n            raise InvalidPosynomial(\"cost must be a Posynomial\")\n        self.posynomials.extend(self.as_posyslt1(self.substitutions))\n        self.hmaps = [p.hmap for p in self.posynomials]\n        ## Generate various maps into the posy- and monomials\n        # k [j]: number of monomials (rows of A) present in each constraint\n        self.k = [len(hm) for hm in self.hmaps]\n        p_idxs = []  # p_idxs [i]: posynomial index of each monomial\n        self.m_idxs = []  # m_idxs [i]: monomial indices of each posynomial\n        for i, p_len in enumerate(self.k):\n            self.m_idxs.append(list(range(len(p_idxs), len(p_idxs) + p_len)))\n            p_idxs += [i]*p_len\n        self.p_idxs = np.array(p_idxs)\n        # m_idxs: first exp-index of each monomial equality\n        self.meq_idxs = {sum(self.k[:i]) for i, p in enumerate(self.posynomials)\n                         if getattr(p, \"from_meq\", False)}\n        self.gen()  # A [i, v]: sparse matrix of powers in each monomial\n        if self.missingbounds and not allow_missingbounds:\n            boundstrs = \"\\n\".join(\"  %s has no %s bound%s\" % (v, b, x)\n                                  for (v, b), x in self.missingbounds.items())\n            raise ValueError(\"Geometric Program is not fully bounded:\\n\"\n                             + boundstrs)\n\n    varkeys = NomialData.varkeys\n\n    def gen(self):\n        \"Generates nomial and solve data (A, p_idxs) from posynomials\"\n        self._hashvalue = self._varlocs = self._varkeys = None\n        self._exps, self._cs = [], []\n        for hmap in self.hmaps:\n            self._exps.extend(hmap.keys())\n            self._cs.extend(hmap.values())\n        self.vks = self.varlocs\n        self.A, self.missingbounds = genA(self.exps, self.varlocs,\n                                          self.meq_idxs)\n\n    # pylint: disable=too-many-statements, too-many-locals\n    def solve(self, solver=None, verbosity=1, warn_on_check=False,\n              process_result=True, gen_result=True, **kwargs):\n        \"\"\"Solves a GeometricProgram and returns the solution.\n\n        Arguments\n        ---------\n        solver : str or function (optional)\n            By default uses one of the solvers found during installation.\n            If set to \"mosek\", \"mosek_cli\", or \"cvxopt\", uses that solver.\n            If set to a function, passes that function cs, A, p_idxs, and k.\n        verbosity : int (default 1)\n            If greater than 0, prints solver name and solve time.\n        **kwargs :\n            Passed to solver constructor and solver function.\n\n\n        Returns\n        -------\n        result : SolutionArray\n        \"\"\"\n        solverfn, solvername = _get_solver(solver, kwargs)\n\n        starttime = time()\n        if verbosity > 0:\n            print(\"Using solver '%s'\" % solvername)\n            print(\"Solving for %i variables.\" % len(self.varlocs))\n\n        solver_kwargs = DEFAULT_SOLVER_KWARGS.get(solvername, {})\n        solver_kwargs.update(kwargs)\n\n        # NOTE: SIDE EFFECTS AS WE LOG SOLVER'S STDOUT AND OUTPUT\n        original_stdout = sys.stdout\n        self.solver_log = SolverLog(verbosity-1, original_stdout)\n        try:\n            sys.stdout = self.solver_log   # CAPTURED\n            solver_out = solverfn(c=self.cs, A=self.A, p_idxs=self.p_idxs,\n                                  k=self.k, **solver_kwargs)\n            self.solver_out = solver_out\n        finally:\n            sys.stdout = original_stdout\n        # STDOUT HAS BEEN RETURNED. ENDING SIDE EFFECTS.\n        self.solver_log = \"\\n\".join(self.solver_log)\n\n        solver_out[\"solver\"] = solvername\n        solver_out[\"soltime\"] = time() - starttime\n        if verbosity > 0:\n            print(\"Solving took %.3g seconds.\" % (solver_out[\"soltime\"],))\n\n        solver_status = str(solver_out.get(\"status\", None))\n        if solver_status.lower() != \"optimal\":\n            raise RuntimeWarning(\n                \"final status of solver '%s' was '%s', not 'optimal'.\\n\\n\"\n                \"The solver's result is stored in model.program.solver_out. \"\n                \"A result dict can be generated via \"\n                \"program._compile_result(program.solver_out).\" %\n                (solvername, solver_status))\n\n        if gen_result:  # NOTE: SIDE EFFECTS\n            self._result = self.generate_result(solver_out, warn_on_check,\n                                                verbosity, process_result)\n            return self.result\n\n        solver_out[\"gen_result\"] = \\\n            lambda: self.generate_result(solver_out, dual_check=False)\n        return solver_out\n\n    @property\n    def result(self):\n        \"Creates and caches a result from the raw solver_out\"\n        if not self._result:\n            self._result = self.generate_result(self.solver_out)\n        return self._result\n\n    def generate_result(self, solver_out, warn_on_check=True, verbosity=0,\n                        process_result=True, dual_check=True):\n        \"Generates a full SolutionArray and checks it.\"\n        if verbosity > 1:\n            tic = time()\n        soltime = solver_out[\"soltime\"]\n        result = self._compile_result(solver_out)  # NOTE: SIDE EFFECTS\n        if verbosity > 1:\n            print(\"result packing took %.2g%% of solve time\" %\n                  ((time() - tic) / soltime * 100))\n            tic = time()\n\n        try:\n            tol = SOLUTION_TOL.get(solver_out[\"solver\"], 1e-5)\n            self.check_solution(result[\"cost\"], solver_out['primal'],\n                                solver_out[\"nu\"], solver_out[\"la\"], tol)\n        except RuntimeWarning as e:\n            if warn_on_check:\n                e = str(e)\n                if dual_check or (\"Dual\" not in e and \"nu\" not in e):\n                    print(\"Solution check warning: %s\" % e)\n            else:\n                raise e\n        if verbosity > 1:\n            print(\"solution checking took %.2g%% of solve time\" %\n                  ((time() - tic) / soltime * 100))\n            tic = time()\n\n        if process_result:\n            self.process_result(result)\n        if verbosity > 1:\n            print(\"processing results took %.2g%% of solve time\" %\n                  ((time() - tic) / soltime * 100))\n        return result\n\n    def _generate_nula(self, solver_out):\n        if \"nu\" in solver_out:\n            # solver gave us monomial sensitivities, generate posynomial ones\n            nu = np.ravel(solver_out[\"nu\"])\n            self.nu_by_posy = [nu[mi] for mi in self.m_idxs]\n            la = np.array([sum(nup) for nup in self.nu_by_posy])\n        elif \"la\" in solver_out:\n            # solver gave us posynomial sensitivities, generate monomial ones\n            la = np.ravel(solver_out[\"la\"])\n            if len(la) == len(self.hmaps) - 1:\n                # assume the solver dropped the cost's sensitivity (always 1.0)\n                la = np.hstack(([1.0], la))\n            Ax = np.ravel(self.A.dot(solver_out['primal']))\n            z = Ax + np.log(self.cs)\n            m_iss = [self.p_idxs == i for i in range(len(la))]\n            self.nu_by_posy = [la[p_i]*np.exp(z[m_is])/sum(np.exp(z[m_is]))\n                               for p_i, m_is in enumerate(m_iss)]\n            nu = np.hstack(self.nu_by_posy)\n        else:\n            raise RuntimeWarning(\"The dual solution was not returned.\")\n        solver_out[\"nu\"], solver_out[\"la\"] = nu, la\n\n    def _compile_result(self, solver_out):\n        \"\"\"Creates a result dict (as returned by solve() from solver output\n\n        This internal method is called from within the solve() method, unless\n        solver_out[\"status\"] is not \"optimal\", in which case a RuntimeWarning\n        is raised prior to this method being called. In that case, users\n        may use this method to attempt to create a results dict from the\n        output of the failed solve.\n\n        Arguments\n        ---------\n        solver_out: dict\n            dict in format returned by solverfn within GeometricProgram.solve\n\n        Returns\n        -------\n        result: dict\n            dict in format returned by GeometricProgram.solve()\n        \"\"\"\n        self._generate_nula(solver_out)\n        primal = solver_out[\"primal\"]\n        nu, la = solver_out[\"nu\"], solver_out[\"la\"]\n        # confirm lengths before calling zip\n        if not self.varlocs and len(primal) == 1 and primal[0] == 0:\n            primal = []  # an empty result, as returned by MOSEK\n        assert len(self.varlocs) == len(primal)\n        result = {\"freevariables\": KeyDict(zip(self.varlocs, np.exp(primal)))}\n        # get cost #\n        if \"objective\" in solver_out:\n            result[\"cost\"] = float(solver_out[\"objective\"])\n        else:\n            # use self.posynomials[0] because the cost may have had constants\n            freev = result[\"freevariables\"]\n            cost = self.posynomials[0].sub(freev)\n            if cost.varkeys:\n                raise ValueError(\"cost contains unsolved variables %s\"\n                                 % cost.varkeys.keys())\n            result[\"cost\"] = mag(cost.c)\n        # get variables #\n        result[\"constants\"] = KeyDict(self.substitutions)\n        result[\"variables\"] = KeyDict(result[\"freevariables\"])\n        result[\"variables\"].update(result[\"constants\"])\n        # get sensitivities #\n        result[\"sensitivities\"] = {\"nu\": nu, \"la\": la}\n        self.v_ss = self.sens_from_dual(la[1:].tolist(), self.nu_by_posy[1:],\n                                        result)\n        # add cost's sensitivity in (nu could be self.nu_by_posy[0])\n        cost_senss = {var: sum([self.cost.exps[i][var]*nu[i] for i in locs])\n                      for (var, locs) in self.cost.varlocs.items()}\n        var_senss = self.v_ss.copy()\n        for key, value in cost_senss.items():\n            var_senss[key] = value + var_senss.get(key, 0)\n        # carry linked sensitivities over to their constants\n        for v in list(v for v in var_senss if v.gradients):\n            dlogcost_dlogv = var_senss.pop(v)\n            val = result[\"constants\"][v]\n            for c, dv_dc in v.gradients.items():\n                if val != 0:\n                    dlogv_dlogc = dv_dc * result[\"constants\"][c]/val\n                # make nans / infs explicitly to avoid warnings\n                elif dlogcost_dlogv == 0:\n                    dlogv_dlogc = np.nan\n                else:\n                    dlogv_dlogc = np.inf * dv_dc*result[\"constants\"][c]\n                accum = var_senss.get(c, 0)\n                var_senss[c] = dlogcost_dlogv*dlogv_dlogc + accum\n                if v in cost_senss:\n                    if c in self.cost.varkeys:\n                        dlogcost_dlogv = cost_senss.pop(v)\n                        accum = cost_senss.get(c, 0)\n                        cost_senss[c] = dlogcost_dlogv*dlogv_dlogc + accum\n\n        result[\"sensitivities\"][\"cost\"] = cost_senss\n        result[\"sensitivities\"][\"variables\"] = KeyDict(var_senss)\n        result[\"sensitivities\"][\"constants\"] = KeyDict(\n            {k: v for k, v in var_senss.items() if k in result[\"constants\"]})\n        result[\"soltime\"] = solver_out[\"soltime\"]\n        return SolutionArray(result)\n\n    def check_solution(self, cost, primal, nu, la, tol, abstol=1e-20):\n        \"\"\"Run a series of checks to mathematically confirm sol solves this GP\n\n        Arguments\n        ---------\n        cost:   float\n            cost returned by solver\n        primal: list\n            primal solution returned by solver\n        nu:     numpy.ndarray\n            monomial lagrange multiplier\n        la:     numpy.ndarray\n            posynomial lagrange multiplier\n\n        Raises\n        ------\n        RuntimeWarning, if any problems are found\n        \"\"\"\n        def _almost_equal(num1, num2):\n            \"local almost equal test\"\n            return (num1 == num2 or abs((num1 - num2) / (num1 + num2)) < tol\n                    or abs(num1 - num2) < abstol)\n        A = self.A.tocsr()\n        # check primal sol\n        primal_exp_vals = self.cs * np.exp(A.dot(primal))   # c*e^Ax\n        if not _almost_equal(primal_exp_vals[self.m_idxs[0]].sum(), cost):\n            raise RuntimeWarning(\"Primal solution computed cost did not match\"\n                                 \" solver-returned cost: %s vs %s\" %\n                                 (primal_exp_vals[self.m_idxs[0]].sum(), cost))\n        for mi in self.m_idxs[1:]:\n            if primal_exp_vals[mi].sum() > 1 + tol:\n                raise RuntimeWarning(\"Primal solution violates constraint:\"\n                                     \" %s is greater than 1.\" %\n                                     primal_exp_vals[mi].sum())\n        # check dual sol\n        # note: follows dual formulation in section 3.1 of\n        # http://web.mit.edu/~whoburg/www/papers/hoburg_phd_thesis.pdf\n        if not _almost_equal(self.nu_by_posy[0].sum(), 1.):\n            raise RuntimeWarning(\"Dual variables associated with objective sum\"\n                                 \" to %s, not 1\" % self.nu_by_posy[0].sum())\n        if any(nu < 0):\n            if all(nu > -tol/1000.):  # HACK, see issue 528\n                print(\"Allowing negative dual variable(s) as small as\"\n                      \" %s.\" % min(nu))\n            else:\n                raise RuntimeWarning(\"Dual solution has negative entries as\"\n                                     \" small as %s.\" % min(nu))\n        ATnu = A.T.dot(nu)\n        if any(np.abs(ATnu) > tol):\n            raise RuntimeWarning(\"sum of nu^T * A did not vanish\")\n        b = np.log(self.cs)\n        dual_cost = sum(\n            self.nu_by_posy[i].dot(\n                b[mi] - np.log(self.nu_by_posy[i]/la[i]))\n            for i, mi in enumerate(self.m_idxs) if la[i])\n        if not _almost_equal(np.exp(dual_cost), cost):\n            raise RuntimeWarning(\"Dual cost %s does not match primal\"\n                                 \" cost %s\" % (np.exp(dual_cost), cost))\n\n\ndef genA(exps, varlocs, meq_idxs):  # pylint: disable=invalid-name\n    \"\"\"Generates A matrix\n\n    Returns\n    -------\n        A : sparse Cootmatrix\n            Exponents of the various free variables for each monomial: rows\n            of A are monomials, columns of A are variables.\n        missingbounds : dict\n            Keys: variables that lack bounds. Values: which bounds are missed.\n    \"\"\"\n    missingbounds = {}\n    row, col, data = [], [], []\n    for j, var in enumerate(varlocs):\n        upperbound, lowerbound = False, False\n        row.extend(varlocs[var])\n        col.extend([j]*len(varlocs[var]))\n        data.extend(exps[i][var] for i in varlocs[var])\n        for i in varlocs[var]:\n            if i not in meq_idxs:\n                if upperbound and lowerbound:\n                    break\n                elif exps[i][var] > 0:  # pylint:disable=simplifiable-if-statement\n                    upperbound = True\n                else:\n                    lowerbound = True\n        if not upperbound:\n            missingbounds[(var, \"upper\")] = \"\"\n        if not lowerbound:\n            missingbounds[(var, \"lower\")] = \"\"\n\n    check_mono_eq_bounds(missingbounds, gen_mono_eq_bounds(exps, meq_idxs))\n\n    # space the matrix out for trailing constant terms\n    for i, exp in enumerate(exps):\n        if not exp:\n            row.append(i)\n            col.append(0)\n            data.append(0)\n    A = CootMatrix(row, col, data)\n\n    return A, missingbounds\n\n\ndef gen_mono_eq_bounds(exps, meq_idxs):  # pylint: disable=too-many-locals\n    \"Generate conditional monomial equality bounds\"\n    meq_bounds = defaultdict(set)\n    for i in meq_idxs:\n        if i % 2:  # skip the second index of a meq\n            continue\n        p_upper, p_lower, n_upper, n_lower = set(), set(), set(), set()\n        for key, x in exps[i].items():\n            if x > 0:\n                p_upper.add((key, \"upper\"))\n                p_lower.add((key, \"lower\"))\n            else:\n                n_upper.add((key, \"upper\"))\n                n_lower.add((key, \"lower\"))\n        # (consider x*y/z == 1)\n        # for a var (e.g. x) to be upper bounded by this monomial equality,\n        #   - vars of the same sign/side (y) must be lower bounded\n        #   - AND vars of the opposite sign/side (z) must be upper bounded\n        p_ub = frozenset(n_upper).union(p_lower)\n        p_lb = frozenset(n_lower).union(p_upper)\n        n_ub = frozenset(p_upper).union(n_lower)\n        n_lb = frozenset(p_lower).union(n_upper)\n        for keys, ub, lb in ((p_upper, p_ub, p_lb), (n_upper, n_ub, n_lb)):\n            for key, _ in keys:\n                meq_bounds[(key, \"upper\")].add(ub.difference([(key, \"lower\")]))\n                meq_bounds[(key, \"lower\")].add(lb.difference([(key, \"upper\")]))\n    return meq_bounds\n\n\ndef check_mono_eq_bounds(missingbounds, meq_bounds):\n    \"Bounds variables with monomial equalities\"\n    still_alive = True\n    while still_alive:\n        still_alive = False  # if no changes are made, the loop exits\n        for bound in list(meq_bounds):\n            if bound not in missingbounds:\n                del meq_bounds[bound]\n                continue\n            conditions = meq_bounds[bound]\n            for condition in conditions:\n                if not any(bound in missingbounds for bound in condition):\n                    del meq_bounds[bound]\n                    del missingbounds[bound]\n                    still_alive = True\n                    break\n    for (var, bound) in meq_bounds:\n        boundstr = (\", but would gain it from any of these\"\n                    \" sets of bounds: \")\n        for condition in list(meq_bounds[(var, bound)]):\n            meq_bounds[(var, bound)].remove(condition)\n            newcond = condition.intersection(missingbounds)\n            if newcond and not any(c.issubset(newcond)\n                                   for c in meq_bounds[(var, bound)]):\n                meq_bounds[(var, bound)].add(newcond)\n        boundstr += \" or \".join(str(list(condition))\n                                for condition in meq_bounds[(var, bound)])\n        missingbounds[(var, bound)] = boundstr\n", "meta": {"hexsha": "cf868438d38b9c4f62023672fb415bc4515bf253", "size": 21494, "ext": "py", "lang": "Python", "max_stars_repo_path": "gpkit/constraints/gp.py", "max_stars_repo_name": "giserh/gpkit", "max_stars_repo_head_hexsha": "71b953fcac8f67f148b67b54b6e8cd4182dc0b3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gpkit/constraints/gp.py", "max_issues_repo_name": "giserh/gpkit", "max_issues_repo_head_hexsha": "71b953fcac8f67f148b67b54b6e8cd4182dc0b3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gpkit/constraints/gp.py", "max_forks_repo_name": "giserh/gpkit", "max_forks_repo_head_hexsha": "71b953fcac8f67f148b67b54b6e8cd4182dc0b3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.8167330677, "max_line_length": 82, "alphanum_fraction": 0.5645761608, "include": true, "reason": "import numpy", "num_tokens": 5096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.29746994883293104, "lm_q1q2_score": 0.18076153626497296}}
{"text": "import numpy as np\nfrom pybullet_utils import bullet_client\nimport math\nfrom .math_utils import *\n\nclass HumanoidPoseInterpolator(object):\n\n  # REPRESENTATION_MODE_CHECKPOINT\n  # def __init__(self):\n  def __init__(self, arg_parser = None):\n    \n    # REPRESENTATION_MODE_CHECKPOINT\n    # self.state_representation_mode = \"Quaternion\"\n    # self.action_representation_mode = \"AxisAngle\"\n    # self.state_representation_mode = \"6D\"\n    # self.action_representation_mode = \"6D\"\n\n    # REPRESENTATION_MODE_CHECKPOINT\n    self._arg_parser = arg_parser\n    self.state_representation_mode = self._arg_parser.parse_string('state_repr', default=\"Quaternion\")\n    self.action_representation_mode = self._arg_parser.parse_string('action_repr', default=\"AxisAngle\")\n    \n    if self.action_representation_mode == \"Quaternion\":\n      self.action_dim = 4\n    elif self.action_representation_mode == \"Euler\":\n      self.action_dim = 3\n    elif self.action_representation_mode == \"AxisAngle\":\n      self.action_dim = 4\n    elif self.action_representation_mode == \"RotVec\":\n      self.action_dim = 3\n    elif self.action_representation_mode == \"RotMat\":\n      self.action_dim = 9\n    elif self.action_representation_mode == \"6D\":\n      self.action_dim = 6\n\n    pass\n\n\n  def Reset(self,\n            \n            basePos=[0, 0, 0],\n            baseOrn=[0, 0, 0, 1],\n\n            chestRot=[0, 0, 0, 1],\n            neckRot=[0, 0, 0, 1],\n            rightHipRot=[0, 0, 0, 1],\n            rightKneeRot=[0],\n            rightAnkleRot=[0, 0, 0, 1],\n            rightShoulderRot=[0, 0, 0, 1],\n            rightElbowRot=[0],\n            leftHipRot=[0, 0, 0, 1],\n            leftKneeRot=[0],\n            leftAnkleRot=[0, 0, 0, 1],\n            leftShoulderRot=[0, 0, 0, 1],\n            leftElbowRot=[0],\n            \n            baseLinVel=[0, 0, 0],\n            baseAngVel=[0, 0, 0],\n            \n            chestVel=[0, 0, 0],\n            neckVel=[0, 0, 0],\n            rightHipVel=[0, 0, 0],\n            rightKneeVel=[0],\n            rightAnkleVel=[0, 0, 0],\n            rightShoulderVel=[0, 0, 0],\n            rightElbowVel=[0],\n            leftHipVel=[0, 0, 0],\n            leftKneeVel=[0],\n            leftAnkleVel=[0, 0, 0],\n            leftShoulderVel=[0, 0, 0],\n            leftElbowVel=[0]):\n\n    self._basePos = basePos\n    self._baseLinVel = baseLinVel\n    #print(\"HumanoidPoseInterpolator.Reset: baseLinVel = \", baseLinVel)\n    self._baseOrn = baseOrn\n    self._baseAngVel = baseAngVel\n\n    self._chestRot = chestRot\n    self._chestVel = chestVel\n    self._neckRot = neckRot\n    self._neckVel = neckVel\n\n    self._rightHipRot = rightHipRot\n    self._rightHipVel = rightHipVel\n    self._rightKneeRot = rightKneeRot\n    self._rightKneeVel = rightKneeVel\n    self._rightAnkleRot = rightAnkleRot\n    self._rightAnkleVel = rightAnkleVel\n\n    self._rightShoulderRot = rightShoulderRot\n    self._rightShoulderVel = rightShoulderVel\n    self._rightElbowRot = rightElbowRot\n    self._rightElbowVel = rightElbowVel\n\n    self._leftHipRot = leftHipRot\n    self._leftHipVel = leftHipVel\n    self._leftKneeRot = leftKneeRot\n    self._leftKneeVel = leftKneeVel\n    self._leftAnkleRot = leftAnkleRot\n    self._leftAnkleVel = leftAnkleVel\n\n    self._leftShoulderRot = leftShoulderRot\n    self._leftShoulderVel = leftShoulderVel\n    self._leftElbowRot = leftElbowRot\n    self._leftElbowVel = leftElbowVel\n\n  def ComputeLinVel(self, posStart, posEnd, deltaTime):\n    vel = [(posEnd[0] - posStart[0]) / deltaTime, (posEnd[1] - posStart[1]) / deltaTime,\n           (posEnd[2] - posStart[2]) / deltaTime]\n    return vel\n\n  def ComputeAngVel(self, ornStart, ornEnd, deltaTime, bullet_client):\n    dorn = bullet_client.getDifferenceQuaternion(ornStart, ornEnd)\n    axis, angle = bullet_client.getAxisAngleFromQuaternion(dorn)\n    angVel = [(axis[0] * angle) / deltaTime, (axis[1] * angle) / deltaTime,\n              (axis[2] * angle) / deltaTime]\n    return angVel\n\n  def ComputeAngVelRel(self, ornStart, ornEnd, deltaTime, bullet_client):\n    ornStartConjugate = [-ornStart[0], -ornStart[1], -ornStart[2], ornStart[3]]\n    pos_diff, q_diff = bullet_client.multiplyTransforms([0, 0, 0], ornStartConjugate, [0, 0, 0],\n                                                        ornEnd)\n    axis, angle = bullet_client.getAxisAngleFromQuaternion(q_diff)\n    angVel = [(axis[0] * angle) / deltaTime, (axis[1] * angle) / deltaTime,\n              (axis[2] * angle) / deltaTime]\n    return angVel\n\n\n\n  def NormalizeVector(self, vec):\n    # length2 = vec[0] * vec[0] + vec[1] * vec[1] + vec[2] * vec[2]\n    length2 = self.DotProduct(vec, vec)\n    if (length2 > 0):\n      length = math.sqrt(length2)\n      vec[0] /= length\n      vec[1] /= length\n      vec[2] /= length\n      return vec\n\n  def NormalizeQuaternion(self, orn):\n    # length2 = orn[0] * orn[0] + orn[1] * orn[1] + orn[2] * orn[2] + orn[3] * orn[3]\n    length2 = self.DotProduct(orn, orn)\n    if (length2 > 0):\n      length = math.sqrt(length2)\n      orn[0] /= length\n      orn[1] /= length\n      orn[2] /= length\n      orn[3] /= length\n      return orn\n\n    #print(\"Normalize? length=\",length)\n\n  def PostProcessMotionData(self, frameData):\n    baseOrn1Start = [frameData[5], frameData[6], frameData[7], frameData[4]]\n\n    chestRotStart = [frameData[9], frameData[10], frameData[11], frameData[8]]\n\n    neckRotStart = [frameData[13], frameData[14], frameData[15], frameData[12]]\n    rightHipRotStart = [frameData[17], frameData[18], frameData[19], frameData[16]]\n    rightAnkleRotStart = [frameData[22], frameData[23], frameData[24], frameData[21]]\n    rightShoulderRotStart = [frameData[26], frameData[27], frameData[28], frameData[25]]\n    leftHipRotStart = [frameData[31], frameData[32], frameData[33], frameData[30]]\n    leftAnkleRotStart = [frameData[36], frameData[37], frameData[38], frameData[35]]\n    leftShoulderRotStart = [frameData[40], frameData[41], frameData[42], frameData[39]]\n\n  def GetPose(self):\n    pose = [\n        # these 7 elements will be zero-ed out in pybullet_deep_mimic_env.set_action()\n        self._basePos[0], self._basePos[1], self._basePos[2],\n        self._baseOrn[0], self._baseOrn[1], self._baseOrn[2], self._baseOrn[3], \n        # these values will be given in ConvertFromAction()\n        self._chestRot[0], self._chestRot[1], self._chestRot[2], self._chestRot[3],\n        self._neckRot[0], self._neckRot[1], self._neckRot[2], self._neckRot[3],\n        self._rightHipRot[0], self._rightHipRot[1], self._rightHipRot[2], self._rightHipRot[3],\n        self._rightKneeRot[0],\n        self._rightAnkleRot[0], self._rightAnkleRot[1], self._rightAnkleRot[2], self._rightAnkleRot[3],\n        self._rightShoulderRot[0], self._rightShoulderRot[1], self._rightShoulderRot[2], self._rightShoulderRot[3],\n        self._rightElbowRot[0],\n        self._leftHipRot[0], self._leftHipRot[1], self._leftHipRot[2], self._leftHipRot[3],\n        self._leftKneeRot[0],\n        self._leftAnkleRot[0], self._leftAnkleRot[1], self._leftAnkleRot[2], self._leftAnkleRot[3],\n        self._leftShoulderRot[0], self._leftShoulderRot[1], self._leftShoulderRot[2], self._leftShoulderRot[3],\n        self._leftElbowRot[0]\n    ]\n    return pose\n\n  def Slerp(self, frameFraction, frameData, frameDataNext, bullet_client):\n    keyFrameDuration = frameData[0]\n    basePos1Start = [frameData[1], frameData[2], frameData[3]]\n    basePos1End = [frameDataNext[1], frameDataNext[2], frameDataNext[3]]\n    self._basePos = [\n        basePos1Start[0] + frameFraction * (basePos1End[0] - basePos1Start[0]),\n        basePos1Start[1] + frameFraction * (basePos1End[1] - basePos1Start[1]),\n        basePos1Start[2] + frameFraction * (basePos1End[2] - basePos1Start[2])\n    ]\n    self._baseLinVel = self.ComputeLinVel(basePos1Start, basePos1End, keyFrameDuration)\n    baseOrn1Start = [frameData[5], frameData[6], frameData[7], frameData[4]]\n    baseOrn1Next = [frameDataNext[5], frameDataNext[6], frameDataNext[7], frameDataNext[4]]\n    self._baseOrn = bullet_client.getQuaternionSlerp(baseOrn1Start, baseOrn1Next, frameFraction)\n    self._baseAngVel = self.ComputeAngVel(baseOrn1Start, baseOrn1Next, keyFrameDuration,\n                                          bullet_client)\n\n    ##pre-rotate to make z-up\n    #y2zPos=[0,0,0.0]\n    #y2zOrn = p.getQuaternionFromEuler([1.57,0,0])\n    #basePos,baseOrn = p.multiplyTransforms(y2zPos, y2zOrn,basePos1,baseOrn1)\n\n    chestRotStart = [frameData[9], frameData[10], frameData[11], frameData[8]]\n    chestRotEnd = [frameDataNext[9], frameDataNext[10], frameDataNext[11], frameDataNext[8]]\n    self._chestRot = bullet_client.getQuaternionSlerp(chestRotStart, chestRotEnd, frameFraction)\n    self._chestVel = self.ComputeAngVelRel(chestRotStart, chestRotEnd, keyFrameDuration,\n                                           bullet_client)\n\n    neckRotStart = [frameData[13], frameData[14], frameData[15], frameData[12]]\n    neckRotEnd = [frameDataNext[13], frameDataNext[14], frameDataNext[15], frameDataNext[12]]\n    self._neckRot = bullet_client.getQuaternionSlerp(neckRotStart, neckRotEnd, frameFraction)\n    self._neckVel = self.ComputeAngVelRel(neckRotStart, neckRotEnd, keyFrameDuration,\n                                          bullet_client)\n\n    rightHipRotStart = [frameData[17], frameData[18], frameData[19], frameData[16]]\n    rightHipRotEnd = [frameDataNext[17], frameDataNext[18], frameDataNext[19], frameDataNext[16]]\n    self._rightHipRot = bullet_client.getQuaternionSlerp(rightHipRotStart, rightHipRotEnd,\n                                                         frameFraction)\n    self._rightHipVel = self.ComputeAngVelRel(rightHipRotStart, rightHipRotEnd, keyFrameDuration,\n                                              bullet_client)\n\n    rightKneeRotStart = [frameData[20]]\n    rightKneeRotEnd = [frameDataNext[20]]\n    self._rightKneeRot = [\n        rightKneeRotStart[0] + frameFraction * (rightKneeRotEnd[0] - rightKneeRotStart[0])\n    ]\n    self._rightKneeVel = [(rightKneeRotEnd[0] - rightKneeRotStart[0]) / keyFrameDuration]\n\n    rightAnkleRotStart = [frameData[22], frameData[23], frameData[24], frameData[21]]\n    rightAnkleRotEnd = [frameDataNext[22], frameDataNext[23], frameDataNext[24], frameDataNext[21]]\n    self._rightAnkleRot = bullet_client.getQuaternionSlerp(rightAnkleRotStart, rightAnkleRotEnd,\n                                                           frameFraction)\n    self._rightAnkleVel = self.ComputeAngVelRel(rightAnkleRotStart, rightAnkleRotEnd,\n                                                keyFrameDuration, bullet_client)\n\n    rightShoulderRotStart = [frameData[26], frameData[27], frameData[28], frameData[25]]\n    rightShoulderRotEnd = [\n        frameDataNext[26], frameDataNext[27], frameDataNext[28], frameDataNext[25]\n    ]\n    self._rightShoulderRot = bullet_client.getQuaternionSlerp(rightShoulderRotStart,\n                                                              rightShoulderRotEnd, frameFraction)\n    self._rightShoulderVel = self.ComputeAngVelRel(rightShoulderRotStart, rightShoulderRotEnd,\n                                                   keyFrameDuration, bullet_client)\n\n    rightElbowRotStart = [frameData[29]]\n    rightElbowRotEnd = [frameDataNext[29]]\n    self._rightElbowRot = [\n        rightElbowRotStart[0] + frameFraction * (rightElbowRotEnd[0] - rightElbowRotStart[0])\n    ]\n    self._rightElbowVel = [(rightElbowRotEnd[0] - rightElbowRotStart[0]) / keyFrameDuration]\n\n    leftHipRotStart = [frameData[31], frameData[32], frameData[33], frameData[30]]\n    leftHipRotEnd = [frameDataNext[31], frameDataNext[32], frameDataNext[33], frameDataNext[30]]\n    self._leftHipRot = bullet_client.getQuaternionSlerp(leftHipRotStart, leftHipRotEnd,\n                                                        frameFraction)\n    self._leftHipVel = self.ComputeAngVelRel(leftHipRotStart, leftHipRotEnd, keyFrameDuration,\n                                             bullet_client)\n\n    leftKneeRotStart = [frameData[34]]\n    leftKneeRotEnd = [frameDataNext[34]]\n    self._leftKneeRot = [\n        leftKneeRotStart[0] + frameFraction * (leftKneeRotEnd[0] - leftKneeRotStart[0])\n    ]\n    self._leftKneeVel = [(leftKneeRotEnd[0] - leftKneeRotStart[0]) / keyFrameDuration]\n\n    leftAnkleRotStart = [frameData[36], frameData[37], frameData[38], frameData[35]]\n    leftAnkleRotEnd = [frameDataNext[36], frameDataNext[37], frameDataNext[38], frameDataNext[35]]\n    self._leftAnkleRot = bullet_client.getQuaternionSlerp(leftAnkleRotStart, leftAnkleRotEnd,\n                                                          frameFraction)\n    self._leftAnkleVel = self.ComputeAngVelRel(leftAnkleRotStart, leftAnkleRotEnd,\n                                               keyFrameDuration, bullet_client)\n\n    leftShoulderRotStart = [frameData[40], frameData[41], frameData[42], frameData[39]]\n    leftShoulderRotEnd = [\n        frameDataNext[40], frameDataNext[41], frameDataNext[42], frameDataNext[39]\n    ]\n    self._leftShoulderRot = bullet_client.getQuaternionSlerp(leftShoulderRotStart,\n                                                             leftShoulderRotEnd, frameFraction)\n    self._leftShoulderVel = self.ComputeAngVelRel(leftShoulderRotStart, leftShoulderRotEnd,\n                                                  keyFrameDuration, bullet_client)\n\n    leftElbowRotStart = [frameData[43]]\n    leftElbowRotEnd = [frameDataNext[43]]\n    self._leftElbowRot = [\n        leftElbowRotStart[0] + frameFraction * (leftElbowRotEnd[0] - leftElbowRotStart[0])\n    ]\n    self._leftElbowVel = [(leftElbowRotEnd[0] - leftElbowRotStart[0]) / keyFrameDuration]\n\n    pose = self.GetPose()\n    return pose\n\n\n  def ConvertFromAction(self, pybullet_client, action):\n    #turn action into pose\n\n    self.Reset()  #?? needed?\n    index = 0\n    \n    self._chestRot = getQuaternionFromAction(action[index:index+self.action_dim], self.action_representation_mode)\n    index += self.action_dim\n    self._neckRot = getQuaternionFromAction(action[index:index+self.action_dim], self.action_representation_mode)\n    index += self.action_dim\n    self._rightHipRot = getQuaternionFromAction(action[index:index+self.action_dim], self.action_representation_mode)\n    index += self.action_dim\n    self._rightKneeRot = [action[index]]\n    index += 1\n    self._rightAnkleRot = getQuaternionFromAction(action[index:index+self.action_dim], self.action_representation_mode)\n    index += self.action_dim\n    self._rightShoulderRot = getQuaternionFromAction(action[index:index+self.action_dim], self.action_representation_mode)\n    index += self.action_dim\n    self._rightElbowRot = [action[index]]\n    index += 1\n    self._leftHipRot = getQuaternionFromAction(action[index:index+self.action_dim], self.action_representation_mode)\n    index += self.action_dim\n    self._leftKneeRot = [action[index]]\n    index += 1\n    self._leftAnkleRot = getQuaternionFromAction(action[index:index+self.action_dim], self.action_representation_mode)\n    index += self.action_dim\n    self._leftShoulderRot = getQuaternionFromAction(action[index:index+self.action_dim], self.action_representation_mode)\n    index += self.action_dim\n    self._leftElbowRot = [action[index]]\n    index += 1\n\n    # if self.action_representation_mode == \"6D\":\n    #   sixdim = action[index:index + 6]\n    #   axis, angle = getAxisAngleFromSixDim(sixdim)\n    #   self._chestRot = pybullet_client.getQuaternionFromAxisAngle(axis, angle)\n    #   index += 6\n\n    #   sixdim = action[index:index + 6]\n    #   axis, angle = getAxisAngleFromSixDim(sixdim)\n    #   self._neckRot = pybullet_client.getQuaternionFromAxisAngle(axis, angle)\n    #   index += 6\n\n    #   sixdim = action[index:index + 6]\n    #   axis, angle = getAxisAngleFromSixDim(sixdim)\n    #   self._rightHipRot = pybullet_client.getQuaternionFromAxisAngle(axis, angle)\n    #   index += 6\n\n    #   angle = action[index]\n    #   self._rightKneeRot = [angle]\n    #   index += 1\n\n    #   sixdim = action[index:index + 6]\n    #   axis, angle = getAxisAngleFromSixDim(sixdim)\n    #   self._rightAnkleRot = pybullet_client.getQuaternionFromAxisAngle(axis, angle)\n    #   index += 6\n\n    #   sixdim = action[index:index + 6]\n    #   axis, angle = getAxisAngleFromSixDim(sixdim)\n    #   self._rightShoulderRot = pybullet_client.getQuaternionFromAxisAngle(axis, angle)\n    #   index += 6\n\n    #   angle = action[index]\n    #   self._rightElbowRot = [angle]\n    #   index += 1\n\n    #   sixdim = action[index:index + 6]\n    #   axis, angle = getAxisAngleFromSixDim(sixdim)\n    #   self._leftHipRot = pybullet_client.getQuaternionFromAxisAngle(axis, angle)\n    #   index += 6\n\n    #   angle = action[index]\n    #   self._leftKneeRot = [angle]\n    #   index += 1\n\n    #   sixdim = action[index:index + 6]\n    #   axis, angle = getAxisAngleFromSixDim(sixdim)\n    #   self._leftAnkleRot = pybullet_client.getQuaternionFromAxisAngle(axis, angle)\n    #   index += 6\n\n    #   sixdim = action[index:index + 6]\n    #   axis, angle = getAxisAngleFromSixDim(sixdim)\n    #   self._leftShoulderRot = pybullet_client.getQuaternionFromAxisAngle(axis, angle)\n    #   index += 6\n\n    #   angle = action[index]\n    #   self._leftElbowRot = [angle]\n    #   index += 1\n    \n    # elif self.action_representation_mode == \"AxisAngle\":    \n    #   angle = action[index]\n    #   axis = [action[index + 1], action[index + 2], action[index + 3]]\n    #   index += 4\n    #   self._chestRot = pybullet_client.getQuaternionFromAxisAngle(axis, angle)\n    #   #print(\"pose._chestRot=\",pose._chestRot)\n\n    #   angle = action[index]\n    #   axis = [action[index + 1], action[index + 2], action[index + 3]]\n    #   index += 4\n    #   self._neckRot = pybullet_client.getQuaternionFromAxisAngle(axis, angle)\n\n    #   angle = action[index]\n    #   axis = [action[index + 1], action[index + 2], action[index + 3]]\n    #   index += 4\n    #   self._rightHipRot = pybullet_client.getQuaternionFromAxisAngle(axis, angle)\n\n    #   angle = action[index]\n    #   index += 1\n    #   self._rightKneeRot = [angle]\n\n    #   angle = action[index]\n    #   axis = [action[index + 1], action[index + 2], action[index + 3]]\n    #   index += 4\n    #   self._rightAnkleRot = pybullet_client.getQuaternionFromAxisAngle(axis, angle)\n\n    #   angle = action[index]\n    #   axis = [action[index + 1], action[index + 2], action[index + 3]]\n    #   index += 4\n    #   self._rightShoulderRot = pybullet_client.getQuaternionFromAxisAngle(axis, angle)\n\n    #   angle = action[index]\n    #   index += 1\n    #   self._rightElbowRot = [angle]\n\n    #   angle = action[index]\n    #   axis = [action[index + 1], action[index + 2], action[index + 3]]\n    #   index += 4\n    #   self._leftHipRot = pybullet_client.getQuaternionFromAxisAngle(axis, angle)\n\n    #   angle = action[index]\n    #   index += 1\n    #   self._leftKneeRot = [angle]\n\n    #   angle = action[index]\n    #   axis = [action[index + 1], action[index + 2], action[index + 3]]\n    #   index += 4\n    #   self._leftAnkleRot = pybullet_client.getQuaternionFromAxisAngle(axis, angle)\n\n    #   angle = action[index]\n    #   axis = [action[index + 1], action[index + 2], action[index + 3]]\n    #   index += 4\n    #   self._leftShoulderRot = pybullet_client.getQuaternionFromAxisAngle(axis, angle)\n\n    #   angle = action[index]\n    #   index += 1\n    #   self._leftElbowRot = [angle]\n      \n    pose = self.GetPose()\n\n    return pose", "meta": {"hexsha": "83dc94317a7705b78a05660966d77f079080604c", "size": 19284, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/pybullet/gym/pybullet_envs/deep_mimic/env/humanoid_pose_interpolator.py", "max_stars_repo_name": "joonkyu4220/bullet3", "max_stars_repo_head_hexsha": "a5fb6c158f6cb744f476d7f1a5fbf6bf611cd9e1", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/pybullet/gym/pybullet_envs/deep_mimic/env/humanoid_pose_interpolator.py", "max_issues_repo_name": "joonkyu4220/bullet3", "max_issues_repo_head_hexsha": "a5fb6c158f6cb744f476d7f1a5fbf6bf611cd9e1", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/pybullet/gym/pybullet_envs/deep_mimic/env/humanoid_pose_interpolator.py", "max_forks_repo_name": "joonkyu4220/bullet3", "max_forks_repo_head_hexsha": "a5fb6c158f6cb744f476d7f1a5fbf6bf611cd9e1", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.1409395973, "max_line_length": 122, "alphanum_fraction": 0.6542729724, "include": true, "reason": "import numpy", "num_tokens": 5559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.18076152446862886}}
{"text": "from mpi4py import MPI\nfrom neuron import h\nfrom Simulation import Simulation\nfrom cells import AfferentFiber\nimport random as rnd\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nimport pickle\nfrom tools import seed_handler as sh\nsh.set_seed()\n\ncomm = MPI.COMM_WORLD\nsizeComm = comm.Get_size()\nrank = comm.Get_rank()\n\nclass CollisionEesNatural(Simulation):\n\t\"\"\" Simulation to evaluate the effect of EES on the natural firing rate in function of the fiber\n\tlegnth, of its firing rate and of the frequency of stimulation.\n\t\"\"\"\n\n\tdef __init__(self, parallelContext, eesFrequencies, fiberDelays, fiberFiringRates, segmentToRecord = None, tstop = 5000):\n\t\t\"\"\" Object initialization.\n\n\t\tKeyword arguments:\n\t\tparallelContext -- Neuron parallelContext object.\n\t\teesFrequencies -- List of stimulation frequencies to test.\n\t\tfiberDelays -- List of fiber delays to test.\n\t\tfiberFiringRates -- List of fiber firing rates to test.\n\t\t\"\"\"\n\n\t\tSimulation.__init__(self,parallelContext)\n\n\t\tif rank==1:\n\t\t\tprint \"\\nMPI execution: the different processes have different stimulation starting time.\"\n\t\t\tprint \"The final result is the mean results between each process\\n\"\n\n\t\t# Variables initializations\n\t\tself._eesFrequencies = eesFrequencies\n\t\tself._fiberDelays = fiberDelays\n\t\tself._fiberFiringRates = fiberFiringRates\n\t\tself._segmentToRecord = segmentToRecord\n\n\t\tself._init_lists()\n\t\tself._results = np.zeros([len(self._eesFrequencies),len(self._fiberDelays),len(self._fiberFiringRates)])\n\n\t\tself._create_fibers()\n\t\tself._create_ees_objects()\n\t\tself._connect_ees_to_fibers()\n\n\t\tself._set_tstop(tstop)\n\t\tself._set_integration_step(AfferentFiber.get_update_period())\n\n\n\t\"\"\"\n\tRedefinition of inherited methods\n\t\"\"\"\n\n\tdef _update(self):\n\t\t\"\"\" Update simulation parameters. \"\"\"\n\t\tself._update_afferents()\n\n\tdef _end_integration(self):\n\t\t\"\"\" Print the total simulation time and extract the results. \"\"\"\n\t\tSimulation._end_integration(self)\n\t\tself._extract_results()\n\n\tdef save_results(self,name=\"\"):\n\t\t\"\"\" Save the simulation results.\n\n\t\tKeyword arguments:\n\t\tname -- string to add at predefined file name (default = \"\").\n\t\t\"\"\"\n\t\tfileName = time.strftime(\"%Y_%m_%d_resultsCollisionEesNatural\"+name+\".p\")\n\t\twith open(self._resultsFolder+fileName, 'w') as pickle_file:\n\t\t\tpickle.dump(self._results, pickle_file)\n\t\t\tpickle.dump(self._eesFrequencies, pickle_file)\n\t\t\tpickle.dump(self._fiberDelays, pickle_file)\n\t\t\tpickle.dump(self._fiberFiringRates, pickle_file)\n\n\tdef plot(self,delay,nColorLevels=None,name=\"\"):\n\t\t\"\"\" Plot the simulation results.\n\n\t\tPlot the percantage of collisions for a given delay in fucntion of the afferent\n\t\tfiring rate and of the stimulation frequency.\n\t\tKeyword arguments:\n\t\tdelay -- fiber delay for which we want the plot.\n\t\tThreshold -- threshold to plot binary simulation results (default = None).\n\t\t\"\"\"\n\t\tif rank == 0:\n\t\t\tfig, ax = plt.subplots(figsize=(16,9))\n\n\t\t\tdataToPlot = self._results[:,delay,:]\n\t\t\ttitle = \"Percentage of sensory information erased by the stimulation\\n (delay \"+str(self._fiberDelays[delay])+\" ms)\"\n\t\t\tif nColorLevels is not None:\n\t\t\t\tdataToPlot=np.round(dataToPlot/100*nColorLevels)*100/nColorLevels\n\t\t\t\tprint dataToPlot\n\t\t\t\ttitle += \"\\nnColorLevels = \"+str(nColorLevels)\n\n\t\t\t# cmap = plt.cm.gray\n\t\t\tcmap = plt.cm.bone_r\n\t\t\tim = ax.imshow(dataToPlot, cmap=cmap, interpolation='nearest',origin=\"lower\",vmin = 0, vmax = 100)\n\t\t\tax.set_title(title)\n\n\t\t\t# Move left and bottom spines outward by 10 points\n\t\t\tax.spines['left'].set_position(('outward', 10))\n\t\t\tax.spines['bottom'].set_position(('outward', 10))\n\t\t\t# Hide the right and top spines\n\t\t\tax.spines['right'].set_visible(False)\n\t\t\tax.spines['top'].set_visible(False)\n\t\t\t# Only show ticks on the left and bottom spines\n\t\t\tax.yaxis.set_ticks_position('left')\n\t\t\tax.xaxis.set_ticks_position('bottom')\n\t\t\tfig.colorbar(im, orientation='vertical',label='% Erased APs')\n\n\t\t\tplt.yticks(range(len(self._eesFrequencies)),self._eesFrequencies)\n\t\t\tplt.xticks(range(len(self._fiberFiringRates)),self._fiberFiringRates)\n\t\t\tplt.ylabel('EES eesFrequency (Hz)')\n\t\t\tplt.xlabel('Natural afferent firing rate (hz)')\n\n\t\t\tfileName = time.strftime(\"%Y_%m_%d_CollisionEesNatural_Delay_\"+str(self._fiberDelays[delay])+name+\".pdf\")\n\t\t\tplt.savefig(self._resultsFolder+fileName, format=\"pdf\",transparent=True)\n\t\t\tplt.show(block=False)\n\n\t\"\"\"\n\tSpecific Methods of this class\n\t\"\"\"\n\tdef _init_lists(self):\n\t\t\"\"\" Initialize lists containg the fibers, netcon objects and ees objects. \"\"\"\n\t\tself._fiberList = [[[] for i in range(len(self._fiberDelays))] for j in range(len(self._eesFrequencies))]\n\t\tself._netconList = [[[] for i in range(len(self._fiberDelays))] for j in range(len(self._eesFrequencies))]\n\t\tself._eesList = []\n\n\tdef _create_fibers(self):\n\t\t\"\"\" Create the fibers with the defined different delays. \"\"\"\n\t\tfor i in range(len(self._eesFrequencies)):\n\t\t\tfor j in range(len(self._fiberDelays)):\n\t\t\t\tfor k in range(len(self._fiberFiringRates)):\n\t\t\t\t\tself._fiberList[i][j].append(AfferentFiber(self._fiberDelays[j]))\n\t\t\t\t\tif self._segmentToRecord is None:\n\t\t\t\t\t\tself._fiberList[i][j][k].set_firing_rate(self._fiberFiringRates[k])\n\t\t\t\t\tif self._segmentToRecord is not None:\n\t\t\t\t\t\tself._fiberList[i][j][k].set_firing_rate(self._fiberFiringRates[k],False)\n\t\t\t\t\t\tself._fiberList[i][j][k].set_recording(True,self._segmentToRecord)\n\n\tdef _create_ees_objects(self):\n\t\t\"\"\" Create different ees objects with the defined stimulation frequencies. \"\"\"\n\t\tscale = rnd.random()\n\t\tfor i in range(len(self._eesFrequencies)):\n\t\t\tself._eesList.append(h.NetStim())\n\t\t\tself._eesList[i].interval = 1000.0/self._eesFrequencies[i]\n\t\t\tself._eesList[i].number = 10000\n\t\t\tself._eesList[i].start = 10.0*scale\n\t\t\tself._eesList[i].noise = 0\n\n\tdef _connect_ees_to_fibers(self):\n\t\t\"\"\" Connect fibers ojects to ees objects to make the stimulation activate these fibers. \"\"\"\n\t\tfor i in range(len(self._eesFrequencies)):\n\t\t\tfor j in range(len(self._fiberDelays)):\n\t\t\t\tfor k in range(len(self._fiberFiringRates)):\n\t\t\t\t\tself._netconList[i][j].append(h.NetCon(self._eesList[i],self._fiberList[i][j][k].cell))\n\t\t\t\t\tself._netconList[i][j][k].delay = 1\n\t\t\t\t\tself._netconList[i][j][k].weight[0] = AfferentFiber.get_ees_weight()\n\n\tdef _update_afferents(self):\n\t\t\"\"\" Update the afferents fiber state. \"\"\"\n\t\tfor i in range(len(self._eesFrequencies)):\n\t\t\tfor j in range(len(self._fiberDelays)):\n\t\t\t\tfor k in range(len(self._fiberFiringRates)):\n\t\t\t\t\tself._fiberList[i][j][k].update(h.t)\n\n\tdef _extract_results(self):\n\t\t\"\"\" Extract the simulation results. \"\"\"\n\t\tfor i in range(len(self._eesFrequencies)):\n\t\t\tfor j in range(len(self._fiberDelays)):\n\t\t\t\tfor k in range(len(self._fiberFiringRates)):\n\t\t\t\t\tsent,arr,coll,perc=self._fiberList[i][j][k].get_stats()\n\t\t\t\t\tself._results[i,j,k]=perc\n\t\tcomm.Barrier()\n\t\tif sizeComm>1:\n\t\t\ttemp = comm.gather(self._results, root=0)\n\t\t\tif rank==0:\n\t\t\t\tfor i in range(1,sizeComm):\n\t\t\t\t\tself._results += temp[i]\n\t\t\t\tself._results/=sizeComm\n\n\tdef plot_isoinformation_surface(self,percentage=50):\n\t\t\"\"\" Plot a surface where the number of AP erased by the stimulation is equal. \"\"\"\n\t\tif rank==0:\n\t\t\tZ = np.zeros([len(self._fiberFiringRates),len(self._fiberDelays)])\n\t\t\ttemp = (self._results - percentage)**2\n\t\t\tfor x in xrange(len(self._fiberFiringRates)):\n\t\t\t\tfor y in xrange(len(self._fiberDelays)):\n\t\t\t\t\tZ[x,y]=self._eesFrequencies[temp[:,y,x].argmin()]\n\n\t\t\tfig, ax = plt.subplots(figsize=(16,9))\n\t\t\tim = ax.imshow(Z, cmap=plt.cm.bone, interpolation='nearest',origin=\"lower\")\n\t\t\tax.set_title(\"Isoinformation surface - \"+str(percentage)+\"% of APs erased\")\n\n\t\t\t# Move left and bottom spines outward by 10 points\n\t\t\tax.spines['left'].set_position(('outward', 10))\n\t\t\tax.spines['bottom'].set_position(('outward', 10))\n\t\t\t# Hide the right and top spines\n\t\t\tax.spines['right'].set_visible(False)\n\t\t\tax.spines['top'].set_visible(False)\n\t\t\t# Only show ticks on the left and bottom spines\n\t\t\tax.yaxis.set_ticks_position('left')\n\t\t\tax.xaxis.set_ticks_position('bottom')\n\t\t\tfig.colorbar(im, orientation='vertical', label=\"Stimulation frequency (Hz)\")\n\n\t\t\tplt.xticks(range(len(self._fiberDelays)),self._fiberDelays)\n\t\t\tplt.yticks(range(len(self._fiberFiringRates)),self._fiberFiringRates)\n\t\t\tplt.xlabel('Fiber delay (ms)')\n\t\t\tplt.ylabel('Natural afferents firing rate (hz)')\n\n\t\t\tfileName = time.strftime(\"%Y_%m_%d_CollisionEesNatural_Isoinfo_\"+str(percentage)+\"perc.pdf\")\n\t\t\tplt.savefig(self._resultsFolder+fileName, format=\"pdf\",transparent=True)\n\t\t\tplt.show(block=False)\n\n\tdef plot_recorded_segment(self, freqInd = 0, delInd = 0, firInd = 0):\n\t\t\"\"\" Plot recorded spikes from a fiber.\n\n\t\t\tKeyword arguments:\n\t\t\tfreqInd -- index of the stimulation frequencies.\n\t\t\tdelInd -- index of the fiber delay.\n\t\t\tfirInd -- index of the fiber natural firing rate.\n\t\t\"\"\"\n\n\t\tif self._segmentToRecord == None: return\n\t\tnaturalSignals, eesInducedSignals, trigger, time = self._fiberList[freqInd][delInd][firInd].get_recording()\n\t\tnNaturalSent,nNaturalArrived,nCollisions,percErasedAp = self._fiberList[freqInd][delInd][firInd].get_stats()\n\n\t\tfig1, ax1 = plt.subplots(1, 1, figsize=(8,4.5))\n\t\tmsToRec = 20\n\t\tsumTrigNaturalSignal = np.zeros(msToRec)\n\t\tsumTrigEesSignal = np.zeros(msToRec)\n\t\tnPeripheralStims = nNaturalSent*np.ones(msToRec)\n\n\t\tfor i,val in enumerate(trigger):\n\t\t\tif val and i+msToRec<len(time):\n\t\t\t\tsumTrigNaturalSignal += naturalSignals[i:i+msToRec]\n\t\t\t\tsumTrigEesSignal += eesInducedSignals[i:i+msToRec]\n\t\tax1.plot(sumTrigNaturalSignal,color='b',label='peripheral')\n\t\tax1.plot(sumTrigEesSignal,color='r',label='spinal')\n\t\tax1.plot(nPeripheralStims,color='g',ls = '--', label='n peripheral stims')\n\t\tax1.set_ylim([-10,nNaturalSent+10])\n\n\t\tcollisionPerc = 100*(1-sumTrigNaturalSignal.max()/float(nNaturalSent))\n\t\tax1.set_title(\"Spikes in segment {0}, collision perc: {1:.1f}%\".format(self._segmentToRecord,collisionPerc))\n\t\tax1.legend()\n\n\t\tfig2, ax2 = plt.subplots(1, 1, figsize=(16,4))\n\t\tax2.plot(time,naturalSignals,color='b',label='peripheral')\n\t\tax2.plot(time,eesInducedSignals,color='r',label='spinal')\n\t\tax2.plot(time,trigger,color='g',label='trigger',ls='--')\n\t\tax2.set_ylim([-0.5,1.5])\n\t\tax2.legend()\n\t\tplt.show()\n", "meta": {"hexsha": "dcdde33b9bd042a8f104afbaa3a0ae57c3af9cf9", "size": 10126, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/simulations/CollisionEesNatural.py", "max_stars_repo_name": "neurorestore/neuraldynamicplatform", "max_stars_repo_head_hexsha": "ac32df03a8892dafdf9765c6148b60ccdd34f1d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-27T03:46:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-01T10:29:45.000Z", "max_issues_repo_path": "code/simulations/CollisionEesNatural.py", "max_issues_repo_name": "neurorestore/neuraldynamicplatform", "max_issues_repo_head_hexsha": "ac32df03a8892dafdf9765c6148b60ccdd34f1d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/simulations/CollisionEesNatural.py", "max_forks_repo_name": "neurorestore/neuraldynamicplatform", "max_forks_repo_head_hexsha": "ac32df03a8892dafdf9765c6148b60ccdd34f1d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7969348659, "max_line_length": 122, "alphanum_fraction": 0.7276318388, "include": true, "reason": "import numpy", "num_tokens": 2809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3557749003442964, "lm_q1q2_score": 0.1806667154075853}}
{"text": "__author__ = 'sebastian'\n\nimport numpy as np\nimport math\nimport os\nfrom photogrammetry_importer.utility.blender_logging_utility import log_report\n\nclass Camera:\n    \"\"\" \n    This class represents a reconstructed camera and provides functionality to manage\n    intrinsic and extrinsic camera parameters as well as image information. \n    \"\"\"\n    panoramic_type_equirectangular = \"EQUIRECTANGULAR\" \n\n    IMAGE_FP_TYPE_NAME = \"NAME\"\n    IMAGE_FP_TYPE_RELATIVE = \"RELATIVE\"\n    IMAGE_FP_TYPE_ABSOLUTE = \"ABSOLUTE\"\n\n    DEPTH_MAP_WRT_UNIT_VECTORS = \"DEPTH_MAP_WRT_UNIT_VECTORS\"\n    DEPTH_MAP_WRT_CANONICAL_VECTORS = \"DEPTH_MAP_WRT_CANONICAL_VECTORS\"\n\n    def __init__(self):\n        self._center = np.array([0, 0, 0], dtype=float)              # C = -R^T t\n        self._translation_vec = np.array([0, 0, 0], dtype=float)     # t = -R C\n        self.normal = np.array([0, 0, 0], dtype=float)\n        self.color = np.array([255, 255, 255], dtype=int)\n\n        # use for these attributes the getter and setter methods\n        self._quaternion = np.array([0, 0, 0, 0], dtype=float)\n        self._rotation_mat = np.zeros((3, 3), dtype=float)\n        \n        self._calibration_mat = np.zeros((3, 3), dtype=float)\n        \n        self.image_fp_type = None\n        self.image_dp = None\n        self._relative_fp = None\n        self._absolute_fp = None\n        self._undistorted_relative_fp = None\n        self._undistorted_absolute_fp = None\n        self.width = None\n        self.height = None\n        self.panoramic_type = None\n\n        self.depth_map_fp = None\n        self.depth_map_callback = None\n        self.depth_map_semantic = None\n\n        self.id = None  # an unique identifier (natural number)\n\n    def __repr__(self):\n        return self.__str__()\n\n    def __str__(self):\n        return str('Camera: ' + self._relative_fp + ' ' + str(self._center) + ' ' + str(self.normal))\n\n    def get_file_name(self):\n        return os.path.basename(self.get_absolute_fp())\n\n    def set_relative_fp(self, relative_fp, image_fp_type):\n        self._relative_fp = relative_fp\n        self.image_fp_type = image_fp_type\n\n    def get_relative_fp(self):\n        return self._get_relative_fp(\n            self._relative_fp, self._absolute_fp)\n\n    def get_undistorted_relative_fp(self):\n        return self._get_relative_fp(\n            self._undistorted_relative_fp, self._undistorted_absolute_fp)\n\n    def _get_relative_fp(self, relative_fp, absolute_fp):\n        if self.image_fp_type == Camera.IMAGE_FP_TYPE_NAME:\n            assert relative_fp is not None\n            return os.path.basename(relative_fp)\n        elif self.image_fp_type == Camera.IMAGE_FP_TYPE_RELATIVE:\n            assert relative_fp is not None\n            return relative_fp\n        elif self.image_fp_type == Camera.IMAGE_FP_TYPE_ABSOLUTE:\n            assert absolute_fp is not None\n            return absolute_fp \n        else:\n            assert False\n\n    def set_absolute_fp(self, absolute_fp):\n        self._absolute_fp = absolute_fp\n\n    def get_absolute_fp(self):\n        return self._get_absolute_fp(\n            self._relative_fp, self._absolute_fp)\n\n    def get_undistored_absolute_fp(self):\n        if self.image_fp_type == Camera.IMAGE_FP_TYPE_ABSOLUTE:\n            assert False # Not supported for undistorted images\n        return self._get_absolute_fp(\n            self._undistorted_relative_fp, self._undistorted_absolute_fp)    \n\n    def _get_absolute_fp(self, relative_fp, absolute_fp):\n        if self.image_fp_type == Camera.IMAGE_FP_TYPE_NAME:\n            assert self.image_dp is not None \n            assert relative_fp is not None\n            return os.path.join(self.image_dp, os.path.basename(relative_fp))\n        elif self.image_fp_type == Camera.IMAGE_FP_TYPE_RELATIVE:\n            assert self.image_dp is not None \n            assert relative_fp is not None\n            return os.path.join(self.image_dp, relative_fp)\n        elif self.image_fp_type == Camera.IMAGE_FP_TYPE_ABSOLUTE:\n            assert absolute_fp is not None\n            return absolute_fp \n        else:\n            assert False\n\n    def has_undistorted_absolute_fp(self):\n        requirements = False\n        if self.image_fp_type == Camera.IMAGE_FP_TYPE_NAME:\n            requirements = (self.image_dp is not None) and (self._undistorted_relative_fp is not None)\n        elif self.image_fp_type == Camera.IMAGE_FP_TYPE_RELATIVE:\n            requirements = (self.image_dp is not None) and (self._undistorted_relative_fp is not None)\n        elif self.image_fp_type == Camera.IMAGE_FP_TYPE_ABSOLUTE:\n            requirements = (self._undistorted_absolute_fp is not None)\n\n        has_fp = False\n        if requirements:\n            fp = self._get_absolute_fp(\n                self._undistorted_relative_fp, \n                self._undistorted_absolute_fp) \n            if os.path.isfile(fp):\n                has_fp = True\n        return has_fp\n\n    def get_blender_obj_gui_str(self):\n        # Replace special characters\n        #image_fp_clean = image_fp.replace(\"/\", \"_\").replace(\"\\\\\", \"_\").replace(\":\", \"_\")\n        image_fp_stem = os.path.splitext(self.get_relative_fp())[0]\n        # Blender supports only object names with length 63\n        # However, we need also space for additional suffixes\n        image_fp_suffix = image_fp_stem[-40:]\n        return image_fp_suffix \n        \n\n    def set_calibration(self, calibration_mat, radial_distortion):\n        self._calibration_mat = np.asarray(calibration_mat, dtype=float)\n        self._radial_distortion = radial_distortion\n        assert self._radial_distortion is not None\n        \n    def has_focal_length(self):\n        return self._calibration_mat[0][0] > 0\n\n    def get_focal_length(self):\n        return self._calibration_mat[0][0]\n    \n    def get_field_of_view(self):\n        assert self.width is not None and self.height is not None\n        angle = math.atan(max(self.width, self.height) / (self.get_focal_length() * 2.0)) * 2.0\n        return angle\n\n    def has_intrinsics(self):\n        return self.has_focal_length() and self.is_principal_point_initialized()\n\n    def check_calibration_mat(self):\n        assert self.has_focal_length() and self.is_principal_point_initialized()\n    \n    def get_calibration_mat(self):\n        self.check_calibration_mat()\n        return self._calibration_mat\n    \n    def set_calibration_mat(self, calibration_mat):\n        self._calibration_mat = calibration_mat\n\n    def set_principal_point(self, principal_point):\n        self._calibration_mat[0][2] = principal_point[0]\n        self._calibration_mat[1][2] = principal_point[1]\n\n    def get_principal_point(self):\n        calibration_mat = self.get_calibration_mat()\n        cx = calibration_mat[0][2]\n        cy = calibration_mat[1][2]\n        return np.asarray([cx,cy], dtype=float)\n    \n    def is_principal_point_initialized(self):\n        cx_zero = np.isclose(self._calibration_mat[0][2], 0.0)\n        cy_zero = np.isclose(self._calibration_mat[1][2], 0.0)\n        initialized = (not cx_zero) and (not cy_zero)\n        return initialized\n\n    def is_panoramic(self):\n        return self.panoramic_type is not None\n\n    def set_panoramic_type(self, panoramic_type):\n        self.panoramic_type = panoramic_type\n\n    def get_panoramic_type(self):\n        return self.panoramic_type\n\n    @staticmethod\n    def compute_calibration_mat(focal_length, cx, cy):\n        return np.array([[focal_length, 0, cx], [0, focal_length, cy], [0,0,1]], dtype=float)\n\n    def set_quaternion(self, quaternion):\n        self._quaternion = quaternion\n        # we must change the rotation matrixes as well\n        self._rotation_mat = Camera.quaternion_to_rotation_matrix(quaternion)\n\n    def set_rotation_mat(self, rotation_mat, check_rotation=True):\n        if check_rotation:\n            assert Camera.is_rotation_mat_valid(rotation_mat)\n        self._rotation_mat = rotation_mat\n        # we must change the quaternion as well\n        self._quaternion = Camera.rotation_matrix_to_quaternion(rotation_mat)\n\n    def set_camera_center_after_rotation(self, center, check_rotation=True):\n        if check_rotation:\n            assert Camera.is_rotation_mat_valid(self._rotation_mat)\n        self._center = center\n        self._translation_vec = - np.dot(self._rotation_mat, center)    # t = -R C\n\n    def set_camera_translation_vector_after_rotation(self, translation_vector, check_rotation=True):\n        if check_rotation:\n            assert Camera.is_rotation_mat_valid(self._rotation_mat)\n        self._translation_vec = translation_vector\n        self._center = - np.dot(self._rotation_mat.transpose(), translation_vector) # C = -R^T t\n\n    def get_quaternion(self):\n        return self._quaternion\n\n    def get_rotation_mat(self):\n        return self._rotation_mat\n\n    def get_translation_vec(self):\n        return self._translation_vec\n\n    def get_camera_center(self):\n        return self._center\n    \n    def set_4x4_cam_to_world_mat(self, cam_to_world_mat, check_rotation=True):\n        self.set_rotation_mat(\n            cam_to_world_mat[0:3, 0:3].transpose(), check_rotation=check_rotation)\n        self.set_camera_center_after_rotation(\n            cam_to_world_mat[0:3, 3], check_rotation=check_rotation)\n\n    @staticmethod\n    def is_rotation_mat_valid(some_mat):\n        # Test if rotation_mat is really a rotation matrix (i.e. det = -1 or det = 1)\n        det = np.linalg.det(some_mat)\n        res = np.isclose(det, 1) or np.isclose(det, -1)\n        return res\n\n    @staticmethod\n    def quaternion_to_rotation_matrix(q):\n        \"\"\"\n        Original C++ Method ('SetQuaternionRotation()') defined in  pba/src/pba/DataInterface.h\n        Parallel bundle adjustment (pba) code (used by visualsfm) is provided here:\n        http://grail.cs.washington.edu/projects/mcba/\n        \"\"\"\n        qq = math.sqrt(q[0]*q[0]+q[1]*q[1]+q[2]*q[2]+q[3]*q[3])\n        if qq > 0:  # Normalize the quaternion\n            qw = q[0]/qq\n            qx = q[1]/qq\n            qy = q[2]/qq\n            qz = q[3]/qq\n        else:\n            qw = 1\n            qx = qy = qz = 0\n        m = np.zeros((3, 3), dtype=float)\n        m[0][0] = float(qw*qw + qx*qx- qz*qz- qy*qy )\n        m[0][1] = float(2*qx*qy -2*qz*qw )\n        m[0][2] = float(2*qy*qw + 2*qz*qx)\n        m[1][0] = float(2*qx*qy+ 2*qw*qz)\n        m[1][1] = float(qy*qy+ qw*qw - qz*qz- qx*qx)\n        m[1][2] = float(2*qz*qy- 2*qx*qw)\n        m[2][0] = float(2*qx*qz- 2*qy*qw)\n        m[2][1] = float(2*qy*qz + 2*qw*qx )\n        m[2][2] = float(qz*qz+ qw*qw- qy*qy- qx*qx)\n        return m\n\n    @staticmethod\n    def rotation_matrix_to_quaternion(m):\n        \"\"\"\n        Original C++ Method ('GetQuaternionRotation()') defined in  pba/src/pba/DataInterface.h\n        Parallel bundle adjustment (pba) code (used by visualsfm) is provided here:\n        http://grail.cs.washington.edu/projects/mcba/\n        \"\"\"\n        q = np.array([0, 0, 0, 0], dtype=float)\n        q[0] = 1 + m[0][0] + m[1][1] + m[2][2]\n        if q[0] > 0.000000001:\n            q[0] = math.sqrt(q[0]) / 2.0\n            q[1] = (m[2][1] - m[1][2]) / ( 4.0 * q[0])\n            q[2] = (m[0][2] - m[2][0]) / ( 4.0 * q[0])\n            q[3] = (m[1][0] - m[0][1]) / ( 4.0 * q[0])\n        else:\n            if m[0][0] > m[1][1] and m[0][0] > m[2][2]:\n                s = 2.0 * math.sqrt(1.0 + m[0][0] - m[1][1] - m[2][2])\n                q[1] = 0.25 * s\n                q[2] = (m[0][1] + m[1][0]) / s\n                q[3] = (m[0][2] + m[2][0]) / s\n                q[0] = (m[1][2] - m[2][1]) / s\n            elif m[1][1] > m[2][2]:\n                s = 2.0 * math.sqrt(1.0 + m[1][1] - m[0][0] - m[2][2])\n                q[1] = (m[0][1] + m[1][0]) / s\n                q[2] = 0.25 * s\n                q[3] = (m[1][2] + m[2][1]) / s\n                q[0] = (m[0][2] - m[2][0]) / s\n            else:\n                s = 2.0 * math.sqrt(1.0 + m[2][2] - m[0][0] - m[1][1])\n                q[1] = (m[0][2] + m[2][0]) / s\n                q[2] = (m[1][2] + m[2][1]) / s\n                q[3] = 0.25 * s\n                q[0] = (m[0][1] - m[1][0]) / s\n        return q\n\n    def set_depth_map(self, depth_map_ifp, depth_map_callback, depth_map_semantic):\n        self.depth_map_fp = depth_map_ifp\n        self.depth_map_callback = depth_map_callback\n        self.depth_map_semantic = depth_map_semantic\n\n    def get_depth_map(self):\n        if os.path.isfile(self.depth_map_fp):\n            return self.depth_map_callback(self.depth_map_fp)\n        else:\n            return None\n\n    def get_4x4_cam_to_world_mat(self):\n        \"\"\"\n        This matrix can be used to convert points given in camera coordinates\n        into points given in world coordinates.\n        M = [R^T    c]\n            [0      1]\n        :return:\n        \"\"\"\n        homogeneous_mat = np.identity(4, dtype=float)\n        homogeneous_mat[0:3, 0:3] = self.get_rotation_mat().transpose()\n        homogeneous_mat[0:3, 3] = self.get_camera_center()\n        return homogeneous_mat\n\n    def convert_depth_map_to_world_coords(  self,\n                                            depth_map_display_sparsity=100):\n        \"\"\"\n        Do not confuse z_buffer with depth_buffer!\n        z_buffer contains values in [0,1]\n        depth_buffer contains the actual distance values\n\n        :param depth_buffer_matrix:\n        :param n_th_result_point:\n        :return:\n        \"\"\"\n        assert 0 < depth_map_display_sparsity\n\n        depth_map = self.get_depth_map()\n        height, width = depth_map.shape\n\n        if self.height == height and self.width == width:\n            x_step_size = 1.0\n            y_step_size = 1.0\n        else:\n            x_step_size = self.width / width\n            y_step_size = self.height / height\n\n        fx = self.get_calibration_mat()[0][0]\n        fy = self.get_calibration_mat()[1][1]\n        cx, cy = self.get_principal_point()\n\n        indices = np.indices((height, width))\n        y_index_list = indices[0].flatten()\n        x_index_list = indices[1].flatten()\n\n        # Use the local coordinate system of the camera to analyze its viewing directions\n        # The Blender camera coordinate system looks along the negative z axis (blue),\n        # the up axis points along the y axis (green).\n\n        y_index_list = y_index_list[::-1]   # Reverse order of indices\n        x_index_list = x_index_list[::-1]   # Reverse order of indices\n        fx = -fx\n        fy = -fy\n        depth_values = depth_map.flatten()\n\n        assert len(x_index_list) == len(y_index_list) == len(depth_values)\n\n        # https://github.com/colmap/colmap/blob/dev/src/base/reconstruction.cc\n        #   // COLMAP assumes that the upper left pixel center is (0.5, 0.5)\n        # https://github.com/simonfuhrmann/mve/blob/master/libs/mve/depthmap.cc\n        #  math::Vec3f v = invproj * math::Vec3f(\n        #       (float)x + 0.5f, (float)y + 0.5f, 1.0f);\n        x_index_coord_list = x_step_size * x_index_list + 0.5\n        y_index_coord_list = y_step_size * y_index_list + 0.5\n\n        # The cannoncial vectors are defined according to p.155 of \n        # \"Multiple View Geometry\" by Hartley and Zisserman using a canonical \n        # focal length of 1 , i.e. vec = [(x - cx) / fx, (y - cy) / fy, 1] \n        x_coords_canonical = (x_index_coord_list - cx) / fx\n        y_coords_canonical = (y_index_coord_list - cy) / fy\n        z_coords_canonical = np.ones(len(depth_values), dtype=float)\n\n        # Determine non-background data\n        non_background_flags = depth_values > 0\n        x_coords_canonical_filtered = x_coords_canonical[non_background_flags]\n        y_coords_canonical_filtered = y_coords_canonical[non_background_flags]\n        z_coords_canonical_filtered = z_coords_canonical[non_background_flags]\n        depth_values_filtered = depth_values[non_background_flags]\n\n        if depth_map_display_sparsity != 100:\n            x_coords_canonical_filtered = x_coords_canonical_filtered[::depth_map_display_sparsity]\n            y_coords_canonical_filtered = y_coords_canonical_filtered[::depth_map_display_sparsity]\n            z_coords_canonical_filtered = z_coords_canonical_filtered[::depth_map_display_sparsity]\n            depth_values_filtered = depth_values_filtered[::depth_map_display_sparsity]\n\n        if self.depth_map_semantic == Camera.DEPTH_MAP_WRT_CANONICAL_VECTORS:\n            # In this case, the depth values are defined w.r.t. the canonical\n            # vectors. This kind of depth data is used by Colmap.\n            x_coords_filtered = x_coords_canonical_filtered * depth_values_filtered\n            y_coords_filtered = y_coords_canonical_filtered * depth_values_filtered\n            z_coords_filtered = z_coords_canonical_filtered * depth_values_filtered\n\n        elif self.depth_map_semantic == Camera.DEPTH_MAP_WRT_UNIT_VECTORS:\n            # In this case the depth values are defined w.r.t. the normalized \n            # canonical vectors. This kind of depth data is used by MVE.\n            cannonical_norms_filtered = np.linalg.norm(\n                np.array(\n                    [x_coords_canonical_filtered, \n                    y_coords_canonical_filtered, \n                    z_coords_canonical_filtered], \n                    dtype=float),\n                axis=0)\n            # Instead of normalizing the x,y and z component, we divide the \n            # depth values by the corresponding norm.\n            normalized_depth_values_filtered = depth_values_filtered / cannonical_norms_filtered\n            x_coords_filtered = x_coords_canonical_filtered * normalized_depth_values_filtered\n            y_coords_filtered = y_coords_canonical_filtered * normalized_depth_values_filtered\n            z_coords_filtered = z_coords_canonical_filtered * normalized_depth_values_filtered\n\n        else:\n            assert False\n\n        hom_entries = np.ones_like(z_coords_filtered)\n        cam_coords_hom = np.dstack(\n            (x_coords_filtered, \n            y_coords_filtered, \n            z_coords_filtered, \n            hom_entries))[0]\n\n        world_coords_hom = self.get_4x4_cam_to_world_mat().dot(cam_coords_hom.T).T\n        world_coords = np.delete(world_coords_hom, 3, 1)\n\n        return world_coords\n\n", "meta": {"hexsha": "b30a770139586b8a9dcdb80ae7dc982e5948cf2f", "size": 18132, "ext": "py", "lang": "Python", "max_stars_repo_path": "photogrammetry_importer/types/camera.py", "max_stars_repo_name": "4xle/Blender-Addon-Photogrammetry-Importer", "max_stars_repo_head_hexsha": "8098dbbb712939973ecc04e7cb82694628c100f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "photogrammetry_importer/types/camera.py", "max_issues_repo_name": "4xle/Blender-Addon-Photogrammetry-Importer", "max_issues_repo_head_hexsha": "8098dbbb712939973ecc04e7cb82694628c100f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "photogrammetry_importer/types/camera.py", "max_forks_repo_name": "4xle/Blender-Addon-Photogrammetry-Importer", "max_forks_repo_head_hexsha": "8098dbbb712939973ecc04e7cb82694628c100f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.8378378378, "max_line_length": 102, "alphanum_fraction": 0.6281711891, "include": true, "reason": "import numpy", "num_tokens": 4626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18066671193889206}}
{"text": "from torchvision import transforms\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data.sampler import BatchSampler\n\nimport numpy as np\nimport torch\nimport os\n\nfrom elbo_functions import deviance_upper_bound, elbo, KL_closed, minibatch_KLD_upper_bound, minibatch_KLD_upper_bound_iter\nfrom model_test import MSE_test_GPapprox, MSE_test\nfrom utils import SubjectSampler, VaryingLengthSubjectSampler, VaryingLengthBatchSampler, HensmanDataLoader\nfrom predict_HealthMNIST import recon_complete_gen, gen_rotated_mnist_plot, variational_complete_gen\nfrom validation import validate\n\ndef hensman_training(nnet_model, type_nnet, epochs, dataset, optimiser, type_KL, num_samples, latent_dim, covar_module0,\n                     covar_module1, likelihoods, m, H, zt_list, P, T, varying_T, Q, weight, id_covariate, loss_function,\n                     natural_gradient=False, natural_gradient_lr=0.01, subjects_per_batch=20, memory_dbg=False,\n                     eps=1e-6, results_path=None, validation_dataset=None, generation_dataset=None,\n                     prediction_dataset=None, gp_model=None, csv_file_test_data=None, csv_file_test_label=None,\n                     test_mask_file=None, data_source_path=None):\n\n    \"\"\"\n    Perform training with minibatching and Stochastic Variational Inference [Hensman et. al, 2013]. See L-VAE supplementary\n    materials\n\n    :param nnet_model: encoder/decoder neural network model \n    :param type_nnet: type of encoder/decoder\n    :param epochs: numner of epochs\n    :param dataset: dataset to use in training\n    :param optimiser: optimiser to be used\n    :param type_KL: type of KL divergenve computation to use\n    :param num_samples: number of samples to use\n    :param latent_dim: number of latent dimensions\n    :param covar_module0: additive kernel (sum of cross-covariances) without id covariate\n    :param covar_module1: additive kernel (sum of cross-covariances) with id covariate\n    :param likelihoods: GPyTorch likelihood model\n    :param m: variational mean\n    :param H: variational variance\n    :param zt_list: list of inducing points\n    :param P: number of unique instances\n    :param T: number of longitudinal samples per individual\n    :param Q: number of covariates\n    :param weight: value for the weight\n    :param id_covariate: covariate number of the id\n    :param loss_function: selected loss function\n    :param natural_gradient: use of natural gradients\n    :param natural_gradient_lr: natural gradients learning rate\n    :param subject_per_batch; number of subjects per batch (vectorisation)\n    :param memory_dbg: enable debugging\n    :param eps: jitter\n    :param results_path: path to results\n    :param validation_dataset: dataset for vaildation set\n    :param generation_dataset: dataset to help with sample image generation\n    :param prediction_dataset; dataset with subjects for prediction\n    :param gp_mode: GPyTorch gp model\n    :param csv_file_test_data: path to test data\n    :param csv_file_test_label: path to test label\n    :param test_mask_file: path to test mask\n    :param data_source_path: path to data source\n\n    :return trained models and resulting losses\n\n    \"\"\"\n\n    device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n    N = len(dataset)\n    assert type_KL == 'GPapprox_closed'\n\n    if varying_T:\n        n_batches = (P + subjects_per_batch - 1)//subjects_per_batch\n        dataloader = HensmanDataLoader(dataset, batch_sampler=VaryingLengthBatchSampler(VaryingLengthSubjectSampler(dataset, id_covariate), subjects_per_batch), num_workers=4)    \n    else:\n        batch_size = subjects_per_batch*T\n        n_batches = (P*T + batch_size - 1)//(batch_size)\n        dataloader = HensmanDataLoader(dataset, batch_sampler=BatchSampler(SubjectSampler(dataset, P, T), batch_size, drop_last=False), num_workers=4)\n\n    net_train_loss_arr = np.empty((0, 1))\n    recon_loss_arr = np.empty((0, 1))\n    nll_loss_arr = np.empty((0, 1))\n    kld_loss_arr = np.empty((0, 1))\n    penalty_term_arr = np.empty((0, 1))\n    best_val_pred_mse = np.Inf\n    best_epoch = 0\n    for epoch in range(1, epochs + 1):\n        recon_loss_sum = 0\n        nll_loss_sum = 0\n        kld_loss_sum = 0\n        net_loss_sum = 0\n        iid_kld_sum = 0\n        for batch_idx, sample_batched in enumerate(dataloader):\n            optimiser.zero_grad()\n            nnet_model.train()\n            covar_module0.train()\n            covar_module1.train()\n            indices = sample_batched['idx']\n            data = sample_batched['digit'].double().to(device)\n            train_x = sample_batched['label'].double().to(device)\n            mask = sample_batched['mask'].double().to(device)\n            N_batch = data.shape[0]\n\n            covariates = torch.cat((train_x[:, :id_covariate], train_x[:, id_covariate+1:]), dim=1)\n\n            recon_batch, mu, log_var = nnet_model(data)\n            [recon_loss, nll] = nnet_model.loss_function(recon_batch, data, mask)\n            recon_loss = torch.sum(recon_loss)\n            nll_loss = torch.sum(nll)\n\n            PSD_H = H if natural_gradient else torch.matmul(H, H.transpose(-1, -2))\n\n            if varying_T:\n                P_in_current_batch = torch.unique(train_x[:, id_covariate]).shape[0]\n                kld_loss, grad_m, grad_H = minibatch_KLD_upper_bound_iter(covar_module0, covar_module1, likelihoods, latent_dim, m, PSD_H, train_x, mu, log_var, zt_list, P, P_in_current_batch, N, natural_gradient, id_covariate, eps)\n            else:\n                P_in_current_batch = N_batch // T\n                kld_loss, grad_m, grad_H = minibatch_KLD_upper_bound(covar_module0, covar_module1, likelihoods, latent_dim, m, PSD_H, train_x, mu, log_var, zt_list, P, P_in_current_batch, T, natural_gradient, eps)\n\n            recon_loss = recon_loss * P/P_in_current_batch\n            nll_loss = nll_loss * P/P_in_current_batch\n\n            if loss_function == 'nll':\n                net_loss = nll_loss + kld_loss\n            elif loss_function == 'mse':\n                kld_loss = kld_loss / latent_dim\n                net_loss = recon_loss + weight * kld_loss\n\n            net_loss.backward()\n            optimiser.step()\n\n            if natural_gradient:\n                LH = torch.cholesky(H)\n                iH = torch.cholesky_solve(torch.eye(H.shape[-1], dtype=torch.double).to(device), LH)\n                iH_new = iH + natural_gradient_lr*(grad_H + grad_H.transpose(-1,-2))\n                LiH_new = torch.cholesky(iH_new)\n                H = torch.cholesky_solve(torch.eye(H.shape[-1], dtype=torch.double).to(device), LiH_new).detach()\n                m = torch.matmul(H, torch.matmul(iH, m) - natural_gradient_lr*(grad_m - 2*torch.matmul(grad_H, m))).detach()\n\n            net_loss_sum += net_loss.item() / n_batches \n            recon_loss_sum += recon_loss.item() / n_batches\n            nll_loss_sum += nll_loss.item() / n_batches\n            kld_loss_sum += kld_loss.item() / n_batches\n\n        print('Iter %d/%d - Loss: %.3f  - GP loss: %.3f  - NLL Loss: %.3f  - Recon Loss: %.3f' % (\n            epoch, epochs, net_loss_sum, kld_loss_sum, nll_loss_sum, recon_loss_sum), flush=True)\n        penalty_term_arr = np.append(penalty_term_arr, 0.0)\n        net_train_loss_arr = np.append(net_train_loss_arr,  net_loss_sum)\n        recon_loss_arr = np.append(recon_loss_arr, recon_loss_sum)\n        nll_loss_arr = np.append(nll_loss_arr, nll_loss_sum)\n        kld_loss_arr = np.append(kld_loss_arr, kld_loss_sum)\n\n        if (not epoch % 25) and epoch != epochs:\n            with torch.no_grad():\n                nnet_model.eval()\n                covar_module0.eval()\n                covar_module1.eval()\n                if validation_dataset is not None:\n                    full_mu = torch.zeros(len(dataset), latent_dim, dtype=torch.double).to(device)\n                    prediction_x = torch.zeros(len(dataset), Q, dtype=torch.double).to(device)\n                    for batch_idx, sample_batched in enumerate(dataloader):\n                        label_id = sample_batched['idx']\n                        prediction_x[label_id] = sample_batched['label'].double().to(device)\n                        data = sample_batched['digit'].double().to(device)\n                        covariates = torch.cat((prediction_x[label_id, :id_covariate], prediction_x[label_id, id_covariate+1:]), dim=1)\n\n                        mu, log_var = nnet_model.encode(data)\n                        full_mu[label_id] = mu\n                    val_pred_mse = validate(nnet_model, type_nnet, validation_dataset, type_KL, num_samples, latent_dim, covar_module0, covar_module1, likelihoods, zt_list, T, weight, full_mu, prediction_x, id_covariate, loss_function, eps=1e-6)\n                    if val_pred_mse < best_val_pred_mse:\n                        best_val_pred_mse = val_pred_mse\n                        best_epoch = epoch\n\n                        prediction_dataloader = DataLoader(prediction_dataset, batch_sampler=VaryingLengthBatchSampler(\n                            VaryingLengthSubjectSampler(prediction_dataset, id_covariate), subjects_per_batch),\n                                                           num_workers=4)\n                        full_mu = torch.zeros(len(prediction_dataset), latent_dim, dtype=torch.double).to(device)\n                        prediction_x = torch.zeros(len(prediction_dataset), Q, dtype=torch.double).to(device)\n\n                        with torch.no_grad():\n                            for batch_idx, sample_batched in enumerate(prediction_dataloader):\n                                label_id = sample_batched['idx']\n                                prediction_x[label_id] = sample_batched['label'].double().to(device)\n                                data = sample_batched['digit'].double().to(device)\n                                covariates = torch.cat(\n                                    (prediction_x[label_id, :id_covariate], prediction_x[label_id, id_covariate + 1:]),\n                                    dim=1)\n\n                                mu, log_var = nnet_model.encode(data)\n                                full_mu[label_id] = mu\n                            covar_module0.eval()\n                            covar_module1.eval()\n                            if type_KL == 'GPapprox' or type_KL == 'GPapprox_closed':\n                                MSE_test_GPapprox(csv_file_test_data, csv_file_test_label, test_mask_file,\n                                                  data_source_path, type_nnet,\n                                                  nnet_model, covar_module0, covar_module1, likelihoods, results_path,\n                                                  latent_dim, prediction_x,\n                                                  full_mu, zt_list, P, T, id_covariate, varying_T,\n                                                  save_file='result_error_best.csv')\n\n                        print('Saving better model')\n                        try:\n                            torch.save(nnet_model.state_dict(), os.path.join(results_path, 'nnet_model_best.pth'))\n                            torch.save(gp_model.state_dict(), os.path.join(results_path, 'gp_model_best.pth'))\n                            torch.save(zt_list, os.path.join(results_path, 'zt_list_best.pth'))\n                            torch.save(m, os.path.join(results_path, 'm_best.pth'))\n                            torch.save(H, os.path.join(results_path, 'H_best.pth'))\n\n                            if results_path and generation_dataset:\n                                prediction_dataloader = DataLoader(prediction_dataset,\n                                                                   batch_sampler=VaryingLengthBatchSampler(\n                                                                       VaryingLengthSubjectSampler(prediction_dataset,\n                                                                                                   id_covariate),\n                                                                       subjects_per_batch), num_workers=4)\n                                full_mu = torch.zeros(len(prediction_dataset), latent_dim, dtype=torch.double).to(\n                                    device)\n                                prediction_x = torch.zeros(len(prediction_dataset), Q, dtype=torch.double).to(device)\n                                for batch_idx, sample_batched in enumerate(prediction_dataloader):\n                                    label_id = sample_batched['idx']\n                                    prediction_x[label_id] = sample_batched['label'].double().to(device)\n                                    data = sample_batched['digit'].double().to(device)\n                                    covariates = torch.cat((prediction_x[label_id, :id_covariate],\n                                                            prediction_x[label_id, id_covariate + 1:]), dim=1)\n\n                                    mu, log_var = nnet_model.encode(data)\n                                    full_mu[label_id] = mu\n\n                                recon_complete_gen(generation_dataset, nnet_model, type_nnet,\n                                                   results_path, covar_module0,\n                                                   covar_module1, likelihoods, latent_dim,\n                                                   './data', prediction_x, full_mu, epoch,\n                                                   zt_list, P, T, id_covariate, varying_T)\n                        except e:\n                            print(e)\n                            print('Saving intermediate model failed!')\n                            pass\n                    if torch.cuda.is_available():\n                        torch.cuda.empty_cache()\n\n    return penalty_term_arr, net_train_loss_arr, nll_loss_arr, recon_loss_arr, kld_loss_arr, m, H, best_epoch\n\n\ndef minibatch_training(nnet_model, type_nnet, epochs, dataset, optimiser, type_KL, num_samples, latent_dim, \n                       covar_module0, covar_module1, likelihoods, zt_list, P, T, Q, weight, id_covariate, \n                       loss_function, memory_dbg=False, eps=1e-6, results_path=None, validation_dataset=None, \n                       generation_dataset=None, prediction_dataset=None):\n\n    \"\"\"\n    Perform training with minibatching (psuedo-minibatching) similar to GPPVAE [Casale el. al, 2018]. See L-VAE supplementary\n    materials\n\n    :param nnet_model: encoder/decoder neural network model \n    :param type_nnet: type of encoder/decoder\n    :param epochs: numner of epochs\n    :param dataset: dataset to use in training\n    :param optimiser: optimiser to be used\n    :param type_KL: type of KL divergenve computation to use\n    :param num_samples: number of samples to use\n    :param latent_dim: number of latent dimensions\n    :param covar_module0: additive kernel (sum of cross-covariances) without id covariate\n    :param covar_module1: additive kernel (sum of cross-covariances) with id covariate\n    :param likelihoods: GPyTorch likelihood model\n    :param zt_list: list of inducing points\n    :param P: number of unique instances\n    :param T: number of longitudinal samples per individual\n    :param Q: number of covariates\n    :param weight: value for the weight\n    :param id_covariate: covariate number of the id\n    :param loss_function: selected loss function\n    :param memory_dbg: enable debugging\n    :param eps: jitter\n    :param results_path: path to results\n    :param validation_dataset: dataset for vaildation set\n    :param generation_dataset: dataset to help with sample image generation\n    :param prediction_dataset; dataset with subjects for prediction\n\n    :return trained models and resulting losses\n\n    \"\"\"\n\n    device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n    batch_size = T\n    assert (type_KL == 'GPapprox_closed' or type_KL == 'GPapprox')\n\n    # set up Data Loader for training\n    dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=4)\n    \n    net_train_loss_arr = np.empty((0, 1))\n    recon_loss_arr = np.empty((0, 1))\n    nll_loss_arr = np.empty((0, 1))\n    gp_loss_arr = np.empty((0, 1))\n    penalty_term_arr = np.empty((0, 1))\n\n    for epoch in range(1, epochs + 1):\n\n        optimiser.zero_grad()\n\n        full_mu = torch.zeros(len(dataset), latent_dim, dtype=torch.double, requires_grad=True).to(device)\n        full_log_var = torch.zeros(len(dataset), latent_dim, dtype=torch.double, requires_grad=True).to(device)\n        train_x = torch.zeros(len(dataset), Q, dtype=torch.double, requires_grad=False).to(device)\n\n        #Step 1: Encode the sample data to obtain \\bar{\\mu} and diag(W)\n        with torch.no_grad():\n            for batch_idx, sample_batched in enumerate(dataloader):\n                indices = sample_batched['idx']\n                data = sample_batched['digit'].double().to(device)\n                train_x[indices] = sample_batched['label'].double().to(device)\n\n                covariates = torch.cat((train_x[indices, :id_covariate], train_x[indices, id_covariate+1:]), dim=1)\n                mu, log_var = nnet_model.encode(data)\n\n                full_mu[indices] = mu\n                full_log_var[indices] = log_var\n\n        mu_grads = torch.zeros(len(dataset), latent_dim, dtype=torch.double, requires_grad=True).to(device)\n        log_var_grads = torch.zeros(len(dataset), latent_dim, dtype=torch.double, requires_grad=True).to(device)\n\n        gp_losses = 0\n        gp_loss_sum = 0\n        param_list = []\n\n        #Steps 2 & 3: compute d and E, compute gradients of KLD w.r.t S and theta\n        if type_KL == 'GPapprox':\n            for sample in range(0, num_samples):\n                Z = nnet_model.sample_latent(full_mu, full_log_var)\n                for i in range(0, latent_dim):\n                    Z_dim = Z[:, i]\n                    gp_loss = -elbo(covar_module0[i], covar_module1[i], likelihoods[i], train_x, Z_dim,\n                                    zt_list[i].to(device), P, T, eps)\n                    gp_loss_sum = gp_loss.item() + gp_loss_sum\n                    gp_losses = gp_losses + gp_loss\n            gp_losses = gp_losses / num_samples\n            gp_loss_sum /= num_samples\n\n        elif type_KL == 'GPapprox_closed':\n            for i in range(0, latent_dim):\n                mu_sliced = full_mu[:, i]\n                log_var_sliced = full_log_var[:, i]\n                gp_loss = deviance_upper_bound(covar_module0[i], covar_module1[i],\n                                               likelihoods[i], train_x,\n                                               mu_sliced, log_var_sliced,\n                                               zt_list[i].to(device), P,\n                                               T, eps)\n                gp_loss_sum = gp_loss.item() + gp_loss_sum\n                gp_losses = gp_losses + gp_loss\n\n        \n        for i in range(0, latent_dim):\n            param_list += list(covar_module0[i].parameters())\n            param_list += list(covar_module1[i].parameters())\n#            param_list.append(zt_list[i])\n\n        if loss_function == 'mse':\n            gp_losses = weight*gp_losses/latent_dim\n            gp_loss_sum /= latent_dim\n        \n        mu_grads = torch.autograd.grad(gp_losses, full_mu, retain_graph=True)[0]\n        log_var_grads = torch.autograd.grad(gp_losses, full_log_var, retain_graph=True)[0]\n        grads = torch.autograd.grad(gp_losses, param_list)\n\n        for ind, p in enumerate(param_list):\n            p.grad = grads[ind]\n\n        recon_loss_sum = 0\n        nll_loss_sum = 0\n        #Step 4: compute reconstruction losses w.r.t phi and psi, add dKLD/dphi to the gradients\n        for batch_idx, sample_batched in enumerate(dataloader):\n            data = sample_batched['digit'].double().to(device)\n            mask = sample_batched['mask'].double().to(device)\n            indices = sample_batched['idx']\n\n            label = sample_batched['label'].double().to(device)\n            covariates = torch.cat((label[:, :id_covariate], label[:, id_covariate+1:]), dim=1)\n            recon_batch, mu, log_var = nnet_model(data)\n            \n            [recon_loss, nll] = nnet_model.loss_function(recon_batch, data, mask)\n            recon_loss = torch.sum(recon_loss)\n            nll = torch.sum(nll)\n\n            mu.backward(mu_grads[indices], retain_graph = True)\n            log_var.backward(log_var_grads[indices], retain_graph = True)\n\n            if loss_function == 'mse':         \n                recon_loss.backward()\n            elif loss_function == 'nll':\n                nll.backward()\n \n            recon_loss_sum = recon_loss_sum + recon_loss.item()\n            nll_loss_sum = nll_loss_sum + nll.item()\n\n        #Do logging\n        print('Iter %d/%d - Loss: %.3f  - GP loss: %.3f  - NLL loss: %.3f  - Recon Loss: %.3f' % (\n            epoch, epochs, recon_loss_sum + weight*gp_loss_sum, gp_loss_sum, nll_loss_sum, recon_loss_sum))\n        penalty_term_arr = np.append(penalty_term_arr, 0.0)\n        net_train_loss_arr = np.append(net_train_loss_arr,  recon_loss_sum + weight*gp_loss_sum)\n        nll_loss_arr = np.append(nll_loss_arr, nll_loss_sum)\n        recon_loss_arr = np.append(recon_loss_arr, recon_loss_sum)\n        gp_loss_arr = np.append(gp_loss_arr, gp_loss_sum)\n\n        #Step 5: apply gradients using an Adam optimiser\n        optimiser.step()\n\n        if (not epoch % 100) and epoch != epochs:\n            if validation_dataset is not None:\n                validate(nnet_model, type_nnet, validation_dataset, type_KL, num_samples, latent_dim, covar_module0, covar_module1, likelihoods, zt_list, T, weight, full_mu, train_x, id_covariate, loss_function, eps=1e-6)\n                if torch.cuda.is_available():\n                    torch.cuda.empty_cache()\n\n            if results_path and generation_dataset:\n                prediction_dataloader = DataLoader(prediction_dataset, batch_size=1000, shuffle=False, num_workers=4)\n                full_mu = torch.zeros(len(prediction_dataset), latent_dim, dtype=torch.double).to(device)\n                prediction_x = torch.zeros(len(prediction_dataset), Q, dtype=torch.double).to(device)\n                with torch.no_grad():\n                    for batch_idx, sample_batched in enumerate(prediction_dataloader):\n                        # no mini-batching. Instead get a batch of dataset size\n                        label_id = sample_batched['idx']\n                        prediction_x[label_id] = sample_batched['label'].double().to(device)\n                        data = sample_batched['digit'].double().to(device)\n                        covariates = torch.cat((prediction_x[label_id, :id_covariate], prediction_x[label_id, id_covariate+1:]), dim=1)\n\n                        mu, log_var = nnet_model.encode(data)\n\n                        full_mu[label_id] = mu\n\n                    recon_complete_gen(generation_dataset, nnet_model, type_nnet,\n                                       results_path, covar_module0,\n                                       covar_module1, likelihoods, latent_dim,\n                                       './data', prediction_x, full_mu, epoch,\n                                       zt_list, P, T, id_covariate)\n\n    return penalty_term_arr, net_train_loss_arr, nll_loss_arr, recon_loss_arr, gp_loss_arr\n\ndef standard_training(nnet_model, type_nnet, epochs, dataset, optimiser, type_KL, num_samples, \n    latent_dim, covar_modules, likelihoods, zt_list, id_covariate, P, T, Q, weight, constrain_scales, \n    loss_function, memory_dbg=False, eps=1e-6, validation_dataset=None, generation_dataset=None, prediction_dataset=None):\n\n\n    \"\"\"\n    Perform training without minibatching.\n\n    :param nnet_model: encoder/decoder neural network model \n    :param type_nnet: type of encoder/decoder\n    :param epochs: numner of epochs\n    :param dataset: dataset to use in training\n    :param optimiser: optimiser to be used\n    :param type_KL: type of KL divergenve computation to use\n    :param num_samples: number of samples to use\n    :param latent_dim: number of latent dimensions\n    :param covar_modules: additive kernel (sum of cross-covariances)\n    :param likelihoods: GPyTorch likelihood model\n    :param zt_list: list of inducing points\n    :param id_covariate: covariate number of the id\n    :param P: number of unique instances\n    :param T: number of longitudinal samples per individual\n    :param Q: number of covariates\n    :param weight: value for the weight\n    :param constrain_scales: boolean to constrain scales to 1\n    :param loss_function: selected loss function\n    :param memory_dbg: enable debugging\n    :param eps: jitter\n    :param validation_dataset: dataset for vaildation set\n    :param generation_dataset: dataset to help with sample image generation\n    :param prediction_dataset; dataset with subjects for prediction\n\n    :return trained models and resulting losses\n\n    \"\"\"\n    if type_KL == 'closed':\n        covar_module = covar_modules[0]\n    elif type_KL == 'GPapprox' or type_KL == 'GPapprox_closed':\n        covar_module0 = covar_modules[0]\n        covar_module1 = covar_modules[1]\n\n    device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n    # set up Data Loader for training\n    dataloader = DataLoader(dataset, batch_size=len(dataset), shuffle=False, num_workers=4)\n\n    net_train_loss_arr = np.empty((0, 1))\n    recon_loss_arr = np.empty((0, 1))\n    nll_loss_arr = np.empty((0, 1))\n    gp_loss_arr = np.empty((0, 1))\n    penalty_term_arr = np.empty((0, 1))\n\n    for epoch in range(1, epochs + 1):\n        for batch_idx, sample_batched in enumerate(dataloader):\n\n            # no mini-batching. Instead get a batch of dataset size.\n            optimiser.zero_grad()                                       # clear gradients\n            label_id = sample_batched['idx']\n            label = sample_batched['label']\n            data = sample_batched['digit']\n            data = data.double().to(device)\n            mask = sample_batched['mask']\n            mask = mask.to(device)\n\n            train_x = label.double().to(device)\n            covariates = torch.cat((train_x[:, :id_covariate], train_x[:, id_covariate+1:]), dim=1)\n\n            # encode data\n            recon_batch, mu, log_var = nnet_model(data)\n\n            [recon_loss, nll] = nnet_model.loss_function(recon_batch, data, mask)\n            recon_loss = torch.sum(recon_loss)\n            nll_loss = torch.sum(nll)\n\n            gp_loss_avg = torch.tensor([0.0]).to(device)\n            net_loss = torch.tensor([0.0]).to(device)\n            penalty_term = torch.tensor([0.0]).to(device)\n\n            for sample_iter in range(0, num_samples):\n\n                # Iterate over specified number of samples. Default: num_samples = 1.\n                Z = nnet_model.sample_latent(mu, log_var)\n                gp_loss = torch.tensor([0.0]).to(device)\n\n                for i in range(0, latent_dim):\n                    Z_dim = Z[:, i].view(-1).type(torch.DoubleTensor).to(device)\n\n                    if type_KL == 'closed':\n\n                        # Closed-form KL divergence formula\n                        kld1 = KL_closed(covar_module[i], train_x, likelihoods[i], data,  mu[:, i], log_var[:, i])\n                        gp_loss = gp_loss + kld1\n                    elif type_KL == 'conj_gradient':\n\n                        # GPyTorch default: use modified batch conjugate gradients\n                        # See: https://arxiv.org/abs/1809.11165\n                        gp_models[i].set_train_data(train_x.to(device), Z_dim.to(device))\n                        gp_loss = gp_loss - mlls[i](gp_models[i](train_x.to(device)), Z_dim)\n                    elif type_KL == 'GPapprox':\n\n                        # Our proposed efficient approximate GP inference scheme\n                        # See: http://arxiv.org/abs/2006.09763\n                        loss = -elbo(covar_module0[i], covar_module1[i], likelihoods[i], train_x, Z_dim,\n                                     zt_list[i].to(device), P, T, eps)\n                        gp_loss = gp_loss + loss\n\n                    elif type_KL == 'GPapprox_closed':\n\n                        # A variant of our proposed efficient approximate GP inference scheme.\n                        # The key difference with GPapprox is the direct use of the variational mean and variance,\n                        # instead of a sample from Z. We can call this a deviance upper bound.\n                        # See the L-VAE supplement for more details: http://arxiv.org/abs/2006.09763\n                        loss = deviance_upper_bound(covar_module0[i], covar_module1[i], likelihoods[i], train_x,\n                                                    mu[:, i].view(-1), log_var[:, i].view(-1), zt_list[i].to(device), P,\n                                                    T, eps)\n                        gp_loss = gp_loss + loss\n\n\n                if type_KL == 'closed' or type_KL == 'GPapprox' or type_KL == 'GPapprox_closed':\n                    if loss_function == 'mse':\n                        gp_loss_avg = gp_loss_avg + (gp_loss / latent_dim)\n                    elif loss_function == 'nll':\n                        gp_loss_avg = gp_loss_avg + gp_loss\n                elif type_KL == 'conj_gradient':\n                    if loss_function == 'mse':\n                        gp_loss = gp_loss * data.shape[0] / latent_dim\n                    elif loss_function == 'nll':\n                        gp_loss = gp_loss * data.shape[0]\n                    gp_loss_avg = gp_loss_avg + gp_loss\n\n            if type_KL == 'closed' or type_KL == 'GPapprox' or type_KL == 'GPapprox_closed':\n                gp_loss_avg = gp_loss_avg / num_samples\n                if loss_function == 'mse':\n                    net_loss = recon_loss + weight * gp_loss_avg\n                elif loss_function == 'nll':\n                    net_loss = nll_loss + gp_loss_avg\n            elif type_KL == 'conj_gradient':\n                gp_loss_avg = gp_loss_avg / num_samples\n                penalty_term = -0.5 * log_var.sum() / latent_dim\n                if loss_function == 'mse':\n                    net_loss = recon_loss + weight * (gp_loss_avg + penalty_term)\n                elif loss_function == 'nll':\n                    net_loss = nll_loss + gp_loss_avg + penalty_term\n\n            net_loss.backward()\n\n            if type_KL == 'closed' or type_KL == 'GPapprox' or type_KL == 'GPapprox_closed':\n                print('Iter %d/%d - Loss: %.3f  - GP loss: %.3f  - NLL Loss: %.3f  - Recon Loss: %.3f' % (\n                    epoch, epochs, net_loss.item(), gp_loss_avg.item(), nll_loss.item(), recon_loss.item()))\n            elif type_KL == 'conj_gradient':\n                print('Iter %d/%d - Loss: %.3f  - GP loss: %.3f  - Penalty: %.3f  - NLL Loss: %.3f  - Recon Loss: %.3f' % (\n                    epoch, epochs, net_loss.item(), gp_loss_avg.item(), penalty_term.item(), nll_loss.item(), recon_loss.item()))\n\n            penalty_term_arr = np.append(penalty_term_arr, penalty_term.cpu().item())\n            net_train_loss_arr = np.append(net_train_loss_arr, net_loss.cpu().item())\n            recon_loss_arr = np.append(recon_loss_arr, recon_loss.cpu().item())\n            nll_loss_arr = np.append(nll_loss_arr, nll_loss.cpu().item())\n            gp_loss_arr = np.append(gp_loss_arr, gp_loss_avg.cpu().item())\n            optimiser.step()\n            if constrain_scales:\n                for i in range(0, latent_dim):\n                    likelihoods[i].noise = torch.tensor([1], dtype=torch.float).to(device)\n\n            if (not epoch % 100) and epoch != epochs:\n                if validation_dataset is not None:\n                    standard_validate(nnet_model, type_nnet, validation_dataset, type_KL, num_samples, latent_dim, covar_module0, covar_module1, likelihoods, zt_list, T, weight, mu, train_x, id_covariate, loss_function, eps=1e-6)\n                    if torch.cuda.is_available():\n                        torch.cuda.empty_cache()\n\n    return penalty_term_arr, net_train_loss_arr, nll_loss_arr, recon_loss_arr, gp_loss_arr\n\ndef variational_inference_optimization(nnet_model, type_nnet, epochs, dataset, prediction_dataset, optimiser, \n    latent_dim, covar_module0, covar_module1, likelihoods, zt_list, P, T, Q, weight, constrain_scales, \n    id_covariate, loss_function, memory_dbg=False, eps=1e-6, results_path=None, save_path=None, gp_model_folder=None,\n    generation_dataset=None):\n\n    device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n    # set up Data Loader for training\n    dataloader = DataLoader(dataset, batch_size=len(dataset), shuffle=False, num_workers=4)\n\n    net_train_loss_arr = np.empty((0, 1))\n    recon_loss_arr = np.empty((0, 1))\n    nll_loss_arr = np.empty((0, 1))\n    gp_loss_arr = np.empty((0, 1))\n    penalty_term_arr = np.empty((0, 1))\n\n    for batch_idx, sample_batched in enumerate(dataloader):\n        label_id = sample_batched['idx']\n        label = sample_batched['label'].double().to(device)\n        data = sample_batched['digit'].double().to(device)\n        mask = sample_batched['mask'].double().to(device)\n\n        covariates = torch.cat((label[:, :id_covariate], label[:, id_covariate+1:]), dim=1)\n\n        # encode data\n        mu, log_var = nnet_model.encode(data)\n\n    mu = torch.nn.Parameter(mu.clone().detach(), requires_grad=True)\n    log_var = torch.nn.Parameter(log_var.clone().detach(), requires_grad=True)\n\n    try:\n        mu = torch.load(os.path.join(gp_model_folder, 'mu.pth'), map_location=torch.device(device)).detach().to(device).requires_grad_(True)\n        log_var = torch.load(os.path.join(gp_model_foder, 'log_var.pth'), map_location=torch.device(device)).detach().to(device).requires_grad_(True)\n    except:\n        pass\n\n    optimiser.add_param_group({'params': mu})\n    optimiser.add_param_group({'params': log_var})\n\n    for epoch in range(1, epochs + 1):\n        optimiser.zero_grad()\n        Z = nnet_model.sample_latent(mu, log_var)\n        recon_batch = nnet_model.decode(Z)\n        [recon_loss, nll] = nnet_model.loss_function(recon_batch, data, mask)\n        recon_loss = torch.sum(recon_loss)\n        nll_loss = torch.sum(nll)\n\n        gp_loss_avg = torch.tensor([0.0]).to(device)\n        net_loss = torch.tensor([0.0]).to(device)\n        penalty_term = torch.tensor([0.0]).to(device)\n\n        for i in range(0, latent_dim):\n            loss = deviance_upper_bound(covar_module0[i], covar_module1[i], likelihoods[i], label,\n                                        mu[:, i].view(-1), log_var[:, i].view(-1), zt_list[i].to(device), P,\n                                        T, eps)\n            gp_loss_avg = gp_loss_avg + loss / latent_dim\n\n        if loss_function == 'mse':\n            net_loss = recon_loss + weight * gp_loss_avg\n        elif loss_function == 'nll':\n            net_loss = nll_loss + gp_loss_avg\n\n        net_loss.backward()\n\n        print('Iter %d/%d - Loss: %.3f  - GP loss: %.3f  - NLL Loss: %.3f  - Recon Loss: %.3f' % (\n              epoch, epochs, net_loss.item(), gp_loss_avg.item(), nll_loss.item(), recon_loss.item()),\n              flush=True)\n\n        penalty_term_arr = np.append(penalty_term_arr, penalty_term.cpu().item())\n        net_train_loss_arr = np.append(net_train_loss_arr, net_loss.cpu().item())\n        recon_loss_arr = np.append(recon_loss_arr, recon_loss.cpu().item())\n        nll_loss_arr = np.append(nll_loss_arr, nll_loss.cpu().item())\n        gp_loss_arr = np.append(gp_loss_arr, gp_loss_avg.cpu().item())\n        optimiser.step()\n\n        if not epoch % 100:\n            sv_pth = os.path.join(save_path, 'recon_' + str(epoch) + '.pdf')\n            gen_rotated_mnist_plot(data[1920:2080].cpu().detach(), recon_batch[1920:2080].cpu().detach(), label[1920:2080].cpu().detach(), seq_length=20, num_sets=8, save_file=sv_pth)\n\n    torch.save(nnet_model.state_dict(), os.path.join(save_path, 'final-vae_model.pth'))\n    torch.save(mu, os.path.join(save_path, 'mu.pth'))\n    torch.save(log_var, os.path.join(save_path, 'log_var.pth'))\n    for i in range(0, latent_dim):\n        torch.save(covar_module0[i].state_dict(), os.path.join(save_path, 'cov_module0_' + str(i) + '.pth'))\n        torch.save(covar_module1[i].state_dict(), os.path.join(save_path, 'cov_module1_' + str(i) + '.pth'))\n\n    prediction_dataloader = DataLoader(prediction_dataset, batch_size=len(prediction_dataset), shuffle=False, num_workers=1)\n    for batch_idx, sample_batched in enumerate(prediction_dataloader):\n        label_pred = sample_batched['label'].double().to(device)\n        data_pred = sample_batched['digit'].double().to(device)\n        mask_pred = sample_batched['mask'].double().to(device)\n        covariates = torch.cat((label_pred[:, :id_covariate], label_pred[:, id_covariate+1:]), dim=1)\n        # encode data\n        mu_pred, log_var_pred = nnet_model.encode(data_pred)\n        break\n\n    try:\n        mu_pred = torch.load(os.path.join(gp_model_folder, 'mu_pred.pth'), map_location=torch.device(device)).detach().to(device).requires_grad_(True)\n        log_var_pred = torch.load(os.path.join(gp_model_folder, 'log_var_pred.pth'), map_location=torch.device(device)).detach().to(device).requires_grad_(True)\n    except:\n        pass\n\n    mu_pred = torch.nn.Parameter(mu_pred.clone().detach(), requires_grad=True)\n    log_var_pred = torch.nn.Parameter(log_var_pred.clone().detach(), requires_grad=True)\n    adam_param_list = []\n    adam_param_list.append({'params': mu_pred})\n    adam_param_list.append({'params': log_var_pred})\n    optimiser_pred = torch.optim.Adam(adam_param_list, lr=1e-3)\n    for epoch in range(1, 1001):\n        optimiser_pred.zero_grad()\n\n        Z = nnet_model.sample_latent(mu_pred, log_var_pred)\n\n        recon_batch = nnet_model.decode(Z)\n        [recon_loss, nll] = nnet_model.loss_function(recon_batch,\n                                                     data_pred,\n                                                     mask_pred)\n\n        recon_loss = torch.sum(recon_loss)\n        nll_loss = torch.sum(nll)\n\n        gp_loss_avg = torch.tensor([0.0]).to(device)\n\n        prediction_mu = torch.cat((mu_pred, mu), dim=0)\n        prediction_log_var = torch.cat((log_var_pred, log_var), dim=0)\n        prediction_x = torch.cat((label_pred, label), dim=0)\n\n        for i in range(0, latent_dim):\n            loss = deviance_upper_bound(covar_module0[i], covar_module1[i], likelihoods[i], prediction_x,\n                                        prediction_mu[:, i].view(-1), prediction_log_var[:, i].view(-1),\n                                        zt_list[i].to(device), P+8, T, eps)\n            gp_loss_avg = gp_loss_avg + loss / latent_dim\n\n        if loss_function == 'mse':\n            net_loss = recon_loss + weight * gp_loss_avg\n        elif loss_function == 'nll':\n            net_loss = nll_loss + gp_loss_avg\n\n        net_loss.backward()\n\n        print('Iter %d/1000 - Total Loss: %.3f  - GP Loss: %.3f  - Recon Loss: %.3f' % (\n              epoch, net_loss.item(), gp_loss_avg.item(), recon_loss.item()),\n              flush=True)\n\n        optimiser_pred.step()\n\n    torch.save(mu_pred, os.path.join(save_path, 'mu_pred.pth'))\n    torch.save(log_var_pred, os.path.join(save_path, 'log_var_pred.pth'))\n\n    l = [i*20 + k for i in range(0,8) for k in range(0,5)]\n    prediction_x = torch.cat((label_pred[l],\n                               label))\n    prediction_mu = torch.cat((mu_pred[l],\n                               mu))\n\n    if generation_dataset:\n        variational_complete_gen(generation_dataset, nnet_model, type_nnet,\n                                 results_path, covar_module0,\n                                 covar_module1, likelihoods, latent_dim,\n                                 './data', prediction_x, prediction_mu, 'final',\n                                 zt_list, P, T, id_covariate)\n\n    exit(0)\n", "meta": {"hexsha": "03c9ef1f24f20ac8f4f293fd7e680b58a95d7879", "size": 39779, "ext": "py", "lang": "Python", "max_stars_repo_path": "training.py", "max_stars_repo_name": "SidRama/Longitudinal-VAE", "max_stars_repo_head_hexsha": "3b8a341da14063728dd37a8e76b4372eb5256c97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-04-02T04:06:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T08:18:36.000Z", "max_issues_repo_path": "training.py", "max_issues_repo_name": "SidRama/Longitudinal-VAE", "max_issues_repo_head_hexsha": "3b8a341da14063728dd37a8e76b4372eb5256c97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-10-30T14:00:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-30T14:00:59.000Z", "max_forks_repo_path": "training.py", "max_forks_repo_name": "SidRama/Longitudinal-VAE", "max_forks_repo_head_hexsha": "3b8a341da14063728dd37a8e76b4372eb5256c97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-19T07:23:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T07:23:08.000Z", "avg_line_length": 51.9986928105, "max_line_length": 245, "alphanum_fraction": 0.6014228613, "include": true, "reason": "import numpy", "num_tokens": 9109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18066671193889203}}
{"text": "# -*- coding: utf-8 -*-\n# pylint: disable=wrong-import-position\n\n\"\"\"\nGenerate single-DOM Retro tables binned in (t,r,theta), with each bin\ncontaining a survival probability and average directionality vector. The length\nof this vector indicates \"how directional\" light is, from 0 (isotropic) to 1\n(perfectly directional). The information provided comes from the single-DOM\nRetro tables generated by CLSim, which are binned in\n(theta,r,t,theta_dir,deltaphi_dir).\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\n__all__ = ['generate_t_r_theta_table']\n\n__author__ = 'P. Eller, J.L. Lanfranchi'\n__license__ = '''Copyright 2017 Philipp Eller and Justin L. Lanfranchi\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.'''\n\nfrom os.path import abspath, dirname\nimport sys\n\nimport numpy as np\n\nif __name__ == '__main__' and __package__ is None:\n    PARENT_DIR = dirname(dirname(abspath(__file__)))\n    if PARENT_DIR not in sys.path:\n        sys.path.append(PARENT_DIR)\nfrom retro import DFLT_NUMBA_JIT_KWARGS, numba_jit\nfrom retro.const import SPEED_OF_LIGHT_M_PER_NS\nfrom retro.utils.stats import weighted_average\n\n\n@numba_jit(**DFLT_NUMBA_JIT_KWARGS)\ndef generate_t_r_theta_table(\n        table,\n        n_photons,\n        group_refractive_index,\n        t_bin_width,\n        angular_acceptance_fract,\n        thetadir_centers,\n        deltaphidir_centers,\n        theta_bin_edges\n    ):\n    \"\"\"Transform information from a raw single-DOM table (as output from CLSim)\n    that is binned in (r, theta, t, theta_dir, deltaphi_dir) into a more\n    compact representation, with a probability and an average direction vector\n    (represented by a single theta and phi) in each (t, r, theta) bin.\n\n    Parameters\n    ----------\n    table\n    n_photons\n    group_refractive_index\n    t_bin_width\n    angular_acceptance_fract\n    thetadir_centers\n    deltaphidir_centers\n    theta_bin_edges\n\n    Returns\n    -------\n    survival_probs\n    average_thetas\n    average_phis\n    lengths\n\n    \"\"\"\n    # Source tables are photon counts binned in\n    # (r, theta, t, dir_theta, dir_phi)\n    n_r_bins = table.shape[0]\n    n_theta_bins = table.shape[1]\n    n_t_bins = table.shape[2]\n\n    # (Base) survival probability (that will be modified by directionality):\n    # We can either\n    # 1. Sum over the directionality dimensions, which means \"probability that\n    #    photon is going in any one of these directions is P_{det, tot}. This\n    #    is like the total area under a curve, but then we have to distribute\n    #    this total area among all the directions via the distribution we\n    #    parameterize as fn of dir vector length.\"\n    # 2. Max over directionality dimensions, which means \"the best P_det occurs\n    #    if the photon is moving in this particular direction, whereupon it\n    #    will be detected with P_{det, max}. It gets worse from there according\n    #    to the distribution we parameterize as fn of dir vector length.\"\n\n    norm = (\n        1\n        / n_photons\n        / (SPEED_OF_LIGHT_M_PER_NS / group_refractive_index)\n        / t_bin_width\n        * angular_acceptance_fract\n        * n_theta_bins\n    )\n\n    # Destination tables are to be binned in (t, r, costheta) (there are as\n    # many costheta bins as theta bins in the original tables)\n    dest_shape = (n_t_bins, n_r_bins, n_theta_bins)\n\n    survival_probs = np.empty(dest_shape, dtype=np.float32)\n    average_thetas = np.empty(dest_shape, dtype=np.float32)\n    average_phis = np.empty(dest_shape, dtype=np.float32)\n    lengths = np.empty(dest_shape, dtype=np.float32)\n\n    for r_i in range(n_r_bins):\n        for theta_j in range(n_theta_bins):\n            for t_k in range(n_t_bins):\n                # flip coszen_dir (photon direction)\n                weights = table[r_i, theta_j, t_k, ::-1, :].astype(np.float64)\n                weights_tot = weights.sum()\n                if weights_tot == 0:\n                    # If no photons, just set the average direction to the\n                    # theta of the bin center...\n                    average_theta = 0.5 * (theta_bin_edges[theta_j]\n                                           + theta_bin_edges[theta_j + 1])\n                    # ... and lengths to 0\n                    length = 0.0\n                    average_phi = 0.0\n                else:\n                    # Average theta\n                    weights_theta = weights.sum(axis=1)\n                    average_theta = weighted_average(thetadir_centers,\n                                                     weights_theta)\n\n                    # Average delta phi\n                    projected_survival_prob = (\n                        (weights.T * np.sin(thetadir_centers)).T\n                    )\n                    weights_phi = projected_survival_prob.sum(axis=0)\n                    average_phi = weighted_average(deltaphidir_centers,\n                                                   weights_phi)\n\n                    # Length of vector (using projections from all vectors\n                    # onto average vector cos(angle) between average vector\n                    # and all angles)\n                    coscos = np.cos(thetadir_centers)*np.cos(average_theta)\n                    sinsin = np.sin(thetadir_centers)*np.sin(average_theta)\n                    cosphi = np.cos(deltaphidir_centers - average_phi)\n                    # Other half of sphere\n                    cospsi = (coscos + np.outer(sinsin, cosphi).T).T\n                    cospsi_avg = (cospsi * weights).sum() / weights_tot\n                    length = max(0.0, 2 * (cospsi_avg - 0.5))\n\n                # Output tables are expected to be in (flip(t), r, costheta).\n                # In addition to time being flipped, coszen is expected to be\n                # ascending, and therefore its binning is also flipped as\n                # compared to the theta binning in the original table.\n                dest_bin = (\n                    n_t_bins - 1 - t_k,\n                    r_i,\n                    n_theta_bins - 1 - theta_j\n                )\n\n                survival_probs[dest_bin] = norm * table[r_i, theta_j, t_k]\n                average_thetas[dest_bin] = average_theta\n                average_phis[dest_bin] = average_phi\n                lengths[dest_bin] = length\n\n    return survival_probs, average_thetas, average_phis, lengths\n", "meta": {"hexsha": "f6b6c8047b5a4a3af1c09035504ec386d3a3ae85", "size": 6800, "ext": "py", "lang": "Python", "max_stars_repo_path": "retro/tables/generate_t_r_theta_table.py", "max_stars_repo_name": "ellohfin/retro", "max_stars_repo_head_hexsha": "58ec8f5b698e6140acd215717f051d99e407c4e5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-02T01:05:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-02T01:05:52.000Z", "max_issues_repo_path": "retro/tables/generate_t_r_theta_table.py", "max_issues_repo_name": "ellohfin/retro", "max_issues_repo_head_hexsha": "58ec8f5b698e6140acd215717f051d99e407c4e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2018-01-30T21:03:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-07T16:42:07.000Z", "max_forks_repo_path": "retro/tables/generate_t_r_theta_table.py", "max_forks_repo_name": "ellohfin/retro", "max_forks_repo_head_hexsha": "58ec8f5b698e6140acd215717f051d99e407c4e5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-07-27T19:49:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-19T13:38:27.000Z", "avg_line_length": 39.5348837209, "max_line_length": 79, "alphanum_fraction": 0.6267647059, "include": true, "reason": "import numpy", "num_tokens": 1575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.18066670847019883}}
{"text": "## Copyright (c) 2019 Richard Offer. All right reserved.\n#\n# see LICENSE.md for license details\n#\n## Wrapper around random routines to make it easier to re-implement\n\nimport logging\n\nimport numpy.random as NPRND\n\nimport censere.utils as UTILS\n\n# Life table for the total population: United States, 2006\ncdc_2006 = [\n    0,\n    1,\n    2,\n    3,\n    4,\n    5,\n    6,\n    7,\n    8,\n    9,\n    10,\n    11,\n    12,\n    13,\n    14,\n    15,\n    16,\n    17,\n    18,\n    19,\n    20,\n    21,\n    22,\n    23,\n    24,\n    25,\n    26,\n    27,\n    28,\n    29,\n    30,\n    31,\n    32,\n    33,\n    34,\n    35,\n    36,\n    37,\n    38,\n    39,\n    40,\n    41,\n    42,\n    43,\n    44,\n    45,\n    46,\n    47,\n    48,\n    49,\n    50,\n    51,\n    52,\n    53,\n    54,\n    55,\n    56,\n    57,\n    58,\n    59,\n    60,\n    61,\n    62,\n    63,\n    64,\n    65,\n    66,\n    67,\n    68,\n    69,\n    70,\n    71,\n    72,\n    73,\n    74,\n    75,\n    76,\n    77,\n    78,\n    79,\n    80,\n    81,\n    82,\n    83,\n    84,\n    85,\n    86,\n    87,\n    88,\n    89,\n    90,\n    91,\n    92,\n    93,\n    94,\n    95,\n    96,\n    97,\n    98,\n    99,\n    100,\n]\n\n# 4.696378 is the sum of all probablilities\n#\ncdc_2006_weights = [\n    0.006713 / 4.696378 ,\n    0.000444 / 4.696378,\n    0.000300 / 4.696378,\n    0.000216 / 4.696378,\n    0.000179 / 4.696378,\n    0.000168 / 4.696378,\n    0.000156 / 4.696378,\n    0.000143 / 4.696378,\n    0.000125 / 4.696378,\n    0.000103 / 4.696378,\n    0.000086 / 4.696378,\n    0.000088 / 4.696378,\n    0.000125 / 4.696378,\n    0.000206 / 4.696378,\n    0.000317 / 4.696378,\n    0.000438 / 4.696378,\n    0.000552 / 4.696378,\n    0.000657 / 4.696378,\n    0.000747 / 4.696378,\n    0.000825 / 4.696378,\n    0.000905 / 4.696378,\n    0.000983 / 4.696378,\n    0.001033 / 4.696378,\n    0.001049 / 4.696378,\n    0.001038 / 4.696378,\n    0.001019 / 4.696378,\n    0.001006 / 4.696378,\n    0.000998 / 4.696378,\n    0.001002 / 4.696378,\n    0.001018 / 4.696378,\n    0.001042 / 4.696378,\n    0.001072 / 4.696378,\n    0.001113 / 4.696378,\n    0.001156 / 4.696378,\n    0.001212 / 4.696378,\n    0.001276 / 4.696378,\n    0.001355 / 4.696378,\n    0.001456 / 4.696378,\n    0.001585 / 4.696378,\n    0.001739 / 4.696378,\n    0.001903 / 4.696378,\n    0.002077 / 4.696378,\n    0.002268 / 4.696378,\n    0.002479 / 4.696378,\n    0.002706 / 4.696378,\n    0.002943 / 4.696378,\n    0.003190 / 4.696378,\n    0.003453 / 4.696378,\n    0.003741 / 4.696378,\n    0.004057 / 4.696378,\n    0.004405 / 4.696378,\n    0.004778 / 4.696378,\n    0.005166 / 4.696378,\n    0.005554 / 4.696378,\n    0.005939 / 4.696378,\n    0.006335 / 4.696378,\n    0.006760 / 4.696378,\n    0.007234 / 4.696378,\n    0.007796 / 4.696378,\n    0.008470 / 4.696378,\n    0.009282 / 4.696378,\n    0.010204 / 4.696378,\n    0.011178 / 4.696378,\n    0.012118 / 4.696378,\n    0.013024 / 4.696378,\n    0.013999 / 4.696378,\n    0.014995 / 4.696378,\n    0.016161 / 4.696378,\n    0.017527 / 4.696378,\n    0.019109 / 4.696378,\n    0.020890 / 4.696378,\n    0.022925 / 4.696378,\n    0.025280 / 4.696378,\n    0.027972 / 4.696378,\n    0.030997 / 4.696378,\n    0.034386 / 4.696378,\n    0.038027 / 4.696378,\n    0.042036 / 4.696378,\n    0.046447 / 4.696378,\n    0.051297 / 4.696378,\n    0.056623 / 4.696378,\n    0.062465 / 4.696378,\n    0.068867 / 4.696378,\n    0.075871 / 4.696378,\n    0.083524 / 4.696378,\n    0.091872 / 4.696378,\n    0.100962 / 4.696378,\n    0.110842 / 4.696378,\n    0.121558 / 4.696378,\n    0.133155 / 4.696378,\n    0.145675 / 4.696378,\n    0.159156 / 4.696378,\n    0.173631 / 4.696378,\n    0.189127 / 4.696378,\n    0.205661 / 4.696378,\n    0.223242 / 4.696378,\n    0.241869 / 4.696378,\n    0.261527 / 4.696378,\n    0.282188 / 4.696378,\n    0.303810 / 4.696378,\n    1.0000 / 4.6963780\n]\n\n\ndef seed( seed ):\n\n    return NPRND.seed( seed )\n\n\ndef set_state( st ):\n\n    return NPRND.set_state( st )\n\ndef get_state( ):\n\n    return NPRND.get_state( )\n\n# return a string of random bytes\n# We use this rather than UUID so that\n# we can get the same IDs if the same seed is used\n#\n# uuid.uuid() uses the os.urandom() and can't be replayed.\n#\ndef id():\n\n    return NPRND.bytes(16).hex()\n\n\ndef random():\n\n    return NPRND.random()\n\n\n## return a random number between start and stop\n#\n# Return a random integer N such that a <= N < b.\n#\ndef randrange( start, stop ):\n\n    return NPRND.randint( start, stop )\n\n##\n#\n# Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1)\n#\ndef randint( start, stop ):\n\n    if start == stop:\n        return start\n\n    return randrange( start, stop + 1  )\n\ndef gauss( mean, sigma):\n\n    return mean + ( NPRND.randn() * sigma )\n\ndef triangle( minimum, peak, maximum):\n\n    return NPRND.triangular( minimum, peak, maximum )\n\ndef choice( lst):\n\n    return NPRND.choice( lst )\n\ndef choices( lst, weights=None ):\n\n    return NPRND.choice( lst, None, p=[ (i/100.0) for i in weights ] )\n\ndef life_expectancy():\n\n    return NPRND.choice( cdc_2006, None, p=cdc_2006_weights )\n\n\n##\n# tables: prefix is only valid for life-expectancy values\n#\n# Difference between randint and randrange is that randint only returns int\n# and handles the case where MIN == MAX, randrange will error in that case\n# TODO\n#   * handle sexes life expectancy independently\n# \ndef parse_random_value( key, default_value=None, key_in_earth_years=False ):\n\n    val = key.split(\":\")\n\n    value = default_value\n\n\n    if val[0] == \"cdc\":\n        value = life_expectancy()\n\n    elif val[0] == \"triangular\" or val[0] == \"triangle\" :\n\n        values = [ float(i) for i in val[1].split(\",\") ]\n        value = triangle( values[0], values[1], values[2] )\n\n    elif val[0] == \"gauss\":\n        values = [ float(i) for i in val[1].split(\",\") ]\n        value = gauss( values[0], values[1] ),\n\n    elif val[0] == \"randint\":\n\n        values = [ int(i) for i in val[1].split(\",\") ]\n        value = randint( values[0], values[1] )\n\n    elif val[0] == \"randrange\":\n\n        values =  [float(i) for i in val[1].split(\",\") ]\n        value = randrange( values[0], values[1] )\n\n    elif val[0] == \"half\":\n\n        values = [ float(i) for i in val[1].split(\",\") ]\n\n        r = random()\n\n        if r < 0.5:\n            value = ( values[0] ) + ( values[1] * random() )\n        elif r < 0.75:\n            value = ( values[0] + ( values[1] ) ) + ( values[1] * random() )\n        elif r < 0.875:\n            value = ( values[0] + ( values[1] * 2 ) ) + ( values[1] * random() )\n        elif r < 0.925:\n            value = ( values[0] + ( values[1] * 3 ) ) + ( values[1] * random() )\n        elif r < 0.9625:\n            value = ( values[0] + ( values[1] * 4 ) ) + ( values[1] * random() )\n        elif r < 0.98125:\n            value = ( values[0] + ( values[1] * 5 ) ) + ( values[1] * random() )\n        elif r < 0.990625:\n            value = ( values[0] + ( values[1] * 6 ) ) + ( values[1] * random() )\n        elif r < 0.9953125:\n            value = ( values[0] + ( values[1] * 7 ) ) + ( values[1] * random() )\n        else:\n            value = ( values[0] + ( values[1] * 8 ) ) + ( values[1] * random() )\n \n    else:\n\n        logging.fatal( 'Invalid value %s', key )\n\n\n    if key_in_earth_years:\n\n        return UTILS.years_to_sols( value )\n\n    return value\n", "meta": {"hexsha": "ac886954222bc2275f12da1a6fd1d935cc0d5971", "size": 7162, "ext": "py", "lang": "Python", "max_stars_repo_path": "censere/utils/random.py", "max_stars_repo_name": "nhi-vanye/mars-censere", "max_stars_repo_head_hexsha": "65678b7bc102e2adff2f78f8b3a13ba84cdf0a01", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "censere/utils/random.py", "max_issues_repo_name": "nhi-vanye/mars-censere", "max_issues_repo_head_hexsha": "65678b7bc102e2adff2f78f8b3a13ba84cdf0a01", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "censere/utils/random.py", "max_forks_repo_name": "nhi-vanye/mars-censere", "max_forks_repo_head_hexsha": "65678b7bc102e2adff2f78f8b3a13ba84cdf0a01", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5683060109, "max_line_length": 80, "alphanum_fraction": 0.5333705669, "include": true, "reason": "import numpy", "num_tokens": 2853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.18066670500150564}}
{"text": "#!/usr/bin/env python2\n\nimport sys\nsys.path.append('../fml/')\n\nimport os\nimport numpy as np\nimport fml\n\nfrom fml.math.distance import get_l2_distance_arad\nfrom fml.kernels import get_atomic_kernels_arad\n\nPTP = {\\\n         1  :[1,1] ,2:  [1,8]#Row1\n       \n        ,3  :[2,1] ,4:  [2,2]#Row2\\\n        ,5  :[2,3] ,6:  [2,4] ,7  :[2,5] ,8  :[2,6] ,9  :[2,7] ,10 :[2,8]\\\n       \n        ,11 :[3,1] ,12: [3,2]#Row3\\\n        ,13 :[3,3] ,14: [3,4] ,15 :[3,5] ,16 :[3,6] ,17 :[3,7] ,18 :[3,8]\\\n       \n        ,19 :[4,1] ,20: [4,2]#Row4\\\n        ,31 :[4,3] ,32: [4,4] ,33 :[4,5] ,34 :[4,6] ,35 :[4,7] ,36 :[4,8]\\\n        ,21 :[4,9] ,22: [4,10],23 :[4,11],24 :[4,12],25 :[4,13],26 :[4,14],27 :[4,15],28 :[4,16],29 :[4,17],30 :[4,18]\\\n\n        ,37 :[5,1] ,38: [5,2]#Row5\\\n        ,49 :[5,3] ,50: [5,4] ,51 :[5,5] ,52 :[5,6] ,53 :[5,7] ,54 :[5,8]\\\n        ,39 :[5,9] ,40: [5,10],41 :[5,11],42 :[5,12],43 :[5,13],44 :[5,14],45 :[5,15],46 :[5,16],47 :[5,17],48 :[5,18]\\\n\n        ,55 :[6,1] ,56: [6,2]#Row6\\\n        ,81 :[6,3] ,82: [6,4] ,83 :[6,5] ,84 :[6,6] ,85 :[6,7] ,86 :[6,8]\n               ,72: [6,10],73 :[6,11],74 :[6,12],75 :[6,13],76 :[6,14],77 :[6,15],78 :[6,16],79 :[6,17],80 :[6,18]\\\n        ,57 :[6,19],58: [6,20],59 :[6,21],60 :[6,22],61 :[6,23],62 :[6,24],63 :[6,25],64 :[6,26],65 :[6,27],66 :[6,28],67 :[6,29],68 :[6,30],69 :[6,31],70 :[6,32],71 :[6,33]\\\n\n        ,87 :[7,1] ,88: [7,2]#Row7\\\n        ,113:[7,3] ,114:[7,4] ,115:[7,5] ,116:[7,6] ,117:[7,7] ,118:[7,8]\\\n               ,104:[7,10],105:[7,11],106:[7,12],107:[7,13],108:[7,14],109:[7,15],110:[7,16],111:[7,17],112:[7,18]\\\n        ,89 :[7,19],90: [7,20],91 :[7,21],92 :[7,22],93 :[7,23],94 :[7,24],95 :[7,25],96 :[7,26],97 :[7,27],98 :[7,28],99 :[7,29],100:[7,30],101:[7,31],101:[7,32],102:[7,14],103:[7,33]}\n#@jit#(nopython = True, nogil = True)   \n\n\n#@jit#(nopython = True, nogil = True)   \n\n\ndef condense(X1,X2,Z1,Z2,width = 0.2, cutDist = 6.,RWidth = 1 ,CWidth = 0.5,num_cores = 1, printTime = False,molecular = False):#RWidth =1./sqrt(2),Cwidth = 1./sqrt(2)):#,RWidth =1.,Cwidth = 1.):\n    def createZINP(Z,l):\n        Z_inp = -1*np.ones((len(Z),l,2)).astype(int)\n        for i in range(len(Z)):\n            Z_inp[i,:len(Z[i])] = np.asarray([PTP[z] for z in Z[i]])\n           \n        return Z_inp\n   \n    RWidth = float(RWidth)\n    Cwidth = float(CWidth)\n    Z1_inp = createZINP(Z1,len(X1[0]))\n    Z2_inp = createZINP(Z2,len(X2[0]))\n   \n    from time import time\n\n   \n\n    start = time()\n    DistMatrix = run(X1,X2,Z1_inp,Z2_inp,width,cutDist,RWidth,Cwidth,num_cores,molecular = molecular)\n    if printTime:\n        print 'Time Paralell: ', time() - start\n    #print DistMatrix[0,0]\n    #print DistMatrix.shape\n    return DistMatrix\n\n\nclass KeyboardInterruptError(Exception): pass\n\ndef run(X1,X2,Z1,Z2,width,cutDist,RWidth,Cwidth,Ncores = 2,NIters = 20, molecular = True ):\n    NIters = min(len(X2),NIters)\n    from multiprocessing import Pool\n    try:\n       \n        p = Pool(Ncores)\n       \n        w_list  = np.repeat(width,len(X1))\n        cD_list = np.repeat(cutDist,len(X1))\n        RW_list = np.repeat(RWidth,len(X1))\n        CW_list = np.repeat(Cwidth,len(X1))\n        const_list =np.repeat(np.NaN,len(X1))\n       \n        w_list_2  = np.repeat(width,len(X2))\n        cD_list_2 = np.repeat(cutDist,len(X2))\n        RW_list_2 = np.repeat(RWidth,len(X2))\n        CW_list_2 = np.repeat(Cwidth,len(X2))\n       \n       \n       \n   \n        args1 = [X1,Z1,w_list,cD_list,RW_list,CW_list]\n        args2 = [X2,Z2,w_list_2,cD_list_2,RW_list_2,CW_list_2]   \n       \n        if molecular:\n            pass_nonmNoDist\n            D1 = np.asarray(p.map(pass_nonmNoDist,zip(*args1)))\n            D2 = np.asarray(p.map(pass_nonmNoDist,zip(*args2)))\n            D1 = unravelKerMatrix(D1)\n            D2 = unravelKerMatrix(D2)\n       \n        else:\n            D1 = np.asarray(p.map(pass_calcNorm,zip(*args1)))\n            D2 = np.asarray(p.map(pass_calcNorm,zip(*args2)))\n       \n        i_2 = 0\n        x2 = np.repeat(np.asarray([X2[i_2:min(len(X2),i_2 + NIters)]]),len(X1),axis = 0)\n        z2 = np.repeat(np.asarray([Z2[i_2:min(len(X2),i_2 + NIters)]]),len(X1),axis = 0)\n        d2 = np.repeat(np.asarray([D2[i_2:min(len(X2),i_2 + NIters)]]),len(X1),axis = 0)\n        d2 = np.repeat(np.asarray([D2[i_2:min(len(X2),i_2 + NIters)]]),len(X1),axis = 0)\n        if molecular:\n            args = [X1,x2,Z1,z2,w_list,cD_list,RW_list,CW_list]\n            results = np.asarray(p.map(pass_calcProdnoDist,zip(*args)))   \n        else:\n            args = [X1,x2,Z1,z2,D1,d2,w_list,cD_list,RW_list,CW_list,const_list]\n            results = np.asarray(p.map(pass_calcProd,zip(*args)))\n\n        for i_2 in range(NIters,len(X2),NIters):\n            x2 = np.repeat(np.asarray([X2[i_2:min(len(X2),i_2 + NIters)]]),len(X1),axis = 0)\n            z2 = np.repeat(np.asarray([Z2[i_2:min(len(X2),i_2 + NIters)]]),len(X1),axis = 0)\n            d2 = np.repeat(np.asarray([D2[i_2:min(len(X2),i_2 + NIters)]]),len(X1),axis = 0)\n           \n            if molecular:\n                args = [X1,x2,Z1,z2,w_list,cD_list,RW_list,CW_list]\n                results = append(results,\n                    np.asarray(p.map(pass_calcProdnoDist,zip(*args))),\n                    axis = 1)   \n            else:\n                args = [X1,x2,Z1,z2,D1,d2,w_list,cD_list,RW_list,CW_list,const_list]\n                results = append(results,\n                    np.asarray(p.map(pass_calcProd,zip(*args))),\n                    axis = 1)\n        p.close()\n        p.join()\n            #print results.shape\n       \n        if molecular:\n            results = unravelKerMatrix(results)\n            #print results[0:5,0:5]\n            #print D1[0:5]\n            #print D2[0:5]           \n            #print results.shape,D1[:,newaxis].shape,D2[newaxis].shape\n\n            D = D1[:,newaxis] +  D2[newaxis]\n            results =  D - 2 * results\n            #print results[0:5,0:5]\n       \n        return results   \n    except KeyboardInterrupt:\n        print 'got ^C'\n        p.terminate()\n        p.join()\n        raise KeyboardInterrupt\n   \n    except Exception, inst:\n        p.terminate()\n        p.join()\n        print 'got exception: %r' % (inst,)\n        print type(inst)     # the exception instance\n        print inst.args      # arguments stored in .args\n        print inst           # __str__ allows args to be printed directly\n        raise inst\n   \ndef pass_calcNorm(args):\n    try:\n        return calcNorm(*args)\n    except KeyboardInterrupt:\n        raise KeyboardInterruptError()\n\ndef calcNorm(X,Z,width,cutDist,RWidth,Cwidth):\n   \n    DistMatrix  = np.zeros(len(X))\n    for i in  range(len(X)):\n        if Z[i,0] == -1:\n            break\n        dd = _MDist(X[i],X[i],width,cutDist,RWidth,Cwidth)\n        DistMatrix[i] = dd\n\n    return DistMatrix   \n\n#@jit\ndef pass_calcProd(args):\n    try:   \n        return calcProd(*args)\n    except KeyboardInterrupt:\n        raise KeyboardInterruptError()\n#@jit#(nopython = True, nogil = True)               \ndef calcProd(X1,X2,Z1,Z2,D1,D2,width,cutDist,RWidth,Cwidth,const):\n    #maxRDist = 8*RWidth\n    #maxCDist = 8*Cwidth\n   \n\n    DistMatrix  = const * np.ones((len(X2), len(X1), len(X2[0])))\n    for i in range(len(X2)):\n        for j_1 in  range(len(X1)):\n\n            if Z1[j_1,0] == -1:\n                break\n\n            for j_2 in range(len(X2[0])):\n\n                if Z2[i,j_2,0] == -1:\n                    break\n\n                RDist = abs(Z1[j_1,0] - Z2[i,j_2,0])\n                CDist = abs(Z1[j_1,1] - Z2[i,j_2,1])\n               \n                #if RDist < maxRDist and CDist < maxCDist:\n                dd = _MDist(X1[j_1],X2[i,j_2],width,cutDist,RWidth,Cwidth)\n                dd = dd *_StochDist(RDist,CDist,RWidth,Cwidth)\n               \n               \n                dd = D1[j_1] + D2[i,j_2] - 2 * dd\n               \n                if dd < 0:\n                    assert dd > -1E-13, 'Something is wrong in calcProd: ' + str(dd)       \n                    DistMatrix[i,j_1,j_2] = 0\n               \n               \n                DistMatrix[i,j_1,j_2] = dd\n               \n    return DistMatrix\n\ndef pass_calcProdnoDist(args):\n    try:\n        return calcProd_noDist(*args)\n    except KeyboardInterrupt:\n        raise KeyboardInterruptError()\n\ndef calcProd_noDist(X1,X2,Z1,Z2,width,cutDist,RWidth,Cwidth):\n   \n    DistMatrix  = np.zeros((len(X2), len(X1), len(X2[0])))\n    for i in range(len(X2)):\n        for j_1 in  range(len(X1)):\n\n            if Z1[j_1,0] == -1:\n                break\n\n            for j_2 in range(len(X2[0])):\n\n                if Z2[i,j_2,0] == -1:\n                    break\n\n                RDist = abs(Z1[j_1,0] - Z2[i,j_2,0])\n                CDist = abs(Z1[j_1,1] - Z2[i,j_2,1])\n               \n                dd = _MDist(X1[j_1],X2[i,j_2],width,cutDist,RWidth,Cwidth)\n                dd = dd *_StochDist(RDist,CDist,RWidth,Cwidth)\n                DistMatrix[i,j_1,j_2] = dd\n               \n    return DistMatrix\n\ndef pass_nonmNoDist(args):\n    try:\n        return nonmNoDist(*args)\n    except KeyboardInterrupt:\n        raise KeyboardInterruptError()\n\ndef nonmNoDist(X1,Z1,width,cutDist,RWidth,Cwidth):\n   \n    DistMatrix  = np.zeros((len(X1), len(X1)))\n    for j_1 in  range(len(X1)):\n        if Z1[j_1,0] == -1:\n            break\n        for j_2 in range(len(X1)):\n            if Z1[j_2,0] == -1:\n                break\n            RDist = abs(Z1[j_1,0] - Z1[j_2,0])\n            CDist = abs(Z1[j_1,1] - Z1[j_2,1])\n            dd = _MDist(X1[j_1],X1[j_2],width,cutDist,RWidth,Cwidth)\n            dd = dd *_StochDist(RDist,CDist,RWidth,Cwidth)\n            DistMatrix[j_1,j_2] = dd\n               \n    return DistMatrix\n\ndef _MDist(X1,X2,width,cutDist,RWidth,Cwidth):\n    maxGausDist = 8*width\n    #maxRDist = 8*RWidth\n    #maxCDist = 8*Cwidth   \n    AAdist = 0\n\n    for m_1 in range(len(X1[0])):\n       \n        if X1[0,m_1] > cutDist:\n            break\n\n        for m_2 in range(len(X2[0])):\n            if X2[0,m_2] > cutDist:\n                break\n            if  abs(X2[0,m_2] - X1[0,m_1]) < maxGausDist:\n                RDist = abs(X1[1,m_1] - X2[1,m_2])\n                CDist = abs(X1[2,m_1] - X2[2,m_2])\n                #if RDist < maxRDist and CDist < maxCDist:\n                d = _dist(X1[0,m_1], X2[0,m_2],width,cutDist)\n                d = d *_StochDist(RDist,CDist,RWidth,Cwidth)\n                AAdist += d * (1 + X1[3,m_1]*X2[3,m_2] + X1[4,m_1]*X2[4,m_2])\n    return AAdist   \n\ndef _dist(x1,x2,w1,w2):\n    return np.exp(-((x1-x2)**2)/(4*w1**2))*(1 - np.sin(np.pi * x1/(2 * w2)))*(1 - np.sin(np.pi * x2/(2 * w2))) #*(math.cos(pi * x1/(2 * w2))*math.cos(pi * x2/(2 * w2)))\n                      \n                      \ndef _StochDist(D1,D2,W1,W2):\n    rdist =  W1**2/(W1**2 + D1**2) * W2**2/(W2**2 + D2**2)\n    # print \"rdist\", rdist\n    return rdist\n    # return W1**2/(W1**2 + D1**2) * W2**2/(W2**2 + D2**2)\n    #math.exp(-(D1**2)/(4*W1**2) -(D2**2)/(4*W2**2))\n   \ndef unravelKerMatrix(KM):\n   \n    KM_unravled = np.nansum(KM,axis = (-2,-1))\n    return KM_unravled\n\n\n\nif __name__ == \"__main__\":\n    \n    \n    mols = []\n    path = \"tests/xyz/\"\n    filenames = os.listdir(path)\n\n\n    print \"Generating ARAD descriptors from FML interface ...\"\n    for filename in filenames:\n\n        mol = fml.Molecule()\n        mol.read_xyz(path + filename)\n        mol.generate_arad_descriptor(size=30)\n        mols.append(mol)\n\n    \n    arad = fml.ARAD()\n\n\n    x1 = []\n    z1 = []\n\n    print \"Generating ARAD descriptors from reference implementation ...\"\n    for mol in mols[:5]:\n\n        z1.append(np.array(mol.nuclear_charges))\n        x1.append(arad.describe(np.array(mol.coordinates),np.array(mol.nuclear_charges)))\n\n\n    x2 = []\n    z2 = []\n\n    for mol in mols[5:]:\n\n        z2.append(np.array(mol.nuclear_charges))\n        x2.append(arad.describe(np.array(mol.coordinates),np.array(mol.nuclear_charges)))\n\n    print \"Calculating ARAD Distance matrix from reference code ...\"\n    Da = condense(x1,x2,z1,z2, molecular=False)\n\n    np.set_printoptions(linewidth=10000000)\n\n    print \"Calculating ARAD Distance matrix from FML code ... \"\n    Db = get_l2_distance_arad(np.array(x1),np.array(x2),z1,z2)\n\n    print \"Example distance matrix (reference)\"\n    print Da[3,2][:10,:10]\n    print Da.shape\n    print \"Example distance matrix (FML ARAD)\"\n    print Db[3,2][:10,:10]\n    print Db.shape\n\n\n    print \"Max abs element distance difference:\", np.nanmax(np.abs(Da - Db))\n    print \"Max abs element distance difference index:\", np.nanargmax(np.abs(Da - Db))\n\n\n    sigmas = [0.1, 1.0, 10.0, 100.0]\n\n    Ka = np.zeros((len(sigmas),len(x1),len(x2)))\n\n    print \"Calculating kernel from reference distance matrix\"\n    for s, sigma in enumerate(sigmas):\n\n        for i in range(len(x1)):\n            for j in range(len(x2)):\n\n                Ka[s,i,j] = np.nansum(np.exp(Da[i,j] * (-1.0 / sigma**2)))\n\n    print \"Calculating kernel from FML distance matrix\"\n    Kb = get_atomic_kernels_arad(np.array(x1), np.array(x2), z1, z2, sigmas)\n\n    print \"Example kernel matrix (reference)\"\n    print Ka[-2]\n\n\n    print \"Example kernel matrix (ARAD)\"\n    print Kb[-2]\n\n    print \"Max abs element kernel difference:\", np.nanmax(np.abs(Ka - Kb))\n    print \"Max abs element kernel difference index:\", np.nanargmax(np.abs(Ka - Kb))\n", "meta": {"hexsha": "4534c5a6095a242df82c213a317551f5724ba1c6", "size": 13235, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_arad.py", "max_stars_repo_name": "larsbratholm/ml_clustering", "max_stars_repo_head_hexsha": "dec3386676f8b22054f18643b1ae7d3e44c65527", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-10-28T11:09:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-21T06:08:21.000Z", "max_issues_repo_path": "tests/test_arad.py", "max_issues_repo_name": "larsbratholm/ml_clustering", "max_issues_repo_head_hexsha": "dec3386676f8b22054f18643b1ae7d3e44c65527", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_arad.py", "max_forks_repo_name": "larsbratholm/ml_clustering", "max_forks_repo_head_hexsha": "dec3386676f8b22054f18643b1ae7d3e44c65527", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-03-31T16:00:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T02:10:29.000Z", "avg_line_length": 33.0049875312, "max_line_length": 195, "alphanum_fraction": 0.5267094824, "include": true, "reason": "import numpy", "num_tokens": 4544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.18063511781900926}}
{"text": "from contextlib import AbstractContextManager, suppress\nfrom enum import IntEnum, unique\nfrom time import sleep\n\nfrom scipy.constants import speed_of_light as c_vacuum\n\nfrom .base import InstrumentException\nfrom .utils import is_valid_IP, timeout\nfrom .XPS_C8_drivers import XPS\n\nair_refractive_index = 1.0003\nc_air = c_vacuum / air_refractive_index  # meters per second\n\n\n@unique\nclass XPSC8Errors(IntEnum):\n    \"\"\"\n    Enumeration of possible XPS-C8 errors.\n    \"\"\"\n\n    # TODO: Error code and error description\n    #       See example:\n    #       https://docs.python.org/3/library/enum.html#planet\n\n    NoError = 0\n    SocketConnectionError = -1\n    WrongObjectTypeForCmd = -8\n    ParameterOutOfRangeOrIncorrect = -17\n    PositionerNameDoesNotExistOrUnknownCmd = -18\n    GroupNameDoesNotExistOrUnknownCmd = -19\n    NotAllowedAction = -22\n    FollowingError = -25\n    EmergencySignal = -26\n    MoveAborted = -27\n    HomeSearchTimeout = -28\n    MotionDoneTimeout = -33\n    PositionOutsideTravelLimits = -35\n    SlaveErrorDisablingMaster = -44\n    InconsistentMechanicalZero = -49\n    MotorInitiError = -50\n    BothEndRunsActivated = -113\n    WarningErrorDuringMove = -120\n    NotExpectedPositionAfterMotion = -221\n\n\ndef _errcheck(returned):\n    \"\"\"\n    This function checks that any error code is 0 (success)\n    Otherwise, raise an InstrumentException with the correct\n    error code. The ``returned`` value is either an error code\n    or a list (in which case the error code is the first value) \n    \"\"\"\n    if returned is None:\n        raise ValueError(\"None has been returned\")\n    with suppress(ValueError):  # unknown error code.\n        if isinstance(returned, list):\n            errcode = returned[0]\n        else:\n            errcode = returned\n        error = XPSC8Errors(int(errcode))\n        if error != XPSC8Errors.NoError:\n            raise InstrumentException(error)\n    return returned\n\n\nclass DelayStage(AbstractContextManager):\n    \"\"\"\n    Abstract interface to one delay-stage\n    connected to a Newport XPS C8.\n\n    Parameters\n    ----------\n    address : str, optional\n        IP address of the XPS, e.g. '192.168.33.101'.\n\n    Raises\n    ------\n    ValueError : if ``address`` is an invalid IPv4 address.\n    InstrumentException : if any connection error occurs.\n    \"\"\"\n\n    _driver = XPS()\n\n    # group and positioner must be overriden in subclasses\n    group = \"\"\n    positioner = group + \"\"\n\n    def __init__(self, address, **kwargs):\n        # self.socket_id = None\n\n        # According to TCP_ConnectToServer documentation,\n        # port is always 5001\n        if not is_valid_IP(address):\n            raise ValueError(\"{} is an invalid IPv4 address\".format(address))\n\n        self.socket_id = _errcheck(\n            self._driver.TCP_ConnectToServer(IP=address, port=5001, timeOut=10)\n        )\n\n        # Reset state by killing the group, and initializing again\n        # Note: GroupKill returns [errcode, string] for some reason\n        # even though documentation doesn't say that\n        _errcheck(self._driver.KillAll(self.socket_id))\n        _errcheck(self._driver.GroupInitialize(self.socket_id, self.group))\n        _errcheck(self._driver.GroupHomeSearch(self.socket_id, self.group))\n\n        # Get position limits\n        errcode, self.min_limit, self.max_limit = _errcheck(\n            self._driver.PositionerUserTravelLimitsGet(self.socket_id, self.positioner)\n        )\n\n    def __exit__(self, *args, **kwargs):\n        self.disconnect()\n        super().__exit__(*args, **kwargs)\n\n    @staticmethod\n    def delay_to_distance(delay):\n        \"\"\" Calculate the distance by which to move [mm] for light round-trip\n        of ``delay`` picoseconds \"\"\"\n        # Distance to move is half because of back-and-forth motion\n        # along the stage\n\n        # Increasing distance means the laser pulse arrives later;\n        # since the electron pulse arrives at fixed times\n        # this means that increasing distance -> earlier probing\n        move_meters = (delay / 1e12) * (c_air / 2)\n        return -1 * move_meters * 1e3\n\n    @staticmethod\n    def distance_to_delay(dist):\n        \"\"\" Calculate the extra time [ps] it takes for light to make a round-trip\n        if the stage moves by ``dist`` millimeters. \"\"\"\n        # Increasing distance means the laser pulse arrives later;\n        # since the electron pulse arrives at fixed times\n        # this means that increasing distance -> earlier probing\n        extra_path = 2 * float(dist) / 1e3  # extra path [meters]\n        return -1 * (extra_path / c_air) * 1e12  # [picoseconds]\n\n    def disconnect(self):\n        \"\"\" Disconnect from the XPS \"\"\"\n        self._driver.TCP_CloseSocket(self.socket_id)\n\n    def _wait_end_of_move(self, tout=10, tol=5e-3):\n        \"\"\" \n        Wait for end of move, i.e. when the current position is close\n        enough to the target.\n\n        Parameters\n        ----------\n        tout : float, optional\n            Time-out time in seconds\n        tol : float, optional\n            Position tolerance.\n        \"\"\"\n        with timeout(tout, InstrumentException, exc_message=\"Movement timeout\"):\n            while abs(self.current_position() - self.target_position()) > tol:\n                sleep(0.1)\n\n    def target_position(self):\n        \"\"\"\n        Get the current absolute position setpoint\n\n        Returns\n        -------\n        pos : float\n        \"\"\"\n        errcode, position = _errcheck(\n            self._driver.GroupPositionTargetGet(\n                self.socket_id, self.positioner, nbElement=1\n            )\n        )\n        return float(position)\n\n    def current_position(self):\n        \"\"\"\n        Get current absolute position\n        \n        Returns\n        -------\n        pos : float\n        \"\"\"\n        errcode, position = _errcheck(\n            self._driver.GroupPositionCurrentGet(\n                self.socket_id, self.positioner, nbElement=1\n            )\n        )\n        return float(position)\n\n    def relative_move(self, move):\n        \"\"\" \n        Move the delay stage relatively to current position, by distance. This\n        function returns when move is completed.\n        \n        Parameters\n        ---------- \n        move : float\n            Relative move [mm]\n        \"\"\"\n        move = float(move)\n        # For some reason, the targetDisplacement parameter\n        # to GroupMoveRelative should be an iterable...\n        _errcheck(\n            self._driver.GroupMoveRelative(self.socket_id, self.positioner, [move])\n        )\n        return self._wait_end_of_move()\n\n    def absolute_move(self, move):\n        \"\"\"\n        Move the delay stage to a new absolute position, by distance. This\n        function returns when move is completed.\n        \n        Parameters\n        ---------- \n        move : float\n            Absolute move [mm]\n        \"\"\"\n        move = float(move)\n        # For some reason, the targetDisplacement parameter\n        # to GroupMoveAbsolute should be an iterable...\n        _errcheck(\n            self._driver.GroupMoveAbsolute(self.socket_id, self.positioner, [move])\n        )\n        return self._wait_end_of_move()\n\n    def relative_time_shift(self, shift):\n        \"\"\"\n        Move the delay stage to achieve a certain relative time-shift. This\n        function returns when move is completed.\n\n        Parameters\n        ----------\n        shift : float\n            Time-shift in picoseconds\n        \"\"\"\n        shift = float(shift)\n        return self.relative_move(self.delay_to_distance(shift))\n\n    def absolute_time(self, time, tzero_position=0.0):\n        \"\"\"\n        Move the delay stage to achieve a time-shift with respect\n        to a position for time-zero. This function returns when move is completed.\n\n        Parameters\n        ----------\n        time : float\n            Desired absolute time-shift in picoseconds\n        tzero_position : float, optional\n            Time-zero position in millimeters.\n        \"\"\"\n        time, tzero_position = float(time), float(tzero_position)\n        return self.absolute_move(self.delay_to_distance(time) + tzero_position)\n\n\nclass ILS250PP(DelayStage):\n    \"\"\"\n    Interface to an ILS250PP delay-stage connected\n    to a Newport XPS C8 positioner.\n    \"\"\"\n\n    group = \"GROUP5\"\n    positioner = group + \".POSITIONER\"\n\n    # Internet address : 132.206.175.95\n    # local address    : 192.168.254.254\n    def __init__(self, address=\"192.168.254.254\", **kwargs):\n        super().__init__(address, **kwargs)\n", "meta": {"hexsha": "aaf16fd63b944383f892a02ec921995b61ea211c", "size": 8465, "ext": "py", "lang": "Python", "max_stars_repo_path": "uedinst/delay_stage.py", "max_stars_repo_name": "LaurentRDC/uedinst", "max_stars_repo_head_hexsha": "b6ab38c32e1889209a95be60fd7177b3f9e9200e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "uedinst/delay_stage.py", "max_issues_repo_name": "LaurentRDC/uedinst", "max_issues_repo_head_hexsha": "b6ab38c32e1889209a95be60fd7177b3f9e9200e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-02T20:51:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T20:51:32.000Z", "max_forks_repo_path": "uedinst/delay_stage.py", "max_forks_repo_name": "LaurentRDC/uedinst", "max_forks_repo_head_hexsha": "b6ab38c32e1889209a95be60fd7177b3f9e9200e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-11-05T20:30:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:44:41.000Z", "avg_line_length": 31.7041198502, "max_line_length": 87, "alphanum_fraction": 0.6261075015, "include": true, "reason": "from scipy", "num_tokens": 1910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.18063511429348433}}
{"text": "from typing import Tuple, List, Dict, Any\nfrom enum import Enum\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python import pywrap_tensorflow\nfrom tensorflow import Tensor\nfrom copy import copy\n\nfrom decompose.distributions.distribution import DrawType, UpdateType\nfrom decompose.distributions.distribution import Distribution\nfrom decompose.distributions.uniform import Uniform\nfrom decompose.distributions.nnUniform import NnUniform\nfrom decompose.likelihoods.likelihood import Likelihood\nfrom decompose.likelihoods.specificNormal2dLikelihood import SpecificNormal2dLikelihood\nfrom decompose.likelihoods.allSpecificNormal2dLikelihood import AllSpecificNormal2dLikelihood\nfrom decompose.likelihoods.normal2dLikelihood import Normal2dLikelihood\nfrom decompose.likelihoods.normalNdLikelihood import NormalNdLikelihood\nfrom decompose.likelihoods.cvNormal2dLikelihood import CVNormal2dLikelihood\nfrom decompose.likelihoods.cvNormalNdLikelihood import CVNormalNdLikelihood\nfrom decompose.postU.postU import PostU\nfrom decompose.stopCriterions.llhImprovementThreshold import LlhImprovementThreshold\nfrom decompose.stopCriterions.llhStall import LlhStall\nfrom decompose.cv.cv import CV\n\n\nEstimatorSpec = tf.estimator.EstimatorSpec\n\n\nclass NoiseUniformity(Enum):\n    HOMOGENEOUS = 0\n    HETEROGENEOUS = 1\n    LAST_FACTOR_HETEROGENOUS = 2\n\n\nHOMOGENEOUS = NoiseUniformity.HOMOGENEOUS\nHETEROGENEOUS = NoiseUniformity.HETEROGENEOUS\nLAST_FACTOR_HETEROGENOUS = NoiseUniformity.LAST_FACTOR_HETEROGENOUS\n\n\nclass parameterProperty(object):\n    \"\"\"Decorator for descriptors that update tf variables during set.\n\n    This decorator is the same as the python property decorator except\n    that its setter method accepts a name which can updates a\n    tensorflow variable depending on\n    \"\"\"\n\n    def __init__(self, fget=None, fset=None, fdel=None, doc=None, name=None):\n        self.name = name\n        self.fget = fget\n        self.fset = fset\n        self.fdel = fdel\n        if doc is None and fget is not None:\n            doc = fget.__doc__\n        self.__doc__ = doc\n\n    def __set__(self, obj, values):\n        if self.fset is None:\n            raise AttributeError(\"can't set attribute\")\n        newValues = []\n        for f, value in enumerate(values):\n            if obj.transform and (f == 0):\n                name = f\"{f}tr\"\n            else:\n                name = f\"{f}\"\n            with tf.variable_scope(\"U\", reuse=tf.AUTO_REUSE):\n                var = tf.get_variable(name, dtype=obj.dtype)\n            value = tf.assign(var, value)\n            newValues.append(value)\n        value = tuple(newValues)\n        self.fset(obj, value)\n\n    def __get__(self, obj, objtype=None):\n        if obj is None:\n            return self\n        if self.fget is None:\n            raise AttributeError(\"unreadable attribute\")\n        return self.fget(obj)\n\n    def __delete__(self, obj):\n        if self.fdel is None:\n            raise AttributeError(\"can't delete attribute\")\n        self.fdel(obj)\n\n    def getter(self, fget):\n        return type(self)(fget, self.fset, self.fdel, self.__doc__, self.name)\n\n    def setter(self, name):\n        if name is None:\n            return type(self)(self.fget, None, self.fdel, self.__doc__, None)\n        if type(name) is not str:\n            raise ValueError(\"setter takes a name argument as a string\")\n\n        def noop(fset):\n            return type(self)(self.fget, fset, self.fdel, self.__doc__, name)\n        return(noop)\n\n    def deleter(self, fdel):\n        return type(self)(self.fget, self.fset, fdel, self.__doc__, self.name)\n\n\nclass Phase(Enum):\n    INIT = 1\n    EM = 2\n    BCD = 3\n\n\nclass TensorFactorisation(object):\n\n    def __init__(self,\n                 U: List[Tensor],\n                 priorU: List[Distribution],\n                 likelihood: Likelihood,\n                 dtype: tf.DType,\n                 stopCriterion,\n                 phase: Phase,\n                 noiseUniformity: NoiseUniformity,\n                 transform: bool = False) -> None:\n\n        # setup the model\n        self.dtype = dtype\n        self.__transform = transform\n        self.__noiseUniformity = noiseUniformity\n        self.likelihood = likelihood\n        self.stopCriterion = stopCriterion\n        self.postU = []  # type: List[PostU]\n        for f, priorUf in enumerate(priorU):\n            postUf = PostU(likelihood, priorUf, f)\n            self.postU.append(postUf)\n\n        # create or reuse the variables for the filter banks\n        for f, Uf in enumerate(copy(U)):\n            if transform and (f == 0):\n                paramName = \"{}tr\".format(f)\n            else:\n                paramName = \"{}\".format(f)\n            with tf.variable_scope(\"U\", reuse=tf.AUTO_REUSE):\n                UfVar = tf.get_variable(paramName,\n                                        dtype=dtype,\n                                        initializer=Uf)\n            U[f] = UfVar\n        self.__U = tuple(U)\n        if phase == Phase.EM or phase == Phase.INIT:\n            self.__setEm()\n        elif phase == Phase.BCD:\n            self.__setBcd()\n        else:\n            raise ValueError\n\n    @classmethod\n    def random(cls,\n               priorU: List[Distribution],\n               likelihood: Likelihood,\n               M: Tuple[int, ...],\n               K: int,\n               dtype: tf.DType,\n               phase: Phase,\n               stopCriterion,\n               noiseUniformity: NoiseUniformity = HOMOGENEOUS,\n               transform: bool = False) -> \"TensorFactorisation\":\n\n        # initialize U\n        dtype = tf.as_dtype(dtype)\n        zero = tf.constant(0., dtype=dtype)\n        one = tf.constant(1., dtype=dtype)\n        normal = tf.distributions.Normal(loc=zero, scale=one)\n        F = len(M)\n        U = []\n        for f in range(F):\n            if priorU[f].nonNegative:\n                UfInit = tf.abs(normal.sample(sample_shape=(K, M[f])))\n            else:\n                UfInit = normal.sample(sample_shape=(K, M[f]))\n            U.append(UfInit)\n\n        # instantiate\n        tefa = TensorFactorisation(U=U,\n                                   priorU=priorU,\n                                   likelihood=likelihood,\n                                   dtype=dtype,\n                                   phase=phase,\n                                   transform=transform,\n                                   noiseUniformity=noiseUniformity,\n                                   stopCriterion=stopCriterion)\n        return(tefa)\n\n    @property\n    def transform(self) -> bool:\n        return(self.__transform)\n\n    @property\n    def noiseUniformity(self) -> NoiseUniformity:\n        return(self.__noiseUniformity)\n\n    @parameterProperty\n    def U(self) -> Tuple[tf.Tensor, ...]:\n        return(self.__U)\n\n    @U.setter(name=\"U\")\n    def U(self, U: Tuple[tf.Tensor, ...]):\n        self.__U = U\n\n    def update(self, X: Tensor) -> Tuple[Tensor, ...]:\n        # update stopping criterion\n        stopCritDeps = self.stopCriterion.update(self, X)\n\n        # perform updated depending on this is train of transformation\n        with tf.control_dependencies(stopCritDeps):\n            if self.transform:\n                self.updateTransform(X)\n            else:\n                self.updateTrain(X)\n\n        # return the updated tensors\n        return(self.U)\n\n    def updateTrain(self, X: Tensor) -> None:\n        # store filterbanks in a list\n        U = list(self.U)  # type: List[Tensor]\n\n        # update the parameters of the likelihood\n        self.likelihood.update(U=U, X=X)\n\n        # update the filters in reversed order\n        for f, postUf in reversed(list(enumerate(self.postU))):\n            U = self.rescale(U=U, fNonUnit=f)\n            U[f] = postUf.update(U=U, X=X, transform=False)\n\n        # update the filter banks\n        self.U = tuple(U)\n\n    def updateTransform(self, X: Tensor) -> None:\n        # store filterbanks in a list\n        U = list(self.U)  # type: List[Tensor]\n\n        # calculate updates of the first filterbank\n        U[0] = self.postU[0].update(U=U, X=X, transform=True)\n\n        # update the filter banks\n        self.U = tuple(U)\n\n    def rescale(self, U: List[Tensor], fNonUnit: int) -> List[Tensor]:\n        \"\"\"Puts all variance in the factor `fUpdate`-th factor.\n\n        The method assumes that the norm of all filters is larger than 0.\"\"\"\n        F = len(U)\n\n        # calculathe the scale for each source\n        scaleOfSources = tf.ones_like(U[0][..., 0])\n        for f in range(F):\n            scaleOfSources = scaleOfSources*tf.norm(U[f], axis=-1)\n\n        for f in range(F):\n            # determine rescaling constant depending on the factor number\n            Uf = U[f]\n            normUf = tf.norm(Uf, axis=-1)\n            if f == fNonUnit:\n                # put all variance in the filters of the fUpdate-th factor\n                rescaleConstant = scaleOfSources/normUf\n            else:\n                # normalize the filters all other factors\n                rescaleConstant = 1./normUf\n\n            # rescaled filters\n            Uf = Uf*rescaleConstant[..., None]\n            U[f] = Uf\n\n        return(U)\n\n    def __setEm(self) -> None:\n        \"\"\"Set prior and noise distributions to perform EM updates.\"\"\"\n        for postUf in self.postU:\n            postUf.prior.drawType = DrawType.SAMPLE\n            postUf.prior.updateType = UpdateType.ALL\n        self.likelihood.noiseDistribution.drawType = DrawType.SAMPLE\n        self.likelihood.noiseDistribution.updateType = UpdateType.ALL\n\n    def __setBcd(self) -> None:\n        \"\"\"Set prior and noise distributions to perform BCD updates.\"\"\"\n        for postUf in self.postU:\n            postUf.prior.drawType = DrawType.MODE\n            postUf.prior.updateType = UpdateType.ONLYLATENTS\n        self.likelihood.noiseDistribution.drawType = DrawType.MODE\n        self.likelihood.noiseDistribution.updateType = UpdateType.ONLYLATENTS\n\n    def loss(self, X: Tensor) -> Tensor:\n        \"\"\"Loss of the data `X` given the parameters.\"\"\"\n        loss = self.likelihood.loss(self.U, X)\n        loss = tf.cast(loss, tf.float64)\n        return(loss)\n\n    def llh(self, X: Tensor) -> Tensor:\n        \"\"\"Log likelihood of the parameters given data `X`.\"\"\"\n\n        # log likelihood of the noise\n        llh = self.likelihood.llh(self.U, X)\n\n        # log likelihood of the factors\n        U = list(self.U)\n        for f, postUf in enumerate(self.postU):\n            U = self.rescale(U=U, fNonUnit=f)\n            UfT = tf.transpose(U[f])\n            llhUf = tf.reduce_sum(postUf.prior.llh(UfT))\n            llh = llh + llhUf\n        llh = tf.cast(llh, tf.float64)\n        return(llh)\n\n    def llhIndividual(self, X: Tensor) -> Tensor:\n        \"\"\"Log likelihood of the parameters given data `X`.\"\"\"\n\n        # log likelihood of the noise\n        llhRes = self.likelihood.llh(self.U, X)\n        llh = llhRes\n\n        # log likelihood of the factors\n        llhU = []\n        llhUfk = []\n        U = list(self.U)\n        for f, postUf in enumerate(self.postU):\n            U = self.rescale(U=U, fNonUnit=f)\n            UfT = tf.transpose(U[f])\n            llhUfk.append(tf.reduce_sum(postUf.prior.llh(UfT), axis=0))\n            llhUf = tf.reduce_sum(postUf.prior.llh(UfT))\n            llh = llh + llhUf\n            llhU.append(llhUf)\n        llh = tf.cast(llh, tf.float64)\n        return(llh, llhRes, llhU, llhUfk)\n\n    @staticmethod\n    def type():\n        return(TensorFactorisation)\n\n    def id(self) -> str:\n        \"\"\"Generate a string representation of the model configuration\"\"\"\n        strId = \"\"\n        for f, postUf in enumerate(self.postU):\n            strId += \"U{}\".format(f) + postUf.prior.id()\n        strId += \"_\" + self.likelihood.id\n        return(strId)\n\n    @classmethod\n    def __model(cls, data: Tensor, priorTypes: List[Distribution],\n                M: Tuple[int, ...],\n                K: int, stopCriterion, phase: Phase, dtype: tf.DType,\n                reuse=False,\n                isFullyObserved: bool = True,\n                cv: CV = None,\n                transform: bool = False,\n                noiseUniformity: NoiseUniformity = HOMOGENEOUS,\n                suffix: str = \"\") -> \"TensorFactorisation\":\n        varscope = \"stopCriterion\" + phase.name\n        stopCriterion.init(ns=varscope)\n        F = len(priorTypes)\n\n        # selecting the apropriate likelihood\n        useNormal2dLikelihood = (\n            F == 2\n            and cv is None\n            and isFullyObserved\n            and (noiseUniformity == HOMOGENEOUS\n                 or phase == Phase.INIT))\n        useAllSpecificNormal2dLikelihood = (\n            F == 2\n            and cv is None\n            and isFullyObserved\n            and noiseUniformity == HETEROGENEOUS\n            and phase != Phase.INIT)\n        useSpecificNormal2dLikelihood = (\n            F == 2\n            and cv is None\n            and isFullyObserved\n            and noiseUniformity == LAST_FACTOR_HETEROGENOUS\n            and phase != Phase.INIT)\n        useCVNormal2dLikelihood = (\n            F == 2\n            and (cv is not None\n                 or not isFullyObserved)\n            and noiseUniformity == HOMOGENEOUS)\n        useNormalNdLikelihood = (\n            F > 2\n            and cv is None\n            and isFullyObserved\n            and noiseUniformity == HOMOGENEOUS)\n        useCVNormalNdLikelihood = (\n            F > 2\n            and (cv is not None\n                 or not isFullyObserved)\n            and noiseUniformity == HOMOGENEOUS)\n\n        # instantiate the likelihood\n        with tf.variable_scope(f\"{suffix}\", reuse=reuse):\n            if useNormal2dLikelihood:\n                likelihood = Normal2dLikelihood(\n                    M=M, K=K, dtype=dtype)  # type: Likelihood\n            elif useAllSpecificNormal2dLikelihood:\n                likelihood = AllSpecificNormal2dLikelihood(\n                    M=M, K=K, dtype=dtype)\n            elif useSpecificNormal2dLikelihood:\n                likelihood = SpecificNormal2dLikelihood(\n                    M=M, K=K, dtype=dtype)\n            elif useCVNormal2dLikelihood:\n                likelihood = CVNormal2dLikelihood(\n                    M=M, K=K, dtype=dtype, cv=cv)\n            elif useNormalNdLikelihood:\n                likelihood = NormalNdLikelihood(\n                    M=M, K=K, dtype=dtype)\n            elif useCVNormalNdLikelihood:\n                likelihood = CVNormalNdLikelihood(\n                    M=M, K=K, dtype=dtype, cv=cv)\n            else:\n                raise NotImplementedError()\n            likelihood.init(data)\n\n            # instantiate the priors\n            priors = []\n            for f, priorType in enumerate(priorTypes):\n                prior = priorType.random(shape=(K,), latentShape=(M[f],),\n                                         name=f\"prior{suffix}{f}\", dtype=dtype)\n                priors.append(prior)\n\n        # instantiate the model\n        tefa = cls.random(priorU=priors, likelihood=likelihood, M=M, K=K,\n                          phase=phase, stopCriterion=stopCriterion,\n                          dtype=dtype, noiseUniformity=noiseUniformity,\n                          transform=transform)\n        return(tefa)\n\n    @classmethod\n    def __estimatorSpec(cls, mode, features, device: str,\n                        isFullyObserved: bool,\n                        priors: List[Distribution],\n                        K: int, stopCriterionInit, stopCriterionEM,\n                        stopCriterionBCD,\n                        cv: CV, path: str,\n                        noiseUniformity: NoiseUniformity,\n                        transform: bool, dtype: tf.DType) -> EstimatorSpec:\n        # PREDICT and EVAL are not supported\n        if mode != tf.estimator.ModeKeys.TRAIN:\n            raise ValueError\n\n        # TRAIN\n        with tf.device(device):\n            # check the input data\n            labels = list(features.keys())\n            assert len(labels) == 1\n            data = features[labels[0]]\n            dataShape = tuple(data.get_shape().as_list())\n            assert len(dataShape) == len(priors)\n\n            # shape of the data\n            M = data.get_shape().as_list()\n\n            # create llh variable\n            inf = np.float64(np.inf)\n            with tf.variable_scope(\"llh\"):\n                llhVar = tf.get_variable(\"llh\", dtype=tf.float64,\n                                         initializer=-inf)\n\n            # create loss variable\n            with tf.variable_scope(\"loss\"):\n                lossVar = tf.get_variable(\"loss\", dtype=tf.float64,\n                                          initializer=inf)\n\n            # create global stopping variable\n            with tf.variable_scope(\"stopCriterion\"):\n                stopVar = tf.get_variable(\"stop\", dtype=tf.bool,\n                                          initializer=False)\n\n            # INIT model\n            initPriors = []  # type: List[Distribution]\n            for prior in priors:\n                if prior.nonNegative:\n                    initPriors.append(NnUniform())\n                else:\n                    initPriors.append(Uniform())\n            tefaInit = cls.__model(data=data, priorTypes=initPriors, K=K, M=M,\n                                   isFullyObserved=isFullyObserved,\n                                   stopCriterion=stopCriterionInit,\n                                   dtype=dtype, reuse=False,\n                                   transform=transform, cv=cv,\n                                   phase=Phase.INIT,\n                                   noiseUniformity=noiseUniformity,\n                                   suffix=\"init\")\n\n            # EM model\n            tefaEM = cls.__model(data=data, priorTypes=priors, K=K, M=M,\n                                 isFullyObserved=isFullyObserved,\n                                 stopCriterion=stopCriterionEM,\n                                 dtype=dtype, phase=Phase.EM,\n                                 transform=transform, cv=cv,\n                                 noiseUniformity=noiseUniformity,\n                                 reuse=tf.AUTO_REUSE)\n\n            # BCD model\n            tefaBCD = cls.__model(data=data, priorTypes=priors, K=K, M=M,\n                                  isFullyObserved=isFullyObserved,\n                                  stopCriterion=stopCriterionBCD,\n                                  dtype=dtype, phase=Phase.BCD,\n                                  transform=transform, cv=cv,\n                                  noiseUniformity=noiseUniformity,\n                                  reuse=tf.AUTO_REUSE)\n\n            # replace nan with zeros\n            data = tf.where(tf.is_nan(data), tf.zeros_like(data), data)\n\n            # conduct an update depending on the current phase\n            stopVarInit = tefaInit.stopCriterion.stopVar\n            stopVarEm = tefaEM.stopCriterion.stopVar\n            loss = tf.cond(tf.logical_not(stopVarInit),\n                           lambda: tefaInit.loss(X=data),\n                           lambda: tf.cond(tf.logical_not(stopVarEm),\n                                           lambda: tefaEM.loss(X=data),\n                                           lambda: tefaBCD.loss(X=data)))\n\n            # conduct an update depending on the current phase\n            deps = tf.cond(tf.logical_not(stopVarInit),\n                           lambda: tefaInit.update(X=data),\n                           lambda: tf.cond(tf.logical_not(stopVarEm),\n                                           lambda: tefaEM.update(X=data),\n                                           lambda: tefaBCD.update(X=data)))\n\n            # update the global stop variable\n            stopVarBcd = tefaBCD.stopCriterion.stopVar\n            stop = tf.logical_and(stopVarInit,\n                                  tf.logical_and(stopVarEm,\n                                                 stopVarBcd))\n            with tf.control_dependencies(deps):\n                updatedStopVar = tf.assign(stopVar, stop)\n\n            # if stopping criterion is reached store the llh\n            updates = tf.cond(stop,\n                              lambda: (tf.assign(llhVar, tefaBCD.llh(data)),\n                                       tf.assign(lossVar, tefaBCD.loss(data))),\n                              lambda: (llhVar, lossVar))\n\n            # increment global step variable\n            with tf.control_dependencies([updatedStopVar, *updates]):\n                step = tf.train.get_or_create_global_step()\n                trainOp = tf.assign(step, step + 1)\n\n            # log summaries\n            tf.summary.scalar(\"loss\", loss)\n            llh = tf.cond(tf.logical_not(stopVarInit),\n                          lambda: tefaInit.llhIndividual(X=data),\n                          lambda: tf.cond(tf.logical_not(stopVarEm),\n                                          lambda: tefaEM.llhIndividual(X=data),\n                                          lambda: tefaBCD.llhIndividual(X=data)))\n            llh, llhRes, llhU, llhUfk = llh\n            tf.summary.scalar(\"llh\", llh)\n            tf.summary.scalar(\"llhResiduals\", llhRes)\n            for f, (llhUf, llhUfk) in enumerate(zip(llhU, llhUfk)):\n                tf.summary.scalar(f\"llhU{f}\", llhUf)\n\n            SAVE_EVERY_N_STEPS = 1  # TODO: make configurable\n            summary_hook = tf.train.SummarySaverHook(\n                SAVE_EVERY_N_STEPS,\n                output_dir=path,\n                summary_op=tf.summary.merge_all())\n\n        return EstimatorSpec(mode, loss=loss, train_op=trainOp,\n                             training_hooks=[summary_hook])\n\n    @classmethod\n    def getEstimator(cls, priors: Tuple[Distribution, ...], K: int,\n                     dtype: tf.DType = tf.float32,\n                     isFullyObserved: bool = True,\n                     noiseUniformity: NoiseUniformity = HOMOGENEOUS,\n                     stopCriterionInit=LlhStall(10),\n                     stopCriterionEM=LlhStall(100),\n                     stopCriterionBCD=LlhImprovementThreshold(1e-2),\n                     path: str = \"/tmp\", device: str = \"/cpu:0\",\n                     cv: CV = None):\n\n        def model_fn(features, labels, mode):\n            es = cls.__estimatorSpec(mode=mode, features=features,\n                                     isFullyObserved=isFullyObserved,\n                                     device=device, priors=priors,\n                                     noiseUniformity=noiseUniformity,\n                                     stopCriterionInit=stopCriterionInit,\n                                     stopCriterionEM=stopCriterionEM,\n                                     stopCriterionBCD=stopCriterionBCD,\n                                     cv=cv, path=path, K=K,\n                                     transform=False, dtype=dtype)\n            return(es)\n\n        est = tf.estimator.Estimator(model_fn=model_fn,\n                                     model_dir=path)\n        return(est)\n\n    @classmethod\n    def getTransformEstimator(cls, priors: Tuple[Distribution, ...], K: int,\n                              chptFile: str, dtype: tf.DType = tf.float32,\n                              noiseUniformity: NoiseUniformity = HOMOGENEOUS,\n                              stopCriterionInit=LlhStall(10),\n                              stopCriterionEM=LlhStall(100),\n                              stopCriterionBCD=LlhImprovementThreshold(1e-2),\n                              path: str = \"/tmp\", device: str = \"/cpu:0\"):\n        # configuring warm start settings\n        reader = pywrap_tensorflow.NewCheckpointReader(chptFile)\n        varList = [v for v in reader.get_variable_to_shape_map().keys()\n                   if (v != \"U/0\" and\n                       v != \"global_step\" and\n                       v != \"stop\" and\n                       not v.startswith(f\"stopCriterion{Phase.INIT.name}/\") and\n                       not v.startswith(f\"stopCriterion{Phase.EM.name}/\") and\n                       not v.startswith(f\"stopCriterion{Phase.BCD.name}/\"))]\n        wsVars = \"|\".join(varList)\n        ws = tf.estimator.WarmStartSettings(ckpt_to_initialize_from=chptFile,\n                                            vars_to_warm_start=wsVars)\n\n        def model_fn(features, labels, mode):\n            es = cls.__estimatorSpec(mode=mode, features=features,\n                                     isFullyObserved=True,\n                                     device=device, priors=priors,\n                                     noiseUniformity=noiseUniformity,\n                                     stopCriterionInit=stopCriterionInit,\n                                     stopCriterionEM=stopCriterionEM,\n                                     stopCriterionBCD=stopCriterionBCD,\n                                     K=K, path=path, cv=None,\n                                     transform=True, dtype=dtype)\n            return(es)\n\n        est = tf.estimator.Estimator(model_fn=model_fn,\n                                     model_dir=path,\n                                     warm_start_from=ws)\n        return(est)\n", "meta": {"hexsha": "6b3e4c13224af23d2e3d4a7d6eb9d7eaa3d6e29b", "size": 24980, "ext": "py", "lang": "Python", "max_stars_repo_path": "decompose/models/tensorFactorisation.py", "max_stars_repo_name": "bethgelab/decompose", "max_stars_repo_head_hexsha": "b6ad3e3d1a2d049f1853cdc309ad042293415ad1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2018-03-27T16:07:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-04T13:25:00.000Z", "max_issues_repo_path": "decompose/models/tensorFactorisation.py", "max_issues_repo_name": "bethgelab/decompose", "max_issues_repo_head_hexsha": "b6ad3e3d1a2d049f1853cdc309ad042293415ad1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-04-10T15:46:20.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-26T20:38:56.000Z", "max_forks_repo_path": "decompose/models/tensorFactorisation.py", "max_forks_repo_name": "bethgelab/decompose", "max_forks_repo_head_hexsha": "b6ad3e3d1a2d049f1853cdc309ad042293415ad1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2018-03-27T20:41:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T08:28:51.000Z", "avg_line_length": 39.8405103668, "max_line_length": 93, "alphanum_fraction": 0.5384707766, "include": true, "reason": "import numpy", "num_tokens": 5436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.1806351142934843}}
{"text": "import os\nfrom json import load\nfrom copy import deepcopy\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import binned_statistic\n\nfrom astropy.io import fits\nimport astropy.units as u\n\n__all__ = ['Planet', 'Filter', 'PhaseCurve']\n\nplanets_path = os.path.join(os.path.dirname(__file__), 'data', 'planets.json')\nfilters_path = os.path.join(os.path.dirname(__file__), 'data', 'filters.json')\npc_path = os.path.join(os.path.dirname(__file__), 'data', 'lightcurves.fits')\n\n\nclass Planet(object):\n    \"\"\"\n    Transiting planet parameters.\n\n    This is meant to be a duck-type drop-in for the ``batman`` package's\n    transiting exoplanet parameters ``TransitParams`` object.\n    \"\"\"\n    with open(planets_path, 'r') as _f:\n        _planets = load(_f)\n\n    def __init__(self, per=None, t0=None, inc=None, rp=None, ecc=None, w=None,\n                 a=None, u=None, fp=None, t_secondary=None, T_s=None, rp_a=None,\n                 limb_dark='quadratic', name=None):\n        \"\"\"\n        Parameters\n        ----------\n        per : float\n            Orbital period [days]\n        t0 : float\n            Mid-transit time\n        inc : float\n            Orbital inclination [deg]\n        rp : float\n            Ratio of planet to star radius\n        ecc : float\n            Eccentricity\n        w : float\n            Argument of periastron [deg]\n        a : float\n            Semimajor axis normalized by the stellar radius\n        u : list\n            (i.e.) Quadratic limb-darkening parameters\n        fp : float\n            Planetary flux out of eclipse\n        t_secondary : float\n            Time of secondary eclipse\n        T_s : float\n            Temperature of the host star [K]\n        rp_a : float\n            Radius of the planet over the semimajor axis\n        limb_dark : str\n            Limb darkening law to use\n        name : str\n            Name metadata for the planet\n        \"\"\"\n        self.per = per\n        self.t0 = t0\n        self.inc = inc\n        self.rp = rp\n        self.ecc = ecc\n        self.w = w\n        self.a = a\n        self.u = u\n        self.limb_dark = limb_dark\n        self.fp = fp\n        self.t_secondary = t_secondary\n        self.T_s = T_s\n        self.rp_a = rp_a\n        self.name = name\n\n    @classmethod\n    def from_name(cls, name):\n        \"\"\"\n        Initialize a Planet instance from the target name.\n\n        There's a small (but growing?) database of planets pre-defined in the\n        ``kelp/data/planets.json`` file. If your favorite planet is missing,\n        pull requests are welcome!\n\n        Parameters\n        ----------\n        name : str (i.e.: \"Kepler-7\" or \"KELT-9\")\n             Name of the planet\n        \"\"\"\n\n        return cls(name=name, **cls._planets[name])\n\n    def eclipse_model(self, xi):\n        r\"\"\"\n        Compute eclipse model at orbital phases ``xi``.\n\n        Parameters\n        ----------\n        xi : `~numpy.ndarray`\n            Orbital phase angle :math:`\\xi`\n\n        Returns\n        -------\n        eclipse : `~numpy.ndarray`\n            Eclipse model normalized such that flux is zero in eclipse.\n        \"\"\"\n        from batman import TransitModel\n\n        xi_over_pi = xi / np.pi\n        eclipse = TransitModel(self, xi_over_pi, transittype='secondary',\n                               exp_time=xi_over_pi[1] - xi_over_pi[0],\n                               supersample_factor=3,\n                               ).light_curve(self)\n        eclipse -= eclipse.min()\n        return eclipse\n\n\nclass Filter(object):\n    \"\"\"\n    Astronomical filter object.\n    \"\"\"\n    with open(filters_path, 'r') as _f:\n        _filters = load(_f)\n\n    def __init__(self, wavelength, transmittance, name=None):\n        \"\"\"\n        Parameters\n        ----------\n        wavelength : `~numpy.ndarray`\n            Wavelength array\n        transmittance : `~numpy.ndarray`\n            Transmittance array\n        \"\"\"\n        self.wavelength = wavelength\n        self.transmittance = transmittance\n        self.name = name\n\n    @classmethod\n    def from_name(cls, name):\n        \"\"\"\n        Initialize a Filter instance from the filter name.\n\n        Parameters\n        ----------\n        name : str\n             Name of the filter. Examples include \"IRAC 1\", \"IRAC 2\", \"Kepler\",\n             \"TESS\", and \"CHEOPS\".\n        \"\"\"\n        return cls(np.array(cls._filters[name]['wavelength']) * u.um,\n                   np.array(cls._filters[name]['transmittance']),\n                   name)\n\n    def plot(self, ax=None, **kwargs):\n        \"\"\"\n        Plot the filter transmittance curve.\n\n        Parameters\n        ----------\n        ax : `~matplotlib.axes.Axes`\n            Matplotlib axis object\n        kwargs : dict\n            Dictionary passed to the `~matplotlib.pyplot.plot` command\n\n        Returns\n        -------\n        ax : `~matplotlib.axes.Axes`\n            Updated axis object\n        \"\"\"\n        if ax is None:\n            ax = plt.gca()\n        ax.set(title=self.name)\n        ax.plot(self.wavelength, self.transmittance, **kwargs)\n\n        return ax\n\n    def bin_down(self, bins=10):\n        \"\"\"\n        Bin down the filter bandpass wavelengths and transmittances (shortcut\n        for faster integration over the bandpass).\n\n        Parameters\n        ----------\n        bins : int\n            Number of bins in the binned transmittance curve.\n        \"\"\"\n        bs = binned_statistic(self.wavelength.value, self.transmittance,\n                              bins=bins, statistic='median')\n        bincenters = 0.5 * (bs.bin_edges[1:] + bs.bin_edges[:-1])\n\n        self.wavelength = bincenters * self.wavelength.unit\n        self.transmittance = bs.statistic\n\n\nclass PhaseCurve(object):\n    \"\"\"\n    Thermal phase curve.\n    \"\"\"\n    fits_file = None\n    available = []\n\n    def __init__(self, xi, flux, name=None, channel=None, year=None,\n                 renormalize=False):\n        \"\"\"\n        Parameters\n        ----------\n        xi : `~numpy.ndarray`\n            Times\n        flux : `~numpy.ndarray`\n            Flux measurements\n        name : str\n            Name of the host star\n        channel : str\n            Name of the Spitzer channel\n        year : int\n            Year of the observations (for disambiguating)\n        renormalize : bool\n            Re-normalize the phase curve such that it is represented as\n            :math:`F_p/F_s`, in units of ppm\n        \"\"\"\n        self.xi = xi[np.argsort(xi)]\n\n        if renormalize:\n            in_eclipse = np.abs(xi) < 0.1\n            flux_in_eclipse = np.nanmedian(flux[in_eclipse])\n            flux = 1e6 * (flux - flux_in_eclipse)\n\n        self.flux = flux[np.argsort(xi)]\n        self.name = name\n        self.channel = channel\n        self.year = year\n\n    @classmethod\n    def from_name(cls, name, channel, year=None):\n        \"\"\"\n        Initialize a Filter instance from the filter name.\n\n        Parameters\n        ----------\n        name : str (i.e.: \"WASP-18\", \"KELT-9\")\n            Name of the host star\n        channel : str (i.e.: \"1\" or \"2\")\n            Name of the filter (IRAC channel number)\n        year : int\n            Year of the observations (when\n            multiple observations are available)\n        \"\"\"\n        if cls.fits_file is None:\n            with fits.open(pc_path) as fitsfile:\n                cls.fits_file = deepcopy(fitsfile)\n            for hdu in cls.fits_file[1:]:\n                cls.available.append(\"{0} (Ch {1}; year {2})\"\n                                     .format(hdu.header['NAME'],\n                                             hdu.header['CHANNEL'],\n                                             hdu.header['YEAR']))\n\n        recarray = None\n        for hdu in cls.fits_file[1:]:\n            if (hdu.header['NAME'] == name and\n                    hdu.header['CHANNEL'] == channel and\n                    hdu.header['YEAR'] == year):\n                recarray = hdu.data\n\n        if recarray is not None:\n            return cls(recarray['xi'], recarray['flux'],\n                       name=name, channel=channel, year=year,\n                       renormalize=False)\n        else:\n            raise KeyError(('Target {1} (Ch {0}, {2}) not ' +\n                            'found in FITS registry, ' +\n                            'which contains: {3}'\n                            ).format(channel, name, year,\n                                     ', '.join(sorted(cls.available))))\n\n    def plot(self, ax=None, mask=None, **kwargs):\n        \"\"\"\n        Plot the phase curve.\n\n        Parameters\n        ----------\n        ax : `~matplotlib.axes.Axes`\n            Matplotlib axis object\n        kwargs : dict\n            Dictionary passed to the `~matplotlib.pyplot.plot` command\n\n        Returns\n        -------\n        ax : `~matplotlib.axes.Axes`\n            Updated axis object\n        \"\"\"\n        if ax is None:\n            ax = plt.gca()\n\n        if mask is None:\n            mask = np.ones_like(self.xi).astype(bool)\n\n        ax.plot(self.xi[mask], self.flux[mask], **kwargs)\n\n        return ax\n\n    def _add_to_fits(self, fitsfile):\n        \"\"\"\n        Add this phase curve to a FITS archive ``fitsfile``.\n\n        Parameters\n        ----------\n        fitsfile : FITS file stream\n            Open FITS file stream\n        \"\"\"\n        ra = np.recarray(len(self.xi), names=[\"xi\", \"flux\"],\n                         formats=['f8', 'f8'])\n        ra['xi'] = self.xi\n        ra['flux'] = self.flux\n        header = fits.Header(dict(YEAR=self.year,\n                                  CHANNEL=self.channel,\n                                  NAME=self.name))\n        fitsfile.append(fits.BinTableHDU(ra, header))\n", "meta": {"hexsha": "f9c10cf99d561b642080c61dfe471c83a9e9d9a6", "size": 9616, "ext": "py", "lang": "Python", "max_stars_repo_path": "kelp/registries.py", "max_stars_repo_name": "KathrynJones1/kelp", "max_stars_repo_head_hexsha": "6c10c70cf1d9c5c59332a44d041d5790ae9b45a8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kelp/registries.py", "max_issues_repo_name": "KathrynJones1/kelp", "max_issues_repo_head_hexsha": "6c10c70cf1d9c5c59332a44d041d5790ae9b45a8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kelp/registries.py", "max_forks_repo_name": "KathrynJones1/kelp", "max_forks_repo_head_hexsha": "6c10c70cf1d9c5c59332a44d041d5790ae9b45a8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.05, "max_line_length": 80, "alphanum_fraction": 0.5185108153, "include": true, "reason": "import numpy,from scipy,import astropy,from astropy", "num_tokens": 2142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.18060761262885988}}
{"text": "r\"\"\"\nHPF Spectrum\n---------------\n\nA container for an HPF spectrum of :math:`M=28` total total orders :math:`m`, each with vectors for wavelength flux and uncertainty, e.g. :math:`F_m(\\lambda)`.  HPF additionally has a sky fiber and optionally a Laser Frequency Comb fiber.  Our experimental API currently ignores the LFC fiber.  The sky fiber can be accessed by passing the `sky=True` kwarg when retrieving the\n\n\nHPFSpectrum\n##############\n\"\"\"\n\nimport warnings\nimport logging\nfrom muler.echelle import EchelleSpectrum, EchelleSpectrumList\nimport numpy as np\nimport astropy\nfrom astropy.io import fits\nfrom astropy import units as u\nfrom astropy.wcs import WCS, FITSFixedWarning\nfrom astropy.nddata import StdDevUncertainty\nfrom scipy.interpolate import InterpolatedUnivariateSpline\nfrom astropy.constants import R_jup, R_sun, G, M_jup, R_earth, c\nfrom astropy.time import Time\nimport copy\n\nlog = logging.getLogger(__name__)\n\nfor category in [\n    astropy.utils.exceptions.AstropyDeprecationWarning,\n    FITSFixedWarning,\n    RuntimeWarning,\n]:\n    warnings.filterwarnings(\"ignore\", category=category)\n\n\n# Convert FITS running index number to echelle order m\ngrating_order_offsets = {\"Goldilocks\": 0, \"HPF\": 0}  # Not implemented yet\n\n\nclass HPFSpectrum(EchelleSpectrum):\n    r\"\"\"\n    A container for HPF spectra\n\n    Args:\n        file (str): A path to a reduced HPF spectrum from Goldilocks *or* the HPF instrument team\n        order (int): which spectral order to read\n        cached_hdus (list) :\n            A pre-loaded HDU to reduce file I/O for multiorder access.\n            If provided, must give both HDUs.  Optional, default is None.\n    \"\"\"\n\n    def __init__(self, *args, file=None, order=19, cached_hdus=None, **kwargs):\n\n        self.site_name = \"mcdonald\"\n        self.ancillary_spectra = [\"sky\", \"lfc\"]\n        self.noisy_edges = (3, 2045)\n        self.instrumental_resolution = 55_000.0\n\n        if file is not None:\n            if \"Goldilocks\" in file:\n                pipeline = \"Goldilocks\"\n            elif \"Slope\" in file:\n                pipeline = \"HPF\"\n            else:\n                raise NameError(\"Cannot identify file as an HPF spectrum\")\n            grating_order = grating_order_offsets[pipeline] + order\n\n            if cached_hdus is not None:\n                hdus = cached_hdus[0]\n            else:\n                hdus = fits.open(str(file))\n            hdr = hdus[0].header\n\n            ## Target Spectrum\n            lamb = hdus[7].data[order].astype(np.float64) * u.AA\n            flux = hdus[1].data[order].astype(np.float64) * u.ct\n            unc = hdus[4].data[order].astype(np.float64) * u.ct\n\n            meta_dict = {\n                \"x_values\": np.arange(0, 2048, 1, dtype=np.int),\n                \"pipeline\": pipeline,\n                \"m\": grating_order,\n                \"header\": hdr,\n            }\n\n            uncertainty = StdDevUncertainty(unc)\n            mask = (\n                np.isnan(flux) | np.isnan(uncertainty.array) | (uncertainty.array <= 0)\n            )\n\n            super().__init__(\n                spectral_axis=lamb,\n                flux=flux,\n                mask=mask,\n                wcs=None,\n                uncertainty=uncertainty,\n                meta=meta_dict,\n                **kwargs,\n            )\n\n            ## Sky Spectrum\n            lamb = hdus[8].data[order].astype(np.float64) * u.AA\n            flux = hdus[2].data[order].astype(np.float64) * u.ct\n            unc = hdus[5].data[order].astype(np.float64) * u.ct\n            uncertainty = StdDevUncertainty(unc)\n            mask = (\n                np.isnan(flux) | np.isnan(uncertainty.array) | (uncertainty.array <= 0)\n            )\n            sky_spectrum = HPFSpectrum(\n                spectral_axis=lamb,\n                flux=flux,\n                mask=mask,\n                wcs=None,\n                uncertainty=uncertainty,\n                meta=meta_dict.copy(),\n                **kwargs,\n            )\n\n            ## LFC Spectrum\n            lamb = hdus[9].data[order].astype(np.float64) * u.AA\n            flux = hdus[3].data[order].astype(np.float64) * u.ct\n            unc = hdus[6].data[order].astype(np.float64) * u.ct\n            uncertainty = StdDevUncertainty(unc)\n            mask = (\n                np.isnan(flux) | np.isnan(uncertainty.array) | (uncertainty.array <= 0)\n            )\n            lfc_spectrum = HPFSpectrum(\n                spectral_axis=lamb,\n                flux=flux,\n                mask=mask,\n                wcs=None,\n                uncertainty=uncertainty,\n                meta=meta_dict.copy(),\n                **kwargs,\n            )\n\n            ## We could optionally enable lfc and sky metadata for these referece spectra\n            ## That's slightly redundant, it enables antipatterns like:\n            # `spectrum.sky.lfc` rather than simply `spectrum.lfc`\n\n            # sky_spectrum.meta[\"lfc\"] = lfc_spectrum\n            # lfc_spectrum.meta[\"sky\"] = sky_spectrum\n\n            sky_spectrum.meta[\"provenance\"] = \"Sky fiber\"\n            lfc_spectrum.meta[\"provenance\"] = \"Laser Frequency Comb\"\n            self.meta[\"provenance\"] = \"Target fiber\"\n\n            self.meta[\"sky\"] = sky_spectrum\n            self.meta[\"lfc\"] = lfc_spectrum\n\n        else:\n            super().__init__(*args, **kwargs)\n\n    @property\n    def provenance(self):\n        \"\"\"What is the provenance of each spectrum?\"\"\"\n        return self.meta[\"provenance\"]\n\n    @property\n    def pipeline(self):\n        \"\"\"Which pipeline does this spectrum originate from?\"\"\"\n        return self.meta[\"pipeline\"]\n\n    @property\n    def spectrographname(self):\n        \"\"\"What's the name of the spectrograph?\"\"\"\n        return \"HPF\"\n\n\n    @property\n    def sky(self):\n        \"\"\"Sky fiber spectrum stored as its own HPFSpectrum object\"\"\"\n        return self.meta[\"sky\"]\n\n    @property\n    def lfc(self):\n        \"\"\"Sky fiber spectrum stored as its own HPFSpectrum object\"\"\"\n        return self.meta[\"lfc\"]\n\n    @property\n    def RA(self):\n        \"\"\"The right ascension from header files\"\"\"\n        return self.meta[\"header\"][\"RA\"] * u.hourangle\n\n    @property\n    def DEC(self):\n        \"\"\"The declination from header files\"\"\"\n        return self.meta[\"header\"][\"DEC\"] * u.deg\n\n    @property\n    def astropy_time(self):\n        \"\"\"The astropy time based on the header\"\"\"\n        mjd = self.meta[\"header\"][\"DATE-OBS\"]\n        return Time(mjd, format=\"isot\", scale=\"utc\")\n\n    def sky_subtract(self):\n        \"\"\"Subtract science spectrum from sky spectrum\n\n        Note: This operation does not wavelength shift or scale the sky spectrum\n\n        Returns\n        -------\n        sky_subtractedSpec : (HPFSpectrum)\n            Sky subtracted Spectrum\n        \"\"\"\n        return self.subtract(self.sky, handle_meta=\"first_found\")\n\n    def blaze_divide_flats(self, flat, order=19):\n        \"\"\"Remove blaze function from spectrum by subtracting by flat spectrum\n\n        Returns\n        -------\n        blaze corrrected spectrum using flat fields : (HPFSpectrum)\n\n        \"\"\"\n        log.warning(\"This method is experimental and subject to change\")\n        new_flux = self.normalize()\n\n        flat_wv = flat[0]\n        flat_flux = flat[1]\n        if len(flat) == 3:\n            flat_err = flat[2]\n\n        master_flat = flat_flux[order] / np.nanmedian(flat_flux[order])\n\n        flat_spline = InterpolatedUnivariateSpline(\n            flat_wv[order], np.nan_to_num(master_flat), k=5\n        )\n        interp_flat = flat_spline(self.wavelength)\n\n        no_flat = new_flux / interp_flat\n\n        return HPFSpectrum(\n            spectral_axis=self.wavelength,\n            flux=no_flat.flux,\n            meta=self.meta,\n            mask=self.mask,\n        )\n\n\nclass HPFSpectrumList(EchelleSpectrumList):\n    r\"\"\"\n    An enhanced container for a list of HPF spectral orders\n\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        self.normalization_order_index = 14\n        super().__init__(*args, **kwargs)\n\n    @staticmethod\n    def read(file, precache_hdus=True):\n        \"\"\"Read in a SpectrumList from a file\n\n        Parameters\n        ----------\n        file : (str)\n            A path to a reduced HPF spectrum from plp\n        \"\"\"\n        assert \".spectra.fits\" in file\n\n        hdus = fits.open(file, memmap=False)\n        cached_hdus = [hdus]\n\n        n_orders, n_pix = hdus[7].data.shape\n\n        list_out = []\n        for i in range(n_orders):\n            spec = HPFSpectrum(file=file, order=i, cached_hdus=cached_hdus)\n            list_out.append(spec)\n        return HPFSpectrumList(list_out)\n\n    # def sky_subtract(self):\n    #     \"\"\"Sky subtract all orders\n    #     \"\"\"\n    #     flux = copy.deepcopy(self.flux)\n    #     sky = copy.deepcopy(self.sky)\n    #     for i in range(len(self)):\n    #         self[i] = flux[i] - sky[i]\n\n    #     return self\n", "meta": {"hexsha": "7fd184833d0e8d1080ac5e2c9f5324a8c1cf74cd", "size": 8824, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/muler/hpf.py", "max_stars_repo_name": "jessicaluna/muler", "max_stars_repo_head_hexsha": "c35906162d4840efa70d52cef023f0e7c886da8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/muler/hpf.py", "max_issues_repo_name": "jessicaluna/muler", "max_issues_repo_head_hexsha": "c35906162d4840efa70d52cef023f0e7c886da8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/muler/hpf.py", "max_forks_repo_name": "jessicaluna/muler", "max_forks_repo_head_hexsha": "c35906162d4840efa70d52cef023f0e7c886da8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2907801418, "max_line_length": 376, "alphanum_fraction": 0.5759292838, "include": true, "reason": "import numpy,from scipy,import astropy,from astropy", "num_tokens": 2097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.18060760520844887}}
{"text": "from __future__ import division\n\nimport numpy as np\nfrom utils import msqrt, check_type, round_array, float_dtypes, integer_dtypes, bool_dtypes, safe_len, find_generations, logp_of_set, symmetrize\nfrom numpy import ones, zeros, log, shape, cov, ndarray, inner, reshape, sqrt, any, array, all, abs, exp, where, isscalar, iterable, multiply, transpose, tri\nfrom numpy.linalg.linalg import LinAlgError\nfrom numpy.linalg import pinv, cholesky\nfrom numpy.random import randint, random\nfrom numpy.random import normal as rnormal\nfrom numpy.random import poisson as rpoisson\nfrom PyMCObjects import Stochastic, Potential, Deterministic\nfrom Container import Container\nfrom Node import ZeroProbability, Node, Variable, StochasticBase\nfrom pymc.decorators import prop\nimport distributions\nfrom copy import copy\nfrom InstantiationDecorators import deterministic\nimport pdb, warnings, sys\nimport inspect\n\n__docformat__='reStructuredText'\n\n\n# Changeset history\n# 22/03/2007 -DH- Added a _state attribute containing the name of the attributes that make up the state of the step method, and a method to return that state in a dict. Added an id.\n# TODO: Test cases for binary and discrete Metropolises.\n\nconjugate_Gibbs_competence = 0\nnonconjugate_Gibbs_competence = 0\n\nclass AdaptationError(ValueError): pass\n\n\n__all__=['DiscreteMetropolis', 'Metropolis', 'PDMatrixMetropolis', 'StepMethod', 'assign_method',  'pick_best_methods', 'StepMethodRegistry', 'NoStepper', 'BinaryMetropolis', 'AdaptiveMetropolis','Gibbs','conjugate_Gibbs_competence', 'nonconjugate_Gibbs_competence', 'DrawFromPrior']\n\n\nStepMethodRegistry = []\n\ndef pick_best_methods(stochastic):\n    \"\"\"\n    Picks the StepMethods best suited to handle\n    a stochastic variable.\n    \"\"\"\n\n    # Keep track of most competent methohd\n    max_competence = 0\n    # Empty set of appropriate StepMethods\n    best_candidates = set([])\n\n    # Loop over StepMethodRegistry\n    for method in StepMethodRegistry:\n\n        # Parse method and its associated competence\n        try:\n            competence = method.competence(stochastic)\n        except:\n#             print '\\n\\tWarning, there was an error while step method %s assessed its competence \\n \\\n# \\tto handle stochastic %s. It is being excluded from consideration.\\n' \\\n#                     %(method.__name__, stochastic)\n            competence = 0\n\n        # If better than current best method, promote it\n        if competence > max_competence:\n            best_candidates = set([method])\n            max_competence = competence\n\n        # If same competence, add it to the set of best methods\n        elif competence == max_competence:\n            best_candidates.add(method)\n\n    if max_competence<=0:\n        raise ValueError, 'Maximum competence reported for stochastic %s is <= 0... you may need to write a custom step method class.' % stochastic.__name__\n\n    # print s.__name__ + ': ', best_candidates, ' ', max_competence\n    return best_candidates\n\ndef assign_method(stochastic, scale=None):\n    \"\"\"\n    Returns a step method instance to handle a\n    variable. If several methods have the same competence,\n    it picks one arbitrarily (using set.pop()).\n    \"\"\"\n\n    # Retrieve set of best candidates\n    best_candidates = pick_best_methods(stochastic)\n\n    # Randomly grab and appropriate method\n    method = best_candidates.pop()\n\n    failure_header = \"\"\"Failed attempting to automatically assign step method class %s\nto stochastic variable %s. Try setting %s's competence method to return 0\nand manually assigning it when appropriate. See the user guide.\n\nError message: \"\"\"%(method.__name__, stochastic.__name__, method.__name__)\n\n    try:\n        if scale:\n            out = method(stochastic, scale = scale)\n        else:\n            out = method(stochastic)\n    except:\n        a,b,c = sys.exc_info()\n        raise a, failure_header + b.message, c\n    return out\n\n\n\nclass StepMethodMeta(type):\n    \"\"\"\n    Automatically registers new step methods if they can be automatically assigned:\n    if their init method has one and only one required argument.\n    \"\"\"\n    def __init__(cls, name, bases, dict):\n        type.__init__(cls, name, bases, dict)\n        args, varargs, varkw, defaults = inspect.getargspec(cls.__init__)\n        auto_assignment_OK = False\n        if len(args) == 2:\n            auto_assignment_OK = True\n        elif len(args)>2:\n            if defaults is not None:\n                if len(defaults) == len(args)-2:\n                    auto_assignment_OK = True\n        elif len(args) == 1 and varargs is not None:\n            auto_assignment_OK = True\n\n        if auto_assignment_OK:\n            StepMethodRegistry.append(cls)\n\n\nclass StepMethod(object):\n    \"\"\"\n    This object knows how to make Stochastics take single MCMC steps.\n    Its step() method will be called by Model at every MCMC iteration.\n\n    :Parameters:\n          -variables : list, array or set\n            Collection of PyMCObjects\n\n          - verbose (optional) : integer\n            Level of output verbosity: 0=none, 1=low, 2=medium, 3=high. Setting to none (Default) allows verbosity to be set by sampler.\n\n    Externally-accessible attributes:\n      stochastics:   The Stochastics over which self has jurisdiction which have observed = False.\n      children: The combined children of all Variables over which self has jurisdiction.\n      parents:  The combined parents of all Nodes over which self has jurisdiction, as a set.\n      loglike:  The summed log-probability of self's children conditional on all of self's\n                  Variables' current values. These will be recomputed only as necessary.\n                  This descriptor should eventually be written in C.\n\n    Externally accesible methods:\n      sample(): A single MCMC step for all the Stochastics over which self has\n        jurisdiction. Must be overridden in subclasses.\n      tune(): Tunes proposal distribution widths for all self's Stochastics.\n      competence(s): Examines Stochastic instance s and returns self's\n        competence to handle it, on a scale of 0 to 3.\n\n    To instantiate a StepMethod called S with jurisdiction over a\n    sequence/set N of Nodes:\n\n      >>> S = StepMethod(N)\n\n    :SeeAlso: Metropolis, Sampler.\n    \"\"\"\n\n    __metaclass__ = StepMethodMeta\n\n    def __init__(self, variables, verbose=None, tally=False):\n        # StepMethod initialization\n\n        if not iterable(variables) or isinstance(variables, Node):\n            variables = [variables]\n\n        self.stochastics = set()\n        self.children = set()\n        self.parents = set()\n        self.tally = tally\n\n        self._state = []\n        self._tuning_info = []\n        self.verbose = verbose\n\n        # File away the variables\n        for variable in variables:\n            # Sort.\n\n            if isinstance(variable,Stochastic) and not variable.observed:\n                self.stochastics.add(variable)\n\n        if len(self.stochastics)==0:\n            raise ValueError, 'No stochastics provided.'\n\n        # Find children, no need to find parents; each variable takes care of those.\n        for variable in variables:\n            self.children |= variable.children\n            for parent in variable.parents.itervalues():\n                if isinstance(parent, Variable):\n                    self.parents.add(parent)\n\n        self.children = set([])\n        self.parents = set([])\n        for s in self.stochastics:\n            self.children |= s.extended_children\n            self.parents |= s.extended_parents\n\n        # Remove own stochastics from children and parents.\n        self.children -= self.stochastics\n        self.parents -= self.stochastics\n\n        # self.markov_blanket is a list, because we want self.stochastics to have the chance to\n        # raise ZeroProbability exceptions before self.children.\n        self.markov_blanket = list(self.stochastics)+list(self.children)\n\n        # ID string for verbose feedback\n        self._id = self.__class__.__name__ + '_' + '_'.join([s.__name__ for s in self.stochastics])\n\n    def step(self):\n        \"\"\"\n        Specifies single step of step method.\n        Must be overridden in subclasses.\n        \"\"\"\n        pass\n\n    @staticmethod\n    def competence(s):\n        \"\"\"\n        This function is used by Sampler to determine which step method class\n        should be used to handle stochastic variables.\n\n        Return value should be a competence\n        score from 0 to 3, assigned as follows:\n\n        0:  I can't handle that variable.\n        1:  I can handle that variable, but I'm a generalist and\n            probably shouldn't be your top choice (Metropolis\n            and friends fall into this category).\n        2:  I'm designed for this type of situation, but I could be\n            more specialized.\n        3:  I was made for this situation, let me handle the variable.\n\n        In order to be eligible for inclusion in the registry, a sampling\n        method's init method must work with just a single argument, a\n        Stochastic object.\n\n        If you want to exclude a particular step method from\n        consideration for handling a variable, do this:\n\n        Competence functions MUST be called 'competence' and be decorated by the\n        '@staticmethod' decorator. Example:\n\n            @staticmethod\n            def competence(s):\n                if isinstance(s, MyStochasticSubclass):\n                    return 2\n                else:\n                    return 0\n\n        :SeeAlso: pick_best_methods, assign_method\n        \"\"\"\n        return 0\n\n\n    def tune(self, *args, **kwargs):\n        return False\n\n    def _get_loglike(self):\n        # Fetch log-probability (as sum of childrens' log probability)\n        sum = logp_of_set(self.children)\n        if self.verbose>1:\n            print '\\t' + self._id + ' Current log-likelihood ', sum\n        return sum\n\n    # Make get property for retrieving log-probability\n    loglike = property(fget = _get_loglike, doc=\"The summed log-probability of all stochastic variables that depend on \\n self.stochastics, with self.stochastics removed.\")\n\n    def _get_logp_plus_loglike(self):\n        sum = logp_of_set(self.markov_blanket)\n        if self.verbose>1:\n            print '\\t' + self._id + ' Current log-likelihood plus current log-probability', sum\n        return sum\n\n    # Make get property for retrieving log-probability\n    logp_plus_loglike = property(fget = _get_logp_plus_loglike, doc=\"The summed log-probability of all stochastic variables that depend on \\n self.stochastics, and self.stochastics.\")\n\n    def current_state(self):\n        \"\"\"Return a dictionary with the current value of the variables defining\n        the state of the step method.\"\"\"\n        state = {}\n        for s in self._state:\n            state[s] = getattr(self, s)\n        return state\n\n\n    @prop\n    def ratio():\n        \"\"\"Acceptance ratio\"\"\"\n        def fget(self):\n            return self.accepted/(self.accepted + self.rejected)\n        return locals()\n\nclass NoStepper(StepMethod):\n    \"\"\"\n    Step and tune methods do nothing.\n\n    Useful for holding stochastics constant without setting observed=True.\n    \"\"\"\n    def step(self):\n        pass\n    def tune(self, *args, **kwargs):\n        pass\n\n# The default StepMethod, which Model uses to handle singleton stochastics.\nclass Metropolis(StepMethod):\n    \"\"\"\n    The default StepMethod, which Model uses to handle singleton, continuous variables.\n\n    Applies the one-at-a-time Metropolis-Hastings algorithm to the Stochastic over which self has jurisdiction.\n\n    To instantiate a Metropolis called M with jurisdiction over a Stochastic P:\n\n      >>> M = Metropolis(P, scale=1, proposal_sd=None, dist=None)\n\n    :Arguments:\n    - s : Stochastic\n            The variable over which self has jurisdiction.\n\n    - scale (optional) : number\n            The proposal jump width is set to scale * variable.value.\n\n    - proposal_sd (optional) : number or vector\n            The proposal jump width is set to proposal_sd.\n\n    - proposal_distribution (optional) : string\n            The proposal distribution. May be 'Normal', 'RoundedNormal', 'Bernoulli',\n            'Prior' or None. If None is provided, a proposal distribution is chosen\n            by examining P.value's type.\n\n    - verbose (optional) : None or integer\n            Level of output verbosity: 0=none, 1=low, 2=medium, 3=high. Setting to none allows verbosity to be turned on by sampler.\n\n    :SeeAlso: StepMethod, Sampler.\n    \"\"\"\n\n    def __init__(self, stochastic, scale=1., proposal_sd=None, proposal_distribution=None, verbose=None, tally=True):\n        # Metropolis class initialization\n\n        # Initialize superclass\n        StepMethod.__init__(self, [stochastic], tally=tally)\n\n        # Initialize hidden attributes\n        self.adaptive_scale_factor = 1.\n        self.accepted = 0.\n        self.rejected = 0.\n        self._state = ['rejected', 'accepted', 'adaptive_scale_factor', 'proposal_sd', 'proposal_distribution']\n        self._tuning_info = ['adaptive_scale_factor']\n\n        # Set public attributes\n        self.stochastic = stochastic\n        if verbose is not None:\n            self.verbose = verbose\n        else:\n            self.verbose = stochastic.verbose\n\n        # Avoid zeros when setting proposal variance\n        if proposal_sd is not None:\n            self.proposal_sd = proposal_sd\n        else:\n            if all(self.stochastic.value != 0.):\n                self.proposal_sd = ones(shape(self.stochastic.value)) * abs(self.stochastic.value) * scale\n            else:\n                self.proposal_sd = ones(shape(self.stochastic.value)) * scale\n\n        # Initialize proposal deviate with array of zeros\n        self.proposal_deviate = zeros(shape(self.stochastic.value), dtype=float)\n\n        # Determine size of stochastic\n        if isinstance(self.stochastic.value, ndarray):\n            self._len = len(self.stochastic.value.ravel())\n        else:\n            self._len = 1\n\n        # If no dist argument is provided, assign a proposal distribution automatically.\n        if not proposal_distribution:\n\n            # Pick Gaussian by default\n            self.proposal_distribution = \"Normal\"\n\n        else:\n            self.proposal_distribution = proposal_distribution\n\n    @staticmethod\n    def competence(s):\n        \"\"\"\n        The competence function for Metropolis\n        \"\"\"\n        if s.dtype is None:\n            return .5\n\n        if not s.dtype in float_dtypes:\n            # If the stochastic's binary or discrete, I can't do it.\n            return 0\n        else:\n            return 1\n\n    def hastings_factor(self):\n        \"\"\"\n        If this is a Metropolis-Hastings method (proposal is not symmetric random walk),\n        this method should return log(back_proposal) - log(forward_proposal).\n        \"\"\"\n        return 0.\n\n    def step(self):\n        \"\"\"\n        The default step method applies if the variable is floating-point\n        valued, and is not being proposed from its prior.\n        \"\"\"\n\n        # Probability and likelihood for s's current value:\n\n        if self.verbose>1:\n            print\n            print self._id + ' getting initial logp.'\n\n        if self.proposal_distribution == \"Prior\":\n            logp = self.loglike\n        else:\n            logp = self.logp_plus_loglike\n\n        if self.verbose>1:\n            print self._id + ' proposing.'\n\n        # Sample a candidate value\n        self.propose()\n\n        # Probability and likelihood for s's proposed value:\n        try:\n            if self.proposal_distribution == \"Prior\":\n                logp_p = self.loglike\n                # Check for weirdness before accepting jump\n                self.stochastic.logp\n            else:\n                logp_p = self.logp_plus_loglike\n\n        except ZeroProbability:\n\n            # Reject proposal\n            if self.verbose>1:\n                print self._id + ' rejecting due to ZeroProbability.'\n            self.reject()\n\n            # Increment rejected count\n            self.rejected += 1\n\n            if self.verbose>1:\n                print self._id + ' returning.'\n            return\n\n        if self.verbose>1:\n            print 'logp_p - logp: ', logp_p - logp\n\n        HF = self.hastings_factor()\n\n        # Evaluate acceptance ratio\n        if log(random()) > logp_p - logp + HF:\n\n            # Revert s if fail\n            self.reject()\n\n            # Increment rejected count\n            self.rejected += 1\n            if self.verbose > 1:\n                print self._id + ' rejecting'\n        else:\n            # Increment accepted count\n            self.accepted += 1\n            if self.verbose > 1:\n                print self._id + ' accepting'\n\n        if self.verbose > 1:\n            print self._id + ' returning.'\n\n    def tune(self, *args, **kwargs):\n        if self.proposal_distribution == \"Prior\":\n            return False\n        else:\n            return StepMethod.tune(self, *args, **kwargs)\n\n    def reject(self):\n        # Sets current s value to the last accepted value\n        # self.stochastic.value = self.stochastic.last_value\n        self.stochastic.revert()\n\n    def propose(self):\n        \"\"\"\n        This method is called by step() to generate proposed values\n        if self.proposal_distribution is \"Normal\" (i.e. no proposal specified).\n        \"\"\"\n        if self.proposal_distribution == \"Normal\":\n            self.stochastic.value = rnormal(self.stochastic.value, self.adaptive_scale_factor * self.proposal_sd)\n        elif self.proposal_distribution == \"Prior\":\n            self.stochastic.random()\n\n    def tune(self, divergence_threshold=1e10, verbose=0):\n        \"\"\"\n        Tunes the scaling parameter for the proposal distribution\n        according to the acceptance rate of the last k proposals:\n\n        Rate    Variance adaptation\n        ----    -------------------\n        <0.001        x 0.1\n        <0.05         x 0.5\n        <0.2          x 0.9\n        >0.5          x 1.1\n        >0.75         x 2\n        >0.95         x 10\n\n        This method is called exclusively during the burn-in period of the\n        sampling algorithm.\n\n        May be overridden in subclasses.\n        \"\"\"\n\n        if self.verbose is not None:\n            verbose = self.verbose\n\n        if self.verbose is not None:\n            verbose = self.verbose\n\n        # Verbose feedback\n        if verbose > 0:\n            print '\\t%s tuning:' % self._id\n\n        # Flag for tuning state\n        tuning = True\n\n        # Calculate recent acceptance rate\n        if not (self.accepted + self.rejected): return tuning\n        acc_rate = self.accepted / (self.accepted + self.rejected)\n\n\n        # Switch statement\n        if acc_rate<0.001:\n            # reduce by 90 percent\n            self.adaptive_scale_factor *= 0.1\n        elif acc_rate<0.05:\n            # reduce by 50 percent\n            self.adaptive_scale_factor *= 0.5\n        elif acc_rate<0.2:\n            # reduce by ten percent\n            self.adaptive_scale_factor *= 0.9\n        elif acc_rate>0.95:\n            # increase by factor of ten\n            self.adaptive_scale_factor *= 10.0\n        elif acc_rate>0.75:\n            # increase by double\n            self.adaptive_scale_factor *= 2.0\n        elif acc_rate>0.5:\n            # increase by ten percent\n            self.adaptive_scale_factor *= 1.1\n        else:\n            tuning = False\n\n        # Re-initialize rejection count\n        self.rejected = 0.\n        self.accepted = 0.\n\n        # More verbose feedback, if requested\n        if verbose > 0:\n            if hasattr(self, 'stochastic'):\n                print '\\t\\tvalue:', self.stochastic.value\n            print '\\t\\tacceptance rate:', acc_rate\n            print '\\t\\tadaptive scale factor:', self.adaptive_scale_factor\n            print\n\n        return tuning\n\nclass PDMatrixMetropolis(Metropolis):\n    \"\"\"Metropolis sampler with proposals customised for symmetric positive definite matrices\"\"\"\n    def __init__(self, stochastic, scale=1., proposal_sd=None, verbose=None, tally=True):\n        Metropolis.__init__(self, stochastic, scale=scale, proposal_sd=proposal_sd, proposal_distribution=\"Normal\", verbose=verbose, tally=tally)\n\n    @staticmethod\n    def competence(s):\n        \"\"\"\n        The competence function for MatrixMetropolis\n        \"\"\"\n        # MatrixMetropolis handles the Wishart family, which are valued as\n        # _symmetric_ matrices.\n        if any([isinstance(s,cls) for cls in [distributions.Wishart,distributions.InverseWishart,distributions.WishartCov]]):\n            return 2\n        else:\n            return 0\n\n    def propose(self):\n        \"\"\"\n        Proposals for positive definite matrix using random walk deviations on the Cholesky\n        factor of the current value.\n        \"\"\"\n\n        # Locally store size of matrix\n        dims = self.stochastic.value.shape\n\n        # Add normal deviate to value and symmetrize\n        dev =  rnormal(0, self.adaptive_scale_factor * self.proposal_sd, size=dims)\n        symmetrize(dev)\n\n        # Replace\n        self.stochastic.value = dev + self.stochastic.value\n\n\nclass Gibbs(Metropolis):\n    \"\"\"\n    Base class for the Gibbs step methods\n    \"\"\"\n    def __init__(self, stochastic, verbose=None):\n        Metropolis.__init__(self, stochastic, verbose=verbose, tally=False)\n\n    # Override Metropolis's competence.\n    competence = classmethod(StepMethod.competence)\n\n    def step(self):\n        if not self.conjugate:\n            logp = self.stochastic.logp\n\n        self.propose()\n\n        if not self.conjugate:\n\n            try:\n                logp_p = self.stochastic.logp\n            except ZeroProbability:\n                self.reject()\n\n            if log(np.random.random()) > logp_p - logp:\n                self.reject()\n\n    def tune(self, *args, **kwargs):\n        return False\n\n    def propose(self):\n        raise NotImplementedError, 'The Gibbs class has to be subclassed, it is not usable directly.'\n\n\nclass DrawFromPrior(StepMethod):\n    \"\"\"\n    Handles dataless submodels.\n    \"\"\"\n    def __init__(self, variables, generations, verbose=None):\n        StepMethod.__init__(self, variables, verbose, tally=False)\n        self.generations = generations\n\n        # Some variables (eg GP) may not have logp attributes, so don't try to\n        # evaluate their logps.\n        self.variables_with_logp = set([])\n        for s in self.markov_blanket:\n            try:\n                s.logp\n                self.variables_with_logp.add(s)\n            except:\n                pass\n    \n    def get_logp_plus_loglike(self):\n        return logp_of_set(self.variables_with_logp)\n    logp_plus_loglike = property(get_logp_plus_loglike)\n\n    def step(self):\n        jumped = []\n        try:\n            for generation in self.generations:\n                for s in generation:\n                    s.rand()\n                    jumped.append(s)\n            self.logp_plus_loglike\n        except ZeroProbability:\n            if self.verbose > 0:\n                forbidden = []\n                for generation in self.generations:\n                    for s in self.stochastics:\n                        try:\n                            s.logp\n                        except ZeroProbability:\n                            forbidden.append(s.__name__)\n                print 'DrawFromPrior jumped stochastics %s to value forbidden by objects %s, rejecting.'%(', '.join(s.__name__ for s in jumped),', '.join(forbidden))\n            warnings.warn('DrawFromPrior jumped to forbidden value')\n            for s in jumped:\n                s.revert()\n\n    @classmethod\n    def competence(s):\n        # Dataless gets assigned specially before other step methods.\n        return 0\n\n\nclass NoStepper(StepMethod):\n    \"\"\"\n    Step and tune methods do nothing.\n\n    Useful for holding stochastics constant without setting observed=True.\n    \"\"\"\n    def step(self, *args, **kwargs):\n        pass\n    def tune(self, *args, **kwargs):\n        return False\n\nclass DiscreteMetropolis(Metropolis):\n    \"\"\"\n    Just like Metropolis, but rounds the variable's value.\n    Good for discrete stochastics.\n    \"\"\"\n    def __init__(self, stochastic, scale=1., proposal_sd=None, proposal_distribution=\"Poisson\", positive=False, verbose=None, tally=True):\n        # DiscreteMetropolis class initialization\n\n        # Initialize superclass\n        Metropolis.__init__(self, stochastic, scale=scale, proposal_sd=proposal_sd, proposal_distribution=proposal_distribution, verbose=verbose, tally=tally)\n\n        # Flag for positive-only values\n        self._positive = positive\n\n    @staticmethod\n    def competence(stochastic):\n        \"\"\"\n        The competence function for DiscreteMetropolis.\n        \"\"\"\n        if stochastic.dtype in integer_dtypes:\n            return 1\n        else:\n            return 0\n\n\n    def propose(self):\n        # Propose new values using normal distribution\n\n        if self.proposal_distribution == \"Normal\":\n\n            # New normal deviate, centred on current value\n            new_val = rnormal(self.stochastic.value, self.adaptive_scale_factor * self.proposal_sd)\n\n            # Round before setting proposed value\n            self.stochastic.value = round_array(new_val)\n\n        elif self.proposal_distribution == \"Poisson\":\n\n            k = shape(self.stochastic.value)\n            # Add or subtract (equal probability) Poisson sample\n            new_val = self.stochastic.value + rpoisson(self.adaptive_scale_factor * self.proposal_sd) * (-ones(k))**(random(k)>0.5)\n\n            if self._positive:\n                # Enforce positive values\n                self.stochastic.value = abs(new_val)\n            else:\n                self.stochastic.value = new_val\n\n        elif self.proposal_distribution == \"Prior\":\n            self.stochastic.random()\n\n\n\nclass BinaryMetropolis(Metropolis):\n    \"\"\"\n    Like Metropolis, but with a modified step() method.\n    Good for binary variables.\n\n    \"\"\"\n\n    def __init__(self, stochastic, p_jump=.1, proposal_distribution=None, verbose=None, tally=True):\n        # BinaryMetropolis class initialization\n\n        # Initialize superclass\n        Metropolis.__init__(self, stochastic, proposal_distribution=proposal_distribution, verbose=verbose, tally=tally)\n\n        self._state.remove('proposal_sd')\n\n        # adaptive_scale_factor controls the jump probability\n        self.adaptive_scale_factor = log(1.-p_jump) / log(.5)\n\n    @staticmethod\n    def competence(stochastic):\n        \"\"\"\n        The competence function for Binary One-At-A-Time Metropolis\n        \"\"\"\n        if stochastic.dtype in bool_dtypes:\n            return 1\n        else:\n            return 0\n\n    def step(self):\n        if not isscalar(self.stochastic.value):\n            Metropolis.step(self)\n        else:\n\n            # See what log-probability of True is.\n            self.stochastic.value = True\n\n            try:\n                logp_true = self.logp_plus_loglike\n            except ZeroProbability:\n                self.stochastic.value = False\n                return\n\n            # See what log-probability of False is.\n            self.stochastic.value = False\n\n            try:\n                logp_false = self.logp_plus_loglike\n            except ZeroProbability:\n                self.stochastic.value = True\n                return\n\n            # Test\n            p_true = exp(logp_true)\n            p_false = exp(logp_false)\n\n            if self.verbose>1:\n                print \"\"\"%s step information:\n    - logp_true: %f\n    - logp_false: %f\n    - p_true: %f\n    - p_false: %f\n                \"\"\" % (self._id, logp_true, logp_false, p_true, p_false)\n\n            # Stochastically set value according to relative\n            # probabilities of True and False\n            if random() > p_false / (p_true + p_false):\n                if self.verbose > 1:\n                    print \"%s setting %s's value to True.\" % (self._id, self.stochastic)\n                self.stochastic.value = True\n            elif self.verbose > 1:\n                print \"%s setting %s's value to False.\" % (self._id, self.stochastic)\n\n\n    def propose(self):\n        # Propose new values\n\n        if self.proposal_distribution == 'Prior':\n            self.stochastic.random()\n        else:\n            # Convert adaptive_scale_factor to a jump probability\n            p_jump = 1.-.5**self.adaptive_scale_factor\n\n            rand_array = random(size=shape(self.stochastic.value))\n            new_value = copy(self.stochastic.value)\n            switch_locs = where(rand_array<p_jump)\n            new_value[switch_locs] = True - new_value[switch_locs]\n            # print switch_locs, rand_array, new_value, self.stochastic.value\n            self.stochastic.value = new_value\n\n\nclass AdaptiveMetropolis(StepMethod):\n    \"\"\"\n    The AdaptativeMetropolis (AM) sampling algorithm works like a regular\n    Metropolis, with the exception that stochastic parameters are block-updated\n    using a multivariate jump distribution whose covariance is tuned during\n    sampling. Although the chain is non-Markovian, i.e. the proposal\n    distribution is asymmetric, it has correct ergodic properties. See\n    (Haario et al., 2001) for details.\n\n    :Parameters:\n      - stochastic : PyMC objects\n          Stochastic objects to be handled by the AM algorith,\n\n      - cov : array\n          Initial guess for the covariance matrix C. If it is None, the \n          covariance will be estimated using the scales dictionary if provided, \n          the existing trace if available, or the current stochastics value. \n          It is suggested to provide a sensible guess for the covariance, and \n          not rely on the automatic assignment from stochastics value. \n\n      - delay : int\n          Number of steps before the empirical covariance is computed. If greedy\n          is True, the algorithm waits for delay *accepted* steps before computing\n          the covariance.\n\n      - interval : int\n          Interval between covariance updates. Higher dimensional spaces require \n          more samples to obtain reliable estimates for the covariance updates. \n\n      - greedy : bool\n          If True, only the accepted jumps are tallied in the internal trace\n          until delay is reached. This is useful to make sure that the empirical\n          covariance has a sensible structure.\n\n      - shrink_if_necessary : bool\n          If True, the acceptance rate is checked when the step method tunes. If\n          the acceptance rate is small, the proposal covariance is shrunk according\n          to the following rule:\n\n          if acc_rate < .001:\n              self.C *= .01\n          elif acc_rate < .01:\n              self.C *= .25\n              \n      - scales : dict\n          Dictionary containing the scale for each stochastic keyed by name.\n          If cov is None, those scales are used to define an initial covariance\n          matrix. If neither cov nor scale is given, the initial covariance is\n          guessed from the trace (it if exists) or the objects value, alt\n          \n      - verbose : int\n          Controls the verbosity level.\n\n\n    :Notes:\n    Use the methods: `cov_from_scales`, `cov_from_trace` and `cov_from_values` for\n    more control on the creation of an initial covariance matrix. A lot of problems\n    can be avoided with a good initial covariance and long enough intervals between\n    covariance updates. That is, do not compensate for a bad covariance guess by \n    reducing the interval between updates thinking the covariance matrix will\n    converge more rapidly. \n    \n\n    :Reference:\n      Haario, H., E. Saksman and J. Tamminen, An adaptive Metropolis algorithm,\n          Bernouilli, vol. 7 (2), pp. 223-242, 2001.\n    \"\"\"\n    def __init__(self, stochastic, cov=None, delay=1000, interval=200, greedy=True, shrink_if_necessary=False, scales=None, verbose=None, tally=False):\n\n        # Verbosity flag\n        self.verbose = verbose\n\n        self.accepted = 0\n        self.rejected = 0\n\n        if not np.iterable(stochastic) or isinstance(stochastic, Variable):\n            stochastic = [stochastic]\n\n        # Initialize superclass\n        StepMethod.__init__(self, stochastic, verbose, tally)\n\n        self._id = 'AdaptiveMetropolis_'+'_'.join([p.__name__ for p in self.stochastics])\n        # State variables used to restore the state in a latter session.\n        self._state += ['accepted', 'rejected', '_trace_count', '_current_iter', 'C', 'proposal_sd',\n        '_proposal_deviate', '_trace', 'shrink_if_necessary']\n        self._tuning_info = ['C']\n\n        self.proposal_sd = None\n        self.shrink_if_necessary=shrink_if_necessary\n\n        # Number of successful steps before the empirical covariance is computed\n        self.delay = delay\n        # Interval between covariance updates\n        self.interval = interval\n        # Flag for tallying only accepted jumps until delay reached\n        self.greedy = greedy\n\n        # Initialization methods\n        self.check_type()\n        self.dimension()\n        \n        # Set the initial covariance using cov, or the following fallback mechanisms:\n        # 1. If scales is provided, use it. \n        # 2. If a trace is present, compute the covariance matrix empirically from it. \n        # 3. Use the stochastics value as a guess of the variance. \n        if cov is not None:\n            self.C = cov\n        elif scales:\n            self.C = self.cov_from_scales(scales)\n        else:\n            try:\n                self.C = self.cov_from_trace()\n            except AttributeError:\n                self.C = self.cov_from_value(100.)\n    \n        self.updateproposal_sd()\n\n        # Keep track of the internal trace length\n        # It may be different from the iteration count since greedy\n        # sampling can be done during warm-up period.\n        self._trace_count = 0\n        self._current_iter = 0\n\n        self._proposal_deviate = np.zeros(self.dim)\n        self.chain_mean = np.asmatrix(np.zeros(self.dim))\n        self._trace = []\n\n        if self.verbose >= 1:\n            print \"Initialization...\"\n            print 'Dimension: ', self.dim\n            print \"C_0: \", self.C\n            print \"Sigma: \", self.proposal_sd\n\n\n    @staticmethod\n    def competence(stochastic):\n        \"\"\"\n        The competence function for AdaptiveMetropolis.\n        The AM algorithm is well suited to deal with multivariate\n        parameters.\n        \"\"\"\n        if not stochastic.dtype in float_dtypes and not stochastic.dtype in integer_dtypes:\n            return 0\n            # Algorithm is not well-suited to sparse datasets. Dont use if less than\n            # 25 percent of values are nonzero\n        if np.alen(stochastic.value) == 1:\n            return 0\n        elif np.alen(stochastic.value) < 5:\n            return 2\n        elif (len(stochastic.value.nonzero()[0]) > 0.25*len(stochastic.value)):\n            return 2\n        else:\n            return 0\n\n                \n    def cov_from_value(self, scaling):\n        \"\"\"Return a covariance matrix for the jump distribution using \n        the actual value of the stochastic as a guess of their variance, \n        divided by the `scaling` argument. \n        \n        Note that this is likely to return a poor guess. \n        \"\"\"\n        rv = []\n        for s in self.stochastics:\n            rv.extend(np.ravel(s.value).copy())\n        \n        # Remove 0 values since this would lead to quite small jumps... \n        arv = np.array(rv)\n        arv[arv==0] = 1.\n\n        # Create a diagonal covariance matrix using the scaling factor.\n        return np.eye(self.dim)*np.abs(arv)/scaling\n\n\n    def cov_from_scales(self, scales):\n        \"\"\"Return a covariance matrix built from a dictionary of scales.\n        \n        `scales` is a dictionary keyed by stochastic instances, and the \n        values refer are the variance of the jump distribution for each \n        stochastic. If a stochastic is a sequence, the variance must\n        have the same length. \n        \"\"\"\n       \n        # Get array of scales\n        ord_sc = []\n        for stochastic in self.stochastics:\n            ord_sc.append(np.ravel(scales[stochastic]))\n        ord_sc = np.concatenate(ord_sc)\n\n        if np.squeeze(ord_sc).shape[0] != self.dim:\n            raise \"Improper initial scales, dimension don't match\", \\\n                (np.squeeze(ord_sc), self.dim)\n        \n        # Scale identity matrix\n        return np.eye(self.dim)*ord_sc\n\n    def cov_from_trace(self, trace=slice(None)):\n        \"\"\"Define the jump distribution covariance matrix from the object's \n        stored trace.\n        \n        :Parameters:\n        - `trace` : slice or int\n          A slice for the stochastic object's trace in the last chain, or a \n          an integer indicating the how many of the last samples will be used.\n          \n        \"\"\"\n        n = []\n        for s in self.stochastics:\n            n.append(s.trace.length())\n        n = set(n)\n        if len(n) > 1:\n            raise ValueError, 'Traces do not have the same length.'\n        elif n == 0:\n            raise AttributeError, 'Stochastic has no trace to compute covariance.'\n        else:\n            n = n.pop()\n            \n        if type(trace) is not slice:\n            trace = slice(trace, n)\n            \n        a = self.trace2array(trace)\n        return np.cov(a, rowvar=0)\n\n    def check_type(self):\n        \"\"\"Make sure each stochastic has a correct type, and identify discrete stochastics.\"\"\"\n        self.isdiscrete = {}\n        for stochastic in self.stochastics:\n            if stochastic.dtype in integer_dtypes:\n                self.isdiscrete[stochastic] = True\n            elif stochastic.dtype in bool_dtypes:\n                raise 'Binary stochastics not supported by AdaptativeMetropolis.'\n            else:\n                self.isdiscrete[stochastic] = False\n\n\n    def dimension(self):\n        \"\"\"Compute the dimension of the sampling space and identify the slices\n        belonging to each stochastic.\n        \"\"\"\n        self.dim = 0\n        self._slices = {}\n        for stochastic in self.stochastics:\n            if isinstance(stochastic.value, np.matrix):\n                p_len = len(stochastic.value.A.ravel())\n            elif isinstance(stochastic.value, np.ndarray):\n                p_len = len(stochastic.value.ravel())\n            else:\n                p_len = 1\n            self._slices[stochastic] = slice(self.dim, self.dim + p_len)\n            self.dim += p_len\n\n\n    def update_cov(self):\n        \"\"\"Recursively compute the covariance matrix for the multivariate normal\n        proposal distribution.\n\n        This method is called every self.interval once self.delay iterations\n        have been performed.\n        \"\"\"\n\n        scaling = (2.4)**2/self.dim # Gelman et al. 1996.\n        epsilon = 1.0e-5\n        chain = np.asarray(self._trace)\n\n        # Recursively compute the chain mean\n        self.C, self.chain_mean = self.recursive_cov(self.C, self._trace_count,\n            self.chain_mean, chain, scaling=scaling, epsilon=epsilon)\n\n        # Shrink covariance if acceptance rate is too small\n        acc_rate = self.accepted / (self.accepted + self.rejected)\n        if self.shrink_if_necessary:\n            if acc_rate < .001:\n                self.C *= .01\n            elif acc_rate < .01:\n                self.C *= .25\n            if self.verbose > 0:\n                if acc_rate < .01:\n                    print '\\tAcceptance rate was',acc_rate,'shrinking covariance'\n        self.accepted = 0.\n        self.rejected = 0.\n\n        if self.verbose > 0:\n            print \"\\tUpdating covariance ...\\n\", self.C\n            print \"\\tUpdating mean ... \", self.chain_mean\n\n        # Update state\n        adjustmentwarning = '\\n'+\\\n        'Covariance was not positive definite and proposal_sd cannot be computed by \\n'+ \\\n        'Cholesky decomposition. The next jumps will be based on the last \\n' + \\\n        'valid covariance matrix. This situation may have arisen because no \\n' + \\\n        'jumps were accepted during the last `interval`. One solution is to \\n' + \\\n        'increase the interval, or specify an initial covariance matrix with \\n' + \\\n        'a smaller variance. For this simulation, each time a similar error \\n' + \\\n        'occurs, proposal_sd will be reduced by a factor .9 to reduce the \\n' + \\\n        'jumps and increase the likelihood of accepted jumps.'\n\n        try:\n            self.updateproposal_sd()\n        except np.linalg.LinAlgError:\n            warnings.warn(adjustmentwarning)\n            self.covariance_adjustment(.9)\n\n        self._trace_count += len(self._trace)\n        self._trace = []\n\n    def covariance_adjustment(self, f=.9):\n        \"\"\"Multiply self.proposal_sd by a factor f. This is useful when the current proposal_sd is too large and all jumps are rejected.\n        \"\"\"\n        self.proposal_sd *= f\n\n    def updateproposal_sd(self):\n        \"\"\"Compute the Cholesky decomposition of self.C.\"\"\"\n        self.proposal_sd = np.linalg.cholesky(self.C)\n\n    def recursive_cov(self, cov, length, mean, chain, scaling=1, epsilon=0):\n        r\"\"\"Compute the covariance recursively.\n\n        Return the new covariance and the new mean.\n\n        .. math::\n            C_k & = \\frac{1}{k-1} (\\sum_{i=1}^k x_i x_i^T - k\\bar{x_k}\\bar{x_k}^T)\n            C_n & = \\frac{1}{n-1} (\\sum_{i=1}^k x_i x_i^T + \\sum_{i=k+1}^n x_i x_i^T - n\\bar{x_n}\\bar{x_n}^T)\n                & = \\frac{1}{n-1} ((k-1)C_k + k\\bar{x_k}\\bar{x_k}^T + \\sum_{i=k+1}^n x_i x_i^T - n\\bar{x_n}\\bar{x_n}^T)\n\n        :Parameters:\n            -  cov : matrix\n                Previous covariance matrix.\n            -  length : int\n                Length of chain used to compute the previous covariance.\n            -  mean : array\n                Previous mean.\n            -  chain : array\n                Sample used to update covariance.\n            -  scaling : float\n                Scaling parameter\n            -  epsilon : float\n                Set to a small value to avoid singular matrices.\n        \"\"\"\n        n = length + len(chain)\n        k = length\n        new_mean = self.recursive_mean(mean, length, chain)\n\n        t0 = k * np.outer(mean, mean)\n        t1 = np.dot(chain.T, chain)\n        t2 = n*np.outer(new_mean, new_mean)\n        t3 = epsilon * np.eye(cov.shape[0])\n\n        new_cov =  (k-1)/(n-1.)*cov + scaling/(n-1.) * (t0 + t1 - t2 + t3)\n        return new_cov, new_mean\n\n    def recursive_mean(self, mean, length, chain):\n        r\"\"\"Compute the chain mean recursively.\n\n        Instead of computing the mean :math:`\\bar{x_n}` of the entire chain,\n        use the last computed mean :math:`bar{x_j}` and the tail of the chain\n        to recursively estimate the mean.\n\n        .. math::\n            \\bar{x_n} & = \\frac{1}{n} \\sum_{i=1}^n x_i\n                      & = \\frac{1}{n} (\\sum_{i=1}^j x_i + \\sum_{i=j+1}^n x_i)\n                      & = \\frac{j\\bar{x_j}}{n} + \\frac{\\sum_{i=j+1}^n x_i}{n}\n\n        :Parameters:\n            -  mean : array\n                Previous mean.\n            -  length : int\n                Length of chain used to compute the previous mean.\n            -  chain : array\n                Sample used to update mean.\n        \"\"\"\n        n = length + len(chain)\n        return length * mean / n + chain.sum(0)/n\n\n\n    def propose(self):\n        \"\"\"\n        This method proposes values for stochastics based on the empirical\n        covariance of the values sampled so far.\n\n        The proposal jumps are drawn from a multivariate normal distribution.\n        \"\"\"\n\n        arrayjump = np.dot(self.proposal_sd, np.random.normal(size=self.proposal_sd.shape[0]))\n        if self.verbose > 2:\n            print 'Jump :', arrayjump\n\n        # Update each stochastic individually.\n        for stochastic in self.stochastics:\n            jump = arrayjump[self._slices[stochastic]]\n            if np.iterable(stochastic.value):\n                jump = np.reshape(arrayjump[self._slices[stochastic]],np.shape(stochastic.value))\n            if self.isdiscrete[stochastic]:\n                jump = round_array(jump)\n            stochastic.value = stochastic.value + jump\n\n    def step(self):\n        \"\"\"\n        Perform a Metropolis step.\n\n        Stochastic parameters are block-updated using a multivariate normal\n        distribution whose covariance is updated every self.interval once\n        self.delay steps have been performed.\n\n        The AM instance keeps a local copy of the stochastic parameter's trace.\n        This trace is used to computed the empirical covariance, and is\n        completely independent from the Database backend.\n\n        If self.greedy is True and the number of iterations is smaller than\n        self.delay, only accepted jumps are stored in the internal\n        trace to avoid computing singular covariance matrices.\n        \"\"\"\n\n        # Probability and likelihood for stochastic's current value:\n        logp = self.logp_plus_loglike\n        if self.verbose > 1:\n            print 'Current value: ', self.stoch2array()\n            print 'Current likelihood: ', logp\n\n        # Sample a candidate value\n        self.propose()\n\n        # Metropolis acception/rejection test\n        accept = False\n        try:\n            # Probability and likelihood for stochastic's proposed value:\n            logp_p = self.logp_plus_loglike\n            if self.verbose > 2:\n                print 'Current value: ', self.stoch2array()\n                print 'Current likelihood: ', logp\n\n            if np.log(random()) < logp_p - logp:\n                accept = True\n                self.accepted += 1\n                if self.verbose > 2:\n                    print 'Accepted'\n            else:\n                self.rejected += 1\n                if self.verbose > 2:\n                    print 'Rejected'\n        except ZeroProbability:\n            self.rejected += 1\n            logp_p = None\n            if self.verbose > 2:\n                    print 'Rejected with ZeroProbability Error.'\n\n        if (not self._current_iter % self.interval) and self.verbose > 1:\n            print \"Step \", self._current_iter\n            print \"\\tLogprobability (current, proposed): \", logp, logp_p\n            for stochastic in self.stochastics:\n                print \"\\t\", stochastic.__name__, stochastic.last_value, stochastic.value\n            if accept:\n                print \"\\tAccepted\\t*******\\n\"\n            else:\n                print \"\\tRejected\\n\"\n            print \"\\tAcceptance ratio: \", self.accepted/(self.accepted+self.rejected)\n\n        if self._current_iter == self.delay:\n            self.greedy = False\n\n        if not accept:\n            self.reject()\n\n        if accept or not self.greedy:\n            self.internal_tally()\n\n        if self._current_iter>self.delay and self._current_iter%self.interval==0:\n           self.update_cov()\n\n        self._current_iter += 1\n\n    # Please keep reject() factored out- helps RandomRealizations figure out what to do.\n    def reject(self):\n        for stochastic in self.stochastics:\n            # stochastic.value = stochastic.last_value\n            stochastic.revert()\n\n    def internal_tally(self):\n        \"\"\"Store the trace of stochastics for the computation of the covariance.\n        This trace is completely independent from the backend used by the\n        sampler to store the samples.\"\"\"\n        chain = []\n        for stochastic in self.stochastics:\n            chain.append(np.ravel(stochastic.value))\n        self._trace.append(np.concatenate(chain))\n\n    def trace2array(self, sl):\n        \"\"\"Return an array with the trace of all stochastics, sliced by sl.\"\"\"\n        chain = []\n        for stochastic in self.stochastics:\n            tr = stochastic.trace.gettrace(slicing=sl)\n            chain.append(tr)\n        return np.hstack(chain)\n\n    def stoch2array(self):\n        \"\"\"Return the stochastic objects as an array.\"\"\"\n        a = np.empty(self.dim)\n        for stochastic in self.stochastics:\n            a[self._slices[stochastic]] = stochastic.value\n        return a\n\n\n    def tune(self, verbose=0):\n        \"\"\"Tuning is done during the entire run, independently from the Sampler\n        tuning specifications. \"\"\"\n        return False\n\n\nclass IIDSStepper(StepMethod):\n    \"\"\"\n    See written documentation.\n    \"\"\"\n    pass\n", "meta": {"hexsha": "1c02d2b9725aa1a04423ff3dddefe88f5f4e4132", "size": 48232, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymc/StepMethods.py", "max_stars_repo_name": "matthew-brett/pymc", "max_stars_repo_head_hexsha": "3a31613f056e7993a449d89bafef5fdaa40d47e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-12-03T09:42:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T19:23:29.000Z", "max_issues_repo_path": "pymc/StepMethods.py", "max_issues_repo_name": "matthew-brett/pymc", "max_issues_repo_head_hexsha": "3a31613f056e7993a449d89bafef5fdaa40d47e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-09-27T02:00:41.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-27T02:15:32.000Z", "max_forks_repo_path": "pymc/StepMethods.py", "max_forks_repo_name": "matthew-brett/pymc", "max_forks_repo_head_hexsha": "3a31613f056e7993a449d89bafef5fdaa40d47e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-10-27T13:27:32.000Z", "max_forks_repo_forks_event_max_datetime": "2017-10-27T13:27:32.000Z", "avg_line_length": 35.4908020603, "max_line_length": 283, "alphanum_fraction": 0.6129955216, "include": true, "reason": "import numpy,from numpy", "num_tokens": 10618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.31069437683198775, "lm_q1q2_score": 0.18060760149824345}}
{"text": "\"\"\"\r\n@author:  Yuhao Cheng\r\n@contact: yuhao.cheng[at]outlook.com\r\n\"\"\"\r\n#!!!!! ignore the warning messages\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\nimport os\r\nimport pickle\r\nimport math\r\nimport torch\r\nimport time\r\nimport numpy as np\r\nfrom PIL import Image\r\nfrom collections import OrderedDict\r\nimport torchvision.transforms as T\r\nimport torchvision.transforms.functional as tf\r\nfrom torch.utils.data import DataLoader\r\n\r\nimport logging\r\nlogger = logging.getLogger(__name__)\r\n\r\nfrom pyanomaly.core.utils import AverageMeter, flow_batch_estimate, tensorboard_vis_images, vis_optical_flow, make_info_message, ParamSet\r\nfrom pyanomaly.datatools.evaluate.utils import psnr_error\r\n\r\nfrom pyanomaly.datatools.evaluate.utils import (\r\n    simple_diff, \r\n    find_max_patch, \r\n    amc_score, \r\n    calc_w\r\n    )\r\n\r\nfrom ..abstract.base_engine import BaseTrainer, BaseInference, BaseService\r\n\r\nfrom ..engine_registry import ENGINE_REGISTRY\r\n\r\n__all__ = ['MATrainer', 'AMCInference']\r\n\r\n@ENGINE_REGISTRY.register()\r\nclass MATrainer(BaseTrainer):\r\n    \"\"\"\r\n    G\r\n    D_frame\r\n    D_pattern\r\n    AE_act\r\n    AE_obj\r\n    PatternNet\r\n    \"\"\"\r\n    NAME = [\"MA.TRAIN\"]    \r\n    def custom_setup(self):\r\n        # create loss meters\r\n        self.loss_meter_G = AverageMeter(name='Loss_G')\r\n        self.loss_meter_D = AverageMeter(name='Loss_D')\r\n        \r\n\r\n        self.optical = ParamSet(name='optical', size=self.config.DATASET.optical_size, output_format=self.config.DATASET.optical_format)\r\n        # import ipdb; ipdb.set_trace()\r\n    \r\n    def train(self,current_step):\r\n        # Pytorch [N, C, D, H, W]\r\n        # initialize\r\n        start = time.time()\r\n        self.set_requires_grad(self.F, False)\r\n        self.set_requires_grad(self.D, True)\r\n        self.set_requires_grad(self.G, True)\r\n        self.G.train()\r\n        self.D.train()\r\n        self.F.eval()\r\n        writer = self.kwargs['writer_dict']['writer']\r\n        global_steps = self.kwargs['writer_dict']['global_steps_{}'.format(self.kwargs['model_type'])]\r\n        \r\n        # get the data\r\n        data, anno, meta = next(self._train_loader_iter)\r\n        self.data_time.update(time.time() - start)\r\n        \r\n        # base on the D to get each frame\r\n        # in this method, D = 2 and not change\r\n        input_data = data[:, :, 0, :, :].cuda() # input(1-st) frame\r\n        target = data[:, :, 1,:, :].cuda() # target(2-nd) frame \r\n        \r\n        # True Process =================Start===================\r\n        #---------update optim_G ---------\r\n        self.set_requires_grad(self.D, False)\r\n        output_flow_G,  output_frame_G = self.G(input_data)\r\n        gt_flow_esti_tensor = torch.cat([input_data, target], 1)\r\n        flow_gt_vis, flow_gt  = flow_batch_estimate(self.F, gt_flow_esti_tensor, self.normalize.param['train'],\r\n                                                    optical_size=self.config.DATASET.optical_size, output_format=self.config.DATASET.optical_format)\r\n        fake_g = self.D(torch.cat([target, output_flow_G], dim=1))\r\n\r\n        loss_g_adv = self.GANLoss(fake_g, True)\r\n        loss_op = self.OpticalflowSqrtLoss(output_flow_G, flow_gt)\r\n        loss_int = self.IntentsityLoss(output_frame_G, target)\r\n        loss_gd = self.GradientLoss(output_frame_G, target)\r\n        loss_g_all = self.loss_lamada['IntentsityLoss'] * loss_int + self.loss_lamada['GradientLoss'] * loss_gd + self.loss_lamada['OpticalflowSqrtLoss'] * loss_op + self.loss_lamada['GANLoss'] * loss_g_adv\r\n\r\n        self.optimizer_G.zero_grad()\r\n        loss_g_all.backward()\r\n        self.optimizer_G.step()\r\n        self.loss_meter_G.update(loss_g_all.detach())\r\n        \r\n        if self.config.TRAIN.adversarial.scheduler.use:\r\n            self.optimizer_G_scheduler.step()\r\n\r\n        #---------update optim_D ---------------\r\n        self.set_requires_grad(self.D, True)\r\n        self.optimizer_D.zero_grad()\r\n        # import ipdb; ipdb.set_trace()\r\n        real_d = self.D(torch.cat([target, flow_gt],dim=1))\r\n        fake_d = self.D(torch.cat([target, output_flow_G.detach()], dim=1))\r\n        loss_d_1 = self.GANLoss(real_d, True)\r\n        loss_d_2 = self.GANLoss(fake_d, False)\r\n        loss_d = (loss_d_1  + loss_d_2) * 0.5 \r\n        loss_d.backward()\r\n        self.optimizer_D.step()\r\n        if self.config.TRAIN.adversarial.scheduler.use:\r\n            self.optimizer_D_scheduler.step()\r\n        self.loss_meter_D.update(loss_d.detach())\r\n        # ======================End==================\r\n\r\n        self.batch_time.update(time.time() - start)\r\n\r\n        if (current_step % self.steps.param['log'] == 0):\r\n            msg = make_info_message(current_step, self.steps.param['max'], self.kwargs['model_type'], self.batch_time, \r\n                                    self.config.TRAIN.batch_size, self.data_time, [self.loss_meter_G, self.loss_meter_D])\r\n            logger.info(msg)\r\n        \r\n        writer.add_scalar('Train_loss_G', self.loss_meter_G.val, global_steps)\r\n        writer.add_scalar('Train_loss_D', self.loss_meter_D.val, global_steps)\r\n\r\n        if (current_step % self.steps.param['vis'] == 0):\r\n            temp = vis_optical_flow(output_flow_G.detach(), output_format=self.config.DATASET.optical_format, output_size=(output_flow_G.shape[-2], output_flow_G.shape[-1]), \r\n                                    normalize=self.normalize.param['train'])\r\n            vis_objects = OrderedDict({\r\n                'train_target_flow': flow_gt_vis.detach(),\r\n                'train_output_flow_G': temp, \r\n                'train_target_frame': target.detach(),\r\n                'train_output_frame_G': output_frame_G.detach(),\r\n            })\r\n            tensorboard_vis_images(vis_objects, writer, global_steps, self.normalize.param['train'])\r\n        global_steps += 1 \r\n        \r\n        # reset start\r\n        start = time.time()\r\n        \r\n        # self.saved_model = {'G':self.G, 'D':self.D}\r\n        self.saved_model['G'] = self.G\r\n        self.saved_model['D'] = self.D\r\n        # self.saved_optimizer = {'optim_G': self.optimizer_G, 'optim_D': self.optimizer_D}\r\n        self.saved_optimizer['optimizer_G'] = self.optimizer_G\r\n        self.saved_optimizer['optimizer_D'] = self.optimizer_D\r\n        # self.saved_loss = {'loss_G':self.loss_meter_G.val, 'loss_D':self.loss_meter_D.val}\r\n        self.saved_loss['loss_G'] = self.loss_meter_G.val\r\n        self.saved_loss['loss_D'] = self.loss_meter_D.val\r\n        self.kwargs['writer_dict']['global_steps_{}'.format(self.kwargs['model_type'])] = global_steps\r\n\r\n\r\n@ENGINE_REGISTRY.register()\r\nclass AMCInference(BaseInference):\r\n    NAME = [\"AMC.INFERENCE\"]\r\n\r\n    def inference(self):\r\n        for h in self._hooks:\r\n            h.inference()\r\n\r\n\r\n\r\n@ENGINE_REGISTRY.register()\r\nclass AMCService(BaseService):\r\n    def custom_setup(self):\r\n        self.optical_format = self.config.DATASET.optical_format\r\n        self.optical_szie = self.engine.config.DATASET.optical_size\r\n        self.wf = 1.0\r\n        self.wi = 1.0\r\n        self.threshold = 0.0 # the threshold to judge whether the frame is the anomaly\r\n\r\n    def get_clip_by_stride(self, video, stride=2):\r\n        \"\"\"Get the clip list by the stride\r\n        \"\"\"\r\n        return []\r\n\r\n    def execute(self, data):\r\n        output_dict = OrderedDict()\r\n        # data.shape = [N,C,D,H,W], data is a whole vide, D=the length of the video\r\n        clip_list = self.get_clip_by_stride(data) # the length of the length is the length of the video\r\n        scores = np.empty(shape=(len(clip_list), ), dtype=np.float32)\r\n\r\n        for index, clip in enumerate(clip_list):\r\n            first_frame = clip[:, :, 0, :, :].cuda()\r\n            second_frame = clip[:, :, 1, :, :].cuda()\r\n\r\n            generated_flow, generated_frame = self.G(first_frame)\r\n            gtFlowEstim = torch.cat([first_frame, second_frame], 1)\r\n            _, gtFlow = flow_batch_estimate(self.F, gtFlowEstim, self.normalize.param['val'], output_format=self.optical_format, optical_size=self.optical_size)\r\n\r\n            score, _, _ = amc_score(second_frame, generated_frame, gtFlow, generated_flow, self.wf, self.wi)\r\n            score = score.tolist()\r\n            scores[index] = score\r\n\r\n        result_mask = scores.gt(self.threshold)\r\n        output_dict['result_dict'] = result_mask\r\n        \r\n        return output_dict\r\n    ", "meta": {"hexsha": "2935a7e2d3eb685fb88a69552cc82b8ff14462bd", "size": 8319, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyanomaly/core/engine/functions/ma.py", "max_stars_repo_name": "sourcery-ai-bot/PyAnomaly", "max_stars_repo_head_hexsha": "c92cec86e4d31daabe8b336fa7067e3b0bb7ca89", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyanomaly/core/engine/functions/ma.py", "max_issues_repo_name": "sourcery-ai-bot/PyAnomaly", "max_issues_repo_head_hexsha": "c92cec86e4d31daabe8b336fa7067e3b0bb7ca89", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyanomaly/core/engine/functions/ma.py", "max_forks_repo_name": "sourcery-ai-bot/PyAnomaly", "max_forks_repo_head_hexsha": "c92cec86e4d31daabe8b336fa7067e3b0bb7ca89", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9802955665, "max_line_length": 207, "alphanum_fraction": 0.6209880995, "include": true, "reason": "import numpy", "num_tokens": 1902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.18041657988430193}}
{"text": "from typing import *\n\nimport numpy as np\nimport torch\nfrom scipy import linalg as la\n\nfrom ...settings_ import settings\nfrom ...typing_ import TensorInitArgType\nfrom . import init\nfrom .core import *\nfrom .layers import *\nfrom .linalg import *\nfrom .nn import *\n\n__all__ = [\n    'Flow', 'FeatureMappingFlow',\n    'InverseFlow', 'SequentialFlow',\n    'LooseInvertibleMatrix', 'StrictInvertibleMatrix',\n    'InvertibleDense', 'InvertibleConv1d', 'InvertibleConv2d',\n    'InvertibleConv3d',\n    'Scale', 'SigmoidScale', 'ExpScale', 'LinearScale',\n]\n\n\n# ---- base flow classes ----\nclass BaseValidateTensorLayer(BaseLayer):\n\n    __constants__ = ('_should_validate_tensor', '_validate_tensor_messgae_prefix')\n\n    _should_validate_tensor: bool\n    _validate_tensor_messgae_prefix: str\n\n    def __init__(self):\n        super().__init__()\n        self._should_validate_tensor = bool(settings.validate_tensors)\n        self._validate_tensor_messgae_prefix = self.__class__.__qualname__\n\n    @jit_method\n    def _maybe_assert_finite(self,\n                             t: Tensor,\n                             name: str,\n                             inverse: bool = False) -> Tensor:\n        if self._should_validate_tensor:\n            msg = '{}.{}'.format(self._validate_tensor_messgae_prefix, name)\n            if inverse:\n                msg += ' [inverse]'\n            t = assert_finite(t, msg)\n        return t\n\n\nclass Flow(BaseValidateTensorLayer):\n    \"\"\"\n    Base class for normalizing flows.\n\n    A normalizing flow transforms a random variable `x` into `y` by an\n    (implicitly) invertible mapping :math:`y = f(x)`, whose Jaccobian matrix\n    determinant :math:`\\\\det \\\\frac{\\\\partial f(x)}{\\\\partial x} \\\\neq 0`, thus\n    can derive :math:`\\\\log p(y)` from given :math:`\\\\log p(x)`.\n    \"\"\"\n\n    __constants__ = BaseValidateTensorLayer.__constants__ + (\n        'x_event_ndims', 'y_event_ndims', 'explicitly_invertible'\n    )\n\n    x_event_ndims: int\n    \"\"\"Number of event dimensions in `x`.\"\"\"\n\n    y_event_ndims: int\n    \"\"\"Number of event dimensions in `y`.\"\"\"\n\n    explicitly_invertible: bool\n    \"\"\"\n    Whether or not this flow is explicitly invertible?\n\n    If a flow is not explicitly invertible, then it only supports to\n    transform `x` into `y`, and corresponding :math:`\\\\log p(x)` into\n    :math:`\\\\log p(y)`.  It cannot compute :math:`\\\\log p(y)` directly\n    without knowing `x`, nor can it transform `x` back into `y`.\n    \"\"\"\n\n    def __init__(self,\n                 x_event_ndims: int,\n                 y_event_ndims: int,\n                 explicitly_invertible: bool):\n        super().__init__()\n\n        self.x_event_ndims = int(x_event_ndims)\n        self.y_event_ndims = int(y_event_ndims)\n        self.explicitly_invertible = bool(explicitly_invertible)\n\n    @jit_method\n    def get_x_event_ndims(self) -> int:\n        return self.x_event_ndims\n\n    @jit_method\n    def get_y_event_ndims(self) -> int:\n        return self.y_event_ndims\n\n    @jit_method\n    def is_explicitly_invertible(self) -> bool:\n        return self.explicitly_invertible\n\n    def invert(self) -> 'Flow':\n        \"\"\"\n        Get the inverse flow from this flow.\n\n        Specifying `inverse = True` when calling the inverse flow will be\n        interpreted as having `inverse = False` in the original flow, and\n        vise versa.\n\n        If the current flow requires to be initialized by calling it\n        with `inverse = False`, then the inversed flow will require to be\n        initialized by calling it with `inverse = True`, and vise versa.\n\n        Returns:\n            The inverse flow.\n        \"\"\"\n        return InverseFlow(self)\n\n    def _transform(self,\n                   input: Tensor,\n                   input_log_det: Optional[Tensor],\n                   inverse: bool,\n                   compute_log_det: bool\n                   ) -> Tuple[Tensor, Optional[Tensor]]:\n        raise NotImplementedError()\n\n    def forward(self,\n                input: Tensor,\n                input_log_det: Optional[Tensor] = None,\n                inverse: bool = False,\n                compute_log_det: bool = True\n                ) -> Tuple[Tensor, Optional[Tensor]]:\n        \"\"\"\n        Transform `x` into `y` and compute the log-determinant of `f` at `x`\n        (if `inverse` is False); or transform `y` into `x` and compute the\n        log-determinant of `f^{-1}` at `y` (if `inverse` is True).\n\n        Args:\n            input: `x` (if `inverse` is False) or `y` (if `inverse` is True).\n            input_log_det: The log-determinant of the previous layer.\n                Will add the log-determinant of this layer to `input_log_det`,\n                to obtain the output log-determinant.  If no previous layer,\n                will start from zero log-det.\n            inverse: See above.\n            compute_log_det: Whether or not to compute the log-determinant?\n\n        Returns:\n            The transformed tensor, and the summed log-determinant of\n            the previous flow layer and this layer.\n        \"\"\"\n        if inverse:\n            if not self.explicitly_invertible:\n                raise RuntimeError('Flow is not explicitly invertible.')\n            event_ndims = self.y_event_ndims\n        else:\n            event_ndims = self.x_event_ndims\n\n        if input.dim() < event_ndims:\n            raise ValueError(\n                '`input` is required to be at least {}d, but the input shape '\n                'is {}.'.format(event_ndims, shape(input))\n            )\n\n        input_shape = input.shape\n        log_det_shape = input_shape[: len(input_shape) - event_ndims]\n\n        if input_log_det is not None:\n            if input_log_det.shape != log_det_shape:\n                raise ValueError(\n                    'The shape of `input_log_det` is not expected: '\n                    'expected to be {}, but got {}.'.\n                    format(list(log_det_shape), shape(input_log_det))\n                )\n\n        # compute the transformed output and log-det\n        output, output_log_det = self._transform(\n            input, input_log_det, inverse, compute_log_det)\n\n        if output_log_det is not None:\n            if output_log_det.shape != log_det_shape:\n                output_log_det = output_log_det + torch.zeros(\n                    log_det_shape, dtype=output_log_det.dtype, device=output_log_det.device)\n\n            if output_log_det.shape != log_det_shape:\n                raise ValueError(\n                    'The shape of `output_log_det` is not expected: '\n                    'expected to be {}, but got {}.'.\n                    format(list(log_det_shape), shape(output_log_det))\n                )\n\n        return output, output_log_det\n\n\nclass FeatureMappingFlow(Flow):\n    \"\"\"Base class for flows mapping input features to output features.\"\"\"\n\n    __constants__ = Flow.__constants__ + ('axis',)\n\n    axis: int\n    \"\"\"The feature axis (negative index).\"\"\"\n\n    def __init__(self,\n                 axis: int,\n                 event_ndims: int,\n                 explicitly_invertible: bool):\n        \"\"\"\n        Construct a new :class:`FeatureMappingFlow`.\n\n        Args:\n            axis: The feature axis, on which to apply the transformation.\n                It must be a negative integer, and included in the\n                event dimensions.\n            event_ndims: Number of event dimensions in both `x` and `y`.\n                `x.ndims - event_ndims == log_det.ndims` and\n                `y.ndims - event_ndims == log_det.ndims`.\n            explicitly_invertible: Whether or not this flow is explicitly\n                invertible?\n        \"\"\"\n        # check the arguments\n        axis = int(axis)\n        event_ndims = int(event_ndims)\n\n        if event_ndims < 1:\n            raise ValueError(f'`event_ndims` must be at least 1: '\n                             f'got {event_ndims}')\n\n        if axis >= 0 or axis < -event_ndims:\n            raise ValueError(\n                f'`-event_ndims <= axis < 0` does not hold: '\n                f'`axis` is {axis}, while `event_ndims` is {event_ndims}.')\n\n        # construct the layer\n        super().__init__(x_event_ndims=event_ndims,\n                         y_event_ndims=event_ndims,\n                         explicitly_invertible=explicitly_invertible)\n        self.axis = axis\n\n    @jit_method\n    def get_axis(self) -> int:\n        return self.axis\n\n    @jit_method\n    def get_event_ndims(self) -> int:\n        \"\"\"Get the number of event dimensions in both `x` and `y`.\"\"\"\n        return self.x_event_ndims\n\n\n# ---- composite flows ----\nclass InverseFlow(Flow):\n    \"\"\"A flow that inverts another given flow.\"\"\"\n\n    original_flow: Module\n    \"\"\"The original flow, which is inverted by this :class:`InverseFlow`.\"\"\"\n\n    def __init__(self, flow: Module):\n        if (not isinstance(flow, Flow) and not is_jit_layer(flow)) or \\\n                not flow.is_explicitly_invertible():\n            raise TypeError(\n                f'`flow` must be an explicitly invertible flow: '\n                f'got {flow!r}'\n            )\n\n        super().__init__(\n            x_event_ndims=flow.get_y_event_ndims(),\n            y_event_ndims=flow.get_x_event_ndims(),\n            explicitly_invertible=flow.is_explicitly_invertible(),\n        )\n        self.original_flow = flow\n\n    def invert(self) -> Flow:\n        return self.original_flow\n\n    def _transform(self,\n                   input: Tensor,\n                   input_log_det: Optional[Tensor],\n                   inverse: bool,\n                   compute_log_det: bool) -> Tuple[Tensor, Optional[Tensor]]:\n        return self.original_flow(\n            input, input_log_det, not inverse, compute_log_det)\n\n\nclass _NotInvertibleFlow(Module):\n\n    def forward(self,\n                input: Tensor,\n                input_log_det: Optional[Tensor],\n                inverse: bool,\n                compute_log_det: bool\n                ) -> Tuple[Tensor, Optional[Tensor]]:\n        raise RuntimeError('Not an explicitly invertible flow.')\n\n\nclass SequentialFlow(Flow):\n\n    _chain: ModuleList\n    _inverse_chain: ModuleList\n\n    def custom_compile_children(self):\n        flows = [jit_compile(m) for m in self._chain]\n        self._chain = torch.jit.script(ModuleList(flows))\n        self._inverse_chain = torch.jit.script(ModuleList(flows[::-1]))\n\n    def __init__(self,\n                 *flows: Union[Module, Sequence[Module]]):\n        from tensorkit.layers import flatten_nested_layers\n\n        # validate the arguments\n        flows = flatten_nested_layers(flows)\n        if not flows:\n            raise ValueError('`flows` must not be empty.')\n\n        for i, flow in enumerate(flows):\n            if not isinstance(flow, Flow) and not is_jit_layer(flow):\n                raise TypeError(f'`flows[{i}]` is not a flow: got {flow!r}')\n\n        for i, (flow1, flow2) in enumerate(zip(flows[:-1], flows[1:])):\n            if flow2.get_x_event_ndims() != flow1.get_y_event_ndims():\n                raise ValueError(\n                    f'`x_event_ndims` of `flows[{i + 1}]` != '\n                    f'`y_event_ndims` of `flows[{i}]`: '\n                    f'{flow2.get_x_event_ndims()} vs {flow1.get_y_event_ndims()}.'\n                )\n\n        super().__init__(\n            x_event_ndims=flows[0].get_x_event_ndims(),\n            y_event_ndims=flows[-1].get_y_event_ndims(),\n            explicitly_invertible=all(\n                flow.is_explicitly_invertible() for flow in flows)\n        )\n        self._chain = ModuleList(flows)\n        self._inverse_chain = ModuleList(flows[::-1])\n\n    def _call_chain(self,\n                            output: Tensor,\n                            output_log_det: Optional[Tensor],\n                            compute_log_det: bool\n                            ) -> Tuple[Tensor, Optional[Tensor]]:\n        for flow in self._chain:\n            output, output_log_det = flow(\n                output, output_log_det, False, compute_log_det)\n        return output, output_log_det\n\n    def _call_inverse_chain(self,\n                            output: Tensor,\n                            output_log_det: Optional[Tensor],\n                            compute_log_det: bool\n                            ) -> Tuple[Tensor, Optional[Tensor]]:\n        for flow in self._inverse_chain:\n            output, output_log_det = flow(\n                output, output_log_det, True, compute_log_det)\n        return output, output_log_det\n\n    def _transform(self,\n                   input: Tensor,\n                   input_log_det: Optional[Tensor],\n                   inverse: bool,\n                   compute_log_det: bool\n                   ) -> Tuple[Tensor, Optional[Tensor]]:\n        output, output_log_det = input, input_log_det\n        event_ndims = self.y_event_ndims if inverse else self.x_event_ndims\n\n        if rank(output) > event_ndims + 1:\n            output, batch_shape = flatten_to_ndims(output, event_ndims + 1)\n            if output_log_det is not None:\n                output_log_det = reshape(output_log_det, [-1])\n        else:\n            batch_shape: Optional[List[int]] = None\n\n        if inverse:\n            output, output_log_det = self._call_inverse_chain(\n                output, output_log_det, compute_log_det)\n        else:\n            output, output_log_det = self._call_chain(\n                output, output_log_det, compute_log_det)\n\n        if batch_shape is not None:\n            output = unflatten_from_ndims(output, batch_shape)\n            if output_log_det is not None:\n                output_log_det = reshape(output_log_det, batch_shape)\n\n        return output, output_log_det\n\n\n# ---- invertible linear flows ----\nclass InvertibleMatrix(BaseValidateTensorLayer):\n\n    __constants__ = BaseValidateTensorLayer.__constants__ + (\n        'size', 'validate_tensors'\n    )\n\n    size: int\n\n    validate_tensors: bool\n    \"\"\"Whether or not to perform time-consuming validations on tensors?\"\"\"\n\n    def __init__(self, size: int):\n        super().__init__()\n        self.size = size\n\n        # TODO: make validate_tensors an argument\n        self.validate_tensors = settings.validate_tensors is True\n\n    def __repr__(self):\n        return f'{self.__class__.__qualname__}(size={self.size})'\n\n\nclass LooseInvertibleMatrix(InvertibleMatrix):\n    \"\"\"\n    A matrix initialized to be an invertible, orthogonal matrix.\n\n    There is no guarantee that the matrix will keep invertible during training.\n    But according to the measure theory, the non-invertible n by n real matrices\n    are of measure 0.  Thus this class is generally enough for use.\n    \"\"\"\n\n    def __init__(self,\n                 seed_matrix: np.ndarray,\n                 dtype: str = settings.float_x,\n                 device: Optional[str] = None):\n        \"\"\"\n        Construct a new :class:`LooseInvertibleMatrix`.\n\n        Args:\n            seed_matrix: A matrix that is used as a seed to obtain the\n                initial invertible and orthogonal matrix.\n            dtype: The dtype of the matrix.\n            device: The device where to place new tensors and variables.\n        \"\"\"\n        device = device or current_device()\n        initial_matrix = la.qr(seed_matrix)[0]\n\n        super().__init__(initial_matrix.shape[0])\n        add_parameter(\n            self, 'matrix',\n            from_numpy(initial_matrix, dtype=dtype, device=device)\n        )\n\n    def forward(self,\n                inverse: bool,\n                compute_log_det: bool\n                ) -> Tuple[Tensor, Optional[Tensor]]:\n        log_det: Optional[Tensor] = None\n        if inverse:\n            matrix = self._maybe_assert_finite(\n                matrix_inverse(self.matrix), 'matrix', inverse)\n            if compute_log_det:\n                log_det = self._maybe_assert_finite(\n                    -slogdet(self.matrix)[1], 'log_det', inverse)\n        else:\n            matrix = self._maybe_assert_finite(self.matrix, 'matrix', inverse)\n            if compute_log_det:\n                log_det = self._maybe_assert_finite(\n                    slogdet(self.matrix)[1], 'log_det', inverse)\n\n        return matrix, log_det\n\n\nclass StrictInvertibleMatrix(InvertibleMatrix):\n    \"\"\"\n    A matrix initialized to be an invertible, orthogonal matrix, and is\n    guarnteed to keep invertible during training.\n    \"\"\"\n\n    def __init__(self,\n                 seed_matrix: np.ndarray,\n                 dtype: str = settings.float_x,\n                 device: Optional[str] = None,\n                 epsilon: float = EPSILON):\n        \"\"\"\n        Construct a new :class:`StrictInvertibleMatrix`.\n\n        Args:\n            seed_matrix: A matrix that is used as a seed to obtain the\n                initial invertible and orthogonal matrix.\n            dtype: The dtype of the matrix.\n            device: The device where to place new tensors and variables.\n            epsilon: The infinitesimal constant to avoid dividing by zero or\n                taking logarithm of zero.\n        \"\"\"\n        initial_matrix = la.qr(seed_matrix)[0]\n        device = device or current_device()\n\n        super().__init__(initial_matrix.shape[0])\n        matrix_shape = list(initial_matrix.shape)\n        self.size = matrix_shape[0]\n\n        initial_P, initial_L, initial_U = la.lu(initial_matrix)\n        initial_s = np.diag(initial_U)\n        initial_sign = np.sign(initial_s)\n        initial_log_s = np.log(np.maximum(np.abs(initial_s), epsilon))\n        initial_U = np.triu(initial_U, k=1)\n\n        add_buffer(self, 'P', from_numpy(initial_P, dtype=dtype, device=device))\n        assert_finite(\n            add_parameter(\n                self, 'pre_L', from_numpy(initial_L, dtype=dtype, device=device)),\n            'pre_L',\n        )\n        add_buffer(\n            self, 'L_mask', from_numpy(\n                np.tril(np.ones(matrix_shape), k=-1), dtype=dtype, device=device)\n        )\n        assert_finite(\n            add_parameter(self, 'pre_U', from_numpy(\n                initial_U, dtype=dtype, device=device)),\n            'pre_U',\n        )\n        add_buffer(\n            self, 'U_mask', from_numpy(\n                np.triu(np.ones(matrix_shape), k=1), dtype=dtype, device=device))\n        add_buffer(\n            self, 'sign', from_numpy(initial_sign, dtype=dtype, device=device))\n        assert_finite(\n            add_parameter(self, 'log_s', from_numpy(\n                initial_log_s, dtype=dtype, device=device)),\n            'log_s',\n        )\n\n    def forward(self,\n                inverse: bool,\n                compute_log_det: bool\n                ) -> Tuple[Tensor, Optional[Tensor]]:\n        P = self.P\n        L = (self.L_mask * self.pre_L +\n             torch.eye(self.size, dtype=P.dtype, device=self.P.device))\n        U = self.U_mask * self.pre_U + torch.diag(self.sign * exp(self.log_s))\n\n        log_det: Optional[Tensor] = None\n        if inverse:\n            matrix = matmul(\n                matrix_inverse(U),\n                matmul(matrix_inverse(L), matrix_inverse(P))\n            )\n            matrix = self._maybe_assert_finite(matrix, 'matrix', inverse)\n            if compute_log_det:\n                log_det = self._maybe_assert_finite(\n                    -reduce_sum(self.log_s), 'log_det', inverse)\n        else:\n            matrix = matmul(P, matmul(L, U))\n            matrix = self._maybe_assert_finite(matrix, 'matrix', inverse)\n            if compute_log_det:\n                log_det = self._maybe_assert_finite(\n                    reduce_sum(self.log_s), 'log_det', inverse)\n\n        return matrix, log_det\n\n\nclass InvertibleLinearNd(FeatureMappingFlow):\n    \"\"\"Base class for invertible linear transformation flows.\"\"\"\n\n    __constants__ = FeatureMappingFlow.__constants__ + (\n        'num_features', 'strict', 'epsilon',\n    )\n\n    invertible_matrix: Module\n    num_features: int\n    strict: bool\n    epsilon: float\n\n    def __init__(self,\n                 num_features: int,\n                 strict: bool = False,\n                 weight_init: TensorInitArgType = init.kaming_uniform,\n                 dtype: str = settings.float_x,\n                 device: Optional[str] = None,\n                 epsilon: float = EPSILON):\n        \"\"\"\n        Construct a new linear transformation flow.\n\n        Args:\n            num_features: The number of features to be transformed.\n                The invertible transformation matrix will have the shape\n                ``[num_features, num_features]``.\n            strict: Whether or not to use the strict invertible matrix?\n                Defaults to :obj:`False`.  See :class:`LooseInvertibleMatrix`\n                and :class:`StrictInvertibleMatrix`.\n            weight_init: The weight initializer for the seed matrix.\n            dtype: The dtype of the invertible matrix.\n            device: The device where to place new tensors and variables.\n            epsilon: The infinitesimal constant to avoid having numerical issues.\n        \"\"\"\n        spatial_ndims = self._get_spatial_ndims()\n        device = device or current_device()\n\n        super().__init__(\n            axis=-(spatial_ndims + 1),\n            event_ndims=(spatial_ndims + 1),\n            explicitly_invertible=True,\n        )\n\n        self.num_features = int(num_features)\n        self.strict = bool(strict)\n        self.epsilon = float(epsilon)\n\n        # Using the backend random generator instead of numpy generator\n        # will allow the backend random seed to have effect on the initialization\n        # step of the invertible matrix.\n        seed_matrix = variable(\n            shape=[num_features, num_features], dtype=dtype, device='cpu',\n            initializer=weight_init, requires_grad=False,\n        )\n        seed_matrix = to_numpy(seed_matrix)\n\n        if strict:\n            self.invertible_matrix = StrictInvertibleMatrix(\n                seed_matrix, dtype=dtype, device=device, epsilon=epsilon)\n        else:\n            self.invertible_matrix = LooseInvertibleMatrix(\n                seed_matrix, dtype=dtype, device=device)\n\n    def _get_spatial_ndims(self) -> int:\n        raise NotImplementedError()\n\n    def _affine_transform(self, input: Tensor, weight: Tensor) -> Tensor:\n        raise NotImplementedError()\n\n    @jit_method\n    def _transform(self,\n                   input: Tensor,\n                   input_log_det: Optional[Tensor],\n                   inverse: bool,\n                   compute_log_det: bool\n                   ) -> Tuple[Tensor, Optional[Tensor]]:\n        # obtain the weight\n        weight, log_det = self.invertible_matrix(\n            inverse=inverse, compute_log_det=compute_log_det)\n        spatial_ndims = self.x_event_ndims - 1\n        weight = torch.reshape(weight, weight.shape + (1,) * spatial_ndims)\n\n        # compute the output\n        output = self._affine_transform(input, weight)\n\n        # compute the log_det\n        output_log_det = input_log_det\n        if log_det is not None:\n            log_det = log_det * torch.prod(\n                torch.as_tensor(input.shape[input.dim() - spatial_ndims:],\n                                dtype=log_det.dtype, device=log_det.device))\n            if input_log_det is not None:\n                output_log_det = input_log_det + log_det\n            else:\n                output_log_det = log_det\n\n        return output, output_log_det\n\n\nclass InvertibleDense(InvertibleLinearNd):\n    \"\"\"An invertible linear transformation.\"\"\"\n\n    def _get_spatial_ndims(self) -> int:\n        return 0\n\n    @jit_method\n    def _affine_transform(self, input: Tensor, weight: Tensor) -> Tensor:\n        return torch.nn.functional.linear(input, weight)\n\n\nclass InvertibleConv1d(InvertibleLinearNd):\n    \"\"\"An invertible 1d 1x1 convolutional transformation.\"\"\"\n\n    def _get_spatial_ndims(self) -> int:\n        return 1\n\n    @jit_method\n    def _affine_transform(self, input: Tensor, weight: Tensor) -> Tensor:\n        return torch.nn.functional.conv1d(input, weight)\n\n\nclass InvertibleConv2d(InvertibleLinearNd):\n    \"\"\"An invertible 2d 1x1 convolutional transformation.\"\"\"\n\n    def _get_spatial_ndims(self) -> int:\n        return 2\n\n    @jit_method\n    def _affine_transform(self, input: Tensor, weight: Tensor) -> Tensor:\n        return torch.nn.functional.conv2d(input, weight)\n\n\nclass InvertibleConv3d(InvertibleLinearNd):\n    \"\"\"An invertible 3d 1x1 convolutional transformation.\"\"\"\n\n    def _get_spatial_ndims(self) -> int:\n        return 3\n\n    @jit_method\n    def _affine_transform(self, input: Tensor, weight: Tensor) -> Tensor:\n        return torch.nn.functional.conv3d(input, weight)\n\n\n# ---- scale modules, for transforming input to output by a scale ----\nclass Scale(BaseValidateTensorLayer):\n    \"\"\"Base class for scaling `input`.\"\"\"\n\n    def _scale_and_log_scale(self,\n                             pre_scale: Tensor,\n                             inverse: bool,\n                             compute_log_scale: bool\n                             ) -> Tuple[Tensor, Optional[Tensor]]:\n        raise NotImplementedError()\n\n    def forward(self,\n                input: Tensor,\n                pre_scale: Tensor,\n                event_ndims: int,\n                input_log_det: Optional[Tensor] = None,\n                compute_log_det: bool = True,\n                inverse: bool = False\n                ) -> Tuple[Tensor, Optional[Tensor]]:\n        # validate the argument\n        if input.dim() < event_ndims:\n            raise ValueError(\n                '`rank(input) >= event_ndims` does not hold: the `input` shape '\n                'is {}, while `event_ndims` is {}.'.\n                format(shape(input), event_ndims)\n            )\n        if pre_scale.dim() > input.dim():\n            raise ValueError(\n                '`rank(input) >= rank(pre_scale)` does not hold: the `input` '\n                'shape is {}, while the shape of `pre_scale` is {}.'.\n                format(shape(input), shape(pre_scale))\n            )\n\n        input_shape = input.shape\n        event_ndims_start = len(input_shape) - event_ndims\n        event_shape = input_shape[event_ndims_start:]\n        log_det_shape = input_shape[: event_ndims_start]\n\n        if input_log_det is not None:\n            if input_log_det.shape != log_det_shape:\n                raise ValueError(\n                    'The shape of `input_log_det` is not expected: '\n                    'expected to be {}, but got {}'.\n                    format(list(log_det_shape), shape(input_log_det))\n                )\n\n        scale, log_scale = self._scale_and_log_scale(\n            pre_scale, inverse, compute_log_det)\n\n        if log_scale is not None:\n            # the last `event_ndims` dimensions must match the `event_shape`\n            r = log_scale.dim()\n            if r < event_ndims or log_scale.shape[r - event_ndims:] != event_shape:\n                # Note: equivalent as the following two lines, but compiles much slower\n                #       on PyTorch 1.3.1 with JIT engine.\n                # log_scale = broadcast_to_shape(\n                #     log_scale,\n                #     get_broadcast_shape(shape(log_scale), event_shape)\n                # )\n                log_scale = log_scale + torch.zeros(\n                    event_shape, device=log_scale.device, dtype=log_scale.dtype)\n\n                r = log_scale.dim()\n                if log_scale.shape[r - event_ndims:] != event_shape:\n                    raise ValueError(\n                        'The shape of the final {}d of `log_scale` is not '\n                        'expected: expected to be {}, but got {}.'.\n                        format(event_ndims, event_shape, log_scale.shape[r - event_ndims:])\n                    )\n\n            # reduce the last `event_ndims` of log_scale\n            log_scale = reduce_sum(log_scale, axis=int_range(-event_ndims, 0))\n\n            # now add to input_log_det, or broadcast `log_scale` to `log_det_shape`\n            if input_log_det is not None:\n                output_log_det = input_log_det + log_scale\n            else:\n                output_log_det = log_scale\n                if output_log_det.shape != log_det_shape:\n                    output_log_det = output_log_det + torch.zeros(\n                        log_det_shape, device=output_log_det.device,\n                        dtype=output_log_det.dtype\n                    )\n\n            if output_log_det.shape != log_det_shape:\n                raise ValueError(\n                    'The shape of the computed `output_log_det` is not expected: '\n                    'expected to be {}, but got {}.'.\n                    format(shape(output_log_det), list(log_det_shape))\n                )\n        else:\n            output_log_det = None\n\n        return input * scale, output_log_det\n\n\nclass ExpScale(Scale):\n    \"\"\"\n    Scaling `input` with `exp` activation.\n\n    ::\n\n        if inverse:\n            output = input / exp(pre_scale)\n            output_log_det = -pre_scale\n        else:\n            output = input * exp(pre_scale)\n            output_log_det = pre_scale\n    \"\"\"\n\n    def _scale_and_log_scale(self,\n                             pre_scale: Tensor,\n                             inverse: bool,\n                             compute_log_scale: bool\n                             ) -> Tuple[Tensor, Optional[Tensor]]:\n        log_scale: Optional[Tensor] = None\n\n        the_pre_scale = -pre_scale if inverse else pre_scale\n        scale = self._maybe_assert_finite(exp(the_pre_scale), 'scale', inverse)\n        if compute_log_scale:\n            log_scale = self._maybe_assert_finite(\n                the_pre_scale, 'log_scale', inverse)\n\n        return scale, log_scale\n\n\nclass SigmoidScale(Scale):\n    \"\"\"\n    Scaling `input` with `sigmoid` activation.\n\n    ::\n\n        if inverse:\n            output = input / sigmoid(pre_scale)\n            output_log_det = -log(sigmoid(pre_scale))\n        else:\n            output = input * sigmoid(pre_scale)\n            output_log_det = log(sigmoid(pre_scale))\n    \"\"\"\n\n    __constants__ = Scale.__constants__ + ('pre_scale_bias',)\n\n    pre_scale_bias: float\n\n    def __init__(self, pre_scale_bias: float = 0.):\n        super().__init__()\n        self.pre_scale_bias = pre_scale_bias\n\n    def _scale_and_log_scale(self,\n                             pre_scale: Tensor,\n                             inverse: bool,\n                             compute_log_scale: bool\n                             ) -> Tuple[Tensor, Optional[Tensor]]:\n        if self.pre_scale_bias != 0.:\n            pre_scale = pre_scale + self.pre_scale_bias\n\n        log_scale: Optional[Tensor] = None\n        if inverse:\n            neg_pre_scale = -pre_scale\n            scale = self._maybe_assert_finite(\n                exp(neg_pre_scale) + 1., 'scale', inverse)\n            if compute_log_scale:\n                log_scale = self._maybe_assert_finite(\n                    softplus(neg_pre_scale), 'log_scale', inverse)\n        else:\n            scale = self._maybe_assert_finite(sigmoid(pre_scale), 'scale', inverse)\n            if compute_log_scale:\n                log_scale = self._maybe_assert_finite(\n                    -softplus(-pre_scale), 'log_scale', inverse)\n\n        return scale, log_scale\n\n\nclass LinearScale(Scale):\n    \"\"\"\n    Scaling `input` with `linear` activation.\n\n    ::\n\n        if inverse:\n            output = input / pre_scale\n            output_log_det = -log(abs(pre_scale))\n        else:\n            output = input * pre_scale\n            output_log_det = log(abs(pre_scale))\n    \"\"\"\n\n    __constants__ = Scale.__constants__ + ('epsilon',)\n\n    epsilon: float\n\n    def __init__(self, epsilon: float = EPSILON):\n        super().__init__()\n        self.epsilon = epsilon\n\n    def _scale_and_log_scale(self,\n                             pre_scale: Tensor,\n                             inverse: bool,\n                             compute_log_scale: bool\n                             ) -> Tuple[Tensor, Optional[Tensor]]:\n        log_scale: Optional[Tensor] = None\n        epsilon = float_scalar_like(self.epsilon, pre_scale)\n\n        if inverse:\n            scale = self._maybe_assert_finite(1. / pre_scale, 'scale', inverse)\n            if compute_log_scale:\n                log_scale = self._maybe_assert_finite(\n                    -log(maximum(abs(pre_scale), epsilon)), 'log_scale', inverse)\n        else:\n            scale = self._maybe_assert_finite(pre_scale, 'scale', inverse)\n            if compute_log_scale:\n                log_scale = self._maybe_assert_finite(\n                    log(maximum(abs(pre_scale), epsilon)), 'log_scale', inverse)\n\n        return scale, log_scale\n", "meta": {"hexsha": "352f6f9f01a23be6a3775d9f03b2325492c54730", "size": 32459, "ext": "py", "lang": "Python", "max_stars_repo_path": "tensorkit/backend/pytorch_/flows.py", "max_stars_repo_name": "lizeyan/tensorkit", "max_stars_repo_head_hexsha": "2997a5914ec3c3ec72f91eb5906b5ee878fdc020", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tensorkit/backend/pytorch_/flows.py", "max_issues_repo_name": "lizeyan/tensorkit", "max_issues_repo_head_hexsha": "2997a5914ec3c3ec72f91eb5906b5ee878fdc020", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tensorkit/backend/pytorch_/flows.py", "max_forks_repo_name": "lizeyan/tensorkit", "max_forks_repo_head_hexsha": "2997a5914ec3c3ec72f91eb5906b5ee878fdc020", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-15T06:41:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T12:55:11.000Z", "avg_line_length": 35.7872105843, "max_line_length": 92, "alphanum_fraction": 0.5797159494, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.18035819995785635}}
{"text": "\"\"\"\n@Fire\nhttps://github.com/fire717\n\"\"\"\nimport sys\n\n\nimport torch\nimport math\nimport numpy as np\n\nimport torch.nn.functional as F\nimport cv2\n\n\n_img_size = 192\n_feature_map_size = _img_size//4\n\n_center_weight_path = 'lib/data/center_weight_origin.npy'\n\n\nclass JointBoneLoss(torch.nn.Module):\n    def __init__(self, joint_num):\n        super(JointBoneLoss, self).__init__()\n        id_i, id_j = [], []\n        for i in range(joint_num):\n            for j in range(i+1, joint_num):\n                id_i.append(i)\n                id_j.append(j)\n        self.id_i = id_i\n        self.id_j = id_j\n\n        # self.id_i = [0,1,2,3,4,5,2]\n        # self.id_j = [1,2,3,4,5,6,4]\n\n\n    def forward(self, joint_out, joint_gt):\n        J = torch.norm(joint_out[:,self.id_i,:] - joint_out[:,self.id_j,:], p=2, dim=-1, keepdim=False)\n        Y = torch.norm(joint_gt[:,self.id_i,:] - joint_gt[:,self.id_j,:], p=2, dim=-1, keepdim=False)\n        loss = torch.abs(J-Y)\n        # loss = loss.mean()\n        loss = torch.sum(loss)/joint_out.shape[0]/len(self.id_i)\n        return loss\n\nclass MovenetLoss(torch.nn.Module):\n    def __init__(self, use_target_weight=False, target_weight=[1]):\n        super(MovenetLoss, self).__init__()\n        self.mse = torch.nn.MSELoss(size_average=True)\n        self.use_target_weight = use_target_weight\n        self.target_weight=target_weight\n\n        self.center_weight = torch.from_numpy(np.load(_center_weight_path))\n        self.make_center_w = False\n\n        # self.range_weight_x = torch.from_numpy(np.array([[x for x in range(48)] for _ in range(48)]))\n        # self.range_weight_y = self.range_weight_x.T \n\n        self.boneloss = JointBoneLoss(17)\n\n\n    def l1(self, pre, target,kps_mask):\n        # print(\"1 \",pre.shape, pre.device)\n        # print(\"2 \",target.shape, target.device)\n        # b\n\n        # return torch.mean(torch.abs(pre - target)*kps_mask)\n        return torch.sum(torch.abs(pre - target)*kps_mask)/ (kps_mask.sum() + 1e-4)\n\n    def l2_loss(self, pre, target):\n        loss = (pre - target) \n        loss = (loss * loss) / 2 / pre.shape[0]\n\n        return loss.sum()\n\n\n\n    def centernetfocalLoss(self, pred, gt):\n        ''' Modified focal loss. Exactly the same as CornerNet.\n          Runs faster and costs a little bit more memory\n        Arguments:\n          pred (batch x c x h x w)\n          gt_regr (batch x c x h x w)\n        '''\n        pos_inds = gt.eq(1).float()\n        neg_inds = gt.lt(1).float()\n\n        neg_weights = torch.pow(1 - gt, 4)\n\n        loss = 0\n\n        pos_loss = torch.log(pred) * torch.pow(1 - pred, 2) * pos_inds\n        neg_loss = torch.log(1 - pred) * torch.pow(pred, 2) * neg_weights * neg_inds\n\n        num_pos  = pos_inds.float().sum()\n        pos_loss = pos_loss.sum()\n        neg_loss = neg_loss.sum()\n\n        if num_pos == 0:\n            loss = loss - neg_loss\n        else:\n            loss = loss - (pos_loss + neg_loss) / num_pos\n        return loss\n\n\n    def myMSEwithWeight(self, pre, target):\n        #target 0-1\n        # pre = torch.sigmoid(pre)\n        # print(torch.max(pre), torch.min(pre))\n        # b\n        loss = torch.pow((pre-target),2)\n        # loss = torch.abs(pre-target)\n\n        #weight_mask = (target+0.1)/1.1\n        weight_mask = target*8+1\n        # weight_mask = torch.pow(target,2)*8+1\n\n        #gamma from focal loss\n        #gamma = torch.pow(torch.abs(target-pre), 2)\n\n        loss = loss*weight_mask#*gamma\n\n        loss = torch.sum(loss)/target.shape[0]/target.shape[1]\n\n        # bg_loss = self.bgLoss(pre, target)\n        return loss\n\n    def heatmapL1(self, pre, target):\n        #target 0-1\n        # pre = torch.sigmoid(pre)\n        # print(torch.max(pre), torch.min(pre))\n        # b\n        loss = torch.abs(pre-target)\n        \n\n        #weight_mask = (target+0.1)/1.1\n        weight_mask = target*4+1\n\n        #gamma from focal loss\n        #gamma = torch.pow(torch.abs(target-pre), 2)\n\n        loss = loss*weight_mask#*gamma\n\n        loss = torch.sum(loss)/target.shape[0]/target.shape[1]\n        return loss\n\n\n    ###############\n    def boneLoss(self, pred, target):\n        #[64, 7, 48, 48]\n        def _Frobenius(mat1, mat2):\n            return torch.pow(torch.sum(torch.pow(mat1-mat2,2)),0.5)\n            # return torch.sum(torch.pow(mat1-mat2,2))\n\n\n        _bone_idx = [[0,1],[1,2],[2,3],[3,4],[4,5],[5,6],[2,4]]\n\n        loss = 0\n        for bone_id in _bone_idx:\n            bone_pre = pred[:,bone_id[0],:,:]-pred[:,bone_id[1],:,:]\n            bone_gt = target[:,bone_id[0],:,:]-target[:,bone_id[1],:,:]\n\n            f = _Frobenius(bone_pre,bone_gt)\n            loss+=f\n\n        loss = loss/len(_bone_idx)/pred.shape[0]\n        return loss\n\n\n    def bgLoss(self, pre, target):\n        ##[64, 7, 48, 48]\n\n        bg_pre = torch.sum(pre, axis=1)\n        bg_pre = 1-torch.clamp(bg_pre, 0, 1)\n\n        bg_gt = torch.sum(target, axis=1)\n        bg_gt = 1-torch.clamp(bg_gt, 0, 1)\n\n        #weight_mask = (1-bg_gt)*4+1\n\n        loss = torch.sum(torch.pow((bg_pre-bg_gt),2))/pre.shape[0]\n\n        return loss\n\n    def heatmapLoss(self, pred, target, batch_size):\n        #[64, 7, 48, 48]\n        # print(pred.shape, target.shape)\n\n        # heatmaps_pred = pred.reshape((batch_size, pred.shape[1], -1)).split(1, 1)\n        # #对tensor在某一dim维度下，根据指定的大小split_size=int，或者list(int)来分割数据，返回tuple元组\n        # #print(len(heatmaps_pred), heatmaps_pred[0].shape)#7 torch.Size([64, 1, 48*48]\n        # heatmaps_gt = target.reshape((batch_size, pred.shape[1], -1)).split(1, 1)\n\n        # loss = 0\n\n        # for idx in range(pred.shape[1]):\n        #     heatmap_pred = heatmaps_pred[idx].squeeze()#[64, 40*40]\n        #     heatmap_gt = heatmaps_gt[idx].squeeze()\n        #     if self.use_target_weight:\n        #         loss += self.centernetfocalLoss(\n        #                         heatmap_pred.mul(self.target_weight[idx//2]),\n        #                         heatmap_gt.mul(self.target_weight[idx//2])\n        #                     )\n        #     else:\n\n        #         loss += self.centernetfocalLoss(heatmap_pred, heatmap_gt)\n        # loss /= pred.shape[1]\n\n        return self.myMSEwithWeight(pred,target) \n             \n\n    def centerLoss(self, pred, target, batch_size):\n        # heatmaps_pred = pred.reshape((batch_size, -1))\n        # heatmaps_gt = target.reshape((batch_size, -1))\n        return self.myMSEwithWeight(pred, target) \n\n\n    def regsLoss(self, pred, target, cx0, cy0,  kps_mask, batch_size, num_joints):\n        #[64, 14, 48, 48]\n        # print(target.shape, cx0.shape, cy0.shape)#torch.Size([64, 14, 48, 48]) torch.Size([64]) torch.Size([64])\n        \n        _dim0 = torch.arange(0,batch_size).long()\n        _dim1 = torch.zeros(batch_size).long()\n\n        #print(\"regsLoss: \" , cx0,cy0)\n        # print(target.shape)#torch.Size([1, 14, 48, 48])\n        # print(torch.max(target[0][2]), torch.min(target[0][2]))\n        # print(torch.max(target[0][3]), torch.min(target[0][3]))\n\n        # cv2.imwrite(\"t.jpg\", target[0][2].cpu().numpy()*255)\n        loss = 0\n        for idx in range(num_joints):\n\n            gt_x = target[_dim0,_dim1+idx*2,cy0,cx0]\n            gt_y = target[_dim0,_dim1+idx*2+1,cy0,cx0]\n            \n            \n            pre_x = pred[_dim0,_dim1+idx*2,cy0,cx0]\n            pre_y = pred[_dim0,_dim1+idx*2+1,cy0,cx0]\n\n            # print(torch.max(target[_dim0,_dim1+idx*2,:,:]),torch.min(target[_dim0,_dim1+idx*2,:,:]))\n            # print(gt_x,pre_x)                                       \n            # print(gt_y,pre_y)\n            \n\n            # print(kps_mask[:,idx])\n            # print(gt_x,pre_x)\n            # print(self.l1(gt_x,pre_x,kps_mask[:,idx]))\n            # print('---')\n            # \n\n            loss+=self.l1(gt_x,pre_x,kps_mask[:,idx])\n            loss+=self.l1(gt_y,pre_y,kps_mask[:,idx])\n        #b\n        # offset_x_pre = torch.clip(pre_x,0,_feature_map_size-1).long()\n        # offset_y_pre = torch.clip(pre_y,0,_feature_map_size-1).long()\n        # offset_x_gt = torch.clip(gt_x+cx0,0,_feature_map_size-1).long()\n        # offset_y_gt = torch.clip(gt_y+cy0,0,_feature_map_size-1).long()\n\n        return loss / num_joints\n\n\n    def offsetLoss(self, pred, target,  cx0, cy0, regs, kps_mask, batch_size, num_joints):\n        _dim0 = torch.arange(0,batch_size).long()\n        _dim1 = torch.zeros(batch_size).long()\n        loss = 0\n        # print(gt_y,gt_x)\n        for idx in range(num_joints):\n            gt_x = regs[_dim0,_dim1+idx*2,cy0,cx0].long()+cx0\n            gt_y = regs[_dim0,_dim1+idx*2+1,cy0,cx0].long()+cy0\n\n            gt_x[gt_x>47]=47\n            gt_x[gt_x<0]=0\n            gt_y[gt_y>47]=47\n            gt_y[gt_y<0]=0\n\n            gt_offset_x = target[_dim0,_dim1+idx*2,gt_y,gt_x]\n            gt_offset_y = target[_dim0,_dim1+idx*2+1,gt_y,gt_x]\n\n            pre_offset_x = pred[_dim0,_dim1+idx*2,gt_y,gt_x]\n            pre_offset_y = pred[_dim0,_dim1+idx*2+1,gt_y,gt_x]\n\n            # print(gt_offset_x, torch.max(target[_dim0,_dim1+idx*2,...]),torch.min(target[_dim0,_dim1+idx*2,...]))\n            # print(gt_offset_y, torch.max(target[_dim0,_dim1+idx*2+1,...]),torch.min(target[_dim0,_dim1+idx*2+1,...]))\n            loss+=self.l1(gt_offset_x,pre_offset_x,kps_mask[:,idx])\n            loss+=self.l1(gt_offset_y,pre_offset_y,kps_mask[:,idx])\n        #     print(gt_y,gt_x)    \n        # b\n        return loss / num_joints\n\n        \"\"\"\n        0.0 0.5\n        0.0 0.75\n        0.75 0.25\n        0.0 0.75\n        0.0 0.5\n        \"\"\"\n\n\n    def maxPointPth(self, heatmap, center=True):\n        #pytorch version\n        # n,1,h,w\n        # 计算center heatmap的最大值得到中心点\n        if center:\n            heatmap = heatmap*self.center_weight[:heatmap.shape[0],...]\n            #加权取最靠近中间的\n\n        n,c,h,w = heatmap.shape\n        heatmap = heatmap.reshape((n, -1)) #64, 48x48\n        # print(heatmap[0])\n        # max_id = torch.argmax(heatmap, 1)#64, 1\n        # print(max_id)\n        max_v,max_id = torch.max(heatmap, 1)#64, 1\n        # print(max_v)\n        # print(\"max_i: \",max_i)\n\n        # mask0 = torch.zeros(max_v.shape).to(heatmap.device)\n        # mask1 = torch.ones(max_v.shape).to(heatmap.device)\n        # mask = torch.where(torch.gt(max_v,th), mask1, mask0)\n        # print(mask)\n        # b\n        y = max_id//w\n        x = max_id%w\n\n        return x,y\n\n\n    def forward(self, output, target, kps_mask):\n        batch_size = output[0].size(0)\n        num_joints = output[0].size(1)\n        #print(\"output: \", [x.shape for x in output])\n        #[64, 7, 48, 48] [64, 1, 48, 48] [64, 14, 48, 48] [64, 14, 48, 48]\n        # print(\"target: \", [x.shape for x in target])#[64, 36, 48, 48]\n        #print(weights.shape)# [14,]\n        heatmaps = target[:,:17,:,:]\n        centers = target[:,17:18,:,:]\n        regs = target[:,18:52,:,:]\n        offsets = target[:,52:,:,:]\n\n\n        heatmap_loss = self.heatmapLoss(output[0], heatmaps, batch_size)\n\n        # bg_loss = self.bgLoss(output[0], heatmaps)\n        #bone_loss = self.boneloss(output[0], heatmaps)\n        bone_loss = self.boneLoss(output[0], heatmaps)\n        #print(heatmap_loss)\n        center_loss = self.centerLoss(output[1], centers, batch_size)\n\n\n        if not self.make_center_w:\n            self.center_weight = torch.reshape(self.center_weight,(1,1,48,48))\n            self.center_weight = self.center_weight.repeat((output[1].shape[0],output[1].shape[1],1,1))\n            # print(self.center_weight.shape)\n            # b\n            self.center_weight = self.center_weight.to(target.device)\n            self.make_center_w = True\n            self.center_weight.requires_grad_(False)\n\n            # self.range_weight_x = self.range_weight_x.to(target.device)\n            # self.range_weight_y = self.range_weight_y.to(target.device)\n            # self.range_weight_x.requires_grad_(False)\n            # self.range_weight_y.requires_grad_(False)\n        #print(self.center_weight)\n\n\n        cx0, cy0 = self.maxPointPth(centers)\n        # cx1, cy1 = self.maxPointPth(pre_centers)\n        cx0 = torch.clip(cx0,0,_feature_map_size-1).long()\n        cy0 = torch.clip(cy0,0,_feature_map_size-1).long()\n        # cx1 = torch.clip(cx1,0,_feature_map_size-1).long()\n        # cy1 = torch.clip(cy1,0,_feature_map_size-1).long()\n\n        # print(cx0, cy0)\n        # bbb\n        # cv2.imwrite(\"_centers.jpg\", centers[0][0].cpu().numpy()*255)\n        # b\n\n        regs_loss = self.regsLoss(output[2], regs, cx0, cy0, kps_mask,batch_size, num_joints)\n        offset_loss = self.offsetLoss(output[3], offsets, \n                            cx0, cy0,regs,\n                            kps_mask,batch_size, num_joints)\n        \n        # total_loss = heatmap_loss+center_loss+0.1*regs_loss+offset_loss\n        # print(heatmap_loss,center_loss,regs_loss,offset_loss)\n        # b\n        \n        \"\"\"\n        \n        \"\"\" \n        # boneloss = self.boneLoss(output[3], offsets, \n        #                     cx0, cy0,regs,\n        #                     kps_mask,batch_size, num_joints)\n\n\n        return [heatmap_loss,bone_loss,center_loss,regs_loss,offset_loss]\n\nmovenetLoss = MovenetLoss(use_target_weight=False)\n\n\ndef calculate_loss(predict, label):\n    loss = movenetLoss(predict, label)\n    return loss \n\n\n", "meta": {"hexsha": "d7e1e7665d2df5c9225ff9381aa8496b3d5572ea", "size": 13187, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/loss/movenet_loss.py", "max_stars_repo_name": "SevenMoGod/movenet.pytorch", "max_stars_repo_head_hexsha": "95ec8535245228aa4335243e68722810e50bcaf8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 87, "max_stars_repo_stars_event_min_datetime": "2021-11-13T11:05:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:00:45.000Z", "max_issues_repo_path": "lib/loss/movenet_loss.py", "max_issues_repo_name": "Dyian-snow/movenet.pytorch", "max_issues_repo_head_hexsha": "95ec8535245228aa4335243e68722810e50bcaf8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2021-11-16T01:13:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:04:31.000Z", "max_forks_repo_path": "lib/loss/movenet_loss.py", "max_forks_repo_name": "Dyian-snow/movenet.pytorch", "max_forks_repo_head_hexsha": "95ec8535245228aa4335243e68722810e50bcaf8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28, "max_forks_repo_forks_event_min_datetime": "2021-11-13T11:22:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:02:09.000Z", "avg_line_length": 32.6410891089, "max_line_length": 119, "alphanum_fraction": 0.5628270266, "include": true, "reason": "import numpy", "num_tokens": 3854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.18035819995785632}}
{"text": "from scipy.interpolate import interp1d\nfrom pyHalo.defaults import *\nfrom pyHalo.Cosmology.cosmology import Cosmology\nfrom pyHalo.Halos.lens_cosmo import LensCosmo\nfrom pyHalo.Halos.HaloModels.NFW import NFWSubhhalo, NFWFieldHalo\nfrom pyHalo.Halos.HaloModels.TNFW import TNFWFieldHalo, TNFWSubhalo\nfrom pyHalo.Halos.HaloModels.PsuedoJaffe import PJaffeSubhalo\nfrom pyHalo.Halos.HaloModels.PTMass import PTMass\nfrom pyHalo.Halos.HaloModels.coreTNFW import coreTNFWFieldHalo, coreTNFWSubhalo\nfrom pyHalo.Halos.HaloModels.ULDM import ULDMFieldHalo, ULDMSubhalo\nimport numpy as np\nfrom copy import deepcopy\n\n\ndef realization_at_z(realization, z, angular_coordinate_x=None, angular_coordinate_y=None, max_range=None):\n    \"\"\"\n    :param realization: an instance of Realization\n    :param z: the redshift where we want to extract halos\n    :param angular_coordinate_x: if max_range is specified, will only keep halos within\n    max_range of (angular_coordinate_x, angular_coordinate_y)\n    :param angular_coordinate_y:\n    :param max_range: radius in arcseconds where we want to keep halos. If None, will return a new realization class\n     that contains all halos at redshift z contained in the input realization class\n    :return: a new instance of Realization\n    \"\"\"\n\n    _halos, _indexes = realization.halos_at_z(z)\n    halos = []\n    indexes = []\n\n    if max_range is not None:\n        for i, halo in enumerate(_halos):\n            dx, dy = halo.x - angular_coordinate_x, halo.y - angular_coordinate_y\n            dr = (dx ** 2 + dy ** 2) ** 0.5\n            if dr < max_range:\n                halos.append(halo)\n                indexes.append(i)\n    else:\n        halos = _halos\n        indexes = _indexes\n\n    centerx, centery = realization.rendering_center\n\n    return Realization.from_halos(halos, realization.lens_cosmo,\n                                  realization._prof_params,\n                                  realization._mass_sheet_correction,\n                                  realization.rendering_classes,\n                                  centerx, centery), indexes\n\nclass Realization(object):\n\n    \"\"\"\n    This is the main class for storing a population of dark matter halos, both in the main lens plane and along the\n    line of sight. This class is created by the main pyhalo module.\n    \"\"\"\n\n    def __init__(self, masses, x, y, r3d, mdefs, z, subhalo_flag, lens_cosmo,\n                 halos=None, kwargs_realization={}, mass_sheet_correction=True,\n                 rendering_classes=None, rendering_center_x=None, rendering_center_y=None,\n                 geometry=None):\n\n        \"\"\"\n\n        This class is the main class that stores information regarding realizations of dark matter halos. It is not\n        intended to be created directly by the user. Instances of this class are created through the class\n        pyHalo or pyHalo_dynamic.\n\n        :param masses: an array of halo masses (units solar mass)\n        :param x: an array of halo x-coordinates (units arcsec)\n        :param y: an array of halo y-coordinates (units arcsec)\n        :param r2d: an array of halo 2-d distances from lens center (units kpc / (kpc/arsec), or arcsec,\n        at halo redshift)\n        :param r3d: an array of halo 2-d distances from lens center (units kpc / (kpc/arsec), or arcsec,\n        at halo redshift)\n        :param mdefs: mass definition of each halo\n        :param z: halo redshift\n        :param subhalo_flag: whether each halo is a subhalo or a regular halo\n        :param lens_cosmo: an instance of LensCosmo (see Halos.lens_cosmo)\n        :param halos: a list of halo class instances\n        :param kwargs_realization: kwargs for the realiztion\n        :param mass_sheet_correction: whether to apply a mass sheet correction\n        :param rendering_classes: a list of rendering class instances\n        :param rendering_center_x: an instance of scipy.interp1d that returns an angular position given a comoving distance.\n        The angular coordinate defines the center of the rendering volume, and halos will be distributed symmetrically around it.\n        The value defaults to 0, but is overridden when the method shift_background_to_source is called\n        :param rendering_center_y: same as rendering_center_x, but for the y angular coordinate\n        :param geometry: (optional, only relevant is subtract_exact_mass_sheets=True is specified in kwargs_realization)\n        an instance of Geometry (pyHalo.Cosmology.geometry) that defines the rendering volume\n        \"\"\"\n\n        self.apply_mass_sheet_correction = mass_sheet_correction\n        self.geometry = geometry\n        self.lens_cosmo = lens_cosmo\n        self._zlens, self._zsource = self.lens_cosmo.z_lens, self.lens_cosmo.z_source\n        self.astropy_instance = self.lens_cosmo.cosmo.astropy\n        self.halos = []\n        self._loaded_models = {}\n        self._has_been_shifted = False\n        self._prof_params = set_default_kwargs(kwargs_realization, self._zsource)\n\n        if halos is None:\n\n            for mi, xi, yi, r3di, mdefi, zi, sub_flag in zip(masses, x, y, r3d,\n                           mdefs, z, subhalo_flag):\n\n                unique_tag = np.random.rand()\n                model = self._load_halo_model(mi, xi, yi, r3di, mdefi, zi, sub_flag, self.lens_cosmo,\n                                              self._prof_params, unique_tag)\n                self.halos.append(model)\n\n\n        else:\n\n            self.halos = halos\n\n        self._reset()\n\n        self.set_rendering_classes(rendering_classes)\n\n        if rendering_center_x is None or rendering_center_y is None:\n            _z = np.linspace(0, self._zsource, 100)\n            d = [self.lens_cosmo.cosmo.D_C_transverse(zi) for zi in _z]\n            angle = np.zeros_like(d)\n            rendering_center_x = interp1d(d, angle)\n            rendering_center_y = interp1d(d, angle)\n\n        self._rendering_center_x = rendering_center_x\n        self._rendering_center_y = rendering_center_y\n\n    @classmethod\n    def from_halos(cls, halos, lens_cosmo, prof_params, msheet_correction, rendering_classes,\n                   rendering_center_x=None, rendering_center_y=None, geometry=None):\n\n        \"\"\"\n\n        :param halos: a list of halo class instances\n        :param lens_cosmo: an instance of LensCosmo (see Halos.lens_cosmo)\n        :param prof_params: keyword arguments for the realization\n        :param msheet_correction: whether or not to apply a mass sheet correction\n        :param rendering_classes: a list of rendering classes\n        :param rendering_center_x: an instance of scipy.interp1d that returns an angular position given a comoving distance.\n        The angular coordinate defines the center of the rendering volume, and halos will be distributed symmetrically around it.\n        The value defaults to 0, but is overridden when the method shift_background_to_source is called\n        :param rendering_center_y: same as rendering_center_x, but for the y angular coordinate\n        :param geometry: (optional, only relevant is subtract_exact_mass_sheets=True is specified in kwargs_realization)\n        an instance of Geometry (pyHalo.Cosmology.geometry) that defines the rendering volume\n        :return: an instance of Realization created directly from the halo class instances\n        \"\"\"\n\n        realization = Realization(None, None, None, None, None, None, None, lens_cosmo,\n                                  halos=halos, kwargs_realization=prof_params,\n                                  mass_sheet_correction=msheet_correction,\n                                  rendering_classes=rendering_classes,\n                                  rendering_center_x=rendering_center_x,\n                                  rendering_center_y=rendering_center_y,\n                                  geometry=geometry)\n\n        return realization\n\n    @property\n    def rendering_center(self):\n\n        \"\"\"\n        Returns the instances of scipy.interp1d that compute the coordinate center of the lensing volume given a comoving\n        distance.\n        \"\"\"\n        return self._rendering_center_x, self._rendering_center_y\n\n    def filter(self, aperture_radius_front,\n               aperture_radius_back,\n               log_mass_allowed_in_aperture_front,\n               log_mass_allowed_in_aperture_back,\n               log_mass_allowed_global_front,\n               log_mass_allowed_global_back,\n               interpolated_x_angle, interpolated_y_angle,\n               zmin=None, zmax=None, aperture_units='ANGLES'):\n\n        \"\"\"\n\n        :param aperture_radius_front: the radius of a circular window around each light ray where halos are halo kept\n        if they are more massive than log_mass_allowed_in_aperture_front (applied for z < z_lens)\n        :param aperture_radius_back: the radius of a circular window around each light ray where halos are halo kept\n        if they are more massive than log_mass_allowed_in_aperture_back (applied for z < z_lens)\n        :param log_mass_allowed_in_aperture_front: the minimum halo mass to be kept inside the tube around each light ray\n        in the foreground\n        :param log_mass_allowed_in_aperture_back: the minimum halo mass to be kept inside the tube around each light ray\n        in the background\n        :param log_mass_allowed_global_front: The minimum mass to be kept everywhere in the foreground (if this is smaller\n        than log_mass_allowed_in_aperture_front, then the argument aperture_radius_front will have no effect)\n        :param log_mass_allowed_global_back: The minimum mass to be kept everywhere in the background (if this is smaller\n        than log_mass_allowed_in_aperture_back, then the argument aperture_radius_back will have no effect)\n        :param interpolated_x_angle: a list of scipy.interp1d that retuns the x angular position of a ray in\n        arcsec given a comoving distance\n        :param interpolated_y_angle: a list of scipy.interp1d that retuns the y angular position of a ray in\n        arcsec given a comoving distance\n        :param zmin: only keep halos at z > zmin\n        :param zmax: only keep halos at z < zmax\n        :param aperture_units: either 'ANGLES' or 'MPC'\n\n        - If 'ANGLES', then halos are kept inside angular apertures\n        around each light ray with size aperture_radius_front/aperture_radius_back.\n        - If 'MPC', then halos are kept inside circular apertures with radius\n        R = aperture_radius_front/back * mpc_per_arcsec(0.5)\n        where D_C(0.5) is the comoving transverse distance at z = 0.5. The unit of R is arcsec * Mpc\n\n        'ANGLES' is more conservative in that it keeps more halos in the lens model; the rendering area is basically a cone\n        since the aperture size is a fixed angle at every redshift, whereas 'MPC' distributes halos in cylindrical\n        tubes around each light ray along the line of sight.\n\n        :return: A new instance of Realization with the cuts on position and mass applied\n        \"\"\"\n        halos = []\n\n        if zmax is None:\n            zmax = self._zsource\n        if zmin is None:\n            zmin = 0\n\n        for plane_index, zi in enumerate(self.unique_redshifts):\n\n            plane_halos, _ = self.halos_at_z(zi)\n            inds_at_z = np.where(self.redshifts == zi)[0]\n            x_at_z = self.x[inds_at_z]\n            y_at_z = self.y[inds_at_z]\n            masses_at_z = self.masses[inds_at_z]\n\n            if zi < zmin:\n                continue\n            if zi > zmax:\n                continue\n\n            comoving_distance_z = self.lens_cosmo.cosmo.D_C_z(zi)\n\n            if zi <= self._zlens:\n\n                minimum_mass_everywhere = deepcopy(log_mass_allowed_global_front)\n                minimum_mass_in_window = deepcopy(log_mass_allowed_in_aperture_front)\n                aperture_radius_arcsec = deepcopy(aperture_radius_front)\n\n            else:\n\n                minimum_mass_everywhere = deepcopy(log_mass_allowed_global_back)\n                minimum_mass_in_window = deepcopy(log_mass_allowed_in_aperture_back)\n                aperture_radius_arcsec = deepcopy(aperture_radius_back)\n\n            keep_inds_mass = np.where(masses_at_z >= 10 ** minimum_mass_everywhere)[0]\n\n            inds_m_low = np.where(masses_at_z < 10 ** minimum_mass_everywhere)[0]\n\n            keep_inds_dr = []\n            for idx in inds_m_low:\n                for k, (interp_x, interp_y) in enumerate(zip(interpolated_x_angle, interpolated_y_angle)):\n\n                    dx = x_at_z[idx] - interp_x(comoving_distance_z)\n                    dy = y_at_z[idx] - interp_y(comoving_distance_z)\n\n                    if aperture_units == 'ANGLES':\n                        dr_cut = aperture_radius_arcsec\n\n                    elif aperture_units == 'MPC':\n                        dx *= comoving_distance_z\n                        dy *= comoving_distance_z\n                        dr_cut = aperture_radius_arcsec * self.lens_cosmo.cosmo.D_C_z(0.5)\n                    else:\n                        raise Exception('aperture units must be either MPC or ANGLES')\n\n                    dr = np.sqrt(dx ** 2 + dy ** 2)\n\n                    if dr <= dr_cut:\n                        keep_inds_dr.append(idx)\n                        break\n\n            keep_inds = np.append(keep_inds_mass, np.array(keep_inds_dr)).astype(int)\n\n            tempmasses = masses_at_z[keep_inds]\n            keep_inds = keep_inds[np.where(tempmasses >= 10 ** minimum_mass_in_window)[0]]\n\n            for halo_index in keep_inds:\n                halos.append(plane_halos[halo_index])\n\n        return Realization.from_halos(halos, self.lens_cosmo, self._prof_params,\n                                      self.apply_mass_sheet_correction, self.rendering_classes,\n                                      self._rendering_center_x, self._rendering_center_y, self.geometry)\n\n    def set_rendering_classes(self, rendering_classes):\n\n        \"\"\"\n        This method sets the rendering classes for the realization, which are used to apply the negative convergence sheet\n        corrections after adding halos. The properties of the convergence sheets you need to add depend on the form of the\n        mass function you have specified, so this information is stored in the classes used to render halos\n        (LOSPowerLaw, MainLensPowerLaw, etc, see classes in pyHalo/Rendering)\n\n        If the rendering classes are not specified for whatever reason, the code will still run but no negative convergence\n        sheets will be included in your lens models. This could potentially bias results as you've effectively made every\n        light cone overdense relative to the mean matter density in the Universe.\n\n        :param rendering_classes: a list or an instance of a rendering class (LOSPowerLaw, MainLensPowerLaw)\n        \"\"\"\n\n        if not isinstance(rendering_classes, list):\n            rendering_classes = [rendering_classes]\n        self.rendering_classes = rendering_classes\n\n    def join(self, real, join_rendering_classes=False):\n\n        \"\"\"\n        This routine combines one realization with another realization, keeping only the unqiue halos\n        (as identified by their .unique_tag attribute) between them.\n\n        :param real: another realization, possibly a filtered version of self\n        :param join_rendering_classes: If True, the rendering classes associated with the new\n        realization will include both the rendering class associated with self and that of real.\n\n        :return: a new realization that contains all unique halos from self and real\n        \"\"\"\n\n        halos = []\n\n        tags = self._tags(self.halos)\n        real_tags = self._tags(real.halos)\n        if len(tags) >= len(real_tags):\n            long, short = tags, real_tags\n            halos_long, halos_short = self.halos, real.halos\n        else:\n            long, short = real_tags, tags\n            halos_long, halos_short = real.halos, self.halos\n\n        for halo in halos_short:\n            halos.append(halo)\n\n        for i, tag in enumerate(long):\n\n            if tag not in short:\n                halos.append(halos_long[i])\n\n        if join_rendering_classes:\n            rendering_class_self = self.rendering_classes\n            rendering_class_new = real.rendering_classes\n            rendering_classes = rendering_class_self + rendering_class_new\n        else:\n            rendering_classes = self.rendering_classes\n\n        centerx, centery = self.rendering_center\n        return Realization.from_halos(halos, self.lens_cosmo, self._prof_params,\n                                      self.apply_mass_sheet_correction, rendering_classes,\n                                      centerx, centery, self.geometry)\n\n    def shift_background_to_source(self, ray_interp_x, ray_interp_y):\n\n        \"\"\"\n        This routine shifts the entire relation along a path specified by ray_interp_x/y. This routine is intended\n        to be used in situations where the source is significantly offset from the origin, and you want to align the\n        center of the rendering volume such that tracks the path of the light.\n\n        :param ray_interp_x: instance of scipy.interp1d, returns the angular position of a ray\n        fired through the lens center given a comoving distance\n        :param ray_interp_y: same but for the y coordinate\n        :return:\n        \"\"\"\n\n        if self._has_been_shifted:\n            return self\n\n        halos = []\n\n        for halo in self.halos:\n\n            comoving_distance_z = self.lens_cosmo.cosmo.D_C_z(halo.z)\n\n            xshift, yshift = ray_interp_x(comoving_distance_z), ray_interp_y(comoving_distance_z)\n\n            halo.x += xshift\n            halo.y += yshift\n            halos.append(halo)\n\n        new_realization = Realization.from_halos(halos, self.lens_cosmo, self._prof_params, self.apply_mass_sheet_correction,\n                                                 self.rendering_classes, ray_interp_x, ray_interp_y, self.geometry)\n\n        new_realization._has_been_shifted = True\n\n        return new_realization\n\n    def lensing_quantities(self, add_mass_sheet_correction=True, z_mass_sheet_max=None,\n                           kwargs_mass_sheet_correction=None):\n\n        \"\"\"\n        :param add_mass_sheet_correction: include sheets of negative convergence to correct for mass added subhalos/field halos\n        :param z_mass_sheet_max: don't include negative convergence sheets at z>z_mass_sheet_max (this does nothing\n        if the previous argument is False\n        :pararm kwargs_mass_sheet_correction: additional keyword arguments for the mass sheet correction\n        (changes the default setting)\n        :return: the lens_model_list, redshift_list, kwargs_lens, and numerical_alpha_class keywords that can be plugged\n        directly into a lenstronomy LensModel class\n        \"\"\"\n\n        kwargs_lens = []\n        lens_model_list = []\n        redshift_array = []\n        numerical_interp = None\n\n        for i, halo in enumerate(self.halos):\n\n            lens_model_name = halo.lenstronomy_ID\n            kwargs_halo, interp_class = halo.lenstronomy_params\n            lens_model_list += lens_model_name\n            kwargs_lens += kwargs_halo\n            redshift_array += [halo.z] * len(lens_model_name)\n\n            if interp_class is not None:\n                numerical_interp = interp_class\n\n        if self.apply_mass_sheet_correction and add_mass_sheet_correction:\n\n            if self.rendering_classes is None:\n                raise Exception('if applying a convergence sheet correction, must specify '\n                                'the rendering classes.')\n\n            kwargs_mass_sheets, profile_list, z_sheets = self._mass_sheet_correction(self.rendering_classes,\n                                                                                     z_mass_sheet_max,\n                                                                                     kwargs_mass_sheet_correction)\n            kwargs_lens += kwargs_mass_sheets\n            lens_model_list += profile_list\n            redshift_array = np.append(redshift_array, z_sheets)\n\n        return lens_model_list, redshift_array, kwargs_lens, numerical_interp\n\n    def split_at_z(self, z):\n        \"\"\"\n        Splits the realization at redshift z, returning one instance at Realization containing all halos with\n        redshift < zlens and another with all halos at redshift >= z. Be careful with the mass sheet corrections contained\n        in the rendering_classes, as both new realizations will get all rendering classes from the parent realization.\n\n        :param z: the redshift at which to split the realization\n        :return: two instances at Realization divided at redshift z\n        \"\"\"\n\n        halos_1, halos_2 = [], []\n        for halo in self.halos:\n            if halo.z <= z:\n                halos_1.append(halo)\n            else:\n                halos_2.append(halo)\n\n        centerx, centery = self.rendering_center\n        realization_1 = Realization.from_halos(halos_1, self.lens_cosmo,\n                                               self._prof_params, self.apply_mass_sheet_correction, self.rendering_classes,\n                                               centerx, centery, self.geometry)\n        realization_2 = Realization.from_halos(halos_2, self.lens_cosmo,\n                                               self._prof_params, self.apply_mass_sheet_correction, self.rendering_classes,\n                                               centerx, centery, self.geometry)\n\n        return realization_1, realization_2\n\n    def halo_comoving_coordinates(self):\n\n        \"\"\"\n        :param halos: a list of halos\n        :return: the comoving (x, y) position, mass, and redshift of each halo in the realization\n        \"\"\"\n        xcoords, ycoords, masses, redshifts = [], [], [], []\n\n        for halo in self.halos:\n            D = self.lens_cosmo.cosmo.D_C_z(halo.z)\n            x_arcsec, y_arcsec = halo.x, halo.y\n            x_comoving, y_comoving = D * x_arcsec, D * y_arcsec\n            xcoords.append(x_comoving)\n            ycoords.append(y_comoving)\n            masses.append(halo.mass)\n            redshifts.append(halo.z)\n\n        return np.array(xcoords), np.array(ycoords), np.log10(masses), np.array(redshifts)\n\n    def halos_at_z(self, z):\n        \"\"\"\n\n        :param z: redshift\n        :return: all halos in the realization that are at redshift z\n        \"\"\"\n        halos = []\n        index = []\n        for i, halo in enumerate(self.halos):\n            if halo.z != z:\n                continue\n            halos.append(halo)\n            index.append(i)\n\n        return halos, index\n\n    def mass_at_z_exact(self, z):\n\n        \"\"\"\n        Computes the total mass rendered at each redshift z\n        :param z: redshift\n        :return: total mass rendered at z\n        \"\"\"\n\n        inds = np.where(self.redshifts == z)\n        m_exact = np.sum(self.masses[inds])\n        return m_exact\n\n    def number_of_halos_before_redshift(self, z):\n\n        \"\"\"\n        Computes the number of halos with redshifts < z\n        :param z: redshift\n        :return: number of halos with redshift < z\n        \"\"\"\n        n = 0\n        for halo in self.halos:\n            if halo.z < z:\n                n += 1\n        return n\n\n    def number_of_halos_after_redshift(self, z):\n\n        \"\"\"\n        Computes the number of halos with redshifts > z\n        :param z: redshift\n        :return: number of halos with redshift > z\n        \"\"\"\n        n = 0\n        for halo in self.halos:\n            if halo.z > z:\n                n += 1\n        return n\n\n    def number_of_halos_at_redshift(self, z):\n\n        \"\"\"\n        Computes the number of halos with redshifts == z\n        :param z: redshift\n        :return: number of halos at z\n        \"\"\"\n\n        n = 0\n        for halo in self.halos:\n            if halo.z == z:\n                n += 1\n        return n\n\n    def _mass_sheet_correction(self, rendering_classes, z_mass_sheet_max, kwargs_mass_sheet_correction):\n\n        \"\"\"\n        This routine adds the negative mass sheet corrections along the LOS and in the main lens plane.\n        The actual physics that determines the amount of negative convergence to add is encoded in the rendering_classes\n        (see for example Rendering.Field.PowerLaw.powerlaw_base.py)\n\n        :param rendering_classes: the rendering class associated with each realization\n        :param z_mass_sheet_max: don't add mass sheets at lens planes with redshift > z_mass_sheet_max\n        :param kwargs_mass_sheet_correction: keyword arguments for the convergence sheet correction\n        :return: the kwargs_lens, lens_model_list, and redshift_list of the mass sheets that can be plugged into lenstronomy\n        \"\"\"\n\n        kwargs_mass_sheets = []\n\n        redshifts = []\n\n        profiles = []\n\n        if self._prof_params['subtract_exact_mass_sheets']:\n\n            for zi in self.unique_redshifts:\n                area = self.geometry.angle_to_physical_area(0.5 * self.geometry.cone_opening_angle, zi)\n                kwargs_mass_sheets += [{'kappa_ext': -self.mass_at_z_exact(zi) / self.lens_cosmo.sigma_crit_mass(zi, area)}]\n\n            redshifts = self.unique_redshifts\n\n            profiles = ['CONVERGENCE'] * len(kwargs_mass_sheets)\n\n        else:\n\n            for rendering_class in rendering_classes:\n\n                if rendering_class is None:\n                    continue\n\n                kwargs_new, profiles_new, redshifts_new = \\\n                    rendering_class.convergence_sheet_correction(kwargs_mass_sheet_correction)\n\n                kwargs_mass_sheets += kwargs_new\n                redshifts += redshifts_new\n                profiles += profiles_new\n\n        if z_mass_sheet_max is not None:\n            kwargs_mass_sheets_out = []\n            profiles_out = []\n            redshifts_out = []\n\n            inds_keep = np.where(np.array(redshifts) <= z_mass_sheet_max)[0]\n\n            for i in range(0, len(kwargs_mass_sheets)):\n                if i in inds_keep:\n                    kwargs_mass_sheets_out.append(kwargs_mass_sheets[i])\n                    profiles_out.append(profiles[i])\n                    redshifts_out.append(redshifts[i])\n        else:\n            kwargs_mass_sheets_out, profiles_out, redshifts_out = kwargs_mass_sheets, profiles, redshifts\n\n        # define the center of mass sheet to be the center of the rendering volume\n        centerx_interp, centery_interp = self.rendering_center\n\n        for i, (zi, profile_name) in enumerate(zip(redshifts_out, profiles_out)):\n            di = self.lens_cosmo.cosmo.D_C_z(zi)\n            x_center, y_center = centerx_interp(di), centery_interp(di)\n            if profile_name == 'CONVERGENCE':\n                kwargs_mass_sheets_out[i]['ra_0'] = float(x_center)\n                kwargs_mass_sheets_out[i]['dec_0'] = float(y_center)\n            else:\n                kwargs_mass_sheets_out[i]['center_x'] = float(x_center)\n                kwargs_mass_sheets_out[i]['center_y'] = float(y_center)\n\n        return kwargs_mass_sheets_out, profiles_out, redshifts_out\n\n    def _load_halo_model(self, mass, x, y, r3d, mdef, z, is_subhalo,\n                         lens_cosmo_instance, args, unique_tag):\n\n        \"\"\"\n        Loads the halo model for each object based on the mass definition\n        :param halo: an instance of Halo\n        :return: the specific Halo class corresponding to mass definition mdef\n        \"\"\"\n\n        if mdef == 'NFW':\n\n            if is_subhalo:\n                model = NFWSubhhalo(mass, x, y, r3d, mdef, z, is_subhalo,\n                                    lens_cosmo_instance, args, unique_tag)\n            else:\n                model = NFWFieldHalo(mass, x, y, r3d, mdef, z, is_subhalo,\n                                    lens_cosmo_instance, args, unique_tag)\n\n\n        elif mdef == 'TNFW':\n\n            if is_subhalo:\n                model = TNFWSubhalo(mass, x, y, r3d, mdef, z, is_subhalo,\n                                    lens_cosmo_instance, args, unique_tag)\n\n            else:\n                model = TNFWFieldHalo(mass, x, y, r3d, mdef, z, is_subhalo,\n                                      lens_cosmo_instance, args, unique_tag)\n\n        elif mdef == 'PT_MASS':\n\n            model = PTMass(mass, x, y, r3d, mdef, z, is_subhalo,\n                           lens_cosmo_instance, args, unique_tag)\n\n        elif mdef == 'PJAFFE':\n\n            model = PJaffeSubhalo(mass, x, y, r3d, mdef, z, is_subhalo,\n                                  lens_cosmo_instance, args, unique_tag)\n\n        elif mdef == 'coreTNFW':\n\n            if is_subhalo:\n                model = coreTNFWSubhalo(mass, x, y, r3d, mdef, z, is_subhalo,\n                                  lens_cosmo_instance, args, unique_tag)\n            else:\n                model = coreTNFWFieldHalo(mass, x, y, r3d, mdef, z, is_subhalo,\n                                  lens_cosmo_instance, args, unique_tag)\n\n        elif mdef == 'ULDM':\n\n            if is_subhalo:\n                model = ULDMSubhalo(mass, x, y, r3d, mdef, z, is_subhalo,\n                                  lens_cosmo_instance, args, unique_tag)\n            else:\n                model = ULDMFieldHalo(mass, x, y, r3d, mdef, z, is_subhalo,\n                                  lens_cosmo_instance, args, unique_tag)\n\n\n        else:\n            raise ValueError('halo profile ' + str(mdef) + ' not recongnized.')\n\n        return model\n\n    def _tags(self, halos=None):\n\n        \"\"\"\n\n        :param halos: a list of halos\n        :return: the unique tag for each halo in halos; if halos is not specified, returns the unique tag for each\n        halo in the realization\n        \"\"\"\n        if halos is None:\n            halos = self.halos\n        tags = []\n\n        for halo in halos:\n\n            tags.append(halo.unique_tag)\n\n        return tags\n\n    def _reset(self):\n        \"\"\"\n        Resets all class attributes to the current set of halos contained in the realization\n        :return:\n        \"\"\"\n\n        self.x = []\n        self.y = []\n        self.masses = []\n        self.redshifts = []\n        self.r3d = []\n        self.mdefs = []\n        self._halo_tags = []\n        self.subhalo_flags = []\n\n        for halo in self.halos:\n            self.masses.append(halo.mass)\n            self.x.append(halo.x)\n            self.y.append(halo.y)\n            self.redshifts.append(halo.z)\n            self.r3d.append(halo.r3d)\n            self.mdefs.append(halo.mdef)\n            self._halo_tags.append(halo.unique_tag)\n            self.subhalo_flags.append(halo.is_subhalo)\n\n        self.masses = np.array(self.masses)\n        self.x = np.array(self.x)\n        self.y = np.array(self.y)\n        self.r3d = np.array(self.r3d)\n        self.redshifts = np.array(self.redshifts)\n\n        self.unique_redshifts = np.unique(self.redshifts)\n\n    def __eq__(self, other_reealization):\n\n        \"\"\"\n        Defintes equality between two realizations if they contain the same halos with the same unique tags\n        :param other_reealization:\n        :return:\n        \"\"\"\n        tags = self._tags(self.halos)\n        other_tags = other_reealization._tags()\n        for tag in other_tags:\n            if tag not in tags:\n                return False\n        else:\n            return True\n\nclass SingleHalo(Realization):\n\n    def __init__(self, halo_mass, x, y, mdef, z, zlens, zsource, r3d=None, subhalo_flag=False,\n                 kwargs_halo={}, cosmo=None):\n\n        \"\"\"\n       Useful for generating a realization with a single or a few\n        user-specified halos.\n        :param halo_mass: mass of the halo in M_sun\n        :param x: halo x coordinate in arcsec\n        :param y: halo y coordinate in arcsec\n        :param mdef: halo mass definition\n        :param z: halo redshift\n        :param zlens: main deflector redshift\n        :param zsource: source redshift\n        :param r3d: three dimensional coordinate of halo inside the host in kpc\n        (only relevant for tidally-truncated subhalos, for field halos this can be None)\n        :param subhalo_flag: bool, sets whether or not a halo is a subhalo\n        :param kwargs_halo: keyword arguments for the halo\n        :param cosmo: an instance of Cosmology(); if none is provided a default cosmology will be used\n        \"\"\"\n        if cosmo is None:\n            cosmo = Cosmology()\n\n        lens_cosmo = LensCosmo(zlens, zsource, cosmo)\n\n        # these are redundant keywords for a single halo, but we need to specify them anyways\n        kwargs_halo.update({'cone_opening_angle': 6., 'log_mlow': 6., 'log_mhigh': 10.})\n        super(SingleHalo, self).__init__([halo_mass], [x], [y],\n                                         [r3d], [mdef], [z], [subhalo_flag], lens_cosmo,\n                                         kwargs_realization=kwargs_halo, mass_sheet_correction=False)\n\n\n\n", "meta": {"hexsha": "0720c66e1666cfe069758f4c876375f72640a999", "size": 32746, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyHalo/single_realization.py", "max_stars_repo_name": "AlexLaroche7/pyHalo", "max_stars_repo_head_hexsha": "77482325e04374ebb7361364f2984dbd639d51e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyHalo/single_realization.py", "max_issues_repo_name": "AlexLaroche7/pyHalo", "max_issues_repo_head_hexsha": "77482325e04374ebb7361364f2984dbd639d51e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyHalo/single_realization.py", "max_forks_repo_name": "AlexLaroche7/pyHalo", "max_forks_repo_head_hexsha": "77482325e04374ebb7361364f2984dbd639d51e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.1441441441, "max_line_length": 129, "alphanum_fraction": 0.6282599401, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.1803581963072076}}
{"text": "from .utils import PyKEArgumentHelpFormatter\nfrom . import kepio, kepmsg, kepkey, kepfunc, kepstat\nfrom astropy.io import fits as pyfits\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom tqdm import tqdm\n\n\n__all__ = ['kepfilter']\n\n\ndef kepfilter(infile, passband, outfile=None, datacol='SAP_FLUX', function='boxcar',\n              cutoff=1.0, plot=False, overwrite=False, verbose=False,\n              logfile='kepfilter.log'):\n    \"\"\"\n    kepfilter -- bandpass filtering of Kepler light curve data\n\n    ``kepfilter`` applies a bandpass filter to Kepler light curve data. In the\n    low bandpass option, the data is convolved with a function of\n    user-specified width. Choices of convolution function are **boxcar**,\n    **Gaussian** or **sinc**. In the high bandpass option the convolution minus\n    the median of the convolution is subtracted from the original data. The\n    filtered data is copied to a new FITS file with the same structure as the\n    input file.\n\n    Parameters\n    ----------\n    infile : str\n        The name of a MAST standard format FITS file containing Kepler light\n        curve data within the first data extension.\n    passband : str\n        The type of filter to be applied. A low bandpass filter will suppress\n        high-frequency signal shorter than the cutoff. A high bandpass filter\n        will suppress low-frequency signal longer than the cutoff.\n        The options are:\n\n        * low\n        * high\n    outfile : str\n        The name of the output FITS file. The output file is identical in\n        format to the input file. The data to be filtered will be overwritten\n        in the output file by its filtered version.\n    datacol : str\n        The name of the data column in the input FITS file to be filtered, e.g.\n        SAP_FLUX, PDCSAP_FLUX, MOM_CENTR1 etc. A full list of\n        archived data columns is provided in the Kepler Archive Manual.\n    function : string\n        The functional form of the bandpass convolution function.\n        The options are:\n\n        * boxcar\n        * gauss\n        * sinc\n    cutoff : float\n        The frequency of the bandpass cutoff in units of days-1.\n    plot : bool\n        Plot the original light curve and the result of the filter?\n    overwrite : bool\n        Overwrite the output file? if overwrite is **False** and an existing\n        file has the same name as outfile then the task will stop with an\n        error.\n    verbose : bool\n        Print informative messages and warnings to the shell and logfile?\n    logfile : str\n        Name of the logfile containing error and warning messages.\n\n    Examples\n    --------\n\n    .. code-block :: bash\n\n        $ kepfilter kplr002436324-2009259160929_llc.fits --datacol 'SAP_FLUX' --function 'boxcar'\n        --plot --verbose --overwrite\n\n    .. image :: ../_static/images/api/kepfilter.png\n        :align: center\n    \"\"\"\n    if outfile is None:\n        outfile = infile.split('.')[0] + \"-{}.fits\".format(__all__[0])\n    ## log the call\n    hashline = '--------------------------------------------------------------'\n    kepmsg.log(logfile, hashline, verbose)\n    call = ('KEPFILTER -- '\n            + ' infile={}'.format(infile)\n            + ' outfile={}'.format(outfile)\n            + ' datacol={}'.format(datacol)\n            + ' function={}'.format(function)\n            + ' cutoff={}'.format(cutoff)\n            + ' passband={}'.format(passband)\n            + ' plot={}'.format(plot)\n            + ' overwrite={}'.format(overwrite)\n            + ' verbose={}'.format(verbose)\n            + ' logfile={}'.format(logfile))\n    kepmsg.log(logfile, call+'\\n', verbose)\n    ## start time\n    kepmsg.clock('KEPFILTER started at',logfile,verbose)\n    ## overwrite output file\n    if overwrite:\n        kepio.overwrite(outfile, logfile, verbose)\n    if kepio.fileexists(outfile):\n        errmsg = 'ERROR -- KEPFILTER: {} exists. Use --overwrite'.format(outfile)\n        kepmsg.err(logfile, message, verbose)\n\n    ## open input file\n    instr = pyfits.open(infile, 'readonly')\n    tstart, tstop, bjdref, cadence = kepio.timekeys(instr, infile,\n                                                    logfile, verbose)\n    try:\n        work = instr[0].header['FILEVER']\n        cadenom = 1.0\n    except:\n        cadenom = cadence\n\n    ## fudge non-compliant FITS keywords with no values\n    instr = kepkey.emptykeys(instr, infile, logfile, verbose)\n    ## read table structure\n    table = kepio.readfitstab(infile, instr[1], logfile, verbose)\n    # read time and flux columns\n    barytime = kepio.readtimecol(infile, table, logfile, verbose)\n    flux= kepio.readsapcol(infile, table, logfile, verbose)\n    # filter input data table\n    try:\n        nanclean = instr[1].header['NANCLEAN']\n    except:\n        naxis2 = 0\n        for i in range(len(table.field(0))):\n            if (np.isfinite(barytime[i]) and np.isfinite(flux[i])\n                and flux[i] != 0.0):\n                table[naxis2] = table[i]\n                naxis2 += 1\n        instr[1].data = table[:naxis2]\n        kepkey.new('NANCLEAN', True, 'NaN cadences removed from data',\n                   instr[1], outfile, logfile, verbose)\n\n    ## read table columns\n    intime = (kepio.readtimecol(infile, instr[1].data, logfile, verbose)\n              + bjdref)\n    indata = kepio.readfitscol(infile, instr[1].data, datacol, logfile,\n                               verbose) / cadenom\n    ## define data sampling\n    tr = 1.0 / (cadence / 86400)\n    timescale = 1.0 / (cutoff / tr)\n    ## define convolution function\n    if function == 'boxcar':\n        filtfunc = np.ones(int(np.ceil(timescale)))\n    elif function == 'gauss':\n        timescale /= 2\n        dx = np.ceil(timescale * 10 + 1)\n        filtfunc = kepfunc.gauss([1.0, dx / 2 - 1.0, timescale],\n                                 np.linspace(0, dx - 1, dx))\n    elif function == 'sinc':\n        dx = np.ceil(timescale * 12 + 1)\n        fx = (np.linspace(0, dx - 1, dx) - dx / 2 + 0.5) / timescale\n        filtfunc = np.sinc(fx)\n\n    filtfunc /= np.sum(filtfunc)\n    ## pad time series at both ends with noise model\n    ave, sigma = (np.mean(indata[:len(filtfunc)]),\n                  np.std(indata[:len(filtfunc)]))\n    padded = np.append(kepstat.randarray(np.ones(len(filtfunc)) * ave,\n                       np.ones(len(filtfunc)) * sigma), indata)\n    ave, sigma = (np.mean(indata[-len(filtfunc):]),\n                  np.std(indata[-len(filtfunc):]))\n    padded = np.append(padded, kepstat.randarray(np.ones(len(filtfunc)) * ave,\n                       np.ones(len(filtfunc)) * sigma))\n    ## convolve data\n    convolved = np.convolve(padded,filtfunc,'same')\n    ## remove padding from the output array\n    if function == 'boxcar':\n        outdata = convolved[len(filtfunc):-len(filtfunc)]\n    else:\n        outdata = convolved[len(filtfunc):-len(filtfunc)]\n    ## subtract low frequencies\n    if passband == 'high':\n        outmedian = np.median(outdata)\n        outdata = indata - outdata + outmedian\n    ## comment keyword in output file\n    kepkey.history(call, instr[0], outfile, logfile, verbose)\n    ## clean up x-axis unit\n    intime0 = float(int(tstart / 100) * 100.0)\n    if intime0 < 2.4e6: intime0 += 2.4e6\n    ptime = intime - intime0\n    xlab = 'BJD $-$ {}'.format(intime0)\n    ## clean up y-axis units\n    pout = indata * 1.0\n    pout2 = outdata * 1.0\n    nrm = len(str(int(np.nanmax(pout)))) - 1\n    pout = pout / 10 ** nrm\n    pout2 = pout2 / 10 ** nrm\n    ylab = '10$^{}$ {}'.format(nrm, 'e$^-$ s$^{-1}$')\n    ## data limits\n    xmin = ptime.min()\n    xmax = ptime.max()\n    ymin = np.nanmin(pout)\n    ymax = np.nanmax(pout)\n    xr = xmax - xmin\n    yr = ymax - ymin\n    ptime = np.insert(ptime, [0], [ptime[0]])\n    ptime = np.append(ptime, [ptime[-1]])\n    pout = np.insert(pout, [0], [0.0])\n    pout = np.append(pout, 0.0)\n    pout2 = np.insert(pout2, [0], [0.0])\n    pout2 = np.append(pout2, 0.0)\n    ## plot light curve\n    if plot:\n        plt.figure()\n        plt.clf()\n\n        ## plot filtered data\n        ax = plt.axes([0.06, 0.1, 0.93, 0.87])\n        plt.gca().xaxis.set_major_formatter(plt.ScalarFormatter(useOffset=False))\n        plt.gca().yaxis.set_major_formatter(plt.ScalarFormatter(useOffset=False))\n        plt.plot(ptime, pout, color='#ff9900', linestyle='-', linewidth=1.0)\n        plt.fill(ptime, pout, color='#ffff00', linewidth=0.0, alpha=0.2)\n        if passband == 'low':\n            plt.plot(ptime[1:-1], pout2[1:-1], color='#0000ff', linestyle='-',\n                     linewidth=1.0)\n        else:\n            plt.plot(ptime, pout2, color='#0000ff', linestyle='-',\n                     linewidth=1.0)\n            plt.fill(ptime, pout2, color='#0000ff', linewidth=0.0, alpha=0.2)\n        plt.xlabel(xlab, {'color' : 'k'})\n        plt.ylabel(ylab, {'color' : 'k'})\n        plt.xlim(xmin-xr*0.01,xmax+xr*0.01)\n        if ymin >= 0.0:\n            plt.ylim(ymin-yr*0.01,ymax+yr*0.01)\n        else:\n            plt.ylim(1.0e-10,ymax+yr*0.01)\n        plt.grid()\n        # render plot\n        plt.show()\n    ## write output file\n    print(\"Writing output file {}...\".format(outfile))\n    for i in tqdm(range(len(outdata))):\n        instr[1].data.field(datacol)[i] = outdata[i]\n    instr.writeto(outfile)\n    ## close input file\n    instr.close()\n    ## end time\n    kepmsg.clock('KEPFILTER completed at', logfile, verbose)\n\ndef kepfilter_main():\n    import argparse\n\n    parser = argparse.ArgumentParser(\n             description='Low bandpass or high bandpass signal filtering',\n             formatter_class=PyKEArgumentHelpFormatter)\n    parser.add_argument('infile', help='Name of input file', type=str)\n    parser.add_argument('--passband', help='low- or high-bandpass filter',\n                        type=str, choices=['low','high'])\n    parser.add_argument('--outfile',\n                        help=('Name of FITS file to output.'\n                              ' If None, outfile is infile-kepfilter.'),\n                        default=None)\n    parser.add_argument('--datacol', default='SAP_FLUX',\n                        help='Name of data column', type=str)\n    parser.add_argument('--function', default='boxcar',\n                        help='The bandpass convolution function', type=str,\n                        choices=['boxcar','gauss','sinc'])\n    parser.add_argument('--cutoff', default=1.0,\n                        help='Characteristic frequency cutoff of filter [1/days]',\n                        type=float)\n    parser.add_argument('--plot', action='store_true',\n                        help='Plot result?')\n    parser.add_argument('--overwrite', action='store_true',\n                        help='Overwrite output file?')\n    parser.add_argument('--verbose', action='store_true',\n                        help='Write to a log file?')\n    parser.add_argument('--logfile', help='Name of ascii log file',\n                        default='kepfilter.log', type=str)\n    args = parser.parse_args()\n    kepfilter(args.infile, args.passband, args.outfile, args.datacol,\n              args.function, args.cutoff, args.plot, args.overwrite,\n              args.verbose, args.logfile)\n", "meta": {"hexsha": "a90e819072ea4b006570b47d0def581856ca0950", "size": 11104, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyke/kepfilter.py", "max_stars_repo_name": "ecalifornica/pyke", "max_stars_repo_head_hexsha": "6a3fcc0513cf012044e4420cc4d17064e582d142", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyke/kepfilter.py", "max_issues_repo_name": "ecalifornica/pyke", "max_issues_repo_head_hexsha": "6a3fcc0513cf012044e4420cc4d17064e582d142", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-07-25T19:23:05.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-25T19:23:05.000Z", "max_forks_repo_path": "pyke/kepfilter.py", "max_forks_repo_name": "mirca/PyKE", "max_forks_repo_head_hexsha": "6a3fcc0513cf012044e4420cc4d17064e582d142", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3781818182, "max_line_length": 97, "alphanum_fraction": 0.5880763689, "include": true, "reason": "import numpy,from astropy", "num_tokens": 2873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.3208212943308302, "lm_q1q2_score": 0.18035819265655886}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"Class holding a set of TwoDSpectra\n\n\n\n    Class Details\n    -------------\n\n\"\"\"\nimport numbers\n\n#import h5py\n#import matplotlib.pyplot as plt  \nimport numpy\n\nfrom ..core.time import TimeAxis\nfrom ..core.valueaxis import ValueAxis\nfrom ..core.frequency import FrequencyAxis\nfrom ..core.dfunction import DFunction\n#from .twod2 import TwoDResponse\nfrom .twod import TwoDSpectrum\n\nfrom ..core.managers import Manager, energy_units\n\n#from ..core.managers import energy_units\nfrom .. import COMPLEX\nfrom .. import REAL\n\nfrom ..core.saveable import Saveable\n\nfrom .. import part_REAL, part_IMAGINARY, part_COMPLEX, part_ABS\nfrom .. import signal_TOTL #, signal_REPH, signal_NONR\n\n\nclass TwoDResponseContainer(Saveable):\n    \"\"\"Class holding a set of TwoDSpectra\n    \n\n    Parameters\n    ----------\n    \n    t2axis: TimeAxis\n       object holding waiting times at which spectra are calculated\n       \n    keep_pathways: bool\n       if set True, the container will keep all types of Liouville pathways\n       stored separately\n       \n    keep_stypes: bool\n       if se t True, the container will keep rephasing and non-rephasing \n       spectra stored separately\n       \n       \n    \"\"\"\n    \n    def __init__(self, t2axis=None, keep_pathways=False, keep_stypes=True):\n        \n        self.t2axis = t2axis\n        self.keep_pathways = keep_pathways\n        self.keep_stypes = keep_stypes\n        \n        self.axis = None\n        \n        self.itype = None\n        self.index = 0\n        self.tags = []\n        \n        if self.keep_pathways:\n            raise Exception(\"Container keeping pathways not available yet\")\n            \n        self.spectra = {}\n        self._which = None\n        \n        if t2axis is not None:\n            self.use_indexing_type(itype=t2axis)\n        \n        \n    def use_indexing_type(self, itype):\n        \"\"\"Sets the type of indices used to identify spectra\n        \n        Parameters\n        ----------\n        \n        itype : string, ValueAxis, TimeAxis, FrequencyAxis\n            Type of indexig. If itype is a string, it should have values\n            either 'integer' or 'string' in which case the specra will be \n            stored by integer index or by string (as in dictionary). If \n            itype is a ValueAxis (TimeAxis, FrequencyAxis), spectra will\n            be indexed by the values in the axis object.\n        \n        \"\"\"\n        \n        if isinstance(itype, str):\n            if itype == \"integer\":\n                self.itype = \"integer\"\n            elif itype == \"string\":\n                self.itype = \"string\"\n            else:\n                raise Exception(\"Unknown indexing type\")\n        elif isinstance(itype, ValueAxis):\n            if isinstance(itype, TimeAxis):\n                self.itype = \"TimeAxis\"\n                self.axis = itype\n                # This axis must FFT in the \"standard\" way \n                # -- it must of the \"complete\" type \n                self.axis.atype = \"complete\" \n            elif isinstance(itype, FrequencyAxis):\n                self.itype = \"FrequencyAxis\"\n                self.axis = itype\n            else:\n                self.itype = \"ValueAxis\"\n                self.axis = itype\n        else:\n            raise Exception(\"Unknown indexing type\")\n        \n\n    def set_spectrum(self, spect, tag=None):\n        \"\"\"Stores spectrum with a tag (time, index, etc.)\n        \n        Stores the spectrum according to present indexing scheme\n        \n        Parameters\n        ----------\n        \n        spect : TwoDSpectrum\n            Object holding the spectrum; when not tag is specified for a\n            spectrum which as its t2 time set, the tag is set to t2 time.\n            \n        tag : {int, string, ValuesAxis, TimeAxis, FrequencyAxis}\n            Tag which will be used for retrieval of the spectrum from \n            the container.\n        \n        \"\"\"\n        \n        \n        if self.itype == \"integer\":\n            \n            if tag is None:\n                self.spectra[self.index] = spect\n                self.index += 1\n                return self.index\n            else:\n                if isinstance(tag, numbers.Integral):\n                    self.spectra[tag] = spect\n                else:\n                    raise Exception(\"The spectrum has to be tagged by an integer\")\n                return tag\n        \n        elif self.itype in [\"ValueAxis\", \"TimeAxis\", \"FrequencyAxis\"]:\n            \n            if tag is None:\n                # we will read the spectrum intrinsic t2 time and set it as tag\n                if spect.t2 >= 0.0:\n                    tag = spect.t2\n                    \n            if tag is not None:\n                if tag in self.axis.data:\n                    self.spectra[tag] = spect\n                    self.tags.append(tag)\n                    self.index += 1\n                else:\n                    raise Exception(\"Tag not compatible with the ValueAxis\")\n            else:\n                raise Exception(\"No tag specified, and spectrum\"\n                                +\" does not have t2 time set\"\n                                +\" - cannot store spectrum\")\n            return self.index\n        \n        elif self.itype == \"string\":\n            if tag is not None:\n                stag = str(tag)\n                self.spectra[stag] = spect\n                self.tags.append(stag)\n                self.index += 1\n            else:\n                raise Exception(\"No tag specified - cannot store spectrum\")\n            return self.index\n\n        else:\n            \n            raise Exception(\"Unknown type of indexing\")    \n\n\n    def _lousy_equal(self, x1, x2, dx, frac=0.25):\n        \"\"\"Equals up to fraction of dx\n        \n        This function returns True if x1 is closer to x2 than `frac` of \n        a specified interval. In addition it saves the value of x2 to which\n        x1 is equal in the attribute _which of the present class.\n        \n        \n        \"\"\"\n        if abs(x1-x2) < dx*frac: \n            self._which = x2\n            return True\n        \n        self._which = None\n        return False\n\n\n    def get_spectrum_by_index(self, indx):\n        \"\"\"Returns spectrum by integet index\n        \n        The integer index is assigned to all spectra in the order they were\n        saved to the container. They can be retrieved in this order\n        \n        Parameters\n        ----------\n        \n        indx : int\n            Index of the spectrum to be retrieved\n            \n        \"\"\"\n        \n        if self.itype == \"integer\":\n            \n            return self.get_spectrum(indx)\n        \n        else:\n\n            return self.spectra[self.tags[indx]]\n\n\n    def get_response(self, tag):\n        \"\"\"Same as get_spectrum, but the name more sense for a response container\n        \n        \"\"\"\n        return self.get_spectrum(tag)\n\n\n    def get_spectrum(self, tag):\n        \"\"\"Returns spectrum corresponing to time t2\n        \n        Checks if the time t2 is present in the t2axis\n        \n        Parameters\n        ----------\n        \n        t2 : float\n            Waiting time for which spectrum should be returned\n            \n            \n        \"\"\"        \n        if self.itype in [\"integer\"]:\n            \n            return self.spectra[tag]\n            \n        elif self.itype in [\"string\"]:\n            \n            return self.spectra[str(tag)]\n\n        elif self.itype in [\"ValueAxis\", \"TimeAxis\", \"FrequencyAxis\"]:\n            \n            with energy_units(\"int\"):\n                if any(self._lousy_equal(tag, li, self.axis.step) \n                   for li in self.axis.data):\n    \n                    try:\n                        return self.spectra[self._which]     \n                    except KeyError:\n                        print(self.spectra)\n                        raise Exception()      \n                else:\n                    raise Exception(\"Tag not compatible with the ValueAxis\")\n            \n        else:\n            \n            raise Exception(\"Unknown type of indexing\")\n\n    \n    def set_data_flag(self, flag):\n        \"\"\"Sets data flag for all spectra in the container\n        \n        \n        \"\"\"\n        \n        for tag in self.spectra:\n            \n            sp = self.spectra[tag]\n            sp.set_data_flag(flag)\n\n\n    def get_TwoDSpectrumContainer(self, stype=signal_TOTL):\n        \"\"\"Returns a container with specific spectra\n        \n        \"\"\"\n        if self.itype in [\"ValueAxis\", \"TimeAxis\", \"FrequencyAxis\"]:\n            axis = self.axis.deepcopy()\n        \n            cont = TwoDSpectrumContainer(axis)\n        \n            for val in self.axis.data:\n                sp = self.get_spectrum(val)\n                nsp = sp.get_TwoDSpectrum(dtype=stype)\n                cont.set_spectrum(nsp, tag=val)\n                \n            return cont\n        \n        else:\n            \n            raise Exception(\"\")\n            \n\n    def get_nearest(self, val):\n        \n        if self.itype == \"FrequencyAxis\":\n            #print(Manager().current_units[\"frequency\"])\n            #print(Manager().current_units[\"energy\"])\n            nval = Manager().convert_energy_2_internal_u(val)\n            # get tags and convert them to numbers\n            ntags = numpy.zeros(len(self.tags), dtype=REAL)\n            k = 0\n            for stag in self.tags:\n                #print(stag)\n                ntag = float(stag)\n                ntags[k] = ntag\n                k += 1\n            dtags = numpy.abs(ntags - nval)\n            imin = numpy.argmin(dtags)\n            #print(\"Returning spectrum at: \", \n            #      Manager().convert_energy_2_current_u(self.tags[imin]))\n            return self.spectra[self.tags[imin]], imin\n            \n\n    def length(self):\n        \"\"\"Returns the length of the container\n        \n        \n        \"\"\"\n        return len(self.spectra.keys())\n\n\n    def get_spectra(self, start=None, end=None):\n        \"\"\"Returns a list of the calculated spectra\n        \n        Returns all spectra or an interval of spectra when `start` and `end`\n        are specified\n        \n        Parameters\n        ----------\n        \n        start : int\n            Index of the first spectrum to be returned\n            \n        end : int\n            Index of the last spectrum to be returned\n\n        \"\"\"\n        \n        ven = [value for (key, value) in sorted(self.spectra.items())]\n        \n        if (start is None) and (end is None): \n            return ven\n        else:\n            ven2 = []\n            vkeys = [key for (key, value) in sorted(self.spectra.items())]\n            for k in vkeys:\n                if k >= start and k <= end:\n                    ven2.append(self.spectra[k])\n            return ven2\n\n        \n    def get_PumpProbeSpectrumContainer(self, skip=0):\n        \"\"\"Converts this container into PumpProbeSpectrumContainer\n        \n        \"\"\"\n        \n        from .pumpprobe import PumpProbeSpectrumContainer\n        \n        k = 0\n        ppc = []\n        ttc = []\n        ii = 0\n        for sp in self.get_spectra():\n            if k == 0:\n                pp = sp.get_PumpProbeSpectrum()\n                ppc.append(pp)\n                ttc.append(self.axis.data[ii])\n            k += 1\n            if k > skip:\n                k = 0\n            ii += 1\n            \n        length = len(ppc)\n        start = ppc[0].get_t2()\n        step = ppc[1].get_t2()-start\n\n        naxis = TimeAxis(start,length,step)        \n        ppcont = PumpProbeSpectrumContainer(t2axis=naxis)\n        ppcont.itype = self.itype\n\n        ii = 0\n        for sp in ppc:\n            tt = ttc[ii]\n            ppcont.set_spectrum(sp, tt)\n            ii += 1\n            \n        return ppcont\n\n\n    def get_integrated_area_evolution(self, times, area, dpart=part_REAL):\n        \"\"\"Returns the integrated area of the 2D spectra as a function of their index\n\n        \"\"\"\n        vals = numpy.zeros(times.length, dtype=COMPLEX)\n        k = 0\n  \n        # this only acts on Frequency axis\n        with energy_units(\"int\"):\n            tms = times.data      \n  \n        for t2 in tms:\n            \n            sp = self.get_spectrum(t2)\n            vals[k] = sp.get_area_integral(area, dpart=part_REAL)\n            k +=1\n            \n        return DFunction(times, vals)        \n\n    \n    def get_point_evolution(self, x, y, times):\n        \"\"\"Tracks an evolution of a single point on the 2D spectrum\n        \n        \n        Parameters\n        ----------\n        \n        x : float\n            x coordinate in the 2D spectrum (usually omega_1 axis)\n\n        y : float\n            y coordinate in the 2D spectrum (usually omega_3 axis)\n            \n        times : ValueAxis\n            Times (usually waiting t_2 times) in which spectra are taken\n            \n        \"\"\"\n\n        vals = numpy.zeros(times.length, dtype=COMPLEX)\n        k = 0\n  \n        # this only acts on Frequency axis\n        with energy_units(\"int\"):\n            tms = times.data      \n  \n        for t2 in tms:\n            \n            sp = self.get_spectrum(t2)\n            vals[k] = sp.get_value_at(x, y)\n            k +=1\n            \n        return DFunction(times, vals)\n\n    \n    def global_fit_exponential(self, guess=None):\n        \"\"\"Global fit of the data with exponentials\n        \n        \n        \"\"\"\n        from scipy.optimize import least_squares\n        from functools import partial\n        \n        if guess is None:\n            guess = [1.0, 1.0/100.0, 0.0]\n \n        _exp_2D_fcion = partial(_exp_2D_data0, times=self.axis.data, cont=self)\n            \n        params = least_squares(_exp_2D_fcion, guess)           \n        \n        return params\n\n    \n    \n    def fft(self, ffttype=\"complex-positive\", window=None, offset=0.0,\n            dtype=None, dpart=part_COMPLEX, tag=None):\n        \"\"\"Fourier transform in t2 time\n        \n        This method performs FFT on the container data determined by the\n        value of the `dtype` argument. The new container is created and \n        the storage resolution of its components is set `off`. This means\n        that the container and its spectra have no idea about what data they\n        store. Even when plotting the spectra, one has to set plotting of\n        the `total` spectrum.\n        \n        Parameters\n        ----------\n        \n        ffttype : string\n            Specifies the type Fourier transform we perform\n            \n        window : DFunction\n            Windowing function for the data. Default is None\n        \n        \"\"\"\n        \n        if dtype is None:\n            raise Exception(\"Type of the data for FFT has to be specified\")\n            \n        if self.itype not in [\"ValueAxis\", \"TimeAxis\", \"FrequencyAxis\"]:\n            raise Exception(\"FFT cannot be performed for\"+\n                            \" this type of indexing\")\n\n        # even when no window function is supplied, we create one with\n        # all elements equal to one\n        if window is None:\n            winfce = DFunction(self.axis, \n                               numpy.ones(self.axis.length, dtype=REAL))\n        else:\n            winfce = window\n             \n        if isinstance(self.axis, TimeAxis):\n            # restrict the time axis by the off-set\n            tlist = []\n            for tt in self.axis.data:\n                if tt >= offset:\n                    tlist.append(tt)\n            if len(tlist) > 1:\n                dt = tlist[1]-tlist[0]\n                Nt = len(tlist)\n                t0 = tlist[0]\n                # effective time axis for fft\n                eff_axis = TimeAxis(t0, Nt, dt, atype=\"complete\") \n            else:\n                raise Exception(\"Offset too large\")\n        else:\n            eff_axis = self.axis\n            \n        # put all data into one array\n        \n        #raise Exception()\n        self.set_data_flag(dtype)\n        \n        tags = eff_axis.data #self.axis.data\n        Nos = self.length()\n\n        if len(tags) <= Nos:\n            tag1 = eff_axis.data[0] #self.axis.data[0]\n            sp1 = self.get_spectrum(tag1)\n            \n            N1, N2 = sp1.d__data.shape\n            data = numpy.zeros((N1, N2, len(tags)), dtype=sp1.d__data.dtype)\n\n\n            for k_n in range(len(tags)):\n                tag = eff_axis.data[k_n] #self.axis.data[k_n]\n                \n                spect = self.get_spectrum(tag)\n                spect.set_data_flag(dtype)\n                if dpart == part_COMPLEX:\n                    data[:,:,k_n] = spect.d__data\n                elif dpart == part_REAL:\n                    data[:,:,k_n] = numpy.real(spect.d__data)\n                elif dpart == part_IMAGINARY:\n                    data[:,:,k_n] = numpy.imag(spect.d__data)\n                elif dpart == part_ABS:\n                    data[:,:,k_n] = numpy.abs(spect.d__data)\n                    \n            \n        else:\n            raise Exception(\"Number of spectra not consistent\"+\n                            \" with ValueAxis object\")\n            \n        #\n        # FFT of the axis\n        #\n        axis = eff_axis # = self.axis            \n        \n        if isinstance(axis, TimeAxis):\n            axis.shift_to_zero()\n            new_axis = axis.get_FrequencyAxis()\n            \n        elif isinstance(axis, FrequencyAxis):\n            new_axis = axis.get_TimeAxis()\n            \n        else: \n            # this must be ValueAxis\n\n            ftaxdata = (2.0*numpy.pi)*numpy.fft.fftfreq(axis.length,\n                                                        axis.step)\n            ftaxdata = numpy.fft.fftshift(ftaxdata)\n            \n            start = ftaxdata[0]\n            length = len(ftaxdata)\n            step = ftaxdata[1]-ftaxdata[0]\n\n            new_axis = ValueAxis(start, length, step)            \n\n        \n        #\n        # FFT of the data\n        #\n        \n        # window function\n        ftdata = numpy.zeros(data.shape, dtype=data.dtype)\n        Nwin = len(winfce.data)\n        Ndat = data.shape[2]\n        for i_n in range(data.shape[0]):\n            for j_n in range(data.shape[1]):\n                ftdata[i_n,j_n,:] = data[i_n,j_n,:]*winfce.data[Nwin-Ndat:Nwin]\n                \n        ftdata = numpy.fft.ifft(ftdata, axis=2)\n        ftdata = numpy.fft.fftshift(ftdata, axes=2)\n        \n        # save it to a new container\n        new_container = TwoDSpectrumContainer()\n        new_container.use_indexing_type(new_axis)\n\n        for k_n in range(Ndat):\n            tag = new_axis.data[k_n]\n            spect = TwoDSpectrum()\n            spect.set_axis_1(sp1.xaxis)\n            spect.set_axis_3(sp1.yaxis)\n            \n            spect.set_data(ftdata[:, :, k_n], dtype=signal_TOTL)\n\n            new_container.set_spectrum(spect, tag=tag)\n        \n        return new_container\n\n          \n    def _create_root_group(self, start, name):\n        return start.create_group(name)\n\n\n    def _save_axis(self, rt, name, ax):\n        axdir = rt.create_group(name)\n        axdir.attrs.create(\"start\",ax.start)\n        axdir.attrs.create(\"length\",ax.length)\n        axdir.attrs.create(\"step\",ax.step)\n\n\n    def _load_axis(self, rt, name):\n        axdir = rt[name]\n        start = axdir.attrs[\"start\"]\n        length = axdir.attrs[\"length\"]\n        step = axdir.attrs[\"step\"]\n        return TimeAxis(start, length, step) \n\n        \n    def trimall_to(self, window=None):\n        \"\"\"Trims all spectra in the container\n\n        Parameters\n        ----------\n        \n        window: list of floats\n            Window, specified by four float number, to which all spectra\n            in the container should be trimmed\n            \n        \"\"\"\n        if window is not None:\n            axes = window\n            for s in self.get_spectra():\n                s.trim_to(window=axes)\n\n    # FIXME: this is still legacy version        \n    def amax(self, spart=part_REAL):\n        \"\"\"Returns maximum amplitude of the spectra in the container\n        \n        \"\"\"\n        \n\n        mxs = []\n        for s in self.get_spectra():       \n            #spect2D = numpy.real(s.d__data)\n            if spart == part_REAL:\n                spect2D = numpy.real(s.data)\n            elif spart == part_IMAGINARY:\n                spect2D = numpy.imag(s.data)\n            elif spart == part_ABS:\n                spect2D = numpy.abs(s.data)\n            else:\n                raise Exception(\"Unknow part of the spectrum:\", spart)\n            mx = numpy.amax(spect2D)\n            mxs.append(mx)\n        return numpy.amax(numpy.array(mxs))\n        \n\n    # Print iterations progress\n    def _printProgressBar(self, iteration, total, \n                          prefix = '', suffix = '', \n                          decimals = 1, length = 100,\n                          fill='*'):\n        \"\"\"\n        Call in a loop to create terminal progress bar\n        @params:\n            iteration   - Required  : current iteration (Int)\n            total       - Required  : total iterations (Int)\n            prefix      - Optional  : prefix string (Str)\n            suffix      - Optional  : suffix string (Str)\n            decimals    - Optional  : positive number of decimals in percent complete (Int)\n            length      - Optional  : character length of bar (Int)\n            fill        - Optional  : bar fill character (Str)\n            \n        Based on: \n        https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console\n        \"\"\"\n#                          fill = '█'):\n        percent = (\"{0:.\" + str(decimals) + \"f}\").format(100 * (iteration / float(total)))\n        filledLength = int(length * iteration // total)\n        bar = fill * filledLength + '-' * (length - filledLength)\n        print('\\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = '\\r')\n        # Print New Line on Complete\n        if iteration == total: \n            print()\n    \n\n             \n    def make_movie(self, filename, window=None,\n                   stype=signal_TOTL, spart=part_REAL, \n                   cmap=None, \n                   Npos_contours=10,\n                   vmax=None, vmin_ratio=0.5,\n                   xlabel=None,\n                   ylabel=None,\n                   axis_label_font=None,\n                   start=None, end=None,\n                   frate=20, dpi=100, \n                   show_states=None, \n                   show_states_func=None,\n                   label=None,\n                   label_func=None,\n                   text_loc=None,\n                   progressbar=False, \n                   use_t2=True, \n                   title=\"Quantarhei movie\",\n                   comment=\"Created with Quantarhei\"):\n        \"\"\"Creates a movie out of the spectra in the container\n        \n        \n        Parameters\n        ----------\n        \n        Npos_contours : int\n            Nomber of positive value contours in the plot\n            \n        \n        \n        \"\"\"\n        \n        \n        import matplotlib.pyplot as plt\n        import matplotlib.animation as manimation\n        \n        FFMpegWriter = manimation.writers[\"ffmpeg\"]\n\n        metadata = dict(title=title, artist='Quantarhei',\n                comment=comment)\n        writer = FFMpegWriter(fps=frate, metadata=metadata)\n        \n        fig = plt.figure() \n        \n        spctr = self.get_spectra()\n        l = len(spctr)\n        \n        if use_t2 and (spctr[0].get_t2() < 0.0):\n            #print(\"Warning: switching off usage of t2\"\n            #      +\" information obtained from the spectrum object (t2 < 0)\")\n            use_t2 = False\n        \n        if use_t2:\n            last_t2 = spctr[l-1].get_t2()\n            first_t2 = spctr[0].get_t2()\n        \n            if start is None:\n                start = first_t2\n            if end is None:\n                end = last_t2\n\n        if vmax is None:\n            mx = self.amax(spart=spart)\n        else:\n            mx = vmax        \n                \n        with writer.saving(fig, filename, dpi):  \n            k = 0\n            # Initial call to print 0% progress\n            if use_t2:\n                sp2write = self.get_spectra(start=start, end=end)\n            else:\n                sp2write = self.get_spectra()\n            l = len(sp2write)\n            \n            if progressbar:\n                self._printProgressBar(0, l, prefix = 'Progress:',\n                                       suffix = 'Complete', length = 50)\n                                \n            for sp in sp2write: #self.get_spectra(start=start, end=end):\n                \n                if label_func is not None:\n                    (label, text_loc) = label_func(sp)\n                if show_states_func is not None:\n                    show_states = show_states_func(sp)\n\n                sp.plot(fig=fig, window=window, cmap=cmap, vmax=mx,\n                        vmin_ratio=vmin_ratio,\n                        Npos_contours=Npos_contours,\n                        stype=stype,spart=spart,\n                        show_states=show_states,\n                        xlabel=xlabel, ylabel=ylabel,\n                        axis_label_font=axis_label_font,\n                        label=label, text_loc=text_loc) #\"T=\"+str(sp.get_t2())+\"fs\")\n                writer.grab_frame()\n                if progressbar:\n                    self._printProgressBar(k + 1, l, prefix = 'Progress:',\n                                           suffix = 'Complete', length = 50)\n                \n                k += 1\n#                if k == 20:\n#                    return\n\n\ndef _exp_2D_data0(params, times=None, cont=None):\n    \"\"\"Returns a residue between time dependent matrix data and a matrix\n       multipled by a sum of exponentials\n    \n    \"\"\"\n    \n    if times is None:\n        raise Exception(\"Times have to be supplied\")\n    if cont is None:\n        raise Exception(\"Spectra container has to be supplied\")\n        \n    np = len(params)\n    \n    data0 = cont.get_spectrum(0.0)\n    \n    residues = numpy.zeros((times.shape[0], data0.data.shape[0],\n                            data0.data.shape[1]), dtype=data0.dtype)\n    \n    N = times.shape[0]*data0.data.shape[0]*data0.data.shape[0]\n    \n    nexp = int((np - 1)/2)\n    \n    ii = 0\n    for t in times:\n\n        ret = 0.0\n        kp = 0\n\n        for kk in range(nexp):\n            ret += params[kp]*numpy.exp(-params[kp+1]*t)\n            kp += 2\n        ret += params[kp]\n        \n        spect = cont.get_spectrum(t)\n        \n        residues[ii,:,:] = numpy.abs(spect.data - ret*data0.data)\n        \n        ii += 1\n        \n    return residues.reshape(N)\n\n\n\n\n\n\nclass TwoDSpectrumContainer(TwoDResponseContainer):\n    \n    def __init__(self, t2axis=None, dtype=signal_TOTL):\n        \n        self.t2axis = t2axis\n\n        self.axis = None\n        \n        self.itype = None\n        self.index = 0\n        self.tags = []\n        self.dtype = dtype\n            \n        self.spectra = {}\n        self._which = None\n        \n        if t2axis is not None:\n            self.use_indexing_type(itype=t2axis)\n            \n\n    def set_data_flag(self, flag):\n        \"\"\"Sets data flag for all spectra in the container\n        \n        \n        \"\"\"\n        \n        if flag != self.dtype:\n            raise Exception(\"Cannot change spectra type\")\n\n            \n    def get_TwoDSpectrumContainer(self, stype=signal_TOTL):\n        \"\"\"Returns a container with specific spectra\n        \n        \"\"\"\n        if stype == self.dtype:\n            return self\n        else:\n            raise Exception(\"Cannot change spectra type in this container\")\n\n           \n    # FIXME: This needs to be reimplemented\n    def get_PumpProbeSpectrumContainer(self, skip=0):\n        \"\"\"Converts this container into PumpProbeSpectrumContainer\n        \n        \"\"\"\n        \n        if self.dtype == signal_TOTL:\n        \n            from .pumpprobe import PumpProbeSpectrumContainer\n            \n            k = 0\n            ppc = []\n            ttc = []\n            ii = 0\n            for sp in self.get_spectra():\n                if k == 0:\n                    pp = sp.get_PumpProbeSpectrum()\n                    ppc.append(pp)\n                    ttc.append(self.axis.data[ii])\n                k += 1\n                if k > skip:\n                    k = 0\n                ii += 1\n                \n            length = len(ppc)\n            start = ppc[0].get_t2()\n            step = ppc[1].get_t2()-start\n    \n            naxis = TimeAxis(start,length,step)        \n            ppcont = PumpProbeSpectrumContainer(t2axis=naxis)\n    \n            ii = 0\n            for sp in ppc:\n                tt = ttc[ii]\n                ppcont.set_spectrum(sp, tt)\n                ii += 1\n                \n            return ppcont  \n        \n        else:\n            \n            raise Exception(\"Cannot calculate Pump-probe from 2D\"+\n                            \" spectra of type\"+self.dtype)\n            \n    def normalize2(self, norm=1.0, each=False, dpart=part_REAL):\n        \"\"\"Normalize the whole container of spectra\n        \n        Normalization of the whole container so that the maximum\n        value of the spectrum is equal to the `norm`.\n        \n        Parameters\n        ----------\n        \n        norm : float\n            Value to which we normalize the spectra\n            \n        each: bool\n            If False, we normalize the global maximum of the container, i.e.\n            a maximum accross whole spectra. if True, each spectrum is\n            normalized individually against its own maximum.\n            \n        dpart: string\n            Part of the spectrum from which the maximum is calculated, it\n            can be part_REAL, part_IMAGINARY or part_ABS. The values of these\n            constants are defined in the highest level of namespace in\n            Quantarhei.\n        \n        \"\"\"\n        \n        nsp = len(self.spectra)\n        mxs = numpy.zeros(nsp, dtype=REAL)\n        ii = 0\n        for tag in self.spectra.keys():\n            sp = self.get_spectrum(tag)\n            mxs[ii] = sp.get_max_value(dpart=dpart)\n            ii += 1\n            \n        mx = numpy.amax(mxs)\n            \n        nmax = [mx]\n        for tag in self.spectra.keys():\n            sp = self.get_spectrum(tag)\n            if each:\n                nmax = [sp.get_max_value(dpart=dpart)]\n            sp.normalize2(norm, dpart=dpart, nmax=nmax)\n            \n        return nmax\n\n            \n    def fft(self, ffttype=\"complex-positive\", window=None, offset=0.0,\n            dtype=None, dpart=part_COMPLEX, tag=None):\n        \"\"\"Fourier transform in t2 time\n        \n        This method performs FFT on the container data determined by the\n        value of the `dtype` argument. The new container is created and \n        the storage resolution of its components is set `off`. This means\n        that the container and its spectra have no idea about what data they\n        store. Even when plotting the spectra, one has to set plotting of\n        the `total` spectrum.\n        \n        Parameters\n        ----------\n        \n        ffttype : string\n            Specifies the type Fourier transform we perform\n            \n        window : DFunction\n            Windowing function for the data. Default is None\n        \n        \"\"\"\n        \n        if dtype is not None:\n            if dtype != self.dtype:\n                raise Exception(\"Cannot change spectra type\"+\n                                \" in TwoDSpectrumContainer\")\n                \n        if self.itype not in [\"ValueAxis\", \"TimeAxis\", \"FrequencyAxis\"]:\n            raise Exception(\"FFT cannot be performed for\"+\n                            \" this type of indexing\")\n\n        # even when no window function is supplied, we create one with\n        # all elements equal to one\n        if window is None:\n            winfce = DFunction(self.axis, \n                               numpy.ones(self.axis.length, dtype=REAL))\n        else:\n            winfce = window\n             \n        if isinstance(self.axis, TimeAxis):\n            # restrict the time axis by the off-set\n            tlist = []\n            for tt in self.axis.data:\n                if tt >= offset:\n                    tlist.append(tt)\n            if len(tlist) > 1:\n                dt = tlist[1]-tlist[0]\n                Nt = len(tlist)\n                t0 = tlist[0]\n                # effective time axis for fft\n                eff_axis = TimeAxis(t0, Nt, dt, atype=\"complete\") \n            else:\n                raise Exception(\"Offset too large\")\n        else:\n            eff_axis = self.axis\n            \n        # put all data into one array\n        \n        #raise Exception()\n        \n        tags = eff_axis.data #self.axis.data\n        Nos = self.length()\n\n        if len(tags) <= Nos:\n            tag1 = eff_axis.data[0] #self.axis.data[0]\n            sp1 = self.get_spectrum(tag1)\n            \n            N1, N2 = sp1.data.shape\n            data = numpy.zeros((N1, N2, len(tags)), dtype=sp1.data.dtype)\n\n\n            for k_n in range(len(tags)):\n                tag = eff_axis.data[k_n] #self.axis.data[k_n]\n                \n                spect = self.get_spectrum(tag)\n\n                if dpart == part_COMPLEX:\n                    data[:,:,k_n] = spect.data\n                elif dpart == part_REAL:\n                    data[:,:,k_n] = numpy.real(spect.data)\n                elif dpart == part_IMAGINARY:\n                    data[:,:,k_n] = numpy.imag(spect.data)\n                elif dpart == part_ABS:\n                    data[:,:,k_n] = numpy.abs(spect.data)\n                    \n            \n        else:\n            raise Exception(\"Number of spectra not consistent\"+\n                            \" with ValueAxis object\")\n            \n        #\n        # FFT of the axis\n        #\n        axis = eff_axis # = self.axis            \n        \n        if isinstance(axis, TimeAxis):\n            axis.shift_to_zero()\n            new_axis = axis.get_FrequencyAxis()\n            \n        elif isinstance(axis, FrequencyAxis):\n            new_axis = axis.get_TimeAxis()\n            \n        else: \n            # this must be ValueAxis\n\n            ftaxdata = (2.0*numpy.pi)*numpy.fft.fftfreq(axis.length,\n                                                        axis.step)\n            ftaxdata = numpy.fft.fftshift(ftaxdata)\n            \n            start = ftaxdata[0]\n            length = len(ftaxdata)\n            step = ftaxdata[1]-ftaxdata[0]\n\n            new_axis = ValueAxis(start, length, step)            \n\n        \n        #\n        # FFT of the data\n        #\n        \n        # window function\n        ftdata = numpy.zeros(data.shape, dtype=data.dtype)\n        Nwin = len(winfce.data)\n        Ndat = data.shape[2]\n        for i_n in range(data.shape[0]):\n            for j_n in range(data.shape[1]):\n                ftdata[i_n,j_n,:] = data[i_n,j_n,:]*winfce.data[Nwin-Ndat:Nwin]\n                \n        ftdata = numpy.fft.ifft(ftdata, axis=2)\n        ftdata = numpy.fft.fftshift(ftdata, axes=2)\n        \n        # save it to a new container\n        new_container = TwoDSpectrumContainer()\n        new_container.use_indexing_type(new_axis)\n\n        for k_n in range(Ndat):\n            tag = new_axis.data[k_n]\n            spect = TwoDSpectrum()\n            spect.set_axis_1(sp1.xaxis)\n            spect.set_axis_3(sp1.yaxis)\n            \n            spect.set_data(ftdata[:, :, k_n], dtype=self.dtype)\n\n            new_container.set_spectrum(spect, tag=tag)\n        \n        return new_container\n\n\n    def unitedir(self, dname):\n        \n        clist = self.loaddir(dname)\n\n        n = len(clist)\n\n        cont = clist[1]\n        \n        for k in range(1, n):\n            \n            ctn = clist[k+1]\n            \n            for tag in ctn.spectra:\n                cont.set_spectrum(ctn.spectra[tag], tag=tag)\n                \n        return cont\n\n        ", "meta": {"hexsha": "b74b09adef48b5450faae21734dd0170c8d718de", "size": 35681, "ext": "py", "lang": "Python", "max_stars_repo_path": "quantarhei/spectroscopy/twodcontainer.py", "max_stars_repo_name": "slamavl/quantarhei", "max_stars_repo_head_hexsha": "d822bc2db86152c418e330a9152e7866869776f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2016-10-16T13:26:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T11:40:52.000Z", "max_issues_repo_path": "quantarhei/spectroscopy/twodcontainer.py", "max_issues_repo_name": "slamavl/quantarhei", "max_issues_repo_head_hexsha": "d822bc2db86152c418e330a9152e7866869776f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 61, "max_issues_repo_issues_event_min_datetime": "2016-09-19T10:45:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-10T13:53:06.000Z", "max_forks_repo_path": "quantarhei/spectroscopy/twodcontainer.py", "max_forks_repo_name": "slamavl/quantarhei", "max_forks_repo_head_hexsha": "d822bc2db86152c418e330a9152e7866869776f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2016-08-30T09:09:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T03:16:35.000Z", "avg_line_length": 30.9462272333, "max_line_length": 91, "alphanum_fraction": 0.496510748, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.18033809465473488}}
{"text": "from collections import OrderedDict\nimport numpy as np\nimport os\nfrom hazel.atmosphere import General_atmosphere\nfrom hazel.util import i0_allen\nfrom hazel.codes import sir_code\nfrom hazel.io import Generic_SIR_file\nimport scipy.interpolate as interp\nfrom hazel.exceptions import NumericalErrorSIR\nfrom hazel.transforms import transformed_to_physical, jacobian_transformation\n\ntry:\n    from hazel.forward_nn import Forward\nexcept:\n    pass\n\n\n__all__ = ['SIR_atmosphere']\n\n# sir_parameters = OrderedDict.fromkeys('T B thetaB phiB v')\n\nclass SIR_atmosphere(General_atmosphere):\n    def __init__(self, working_mode, name='', root='', verbose=0):\n        \n        super().__init__('photosphere', name=name)\n\n        self.ff = 1.0        \n        self.macroturbulence = np.zeros(1)\n        self.working_mode = working_mode\n        self.graphnet_nlte = None\n        self.root = root\n        \n        self.parameters['T'] = None\n        self.parameters['vmic'] = None\n        self.parameters['v'] = None\n        self.parameters['Bx'] = None\n        self.parameters['By'] = None\n        self.parameters['Bz'] = None\n        self.parameters['ff'] = None\n        self.parameters['vmac'] = None\n\n        self.nodes_location['T'] = None\n        self.nodes_location['vmic'] = None\n        self.nodes_location['v'] = None\n        self.nodes_location['Bx'] = None\n        self.nodes_location['By'] = None\n        self.nodes_location['Bz'] = None\n        self.nodes_location['ff'] = None\n        self.nodes_location['vmac'] = None\n\n        self.n_nodes['T'] = 0\n        self.n_nodes['vmic'] = 0\n        self.n_nodes['v'] = 0\n        self.n_nodes['Bx'] = 0\n        self.n_nodes['By'] = 0\n        self.n_nodes['Bz'] = 0\n        self.n_nodes['ff'] = 0\n        self.n_nodes['vmac'] = 0\n\n        self.nodes['T'] = 0\n        self.nodes['vmic'] = 0\n        self.nodes['v'] = 0\n        self.nodes['Bx'] = 0\n        self.nodes['By'] = 0\n        self.nodes['Bz'] = 0\n        self.nodes['ff'] = 0\n        self.nodes['vmac'] = 0\n\n        self.rf_analytical = OrderedDict()\n        self.rf_analytical['T'] = None\n        self.rf_analytical['vmic'] = None\n        self.rf_analytical['v'] = None\n        self.rf_analytical['Bx'] = None\n        self.rf_analytical['By'] = None\n        self.rf_analytical['Bz'] = None\n        self.rf_analytical['ff'] = None\n        self.rf_analytical['vmac'] = None\n\n        self.ranges['T'] = None\n        self.ranges['vmic'] = None\n        self.ranges['v'] = None\n        self.ranges['Bx'] = None\n        self.ranges['By'] = None\n        self.ranges['Bz'] = None\n        self.ranges['ff'] = None\n        self.ranges['vmac'] = None\n\n        self.cycles['T'] = None\n        self.cycles['vmic'] = None\n        self.cycles['v'] = None\n        self.cycles['Bx'] = None\n        self.cycles['By'] = None\n        self.cycles['Bz'] = None\n        self.cycles['ff'] = None\n        self.cycles['vmac'] = None\n\n        self.epsilon['T'] = 0.01\n        self.epsilon['vmic'] = 0.01\n        self.epsilon['v'] = 0.01\n        self.epsilon['Bx'] = 0.01\n        self.epsilon['By'] = 0.01\n        self.epsilon['Bz'] = 0.01\n        self.epsilon['ff'] = 0.01\n        self.epsilon['vmac'] = 0.01\n\n        self.regularization['T'] = None\n        self.regularization['vmic'] = None\n        self.regularization['v'] = None\n        self.regularization['Bx'] = None\n        self.regularization['By'] = None\n        self.regularization['Bz'] = None\n        self.regularization['ff'] = None\n        self.regularization['vmac'] = None\n\n        self.verbose = verbose\n        \n        \n    def list_lines(self):\n        \"\"\"\n        List the lines available in SIR for synthesis\n            \n        \"\"\"\n        f = open('LINEAS', 'r')\n        lines = f.readlines()\n        f.close()\n\n        print(\"Available lines:\")\n        for l in lines[:-1]:\n            print(l[:-1])\n\n    def add_active_line(self, lines, spectrum, wvl_range, verbose):\n        \"\"\"\n        Add an active lines in this atmosphere\n        \n        Parameters\n        ----------\n        lines : str\n            Line to activate\n        spectrum : Spectrum\n            Spectrum object\n        wvl_range : float\n            Vector containing wavelength range over which to synthesize this line\n        \n        Returns\n        -------\n        None\n    \n        \"\"\"\n        \n        self.lines = lines        \n        self.wvl_range_lambda = wvl_range\n\n        ind_low = (np.abs(spectrum.wavelength_axis - wvl_range[0])).argmin()\n        ind_top = (np.abs(spectrum.wavelength_axis - wvl_range[1])).argmin()\n\n        self.spectrum = spectrum\n        self.wvl_axis = spectrum.wavelength_axis[ind_low:ind_top+1]\n        self.wvl_range = np.array([ind_low, ind_top+1])\n\n        # Check if Ca II 8542 is in the list of lines and instantiate the neural networks\n        if (self.nlte):            \n            if 301 in self.lines:\n                if self.graphnet_nlte is None:                    \n                    path = str(__file__).split('/')\n                    checkpoint = '/'.join(path[0:-1])+'/data/20211114-131045_best.prd.pth'\n                    if (verbose >= 1):\n                        self.logger.info('    * Reading NLTE Neural Network')\n                    self.graphnet_nlte = Forward(checkpoint=checkpoint, verbose=verbose)\n                                        \n    def interpolate_nodes(self, log_tau, reference, nodes):\n        \"\"\"\n        Generate a model atmosphere by interpolating the defined nodes. The interpolation\n        order depends on the number of nodes.\n        \n        Parameters\n        ----------\n        log_tau : float\n            Vector of log optical depth at 500 nm\n        reference : float\n            Vector with the reference atmosphere to which the nodes are added\n        nodes : float\n            List with the position of the nodes\n\n        Returns\n        -------\n        real\n            Vector with the interpolated atmosphere\n    \n        \"\"\"\n        n_nodes = len(nodes)\n        n_depth = len(log_tau)\n\n        if (n_nodes == 0):\n            return reference, 0\n        \n        if (n_nodes == 1):\n            return reference + nodes[0], n_depth//2\n\n        # if (n_nodes >= 2):\n        #     # pos = np.linspace(n_depth-1, 0, n_nodes+2, dtype=int)[1:-1]\n        #     pos = np.linspace(n_depth-1, 0, n_nodes, dtype=int)\n        #     f = interp.PchipInterpolator(log_tau[pos], nodes, extrapolate=True)            \n        #     return reference + f(log_tau), pos\n        \n        if (n_nodes == 2):\n            # pos = np.linspace(0, n_depth-1, n_nodes+2, dtype=int)[1:-1]\n            pos = np.linspace(0, n_depth-1, n_nodes, dtype=int)\n            f = interp.interp1d(log_tau[pos], nodes, 'linear', bounds_error=False, fill_value='extrapolate')\n            return reference + f(log_tau), pos\n\n        if (n_nodes == 3):\n            # pos = np.linspace(0, n_depth-1, n_nodes+2, dtype=int)[1:-1]\n            pos = np.linspace(0, n_depth-1, n_nodes, dtype=int)\n            f = interp.interp1d(log_tau[pos], nodes, 'quadratic', bounds_error=False, fill_value='extrapolate')            \n            return reference + f(log_tau), pos\n\n        if (n_nodes > 3):\n            # pos = np.linspace(n_depth-1, 0, n_nodes+2, dtype=int)[1:-1]\n            pos = np.linspace(n_depth-1, 0, n_nodes, dtype=int)\n            f = interp.PchipInterpolator(log_tau[pos], nodes, extrapolate=True)            \n            return reference + f(log_tau), pos\n\n    def interpolate_nodes_rf(self, log_tau, reference, nodes, lower, upper):\n        \"\"\"\n        Generate a model atmosphere by interpolating the defined nodes. The interpolation\n        order depends on the number of nodes.\n        \n        Parameters\n        ----------\n        log_tau : float\n            Vector of log optical depth at 500 nm\n        reference : float\n            Vector with the reference atmosphere to which the nodes are added\n        nodes : float\n            List with the position of the nodes\n\n        Returns\n        -------\n        real\n            Vector with the interpolated atmosphere\n    \n        \"\"\"\n        n_nodes = len(nodes)\n        n_depth = len(log_tau)\n\n        if (n_nodes == 0):\n            return np.zeros(n_depth)\n        \n        if (n_nodes == 1):\n            rf = np.zeros((n_nodes, n_depth))\n\n            tmp0 = reference + nodes[0]\n\n            # Add the Jacobian to each height\n            jacobian = jacobian_transformation(tmp0, lower, upper)\n\n            rf[0,:] = 1.0 * jacobian\n            return rf\n        \n        if (n_nodes == 2):\n            rf = np.zeros((n_nodes, n_depth))\n\n            pos = np.linspace(0, n_depth-1, n_nodes+2, dtype=int)[1:-1]\n            f = interp.interp1d(log_tau[pos], nodes, 'linear', bounds_error=False, fill_value='extrapolate')\n\n            tmp0 = reference + f(log_tau)\n\n            jacobian = jacobian_transformation(tmp0, lower, upper)\n\n            delta = 1e-3\n\n            for i in range(n_nodes):\n                tmp_nodes = np.copy(nodes)\n                tmp_nodes[i] += delta\n                f = interp.interp1d(log_tau[pos], tmp_nodes, 'linear', bounds_error=False, fill_value='extrapolate')\n\n                tmp1 = reference + f(log_tau)\n\n                rf[i,:] = (tmp1 - tmp0) / delta * jacobian\n            \n            return rf\n\n        if (n_nodes == 3):\n            rf = np.zeros((n_nodes, n_depth))\n\n            pos = np.linspace(0, n_depth-1, n_nodes+2, dtype=int)[1:-1]\n            f = interp.interp1d(log_tau[pos], nodes, 'quadratic', bounds_error=False, fill_value='extrapolate')\n            tmp0 = reference + f(log_tau)\n\n            jacobian = jacobian_transformation(tmp0, lower, upper)\n\n            delta = 1e-3\n\n            for i in range(n_nodes):\n                tmp_nodes = np.copy(nodes)\n                tmp_nodes[i] += delta\n                f = interp.interp1d(log_tau[pos], tmp_nodes, 'quadratic', bounds_error=False, fill_value='extrapolate')\n\n                tmp1 = reference + f(log_tau)\n\n                rf[i,:] = (tmp1 - tmp0) / delta * jacobian\n            \n            return rf\n\n        if (n_nodes > 3):\n            rf = np.zeros((n_nodes, n_depth))\n\n            pos = np.linspace(n_depth-1, 0, n_nodes+2, dtype=int)[1:-1]\n            f = interp.PchipInterpolator(log_tau[pos], nodes, extrapolate=True)\n\n            tmp0 = reference + f(log_tau)\n\n            jacobian = jacobian_transformation(tmp0, lower, upper)\n\n            delta = 1e-3\n\n            for i in range(n_nodes):\n                tmp_nodes = np.copy(nodes)\n                tmp_nodes[i] += delta\n                f = interp.PchipInterpolator(log_tau[pos], tmp_nodes, extrapolate=True)\n\n                tmp1 = reference + f(log_tau)\n\n                rf[i,:] = (tmp1 - tmp0) / delta * jacobian\n            \n            return rf\n\n    def load_reference_model(self, model_file, verbose):\n        \"\"\"\n        Load a reference model or a model for every pixel for synthesis/inversion\n\n        Parameters\n        ----------\n        model_file : str\n            String with the name of the file. Extensions can currently be \"1d\" or \"h5\"\n        verbose : bool\n            Verbosity\n\n        Returns\n        -------\n        None\n        \"\"\"\n        extension = os.path.splitext(model_file)[1][1:]\n        if (extension == '1d'):\n            if (verbose >= 1):\n                self.logger.info('    * Reading 1D model {0} as reference'.format(model_file))\n            self.model_type = '1d'\n            self.model_filename = model_file\n        \n        if (extension == 'h5'):\n            if (verbose >= 1):\n                self.logger.info('    * Reading 3D model {0} as reference'.format(model_file))\n            self.model_type = '3d'\n                        \n\n        self.model_handler = Generic_SIR_file(model_file)\n        self.model_handler.open()\n        out, ff, vmac = self.model_handler.read(pixel=0)\n        self.model_handler.close()\n\n        self.set_parameters(out, ff, vmac)\n\n        self.t_old = np.zeros_like(self.parameters['T'])\n        \n        self.init_reference(check_borders=True)\n\n        self.departure = np.ones((2, len(self.lines), len(self.log_tau)))\n                        \n    def set_parameters(self, model, ff, vmac):\n        \"\"\"\n        Set the parameters of the current model to those passed as argument\n\n        Parameters\n        ----------\n        model_in : float\n            Array with the model        \n        ff : float\n            Value of the filling factor\n        vmac : float\n            Value of the macroturbulent velocity\n\n        Returns\n        -------\n        None\n        \"\"\"\n        \n        self.log_tau = model[:,0]\n        self.parameters['T'] = model[:,1]\n        self.parameters['vmic'] = model[:,3]\n        self.parameters['v'] = model[:,4]\n        self.parameters['Bx'] = model[:,5]\n        self.parameters['By'] = model[:,6]\n        self.parameters['Bz'] = model[:,7]\n\n        if (np.min(model[:,2]) > 0.0):\n            self.Pe = model[:,2]\n        else:\n            self.Pe = -np.ones(len(self.log_tau))\n            self.Pe[-1] = 1.11634e-1        \n        \n        self.parameters['ff'] = ff\n        self.parameters['vmac'] = vmac\n\n        # Check that parameters are inside borders by clipping inside the interval with a border of 1e-8\n        if (self.working_mode == 'inversion'):\n            for k, v in self.parameters.items():                \n                self.parameters[k] = np.clip(v, self.ranges[k][0] + 1e-8, self.ranges[k][1] - 1e-8)\n                \n\n    def get_parameters(self):                \n        \"\"\"\n        Get the curent parameters as a model\n\n        Parameters\n        ----------\n        None\n\n        Returns\n        -------\n        model: a 6xN photspheric model\n        \"\"\"\n        \n        model = np.zeros((len(self.log_tau),8))\n        model[:,0] = self.log_tau\n        model[:,1] = self.parameters['T']\n        model[:,2] = self.Pe\n        model[:,3] = self.parameters['vmic']\n        model[:,4] = self.parameters['v']\n        model[:,5] = self.parameters['Bx']\n        model[:,6] = self.parameters['By']\n        model[:,7] = self.parameters['Bz']\n\n        return model        \n\n    def nodes_to_model(self):\n        \"\"\"\n        Transform from nodes to model\n        \n        Parameters\n        ----------\n        None\n                                \n        Returns\n        -------\n        None\n        \"\"\"        \n        for k, v in self.nodes.items():\n            if (self.n_nodes[k] > 0):                \n                self.parameters[k], self.nodes_location[k] = self.interpolate_nodes(self.log_tau, self.reference[k], self.nodes[k])\n            else:\n                self.parameters[k] = self.reference[k]\n\n        self.Pe = -np.ones(len(self.log_tau))\n        self.Pe[-1] = 1.11634e-1 \n                    \n    def model_to_nodes(self):\n        \"\"\"\n        Transform from model to nodes\n        \n        Parameters\n        ----------\n        None\n                                \n        Returns\n        -------\n        None        \n        \"\"\"\n\n        pass\n\n        # for k, v in self.parameters.items():\n            # if (k is not 'log_tau'):\n\n        # self.interpolate_nodes(self.parameters['log_tau'], self.reference['T'], [1000])\n        # stop()\n        # for k, v in self.parameters.items():\n            # if (k is not 'log_tau'):\n                \n    # def print_parameters_old(self, first=False, error=False):\n    #     breakpoint()\n    #     for k, v in self.nodes.items():\n    #         if (self.n_nodes[k] > 0):\n    #             if (k != 'ff'):\n    #                 lower = self.ranges[k][0] #- self.eps_borders\n    #                 upper = self.ranges[k][1] #+ self.eps_borders\n    #                 nodes = transformed_to_physical(v, lower, upper)\n    #                 self.logger.info('{0} -> {1}'.format(k, nodes))\n\n    def print_parameters(self, first=False, error=False):        \n        for k, v in self.parameters.items():\n            if (self.n_nodes[k] > 0):\n                if (k != 'ff'):                    \n                    pars = v[self.nodes_location[k]]\n                    self.logger.info('{0} -> {1}'.format(k, pars))\n                    \n            \n    def synthesize(self, stokes_in, returnRF=False, nlte=False):\n        \"\"\"\n        Carry out the synthesis and returns the Stokes parameters and the response \n        functions to all physical variables at all depths\n        \n        Parameters\n        ----------\n        stokes_in : float\n            An array of size [4 x nLambda] with the input Stokes parameter. It is irrelevant in this case\n            because we assume that all SIR atmospheres have the Planck function as boundary.\n                \n        returnRF : bool, optional\n            Return response functions\n        \n        Returns\n        -------\n        \n        stokes : float\n            Stokes parameters, with the first index containing the wavelength displacement and the remaining\n                                    containing I, Q, U and V. Size (5,nLambda)\n        rf: float (optional)\n            Response functions to T, Pe, vmic, B, v, theta, phi, all of size (4,nLambda,nDepth), plus the RF to macroturbulence of size (4,nLambda)\n                            It is not returned if returnRF=False\n        \"\"\"\n        \n        if (self.working_mode == 'inversion'):\n            self.nodes_to_model()\n            self.to_physical()\n        \n        if (returnRF):\n\n            stokes, cmass, rf, error = sir_code.synthRF(self.index, self.n_lambda, self.log_tau, self.parameters['T'], \n                self.Pe, 1e5*self.parameters['vmic'], 1e5*self.parameters['v'], self.parameters['Bx'], self.parameters['By'], \n                self.parameters['Bz'], self.parameters['vmac'])            \n\n            if (error == 1):\n                raise NumericalErrorSIR()\n\n            B = np.sqrt(self.parameters['Bx']**2 + self.parameters['By']**2 + self.parameters['Bz']**2)\n            \n            thetaB = np.arccos(self.parameters['Bz'] / B)\n            thetaB[B == 0] = 0.0\n\n            phiB = np.arctan2(self.parameters['By'], self.parameters['Bx'])\n\n            # rfn = np.zeros((150, 73))\n            # pars = copy.deepcopy(self.parameters)\n            # for pos in range(73):\n            #     ind_sto = 0\n\n            #     self.parameters = copy.deepcopy(pars)\n\n            #     delta = 5e-4*self.parameters['T'][pos]\n            #     self.parameters['T'][pos] += delta\n\n            #     stokes2, rf2, error = sir_code.synthRF(self.index, self.n_lambda, self.log_tau, self.parameters['T'], \n            #         self.Pe, 1e5*self.parameters['vmic'], 1e5*self.parameters['v'], self.parameters['Bx'], self.parameters['By'], \n            #         self.parameters['Bz'], self.parameters['vmac'])\n            #     error = 0\n\n            #     rfn[:, pos] = (stokes2[ind_sto+1,:]-stokes[ind_sto+1,:])/delta\n\n            # breakpoint()\n\n            # import matplotlib.pyplot as pl\n            # pl.plot(rfn[:, 40], '-o', label='numerical')\n\n            self.rf_analytical['T'] = rf[0]+rf[1]       #OK\n            self.rf_analytical['vmic'] = 1e5*rf[6]   #OK\n            self.rf_analytical['v'] = 1e5*rf[3]      #OK\n\n            # Transform SIR RFs into response functions to Bx, By and Bz.\n            # To this end, we have:\n            # [RF_B ]   [dBxdB     dBydB    dBzdB ][RF_Bx]\n            # [RF_th] = [dBxdthB  dBydthB  dBzdthB][RF_By] \n            # [RF_ph]   [dBxdphB  dBydphB  dBzdphB][RF_Bz]\n            # and then invert the Jacobian\n\n            RFB = rf[2]\n            RFt = rf[4]\n            RFp = rf[5]\n\n            self.rf_analytical['Bx'] = RFB * np.sin(thetaB) * np.cos(phiB) + \\\n                                        RFt * np.cos(thetaB) * np.cos(phiB) / (B + 1e-6) - \\\n                                        RFp * np.sin(phiB) / (B * np.sin(thetaB))\n            self.rf_analytical['By'] = RFB * np.sin(thetaB) * np.sin(phiB) + \\\n                                        RFt * np.cos(thetaB) * np.sin(phiB) / (B + 1e-6) + \\\n                                        RFp * np.cos(phiB) / (B * np.sin(thetaB))\n            self.rf_analytical['Bz'] = RFB * np.cos(thetaB) - RFt * np.sin(thetaB) / (B + 1e-6)\n\n            self.rf_analytical['vmac'] = rf[7][:, :, None]\n\n            # pl.plot(self.rf_analytical['T'][ind_sto,:,pos], label='analytical')\n            # pl.legend()\n            # pl.show()\n\n            # import matplotlib.pyplot as pl\n            # f, ax = pl.subplots(nrows=3, ncols=3, figsize=(10,10))\n            # ax = ax.flatten()\n            # for i in range(9):\n            #     ax[i].plot(np.log(self.rf_analytical['T'][0,i*10,:]), color=f'C{i}')\n            #     ax[i].plot(np.log(rfn[i*10,:]), 'o', color=f'C{i}')\n            # pl.show()\n\n            i0 = i0_allen(np.mean(self.wvl_axis), self.spectrum.mu)\n\n            for k, v in self.nodes.items():\n                if (k != 'vmac'):\n                    if (self.n_nodes[k] > 0):\n                        lower = self.ranges[k][0]\n                        upper = self.ranges[k][1]\n                        rf = self.interpolate_nodes_rf(self.log_tau, self.reference[k], self.nodes[k], lower, upper)\n\n                        # import matplotlib.pyplot as pl\n                        # f, ax = pl.subplots(nrows=3, ncols=3, figsize=(10,10))\n                        # ax = ax.flatten()\n                        # for i in range(9):\n                        #     ax[i].plot(rfn[i*10,:] / self.rf_analytical['T'][0,i*10,:], color=f'C{i}')\n                        #     ax[i].set_ylim([0,2])\n                        # pl.show()\n                        # print(k)\n                        # breakpoint()\n\n                        self.rf_analytical[k] = np.einsum('ijk,lk->ijl', self.rf_analytical[k], rf) * i0\n\n            return self.parameters['ff'] * stokes[1:,:] * i0, self.rf_analytical, error\n        else:                       \n            # stokes, error = sir_code.synth(self.index, self.n_lambda, self.log_tau, self.parameters['T'], \n                # self.Pe, 1e5*self.parameters['vmic'], 1e5*self.parameters['v'], self.parameters['Bx'], self.parameters['By'], \n                # self.parameters['Bz'], self.parameters['vmac'])\n\n            # If we need to put the atmosphere in hydrostatic eq.\n            if (self.working_mode == 'inversion'):\n                self.Pe = sir_code.hydroeq(self.log_tau, self.parameters['T'], \n                    self.Pe, 1e5*self.parameters['vmic'], 1e5*self.parameters['v'], self.parameters['Bx'], self.parameters['By'], \n                    self.parameters['Bz'])            \n\n            # Check if the line is 8542 and we want NLTE. If that is the case, then evaluate the\n            # neural network to return the departure coefficients\n            \n            if (nlte):\n                if (self.nlte):                    \n                    dif = (self.parameters['T'] - self.t_old)                                        \n                    if (np.max(dif) > self.t_change_departure):\n                        for i, l in enumerate(self.lines):\n                            if (l == 301):\n                                if (self.verbose >= 4):\n                                    self.logger.info('  - NLTE neural oracle')\n                                n = len(self.log_tau)                            \n                                tau = [10.0**self.log_tau[::-1]]\n                                ne = self.Pe / (1.381e-16 * self.parameters['T'])\n                                ne = [ne[::-1] * 1e6]                                 # in m^-3\n                                tt = [self.parameters['T'][::-1]]\n                                vturb = [self.parameters['vmic'][::-1] * 1e3]         # in m/s                            \n                                vlos = [self.parameters['v'][::-1] * 1e3]             # in m/s\n                                prediction = self.graphnet_nlte.predict(tau, ne, vturb, tt, vlos)\n                                self.departure[0, i, :] = 10.0**prediction[0][::-1, 2]\n                                self.departure[1, i, :] = 10.0**prediction[0][::-1, 4]\n            \n                            self.t_old = self.parameters['T']\n                        \n            else:\n                self.departure = np.ones((2, len(self.lines), len(self.log_tau)))\n            \n            stokes, cmass, rf, error = sir_code.synthRF(self.index, self.n_lambda, self.log_tau, self.parameters['T'], \n                self.Pe, 1e5*self.parameters['vmic'], 1e5*self.parameters['v'], self.parameters['Bx'], self.parameters['By'], \n                self.parameters['Bz'], self.parameters['vmac'], np.asfortranarray(self.departure))\n\n            # Transform SIR RFs into response functions to Bx, By and Bz.\n            # To this end, we have:\n            # [RF_B ]   [dBxdB     dBydB    dBzdB ][RF_Bx]\n            # [RF_th] = [dBxdthB  dBydthB  dBzdthB][RF_By] \n            # [RF_ph]   [dBxdphB  dBydphB  dBzdphB][RF_Bz]\n            # and then invert the Jacobian\n            B = np.sqrt(self.parameters['Bx']**2 + self.parameters['By']**2 + self.parameters['Bz']**2) + 1e-6\n            thetaB = np.arccos(self.parameters['Bz'] / B)\n            thetaB[B == 0] = 0.0\n            phiB = np.arctan2(self.parameters['By'], self.parameters['Bx'])\n\n            self.rf_analytical['T'] = rf[0]+rf[1]       #OK\n            self.rf_analytical['vmic'] = 1e5*rf[6]   #OK\n            self.rf_analytical['v'] = 1e5*rf[3]      #OK\n            \n            RFB = rf[2]\n            RFt = rf[4]\n            RFp = rf[5]\n\n            self.rf_analytical['Bx'] = RFB * np.sin(thetaB) * np.cos(phiB) + \\\n                                        RFt * np.cos(thetaB) * np.cos(phiB) / B - \\\n                                        RFp * np.sin(phiB) / (B * np.sin(thetaB))\n            self.rf_analytical['By'] = RFB * np.sin(thetaB) * np.sin(phiB) + \\\n                                        RFt * np.cos(thetaB) * np.sin(phiB) / B + \\\n                                        RFp * np.cos(phiB) / (B * np.sin(thetaB))\n            self.rf_analytical['Bz'] = RFB * np.cos(thetaB) - RFt * np.sin(thetaB) / B \n\n            self.rf_analytical['vmac'] = rf[7][:, :, None]\n\n            if (error == 1):\n                raise NumericalErrorSIR()\n\n            return self.parameters['ff'] * stokes[1:,:] * i0_allen(np.mean(self.wvl_axis), self.spectrum.mu), error #hsra_continuum(np.mean(self.wvl_axis)), error\n", "meta": {"hexsha": "186b2beb762f6132cd87ef1b2d13bdca0ae36246", "size": 26360, "ext": "py", "lang": "Python", "max_stars_repo_path": "hazel/photosphere.py", "max_stars_repo_name": "aasensio/hazel2", "max_stars_repo_head_hexsha": "d9b551915f5d2bb399e03b054dffe4ca42fedeb5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2018-08-31T11:13:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T02:30:56.000Z", "max_issues_repo_path": "hazel/photosphere.py", "max_issues_repo_name": "aasensio/hazel2", "max_issues_repo_head_hexsha": "d9b551915f5d2bb399e03b054dffe4ca42fedeb5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2018-04-03T15:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-27T10:10:45.000Z", "max_forks_repo_path": "hazel/photosphere.py", "max_forks_repo_name": "aasensio/hazel2", "max_forks_repo_head_hexsha": "d9b551915f5d2bb399e03b054dffe4ca42fedeb5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-05-01T13:47:21.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-23T20:49:08.000Z", "avg_line_length": 37.7650429799, "max_line_length": 162, "alphanum_fraction": 0.4985204856, "include": true, "reason": "import numpy,import scipy", "num_tokens": 6527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3345894346180164, "lm_q1q2_score": 0.18033809107848978}}
{"text": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\nfrom audioop import bias\nfrom os import X_OK\nfrom re import M\nimport os\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.models\nimport numpy as np\nfrom torch.distributions.distribution import Distribution\nimport torchvision.models.alexnet\nfrom collections import OrderedDict\nfrom itertools import chain\n\nfrom domainbed.lib import wide_resnet\nfrom domainbed.lib import gaussian_random_fields as grf\nimport copy\nimport time\nimport math\n# from imgaug import augmenters as iaa\n# from torchvision import transforms\nimport torch.utils.model_zoo as model_zoo\n\nmodel_urls = {\n    'alexnet': 'https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth',\n}\n\n\ndef remove_batch_norm_from_resnet(model):\n    fuse = torch.nn.utils.fusion.fuse_conv_bn_eval\n    model.eval()\n\n    model.conv1 = fuse(model.conv1, model.bn1)\n    model.bn1 = Identity()\n\n    for name, module in model.named_modules():\n        if name.startswith(\"layer\") and len(name) == 6:\n            for b, bottleneck in enumerate(module):\n                for name2, module2 in bottleneck.named_modules():\n                    if name2.startswith(\"conv\"):\n                        bn_name = \"bn\" + name2[-1]\n                        setattr(bottleneck, name2,\n                                fuse(module2, getattr(bottleneck, bn_name)))\n                        setattr(bottleneck, bn_name, Identity())\n                if isinstance(bottleneck.downsample, torch.nn.Sequential):\n                    bottleneck.downsample[0] = fuse(bottleneck.downsample[0],\n                                                    bottleneck.downsample[1])\n                    bottleneck.downsample[1] = Identity()\n    model.train()\n    return model\n\n\nclass Identity(nn.Module):\n    \"\"\"An identity layer\"\"\"\n    def __init__(self):\n        super(Identity, self).__init__()\n\n    def forward(self, x):\n        return x\n\n\nclass MLP(nn.Module):\n    \"\"\"Just  an MLP\"\"\"\n    def __init__(self, n_inputs, n_outputs, hparams):\n        super(MLP, self).__init__()\n        self.input = nn.Linear(n_inputs, hparams['mlp_width'])\n        self.dropout = nn.Dropout(hparams['mlp_dropout'])\n        self.hiddens = nn.ModuleList([\n            nn.Linear(hparams['mlp_width'], hparams['mlp_width'])\n            for _ in range(hparams['mlp_depth']-2)])\n        self.output = nn.Linear(hparams['mlp_width'], n_outputs)\n        self.n_outputs = n_outputs\n\n    def forward(self, x):\n        x = self.input(x)\n        x = self.dropout(x)\n        x = F.relu(x)\n        for hidden in self.hiddens:\n            x = hidden(x)\n            x = self.dropout(x)\n            x = F.relu(x)\n        x = self.output(x)\n        return x\n\nclass ResNet(torch.nn.Module):\n    \"\"\"ResNet with the softmax chopped off and the batchnorm frozen\"\"\"\n    def __init__(self, input_shape, hparams):\n        super(ResNet, self).__init__()\n        if hparams['resnet18']:\n            self.network = torchvision.models.resnet18(pretrained=True)\n            self.n_outputs = 512\n        else:\n            self.network = torchvision.models.resnet50(pretrained=True)\n            self.n_outputs = 2048\n\n        # self.network = remove_batch_norm_from_resnet(self.network)\n\n        # adapt number of channels\n        nc = input_shape[0]\n        if nc != 3:\n            tmp = self.network.conv1.weight.data.clone()\n\n            self.network.conv1 = nn.Conv2d(\n                nc, 64, kernel_size=(7, 7),\n                stride=(2, 2), padding=(3, 3), bias=False)\n\n            for i in range(nc):\n                self.network.conv1.weight.data[:, i, :, :] = tmp[:, i % 3, :, :]\n\n        # save memory\n        del self.network.fc\n        self.network.fc = Identity()\n\n        self.freeze_bn()\n        self.hparams = hparams\n        self.dropout = nn.Dropout(hparams['resnet_dropout'])\n\n    def forward(self, x):\n        \"\"\"Encode x into a feature vector of size n_outputs.\"\"\"\n        return self.dropout(self.network(x))\n\n    def train(self, mode=True):\n        \"\"\"\n        Override the default train() to freeze the BN parameters\n        \"\"\"\n        super().train(mode)\n        self.freeze_bn()\n\n    def freeze_bn(self):\n        for m in self.network.modules():\n            if isinstance(m, nn.BatchNorm2d):\n                m.eval()\n\nclass AlexNet(nn.Module):\n    \n    def __init__(self, hparams):\n        super(AlexNet, self).__init__()\n        self.features = nn.Sequential(\n            nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),\n            nn.ReLU(inplace=True),\n            nn.MaxPool2d(kernel_size=3, stride=2),\n            nn.Conv2d(64, 192, kernel_size=5, padding=2),\n            nn.ReLU(inplace=True),\n            nn.MaxPool2d(kernel_size=3, stride=2),\n            nn.Conv2d(192, 384, kernel_size=3, padding=1),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(384, 256, kernel_size=3, padding=1),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(256, 256, kernel_size=3, padding=1),\n            nn.ReLU(inplace=True),\n            nn.MaxPool2d(kernel_size=3, stride=2),\n        )\n        \n        self.avgpool = nn.AdaptiveAvgPool2d((6, 6))\n        # self.classifier = nn.Sequential(\n        #     nn.Dropout(p=True),\n        #     nn.Linear(256 * 6 * 6, 4096),\n        #     nn.ReLU(inplace=True),\n        #     nn.Dropout(p=True),\n        #     nn.Linear(4096, 4096),\n        #     nn.ReLU(inplace=True),\n        #     nn.Linear(4096, 1000),\n        # )\n        \n        self.n_outputs = 256 * 6 * 6\n        self.hparams = hparams\n\n    def forward(self, x):\n        x = self.features(x)\n        x = self.avgpool(x)\n        x = torch.flatten(x, 1)\n    #     x = self.classifier(x)\n        return x\n    \n\nclass AlexNetCaffe(nn.Module):\n    def __init__(self, n_classes=7, hparams=None):\n        super(AlexNetCaffe, self).__init__()\n        print(\"Using Caffe AlexNet\")\n        self.features = nn.Sequential(OrderedDict([\n            (\"conv1\", nn.Conv2d(3, 96, kernel_size=11, stride=4)),\n            (\"relu1\", nn.ReLU(inplace=True)),\n            (\"pool1\", nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True)),\n            (\"norm1\", nn.LocalResponseNorm(5, 1.e-4, 0.75)),\n            (\"conv2\", nn.Conv2d(96, 256, kernel_size=5, padding=2, groups=2)),\n            (\"relu2\", nn.ReLU(inplace=True)),\n            (\"pool2\", nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True)),\n            (\"norm2\", nn.LocalResponseNorm(5, 1.e-4, 0.75)),\n            (\"conv3\", nn.Conv2d(256, 384, kernel_size=3, padding=1)),\n            (\"relu3\", nn.ReLU(inplace=True)),\n            (\"conv4\", nn.Conv2d(384, 384, kernel_size=3, padding=1, groups=2)),\n            (\"relu4\", nn.ReLU(inplace=True)),\n            (\"conv5\", nn.Conv2d(384, 256, kernel_size=3, padding=1, groups=2)),\n            (\"relu5\", nn.ReLU(inplace=True)),\n            (\"pool5\", nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True)),\n        ]))\n        # self.classifier = nn.Sequential(OrderedDict([\n        #     (\"fc6\", nn.Linear(256 * 6 * 6, 4096)),\n        #     (\"relu6\", nn.ReLU(inplace=True)),\n        #     (\"drop6\", nn.Dropout()),\n        #     (\"fc7\", nn.Linear(4096, 4096)),\n        #     (\"relu7\", nn.ReLU(inplace=True)),\n        #     (\"drop7\", nn.Dropout())]))\n\n        # self.classifier = nn.Linear(4096, n_classes)\n        \n        self.n_outputs = 256 * 6 * 6\n        self.hparams = hparams\n        # self.p_logvar = nn.Sequential(nn.Linear(4096, 512),\n        #                               nn.ReLU())\n        # self.p_mu = nn.Sequential(nn.Linear(4096, 512),\n        #                           nn.LeakyReLU())\n\n    def get_params(self, base_lr):\n        return [{\"params\": self.features.parameters(), \"lr\": 0.},\n                {\"params\": chain(self.classifier.parameters(), self.classifier_l.parameters(), self.p_logvar.parameters(), self.p_mu.parameters()\n                                 ), \"lr\": base_lr}]\n\n    def is_patch_based(self):\n        return False\n\n    def forward(self, x, train=True):\n        # end_points={}\n        x = self.features(x*57.6)  #57.6 is the magic number needed to bring torch data back to the range of caffe data, based on used std\n        x = x.view(x.size(0), -1)\n        # x = self.classifier(x)\n\n        # logvar = self.p_logvar(x)\n        # mu = self.p_mu(x)\n        # end_points['logvar'] = logvar\n        # end_points['mu'] = mu\n\n        # if train:\n        #     x = self.reparametrize(mu, logvar)\n        # else:\n        #     x = mu\n\n        # end_points['Embedding'] = x\n        # x = self.classifier_l(x)\n        # end_points['Predictions'] = nn.functional.softmax(input=x, dim=-1)\n\n\n        # return x, end_points\n        return x\n\n    def reparametrize(self, mu, logvar, factor=0.2):\n        std = logvar.div(2).exp()\n        eps = std.data.new(std.size()).normal_()\n        return mu + factor*std*eps\n\n\n\ndef alexnet(pretrained=True, num_classes=1000, feature_size=6, model_path=None):\n    r\"\"\"AlexNet model architecture from the\n    `\"One weird trick...\" <https://arxiv.org/abs/1404.5997>`_ paper.\n    Args:\n        pretrained (bool): If True, returns a model pre-trained on ImageNet\n        num_classes (int): number of classes\n        model_path (string): path to pretrain model (using official model if is None)\n    \"\"\"\n    model = AlexNet()\n    if pretrained:\n        if model_path is None:\n            model.load_state_dict(model_zoo.load_url(model_urls['alexnet']))\n        else:\n            print(\"Loading model {}\".format(model_path))\n            checkpoint = torch.load(model_path, map_location='cpu')\n            model.load_state_dict(checkpoint['state_dict'])\n\n    if feature_size == 6:\n        model.classifier[6] = nn.Linear(4096, num_classes)\n        # nn.init.xavier_uniform_(model.classifier[-1].weight, .1)\n        # nn.init.constant_(model.classifier[-1].bias, 0.)\n    else:\n        print(\"Adpating new classifier\")\n        fc_size = feature_size*feature_size*256\n        model.classifier = nn.Sequential(\n            nn.Dropout(),\n            nn.Linear(fc_size, fc_size),\n            nn.ReLU(inplace=True),\n            nn.Dropout(),\n            nn.Linear(fc_size, fc_size),\n            nn.ReLU(inplace=True),\n            nn.Linear(fc_size, num_classes),\n        )\n        for m in model.classifier.modules():\n            if type(m) == nn.Linear:\n                nn.init.xavier_uniform_(m.weight)\n                nn.init.constant_(m.bias, 0.)\n\n    return model\n\n\nclass DigitsConvNet(nn.Module):\n\n    def __init__(self, input_shape, hparams):\n        super(DigitsConvNet, self).__init__()\n\n        self.batch_size = hparams['batch_size']\n\n        kernel_size = 5\n        stride = 1\n        padding = 0\n        dim_conv1 = 64\n        dim_conv2 = 128\n        self.conv1 = nn.Conv2d(input_shape[0], dim_conv1, kernel_size=kernel_size, stride=stride, padding=padding)\n        self.relu1 = nn.ReLU(inplace=True)\n        self.conv2 = nn.Conv2d(dim_conv1, dim_conv2, kernel_size=kernel_size, stride=stride, padding=padding)\n        self.relu2 = nn.ReLU(inplace=True)\n        self.mp = nn.MaxPool2d(2)\n        w = int(np.floor((np.floor((input_shape[-1] - kernel_size + 2 * padding) / stride + 1) // 2 - kernel_size + 2 * padding) / stride + 1) // 2)\n        self.n_outputs = w ** 2 * dim_conv2\n\n    def forward(self, x):\n\n        in_size = x.size(0)\n        out1 = self.mp(self.relu1(self.conv1(x)))\n        out2 = self.mp(self.relu2(self.conv2(out1)))\n        out2 = out2.view(in_size, -1)\n        return out2\n\n\n\nclass GeneralClassifier(nn.Module):\n    def __init__(self, in_features, out_features, hparams):\n        super(GeneralClassifier, self).__init__()\n        self.is_nonlinear = hparams['nonlinear_classifier']\n        self.is_proj = hparams['is_proj']\n        self.dim_proj = hparams['dim_proj']\n        self.is_manual_fc_dim = hparams['is_manual_fc_dim']\n        self.dim_fc = hparams['dim_fc']\n        self.alexnet = hparams['alexnet'] and hparams['alexnet_classifier']\n        \n        if self.alexnet:\n            if self.is_proj:\n                self.classifier = nn.Sequential(\n                    nn.Dropout(p=hparams['alexnet_dropout']),\n                    nn.Linear(in_features, 4096),\n                    nn.ReLU(inplace=True),\n                    nn.Dropout(p=hparams['alexnet_dropout']),\n                    nn.Linear(4096, 4096),\n                    nn.ReLU(inplace=True),\n                )\n                self.head = nn.Linear(4096, out_features)\n                self.pro_head = nn.Linear(4096, self.dim_proj)\n            else:\n                self.classifier = nn.Sequential(\n                    nn.Dropout(p=hparams['alexnet_dropout']),\n                    nn.Linear(in_features, 4096),\n                    nn.ReLU(inplace=True),\n                    nn.Dropout(p=hparams['alexnet_dropout']),\n                    nn.Linear(4096, 4096),\n                    nn.ReLU(inplace=True),\n                    nn.Linear(4096, out_features),\n                )\n        else:\n            if self.is_nonlinear:\n                if self.is_manual_fc_dim:\n                    self.fc1 = torch.nn.Linear(in_features, self.dim_fc)\n                    self.relu1 = torch.nn.ReLU()\n                    self.fc2 = torch.nn.Linear(self.dim_fc, self.dim_fc)\n                    self.relu2 = torch.nn.ReLU()\n                    self.fc3 = torch.nn.Linear(self.dim_fc, out_features)\n                    if self.is_proj:\n                        self.pro_head = nn.Linear(self.dim_fc, self.dim_proj)\n                else:\n                    self.fc1 = torch.nn.Linear(in_features, in_features // 2)\n                    self.relu1 = torch.nn.ReLU()\n                    self.fc2 = torch.nn.Linear(in_features // 2, in_features // 4)\n                    self.relu2 = torch.nn.ReLU()\n                    self.fc3 = torch.nn.Linear(in_features // 4, out_features)\n                    if self.is_proj:\n                        self.pro_head = nn.Linear(in_features // 4, self.dim_proj)\n            else:\n                self.fc1 = torch.nn.Linear(in_features, out_features)\n                if self.is_proj:\n                    self.pro_head = nn.Linear(in_features, self.dim_proj)\n\n    def forward(self, x, mode='test'):\n        if self.alexnet:\n            if self.is_proj:\n                x = self.classifier(x)\n                p = self.head(x)\n            else:\n                p = self.classifier(x)\n        else:\n            if self.is_nonlinear:\n                x = self.fc1(x)\n                x = self.relu1(x)\n                x = self.fc2(x)\n                x = self.relu2(x)\n                p = self.fc3(x)\n            else:\n                p = self.fc1(x)\n        if mode == 'test':\n            return p\n        elif mode == 'tsne':\n            return p, x\n        elif mode =='train':\n            if self.is_proj:\n                z = self.pro_head(x)\n                z = F.normalize(z)\n                return p,z\n            else:\n                return p,None\n\n\nclass MNIST_CNN(nn.Module):\n    \"\"\"\n    Hand-tuned architecture for MNIST.\n    Weirdness I've noticed so far with this architecture:\n    - adding a linear layer after the mean-pool in features hurts\n        RotatedMNIST-100 generalization severely.\n    \"\"\"\n    n_outputs = 128\n\n    def __init__(self, input_shape, hparams):\n        super(MNIST_CNN, self).__init__()\n\n        self.conv1 = nn.Conv2d(input_shape[0], 64, 3, 1, padding=1)\n        self.conv2 = nn.Conv2d(64, 128, 3, stride=2, padding=1)\n        self.conv3 = nn.Conv2d(128, 128, 3, 1, padding=1)\n        self.conv4 = nn.Conv2d(128, 128, 3, 1, padding=1)\n\n        self.bn0 = nn.GroupNorm(8, 64)\n        self.bn1 = nn.GroupNorm(8, 128)\n        self.bn2 = nn.GroupNorm(8, 128)\n        self.bn3 = nn.GroupNorm(8, 128)\n\n        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\n\n    def forward(self, x):\n        x = self.conv1(x)\n        x = F.relu(x)\n        x = self.bn0(x)\n\n        x = self.conv2(x)\n        x = F.relu(x)\n        x = self.bn1(x)\n\n        x = self.conv3(x)\n        x = F.relu(x)\n        x = self.bn2(x)\n\n        x = self.conv4(x)\n        x = F.relu(x)\n        x = self.bn3(x)\n\n        x = self.avgpool(x)\n        x = x.view(len(x), -1)\n        return x\n\n\nclass ContextNet(nn.Module):\n    def __init__(self, input_shape):\n        super(ContextNet, self).__init__()\n\n        # Keep same dimensions\n        padding = (5 - 1) // 2\n        self.context_net = nn.Sequential(\n            nn.Conv2d(input_shape[0], 64, 5, padding=padding),\n            nn.BatchNorm2d(64),\n            nn.ReLU(),\n            nn.Conv2d(64, 64, 5, padding=padding),\n            nn.BatchNorm2d(64),\n            nn.ReLU(),\n            nn.Conv2d(64, 1, 5, padding=padding),\n        )\n\n    def forward(self, x):\n        return self.context_net(x)\n\n\ndef Featurizer(input_shape, hparams):\n    \"\"\"Auto-select an appropriate featurizer for the given input shape.\"\"\"\n    if hparams['digits_convnet']:\n        return DigitsConvNet(input_shape, hparams)\n    else:\n        if len(input_shape) == 1:\n            # print('MLP')\n            return MLP(input_shape[0], hparams[\"mlp_width\"], hparams)\n        elif input_shape[1:3] == (28, 28):\n            # print('MNIST_CNN')\n            return MNIST_CNN(input_shape, hparams)\n        elif input_shape[1:3] == (32, 32):\n            # print('Wide_ResNet')\n            if hparams['wide_resnet_type'] == 1:\n                return wide_resnet.Wide_ResNet(input_shape, hparams['wide_resnet_layers'], hparams['widen_factor'], hparams['widen_dropout'])\n            elif hparams['wide_resnet_type'] == 2:\n                return wide_resnet.Wide_ResNet2(input_shape, hparams['wide_resnet_layers'], hparams['widen_factor'], hparams['widen_dropout'])\n            else:\n                NotImplementedError\n\n        elif input_shape[1:3] == (224, 224):\n            # print('ResNet')\n\n            if hparams['alexnet']:\n                if hparams['alexnet_flag'] == 1:\n                    model = AlexNet(hparams)\n                    model.load_state_dict(model_zoo.load_url(model_urls['alexnet']), strict=False)\n                    # del model.classifier\n                else:\n                    model = AlexNetCaffe(hparams)\n                    for m in model.modules():\n                        if isinstance(m, nn.Linear):\n                            nn.init.xavier_uniform_(m.weight, .1)\n                            nn.init.constant_(m.bias, 0.)\n                    state_dict = torch.load(\"./domainbed/data/alexnet/alexnet_caffe.pth.tar\")\n                    del state_dict[\"classifier.fc8.weight\"]\n                    del state_dict[\"classifier.fc8.bias\"]\n                    model.load_state_dict(state_dict, strict=False)\n                    # del model.classifier\n            \n                return model\n            else:\n                return ResNet(input_shape, hparams)\n        else:\n            return ResNet(input_shape, hparams)\n            # raise NotImplementedError\n\n\ndef Classifier(in_features, out_features, is_nonlinear=False):\n    if is_nonlinear:\n        return torch.nn.Sequential(\n            torch.nn.Linear(in_features, in_features // 2),\n            torch.nn.ReLU(),\n            torch.nn.Linear(in_features // 2, in_features // 4),\n            torch.nn.ReLU(),\n            torch.nn.Linear(in_features // 4, out_features))\n    else:\n        return torch.nn.Linear(in_features, out_features)\n\n\nclass WholeFish(nn.Module):\n    def __init__(self, input_shape, num_classes, hparams, weights=None):\n        super(WholeFish, self).__init__()\n        featurizer = Featurizer(input_shape, hparams)\n        # classifier = Classifier(\n        #     featurizer.n_outputs,\n        #     num_classes,\n        #     hparams['nonlinear_classifier'])\n        classifier = GeneralClassifier(\n            featurizer.n_outputs,\n            num_classes,\n            hparams)\n        self.net = nn.Sequential(\n            featurizer, classifier\n        )\n        if weights is not None:\n            self.load_state_dict(copy.deepcopy(weights))\n\n    def reset_weights(self, weights):\n        self.load_state_dict(copy.deepcopy(weights))\n\n    def forward(self, x):\n        return self.net(x)\n\n\n## ------------------- for PDEN ---------------------\nclass AdaIN2d(nn.Module):\n    def __init__(self, style_dim, num_features):\n        super().__init__()\n        self.norm = nn.InstanceNorm2d(num_features, affine=False)\n        self.fc = nn.Linear(style_dim, num_features*2)\n    def forward(self, x, s): \n        h = self.fc(s)\n        h = h.view(h.size(0), h.size(1), 1, 1)\n        gamma, beta = torch.chunk(h, chunks=2, dim=1)\n        return (1 + gamma) * self.norm(x) + beta\n        #return (1+gamma)*(x)+beta\n\nclass IN2d(nn.Module):\n    def __init__(self, num_features):\n        super().__init__()\n        self.norm = nn.InstanceNorm2d(num_features, affine=False)\n    def forward(self, x, y=None): \n        return self.norm(x)\n\nclass selfIN2d(nn.Module):\n    def __init__(self, num_features):\n        super().__init__()\n        self.norm = nn.InstanceNorm2d(num_features, affine=False)\n    def forward(self, x, w, b): \n        return w * self.norm(x) + b\n\nclass GeneralizedAdaIN(nn.Module):\n    def __init__(self, norm_opt = []):\n    # def __init__(self, flag = None, num_features = 0, style = 'batch', same=True, batch_size=0, num_classes = 0, inv_prop = 0.0, std1 = 1.0, std2 = 1.0, v_std1=False, v_std2=False, norm_true=True, not_used='none'):\n        super().__init__()\n\n        self.flag_gamma = norm_opt['flag_gamma']\n        self.flag_beta = norm_opt['flag_beta']\n\n        self.num_features = norm_opt['num_features']\n        self.style = norm_opt['style']\n        self.same = norm_opt['same']\n        self.batch_size = norm_opt['batch_size']\n        self.num_classes = norm_opt['num_classes']\n        self.inv_prop = norm_opt['inv_prop']\n        self.std1 = norm_opt['std1']\n        self.std2 = norm_opt['std2']\n        self.v_std1 = norm_opt['v_std1']\n        self.v_std2 = norm_opt['v_std2']\n        self.norm_true = norm_opt['norm_true']\n        self.not_used = norm_opt['not_used']\n        self.norm = nn.InstanceNorm2d(self.num_features, affine=False)\n\n        if self.v_std1 == 'first_gen':\n            self.apply_std1 = self.std1*torch.rand(1).item()\n            # print('std1:{}'.format(self.apply_std1))\n        else:\n            self.apply_std1 = self.std1\n        if self.v_std2 == 'first_gen':\n            self.apply_std2 = self.std2*torch.rand(1).item()\n            # print('std2:{}'.format(self.apply_std2))\n        else:\n            self.apply_std2 = self.std2\n\n        if self.same:\n            self.gamma, self.beta = self.make_parameter()\n\n\n    def make_parameter(self):\n        if self.v_std1 == 'each_gen':\n            self.apply_std1 = self.std1*torch.rand(1).item()\n            # print('std11:{}'.format(self.apply_std1))\n        if self.v_std2 == 'each_gen':\n            self.apply_std2 = self.std2*torch.rand(1).item()\n            # print('std22:{}'.format(self.apply_std2))\n        \n        \n        if self.style == 'instance':\n            num_b = self.batch_size\n        elif self.style == 'class':\n            num_b = self.num_classes\n        elif self.style == 'batch':\n            num_b = 1\n        else: \n            NotImplementedError\n            \n        if self.flag_gamma == 'lognormal':\n            gamma = torch.exp(torch.normal(mean = 0, std = self.apply_std1 * torch.ones(num_b, self.num_features, 1, 1))).cuda() # log normal distribution\n            if self.inv_prop > 0.0:\n                idx = torch.rand(num_b, self.num_features, 1, 1) < self.inv_prop\n                gamma[idx] = -gamma[idx]\n        elif self.flag_gamma == 'normal':\n            gamma = torch.normal(mean = 0, std = self.apply_std1 * torch.ones(num_b, self.num_features, 1, 1)).cuda() # normal distribution\n        elif self.flag_gamma == 'uniform':\n            gamma = self.apply_std1 * (2.0*torch.rand(num_b, self.num_features, 1, 1).cuda()-1) # uniform distribution\n\n        if self.flag_beta == 'lognormal':\n            beta = torch.exp(torch.normal(mean = 0, std = self.apply_std2 * torch.ones(num_b, self.num_features, 1, 1))).cuda() # log normal distribution\n            if self.inv_prop > 0.0:\n                idx = torch.rand(num_b, self.num_features, 1, 1) < self.inv_prop\n                beta[idx] = -beta[idx]\n        elif self.flag_beta == 'normal':\n            beta = torch.normal(mean = 0, std = self.apply_std2 * torch.ones(num_b, self.num_features, 1, 1)).cuda() # normal distribution\n        elif self.flag_beta == 'uniform':\n            beta = self.apply_std2 * (2.0*torch.rand(num_b, self.num_features, 1, 1).cuda()-1) # uniform distribution\n\n        if self.not_used == 'gamma':\n            gamma[:] = 1.0\n        elif self.not_used == 'beta':\n            beta[:] = 0.0\n\n        return gamma, beta\n\n    def forward(self, x, y=None): # old: not same, instance, lognormal\n        if not self.same: # re-initialization\n            self.gamma, self.beta = self.make_parameter()\n\n        if self.style == 'class':\n            gamma = torch.zeros([self.batch_size, self.gamma.size(1), self.gamma.size(2), self.gamma.size(3)]).cuda()\n            beta = torch.zeros([self.batch_size, self.gamma.size(1), self.gamma.size(2), self.gamma.size(3)]).cuda()\n\n            for y_local in range(self.num_classes):\n                idx = [j for j, k in enumerate(y) if k == y_local]\n                if len(idx) > 0:\n                    for idx_local in idx:\n                        gamma[idx_local] = self.gamma[y_local,:,:,:]\n                        beta[idx_local] = self.beta[y_local,:,:,:]\n        else:\n            gamma = self.gamma\n            beta = self.beta\n        if self.norm_true:\n            return gamma * self.norm(x) + beta\n        else:\n            return gamma * x + beta\n\n        \n\n\n\nclass cnnGenerator(nn.Module):\n    def __init__(self, n=16, kernelsize=3, imdim=3, imsize=[192, 320], zdim=10):\n        super().__init__()\n        stride = (kernelsize-1)//2\n        self.zdim = zdim\n        self.imdim = imdim\n        self.imsize = imsize\n\n        self.conv1 = nn.Conv2d(imdim, n, kernelsize, 1, stride)\n        self.conv2 = nn.Conv2d(n, 2*n, kernelsize, 1, stride)\n        self.adain2 = AdaIN2d(zdim, 2*n)\n        self.conv3 = nn.Conv2d(2*n, 4*n, kernelsize, 1, stride)\n        self.conv4 = nn.Conv2d(4*n, imdim, kernelsize, 1, stride)\n\n    def forward(self, x, rand=False): \n        x = F.relu(self.conv1(x))\n        x = F.relu(self.conv2(x))\n        if rand:\n            z = torch.randn(len(x), self.zdim).cuda()\n            x = self.adain2(x, z)\n        x = F.relu(self.conv3(x))\n        x = torch.sigmoid(self.conv4(x))\n        return x\n\nclass RandGenerator(nn.Module):\n    def __init__(self, im_dim=3, im_size=[32, 32], gen_model=None, first_flag=False, gen_num=1, n_tgt=0, step_base_cnt=0, opt={}):\n        super().__init__()\n        \n        self.structure = gen_model['structure']\n        self.init_norm_model = gen_model['init_norm_model']\n        self.deform_offset_style = gen_model['deform_offset_style']\n        self.deform_offset_clamp = gen_model['deform_offset_clamp']\n        self.deform_style = gen_model['deform_style']\n        self.deform_same = gen_model['deform_same']\n        self.deform_global = gen_model['deform_global']\n        self.deform_variable = gen_model['deform_variable']\n        self.deform_variable_range = gen_model['deform_variable_range']\n\n        self.noise_model = gen_model['noise_model']\n        self.noise_style = gen_model['noise_style']\n        self.noise_channel = gen_model['noise_channel']\n        self.noise_prop = gen_model['noise_prop']\n        self.noise_scale = gen_model['noise_scale']\n        self.noise_alpha = gen_model['noise_alpha']\n        self.noise_first = gen_model['noise_first']\n        \n        self.augment_model = gen_model['augment_model']\n\n        self.encoder_model = gen_model['encoder_model']\n        self.encoder_style = gen_model['encoder_style']\n        self.encoder_same = gen_model['encoder_same']\n        self.encoder_act = gen_model['encoder_act']\n        self.encoder_num = gen_model['encoder_num']\n\n        self.norm_model = gen_model['norm_model']\n        self.norm_style = gen_model['norm_style']\n        self.norm_same = gen_model['norm_same']\n        self.norm_std1 = gen_model['norm_std1']\n        self.norm_std2 = gen_model['norm_std2']\n        self.norm_not_used = gen_model['norm_not_used']\n        self.norm_variable_std1 = gen_model['norm_variable_std1']\n        self.norm_variable_std2 = gen_model['norm_variable_std2']\n        self.norm_true = gen_model['norm_true']\n\n        self.norm_inv_prop = gen_model['norm_inv_prop']\n        self.decoder_model = gen_model['decoder_model']\n        self.decoder_style = gen_model['decoder_style']\n        self.decoder_act = gen_model['decoder_act']\n        self.decoder_num = gen_model['decoder_num']\n        self.final_act = gen_model['final_act']\n        self.final_norm = gen_model['final_norm']\n        self.initialization = gen_model['initialization']\n        self.dim = gen_model['dim']\n        self.zdim = gen_model['zdim']\n        self.bias = gen_model['bias']\n        self.input_normalize = gen_model['input_normalize']\n        self.num_classes = gen_model['num_classes']\n        self.batch_size = gen_model['batch_size']\n\n        self.kernelsize = gen_model['kernelsize']\n        self.multiconv_kernelsize = gen_model['multiconv_kernelsize']\n        self.multiconv_same = gen_model['multiconv_same']\n\n        self.variable_kernelsize = gen_model['variable_kernelsize']\n        self.variable_times = gen_model['variable_times']\n        self.variable_th = gen_model['variable_th']\n        self.variable_limit = gen_model['variable_limit']\n        self.variable_updated_flag = gen_model['variable_updated_flag']\n        self.dilation = gen_model['dilation']\n\n        self.im_size = im_size\n        self.im_dim = im_dim\n        self.gen_num = gen_num\n\n        \n        self.n_tgt = n_tgt\n        self.step_base_cnt = step_base_cnt\n        self.opt = opt\n\n        self.init_norm = []\n        self.encoder = []\n        self.norm = []\n        self.decoder = []\n        self.encoder_activation = []\n        self.decoder_activation = []\n\n        self.debug_output = []\n        self.debug_name = []\n\n\n        if self.structure.lower() == 'pden':\n            self.encoder.append(self.conv_flag(self.im_dim,   self.dim, self.bias, self.encoder_model, self.encoder_style))\n            self.encoder.append(self.conv_flag(self.dim,    2*self.dim, self.bias, self.encoder_model, self.encoder_style))\n            self.norm.append(AdaIN2d(self.zdim, 2*self.dim))\n            self.decoder.append(self.conv_flag(2*self.dim,  4*self.dim, self.bias, self.decoder_model, self.encoder_style))\n            self.decoder.append(self.conv_flag(4*self.dim, self.im_dim, self.bias, self.decoder_model, self.encoder_style))\n\n        elif self.structure == 'randconv': \n\n            if 'multi' in self.encoder_model:\n                kernelsize = self.multiconv_kernelsize\n                try:\n                    kernelsize = [int(i) for i in kernelsize.split('_')]\n                except:\n                    kernelsize = [int(i[1:]) for i in kernelsize.split('_')]\n                kernelsize = kernelsize[np.random.randint(len(kernelsize))]\n                self.kernelsize = kernelsize\n            self.encoder.append(self.conv_flag(self.im_dim, self.im_dim, self.bias, self.encoder_model, self.encoder_style))\n\n        elif self.structure == 'vae':\n            \n            # if self.augment_model == 'randaug':\n            #     print('.')\n            #     ia.seed(4)\n            #     self.aug_sequence = iaa.Affine(rotate=(-25, 25))\n                \n            #     torchvision.transforms.ColorJitter(brightness=0, contrast=0, saturation=0, hue=0)\n                \n            #     augment_transform.append(transforms.ColorJitter(0.3, 0.3, 0.3, 0.3))\n            #     tfs = transforms.Compose([\n            #         iaa.Sequential([\n            #             iaa.flip.Fliplr(p=0.5),\n            #             iaa.flip.Flipud(p=0.5),\n            #             iaa.GaussianBlur(sigma=(0.0, 0.1)),\n            #             iaa.MultiplyBrightness(mul=(0.65, 1.35)),\n            #         ]).augment_image,\n            #         transforms.ToTensor()\n            #     ])\n            \n            \n            \n            \n            \n            \n\n            if self.init_norm_model == 'self_in':\n                self.init_norm.append(selfIN2d(self.im_dim))\n            elif self.init_norm_model == 'in': # instance norm\n                self.init_norm.append(IN2d(self.im_dim))\n\n            self.conv_dim = self.dim\n            if self.decoder_num > 0:\n                self.norm_dim = self.conv_dim\n            else:\n                self.norm_dim = self.im_dim\n            if self.encoder_num == 0:\n                self.norm_dim = self.im_dim\n\n            if self.variable_kernelsize == 'none':\n                if 'multi' in self.encoder_model:\n                    kernelsize = self.multiconv_kernelsize\n                    try:\n                        kernelsize = [int(i) for i in kernelsize.split('_')]\n                    except:\n                        kernelsize = [int(i[1:]) for i in kernelsize.split('_')]\n                    kernelsize = kernelsize[np.random.randint(len(kernelsize))]\n                    self.kernelsize = kernelsize\n            elif self.variable_kernelsize == 'increased_gen':\n                self.kernelsize = int(self.gen_num * 2 + 1) # first kernelsize is 3\n            elif self.variable_kernelsize == 'updated_epoch':\n                if len(self.opt) <= 1:\n                    idx = 1\n                    self.kernelsize = int(idx * 2 + 1) \n                else:\n                    if self.variable_updated_flag == 1:\n                        present_val = np.mean(self.opt['GT_logit'])\n                    elif self.variable_updated_flag == 2:\n                        present_val = np.mean(self.opt['predicted_logit'])\n                    elif self.variable_updated_flag == 3:\n                        present_val = np.mean(self.opt['acc'])\n\n                    if present_val > self.variable_th:\n                        changed_flag = True\n                    else:\n                        changed_flag = False\n                        \n                    if changed_flag:\n                        \n                        print('kernelsize is changed {}, step: {}'.format(self.kernelsize, self.step_base_cnt))\n                        self.kernelsize = opt['previous_kernelsize'] + 2\n                    else:\n                        self.kernelsize = opt['previous_kernelsize']\n\n                    if self.kernelsize > self.variable_limit:\n                        self.kernelsize = opt['previous_kernelsize']\n            elif self.variable_kernelsize == 'increased_epoch':\n                idx = math.ceil(self.step_base_cnt * self.variable_times / self.n_tgt)\n                if idx < 1:\n                    idx = 1\n                if idx > self.variable_times:\n                    idx = self.variable_times # idx will be [1,self.variable_times]\n                self.kernelsize = int(idx * 2 + 1) \n            elif self.variable_kernelsize == 'decreased_epoch':\n                idx = math.ceil(self.step_base_cnt * self.variable_times / self.n_tgt)\n                if idx < 1:\n                    idx = 1\n                if idx > self.variable_times:\n                    idx = self.variable_times\n                idx = self.variable_times - idx + 1 \n                self.kernelsize = int(idx * 2 + 1)\n\n        \n            if self.encoder_model != 'none':\n                if self.encoder_same: # re-initialization\n                    \n                    if self.encoder_num == 1:\n                        self.encoder.append(self.conv_flag(self.im_dim, self.norm_dim, self.bias, self.encoder_model, self.encoder_style))\n                    elif self.encoder_num >= 2:\n                        self.encoder.append(self.conv_flag(self.im_dim, self.conv_dim, self.bias, self.encoder_model, self.encoder_style))\n                        for _ in range(self.encoder_num - 2): \n                            self.encoder.append(self.conv_flag(self.conv_dim, self.conv_dim, self.bias, self.encoder_model, self.encoder_style))\n                        self.encoder.append(self.conv_flag(self.conv_dim, self.norm_dim, self.bias, self.encoder_model, self.encoder_style))\n                    \n                    # if 'deform' in self.encoder_model:\n                    #     self.deform_weight = []\n                    #     for i in range(self.encoder_num): \n                    #         self.deform_weight.append(self.deform_weight_flag(self.encoder[i], init=True))\n\n            if 'deform' in self.encoder_model:  \n                self.change_deform_offset = False  \n                if not self.encoder_same and ('multi' in self.encoder_model) and (not self.multiconv_same): # If kernel is changed.\n                    self.change_deform_offset = True\n                if not self.deform_same:\n                    self.change_deform_offset = True\n\n                if not self.change_deform_offset: # re-initialization\n                    # print('deform_offset [init]')\n                    self.deform_offset = []\n                    for i in range(self.encoder_num):\n                        self.deform_offset.append(self.deform_offset_flag(init=True))\n\n            if self.encoder_act != 'none':\n                for _ in range(self.encoder_num):\n                    if self.encoder_act == 'sigmoid':\n                        self.encoder_activation.append(torch.nn.Sigmoid())\n                    elif self.encoder_act == 'tanh':\n                        self.encoder_activation.append(torch.nn.Tanh())\n                    elif self.encoder_act == 'hardtanh':\n                        self.encoder_activation.append(torch.nn.Hardtanh())\n                    elif self.encoder_act == 'relu':\n                        self.encoder_activation.append(torch.nn.ReLU())\n                    elif self.encoder_act == 'lrelu':\n                        self.encoder_activation.append(torch.nn.LeakyReLU(negative_slope=0.01))\n            \n            if self.norm_model == 'adain':\n                self.norm.append(AdaIN2d(self.zdim, self.norm_dim))\n            elif self.norm_model == 'self_in': \n                self.norm.append(selfIN2d(self.norm_dim))\n            elif self.norm_model == 'in': # instance norm\n                self.norm.append(IN2d(self.norm_dim))\n            elif 'adain_' in self.norm_model == 'adain_normal' or self.norm_model == 'adain_uniform' or self.norm_model == 'adain_lognormal':\n                if self.norm_model == 'adain_normal':\n                    flag_gamma = 'normal'\n                    flag_beta = 'normal'\n                elif self.norm_model == 'adain_uniform':\n                    flag_gamma = 'uniform'\n                    flag_beta = 'uniform'\n                elif self.norm_model == 'adain_lognormal':\n                    flag_gamma = 'lognormal'\n                    flag_beta = 'normal'\n                elif self.norm_model == 'adain_uniform_gamma':\n                    flag_gamma = 'uniform'\n                    flag_beta = 'normal'\n                elif self.norm_model == 'adain_uniform_beta':\n                    flag_gamma = 'normal'\n                    flag_beta = 'uniform'\n                elif self.norm_model == 'adain_lognormal_both':\n                    flag_gamma = 'lognormal'\n                    flag_beta = 'lognormal'\n                elif self.norm_model == 'adain_lognormal_uniform':\n                    flag_gamma = 'lognormal'\n                    flag_beta = 'uniform'\n\n\n                norm_opt = {}\n                norm_opt['flag_gamma'] = flag_gamma\n                norm_opt['flag_beta'] = flag_beta\n                norm_opt['num_features'] = self.norm_dim\n                norm_opt['style'] = self.norm_style\n                norm_opt['same'] = self.norm_same\n                norm_opt['batch_size'] = self.batch_size\n                norm_opt['num_classes'] = self.num_classes\n                norm_opt['inv_prop'] = self.norm_inv_prop\n                norm_opt['std1'] = self.norm_std1\n                norm_opt['std2'] = self.norm_std2\n                norm_opt['v_std1'] = self.norm_variable_std1\n                norm_opt['v_std2'] = self.norm_variable_std2\n                norm_opt['norm_true'] = self.norm_true\n                norm_opt['not_used']=self.norm_not_used\n                self.norm.append(GeneralizedAdaIN(norm_opt))\n            #     self.norm.append(GeneralizedAdaIN(flag = 'normal', num_features = self.norm_dim, style = self.norm_style, same=self.norm_same, batch_size=self.batch_size, num_classes = self.num_classes, inv_prop = self.norm_inv_prop, std1 = self.norm_std1, std2 = self.norm_std2, v_std1 = self.norm_variable_std1, v_std2 = self.norm_variable_std2, norm_true = self.norm_true, not_used=self.norm_not_used))\n            # elif self.norm_model == 'adain_uniform': # gamma: uniform, beta: uniform\n            #     self.norm.append(GeneralizedAdaIN(flag = 'uniform', num_features = self.norm_dim, style = self.norm_style, same=self.norm_same, batch_size=self.batch_size, num_classes = self.num_classes, inv_prop = self.norm_inv_prop, std1 = self.norm_std1, std2 = self.norm_std2, v_std1 = self.norm_variable_std1, v_std2 = self.norm_variable_std2, norm_true = self.norm_true, not_used=self.norm_not_used))\n            # elif self.norm_model == 'adain_lognormal': # gamma: lognormal, beta: normal\n            #     self.norm.append(GeneralizedAdaIN(flag = 'lognormal', num_features = self.norm_dim, style = self.norm_style, same=self.norm_same, batch_size=self.batch_size, num_classes = self.num_classes, inv_prop = self.norm_inv_prop, std1 = self.norm_std1, std2 = self.norm_std2, v_std1 = self.norm_variable_std1, v_std2 = self.norm_variable_std2, norm_true = self.norm_true, not_used=self.norm_not_used))\n\n\n\n            if self.decoder_model != 'none':\n                if self.decoder_num == 1:\n                    self.decoder.append(self.conv_flag(self.norm_dim, self.im_dim, self.bias, self.decoder_model, self.decoder_style))\n                elif self.decoder_num >= 2:\n                    self.decoder.append(self.conv_flag(self.norm_dim, self.conv_dim, self.bias, self.decoder_model, self.decoder_style))\n                    for _ in range(self.decoder_num - 2): # if self.decoder_num == 3, cycle 1 time\n                        self.decoder.append(self.conv_flag(self.conv_dim, self.conv_dim, self.bias, self.decoder_model, self.decoder_style))\n                    self.decoder.append(self.conv_flag(self.conv_dim, self.im_dim, self.bias, self.decoder_model, self.decoder_style))\n\n            if self.decoder_act != 'none':\n                for _ in range(self.decoder_num - 1):\n                    if self.decoder_act == 'sigmoid':\n                        self.decoder_activation.append(torch.nn.Sigmoid())\n                    elif self.decoder_act == 'tanh':\n                        self.decoder_activation.append(torch.nn.Tanh())\n                    elif self.decoder_act == 'hardtanh':\n                        self.decoder_activation.append(torch.nn.Hardtanh())\n                    elif self.decoder_act == 'relu':\n                        self.decoder_activation.append(torch.nn.ReLU())\n                    elif self.decoder_act == 'lrelu':\n                        self.decoder_activation.append(torch.nn.LeakyReLU(negative_slope=0.01))\n            if self.final_act != 'none':\n                if self.final_act == 'sigmoid':\n                    self.decoder_activation.append(torch.nn.Sigmoid())\n                elif self.final_act == 'tanh':\n                    self.decoder_activation.append(torch.nn.Tanh())\n                elif self.final_act == 'hardtanh':\n                    self.decoder_activation.append(torch.nn.Hardtanh())\n                elif self.final_act == 'relu':\n                    self.decoder_activation.append(torch.nn.ReLU())\n                elif self.final_act == 'lrelu':\n                    self.decoder_activation.append(torch.nn.LeakyReLU(negative_slope=0.01))\n\n\n        self.init_norm_module = nn.Sequential(*self.init_norm)\n        self.encoder_module = nn.Sequential(*self.encoder)\n        self.encoder_activation_module = nn.Sequential(*self.encoder_activation)\n        self.norm_module = nn.Sequential(*self.norm)\n        self.decoder_module = nn.Sequential(*self.decoder)\n        self.decoder_activation_module = nn.Sequential(*self.decoder_activation)\n\n\n        if first_flag:\n            if len(self.init_norm_module) > 0:\n                print('*-'*10 + ' [encoder] '+'-*'*10)\n                print(self.init_norm_module)\n            if len(self.encoder_module) > 0:\n                print('*-'*10 + ' [encoder] '+'-*'*10)\n                print(self.encoder_module)\n            if len(self.encoder_activation_module) > 0:\n                print('*-'*10 + ' [encoder ACT] '+'-*'*10)\n                print(self.encoder_activation_module)\n            if len(self.norm_module) > 0:\n                print('*-'*10 + ' [norm] '+'-*'*10)\n                print(self.norm_module)\n            if len(self.decoder_module) > 0:\n                print('*-'*10 + ' [decoder] '+'-*'*10)\n                print(self.decoder_module)\n            if len(self.decoder_activation_module) > 0:\n                print('*-'*10 + ' [decoder ACT] '+'-*'*10)\n                print(self.decoder_activation_module)\n\n    def conv_flag(self, dim1, dim2, bias, flag, style):\n        \n        if 'deform' in self.encoder_model:\n            if style == 'channel':\n                output = torchvision.ops.DeformConv2d(dim1, dim2, self.kernelsize, bias=bias, groups=3,dilation=self.dilation)\n            elif style == 'instance':\n                output = torchvision.ops.DeformConv2d(dim1*self.batch_size, dim2*self.batch_size, self.kernelsize, bias=bias, groups=self.batch_size,dilation=self.dilation)\n            elif style == 'class':\n                output = torchvision.ops.DeformConv2d(dim1*self.batch_size, dim2*self.batch_size, self.kernelsize, bias=bias, groups=self.batch_size,dilation=self.dilation)\n            elif style == 'old_class':\n                output = []\n                for _ in range(self.num_classes):\n                    output.append(torchvision.ops.DeformConv2d(dim1, dim2, self.kernelsize, bias=bias,dilation=self.dilation))\n                output = nn.Sequential(*output)\n            else:\n                output = torchvision.ops.DeformConv2d(dim1, dim2, self.kernelsize, bias=bias,dilation=self.dilation)\n            self.m_pad = torch.nn.ReplicationPad2d(((self.kernelsize-1)//2, (self.kernelsize-1)//2, (self.kernelsize-1)//2, (self.kernelsize-1)//2)).cuda()\n        else:\n            if style == 'channel':\n                output = nn.Conv2d(dim1, dim2, self.kernelsize, padding=(self.kernelsize-1)//2, bias=bias, padding_mode='replicate', groups=3)\n            elif style == 'instance':\n                output = nn.Conv2d(dim1*self.batch_size, dim2*self.batch_size, self.kernelsize, padding=(self.kernelsize-1)//2, bias=bias, padding_mode='replicate', groups=self.batch_size)\n            elif style == 'class':\n                output = nn.Conv2d(dim1*self.batch_size, dim2*self.batch_size, self.kernelsize, padding=(self.kernelsize-1)//2, bias=bias, padding_mode='replicate', groups=self.batch_size)\n            elif style == 'old_class':\n                output = []\n                for _ in range(self.num_classes):\n                    output.append(nn.Conv2d(dim1, dim2, self.kernelsize, padding=(self.kernelsize-1)//2, bias=bias, padding_mode='replicate'))\n                output = nn.Sequential(*output)\n            else:\n                output = nn.Conv2d(dim1, dim2, self.kernelsize, padding=(self.kernelsize-1)//2, bias=bias, padding_mode='replicate')\n\n        return output\n\n    def compute_offset(self, k_size1, k_size2, x_size1, x_size2):\n        \n        offset = torch.zeros(self.batch_size, 2*k_size1*k_size2, x_size1, x_size2).cuda()\n        \n        if self.deform_global:\n            x1 = 1\n            x2 = 1\n        else:\n            x1 = x_size1\n            x2 = x_size2\n            \n        if self.deform_style == 'batch': \n            b = 1\n        elif self.deform_style == 'class':\n            b = self.num_classes\n        else:\n            b = self.batch_size\n            \n        if self.deform_variable == 'increased_epoch':\n            deform_offset_range = self.step_base_cnt / self.n_tgt * self.deform_variable_range\n        elif self.deform_variable == 'rand_uniform':\n            deform_offset_range = self.deform_variable_range * torch.rand(1).item()\n            # print('deform:{}'.format(deform_offset_range))\n        elif self.deform_variable == 'none':\n            deform_offset_range = self.deform_variable_range\n            \n        rand_size = [b, 2*k_size1*k_size2, x1, x2]\n        if self.deform_offset_style == 'normal': # [std:offset_range]\n            if self.deform_style == 'class':\n                offset[0:b,:,:,:] = torch.normal(mean = 0, std = deform_offset_range * torch.ones(rand_size)).cuda() # normal distribution\n            else:\n                offset[:,:,:,:] = torch.normal(mean = 0, std = deform_offset_range * torch.ones(rand_size)).cuda() # normal distribution\n            if self.deform_offset_clamp:\n                offset[offset>1.0] = 1.0 # clamp\n                offset[offset<-1.0] = 1.0 # clamp\n        elif self.deform_offset_style == 'uniform': # [-offset_range, offset_range]\n            if self.deform_style == 'class':\n                offset[0:b,:,:,:] = torch.rand(rand_size).cuda()\n            else:\n                offset[:,:,:,:] = torch.rand(rand_size).cuda()\n            offset = deform_offset_range * (offset * 2.0 - 1.0) # for uniform\n            \n        if self.encoder_style == 'class' or self.encoder_style == 'instance':\n            offset = torch.reshape(offset, (1, offset.shape[0]*offset.shape[1], offset.shape[2], offset.shape[3]))\n\n        max_offset = torch.abs(torch.max(offset)).item()\n        min_offset = torch.abs(torch.min(offset)).item()        \n\n        # for solve padding problem\n        for k in range(min(math.ceil(max([max_offset, min_offset])), offset.size(2))):\n            offset[:, :, k, :] = 0.0\n            offset[:, :, -k-1, :] = 0.0\n            offset[:, :, :, k] = 0.0\n            offset[:, :, :, -k-1] = 0.0\n\n        return offset\n\n    # def deform_weight_flag(self, output, init=False):\n    \n    #     deform_weight = output.weight.data.cuda()\n    #     self.m_pad = torch.nn.ReplicationPad2d(((self.kernelsize-1)//2, (self.kernelsize-1)//2, (self.kernelsize-1)//2, (self.kernelsize-1)//2)).cuda()\n\n    #     return deform_weight\n\n    def deform_offset_flag(self, init=False):\n        # offset\n        x_size1 = self.im_size[0]\n        x_size2 = self.im_size[1]\n        deform_offset = self.compute_offset(self.kernelsize, self.kernelsize, x_size1, x_size2)\n        # if not init:\n        deform_offset = deform_offset.cuda()\n\n        return deform_offset\n\n\n    def forward_noise(self, x, y, flag_ori = False):\n        \n        if self.noise_model == 'grf':\n            \n            if (self.noise_first and flag_ori) or self.noise_first == False:\n                if self.noise_style == 'batch':\n                    n = 1\n                elif self.noise_style == 'class':\n                    n = self.num_classes\n                elif self.noise_style == 'instance':\n                    n = self.batch_size\n                x_noise_all = []\n                \n                \n                for _ in range(n):\n                    x_noise_channel = []\n                    for _ in range(self.noise_channel):\n                        x_noise_channel.append(torch.Tensor(grf.gaussian_random_field(alpha=torch.rand(1).item()*self.noise_alpha, size=x.shape[-1])).cuda())\n                    x_noise_channel_all = torch.stack(x_noise_channel)\n                    if torch.rand(1) > self.noise_prop:\n                        x_noise_channel_all[:] = 0.0\n                    x_noise_all.append(x_noise_channel_all)\n                x_noise = torch.stack(x_noise_all)/self.noise_scale\n\n                \n                if self.noise_style == 'class':\n                    xx = torch.zeros_like(x)\n                    for y_local in range(self.num_classes):\n                        idx = [j for j, k in enumerate(y) if k == y_local]\n                        if len(idx) > 0:\n                            for idx_local in idx:\n                                xx[idx_local] = x_noise[y_local,:,:,:]\n                                \n                    x = x + xx.detach()\n                else:\n                    x = x + x_noise.detach()\n        return x\n\n    \n    def forward_init_norm(self, x, y, debug = False, w=[], b=[]):\n\n        for i in range(len(self.init_norm_module)):\n            if self.init_norm_model == 'self_in':\n                if len(w) == 0:\n                    x = self.init_norm_module[i](x, w=self.saved_w, b=self.saved_b)\n                else:\n                    x = self.init_norm_module[i](x, w=w, b=b)\n            else:\n                x = self.init_norm_module[i](x, y=y)\n            if debug:\n                self.debug_name.append('init_norm_'+self.norm_model+str(i))\n                self.debug_output.append(x.clone().detach())\n        \n        return x\n\n    def forward_encoder(self, x, y, debug = False):\n\n        if self.encoder_model != 'none':\n            if not self.encoder_same: # re-initialization\n                \n                if self.variable_kernelsize == 'none':\n                    if ('multi' in self.encoder_model) and (not self.multiconv_same):\n                        kernelsize = self.multiconv_kernelsize\n                        try:\n                            kernelsize = [int(i) for i in kernelsize.split('_')]\n                        except:\n                            kernelsize = [int(i[1:]) for i in kernelsize.split('_')]\n                        kernelsize = kernelsize[np.random.randint(len(kernelsize))]\n                        self.kernelsize = kernelsize\n\n                self.encoder = []\n                if self.encoder_num == 1:\n                    self.encoder.append(self.conv_flag(self.im_dim, self.norm_dim, self.bias, self.encoder_model, self.encoder_style))\n                elif self.encoder_num >= 2:\n                    self.encoder.append(self.conv_flag(self.im_dim, self.conv_dim, self.bias, self.encoder_model, self.encoder_style))\n                    for _ in range(self.encoder_num - 2): \n                        self.encoder.append(self.conv_flag(self.conv_dim, self.conv_dim, self.bias, self.encoder_model, self.encoder_style))\n                    self.encoder.append(self.conv_flag(self.conv_dim, self.norm_dim, self.bias, self.encoder_model, self.encoder_style))\n                self.encoder_module = nn.Sequential(*self.encoder).cuda()\n\n                # if 'deform' in self.encoder_model:\n                #     self.deform_weight = []\n                #     for i in range(self.encoder_num): \n                #         self.deform_weight.append(self.deform_weight_flag(self.encoder[i], init=False))\n            \n        \n        if 'deform' in self.encoder_model:\n            if self.change_deform_offset:\n                # print('deform_offset [changed]')\n                self.deform_offset = []\n                for i in range(self.encoder_num): \n                    self.deform_offset.append(self.deform_offset_flag(init=False))\n\n        # Encoder\n        for i in range(len(self.encoder_module)):\n            # enc module\n            x_shape = x.shape\n            if 'deform' in self.encoder_model: \n                x = self.m_pad(x)\n\n            if self.encoder_style == 'old_class': # y\n                xx = torch.zeros_like(x)\n                for y_local in range(self.num_classes):\n                    idx = [j for j, k in enumerate(y) if k == y_local]\n                    if len(idx) > 0:\n                        if 'deform' in self.encoder_model: \n                            xx[idx] = self.encoder_module[i][y_local](x[idx], self.deform_offset[i])\n                        else:\n                            xx[idx] = self.encoder_module[i][y_local](x[idx])\n                x = xx.clone().detach()\n\n            elif self.encoder_style == 'class': # y\n                if 'deform' in self.encoder_model: \n                    x = torch.reshape(x, (1, x_shape[0]*x_shape[1], x.shape[2], x.shape[3]))\n                    # weight extract (assumption: 3, 3, 3, 3, 3 )\n                    classwise_weight = []\n                    for j in range(self.num_classes):\n                        # j_idx = [z*x_shape[0]+j for z in range(x_shape[1])]\n                        j_idx = [j*x_shape[1]+z for z in range(x_shape[1])]\n                        classwise_weight.append(self.encoder_module[i].weight.data[j_idx].clone().detach())\n                    # weight allocation\n                    for j in range(self.batch_size):\n                        y_local = y[j]\n                        # j_idx = [z*x_shape[0]+j for z in range(x_shape[1])]\n                        j_idx = [j*x_shape[1]+z for z in range(x_shape[1])]\n                        self.encoder_module[i].weight.data[j_idx] = classwise_weight[y_local]\n\n                    if self.deform_style == 'class':\n                        deform_offset = torch.zeros_like(self.deform_offset[i][0])\n                        deform_offset2 = self.deform_offset[i][0].clone().detach()\n                        # weight extract (assumption: 2*kernel*kernel )\n                        classwise_offset = []\n                        for j in range(self.num_classes):\n                            # j_idx = [z*x_shape[0]+j for z in range(x_shape[1])]\n                            j_idx = [j*2*self.kernelsize*self.kernelsize+z for z in range(2*self.kernelsize*self.kernelsize)]\n                            classwise_offset.append(deform_offset2[j_idx])\n                        # weight allocation\n                        for j in range(self.batch_size):\n                            y_local = y[j]\n                            # j_idx = [z*x_shape[0]+j for z in range(x_shape[1])]\n                            j_idx = [j*2*self.kernelsize*self.kernelsize+z for z in range(2*self.kernelsize*self.kernelsize)]\n                            deform_offset[j_idx] = classwise_offset[y_local]\n                        x = self.encoder_module[i](x, deform_offset.unsqueeze(0))\n                    else:\n                        x = self.encoder_module[i](x, self.deform_offset[i])\n\n                    x = torch.reshape(x, (x_shape[0], x_shape[1], x.shape[2], x.shape[3]))\n                else:\n                    x = torch.reshape(x, (1, x_shape[0]*x_shape[1], x.shape[2], x.shape[3]))\n                    # weight extract (assumption: 3, 3, 3, 3, 3 )\n                    classwise_weight = []\n                    for j in range(self.num_classes):\n                        # j_idx = [z*x_shape[0]+j for z in range(x_shape[1])]\n                        j_idx = [j*x_shape[1]+z for z in range(x_shape[1])]\n                        classwise_weight.append(self.encoder_module[i].weight.data[j_idx].clone().detach())\n                    # weight allocation\n                    for j in range(self.batch_size):\n                        y_local = y[j]\n                        # j_idx = [z*x_shape[0]+j for z in range(x_shape[1])]\n                        j_idx = [j*x_shape[1]+z for z in range(x_shape[1])]\n                        self.encoder_module[i].weight.data[j_idx] = classwise_weight[y_local]\n\n                    x = self.encoder_module[i](x)\n                    x = torch.reshape(x, (x_shape[0], x_shape[1], x.shape[2], x.shape[3]))\n            elif self.encoder_style == 'instance':\n                if 'deform' in self.encoder_model: \n                    x = torch.reshape(x, (1, x_shape[0]*x_shape[1], x.shape[2], x.shape[3]))\n                    if self.deform_style == 'class':\n                        deform_offset = torch.zeros_like(self.deform_offset[i][0])\n                        deform_offset2 = self.deform_offset[i][0].clone().detach()\n                        # weight extract (assumption: 2*kernel*kernel )\n                        classwise_offset = []\n                        for j in range(self.num_classes):\n                            # j_idx = [z*x_shape[0]+j for z in range(x_shape[1])]\n                            j_idx = [j*2*self.kernelsize*self.kernelsize+z for z in range(2*self.kernelsize*self.kernelsize)]\n                            classwise_offset.append(deform_offset2[j_idx])\n                        # weight allocation\n                        for j in range(self.batch_size):\n                            y_local = y[j]\n                            # j_idx = [z*x_shape[0]+j for z in range(x_shape[1])]\n                            j_idx = [j*2*self.kernelsize*self.kernelsize+z for z in range(2*self.kernelsize*self.kernelsize)]\n                            deform_offset[j_idx] = classwise_offset[y_local]\n                        x = self.encoder_module[i](x, deform_offset.unsqueeze(0))\n                    else:\n                        x = self.encoder_module[i](x, self.deform_offset[i])\n                    x = torch.reshape(x, (x_shape[0], x_shape[1], x.shape[2], x.shape[3]))\n                else:\n                    x = torch.reshape(x, (1, x_shape[0]*x_shape[1], x.shape[2], x.shape[3]))\n                    x = self.encoder_module[i](x)\n                    x = torch.reshape(x, (x_shape[0], x_shape[1], x.shape[2], x.shape[3]))\n            else:\n                if 'deform' in self.encoder_model: \n                    if self.deform_style == 'class':\n                        \n                        # added (due to different size)\n                        offset = torch.reshape(self.deform_offset[i], (1, self.deform_offset[i].shape[0]*self.deform_offset[i].shape[1], self.deform_offset[i].shape[2], self.deform_offset[i].shape[3]))\n                        deform_offset = torch.zeros_like(offset[0])\n                        deform_offset2 = offset[0].clone().detach()\n                        # weight extract (assumption: 2*kernel*kernel )\n                        classwise_offset = []\n                        for j in range(self.num_classes):\n                            # j_idx = [z*x_shape[0]+j for z in range(x_shape[1])]\n                            j_idx = [j*2*self.kernelsize*self.kernelsize+z for z in range(2*self.kernelsize*self.kernelsize)]\n                            classwise_offset.append(deform_offset2[j_idx])\n                        # weight allocation\n                        for j in range(self.batch_size):\n                            y_local = y[j]\n                            # j_idx = [z*x_shape[0]+j for z in range(x_shape[1])]\n                            j_idx = [j*2*self.kernelsize*self.kernelsize+z for z in range(2*self.kernelsize*self.kernelsize)]\n                            deform_offset[j_idx] = classwise_offset[y_local]\n                        # added (due to different size)\n                        deform_offset = torch.reshape(deform_offset, self.deform_offset[i].shape)\n                        x = self.encoder_module[i](x, deform_offset)\n                    else:\n                        x = self.encoder_module[i](x, self.deform_offset[i])\n                else:\n                    x = self.encoder_module[i](x)\n\n\n            if debug:\n                self.debug_name.append('enc_'+self.encoder_model+str(i))\n                self.debug_output.append(x.clone().detach())\n\n            # enc activation\n            if len(self.encoder_activation_module) > 0:\n                x = self.encoder_activation_module[i](x)\n                if debug:\n                    self.debug_name.append('enc_'+self.encoder_model+str(i)+'_'+self.encoder_act)\n                    self.debug_output.append(x.clone().detach())\n\n        return x\n\n    \n    def forward_norm(self, x, y, debug = False, w=[], b=[], rand=False):\n        \n        # Norm\n        for i in range(len(self.norm_module)):\n            if self.norm_model == 'adain':\n                if rand:\n                    z = torch.randn(len(x), self.zdim).cuda()\n                    x = self.norm_module[i](x, z)\n            elif self.norm_model == 'self_in':\n                if len(w) == 0:\n                    x = self.norm_module[i](x, w=self.saved_w, b=self.saved_b)\n                else:\n                    x = self.norm_module[i](x, w=w, b=b)\n            else:\n                x = self.norm_module[i](x, y=y)\n            if debug:\n                self.debug_name.append('norm_'+self.norm_model+str(i))\n                self.debug_output.append(x.clone().detach())\n\n        return x\n\n\n    def forward_decoder(self, x, y, debug = False):\n        \n        # Decoder\n        if len(self.decoder_activation_module) > len(self.decoder_module):\n            NotImplementedError\n\n        if len(self.decoder_module) > 0:\n            for i in range(len(self.decoder_module)):\n\n                # dec module\n                x = self.decoder_module[i](x)\n                if debug:\n                    self.debug_name.append('dec_'+self.decoder_model+str(i))\n                    self.debug_output.append(x.clone().detach())\n\n                # dec activation\n                if len(self.decoder_activation_module)-1 >= i:\n                    x = self.decoder_activation_module[i](x)\n                    if debug:\n                        self.debug_name.append('enc_'+self.decoder_model+str(i)+'_'+self.decoder_act)\n                        self.debug_output.append(x.clone().detach())\n\n        else: # no decoder (check decoder_Activation)\n            if len(self.decoder_activation_module) == 1: # only final activation\n                x = self.decoder_activation_module[0](x)\n            elif len(self.decoder_activation_module) > 1:\n                NotImplementedError\n\n        return x\n\n    \n    def forward_activation(self, x):\n        \n        if self.final_act != 'none':\n            if self.final_act == 'sigmoid' and self.input_normalize:\n                x = (x - 0.5) / 0.5\n            elif self.final_act == 'tanh' and not self.input_normalize:\n                x = x * 0.5 + 0.5\n\n        if self.final_norm == 'clamp':\n            x[x>1.0] = 1.0\n            if self.input_normalize: # [-1,1]\n                x[x<-1.0] = -1.0\n            else:\n                x[x<0] = 0.0\n        elif self.final_norm == 'each_minmax':\n            for j in range(len(x)):\n                x[j] = (x[j] - x[j].min()) / (x[j].max() - x[j].min() + 0.00000001)\n                if self.input_normalize:\n                    x[j] = (x[j] - 0.5) / 0.5\n        elif self.final_norm == 'batch_minmax':\n            x = (x-x.min()) / (x.max()-x.min() + 0.00000001)\n            if self.input_normalize:\n                x = (x-0.5)/0.5\n\n        return x\n\n    def forward(self, x, rand=False, debug=False, w=[], b=[], y=[], flag_ori=False): \n        if len(w) > 0:\n            self.saved_w = w\n            self.saved_b = b\n\n        x = self.forward_noise(x, y, flag_ori)\n        x = self.forward_init_norm(x, y, debug, w, b)\n        x = self.forward_encoder(x, y, debug)\n        x = self.forward_norm(x, y, debug, w, b, rand)\n        x = self.forward_decoder(x, y, debug)\n        x = self.forward_activation(x)\n\n        if debug:\n            return x, self.debug_output, self.debug_name\n        else:\n            return x, None, None\n\nclass stnGenerator(nn.Module):\n    ''' 仿射变换 '''\n    def __init__(self, zdim=10, imsize=[32,32], mode=None):\n        super().__init__()\n        self.mode = mode\n        self.zdim = zdim\n        \n        self.mapz = nn.Linear(zdim, imsize[0]*imsize[1])\n        if imsize == [32,32]:\n            self.loc = nn.Sequential(\n                    nn.Conv2d( 4,  16, 5), nn.MaxPool2d(2), nn.ReLU(),\n                    nn.Conv2d( 16, 32, 5), nn.MaxPool2d(2), nn.ReLU(),)\n            self.fc_loc = nn.Sequential(\n                    nn.Linear(32*5*5, 32), nn.ReLU(),\n                    nn.Linear(32, 6))\n        # init the weight\n        self.fc_loc[2].weight.data.zero_()\n        self.fc_loc[2].bias.data.copy_(torch.tensor([1,0,0,0,1,0]))\n    def forward(self, x, rand, return_H=False):\n        if rand:\n            z = torch.randn(len(x), self.zdim).cuda()\n        z = self.mapz(z).view(len(x), 1, x.size(2), x.size(3))\n        loc = self.loc(torch.cat([x, z], dim=1)) # [N, -1]\n        loc = loc.view(len(loc), -1)\n        H = self.fc_loc(loc)\n        H = H.view(len(H), 2, 3)\n        if self.mode == 'translate':\n            H[:,0,0] = 1 \n            H[:,0,1] = 0 \n            H[:,1,0] = 0 \n            H[:,1,1] = 1 \n        grid = F.affine_grid(H, x.size())\n        x = F.grid_sample(x, grid)\n        if return_H:\n            return x, H\n        else:\n            return x\n\n", "meta": {"hexsha": "42c914b735f8c1d0cb3861aeda7738a9b2535897", "size": 68694, "ext": "py", "lang": "Python", "max_stars_repo_path": "domainbed/networks.py", "max_stars_repo_name": "bismex/DomainBed", "max_stars_repo_head_hexsha": "27335e6ba24a946fedd2c52b13e39df132a89008", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "domainbed/networks.py", "max_issues_repo_name": "bismex/DomainBed", "max_issues_repo_head_hexsha": "27335e6ba24a946fedd2c52b13e39df132a89008", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "domainbed/networks.py", "max_forks_repo_name": "bismex/DomainBed", "max_forks_repo_head_hexsha": "27335e6ba24a946fedd2c52b13e39df132a89008", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-11T11:09:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T11:09:12.000Z", "avg_line_length": 44.2615979381, "max_line_length": 410, "alphanum_fraction": 0.5451422249, "include": true, "reason": "import numpy", "num_tokens": 15889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.26284183159693775, "lm_q1q2_score": 0.1802962111372746}}
{"text": "from . import Utils\nfrom . import DataMisfit\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport warnings\nfrom .PF import Magnetics\nfrom . import Regularization\nfrom . import Mesh\nfrom . import ObjectiveFunction\nimport json\n\n\nclass InversionDirective:\n    \"\"\"InversionDirective\"\"\"\n\n    debug = False  #: Print debugging information\n    _regPair = [\n        Regularization.BaseComboRegularization,\n        Regularization.BaseRegularization,\n        ObjectiveFunction.ComboObjectiveFunction,\n    ]\n    _dmisfitPair = [DataMisfit.BaseDataMisfit, ObjectiveFunction.ComboObjectiveFunction]\n\n    def __init__(self, **kwargs):\n        Utils.setKwargs(self, **kwargs)\n\n    @property\n    def inversion(self):\n        \"\"\"This is the inversion of the InversionDirective instance.\"\"\"\n        return getattr(self, \"_inversion\", None)\n\n    @inversion.setter\n    def inversion(self, i):\n        # if getattr(self, '_inversion', None) is not None:\n        #     warnings.warn(\n        #         'InversionDirective {0!s} has switched to a new inversion.'\n        #         .format(self.__class__.__name__)\n        #     )\n        self._inversion = i\n\n    @property\n    def invProb(self):\n        return self.inversion.invProb\n\n    @property\n    def opt(self):\n        return self.invProb.opt\n\n    @property\n    def reg(self):\n        if getattr(self, \"_reg\", None) is None:\n            self.reg = self.invProb.reg  # go through the setter\n        return self._reg\n\n    @reg.setter\n    def reg(self, value):\n        assert any(\n            [isinstance(value, regtype) for regtype in self._regPair]\n        ), \"Regularization must be in {}, not {}\".format(self._regPair, type(value))\n\n        if isinstance(value, Regularization.BaseComboRegularization):\n            value = 1 * value  # turn it into a combo objective function\n        self._reg = value\n\n    @property\n    def dmisfit(self):\n        if getattr(self, \"_dmisfit\", None) is None:\n            self.dmisfit = self.invProb.dmisfit  # go through the setter\n        return self._dmisfit\n\n    @dmisfit.setter\n    def dmisfit(self, value):\n\n        assert any(\n            [isinstance(value, dmisfittype) for dmisfittype in self._dmisfitPair]\n        ), \"Regularization must be in {}, not {}\".format(self._dmisfitPair, type(value))\n\n        if not isinstance(value, ObjectiveFunction.ComboObjectiveFunction):\n            value = 1 * value  # turn it into a combo objective function\n        self._dmisfit = value\n\n    @property\n    def survey(self):\n        \"\"\"\n           Assuming that dmisfit is always a ComboObjectiveFunction,\n           return a list of surveys for each dmisfit [survey1, survey2, ... ]\n        \"\"\"\n        return [objfcts.survey for objfcts in self.dmisfit.objfcts]\n\n    @property\n    def prob(self):\n        \"\"\"\n           Assuming that dmisfit is always a ComboObjectiveFunction,\n           return a list of problems for each dmisfit [prob1, prob2, ...]\n        \"\"\"\n        return [objfcts.prob for objfcts in self.dmisfit.objfcts]\n\n    def initialize(self):\n        pass\n\n    def endIter(self):\n        pass\n\n    def finish(self):\n        pass\n\n    def validate(self, directiveList=None):\n        return True\n\n\nclass DirectiveList:\n\n    dList = None  #: The list of Directives\n\n    def __init__(self, *directives, **kwargs):\n        self.dList = []\n        for d in directives:\n            assert isinstance(\n                d, InversionDirective\n            ), \"All directives must be InversionDirectives not {}\".format(type(d))\n            self.dList.append(d)\n        Utils.setKwargs(self, **kwargs)\n\n    @property\n    def debug(self):\n        return getattr(self, \"_debug\", False)\n\n    @debug.setter\n    def debug(self, value):\n        for d in self.dList:\n            d.debug = value\n        self._debug = value\n\n    @property\n    def inversion(self):\n        \"\"\"This is the inversion of the InversionDirective instance.\"\"\"\n        return getattr(self, \"_inversion\", None)\n\n    @inversion.setter\n    def inversion(self, i):\n        if self.inversion is i:\n            return\n        if getattr(self, \"_inversion\", None) is not None:\n            warnings.warn(\n                f\"{self.__class__.__name__!s} has switched to a new inversion.\"\n            )\n        for d in self.dList:\n            d.inversion = i\n        self._inversion = i\n\n    def call(self, ruleType):\n        if self.dList is None:\n            if self.debug:\n                print(\"DirectiveList is None, no directives to call!\")\n            return\n\n        directives = [\"initialize\", \"endIter\", \"finish\"]\n        assert ruleType in directives, 'Directive type must be in [\"{!s}\"]'.format(\n            '\", \"'.join(directives)\n        )\n        for r in self.dList:\n            getattr(r, ruleType)()\n\n    def validate(self):\n        [directive.validate(self) for directive in self.dList]\n        return True\n\n\nclass BetaEstimate_ByEig(InversionDirective):\n    \"\"\"BetaEstimate\"\"\"\n\n    beta0 = None  #: The initial Beta (regularization parameter)\n    beta0_ratio = 1e2  #: estimateBeta0 is used with this ratio\n\n    def initialize(self):\n        \"\"\"\n            The initial beta is calculated by comparing the estimated\n            eigenvalues of JtJ and WtW.\n\n            To estimate the eigenvector of **A**, we will use one iteration\n            of the *Power Method*:\n\n            .. math::\n\n                \\\\mathbf{x_1 = A x_0}\n\n            Given this (very course) approximation of the eigenvector, we can\n            use the *Rayleigh quotient* to approximate the largest eigenvalue.\n\n            .. math::\n\n                \\\\lambda_0 = \\\\frac{\\\\mathbf{x^\\\\top A x}}{\\\\mathbf{x^\\\\top x}}\n\n            We will approximate the largest eigenvalue for both JtJ and WtW,\n            and use some ratio of the quotient to estimate beta0.\n\n            .. math::\n\n                \\\\beta_0 = \\\\gamma \\\\frac{\\\\mathbf{x^\\\\top J^\\\\top J x}}{\\\\mathbf{x^\\\\top W^\\\\top W x}}\n\n            :rtype: float\n            :return: beta0\n        \"\"\"\n\n        if self.debug:\n            print(\"Calculating the beta0 parameter.\")\n\n        m = self.invProb.model\n        f = self.invProb.getFields(m, store=True, deleteWarmstart=False)\n\n        x0 = np.random.rand(m.shape[0])\n        t = np.dot(x0, self.dmisfit.deriv2(m, x0, f=f))\n        b = np.dot(x0, self.reg.deriv2(m, v=x0))\n\n        self.beta0 = self.beta0_ratio * (t / b)\n\n        self.invProb.beta = self.beta0\n\n\nclass BetaSchedule(InversionDirective):\n    \"\"\"BetaSchedule\"\"\"\n\n    coolingFactor = 8.0\n    coolingRate = 3\n\n    def endIter(self):\n        if self.opt.iter > 0 and self.opt.iter % self.coolingRate == 0:\n            if self.debug:\n                print(\n                    \"BetaSchedule is cooling Beta. Iteration: {:d}\".format(\n                        self.opt.iter\n                    )\n                )\n            self.invProb.beta /= self.coolingFactor\n\n\nclass TargetMisfit(InversionDirective):\n\n    chifact = 1.0\n    phi_d_star = None\n\n    @property\n    def target(self):\n        if getattr(self, \"_target\", None) is None:\n            # the factor of 0.5 is because we do phid = 0.5*|| dpred - dobs||^2\n            if self.phi_d_star is None:\n\n                nD = 0\n                for survey in self.survey:\n                    nD += survey.nD\n\n                self.phi_d_star = 0.5 * nD\n\n            self._target = self.chifact * self.phi_d_star\n        return self._target\n\n    @target.setter\n    def target(self, val):\n        self._target = val\n\n    def endIter(self):\n        if self.invProb.phi_d < self.target:\n            self.opt.stopNextIteration = True\n\n\nclass SaveEveryIteration(InversionDirective):\n    @property\n    def name(self):\n        if getattr(self, \"_name\", None) is None:\n            self._name = \"InversionModel\"\n        return self._name\n\n    @name.setter\n    def name(self, value):\n        self._name = value\n\n    @property\n    def fileName(self):\n        if getattr(self, \"_fileName\", None) is None:\n            from datetime import datetime\n\n            self._fileName = \"{!s}-{!s}\".format(\n                self.name, datetime.now().strftime(\"%Y-%m-%d-%H-%M\")\n            )\n        return self._fileName\n\n    @fileName.setter\n    def fileName(self, value):\n        self._fileName = value\n\n\nclass SaveModelEveryIteration(SaveEveryIteration):\n    \"\"\"SaveModelEveryIteration\"\"\"\n\n    def initialize(self):\n        print(\n            \"SimPEG.SaveModelEveryIteration will save your models as: '###-{!s}.npy'\".format(\n                self.fileName\n            )\n        )\n\n    def endIter(self):\n        np.save(f\"{self.opt.iter:03d}-{self.fileName!s}\", self.opt.xc)\n\n\nclass SaveUBCModelEveryIteration(SaveEveryIteration):\n    \"\"\"SaveModelEveryIteration\"\"\"\n\n    replace = True\n    saveComp = True\n    mapping = None\n    vector = False\n    mesh = None\n\n    def initialize(self):\n\n        if getattr(self, \"mapping\", None) is None:\n            return self.mapPair()\n        print(\n            \"SimPEG.SaveModelEveryIteration will save your models\"\n            + f\" in UBC format as: '###-{self.fileName!s}.mod'\"\n        )\n\n    def endIter(self):\n\n        if not self.replace:\n            fileName = self.fileName + \"Iter\" + str(self.opt.iter)\n        else:\n            fileName = self.fileName\n\n        count = -1\n        for prob, survey, reg in zip(self.prob, self.survey, self.reg.objfcts):\n\n            count += 1\n\n            # if getattr(prob, 'mapping', None) is not None:\n            #     xc = prob.mapping * self.opt.xc\n\n            # else:\n            xc = self.mapping * self.opt.xc\n\n            # # Save predicted data\n            # if len(self.prob) > 1:\n            #     Magnetics.writeUBCobs(fileName + \"Prob\" + str(count) + '.pre', survey, survey.dpred(m=self.opt.xc))\n\n            # else:\n            #     Magnetics.writeUBCobs(fileName + '.pre', survey, survey.dpred(m=self.opt.xc))\n\n            # Save model\n            if not self.vector:\n\n                if isinstance(self.mesh, Mesh.TreeMesh):\n                    Mesh.TreeMesh.writeUBC(\n                        self.mesh, fileName + \".msh\", models={fileName + \".mod\": xc}\n                    )\n\n                else:\n                    Mesh.TensorMesh.writeModelUBC(self.mesh, fileName + \".mod\", xc)\n            else:\n\n                nC = self.mesh.nC\n\n                if prob.coordinate_system == \"spherical\":\n                    vec_xyz = Utils.matutils.atp2xyz(\n                        xc.reshape((int(len(xc) / 3), 3), order=\"F\")\n                    )\n                    theta = xc[nC : 2 * nC]\n                    phi = xc[2 * nC :]\n                else:\n                    vec_xyz = xc\n                    atp = Utils.matutils.xyz2atp(\n                        xc.reshape((int(len(xc) / 3), 3), order=\"F\")\n                    )\n                    theta = atp[nC : 2 * nC]\n                    phi = atp[2 * nC :]\n\n                vec_x = vec_xyz[:nC]\n                vec_y = vec_xyz[nC : 2 * nC]\n                vec_z = vec_xyz[2 * nC :]\n\n                vec = np.c_[vec_x, vec_y, vec_z]\n\n                m_pst = Utils.matutils.xyz2pst(vec, self.survey[0].srcField.param)\n                m_ind = m_pst.copy()\n                m_ind[:, 1:] = 0.0\n                m_ind = Utils.matutils.pst2xyz(m_ind, self.survey[0].srcField.param)\n\n                m_rem = m_pst.copy()\n                m_rem[:, 0] = 0.0\n                m_rem = Utils.matutils.pst2xyz(m_rem, self.survey[0].srcField.param)\n\n                if self.saveComp:\n                    if isinstance(self.mesh, Mesh.TreeMesh):\n                        Mesh.TreeMesh.writeUBC(\n                            self.mesh,\n                            fileName + \".msh\",\n                            models={\n                                fileName + \".dip\": (np.rad2deg(theta)),\n                                fileName + \".azm\": ((450 - np.rad2deg(phi)) % 360),\n                                fileName + \"_TOT.mod\": np.sum(vec ** 2, axis=1) ** 0.5,\n                                fileName\n                                + \"_IND.mod\": np.sum(m_ind ** 2, axis=1) ** 0.5,\n                                fileName\n                                + \"_REM.mod\": np.sum(m_rem ** 2, axis=1) ** 0.5,\n                            },\n                        )\n\n                        Utils.io_utils.writeVectorUBC(self.mesh, fileName + \".fld\", vec)\n\n                    else:\n                        Mesh.TensorMesh.writeModelUBC(\n                            self.mesh, fileName + \".dip\", (np.rad2deg(theta))\n                        )\n                        Mesh.TensorMesh.writeModelUBC(\n                            self.mesh, fileName + \".azm\", (450 - np.rad2deg(phi)) % 360\n                        )\n                        Mesh.TensorMesh.writeModelUBC(\n                            self.mesh,\n                            fileName + \"_TOT.mod\",\n                            np.sum(vec ** 2, axis=1) ** 0.5,\n                        )\n                        Mesh.TensorMesh.writeModelUBC(\n                            self.mesh,\n                            fileName + \"_IND.mod\",\n                            np.sum(m_ind ** 2, axis=1) ** 0.5,\n                        )\n                        Mesh.TensorMesh.writeModelUBC(\n                            self.mesh,\n                            fileName + \"_REM.mod\",\n                            np.sum(m_rem ** 2, axis=1) ** 0.5,\n                        )\n                        Utils.io_utils.writeVectorUBC(\n                            self.mesh, fileName + \"_VEC.fld\", vec\n                        )\n\n\nclass SaveUBCPredictedEveryIteration(SaveEveryIteration):\n    \"\"\"SaveModelEveryIteration\"\"\"\n\n    replace = True\n    format = \"grav\"\n    fileName = \"Predicted\"\n    residuals = True\n    survey = None\n\n    def initialize(self):\n\n        self.invProb.evalFunction(self.invProb.model, return_g=False, return_H=False)\n\n        residuals = self.survey.dobs - self.invProb.dpred\n\n        if self.format == \"grav\":\n            Utils.io_utils.writeUBCgravityObservations(\n                self.fileName + \"_Initial.pre\", self.survey, self.invProb.dpred\n            )\n\n            if self.residuals:\n                Utils.io_utils.writeUBCgravityObservations(\n                    self.fileName + \"_Initial_Residual.pre\", self.survey, residuals\n                )\n\n        elif self.format in [\"mag\", \"mvi\", \"mvis\"]:\n            Utils.io_utils.writeUBCmagneticsObservations(\n                self.fileName + \"_Initial.pre\", self.survey, self.invProb.dpred\n            )\n\n            if self.residuals:\n                Utils.io_utils.writeUBCmagneticsObservations(\n                    self.fileName + \"_Initial_Residual.pre\", self.survey, residuals\n                )\n\n        print(\n            \"SimPEG.SavePredictedEveryIteration will save your predicted data\"\n            + f\" in UBC format as: '###-{self.fileName!s}.mod'\"\n        )\n\n    def endIter(self):\n\n        if not self.replace:\n            fileName = self.fileName + \"Iter\" + str(self.opt.iter)\n        else:\n            fileName = self.fileName\n\n        residuals = self.survey.dobs - self.invProb.dpred\n\n        if self.format == \"grav\":\n            Utils.io_utils.writeUBCgravityObservations(\n                fileName + \".pre\", self.survey, self.invProb.dpred\n            )\n\n            if self.residuals:\n                Utils.io_utils.writeUBCgravityObservations(\n                    fileName + \"_Residual.pre\", self.survey, residuals\n                )\n\n        elif self.format in [\"mag\", \"mvi\", \"mvis\"]:\n            Utils.io_utils.writeUBCmagneticsObservations(\n                fileName + \".pre\", self.survey, self.invProb.dpred\n            )\n\n            if self.residuals:\n                Utils.io_utils.writeUBCmagneticsObservations(\n                    fileName + \"_Residual.pre\", self.survey, residuals\n                )\n\n\nclass SaveOutputEveryIteration(SaveEveryIteration):\n    \"\"\"SaveModelEveryIteration\"\"\"\n\n    header = None\n    save_txt = True\n    beta = None\n    phi_d = None\n    phi_m = None\n    phi_m_small = None\n    phi_m_smooth_x = None\n    phi_m_smooth_y = None\n    phi_m_smooth_z = None\n    phi = None\n\n    def initialize(self):\n        if self.save_txt is True:\n            print(\n                \"SimPEG.SaveOutputEveryIteration will save your inversion \"\n                \"progress as: '###-{!s}.txt'\".format(self.fileName)\n            )\n            f = open(self.fileName + \".txt\", \"w\")\n            self.header = \"  #     beta     phi_d     phi_m   phi_m_small     phi_m_smoomth_x     phi_m_smoomth_y     phi_m_smoomth_z      phi\\n\"\n            f.write(self.header)\n            f.close()\n\n        self.beta = []\n        self.phi_d = []\n        self.phi_m = []\n        self.phi_m_small = []\n        self.phi_m_smooth_x = []\n        self.phi_m_smooth_y = []\n        self.phi_m_smooth_z = []\n        self.phi = []\n\n    def endIter(self):\n        phi_s, phi_x, phi_y, phi_z = 0, 0, 0, 0\n        for reg in self.reg.objfcts:\n\n            # f_m = reg.objfcts[0].f_m\n            # phi_s += np.sum(f_m**2./(f_m**2. + 1e-8)**(1-reg.objfcts[0].norm/2.))\n\n            # f_m = reg.objfcts[1].f_m\n            # phi_x += np.sum(f_m**2./(f_m**2. + 1e-8)**(1-reg.objfcts[1].norm/2.))\n            phi_s += reg.objfcts[0](self.invProb.model) * reg.alpha_s\n            phi_x += reg.objfcts[1](self.invProb.model) * reg.alpha_x\n\n            if reg.regmesh.dim > 1:\n                # f_m = reg.objfcts[2].f_m\n                # phi_x += np.sum(f_m**2./(f_m**2. + 1e-8)**(1-reg.objfcts[2].norm/2.))\n                phi_y += reg.objfcts[2](self.invProb.model) * reg.alpha_y\n\n            if reg.regmesh.dim > 2:\n                # f_m = reg.objfcts[3].f_m\n                # phi_x += np.sum(f_m**2./(f_m**2. + 1e-8)**(1-reg.objfcts[3].norm/2.))\n\n                phi_z += reg.objfcts[3](self.invProb.model) * reg.alpha_z\n\n            # elif reg.regmesh.dim == 3:\n            #     phi_y += (\n            #         reg.objfcts[2](self.invProb.model) * reg.alpha_y\n            #     )\n\n        self.beta.append(self.invProb.beta)\n        self.phi_d.append(self.invProb.phi_d)\n        self.phi_m.append(self.invProb.phi_m)\n        self.phi_m_small.append(phi_s)\n        self.phi_m_smooth_x.append(phi_x)\n        self.phi_m_smooth_y.append(phi_y)\n        self.phi_m_smooth_z.append(phi_z)\n        self.phi.append(self.opt.f)\n\n        if self.save_txt:\n            f = open(self.fileName + \".txt\", \"a\")\n            f.write(\n                \" {:3d} {:1.4e} {:1.4e} {:1.4e} {:1.4e} {:1.4e} \"\n                \"{:1.4e}  {:1.4e}  {:1.4e}\\n\".format(\n                    self.opt.iter,\n                    self.beta[self.opt.iter - 1],\n                    self.phi_d[self.opt.iter - 1],\n                    self.phi_m[self.opt.iter - 1][0],\n                    self.phi_m_small[self.opt.iter - 1],\n                    self.phi_m_smooth_x[self.opt.iter - 1],\n                    self.phi_m_smooth_y[self.opt.iter - 1],\n                    self.phi_m_smooth_z[self.opt.iter - 1],\n                    self.phi[self.opt.iter - 1][0],\n                )\n            )\n            f.close()\n\n    def load_results(self):\n        results = np.loadtxt(self.fileName + \".txt\", comments=\"#\")\n        self.beta = results[:, 1]\n        self.phi_d = results[:, 2]\n        self.phi_m = results[:, 3]\n        self.phi_m_small = results[:, 4]\n        self.phi_m_smooth_x = results[:, 5]\n        self.phi_m_smooth_y = results[:, 6]\n        self.phi_m_smooth_z = results[:, 7]\n\n        if self.reg.regmesh.dim == 1:\n            self.phi_m_smooth = self.phi_m_smooth_x.copy()\n        elif self.reg.regmesh.dim == 2:\n            self.phi_m_smooth = self.phi_m_smooth_x + self.phi_m_smooth_y\n        elif self.reg.regmesh.dim == 3:\n            self.phi_m_smooth = (\n                self.phi_m_smooth_x + self.phi_m_smooth_y + self.phi_m_smooth_z\n            )\n\n        self.f = results[:, 7]\n\n        self.target_misfit = self.invProb.dmisfit.prob.survey.nD / 2.0\n        self.i_target = None\n\n        if self.invProb.phi_d < self.target_misfit:\n            i_target = 0\n            while self.phi_d[i_target] > self.target_misfit:\n                i_target += 1\n            self.i_target = i_target\n\n    def plot_misfit_curves(self, fname=None, plot_small_smooth=False):\n\n        self.target_misfit = self.invProb.dmisfit.prob.survey.nD / 2.0\n        self.i_target = None\n\n        if self.invProb.phi_d < self.target_misfit:\n            i_target = 0\n            while self.phi_d[i_target] > self.target_misfit:\n                i_target += 1\n            self.i_target = i_target\n\n        fig = plt.figure(figsize=(5, 2))\n        ax = plt.subplot(111)\n        ax_1 = ax.twinx()\n        ax.semilogy(np.arange(len(self.phi_d)), self.phi_d, \"k-\", lw=2)\n        ax_1.semilogy(np.arange(len(self.phi_d)), self.phi_m, \"r\", lw=2)\n        if plot_small_smooth:\n            ax_1.semilogy(np.arange(len(self.phi_d)), self.phi_m_small, \"ro\")\n            ax_1.semilogy(np.arange(len(self.phi_d)), self.phi_m_smooth, \"rx\")\n            ax_1.legend((r\"$\\phi_m$\", \"small\", \"smooth\"), bbox_to_anchor=(1.5, 1.0))\n\n        ax.plot(\n            np.r_[ax.get_xlim()[0], ax.get_xlim()[1]],\n            np.ones(2) * self.target_misfit,\n            \"k:\",\n        )\n        ax.set_xlabel(\"Iteration\")\n        ax.set_ylabel(r\"$\\phi_d$\")\n        ax_1.set_ylabel(r\"$\\phi_m$\", color=\"r\")\n        for tl in ax_1.get_yticklabels():\n            tl.set_color(\"r\")\n        plt.show()\n\n    def plot_tikhonov_curves(self, fname=None, dpi=200):\n\n        self.target_misfit = self.invProb.dmisfit.prob.survey.nD / 2.0\n        self.i_target = None\n\n        if self.invProb.phi_d < self.target_misfit:\n            i_target = 0\n            while self.phi_d[i_target] > self.target_misfit:\n                i_target += 1\n            self.i_target = i_target\n\n        fig = plt.figure(figsize=(5, 8))\n        ax1 = plt.subplot(311)\n        ax2 = plt.subplot(312)\n        ax3 = plt.subplot(313)\n\n        ax1.plot(self.beta, self.phi_d, \"k-\", lw=2, ms=4)\n        ax1.set_xlim(np.hstack(self.beta).min(), np.hstack(self.beta).max())\n        ax1.set_xlabel(\"$\\\\beta$\", fontsize=14)\n        ax1.set_ylabel(r\"$\\phi_d$\", fontsize=14)\n\n        ax2.plot(self.beta, self.phi_m, \"k-\", lw=2)\n        ax2.set_xlim(np.hstack(self.beta).min(), np.hstack(self.beta).max())\n        ax2.set_xlabel(\"$\\\\beta$\", fontsize=14)\n        ax2.set_ylabel(r\"$\\phi_m$\", fontsize=14)\n\n        ax3.plot(self.phi_m, self.phi_d, \"k-\", lw=2)\n        ax3.set_xlim(np.hstack(self.phi_m).min(), np.hstack(self.phi_m).max())\n        ax3.set_xlabel(r\"$\\phi_m$\", fontsize=14)\n        ax3.set_ylabel(r\"$\\phi_d$\", fontsize=14)\n\n        if self.i_target is not None:\n            ax1.plot(self.beta[self.i_target], self.phi_d[self.i_target], \"k*\", ms=10)\n            ax2.plot(self.beta[self.i_target], self.phi_m[self.i_target], \"k*\", ms=10)\n            ax3.plot(self.phi_m[self.i_target], self.phi_d[self.i_target], \"k*\", ms=10)\n\n        for ax in [ax1, ax2, ax3]:\n            ax.set_xscale(\"log\")\n            ax.set_yscale(\"log\")\n        plt.tight_layout()\n        plt.show()\n        if fname is not None:\n            fig.savefig(fname, dpi=dpi)\n\n\nclass SaveOutputDictEveryIteration(SaveEveryIteration):\n    \"\"\"\n        Saves inversion parameters at every iteraion.\n    \"\"\"\n\n    # Initialize the output dict\n    outDict = None\n    outDict = {}\n\n    def initialize(self):\n        print(\n            \"SimPEG.SaveOutputDictEveryIteration will save your inversion progress as dictionary: '###-{!s}.npz'\".format(\n                self.fileName\n            )\n        )\n\n    def endIter(self):\n\n        regCombo = [\"phi_ms\", \"phi_msx\"]\n\n        if self.prob[0].mesh.dim >= 2:\n            regCombo += [\"phi_msy\"]\n\n        if self.prob[0].mesh.dim == 3:\n            regCombo += [\"phi_msz\"]\n\n        # Initialize the output dict\n        iterDict = {}\n\n        # Save the data.\n        iterDict[\"iter\"] = self.opt.iter\n        iterDict[\"beta\"] = self.invProb.beta\n        iterDict[\"phi_d\"] = self.invProb.phi_d\n        iterDict[\"phi_m\"] = self.invProb.phi_m\n\n        for label, fcts in zip(regCombo, self.reg.objfcts[0].objfcts):\n            iterDict[label] = fcts(self.invProb.model)\n\n        iterDict[\"f\"] = self.opt.f\n        iterDict[\"m\"] = self.invProb.model\n        iterDict[\"dpred\"] = self.invProb.dpred\n\n        if hasattr(self.dmisfit.objfcts[0].prob, \"coordinate_system\") is True:\n            iterDict[\"coordinate_system\"] = self.dmisfit.objfcts[\n                0\n            ].prob.coordinate_system\n        else:\n            iterDict[\"coordinate_system\"] = False\n\n        if hasattr(self.reg.objfcts[0], \"eps_p\") is True:\n            iterDict[\"eps_p\"] = self.reg.objfcts[0].eps_p\n            iterDict[\"eps_q\"] = self.reg.objfcts[0].eps_q\n\n        iterDict[\"IRLSiterStart\"] = None\n        for direct in self.inversion.directiveList.dList:\n            if isinstance(direct, Update_IRLS) and hasattr(direct, \"iterStart\") is True:\n                if direct.IRLSiter > 0:\n                    iterDict[\"IRLSiterStart\"] = direct.iterStart\n\n        if hasattr(self.reg.objfcts[0], \"norms\") is True:\n            for objfct in self.reg.objfcts[0].objfcts:\n                objfct.stashedR = None\n\n            iterDict[\"lps\"] = self.reg.objfcts[0].norms[0][0]\n            iterDict[\"lpx\"] = self.reg.objfcts[0].norms[0][1]\n\n        iterDict[\"dphisdm\"] = self.reg.objfcts[0].alpha_s * self.reg.objfcts[0].objfcts[\n            0\n        ].deriv(self.invProb.model)\n        iterDict[\"dphixdm\"] = self.reg.objfcts[0].alpha_x * self.reg.objfcts[0].objfcts[\n            1\n        ].deriv(self.invProb.model)\n\n        # Save the file as a npz\n        self.outDict[self.opt.iter] = iterDict\n\n\nclass SaveIterationsGeoH5(InversionDirective):\n    \"\"\"\n        Saves inversion results to a geoh5 file\n    \"\"\"\n\n    # Initialize the output dict\n    h5_object = None\n    channels = [\"model\"]\n    attribute = \"model\"\n    association = \"VERTEX\"\n    sorting = None\n    mapping = None\n    save_objective_function = False\n    data_type = {}\n    replace_values = False\n    no_data_value = None\n\n    def initialize(self):\n\n        if self.attribute == \"predicted\":\n            if getattr(self.dmisfit, \"objfcts\", None) is not None:\n                dpred = []\n                for local_misfit in self.dmisfit.objfcts:\n                    dpred.append(\n                        np.asarray(local_misfit.survey.dpred(self.invProb.model))\n                    )\n                prop = np.hstack(dpred)\n            else:\n                prop = self.dmisfit.survey.dpred(self.invProb.model)\n        else:\n            prop = self.invProb.model\n\n        if self.mapping is not None:\n            prop = self.mapping * prop\n\n        prop = self.check_mvi_format(prop)\n\n        for ii, channel in enumerate(self.channels):\n\n            attr = prop[ii :: len(self.channels)]\n\n            if self.sorting is not None:\n                attr = attr[self.sorting]\n\n            data = self.h5_object.add_data(\n                {\n                    f\"Iteration_0_\"\n                    + channel: {\"association\": self.association, \"values\": attr}\n                }\n            )\n\n            data.entity_type.name = channel\n            self.data_type[channel] = data.entity_type\n\n        if self.save_objective_function:\n            regCombo = [\"phi_ms\", \"phi_msx\"]\n\n            if self.prob[0].mesh.dim >= 2:\n                regCombo += [\"phi_msy\"]\n\n            if self.prob[0].mesh.dim == 3:\n                regCombo += [\"phi_msz\"]\n\n            # Save the data.\n            iterDict = {\"beta\": f\"{self.invProb.beta:.3e}\"}\n            iterDict[\"phi_d\"] = f\"{self.invProb.phi_d:.3e}\"\n            iterDict[\"phi_m\"] = f\"{self.invProb.phi_m:.3e}\"\n\n            for label, fcts in zip(regCombo, self.reg.objfcts[0].objfcts):\n                iterDict[label] = f\"{fcts(self.invProb.model):.3e}\"\n\n            self.h5_object.parent.add_comment(\n                json.dumps(iterDict), author=f\"Iteration_{0}\"\n            )\n\n        self.h5_object.workspace.finalize()\n\n    def endIter(self):\n        if self.attribute == \"predicted\":\n            if getattr(self.dmisfit, \"objfcts\", None) is not None:\n                dpred = []\n                for local_misfit in self.dmisfit.objfcts:\n                    dpred.append(\n                        np.asarray(local_misfit.survey.dpred(self.invProb.model))\n                    )\n                prop = np.hstack(dpred)\n            else:\n                prop = self.dmisfit.survey.dpred(self.invProb.model)\n        else:\n            prop = self.invProb.model\n\n        if self.mapping is not None:\n            prop = self.mapping * prop\n\n        prop = self.check_mvi_format(prop)\n\n        for ii, channel in enumerate(self.channels):\n            attr = prop[ii :: len(self.channels)]\n\n            if self.sorting is not None:\n                attr = attr[self.sorting]\n\n            if self.replace_values and self.h5_object.get_data(\n                f\"Iteration_{self.opt.iter-1}_\" + channel\n            ):\n                data = self.h5_object.get_data(\n                    f\"Iteration_{self.opt.iter-1}_\" + channel\n                )[0]\n                data.name = f\"Iteration_{self.opt.iter}_\" + channel\n                data.values = attr\n            else:\n                self.h5_object.add_data(\n                    {\n                        f\"Iteration_{self.opt.iter}_\"\n                        + channel: {\n                            \"values\": attr,\n                            \"association\": self.association,\n                            \"entity_type\": self.data_type[channel],\n                        }\n                    }\n                )\n\n        if self.save_objective_function:\n            regCombo = [\"phi_ms\", \"phi_msx\"]\n\n            if self.prob[0].mesh.dim >= 2:\n                regCombo += [\"phi_msy\"]\n\n            if self.prob[0].mesh.dim == 3:\n                regCombo += [\"phi_msz\"]\n\n            # Save objective function.\n            if isinstance(self.invProb.beta, float):\n                beta = self.invProb.beta\n            else:\n                beta = self.invProb.beta[0]\n\n            iterDict = {\"beta\": f\"{beta:.3e}\"}\n\n            if isinstance(self.invProb.phi_d, float):\n                phi_d = self.invProb.phi_d\n            else:\n                phi_d = self.invProb.phi_d[0]\n\n            if isinstance(self.invProb.phi_m, float):\n                phi_m = self.invProb.phi_m\n            else:\n                phi_m = self.invProb.phi_m[0]\n\n            iterDict[\"phi_d\"] = f\"{phi_d:.3e}\"\n            iterDict[\"phi_m\"] = f\"{phi_m:.3e}\"\n\n            for label, fcts in zip(regCombo, self.reg.objfcts[0].objfcts):\n                iterDict[label] = f\"{fcts(self.invProb.model):.3e}\"\n\n            self.h5_object.parent.add_comment(\n                json.dumps(iterDict), author=f\"Iteration_{self.opt.iter}\"\n            )\n\n        self.h5_object.workspace.finalize()\n\n    def check_mvi_format(self, values):\n        if \"mvi\" in self.attribute:\n            values = values.reshape((-1, 3), order=\"F\")\n            if self.no_data_value is not None:\n                ndv_ind = values[:, 0] == self.no_data_value\n                values[ndv_ind, :] = 0\n            else:\n                ndv_ind = np.zeros(values.shape[0], dtype=\"bool\")\n\n            if self.attribute == \"mvi_model\":\n                values = np.linalg.norm(values, axis=1)\n            elif self.attribute == \"mvi_model_s\":\n                values = values[:, 0]\n            elif self.attribute == \"mvi_angles\":\n                atp = Utils.matutils.xyz2atp(values)\n                values = atp.reshape((-1, 3), order=\"F\")\n\n            if \"model\" in self.attribute:\n                values[ndv_ind] = self.no_data_value\n            elif \"angles\" in self.attribute:\n                values = np.rad2deg(values[:, 1:])\n                values[ndv_ind, :] = self.no_data_value\n                values = values.ravel()\n\n        return values\n\n\nclass VectorInversion(InversionDirective):\n    \"\"\"\n    Control a vector inversion from Cartesian to spherical coordinates\n    \"\"\"\n\n    chifact_target = 1.0\n    mref = None\n    mode = \"cartesian\"\n    inversion_type = \"mvis\"\n    norms = []\n    alphas = []\n\n    @property\n    def target(self):\n        if getattr(self, \"_target\", None) is None:\n            nD = 0\n            for survey in self.survey:\n                nD += survey.nD\n\n            self._target = nD * 0.5 * self.chifact_target\n\n        return self._target\n\n    @target.setter\n    def target(self, val):\n        self._target = val\n\n    def initialize(self):\n\n        for reg in self.reg.objfcts:\n            reg.model = self.invProb.model\n\n        self.mref = reg.mref\n\n        for prob in self.prob:\n            if getattr(prob, \"coordinate_system\", None) is not None:\n                prob.coordinate_system = self.mode\n\n    def endIter(self):\n        if (\n            self.invProb.phi_d < self.target\n        ) and self.mode == \"cartesian\":  # and self.inversion_type == 'mvis':\n            print(\"Switching MVI to spherical coordinates\")\n            self.mode = \"spherical\"\n\n            mstart = Utils.matutils.xyz2atp(\n                self.invProb.model.reshape((-1, 3), order=\"F\")\n            )\n            mref = Utils.matutils.xyz2atp(self.mref.reshape((-1, 3), order=\"F\"))\n\n            self.invProb.model = mstart\n            self.invProb.beta *= 2\n            self.opt.xc = mstart\n\n            nC = mstart.reshape((-1, 3)).shape[0]\n            self.opt.lower = np.kron(np.asarray([0, -np.inf, -np.inf]), np.ones(nC))\n            self.opt.upper[nC:] = np.inf\n\n            self.reg.mref = mref\n            self.reg.model = mstart\n\n            for prob in self.prob:\n                if getattr(prob, \"coordinate_system\", None) is not None:\n                    prob.coordinate_system = self.mode\n                    prob.model = mstart\n\n            for ind, reg_fun in enumerate(self.reg.objfcts):\n\n                reg_fun.mref = mref\n                reg_fun.model = mstart\n\n                if ind > 0:\n                    reg_fun.alpha_s = 0\n                    reg_fun.eps_q = np.pi\n                    for reg in reg_fun.objfcts:\n                        reg.space = \"spherical\"\n\n            # Add directives\n            directiveList = []\n            update_Jacobi = []\n            IRLS = []\n            for directive in self.inversion.directiveList.dList:\n                if isinstance(directive, SaveIterationsGeoH5):\n                    channels = []\n                    for channel in directive.channels:\n                        channels.append(channel + \"_s\")\n                        directive.data_type[channel + \"_s\"] = directive.data_type[\n                            channel\n                        ]\n\n                    directive.channels = channels\n\n                    if directive.attribute == \"mvi_model\":\n                        directive.attribute = \"mvi_model_s\"\n                    elif directive.attribute == \"mvi_angles\":\n                        directive.attribute = \"mvi_angles_s\"\n\n                    directiveList.append(directive)\n\n                elif isinstance(directive, SaveUBCModelEveryIteration):\n                    directive.fileName = directive.fileName + \"_S\"\n                    directiveList.append(directive)\n\n                elif isinstance(directive, SaveUBCPredictedEveryIteration):\n                    directive.fileName = directive.fileName + \"_S\"\n                    directiveList.append(directive)\n\n                elif isinstance(directive, Update_IRLS):\n                    directive.sphericalDomain = True\n                    directive.model = mstart\n                    directive.coolingFactor = 1.5\n                    IRLS = directive\n\n                elif isinstance(directive, UpdatePreconditioner):\n                    update_Jacobi = directive\n                else:\n                    directiveList.append(directive)\n\n            directiveList = [\n                ProjSpherical(),\n                IRLS,\n                UpdateSensitivityWeights(),\n                update_Jacobi,\n            ] + directiveList\n\n            self.inversion.directiveList = directiveList\n            directiveList[1].endIter()\n            directiveList[2].endIter()\n            directiveList[3].endIter()\n        elif (self.invProb.phi_d < self.target) and self.mode == \"spherical\":\n\n            for directive in self.inversion.directiveList.dList:\n                if isinstance(directive, Update_IRLS) and directive.mode != 1:\n                    directive.coolingFactor = 2\n\n\nclass Update_IRLS(InversionDirective):\n\n    updateGamma = False\n    f_old = np.inf\n    f_min_change = 1e-2\n    beta_tol = 1e-1\n    beta_ratio_l2 = None\n    prctile = 90\n    chifact_target = 1.0\n\n    # Solving parameter for IRLS (mode:2)\n    IRLSiter = 0\n    minGNiter = 1\n    maxIRLSiter = 20\n    iterStart = 0\n    sphericalDomain = False\n\n    # Beta schedule\n    updateBeta = True\n    betaSearch = True\n    coolingFactor = 2.0\n    coolingRate = 1\n    ComboObjFun = False\n    mode = 1\n    coolEpsOptimized = True\n    coolEps_p = True\n    coolEps_q = True\n    floorEps_p = [1e-8, 1e-8, 1e-8]\n    floorEps_q = [1e-8, 1e-8, 1e-8]\n    floorEpsEnforced = True\n    coolEpsFact = 1.2\n    silent = False\n    fix_Jmatrix = False\n\n    @property\n    def target(self):\n        if getattr(self, \"_target\", None) is None:\n            nD = 0\n            for survey in self.survey:\n                nD += survey.nD\n\n            self._target = nD * 0.5 * self.chifact_target\n\n        return self._target\n\n    @target.setter\n    def target(self, val):\n        self._target = val\n\n    def initialize(self):\n\n        if self.mode == 1:\n\n            self.norms = []\n            for reg in self.reg.objfcts:\n                self.norms.append(reg.norms)\n                reg.norms = np.c_[2.0, 2.0, 2.0, 2.0]\n                reg.model = self.invProb.model\n\n        for reg in self.reg.objfcts:\n            reg.model = self.invProb.model\n            for comp in reg.objfcts:\n                self.f_old += comp(reg.model)\n\n        self.phi_dm = []\n        self.phi_dmx = []\n        # Look for cases where the block models in to be scaled\n        for prob in self.prob:\n\n            if getattr(prob, \"coordinate_system\", None) is not None:\n                if prob.coordinate_system == \"spherical\":\n                    self.sphericalDomain = True\n\n        if self.sphericalDomain:\n            self.angleScale()\n\n    def endIter(self):\n\n        if self.sphericalDomain:\n            self.angleScale()\n\n        # Check if misfit is within the tolerance, otherwise scale beta\n        if np.all(\n            [\n                np.abs(1.0 - float(self.invProb.phi_d) / self.target) > self.beta_tol,\n                self.updateBeta,\n                self.mode != 1,\n            ]\n        ):\n\n            ratio = self.target / self.invProb.phi_d\n\n            if ratio > 1:\n                ratio = np.min([2.0, ratio])\n\n            else:\n                ratio = np.max([0.75, ratio])\n\n            self.invProb.beta = self.invProb.beta * ratio\n\n            if np.all([self.mode != 1, self.betaSearch]):\n                # Re-use previous model and continue with new beta\n                self.invProb.model = self.reg.objfcts[0].model\n                self.opt.xc = self.reg.objfcts[0].model\n                self.opt.iter -= 1\n                return\n\n        elif np.all([self.mode == 1, (self.opt.iter % self.coolingRate) == 0]):\n\n            self.invProb.beta = self.invProb.beta / self.coolingFactor\n\n        phim_new = 0\n        for reg in self.reg.objfcts:\n            reg.model = self.invProb.model\n            for comp in reg.objfcts:\n                phim_new += comp(reg.model)\n\n        # Update the model used by the regularization\n        phi_m_last = []\n        for reg in self.reg.objfcts:\n            reg.model = self.invProb.model\n            phi_m_last += [reg(self.invProb.model)]\n\n        # After reaching target misfit with l2-norm, switch to IRLS (mode:2)\n        if np.all([float(self.invProb.phi_d) < self.target, self.mode == 1]):\n            self.startIRLS()\n            self.f_old = np.sum(phi_m_last)\n\n        # Only update after GN iterations\n        if np.all(\n            [\n                (float(self.opt.iter) - self.iterStart) % self.minGNiter == 0,\n                self.mode != 1,\n            ]\n        ):\n            if self.fix_Jmatrix:\n                self.invProb.dmisfit.prob.fix_Jmatrix = True\n\n            # Check for maximum number of IRLS cycles\n            if self.IRLSiter == self.maxIRLSiter:\n                if not self.silent:\n                    print(\n                        \"Reach maximum number of IRLS cycles:\"\n                        + f\" {int(self.maxIRLSiter)}\"\n                    )\n\n                self.opt.stopNextIteration = True\n                return\n\n            # Print to screen\n            for ii, reg in enumerate(self.reg.objfcts):\n\n                if reg.eps_p > self.floorEps_p[ii] and self.coolEps_p:\n                    reg.eps_p /= self.coolEpsFact\n\n                elif self.floorEpsEnforced:\n                    reg.eps_p = self.floorEps_p[ii]\n\n                if reg.eps_q > self.floorEps_q[ii] and self.coolEps_q:\n                    reg.eps_q /= self.coolEpsFact\n\n                elif self.floorEpsEnforced:\n                    reg.eps_q = self.floorEps_q[ii]\n\n            self.IRLSiter += 1\n\n            # Reset the regularization matrices so that it is\n            # recalculated for current model. Do it to all levels of comboObj\n            for reg in self.reg.objfcts:\n                # If comboObj, go down one more level\n                for comp in reg.objfcts:\n                    comp.stashedR = None\n\n            for dmis in self.dmisfit.objfcts:\n                if getattr(dmis, \"stashedR\", None) is not None:\n                    dmis.stashedR = None\n\n            # Compute new model objective function value\n            phi_m_new = []\n            for reg in self.reg.objfcts:\n                phi_m_new += [reg(self.invProb.model)]\n\n            self.f_change = np.abs(self.f_old - phim_new) / self.f_old\n\n            # Check if the function has changed enough\n            if np.all(\n                [\n                    self.f_change < self.f_min_change,\n                    self.IRLSiter > 1,\n                    np.abs(1.0 - float(self.invProb.phi_d) / self.target)\n                    < self.beta_tol,\n                ]\n            ):\n\n                print(\"Minimum decrease in regularization.\" + \"End of IRLS\")\n                self.opt.stopNextIteration = True\n                return\n\n            self.f_old = phim_new\n\n            self.updateBeta = True\n            self.invProb.phi_m_last = self.reg(self.invProb.model)\n\n    def startIRLS(self):\n        if not self.silent:\n            print(\n                \"Reached starting chifact with l2-norm regularization:\"\n                + \" Start IRLS steps...\"\n            )\n\n        self.mode = 2\n\n        if getattr(self.opt, \"iter\", None) is None:\n            self.iterStart = 0\n        else:\n            self.iterStart = self.opt.iter\n\n        self.invProb.phi_m_last = self.reg(self.invProb.model)\n\n        # Either use the supplied epsilon, or fix base on distribution of\n        # model values\n        for reg in self.reg.objfcts:\n\n            if getattr(reg, \"eps_p\", None) is None:\n\n                reg.eps_p = np.percentile(\n                    np.abs(reg.mapping * reg._delta_m(self.invProb.model)), self.prctile\n                )\n            if getattr(reg, \"eps_q\", None) is None:\n                reg.eps_q = reg.eps_p\n\n        # Re-assign the norms supplied by user l2 -> lp\n        for reg, norms in zip(self.reg.objfcts, self.norms):\n            reg.norms = norms\n\n        # Save l2-model\n        self.invProb.l2model = self.invProb.model.copy()\n\n    def angleScale(self):\n        \"\"\"\n            Update the scales used by regularization for the\n            different block of models\n        \"\"\"\n        # Currently implemented for MVI-S only\n        max_p = []\n        for reg in self.reg.objfcts[0].objfcts:\n            eps_p = reg.epsilon\n            norm_p = 2  # self.reg.objfcts[0].norms[0]\n            f_m = abs(reg.f_m)\n            max_p += [np.max(f_m)]\n\n        max_p = np.asarray(max_p).max() * 2.0\n\n        scales = [max_p / np.pi, max_p / np.pi]\n        for obj, scale in zip(self.reg.objfcts[1:3], scales):\n            obj.scales = np.ones(obj.scales.shape) * scale\n        # self.reg.objfcts[0].scales = np.ones(self.reg.objfcts[0].scales.shape)\n        # Probably doing rotated obj fun\n        if len(self.reg) > 3:\n\n            for obj, scale in zip(self.reg.objfcts[4:], scales):\n                obj.scales = np.ones(obj.scales.shape) * scale\n\n    def validate(self, directiveList):\n        # check if a linear preconditioner is in the list, if not warn else\n        # assert that it is listed after the IRLS directive\n        dList = directiveList.dList\n        self_ind = dList.index(self)\n        lin_precond_ind = [isinstance(d, UpdatePreconditioner) for d in dList]\n\n        if any(lin_precond_ind):\n            assert lin_precond_ind.index(True) > self_ind, (\n                \"The directive 'UpdatePreconditioner' must be after Update_IRLS \"\n                \"in the directiveList\"\n            )\n        else:\n            warnings.warn(\n                \"Without a Linear preconditioner, convergence may be slow. \"\n                \"Consider adding `Directives.UpdatePreconditioner` to your \"\n                \"directives list\"\n            )\n        return True\n\n\nclass UpdatePreconditioner(InversionDirective):\n    \"\"\"\n    Create a Jacobi preconditioner for the linear problem\n    \"\"\"\n\n    onlyOnStart = False\n    mapping = None\n    misfitDiag = None\n    epsilon = 1e-8\n\n    def initialize(self):\n\n        m = self.invProb.model\n        # Create the pre-conditioner\n        regDiag = np.zeros_like(self.invProb.model)\n\n        for reg in self.reg.objfcts:\n            # # Check if regularization has a projection\n            # if getattr(reg.mapping, 'P', None) is None:\n            #     regDiag += (reg.W.T*reg.W).diagonal()\n            # else:\n            #     P = reg.mapping.P\n            #     regDiag += (P.T * (reg.W.T * (reg.W * P))).diagonal()\n            regDiag += reg.deriv2(m).diagonal()\n\n        # Deal with the linear case\n        if getattr(self.opt, \"JtJdiag\", None) is None:\n            JtJdiag = np.zeros_like(self.invProb.model)\n            m = self.invProb.model\n            for prob, dmisfit in zip(self.prob, self.dmisfit.objfcts):\n\n                if getattr(prob, \"getJtJdiag\", None) is None:\n                    assert getattr(prob, \"getJ\", None) is not None, (\n                        \"Problem does not have a getJ attribute.\"\n                        + \"Cannot form the sensitivity explicitely\"\n                    )\n                    JtJdiag += np.sum(np.power((dmisfit.W * prob.getJ(m)), 2), axis=0)\n                else:\n                    JtJdiag += prob.getJtJdiag(m, W=dmisfit.W)\n            self.opt.JtJdiag = JtJdiag\n\n        diagA = self.opt.JtJdiag + self.invProb.beta * regDiag\n\n        diagA[diagA != 0] = diagA[diagA != 0] ** -1.0\n        PC = Utils.sdiag(diagA)\n\n        self.opt.approxHinv = PC\n\n    def endIter(self):\n\n        # Cool the threshold parameter\n        if self.onlyOnStart is True:\n            return\n\n        m = self.invProb.model\n        # Create the pre-conditioner\n        regDiag = np.zeros_like(self.invProb.model)\n\n        for reg in self.reg.objfcts:\n            regDiag += reg.deriv2(m).diagonal()\n\n        # Assumes that opt.JtJdiag has been updated or static\n        diagA = self.opt.JtJdiag + self.invProb.beta * regDiag\n\n        diagA[diagA != 0] = diagA[diagA != 0] ** -1.0\n        PC = Utils.sdiag(diagA)\n        self.opt.approxHinv = PC\n\n\nclass UpdateSensitivityWeights(InversionDirective):\n    \"\"\"\n    Directive to take care of re-weighting\n    the non-linear magnetic problems.\n    \"\"\"\n\n    mapping = None\n    JtJdiag = None\n    everyIter = True\n    threshold = 1e-12\n    switch = True\n\n    def initialize(self):\n\n        # Calculate and update sensitivity\n        # for optimization and regularization\n        self.update()\n\n    def endIter(self):\n\n        if self.everyIter:\n            # Update inverse problem\n            self.update()\n\n    def update(self):\n        # Get sum square of columns of J\n        self.getJtJdiag()\n\n        # Compute normalized weights\n        self.wr = self.getWr()\n\n        # Send a copy of JtJdiag for the preconditioner\n        self.updateOpt()\n\n        # Update the regularization\n        self.updateReg()\n\n    def getJtJdiag(self):\n        \"\"\"\n            Compute explicitely the main diagonal of JtJ\n            Good for any problem where J is formed explicitely\n        \"\"\"\n        self.JtJdiag = []\n\n        for prob, dmisfit in zip(self.prob, self.dmisfit.objfcts):\n            m = self.invProb.model\n\n            if getattr(prob, \"getJtJdiag\", None) is None:\n                assert getattr(prob, \"getJ\", None) is not None, (\n                    \"Problem does not have a getJ attribute.\"\n                    + \"Cannot form the sensitivity explicitely\"\n                )\n\n                self.JtJdiag += [\n                    Utils.mkvc(np.sum((dmisfit.W * prob.getJ(m)) ** (2.0), axis=0))\n                ]\n            else:\n                self.JtJdiag += [prob.getJtJdiag(m, W=dmisfit.W)]\n\n        return self.JtJdiag\n\n    def getWr(self):\n        \"\"\"\n            Take the diagonal of JtJ and return\n            a normalized sensitivty weighting vector\n        \"\"\"\n\n        wr = np.zeros_like(self.invProb.model)\n        if self.switch:\n            for prob_JtJ, prob, dmisfit in zip(\n                self.JtJdiag, self.prob, self.dmisfit.objfcts\n            ):\n\n                wr += prob_JtJ + self.threshold\n\n            wr = wr ** 0.5\n            wr /= wr.max()\n        else:\n            wr += 1.0\n\n        return wr\n\n    def updateReg(self):\n        \"\"\"\n            Update the cell weights with the approximated sensitivity\n        \"\"\"\n\n        for reg in self.reg.objfcts:\n            reg.cell_weights = reg.mapping * (self.wr)\n\n    def updateOpt(self):\n        \"\"\"\n            Update a copy of JtJdiag to optimization for preconditioner\n        \"\"\"\n        # if self.ComboMisfitFun:\n        JtJdiag = np.zeros_like(self.invProb.model)\n        for prob, JtJ, dmisfit in zip(self.prob, self.JtJdiag, self.dmisfit.objfcts):\n\n            JtJdiag += JtJ\n\n        self.opt.JtJdiag = JtJdiag\n\n\nclass ProjSpherical(InversionDirective):\n    \"\"\"\n        Trick for spherical coordinate system.\n        Project \\theta and \\\\phi angles back to [-\\\\pi,\\\\pi] using\n        back and forth conversion.\n        spherical->cartesian->spherical\n    \"\"\"\n\n    def initialize(self):\n\n        x = self.invProb.model\n        # Convert to cartesian than back to avoid over rotation\n        nC = int(len(x) / 3)\n\n        xyz = Utils.matutils.atp2xyz(x.reshape((nC, 3), order=\"F\"))\n        m = Utils.matutils.xyz2atp(xyz.reshape((nC, 3), order=\"F\"))\n\n        self.invProb.model = m\n\n        for prob in self.prob:\n            prob.model = m\n\n        self.opt.xc = m\n\n    def endIter(self):\n        x = self.invProb.model\n        nC = int(len(x) / 3)\n\n        # Convert to cartesian than back to avoid over rotation\n        xyz = Utils.matutils.atp2xyz(x.reshape((nC, 3), order=\"F\"))\n        m = Utils.matutils.xyz2atp(xyz.reshape((nC, 3), order=\"F\"))\n\n        self.invProb.model = m\n\n        phi_m_last = []\n        for reg in self.reg.objfcts:\n            reg.model = self.invProb.model\n            phi_m_last += [reg(self.invProb.model)]\n\n        self.invProb.phi_m_last = phi_m_last\n\n        for prob in self.prob:\n            prob.model = m\n\n        self.opt.xc = m\n\n\nclass JointAmpMVI(InversionDirective):\n    \"\"\"\n        Directive controlling the joint inversion of\n        magnetic amplitude data and MVI. Use the vector\n        magnetization model (M) to update the linear amplitude\n        operator.\n\n    \"\"\"\n\n    amp = None\n    minGNiter = 1\n    jointMVIS = False\n    updateM = False\n\n    def initialize(self):\n\n        # Get current MVI model and update MAI sensitivity\n        # if isinstance(self.prob, list):\n\n        m = self.invProb.model.copy()\n        for prob in self.prob:\n\n            if isinstance(prob, Magnetics.MagneticVector):\n                if prob.coordinate_system == \"spherical\":\n                    xyz = Magnetics.atp2xyz(\n                        (prob.chiMap * m).reshape((int(len(m) / 3), 3), order=\"F\")\n                    )\n                    self.jointMVIS = True\n                elif prob.coordinate_system == \"cartesian\":\n                    xyz = prob.chiMap * m\n\n            if isinstance(prob, Magnetics.MagneticAmplitude):\n                self.amp = prob.chiMap * m\n\n        for prob in self.prob:\n            if isinstance(prob, Magnetics.MagneticAmplitude):\n                if self.jointMVIS:\n                    prob.jointMVIS = True\n\n                nC = prob.mesh.nC\n\n                mcol = xyz.reshape((nC, 3), order=\"F\")\n                amp = np.sum(mcol ** 2.0, axis=1) ** 0.5\n                M = Utils.sdiag(1.0 / amp) * mcol\n\n        else:\n            assert \"This directive needs to used on a ComboObjective\"\n\n    def endIter(self):\n\n        # Get current MVI model and update magnetization model for MAI\n        m = self.invProb.model.copy()\n        for prob in self.prob:\n\n            if isinstance(prob, Magnetics.MagneticVector):\n                if prob.coordinate_system == \"spherical\":\n                    xyz = Magnetics.atp2xyz(\n                        (prob.chiMap * m).reshape((int(len(m) / 3), 3), order=\"F\")\n                    )\n\n                elif prob.coordinate_system == \"cartesian\":\n                    xyz = prob.chiMap * m\n\n            if isinstance(prob, Magnetics.MagneticAmplitude):\n                if prob.chiMap.shape[0] == 3 * prob.mesh.nC:\n\n                    nC = prob.mesh.nC\n\n                    mcol = (prob.chiMap * m).reshape((nC, 3), order=\"F\")\n                    self.amp = np.sum(mcol ** 2.0, axis=1) ** 0.5\n                else:\n\n                    self.amp = prob.chiMap * m\n\n        for prob in self.prob:\n            if np.all([isinstance(prob, Magnetics.MagneticAmplitude), self.updateM]):\n\n                nC = prob.mesh.nC\n\n                mcol = xyz.reshape((nC, 3), order=\"F\")\n                amp = np.sum(mcol ** 2.0, axis=1) ** 0.5\n\n                M = Utils.sdiag(1.0 / amp) * mcol\n\n                prob.M = M\n                prob._Mxyz = None\n                prob.Mxyz\n                # if prob.model is None:\n                #     prob.model = prob.chiMap * m\n\n                # ampW = (amp/amp.max() + 1e-2)**-1.\n                # prob.W = ampW\n\n            if isinstance(prob, Magnetics.MagneticVector):\n\n                if (prob.coordinate_system == \"cartesian\") and (self.amp is not None):\n\n                    ampW = (self.amp / self.amp.max() + 1e-2) ** -1.0\n                    ampW = np.r_[ampW, ampW, ampW]\n\n                    # Scale max values\n                    prob.W = ampW\n\n\nclass UpdateApproxJtJ(InversionDirective):\n    \"\"\"\n        Create approx-sensitivity base weighting using the probing method\n    \"\"\"\n\n    k = None  # Number of probing cycles\n    itr = None  # Iteration number to update Wj, or always update if None\n\n    def endIter(self):\n\n        if self.itr is None or self.itr == self.opt.iter:\n\n            m = self.invProb.model\n            if self.k is None:\n\n                nD = 0\n                for survey in self.survey:\n                    nD += survey.nD\n\n                self.k = int(nD / 10)\n\n            def JtJv(v):\n\n                Jv = self.prob.Jvec(m, v)\n\n                return self.prob.Jtvec(m, Jv)\n\n            JtJdiag = Utils.diagEst(JtJv, len(m), k=self.k)\n            JtJdiag = JtJdiag / max(JtJdiag)\n\n            self.reg.wght = JtJdiag\n\n\nclass ScaleComboReg(InversionDirective):\n    \"\"\"\n    Directive to take care of re-weighting\n    the non-linear magnetic problems.\n\n    \"\"\"\n\n    # coordinate_system = 'Amp'\n    # test = False\n    mapping = None\n    ComboRegFun = False\n    ComboMisfitFun = False\n    JtJdiag = None\n    everyIter = True\n\n    def initialize(self):\n\n        # for reg in self.reg.objfcts:\n        m = self.invProb.model\n\n        scale = (\n            np.abs(self.reg.objfcts[0](m)).max() / np.abs(self.reg.objfcts[1](m)).max()\n        )\n        self.reg.objfcts[1].scale = scale\n\n    def endIter(self):\n\n        m = self.invProb.model\n\n        scale = (\n            np.abs(self.reg.objfcts[0].deriv(m)).max()\n            / np.abs(self.reg.objfcts[1].deriv(m)).max()\n        )\n        self.reg.objfcts[1].scale = scale\n", "meta": {"hexsha": "a26eda6046e4b7b87690b554eb94a50e1c96c843", "size": 56547, "ext": "py", "lang": "Python", "max_stars_repo_path": "geoapps/simpegPF/Directives.py", "max_stars_repo_name": "sebhmg/geoapps", "max_stars_repo_head_hexsha": "1463ba4ec3c914abdc7403e54eca0ee2bbc3f4f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-18T16:24:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T16:24:53.000Z", "max_issues_repo_path": "geoapps/simpegPF/Directives.py", "max_issues_repo_name": "sebhmg/geoapps", "max_issues_repo_head_hexsha": "1463ba4ec3c914abdc7403e54eca0ee2bbc3f4f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geoapps/simpegPF/Directives.py", "max_forks_repo_name": "sebhmg/geoapps", "max_forks_repo_head_hexsha": "1463ba4ec3c914abdc7403e54eca0ee2bbc3f4f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7858347386, "max_line_length": 145, "alphanum_fraction": 0.5283923108, "include": true, "reason": "import numpy", "num_tokens": 13709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.35220178884745895, "lm_q1q2_score": 0.18022750355975506}}
{"text": "#!/usr/bin/env python\n\nimport os\nimport time\nimport warnings\n\nimport numpy\n\nfrom cogent3.maths.optimisers import ParameterOutOfBoundsError, maximise\nfrom cogent3.maths.solve import find_root\n\n\nFloat = numpy.core.numerictypes.sctype2char(float)\n\n\nTRACE_DEFAULT = \"COGENT3_TRACE\" in os.environ\nTRACE_SCALE = 100000\n\n__author__ = \"Peter Maxwell\"\n__copyright__ = \"Copyright 2007-2020, The Cogent Project\"\n__credits__ = [\"Peter Maxwell\", \"Gavin Huttley\", \"Daniel McDonald\"]\n__license__ = \"BSD-3\"\n__version__ = \"2020.2.7a\"\n__maintainer__ = \"Peter Maxwell\"\n__email__ = \"pm67nz@gmail.com\"\n__status__ = \"Production\"\n\n# This is the 'live' layer of the recalculation system\n# Cells and OptPars are held by a Calculator\n# For docstring see definitions.py\n\n\nclass CalculationInterupted(Exception):\n    pass\n\n\nclass OptPar(object):\n    \"\"\"One parameter, as seen by the optimiser, eg: length of one edge.\n    An OptPar reports changes to the ParameterValueSet for its parameter.\n    \"\"\"\n\n    is_constant = False\n    recycled = False\n    args = ()\n    # Use of __slots__ here and in Cell gives 8% speedup on small calculators.\n    __slots__ = [\n        \"clients\",\n        \"client_ranks\",\n        \"name\",\n        \"lower\",\n        \"default_value\",\n        \"upper\",\n        \"scope\",\n        \"order\",\n        \"label\",\n        \"consequences\",\n        \"rank\",\n    ]\n\n    def __init__(self, name, scope, bounds):\n        self.clients = []\n        self.client_ranks = []\n        self.name = name\n        for (attr, v) in zip([\"lower\", \"default_value\", \"upper\"], bounds):\n            setattr(self, attr, float(v))\n\n        # controls order in optimiser - group for LF\n        self.scope = scope\n        self.order = (len(scope), scope and min(scope), name)\n        self.label = self.name\n\n    def add_client(self, client):\n        self.clients.append(client)\n\n    def __lt__(self, other):\n        # optimisation is more efficient if params for one edge are neighbours\n        return self.order < other.order\n\n    def __eq__(self, other):\n        # optimisation is more efficient if params for one edge are neighbours\n        return self.order == other.order\n\n    def __ne__(self, other):\n        # optimisation is more efficient if params for one edge are neighbours\n        return self.order != other.order\n\n    def __repr__(self):\n        return \"%s(%s)\" % (self.__class__.__name__, self.label)\n\n    def get_optimiser_bounds(self):\n        lower = self.transform_to_optimiser(self.lower)\n        upper = self.transform_to_optimiser(self.upper)\n        return (lower, upper)\n\n    def transform_from_optimiser(self, value):\n        return value\n\n    def transform_to_optimiser(self, value):\n        return value\n\n\nclass LogOptPar(OptPar):\n    # For ratios, optimiser sees log(param value).  Conversions to/from\n    # optimiser representation are only done by Calculator.change(),\n    # .get_value_array() and .getBoundsArrrays().\n\n    def transform_from_optimiser(self, value):\n        return numpy.exp(value)\n\n    def transform_to_optimiser(self, value):\n        try:\n            return numpy.log(value)\n        except OverflowError:\n            raise OverflowError(\"log(%s)\" % value)\n\n\nclass EvaluatedCell(object):\n    __slots__ = [\n        \"client_ranks\",\n        \"rank\",\n        \"calc\",\n        \"args\",\n        \"is_constant\",\n        \"clients\",\n        \"failure_count\",\n        \"name\",\n        \"arg_ranks\",\n        \"consequences\",\n        \"recycled\",\n        \"default\",\n    ]\n\n    def __init__(self, name, calc, args, recycling=None, default=None):\n        self.name = name\n        self.rank = None\n        self.calc = calc\n        self.default = default\n        self.args = tuple(args)\n\n        self.recycled = recycling\n        if recycling:\n            self.args = (self,) + self.args\n\n        self.is_constant = True\n        for arg in args:\n            arg.add_client(self)\n            if not arg.is_constant:\n                self.is_constant = False\n\n        self.clients = []\n        self.client_ranks = []\n        self.failure_count = 0\n\n    def add_client(self, client):\n        self.clients.append(client)\n\n    def update(self, data):\n        data[self.rank] = self.calc(*[data[arg_rank] for arg_rank in self.arg_ranks])\n\n    def prime(self, data_sets):\n        if self.is_constant:\n            # Just calc once\n            self.update(data_sets[0])\n            for data in data_sets[1:]:\n                data[self.rank] = data_sets[0][self.rank]\n        else:\n            for data in data_sets:\n                self.update(data)\n\n    def report_error(self, detail, data):\n        self.failure_count += 1\n        if self.failure_count <= 5:\n            print((\"%s in calculating %s:\", detail.__class__.__name__, self.name))\n        if self.failure_count == 5:\n            print(\"Additional failures of this type will not be reported.\")\n        if self.failure_count < 2:\n            print(\"%s inputs were:\", len(self.arg_ranks))\n            for (i, arg) in enumerate(self.arg_ranks):\n                print(\"%s: \" % i + repr(data[arg]))\n\n\nclass ConstCell(object):\n    __slots__ = [\"name\", \"scope\", \"value\", \"rank\", \"consequences\", \"clients\"]\n\n    recycled = False\n    is_constant = True\n    args = ()\n\n    def __init__(self, name, value):\n        self.name = name\n        self.clients = []\n        self.value = value\n\n    def add_client(self, client):\n        self.clients.append(client)\n\n\nclass Calculator(object):\n    \"\"\"A complete hierarchical function with N evaluation steps to call\n    for each change of inputs.  Made by a ParameterController.\"\"\"\n\n    def __init__(self, cells, defns, trace=None, with_undo=True):\n        if trace is None:\n            trace = TRACE_DEFAULT\n        self.with_undo = with_undo\n        self.results_by_id = defns\n        self.opt_pars = []\n        other_cells = []\n        for cell in cells:\n            if isinstance(cell, OptPar):\n                self.opt_pars.append(cell)\n            else:\n                other_cells.append(cell)\n        self._cells = self.opt_pars + other_cells\n        data_sets = [[0], [0, 1]][self.with_undo]\n        self.cell_values = [[None] * len(self._cells) for switch in data_sets]\n        self.arg_ranks = [[] for cell in self._cells]\n        for (i, cell) in enumerate(self._cells):\n            cell.rank = i\n            cell.consequences = {}\n            if isinstance(cell, OptPar):\n                for switch in data_sets:\n                    self.cell_values[switch][i] = cell.default_value\n            elif isinstance(cell, ConstCell):\n                for switch in data_sets:\n                    self.cell_values[switch][i] = cell.value\n            elif isinstance(cell, EvaluatedCell):\n                cell.arg_ranks = []\n                for arg in cell.args:\n                    if hasattr(arg, \"client_ranks\"):\n                        arg.client_ranks.append(i)\n                    self.arg_ranks[i].append(arg.rank)\n                    cell.arg_ranks.append(arg.rank)\n\n                try:\n                    cell.prime(self.cell_values)\n                except KeyboardInterrupt:\n                    raise\n                except Exception as detail:\n                    print((\"Failed initial calculation of %s\" % cell.name))\n                    raise\n            else:\n                raise RuntimeError(\"Unexpected Cell type %s\" % type(cell))\n\n        self._switch = 0\n        self.recycled_cells = [cell.rank for cell in self._cells if cell.recycled]\n        self.spare = [None] * len(self._cells)\n\n        for cell in self._cells[::-1]:\n            for arg in cell.args:\n                arg.consequences[cell.rank] = True\n                arg.consequences.update(cell.consequences)\n\n        self._programs = {}\n        # Just for timings pre-calc these\n        for opt_par in self.opt_pars:\n            self.cells_changed_by([(opt_par.rank, None)])\n\n        self.last_values = self.get_value_array()\n        self.last_undo = []\n        self.elapsed_time = 0.0\n        self.evaluations = 0\n        self.set_tracing(trace)\n        self.optimised = False\n\n    def graphviz(self):\n        \"\"\"Returns a string in the 'dot' graph description language used by the\n        program 'Graphviz'.  One box per cell, grouped by Defn.\"\"\"\n\n        lines = [\"digraph G {\\n rankdir = LR\\n ranksep = 1\\n\"]\n        evs = []\n        for cell in self._cells:\n            if cell.name not in evs:\n                evs.append(cell.name)\n        nodes = dict([(name, []) for name in evs])\n        edges = []\n        for cell in self._cells:\n            if hasattr(cell, \"name\"):\n                nodes[cell.name].append(cell)\n                for arg in cell.args:\n                    if arg is not cell:\n                        edges.append(\n                            '\"%s\":%s -> \"%s\":%s'\n                            % (arg.name, arg.rank, cell.name, cell.rank)\n                        )\n        for name in evs:\n            all_const = True\n            some_const = False\n            enodes = [name.replace(\"edge\", \"QQQ\")]\n            for cell in nodes[name]:\n                value = self._get_current_cell_value(cell)\n                if isinstance(value, float):\n                    label = \"%5.2e\" % value\n                else:\n                    label = \"[]\"\n                label = \"<%s> %s\" % (cell.rank, label)\n                enodes.append(label)\n                all_const = all_const and cell.is_constant\n                some_const = some_const or cell.is_constant\n            enodes = \"|\".join(enodes)\n            colour = [\"\", \" fillcolor=gray90, style=filled,\"][some_const]\n            colour = [colour, \" fillcolor=gray, style=filled,\"][all_const]\n            lines.append(\n                '\"%s\" [shape = \"record\",%s label=\"%s\"];' % (name, colour, enodes)\n            )\n        lines.extend(edges)\n        lines.append(\"}\")\n        return \"\\n\".join(lines).replace(\"edge\", \"egde\").replace(\"QQQ\", \"edge\")\n\n    def optimise(self, **kw):\n        x = self.get_value_array()\n        bounds = self.get_bounds_vectors()\n        maximise(self, x, bounds, **kw)\n        self.optimised = True\n\n    def set_tracing(self, trace=False):\n        \"\"\"With 'trace' true every evaluated is printed.  Useful for profiling\n        and debugging.\"\"\"\n\n        self.trace = trace\n        if trace:\n            print()\n            n_opars = len(self.opt_pars)\n            n_cells = len([c for c in self._cells if not c.is_constant])\n            print(n_opars, \"OptPars and\", n_cells - n_opars, \"derived values\")\n            print(\"OptPars: \", \", \".join([par.name for par in self.opt_pars]))\n            print(\"Times in 1/%sths of a second\" % TRACE_SCALE)\n\n            groups = []\n            groupd = {}\n            for cell in self._cells:\n                if cell.is_constant or not isinstance(cell, EvaluatedCell):\n                    continue\n                if cell.name not in groupd:\n                    group = []\n                    groups.append((cell.name, group))\n                    groupd[cell.name] = group\n                groupd[cell.name].append(cell)\n\n            widths = []\n            for (name, cells) in groups:\n                width = 4 + len(cells)\n                widths.append(min(15, width))\n            self._cellsGroupedForDisplay = list(zip(groups, widths))\n            for ((name, cells), width) in self._cellsGroupedForDisplay:\n                print(name[:width].ljust(width), \"|\", end=\" \")\n            print()\n            for width in widths:\n                print(\"-\" * width, \"|\", end=\" \")\n            print()\n\n    def get_value_array(self):\n        \"\"\"This being a caching function, you can ask it for its current\n        input!  Handy for initialising the optimiser.\"\"\"\n        values = [\n            p.transform_to_optimiser(self._get_current_cell_value(p))\n            for p in self.opt_pars\n        ]\n        return values\n\n    # get_bounds_vectors and testoptparvector make up the old LikelihoodFunction\n    # interface expected by the optimiser.\n\n    def get_bounds_vectors(self):\n        \"\"\"2 arrays: minimums, maximums\"\"\"\n        lower = numpy.zeros([len(self.opt_pars)], Float)\n        upper = numpy.zeros([len(self.opt_pars)], Float)\n        for (i, opt_par) in enumerate(self.opt_pars):\n            (lb, ub) = opt_par.get_optimiser_bounds()\n            lower[i] = lb\n            upper[i] = ub\n        return (lower, upper)\n\n    def fuzz(self, random_series=None, seed=None):\n        # Slight randomisation suitable for removing right-on-the-\n        # ridge starting points before local optimisation.\n        if random_series is None:\n            import random\n\n            random_series = random.Random()\n        if seed is not None:\n            random_series.seed(seed)\n        X = self.get_value_array()\n        for (i, (l, u)) in enumerate(zip(*self.get_bounds_vectors())):\n            sign = random_series.choice([-1, +1])\n            step = random_series.uniform(+0.05, +0.025)\n            X[i] = max(l, min(u, (1.0 + sign * step * X[i])))\n        self.testoptparvector(X)\n        self.optimised = False\n\n    def testoptparvector(self, values):\n        \"\"\"AKA self().  Called by optimisers.  Returns the output value\n        after doing any recalculation required for the new input 'values'\n        array\"\"\"\n\n        assert len(values) == len(self.opt_pars)\n        changes = [\n            (i, new)\n            for (i, (old, new)) in enumerate(zip(self.last_values, values))\n            if old != new\n        ]\n        return self.change(changes)\n\n    __call__ = testoptparvector\n\n    def testfunction(self):\n        \"\"\"Return the current output value without changing any inputs\"\"\"\n        return self._get_current_cell_value(self._cells[-1])\n\n    def change(self, changes):\n        \"\"\"Returns the output value after applying 'changes', a list of\n        (optimisable_parameter_ordinal, new_value) tuples.\"\"\"\n\n        t0 = time.time()\n        self.evaluations += 1\n\n        # If ALL of the changes made in the last step are reversed in this step\n        # then it is safe to undo them first, taking advantage of the 1-deep\n        # cache.\n        if self.with_undo and self.last_undo:\n            for (i, v) in self.last_undo:\n                if (i, v) not in changes:\n                    break\n            else:\n                changes = [ch for ch in changes if ch not in self.last_undo]\n                self._switch = not self._switch\n                for (i, v) in self.last_undo:\n                    self.last_values[i] = v\n\n        self.last_undo = []\n        program = self.cells_changed_by(changes)\n\n        if self.with_undo:\n            self._switch = not self._switch\n            data = self.cell_values[self._switch]\n            base = self.cell_values[not self._switch]\n\n            # recycle and undo interact in bad ways\n            for rank in self.recycled_cells:\n                if data[rank] is not base[rank]:\n                    self.spare[rank] = data[rank]\n            data[:] = base[:]\n            for cell in program:\n                if cell.recycled:\n                    if data[cell.rank] is base[cell.rank]:\n                        data[cell.rank] = self.spare[cell.rank]\n                        assert data[cell.rank] is not base[cell.rank]\n        else:\n            data = self.cell_values[self._switch]\n\n        # Set new OptPar values\n        changed_optpars = []\n        for (i, v) in changes:\n            if i < len(self.opt_pars):\n                assert isinstance(v * 1.0, float), v\n                changed_optpars.append((i, self.last_values[i]))\n                self.last_values[i] = v\n                data[i] = self.opt_pars[i].transform_from_optimiser(v)\n            else:\n                data[i] = v\n\n        try:\n            if self.trace:\n                self.tracing_update(changes, program, data)\n            else:\n                self.plain_update(program, data)\n\n            # if non-optimiser parameter was set then undo is invalid\n            if self.last_undo and max(self.last_undo)[0] >= len(self.opt_pars):\n                self.last_undo = []\n            else:\n                self.last_undo = changed_optpars\n\n        except CalculationInterupted as detail:\n            if self.with_undo:\n                self._switch = not self._switch\n            for (i, v) in changed_optpars:\n                self.last_values[i] = v\n            self.last_undo = []\n            (cell, exception) = detail.args\n            raise exception\n\n        finally:\n            self.elapsed_time += time.time() - t0\n\n        return self.cell_values[self._switch][-1]\n\n    def cells_changed_by(self, changes):\n        # What OptPars have been changed determines cells to update\n        change_key = list(dict(changes).keys())\n        change_key.sort()\n        change_key = tuple(change_key)\n        if change_key in self._programs:\n            program = self._programs[change_key]\n        else:\n            # Make a list of the cells to update and cache it.\n            consequences = {}\n            for i in change_key:\n                consequences.update(self._cells[i].consequences)\n            self._programs[change_key] = program = [\n                cell for cell in self._cells if cell.rank in consequences\n            ]\n        return program\n\n    def plain_update(self, program, data):\n        try:\n            for cell in program:\n                data[cell.rank] = cell.calc(*[data[a] for a in cell.arg_ranks])\n        except ParameterOutOfBoundsError as detail:\n            # Non-fatal error, just cancel this calculation.\n            raise CalculationInterupted(cell, detail)\n        except ArithmeticError as detail:\n            # Non-fatal but unexpected error. Warn and cancel this calculation.\n            cell.report_error(detail, data)\n            raise CalculationInterupted(cell, detail)\n\n    def tracing_update(self, changes, program, data):\n        # Does the same thing as plain_update, but also produces lots of\n        # output showing how long each step of the calculation takes.\n        # One line per call, '-' for undo, '+' for calculation\n\n        exception = None\n        elapsed = {}\n        for cell in program:\n            try:\n                t0 = time.time()\n                data[cell.rank] = cell.calc(*[data[a] for a in cell.arg_ranks])\n                t1 = time.time()\n            except (ParameterOutOfBoundsError, ArithmeticError) as exception:\n                error_cell = cell\n                break\n            elapsed[cell.rank] = t1 - t0\n\n        tds = []\n        for ((name, cells), width) in self._cellsGroupedForDisplay:\n            text = \"\".join([\" +\"[cell.rank in elapsed] for cell in cells])\n            elap = sum([elapsed.get(cell.rank, 0) for cell in cells])\n            if len(text) > width - 4:\n                edge_width = min(len(text), (width - 4 - 3)) // 2\n                elipsis = [\"   \", \"...\"][not not text.strip()]\n                text = text[:edge_width] + elipsis + text[-edge_width:]\n            tds.append(\"%s%4s\" % (text, int(TRACE_SCALE * elap + 0.5) or \"\"))\n\n        par_descs = []\n        for (i, v) in changes:\n            cell = self._cells[i]\n            if isinstance(cell, OptPar):\n                par_descs.append(\"%s=%8.6f\" % (cell.name, v))\n            else:\n                par_descs.append(\"%s=?\" % cell.name)\n        par_descs = \", \".join(par_descs)[:22].ljust(22)\n        print(\" | \".join(tds + [\"\"]), end=\" \")\n        if exception:\n            print(\"%15s | %s\" % (\"\", par_descs))\n            error_cell.report_error(exception, data)\n            raise CalculationInterupted(cell, exception)\n        else:\n            print(\"%-15s | %s\" % (repr(data[-1])[:15], par_descs))\n\n    def measure_evals_per_second(self, time_limit=1.0, wall=True, sa=False):\n        # Returns an estimate of the number of evaluations per second\n        # an each-optpar-in-turn simulated annealing type optimiser\n        # can achive, spending not much more than 'time_limit' doing\n        # so.  'wall'=False causes process time to be used instead of\n        # wall time.\n        # 'sa' makes it simulated-annealing-like, with frequent backtracks\n        if wall:\n            now = time.time\n        else:\n            now = time.clock\n        x = self.get_value_array()\n        samples = []\n        elapsed = 0.0\n        rounds_per_sample = 2\n        while elapsed < time_limit and len(samples) < 5:\n            time.sleep(0.01)\n            t0 = now()\n            last = []\n            for j in range(rounds_per_sample):\n                for (i, v) in enumerate(x):\n                    # Not a real change, but works like one.\n                    self.change(last + [(i, v)])\n                    if sa and (i + j) % 2:\n                        last = [(i, v)]\n                    else:\n                        last = []\n            # Use one agreed on delta otherwise different cpus will finish the\n            # loop at different times causing chaos.\n            delta = now() - t0\n            if delta < 0.1:\n                # time.clock is low res, so need to ensure each sample\n                # is long enough to take SOME time.\n                rounds_per_sample *= 2\n                continue\n            else:\n                rate = rounds_per_sample * len(x) / delta\n                samples.append(rate)\n                elapsed += delta\n\n        if wall:\n            samples.sort()\n            return samples[len(samples) // 2]\n        else:\n            return sum(samples) / len(samples)\n\n    def _get_current_cell_value(self, cell):\n        return self.cell_values[self._switch][cell.rank]\n\n    def get_current_cell_values_for_defn(self, defn):\n        cells = self.results_by_id[id(defn)]\n        return [self.cell_values[self._switch][cell.rank] for cell in cells]\n\n    def __get_bounded_root(self, func, origX, direction, bound, xtol):\n        return find_root(\n            func,\n            origX,\n            direction,\n            bound,\n            xtol=xtol,\n            expected_exception=(ParameterOutOfBoundsError, ArithmeticError),\n        )\n\n    def _get_current_cell_interval(self, opt_par, dropoff, xtol=None):\n        # (min, opt, max) tuples for each parameter where f(min) ==\n        # f(max) == f(opt)-dropoff.  Uses None when a bound is hit.\n        # assert self.optimised, \"Call optimise() first\"\n        origY = self.testfunction()\n        (lower, upper) = opt_par.get_optimiser_bounds()\n        opt_value = self._get_current_cell_value(opt_par)\n        origX = opt_par.transform_to_optimiser(opt_value)\n\n        def func(x):\n            Y = self.change([(opt_par.rank, x)])\n            return Y - (origY - dropoff)\n\n        try:\n            lowX = self.__get_bounded_root(func, origX, -1, lower, xtol)\n            highX = self.__get_bounded_root(func, origX, +1, upper, xtol)\n        finally:\n            func(origX)\n\n        triple = []\n        for x in [lowX, origX, highX]:\n            if x is not None:\n                x = opt_par.transform_from_optimiser(x)\n            triple.append(x)\n        return tuple(triple)\n", "meta": {"hexsha": "0fdc9975cf281039f7825d321bf20fb1acad6f27", "size": 22936, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/cogent3/recalculation/calculation.py", "max_stars_repo_name": "GavinHuttley/c3test", "max_stars_repo_head_hexsha": "c5bf7f8252b4f7b75a851e28275536a8c378897a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cogent3/recalculation/calculation.py", "max_issues_repo_name": "GavinHuttley/c3test", "max_issues_repo_head_hexsha": "c5bf7f8252b4f7b75a851e28275536a8c378897a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cogent3/recalculation/calculation.py", "max_forks_repo_name": "GavinHuttley/c3test", "max_forks_repo_head_hexsha": "c5bf7f8252b4f7b75a851e28275536a8c378897a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-04T02:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-04T02:44:00.000Z", "avg_line_length": 35.3950617284, "max_line_length": 85, "alphanum_fraction": 0.5553278689, "include": true, "reason": "import numpy", "num_tokens": 5188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117165898111866, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.1802275017938738}}
{"text": "import os\nimport copy\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.autograd import grad\nfrom procedures import get_ntk_n\n\n\nreward_type2index = {\n    'ntk': 0,\n    'exp': 1,\n    'constraint': 3\n}\nindex2reward_type = {\n    0: 'ntk',\n    1: 'exp',\n    3: 'constraint'\n}\n\n\ndef kaiming_normal_fanin_init(m):\n    if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):\n        nn.init.kaiming_normal_(m.weight, mode='fan_in', nonlinearity='relu')\n        if hasattr(m, 'bias') and m.bias is not None:\n            nn.init.zeros_(m.bias)\n    elif isinstance(m, nn.BatchNorm2d):\n        nn.init.ones_(m.weight.data)\n        nn.init.constant_(m.bias.data, 0.0)\n\n\ndef kaiming_normal_fanout_init(m):\n    if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):\n        nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n        if hasattr(m, 'bias') and m.bias is not None:\n            nn.init.zeros_(m.bias)\n    elif isinstance(m, nn.BatchNorm2d) or isinstance(m, nn.LayerNorm):\n        nn.init.ones_(m.weight.data)\n        nn.init.constant_(m.bias.data, 0.0)\n\n\ndef init_model(model, method='kaiming_norm_fanin'):\n    if method == 'kaiming_norm_fanin':\n        model.apply(kaiming_normal_fanin_init)\n    elif method == 'kaiming_norm_fanout':\n        model.apply(kaiming_normal_fanout_init)\n    return model\n\n\nclass TEG(object):\n    def __init__(self, loader, loader_val, class_num=1000, repeat=3, size_curve=(500, 3, 16, 16), batch_curve=6, reward_types=[\"ntk\", \"exp\"], buffer_size=10, constraint_weight=0.):\n        # self.__super__()\n        self.repeat = repeat\n        self.constraint_weight = constraint_weight # e.g. FLOPs constraint\n        self.batch_size_curve = batch_curve\n\n        self.reward_type2index = reward_type2index\n        self.index2reward_type = index2reward_type\n        self._reward_types = reward_types\n        self._reward_sign = {\"ntk\": -1, \"exp\": 1, \"constraint\": -1} # ntk: lower the better; exp: higher the better\n        self._buffers = {key: [] for key in self._reward_types}\n        self._buffers['constraint'] = []\n        self._buffers_bad = [] # indicator of bad architectures\n        self._buffers_change = {key: [] for key in self._reward_types}\n        self._buffers_change['constraint'] = []\n        self._buffer_length = buffer_size\n        self._class_num = class_num\n        # build fixed data samples\n        self._ntk_input_data = []\n        for i, (inputs, targets) in enumerate(loader):\n            if i >= self.repeat: break\n            self._ntk_input_data.append((inputs, targets))\n            self.batch_size = len(inputs)\n        self._ntk_target_data = [] # for NTK kernel regression\n        for i, (inputs, targets) in enumerate(loader_val):\n            if i >= self.repeat: break\n            self._ntk_target_data.append((inputs, targets))\n        # Curve complexity\n        n_interp, C, H, W = size_curve\n        self.theta = []; self.curve_input = []\n        for _ in range(self.repeat):\n            self.theta.append(torch.linspace(0, 2 * np.pi, n_interp))\n            self.theta[-1].requires_grad_(True)\n            self.curve_input.append(torch.matmul(torch.svd(torch.randn(H*W*C, 2))[0], torch.stack([torch.cos(self.theta[-1]), torch.sin(self.theta[-1])])).T.reshape((n_interp, C, H, W)).cuda(non_blocking=True))\n            self.curve_input[-1].requires_grad_(True)\n\n    def reset(self, constraint_weight=0):\n        self.constraint_weight = constraint_weight\n        # self._reward_types = reward_types\n        self._buffers = {key: [] for key in self._reward_types}; self._buffers['constraint'] = []\n        self._buffers_bad = [] # indicator of bad architectures\n        self._buffers_change = {key: [] for key in self._reward_types}; self._buffers_change['constraint'] = []\n\n    def set_network(self, network):\n        if hasattr(self, \"_networks\"):\n            del self._networks\n        self._networks = []\n        for _ in range(self.repeat):\n            net = copy.deepcopy(network)\n            net.apply(net._init_weights)\n            self._networks.append(net.cuda())\n\n    def get_ntk(self):\n        for net in self._networks:\n            net.switch_norm('ln')\n        ntks = get_ntk_n(self._ntk_input_data, self._networks, criterion=torch.nn.CrossEntropyLoss(), train_mode=True, num_batch=1, num_classes=self._class_num)\n        for network in self._networks:\n            network.zero_grad()\n        torch.cuda.empty_cache()\n        return np.mean(ntks)\n\n    def get_curve_complexity(self):\n        for net in self._networks:\n            net.switch_norm('id')\n        LE = [0 for _ in range(len(self._networks))]\n        for net_idx, network in enumerate(self._networks):\n            network = network.cuda()\n            network.train()\n            network.zero_grad()\n            _idx = 0\n            while _idx < len(self.curve_input[net_idx]):\n                output = network.forward_features(self.curve_input[net_idx][_idx:_idx+self.batch_size_curve])[1]\n                _idx += self.batch_size_curve\n                output = output.reshape(output.size(0), -1)\n                n, c = output.size()\n                jacobs = []\n                for coord in range(c):\n                    output[:, coord].backward(torch.ones_like(output[:, coord]), retain_graph=True)\n                    # actually only \"batch_size\" number of thetas have grad, but it is ok, since zeros won't contribute to gE.sum()\n                    jacobs.append(self.theta[net_idx].grad.detach().clone())\n                    self.theta[net_idx].grad.zero_()\n                jacobs = torch.stack(jacobs, 0)\n                jacobs = jacobs.permute(1, 0) # num_theta x c\n                gE = torch.einsum('nd,nd->n', jacobs, jacobs).sqrt()\n                LE[net_idx] += gE.sum().item()\n                torch.cuda.empty_cache()\n            network = network.cpu()\n            torch.cuda.empty_cache()\n        for net in self._networks:\n            net.switch_norm('ln')\n        return np.mean(LE)\n\n    def get_curve_complexity_gauss(self):\n        for net in self._networks:\n            net.switch_norm('id')\n        LG = [0 for _ in range(len(self._networks))]\n        for net_idx, network in enumerate(self._networks):\n            network = network.cuda()\n            network.train()\n            network.zero_grad()\n            _idx = 0\n            v_s = [] # 1st derivative\n            while _idx < len(self.curve_input[net_idx]):\n                output = network.forward_features(self.curve_input[net_idx][_idx:_idx+self.batch_size_curve])[1]\n                output = output.reshape(output.size(0), -1)\n                n, c = output.size()\n                _v_s = [] # 1st derivative\n                for coord in range(c):\n                    v = grad(output[:, coord].sum(), self.theta[net_idx], create_graph=True, retain_graph=True)[0][_idx:_idx+self.batch_size_curve] # batch size (of thetas)\n                    _v_s.append(v.detach().clone())\n                v_s.append(torch.stack(_v_s, 0).permute(1, 0)) # bach_size x c\n                _idx += self.batch_size_curve\n            v_s = torch.cat(v_s, 0) # num_thetas x c\n            v_s_norm = v_s.norm(2, dim=1, keepdim=True) # norm over c of all thetas\n            _idx = 0\n            while _idx < len(self.curve_input[net_idx]):\n                output = network.forward_features(self.curve_input[net_idx][_idx:_idx+self.batch_size_curve])[1]\n                output = output.reshape(output.size(0), -1)\n                n, c = output.size()\n                d_v_hat_s = [] # 2nd derivative\n                for coord in range(c):\n                    v = grad(output[:, coord].sum(), self.theta[net_idx], create_graph=True, retain_graph=True)[0][_idx:_idx+self.batch_size_curve] # batch size (of thetas)\n                    d_v_hat = grad((v / v_s_norm[_idx:_idx+self.batch_size_curve]).sum(), self.theta[net_idx], create_graph=True, retain_graph=True)[0][_idx:_idx+self.batch_size_curve] # batch size (of thetas)\n                    d_v_hat_s.append(d_v_hat.detach().clone())\n                    del v\n                d_v_hat_s = torch.stack(d_v_hat_s, 0).permute(1, 0) # batch_size_curve x c\n                gG = torch.einsum('nd,nd->n', d_v_hat_s, d_v_hat_s).sqrt()\n                LG[net_idx] += gG.sum().item()\n                torch.cuda.empty_cache()\n                _idx += self.batch_size_curve\n            network = network.cpu()\n            torch.cuda.empty_cache()\n        return np.mean(LG)\n\n    def get_extrinsic_curvature(self):\n        for net in self._networks:\n            net.switch_norm('id')\n        kappa = [0 for _ in range(len(self._networks))]\n        for net_idx, network in enumerate(self._networks):\n            network = network.cuda()\n            network.train()\n            network.zero_grad()\n            _idx = 0\n            while _idx < len(self.curve_input[net_idx]):\n                output = network.forward_features(self.curve_input[net_idx][_idx:_idx+self.batch_size_curve])[1]\n                output = output.reshape(output.size(0), -1)\n                n, c = output.size()\n                v_s = [] # 1st derivative\n                a_s = [] # 2nd derivative\n                for coord in range(c):\n                    v = grad(output[:, coord].sum(), self.theta[net_idx], create_graph=True, retain_graph=True)[0][_idx:_idx+self.batch_size_curve] # batch size (of thetas)\n                    a = grad(v.sum(), self.theta[net_idx], create_graph=True, retain_graph=True)[0][_idx:_idx+self.batch_size_curve] # batch size (of thetas)\n                    v_s.append(v.detach().clone())\n                    a_s.append(a.detach().clone())\n                v_s = torch.stack(v_s, 0).permute(1, 0) # batch_size_curve x c\n                a_s = torch.stack(a_s, 0).permute(1, 0) # batch_size_curve x c\n                vv = torch.einsum('nd,nd->n', v_s, v_s)\n                aa = torch.einsum('nd,nd->n', a_s, a_s)\n                va = torch.einsum('nd,nd->n', v_s, a_s)\n                kappa[net_idx] += (vv**(-3/2) * (vv * aa - va ** 2).sqrt()).sum().item()\n                torch.cuda.empty_cache()\n                _idx += self.batch_size_curve\n            network = network.cpu()\n            torch.cuda.empty_cache()\n        return np.mean(kappa)\n\n    def _update_bad_cases(self, reward_type, reward):\n        # re-set \"reward_type\" of bad architectures to \"reward\"\n        for _type in self._reward_types:\n            for _idx, isbad in enumerate(self._buffers_bad):\n                if isbad:\n                    self._buffers[_type][_idx] = reward\n            for _idx, isbad in enumerate(self._buffers_bad):\n                if isbad:\n                    self._buffers_change[_type][_idx] = (self._buffers[_type][_idx] - self._buffers[_type][_idx-1]) / (max(self._buffers[_type][max(0, _idx+1-self._buffer_length):_idx+1]) - min(self._buffers[_type][max(0, _idx+1-self._buffer_length):_idx+1]) + 1e-6)\n                    if _idx + 1 < len(self._buffers_bad):\n                        self._buffers_change[_type][_idx+1] = (self._buffers[_type][_idx+1] - self._buffers[_type][_idx]) / (max(self._buffers[_type][max(0, _idx+2-self._buffer_length):_idx+2]) - min(self._buffers[_type][max(0, _idx+2-self._buffer_length):_idx+2]) + 1e-6)\n\n    def get_reward(self):\n        #  changing range comparison ######\n        _reward = _type = 0\n        if len(self._buffers[self._reward_types[0]]) <= 1:\n            # dummy reward for step 0\n            return 0\n        type_reward = [] # tuples of (type, reward)\n        for _type in self._reward_types:\n            var = self._buffers_change[_type][-1]\n            type_reward.append((self.reward_type2index[_type], self._reward_sign[_type] * var))\n        if 'constraint' in self._buffers and len(self._buffers['constraint']) > 0:\n            var = self._buffers_change['constraint'][-1]\n            type_reward.append((self.reward_type2index['constraint'], self._reward_sign['constraint'] * var * self.constraint_weight))\n        if len(type_reward) > 0:\n            _reward = sum([_r for _t, _r in type_reward])\n        return _reward\n\n    def _buffer_insert(self, results):\n        if len(self._buffers[self._reward_types[0]]) == 0:\n            self._buffers_bad.append(results['bad'])\n            for _type in self._reward_types:\n                self._buffers_change[_type].append(0)\n                self._buffers[_type].append(results[_type])\n            if 'constraint' in results:\n                self._buffers_change['constraint'].append(0)\n                self._buffers['constraint'].append(results['constraint'])\n        else:\n            if results['bad']:\n                # set ntk of bad architecture as worst case in current buffer\n                if 'ntk' in self._reward_types: results['ntk'] = max(self._buffers['ntk'])\n            else:\n                if 'ntk' in self._reward_types and results['ntk'] > max(self._buffers['ntk']):\n                    self._update_bad_cases('ntk', results['ntk'])\n            self._buffers_bad.append(results['bad'])\n            for _type in self._reward_types:\n                self._buffers[_type].append(results[_type])\n                var = (self._buffers[_type][-1] - self._buffers[_type][-2]) / (max(self._buffers[_type][-self._buffer_length:]) - min(self._buffers[_type][-self._buffer_length:]) + 1e-6)\n                self._buffers_change[_type].append(var)\n            if 'constraint' in results:\n                self._buffers['constraint'].append(results['constraint'])\n                var = (self._buffers['constraint'][-1] - self._buffers['constraint'][-2]) / (max(self._buffers['constraint'][-self._buffer_length:]) - min(self._buffers['constraint'][-self._buffer_length:]) + 1e-6)\n                self._buffers_change['constraint'].append(var)\n\n    def get_ntk_exp(self):\n        results = {}\n        if 'ntk' in self._reward_types:\n            ntk = self.get_ntk()\n            results['ntk'] = ntk\n            results['bad'] = ntk==-1 # networks of bad gradients\n        if 'exp' in self._reward_types:\n            exp = self.get_curve_complexity()\n            results['exp'] = exp\n            results['bad'] = False # networks of bad gradients\n        torch.cuda.empty_cache()\n        return results\n\n    def step(self, network, constraint=None, verbose=False):\n        self.set_network(network)\n        results = self.get_ntk_exp()\n        if constraint is not None:\n            results['constraint'] = constraint\n        self._buffer_insert(results)\n        if verbose:\n            print(\"NTK buffer:\", self._buffers['ntk'][-self._buffer_length:])\n            print(\"NTK change buffer:\", self._buffers_change['ntk'][-self._buffer_length:])\n            print(\"Exp buffer:\", self._buffers['exp'][-self._buffer_length:])\n            print(\"Exp change buffer:\", self._buffers_change['exp'][-self._buffer_length:])\n            if constraint is not None:\n                print(\"Constraint buffer:\", self._buffers['constraint'][-self._buffer_length:])\n                print(\"Constraint change buffer:\", self._buffers_change['constraint'][-self._buffer_length:])\n        reward = self.get_reward()\n        # reward larger the better\n        return reward\n\n    def _buffer_rank_best(self):\n        # return the index of the best based on rankings over three buffers\n        rankings = {}\n        buffers_sorted = {}\n        rankings_all = []\n        for _type in self._reward_types:\n            buffers_sorted[_type] = sorted(self._buffers[_type], reverse=self._reward_sign[_type]==1) # by default ascending\n            num_samples = len(buffers_sorted[_type])\n            rankings[_type] = [ buffers_sorted[_type].index(value) for value in self._buffers[_type] ]\n        for _idx in range(num_samples):\n            rankings_all.append(sum([ rankings[_type][_idx] for _type in rankings.keys() ]))\n        return np.argmin(rankings_all)\n", "meta": {"hexsha": "2a8ecbf18bf754de075ca076b4e2efbda8b2a16b", "size": 15796, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/procedures/teg.py", "max_stars_repo_name": "VITA-Group/AsViT", "max_stars_repo_head_hexsha": "e326ccaf63e05f241f8f48a0e045b63d221be62a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 43, "max_stars_repo_stars_event_min_datetime": "2022-02-24T12:57:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T07:23:41.000Z", "max_issues_repo_path": "lib/procedures/teg.py", "max_issues_repo_name": "VITA-Group/AsViT", "max_issues_repo_head_hexsha": "e326ccaf63e05f241f8f48a0e045b63d221be62a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/procedures/teg.py", "max_forks_repo_name": "VITA-Group/AsViT", "max_forks_repo_head_hexsha": "e326ccaf63e05f241f8f48a0e045b63d221be62a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-28T02:35:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T02:35:29.000Z", "avg_line_length": 50.146031746, "max_line_length": 272, "alphanum_fraction": 0.5960369714, "include": true, "reason": "import numpy", "num_tokens": 3845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3522017820478896, "lm_q1q2_score": 0.18022750008030253}}
{"text": "from __future__ import absolute_import\n# #START_LICENSE###########################################################\n#\n#\n# This file is part of the Environment for Tree Exploration program\n# (ETE).  http://etetoolkit.org\n#\n# ETE is free software: you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# ETE is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public\n# License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with ETE.  If not, see <http://www.gnu.org/licenses/>.\n#\n#\n#                     ABOUT THE ETE PACKAGE\n#                     =====================\n#\n# ETE is distributed under the GPL copyleft license (2008-2015).\n#\n# If you make use of ETE in published work, please cite:\n#\n# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon.\n# ETE: a python Environment for Tree Exploration. Jaime BMC\n# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24\n#\n# Note that extra references to the specific methods implemented in\n# the toolkit may be available in the documentation.\n#\n# More info at http://etetoolkit.org. Contact: huerta@embl.de\n#\n#\n# #END_LICENSE#############################################################\n\n\nfrom math import log, exp\n\nfrom six.moves import range\nfrom numpy import floor, pi as PI, sin\n\nfrom .. import Tree\n\n\ndef get_rooting(tol, seed_species, agename = False):\n    '''\n    returns dict of species age for a given TOL and a given seed\n\n    **Example:**\n\n    ::\n\n      tol  = \"((((((((Drosophila melanogaster,(Drosophila simulans,Drosophila secchellia)),(Drosophila yakuba,Drosophila erecta))[&&NHX:name=melanogaster subgroup],Drosophila ananassae)[&&NHX:name=melanogaster group],(Drosophila pseudoobscura,Drosophila persimilis)[&&NHX:name=obscura group])[&&NHX:name=Sophophora Old World],Drosophila willistoni)[&&NHX:name=subgenus Sophophora],(Drosophila grimshawi,(Drosophila virilis,Drosophila mojavensis))[&&NHX:name=subgenus Drosophila])[&&NHX:name=genus Drosophila],(Anopheles gambiae,Aedes aegypti)[&&NHX:name=Culicidae])[&&NHX:name=Arthropoda],Caenorhabditis elegans)[&&NHX:name=Animalia];\"\n      seed = \"Drosophila melanogaster\"\n      ROOTING, age2name = get_rooting (tol, seed, True)\n\n      ROOTING == {\"Aedes aegypti\"           : 7,\n                  \"Anopheles gambiae\"       : 7,\n                  \"Caenorhabditis elegans\"  : 8,\n                  \"Drosophila ananassae\"    : 3,\n                  \"Drosophila erecta\"       : 2,\n                  \"Drosophila grimshawi\"    : 6,\n                  \"Drosophila melanogaster\" : 1,\n                  \"Drosophila mojavensis\"   : 6,\n                  \"Drosophila persimilis\"   : 4,\n                  \"Drosophila pseudoobscura\": 4,\n                  \"Drosophila secchellia\"   : 1,\n                  \"Drosophila simulans\"     : 1,\n                  \"Drosophila virilis\"      : 6,\n                  \"Drosophila willistoni\"   : 5,\n                  \"Drosophila yakuba\"       : 2}\n\n      age2name == {1: \"Drosophila melanogaster. Drosophila simulans. Drosophila secchellia\",\n                   2: \"melanogaster subgroup\",\n                   3: \"melanogaster group\",\n                   4: \"Sophophora Old World\",\n                   5: \"subgenus Sophophora\",\n                   6: \"genus Drosophila\",\n                   7: \"Arthropoda\",\n                   8: \"Animalia\"}\n\n    :argument seed_species: species name\n    :argument False agename: if True, also returns the inverse dictionary\n\n    :returns: ROOTING dictionary with age of each species\n\n    '''\n\n    tol = Tree (tol)\n    try:\n        node = tol.search_nodes (name=seed_species)[0]\n    except IndexError:\n        exit ('ERROR: Seed species not found in tree\\n')\n    age = 1\n    ROOTING = {}\n    if agename:\n        age2name = {}\n    while not node.is_root():\n        node = node.up\n        for leaf in node.get_leaf_names():\n            if agename:\n                if node.name == 'NoName':\n                    nam = '.'.join (node.get_leaf_names())\n                else:\n                    nam = node.name\n                age2name.setdefault (age, nam)\n            ROOTING.setdefault (leaf, age)\n        age += 1\n    if agename:\n        return ROOTING, age2name\n    return ROOTING\n\n\ndef translate(sequence):\n    '''\n    little function to translate DNA to protein...\n    from: http://python.genedrift.org/\n    TODO : inseqgroup functions?\n\n    :argument sequence: string\n\n    :returns: translated sequence\n    '''\n    #dictionary with the genetic code\n    gencode = {\n        'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',\n        'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',\n        'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',\n        'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',\n        'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',\n        'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',\n        'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',\n        'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',\n        'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',\n        'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',\n        'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',\n        'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',\n        'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',\n        'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',\n        'TAC':'Y', 'TAT':'Y', 'TAA':'.', 'TAG':'.',\n        'TGC':'C', 'TGT':'C', 'TGA':'.', 'TGG':'W',\n        '---':'-', 'nnn':'x', 'NNN':'X'\n    }\n    ambig = {'Y':['A', 'G'], 'R':['C', 'T'], 'M':['G', 'T'], 'K':['A', 'C'], \\\n             'S':['G', 'C'],'W':['A', 'T'], 'V':['C', 'G', 'T'], \\\n             'H':['A', 'G', 'T'], 'D':['A', 'C', 'T'], 'B':['A', 'C', 'G'], \\\n             'N':['A', 'C', 'G', 'T']}\n    proteinseq = ''\n    #loop to read DNA sequence in codons, 3 nucleotides at a time\n    sequence = sequence.upper()\n    for n in range(0, len(sequence), 3):\n        #checking to see if the dictionary has the key\n        try:\n            proteinseq += gencode[sequence[n:n+3]]\n        except KeyError:\n            newcod = []\n            for nt in sequence[n:n+3]:\n                if nt in ambig:\n                    newcod.append(ambig[nt])\n                else :\n                    newcod.append(list (nt))\n            aa = ''\n            for nt1 in newcod[0]:\n                for nt2 in newcod[1]:\n                    for nt3 in newcod[2]:\n                        try:\n                            if aa == '':\n                                aa  = gencode[nt1+nt2+nt3]\n                            elif gencode[nt1+nt2+nt3] != aa:\n                                aa = 'X'\n                                break\n                        except KeyError:\n                            aa = 'X'\n                            break\n            proteinseq += aa\n    return proteinseq\n\n\n# reused from pycogent\nROUND_ERROR = 1e-14\nMAXLOG      = 7.09782712893383996843E2\nMAXLGM      = 2.556348e305\nbig         = 4.503599627370496e15\nbiginv      = 2.22044604925031308085e-16\nMACHEP      = 1.11022302462515654042E-16\nLS2PI       =  0.91893853320467274178\nLOGPI       = 1.14472988584940017414\n\n\ndef chi_high(x, df):\n    \"\"\"Returns right-hand tail of chi-square distribution (x to infinity).\n\n    df, the degrees of freedom, ranges from 1 to infinity (assume integers).\n    Typically, df is (r-1)*(c-1) for a r by c table.\n\n    Result ranges from 0 to 1.\n\n    See Cephes docs for details.\n    \"\"\"\n    x = fix_rounding_error(x)\n\n    if x < 0:\n        raise ValueError(\"chi_high: x must be >= 0 (got %s).\" % x)\n    if df < 1:\n        raise ValueError(\"chi_high: df must be >= 1 (got %s).\" % df)\n    return igamc(float(df)/2, x/2)\n\n\ndef fix_rounding_error(x):\n    \"\"\"If x is almost in the range 0-1, fixes it.\n\n    Specifically, if x is between -ROUND_ERROR and 0, returns 0.\n    If x is between 1 and 1+ROUND_ERROR, returns 1.\n    \"\"\"\n    if -ROUND_ERROR < x < 0:\n        return 0\n    elif 1 < x < 1+ROUND_ERROR:\n        return 1\n    return x\n\n\ndef igamc(a,x):\n    \"\"\"Complemented incomplete Gamma integral: see Cephes docs.\"\"\"\n    if x <= 0 or a <= 0:\n        return 1\n    if x < 1 or x < a:\n        return 1 - igam(a, x)\n    ax = a * log(x) - x - lgam(a)\n    if ax < -MAXLOG:    #underflow\n        return 0\n    ax = exp(ax)\n    #continued fraction\n    y = 1 - a\n    z = x + y + 1\n    c = 0\n    pkm2 = 1\n    qkm2 = x\n    pkm1 = x + 1\n    qkm1 = z * x\n    ans = pkm1/qkm1\n\n    while 1:\n        c += 1\n        y += 1\n        z += 2\n        yc = y * c\n        pk = pkm1 * z - pkm2 * yc\n        qk = qkm1 * z - qkm2 * yc\n        if qk != 0:\n            r = pk/qk\n            t = abs((ans-r)/r)\n            ans = r\n        else:\n            t = 1\n        pkm2 = pkm1\n        pkm1 = pk\n        qkm2 = qkm1\n        qkm1 = qk\n        if abs(pk) > big:\n            pkm2 *= biginv\n            pkm1 *= biginv\n            qkm2 *= biginv\n            qkm1 *= biginv\n        if t <= MACHEP:\n            break\n    return ans * ax\n\n\ndef lgam(x):\n    \"\"\"Natural log of the gamma fuction: see Cephes docs for details\"\"\"\n    if x < -34:\n        q = -x\n        w = lgam(q)\n        p = floor(q)\n        if p == q:\n            raise OverflowError(\"lgam returned infinity.\")\n        z = q - p\n        if z > 0.5:\n            p += 1\n            z = p - q\n        z = q * sin(PI * z)\n        if z == 0:\n            raise OverflowError(\"lgam returned infinity.\")\n        z = LOGPI - log(z) - w\n        return z\n    if x < 13:\n        z = 1\n        p = 0\n        u = x\n        while u >= 3:\n            p -= 1\n            u = x + p\n            z *= u\n        while u < 2:\n            if u == 0:\n                raise OverflowError(\"lgam returned infinity.\")\n            z /= u\n            p += 1\n            u = x + p\n        if z < 0:\n            z = -z\n        if u == 2:\n            return log(z)\n        p -= 2\n        x = x + p\n        p = x * polevl(x, GB)/polevl(x,GC)\n        return log(z) + p\n    if x > MAXLGM:\n        raise OverflowError(\"Too large a value of x in lgam.\")\n    q = (x - 0.5) * log(x) - x + LS2PI\n    if x > 1.0e8:\n        return q\n    p = 1/(x*x)\n    if x >= 1000:\n        q += ((  7.9365079365079365079365e-4 * p\n                 -2.7777777777777777777778e-3) *p\n              + 0.0833333333333333333333) / x\n    else:\n        q += polevl(p, GA)/x\n    return q\n\n\ndef polevl(x, coef):\n    \"\"\"evaluates a polynomial y = C_0 + C_1x + C_2x^2 + ... + C_Nx^N\n\n    Coefficients are stored in reverse order, i.e. coef[0] = C_N\n    \"\"\"\n    result = 0\n    for c in coef:\n        result = result * x + c\n    return result\n\n\ndef igam(a, x):\n    \"\"\"Left tail of incomplete gamma function: see Cephes docs for details\"\"\"\n    if x <= 0 or a <= 0:\n        return 0\n    if x > 1 and x > a:\n        return 1 - igamc(a,x)\n\n    #Compute x**a * exp(x) / Gamma(a)\n\n    ax = a * log(x) - x - lgam(a)\n    if ax < -MAXLOG:    #underflow\n        return 0.0\n    ax = exp(ax)\n\n    #power series\n    r = a\n    c = 1\n    ans = 1\n    while 1:\n        r += 1\n        c *= x/r\n        ans += c\n        if c/ans <= MACHEP:\n            break\n\n    return ans * ax / a\n\n#Coefficients for Gamma follow:\nGA = [\n    8.11614167470508450300E-4,\n    -5.95061904284301438324E-4,\n    7.93650340457716943945E-4,\n    -2.77777777730099687205E-3,\n    8.33333333333331927722E-2,\n]\n\nGB = [\n    -1.37825152569120859100E3,\n    -3.88016315134637840924E4,\n    -3.31612992738871184744E5,\n    -1.16237097492762307383E6,\n    -1.72173700820839662146E6,\n    -8.53555664245765465627E5,\n]\n\nGC = [\n    1.00000000000000000000E0,\n    -3.51815701436523470549E2,\n    -1.70642106651881159223E4,\n    -2.20528590553854454839E5,\n    -1.13933444367982507207E6,\n    -2.53252307177582951285E6,\n    -2.01889141433532773231E6,\n]\n\nGP = [\n    1.60119522476751861407E-4,\n    1.19135147006586384913E-3,\n    1.04213797561761569935E-2,\n    4.76367800457137231464E-2,\n    2.07448227648435975150E-1,\n    4.94214826801497100753E-1,\n    9.99999999999999996796E-1,\n]\n\nGQ = [\n    -2.31581873324120129819E-5,\n    5.39605580493303397842E-4,\n    -4.45641913851797240494E-3,\n    1.18139785222060435552E-2,\n    3.58236398605498653373E-2,\n    -2.34591795718243348568E-1,\n    7.14304917030273074085E-2,\n    1.00000000000000000320E0,\n]\n", "meta": {"hexsha": "92e490acc46ecc9e830bf4c8c4dd7dc9814e8a35", "size": 12335, "ext": "py", "lang": "Python", "max_stars_repo_path": "venv/lib/python3.8/site-packages/ete3/evol/utils.py", "max_stars_repo_name": "bjru/dendogram-traversal", "max_stars_repo_head_hexsha": "410bea2dd852caef5fd9d4dde9306203a2d29220", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "venv/lib/python3.8/site-packages/ete3/evol/utils.py", "max_issues_repo_name": "bjru/dendogram-traversal", "max_issues_repo_head_hexsha": "410bea2dd852caef5fd9d4dde9306203a2d29220", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "venv/lib/python3.8/site-packages/ete3/evol/utils.py", "max_forks_repo_name": "bjru/dendogram-traversal", "max_forks_repo_head_hexsha": "410bea2dd852caef5fd9d4dde9306203a2d29220", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7946859903, "max_line_length": 635, "alphanum_fraction": 0.5170652615, "include": true, "reason": "from numpy", "num_tokens": 4000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.35220176844875106, "lm_q1q2_score": 0.18022749312139752}}
{"text": "# -*- coding: utf-8 -*-\n# @Brief: 模型loss函数\n\n\nfrom tensorflow.keras import backend, losses\nimport tensorflow as tf\nimport numpy as np\n\n\ndef rpn_cls_loss(ratio=3):\n    def cls_loss(y_true, y_pred):\n        \"\"\"\n        计算rpn 是否有物体的loss，可以直接用交叉熵计算损失，但这里计算\n        :param y_true: 真实值 [batch_size, num_anchor, 1]\n        :param y_pred: 预测值 [batch_size, num_anchor, 1]\n        :return: rpn cls_loss\n        \"\"\"\n\n        label_true = y_true[:, :, -1]       # 取出真实值的label rpn的label 1是物体，0是背景，-1是需要忽略的\n        label_pred = y_pred\n\n        # 找出存在目标的先验框 有目标是1\n        indices_for_object = tf.where(backend.equal(label_true, 1))     # 如果x,y都为None，就返回condition的坐标\n        labels_for_object = tf.gather_nd(y_true, indices_for_object)    # 根据indices选取真实值标签\n        classification_for_object = tf.gather_nd(label_pred, indices_for_object)    # 选取预测值标签\n\n        cls_loss_for_object = backend.binary_crossentropy(labels_for_object, classification_for_object)\n\n        # 找出实际上为背景的先验框 没有目标是0\n        indices_for_back = tf.where(backend.equal(label_true, 0))\n        labels_for_back = tf.gather_nd(y_true, indices_for_back)\n        classification_for_back = tf.gather_nd(label_pred, indices_for_back)\n\n        # 计算每一个先验框应该有的权重\n        cls_loss_for_back = backend.binary_crossentropy(labels_for_back, classification_for_back)\n\n        # 标准化，计算是正样本的数量\n        normalizer_pos = tf.where(backend.equal(label_true, 1))\n        normalizer_pos = backend.cast(backend.shape(normalizer_pos)[0], 'float32')\n        normalizer_pos = backend.maximum(backend.cast_to_floatx(1.0), normalizer_pos)\n\n        # 计算负样本的数量\n        normalizer_neg = tf.where(backend.equal(label_true, 0))\n        normalizer_neg = backend.cast(backend.shape(normalizer_neg)[0], 'float32')\n        normalizer_neg = backend.maximum(backend.cast_to_floatx(1.0), normalizer_neg)\n\n        # 将所获得的loss除上样本的数量\n        cls_loss_for_object = backend.sum(cls_loss_for_object) / normalizer_pos         # 物体的loss\n        cls_loss_for_back = ratio * backend.sum(cls_loss_for_back) / normalizer_neg     # 背景的loss\n\n        # 总的loss\n        loss = cls_loss_for_object + cls_loss_for_back\n\n        return loss\n\n    return cls_loss\n\n\ndef rpn_regr_loss(sigma=1.0):\n    sigma_squared = sigma ** 2\n\n    def smooth_l1(y_true, y_pred):\n        \"\"\"\n        计算rpn 建议框坐标的loss\n        使用smooth l1 loss\n        f(x) =  0.5 * (sigma * x)^2          if |x| < 1 / sigma / sigma\n                |x| - 0.5 / sigma^2          otherwise\n        :param sigma: 是平滑参数，控制平滑区域\n        :param y_true: 真实值 [batch_size, num_anchor, 4+1]\n        :param y_pred: 预测值 [batch_size, num_anchor, 4]\n        :return: rpn regr_loss\n        \"\"\"\n        regression_pred = y_pred\n        regression_true = y_true[:, :, :-1]   # 取rpn上的坐标\n        label_true = y_true[:, :, -1]         # 取框内是否有物体的预测值\n\n        # 找到只有物体的框，不要背景\n        indices = tf.where(backend.equal(label_true, 1))                    # 如果x,y都为None，就返回condition的坐标\n        regression_pred = tf.gather_nd(regression_pred, indices)            # 根据有物体的索引，取出预测框的相关坐标\n        regression_true = tf.gather_nd(regression_true, indices)            # 取出真实框的坐标\n\n        # 计算 smooth L1 loss\n        regression_diff = backend.abs(regression_pred - regression_true)\n        regression_loss = tf.where(  # tf.where用做判断条件\n            backend.less(regression_diff, 1.0 / sigma_squared),             # 绝对值是否小于1\n            0.5 * sigma_squared * backend.pow(regression_diff, 2),          # 如果是\n            regression_diff - 0.5 / sigma_squared                           # 如果不是\n        )\n\n        # 除于N_cls\n        normalizer = backend.maximum(1, backend.shape(indices)[0])\n        normalizer = backend.cast(normalizer, dtype='float32')\n        loss = backend.sum(regression_loss) / normalizer\n\n        return loss\n\n    return smooth_l1\n\n\ndef class_loss_regr(num_classes):\n    epsilon = 1e-4\n\n    def class_loss_regr_fixed_num(y_true, y_pred):\n        \"\"\"\n        计算classifier的回归损失\n        :param y_true: 真实值 [batch_size, num_rois, num_classes * 8]\n        :param y_pred: 预测值 [batch_size, num_rois, num_classes * 4]\n        :return: classifier regr_loss\n        \"\"\"\n        regr_loss = 0\n        batch_size = len(y_true)\n        for i in range(batch_size):\n            x = y_true[i, :, 4 * num_classes:] - y_pred[i, :, :]                    # 取出y_true后一半的数据，与y_pred做差值\n            x_abs = backend.abs(x)                                                  # 计算绝对值\n            x_bool = backend.cast(backend.less_equal(x_abs, 1.0), 'float32')        # 小于1的值\n\n            # 1、差值绝对值小于1时0.5 * X^2，大于1的绝对值减0.5然后相加\n            # 2、在乘上是否要计算这个loss\n            # 3、求和在除以个数，得均值\n            loss = 4 * backend.sum(\n                y_true[i, :, :4 * num_classes] * (x_bool * (0.5 * x * x) + (1 - x_bool) * (x_abs - 0.5))) / backend.sum(\n                epsilon + y_true[i, :, :4 * num_classes])\n            regr_loss += loss\n\n        return regr_loss / backend.constant(batch_size)\n\n    return class_loss_regr_fixed_num\n\n\ndef class_loss_cls(y_true, y_pred):\n    \"\"\"\n    计算具体的分类loss\n    :param y_true: 真实值 [batch_size, num_rois, 4+1]\n    :param y_pred: 预测值 [batch_size, num_rois, 4+1]\n    :return: classifier class_loss\n    \"\"\"\n    return backend.mean(losses.categorical_crossentropy(y_true, y_pred))\n", "meta": {"hexsha": "881652950d09daf4597a791f004353db01137bbc", "size": 5212, "ext": "py", "lang": "Python", "max_stars_repo_path": "core/losses.py", "max_stars_repo_name": "verages/Faster_RCNN", "max_stars_repo_head_hexsha": "9752dc90857bc5cb639ec03fb84889fbfb859cc7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core/losses.py", "max_issues_repo_name": "verages/Faster_RCNN", "max_issues_repo_head_hexsha": "9752dc90857bc5cb639ec03fb84889fbfb859cc7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-02-09T23:59:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:59:11.000Z", "max_forks_repo_path": "core/losses.py", "max_forks_repo_name": "verages/Faster_RCNN", "max_forks_repo_head_hexsha": "9752dc90857bc5cb639ec03fb84889fbfb859cc7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.768115942, "max_line_length": 120, "alphanum_fraction": 0.6162701458, "include": true, "reason": "import numpy", "num_tokens": 1704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.2751297297667525, "lm_q1q2_score": 0.18018100982703114}}
{"text": "\"\"\"Module for representation and analysis of MS measurements\"\"\"\n\nimport re\nimport numpy as np\nimport json  # FIXME: This is for MSCalibration.export, but shouldn't have to be here.\nimport warnings\n\nfrom ..measurements import Measurement, Calibration\nfrom ..spectra import Spectrum\nfrom ..plotters.ms_plotter import MSPlotter, STANDARD_COLORS\nfrom ..exceptions import QuantificationError\nfrom ..constants import (\n    AVOGADROS_CONSTANT,\n    BOLTZMAN_CONSTANT,\n    STANDARD_TEMPERATURE,\n    STANDARD_PRESSURE,\n    DYNAMIC_VISCOSITIES,\n    MOLECULAR_DIAMETERS,\n    MOLAR_MASSES,\n)\nfrom ..data_series import ValueSeries\nfrom ..db import Saveable\nfrom ..tools import deprecate\n\n\nclass MSMeasurement(Measurement):\n    \"\"\"Class implementing raw MS functionality\"\"\"\n\n    extra_column_attrs = {\"ms_measurement\": (\"tspan_bg\",)}\n    default_plotter = MSPlotter\n\n    def __init__(self, name, **kwargs):\n        tspan_bg = kwargs.pop(\"tspan_bg\", None)\n        super().__init__(name, **kwargs)\n        self.tspan_bg = tspan_bg\n\n    @property\n    def ms_calibration(self):\n        ms_cal_list = []\n        tspan_bg = None\n        signal_bgs = {}\n        for cal in self.calibration_list:\n            ms_cal_list = ms_cal_list + getattr(cal, \"ms_cal_list\", [])\n            for mass, bg in getattr(cal, \"signal_bgs\", {}).items():\n                if mass not in signal_bgs:\n                    signal_bgs[mass] = bg\n            tspan_bg = tspan_bg or getattr(cal, \"tspan_bg\", None)\n        return MSCalibration(ms_cal_results=ms_cal_list, signal_bgs=signal_bgs)\n\n    @property\n    def signal_bgs(self):\n        return self.ms_calibration.signal_bgs\n\n    def set_bg(self, tspan_bg=None, mass_list=None):\n        \"\"\"Set background values for mass_list to the average signal during tspan_bg.\"\"\"\n        mass_list = mass_list or self.mass_list\n        tspan_bg = tspan_bg or self.tspan_bg\n        signal_bgs = {}\n        for mass in mass_list:\n            t, v = self.grab(mass, tspan_bg)\n            signal_bgs[mass] = np.mean(v)\n        self.add_calibration(MSCalibration(signal_bgs=signal_bgs))\n\n    def reset_bg(self, mass_list=None):\n        \"\"\"Reset background values for the masses in mass_list\"\"\"\n        mass_list = mass_list or self.mass_list\n        for mass in mass_list:\n            if mass in self.signal_bgs:\n                del self.signal_bgs[mass]\n\n    def grab(\n        self,\n        item,\n        tspan=None,\n        tspan_bg=None,\n        include_endpoints=False,\n        remove_background=False,\n    ):\n        \"\"\"Returns t, S where S is raw signal in [A] for a given signal name (ie mass)\n\n        Args:\n            item (str): Name of the signal.\n            tspan (list): Timespan for which the signal is returned.\n            tspan_bg (list): Timespan that corresponds to the background signal.\n                If not given, no background is subtracted.\n            remove_background (bool): Whether to remove a pre-set background if\n                available. This is special to MSMeasurement.\n                Defaults to False, but in grab_flux it defaults to True.\n            include_endpoints (bool): Whether to ensure tspan[0] and tspan[-1] are in t\n        \"\"\"\n        time, value = super().grab(\n            item, tspan=tspan, include_endpoints=include_endpoints\n        )\n\n        if tspan_bg:\n            _, bg = self.grab(item, tspan=tspan_bg)\n            return time, value - np.average(bg)\n        elif remove_background:\n            if item in self.signal_bgs:\n                return time, value - self.signal_bgs[item]\n            elif self.tspan_bg:\n                _, bg = self.grab(item, tspan=self.tspan_bg)\n                return time, value - np.average(bg)\n        return time, value\n\n    def grab_for_t(self, item, t, tspan_bg=None, remove_background=False):\n        \"\"\"Return a numpy array with the value of item interpolated to time t\n\n        Args:\n            item (str): The name of the value to grab\n            t (np array): The time vector to grab the value for\n            tspan_bg (iterable): Optional. A timespan defining when `item` is at its\n                baseline level. The average value of `item` in this interval will be\n                subtracted from what is returned.\n            remove_background (bool): Whether to remove a pre-set background if\n                available. This is special to MSMeasurement.\n                Defaults to False, but in grab_flux it defaults to True.\n        \"\"\"\n        t_0, v_0 = self.grab(\n            item, tspan_bg=tspan_bg, remove_background=remove_background\n        )\n        v = np.interp(t, t_0, v_0)\n        return v\n\n    def grab_signal(self, *args, **kwargs):\n        \"\"\"Alias for grab()\"\"\"\n        return self.grab(*args, **kwargs)\n\n    @deprecate(\n        \"0.1\", \"Use `remove_background` instead.\", \"0.3\", kwarg_name=\"removebackground\"\n    )\n    def grab_flux(\n        self,\n        mol,\n        tspan=None,\n        tspan_bg=None,\n        remove_background=True,\n        removebackground=None,\n        include_endpoints=False,\n    ):\n        \"\"\"Return the flux of mol (calibrated signal) in [mol/s]\n\n        Note:\n        `grab_flux(mol, ...)` is identical to `grab(f\"n_dot_{mol}\", ...)` with\n        remove_background=True by default. An MSCalibration does the maths.\n\n        Args:\n            mol (str or MSCalResult): Name of the molecule or a ms_calibration thereof\n            tspan (list): Timespan for which the signal is returned.\n            tspan_bg (list): Timespan that corresponds to the background signal.\n                If not given, no background is subtracted.\n            remove_background (bool): Whether to remove a pre-set background if available\n                Defaults to True.\n            removebackground (bool): DEPRECATED. Use `remove_background`.\n            include_endpoints (bool): Whether to interpolate for tspan[0] and tspan[-1]\n        \"\"\"\n        if removebackground is not None:\n            remove_background = removebackground\n        if isinstance(mol, MSCalResult):\n            t, signal = self.grab(\n                mol.mass,\n                tspan=tspan,\n                tspan_bg=tspan_bg,\n                remove_background=remove_background,\n                include_endpoints=include_endpoints,\n            )\n            return t, signal / mol.F\n        return self.grab(\n            # grab() invokes __getitem__, which invokes the `Calibration`. Specifically,\n            # `MSCalibration.calibrate_series()` interprets item names starting with\n            # \"n_\" as molecule fluxes, and checks itself for a sensitivity factor.\n            f\"n_dot_{mol}\",\n            tspan=tspan,\n            tspan_bg=tspan_bg,\n            remove_background=remove_background,\n            include_endpoints=include_endpoints,\n        )\n\n    @deprecate(\n        \"0.1\", \"Use `remove_background` instead.\", \"0.3\", kwarg_name=\"removebackground\"\n    )\n    def grab_flux_for_t(\n        self,\n        mol,\n        t,\n        tspan_bg=None,\n        remove_background=False,\n        removebackground=None,\n    ):\n        \"\"\"Return the flux of mol (calibrated signal) in [mol/s] for a given time vec\n\n        Args:\n            mol (str): Name of the molecule.\n            t (np.array): The time vector along which to give the flux\n            tspan_bg (tspan): Timespan that corresponds to the background signal.\n                If not given, no background is subtracted.\n            remove_background (bool): Whether to remove a pre-set background if available\n            removebackground (bool): DEPRECATED. Use `remove_background`.\n        \"\"\"\n        if removebackground is not None:\n            remove_background = removebackground\n        t_0, y_0 = self.grab_flux(\n            mol,\n            tspan_bg=tspan_bg,\n            remove_background=remove_background,\n        )\n        y = np.interp(t, t_0, y_0)\n        return y\n\n    def get_flux_series(self, mol):\n        \"\"\"Return a ValueSeries with the calibrated flux of mol\"\"\"\n        return self[f\"n_dot_{mol}\"]\n\n    def integrate_signal(self, mass, tspan, tspan_bg, ax=None):\n        \"\"\"Integrate a ms signal with background subtraction and evt. plotting\n\n        TODO: Should this, like grab_signal does now, have the option of using a\n            background saved in the object rather than calculating a new one?\n\n        Args:\n            mass (str): The mass for which to integrate the signal\n            tspan (tspan): The timespan over which to integrate\n            tspan_bg (tspan): Timespan at which the signal is at its background value\n            ax (Axis): axis to plot on. Defaults to None\n        \"\"\"\n        t, S = self.grab_signal(mass, tspan=tspan, include_endpoints=True)\n        if tspan_bg:\n            t_bg, S_bg_0 = self.grab_signal(mass, tspan=tspan_bg, include_endpoints=True)\n            S_bg = np.mean(S_bg_0) * np.ones(t.shape)\n        else:\n            S_bg = np.zeros(t.shape)\n        if ax:\n            if ax == \"new\":\n                fig, ax = self.plotter.new_ax()\n            ax.fill_between(t, S_bg, S, color=STANDARD_COLORS[mass], alpha=0.2)\n        return np.trapz(S - S_bg, t)\n\n    @property\n    def mass_list(self):\n        \"\"\"List of the masses for which ValueSeries are contained in the measurement\"\"\"\n        return [self.as_mass(col) for col in self.series_names if self.is_mass(col)]\n\n    def is_mass(self, item):\n        if re.search(\"^M[0-9]+$\", item):\n            return True\n        if item in self.reverse_aliases and self.is_mass(self.reverse_aliases[item][0]):\n            return True\n        return False\n\n    def as_mass(self, item):\n        if re.search(\"^M[0-9]+$\", item):\n            return item\n        new_item = self.reverse_aliases[item][0]\n        if self.is_mass(new_item):\n            return self.as_mass(new_item)\n        raise TypeError(f\"{self} does not recognize '{item}' as a mass.\")\n\n\nclass MSCalResult(Saveable):\n    \"\"\"A class for a mass spec ms_calibration result.\n\n    FIXME: I think that something inheriting directly from Saveable does not belong in\n        a technique module.\n    \"\"\"\n\n    table_name = \"ms_cal_results\"\n    column_attrs = {\"name\", \"mol\", \"mass\", \"cal_type\", \"F\"}\n\n    def __init__(\n        self,\n        name=None,\n        mol=None,\n        mass=None,\n        cal_type=None,\n        F=None,\n    ):\n        super().__init__()\n        self.name = name or f\"{mol}@{mass}\"\n        self.mol = mol\n        self.mass = mass\n        self.cal_type = cal_type\n        self.F = F\n\n    def __repr__(self):\n        return (\n            f\"{self.__class__.__name__}(name={self.name}, mol={self.mol}, \"\n            f\"mass={self.mass}, F={self.F})\"\n        )\n\n    @property\n    def color(self):\n        return STANDARD_COLORS[self.mass]\n\n\nclass MSCalibration(Calibration):\n    \"\"\"Class for mass spec calibrations. TODO: replace with powerful external package\"\"\"\n\n    extra_linkers = {\"ms_calibration_results\": (\"ms_cal_results\", \"ms_cal_result_ids\")}\n    # FIXME: signal_bgs are not saved at present. Should they be a separate table\n    #   of Saveable objects like ms_cal_results or should they be a single json value?\n    child_attrs = [\n        \"ms_cal_results\",\n    ]\n\n    def __init__(\n        self,\n        name=None,\n        date=None,\n        tstamp=None,  # FIXME: No need to have both a date and a tstamp?\n        setup=None,\n        ms_cal_results=None,\n        signal_bgs=None,\n        technique=\"MS\",\n        measurement=None,\n    ):\n        \"\"\"\n        Args:\n            name (str): Name of the ms_calibration\n            date (str): Date of the ms_calibration\n            setup (str): Name of the setup where the ms_calibration is made\n            ms_cal_results (list of MSCalResult): The mass spec calibrations\n            measurement (MSMeasurement): The measurement\n        \"\"\"\n        super().__init__(\n            name=name or f\"EC-MS ms_calibration for {setup} on {date}\",\n            technique=technique,\n            tstamp=tstamp,\n            measurement=measurement,\n        )\n        self.date = date\n        self.setup = setup\n        self.ms_cal_results = ms_cal_results or []\n        self.signal_bgs = signal_bgs or {}\n\n    @property\n    def ms_cal_result_ids(self):\n        return [cal.id for cal in self.ms_cal_results]\n\n    @property\n    def mol_list(self):\n        return list({cal.mol for cal in self.ms_cal_results})\n\n    @property\n    def mass_list(self):\n        return list({cal.mass for cal in self.ms_cal_results})\n\n    @property\n    def name_list(self):\n        return list({cal.name for cal in self.ms_cal_results})\n\n    def __contains__(self, mol):\n        return mol in self.mol_list or mol in self.name_list\n\n    def __iter__(self):\n        yield from self.ms_cal_results\n\n    def calibrate_series(self, key, measurement=None):\n        \"\"\"Return a calibrated series for `key` if possible.\n\n        If key starts with \"n_\", it is interpreted as a molecule flux. This method then\n        searches the calibration for a sensitivity factor for that molecule uses it to\n        divide the relevant mass signal from the measurement. Example acceptable keys:\n        \"n_H2\", \"n_dot_H2\".\n        If the key does not start with \"n_\", or the calibration can't find a relevant\n        sensitivity factor and mass signal, this method returns None.\n        \"\"\"\n        measurement = measurement or self.measurement\n        if key.startswith(\"n_\"):  # it's a flux!\n            mol = key.split(\"_\")[-1]\n            try:\n                mass, F = self.get_mass_and_F(mol)\n            except QuantificationError:\n                # Calibrations just return None when they can't get what's requested.\n                return\n            signal_series = measurement[mass]\n            y = signal_series.data\n            if mass in measurement.signal_bgs:\n                # FIXME: How to make this optional to user of MSMeasuremt.grab()?\n                y = y - measurement.signal_bgs[mass]\n            n_dot = y / F\n            return ValueSeries(\n                name=f\"n_dot_{mol}\",\n                unit_name=\"mol/s\",\n                data=n_dot,\n                tseries=signal_series.tseries,\n            )\n\n    def get_mass_and_F(self, mol):\n        \"\"\"Return the mass and sensitivity factor to use for simple quant. of mol\"\"\"\n        cal_list_for_mol = [cal for cal in self if cal.mol == mol or cal.name == mol]\n        Fs = [cal.F for cal in cal_list_for_mol]\n        if not Fs:\n            raise QuantificationError(f\"{self} has no sensitivity factor for {mol}\")\n        index = np.argmax(np.array(Fs))\n\n        the_good_cal = cal_list_for_mol[index]\n        return the_good_cal.mass, the_good_cal.F\n\n    def get_F(self, mol, mass):\n        \"\"\"Return the sensitivity factor for mol at mass\"\"\"\n        cal_list_for_mol_at_mass = [\n            cal\n            for cal in self\n            if (cal.mol == mol or cal.name == mol) and cal.mass == mass\n        ]\n        F_list = [cal.F for cal in cal_list_for_mol_at_mass]\n        if not F_list:\n            raise QuantificationError(\n                f\"{self} has no sensitivity factor for {mol} at {mass}\"\n            )\n        return np.mean(np.array(F_list))\n\n    def scaled_to(self, ms_cal_result):\n        \"\"\"Return a new ms_calibration w scaled sensitivity factors to match one given\"\"\"\n        F_0 = self.get_F(ms_cal_result.mol, ms_cal_result.mass)\n        scale_factor = ms_cal_result.F / F_0\n        calibration_as_dict = self.as_dict()\n        new_cal_list = []\n        for cal in self.ms_cal_results:\n            cal = MSCalResult(\n                name=cal.name,\n                mass=cal.mass,\n                mol=cal.mol,\n                F=cal.F * scale_factor,\n                cal_type=cal.cal_type + \" scaled\",\n            )\n            new_cal_list.append(cal)\n        calibration_as_dict[\"ms_cal_results\"] = new_cal_list\n        del calibration_as_dict[\"ms_cal_result_ids\"]\n        # ^ FIXME: ms_cal_result_ids via MemoryBackend\n        calibration_as_dict[\"name\"] = calibration_as_dict[\"name\"] + \" scaled\"\n        return self.__class__.from_dict(calibration_as_dict)\n\n    @classmethod\n    def read(cls, path_to_file):\n        \"\"\"Read an MSCalibration from a json-formatted text file\"\"\"\n        with open(path_to_file) as f:\n            obj_as_dict = json.load(f)\n        # put the MSCalResults (exported as dicts) into objects:\n        obj_as_dict[\"ms_cal_results\"] = [\n            MSCalResult.from_dict(ms_cal_as_dict)\n            for ms_cal_as_dict in obj_as_dict[\"ms_cal_results\"]\n        ]\n        return cls.from_dict(obj_as_dict)\n\n    def export(self, path_to_file=None):\n        \"\"\"Export an ECMSCalibration as a json-formatted text file\"\"\"\n        path_to_file = path_to_file or (self.name + \".ix\")\n        self_as_dict = self.as_dict()\n        # replace the ms_cal_result ids with the dictionaries of the results themselves:\n        del self_as_dict[\"ms_cal_result_ids\"]\n        self_as_dict[\"ms_cal_results\"] = [cal.as_dict() for cal in self.ms_cal_results]\n        with open(path_to_file, \"w\") as f:\n            json.dump(self_as_dict, f, indent=4)\n\n\nclass MSInlet:\n    \"\"\"A class for describing the inlet to the mass spec\n\n    Every MSInlet describes the rate and composition of the gas entering a mass\n    spectrometer. The default is a Spectro Inlets EC-MS chip.\n    TODO: Replace with powerful external package.\n    \"\"\"\n\n    def __init__(\n        self,\n        *,\n        l_cap=1e-3,\n        w_cap=6e-6,\n        h_cap=6e-6,\n        gas=\"He\",\n        T=STANDARD_TEMPERATURE,\n        p=STANDARD_PRESSURE,\n        verbose=True,\n    ):\n        \"\"\"Create an MSInlet object given its properties.\n\n        Args:\n            l_cap (float): capillary length [m]. Defaults to design parameter.\n            w_cap (float): capillary width [m]. Defaults to design parameter.\n            h_cap (float): capillary height [m]. Defaults to design parameter.\n            p (float): system pressure in [Pa] (if to change from that in medium)\n            T (float): system temperature in [K] (if to change from that in medium)\n            gas (str): the gas at the start of the inlet.\n            verbose (bool): whether to print stuff to the terminal\n        \"\"\"\n        self.verbose = verbose\n        self.l_cap = l_cap\n        self.l_cap_eff = {}\n        self.w_cap = w_cap\n        self.h_cap = h_cap\n        self.p = p\n        self.T = T\n        self.gas = gas  # TODO: Gas mixture class. This must be a pure gas now.\n\n    def calc_l_cap_eff(\n        self, n_dot_measured, gas=None, w_cap=None, h_cap=None, T=None, p=None\n    ):\n        \"\"\"Calculate gas specific effective length of the capillary in [m]\n        and add {gas:value} to l_cap_eff (dict)\n\n        Args:\n            w_cap (float): Capillary width [m], defaults to self.w_cap\n            h_cap (float): Capillary height [m], defaults to self.h_cap\n            n_dot_measured (float): Measured flux of gas [mol/s]\n            gas (dict or str): The gas in the chip, defaults to self.gas\n            T (float): Temperature [K], if to be updated\n            p (float): Pressure [Pa], if to be updated\n        Returns:\n            float: Gas specific effective length in [m]\n        \"\"\"\n\n        n_dot_predicted = self.calc_n_dot_0(gas=gas, w_cap=w_cap, h_cap=h_cap, T=T, p=p)\n\n        l_cap_gas_specific_eff = self.l_cap * n_dot_predicted / n_dot_measured\n        self.l_cap_eff[\n            gas\n        ] = l_cap_gas_specific_eff  # add effective l_cap for specific gas\n\n        return l_cap_gas_specific_eff\n\n    def update_l_cap(self, gases=[]):\n        \"\"\"Update self.l_cap from average of values in dict l_cap_eff\n\n        Args:\n            gases (list): List of gases to average l_cap, default all\n        Returns:\n            float: Averaged effective capilllary length in [m]\n        \"\"\"\n        if self.l_cap_eff and not gases:\n            self.l_cap = np.mean(list(self.l_cap_eff.values()))\n        elif self.l_cap_eff and gases:\n            _l_cap = 0\n            for gas in gases:\n                _l_cap += self.l_cap_eff[gas]\n            self.l_cap = _l_cap / len(gases)\n\n        return self.l_cap\n\n    def calc_n_dot_0(self, gas=None, w_cap=None, h_cap=None, l_cap=None, T=None, p=None):\n        \"\"\"Calculate the total molecular flux through the capillary in [s^-1]\n\n        Uses Equation 4.10 of Trimarco, 2017. \"Real-time detection of sub-monolayer\n        desorption phenomena during electrochemical reactions: Instrument development\n        and applications.\" PhD Thesis, Technical University of Denmark.\n\n        Args:\n            w_cap (float): Capillary width [m], defaults to self.w_cap\n            h_cap (float): Capillary height [m], defaults to self.h_cap\n            l_cap (float): Capillary length [m], defaults to self.l_cap\n            gas (dict or str): The gas in the chip, defaults to self.gas\n            T (float): Temperature [K], if to be updated\n            p (float): Pressure [Pa], if to be updated\n        Returns:\n            float: The total molecular flux in [s^-1] through the capillary\n        \"\"\"\n\n        if w_cap is None:\n            w_cap = self.w_cap  # capillary width in [m]\n        if h_cap is None:\n            h_cap = self.h_cap  # capillary height in [m]\n        if l_cap is None:\n            l_cap = self.l_cap  # effective capillary length in [m]\n        if T is None:\n            T = self.T\n        if p is None:\n            p = self.p\n        pi = np.pi\n\n        # TODO: make it so that DYNAMIC_VISCOSITIES[gas] can just be a float if someone\n        #   enters it without having access to the temperature-dependent values.\n        if T < DYNAMIC_VISCOSITIES[gas][0, 0] or T > DYNAMIC_VISCOSITIES[gas][-1, 0]:\n            warnings.warn(\n                \"Insufficient data in constants.py to appropriately estimate \"\n                f\"the dynamic viscosity for {gas} at temperature: {T}K\",\n                stacklevel=2,\n            )\n\n        _eta_v = DYNAMIC_VISCOSITIES[gas][:, 1]  # list of known eta(T) for 'gas'\n        _eta_T = DYNAMIC_VISCOSITIES[gas][:, 0]  # list of paired Ts for eta(T)\n\n        eta = np.interp(T, _eta_T, _eta_v)  # dynamic viscosity of gas at T in [Pa*s]\n\n        s = MOLECULAR_DIAMETERS[gas]  # molecule diameter in [m]\n        m = MOLAR_MASSES[gas] * 1e-3 / AVOGADROS_CONSTANT  # molecule mass in [kg]\n\n        d = ((w_cap * h_cap) / pi) ** 0.5 * 2\n        # d = 4.4e-6  #used in Henriksen2009\n        a = d / 2\n        p_1 = p\n        lambda_ = d  # defining the transitional pressure\n        # ...from setting mean free path equal to capillary d\n        p_t = BOLTZMAN_CONSTANT * T / (2**0.5 * pi * s**2 * lambda_)\n        p_2 = 0\n        p_m = (p_1 + p_t) / 2  # average pressure in the transitional flow region\n        v_m = (8 * BOLTZMAN_CONSTANT * T / (pi * m)) ** 0.5\n        # a reciprocal velocity used for short-hand:\n        nu = (m / (BOLTZMAN_CONSTANT * T)) ** 0.5\n\n        # ... and now, we're ready for the capillary equation.\n        #   (need to turn of black and flake8 for tolerable format)\n        # fmt: off\n        #   Equation 4.10 of Daniel Trimarco's PhD Thesis:\n        N_dot = (                                                               # noqa\n            1 / (BOLTZMAN_CONSTANT * T) * 1 / l_cap * (                         # noqa\n                (p_t - p_2) * a**3 * 2 * pi / 3 * v_m + (p_1 - p_t) * (         # noqa\n                    a**4 * pi / (8 * eta) * p_m  + a**3 * 2 * pi / 3 * v_m * (  # noqa\n                        (1 + 2 * a * nu * p_m / eta) / (                        # noqa\n                        1 + 2.48 * a * nu * p_m / eta                           # noqa\n                        )                                                       # noqa\n                    )                                                           # noqa\n                )                                                               # noqa\n            )                                                                   # noqa\n        )                                                                       # noqa\n        # fmt: on\n        n_dot = N_dot / AVOGADROS_CONSTANT\n        return n_dot\n\n    def gas_flux_calibration(\n        self,\n        measurement,\n        mol,\n        mass,\n        tspan=None,\n        tspan_bg=None,\n        ax=None,\n        carrier_mol=None,\n        mol_conc_ppm=None,\n    ):\n        \"\"\"\n        Args:\n            measurement (MSMeasurement): The measurement with the ms_calibration data\n            mol (str): The name of the molecule to calibrate\n            mass (str): The mass to calibrate at\n            tspan (iter): The timespan to average the signal over. Defaults to all\n            tspan_bg (iter): Optional timespan at which the signal is at its background.\n            ax (matplotlib axis): The axis on which to indicate what signal is used\n                with a thicker line. Defaults to none\n            carrier_mol (str): The name of the molecule of the carrier gas if\n                a dilute analyte is used. Calibration assumes total flux of the\n                capillary is the same as the flux of pure carrier gas. Defaults\n                to None.\n            mol_conc_ppm (float): Concentration of the dilute analyte in the carrier gas\n                in ppm. Defaults to None.\n\n        Returns MSCalResult: a ms_calibration result containing the sensitivity factor\n            for mol at mass\n        \"\"\"\n        t, S = measurement.grab_signal(mass, tspan=tspan, tspan_bg=tspan_bg)\n        if ax:\n            ax.plot(t, S, color=STANDARD_COLORS[mass], linewidth=5)\n        if carrier_mol:\n            if mol_conc_ppm:\n                cal_type = \"carrier_gas_flux_calibration\"\n            else:\n                raise QuantificationError(\n                    \"Cannot use carrier gas calibration without analyte\"\n                    \" concentration. mol_conc_ppm is missing.\"\n                )\n        elif mol_conc_ppm:\n            raise QuantificationError(\n                \"Cannot use carrier gas calibration without carrier\"\n                \" gas definition. carrier_mol is missing.\"\n            )\n        else:\n            cal_type = \"gas_flux_calibration\"\n            mol_conc_ppm = 10**6\n            carrier_mol = mol\n\n        n_dot = self.calc_n_dot_0(gas=carrier_mol) * mol_conc_ppm / 10**6\n        F = np.mean(S) / n_dot\n        return MSCalResult(\n            name=f\"{mol}@{mass}\",\n            mol=mol,\n            mass=mass,\n            cal_type=cal_type,\n            F=F,\n        )\n\n\nclass MSSpectrum(Spectrum):\n    \"\"\"Nothing to add to normal spectrum yet.\n    TODO: Methods for co-plotting ref spectra from a database\n    \"\"\"\n\n    pass\n", "meta": {"hexsha": "732ba326e7b36ebc29b50293583b3e003e3996e2", "size": 26529, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/ixdat/techniques/ms.py", "max_stars_repo_name": "matenestor/ixdat", "max_stars_repo_head_hexsha": "ac3ff81f5c92f2d4bbede5fc9fc5a1df2a5eb34f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ixdat/techniques/ms.py", "max_issues_repo_name": "matenestor/ixdat", "max_issues_repo_head_hexsha": "ac3ff81f5c92f2d4bbede5fc9fc5a1df2a5eb34f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-31T09:54:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T09:54:40.000Z", "max_forks_repo_path": "src/ixdat/techniques/ms.py", "max_forks_repo_name": "matenestor/ixdat", "max_forks_repo_head_hexsha": "ac3ff81f5c92f2d4bbede5fc9fc5a1df2a5eb34f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.615720524, "max_line_length": 89, "alphanum_fraction": 0.5840024125, "include": true, "reason": "import numpy", "num_tokens": 6255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.18016401282742028}}
{"text": "import glob\r\nimport os\r\nimport pysiaf\r\n\r\nimport astropy.coordinates as crd\r\nimport astropy.units as u\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom astroquery.irsa import Irsa\r\nfrom matplotlib import cm\r\nfrom scipy.io import readsav\r\nfrom astropy.io import fits\r\nfrom exoctk.utils import get_env_variables\r\nfrom pysiaf.utils import rotations\r\n\r\nEXOCTK_DATA = os.environ.get('EXOCTK_DATA')\r\nif not EXOCTK_DATA:\r\n    print('WARNING: The $EXOCTK_DATA environment variable is not set. '\r\n          'Contamination overlap will not work. Please set the '\r\n          'value of this variable to point to the location of the exoctk_data '\r\n          'download folder.  Users may retreive this folder by clicking the '\r\n          '\"ExoCTK Data Download\" button on the ExoCTK website, or by using '\r\n          'the exoctk.utils.download_exoctk_data() function.'\r\n          )\r\n    TRACES_PATH = None\r\nelse:\r\n    TRACES_PATH = os.path.join(EXOCTK_DATA, 'exoctk_contam', 'traces')\r\n\r\n\r\ndef sossFieldSim(ra, dec, binComp='', dimX=256):\r\n    \"\"\" Produce a SOSS field simulation for a target.\r\n\r\n    Parameters\r\n    ----------\r\n    ra: float\r\n        The RA of the target.\r\n    dec: float\r\n        The Dec of the target.\r\n    binComp: sequence\r\n        The parameters of a binary companion.\r\n    dimX: int\r\n        The subarray size.\r\n\r\n    Returns\r\n    -------\r\n    simuCub : np.ndarray\r\n        The simulated data cube.\r\n    \"\"\"\r\n\r\n    # STEP 1\r\n    # Pulling stars from IRSA point-source catalog\r\n    targetcrd = crd.SkyCoord(ra=ra, dec=dec, unit=(u.hour, u.deg))\r\n    targetRA = targetcrd.ra.value\r\n    targetDEC = targetcrd.dec.value\r\n    info = Irsa.query_region(targetcrd,\r\n                             catalog='fp_psc',\r\n                             spatial='Cone',\r\n                             radius=2.5 * u.arcmin)\r\n\r\n    # Coordinates of all stars in FOV, including target\r\n    allRA = info['ra'].data.data\r\n    allDEC = info['dec'].data.data\r\n    Jmag = info['j_m'].data.data\r\n    Hmag = info['h_m'].data.data\r\n    Kmag = info['k_m'].data.data\r\n\r\n    # J-H band, H-K band. This will be used to derive the stellar Temps later\r\n    J_Hobs = Jmag - Hmag\r\n    H_Kobs = Hmag - Kmag\r\n\r\n    # Determining target index by calculating the relative distance between\r\n    # each source and the target. The target will have the smallest distance\r\n    # from itself (oof) so whatever that index is will be the targetIndex\r\n    aa = ((targetRA - allRA) * np.cos(targetDEC))\r\n    distance = np.sqrt(aa**2 + (targetDEC - allDEC)**2)\r\n    targetIndex = np.argmin(distance)\r\n\r\n    # Add any missing companion\r\n    if binComp != '':\r\n        deg2rad = np.pi / 180\r\n        bb = binComp[0] / 3600 / np.cos(allDEC[targetIndex] * deg2rad)\r\n        allRA = np.append(allRA, (allRA[targetIndex] + bb))\r\n        allDEC = np.append(allDEC, (allDEC[targetIndex] + binComp[1] / 3600))\r\n        Jmag = np.append(Jmag, binComp[2])\r\n        Hmag = np.append(Kmag, binComp[3])\r\n        Kmag = np.append(Kmag, binComp[4])\r\n        J_Hobs = Jmag - Hmag\r\n        H_Kobs = Hmag - Kmag\r\n\r\n    # Number of stars\r\n    nStars = allRA.size\r\n\r\n    # Restoring model parameters\r\n    modelParam = readsav(os.path.join(TRACES_PATH, 'NIRISS', 'modelsInfo.sav'),\r\n                         verbose=False)\r\n    models = modelParam['models']\r\n    modelPadX = modelParam['modelpadx']\r\n    modelPadY = modelParam['modelpady']\r\n    dimXmod = modelParam['dimxmod']\r\n    dimYmod = modelParam['dimymod']\r\n    jhMod = modelParam['jhmod']\r\n    hkMod = modelParam['hkmod']\r\n    teffMod = modelParam['teffmod']\r\n\r\n    # Find/assign Teff of each star\r\n    starsT = np.empty(nStars)\r\n    for j in range(nStars):\r\n        color_separation = (J_Hobs[j] - jhMod)**2 + (H_Kobs[j] - hkMod)**2\r\n        min_separation_ind = np.argmin(color_separation)\r\n        starsT[j] = teffMod[min_separation_ind]\r\n\r\n    sweetSpot = dict(x=856, y=107, RA=allRA[targetIndex],\r\n                     DEC=allDEC[targetIndex], jmag=Jmag[targetIndex])\r\n\r\n    radeg = 180 / np.pi\r\n    niriss_pixel_scale = 0.065  # arcsec\r\n    # offset between all stars and target\r\n    dRA = (allRA - sweetSpot['RA']) * np.cos(sweetSpot['DEC'] / radeg) * 3600\r\n    dDEC = (allDEC - sweetSpot['DEC']) * 3600\r\n\r\n    # Put field stars positions and magnitudes in structured array\r\n    _ = dict(RA=allRA, DEC=allDEC, dRA=dRA, dDEC=dDEC, jmag=Jmag, T=starsT,\r\n             x=np.empty(nStars), y=np.empty(nStars), dx=np.empty(nStars),\r\n             dy=np.empty(nStars))\r\n    stars = np.empty(nStars,\r\n                     dtype=[(key, val.dtype) for key, val in _.items()])\r\n    for key, val in _.items():\r\n        stars[key] = val\r\n\r\n    # Initialize final fits cube that contains the modelled traces\r\n    # with contamination\r\n    PAmin = 0  # instrument PA, degrees\r\n    PAmax = 360\r\n    dPA = 1  # degrees\r\n\r\n    # Set of IPA values to cover\r\n    PAtab = np.arange(PAmin, PAmax, dPA)    # degrees\r\n    nPA = len(PAtab)\r\n\r\n    dimY = 2048\r\n    # cube of trace simulation at every degree of field rotation,\r\n    # +target at O1 and O2\r\n    simuCube = np.zeros([nPA + 2, dimY, dimX])\r\n\r\n    saveFiles = glob.glob(\r\n        os.path.join(\r\n            TRACES_PATH,\r\n            'NIRISS',\r\n            '*modelOrder12*.sav'))\r\n\r\n    # Big loop to generate a simulation at each instrument PA\r\n\r\n    for kPA in range(PAtab.size):\r\n        APA = PAtab[kPA]\r\n        print('Generating field at APA : {}'.format(str(APA)))\r\n\r\n        V3PA = APA + 0.57  # from APT\r\n\r\n        sindx = np.sin((np.pi / 2) + APA / radeg) * stars['dDEC']\r\n        cosdx = np.cos((np.pi / 2) + APA / radeg) * stars['dDEC']\r\n        nps = niriss_pixel_scale\r\n        stars['dx'] = (np.cos((np.pi / 2) + APA / radeg)\r\n                       * stars['dRA'] - sindx) / nps\r\n        stars['dy'] = (np.sin((np.pi / 2) + APA / radeg)\r\n                       * stars['dRA'] + cosdx) / nps\r\n        stars['x'] = stars['dx'] + sweetSpot['x']\r\n        stars['y'] = stars['dy'] + sweetSpot['y']\r\n\r\n        # Retain stars that are within the Direct Image NIRISS POM FOV\r\n        ind, = np.where((stars['x'] >= -162) & (stars['x'] <= 2047 + 185) &\r\n                        (stars['y'] >= -154) & (stars['y'] <= 2047 + 174))\r\n        starsInFOV = stars[ind]\r\n\r\n        for i in range(len(ind)):\r\n            intx = round(starsInFOV['dx'][i])\r\n            inty = round(starsInFOV['dy'][i])\r\n\r\n            k = np.where(teffMod == starsInFOV['T'][i])[0][0]\r\n\r\n            fluxscale = 10.0**(-0.4 *\r\n                               (starsInFOV['jmag'][i] - sweetSpot['jmag']))\r\n\r\n            # deal with subection sizes.\r\n            # these variables will determine where the\r\n            # trace will land on the array based on the\r\n            # neighbor's position relative to the target's position\r\n            mx0 = int(modelPadX - intx)\r\n            mx1 = int(modelPadX - intx + dimX)\r\n            my0 = int(modelPadY - inty)\r\n            my1 = int(modelPadY - inty + dimY)\r\n\r\n            if (mx0 > dimXmod) or (my0 > dimYmod):\r\n                continue\r\n            if (mx1 < 0) or (my1 < 0):\r\n                continue\r\n\r\n            x0 = (mx0 < 0) * (-mx0)\r\n            y0 = (my0 < 0) * (-my0)\r\n            mx0 *= (mx0 >= 0)\r\n            mx1 = dimXmod if mx1 > dimXmod else mx1\r\n            my0 *= (my0 >= 0)\r\n            my1 = dimYmod if my1 > dimYmod else my1\r\n\r\n            # if target and first kPA, add target traces of order 1 and 2\r\n            # in output cube\r\n            if (intx == 0) & (inty == 0) & (kPA == 0):\r\n                fNameModO12 = saveFiles[k]\r\n\r\n                modelO12 = readsav(fNameModO12, verbose=False)['modelo12']\r\n                ord1 = modelO12[0, my0:my1, mx0:mx1] * fluxscale\r\n                ord2 = modelO12[1, my0:my1, mx0:mx1] * fluxscale\r\n                simuCube[0, y0:y0 + my1 - my0, x0:x0 + mx1 - mx0] = ord1\r\n                simuCube[1, y0:y0 + my1 - my0, x0:x0 + mx1 - mx0] = ord2\r\n\r\n            if (intx != 0) or (inty != 0):\r\n                mod = models[k, my0:my1, mx0:mx1]\r\n                simuCube[kPA + 2, y0:y0 + my1 - my0,\r\n                         x0:x0 + mx1 - mx0] += mod * fluxscale\r\n    return simuCube\r\n\r\n\r\ndef gtsFieldSim(ra, dec, filter, binComp=''):\r\n    \"\"\" Produce a Grism Time Series field simulation for a target.\r\n    Parameters\r\n    ----------\r\n    ra : float\r\n        The RA of the target.\r\n    dec : float\r\n        The Dec of the target.\r\n    filter : str\r\n        The NIRCam filter being used. Can either be:\r\n        'F444W' or 'F322W2' (case-sensitive)\r\n    binComp : sequence\r\n        The parameters of a binary companion.\r\n\r\n    Returns\r\n    -------\r\n    simuCube : np.ndarray\r\n        The simulated data cube. Index 0 and 1 (axis=0) show the trace of\r\n        the target for orders 1 and 2 (respectively). Index 2-362 show the trace\r\n        of the target at every position angle (PA) of the instrument.\r\n    \"\"\"\r\n    # Instantiate a pySIAF object\r\n    siaf = pysiaf.Siaf('NIRCam')\r\n\r\n    full = siaf.apertures['NRCA5_FULL']\r\n    if filter == 'F444W':\r\n        aper = siaf.apertures['NRCA5_GRISM256_F444W']\r\n    elif filter == 'F322W2':\r\n        aper = siaf.apertures['NRCA5_GRISM256_F322W2']\r\n\r\n    # Calling the variables\r\n    deg2rad = np.pi / 180\r\n    subX, subY = aper.XSciSize, aper.YSciSize\r\n    rad = 2.5  # arcmins\r\n    pixel_scale = 0.063  # arsec/pixel\r\n    V3PAs = np.arange(0, 360, 1)\r\n    nPA = len(V3PAs)\r\n    # Generate cube of field simulation at every degree of APA rotation\r\n    simuCube = np.zeros([nPA + 1, subY, subX])\r\n    xSweet, ySweet = aper.reference_point('det')\r\n    add_to_v3pa = aper.V3IdlYAngle\r\n    # NIRCam Full Frame dimensions\r\n    rows, cols = full.corners('det')\r\n    minrow, maxrow = rows.min(), rows.max()\r\n    mincol, maxcol = cols.min(), cols.max()\r\n\r\n    #############################STEP 1#####################################\r\n    ########################################################################\r\n    # Converting to degrees\r\n    targetcrd = crd.SkyCoord(ra=ra, dec=dec, unit=(u.hour, u.deg))\r\n    targetRA = targetcrd.ra.value\r\n    targetDEC = targetcrd.dec.value\r\n\r\n    # Querying for neighbors with 2MASS IRSA's fp_psc (point-source catalog)\r\n    info = Irsa.query_region(targetcrd, catalog='fp_psc', spatial='Cone',\r\n                             radius=rad * u.arcmin)\r\n\r\n    # Coordinates of all the stars in FOV, including target\r\n    allRA = info['ra'].data.data\r\n    allDEC = info['dec'].data.data\r\n\r\n    # Initiating a dictionary to hold all relevant star information\r\n    stars = {}\r\n    stars['RA'], stars['DEC'] = allRA, allDEC\r\n\r\n    #############################STEP 2#####################################\r\n    ########################################################################\r\n    sindRA = (targetRA - stars['RA']) * np.cos(targetDEC)\r\n    cosdRA = targetDEC - stars['DEC']\r\n    distance = np.sqrt(sindRA**2 + cosdRA**2)\r\n    if np.min(distance) > 1.0*(10**-4):\r\n        coords = crd.SkyCoord(ra=ra, dec=dec, unit=(u.hour, u.deg)).to_string('decimal')\r\n        ra, dec = coords.split(' ')[0], coords.split(' ')[1]\r\n        raise Exception('Unable to detect a source with coordinates [RA: {}, DEC: {}] within IRSA`s 2MASS Point-Source Catalog. Please enter different coordinates or contact the JWST help desk.'.format(str(ra), str(dec)))\r\n\r\n    targetIndex = np.argmin(distance)\r\n\r\n    # Restoring model parameters\r\n    modelParam = readsav(os.path.join(TRACES_PATH, 'NIRISS', 'modelsInfo.sav'),\r\n                         verbose=False)\r\n    models = modelParam['models']\r\n    modelPadX = modelParam['modelpadx']\r\n    modelPadY = modelParam['modelpady']\r\n    dimXmod = modelParam['dimxmod']\r\n    dimYmod = modelParam['dimymod']\r\n    jhMod = modelParam['jhmod']\r\n    hkMod = modelParam['hkmod']\r\n    teffMod = modelParam['teffmod']\r\n\r\n    #############################STEP 3#####################################\r\n    ########################################################################\r\n    # JHK bands of all stars in FOV, including target\r\n    Jmag = info['j_m'].data.data\r\n    Hmag = info['h_m'].data.data\r\n    Kmag = info['k_m'].data.data\r\n    # J-H band, H-K band. This will be used to derive the Teff\r\n    J_Hobs = Jmag - Hmag\r\n    H_Kobs = Hmag - Kmag\r\n\r\n    # Add any missing companion\r\n    if binComp != '':\r\n        bb = binComp[0] / 3600 / np.cos(allDEC[targetIndex] * deg2rad)\r\n        allRA = np.append(allRA, (allRA[targetIndex] + bb))\r\n        allDEC = np.append(allDEC, (allDEC[targetIndex] + binComp[1] / 3600))\r\n        Jmag = np.append(Jmag, binComp[2])\r\n        Hmag = np.append(Kmag, binComp[3])\r\n        Kmag = np.append(Kmag, binComp[4])\r\n        J_Hobs = Jmag - Hmag\r\n        H_Kobs = Hmag - Kmag\r\n\r\n    # Number of stars\r\n    nStars = stars['RA'].size\r\n\r\n    # Find/assign Teff of each star\r\n    starsT = np.empty(nStars)\r\n    for j in range(nStars):\r\n        color_separation = (J_Hobs[j] - jhMod)**2 + (H_Kobs[j] - hkMod)**2\r\n        min_separation_ind = np.argmin(color_separation)\r\n        starsT[j] = teffMod[min_separation_ind]\r\n\r\n    # Record keeping\r\n    stars['Temp'] = starsT\r\n    stars['Jmag'] = Jmag\r\n\r\n    #############################STEP 4#####################################\r\n    ########################################################################\r\n    # Calculate corresponding V2/V3 (TEL) coordinates for Sweetspot\r\n    v2targ, v3targ = aper.det_to_tel(xSweet, ySweet)\r\n\r\n    for V3PA in range(0, nPA, 1):\r\n        # Get APA from V3PA\r\n        APA = V3PA + add_to_v3pa\r\n        if APA > 360:\r\n            APA = APA-360\r\n        elif APA < 0:\r\n            APA = APA+360\r\n\r\n        print('Generating field at APA : {}'.format(str(APA)))\r\n\r\n        # Get target's attitude matrix for each Position Angle\r\n        attitude = rotations.attitude_matrix(v2targ, v3targ,\r\n                                             targetRA, targetDEC,\r\n                                             APA)\r\n\r\n        xdet, ydet = [], []\r\n        xsci, ysci = [], []\r\n        for starRA, starDEC in zip(stars['RA'], stars['DEC']):\r\n            # Get the TEL coordinates of each star w attitude matrix\r\n            V2, V3 = rotations.sky_to_tel(attitude, starRA, starDEC)\r\n            # Convert to arcsec and turn to a float\r\n            V2, V3 = V2.to(u.arcsec).value, V3.to(u.arcsec).value\r\n\r\n            XDET, YDET = aper.tel_to_det(V2, V3)\r\n            XSCI, YSCI = aper.det_to_sci(XDET, YDET)\r\n\r\n            xdet.append(XDET)\r\n            ydet.append(YDET)\r\n            xsci.append(XSCI)\r\n            ysci.append(YSCI)\r\n\r\n        # Record keeping\r\n        stars['xdet'], stars['ydet'] = np.array(xdet), np.array(ydet)\r\n        stars['xsci'], stars['ysci'] = np.array(xsci), np.array(ysci)\r\n\r\n        sci_targx, sci_targy = stars['xsci'][targetIndex],\\\r\n            stars['ysci'][targetIndex]\r\n\r\n    #############################STEP 5#####################################\r\n    ########################################################################\r\n        inFOV = []\r\n        for star in range(0, nStars):\r\n\r\n            x, y = stars['xdet'][star], stars['ydet'][star]\r\n            if (mincol < x) & (x < maxcol) & (minrow < y) & (y < maxrow):\r\n                inFOV.append(star)\r\n\r\n        inFOV = np.array(inFOV)\r\n\r\n    #############################STEP 6#####################################\r\n    ########################################################################\r\n        nircam_path = 'NIRCam_F444W' if filter == 'F444W' else 'NIRCam_F322W2'\r\n        fitsFiles = glob.glob(\r\n            os.path.join(\r\n                TRACES_PATH,\r\n                nircam_path,\r\n                'rot*.fits'))\r\n        fitsFiles = np.sort(fitsFiles)\r\n\r\n        for idx in inFOV:\r\n\r\n            sci_dx = round(sci_targx - stars['xsci'][idx])\r\n            sci_dy = round(sci_targy - stars['ysci'][idx])\r\n            temp = stars['Temp'][idx]\r\n\r\n            for file in fitsFiles:\r\n                if str(temp) in file:\r\n                    trace = fits.getdata(file, 1)[0]\r\n\r\n            fluxscale = 10.0**(-0.4 * \\\r\n                               (stars['Jmag'][idx] - stars['Jmag'][targetIndex]))\r\n\r\n            # Padding array\r\n            pad_trace = np.pad(trace, pad_width=5000, mode='constant',\r\n                               constant_values=0)\r\n\r\n            # Determine the highest pixel value of trace\r\n            maxY, maxX = np.where(pad_trace == pad_trace.max())\r\n            peakY, peakX = maxY[0], maxX[0]\r\n\r\n            # Use relative distances (sci_dx, sci_dy) to find target\r\n            xTarg = peakX + sci_dx\r\n            yTarg = peakY + sci_dy\r\n\r\n            # Use the (xTarg, yTarg) coordinates to slice out subarray\r\n            # remember X is columns, Y is rows\r\n            dimX0, dimX1 = xTarg - sci_targx, xTarg + subX - sci_targx\r\n            dimY0, dimY1 = yTarg - sci_targy, yTarg + subY - sci_targy\r\n\r\n            if dimX0 < 0:\r\n                dimX0 = 0\r\n                dimX1 = subX\r\n            if dimY0 < 0:\r\n                dimY0 = 0\r\n                dimY1 = subY\r\n\r\n            traceX, traceY = np.shape(pad_trace)[1], np.shape(pad_trace)[0]\r\n            if dimX1 > traceX:\r\n                dimX1 = traceX\r\n                dimX0 = traceX - subX\r\n            if dimY1 > traceY:\r\n                dimY1 = traceY\r\n                dimY0 = traceY - subY\r\n\r\n            if (dimX1 < 0) or (dimY1 < 0):\r\n                continue\r\n\r\n            # -1 because pySIAF is 1-indexed\r\n            mx0, mx1 = int(dimX0) - 1, int(dimX1) - 1\r\n            my0, my1 = int(dimY0) - 1, int(dimY1) - 1\r\n\r\n            # Fleshing out index 0 of the simulation cube (trace of target)\r\n            if (sci_dx == 0) & (sci_dy == 0):  # this is the target\r\n\r\n                tr = pad_trace[my0:my1, mx0:mx1] * fluxscale\r\n                trX, trY = np.shape(tr)[1], np.shape(tr)[0]\r\n\r\n                simuCube[0, 0:trY, 0:trX] = tr\r\n\r\n            # Fleshing out indexes 1-361 of the simulation cube\r\n            # (trace of neighboring stars at every position angle)\r\n            else:\r\n\r\n                tr = pad_trace[my0:my1, mx0:mx1] * fluxscale\r\n                trX, trY = np.shape(tr)[1], np.shape(tr)[0]\r\n                simuCube[V3PA + 1, 0:trY, 0:trX] += tr\r\n\r\n    return simuCube\r\n\r\n\r\ndef lrsFieldSim(ra, dec, binComp=''):\r\n    \"\"\" Produce a Grism Time Series field simulation for a target.\r\n    Parameters\r\n    ----------\r\n    ra : float\r\n        The RA of the target.\r\n    dec : float\r\n        The Dec of the target.\r\n    binComp : sequence\r\n        The parameters of a binary companion.\r\n\r\n    Returns\r\n    -------\r\n    simuCube : np.ndarray\r\n        The simulated data cube. Index 0 and 1 (axis=0) show the trace of\r\n        the target for orders 1 and 2 (respectively). Index 2-362 show the trace\r\n        of the target at every position angle (PA) of the instrument.\r\n    \"\"\"\r\n    #############################INSTRUMENT PARAMETERS######################\r\n    ########################################################################\r\n    # Instantiate a pySIAF object\r\n    siaf = pysiaf.Siaf('MIRI')\r\n    aper = siaf.apertures['MIRIM_SLITLESSPRISM']\r\n    full = siaf.apertures['MIRIM_FULL']\r\n\r\n    # Calling the variables\r\n    deg2rad = np.pi / 180\r\n    subX, subY = aper.XSciSize, aper.YSciSize\r\n    rad = 2.0  # arcmins\r\n    pixel_scale = 0.11  # arsec/pixel\r\n    V3PAs = np.arange(0, 360, 1)\r\n    nPA = len(V3PAs)\r\n    # Generate cube of field simulation at every degree of APA rotation\r\n    simuCube = np.zeros([nPA + 1, subY, subX])\r\n    xSweet, ySweet = aper.reference_point('det')\r\n    add_to_v3pa = aper.V3IdlYAngle\r\n    # MIRI Full Frame dimensions\r\n    rows, cols = full.corners('det')\r\n    minrow, maxrow = rows.min(), rows.max()\r\n    mincol, maxcol = cols.min(), cols.max()\r\n\r\n    #############################STEP 1#####################################\r\n    ########################################################################\r\n    # Converting to degrees\r\n    targetcrd = crd.SkyCoord(ra=ra, dec=dec, unit=(u.hour, u.deg))\r\n    targetRA = targetcrd.ra.value\r\n    targetDEC = targetcrd.dec.value\r\n\r\n    # Querying for neighbors with 2MASS IRSA's fp_psc (point-source catalog)\r\n    info = Irsa.query_region(targetcrd, catalog='fp_psc', spatial='Cone',\r\n                             radius=rad * u.arcmin)\r\n\r\n    # Coordinates of all the stars in FOV, including target\r\n    allRA = info['ra'].data.data\r\n    allDEC = info['dec'].data.data\r\n\r\n    # Initiating a dictionary to hold all relevant star information\r\n    stars = {}\r\n    stars['RA'], stars['DEC'] = allRA, allDEC\r\n\r\n    #############################STEP 2#####################################\r\n    ########################################################################\r\n    sindRA = (targetRA - stars['RA']) * np.cos(targetDEC)\r\n    cosdRA = targetDEC - stars['DEC']\r\n    distance = np.sqrt(sindRA**2 + cosdRA**2)\r\n    if np.min(distance) > 1.0*(10**-4):\r\n        coords = crd.SkyCoord(ra=ra, dec=dec, unit=(u.hour, u.deg)).to_string('decimal')\r\n        ra, dec = coords.split(' ')[0], coords.split(' ')[1]\r\n        raise Exception('Unable to detect a source with coordinates [RA: {}, DEC: {}] within IRSA`s 2MASS Point-Source Catalog. Please enter different coordinates or contact the JWST help desk.'.format(str(ra), str(dec)))\r\n\r\n    targetIndex = np.argmin(distance)\r\n\r\n    # Restoring model parameters\r\n    modelParam = readsav(os.path.join(TRACES_PATH, 'NIRISS', 'modelsInfo.sav'),\r\n                         verbose=False)\r\n    models = modelParam['models']\r\n    modelPadX = modelParam['modelpadx']\r\n    modelPadY = modelParam['modelpady']\r\n    dimXmod = modelParam['dimxmod']\r\n    dimYmod = modelParam['dimymod']\r\n    jhMod = modelParam['jhmod']\r\n    hkMod = modelParam['hkmod']\r\n    teffMod = modelParam['teffmod']\r\n\r\n    #############################STEP 3#####################################\r\n    ########################################################################\r\n    # JHK bands of all stars in FOV, including target\r\n    Jmag = info['j_m'].data.data\r\n    Hmag = info['h_m'].data.data\r\n    Kmag = info['k_m'].data.data\r\n    # J-H band, H-K band. This will be used to derive the Teff\r\n    J_Hobs = Jmag - Hmag\r\n    H_Kobs = Hmag - Kmag\r\n\r\n    # Add any missing companion\r\n    if binComp != '':\r\n        bb = binComp[0] / 3600 / np.cos(allDEC[targetIndex] * deg2rad)\r\n        allRA = np.append(allRA, (allRA[targetIndex] + bb))\r\n        allDEC = np.append(allDEC, (allDEC[targetIndex] + binComp[1] / 3600))\r\n        Jmag = np.append(Jmag, binComp[2])\r\n        Hmag = np.append(Kmag, binComp[3])\r\n        Kmag = np.append(Kmag, binComp[4])\r\n        J_Hobs = Jmag - Hmag\r\n        H_Kobs = Hmag - Kmag\r\n\r\n    # Number of stars\r\n    nStars = stars['RA'].size\r\n\r\n    # Find/assign Teff of each star\r\n    starsT = np.empty(nStars)\r\n    for j in range(nStars):\r\n        color_separation = (J_Hobs[j] - jhMod)**2 + (H_Kobs[j] - hkMod)**2\r\n        min_separation_ind = np.argmin(color_separation)\r\n        starsT[j] = teffMod[min_separation_ind]\r\n\r\n    # Record keeping\r\n    stars['Temp'] = starsT\r\n    stars['Jmag'] = Jmag\r\n\r\n    #############################STEP 4#####################################\r\n    ########################################################################\r\n    # Calculate corresponding V2/V3 (TEL) coordinates for Sweetspot\r\n    v2targ, v3targ = aper.det_to_tel(xSweet, ySweet)\r\n\r\n    for V3PA in range(0, nPA, 1):\r\n        # Get APA from V3PA\r\n        APA = V3PA + add_to_v3pa\r\n        if APA > 360:\r\n            APA = APA-360\r\n        elif APA < 0:\r\n            APA = APA+360\r\n\r\n        print('Generating field at APA : {}'.format(str(APA)))\r\n\r\n        # Get target's attitude matrix for each Position Angle\r\n        attitude = rotations.attitude_matrix(v2targ, v3targ,\r\n                                             targetRA, targetDEC,\r\n                                             APA)\r\n\r\n        xdet, ydet = [], []\r\n        xsci, ysci = [], []\r\n        for starRA, starDEC in zip(stars['RA'], stars['DEC']):\r\n            # Get the TEL coordinates of each star w attitude matrix\r\n            V2, V3 = rotations.sky_to_tel(attitude, starRA, starDEC)\r\n            # Convert to arcsec and turn to a float\r\n            V2, V3 = V2.to(u.arcsec).value, V3.to(u.arcsec).value\r\n\r\n            XDET, YDET = aper.tel_to_det(V2, V3)\r\n            XSCI, YSCI = aper.det_to_sci(XDET, YDET)\r\n\r\n            xdet.append(XDET)\r\n            ydet.append(YDET)\r\n            xsci.append(XSCI)\r\n            ysci.append(YSCI)\r\n\r\n        # Record keeping\r\n        stars['xdet'], stars['ydet'] = np.array(xdet), np.array(ydet)\r\n        stars['xsci'], stars['ysci'] = np.array(xsci), np.array(ysci)\r\n\r\n        sci_targx, sci_targy = stars['xsci'][targetIndex],\\\r\n            stars['ysci'][targetIndex]\r\n    #############################STEP 5#####################################\r\n    ########################################################################\r\n        inFOV = []\r\n        for star in range(0, nStars):\r\n\r\n            x, y = stars['xdet'][star], stars['ydet'][star]\r\n            if (mincol < x) & (x < maxcol) & (minrow < y) & (y < maxrow):\r\n                inFOV.append(star)\r\n\r\n        inFOV = np.array(inFOV)\r\n\r\n    #############################STEP 6#####################################\r\n    ########################################################################\r\n        fitsFiles = glob.glob(os.path.join(TRACES_PATH, 'MIRI', 'LOW*.fits'))\r\n        fitsFiles = np.sort(fitsFiles)\r\n\r\n        for idx in inFOV:\r\n\r\n            sci_dx = round(sci_targx - stars['xsci'][idx])\r\n            sci_dy = round(sci_targy - stars['ysci'][idx])\r\n\r\n            temp = stars['Temp'][idx]\r\n\r\n            for file in fitsFiles:\r\n                if str(temp) in file:\r\n                    trace = fits.getdata(file)[0]\r\n\r\n            fluxscale = 10.0**(-0.4 * \\\r\n                               (stars['Jmag'][idx] - stars['Jmag'][targetIndex]))\r\n\r\n            # Padding array\r\n            pad_trace = np.pad(trace, pad_width=5000, mode='constant',\r\n                               constant_values=0)\r\n\r\n            # Determine the highest pixel value of trace\r\n            maxY, maxX = np.where(pad_trace == pad_trace.max())\r\n            peakY, peakX = maxY[0], maxX[0]\r\n\r\n            # Use relative distances (sci_dx, sci_dy) to find target\r\n            # xTarg,yTarg are essentially the \"sweetspot\" in the PADDED arr\r\n            xTarg = peakX + sci_dx\r\n            yTarg = peakY + sci_dy\r\n\r\n            # Use the (xTarg, yTarg) coordinates to slice out subarray\r\n            # remember X is columns, Y is rows\r\n            dimX0, dimX1 = xTarg - sci_targx, xTarg + subX - sci_targx\r\n            dimY0, dimY1 = yTarg - sci_targy, yTarg + subY - sci_targy\r\n\r\n            if dimX0 < 0:\r\n                dimX0 = 0\r\n                dimX1 = subX\r\n            if dimY0 < 0:\r\n                dimY0 = 0\r\n                dimY1 = subY\r\n\r\n            traceX, traceY = np.shape(pad_trace)[1], np.shape(pad_trace)[0]\r\n            if dimX1 > traceX:\r\n                dimX1 = traceX\r\n                dimX0 = traceX - subX\r\n            if dimY1 > traceY:\r\n                dimY1 = traceY\r\n                dimY0 = traceY - subY\r\n\r\n            if (dimX1 < 0) or (dimY1 < 0):\r\n                continue\r\n\r\n            # -1 because pySIAF is 1-indexed\r\n            mx0, mx1 = int(dimX0) - 1, int(dimX1) - 1\r\n            my0, my1 = int(dimY0) - 1, int(dimY1) - 1\r\n\r\n            # Fleshing out index 0 of the simulation cube (trace of target)\r\n            if (sci_dx == 0) & (sci_dy == 0):  # this is the target\r\n\r\n                tr = pad_trace[my0:my1, mx0:mx1] * fluxscale\r\n                trX, trY = np.shape(tr)[1], np.shape(tr)[0]\r\n\r\n                simuCube[0, 0:trY, 0:trX] = tr\r\n\r\n            # Fleshing out indexes 1-361 of the simulation cube\r\n            # (trace of neighboring stars at every position angle)\r\n            else:\r\n\r\n                tr = pad_trace[my0:my1, mx0:mx1] * fluxscale\r\n                trX, trY = np.shape(tr)[1], np.shape(tr)[0]\r\n                simuCube[V3PA + 1, 0:trY, 0:trX] += tr\r\n\r\n    return simuCube\r\n\r\n\r\ndef fieldSim(ra, dec, instrument, binComp='', testing=False):\r\n    \"\"\" Wraps ``sossFieldSim``, ``gtsFieldSim``, and ``lrsFieldSim`` together.\r\n    Produces a field simulation for a target using any instrument (NIRISS,\r\n    NIRCam, or MIRI).\r\n\r\n    Parameters\r\n    ----------\r\n    ra : float\r\n        The RA of the target.\r\n    dec : float\r\n        The Dec of the target.\r\n    instrument : str\r\n        The instrument the contamination is being calculated for.\r\n        Can either be (case-sensitive):\r\n        'NIRISS', 'NIRCam F322W2', 'NIRCam F444W', 'MIRI'\r\n    binComp : sequence\r\n        The parameters of a binary companion.\r\n    testing : bool\r\n        Shoud be ``True`` if running fieldSim for testing / troubleshooting\r\n        purposes. This will generate a matplotlib figure showing the target\r\n        FOV. The neighboring stars in this FOV will be included in the\r\n        contamination calculation (contamFig.py).\r\n\r\n    Returns\r\n    -------\r\n    simuCube : np.ndarray\r\n        The simulated data cube. Index 0 and 1 (axis=0) show the trace of\r\n        the target for orders 1 and 2 (respectively). Index 2-362 show the trace\r\n        of the target at every position angle (PA) of the instrument.\r\n    plt.plot() : matplotlib object\r\n        A plot. Only if `testing` parameter is set to True.\r\n    \"\"\"\r\n\r\n    # Calling the variables which depend on what instrument you use\r\n    if instrument == 'NIRISS':\r\n        simuCube = sossFieldSim(ra, dec, binComp)\r\n\r\n    elif instrument == 'NIRCam F444W':\r\n        simuCube = gtsFieldSim(ra, dec, 'F444W', binComp)\r\n\r\n    elif instrument == 'NIRCam F322W2':\r\n        simuCube = gtsFieldSim(ra, dec, 'F322W2', binComp)\r\n\r\n    elif instrument == 'MIRI':\r\n        simuCube = lrsFieldSim(ra, dec, binComp)\r\n\r\n    return simuCube\r\n\r\n\r\nif __name__ == '__main__':\r\n    ra, dec = \"04 25 29.0162\", \"-30 36 01.603\"  # Wasp 79\r\n    #sossFieldSim(ra, dec)\r\n    if EXOCTK_DATA:\r\n        fieldSim(ra, dec, instrument='NIRISS')\r\n", "meta": {"hexsha": "82ad2c43d3d4513b666c7a53ed6a2ce96f8162f9", "size": 29949, "ext": "py", "lang": "Python", "max_stars_repo_path": "exoctk/contam_visibility/field_simulator.py", "max_stars_repo_name": "jaymedina/ExoCTK", "max_stars_repo_head_hexsha": "1591830b9ec5194a4e60db17a168a7f231580277", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exoctk/contam_visibility/field_simulator.py", "max_issues_repo_name": "jaymedina/ExoCTK", "max_issues_repo_head_hexsha": "1591830b9ec5194a4e60db17a168a7f231580277", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exoctk/contam_visibility/field_simulator.py", "max_forks_repo_name": "jaymedina/ExoCTK", "max_forks_repo_head_hexsha": "1591830b9ec5194a4e60db17a168a7f231580277", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-05T17:07:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T17:07:46.000Z", "avg_line_length": 38.1515923567, "max_line_length": 222, "alphanum_fraction": 0.5196166817, "include": true, "reason": "import numpy,from scipy,import astropy,from astropy", "num_tokens": 8187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3415825128436339, "lm_q1q2_score": 0.18012210311996135}}
{"text": "#!/usr/bin/env python\n\nimport itertools as itt\nimport logging\nimport os\nfrom datetime import datetime\nfrom getpass import getuser\n\nimport numpy as np\nimport pandas as pd\n\nfrom .generate import get_percentile_diff, get_inducible_pairs\nfrom .. import hgnc, mi, up, snp as rs\nfrom ..struct.hetnet import HetNet, encode_color_path\n\nlog = logging.getLogger()\n\nCP1 = ('p', 'm')\nCP1_TERMINAL = ('p', ('m', ()))\nCP1_STR = encode_color_path(CP1_TERMINAL, color_path_type='terminal')\nCP2 = ('p', 'p', ('g', (('regulated', 'T'),)))\nCP2_STR = encode_color_path(CP2, color_path_type='terminal')\n\n\ndef convert_simple_to_terminal(cp):\n    *head, tail = cp\n    tail = (tail, ())\n\n    if isinstance(cp, list):\n        return list(head) + [tail]\n\n    return tuple(head) + (tail,)\n\n\ndef generate_toy(seed=None):\n    np.random.seed(seed)\n    h = HetNet({\n        \"g\": {\n            \"regulated\": [\"T\", \"F\"]  # significant regulation\n        },\n        \"p\": {\n        },\n        \"m\": {\n        },\n        \"s\": {\n        }\n    })\n\n    n_genes = 426\n    n_proteins = 275\n    n_mirnas = 16\n    n_snps = 14\n\n    n_mirna_encoding_genes = 8\n    n_protein_encoding_genes = 275\n\n    n_ppis = 292\n    n_mtis = 51\n\n    # ??? not sure about numbers\n    n_regulated = 25\n    n_coexprs = 400\n\n    regulated = np.random.choice(np.arange(n_genes), size=n_regulated, replace=False)\n    genes = {}\n    for i in range(n_genes):\n        gene = hgnc(i)\n        genes[i] = gene\n        h.add_node(gene, dict(color='g', annotations={'regulated': (\"T\" if i in regulated else \"F\")}))\n\n    protein_encoding_genes = sorted(genes.values())[:n_protein_encoding_genes]\n    proteins = {}\n    for i, gene in zip(range(n_proteins), protein_encoding_genes):\n        protein = up(i)\n        proteins[i] = protein\n        h.add_node(protein, dict(color='p', annotations={}))\n        h.add_edge(gene, protein)\n\n    mirna_encoding_genes = list(\n        np.random.choice(list(set(genes.values()) - set(protein_encoding_genes)), size=n_mirna_encoding_genes,\n                         replace=False))\n    mirnas = {}\n    for i, gene in zip(range(n_mirnas), 2 * mirna_encoding_genes):\n        mirna = mi(i)\n        mirnas[i] = mirna\n        h.add_node(mirna, dict(color='m', annotations={}))\n        h.add_edge(gene, mirna)\n\n    h.mirna_encoding = mirna_encoding_genes\n\n    mutations = np.random.choice(list(set(genes.values()) - set(protein_encoding_genes) - set(mirna_encoding_genes)),\n                                 size=n_snps, replace=False)\n    snps = {}\n    for i, gene in zip(range(n_snps), mutations):\n        snp = rs(i)\n        snps[i] = snp\n        h.add_node(snp, dict(color='s', annotations={}))\n        h.add_edge(gene, snp)\n\n    pp = list(itt.combinations(proteins, 2))\n    for i in np.random.choice(len(pp), size=n_ppis, replace=False):\n        a, b = pp[i]\n        h.add_edge(proteins[a], proteins[b])\n\n    gg = list(itt.combinations(genes, 2))\n    for i in np.random.choice(len(gg), size=n_coexprs, replace=False):\n        a, b = gg[i]\n        h.add_edge(genes[a], genes[b])\n\n    mp = list(itt.product(proteins, mirnas))\n    for i in np.random.choice(len(mp), size=n_mtis, replace=False):\n        a, b = mp[i]\n        h.add_edge(proteins[a], mirnas[b])\n\n    h.graph['generation_manifest'] = {\n        'user': getuser(),\n        'generation_time': str(datetime.now()),\n        'np_random_seed': seed,\n        'protein_encoding': protein_encoding_genes\n    }\n\n    return h\n\n\ndef induce_toy(graph, target_nodes, upper=100, lower=90, loc_coef=1.1, scale_coef=1.2, seed=None):\n    \"\"\"\n    Generate network pertaining to actual biology, and induce 2 features over protein-coding genes:\n        - protein-mirna\n        - protein-protein-regulated_gene\n\n    :param graph: the network to induce\n    :param target_nodes: the nodes to induce in the network\n    :param upper: the upper percentile to calculate for the color paths\n    :param lower: the lower percentile to calculate for the color paths\n    :param loc_coef: the factor to multiply the upper percentile for induction for the mean of random gaussian sampling\n    :param scale_coef: the factor to multiply the upper-lower percentile difference for the standard deviation of random\n                        gaussian sampling\n    :param seed: seed for numpy random number generator\n    :return:\n    \"\"\"\n\n    np.random.seed(seed)\n    pairs = []\n\n    # TODO factor out induction parameters\n    p100a, p98a, pt2a = get_percentile_diff(graph, CP1, upper, lower, color_path_type='simple')\n    log.debug(\n        'CP {} -> {}%: {}, {}%: {}, D{}%: {}'.format(encode_color_path(CP1, color_path_type=\"simple\"), upper, p100a,\n                                                     lower, p98a, upper - lower, pt2a))\n\n    p100b, p98b, pt2b = get_percentile_diff(graph, CP2, upper, lower, color_path_type='terminal')\n    log.debug(\n        'CP {} -> {}%: {}, {}%: {}, D{}%: {}'.format(encode_color_path(CP2, color_path_type=\"terminal\"), upper, p100b,\n                                                     lower, p98b, upper - lower, pt2b))\n\n    for node in target_nodes:\n        for edge in get_inducible_pairs(graph, node, CP1,\n                                        int(np.random.normal(loc=(loc_coef * p100a), scale=(scale_coef * pt2a))),\n                                        color_path_type='simple'):\n            pairs.append(edge)\n        for edge in get_inducible_pairs(graph, node, CP2,\n                                        int(np.random.normal(loc=(loc_coef * p100b), scale=(scale_coef * pt2b))),\n                                        color_path_type='terminal'):\n            pairs.append(edge)\n\n    \"\"\"\n    params = [\n        (CP1, upper, lower, 1.1, 1.2, 'simple'),\n        (CP2, upper, lower, 1.1, 1.2, 'terminal')\n    ]\n    pairs = []\n    for cp, up, lo, lc, sc, cpt in params:\n        p100, p98, pt2 = get_percentile_diff(graph, cp, up, lo, color_path_type=cpt)\n        for node in target_nodes:\n            ne = int(np.random.normal(loc=(lc * p100), scale=(sc * pt2)))\n            pairs.extend(get_inducible_pairs(graph, node, cp, ne, color_path_type=cpt))\n    \"\"\"\n\n    for a, b in set(pairs):\n        graph.add_edge(a, b)\n\n    graph.graph['induction_manifest'] = {\n        'user': getuser(),\n        'induction_time': str(datetime.now()),\n        'induced': sorted(target_nodes),\n        'upper': upper,\n        'lower': lower,\n        'loc_coef': loc_coef,\n        'scale_coef': scale_coef,\n        'np_random_seed': seed\n    }\n\n    return graph\n\n\ndef main(directory, percent=0.8, seed=None):\n    \"\"\"\n    :param directory: output directory\n    :param percent: if given, outputs a training and test manifest\n    :param seed: seed for numpy random number generator\n    \"\"\"\n\n    np.random.seed(seed)\n\n    h = generate_toy()\n    n_induce = int(0.5 + 7 / percent)\n    target_nodes = np.random.choice(h.graph['generation_manifest']['protein_encoding'], size=n_induce, replace=False)\n    hn = induce_toy(h, target_nodes)\n    hn.to_resource(directory)\n\n    induced = hn.graph['induction_manifest']['induced']\n    nodes = sorted(hn.graph['generation_manifest']['protein_encoding'])\n\n    full_induction_manifest = pd.DataFrame([node in induced for node in nodes], index=nodes, columns=['induced'])\n    full_induction_manifest.to_csv(os.path.join(directory, 'full_induce_manifest.csv'))\n\n    not_induced = list(set(nodes) - set(induced))\n    n_induced = len(induced)\n    n_not_induced = len(not_induced)\n\n    np.random.shuffle(induced)\n    np.random.shuffle(not_induced)\n\n    head_induced = induced[:int(percent * n_induced)]\n    tail_induced = induced[int(percent * n_induced):]\n\n    head_not_induced = not_induced[:int(percent * n_not_induced)]\n    tail_not_induced = not_induced[int(percent * n_not_induced):]\n\n    head = sorted(head_induced) + sorted(head_not_induced)\n    tail = sorted(tail_induced) + sorted(tail_not_induced)\n\n    full_induction_manifest.loc[head].to_csv(os.path.join(directory, 'training_induce_manifest.csv'))\n    full_induction_manifest.loc[tail].to_csv(os.path.join(directory, 'test_induce_manifest.csv'))\n", "meta": {"hexsha": "5c3dd9f6b9aa84c22781608c979e3a3cb95f53fd", "size": 8037, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/hetnetana/generation/generate_toy.py", "max_stars_repo_name": "cthoyt/hetnetana", "max_stars_repo_head_hexsha": "de7dc74962e110c4303f6d4549989db8e82be69a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/hetnetana/generation/generate_toy.py", "max_issues_repo_name": "cthoyt/hetnetana", "max_issues_repo_head_hexsha": "de7dc74962e110c4303f6d4549989db8e82be69a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-09-02T17:27:40.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-02T17:27:40.000Z", "max_forks_repo_path": "src/hetnetana/generation/generate_toy.py", "max_forks_repo_name": "cthoyt/hetnetana", "max_forks_repo_head_hexsha": "de7dc74962e110c4303f6d4549989db8e82be69a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2, "max_line_length": 120, "alphanum_fraction": 0.6197586164, "include": true, "reason": "import numpy", "num_tokens": 2075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.18012209605111626}}
{"text": "# coding: utf-8\n# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\n\"\"\"\nThis module defines classes to represent crystal orbital Hamilton\npopulations (COHP) and integrated COHP (ICOHP), but can also be used\nfor crystal orbital overlap populations (COOP).\n\"\"\"\n\nimport warnings\nimport re\nimport sys\n\nimport numpy as np\n\nfrom monty.json import MSONable\n\nfrom pymatgen.electronic_structure.core import Spin, Orbital\nfrom pymatgen.core.sites import PeriodicSite\nfrom pymatgen.core.structure import Structure\nfrom pymatgen.io.lmto import LMTOCopl\nfrom pymatgen.io.lobster import Cohpcar\nfrom pymatgen.util.num import round_to_sigfigs\nfrom pymatgen.util.coord import get_linear_interpolated_value\n\n__author__ = \"Marco Esters, Janine George\"\n__copyright__ = \"Copyright 2017, The Materials Project\"\n__version__ = \"0.2\"\n__maintainer__ = \"Marco Esters, Janine George\"\n__email__ = \"esters@uoregon.edu, janine.george@uclouvain.be\"\n__date__ = \"Dec 13, 2017\"\n\n\nclass Cohp(MSONable):\n    \"\"\"\n    Basic COHP object.\n    \"\"\"\n\n    def __init__(self, efermi, energies, cohp, are_coops=False, icohp=None):\n        \"\"\"\n        Args:\n            are_coops: Indicates whether this object describes COHPs or COOPs.\n            efermi: Fermi energy.\n            energies: A sequence of energies.\n            cohp ({Spin: np.array}): representing the COHP for each spin.\n            icohp ({Spin: np.array}): representing the ICOHP for each spin.\n        \"\"\"\n        self.are_coops = are_coops\n        self.efermi = efermi\n        self.energies = np.array(energies)\n        self.cohp = cohp\n        self.icohp = icohp\n\n    def __repr__(self):\n        return self.__str__()\n\n    def __str__(self):\n        \"\"\"\n        Returns a string that can be easily plotted (e.g. using gnuplot).\n        \"\"\"\n        cohpstring = \"COOP\" if self.are_coops else \"COHP\"\n        header = [\"Energy\", cohpstring + \"Up\"]\n        data = [self.energies, self.cohp[Spin.up]]\n        if Spin.down in self.cohp:\n            header.append(cohpstring + \"Down\")\n            data.append(self.cohp[Spin.down])\n        if self.icohp:\n            header.append(\"I\" + cohpstring + \"Up\")\n            data.append(self.icohp[Spin.up])\n            if Spin.down in self.cohp:\n                header.append(\"I\" + cohpstring + \"Down\")\n                data.append(self.icohp[Spin.down])\n        formatheader = \"#\" + \" \".join([\"{:15s}\" for __ in header])\n        formatdata = \" \".join([\"{:.5f}\" for __ in header])\n        stringarray = [formatheader.format(*header)]\n        for i, __ in enumerate(self.energies):\n            stringarray.append(formatdata.format(*[d[i] for d in data]))\n        return \"\\n\".join(stringarray)\n\n    def as_dict(self):\n        \"\"\"\n        Json-serializable dict representation of COHP.\n        \"\"\"\n        d = {\"@module\": self.__class__.__module__,\n             \"@class\": self.__class__.__name__,\n             \"are_coops\": self.are_coops,\n             \"efermi\": self.efermi,\n             \"energies\": self.energies.tolist(),\n             \"COHP\": {str(spin): pops.tolist()\n                      for spin, pops in self.cohp.items()}}\n        if self.icohp:\n            d[\"ICOHP\"] = {str(spin): pops.tolist()\n                          for spin, pops in self.icohp.items()}\n        return d\n\n    def get_cohp(self, spin=None, integrated=False):\n        \"\"\"\n        Returns the COHP or ICOHP for a particular spin.\n\n        Args:\n            spin: Spin. Can be parsed as spin object, integer (-1/1)\n                or str (\"up\"/\"down\")\n            integrated: Return COHP (False) or ICOHP (True)\n\n        Returns:\n            Returns the CHOP or ICOHP for the input spin. If Spin is\n            None and both spins are present, both spins will be returned\n            as a dictionary.\n        \"\"\"\n        if not integrated:\n            populations = self.cohp\n        else:\n            populations = self.icohp\n\n        if populations is None:\n            return None\n        if spin is None:\n            return populations\n        if isinstance(spin, int):\n            spin = Spin(spin)\n        elif isinstance(spin, str):\n            s = {\"up\": 1, \"down\": -1}[spin.lower()]\n            spin = Spin(s)\n        return {spin: populations[spin]}\n\n    def get_icohp(self, spin=None):\n        \"\"\"\n        Convenient alternative to get the ICOHP for a particular spin.\n        \"\"\"\n        return self.get_cohp(spin=spin, integrated=True)\n\n    def get_interpolated_value(self, energy, integrated=False):\n        \"\"\"\n        Returns the COHP for a particular energy.\n\n        Args:\n            energy: Energy to return the COHP value for.\n        \"\"\"\n        inter = {}\n        for spin in self.cohp:\n            if not integrated:\n                inter[spin] = get_linear_interpolated_value(self.energies,\n                                                            self.cohp[spin],\n                                                            energy)\n            elif self.icohp is not None:\n                inter[spin] = get_linear_interpolated_value(self.energies,\n                                                            self.icohp[spin],\n                                                            energy)\n            else:\n                raise ValueError(\"ICOHP is empty.\")\n        return inter\n\n    def has_antibnd_states_below_efermi(self, spin=None, limit=0.01):\n        \"\"\"\n        Returns dict indicating if there are antibonding states below the Fermi level depending on the spin\n            spin: Spin\n            limit: -COHP smaller -limit will be considered.\n\n        \"\"\"\n        warnings.warn(\"This method has not been tested on many examples. Check the parameter limit, pls!\")\n\n        populations = self.cohp\n        number_energies_below_efermi = len([x for x in self.energies if x <= self.efermi])\n\n        if populations is None:\n            return None\n        if spin is None:\n            dict_to_return = {}\n            for sp, cohpvalues in populations.items():\n                if (max(cohpvalues[0:number_energies_below_efermi])) > limit:\n                    dict_to_return[sp] = True\n                else:\n                    dict_to_return[sp] = False\n        else:\n            dict_to_return = {}\n            if isinstance(spin, int):\n                spin = Spin(spin)\n            elif isinstance(spin, str):\n                s = {\"up\": 1, \"down\": -1}[spin.lower()]\n                spin = Spin(s)\n            if (max(populations[spin][0:number_energies_below_efermi])) > limit:\n                dict_to_return[spin] = True\n            else:\n                dict_to_return[spin] = False\n\n        return dict_to_return\n\n    @classmethod\n    def from_dict(cls, d):\n        \"\"\"\n        Returns a COHP object from a dict representation of the COHP.\n\n        \"\"\"\n        if \"ICOHP\" in d:\n            icohp = {Spin(int(key)): np.array(val)\n                     for key, val in d[\"ICOHP\"].items()}\n        else:\n            icohp = None\n        return Cohp(d[\"efermi\"], d[\"energies\"],\n                    {Spin(int(key)): np.array(val)\n                     for key, val in d[\"COHP\"].items()},\n                    icohp=icohp, are_coops=d[\"are_coops\"])\n\n\nclass CompleteCohp(Cohp):\n    \"\"\"\n    A wrapper class that defines an average COHP, and individual COHPs.\n\n    .. attribute: are_coops\n\n         Indicates whether the object is of COOPs or COHPs.\n\n    .. attribute: efermi\n\n         Fermi energy\n\n    .. attribute: energies\n\n         Sequence of energies\n\n    .. attribute: structure\n\n         Structure associated with the COHPs.\n\n    .. attribute: cohp, icohp\n\n         The average COHP/ICOHP.\n\n    .. attribute: all_cohps\n\n         A dict of COHPs for individual bonds of the form {label: COHP}\n\n    .. attribute: orb_res_cohp\n\n        Orbital-resolved COHPs.\n    \"\"\"\n\n    def __init__(self, structure, avg_cohp, cohp_dict, bonds=None,\n                 are_coops=False, orb_res_cohp=None):\n        \"\"\"\n        Args:\n            structure: Structure assosciated with this COHP.\n            avg_cohp: The average cohp as a COHP object.\n            cohps: A dict of COHP objects for individual bonds of the form\n                {label: COHP}\n            bonds: A dict containing information on the bonds of the form\n                {label: {key: val}}. The key-val pair can be any information\n                the user wants to put in, but typically contains the sites,\n                the bond length, and the number of bonds. If nothing is\n                supplied, it will default to an empty dict.\n            are_coops: indicates whether the Cohp objects are COHPs or COOPs.\n                Defauls to False for COHPs.\n            orb_res_cohp: Orbital-resolved COHPs.\n        \"\"\"\n        super().__init__(avg_cohp.efermi, avg_cohp.energies, avg_cohp.cohp,\n                         are_coops=are_coops, icohp=avg_cohp.icohp)\n        self.structure = structure\n        self.are_coops = are_coops\n        self.all_cohps = cohp_dict\n        self.orb_res_cohp = orb_res_cohp\n        if bonds is None:\n            self.bonds = {label: {} for label in self.all_cohps.keys()}\n        else:\n            self.bonds = bonds\n\n    def __str__(self):\n        if self.are_coops:\n            return \"Complete COOPs for \" + str(self.structure)\n        return \"Complete COHPs for \" + str(self.structure)\n\n    def as_dict(self):\n        \"\"\"\n        Json-serializable dict representation of CompleteCohp.\n        \"\"\"\n        d = {\"@module\": self.__class__.__module__,\n             \"@class\": self.__class__.__name__,\n             \"are_coops\": self.are_coops,\n             \"efermi\": self.efermi,\n             \"structure\": self.structure.as_dict(),\n             \"energies\": self.energies.tolist(),\n             \"COHP\": {\"average\": {str(spin): pops.tolist()\n                                  for spin, pops in\n                                  self.cohp.items()}}}\n\n        if self.icohp is not None:\n            d[\"ICOHP\"] = {\"average\": {str(spin): pops.tolist()\n                                      for spin, pops in\n                                      self.icohp.items()}}\n\n        for label in self.all_cohps.keys():\n            d[\"COHP\"].update({label: {str(spin): pops.tolist()\n                                      for spin, pops in\n                                      self.all_cohps[label].cohp.items()}})\n            if self.all_cohps[label].icohp is not None:\n                if \"ICOHP\" not in d.keys():\n                    d[\"ICOHP\"] = {label: {str(spin): pops.tolist()\n                                          for spin, pops in\n                                          self.all_cohps[label].icohp.items()}}\n                else:\n                    d[\"ICOHP\"].update({label: {str(spin): pops.tolist()\n                                               for spin, pops in\n                                               self.all_cohps[label].icohp.items()}})\n        if False in [bond_dict == {} for bond_dict in self.bonds.values()]:\n            d[\"bonds\"] = {bond: {\"length\": self.bonds[bond][\"length\"],\n                                 \"sites\": [site.as_dict() for site\n                                           in self.bonds[bond][\"sites\"]]}\n                          for bond in self.bonds}\n        if self.orb_res_cohp:\n            orb_dict = {}\n            for label in self.orb_res_cohp:\n                orb_dict[label] = {}\n                for orbs in self.orb_res_cohp[label]:\n                    cohp = {str(spin): pops.tolist() for spin, pops in\n                            self.orb_res_cohp[label][orbs][\"COHP\"].items()}\n                    orb_dict[label][orbs] = {\"COHP\": cohp}\n                    icohp = {str(spin): pops.tolist() for spin, pops in\n                             self.orb_res_cohp[label][orbs][\"ICOHP\"].items()}\n                    orb_dict[label][orbs][\"ICOHP\"] = icohp\n                    orbitals = [[orb[0], orb[1].name] for orb in\n                                self.orb_res_cohp[label][orbs][\"orbitals\"]]\n                    orb_dict[label][orbs][\"orbitals\"] = orbitals\n            d[\"orb_res_cohp\"] = orb_dict\n\n        return d\n\n    def get_cohp_by_label(self, label):\n        \"\"\"\n        Get specific COHP object.\n\n        Args:\n            label: string (for newer Lobster versions: a number)\n\n        Returns:\n            Returns the COHP object to simplify plotting\n        \"\"\"\n        if label.lower() == \"average\":\n            return Cohp(efermi=self.efermi, energies=self.energies,\n                        cohp=self.cohp, are_coops=self.are_coops, icohp=self.icohp)\n        return Cohp(efermi=self.efermi, energies=self.energies,\n                    cohp=self.all_cohps[label].get_cohp(spin=None, integrated=False),\n                    are_coops=self.are_coops,\n                    icohp=self.all_cohps[label].get_icohp(spin=None))\n\n    def get_summed_cohp_by_label_list(self, label_list, divisor=1):\n        \"\"\"\n        Returns a COHP object that includes a summed COHP divided by divisor\n\n        Args:\n            label_list: list of labels for the COHP that should be included in the summed cohp\n            divisor: float/int, the summed cohp will be divided by this divisor\n        Returns:\n            Returns a COHP object including a summed COHP\n        \"\"\"\n        # check if cohps are spinpolarized or not\n        first_cohpobject = self.get_cohp_by_label(label_list[0])\n        summed_cohp = first_cohpobject.cohp.copy()\n        summed_icohp = first_cohpobject.icohp.copy()\n        for label in label_list[1:]:\n            cohp_here = self.get_cohp_by_label(label)\n            summed_cohp[Spin.up] = np.sum([summed_cohp[Spin.up], cohp_here.cohp[Spin.up]], axis=0)\n            if Spin.down in summed_cohp:\n                summed_cohp[Spin.down] = np.sum([summed_cohp[Spin.down], cohp_here.cohp[Spin.down]], axis=0)\n            summed_icohp[Spin.up] = np.sum([summed_icohp[Spin.up], cohp_here.icohp[Spin.up]], axis=0)\n            if Spin.down in summed_icohp:\n                summed_icohp[Spin.down] = np.sum([summed_icohp[Spin.down], cohp_here.icohp[Spin.down]], axis=0)\n\n        divided_cohp = {}\n        divided_icohp = {}\n        divided_cohp[Spin.up] = np.divide(summed_cohp[Spin.up], divisor)\n        divided_icohp[Spin.up] = np.divide(summed_icohp[Spin.up], divisor)\n        if Spin.down in summed_cohp:\n            divided_cohp[Spin.down] = np.divide(summed_cohp[Spin.down], divisor)\n            divided_icohp[Spin.down] = np.divide(summed_icohp[Spin.down], divisor)\n\n        return Cohp(efermi=first_cohpobject.efermi, energies=first_cohpobject.energies, cohp=divided_cohp,\n                    are_coops=first_cohpobject.are_coops,\n                    icohp=divided_icohp)\n\n    def get_summed_cohp_by_label_and_orbital_list(self, label_list, orbital_list, divisor=1):\n        \"\"\"\n        Returns a COHP object that includes a summed COHP divided by divisor\n\n        Args:\n            label_list: list of labels for the COHP that should be included in the summed cohp\n            orbital_list: list of orbitals for the COHPs that should be included in the summed cohp (same order as\n                label_list)\n            divisor: float/int, the summed cohp will be divided by this divisor\n        Returns:\n            Returns a COHP object including a summed COHP\n        \"\"\"\n        # check length of label_list and orbital_list:\n        if not len(label_list) == len(orbital_list):\n            raise ValueError(\"label_list and orbital_list don't have the same length!\")\n        # check if cohps are spinpolarized or not\n        first_cohpobject = self.get_orbital_resolved_cohp(label_list[0], orbital_list[0])\n        summed_cohp = first_cohpobject.cohp.copy()\n        summed_icohp = first_cohpobject.icohp.copy()\n        for ilabel, label in enumerate(label_list[1:], 1):\n            cohp_here = self.get_orbital_resolved_cohp(label, orbital_list[ilabel])\n            summed_cohp[Spin.up] = np.sum([summed_cohp[Spin.up], cohp_here.cohp.copy()[Spin.up]], axis=0)\n            if Spin.down in summed_cohp:\n                summed_cohp[Spin.down] = np.sum([summed_cohp[Spin.down], cohp_here.cohp.copy()[Spin.down]], axis=0)\n            summed_icohp[Spin.up] = np.sum([summed_icohp[Spin.up], cohp_here.icohp.copy()[Spin.up]], axis=0)\n            if Spin.down in summed_icohp:\n                summed_icohp[Spin.down] = np.sum([summed_icohp[Spin.down], cohp_here.icohp.copy()[Spin.down]], axis=0)\n\n        divided_cohp = {}\n        divided_icohp = {}\n        divided_cohp[Spin.up] = np.divide(summed_cohp[Spin.up], divisor)\n        divided_icohp[Spin.up] = np.divide(summed_icohp[Spin.up], divisor)\n        if Spin.down in summed_cohp:\n            divided_cohp[Spin.down] = np.divide(summed_cohp[Spin.down], divisor)\n            divided_icohp[Spin.down] = np.divide(summed_icohp[Spin.down], divisor)\n\n        return Cohp(efermi=first_cohpobject.efermi, energies=first_cohpobject.energies, cohp=divided_cohp,\n                    are_coops=first_cohpobject.are_coops,\n                    icohp=divided_icohp)\n\n    def get_orbital_resolved_cohp(self, label, orbitals):\n        \"\"\"\n        Get orbital-resolved COHP.\n\n        Args:\n            label: bond label (Lobster: labels as in ICOHPLIST/ICOOPLIST.lobster).\n\n            orbitals: The orbitals as a label, or list or tuple of the form\n                [(n1, orbital1), (n2, orbital2)]. Orbitals can either be str,\n                int, or Orbital.\n\n        Returns:\n            A Cohp object if CompleteCohp contains orbital-resolved cohp,\n            or None if it doesn't.\n\n        Note: It currently assumes that orbitals are str if they aren't the\n            other valid types. This is not ideal, but the easiest way to\n            avoid unicode issues between python 2 and python 3.\n        \"\"\"\n        if self.orb_res_cohp is None:\n            return None\n        if isinstance(orbitals, (list, tuple)):\n            cohp_orbs = [d[\"orbitals\"] for d in\n                         self.orb_res_cohp[label].values()]\n            orbs = []\n            for orbital in orbitals:\n                if isinstance(orbital[1], int):\n                    orbs.append(tuple((orbital[0], Orbital(orbital[1]))))\n                elif isinstance(orbital[1], Orbital):\n                    orbs.append(tuple((orbital[0], orbital[1])))\n                elif isinstance(orbital[1], str):\n                    orbs.append(tuple((orbital[0], Orbital[orbital[1]])))\n                else:\n                    raise TypeError(\"Orbital must be str, int, or Orbital.\")\n            orb_index = cohp_orbs.index(orbs)\n            orb_label = list(self.orb_res_cohp[label].keys())[orb_index]\n        elif isinstance(orbitals, str):\n            orb_label = orbitals\n        else:\n            raise TypeError(\"Orbitals must be str, list, or tuple.\")\n        try:\n            icohp = self.orb_res_cohp[label][orb_label][\"ICOHP\"]\n        except KeyError:\n            icohp = None\n        return Cohp(self.efermi, self.energies,\n                    self.orb_res_cohp[label][orb_label][\"COHP\"],\n                    icohp=icohp, are_coops=self.are_coops)\n\n    @classmethod\n    def from_dict(cls, d):\n        \"\"\"\n        Returns CompleteCohp object from dict representation.\n        \"\"\"\n        cohp_dict = {}\n        efermi = d[\"efermi\"]\n        energies = d[\"energies\"]\n        structure = Structure.from_dict(d[\"structure\"])\n        if \"bonds\" in d.keys():\n            bonds = {bond: {\"length\": d[\"bonds\"][bond][\"length\"],\n                            \"sites\": tuple(PeriodicSite.from_dict(site)\n                                           for site in d[\"bonds\"][bond][\"sites\"])}\n                     for bond in d[\"bonds\"]}\n        else:\n            bonds = None\n        for label in d[\"COHP\"]:\n            cohp = {Spin(int(spin)): np.array(d[\"COHP\"][label][spin])\n                    for spin in d[\"COHP\"][label]}\n            try:\n                icohp = {Spin(int(spin)): np.array(d[\"ICOHP\"][label][spin])\n                         for spin in d[\"ICOHP\"][label]}\n            except KeyError:\n                icohp = None\n            if label == \"average\":\n                avg_cohp = Cohp(efermi, energies, cohp, icohp=icohp)\n            else:\n                cohp_dict[label] = Cohp(efermi, energies, cohp, icohp=icohp)\n\n        if \"orb_res_cohp\" in d.keys():\n            orb_cohp = {}\n            for label in d[\"orb_res_cohp\"]:\n                orb_cohp[label] = {}\n                for orb in d[\"orb_res_cohp\"][label]:\n                    cohp = {Spin(int(s)): np.array(d[\"orb_res_cohp\"][label][orb][\"COHP\"][s], dtype=float)\n                            for s in d[\"orb_res_cohp\"][label][orb][\"COHP\"]}\n                    try:\n                        icohp = {Spin(int(s)): np.array(d[\"orb_res_cohp\"][label][orb][\"ICOHP\"][s], dtype=float)\n                                 for s in d[\"orb_res_cohp\"][label][orb][\"ICOHP\"]}\n                    except KeyError:\n                        icohp = None\n                    orbitals = [tuple((int(o[0]), Orbital[o[1]])) for o in\n                                d[\"orb_res_cohp\"][label][orb][\"orbitals\"]]\n                    orb_cohp[label][orb] = {\"COHP\": cohp, \"ICOHP\": icohp,\n                                            \"orbitals\": orbitals}\n                # If no total COHPs are present, calculate the total\n                # COHPs from the single-orbital populations. Total COHPs\n                # may not be present when the cohpgenerator keyword is used\n                # in LOBSTER versions 2.2.0 and earlier.\n                if label not in d[\"COHP\"] or d[\"COHP\"][label] is None:\n                    cohp = {Spin.up: np.sum(np.array(\n                        [orb_cohp[label][orb][\"COHP\"][Spin.up]\n                         for orb in orb_cohp[label]]), axis=0)}\n                    try:\n                        cohp[Spin.down] = np.sum(np.array([orb_cohp[label][orb][\"COHP\"][Spin.down]\n                                                           for orb in orb_cohp[label]]), axis=0)\n                    except KeyError:\n                        pass\n\n                orb_res_icohp = None in [orb_cohp[label][orb][\"ICOHP\"] for orb in orb_cohp[label]]\n                if (label not in d[\"ICOHP\"] or d[\"ICOHP\"][label] is None) and orb_res_icohp:\n                    icohp = {Spin.up: np.sum(np.array([orb_cohp[label][orb][\"ICOHP\"][Spin.up]\n                                                       for orb in orb_cohp[label]]), axis=0)}\n                    try:\n                        icohp[Spin.down] = np.sum(np.array([orb_cohp[label][orb][\"ICOHP\"][Spin.down]\n                                                            for orb in orb_cohp[label]]), axis=0)\n                    except KeyError:\n                        pass\n        else:\n            orb_cohp = None\n\n        if \"average\" not in d[\"COHP\"].keys():\n            # calculate average\n            cohp = np.array([np.array(c)\n                             for c in d[\"COHP\"].values()]).mean(axis=0)\n            try:\n                icohp = np.array([np.array(c)\n                                  for c in d[\"ICOHP\"].values()]).mean(axis=0)\n            except KeyError:\n                icohp = None\n            avg_cohp = Cohp(efermi, energies, cohp, icohp=icohp)\n\n        return CompleteCohp(structure, avg_cohp, cohp_dict, bonds=bonds,\n                            are_coops=d[\"are_coops\"], orb_res_cohp=orb_cohp)\n\n    @classmethod\n    def from_file(cls, fmt, filename=None,\n                  structure_file=None, are_coops=False):\n        \"\"\"\n        Creates a CompleteCohp object from an output file of a COHP\n        calculation. Valid formats are either LMTO (for the Stuttgart\n        LMTO-ASA code) or LOBSTER (for the LOBSTER code).\n\n        Args:\n            cohp_file: Name of the COHP output file. Defaults to COPL\n                for LMTO and COHPCAR.lobster/COOPCAR.lobster for LOBSTER.\n\n            are_coops: Indicates whether the populations are COOPs or\n                COHPs. Defaults to False for COHPs.\n\n            fmt: A string for the code that was used to calculate\n                the COHPs so that the output file can be handled\n                correctly. Can take the values \"LMTO\" or \"LOBSTER\".\n\n            structure_file: Name of the file containing the structure.\n                If no file name is given, use CTRL for LMTO and POSCAR\n                for LOBSTER.\n\n        Returns:\n            A CompleteCohp object.\n        \"\"\"\n        fmt = fmt.upper()\n        if fmt == \"LMTO\":\n            # LMTO COOPs and orbital-resolved COHP cannot be handled yet.\n            are_coops = False\n            orb_res_cohp = None\n            if structure_file is None:\n                structure_file = \"CTRL\"\n            if filename is None:\n                filename = \"COPL\"\n            cohp_file = LMTOCopl(filename=filename, to_eV=True)\n        elif fmt == \"LOBSTER\":\n            if structure_file is None:\n                structure_file = \"POSCAR\"\n            if filename is None:\n                filename = \"COOPCAR.lobster\" if are_coops \\\n                    else \"COHPCAR.lobster\"\n            warnings.warn(\n                \"The bond labels are currently consistent with ICOHPLIST.lobster/ICOOPLIST.lobster, not with \"\n                \"COHPCAR.lobster/COOPCAR.lobster. Please be aware!\")\n            cohp_file = Cohpcar(filename=filename, are_coops=are_coops)\n            orb_res_cohp = cohp_file.orb_res_cohp\n        else:\n            raise ValueError(\"Unknown format %s. Valid formats are LMTO \"\n                             \"and LOBSTER.\" % fmt)\n\n        structure = Structure.from_file(structure_file)\n        efermi = cohp_file.efermi\n        cohp_data = cohp_file.cohp_data\n        energies = cohp_file.energies\n\n        # Lobster shifts the energies so that the Fermi energy is at zero.\n        # Shifting should be done by the plotter object though.\n\n        spins = [Spin.up, Spin.down] if cohp_file.is_spin_polarized \\\n            else [Spin.up]\n        if fmt == \"LOBSTER\":\n            energies += efermi\n\n        if orb_res_cohp is not None:\n            # If no total COHPs are present, calculate the total\n            # COHPs from the single-orbital populations. Total COHPs\n            # may not be present when the cohpgenerator keyword is used\n            # in LOBSTER versions 2.2.0 and earlier.\n            # TODO: Test this more extensively\n            # pylint: disable=E1133,E1136\n            for label in orb_res_cohp:\n                if cohp_file.cohp_data[label][\"COHP\"] is None:\n                    # print(label)\n                    cohp_data[label][\"COHP\"] = {\n                        sp: np.sum([orb_res_cohp[label][orbs][\"COHP\"][sp] for orbs in orb_res_cohp[label]], axis=0)\n                        for sp in spins}\n                if cohp_file.cohp_data[label][\"ICOHP\"] is None:\n                    cohp_data[label][\"ICOHP\"] = \\\n                        {sp: np.sum([orb_res_cohp[label][orbs][\"ICOHP\"][sp]\n                                     for orbs in orb_res_cohp[label]],\n                                    axis=0) for sp in spins}\n\n        if fmt == \"LMTO\":\n            # Calculate the average COHP for the LMTO file to be\n            # consistent with LOBSTER output.\n            avg_data = {\"COHP\": {}, \"ICOHP\": {}}\n            for i in avg_data:\n                for spin in spins:\n                    rows = np.array([cohp_data[label][i][spin]\n                                     for label in cohp_data])\n                    avg = np.average(rows, axis=0)\n                    # LMTO COHPs have 5 significant figures\n                    avg_data[i].update({spin: np.array([round_to_sigfigs(a, 5)\n                                                        for a in avg], dtype=float)})\n            avg_cohp = Cohp(efermi, energies,\n                            avg_data[\"COHP\"],\n                            icohp=avg_data[\"ICOHP\"])\n        else:\n            avg_cohp = Cohp(efermi, energies,\n                            cohp_data[\"average\"][\"COHP\"],\n                            icohp=cohp_data[\"average\"][\"COHP\"],\n                            are_coops=are_coops)\n            del cohp_data[\"average\"]\n\n        cohp_dict = {label: Cohp(efermi, energies,\n                                 cohp_data[label][\"COHP\"],\n                                 icohp=cohp_data[label][\"ICOHP\"],\n                                 are_coops=are_coops)\n                     for label in cohp_data}\n\n        bond_dict = {label: {\"length\": cohp_data[label][\"length\"],\n                             \"sites\": [structure.sites[site]\n                                       for site in cohp_data[label][\"sites\"]]}\n                     for label in cohp_data}\n\n        return CompleteCohp(structure, avg_cohp, cohp_dict, bonds=bond_dict,\n                            are_coops=are_coops, orb_res_cohp=orb_res_cohp)\n\n\nclass IcohpValue(MSONable):\n    \"\"\"\n    Class to store information on an ICOHP or ICOOP value\n\n    .. attribute:: num_bonds\n            number of bonds used for the average cohp (relevant for Lobster versions <3.0) (int)\n\n    .. attribute:: are_coops\n            Boolean to indicate whether ICOOP or not\n\n    .. attribute:: icohp\n            dict={Spin.up: icohpvalue for spin.up, Spin.down: icohpvalue for spin.down}\n\n    .. attribute:: summed_icohp:\n            sum of icohp/icoop of both spin channels\n\n    \"\"\"\n\n    def __init__(self, label, atom1, atom2, length, translation, num, icohp, are_coops=False):\n        \"\"\"\n        Args:\n            label: label for the icohp\n            atom1: str of atom that is contributing to the bond\n            atom2: str of second atom that is contributing to the bond\n            length: float of bond lengths\n            translation: translation list, e.g. [0,0,0]\n            num: integer describing how often the bond exists\n            icohp: dict={Spin.up: icohpvalue for spin.up, Spin.down: icohpvalue for spin.down}\n        \"\"\"\n        self._are_coops = are_coops\n        self._label = label\n        self._atom1 = atom1\n        self._atom2 = atom2\n        self._length = length\n        self._translation = translation\n        self._num = num\n        self._icohp = icohp\n        if Spin.down in self._icohp:\n            self._is_spin_polarized = True\n        else:\n            self._is_spin_polarized = False\n\n    def __str__(self):\n\n        if not self._are_coops:\n            if self._is_spin_polarized:\n                return (\"ICOHP \" + str(self._label) + \" between \" + str(self._atom1) + \" and \" + str(self._atom2) +\n                        \" (\" + str(self._translation) + \"): \" + str(self._icohp[Spin.up]) + \" eV (Spin up) and \" +\n                        str(self._icohp[Spin.down]) + \" eV (Spin down)\")\n            return (\"ICOHP \" + str(self._label) + \" between \" + str(self._atom1) + \" and \" + str(self._atom2) +\n                    \" (\" + str(self._translation) + \"): \" + str(self._icohp[Spin.up]) + \" eV (Spin up)\")\n        if self._is_spin_polarized:\n            return (\"ICOOP \" + str(self._label) + \" between \" + str(self._atom1) + \" and \" + str(self._atom2) +\n                    \" (\" + str(self._translation) + \"): \" + str(self._icohp[Spin.up]) + \" (Spin up) and \" +\n                    str(self._icohp[Spin.down]) + \" (Spin down)\")\n        return (\"ICOOP \" + str(self._label) + \" between \" + str(self._atom1) + \" and \" + str(self._atom2) +\n                \" (\" + str(self._translation) + \"): \" + str(self._icohp[Spin.up]) + \" (Spin up)\")\n\n    @property\n    def num_bonds(self):\n        \"\"\"\n        tells the number of bonds for which the ICOHP value is an average\n        Returns:\n            Int\n        \"\"\"\n        return self._num\n\n    @property\n    def are_coops(self):\n        \"\"\"\n        tells if ICOOPs or not\n        Returns:\n            Boolean\n        \"\"\"\n        return self._are_coops\n\n    @property\n    def is_spin_polarized(self):\n        \"\"\"\n        tells if spin polarized calculation or not\n        Returns:\n            Boolean\n\n        \"\"\"\n        return self._is_spin_polarized\n\n    def icohpvalue(self, spin=Spin.up):\n        \"\"\"\n        Args:\n            spin: Spin.up or Spin.down\n        Returns:\n            icohpvalue (float) corresponding to chosen spin\n        \"\"\"\n        if not self.is_spin_polarized and spin == Spin.down:\n            raise ValueError(\"The calculation was not performed with spin polarization\")\n\n        return self._icohp[spin]\n\n    @property\n    def icohp(self):\n        \"\"\"\n        dict with icohps for spinup and spindown\n        Return:\n            dict={Spin.up: icohpvalue for spin.up, Spin.down: icohpvalue for spin.down}\n        \"\"\"\n        return self._icohp\n\n    @property\n    def summed_icohp(self):\n        \"\"\"\n        Adds ICOHPs of both spin channels for spin polarized compounds\n        Returns:\n             icohp value in eV\n        \"\"\"\n        if self._is_spin_polarized:\n            sum_icohp = self._icohp[Spin.down] + self._icohp[Spin.up]\n        else:\n            sum_icohp = self._icohp[Spin.up]\n        return sum_icohp\n\n\nclass IcohpCollection(MSONable):\n    \"\"\"\n    Class to store IcohpValues\n\n    .. attribute:: are_coops\n        Boolean to indicate whether ICOHPs or ICOOPs are stored\n\n    .. attribute:: is_spin_polarized\n        Boolean to indicate if the Lobster calculation was done spin polarized or not\n\n    \"\"\"\n\n    def __init__(self, list_labels, list_atom1, list_atom2, list_length,\n                 list_translation, list_num, list_icohp, is_spin_polarized, are_coops=False):\n        \"\"\"\n        Args:\n            is_spin_polarized: Boolean to indicate if the Lobster calculation was done spin polarized or not Boolean to\n                indicate if the Lobster calculation was done spin polarized or not\n            are_coops: Boolean to indicate whether ICOHPs or ICOOPs are stored\n            list_labels: list of labels for ICOHP/ICOOP values\n            list_atom1: list of str of atomnames e.g. \"O1\"\n            list_atom2: list of str of atomnames e.g. \"O1\"\n            list_length: list of lengths of corresponding bonds in Angstrom\n            list_translation: list of translation list, e.g. [0,0,0]\n            list_num: list of equivalent bonds, usually 1 starting from Lobster 3.0.0\n            list_icohp: list of dict={Spin.up: icohpvalue for spin.up, Spin.down: icohpvalue for spin.down}\n        \"\"\"\n        self._are_coops = are_coops\n        self._icohplist = {}\n        self._is_spin_polarized = is_spin_polarized\n        self._list_labels = list_labels\n        self._list_atom1 = list_atom1\n        self._list_atom2 = list_atom2\n        self._list_length = list_length\n        self._list_translation = list_translation\n        self._list_num = list_num\n        self._list_icohp = list_icohp\n\n        for ilist, listel in enumerate(list_labels):\n            self._icohplist[listel] = IcohpValue(listel, list_atom1[ilist], list_atom2[ilist], list_length[ilist],\n                                                 list_translation[ilist], list_num[ilist], list_icohp[ilist])\n\n    def __str__(self):\n        joinstr = []\n        for value in self._icohplist.values():\n            joinstr.append(str(value))\n        return \"\\n\".join(joinstr)\n\n    def get_icohp_by_label(self, label, summed_spin_channels=True, spin=Spin.up):\n        \"\"\"\n        get an icohp value for a certain bond as indicated by the label (bond labels starting by \"1\" as in\n        ICOHPLIST/ICOOPLIST)\n\n        Args:\n            label: label in str format (usually the bond number in Icohplist.lobster/Icooplist.lobster\n            summed_spin_channels: Boolean to indicate whether the ICOHPs/ICOOPs of both spin channels should be summed\n            spin: if summed_spin_channels is equal to False, this spin indicates which spin channel should be returned\n\n        Returns:\n            float describing ICOHP/ICOOP value\n        \"\"\"\n\n        icohp_here = self._icohplist[label]\n        if icohp_here._is_spin_polarized:\n            if summed_spin_channels:\n                return icohp_here.summed_icohp\n            return icohp_here.icohpvalue(spin)\n        return icohp_here.icohpvalue(spin)\n\n    def get_summed_icohp_by_label_list(self, label_list, divisor=1.0, summed_spin_channels=True, spin=Spin.up):\n        \"\"\"\n        get the sum of several ICOHP values that are indicated by a list of labels (labels of the bonds are the same as\n        in ICOHPLIST/ICOOPLIST)\n\n        Args:\n            label_list: list of labels of the ICOHPs/ICOOPs that should be summed\n            divisor: is used to divide the sum\n            summed_spin_channels: Boolean to indicate whether the ICOHPs/ICOOPs of both spin channels should be summed\n            spin: if summed_spin_channels is equal to False, this spin indicates which spin channel should be returned\n\n        Returns:\n             float that is a sum of all ICOHPs/ICOOPs as indicated with label_list\n        \"\"\"\n        sum_icohp = 0\n        for label in label_list:\n            icohp_here = self._icohplist[label]\n            if icohp_here.num_bonds != 1:\n                warnings.warn(\"One of the ICOHP values is an average over bonds. This is currently not considered.\")\n            # prints warning if num_bonds is not equal to 1\n            if icohp_here._is_spin_polarized:\n                if summed_spin_channels:\n                    sum_icohp = sum_icohp + icohp_here.summed_icohp\n                else:\n                    sum_icohp = sum_icohp + icohp_here.icohpvalue(spin)\n            else:\n                sum_icohp = sum_icohp + icohp_here.icohpvalue(spin)\n        return sum_icohp / divisor\n\n    def get_icohp_dict_by_bondlengths(self, minbondlength=0.0, maxbondlength=8.0):\n        \"\"\"\n        get a dict of IcohpValues corresponding to certaind bond lengths\n        Args:\n            minbondlength: defines the minimum of the bond lengths of the bonds\n            maxbondlength: defines the maximum of the bond lengths of the bonds\n        Returns:\n             dict of IcohpValues, the keys correspond to the values from the initial list_labels\n        \"\"\"\n        newicohp_dict = {}\n        for value in self._icohplist.values():\n            if value._length >= minbondlength and value._length <= maxbondlength:\n                newicohp_dict[value._label] = value\n        return newicohp_dict\n\n    def get_icohp_dict_of_site(self, site, minsummedicohp=None, maxsummedicohp=None, minbondlength=0.0,\n                               maxbondlength=8.0, only_bonds_to=None):\n        \"\"\"\n        get a dict of IcohpValue for a certain site (indicated by integer)\n        Args:\n            site: integer describing the site of interest, order as in Icohplist.lobster/Icooplist.lobster, starts at 0\n            minsummedicohp: float, minimal icohp/icoop of the bonds that are considered. It is the summed ICOHP value\n                from both spin channels for spin polarized cases\n            maxsummedicohp: float, maximal icohp/icoop of the bonds that are considered. It is the summed ICOHP value\n                from both spin channels for spin polarized cases\n            minbondlength: float, defines the minimum of the bond lengths of the bonds\n            maxbondlength: float, defines the maximum of the bond lengths of the bonds\n            only_bonds_to: list of strings describing the bonding partners that are allowed, e.g. ['O']\n        Returns:\n             dict of IcohpValues, the keys correspond to the values from the initial list_labels\n        \"\"\"\n\n        newicohp_dict = {}\n        for key, value in self._icohplist.items():\n            atomnumber1 = int(re.split(r'(\\d+)', value._atom1)[1]) - 1\n            atomnumber2 = int(re.split(r'(\\d+)', value._atom2)[1]) - 1\n            if site in (atomnumber1, atomnumber2):\n                # manipulate order of atoms so that searched one is always atom1\n                if site == atomnumber2:\n                    save = value._atom1\n                    value._atom1 = value._atom2\n                    value._atom2 = save\n\n                if only_bonds_to is None:\n                    second_test = True\n                else:\n                    second_test = (re.split(r'(\\d+)', value._atom2)[0] in only_bonds_to)\n                if value._length >= minbondlength and value._length <= maxbondlength and second_test:\n                    if minsummedicohp is not None:\n                        if value.summed_icohp >= minsummedicohp:\n                            if maxsummedicohp is not None:\n                                if value.summed_icohp <= maxsummedicohp:\n                                    newicohp_dict[key] = value\n                            else:\n                                newicohp_dict[key] = value\n                    else:\n                        if maxsummedicohp is not None:\n                            if value.summed_icohp <= maxsummedicohp:\n                                newicohp_dict[key] = value\n                        else:\n                            newicohp_dict[key] = value\n\n        return newicohp_dict\n\n    def extremum_icohpvalue(self, summed_spin_channels=True, spin=Spin.up):\n        \"\"\"\n        get ICOHP/ICOOP of strongest bond\n        Args:\n            summed_spin_channels: Boolean to indicate whether the ICOHPs/ICOOPs of both spin channels should be summed\n\n            spin: if summed_spin_channels is equal to False, this spin indicates which spin channel should be returned\n        Returns:\n            lowest ICOHP/largest ICOOP value (i.e. ICOHP/ICOOP value of strongest bond)\n        \"\"\"\n        if not self._are_coops:\n            extremum = sys.float_info.max\n        else:\n            extremum = -sys.float_info.max\n\n        if not self._is_spin_polarized:\n            if spin == Spin.down:\n                warnings.warn(\"This spin channel does not exist. I am switching to Spin.up\")\n            spin = Spin.up\n\n        for value in self._icohplist.values():\n            if not value.is_spin_polarized or not summed_spin_channels:\n                if not self._are_coops:\n                    if value.icohpvalue(spin) < extremum:\n                        extremum = value.icohpvalue(spin)\n                        # print(extremum)\n                else:\n                    if value.icohpvalue(spin) > extremum:\n                        extremum = value.icohpvalue(spin)\n                        # print(extremum)\n            else:\n                if not self._are_coops:\n                    if value.summed_icohp < extremum:\n                        extremum = value.summed_icohp\n                        # print(extremum)\n                else:\n                    if value.summed_icohp > extremum:\n                        extremum = value.summed_icohp\n                        # print(extremum)\n        return extremum\n\n    @property\n    def is_spin_polarized(self):\n        \"\"\"\n        :return: Whether it is spin polarized.\n        \"\"\"\n        return self._is_spin_polarized\n\n    @property\n    def are_coops(self):\n        \"\"\"\n        :return: Whether this is coops.\n        \"\"\"\n        return self._are_coops\n", "meta": {"hexsha": "4c2464bab2788c1e3a108b7cc7bbcb1762655389", "size": 42867, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymatgen/electronic_structure/cohp.py", "max_stars_repo_name": "Chessmag/pymatgen", "max_stars_repo_head_hexsha": "61a4bb7a1792e1ea2379abd45b3c40efb816fd64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-18T01:26:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-18T01:26:50.000Z", "max_issues_repo_path": "pymatgen/electronic_structure/cohp.py", "max_issues_repo_name": "Chessmag/pymatgen", "max_issues_repo_head_hexsha": "61a4bb7a1792e1ea2379abd45b3c40efb816fd64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pymatgen/electronic_structure/cohp.py", "max_forks_repo_name": "Chessmag/pymatgen", "max_forks_repo_head_hexsha": "61a4bb7a1792e1ea2379abd45b3c40efb816fd64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4425742574, "max_line_length": 119, "alphanum_fraction": 0.5564886743, "include": true, "reason": "import numpy", "num_tokens": 10396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.18012208390748802}}
{"text": "#!/usr/bin/env python\n\nimport os\nimport time\nimport json\nimport tensorflow as tf\nimport numpy as np\nfrom utils import *\nfrom data_loader import *\nfrom attention import attention\nfrom ffindex import FFindexDB, read_index, read_data\n\neps  = 1e-9 # small number\n\nN_AA = 20 # regular aa\nN_AA_MSA = 21 # regular aa + gap\nWMIN = 0.8\n\nN_PRINT_LEVEL = 50\n\nTRAIN_LOG = \"Train [%03d/%03d] counter: %5d  time: %10.1f lr: %.6f | loss: %7.4f | %.4f %.4f %.4f %.4f %.4f %.4f %.4f | %.4f %.4f %.4f %.4f %.4f %.4f %.4f\"\nVALID_LOG = \"Valid [%03d/%03d] counter: %5d  time: %10.1f lr: %.6f | loss: %7.4f | %.4f %.4f %.4f %.4f %.4f %.4f %.4f | %.4f %.4f %.4f %.4f %.4f %.4f %.4f\"\n\n# ResNet model definition\nclass ResNet_model(object):\n    def __init__(self, sess, n_1d_layer=2, dilation=[1],\n                 p_dropout=0.2, l2_coeff=0.001, kernel_size=3, n_hidden_rnn=64, attention_size=50,\n                 n_feat_1d=64, n_feat_2d = 64, n_bottle_1d=32, n_bottle_2d=32, use_cpu=False, use_templ=False):\n        self.sess = sess # tensorflow session\n        #\n        self.n_1d_layer = n_1d_layer\n        self.dilation = dilation\n        self.kernel = kernel_size\n        #\n        self.n_seq_1d = N_AA + N_AA_MSA + 1\n        self.n_str_feat = 8 # 1 dist_map + 6 ori_map + 1 seqsep\n        self.SS_dim     = 9\n        self.phi_dim    = 36\n        self.psi_dim    = 36\n        self.omg_dim    = 2\n        #\n        self.n_hidden_rnn = n_hidden_rnn\n        self.attention_size = attention_size\n        #\n        # hidden layer (1d)\n        self.n_feat_1d = n_feat_1d\n        self.n_feat_2d = n_feat_2d\n        self.n_bottle_1d = n_bottle_1d\n        self.n_bottle_2d = n_bottle_2d\n        #\n        self.p_dropout = p_dropout\n        self.rnn_p_dropout = p_dropout\n        self.l2_coeff = l2_coeff\n        #\n        with tf.variable_scope(\"SStorPred\"):\n            self.build_model(use_cpu=use_cpu, use_templ=use_templ)\n\n    def build_model(self, use_cpu=False, use_templ=False):\n        #\n        # Receive inputs\n        with tf.variable_scope(\"input\"):\n            self.seq      = tf.placeholder(tf.float32, [None, N_AA], name=\"seq\") # n_res, N_AA (blosum)\n            self.msa      = tf.placeholder(tf.uint8, [None, None], name=\"msa\") # n_seq, n_res\n            self.str_2d   = tf.placeholder(tf.float32, [None, None, None, self.n_str_feat], name=\"str_2d\") # 1, n_res, n_res, n_feat\n            self.pth_1d   = tf.placeholder(tf.float32, [None, None, 4])\n            self.pth_2d   = tf.placeholder(tf.float32, [None, None, None, 6])\n            self.SS       = tf.placeholder(tf.float32, [None, None, self.SS_dim]) # SS label\n            self.phi      = tf.placeholder(tf.float32, [None, None, self.phi_dim]) # ref. phi distrib\n            self.psi      = tf.placeholder(tf.float32, [None, None, self.psi_dim]) # ref. psi distrib\n            self.omg      = tf.placeholder(tf.float32, [None, None, self.omg_dim]) # ref. omg distrib\n            self.is_train = tf.placeholder(tf.bool)\n            self.n_batch = tf.shape(self.str_2d)[0]\n            self.n_res = tf.shape(self.seq)[0]\n        #\n        # 3-state answer\n        self.SS3 = tf.stack([tf.reduce_sum(self.SS[:,:, :3], axis=-1), \n                             tf.reduce_sum(self.SS[:,:,3:6], axis=-1),\n                             tf.reduce_sum(self.SS[:,:,6: ], axis=-1)], axis=-1)\n        #\n        # 8-state answer\n        self.SS8 = tf.stack([self.SS[:,:,0],\n                             tf.reduce_sum(self.SS[:,:,1:3], axis=-1),\n                             self.SS[:,:,3],\n                             self.SS[:,:,4],\n                             self.SS[:,:,5],\n                             self.SS[:,:,6],\n                             self.SS[:,:,7],\n                             self.SS[:,:,8]], axis=-1)\n        #================================\n        # sequence features\n        #================================\n        # get pssm features from MSA\n        msa1hot = tf.one_hot(self.msa, N_AA_MSA, dtype=tf.float32)\n        w_seq = reweight_seq(msa1hot, WMIN)\n        pssm = msa2pssm(msa1hot, w_seq)\n        #\n        seq_1d = tf.concat([self.seq, pssm], axis=-1) # sequence based features\n        seq_1d = tf.expand_dims(seq_1d, 0)\n        #\n        # projection to n_feat_1d\n        feat = tf.layers.conv1d(seq_1d, self.n_feat_1d, 1, padding='same')\n        #\n        #=================================\n        # 1D ResNet with combined features\n        #=================================\n        # Stacking 1-dim residual blocks\n        for i in range(self.n_1d_layer):\n            d = self.dilation[i%len(self.dilation)]\n            feat = self.ResNet_block_1d(feat, self.is_train, step=i, dilation=d)\n        feat = tf.nn.elu(inst_norm(feat))\n        #\n        seq_1d = tf.tile(tf.reshape(feat, [-1]), [self.n_batch*self.n_res])\n        seq_1d = tf.reshape(seq_1d, [self.n_batch, self.n_res, self.n_res, self.n_feat_1d])\n        \n        if use_templ:\n            #=================================\n            # Process template info\n            #=================================\n            t1d = tf.concat([tf.sin(self.pth_1d[:,:,0])[:,:,None],\n                            tf.cos(self.pth_1d[:,:,0])[:,:,None],\n                            tf.sin(self.pth_1d[:,:,1])[:,:,None],\n                            tf.cos(self.pth_1d[:,:,1])[:,:,None],\n                            self.pth_1d[:,:,2:]], axis=-1)\n            t2d = tf.concat([tf.one_hot(tf.cast(self.pth_2d[:,:,:,0],dtype=tf.uint8),19,dtype=tf.float32),\n                            tf.sin(self.pth_2d[:,:,:,1])[:,:,:,None],\n                            tf.cos(self.pth_2d[:,:,:,1])[:,:,:,None],\n                            tf.sin(self.pth_2d[:,:,:,2])[:,:,:,None],\n                            tf.cos(self.pth_2d[:,:,:,2])[:,:,:,None],\n                            tf.sin(self.pth_2d[:,:,:,3])[:,:,:,None],\n                            tf.cos(self.pth_2d[:,:,:,3])[:,:,:,None],\n                            tf.tile(t1d[:,:,None,:],[1,1,self.n_res,1]),\n                            tf.tile(t1d[:,None,:,:],[1,self.n_res,1,1])], axis=-1)\n            sgnl = tf.nn.elu(tf.layers.conv2d(t2d, self.n_feat_2d, 3, padding='SAME'))\n            prob = tf.nn.softmax(tf.layers.conv2d(t2d, 1, 3, padding='SAME'), axis=0)\n            t2d = tf.reduce_sum(sgnl*prob,axis=0)\n        #\n        # combine with 2D str features\n        str_2d = tf.layers.conv2d(self.str_2d, self.n_feat_2d, 1, padding='same')\n        str_2d = tf.nn.elu(inst_norm(str_2d))\n        \n        if use_templ:\n            feat = tf.concat((str_2d, t2d[None, :,:,:], seq_1d, tf.transpose(seq_1d, (0,2,1,3))), axis=-1)\n        else:\n            feat = tf.concat((str_2d, seq_1d, tf.transpose(seq_1d, (0,2,1,3))), axis=-1)\n        #\n        # projection to n_feat_2d\n        feat = tf.layers.conv2d(feat, self.n_feat_2d, 1, padding='same', use_bias=False)\n        #\n        #=================================\n        # 2D ResNet with combined features\n        #=================================\n        # Stacking 2-dim residual blocks (receptive field size: 61) \n        for i in range(8):\n            d = self.dilation[i%len(self.dilation)]\n            feat = self.ResNet_block_2d(feat, self.is_train, step=i, dilation=d)\n        feat = tf.nn.elu(inst_norm(feat))\n        #\n        #=================================\n        # LSTM to extract 1-dimensional features from input features\n        #=================================\n        with tf.variable_scope(\"AttBiLSTM\") as scope:\n            # convert to 1D using LSTM\n            weights = {'out': tf.Variable(tf.random_normal([self.n_hidden_rnn*2, self.n_feat_1d]), name='kernel')}\n            biases  = {'out': tf.Variable(tf.random_normal([self.n_feat_1d]), name='bias')}\n            #\n            if use_cpu:\n                feat, self.alphas = self.BiLSTM_w_attention_cpu(feat, weights, biases)\n            else:\n                feat, self.alphas = self.BiLSTM_w_attention_gpu(feat, weights, biases)\n            feat = tf.reshape(feat, [self.n_batch, self.n_res, self.n_feat_1d])\n        #\n        # Stacking 1-dim residual blocks\n        with tf.variable_scope(\"additional_ResNet\"):\n            for i in range(4):\n                d = self.dilation[i%len(self.dilation)]\n                feat = self.ResNet_block_1d(feat, self.is_train, step=i, dilation=d)\n        #\n        # Final branching\n        with tf.variable_scope(\"final_SS\") as scope:\n            for i in range(4):\n                d = self.dilation[i%len(self.dilation)]\n                feat = self.ResNet_block_1d(feat, self.is_train, step=i, dilation=d)\n            feat = tf.nn.elu(feat)\n            SS_logit = tf.layers.conv1d(feat, self.SS_dim, 1, padding='same')\n        #\n        with tf.variable_scope(\"final_phi\") as scope:\n            for i in range(4):\n                d = self.dilation[i%len(self.dilation)]\n                feat = self.ResNet_block_1d(feat, self.is_train, step=i, dilation=d)\n            feat = tf.nn.elu(feat)\n            phi_logit = tf.layers.conv1d(feat, self.phi_dim, 1, padding='same')\n        #\n        with tf.variable_scope(\"final_psi\") as scope:\n            for i in range(4):\n                d = self.dilation[i%len(self.dilation)]\n                feat = self.ResNet_block_1d(feat, self.is_train, step=i, dilation=d)\n            feat = tf.nn.elu(feat)\n            psi_logit = tf.layers.conv1d(feat, self.psi_dim, 1, padding='same')\n        #\n        with tf.variable_scope(\"final_omg\") as scope:\n            for i in range(4):\n                d = self.dilation[i%len(self.dilation)]\n                feat = self.ResNet_block_1d(feat, self.is_train, step=i, dilation=d)\n            feat = tf.nn.elu(feat)\n            omg_logit = tf.layers.conv1d(feat, self.omg_dim, 1, padding='same')\n        #\n        # calculate probability\n        SS_prob = tf.nn.softmax(SS_logit)\n        SS3_prob = tf.stack([tf.reduce_sum(SS_prob[:,:, :3], axis=-1), \n                             tf.reduce_sum(SS_prob[:,:,3:6], axis=-1),\n                             tf.reduce_sum(SS_prob[:,:,6: ], axis=-1)], axis=-1)\n        SS8_prob = tf.stack([SS_prob[:,:,0],\n                             tf.reduce_sum(SS_prob[:,:,1:3], axis=-1),\n                             SS_prob[:,:,3],\n                             SS_prob[:,:,4],\n                             SS_prob[:,:,5],\n                             SS_prob[:,:,6],\n                             SS_prob[:,:,7],\n                             SS_prob[:,:,8]], axis=-1)\n        phi_prob = tf.nn.softmax(phi_logit)\n        psi_prob = tf.nn.softmax(psi_logit)\n        omg_prob = tf.nn.softmax(omg_logit)\n        self.prob_s = [SS_prob, SS8_prob, SS3_prob, phi_prob, psi_prob, omg_prob]\n        \n        # calculate loss function (softmax cross-entropy)\n        # For SS & omega, it is same as categorical cross entropy\n        # For phi psi angles, reference is defined with von Mises distrib.\n        # It should be noted that minimizing softmax cross-entropy is same as minimizing KL divergence\n        \n        SS_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(self.SS, SS_logit))\n\n        SS3_loss = -tf.reduce_sum(self.SS3 * tf.log(SS3_prob+eps), axis=-1)\n        SS3_loss = tf.reduce_mean(SS3_loss)\n        \n        SS8_loss = -tf.reduce_sum(self.SS8 * tf.log(SS8_prob+eps), axis=-1)\n        SS8_loss = tf.reduce_mean(SS8_loss)\n        \n        phi_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(self.phi, phi_logit))\n        psi_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(self.psi, psi_logit))\n        omg_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(self.omg, omg_logit))\n\n        self.t_vars = tf.trainable_variables()\n        #\n        # L2-regularization to avoid overfitting\n        l2_loss = tf.add_n([tf.nn.l2_loss(var)\n                            for var in self.t_vars if 'kernel' in var.name]) * self.l2_coeff\n        #\n        # total losses\n        self.loss_s = [SS_loss, SS8_loss, SS3_loss, phi_loss, psi_loss, omg_loss, l2_loss]\n        self.tot_loss = tf.add_n(self.loss_s)\n        \n        # calculate accuracy\n        equal = tf.cast(tf.equal(tf.argmax(SS_prob, axis=-1), tf.argmax(self.SS, axis=-1)), tf.float32)\n        SS_acc = tf.reduce_mean(tf.cast(equal, tf.float32))\n        #\n        equal = tf.cast(tf.equal(tf.argmax(SS3_prob, axis=-1), tf.argmax(self.SS3, axis=-1)), tf.float32)\n        SS3_acc = tf.reduce_mean(tf.cast(equal, tf.float32))\n        #\n        equal = tf.cast(tf.equal(tf.argmax(SS8_prob, axis=-1), tf.argmax(self.SS8, axis=-1)), tf.float32)\n        SS8_acc = tf.reduce_mean(tf.cast(equal, tf.float32))\n        #\n        phi_equal = tf.equal(tf.argmax(phi_prob, axis=-1), tf.argmax(self.phi, axis=-1))\n        phi_acc = tf.reduce_mean(tf.cast(phi_equal, tf.float32))\n        #\n        psi_equal = tf.equal(tf.argmax(psi_prob, axis=-1), tf.argmax(self.psi, axis=-1))\n        psi_acc = tf.reduce_mean(tf.cast(psi_equal, tf.float32))\n        #\n        omg_equal = tf.equal(tf.argmax(omg_prob, axis=-1), tf.argmax(self.omg, axis=-1))\n        omg_acc = tf.reduce_mean(tf.cast(omg_equal, tf.float32))\n        #\n        equal = tf.stack([phi_equal, psi_equal, omg_equal], axis=-1)\n        equal = tf.reduce_all(equal, axis=-1)\n        tot_acc = tf.reduce_mean(tf.cast(equal, tf.float32))\n        self.acc_s = [SS_acc, SS8_acc, SS3_acc, phi_acc, psi_acc, omg_acc, tot_acc]\n        #\n        # define trained model saver\n        self.saver = tf.train.Saver()\n    \n    def BiLSTM_w_attention_gpu(self, x, weights, biases, return_alphas=True):\n        # prepare input data shape to match rnn function requirements\n        # input x: (batch_size, n_res, n_res, n_ch)\n        # Required shape: timesteps tensors list of shape (batch_size', n_input')\n        #   - howto? batch_size' = batch_size*n_res , n_input' = n_ch\n        #            # of timesteps = n_res\n        \n        # reshape input x to (batch_size*n_res, n_res, n_ch), CAUTION: batch_size=1 here\n        # first n_res: time-series & time-series should go first in cudnn version\n        x = tf.transpose(x, (1,0,2,3))\n        x = tf.reshape(x, [self.n_res, self.n_batch*self.n_res, self.n_feat_2d])\n        #x = tf.reshape(x, [self.n_res, self.n_batch*self.n_res, self.n_hidden_rnn])\n        \n        # define a lstm cell\n        lstm = tf.contrib.cudnn_rnn.CudnnLSTM(3, self.n_hidden_rnn, direction='bidirectional', dtype=tf.float32)\n\n        # Get BiLSTM cell output \n        outputs, states = lstm(x)\n        outputs = tf.concat(outputs, axis=-1)\n\n        # apply attention\n        outputs, alphas = attention(outputs, self.attention_size, return_alphas=return_alphas, time_major=True)\n\n        # apply linear activation\n        return tf.matmul(outputs, weights['out']) + biases['out'], alphas\n    \n    def BiLSTM_w_attention_cpu(self, x, weights, biases, return_alphas=True):\n        # prepare input data shape to match rnn function requirements\n        # input x: (batch_size, n_res, n_res, n_ch)\n        # Required shape: timesteps tensors list of shape (batch_size', n_input')\n        #   - howto? batch_size' = batch_size*n_res , n_input' = n_ch\n        #            # of timesteps = n_res\n        \n        # reshape input x to (batch_size*n_res, n_res, n_ch), CAUTION: batch_size=1 here\n        # first n_res: time-series & time-series should go first in cudnn version\n        x = tf.transpose(x, (1,0,2,3))\n        x = tf.reshape(x, [self.n_res, self.n_batch*self.n_res, self.n_feat_2d])\n        #x = tf.reshape(x, [self.n_res, self.n_batch*self.n_res, self.n_hidden_rnn])\n        \n        # define a lstm cell\n        with tf.variable_scope(\"cudnn_lstm\"):\n            single_cell = lambda: tf.contrib.cudnn_rnn.CudnnCompatibleLSTMCell(self.n_hidden_rnn)\n            cells_fw = [single_cell() for _ in range(3)]\n            cells_bw = [single_cell() for _ in range(3)]\n            #\n            # Get BiLSTM cell output \n            outputs, output_state_fw, output_state_bw = tf.contrib.rnn.stack_bidirectional_dynamic_rnn(cells_fw, cells_bw, x, time_major=True, dtype=tf.float32)\n        outputs = tf.concat(outputs, axis=-1)\n\n        # apply attention\n        outputs, alphas = attention(outputs, self.attention_size, return_alphas=return_alphas, time_major=True)\n\n        # apply linear activation\n        return tf.matmul(outputs, weights['out']) + biases['out'], alphas\n    \n    def ResNet_block_2d(self, x, is_train, step=0, dilation=1): # bottleneck block w/ pre-activation\n        with tf.variable_scope(\"ResNet_2d_{}\".format(step)) as scope:\n            shortcut = x\n            # bottleneck layer (kernel: 1, n_feat_2d => n_bottle_2d)\n            x = tf.nn.elu(inst_norm(x))\n            x = tf.layers.conv2d(x, self.n_bottle_2d, 1, padding='same')\n            x = tf.nn.elu(inst_norm(x))\n            # convolution\n            x = tf.layers.conv2d(x, self.n_bottle_2d, self.kernel, dilation_rate=dilation,\n                                 padding='same')\n            x = tf.nn.elu(inst_norm(x))\n            x = tf.layers.dropout(x, rate=self.p_dropout, training=is_train)\n            # project up (kernel: 1, n_bottle_1d => n_feat_1d)\n            x = tf.layers.conv2d(x, self.n_feat_2d, 1, padding='same')\n            # add\n            x += shortcut\n        return x\n    \n    def ResNet_block_1d(self, x, is_train, step=0, dilation=1): # bottleneck block w/ pre-activation\n        with tf.variable_scope(\"ResNet_1d_{}\".format(step)) as scope:\n        #with tf.variable_scope(\"ResNet_1d_{}\".format(step), custom_getter=float32_variable_storage_getter) as scope:\n            shortcut = x\n            # bottleneck layer (kernel: 1, n_feat_1d => n_bottle_1d)\n            x = tf.nn.elu(inst_norm(x))\n            x = tf.layers.conv1d(x, self.n_bottle_1d, 1, padding='same')\n            x = tf.nn.elu(inst_norm(x))\n            # convolution\n            x = tf.layers.conv1d(x, self.n_bottle_1d, self.kernel, dilation_rate=dilation,\n                                 padding='same')\n            x = tf.nn.elu(inst_norm(x))\n            x = tf.layers.dropout(x, rate=self.p_dropout, training=is_train)\n            # project up (kernel: 1, n_bottle_1d => n_feat_1d)\n            x = tf.layers.conv1d(x, self.n_feat_1d, 1, padding='same')\n            # add\n            x += shortcut\n        return x\n    \n    def save(self, folder, prefix):\n        if not os.path.exists(folder):\n            os.mkdir(folder)\n        self.saver.save(self.sess, folder+\"/%s.ckpt\"%prefix)\n    \n    def load(self, folder, prefix):\n        model_fn = os.path.join(folder, \"%s.ckpt.index\"%prefix)\n        if os.path.exists(model_fn):\n            self.saver.restore(self.sess, folder+\"/%s.ckpt\"%prefix)\n            return True\n        return False\n    \n    def close(self):\n        self.sess.close()\n\n    def train(self, config_file):\n        # read config_file\n        with open(config_file) as json_file:\n            config = json.load(json_file, object_hook=Json_param)\n        #\n        train_pdbs = [line.split()[0] for line in open(config.train_list)]\n        self.n_train = len(train_pdbs)\n        #\n        global_step = tf.Variable(0, trainable=False)\n        \n        # define optimizer\n        if config.lr_schedule == \"CosineDecay\":\n            lr = tf.train.cosine_decay_restarts(learning_rate=config.lr,\n                                                global_step=global_step,\n                                                first_decay_steps=config.f_decay*self.n_train,\n                                                t_mul=config.t_mul,\n                                                m_mul=config.m_mul,\n                                                alpha=0.1)\n        elif config.lr_schedule == 'ExpDecay':\n            lr = tf.train.exponential_decay(config.lr,\n                                            global_step=global_step,\n                                            decay_steps=self.n_train,\n                                            decay_rate=0.99,\n                                            staircase=True)\n        else: # flat lr\n            lr = tf.Variable(config.lr, trainable=False)\n        \n        if config.optim == 'adam':\n            optimizer = tf.train.AdamOptimizer(lr)\n        elif config.optim == 'momentum':\n            optimizer = tf.train.MomentumOptimizer(lr, 0.5, use_nesterov=True)\n        else:\n            optimizer = tf.train.GradientDescentOptimizer(lr)\n\n        optim = optimizer.minimize(self.tot_loss, global_step=global_step, var_list=self.t_vars)\n        ops_to_run = [optim, lr, self.tot_loss, self.loss_s, self.acc_s]\n        #\n        # initialize all variables\n        init_op = tf.group(tf.global_variables_initializer(),\n                           tf.local_variables_initializer())\n        self.sess.run(init_op)\n        #\n        counter = 0\n        self.start_time = time.time()\n        #\n        n_batch = len(train_pdbs) \n        min_val_loss = config.best_loss\n        #\n        # Try to load pre-trained model if exists\n        could_load = self.load(\"model_%d_%d_%d\"%(self.n_hidden_rnn, self.n_1d_layer, self.attention_size), 'last_epoch')\n        if not could_load:\n            could_load = self.load(\"model_%d_%d_%d\"%(self.n_hidden_rnn, self.n_1d_layer, self.attention_size), 'model')\n        #\n        for epoch in range(config.n_epoch):\n            np.random.shuffle(train_pdbs)\n            tot_loss_value = 0.0\n            tot_loss_s = np.zeros(7, dtype=np.float32)\n            tot_acc_s = np.zeros(7, dtype=np.float32)\n            n_tot = 0.0\n            #\n            for pdb in train_pdbs:\n                seq, msa, str_2d, pth_1d, pth_2d, SS_labels, phi_labels, psi_labels, omg_labels = load_train_data(pdb, \\\n                                                is_train=True, mask_diag=config.mask_diag)\n                #\n                _, decayed_lr, loss_value, loss_s, acc_s = self.sess.run(ops_to_run,\n                                         feed_dict={\n                                             self.seq: seq,\n                                             self.msa: msa,\n                                             self.str_2d: str_2d[np.newaxis,:,:,:],\n                                             self.pth_1d: pth_1d,\n                                             self.pth_2d: pth_2d,\n                                             self.SS: SS_labels[np.newaxis,:,:],\n                                             self.phi: phi_labels[np.newaxis,:,:],\n                                             self.psi: psi_labels[np.newaxis,:,:],\n                                             self.omg: omg_labels[np.newaxis,:],\n                                             self.is_train: True})\n                tot_loss_value += loss_value\n                tot_loss_s += np.array(loss_s)\n                tot_acc_s += np.array(acc_s)\n                n_tot += 1.0\n                #\n                counter += 1\n                if counter % N_PRINT_LEVEL == 0:\n                    loss_value = tot_loss_value/n_tot\n                    loss_s = tot_loss_s/n_tot\n                    acc_s = tot_acc_s/n_tot\n                    tot_loss_value = 0.0\n                    tot_loss_s = np.zeros(7, dtype=np.float32)\n                    tot_acc_s = np.zeros(7, dtype=np.float32)\n                    n_tot = 0.0\n                    log_list = [epoch, config.n_epoch, counter, time.time()-self.start_time, decayed_lr*100.0, loss_value-loss_s[-1]]\n                    log_list.extend(loss_s)\n                    log_list.extend(acc_s)\n                    print (TRAIN_LOG%tuple(log_list))\n            #\n            val_loss = self.validation(config, epoch, counter, decayed_lr)\n            if val_loss < min_val_loss:\n                self.save(\"model_%d_%d_%d\"%(self.n_hidden_rnn, self.n_1d_layer, self.attention_size), 'model')\n                min_val_loss = val_loss\n            self.save(\"model_%d_%d_%d\"%(self.n_hidden_rnn, self.n_1d_layer, self.attention_size), 'last_epoch')\n\n    def validation(self, config, epoch, counter, decayed_lr):\n        ops_to_run = [self.tot_loss, self.loss_s, self.acc_s]\n        valid_pdbs = [line.split()[0] for line in open(config.valid_list) if line[0] != \"#\"]\n        #\n        tot_loss_value = 0.0\n        tot_loss_s = np.zeros(7, dtype=np.float32)\n        tot_acc_s = np.zeros(7, dtype=np.float32)\n        n_tot = 0.0\n        for pdb in valid_pdbs:\n            seq, msa, str_2d, pth_1d, pth_2d, SS_labels, phi_labels, psi_labels, omg_labels\\\n                     = load_train_data(pdb, \\\n                                            is_train=False, mask_diag=config.mask_diag)\n            #\n            loss_value, loss_s, acc_s = self.sess.run(ops_to_run,\n                                             feed_dict={\n                                                 self.seq: seq,\n                                                 self.msa: msa,\n                                                 self.str_2d: str_2d[np.newaxis,:,:,:],\n                                                 self.pth_1d: pth_1d,\n                                                 self.pth_2d: pth_2d,\n                                                 self.SS: SS_labels[np.newaxis,:,:],\n                                                 self.phi: phi_labels[np.newaxis,:,:],\n                                                 self.psi: psi_labels[np.newaxis,:,:],\n                                                 self.omg: omg_labels[np.newaxis,:],\n                                                 self.is_train:False})\n            tot_loss_value += loss_value\n            tot_loss_s += np.array(loss_s)\n            tot_acc_s += np.array(acc_s)\n            n_tot += 1.0\n        #\n        loss_value = tot_loss_value/n_tot\n        loss_s = tot_loss_s/n_tot\n        acc_s = tot_acc_s/n_tot\n        #\n        log_list = [epoch, config.n_epoch, counter, time.time()-self.start_time, decayed_lr*100.0, loss_value-loss_s[-1]]\n        log_list.extend(loss_s)\n        log_list.extend(acc_s)\n        print (VALID_LOG%tuple(log_list))\n        return loss_value-loss_s[-1]\n    \n    def predict(self, config):\n        self.load(config.model_dir, 'model')\n        #\n        ffdb = None\n        if config.templ_fn != None:\n            ffdb = FFindexDB(read_index(config.TMPDB+'_pdb.ffindex'),\n                             read_data(config.TMPDB+\"_pdb.ffdata\"))\n            hhr_fn = config.templ_fn\n        #\n        out_fn = \"%s.npz\"%config.outprefix\n        a3m_fn = config.a3m_fn\n        pdb_fn = config.pdb_fn\n        hhr_fn = config.templ_fn\n        # \n        seq, msa, str_2d, pth_1d, pth_2d = make_input_features(a3m_fn, pdb_fn, hhr_fn, ffdb)\n        #\n        if hhr_fn != None:\n            prob_s, alpha = self.sess.run([self.prob_s, self.alphas], feed_dict={\n                                                     self.seq: seq,\n                                                     self.msa: msa,\n                                                     self.str_2d: str_2d[np.newaxis,:,:,:],\n                                                     self.pth_1d: pth_1d,\n                                                     self.pth_2d: pth_2d,\n                                                     self.is_train:False})\n        else:\n            prob_s, alpha = self.sess.run([self.prob_s, self.alphas], feed_dict={\n                                                     self.seq: seq,\n                                                     self.msa: msa,\n                                                     self.str_2d: str_2d[np.newaxis,:,:,:],\n                                                     self.is_train:False})\n\n        SS_prob = prob_s[0].reshape(-1, self.SS_dim)\n        phi_prob = prob_s[3].reshape(-1, self.phi_dim)\n        psi_prob = prob_s[4].reshape(-1, self.psi_dim)\n        omg_prob = prob_s[5].reshape(-1, self.omg_dim)\n        tor_prob = np.concatenate((phi_prob, psi_prob, omg_prob), axis=-1)\n        np.savez_compressed(out_fn, ss9=SS_prob.astype(np.float16), tor=tor_prob.astype(np.float16))\n    \n    def predict_multi(self, config, a3m_s, pdb_s, hhr_s, out_s):\n        self.load(config.model_dir, 'model')\n        #\n        ffdb = None\n        if hhr_s[0] != None:\n            ffdb = FFindexDB(read_index(config.TMPDB+'_pdb.ffindex'),\n                             read_data(config.TMPDB+\"_pdb.ffdata\"))\n        #\n        for i, a3m_fn in enumerate(a3m_s):\n            out_fn = out_s[i]\n            pdb_fn = pdb_s[i]\n            hhr_fn = hhr_s[i]\n            if os.path.exists(out_fn):\n                continue\n            print (\"Running..., %s\"%out_fn)\n            # \n            seq, msa, str_2d, pth_1d, pth_2d = make_input_features(a3m_fn, pdb_fn, hhr_fn, ffdb)\n            #\n            if hhr_fn != None:\n                prob_s, alpha = self.sess.run([self.prob_s, self.alphas], feed_dict={\n                                                         self.seq: seq,\n                                                         self.msa: msa,\n                                                         self.str_2d: str_2d[np.newaxis,:,:,:],\n                                                         self.pth_1d: pth_1d,\n                                                         self.pth_2d: pth_2d,\n                                                         self.is_train:False})\n            else:\n                prob_s, alpha = self.sess.run([self.prob_s, self.alphas], feed_dict={\n                                                         self.seq: seq,\n                                                         self.msa: msa,\n                                                         self.str_2d: str_2d[np.newaxis,:,:,:],\n                                                         self.is_train:False})\n\n            SS_prob = prob_s[0].reshape(-1, self.SS_dim)\n            phi_prob = prob_s[3].reshape(-1, self.phi_dim)\n            psi_prob = prob_s[4].reshape(-1, self.psi_dim)\n            omg_prob = prob_s[5].reshape(-1, self.omg_dim)\n            tor_prob = np.concatenate((phi_prob, psi_prob, omg_prob), axis=-1)\n            np.savez_compressed(out_fn, ss9=SS_prob.astype(np.float16), tor=tor_prob.astype(np.float16))\n", "meta": {"hexsha": "0681018028e557f2c3fbc4198c9bf74007e86a63", "size": 29999, "ext": "py", "lang": "Python", "max_stars_repo_path": "trRefine/SStor_pred/model.py", "max_stars_repo_name": "NatureGeorge/trRosetta2", "max_stars_repo_head_hexsha": "dba6078ebda9f2429264ace3deaffe50d9899def", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2021-05-21T07:03:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:11:28.000Z", "max_issues_repo_path": "trRefine/SStor_pred/model.py", "max_issues_repo_name": "partrita/trRosetta2", "max_issues_repo_head_hexsha": "7036f81cdcfac6adcfebdc1ee917f46d8345229a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-05-20T21:35:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-05T15:38:55.000Z", "max_forks_repo_path": "trRefine/SStor_pred/model.py", "max_forks_repo_name": "partrita/trRosetta2", "max_forks_repo_head_hexsha": "7036f81cdcfac6adcfebdc1ee917f46d8345229a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2021-05-24T10:26:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T14:11:45.000Z", "avg_line_length": 49.667218543, "max_line_length": 160, "alphanum_fraction": 0.5164172139, "include": true, "reason": "import numpy", "num_tokens": 7418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.27202455699569283, "lm_q1q2_score": 0.18005927706840966}}
{"text": "#! /usr/bin/env python\n\n\"\"\"\nModule with local/smart PCA (annulus or patch-wise) model PSF subtraction for\nADI, ADI+SDI (IFS) and ADI+RDI datasets. This implementation make use of\nPython multiprocessing capabilities.\n\"\"\"\n\nfrom __future__ import division, print_function\n\n__author__ = 'Carlos Alberto Gomez Gonzalez'\n__all__ = ['pca_annular',\n           'pca_rdi_annular']\n\nimport numpy as np\nfrom scipy import stats\nfrom multiprocessing import cpu_count\nfrom ..preproc import (cube_derotate, cube_collapse, check_pa_vector,\n                       check_scal_vector)\nfrom ..preproc import cube_rescaling_wavelengths as scwave\nfrom ..preproc.derotation import _find_indices_adi, _define_annuli\nfrom ..preproc.rescaling import _find_indices_sdi\nfrom ..conf import time_ini, timing\nfrom ..conf.utils_conf import pool_map, fixed\nfrom ..var import get_annulus_segments, matrix_scaling\nfrom ..stats import descriptive_stats\nfrom .svd import get_eigenvectors\n\n\ndef pca_annular(cube, angle_list, scale_list=None, radius_int=0, fwhm=4,\n                asize=4, n_segments=1, delta_rot=1, delta_sep=(0.1, 1), ncomp=1,\n                ncomp2=1, svd_mode='lapack', nproc=1, min_frames_lib=2,\n                max_frames_lib=200, tol=1e-1, scaling=None, imlib='opencv',\n                interpolation='lanczos4', collapse='median', full_output=False,\n                verbose=True):\n    \"\"\" PCA model PSF subtraction for ADI and ADI + mSDI (IFS) data. The PCA\n    model is computed locally in each annulus (or annular sectors according to\n    ``n_segments``). For each sector we discard reference frames taking into\n    account a parallactic angle threshold (``delta_rot``) and a radial movement\n    threshold (``delta_sep``).\n\n    Parameters\n    ----------\n    cube : array_like, 3d or 4d\n        Input cube.\n    angle_list : array_like, 1d\n        Corresponding parallactic angle for each frame.\n    scale_list :\n        Scaling factors in case of IFS data (ADI+mSDI cube). Usually, the\n        scaling factors are the central channel wavelength divided by the\n        shortest wavelength in the cube (more thorough approaches can be used\n        to get the scaling factors). This scaling factors are used to re-scale\n        the spectral channels and align the speckles.\n    radius_int : int, optional\n        The radius of the innermost annulus. By default is 0, if >0 then the\n        central circular area is discarded.\n    fwhm : float, optional\n        Known size of the FHWM in pixels to be used. Default is 4.\n    asize : float, optional\n        The size of the annuli, in pixels.\n    n_segments : int or list of ints or 'auto', optional\n        The number of segments for each annulus. When a single integer is given\n        it is used for all annuli. When set to 'auto', the number of segments is\n        automatically determined for every annulus, based on the annulus width.\n    delta_rot : float, optional\n        Factor for increasing the parallactic angle threshold, expressed in\n        FWHM. Default is 1 (excludes 1 FHWM on each side of the considered\n        frame). According to Absil+13, a slightly better contrast can be reached\n        for the innermost annuli if we consider a ``delta_rot`` condition as\n        small as 0.1 lambda/D. This is because at very small separation, the\n        effect of speckle correlation is more significant than self-subtraction.\n    delta_sep : float or tuple of floats, optional\n        The threshold separation in terms of the mean FWHM (for ADI+mSDI data).\n        If a tuple of two values is provided, they are used as the lower and\n        upper intervals for the threshold (grows as a function of the\n        separation).\n    ncomp : int or list or 1d numpy array, optional\n        How many PCs are used as a lower-dimensional subspace to project the\n        target (sectors of) frames. If ``auto`` it will be automatically\n        determined. If ``cube`` is a 3d array (ADI), ``ncomp`` can be a list,\n        in which case a different number of PCs will be used for each annulus\n        (starting with the innermost one). If ``cube`` is a 4d array, then\n        ``ncomp`` is the number of PCs obtained from each multi-spectral frame\n        (for each sector).\n    ncomp2 : int, optional\n        Only used for ADI+mSDI (4d) cubes. ``ncomp2`` sets the number of PCs\n        used in the second PCA stage (ADI fashion, using the residuals of the\n        first stage). If None then the second PCA stage is skipped and the\n        residuals are de-rotated and combined.\n    mode : {'lapack', 'arpack', 'eigen', 'randsvd', 'cupy', 'eigencupy',\n            'randcupy', 'pytorch', 'eigenpytorch', 'randpytorch'}, str optional\n        Switch for the SVD method/library to be used. ``lapack`` uses the LAPACK\n        linear algebra library through Numpy and it is the most conventional way\n        of computing the SVD (deterministic result computed on CPU). ``arpack``\n        uses the ARPACK Fortran libraries accessible through Scipy (computation\n        on CPU). ``eigen`` computes the singular vectors through the\n        eigendecomposition of the covariance M.M' (computation on CPU).\n        ``randsvd`` uses the randomized_svd algorithm implemented in Sklearn\n        (computation on CPU). ``cupy`` uses the Cupy library for GPU computation\n        of the SVD as in the LAPACK version. ``eigencupy`` offers the same\n        method as with the ``eigen`` option but on GPU (through Cupy).\n        ``randcupy`` is an adaptation of the randomized_svd algorithm, where all\n        the computations are done on a GPU (through Cupy). ``pytorch`` uses the\n        Pytorch library for GPU computation of the SVD. ``eigenpytorch`` offers\n        the same method as with the ``eigen`` option but on GPU (through\n        Pytorch). ``randpytorch`` is an adaptation of the randomized_svd\n        algorithm, where all the linear algebra computations are done on a GPU\n        (through Pytorch).\n    nproc : None or int, optional\n        Number of processes for parallel computing. If None the number of\n        processes will be set to (cpu_count()/2).\n    min_frames_lib : int, optional\n        Minimum number of frames in the PCA reference library.\n    max_frames_lib : int, optional\n        Maximum number of frames in the PCA reference library for annuli beyond\n        10*FWHM. The more distant/decorrelated frames are removed from the\n        library.\n    tol : float, optional\n        Stopping criterion for choosing the number of PCs when ``ncomp``\n        is None. Lower values will lead to smaller residuals and more PCs.\n    scaling : {None, 'temp-mean', 'spat-mean', 'temp-standard', 'spat-standard'}\n        With None, no scaling is performed on the input data before SVD. With\n        \"temp-mean\" then temporal px-wise mean subtraction is done, with\n        \"spat-mean\" then the spatial mean is subtracted, with \"temp-standard\"\n        temporal mean centering plus scaling to unit variance is done and with\n        \"spat-standard\" spatial mean centering plus scaling to unit variance is\n        performed.\n    imlib : str, optional\n        See the documentation of the ``vip_hci.preproc.frame_rotate`` function.\n    interpolation : str, optional\n        See the documentation of the ``vip_hci.preproc.frame_rotate`` function.\n    collapse : {'median', 'mean', 'sum', 'trimmean'}, str optional\n        Sets the way of collapsing the frames for producing a final image.\n    full_output: boolean, optional\n        Whether to return the final median combined image only or with other\n        intermediate arrays.\n    verbose : bool, optional\n        If True prints to stdout intermediate info.\n\n    Returns\n    -------\n    frame : array_like, 2d\n        Median combination of the de-rotated cube.\n    If full_output is True:\n    array_out : array_like, 3d\n        Cube of residuals.\n    array_der : array_like, 3d\n        Cube residuals after de-rotation.\n\n    \"\"\"\n    if verbose:\n        global start_time\n        start_time = time_ini()\n\n    # ADI datacube\n    if cube.ndim == 3:\n        res = _pca_adi_ann(cube, angle_list, radius_int, fwhm, asize,\n                           n_segments, delta_rot, ncomp, svd_mode, nproc,\n                           min_frames_lib, max_frames_lib, tol, scaling, imlib,\n                           interpolation, collapse, full_output, verbose)\n\n        if verbose:\n            print('Done derotating and combining.')\n            timing(start_time)\n        if full_output:\n            cube_out, cube_der, frame = res\n            return cube_out, cube_der, frame\n        else:\n            return res\n\n    # ADI+mSDI (IFS) datacubes\n    elif cube.ndim == 4:\n        global ARRAY\n        ARRAY = cube\n\n        z, n, y_in, x_in = cube.shape\n        fwhm = int(np.round(np.mean(fwhm)))\n        n_annuli = int((y_in / 2 - radius_int) / asize)\n\n        if scale_list is None:\n            raise ValueError('Scaling factors vector must be provided')\n        else:\n            if np.array(scale_list).ndim > 1:\n                raise ValueError('Scaling factors vector is not 1d')\n            if not scale_list.shape[0] == z:\n                raise ValueError('Scaling factors vector has wrong length')\n\n        if verbose:\n            print('First PCA subtraction exploiting the spectral variability')\n            print('{} spectral channels per IFS frame'.format(z))\n            print('N annuli = {}, mean FWHM = {:.3f}'.format(n_annuli, fwhm))\n\n        res = pool_map(nproc, _pca_sdi_fr, fixed(range(n)), scale_list,\n                       radius_int, fwhm, asize, n_segments, delta_sep, ncomp,\n                       svd_mode, tol, scaling, imlib, interpolation, collapse,\n                       verbose=verbose)\n        residuals_cube_channels = np.array(res)\n\n        # Exploiting rotational variability\n        if verbose:\n            timing(start_time)\n            print('{} ADI frames'.format(n))\n\n        if ncomp2 is None:\n            if verbose:\n                msg = 'Skipping the second PCA subtraction'\n                print(msg)\n\n            cube_out = residuals_cube_channels\n            cube_der = cube_derotate(cube_out, angle_list, imlib=imlib,\n                                     interpolation=interpolation)\n            frame = cube_collapse(cube_der, mode=collapse)\n\n        else:\n            if verbose:\n                msg = 'Second PCA subtraction exploiting the angular '\n                msg += 'variability'\n                print(msg)\n\n            res = _pca_adi_ann(residuals_cube_channels, angle_list, radius_int,\n                               fwhm, asize, n_segments, delta_rot, ncomp2,\n                               svd_mode, nproc, min_frames_lib, max_frames_lib,\n                               tol, scaling, imlib, interpolation, collapse,\n                               full_output, verbose)\n            if full_output:\n                cube_out, cube_der, frame = res\n            else:\n                frame = res\n\n        if verbose:\n            print('Done derotating and combining.')\n            timing(start_time)\n        if full_output:\n            return cube_out, cube_der, frame\n        else:\n            return frame\n\n    else:\n        raise TypeError('Input array is not a cube or 3d array')\n\n\ndef pca_rdi_annular(cube, angle_list, cube_ref, radius_int=0, asize=1, ncomp=1,\n                    svd_mode='lapack', min_corr=0.9, fwhm=4,\n                    scaling='temp-standard', imlib='opencv',\n                    interpolation='lanczos4', collapse='median',\n                    full_output=False, verbose=True):\n    \"\"\" Annular PCA with Reference Library + Correlation + standardization\n\n    In the case of having a large number of reference images, e.g. for a survey\n    on a single instrument, we can afford a better selection of the library by\n    constraining the correlation with the median of the science dataset and by\n    working on an annulus-wise way. As with other local PCA algorithms in VIP\n    the number of principal components can be automatically adjusted by the\n    algorithm by minmizing the residuals in the given patch (a la LOCI).\n\n    Parameters\n    ----------\n    cube : array_like, 3d\n        Input science cube.\n    angle_list : array_like, 1d\n        Corresponding parallactic angle for each frame.\n    cube_ref : array_like, 3d\n        Reference library cube. For Reference Star Differential Imaging.\n    radius_int : int, optional\n        The radius of the innermost annulus. By default is 0, if >0 then the\n        central circular area is discarded.\n    asize : float, optional\n        The size of the annuli, in FWHM. Default is 3.\n    ncomp : int, optional\n        How many PCs are kept. If none it will be automatically determined.\n    svd_mode : {'lapack', 'arpack', 'eigen', 'randsvd', 'cupy', 'eigencupy', 'randcupy'}, str\n        Switch for the SVD method/library to be used. ``lapack`` uses the LAPACK\n        linear algebra library through Numpy and it is the most conventional way\n        of computing the SVD (deterministic result computed on CPU). ``arpack``\n        uses the ARPACK Fortran libraries accessible through Scipy (computation\n        on CPU). ``eigen`` computes the singular vectors through the\n        eigendecomposition of the covariance M.M' (computation on CPU).\n        ``randsvd`` uses the randomized_svd algorithm implemented in Sklearn\n        (computation on CPU). ``cupy`` uses the Cupy library for GPU computation\n        of the SVD as in the LAPACK version. ``eigencupy`` offers the same\n        method as with the ``eigen`` option but on GPU (through Cupy).\n        ``randcupy`` is an adaptation of the randomized_svd algorith, where all\n        the computations are done on a GPU.\n    min_corr : int, optional\n        Level of linear correlation between the library patches and the median\n        of the science. Deafult is 0.9.\n    fwhm : float, optional\n        Known size of the FHWM in pixels to be used. Deafult is 4.\n    scaling : {None, 'temp-mean', 'spat-mean', 'temp-standard', 'spat-standard'}\n        With None, no scaling is performed on the input data before SVD. With\n        \"temp-mean\" then temporal px-wise mean subtraction is done, with\n        \"spat-mean\" then the spatial mean is subtracted, with \"temp-standard\"\n        temporal mean centering plus scaling to unit variance is done and with\n        \"spat-standard\" spatial mean centering plus scaling to unit variance is\n        performed.\n    imlib : str, optional\n        See the documentation of the ``vip_hci.preproc.frame_rotate`` function.\n    interpolation : str, optional\n        See the documentation of the ``vip_hci.preproc.frame_rotate`` function.\n    collapse : {'median', 'mean', 'sum', 'trimmean'}, str optional\n        Sets the way of collapsing the frames for producing a final image.\n    full_output: boolean, optional\n        Whether to return the final median combined image only or with other\n        intermediate arrays.\n    verbose : {True, False}, bool optional\n        If True prints to stdout intermediate info.\n\n    Returns\n    -------\n    frame : array_like, 2d\n        Median combination of the de-rotated cube.\n    If full_output is True:\n    array_out : array_like, 3d\n        Cube of residuals.\n    array_der : array_like, 3d\n        Cube residuals after de-rotation.\n\n    \"\"\"\n    def define_annuli(angle_list, ann, n_annuli, fwhm, radius_int,\n                      annulus_width,\n                      verbose):\n        \"\"\" Defining the annuli \"\"\"\n        if ann == n_annuli - 1:\n            inner_radius = radius_int + (ann * annulus_width - 1)\n        else:\n            inner_radius = radius_int + ann * annulus_width\n        ann_center = (inner_radius + (annulus_width / 2.0))\n\n        if verbose:\n            msg2 = 'Annulus {}, Inn radius = {:.2f}, Ann center = {:.2f} '\n            print(msg2.format(int(ann + 1), inner_radius, ann_center))\n        return inner_radius, ann_center\n\n    def fr_ref_correlation(vector, matrix):\n        \"\"\" Getting the correlations \"\"\"\n        lista = []\n        for i in range(matrix.shape[0]):\n            pears, _ = stats.pearsonr(vector, matrix[i])\n            lista.append(pears)\n\n        return lista\n\n    def do_pca_annulus(ncomp, matrix, svd_mode, noise_error, data_ref):\n        \"\"\" PCA for given annulus \"\"\"\n        V = get_eigenvectors(ncomp, matrix, svd_mode,\n                             noise_error=noise_error,\n                             data_ref=data_ref, debug=False)\n        # new variables as linear combinations of the original variables in\n        # matrix.T with coefficientes from EV\n        transformed = np.dot(V, matrix.T)\n        reconstructed = np.dot(V.T, transformed)\n        residuals = matrix - reconstructed.T\n        return residuals, V.shape[0]\n\n    #---------------------------------------------------------------------------\n    array = cube\n    array_ref = cube_ref\n    if array.ndim != 3:\n        raise TypeError('Input array is not a cube or 3d array.')\n    if array.shape[0] != angle_list.shape[0]:\n        raise TypeError(\n            'Input vector or parallactic angles has wrong length.')\n\n    n, y, _ = array.shape\n    if verbose:  start_time = time_ini()\n\n    angle_list = check_pa_vector(angle_list)\n\n    annulus_width = asize * fwhm  # equal size for all annuli\n    n_annuli = int(np.floor((y / 2 - radius_int) / annulus_width))\n    if verbose:\n        msg = '# annuli = {}, Ann width = {}, FWHM = {:.3f}\\n'\n        print(msg.format(n_annuli, annulus_width, fwhm))\n        print('PCA will be done locally per annulus and per quadrant.\\n')\n\n    cube_out = np.zeros_like(array)\n    for ann in range(n_annuli):\n        inner_radius, _ = define_annuli(angle_list, ann, n_annuli, fwhm,\n                                        radius_int, annulus_width, verbose)\n        indices = get_annulus(array[0], inner_radius, annulus_width,\n                              output_indices=True)\n        yy = indices[0]\n        xx = indices[1]\n\n        matrix = array[:, yy, xx]  # shape [nframes x npx_ann]\n        matrix_ref = array_ref[:, yy, xx]\n\n        corr = fr_ref_correlation(np.median(matrix, axis=0), matrix_ref)\n        indcorr = np.where(np.abs(corr) >= min_corr)\n        data_ref = matrix_ref[indcorr]\n        nfrslib = data_ref.shape[0]\n\n        if nfrslib < 5:\n            msg = 'Too few frames left (<5) fulfill the given correlation'\n            msg += ' level. Try decreasing it'\n            raise RuntimeError(msg)\n\n        matrix = matrix_scaling(matrix, scaling)\n        data_ref = matrix_scaling(data_ref, scaling)\n\n        residuals, ncomps = do_pca_annulus(ncomp, matrix, svd_mode, 10e-3,\n                                           data_ref)\n        cube_out[:, yy, xx] = residuals\n\n        if verbose in [1, 2]:\n            print('# frames in LIB = {}'.format(nfrslib))\n            print('# PCs = {}'.format(ncomps))\n            print('Done PCA with {} for current annulus'.format(svd_mode))\n            timing(start_time)\n\n    cube_der = cube_derotate(cube_out, angle_list, imlib=imlib,\n                             interpolation=interpolation)\n    frame = cube_collapse(cube_der, mode=collapse)\n    if verbose:\n        print('Done derotating and combining.')\n        timing(start_time)\n    if full_output:\n        return cube_out, cube_der, frame\n    else:\n        return frame\n\n\n################################################################################\n# Help functions (encapsulating portions of the main algorithm)\n################################################################################\n\ndef _pca_sdi_fr(fr, wl, radius_int, fwhm, asize, n_segments, delta_sep,\n                ncomp, svd_mode, tol, scaling, imlib, interpolation, collapse):\n    \"\"\" Optimized PCA subtraction on a multi-spectral frame (IFS data).\n    \"\"\"\n    z, n, y_in, x_in = ARRAY.shape\n\n    scale_list = check_scal_vector(wl)\n    # rescaled cube, aligning speckles\n    multispec_fr = scwave(ARRAY[:, fr, :, :], scale_list,\n                          imlib=imlib, interpolation=interpolation)[0]\n\n    # Exploiting spectral variability (radial movement)\n    fwhm = int(np.round(np.mean(fwhm)))\n    n_annuli = int((y_in / 2 - radius_int) / asize)\n\n    if isinstance(n_segments, int):\n        n_segments = [n_segments for _ in range(n_annuli)]\n    elif n_segments == 'auto':\n        n_segments = list()\n        n_segments.append(2)  # for first annulus\n        n_segments.append(3)  # for second annulus\n        ld = 2 * np.tan(360 / 4 / 2) * asize\n        for i in range(2, n_annuli):  # rest of annuli\n            radius = i * asize\n            ang = np.rad2deg(2 * np.arctan(ld / (2 * radius)))\n            n_segments.append(int(np.ceil(360 / ang)))\n\n    cube_res = np.zeros_like(multispec_fr)    # shape (z, resc_y, resc_x)\n\n    if isinstance(delta_sep, tuple):\n        delta_sep_vec = np.linspace(delta_sep[0], delta_sep[1], n_annuli)\n    else:\n        delta_sep_vec = [delta_sep] * n_annuli\n\n    for ann in range(n_annuli):\n        if ann == n_annuli - 1:\n            inner_radius = radius_int + (ann * asize - 1)\n        else:\n            inner_radius = radius_int + ann * asize\n        ann_center = inner_radius + (asize / 2)\n\n        indices = get_annulus_segments(multispec_fr[0], inner_radius, asize,\n                                       n_segments[ann])\n        # Library matrix is created for each segment and scaled if needed\n        for seg in range(n_segments[ann]):\n            yy = indices[seg][0]\n            xx = indices[seg][1]\n            matrix = multispec_fr[:, yy, xx]  # shape (z, npx_annsegm)\n            matrix = matrix_scaling(matrix, scaling)\n\n            for j in range(z):\n                indices_left = _find_indices_sdi(wl, ann_center, j,\n                                                 fwhm, delta_sep_vec[ann])\n                matrix_ref = matrix[indices_left]\n                curr_frame = matrix[j]  # current frame\n                V = get_eigenvectors(ncomp, matrix_ref, svd_mode,\n                                     noise_error=tol, debug=False)\n                transformed = np.dot(curr_frame, V.T)\n                reconstructed = np.dot(transformed.T, V)\n                residuals = curr_frame - reconstructed\n                # return residuals, V.shape[0], matrix_ref.shape[0]\n                cube_res[j, yy, xx] = residuals\n\n    frame_desc = scwave(cube_res, scale_list, full_output=False, inverse=True,\n                        y_in=y_in, x_in=x_in, imlib=imlib,\n                        interpolation=interpolation, collapse=collapse)\n    return frame_desc\n\n\ndef _pca_adi_ann(cube, angle_list, radius_int=0, fwhm=4, asize=2, n_segments=1,\n                 delta_rot=1, ncomp=1, svd_mode='lapack', nproc=None,\n                 min_frames_lib=2, max_frames_lib=200, tol=1e-1, scaling=None,\n                 imlib='opencv', interpolation='lanczos4', collapse='median',\n                 full_output=False, verbose=1):\n    \"\"\" PCA exploiting angular variability (ADI fashion).\n    \"\"\"\n    array = cube\n    if array.ndim != 3:\n        raise TypeError('Input array is not a cube or 3d array')\n    if array.shape[0] != angle_list.shape[0]:\n        raise TypeError('Input vector or parallactic angles has wrong length')\n\n    n, y, _ = array.shape\n\n    angle_list = check_pa_vector(angle_list)\n    n_annuli = int((y / 2 - radius_int) / asize)\n\n    if isinstance(n_segments, int):\n        n_segments = [n_segments for _ in range(n_annuli)]\n    elif n_segments == 'auto':\n        n_segments = list()\n        n_segments.append(2)  # for first annulus\n        n_segments.append(3)  # for second annulus\n        ld = 2 * np.tan(360 / 4 / 2) * asize\n        for i in range(2, n_annuli):  # rest of annuli\n            radius = i * asize\n            ang = np.rad2deg(2 * np.arctan(ld / (2 * radius)))\n            n_segments.append(int(np.ceil(360 / ang)))\n\n    if verbose:\n        msg = '# annuli = {}, Ann width = {}, FWHM = {:.3f}'\n        print(msg.format(n_annuli, asize, fwhm))\n        print('PCA per annulus (or annular sectors):')\n\n    if nproc is None:   # Hyper-threading \"duplicates\" the cores -> cpu_count/2\n        nproc = cpu_count() // 2\n\n    # The annuli are built, and the corresponding PA thresholds for frame\n    # rejection are calculated (at the center of the annulus)\n    cube_out = np.zeros_like(array)\n    for ann in range(n_annuli):\n        if isinstance(ncomp, list) or isinstance(ncomp, np.ndarray):\n            if len(ncomp) == n_annuli:\n                ncompann = ncomp[ann]\n            else:\n                msge = 'If ncomp is a list, it must match the number of annuli'\n                raise TypeError(msge)\n        else:\n            ncompann = ncomp\n\n        n_segments_ann = n_segments[ann]\n        res_ann_par = _define_annuli(angle_list, ann, n_annuli, fwhm,\n                                     radius_int, asize, delta_rot,\n                                     n_segments_ann, verbose)\n        pa_thr, inner_radius, ann_center = res_ann_par\n        indices = get_annulus_segments(array[0], inner_radius, asize,\n                                       n_segments_ann)\n        # Library matrix is created for each segment and scaled if needed\n        for j in range(n_segments_ann):\n            yy = indices[j][0]\n            xx = indices[j][1]\n            matrix_segm = array[:, yy, xx]  # shape [nframes x npx_segment]\n            matrix_segm = matrix_scaling(matrix_segm, scaling)\n\n            res = pool_map(nproc, do_pca_patch, matrix_segm, fixed(range(n)),\n                           angle_list, fwhm, pa_thr, ann_center, svd_mode,\n                           ncompann, min_frames_lib, max_frames_lib, tol,\n                           verbose=False)\n\n            res = np.array(res)\n            residuals = np.array(res[:, 0])\n            ncomps = res[:, 1]\n            nfrslib = res[:, 2]\n            for fr in range(n):\n                cube_out[fr][yy, xx] = residuals[fr]\n\n            # number of frames in library printed for each annular quadrant\n            # number of PCs printed for each annular quadrant\n            if verbose == 2:\n                descriptive_stats(nfrslib, verbose=verbose, label='\\tLIBsize: ')\n                descriptive_stats(ncomps, verbose=verbose, label='\\tNum PCs: ')\n\n        if verbose == 2:\n            print('Done PCA with {} for current annulus'.format(svd_mode))\n        if verbose:\n            timing(start_time)\n\n    # Cube is derotated according to the parallactic angle and collapsed\n    cube_der = cube_derotate(cube_out, angle_list, imlib=imlib,\n                             interpolation=interpolation)\n    frame = cube_collapse(cube_der, mode=collapse)\n    if verbose:\n        print('Done derotating and combining.')\n        timing(start_time)\n    if full_output:\n        return cube_out, cube_der, frame\n    else:\n        return frame\n\n\ndef do_pca_patch(matrix, frame, angle_list, fwhm, pa_threshold, ann_center,\n                 svd_mode, ncomp, min_frames_lib, max_frames_lib, tol):\n    \"\"\" Does the SVD/PCA for each frame patch (small matrix). For each frame we\n    find the frames to be rejected depending on the amount of rotation. The\n    library is also truncated on the other end (frames too far or which have\n    rotated more) which are more decorrelated to keep the computational cost\n    lower. This truncation is done on the annuli after 10*FWHM and the goal is\n    to keep min(num_frames/2, 200) in the library.\n    \"\"\"\n    if pa_threshold != 0:\n        if ann_center > fwhm*10:    # TODO: 10*FWHM optimal? new parameter?\n            indices_left = _find_indices_adi(angle_list, frame, pa_threshold,\n                                             truncate=True,\n                                             max_frames=max_frames_lib)\n        else:\n            indices_left = _find_indices_adi(angle_list, frame, pa_threshold,\n                                             truncate=False)\n\n        data_ref = matrix[indices_left]\n\n        if data_ref.shape[0] <= min_frames_lib:\n            msg = 'Too few frames left in the PCA library. '\n            msg += 'Try decreasing either delta_rot or min_frames_lib.'\n            raise RuntimeError(msg)\n    else:\n        data_ref = matrix\n\n    data = data_ref\n    curr_frame = matrix[frame]                     # current frame\n\n    V = get_eigenvectors(ncomp, data, svd_mode, noise_error=tol, debug=False)\n\n    transformed = np.dot(curr_frame, V.T)\n    reconstructed = np.dot(transformed.T, V)\n    residuals = curr_frame - reconstructed\n    return residuals, V.shape[0], data_ref.shape[0]\n\n\n\n\n", "meta": {"hexsha": "d11adcf95c371f327c6e5094278a6dbc95a371c3", "size": 28432, "ext": "py", "lang": "Python", "max_stars_repo_path": "vip_hci/pca/pca_local.py", "max_stars_repo_name": "FaustineAstro/VIP", "max_stars_repo_head_hexsha": "349875f51358948589ccfb4d94808472e7fc90cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vip_hci/pca/pca_local.py", "max_issues_repo_name": "FaustineAstro/VIP", "max_issues_repo_head_hexsha": "349875f51358948589ccfb4d94808472e7fc90cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vip_hci/pca/pca_local.py", "max_forks_repo_name": "FaustineAstro/VIP", "max_forks_repo_head_hexsha": "349875f51358948589ccfb4d94808472e7fc90cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.6342229199, "max_line_length": 93, "alphanum_fraction": 0.6183877321, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.29421498454004374, "lm_q1q2_score": 0.17987774198738718}}
{"text": "#!/usr/bin/env python\n# encoding: utf-8\n\n################################################################################\n#\n#   RMG - Reaction Mechanism Generator\n#\n#   Copyright (c) 2009-2011 by the RMG Team (rmg_dev@mit.edu)\n#\n#   Permission is hereby granted, free of charge, to any person obtaining a\n#   copy of this software and associated documentation files (the 'Software'),\n#   to deal in the Software without restriction, including without limitation\n#   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n#   and/or sell copies of the Software, and to permit persons to whom the\n#   Software is furnished to do so, subject to the following conditions:\n#\n#   The above copyright notice and this permission notice shall be included in\n#   all copies or substantial portions of the Software.\n#\n#   THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n#   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n#   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n#   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n#   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n#   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n#   DEALINGS IN THE SOFTWARE.\n#\n################################################################################\n\n\"\"\"\nContains the :class:`Geometry` class for working with the three-dimensional\ngeometry of molecules and evaluating properties based on the geometry\ninformation, e.g. moments of inertia.\n\"\"\"\n\nimport numpy\nimport cython\n\nfrom rmgpy.quantity import Quantity, constants\n\n################################################################################\n\nclass GeometryError(Exception):\n    \"\"\"\n    An exception class for errors that occur while working with molecular\n    geometries. Pass a string describing the circumstances that caused the\n    exceptional behavior.\n    \"\"\"\n    pass\n\n################################################################################\n\nclass Geometry:\n    \"\"\"\n    The three-dimensional geometry of a molecular configuration. The attributes\n    are:\n\n    =============== ======================= ====================================\n    Attribute       Type                    Description\n    =============== ======================= ====================================\n    `coordinates`   :class:`numpy.ndarray`  An N x 3 array containing the 3D coordinates of each atom\n    `number`        :class:`numpy.ndarray`  An array containing the integer atomic number of each atom\n    `mass`          :class:`numpy.ndarray`  An array containing the atomic mass in kg/mol of each atom\n    =============== ======================= ====================================\n\n    The integer index of each atom is consistent across all three attributes.\n    \"\"\"\n    \n    def __init__(self, coordinates, number, mass):\n        self.coordinates = Quantity(coordinates).values\n        self.number = Quantity(number).values\n        self.mass = Quantity(mass).values\n    \n    def __repr__(self):\n        \"\"\"\n        Return a string representation that can be used to reconstruct the\n        object.\n        \"\"\"\n        coordinates = '(['\n        for i in range(self.coordinates.shape[0]):\n            if i > 0: coordinates += ', '\n            coordinates += '[{0}]'.format(','.join(['{0:g}'.format(self.coordinates[i,j]) for j in range(self.coordinates.shape[1])]))\n        coordinates += '],\"m\")'\n        number = '[{0}]'.format(','.join(['{0:d}'.format(n) for n in self.number]))\n        mass = '([{0}],\"g/mol\")'.format(','.join(['{0:g}'.format(m * 1000.) for m in self.mass]))\n        return 'Geometry(coordinates={0}, number={1}, mass={2})'.format(coordinates, number, mass)\n\n    def __reduce__(self):\n        \"\"\"\n        A helper function used when pickling an object.\n        \"\"\"\n        return (Geometry, (self.coordinates, self.number, self.mass))\n\n    def getTotalMass(self, atoms=None):\n        \"\"\"\n        Calculate and return the total mass of the atoms in the geometry in \n        kg/mol. If a list `atoms` of atoms is specified, only those atoms will\n        be used to calculate the center of mass. Otherwise, all atoms will be\n        used.\n        \"\"\"\n        if atoms is None: atoms = range(len(self.mass))\n        return sum([self.mass[atom] for atom in atoms])\n\n    def getCenterOfMass(self, atoms=None):\n        \"\"\"\n        Calculate and return the [three-dimensional] position of the center of\n        mass of the current geometry. If a list `atoms` of atoms is specified,\n        only those atoms will be used to calculate the center of mass. \n        Otherwise, all atoms will be used.\n        \"\"\"\n\n        cython.declare(center=numpy.ndarray, mass=cython.double, atom=cython.int)\n\n        if atoms is None: atoms = range(len(self.mass))\n        center = numpy.zeros(3, numpy.float64); mass = 0.0\n        for atom in atoms:\n            center += self.mass[atom] * self.coordinates[atom]\n            mass += self.mass[atom]\n        center /= mass\n        return center\n\n    def getMomentOfInertiaTensor(self):\n        \"\"\"\n        Calculate and return the moment of inertia tensor for the current \n        geometry in kg*m^2. If the coordinates are not at the center of mass,\n        they are temporarily shifted there for the purposes of this calculation.\n        \"\"\"\n        \n        cython.declare(I=numpy.ndarray, mass=cython.double, atom=cython.int)\n        cython.declare(coord0=numpy.ndarray, coord=numpy.ndarray, centerOfMass=numpy.ndarray)\n\n        I = numpy.zeros((3,3), numpy.float64)\n        centerOfMass = self.getCenterOfMass()\n        for atom, coord0 in enumerate(self.coordinates):\n            mass = self.mass[atom] / constants.Na\n            coord = coord0 - centerOfMass\n            I[0,0] += mass * (coord[1] * coord[1] + coord[2] * coord[2])\n            I[1,1] += mass * (coord[0] * coord[0] + coord[2] * coord[2])\n            I[2,2] += mass * (coord[0] * coord[0] + coord[1] * coord[1])\n            I[0,1] -= mass * coord[0] * coord[1]\n            I[0,2] -= mass * coord[0] * coord[2]\n            I[1,2] -= mass * coord[1] * coord[2]\n        I[1,0] = I[0,1]\n        I[2,0] = I[0,2]\n        I[2,1] = I[1,2]\n        \n        return I\n    \n    def getPrincipalMomentsOfInertia(self):\n        \"\"\"\n        Calculate and return the principal moments of inertia and corresponding \n        principal axes for the current geometry. The moments of inertia are in\n        kg*m^2, while the principal axes have unit length.\n        \"\"\"\n        I0 = self.getMomentOfInertiaTensor()\n        # Since I0 is real and symmetric, diagonalization is always possible\n        I, V = numpy.linalg.eig(I0)\n        return I, V\n    \n    def getInternalReducedMomentOfInertia(self, pivots, top1):\n        \"\"\"\n        Calculate and return the reduced moment of inertia for an internal\n        torsional rotation around the axis defined by the two atoms in \n        `pivots`. The list `top1` contains the atoms that should be considered\n        as part of the rotating top; this list should contain the pivot atom\n        connecting the top to the rest of the molecule.\tThe procedure used is\n        that of Pitzer [1]_, which is described as :math:`I^{(2,3)}` by East\n        and Radom [2]_. In this procedure, the molecule is divided into two\n        tops: those at either end of the hindered rotor bond. The moment of\n        inertia of each top is evaluated using an axis passing through the\n        center of mass of both tops. Finally, the reduced moment of inertia is\n        evaluated from the moment of inertia of each top via the formula\n\n        .. math:: \\\\frac{1}{I^{(2,3)}} = \\\\frac{1}{I_1} + \\\\frac{1}{I_2}\n        \n        .. [1] Pitzer, K. S. *J. Chem. Phys.* **14**, p. 239-243 (1946).\n        \n        .. [2] East, A. L. L. and Radom, L. *J. Chem. Phys.* **106**, p. 6655-6674 (1997).\n        \n        \"\"\"\n\n        cython.declare(Natoms=cython.int, top2=list, top1CenterOfMass=numpy.ndarray, top2CenterOfMass=numpy.ndarray)\n        cython.declare(axis=numpy.ndarray, I1=cython.double, I2=cython.double, atom=cython.int, i=cython.int)\n\n        # The total number of atoms in the geometry\n        Natoms = len(self.mass)\n\n        # Check that exactly one pivot atom is in the specified top\n        if pivots[0] not in top1 and pivots[1] not in top1:\n            raise GeometryError('No pivot atom included in top; you must specify which pivot atom belongs with the specified top.')\n        elif pivots[0] in top1 and pivots[1] in top1:\n            raise GeometryError('Both pivot atoms included in top; you must specify only one pivot atom that belongs with the specified top.')\n\n        # Determine atoms in other top\n        top2 = []\n        for i in range(Natoms):\n            if i not in top1: top2.append(i)\n        \n        # Determine centers of mass of each top\n        top1CenterOfMass = self.getCenterOfMass(top1)\n        top2CenterOfMass = self.getCenterOfMass(top2)\n        \n        # Determine axis of rotation\n        axis = (top1CenterOfMass - top2CenterOfMass)\n        axis /= numpy.linalg.norm(axis)\n        \n        # Determine moments of inertia of each top\n        I1 = 0.0\n        for atom in top1:\n            r1 = self.coordinates[atom,:] - top1CenterOfMass\n            r1 -= numpy.dot(r1, axis) * axis\n            I1 += self.mass[atom] / constants.Na * numpy.linalg.norm(r1)**2\n        I2 = 0.0\n        for atom in top2:\n            r2 = self.coordinates[atom,:] - top2CenterOfMass\n            r2 -= numpy.dot(r2, axis) * axis\n            I2 += self.mass[atom] / constants.Na * numpy.linalg.norm(r2)**2\n        \n        return 1.0 / (1.0 / I1 + 1.0 / I2)\n", "meta": {"hexsha": "d7bfe428ca1ca702e3ebaa4029645c045397b09f", "size": 9718, "ext": "py", "lang": "Python", "max_stars_repo_path": "rmgpy/cantherm/geometry.py", "max_stars_repo_name": "sean-v8/RMG-Py", "max_stars_repo_head_hexsha": "7cc7c3bfb330786526c56113d98c785bcaaa161a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rmgpy/cantherm/geometry.py", "max_issues_repo_name": "sean-v8/RMG-Py", "max_issues_repo_head_hexsha": "7cc7c3bfb330786526c56113d98c785bcaaa161a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rmgpy/cantherm/geometry.py", "max_forks_repo_name": "sean-v8/RMG-Py", "max_forks_repo_head_hexsha": "7cc7c3bfb330786526c56113d98c785bcaaa161a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.1727272727, "max_line_length": 142, "alphanum_fraction": 0.594772587, "include": true, "reason": "import numpy", "num_tokens": 2303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.17987773403724594}}
{"text": "'''\nhttps://github.com/zhangqianhui/Conditional-GAN\n\nModified by Wei Chen(wchen@cqu.edu.cn), Qiuli Wang(wangqiuli@cqu.edu.cn)\n7/12/2020\n'''\n\nfrom utils import save_images, vis_square,sample_label,sample_masks, sample_masks_test\nfrom tensorflow.contrib.layers.python.layers import xavier_initializer\nimport cv2\nfrom ops import *\nimport tensorflow as tf\nimport numpy as np\n\nclass CMGAN(object):\n    def __init__(self, data_ob, train_dir, eval_dir, test_dir, output_size, learn_rate, batch_size, z_dim, y_dim, log_dir\n         , model_path, load = False, gf_dim=64, df_dim = 64, output_c_dim=1, L1_lambda=100):\n\n        self.data_ob = data_ob\n        self.train_dir = train_dir\n        self.eval_dir = eval_dir\n        self.test_dir = test_dir\n        self.output_size = output_size\n        self.learn_rate = learn_rate\n        self.batch_size = batch_size\n        self.z_dim = z_dim\n        self.y_dim = y_dim\n        self.load = load\n        self.log_dir = log_dir\n        self.model_path = model_path\n        self.channel = self.data_ob.shape[2]\n        self.images = tf.placeholder(tf.float32, [batch_size, self.output_size, self.output_size, self.channel])\n        self.masks = tf.placeholder(tf.float32, [batch_size, self.output_size, self.output_size, self.channel])\n        self.lungwindow = tf.placeholder(tf.float32, [batch_size, self.output_size, self.output_size, self.channel])\n        self.mediastinumwindow = tf.placeholder(tf.float32, [batch_size, self.output_size, self.output_size, self.channel])\n\n        self.L1_lambda = L1_lambda\n        self.z = tf.placeholder(tf.float32, [self.batch_size, self.z_dim])\n        self.y = tf.placeholder(tf.float32, [self.batch_size, self.y_dim])\n        self.training_step = 50000\n\n        print('image shape: ', self.images.get_shape().as_list())\n\n        self.gf_dim = gf_dim\n        self.df_dim = df_dim\n        self.output_c_dim = output_c_dim\n        self.d_bn1 = batch_norm(name='d_bn1')\n        self.d_bn2 = batch_norm(name='d_bn2')\n        self.d_bn3 = batch_norm(name='d_bn3')\n\n        self.g_bn_e2 = batch_norm(name='g_bn_e2')\n        self.g_bn_e3 = batch_norm(name='g_bn_e3')\n        self.g_bn_e4 = batch_norm(name='g_bn_e4')\n        self.g_bn_e5 = batch_norm(name='g_bn_e5')\n        self.g_bn_e6 = batch_norm(name='g_bn_e6')\n        self.g_bn_e7 = batch_norm(name='g_bn_e7')\n        self.g_bn_e8 = batch_norm(name='g_bn_e8')\n\n        self.g_bn_d1 = batch_norm(name='g_bn_d1')\n        self.g_bn_d2 = batch_norm(name='g_bn_d2')\n        self.g_bn_d3 = batch_norm(name='g_bn_d3')\n        self.g_bn_d4 = batch_norm(name='g_bn_d4')\n        self.g_bn_d5 = batch_norm(name='g_bn_d5')\n        self.g_bn_d6 = batch_norm(name='g_bn_d6')\n        self.g_bn_d7 = batch_norm(name='g_bn_d7')\n\t\n\t# build model\n    def build_model(self):\n        print('Building the model:')\n        self.real_A = self.masks\n        print('shape of real_A: ', self.real_A.get_shape().as_list())\n\n        self.fake_B = self.generator(self.real_A, self.y)\n        print('shape of self.y: ', self.y.get_shape().as_list())\n        print('shape of fake_B: ', self.fake_B.get_shape().as_list())\n\n        self.lung_logits, self.fake_lungwindow = self.decorator_lung_window(self.fake_B, self.lungwindow, self.y)\n        self.mediastinum_logits, self.fake_mediastinumwindow = self.decorator_mediastinum_window(self.fake_B, self.mediastinumwindow, self.y)\n        self.real_all_masks_images = tf.concat([self.real_A, self.images], 3)\n        self.fake_all_masks_images = tf.concat([self.real_A, self.fake_B], 3)\n\n        self.D_all, self.D_all_logits = self.discriminator_all(self.real_all_masks_images, self.y, reuse = False)\n        self.D_all_, self.D_all_logits_ = self.discriminator_all(self.fake_all_masks_images, self.y, reuse = True)\n\n        self.d_all_loss_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits = self.D_all_logits, labels = tf.ones_like(self.D_all)))\n        self.d_all_loss_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits = self.D_all_logits_, labels = tf.zeros_like(self.D_all_)))\n        \n        self.y_lobu = tf.slice(self.y, [0,0], [64,5])\n        self.y_spicu = tf.slice(self.y, [0,5], [64,5])\n        self.y_mali = tf.slice(self.y, [0,10], [64,5])\n        print('shape of lobu label ', self.y_lobu.get_shape().as_list())\n        print('shape of spicu label ', self.y_spicu.get_shape().as_list())\n        print('shape of mali label ', self.y_mali.get_shape().as_list())\n\n        # the loss of classify\n        self.pre_lung, self.pre_lung_logits = self.classify_lung(self.fake_lungwindow)\n        self.d_loss_classify_lung = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.pre_lung, labels=self.y_spicu))\n\n        self.pre_mediastinum, self.pre_mediastinum_logits = self.classify_mediastinum(self.fake_mediastinumwindow)\n        self.d_loss_classify_mediastinum = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.pre_mediastinum, labels=self.y_lobu))\n\n        # the loss of malignancy prediction\n        self.pre_lung_mali, self.pre_lung_logits_mali = self.classify_lung_mali(self.fake_lungwindow)\n        self.d_loss_classify_lung_mali = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.pre_lung_mali, labels=self.y_mali))\n\n        self.pre_mediastinum_mali, self.pre_mediastinum_logits_mali = self.classify_mediastinum_mali(self.fake_mediastinumwindow)\n        self.d_loss_classify_mediastinum_mali = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.pre_mediastinum_mali, labels=self.y_mali))\n\n\n        # the loss of generator network\n        self.g_lung_loss = self.L1_lambda * tf.reduce_mean(tf.square(self.lungwindow - self.fake_lungwindow))\n        self.g_mediastinum_loss = self.L1_lambda * tf.reduce_mean(tf.square(self.mediastinumwindow - self.fake_mediastinumwindow))\n        self.g_all_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.D_all_logits_, labels=tf.ones_like(self.D_all_))) \\\n                        + self.L1_lambda * tf.reduce_mean(tf.square(self.images - self.fake_B))\n\n        # the loss of decorator network\n        self.d_all_loss = self.d_all_loss_fake + self.d_all_loss_real + self.d_loss_classify_lung + self.d_loss_classify_mediastinum + self.d_loss_classify_lung_mali + self.d_loss_classify_mediastinum_mali\n        self.d_c_loss = self.d_loss_classify_lung + self.d_loss_classify_mediastinum + self.d_loss_classify_lung_mali + self.d_loss_classify_mediastinum_mali \n        self.d_loss = self.d_all_loss\n        self.g_loss = self.g_lung_loss + self.g_mediastinum_loss + self.g_all_loss\n\n        t_vars = tf.trainable_variables()\n        self.d_vars = [var for var in t_vars if 'd_' in var.name]\n        self.c_vars = [var for var in t_vars if 'c_' in var.name]\n        self.g_vars = [var for var in t_vars if 'g_' in var.name]\n\n        self.saver = tf.train.Saver(keep_checkpoint_every_n_hours=0.5)\n\n    def train(self,args):\n    \n        opti_D = tf.train.AdamOptimizer(args.lr, beta1=args.beta1) \\\n                          .minimize(self.d_loss, var_list=self.d_vars)\n        opti_G = tf.train.AdamOptimizer(args.lr, beta1=args.beta1) \\\n                          .minimize(self.g_loss, var_list=self.g_vars)\n        opti_C = tf.train.AdamOptimizer(args.lr, beta1=args.beta1) \\\n                          .minimize(self.d_c_loss, var_list=self.c_vars)\n\n        init = tf.global_variables_initializer()\n        config = tf.ConfigProto()\n        config.gpu_options.allow_growth = True\n\n        with tf.Session(config=config) as sess:\n            sess.run(init)\n            if self.load:\n            \t# load pretrained model \n                print('loading:')\n                self.saver = tf.train.import_meta_graph('./model/model.ckpt-20201.meta')  # default to save all variable\n                self.saver.restore(sess, tf.train.latest_checkpoint('./model/'))\n           \n            self.writer = tf.summary.FileWriter(\"./logs\", sess.graph)\n            summary_writer = tf.summary.FileWriter(self.log_dir, graph=sess.graph)\n\n            step = 0\n            while step <= self.training_step:\n                realbatch_array, real_lungs, real_mediastinums, realmasks, real_labels = self.data_ob.getNext_batch(step,batch_size=self.batch_size)\n                batch_z = np.random.uniform(-1, 1, size=[self.batch_size, self.z_dim])\n                sess.run([opti_D],feed_dict={self.images: realbatch_array, self.lungwindow: real_lungs, self.mediastinumwindow: real_mediastinums, self.masks: realmasks, self.z: batch_z, self.y: real_labels})\n                sess.run([opti_G],feed_dict={self.images: realbatch_array, self.lungwindow: real_lungs, self.mediastinumwindow: real_mediastinums, self.masks: realmasks, self.z: batch_z, self.y: real_labels})\n                sess.run([opti_C],feed_dict={self.images: realbatch_array, self.lungwindow: real_lungs, self.mediastinumwindow: real_mediastinums, self.masks: realmasks, self.z: batch_z, self.y: real_labels})\n                \n                if np.mod(step, 50) == 1 and step != 0:\n                    print('Saving...')\n                    sample_images, lungwindow, mediastinumwindow = sess.run([self.fake_B, self.fake_lungwindow, self.fake_mediastinumwindow], feed_dict={self.images: realbatch_array, self.lungwindow: real_lungs, self.mediastinumwindow: real_mediastinums, self.masks: realmasks, self.z: batch_z, self.y: real_labels})\n                    save_images(sample_images, [8, 8],\n                                './{}/{:04d}_sample.png'.format(self.train_dir, step))\n                    save_images(lungwindow, [8, 8],\n                                './{}/{:04d}_lung.png'.format(self.train_dir, step))\n                    save_images(mediastinumwindow, [8, 8],\n                                './{}/{:04d}_mediastinum.png'.format(self.train_dir, step))\n                    save_images(realmasks, [8, 8],\n                                './{}/{:04d}_mask.png'.format(self.train_dir, step)) \n                         \n                    print('save eval image')\n                    \n                    real_labels = sample_label()\n                    realmasks = sample_masks()\n                    sample_images, lungwindow, mediastinumwindow = sess.run([self.fake_B, self.fake_lungwindow, self.fake_mediastinumwindow], feed_dict={self.masks: realmasks, self.y: real_labels})\n                    save_images(sample_images, [8, 8],\n                                './{}/{:04d}_sample.png'.format(self.eval_dir, step))\n                    save_images(lungwindow, [8, 8],\n                                './{}/{:04d}_lung.png'.format(self.eval_dir, step))\n                    save_images(mediastinumwindow, [8, 8],\n                                './{}/{:04d}_mediastinum.png'.format(self.eval_dir, step))  \n                    save_images(realmasks, [8, 8],\n                                './{}/{:04d}_mask.png'.format(self.eval_dir, step)) \n                    \n                    print('save test image')\n                    real_labels = sample_label()\n                    realmasks = sample_masks_test()\n                    sample_images, lungwindow, mediastinumwindow = sess.run([self.fake_B, self.fake_lungwindow, self.fake_mediastinumwindow], feed_dict={self.masks: realmasks, self.y: real_labels})\n                    save_images(sample_images, [8, 8],\n                                './{}/{:04d}_sample.png'.format(self.test_dir, step))\n                    save_images(lungwindow, [8, 8],\n                                './{}/{:04d}_lung.png'.format(self.test_dir, step))\n                    save_images(mediastinumwindow, [8, 8],\n                                './{}/{:04d}_mediastinum.png'.format(self.test_dir, step))                   \n                    save_images(realmasks, [8, 8],\n                                './{}/{:04d}_mask.png'.format(self.test_dir, step))\n                    # save model each 50 epochs  \n                    self.saver.save(sess, self.model_path,global_step=step)\n\n                step = step + 1\n\n            save_path = self.saver.save(sess, self.model_path)\n            print (\"Model saved in file: %s\" % save_path)\n\n\n    def test(self):\n    \t'''\n    \tload pretrained model for model testing\n    \t'''\n        init = tf.initialize_all_variables()\n        with tf.Session() as sess:\n            sess.run(init)\n            self.saver.restore(sess, self.model_path)\n            sample_z = np.random.uniform(1, -1, size=[self.batch_size, self.z_dim])\n            output = sess.run(self.fake_images, feed_dict={self.z: sample_z, self.y: sample_label()})\n            save_images(output, [8, 8], './{}/test{:02d}_{:04d}.png'.format(self.train_dir, 0, 0))\n            image = cv2.imread('./{}/test{:02d}_{:04d}.png'.format(self.train_dir, 0, 0), 0)\n            cv2.imshow(\"test\", image)\n            cv2.waitKey(-1)\n            print(\"Test finish!\")\n\n\n    def generator(self, image, y=None):\n        with tf.variable_scope(\"generator\") as scope:\n            print('generator U-Net:')\n            print('shape of y: ', y.get_shape().as_list()) \n            print('shape of image: ', image.get_shape().as_list()) \n            y = tf.reshape(y, shape=[self.batch_size, 1, 1, self.y_dim])\n\n            s = self.output_size\n            s2, s4, s8, s16, s32, s64, s128 = int(s/2), int(s/4), int(s/8), int(s/16), int(s/32), int(s/64), int(s/128)\n            \n            print('shape of image: ', image.get_shape().as_list())\n           \n            e1 = conv2d_UNet(image, self.gf_dim, name='g_e1_conv')\n            e1 = conv_cond_concat(e1, y)\n\n            e2 = self.g_bn_e2(conv2d_UNet(lrelu(e1), self.gf_dim*2, name='g_e2_conv'))\n            e2 = conv_cond_concat(e2, y)\n\n            e3 = self.g_bn_e3(conv2d_UNet(lrelu(e2), self.gf_dim*4, name='g_e3_conv'))\n            e3 = conv_cond_concat(e3, y)\n\n            e4 = self.g_bn_e4(conv2d_UNet(lrelu(e3), self.gf_dim*8, name='g_e4_conv'))\n            e4 = conv_cond_concat(e4, y)\n\n            e5 = self.g_bn_e5(conv2d_UNet(lrelu(e4), self.gf_dim*8, name='g_e5_conv'))\n            e5 = conv_cond_concat(e5, y)\n     \n            e6 = self.g_bn_e6(conv2d_UNet(lrelu(e5), self.gf_dim*8, name='g_e6_conv'))\n            e6 = conv_cond_concat(e6, y)\n\n            e7 = self.g_bn_e7(conv2d_UNet(lrelu(e6), self.gf_dim*8, name='g_e7_conv'))\n            e7 = conv_cond_concat(e7, y)\n\n            e8 = self.g_bn_e8(conv2d_UNet(lrelu(e7), self.gf_dim*8, name='g_e8_conv'))\n            e8 = conv_cond_concat(e8, y)\n\n            self.d1, self.d1_w, self.d1_b = deconv2d(tf.nn.relu(e8),\n                [self.batch_size, s128, s128, self.gf_dim*8], name='g_d1', with_w=True)\n            d1 = tf.nn.dropout(self.g_bn_d1(self.d1), 0.5)\n            d1 = tf.concat([d1, e7], 3)\n            d1 = conv_cond_concat(d1, y)\n           \n            self.d2, self.d2_w, self.d2_b = deconv2d(tf.nn.relu(d1),\n                [self.batch_size, s64, s64, self.gf_dim*8], name='g_d2', with_w=True)\n            d2 = tf.nn.dropout(self.g_bn_d2(self.d2), 0.5)\n            d2 = tf.concat([d2, e6], 3)\n            d2 = conv_cond_concat(d2, y)\n\n            self.d3, self.d3_w, self.d3_b = deconv2d(tf.nn.relu(d2),\n                [self.batch_size, s32, s32, self.gf_dim*8], name='g_d3', with_w=True)\n            d3 = tf.nn.dropout(self.g_bn_d3(self.d3), 0.5)\n            d3 = tf.concat([d3, e5], 3)\n            d3 = conv_cond_concat(d3, y)\n\n            self.d4, self.d4_w, self.d4_b = deconv2d(tf.nn.relu(d3),\n                [self.batch_size, s16, s16, self.gf_dim*8], name='g_d4', with_w=True)\n            d4 = self.g_bn_d4(self.d4)\n            d4 = tf.concat([d4, e4], 3)\n            d4 = conv_cond_concat(d4, y)\n\n            self.d5, self.d5_w, self.d5_b = deconv2d(tf.nn.relu(d4),\n                [self.batch_size, s8, s8, self.gf_dim*4], name='g_d5', with_w=True)\n            d5 = self.g_bn_d5(self.d5)\n            d5 = tf.concat([d5, e3], 3)\n            d5 = conv_cond_concat(d5, y)\n\n            self.d6, self.d6_w, self.d6_b = deconv2d(tf.nn.relu(d5),\n                [self.batch_size, s4, s4, self.gf_dim*2], name='g_d6', with_w=True)\n            d6 = self.g_bn_d6(self.d6)\n            d6 = tf.concat([d6, e2], 3)\n            d6 = conv_cond_concat(d6, y)\n\n            self.d7, self.d7_w, self.d7_b = deconv2d(tf.nn.relu(d6),\n                [self.batch_size, s2, s2, self.gf_dim], name='g_d7', with_w=True)\n            d7 = self.g_bn_d7(self.d7)\n            d7 = tf.concat([d7, e1], 3)\n            d7 = conv_cond_concat(d7, y)\n\n            self.d8, self.d8_w, self.d8_b = deconv2d(tf.nn.relu(d7),\n                [self.batch_size, s, s, self.output_c_dim], name='g_d8', with_w=True)\n            print('shape of d8: ', self.d8.get_shape().as_list())\n            return tf.nn.tanh(self.d8)\n\n    def decorator_lung_window(self, images, masks, y = None):\n        with tf.variable_scope('decorator_lungwindow') as scope:\n            print('Decorator for lung window')\n            y = tf.reshape(y, shape=[self.batch_size, 1, 1, self.y_dim])\n\n            images = conv_cond_concat(images, y)\n            h0 = lrelu(conv2d_decorator(images, 32, name='g_deco_lung_h0_conv'))\n            h0 = conv_cond_concat(h0, y)\n            h1 = lrelu(conv2d_decorator(h0, 64, name='g_deco_lung_h1_conv'))\n            h1 = conv_cond_concat(h1, y)\n            h2 = lrelu(conv2d_decorator(h1, 128, name = 'g_deco_lung_h2_conv'))\n            h2 = conv_cond_concat(h2, y)\n            h3 = lrelu(conv2d_decorator(h2, 64, name = 'g_deco_lung_h3_conv'))\n            h3 = conv_cond_concat(h3, y)\n            h4 = lrelu(conv2d_decorator(h3, 32, name='g_deco_lung_h4_conv'))\n            h4 = conv_cond_concat(h4, y)\n            h5 = lrelu(conv2d_decorator(h4, self.output_c_dim, name='g_deco_lung_h5_conv'))\n            print('shape of h5: ', h5.get_shape().as_list())\n            return tf.nn.relu(h5), h5\n\n    def decorator_mediastinum_window(self, images, masks, y = None):\n        with tf.variable_scope('decorator_mediastinum') as scope:\n            print('Decorator for mediastinum window')\n            y = tf.reshape(y, shape=[self.batch_size, 1, 1, self.y_dim])\n\n            images = conv_cond_concat(images, y)\n            h0 = lrelu(conv2d_decorator(images, 32, name='g_deco_mediastinum_h0_conv'))\n            h0 = conv_cond_concat(h0, y)\n            h1 = lrelu(conv2d_decorator(h0, 64, name='g_deco_mediastinum_h1_conv'))\n            h1 = conv_cond_concat(h1, y)\n            h2 = lrelu(conv2d_decorator(h1, 128, name = 'g_deco_mediastinum_h2_conv'))            \n            h2 = conv_cond_concat(h2, y)\n            h3 = lrelu(conv2d_decorator(h2, 64, name = 'g_deco_mediastinum_h3_conv'))            \n            h3 = conv_cond_concat(h3, y)\n            h4 = lrelu(conv2d_decorator(h3, 32, name='g_deco_mediastinum_h4_conv'))            \n            h4 = conv_cond_concat(h4, y)\n            h5 = lrelu(conv2d_decorator(h4, self.output_c_dim, name='g_deco_mediastinum_h5_conv'))\n            print('shape of h5: ', h5.get_shape().as_list())\n            return tf.nn.relu(h5), h5\n\n    def decorator(self, images, masks, y = None):\n        with tf.variable_scope('decorator_allattributes') as scope:\n            print('Decorator for all attributes')\n            y = tf.reshape(y, shape=[self.batch_size, 1, 1, self.y_dim])\n\n            images = conv_cond_concat(images, y)\n\n            h0 = lrelu(conv2d_decorator(images, 32, name='g_deco_h0_conv'))\n            h0 = conv_cond_concat(h0, y)\n            h1 = lrelu(conv2d_decorator(h0, 64, name='g_deco_h1_conv'))\n            h1 = conv_cond_concat(h1, y)\n            h2 = lrelu(conv2d_decorator(h1, 128, name = 'g_deco_h2_conv'))\n            h2 = conv_cond_concat(h2, y)\n            h3 = lrelu(conv2d_decorator(h2, 64, name = 'g_deco_h3_conv'))\n            h3 = conv_cond_concat(h3, y)\n            h4 = lrelu(conv2d_decorator(h3, 32, name='g_deco_h4_conv'))\n            h4 = conv_cond_concat(h4, y)\n            h5 = lrelu(conv2d_decorator(h4, self.output_c_dim, name='g_deco_h5_conv'))\n            print('shape of h5: ', h5.get_shape().as_list())\n            return tf.nn.tanh(h5), h5\n\n    def discriminator_all(self, image, y=None, reuse=False):\n        with tf.variable_scope(\"discriminator\") as scope:\n            print('discriminator:')\n            if reuse:\n                tf.get_variable_scope().reuse_variables()\n            else:\n                assert tf.get_variable_scope().reuse == False\n            y = tf.reshape(y, shape=[self.batch_size, 1, 1, self.y_dim])\n\n            image = conv_cond_concat(image, y)\n            h0 = lrelu(conv2d_UNet(image, self.df_dim, name='d_h0_conv'))\n            h0 = conv_cond_concat(h0, y)           \n            h1 = lrelu(self.d_bn1(conv2d_UNet(h0, self.df_dim*2, name='d_h1_conv')))\n            h1 = conv_cond_concat(h1, y)\n            h2 = lrelu(self.d_bn2(conv2d_UNet(h1, self.df_dim*4, name='d_h2_conv')))\n            h2 = conv_cond_concat(h2, y)\n            h3 = lrelu(self.d_bn3(conv2d_UNet(h2, self.df_dim*8, d_h=1, d_w=1, name='d_h3_conv')))\n            h3 = conv_cond_concat(h3, y)\n            h4 = linear(tf.reshape(h3, [self.batch_size, -1]), 1, 'd_h3_lin')\n            print('shape of h4: ', h4.get_shape().as_list())\n            return tf.nn.sigmoid(h4), h4\n\n\n    def classify_lung(self, image, y=None, reuse=False):\n        with tf.variable_scope(\"classify_lung\") as scope:\n            print('classify_lung:')\n            if reuse:\n                tf.get_variable_scope().reuse_variables()\n            else:\n                assert tf.get_variable_scope().reuse == False\n\n            layer = tf.layers.conv2d(image,64,[3,3],padding=\"same\",activation=tf.nn.relu,name='c_classify_1')\n            layer = tf.layers.max_pooling2d(layer,pool_size=[2,2],strides=2,name='c_classify_2')\n            layer = tf.layers.conv2d(layer,128,[3,3],padding=\"same\",activation=tf.nn.relu,name='c_classify_3')\n            layer = tf.layers.max_pooling2d(layer,pool_size=[2,2],strides=2,name='c_classify_4')\n            layer = tf.layers.conv2d(layer,256,[3,3],padding=\"same\",activation=tf.nn.relu,name='c_classify_5')\n            layer = tf.layers.max_pooling2d(layer,pool_size=[2,2],strides=2,name='c_classify_6')\n            layer = tf.reshape(layer, [-1, 16 * 16 * 256])\n            layer = tf.layers.dense(layer,100,activation=tf.nn.relu,name='c_classify_7')\n            layer = tf.layers.dropout(layer,0.5,name='c_classify_8')\n            layer = tf.layers.dense(layer,5,activation=tf.nn.relu,name='c_classify_9')\n            logits = tf.nn.softmax(layer)\n            return layer, logits\n\n\n    def classify_mediastinum(self, image, y=None, reuse=False):\n        with tf.variable_scope(\"classify_mediastinum\") as scope:\n            print('classify_mediastinum:')\n            if reuse:\n                tf.get_variable_scope().reuse_variables()\n            else:\n                assert tf.get_variable_scope().reuse == False\n\n            layer = tf.layers.conv2d(image,64,[3,3],padding=\"same\",activation=tf.nn.relu,name='c_mediastinum_1')\n            layer = tf.layers.max_pooling2d(layer,pool_size=[2,2],strides=2,name='c_mediastinum_2')\n            layer = tf.layers.conv2d(layer,128,[3,3],padding=\"same\",activation=tf.nn.relu,name='c_mediastinum_3')\n            layer = tf.layers.max_pooling2d(layer,pool_size=[2,2],strides=2,name='c_mediastinum_4')\n\n            layer = tf.layers.conv2d(layer,256,[3,3],padding=\"same\",activation=tf.nn.relu,name='c_mediastinum_5')\n            layer = tf.layers.max_pooling2d(layer,pool_size=[2,2],strides=2,name='c_mediastinum_6')\n            layer = tf.reshape(layer, [-1, 16 * 16 * 256])\n\n            layer = tf.layers.dense(layer,100,activation=tf.nn.relu,name='c_mediastinum_7')\n            layer = tf.layers.dropout(layer,0.5,name='c_mediastinum_8')\n            layer = tf.layers.dense(layer,5,activation=tf.nn.relu,name='c_mediastinum_9')\n\n            logits = tf.nn.softmax(layer)\n            return layer, logits\n\n\n    def classify_lung_mali(self, image, y=None, reuse=False):\n        with tf.variable_scope(\"classify_lung_mali\") as scope:\n            print('classify_lung_mali:')\n            if reuse:\n                tf.get_variable_scope().reuse_variables()\n            else:\n                assert tf.get_variable_scope().reuse == False\n\n            layer = tf.layers.conv2d(image,64,[3,3],padding=\"same\",activation=tf.nn.relu,name='c_classify_mali_1')\n            layer = tf.layers.max_pooling2d(layer,pool_size=[2,2],strides=2,name='c_classify_mali_2')\n            layer = tf.layers.conv2d(layer,128,[3,3],padding=\"same\",activation=tf.nn.relu,name='c_classify_mali_3')\n            layer = tf.layers.max_pooling2d(layer,pool_size=[2,2],strides=2,name='c_classify_mali_4')\n\n            layer = tf.layers.conv2d(layer,256,[3,3],padding=\"same\",activation=tf.nn.relu,name='c_classify_mali_5')\n            layer = tf.layers.max_pooling2d(layer,pool_size=[2,2],strides=2,name='c_classify_mali_6')\n            layer = tf.reshape(layer, [-1, 16 * 16 * 256])\n\n            layer = tf.layers.dense(layer,100,activation=tf.nn.relu,name='c_classify_mali_7')\n            layer = tf.layers.dropout(layer,0.5,name='c_classify_mali_8')\n            layer = tf.layers.dense(layer,5,activation=tf.nn.relu,name='c_classify_mali_9')\n            logits = tf.nn.softmax(layer)\n            return layer, logits\n\n\n    def classify_mediastinum_mali(self, image, y=None, reuse=False):\n        with tf.variable_scope(\"classify_mediastinum_mali\") as scope:\n            print('classify_mediastinum_mali:')\n            if reuse:\n                tf.get_variable_scope().reuse_variables()\n            else:\n                assert tf.get_variable_scope().reuse == False\n\n            layer = tf.layers.conv2d(image,64,[3,3],padding=\"same\",activation=tf.nn.relu,name='c_mediastinum_mali_1')\n            layer = tf.layers.max_pooling2d(layer,pool_size=[2,2],strides=2,name='c_mediastinum_mali_2')\n            layer = tf.layers.conv2d(layer,128,[3,3],padding=\"same\",activation=tf.nn.relu,name='c_mediastinum_mali_3')\n            layer = tf.layers.max_pooling2d(layer,pool_size=[2,2],strides=2,name='c_mediastinum_mali_4')\n\n            layer = tf.layers.conv2d(layer,256,[3,3],padding=\"same\",activation=tf.nn.relu,name='c_mediastinum_mali_5')\n            layer = tf.layers.max_pooling2d(layer,pool_size=[2,2],strides=2,name='c_mediastinum_mali_6')\n            layer = tf.reshape(layer, [-1, 16 * 16 * 256])\n\n            layer = tf.layers.dense(layer,100,activation=tf.nn.relu,name='c_mediastinum_mali_7')\n            layer = tf.layers.dropout(layer,0.5,name='c_mediastinum_mali_8')\n            layer = tf.layers.dense(layer,5,activation=tf.nn.relu,name='c_mediastinum_mali_9')\n\n            logits = tf.nn.softmax(layer)\n            return layer, logits", "meta": {"hexsha": "6aeff4742785d5f7f41995e30eb07b4e5b08d616", "size": 26687, "ext": "py", "lang": "Python", "max_stars_repo_path": "model.py", "max_stars_repo_name": "chinichenw/CA-MW-Adversarial-Synthesis", "max_stars_repo_head_hexsha": "c6365ee323cfd9947be4608195e1f8b82a85e889", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-16T01:16:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-19T11:10:12.000Z", "max_issues_repo_path": "model.py", "max_issues_repo_name": "chinichenw/CA-MW-Adversarial-Synthesis", "max_issues_repo_head_hexsha": "c6365ee323cfd9947be4608195e1f8b82a85e889", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model.py", "max_forks_repo_name": "chinichenw/CA-MW-Adversarial-Synthesis", "max_forks_repo_head_hexsha": "c6365ee323cfd9947be4608195e1f8b82a85e889", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.024742268, "max_line_length": 316, "alphanum_fraction": 0.617529134, "include": true, "reason": "import numpy", "num_tokens": 7339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.1798777340372459}}
{"text": "\"\"\"\nVABY_MODELS_CVR: VABY forward models for CVR\n\nForward model for CVR measurement using BOLD MRI and PETCo2\n\nBased on Matlab code written by Joana Pinto, December 2020, Oxford\nand adapted from Daniel Bulte 2018 script\n\nPython conversion by Martin Craig 2021, Nottingham\n\n(c) 2021 University of Nottingham\n\"\"\"\nimport tensorflow as tf\n\nimport numpy as np\n#import tensorflow_probability as tfp\n\nfrom vaby.model import Model, ModelOption\nfrom vaby.utils import ValueList\nfrom vaby.parameter import get_parameter\n\nfrom ._version import __version__\n\nclass CvrPetCo2Model(Model):\n    \"\"\"\n    Inference forward model for CVR measurement using PETCo2\n    \"\"\"\n\n    def options(self):\n        return [\n            # Regressor, e.g. physiological data file containing PETCO2 measurements\n            ModelOption(\"regressors\", \"Regression data (e.g. PETCO2 or O2 time series)\", type=str, default=None),\n            ModelOption(\"regressor_types\", \"Regressor types - comma separated one for each regressor. Supported types: co2, petco2, custom\", type=str, default=\"co2\"),\n            ModelOption(\"regressor_trs\", \"Regressor time resolutions\", unit=\"s\", type=ValueList, default=[0.01,]),\n\n            # Protocol parameters\n            ModelOption(\"baseline\", \"Length of initial baseline block\", unit=\"s\", type=int, default=60),\n            ModelOption(\"data_start_time\", \"Start of MR data relative to start of regressor data - if not provided will be estimated\", unit=\"s\", type=float, default=None),\n            ModelOption(\"tr\", \"Time between MR volumes\", unit=\"s\", type=float, default=None),\n            ModelOption(\"air_pressure\", \"Barometric pressure\", unit=\"mbar\", type=int, default=1020),\n\n            # Model options\n            ModelOption(\"infer_sig0\", \"Infer signal offset\", type=bool, default=False),\n            ModelOption(\"infer_delay\", \"Infer delay shift on regressors\", type=bool, default=False),\n            #ModelOption(\"infer_drift\", \"Infer a linear drift on signal\", type=bool, default=False),\n            #ModelOption(\"sigmoid_response\", \"Use sigmoid relationship between PETCO2 and CVR\", type=bool, default=False)\n        ]\n\n    def __str__(self):\n        return \"CVR-PETCO2 model: %s\" % __version__\n\n    def __init__(self, data_model, **options):\n        Model.__init__(self, data_model, **options)\n\n        if self.regressors is None:\n            raise ValueError(\"A regressor must be provided\")\n\n        if isinstance(self.regressors, str):\n            fnames = self.regressors.split(\",\") # Hopefully no commas in file names\n            self.regressors = np.array([np.squeeze(np.loadtxt(fname)) for fname in fnames])\n        else:\n            self.regressors = np.array(self.regressors)\n\n        if self.regressors.ndim < 2:\n            self.regressors = self.regressors[np.newaxis, ...]\n        if self.regressors.ndim != 2:\n            raise ValueError(\"Regressor must be 1D or 2D\")\n\n        self.n_regressors = self.regressors.shape[0]\n        self.regressor_types = [s.strip() for s in self.regressor_types.split(\",\")]\n        if len(self.regressor_types) != self.n_regressors:\n            raise ValueError(\"Number of regressors provided (%i) does not match number of regressor types (%i)\" % (self.n_regressors, len(self.regressor_types)))\n        if len(self.regressor_trs) == 1:\n            # Use same value for all regressors\n            self.regressor_trs = self.regressor_trs * self.n_regressors\n        elif len(self.regressor_trs) != self.n_regressors:\n            raise ValueError(\"Number of regressors provided (%i) does not match number of time resolutions (%i)\" % (self.n_regressors, len(self.regressor_trs)))\n\n        # Process regressors and generate regression parameters for each\n        self.params = []\n        regressors = []\n        regressor_tpts = []\n        for idx, regressor_type in enumerate(self.regressor_types):\n            if regressor_type == \"co2\":\n                # Unprocessed CO2\n                regressors.append(self._preproc_co2(self.regressors[idx], self.regressor_trs[idx]))\n                regressor_tpts.append(self.tpts())\n                self.params.append(get_parameter(\"cvr%i\" % (idx+1), mean=1.0, dist=\"FoldedNormal\", prior_var=2000, post_var=10, **options))\n                self.data_start_time = 0\n            elif regressor_type == \"petco2\":\n                # Preprocessed end-tidal CO2 - not necessarily aligned with data or at same temporal resolution\n                regressors.append(self.regressors[idx].astype(np.float32))\n                regressor_tpts.append(np.array(range(len(self.regressors[idx]))) * self.regressor_trs[idx])\n                self.params.append(get_parameter(\"cvr%i\" % (idx+1), mean=1.0, dist=\"FoldedNormal\", prior_var=2000, post_var=10, **options))\n            elif regressor_type == \"custom\":\n                # Generic regressor, not necessarily aligned to data or at same temporal resolution\n                regressors.append(self.regressors[idx].astype(np.float32))\n                regressor_tpts.append(np.array(range(len(self.regressors[idx]))) * self.regressor_trs[idx])\n                self.params.append(get_parameter(\"beta%i\" % (idx+1), mean=0.0, dist=\"Normal\", prior_var=1e6, post_var=1e3, **options))\n            else:\n                raise ValueError(\"Unrecognized regressor type: %s\" % regressor_type)\n        self.regressors = np.array(regressors)\n        self.regressor_tpts = np.array(regressor_tpts)\n\n        # Differences between timepoints for quick interpolation. Given a delay\n        # time > 0 we can compute value = regressors[int(delay)] + frac(delay) * regressor_diff[int(delay)]\n        self.regressor_diffs = np.zeros(self.regressors.shape, dtype=np.float32)\n        self.regressor_diffs[:, :-1] = self.regressors[:, 1:] - self.regressors[:, :-1]\n\n        # Min/max values\n        self.regressor_mins = np.min(self.regressors, axis=1)\n        self.regressor_maxs = np.max(self.regressors, axis=1)\n        self.log.info(\"Regressor minimum values: %s\", self.regressor_mins)\n        self.log.info(\"Regressor maximum values: %s\", self.regressor_maxs)\n\n        # Estimate data start time\n        if self.data_start_time is None:\n            self.estimate_data_start_time(self.regressors[0], self.regressor_tpts[0])\n\n        if self.infer_sig0:\n            self.params.append(get_parameter(\"sig0\", mean=1, prior_var=1e9, post_mean=1, post_var=10, post_init=self._init_sig0, **options))\n        if self.infer_delay:\n            self.params.append(get_parameter(\"delay\", mean=0, prior_var=100, post_var=10, **options))\n\n    def _init_sig0(self, _param, _t, data):\n        return np.mean(data, axis=-1), None\n\n    def fit_glm(self, delay_min=-1, delay_max=1, delay_step=1, progress_cb=None):\n        self.log.info(\"GLM: Doing fitting on %i voxels\", self.data_model.data_space.size)\n        bold_data = self.data_model.data_space.srcdata.flat\n        t = self.tpts() # in seconds\n\n        delays = np.arange(delay_min, delay_max+delay_step, delay_step, dtype=np.float32)\n        best_resid = np.ones(bold_data.shape[0], dtype=np.float32) * 1e99\n        best_delay = np.zeros(bold_data.shape[0], dtype=np.float32)\n        best_cvr = np.zeros((bold_data.shape[0], self.n_regressors), dtype=np.float32)\n        best_sig0 = np.zeros(bold_data.shape[0], dtype=np.float32)\n        best_modelfit = np.zeros(bold_data.shape, dtype=np.float32)\n        for idx, delay in enumerate(delays):\n            self.log.info(\"GLM: fitting with delay=%f\", delay)\n            delayed_tpts = t - delay + self.data_start_time\n            x = []\n            for idx, regressor in enumerate(self.regressors):\n                # FIXME sampling rates, regressor time span...\n                delayed = np.interp(delayed_tpts, self.regressor_tpts[idx], regressor)\n                regressor_type = self.regressor_types[idx]\n                if regressor_type in (\"co2\", \"petco2\"):\n                    x.append((delayed - self.regressor_mins[idx]) / (self.regressor_maxs[idx] - self.regressor_mins[idx]))\n                else:\n                    x.append(delayed)\n\n            x.append(np.ones(self.data_model.data_space.srcdata.n_tpts))\n            x = np.array(x).T\n            for vox in range(bold_data.shape[0]):\n                y = bold_data[vox, :]\n                beta, resid, _rank, _s = np.linalg.lstsq(x, y)\n                model = np.dot(x, beta)\n                vox_resid = resid[0]\n                if vox_resid < best_resid[vox]:\n                    best_delay[vox] = delay\n                    best_sig0[vox] = beta[-1]\n                    for ridx, regressor_type in enumerate(self.regressor_types):\n                        if regressor_type in (\"co2\", \"petco2\"):\n                            best_cvr[vox, ridx] = beta[ridx]*100/(self.regressor_maxs[ridx] - self.regressor_mins[ridx])/best_sig0[vox]\n                        else:\n                            best_cvr[vox, ridx] = beta[ridx]/best_sig0[vox]\n                    best_modelfit[vox] = model\n                    best_resid[vox] = vox_resid\n            if progress_cb is not None:\n                progress_cb(float(idx)/float(len(delays)))\n\n        self.log.info(\"GLM: DONE\")\n        ret = []\n        for idx in range(self.n_regressors):\n            ret.append(best_cvr[..., idx])\n        ret.append(best_delay)\n        ret.append(best_sig0)\n        ret.append(best_modelfit)\n        return tuple(ret)\n\n    def evaluate(self, params, tpts):\n        \"\"\"\n        FIXME won't work in SVB batch training because of timepoints\n\n        :param t: Time values tensor of shape [W, 1, N] or [1, 1, N]\n        :param params Sequence of parameter values arrays, one for each parameter.\n                      Each array is [W, S, 1] tensor where W is the number of nodes and\n                      S the number of samples. This\n                      may be supplied as a [P, W, S, 1] tensor where P is the number of\n                      parameters.\n\n        :return: [W, S, N] tensor containing model output at the specified time values\n                 and for each time value using the specified parameter values\n        \"\"\"\n        regressor_params = params[:self.n_regressors]\n\n        extra_param = self.n_regressors\n        if self.infer_sig0:\n            sig0 = params[extra_param]\n            extra_param += 1\n        else:\n            sig0 = 0\n\n        if self.infer_delay:\n            delay = params[extra_param] - self.data_start_time\n            extra_param += 1\n\n            # Apply time delay [W, (S), N] FIXME what is length of regressor\n            t_delayed = (tpts - delay) / self.tr\n            t_delayed = tf.clip_by_value(t_delayed, 0, len(self.regressors[0])-1)\n            t_base = tf.floor(t_delayed)\n\n            # Integer index into the CO2 and diff arrays\n            t_base_idx = tf.cast(t_base, tf.int32)\n\n            # Fractional distance to next array index, or 0 if base index was < 0\n            t_frac = tf.clip_by_value(t_delayed - t_base, 0, 1)\n        else:\n            t_base_idx = tf.cast(tf.floor(tpts / self.tr), tf.int32)\n            t_frac = None\n\n        fit = 1\n        for idx, regressor in enumerate(self.regressors):\n            # Tile regressor arrays over all nodes so we can use tf.gather\n            regressor = tf.tile(regressor[np.newaxis, ...], (tf.shape(t_base_idx)[0], 1))\n\n            # Get value of regressor at integer part of time points\n            delayed = tf.gather(regressor, t_base_idx, axis=1, batch_dims=1)\n\n            if t_frac is not None:\n                # If we have a delay, use the differenced regressor to do linear interpolation on the\n                # fractional part of the time points\n                regressor_diff = tf.tile(self.regressor_diffs[idx][np.newaxis, ...], (tf.shape(t_base_idx)[0], 1))\n                delayed_diff = tf.gather(regressor_diff, t_base_idx, axis=1, batch_dims=1)\n                delayed += t_frac * delayed_diff\n\n            # Sigmoid response\n            #return sig0 + (b/(1+c.(e^(-(delayed_co2-c)/d))))/100\n\n            if self.regressor_types[idx] in (\"petco2\", \"co2\"):\n                # Regressor parameter is CVR\n                fit += regressor_params[idx] * (delayed - self.regressor_mins[idx]) / 100\n            elif self.regressor_types[idx] == \"custom\":\n                # Regressor parameter is generic coefficient\n                fit += regressor_params[idx] * delayed\n\n        fit = sig0 * fit\n        return fit\n\n    def tpts(self):\n        \"\"\"\n        Get the full set of timeseries time values\n\n        :return: Either a Numpy array of shape [N] or a Numpy array of shape\n                 [W, N] for nodewise timepoints.\n        \"\"\"\n        return np.linspace(0, self.data_model.data_space.srcdata.n_tpts, num=self.data_model.data_space.srcdata.n_tpts, endpoint=False, dtype=np.float32) * self.tr\n\n    def estimate_data_start_time(self, regressor, regressor_tpts):\n        # Mean time series\n        bold_data_average = np.mean(self.data_model.data_space.srcdata.flat, axis=0)\n\n        # Interpolate BOLD timeseries onto regressor\n        mr_timings = self.tpts()\n        bold_data_interp = np.interp(regressor_tpts, mr_timings, bold_data_average)\n\n        _cc, delay_vols = self._cross_corr(bold_data_interp, regressor)\n        self.data_start_time = -delay_vols * regressor_tpts[1] # to seconds assuming uniform spacing\n        self.log.info(\"Cross correlation estimated data start time: %f\", self.data_start_time)\n\n        # Calculate the latest possible start time of the MR data\n        # in case the cross correlation method returns something silly\n        regressor_duration = len(regressor) * regressor_tpts[1]\n        mr_duration = mr_timings[-1]\n        max_time_begin = regressor_duration - mr_duration\n        self.log.debug(\"Regressor duration: %f\", regressor_duration)\n        self.log.debug(\"MR duration: %f\", mr_duration)\n        self.log.info(\"Absolute latest start time: %f\", max_time_begin)\n        self.data_start_time = min(self.data_start_time, max_time_begin)\n        self.log.info(\"Final estimated data start time: %f\", self.data_start_time)\n\n    def _cross_corr(self, y1, y2):\n        \"\"\"\n        Calculates the cross correlation and lags\n\n        :param y1: 1D Numpy array\n        :param y2: 1D Numpy array, same length as y1\n\n        :return: Tuple of Maximum correlation, lag in terms of the index\n        \"\"\"\n        if len(y1) != len(y2):\n            raise ValueError('The lengths of the inputs should be the same.')\n\n        corr = np.correlate(y1 - np.mean(y1), \n                            y2 - np.mean(y2),\n                            mode='full')\n        lag = corr.argmax() - (len(y1) - 1)\n        return np.max(corr), lag\n\n    def _preproc_co2(self, co2, regressor_tr):\n        \"\"\"\n        Preprocess CO2 measurements from physiological data file\n        \"\"\"\n        co2 = np.squeeze(co2)\n        samp_rate = 1/regressor_tr\n\n        # FIXME we need the data start time to have been already estimated, \n        # although we probably shouldn't since there is no need to trim the CO2 trace\n        if self.data_start_time is None:\n            self.estimate_data_start_time(co2, np.array(range(len(co2))) * regressor_tr)\n            data_start = self.data_start_time\n            self.data_start_time = None\n\n        # FIXME should we really trim the CO2 trace?\n        co2_trim = co2[int(data_start * samp_rate):]\n        \n        # Determined respiratory frequency during baseline and use info to\n        # determine size of end-tidal search window\n        baseline_vols = int(self.baseline * samp_rate)\n        baseline_fft = np.fft.fft(co2_trim[:baseline_vols])\n        p2 = np.abs(baseline_fft/baseline_vols)\n        p1 = np.array(p2[:int(baseline_vols/2)+1])\n        p1[1:-2] = 2*p1[1:-2]\n        f = np.linspace(0, samp_rate/2, int(baseline_vols/2)+1)\n\n        loc = np.argmax(p1[1:])\n\n        pkloc = loc+1\n        harm = f[pkloc]\n        resp_period = round(1/harm) # e.g. 8s\n\n        # Search window = 1 second more than the respiratory period\n        nsearch_vols = int((resp_period+1)*samp_rate)\n        windows = int(np.floor(co2_trim.shape[0]/nsearch_vols))\n\n        # Find peak PETCO2 in each window - it's value and index position\n        posmax = np.zeros(windows, dtype=np.int)\n        winmax = np.zeros(windows)\n        for i in range(windows):\n            for j in range(nsearch_vols):\n                if j == 0 or co2_trim[i*nsearch_vols+j] > winmax[i]:\n                    winmax[i] = co2_trim[i*nsearch_vols+j]\n                    posmax[i] = i*nsearch_vols+j\n\n        # Make new full sample ET time course where the PETCO2 changes linearly\n        # between window maxima\n        co2_resamp = np.zeros((co2_trim.shape[0], 1))\n        for x in range(windows-1):\n            dist_c = posmax[x+1] - posmax[x]\n            step_c = winmax[x+1] - winmax[x]\n            ramp_c = step_c / dist_c\n            for g in range(dist_c+1):\n                co2_resamp[posmax[x]+g] = winmax[x] + (ramp_c * g)\n\n        # Pad the start and end with repeats of first and last value to maintain\n        # length and phase\n        co2_resamp[:posmax[0]] = co2_resamp[posmax[0]]\n        co2_resamp[posmax[-1]:] = co2_resamp[posmax[-1]]\n\n        # Create a timecourse of the end tidal CO2 values at the TR's for use with CVR sigmoids\n        # Make new time course at the TR resolution and normalise timecourse betwwen 0 and 1 to create EV\n        block = int(round(self.tr*samp_rate))\n        ev_co2 = np.zeros((self.data_model.data_space.srcdata.n_tpts,), dtype=np.float32)\n        for i in range(self.data_model.data_space.srcdata.n_tpts):\n            ev_co2[i] = co2_resamp[block * i + block-1]\n\n        # Convert to mmHg\n        air_pressure_mmhg = self.air_pressure/1.33322387415 # pressure mbar\n        co2_mmHg = (ev_co2 * air_pressure_mmhg) / 100 # div by 100 as values are in percent\n\n        # Calculation of normo/hypercapnea from on/off volumes\n        # Convert time periods to number of volumes\n        #baseline_vols = self.baseline/self.tr\n        #blocksize_on_vols = self.blocksize_on/self.tr\n        #blocksize_off_vols = self.blocksize_off/self.tr\n\n        # Average all of first baseline block\n        #self.normocap = np.mean(co2_mmHg[:int(baseline_vols+self.delay)])\n\n        #s1 = (baseline_vols+self.delay+blocksize_on_vols/2)\n        #s2 = (baseline_vols+self.delay+blocksize_on_vols)\n        #s3 = (baseline_vols+self.delay+blocksize_on_vols+blocksize_off_vols+blocksize_on_vols/2)\n        #s4 = (baseline_vols+self.delay+blocksize_on_vols+blocksize_off_vols+blocksize_on_vols)\n        #s1, s2, s3, s4 = int(s1), int(s2), int(s3), int(s4)\n        # Select 2nd half of each hypercapnic block to average\n        #hyperblock = np.concatenate([co2_mmHg[s1-1:s2], co2_mmHg[s3-1:s4]])\n        #self.hypercap = np.mean(hyperblock)\n\n        return co2_mmHg\n", "meta": {"hexsha": "90888f22a6e246f74f76bef86d8502924d1a0130", "size": 18778, "ext": "py", "lang": "Python", "max_stars_repo_path": "vaby_models_cvr/petco2.py", "max_stars_repo_name": "physimals/vaby_models_cvr", "max_stars_repo_head_hexsha": "798d347653fa31b1de8072674ddbc2dbafea8ad7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vaby_models_cvr/petco2.py", "max_issues_repo_name": "physimals/vaby_models_cvr", "max_issues_repo_head_hexsha": "798d347653fa31b1de8072674ddbc2dbafea8ad7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vaby_models_cvr/petco2.py", "max_forks_repo_name": "physimals/vaby_models_cvr", "max_forks_repo_head_hexsha": "798d347653fa31b1de8072674ddbc2dbafea8ad7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.1487179487, "max_line_length": 171, "alphanum_fraction": 0.625678986, "include": true, "reason": "import numpy", "num_tokens": 4732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3242354120407358, "lm_q1q2_score": 0.1797789596708625}}
{"text": "from model.abstract_VAE import VAE\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom scipy.stats import norm\n\nclass StableBCELoss(nn.modules.Module):\n    def __init__(self):\n        super(StableBCELoss, self).__init__()\n    def forward(self, input, target):\n        neg_abs = - input.abs()\n        loss = input.clamp(min=0) - input * target + (1 + neg_abs.exp()).log()\n        return loss.sum()\n\nclass CNNEncodeLayer(nn.Module):\n    def __init__(self, input, output, zdim, batchnorm, activacation, out_img_dims):\n        super(CNNEncodeLayer, self).__init__()\n        if activacation == \"lrelu\":\n            self.act = nn.LeakyReLU()\n        else:\n            self.act = nn.ReLU()\n        if batchnorm:\n            main = nn.Sequential(\n                nn.Conv2d(input, output,  4, stride=2, padding=1),\n                nn.BatchNorm2d(output),\n                self.act,\n            )\n            main2 = nn.Sequential(\n                nn.Conv2d(input, output,  4, stride=2, padding=1),\n                nn.BatchNorm2d(output),\n                self.act,\n            )\n        else:\n            main = nn.Sequential(\n                nn.Conv2d(input, output,  4, stride=2, padding=1),\n                self.act,\n            )\n            main2 = nn.Sequential(\n                nn.Conv2d(input, output,  4, stride=2, padding=1),\n                self.act,\n            )\n        self.main = main \n        self.main2 = main2\n        self.fc1 = nn.Linear(output * out_img_dims[0] * out_img_dims[1], zdim)\n        self.fc2 = nn.Linear(output * out_img_dims[0] * out_img_dims[1], zdim)\n        self.out_img_dims = out_img_dims\n        # print (\"Not implemented now...\")\n        return \n    def forward(self, x):\n\n        h = self.main(x)\n        h2 = self.main2(x)\n        return h, self.fc1(h2.view(h2.size(0), -1)), self.fc2(h2.view(h2.size(0), -1))\n\nclass CNNDecodeLayer(nn.Module):\n    def __init__(self, input, output, zdim, batchnorm, activacation, input_img_dims):\n        super(CNNDecodeLayer, self).__init__()\n        \n        if activacation == \"lrelu\":\n            self.act = nn.LeakyReLU()\n        else:\n            self.act = nn.ReLU()\n        if input == 0:\n            input = output\n            self.fc = nn.Linear(zdim, input * input_img_dims[0] * input_img_dims[0])\n        else:\n            self.fc = nn.Linear(zdim, input * input_img_dims[0] * input_img_dims[0])\n            input *= 2\n        if batchnorm:\n            main = nn.Sequential(\n                nn.ConvTranspose2d(input, output,  4, stride=2, padding=1),\n                nn.BatchNorm2d(output),\n                self.act,\n            )\n        else:\n            main = nn.Sequential(\n                nn.ConvTranspose2d(input, output,  4, stride=2, padding=1),\n                self.act,\n            )\n        self.main = main\n        self.input_img_dims = input_img_dims\n    def forward(self, input, z):\n        if input is None:\n            input = self.act(self.fc(z).view(z.size(0), -1, self.input_img_dims[0], self.input_img_dims[1]))\n        else:\n            input = torch.cat([input, self.fc(z).view(z.size(0), -1, self.input_img_dims[0], self.input_img_dims[1])], 1)\n        return self.main(input)\n\nclass EncodeLayer(nn.Module):\n    def __init__(self, input, output, zdim, batchnorm, activacation):\n        super(EncodeLayer, self).__init__()\n        if activacation == \"lrelu\":\n            self.act = nn.LeakyReLU()\n        else:\n            self.act = nn.ReLU()\n        if batchnorm:\n            main = nn.Sequential(\n                nn.Linear(input, output),\n                nn.BatchNorm1d(output),\n                self.act,\n            )\n        else:\n            main = nn.Sequential(\n                nn.Linear(input, output),\n                self.act,\n            )\n        self.main = main\n        self.fc1 = nn.Linear(output, zdim)\n        self.fc2 = nn.Linear(output, zdim)\n    def forward(self, x):\n        h = self.main(x)\n        return self.main(x),self.fc1(h), self.fc2(h)\n\n\nclass DecodeLayer(nn.Module):\n    def __init__(self, input, output, zdim, batchnorm, activacation):\n        super(DecodeLayer, self).__init__()\n        \n        if activacation == \"lrelu\":\n            self.act = nn.LeakyReLU()\n        else:\n            self.act = nn.ReLU()\n        if input == 0:\n            input = output\n            self.fc = nn.Linear(zdim, input)\n        else:\n            self.fc = nn.Linear(zdim, input)\n            input *= 2\n        if batchnorm:\n            main = nn.Sequential(\n                nn.Linear(input, output),\n                nn.BatchNorm1d(output),\n                self.act,\n            )\n        else:\n            main = nn.Sequential(\n                nn.Linear(input, output),\n                self.act,\n            )\n        self.main = main\n\n    def forward(self, input, z):\n        if input is None:\n            input = self.act(self.fc(z))\n        else:\n            input = torch.cat([input, self.act(self.fc(z))], 1)\n        return self.main(input)\n\nclass VLAE(VAE):\n\n    def __init__(self, input_dims, code_dims, beta=1.0,\n                 hidden=400, activacation=\"lrelu\",\n                 decoder=\"Bernoulli\", batchnorm=False):\n\n        super(VLAE, self).__init__(input_dims, code_dims)\n        self.name = \"VLAE\"\n        self.nx = int(np.prod(input_dims))\n        self.nz = int(np.prod(code_dims))\n        self.beta = beta\n        if activacation == \"lrelu\":\n            self.act = nn.LeakyReLU()\n        else:\n            self.act = nn.ReLU()\n        if decoder == \"Bernoulli\":\n            self.reconstruct_loss = StableBCELoss()\n        else:\n            self.reconstruct_loss = nn.MSELoss()\n\n        self.encode_layers = nn.ModuleList([EncodeLayer(self.nx, hidden, code_dims[1], batchnorm, activacation)]) \n        self.decode_layers = nn.ModuleList([])\n        for i in range(code_dims[0]-1):\n            el = EncodeLayer(hidden, hidden, code_dims[1], batchnorm, activacation)\n            dl = DecodeLayer(hidden, hidden, code_dims[1], batchnorm, activacation)\n            self.encode_layers.append(el)\n            self.decode_layers.append(dl)\n    \n        self.fc1 = nn.Linear(code_dims[1], hidden)\n        self.fc2 = nn.Linear(hidden, self.nx)\n\n    def encode(self, x):\n        h = x.view(x.size(0), -1)\n        mu_list = []\n        logvar_list = []\n        for fc in self.encode_layers:\n            h, mu, logvar = fc(h)\n            mu_list.append(mu)\n            logvar_list.append(logvar)\n        return torch.cat(mu_list, dim=1), torch.cat(logvar_list, dim=1)\n\n    def reparametrize(self, mu, logvar):\n        std = logvar.mul(0.5).exp_()\n        if isinstance(mu, torch.cuda.FloatTensor):\n            eps = torch.cuda.FloatTensor(std.size()).normal_()\n        else:\n            eps = torch.FloatTensor(std.size()).normal_()\n#        eps[:,-2:-1] = (eps[:,-2:-1] - mu.data[:,-2:-1]) / std.data[:,-2:-1]\n        eps = Variable(eps)\n        return eps.mul(std).add_(mu) \n    \n    def decode(self, z):\n        zcode = list(torch.chunk(z, self.code_dims[0], dim=1))[::-1]\n        h = self.act(self.fc1(zcode[0]))\n        for z, fc in zip(zcode[1:], self.decode_layers):\n            h = fc(h, z)\n        return self.fc2(h)\n\n    def forward(self, x):\n        mu, logvar = self.encode(x.view(x.size(0), -1))\n        z = self.reparametrize(mu, logvar)\n        return self.decode(z), mu, logvar, z\n\n    def loss(self, recon_x, x, mu, logvar, z):\n        x = x.view(x.size(0), -1)\n        BCE = self.reconstruct_loss(recon_x, x) / x.size(0)\n        # see Appendix B from VAE paper:\n        # Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014\n        # https://arxiv.org/abs/1312.6114\n        # 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)\n        KLD_element = mu.pow(2).add_(logvar.exp()).mul_(-1).add_(1).add_(logvar)\n        KLD = torch.sum(KLD_element).mul_(-0.5) / x.size(0)\n        return BCE + self.beta * KLD, BCE, KLD\n\n    def mutual_info_q(self, x):\n        mu, logvar = self.encode(x.view(x.size(0), -1))\n        z = self.reparametrize(mu, logvar)\n        l = z.size(0)\n        z = z.repeat(l, 1, 1)\n        mu = mu.unsqueeze(2).repeat(1,1,l).transpose(1,2)\n        logvar = logvar.unsqueeze(2).repeat(1,1,l).transpose(1,2)\n        p_matrix =  ( - torch.sum((z - mu) ** 2  / logvar.exp(), dim=2) / 2.0 - 0.5 * torch.sum(logvar, dim=2)).exp_()\n        p_split_matrix = (- (z - mu) ** 2  / logvar.exp() / 2.0 - 0.5 * logvar ).exp_()\n        p_split_vector = torch.sum(p_split_matrix, dim=1)\n        p_vector =  torch.sum(p_matrix, dim=1)\n        I = torch.FloatTensor([np.log(l)])\n        I_split = torch.FloatTensor([np.log(l)] * int(z.size(2)))\n        for i in range(l):\n            I += (p_matrix[i][i].log() - p_vector[i].log()).data / l\n            I_split += (p_split_matrix[i][i].log() - p_split_vector[i].log()).data / l\n        # q(z_i) is not independent..\n        # assert np.allclose(I.numpy(), np.sum(I_split.numpy()))\n        return I, I_split\n\n\nclass MMDVLAE(VLAE):\n    def compute_kernel(self, x, y):\n        x_size = x.size(0)\n        y_size = y.size(0)\n        dim = x.size(1)\n        tiled_x = x.unsqueeze(1).repeat(1, y_size, 1)\n        tiled_y = y.unsqueeze(0).repeat(x_size, 1, 1)\n        return ((-(tiled_x - tiled_y) ** 2).mean(dim=2) / float(dim)).exp_()\n    \n    def compute_mmd(self, x, y, sigma_sqr=1.0):\n        x_kernel = self.compute_kernel(x, x)\n        y_kernel = self.compute_kernel(y, y)\n        xy_kernel = self.compute_kernel(x, y)\n        return torch.mean(x_kernel) + torch.mean(y_kernel) - 2 * torch.mean(xy_kernel)\n    def loss(self, recon_x, x, mu, logvar, z):\n        x = x.view(x.size(0), -1)\n        BCE = self.reconstruct_loss(recon_x, x) / (x.size(0) * x.size(1))\n        \n        true_samples = Variable(torch.FloatTensor(x.size(0), self.nz).normal_())\n        MMD = self.compute_mmd(true_samples, z)\n        return BCE + self.beta *  MMD , BCE, MMD\n\nclass CNNVLAE(VAE):\n    def __init__(self, input_dims, code_dims, beta=1.0,\n                 hidden=400, activacation=\"lrelu\",\n                 decoder=\"Bernoulli\", batchnorm=True):\n\n        super(CNNVLAE, self).__init__(input_dims, code_dims)\n        self.name = \"CNNVLAE\"\n        self.nx = input_dims[0]\n        self.nz = int(np.prod(code_dims))\n        self.beta = beta\n        if activacation == \"lrelu\":\n            self.act = nn.LeakyReLU()\n        else:\n            self.act = nn.ReLU()\n        if decoder == \"Bernoulli\":\n            self.reconstruct_loss = StableBCELoss()\n        else:\n            self.reconstruct_loss = nn.MSELoss()\n\n        assert(input_dims[1] == input_dims[2])\n        l = input_dims[1]\n        l = int(l/2)\n        self.encode_layers = [CNNEncodeLayer(self.nx, hidden, code_dims[1], batchnorm, activacation, (l, l))]\n        self.decode_layers = [CNNDecodeLayer(hidden*2, hidden, code_dims[1], batchnorm, activacation, (l, l))]\n        self.conv2 = nn.ConvTranspose2d(hidden, 1, 1, 1)\n        for i in range(code_dims[0]-2):\n            l = int(l/2)\n            el = CNNEncodeLayer(hidden, hidden * 2, code_dims[1], batchnorm, activacation, (l, l))\n            hidden *= 2\n            dl = CNNDecodeLayer(hidden * 2, hidden, code_dims[1], batchnorm, activacation, (l, l))\n            self.encode_layers.append(el)\n            self.decode_layers.insert(0, dl)\n        self.encode_layers = nn.ModuleList(self.encode_layers)\n        self.decode_layers = nn.ModuleList(self.decode_layers)\n        l = int(l/2)\n        self.encode_layers.append(CNNEncodeLayer(hidden, hidden*2, code_dims[1], batchnorm, activacation, (l, l)))\n        hidden *= 2\n        self.conv1 = CNNDecodeLayer(0, hidden, code_dims[1], batchnorm, activacation, (l, l))\n\n    def encode(self, x):\n        h = x\n        mu_list = []\n        logvar_list = []\n        for conv in self.encode_layers:\n            h, mu, logvar = conv(h)\n            mu_list.append(mu)\n            logvar_list.append(logvar)\n        return torch.cat(mu_list, dim=1), torch.cat(logvar_list, dim=1)\n\n    def reparametrize(self, mu, logvar):\n        std = logvar.mul(0.5).exp_()\n        if isinstance(mu, torch.cuda.FloatTensor):\n            eps = torch.cuda.FloatTensor(std.size()).normal_()\n        else:\n            eps = torch.FloatTensor(std.size()).normal_()\n#        eps[:,-2:-1] = (eps[:,-2:-1] - mu.data[:,-2:-1]) / std.data[:,-2:-1]\n        eps = Variable(eps)\n        return eps.mul(std).add_(mu) \n    \n    def decode(self, z):\n\n        zcode = list(torch.chunk(z, self.code_dims[0], dim=1))[::-1]\n        h = self.act(self.conv1(None, zcode[0]))\n        for z, conv in zip(zcode[1:], self.decode_layers):\n            h = conv(h, z)\n        return self.conv2(h)\n\n    def forward(self, x):\n        mu, logvar = self.encode(x)\n        z = self.reparametrize(mu, logvar)\n        return self.decode(z), mu, logvar, z\n\n    def loss(self, recon_x, x, mu, logvar, z):\n        x = x.view(x.size(0), -1)\n        recon_x = recon_x.view(recon_x.size(0), -1)\n        BCE = self.reconstruct_loss(recon_x, x) / x.size(0)\n        # see Appendix B from VAE paper:\n        # Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014\n        # https://arxiv.org/abs/1312.6114\n        # 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)\n        KLD_element = mu.pow(2).add_(logvar.exp()).mul_(-1).add_(1).add_(logvar)\n        KLD = torch.sum(KLD_element).mul_(-0.5) / x.size(0)\n        return BCE + self.beta * KLD, BCE, KLD\n\n    def mutual_info_q(self, x):\n        mu, logvar = self.encode(x)\n        z = self.reparametrize(mu, logvar)\n        z = z.view(z.size(0), -1)\n        mu = mu.view(mu.size(0), -1)\n        logvar = logvar.view(logvar.size(0), -1)\n        l = z.size(0)\n        z = z.repeat(l, 1, 1)\n        mu = mu.unsqueeze(2).repeat(1,1,l).transpose(1,2)\n        logvar = logvar.unsqueeze(2).repeat(1,1,l).transpose(1,2)\n        p_matrix =  ( - torch.sum((z - mu) ** 2  / logvar.exp(), dim=2) / 2.0 - 0.5 * torch.sum(logvar, dim=2)).exp_()\n        p_split_matrix = (- (z - mu) ** 2  / logvar.exp() / 2.0 - 0.5 * logvar ).exp_()\n        p_split_vector = torch.sum(p_split_matrix, dim=1)\n        p_vector =  torch.sum(p_matrix, dim=1)\n        I = torch.FloatTensor([np.log(l)])\n        I_split = torch.FloatTensor([np.log(l)] * int(z.size(2)))\n        for i in range(l):\n            I += (p_matrix[i][i].log() - p_vector[i].log()).data / l\n            I_split += (p_split_matrix[i][i].log() - p_split_vector[i].log()).data / l\n        # q(z_i) is not independent..\n        # assert np.allclose(I.numpy(), np.sum(I_split.numpy()))\n        return I, I_split\n", "meta": {"hexsha": "a10dd1fc2ca4d01a124ab4ccb09d380ad9d39cfd", "size": 14516, "ext": "py", "lang": "Python", "max_stars_repo_path": "model/VLAE.py", "max_stars_repo_name": "Jueast/VLAE_Pytorch", "max_stars_repo_head_hexsha": "8373390008d611909997e4a3de8396f617d53a49", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "model/VLAE.py", "max_issues_repo_name": "Jueast/VLAE_Pytorch", "max_issues_repo_head_hexsha": "8373390008d611909997e4a3de8396f617d53a49", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model/VLAE.py", "max_forks_repo_name": "Jueast/VLAE_Pytorch", "max_forks_repo_head_hexsha": "8373390008d611909997e4a3de8396f617d53a49", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9168900804, "max_line_length": 121, "alphanum_fraction": 0.5493248829, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3242354120407358, "lm_q1q2_score": 0.1797789596708625}}
{"text": "# Copyright (c) 2014 Evalf\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\"\"\"\nThe matrix module defines an abstract :class:`Matrix` object and several\nimplementations.  Matrix objects support basic addition and subtraction\noperations and provide a consistent insterface for solving linear systems.\nMatrices can be converted into other forms suitable for external processing via\nthe ``export`` method.\n\"\"\"\n\nfrom . import numpy, numeric, warnings, cache, types, config, util\nimport abc, sys, ctypes, treelog as log\n\n\nclass MatrixError(Exception): pass\n\n\nclass Backend(metaclass=abc.ABCMeta):\n  'backend base class'\n\n  def __enter__(self):\n    if hasattr(self, '_old_backend'):\n      raise RuntimeError('This context manager is not reentrant.')\n    global _current_backend\n    self._old_backend = _current_backend\n    _current_backend = self\n    return self\n\n  def __exit__(self, etype, value, tb):\n    if not hasattr(self, '_old_backend'):\n      raise RuntimeError('This context manager is not yet entered.')\n    global _current_backend\n    _current_backend = self._old_backend\n    del self._old_backend\n\n  @abc.abstractmethod\n  def assemble(self, data, index, shape):\n    '''Assemble a (sparse) tensor based on index-value pairs.\n\n    .. Note:: This function is abstract.\n    '''\n\nclass Matrix(metaclass=types.CacheMeta):\n  'matrix base class'\n\n  def __init__(self, shape):\n    assert len(shape) == 2\n    self.shape = shape\n\n  @abc.abstractmethod\n  def __add__(self, other):\n    'add two matrices'\n\n  @abc.abstractmethod\n  def __mul__(self, other):\n    'multiply matrix with a scalar'\n\n  @abc.abstractmethod\n  def __neg__(self, other):\n    'negate matrix'\n\n  def __sub__(self, other):\n    return self.__add__(-other)\n\n  def __rmul__(self, other):\n    return self.__mul__(other)\n\n  def __truediv__(self, other):\n    return self.__mul__(1/other)\n\n  @property\n  @abc.abstractmethod\n  def T(self):\n    'transpose matrix'\n\n  @property\n  def size(self):\n    return numpy.prod(self.shape)\n\n  def rowsupp(self, tol=0):\n    'return row indices with nonzero/non-small entries'\n\n    data, (row, col) = self.export('coo')\n    supp = numpy.zeros(self.shape[0], dtype=bool)\n    supp[row[abs(data) > tol]] = True\n    return supp\n\n  @abc.abstractmethod\n  def solve(self, rhs=None, *, lhs0=None, constrain=None, rconstrain=None, **solverargs):\n    '''Solve system given right hand side vector and/or constraints.\n\n    Args\n    ----\n    rhs : :class:`float` vector or :any:`None`\n        Right hand side vector. `None` implies all zeros.\n    lhs0 : class:`float` vector or :any:`None`\n        Initial values. `None` implies all zeros.\n    constrain : :class:`float` or :class:`bool` array, or :any:`None`\n        Column constraints. For float values, a number signifies a constraint,\n        NaN signifies a free dof. For boolean, a True value signifies a\n        constraint to the value in `lhs0`, a False value signifies a free dof.\n        `None` implies no constraints.\n    rconstrain : :class:`bool` array or :any:`None`\n        Row constrains. A True value signifies a constrains, a False value a free\n        dof. `None` implies that the constraints follow those defined in\n        `constrain` (by implication the matrix must be square).\n\n    Returns\n    -------\n    :class:`numpy.ndarray`\n        Left hand side vector.\n    '''\n\n  @abc.abstractmethod\n  def submatrix(self, rows, cols):\n    '''Create submatrix from selected rows, columns.\n\n    Args\n    ----\n    rows : :class:`bool`/:class:`int` array selecting rows for keeping\n    cols : :class:`bool`/:class:`int` array selecting columns for keeping\n\n    Returns\n    -------\n    :class:`Matrix`\n        Matrix instance of reduced dimensions\n    '''\n\n  def export(self, form):\n    '''Export matrix data to any of supported forms.\n\n    Args\n    ----\n    form : :class:`str`\n      - \"dense\" : return matrix as a single dense array\n      - \"csr\" : return matrix as 3-tuple of (data, indices, indptr)\n      - \"coo\" : return matrix as 2-tuple of (data, (row, col))\n    '''\n\n    raise NotImplementedError('cannot export {} to {!r}'.format(self.__class__.__name__, form))\n\n  def __repr__(self):\n    return '{}<{}x{}>'.format(type(self).__qualname__, *self.shape)\n\ndef preparesolvearguments(wrapped):\n  '''Make rhs optional, add lhs0, constrain, rconstrain arguments.\n\n  See Matrix.solve.'''\n\n  def solve(self, rhs=None, *, lhs0=None, constrain=None, rconstrain=None, **solverargs):\n    nrows, ncols = self.shape\n    if lhs0 is None:\n      x = numpy.zeros(ncols)\n    else:\n      x = numpy.array(lhs0, dtype=float)\n      assert x.shape == (ncols,)\n    if constrain is None:\n      J = numpy.ones(ncols, dtype=bool)\n    else:\n      assert constrain.shape == (ncols,)\n      if constrain.dtype == bool:\n        J = ~constrain\n      else:\n        J = numpy.isnan(constrain)\n        x[~J] = constrain[~J]\n    if rconstrain is None:\n      assert nrows == ncols\n      I = J\n    else:\n      assert rconstrain.shape == (nrows,) and constrain.dtype == bool\n      I = ~rconstrain\n    assert I.sum() == J.sum(), 'constrained matrix is not square: {}x{}'.format(I.sum(), J.sum())\n    if rhs is None:\n      rhs = 0.\n    b = (rhs - self.matvec(x))[J]\n    if b.any():\n      x[J] += wrapped(self if I.all() and J.all() else self.submatrix(I, J), b, **solverargs)\n      if not numpy.isfinite(x).all():\n        raise MatrixError('solver returned non-finite left hand side')\n      log.info('solver returned with residual {:.0e}'.format(numpy.linalg.norm((rhs - self.matvec(x))[J])))\n    else:\n      log.info('skipping solver because initial vector is exact')\n    return x\n  return log.withcontext(solve)\n\n\n## NUMPY BACKEND\n\nclass Numpy(Backend):\n  '''matrix backend based on numpy array'''\n\n  def assemble(self, data, index, shape):\n    array = numeric.accumulate(data, index, shape)\n    return NumpyMatrix(array) if len(shape) == 2 else array\n\nclass NumpyMatrix(Matrix):\n  '''matrix based on numpy array'''\n\n  def __init__(self, core):\n    assert numeric.isarray(core)\n    self.core = core\n    super().__init__(core.shape)\n\n  def __add__(self, other):\n    if not isinstance(other, NumpyMatrix) or self.shape != other.shape:\n      return NotImplemented\n    return NumpyMatrix(self.core + other.core)\n\n  def __mul__(self, other):\n    if not numeric.isnumber(other):\n      return NotImplemented\n    return NumpyMatrix(self.core * other)\n\n  def __neg__(self):\n    return NumpyMatrix(-self.core)\n\n  @property\n  def T(self):\n    return NumpyMatrix(self.core.T)\n\n  def matvec(self, vec):\n    return numpy.dot(self.core, vec)\n\n  def export(self, form):\n    if form == 'dense':\n      return self.core\n    if form == 'coo':\n      ij = self.core.nonzero()\n      return self.core[ij], ij\n    if form == 'csr':\n      rows, cols = self.core.nonzero()\n      return self.core[rows, cols], cols, rows.searchsorted(numpy.arange(self.shape[0]+1))\n    raise NotImplementedError('cannot export NumpyMatrix to {!r}'.format(form))\n\n  def rowsupp(self, tol=0):\n    return numpy.greater(abs(self.core), tol).any(axis=1)\n\n  @preparesolvearguments\n  def solve(self, rhs):\n    try:\n      return numpy.linalg.solve(self.core, rhs)\n    except numpy.linalg.LinAlgError as e:\n      raise MatrixError(e) from e\n\n  def submatrix(self, rows, cols):\n    return NumpyMatrix(self.core[numpy.ix_(rows, cols)])\n\n\n## SCIPY BACKEND\n\ntry:\n  import scipy.sparse.linalg\nexcept ImportError:\n  pass\nelse:\n\n  class Scipy(Backend):\n    '''matrix backend based on scipy's sparse matrices'''\n\n    def assemble(self, data, index, shape):\n      if len(shape) < 2:\n        return numeric.accumulate(data, index, shape)\n      if len(shape) == 2:\n        csr = scipy.sparse.csr_matrix((data, index), shape)\n        return ScipyMatrix(csr)\n      raise MatrixError('{}d data not supported by scipy backend'.format(len(shape)))\n\n  class ScipyMatrix(Matrix):\n    '''matrix based on any of scipy's sparse matrices'''\n\n    def __init__(self, core):\n      self.core = core\n      super().__init__(core.shape)\n\n    def __add__(self, other):\n      if not isinstance(other, ScipyMatrix) or self.shape != other.shape:\n        return NotImplemented\n      return ScipyMatrix(self.core + other.core)\n\n    def __sub__(self, other):\n      if not isinstance(other, ScipyMatrix) or self.shape != other.shape:\n        return NotImplemented\n      return ScipyMatrix(self.core - other.core)\n\n    def __mul__(self, other):\n      if not numeric.isnumber(other):\n        return NotImplemented\n      return ScipyMatrix(self.core * other)\n\n    def __neg__(self):\n      return ScipyMatrix(-self.core)\n\n    def matvec(self, vec):\n      return self.core.dot(vec)\n\n    def export(self, form):\n      if form == 'dense':\n        return self.core.toarray()\n      if form == 'csr':\n        csr = self.core.tocsr()\n        return csr.data, csr.indices, csr.indptr\n      if form == 'coo':\n        coo = self.core.tocoo()\n        return coo.data, (coo.row, coo.col)\n      raise NotImplementedError('cannot export NumpyMatrix to {!r}'.format(form))\n\n    @property\n    def T(self):\n      return ScipyMatrix(self.core.transpose())\n\n    @preparesolvearguments\n    def solve(self, rhs, atol=0, solver='spsolve', callback=None, precon=None, **solverargs):\n      if solver == 'spsolve':\n        log.info('solving system using sparse direct solver')\n        return scipy.sparse.linalg.spsolve(self.core, rhs)\n      assert atol, 'tolerance must be specified for iterative solver'\n      rhsnorm = numpy.linalg.norm(rhs)\n      if rhsnorm <= atol:\n        return numpy.zeros(self.shape[1])\n      log.info('solving system using {} iterative solver'.format(solver))\n      solverfun = getattr(scipy.sparse.linalg, solver)\n      myrhs = rhs / rhsnorm # normalize right hand side vector for best control over scipy's stopping criterion\n      mytol = atol / rhsnorm\n      niter = numpy.array(0)\n      def mycallback(arg):\n        niter[...] += 1\n        # some solvers provide the residual, others the left hand side vector\n        res = numpy.linalg.norm(myrhs - self.matvec(arg)) if numpy.ndim(arg) == 1 else float(arg)\n        if callback:\n          callback(res)\n        with log.context('residual {:.2e} ({:.0f}%)'.format(res, 100. * numpy.log10(res) / numpy.log10(mytol) if res > 0 else 0)):\n          pass\n      M = self.getprecon(precon) if isinstance(precon, str) else precon(self.core) if callable(precon) else precon\n      mylhs, status = solverfun(self.core, myrhs, M=M, tol=mytol, callback=mycallback, **solverargs)\n      if status != 0:\n        raise MatrixError('{} solver failed with status {}'.format(solver, status))\n      log.info('solver converged in {} iterations'.format(niter))\n      return mylhs * rhsnorm\n\n    def getprecon(self, name):\n      name = name.lower()\n      assert self.shape[0] == self.shape[1], 'constrained matrix must be square'\n      log.info('building {} preconditioner'.format(name))\n      if name == 'splu':\n        try:\n          precon = scipy.sparse.linalg.splu(self.core.tocsc()).solve\n        except RuntimeError as e:\n          raise MatrixError(e) from e\n      elif name == 'spilu':\n        try:\n          precon = scipy.sparse.linalg.spilu(self.core.tocsc(), drop_tol=1e-5, fill_factor=None, drop_rule=None, permc_spec=None, diag_pivot_thresh=None, relax=None, panel_size=None, options=None).solve\n        except RuntimeError as e:\n          raise MatrixError(e) from e\n      elif name == 'diag':\n        diag = self.core.diagonal()\n        if not diag.all():\n          raise MatrixError(\"building 'diag' preconditioner: diagonal has zero entries\")\n        precon = numpy.reciprocal(diag).__mul__\n      else:\n        raise MatrixError('invalid preconditioner {!r}'.format(name))\n      return scipy.sparse.linalg.LinearOperator(self.shape, precon, dtype=float)\n\n    def submatrix(self, rows, cols):\n      return ScipyMatrix(self.core[rows,:][:,cols])\n\n\n## INTEL MKL BACKEND\n\nlibmkl = util.loadlib(linux='libmkl_rt.so', darwin='libmkl_rt.dylib', win32='mkl_rt.dll')\nif libmkl is not None:\n\n  # typedefs\n  c_int = types.c_array[numpy.int32]\n  c_long = types.c_array[numpy.int64]\n  c_double = types.c_array[numpy.float64]\n\n  libtbb = util.loadlib(linux='libtbb.so.2', darwin='libtbb.dylib', win32='tbb.dll')\n\n  class MKL(Backend):\n    '''matrix backend based on Intel's Math Kernel Library'''\n\n    def __enter__(self):\n      super().__enter__()\n      usethreads = config.nprocs > 1\n      libmkl.mkl_set_threading_layer(c_long(4 if usethreads else 1)) # 1:SEQUENTIAL, 4:TBB\n      if usethreads and libtbb:\n        self.tbbhandle = ctypes.c_void_p()\n        libtbb._ZN3tbb19task_scheduler_init10initializeEim(ctypes.byref(self.tbbhandle), ctypes.c_int(config.nprocs), ctypes.c_int(2))\n      else:\n        self.tbbhandle = None\n      return self\n\n    def __exit__(self, etype, value, tb):\n      if self.tbbhandle:\n        libtbb._ZN3tbb19task_scheduler_init9terminateEv(ctypes.byref(self.tbbhandle))\n      super().__exit__(etype, value, tb)\n\n    @staticmethod\n    def assemble(data, index, shape):\n      if len(shape) < 2:\n        return numeric.accumulate(data, index, shape)\n      if len(shape) == 2:\n        return MKLMatrix(data, index, shape)\n      raise MatrixError('{}d data not supported by scipy backend'.format(len(shape)))\n\n  class Pardiso:\n    '''simple wrapper for libmkl.pardiso\n\n    https://software.intel.com/en-us/mkl-developer-reference-c-pardiso\n    '''\n\n    _pardiso = libmkl.pardiso\n    _errorcodes = {\n      -1: 'input inconsistent',\n      -2: 'not enough memory',\n      -3: 'reordering problem',\n      -4: 'zero pivot, numerical factorization or iterative refinement problem',\n      -5: 'unclassified (internal) error',\n      -6: 'reordering failed (matrix types 11 and 13 only)',\n      -7: 'diagonal matrix is singular',\n      -8: '32-bit integer overflow problem',\n      -9: 'not enough memory for OOC',\n     -10: 'error opening OOC files',\n     -11: 'read/write error with OOC files',\n     -12: 'pardiso_64 called from 32-bit library',\n    }\n\n    def __init__(self):\n      self.pt = numpy.zeros(64, numpy.int64) # handle to data structure\n\n    @types.apply_annotations\n    def __call__(self, *, phase:c_int, iparm:c_int, maxfct:c_int=1, mnum:c_int=1, mtype:c_int=0, n:c_int=0, a:c_double=None, ia:c_int=None, ja:c_int=None, perm:c_int=None, nrhs:c_int=0, msglvl:c_int=0, b:c_double=None, x:c_double=None):\n      error = ctypes.c_int32(1)\n      self._pardiso(self.pt.ctypes, maxfct, mnum, mtype, phase, n, a, ia, ja, perm, nrhs, iparm, msglvl, b, x, ctypes.byref(error))\n      if error.value:\n        raise MatrixError(self._errorcodes.get(error.value, 'unknown error {}'.format(error.value)))\n\n    def __del__(self):\n      if self.pt.any(): # release all internal memory for all matrices\n        self(phase=-1, iparm=numpy.zeros(64, dtype=numpy.int32))\n        assert not self.pt.any(), 'it appears that Pardiso failed to release its internal memory'\n\n  class MKLMatrix(Matrix):\n    '''matrix implementation based on sorted coo data'''\n\n    __cache__ = 'indptr',\n\n    _factors = False\n\n    def __init__(self, data, index, shape):\n      assert index.shape == (2, len(data))\n      if len(data):\n        # sort rows, columns\n        reorder = numpy.lexsort(index[::-1])\n        index = index[:,reorder]\n        data = data[reorder]\n        # sum duplicate entries\n        keep = numpy.empty(len(reorder), dtype=bool)\n        keep[0] = True\n        numpy.not_equal(index[:,1:], index[:,:-1]).any(axis=0, out=keep[1:])\n        if not keep.all():\n          index = index[:,keep]\n          data = numeric.accumulate(data, [keep.cumsum()-1], [index.shape[1]])\n        if not data.all():\n          nz = data.astype(bool)\n          data = data[nz]\n          index = index[:,nz]\n      self.data = numpy.ascontiguousarray(data, dtype=numpy.float64)\n      self.index = numpy.ascontiguousarray(index, dtype=numpy.int32)\n      super().__init__(shape)\n\n    @property\n    def indptr(self):\n      return self.index[0].searchsorted(numpy.arange(self.shape[0]+1)).astype(numpy.int32, copy=False)\n\n    def __add__(self, other):\n      if not isinstance(other, MKLMatrix) or self.shape != other.shape:\n        return NotImplemented\n      return MKLMatrix(numpy.concatenate([self.data, other.data]), numpy.concatenate([self.index, other.index], axis=1), self.shape)\n\n    def __sub__(self, other):\n      if not isinstance(other, MKLMatrix) or self.shape != other.shape:\n        return NotImplemented\n      return MKLMatrix(numpy.concatenate([self.data, -other.data]), numpy.concatenate([self.index, other.index], axis=1), self.shape)\n\n    def __mul__(self, other):\n      if not numeric.isnumber(other):\n        return NotImplemented\n      return MKLMatrix(self.data * other, self.index, self.shape)\n\n    def __neg__(self):\n      return MKLMatrix(-self.data, self.index, self.shape)\n\n    @property\n    def T(self):\n      return MKLMatrix(self.data, self.index[::-1], self.shape[::-1])\n\n    def matvec(self, vec):\n      rows, cols = self.index\n      return numeric.accumulate(self.data * vec[cols], [rows], [self.shape[0]])\n\n    def export(self, form):\n      if form == 'dense':\n        return numeric.accumulate(self.data, self.index, self.shape)\n      if form == 'csr':\n        return self.data, self.index[1], self.indptr\n      if form == 'coo':\n        return self.data, self.index\n      raise NotImplementedError('cannot export MKLMatrix to {!r}'.format(form))\n\n    def submatrix(self, rows, cols):\n      I, J = self.index\n      keep = numpy.logical_and(rows[I], cols[J])\n      csI = rows.cumsum()\n      csJ = cols.cumsum()\n      return MKLMatrix(self.data[keep], numpy.array([csI[I[keep]]-1, csJ[J[keep]]-1]), shape=(csI[-1], csJ[-1]))\n\n    @preparesolvearguments\n    def solve(self, rhs):\n      log.info('solving {0}x{0} system using MKL Pardiso'.format(self.shape[0]))\n      if self._factors:\n        log.info('reusing existing factorization')\n        pardiso, iparm, mtype = self._factors\n        phase = 33 # solve, iterative refinement\n      else:\n        pardiso = Pardiso()\n        iparm = numpy.zeros(64, dtype=numpy.int32) # https://software.intel.com/en-us/mkl-developer-reference-c-pardiso-iparm-parameter\n        iparm[0] = 1 # supply all values in components iparm[1:64]\n        iparm[1] = 2 # fill-in reducing ordering for the input matrix: nested dissection algorithm from the METIS package\n        iparm[9] = 13 # pivoting perturbation threshold 1e-13 (default for nonsymmetric)\n        iparm[10] = 1 # enable scaling vectors (default for nonsymmetric)\n        iparm[12] = 1 # enable improved accuracy using (non-) symmetric weighted matching (default for nonsymmetric)\n        iparm[34] = 1 # zero base indexing\n        mtype = 11 # real and nonsymmetric\n        phase = 13 # analysis, numerical factorization, solve, iterative refinement\n        self._factors = pardiso, iparm, mtype\n      lhs = numpy.empty(self.shape[1], dtype=numpy.float64)\n      pardiso(phase=phase, mtype=mtype, iparm=iparm, n=self.shape[0], nrhs=1, b=rhs, x=lhs, a=self.data, ia=self.indptr, ja=self.index[1])\n      return lhs\n\n\n## MODULE METHODS\n\n_current_backend = Numpy()\n\ndef backend(names):\n  for name in names.lower().split(','):\n    for cls in Backend.__subclasses__():\n      if cls.__name__.lower() == name:\n        return cls()\n  raise RuntimeError('matrix backend {!r} is not available'.format(names))\n\ndef assemble(data, index, shape):\n  return _current_backend.assemble(data, index, shape)\n\ndef diag(d):\n  assert d.ndim == 1\n  return assemble(d, index=numpy.arange(len(d))[numpy.newaxis].repeat(2, axis=0), shape=d.shape*2)\n\ndef eye(n):\n  return diag(numpy.ones(n))\n\n# vim:sw=2:sts=2:et\n", "meta": {"hexsha": "10c3bc22e15792439f59ee32dc4a6907024f22a7", "size": 20551, "ext": "py", "lang": "Python", "max_stars_repo_path": "nutils/matrix.py", "max_stars_repo_name": "JochenHinz/nutils", "max_stars_repo_head_hexsha": "ac18dd6825b107e2e4c186ebb1598dbf0fff0f77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nutils/matrix.py", "max_issues_repo_name": "JochenHinz/nutils", "max_issues_repo_head_hexsha": "ac18dd6825b107e2e4c186ebb1598dbf0fff0f77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nutils/matrix.py", "max_forks_repo_name": "JochenHinz/nutils", "max_forks_repo_head_hexsha": "ac18dd6825b107e2e4c186ebb1598dbf0fff0f77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3109965636, "max_line_length": 236, "alphanum_fraction": 0.6608437546, "include": true, "reason": "import numpy,import scipy", "num_tokens": 5281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847395, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.1797789572037416}}
{"text": "r\"\"\"Classes for MRI excitation simulations\n\"\"\"\nimport copy\nfrom typing import Optional\nimport inspect\n\nimport numpy as np\nfrom scipy import interpolate\nimport torch\nfrom torch import tensor, Tensor\n\nfrom mrphy import γH, dt0, gmax0, smax0, rfmax0, T1G, T2G, π\nfrom mrphy import utils, beffective, sims\n\n__all__ = ['Pulse', 'SpinArray', 'SpinCube', 'Examples']\n\n\nclass Pulse(object):\n    r\"\"\"Pulse object of RF and GR\n\n    Usage:\n        ``pulse = Pulse(rf, gr, *, dt, gmax, smax, rfmax, desc, device,``\\\n        `` dtype)``\n\n    Inputs:\n        - ``rf``: `(N,xy, nT,(nCoils))` \"Gauss\", ``xy`` for separating real \\\n          and imag part.\n        - ``gr``: `(N,xyz,nT)`, \"Gauss/cm\"\n        - ``dt``: `()` ⊻ `(N ⊻ 1,)`, \"Sec\", dwell time.\n        - ``gmax``: `()` ⊻ `(N ⊻ 1, xyz ⊻ 1)`, \"Gauss/cm\", max \\|gradient\\|.\n        - ``smax``: `()` ⊻ `(N ⊻ 1, xyz ⊻ 1)`, \"Gauss/cm/Sec\", max \\\n          \\|slew rate\\|.\n        - ``rfmax``: `()` ⊻ `(N ⊻ 1,(nCoils))`, \"Gauss\", max \\|RF\\|.\n        - ``desc``: str, an description of the pulse to be constructed.\n        - ``device``: torch.device.\n        - ``dtype``: torch.dtype.\n\n    Properties:\n        - ``device``\n        - ``dtype``\n        - ``is_cuda``\n        - ``shape``: ``(N,1,nT)``\n        - ``gmax``: `(N ⊻ 1, xyz)`, \"Gauss/cm\", max \\|gradient\\|.\n        - ``smax``: `(N ⊻ 1, xyz)`, \"Gauss/cm/Sec\", max \\|slew rate\\|.\n        - ``rfmax``: `(N ⊻ 1,(nCoils))`, \"Gauss\", max \\|RF\\|.\n        - ``rf``: `(N,xy, nT,(nCoils))`, \"Gauss\", ``xy`` for separating real \\\n          and imag part.\n        - ``gr``: `(N,xyz,nT)`, \"Gauss/cm\"\n        - ``dt``: `(N ⊻ 1,)`, \"Sec\", dwell time.\n        - ``desc``: str, an description of the pulse to be constructed.\n    \"\"\"\n\n    _readonly = ('device', 'dtype', 'is_cuda', 'shape')\n    _limits = ('gmax', 'smax', 'rfmax')\n    __slots__ = set(_readonly + _limits + ('rf', 'gr', 'dt', 'desc'))\n\n    def __init__(\n        self,\n        rf: Optional[Tensor] = None, gr: Optional[Tensor] = None, *,\n        dt: Tensor = dt0,\n        gmax: Tensor = gmax0, smax: Tensor = smax0, rfmax: Tensor = rfmax0,\n        desc: str = \"generic pulse\",\n        device: torch.device = torch.device('cpu'),\n        dtype: torch.dtype = torch.float32\n    ):\n        assert(isinstance(device, torch.device) and\n               isinstance(dtype, torch.dtype))\n\n        # Defaults\n        rf_miss, gr_miss = rf is None, gr is None\n        assert (not(rf_miss and gr_miss)), \"Missing both `rf` and `gr` inputs\"\n\n        object.__setattr__(self, 'device', device)\n        object.__setattr__(self, 'dtype', dtype)\n        object.__setattr__(self, 'is_cuda', self.device.type == 'cuda')\n\n        kw = {'device': self.device, 'dtype': self.dtype}\n\n        if rf_miss:\n            N, nT = gr.shape[0], gr.shape[2]\n            rf = torch.zeros((N, 2, nT), **kw)\n        else:\n            N, nT = rf.shape[0], rf.shape[2]\n            if gr_miss:\n                gr = torch.zeros((N, 3, nT), **kw)\n            else:\n                assert (N == gr.shape[0] and nT == gr.shape[2])\n        object.__setattr__(self, 'shape', torch.Size((N, 1, nT)))\n\n        self.rf, self.gr = rf.to(**kw), gr.to(**kw)\n        self.dt, self.gmax, self.smax, self.rfmax = dt, gmax, smax, rfmax\n        self.desc = desc\n        return\n\n    def __setattr__(self, k, v):\n        if 'deepcopy' in (_.function for _ in inspect.stack()):\n            # Hack, this enables `deepcopy()` w/o overriding `__deepcopy__()`.\n            # Generator is faster than list comprehension.\n            object.__setattr__(self, k, v)\n            return\n\n        if k in self._readonly:\n            raise AttributeError(f\"'Pulse' object attribute '{k}'\"\n                                 \" is read-only\")\n\n        if k != 'desc':\n            kw = {'device': self.device, 'dtype': self.dtype}\n            v = (v.to(**kw) if isinstance(v, Tensor) else tensor(v, **kw))\n\n        if k in ('rf', 'gr'):\n            assert(v.shape[0] == self.shape[0] and v.shape[2] == self.shape[2])\n        elif (k in ('gmax', 'smax')):  # -> (N ⊻ 1, xyz)\n            v = v.expand((1 if v.ndim == 0 else v.shape[0], self.gr.shape[1]))\n        elif k == 'rfmax':  # -> (N ⊻ 1, (nCoils))\n            if v.ndim == 0:\n                v = v[None]\n            elif v.ndim == 2 and v.shape[1] == 1:\n                v = v[:, 0]\n        elif k == 'dt':\n            if v.ndim == 0:\n                v = v[None]\n            assert(v.ndim == 1)\n\n        object.__setattr__(self, k, v)\n        return\n\n    def asdict(self, *, toNumpy: bool = True) -> dict:\n        r\"\"\"Convert mrphy.mobjs.Pulse object to dict\n\n        Usage:\n            ``d = pulse.asdict(*, toNumpy)``\n\n        Inputs:\n            - ``toNumpy``: [T/f], convert Tensor to Numpy arrays.\n        Outputs:\n            - ``d``: dict, dictionary with detached data identical to the \\\n              object.\n        \"\"\"\n        _ = ('rf', 'gr', 'dt', 'gmax', 'smax', 'rfmax')\n        fn_np = ((lambda x: x.detach().cpu().numpy()) if toNumpy else\n                 (lambda x: x.detach()))\n\n        d = {k: fn_np(getattr(self, k)) for k in _}\n        d.update({k: getattr(self, k) for k in ('desc', 'device', 'dtype')})\n\n        return d\n\n    def beff(\n            self, loc: Tensor, *,\n            Δf: Optional[Tensor] = None, b1Map: Optional[Tensor] = None,\n            γ: Tensor = γH\n    ) -> Tensor:\n        r\"\"\"Compute B-effective of provided location from the pulse\n\n        Usage:\n            ``beff = pulse.beff(loc, *, Δf, b1Map, γ)``\n        Inputs:\n            - ``loc``: `(N,*Nd,xyz)`, \"cm\", locations.\n        Optionals:\n            - ``Δf``: `(N,*Nd,)`, \"Hz\", off-resonance.\n            - ``b1Map``: `(N,*Nd,xy,(nCoils))`, a.u., transmit sensitivity.\n            - ``γ``: `(N,*Nd)`, \"Hz/Gauss\", gyro-ratio\n        Outputs:\n            - ``beff``: `(N,*Nd,xyz,nT)`\n        \"\"\"\n        device = self.device\n        loc = loc.to(device=device)\n        fn = lambda x: None if x is None else x.to(device=device)  # noqa: E731\n        Δf, b1Map, γ = (fn(x) for x in (Δf, b1Map, γ))\n\n        return beffective.rfgr2beff(self.rf, self.gr, loc,\n                                    Δf=Δf, b1Map=b1Map, γ=γ)\n\n    def interpT(self, dt: Tensor, *, kind: str = 'linear') -> 'Pulse':\n        r\"\"\" Interpolate pulse of `dt` by `kind`.\n\n        Usage:\n            ``new_pulse = pulse.interpT(dt, *, kind)``\n        Inputs:\n            - ``dt``: `(1,)`, \"Sec\", new simulation dwell time.\n            - ``kind``: str, passed to scipy.interpolate.interp1d.\n        Outputs:\n            - ``new_pulse``: mrphy.mobjs.Pulse object.\n\n        .. note::\n            This method requires both `dt` and `self.dt` to be unique/global,\n            i.e., of shape ``(1,)``, which ensures pulse length to be the same\n            within a batch after interpolation.\n        \"\"\"\n        assert(self.dt.numel() == dt.numel() == 1)\n\n        dt_o_np, dt_n_np = self.dt.item(), dt.item()\n        if dt_o_np == dt_n_np:\n            return copy.deepcopy(self)\n\n        axis = 2  # Along temporal dimension\n        dkw = {'device': self.device, 'dtype': self.dtype}\n        kw = {'axis': axis, 'kind': kind, 'copy': False, 'assume_sorted': True}\n\n        f_np = lambda x: x.detach().cpu().numpy()  # noqa: E731\n        f_0 = lambda x: np.dstack((np.zeros_like(x[:, :, [0]]),  # noqa: E731\n                                   x))\n\n        # convert to np array, then prepend 0's.\n        rf_np, gr_np = f_0(f_np(self.rf)), f_0(f_np(self.gr))\n\n        nT = rf_np.shape[axis]\n\n        t_o = np.arange(0, nT)*dt_o_np  # (nT,)\n        t_n = np.arange(1, t_o[-1]//dt_n_np + 1)*dt_n_np\n\n        f_rf = interpolate.interp1d(t_o, rf_np, **kw)\n        f_gr = interpolate.interp1d(t_o, gr_np, **kw)\n\n        rf_n, gr_n = tensor(f_rf(t_n), **dkw), tensor(f_gr(t_n), **dkw)\n\n        desc = f\"{self.desc} + interpT\\'ed: dt = {dt_n_np}\"\n        return Pulse(rf_n, gr_n, dt=dt, desc=desc, **dkw)\n\n    def to(\n        self, *,\n        device: torch.device = torch.device('cpu'),\n        dtype: torch.dtype = torch.float32\n    ) -> 'Pulse':\n        r\"\"\"Duplicate the object to the prescribed device with dtype\n\n        Usage:\n            ``new_pulse = pulse.to(*, device, dtype)``\n        Inputs:\n            - ``device``: torch.device\n            - ``dtype``: torch.dtype\n        Outputs:\n            - ``new_pulse``: mrphy.mobjs.Pulse object.\n        \"\"\"\n        if self.device == device and self.dtype == dtype:\n            return self\n        return Pulse(self.rf, self.gr, dt=self.dt, desc=self.desc,\n                     device=device, dtype=dtype)\n\n\nclass SpinArray(object):\n    r\"\"\"mrphy.mobjs.SpinArray object\n\n    Usage:\n        ``spinarray = SpinArray(shape, mask, *, T1_, T2_, γ_, M_, device,``\\\n        `` dtype)``\n        ``spinarray = SpinArray(shape, mask, *, T1, T2, γ, M, device, dtype)``\n    Inputs:\n        - ``shape``: tuple, e.g., ``(N, nx, ny, nz)``.\n    Optionals:\n        - ``mask``: `(1, *Nd)`, where does compact attributes locate in `Nd`.\n        - ``T1`` ⊻ ``T1_``: `(N, *Nd ⊻ nM)`, \"Sec\", T1 relaxation coeff.\n        - ``T2`` ⊻ ``T2_``: `(N, *Nd ⊻ nM)`, \"Sec\", T2 relaxation coeff.\n        - ``γ`` ⊻ ``γ_``: `(N, *Nd ⊻ nM)`,  \"Hz/Gauss\", gyro ratio.\n        - ``M`` ⊻ ``M_``: `(N, *Nd ⊻ nM, xyz)`, spins, equilibrium ``[0 0 1]``.\n        - ``device``: torch.device.\n        - ``dtype``: torch.dtype\n\n    Properties:\n        - ``shape``: `(N, *Nd)`.\n        - ``mask``: `(1, *Nd)`.\n        - ``device``.\n        - ``dtype``.\n        - ``ndim``: ``len(shape)``\n        - ``nM``: ``nM = torch.count_nonzero(mask).item()``.\n        - ``T1_``: `(N, nM)`, \"Sec\", T1 relaxation coeff.\n        - ``T2_``: `(N, nM)`, \"Sec\", T2 relaxation coeff.\n        - ``γ_``: `(N, nM)`, \"Hz/Gauss\", gyro ratio.\n        - ``M_``: `(N, nM, xyz)`, spins, equilibrium [0 0 1]\n\n    .. warning::\n        - Do NOT modify the ``mask`` of an object, e.g., \\\n          ``spinarray.mask[0] = True``.\n        - Do NOT proceed indexed/masked assignments over any non-compact \\\n          attribute, e.g., ``spinarray.T1[0] = T1G`` or \\\n          ``spinarray.T1[mask] = T1G``.\n          The underlying compact attributes will **NOT** be updated, since \\\n          they do not share memory.\n          The only exception is when ``torch.all(mask == True)`` and the \\\n          underlying compact is **contiguous**, where the non-compact is just \\\n          a ``view((N, *Nd, ...))``.\n          Checkout :func:`~mrphy.mobjs.SpinArray.crds_` and \\\n          :func:`~mrphy.mobjs.SpinArray.mask_` for indexed/masked access to \\\n          compacts.\n\n    .. tip::\n        - ``mask`` is GLOBAL for a batch, in other words, one cannot specify \\\n          distinct masks w/in a batch. \\\n          This design is to reduce storage/computations in, e.g., \\\n          ``applypulse`` (``blochsim``), avoiding extra allocations. \\\n          For DNN applications where an in-batch variation of ``mask`` may \\\n          seemingly be of interest, having ``torch.all(mask == True)`` and \\\n          postponing the variations to eventual losses evaluation can be a \\\n          better design, which allows reuse of ``M_``, etc., avoiding \\\n          repetitive allocations.\n    \"\"\"\n\n    _readonly = ('shape', 'mask', 'device', 'dtype', 'is_cuda', 'ndim', 'nM')\n    _compact = ('T1_', 'T2_', 'γ_', 'M_')\n    __slots__ = set(_readonly + _compact)\n\n    def __init__(\n        self, shape: tuple, mask: Optional[Tensor] = None, *,\n        T1: Optional[Tensor] = None, T1_: Optional[Tensor] = None,\n        T2: Optional[Tensor] = None, T2_: Optional[Tensor] = None,\n        γ: Optional[Tensor] = None,  γ_: Optional[Tensor] = None,\n        M: Optional[Tensor] = None,  M_: Optional[Tensor] = None,\n        device: torch.device = torch.device('cpu'),\n        dtype: torch.dtype = torch.float32\n    ):\n\n        mask = (torch.ones((1,)+shape[1:], dtype=torch.bool, device=device)\n                if mask is None else mask.to(device=device))\n\n        assert(isinstance(device, torch.device) and\n               isinstance(dtype, torch.dtype) and\n               mask.dtype == torch.bool and\n               mask.shape == (1,)+shape[1:])\n\n        object.__setattr__(self, 'shape', shape)\n        object.__setattr__(self, 'mask', mask)\n        object.__setattr__(self, 'ndim', len(shape))\n        object.__setattr__(self, 'nM', torch.count_nonzero(mask).item())\n        object.__setattr__(self, 'device', device)\n        object.__setattr__(self, 'dtype', dtype)\n        object.__setattr__(self, 'is_cuda', self.device.type == 'cuda')\n\n        assert((T1 is None) or (T1_ is None))\n        if T1 is None:\n            self.T1_ = (T1G if T1_ is None else T1_)\n        else:\n            self.T1 = T1\n\n        assert((T2 is None) or (T2_ is None))\n        if T2 is None:\n            self.T2_ = (T2G if T2_ is None else T2_)\n        else:\n            self.T2 = T2\n\n        assert((γ is None) or (γ_ is None))\n        if γ is None:\n            self.γ_ = (γH if γ_ is None else γ_)\n        else:\n            self.γ = γ\n\n        assert((M is None) or (M_ is None))\n        if M is None:\n            self.M_ = (tensor([0., 0., 1.]) if M_ is None else M_)\n        else:\n            self.M = M\n\n        return\n\n    def __getattr__(self, k):  # provoked only when `__getattribute__` failed\n        if k+'_' not in self._compact:\n            raise AttributeError(f\"'SpinArray' has no attribute '{k}'\")\n\n        v_ = getattr(self, k+'_')\n        return (self.embed(v_) if self.nM != np.prod(self.shape[1:]) else\n                v_.reshape(self.shape+v_.shape[2:]))  # ``mask`` is all True\n\n    def __setattr__(self, k_, v_):\n        if 'deepcopy' in (_.function for _ in inspect.stack()):\n            # Hack, this enables `deepcopy()` w/o overriding `__deepcopy__()`.\n            # Generator is faster than list comprehension.\n            object.__setattr__(self, k_, v_)\n            return\n\n        if k_ in self._readonly:\n            raise AttributeError(f\"'SpinArray' object attribute '{k_}'\"\n                                 \" is read-only\")\n\n        # Transfer ``v_`` to ``kw`` before ``extract`\n        kw = {'device': self.device, 'dtype': self.dtype}\n        v_ = (v_.to(**kw) if isinstance(v_, Tensor) else tensor(v_, **kw))\n\n        shape = self.shape\n        if k_+'_' in self._compact:  # enable non-compact assignment\n            k_ = k_+'_'\n            v_ = self.extract(v_.expand(shape+(3,) if k_ == 'M_' else shape))\n\n        # `tensor.expand(size)` needs `tensor.shape` broadcastable with `size`\n        if k_ == 'M_':\n            if v_.shape != shape[:1]+(self.nM, 3):  # (N, nM, xyz)\n                v_ = v_.expand(shape[:1]+(self.nM, 3)).clone()\n        elif k_ in self._compact:  # (T1_, T2_, γ_)\n            v_ = v_.expand((self.shape[0], self.nM))  # (N, nM)\n\n        object.__setattr__(self, k_, v_)\n        return\n\n    def applypulse(\n        self, pulse: Pulse, *,\n        doEmbed: bool = False, doRelax: bool = True, doUpdate: bool = False,\n        loc: Optional[Tensor] = None, loc_: Optional[Tensor] = None,\n        Δf: Optional[Tensor] = None, Δf_: Optional[Tensor] = None,\n        b1Map: Optional[Tensor] = None, b1Map_: Optional[Tensor] = None\n    ) -> Tensor:\n        r\"\"\"Apply a pulse to the spinarray object\n\n        Typical usage:\n            ``M = spinarray.applypulse(pulse, *, loc, doEmbed=True, doRelax,``\\\n            `` doUpdate, Δf, b1Map)``\n            ``M_ = spinarray.applypulse(pulse, *, loc_, doEmbed=False, `` \\\n            ``doRelax, doUpdate, Δf_, b1Map_)``\n        Inputs:\n            - ``pulse``: mrphy.mobjs.Pulse.\n            - ``loc`` ⊻ ``loc_``: `(N,*Nd ⊻ nM,xyz)`, \"cm\", locations.\n        Optionals:\n            - ``doEmbed``: [t/F], return ``M`` or ``M_``\n            - ``doRelax``: [T/f], do relaxation during Bloch simulation.\n            - ``doUpdate``: [t/F], update ``self.M_``\n            - ``Δf``⊻ ``Δf_``: `(N,*Nd ⊻ nM)`, \"Hz\", off-resonance.\n            - ``b1Map`` ⊻ ``b1Map_``: `(N,*Nd ⊻ nM,xy,(nCoils))`, transmit \\\n              sensitivity.\n        Outputs:\n            - ``M`` ⊻ ``M_``: `(N,*Nd ⊻ nM,xyz)`\n\n        .. note::\n            When ``doUpdate == True and doEmbed == False``, the output compact\n            magnetization Tensor is a reference to ``self.M_``, and needs\n            caution when being accessed.\n        \"\"\"\n        assert ((loc_ is None) != (loc is None))  # XOR\n        loc_ = (loc_ if loc is None else self.extract(loc))\n\n        assert ((Δf_ is None) or (Δf is None))\n        Δf_ = (Δf_ if Δf is None else self.extract(Δf))\n\n        assert ((b1Map_ is None) or (b1Map is None))\n        b1Map_ = (b1Map_ if b1Map is None else self.extract(b1Map))\n\n        beff_ = self.pulse2beff(pulse, loc_=loc_,\n                                Δf_=Δf_, b1Map_=b1Map_, doEmbed=False)\n\n        if doRelax:\n            kw_bsim = {'T1': self.T1_, 'T2': self.T2_}\n        else:\n            kw_bsim = {'T1': None, 'T2': None}\n\n        kw_bsim['γ'] = self.γ_\n        kw_bsim['dt'] = pulse.dt\n\n        M_ = sims.blochsim(self.M_, beff_, **kw_bsim)\n        if doUpdate:\n            self.M_ = M_\n        M_ = (self.embed(M_) if doEmbed else M_)\n        return M_\n\n    def asdict(self, *, toNumpy: bool = True, doEmbed: bool = True) -> dict:\n        r\"\"\"Convert mrphy.mobjs.SpinArray object to dict\n\n        Usage:\n            ``d = spinarray.asdict(*, toNumpy, doEmbed)``\n\n        Inputs:\n            - ``toNumpy``: [T/f], convert ``Tensor`` to Numpy arrays.\n            - ``doEmbed``: [T/f], embed compactly stored (nM) data to the \\\n              mask (\\*Nd).\n        Outputs:\n            - ``d``: dict, dictionary with detached data identical to the \\\n              object.\n        \"\"\"\n        fn_np = ((lambda x: x.detach().cpu().numpy()) if toNumpy else\n                 (lambda x: x.detach()))\n\n        _ = (('T1', 'T2', 'γ', 'M') if doEmbed else ('T1_', 'T2_', 'γ_', 'M_'))\n        d = {k: fn_np(getattr(self, k)) for k in _}\n        d['mask'] = fn_np(getattr(self, 'mask'))\n\n        d.update({k: getattr(self, k) for k in ('shape', 'device', 'dtype')})\n        return d\n\n    def crds_(self, crds: list) -> list:\n        r\"\"\"Compute crds for compact attributes\n\n        Data in a SpinArray object is stored compactly, such that only those\n        correspond to ``1`` on the ``spinarray.mask`` is kept.\n        This function is provided to facilitate indexing the compact data from\n        regular indices, by computing (ix, iy, iz) -> iM\n\n        Usage:\n            ``crds_ = spinarray.crds_(crds)``\n        Inputs:\n            - ``crds``: indices for indexing non-compact attributes.\n        Outputs:\n            - ``crds_``: list, ``len(crds_) == 2+len(crds)-self.ndim``.\n\n        ``v_[crds_] == v[crds]``, when ``v_[crds_]=new_value`` is effective.\n        \"\"\"\n        mask, ndim, nM = self.mask, self.ndim, self.nM\n        assert (len(crds) >= ndim)\n        crds_ = [crds[i] for i in (0,)+tuple(range(ndim, len(crds)))]\n        m = torch.zeros(mask.shape, dtype=tensor(mask.numel()).dtype)-1\n        m[mask] = torch.arange(nM)\n        inds_ = [ind_ for ind_ in m[[[0]]+crds[1:ndim]].tolist() if ind_ != -1]\n\n        crds_.insert(1, inds_)\n\n        return crds_\n\n    def dim(self) -> int:\n        r\"\"\"Nd of the spinarray object, syntax sugar for len(spinarray.shape)\n\n        Usage:\n            ``Nd = spinarray.dim()``\n        \"\"\"\n        return len(self.shape)\n\n    def embed(self, v_: Tensor, *, out: Optional[Tensor] = None) -> Tensor:\n        \"\"\"Embed compact data into the spinarray.mask\n\n        Usage:\n            ``out = spinarray.embed(v_, *, out)``\n        Inputs:\n            - ``v_``: `(N, nM, ...)`, must be contiguous.\n        Optionals:\n            - ``out``: `(N, *Nd, ...)`, in-place holder.\n        Outputs:\n            - ``out``: `(N, *Nd, ...)`.\n        \"\"\"\n        oshape = self.shape+v_.shape[2:]\n        out = (v_.new_full(oshape, float('NaN')) if out is None else out)\n        mask = self.mask.expand(self.shape)\n        out[mask] = v_.view((-1,)+v_.shape[2:])\n        # `v.reshape()` has intermediate alloc, leaving `out` pointless.\n        # out[mask] = v_.reshape((-1,)+v_.shape[2:])\n        return out\n\n    def extract(self, v: Tensor, *, out_: Optional[Tensor] = None) -> Tensor:\n        r\"\"\"Extract data with the spinarray.mask, making it compact\n\n        Usage:\n            ``out_ = spinarray.extract(v, *, out_)``\n        Inputs:\n            - ``v``: `(N, *Nd, ...)`.\n        Optionals:\n            - ``out_``: `(N, nM, ...)`, in-place holder, must be contiguous.\n        Outputs:\n            - ``out_``: `(N, nM, ...)`.\n        \"\"\"\n        oshape = (self.shape[0], self.nM)+v.shape[self.ndim:]\n        out_ = (v.new_empty(oshape) if out_ is None else out_)\n        mask = self.mask.expand(self.shape)\n        # ! do NOT use ``out_.reshape()`; It creats new tensor when should\n        # fail instead.\n        out_.view((-1,)+v.shape[self.ndim:]).copy_(v[mask])\n        # ``v[mask].reshape()`` has intermediate alloc, leaving ``out_``\n        # pointless.\n        # out_.copy_(v[mask].reshape((-1,)+v.shape[self.ndim:]))\n        return out_\n\n    def freeprec(\n        self, dur: Tensor, *,\n        doEmbed: bool = False, doRelax: bool = True, doUpdate: bool = False,\n        Δf: Optional[Tensor] = None, Δf_: Optional[Tensor] = None\n    ) -> Tensor:\n        r\"\"\"Free precession of duration ``dur``\n\n        Typical usage:\n            ``M = obj.freeprec(dur, doEmbed=True, doRelax, doUpdate, Δf)``\n            ``M_ = obj.applypulse(dur, doEmbed=False, doRelax, doUpdate, Δf_)``\n        Inputs:\n            - ``dur``: `()` ⊻ `(N ⊻ 1,)`, \"Sec\", duration of free-precession.\n        Optionals:\n            - ``doEmbed``: [t/F], return ``M`` or ``M_``\n            - ``doRelax``: [T/f], do relaxation during free precession.\n            - ``doUpdate``: [t/F], update ``self.M_``\n            - ``Δf``⊻ ``Δf_``: `(N ⊻ 1,*Nd ⊻ nM)`, \"Hz\", off-resonance.\n        Outputs:\n            - ``M`` ⊻ ``M_``: `(N,*Nd ⊻ nM,xyz)`\n\n        .. note::\n            When ``doUpdate == True and doEmbed == False``, the output compact\n            magnetization Tensor is a reference to ``self.M_``, and needs\n            caution when being accessed.\n        \"\"\"\n        assert ((Δf_ is None) or (Δf is None))\n        Δf_ = (Δf_ if Δf is None else self.extract(Δf))\n\n        if doRelax:\n            kw_bsim = {'T1': self.T1_, 'T2': self.T2_}\n        else:\n            kw_bsim = {'T1': None, 'T2': None}\n\n        M_ = sims.freeprec(self.M_, dur, **kw_bsim, Δf=Δf_)\n        if doUpdate:\n            self.M_ = M_\n        M_ = (self.embed(M_) if doEmbed else M_)\n        return M_\n\n    def mask_(self, *, mask: Tensor) -> Tensor:\n        r\"\"\"Extract the compact region of an input external ``mask``.\n\n        Usage:\n            ``mask_ = spinarray.mask_(mask)``\n        Inputs:\n            - ``mask``: `(1, *Nd)`.\n        Outputs:\n            - ``mask_``: `(1, nM)`, ``mask_`` can be used on compact \\\n              attributes.\n        \"\"\"\n        mask_ = mask(self.mask).reshape((1, -1))\n        return mask_\n\n    def numel(self) -> int:\n        r\"\"\"Number of spins for the spinarray object, incompact.\n\n        Syntax sugar of ``spinarray.mask.numel()``, effectively\n        ``prod(spinarray.size())``.\n\n        Usage:\n            ``res = spinarray.numel()``\n        \"\"\"\n        return self.mask.numel()\n\n    def pulse2beff(\n        self, pulse: Pulse, *, doEmbed: bool = False,\n        loc: Optional[Tensor] = None, loc_: Optional[Tensor] = None,\n        Δf: Optional[Tensor] = None, Δf_: Optional[Tensor] = None,\n        b1Map: Optional[Tensor] = None, b1Map_: Optional[Tensor] = None\n    ) -> Tensor:\n        r\"\"\"Compute B-effective of ``pulse`` with the spinarray's parameters\n\n        Typical usage:\n            ``beff = spinarray.pulse2beff(pulse, *, loc, doEmbed=True, Δf, ``\\\n            ``b1Map)``\n            ``beff_ = spinarray.pulse2beff(pulse, *, loc_, doEmbed=False, ``\\\n            ``Δf_, b1Map_)``\n        Inputs:\n            - ``pulse``: mrphy.mobjs.Pulse.\n            - ``loc`` ⊻ ``loc_``: `(N,*Nd ⊻ nM,xyz)`, \"cm\", locations.\n        Optionals:\n            - ``doEmbed``: [t/F], return ``beff`` or ``beff_``\n            - ``Δf`` ⊻ ``Δf_``: `(N,*Nd ⊻ nM)`, \"Hz\", off-resonance.\n            - ``b1Map`` ⊻ ``b1Map_``: `(N,*Nd ⊻ nM,xy,(nCoils))`, transmit \\\n              sensitivity.\n        Outputs:\n            - ``beff`` ⊻ ``beff_``: `(N,*Nd ⊻ nM,xyz,nT)`.\n        \"\"\"\n        assert ((loc_ is None) != (loc is None))  # XOR\n        loc_ = (loc_ if loc is None else self.extract(loc))\n\n        assert ((Δf_ is None) or (Δf is None))\n        Δf_ = (Δf_ if Δf is None else self.extract(Δf))\n\n        assert ((b1Map_ is None) or (b1Map is None))\n        b1Map_ = (b1Map_ if b1Map is None else self.extract(b1Map))\n\n        pulse = pulse.to(device=self.device, dtype=self.dtype)\n        beff_ = pulse.beff(loc_, γ=self.γ_, Δf=Δf_, b1Map=b1Map_)\n        beff_ = (self.embed(beff_) if doEmbed else beff_)\n        return beff_\n\n    def size(self) -> tuple:\n        r\"\"\"Size of the spinarray object.\n\n        Syntax sugar of ``spinarray.shape``.\n\n        Usage:\n            ``sz = spinarray.size()``\n        \"\"\"\n        return self.shape\n\n    def to(\n        self, *,\n        device: torch.device = torch.device('cpu'),\n        dtype: torch.dtype = torch.float32\n    ) -> 'SpinArray':\n        r\"\"\"Duplicate the object to the prescribed device with dtype\n\n        Usage:\n            ``new_spinarray = spinarray.to(*, device, dtype)``\n        Inputs:\n            - ``device``: torch.device\n            - ``dtype``: torch.dtype\n        Outputs:\n            - ``new_spinarray``: mrphy.mobjs.SpinArray object\n        \"\"\"\n        if self.device == device and self.dtype == dtype:\n            return self\n        return SpinArray(self.shape, self.mask, T1_=self.T1_, T2_=self.T2_,\n                         γ_=self.γ_, M_=self.M_, device=device, dtype=dtype)\n\n\nclass SpinCube(SpinArray):\n    r\"\"\"mrphy.mobjs.SpinCube object\n\n    Usage:\n        ``SpinCube(shape, fov, mask, *, ofst, Δf_, T1_, T2_, γ_, M_, device,``\\\n        `` dtype)``\n        ``SpinCube(shape, fov, mask, *, ofst, Δf, T1, T2, γ, M, device,``\\\n        '' dtype)``\n    Inputs:\n        - ``shape``: tuple, e.g., ``(N, nx, ny, nz)``.\n        - ``fov``: `(N, xyz)`, \"cm\", field of view.\n    Optionals:\n        - ``mask``: `(1, *Nd)`, where does compact attributes locate in `Nd`.\n        - ``ofst``: `(N, xyz)`, Tensor \"cm\", fov offset from iso-center.\n        - ``Δf`` ⊻ ``Δf_``: `(N, *Nd ⊻ nM)`, \"Hz\", off-resonance map.\n        - ``T1`` ⊻ ``T1_``: `(N, *Nd ⊻ nM)`, \"Sec\", T1 relaxation coeff.\n        - ``T2`` ⊻ ``T2_``: `(N, *Nd ⊻ nM)`, \"Sec\", T2 relaxation coeff.\n        - ``γ`` ⊻ ``γ_``: `(N, *Nd ⊻ nM)`,  \"Hz/Gauss\", gyro ratio.\n        - ``M`` ⊻ ``M_``: `(N, *Nd ⊻ nM, xyz)`, spins, equilibrium ``[0 0 1]``.\n        - ``device``: torch.device.\n        - ``dtype``: torch.dtype\n\n    Properties:\n        - ``spinarray``: SpinArray object.\n        - ``Δf_``: `(N, nM)`, \"Hz\", off-resonance map.\n        - ``loc_``: `(N, nM, xyz)`, \"cm\", location of spins.\n        - ``fov``: `(N, xyz)`, \"cm\", field of view.\n        - ``ofst``: `(N, xyz)`, \"cm\", fov offset from iso-center.\n    \"\"\"\n\n    _readonly = ('spinarray', 'loc_')\n    _compact = ('Δf_', 'loc_')  # `loc_` depends on `shape`, `fov` and `ofst`\n    __slots__ = set(_readonly+_compact+('fov', 'ofst'))\n\n    def __init__(\n        self, shape: tuple, fov: Tensor, *, mask: Optional[Tensor] = None,\n        ofst: Tensor = tensor([[0., 0., 0.]]),\n        Δf: Optional[Tensor] = None, Δf_: Optional[Tensor] = None,\n        T1: Optional[Tensor] = None, T1_: Optional[Tensor] = None,\n        T2: Optional[Tensor] = None, T2_: Optional[Tensor] = None,\n        γ: Optional[Tensor] = None,  γ_: Optional[Tensor] = None,\n        M: Optional[Tensor] = None,  M_: Optional[Tensor] = None,\n        device: torch.device = torch.device('cpu'),\n        dtype: torch.dtype = torch.float32\n    ):\n        # 1) `SpinCube` is subclassed to `SpinArray`.\n        # 2) Attribute `spinarray` is included to enable extracting the\n        # `SpinArray` part of a `SpinCube()` instance.\n        # 3) `SpinCube.__getattr__` is tweaked for immitating super class\n        # access to `SpinCube().spinarray`'s attributes.\n        # To have these three features, we cannot have `super().__init__()` in\n        # `SpinCube`, which will disable the `__getattr__` tweak.\n        sp = SpinArray(shape, mask, T1=T1, T1_=T1_, T2=T2, T2_=T2_, γ=γ, γ_=γ_,\n                       M=M, M_=M_, device=device, dtype=dtype)\n        object.__setattr__(self, 'spinarray', sp)\n\n        kw = {'device': sp.device, 'dtype': sp.dtype}\n        # setattr(self, k, v), avoid computing `loc_` w/ `fov` & `ofst` not set\n        object.__setattr__(self, 'fov', fov.to(**kw))\n        object.__setattr__(self, 'ofst', ofst.to(**kw))\n        # Initialize ``loc_`` in memory, reuse it.\n        object.__setattr__(self, 'loc_',\n                           torch.zeros((sp.shape[0], sp.nM, 3), **kw))\n        self._update_loc_()  # compute ``loc_`` from set ``fov`` & ``ofst`\n\n        assert((Δf is None) or (Δf_ is None))\n        if Δf is None:\n            self.Δf_ = (tensor(0.) if Δf_ is None else Δf_)\n        else:\n            self.Δf = Δf\n\n        return\n\n    def __getattr__(self, k):  # provoked only when `__getattribute__` failed\n        if k+'_' not in self._compact:  # k not in ('Δf_', 'loc')\n            # Cannot do `self.spinarray` or `getattr(self, 'spinarray')` here.\n            # They cause infinite recursion when `SpinCube().__getattr__()` is\n            # queried with `spinarray`, which may happen during `deepcopy` or\n            # `pickle`.\n            # Therefore, call `object.__getattribute__()` here, and let it fail\n            # when it should.\n            spinarray = object.__getattribute__(self, 'spinarray')\n            try:\n                return getattr(spinarray, k)\n            except AttributeError:\n                raise AttributeError(f\"'SpinCube' has no attribute '{k}'\")\n\n        v_, sp = getattr(self, k+'_'), self.spinarray\n        return (sp.embed(v_) if sp.nM != np.prod(sp.shape[1:]) else\n                v_.reshape(sp.shape+v_.shape[2:]))  # `mask` is all True\n\n    def __setattr__(self, k_, v_):\n        if 'deepcopy' in (_.function for _ in inspect.stack()):\n            # Hack, this enables `deepcopy()` w/o overriding `__deepcopy__()`.\n            # Generator is faster than list comprehension.\n            object.__setattr__(self, k_, v_)\n            return\n\n        if (k_ in self._readonly) or (k_+'_' in self._readonly):\n            raise AttributeError(f\"'SpinCube' object attribute '{k_}'\"\n                                 \" is read-only\")\n\n        sp = self.spinarray\n        if k_ in SpinArray.__slots__ or k_+'_' in SpinArray.__slots__:\n            setattr(sp, k_, v_)\n            return\n\n        kw = {'device': sp.device, 'dtype': sp.dtype}\n        v_ = (v_.to(**kw) if isinstance(v_, Tensor) else tensor(v_, **kw))\n\n        shape = sp.shape\n        if k_+'_' in self._compact:  # `loc_` excluded by beginning assert\n            k_ = k_+'_'\n            v_ = self.extract(v_.expand(shape+(3,) if k_ == 'loc_' else shape))\n\n        if k_ == 'Δf_':\n            v_ = v_.expand((shape[0], sp.nM))  # (N, nM)\n        elif k_ in ('fov', 'ofst'):\n            assert(v_.ndim == 2)\n\n        object.__setattr__(self, k_, v_)\n\n        # update `loc_` when needed\n        if k_ in ('fov', 'ofst'):\n            self._update_loc_()\n        return\n\n    def _update_loc_(self):\n        r\"\"\"Update ``spincube.loc_`` using FOV and offset\n\n        The ``spincube``'s spin locations are computed internally from set FOV\n        and offset.\n\n        Usage:\n            ``loc_ = spincube._update_loc_()``\n        \"\"\"\n        loc_, fov, ofst = self.loc_, self.fov, self.ofst\n        sp = self.spinarray\n        kw = {'device': sp.device, 'dtype': sp.dtype}\n\n        # locn (1, prod(Nd), xyz)  normalized locations, [-0.5, 0.5)\n        shape, mask = sp.shape, sp.mask\n        crdn = ((torch.arange(x, **kw)-utils.ctrsub(x))/x for x in shape[1:])\n        _locn = torch.meshgrid(*crdn)  # ((*Nd,), (*Nd), (*Nd))\n\n        for i in range(3):  # xyz, (N, nM)\n            # According to `memory_profiler`, this does not provoke allocs.\n            # `torch.addr`'s `vec2`, _locn[i][mask[0, ...]], provokes alloc.\n            loc_[..., i] = (fov[:, None, i]*_locn[i][mask[0, ...]][None, ...]\n                            + ofst[:, None, i])\n\n        return\n\n    def applypulse(\n        self, pulse: Pulse, *,\n        doEmbed: bool = False, doRelax: bool = True, doUpdate: bool = False,\n        b1Map: Optional[Tensor] = None, b1Map_: Optional[Tensor] = None\n    ) -> Tensor:\n        r\"\"\"Apply a pulse to the spincube object\n\n        Usage:\n            ``M = spincube.applypulse(pulse, *, doEmbed=True, doRelax, b1Map)``\n            ``M_ = spincube.applypulse(pulse, *, doEmbed=False, doRelax,``\\\n            `` b1Map_)``\n\n        Inputs:\n            - ``pulse``: mobjs.Pulse object.\n        Optionals:\n            - ``doEmbed``: [t/F], return ``M`` or ``M_``.\n            - ``doRelax``: [T/f], do relaxation during Bloch simulation.\n            - ``b1Map`` ⊻ ``b1Map_``: `(N,*Nd ⊻ nM,xy,(nCoils))`, transmit \\\n              sensitivity.\n        Outputs:\n            - ``M`` ⊻ ``M_``: `(N,*Nd ⊻ nM,xyz)`.\n        \"\"\"\n        assert ((b1Map_ is None) or (b1Map is None))\n        b1Map_ = (b1Map_ if b1Map is None else self.extract(b1Map))\n\n        return self.spinarray.applypulse(pulse, doEmbed=doEmbed,\n                                         doRelax=doRelax, doUpdate=doUpdate,\n                                         Δf_=self.Δf_, loc_=self.loc_,\n                                         b1Map_=b1Map_)\n\n    def freeprec(\n        self, dur: Tensor, *,\n        doEmbed: bool = False, doRelax: bool = True, doUpdate: bool = False\n    ) -> Tensor:\n        r\"\"\"Free precession of duration ``dur``\n\n        Typical usage:\n            ``M = obj.freeprec(dur, doEmbed=True, doRelax, doUpdate)``\n            ``M_ = obj.applypulse(dur, doEmbed=False, doRelax, doUpdate)``\n        Inputs:\n            - ``dur``: `()` ⊻ `(N ⊻ 1,)`, \"Sec\", duration of free-precession.\n        Optionals:\n            - ``doEmbed``: [t/F], return ``M`` or ``M_``\n            - ``doRelax``: [T/f], do relaxation during free precession.\n            - ``doUpdate``: [t/F], update ``self.M_``\n        Outputs:\n            - ``M`` ⊻ ``M_``: `(N,*Nd ⊻ nM,xyz)`\n\n        .. note::\n            When ``doUpdate == True and doEmbed == False``, the output compact\n            magnetization Tensor is a reference to ``self.M_``, and needs\n            caution when being accessed.\n        \"\"\"\n\n        return self.spinarray.freeprec(dur, Δf_=self.Δf_, doEmbed=doEmbed,\n                                       doRelax=doRelax, doUpdate=doUpdate)\n\n    def asdict(self, *, toNumpy: bool = True, doEmbed: bool = True) -> dict:\n        r\"\"\"Convert mrphy.mobjs.SpinCube object to dict\n\n        Usage:\n            ``d = spincube.asdict(*, toNumpy, doEmbed)``\n\n        Inputs:\n            - ``toNumpy``: [T/f], convert ``Tensor`` to Numpy arrays.\n            - ``doEmbed``: [T/f], embed compactly stored (nM) data to the \\\n              mask `(*Nd)`.\n        Outputs:\n            - ``d``: dict, dictionary with detached data identical to the \\\n              object.\n        \"\"\"\n        fn_np = ((lambda x: x.detach().cpu().numpy()) if toNumpy else\n                 (lambda x: x.detach()))\n\n        _ = (('loc', 'Δf') if doEmbed else ('loc', 'Δf'))\n        d = {k: fn_np(getattr(self, k)) for k in _}\n\n        d.update({k: getattr(self, k) for k in ('fov', 'ofst')})\n\n        d.update(self.spinarray.asdict(toNumpy=toNumpy, doEmbed=doEmbed))\n        return d\n\n    def pulse2beff(\n        self, pulse: Pulse, *,\n        doEmbed: bool = False,\n        b1Map: Optional[Tensor] = None, b1Map_: Optional[Tensor] = None\n    ) -> Tensor:\n        r\"\"\"Compute B-effective of ``pulse`` with the spincube's parameters\n\n        Typical usage:\n            ``beff = spincube.pulse2beff(pulse, *, doEmbed=True, b1Map)``\n            ``beff_ = spincube.pulse2beff(pulse, *, doEmbed=False, b1Map_)``\n        Inputs:\n            - ``pulse``: mrphy.mobjs.Pulse.\n        Optionals:\n            - ``doEmbed``: [t/F], return ``beff`` or ``beff_``.\n            - ``b1Map`` ⊻ ``b1Map_``: `(N,*Nd ⊻ nM,xy,(nCoils))`, transmit \\\n              sensitivity.\n        Outputs:\n            - ``beff`` ⊻ ``beff_``: `(N,*Nd ⊻ nM,xyz,nT)`.\n        \"\"\"\n        return self.spinarray.pulse2beff(pulse, self.loc_, doEmbed=doEmbed,\n                                         Δf_=self.Δf_,\n                                         b1Map=b1Map, b1Map_=b1Map_)\n\n    def to(\n        self, *,\n        device: torch.device = torch.device('cpu'),\n        dtype: torch.dtype = torch.float32\n    ) -> 'SpinCube':\n        r\"\"\"Duplicate the object to the prescribed device with dtype\n\n        Usage:\n            ``new_spincube = spincube.to(*, device, dtype)``\n        Inputs:\n            - ``device``: torch.device.\n            - ``dtype``: torch.dtype.\n        Outputs:\n            - ``new_spincube``: mrphy.mobjs.SpinCube object.\n        \"\"\"\n        if self.device == device and self.dtype == dtype:\n            return self\n        return SpinCube(self.shape, self.fov, ofst=self.ofst, Δf_=self.Δf_,\n                        T1_=self.T1_, T2_=self.T2_, γ_=self.γ_, M_=self.M_,\n                        device=device, dtype=dtype)\n\n\nclass SpinBolus(SpinArray):\n    def __init__(\n        self\n    ):\n        pass\n    pass\n\n\nclass Examples(object):\n    r\"\"\"Class for quickly creating exemplary instances to play around with.\n    \"\"\"\n    @staticmethod\n    def pulse() -> Pulse:\n        r\"\"\"Create a mrphy.mobjs.Pulse object.\n        \"\"\"\n        device = torch.device('cpu')\n        dtype = torch.float32\n\n        kw = {'dtype': dtype, 'device': device}\n        N, nT, dt = 1, 512, dt0\n\n        # pulse: Sec; Gauss; Gauss/cm.\n        pulse_size = (N, 1, nT)\n        t = torch.arange(0, nT, **kw).reshape(pulse_size)\n        rf = 10*torch.cat([torch.cos(t/nT*2*π),                # (1,xy, nT)\n                           torch.sin(t/nT*2*π)], 1)\n        gr = torch.cat([torch.ones(pulse_size, **kw),\n                        torch.ones(pulse_size, **kw),\n                        10*torch.atan(t - round(nT/2))/π], 1)  # (1,xyz,nT)\n\n        # Pulse\n        p = Pulse(rf=rf, gr=gr, dt=dt, **kw)\n        return p\n\n    @staticmethod\n    def spinarray() -> SpinArray:\n        r\"\"\"Create a mrphy.mobjs.SpinArray object.\n        \"\"\"\n        device = torch.device('cpu')\n        dtype = torch.float32\n        kw = {'dtype': dtype, 'device': device}\n\n        N, Nd, γ_ = 1, (3, 3, 3), γH\n        shape = (N, *Nd)\n        mask = torch.zeros((1,)+Nd, device=device, dtype=torch.bool)\n        mask[0, :, 1, :], mask[0, 1, :, :] = True, True\n        T1_, T2_ = tensor([[1.]], **kw), tensor([[4e-2]], **kw)\n\n        array = SpinArray(shape, mask=mask, T1_=T1_, T2_=T2_, γ_=γ_, **kw)\n        return array\n\n    @staticmethod\n    def spincube() -> SpinCube:\n        r\"\"\"Create a mrphy.mobjs.SpinCube object.\n        \"\"\"\n        device = torch.device('cpu')\n        dtype = torch.float32\n        kw = {'dtype': dtype, 'device': device}\n\n        N, Nd, γ_ = 1, (3, 3, 3), γH\n        shape = (N, *Nd)\n        mask = torch.zeros((1,)+Nd, device=device, dtype=torch.bool)\n        mask[0, :, 1, :], mask[0, 1, :, :] = True, True\n        fov, ofst = tensor([[3., 3., 3.]], **kw), tensor([[0., 0., 1.]], **kw)\n        T1_, T2_ = tensor([[1.]], **kw), tensor([[4e-2]], **kw)\n\n        cube = SpinCube(shape, fov, mask=mask, ofst=ofst,\n                        T1_=T1_, T2_=T2_, γ_=γ_, **kw)\n\n        cube.Δf = torch.sum(-cube.loc[0:1, :, :, :, 0:2], dim=-1) * γ_\n        return cube\n", "meta": {"hexsha": "bba628757ab2c2307a9d1fcd37e206e96ae0ad40", "size": 39654, "ext": "py", "lang": "Python", "max_stars_repo_path": "mrphy/mobjs.py", "max_stars_repo_name": "tianrluo/MRphy.py", "max_stars_repo_head_hexsha": "4245ccadc4a87b227a733dc46290a9e09aea2bc1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-12T18:18:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T20:54:39.000Z", "max_issues_repo_path": "mrphy/mobjs.py", "max_issues_repo_name": "tianrluo/MRphy.py", "max_issues_repo_head_hexsha": "4245ccadc4a87b227a733dc46290a9e09aea2bc1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-24T12:06:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-30T21:58:42.000Z", "max_forks_repo_path": "mrphy/mobjs.py", "max_forks_repo_name": "tianrluo/MRphy.py", "max_forks_repo_head_hexsha": "4245ccadc4a87b227a733dc46290a9e09aea2bc1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-18T15:20:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-08T01:18:41.000Z", "avg_line_length": 38.2391513983, "max_line_length": 79, "alphanum_fraction": 0.5127351591, "include": true, "reason": "import numpy,from scipy", "num_tokens": 11691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3486451353339457, "lm_q1q2_score": 0.17976837529812845}}
{"text": "\"\"\"\nAn Implementation of Euler Integration for reaction path following.\n\nReferences:\n[1] C. Gonzalez and H. B. Schlegel, J. Chem. Phys. 90(4):2154 (An Improved Algorithm for Reaction-Path Following)\n\"\"\"\n\n__authors__  = \"Wallace D. Derricotte\"\n__credits__  = [\"Wallace D. Derricotte\"]\n\n__copyright__  = \"(c) 2018-2019, Derricotte Research Group\"\n__license__    = \"MIT License\"\n__date__       = \"2019-01-02\"\n\nimport numpy as np\nimport psi4\nimport os\nimport sys\nimport json\nfrom pyscf import gto, scf, dft, grad, solvent, mp \n\n\n########################\n## Gradient Functions ##\n########################\n\ndef energy_calc(params, current_geom, mol):\n    energy = 0.0\n    if(params.qm_program=='pyscf'):\n        pymol = gto.Mole()\n        pymol.verbose = 0\n        geom_vec = []\n        for i in range(params.natoms):\n            atom = [params.symbols[i],]\n            atom_coords = []\n            for j in range(3):\n                atom_coords.append(current_geom[i][j])\n            atom_coords = tuple(atom_coords)\n            atom.append(atom_coords)\n            geom_vec.append(atom)\n        #print(geom_vec)\n        pymol.atom = geom_vec\n        pymol.unit = 'Bohr'\n        pymol.basis = params.basis\n        pymol.charge = params.charge\n        pymol.spin = params.mult - 1\n        pymol.build()\n        if(params.method == \"scf\"):\n            scf_obj = scf.RHF(pymol)\n        #if(params.method == \"mp2\"): #TODO Doesn't work yet. Few things left to figure out. \n        #    scf_obj = scf.RHF(pymol).run()\n        #    scf_obj = mp.MP2(scf_obj).run()\n        #if(params.method == \"dft\"):\n        #    scf_obj = dft.RKS(mol)\n        #    scf_obj.xc = params.xc_functional\n        if(params.do_solvent):\n            solv_obj = solvent.ddCOSMO(scf_obj)\n            solv_obj.with_solvent.eps = params.eps\n            solv_obj.run()\n            energy = solv_obj.kernel()\n            print(energy)\n        else:\n            energy = scf_obj.scf()\n\n    if(params.qm_program=='psi4'):\n        mol.set_geometry(psi4.core.Matrix.from_array(current_geom))\n        grad_method = \"%s/%s\" %(params.method,params.basis)\n        psi4.core.set_output_file(\"psi4_out.dat\", False)\n        psi4.set_options(params.keywords)\n        psi4.set_num_threads(params.nthreads)\n        energy = psi4.energy(grad_method) \n    return energy\n\n\ndef grad_calc(params,current_geom, mol):\n    \"\"\"\n        Uses Psi4 to calculate the energy gradient and returns the mass-weighted\n        gradient and energy. Here any of the keywords the user provides in the \n        .json input are used to set the options for the energy calculation.\n\n        Parameters:\n        ----------\n            params(self) -- contains initialized shared parameters.\n            current_geom(np array) -- Matrix of size natoms x 3 containing the geometry.\n            mol(psi4.Molecule) -- Psi4 molecule object containing the current molecule.\n        Returns:\n        -------\n            grad_mw(np array) -- Mass weighted gradient matrix of size natoms x 3.\n            E(float) -- single-point energy from Psi4 calculation. \n    \"\"\"\n    if(params.qm_program=='pyscf'):\n        pymol = gto.Mole()\n        pymol.verbose = 0\n        geom_vec = []\n        for i in range(params.natoms):\n            atom = [params.symbols[i],]\n            atom_coords = []\n            for j in range(3):\n                atom_coords.append(current_geom[i][j])\n            atom_coords = tuple(atom_coords)\n            atom.append(atom_coords)\n            geom_vec.append(atom)\n        #print(geom_vec)\n        pymol.atom = geom_vec\n        pymol.unit = 'Bohr'\n        pymol.basis = params.basis\n        pymol.charge = params.charge\n        pymol.spin = params.mult - 1\n        pymol.build()\n        if(params.method == \"scf\"):\n            scf_obj = scf.RHF(pymol)\n        #if(params.method == \"mp2\"): #TODO Doesn't work yet. Few things left to figure out.\n        #    mf = scf.RHF(pymol).run()\n        #    scf_obj = mp.MP2(mf).run()\n        if(params.do_solvent):\n            solv_obj = solvent.ddCOSMO(scf_obj)\n            solv_obj.with_solvent.eps = params.eps\n            solv_obj.run()\n            E = solv_obj.kernel()\n            grad = solv_obj.nuc_grad_method().kernel()\n        else:\n            E = scf_obj.kernel()\n            grad = scf_obj.nuc_grad_method().kernel()\n        #print(grad)\n        grad_mw = mass_weight(params.natoms, grad, mol)        \n    if(params.qm_program=='psi4'):\n        mol.set_geometry(psi4.core.Matrix.from_array(current_geom))\n        mol.fix_orientation(True)\n        mol.fix_com(True)\n        mol.reset_point_group('c1')\n        grad_method = \"%s/%s\" %(params.method,params.basis)\n        psi4.core.set_output_file(\"psi4_out.dat\", False)\n        psi4.set_options(params.keywords)\n        psi4.set_num_threads(params.nthreads)\n        E, wfn = psi4.energy(grad_method,return_wfn=True)\n        psi4.set_num_threads(params.nthreads)\n        grad = np.asarray(psi4.gradient(grad_method,ref_wfn=wfn))\n        #print(grad)\n        grad_mw = mass_weight(params.natoms, grad, mol)\n    return grad_mw, E\n\n\ndef parabolic_fit(xs, ys):\n    fit = np.polyfit(xs, ys, deg=2)\n    fit = np.poly1d(fit)\n    minima = fit.deriv().r\n    real_minima = minima[minima.imag==0].real\n    return real_minima\n\n\ndef ishida_morokuma(params,output_file):\n    \"\"\"\n        This function runs the Ishida-Morokuma irc procedure\n    \"\"\"\n    max_steps = 1000\n    #params = Params()\n    line_step_size = 0.3333*params.step_size\n    #line_step_size = 0.025*params.step_size\n    current_geom = params.geometry\n    mol = psi4.geometry(params.geometry)\n    starting_vec = np.asarray(params.ts_vec)\n    grad_method = \"%s/%s\" %(params.method,params.basis)\n    steps = 0\n    E = 0.0\n    previous_E = 0.0\n    del_E = 0.0\n    energies = []\n    current_geom = np.asarray(mol.geometry())\n    #print(current_geom)\n    output = open(output_file, \"a\")\n    output.write('\\n\\n--Intrinsic Reaction Coordinate (%s)--\\n' %(params.direction))\n    output.write('\\n--------------------------------------------------------------------------------------\\n')\n    output.write('\\n{:>20} {:>20} {:>20} {:>20}\\n'.format('Coordinate', 'E', 'Delta E', 'Gradient Norm'))\n    output.write('-------------------------------------------------------------------------------------\\n')\n    output.close()\n    last_energy = None\n    while (steps <= max_steps):\n        if(steps==0):\n            grad_0 = mass_weight(params.natoms, starting_vec, mol)\n            E_0 = energy_calc(params, current_geom, mol)\n        else:\n            grad_0, E_0  = grad_calc(params, current_geom, mol)\n        \n        if(last_energy):\n            del_E = E_0 - last_energy\n        if((last_energy and (E_0 > last_energy) and steps > params.grace_period)):\n            output = open(output_file, \"a\") \n            print(\"\\nIRC Energy Has Increased! You're Likely Near a Minimum!\\n\")\n            output.close()\n            break\n        if(last_energy and np.abs(del_E)<params.e_conv and steps > params.grace_period):\n            output = open(output_file, \"a\")\n            print(\"\\nIRC Has Converged!\\n\")\n            output.close()\n            break\n        mol.save_xyz_file('imk_step_'+str(steps)+'.xyz',False)\n        coords_1 = euler_step(params.natoms, current_geom, grad_0,params.step_size,mol)\n        current_geom = coords_1\n        #mol.set_geometry(psi4.core.Matrix.from_array(current_geom))\n        grad_1, E_1 = grad_calc(params, current_geom, mol) \n        grad_0_norm = np.linalg.norm(grad_0)\n        grad_1_norm = np.linalg.norm(grad_1)\n\n        # Calculate Bisector (Eq. 6)\n        D = grad_0/grad_0_norm - grad_1/grad_1_norm\n        D_normed = D/np.linalg.norm(D)\n\n        line_xs = [0,]\n        line_energies = [E_1,]\n\n        line_step_size_thresh = 1.5*line_step_size\n        #line_step_size_thresh = 2.0*line_step_size\n        \n        # Find useful point by projecting grad_1 on D\n        grad_1_normed = grad_1/grad_1_norm\n        step_D1 = grad_1*D_normed*D_normed*line_step_size\n        step_D1_norm = np.linalg.norm(step_D1)\n       # if step_D1_norm < line_step_size_thresh:\n       #     coords_1 = mass_weight_geom(params.natoms, coords_1, mol)\n       #     current_geom = coords_1 + step_D1\n       #     current_geom = un_mass_weight_geom(params.natoms, current_geom, mol) \n       #     mol.set_geometry(psi4.core.Matrix.from_array(current_geom))\n       #     step_D1_E = psi4.energy(grad_method)\n       #     line_xs.append(step_D1_norm)\n       #     line_energies.append(step_D1_E)\n        # Otherwise take a step along D\n       # else:\n        step_D2 = line_step_size*D_normed\n        step_D2_norm = np.linalg.norm(step_D2)\n        coords_1 = mass_weight_geom(params.natoms, coords_1, mol)\n        current_geom = coords_1 + step_D2\n        current_geom = un_mass_weight_geom(params.natoms, coords_1, mol)\n        #mol.set_geometry(psi4.core.Matrix.from_array(current_geom))\n        #step_D2_E = psi4.energy(grad_method)\n        step_D2_E = energy_calc(params, current_geom, mol)\n        #line_xs.append(step_D2_norm)\n        line_xs.append(step_D2_norm)\n        line_energies.append(step_D2_E)\n\n        # Calculate 3rd point by taking a half step size\n        if(line_energies[1] >= line_energies[0]):\n            step_D3 = 0.5*line_step_size*D_normed # Half Step Size\n            #new_del = 0.5*line_step_size\n        else:\n            step_D3 = 2.0*line_step_size*D_normed #Double Step Size\n            #new_del = 2.0*line_step_size\n        \n        step_D3_norm = np.linalg.norm(step_D3)\n        #coords_1 = mass_weight_geom(params.natoms, coords_1, mol)\n        current_geom = coords_1 + step_D3\n        current_geom = un_mass_weight_geom(params.natoms, current_geom, mol)\n        #mol.set_geometry(psi4.core.Matrix.from_array(current_geom))\n        #step_D3_E = psi4.energy(grad_method)\n        step_D3_E = energy_calc(params, current_geom, mol)\n        line_xs.append(step_D3_norm)\n        line_energies.append(step_D3_E) \n\n        real_minimum = parabolic_fit(line_xs, line_energies)\n        \n        current_geom = coords_1 + (real_minimum*D_normed)\n        current_geom = un_mass_weight_geom(params.natoms, current_geom, mol)\n        \n        mol.set_geometry(psi4.core.Matrix.from_array(current_geom))\n\n        last_energy = E_0\n        \n        #params.damp -= 0.5\n\n        if(params.direction==\"backward\"):\n            coord = -1*steps*params.step_size\n        else:\n            coord = steps*params.step_size\n        print_step(output_file,coord, E_0, del_E, grad_0_norm)\n        steps = steps+1\n    output = open(output_file, \"a\")\n    output.write('-------------------------------------------------------------------------------------\\n')\n    output.close()\n    with open('irc_%s.xyz' %params.direction,'w') as outfile:\n        for i in range(steps):\n            with open('imk_step_'+str(i)+'.xyz')as infile:\n                outfile.write(infile.read())\n        os.system('rm imk_step*')\n\n            \n\n\ndef mass_weight(natoms,grad, mol):\n    \"\"\"\n        Mass weights the given gradient\n\n        Parameters:\n        ----------\n            natoms(int) -- number of atoms in the molecule.\n            grad(np array) -- matrix of size natoms x 3 containing the gradients.\n        Returns:\n        -------\n            grad_mw(np array) -- Mass weighted gradient matrix of size natoms x 3.\n    \"\"\"\n    grad_mw = np.zeros((natoms, 3))\n    for i in range(natoms):\n        for j in range(3):\n            grad_mw[i][j] = grad[i][j]/np.sqrt(mol.mass(i))\n    return grad_mw\n\ndef mass_weight_geom(natoms,geom,mol):\n    \"\"\"\n        Mass weights the given coordinates\n\n        Parameters:\n        ----------\n            natoms(int) -- number of atoms in the molecule.\n            geom(np array) -- matrix of size natoms x 3 containing the cartesian geometry (bohr).\n        Returns:\n        -------\n            coord_mw(np array) -- Mass weighted coordinate matrix of size natoms x 3 in units\n            amu^(1/2)*bohr.\n    \"\"\"\n    coord_mw = np.zeros((natoms, 3))\n    for i in range(natoms):\n        for j in range(3):\n            coord_mw[i][j] = geom[i][j]*np.sqrt(mol.mass(i))\n    return coord_mw\n\ndef un_mass_weight_geom(natoms,geom_mw,mol):\n    \"\"\"\n        Un-Mass weights the given coordinates. Displacements are done along the mass weighted\n        coordinate and then un-mass-weighted prior to gradient calculations.\n\n        Parameters:\n        ----------\n            natoms(int) -- number of atoms in the molecule.\n            geom_mw(np array) -- matrix of size natoms x 3 containing the cartesian geometry\n            in units amu^(1/2)*bohr\n        Returns:\n        -------\n            coord(np array) -- Coordinate matrix of size natoms x 3 in units bohr.\n    \"\"\"\n    coord = np.zeros((natoms, 3))\n    for i in range(natoms):\n        for j in range(3):\n            coord[i][j] = geom_mw[i][j]/np.sqrt(mol.mass(i))\n    return coord\n\ndef euler_step(natoms,current_geom,grad,step_size,mol):\n    \"\"\"\n        Take a single Euler step along the gradient. The coordinates are first mass weighted prior\n        to the Euler step and then un-mass-weighted for printing/gradient calculation. This \n        procedure is adapted from Equation 2 in Ref [1].\n\n        Parameters:\n        ----------\n            natoms(int) -- number of atoms in the molecule.\n            current_geom(np array) -- matrix of size natoms x 3 containing the cartesian \n            geometry in units bohr.\n            grad(np array) -- mass-weighted gradient matrix of size natoms x 3 containing\n            the gradients in units amu^(1/2)*bohr.\n            step_size(float) -- user provided IRC step size in units amu^(1/2)*bohr. \n    \"\"\"\n    current_geom = mass_weight_geom(natoms, current_geom,mol)\n    grad_norm = np.asarray(np.linalg.norm(grad))\n    current_geom -= step_size*(grad/grad_norm)\n    #real_step = step_size/grad_norm\n    #current_geom -= step_size*(grad)\n    #current_geom -= real_step*(grad)\n    current_geom = un_mass_weight_geom(natoms, current_geom,mol)\n    return current_geom\n\ndef irc(output_file):\n    \"\"\"\n        This function runs the irc procedure\n    \"\"\"\n    max_steps = 1000\n    params = Params()\n    \n    mol = psi4.geometry(params.geometry)\n    print(mol)\n    starting_vec = np.asarray(params.ts_vec)\n\n    steps = 0\n    E = 0.0\n    previous_E = 0.0\n    energies = []\n    current_geom = np.asarray(mol.geometry())\n    #print(current_geom)\n    output = open(output_file, \"a\")\n    output.write('\\n\\n--Intrinsic Reaction Coordinate (%s)--\\n' %(params.direction))\n    output.write('\\n-------------------------------------------------------------------------------------')\n    output.write('\\n{:>20} {:>20} {:>20} {:>20}\\n'.format('Coordinate', 'E', 'Delta E', 'Gradient Norm'))\n    output.write('-------------------------------------------------------------------------------------\\n')\n    output.close()\n    while (steps <= max_steps):\n        mol.save_xyz_file('euler_step_'+str(steps)+'.xyz',False)\n        if(steps==0):\n            grad = mass_weight(params.natoms, starting_vec, mol)\n        else:\n            grad, E  = grad_calc(params, current_geom, mol)\n    \n        current_geom = euler_step(params.natoms, current_geom, grad,params.step_size,mol)\n        if(steps > 20):\n            if(E>previous_E):\n                #print(\"pyREX: New energy is greater! Likely near a minimum!\")\n                break\n        steps = steps + 1\n        del_E = E - previous_E\n        previous_E = E\n        if(params.direction==\"backward\"):\n            coord = -1*steps*params.step_size\n        else:\n            coord = steps*params.step_size\n        print_step(output_file,coord, E, del_E, grad)\n    output = open(output_file, \"a\")\n    output.write('-------------------------------------------------------------------------------------\\n')\n    output.close()\n    with open('irc_%s.xyz' %params.direction,'w') as outfile:\n        for i in range(steps):\n            with open('euler_step_'+str(i)+'.xyz')as infile:\n                outfile.write(infile.read())\n        os.system('rm euler_step*')\n\ndef print_step(output_file, coord, energy, del_E, grad):\n    output = open(output_file, \"a\")\n    grad_norm = np.linalg.norm(grad)\n    output.write('\\n{:>20.4f} {:>20.7f} {:>20.10f} {:>20.10f}\\n'.format(coord, energy, del_E, grad_norm)) \n    output.close()  \n", "meta": {"hexsha": "eeb7e58d252959cd37c53d09b6696535a2c51821", "size": 16264, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyrex/euler.py", "max_stars_repo_name": "derricottegroup/pyrex", "max_stars_repo_head_hexsha": "edc3b2bd73314b87212d9d4069c0b511f7cfb021", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-11-21T14:42:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-23T03:06:50.000Z", "max_issues_repo_path": "pyrex/euler.py", "max_issues_repo_name": "derricottegroup/pyrex", "max_issues_repo_head_hexsha": "edc3b2bd73314b87212d9d4069c0b511f7cfb021", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-11-26T11:19:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-31T13:11:30.000Z", "max_forks_repo_path": "pyrex/euler.py", "max_forks_repo_name": "WDerricotte/pyrex", "max_forks_repo_head_hexsha": "edc3b2bd73314b87212d9d4069c0b511f7cfb021", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-04T12:22:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-04T12:22:21.000Z", "avg_line_length": 38.2682352941, "max_line_length": 113, "alphanum_fraction": 0.5860796852, "include": true, "reason": "import numpy", "num_tokens": 4069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3486451285660856, "lm_q1q2_score": 0.17976837180848498}}
{"text": "__author__ = \"Luke Liu\"\n#encoding=\"utf-8\"\n# -*- coding: utf-8 -*-\n\n# 引入第三方库\nimport tensorflow as tf\nimport numpy as np\nimport urllib\nimport tarfile\nimport os\nimport matplotlib.pyplot as plt\nfrom imageio import imread, imsave, mimsave\nfrom scipy.misc import imresize\nimport glob\n\n\"\"\"\n准备工作\n\"\"\"\n# database's path\nfilename = 'D:/BaiduYunDownload/python_exe/dataset/lfw.tgz'\ndirectory = 'lfw_imgs'\nnew_dir = 'lfw_new_imgs'\n# # 解压文件\n# tar = tarfile.open(filename, 'r:gz')\n# tar.extractall(path=directory)\n# tar.close()\n# #统计照片的个数，并且把照片存入new_dir\n# count = 0\n# for dir_, _, files in os.walk(directory):\n#     for file_ in files:\n#         img = imread(os.path.join(dir_, file_))\n#         imsave(os.path.join(new_dir, '%d.png' % count), img)\n#         count += 1\n# print(count)\n#指定dataset\ndataset = 'D:\\BaiduYunDownload\\python_exe\\dataset\\scut_faces\\AF' # LFW\n# dataset = 'celeba' # CelebA\nimages = glob.glob(os.path.join(dataset, '*.*'))\nprint(len(images))\n# 定义一个输出sample的file\nOUTPUT_DIR = 'samples_'\nif not os.path.exists(OUTPUT_DIR):\n    os.mkdir(OUTPUT_DIR)\n\n\"\"\"\n建立参数\n\n\"\"\"\n#\nbatch_size = 100\n# noise dim is 100\nz_dim = 100\nWIDTH = 64\nHEIGHT = 64\n\n# 指定输入与是否训练\nX = tf.placeholder(dtype=tf.float32, shape=[None, HEIGHT, WIDTH, 3], name='X')\nnoise = tf.placeholder(dtype=tf.float32, shape=[None, z_dim], name='noise')\nis_training = tf.placeholder(dtype=tf.bool, name='is_training')\n\ndef lrelu(x, leak=0.2):\n    return tf.maximum(x, leak * x)\n\n#先用sigmoid处理到0-1，然后进过cross-entropy\ndef sigmoid_cross_entropy_with_logits(x, y):\n    return tf.nn.sigmoid_cross_entropy_with_logits(logits=x, labels=y)\n\n# 判别器部分, 2 return ,\ndef discriminator(image, reuse=None, is_training=is_training):\n    momentum = 0.9\n    with tf.variable_scope('discriminator', reuse=reuse):\n        #Conv1_: 64 filter is 5, stride is 2, activation is Lekrelu\n        h0 = lrelu(tf.layers.conv2d(image, kernel_size=5, filters=64, strides=2, padding='same'))\n        # Conv2_: 128 filter is 5 ,stride is 2,activation is lkeRelu\n        h1 = tf.layers.conv2d(h0, kernel_size=5, filters=128, strides=2, padding='same')\n        # BN\n        h1 = lrelu(tf.contrib.layers.batch_norm(h1, is_training=is_training, decay=momentum))\n        #\n\n        h2 = tf.layers.conv2d(h1, kernel_size=5, filters=256, strides=2, padding='same')\n        h2 = lrelu(tf.contrib.layers.batch_norm(h2, is_training=is_training, decay=momentum))\n\n        h3 = tf.layers.conv2d(h2, kernel_size=5, filters=512, strides=2, padding='same')\n        h3 = lrelu(tf.contrib.layers.batch_norm(h3, is_training=is_training, decay=momentum))\n       # 展开，但不要连全连接层\n        h4 = tf.contrib.layers.flatten(h3)\n        # 直接交sigmoid\n        h4 = tf.layers.dense(h4, units=1)\n        return tf.nn.sigmoid(h4), h4\n\n\ndef generator(z, is_training=is_training):\n    momentum = 0.9\n    with tf.variable_scope('generator', reuse=None):\n# d is the deep of the image\n        d = 4\n        h0 = tf.layers.dense(z, units=d * d * 512)\n# 增加一个维度\n        h0 = tf.reshape(h0, shape=[-1, d, d, 512])\n# 前面的卷积转置都不加激活函数\n        h0 = tf.nn.relu(tf.contrib.layers.batch_norm(h0, is_training=is_training, decay=momentum))\n\n        h1 = tf.layers.conv2d_transpose(h0, kernel_size=5, filters=256, strides=2, padding='same')\n        h1 = tf.nn.relu(tf.contrib.layers.batch_norm(h1, is_training=is_training, decay=momentum))\n\n        h2 = tf.layers.conv2d_transpose(h1, kernel_size=5, filters=128, strides=2, padding='same')\n        h2 = tf.nn.relu(tf.contrib.layers.batch_norm(h2, is_training=is_training, decay=momentum))\n\n        h3 = tf.layers.conv2d_transpose(h2, kernel_size=5, filters=64, strides=2, padding='same')\n        h3 = tf.nn.relu(tf.contrib.layers.batch_norm(h3, is_training=is_training, decay=momentum))\n\n# 最后一个卷积装置的输出要经过tanh激活函数\n        h4 = tf.layers.conv2d_transpose(h3, kernel_size=5, filters=3, strides=2, padding='same', activation=tf.nn.tanh,\n                                        name='g')\n        return h4\n\n# 定义损失函数\n# 产生噪声\ng = generator(noise)\nd_real, d_real_logits = discriminator(X)\nd_fake, d_fake_logits = discriminator(g, reuse=True)\n# generator的可训练参数以及discriminator的可训练参数\nvars_g = [var for var in tf.trainable_variables() if var.name.startswith('generator')]\nvars_d = [var for var in tf.trainable_variables() if var.name.startswith('discriminator')]\n# generator 的loss以及 discriminator 的loss\nloss_d_real = tf.reduce_mean(sigmoid_cross_entropy_with_logits(d_real_logits, tf.ones_like(d_real)))\nloss_d_fake = tf.reduce_mean(sigmoid_cross_entropy_with_logits(d_fake_logits, tf.zeros_like(d_fake)))\nloss_g = tf.reduce_mean(sigmoid_cross_entropy_with_logits(d_fake_logits, tf.ones_like(d_fake)))\nloss_d = loss_d_real + loss_d_fake\n\n# 优化参数\n# 关于在batch_norm中，即为更新mean和variance的操作，因此需要update_ops\nupdate_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\nwith tf.control_dependencies(update_ops):\n# 首先优化dis\n    optimizer_d = tf.train.AdamOptimizer(learning_rate=0.0002, beta1=0.5).minimize(loss_d, var_list=vars_d)\n# 然后优化gen\n    optimizer_g = tf.train.AdamOptimizer(learning_rate=0.0002, beta1=0.5).minimize(loss_g, var_list=vars_g)\n\n\ndef read_image(path, height, width):\n    image = imread(path)\n    h = image.shape[0]\n    w = image.shape[1]\n\n    if h > w:\n        image = image[h // 2 - w // 2: h // 2 + w // 2, :, :]\n    else:\n        image = image[:, w // 2 - h // 2: w // 2 + h // 2, :]\n\n    image = imresize(image, (height, width))\n    return image / 255.\n# 合成多张图片\ndef montage(images):\n    if isinstance(images, list):\n        images = np.array(images)\n    img_h = images.shape[1]\n    img_w = images.shape[2]\n    n_plots = int(np.ceil(np.sqrt(images.shape[0])))\n    if len(images.shape) == 4 and images.shape[3] == 3:\n        m = np.ones(\n            (images.shape[1] * n_plots + n_plots + 1,\n             images.shape[2] * n_plots + n_plots + 1, 3)) * 0.5\n    elif len(images.shape) == 4 and images.shape[3] == 1:\n        m = np.ones(\n            (images.shape[1] * n_plots + n_plots + 1,\n             images.shape[2] * n_plots + n_plots + 1, 1)) * 0.5\n    elif len(images.shape) == 3:\n        m = np.ones(\n            (images.shape[1] * n_plots + n_plots + 1,\n             images.shape[2] * n_plots + n_plots + 1)) * 0.5\n    else:\n        raise ValueError('Could not parse image shape of {}'.format(images.shape))\n    for i in range(n_plots):\n        for j in range(n_plots):\n            this_filter = i * n_plots + j\n            if this_filter < images.shape[0]:\n                this_img = images[this_filter]\n                m[1 + i + i * img_h:1 + i + (i + 1) * img_h,\n                  1 + j + j * img_w:1 + j + (j + 1) * img_w] = this_img\n    return m\n\n# 进行训练\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\nz_samples = np.random.uniform(-1.0, 1.0, [batch_size, z_dim]).astype(np.float32)\nsamples = []\nloss = {'d': [], 'g': []}\n\nsaver = tf.train.Saver()\noffset = 0\nfor i in range(60000):\n    n = np.random.uniform(-1.0, 1.0, [batch_size, z_dim]).astype(np.float32)\n    offset = (offset + batch_size) % len(images)\n    batch = np.array([read_image(img, HEIGHT, WIDTH) for img in images[offset: offset + batch_size]])\n    batch = (batch - 0.5) * 2\n    d_ls, g_ls = sess.run([loss_d, loss_g], feed_dict={X: batch, noise: n, is_training: True})\n    loss['d'].append(d_ls)\n    loss['g'].append(g_ls)\n     #每优化一次discrimintor,优化两次generator\n    sess.run(optimizer_d, feed_dict={X: batch, noise: n, is_training: True})\n    sess.run(optimizer_g, feed_dict={X: batch, noise: n, is_training: True})\n    sess.run(optimizer_g, feed_dict={X: batch, noise: n, is_training: True})\n    print(\"now is iteratio {}\".format(i))\n\n    if i % 50 == 0:\n        print(\"iteration {}, the d_ls is {}, and the g_ls is {}\".format(i,d_ls,g_ls))\n        #生成图片\n        gen_imgs = sess.run(g, feed_dict={noise: z_samples, is_training: False})\n        gen_imgs = (gen_imgs + 1) / 2\n        imgs = [img[:, :, :] for img in gen_imgs]\n        gen_imgs = montage(imgs)\n        imsave(os.path.join(OUTPUT_DIR, 'sample_%d.jpg' % i), gen_imgs)\n        samples.append(gen_imgs)\n\nplt.plot(loss['d'], label='Discriminator')\nplt.plot(loss['g'], label='Generator')\nplt.legend(loc='upper right')\nplt.savefig(os.path.join(OUTPUT_DIR, 'Loss.png'))\nplt.show()\nmimsave(os.path.join(OUTPUT_DIR, 'samples.gif'), samples, fps=10)\n# save the data checkpoint\nsaver.save(sess, os.path.join(OUTPUT_DIR, 'dcgan_' + dataset), global_step=60000)\n", "meta": {"hexsha": "281e34c1073465ca98492e0e0154f337cff9f4ab", "size": 8314, "ext": "py", "lang": "Python", "max_stars_repo_path": "Day08_20190909/data_preprocess/gg_faces.py", "max_stars_repo_name": "Magicboomliu/liuzihua_PKU_intern", "max_stars_repo_head_hexsha": "6d7c8cee49ad0c9471b184432a64f2cebea0d6c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-16T11:11:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-20T04:53:12.000Z", "max_issues_repo_path": "Day08_20190909/data_preprocess/gg_faces.py", "max_issues_repo_name": "Magicboomliu/liuzihua_PKU_intern", "max_issues_repo_head_hexsha": "6d7c8cee49ad0c9471b184432a64f2cebea0d6c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day08_20190909/data_preprocess/gg_faces.py", "max_forks_repo_name": "Magicboomliu/liuzihua_PKU_intern", "max_forks_repo_head_hexsha": "6d7c8cee49ad0c9471b184432a64f2cebea0d6c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1160714286, "max_line_length": 119, "alphanum_fraction": 0.6593697378, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.34864512856608554, "lm_q1q2_score": 0.17976837180848498}}
{"text": "#!/usr/bin/env python3\nimport numpy as np\n\n#we can define these centrality bins for all STAR observables\nSTAR_cent_bins = np.array( [ [0,5],[5,10],[10,20],[20,30],[30,40],[40,50],[50,60],[60,70], [70,80] ] ) # 9 bins\n#more central bins to use for parameter estimation to avoid including empty events\ncentral_STAR_cent_bins = np.array( [ [0,5],[5,10],[10,20],[20,30],[30,40],[40,50] ] ) # 6 bins\n#more central bins for some PHENIX measurements\ncentral_PHENIX_cent_bins = np.array( [ [0,5],[5,10],[10,15],[15,20],[20,30],[30,40],[40,50] ] ) # 7 bins\n#these bins are common to many ALICE observables\nALICE_cent_bins = np.array( [ [0,5],[5,10],[10,20],[20,30],[30,40],[40,50],[50,60],[60,70] ] ) # 8 bins\n#Tmunu_cents = ALICE_cent_bins\n\n#the observables which will be used for parameter estimation\nobs_cent_list = {\n\n'Pb-Pb-2760': {\n\t'dNch_deta' : ALICE_cent_bins,\n\t'dET_deta' : np.array([[0, 2.5], [2.5, 5], [5, 7.5], [7.5, 10],\n\t\t                   [10, 12.5], [12.5, 15], [15, 17.5], [17.5, 20],\n\t\t                   [20, 22.5], [22.5, 25], [25, 27.5], [27.5, 30],\n\t\t                   [30, 32.5], [32.5, 35], [35, 37.5], [37.5, 40],\n\t\t                   [40, 45], [45, 50], [50, 55], [55, 60],\n\t\t                   [60, 65], [65, 70]]), # 22 bins\n\t'dN_dy_pion'   : ALICE_cent_bins,\n\t'dN_dy_kaon'   : ALICE_cent_bins,\n\t'dN_dy_proton' : ALICE_cent_bins,\n\t'dN_dy_Lambda' : np.array([[0,5],[5,10],[10,20],[20,40],[40,60]]), # 5 bins\n\t'dN_dy_Omega'  : np.array([[0,10],[10,20],[20,40],[40,60]]), # 4 bins\n\t'dN_dy_Xi'     : np.array([[0,10],[10,20],[20,40],[40,60]]), # 4 bins\n\t#'dN_dy_d'      : np.array([[0,10],[10,20],[20,40],[40,60]]), # 4 bins\n\t'mean_pT_pion'   : ALICE_cent_bins,\n\t'mean_pT_kaon'   : ALICE_cent_bins,\n\t'mean_pT_proton' : ALICE_cent_bins,\n\t#'mean_pT_d'      : np.array([[0,10],[10,20],[20,40],[40,60]]), # 4 bins\n\t'pT_fluct' : np.array([[0,5],[5,10],[10,15],[15,20], [20,25],[25,30],[30,35],[35,40], [40,45],[45,50],[50,55],[55,60]]), #12 bins\n\t'v22' : ALICE_cent_bins,\n\t'v32' : np.array([[0,5],[5,10],[10,20],[20,30], [30,40],[40,50]]), # 6 bins\n\t'v42' : np.array([[0,5],[5,10],[10,20],[20,30], [30,40],[40,50]]), # 6 bins\n\n\t#'Tmunu0' : Tmunu_cents,\n    #'Tmunu1' : Tmunu_cents,\n\t#'Tmunu2' : Tmunu_cents,\n\t#'Tmunu3' : Tmunu_cents,\n\t#'Tmunu4' : Tmunu_cents,\n\t#'Tmunu5' : Tmunu_cents,\n\t#'Tmunu6' : Tmunu_cents,\n\t#'Tmunu7' : Tmunu_cents,\n\t#'Tmunu8' : Tmunu_cents,\n\t#'Tmunu9' : Tmunu_cents\n    },\n\n'Pb-Pb-5020': {\n\t'dNch_deta' : np.array( [ [0,2.5],[2.5,5],[5,7.5],[7.5,10],[10,20],[20,30],[30,40],[40,50],[50,60],[60,70] ] ),\n\t'dN_dy_pion'   : ALICE_cent_bins,\n\t'dN_dy_kaon'   : ALICE_cent_bins,\n\t'dN_dy_proton' : ALICE_cent_bins,\n\t#'dN_dy_d'      : np.array([[0,10],[10,20],[20,40],[40,60]]), # 4 bins\n\t'mean_pT_pion'   : ALICE_cent_bins,\n\t'mean_pT_kaon'   : ALICE_cent_bins,\n\t'mean_pT_proton' : ALICE_cent_bins,\n\t#'mean_pT_d'      : np.array([[0,10],[10,20],[20,40],[40,60]]), # 4 bins\n\t'v22' : ALICE_cent_bins,\n\t'v32' : np.array([[0,5],[5,10],[10,20],[20,30],[30,40],[40,50]]), # 6 bins\n\t'v42' : np.array([[0,5],[5,10],[10,20],[20,30],[30,40],[40,50]]), # 6 bins\n    },\n\n'Xe-Xe-5440': {\n\t'dNch_deta' : np.array( [ [0,2.5],[2.5,5],[5,7.5],[7.5,10],[10,20],[20,30],[30,40],[40,50],[50,60],[60,70] ] ),\n\t'v22' : ALICE_cent_bins,\n\t'v32' : ALICE_cent_bins,\n    },\n\n'Au-Au-200': {\n\t'dN_dy_pion'   : central_STAR_cent_bins,\n\t'dN_dy_kaon'   : central_STAR_cent_bins,\n\t#current calculations use STAR centrality bins\n\t#NOTE that the model calculations need to be re-averaged using the PHENIX cent bins if we want to include proton\n\t'dN_dy_proton' : central_STAR_cent_bins,\n\t'mean_pT_pion'   : central_STAR_cent_bins,\n\t'mean_pT_kaon'   : central_STAR_cent_bins,\n\t'mean_pT_proton' : central_STAR_cent_bins,\n\t'v22' : central_STAR_cent_bins,\n\t'v32' : central_STAR_cent_bins,\n    },\n\n\n}\n\n#these just define some 'reasonable' ranges for plotting purposes\nobs_range_list = {\n    'Pb-Pb-2760': {\n\t\t'dNch_deta': [0,2000],\n\t\t'dET_deta': [0,2200],\n\t\t'dN_dy_pion': [0,1700],\n\t\t'dN_dy_kaon': [0,400],\n\t\t'dN_dy_proton': [0,120],\n\t\t'dN_dy_Lambda': [0,40],\n\t\t'dN_dy_Omega': [0,2],\n\t\t'dN_dy_Xi': [0,10],\n\t\t'mean_pT_pion': [0,1],\n\t\t'mean_pT_kaon': [0,1.5],\n\t\t'mean_pT_proton': [0,2],\n\t\t'pT_fluct': [0,0.05],\n\t\t'v22': [0,0.16],\n\t\t'v32': [0,0.1],\n\t\t'v42': [0,0.1]\n    },\n\t'Au-Au-200': {\n\t\t'dNch_deta': [0,1000],\n\t\t'dET_deta': [0,1200],\n\t\t'dN_dy_pion': [0,800],\n\t\t'dN_dy_kaon': [0,120],\n\t\t'dN_dy_proton': [0,40],\n\t\t'dN_dy_Lambda': [0,40],\n\t\t'dN_dy_Omega': [0,2],\n\t\t'dN_dy_Xi': [0,10],\n\t\t'mean_pT_pion': [0,1],\n\t\t'mean_pT_kaon': [0,1.5],\n\t\t'mean_pT_proton': [0,2],\n\t\t'pT_fluct': [0,0.05],\n\t\t'v22': [0,0.16],\n\t\t'v32': [0,0.1],\n\t\t'v42': [0,0.1]\n    },\n}\n", "meta": {"hexsha": "98973fdfb9b1ccb6c5da489d879621ed98daac1a", "size": 4636, "ext": "py", "lang": "Python", "max_stars_repo_path": "NN_regression_w_uncert/bins_and_cuts.py", "max_stars_repo_name": "derekeverett/stat_model_surrogates", "max_stars_repo_head_hexsha": "48b140fe89ac1ffa5a7d5733337a5fa519f95d6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NN_regression_w_uncert/bins_and_cuts.py", "max_issues_repo_name": "derekeverett/stat_model_surrogates", "max_issues_repo_head_hexsha": "48b140fe89ac1ffa5a7d5733337a5fa519f95d6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NN_regression_w_uncert/bins_and_cuts.py", "max_forks_repo_name": "derekeverett/stat_model_surrogates", "max_forks_repo_head_hexsha": "48b140fe89ac1ffa5a7d5733337a5fa519f95d6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-06T22:35:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-06T22:35:03.000Z", "avg_line_length": 36.5039370079, "max_line_length": 130, "alphanum_fraction": 0.5813201035, "include": true, "reason": "import numpy", "num_tokens": 2082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3486451285660856, "lm_q1q2_score": 0.17976837180848498}}
{"text": "\"\"\"\nMIT License\n\nCopyright (c) 2019 Simon Olofsson\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nimport numpy as np\nimport math\nfrom scipy import special as sp\n\nclass StateConstraint:\n    def __init__ (self, bounds, **kwargs):\n        self.bounds = np.asarray( bounds )\n\n        if self.bounds.ndim == 2:\n            # Constant bounds\n            assert self.bounds.shape[1] == 2\n            self.num_states = self.bounds.shape[0]\n        elif self.bounds.ndim == 3:\n            # Time-dependent bounds\n            assert self.bounds.shape[2] == 2\n            self.num_steps  = self.bounds.shape[0]\n            self.num_states = self.bounds.shape[1]\n        \n        if 'conf' in kwargs:\n            # Constant bounds\n            self.conf = kwargs['conf']\n            \n            \n            \n        \n    @property\n    def has_added_variables (self):\n        return False\n\n    def num_constraints (self):\n        # Number of individual constraints constructed by class\n        raise NotImplementedError \n        \n    def __call__ (self, M, S, step=None, grad=False):\n        \"\"\"\n        Input:\n        M   [ num_meas ]              Matrix of predictive means\n        S   [ num_meas x num_meas ]   Matrix of predictive covariances\n        grad                          Return gradients wrt M and S\n\n        Output:\n        c      Constraint score for M, S\n        dcdM   Gradient d c / d M\n        dcdS   Gradient d c / d S\n        \"\"\"\n        raise NotImplementedError\n        \n\nclass ConstantMeanStateConstraint (StateConstraint):\n    r\"\"\"\n    Mean constraint:\n        bounds[i,0] <= \\mu_i(t) <= bounds[i,1]\n    \"\"\"\n    def __init__ (self, bounds):\n        super().__init__ (bounds)\n        assert self.bounds.ndim == 2\n\n    def num_constraints (self):\n        return 2 * self.num_states\n        \n    def __call__ (self, M, S, step=None, grad=False):\n        C = np.zeros( 2 * self.num_states )\n        #print( 'mean' )\n        if grad:\n            dCdM = np.zeros( C.shape + M.shape )\n            dCdS = np.zeros( C.shape + S.shape )\n        \n        for i in range(self.num_states):\n            C[2*i]   = M[i] - self.bounds[i,0]\n            #print('lower: %d'%i)\n            #print(self.bounds[i,0])\n            C[2*i+1] = self.bounds[i,1] - M[i]\n            #print('upper: %d'%i)\n            #print(self.bounds[i,1])\n            if grad:\n                dCdM[2*i,  i] = 1.\n                dCdM[2*i+1,i] = -1.\n        return C if not grad else (C, dCdM, dCdS)\n        \n\nclass MovingMeanStateConstraint (StateConstraint):\n    r\"\"\"\n    Mean constraint:\n        bounds[t,i,0] <= \\mu_i(t) <= bounds[t,i,1]\n    \"\"\"\n    def __init__ (self, bounds):\n        super().__init__ (bounds)\n        assert self.bounds.ndim == 3\n\n    def num_constraints (self):\n        return 2 * self.num_states\n        \n    def __call__ (self, M, S, step, grad=False):\n        step = np.min(( self.num_steps-1, step ))\n        C    = np.zeros( 2 * self.num_states )\n        if grad:\n            dCdM = np.zeros( C.shape + M.shape )\n            dCdS = np.zeros( C.shape + S.shape )\n        \n        for i in range(self.num_states):\n            C[2*i]   = M[i] - self.bounds[step,i,0]\n            C[2*i+1] = self.bounds[step,i,1] - M[i]\n            if grad:\n                dCdM[2*i,  i] = 1.\n                dCdM[2*i+1,i] = -1.\n        return C if not grad else (C, dCdM, dCdS)\n    \n\nclass SingleChanceStateConstraint (StateConstraint):\n    r\"\"\"    \n    Chance constraint:\n        conf = probability\n        r = distance from the mean value for a defined tolerance\n        P(\\mu_i(t)+r*S <= bounds[i,1]) > 1-conf\n        P(\\mu_i(t)-r*S >= bounds[i,1]) > 1-conf\n    \"\"\"   \n    \n    def __init__ (self, bounds, **kwargs):\n        super().__init__ (bounds,**kwargs)\n        assert self.bounds.ndim == 2\n        \n\n    def num_constraints (self):\n        return 2 * self.num_states\n    \n    def __call__ (self, M, S, step=None, grad=False):\n        C = np.zeros( 2 * self.num_states )\n        r = math.pow(2,0.5)*sp.erfinv(self.conf)\n        if grad:\n            dCdM = np.zeros( C.shape + M.shape )\n            dCdS = np.zeros( C.shape + S.shape )\n        \n        for i in range(self.num_states):\n            C[2*i]   = M[i] - r*np.sqrt(S[i,i]) - self.bounds[i,0];\n            C[2*i+1] = self.bounds[i,1]- r*np.sqrt(S[i,i]) - M[i];\n            \n            if grad:\n                dCdM[2*i,  i] = 1.\n                dCdM[2*i+1,i] = -1.\n                dCdS[2*i,  i] = -r/(2*np.sqrt(S[i,i]))\n                dCdS[2*i+1,i] = -r/(2*np.sqrt(S[i,i]))\n        return C if not grad else (C, dCdM, dCdS)\n    \nclass JointTimeChanceStateConstraint (StateConstraint):\n    r\"\"\"    \n    Chance constraint:\n        P1(\\mu_i(t)+r*S <= bounds[i,1]) > 1-eps\n        P2(\\mu_i(t)-r*S >= bounds[i,1]) > 1-eps\n    \"\"\"   \n    \n    def __init__ (self, bounds,**kwargs):\n        super().__init__ (bounds,**kwargs)\n        assert self.bounds.ndim == 2\n        \n\n    def num_constraints (self):\n        return 2 * self.num_states\n    \n    def __call__ (self, M, S, step=None, grad=False):\n        C = np.zeros( 2 * self.num_states )\n        \n        if grad:\n            dCdM = np.zeros( C.shape + M.shape )\n            dCdS = np.zeros( C.shape + S.shape )\n        \n        for i in range(self.num_states):\n            r1 = (M[i] - self.bounds[i,0])/np.sqrt(S[i,i])\n            r2 = (self.bounds[i,1] - M[i])/np.sqrt(S[i,i])\n            P1 = 1-(0.5+0.5*sp.erf(r1/(math.pow(2,0.5))))\n            P2 = 1-(0.5+0.5*sp.erf(r2/(math.pow(2,0.5))))\n            \n            C[2*i]   = P1\n            C[2*i+1] = P2\n            \n            if grad:\n                dCdM[2*i,  i] = -math.exp(-math.pow(M[i]- self.bounds[i,0],2)/(2*S[i,i]))/(np.sqrt(2*math.pi*S[i,i]))\n                dCdM[2*i+1,i] = -math.exp(-math.pow(self.bounds[i,1] - M[i],2)/(2*S[i,i]))/(np.sqrt(2*math.pi*S[i,i]))\n                dCdS[2*i,  i] = (M[i]-self.bounds[i,0])*math.exp(-math.pow(M[i]- self.bounds[i,0],2)/(2*S[i,i]))/(np.sqrt(2*math.pi)*S[i,i])\n                dCdS[2*i+1,i] = (self.bounds[i,1] - M[i])*math.exp(-math.pow(self.bounds[i,1] - M[i],2)/(2*S[i,i]))/(np.sqrt(2*math.pi)*S[i,i])\n        return C if not grad else (C, dCdM, dCdS)\n\n", "meta": {"hexsha": "726ad138b28d25625a49af447a5bb1e602f28acd", "size": 7146, "ext": "py", "lang": "Python", "max_stars_repo_path": "doepy/constraints/state_constraints.py", "max_stars_repo_name": "scwolof/doepy", "max_stars_repo_head_hexsha": "acb2cad95428de2c14b28563cff1aa30679e1f39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-23T13:43:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-23T13:43:35.000Z", "max_issues_repo_path": "doepy/constraints/state_constraints.py", "max_issues_repo_name": "scwolof/doepy", "max_issues_repo_head_hexsha": "acb2cad95428de2c14b28563cff1aa30679e1f39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doepy/constraints/state_constraints.py", "max_forks_repo_name": "scwolof/doepy", "max_forks_repo_head_hexsha": "acb2cad95428de2c14b28563cff1aa30679e1f39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-13T14:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T14:38:32.000Z", "avg_line_length": 34.6893203883, "max_line_length": 143, "alphanum_fraction": 0.5401623286, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.17976836831884152}}
{"text": "from __future__ import division\nimport sys\nimport json\nimport numpy as np\nfrom functools import partial\nimport matplotlib as mpl\nimport os\nmpl.use('TkAgg')\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport matplotlib.animation as animation\n\n\n#--------------------------------------------------------------------------------------\n# This plotter assumes the presence of the following data file structure:\n#\n# - All output files are located inside a subdir of the working dir named <name>\n#\n# - The subdir <name> contains a preamble file named \"name.pre\"\n#\n# - Each run is recorded in a data file named \"name_i.dat\", where $i$ is the run index\n#\n# - The preamble format is a Python DICT with the following standard keys:\n#   'Nruns'             -   the number of runs recorded in this directory\n#   'name'              -   the string identifier <name>\n#   'ex_dataQ'          -   Boolean indicating whether or not experiment update cycle\n#                           data was recorded in addition to the experiment state\n#   'agent_dataQ'       -   Boolean indicating whether or not per-agent update cycle\n#                           data was recorded in addition to the experiment state\n#   'mids_to_record'    -   List of mids (belonging to the experiment) whose values\n#                           were recorded (for each cycle of each run)\n#\n# - Additional preamble values are experiment-dependent.\n#   For SNIFFY, we have:\n#   'env_length'        -   The size of SNIFFY's environment\n#   'total_cycles'      -   Length (in cycles) of the whole run   \n#--------------------------------------------------------------------------------------\n\ndef get_pickles(infile):\n    for item in infile:\n        yield json.loads(item)\n\ndef compi(x):\n    if type(x)==type(0):\n        return x+1 if x%2==0 else x-1\n    else:\n        raise Exception('Input to \\\"compi\\\" must be an integer! \\n')\n\ndef fcomp(x):\n    #assuming x is a footprint and an np.array:\n    return 1-x\n\n# inequality check for qualitative weights: \"IS x strictly less than y?\"\ndef qless(x,y):\n    if x<0: #infinity is never less than anything\n        return False\n    elif y<0: #anything finite is less than infinity\n        return True\n    else: #finite things compared as usual\n        return x<y\n\n# max function for qualitative weights\ndef qmax(*args):\n    if min(args)<0:\n        return -1\n    else:\n        return max(args)\n\ndef qmin(*args):\n    if max(args)<0:\n        return -1\n    else:\n        return min(filter(lambda x: x>=0, args))\n\n# convert npdirs data into a matrix\ndef convert_full_implications(matr):\n    L=len(matr)\n    for i in range(L):\n        for j in range(L):\n            if j >= len(matr[i]):\n                matr[i].append(matr[compi(j)][compi(i)])\n    return np.matrix(matr,dtype=int)\n\n# convert dirs data into a matrix\ndef convert_raw_implications(matr):\n    L=len(matr)\n    for i in range(L):\n        for j in range(L):\n            if j >= len(matr[i]):\n                try:\n                    matr[i].append(matr[compi(j)][compi(i)])\n                except IndexError:\n                    matr[i].append(False)\n    return np.matrix(matr,dtype=int)\n\n# convert weights data into a matrix\ndef convert_weights(matr):\n    L=len(matr)\n    newmatr=[[] for ind in xrange(L)]\n    for i in xrange(L):\n        for j in xrange(L):\n            if j>=len(matr[i]):\n                newmatr[i].append(matr[j][i])\n            else:\n                newmatr[i].append(matr[i][j])\n    return np.matrix(newmatr)\n\ndef ellone(x,y):\n    #assuming x,y are np arrays of the same shape, \n    #return the ell-1 distance between them:\n    return np.sum(np.abs(x-y))\n\n\n#\n# Read the preamble (GENERIC)\n#\n\nNAME=sys.argv[1]\n\npreamble_file_name = os.path.join(NAME, NAME+\".pre\")\npreamblef=open(preamble_file_name,'rb')\npreamble=json.load(preamblef)\npreamblef.close()\n\nRUN_NAME=lambda i: NAME+\"_\"+str(i)\ninput_file_name=lambda i: os.path.join(NAME, RUN_NAME(i) + \".dat\")\nsupp_file_name=lambda i: os.path.join(NAME, RUN_NAME(i) + \".sup\")\nNRUNS=preamble['Nruns']\n\n\n#\n# Open the data files (GENERIC)\n#\n\ninput_file={}\nfor ind in xrange(NRUNS):\n    input_file[ind]=open(input_file_name(ind),'rb')\n\nsupp_file={}\nfor ind in xrange(NRUNS):\n    supp_file[ind]=open(supp_file_name(ind),'rb')\n\n\n#\n# Prepare data entries (GENERIC)\n#\n\nDATA={}\n\n#- prepare entries for experiment measurables\nif preamble['mids_recorded'] is []:\n    pass\nelse:\n    for mid in preamble['mids_recorded']:\n        DATA[mid]=[[] for ind in xrange(NRUNS)]\n\n#- prepare entries for update cycle reports\nif bool(preamble['ex_dataQ']):\n    for mid in preamble['ex_data_recorded']:\n        DATA[mid]=[[] for ind in xrange(NRUNS)]\n\n#- prepare entries for per-agent update cycle reports\nif bool(preamble['agent_dataQ']):\n    for mid in preamble['agent_data_recorded']:\n        for agent_id in preamble['agents']:\n            DATA[(agent_id,mid)]=[[] for ind in xrange(NRUNS)]\n\n\n#\n# Read the data from the .dat files (GENERIC)\n#\nSUPP={}\nfor ind in xrange(NRUNS):\n    #load data from the supplementary files:\n    SUPP[ind]=json.loads(supp_file[ind].readline())  \n\n    #load data from the data files:\n    for record in get_pickles(input_file[ind]):\n        #- read entries for experiment measurables        \n        if preamble['mids_recorded'] is []:\n            pass\n        else:\n            for mid,item in zip(preamble['mids_recorded'],record['mids_recorded']):\n                DATA[mid][ind].append(item)\n        #- read entries for experiment update cycle data\n        if bool(preamble['ex_dataQ']):    \n            for tag,item in zip(preamble['ex_data_recorded'],record['ex_data_recorded']):\n                DATA[tag][ind].append(item)\n        #- read entries for experiment update cycle data        \n        if bool(preamble['agent_dataQ']):\n            for agent_id in preamble['agents']:\n                for tag,item in zip(preamble['agent_data_recorded'],record['agent_data_recorded'][agent_id]):\n                    DATA[(agent_id,tag)][ind].append(item)\n\n# close the data & supplementary files:\nfor ind in xrange(NRUNS):\n    input_file[ind].close()\n    supp_file[ind].close()\n\n\n#------------------------------------------------------------------------------------\n# At this point, each DATA[tag] item is a 2-dim Python list object,\n# with the tags taking the form of:\n# - an experiment measurable id;\n# - a measurement tag from the update cycle (time stamp, decision, etc.);\n# - a double tag of the form (agent_id,tag) indicating an agent-specific measurement\n#   from that agent's update cycle.\n#\n# From this point on, all instructions are specific to the experiment at hand\n#------------------------------------------------------------------------------------\n\n#\n# Prepare the plots (EXPERIMENT-SPECIFIC)\n#\n\nAGENT_TYPES={\n    '_Q':['qualitative','xkcd:red'],\n    '_Eu':['empirical uniform','xkcd:sky blue'],\n    '_Ev':['empirical value-based','xkcd:blue'],\n    '_Du':['discounted uniform','xkcd:forest green'],\n    '_Dv':['discounted value-based','xkcd:green'],\n    }\n#ORDERED_TYPES=['_Q','_Eu','_Ev','_Du','_Dv']\nORDERED_TYPES=['_Eu','_Du']\n#ORDERED_TYPES=['_Q','_Ev','_Dv']\nNTYPES=len(ORDERED_TYPES)\n\n# length of the environment (due to differences between circle and interval)\nenv_length=lambda ind,typ: len(SUPP[ind]['values'][typ])\n# duration of the experiment for each run\nduration=lambda ind: len(DATA['counter'][ind])\ndef duration_gen():\n    for ind in xrange(NRUNS):\n        yield duration(ind)\nDURATION=max(duration_gen())\n\n# value of each position in the environment, needed as np.array, for each run and type\nvm=lambda ind,typ: np.array(SUPP[ind]['values'][typ])\n# extreme (=target) value of signal for each run and type\nv_extreme=lambda ind,typ: vm(ind,typ).min() if typ=='_Q' else vm(ind,typ).max()\n\n# sensor footprints for each run\nfp=lambda ind,sensor_ind: np.array(SUPP[ind]['footprints'][sensor_ind]) #compute a footprint vector\n# number of sensor for each run\nNsensors=lambda ind: len(SUPP[ind]['footprints'])   #the number of footprint vectors\ndef Nsensors_gen():\n    for ind in xrange(NRUNS):\n        yield Nsensors(ind)\nNSENSORS=max(Nsensors_gen())\n\n# [initial] implication threshold for each run\nthreshold=lambda ind: SUPP[ind]['threshold']\n\n#Form the implications matrices\n#\n#- check for inclusions among footprints:\nstd_imp_check=lambda x,y: all(x<=y)\n#- check for ground truth thresholded inclusions\ndef lookup_val(x,y,ind,typ):\n    if typ=='_Q':\n        return -1 if not sum(x*y) else np.extract(x*y,vm(ind,typ)).min()\n    else:\n        return (0.+sum(x*y*vm(ind,typ)))/env_length(ind,typ)\n\ndef imp_check(x,y,ind,typ):\n    XY=lookup_val(x,y,ind,typ)\n    X_Y=lookup_val(fcomp(x),y,ind,typ)\n    X_Y_=lookup_val(fcomp(x),fcomp(y),ind,typ)\n    XY_=lookup_val(x,fcomp(y),ind,typ)\n    total=sum(vm(ind,typ))\n    if typ=='_Q': #qualitative implication (zero threshold)\n        return qless(qmax(XY,X_Y_),XY_)\n    else: #real-valued (statistical) implication\n        return XY_<min(total*threshold(ind),XY,X_Y_,X_Y) or (XY_==0 and X_Y==0)# and XY>0 and X_Y_>0)\n\n#- construct the ground truth PCR matrices for each run and type\nGROUND_WEIGHTS={typ:[] for typ in ORDERED_TYPES}\nGROUND_RAW_IMPS={typ:[] for typ in ORDERED_TYPES}\nABS_GROUND_RAW_IMPS=[]\nfor typ in ORDERED_TYPES:\n    for ind in xrange(NRUNS):\n        lookup=lambda x,y: lookup_val(x,y,ind,typ)\n        check=lambda x,y: imp_check(x,y,ind,typ)\n        # Weight matrix computed from known values of states\n        GROUND_WEIGHTS[typ].append(np.matrix([[lookup(fp(ind,yind),fp(ind,xind)) for xind in xrange(Nsensors(ind))] for yind in xrange(Nsensors(ind))]))\n        # PCR matrix computed from known values of states; note the transpose!!\n        GROUND_RAW_IMPS[typ].append(np.matrix([[check(fp(ind,yind),fp(ind,xind)) for xind in xrange(Nsensors(ind))] for yind in xrange(Nsensors(ind))],dtype=int))\nfor ind in xrange(NRUNS):\n    ABS_GROUND_RAW_IMPS.append(np.matrix([[std_imp_check(fp(ind,yind),fp(ind,xind)) for xind in xrange(Nsensors(ind))] for yind in xrange(Nsensors(ind))],dtype=int))\n\n\n#- construct matrices from data\nWEIGHTS={typ:[[] for ind in xrange(NRUNS)] for typ in ORDERED_TYPES}\nRAW_IMPS={typ:[[] for ind in xrange(NRUNS)] for typ in ORDERED_TYPES}\nFULL_IMPS={typ:[[] for ind in xrange(NRUNS)] for typ in ORDERED_TYPES}\nWEIGHT_DIFFS={typ:[[] for ind in xrange(NRUNS)] for typ in ORDERED_TYPES}\nRAW_DIFFS={typ:[[] for ind in xrange(NRUNS)] for typ in ORDERED_TYPES}\nFULL_DIFFS={typ:[[] for ind in xrange(NRUNS)] for typ in ORDERED_TYPES}\nSTD_DIFFS={typ:[[] for ind in xrange(NRUNS)] for typ in ORDERED_TYPES}\nfor typ in ORDERED_TYPES:\n    for ind in xrange(NRUNS):\n        for t in xrange(DURATION):\n            #- learned weight matrix at time t:\n            tmp_raw_weights=convert_weights(DATA[('obs'+typ,'weights')][ind][t]['minus'])\n            WEIGHTS[typ][ind].append(tmp_raw_weights)\n\n            #- learned PCR structure (learned raw implications) at time t:\n            tmp_raw_imps=convert_raw_implications(DATA[('obs'+typ,'raw_implications')][ind][t]['minus'])\n            RAW_IMPS[typ][ind].append(tmp_raw_imps)\n\n            #- transitive closure of learned PCR at time t:\n            tmp_full_imps=convert_full_implications(DATA[('obs'+typ,'full_implications')][ind][t]['minus'])\n            FULL_IMPS[typ][ind].append(tmp_full_imps)\n\n            #- ell-1 distance of learned weights to ground truth weights\n            WEIGHT_DIFFS[typ][ind].append((np.abs(tmp_raw_weights-GROUND_WEIGHTS[typ][ind])).max())\n            #- ell-1 distance of learned PCR to ground truth PCR\n            RAW_DIFFS[typ][ind].append(ellone(tmp_raw_imps,GROUND_RAW_IMPS[typ][ind]))\n            #- ell-1 distance of transitive closure to ground truth PCR (could be quite bigger)\n            FULL_DIFFS[typ][ind].append(ellone(tmp_full_imps,GROUND_RAW_IMPS[typ][ind]))\n            STD_DIFFS[typ][ind].append(ellone(tmp_full_imps,ABS_GROUND_RAW_IMPS[ind]))\n\n#\n#Initialize the plots\n#\n\n#- initialize figure\nfig,ax_imps=plt.subplots(nrows=len(ORDERED_TYPES),ncols=1,sharex=True,sharey=True)\nfig.suptitle('# of incorrect implications over time',fontsize=10)\nplt.subplots_adjust(left=0.05,right=0.95,bottom=0.05,top=0.95)\nplt.xlabel('time elapsed (cycles)',fontsize=10)\n\n#- form the implications plots\nAX={}\nt=xrange(DURATION)\nfor typ,ax in zip(ORDERED_TYPES,ax_imps):\n    AX[typ]=ax\n    ax.set_ylabel('% incorrect implications',fontsize=10)\n    \n    SKIP=DURATION/100\n    OFFSET=1\n\n    weight_diffs=np.array(WEIGHT_DIFFS[typ])\n    raw_diffs=np.array(RAW_DIFFS[typ])/pow(NSENSORS,2)\n    full_diffs=np.array(FULL_DIFFS[typ])/pow(NSENSORS,2)\n    std_diffs=np.array(STD_DIFFS[typ])/pow(NSENSORS,2)\n    #YMAX=max(np.max(raw_diffs),np.max(full_diffs),np.max(std_diffs))\n    ax.set_ylim(bottom=0.,top=1.)\n\n    #means over runs\n    diff_weight_mean=np.mean(weight_diffs,axis=0)\n    diff_raw_mean=np.mean(raw_diffs,axis=0)\n    diff_full_mean=np.mean(full_diffs,axis=0)\n    diff_std_mean=np.mean(std_diffs,axis=0)\n    #standard deviations over runs\n    diff_weight_sdv=np.std(weight_diffs,axis=0)\n    diff_raw_sdv=np.std(raw_diffs,axis=0)\n    diff_full_sdv=np.std(full_diffs,axis=0)\n    diff_std_sdv=np.std(std_diffs,axis=0)\n\n    ALPH=0.7 #foreground transparency coefficients\n    BETA=0.2 #background transparency coefficients\n\n    ax.fill_between(t,diff_weight_mean-diff_weight_sdv,diff_weight_mean+diff_weight_sdv,alpha=BETA,color=AGENT_TYPES[typ][1])\n    ax.fill_between(t,diff_raw_mean-diff_raw_sdv,diff_raw_mean+diff_raw_sdv,alpha=BETA,color=AGENT_TYPES[typ][1])\n    #ax.fill_between(t,diff_full_mean-diff_full_sdv,diff_full_mean+diff_full_sdv,alpha=BETA,color=AGENT_TYPES[typ][1])\n    #ax.fill_between(t,diff_std_mean-diff_std_sdv,diff_std_mean+diff_std_sdv,alpha=BETA,color=AGENT_TYPES[typ][1])\n    \n    ax.plot(t,diff_weight_mean,linestyle='--',linewidth=3,color=AGENT_TYPES[typ][1],alpha=ALPH,label='Learned weights vs. Ground weights, '+AGENT_TYPES[typ][0])\n    ax.plot(t,diff_raw_mean,linestyle='solid',linewidth=3,color=AGENT_TYPES[typ][1],alpha=ALPH,label='Learned PCR vs. Ground PCR, '+AGENT_TYPES[typ][0])\n    #ax.plot(t,diff_full_mean,linestyle='dashed',linewidth=3,color=AGENT_TYPES[typ][1],alpha=ALPH,label='Full implications vs. Ground PCR, '+AGENT_TYPES[typ][0])\n    #ax.plot(t,diff_std_mean,linestyle='dotted',linewidth=2,color=AGENT_TYPES[typ][1],alpha=ALPH,label='Full implications vs. Set implications, '+AGENT_TYPES[typ][0])\n\n    ax.legend()\n#ax_imps.legend()\n\n#Show the plots\nplt.show()\n", "meta": {"hexsha": "ef26d4502eeab91fe8a9d90fe2c1b9f6cebb4960", "size": 14419, "ext": "py", "lang": "Python", "max_stars_repo_path": "suites/learning_stats/plot_batch_comp.py", "max_stars_repo_name": "kotmasha/kodlab-uma-client", "max_stars_repo_head_hexsha": "0a8219100f5b6408b1f2df815477d4ba37811fb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "suites/learning_stats/plot_batch_comp.py", "max_issues_repo_name": "kotmasha/kodlab-uma-client", "max_issues_repo_head_hexsha": "0a8219100f5b6408b1f2df815477d4ba37811fb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "suites/learning_stats/plot_batch_comp.py", "max_forks_repo_name": "kotmasha/kodlab-uma-client", "max_forks_repo_head_hexsha": "0a8219100f5b6408b1f2df815477d4ba37811fb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0448548813, "max_line_length": 166, "alphanum_fraction": 0.6638463139, "include": true, "reason": "import numpy", "num_tokens": 3792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.17976836831884152}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*\n\nimport os\nimport os.path\nimport re\nimport scipy.io as sio\nimport numpy as np\nfrom mpi4py import MPI\nfrom pyscf import gto\n\nimport decodense\n\n# decodense variables\nPARAMS = {\n    'prop': 'energy',\n    'basis': 'ccpvdz',\n    'xc': 'pbe0',\n    'loc': 'ibo-2',\n    'pop': 'iao',\n    'part': 'atoms'\n}\nUNIT = 'au'\nN_ATOMS = 3\nRST_FREQ = 50\n\n# input / output\nINPUT = os.getcwd() + '/water_therm_1000.mat'\nOUTPUT = os.getcwd() + '/{:}_{:}_{:}_{:}_{:}_{:}/'.format(PARAMS['prop'], PARAMS['xc'] if PARAMS['xc'] != '' else 'hf', \\\n                                                          PARAMS['basis'], PARAMS['loc'] if PARAMS['loc'] != '' else 'can', \\\n                                                          PARAMS['pop'], PARAMS['part'], PARAMS['prop'])\n\ndef main():\n        \"\"\"\n        main program\n        \"\"\"\n        # mpi attributes\n        comm = MPI.COMM_WORLD\n        stat = MPI.Status()\n        rank = comm.Get_rank()\n        size = comm.Get_size()\n        assert 1 < size, 'script must be run in parallel: `mpiexec -np N ...`'\n\n        # init decomp object\n        decomp = decodense.DecompCls(**PARAMS)\n\n        # master\n        if rank == 0:\n\n            # write MPI parameters\n            print('\\n MPI global size = {:}\\n'.format(size))\n\n            # make output dir\n            if not os.path.isdir(OUTPUT):\n                restart = False\n                os.mkdir(OUTPUT)\n            else:\n                restart = True\n            # load in dataset\n            data = sio.loadmat(INPUT)\n            # number of slaves and tasks\n            n_slaves = size - 1\n            n_tasks = data['R'].shape[0]\n\n            # start_idx\n            if restart:\n                res_el = np.load(OUTPUT + 'elec.npy')\n                res_nuc = np.load(OUTPUT + 'nuc.npy')\n                start_idx = np.argmax(res_el[:, 0] == 0.)\n            else:\n                res_el = np.zeros([n_tasks, N_ATOMS], dtype=np.float64)\n                res_nuc = np.zeros([n_tasks, N_ATOMS], dtype=np.float64)\n                start_idx = 0\n\n            # loop over molecules in data set\n            for mol_idx, mol_geo in enumerate(data['R'][start_idx:], start_idx):\n\n                # probe for available slaves\n                comm.Probe(source=MPI.ANY_SOURCE, tag=1, status=stat)\n                # receive slave results\n                res = comm.recv(source=stat.source, tag=1)\n                # retrieve results\n                if res is not None:\n                    res_el[res['idx']] = res['prop_el']\n                    res_nuc[res['idx']] = res['prop_nuc']\n                    if res['idx'] % RST_FREQ == 0:\n                        # save results\n                        np.save(OUTPUT + 'elec', res_el)\n                        np.save(OUTPUT + 'nuc', res_nuc)\n                        # print status\n                        prog = (res['idx'] + 1) / n_tasks\n                        status = int(round(50 * prog))\n                        remainder = (50 - status)\n                        print(' STATUS:   [{:}]   ---  {:>6.2f} %'.format('#' * status + '-' * remainder, prog * 100.))\n\n\n                # send mol_dict to slave\n                comm.send({'idx': mol_idx, \\\n                           'struct': [[int(z), mol_geo[i]] for i, z in enumerate(data['Z'][mol_idx]) if 0. < z]}, \\\n                          dest=stat.source, tag=2)\n\n            # done with all tasks\n            while n_slaves > 0:\n\n                # probe for available slaves\n                comm.Probe(source=MPI.ANY_SOURCE, tag=1, status=stat)\n                # receive slave results\n                res = comm.recv(source=stat.source, tag=1)\n                # save results\n                if res is not None:\n                    res_el[res['idx']] = res['prop_el']\n                    res_nuc[res['idx']] = res['prop_nuc']\n                    if res['idx'] % RST_FREQ == 0:\n                        np.save(OUTPUT + 'elec', res_el)\n                        np.save(OUTPUT + 'nuc', res_nuc)\n\n                # send exit signal to slave\n                comm.send(None, dest=stat.source, tag=2)\n                # remove slave\n                n_slaves -= 1\n\n            # save final results\n            np.save(OUTPUT + 'elec', res_el)\n            np.save(OUTPUT + 'nuc', res_nuc)\n            # print final status\n            print(' STATUS:   [{:}]   ---  {:>6.2f} %'.format('#' * 50 + '-' * 0, 100.))\n            # write final info\n            with open(OUTPUT + 'info.txt', 'w') as f_info:\n                f_info.write(decodense.info(decomp))\n\n        else: # slaves\n\n            # send availability to master\n            comm.send(None, dest=0, tag=1)\n\n            # receive work from master\n            while True:\n\n                # receive mol_dict\n                mol_dict = comm.recv(source=0, tag=2)\n                # perform task\n                if mol_dict is not None:\n                    # init molecule\n                    mol = gto.M(verbose = 0, output = None, unit = UNIT, \\\n                                basis = PARAMS['basis'], atom = mol_dict['struct'])\n                    # decodense calc\n                    res = decodense.main(mol, decomp)\n                    # send results to master\n                    comm.send({'idx': mol_dict['idx'], 'prop_nuc': res['prop_nuc'], 'prop_el': res['prop_el']}, dest=0, tag=1)\n                else:\n                    # exit\n                    break\n\n        # barrier\n        comm.Barrier()\n\n\nif __name__ == '__main__':\n    main()\n\n\n", "meta": {"hexsha": "81645798e5a448f9654721c812ad02de15cd2ae5", "size": 5513, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/water_therm_1000/water_therm_1000.py", "max_stars_repo_name": "januseriksen/decodense", "max_stars_repo_head_hexsha": "f663ce171cce767568e2c8dd57c3efa92d2c24eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-24T08:11:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T15:00:25.000Z", "max_issues_repo_path": "examples/water_therm_1000/water_therm_1000.py", "max_issues_repo_name": "januseriksen/decodense", "max_issues_repo_head_hexsha": "f663ce171cce767568e2c8dd57c3efa92d2c24eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/water_therm_1000/water_therm_1000.py", "max_forks_repo_name": "januseriksen/decodense", "max_forks_repo_head_hexsha": "f663ce171cce767568e2c8dd57c3efa92d2c24eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-09T08:41:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T08:41:16.000Z", "avg_line_length": 34.0308641975, "max_line_length": 126, "alphanum_fraction": 0.451478324, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.3311197396289915, "lm_q1q2_score": 0.17975274408041148}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"Functions for performing PSF fitting photometry on 2-D arrays.\"\"\"\n\nfrom __future__ import division\nimport warnings\n\nimport numpy as np\nfrom astropy.modeling.parameters import Parameter\nfrom astropy.utils.exceptions import AstropyUserWarning\nfrom astropy.modeling.fitting import LevMarLSQFitter\nfrom astropy.modeling import Fittable2DModel\nfrom imageutils import (extract_array_2d, subpixel_indices, add_array_2d,\n                        mask_to_mirrored_num)\n\n\n__all__ = ['DiscretePRF', 'create_prf', 'psf_photometry',\n           'GaussianPSF', 'subtract_psf']\n\n\nclass DiscretePRF(Fittable2DModel):\n    \"\"\"\n    A discrete PRF model.\n\n    The discrete PRF model stores images of the PRF at different subpixel\n    positions or offsets as a lookup table. The resolution is given by the\n    subsampling parameter, which states in how many subpixels a pixel is\n    divided.\n\n    The discrete PRF model class in initialized with a 4 dimensional\n    array, that contains the PRF images at different subpixel positions.\n    The definition of the axes is as following:\n\n        1. Axis: y subpixel position\n        2. Axis: x subpixel position\n        3. Axis: y direction of the PRF image\n        4. Axis: x direction of the PRF image\n\n    The total array therefore has the following shape\n    (subsampling, subsampling, prf_size, prf_size)\n\n    Parameters\n    ----------\n    prf_array : ndarray\n        Array containing PRF images.\n    normalize : bool\n        Normalize PRF images to unity.\n    subsampling : int, optional\n        Factor of subsampling. Default = 1.\n    \"\"\"\n    amplitude = Parameter('amplitude')\n    x_0 = Parameter('x_0')\n    y_0 = Parameter('y_0')\n    linear = True\n\n    def __init__(self, prf_array, normalize=True, subsampling=1):\n\n        # Array shape and dimension check\n        if subsampling == 1:\n            if prf_array.ndim == 2:\n                prf_array = np.array([[prf_array]])\n        if prf_array.ndim != 4:\n            raise TypeError('Array must have 4 dimensions.')\n        if prf_array.shape[:2] != (subsampling, subsampling):\n            raise TypeError('Incompatible subsampling and array size')\n        if np.isnan(prf_array).any():\n            raise Exception(\"Array contains NaN values. Can't create PRF.\")\n\n        # Normalize if requested\n        if normalize:\n            for i in range(prf_array.shape[0]):\n                for j in range(prf_array.shape[1]):\n                    prf_array[i, j] /= prf_array[i, j].sum()\n\n        # Set PRF asttributes\n        self._prf_array = prf_array\n        self.subsampling = subsampling\n\n        constraints = {'fixed': {'x_0': True, 'y_0': True}}\n        x_0 = 0\n        y_0 = 0\n        amplitude = 1\n        super(DiscretePRF, self).__init__(n_models=1, x_0=x_0, y_0=y_0,\n                                          amplitude=amplitude, **constraints)\n        self.fitter = LevMarLSQFitter()\n\n        # Fix position per default\n        self.x_0.fixed = True\n        self.y_0.fixed = True\n\n    @property\n    def shape(self):\n        \"\"\"\n        Shape of the PRF image.\n        \"\"\"\n        return self._prf_array.shape[-2:]\n\n    def eval(self, x, y, amplitude, x_0, y_0):\n        \"\"\"\n        Discrete PRF model evaluation.\n\n        Given a certain position and amplitude the corresponding image of\n        the PSF is chosen and scaled to the amplitude. If x and y are\n        outside the boundaries of the image, zero will be returned.\n\n        Parameters\n        ----------\n        x : float\n            x coordinate array in pixel coordinates.\n        y : float\n            y coordinate array in pixel coordinates.\n        amplitude : float\n            Model amplitude.\n        x_0 : float\n            x position of the center of the PRF.\n        y_0 : float\n            y position of the center of the PRF.\n        \"\"\"\n        # Convert x and y to index arrays\n        x = (x - int(x_0 + 0.5)).astype('int') + self.shape[1] // 2\n        y = (y - int(y_0 + 0.5)).astype('int') + self.shape[0] // 2\n\n        # Get subpixel indices\n        x_sub, y_sub = subpixel_indices((x_0, y_0), self.subsampling)\n\n        # Out of boundary masks\n        x_bound = np.logical_or(x < 0, x >= self.shape[1])\n        y_bound = np.logical_or(y < 0, y >= self.shape[0])\n        out_of_bounds = np.logical_or(x_bound, y_bound)\n\n        # Set out of boundary indices to zero\n        x[x_bound] = 0\n        y[y_bound] = 0\n        result = amplitude * self._prf_array[y_sub, x_sub][y, x]\n\n        # Set out of boundary values to zero\n        result[out_of_bounds] = 0\n        return result\n\n    def fit(self, data, indices):\n        \"\"\"\n        Fit PSF/PRF to data.\n\n        Fits the PSF/PRF to the data and returns the best fitting flux.\n        If the data contains NaN values or if the source is not completely\n        contained in the image data the fitting is omitted and a flux of 0\n        is returned.\n\n        For reasons of performance, indices for the data have to be created\n        outside and passed to the function.\n\n        The fit is performed on a slice of the data with the same size as\n        the PRF.\n\n        Parameters\n        ----------\n        data : ndarray\n            Array containig image data.\n        indices : ndarray\n            Array with indices of the data. As\n            returned by np.indices(data.shape)\n        \"\"\"\n        # Extract sub array of the data of the size of the PRF grid\n        sub_array_data = extract_array_2d(data, self.shape,\n                                          (self.x_0.value, self.y_0.value))\n\n        # Fit only if PSF is completely contained in the image and no NaN\n        # values are present\n        if sub_array_data.shape == self.shape and not np.isnan(sub_array_data).any():\n            y = extract_array_2d(indices[0], self.shape,\n                                 (self.x_0.value, self.y_0.value))\n            x = extract_array_2d(indices[1], self.shape,\n                                 (self.x_0.value, self.y_0.value))\n            # TODO: It should be discussed whether this is  the right place to fix\n            # the warning. Maybe it should be handled better in astropy.modeling.fitting\n            with warnings.catch_warnings():\n                warnings.simplefilter(\"ignore\", AstropyUserWarning)\n                m = self.fitter(self, x, y, sub_array_data)\n            return m.amplitude.value\n        else:\n            return 0\n\n\nclass GaussianPSF(Fittable2DModel):\n    \"\"\"\n    Symmetrical Gaussian PSF model.\n\n    The PSF is evaluated by using the `scipy.special.erf` function\n    on a fixed grid of the size of 1 pixel to assure flux conservation\n    on subpixel scale.\n\n    Parameters\n    ----------\n    sigma : float\n        Width of the Gaussian PSF.\n    amplitude : float (default 1)\n        Amplitude at the peak value.\n    x_0 : float (default 0)\n        Position of the peak in x direction.\n    y_0 : float (default 0)\n        Position of the peak in y direction.\n\n    Notes\n    -----\n    The PSF model is evaluated according to the following formula:\n\n        .. math::\n\n            f(x, y) =\n                \\\\frac{A}{4}\n                \\\\left[\n                \\\\textnormal{erf} \\\\left(\\\\frac{x - x_0 + 0.5}\n                {\\\\sqrt{2} \\\\sigma} \\\\right) -\n                \\\\textnormal{erf} \\\\left(\\\\frac{x - x_0 - 0.5}\n                {\\\\sqrt{2} \\\\sigma} \\\\right)\n                \\\\right]\n                \\\\left[\n                \\\\textnormal{erf} \\\\left(\\\\frac{y - y_0 + 0.5}\n                {\\\\sqrt{2} \\\\sigma} \\\\right) -\n                \\\\textnormal{erf} \\\\left(\\\\frac{y - y_0 - 0.5}\n                {\\\\sqrt{2} \\\\sigma} \\\\right)\n                \\\\right]\n\n    Where ``erf`` denotes the error function.\n    \"\"\"\n    amplitude = Parameter('amplitude')\n    x_0 = Parameter('x_0')\n    y_0 = Parameter('y_0')\n    sigma = Parameter('sigma')\n\n    _erf = None\n\n    def __init__(self, sigma, amplitude=1, x_0=0, y_0=0):\n        if self._erf is None:\n            from scipy.special import erf\n            self.__class__._erf = erf\n\n        constraints = {'fixed': {'x_0': True, 'y_0': True, 'sigma': True}}\n        super(GaussianPSF, self).__init__(n_models=1, sigma=sigma,\n                                          x_0=x_0, y_0=y_0,\n                                          amplitude=amplitude, **constraints)\n\n        # Default size is 8 * sigma\n        self.shape = (int(8 * sigma) + 1, int(8 * sigma) + 1)\n        self.fitter = LevMarLSQFitter()\n\n        # Fix position per default\n        self.x_0.fixed = True\n        self.y_0.fixed = True\n\n    def eval(self, x, y, amplitude, x_0, y_0, sigma):\n        \"\"\"\n        Model function Gaussian PSF model.\n        \"\"\"\n        return amplitude / 4 * ((self._erf((x - x_0 + 0.5) / (np.sqrt(2) * sigma))\n                            - self._erf((x - x_0 - 0.5) / (np.sqrt(2) * sigma)))\n                            * (self._erf((y - y_0 + 0.5) / (np.sqrt(2) * sigma))\n                            - self._erf((y - y_0 - 0.5) / (np.sqrt(2) * sigma))))\n\n    def fit(self, data, indices):\n        \"\"\"\n        Fit PSF/PRF to data.\n\n        Fits the PSF/PRF to the data and returns the best fitting flux.\n        If the data contains NaN values or if the source is not completely\n        contained in the image data the fitting is omitted and a flux of 0\n        is returned.\n\n        For reasons of performance, indices for the data have to be created\n        outside and passed to the function.\n\n        The fit is performed on a slice of the data with the same size as\n        the PRF.\n\n        Parameters\n        ----------\n        data : ndarray\n            Array containig image data.\n        indices : ndarray\n            Array with indices of the data. As\n            returned by np.indices(data.shape)\n\n        Returns\n        -------\n        flux : float\n            Best fit flux value. Returns flux = 0 if PSF is not completely\n            contained in the image or if NaN values are present.\n        \"\"\"\n        # Set position\n        position = (self.x_0.value, self.y_0.value)\n\n        # Extract sub array with data of interest\n        sub_array_data = extract_array_2d(data, self.shape, position)\n\n        # Fit only if PSF is completely contained in the image and no NaN\n        # values are present\n        if sub_array_data.shape == self.shape and not np.isnan(sub_array_data).any():\n            y = extract_array_2d(indices[0], self.shape, position)\n            x = extract_array_2d(indices[1], self.shape, position)\n            m = self.fitter(self, x, y, sub_array_data)\n            return m.amplitude.value\n        else:\n            return 0\n\n\ndef psf_photometry(data, positions, psf, mask=None, mode='sequential',\n                   tune_coordinates=False):\n    \"\"\"\n    Perform PSF/PRF photometry on the data.\n\n    Given a PSF or PRF model, the model is fitted simultaneously or\n    sequentially to the given positions to obtain an estimate of the\n    flux. If required, coordinates are also tuned to match best the data.\n\n    If the data contains NaN values or the PSF/PRF is not completely\n    contained in the image, a flux of zero is returned.\n\n    Parameters\n    ----------\n    data : ndarray\n        Image data array\n    positions : List or array\n        List of positions in pixel coordinates\n        where to fit the PSF/PRF.\n    psf : `photutils.psf.DiscretePRF` or `photutils.psf.GaussianPSF`\n        PSF/PRF model to fit to the data.\n    mask : ndarray, optional\n        Mask to be applied to the data.\n    mode : {'sequential', 'simultaneous'}\n        One of the following modes to do PSF/PRF photometry:\n            * 'simultaneous'\n                Fit PSF/PRF simultaneous to all given positions.\n            * 'sequential' (default)\n                Fit PSF/PRF one after another to the given positions .\n\n    Examples\n    --------\n    See `Spitzer PSF Photometry <http://nbviewer.ipython.org/gist/adonath/\n    6550989/PSFPhotometrySpitzer.ipynb>`_ for a short tutorial.\n    \"\"\"\n    # Check input array type and dimension.\n    if np.iscomplexobj(data):\n        raise TypeError('Complex type not supported')\n    if data.ndim != 2:\n        raise ValueError('{0}-d array not supported. '\n                         'Only 2-d arrays supported.'.format(data.ndim))\n\n    # Fit coordinates if requested\n    if tune_coordinates:\n        psf.fixed['x_0'] = False\n        psf.fixed['y_0'] = False\n\n    # Actual photometry\n    result = np.array([])\n    indices = np.indices(data.shape)\n\n    if mode == 'simultaneous':\n        raise NotImplementedError('Simultaneous mode not implemented')\n    elif mode == 'sequential':\n        for i, position in enumerate(positions):\n                psf.x_0, psf.y_0 = position\n                flux = psf.fit(data, indices)\n                result = np.append(result, flux)\n    else:\n        raise Exception('Invalid photometry mode.')\n    return result\n\n\ndef create_prf(data, positions, size, fluxes=None, mask=None, mode='mean',\n               subsampling=1, fix_nan=False):\n    \"\"\"\n    Estimate point response function (PRF) from image data.\n\n    Given a list of positions and size this function estimates an image of\n    the PRF by extracting and combining the individual PRFs from the given\n    positions. Different modes of combining are available.\n\n    NaN values are either ignored by passing a mask or can be replaced by\n    the mirrored value with respect to the center of the PRF.\n\n    Furthermore it is possible to specify fluxes to have a correct\n    normalization of the individual PRFs. Otherwise the flux is estimated from\n    a quadratic aperture of the same size as the PRF image.\n\n    Parameters\n    ----------\n    data : array\n        Data array\n    positions : List or array\n        List of pixel coordinate source positions to use in creating the PRF.\n    size : odd int\n        Size of the quadratic PRF image in pixels.\n    mask : bool array, optional\n        Boolean array to mask out bad values.\n    fluxes : array, optional\n        Object fluxes to normalize extracted PRFs.\n    mode : {'mean', 'median'}\n        One of the following modes to combine the extracted PRFs:\n            * 'mean'\n                Take the pixelwise mean of the extracted PRFs.\n            * 'median'\n                Take the pixelwise median of the extracted PRFs.\n    subsampling : int\n        Factor of subsampling of the PRF (default = 1).\n    fix_nan : bool\n        Fix NaN values in the data by replacing it with the\n        mirrored value. Assuming that the PRF is symmetrical.\n\n    Returns\n    -------\n    prf : `photutils.psf.DiscretePRF`\n        Discrete PRF model estimated from data.\n\n    Notes\n    -----\n    In Astronomy different definitions of Point Spread Function (PSF) and\n    Point Response Function (PRF) are used. Here we assume that the PRF is\n    an image of a point source after discretization e.g. with a CCD. This\n    definition is equivalent to the `Spitzer definiton of the PRF\n    <http://irsa.ipac.caltech.edu/data/SPITZER/docs/dataanalysistools/tools/mopex/mopexusersguide/89/>`_.\n\n    References\n    ----------\n    `Spitzer PSF vs. PRF\n    <http://irsa.ipac.caltech.edu/data/SPITZER/docs/files/spitzer/PRF_vs_PSF.pdf>`_\n\n    `Kepler PSF calibration\n    <http://keplerscience.arc.nasa.gov/CalibrationPSF.shtml>`_\n\n    `The Kepler Pixel Response Function\n    <http://adsabs.harvard.edu/abs/2010ApJ...713L..97B>`_\n    \"\"\"\n\n    # Check input array type and dimension.\n    if np.iscomplexobj(data):\n        raise TypeError('Complex type not supported')\n    if data.ndim != 2:\n        raise ValueError('{0}-d array not supported. '\n                         'Only 2-d arrays supported.'.format(data.ndim))\n    if size % 2 == 0:\n        raise TypeError(\"Size must be odd.\")\n\n    if fluxes is not None and len(fluxes) != len(positions):\n        raise TypeError(\"Position and flux arrays must be of equal length.\")\n\n    if mask is None:\n        mask = np.isnan(data)\n\n    if isinstance(positions, (list, tuple)):\n        positions = np.array(positions)\n\n    if isinstance(fluxes, (list, tuple)):\n        fluxes = np.array(fluxes)\n\n    if mode == 'mean':\n        combine = np.ma.mean\n    elif mode == 'median':\n        combine = np.ma.median\n    else:\n        raise Exception('Invalid mode to combine prfs.')\n\n    data_internal = np.ma.array(data=data, mask=mask)\n    prf_model = np.ndarray(shape=(subsampling, subsampling, size, size))\n    positions_subpixel_indices = np.array([subpixel_indices(_, subsampling)\n                                           for _ in positions])\n\n    for i in range(subsampling):\n        for j in range(subsampling):\n            extracted_sub_prfs = []\n            sub_prf_indices = np.all(positions_subpixel_indices == [j, i],\n                                     axis=1)\n            positions_sub_prfs = positions[sub_prf_indices]\n            for k, position in enumerate(positions_sub_prfs):\n                extracted_prf = extract_array_2d(data_internal, (size, size),\n                                                 position)\n                # Check shape to exclude incomplete PRFs at the boundaries\n                # of the image\n                if extracted_prf.shape == (size, size) and np.ma.sum(extracted_prf) != 0:\n                    # Replace NaN values by mirrored value, with respect\n                    # to the prf's center\n                    if fix_nan:\n                        prf_nan = np.isnan(extracted_prf)\n                        if prf_nan.any():\n                            if prf_nan.sum() > 3 or prf_nan[size / 2, size / 2]:\n                                continue\n                            else:\n                                extracted_prf = mask_to_mirrored_num(\n                                    extracted_prf, prf_nan)\n                    # Normalize and add extracted PRF to data cube\n                    if fluxes is None:\n                        extracted_prf_norm = np.ma.copy(extracted_prf) / np.ma.sum(extracted_prf)\n                    else:\n                        fluxes_sub_prfs = fluxes[sub_prf_indices]\n                        extracted_prf_norm = np.ma.copy(extracted_prf) / fluxes_sub_prfs[k]\n                    extracted_sub_prfs.append(extracted_prf_norm)\n                else:\n                    continue\n            prf_model[i, j] = np.ma.getdata(combine(np.ma.dstack(extracted_sub_prfs), axis=2))\n    return DiscretePRF(prf_model, subsampling=subsampling)\n\n\ndef subtract_psf(data, psf, positions, fluxes, mask=None):\n    \"\"\"\n    Removes PSF/PRF at the given positions.\n\n    To calculate residual images the PSF/PRF model is subtracted from the data\n    at the given positions.\n\n    Parameters\n    ----------\n    data : ndarray\n        Image data.\n    psf : `photutils.psf.DiscretePRF` or `photutils.psf.GaussianPSF`\n        PSF/PRF model to be substracted from the data.\n    positions : ndarray\n        List of center positions where PSF/PRF is removed.\n    fluxes : ndarray\n        List of fluxes of the sources, for correct\n        normalization.\n    \"\"\"\n    # Set up indices\n    indices = np.indices(data.shape)\n\n    # Loop over position\n    for i, position in enumerate(positions):\n        y = extract_array_2d(indices[0], psf.shape, position)\n        x = extract_array_2d(indices[1], psf.shape, position)\n        psf_image = psf.eval(x, y, fluxes[i], position[0], position[1])\n        data = add_array_2d(data, -psf_image, position)\n    return data\n", "meta": {"hexsha": "1350e0567e72cc811a72d851ab06dcea38507da7", "size": 19387, "ext": "py", "lang": "Python", "max_stars_repo_path": "photutils/psf.py", "max_stars_repo_name": "hamogu/photutils", "max_stars_repo_head_hexsha": "d032c703260482aa57fc76c1adb7d244b376c39a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "photutils/psf.py", "max_issues_repo_name": "hamogu/photutils", "max_issues_repo_head_hexsha": "d032c703260482aa57fc76c1adb7d244b376c39a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-02-19T14:00:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-19T14:00:04.000Z", "max_forks_repo_path": "photutils/psf.py", "max_forks_repo_name": "hamogu/photutils", "max_forks_repo_head_hexsha": "d032c703260482aa57fc76c1adb7d244b376c39a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.579245283, "max_line_length": 105, "alphanum_fraction": 0.5937483881, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 4717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.17975274181177028}}
{"text": "import numpy\nimport math\nimport sys\nimport conf\n#COMMONINPT\n# NGAS=conf.NGAS\n# NSTEP=conf.NSTEP\n# NANISO=conf.NANISO\n# EFINAL=conf.EFINAL\n# ESTEP=conf.ESTEP\n# AKT=conf.AKT\n# ARY=conf.ARY\n# TEMPC=conf.TEMPC\n# TORR=conf.TORR\n# IPEN=conf.IPEN\n# #COMMONCNSTS\n# ECHARG=conf.ECHARG\n# EMASS=conf.EMASS\n# AMU=conf.AMU\n# PIR2=conf.PIR2\n# #COMMONINPT2\n# KGAS=conf.KGAS\n# LGAS=conf.LGAS\n# DETEFF=conf.DETEFF\n# EXCWGHT=conf.EXCWGHT\n# #COMMONINPT1\n# NDVEC=conf.NDVEC\n# #COMMONCNSTS1\n# CONST1=conf.CONST1\n# CONST2=conf.CONST2\n# CONST3=conf.CONST3\n# CONST4=conf.CONST4\n# CONST5=conf.CONST5\n# #COMMONRATIO\n# AN1=conf.AN1\n# AN2=conf.AN2\n# AN3=conf.AN3\n# AN4=conf.AN4\n# AN5=conf.AN5\n# AN6=conf.AN6\n# AN=conf.AN\n# FRAC=conf.FRAC\n# #COMMONGASN\n# NGASN=conf.NGASN\n# #COMMONSETP\n# TMAX=conf.TMAX\n# SMALL=conf.SMALL\n# API=conf.API\n# ESTART=conf.ESTART\n# THETA=conf.THETA\n# PHI=conf.PHI\n# TCFMAX=conf.TCFMAX\n# TCFMAX1=conf.TCFMAX1\n\n# RSTART=conf.RSTART\n# EFIELD=conf.EFIELD\n# ETHRM=conf.ETHRM\n# ECUT=conf.ECUT\n# NEVENT=conf.NEVENT\n# IMIP=conf.IMIP\n# IWRITE=conf.IWRITE\n# #COMMONSET2\n# DRXINIT=conf.DRXINIT\n# DRYINIT=conf.DRYINIT\n# DRZINIT=conf.DRZINIT\n# #COMMONBFLD\n# EOVB=conf.EOVB\n# WB=conf.WB\n# BTHETA=conf.BTHETA\n# BMAG=conf.BMAG\n# #COMMONIONC\n# DOUBLE=conf.DOUBLE\n# CMINIXSC=conf.CMINIXSC\n# CMINEXSC=conf.CMINEXSC\n# ECLOSS=conf.ECLOSS\n\n# WPLN=conf.WPLN\n# ICOUNT=conf.ICOUNT\n# AVPFRAC=conf.AVPFRAC\n# #COMMONMRATIO\n# VAN1=conf.VAN1\n# VAN2=conf.VAN2\n# VAN3=conf.VAN3\n# VAN4=conf.VAN4\n# VAN5=conf.VAN5\n# VAN6=conf.VAN6\n# VAN=conf.VAN\n# #COMMONOUTPT\n# ICOLL=conf.ICOLL\n# NETOT=conf.NETOT\n# NPRIME=conf.NPRIME\n# TMAX1=conf.TMAX1\n# TIME=conf.TIME\n# NNULL=conf.NNULL\n\n# NITOT=conf.NITOT\n# ICOLN=conf.ICOLN\n# ICOLNN=conf.ICOLNN\n# NREAL=conf.NREAL\n# NEXCTOT=conf.NEXCTOT\n# #COMMONPRIM3\n# MSUM=conf.MSUM\n# MCOMP=conf.MCOMP\n# MRAYL=conf.MRAYL\n# MPAIR=conf.MPAIR\n\n# MPHOT=conf.MPHOT\n# MVAC=conf.MVAC\n# #COMMONRLTVY\n# BET=conf.BET\n# GAM=conf.GAM\n# VC=conf.VC\n# EMS=conf.EMS\n# #COMMONCOMP\n# ICMP=conf.ICMP\n# ICFLG=conf.ICFLG\n# IRAY=conf.IRAY\n# IRFLG=conf.IRFLG\n# IPAP=conf.IPAP\n# IPFLG=conf.IPFLG\n# IBRM=conf.IBRM\n# IBFLG=conf.IBFLG\n# LPEFLG=conf.LPEFLG\n# #COMMONMIX2\n# E=conf.E\n# EROOT=conf.EROOT\n# QTOT=conf.QTOT\n# QREL=conf.QREL\n\n# QINEL=conf.QINEL\n# QEL=conf.QEL\n# #COMMONPLOT\n# NXPL10=conf.NXPL10\n# NYPL10=conf.NYPL10\n# NZPL10=conf.NZPL10\n# NXPL40=conf.NXPL40\n\n# NYPL40=conf.NYPL40\n# NZPL40=conf.NZPL40\n# NXPL100=conf.NXPL100\n# NYPL100=conf.NYPL100\n# NZPL100=conf.NZPL100\n\n# NXPL400=conf.NXPL400\n# NYPL400=conf.NYPL400\n# NZPL400=conf.NZPL400\n# NXPL1000=conf.NXPL1000\n# NYPL1000=conf.NYPL1000\n\n# NZPL1000=conf.NZPL1000\n# NXPL2=conf.NXPL2\n# NYPL2=conf.NYPL2\n# NZPL2=conf.NZPL2\n# NXPL4000=conf.NXPL4000\n\n# NYPL4000=conf.NYPL4000\n# NZPL4000=conf.NZPL4000\n# NXPL10000=conf.NXPL10000\n# NYPL10000=conf.NYPL10000\n\n# NZPL10000=conf.NZPL10000\n# NXPL40000=conf.NXPL40000\n# NYPL40000=conf.NYPL40000\n# NZPL40000=conf.NZPL40000\n\n# NXPL100000=conf.NXPL100000\n# NYPL100000=conf.NYPL100000\n# NZPL100000=conf.NZPL100000\n# NRPL2=conf.NRPL2\n# NRPL10=conf.NRPL10\n\n# NRPL40=conf.NRPL40\n# NRPL100=conf.NRPL100\n# NRPL400=conf.NRPL400\n# NRPL1000=conf.NRPL1000\n# NRPL4000=conf.NRPL4000\n\n# NRPL10000=conf.NRPL10000\n# NRPL40000=conf.NRPL40000\n# NRPL100000=conf.NRPL100000\n# NEPL1=conf.NEPL1\n\n# NEPL10=conf.NEPL10\n# NEPL100=conf.NEPL100\n# MELEC=conf.MELEC\n# MELEC3=conf.MELEC3\n# MELEC10=conf.MELEC10\n\n# MELEC30=conf.MELEC30\n# MELEC100=conf.MELEC100\n# MELEC300=conf.MELEC300\n# #COMMONBREMG\n# EBRGAM=conf.EBRGAM\n# BRDCOSX=conf.BRDCOSX\n# BRDCOSY=conf.BRDCOSY\n# BRDCOSZ=conf.BRDCOSZ\n\n# BRX=conf.BRX\n# BRY=conf.BRY\n# BRZ=conf.BRZ\n# BRT=conf.BRT\n# EBRTOT=conf.EBRTOT\n# NBREM=conf.NBREM\n# #COMMONCLUS\n# XAV=conf.XAV\n# YAV=conf.YAV\n# ZAV=conf.ZAV\n# TAV=conf.TAV\n\n# XYAV=conf.XYAV\n# XYZAV=conf.XYZAV\n# DX=conf.DX\n# DY=conf.DY\n# DZ=conf.DZ\n\n# DT=conf.DT\n# DXY=conf.DXY\n# DXYZ=conf.DXYZ\n# NCL=conf.NCL\n# FARX1=conf.FARX1\n# FARY1=conf.FARY1\n# FARZ1=conf.FARZ1\n# FARXY1=conf.FARXY1\n# RMAX1=conf.RMAX1\n\n# TSUM=conf.TSUM\n# XNEG=conf.XNEG\n \n# YNEG=conf.YNEG\n# ZNEG=conf.ZNEG\n# EDELTA=conf.EDELTA\n# EDELTA2=conf.EDELTA2\n\n# NCLEXC=conf.NCLEXC\n# #COMMONKSEED\n# NSEED=conf.NSEED\n# #COMMONECASC\n# NEGAS=conf.NEGAS\n# LEGAS=conf.LEGAS\n# IESHELL=conf.IESHELL\n# IECASC=conf.IECASC\n\ndef SETUP(LAST):\n\tdef GOTO999():\n\t\t# print(\"in GOTO999\")\n\t\tprint(conf.NGASN,conf.FRAC)\n\t\tprint(' ERROR IN GAS INPUT : NGAS=',conf.NGAS,'\\n')\n\t\tfor J in range(1,6+1):\n\t\t\t# print(J)\n\t\t\tprint(' N=',J,' NGAS=',conf.NGASN[J],' FRAC=',conf.FRAC[J])\n\t\tLAST=1                                                            \n\t\treturn LAST\n\t#IMPLICIT #real*8 (A-H,O-Z) \n\t#IMPLICIT #integer*8 (I-N) \n\t#integer*4 NSEED                                       \n\tglobal NGAS,NSTEP,NANISO,EFINAL,ESTEP,AKT,ARY,TEMPC,TORR,IPEN\n\tglobal ECHARG,EMASS,AMU,PIR2\n\tglobal KGAS,LGAS,DETEFF,EXCWGHT\n\tglobal NDVEC,CONST1,CONST2,CONST3,CONST4,CONST5                  \n\tglobal AN1,AN2,AN3,AN4,AN5,AN6,AN,FRAC #=[0 for x in range[6]]               \n\tglobal NGASN #=[0 for x in range[6]]                                 \n\tglobal TMAX,SMALL,API,ESTART,THETA,PHI,TCFMAX #=[0 for x in range(10)]\n\tglobal TCFMAX1,RSTART,EFIELD,ETHRM,ECUT,NEVENT,IMIP,IWRITE\n\tglobal DRXINIT,DRYINIT,DRZINIT\n\tglobal EOVB,WB,BTHETA,BMAG \n\tglobal DOUBLE #=[[0 for x in range[6]] for y in range(20000)]\n\tglobal AVPFRAC #=[[0 for x in range(3)] for y in range(6)]\n\tglobal CMINIXSC #=[0 for x in range[6]]\n\tglobal CMINEXSC #=[0 for x in range[6]]\n\tglobal ECLOSS #=[0 for x in range[6]]\n\tglobal WPLN #=[0 for x in range[6]]\n\tglobal ICOUNT\n\tglobal OVAN1,VAN2,VAN3,VAN4,VAN5,VAN6,VAN\n\tglobal ICOLL#=[0 for x in range(30)]\n\tglobal NETOT,NPRIME,TMAX1\n\tglobal TIME #=[0 for x in range(300)]\n\tglobal NNULL,NITOT\n\tglobal ICOLN #=[0 for x i range(512)]\n\tglobal ICOLNN#=[0 for x in range(60)]\n\tglobal NREAL,NEXCTOT\n\tglobal MSUM#=[0 for x in range(10000)]\n\tglobal MCOMP#=[0 for x in range(10000)]\n\tglobal MRAYL#=[0 for x in range(10000)]\n\tglobal MPAIR#=[0 for x in range(10000)]\n\tglobal MPHOT#=[0 for x in range(10000)]\n\tglobal MVAC#=[0 for x in range(10000)]\n\tglobal BET#=[0 for x in range(2000)]\n\tglobal GAM#=[0 for x in range(20000)]\n\tglobal VC,EMS \n\tglobal ICMP,ICFLG,IRAY,IRFLG,IPAP,IPFLG,IBRM,IBFLG,LPEFLG \n\tglobal E #=[0 for x in range(20000)]\n\tglobal EROOT #=[0 for x in range(20000)]\n\tglobal QTOT #=[0 for x in range(20000)]\n\tglobal QREL #=[0 for x in range(20000)]\n\tglobal QINEL #=[0 for x in range(20000)]\n\tglobal QEL #=[0 for x in range(20000)]\n\tglobal NXPL10#=[0 for x in range(31)]\n\tglobal NYPL10#=[0 for x in range(31)]\n\tglobal NZPL10#=[0 for x in range(31)]\n\tglobal NXPL40#=[0 for x in range(31)]\n\tglobal NYPL40#=[0 for x in range(31)]\n\tglobal NZPL40#=[0 for x in range(31)]\n\tglobal NXPL100#=[0 for x in range(31)]\n\tglobal NYPL100#=[0 for x in range(31)]\n\tglobal NZPL100#=[0 for x in range(31)]\n\tglobal NXPL400#=[0 for x in range(31)]\n\tglobal NYPL400#=[0 for x in range(31)]\n\tglobal NZPL400#=[0 for x in range(31)]\n\tglobal NXPL1000#=[0 for x in range(31)]\n\tglobal NYPL1000#=[0 for x in range(31)]\n\tglobal NZPL1000#=[0 for x in range(31)]\n\tglobal NXPL2#=[0 for x in range(31)]\n\tglobal NYPL2#=[0 for x in range(31)]\n\tglobal NZPL2#=[0 for x in range(31)]\n\tglobal NXPL4000#=[0 for x in range(31)]\n\tglobal NYPL4000#=[0 for x in range(31)]\n\tglobal NZPL4000#=[0 for x in range(31)]\n\tglobal NXPL10000#=[0 for x in range(31)]\n\tglobal NYPL10000#=[0 for x in range(31)]\n\tglobal NZPL10000#=[0 for x in range(31)]\n\tglobal NXPL40000#=[0 for x in range(31)]\n\tglobal NYPL40000#=[0 for x in range(31)]\n\tglobal NZPL40000#=[0 for x in range(31)]\n\tglobal NXPL100000#=[0 for x in range(31)]\n\tglobal NYPL100000#=[0 for x in range(31)]\n\tglobal NZPL100000#=[0 for x in range(31)]\n\tglobal NRPL2#=[0 for x in range(31)]\n\tglobal NRPL10#=[0 for x in range(31)]\n\tglobal NRPL40#=[0 for x in range(31)]\n\tglobal NRPL100#=[0 for x in range(31)]\n\tglobal NRPL400#=[0 for x in range(31)]\n\tglobal NRPL1000#=[0 for x in range(31)]\n\tglobal NRPL4000#=[0 for x in range(31)]\n\tglobal NRPL10000#=[0 for x in range(31)]\n\tglobal NRPL40000#=[0 for x in range(31)]\n\tglobal NRPL100000#=[0 for x in range(31)]\n\tglobal NEPL1#=[0 for x in range(100)]\n\tglobal NEPL10#=[0 for x in range(100)]\n\tglobal NEPL100#=[0 for x in range(100)]\n\tglobal MELEC#=[0 for x in range(1000)]\n\tglobal MELEC3#=[0 for x in range(1000)]\n\tglobal MELEC10#=[0 for x in range(1000)]\n\tglobal MELEC30#=[0 for x in range(1000)]\n\tglobal MELEC100#=[0 for x in range(1000)]\n\tglobal MELEC300#=[0 for x in range(1000)]\n\tglobal EBRGAM#=[0 for x in range(10)]\n\tglobal BRDCOSX# =[0 for x in range(10)]\n\tglobal BRDCOSY# =[0 for x in range(10)]\n\tglobal BRDCOSZ# =[0 for x in range(10)]\n\tglobal BRX#=[0 for x in range(10)]\n\tglobal BRY#=[0 for x in range(10)]\n\tglobal BRZ#=[0 for x in range(10)]\n\tglobal BRT#=[0 for x in range(10)]\n\tglobal EBRTOT#=[0 for x in range[6]]\n\tglobal NBREM#=[0 for x in range[6]]\n\tglobal XAV#=[0 for x in range(100000)]\n\tglobal YAV#=[0 for x in range(100000)]\n\tglobal ZAV#=[0 for x in range(100000)]\n\tglobal TAV#=[0 for x in range(100000)]\n\tglobal XYAV#=[0 for x in range(100000)]\n\tglobal XYZAV#=[0 for x in range(100000)]\n\tglobal DX#=[0 for x in range(100000)]\n\tglobal DY#=[0 for x in range(100000)] \n\tglobal DZ#=[0 for x in range(100000)]\n\tglobal DT#=[0 for x in range(100000)]\n\tglobal DXY#=[0 for x in range(100000)]\n\tglobal DXYZ#=[0 for x in range(100000)]\n\tglobal NCL#=[0 for x in range(100000)]\n\tglobal FARX1#=[0 for x in range(100000)]\n\tglobal FARY1#=[0 for x in range(100000)]\n\tglobal FARZ1#=[0 for x in range(100000)]\n\tglobal FARXY1#=[0 for x in range(100000)]\n\tglobal RMAX1#=[0 for x in range(100000)]\n\tglobal TSUM#=[0 for x in range(100000)]\n\tglobal XNEG#=[0 for x in range(100000)]\n\tglobal YNEG#=[0 for x in range(100000)]\n\tglobal ZNEG#=[0 for x in range(100000)]\n\tglobal EDELTA#[100000]\n\tglobal EDELTA2#=[0 for x in range(100000)]\n\tglobal NCLEXC#=[0 for x in range(100000)]\n\tglobal NSEED\n\tglobal NEGAS#=[0 for x in range(512)]\n\tglobal LEGAS#=[0 for x in range(512)]\n\tglobal IESHELL#=[0 for x in range(512)]\n\tglobal IECASC\n\t#                                                                       \n\t#   NEW UPDATE OF CONSTANTS 2010\n\t#\n\tconf.API=numpy.arccos(-1.00)                                                 \n\tconf.ARY=13.605692530                                              \n\tconf.PIR2=8.7973554297*(10**-17)\n\tconf.ECHARG=1.602176565*(10**-19)                                         \n\tconf.EMASS=9.10938291*(10**-31)                     \n\tconf.EMS=510998.9280\n\tconf.VC=299792458.00                       \n\tconf.AMU=1.660538921*(10**-27)                                             \n\tBOLTZ=8.6173324*(10**-5)    \n\tBOLTZJ=1.3806488*(10**-23)                                              \n\tAWB=1.758820088*(10**10)                                             \n\tALOSCH=2.6867805*(10**19)     \n\tRE=2.8179403267*(10**-13)    \n\tALPH=137.035999074\n\tHBAR=6.58211928*(10**-16)                                     \n\tEOVM=math.sqrt(2.00*conf.ECHARG/conf.EMASS)*100.00                            \n\tABZERO=273.150                                                   \n\tATMOS=760.00                                                     \n\tconf.CONST1=AWB/2.00*1.0*(10**-19)                                          \n\tconf.CONST2=conf.CONST1*1.0*(10**-2)                                             \n\tconf.CONST3=math.sqrt(0.20*AWB)*1.0*(10**-9)                                   \n\tconf.CONST4=conf.CONST3*ALOSCH*1.0*(10**-15)                                      \n\tconf.CONST5=conf.CONST3/2.00\n\tTWOPI=2.00*conf.API\n\tconf.NANISO=2\n\tconf.NBREM=numpy.zeros(7)  # negotiated for extra element \n\tconf.EBRTOT=numpy.zeros(7)   # negotiated for extra element \n\n\tconf.ICFLG=0\n\tconf.IRFLG=0\n\tconf.IPFLG=0\n\tconf.IBFLG=0\n\tconf.LPEFLG=0\n\t#  --------------------------------------------       \n\t#                                                                       \n\t#      READ IN OUTPUT CONTROL AND INTEGRATION DATA                      \n\t#                \n\tconf.NGAS,conf.NEVENT,conf.IMIP,conf.NDVEC,conf.NSEED,conf.ESTART,conf.ETHRM,conf.ECUT=2,100,5,1,0,1.0,1.5,2.0\n\n\t# NGAS,NEVENT,IMIP,NDVEC,NSEED,ESTART,ETHRM,ECUT=input(\"Input Card 1 \").split()\n\tconf.NGAS=int(conf.NGAS)#input('NGAS'))\n\tconf.NEVENT=int(conf.NEVENT)#input('NEVENT'))\n\tconf.IMIP=int(conf.IMIP)#input('IMIP'))\n\tconf.NDVEC=int(conf.NDVEC)#input('NDVEC'))\n\tconf.NSEED=int(conf.NSEED)#input('NSEED'))\n\tconf.ESTART=float(conf.ESTART)#input('ESTART'))\n\tconf.ETHRM=float(conf.ETHRM)#input('ETHRM'))\n\tconf.ECUT=float(conf.ECUT)#input('ECUT'))\n\tconf.ICOUNT=0\n\n\tif(conf.IMIP == 1):\n\t\tconf.ICOUNT=1 \n\tif(conf.NGAS == 0):\n\t\tLAST=1\n\t\treturn LAST\n\tif(conf.ESTART > 3.0*(10**6) and conf.IMIP == 3):\n\t\tprint(' SUBROUTINE STOPPED: X-RAY ENERGY=','%.3f' % conf.ESTART,'EV. MAXIMUM ENERGY 3.0MEV')\n\t\tsys.exit() \n\t# endif\n\tif(conf.IMIP != 1 and conf.NEVENT > 10000):\n\t\tprint(' SUBROUTINE STOPPED: NUMBER OF EVENTS =',conf.NEVENT,' LARGER THAN ARRAY LIMIT OF 10000')\n\t\tsys.exit()\n\t# endif\n\tif(conf.IMIP == 1 and conf.NEVENT > 100000):\n\t\tprint(' SUBROUTINE STOPPED: NUMBER OF EVENTS =',conf.NEVENT,' LARGER THAN ARRAY LIMIT OF 100000')\n\t\tsys.exit()\n\t# endif\n\t# \n\t#   GAS IDENTIFIERS \n\t#\n\tconf.NGASN=numpy.zeros(7)\n\tcard2=[2 , 12 , 0 , 0 , 0 , 0]\n\t# card2=input(\"Input Card 2 \").split()\n\tfor i in range(6):\n\t\tconf.NGASN[i+1]=card2[i]\n\t#      \n\t#      GAS PARAMETERS\n\t#\n\tconf.FRAC=numpy.zeros(7)\n\tcard3=[80.000,20.000,0.0,0.0,0.0,0.0,20.000,760.000]\n\t# card3=input(\"Input Card 3 \").split()\n\tfor i in range(6):\n\t\tconf.FRAC[i+1]=float(card3[i])\n\tconf.TEMPC=round(float(card3[6]),4)  \t\t\t\t#print(8'%.4f' %)      \n\tconf.TORR=round(float(card3[7]),4)                  \t#print(8'%.4f' %)      \n\n       \n\t#print(8'%.4f' %)      \n\t#                                                  \n\t#      FIELD VALUES                                                    \n\t#   \n\tconf.EFIELD,conf.BMAG,conf.BTHETA,conf.IWRITE,conf.IPEN=2.000,3.000,30.000,0,0\n\t# EFIELD,BMAG,BTHETA,IWRITE,IPEN=input(\"Input Card 4 \").split()                                                                    \n\tconf.EFIELD=round(float(conf.EFIELD),3)  \t\t\t#print(3'%.3f' % ,2I5)\n\tconf.BMAG=round(float(conf.BMAG),3)\t\t\t#print(3'%.3f' % ,2I5)\n\tconf.BTHETA=round(float(conf.BTHETA),3)\t\t\t#print(3'%.3f' % ,2I5)\n\tconf.IWRITE=int(conf.IWRITE)\t\t\t#print(3'%.3f' % ,2I5)\n\tconf.IPEN=int(conf.IPEN)                    \t\t\t#print(3'%.3f' % ,2I5)     \n\t\n\tconf.DETEFF,conf.EXCWGHT,conf.KGAS,conf.LGAS,conf.ICMP,conf.IRAY,conf.IPAP,conf.IBRM,conf.IECASC=50.0,0.55,2,1,1,1,1,1,1\n\t# DETEFF,EXCWGHT,KGAS,LGAS,ICMP,IRAY,IPAP,IBRM,IECASC=input(\"Input Card 5 \").split()\n\tconf.DETEFF=round(float(conf.DETEFF),3)      \t# print(2'%.3f' % ,7I5)\n\tconf.EXCWGHT=round(float(conf.EXCWGHT),3)\t\t# print(2'%.3f' % ,7I5)\t\t\t\n\tconf.KGAS=int(conf.KGAS)\t\t\t\t\t\t# print(2'%.3f' % ,7I5)\n\tconf.LGAS=int(conf.LGAS)\t\t\t\t\t\t# print(2'%.3f' % ,7I5)\n\tconf.ICMP=int(conf.ICMP)\t\t\t\t\t\t# print(2'%.3f' % ,7I5)\n\tconf.IRAY=int(conf.IRAY)\t\t\t\t\t\t# print(2'%.3f' % ,7I5)\n\tconf.IPAP=int(conf.IPAP)\t\t\t\t\t\t# print(2'%.3f' % ,7I5)\n\tconf.IBRM=int(conf.IBRM)\t\t\t\t\t\t# print(2'%.3f' % ,7I5)\n\tconf.IECASC =int(conf.IECASC)\t\t\t\t\t# print(2'%.3f' % ,7I5)\n\t#     WRITE(6,656) IWRITE\n\t# 656 print(' IWRITE=',I3)  \n\tif(conf.IMIP != 0):\n\t\toutputfile=open(\"DEGRAD.OUT\",\"w\")\n\t# CALCULATE EFINAL FOR DELTAS OR XRAYS \n\t# INCREASED EFINAL CAUSED BY ELECTRIC FIELD \n\tEBIG=0.05*conf.ESTART/1000. \n\tconf.EFINAL=conf.ESTART*1.0001+760.0*EBIG/conf.TORR*(conf.TEMPC+ABZERO)/293.15*conf.EFIELD\n\tif(conf.EFINAL < (1.01*conf.ESTART)):\n\t\tconf.EFINAL=1.01*conf.ESTART \n\t#   CHECK INPUT\n\tTOTFRAC=0.00\n\tif(conf.NGAS == 0 or conf.NGAS > 6):\n\t\t\tGOTO999()\n\tfor J in range(1,conf.NGAS+1):\n\t\t# \tprint('J',J)\n\t\tif(conf.NGASN[J]== 0 or conf.FRAC[J] == 0.00):\n\t\t\tGOTO999()\n\t\tTOTFRAC=TOTFRAC+conf.FRAC[J]\n\n\tif(abs(TOTFRAC-100.00)> 1*(10**-6)):\n\t\tprint(TOTFRAC)\n\t\tGOTO999()\n\tLAST=0\n\tconf.TMAX=100.00  \n\tNOUT=10  \n\tconf.NSTEP=20000\n\t# INITIAL ANGLES\n\tif(conf.NDVEC): #22594\n\t\tconf.PHI=0\n\t\tconf.THETA=0\n\telif(conf.NDVEC==-1):\n\t\tconf.PHI=0\n\t\tconf.THETA=numpy.arccos(-1)\n\telif(conf.NDVEC==0):\n\t\tconf.PHI=0.0\n\t\tconf.THETA=conf.API/2.0\n\telif(conf.NDVEC==2):\n\t\tR3=DRAND48(0.0,1.0)\n\t\tconf.PHI=TWOPI*R3\n\t\tR4=DRAND48(1.5, 1.9)\n\t\tconf.THETA=numpy.arccos(1.0-2.0*R4)\n\telse :\n\t\tprint('DIRECTION OF BEAM NOT DEFINED NDVEC =',conf.NDVEC)\n\t\tsys.exit()\n\n\t# INITIAL DIRECTION COSINES FOR CASCADE CALCULATION\n\tconf.DRZINIT= numpy.cos(conf.THETA)\n\tconf.DRXINIT= numpy.sin(conf.THETA)*numpy.cos(conf.PHI)\n\tconf.DRYINIT=numpy.sin(conf.THETA)*numpy.sin(conf.PHI)\n\t# ZERO COMMON BLOCKS OF OUTPUT RESULTS\n\tconf.MSUM=numpy.zeros(10001,dtype=int)\n\tconf.MCOMP=numpy.zeros(10001,dtype=int)\n\tconf.MRAYL=numpy.zeros(10001,dtype=int)\n\tconf.MPAIR=numpy.zeros(10001,dtype=int)\n\tconf.MPHOT=numpy.zeros(10001,dtype=int)\n\tconf.MVAC=numpy.zeros(10001,dtype=int)\n\n\t# for J in range(1,300):\n\tconf.TIME=numpy.zeros(301,dtype=int)\n\t# for K in range(1,30):\n\tconf.ICOLL=numpy.zeros(31,dtype=int)\n\t# for K in range(1,512):\n\tconf.ICOLN=numpy.zeros(513,dtype=int)\n\t# for K in range(1,60):\n\tconf.ICOLNN=numpy.zeros(61,dtype=int)\n\t# for K in range(1,10):\n\tconf.TCFMAX=numpy.zeros(11)\n\t# ZERO PLOT ARRAYS\n\tconf.NXPL2=numpy.zeros(32,dtype=int)\n\tconf.NYPL2=numpy.zeros(32,dtype=int)\n\tconf.NZPL2=numpy.zeros(32,dtype=int)\n\tconf.NXPL10=numpy.zeros(32,dtype=int)\n\tconf.NYPL10=numpy.zeros(32,dtype=int)\n\tconf.NZPL10=numpy.zeros(32,dtype=int)\n\tconf.NXPL40=numpy.zeros(32,dtype=int)\n\tconf.NYPL40=numpy.zeros(32,dtype=int)\n\tconf.NZPL40=numpy.zeros(32,dtype=int)\n\tconf.NXPL100=numpy.zeros(32,dtype=int)\n\tconf.NYPL100=numpy.zeros(32,dtype=int)\n\tconf.NZPL100=numpy.zeros(32,dtype=int)\n\tconf.NXPL400=numpy.zeros(32,dtype=int)\n\tconf.NYPL400=numpy.zeros(32,dtype=int)\n\tconf.NZPL400=numpy.zeros(32,dtype=int)\n\tconf.NXPL1000=numpy.zeros(32,dtype=int)\n\tconf.NYPL1000=numpy.zeros(32,dtype=int)\n\tconf.NZPL1000=numpy.zeros(32,dtype=int)\n\tconf.NXPL4000=numpy.zeros(32,dtype=int)\n\tconf.NYPL4000=numpy.zeros(32,dtype=int)\n\tconf.NZPL4000=numpy.zeros(32,dtype=int)\n\tconf.NXPL10000=numpy.zeros(32,dtype=int)\n\tconf.NYPL10000=numpy.zeros(32,dtype=int)\n\tconf.NZPL10000=numpy.zeros(32,dtype=int)\n\tconf.NXPL40000=numpy.zeros(32,dtype=int)\n\tconf.NYPL40000=numpy.zeros(32,dtype=int)\n\tconf.NZPL40000=numpy.zeros(32,dtype=int)\n\tconf.NXPL100000=numpy.zeros(32,dtype=int)\n\tconf.NYPL100000=numpy.zeros(32,dtype=int)\n\tconf.NZPL100000=numpy.zeros(32,dtype=int)\n\tconf.NRPL2=numpy.zeros(32,dtype=int)\n\tconf.NRPL10=numpy.zeros(32,dtype=int)\n\tconf.NRPL40=numpy.zeros(32,dtype=int)\n\tconf.NRPL100=numpy.zeros(32,dtype=int)\n\tconf.NRPL400=numpy.zeros(32,dtype=int)\n\tconf.NRPL1000=numpy.zeros(32,dtype=int)\n\tconf.NRPL4000=numpy.zeros(32,dtype=int)\n\tconf.NRPL10000=numpy.zeros(32,dtype=int)\n\tconf.NRPL40000=numpy.zeros(32,dtype=int)\n\tconf.NRPL100000=numpy.zeros(32,dtype=int) #22678\n\tconf.NEPL1=numpy.zeros(101,dtype=int)\n\tconf.NEPL10=numpy.zeros(101,dtype=int)\n\tconf.NEPL100=numpy.zeros(101,dtype=int)\n\tconf.MELEC=numpy.zeros(1001,dtype=int)\n\tconf.MELEC3=numpy.zeros(1001,dtype=int)\n\tconf.MELEC10=numpy.zeros(1001,dtype=int)\n\tconf.MELEC30=numpy.zeros(1001,dtype=int)\n\tconf.MELEC100=numpy.zeros(1001,dtype=int)\n\tconf.MELEC300=numpy.zeros(1001,dtype=int) #22689\n\t# C ZERO ARRAYS\n\tconf.XAV=numpy.zeros(100001)\n\tconf.YAV=numpy.zeros(100001)\n\tconf.ZAV=numpy.zeros(100001)\n\tconf.TAV=numpy.zeros(100001)\n\tconf.XYAV=numpy.zeros(100001)\n\tconf.XYZAV=numpy.zeros(100001)\n\tconf.DX=numpy.zeros(100001)\n\tconf.DY=numpy.zeros(100001)\n\tconf.DZ=numpy.zeros(100001)\n\tconf.DT=numpy.zeros(100001)\n\tconf.DXY=numpy.zeros(100001)\n\tconf.DXYZ=numpy.zeros(100001)\n\tconf.FARX1=numpy.zeros(100001)\n\tconf.FARY1=numpy.zeros(100001)\n\tconf.FARZ1=numpy.zeros(100001)\n\tconf.FARXY1=numpy.zeros(100001)\n\tconf.RMAX1=numpy.zeros(100001)\n\tconf.TSUM=numpy.zeros(100001)\n\tconf.XNEG=numpy.zeros(100001)\n\tconf.YNEG=numpy.zeros(100001)\n\tconf.ZNEG=numpy.zeros(100001)\n\tconf.EDELTA=numpy.zeros(100001)\n\tconf.EDELTA2=numpy.zeros(100001)\n\tconf.NCL=numpy.zeros(100001)\n\tconf.NCLEXC=numpy.zeros(100001) ##22716 #22915\n\t# ----------------------------------------------------  \n\t# if NSEED = 0 : USE STANDARD SEED VALUE =54217137\n\tif(conf.NSEED != 0):\n\t\tRM48(conf.NSEED,0,0)                           \n\t#-----------------------------------------------      \n\t#\n\tCORR=ABZERO*conf.TORR/(ATMOS*(ABZERO+conf.TEMPC)*100.00)                    #check precision\n\tconf.AKT=(ABZERO+conf.TEMPC)*BOLTZ\n\tconf.AN1=conf.FRAC[1]*CORR*ALOSCH                                           \n\tconf.AN2=conf.FRAC[2]*CORR*ALOSCH                                           \n\tconf.AN3=conf.FRAC[3]*CORR*ALOSCH                                           \n\tconf.AN4=conf.FRAC[4]*CORR*ALOSCH\n\tconf.AN5=conf.FRAC[5]*CORR*ALOSCH\n\tconf.AN6=conf.FRAC[6]*CORR*ALOSCH                                           \n\tconf.AN=float(100.00*CORR*ALOSCH)\n\tconf.AN=100.00*CORR*ALOSCH                                            \n\t#VAN1=FRAC[1]*CORR*CONST4*1.0D15                                   \n\t#VAN2=FRAC[2]*CORR*CONST4*1.0D15                                   \n\t#VAN3=FRAC(3)*CORR*CONST4*1.0D15                                   \n\t#VAN4=FRAC[4]*CORR*CONST4*1.0D15\n\t#VAN5=FRAC[5]*CORR*CONST4*1.0D15\n\t#VAN6=FRAC[6]*CORR*CONST4*1.0D15                                   \n\t#VAN=100.00*CORR*CONST4*1.0D15\n\tconf.VAN1=conf.FRAC[1]*CORR*ALOSCH*conf.VC                                   \n\tconf.VAN2=conf.FRAC[2]*CORR*ALOSCH*conf.VC                                   \n\tconf.VAN3=conf.FRAC[3]*CORR*ALOSCH*conf.VC                                  \n\tconf.VAN4=conf.FRAC[4]*CORR*ALOSCH*conf.VC\n\tconf.VAN5=conf.FRAC[5]*CORR*ALOSCH*conf.VC\n\tconf.VAN6=conf.FRAC[6]*CORR*ALOSCH*conf.VC                                  \n\tconf.VAN=float(100.00*CORR*ALOSCH*conf.VC)    #22745 #22945\n\t# CALCULATE AND STORE ENERGY GRID FOR XRAYS BETAS OR PARTICLES\n\tE=numpy.zeros(20001)\n\tconf.GAM=numpy.zeros(20001)\n\tconf.BET=numpy.zeros(20001)\n\tif(conf.EFINAL <= 20000.0):\n\t\tconf.ESTEP=float(conf.EFINAL/float(conf.NSTEP))\n\t\tEHALF=float(conf.ESTEP/2.00)\n\t\tconf.E[1]=EHALF\n\t\tconf.GAM[1]=(conf.EMS+conf.E[1])/conf.EMS\n\t\tconf.BET[1]=math.sqrt(1.00-1.00/(conf.GAM[1]*conf.GAM[1]))  #ifcontinues\n\t\tfor I in range(2,20000+1):                      #ifcontinues\n\t\t\tAJ=float(I-1)\n\t\t\tconf.E[I]=EHALF+conf.ESTEP*AJ\n\t\t\tconf.GAM[I]=(conf.EMS+conf.E[I])/conf.EMS\n\t\t\tconf.BET[I]=math.sqrt(1.00-1.00/(conf.GAM[I]*conf.GAM[I]))\n\telif(conf.EFINAL > 20000.0 and conf.EFINAL <= 140000.) :\n\t\tconf.ESTEP=1.0\n\t\tEHALF=0.5\n\t\tconf.E[1]=EHALF\n\t\tconf.GAM[1]=(conf.EMS+conf.E[1])/conf.EMS\n\t\tconf.BET[1]=math.sqrt(1.00-1.00/(conf.GAM[1]*conf.GAM[1]))\n\t\tfor i in range(2,16000+1):\n\t\t\tAJ=float(I-1)\n\t\t\tconf.E[I]=EHALF+conf.ESTEP*AJ\n\t\t\tconf.GAM[I]=(conf.EMS+conf.E[I])/conf.EMS\n\t\t\tconf.BET[I]=math.sqrt(1.00-1.00/(conf.GAM[I]*conf.GAM[I]))   #22768 #22968  \n\t\tESTEP1=(conf.EFINAL-16000.0)/float(4000)\n\t\tfor I in range(16001,2000+1):\n\t\t\tAJ=float(I-16000)\n\t\t\tconf.E[I]=16000.0+AJ*ESTEP1\n\t\t\tconf.GAM[I]=(conf.EMS+conf.E[I])/conf.EMS\n\t\t\tconf.BET[I]=math.sqrt(1.00-1.00/(conf.GAM[I]*conf.GAM[I]))\n\telse:\n\t\tconf.ESTEP=1.0\n\t\tEHALF=0.5\n\t\tconf.E[1]=EHALF\n\t\tconf.GAM[1]=(conf.EMS+conf.E[1])/conf.EMS\n\t\tconf.BET[1]=math.sqrt(1.00-1.00/(conf.GAM[1]*conf.GAM[1]))\n\t\tfor I in range(2,12000+1):\n\t\t\tAJ=float(I-1)\n\t\t\tconf.E[I]=EHALF+conf.ESTEP*AJ\n\t\t\tconf.GAM[I]=(conf.EMS+conf.E[I])/conf.EMS\n\t\t\tconf.BET[I]=math.sqrt(1.00-1.00/(conf.GAM[I]*conf.GAM[I]))\n\t\tESTEP1=20.0\n\t\tfor I in range(12001,16000+1):\n\t\t\tAJ=float(I-12000)\n\t\t\tconf.E[I]=12000.0+AJ*ESTEP1\n\t\t\tconf.GAM[I]=(conf.EMS+conf.E[I])/conf.EMS\n\t\t\tconf.BET[I]=math.sqrt(1.00-1.00/(conf.GAM[I]*conf.GAM[I]))\n\t\tESTEP2=(conf.EFINAL-92000.0)/float(4000)\n\t\tfor I in range(16001,20000+1):\n\t\t\tAJ=float(I-16000)\n\t\t\tconf.E[I]=92000.0+AJ*ESTEP2\n\t\t\tconf.GAM[I]=(conf.EMS+conf.E[I])/conf.EMS\n\t\t\tconf.BET[I]=math.sqrt(1.00-1.00/(conf.GAM[I]*conf.GAM[I]))\n\t# endif\n\t#  RADIANS PER PICOSECOND                                        \n\tconf.WB=AWB*conf.BMAG*1.0*(10**-12 )\n\t#   METRES PER PICOSECOND\n\n\tif(conf.BMAG == 0.00):\n\t\treturn LAST\n\tconf.EOVB=conf.EFIELD*1*(10**-9)/conf.BMAG\n\treturn LAST\n\t\n\tGOTO999()                                                            \n\t# end                                                               \n\n# SETUP(0)", "meta": {"hexsha": "99e6252ab9cabb45e583c646ad1371a38107da24", "size": 23859, "ext": "py", "lang": "Python", "max_stars_repo_path": "Setup.py", "max_stars_repo_name": "fireballpoint1/fortranTOpy", "max_stars_repo_head_hexsha": "55843a62c6f0a2f8e2a777ef70193940d3d2d141", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-26T05:10:56.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-26T05:10:56.000Z", "max_issues_repo_path": "Setup.py", "max_issues_repo_name": "fireballpoint1/fortranTOpy", "max_issues_repo_head_hexsha": "55843a62c6f0a2f8e2a777ef70193940d3d2d141", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Setup.py", "max_forks_repo_name": "fireballpoint1/fortranTOpy", "max_forks_repo_head_hexsha": "55843a62c6f0a2f8e2a777ef70193940d3d2d141", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-06-26T18:06:44.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-26T18:06:44.000Z", "avg_line_length": 32.1983805668, "max_line_length": 132, "alphanum_fraction": 0.6367827654, "include": true, "reason": "import numpy", "num_tokens": 9113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757645879592641, "lm_q2_score": 0.26588047891687405, "lm_q1q2_score": 0.1796726122816732}}
{"text": "\"\"\"\nPVSource.py\n\nAuthor: Matthew Yu, Array Lead (2020).\nContact: matthewjkyu@gmail.com\nCreated: 11/14/20\nLast Modified: 11/24/20\n\nDescription: The PVSource (Photovoltaic Cell/Module/Subarray) class is a\nconcrete base class that provides a common API for derived classes to use. The\nPVCell class enables users to retrieve information of the PV model, such as\nIV curves, maximum power points, and so on given a set of input conditions.\n\nThe following paper discusses how to model multiple module PV sources with\nvariable shading:\n\n    Accurate Modeling of Partially Shaded PV Arrays (Meyers\n    et Mikofski)\n\n    A library developed by these authors is called PVMismatch;\n    it can be found at [https://github.com/SunPower/PVMismatch].\n    We can potentially draw inspiration on this work to build\n    PVSource (This is very hard, since I don't understand their\n    code!)\n\n    Attribution of the library:\n\n    Mark Mikofski, Bennet Meyers, Chetan Chaudhari (2018).\n    “PVMismatch Project: https://github.com/SunPower/PVMismatch\".\n    SunPower Corporation, Richmond, CA.\n\nTODO: for now, we'll just use the first module we come across when generating\ncurrent and associated IV curve characteristics.\n\"\"\"\n# Library Imports.\nimport numpy as np\nimport sys\n\n# Custom Imports.\nfrom ArraySimulation.PVSource.PVCell.PVCellIdeal import PVCellIdeal\nfrom ArraySimulation.PVSource.PVCell.PVCellNonideal import PVCellNonideal\n\n\nclass PVSource:\n    \"\"\"\n    The PVSource (Photovoltaic source, which encompasses cells, modules, and\n    subarrays), is a concrete base class that provides a common API for clients\n    to use. The PVSource class enables users to retrieve information on the\n    PVSource model, such as IV curves, maximum power points, and so on given a\n    set of input conditions.\n    \"\"\"\n\n    # The upper voltage bound that should be tested by any model for a single\n    # cell. We expect the PV to always be at open circuit voltage at this point.\n    # Adjustable based on the number of cells determined from the initialization.\n    MAX_CELL_VOLTAGE = 0.8\n\n    # Our starting upper current bound when looking for the minimum current of\n    # a set of modules in series with bypass diodes.\n    MAX_CURRENT = 8\n\n    # Out starting lower current bound when looking for the I-V curve of a set\n    # of modules in series with bypass diodes.\n    MIN_CURRENT = 0\n\n    def __init__(self):\n        # Determines the model used by each cell. Every cell gets the same model.\n        self._modelType = None\n\n        # Controls whether each cell in a model calculates its current using a\n        # lookup table or not.\n        self._useLookup = None\n\n    def setupModel(self, modelType=\"Default\", useLookup=True):\n        \"\"\"\n        Sets up the initial source parameters.\n\n        Parameters\n        ----------\n        modelType: String\n            Specifies the PVCell model used for modeling all photovoltaics.\n        useLookup: Bool\n            Enables the use of lookup tables, if they exist for the model. If it\n            doesn't, we default to the getCurrent function that doesn't use\n            lookups.\n        \"\"\"\n        self._modelType = modelType\n        if modelType == \"Ideal\":\n            self._model = PVCellIdeal(useLookup)\n        elif modelType == \"Nonideal\":\n            self._model = PVCellNonideal(useLookup)\n        else:\n            self._model = None\n\n        self._useLookup = useLookup\n\n    def getModuleCurrent(self, moduleDef):\n        \"\"\"\n        Calculates and returns the source model current for a specific module\n        given various environmental parameters.\n\n        Parameters\n        ----------\n        moduleDef: Dict\n            A dictionary for a single module, in the following format:\n\n            moduleDef = {\n                \"numCells\": int,\n                \"voltage\": float,       (V)\n                \"irradiance\": float,    (W/m^2)\n                \"temperature\": float,   (C)\n            }\n\n        Returns\n        -------\n        float|None:\n            Current of the module model or None if the model is not defined.\n        Throws an exception for undefined cell model.\n\n        Assumptions\n        -----------\n        Current is roughly linear to the number of cells in series.\n        \"\"\"\n        if self._model is not None:\n            if self._useLookup:\n                return self._model.getCurrentLookup(\n                    moduleDef[\"numCells\"],\n                    moduleDef[\"voltage\"],\n                    moduleDef[\"irradiance\"],\n                    moduleDef[\"temperature\"],\n                )\n            else:\n                return self._model.getCurrent(\n                    moduleDef[\"numCells\"],\n                    moduleDef[\"voltage\"],\n                    moduleDef[\"irradiance\"],\n                    moduleDef[\"temperature\"],\n                )\n        else:\n            raise Exception(\"No cell model is defined for the PVSource.\")\n\n    def getSourceCurrent(self, modulesDef):\n        \"\"\"\n        Calculates and returns the source model current given various\n        environmental parameters.\n\n        Parameters\n        ----------\n        modulesDef: Dict\n            A dictionary for a set of modules representing the source, in the\n            following format:\n\n            modulesDef = {\n                \"0\": {\n                    \"numCells\": int,\n                    \"voltage\": float,       (V)\n                    \"irradiance\": float,    (W/m^2)\n                    \"temperature\": float,   (C)\n                },\n                ...\n            }\n\n        Returns\n        -------\n        float|None:\n            Current of the source model or None if the model is not defined.\n\n        Assumptions\n        -----------\n        Current is roughly linear to the number of cells in series.\n        \"\"\"\n        if self._model is not None:\n            # Go through each module and look for the current.\n            moduleCurrents = {}\n            for (moduleKey, moduleVals) in modulesDef.items():\n                moduleCurrents[moduleKey] = self.getModuleCurrent(moduleVals)\n\n            # Sort the list in descending current order.\n            moduleCurrentsSorted = sorted(\n                moduleCurrents.items(), key=lambda item: -item[1]\n            )\n\n            # Get the list of currents again, but each successive module has\n            # numCells incremented by 1.\n            currents = []\n            curCellNum = 0\n            for moduleKey in moduleCurrentsSorted:\n                module = modulesDef[moduleKey[0]]\n                currents.append(\n                    self.getModuleCurrent(\n                        {\n                            \"numCells\": module[\"numCells\"] + curCellNum,\n                            \"voltage\": module[\"voltage\"], # TODO: getModuleCurrent can't deal with >1 cell\n                            \"irradiance\": module[\"irradiance\"],\n                            \"temperature\": module[\"temperature\"],\n                        }\n                    )\n                )\n                curCellNum += module[\"numCells\"]\n\n            current = max(currents) * (\n                1 - np.exp(-1000)  # TODO: this is a magic number for now.\n            )\n            return current\n        else:\n            raise Exception(\"No cell model is defined for the PVSource.\")\n\n    def getIV(self, modulesDef, numCells, resolution=0.01):\n        \"\"\"\n        TODO: implement multimodule support\n        Calculates the entire source model current voltage plot given various\n        environmental parameters.\n\n        Parameters\n        ----------\n        modulesDef: Dict\n            A dictionary for a set of modules representing the source, in the\n            following format:\n\n            modulesDef = {\n                \"0\": {\n                    \"numCells\": int,\n                    \"voltage\": float,       (V)\n                    \"irradiance\": float,    (W/m^2)\n                    \"temperature\": float,   (C)\n                },\n                ...\n            }\n        numCells: int\n            Total number of cells in the source.\n        resolution: float\n            Voltage stride across the source. Occurs within the bounds of [0,\n            MAX_VOLTAGE], inclusive.\n\n        Returns\n        -------\n        list: [(voltage:float, current:float), ...]\n            A list of paired voltage|current tuples across the cell IV curve.\n\n        Assumptions\n        -----------\n        The IV curve of the source has a short circuit current of 0A at\n        MAX_VOLTAGE.\n        \"\"\"\n        # We need to calculate the expected maximum voltage that can be applied\n        # over all modules.\n        model = []\n        if self._model is not None:\n            for voltage in np.arange(\n                0, round(PVSource.MAX_CELL_VOLTAGE * numCells, 2) + 0.01, 0.01\n            ):\n                for module in modulesDef.values():\n                    module[\"voltage\"] = voltage\n                current = self.getSourceCurrent(modulesDef)\n                voltCurrPair = (voltage, current)\n                model.append(voltCurrPair)\n            return model\n        else:\n            raise Exception(\"No cell model is defined for the PVSource.\")\n\n    def getEdgeCharacteristics(self, modulesDef, numCells, resolution=0.01):\n        \"\"\"\n        Calculates the source model edge characteristics given various\n        environmental parameters.\n\n        Parameters\n        ----------\n        modulesDef: Dict\n            A dictionary for a set of modules representing the source, in the\n            following format:\n\n            modulesDef = {\n                \"0\": {\n                    \"numCells\": int,\n                    \"voltage\": float,       (V)     <- This is ignored.\n                    \"irradiance\": float,    (W/m^2)\n                    \"temperature\": float,   (C)\n                },\n                ...\n            }\n        numCells: int\n            Total number of cells in the source.\n        resolution: float\n            Voltage stride across the source. Occurs within the bounds of [0,\n            MAX_VOLTAGE], inclusive.\n\n        Returns\n        -------\n        tuple: (V_OC:float, I_SC:float, (V_MPP:float, I_MPP:float)):\n            A tuple of tuples indicating the open circuit voltage, the short\n            circuit current, and the GLOBAL maximum power point (MPP) voltage\n            and current.\n        \"\"\"\n        if self._model is not None:\n            mpp = (0, 0)  # voltage, current list\n            OCVoltage = 0.0\n\n            if resolution <= 0:\n                resolution = self.MIN_RESOLUTION\n\n            model = self.getIV(modulesDef, numCells, resolution)\n\n            if model != []:\n                SCCurrent = model[0][1]  # Current in first entry\n                for (voltage, current) in model:\n                    if mpp[0] * mpp[1] < voltage * current:\n                        mpp = (voltage, current)\n                    if OCVoltage != 0.0 and current == 0:\n                        OCVoltage = voltage\n\n                return (OCVoltage, SCCurrent, mpp)\n            else:\n                return (0, 0, (0, 0))\n        else:\n            raise Exception(\"No cell model is defined for the PVSource.\")\n\n    def getModelType(self):\n        \"\"\"\n        Returns the model type used for each PVCell in PVSource.\n\n        Return\n        ------\n        String: Model type name.\n        \"\"\"\n        return self._modelType\n", "meta": {"hexsha": "781ef6803b76290462547a85c8acbaad3cde58eb", "size": 11352, "ext": "py", "lang": "Python", "max_stars_repo_path": "ArraySimulation/PVSource/PVSource.py", "max_stars_repo_name": "lhr-solar/Array-Sim-Training", "max_stars_repo_head_hexsha": "e7372ee4ed094f1527e5cdbc1817108d93acace8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ArraySimulation/PVSource/PVSource.py", "max_issues_repo_name": "lhr-solar/Array-Sim-Training", "max_issues_repo_head_hexsha": "e7372ee4ed094f1527e5cdbc1817108d93acace8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-10-13T04:59:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-28T04:13:22.000Z", "max_forks_repo_path": "ArraySimulation/PVSource/PVSource.py", "max_forks_repo_name": "lhr-solar/Array-Sim-Training", "max_forks_repo_head_hexsha": "e7372ee4ed094f1527e5cdbc1817108d93acace8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8220858896, "max_line_length": 106, "alphanum_fraction": 0.5567300916, "include": true, "reason": "import numpy", "num_tokens": 2381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.1796691581831434}}
{"text": "\"\"\"MBT: Multimodal Bottleneck Transformers.\"\"\"\n\nimport functools\nfrom typing import Any, Callable, Dict, Iterable, Optional, Tuple\n\nfrom absl import logging\nimport flax.linen as nn\nfrom flax.linen.linear import default_kernel_init\nfrom immutabledict import immutabledict\nimport jax\nimport jax.numpy as jnp\nimport ml_collections\nimport numpy as np\nfrom scenic.model_lib.base_models import base_model\nfrom scenic.model_lib.base_models import classification_model\nfrom scenic.model_lib.base_models import model_utils as base_model_utils\nfrom scenic.model_lib.base_models.classification_model import ClassificationModel\nfrom scenic.model_lib.layers import attention_layers\nfrom scenic.model_lib.layers import nn_layers\nfrom scenic.projects.baselines import vit\nfrom scenic.projects.mbt import model_utils\n\nInitializer = Callable[[jnp.ndarray, Iterable[int], jnp.dtype], jnp.ndarray]\n\n_MBT_CLASSIFICATION_METRICS = immutabledict({\n    'accuracy': (base_model_utils.weighted_correctly_classified,\n                 base_model_utils.num_examples),\n    'accuracy_top_5': (functools.partial(\n        base_model_utils.weighted_topk_correctly_classified,\n        k=5), base_model_utils.num_examples),\n    'loss': (base_model_utils.weighted_unnormalized_softmax_cross_entropy,\n             base_model_utils.num_examples)\n})\n\n_MODALITIES = ['rgb', 'spectrogram']\n\n\ndef _reshape_to_time_space(x, temporal_dims):\n  if x.ndim == 3:\n    b, thw, d = x.shape\n    assert thw % temporal_dims == 0\n    hw = thw // temporal_dims\n    x = jnp.reshape(x, [b, temporal_dims, hw, d])\n  assert x.ndim == 4\n  return x\n\n\ndef embed_2d_patch(x, patches, embedding_dim, name='embedding'):\n  \"\"\"Embedding input patches with 2D conv.\"\"\"\n\n  assert patches.get('size') is not None, ('patches.size is now the only way'\n                                           'to define the patches')\n  assert embedding_dim, 'embedding_dim must be specified'\n  fh = patches.size[0]\n  fw = patches.size[1]\n  x = nn.Conv(\n      embedding_dim, (fh, fw),\n      strides=(fh, fw),\n      padding='VALID',\n      name=name)(x)\n\n  return x\n\n\ndef embed_3d_patch(x,\n                   patches,\n                   embedding_dim,\n                   kernel_init_method,\n                   name='embedding'):\n  \"\"\"Embed 3D input patches into tokens.\"\"\"\n\n  assert patches.get('size') is not None, 'patches.size must be defined'\n  assert len(patches.size) == 3, 'patches.size must have 3 elements'\n  assert embedding_dim, 'embedding_dim must be specified'\n\n  fh, fw, ft = patches.size\n\n  if kernel_init_method == 'central_frame_initializer':\n    kernel_initializer = model_utils.central_frame_initializer()\n    logging.info('Using central frame initializer for input embedding')\n  elif kernel_init_method == 'average_frame_initializer':\n    kernel_initializer = model_utils.average_frame_initializer()\n    logging.info('Using average frame initializer for input embedding')\n  else:\n    kernel_initializer = default_kernel_init\n    logging.info('Using default initializer for input embedding')\n\n  x = nn.Conv(\n      embedding_dim, (ft, fh, fw),\n      strides=(ft, fh, fw),\n      padding='VALID',\n      name=name,\n      kernel_init=kernel_initializer)(x)\n\n  return x\n\n\ndef temporal_encode(x,\n                    modality,\n                    temporal_encoding_config,\n                    patches,\n                    hidden_size,\n                    return_1d=True):\n  \"\"\"Encode video for feeding into ViT.\"\"\"\n  if modality == 'spectrogram':\n    # Spectrogram is treated as a big num_time_bins by num_mel_bins image.\n    x = embed_2d_patch(x, patches, hidden_size, 'embedding_spectrogram')\n    temporal_dims = 1\n    if return_1d:\n      n, h, w, c = x.shape\n      x = jnp.reshape(x, [n, h * w, c])\n  elif modality == 'rgb':\n    if temporal_encoding_config.method == 'temporal_sampling':\n      n, num_frames, in_h, in_w, c = x.shape\n      n_sampled_frames = temporal_encoding_config.n_sampled_frames\n      if n_sampled_frames < num_frames:\n        t_start_idx = num_frames / (n_sampled_frames + 1)\n        t_step = t_start_idx\n      else:\n        t_start_idx = 0\n        t_step = 1\n      t_end_idx = num_frames\n      temporal_indices = jnp.arange(t_start_idx, t_end_idx, t_step)\n      temporal_indices = jnp.round(temporal_indices).astype(jnp.int32)\n      temporal_indices = jnp.minimum(temporal_indices, num_frames - 1)\n\n      x = x[:, temporal_indices]  # [n, t_s, in_h, in_w, c]\n      t_s = x.shape[1]\n      x = jnp.reshape(x, [n, t_s * in_h, in_w, c])\n      x = embed_2d_patch(x, patches, hidden_size)\n      temporal_dims = t_s\n      if return_1d:\n        n, th, w, c = x.shape\n        x = jnp.reshape(x, [n, th * w, c])\n      else:\n        n, th, w, c = x.shape\n        x = jnp.reshape(x, [n, t_s, -1, w, c])\n    if temporal_encoding_config.method == '3d_conv':\n      kernel_init_method = temporal_encoding_config.get('kernel_init_method',\n                                                        None)\n\n      x = embed_3d_patch(x, patches, hidden_size, kernel_init_method)\n      temporal_dims = x.shape[1]\n      if return_1d:\n        n, t, h, w, c = x.shape\n        x = jnp.reshape(x, [n, t * h * w, c])\n  else:\n    raise AssertionError('Unknown temporal encoding method.')\n  return x, temporal_dims\n\n\ndef add_positional_embed(x, feat_name):\n  \"\"\"Adds positional embedding.\"\"\"\n  assert x.ndim == 3  # (batch, len, emb)\n  x = vit.AddPositionEmbs(\n      posemb_init=nn.initializers.normal(stddev=0.02),  # from BERT.\n      name=feat_name)(x)\n  return x\n\n\nclass EncoderBlock(nn.Module):\n  \"\"\"Transformer encoder block.\n\n  Attributes:\n    mlp_dim: Dimension of the mlp on top of attention block.\n    num_heads: Number of heads.\n    dtype: The dtype of the computation (default: float32).\n    dropout_rate: Dropout rate.\n    attention_dropout_rate: Dropout for attention heads.\n    attention_kernel_initializer: Initializer to use for attention\n      layers.\n    droplayer_p: Probability of dropping a layer.\n\n\n\n  Returns:\n    Output after transformer encoder block.\n  \"\"\"\n  mlp_dim: int\n  num_heads: int\n  dtype: Any = jnp.float32\n  dropout_rate: float = 0.1\n  attention_dropout_rate: float = 0.1\n  attention_kernel_initializer: Initializer = nn.initializers.xavier_uniform()\n  droplayer_p: float = 0.0\n\n  def get_drop_pattern(self, x, deterministic):\n    if not deterministic and self.droplayer_p:\n      shape = (x.shape[0],) + (1,) * (x.ndim - 1)\n      return jax.random.bernoulli(\n          self.make_rng('dropout'), self.droplayer_p, shape).astype('float32')\n    else:\n      return 0.0\n\n  @nn.compact\n  def __call__(self, inputs: jnp.ndarray, deterministic: bool) -> jnp.ndarray:\n    \"\"\"Applies Encoder1DBlock module.\"\"\"\n\n    # Attention block.\n    x = nn.LayerNorm(dtype=self.dtype)(inputs)\n    x = nn.MultiHeadDotProductAttention(\n        num_heads=self.num_heads,\n        kernel_init=self.attention_kernel_initializer,\n        broadcast_dropout=False,\n        dropout_rate=self.attention_dropout_rate,\n        dtype=self.dtype)(x, x, deterministic=deterministic)\n    x = nn.Dropout(rate=self.dropout_rate)(x, deterministic)\n\n    drop_pattern = self.get_drop_pattern(x, deterministic)\n    x = x * (1.0 - drop_pattern) + inputs\n\n    # MLP block.\n    y = nn.LayerNorm(dtype=self.dtype)(x)\n    y = attention_layers.MlpBlock(\n        mlp_dim=self.mlp_dim,\n        dtype=self.dtype,\n        dropout_rate=self.dropout_rate,\n        activation_fn=nn.gelu,\n        kernel_init=nn.initializers.xavier_uniform(),\n        bias_init=nn.initializers.normal(stddev=1e-6))(\n            y, deterministic=deterministic)\n\n    drop_pattern = self.get_drop_pattern(x, deterministic)\n    return y * (1.0 - drop_pattern) + x\n\n\nclass Encoder(nn.Module):\n  \"\"\"Transformer Encoder.\n\n  Attributes:\n    mlp_dim: Dimension of the mlp on top of attention block.\n    num_layers: Number of layers.\n    num_heads: Number of attention heads.\n    dropout_rate: Dropout rate.\n    attention_dropout_rate: Dropout for attention heads.\n    stochastic_droplayer_rate: Probability of dropping a layer linearly\n      grows from 0 to the provided value. Our implementation of stochastic\n      depth follows timm library, which does per-example layer dropping and\n      uses independent dropping patterns for each skip-connection.\n    modality_fusion: Tuple with modalities to combine.\n    fusion_layer: Which layer to fuse modalities. fusion_layer == 0 provides\n      early fusion.\n    use_bottleneck: If True, adds self-attention bottleneck.\n    test_with_bottlenecks: Whether to use bottlenecks at test time.\n    share_encoder: If True, different modalities share the same encoder weights\n      for the layers before fusion.\n    dtype: The dtype of the computation (default: float32).\n  \"\"\"\n  mlp_dim: int\n  num_layers: int\n  num_heads: int\n  dropout_rate: float = 0.1\n  attention_dropout_rate: float = 0.1\n  stochastic_droplayer_rate: float = 0.0\n  modality_fusion: Tuple[str] = ('spectrogram',)\n  fusion_layer: int = 0\n  use_bottleneck: bool = False\n  test_with_bottlenecks: bool = True\n  share_encoder: bool = False\n  dtype: Any = jnp.float32\n\n  @nn.compact\n  def __call__(self, x: Dict[str, Any],\n               bottleneck: jnp.ndarray, *,\n               train: bool):\n    \"\"\"Applies Transformer model on the inputs.\"\"\"\n\n    def get_encoder_block(encoder_block, droplayer_p, name):\n      \"\"\"Returns the encoder block for a single layer.\"\"\"\n      dtype = jax.dtypes.canonicalize_dtype(self.dtype)\n      return encoder_block(\n          mlp_dim=self.mlp_dim,\n          num_heads=self.num_heads,\n          dropout_rate=self.dropout_rate,\n          attention_dropout_rate=self.attention_dropout_rate,\n          droplayer_p=droplayer_p,\n          name=name,\n          dtype=dtype)\n\n    def get_context(target_modality, modality_fusion, x):\n      \"\"\"Returns list of context modalities.\"\"\"\n      context = []\n      for modality in _MODALITIES:\n        if modality != target_modality and modality in modality_fusion:\n          context.append(x[modality])\n      return context\n\n    def combine_context(x, other_modalities):\n      \"\"\"Combine x with a list of other modalities.\"\"\"\n      num_tokens = x.shape[1]\n      # Append x to the end of the list\n      other_modalities.append(x)\n      x_combined = jnp.concatenate(other_modalities, axis=1)\n      return x_combined, num_tokens\n\n    assert self.modality_fusion\n\n    # Add positional embeddings\n    for modality in self.modality_fusion:\n      if modality == 'rgb':\n        name = ''\n      else:\n        name = '_' + modality\n      x[modality] = add_positional_embed(x[modality], 'posembed_input' + name)\n\n    use_bottlenecks = train or self.test_with_bottlenecks\n    x_combined = None\n    # Input Encoder\n    for lyr in range(self.num_layers):\n      droplayer_p = (\n          lyr / max(self.num_layers - 1, 1)) * self.stochastic_droplayer_rate\n      encoders = {}\n      encoders['rgb'] = get_encoder_block(EncoderBlock, droplayer_p,\n                                          f'encoderblock_{lyr}')\n\n      for modality in self.modality_fusion:\n        if modality != 'rgb':\n          if self.share_encoder:\n            encoders[modality] = encoders['rgb']\n          else:\n            encoders[modality] = get_encoder_block(\n                EncoderBlock, droplayer_p,\n                f'encoderblock_{lyr}_' + modality)\n\n      if (lyr < self.fusion_layer or len(self.modality_fusion) == 1 or\n          (self.use_bottleneck and not use_bottlenecks)):\n        for modality in self.modality_fusion:\n          x[modality] = encoders[modality](x[modality], deterministic=not train)\n      else:\n        if self.use_bottleneck:\n          bottle = []\n          for modality in self.modality_fusion:\n            t_mod = x[modality].shape[1]\n            in_mod = jnp.concatenate([x[modality], bottleneck], axis=1)\n            out_mod = encoders[modality](in_mod, deterministic=not train)\n            x[modality] = out_mod[:, :t_mod]\n            bottle.append(out_mod[:, t_mod:])\n          bottleneck = jnp.mean(jnp.stack(bottle, axis=-1), axis=-1)\n        else:\n          if not self.share_encoder and len(self.modality_fusion) > 1:\n            x_new = {}\n            for modality in self.modality_fusion:\n              other_modalities = get_context(modality, self.modality_fusion, x)\n              combined_mods, t = combine_context(x[modality], other_modalities)\n              combined_mods = encoders[modality](\n                  combined_mods, deterministic=not train)\n              x_new[modality] = combined_mods[:, -t:]\n            x = x_new\n\n          elif self.share_encoder and len(self.modality_fusion) > 1:\n            if x_combined is None:\n              x_combined = []\n              for modality in self.modality_fusion:\n                x_combined.append(x[modality])\n              x_combined = jnp.concatenate(x_combined, axis=1)\n            x_combined = encoders['rgb'](x_combined, deterministic=not train)\n    if x_combined is not None:\n      x_out = x_combined\n    else:\n      x_out = []\n      for modality in self.modality_fusion:\n        x_out.append(x[modality])\n      x_out = jnp.concatenate(x_out, axis=1)\n    encoded = nn.LayerNorm(name='encoder_norm')(x_out)\n\n    return encoded\n\n\nclass MBT(nn.Module):\n  \"\"\"Audio-Visual Fusion Transformer model for Video.\n\n  Attributes:\n    mlp_dim: Dimension of the mlp on top of attention block.\n    num_layers: Number of layers.\n    num_heads: Number of self-attention heads.\n    num_classes: Number of output classes.\n    patches: Configuration of the patches extracted in the stem of the model.\n    hidden_size: Size of the hidden state of the output of model's stem.\n      if None, we skip the extra projection + tanh activation at the end.\n    temporal_encoding_config: ConfigDict which defines the type of input\n      encoding when tokenising the video.\n    attention_config: ConfigDict which defines the type of spatio-temporal\n      attention applied in the model.\n    representation_size: Size of the representation layer in the model's head.\n    dropout_rate: Dropout rate.\n    attention_dropout_rate: Dropout for attention heads.\n    stochastic_droplayer_rate: Probability of dropping a layer. Linearly\n      increases from 0 to the provided value..\n    classifier: type of the classifier layer. Options are 'gap', 'gmp', 'gsp',\n      'token'.\n    modality_fusion: Tuple with modalities to combine.\n    fusion_layer: Which layer to fuse modalities.\n    return_prelogits: If true, return the final representation of the network\n      before the classification head. Useful when using features for a\n      downstream task.\n    return_preclassifier: If true, return a dict of all token embeddings.\n      Useful when using token embeddings for a downstream task.\n    use_bottleneck: If True, adds self-attention bottleneck.\n    n_bottlenecks: Number of bottleneck tokens.\n    test_with_bottlenecks: Whether to use bottlenecks at test time.\n    share_encoder: If True, different modalities share the same encoder weights\n      for the layers before fusion.\n    dtype: JAX data type for activations.\n  \"\"\"\n\n  mlp_dim: int\n  num_layers: int\n  num_heads: int\n  num_classes: int\n  patches: ml_collections.ConfigDict\n  hidden_size: int\n  temporal_encoding_config: ml_collections.ConfigDict\n  attention_config: ml_collections.ConfigDict\n  representation_size: Optional[int] = None\n  dropout_rate: float = 0.1\n  attention_dropout_rate: float = 0.1\n  stochastic_droplayer_rate: float = 0.\n  classifier: str = 'gap'\n  modality_fusion: Tuple[str] = ('spectrogram',)\n  fusion_layer: int = 0\n  return_prelogits: bool = False\n  return_preclassifier: bool = False\n  use_bottleneck: bool = False\n  n_bottlenecks: int = 4\n  test_with_bottlenecks: bool = True\n  share_encoder: bool = False\n  dtype: Any = jnp.float32\n\n  @nn.compact\n  def __call__(self,\n               x,\n               *,\n               train: bool,\n               debug: bool = False):\n    assert self.fusion_layer <= self.num_layers and self.fusion_layer >= 0\n    assert self.classifier in ['token', '0', 'gap', 'gmp', 'gsp']\n\n    temporal_dims = {}\n    for modality in self.modality_fusion:\n      x[modality], _ = temporal_encode(\n          x[modality], modality, self.temporal_encoding_config, self.patches,\n          self.hidden_size)\n      # If we want to add a class token, add it here.\n      if self.classifier in ['token']:\n        if modality == 'rgb' or len(self.modality_fusion) == 1:\n          name = ''\n        else:\n          name = modality\n        n, temporal_dims[modality], c = x[modality].shape\n        cls = self.param('cls'+name, nn.initializers.zeros, (1, 1, c),\n                         x[modality].dtype)\n        cls = jnp.tile(cls, [n, 1, 1])\n        x[modality] = jnp.concatenate([cls, x[modality]], axis=1)\n        bottleneck_dtype = x[modality].dtype\n\n    bottleneck = None\n    if self.use_bottleneck:\n      n_bottlenecks = self.n_bottlenecks\n      if self.classifier in ['token']:\n        n_bottlenecks += 1\n      bottleneck = self.param('bottleneck',\n                              nn.initializers.normal(stddev=0.02),  # From BERT.\n                              (1, n_bottlenecks, c), bottleneck_dtype)\n      bottleneck = jnp.tile(bottleneck, [n, 1, 1])\n\n    x = Encoder(\n        modality_fusion=self.modality_fusion,\n        fusion_layer=self.fusion_layer,\n        mlp_dim=self.mlp_dim,\n        num_layers=self.num_layers,\n        num_heads=self.num_heads,\n        dropout_rate=self.dropout_rate,\n        attention_dropout_rate=self.attention_dropout_rate,\n        stochastic_droplayer_rate=self.stochastic_droplayer_rate,\n        use_bottleneck=self.use_bottleneck,\n        test_with_bottlenecks=self.test_with_bottlenecks,\n        share_encoder=self.share_encoder,\n        dtype=self.dtype,\n        name='Transformer')(x, bottleneck, train=train)\n\n    if self.return_preclassifier:\n      return x\n\n    if self.classifier in ['token', '0']:\n      # Obtaining the CLS tokens for each modality.\n      x_out = {}\n      counter = 0\n      for modality in self.modality_fusion:\n        x_out[modality] = x[:, counter]\n        counter += temporal_dims[modality] + 1\n    elif self.classifier in ('gap', 'gmp', 'gsp'):\n      fn = {'gap': jnp.mean, 'gmp': jnp.max, 'gsp': jnp.sum}[self.classifier]\n      x_out = fn(x, axis=list(range(1, x.ndim - 1)))\n\n    if self.representation_size is not None:\n      pre_logits_fc = nn.Dense(self.representation_size, name='pre_logits')\n      if isinstance(x_out, dict):\n        for modality in x_out:\n          x_out[modality] = pre_logits_fc(x_out[modality])\n          x_out[modality] = nn.tanh(x_out[modality])\n      else:\n        x_out = nn.Dense(self.representation_size, name='pre_logits')(x_out)\n        x_out = nn.tanh(x_out)\n    else:\n      if not isinstance(x_out, dict):\n        x_out = nn_layers.IdentityLayer(name='pre_logits')(x_out)\n\n    if self.return_prelogits:\n      return x_out\n    if isinstance(x_out, dict):\n      output_projection_fc = nn.Dense(\n          self.num_classes,\n          kernel_init=nn.initializers.zeros,\n          name='output_projection')\n      x_pool = 0\n      for modality in x_out:\n        x_out[modality] = output_projection_fc(x_out[modality])\n        x_pool += x_out[modality]\n      x_pool /= len(x_out)\n      if not train:\n        return x_pool\n    else:\n      x_out = nn.Dense(\n          self.num_classes,\n          kernel_init=nn.initializers.zeros,\n          name='output_projection')(\n              x_out)\n    return x_out\n\n\nclass MBTMultilabelClassificationModel(vit.ViTMultiLabelClassificationModel):\n  \"\"\"Video Transformer model for multi-class classification.\"\"\"\n\n  def build_flax_model(self) -> nn.Module:\n    model_dtype = getattr(jnp, self.config.get('model_dtype_str', 'float32'))\n    return MBT(\n        num_classes=self.dataset_meta_data['num_classes'],\n        modality_fusion=self.config.model.modality_fusion,\n        fusion_layer=self.config.model.fusion_layer,\n        use_bottleneck=self.config.model.get('use_bottleneck', False),\n        test_with_bottlenecks=self.config.model.get(\n            'test_with_bottlenecks', True),\n        n_bottlenecks=self.config.model.get('n_bottlenecks', 4),\n        share_encoder=self.config.model.get('share_encoder', False),\n        mlp_dim=self.config.model.mlp_dim,\n        num_layers=self.config.model.num_layers,\n        num_heads=self.config.model.num_heads,\n        representation_size=self.config.model.representation_size,\n        patches=self.config.model.patches,\n        hidden_size=self.config.model.hidden_size,\n        temporal_encoding_config=self.config.model.temporal_encoding_config,\n        attention_config=self.config.model.attention_config,\n        classifier=self.config.model.classifier,\n        dropout_rate=self.config.model.get('dropout_rate', 0.1),\n        attention_dropout_rate=self.config.model.get('attention_dropout_rate',\n                                                     0.1),\n        stochastic_droplayer_rate=self.config.model.get(\n            'stochastic_droplayer_rate', 0),\n        return_prelogits=self.config.model.get('return_prelogits', False),\n        dtype=model_dtype)\n\n  def init_from_train_state(self,\n                            train_state: Any,\n                            restored_train_state: Any,\n                            restored_model_cfg: ml_collections.ConfigDict,\n                            restore_output_proj: bool = False) -> Any:\n    \"\"\"Updates the train_state with data from restored_train_state.\"\"\"\n    return model_utils.initialise_from_train_state(self.config, train_state,\n                                                   restored_train_state,\n                                                   restored_model_cfg,\n                                                   restore_output_proj)\n\n  def loss_function(self,\n                    logits: jnp.array,\n                    batch: base_model.Batch,\n                    model_params: Optional[jnp.array] = None) -> float:\n    \"\"\"Returns sigmoid cross entropy loss with an L2 penalty on the weights.\n\n    Args:\n      logits: Output of model in shape [batch, length, num_classes]. Optionally,\n        this can also be a dictionary with logits for individual modalities.\n      batch: Batch of data that has 'label' and optionally 'batch_mask'.\n      model_params: Parameters of the model, for optionally applying\n        regularization.\n\n    Returns:\n      Total loss.\n    \"\"\"\n    weights = batch.get('batch_mask')\n    labels = batch['label']\n\n    assert self.dataset_meta_data.get('target_is_onehot', False)\n\n    label_weights = self.dataset_meta_data.get('class_weights', None)\n\n    if isinstance(logits, dict):\n      sig_ce_loss = []\n      for modality in logits:\n        sig_ce_loss.append(base_model_utils.weighted_sigmoid_cross_entropy(\n            logits[modality],\n            labels[modality],\n            weights,\n            label_weights=label_weights,\n            label_smoothing=self.config.get('label_smoothing')))\n      sig_ce_loss = jnp.mean(jnp.array(sig_ce_loss))\n    else:\n      if isinstance(labels, dict):\n        assert 'all' in labels, 'mixmod must be turned off.'\n        labels = labels['all']\n      sig_ce_loss = base_model_utils.weighted_sigmoid_cross_entropy(\n          logits,\n          labels,\n          weights,\n          label_weights=label_weights,\n          label_smoothing=self.config.get('label_smoothing'))\n    if self.config.get('l2_decay_factor') is None:\n      total_loss = sig_ce_loss\n    else:\n      l2_loss = base_model_utils.l2_regularization(model_params)\n      total_loss = sig_ce_loss + 0.5 * self.config.l2_decay_factor * l2_loss\n    return total_loss\n\n\nclass MBTClassificationModel(ClassificationModel):\n  \"\"\"Audio Video Transformer model for n-way classification.\"\"\"\n\n  def build_flax_model(self) -> nn.Module:\n    assert (self.config.model.attention_config.get('type', 'spacetime') !=\n            'factorized_encoder'), (\n                'Other attention types not supported.')\n    model_dtype = getattr(jnp, self.config.get('model_dtype_str', 'float32'))\n    return MBT(\n        num_classes=self.dataset_meta_data['num_classes'],\n        modality_fusion=self.config.model.modality_fusion,\n        fusion_layer=self.config.model.fusion_layer,\n        use_bottleneck=self.config.model.get('use_bottleneck', False),\n        test_with_bottlenecks=self.config.model.get(\n            'test_with_bottlenecks', True),\n        n_bottlenecks=self.config.model.get('n_bottlenecks', 4),\n        share_encoder=self.config.model.get('share_encoder', False),\n        mlp_dim=self.config.model.mlp_dim,\n        num_layers=self.config.model.num_layers,\n        num_heads=self.config.model.num_heads,\n        representation_size=self.config.model.representation_size,\n        patches=self.config.model.patches,\n        hidden_size=self.config.model.hidden_size,\n        temporal_encoding_config=self.config.model.temporal_encoding_config,\n        attention_config=self.config.model.attention_config,\n        classifier=self.config.model.classifier,\n        dropout_rate=self.config.model.get('dropout_rate', 0.1),\n        attention_dropout_rate=self.config.model.get('attention_dropout_rate',\n                                                     0.1),\n        stochastic_droplayer_rate=self.config.model.get(\n            'stochastic_droplayer_rate', 0),\n        return_prelogits=self.config.model.get('return_prelogits', False),\n        dtype=model_dtype)\n\n  def loss_function(self,\n                    logits: jnp.ndarray,\n                    batch: base_model.Batch,\n                    model_params: Optional[jnp.ndarray] = None) -> float:\n    \"\"\"Returns softmax cross entropy loss with an L2 penalty on the weights.\n\n    Args:\n      logits: Output of model in shape [batch, length, num_classes]. Optionally,\n        this can also be a dictionary with logits for individual modalities.\n      batch: Batch of data that has 'label' and optionally 'batch_mask'.\n      model_params: Parameters of the model, for optionally applying\n        regularization.\n\n    Returns:\n      Total loss.\n    \"\"\"\n    weights = batch.get('batch_mask')\n    labels = batch['label']\n\n    assert self.dataset_meta_data.get('target_is_onehot', False)\n\n    if isinstance(logits, dict):\n      sof_ce_loss = []\n      for modality in logits:\n        sof_ce_loss.append(base_model_utils.weighted_softmax_cross_entropy(\n            logits[modality],\n            labels[modality],\n            weights,\n            label_smoothing=self.config.get('label_smoothing')))\n      sof_ce_loss = jnp.mean(jnp.array(sof_ce_loss))\n    else:\n      sof_ce_loss = base_model_utils.weighted_softmax_cross_entropy(\n          logits,\n          labels,\n          weights,\n          label_smoothing=self.config.get('label_smoothing'))\n    if self.config.get('l2_decay_factor') is None:\n      total_loss = sof_ce_loss\n    else:\n      l2_loss = base_model_utils.l2_regularization(model_params)\n      total_loss = sof_ce_loss + 0.5 * self.config.l2_decay_factor * l2_loss\n    return total_loss\n\n  def get_metrics_fn(self, split: Optional[str] = None) -> base_model.MetricFn:\n    \"\"\"Returns a callable metric function for the model.\n\n    Args:\n      split: The split for which we calculate the metrics. It should be one\n        of the ['train',  'validation', 'test'].\n    Returns: A metric function with the following API: ```metrics_fn(logits,\n      label, weights)```\n    \"\"\"\n    del split  # for all splits, we return the same metric functions\n\n    return functools.partial(\n        classification_model.classification_metrics_function,\n        target_is_onehot=self.dataset_meta_data.get('target_is_onehot', False),\n        metrics=_MBT_CLASSIFICATION_METRICS)\n\n  def init_from_train_state(self,\n                            train_state: Any,\n                            restored_train_state: Any,\n                            restored_model_cfg: ml_collections.ConfigDict,\n                            restore_output_proj: bool = False) -> Any:\n    \"\"\"Updates the train_state with data from restored_train_state.\"\"\"\n    return model_utils.initialise_from_train_state(self.config, train_state,\n                                                   restored_train_state,\n                                                   restored_model_cfg,\n                                                   restore_output_proj)\n\n\nclass MBTMultiHeadClassificationModel(MBTClassificationModel):\n  \"\"\"Audio Visual Transformer model for multiple n-way classification.\"\"\"\n\n  def __init__(self, config, dataset_meta_data):\n    super().__init__(config, dataset_meta_data)\n\n    assert self.config.dataset_configs.get('class_splits'), (\n        'dataset_configs.class_splits must be specified')\n    self.class_splits = np.cumsum(self.config.dataset_configs.class_splits)\n    if self.config.dataset_configs.get('split_names'):\n      self.split_names = self.config.dataset_configs.split_names\n    else:\n      self.split_names = [str(x + 1) for x in range(len(self.class_splits))]\n\n    assert not config.get('multicrop_softmax_logits', False), (\n        'Returning softmaxed logits during multicrop evaluation is not '\n        'supported for this model.')\n\n  def loss_function(self,\n                    logits: jnp.ndarray,\n                    batch: base_model.Batch,\n                    model_params: Optional[jnp.ndarray] = None) -> float:\n    \"\"\"Return softmax cross entropy loss with an L2 penalty on the weights.\"\"\"\n    weights = batch.get('batch_mask')\n    labels = batch['label']\n\n    assert self.dataset_meta_data.get('target_is_onehot', False)\n    if not isinstance(logits, dict):\n      all_logits = logits\n      logits = {}\n      logits['all'] = all_logits\n      if isinstance(labels, dict):\n        assert 'all' in labels, 'mixmod must be turned off.'\n        labels = labels['all']\n      else:\n        all_labels = labels\n        labels = {}\n        labels['all'] = all_labels\n\n    sof_ce_loss = []\n    for modality in logits:\n      if logits[modality].shape[-1] != self.class_splits[-1]:\n        raise AssertionError(\n            'Logit dimension must be equal to number of classes')\n\n      logit_splits = jnp.split(logits[modality],\n                               self.class_splits, axis=-1)[:-1]\n      assert not isinstance(labels[modality], dict), labels.keys()\n      labels_splits = jnp.split(\n          labels[modality], self.class_splits, axis=-1)[:-1]\n      label_smoothing = self.config.get('label_smoothing')\n\n      sof_ce_losses = [\n          base_model_utils.weighted_softmax_cross_entropy(\n              logit_split, labels_split, weights, label_smoothing)\n          for logit_split, labels_split in zip(logit_splits, labels_splits)\n      ]\n      sof_ce_loss.append(jnp.mean(jnp.array(sof_ce_losses)))\n    sof_ce_loss = jnp.mean(jnp.array(sof_ce_loss))\n\n    if self.config.get('l2_decay_factor') is None:\n      total_loss = sof_ce_loss\n    else:\n      l2_loss = base_model_utils.l2_regularization(model_params)\n      total_loss = sof_ce_loss + 0.5 * self.config.l2_decay_factor * l2_loss\n    return total_loss\n\n  def get_metrics_fn(self, split: Optional[str] = None) -> base_model.MetricFn:\n    \"\"\"Returns a callable metric function for the model.\n\n    Args:\n      split: The split for which we calculate the metrics. It should be one\n        of the ['train',  'validation', 'test'].\n    Returns: A metric function with the following API: ```metrics_fn(logits,\n      label, weights)```\n    \"\"\"\n    del split  # for all splits, we return the same metric functions\n\n    def classification_metrics_function(logits, batch, metrics, class_splits,\n                                        split_names):\n\n      one_hot_targets = batch['label']\n      weights = batch.get('batch_mask')  # batch_mask might not be defined\n\n      logit_splits = jnp.split(logits, class_splits, axis=-1)[:-1]\n      one_hot_target_splits = jnp.split(\n          one_hot_targets, class_splits, axis=-1)[:-1]\n\n      evaluated_metrics = {}\n      total_loss = [0.0, 0.0]\n      for logits_i, one_hot_targets_i, name in zip(logit_splits,\n                                                   one_hot_target_splits,\n                                                   split_names):\n        for key, val in metrics.items():\n          evaluated_metrics[\n              f'{name}_{key}'] = base_model_utils.psum_metric_normalizer(\n                  (val[0](logits_i, one_hot_targets_i,\n                          weights), val[1](logits_i, one_hot_targets_i,\n                                           weights)))\n          if key == 'loss':\n            total_loss[0] += evaluated_metrics[f'{name}_{key}'][0]\n            total_loss[1] += evaluated_metrics[f'{name}_{key}'][1]\n      evaluated_metrics['total_loss'] = total_loss\n\n      if len(class_splits) == 2:\n        pairwise_acc = base_model_utils.psum_metric_normalizer(\n            (model_utils.joint_accuracy(logits, one_hot_targets, class_splits,\n                                        weights),\n             base_model_utils.num_examples(logits, one_hot_targets, weights)))\n        pairwise_top_five = base_model_utils.psum_metric_normalizer(\n            (model_utils.joint_top_k(\n                logits, one_hot_targets, class_splits, k=5, weights=weights),\n             base_model_utils.num_examples(logits, one_hot_targets, weights)))\n        eval_name = f'{split_names[0]}-{split_names[1]}'\n        evaluated_metrics[f'{eval_name}_accuracy'] = pairwise_acc\n        evaluated_metrics[f'{eval_name}_accuracy_top_5'] = pairwise_top_five\n\n      return evaluated_metrics\n\n    return functools.partial(\n        classification_metrics_function,\n        metrics=_MBT_CLASSIFICATION_METRICS,\n        class_splits=self.class_splits,\n        split_names=self.split_names)\n", "meta": {"hexsha": "4febaaf001f2e1a779d72ee762d1eb2335ae5701", "size": 33580, "ext": "py", "lang": "Python", "max_stars_repo_path": "scenic/projects/mbt/model.py", "max_stars_repo_name": "techthiyanes/scenic", "max_stars_repo_head_hexsha": "05585b1189364e29d82413b9d4a50ffa8c246f0c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scenic/projects/mbt/model.py", "max_issues_repo_name": "techthiyanes/scenic", "max_issues_repo_head_hexsha": "05585b1189364e29d82413b9d4a50ffa8c246f0c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scenic/projects/mbt/model.py", "max_forks_repo_name": "techthiyanes/scenic", "max_forks_repo_head_hexsha": "05585b1189364e29d82413b9d4a50ffa8c246f0c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.366940211, "max_line_length": 81, "alphanum_fraction": 0.6561346039, "include": true, "reason": "import numpy,import jax", "num_tokens": 7717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.17966915353558557}}
{"text": "#!/usr/bin/env python\n\"\"\"\n Author: Shane Bussmann, T. K. Daisy Leung\n\n\nSimilar to uvmcmcfit.py, but here we edited it to\n    - throw out a pre-defined number of burn-in samples;\n    - save acceptance_fraction + misc stuff as a separate file\n    - only save samples every some number of samples (instead of every iteration)\n    - email ourselves once a certain number of samples have been obtained, and so we can decide whether or not to stop sampling instead of interupting the code\n\n\n Last modified: 2016 Dec 15\n\n Note: This is experimental software that is in a very active stage of\n development.  If you are interested in using this for your research, please\n contact me first at tleung@astro.cornell.edu!  Thanks.\n\n Purpose: Fit a parametric model to interferometric data using Dan\n Foreman-Mackey's emcee routine.  Gravitationally lensed sources are accounted\n for using ray-tracing routines based on Adam Bolton's lensdemo_script and\n lensdemo_func python scripts.  Here is the copyright license from\n lensdemo_script.py:\n\n Copyright 2009 by Adam S. Bolton\n Creative Commons Attribution-Noncommercial-ShareAlike 3.0 license applies:\n http://creativecommons.org/licenses/by-nc-sa/3.0/\n All redistributions, modified or otherwise, must include this\n original copyright notice, licensing statement, and disclaimer.\n DISCLAIMER: ABSOLUTELY NO WARRANTY EXPRESS OR IMPLIED.\n AUTHOR ASSUMES NO LIABILITY IN CONNECTION WITH THIS COMPUTER CODE.\n\n--------------------------\n USAGE\n\n python $PYSRC/uvmcmcfit2.py\n\n--------------------------\n SETUP PROCEDURES\n\n 1. Establish a directory that contains data for the specific target for which\n you wish to measure a lens model.  This is the directory from which you will\n run the software.\n\n I call this \"uvfit00\" for the first run on a given dataset, \"uvfit01\" for\n the second, etc.\n\n 2. Inside this directory, you must ensure the following files are present:\n\n - \"config.yaml\": This is the configuration file that describes where the source\n of interest is located, what type of model to use for the lens and source, the\n name of the image of the target from your interferometric data, the name of\n the uvfits files containing the interferometric visibilities, and a few\n important processing options as well.  Syntax is yaml.\n\n - Image of the target from your interferometric data.  The spatial resolution\n of this image (arcseconds per pixel), modified by an optional oversampling\n parameter, defines the spatial resolution in both the unlensed and lensed\n surface brightness maps.\n\n - interferometric visibilities for every combination of array configuration,\n sideband, and date observed that you want to model.\n\n 3. More info about the constraints and priors input files.\n\n - Lenses: The lenses are assumed to have singular isothermal ellipsoid\n profiles.\n\n - Sources: Sources are represented by Gaussian profiles.\n\n--------\n OUTPUTS\n\n \"posteriorpdf.fits\": model parameters for every MCMC iteration, in fits\n format.\n\n \"summary.txt\": contains mean acceptance fraction\n\n\"\"\"\n\nfrom __future__ import print_function\n\n# import the required modules\nimport os\nimport os.path\nimport sys\nfrom astropy.io import fits\nimport numpy\nfrom astropy.table import Table\nimport emcee\n#import pyximport\n#pyximport.install(setup_args={\"include_dirs\":numpy.get_include()})\nimport sample_vis\nimport lensutil\nimport uvutil\nimport setuputil\nimport yaml\nfrom subprocess import call\nimport time\n\n\n#cwd = os.getcwd()\n#sys.path.append(cwd)\n#import config\n\ndef lnprior(pzero_regions, paramSetup):\n\n    \"\"\"\n\n    Function that computes the ln prior probabilities of the model parameters.\n\n    \"\"\"\n    priorln = 0.0\n    mu = 1\n\n#     import pdb; pdb.set_trace()\n\n    # ensure all parameters are finite\n    if (pzero_regions * 0 != 0).any():\n        priorln = -numpy.inf\n        return priorln, mu\n\n    # Uniform priors\n    uniform_regions = paramSetup['PriorShape'] == 'Uniform'\n    if uniform_regions.any():\n        p_l_regions = paramSetup['p_l'][uniform_regions]\n        p_u_regions = paramSetup['p_u'][uniform_regions]\n        pzero_uniform = pzero_regions[uniform_regions]\n        if (pzero_uniform > p_l_regions).all() and (pzero_uniform < p_u_regions).all():\n            # log prior\n            priorln += numpy.log(1.0/numpy.abs(p_l_regions - p_u_regions)).sum()\n        else:\n            priorln = -numpy.inf\n            return priorln, mu\n\n    # Gaussian priors\n    gaussian_regions = paramSetup['PriorShape'] == 'Gaussian'\n    if gaussian_regions.any():\n        import scipy.stats as stats\n        # initlized as [mean, blah, blah, sigma]\n        mean_regions = paramSetup['p_l'][gaussian_regions]\n        rms_regions = paramSetup['p_u'][gaussian_regions]\n        pzero_gauss = pzero_regions[gaussian_regions]\n        priorln += numpy.log(stats.norm(scale=rms_regions, loc=mean_regions).pdf(pzero_gauss)).sum()\n\n    # Gaussian pos (for parameter that must be positive e.g. flux density)\n    gaussPos_regions = paramSetup['PriorShape'] == 'GaussianPos'\n    if gaussPos_regions.any():\n        pzero_gaussPos = pzero_regions[gaussPos_regions]\n        if pzero_gaussPos < 0.0:\n            priorln = -numpy.inf\n            return priorln, mu\n        else:\n            import scipy.stats as stats\n            # initlized as [mean, blah, blah, sigma]\n            mean_regions = paramSetup['p_l'][gaussPos_regions]\n            rms_regions = paramSetup['p_u'][gaussPos_regions]\n            priorln += numpy.log(stats.norm(scale=rms_regions, loc=mean_regions).pdf(pzero_gauss)).sum()\n\n#     if not isinstance(priorln, float):\n#         priorln = priorln.sum()\n    return priorln, mu\n\n\ndef lnlike(pzero_regions, vis_complex, wgt, uuu, vvv, pcd,\n           fixindx, paramSetup, computeamp=True, miriad=False):\n    \"\"\" Function that computes the Ln likelihood of the data\"\"\"\n\n    # search poff_models for parameters fixed relative to other parameters\n    fixindx = numpy.array(fixindx)\n    fixed = (numpy.where(fixindx >= 0))[0]\n    nfixed = fixindx[fixed].size\n    p_u_regions = paramSetup['p_u']\n    poff_regions = p_u_regions.copy()\n    poff_regions[:] = 0.\n    #for ifix in range(nfixed):\n    #    poff_regions[fixed[ifix]] = pzero_regions[fixindx[fixed[ifix]]]\n    for ifix in range(nfixed):\n        ifixed = int(fixed[ifix])\n        subindx = int(fixindx[ifixed])\n        par0 = 0\n        if fixindx[subindx] > 0:\n            par0 = pzero_regions[fixindx[subindx]]\n        poff_regions[ifixed] = pzero_regions[subindx] + par0\n\n    parameters_regions = pzero_regions + poff_regions\n\n    npar_previous = 0\n\n    amp = []  # Will contain the 'blobs' we compute\n    g_image_all = 0.\n    g_lensimage_all = 0.\n    e_image_all = 0.\n    e_lensimage_all = 0.\n\n    nregions = paramSetup['nregions']\n    for regioni in range(nregions):\n\n        # get the model info for this model\n        x = paramSetup['x'][regioni]\n        y = paramSetup['y'][regioni]\n        headmod = paramSetup['modelheader'][regioni]\n        nlens = paramSetup['nlens_regions'][regioni]\n        nsource = paramSetup['nsource_regions'][regioni]\n        model_types = paramSetup['model_types'][regioni]\n\n        # get pzero, p_u, and p_l for this specific model\n        nparlens = 5 * nlens\n        nparsource = 6 * nsource\n        npar = nparlens + nparsource + npar_previous\n        parameters = parameters_regions[npar_previous:npar]\n        npar_previous = npar\n\n        #-----------------------------------------------------------------\n        # Create a surface brightness map of lensed emission for the given set\n        # of foreground lens(es) and background source parameters.\n        #-----------------------------------------------------------------\n\n        g_image, g_lensimage, e_image, e_lensimage, amp_tot, amp_mask = \\\n                lensutil.sbmap(x, y, nlens, nsource, parameters, model_types,\n                computeamp=computeamp)\n        e_image_all += e_image\n        e_lensimage_all += e_lensimage\n        g_image_all += g_image\n        g_lensimage_all += g_lensimage\n        amp.extend(amp_tot)\n        amp.extend(amp_mask)\n\n        # --------------------------------------------------------------------\n        # Python version of UVMODEL:\n        # \"Observe\" the lensed emission with the interferometer\n        # --------------------------------------------------------------------\n\n        if nlens > 0:\n            if computeamp:\n                # Evaluate amplification for each region\n                lensmask = e_lensimage != 0\n                mask = e_image != 0\n                numer = g_lensimage[lensmask].sum()\n                denom = g_image[mask].sum()\n                amp_mask = numer / denom\n                numer = g_lensimage.sum()\n                denom = g_image.sum()\n                amp_tot = numer / denom\n                if amp_tot > 1e2:\n                    amp_tot = 1e2\n                if amp_mask > 1e2:\n                    amp_mask = 1e2\n                amp.extend([amp_tot])\n                amp.extend([amp_mask])\n            else:\n                amp.extend([1.0])\n                amp.extend([1.0])\n\n    if miriad:\n        # save the fits image of the lensed source\n        ptag = str(os.getpid())\n        SBmapLoc = 'LensedSBmap' + ptag + '.fits'\n        fits.writeto(SBmapLoc, g_lensimage_all, header=headmod, clobber=True)\n\n        # convert fits format to miriad format\n        SBmapMiriad = 'LensedSBmap' + ptag + '.miriad'\n        os.system('rm -rf ' + SBmapMiriad)\n        cmd = 'fits op=xyin in=' + SBmapLoc + ' out=' + SBmapMiriad\n        call(cmd + ' > /dev/null 2>&1', shell=True)\n\n        # compute simulated visibilities\n        modelvisfile = 'SimulatedVisibilities' + ptag + '.miriad'\n        call('rm -rf ' + modelvisfile, shell=True)\n        cmd = 'uvmodel options=subtract vis=' + visfilemiriad + \\\n                ' model=' + SBmapMiriad + ' out=' + modelvisfile\n        call(cmd + ' > /dev/null 2>&1', shell=True)\n\n        # convert simulated visibilities to uvfits format\n        mvuvfits = 'SimulatedVisibilities' + ptag + '.uvfits'\n        call('rm -rf ' + mvuvfits, shell=True)\n        cmd = 'fits op=uvout in=' + modelvisfile + ' out=' + mvuvfits\n        call(cmd + ' > /dev/null 2>&1', shell=True)\n\n        # read simulated visibilities\n        mvuv = fits.open(mvuvfits)\n        diff_real = mvuv[0].data['DATA'][:, 0, 0, 0, 0, 0]\n        diff_imag = mvuv[0].data['DATA'][:, 0, 0, 0, 0, 1]\n        wgt = mvuv[0].data['DATA'][:, 0, 0, 0, 0, 2]\n        #model_complex = model_real[goodvis] + 1.0j * model_imag[goodvis]\n        diff_all = numpy.append(diff_real, diff_imag)\n        wgt = numpy.append(wgt, wgt)\n        goodvis = wgt > 0\n        diff_all = diff_all[goodvis]\n        wgt = wgt[goodvis]\n        chi2_all = wgt * diff_all * diff_all\n    else:\n        model_complex = sample_vis.uvmodel(g_lensimage_all, headmod,\n                uuu, vvv, pcd)\n        diff_all = numpy.abs(vis_complex - model_complex)\n        chi2_all = wgt * diff_all * diff_all\n    #model_real += numpy.real(model_complex)\n    #model_imag += numpy.imag(model_complex)\n\n    #fits.writeto('g_lensimage.fits', g_lensimage_all, headmod, clobber=True)\n    #import matplotlib.pyplot as plt\n    #print(pzero_regions)\n    #plt.imshow(g_lensimage, origin='lower')\n    #plt.colorbar()\n    #plt.show()\n    #plt.imshow(g_image, origin='lower')\n    #plt.colorbar()\n    #plt.show()\n\n    # calculate chi^2 assuming natural weighting\n    #fnuisance = 0.0\n    #modvariance_real = 1 / wgt #+ fnuisance ** 2 * model_real ** 2\n    #modvariance_imag = 1 / wgt #+ fnuisance ** 2 * model_imag ** 2\n    #wgt = wgt / 4.\n    #chi2_real_all = (real - model_real) ** 2. / modvariance_real\n    #chi2_imag_all = (imag - model_imag) ** 2. / modvariance_imag\n    #chi2_all = numpy.append(chi2_real_all, chi2_imag_all)\n\n    # compute the sigma term\n    #sigmaterm_real = numpy.log(2 * numpy.pi / wgt)\n    #sigmaterm_imag = numpy.log(2 * numpy.pi * modvariance_imag)\n\n    # compute the ln likelihood\n    lnlikemethod = paramSetup['lnlikemethod']\n    if lnlikemethod == 'chi2':\n        lnlike = chi2_all\n    else:\n        # by definition, loglike = -n/2*ln(2pi sigma^2) - 1/(2sigma^2) sum of (data-model)^2 over i=1 to n; but the constant term doesn't matter\n        sigmaterm_all = len(wgt) * numpy.log(2 * numpy.pi / wgt)\n        lnlike = chi2_all   # + sigmaterm_all\n        # * -1/2 factor in latter step\n\n    # compute number of degrees of freedom\n    #nmeasure = lnlike.size\n    #nparam = (pzero != 0).size\n    #ndof = nmeasure - nparam\n\n    # assert that lnlike is equal to -1 * maximum likelihood estimate\n    # use visibilities where weight is greater than 0\n    #goodvis = wgt > 0\n    #likeln = -0.5 * lnlike[goodvis].sum()\n    likeln = -0.5 * lnlike.sum()\n    #print(pcd, likeln)\n    if likeln * 0 != 0:\n        likeln = -numpy.inf\n\n    return likeln, amp\n\ndef lnprob(pzero_regions, vis_complex, wgt, uuu, vvv, pcd,\n           fixindx, paramSetup, computeamp=True, miriad=False):\n\n    \"\"\"\n\n    Computes ln probabilities via ln prior + ln likelihood\n\n    \"\"\"\n\n    lp, mu = lnprior(pzero_regions, paramSetup)\n\n    if not numpy.isfinite(lp):\n        probln = -numpy.inf\n        mu = 1\n        return probln, mu\n\n    ll, mu = lnlike(pzero_regions, vis_complex, wgt, uuu, vvv, pcd,\n           fixindx, paramSetup, computeamp=computeamp, miriad=miriad)\n\n    normalization = 1.0#2 * real.size\n    probln = lp * normalization + ll\n#    print(probln, lp*normalization, ll)   # remove\n\n    return probln, mu\n\nconfigloc = 'config.yaml'\nconfigfile = open(configloc, 'r')\nconfig = yaml.load(configfile)\n\n\n# Determine if we are going to compute the amplification of every model\nif config.keys().count('ComputeAmp') > 0:\n    computeamp = config['ComputeAmp']\nelse:\n    computeamp = True\n\n# Determine parallel processing options\nif config.keys().count('MPI') > 0:\n    mpi = config['MPI']\nelse:\n    mpi = False\n\n# multiple processors on a cluster using MPI\nif mpi:\n\n    from emcee.utils import MPIPool\n\n    # One thread per slot\n    Nthreads = 1\n\n    # Initialize the pool object\n    pool = MPIPool()\n\n    # If this process is not running as master, wait for instructions, then exit\n    if not pool.is_master():\n        pool.wait()\n        sys.exit(0)\n\n# Single processor with Nthreads cores\nelse:\n\n    if config.keys().count('Nthreads') > 0:\n        # set the number of threads to use for parallel processing\n        Nthreads = config['Nthreads']\n    else:\n        Nthreads = 1\n\n    # Initialize the pool object\n    pool = ''\n\n#--------------------------------------------------------------------------\n# Read in ALMA image and beam\n#im = fits.getdata(config['ImageName'])\n#im = im[0, 0, :, :].copy()\nheadim = fits.getheader(config['ImageName'])\n\n# get resolution in ALMA image\n#celldata = numpy.abs(headim['CDELT1'] * 3600)\n\n#--------------------------------------------------------------------------\n# read in visibility data\nvisfile = config['UVData']\n\n# Determine if we will use miriad to compute simulated visibilities\nif config.keys().count('UseMiriad') > 0:\n    miriad = config['UseMiriad']\n\n    if miriad:\n        interactive = False\n        index = visfile.index('uvfits')\n        visfilemiriad = visfile[0:index] + 'miriad'\n\n        # scale the weights\n        newvisfile = visfile[0:index] + 'scaled.uvfits'\n        uvutil.scalewt(visfile, newvisfile)\n        visfile = newvisfile\n    else:\n        miriad = False\nelse:\n    miriad = False\n\n# attempt to process multiple visibility files.  This won't work if miriad=True\ntry:\n    filetype = visfile[-6:]\n    if filetype == 'uvfits':\n        uvfits = True\n    else:\n        uvfits = False\n    uuu, vvv, www = uvutil.uvload(visfile)\n    pcd = uvutil.pcdload(visfile)\n    vis_complex, wgt = uvutil.visload(visfile)\nexcept:\n    try:\n        for i, ivisfile in enumerate(visfile):\n            filetype = ivisfile[-6:]\n            if filetype == 'uvfits':\n                uvfits = True\n            else:\n                uvfits = False\n            iuuu, ivvv, iwww = uvutil.uvload(ivisfile)\n            ipcd = uvutil.pcdload(ivisfile)\n            ivis_complex, iwgt = uvutil.visload(ivisfile)\n            if i == 0:\n                uuu = iuuu\n                vvv = ivvv\n                pcd = ipcd\n                vis_complex = ivis_complex\n                wgt = iwgt\n            else:\n                uuu = numpy.append(uuu, iuuu)\n                vvv = numpy.append(vvv, ivvv)\n                if ipcd != pcd:\n                    data1 = visfile[0]\n                    data2 = visfile[ivisfile]\n                    msg = 'Phase centers in ' + data1 + ' and ' + data2 \\\n                            + ' do not match.  Please ensure phase ' \\\n                            + 'centers in all visibility datasets are equal.'\n                    print(msg)\n                    raise TypeError\n                vis_complex = numpy.append(vis_complex, ivis_complex)\n                wgt = numpy.append(wgt, iwgt)\n    except:\n        msg = \"Visibility datasets must be specified as either a string or \"\\\n                \"a list of strings.\"\n        print(msg)\n        raise TypeError\n\n\n# remove the data points with zero or negative weight\npositive_definite = wgt > 0\nassert len(positive_definite[positive_definite]) > 0, \" --- Find no data to fit, check the weights --- \"\nvis_complex = vis_complex[positive_definite]\nwgt = wgt[positive_definite]\nuuu = uuu[positive_definite]\nvvv = vvv[positive_definite]\n#www = www[positive_definite]\n\nnpos = wgt.size\n\n#----------------------------------------------------------------------------\n# Load input parameters\nparamSetup = setuputil.loadParams(config)\nnwalkers = paramSetup['nwalkers']\nnregions = paramSetup['nregions']\nnparams = paramSetup['nparams']\npname = paramSetup['pname']\nnsource_regions = paramSetup['nsource_regions']\n\n# Use an intermediate posterior PDF to initialize the walkers if it exists\nposteriorloc = 'posteriorpdf.fits'\nif os.path.exists(posteriorloc):\n\n    # read the latest posterior PDFs\n    print(\"Found existing posterior PDF file: {:s}\".format(posteriorloc))\n    posteriordat = Table.read(posteriorloc)\n    if len(posteriordat) > 1:\n\n        # assign values to pzero\n        nlnprob = 1\n        pzero = numpy.zeros((nwalkers, nparams))\n        startindx = nlnprob\n        for j in range(nparams):\n            namej = posteriordat.colnames[j + startindx]\n            pzero[:, j] = posteriordat[namej][-nwalkers:]\n\n        # number of mu measurements\n        nmu = len(posteriordat.colnames) - nparams - nlnprob\n\n        # output name is based on most recent burnin file name\n        realpdf = True\n    else:\n        realpdf = False\nelse:\n    realpdf = False\n\nif not realpdf:\n    extendedpname = ['lnprob']\n    extendedpname.extend(pname)\n    nmu = 0\n    for regioni in range(nregions):\n        ri = str(regioni)\n        if paramSetup['nlens_regions'][regioni] > 0:\n            nsource = nsource_regions[regioni]\n            for i in range(nsource):\n                si = '.Source' + str(i) + '.Region' + ri\n                extendedpname.append('mu_tot' + si)\n                nmu += 1\n            for i in range(nsource):\n                si = '.Source' + str(i) + '.Region' + ri\n                extendedpname.append('mu_aper' + si)\n                nmu += 1\n            extendedpname.append('mu_tot.Region' + ri)\n            extendedpname.append('mu_aper.Region' + ri)\n            nmu += 2\n    posteriordat = Table(names = extendedpname)\n    pzero = numpy.array(paramSetup['pzero'])\n\n# make sure no parts of pzero exceed p_u or p_l\n#arrayp_u = numpy.array(p_u)\n#arrayp_l = numpy.array(p_l)\n#for j in range(nwalkers):\n#    exceed = arraypzero[j] >= arrayp_u\n#    arraypzero[j, exceed] = 2 * arrayp_u[exceed] - arraypzero[j, exceed]\n#    exceed = arraypzero[j] <= arrayp_l\n#    arraypzero[j, exceed] = 2 * arrayp_l[exceed] - arraypzero[j, exceed]\n#pzero = arraypzero\n#p_u = arrayp_u\n#p_l = arrayp_l\n\n# determine the indices for fixed parameters\nfixindx = setuputil.fixParams(paramSetup)\nfixindx = map(int, fixindx)\n\n# Initialize the sampler with the chosen specs.\nif mpi:\n    sampler = emcee.EnsembleSampler(nwalkers, nparams, lnprob, pool=pool, \\\n        args=[vis_complex, wgt, uuu, vvv, pcd, \\\n        fixindx, paramSetup, computeamp, miriad])\nelse:\n    sampler = emcee.EnsembleSampler(nwalkers, nparams, lnprob, \\\n        args=[vis_complex, wgt, uuu, vvv, pcd, \\\n        fixindx, paramSetup, computeamp, miriad], threads=Nthreads)\n\n# Sample, outputting to a file\n#os.system('date')\ncurrenttime = time.time()\n\n# do burn-in if posteriorpdf.fits doesn't exist or contains any samples\n# But, it's difficult to judge how many steps is needed\n# need to may sure later that we are sampling longer than the AC time\nif not realpdf:\n    burnin = 150\n    print(\"*** Running Burn in phase of steps {:d} ***\".format(burnin))\n    try:\n        pos0, lnprob0, rstate0 = sampler.run_mcmc(pzero, burnin)\n    except ValueError:\n        pos0, lnprob0, rstate0, _ = sampler.run_mcmc(pzero, burnin)\n    sampler.reset()            # reset chain\nelse:\n    pos0 = pzero\n\n\nclass AlarmException(Exception):\n    pass\n\n\ndef alarmHandler(signum, frame):\n    raise AlarmException\n\n\ndef nonBlockingRawInput(prompt='', timeout=20, response='yes'):\n    '''\n\n    '''\n    import signal\n    signal.signal(signal.SIGALRM, alarmHandler)\n    signal.alarm(timeout)\n    try:\n        text = raw_input(prompt)\n        signal.alarm(0)\n        return text\n    except AlarmException:\n        print('\\nPrompt timeout. Continuing...')\n    signal.signal(signal.SIGALRM, signal.SIG_IGN)\n    return response\n\n\ndef query_yes_no(question, default=None):\n    \"\"\"Ask a yes/no question via raw_input() and return their answer.\n\n    \"question\" is a string that is presented to the user.\n    \"default\" is the presumed answer if the user just hits <Enter>.\n        It must be \"yes\" (the default), \"no\" or None (meaning\n        an answer is required of the user).\n\n    The \"answer\" return value is True for \"yes\" or False for \"no\".\n    \"\"\"\n\n    import sys\n    valid = {\"yes\": True, \"y\": True, \"ye\": True,\n             \"no\": False, \"n\": False}\n    if default is None:\n        prompt = \" [y/n] \"\n    elif default == \"yes\":\n        prompt = \" [Y/n] \"\n    elif default == \"no\":\n        prompt = \" [y/N] \"\n    else:\n        raise ValueError(\"invalid default answer: '%s'\" % default)\n\n    while True:\n        sys.stdout.write(question + prompt)\n        choice = raw_input().lower()\n        if default is not None and choice == '':\n            return valid[default]\n        elif choice in valid:\n            return valid[choice]\n        else:\n            sys.stdout.write(\"Please respond with 'yes' or 'no' \"\n                             \"(or 'y' or 'n').\\n\")\n#        sys.stdout.flush()\n\n\ndef email_self(msg, receiver='tleung@astro.cornell.edu'):\n\n    '''\n    Parameters\n    ----------\n    msg: str\n        in email\n\n    '''\n\n    import os\n\n    #email\n    SENDMAIL = \"/usr/sbin/sendmail\"\n    p = os.popen(\"%s -t\" % SENDMAIL, \"w\")\n    p.write(\"To: \"+receiver+\"\\n\")\n    p.write(\"Subject: uvmcmcfit needs a respond to continuue. \\n\")\n    p.write(\"\\n\")    # blank line separating headers from body\n\n    message = msg + \"\\n\\n\" + ' Continue?'\n\n    p.write(message)\n    sts = p.close()\n    if sts != 0:\n        print(\"Sendmail exit status {}\".format(sts))\n\n\nimport cPickle as pickle\nimport os\n# pos - A list of current positions of walkers in the parameter space; dim = (nwalkers, dim)\n# prob - The list of log posterior probabilities for the walkers at positions given by pos . The shape of this object is (nwalkers, dim).\n# state - the random number generator state\n# amp - metadata 'blobs' associated with the current positon\n\n# below for testing..\n# nsamples = 1000\n# nsessions = 2\n\n# in general, we want many samples.\n# niter & nsesions dep. on nwalkers\n#\nnsamples = 1e6\nniter = int(round(nsamples/nwalkers))\nnsessions = 10\nsaveint = niter/nsessions/3\n\nvalid = {\"yes\": True, \"y\": True, \"ye\": True,\n         \"no\": False, \"n\": False}\n\nfor i in range(nsessions):\n    saveidx = 0\n    for pos, prob, state, amp in sampler.sample(pos0, iterations=int(niter/nsessions)):\n    # using sampler.sample() will have pre-defined 0s in elements (cf. run_mcmc())\n        walkers, steps, dim = sampler.chain.shape\n        result = [\n            \"Mean Acceptance fraction across all walkers of this iteration: {:.2f}\".format(numpy.mean(sampler.acceptance_fraction)),\n            \"Mean lnprob and Max lnprob values: {:f} {:f}\".format(numpy.mean(prob), numpy.max(prob)),\n            \"Time to run previous set of walkers (seconds): {:f}\".format(time.time() - currenttime)\n                ]\n        print('\\n'.join(result))\n        f = open('summary.txt', 'a')\n        f.write('\\n'.join(result))\n        f.write('\\n')\n        f.close()\n\n        currenttime = time.time()\n        #ff.write(str(prob))\n\n        superpos = numpy.zeros(1 + nparams + nmu)\n        for wi in range(nwalkers):\n            superpos[0] = prob[wi]\n            superpos[1:nparams + 1] = pos[wi]\n            superpos[nparams + 1:nparams + nmu + 1] = amp[wi]\n            posteriordat.add_row(superpos)\n\n        # only save if it has went through every saveint iterations or is the last sample\n        if not sampler.chain[:, numpy.any(sampler.chain[0, :, :] != 0, axis=1), :].shape[1] % saveint or (sampler.chain[:, numpy.any(sampler.chain[0, :, :] != 0, axis=1), :].shape[1] == int(niter/nsessions)):\n            print(\"Ran {:d} iterations in this session. Saving data\".format(sampler.chain[:, numpy.any(sampler.chain[0, :, :] != 0, axis=1), :].shape[1]))\n            posteriordat.write('posteriorpdf.fits', overwrite=True)\n            #posteriordat.write('posteriorpdf.txt', format='ascii')\n\n            saveidx = sampler.chain[:, numpy.any(sampler.chain[0, :, :] != 0, axis=1), :].shape[1]\n\n    message = \"We have finished {:d} iterations with {:d} walkers. \".format(sampler.chain[:, numpy.any(sampler.chain[0, :, :] != 0, axis=1), :].shape[1], nwalkers)\n\n    if i < nsessions-1:\n        email_self(message)\n        print(message)\n        ret = nonBlockingRawInput(\"Shall we continuue with next session? (Y/N)\", timeout=600).lower()\n\n        while not ret in valid:\n            print(\"Please respond with 'yes' or 'no' (or 'y' or 'n').\\n\")\n            ret = nonBlockingRawInput(\"Shall we continuue with next session? (Y/N)\", timeout=600).lower()\n        if not valid[ret]:\n            import sys\n            sys.exit(\"Quiting... \")\n            if mpi: pool.close()\n\n    sampler.reset()\n    pos0 = pos\n\nf = open('summary.txt', 'a')\nf.write(\"Finish all {:d} sessions \\n\".format(nsessions))\nf.write(\"Total number of samples: {:d} \\n\".format(niter/nsessions * nsessions * nwalkers))\nf.write('\\n')\nf.close()\n\nif mpi: pool.close()\n", "meta": {"hexsha": "68489e280c0bc3761abf8af4b0938c52ace2851f", "size": 26614, "ext": "py", "lang": "Python", "max_stars_repo_path": "uvmcmcfit.py", "max_stars_repo_name": "astro313/uvmcmcfit", "max_stars_repo_head_hexsha": "bab33afa289ead2868bd6efc4caa035b9acd0b0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "uvmcmcfit.py", "max_issues_repo_name": "astro313/uvmcmcfit", "max_issues_repo_head_hexsha": "bab33afa289ead2868bd6efc4caa035b9acd0b0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "uvmcmcfit.py", "max_forks_repo_name": "astro313/uvmcmcfit", "max_forks_repo_head_hexsha": "bab33afa289ead2868bd6efc4caa035b9acd0b0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1205128205, "max_line_length": 208, "alphanum_fraction": 0.6182836101, "include": true, "reason": "import numpy,import scipy,from astropy", "num_tokens": 6969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.17966914988070495}}
{"text": "import time\nfrom collections import deque\nimport cupy as cp\nimport copy\nimport multiprocessing\nimport cupyx.scipy.ndimage\nimport cupyx.scipy.fftpack as scipyfftpack\nimport numpy as np\nimport prysm\nfrom scipy import interpolate, ndimage, fftpack, optimize, signal\nimport matplotlib.pyplot as plt\n\nfrom lentil import wavefront_config__old as conf\nfrom lentil.wavefront_config__old import SPACIAL_FREQS, BASE_WAVELENGTH, MODEL_WVLS, DEFAULT_SAMPLES\nfrom lentil.constants_utils import *\n\n\nzcache = prysm.zernike.zcache.regular\ncupyzcache = {}\nnumpyzcache_arrays = {}\ncupyzcache_arrays = {}\ncache_idx = {}\ncache_idx[\"cp\"] = None\ncache_idx[\"np\"] = None\nwindow_cache = {}\n\nall_but_z4_and_z9_phasecache = dict(np={}, cp={})\n\nRETURN_MTF = 1\nRETURN_OTF = 2\nRETURN_LSF = 3\nRETURN_PSF = 4\nRETURN_WITH_PROCESSING_DETAILS = 5\n\nsettings_cache = {}\n\nmask_cache = deque(maxlen=conf.MASK_CACHE_SIZE)\n\ndeltas = np.linspace(-1,1, 19) * 1e-12\na = np.random.random((256, 256))\npsf_size = 256\nmses = []\nfor d in deltas:\n    normshift_x = d\n    normshift_y = 0\n    zoom_factor = 1.0000\n    transform = np.array(((1.0 / zoom_factor, 0), (0, 1.0 / zoom_factor)))\n    offset_x = (psf_size - 1 + 1) / 2 * (1.0 - 1.0 / zoom_factor - normshift_x)\n    offset_y = (psf_size - 1 + 1) / 2 * (1.0 - 1.0 / zoom_factor - normshift_y)\n    order = conf.PSF_SPLINE_ORDER\n    zoomed_mono_psf = ndimage.affine_transform(a, transform, (offset_y, offset_x),\n                                       order=order)\n    mses.append(((zoomed_mono_psf - a)**2).sum())\n    print(d, mses[-1])\n\n# plt.plot(deltas, mses)\n# plt.show()\n# exit()\nclass TestSettings:\n    def __init__(self, defocus, p):\n        self.defocus = defocus\n        self.p = p\n        self.mono = False\n        self.plot = False\n        self.dummy = False\n        self.allow_cuda = conf.USE_CUDA\n        self.id_or_hash = 0\n        self.strehl_estimate = 1.0\n        self.fftsize = None\n        self.phasesamples = None\n        self.return_otf = True\n        self.return_otf_mtf = False\n        self.return_psf = False\n        self.return_prysm_mtf = False\n        self.return_mask = False\n        self.mask = None\n        self.prysm_mtf = None\n        self.cpu_gpu_arraysize_boundary = conf.CPU_GPU_ARRAYSIZE_BOUNDARY\n        self.effective_q = None\n        self.guide_mtf = None\n        self.q_autosize_scalar = conf.Q_AUTOSIZE_SCALAR\n        self.phase_autosize_scalar = conf.PHASE_AUTOSIZE_SCALAR\n        self.cache_sizes = True\n        self.x_loc = IMAGE_WIDTH / 2\n        self.y_loc = IMAGE_HEIGHT / 2\n        self.pixel_vignetting = True\n        self.lens_vignetting = True\n        self.default_exit_pupil_position_mm = 100\n        self.exif = None\n        self.fix_pupil_rotation = True\n\n    @property\n    def fftshape(self):\n        if self.fftsize is None:\n            return None\n        return self.fftsize, self.fftsize\n\n    @property\n    def phaseshape(self):\n        if self.phasesamples is None:\n            return None\n        return self.phasesamples, self.phasesamples\n\n    @property\n    def is_valid(self):\n        if self.fftsize is None:\n            return False\n        if self.phasesamples is None:\n            return False\n        if self.p is None:\n            return False\n        if self.defocus is None:\n            return False\n        return True\n\n    def get_processing_details(self):\n        get_processing_details(self)\n        return self\n\n\nclass TestResults:\n    def __init__(self):\n        self.lsf = None\n        self.psf = None\n        self.otf = None\n        self.timings = None\n        self.strehl = None\n        self.fftsize = None\n        self.samples = None\n        self.id_or_hash = None\n        self.used_cuda = None\n\n    def copy_important_settings(self, s: TestSettings):\n        self.fftsize = s.fftsize\n        self.samples = s.phasesamples\n        self.id_or_hash = s.id_or_hash\n\n    def get_mtf(self):\n        return abs(self.otf[0]), abs(self.otf[1])\n\n\ndef zoom(inarr, xfactor=1.0, yfactor=1.0, xoffset=0.0, yoffset=0.0, affine_transform=ndimage.affine_transform, me=np):\n    shape = inarr.shape\n    transform = me.array(((1.0 / yfactor, 0), (0, 1.0 / xfactor)))\n    offset_x = (shape[0]) / 2 * (1.0 - 1.0 / xfactor) - xoffset / xfactor\n    offset_y = (shape[1]) / 2 * (1.0 - 1.0 / yfactor) - yoffset / yfactor\n    if me is cp:\n        return affine_transform(inarr, transform, (offset_y, offset_x),\n                                           order=1)\n    else:\n        real = affine_transform(inarr.real, transform, (offset_y, offset_x),\n                                           order=conf.PSF_SPLINE_ORDER)\n        imag = affine_transform(inarr.imag, transform, (offset_y, offset_x),\n                                           order=conf.PSF_SPLINE_ORDER)\n        return real + 1j * imag\n\n\ndef get_z9(p, modelwavelength):\n    rel_wv = modelwavelength / BASE_WAVELENGTH\n    spca = p.get('spca', 0.0) * 30\n    spca2 = p.get('spca2', 0.0) * 30\n\n    spcaz9 = (modelwavelength / BASE_WAVELENGTH - 1.0) * spca + spca * 0.028\n    spca2z9 = (rel_wv - 1.0) ** 2 * spca2 * 10 - spca2 * 0.06\n    return (p.get('z9', 0.0) + spcaz9 + spca2z9) * conf.BASE_WAVELENGTH\n\n\ndef get_z4(defocus, p, modelwavelength):\n    fstop_base_ratio = p['fstop'] / p['base_fstop']\n    rel_wv = modelwavelength / BASE_WAVELENGTH\n    loca = p.get('loca', 0.0) * 30\n    loca1 = p.get('loca1', 0.0) * 30\n\n    locadefocus = (rel_wv - 1.0) ** 2 * 10 * loca - loca * 0.06\n    loca1defocus = (rel_wv - 1.0) * 1 * loca1 + loca1 * 0.027\n    base_z4 = ((defocus - p.get('df_offset', 0)) * p.get('df_step', 1)) * fstop_base_ratio ** 2\n    # print(p)\n    return -(base_z4 - locadefocus - loca1defocus) * conf.BASE_WAVELENGTH\n\n\ndef get_lca_shifts(s: TestSettings, modelwavelength, samplespacing):\n    rel_wv = modelwavelength / 0.54\n\n    img_height = calc_image_height(s.x_loc, s.y_loc)\n\n    px = s.p.get('tca_slr', 0.0) * 1e2 * img_height\n    py = 0\n\n    shiftx = (rel_wv - 1.0) ** 2 * px * 10 - px / 14\n    shifty = (rel_wv - 1.0) ** 2 * py * 10 - py / 14\n    return shiftx / samplespacing / s.fftsize, shifty / samplespacing / s.fftsize\n\n\nstrehl_estimate_cache = None\nmtf_cache = None\nreturn_cache = None\n\n\ndef get_used_zernikes(iterable, cache=True, me=np):\n    max = 0\n    arr = me.zeros(48, dtype=\"int\")\n    idx = me.zeros(48, dtype=\"int\") - 1\n    used = []\n    count = 0\n    for item in iterable:\n        if item[0].lower() == \"z\" and item[1].isdigit():\n            print(item)\n            zn = int(item[1:])\n            arr[zn - 1] = 1\n            if (zn) > max:\n                max = zn\n            idx[zn - 1] = count\n            count += 1\n            used.append(zn)\n    arr[3] = 1\n    print(arr, max, idx, 99)\n    return arr, max, idx, used\n\n\ndef get_processing_details(s: TestSettings):\n    if s.id_or_hash is not None and s.id_or_hash in settings_cache:\n        stup = settings_cache[s.id_or_hash]\n        if s.fftsize is None:\n            s.fftsize = stup[0]\n        if s.phasesamples is None:\n            s.phasesamples = stup[1]\n        if s.effective_q is None:\n            s.effective_q = stup[2]\n        s.allow_cuda = s.allow_cuda and s.fftsize > s.cpu_gpu_arraysize_boundary\n        return s\n\n    # if s.return_type == RETURN_LSF:\n    #     s.fftsize = 128\n    #     s.phasesamples = 64\n    #     s.effective_q = 2\n    #     return s\n\n    minimum_q = np.clip((s.strehl_estimate * 4) * s.q_autosize_scalar, 2, 3)\n    # minimum_q = np.clip((0.5 + s.strehl_estimate * 3.5) * s.q_autosize_scalar, 1.0, 5)\n    min_samples = -np.inf\n    f_stopped_down = s.p['fstop'] / s.p['base_fstop']\n    if s.guide_mtf is None:\n        min_samples = 384\n    else:\n        for otf in s.guide_mtf:\n            freqs = np.arange(0, 65) / 64\n            zero_plus_spacial_freqs = np.concatenate(([0], SPACIAL_FREQS, [1.0, 2.0]))\n            interpotf_real = interpolate.InterpolatedUnivariateSpline(zero_plus_spacial_freqs, np.concatenate(([1.0], otf.real, [0,0])), k=2)(freqs)\n            interpotf_imag = interpolate.InterpolatedUnivariateSpline(zero_plus_spacial_freqs, np.concatenate(([1.0], otf.imag, [0,0])), k=2)(freqs)\n            interpotf = interpotf_real + 1j * interpotf_imag\n            fftin = np.concatenate((interpotf[:-1], np.flip(interpotf[1:])))\n            lsfshifted = np.abs(fftpack.ifft(fftin))\n            lsfmax = np.maximum(lsfshifted[:64], np.flip(lsfshifted[64:]))\n            lsfmax /= lsfmax.max()\n\n            fitweights = np.clip((0.1 - lsfmax)*25, 0, 0.999) ** 4\n            fitweights = (0.01 < lsfmax) * (lsfmax < 0.12)\n            x_arr = np.arange(len(lsfmax))\n\n            def cost(params, return_curve=False):\n                a, b = params\n                c = 0\n                expcurve = b * np.exp(-0.1 * a * x_arr) + c\n                if return_curve:\n                    return expcurve\n                return ((lsfmax - expcurve) ** 2 * fitweights).mean()\n\n            a, b = optimize.minimize(cost, (1.0, 1.0,), bounds=((0.01, 70), (0.1, 30),)).x\n            c = 0\n            cutoff = 0.03\n\n            needed_width = -10 / a * np.log((cutoff - c) / b)\n\n            # plt.plot(cost((a, b), return_curve=True), label=\"fit\")\n            # plt.plot(lsfshifted / lsfshifted.max(), label=\"lsfshifted\")\n            # plt.plot(fftin, label=\"fftin\")\n            # plt.plot(lsfmax, label=\"lsfmax\")\n            # plt.ylim(0, 1)\n            # plt.hlines([cutoff], 0, 64)\n            # plt.legend()\n            # plt.show()\n\n            min_samples_this_axis = needed_width * s.phase_autosize_scalar * 9\n            if min_samples_this_axis > min_samples:\n                min_samples = min_samples_this_axis\n    # min_samples = 64 + (1.0 - minmtf[3])**2 * 400\n\n    # samples = int(min_samples / 2 + 1) * 2\n\n    # for samples in CUDA_GOOD_FFT_SIZES: # limit sizes for cache reasons\n    #     if samples >= min_samples:\n    #         break\n    for power in range(4, 10):\n        samples = 2 ** power\n        if samples > min_samples:\n            break\n        samples = int((2 ** power * 1.5) / 2 + 0.5) * 2\n        if samples > min_samples:\n            break\n\n    effective_q_without_padding = f_stopped_down\n\n    min_fftsize = minimum_q * samples / effective_q_without_padding\n\n\n    for fftsize in (CUDA_GOOD_FFT_SIZES if s.allow_cuda else CPU_GOOD_FFT_SIZES):\n        if fftsize >= min_fftsize:\n            break\n\n    # s.allow_cuda = s.allow_cuda and (samples + fftsize) >= (s.cpu_gpu_arraysize_boundary / 2)\n    s.allow_cuda = s.allow_cuda and fftsize >= s.cpu_gpu_arraysize_boundary\n\n    effective_q = fftsize / samples * effective_q_without_padding\n\n    assert (fftsize - samples) % 2 == 0\n    assert fftsize % 2 == 0\n    assert samples % 2 == 0\n\n    if s.fftsize is None:\n        s.fftsize = fftsize\n    if s.phasesamples is None:\n        s.phasesamples = samples\n\n    s.effective_q = effective_q\n\n    if s.id_or_hash is not None:\n        settings_cache[s.id_or_hash] = fftsize, samples, effective_q\n\n    # s.fftsize = 1024\n    # s.phasesamples = 512\n\n    return s\n\n# s = TestSettings(0, dict(fstop=5.6, base_fstop=1.4))\n# s.phasesamples = 256\n# get_processing_details(s)\n# exit()\n\n\ndef try_wavefront(s: TestSettings):\n    global window_cache\n\n    orig_s = copy.copy(s)\n    orig_s.p = s.p.copy()\n    t = time.time()\n\n    tr = TestResults()\n    tr.copy_important_settings(s)\n    if s.id_or_hash == 1:\n        print(\"step\", s.p['df_step'])\n\n    if s.dummy:\n        return tr\n\n    if s.p['fstop'] < s.p['base_fstop']:\n        raise ValueError(\"Base_fstop must be wider (lower) than fstop {} < {}\".format(s.p['fstop'], s.p['base_fstop']))\n    mul = 1\n    mtfs = []\n    pupilslices = []\n    bestpupil = (np.inf, None, None)\n\n    if not s.is_valid:\n        s = get_processing_details(s)\n\n    use_cuda = s.allow_cuda\n    # prysm_path_q = 4\n    # s.fftsize = prysm_path_q * s.phasesamples\n    prysm_path_q = max(1, s.fftsize / s.phasesamples)\n\n\n    if use_cuda:\n        fft2 = cupyx.scipy.fftpack.fft2\n        fftpack = cupyx.scipy.fftpack\n        affine_transform = cupyx.scipy.ndimage.affine_transform\n        # affine_transform = ndimage.affine_transform\n    else:\n        fft2 = scipyfftpack.fft2\n        fftpack = scipyfftpack\n        affine_transform = ndimage.affine_transform\n\n    tr.used_cuda = use_cuda\n\n    SAM_RADIOMETRIC_MODEL = True\n\n    USE_PSF = False\n\n    # cudadevice = cp.cuda.Device(0)\n\n    def sync():\n        pass\n        # if use_cuda:\n        #     cudadevice.synchronize()\n\n    realdtype = \"float32\" if conf.PRECISION == 32 else \"float64\"\n    complexdtype = \"complex64\" if conf.PRECISION == 32 else \"complex128\"\n\n    me, engine_string = (cp, 'np') if use_cuda else (np, 'np')\n\n    eval_wavelengths = [BASE_WAVELENGTH] if s.mono else MODEL_WVLS\n    # eval_wavelengths = [BASE_WAVELENGTH] if s.mono else [0.5, 0.9]\n\n    # s.p['loca'] *= 0.1\n    # s.p['loca1'] *= 0.1\n    # s.p['spca2'] *= 0.1\n    # s.p['spca'] *= 0.1\n    # s.p['tca_slr'] = 0\n    if s.return_psf or USE_PSF or s.return_prysm_mtf:\n        mono_psf_stack = me.zeros(s.fftshape, dtype=\"float64\")\n\n    psf_sag = np.zeros((s.fftsize, ), dtype=\"float64\")\n    psf_tan = np.zeros((s.fftsize, ), dtype=\"float64\")\n    psf_lst = []\n    samplelst = []\n\n    polychromatic_weights = np.array([float(photopic_fn(wv * 1e3) * d50_interpolator(wv)) for wv in eval_wavelengths])\n    # polychromatic_weights **= 2\n    # polychromatic_weights = me.array([0.5, 0.5])\n\n    t_misc = 0\n    t_pupils = 0\n    t_get_phases = 0\n    t_get_fcns = 0\n    t_fcntransforms = 0\n    t_pads = 0\n    t_ffts = 0\n    t_cudasyncs = 0\n    t_affines = 0\n    t_mtfs = 0\n    t_init = time.time() - t\n    t = time.time()\n\n    mask = mask_pupil(s, engine=me, dtype=realdtype)\n\n    if s.return_mask:\n        tr.mask = mask\n\n    t_maskmaking = time.time() - t\n\n    used_zernikes_flags, max_zernike, cache_idx_, used_zernikes = get_used_zernikes(s.p.keys())\n\n    if cache_idx[engine_string] is not None:\n        if not me.all(cache_idx[engine_string] == cache_idx_):\n            raise Exception(\"Zernicke cache does not match P dict\")\n    else:\n        cache_idx[engine_string] = cache_idx_\n\n    zkwargs = {}\n    for key, value in s.p.items():\n\n        # if key.upper() == 'Z9':\n        #     zkwargs[key] = z9\n        #     continue\n        # if key.upper() == 'Z4':\n        #     raise ValueError(\"No Z4 separately!\")\n        if key.lower().startswith('z') and key[1].isdigit():\n            # if key not in ['z9', 'z16', 'z25', 'z36']:\n            #     continue\n            zkwargs[key] = value * mul * conf.BASE_WAVELENGTH\n\n    z_arr_no_z4_z9 = np.zeros(used_zernikes_flags.sum(), dtype=realdtype)\n    for key, value in zkwargs.items():\n        idx = cache_idx['np'][int(key[1:]) - 1]\n        z_arr_no_z4_z9[idx] = value\n    z_arr_no_z4_z9[cache_idx[engine_string][3]] = 0\n    z_arr_no_z4_z9[cache_idx[engine_string][8]] = 0\n    print(zkwargs)\n    print(zkwargs)\n    print(zkwargs)\n    print(zkwargs)\n    print(z_arr_no_z4_z9)\n    print(z_arr_no_z4_z9)\n    print(z_arr_no_z4_z9)\n    print(z_arr_no_z4_z9)\n    print(z_arr_no_z4_z9)\n    print(z_arr_no_z4_z9)\n    print(z_arr_no_z4_z9)\n    zhash = hash(tuple(z_arr_no_z4_z9))\n\n    if me is not np:\n        z_arr_no_z4_z9 = me.array(z_arr_no_z4_z9, dtype=realdtype)\n\n    if me is cp:\n        # cache = cupyzcache\n        cache_array = cupyzcache_arrays\n    else:\n        # cache = zcache\n        cache_array = numpyzcache_arrays\n\n    for wvl_num, (model_wvl, polych_weight) in enumerate(zip(eval_wavelengths, polychromatic_weights)):\n        t = time.time()\n        rel_wv = model_wvl / BASE_WAVELENGTH\n\n        z4 = get_z4(s.defocus, s.p, model_wvl)\n        z9 = get_z9(s.p, model_wvl)\n\n        samplelst.append(s.phasesamples)\n        t_misc += time.time() - t\n        if s.phasesamples not in cache_array:\n            t = time.time()\n            if s.phasesamples not in zcache:\n                pupil = prysm.FringeZernike(used_zernikes_flags,\n                                            dia=10, norm=False,\n                                            wavelength=model_wvl,\n                                            opd_unit=\"um\",\n                                            mask_target='none',\n                                            samples=s.phasesamples, )  # This is just here to fill the coeff cache\n            t_pupils += time.time() - t\n            t = time.time()\n\n            # if me is cp:\n            #     cache[s.phasesamples] = {}\n            cache_array[s.phasesamples] = me.empty((s.phasesamples, s.phasesamples, used_zernikes_flags.sum()), dtype=realdtype)\n            # cache_array[s.phasesamples] = 1\n\n            # for key, val in cache[s.phasesamples].items():\n            if 1:\n                idx = cache_idx['np'][key]\n                # if me is cp:\n                #     cache[s.phasesamples][key] = me.array(val)\n                cache_array[s.phasesamples][:, :, idx] = me.array(val, dtype=realdtype)\n\n                cache_idx[key] = idx\n            print(\"graaagl\")\n\n            sync()\n            t_get_phases += time.time() - t\n        t = time.time()\n        pupil = prysm.FringeZernike(dia=10, wavelength=model_wvl, norm=False,\n                                    opd_unit=\"um\",\n                                    mask_target='none',\n                                    samples=s.phasesamples, )\n        t_pupils += time.time() - t\n        t = time.time()\n\n        if s.phasesamples not in all_but_z4_and_z9_phasecache[engine_string] or \\\n                all_but_z4_and_z9_phasecache[engine_string][s.phasesamples][0] != zhash:\n            all_but_z4_and_z9_phasecache[engine_string][s.phasesamples] = zhash, cache_array[s.phasesamples] @ z_arr_no_z4_z9\n\n        if me is cp:\n            phase = cache_array[s.phasesamples][:, :, 3] * z4\n            phase += all_but_z4_and_z9_phasecache[engine_string][s.phasesamples][1]\n            phase += cache_array[s.phasesamples][:, :, 8] * z9\n        else:\n            # print(cache)\n            phase = cache[s.phasesamples][3] * z4\n            phase += all_but_z4_and_z9_phasecache[engine_string][s.phasesamples][1]\n            phase += cache[s.phasesamples][8] * z9\n        phase /= model_wvl\n        sync()\n        t_get_phases += time.time() - t\n\n        t = time.time()\n        # phase = me.array(pupil.change_phase_unit(to='waves', inplace=False),\n        #                  dtype=realdtype)\n        # phase = me.zeros((samples, samples), dtype=realdtype)\n        wavefunction = me.exp(1j * 2 * me.pi * phase)\n        wavefunction *= mask\n\n\n        # if me is cp:\n        #     plt.imshow(cp.asnumpy(me.angle(wavefunction)))\n        #     plt.show()\n        # else:\n        #     plt.imshow(me.angle(wavefunction))\n        #     plt.show()\n        sync()\n        t_get_fcns += time.time() - t\n\n        if model_wvl == min(eval_wavelengths):\n            if s.plot:\n                mono_psf = prysm.PSF.from_pupil(pupil, efl=s.p['base_fstop'] * 10, Q=prysm_path_q)\n\n            # psf_x_units, psf_y_units = prysm.propagation.prop_pupil_plane_to_psf_plane_units(wavefunction,\n            #                                                              pupil.sample_spacing,\n            #                                                              s.p['base_fstop'] * 10, model_wvl,\n            #                                                              prysm_path_q)\n\n            psf_sample_spacing = prysm.propagation.pupil_sample_to_psf_sample(pupil_sample=pupil.sample_spacing,\n                                                          samples=s.fftsize,\n                                                          wavelength=model_wvl,\n                                                          efl=s.p['base_fstop'] * 10) * 1e-3\n            psf_units = np.arange(-s.fftsize / 2, s.fftsize / 2) * psf_sample_spacing\n\n\n        padpx = int((s.fftsize - s.phasesamples) / 2)\n\n        ellip = s.p.get('ellip', 0)\n        if ellip == 0:\n            ellip = None\n        else:\n            xellip = np.clip(1 + ellip, 0.5, 1.0)\n            yellip = np.clip(1.0 - ellip, 0.5, 1.0)\n\n        if padpx > 0:\n            pt = padpx, padpx\n            if conf.ENABLE_PUPIL_DISTORTION and ellip is not None:\n                t = time.time()\n                wavefunction = zoom(wavefunction, xellip, yellip, affine_transform=affine_transform, me=me)\n                t_fcntransforms += time.time() - t\n            t = time.time()\n            padded_cropped_pupil_fcn = me.pad(me.array(wavefunction, dtype=complexdtype), (pt, pt), mode=\"constant\")\n            t_pads += time.time() - t\n        elif padpx < 0:\n            t = time.time()\n            padded_cropped_pupil_fcn = me.array(wavefunction[-padpx:-padpx+s.fftsize, -padpx:-padpx+s.fftsize], dtype=complexdtype)\n            t_pads += time.time() - t\n            if conf.ENABLE_PUPIL_DISTORTION and ellip is not None:\n                t = time.time()\n                padded_cropped_pupil_fcn = zoom(padded_cropped_pupil_fcn, xellip, yellip, affine_transform=affine_transform, me=me)\n                t_fcntransforms += time.time() - t\n\n        else:\n            # padded_cropped_pupil_fcn = me.array(wavefunction, dtype=complexdtype)\n            padded_cropped_pupil_fcn = wavefunction\n            if conf.ENABLE_PUPIL_DISTORTION and ellip is not None:\n                t = time.time()\n                padded_cropped_pupil_fcn = zoom(padded_cropped_pupil_fcn, xellip, yellip, affine_transform=affine_transform, me=me)\n                t_fcntransforms += time.time() - t\n        t = time.time()\n        pad = me.fft.fftshift(padded_cropped_pupil_fcn)\n        sync()\n        t_pads += time.time() - t\n        t = time.time()\n\n        # pad = me.fft.fft2(pad, norm='ortho')\n        pad = fft2(pad, overwrite_x=True)\n        shifted = me.fft.ifftshift(pad)\n        impulse_response = me.absolute(shifted)\n        impulse_response **= 2\n        if not SAM_RADIOMETRIC_MODEL:\n            impulse_response /= impulse_response.sum()\n        impx = impulse_response.sum(axis=1)\n        impy = impulse_response.sum(axis=0)\n\n        sync()\n        t_ffts += time.time() - t\n\n        psf_size = impulse_response.shape[0]\n\n        zoom_factor = float(np.clip(model_wvl / min(eval_wavelengths), 1.00001, np.inf))\n        normshift_x, normshift_y = get_lca_shifts(s, model_wvl, psf_sample_spacing)\n\n        if s.return_psf or USE_PSF:\n            t = time.time()\n            transform = me.array(((1.0 / zoom_factor, 0), (0, 1.0 / zoom_factor)))\n            offset_x = (psf_size - 1 + 1) / 2 * (1.0 - 1.0 / zoom_factor - normshift_x)\n            offset_y = (psf_size - 1 + 1) / 2 * (1.0 - 1.0 / zoom_factor - normshift_y)\n            if use_cuda:\n                order = 1\n            else:\n                order = conf.PSF_SPLINE_ORDER\n            zoomed_mono_psf = affine_transform(impulse_response, transform, (offset_y, offset_x),\n                                               order=order)\n            if SAM_RADIOMETRIC_MODEL:\n                zoomed_mono_psf *= polych_weight / zoomed_mono_psf.sum()\n            else:\n                zoomed_mono_psf *= polych_weight\n            mono_psf_stack += zoomed_mono_psf\n            sync()\n            t_affines += time.time() - t\n        # else:\n        if 1:\n            t = time.time()\n            if me is cp:\n                impx = cp.asnumpy(impx)\n                impy = cp.asnumpy(impy)\n            sync()\n            t_cudasyncs += time.time() - t\n\n            t = time.time()\n            transform = np.array((1.0 / zoom_factor,))\n\n            offset_x = (psf_size - 1 + 1) / 2 * (1.0 - 1.0 / zoom_factor - normshift_x)\n            offset_y = (psf_size - 1 + 1) / 2 * (1.0 - 1.0 / zoom_factor - normshift_y)\n\n            # impx /= impx.sum()\n            # impy /= impy.sum()\n\n            zoomx = ndimage.affine_transform(impx, transform, offset_x, order=conf.PSF_SPLINE_ORDER)\n            zoomy = ndimage.affine_transform(impy, transform, offset_y, order=conf.PSF_SPLINE_ORDER)\n\n            # zoomx = zoomed_mono_psf.mean(axis=0)\n            # zoomy = zoomed_mono_psf.mean(axis=1)\n\n            # plt.plot(zoomx / zoomx.max())\n            # plt.plot(zoomx_ / zoomx_.max())\n            # plt.show()\n\n            # plt.plot(zoomy / zoomy.max())\n            # plt.plot(zoomy_ / zoomy_.max())\n            # plt.show()\n\n\n            # print(model_wvl, s.id_or_hash)\n            # plt.plot(psf_units, zoomx)\n            # plt.plot(psf_units, zoomy)\n            # plt.plot(psf_units, impx)\n            # plt.plot(psf_units, impy)\n            # plt.show()\n\n            mul = 1.0 * zoom_factor\n            # mul = 1\n\n            if SAM_RADIOMETRIC_MODEL:\n                # pass\n                psf_sag += zoomx / zoomx.sum() * polych_weight\n                psf_tan += zoomy / zoomy.sum() * polych_weight\n            else:\n                psf_sag += zoomx * polych_weight * mul\n                psf_tan += zoomy * polych_weight * mul\n            sync()\n            t_affines += time.time() - t\n\n        if s.plot:\n            psf_lst.append(mono_psf)\n\n        pupilslices.append(pupil.slice_x[1])\n\n        metric = np.abs(rel_wv - 1)\n        if metric < bestpupil[0]:\n            bestpupil = metric, pupil, model_wvl, zkwargs\n\n    t = time.time()\n\n    if USE_PSF:\n        psf_sag = mono_psf_stack.sum(axis=1)\n        psf_tan = mono_psf_stack.sum(axis=0)\n        if me is cp:\n            psf_sag = cp.asnumpy(psf_sag)\n            psf_tan = cp.asnumpy(psf_tan)\n        # plt.plot(psf_sag / psf_sag.mean())\n        # plt.plot(psf_sag_ / psf_sag_.mean())\n        # plt.plot(((psf_sag / psf_sag.mean()) / (psf_sag_ / psf_sag_.mean()))[192:256+64])\n        # plt.show()\n    # ref_tr = _try_wavefront_prysmref(orig_s)\n\n    if s.return_psf or s.return_prysm_mtf:\n        npunits = cp.asnumpy(psf_units)\n        prysm_psf = prysm.PSF(x=npunits, y=npunits, data=cp.asnumpy(mono_psf_stack))\n        tr.psf = prysm_psf\n        if 0:\n\n            psf3 = prysm.PSF(x=npunits, y=npunits, data=cp.asnumpy(mono_psf_stack))\n            psf2 = ref_tr.psf\n\n            prysm_psf.data /= prysm_psf.data.sum()\n            psf2.data /= psf2.data.sum()\n\n            # assert np.allclose(prysm_psf.data, psf2.data)\n            # assert np.allclose([prysm_psf.sample_spacing], [psf2.sample_spacing])\n            psfnorm = prysm_psf.data / prysm_psf.data.sum()\n            psf2norm = psf2.data / psf2.data.sum()\n            psf3.data = np.clip(psfnorm / psf2norm, 0.3, 3)\n            # print(psf3.data)\n            # psf3.data[0,0] = max(psfnorm.max(), psf2norm.max())\n            f, (a1, a2, a3) = plt.subplots(1, 3)\n\n            tr.psf = prysm_psf\n            prysm_psf.plot2d(axlim=18, ax=a1, fig=f)\n            psf2.plot2d(axlim=18, ax=a2, fig=f)\n            psf3.plot2d(axlim=18, ax=a3, fig=f)\n            plt.show()\n        # tr.otf = np.ones_like(SPACIAL_FREQS), np.ones_like(SPACIAL_FREQS)\n        # return tr\n\n    # plt.plot(psf_units, psf_sag / psf_sag.max()+ 0.1)\n    # plt.plot(psf_units, mono_psf_stack.mean(axis=0) / mono_psf_stack.mean(axis=0).max())\n    # plt.show()\n    # plt.plot(psf_units, psf_tan / psf_tan.max() + 0.1)\n    # plt.plot(psf_units, mono_psf_stack.mean(axis=1) / mono_psf_stack.mean(axis=1).max())\n    # plt.show()\n\n    # if s.return_type == RETURN_LSF:\n    #     lsf_sag = mono_psf_stack.sum(axis=0)\n    #     lsf_sag /= lsf_sag.max()\n    #     lsf_tan = mono_psf_stack.sum(axis=1)\n    #     lsf_tan /= lsf_tan.max()\n    #     tr.lsf = lsf_sag, lsf_tan\n    #     return tr\n\n    centre = s.fftsize // 2\n    mtf_x_units = prysm.fttools.forward_ft_unit(psf_sample_spacing * 1e-3, s.fftsize)\n    sag_x = mtf_x_units[centre:]\n    tan_x = mtf_x_units[centre:]\n\n    if 0:\n        if otf:\n            mtf = me.fft.fftshift(me.fft.fft2(me.fft.ifftshift(mixedpsf)))\n        # else:\n    # mtf = me.absolute(me.fft.fft2(mono_psf_stack))\n    # psf_y_units = prysm.fttools.forward_ft_unit((psf_x_units[1] - psf_x_units[0]) / 1e3, len(psf_y_units))\n    # mtf = mtf / np.abs(mtf[0, 0])\n    # sag_mod = mtf[0, :centre]\n    # tan_mod = mtf[:centre, 0]\n\n    # sag_mod = me.fft.fftshift(me.fft.fft(me.fft.ifftshift(psf_sag)))[centre:]\n    # tan_mod = me.fft.fftshift(me.fft.fft(me.fft.ifftshift(psf_tan)))[centre:]\n\n    # sag_mod /= np.abs(sag_mod)[0]\n    # tan_mod /= np.abs(tan_mod)[0]\n\n    mtf_mapper_fft_halfwindowsize_um = 16 * DEFAULT_PIXEL_SIZE * 1e6\n\n    tukeykey = (s.fftsize, psf_sample_spacing)\n    try:\n        tukey_window = window_cache[tukeykey]\n    except KeyError:\n        if len(window_cache) > 300:\n            window_cache = {}\n        tukey_window = tukey(psf_units / mtf_mapper_fft_halfwindowsize_um, 0.6)\n        window_cache[tukeykey] = tukey_window\n        # print(\"PSF size {}um\".format(psf_units[-1]*2), len(window_cache))\n\n    # tukey_window = np.ones_like(psf_sag)\n\n    # tukey_window = get_window(s.fftsize, psf_sample_spacing)\n    # print(\"{:.3f} {:.3f}\".format(np.sum(psf_sag * psf_units) / psf_sag.sum(), np.sum(psf_tan * psf_units) / psf_tan.sum()))\n    sag_mod = normalised_centreing_fft(psf_sag * tukey_window, fftpack=scipyfftpack, engine=np)[:centre]\n    tan_mod = normalised_centreing_fft(psf_tan * tukey_window, fftpack=scipyfftpack, engine=np)[:centre]\n\n    # sag_mod = abs(fftpack.fft(np.fft.fftshift(psf_sag))[:centre])\n    # tan_mod = abs(fftpack.fft(np.fft.fftshift(psf_tan))[:centre])\n    # try:\n    #     sag_mod /= sag_mod[0]\n    # except FloatingPointError:\n    #     sag_mod = np.zeros(centre)\n    # try:\n    #     tan_mod /= tan_mod[0]\n    # except FloatingPointError:\n    #     tan_mod = np.zeros(centre)\n    # tan_mod /= tan_mod[0]\n\n    # ref_mtf = ref_tr._prysm_mtf\n    # (p_sag_x, p_sag_mod), (p_tan_x, p_tan_mod) = ref_mtf\n\n    # assert np.allclose(p_sag_mod, abs(sag_mod))\n    # assert np.allclose(p_tan_mod, abs(tan_mod))\n\n    # plt.plot(p_sag_x, p_sag_mod)\n    # plt.plot(sag_x, abs(sag_mod))\n    # plt.show()\n    # plt.plot(sag_x, abs(sag_mod) / p_sag_mod)\n    # plt.show()\n    # plt.plot(p_tan_x, p_tan_mod)\n    # plt.plot(tan_x, abs(tan_mod))\n    # plt.show()\n    # plt.plot(tan_x, abs(tan_mod) / p_tan_mod)\n    # plt.show()\n    if s.return_prysm_mtf:\n        prysm_mtf = prysm.MTF.from_psf(prysm_psf)\n        tr.prysm_mtf = prysm_mtf\n\n    if s.return_otf and s.return_otf_mtf:\n        interpfn = interpolate.InterpolatedUnivariateSpline(sag_x, np.abs(sag_mod), k=1)\n        sagmtf = interpfn(SPACIAL_FREQS / DEFAULT_PIXEL_SIZE * 1e-3)\n        interpfn = interpolate.InterpolatedUnivariateSpline(tan_x, np.abs(tan_mod), k=1)\n        tanmtf = interpfn(SPACIAL_FREQS / DEFAULT_PIXEL_SIZE * 1e-3)\n        tr.otf = sagmtf, tanmtf\n\n        # plt.plot(abs(tr.otf[0]))\n        # plt.plot(ref_tr.otf[0])\n        # plt.show()\n        # plt.plot(abs(tr.otf[1]))\n        # plt.plot(ref_tr.otf[1])\n        # plt.show()\n\n    if s.return_otf and not s.return_otf_mtf:\n        interpfn = interpolate.InterpolatedUnivariateSpline(sag_x, np.real(sag_mod), k=1)\n        sagmtf = interpfn(SPACIAL_FREQS / DEFAULT_PIXEL_SIZE * 1e-3)\n        interpfn = interpolate.InterpolatedUnivariateSpline(tan_x, np.real(tan_mod), k=1)\n        tanmtf = interpfn(SPACIAL_FREQS / DEFAULT_PIXEL_SIZE * 1e-3)\n        interpfn = interpolate.InterpolatedUnivariateSpline(sag_x, np.imag(sag_mod), k=1)\n        sagmtf_i = interpfn(SPACIAL_FREQS / DEFAULT_PIXEL_SIZE * 1e-3)\n        interpfn = interpolate.InterpolatedUnivariateSpline(tan_x, np.imag(tan_mod), k=1)\n        tanmtf_i = interpfn(SPACIAL_FREQS / DEFAULT_PIXEL_SIZE * 1e-3)\n        # sagmtf = sagmtf + sagmtf_i * 1j\n        # tanmtf = tanmtf + tanmtf_i * 1j\n\n        # Normalise phase somehow\n\n        # tr.otf = normalised_fft(sagmtf, sagmtf_i, SPACIAL_FREQS, inc_neg_freqs=False, return_type=COMPLEX_CARTESIAN), \\\n        #          normalised_fft(tanmtf, tanmtf_i, SPACIAL_FREQS, inc_neg_freqs=False, return_type=COMPLEX_CARTESIAN)\n\n        # if s.id_or_hash == 0:\n        #     normalised_fft(sagmtf, sagmtf_i, SPACIAL_FREQS, inc_neg_freqs=False,\n        #                    return_type=COMPLEX_CARTESIAN, plot=True)\n            # plt.plot(tuple(psf_sag))\n            # plt.plot(tuple(psf_tan))\n            # plt.show()\n            # plt.plot(sagmtf, color='red')\n            # plt.plot(tr.otf[0].real, '--', color='red')\n            # plt.plot(tanmtf, color='green')\n            # plt.plot(tr.otf[1].real, '--', color='green')\n            # plt.plot(sagmtf_i, color='orange')\n            # plt.plot(tr.otf[0].imag, '--', color='orange')\n            # plt.plot(tanmtf_i, color='blue')\n            # plt.plot(tr.otf[1].imag, '--', color='blue')\n            # plt.show()\n\n        tr.otf = sagmtf + 1j * sagmtf_i, tanmtf + 1j * tanmtf_i\n\n\n    sync()\n    t_mtfs += time.time() - t\n\n    timings = dict(t_init=t_init,\n                   t_maskmaking=t_maskmaking,\n                   t_pupils=t_pupils,\n                   t_get_phases=t_get_phases,\n                   t_get_fcns=t_get_fcns,\n                   t_fcntransforms=t_fcntransforms,\n                   t_pads=t_pads,\n                   t_ffts=t_ffts,\n                   t_cudasyncs=t_cudasyncs,\n                   t_affines=t_affines,\n                   t_mtfs=t_mtfs,\n                   t_misc=t_misc)\n\n    tr.timings = timings\n\n    sliceavg = me.average(me.array(pupilslices, dtype='float64'), axis=0, weights=polychromatic_weights)\n\n    slice_ = bestpupil[1].slice_x[1]\n    slicedv = me.abs(me.diff(sliceavg[me.isfinite(sliceavg)]))\n    if slicedv.sum() != 0:\n        peakiness = slicedv.max() / slicedv.mean()\n    else:\n        peakiness = 999.0\n    strehl = float(bestpupil[1].strehl)\n\n    if s.plot:\n        # Plot each Z phase separately\n        for key, value in bestpupil[3].items():\n            if value != 0:\n                pupil = prysm.FringeZernike(dia=10, norm=False,\n                                            wavelength=bestpupil[2],\n                                            opd_unit=\"um\",\n                                            samples=samples,\n                                            **{key: value})\n                pupil = mask_pupil(pupil, p['base_fstop'], p['fstop'], engine=me)\n                slice = pupil.slice_x[1]\n                rms = (slice[me.isfinite(slice)] ** 2).mean() ** 0.5\n                plt.plot(cp.asnumpy(slice), label=\"{} : {:.3f} λRMS\".format(key, rms / conf.BASE_WAVELENGTH))\n        slice_ = bestpupil[1].slice_x[1]\n        rms = (slice_[me.isfinite(slice_)] ** 2).mean() ** 0.5\n        plt.plot(slice_, label=\"All : {:.3f} λRMS\".format(rms / conf.BASE_WAVELENGTH))\n        pupil = prysm.FringeZernike(z4=z4,\n                                    dia=10, norm=False,\n                                  wavelength=bestpupil[2],\n                                  opd_unit=\"um\",\n                                  samples=samples,\n                                  **bestpupil[3])\n\n        pupil = mask_pupil(pupil, p['base_fstop'], p['fstop'])\n        slice_ = pupil.slice_x[1]\n        rms = (slice_[me.isfinite(slice_)] ** 2).mean() ** 0.5\n        plt.plot(slice_, '--', label=\"ZeroZ4 : {:.3f} λRMS\".format(rms / conf.BASE_WAVELENGTH), color='black')\n        plt.legend()\n        plt.show()\n        mono_psf = prysm.PSF.from_pupil(pupil, efl=p['base_fstop']*10)\n        mono_psf.plot2d(axlim=8)\n        plt.show()\n\n        slicedv = np.abs(np.diff(sliceavg[me.isfinite(slice_)]))\n        peakiness = slicedv.max() / slicedv.mean()\n\n        plt.plot(np.diff(slice_), label=\"Pupil slice derivative at best focus {:.3f}\".format(peakiness))\n        plt.legend()\n        plt.show()\n\n    return tr\n\n\ndef _try_wavefront_prysmref(s: TestSettings):\n    t = time.time()\n\n    tr = TestResults()\n    tr.copy_important_settings(s)\n\n    if s.dummy:\n        return tr\n\n    if s.p['fstop'] < s.p['base_fstop']:\n        raise ValueError(\"Base_fstop must be wider (lower) than fstop {} < {}\".format(s.p['fstop'], s.p['base_fstop']))\n    pupilslices = []\n\n    if not s.is_valid:\n        s = get_processing_details(s)\n\n    use_cuda = False\n\n    if prysm.config.backend != np:\n        prysm.config.backend = np\n        prysm.config.precision = conf.PRECISION\n\n\n    tr.used_cuda = use_cuda\n\n    realdtype = \"float32\" if conf.PRECISION == 32 else \"float64\"\n    complexdtype = \"complex64\" if conf.PRECISION == 32 else \"complex128\"\n\n    me, mestr = (cp, 'np') if use_cuda else (np, 'np')\n\n    eval_wavelengths = [BASE_WAVELENGTH] if s.mono else MODEL_WVLS\n\n    # eval_wavelengths = [BASE_WAVELENGTH] if s.mono else [0.5, 0.9]\n\n    # s.p['loca'] *= 0.1\n    # s.p['loca1'] *= 0.1\n    # s.p['spca2'] *= 0.1\n    # s.p['spca'] *= 0.1\n\n    psf_lst = []\n\n    # s.fftsize = s.phasesamples * 4\n\n    prysm_path_q = max(1, s.fftsize / s.phasesamples)\n\n    samplelst = []\n    print(s.id_or_hash)\n\n    polychromatic_weights = me.array([float(photopic_fn(wv * 1e3) * d50_interpolator(wv)) for wv in eval_wavelengths])\n    # polychromatic_weights = me.array([0.5, 0.5])\n    t_misc = 0\n    t_pupils = 0\n    t_get_phases = 0\n    t_get_fcns = 0\n    t_pads = 0\n    t_ffts = 0\n    t_cudasyncs = 0\n    t_affines = 0\n    t_mtfs = 0\n    t_init = time.time() - t\n    t = time.time()\n\n    mask = mask_pupil(s, engine=me, dtype=realdtype)\n\n    t_maskmaking = time.time() - t\n\n    bestpupil = None\n\n    zkwargs = {}\n    for key, value in s.p.items():\n        if key.lower().startswith('z') and key[1].isdigit():\n            if key.lower() != \"z4\" and key.lower() != \"z9\":\n                zkwargs[key] = value * conf.BASE_WAVELENGTH\n\n    for wvl_num, (model_wvl, polych_weight) in enumerate(zip(eval_wavelengths, polychromatic_weights)):\n        t = time.time()\n        rel_wv = model_wvl / BASE_WAVELENGTH\n\n        z4 = get_z4(s.defocus, s.p, model_wvl)\n        z9 = get_z9(s.p, model_wvl)\n\n        samplelst.append(s.phasesamples)\n        t_misc += time.time() - t\n        t = time.time()\n        pupil = prysm.FringeZernike(z4=z4, z9=z9, dia=10, norm=False,\n                                    wavelength=model_wvl,\n                                    opd_unit=\"um\",\n                                    mask_target='fcn',\n                                    mask=mask,\n                                    samples=s.phasesamples, **zkwargs)\n        t_pupils += time.time() - t\n        t = time.time()\n\n        t_get_phases += time.time() - t\n        t = time.time()\n\n        t_get_phases += time.time() - t\n\n        t = time.time()\n        mono_psf = prysm.PSF.from_pupil(pupil, efl=s.p['base_fstop'] * 10, Q=prysm_path_q, norm='radiometric')\n        # plt.plot(np.log10(mono_psf.data[int(mono_psf.data.shape[0]/2), :]))\n        # mono_psf.plot2d()\n        # plt.show()\n\n        t_ffts += time.time() - t\n\n        psf_lst.append(mono_psf)\n\n        pupilslices.append(pupil.slice_x[1])\n\n        metric = np.abs(rel_wv - 1)\n        if bestpupil is None or metric < bestpupil[0]:\n            bestpupil = metric, pupil, model_wvl, zkwargs\n\n    t = time.time()\n\n    mixedpsf = prysm.PSF.polychromatic(psf_lst, me.array(polychromatic_weights))\n    tr.psf = mixedpsf\n    # print(s.id_or_hash)\n    # tr2 = _try_wavefront_prysmref(s)\n    # mixedpsf.plot2d(axlim=18)\n    # ax = plt.gca()\n    # ax.set_title(\"A\")\n    # plt.show()\n    # tr.otf = np.ones_like(SPACIAL_FREQS), np.ones_like(SPACIAL_FREQS)\n\n    t_ffts += time.time() - t\n\n    t = time.time()\n    freqs = SPACIAL_FREQS / DEFAULT_PIXEL_SIZE * 1e-3\n    mtf = prysm.MTF.from_psf(mixedpsf)\n    tr._prysm_mtf = mtf.sag, mtf.tan\n    tr.otf = mtf.exact_sag(freqs), mtf.exact_tan(freqs)\n    # tr._prysm_otf = tr.otf\n    if 0:\n        centre = s.fftsize // 2\n\n        otf = me.fft.fftshift(me.fft.fft2(me.fft.ifftshift(mixedpsf.data)))\n\n        f_units = prysm.fttools.forward_ft_unit(mixedpsf.sample_spacing, len(mixedpsf.x))\n        otf /= np.abs(otf[centre, centre])\n        sag_mod = otf[centre, centre:]\n        tan_mod = otf[centre:, centre]\n        f_units = f_units[centre:]\n\n        interpfn = interpolate.InterpolatedUnivariateSpline(f_units, np.real(sag_mod), k=1)\n        sagmtf = interpfn(SPACIAL_FREQS / DEFAULT_PIXEL_SIZE * 1e-3)\n        interpfn = interpolate.InterpolatedUnivariateSpline(f_units, np.real(tan_mod), k=1)\n        tanmtf = interpfn(SPACIAL_FREQS / DEFAULT_PIXEL_SIZE * 1e-3)\n        interpfn = interpolate.InterpolatedUnivariateSpline(f_units, np.imag(sag_mod), k=1)\n        sagmtf_i = interpfn(SPACIAL_FREQS / DEFAULT_PIXEL_SIZE * 1e-3)\n        interpfn = interpolate.InterpolatedUnivariateSpline(f_units, np.imag(tan_mod), k=1)\n        tanmtf_i = interpfn(SPACIAL_FREQS / DEFAULT_PIXEL_SIZE * 1e-3)\n\n        tr.otf = sagmtf + 1j * sagmtf_i, tanmtf + 1j * tanmtf_i\n\n    t_mtfs += time.time() - t\n\n    timings = dict(t_init=t_init,\n                   t_maskmaking=t_maskmaking,\n                   t_pupils=t_pupils,\n                   t_get_phases=t_get_phases,\n                   t_get_fcns=t_get_fcns,\n                   t_pads=t_pads,\n                   t_ffts=t_ffts,\n                   t_cudasyncs=t_cudasyncs,\n                   t_affines=t_affines,\n                   t_mtfs=t_mtfs,\n                   t_misc=t_misc)\n\n    tr.timings = timings\n\n    sliceavg = me.average(me.array(pupilslices, dtype='float64'), axis=0, weights=polychromatic_weights)\n\n    slice_ = bestpupil[1].slice_x[1]\n    slicedv = me.abs(me.diff(sliceavg[me.isfinite(sliceavg)]))\n    if slicedv.sum() != 0:\n        peakiness = slicedv.max() / slicedv.mean()\n    else:\n        peakiness = 999.0\n    # strehl = float(bestpupil[1].strehl)\n    strehl = 1\n\n    if s.plot:\n        # Plot each Z phase separately\n        for key, value in bestpupil[3].items():\n            if value != 0:\n                pupil = prysm.FringeZernike(dia=10, norm=False,\n                                            wavelength=bestpupil[2],\n                                            opd_unit=\"um\",\n                                            samples=samples,\n                                            **{key: value})\n                pupil = mask_pupil(pupil, p['base_fstop'], p['fstop'], engine=me)\n                slice = pupil.slice_x[1]\n                rms = (slice[me.isfinite(slice)] ** 2).mean() ** 0.5\n                plt.plot(cp.asnumpy(slice), label=\"{} : {:.3f} λRMS\".format(key, rms / conf.BASE_WAVELENGTH))\n        slice_ = bestpupil[1].slice_x[1]\n        rms = (slice_[me.isfinite(slice_)] ** 2).mean() ** 0.5\n        plt.plot(slice_, label=\"All : {:.3f} λRMS\".format(rms / conf.BASE_WAVELENGTH))\n        pupil = prysm.FringeZernike(z4=z4,\n                                    dia=10, norm=False,\n                                    wavelength=bestpupil[2],\n                                    opd_unit=\"um\",\n                                    samples=samples,\n                                    **bestpupil[3])\n\n        pupil = mask_pupil(pupil, p['base_fstop'], p['fstop'])\n        slice_ = pupil.slice_x[1]\n        rms = (slice_[me.isfinite(slice_)] ** 2).mean() ** 0.5\n        plt.plot(slice_, '--', label=\"ZeroZ4 : {:.3f} λRMS\".format(rms / conf.BASE_WAVELENGTH), color='black')\n        plt.legend()\n        plt.show()\n        mono_psf = prysm.PSF.from_pupil(pupil, efl=p['base_fstop']*10)\n        mono_psf.plot2d(axlim=8)\n        plt.show()\n\n        slicedv = np.abs(np.diff(sliceavg[me.isfinite(slice_)]))\n        peakiness = slicedv.max() / slicedv.mean()\n\n        plt.plot(np.diff(slice_), label=\"Pupil slice derivative at best focus {:.3f}\".format(peakiness))\n        plt.legend()\n        plt.show()\n\n    return tr\n\n\ntempcache = {}\n\n\ndef mask_pupil(s: TestSettings, engine=np, dtype=\"float64\", plot=False):\n    # s.p['v_rad'] = 1.0\n    hashtuple = (s.p['base_fstop'],\n                 s.p['fstop'],\n                 s.x_loc,\n                 s.y_loc,\n                 s.phasesamples,\n                 s.p.get('a', 0.0),\n                 s.p.get('b', 0.0),\n                 s.p.get('v_scr', 1.0),\n                 s.p.get('v_rad', 1.0),\n                 # s.p.get('v_x', 0.0),\n                 # s.p.get('v_y', 0.0),\n                 s.p.get('squariness', 0.5),\n                 \"np\" if engine is np else \"cp\",\n                 dtype)\n\n    hash = hashtuple.__hash__()\n\n    for cachehash, mask in mask_cache:\n        if cachehash == hash:\n            return mask\n\n    smoothfactor = s.phasesamples / 1.5\n\n    me = engine\n\n    aperture_stop_norm_radius = s.p['base_fstop'] / s.p['fstop']\n\n    na = 1 / (2.0 * s.p['base_fstop'])\n    onaxis_peripheral_ray_angle = me.arcsin(na, dtype=dtype)\n\n    pupil_radius_mm = me.tan(onaxis_peripheral_ray_angle, dtype=dtype) * s.default_exit_pupil_position_mm\n\n    x_displacement_mm = (s.x_loc - IMAGE_WIDTH / 2) * DEFAULT_PIXEL_SIZE * 1e3\n    y_displacement_mm = (s.y_loc - IMAGE_HEIGHT / 2) * DEFAULT_PIXEL_SIZE * 1e3\n\n    # angle = s.p.get('v_angle', 0)\n    magnitude = (x_displacement_mm ** 2 + y_displacement_mm ** 2) ** 0.5\n\n    if s.fix_pupil_rotation:\n        x_displacement_mm = -magnitude\n        y_displacement_mm = 0\n\n    x_displacement_mm_min = -x_displacement_mm - pupil_radius_mm\n    x_displacement_mm_max = -x_displacement_mm + pupil_radius_mm\n    y_displacement_mm_min = -y_displacement_mm - pupil_radius_mm\n    y_displacement_mm_max = -y_displacement_mm + pupil_radius_mm\n\n    x = me.linspace(x_displacement_mm_min, x_displacement_mm_max, s.phasesamples, dtype=dtype)\n    y = me.linspace(y_displacement_mm_min, y_displacement_mm_max, s.phasesamples, dtype=dtype)\n    gridx, gridy = me.meshgrid(x, y)\n    displacement_grid = (gridx**2 + gridy**2) ** 0.5\n    squariness = (2**0.5 - displacement_grid / me.maximum(abs(gridx), abs(gridy))) ** 2\n    pixel_angle_grid = me.arctan(displacement_grid / s.default_exit_pupil_position_mm *\n                                 (1.0 + squariness * s.p.get('squariness', 0.5)), dtype=dtype)\n\n    normarr = me.linspace(-1, 1, s.phasesamples, dtype=dtype)\n    gridx, gridy = me.meshgrid(normarr, normarr)\n    pupil_norm_radius_grid = (gridx ** 2 + gridy ** 2) ** 0.5\n\n    stopmask = np.clip( (aperture_stop_norm_radius - pupil_norm_radius_grid) * smoothfactor + 0.5, 0, 1)\n\n    a = s.p.get('a', 1.0)\n    b = s.p.get('b', 1.0)\n\n    if not s.pixel_vignetting:\n        mask = stopmask\n    else:\n        coeff_4 = -18.73 * a\n        corff_6 = 485 * b\n        square_grid = 1.0 / (1.0 + (pixel_angle_grid**4 * coeff_4 + pixel_angle_grid ** 6 * corff_6))\n        mask = stopmask * square_grid\n\n    if s.lens_vignetting:\n        # Lens vignette\n        normarr = me.linspace(-1, 1, s.phasesamples, dtype=dtype)\n        image_circle_modifier = s.p.get('v_slr', 1.0) * 0.6\n        gridx, gridy = me.meshgrid(normarr - x_displacement_mm / SENSOR_WIDTH * 1e-3 * image_circle_modifier,\n                                   normarr - y_displacement_mm / SENSOR_WIDTH * 1e-3 * image_circle_modifier)\n        vignette_radius_grid = (gridx ** 2 + gridy ** 2) ** 0.5\n        vignette_crop_circle_radius = s.p.get('v_rad', 1.0)\n        vignette_mask = vignette_radius_grid < vignette_crop_circle_radius\n        vignette_mask = np.clip((vignette_crop_circle_radius - vignette_radius_grid) * smoothfactor + 0.5, 0, 1)\n        mask *= vignette_mask\n\n        normarr = me.linspace(-1, 1, s.phasesamples, dtype=dtype)\n        image_circle_modifier = s.p.get('v_slr', 1.0) * 0.6\n        gridx, gridy = me.meshgrid(normarr + x_displacement_mm / SENSOR_WIDTH * 1e-3 * image_circle_modifier,\n                                   normarr + y_displacement_mm / SENSOR_WIDTH * 1e-3 * image_circle_modifier)\n        vignette_radius_grid = (gridx ** 2 + gridy ** 2) ** 0.5\n        vignette_crop_circle_radius = s.p.get('v_rad', 1.0) * 1.0\n        vignette_mask = vignette_radius_grid < vignette_crop_circle_radius\n        vignette_mask = np.clip((vignette_crop_circle_radius - vignette_radius_grid) * smoothfactor + 0.5, 0, 1)\n        mask *= vignette_mask\n\n    if plot or s.id_or_hash == -1:\n        if engine is cp:\n            print(square_grid)\n            plt.imshow(cp.asnumpy(mask))\n            plt.colorbar()\n            plt.show()\n        else:\n            print(square_grid)\n            plt.imshow(mask)\n            plt.colorbar()\n            plt.show()\n    return mask\n\n\ndef plot_pixel_vignetting_loss():\n    fstops = 2.0 ** np.linspace(0.0, 1.5, 6)\n    test_fstops = (1, 2**0.16667, 1.222, 2**0.5, 1.4 * 2**0.166667, 2, 2 * 2 ** 0.166667, 2 * 2**0.5)\n    benefits_exp = (1.93,1.90, 1.81, 1.70, 1.5, 0.93, 0.62, 0)\n\n    s = TestSettings(0, dict(base_fstop=1.0, fstop=2.0 * 2**0.5))\n    s.phasesamples = 256\n    s.pixel_vignetting = False\n    baseline = mask_pupil(s, np).mean()\n\n    s.pixel_vignetting = True\n\n    if \"optimise\" and 0:\n        def callable(x):\n            error = 0\n            for testfstop, benefit_exp in zip(test_fstops, benefits_exp):\n                s.p = dict(base_fstop=1, fstop=testfstop)\n                s.p['a'], s.p['b'] = x\n                benefit = np.log2(mask_pupil(s, np).mean() / baseline)\n                print(x[0], x[1], testfstop, benefit)\n                error += (benefit - benefit_exp) ** 2\n            print()\n            return error\n\n        opt = optimize.minimize(callable, (0, 0))  # ,bounds=((-20,20), (-30, 30)\n        a, b = opt.x\n    else:\n        a, b = 0, 0\n\n    plot_fstops = 2**np.linspace(0, 1.5, 6)\n    benefits = []\n    benefits_stop = []\n    for testfstop in plot_fstops:\n        s.p = dict(base_fstop=testfstop, fstop=testfstop)\n        s.p['a'], s.p['b'] = a, b\n        benefit = np.log2(mask_pupil(s, np, plot=True).mean()/(testfstop**2) / baseline)\n        benefits.append(benefit)\n        s.p = dict(base_fstop=1, fstop=testfstop)\n        s.p['a'], s.p['b'] = a, b\n        benefit = np.log2(mask_pupil(s, np, plot=True).mean() / baseline)\n        benefits_stop.append(benefit)\n\n    plt.plot(plot_fstops, benefits)\n    plt.plot(plot_fstops, benefits_stop)\n    plt.plot(test_fstops, benefits_exp)\n    plt.plot()\n    plt.show()\n    exit()\n\n\ndef plot_lens_vignetting_loss(base_fstop=1.4):\n    fstops = 2.0 ** np.linspace(0.0, 2, 4)\n    for stop in fstops:\n        s = TestSettings(0, dict(base_fstop=base_fstop, fstop=stop * base_fstop))\n        s.phasesamples = 128\n        s.pixel_vignetting = True\n        s.lens_vignetting = True\n        s.p['v_mag'] = 0.8\n        s.p['v_rad'] = 1.3\n        s.p['v_x'] = -0.8\n        s.p['v_y'] = -0.8\n        baseline = mask_pupil(s, np).mean()\n        heights = np.linspace(0, 1, 16)\n        losses = []\n        s.x_loc = 0\n        s.y_loc = 0\n        mask_pupil(s, np, plot=True)\n        for height in heights:\n            s.x_loc = 3000 + height * IMAGE_WIDTH / 2\n            s.y_loc = 2000 + height * IMAGE_HEIGHT / 2\n            # losses.append(np.log2(mask_pupil(s, np).mean() / baseline))\n            losses.append(mask_pupil(s, np).mean() / baseline)\n        plt.plot(heights, losses)\n    plt.show()\n\n# from lentil import wavefront_test\n# s = TestSettings(0, dict(base_fstop=2.6, fstop=2.6))\n# s.phasesamples = 256\n# s.return_type = RETURN_MTF\n# s.p['tca_slr'] = 0\n#\n# s.p['v_slr'] =2.6\n# s.x_loc = 5600\n# s.y_loc = 3800\n# s.x_loc = 6000-5600\n# s.y_loc = 4000-3800\n# s.p['z5'] = -1\n# s.p['df_offset'] = 0\n# s.p['df_step'] = 1\n# s.default_exit_pupil_position_mm = 1000\n# s.p['ellip'] = 0\n# s.allow_cuda = False\n# s.p['loca'] = 0.0000001\n# s.defocus = 0\n# s.mono = True\n\n# mask_pupil(s, plot=True)\n# tr = try_wavefront(s)\n# plt.plot(tr.otf[0], label='sag')\n# plt.plot(tr.otf[1], label='tan')\n# plt.legend()\n# print(tr.otf[0])\n# psf = tr.psf\n# psf.plot2d(axlim=30)\n# plt.show()\n# exit()y\n\n\n\npool = multiprocessing.Pool(processes=8)\n\ndef testmul(samples, total_loops=2*5, Q=2):\n    s = TestSettings(0, dict(fstop=1.4, base_fstop=1.4))\n    s.phasesamples = 256\n    s.fftsize = 512\n    s.allow_cuda = False\n    pool.starmap(try_wavefront, [(s, )] * 16 * 5)\n", "meta": {"hexsha": "3360140546a540c98f39d346f685a91f32514bd0", "size": 51303, "ext": "py", "lang": "Python", "max_stars_repo_path": "lentil/wavefront_test__old.py", "max_stars_repo_name": "samkberry/lentil", "max_stars_repo_head_hexsha": "161b64449cd0f2278af9554ba2a7d6b2da0e532b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-17T08:49:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T11:56:39.000Z", "max_issues_repo_path": "lentil/wavefront_test__old.py", "max_issues_repo_name": "samkberry/lentil", "max_issues_repo_head_hexsha": "161b64449cd0f2278af9554ba2a7d6b2da0e532b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lentil/wavefront_test__old.py", "max_forks_repo_name": "samkberry/lentil", "max_forks_repo_head_hexsha": "161b64449cd0f2278af9554ba2a7d6b2da0e532b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8762237762, "max_line_length": 148, "alphanum_fraction": 0.5744498372, "include": true, "reason": "import numpy,from scipy,import cupy", "num_tokens": 15350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.17965156415429945}}
{"text": "#!/usr/bin/env python\n\nimport sys\nimport numpy as np\nfrom libs import base\nfrom libs import utils\nimport libs.cadnano_utils as cu\nimport re\nimport os\nimport pickle\n\nDEBUG = 0\nDIST_HEXAGONAL = 2.55  # distance between centres of virtual helices (hexagonal array)\nDIST_SQUARE = 2.60  # distance between centres of virtual helices (square array)\nBOX_FACTOR = 2  # factor by which to expand the box (linear dimension)\n\n\nclass vh_nodes(object):\n\n    def __init__(self):\n        self.begin = []\n        self.end = []\n\n    def __str__(self):\n        return str([self.begin, self.end])\n\n    def add_begin(self, begin_index):\n        if begin_index not in self.begin:\n            self.begin.append(begin_index)\n\n    def add_end(self, end_index):\n        if end_index not in self.end:\n            self.end.append(end_index)\n\n\ndef vhelix_rotation_origami_sq(direction, perp):\n    R = utils.get_rotation_matrix(direction, np.pi * 15. / 180)\n    return np.dot(R, perp)\n\n\ndef vhelix_rotation_origami_he(direction, perp):\n    R = utils.get_rotation_matrix(direction, np.pi * 160. / 180)\n    return np.dot(R, perp)\n\n\ndef insert_loop_skip(strands, start_pos, direction, perp, rot, helix_angles, vhelix, nodes, use_seq, seqs):\n    # return a double strand which is a copy of the double strand in the first argument, but with skips and loops\n\n    # strand is generated right to left i.e. opposite direction to even vhelix\n    length_change = []\n    length_change_total = 0\n    new_nodes = vh_nodes()\n    new_angle = []\n    helix_angles_new = np.copy(helix_angles)\n\n    if vhelix.num % 2 == 1:\n        reverse_nodes = vh_nodes()\n        reverse_nodes.begin = list(reversed(nodes.begin))\n        reverse_nodes.end = list(reversed(nodes.end))\n\n    for i in range(len(nodes.begin)):\n        # ltr: left to right; looking at the strand left to right (low to high square index), the beginning/end of the effective strand is here (before skips/loops)\n        # gs: generated strand; the index of the nucleotide (BEFORE skips/loops are applied) on the generated strand corresponding to the beginning/end of the effective strand\n        if vhelix.num % 2 == 0:\n            begin_ltr = nodes.begin[i]\n            end_ltr = nodes.end[i]\n            begin_gs = nodes.begin[i]\n            end_gs = nodes.end[i]\n        else:\n            begin_ltr = reverse_nodes.end[i]\n            end_ltr = reverse_nodes.begin[i]\n            begin_gs = vhelix.len - reverse_nodes.begin[i] - 1\n            end_gs = vhelix.len - reverse_nodes.end[i] - 1\n\n        # check for zero length effective strand\n        if end_gs - begin_gs != 0:\n            # get length change for this effective strand\n            length_change.append(0)\n            for j in vhelix.skip[begin_ltr:end_ltr + 1]:\n                length_change[i] -= int(j)\n            for j in vhelix.loop[begin_ltr:end_ltr + 1]:\n                length_change[i] += int(j)\n            # get new pitch angles for this effective strand\n            new_angle.append(sum(helix_angles[begin_gs:end_gs]) / (end_gs - begin_gs + length_change[i]))\n            helix_angles_new[begin_gs:end_gs] = new_angle[i]\n            # adjust beginning/end indices according to length change\n            begin_gs += length_change_total\n            end_gs += length_change_total + length_change[i]\n            new_nodes.add_begin(begin_gs)\n            new_nodes.add_end(end_gs)  # begin_gs > end_gs.....\n        else:\n            length_change.append(0)\n            new_angle.append(sum(helix_angles) / len(helix_angles))  # append an average angle\n            new_nodes.add_begin(begin_gs)\n            new_nodes.add_end(end_gs)\n        length_change_total += length_change[i]\n\n    # adjust the new helix angle array according to skips/loops\n    deleted = 0\n    inserted = 0\n    deleted_this_iteration = 0\n    inserted_this_iteration = 0\n    for i in range(len(nodes.begin)):\n        deleted += deleted_this_iteration\n        inserted += inserted_this_iteration\n        deleted_this_iteration = 0\n        inserted_this_iteration = 0\n        if vhelix.num % 2 == 0:\n            begin_ltr = nodes.begin[i]\n            end_ltr = nodes.end[i]\n            begin_gs = nodes.begin[i]\n            end_gs = nodes.end[i]\n        else:\n            begin_ltr = reverse_nodes.end[i]\n            end_ltr = reverse_nodes.begin[i]\n            begin_gs = vhelix.len - reverse_nodes.begin[i] - 1\n            end_gs = vhelix.len - reverse_nodes.end[i] - 1\n        for j in vhelix.skip[begin_ltr:end_ltr + 1]:\n            if j == 1:\n                helix_angles_new = np.delete(helix_angles_new, begin_gs - deleted + inserted)\n                deleted_this_iteration += 1\n        for j in vhelix.loop[begin_ltr:end_ltr + 1]:\n            for _ in range(j):\n                helix_angles_new = np.insert(helix_angles_new, begin_gs - deleted + inserted, new_angle[i])\n                inserted_this_iteration += 1\n                \n    g = cu.StrandGenerator()\n    new_strands = g.generate_or_sq(len(helix_angles_new) + 1, start_pos=start_pos, direction=direction, perp=perp, double=True, rot=rot, angle=helix_angles_new, length_change=length_change, region_begin=new_nodes.begin, region_end=new_nodes.end)\n    if use_seq:\n        try:\n            sequence = [x for x in seqs[vhelix.cad_index]]\n        except IndexError:\n            base.Logger.die(\"sequence file contains too few rows compared to the number of virtual helices in the cadnano file, dying\")\n        if vhelix.num % 2 == 1:\n            sequence.reverse()\n        if new_strands[0].get_length() != len(sequence):\n            base.Logger.log(\"Cannot change sequence: lengths don't match; virtual helix %s, sequence length %s, virtual helix length %s - are skips/loops accounted for?\" % (vhelix.num, len(sequence), new_strands[0].get_length()), base.Logger.WARNING)\n        else:\n            new_strands[0].set_sequence(sequence)\n        sequence2 = [3 - s for s in sequence]\n        sequence2.reverse()\n        if new_strands[0].get_length() != len(sequence):\n            base.Logger.log(\"Cannot change sequence: lengths don't match; virtual helix %s, sequence length %s, virtual helix length %s - are skips/loops accounted for?\" % (vhelix.num, len(sequence), new_strands[0].get_length()), base.Logger.WARNING)\n        else:\n            new_strands[1].set_sequence(sequence2)\n\n    return new_strands\n\n\ndef add_slice(current_system, vhelix, begin, end, nodes, strands, pos, direction, perp, rot, helix_angles, strand_type, use_seq, seqs):\n    # add a slice of the virtual helix to the slice system, taking into account skips and loops\n    length_change_begin = 0\n    length_change_end = 0\n    \n    if (vhelix.num % 2 + strand_type) % 2 == 0:  # strand and even num or staple and odd num\n        for i in vhelix.skip[:begin]:\n            length_change_begin -= int(i)\n        for i in vhelix.skip[:end + 1]:\n            length_change_end -= int(i)\n            \n        for i in vhelix.loop[:begin]:\n            length_change_begin += int(i)\n        for i in vhelix.loop[:end + 1]:\n            length_change_end += int(i)\n    \n        begin_slice = begin + length_change_begin\n        end_slice = end + 1 + length_change_end\n\n    else:\n        for i in vhelix.skip[end:]:\n            length_change_end -= int(i)\n        for i in vhelix.skip[begin + 1:]:\n            length_change_begin -= int(i)\n            \n        for i in vhelix.loop[end:]:\n            length_change_end += int(i)\n        for i in vhelix.loop[begin + 1:]:\n            length_change_begin += int(i)\n\n        begin_slice = vhelix.len - begin - 1 + length_change_begin\n        end_slice = vhelix.len - end + length_change_end\n\n    new_strands = insert_loop_skip(strands, pos, direction, perp, rot, helix_angles, vhelix, nodes, use_seq, seqs)\n    current_system.add_strand(new_strands[strand_type].get_slice(begin_slice, end_slice), check_overlap=False)\n    return current_system\n\n\ndef add_slice_nupack(vhelix, strand_number, begin_helix, end_helix, index_lookup, strand_type):\n    length_change = 0\n    skips = 0\n    loops = 0\n    if (vhelix.num % 2 + strand_type) % 2 == 0 :  # strand and even num or staple and odd num\n        for i in vhelix.skip[begin_helix:end_helix + 1]:\n            length_change -= int(i)\n            \n        for i in vhelix.loop[begin_helix:end_helix + 1]:\n            length_change += int(i)\n    \n    else:\n        for i in vhelix.skip[end_helix:begin_helix + 1]:\n            length_change -= int(i)\n            \n        for i in vhelix.loop[end_helix:begin_helix + 1]:\n            length_change += int(i)\n            \n    if (strand_type + vhelix.num % 2) % 2 == 0:\n        iter_length = end_helix - begin_helix + 1 + length_change\n    else:\n        iter_length = begin_helix + 1 - end_helix + length_change\n\n    nucleotide = 0\n    while nucleotide < iter_length:\n        if (strand_type + vhelix.num % 2) % 2 == 0:\n            vhelix_base = nucleotide + begin_helix + skips - loops\n        else:\n            vhelix_base = begin_helix - nucleotide - skips + loops\n        if vhelix.skip[vhelix_base] != 1:\n            if (strand_type + vhelix.num % 2) % 2 == 0:\n                add_nuc = [nucleotide + x for x in range(vhelix.loop[vhelix_base] + 1)]\n            else:\n                add_nuc = [nucleotide + x for x in range(vhelix.loop[vhelix_base] + 1)[::-1]]\n            if strand_type == 0:\n                index_lookup[(vhelix.num, vhelix_base)] = [strand_number, nucleotide]\n            elif strand_type == 1:\n                index_lookup[(strand_number, nucleotide)] = [vhelix.num, vhelix_base]\n            elif strand_type == 2:\n                index_lookup.add_scaf(vhelix.num, vhelix_base, strand_number, add_nuc)\n            elif strand_type == 3:\n                index_lookup.add_stap(vhelix.num, vhelix_base, strand_number, add_nuc)\n            nucleotide += 1 + vhelix.loop[vhelix_base]\n            loops += vhelix.loop[vhelix_base]\n        else:\n            if strand_type == 2:\n                index_lookup.add_scaf(vhelix.num, vhelix_base, strand_number, [])\n            elif strand_type == 3:\n                index_lookup.add_stap(vhelix.num, vhelix_base, strand_number, [])\n            skips += 1\n\n    return index_lookup\n\n\ndef build_nodes(vh):\n    # returns a vh_nodes object which contains the beginning and end square indices of each effective strand. Effective strands\n    # on a given vhelix are a combination of information on staple and scaffold strands. Together they tell us which\n    # nucleotides need to be held constant when we alter the angles/base-base distances for a section of nucleotides along a final strand\n    nodes = vh_nodes()\n    if vh.num % 2 == 0:\n        direction = 1\n    else:\n        direction = -1\n    for i in range(len(vh.scaf)):\n        # need to consider what happens when I add an index to the node list that doesn't fall within the range of square indices in the vhelix\n        previd = i - 1 * direction\n        nextid = i + 1 * direction\n        if previd in range(len(vh.scaf)):\n            prev = vh.scaf[previd].type(vh, previd)\n            prev_stap = vh.stap[previd].type(vh, previd)\n        else:\n            prev = False\n            prev_stap = False\n        if nextid in range(len(vh.scaf)):\n            next_ = vh.scaf[nextid].type(vh, nextid)\n            next_stap = vh.stap[nextid].type(vh, nextid)\n        else:\n            next_ = False\n            next_stap = False\n        # now build the effective strand vh_nodes object\n        if not ((prev == prev_stap and (prev == 'begin' or prev == 'end')) or (next_ == next_stap and (next_ == 'begin' or next_ == 'end'))):\n            if vh.scaf[i].type(vh, i) == 'empty':\n                if vh.stap[i].type(vh, i) == 'begin':\n                    nodes.add_end(i)\n                elif vh.stap[i].type(vh, i) == 'end':\n                    nodes.add_begin(i)\n            elif vh.scaf[i].type(vh, i) == 'begin':\n                if vh.stap[i].type(vh, i) == 'empty':\n                    nodes.add_begin(i)\n                elif vh.stap[i].type(vh, i) == 'continue':\n                    nodes.add_begin(i)\n                    nodes.add_end(i - 1 * direction)\n                elif vh.stap[i].type(vh, i) == 'begin':\n                    nodes.add_begin(i + 1 * direction)\n                    nodes.add_end(i - 1 * direction)\n                elif vh.stap[i].type(vh, i) == 'end':\n                    nodes.add_begin(i)\n            elif vh.scaf[i].type(vh, i) == 'end':\n                if vh.stap[i].type(vh, i) == 'empty':\n                    nodes.add_end(i)\n                elif vh.stap[i].type(vh, i) == 'continue':\n                    nodes.add_begin(i + 1 * direction)\n                    nodes.add_end(i)\n                elif vh.stap[i].type(vh, i) == 'begin':\n                    nodes.add_end(i)\n                elif vh.stap[i].type(vh, i) == 'end':\n                    nodes.add_begin(i + 1 * direction)\n                    nodes.add_end(i - 1 * direction)\n            elif vh.scaf[i].type(vh, i) == 'continue':\n                if vh.stap[i].type(vh, i) == 'begin':\n                    nodes.add_begin(i + 1 * direction)\n                    nodes.add_end(i)\n                elif vh.stap[i].type(vh, i) == 'end':\n                    nodes.add_begin(i)\n                    nodes.add_end(i - 1 * direction)\n                    \n    return nodes\n\n\ndef generate_vhelices_origami_sq(vhelix_direction, vhelix_perp, h, sequence_file, single_strand_system, vhelix_counter):\n    g = cu.StrandGenerator()\n    # generate helix angles\n    helix_angles = np.zeros(h.len - 1, dtype=float)\n    # hard upper limit on pitch angle seems to be between 54.5 and 55 degrees\n    for i in range(len(helix_angles)):\n        modi = i % 32\n        if modi < 2:\n            helix_angles[i] = 28 * np.pi / 180\n        elif modi == 2:\n            helix_angles[i] = 36 * np.pi / 180\n        elif modi == 3:\n            helix_angles[i] = 54.375 * np.pi / 180\n        elif modi == 4:\n            helix_angles[i] = 37 * np.pi / 180\n        elif modi in (5, 6):\n            helix_angles[i] = 27.6666666666666 * np.pi / 180\n        elif modi == 7:\n            helix_angles[i] = 30.6666666666666 * np.pi / 180\n        elif modi in (8, 9):\n            helix_angles[i] = 29.3333333333 * np.pi / 180\n        elif modi == 10:\n            helix_angles[i] = 34.3333333333 * np.pi / 180\n        elif modi == 11:\n            helix_angles[i] = 54.5 * np.pi / 180\n        elif modi in (12, 13):\n            helix_angles[i] = (28.91666666666 * np.pi / 180)  # + 0.25) * np.pi/180\n        elif modi in (14, 15, 16, 17):\n            helix_angles[i] = 31.16666666666 * np.pi / 180\n        elif modi == 18:\n            helix_angles[i] = 35.5 * np.pi / 180\n        elif modi == 19:\n            helix_angles[i] = 52 * np.pi / 180\n        elif modi == 20:\n            helix_angles[i] = 35.5 * np.pi / 180\n        elif modi in (21, 22):\n            helix_angles[i] = 27.5 * np.pi / 180\n        elif modi == 23:\n            helix_angles[i] = 35.5 * np.pi / 180\n        elif modi >= 24 and modi < 27:\n            helix_angles[i] = 30 * np.pi / 180\n        elif modi == 27:\n            helix_angles[i] = 52 * np.pi / 180\n        elif modi == 28:\n            helix_angles[i] = 35.5 * np.pi / 180\n        else:\n            helix_angles[i] = 30.91666666666 * (np.pi / 180)\n\n    # make sure the helices are periodic in 32 bases\n    total_sum = 0\n    for i in range(31):\n        total_sum += helix_angles[i]\n\n    for i in range(len(helix_angles)):\n        if i % 32 == 31:\n            helix_angles[i] = 1080 * np.pi / 180 - total_sum\n            \n    # make the virtual helices\n    if h.num % 2 == 0:\n        pos = np.array([h.col * DIST_SQUARE, h.row * DIST_SQUARE, 0])\n        direction = vhelix_direction\n        perp = vhelix_perp\n        rot = 0.\n        angles = helix_angles\n        strands = g.generate_or_sq(h.len, start_pos=pos, direction=direction, perp=perp, double=True, rot=rot, angle=angles)\n\n    else:\n        pos = np.array([h.col * DIST_SQUARE, h.row * DIST_SQUARE, (h.len - 1) * base.BASE_BASE])\n        direction = -vhelix_direction\n        perp = -vhelix_perp\n        rot = -np.sum(helix_angles) % (2 * np.pi)\n        angles = np.flipud(helix_angles)\n        strands = g.generate_or_sq(h.len, start_pos=pos, direction=direction, perp=perp, double=True, rot=rot, angle=angles)\n\n    return (strands[0], strands[1]), helix_angles, pos, rot, direction, perp\n\n\ndef generate_vhelices_origami_he(vhelix_direction, vhelix_perp, h, sequence_file, single_strand_system, vhelix_counter):\n    g = cu.StrandGenerator()\n    # generate helix angles\n    helix_angles = np.zeros(h.len - 1, dtype=float)\n\n    for i in range(len(helix_angles)):\n        modi = i % 21\n        if modi == 0:\n            helix_angles[i] = 32.571 * np.pi / 180\n        elif modi == 1:\n            helix_angles[i] = 36 * np.pi / 180\n        elif modi in (1, 2, 3):\n            helix_angles[i] = 42 * np.pi / 180\n        elif modi in (5, 6, 7):\n            helix_angles[i] = 29.143 * np.pi / 180\n        elif modi == 8:\n            helix_angles[i] = 32 * np.pi / 180\n        elif modi in (9, 10):\n            helix_angles[i] = 44 * np.pi / 180\n        elif modi in (12, 13, 14):\n            helix_angles[i] = 28.571 * np.pi / 180\n        elif modi in (16, 17):\n            helix_angles[i] = 41.5 * np.pi / 180\n        elif modi in (19, 20):\n            helix_angles[i] = 28.476 * np.pi / 180\n        else:\n            helix_angles[i] = 720. / 21 * (np.pi / 180.) \n\n    # make sure it's periodic\n    total_sum = 0\n    for i in range(20):\n        total_sum += helix_angles[i]\n\n    for i in range(len(helix_angles)):\n        if i % 21 == 20:\n            helix_angles[i] = 720. * np.pi / 180 - total_sum\n\n    # make the virtual helices\n    if h.num % 2 == 0:\n        pos = np.array([h.col * np.sqrt(3) * DIST_HEXAGONAL / 2, h.row * 3 * DIST_HEXAGONAL / 2, 0])\n        direction = vhelix_direction\n        perp = vhelix_perp\n        rot = 0.\n        strands = g.generate_or_sq(h.len, start_pos=pos, direction=direction, perp=perp, double=True, rot=rot, angle=helix_angles)\n\n    else:\n        pos = np.array([h.col * np.sqrt(3) * DIST_HEXAGONAL / 2, h.row * 3 * DIST_HEXAGONAL / 2 + DIST_HEXAGONAL / 2, (h.len - 1) * base.BASE_BASE])\n        direction = -vhelix_direction\n        perp = -vhelix_perp\n        if base.MM_GROOVING:\n            rot = -np.sum(helix_angles) % (2 * np.pi) - 0.07\n        else:\n            rot = -np.sum(helix_angles) % (2 * np.pi)\n        angles = np.flipud(helix_angles)\n        strands = g.generate_or_sq(h.len, start_pos=pos, direction=direction, perp=perp, double=True, rot=rot, angle=angles)\n\n    return (strands[0], strands[1]), helix_angles, pos, rot, direction, perp\n\n\n# cadnano object structure\nclass vstrands (object):\n\n    def __init__(self):\n        self.vhelices = []\n\n    def add_vhelix(self, toadd):\n        self.vhelices.append(toadd)\n\n    def bbox(self):\n        rows = []\n        cols = []\n        lens = []\n        for h in self.vhelices:\n            rows.append(h.row)\n            cols.append(h.col)\n            lens.append(len(h.stap))\n\n        dr = DIST_SQUARE * (max(rows) - min(rows) + 2)\n        dc = DIST_SQUARE * (max(cols) - min(cols) + 2)\n        dl = 0.34 * (max(lens) + 2)\n        \n        return 2 * max([dr, dc, dl]) * BOX_FACTOR\n    \n    def __str__(self):\n        a = '{\\n\"vstrands\":[\\n'\n        if len(self.vhelices) > 0:\n            for h in self.vhelices:\n                a = a + str(h) + ','\n            a = a[0:len(a) - 1]\n        a = a + '}\\n'\n        return a\n\n\nclass vhelix (object):\n\n    def __init__(self):\n        self.stapLoop = []\n        self.scafLoop = []\n        self.skip = []\n        self.loop = []\n        self.stap_colors = []\n        self.row = 0\n        self.col = 0\n        self.num = 0\n        self.stap = []\n        self.scaf = []\n        self.cad_index = -1\n        self.skiploop_bases = 0\n\n    def get_length(self):\n        return max (len(self.scaf), len(self.stap))\n\n    len = property (get_length)\n\n    def add_square(self, toadd, which):\n        if which == 'stap':\n            self.stap.append(toadd)\n        elif which == 'scaf':\n            self.scaf.append (toadd)\n        else:\n            base.Logger.log(\"Cannot add square that is not scaf or stap. Dying now\", base.Logger.CRITICAL)\n            sys.exit(-1)\n    \n    def __str__(self):\n        a = '{\\n'\n\n        a = a + '\"stapLoop\":['\n        if len(self.stapLoop) > 0:\n            for i in self.stapLoop:\n                a = a + str(i) + ','\n            a = a[0:len(a) - 1]  # remove last comma\n        a = a + '],\\n'\n\n        a = a + '\"skip\":['\n        if len(self.skip) > 0:\n            for e in self.skip:\n                a = a + str(e) + ','\n            a = a[0:len(a) - 1]  # remove last comma\n        a = a + '],\\n'\n        \n        a = a + '\"loop\":['\n        if len(self.loop) > 0:\n            for e in self.loop:\n                a = a + str(e) + ','\n            a = a[0:len(a) - 1]  # remove last comma\n        a = a + '],\\n'\n        \n        a = a + '\"stap_colors\":['\n        if len (self.stap_colors) > 0:\n            for e in self.stap_colors:\n                a = a + str(e) + ','\n            a = a[0:len(a) - 1]  # remove last comma\n        a = a + '],\\n'\n\n        a = a + '\"row\":' + str(self.row) + ',\\n'\n        a = a + '\"col\":' + str(self.col) + ',\\n'\n        a = a + '\"num\":' + str(self.num) + ',\\n'\n        \n        a = a + '\"scafLoop\":['\n        if len(self.scafLoop) > 0:\n            for i in self.scafLoop:\n                a = a + str(i) + ','\n            a = a[0:len(a) - 1]  # remove last comma\n        a = a + '],\\n'\n        \n        a = a + '\"stap\":['\n        if len(self.stap) > 0:\n            for i in self.stap:\n                a = a + str(i) + ','\n            a = a[0:len(a) - 1]  # remove last comma\n        a = a + '],\\n'\n        \n        a = a + '\"scaf\":['\n        if len(self.scaf) > 0:\n            for i in self.scaf:\n                a = a + str(i) + ','\n            a = a[0:len(a) - 1]  # remove last comma\n        a = a + ']\\n}'\n        return a\n\n\nclass square(object):\n\n    def __init__ (self, V_0=-1, b_0=-1, V_1=-1, b_1=-1):\n        \"\"\"\n        V_0, b_0, V_1, b_1 are integer indices correspond to:\n        virtual_helix_behind, virtual_base_behind, virtual_helix_ahead, virtual_base_ahead\n        \"\"\"\n        self.V_0 = V_0\n        self.b_0 = b_0\n        self.V_1 = V_1\n        self.b_1 = b_1\n\n    def __str__ (self):\n        return '[%i,%i,%i,%i]' % (self.V_0, self.b_0, self.V_1, self.b_1)\n\n    def type(self, vhelix, myid):\n        # find type of strand (junction) on this square\n        # currently direction always equals zero...\n        direction = 0\n        if self.V_0 == -1 and self.b_0 == -1:\n            if self.V_1 == -1 and self.b_1 == -1:\n                return 'empty'\n            elif self.V_1 == vhelix.num and abs(self.b_1 - myid) == 1:\n                if direction == 0:\n                    return 'begin'\n                else:\n                    return 'end'\n        elif self.V_0 == vhelix.num and abs(self.b_0 - myid) == 1:\n            if self.V_1 == -1:\n                if direction == 0:\n                    return 'end'\n                else:\n                    return 'begin'\n            elif self.V_1 == vhelix.num and abs(self.b_1 - myid) == 1:\n                return 'continue'\n            else:\n                # join\n                if direction == 0:\n                    return 'end'\n                else:\n                    return 'begin'\n        else:\n            if self.V_1 == vhelix.num and abs(self.b_1 - myid) == 1:\n                if direction == 0:\n                    return 'begin'\n                else:\n                    return 'end'\n\n        # shouldn't get to here\n        base.Logger.log('unexpected square array', base.Logger.WARNING)\n\n        \ndef parse_cadnano(path):\n    import json\n    \n    cadsys = vstrands()\n    \n    try:\n        with open(path) as json_data:\n            cadnano = json.load(json_data)\n            for vstrand in cadnano[\"vstrands\"]:\n                vh = vhelix()\n                for key, val in vstrand.items():\n                    if key == \"skip\":\n                        vh.skip = [abs(int(x)) for x in val]\n                    else:\n                        setattr(vh, key, val)\n                vh.stap = [square(*i) for i in vh.stap]\n                vh.scaf = [square(*i) for i in vh.scaf]\n                vh.skiploop_bases = len(vh.skip) + sum(vh.loop) - sum(vh.skip)\n                cadsys.add_vhelix(vh)\n    except IOError:\n        print >> sys.stderr, \"File '\" + path + \"' not found, aborting\"\n        sys.exit(1)\n    except ValueError:\n        print >> sys.stderr, \"Invalid json file '\" + path + \"', aborting\"\n        sys.exit(1)\n    except:\n        print >> sys.stderr, \"Caught an error while parsing '\" + path + \"', aborting\"\n        sys.exit(1)\n        \n    return cadsys\n\n\nif __name__ == '__main__':\n    \n    def print_usage():\n        print >> sys.stderr, \"USAGE:\"\n        print >> sys.stderr, \"\\t%s cadnano_file lattice_type\" % sys.argv[0]\n        print >> sys.stderr, \"\\t[-q\\--sequence FILE] [-b\\--box VALUE] [-e\\--seed VALUE] [-p\\--print-virt2nuc]\" \n        exit(1)\n        \n    if len(sys.argv) < 3:\n        print_usage()\n        \n    shortArgs = 'q:b:e:p'\n    longArgs = ['sequence=', 'box=', 'seed=', 'print-virt2nuc']\n    \n    side = False\n    sequence_filename = False\n    print_virt2nuc = False\n    source_file = sys.argv[1]\n    \n    origami_sq = False\n    origami_he = False\n    if sys.argv[2] == \"sq\":\n        origami_sq = True\n    elif sys.argv[2] == \"he\":\n        origami_he = True\n    else:\n        print >> sys.stderr, \"Lattice_type should be either 'sq' or 'he'\"\n        exit(1)\n    \n    try:\n        import getopt\n        args, files = getopt.gnu_getopt(sys.argv[3:], shortArgs, longArgs)\n        for k in args:\n            if k[0] == '-q' or k[0] == \"--sequence\": \n                sequence_filename = k[1]\n            elif k[0] == '-b' or k[0] == \"--box\": \n                side = float(k[1])\n                base.Logger.log(\"The system will be put in a box of side %s (in oxDNA simulation units)\" % str(side), base.Logger.INFO)\n            elif k[0] == '-e' or k[0] == \"--seed\": \n                np.random.seed(int(k[1]))\n            elif k[0] == '-p' or k[0] == \"--print-virt2nuc\":\n                print_virt2nuc = True\n            \n            \n    except Exception:\n        print_usage()\n\n    vh_vb2nuc = cu.vhelix_vbase_to_nucleotide()\n    vh_vb2nuc_final = cu.vhelix_vbase_to_nucleotide()\n\n    cadsys = parse_cadnano(source_file)\n    base.Logger.log(\"Using json file %s\" % source_file, base.Logger.INFO)\n\n    # define sequences by vhelix\n    sequence_file = 0\n    single_strand_system = False\n    sequences = []\n    block_seq = True\n    if sequence_filename:\n        sequence_file = open(sequence_filename, \"r\")\n        base.Logger.log(\"Using sequence file '%s'\" % sequence_filename, base.Logger.INFO)\n        # with this we can remove all whitespace and we don't have issues with the different newline sequences (\\n vs \\r\\n)\n        pattern = re.compile('\\s+')\n        lines = sequence_file.readlines()\n        for line in lines:\n            seq = []\n            for x in re.sub(pattern, '', line):\n                if x in [\"R\", \"r\"]:\n                    seq.append(np.random.randint(0, 4))\n                else:\n                    try:\n                        seq.append(base.base_to_number[x])\n                    except KeyError:\n                        base.Logger.log(\"KeyError while converting base names to integer; check the sequence file\", base.Logger.CRITICAL)\n                        sys.exit()\n            sequences.append(seq)\n    else:\n        base.Logger.log(\"No sequence file given, using random sequence\", base.Logger.INFO)\n        for ii in range(len(cadsys.vhelices)):\n            seq = []\n            for _ in range(cadsys.vhelices[ii].skiploop_bases):\n                seq.append(np.random.randint(0, 4))\n            sequences.append(seq)\n\n    # check whether we're dealing with a 1 strand system (i.e. NOT double helix) across many vhelices and defined with 1 .sqs line\n    if len(sequences) == 1 and len(cadsys.vhelices) > 1:\n        base.Logger.log(\"One line detected in the sequence file. Since the cadnano file contains more than 1 virtual helix, the sequence found will be used as we were dealing with a single-strand system\", base.Logger.INFO)\n        single_strand_system = True\n        block_seq = False\n\n    vhelix_counter = 0\n    if not side:\n        side = cadsys.bbox()\n        base.Logger.log(\"Using default box size, a factor %s larger than the size of the cadnano system\" % str(BOX_FACTOR), base.Logger.INFO)\n    vhelix_direction_initial = np.array([0., 0., 1.])\n    vhelix_perp_initial = np.array([1., 0., 0.])\n    if origami_sq:\n        vhelix_perp_initial = vhelix_rotation_origami_sq(vhelix_direction_initial, vhelix_perp_initial)\n    elif origami_he:\n        vhelix_perp_initial = vhelix_rotation_origami_he(vhelix_direction_initial, vhelix_perp_initial)\n\n    slice_sys = base.System([side, side, side])\n    final_sys = base.System([side, side, side])\n    strand_number = -1\n    partner_list_scaf = []\n    partner_list_stap = []\n    found_partner = False\n    join_list_scaf = []\n    join_list_stap = []\n    begin_helix = -1\n    end_helix = -1\n    for h in cadsys.vhelices:\n        h.cad_index = vhelix_counter\n        if origami_sq:\n            strands, helix_angles, pos, rot, vhelix_direction, vhelix_perp = generate_vhelices_origami_sq(vhelix_direction_initial, vhelix_perp_initial, h, sequence_file, single_strand_system, vhelix_counter)\n        elif origami_he:\n            strands, helix_angles, pos, rot, vhelix_direction, vhelix_perp = generate_vhelices_origami_he(vhelix_direction_initial, vhelix_perp_initial, h, sequence_file, single_strand_system, vhelix_counter)\n\n        nodes = build_nodes(h)\n        \n        # read the scaffold squares and add strands to slice_sys\n        i = 0\n        for s in h.scaf:\n            if s.V_0 == -1 and s.b_0 == -1:\n                if s.V_1 == -1 and s.b_0 == -1:\n                    pass\n                elif s.V_1 == h.num and abs(s.b_1 - i) == 1:\n                    if h.num % 2 == 0:\n                        strand_number += 1\n                    begin_helix = i\n                    if h.num % 2 == 1:\n                        slice_sys = add_slice(slice_sys, h, begin_helix, end_helix, nodes, strands, pos, vhelix_direction, vhelix_perp, rot, helix_angles, 0, block_seq, sequences)\n                        vh_vb2nuc = add_slice_nupack(h, strand_number, begin_helix, end_helix, vh_vb2nuc, 2)\n                else:\n                    base.Logger.log(\"unexpected square array\", base.Logger.WARNING)\n            elif s.V_0 == h.num and abs(s.b_0 - i) == 1:\n                if s.V_1 == -1 and s.b_1 == -1:\n                    if h.num % 2 == 1:\n                        strand_number += 1\n                    end_helix = i\n                    if h.num % 2 == 0:\n                        slice_sys = add_slice(slice_sys, h, begin_helix, end_helix, nodes, strands, pos, vhelix_direction, vhelix_perp, rot, helix_angles, 0, block_seq, sequences)\n                        vh_vb2nuc = add_slice_nupack(h, strand_number, begin_helix, end_helix, vh_vb2nuc, 2)\n                elif s.V_1 == h.num and abs(s.b_1 - i) == 1:\n                    pass\n                else:\n                    if h.num % 2 == 1:\n                        strand_number += 1\n                    end_helix = i\n                    if h.num % 2 == 0 :\n                        slice_sys = add_slice(slice_sys, h, begin_helix, end_helix, nodes, strands, pos, vhelix_direction, vhelix_perp, rot, helix_angles, 0, block_seq, sequences)\n                        vh_vb2nuc = add_slice_nupack(h, strand_number, begin_helix, end_helix, vh_vb2nuc, 2)\n\n                    if h.num % 2 == 1:\n                        column = i\n                    else:\n                        column = i\n                    for j in range(len(partner_list_scaf)):\n\n                        if [h.num, column] == partner_list_scaf[j]:\n                            join_list_scaf[j].insert(0, strand_number)\n                            found_partner = True\n                    if found_partner == False:\n                        join_list_scaf.append([strand_number])\n                        partner_list_scaf.append([s.V_1, s.b_1])\n                    found_partner = False\n            else:\n                if s.V_1 == -1 and s.b_1 == -1:\n                    base.Logger.log(\"unexpected square array\", base.Logger.WARNING)\n                elif s.V_1 == h.num and abs(s.b_1 - i) == 1:\n                    if h.num % 2 == 0:\n                        strand_number += 1\n                    begin_helix = i\n                    if h.num % 2 == 1:\n                        slice_sys = add_slice(slice_sys, h, begin_helix, end_helix, nodes, strands, pos, vhelix_direction, vhelix_perp, rot, helix_angles, 0, block_seq, sequences)\n                        vh_vb2nuc = add_slice_nupack(h, strand_number, begin_helix, end_helix, vh_vb2nuc, 2)\n\n                    for j in range(len(partner_list_scaf)):\n                        if h.num % 2 == 1:\n                            column = i\n                        else:\n                            column = i\n                        if [h.num, column] == partner_list_scaf[j]:\n                            join_list_scaf[j].append(strand_number)\n                            found_partner = True\n                    if found_partner == False:\n                        join_list_scaf.append([strand_number])\n                        partner_list_scaf.append([s.V_0, s.b_0])\n                    found_partner = False\n                else:\n                    base.Logger.log(\"unexpected square array\", base.Logger.WARNING)                \n            i += 1\n            \n        if slice_sys.N_strands == 0:\n            base.Logger.log(\"No scaffold strand found in virtual helix n. %d: staples-only virtual helices are not supported\" % h.num, base.Logger.WARNING)\n            continue\n\n        # read the staple squares and add strands to slice_sys\n        i = 0\n        for s in h.stap:\n            if s.V_0 == -1 and s.b_0 == -1:\n                if s.V_1 == -1 and s.b_0 == -1:\n                    pass\n                elif s.V_1 == h.num and abs(s.b_1 - i) == 1:\n                    if h.num % 2 == 1:\n                        strand_number += 1\n                    begin_helix = i\n                    if h.num % 2 == 0:\n                        slice_sys = add_slice(slice_sys, h, begin_helix, end_helix, nodes, strands, pos, vhelix_direction, vhelix_perp, rot, helix_angles, 1, block_seq, sequences)\n                        vh_vb2nuc = add_slice_nupack(h, strand_number, begin_helix, end_helix, vh_vb2nuc, 3)\n                else:\n                    base.Logger.log(\"unexpected square array\", base.Logger.WARNING)\n            elif s.V_0 == h.num and abs(s.b_0 - i) == 1:\n                if s.V_1 == -1 and s.b_1 == -1:\n                    if h.num % 2 == 0:\n                        strand_number += 1\n                    end_helix = i\n                    if h.num % 2 == 1:\n                        slice_sys = add_slice(slice_sys, h, begin_helix, end_helix, nodes, strands, pos, vhelix_direction, vhelix_perp, rot, helix_angles, 1, block_seq, sequences)\n                        vh_vb2nuc = add_slice_nupack(h, strand_number, begin_helix, end_helix, vh_vb2nuc, 3)\n\n                elif s.V_1 == h.num and abs(s.b_1 - i) == 1:\n                    pass\n                else:\n                    if h.num % 2 == 0:\n                        strand_number += 1\n                    end_helix = i\n                    if h.num % 2 == 1:\n                        slice_sys = add_slice(slice_sys, h, begin_helix, end_helix, nodes, strands, pos, vhelix_direction, vhelix_perp, rot, helix_angles, 1, block_seq, sequences)\n                        vh_vb2nuc = add_slice_nupack(h, strand_number, begin_helix, end_helix, vh_vb2nuc, 3)\n\n                    if h.num % 2 == 0:\n                        column = i\n                    else:\n                        column = i\n                    for j in range(len(partner_list_stap)):\n\n                        if [h.num, column] == partner_list_stap[j]:\n                            join_list_stap[j].insert(0, strand_number)\n                            found_partner = True\n                    if found_partner == False:\n                        join_list_stap.append([strand_number])\n                        partner_list_stap.append([s.V_1, s.b_1])\n                    found_partner = False\n            else:\n                if s.V_1 == -1 and s.b_1 == -1:\n                    base.Logger.log(\"unexpected square array\", base.Logger.WARNING)\n                elif s.V_1 == h.num and abs(s.b_1 - i) == 1:\n                    if h.num % 2 == 1:\n                        strand_number += 1\n                    begin_helix = i\n                    if h.num % 2 == 0:\n                        slice_sys = add_slice(slice_sys, h, begin_helix, end_helix, nodes, strands, pos, vhelix_direction, vhelix_perp, rot, helix_angles, 1, block_seq, sequences)\n                        vh_vb2nuc = add_slice_nupack(h, strand_number, begin_helix, end_helix, vh_vb2nuc, 3)\n\n                    for j in range(len(partner_list_stap)):\n                        if h.num % 2 == 0:\n                            column = i\n                        else:\n                            column = i\n                        if [h.num, column] == partner_list_stap[j]:\n                            join_list_stap[j].append(strand_number)\n                            found_partner = True\n                    if found_partner == False:\n                        join_list_stap.append([strand_number])\n                        partner_list_stap.append([s.V_0, s.b_0])\n                    found_partner = False\n                else:\n                    base.Logger.log(\"unexpected square array\", base.Logger.WARNING)                \n            i += 1\n        vhelix_counter += 1\n\n    join_lists = [join_list_scaf, join_list_stap]\n\n    # add strands to final_sys that aren't joined\n    join_list_unpacked = []\n    for a in range(2):\n        for i in join_lists[a]:\n            join_list_unpacked.extend(i)\n    for i in range(len(slice_sys._strands)):\n        if i not in join_list_unpacked:\n            final_sys.add_strand(slice_sys._strands[i], check_overlap=False)\n            vh_vb2nuc_final.add_strand(i, vh_vb2nuc)\n\n    for a in range(2):\n        join_list = join_lists[a]\n        all_are_joined = False\n        restart = False\n\n        # check distance between the backbones we are about to join\n        for pair in join_list:\n            strand1 = slice_sys._strands[pair[0]]\n            strand2 = slice_sys._strands[pair[1]]\n            backbone_backbone_dist = strand1._nucleotides[-1].distance(strand2._nucleotides[0], PBC=False)\n            absolute_bb_dist = np.sqrt(np.dot(backbone_backbone_dist, backbone_backbone_dist))\n            if absolute_bb_dist > 1.0018 or absolute_bb_dist < 0.5525:\n                base.Logger.log(\"the backbone-backbone distance across joints is %f: it will have to be relaxed with preliminary simulations\" % absolute_bb_dist, base.Logger.WARNING)\n\n        # match up all the pairs of joins that involve the same strand\n        circular = []\n        while all_are_joined == False:\n            restart = False\n            for i in range(len(join_list)):\n                if restart == True:\n                    break\n                for j in range(len(join_list)):\n                    if restart == True:\n                        break\n                    if join_list[i][0] == join_list[j][-1]:\n                        if i != j:\n                            join_list[j].extend(join_list[i][1:])\n                            join_list.pop(i)\n                            restart = True\n                            break\n                        else:\n                            if i not in circular:\n                                circular.append(i)\n\n            if restart == False:\n                all_are_joined = True\n\n        # add joined strands\n        for ii, join in enumerate(join_list):\n            joined_strand = slice_sys._strands[join[0]]\n            if ii in circular:\n                for k in range(1, len(join) - 1):\n                    joined_strand = joined_strand.append(slice_sys._strands[join[k]])\n                joined_strand.make_circular(check_join_len=True)\n            else:\n                for k in range(1, len(join)):\n                    joined_strand = joined_strand.append(slice_sys._strands[join[k]])\n                \n            final_sys.add_strand(joined_strand, check_overlap=False)\n\n            # This is a bug fix. Ben 12/2/14\n            # for a circular strand we need to terminate the strand one element early (so reduce the length\n            # of the range by 1), since the final element is just a repeat of the first one.\n            if joined_strand._circular:\n                joining_range = range(len(join) - 2)\n            else:\n                joining_range = range(len(join) - 1)\n            # add joined strands to v2n index\n            for k in joining_range:\n                vh_vb2nuc_final.add_strand(join[k], vh_vb2nuc, continue_join=True)\n            vh_vb2nuc_final.add_strand(join[k + 1], vh_vb2nuc, continue_join=False)\n                \n            if single_strand_system == 1:\n                final_sys._strands[0].set_sequence(sequences[0])\n    \n    if sequence_file and single_strand_system:\n        if len(final_sys._strands) > 1:\n            base.Logger.log(\"more than one strand detected - sequence file will not be read\", base.Logger.WARNING)\n            final_sys._strands[0].set_sequence(np.random.randint(0, 4, len(final_sys._strands[0]._nucleotides)))  # this line does not work\n\n    # # Fix to reverse the direction of every strand so that the 3' to 5' direction is the same\n    # # as in Cadnano. In cadnano the strands point in the 5' to 3' direction, whereas in oxDNA\n    # # they point in the 3' to 5' direction. Ben 29/11/13\n    rev_sys = base.System(final_sys._box)\n    for strand in final_sys._strands:\n        reverse_nucs = [nuc for nuc in strand._nucleotides]\n        reverse_nucs.reverse()\n        rev_strand = base.Strand()\n        for nuc in reverse_nucs:\n            rev_strand.add_nucleotide(base.Nucleotide(nuc.cm_pos, nuc._a1, -nuc._a3, nuc._base, nuc._btype))\n        if strand._circular:\n            rev_strand.make_circular(check_join_len=True)\n        rev_sys.add_strand(rev_strand, check_overlap=False)\n    # # also reverse the vhelix_vbase_to_nucleotide order so it corresponds to the reversed system\n    vh_vb2nuc_rev = cu.vhelix_vbase_to_nucleotide()\n    # count the number of nucleotides up to but not including the nucleotides in strand ii\n    nnucs_to_here = range(rev_sys._N_strands)\n    nuc_total = 0\n    for strandii, strand in enumerate(rev_sys._strands):\n        nnucs_to_here[strandii] = nuc_total\n        nuc_total += len(strand._nucleotides)\n\n    # fill in the _scaf and _stap dicts for the reverse vhelix_vbase_to_nucleotide object\n    for vh, vb in vh_vb2nuc_final._scaf.keys():\n        strandii, nuciis = vh_vb2nuc_final._scaf[(vh, vb)]\n        rev_nuciis = []\n        for nucii in nuciis:\n            rev_nuciis.append(len(rev_sys._strands[strandii]._nucleotides) - 1 - (nucii - nnucs_to_here[strandii]) + nnucs_to_here[strandii])\n        vh_vb2nuc_rev.add_scaf(vh, vb, strandii, rev_nuciis)\n    for vh, vb in vh_vb2nuc_final._stap.keys():\n        strandii, nuciis = vh_vb2nuc_final._stap[(vh, vb)]\n        rev_nuciis = []\n        for nucii in nuciis:\n            rev_nuciis.append(len(rev_sys._strands[strandii]._nucleotides) - 1 - (nucii - nnucs_to_here[strandii]) + nnucs_to_here[strandii])\n        vh_vb2nuc_rev.add_stap(vh, vb, strandii, rev_nuciis)\n        \n    # dump the spatial arrangement of the vhelices to a file\n    vhelix_pattern = {}\n    for i in range(len(cadsys.vhelices)):\n        vhelix_pattern[cadsys.vhelices[i].num] = (cadsys.vhelices[i].row,cadsys.vhelices[i].col)\n        \n    if rev_sys.N == 0:\n        base.Logger.log(\"The generated configuration is empty: this might be due to this conversion module not supporting virtual helices containing no scaffold strands.\", base.Logger.CRITICAL)\n        exit(1)\n\n    if print_virt2nuc:\n        with open(\"virt2nuc\", \"w\") as fout:\n            pickle.dump((vh_vb2nuc_rev, vhelix_pattern), fout)\n            print >> sys.stderr, \"## Wrote nucleotides' index conversion data to virt2nuc\"\n\n    basename = os.path.basename(sys.argv[1])\n    topology_file = basename + \".top\"\n    configuration_file = basename + \".oxdna\"\n    \n    rev_sys.print_lorenzo_output(configuration_file, topology_file)\n    \n    print >> sys.stderr, \"## Wrote data to '%s' / '%s'\" % (configuration_file, topology_file)\n    print >> sys.stderr, \"## DONE\"\n    ", "meta": {"hexsha": "75d24f0448f03b2d7d1ae909e0a46079e3aa2be7", "size": 44830, "ext": "py", "lang": "Python", "max_stars_repo_path": "supporting_scripts/tacoxDNA/src/cadnano_oxDNA.py", "max_stars_repo_name": "ItsTheSebbe/4vHelix_GUI", "max_stars_repo_head_hexsha": "6626d29bf9a2150b2ab49104918ab2faa5f45c30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "supporting_scripts/tacoxDNA/src/cadnano_oxDNA.py", "max_issues_repo_name": "ItsTheSebbe/4vHelix_GUI", "max_issues_repo_head_hexsha": "6626d29bf9a2150b2ab49104918ab2faa5f45c30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "supporting_scripts/tacoxDNA/src/cadnano_oxDNA.py", "max_forks_repo_name": "ItsTheSebbe/4vHelix_GUI", "max_forks_repo_head_hexsha": "6626d29bf9a2150b2ab49104918ab2faa5f45c30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.2525918944, "max_line_length": 250, "alphanum_fraction": 0.5503680571, "include": true, "reason": "import numpy", "num_tokens": 11939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.29746993014852224, "lm_q1q2_score": 0.17965156039292976}}
{"text": "# ------------------------------------------------------------------\n# Compute residual VLM from alt-tg\n# This program has 2 modes:\n# First mode:\n# Compute alt-tg for provisional region list for during TG QC\n# Compute alt-tg for final region list\n# ------------------------------------------------------------------\nimport numpy as np\nfrom netCDF4 import Dataset\nimport os\nimport mod_gentools as gentools\nimport shutil\nimport multiprocessing as mp\nimport ctypes as ct\nimport glob\n\ndef main():\n    set_settings()\n    read_altimetry()\n    set_alttg_list()\n    compute_correlating_points()\n    compute_ts()\n    compute_trend()\n    save_data()\n    return\n\ndef set_settings():\n    print('Define settings...')\n    global settings\n    settings = {}\n    settings['region_selection'] = False # True: read from region_selection list. # False: read from final list\n    settings['select_latest_statlist'] = False\n    settings['test_run_ICE6G_D'] = True\n    settings['years'] = np.arange(1900,2019)\n    settings['min_alt_years'] = 15  # Minimum number of years of overlap between alt/tg required to compute VLM trend\n    settings['min_corr'] = 0.5      # Minimum correlation between altimetry and tide gauge\n    settings['max_dist'] = 300000   # Maximum distance (m) between altimetry grid cell and tide gauge location\n    settings['num_ens']  = 100     # Number of ensembles\n\n    settings['dir_data'] = os.getenv('HOME') + '/Data/'\n    settings['dir_scratch'] = os.getenv('HOME') + '/Scratch/'\n    if os.uname().nodename == 'MT-110180':\n        settings['nproc'] = 4\n        settings['fn_hector'] = os.getenv('HOME') + '/Scripts/Hector/Python/MacOS/est_trend/estimatetrend'\n    else:\n        settings['nproc'] = 40\n        settings['fn_hector'] = os.getenv('HOME') + '/Code/Hector/estimatetrend'\n    settings['dir_budget']  = settings['dir_data'] + 'Budget_20c/'\n\n    if settings['test_run_ICE6G_D']:\n        settings['dir_grd'] = settings['dir_budget'] + 'grd_ICE6G/'\n        settings['fn_gia_rad'] = settings['dir_data']+'GIA/ICE6G_D/ICE6G_D_05.nc'\n        settings['fn_gia_rsl'] = settings['dir_data']+'GIA/ICE6G_D/ICE6G_D_05.nc'\n        settings['probability'] = np.ones(settings['num_ens'])/settings['num_ens']\n    else:\n        settings['dir_grd'] = settings['dir_budget'] + 'grd/'\n        settings['fn_gia_rad'] = settings['dir_data'] + 'GIA/Caron/Ensemble/rad_ens_05.nc'\n        settings['fn_gia_rsl'] = settings['dir_data'] + 'GIA/Caron/Ensemble/rsl_ens_05.nc'\n        settings['probability'] = Dataset(settings['fn_gia_rad'], 'r').variables['probability'][:settings['num_ens']]._get_data()\n        settings['probability'] = settings['probability'] / settings['probability'].sum()\n\n    settings['fn_altimetry'] = settings['dir_budget']+'vlm/Altimetry_annual.nc'\n    settings['fn_station_data'] = settings['dir_budget']+'tg/station_data.npy'\n    settings['fn_regions_for_selection'] = settings['dir_budget']+'tg/regions_for_selection.npy'\n    if settings['region_selection']:\n        print('   MODE: REGION SELECTION')\n        settings['fn_alttg_data'] = settings['dir_budget'] + 'vlm/alttg_for_region_selection.npy'\n    else:\n        print('   MODE: VIRTUAL STATION')\n        if settings['test_run_ICE6G_D']:\n            settings['fn_alttg_data'] = settings['dir_budget'] + 'vlm/alttg_for_virstat_ice6g.npy'\n        else:\n            settings['fn_alttg_data'] = settings['dir_budget'] + 'vlm/alttg_for_virstat.npy'\n        # REGION LIST\n        if settings['select_latest_statlist']:\n            flist = glob.glob(settings['dir_budget']+'region_data/region_list*')\n            cdate = np.zeros(len(flist))\n            for idx, file in enumerate(flist): cdate[idx] = os.path.getmtime(file)\n            settings['fn_region_list'] = flist[np.argmax(cdate)]\n            print(flist[np.argmax(cdate)])\n        else:\n            settings['fn_region_list'] = settings['dir_budget']+'region_data/region_list_beta_march_9.npy'\n    return\n\ndef set_alttg_list():\n    print('Filling alt-tg-information...')\n    global alttg_list, settings\n    alttg_list = {}\n    time_alt_idx = np.in1d(settings['years'],altimetry['time'])\n    if settings['region_selection']: # Read from region_selection\n        regions_for_selection = np.load(settings['fn_regions_for_selection'], allow_pickle=True).all()\n        alttg_list['id']     = regions_for_selection['id'].copy()\n        alttg_list['coords'] = mp_filled_float(regions_for_selection['coords'])\n        alttg_list['height'] = mp_filled_float(regions_for_selection['height_corr'][:,time_alt_idx])\n    else: # Compute merged stations from definitive list\n        station_data = np.load(settings['fn_station_data'], allow_pickle=True).all()\n        region_list  = np.load(settings['fn_region_list'], allow_pickle=True)\n        alttg_id = []\n        alttg_coords = []\n        alttg_height = []\n        for basin in range(len(region_list)):\n            for region in range(len(region_list[basin]['list'])):\n                if 'ALTTG' in region_list[basin]['list'][region]['vlm_id']:\n                    rsl_in_region = np.zeros([len(settings['years']), len(region_list[basin]['list'][region]['id'])])\n                    for station in range(len(region_list[basin]['list'][region]['id'])):\n                        idx = station_data['id'] == region_list[basin]['list'][region]['id'][station]\n                        rsl_in_region[:,station] = station_data['height_corr'][idx,:]\n                        height_lcl = merge_stations_to_region(rsl_in_region)\n                    # Store\n                    alttg_id.append(region_list[basin]['list'][region]['id'])\n                    alttg_coords.append(station_data['coords'][idx])\n                    alttg_height.append(height_lcl)\n        alttg_list['id'] = np.array(alttg_id)\n        alttg_list['coords'] = mp_filled_float(np.array(alttg_coords).squeeze())\n        alttg_list['height'] = mp_filled_float(np.array(alttg_height)[:,time_alt_idx])\n        return\n\ndef compute_correlating_points():\n    global altimetry, alttg_list, settings\n    # ------------------------------------------------------\n    # Determine points in altimetry that correlate with tide\n    # gauge sea level and store for ensemble computation\n    # ------------------------------------------------------\n    print('Computing correlation points...')\n    alttg_list['tg_coords']     = np.zeros([len(alttg_list['id']),2],dtype=int)\n    alttg_list['weight']        = np.zeros(len(alttg_list['id']),dtype=object)\n    alttg_list['has_corr']      = np.zeros(len(alttg_list['id']),dtype=bool)\n    alttg_list['time_acc']      = np.zeros(len(alttg_list['id']),dtype=object)\n    alttg_list['tg_tseries']    = np.zeros(len(alttg_list['id']),dtype=object)\n    alttg_list['alt_coords']    = np.zeros(len(alttg_list['id']),dtype=object)\n    for region in range(len(alttg_list['id'])):\n        time_acc  = np.isfinite(alttg_list['height'][region,:])\n        if time_acc.sum()>settings['min_alt_years']:\n            alttg_list['tg_coords'][region,0] = np.argmin(np.abs(altimetry['lat'] - alttg_list['coords'][region,0]))\n            alttg_list['tg_coords'][region,1] = np.argmin(np.abs(altimetry['lon'] - alttg_list['coords'][region,1]))\n            # Detrend TG and altimetry data set for correlation\n            amat = np.ones([time_acc.sum(),2])\n            amat[:,1] = altimetry['time'][time_acc] - altimetry['time'][time_acc].mean()\n            tg_detrend = alttg_list['height'][region,:][time_acc] - np.matmul(amat,np.linalg.lstsq(amat, alttg_list['height'][region,:][time_acc],rcond=None)[0])\n            # Accepted points\n            distance  = gentools.point_grid_distance(alttg_list['coords'][region,0],alttg_list['coords'][region,1],altimetry['lat'],altimetry['lon'])\n            distance[~altimetry['slm']] = 1e9\n            alt_acc = np.array(np.where(distance < settings['max_dist'])).T\n            corr_array = np.zeros(len(alt_acc))\n            for alt in range(len(alt_acc)):\n                alt_detrend = altimetry['ssh'][:,alt_acc[alt,0],alt_acc[alt,1]][time_acc] - np.matmul(amat, np.linalg.lstsq(amat, altimetry['ssh'][:,alt_acc[alt,0],alt_acc[alt,1]][time_acc], rcond=None)[0])\n                corr_array[alt] = np.corrcoef(alt_detrend,tg_detrend)[0,1]\n            corr_array[np.isnan(corr_array)]=-1\n            if (corr_array>settings['min_corr']).sum()>0:\n                # Compute weight\n                corr_array_flt = corr_array[corr_array>settings['min_corr']]\n                weight = corr_array_flt/corr_array_flt.sum()\n                # Store data\n                alttg_list['has_corr'][region] = True\n                alttg_list['weight'][region] = weight\n                alttg_list['time_acc'][region]   = time_acc\n                alttg_list['alt_coords'][region] = alt_acc[corr_array>settings['min_corr'],:]\n    return\n\ndef compute_ts():\n    global altimetry, alttg_list, alttg_data, settings\n    print('Sampling GIA and GRD at altimetry points...')\n    # --------------------------------------------------------\n    # Compute time series of VLM and residual VLM\n    # vlm_res = Alt - GSL_gia - GSL_pd - TG + RSL_gia + RSL_pd\n    # --------------------------------------------------------\n    alttg_data = {}\n    alttg_data['vlm_ts']    = mp_filled_float(np.zeros([len(alttg_list['id']),len(altimetry['time'])])*np.nan)\n    alttg_data['resvlm_ts'] = mp_filled_float(np.zeros([settings['num_ens'],len(alttg_list['id']),len(altimetry['time'])])*np.nan)\n    # Full VLM time series\n    for region in range(len(alttg_list['has_corr'])):\n        if alttg_list['has_corr'][region]:\n            # vlm_ts_lcl = altimetry - tg: Weighted average of all grid points\n            vlm_ts_lcl = (alttg_list['weight'][region] * (altimetry['ssh'][:,alttg_list['alt_coords'][region][:,0], alttg_list['alt_coords'][region][:,1]] - alttg_list['height'][region,:][:, np.newaxis])).sum(axis=1)\n            alttg_data['vlm_ts'][region] = vlm_ts_lcl - np.nanmean(vlm_ts_lcl)\n    pool = mp.Pool(settings['nproc'])\n    out  = pool.map(resvlm_ts_ens, range(settings['num_ens']))\n    return\n\ndef resvlm_ts_ens(ens):\n    print(ens)\n    global altimetry, alttg_list, alttg_data, settings\n    time_alt_idx = np.in1d(settings['years'],altimetry['time'])\n    GRD = read_GRD_ens(ens, time_alt_idx, settings)\n    GIA = read_GIA_ens(ens,settings)\n    # Dynamic altimetry: altimetry - GSL_GRD - GSL_GIA\n    # Dynamic tide gauge = tide gauge - RSL_GIA - RSL_GRD\n    altimetry_dynamic = altimetry['ssh'] - GIA['gsl'][np.newaxis, :, :] * (altimetry['time'] - altimetry['time'].mean())[:, np.newaxis, np.newaxis] - GRD['gsl']\n    for region in range(len(alttg_list['has_corr'])):\n        if alttg_list['has_corr'][region]:\n            tidegauge_dynamic = alttg_list['height'][region] - GIA['rsl'][alttg_list['tg_coords'][region,0],alttg_list['tg_coords'][region,1]]*(altimetry['time']-altimetry['time'].mean())-GRD['rsl'][:,alttg_list['tg_coords'][region, 0],alttg_list['tg_coords'][region, 1]]\n            residual_vlm_lcl = (alttg_list['weight'][region]*(altimetry_dynamic[:,alttg_list['alt_coords'][region][:,0], alttg_list['alt_coords'][region][:, 1]]-tidegauge_dynamic[:, np.newaxis])).sum(axis=1)\n            alttg_data['resvlm_ts'][ens,region,:] = residual_vlm_lcl\n    return\n\ndef compute_trend():\n    global alttg_list, alttg_data, settings\n    print('Computing ALTTG trends...')\n    alttg_data['vlm_trend']         = mp_filled_float(np.zeros([len(alttg_list['id']),2])*np.nan)\n    alttg_data['resvlm_trend_mean'] = mp_filled_float(np.zeros([len(alttg_list['id']),2])*np.nan)\n    alttg_data['resvlm_trend_ens']  = mp_filled_float(np.zeros([settings['num_ens'],len(alttg_list['id'])])*np.nan)\n\n    alttg_data['resvlm_sterr_AR1'] = mp_filled_float(np.zeros(len(alttg_list['id']))*np.nan)\n    pool = mp.Pool(settings['nproc'])\n    out  = pool.map(compute_trend_indiv, range(len(alttg_list['id'])))\n    return\n\ndef compute_trend_indiv(region):\n    global altimetry, alttg_list, alttg_data, settings\n    if alttg_list['has_corr'][region]:\n        print('   Region ' + str(region))\n        # Trend in VLM\n        alttg_data['vlm_trend'][region,:] = np.array(trend_ar1(region, altimetry['time'][alttg_list['time_acc'][region]], alttg_data['vlm_ts'][region][alttg_list['time_acc'][region]]))\n        # Trend in residual VLM\n        # AR1 trend uncertainty\n        alttg_data['resvlm_trend_mean'][region,:] = np.array(trend_ar1(region, altimetry['time'][alttg_list['time_acc'][region]],  (settings['probability'][:,np.newaxis] * alttg_data['resvlm_ts'][:,region, :]).sum(axis=0)[alttg_list['time_acc'][region]]))\n        alttg_data['resvlm_sterr_AR1'][region] = alttg_data['resvlm_trend_mean'][region,1].copy()\n        amat = np.ones([alttg_list['time_acc'][region].sum(), 2])\n        amat[:, 1] = altimetry['time'][alttg_list['time_acc'][region]] - altimetry['time'][alttg_list['time_acc'][region]].mean()\n        resvlm_ens_mean = np.zeros(settings['num_ens'])\n        for ens in range(settings['num_ens']):\n            resvlm_ens_mean[ens] = np.linalg.lstsq(amat, alttg_data['resvlm_ts'][ens,region, alttg_list['time_acc'][region]], rcond=None)[0][1]\n        alttg_data['resvlm_trend_ens'][:,region] = resvlm_ens_mean\n        resvlm_mn = (settings['probability'] * resvlm_ens_mean).sum()\n        resvlm_se = np.sqrt((settings['probability'] * (resvlm_ens_mean-resvlm_mn)**2).sum())\n        alttg_data['resvlm_trend_mean'][region,1] = np.sqrt(alttg_data['resvlm_sterr_AR1'][region]**2+resvlm_se**2)\n    return\n\ndef save_data():\n    print('Saving data...')\n    global alttg_list, alttg_data, settings\n    acc_idx = np.isfinite(alttg_data['vlm_trend'][:,0])\n    alttg = {}\n    alttg['id'] = alttg_list['id'][acc_idx]\n    alttg['coords'] = alttg_list['coords'][acc_idx,:]\n    alttg['vlm_trend'] = alttg_data['vlm_trend'][acc_idx,:]\n    alttg['resvlm_trend_mean'] = alttg_data['resvlm_trend_mean'][acc_idx,:]\n    alttg['resvlm_trend_ens']  = alttg_data['resvlm_trend_ens'][:,acc_idx]\n    alttg['resvlm_sterr_AR1']  = alttg_data['resvlm_sterr_AR1'][acc_idx]\n    alttg['code'] = np.zeros(acc_idx.sum(),dtype=object)\n    alttg['code'][:] = 'ALTTG'\n    np.save(settings['fn_alttg_data'],alttg)\n    return\n\n### HELPER FUNCTIONS\n# def read_GIA(settings):\n#     print('Reading GIA...')\n#     global GIA\n#     GIA = {}\n#     file_handle = Dataset(settings['fn_gia_rad'], 'r')\n#     file_handle.set_auto_mask(False)\n#     GIA['lat'] =  mp_filled_float(file_handle.variables['y'][:])\n#     GIA['lon'] =  mp_filled_float(file_handle.variables['x'][:])\n#     GIA['probability'] = mp_filled_float(file_handle.variables['probability'][:settings['num_ens']])\n#     GIA['probability'] = GIA['probability']/GIA['probability'].sum()\n#     GIA['rad'] = mp_filled_float(file_handle.variables['rad'][:settings['num_ens'],:,:])\n#     file_handle.close()\n#\n#     file_handle = Dataset(settings['fn_gia_rsl'], 'r')\n#     file_handle.set_auto_mask(False)\n#     GIA['rsl'] = mp_filled_float(file_handle.variables['rsl'][:settings['num_ens'],:,:])\n#     file_handle.close()\n#     GIA['gsl'] = mp_filled_float(GIA['rad'] + GIA['rsl'])\n#     return\n\ndef read_GIA_ens(ens,settings):\n    GIA = {}\n    # radial deformation\n    file_handle = Dataset(settings['fn_gia_rad'], 'r')\n    file_handle.set_auto_mask(False)\n    if settings['test_run_ICE6G_D']:\n        GIA['rad'] = file_handle.variables['rad'][:]\n    else:\n        GIA['rad'] = file_handle.variables['rad'][ens,:,:]\n    # rsl\n    file_handle = Dataset(settings['fn_gia_rsl'], 'r')\n    file_handle.set_auto_mask(False)\n    if settings['test_run_ICE6G_D']:\n        GIA['rsl'] = file_handle.variables['RSL'][:]\n    else:\n        GIA['rsl'] = file_handle.variables['rsl'][ens,:,:]\n    file_handle.close()\n    #gsl\n    GIA['gsl'] = mp_filled_float(GIA['rad'] + GIA['rsl'])\n    return(GIA)\n\ndef read_GRD_ens(ens,time_alt_idx,settings):\n    file_handle = Dataset(settings['dir_grd']+'grd_'+str(ens)+'.nc', 'r')\n    file_handle.set_auto_mask(False)\n    PD = {}\n    PD['rad'] = file_handle.variables['rad'][time_alt_idx,:,:]\n    PD['rsl'] = file_handle.variables['rsl'][time_alt_idx,:,:]\n    PD['gsl'] = PD['rad'] + PD['rsl']\n    file_handle.close()\n    return(PD)\n\ndef read_altimetry():\n    print('Reading altimetry...')\n    global altimetry, settings\n    altimetry = {}\n    file_handle = Dataset(settings['fn_altimetry'], 'r')\n    file_handle.set_auto_mask(False)\n    altimetry['lat']  =  mp_filled_float(file_handle.variables['y'][:])\n    altimetry['lon']  =  mp_filled_float(file_handle.variables['x'][:])\n    altimetry['time'] =  mp_filled_float(file_handle.variables['t'][:])\n    altimetry['ssh'] = mp_filled_float(file_handle.variables['z'][:])\n    file_handle.close()\n    altimetry['slm'] = mp_filled_bool(np.isfinite(altimetry['ssh'][-1,:,:]))\n    return\n\ndef trend_ar1(region,time,tseries):\n    global settings\n    # Determine trend and associated uncertainty (AR1) using Hector\n    # 1. Save settings\n    dir_lcl = settings['dir_scratch']+str(region)+'/'\n    if not os.path.isdir(dir_lcl):\n        os.mkdir(dir_lcl)\n    config_list = []\n    config_list.append('DataFile input.mom\\n')\n    config_list.append('DataDirectory ./\\n')\n    config_list.append('OutputFile trend.out\\n')\n    config_list.append('interpolate no\\n')\n    config_list.append('firstdifference no\\n')\n    config_list.append('PhysicalUnit m\\n')\n    config_list.append('DegreePolynomial 1\\n')\n    config_list.append('seasonalsignal no\\n')\n    config_list.append('halfseasonalsignal no\\n')\n    config_list.append('estimateoffsets no\\n')\n    config_list.append('NoiseModels ARMA White\\n')\n    config_list.append('AR_p 1\\n')\n    config_list.append('MA_q 0\\n')\n    config_list.append('RandomiseFirstGuess yes\\n')\n    open(dir_lcl+'estimatetrend.ctl','w+').writelines(config_list)\n    out = shutil.copy2(settings['fn_hector'],dir_lcl) # Copy Hector executable to scratch\n    tseries = tseries - tseries.mean()\n    mjd = 365.25 * (time-time[0])\n    sample_period = np.min(np.diff(mjd))\n    headerline = 'sampling period '+str(sample_period)\n    np.savetxt(dir_lcl+'input.mom', np.transpose([mjd, tseries]), fmt=['%.4f', '%.4f'], header=headerline)\n    os.chdir(dir_lcl)\n    os.system(dir_lcl + 'estimatetrend >' + dir_lcl + 'output_orig.txt')\n    output_data = [line.rstrip('\\n') for line in open(dir_lcl + 'output_orig.txt')]\n    trend_str = next((s for s in output_data if 'trend: ' in s), None)\n    trend_mean = float(trend_str.split()[1])\n    trend_sterr = float(trend_str.split()[3])\n    os.chdir(os.getenv('HOME')+'/Scripts/Python/')\n    return(trend_mean,trend_sterr)\n\ndef merge_stations_to_region(rsl_in_region):\n    while rsl_in_region.shape[1]>1:\n        # Find max number of overlaps\n        n_ovl = np.zeros([rsl_in_region.shape[1],rsl_in_region.shape[1]],dtype=int)\n        for i in range(rsl_in_region.shape[1]):\n            for j in range(rsl_in_region.shape[1]):\n                if i>j: n_ovl[i,j] = np.isfinite(rsl_in_region[:,i]*rsl_in_region[:,j]).sum()\n        merge_idx = np.unravel_index(np.argmax(n_ovl),n_ovl.shape)\n        merge_array_lcl = rsl_in_region[:,merge_idx]\n        merge_array_lcl = gentools.merge_common_mean(merge_array_lcl)\n        rsl_in_region = np.hstack([rsl_in_region,merge_array_lcl[:,np.newaxis]])\n        rsl_in_region = np.delete(rsl_in_region,merge_idx,axis=1)\n    rsl_in_region = rsl_in_region.flatten()\n    return(rsl_in_region)\n\n# Parallel processing routines\ndef mp_empty_float(shape):\n    shared_array_base = mp.RawArray(ct.c_float, int(np.prod(shape)))\n    shared_array = np.ctypeslib.as_array(shared_array_base).reshape(*shape)\n    return shared_array\n\ndef mp_empty_int(shape):\n    shared_array_base = mp.RawArray(ct.c_int, int(np.prod(shape)))\n    shared_array = np.ctypeslib.as_array(shared_array_base).reshape(*shape)\n    return shared_array\n\ndef mp_filled_float(input_array):\n    shape = input_array.shape\n    shared_array_base = mp.RawArray(ct.c_float, input_array.flatten())\n    shared_array = np.ctypeslib.as_array(shared_array_base).reshape(*shape)\n    return shared_array\n\ndef mp_filled_bool(input_array):\n    shape = input_array.shape\n    shared_array_base = mp.RawArray(ct.c_bool, input_array.flatten())\n    shared_array = np.ctypeslib.as_array(shared_array_base).reshape(*shape)\n    return shared_array\n\nif __name__ == '__main__':\n    main()", "meta": {"hexsha": "8d83dd53063628b67c12b59b8b36f3028bf29921", "size": 20218, "ext": "py", "lang": "Python", "max_stars_repo_path": "vlm/vlm_alt_tg.py", "max_stars_repo_name": "thomasfrederikse/sealevelbudget_20c", "max_stars_repo_head_hexsha": "eb3155da7255cd7e17cd574464e730b6ba16cb7d", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2020-08-19T21:32:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T12:35:42.000Z", "max_issues_repo_path": "vlm/vlm_alt_tg.py", "max_issues_repo_name": "thomasfrederikse/sealevelbudget_20c", "max_issues_repo_head_hexsha": "eb3155da7255cd7e17cd574464e730b6ba16cb7d", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-09T08:51:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-09T08:51:00.000Z", "max_forks_repo_path": "vlm/vlm_alt_tg.py", "max_forks_repo_name": "thomasfrederikse/sealevelbudget_20c", "max_forks_repo_head_hexsha": "eb3155da7255cd7e17cd574464e730b6ba16cb7d", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.1082474227, "max_line_length": 271, "alphanum_fraction": 0.6496686121, "include": true, "reason": "import numpy", "num_tokens": 5568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.17958974228984034}}
{"text": "# -*- coding: utf-8 -*-\n__author__ = \"Konstantin Klementiev\", \"Roman Chernikov\"\n__date__ = \"4 Oct 2021\"\nimport numpy as np\nimport pickle\nfrom .. import raycing\n\ndefaultEnergy = 9.0e3\nallArguments = ('bl', 'name', 'center', 'pitch', 'yaw', 'nrays',\n                'eE', 'eI', 'eEspread', 'eSigmaX', 'eSigmaZ',\n                'eEpsilonX', 'eEpsilonZ', 'betaX', 'betaZ',\n                'distx', 'dx', 'disty', 'dy', 'distz', 'dz',\n                'distxprime', 'dxprime', 'distzprime', 'dzprime',\n                'xPrimeMax', 'zPrimeMax', 'minxprime', 'maxxprime',\n                'minzprime', 'maxzprime',\n                'xPrimeMaxAutoReduce', 'zPrimeMaxAutoReduce',\n                'distE', 'energies', 'targetE', 'eMin', 'eMax', 'eN',\n                'B0', 'rho', 'K', 'Kx', 'Ky', 'period',\n                'n', 'phaseDeg', 'taper', 'R0',\n                'polarization', 'filamentBeam',\n                'uniformRayDensity', 'nx', 'nz', 'withCentralRay',\n                'autoAppendToBL', 'customField', 'gp', 'gIntervals', 'nRK',\n                'targetOpenCL', 'precisionOpenCL')\n\n\nclass BeamProxy(object):\n    \"\"\"An empty object to attach fields to it. With a simple instance of\n    object() this is impossible but doable with an empty class.\"\"\"\n    basicAttrs = ['x', 'y', 'z', 'a', 'b', 'c', 'state', 'E', 'path',\n                  'Es', 'Ep', 'Jss', 'Jpp', 'Jsp']\n    # farAttrs = ['a', 'b', 'c', 'state', 'E', 'path',\n    #             'Es', 'Ep', 'Jss', 'Jpp', 'Jsp']\n\n    def __init__(self, copyFrom=None):\n        if copyFrom is None:\n            return\n        for attr in self.basicAttrs:\n            setattr(self, attr, np.copy(getattr(copyFrom, attr)))\n\n    # def filter_by_index(self, indarr):\n    #     for attr in self.farAttrs:\n    #         setattr(self, attr, np.copy(getattr(self, attr))[indarr])\n\n\nclass Beam(object):\n    \"\"\"Container for the beam arrays. *x, y, z* give the starting points.\n    *a, b, c* give normalized vectors of ray directions (the source must take\n    care about the normalization). *E* is energy. *Jss*, *Jpp* and *Jsp* are\n    the components  of the coherency matrix. The latter one is complex. *Es*\n    and *Ep* are *s* and *p* field amplitudes (not always used). *path* is the\n    total path length from the source to the last impact point. *theta* is the\n    incidence angle. *order* is the order of grating diffraction. If multiple\n    reflections are considered: *nRefl* is the number of reflections,\n    *elevationD* is the maximum elevation distance between the rays and the\n    surface as the ray travels from one impact point to the next one,\n    *elevationX*, *elevationY*, *elevationZ* are the coordinates of the\n    highest elevation points. If an OE uses a parametric representation,\n    *s*, *phi*, *r* arrays store the impact points in the parametric\n    coordinates.\n    \"\"\"\n    listOfAttrs = ['x', 'y', 'z', 'sourceSIGMAx', 'sourceSIGMAz',\n                   'filamentDX', 'filamentDZ', 'filamentDtheta',\n                   'filamentDpsi', 'filamentDgamma',\n                   'state', 'a', 'b', 'c', 'path',\n                   'E', 'Jss', 'Jpp', 'Jsp', 'elevationD',\n                   'elevationX', 'elevationY', 'elevationZ', 's',\n                   'phi', 'r', 'theta', 'order', 'accepted',\n                   'acceptedE', 'seeded', 'seededI', 'Es', 'Ep',\n                   # 'area',\n                   'nRefl']\n\n    def __init__(self, nrays=raycing.nrays, copyFrom=None, forceState=False,\n                 withNumberOfReflections=False, withAmplitudes=False,\n                 xyzOnly=False, bl=None):\n        # if type(copyFrom) == type(self):\n        if hasattr(copyFrom, 'a') and hasattr(copyFrom, 'x'):\n            try:\n                for attr in self.listOfAttrs:\n                    if hasattr(copyFrom, attr):\n                        setattr(self, attr, np.copy(getattr(copyFrom, attr)))\n#                if not withNumberOfReflections and hasattr(self, 'nRefl'):\n#                    delattr(self, 'nRefl')\n            except:\n                print(\"Can't copy beam from\", copyFrom)\n                copyFrom = None\n        elif isinstance(copyFrom, raycing.basestring):\n            try:\n                if copyFrom.endswith('mat'):\n                    import scipy.io as io\n                    self.__dict__.update(io.loadmat(copyFrom))\n                elif copyFrom.endswith('npy'):\n                    self.__dict__.update(np.load(copyFrom).item())\n                else:\n                    pickleFile = open(copyFrom, 'rb')\n                    self.__dict__.update(pickle.load(pickleFile))\n                    pickleFile.close()\n                for key in ['fromOE', 'toOE', 'parentId']:\n                    if hasattr(self, key):\n                        if bl is not None:\n                            try:\n                                setattr(self, key, bl.oesDict[getattr(\n                                    self, key)][0])\n                            except:\n                                print(\"OEs cannot be resolved. This can cause errors in wave propagation routine.\")  # analysis:ignore\n                                continue\n                        else:\n                            print(getattr(self, key), \"cannot be resolved. Please provide the beamLine instance.\")  # analysis:ignore\n\n            except:\n                print(\"Can't load beam object from\", copyFrom)\n                copyFrom = None\n                raise\n        elif copyFrom is None:\n            # coordinates of starting points\n            nrays = np.long(nrays)\n            self.x = np.zeros(nrays)\n            self.y = np.zeros(nrays)\n            self.z = np.zeros(nrays)\n            if not xyzOnly:\n                self.sourceSIGMAx = 0.\n                self.sourceSIGMAz = 0.\n                self.filamentDtheta = 0.\n                self.filamentDpsi = 0.\n                self.filamentDgamma = 0.\n                self.filamentDX = 0.\n                self.filamentDZ = 0.\n                self.state = np.zeros(nrays, dtype=np.int)\n                # components of direction\n                self.a = np.zeros(nrays)\n                self.b = np.ones(nrays)\n                self.c = np.zeros(nrays)\n                # total ray path\n                self.path = np.zeros(nrays)\n                # energy\n                self.E = np.ones(nrays) * defaultEnergy\n                # components of coherency matrix\n                self.Jss = np.ones(nrays)\n                self.Jpp = np.zeros(nrays)\n                self.Jsp = np.zeros(nrays, dtype=complex)\n                if withAmplitudes:\n                    self.Es = np.zeros(nrays, dtype=complex)\n                    self.Ep = np.zeros(nrays, dtype=complex)\n        if type(forceState) == int:\n            self.state[:] = forceState\n\n    def export_beam(self, fileName, fformat='npy'):\n        \"\"\"Saves the *beam* to a binary file. File format can be Numpy 'npy',\n        Matlab 'mat' or python 'pickle'. Matlab format should not be used for\n        future imports in xrt as it does not allow correct load.\"\"\"\n        outputDict = dict()\n        outputDict.update(self.__dict__)\n        for key in ['fromOE', 'toOE', 'parentId']:\n            if hasattr(self, key):\n                try:\n                    outputDict[key] = getattr(self, key).name\n                except:\n                    continue\n\n        if str(fformat).lower() in ['npy', 'np', 'numpy']:  # numpy compress\n            try:\n                if not fileName.endswith('npy'):\n                    fileName += '.npy'\n                np.save(fileName, outputDict)\n            except:\n                print(\"Can't save the beam to\", str(fileName))\n        elif str(fformat).lower()in ['mat', 'matlab']:  # Matlab *.mat\n            try:\n                import scipy.io as io\n                if not fileName.endswith('mat'):\n                    fileName += '.mat'\n                io.savemat(fileName, outputDict)\n            except:\n                print(\"Can't save the beam to\", str(fileName))\n        else:  # pickle\n            try:\n                if not fileName.endswith('pickle'):\n                    fileName += '.pickle'\n                f = open(fileName, 'wb')\n                pickle.dump(outputDict, f, protocol=2)\n                f.close()\n            except:\n                print(\"Can't save the beam to\", str(fileName))\n\n    def concatenate(self, beam):\n        \"\"\"Adds *beam* to *self*. Useful when more than one source is\n        presented.\"\"\"\n        self.state = np.concatenate((self.state, beam.state))\n        self.x = np.concatenate((self.x, beam.x))\n        self.y = np.concatenate((self.y, beam.y))\n        self.z = np.concatenate((self.z, beam.z))\n        self.a = np.concatenate((self.a, beam.a))\n        self.b = np.concatenate((self.b, beam.b))\n        self.c = np.concatenate((self.c, beam.c))\n        self.path = np.concatenate((self.path, beam.path))\n        self.E = np.concatenate((self.E, beam.E))\n        self.Jss = np.concatenate((self.Jss, beam.Jss))\n        self.Jpp = np.concatenate((self.Jpp, beam.Jpp))\n        self.Jsp = np.concatenate((self.Jsp, beam.Jsp))\n        if hasattr(self, 'nRefl') and hasattr(beam, 'nRefl'):\n            self.nRefl = np.concatenate((self.nRefl, beam.nRefl))\n        if hasattr(self, 'elevationD') and hasattr(beam, 'elevationD'):\n            self.elevationD = np.concatenate(\n                (self.elevationD, beam.elevationD))\n            self.elevationX = np.concatenate(\n                (self.elevationX, beam.elevationX))\n            self.elevationY = np.concatenate(\n                (self.elevationY, beam.elevationY))\n            self.elevationZ = np.concatenate(\n                (self.elevationZ, beam.elevationZ))\n        if hasattr(self, 's') and hasattr(beam, 's'):\n            self.s = np.concatenate((self.s, beam.s))\n        if hasattr(self, 'phi') and hasattr(beam, 'phi'):\n            self.phi = np.concatenate((self.phi, beam.phi))\n        if hasattr(self, 'r') and hasattr(beam, 'r'):\n            self.r = np.concatenate((self.r, beam.r))\n        if hasattr(self, 'theta') and hasattr(beam, 'theta'):\n            self.theta = np.concatenate((self.theta, beam.theta))\n        if hasattr(self, 'order') and hasattr(beam, 'order'):\n            self.order = np.concatenate((self.order, beam.order))\n        if hasattr(self, 'accepted') and hasattr(beam, 'accepted'):\n            seeded = self.seeded + beam.seeded\n            self.accepted = (self.accepted / self.seeded +\n                             beam.accepted / beam.seeded) * seeded\n            self.acceptedE = (self.acceptedE / self.seeded +\n                              beam.acceptedE / beam.seeded) * seeded\n            self.seeded = seeded\n            self.seededI = self.seededI + beam.seededI\n        if hasattr(self, 'Es') and hasattr(beam, 'Es'):\n            self.Es = np.concatenate((self.Es, beam.Es))\n            self.Ep = np.concatenate((self.Ep, beam.Ep))\n\n    def filter_by_index(self, indarr):\n        self.state = self.state[indarr]\n        self.x = self.x[indarr]\n        self.y = self.y[indarr]\n        self.z = self.z[indarr]\n        self.a = self.a[indarr]\n        self.b = self.b[indarr]\n        self.c = self.c[indarr]\n        self.path = self.path[indarr]\n        self.E = self.E[indarr]\n        self.Jss = self.Jss[indarr]\n        self.Jpp = self.Jpp[indarr]\n        self.Jsp = self.Jsp[indarr]\n        if hasattr(self, 'nRefl'):\n            self.nRefl = self.nRefl[indarr]\n        if hasattr(self, 'elevationD'):\n            self.elevationD = self.elevationD[indarr]\n            self.elevationX = self.elevationX[indarr]\n            self.elevationY = self.elevationY[indarr]\n            self.elevationZ = self.elevationZ[indarr]\n        if hasattr(self, 's'):\n            self.s = self.s[indarr]\n        if hasattr(self, 'phi'):\n            self.phi = self.phi[indarr]\n        if hasattr(self, 'r'):\n            self.r = self.r[indarr]\n        if hasattr(self, 'theta'):\n            self.theta = self.theta[indarr]\n        if hasattr(self, 'order'):\n            self.order = self.order[indarr]\n        if hasattr(self, 'Es'):\n            self.Es = self.Es[indarr]\n            self.Ep = self.Ep[indarr]\n        return self\n\n    def replace_by_index(self, indarr, beam):\n        self.state[indarr] = beam.state[indarr]\n        self.x[indarr] = beam.x[indarr]\n        self.y[indarr] = beam.y[indarr]\n        self.z[indarr] = beam.z[indarr]\n        self.a[indarr] = beam.a[indarr]\n        self.b[indarr] = beam.b[indarr]\n        self.c[indarr] = beam.c[indarr]\n        self.path[indarr] = beam.path[indarr]\n        self.E[indarr] = beam.E[indarr]\n        self.Jss[indarr] = beam.Jss[indarr]\n        self.Jpp[indarr] = beam.Jpp[indarr]\n        self.Jsp[indarr] = beam.Jsp[indarr]\n        if hasattr(self, 'nRefl') and hasattr(beam, 'nRefl'):\n            self.nRefl[indarr] = beam.nRefl[indarr]\n        if hasattr(self, 'elevationD') and hasattr(beam, 'elevationD'):\n            self.elevationD[indarr] = beam.elevationD[indarr]\n            self.elevationX[indarr] = beam.elevationX[indarr]\n            self.elevationY[indarr] = beam.elevationY[indarr]\n            self.elevationZ[indarr] = beam.elevationZ[indarr]\n        if hasattr(self, 's') and hasattr(beam, 's'):\n            self.s[indarr] = beam.s[indarr]\n        if hasattr(self, 'phi') and hasattr(beam, 'phi'):\n            self.phi[indarr] = beam.phi[indarr]\n        if hasattr(self, 'r') and hasattr(beam, 'r'):\n            self.r[indarr] = beam.r[indarr]\n        if hasattr(self, 'theta') and hasattr(beam, 'theta'):\n            self.theta[indarr] = beam.theta[indarr]\n        if hasattr(self, 'order') and hasattr(beam, 'order'):\n            self.order[indarr] = beam.order[indarr]\n        if hasattr(self, 'Es') and hasattr(beam, 'Es'):\n            self.Es[indarr] = beam.Es[indarr]\n        if hasattr(self, 'Ep') and hasattr(beam, 'Ep'):\n            self.Ep[indarr] = beam.Ep[indarr]\n        return self\n\n    def filter_good(self):\n        return self.filter_by_index(self.state == 1)\n\n    def absorb_intensity(self, inBeam, sign=1):\n        self.Jss = (inBeam.Jss - self.Jss) * sign\n        self.Jpp = (inBeam.Jpp - self.Jpp) * sign\n        self.Jsp = (inBeam.Jsp - self.Jsp) * sign\n        self.displayAsAbsorbedPower = True\n\n    def add_wave(self, wave, sign=1):\n        self.Es += sign*wave.Es\n        self.Ep += sign*wave.Ep\n        self.Jss = (self.Es * self.Es.conjugate()).real\n        self.Jpp = (self.Ep * self.Ep.conjugate()).real\n        self.Jsp = self.Es * self.Ep.conjugate()\n\n    def project_energy_to_band(self, EnewMin, EnewMax):\n        \"\"\"Uniformly projects the energy array self.E to a new band determined\n        by *EnewMin* and *EnewMax*. This function is useful for simultaneous\n        ray tracing of white beam and monochromatic beam parts of a beamline.\n        \"\"\"\n        EoldMin = np.min(self.E)\n        EoldMax = np.max(self.E)\n        if EoldMin >= EoldMax:\n            return\n        self.E[:] = EnewMin +\\\n            (self.E-EoldMin) / (EoldMax-EoldMin) * (EnewMax-EnewMin)\n\n    def make_uniform_energy_band(self, EnewMin, EnewMax):\n        \"\"\"Makes a uniform energy distribution. This function is useful for\n        simultaneous ray tracing of white beam and monochromatic beam parts of\n        a beamline.\n        \"\"\"\n        self.E[:] = np.random.uniform(EnewMin, EnewMax, len(self.E))\n\n    def diffract(self, wave):\n        from . import waves as rw\n        return rw.diffract(self, wave)\n\n\ndef copy_beam(\n        beamTo, beamFrom, indarr, includeState=False, includeJspEsp=True):\n    \"\"\"Copies arrays of *beamFrom* to arrays of *beamTo*. The slicing of the\n    arrays is given by *indarr*.\"\"\"\n    beamTo.x[indarr] = beamFrom.x[indarr]\n    beamTo.y[indarr] = beamFrom.y[indarr]\n    beamTo.z[indarr] = beamFrom.z[indarr]\n    beamTo.a[indarr] = beamFrom.a[indarr]\n    beamTo.b[indarr] = beamFrom.b[indarr]\n    beamTo.c[indarr] = beamFrom.c[indarr]\n    beamTo.path[indarr] = beamFrom.path[indarr]\n    beamTo.E[indarr] = beamFrom.E[indarr]\n    if includeState:\n        beamTo.state[indarr] = beamFrom.state[indarr]\n    if hasattr(beamFrom, 'nRefl') and hasattr(beamTo, 'nRefl'):\n        beamTo.nRefl[indarr] = beamFrom.nRefl[indarr]\n    if hasattr(beamFrom, 'order'):\n        beamTo.order = beamFrom.order\n    if hasattr(beamFrom, 'elevationD') and hasattr(beamTo, 'elevationD'):\n        beamTo.elevationD[indarr] = beamFrom.elevationD[indarr]\n        beamTo.elevationX[indarr] = beamFrom.elevationX[indarr]\n        beamTo.elevationY[indarr] = beamFrom.elevationY[indarr]\n        beamTo.elevationZ[indarr] = beamFrom.elevationZ[indarr]\n    if hasattr(beamFrom, 'accepted'):\n        beamTo.accepted = beamFrom.accepted\n        beamTo.acceptedE = beamFrom.acceptedE\n        beamTo.seeded = beamFrom.seeded\n        beamTo.seededI = beamFrom.seededI\n    if hasattr(beamTo, 'area'):\n        beamTo.area = beamFrom.area\n    if includeJspEsp:\n        beamTo.Jss[indarr] = beamFrom.Jss[indarr]\n        beamTo.Jpp[indarr] = beamFrom.Jpp[indarr]\n        beamTo.Jsp[indarr] = beamFrom.Jsp[indarr]\n        if hasattr(beamFrom, 'Es') and hasattr(beamTo, 'Es'):\n            beamTo.Es[indarr] = beamFrom.Es[indarr]\n            beamTo.Ep[indarr] = beamFrom.Ep[indarr]\n\n\ndef rotate_coherency_matrix(beam, indarr, roll):\n    r\"\"\"Rotates the coherency matrix :math:`J`:\n\n    .. math::\n\n        J = \\left( \\begin{array}{ccc}\n        J_{ss} & J_{sp} \\\\\n        J^*_{sp} & J_{pp}\\end{array} \\right)\n\n    by angle :math:`\\phi` around the beam direction as :math:`J' = R_{\\phi}\n    J R^{-1}_{\\phi}` with the rotation matrix :math:`R_{\\phi}` defined as:\n\n    .. math::\n\n        R_{\\phi} = \\left( \\begin{array}{ccc}\n        \\cos{\\phi} & \\sin{\\phi} \\\\\n        -\\sin{\\phi} & \\cos{\\phi}\\end{array} \\right)\n    \"\"\"\n#    if (roll == 0).all():\n#        return beam.Jss[indarr], beam.Jpp[indarr], beam.Jsp[indarr]\n    c = np.cos(roll)\n    s = np.sin(roll)\n    c2 = c**2\n    s2 = s**2\n    cs = c * s\n    JssN = beam.Jss[indarr]*c2 + beam.Jpp[indarr]*s2 +\\\n        2*beam.Jsp[indarr].real*cs\n    JppN = beam.Jss[indarr]*s2 + beam.Jpp[indarr]*c2 -\\\n        2*beam.Jsp[indarr].real*cs\n    JspN = (beam.Jpp[indarr]-beam.Jss[indarr])*cs +\\\n        beam.Jsp[indarr].real*(c2-s2) + beam.Jsp[indarr].imag*1j\n    return JssN, JppN, JspN\n", "meta": {"hexsha": "ed5bc8f8c12076dfec9bba5d67eee616cef98ca0", "size": 18242, "ext": "py", "lang": "Python", "max_stars_repo_path": "xrt/backends/raycing/sources_beams.py", "max_stars_repo_name": "kklmn/xrt", "max_stars_repo_head_hexsha": "fe0f17fe712a84bc7dbbf5d807969630c9bddbde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71, "max_stars_repo_stars_event_min_datetime": "2016-07-04T06:40:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T10:03:07.000Z", "max_issues_repo_path": "xrt/backends/raycing/sources_beams.py", "max_issues_repo_name": "kklmn/xrt", "max_issues_repo_head_hexsha": "fe0f17fe712a84bc7dbbf5d807969630c9bddbde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 99, "max_issues_repo_issues_event_min_datetime": "2016-07-10T16:39:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T07:50:10.000Z", "max_forks_repo_path": "xrt/backends/raycing/sources_beams.py", "max_forks_repo_name": "kklmn/xrt", "max_forks_repo_head_hexsha": "fe0f17fe712a84bc7dbbf5d807969630c9bddbde", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2016-07-08T17:12:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T06:54:21.000Z", "avg_line_length": 44.0628019324, "max_line_length": 134, "alphanum_fraction": 0.5526258086, "include": true, "reason": "import numpy,import scipy", "num_tokens": 4785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.33807711081162, "lm_q1q2_score": 0.17958973018625063}}
{"text": "# This file is part of LayerModel_lib\n#\n#     A tool to compute the transmission behaviour of plane electromagnetic waves\n#     through human tissue.\n#\n# Copyright (C) 2018 Jan-Christoph Brumm\n#\n# Licensed under MIT license.\n#\nimport numpy as np\nimport os\n\nfrom LayerModel_lib.voxelmodel import VoxelModel\nfrom LayerModel_lib.voxelmodel_importer import VoxelModelImporter\nfrom LayerModel_lib.coordinate import Coordinate\n\ncurrent_directory = os.path.dirname(__file__)\nbase_path = os.path.join(current_directory, '..', '..', '..', '..', '..', 'Numerical Human Phantoms', 'Frank')\n\n# path to the AVW File of this model\nfilename = os.path.join(base_path, 'segm_frank')\n# path to the tissue_mapping file\ntissue_file = os.path.join('ImportFrank_tissues.txt')\n\nAVW_Data = VoxelModelImporter(filename, tissue_file, 'AVW')\nmodel_orig = AVW_Data.data['image']\ntissue_name_orig = AVW_Data.tissue_names\ntissue_mapping = AVW_Data.tissue_mapping\n\nFrank = VoxelModel()\nFrank.show_progress_bar = True\n\n# needs to be set manually from README.txt\nFrank.set_scale(0.742188, 0.742188, 5)\n\nFrank.name = 'Frank'\nFrank.description = 'Frank model from the Helmholtz Zentrum München. ' \\\n                    'Resolution %.2fmm x %.2fmm x %.2fmm' % (Frank.scaling.x,\n                                                             Frank.scaling.y, Frank.scaling.z)\n\n# For some reason Frank needs to be shifted back circularly\nmodel_orig = np.vstack((model_orig[25::, :, :], model_orig[0:25, :, :]))\n\n#  Calculate the outer_shape of the original and the complete model\nouter_shape = AVW_Data.calculate_outer_shape(model_orig, tissue_mapping)\n\nFrank.add_voxel_data(short_name='original',\n                     name='Original data from AVW file',\n                     model=model_orig,\n                     outer_shape=outer_shape,\n                     tissue_names=tissue_name_orig)\n\nFrank.add_voxel_data(short_name='complete',\n                     name='The \\'original\\' model converted to our TissueProperties.',\n                     model=Frank.models['original'].data,\n                     outer_shape=outer_shape,\n                     tissue_mapping=tissue_mapping)\n\n# Calculate the trunk model\nstart_slice = int(0)\nend_slice = int(110)\n\n(model_trunk, trunk_mask) = AVW_Data.calculate_trunk_model(Frank, 'complete', z_start=start_slice, z_end=end_slice)\nouter_shape_trunk = AVW_Data.calculate_outer_shape(model_trunk)\n\nFrank.add_voxel_data(short_name='trunk',\n                     name=\"The trunk of the 'complete' model. Arms have been removed using \"\n                          \"VoxelModel.remove_arms().\",\n                     outer_shape=outer_shape_trunk,\n                     model=model_trunk,\n                     mask=trunk_mask,\n                     tissue_mapping=None)\n\nsurface = Frank.create_3d_model(model_type='trunk', patch_size=(30, 30))\nFrank.models['trunk'].surface_3d = surface\n\nFrank.models['trunk'].endpoints = []\nfor (i, s) in enumerate(surface):\n    Frank.models['trunk'].endpoints.append(Coordinate(np.array(s['centroid'])))\n\nFrank.save_model()\n", "meta": {"hexsha": "33a05a7a49a81e20d17442687cc2b12dcabadc72", "size": 3043, "ext": "py", "lang": "Python", "max_stars_repo_path": "phantom_import/ImportFrank.py", "max_stars_repo_name": "janbrumm/layermodel_lib", "max_stars_repo_head_hexsha": "0d5e0c9ac77d302910823ebc757a4ec99541f3ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "phantom_import/ImportFrank.py", "max_issues_repo_name": "janbrumm/layermodel_lib", "max_issues_repo_head_hexsha": "0d5e0c9ac77d302910823ebc757a4ec99541f3ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phantom_import/ImportFrank.py", "max_forks_repo_name": "janbrumm/layermodel_lib", "max_forks_repo_head_hexsha": "0d5e0c9ac77d302910823ebc757a4ec99541f3ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1097560976, "max_line_length": 115, "alphanum_fraction": 0.6766348998, "include": true, "reason": "import numpy", "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.17958973018625057}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar  4 20:25:37 2016\n\n@author: sthomp\n\"\"\"\n\nimport numpy as np\n\n#Try to locate cadences of transit ingress or egress\n#Then check if any of those cadences are flagged with thruster firings.\n\ndef flagIngressEgress(clip):\n    \"\"\"\n    Take a clip and return an array of flags\n    That give the ingress and egress times.\n    \"\"\"\n    \n    epoch=clip.trapFit.epoch_bkjd;\n    period=clip.trapFit.period_days;\n    ingress=clip.trapFit.ingress_hrs/(24.0);\n    duration=clip.trapFit.duration_hrs/(24.0);\n    qflags=clip.serve.flags\n    time=clip.serve.time;\n\n    thruster=2**20;\n    safemode=1;\n\n    t=np.bitwise_and(qflags,thruster)/thruster\n    s=np.bitwise_and(qflags,safemode)/safemode    \n    inflags=t | s\n    \n    t1=epoch-0.5*duration;\n    t4=epoch+0.5*duration;\n    \n    nstart=np.ceil((time[0]-epoch)/period)\n    nend=np.ceil((time[-1]-epoch)/period)\n    ntransit=nend-nstart;\n    n=np.linspace(nstart,nend-1,nend-nstart)\n    \n    count=0\n    for i in n:\n        start=t1+i*period;\n        stop=start+ingress;\n        inflagged=checkTimeSpan(start,stop,time,inflags)\n        \n        stop=t4+i*period;\n        start=stop-ingress;\n        egflagged=checkTimeSpan(start,stop,time,inflags) \n        print start,stop\n        print egflagged,inflagged\n                \n        if (egflagged+inflagged)>0:\n            count=count+1\n    \n        \n    return (count,ntransit)\n\ndef checkTimeSpan(start,stop,time,flags):\n    \"\"\"\n    return number of flags between the start and stop times.\n    flags should be true false for flags you care about.\n    \"\"\"\n    \n    want=(time>=start) & (time<=stop);\n    nflags=np.sum(flags[want]==1)\n    print flags[want]\n    \n    return nflags\n    ", "meta": {"hexsha": "26c4bf2764519f128b146e12ed62da9d60d361fc", "size": 1713, "ext": "py", "lang": "Python", "max_stars_repo_path": "susanplay/spansBad.py", "max_stars_repo_name": "exoplanetvetting/DAVE", "max_stars_repo_head_hexsha": "aea19a30d987b214fb4c0cf01aa733f127c411b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-05-07T02:01:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T08:09:39.000Z", "max_issues_repo_path": "susanplay/spansBad.py", "max_issues_repo_name": "barentsen/dave", "max_issues_repo_head_hexsha": "45ba97b7b535ad26dd555c33c963c6224a9af23c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2015-12-09T22:18:59.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-26T13:11:44.000Z", "max_forks_repo_path": "susanplay/spansBad.py", "max_forks_repo_name": "barentsen/dave", "max_forks_repo_head_hexsha": "45ba97b7b535ad26dd555c33c963c6224a9af23c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-03-08T11:42:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-07T00:10:37.000Z", "avg_line_length": 24.4714285714, "max_line_length": 71, "alphanum_fraction": 0.631640397, "include": true, "reason": "import numpy", "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.17942456629566939}}
{"text": "import numpy as np\nfrom glob import glob\nimport time\nimport os\nfrom pathlib import Path\nimport types\nimport contextlib\nfrom scipy import stats, signal, interpolate, special, integrate\n\nfrom darklim import constants\nfrom darklim.limit import _upper\nimport mendeleev\n\n\n__all__ = [\n    \"upper\",\n    \"helmfactor\",\n    \"drde\",\n    \"drde_max_q\",\n    \"gauss_smear\",\n    \"optimuminterval\",\n]\n\n\n@contextlib.contextmanager\ndef _working_directory(path):\n    \"\"\"\n    Changes working directory and returns to previous on exit.\n\n    Parameters\n    ----------\n    path : str\n        The directory that the current working directory will temporarily be switched to.\n\n    \"\"\"\n\n    prev_cwd = Path.cwd()\n    os.chdir(path)\n    try:\n        yield\n    finally:\n        os.chdir(prev_cwd)\n\n\ndef upper(fc, cl=0.9):\n    \"\"\"\n    Fortran wrapper function for Steve Yellin's Optimum Interval code `Upper.f`. In this case,\n    it calls a version of `UpperLim.f` that allows a larger range of confidence levels.\n\n    Parameters\n    ----------\n    fc : array_like\n        Given the foreground distribution whose shape is known, but whose normalization is\n        to have its upper limit total expected number of events determined, fc(0) to fc(N+1),\n        with fc(0)=0, fc(N+1)=1, and with  fc(i) the increasing ordered set of cumulative\n        probabilities for the foreground distribution for event i, i=1 to N.\n    cl : float, optional\n        The confidence level desired for the upper limit. Default is 0.9. Can be any value\n        between 0.00001 and 0.99999. However, the algorithm requires less than 100 upper\n        limit events when outside the range 0.8 to 0.995 in order to work, so an error may\n        be raised.\n\n    Returns\n    -------\n    ulout : float\n        The output of the Upper Fortran code, corresponding to the upper limit expected number of\n        events. To convert to cross section, the output should be divided by the total rate of the\n        signal and multiplied by the expected cross section for that rate.\n    endpoints0 : int\n        An integer giving the index of FC at which the optimum interval started.\n    endpoints1 : int\n        An integer giving the index of FC at which the optimum interval ended.\n\n    Notes\n    -----\n    This is a wrapper around Steve Yellin's Optimum Interval Fortran code, which was compiled via f2py to\n    be callable by Python. Because the Fortran code expects look-up tables in the current working directory,\n    we need to use a context manager to switch directories to where the look-up tables are when running the\n    algorithm.\n\n    Read more about Steve Yellin's Optimum Interval code here:\n        - http://titus.stanford.edu/Upper/\n        - https://arxiv.org/abs/physics/0203002\n        - https://arxiv.org/abs/0709.2701\n\n    \"\"\"\n\n    file_path = os.path.dirname(os.path.realpath(__file__))\n\n    # make sure fc starts with 0 and ends with 1\n    fc_new = fc\n    if fc[0]!=0:\n        fc_new = np.concatenate(([0], fc_new))\n    if fc[-1]!=1:\n        fc_new = np.concatenate((fc_new, [1]))\n\n    method = 0\n    nexp = 1\n    maxp1 = len(fc_new) - 1\n    nevts = np.array([maxp1 - 1])\n    mu = 1\n    icode = 0\n\n    with _working_directory(f\"{file_path}/_upper/\"):\n        ulout = _upper.upper(\n            method=method,\n            cl=cl,\n            nexp=nexp,\n            maxp1=maxp1,\n            nevts=nevts,\n            mu=np.asarray([mu]),\n            fc=fc_new[:, np.newaxis],\n            icode=icode,\n        )\n\n    endpoints = _upper.upperlimcom.endpoints\n\n    return ulout, endpoints[0], endpoints[1]\n\n\ndef helmfactor(er, tm='Si'):\n    \"\"\"\n    The analytic nuclear form factor via the Helm approximation.\n\n    Parameters\n    ----------\n    er : array_like\n        The recoil energy to use in the form factor calculation, units of keV.\n    tm : str, int, optional\n        The target material of the detector. Can be passed as either the atomic symbol, the\n        atomic number, or the full name of the element. Default is 'Si'.\n\n    Returns\n    -------\n    ffactor2 : ndarray\n        The square of the dimensionless form factor for the inputted recoil energies and target\n        material.\n\n    Notes\n    -----\n    This form factor uses Helm's approximation to the charge density of the nucleus, as explained by\n    Lewin and Smith in section 4 of their paper:\n        - https://doi.org/10.1016/S0927-6505(96)00047-3\n\n    \"\"\"\n\n    er = np.atleast_1d(er)\n\n    hbarc = constants.hbar * constants.c / constants.e * 1e-6 * 1e15 # [MeV fm]\n    mn = constants.atomic_mass * constants.c**2 / constants.e * 1e-9 # 1 amu in [GeV]\n    atomic_weight = mendeleev.element(tm).atomic_weight\n\n    # dimensionless momentum transfer\n    q = np.sqrt(2 * mn * atomic_weight * er) # [MeV]\n\n    # using the parameters defined in L&S\n    s = 0.9 # [fm]\n    a = 0.52 # [fm]\n    c = 1.23 * atomic_weight**(1 / 3) - 0.60 # [fm]\n\n    # approximation of rn [Eq. 4.11 of L&S]\n    rn = np.sqrt(c**2 + 7 / 3 * np.pi**2 * a**2 - 5 * s**2)\n\n    qrn = q * rn / hbarc\n    qs = q * s / hbarc\n\n    # Helm approximation of form facter [Eq. 4.7 of L&S]\n    ffactor2 = (3 * special.spherical_jn(1, qrn) / qrn * np.exp(-qs**2 / 2))**2 \n\n    return ffactor2\n\ndef _mixed_tm(tm):\n    \"\"\"\n    Helper function for extracting the element names and number\n    of them from an inputted chemical formula.\n\n    \"\"\"\n\n    pos = [i for i, e in enumerate(tm + 'A') if e.isupper()]\n    parts = [tm[pos[j]:pos[j + 1]] for j in range(len(pos) - 1)]\n    tms = []\n    for item in parts:\n        for ii, letter in enumerate(item):\n            if letter.isdigit():\n                tm_temp = [item[:ii], int(item[ii:])]\n                break\n            elif ii == len(item) - 1:\n                tm_temp = [item, 1]\n        tms.append(tm_temp)\n\n    return tms\n\n\ndef drde(q, m_dm, sig0, tm='Si'):\n    \"\"\"\n    The differential event rate of an expected WIMP.\n\n    Parameters\n    ----------\n    q : array_like\n        The recoil energies at which to calculate the dark matter differential\n        event rate. Expected units are keV.\n    m_dm : float\n        The dark matter mass at which to calculate the expected differential\n        event rate. Expected units are GeV.\n    sig0 : float\n        The dark matter cross section at which to calculate the expected differential\n        event rate. Expected units are cm^2.\n    tm : str, int, optional\n        The target material of the detector. Must be passed as the atomic\n        symbol. Can also pass a compound, but must be its chemical formula\n        (e.g. sapphire is 'Al2O3'). Default value is 'Si'.\n\n    Returns\n    -------\n    rate : ndarray\n        The expected dark matter differential event rate for the inputted recoil energies,\n        dark matter mass, and dark matter cross section. Units are events/keV/kg/day, \n        or \"DRU\".\n\n    Notes\n    -----\n    The derivation of the expected dark matter differential event rate is done in Lewin and\n    Smith's paper \"Review of mathematics, numerical factors, and corrections dark matter experiments\n    based on elastic nuclear recoil\", which can be found here:\n        - https://doi.org/10.1016/S0927-6505(96)00047-3\n\n    The derivation by L&S is incomplete, see Eq. 22 of R. Schnee's paper \"Introduction to Dark Matter\n    Experiments\", which includes the correct rate for `vmin` in the range (`vesc` - `ve`, `vesc` + `ve`)\n        - https://arxiv.org/abs/1101.5205\n\n    Another citation for this correction can be found in Savage, et. al.'s paper \"Compatibility of\n    DAMA/LIBRA dark matter detection with other searches\", see Eq. 19. This is a different parameterization,\n    but is the same solution.\n        - https://doi.org/10.1088/1475-7516/2009/04/010\n\n    \"\"\"\n\n    totalmassnum = sum([mendeleev.element(t).mass_number * num for t, num in _mixed_tm(tm)])\n    rate = sum(\n        [mendeleev.element(t).mass_number * num / totalmassnum * _drde(\n            q, m_dm, sig0, t,\n        ) for t, num in _mixed_tm(tm)]\n    )\n\n    return rate\n\n\ndef _drde(q, m_dm, sig0, tm):\n    \"\"\"\n    The differential event rate of an expected WIMP for a single target material.\n    See `drde` for the full explanation of each parameter.\n\n    \"\"\"\n\n    q = np.atleast_1d(q) # convert to recoil energy in keV\n\n    v0 = constants.v0_sun # sun velocity about galactic center [m/s]\n    ve = constants.ve_orbital # mean orbital velocity of Earth [m/s]\n    vesc = constants.vesc_galactic # galactic escape velocity [m/s]\n    rho0 = constants.rho0_dm # local DM density [GeV/cm^3]\n\n    a = mendeleev.element(tm).atomic_weight\n    mn = constants.atomic_mass * constants.c**2 / constants.e * 1e-9 # nucleon mass (1 amu) [GeV]\n    mtarget = a * mn # nucleon mass for tm [GeV]\n    r = 4 * m_dm * mtarget / (m_dm + mtarget)**2 # unitless reduced mass parameter\n    e0 = 0.5 * m_dm * (v0 / constants.c)**2 * 1e6 # kinetic energy of dark matter [keV]\n    vmin = np.sqrt(q / (e0 * r)) * v0 # DM velocity for smallest particle energy to give recoil energy q\n\n    form_factor = helmfactor(q, tm=tm)\n\n    # spin-independent cross section on entire nucleus\n    sigma = form_factor * sig0 * a**2 * (mtarget/(m_dm + mtarget))**2 / (mn / (m_dm + mn))**2\n\n    # event rate per unit mass for ve= 0 and vesc = infinity [Eq. 3.1 of L&S]\n    r0con = 2 * constants.N_A / np.sqrt(np.pi) * 1e5 * constants.day\n    r0 = r0con * sigma * rho0 * v0 / (a * m_dm)\n\n    # ratio of k0/k1 [Eq. 2.2 of L&S]\n    k0_over_k1 = 1 / (special.erf(vesc / v0) - 2 / np.sqrt(np.pi) * vesc / v0 * np.exp(-(vesc / v0)**2))\n\n    # rate integrated to infinity [Eq. 3.12 of L&S]\n    rate_inf = r0 * np.sqrt(np.pi) * v0 / (4 * e0 * r * ve) * (special.erf((vmin + ve) / v0) - special.erf((vmin - ve) / v0))\n    # rate integrated to vesc [Eq. 3.13 of L&S]\n    rate_vesc = k0_over_k1 * (rate_inf - r0 / (e0 * r) * np.exp(-(vesc / v0)**2))\n\n    # rate calculation correction to L&S for `vmin` in range (`vesc` - `ve`, `vesc` + `ve`) [Eq. 22 of Schnee]\n    rate_inf2 = r0 * np.sqrt(np.pi) * v0 / (4 * e0 * r * ve) * (special.erf(vesc / v0) - special.erf((vmin - ve) / v0))\n    rate_high_vmin = k0_over_k1 * (rate_inf2 - r0 / (e0 * r) * (vesc + ve - vmin) / (2 * ve) * np.exp(-(vesc / v0)**2))\n\n    # combine the calculations based on their regions of validity\n    rate = np.zeros(q.shape)\n    rate[(vmin < vesc - ve) & (vmin > 0)] = rate_vesc[(vmin < vesc - ve) & (vmin > 0)]\n    rate[(vmin > vesc - ve) & (vmin < vesc + ve)] = rate_high_vmin[(vmin > vesc - ve) & (vmin < vesc + ve)]\n\n    return rate\n\n\ndef drde_max_q(m_dm, tm='Si'):\n    \"\"\"\n    Function for calculating the energy corresponding to the largest nonzero value of the differential rate,\n    i.e. `rqpy.limit.drde`.\n\n    Parameters\n    ----------\n    m_dm : float, ndarray\n        The dark matter mass at which to calculate the expected differential\n        event rate. Expected units are GeV.\n    tm : str, int, optional\n        The target material of the detector. Must be passed as the atomic\n        symbol. Can also pass a compound, but must be its chemical formula\n        (e.g. sapphire is 'Al2O3'). Default value is 'Si'.\n\n    Returns\n    -------\n    qmax : float, ndarray\n        The energy corresponding to the largest nonzero value of the differential rate, where recoil energies\n        above this value will have a differential rate of zero.\n\n    \"\"\"\n\n    qmax = max([_drde_max_q(m_dm, t) for t, num in _mixed_tm(tm)])\n\n    return qmax\n\ndef _drde_max_q(m_dm, tm):\n    \"\"\"\n    Function for calculating the energy corresponding to the largest nonzero\n    value of the differential rate, i.e. `rqpy.limit.drde`. See `drde_max_q` for\n    the full documentation.\n\n    \"\"\"\n\n    a = mendeleev.element(tm).mass_number\n    mn = constants.atomic_mass * constants.c**2 / constants.e * 1e-9 # nucleon mass (1 amu) [GeV]\n    mtarget = a * mn # nucleon mass for tm [GeV]\n    r = 4 * m_dm * mtarget / (m_dm + mtarget)**2 # unitless reduced mass parameter\n    e0 = 0.5 * m_dm * (constants.v0_sun / constants.c)**2 * 1e6 # kinetic energy of dark matter [keV]\n    qmax = e0 * r * ((constants.vesc_galactic + constants.ve_orbital) / constants.v0_sun)**2\n\n    return qmax\n\ndef gauss_smear(x, f, res, nres=1e5, gauss_width=10):\n    \"\"\"\n    Function for smearing an array of values by a Gaussian.\n\n    Parameters\n    ----------\n    x : array_like\n        The x-values of the array `f` that will be smeared.\n    f : array_like\n        The array of value to smear via a Gaussian distribution.\n    res : float\n        The width of the Gaussian (1 standard deviation) that will be\n        used to smear the inputted array. Should have the same units as `x`.\n    nres : float, optional\n        The size of the array that the Gaussian distribution will be saved to.\n        Default is 1e5.\n    gauss_width : float, optional\n        The number of standard deviations of the Gaussian distribution that the\n        smearing will go out to. Default is 10.\n\n    Returns\n    -------\n    sx : ndarray\n        The inputted array `f` after being smeared by the Gaussian distribution.\n\n    \"\"\"\n\n    x2 = np.linspace(min(x), max(x), num=int(nres))\n    spacing = np.mean(np.diff(x2))\n    f2 = interpolate.interp1d(x, f)\n\n    xgauss = np.arange(-gauss_width*res, gauss_width*res, spacing)\n    gauss = stats.norm.pdf(xgauss, scale=res)\n\n    sce = signal.convolve(f2(x2), gauss, mode=\"full\", method=\"direct\") * spacing\n    e_conv = np.arange(-gauss_width * res + x2[0], gauss_width * res + x2[-1], spacing)\n    s = interpolate.interp1d(e_conv, sce)\n\n    return s(x)\n\n\ndef optimuminterval(eventenergies, effenergies, effs, masslist, exposure,\n                    tm=\"Si\", cl=0.9, res=None, gauss_width=10, verbose=False,\n                    drdefunction=None, hard_threshold=0.0):\n    \"\"\"\n    Function for running Steve Yellin's Optimum Interval code on an inputted spectrum and efficiency curve.\n\n    Parameters\n    ----------\n    eventenergies : ndarray\n        Array of all of the event energies (in keV) to use for calculating the sensitivity.\n    effenergies : ndarray \n        Array of the energy values (in keV) of the efficiency curve.\n    effs : ndarray\n        Array of the efficiencies (unitless) corresponding to `effenergies`.\n        If `drdefunction` argument is provided, the `effs` argument is ignored. It is kept as\n        a positional argument for backward compatibility\n    masslist : ndarray\n        List of candidate DM masses (in GeV/c^2) to calculate the sensitivity at.\n    exposure : float\n        The total exposure of the detector (kg*days).\n    tm : str, int, optional\n        The target material of the detector. Must be passed as the atomic\n        symbol. Can also pass a compound, but must be its chemical formula\n        (e.g. sapphire is 'Al2O3'). Default value is 'Si'.\n    cl : float, optional\n        The confidence level desired for the upper limit. Default is 0.9. Can be any value\n        between 0.00001 and 0.99999. However, the algorithm requires less than 100 upper\n        limit events when outside the range 0.8 to 0.995 in order to work, so an error may\n        be raised.\n    res : float, NoneType, optional\n        The detector resolution in units of keV. If passed, then the differential event\n        rate of the dark matter is convoluted with a Gaussian with width `res`, which results\n        in a smeared spectrum. If left as None, no smearing is performed.\n        If `drdefunction` is provided, this argument is ignored\n    gauss_width : float, optional\n        If `res` is not None, this is the number of standard deviations of the Gaussian\n        distribution that the smearing will go out to. Default is 10.\n        If `drdefunction` is provided, this argument is ignored\n    verbose : bool, optional\n        If True, then the algorithm prints out which mass is currently being used in the calculation.\n        If False, no information is printed. Default is False.\n    drdefunction : list, optional\n        List of callables of type float(float). Every element of the list represents the signal model\n        rate as a function of reconstructed energy for the corresponding Dark Matter mass from the\n        `masslist` and the cross section sigma=10^-41 cm^2. The experiment efficiency must be taken\n        into account. The energy unit is keV, the rate unit is 1/keV/kg/day.\n        By default (or if None is provided) the standard Lewin&Smith signal model is used with gaussian\n        smearing of width `res`, truncated at `gauss_width` standard deviations.\n    hard_threshold : float, optional\n        The energy value (keV) below which the efficiency is zero.\n        This argument is not required in a case of smooth efficiency curve, however it must be provided \n        in a case of step-function-like efficiency.\n\n    Returns\n    -------\n    sigma : ndarray\n        The corresponding cross sections of the sensitivity curve (in cm^2).\n    oi_energy0 : ndarray\n        The energies in keV at which each optimum interval started.\n    oi_energy1 : ndarray\n        The energies in keV at which each optimum interval ended.\n\n    Notes\n    -----\n    This function is a wrapper for Steve Yellin's Optimum Interval code. His code can be found\n    here: titus.stanford.edu/Upper/\n\n    Read more about the Optimum Interval code in these two papers:\n        - https://arxiv.org/abs/physics/0203002\n        - https://arxiv.org/abs/0709.2701\n\n    \"\"\"\n\n    if np.isscalar(masslist):\n        masslist = [masslist]\n\n    eventenergies = np.sort(eventenergies)\n\n    elow = max(hard_threshold, min(effenergies))\n    ehigh = max(effenergies)\n\n    en_interp = np.logspace(np.log10(elow), np.log10(ehigh), int(1e5))\n\n    sigma0 = 1e-41\n\n    event_inds = (eventenergies > elow) & (eventenergies < ehigh)\n\n    sigma = np.ones(len(masslist)) * np.inf\n    oi_energy0 = np.zeros(len(masslist))\n    oi_energy1 = np.zeros(len(masslist))\n\n    for ii, mass in enumerate(masslist):\n        if verbose:\n            print(f\"On mass {ii+1} of {len(masslist)}.\")\n\n        if drdefunction is None:\n            exp = effs * exposure\n\n            curr_exp = interpolate.interp1d(\n                effenergies, exp, kind=\"linear\", bounds_error=False, fill_value=(0, exp[-1]),\n            )\n    \n            init_rate = drde(\n                en_interp, mass, sigma0, tm=tm,\n            )\n            if res is not None:\n                init_rate = gauss_smear(en_interp, init_rate, res, gauss_width=gauss_width)\n            rate = init_rate * curr_exp(en_interp)\n        else:\n            rate = drdefunction[ii](en_interp) * exposure\n\n        integ_rate = integrate.cumtrapz(rate, x=en_interp, initial=0)\n\n        tot_rate = integ_rate[-1]\n\n        x_val_fcn = interpolate.interp1d(\n            en_interp,\n            integ_rate,\n            kind=\"linear\",\n            bounds_error=False,\n            fill_value=(0, tot_rate),\n        )\n\n        x_vals = x_val_fcn(eventenergies[event_inds])\n\n        if tot_rate != 0:\n            fc = x_vals/tot_rate\n            fc[fc > 1] = 1\n\n            cdf_max = 1 - 1e-6\n            possiblewimp = fc <= cdf_max\n            fc = fc[possiblewimp]\n\n            if len(fc) == 0:\n                fc = np.asarray([0, 1])\n\n            try:\n                uloutput, endpoint0, endpoint1 = upper(fc, cl=cl)\n\n                sigma[ii] = (sigma0 / tot_rate) * uloutput\n\n                oi_energy0[ii] = eventenergies[event_inds][possiblewimp][endpoint0-1] if endpoint0>0 else elow # endpoint==0 means the start of the SM integration range\n                oi_energy1[ii] = eventenergies[event_inds][possiblewimp][endpoint1-1] if endpoint1-1 < len(fc) else ehigh\n            except:\n                pass\n\n    return sigma, oi_energy0, oi_energy1\n\n", "meta": {"hexsha": "d45ab91ded01f259f672fe9268e80f368575468c", "size": 19569, "ext": "py", "lang": "Python", "max_stars_repo_path": "darklim/limit/_limit.py", "max_stars_repo_name": "slwatkins/DarkLim", "max_stars_repo_head_hexsha": "22a0f8ea7dd609075d55c413b598e42da8ef348f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-21T16:56:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T16:56:36.000Z", "max_issues_repo_path": "darklim/limit/_limit.py", "max_issues_repo_name": "slwatkins/DarkLim", "max_issues_repo_head_hexsha": "22a0f8ea7dd609075d55c413b598e42da8ef348f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "darklim/limit/_limit.py", "max_forks_repo_name": "slwatkins/DarkLim", "max_forks_repo_head_hexsha": "22a0f8ea7dd609075d55c413b598e42da8ef348f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7838345865, "max_line_length": 168, "alphanum_fraction": 0.6371812561, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.1794245580912754}}
{"text": "\"\"\"\nThis file is the main source file of the ProcessMCRaT library which is used to read and process\nthe results of a MCRaT simulation\n\nWritten by: Tyler Parsotan April 2021\n\n\"\"\"\nimport os\nimport astropy as ap\nimport h5py as h5\nimport numpy as np\nfrom astropy import units as u\nfrom astropy import constants as const\nfrom astropy.units import UnitConversionError\n\n\n\nclass PhotonList(object):\n    def __init__(self, r0, r1, r2, p0, p1, p2, p3, weight, scatterings, file_index, comv_p0=None, comv_p1=None, comv_p2=None,\\\n                 comv_p3=None, s0=None, s1=None, s2=None, s3=None, photon_type=None):\n        \"\"\"\n        Iniitalizes the 4 momenta (lab and comoving), position, stokes parameters, weight, number of scatterings, and the photon type of each\n        photon in the MCRaT file. units are cgs units\n        :param r0:\n        :param r1:\n        :param r2:\n        :param s0:\n        :param s1:\n        :param s2:\n        :param s3:\n        :param p0:\n        :param p1:\n        :param p2:\n        :param p3:\n        :param comv_p0:\n        :param comv_p1:\n        :param comv_p2:\n        :param comv_p3:\n        :param weight:\n        :param scatterings:\n        \"\"\"\n        self.p0=p0\n        self.p1=p1\n        self.p2=p2\n        self.p3=p3\n        self.comv_p0=comv_p0\n        self.comv_p1=comv_p1\n        self.comv_p2=comv_p2\n        self.comv_p3=comv_p3\n        self.r0=r0\n        self.r1=r1\n        self.r2=r2\n        self.s0=s0\n        self.s1=s1\n        self.s2=s2\n        self.s3=s3\n        self.weight=weight\n        self.scatterings=scatterings\n        self.photon_type=photon_type\n        self.file_index=file_index\n\n    def get_energies(self, unit=u.keV):\n        try:\n            return self.p0 * (const.c.cgs.value * u.erg).to(unit).value\n        except UnitConversionError:\n            #trying to get wavelength so need to convert to si units for energy first\n            x=self.p0 * (const.c.cgs.value * u.erg)\n            return x.to(unit, equivalencies=u.spectral()).value\n\n    def get_comv_energies(self, unit=u.keV):\n        try:\n            return self.comv_p0*(const.c.cgs.value*u.erg).to(unit).value\n        except UnitConversionError:\n            #trying to get wavelength so need to convert to si units for energy first\n            x=self.comv_p0 * (const.c.cgs.value * u.erg)\n            return x.to(unit, equivalencies=u.spectral()).value\n\n\ndef curdir():\n    \"\"\"\n    Get the current working directory.\n\t\"\"\"\n    curdir = os.getcwd() + '/'\n    return curdir\n\nclass McratSimLoad(object):\n    def __init__(self, file_directory=None):\n        \"\"\"\n        Initalized the mload class with the directory that the MCRaT files are located in, and the frames per second of\n        the simulation (this is found in the MCRaT mc.par file).\n        :param file_directory:\n        :param frames_per_second:\n        \"\"\"\n        if file_directory is not None:\n            self.file_directory=file_directory\n        else:\n            self.file_directory=curdir()\n\n    def load_frame(self, frame_num, read_comv=False, read_stokes=False, read_type=False):\n        \"\"\"\n        Reads in MCRaT data for current version of MCRaT that outputs data in hdf5 files. Also has support for various\n        MCRaT switches that can be turned on by the user.\n        :param frame_num:\n        :param read_comv:\n        :param read_stokes:\n        :param read_type:\n        :return:\n        \"\"\"\n\n        with h5.File(self.file_directory+\"mcdata_\" + np.str_(frame_num) + '.h5', 'r') as f:\n            pw = f['PW'][:]\n            ns = f['NS'][:]\n            p0 = f['P0'][:]\n            p1 = f['P1'][:]\n            p2 = f['P2'][:]\n            p3 = f['P3'][:]\n            r0 = f['R0'][:]\n            r1 = f['R1'][:]\n            r2 = f['R2'][:]\n            if read_stokes:\n                s0 = f['S0'][:]\n                s1 = f['S1'][:]\n                s2 = f['S2'][:]\n                s3 = f['S3'][:]\n            else:\n                s0 = np.zeros(pw.size)\n                s1 = np.zeros(pw.size)\n                s2 = np.zeros(pw.size)\n                s3 = np.zeros(pw.size)\n\n            if read_comv:\n                comv_p0 = f['COMV_P0'][:]\n                comv_p1 = f['COMV_P1'][:]\n                comv_p2 = f['COMV_P2'][:]\n                comv_p3 = f['COMV_P3'][:]\n            else:\n                comv_p0 = np.zeros(pw.size)\n                comv_p1 = np.zeros(pw.size)\n                comv_p2 = np.zeros(pw.size)\n                comv_p3 = np.zeros(pw.size)\n\n            if read_type:\n                pt = f['PT'][:]\n                pt = np.array([i for i in bytes(pt).decode()])\n            else:\n                pt = np.full(pw.size, None)\n\n        idx=np.arange(pw.size)\n\n        photons=PhotonList(r0, r1, r2, p0, p1, p2, p3, pw, ns, idx, comv_p0=comv_p0, comv_p1=comv_p1,\\\n                        comv_p2=comv_p2, comv_p3=comv_p3, s0=s0, s1=s1, s2=s2, s3=s3, photon_type=pt)\n\n        self.loaded_photons=photons\n        self.read_stokes=read_stokes\n        self.read_comv=read_comv\n        self.read_type=read_type\n        self.frame_num=frame_num\n", "meta": {"hexsha": "2f0bebe04c91fb517e15c64c5668631b63585347", "size": 5060, "ext": "py", "lang": "Python", "max_stars_repo_path": "processmcrat/processmcrat.py", "max_stars_repo_name": "parsotat/ProcessMCRaT", "max_stars_repo_head_hexsha": "12abb6e6507a8d167d884b96b8f969a02bf4ee55", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "processmcrat/processmcrat.py", "max_issues_repo_name": "parsotat/ProcessMCRaT", "max_issues_repo_head_hexsha": "12abb6e6507a8d167d884b96b8f969a02bf4ee55", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "processmcrat/processmcrat.py", "max_forks_repo_name": "parsotat/ProcessMCRaT", "max_forks_repo_head_hexsha": "12abb6e6507a8d167d884b96b8f969a02bf4ee55", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-01-12T11:23:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T09:12:47.000Z", "avg_line_length": 32.0253164557, "max_line_length": 141, "alphanum_fraction": 0.547826087, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 1427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.17928954658066912}}
{"text": "\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nfrom typing import Optional\n\nfrom oneflow.framework.tensor import Tensor\nfrom oneflow.nn.module import Module\n\n\nclass PixelShufflev2(Module):\n    \"\"\"\n    Part of the documentation is referenced from:\n    https://pytorch.org/docs/stable/generated/torch.nn.PixelShuffle.html#torch.nn.PixelShuffle\n\n    Rearranges elements in a tensor of shape :math:`(*, C \\\\times r_h \\\\times r_w, H, W)`\n    to a tensor of shape :math:`(*, C, H \\\\times r_h, W \\\\times r_w)`, where r_h and r_w are upscale factors.\n\n    This is useful for implementing efficient sub-pixel convolution\n    with a stride of :math:`1/r`.\n\n    See the paper:\n    `Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network`_\n    by Shi et. al (2016) for more details.\n\n    Args:\n        upscale_factor (int, optional): factor to increase spatial resolution by, only use when factors of height and width spatial are the same.\n\n        h_upscale_factor (int, optional): factor to increase height spatial resolution by, only one of h_upscale_factor and upscale_factor can be used.\n        w_upscale_factor (int, optional): factor to increase width spatial resolution by, only one of w_upscale_factor and upscale_factor can be used.\n\n    Shape:\n        - Input: :math:`(*, C_{in}, H_{in}, W_{in})`, where * is zero or more batch dimensions\n        - Output: :math:`(*, C_{out}, H_{out}, W_{out})`, where\n\n    if use upscale_factor:\n\n    .. math::\n        C_{out} = C_{in} \\\\div \\\\text{h_upscale_factor}^2\n\n        H_{out} = H_{in} \\\\times \\\\text{upscale_factor}\n\n        W_{out} = W_{in} \\\\times \\\\text{upscale_factor}\n\n    if use h_upscale_factor and w_upscale_factor:\n\n    .. math::\n        C_{out} = C_{in} \\\\div \\\\text{h_upscale_factor} \\\\div \\\\text{w_upscale_factor}\n\n        H_{out} = H_{in} \\\\times \\\\text{h_upscale_factor}\n\n        W_{out} = W_{in} \\\\times \\\\text{w_upscale_factor}\n\n    For example:\n\n    .. code-block:: python\n\n        >>> import oneflow as flow\n        >>> import numpy as np\n        >>> m = flow.nn.PixelShuffle(upscale_factor=2)\n        >>> x = flow.Tensor(np.random.randn(3, 4, 5, 5))\n        >>> y = m(x)\n        >>> y.shape\n        oneflow.Size([3, 1, 10, 10])\n\n        >>> m = flow.nn.PixelShuffle(h_upscale_factor=3, w_upscale_factor=4)\n        >>> x = flow.Tensor(np.random.randn(1, 24, 2, 2))\n        >>> y = m(x)\n        >>> y.shape\n        oneflow.Size([1, 2, 6, 8])\n\n    .. _Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network:\n        https://arxiv.org/abs/1609.05158\n    \"\"\"\n\n    def __init__(\n        self,\n        upscale_factor: Optional[int] = None,\n        h_upscale_factor: Optional[int] = None,\n        w_upscale_factor: Optional[int] = None,\n    ) -> None:\n        super().__init__()\n        if upscale_factor is None:\n            assert (\n                h_upscale_factor is not None and w_upscale_factor is not None\n            ), \"h_upscale_factor and w_upscale_factor should be None if use upscale_factor\"\n        else:\n            assert (\n                h_upscale_factor is None and w_upscale_factor is None\n            ), \"upscale_factor should be None if use h_upscale_factor and w_upscale_factor\"\n            h_upscale_factor = upscale_factor\n            w_upscale_factor = upscale_factor\n        assert (\n            h_upscale_factor > 0 and w_upscale_factor > 0\n        ), \"The scale factor of height and width must larger than zero\"\n        self.h_upscale_factor = h_upscale_factor\n        self.w_upscale_factor = w_upscale_factor\n\n    def forward(self, input: Tensor) -> Tensor:\n        assert len(input.shape) == 4, \"Only Accept 4D Tensor\"\n        (_batch, _channel, _height, _width) = input.shape\n        assert (\n            _channel % (self.h_upscale_factor * self.w_upscale_factor) == 0\n        ), \"The channels of input tensor must be divisible by (upscale_factor * upscale_factor) or (h_upscale_factor * w_upscale_factor)\"\n        _new_c = int(_channel / (self.h_upscale_factor * self.w_upscale_factor))\n        out = input.reshape(\n            _batch,\n            _new_c,\n            self.h_upscale_factor * self.w_upscale_factor,\n            _height,\n            _width,\n        )\n        out = out.reshape(\n            _batch,\n            _new_c,\n            self.h_upscale_factor,\n            self.w_upscale_factor,\n            _height,\n            _width,\n        )\n        out = out.permute(0, 1, 4, 2, 5, 3)\n        out = out.reshape(\n            _batch,\n            _new_c,\n            _height * self.h_upscale_factor,\n            _width * self.w_upscale_factor,\n        )\n        return out\n\n    def extra_repr(self) -> str:\n        return f\"w_upscale_factor={self.w_upscale_factor}, h_upscale_factor={self.h_upscale_factor}\"\n\n\nif __name__ == \"__main__\":\n    import doctest\n\n    doctest.testmod(raise_on_error=True)\n", "meta": {"hexsha": "d5c2662f9ad0a9a3a588de112137a1568bc8bcbe", "size": 5446, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/oneflow/nn/modules/pixelshuffle.py", "max_stars_repo_name": "grybd/oneflow", "max_stars_repo_head_hexsha": "82237ad096a10527591660c09b61444c42917e69", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3285, "max_stars_repo_stars_event_min_datetime": "2020-07-31T05:51:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:20:16.000Z", "max_issues_repo_path": "python/oneflow/nn/modules/pixelshuffle.py", "max_issues_repo_name": "grybd/oneflow", "max_issues_repo_head_hexsha": "82237ad096a10527591660c09b61444c42917e69", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2417, "max_issues_repo_issues_event_min_datetime": "2020-07-31T06:28:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:04:14.000Z", "max_forks_repo_path": "python/oneflow/nn/modules/pixelshuffle.py", "max_forks_repo_name": "grybd/oneflow", "max_forks_repo_head_hexsha": "82237ad096a10527591660c09b61444c42917e69", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 520, "max_forks_repo_forks_event_min_datetime": "2020-07-31T05:52:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T02:38:11.000Z", "avg_line_length": 36.5503355705, "max_line_length": 151, "alphanum_fraction": 0.6404700698, "include": true, "reason": "import numpy", "num_tokens": 1381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.17928954658066912}}
{"text": "\"\"\"\nI'm copying this from some of my much older work. It's probably going to be\nbuggy. Yep, it was. I've done some refactoring and whatnot but it could probably\nuse some more. Maybe combine with `GeoDFUtils`? It would be nice to be able to\neasily operate on GDF subsets and selections.\n\n`buffer` and `rasterize` are working pretty well. Still need tests and whatnot\nbut those methods are the main use for this module at the moment. The two\n`error_matrix` functions are useful and working too.\n\"\"\"\n\n#from error_matrix import *\nfrom RasterDS import RasterDS\nfrom ErrorMatrix import ErrorMatrix\nfrom scipy.stats.stats import mode\nimport numpy as np\nimport pandas as pd\nimport geopandas as gpd\nimport os\nfrom osgeo import ogr, gdal, osr\nimport shapely as shpl\nfrom scipy.stats import mode as scipymode\nfrom tempfile import mkdtemp\nimport shutil\n\nclass GroundTruthGDF(gpd.GeoDataFrame):\n    def __init__(self, *args, **kwargs):\n        hf = kwargs.pop('habfield', 'habitat')\n        hc = kwargs.pop('habcodefield', 'hab_num')\n        super(GroundTruthGDF, self).__init__(*args, **kwargs)\n        self.habfield = hf\n        self.habcodefld = hc\n\n    @classmethod\n    def new(cls,*args,**kwargs):\n        return cls(*args,**kwargs)\n\n    @classmethod\n    def from_file(cls, filename, **kwargs):\n        hf = kwargs.pop('habfield', 'habitat')\n        hc = kwargs.pop('habcodefield', 'hab_num')\n        gdf = gpd.io.file.read_file(filename, **kwargs)\n        return cls(gdf, habfield=hf, habcodefield=hc)\n\n    @property\n    def codes_habitat(self):\n        \"\"\"\n        Return a dictionary just like habitat_codes only backwards.\n        \"\"\"\n        hf = self.habfield\n        hcf = self.habcodefld\n        hcd = dict()\n        for cl in self[hcf].unique():\n            if cl > 0:\n                sers = self[self[hcf]==cl][hf]\n                if sers.count() > 1:\n                    hcd[cl] = sers.mode().item()\n                elif sers.count() > 0:\n                    hcd[cl] = sers.item()\n        return hcd\n\n    def __getitem__(self, key):\n        result = super(GroundTruthGDF, self).__getitem__(key)\n        if isinstance(result, gpd.GeoDataFrame):\n            result.__class__ = GroundTruthGDF\n            result.habfield = self.habfield\n            result.habcodefld = self.habcodefld\n        return result\n\n    def query(self, expr, inplace=False, **kwargs):\n        result = super(GroundTruthGDF, self).query(expr, inplace=False, **kwargs)\n        if isinstance(result, gpd.GeoDataFrame):\n            result.__class__ = GroundTruthGDF\n            result.habfield = self.habfield\n            result.habcodefld = self.habcodefld\n        return result\n\n    def comparison_df(self, rds, radius=0, generous=False, band_index=0,\n                       out_of_bounds=np.nan, with_unclassed=False):\n        \"\"\"\n        There can be problems if there are codes in the raster that do not exist\n        in the geodataframe. I should probably check for this condition and\n        raise an exception. No time right now.\n        \"\"\"\n        pred = self.compare_raster(rds, radius=radius, generous=generous,\n                                   band_index=band_index,\n                                   out_of_bounds=out_of_bounds)\n        truth = self.__getitem__(self.habcodefld)\n        truth.name = 'truth'\n        pred.name = 'pred'\n        preddf = pd.concat((truth, pred), axis=1)\n        if not with_unclassed:\n            # Get rid of any row that has a zero in it\n            preddf = preddf[(preddf!=0).all(1)]\n        return preddf\n\n    def error_matrix(self, rds, radius=0, generous=False, band_index=0,\n                       out_of_bounds=np.nan, with_unclassed=False):\n        from sklearn.metrics import confusion_matrix\n        compdf = self.comparison_df(rds, radius=radius, generous=generous,\n                                    band_index=band_index,\n                                    out_of_bounds=out_of_bounds,\n                                    with_unclassed=with_unclassed).dropna()\n        # scikit-learn returns pred on x and true on y. I want it the other\n        # way around so .T\n        em = confusion_matrix(compdf.truth, compdf.pred).T.view(ErrorMatrix)\n        codes = np.sort(np.unique(compdf.dropna()))\n        em.categories = map(lambda s: self.codes_habitat.get(s, \"Unclassified\"),\n                            codes)\n        return em\n\n    def compare_raster(self, rds, radius=0, generous=False, band_index=0,\n                       out_of_bounds=np.nan):\n        \"\"\"\n        Compare habitat codes in `gdf` with codes in corresponding locations of\n        a raster habitat map (`rds`). This can be an exact point to point\n        comparison (when `radius`=0) or can be more forgiving. When `radius`>0\n        and `generous` is `False`, the mode (most common) value within `radius`\n        of each point will be returned. When `radius`>0 and `generous` is True,\n        ground truth habitat codes will be returned if found within `radius` of\n        each point, and the mode will be returned if not.\n\n        Parameters\n        ----------\n        rds : OpticalRS.RasterDS\n            The habitat map (or whatever raster) you want to compare to the\n            `GroundTruthShapefile` (self). The projection of this raster must\n            match the projection of the `GroundTruthShapefile`. If it doesn't\n            match, you might get results but they'll be wrong.\n        radius : float\n            The radius with which to buffer `point`. The units of this value\n            depend on the projection being used.\n        generous : boolean\n            If False (default), mode will be returned. If True, habitat code will be\n            returned if within `radius`. See function description for more info.\n        band_index : int\n            Index of the image band to sample. Zero indexed (band 1 = 0). For\n            single band rasters, this should be left at the default value (0).\n        out_of_bounds : float, int, or nan (default)\n            If `point` is not within `self.raster_extent`, `out_of_bounds` will\n            be returned.\n\n        Returns\n        -------\n        pandas Series\n            The values from `rds` that correspond to each point in `gdf`.\n        \"\"\"\n        column = self.habcodefld\n        if generous:\n            rcheck = lambda row: rds.radiused_point_check(row.geometry,\n                                                          radius=radius,\n                                                          search_value=row[column],\n                                                          band_index=band_index,\n                                                          out_of_bounds=out_of_bounds)\n        else:\n            rcheck = lambda row: rds.radiused_point_check(row.geometry,\n                                                          radius=radius,\n                                                          search_value=None,\n                                                          band_index=band_index,\n                                                          out_of_bounds=out_of_bounds)\n        return self.apply(rcheck, axis=1)\n\nclass GroundTruthShapefile(object):\n    \"\"\"\n    This class contains code for relating point ground truth shapefiles (such as\n    the ones generated by Benthic Photo Survey) to raster maps. The default\n    values (for `habfield` and `habcodefield`) assume that there's a field\n    called habitat that contains a text description of the habitat class for\n    each point.\n\n    \"\"\"\n    def __init__(self, file_path, habfield='habitat', habcodefield='hab_num'):\n        self.habfield = habfield\n        self.habcodefld = habcodefield\n        self.file_path = file_path\n        self.ds = open_shapefile(self.file_path)\n        self.hab_dict = self.__setup_hab_dict()\n        self.legit_habs = sorted( [ h for h in self.habitats if h ] ) # Exclude None as a habitat value\n        self.habitat_codes = self.__setup_hab_codes() # dict( zip( legit_habs, range( 1, len(legit_habs) + 1 ) ) )\n\n    def __setup_hab_dict(self):\n        \"\"\"\n        The hab_dict is a dictionary that contains a list of ogr features for\n        each habitat key.\n        \"\"\"\n        hab_dict = {}\n        for hab in self.habitats:\n            hab_dict[hab] = [f for f in self.features if f.__getattr__(self.habfield)==hab]\n        return hab_dict\n\n    def __setup_hab_codes(self):\n        \"\"\"\n        There should be habitat codes in the shapefile in a field called\n        hab_num. We need to get them and set up the matching names. This only\n        works for BPS shapefiles with a hab_num field set up to match the\n        habitat field. If `self.habfield` is set to something else, we'll just\n        generate integer codes.\n        \"\"\"\n        # Exclude None from list of habitats\n        hcd = {}\n        if self.habcodefld is not None:\n            for hab in self.legit_habs:\n                feat = self.hab_dict[hab][0]\n                hcd[hab] = feat.__getattr__(self.habcodefld)\n        else:\n            for i, hab in enumerate(self.legit_habs):\n                hcd[hab] = i+1 # +1 to make it not zero indexed\n        return hcd\n\n    @property\n    def features(self):\n        fts = [f for f in self.ds.GetLayer()]\n        self.ds.GetLayer().ResetReading()\n        return fts\n\n    @property\n    def habitats(self):\n        habs = sorted( set([f.__getattr__(self.habfield) for f in self.features]))\n        return habs\n\n    @property\n    def legit_habs_code_sorted(self):\n        \"\"\"\n        Return the legit habitats sorted by order of their numeric codes.\n        \"\"\"\n        return [v for k,v in sorted(self.codes_habitat.items())]\n\n    @property\n    def geo_data_frame(self):\n        \"\"\"\n        Return a GeoPandas GeoDataFrame object.\n        \"\"\"\n        gtgdf = GroundTruthGDF.from_file(self.file_path, habfield=self.habfield,\n                                         habcodefield=self.habcodefld)\n        # gtgdf = gpd.GeoDataFrame.from_file(self.file_path)\n        return gtgdf\n\n    def geopandas_subset(self, query, file_name=None):\n        \"\"\"\n        Create a `GroundTruthShapefile` based on a geopandas subset of\n        `self.geo_data_frame`. If `file_name` is `None` (default), then the file\n        will only be temporarily saved. It will be deleted before this function\n        returns. This seems to work fine for generating error matrices from\n        subsets but it could have unintended consequences elsewhere. If you\n        provide a `file_name`, a shapefile will be saved from the output.\n\n        Parameters\n        ----------\n        query : string or pandas Series\n            If `query` is a string, `pandas.DataFrame.query` will be used to\n            generate the subset. Otherwise, query is assumed to be a series that\n            can be used to index `self.geo_data_frame`.\n        file_name : string file path or None\n            If `None`, a temporary shapefile will be created and immediately\n            deleted. Otherwise, the subset will be saved as a shapefile.\n\n        Returns\n        -------\n        GroundTruthShapefile\n            A `GroundTruthShapefile` object containing only the selected subset\n            of features.\n        \"\"\"\n        if file_name is None:\n            tdir = mkdtemp()\n            tfn = os.path.join(tdir, 'temp.shp')\n        else:\n            tfn = file_name\n        if type(query) is str:\n            gdf = self.geo_data_frame.query(query)\n        else:\n            gdf = self.geo_data_frame[query]\n        # save the subset to a file\n        gdf.to_file(tfn)\n        # make a new GroundTruthShapefile\n        gts = GroundTruthShapefile(tfn, self.habfield, self.habcodefld)\n        if file_name is None:\n            shutil.rmtree(tdir)\n        return gts\n\n\n    @property\n    def spatial_reference(self):\n        \"\"\"\n        Return the OGR spatial reference object for the shapefile.\n        \"\"\"\n        return self.ds.GetLayer().GetSpatialRef()\n\n    @property\n    def projection_wkt(self):\n        \"\"\"\n        Return the well known text (WKT) representation of the shapefile's projection.\n        \"\"\"\n        return self.spatial_reference.ExportToWkt()\n\n    @property\n    def projcs(self):\n        \"\"\"\n        Return the PROJCS value from the shapefile's spatial reference. This is\n        basically the name of the projection. ...I think.\n        \"\"\"\n        return self.spatial_reference.GetAttrValue('PROJCS')\n\n    @property\n    def geometry_type(self):\n        \"\"\"\n        Just return whether it's a type of point, line, or polygon.\n        \"\"\"\n        type_name = ogr.GeometryTypeToName( self.ds.GetLayer().GetGeomType() ).lower()\n        if type_name.find('point') <> -1:\n            return 'point'\n        elif type_name.find('line') <> -1:\n            return 'line'\n        elif type_name.find('polygon') <> -1:\n            return 'polygon'\n        else:\n            return None\n\n    @property\n    def hab_colors(self):\n        \"\"\"\n        return a dictionary with hab codes as keys and hab colors as values.\n        \"\"\"\n        legit_habs = sorted( [ h for h in self.habitats if h ] )\n        hcd = {}\n        for hab in legit_habs:\n            feat = self.hab_dict[hab][0]\n            hcd[hab] = feat.hab_color\n        return hcd\n\n    @property\n    def codes_habitat(self):\n        \"\"\"\n        Return a dictionary just like habitat_codes only backwards.\n        \"\"\"\n        chd = {}\n        for k,v in self.habitat_codes.items():\n            chd[v] = k\n        return chd\n\n    @property\n    def qgis_vector(self):\n        qvl = QgsVectorLayer(self.file_path,'grnd_truth','ogr')\n        if qvl.isValid():\n            return qvl\n        else:\n            raise Exception(\"Failed to create a QGis Vector Layer. QGis provider path problems, perhaps?\")\n\n    def buffer(self, radius=1.0, file_path=None):\n        \"\"\"\n        Buffer the geometries in `self` and return a new `ogr` datasource. If\n        `file_path` is `None`, just create the datasource in memory. If a file\n        path is given, write out a shapefile. All fields and values (aside from\n        geometry) are cloned.\n        \"\"\"\n        if file_path == None:\n            drvname = 'Memory'\n        else:\n            drvname = 'ESRI Shapefile'\n        srcds = self.ds\n        # get projection\n        lyr = srcds.GetLayer(0)\n        sptrf = lyr.GetSpatialRef()\n        proj = osr.SpatialReference()\n        proj.ImportFromWkt(sptrf.ExportToWkt())\n        drv = ogr.GetDriverByName(drvname)\n        if file_path == None:\n            dst_ds = drv.CreateDataSource('out')\n        elif os.path.exists(file_path):\n            raise Exception(\"{} already exists!\".format(file_path))\n        else:\n            dst_ds = drv.CreateDataSource(file_path)\n        dst_lyr = dst_ds.CreateLayer('', srs=proj, geom_type=ogr.wkbPolygon)\n        # copy all the fields to the destination ds\n        featr = lyr.GetFeature(0)\n        nfields = featr.GetFieldCount()\n        for i in range(nfields):\n            fld = featr.GetFieldDefnRef(i)\n            dst_lyr.CreateField(fld)\n        feat_defn = dst_lyr.GetLayerDefn()\n        # reset the feature counter\n        lyr.ResetReading()\n        # buffer the geometries and copy the fields\n        for i in range(lyr.GetFeatureCount()):\n            # get the feature and geometry\n            feat = lyr.GetFeature(i)\n            geom = feat.GetGeometryRef()\n            # create a new feature\n            newfeat = feat.Clone()\n            # get the buffered geometry\n            bufgeom = geom.Buffer(radius)\n            # set the new geometry to the buffered geom\n            newfeat.SetGeometry(bufgeom)\n            # add the new feature to the destination layer\n            dst_lyr.CreateFeature(newfeat)\n            # clean up\n            newfeat.Destroy()\n            feat.Destroy()\n        # ensure the new features are written\n        dst_lyr.SyncToDisk()\n        return dst_ds\n\n    def rasterize(self, buffer_radius=None, raster_template=None,\n                  pixel_size=1.99976, value_field='hab_num', float_values=False,\n                  array_only=False, out_file_path=None):\n        \"\"\"\n        Return a raster that can be used for classification training.\n\n        buffer_radius: A float value in projection units to buffer the\n        geometries by. If buffer_radius is left None then only pixels right\n        under points will be classified.\n\n        raster_template: A RasterDS object. If supplied, the resulting\n        rasterized image will have the same extent and geotransform as the\n        template. Also, if a raster_template is provided, the pixel_size keyword\n        value will be ignored and pixel size will come from the template.\n\n        pixel_size: A float value representing pixel size in projection units.\n        This value will be ignored if a raster_template is supplied.\n\n        value_field: A string representing the name of the field in the\n        shapefile that holds the numeric code that will be burned into the\n        raster output as the pixel value.\n\n        float_values: Boolean. If `True`, the output raster will contain floats.\n        If `False`, the output will be integers. Default is `False`.\n\n        array_only: A boolean. If true we'll try to just write the raster to\n        memory and not to disk. If you don't need to keep the raster, this will\n        just keep you from having to clean up useless files later. Then we'll\n        just return an array instead of GroundTruthRaster object.\n\n        out_file_path: String. Path to the raster file output. If `None`\n        (default) and `array_only=False`, a file name based on the\n        `GroundTruthShapefile` file name will be created. If `array_only=True`,\n        `out_file_path` is ignored.\n        \"\"\"\n        if float_values:\n            datatype = gdal.GDT_Float32\n        else:\n            datatype = gdal.GDT_Byte\n        # Make a copy of the layer's data source because we'll need to\n        # modify its attributes table\n        if buffer_radius:\n            source_ds = ogr.GetDriverByName(\"Memory\").CopyDataSource( self.buffer(radius=buffer_radius), \"\" )\n        else:\n            source_ds = ogr.GetDriverByName(\"Memory\").CopyDataSource( self.ds, \"\")\n        source_layer = source_ds.GetLayer(0)\n        source_srs = source_layer.GetSpatialRef()\n\n        if raster_template:\n            gTrans = raster_template.gdal_ds.GetGeoTransform()\n            pixsizeX = gTrans[1]\n            pixsizeY = gTrans[5]\n            x_res = raster_template.gdal_ds.RasterXSize\n            y_res = raster_template.gdal_ds.RasterYSize\n            rdsarr = raster_template.band_array\n            # if np.ma.is_masked(rdsarr):\n            #     mask = rdsarr[...,0].mask\n            # else:\n            #     mask = None\n        else:\n            x_min, x_max, y_min, y_max = source_layer.GetExtent()\n            # Create the destination data source\n            x_res = int((x_max - x_min) / pixel_size)\n            y_res = int((y_max - y_min) / pixel_size)\n\n        if out_file_path:\n            targ_fn = out_file_path\n        else:\n            # make a target ds with filename based on source filename\n            targ_fn = self.file_path.rsplit(os.path.extsep, 1)[0] + '_rast' + os.path.extsep + 'tif'\n        # print \"x_res: %i, y_res: %i\" % (x_res,y_res)\n        target_ds = gdal.GetDriverByName('GTiff').Create(targ_fn, x_res, y_res, 1, datatype)\n\n        if raster_template:\n            # Use the raster template supplied so that we get the same extent as the raster\n            # we're trying to classify\n            target_ds.SetGeoTransform( gTrans )\n        else:\n            # None supplied so use the pixel_size value and the extent of the shapefile\n            target_ds.SetGeoTransform(( x_min, pixel_size, 0, y_max, 0, -pixel_size, ))\n        if raster_template:\n            target_ds.SetProjection( raster_template.gdal_ds.GetProjection() )\n        elif source_srs:\n            # Make the target raster have the same projection as the source\n            target_ds.SetProjection(source_srs.ExportToWkt())\n        else:\n            # Source has no projection (needs GDAL >= 1.7.0 to work)\n            target_ds.SetProjection('LOCAL_CS[\"arbitrary\"]')\n        # Rasterize\n        err = gdal.RasterizeLayer(target_ds, [1], source_layer,\n                burn_values=[0],\n                options=[\"ATTRIBUTE=%s\" % value_field])\n        if err != 0:\n            raise Exception(\"error rasterizing layer: %s\" % err)\n        # clean up\n        source_layer = None\n        source_srs = None\n        source_ds = None\n\n        if array_only:\n            out_array = target_ds.ReadAsArray()\n            target_ds = None\n            os.remove( targ_fn )\n            return out_array\n        else:\n            target_ds = None\n            return RasterDS(targ_fn)\n\n    def error_matrix(self, classification_ds, with_unclassed=False):\n        \"\"\"\n        Take a RasterDS (classification_ds) and create a user / producer\n        accuracy table. Return as an array so it can be displayed in multiple\n        ways. See the `ErrorMatrix` module for more information on the returned\n        object.\n\n        Parameters\n        ----------\n        classification_ds : OpticalRS.RasterDS\n            The habitat map (or whatever raster) you want to compare to the\n            `GroundTruthShapefile` (self). The projection of this raster must\n            match the projection of the `GroundTruthShapefile`. If it doesn't\n            match, you might get results but they'll be wrong.\n\n        Returns\n        -------\n        ErrorMatrix\n            See the `ErrorMatrix` module for more information on the returned\n            object.\n\n        Notes\n        -----\n        This function should be merged in some way with `error_matrix_buffered`.\n        There's a bunch of redundancy between the two. I don't have time to do\n        it right now.\n        \"\"\"\n        maxcode = max(self.habitat_codes.values())\n        if with_unclassed:\n            maxcode += 1\n        errmat = np.zeros((maxcode, maxcode), int)\n        cats = list()\n        rext = classification_ds.raster_extent\n        for hab,code in self.habitat_codes.items():\n            for feature in self.hab_dict[hab]:\n                ref_val = code\n                geom = feature.geometry()\n                pnt = shpl.geometry.base.geom_from_wkb(geom.ExportToWkb())\n                if pnt.within(rext):\n                    cls_val = classification_ds.value_at_point( geom )\n                else:\n                    # this means that the point is not within the raster\n                    # I think that means we don't want to count this point at\n                    # all in the accuracy assessment.\n                    continue\n                if with_unclassed:\n                    errmat[ cls_val ][ ref_val ] += 1\n                elif cls_val == 0:\n                    # If we're not including unclassified values\n                    # we don't want this showing up in the totals.\n                    continue\n                else:\n                    errmat[ cls_val - 1 ][ ref_val - 1 ] += 1\n        # Get rid of all zero rows and columns. This can happen if hab codes\n        # skip an integer.\n        em = errmat.view( ErrorMatrix ).clean_zeros(with_unclassed)\n        # Rows and Columns of errmat end up sorted by hab code. This next line\n        # will give the habitat names sorted by hab code number.\n        if with_unclassed:\n            em.categories = ['Unclassified'] + sorted(self.habitat_codes, key=self.habitat_codes.get)\n        else:\n            em.categories = sorted(self.habitat_codes, key=self.habitat_codes.get)\n        return em\n\n    def error_matrix_buffered(self, classification_ds, radius=2.0, with_unclassed=False):\n        \"\"\"\n        Take a RasterDS (classification_ds) and create a user / producer\n        accuracy table. Ground Truth points will be buffered and matching\n        habitat codes within `radius` of a point will be considered success.\n        Return as an array so it can be displayed in multiple ways. See the\n        `ErrorMatrix` module for more information on the returned object.\n\n        Parameters\n        ----------\n        classification_ds : OpticalRS.RasterDS\n            The habitat map (or whatever raster) you want to compare to the\n            `GroundTruthShapefile` (self). The projection of this raster must\n            match the projection of the `GroundTruthShapefile`. If it doesn't\n            match, you might get results but they'll be wrong.\n        radius : float\n            The radius with which to buffer points. The units of this value\n            depend on the projection being used. You can use\n            `GroundTruthShapefile.projection_wkt` to examine the projection and\n            find the units.\n\n        Returns\n        -------\n        ErrorMatrix\n            See the `ErrorMatrix` module for more information on the returned\n            object.\n        \"\"\"\n        maxcode = max(self.habitat_codes.values())\n        if with_unclassed:\n            maxcode += 1\n        errmat = np.zeros((maxcode, maxcode), int)\n        cats = list()\n        rext = classification_ds.raster_extent\n        for hab,code in self.habitat_codes.items():\n            for feature in self.hab_dict[hab]:\n                ref_val = code\n                geom = feature.geometry()\n                pnt = shpl.geometry.base.geom_from_wkb(geom.ExportToWkb())\n                if pnt.within(rext):\n                    clsarr = classification_ds.geometry_subset(pnt.buffer(radius),\n                                                               all_touched=True)\n                else:\n                    # this means that the point is not within the raster\n                    # I think that means we don't want to count this point at\n                    # all in the accuracy assessment.\n                    continue\n\n                if ref_val in clsarr.compressed():\n                    cls_val = ref_val # this counts as success\n                elif not pnt.within(rext):\n                    # this means that the point is not within the raster\n                    # I think that means we don't want to count this point at\n                    # all in the accuracy assessment.\n                    continue\n                else:\n                    # our reference value was not found within radius of point\n                    # so we'll report it as the most common class within radius\n                    if len(clsarr.compressed()) == 0:\n                        cls_val = 0 # Assuming zero is code for unclassified\n                    else:\n                        cls_val = scipymode(clsarr.compressed()).mode.item()\n                if with_unclassed:\n                    errmat[ cls_val ][ ref_val ] += 1\n                elif cls_val == 0:\n                    # If we're not including unclassified values\n                    # we don't want this showing up in the totals.\n                    continue\n                else:\n                    errmat[ cls_val - 1 ][ ref_val - 1 ] += 1\n        # Get rid of all zero rows and columns. This can happen if hab codes\n        # skip an integer.\n        em = errmat.view( ErrorMatrix ).clean_zeros(with_unclassed)\n        # Rows and Columns of errmat end up sorted by hab code. This next line\n        # will give the habitat names sorted by hab code number.\n        if with_unclassed:\n            em.categories = ['Unclassified'] + sorted(self.habitat_codes, key=self.habitat_codes.get)\n        else:\n            em.categories = sorted(self.habitat_codes, key=self.habitat_codes.get)\n        return em\n\n    @property\n    def hab_dict_counts(self):\n        ret_dict = {}\n        for hab in self.habitats:\n            ret_dict[hab] = len( self.hab_dict[hab] )\n        return ret_dict\n\n    def add_raster_values(self, raster_ds):\n        \"\"\"\n        The raster data source here is assumed to be a classified image. The raster\n        values should correspond to classes.\n        \"\"\"\n        trans = transform_dict(raster_ds)\n        band = raster_ds.GetRasterBand(1)\n        self.features = [ add_raster_value(f,trans,band) for f in self.ds.GetLayer() ]\n        self.ds.GetLayer().ResetReading()\n        self.hab_dict = self.__setup_hab_dict()\n\n    @property\n    def unsupervised_habitat_class_dict(self):\n        \"\"\"\n        For each habitat, give a list of raster values that correspond to the ground truth\n        points of that habitat type. This will be used with unsupervised classifications to\n        figure out which, if any, of the classes correspond to particular habitat types.\n        \"\"\"\n        try:\n            hcd = {}\n            for hab in self.habitats:\n                hcd[hab] = [ f.raster_value for f in self.hab_dict[hab] ]\n        except AttributeError:\n            raise AttributeError(\"Features need to be assigned raster values before you can create a habitat class dictionary.\")\n        return hcd\n\n    @property\n    def unsupervised_habitat_class_modes(self):\n        hcm = {}\n        for hab in self.habitats:\n            md, cn = mode( self.unsupervised_habitat_class_dict[hab] )\n            if len( md )==1:\n                hcm[hab] = md[0]\n            else:\n                hcm[hab] = None\n        return hcm\n\n    def __output_training_LAN(self,img,buffer_radius=3.5,driver_str='LAN'):\n        \"\"\"\n        DEPRICATED! -> This only works for points. I think I can use the\n        rasterize method instead. I need to verify and then get rid of this\n        method. This method also has the habitat field hard coded (search for\n        feat.habitat). That would need to be changed to\n        feat.__getattr__(self.habfield) to make this work correctly.\n\n        Create a raster input for supervised classifications. img is the image\n        that we want to classify (in the form of a gdal datasource). Spectral\n        can't use tifs so we will create LAN file.\n\n        A buffer radius of 3.5 meters gives us 3 x 3 sets of pixels with our\n        point feature in the center. This, of course, assumes that we're dealing\n        with WV2 imagery and a projection with meters as the units. This works\n        for me on my project but might now work for others.\n        \"\"\"\n        if driver_str=='LAN':\n            f_ext = 'lan'\n        elif driver_str=='GTiff':\n            f_ext = 'tif'\n        else:\n            raise ValueError(\"At this point, the output_training_LAN method only knows how to deal with LAN and GTiff file types. Sorry.\")\n\n        lyr = self.ds.GetLayer()\n        lyr.ResetReading()\n        trans = transform_dict(img)\n        driver = gdal.GetDriverByName(driver_str)\n        rows = img.RasterYSize\n        cols = img.RasterXSize\n        fname = img.GetDescription().rsplit(os.path.extsep)[0] + '_train' + os.path.extsep + f_ext\n        add_num = 0\n        while os.path.exists(fname):\n            add_num += 1\n            if add_num==1:\n                fname = fname.replace( os.path.extsep + f_ext, '_%i' % add_num + os.path.extsep + f_ext )\n            else:\n                old = '_%i.%s' % ( add_num - 1, f_ext )\n                new = '_%i.%s' % ( add_num, f_ext )\n                fname = fname.replace( old, new )\n        outDs = driver.Create(fname, cols, rows, 1, GDT_Int16)\n        if outDs is None:\n            print 'Could not create %s' % fname\n            sys.exit(1)\n\n        outBand = outDs.GetRasterBand(1)\n\n        pixel_count = 0\n        hab_pix_count = dict( zip( [h for h in self.habitats if h], np.zeros( len([h for h in self.habitats if h]), dtype=np.int ) ) )\n        for feat in lyr:\n            if not feat.habitat:\n                continue\n            if self.hab_dict_counts[feat.habitat] < 24:\n                continue\n            if buffer_radius:\n                geom = feat.geometry().Buffer(buffer_radius)\n                elp = envelope_dict(geom)\n                xtop = elp['xLeft']\n                ytop = elp['yTop']\n                xOffset = int( (xtop - trans['originX']) / trans['pixWidth'] )\n                yOffset = int( (ytop - trans['originY']) / trans['pixHeight'] )\n                xdist = elp['xRight'] - elp['xLeft']\n                ydist = elp['yBottom'] - elp['yTop']\n                cols = int( xdist / trans['pixWidth'] )\n                rows = int( ydist / trans['pixHeight'] )\n                pixarr = int( self.habitat_codes[feat.habitat] ) * np.ones((rows,cols), dtype=np.int16)\n            else:\n                geom = feat.geometry()\n                xOffset = int( (geom.GetX() - trans['originX']) / trans['pixWidth'] )\n                yOffset = int( (geom.GetY() - trans['originY']) / trans['pixHeight'] )\n                pixarr = np.array( [[ self.habitat_codes[feat.habitat] ]] )\n\n            outBand.WriteArray(pixarr,xOffset,yOffset)\n            pixel_count += pixarr.size\n            hab_pix_count[feat.habitat] += pixarr.size\n\n        outBand.FlushCache()\n        outBand.SetNoDataValue(0)\n        # georeference the image and set the projection\n        outDs.SetGeoTransform(img.GetGeoTransform())\n        outDs.SetProjection(img.GetProjection())\n\n        # build pyramids\n        gdal.SetConfigOption('HFA_USE_RRD', 'YES')\n        outDs.BuildOverviews(overviewlist=[2,4,8,16,32,64,128])\n\n        print \"%i pixels total\" % pixel_count\n        for hab in self.habitats:\n            if hab:\n                print \"%i pixels for %s\" % ( hab_pix_count[hab], hab )\n\n        return GroundTruthRaster( outDs.GetDescription() )\n\n    def training_classes(self, rds, buffer_radius=None,calc_stats=0):\n        \"\"\"\n        I think I should move some of this functionality over to the GroundTruthRaster class\n        in common.py.  I'm generating classes okay from what I can tell but I get a singular\n        matrix error when I try to run the Gaussian Classifier. I have no idea why. Baffled,\n        I am.\n        \"\"\"\n        grnd_truth = self.rasterize(buffer_radius=buffer_radius,raster_template=rds,array_only=True)\n        sp_img = rds.spy_image.load()\n        return sp.create_training_classes(sp_img, grnd_truth,calc_stats=calc_stats)\n\ndef add_raster_value(feature, trans, band ):\n    geom = feature.geometry()\n    x = geom.GetX()\n    y = geom.GetY()\n\n    xOffset = int( (x - trans['originX']) / trans['pixWidth'] )\n    yOffset = int( (y - trans['originY']) / trans['pixHeight'] )\n\n    data = band.ReadAsArray(xOffset, yOffset, 1, 1)\n    feature.raster_value = data[0,0]\n    return feature\n\ndef open_shapefile(filename):\n    \"\"\"Take a file path string and return an ogr shape\"\"\"\n    # open the shapefile and get the layer\n    driver = ogr.GetDriverByName('ESRI Shapefile')\n    shp = driver.Open(filename)\n    if shp is None:\n        print 'Could not open %s' % filename\n        sys.exit(1)\n    return shp\n", "meta": {"hexsha": "f746ae347a6f10b6f598c54a17e9ec490e163089", "size": 34647, "ext": "py", "lang": "Python", "max_stars_repo_path": "OpticalRS/GroundTruthShp.py", "max_stars_repo_name": "melkimble/OpticalRS", "max_stars_repo_head_hexsha": "54404f6c1e4e4a6f625e7b15e9f0489cb3600d79", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2016-06-13T02:29:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T13:30:39.000Z", "max_issues_repo_path": "OpticalRS/GroundTruthShp.py", "max_issues_repo_name": "melkimble/OpticalRS", "max_issues_repo_head_hexsha": "54404f6c1e4e4a6f625e7b15e9f0489cb3600d79", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2017-09-02T12:50:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-14T18:32:52.000Z", "max_forks_repo_path": "OpticalRS/GroundTruthShp.py", "max_forks_repo_name": "melkimble/OpticalRS", "max_forks_repo_head_hexsha": "54404f6c1e4e4a6f625e7b15e9f0489cb3600d79", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2016-04-02T14:03:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T06:00:45.000Z", "avg_line_length": 42.0984204131, "max_line_length": 138, "alphanum_fraction": 0.5924611077, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.17928954658066912}}
{"text": "\"\"\"\nCopyright 2013 Steven Diamond\n\nThis file is part of CVXPY.\n\nCVXPY is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nCVXPY is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with CVXPY.  If not, see <http://www.gnu.org/licenses/>.\n\"\"\"\n\nimport cvxpy.settings as s\nfrom cvxpy.problems.solvers.ecos_intf import ECOS\nimport ecos\n\nclass ECOS_BB(ECOS):\n    \"\"\"An interface for the ECOS BB solver.\n    \"\"\"\n\n    # Solver capabilities.\n    LP_CAPABLE = True\n    SOCP_CAPABLE = True\n    SDP_CAPABLE = False\n    EXP_CAPABLE = False\n    MIP_CAPABLE = True\n\n    def name(self):\n        \"\"\"The name of the solver.\n        \"\"\"\n        return s.ECOS_BB\n\n    @staticmethod\n    def _noncvx_id_to_idx(dims, var_offsets, var_sizes):\n        \"\"\"Converts the nonconvex constraint variable ids in dims into indices.\n\n        Parameters\n        ----------\n        dims : dict\n            The dimensions of the cones.\n        var_offsets : dict\n            A dict of variable id to horizontal offset.\n        var_sizes : dict\n            A dict of variable id to variable dimensions.\n\n        Returns\n        -------\n        tuple\n            A list of indices for the boolean variables and integer variables.\n        \"\"\"\n        bool_idx = []\n        int_idx = []\n        for indices, constr_type in zip([bool_idx, int_idx],\n                                        [s.BOOL_IDS, s.INT_IDS]):\n            for var_id in dims[constr_type]:\n                offset = var_offsets[var_id]\n                size = var_sizes[var_id]\n                for i in range(size[0]*size[1]):\n                    indices.append(offset + i)\n            del dims[constr_type]\n\n        return bool_idx, int_idx\n\n    def get_problem_data(self, objective, constraints, cached_data):\n        \"\"\"Returns the argument for the call to the solver.\n\n        Parameters\n        ----------\n        objective : LinOp\n            The canonicalized objective.\n        constraints : list\n            The list of canonicalized cosntraints.\n        cached_data : dict\n            A map of solver name to cached problem data.\n\n        Returns\n        -------\n        dict\n            The arguments needed for the solver.\n        \"\"\"\n        data = super(ECOS_BB, self).get_problem_data(objective, constraints,\n                                                     cached_data)\n        sym_data = self.get_sym_data(objective, constraints, cached_data)\n        bool_idx, int_idx = self._noncvx_id_to_idx(data[s.DIMS],\n                                                   sym_data.var_offsets,\n                                                   sym_data.var_sizes)\n        data[s.BOOL_IDX] = bool_idx\n        data[s.INT_IDX] = int_idx\n        return data\n\n    def solve(self, objective, constraints, cached_data,\n              warm_start, verbose, solver_opts):\n        \"\"\"Returns the result of the call to the solver.\n\n        Parameters\n        ----------\n        objective : LinOp\n            The canonicalized objective.\n        constraints : list\n            The list of canonicalized cosntraints.\n        cached_data : dict\n            A map of solver name to cached problem data.\n        warm_start : bool\n            Not used.\n        verbose : bool\n            Should the solver print output?\n        solver_opts : dict\n            Additional arguments for the solver.\n\n        Returns\n        -------\n        tuple\n            (status, optimal value, primal, equality dual, inequality dual)\n        \"\"\"\n        data = self.get_problem_data(objective, constraints, cached_data)\n        # Default verbose to false for BB wrapper.\n        mi_verbose = solver_opts.get('mi_verbose', False)\n        results_dict = ecos.solve(data[s.C], data[s.G], data[s.H],\n                                  data[s.DIMS], data[s.A], data[s.B],\n                                  verbose=verbose,\n                                  mi_verbose=mi_verbose,\n                                  bool_vars_idx=data[s.BOOL_IDX],\n                                  int_vars_idx=data[s.INT_IDX],\n                                  **solver_opts)\n        return self.format_results(results_dict, None,\n                                   data[s.OFFSET], cached_data)\n", "meta": {"hexsha": "b907c22f6a85dc27f73a46d49de8641051758666", "size": 4591, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/tools/ecos/cvxpy/cvxpy/problems/solvers/ecos_bb_intf.py", "max_stars_repo_name": "riadnassiffe/Simulator", "max_stars_repo_head_hexsha": "7d9ff09f26367d3714e3d10be3dd4a9817b8ed6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tools/ecos/cvxpy/cvxpy/problems/solvers/ecos_bb_intf.py", "max_issues_repo_name": "riadnassiffe/Simulator", "max_issues_repo_head_hexsha": "7d9ff09f26367d3714e3d10be3dd4a9817b8ed6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-06-05T17:21:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-22T23:20:32.000Z", "max_forks_repo_path": "src/tools/ecos/cvxpy/cvxpy/problems/solvers/ecos_bb_intf.py", "max_forks_repo_name": "riadnassiffe/Simulator", "max_forks_repo_head_hexsha": "7d9ff09f26367d3714e3d10be3dd4a9817b8ed6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2611940299, "max_line_length": 79, "alphanum_fraction": 0.5693748639, "include": true, "reason": "import cvxpy,from cvxpy", "num_tokens": 931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.34510526422232046, "lm_q1q2_score": 0.17928954308140624}}
{"text": "\"\"\"Estimation functions for WFSC.\"\"\"\n\nimport numpy as np\nimport multiprocessing\n# from astropy.io import fits\nimport matplotlib.pyplot as plt\nimport falco\nfrom . import check\n\ndef perfect(mp):\n    \"\"\"\n    Return the perfect-knowledge E-field from the full model.\n    \n    Optionally add Zernikes at the input pupil.\n\n    Parameters\n    ----------\n    mp : ModelParameters\n        Structure containing optical model parameters\n        \n    Returns\n    -------\n    Emat : numpy ndarray\n        2-D array with the vectorized, complex E-field of the dark hole pixels\n        for each mode included in the control Jacobian.\n    \"\"\"\n    if type(mp) is not falco.config.ModelParameters:\n        raise TypeError('Input \"mp\" must be of type ModelParameters')\n    \n    if mp.flagParallel:\n        \n        Emat = np.zeros((mp.Fend.corr.Npix, mp.jac.Nmode), dtype=complex)\n        \n        # Loop over all modes and wavelengths\n        inds_list = [(x, y) for x in range(mp.jac.Nmode) for y in range(mp.Nwpsbp)]\n        Nvals = mp.jac.Nmode*mp.Nwpsbp\n\n        pool = multiprocessing.Pool(processes=mp.Nthreads)\n        resultsRaw = [pool.apply_async(_est_perfect_Efield_with_Zernikes_in_parallel,\n                                       args=(mp, ilist, inds_list)) for ilist in range(Nvals)]\n        results = [p.get() for p in resultsRaw]  # All the images in a list\n        pool.close()\n        pool.join()\n        \n        # Re-order for easier indexing\n        Ecube = np.zeros((mp.Fend.corr.Npix, mp.jac.Nmode, mp.Nwpsbp), dtype=complex)\n        for iv in range(Nvals):\n            im = inds_list[iv][0]  # Index of the Jacobian mode\n            wi = inds_list[iv][1]   # Index of the wavelength in the sub-bandpass\n            Ecube[:, im, wi] = results[iv]\n        Emat = np.mean(Ecube, axis=2)  # Average over wavelengths in the subband\n  \n#        EmatAll = np.zeros((mp.Fend.corr.Npix, Nval))\n#        for iv in range(Nval):\n#            EmatAll[:, iv] = results[iv]\n#\n#        counter = 0;\n#        for im=1:mp.jac.Nmode\n#            EsbpMean = 0;\n#            for wi=1:mp.Nwpsbp\n#                counter = counter + 1;\n#                EsbpMean = EsbpMean + EmatAll(:,counter) * \\\n#                     mp.full.lambda_weights(wi);\n#            end\n#            Emat(:,im) = EsbpMean;\n#        end\n    \n    else:\n    \n        Emat = np.zeros((mp.Fend.corr.Npix, mp.jac.Nmode), dtype=complex)\n        modvar = falco.config.Object()\n        \n        for im in range(mp.jac.Nmode):\n            modvar.sbpIndex = mp.jac.sbp_inds[im]\n            modvar.zernIndex = mp.jac.zern_inds[im]\n            modvar.whichSource = 'star'\n            \n            # Take the mean over the wavelengths within the sub-bandpass\n            EmatSbp = np.zeros((mp.Fend.corr.Npix, mp.Nwpsbp), dtype=complex)\n            for wi in range(mp.Nwpsbp):\n                modvar.wpsbpIndex = wi\n                E2D = falco.model.full(mp, modvar)\n                # Actual field in estimation area. Apply spectral weight\n                # within the sub-bandpass\n                EmatSbp[:, wi] = mp.full.lambda_weights[wi] * \\\n                    E2D[mp.Fend.corr.maskBool]\n            Emat[:, im] = np.sum(EmatSbp, axis=1)\n            \n    return Emat\n    \n\n# Extra function needed to use parfor (because parfor can have only a\n# single changing input argument).\ndef _est_perfect_Efield_with_Zernikes_in_parallel(mp, ilist, inds_list):\n\n    im = inds_list[ilist][0]  # Index of the Jacobian mode\n    wi = inds_list[ilist][1]   # Index of the wavelength in the sub-bandpass\n    \n    modvar = falco.config.Object()\n    modvar.sbpIndex = mp.jac.sbp_inds[im]\n    modvar.zernIndex = mp.jac.zern_inds[im]\n    modvar.wpsbpIndex = wi\n    modvar.whichSource = 'star'\n    \n    E2D = falco.model.full(mp, modvar)\n\n    # Actual field in estimation area. Don't apply spectral weight here.\n    return E2D[mp.Fend.corr.maskBool]\n\n\ndef pairwise_probing(mp, ev, jacStruct=np.array([])):\n    \"\"\"\n    Estimate the dark hole E-field with pair-wise probing.\n\n    Parameters\n    ----------\n    mp : falco.config.ModelParameter\n        Object containing all model parameters.\n    ev : falco.config.Object()\n    jacStruct : array_like, optional\n        Array containing the control Jacobian. Default is an empty array.\n\n    Returns\n    -------\n    None\n        Outputs are included in the object ev.\n        \n    \"\"\"\n    # \"ev\" is passed in only for the Kalman filter. Reset it for the batch\n    # process to avoid accidentally using old data.\n    # if 'pwp-bp' == mp.estimator.lower():\n    #     ev = falco.config.Object()\n    \n    # Select number of actuators across based on chosen DM for the probing\n    if mp.est.probe.whichDM == 1:\n        Nact = mp.dm1.Nact\n    elif mp.est.probe.whichDM == 2:\n        Nact = mp.dm2.Nact\n    else:\n        raise ValueError('mp.est.probe.whichDM must equal 1 or 2.')\n    \n    # Store the initial DM commands\n    if np.any(mp.dm_ind == 1):\n        DM1Vnom = mp.dm1.V\n    \n    if np.any(mp.dm_ind == 2):\n        DM2Vnom = mp.dm2.V\n    else:\n        DM2Vnom = np.zeros_like(mp.dm1.V)\n    \n    # Definitions:\n    Npairs = mp.est.probe.Npairs  # Number of image PAIRS\n    ev.Icube = np.zeros((mp.Fend.Neta, mp.Fend.Nxi, 1+2*Npairs))\n    if np.any(mp.dm_ind == 1):\n        ev.Vcube1 = np.zeros((mp.dm1.Nact, mp.dm1.Nact, 1+2*Npairs))\n    if np.any(mp.dm_ind == 2):\n        ev.Vcube2 = np.zeros((mp.dm2.Nact, mp.dm2.Nact, 1+2*Npairs))\n    \n    # Generate evenly spaced probes along the complex unit circle\n    # NOTE: Nprobes=Npairs*2\n    probePhaseVec = np.array([0, Npairs])\n    for k in range(Npairs-1):\n        probePhaseVec = np.append(probePhaseVec, probePhaseVec[-1]-(Npairs-1))\n        probePhaseVec = np.append(probePhaseVec, probePhaseVec[-1]+Npairs)\n    probePhaseVec = probePhaseVec*np.pi/(Npairs)\n    \n    badAxisVec = ''\n    if mp.est.probe.axis.lower() == 'y':\n        for _iter in range(2*Npairs):\n            badAxisVec += 'y'\n    elif mp.est.probe.axis.lower() == 'x':\n        for _iter in range(2*Npairs):\n            badAxisVec += 'x'\n    elif mp.est.probe.axis.lower() in ('alt', 'xy', 'alternate'):\n        for iPair in range(2*Npairs):\n            if (iPair+1) % 4 == 1 or (iPair+1) % 4 == 2:\n                badAxisVec += 'x'\n            elif (iPair+1) % 4 == 3 or (iPair+1) % 4 == 0:\n                badAxisVec += 'y'\n    elif mp.est.probe.axis.lower() in ('m', 'multi'):\n        for _iter in range(2*Npairs):\n            badAxisVec += 'm'\n    else:\n        raise ValueError('Incorrect value for mp.est.probe.axis')\n    \n    # Initialize output arrays\n    ev.Eest = np.zeros((mp.Fend.corr.Npix, mp.Nsbp), dtype=complex)\n    ev.IincoEst = np.zeros((mp.Fend.corr.Npix, mp.Nsbp))\n    ev.I0mean = 0\n    ev.IprobedMean = 0\n    \n    # Get images and perform estimates in each sub-bandpass\n    print('Estimating electric field with batch process estimation ...')\n    \n    for si in range(mp.Nsbp):\n        print('Wavelength: %u/%u ... ' % (si, mp.Nsbp-1))\n    \n        # Valid for all calls to model_compact.m:\n        modvar = falco.config.Object()  # Initialize the new structure\n        modvar.sbpIndex = si\n        modvar.whichSource = 'star'\n    \n        # Measure current contrast level average\n        # Reset DM commands to the unprobed state:\n        mp.dm1.V = DM1Vnom\n        mp.dm2.V = DM2Vnom\n        # Separate out image values at DH pixels and delta DM voltage settings\n        Iplus = np.zeros((mp.Fend.corr.Npix, Npairs))\n        Iminus = np.zeros((mp.Fend.corr.Npix, Npairs))\n        DM1Vplus = np.zeros((Nact, Nact, Npairs))\n        DM1Vminus = np.zeros((Nact, Nact, Npairs))\n        DM2Vplus = np.zeros((Nact, Nact, Npairs))\n        DM2Vminus = np.zeros((Nact, Nact, Npairs))\n    \n        # Compute probe shapes and take probed images:\n    \n        # Take initial, unprobed image (for unprobed DM settings).\n        whichImg = 1\n        I0 = falco.imaging.get_sbp_image(mp, si)\n        I0vec = I0[mp.Fend.corr.maskBool]  # Vectorize the correction region\n        ev.I0mean = ev.I0mean+I0/mp.Nsbp  # Getting Inorm for whole bandpass\n    \n        # Store values for first image and its DM commands\n        ev.Icube[:, :, whichImg] = I0\n        if np.any(mp.dm_ind == 1):\n            ev.Vcube1[:, :, whichImg] = mp.dm1.V\n        if np.any(mp.dm_ind == 2):\n            ev.Vcube2[:, :, whichImg] = mp.dm2.V\n    \n        # Compute the average Inorm in the scoring and correction regions\n        ev.InormScore = np.mean(I0[mp.Fend.score.maskBool])\n        ev.InormCorr = np.mean(I0[mp.Fend.corr.maskBool])\n        print('Measured unprobed Inorm (Corr / Score): %.2e \\t%.2e \\n' %\n              (ev.InormCorr, ev.InormScore))\n    \n        # Set (approximate) probe intensity based on current measured Inorm\n        if mp.flagFiber:\n            ev.InormProbeMax = 1e-5\n            InormProbe = np.min([np.sqrt(np.max(I0)*1e-8), ev.InormProbeMax])\n        else:\n            ev.InormProbeMax = 1e-4\n            InormProbe = np.min([np.sqrt(np.max(I0vec)*1e-5),\n                                 ev.InormProbeMax])\n            # Change this to a high percentile value (e.g., 90%) instead of the\n            # max to avoid being tricked by noise\n        print('Chosen probe intensity: %.2e' % InormProbe)\n    \n        # Perform the probing\n        iOdd = 0  # Initialize index counters\n        iEven = 0\n        for iProbe in range(2*Npairs):\n\n            # Generate the command map for the probe\n            probeCmd = gen_pairwise_probe(mp, InormProbe,\n                                probePhaseVec[iProbe], badAxisVec[iProbe])\n    \n            # Select which DM to use for probing. Allocate probe to that DM\n            if mp.est.probe.whichDM == 1:\n                dDM1Vprobe = probeCmd/mp.dm1.VtoH  # Now in volts\n                dDM2Vprobe = 0\n            elif mp.est.probe.whichDM == 2:\n                dDM1Vprobe = 0\n                dDM2Vprobe = probeCmd/mp.dm1.VtoH  # Now in volts\n            else:\n                raise ValueError('DM for probing must be 1 or 2.')\n                \n            if np.any(mp.dm_ind == 1):\n                mp.dm1.V = DM1Vnom + dDM1Vprobe\n            if np.any(mp.dm_ind == 2):\n                mp.dm2.V = DM2Vnom + dDM2Vprobe\n                    \n            # Take probed image\n            if mp.flagFiber:\n                Im = falco.imaging.get_sbp_image_fiber(mp, si)\n            else:\n                Im = falco.imaging.get_sbp_image(mp, si)\n            \n            # plt.imshow(np.log10(Im)); plt.title('Probed Image %d' % iProbe); plt.colorbar(); plt.pause(1e-2);\n            \n            ImNonneg = Im\n            ImNonneg[Im < 0] = 0\n            whichImg = 1+iProbe  # Increment image counter\n            # Inorm averaged over all the probed images\n            ev.IprobedMean = ev.IprobedMean + \\\n                np.mean(Im[mp.Fend.corr.maskBool]) / (2*Npairs)\n    \n            # Store probed image and its DM settings\n            ev.Icube[:, :, whichImg] = Im\n            if np.any(mp.dm_ind == 1):\n                ev.Vcube1[:, :, whichImg] = mp.dm1.V\n            if np.any(mp.dm_ind == 2):\n                ev.Vcube2[:, :, whichImg] = mp.dm2.V\n    \n            # Report results\n            probeSign = '-+'\n            print('Actual Probe %d%s Contrast is: %.2e' % (\n                    np.floor(iProbe/2), probeSign[(iProbe+1) % 2],\n            np.mean(Im[mp.Fend.corr.maskBool])))\n\n            # Assign image to positive or negative probe collection:\n            if (iProbe+1) % 2 == 1:  # Odd; for plus probes\n                if np.any(mp.dm_ind == 1):\n                    DM1Vplus[:, :, iOdd] = dDM1Vprobe + DM1Vnom\n                if np.any(mp.dm_ind == 2):\n                    DM2Vplus[:, :, iOdd] = dDM2Vprobe + DM2Vnom\n                Iplus[:, iOdd] = Im[mp.Fend.corr.maskBool]\n                iOdd += 1\n            elif (iProbe+1) % 2 == 0:  # Even; for minus probes\n                if np.any(mp.dm_ind == 1):\n                    DM1Vminus[:, :, iEven] = dDM1Vprobe + DM1Vnom\n                if np.any(mp.dm_ind == 2):\n                    DM2Vminus[:, :, iEven] = dDM2Vprobe + DM2Vnom\n                Iminus[:, iEven] = Im[mp.Fend.corr.maskBool]\n                iEven += 1\n    \n        # Calculate probe amplitudes and measurement vector.\n        # (Refer again to Give'on+ SPIE 2011 to undersand why.)\n        ampSq = (Iplus+Iminus)/2 - np.tile(I0vec.reshape((-1, 1)), (1, Npairs))  # square of probe E-field amplitudes\n        ampSq[ampSq < 0] = 0  # If probe amplitude is zero, set amp = 0\n        amp = np.sqrt(ampSq)  # E-field amplitudes, dimensions: [mp.Fend.corr.Npix, Npairs]\n        isnonzero = np.all(amp, 1)\n        zAll = ((Iplus-Iminus)/4).T  # Measurement vector, dimensions: [Npairs,mp.Fend.corr.Npix]\n        ampSq2Dcube = np.zeros((mp.Fend.Neta, mp.Fend.Nxi, mp.est.probe.Npairs))\n        for iProbe in range(Npairs):  # Display the actual probe intensity\n            ampSq2D = np.zeros((mp.Fend.Neta, mp.Fend.Nxi))\n            ampSq2D[mp.Fend.corr.maskBool] = ampSq[:, iProbe]\n            ampSq2Dcube[:, :, iProbe] = ampSq2D\n            print('*** Mean measured Inorm for probe #%d  =\\t%.3e' %\n                  (iProbe, np.mean(ampSq2D[mp.Fend.corr.maskBool])))\n    \n        # Plot relevant data for all the probes\n        # falco_plot_pairwi1se_probes(mp, ev,\n        #         DM1Vplus-repmat(DM1Vnom, [1,1,size(DM1Vplus,3)]),\n        #         ampSq2Dcube)\n    \n        # ################# Perform the estimation ############################\n        \n        # Use Jacobian for estimation. This is fully model-based if the\n        # Jacobian is purely model-based, or it is better if the Jacobian is\n        # adaptive based on empirical data.\n        if mp.est.flagUseJac:\n            \n            dEplus = np.zeros_like(Iplus, dtype=complex)\n            for iProbe in range(Npairs):\n                if mp.est.probe.whichDM == 1:\n                    dV = DM1Vplus[:, :, iProbe] - DM1Vnom\n                    dEplus[:, iProbe] = np.squeeze(jacStruct.G1[:, :, si]) * \\\n                        dV[mp.dm1.act_ele]\n                elif mp.est.probe.whichDM == 2:\n                    dV = DM2Vplus[:, :, iProbe] - DM2Vnom\n                    dEplus[:, iProbe] = np.squeeze(jacStruct.G2[:, :, si]) * \\\n                        dV[mp.dm2.act_ele]\n\n        # Get the probe phase from the model and measure the probe amplitude\n        else:\n\n            # For unprobed field based on model:\n            if np.any(mp.dm_ind == 1):\n                mp.dm1.V = DM1Vnom\n            if np.any(mp.dm_ind == 2):\n                mp.dm2.V = DM2Vnom\n            if mp.flagFiber:\n                pass\n                # [~, E0] = model_compact(mp, modvar)\n            else:\n                E0 = falco.model.compact(mp, modvar)\n\n            E0vec = E0[mp.Fend.corr.maskBool]\n    \n            # For probed fields based on model:\n            Eplus = np.zeros_like(Iplus, dtype=complex)\n            Eminus = np.zeros_like(Iminus, dtype=complex)\n            for iProbe in range(Npairs):\n                # For plus probes:\n                if np.any(mp.dm_ind == 1):\n                    mp.dm1.V = np.squeeze(DM1Vplus[:, :, iProbe])\n                if np.any(mp.dm_ind == 2):\n                    mp.dm2.V = np.squeeze(DM2Vplus[:, :, iProbe])\n                if(mp.flagFiber):\n                    pass\n                    # [~, Etemp] = model_compact(mp, modvar);\n                else:\n                    Etemp = falco.model.compact(mp, modvar)\n                Eplus[:, iProbe] = Etemp[mp.Fend.corr.maskBool]\n                \n                # For minus probes:\n                if np.any(mp.dm_ind == 1):\n                    mp.dm1.V = np.squeeze(DM1Vminus[:, :, iProbe])\n                if np.any(mp.dm_ind == 2):\n                    mp.dm2.V = np.squeeze(DM2Vminus[:, :, iProbe])\n                if mp.flagFiber:\n                    pass\n                    # [~, Etemp] = model_compact(mp, modvar)\n                else:\n                    Etemp = falco.model.compact(mp, modvar)\n                Eminus[:, iProbe] = Etemp[mp.Fend.corr.maskBool]\n    \n            # Create delta E-fields for each probe image.\n            # Then create Npairs phase angles.\n            dEplus = Eplus - np.tile(E0vec.reshape((-1, 1)), (1, Npairs))\n            dEminus = Eminus - np.tile(E0vec.reshape((-1, 1)), (1, Npairs))\n            dphdm = np.zeros((mp.Fend.corr.Npix, Npairs))  # phases\n            for iProbe in range(Npairs):\n                dphdm[:, iProbe] = np.arctan2(\n                    np.imag(dEplus[:, iProbe]) - np.imag(dEminus[:, iProbe]),\n                    np.real(dEplus[:, iProbe]) - np.real(dEminus[:, iProbe]))\n                    \n        # Batch process the measurements to estimate the electric field in the\n        # dark hole. Done pixel by pixel.\n        \n        if (mp.estimator.lower() == 'pwp-bp') or \\\n            (mp.estimator.lower() == 'pwp-kf' and ev.Itr < mp.est.ItrStartKF):\n    \n            Eest = np.zeros((mp.Fend.corr.Npix,), dtype=complex)\n            zerosCounter = 0  # number of zeroed-out dark hole pixels\n            for ipix in range(mp.Fend.corr.Npix):\n                \n                if mp.est.flagUseJac:\n                    dE = dEplus[ipix, :].T\n                    H = np.array([np.real(dE), np.imag(dE)])\n                else:\n                    H = np.zeros([Npairs, 2])  # Observation matrix\n                    # Leave Eest for a pixel as zero if any probe amp is 0\n                    if isnonzero[ipix] == 1:\n                        for iProbe in range(Npairs):\n                            H[iProbe, :] = amp[ipix, iProbe] * \\\n                                np.array([np.cos(dphdm[ipix, iProbe]),\n                                          np.sin(dphdm[ipix, iProbe])])\n                    else:\n                        zerosCounter += 1\n    \n                Epix = np.linalg.pinv(H) @ zAll[:, ipix]  # Batch processing\n                Eest[ipix] = Epix[0] + 1j*Epix[1]\n\n            # If estimate is too bright, the estimate was probably bad.\n            # !!!!!!!!!!!!!!BE VERY CAREFUL WITH THIS HARD-CODED VALUE!!!!!!!!!\n            Eest[np.abs(Eest)**2 > 1e-2] = 0.0\n            \n            print('%d of %d pixels were given zero probe amplitude.' %\n                    (zerosCounter, mp.Fend.corr.Npix))\n        \n            # Initialize the state and state covariance estimates for Kalman\n            # filter. The state is the real and imag parts of the E-field.\n            if mp.estimator.lower() == 'pwp-kf':\n                # Re-organize the batch-processed E-field estimate into the 1st\n                # state estimate for the Kalman filter\n                xOld = np.zeros((2*mp.Fend.corr.Npix, 1))\n                for ii in range(mp.Fend.corr.Npix):\n                    xOld[2*(ii-1)+0:2*(ii-1)+1] = np.array([np.real(Eest[ii]),\n                                                            np.imag(Eest[ii])])\n                ev.xOld = xOld  # Save out for returning later\n    \n                # Initialize the state covariance matrix\n                # (2x2 for each dark hole pixel)\n                ev.Pold_KF_array = np.tile(mp.est.Pcoef0*np.eye(2),\n                                           (mp.Fend.corr.Npix, 1, mp.Nsbp))\n    \n        # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n        # Begin Kalman Filter Update\n        # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n        #\n        # To be completed later...\n        #\n        # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n        # End Kalman Filter Update\n        # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n        \n        # Save out the estimates\n        ev.Eest[:, si] = Eest\n        Iest = np.abs(Eest)**2\n        ev.IincoEst[:, si] = I0vec - Iest  # incoherent light\n    \n    # Other data to save out\n    ev.ampSqMean = np.mean(ampSq)  # Mean probe intensity\n    ev.ampNorm = amp/np.sqrt(InormProbe)  # Normalized probe amplitude maps\n    \n    # Calculate the mean normalized intensity over the whole dark hole at all\n    # wavelengths.\n    ev.InormEst = np.mean(Iest)\n    \n    # Reset DM commands to their values before probing\n    if np.any(mp.dm_ind == 1):\n        mp.dm1.V = DM1Vnom\n    \n    if np.any(mp.dm_ind == 2):\n        mp.dm2.V = DM2Vnom\n    \n    print('Completed pairwise probing estimation.')\n \n    pass\n    # return None\n\n\ndef gen_pairwise_probe(mp, InormDes, psi, badAxis):\n    \"\"\"\n    Generate delta DM commands that probe the dark hole.\n    \n    Parameters\n    ----------\n    mp : falco.config.ModelParameter\n        Object containing all model parameters.\n    InormDes : float\n        Desired normalized intensity of the probes in the image.\n    psi : float\n        phase angle of the sinusoidal part of the probe. Units of radians.\n    badAxis : TYPE\n        DESCRIPTION.\n\n    Returns\n    -------\n    probeCmd : array_like\n         Nact x Nact array of delta DM actuator commands to make a probe.\n    \"\"\"\n    check.real_positive_scalar(InormDes, 'InormDes', ValueError)\n    check.real_scalar(psi, 'psi', TypeError)\n    if badAxis.lower() not in ('x', 'y', 'm'):\n        raise ValueError('Invalid value for badAxis.')\n        \n    # Number of actuators across DM surface\n    # (independent of beam diameter for time being)\n    if mp.est.probe.whichDM == 1:\n        Nact = mp.dm1.Nact\n        dm = mp.dm1\n    elif mp.est.probe.whichDM == 2:\n        Nact = mp.dm2.Nact\n        dm = mp.dm2\n    \n    # Coordinates in actuator space\n    xs = np.arange(-(Nact-1)/2, (Nact+1)/2)/Nact - \\\n        np.round(mp.est.probe.offsetX)/Nact\n    ys = np.arange(-(Nact-1)/2, (Nact+1)/2)/Nact - \\\n        np.round(mp.est.probe.offsetY)/Nact\n    [XS, YS] = np.meshgrid(xs, ys)\n    \n    # Restrict the probing region if it is not possible to achieve\n    if mp.est.probe.radius > Nact/2.0:\n        mp.est.probe.radius = Nact/2.0\n    \n    # Generate the DM command for the probe\n    magn = 4*np.pi*mp.lambda0*np.sqrt(InormDes)  # surface height to get desired intensity [meters]\n    if badAxis.lower() == 'y':\n        mX = mp.est.probe.radius\n        mY = 2*mp.est.probe.radius\n        omegaX = mp.est.probe.radius/2\n        probeSurf = magn*np.sinc(mX*XS)*np.sinc(mY*YS)*np.cos(2*np.pi*omegaX*XS + psi)\n\n    elif badAxis.lower() == 'x':\n        mX = 2*mp.est.probe.radius\n        mY = mp.est.probe.radius\n        omegaY = mp.est.probe.radius/2\n        probeSurf = magn*np.sinc(mX*XS)*np.sinc(mY*YS)*np.cos(2*np.pi*omegaY*YS + psi)\n    \n    elif badAxis.lower() == 'm':\n        omegaX = mp.est.probe.Xloc/2\n        omegaY = mp.est.probe.Yloc/2\n        probeSurf = np.zeros_like(XS)\n        for i in range(mp.Fend.Nfiber):\n            probeSurf = probeSurf + \\\n                magn*np.sin(2*np.pi*omegaX(i)*XS + 2*np.pi*omegaY(i)*YS + psi)\n\n    # Option to use just the sincs for a zero phase shift. This avoids the\n    # phase discontinuity along one axis (for this probe only!).\n    if psi == 0:\n        m = 2*mp.est.probe.radius\n        probeSurf = magn*np.sinc(m*XS)*np.sinc(m*YS)\n    \n    probeCmd = falco.dm.fit_surf_to_act(dm, probeSurf)\n    \n    # Scale the probe amplitude empirically if needed\n    probeCmd = mp.est.probe.gainFudge*probeCmd\n    \n    return probeCmd\n", "meta": {"hexsha": "19188dbabb1022ce90aefd61532840a68e3b3f8e", "size": 23165, "ext": "py", "lang": "Python", "max_stars_repo_path": "falco/est.py", "max_stars_repo_name": "kian1377/falco-python", "max_stars_repo_head_hexsha": "a9666629845fc72957cd89339f924b9cfb7ce6f5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-05-22T22:24:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-21T13:32:36.000Z", "max_issues_repo_path": "falco/est.py", "max_issues_repo_name": "kian1377/falco-python", "max_issues_repo_head_hexsha": "a9666629845fc72957cd89339f924b9cfb7ce6f5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2018-06-22T01:05:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-03T13:46:25.000Z", "max_forks_repo_path": "falco/est.py", "max_forks_repo_name": "kian1377/falco-python", "max_forks_repo_head_hexsha": "a9666629845fc72957cd89339f924b9cfb7ce6f5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-06-21T23:58:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-13T21:25:23.000Z", "avg_line_length": 40.427574171, "max_line_length": 117, "alphanum_fraction": 0.5377077488, "include": true, "reason": "import numpy,from astropy", "num_tokens": 6270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.17927716416084485}}
{"text": "#-------------------------------- main.py file -----------------------------------------#\r\n\"\"\"\r\nMain file - entry point to the code. This file coordinates all other files and \r\nimplements all the functionality directly available to the user.\r\n\"\"\"\r\n\r\n# import statements\r\nimport numpy as np\r\nimport joblib\r\nfrom pkg_resources import get_distribution\r\nfrom boreas.models import makePrediction, RFModelIsotropic, TBNNSModelAnisotropic\r\nfrom boreas.case import TestCase, TrainingCase\r\nfrom boreas import process\r\nfrom boreas import constants\r\n\r\n\r\ndef printInfo():\r\n    \"\"\"\r\n    Makes sure everything is properly installed.\r\n    \r\n    We print a welcome message, the version of the package, and attempt to load\r\n    the pre-trained models to make sure the data file is there. Return 1 at the end\r\n    if no exceptions were raised.\r\n    \"\"\"\r\n    \r\n    print('Welcome to Boreas - a package for industrial deployment of machine-learned '\r\n          + 'turbulent mixing models for film cooling (formerly known as RaFoFC)!')\r\n    \r\n    # Get distribution version\r\n    dist = get_distribution('boreas')\r\n    print('Version: {}'.format(dist.version))\r\n    \r\n    # Try to load the default RF model and print information about it\r\n    print('Attempting to load the default RF model...')\r\n    rf = RFModelIsotropic()\r\n    rf.loadFromDisk()\r\n    print('Default model was found and can be loaded properly.')\r\n    print('\\t Description: ', end=\"\", flush=True)\r\n    rf.printDescription()\r\n    \r\n    # Try to load the default TBNNS model and print information about it\r\n    print('Attempting to load the default TBNN-s model...')\r\n    nn = TBNNSModelAnisotropic()\r\n    nn.loadFromDisk()\r\n    print('Default model was found and can be loaded properly.')\r\n    print('\\t Description: ', end=\"\", flush=True)\r\n    nn.printDescription()\r\n    \r\n    return 1 # return this if everything went ok\r\n\r\n    \r\ndef applyMLModel(tecplot_in_path, tecplot_out_path, *,  \r\n                 zone = None, deltaT0 = None, \r\n                 use_default_var_names = False, use_default_derivative_names = True,\r\n                 calc_derivatives = True, write_derivatives = True, \r\n                 threshold = None, default_prt = None, clean_features = True, \r\n                 features_load_path = None, features_dump_path = None,\r\n                 ip_file_path = None, csv_file_path = None,\r\n                 variables_to_write = None, outnames_to_write = None,                 \r\n                 model_path = None, secondary_model_path = None, \r\n                 model_type = \"RF\", features_type=\"F2\",\r\n                 ensemble_of_models = False, std_ensemble = False):\r\n    \"\"\"\r\n    Applies ML model on a single test case, given in a Tecplot file.\r\n    \r\n    Main function of package. Call this to take in a Tecplot file, process it, apply\r\n    the machine learning model, and save results to disk. All optional arguments must\r\n    be used with the identifying keyword (that's what * means)\r\n    \r\n    Arguments:\r\n    tecplot_in_path -- string containing the path of the input tecplot file. It must be\r\n                       a binary .plt file, resulting from a k-epsilon simulation.\r\n    tecplot_out_path -- string containing the path to which the final tecplot dataset\r\n                        will be saved.    \r\n    zone -- optional argument. The zone where the flow field solution is saved in \r\n            Tecplot. By default, it is zone 0. This can be either a string (with the \r\n            zone name) or an integer with the zone index.    \r\n    deltaT0 -- optional argument. Temperature scale (Tmax - Tmin) that will be used to \r\n               non-dimensionalize the dataset. If it is not provided (default behavior),\r\n               the user will be prompted to enter an appropriate number.    \r\n    use_default_var_names -- optional argument. Boolean flag (True/False) that determines\r\n                             whether default Fluent names will be used to fetch variables\r\n                             in the Tecplot dataset. If the flag is False (default \r\n                             behavior), the user will be prompted to enter names for each\r\n                             variable that is needed.\r\n    use_default_derivative_names -- optional argument. Boolean flag (True/False) that \r\n                                    determine if the user will pick the names for the\r\n                                    derivative quantities in the Tecplot file or whether\r\n                                    default names are used. This flag is only used if the\r\n                                    next flag is False (i.e., if derivatives are \r\n                                    already pre-calculated, then setting this flag to \r\n                                    False allows the user to input the names of each\r\n                                    derivative in the input .plt file). It defaults to\r\n                                    True.\r\n    calc_derivatives -- optional argument. Boolean flag (True/False) that determines \r\n                        whether derivatives need to be calculated in the Tecplot file.\r\n                        Note we need derivatives of U, V, W, and Temperature, with names\r\n                        ddx_{}, ddy_{}, ddz_{}. If such variables were already calculated\r\n                        and exist in the dataset, set this flag to False to speed up the \r\n                        process. By default (True), derivatives are calculated and a new\r\n                        file with derivatives called \"derivatives_{}\" will be saved to \r\n                        disk.\r\n    write_derivatives -- optional argument. Boolean flag (True/False) that determines \r\n                         whether to write a binary Tecplot file to disk with the newly\r\n                         calculated derivatives. The file will have the same name as the\r\n                         input, except followed by \"_derivatives\". This is useful because\r\n                         calculating derivatives takes a long time, so you might want to\r\n                         save results to disk as soon as they are calculated.    \r\n    threshold -- optional argument. This variable determines the threshold for \r\n                 (non-dimensional) temperature gradient below which we throw away a \r\n                 point. If None, use the value in constants.py (default value is 1e-3).\r\n                 For temperature gradient less than that, we use the Reynolds analogy\r\n                 (with fixed Pr_t). For gradients larger than that, we use the \r\n                 model.\r\n    default_prt -- optional argument, this variable contains the default value of Pr_t to\r\n                   use in regions where gradients are low or features have been cleaned.\r\n                   If this is None (default), then use the value from constants.py.\r\n    clean_features -- optional argument. This determines whether we should remove outlier\r\n                      points from the dataset before applying the model. This is measured\r\n                      by the standard deviation of points around the mean.\r\n    features_load_path -- optional argument. If this is supplied, then the function will\r\n                           try to load the features from disk instead of \r\n                           processing the tecplot file all over again. Since calculating\r\n                           the features can take a while for large datasets, this can be \r\n                           useful to speed up repetitions.                           \r\n    features_dump_path -- optional argument. If this is provided and we processed the\r\n                           tecplot data from scratch (i.e. we calculated the features), \r\n                           then the function will save the features to disk, so it is \r\n                           much faster to perform the same computations again later.\r\n    ip_file_path -- optional argument. String containing the path to which the\r\n                    interpolation file (which is read by ANSYS Fluent) will be saved. If\r\n                    this argument is None (by default), then no interpolation file is\r\n                    written.\r\n    csv_file_path -- optional argument. String containing the path to which the csv file\r\n                     (which can be read by StarCCM+) will be saved. If this is None \r\n                     (default), then no csv file is written.    \r\n    variables_to_write -- optional argument. This is a list of strings containing names \r\n                          of variables in the Tecplot file that we want to write in the \r\n                          Fluent interpolation file/CSV file. By default, it is None, \r\n                          which leads the program to pick only the diffusivity variables\r\n                          just calculated.\r\n    outnames_to_write -- optional argument. This is a list of strings that must have the \r\n                        same length as the previous argument. It contains the names that\r\n                        each of the variables written in the interpolation/csv files will \r\n                        have. By default, this is None, which leads to code to name all\r\n                        variables being written sequentially, starting at \"uds-2\". Naming\r\n                        them as \"user defined scalars x\" (uds-x) is an easy way to read\r\n                        them in Fluent.\r\n    model_path -- optional argument. This is the path where the function will look for\r\n                  a pre-trained machine learning model. The file must be a pickled\r\n                  instance of a random forest regressor class or a pickled instance of\r\n                  the TBNN-s class, saved to disk using joblib. If None, the default\r\n                  machine learning model that comes with the package(which is already\r\n                  pre-trained with LES/DNS) is employed.\r\n    secondary_model_path -- optional argument. This is the path where the function will\r\n                            look for a pre-trained random forest model to support the \r\n                            TBNN-s model in the hybrid formulation. The file must be a\r\n                            pickled instance of a random forest regressor class, saved to\r\n                            disk using joblib. By default, the default RF is loaded. This\r\n                            argument is only relevant when model_type = \"TBNNS_hybrid\".\r\n    model_type -- optional argument. This tells us which type of model we are loading.\r\n                  It must be a string, and the currently supported options are \"RF\",\r\n                  \"TBNNS\", and \"TBNNS_hybrid\". The default option is \"RF\".\r\n    features_type -- optional argument, string determining the type of features that\r\n                     we are currently extracting. Options are \"F1\" and \"F2\". Default\r\n                     value is \"F2\".\r\n    ensemble_of_models -- optional argument. This is a boolean flag that tells us whether\r\n                          to use a model ensemble instead of a single model instance. If\r\n                          this is true, the model_path parameter must be a list of paths\r\n                          instead of a single path. The default option is \"False\"\r\n    std_ensemble -- optional argument. This is a boolean flag that instructs the solver\r\n                    to return the standard deviation across the ensemble of models. This\r\n                    can only be True if ensemble_of_models=True; in which case, we only\r\n                    return the standard deviation and not the actual diffusivity. This\r\n                    option only makes sense for the TBNN-s model (since the RF is already\r\n                    an ensemble) and is not supported for the hybrid model. The default\r\n                    option is \"False\"\r\n    \"\"\"\r\n    \r\n    assert model_type == \"RF\" or model_type == \"TBNNS\" or model_type == \"TBNNS_hybrid\", \\\r\n            \"Invalid model_type received!\"\r\n    assert features_type == \"F1\" or features_type == \"F2\", \\\r\n            \"Invalid features_type received!\"\r\n            \r\n    if ensemble_of_models: # check whether model_path is a list if model ensemble\r\n        assert type(model_path) is list, \\\r\n            \"Error! For a model ensemble, model_path must be a list\"\r\n        assert len(model_path) > 0, \"Error! model_path is an empty list!\"\r\n    \r\n    # Initialize dataset and get scales for non-dimensionalization. The default behavior\r\n    # is to ask the user for the names and the scales. Passing keyword arguments to this\r\n    # function can be done to go around this behavior\r\n    dataset = TestCase(tecplot_in_path, zone=zone, \r\n                        use_default_names=use_default_var_names)\r\n    dataset.normalize(deltaT0=deltaT0)\r\n    \r\n    # If this flag is True (default) calculate the derivatives and save the result to\r\n    # disk (since it takes a while to do that...)\r\n    if calc_derivatives:\r\n        dataset.calculateDerivatives()\r\n        if write_derivatives: # write new Tecplot file to disk\r\n            dataset.saveDataset(tecplot_in_path[0:-4] + \"_derivatives.plt\")\r\n    else:\r\n        print(\"Derivatives already calculated!\")\r\n        dataset.addDerivativeNames(use_default_derivative_names)\r\n    \r\n    # Here, run the code for applying random forest model (\"RF\")\r\n    if model_type == \"RF\":\r\n        # This line processes the dataset and extracts features for the ML step which\r\n        # can take a long time. features_load_path and features_dump_path can be\r\n        # set to make the method load/save the processed quantities from disk.\r\n        x, _ = dataset.extractFeatures(with_tensor_basis=False, \r\n                                       features_type=features_type, threshold=threshold, \r\n                                       features_load_path=features_load_path,\r\n                                       features_dump_path=features_dump_path,\r\n                                       clean_features=clean_features)        \r\n        prt_ML = makePrediction(\"RF\", model_path, x, features_type)\r\n        \r\n        # Adds result to tecplot and sets the default variable names to output\r\n        varname = \"Prt_ML\"\r\n        dataset.addPrt(prt_ML, varname, default_prt)\r\n        if variables_to_write is None: \r\n            variables_to_write = [varname]\r\n        if outnames_to_write is None: \r\n            outnames_to_write = [\"uds-2\"]\r\n    \r\n    # Here, run the code for applying TBNN model (\"TBNNS\")\r\n    elif model_type == \"TBNNS\":\r\n        # This line processes the dataset and returns the features and tensor basis\r\n        # at each point in the dataset where gradients are significant.\r\n        x, tb = dataset.extractFeatures(with_tensor_basis=True, \r\n                                        features_type=features_type, threshold=threshold, \r\n                                        features_load_path=features_load_path,\r\n                                        features_dump_path=features_dump_path,\r\n                                        clean_features=clean_features)        \r\n        alphaij_ML, g_ML = makePrediction(\"TBNNS\", model_path, x, features_type, tb, \r\n                                          ensemble=ensemble_of_models, \r\n                                          std_flag=std_ensemble)\r\n                \r\n        # Adds result to tecplot and sets the default variable names to output\r\n        varname = [\"Dxx\", \"Dxy\", \"Dxz\", \"Dyx\", \"Dyy\", \"Dyz\", \"Dzx\", \"Dzy\", \"Dzz\"]\r\n        dataset.addTensorDiff(alphaij_ML, varname, default_prt)\r\n        g_name = [\"g1\", \"g2\", \"g3\", \"g4\", \"g5\", \"g6\"]\r\n        dataset.addG(g_ML, g_name, default_prt)\r\n        \r\n        if variables_to_write is None: \r\n            variables_to_write = varname\r\n        if outnames_to_write is None: \r\n            outnames_to_write = [\"uds-2\", \"uds-3\", \"uds-4\", \"uds-5\", \"uds-6\", \"uds-7\",\r\n                                 \"uds-8\", \"uds-9\", \"uds-10\"]\r\n    \r\n    # Here, run the code for applying TBNN-s + random forest model (\"TBNNS_hybrid\")\r\n    elif model_type == \"TBNNS_hybrid\":\r\n        # This line processes the dataset and returns the features and tensor basis\r\n        # at each point in the dataset where gradients are significant.\r\n        x, tb = dataset.extractFeatures(with_tensor_basis=True, \r\n                                        features_type=features_type, threshold=threshold, \r\n                                        features_load_path=features_load_path,\r\n                                        features_dump_path=features_dump_path,\r\n                                        clean_features=clean_features)        \r\n        alphaij_ML, g_ML = makePrediction(\"TBNNS\", model_path, x, features_type, tb,\r\n                                          ensemble=ensemble_of_models, \r\n                                          std_flag=std_ensemble)\r\n\r\n        # Now, get a random forest prediction for the turbulent Prandtl number\r\n        prt_ML = makePrediction(\"RF\", secondary_model_path, x, features_type)        \r\n        \r\n        # Combine alphaij_ML and prt_ML into a single diffusivity tensor\r\n        alphaij_mod = dataset.enforcePrt(alphaij_ML, prt_ML)\r\n        \r\n        # Adds result to tecplot and sets the default variable names to output\r\n        varname = [\"Dxx\", \"Dxy\", \"Dxz\", \"Dyx\", \"Dyy\", \"Dyz\", \"Dzx\", \"Dzy\", \"Dzz\"]\r\n        dataset.addTensorDiff(alphaij_mod, varname, default_prt)\r\n        g_name = [\"g1\", \"g2\", \"g3\", \"g4\", \"g5\", \"g6\"]\r\n        dataset.addG(g_ML, g_name, default_prt)\r\n        \r\n        if variables_to_write is None: \r\n            variables_to_write = varname\r\n        if outnames_to_write is None: \r\n            outnames_to_write = [\"uds-2\", \"uds-3\", \"uds-4\", \"uds-5\", \"uds-6\", \"uds-7\",\r\n                                 \"uds-8\", \"uds-9\", \"uds-10\"]\r\n        \r\n    # Write output: create interp/csv files and produce tecplot file\r\n    if ip_file_path is not None:\r\n        dataset.createInterpFile(ip_file_path, variables_to_write, outnames_to_write)    \r\n    if csv_file_path is not None:\r\n        dataset.createCsvFile(csv_file_path, variables_to_write, outnames_to_write)        \r\n    dataset.saveDataset(tecplot_out_path)\r\n\r\n\r\ndef produceTrainingFeatures(tecplot_in_path, *, data_path = None,  \r\n                            zone = None, deltaT0 = None, \r\n                            use_default_var_names = False, \r\n                            use_default_derivative_names = True,\r\n                            calc_derivatives = True, write_derivatives = True, \r\n                            threshold = None, clean_features = True, \r\n                            features_load_path = None, features_dump_path = None,\r\n                            prt_cap = None, gamma_correction = False,\r\n                            downsample = None, tecplot_out_path = None,\r\n                            model_type = \"RF\", features_type=\"F2\"):\r\n                            \r\n    \"\"\"\r\n    Produces features and labels from a single Tecplot file, used for training.\r\n    \r\n    This function is useful for training your own models. Call it on a single Tecplot\r\n    file (.plt) that contains all mean data including u'c' values, and it will process\r\n    it to generate the features and labels used for training. All optional arguments may\r\n    only be used with the keyword (that's what * means)\r\n    \r\n    Arguments:\r\n    tecplot_in_path -- string containing the path of the input tecplot file. It must be\r\n                       a binary .plt file, resulting from a k-epsilon simulation.\r\n    data_path -- optional argument. A string containing the path where a joblib file is\r\n                 saved, containing features and labels for training ML models. If None\r\n                 (default), a default name is employed.\r\n    zone -- optional argument. The zone where the flow field solution is saved in \r\n            Tecplot. By default, it is zone 0. This can be either a string (with the \r\n            zone name) or an integer with the zone index.    \r\n    deltaT0 -- optional argument. Temperature scale (Tmax - Tmin) that will be used to \r\n               non-dimensionalize the dataset. If it is not provided (default behavior),\r\n               the user will be prompted to enter an appropriate number.    \r\n    use_default_var_names -- optional argument. Boolean flag (True/False) that determines\r\n                             whether default Fluent names will be used to fetch variables\r\n                             in the Tecplot dataset. If the flag is False (default \r\n                             behavior), the user will be prompted to enter names for each\r\n                             variable that is needed.\r\n    use_default_derivative_names -- optional argument. Boolean flag (True/False) that \r\n                                    determine if the user will pick the names for the\r\n                                    derivative quantities in the Tecplot file or whether\r\n                                    default names are used. This flag is only used if the\r\n                                    next flag is False (i.e., if derivatives are \r\n                                    already pre-calculated, then setting this flag to \r\n                                    False allows the user to input the names of each\r\n                                    derivative in the input .plt file). It defaults to\r\n                                    True.\r\n    calc_derivatives -- optional argument. Boolean flag (True/False) that determines \r\n                        whether derivatives need to be calculated in the Tecplot file.\r\n                        Note we need derivatives of U, V, W, and Temperature, with names\r\n                        ddx_{}, ddy_{}, ddz_{}. If such variables were already calculated\r\n                        and exist in the dataset, set this flag to False to speed up the \r\n                        process. By default (True), derivatives are calculated and a new\r\n                        file with derivatives called \"derivatives_{}\" will be saved to \r\n                        disk.\r\n    write_derivatives -- optional argument. Boolean flag (True/False) that determines \r\n                         whether to write a binary Tecplot file to disk with the newly\r\n                         calculated derivatives. The file will have the same name as the\r\n                         input, except followed by \"_derivatives\". This is useful because\r\n                         calculating derivatives takes a long time, so you might want to\r\n                         save results to disk as soon as they are calculated.    \r\n    threshold -- optional argument. This variable determines the threshold for \r\n                 (non-dimensional) temperature gradient below which we throw away a \r\n                 point. If None, use the value in constants.py (default value is 1e-3).\r\n                 For temperature gradient less than that, we use the Reynolds analogy\r\n                 (with fixed Pr_t). For gradients larger than that, we use the \r\n                 model.\r\n    clean_features -- optional argument. This determines whether we should remove outlier\r\n                      points from the dataset before applying the model. This is measured\r\n                      by the standard deviation of points around the mean.\r\n    features_load_path -- optional argument. If this is supplied, then the function will\r\n                          try to load the features from disk instead of \r\n                          processing the tecplot file all over again. Since calculating\r\n                          the features can take a while for large datasets, this can be \r\n                          useful to speed up repetitions.                           \r\n    features_dump_path -- optional argument. If this is provided and we processed the\r\n                          tecplot data from scratch (i.e. we calculated the features), \r\n                          then the function will save the features to disk, so it is \r\n                          much faster to perform the same computations again later.\r\n    prt_cap -- optional, contains the (symmetric) cap on the value of Pr_t. If None,\r\n               then use the value in constants.py. If this value is 100, for example,\r\n               then 0.01 < Pr_t < 100, and values outside of this range are capped.\r\n    gamma_correction -- optional. If True, use the correction defined in \r\n                        Milani, Ling, Eaton (JTM 2020). That correction only makes\r\n                        sense if training data is on a fixed reference frame (it breaks\r\n                        Galilean invariance), so it is turned off by default. However,\r\n                        it can improve results in some cases.\r\n    downsample -- optional, number that controls how we downsample the data before\r\n                  saving it to disk. If None (default), it will read the number from \r\n                  constants.py. If this number is more than 1, then it represents the\r\n                  number of examples we want to save; if it is less than 1, it represents\r\n                  the ratio of all training examples we want to save.\r\n    tecplot_out_path -- optional, a string containing the path to which the final tecplot\r\n                        dataset will be saved. Useful for sanity checking the results. By\r\n                        default it is None (no .plt file saved)\r\n    model_type -- optional argument. This tells us which type of model we are loading.\r\n                  It must be a string, and the currently supported options are \"RF\".\r\n                  The default option is \"RF\".\r\n    features_type -- optional argument, string determining the type of features that\r\n                     we are currently extracting. Options are \"F1\" and \"F2\". Default\r\n                     value is \"F2\".\r\n    \"\"\"\r\n    \r\n    assert model_type == \"RF\" or model_type == \"TBNNS\" or model_type == \"TBNNS_hybrid\", \\\r\n           \"Invalid model_type received!\"\r\n    \r\n    # Initialize dataset and get scales for non-dimensionalization. The default behavior\r\n    # is to ask the user for the names and the scales. Passing keyword arguments to this\r\n    # function can be done to go around this behavior\r\n    dataset = TrainingCase(tecplot_in_path, zone=zone, \r\n                           use_default_names=use_default_var_names)\r\n    dataset.normalize(deltaT0=deltaT0)\r\n    \r\n    # If this flag is True (default) calculate the derivatives and save the result to\r\n    # disk (since it takes a while to do that...)\r\n    if calc_derivatives:\r\n        dataset.calculateDerivatives()\r\n        if write_derivatives: # write new Tecplot file to disk\r\n            dataset.saveDataset(tecplot_in_path[0:-4] + \"_derivatives.plt\")\r\n    else:\r\n        print(\"Derivatives already calculated!\")\r\n        dataset.addDerivativeNames(use_default_derivative_names)\r\n    \r\n    metadata = {}\r\n    metadata[\"features_type\"] = features_type\r\n    if model_type == \"RF\":\r\n        # This line processes the dataset and extracts features for the ML step which\r\n        # can take a long time. features_load_path and features_dump_path can be\r\n        # set to make the method load/save the processed quantities from disk.\r\n        x, _ = dataset.extractFeatures(with_tensor_basis=False, \r\n                                       features_type=features_type, threshold=threshold, \r\n                                       features_load_path=features_load_path,\r\n                                       features_dump_path=features_dump_path,\r\n                                       clean_features=clean_features)\r\n        gamma = dataset.extractGamma(prt_cap, gamma_correction) # gamma = 1/Prt\r\n        \r\n        training_list = [x, gamma]  # what is used for training\r\n        metadata[\"with_tensor_basis\"]=False\r\n        metadata[\"with_gamma\"]=True\r\n        \r\n        # Write the Tecplot data to disk with the extracted Prt_LES for sanity check\r\n        if tecplot_out_path is not None:\r\n            dataset.addPrt(1.0/gamma, \"Prt_LES\")\r\n            dataset.saveDataset(tecplot_out_path)  \r\n    \r\n    elif model_type == \"TBNNS\":\r\n        # This line processes the dataset and returns the features and tensor basis\r\n        # at each point in the dataset where gradients are significant.\r\n        x, tb = dataset.extractFeatures(with_tensor_basis=True, \r\n                                        features_type=features_type, threshold=threshold, \r\n                                        features_load_path=features_load_path,\r\n                                        features_dump_path=features_dump_path,\r\n                                        clean_features=clean_features)                                        \r\n        uc, gradT, nut = dataset.extractUc()\r\n        \r\n        training_list = [x, tb, uc, gradT, nut]  # what is used for training\r\n        metadata[\"with_tensor_basis\"]=True\r\n        metadata[\"with_gamma\"]=False    \r\n        \r\n    elif model_type == \"TBNNS_hybrid\":    \r\n        # This line processes the dataset and returns the features and tensor basis\r\n        # at each point in the dataset where gradients are significant.\r\n        x, tb = dataset.extractFeatures(with_tensor_basis=True, \r\n                                        features_type=features_type, threshold=threshold, \r\n                                        features_load_path=features_load_path,\r\n                                        features_dump_path=features_dump_path,\r\n                                        clean_features=clean_features)\r\n                                        \r\n        uc, gradT, nut = dataset.extractUc()\r\n        gamma = dataset.extractGamma(prt_cap, gamma_correction)\r\n        \r\n        training_list = [x, tb, uc, gradT, nut, gamma]  # what is used for training\r\n        metadata[\"with_tensor_basis\"]=True\r\n        metadata[\"with_gamma\"]=True    \r\n\r\n    # Saves joblib file to disk with features/labels for this dataset\r\n    # If data_path is None, use default name (appending _trainingdata to the end)\r\n    if data_path is None:\r\n        data_path = tecplot_in_path[0:-4] + \"_trainingdata.pckl\" # default name\r\n    \r\n    # Save training features to disk\r\n    process.saveTrainingFeatures(training_list, metadata, data_path, downsample)\r\n\r\n\r\ndef trainRFModel(features_list, description, model_path, *, features_type=\"F1\", \r\n                 downsample=None, n_trees = None, max_depth = None, \r\n                 min_samples_split = None, n_jobs = None):\r\n    \"\"\"\r\n    Trains a random forest model and saves it to disk.\r\n    \r\n    Trains a random forest, isotropic model, with features and labels previously \r\n    calculated. Multiple files can be used at the same time (each file in the list\r\n    comes from a given dataset. All optional arguments may only be used with the \r\n    keyword (that's what * means)\r\n    \r\n    Arguments:\r\n    features_list -- list containing paths to files saved to disk with features\r\n                     and labels for training. These files are produced by the function\r\n                     above (produceTrainingFeatures) from Tecplot files.\r\n    description -- A short, written description of the model being trained. It will be\r\n                   saved to disk together with the model itself.\r\n    model_path -- The path where the trained model will be saved in disk.\r\n    features_type -- optional argument, string determining the type of features that\r\n                     we are currently extracting. Options are \"F1\" and \"F2\". Default\r\n                     value is \"F1\".\r\n    downsample -- optional, number that controls how we downsample the data before\r\n                  using it to train. If None (default), it will read the number from \r\n                  constants.py. If this number is more than 1, then it represents the\r\n                  number of examples we want to save; if it is less than 1, it represents\r\n                  the ratio of all training examples we want to save. Can also be a list\r\n                  of numbers, in which case each number is applied to an element of\r\n                  features_list\r\n    n_trees -- optional. Hyperparameter of the random forest, contains number of\r\n                   trees to use. If None (default), reads value from constants.py\r\n    max_depth -- optional. Hyperparameter of the random forest, contains maximum\r\n                 depth of each tree to use. If None (default), reads value from\r\n                 constants.py \r\n    min_samples_split -- optional. Hyperparameter of the random forest, contains\r\n                         minimum number of samples at a node required to split. Can\r\n                         either be an int (number itself) or a float (ratio of total\r\n                         examples). If None (default), reads value from constants.py\r\n    n_jobs -- optional. Number of processors to use when training the RF (notice that\r\n              training is embarassingly parallel). If None (default behavior), then\r\n              the value is read from constants.py. See manual for \r\n              RandomForestRegressor class; if this is -1, all processors are used.\r\n    \"\"\"\r\n    \r\n    # Reads the list of files provided for features/labels\r\n    print(\"{} file(s) were provided and will be used\".format(len(features_list)))\r\n    x_list = []\r\n    y_list = []\r\n\r\n    if isinstance(downsample, list): # make sure list is the right size\r\n        assert len(downsample) == len(features_list), \\\r\n           \"downsample is a list, but it has the wrong number of entries!\"\r\n           \r\n    for i, file in enumerate(features_list):\r\n        if isinstance(downsample, list): # if list, take each element sequentially\r\n            x_features, gamma = process.loadTrainingFeatures(file, \"RF\", downsample[i],\r\n                                                             features_type)\r\n        else:\r\n            x_features, gamma = process.loadTrainingFeatures(file, \"RF\", downsample,\r\n                                                             features_type)\r\n            \r\n        x_list.append(x_features)\r\n        y_list.append(gamma)             \r\n    \r\n    x_total = np.concatenate(x_list, axis=0)\r\n    y_total = np.concatenate(y_list, axis=0)\r\n    \r\n    # Here, we train and save the model\r\n    rf = RFModelIsotropic()\r\n    rf.train(x_total, y_total, n_trees, max_depth, min_samples_split, n_jobs)\r\n    rf.save(description, model_path)\r\n    \r\n    \r\ndef trainTBNNSModel(features_list_train, features_list_dev, description, model_path, \r\n                    path_to_saver, *, FLAGS={}, features_type=\"F2\",\r\n                    downsample_train=None, downsample_dev=None,):\r\n    \"\"\"\r\n    Trains a TBNN-s and saves it to disk.\r\n    \r\n    Trains a TBNN-s, anisotropic model, with features and labels previously \r\n    calculated. Multiple files can be used at the same time (each file in the list\r\n    comes from a given dataset. All optional arguments may only be used with the \r\n    keyword (that's what * means)\r\n    \r\n    Arguments:\r\n    features_list_train -- list containing paths to files saved to disk with features\r\n                     and labels for training. These files are produced by the function\r\n                     above (produceTrainingFeatures) from Tecplot files.\r\n    features_list_dev -- list containing paths to files saved to disk with features\r\n                     and labels for the validation set. These files are produced by \r\n                     the function above (produceTrainingFeatures) from Tecplot files.\r\n    description -- A short, written description of the model being trained. It will be\r\n                   saved to disk together with the model itself.\r\n    model_path -- The path where the trained model will be saved in disk.\r\n    path_to_saver -- The path where the model parameters are saved to disk, through the\r\n                    tf.Saver class. Usually, we want to put that in a folder called\r\n                    checkpoints.\r\n    FLAGS -- optional argument, dictionary that controls training parameters for \r\n             the TBNNS model. Check the tbnns package to see what settings can be used.\r\n    features_type -- optional argument, string determining the type of features that\r\n                     we are currently extracting. Options are \"F1\" and \"F2\". Default\r\n                     value is \"F2\".\r\n    downsample_train -- optional, number that controls how we downsample the data before\r\n                  using it to train. If None (default), it will read the number from \r\n                  constants.py. If this number is more than 1, then it represents the\r\n                  number of examples we want to save; if it is less than 1, it represents\r\n                  the ratio of all training examples we want to save. Can also be a list\r\n                  of numbers, in which case each number is applied to an element of\r\n                  features_list.\r\n    downsample_dev -- optional, same as above for the dev set.        \r\n    \"\"\"\r\n    \r\n    # Reads the list of files provided for features/labels\r\n    print(\"{} file(s) were provided and will be used for training\"\\\r\n            .format(len(features_list_train)))\r\n    print(\"{} file(s) were provided and will be used for validation\"\\\r\n            .format(len(features_list_dev)))\r\n    \r\n    # Makes sure downsample list is the right size\r\n    if isinstance(downsample_train, list): \r\n        assert len(downsample_train) == len(features_list_train), \\\r\n           \"downsample is a list, but it has the wrong number of entries!\"\r\n    if isinstance(downsample_dev, list): # make sure list is the right size\r\n        assert len(downsample_dev) == len(features_list_dev), \\\r\n           \"downsample is a list, but it has the wrong number of entries!\"    \r\n    \r\n    # Load training files\r\n    x_list_train=[]; tb_list_train=[]; uc_list_train=[]; \r\n    gradT_list_train=[]; nut_list_train=[]\r\n    for i, file in enumerate(features_list_train):\r\n        if isinstance(downsample_train, list): # if list, take each element sequentially\r\n            x, tb, uc, gradT, nut = process.loadTrainingFeatures(file, \"TBNNS\", \r\n                                                                 downsample_train[i], \r\n                                                                 features_type)\r\n        else:\r\n            x, tb, uc, gradT, nut = process.loadTrainingFeatures(file, \"TBNNS\", \r\n                                                                 downsample_train,\r\n                                                                 features_type)            \r\n        x_list_train.append(x); tb_list_train.append(tb); uc_list_train.append(uc)\r\n        gradT_list_train.append(gradT); nut_list_train.append(nut)   \r\n    x_train = np.concatenate(x_list_train, axis=0)\r\n    tb_train = np.concatenate(tb_list_train, axis=0)\r\n    uc_train = np.concatenate(uc_list_train, axis=0)\r\n    gradT_train = np.concatenate(gradT_list_train, axis=0)\r\n    nut_train = np.concatenate(nut_list_train, axis=0)    \r\n    \r\n    # Load dev files\r\n    x_list_dev=[]; tb_list_dev=[]; uc_list_dev=[]; \r\n    gradT_list_dev=[]; nut_list_dev=[]\r\n    for i, file in enumerate(features_list_dev):\r\n        if isinstance(downsample_dev, list): # if list, take each element sequentially\r\n            x, tb, uc, gradT, nut = process.loadTrainingFeatures(file, \"TBNNS\", \r\n                                                                 downsample_dev[i],\r\n                                                                 features_type)\r\n        else:\r\n            x, tb, uc, gradT, nut = process.loadTrainingFeatures(file, \"TBNNS\", \r\n                                                                 downsample_dev,\r\n                                                                 features_type)            \r\n        x_list_dev.append(x); tb_list_dev.append(tb); uc_list_dev.append(uc)\r\n        gradT_list_dev.append(gradT); nut_list_dev.append(nut)   \r\n    x_dev = np.concatenate(x_list_dev, axis=0)\r\n    tb_dev = np.concatenate(tb_list_dev, axis=0)\r\n    uc_dev = np.concatenate(uc_list_dev, axis=0)\r\n    gradT_dev = np.concatenate(gradT_list_dev, axis=0)\r\n    nut_dev = np.concatenate(nut_list_dev, axis=0)    \r\n\r\n    # Edit FLAGS if necessary:\r\n    if features_type==\"F1\": FLAGS['num_features'] = constants.NUM_FEATURES_F1\r\n    elif features_type==\"F2\": FLAGS['num_features'] = constants.NUM_FEATURES_F2\r\n        \r\n    # Here, we train and save the model\r\n    nn = TBNNSModelAnisotropic()\r\n    nn.train(FLAGS, path_to_saver,\r\n             x_train, tb_train, uc_train, gradT_train, nut_train,\r\n             x_dev, tb_dev, uc_dev, gradT_dev, nut_dev)\r\n    nn.save(description, model_path)", "meta": {"hexsha": "c1abe4b869ac6cd9f690d7fc32568a53e79d29be", "size": 40551, "ext": "py", "lang": "Python", "max_stars_repo_path": "boreas/main.py", "max_stars_repo_name": "pmmilani/boreas", "max_stars_repo_head_hexsha": "e422b44236774d98bbf96f861dcc72e9e86d7b83", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-07-21T10:06:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-03T18:45:14.000Z", "max_issues_repo_path": "boreas/main.py", "max_issues_repo_name": "pmmilani/boreas", "max_issues_repo_head_hexsha": "e422b44236774d98bbf96f861dcc72e9e86d7b83", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boreas/main.py", "max_forks_repo_name": "pmmilani/boreas", "max_forks_repo_head_hexsha": "e422b44236774d98bbf96f861dcc72e9e86d7b83", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-21T10:06:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-21T10:06:25.000Z", "avg_line_length": 62.6754250386, "max_line_length": 111, "alphanum_fraction": 0.5965081009, "include": true, "reason": "import numpy", "num_tokens": 8007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.1792771572768154}}
{"text": "# This file is part of LayerModel_lib\n#\n#     A tool to compute the transmission behaviour of plane electromagnetic waves\n#     through human tissue.\n#\n# Copyright (C) 2018 Jan-Christoph Brumm\n#\n# Licensed under MIT license.\n#\nimport numpy as np\nimport os\n\nfrom LayerModel_lib.voxelmodel import VoxelModel\nfrom LayerModel_lib.voxelmodel_importer import VoxelModelImporter\nfrom LayerModel_lib.coordinate import Coordinate\n\ncurrent_directory = os.path.dirname(__file__)\nbase_path = os.path.join(current_directory, '..', '..', '..', '..', '..', 'Numerical Human Phantoms', 'Katja')\n\n# path to the AVW File of this model\nfilename = os.path.join(base_path, 'Katja')\n# path to the tissue_mapping file\ntissue_file = os.path.join('ImportKatja_tissues.txt')\n\nAVW_Data = VoxelModelImporter(filename, tissue_file, 'AVW')\nmodel_orig = AVW_Data.data['image']\ntissue_name_orig = AVW_Data.tissue_names\ntissue_mapping = AVW_Data.tissue_mapping\n\nKatja = VoxelModel()\nKatja.show_progress_bar = True\n\n# needs to be set manually from README.txt\nKatja.set_scale(1.775, 1.775, 4.84)\n\nKatja.name = 'Katja'\nKatja.description = 'Katja model from the Helmholtz Zentrum München. ' \\\n                    'Resolution %.2fmm x %.2fmm x %.2fmm' % (Katja.scaling.x,\n                                                             Katja.scaling.y, Katja.scaling.z)\n\n# For some reason Katja needs to be shifted left and back circularly\n# first the shift left\nmodel_orig = np.hstack((model_orig[:, 210::, :], model_orig[:, 0:210, :]))\n# then shift back\nmodel_orig = np.vstack((model_orig[16::, :, :], model_orig[0:16, :, :]))\n# Katja has inverse x coordinates in the model. Correct that by flipping along the first axis\nmodel_orig = np.flip(model_orig, axis=0)\n\n# Calculate the outer_shape of the original and the complete model\nouter_shape = AVW_Data.calculate_outer_shape(model_orig, tissue_mapping)\n\nKatja.add_voxel_data(short_name='original',\n                     name='Original data from AVW file',\n                     model=model_orig,\n                     outer_shape=outer_shape,\n                     tissue_names=tissue_name_orig)\n\nKatja.add_voxel_data(short_name='complete',\n                     name='The \\'original\\' model converted to our TissueProperties.',\n                     model=Katja.models['original'].data,\n                     outer_shape=outer_shape,\n                     tissue_mapping=tissue_mapping)\n\n# Calculate the trunk model\nstart_slice = int(177)\nend_slice = int(290)\n\n(model_trunk, trunk_mask) = AVW_Data.calculate_trunk_model(Katja, 'complete', z_start=start_slice, z_end=end_slice)\nouter_shape_trunk = AVW_Data.calculate_outer_shape(model_trunk)\n\nKatja.add_voxel_data(short_name='trunk',\n                     name=\"The trunk of the 'complete' model. Arms have been removed using \"\n                          \"VoxelModel.remove_arms().\",\n                     outer_shape=outer_shape_trunk,\n                     model=model_trunk,\n                     mask=trunk_mask,\n                     tissue_mapping=None)\n\nsurface = Katja.create_3d_model(model_type='trunk', patch_size=(30, 30))\nKatja.models['trunk'].surface_3d = surface\n\nKatja.models['trunk'].endpoints = []\nfor (i, s) in enumerate(surface):\n    Katja.models['trunk'].endpoints.append(Coordinate(np.array(s['centroid'])))\n\nKatja.save_model()\n", "meta": {"hexsha": "4df92b3984c60e8354677d27695bb3c88388c7f4", "size": 3296, "ext": "py", "lang": "Python", "max_stars_repo_path": "phantom_import/ImportKatja.py", "max_stars_repo_name": "janbrumm/layermodel_lib", "max_stars_repo_head_hexsha": "0d5e0c9ac77d302910823ebc757a4ec99541f3ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "phantom_import/ImportKatja.py", "max_issues_repo_name": "janbrumm/layermodel_lib", "max_issues_repo_head_hexsha": "0d5e0c9ac77d302910823ebc757a4ec99541f3ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phantom_import/ImportKatja.py", "max_forks_repo_name": "janbrumm/layermodel_lib", "max_forks_repo_head_hexsha": "0d5e0c9ac77d302910823ebc757a4ec99541f3ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8850574713, "max_line_length": 115, "alphanum_fraction": 0.6796116505, "include": true, "reason": "import numpy", "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3276683073862188, "lm_q1q2_score": 0.17914876484426767}}
{"text": "# Script to create Proximity Interaction Graphs. \n# Author: Marc Moesser\n# This script uses adapted functions from the ECIF script supplied in https://github.com/DIFACQUIM/ECIF\n\nimport pandas as pd\nimport numpy as np\nimport networkx as nx\nfrom scipy.spatial.distance import cdist\nfrom itertools import product\n\n\ndef GetAtomType(atom):\n# Atom types are defined as follows:\n# 1) Atom symbol\n# 2) Explicit Valence\n# 3) # Heavy Atom Neighbors\n# 4) # Hydrogen Neighbors\n# 5) Boolean: Is atom aromatic?\n# 6) Boolean: is atom in a ring?\n\n# This function can be used to identify all unique protein atom types in the dataset.\n    \n    AtomType = [atom.GetSymbol(),\n                str(atom.GetExplicitValence()),\n                str(len([x.GetSymbol() for x in atom.GetNeighbors() if x.GetSymbol() != \"H\"])),\n                str(len([x.GetSymbol() for x in atom.GetNeighbors() if x.GetSymbol() == \"H\"])),\n                str(int(atom.GetIsAromatic())),\n                str(int(atom.IsInRing())), \n               ]\n\n    return(\";\".join(AtomType))\n\n\ndef LoadSDFasDF(mol):\n# This function converts the input ligand (.MOL file) into a pandas DataFrame with the ligand atom position in 3D (X,Y,Z)\n    \n    m = mol\n    \n    atoms = []\n\n    for atom in m.GetAtoms():\n        if atom.GetSymbol() != \"H\": # Include only non-hydrogen atoms\n            entry = [int(atom.GetIdx())]\n            entry.append(str(atom.GetSymbol()))\n            pos = m.GetConformer().GetAtomPosition(atom.GetIdx())\n            entry.append(float(\"{0:.4f}\".format(pos.x)))\n            entry.append(float(\"{0:.4f}\".format(pos.y)))\n            entry.append(float(\"{0:.4f}\".format(pos.z)))\n            atoms.append(entry)\n\n    df = pd.DataFrame(atoms)\n    df.columns = [\"ATOM_INDEX\",\"ATOM_TYPE\",\"X\",\"Y\",\"Z\"]\n    \n    return(df)\n\n\ndef LoadPDBasDF(PDB, Atom_Keys):\n# This function converts a protein PDB file into a pandas DataFrame with the protein atom position in 3D (X,Y,Z)\n\n    prot_atoms = []\n    \n    f = open(PDB)\n    for i in f:\n        if i[:4] == \"ATOM\":\n            # Include only non-hydrogen atoms\n            if (len(i[12:16].replace(\" \",\"\")) < 4 and i[12:16].replace(\" \",\"\")[0] != \"H\") or (len(i[12:16].replace(\" \",\"\")) == 4 and i[12:16].replace(\" \",\"\")[1] != \"H\" and i[12:16].replace(\" \",\"\")[0] != \"H\"):\n                prot_atoms.append([int(i[6:11]),\n                         i[17:20]+\"-\"+i[12:16].replace(\" \",\"\"),\n                         float(i[30:38]),\n                         float(i[38:46]),\n                         float(i[46:54])\n                        ])\n                \n    f.close()\n    \n    df = pd.DataFrame(prot_atoms, columns=[\"ATOM_INDEX\",\"PDB_ATOM\",\"X\",\"Y\",\"Z\"])\n    df = df.merge(Atom_Keys, left_on='PDB_ATOM', right_on='PDB_ATOM')[[\"ATOM_INDEX\", \"ATOM_TYPE\", \"X\", \"Y\", \"Z\"]].sort_values(by=\"ATOM_INDEX\").reset_index(drop=True)\n    if list(df[\"ATOM_TYPE\"].isna()).count(True) > 0:\n        print(\"WARNING: Protein contains unsupported atom types. Only supported atom-type pairs are counted.\")\n    return(df)\n\ndef GetAtomContacts(PDB_protein, mol, Atom_Keys, distance_cutoff=6.0):\n# This function returns the list of protein atom types the ligand interacts with for a given distance cutoff\n# cutoff = 6 Angstrom is standard\n    \n    # Protein and ligand structure are loaded as pandas DataFrame\n    Target = LoadPDBasDF(PDB_protein, Atom_Keys)\n    Ligand = LoadSDFasDF(mol)\n    \n    # A cubic box around the ligand is created using the proximity threshold specified (here distance_cutoff = 6 Angstrom by default).\n    for i in [\"X\",\"Y\",\"Z\"]:\n        Target = Target[Target[i] < float(Ligand[i].max())+distance_cutoff]\n        Target = Target[Target[i] > float(Ligand[i].min())-distance_cutoff]\n\n    # Calculate the possible pairs\n    Pairs = list(product(Target[\"ATOM_TYPE\"], Ligand[\"ATOM_INDEX\"]))\n    Pairs = [str(x[0])+\"-\"+str(x[1]) for x in Pairs]\n    Pairs = pd.DataFrame(Pairs, columns=[\"ATOM_PAIR\"])\n    \n    Distances = cdist(Target[[\"X\",\"Y\",\"Z\"]], Ligand[[\"X\",\"Y\",\"Z\"]], metric=\"euclidean\")\n    Distances = Distances.reshape(Distances.shape[0]*Distances.shape[1],1)\n    Distances = pd.DataFrame(Distances, columns=[\"DISTANCE\"])\n\n    #Select pairs with distance lower than the cutoff\n    Pairs = pd.concat([Pairs,Distances], axis=1)\n    Pairs = Pairs[Pairs[\"DISTANCE\"] <= distance_cutoff].reset_index(drop=True)\n    \n    contact_pair_list = [i.split(\"-\")[0] for i in Pairs[\"ATOM_PAIR\"]]\n    Pairs[\"PROT_ATOM\"] = contact_pair_list\n    Pairs[\"LIG_ATOM\"] = [int(i.split(\"-\")[1]) for i in Pairs[\"ATOM_PAIR\"]]\n    \n    return Pairs\n\n\ndef atom_features(atom, features=[\"num_heavy_atoms\", \"total_num_Hs\", \"explicit_valence\", \"is_aromatic\", \"is_in_ring\"]):\n    # Computes the ligand atom features for graph node construction\n    # The standard features are the following:\n    # num_heavy_atoms = # of heavy atom neighbors\n    # total_num_Hs = # number of hydrogen atom neighbors\n    # explicit_valence = explicit valence of the atom\n    # is_aromatic = boolean 1 - aromatic, 0 - not aromatic\n    # is_in_ring = boolean 1 - is in ring, 0 - is not in ring\n\n    feature_list = []\n    if \"num_heavy_atoms\" in features:\n        feature_list.append(len([x.GetSymbol() for x in atom.GetNeighbors() if x.GetSymbol() != \"H\"]))\n    if \"total_num_Hs\" in features:\n        feature_list.append(len([x.GetSymbol() for x in atom.GetNeighbors() if x.GetSymbol() == \"H\"]))\n    if \"explicit_valence\" in features: #-NEW ADDITION FOR PLIG\n        feature_list.append(atom.GetExplicitValence())\n    if \"is_aromatic\" in features:\n        \n        if atom.GetIsAromatic():\n            feature_list.append(1)\n        else:\n            feature_list.append(0)\n    if \"is_in_ring\" in features:\n        if atom.IsInRing():\n            feature_list.append(1)\n        else:\n            feature_list.append(0)\n    return np.array(feature_list)\n\n\ndef atom_features_PLIG(atom_idx, atom, contact_df, extra_features, Atom_Keys):\n    # Generates the protein-ligand interaction features for the PLIG creation\n\n    possible_contacts = list(dict.fromkeys(Atom_Keys[\"ATOM_TYPE\"]))\n    feature_list = np.zeros(len(possible_contacts), dtype=int)\n    contact_df_slice = contact_df[contact_df[\"LIG_ATOM\"] == atom_idx]\n\n    #count the number of contacts between ligand and protein atoms\n    for i,contact in enumerate(possible_contacts):\n        for k in contact_df_slice[\"PROT_ATOM\"]:\n            if k == contact:\n                feature_list[i] +=1\n                \n    extra_feature_array = atom_features(atom, extra_features)\n    output = np.append(extra_feature_array, feature_list)\n\n    return output\n\ndef mol_to_graph(mol, contact_df, Atom_Keys, extra_features=[\"num_heavy_atoms\", \"total_num_Hs\", \"explicit_valence\",\"is_aromatic\", \"is_in_ring\"]):\n    #Final function to summarize the generation of PLIGS\n\n    #Extra features are any extra features to be added to the protein-ligand interaction features.\n    #In this work, we use the following ligand-based features as the ligand atom node features that are added to the interaction features:\n\n    #num_heavy_atoms\n    #total_num_hs\n    #explicit_valence\n    #is_aromatic\n    #is_in_ring\n\n    #However, this is freely customizable! Any additional features can be added here.\n\n\n\n    c_size = len([x.GetSymbol() for x in mol.GetAtoms() if x.GetSymbol() != \"H\"])\n    features = []\n    heavy_atom_index = []\n    idx_to_idx = {}\n    counter = 0\n\n    # Generate nodes\n    for atom in mol.GetAtoms():\n        if atom.GetSymbol() != \"H\": # Include only non-hydrogen atoms\n            idx_to_idx[atom.GetIdx()] = counter\n            counter +=1\n            heavy_atom_index.append(atom.GetIdx())\n            feature = atom_features_PLIG(atom.GetIdx(), atom, contact_df, extra_features, Atom_Keys)\n            features.append(feature)\n\n    #Generate edges\n    edges = []\n    for bond in mol.GetBonds():\n        idx1 = bond.GetBeginAtomIdx()\n        idx2 = bond.GetEndAtomIdx()\n        if idx1 in heavy_atom_index and idx2 in heavy_atom_index:\n            edges.append([idx_to_idx[bond.GetBeginAtomIdx()], idx_to_idx[bond.GetEndAtomIdx()]])\n    g = nx.Graph(edges).to_directed()\n    edge_index = []\n    for e1, e2 in g.edges:\n        edge_index.append([e1, e2])\n\n    #return molecular graph with its node features and edge indices\n    return c_size, features, edge_index\n", "meta": {"hexsha": "a06f2fbe7311ee5760b16019ff1c374a7ebe37fa", "size": 8266, "ext": "py", "lang": "Python", "max_stars_repo_path": "PLIG_tutorial/PLIG_utils.py", "max_stars_repo_name": "MarcMoesser/Protein-Ligand-Interaction-Graphs", "max_stars_repo_head_hexsha": "b1fc5e3016c193f56c2495aa57b1070c04722f4c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2022-03-03T21:08:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T05:17:32.000Z", "max_issues_repo_path": "PLIG_tutorial/PLIG_utils.py", "max_issues_repo_name": "MarcMoesser/Protein-Ligand-Interaction-Graphs", "max_issues_repo_head_hexsha": "b1fc5e3016c193f56c2495aa57b1070c04722f4c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PLIG_tutorial/PLIG_utils.py", "max_forks_repo_name": "MarcMoesser/Protein-Ligand-Interaction-Graphs", "max_forks_repo_head_hexsha": "b1fc5e3016c193f56c2495aa57b1070c04722f4c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7403846154, "max_line_length": 208, "alphanum_fraction": 0.6393660779, "include": true, "reason": "import numpy,from scipy,import networkx", "num_tokens": 2124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.32766830082071396, "lm_q1q2_score": 0.17914875641468112}}
{"text": "\"\"\"Library implementing attention modules.\n\nAuthors\n * Anonymous\n\"\"\"\n\nimport torch\nimport logging\nimport torch.nn as nn\nimport numpy as np\nfrom typing import Optional\nfrom speechbrain.dataio.dataio import length_to_mask\nimport torch.nn.functional as F\nimport math\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass ContentBasedAttention(nn.Module):\n    \"\"\" This class implements content-based attention module for seq2seq\n    learning.\n\n    Reference: NEURAL MACHINE TRANSLATION BY JOINTLY LEARNING TO ALIGN\n    AND TRANSLATE, Bahdanau et.al. https://arxiv.org/pdf/1409.0473.pdf\n\n    Arguments\n    ---------\n    attn_dim : int\n        Size of the attention feature.\n    output_dim : int\n        Size of the output context vector.\n    scaling : float\n        The factor controls the sharpening degree (default: 1.0).\n\n    Example\n    -------\n    >>> enc_tensor = torch.rand([4, 10, 20])\n    >>> enc_len = torch.ones([4]) * 10\n    >>> dec_tensor = torch.rand([4, 25])\n    >>> net = ContentBasedAttention(enc_dim=20, dec_dim=25, attn_dim=30, output_dim=5)\n    >>> out_tensor, out_weight = net(enc_tensor, enc_len, dec_tensor)\n    >>> out_tensor.shape\n    torch.Size([4, 5])\n    \"\"\"\n\n    def __init__(self, enc_dim, dec_dim, attn_dim, output_dim, scaling=1.0):\n        super(ContentBasedAttention, self).__init__()\n\n        self.mlp_enc = nn.Linear(enc_dim, attn_dim)\n        self.mlp_dec = nn.Linear(dec_dim, attn_dim)\n        self.mlp_attn = nn.Linear(attn_dim, 1, bias=False)\n        self.mlp_out = nn.Linear(enc_dim, output_dim)\n\n        self.scaling = scaling\n\n        self.softmax = nn.Softmax(dim=-1)\n\n        # reset the encoder states, lengths and masks\n        self.reset()\n\n    def reset(self):\n        \"\"\"Reset the memory in the attention module.\n        \"\"\"\n        self.enc_len = None\n        self.precomputed_enc_h = None\n        self.mask = None\n\n    def forward(self, enc_states, enc_len, dec_states):\n        \"\"\"Returns the output of the attention module.\n\n        Arguments\n        ---------\n        enc_states : torch.Tensor\n            The tensor to be attended.\n        enc_len : torch.Tensor\n            The real length (without padding) of enc_states for each sentence.\n        dec_states : torch.Tensor\n            The query tensor.\n\n        \"\"\"\n\n        if self.precomputed_enc_h is None:\n\n            self.precomputed_enc_h = self.mlp_enc(enc_states)\n            self.mask = length_to_mask(\n                enc_len, max_len=enc_states.size(1), device=enc_states.device\n            )\n\n        dec_h = self.mlp_dec(dec_states.unsqueeze(1))\n        attn = self.mlp_attn(\n            torch.tanh(self.precomputed_enc_h + dec_h)\n        ).squeeze(-1)\n\n        # mask the padded frames\n        attn = attn.masked_fill(self.mask == 0, -np.inf)\n        attn = self.softmax(attn * self.scaling)\n\n        # compute context vectors\n        # [B, 1, L] X [B, L, F]\n        context = torch.bmm(attn.unsqueeze(1), enc_states).squeeze(1)\n        context = self.mlp_out(context)\n\n        return context, attn\n\n\nclass LocationAwareAttention(nn.Module):\n    \"\"\"This class implements location-aware attention module for seq2seq learning.\n\n    Reference: Attention-Based Models for Speech Recognition, Chorowski et.al.\n    https://arxiv.org/pdf/1506.07503.pdf\n\n    Arguments\n    ---------\n    attn_dim : int\n        Size of the attention feature.\n    output_dim : int\n        Size of the output context vector.\n    conv_channels : int\n        Number of channel for location feature.\n    kernel_size : int\n        Kernel size of convolutional layer for location feature.\n    scaling : float\n        The factor controls the sharpening degree (default: 1.0).\n\n    Example\n    -------\n    >>> enc_tensor = torch.rand([4, 10, 20])\n    >>> enc_len = torch.ones([4]) * 10\n    >>> dec_tensor = torch.rand([4, 25])\n    >>> net = LocationAwareAttention(\n    ...     enc_dim=20,\n    ...     dec_dim=25,\n    ...     attn_dim=30,\n    ...     output_dim=5,\n    ...     conv_channels=10,\n    ...     kernel_size=100)\n    >>> out_tensor, out_weight = net(enc_tensor, enc_len, dec_tensor)\n    >>> out_tensor.shape\n    torch.Size([4, 5])\n    \"\"\"\n\n    precomputed_enc_h: Optional[torch.Tensor]\n\n    def __init__(\n        self,\n        enc_dim,\n        dec_dim,\n        attn_dim,\n        output_dim,\n        conv_channels,\n        kernel_size,\n        scaling=1.0,\n    ):\n        super(LocationAwareAttention, self).__init__()\n\n        self.mlp_enc = nn.Linear(enc_dim, attn_dim)\n        self.mlp_dec = nn.Linear(dec_dim, attn_dim)\n        self.mlp_attn = nn.Linear(attn_dim, 1, bias=False)\n        self.conv_loc = nn.Conv1d(\n            1,\n            conv_channels,\n            kernel_size=2 * kernel_size + 1,\n            padding=kernel_size,\n            bias=False,\n        )\n        self.mlp_loc = nn.Linear(conv_channels, attn_dim)\n        self.mlp_attn = nn.Linear(attn_dim, 1, bias=False)\n        self.mlp_out = nn.Linear(enc_dim, output_dim)\n\n        self.scaling = scaling\n\n        self.softmax = nn.Softmax(dim=-1)\n\n        # reset the encoder states, lengths and masks\n        self.reset()\n\n    def reset(self):\n        \"\"\"Reset the memory in attention module.\n        \"\"\"\n        self.enc_len = None\n        self.precomputed_enc_h = None\n        self.mask = None\n        self.prev_attn = None\n\n    def forward(self, enc_states, enc_len, dec_states):\n        \"\"\"Returns the output of the attention module.\n\n        Arguments\n        ---------\n        enc_states : torch.Tensor\n            The tensor to be attended.\n        enc_len : torch.Tensor\n            The real length (without padding) of enc_states for each sentence.\n        dec_states : torch.Tensor\n            The query tensor.\n        \"\"\"\n        if self.precomputed_enc_h is None:\n\n            self.precomputed_enc_h = self.mlp_enc(enc_states)\n            self.mask = length_to_mask(\n                enc_len, max_len=enc_states.size(1), device=enc_states.device\n            )\n\n            # multiply mask by 1/Ln for each row\n            self.prev_attn = self.mask * (1 / enc_len.float()).unsqueeze(1)\n\n        # compute location-aware features\n        # [B, 1, L] -> [B, C, L]\n        attn_conv = self.conv_loc(self.prev_attn.unsqueeze(1))\n        # [B, C, L] -> [B, L, C] -> [B, L, F]\n        attn_conv = self.mlp_loc(attn_conv.transpose(1, 2))\n\n        dec_h = self.mlp_dec(dec_states.unsqueeze(1))\n        attn = self.mlp_attn(\n            torch.tanh(self.precomputed_enc_h + dec_h + attn_conv)\n        ).squeeze(-1)\n\n        # mask the padded frames\n        attn = attn.masked_fill(self.mask == 0, -np.inf)\n        attn = self.softmax(attn * self.scaling)\n\n        # set prev_attn to current attn for the next timestep\n        self.prev_attn = attn.detach()\n\n        # compute context vectors\n        # [B, 1, L] X [B, L, F]\n        context = torch.bmm(attn.unsqueeze(1), enc_states).squeeze(1)\n        context = self.mlp_out(context)\n\n        return context, attn\n\n\nclass KeyValueAttention(nn.Module):\n    \"\"\" This class implements a single-headed key-value attention module for seq2seq\n    learning.\n\n    Reference: \"Attention Is All You Need\" by Vaswani et al., sec. 3.2.1\n\n    Arguments\n    ---------\n    enc_dim : int\n        Size of the encoder feature vectors from which keys and values are computed.\n    dec_dim : int\n        Size of the decoder feature vectors from which queries are computed.\n    attn_dim : int\n        Size of the attention feature.\n    output_dim : int\n        Size of the output context vector.\n\n    Example\n    -------\n    >>> enc_tensor = torch.rand([4, 10, 20])\n    >>> enc_len = torch.ones([4]) * 10\n    >>> dec_tensor = torch.rand([4, 25])\n    >>> net = KeyValueAttention(enc_dim=20, dec_dim=25, attn_dim=30, output_dim=5)\n    >>> out_tensor, out_weight = net(enc_tensor, enc_len, dec_tensor)\n    >>> out_tensor.shape\n    torch.Size([4, 5])\n    \"\"\"\n\n    def __init__(self, enc_dim, dec_dim, attn_dim, output_dim):\n        super(KeyValueAttention, self).__init__()\n\n        self.key_linear = nn.Linear(enc_dim, attn_dim)\n        self.query_linear = nn.Linear(dec_dim, attn_dim)\n        self.value_linear = nn.Linear(enc_dim, output_dim)\n        self.scaling = torch.sqrt(torch.tensor(attn_dim).float())\n\n        # reset the encoder states, lengths and masks\n        self.reset()\n\n    def reset(self):\n        \"\"\"Reset the memory in the attention module.\n        \"\"\"\n        self.values = None\n        self.keys = None\n        self.mask = None\n\n    def forward(self, enc_states, enc_len, dec_states):\n        \"\"\"Returns the output of the attention module.\n\n        Arguments\n        ---------\n        enc_states : torch.Tensor\n            The tensor to be attended.\n        enc_len : torch.Tensor\n            The real length (without padding) of enc_states for each sentence.\n        dec_states : torch.Tensor\n            The query tensor.\n        \"\"\"\n\n        if self.keys is None:\n\n            self.keys = self.key_linear(enc_states)\n            self.values = self.value_linear(enc_states)\n            self.mask = length_to_mask(\n                enc_len, max_len=enc_states.size(1), device=enc_states.device\n            ).unsqueeze(2)\n\n        query = self.query_linear(dec_states).unsqueeze(2)\n        scores = torch.matmul(self.keys, query) / self.scaling\n        scores = scores.masked_fill(self.mask == 0, -np.inf)\n        normalized_scores = scores.softmax(1).transpose(1, 2)\n        out = torch.matmul(normalized_scores, self.values).squeeze(1)\n        return out, normalized_scores\n\n\nclass RelPosEncXL(nn.Module):\n    \"\"\"\n\n    \"\"\"\n\n    def __init__(self, emb_dim):\n        super().__init__()\n        self.emb_dim = emb_dim\n\n        inv_freq = torch.exp(\n            torch.arange(0, self.emb_dim, 2, dtype=torch.float32)\n            * -(math.log(10000.0) / self.emb_dim)\n        )\n        self.register_buffer(\"inv_freq\", inv_freq)\n\n    def forward(self, x: torch.Tensor):\n        \"\"\"\n        Parameters\n        ----------\n        x : torch.Tensor\n        input tensor with shape seq_len, batch_size, embed_dim\n        Returns\n        -------\n        pos_emb : torch.Tensor\n        \"\"\"\n        seq_len = x.size(1)\n        with torch.no_grad():\n            tot_pe = torch.zeros((2, seq_len, self.emb_dim), dtype=x.dtype).to(\n                x\n            )\n            pe_past = tot_pe[0]\n            pe_future = tot_pe[1]\n            positions = (\n                torch.arange(0, seq_len, dtype=x.dtype).to(x).unsqueeze(-1)\n            )\n            sinusoids = torch.sin(positions * self.inv_freq)\n            pe_past[:, 0::2] = sinusoids\n            pe_past[:, 1::2] = torch.cos(positions * self.inv_freq)\n            pe_future[:, 0::2] = sinusoids  # same for past and future\n            pe_future[:, 1::2] = torch.cos(-positions * self.inv_freq)\n\n            pe_past = torch.flip(pe_past, (0,)).unsqueeze(0)\n            pe_future = pe_future[1:].unsqueeze(0)\n            pe = torch.cat([pe_past, pe_future], dim=1)\n            # pe is now 1, 2*seq_len, embed_dim\n            return pe\n\n\nclass RelPosMHAXL(nn.Module):\n    \"\"\" This class implements the relative multihead implementation similar to that in Transformer XL\n    https://arxiv.org/pdf/1901.02860.pdf\n\n    Arguments\n    ---------\n    embed_dim : int\n        Size of the encoder feature vectors from which keys and values are computed.\n    num_heads: int\n        Number of attention heads.\n    dropout : float, optional\n        Dropout rate.\n    vbias: bool, optional\n        Whether to use bias for computing value.\n    vdim: int, optional\n        Size for value. Default is embed_dim (Note each head is embed_dim // num_heads).\n    mask_pos_future: bool, optional\n        Whether to mask future positional encodings values.\n        Must be true for causal applications e.g. decoder.\n    Example\n    -------\n    >>> inputs = torch.rand([6, 60, 512])\n    >>> pos_emb = torch.rand([1, 2*60-1, 512])\n    >>> net = RelPosMHAXL(num_heads=8, embed_dim=inputs.shape[-1])\n    >>> outputs, attn = net(inputs, inputs, inputs, pos_emb)\n    >>> outputs.shape\n    torch.Size([6, 60, 512])\n    \"\"\"\n\n    def __init__(\n        self,\n        embed_dim,\n        num_heads,\n        dropout=0.0,\n        vbias=False,\n        vdim=None,\n        mask_pos_future=False,\n    ):\n        super(RelPosMHAXL, self).__init__()\n        self.embed_dim = embed_dim\n        self.vdim = vdim if vdim is not None else embed_dim\n        self._qkv_same_embed_dim = self.vdim == embed_dim\n        self.mask_pos_future = mask_pos_future\n        self.vbias = vbias\n\n        self.num_heads = num_heads\n        self.dropout = dropout\n        self.head_dim = embed_dim // num_heads\n        self.vhead_dim = self.vdim // num_heads\n\n        assert (\n            self.head_dim * num_heads == self.embed_dim\n        ), \"embed_dim must be divisible by num_heads\"\n        assert (\n            self.vhead_dim * num_heads == self.vdim\n        ), \"vdim must be divisible by num_heads\"\n\n        if self._qkv_same_embed_dim is False:\n            self.qk_proj_weight = nn.Parameter(\n                torch.empty(2 * embed_dim, embed_dim)\n            )\n            self.v_proj_weight = nn.Parameter(torch.empty(self.vdim, embed_dim))\n        else:\n            self.in_proj_weight = nn.Parameter(\n                torch.empty(3 * embed_dim, embed_dim)\n            )\n\n        if vbias:\n            self.value_bias_weight = nn.Parameter(torch.empty(self.vdim))\n        else:\n            self.vbias = None\n\n        self.dropout_att = nn.Dropout(dropout)\n        self.out_proj = nn.Linear(self.vdim, embed_dim)\n\n        self.linear_pos = nn.Linear(embed_dim, embed_dim, bias=False)\n\n        self.pos_bias_u = nn.Parameter(\n            torch.empty(self.head_dim, self.num_heads)\n        )\n        self.pos_bias_v = nn.Parameter(\n            torch.empty(self.head_dim, self.num_heads)\n        )\n\n        if next(self.parameters()).dtype == torch.float16:\n            self.attn_fill_value = -65000\n        else:\n            self.attn_fill_value = -float(\"inf\")\n\n        self._reset_parameters()\n        self.scale = 1 / math.sqrt(self.embed_dim)\n\n    def _reset_parameters(self):\n        if self._qkv_same_embed_dim:\n            torch.nn.init.xavier_uniform_(self.in_proj_weight)\n        else:\n            torch.nn.init.xavier_uniform_(self.qk_proj_weight)\n            torch.nn.init.xavier_uniform_(self.v_proj_weight)\n\n        if self.vbias is not None:\n            torch.nn.init.constant_(self.value_bias_weight, 0.0)\n\n        # positional biases\n        torch.nn.init.xavier_uniform_(self.pos_bias_u)\n        torch.nn.init.xavier_uniform_(self.pos_bias_v)\n\n    def rel_shift(self, x):\n        # batch, head, time1, 2*time1-1.\n\n        zero_pad = torch.zeros(\n            (*x.size()[:3], 1), device=x.device, dtype=x.dtype\n        )\n        x_padded = torch.cat([zero_pad, x], dim=-1)\n\n        x_padded = x_padded.view(*x.size()[:2], x.size(3) + 1, x.size(2))\n        x = x_padded[:, :, 1:].view_as(x)[\n            :, :, :, : x.size(-1) // 2 + 1\n        ]  # only keep the positions from 0 to time2\n\n        if self.mask_pos_future:\n            ones = torch.ones((x.size(2), x.size(3)), device=x.device)\n            x = x * torch.tril(ones, x.size(3) - x.size(2))[None, None, :, :]\n\n        return x\n\n    def forward(\n        self,\n        query,\n        key,\n        value,\n        pos_embs,\n        key_padding_mask=None,\n        attn_mask=None,\n        return_attn_weights=True,\n    ):\n        \"\"\"\n        Arguments\n        ----------\n        query : tensor\n            (B, L, E) where L is the target sequence length,\n            B is the batch size, E is the embedding dimension.\n        key : tensor\n            (B, S, E) where S is the source sequence length,\n            B is the batch size, E is the embedding dimension.\n        value : tensor\n            (B, S, E) where S is the source sequence length,\n            B is the batch size, E is the embedding dimension.\n        pos_emb : tensor\n            bidirectional sinusoidal positional embedding tensor (1, 2*S-1, E) where S is the max length between source and target sequence lengths,\n            and E is the embedding dimension.\n        key_padding_mask : tensor\n            (B, S) where B is the batch size, S is the source sequence\n            length. If a ByteTensor is provided, the non-zero positions will\n            be ignored while the position with the zero positions will be\n            unchanged. If a BoolTensor is provided, the positions with the\n            value of True will be ignored while the position with the value\n            of False will be unchanged.\n        attn_mask : tensor\n            2D mask (L, S) where L is the target sequence length, S is\n            the source sequence length.\n            3D mask (N*num_heads, L, S) where N is the batch\n            size, L is the target sequence length, S is the source sequence\n            length. attn_mask ensure that position i is allowed to attend the\n            unmasked positions. If a ByteTensor is provided, the non-zero\n            positions are not allowed to attend while the zero positions will\n            be unchanged. If a BoolTensor is provided, positions with True is\n            not allowed to attend while False values will be unchanged. If a\n            FloatTensor is provided, it will be added to the attention weight.\n\n        Outputs\n        -------\n        out : tensor\n            (B, L, E) where L is the target sequence length, B is the\n            batch size, E is the embedding dimension.\n        attn_score : tensor\n            (B, L, S) where B is the batch size, L is the target\n            sequence length, S is the source sequence length.\n        \"\"\"\n\n        # query, key and value are of shape batch, time, embed_dim\n        bsz = query.shape[0]\n        klen = key.shape[1]\n        qlen = query.shape[1]\n\n        if self._qkv_same_embed_dim:\n            # self-attention\n            if (query is key or torch.equal(query, key)) and (\n                key is value or torch.equal(key, value)\n            ):\n                query, key, value = (\n                    nn.functional.linear(query, self.in_proj_weight)\n                    .view(bsz, -1, self.num_heads, self.head_dim * 3)\n                    .chunk(3, dim=-1)\n                )\n            else:\n                qweight, kweight, vweight = self.in_proj_weight.chunk(3, dim=0)\n                query = nn.functional.linear(query, qweight).view(\n                    bsz, -1, self.num_heads, self.head_dim\n                )\n                key = nn.functional.linear(key, kweight).view(\n                    bsz, -1, self.num_heads, self.head_dim\n                )\n                value = nn.functional.linear(value, vweight).view(\n                    bsz, -1, self.num_heads, self.head_dim\n                )\n        else:\n            raise NotImplementedError\n            query, key = (\n                nn.functional.linear(query, self.qk_proj_weight)\n                .view(bsz, -1, self.num_heads, self.head_dim * 2)\n                .chunk(2, dim=-1)\n            )\n            value = nn.functional.linear(value, self.v_proj_weight).view(\n                bsz, -1, self.num_heads, self.vhead_dim\n            )\n\n        if self.vbias is not None:\n            value = value + self.value_bias_weight.view(\n                1, 1, self.num_heads, self.vhead_dim\n            )\n\n        p_k = self.linear_pos(pos_embs).view(\n            1, -1, self.num_heads, self.head_dim\n        )\n        # (batch, head, klen, d_k)\n\n        q_with_bias_u = (\n            query + self.pos_bias_u.view(1, 1, self.num_heads, self.head_dim)\n        ).transpose(1, 2)\n        # (batch, head, qlen, d_k)\n        q_with_bias_v = (\n            query + self.pos_bias_v.view(1, 1, self.num_heads, self.head_dim)\n        ).transpose(1, 2)\n\n        # (batch, head, qlen, klen)\n        matrix_ac = torch.matmul(q_with_bias_u, key.permute(0, 2, 3, 1))\n        # (batch, num_heads, klen, 2*klen-1)\n        matrix_bd = torch.matmul(q_with_bias_v, p_k.permute(0, 2, 3, 1))\n        matrix_bd = self.rel_shift(matrix_bd)  # shifting trick\n\n        # if klen != qlen:\n        #   import ipdb\n        #  ipdb.set_trace(\n\n        attn_score = (matrix_ac + matrix_bd) * self.scale\n\n        # compute attention probability\n        if attn_mask is not None:\n            if attn_mask.ndim == 2:\n                attn_mask = attn_mask.view(1, 1, qlen, klen)\n            else:\n                attn_mask = attn_mask.view(-1, self.num_heads, qlen, klen)\n\n            if attn_mask.dtype == torch.bool:\n                attn_score = attn_score.masked_fill(\n                    attn_mask, self.attn_fill_value\n                )\n            else:\n                attn_score += attn_mask\n\n        if key_padding_mask is not None:\n            attn_score = attn_score.masked_fill(\n                key_padding_mask.view(bsz, 1, 1, klen), self.attn_fill_value,\n            )\n\n        attn_score = F.softmax(attn_score, dim=-1)\n        attn_score = self.dropout_att(attn_score)\n        x = torch.matmul(\n            attn_score, value.transpose(1, 2)\n        )  # (batch, head, time1, d_k)\n        x = (\n            x.transpose(1, 2)\n            .contiguous()\n            .view(bsz, -1, self.vhead_dim * self.num_heads)\n        )  # (batch, time1, d_model)\n\n        out = self.out_proj(x)\n        if return_attn_weights:\n            return out, attn_score\n        return out\n\n\nclass MultiheadAttention(nn.Module):\n    \"\"\" The class is a wrapper of MultiHead Attention for torch.nn.MultiHeadAttention.\n\n    Reference: https://pytorch.org/docs/stable/nn.html\n\n    Arguments\n    ----------\n    num_heads : int\n        parallel attention heads.\n    dropout : float\n        a Dropout layer on attn_output_weights (default: 0.0).\n    bias : bool\n        add bias as module parameter (default: True).\n    add_bias_kv : bool\n        add bias to the key and value sequences at dim=0.\n    add_zero_attn : bool\n        add a new batch of zeros to the key and value sequences at dim=1.\n    kdim : int\n        total number of features in key (default: None).\n    vdim : int\n        total number of features in value (default: None).\n\n    Example\n    -------\n    >>> inputs = torch.rand([8, 60, 512])\n    >>> net = MultiheadAttention(nhead=8, d_model=inputs.shape[-1])\n    >>> outputs, attn = net(inputs, inputs, inputs)\n    >>> outputs.shape\n    torch.Size([8, 60, 512])\n    \"\"\"\n\n    def __init__(\n        self,\n        nhead,\n        d_model,\n        dropout=0.0,\n        bias=True,\n        add_bias_kv=False,\n        add_zero_attn=False,\n        kdim=None,\n        vdim=None,\n    ):\n        super().__init__()\n\n        self.att = nn.MultiheadAttention(\n            embed_dim=d_model,\n            num_heads=nhead,\n            dropout=dropout,\n            bias=bias,\n            add_bias_kv=add_bias_kv,\n            add_zero_attn=add_zero_attn,\n            kdim=kdim,\n            vdim=vdim,\n        )\n\n    def forward(\n        self,\n        query,\n        key,\n        value,\n        attn_mask: Optional[torch.Tensor] = None,\n        key_padding_mask: Optional[torch.Tensor] = None,\n        return_attn_weights: Optional[torch.Tensor] = True,\n        pos_embs: Optional[torch.Tensor] = None,\n    ):\n        \"\"\"\n        Arguments\n        ----------\n        query : torch.Tensor\n            (B, L, E) where L is the target sequence length,\n            B is the batch size, E is the embedding dimension.\n        key : torch.Tensor\n            (B, S, E) where S is the source sequence length,\n            B is the batch size, E is the embedding dimension.\n        value : torch.Tensor\n            (B, S, E) where S is the source sequence length,\n            B is the batch size, E is the embedding dimension.\n        key_padding_mask : torch.Tensor, optional\n            (B, S) where B is the batch size, S is the source sequence\n            length. If a ByteTensor is provided, the non-zero positions will\n            be ignored while the position with the zero positions will be\n            unchanged. If a BoolTensor is provided, the positions with the\n            value of True will be ignored while the position with the value\n            of False will be unchanged.\n        attn_mask : torch.Tensor, optional\n            2D mask (L, S) where L is the target sequence length, S is\n            the source sequence length.\n            3D mask (N*num_heads, L, S) where N is the batch\n            size, L is the target sequence length, S is the source sequence\n            length. attn_mask ensure that position i is allowed to attend the\n            unmasked positions. If a ByteTensor is provided, the non-zero\n            positions are not allowed to attend while the zero positions will\n            be unchanged. If a BoolTensor is provided, positions with True is\n            not allowed to attend while False values will be unchanged. If a\n            FloatTensor is provided, it will be added to the attention weight.\n        pos_embs: torch.Tensor, optional\n            Positional embeddings added to the attention map of shape (L, S, E) or (L, S, 1).\n\n        Outputs\n        -------\n        attn_output : torch.Tensor\n            (B, L, E) where L is the target sequence length, B is the\n            batch size, E is the embedding dimension.\n        attn_output_weights : torch.Tensor\n            (B, L, S) where B is the batch size, L is the target\n            sequence length, S is the source sequence length.\n        \"\"\"\n        # give tensors of shape (time, batch, fea)\n        query = query.permute(1, 0, 2)\n        key = key.permute(1, 0, 2)\n        value = value.permute(1, 0, 2)\n\n        # this will be legit because of https://github.com/pytorch/pytorch/blob/5288d05cfdda85c46c4df84617fa7f37c21b10b3/torch/nn/functional.py#L4946\n        # we can inject relative learnable pos embeddings directly in MHA via the attn_mask\n        if pos_embs is not None:\n            if attn_mask is not None:\n                attn_mask += pos_embs\n            else:\n                attn_mask = pos_embs\n\n        output = self.att(\n            query,\n            key,\n            value,\n            attn_mask=attn_mask,\n            key_padding_mask=key_padding_mask,\n            need_weights=return_attn_weights,\n        )\n\n        if return_attn_weights:\n            output, attention_weights = output\n            # reshape the output back to (batch, time, fea)\n            output = output.permute(1, 0, 2)\n            return output, attention_weights\n        else:\n            output = output.permute(1, 0, 2)\n            return output\n\n\nclass PositionalwiseFeedForward(nn.Module):\n    \"\"\"The class implements the positional-wise feed forward module in\n    “Attention Is All You Need”.\n\n    Arguments\n    ----------\n    d_ffn: int\n        Hidden layer size.\n    input_shape : tuple, optional\n        Expected shape of the input. Alternatively use ``input_size``.\n    input_size : int, optional\n        Expected size of the input. Alternatively use ``input_shape``.\n    dropout: float, optional\n        Dropout rate.\n    activation: torch.nn.Module, optional\n        activation functions to be applied (Recommendation: ReLU, GELU).\n\n    Example\n    -------\n    >>> inputs = torch.rand([8, 60, 512])\n    >>> net = PositionalwiseFeedForward(256, input_size=inputs.shape[-1])\n    >>> outputs = net(inputs)\n    >>> outputs.shape\n    torch.Size([8, 60, 512])\n    \"\"\"\n\n    def __init__(\n        self,\n        d_ffn,\n        input_shape=None,\n        input_size=None,\n        dropout=0.0,\n        activation=nn.ReLU,\n    ):\n        super().__init__()\n\n        if input_shape is None and input_size is None:\n            raise ValueError(\"Expected one of input_shape or input_size\")\n\n        if input_size is None:\n            input_size = input_shape[-1]\n\n        self.ffn = nn.Sequential(\n            nn.Linear(input_size, d_ffn),\n            activation(),\n            nn.Dropout(dropout),\n            nn.Linear(d_ffn, input_size),\n        )\n\n    def forward(self, x):\n        # give a tensor of shap (time, batch, fea)\n        x = x.permute(1, 0, 2)\n        x = self.ffn(x)\n\n        # reshape the output back to (batch, time, fea)\n        x = x.permute(1, 0, 2)\n\n        return x\n", "meta": {"hexsha": "7ca304facffbac84793ba0e32ab41f627dbd19c0", "size": 28131, "ext": "py", "lang": "Python", "max_stars_repo_path": "speechbrain/nnet/attention.py", "max_stars_repo_name": "anonymspeechbrain/speechbrain", "max_stars_repo_head_hexsha": "9a0632ddb066f5bceffb71fb971552fb542f7b7e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "speechbrain/nnet/attention.py", "max_issues_repo_name": "anonymspeechbrain/speechbrain", "max_issues_repo_head_hexsha": "9a0632ddb066f5bceffb71fb971552fb542f7b7e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "speechbrain/nnet/attention.py", "max_forks_repo_name": "anonymspeechbrain/speechbrain", "max_forks_repo_head_hexsha": "9a0632ddb066f5bceffb71fb971552fb542f7b7e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6495215311, "max_line_length": 149, "alphanum_fraction": 0.5838398919, "include": true, "reason": "import numpy", "num_tokens": 6780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.1791232009493735}}
{"text": "\"\"\"Learning rate scheduler.\"\"\"\n\nimport numpy as np\nimport torch\n#from dotmap import DotMap\n#from fairseq.optim.fairseq_optimizer import FairseqOptimizer\n#from fairseq.optim.lr_scheduler import cosine_lr_scheduler\nfrom torch import nn\nfrom torch.optim.lr_scheduler import LambdaLR\nfrom functools import wraps\nimport warnings\nimport math\nfrom torch.optim.optimizer import Optimizer\nimport weakref\n\nEPOCH_DEPRECATION_WARNING = (\n    \"The epoch parameter in `scheduler.step()` was not necessary and is being \"\n    \"deprecated where possible. Please use `scheduler.step()` to step the \"\n    \"scheduler. During the deprecation, if epoch is different from None, the \"\n    \"closed form is used instead of the new chainable form, where available. \"\n    \"Please open an issue if you are unable to replicate your use case: \"\n    \"https://github.com/pytorch/pytorch/issues/new/choose.\"\n)\n# from transformers import (\n#     get_constant_schedule,\n#     get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup)\nclass _LRScheduler(object):\n\n    def __init__(self, optimizer, last_epoch=-1, verbose=False):\n\n        # Attach optimizer\n        if not isinstance(optimizer, Optimizer):\n            raise TypeError('{} is not an Optimizer'.format(\n                type(optimizer).__name__))\n        self.optimizer = optimizer\n\n        # Initialize epoch and base learning rates\n        if last_epoch == -1:\n            for group in optimizer.param_groups:\n                group.setdefault('initial_lr', group['lr'])\n        else:\n            for i, group in enumerate(optimizer.param_groups):\n                if 'initial_lr' not in group:\n                    raise KeyError(\"param 'initial_lr' is not specified \"\n                                   \"in param_groups[{}] when resuming an optimizer\".format(i))\n        self.base_lrs = [group['initial_lr'] for group in optimizer.param_groups]\n        self.last_epoch = last_epoch\n\n        # Following https://github.com/pytorch/pytorch/issues/20124\n        # We would like to ensure that `lr_scheduler.step()` is called after\n        # `optimizer.step()`\n        def with_counter(method):\n            if getattr(method, '_with_counter', False):\n                # `optimizer.step()` has already been replaced, return.\n                return method\n\n            # Keep a weak reference to the optimizer instance to prevent\n            # cyclic references.\n            instance_ref = weakref.ref(method.__self__)\n            # Get the unbound method for the same purpose.\n            func = method.__func__\n            cls = instance_ref().__class__\n            del method\n\n            @wraps(func)\n            def wrapper(*args, **kwargs):\n                instance = instance_ref()\n                instance._step_count += 1\n                wrapped = func.__get__(instance, cls)\n                return wrapped(*args, **kwargs)\n\n            # Note that the returned function here is no longer a bound method,\n            # so attributes like `__func__` and `__self__` no longer exist.\n            wrapper._with_counter = True\n            return wrapper\n\n        self.optimizer.step = with_counter(self.optimizer.step)\n        self.optimizer._step_count = 0\n        self._step_count = 0\n        self.verbose = verbose\n\n        self.step()\n\n    def state_dict(self):\n        \"\"\"Returns the state of the scheduler as a :class:`dict`.\n\n        It contains an entry for every variable in self.__dict__ which\n        is not the optimizer.\n        \"\"\"\n        return {key: value for key, value in self.__dict__.items() if key != 'optimizer'}\n\n    def load_state_dict(self, state_dict):\n        \"\"\"Loads the schedulers state.\n\n        Args:\n            state_dict (dict): scheduler state. Should be an object returned\n                from a call to :meth:`state_dict`.\n        \"\"\"\n        self.__dict__.update(state_dict)\n\n    def get_last_lr(self):\n        \"\"\" Return last computed learning rate by current scheduler.\n        \"\"\"\n        return self._last_lr\n\n    def get_lr(self):\n        # Compute learning rate using chainable form of the scheduler\n        raise NotImplementedError\n\n    def print_lr(self, is_verbose, group, lr, epoch=None):\n        \"\"\"Display the current learning rate.\n        \"\"\"\n        if is_verbose:\n            if epoch is None:\n                print('Adjusting learning rate'\n                      ' of group {} to {:.4e}.'.format(group, lr))\n            else:\n                print('Epoch {:5d}: adjusting learning rate'\n                      ' of group {} to {:.4e}.'.format(epoch, group, lr))\n\n\n    def step(self, epoch=None):\n        # Raise a warning if old pattern is detected\n        # https://github.com/pytorch/pytorch/issues/20124\n        if self._step_count == 1:\n            if not hasattr(self.optimizer.step, \"_with_counter\"):\n                warnings.warn(\"Seems like `optimizer.step()` has been overridden after learning rate scheduler \"\n                              \"initialization. Please, make sure to call `optimizer.step()` before \"\n                              \"`lr_scheduler.step()`. See more details at \"\n                              \"https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate\", UserWarning)\n\n            # Just check if there were two first lr_scheduler.step() calls before optimizer.step()\n            elif self.optimizer._step_count < 1:\n                warnings.warn(\"Detected call of `lr_scheduler.step()` before `optimizer.step()`. \"\n                              \"In PyTorch 1.1.0 and later, you should call them in the opposite order: \"\n                              \"`optimizer.step()` before `lr_scheduler.step()`.  Failure to do this \"\n                              \"will result in PyTorch skipping the first value of the learning rate schedule. \"\n                              \"See more details at \"\n                              \"https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate\", UserWarning)\n        self._step_count += 1\n\n        class _enable_get_lr_call:\n\n            def __init__(self, o):\n                self.o = o\n\n            def __enter__(self):\n                self.o._get_lr_called_within_step = True\n                return self\n\n            def __exit__(self, type, value, traceback):\n                self.o._get_lr_called_within_step = False\n\n        with _enable_get_lr_call(self):\n            if epoch is None:\n                self.last_epoch += 1\n                values = self.get_lr()\n            else:\n                warnings.warn(EPOCH_DEPRECATION_WARNING, UserWarning)\n                self.last_epoch = epoch\n                if hasattr(self, \"_get_closed_form_lr\"):\n                    values = self._get_closed_form_lr()\n                else:\n                    values = self.get_lr()\n\n        for i, data in enumerate(zip(self.optimizer.param_groups, values)):\n            param_group, lr = data\n            param_group['lr'] = lr\n            self.print_lr(self.verbose, i, lr, epoch)\n\n        self._last_lr = [group['lr'] for group in self.optimizer.param_groups]\n\nclass CosineAnnealingLR(_LRScheduler):\n    r\"\"\"Set the learning rate of each parameter group using a cosine annealing\n    schedule, where :math:`\\eta_{max}` is set to the initial lr and\n    :math:`T_{cur}` is the number of epochs since the last restart in SGDR:\n\n    .. math::\n        \\begin{aligned}\n            \\eta_t & = \\eta_{min} + \\frac{1}{2}(\\eta_{max} - \\eta_{min})\\left(1\n            + \\cos\\left(\\frac{T_{cur}}{T_{max}}\\pi\\right)\\right),\n            & T_{cur} \\neq (2k+1)T_{max}; \\\\\n            \\eta_{t+1} & = \\eta_{t} + \\frac{1}{2}(\\eta_{max} - \\eta_{min})\n            \\left(1 - \\cos\\left(\\frac{1}{T_{max}}\\pi\\right)\\right),\n            & T_{cur} = (2k+1)T_{max}.\n        \\end{aligned}\n\n    When last_epoch=-1, sets initial lr as lr. Notice that because the schedule\n    is defined recursively, the learning rate can be simultaneously modified\n    outside this scheduler by other operators. If the learning rate is set\n    solely by this scheduler, the learning rate at each step becomes:\n\n    .. math::\n        \\eta_t = \\eta_{min} + \\frac{1}{2}(\\eta_{max} - \\eta_{min})\\left(1 +\n        \\cos\\left(\\frac{T_{cur}}{T_{max}}\\pi\\right)\\right)\n\n    It has been proposed in\n    `SGDR: Stochastic Gradient Descent with Warm Restarts`_. Note that this only\n    implements the cosine annealing part of SGDR, and not the restarts.\n\n    Args:\n        optimizer (Optimizer): Wrapped optimizer.\n        T_max (int): Maximum number of iterations.\n        eta_min (float): Minimum learning rate. Default: 0.\n        last_epoch (int): The index of last epoch. Default: -1.\n        verbose (bool): If ``True``, prints a message to stdout for\n            each update. Default: ``False``.\n\n    .. _SGDR\\: Stochastic Gradient Descent with Warm Restarts:\n        https://arxiv.org/abs/1608.03983\n    \"\"\"\n\n    def __init__(self, optimizer, T_max, eta_min=0, last_epoch=-1, verbose=False):\n        self.T_max = T_max\n        self.eta_min = eta_min\n        super(CosineAnnealingLR, self).__init__(optimizer, last_epoch, verbose)\n\n    def get_lr(self):\n        if not self._get_lr_called_within_step:\n            warnings.warn(\"To get the last learning rate computed by the scheduler, \"\n                          \"please use `get_last_lr()`.\", UserWarning)\n\n        if self.last_epoch == 0:\n            return self.base_lrs\n        elif (self.last_epoch - 1 - self.T_max) % (2 * self.T_max) == 0:\n            return [group['lr'] + (base_lr - self.eta_min) *\n                    (1 - math.cos(math.pi / self.T_max)) / 2\n                    for base_lr, group in\n                    zip(self.base_lrs, self.optimizer.param_groups)]\n        return [(1 + math.cos(math.pi * self.last_epoch / self.T_max)) /\n                (1 + math.cos(math.pi * (self.last_epoch - 1) / self.T_max)) *\n                (group['lr'] - self.eta_min) + self.eta_min\n                for group in self.optimizer.param_groups]\n\n    def _get_closed_form_lr(self):\n        return [self.eta_min + (base_lr - self.eta_min) *\n                (1 + math.cos(math.pi * self.last_epoch / self.T_max)) / 2\n                for base_lr in self.base_lrs]\n\n\n\ndef clip_gradient(model, clip: float):\n    nn.utils.clip_grad_norm_(model.parameters(), clip)\n\n\nclass ConcatLR(torch.optim.lr_scheduler._LRScheduler):\n    \"\"\"\n    From Over9000\n    https://github.com/mgrankin/over9000/blob/master/train.py\n    \"\"\"\n    def __init__(self, optimizer, scheduler1, scheduler2, total_steps,\n                 pct_start=0.5, last_epoch=-1):\n        self.scheduler1 = scheduler1\n        self.scheduler2 = scheduler2\n        self.step_start = float(pct_start * total_steps) - 1\n        self.curr_epoch = 0\n        super(ConcatLR, self).__init__(optimizer, last_epoch)\n\n    def step(self):\n        if self.curr_epoch <= self.step_start:\n            self.scheduler1.step()\n        else:\n            self.scheduler2.step()\n        self.curr_epoch += 1\n        super().step()\n\n    def get_lr(self):\n        if self.curr_epoch <= self.step_start:\n            return self.scheduler1.get_last_lr()\n        else:\n            return self.scheduler2.get_last_lr()\n\n\nclass TradeoffAnnealer:\n    def __init__(self, c, num_steps=None):\n        \"\"\"\n        Anneal the tradeoff between label and augmentation loss according\n            to some schedule.\n\n        :param c: config\n        :param num_steps: int, provide when loading from checkpoint to fast-\n            forward to that tradeoff value.\n        \"\"\"\n        self.c = c\n        self.name = self.c.exp_tradeoff_annealing\n\n        self.num_steps = 0\n        self.init_tradeoff = self.c.exp_tradeoff\n        self.curr_tradeoff = self.c.exp_tradeoff\n        self.max_steps = self.get_max_steps()\n        self.step_map = {\n            'constant': self.constant_step,\n            'cosine': self.cosine_step,\n            'linear_decline': self.linear_decline_step}\n\n        if self.name not in self.step_map.keys():\n            raise NotImplementedError\n\n        self.step = self.step_map[self.name]\n\n        if num_steps > 0:\n            # If we are loading a model from checkpoint,\n            # should update the annealer to that number of steps.\n            for _ in range(num_steps):\n                self.step()\n\n            print(f'Fast-forwarded tradeoff annealer to step {num_steps}.')\n\n        print(\n            f'Initialized \"{self.name}\" augmentation/label tradeoff annealer. '\n            f'Annealing to minimum value in {self.max_steps} steps.')\n\n    def get_max_steps(self):\n        # If annealing proportion is set to -1,\n        if self.c.exp_tradeoff_annealing_proportion == -1:\n            # and the optimizer proportion is set, we use the optimizer\n            # proportion to determine how long it takes for the tradeoff to\n            # anneal to 0.\n            if self.c.exp_optimizer_warmup_proportion != -1:\n                return int(np.ceil(self.c.exp_optimizer_warmup_proportion\n                                   * self.c.exp_num_total_steps))\n            # and the optimizer proportion is not set,\n            # we take all steps to anneal.\n            else:\n                return self.c.exp_num_total_steps\n\n        if (self.c.exp_tradeoff_annealing_proportion < 0\n                or self.c.exp_tradeoff_annealing_proportion > 1):\n            raise Exception('Invalid tradeoff annealing proportion.')\n\n        # Otherwise, we use the tradeoff annealing proportion to determine\n        # for how long we anneal.\n        return int(np.ceil(self.c.exp_tradeoff_annealing_proportion\n                           * self.c.exp_num_total_steps))\n\n    def constant_step(self):\n        self.num_steps += 1\n        return self.curr_tradeoff\n\n    def linear_decline_step(self):\n        curr = self.num_steps\n        max_val = self.init_tradeoff\n\n        if self.num_steps <= self.max_steps:\n            self.curr_tradeoff = max_val - (curr / self.max_steps) * max_val\n        else:\n            self.curr_tradeoff = 0\n\n        self.num_steps += 1\n\n        return self.curr_tradeoff\n\n    def cosine_step(self):\n        if self.num_steps <= self.max_steps:\n            self.curr_tradeoff = self.init_tradeoff * (1 / 2) * (\n                np.cos(np.pi * (self.num_steps / self.max_steps)) + 1)\n        else:\n            self.curr_tradeoff = 0\n\n        self.num_steps += 1\n\n        return self.curr_tradeoff\n\n\nclass LRScheduler:\n    def __init__(self, c, name, optimizer):\n        self.c = c\n        self.name = name\n        self.optimizer = optimizer\n        self.num_steps = 0\n\n        self.construct_auto_scheduler()\n\n        print(f'Initialized \"{name}\" learning rate scheduler.')\n\n    def construct_auto_scheduler(self):\n        total_steps = self.c.exp_num_total_steps\n\n        if self.c.exp_optimizer_warmup_proportion >= 0:\n            num_warmup_steps = (\n                    total_steps * self.c.exp_optimizer_warmup_proportion)\n        else:\n            num_warmup_steps = self.c.exp_optimizer_warmup_fixed_n_steps\n\n        print(f'Warming up for {num_warmup_steps}/{total_steps} steps.')\n\n        if self.name == 'constant':\n            self.scheduler = get_constant_schedule(optimizer=self.optimizer)\n        elif self.name == 'linear_warmup':\n            self.scheduler = get_linear_schedule_with_warmup(\n                optimizer=self.optimizer,\n                num_warmup_steps=num_warmup_steps,\n                num_training_steps=total_steps)\n        # elif self.name == 'cosine_cyclic':\n        #     args = dict(\n        #         warmup_updates=num_warmup_steps,\n        #         warmup_init_lr=1e-7,\n        #         max_lr=self.c.exp_lr,\n        #         lr=[1e-7],\n        #         t_mult=2.,\n        #         lr_period_updates=num_warmup_steps * 2,\n        #         lr_shrink=0.5)\n        #     optim = FairseqOptimizer(None)\n        #     optim._optimizer = optim.optimizer = self.optimizer\n        #     self.scheduler = cosine_lr_scheduler.CosineSchedule(\n        #         optimizer=optim, args=DotMap(args))\n        elif self.name == 'polynomial_decay_warmup':\n            # Based on the fairseq implementation, which is based on BERT\n            self.scheduler = get_polynomial_decay_schedule_with_warmup(\n                optimizer=self.optimizer,\n                num_warmup_steps=num_warmup_steps,\n                num_training_steps=total_steps,\n                lr_end=1e-7,\n                power=1.0)\n        elif self.name == 'flat_and_anneal':\n            def d(x):\n                return 1\n\n            assert self.c.exp_optimizer_warmup_proportion >= 0\n\n            # We use exp_optimizer_warmup_proportion to denote the\n            # flat LR regime, prior to annealing\n            dummy = LambdaLR(self.optimizer, d)\n            cosine = CosineAnnealingLR(\n                self.optimizer, int(total_steps * (\n                    1 - self.c.exp_optimizer_warmup_proportion)))\n            self.scheduler = ConcatLR(\n                self.optimizer, dummy, cosine, total_steps,\n                self.c.exp_optimizer_warmup_proportion)\n        else:\n            raise NotImplementedError\n\n    def step(self):\n        self.num_steps += 1\n        c_lr = self.c.exp_lr\n        num = self.num_steps\n        tot = self.c.exp_num_total_steps\n\n        if self.name == 'cosine_cyclic':\n            self.scheduler.step_update(num_updates=num)\n        else:\n            self.scheduler.step()\n", "meta": {"hexsha": "8b861f2155e3fa89db55b12dfe4296bbee1cae43", "size": 17348, "ext": "py", "lang": "Python", "max_stars_repo_path": "npt/optim.py", "max_stars_repo_name": "yonip97/non-parametric-transformers", "max_stars_repo_head_hexsha": "33fc744ce78a97024443f1e0080a8849fc43dbb7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "npt/optim.py", "max_issues_repo_name": "yonip97/non-parametric-transformers", "max_issues_repo_head_hexsha": "33fc744ce78a97024443f1e0080a8849fc43dbb7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "npt/optim.py", "max_forks_repo_name": "yonip97/non-parametric-transformers", "max_forks_repo_head_hexsha": "33fc744ce78a97024443f1e0080a8849fc43dbb7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1602708804, "max_line_length": 116, "alphanum_fraction": 0.5989163016, "include": true, "reason": "import numpy", "num_tokens": 3892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.17912319623381878}}
{"text": "#ebtel_plot.py\n\n#Will Barnes\n#7 May 2015\n\n#Import necessary modules\ntry:\n    import __builtin__\nexcept ImportError:\n    import builtins as __builtin__\n    \nimport logging\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn.apionly as sns\nfrom matplotlib.ticker import MaxNLocator\nfrom scipy.optimize import curve_fit\n\n#Resolve Python 2/3 exception problem\nexc = getattr(__builtin__,\"IOError\",\"FileNotFoundError\")\n\nclass Plotter(object):\n\n    def __init__(self,lvl0_filename=None,dpi=1000,fontsize=18,alfs=0.65,figsize=(8,8),fformat='eps',two_fluid=True,**kwargs):\n        #configure logger\n        self.logger = logging.getLogger(type(self).__name__)\n        #configure keyword arguments\n        self.dpi = dpi\n        self.fontsize = fontsize\n        self.alfs = alfs\n        self.figsize = figsize\n        self.fformat = fformat\n        self.two_fluid = two_fluid\n        #plotting helpers\n        self.linestyles = ('-','--','-.',':')\n        #load variables\n        if lvl0_filename is not None:\n            self.load_variables(lvl0_filename)\n        else:\n            self.logger.warning(\"No file specified. Variable namespace will not be populated.\")\n\n    def load_variables(self,lvl0_filename,**kwargs):\n        #load plasma parameters\n        try:\n            index_offset = 0\n            data = np.loadtxt(lvl0_filename+'.txt')\n            if self.two_fluid:\n                index_offset += 1 \n                self.temp_i = data[:,2]\n                self.temp_apex_i = data[:,8]\n            self.time = data[:,0]\n            self.temp_e = data[:,1]\n            self.dens = data[:,2+index_offset]\n            self.temp_apex_e = data[:,5+2*index_offset]\n            self.dens_apex = data[:,6+3*index_offset]\n            self.heat = data[:,10+5*index_offset]\n        except exc:\n            self.logger.warning(\"Unable to load plasma parameters from %s.\"%(lvl0_filename+'.txt'))\n            pass\n\n        #load dem parameters\n        try:\n            data = np.loadtxt(lvl0_filename+'_dem.txt')\n            self.temp_dem = data[:,0]\n            self.dem_tr = data[:,1]\n            self.dem_cor = data[:,2]\n            self.dem_tot = data[:,3]\n            self.em_cor = data[:,4]\n        except exc:\n            self.logger.warning(\"Unable to load DEM parameters from %s.\"%(lvl0_filename+'_dem.txt'))\n            pass\n            \n        #load heat parameters\n        try:\n            self.events = np.loadtxt(lvl0_filename+'_heat_amp.txt')\n        except exc:\n            self.logger.warning(\"Unable to load heating event amplitudes from %s.\"%(lvl0_filename+'_heat_amp.txt'))\n            pass\n\n\n    def plot_params(self,print_fig_filename=None,**kwargs):\n        #set up figure\n        fig,ax = plt.subplots(3,1,figsize=(1.5*self.figsize[0],self.figsize[1]),sharex=True)\n        ax_n = ax[1].twinx()\n        ax_na = ax[2].twinx()\n        \n        if self.two_fluid:\n            tlab = r'$T_e$'\n        else:\n            tlab = r'$T$'\n\n        #plot heating\n        ax[0].plot(self.time,self.heat,color=sns.color_palette('deep')[0])\n        ax[0].set_ylabel(r'$h$ (erg cm$^{-3}$ s$^{-1}$)',fontsize=self.fontsize)\n        ax[0].set_xlim([self.time[0],self.time[-1]])\n        ax[0].locator_params(nbins=5)\n        ax[0].ticklabel_format(axis='y', style='sci', scilimits=(-2,2) )\n        ax[0].tick_params(axis='both',labelsize=self.alfs*self.fontsize,pad=8)\n        #plot average temperature and density\n        line_te = ax[1].plot(self.time,self.temp_e/10**6,label=tlab,color=sns.color_palette('deep')[0])\n        if self.two_fluid:\n            line_ti = ax[1].plot(self.time,self.temp_i/10**6,color=sns.color_palette('deep')[2],label=r'$T_i$')\n        ax[1].set_ylabel(r'$T$ (MK)',fontsize=self.fontsize)\n        ax[1].yaxis.set_major_locator(MaxNLocator(prune='lower'))\n        ax[1].locator_params(nbins=5)\n        ax[1].ticklabel_format(axis='y', style='sci', scilimits=(-2,2) )\n        ax[1].tick_params(axis='both',labelsize=self.alfs*self.fontsize,pad=8)\n        line_n = ax_n.plot(self.time,self.dens/10**8,color=sns.color_palette('deep')[0],linestyle='--',label=r'$n$')\n        ax_n.set_ylabel(r'$n$ (10$^8$ cm$^{-3}$)',fontsize=self.fontsize)\n        ax_n.yaxis.set_major_locator(MaxNLocator(prune='lower'))\n        ax_n.locator_params(nbins=5)\n        ax_n.ticklabel_format(axis='y', style='sci', scilimits=(-2,2) )\n        ax_n.tick_params(axis='both',labelsize=self.alfs*self.fontsize,pad=8)\n        ax[1].set_xlim([self.time[0],self.time[-1]])\n        #plot apex temperature and density\n        ax[2].plot(self.time,self.temp_apex_e/10**6,color=sns.color_palette('deep')[0])\n        if self.two_fluid:\n            ax[2].plot(self.time,self.temp_apex_i/10**6,color=sns.color_palette('deep')[2])\n        ax[2].set_ylabel(r'$T_a$ (MK)',fontsize=self.fontsize)\n        ax[2].yaxis.set_major_locator(MaxNLocator(prune='lower'))\n        ax[2].locator_params(nbins=5)\n        ax[2].ticklabel_format(axis='y', style='sci', scilimits=(-2,2) )\n        ax[2].tick_params(axis='both',labelsize=self.alfs*self.fontsize,pad=8)\n        ax_na.plot(self.time,self.dens_apex/10**8,color=sns.color_palette('deep')[0],linestyle='--')\n        ax_na.set_ylabel(r'$n_a$ (10$^8$ cm$^{-3}$)',fontsize=self.fontsize)\n        ax_na.yaxis.set_major_locator(MaxNLocator(prune='lower'))\n        ax_na.locator_params(nbins=5)\n        ax_na.ticklabel_format(axis='y', style='sci', scilimits=(-2,2) )\n        ax_na.tick_params(axis='both',labelsize=self.alfs*self.fontsize,pad=8)\n        ax[2].set_xlim([self.time[0],self.time[-1]])\n        ax[2].set_xlabel(r'$t$ (s)',fontsize=self.fontsize)\n\n        #configure legend\n        lines = line_te + line_n\n        if self.two_fluid:\n            lines = line_te + line_ti + line_n\n        labels = [l.get_label() for l in lines]\n        ax[1].legend(lines,labels,loc=1)\n\n        #Check if output filename is specified\n        if print_fig_filename is not None:\n            plt.savefig(print_fig_filename+'.'+self.fformat,format=self.fformat,dpi=self.dpi)\n        else:\n            plt.show()\n\n\n    def plot_dem(self,print_fig_filename=None,**kwargs):\n        #set up figure\n        fig = plt.figure(figsize=self.figsize)\n        ax = fig.gca()\n\n        #plot dem curves\n        ax.plot(self.temp_dem,self.dem_tr,label=r'TR')\n        ax.plot(self.temp_dem,self.dem_cor,label=r'corona')\n        ax.plot(self.temp_dem,self.dem_tot,label=r'total')\n        ax.plot(self.temp_dem,self.em_cor,label=r'EM$_{corona}$')\n        ax.legend()\n        ax.set_xlabel(r'$\\log{T}$ (K)',fontsize=self.fontsize)\n        ax.set_ylabel(r'$\\log{\\mathrm{DEM}}$ (cm$^{-5}$ K$^{-1}$)',fontsize=self.fontsize)\n        ax.set_xlim([5.5,7.5])\n\n        #Check if output filename is specified\n        if print_fig_filename is not None:\n            plt.savefig(print_fig_filename+'.'+self.fformat,format=self.fformat,dpi=self.dpi)\n        else:\n            plt.show()\n\n\n    def plot_event_distribution(self,print_fig_filename=None,noise_thresh=0.01,return_params=True,show_plot=True,xmin=None,**kwargs):\n        \"\"\"Fit event energy distribution with a power-law and plot it.\"\"\"\n        \n        #set up figure\n        fig = plt.figure(figsize=self.figsize)\n        ax = fig.gca()\n\n        #Create a histogram\n        num_bins = self._freedman_diaconis()\n        n,bins,patches = ax.hist(self.events,num_bins,histtype='stepfilled',facecolor='blue',alpha=0.25,label=r'Events')\n        bin_centers = np.log10(np.diff(bins)/2.0+bins[0:-1])\n        \n        #Fit with \"graphical method\"\n        #check for bins with no entries in them; below these entries (if they exist), don't calculate fit\n        noise = np.where(n <= int(np.max(n)*noise_thresh))\n        if len(noise[0]) > 0:\n            n = n[0:noise[0][0]]\n            bin_centers = bin_centers[0:noise[0][0]]\n\n        #calculate fit\n        pars,covar = curve_fit(self._power_law_curve,bin_centers,np.log10(n),sigma=np.sqrt(np.log10(n)))\n        pl_fit = self._power_law_curve(bin_centers,*pars)\n\n        #exception for when uncertainty calculation fails\n        try:\n            sigma = np.sqrt(np.diag(covar))\n        except:\n            sigma = [0.0,0.0]\n            print(\"Uncertainty calculation failed. Resulting value is a placeholder.\")\n            pass\n            \n        #estimate power-law fit using maximum likelihood estimation (see D'Huys et al., 2016, Sol. Phys.)\n        if xmin is None:\n            xmin = np.min(self.events)\n        alpha_mle = 1. + len(self.events)*1.0/(np.sum(np.log([e/xmin for e in self.events])))\n        sigma_mle = (alpha_mle - 1.)/np.sqrt(len(self.events))\n\n        #plot fit\n        ax.plot(10**bin_centers,10**pl_fit,'--r',label=r'Fit',linewidth=2.0)\n        ax.set_xlabel(r'$E_H$ (erg cm$^{-3}$ s$^{-1}$)',fontsize=self.fontsize)\n        ax.set_ylabel(r'Number of Events',fontsize=self.fontsize)\n        ax.set_title(r'Graphical: $\\alpha$ = %.2f $\\pm$ %.2e, MLE: $\\alpha$= %.2f $\\pm$ %.2e' % (pars[1], sigma[1], alpha_mle, sigma_mle),fontsize=self.fontsize)\n        ax.set_yscale('log',nonposy='clip')\n        ax.set_xscale('log')\n        ax.set_xlim([np.min(self.events),np.max(self.events)])\n        ax.tick_params(axis='both',labelsize=0.75*self.fontsize)\n        ax.legend(fontsize=0.75*self.fontsize,loc=1)\n\n        #Check if output filename is specified\n        if print_fig_filename is not None:\n            plt.savefig(print_fig_filename+'.'+self.fformat,format=self.fformat,dpi=self.dpi)\n            plt.close('all')\n        elif show_plot:\n            plt.show()\n        else:\n            plt.close('all')\n            \n        if return_params:\n            return {'graphical':{'alpha':pars[1],'sigma':sigma[1]},'mle':{'alpha':alpha_mle,'sigma':sigma_mle}}\n\n\n    def _power_law_curve(self,x,a,b):\n        return a + b*x\n    \n    def _freedman_diaconis(self,**kwargs):\n        q75,q25 = np.percentile(self.events,[75,25])\n        iqr = q75 - q25\n        w = 2.0*iqr*(len(self.events))**(-1.0/3.0)\n        return int((np.max(np.array(self.events)) - np.min(np.array(self.events)))/w)\n\n\n    def plot_surface(self,param_1,param_2,surf_list,**kwargs):\n        #set up figure\n        fig = plt.figure(figsize=self.figsize)\n        ax = fig.gca()\n\n        #set colorbar limits\n        if 'vmin' in kwargs:\n            vmin = kwargs['vmin']\n        else:\n            vmin = np.min(np.array(surf_list))\n        if 'vmax' in kwargs:\n            vmax = kwargs['vmax']\n        else:\n            vmax = np.max(np.array(surf_list))\n\n        #set up mesh\n        p1_mesh,p2_mesh = np.meshgrid(np.array(param_1),np.array(param_2))\n        surf = ax.pcolormesh(p1_mesh,p2_mesh,np.array(surf_list),cmap='hot',vmin=vmin,vmax=vmax)\n        fig.colorbar(surf,ax=ax)\n\n        #set limits\n        if 'xlim' in kwargs:\n            ax.set_xlim([kwargs['xlim'][0],kwargs['xlim'][1]])\n        else:\n            ax.set_xlim([param_1[0],param_1[-1]])\n        if 'ylim' in kwargs:\n            ax.set_ylim([kwargs['ylim'][0],kwargs['ylim'][1]])\n        else:\n            ax.set_ylim([param_2[0],param_2[-1]])\n\n        #set labels\n        if 'ylab' in kwargs:\n            ax.set_ylabel(kwargs['ylab'],fontsize=self.fontsize)\n        if 'xlab' in kwargs:\n            ax.set_xlabel(kwargs['xlab'],fontsize=self.fontsize)\n        if 'plot_title' in kwargs:\n            ax.set_title(kwargs['plot_title'],fontsize=self.fontsize)\n\n        #Check if output filename is specified\n        if 'print_fig_filename' in kwargs:\n            plt.savefig(kwargs['print_fig_filename']+'.'+self.fformat,format=self.fformat,dpi=self.dpi)\n        else:\n            plt.show()\n", "meta": {"hexsha": "4d48dc1122ae2a3a979f0bf63c0882011b82312b", "size": 11593, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/ebtel_plot.py", "max_stars_repo_name": "wtbarnes/EBTEL_analysis", "max_stars_repo_head_hexsha": "208bfd0700881973a1633101993d6bea75f72bfb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-09-19T18:54:17.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-06T19:28:59.000Z", "max_issues_repo_path": "src/ebtel_plot.py", "max_issues_repo_name": "wtbarnes/EBTEL_analysis", "max_issues_repo_head_hexsha": "208bfd0700881973a1633101993d6bea75f72bfb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ebtel_plot.py", "max_forks_repo_name": "wtbarnes/EBTEL_analysis", "max_forks_repo_head_hexsha": "208bfd0700881973a1633101993d6bea75f72bfb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6771929825, "max_line_length": 161, "alphanum_fraction": 0.6017424308, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.17912318898251695}}
{"text": "#!/usr/bin/python\n\nimport os\nimport os.path\nimport numpy as np\nimport ROOT\nimport argparse\nimport subprocess\nimport resource\nimport glob\nimport sys\nsys.path.append(\"..\")\nfrom lib import colourLogger\nfrom lib import generalUtil as gUtil\n\n\ndef calcLC(source, configAnal):\n\n    logStdout.info([['wb', 'Producing a lightcurve for'],\n                    ['p', source]])\n\n    anasumFile = configAnal['anasumFiles'][source]\n    sourceSpectralParam = configAnal['spectralParameters'][source]\n    dirNow = os.path.join(os.getcwd(), source)\n\n    minEnergyFluxCalc = sourceSpectralParam[0]\n    normalizationEnergy = sourceSpectralParam[1]\n    spectralIndex = sourceSpectralParam[2]\n    maxEnergyFluxCalc = sourceSpectralParam[3]\n\n    # Read energy threshold from file\n    headersType = {'names': ('Source', 'z', 'tau = 1',\n                             'tau = 2', 'tau = 3'),\n                   'formats': ('U20', 'f8',\n                               'f8', 'f8', 'f8')}\n\n    sourceEnergyThresholds = np.loadtxt('../../{}_sourcesThresholds.txt'.\n                                        format(configAnal['EBL']['model']), dtype=headersType)\n    sourceIndex = np.where(sourceEnergyThresholds['Source'] == source)\n    # first two entries are source and z\n    thresholdsForThisSource = list(sourceEnergyThresholds[sourceIndex[0][0]])[2:4]\n    thresholdsForThisSource.insert(0, minEnergyFluxCalc)\n\n    binningDict = {'nightly': 1, 'weekly': 7, 'monthly': 28, 'yearly': 365}\n    mjd_min = configAnal['dates']['veritas'][0]\n    mjd_max = configAnal['dates']['veritas'][1]\n\n    thresholds = list()\n    # Build a list of pairs of min/max energies to run over\n    for i_thr, thresholdNow in enumerate(thresholdsForThisSource):\n\n        minEnergy = thresholdNow\n        if i_thr == len(thresholdsForThisSource) - 1:\n            maxEnergy = 30.\n        else:\n            maxEnergy = thresholdsForThisSource[i_thr + 1]\n\n        prefix = 'LightCurve_'\n        interfix = 'tau-{}_'.format(i_thr + 1)\n        suffix = 'range_{0:1.0f}_{1:1.0f}_GeV.txt'.format(minEnergy*1000., maxEnergy*1000.)\n        fileName = prefix + interfix + suffix\n        thresholds.append({'minEnergy': thresholdNow,\n                           'maxEnergy': maxEnergy,\n                           'fileName': fileName})\n\n    # Make two versions of the lightcurves, one with negative fluxes\n    # and one without. The former is only for the luminosity function study.\n    suffixNegativeFlux = ['', '_unbound']\n\n    for suffixNegativeFluxNow in suffixNegativeFlux:\n\n        prefix = 'LightCurve_'\n        interfix = 'fullEnergyRange_'\n        suffix = 'range_{0:1.0f}_{1:1.0f}_GeV{2}.txt'.format(minEnergyFluxCalc*1000.,\n                                                             30*1000.,\n                                                             suffixNegativeFluxNow)\n        fileName = prefix + interfix + suffix\n        thresholds.append({'minEnergy': minEnergyFluxCalc,\n                           'maxEnergy': maxEnergy,\n                           'fileName': fileName})\n\n    for thresholdsNow in thresholds:\n\n        for binning, timeBinLength_days in binningDict.items():\n\n            logStdout.info([['p', source],\n                            ['bb', binning],\n                            ['wb', 'lightcurve,'],\n                            ['g', '{} < E < {} TeV'.format(thresholdsNow['minEnergy'],\n                                                           thresholdsNow['maxEnergy'])]])\n\n            iLightCurve = ROOT.VLightCurve()\n\n            iLightCurve.initializeTeVLightCurve(anasumFile, timeBinLength_days,\n                                                mjd_min, mjd_max)\n\n            # set spectral parameters (start of flux calculation [TeV],\n            # normalization at energy E0 [TeV], spectral index, end of flux calculation [TeV])\n            iLightCurve.setSpectralParameters(minEnergyFluxCalc, normalizationEnergy,\n                                              spectralIndex, maxEnergyFluxCalc)\n\n            # plot ULs for poins with <2 sigma significance; to get rid of\n            # significance limits for upper limits of flux use (-999, 999);\n            iLightCurve.setSignificanceParameters(-999, -999)\n            # Avoid negative fluxes (if True it avoids them)\n            iLightCurve.setFluxCalculationMethod('unbound' not in thresholdsNow['fileName'])\n            # calculate fluxes and upper flux limits for energies in the range given\n            iLightCurve.fill(thresholdsNow['minEnergy'], thresholdsNow['maxEnergy'])\n            iLightCurve.writeASCIIFile(os.path.join(dirNow,\n                                                    binning +\n                                                    thresholdsNow['fileName']))\n            del iLightCurve\n\n\ndef moveFileToLumiFunctionStudyDir(source):\n\n    files = glob.glob('{}/*fullEnergyRange*'.format(source))\n    for fileNow in files:\n        if 'unbound' in fileNow:\n            command = 'mv'\n            fileDest = fileNow.replace('_unbound', '')\n        else:\n            command = 'cp'\n            fileDest = fileNow.replace('.txt', '_bounded.txt')\n\n        fileDest = fileDest.replace('fullEnergyRange_range', 'energyRange')\n        # The 195 GeV threshold in ED is essentially equivalent to 200 GeV.\n        fileDest = fileDest.replace('195', '200')\n\n        subprocess.call('mkdir -p lightcurvesForLumiFunctionStudy/{}'.format(source), shell=True)\n        fullCommand = '/bin/{} {} lightcurvesForLumiFunctionStudy/{}'.format(command,\n                                                                             fileNow,\n                                                                             fileDest)\n        subprocess.call(fullCommand, shell=True)\n\n    return\n\n\nif __name__ == '__main__':\n\n    parser = argparse.ArgumentParser(description='Produce light-curve.')\n    parser.add_argument('source', action='store',\n                        help='Source to produce the light-curve for')\n    parser.add_argument('configAnalFile', action='store',\n                        help='YAML file with the analysis configuration')\n\n    args = parser.parse_args()\n\n    logStdout = colourLogger.initStdOutLogger()\n\n    # A horrible hack to avoid the following ROOT error\n    # SysError in <TFile::TFile>: file  can not be opened for reading (Too many open files)\n    logStdout.info([['wb', 'getrlimit before:'],\n                    ['bb', resource.getrlimit(resource.RLIMIT_NOFILE)]])\n    resource.setrlimit(resource.RLIMIT_NOFILE, (4096, 4096))\n    logStdout.info([['wb', 'getrlimit after:'],\n                    ['bb', resource.getrlimit(resource.RLIMIT_NOFILE)]])\n\n    ROOT.gROOT.SetBatch(True)\n    ROOT.TFile.Open._creates = True\n\n    # load shared library\n    ROOT.gSystem.Load(\"$EVNDISPSYS/lib/libVAnaSum.so\")\n\n    configAnal = gUtil.readYamlFile(logStdout, args.configAnalFile)\n    calcLC(args.source, configAnal)\n\n    moveFileToLumiFunctionStudyDir(args.source)\n", "meta": {"hexsha": "957cb628df176bed6988f8210269c2c55f3557ee", "size": 6908, "ext": "py", "lang": "Python", "max_stars_repo_path": "makeLC/calcLC.py", "max_stars_repo_name": "orelgueta/blazar-variability-study", "max_stars_repo_head_hexsha": "d40ca43602601180c9a8c9c54be0680288aeaa11", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-23T01:58:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T01:58:35.000Z", "max_issues_repo_path": "makeLC/calcLC.py", "max_issues_repo_name": "orelgueta/blazar-variability-study", "max_issues_repo_head_hexsha": "d40ca43602601180c9a8c9c54be0680288aeaa11", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "makeLC/calcLC.py", "max_forks_repo_name": "orelgueta/blazar-variability-study", "max_forks_repo_head_hexsha": "d40ca43602601180c9a8c9c54be0680288aeaa11", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.875739645, "max_line_length": 97, "alphanum_fraction": 0.5874348581, "include": true, "reason": "import numpy", "num_tokens": 1548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.304041668660366, "lm_q1q2_score": 0.17904682958721949}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom past.utils import old_div\nfrom builtins import range\nfrom __future__ import (division, print_function, absolute_import, unicode_literals)\n\nimport sys\nimport numpy as np\nimport fsps\nfrom cloudyfsps.ASCIItools import (writeASCII, compileASCII, checkCompiled, compiledExists)\n\n# this code snippet goes through every step needed\n# to integrate FSPS into Cloudy.\n# This example uses stellar pops with a constant SFH\n# as the input ionizing source.\n# 1. Write an ascii file in Cloudy format with grid\n#    of FSPS spectra in all available ages and\n#    metallicities\n# 2. Compile asii file into binary format required\n#    for Cloudy use. Assumes $CLOUDY_EXE is set to\n#    your /path/to/cloudy.exe\n# 3. Writes Cloudy input files for a subset of grid\n#    parameters.\n# 4. Runs Cloudy on the *.in files\n# 5. Formats the various output files\n\nzsun = 0.0142 # this is solar metallicity for the MIST isochrones\n\nexec_write_ascii = True\n\n# Function to write the ascii file.\n# This is where you set the properties of the\n# ionizing spectrum (SSP/CSFH, IMF, FBHB, etc)\n\ndef mist_ascii(fileout, **kwargs):\n    # change these parameters to modify the ionizing source grid\n    # default mode is to produce an ascii grid in age and Z,\n    # though different variables and more dimensions are possible.\n    sp_dict = dict(zcontinuous=1,\n                   imf_type=2,\n                   sfh=0,\n                   const=0.0,\n                   sf_start=0.0)\n    sp = fsps.StellarPopulation(**sp_dict)\n    # all ages and Zs\n    ages = 10.**sp.log_age\n    logZs = np.log10(old_div(sp.zlegend,zsun))\n    modpars = [(age, logZ) for age in ages for logZ in logZs]\n    lam = sp.wavelengths\n    all_fluxs = []\n    for logZ in logZs:\n        sp.params['logzsol'] = logZ\n        all_fluxs.append(sp.get_spectrum()[1]) #lsun per hz\n    nmod = len(modpars)\n    # flatten flux for writing\n    flat_flux = np.array([all_fluxs[j][i]\n                          for i in range(len(ages))\n                          for j in range(len(logZs))])\n    # this function is flexible, ndim can be 3/4/n.\n    # in this example, however, ndim is 2 (age, logz).\n    writeASCII(fileout, lam, flat_flux, modpars,\n               nx=len(lam), ndim=2, npar=2, nmod=nmod)\n    return\n#---------------------------------------------------------------------\n# ASCII FILE: WRITE AND COMPILE\n#---------------------------------------------------------------------\n# assumes you have $CLOUDY_EXE and $CLOUDY_DATA_PATH set as sys vars.\n\n# name of ascii file\nascii_file = 'FSPS_MIST_SSP.ascii'\n\n# the ascii file takes a while to generate, so if an already-compiled\n# version exists, the code will not overwrite it.\n\ncompiled_ascii = '{}.mod'.format(ascii_file.split('.')[0])\nif exec_write_ascii:\n    print(\"Executing write ascii sequence...\")\n    if not compiledExists(ascii_file):\n        print(\"No compiled model exists...Writing.\")\n        mist_ascii(ascii_file)\n        print(\"Compiling {} with Cloudy\".format(ascii_file))\n        compileASCII(ascii_file)\n        print(\"Checking to see if compilation was successful...\")\n        if checkCompiled(ascii_file):\n            print(\"Your model {} is ready to run.\".format(compiled_ascii))\n        else:\n            sys.exit()\n    else:\n        print(\"{} already exists.\".format(compiled_ascii))\n", "meta": {"hexsha": "62bfa1b7ffa4b75336acafca000a8131ea7bd135", "size": 3444, "ext": "py", "lang": "Python", "max_stars_repo_path": "demos/generateCloudyBinaryFile.py", "max_stars_repo_name": "prerakgarg07/cloudyfsps", "max_stars_repo_head_hexsha": "4a6a185343ed1e09b9f201a465c37e377ef42101", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-12-07T01:00:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T17:50:51.000Z", "max_issues_repo_path": "demos/generateCloudyBinaryFile.py", "max_issues_repo_name": "prerakgarg07/cloudyfsps", "max_issues_repo_head_hexsha": "4a6a185343ed1e09b9f201a465c37e377ef42101", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demos/generateCloudyBinaryFile.py", "max_forks_repo_name": "prerakgarg07/cloudyfsps", "max_forks_repo_head_hexsha": "4a6a185343ed1e09b9f201a465c37e377ef42101", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-12-08T22:57:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-30T15:04:33.000Z", "avg_line_length": 36.6382978723, "max_line_length": 91, "alphanum_fraction": 0.6495354239, "include": true, "reason": "import numpy", "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3345894478883556, "lm_q1q2_score": 0.17903828780010458}}
{"text": "# -*- coding: utf-8 -*-\n# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\nimport numpy as np\n\nfrom astropy import units as u\nfrom astropy.utils.state import ScienceState\nfrom astropy.utils.decorators import format_doc\nfrom astropy.coordinates.angles import Angle\nfrom astropy.coordinates.matrix_utilities import rotation_matrix, matrix_product, matrix_transpose\nfrom astropy.coordinates import representation as r\nfrom astropy.coordinates.baseframe import (BaseCoordinateFrame,\n                                           frame_transform_graph,\n                                           base_doc)\nfrom astropy.coordinates.attributes import (CoordinateAttribute,\n                                            QuantityAttribute,\n                                            DifferentialAttribute)\nfrom astropy.coordinates.transformations import AffineTransform\nfrom astropy.coordinates.errors import ConvertError\n\nfrom .icrs import ICRS\n\n__all__ = ['Galactocentric']\n\n\n# Measured by minimizing the difference between a plane of coordinates along\n#   l=0, b=[-90,90] and the Galactocentric x-z plane\n# This is not used directly, but accessed via `get_roll0`.  We define it here to\n# prevent having to create new Angle objects every time `get_roll0` is called.\n_ROLL0 = Angle(58.5986320306*u.degree)\n\n\nclass galactocentric_frame_defaults(ScienceState):\n    \"\"\"This class controls the global setting of default values for the frame\n    attributes in the `~astropy.coordinates.Galactocentric` frame, which may be\n    updated in future versions of ``astropy``. Note that when using\n    `~astropy.coordinates.Galactocentric`, changing values here will not affect\n    any attributes that are set explicitly by passing values in to the\n    `~astropy.coordinates.Galactocentric` initializer. Modifying these defaults\n    will only affect the frame attribute values when using the frame as, e.g.,\n    ``Galactocentric`` or ``Galactocentric()`` with no explicit arguments.\n\n    This class controls the parameter settings by specifying a string name,\n    which can be one of:\n\n    - 'pre-v4.0': The current default value, which sets the default frame\n      attribute values to their original (pre-astropy-v4.0) values.\n    - 'v4.0': The attribute values as updated in Astropy version 4.0.\n    - 'latest': An alias of the most recent parameter set (currently: 'v4.0')\n\n    See :ref:`astropy-coordinates-galactocentric-defaults` for more information.\n\n    Examples\n    --------\n    The default `~astropy.coordinates.Galactocentric` frame parameters can be\n    modified globally::\n\n        >>> from astropy.coordinates import galactocentric_frame_defaults\n        >>> _ = galactocentric_frame_defaults.set('v4.0') # doctest: +SKIP\n        >>> Galactocentric() # doctest: +SKIP\n        <Galactocentric Frame (galcen_coord=<ICRS Coordinate: (ra, dec) in deg\n            (266.4051, -28.936175)>, galcen_distance=8.122 kpc, galcen_v_sun=(12.9, 245.6, 7.78) km / s, z_sun=20.8 pc, roll=0.0 deg)>\n        >>> _ = galactocentric_frame_defaults.set('pre-v4.0') # doctest: +SKIP\n        >>> Galactocentric() # doctest: +SKIP\n        <Galactocentric Frame (galcen_coord=<ICRS Coordinate: (ra, dec) in deg\n            (266.4051, -28.936175)>, galcen_distance=8.3 kpc, galcen_v_sun=(11.1, 232.24, 7.25) km / s, z_sun=27.0 pc, roll=0.0 deg)>\n\n    The default parameters can also be updated by using this class as a context\n    manager::\n\n        >>> with galactocentric_frame_defaults.set('pre-v4.0'):\n        ...     print(Galactocentric()) # doctest: +FLOAT_CMP\n        <Galactocentric Frame (galcen_coord=<ICRS Coordinate: (ra, dec) in deg\n            (266.4051, -28.936175)>, galcen_distance=8.3 kpc, galcen_v_sun=(11.1, 232.24, 7.25) km / s, z_sun=27.0 pc, roll=0.0 deg)>\n\n    Again, changing the default parameter values will not affect frame\n    attributes that are explicitly specified::\n\n        >>> import astropy.units as u\n        >>> with galactocentric_frame_defaults.set('pre-v4.0'):\n        ...     print(Galactocentric(galcen_distance=8.0*u.kpc)) # doctest: +FLOAT_CMP\n        <Galactocentric Frame (galcen_coord=<ICRS Coordinate: (ra, dec) in deg\n            (266.4051, -28.936175)>, galcen_distance=8.0 kpc, galcen_v_sun=(11.1, 232.24, 7.25) km / s, z_sun=27.0 pc, roll=0.0 deg)>\n\n    \"\"\"\n\n    _latest_value = 'v4.0'\n    _references = None\n    _value = None\n\n    @classmethod\n    def get_solar_params_from_string(cls, arg):\n        \"\"\"Return Galactocentric solar parameters given string names for the\n        parameter sets.\n        \"\"\"\n\n        # Resolve the meaning of 'latest': The latest parameter set is from v4.0\n        # - update this as newer parameter choices are added\n        if arg == 'latest':\n            arg = cls._latest_value\n\n        params = dict()\n        references = dict()\n\n        # Currently, all versions use the same sky position for Sgr A*:\n        params['galcen_coord'] = ICRS(ra=266.4051*u.degree,\n                                      dec=-28.936175*u.degree)\n        references['galcen_coord'] = \\\n            'http://adsabs.harvard.edu/abs/2004ApJ...616..872R'\n\n        # The roll angle is the same for both frames:\n        params['roll'] = 0 * u.deg\n\n        if arg == 'pre-v4.0':\n            params['galcen_distance'] = 8.3 * u.kpc\n            references['galcen_distance'] = \\\n                'https://ui.adsabs.harvard.edu/#abs/2009ApJ...692.1075G'\n\n            params['galcen_v_sun'] = r.CartesianDifferential([11.1,\n                                                              220+12.24,\n                                                              7.25]*u.km/u.s)\n            references['galcen_v_sun'] = \\\n                ['https://ui.adsabs.harvard.edu/#abs/2010MNRAS.403.1829S',\n                 'https://ui.adsabs.harvard.edu/#abs/2015ApJS..216...29B']\n\n            params['z_sun'] = 27.0 * u.pc\n            references['z_sun'] = \\\n                'https://ui.adsabs.harvard.edu/#abs/2001ApJ...553..184C'\n\n        elif arg == 'v4.0':\n            params['galcen_distance'] = 8.122 * u.kpc\n            references['galcen_distance'] = \\\n                'https://ui.adsabs.harvard.edu/abs/2018A%26A...615L..15G'\n\n            params['galcen_v_sun'] = r.CartesianDifferential([12.9,\n                                                              245.6,\n                                                              7.78]*u.km/u.s)\n            references['galcen_v_sun'] = \\\n                ['https://ui.adsabs.harvard.edu/abs/2018RNAAS...2..210D',\n                 'https://ui.adsabs.harvard.edu/abs/2018A%26A...615L..15G',\n                 'https://ui.adsabs.harvard.edu/abs/2004ApJ...616..872R']\n\n            params['z_sun'] = 20.8 * u.pc\n            references['z_sun'] = \\\n                'https://ui.adsabs.harvard.edu/abs/2019MNRAS.482.1417B'\n\n        else:\n            raise ValueError(f'Invalid string input to retrieve solar '\n                             f'parameters for Galactocentric frame: \"{arg}\"')\n\n        return params, references\n\n    @classmethod\n    def validate(cls, value):\n        if value is None:\n            value = cls._latest_value\n\n        if isinstance(value, str):\n            params, refs = cls.get_solar_params_from_string(value)\n            cls._references = refs\n            return params\n\n        elif isinstance(value, dict):\n            return value\n\n        elif isinstance(value, Galactocentric):\n            # turn the frame instance into a dict of frame attributes\n            attrs = dict()\n            for k in value.frame_attributes:\n                attrs[k] = getattr(value, k)\n            cls._references = value.frame_attribute_references()\n            return attrs\n\n        else:\n            raise ValueError(\"Invalid input to retrieve solar parameters for \"\n                             \"Galactocentric frame: input must be a string, \"\n                             \"dict, or Galactocentric instance\")\n\n\ndoc_components = \"\"\"\n    x : `~astropy.units.Quantity`, optional\n        Cartesian, Galactocentric :math:`x` position component.\n    y : `~astropy.units.Quantity`, optional\n        Cartesian, Galactocentric :math:`y` position component.\n    z : `~astropy.units.Quantity`, optional\n        Cartesian, Galactocentric :math:`z` position component.\n\n    v_x : `~astropy.units.Quantity`, optional\n        Cartesian, Galactocentric :math:`v_x` velocity component.\n    v_y : `~astropy.units.Quantity`, optional\n        Cartesian, Galactocentric :math:`v_y` velocity component.\n    v_z : `~astropy.units.Quantity`, optional\n        Cartesian, Galactocentric :math:`v_z` velocity component.\n\"\"\"\n\ndoc_footer = \"\"\"\n    Other parameters\n    ----------------\n    galcen_coord : `ICRS`, optional, must be keyword\n        The ICRS coordinates of the Galactic center.\n    galcen_distance : `~astropy.units.Quantity`, optional, must be keyword\n        The distance from the sun to the Galactic center.\n    galcen_v_sun : `~astropy.coordinates.representation.CartesianDifferential`, optional, must be keyword\n        The velocity of the sun *in the Galactocentric frame* as Cartesian\n        velocity components.\n    z_sun : `~astropy.units.Quantity`, optional, must be keyword\n        The distance from the sun to the Galactic midplane.\n    roll : `~astropy.coordinates.Angle`, optional, must be keyword\n        The angle to rotate about the final x-axis, relative to the\n        orientation for Galactic. For example, if this roll angle is 0,\n        the final x-z plane will align with the Galactic coordinates x-z\n        plane. Unless you really know what this means, you probably should\n        not change this!\n\n    Examples\n    --------\n\n    To transform to the Galactocentric frame with the default\n    frame attributes, pass the uninstantiated class name to the\n    ``transform_to()`` method of a `~astropy.coordinates.SkyCoord` object::\n\n        >>> import astropy.units as u\n        >>> import astropy.coordinates as coord\n        >>> c = coord.SkyCoord(ra=[158.3122, 24.5] * u.degree,\n        ...                    dec=[-17.3, 81.52] * u.degree,\n        ...                    distance=[11.5, 24.12] * u.kpc,\n        ...                    frame='icrs')\n        >>> c.transform_to(coord.Galactocentric) # doctest: +FLOAT_CMP\n        <SkyCoord (Galactocentric: galcen_coord=<ICRS Coordinate: (ra, dec) in deg\n            (266.4051, -28.936175)>, galcen_distance=8.122 kpc, galcen_v_sun=(12.9, 245.6, 7.78) km / s, z_sun=20.8 pc, roll=0.0 deg): (x, y, z) in kpc\n            [( -9.43489286, -9.40062188, 6.51345359),\n             (-21.11044918, 18.76334013, 7.83175149)]>\n\n\n    To specify a custom set of parameters, you have to include extra keyword\n    arguments when initializing the Galactocentric frame object::\n\n        >>> c.transform_to(coord.Galactocentric(galcen_distance=8.1*u.kpc)) # doctest: +FLOAT_CMP\n        <SkyCoord (Galactocentric: galcen_coord=<ICRS Coordinate: (ra, dec) in deg\n            (266.4051, -28.936175)>, galcen_distance=8.1 kpc, galcen_v_sun=(12.9, 245.6, 7.78) km / s, z_sun=20.8 pc, roll=0.0 deg): (x, y, z) in kpc\n            [( -9.41284763, -9.40062188, 6.51346272),\n             (-21.08839478, 18.76334013, 7.83184184)]>\n\n    Similarly, transforming from the Galactocentric frame to another coordinate frame::\n\n        >>> c = coord.SkyCoord(x=[-8.3, 4.5] * u.kpc,\n        ...                    y=[0., 81.52] * u.kpc,\n        ...                    z=[0.027, 24.12] * u.kpc,\n        ...                    frame=coord.Galactocentric)\n        >>> c.transform_to(coord.ICRS) # doctest: +FLOAT_CMP\n        <SkyCoord (ICRS): (ra, dec, distance) in (deg, deg, kpc)\n            [( 88.22423301, 29.88672864,  0.17813456),\n             (289.72864549, 49.9865043 , 85.93949064)]>\n\n    Or, with custom specification of the Galactic center::\n\n        >>> c = coord.SkyCoord(x=[-8.0, 4.5] * u.kpc,\n        ...                    y=[0., 81.52] * u.kpc,\n        ...                    z=[21.0, 24120.0] * u.pc,\n        ...                    frame=coord.Galactocentric,\n        ...                    z_sun=21 * u.pc, galcen_distance=8. * u.kpc)\n        >>> c.transform_to(coord.ICRS) # doctest: +FLOAT_CMP\n        <SkyCoord (ICRS): (ra, dec, distance) in (deg, deg, kpc)\n            [( 86.2585249 , 28.85773187, 2.75625475e-05),\n             (289.77285255, 50.06290457, 8.59216010e+01)]>\n\n\"\"\"\n\n\n@format_doc(base_doc, components=doc_components, footer=doc_footer)\nclass Galactocentric(BaseCoordinateFrame):\n    r\"\"\"\n    A coordinate or frame in the Galactocentric system.\n\n    This frame allows specifying the Sun-Galactic center distance, the height of\n    the Sun above the Galactic midplane, and the solar motion relative to the\n    Galactic center. However, as there is no modern standard definition of a\n    Galactocentric reference frame, it is important to pay attention to the\n    default values used in this class if precision is important in your code.\n    The default values of the parameters of this frame are taken from the\n    original definition of the frame in 2014. As such, the defaults are somewhat\n    out of date relative to recent measurements made possible by, e.g., Gaia.\n    The defaults can, however, be changed at runtime by setting the parameter\n    set name in `~astropy.coordinates.galactocentric_frame_defaults`.\n\n    The current default parameter set is ``\"pre-v4.0\"``, indicating that the\n    parameters were adopted before ``astropy`` version 4.0. A regularly-updated\n    parameter set can instead be used by setting\n    ``galactocentric_frame_defaults.set ('latest')``, and other parameter set\n    names may be added in future versions. To find out the scientific papers\n    that the current default parameters are derived from, use\n    ``galcen.frame_attribute_references`` (where ``galcen`` is an instance of\n    this frame), which will update even if the default parameter set is changed.\n\n    The position of the Sun is assumed to be on the x axis of the final,\n    right-handed system. That is, the x axis points from the position of\n    the Sun projected to the Galactic midplane to the Galactic center --\n    roughly towards :math:`(l,b) = (0^\\circ,0^\\circ)`. For the default\n    transformation (:math:`{\\rm roll}=0^\\circ`), the y axis points roughly\n    towards Galactic longitude :math:`l=90^\\circ`, and the z axis points\n    roughly towards the North Galactic Pole (:math:`b=90^\\circ`).\n\n    For a more detailed look at the math behind this transformation, see\n    the document :ref:`coordinates-galactocentric`.\n\n    The frame attributes are listed under **Other Parameters**.\n    \"\"\"\n\n    default_representation = r.CartesianRepresentation\n    default_differential = r.CartesianDifferential\n\n    # frame attributes\n    galcen_coord = CoordinateAttribute(frame=ICRS)\n    galcen_distance = QuantityAttribute(unit=u.kpc)\n\n    galcen_v_sun = DifferentialAttribute(\n        allowed_classes=[r.CartesianDifferential])\n\n    z_sun = QuantityAttribute(unit=u.pc)\n    roll = QuantityAttribute(unit=u.deg)\n\n    def __init__(self, *args, **kwargs):\n        # Set default frame attribute values based on the ScienceState instance\n        # for the solar parameters defined above\n        default_params = galactocentric_frame_defaults.get()\n        self.frame_attribute_references = \\\n            galactocentric_frame_defaults._references.copy()\n\n        for k in default_params:\n            if k in kwargs:\n                # If a frame attribute is set by the user, remove its reference\n                self.frame_attribute_references.pop(k, None)\n\n            # Keep the frame attribute if it is set by the user, otherwise use\n            # the default value\n            kwargs[k] = kwargs.get(k, default_params[k])\n\n        super().__init__(*args, **kwargs)\n\n    @classmethod\n    def get_roll0(cls):\n        \"\"\"\n        The additional roll angle (about the final x axis) necessary to align\n        the final z axis to match the Galactic yz-plane.  Setting the ``roll``\n        frame attribute to  -this method's return value removes this rotation,\n        allowing the use of the `Galactocentric` frame in more general contexts.\n        \"\"\"\n        # note that the actual value is defined at the module level.  We make at\n        # a property here because this module isn't actually part of the public\n        # API, so it's better for it to be accessable from Galactocentric\n        return _ROLL0\n\n# ICRS to/from Galactocentric ----------------------->\n\n\ndef get_matrix_vectors(galactocentric_frame, inverse=False):\n    \"\"\"\n    Use the ``inverse`` argument to get the inverse transformation, matrix and\n    offsets to go from Galactocentric to ICRS.\n    \"\"\"\n    # shorthand\n    gcf = galactocentric_frame\n\n    # rotation matrix to align x(ICRS) with the vector to the Galactic center\n    mat1 = rotation_matrix(-gcf.galcen_coord.dec, 'y')\n    mat2 = rotation_matrix(gcf.galcen_coord.ra, 'z')\n    # extra roll away from the Galactic x-z plane\n    mat0 = rotation_matrix(gcf.get_roll0() - gcf.roll, 'x')\n\n    # construct transformation matrix and use it\n    R = matrix_product(mat0, mat1, mat2)\n\n    # Now need to translate by Sun-Galactic center distance around x' and\n    # rotate about y' to account for tilt due to Sun's height above the plane\n    translation = r.CartesianRepresentation(gcf.galcen_distance * [1., 0., 0.])\n    z_d = gcf.z_sun / gcf.galcen_distance\n    H = rotation_matrix(-np.arcsin(z_d), 'y')\n\n    # compute total matrices\n    A = matrix_product(H, R)\n\n    # Now we re-align the translation vector to account for the Sun's height\n    # above the midplane\n    offset = -translation.transform(H)\n\n    if inverse:\n        # the inverse of a rotation matrix is a transpose, which is much faster\n        #   and more stable to compute\n        A = matrix_transpose(A)\n        offset = (-offset).transform(A)\n        offset_v = r.CartesianDifferential.from_cartesian(\n            (-gcf.galcen_v_sun).to_cartesian().transform(A))\n        offset = offset.with_differentials(offset_v)\n\n    else:\n        offset = offset.with_differentials(gcf.galcen_v_sun)\n\n    return A, offset\n\n\ndef _check_coord_repr_diff_types(c):\n    if isinstance(c.data, r.UnitSphericalRepresentation):\n        raise ConvertError(\"Transforming to/from a Galactocentric frame \"\n                           \"requires a 3D coordinate, e.g. (angle, angle, \"\n                           \"distance) or (x, y, z).\")\n\n    if ('s' in c.data.differentials and\n            isinstance(c.data.differentials['s'],\n                       (r.UnitSphericalDifferential,\n                        r.UnitSphericalCosLatDifferential,\n                        r.RadialDifferential))):\n        raise ConvertError(\"Transforming to/from a Galactocentric frame \"\n                           \"requires a 3D velocity, e.g., proper motion \"\n                           \"components and radial velocity.\")\n\n\n@frame_transform_graph.transform(AffineTransform, ICRS, Galactocentric)\ndef icrs_to_galactocentric(icrs_coord, galactocentric_frame):\n    _check_coord_repr_diff_types(icrs_coord)\n    return get_matrix_vectors(galactocentric_frame)\n\n\n@frame_transform_graph.transform(AffineTransform, Galactocentric, ICRS)\ndef galactocentric_to_icrs(galactocentric_coord, icrs_frame):\n    _check_coord_repr_diff_types(galactocentric_coord)\n    return get_matrix_vectors(galactocentric_coord, inverse=True)\n", "meta": {"hexsha": "16b97c0b31860abb6fea3632caf95a41fee0a3db", "size": 19293, "ext": "py", "lang": "Python", "max_stars_repo_path": "astropy/coordinates/builtin_frames/galactocentric.py", "max_stars_repo_name": "mehrdad-shokri/astropy", "max_stars_repo_head_hexsha": "abd73b51277694338c8eca7639da956dcd06f207", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "astropy/coordinates/builtin_frames/galactocentric.py", "max_issues_repo_name": "mehrdad-shokri/astropy", "max_issues_repo_head_hexsha": "abd73b51277694338c8eca7639da956dcd06f207", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "astropy/coordinates/builtin_frames/galactocentric.py", "max_forks_repo_name": "mehrdad-shokri/astropy", "max_forks_repo_head_hexsha": "abd73b51277694338c8eca7639da956dcd06f207", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.1826697892, "max_line_length": 151, "alphanum_fraction": 0.6395583891, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 4881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.29098086621490676, "lm_q1q2_score": 0.17897879699633445}}
{"text": "from __future__ import division, print_function\nimport sys\nfrom pkg_resources import Requirement, resource_stream\nimport numpy as np\nimport itertools\nimport logging\n\nnt = { 'a': 0, 'c': 1, 'g': 2, 't': 3 }\ntops = lambda s: 4*s[:,:-1]+s[:,1:]\n\nclass ToeholdSpecificationError(ValueError):\n    '''\n    Error raised when stickydesign cannot satisfy user's toehold specifications.\n    '''\n    def __init__(self, message):\n        #self.expression = expression\n        self.message = message\n\ndef exceptionhook(exception_type, exception, traceback, default_hook = sys.excepthook):\n    if 'Toehold' in exception_type.__name__ :\n        print(\"{}: {}\".format('RuntimeError', exception.message))\n    else:\n        default_hook(exception_type, exception, traceback)\n\nsys.excepthook = exceptionhook\n\nclass energyfuncs:\n    \"\"\"\n    Energy functions based on SantaLucia's 2004 paper.\n\n    mismatchtype is one of 'max', 'loop', or 'dangle', specifying how to\n    consider mismatches.  'max' is probably the best choice, but is slowest -\n    it takes the maximum interaction of the 'loop' and 'dangle' options.\n    \"\"\"\n    def __init__(self, targetdG=7.7, length=7, deviation=0.5, max_spurious=0.4):\n        import os\n        try:\n            dsb = resource_stream('stickydesign', 'stickydesign/params/dnastackingbig.csv')\n        except:\n            try:\n                dsb = resource_stream('stickydesign', 'params/dnastackingbig.csv')\n            except IOError:\n                raise IOError(\"Error loading dnastackingbig.csv\")\n        try:\n            dgl = resource_stream('piperine', 'data/dnadangle.csv')\n        except:\n            try:\n                this_dir, this_filename = os.path.split(__file__)\n                dgl = open( os.path.join(this_dir, \"data\", \"dnadangle.csv\") )\n            except IOError:\n                raise IOError(\"Error loading dnadangle.csv\")\n        self.targetdG=targetdG\n        self.alphabet='h'\n        self.adjs=['c', 'g']\n        self.deviation=deviation\n        self.max_spurious=max_spurious\n        self.length=length\n        self.nndG_full = -np.loadtxt(dsb ,delimiter=',')\n        self.dgldG_full = -np.loadtxt(dgl ,delimiter=',')\n        self.taildG = 1.3\n        dsb.close()\n        dgl.close()\n        self.initdG = 0.0 # 1.96 DISABLED FOR NOW\n        self.nndG = self.nndG_full[np.arange(0,16),15-np.arange(0,16)]\n        # 30-01-15: The only dangle contexts we are interested in are 3' dangle\n        # s. Select those from the Santa Lucia table. We'll have to flip the\n        # order of the vector, though, to mach the 5->3 orientation of the gene\n        # rated toeholds. To flip, we need to count up to 15 with the opposite-\n        # endian order, in terms of quaternary representation\n        indcs = 4*np.tile(np.arange(4), 4) + np.repeat(np.arange(4), 4)\n        self.dgldG = self.dgldG_full[1, indcs]\n        # 30-01-15: As of now, the dangle base is set to C, so make a lookup ta\n        # ble ordered by terminating toehold base\n        self.dgldG_fixedC = self.dgldG_full[1, np.arange(4) + 4 * nt['c']]\n        self.uniform = lambda x,y: np.maximum( self.uniform_loopmismatch(x,y), \\\n                                               self.uniform_danglemismatch(x,y) \\\n                                             )\n\n    def th_external_dG(self, seqs):\n        # Convert nearest-neighbor stacks to dG-table lookup indices.\n        # Sum up the near-neighbor energy contributions\n        # Add context-specific dG values, eg tail or dangle contributions\n        seqs_len = np.size(seqs, 1)\n        # The external context involves a 3' dangle, so exclude the 3' flank\n        # base.\n        cols_external = np.arange(seqs_len-1)\n        tops_external = tops(seqs[:, cols_external])\n        nndG_external = np.sum(self.nndG[tops_external], 1)\n        # The external-context dangle is fixed at C.\n        dgldG_external = self.dgldG_fixedC[seqs[:, seqs_len-2]]\n        return nndG_external + dgldG_external - self.taildG - self.initdG\n\n    def th_internal_dG(self, seqs):\n        # Convert nearest-neighbor stacks to dG-table lookup indices\n        # Sum up and return the near-neighbor energy contributions\n        # Add context-specific dG values, eg tail or dangle contributions\n        seqs_len = np.size(seqs, 1)\n        # The internal context involves a truncated toehold. Remove first 3' to\n        # ehold base.\n        cols_internal = np.concatenate((np.arange(seqs_len-2), [seqs_len-1]))\n        tops_internal = tops(seqs[:, cols_internal])\n        nndG_internal = np.sum(self.nndG[tops_internal], 1)\n        return nndG_internal - self.taildG - self.initdG\n\n    def matching_uniform(self, seqs):\n        # Make a boolean vector representing which toeholds' external context dG\n        # is further from the target dG than than their internal context dG\n        dG_external = self.th_external_dG(seqs)\n        dG_internal = self.th_internal_dG(seqs)\n        external_further_bool = np.abs(dG_external - self.targetdG) >\\\n                                np.abs(dG_internal - self.targetdG)\n        return np.choose(external_further_bool, [dG_internal, dG_external])\n\n    def uniform_loopmismatch(self, seqs1, seqs2):\n        if seqs1.shape != seqs2.shape:\n            if seqs1.ndim == 1:\n                seqs1 = endarray( np.repeat(np.array([seqs1]),seqs2.shape[0],0), seqs1.endtype )\n            else:\n                raise InputError(\"Lengths of sequence arrays are not acceptable.\")\n        assert seqs1.endtype == seqs2.endtype\n        endtype = seqs1.endtype\n\n        endlen = seqs1.endlen\n        plen = endlen-1\n\n        # Run through the\n        # TODO: replace this with cleaner code\n        if endtype=='DT':\n            ps1 = seqs1[:,1:-1]*4+seqs1[:,2:]\n            pa1 = seqs1[:,0]*4+seqs1[:,1]\n            pac1 = (3-seqs1[:,0])*4+seqs2[:,-1]\n            ps2 = seqs2[:,::-1][:,:-2]*4+seqs2[:,::-1][:,1:-1]\n            pa2 = seqs2[:,0]*4+seqs2[:,1]\n            pac2 = (3-seqs2[:,0])*4+seqs1[:,-1]\n        if endtype=='TD':\n            ps1 = seqs1[:,:-2]*4+seqs1[:,1:-1]\n            pa1 = seqs1[:,-2]*4+seqs1[:,-1]\n            pac1 = seqs2[:,0]*4+(3-seqs1[:,-1])\n            ps2 = seqs2[:,::-1][:,1:-1]*4+seqs2[:,::-1][:,2:]\n            pa2 = seqs2[:,-2]*4+seqs2[:,-1]\n            pac2 = (seqs1[:,0])*4+(3-seqs2[:,-1])\n\n        # Shift here is considering the first strand as fixed, and the second one as\n        # shifting.  The shift is the offset of the bottom one in terms of pair\n        # sequences (thus +2 and -1 instead of +1 and 0).\n        en = np.zeros( (ps1.shape[0], 2*plen) )\n        for shift in range(-plen+1,plen):\n            #import pdb\n            #pdb.set_trace()\n            en[:,plen+shift-1] = np.sum( \\\n                    self.nndG_full[ ps1[:,max(shift,0):plen+shift], \\\n                               ps2[:,max(-shift,0):plen-shift] ], \\\n                               axis=1)\n        en[:,plen-1] = en[:,plen-1] + self.nndG_full[pa1,pac1] + self.nndG_full[pa2,pac2]\n        return np.amax(en,1) - self.initdG\n\n    def uniform_danglemismatch(self, seqs1,seqs2,fast=True):\n        if seqs1.shape != seqs2.shape:\n            if seqs1.ndim == 1:\n                seqs1 = endarray( np.repeat(np.array([seqs1]),seqs2.shape[0],0), seqs1.endtype )\n            else:\n                raise InputError(\"Lengths of sequence arrays are not acceptable.\")\n        assert seqs1.endtype == seqs2.endtype\n        endtype = seqs1.endtype\n        s1 = tops(seqs1)\n        s2 = tops(seqs2)\n        l = s1.shape[1]\n        s2r = np.fliplr(np.invert(s2)%16)\n        s2r = s2r//4 + 4*(s2r%4)\n        m = np.zeros((s1.shape[0],2*np.sum(np.arange(2,l+1))+l+1))\n        r = np.zeros(m.shape[0])\n        z = 0;\n        if endtype == 'TD':\n            s1c = s1[:,0:-1]\n            s2rc = s2r[:,1:]\n            s1l = np.hstack(( (4*(s2r[:,0]//4) + s1[:,0]//4).reshape(-1,1) , s1 ))\n            s2rl = np.hstack(( s2r , (4*(s2r[:,-1]%4) + s1[:,-1]%4).reshape(-1,1) ))\n        elif endtype == 'DT':\n            s1c = s1[:,1:]\n            s2rc = s2r[:,0:-1]\n            s2rl = np.hstack(( (4*(s1[:,0]//4) + s2r[:,0]//4).reshape(-1,1) , s2r ))\n            s1l = np.hstack(( s1 , (4*(s1[:,-1]%4) + s2r[:,-1]%4).reshape(-1,1) ))\n        for o in range(1,l-1):\n            zn = l-1-o\n            m[:,z:z+zn] = ( s1c[:,:-o]==s2rc[:,o:] ) * self.nndG[s1c[:,:-o]]\n            z = z+zn+2\n            m[:,z:z+zn] = ( s2rc[:,:-o]==s1c[:,o:] ) * self.nndG[s2rc[:,:-o]]\n            z = z+zn+2\n        m[:,z:z+l+1] = (s1l == s2rl) * self.nndG[s1l]\n        i = 0\n        im = len(m)\n        # This needs to be changed to something faster\n        if not fast:\n            for xi in range(0,m.shape[0]):\n                gm = 0\n                g = 0\n                for y in m[xi,:]:\n                    if y == 0:\n                        g = 0\n                    else:\n                        g += y\n                        if gm > g:\n                            gm = g\n                r[xi] = gm\n                i+=1\n                if not i%1000:\n                    print(\"%d/%d\" % (i,im))\n        else:\n            from stickydesign import _stickyext\n            x = m\n            _stickyext.fastsub(x,r)\n\n        return r-self.initdG\n\n    def score_toeholds(self, toeholds):\n        import stickydesign as sd\n        toeholds = [ th_set[0] for th_set in toeholds]\n        toeholds_flanked = [ 'c' + th.lower() + 'c' for th in toeholds]\n        ends = sd.endarray(toeholds_flanked, 'TD')\n        e_vec_ext = self.th_external_dG(ends)\n        e_vec_int = self.th_internal_dG(ends)\n        e_vec_all = np.concatenate( (e_vec_int, e_vec_ext))\n        e_err = np.abs(e_vec_all.mean() - self.targetdG)\n        e_rng = e_vec_all.max() - e_vec_all.min()\n        return (e_err, e_rng)\n\n    def calculate_unrestricted_toehold_characteristics(self):\n        import stickydesign as sd\n        ends = sd.easyends('TD',\n                           self.length,\n                           alphabet=self.alphabet,\n                           adjs=self.adjs,\n                           energetics=self)\n        n_ends = len(ends)\n        e_array = sd.energy_array_uniform(ends, self)\n        e_array = e_array[n_ends:, :n_ends]\n        for i in range(n_ends):\n            e_array[i,i] = 0\n        e_spr = e_array.max()/self.targetdG\n        e_vec_ext = self.th_external_dG(ends)\n        e_vec_int = self.th_internal_dG(ends)\n        e_vec_all = np.concatenate( (e_vec_int, e_vec_ext))\n        e_avg = e_vec_all.mean()\n        e_dev = np.max(np.abs(e_vec_all - self.targetdG))\n        return e_avg, e_dev, e_spr, n_ends\n\n    def get_toeholds(self, n_ths=6, timeout=8):\n        from  time import time\n        import stickydesign as sd\n        \"\"\" Generate specified stickyends for the Soloveichik DSD approach\n\n        A given run of stickydesign may not generate toeholds that match the\n        Soloveichik approach. This function reports whether the run was successful\n        or not. Otherwise, the toeholds are matched to respect the backwards\n        strand back-to-back toeholds.\n\n        Args:\n            n_ths: Number of toeholds to generate. (6)\n            timeout: Time duration allowed for finding toeholds in seconds. (8)\n        Returns:\n            List of toehold strings\n        \"\"\"\n        # Give StickyDesign a set of trivial, single-nucleotide toeholds to avoid poor\n        # designs. I'm not sure if this helps now, but it did once.\n        avoid_list = [i * int(self.length + 2) for i in ['a', 'c', 't']]\n\n        # Generate toeholds\n        fdev = self.deviation / self.targetdG\n        notoes = True\n        startime = time()\n        while notoes:\n            try:\n                ends = sd.easyends('TD',\n                                   self.length,\n                                   interaction=self.targetdG,\n                                   fdev=fdev,\n                                   alphabet=self.alphabet,\n                                   adjs=self.adjs,\n                                   maxspurious=self.max_spurious,\n                                   energetics=self,\n                                   oldends=avoid_list)\n                notoes = len(ends) < n_ths + len(avoid_list)\n                if (time() - startime) > timeout:\n                    e_avg, e_spr, e_dev, n_ends = self.calculate_unrestricted_toehold_characteristics()\n                    msg = \"Cannot make toeholds to user specification! Try target energy:{:.2}, maxspurious:{:.2}, deviation:{:.2}, which makes {:d} toeholds.\"\n                    exception = ToeholdSpecificationError(msg.format(e_avg, e_spr, e_dev, n_ends))\n                    raise exception\n            except ValueError:\n                e_avg, e_spr, e_dev, n_ends = self.calculate_unrestricted_toehold_characteristics()\n                msg = \"Cannot make toeholds to user specification! Try target energy:{:.2}, maxspurious:{:.2}, deviation:{:.2}, which makes {:d} toeholds.\"\n                exception = ToeholdSpecificationError(msg.format(e_avg, e_spr, e_dev, n_ends))\n                raise exception\n        th_cands = ends.tolist()\n        # remove \"avoid\" sequences\n        th_cands = th_cands[len(avoid_list):]\n        # Make as many end in c as possible\n        th_cands = th_cands[:n_ths]\n        th_all = [ th[1:-1] for th in th_cands]\n        ends_full = sd.endarray(th_cands, 'TD')\n        ends_all = sd.endarray(th_all, 'TD')\n        return ends_all.tolist()\n\n\n", "meta": {"hexsha": "22afe1bea840c87abef311f7c28e7efa5e938092", "size": 13396, "ext": "py", "lang": "Python", "max_stars_repo_path": "piperine/Srinivas2017/energetics.py", "max_stars_repo_name": "DNA-and-Natural-Algorithms-Group/piperine", "max_stars_repo_head_hexsha": "40855414e709d38bd4b66436e1443b88c5aac34e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2017-07-05T17:15:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T01:05:32.000Z", "max_issues_repo_path": "piperine/Srinivas2017/energetics.py", "max_issues_repo_name": "DNA-and-Natural-Algorithms-Group/piperine", "max_issues_repo_head_hexsha": "40855414e709d38bd4b66436e1443b88c5aac34e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-02-19T22:08:20.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-18T11:02:21.000Z", "max_forks_repo_path": "piperine/Srinivas2017/energetics.py", "max_forks_repo_name": "DNA-and-Natural-Algorithms-Group/piperine", "max_forks_repo_head_hexsha": "40855414e709d38bd4b66436e1443b88c5aac34e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-08-05T06:39:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T15:54:46.000Z", "avg_line_length": 44.0657894737, "max_line_length": 159, "alphanum_fraction": 0.5538220364, "include": true, "reason": "import numpy", "num_tokens": 3698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3140505578320071, "lm_q1q2_score": 0.17896254305866433}}
{"text": "from abc import ABC, abstractmethod\n\nimport numpy as np\nfrom astropy.nddata import StdDevUncertainty, VarianceUncertainty, InverseVariance\nfrom astropy.units import Quantity\nfrom scipy.interpolate import CubicSpline\n\nfrom ..spectra import Spectrum1D, SpectralAxis\n\n__all__ = ['ResamplerBase', 'FluxConservingResampler',\n           'LinearInterpolatedResampler', 'SplineInterpolatedResampler']\n\n\nclass ResamplerBase(ABC):\n    \"\"\"\n    Base class for resample classes.  The algorithms and needs for difference\n    resamples will vary quite a bit, so this class is relatively sparse.\n\n    Parameters\n    ----------\n    extrapolation_treatment : str\n        What to do when resampling off the edge of the spectrum.  Can be\n        ``'nan_fill'`` to have points beyond the edges by set to NaN, or\n        ``'zero_fill'`` to be set to zero.\n    \"\"\"\n    def __init__(self, extrapolation_treatment='nan_fill'):\n        if extrapolation_treatment not in ('nan_fill', 'zero_fill'):\n            raise ValueError('invalid extrapolation_treatment value: ' + str(extrapolation_treatment))\n        self.extrapolation_treatment = extrapolation_treatment\n\n    def __call__(self, orig_spectrum, fin_spec_axis):\n        \"\"\"\n        Return the resulting `~specutils.Spectrum1D` of the resampling.\n        \"\"\"\n        return self.resample1d(orig_spectrum, fin_spec_axis)\n\n    @abstractmethod\n    def resample1d(self, orig_spectrum, fin_spec_axis):\n        \"\"\"\n        Workhorse method that will return the resampled Spectrum1D\n        object.\n        \"\"\"\n        return NotImplemented\n\n\nclass FluxConservingResampler(ResamplerBase):\n    \"\"\"\n    This resampling algorithm conserves overall integrated flux (as opposed to\n    flux density).\n    Algorithm based on the equations documented in the following paper:\n    https://ui.adsabs.harvard.edu/abs/2017arXiv170505165C/abstract\n\n    Parameters\n    ----------\n    extrapolation_treatment : str\n        What to do when resampling off the edge of the spectrum.  Can be\n        ``'nan_fill'`` to have points beyond the edges by set to NaN, or\n        ``'zero_fill'`` to be set to zero.\n\n    Examples\n    --------\n\n    To resample an input spectrum to a user specified spectral grid using\n    a flux conserving algorithm:\n\n    >>> import numpy as np\n    >>> import astropy.units as u\n    >>> from specutils import Spectrum1D\n    >>> from specutils.manipulation import FluxConservingResampler\n    >>> input_spectra = Spectrum1D(\n    ...     flux=np.array([1, 3, 7, 6, 20]) * u.mJy,\n    ...     spectral_axis=np.array([2, 4, 12, 16, 20]) * u.nm)\n    >>> resample_grid = [1, 5, 9, 13, 14, 17, 21, 22, 23]  *u.nm\n    >>> fluxc_resample = FluxConservingResampler()\n    >>> output_spectrum1D = fluxc_resample(input_spectra, resample_grid) # doctest: +IGNORE_OUTPUT\n\n    \"\"\"\n\n    def _resample_matrix(self, orig_spec_axis, fin_spec_axis):\n        \"\"\"\n        Create a re-sampling matrix to be used in re-sampling spectra in a way\n        that conserves flux. This code was heavily influenced by Nick Earl's\n        resample rough draft: nmearl@0ff6ef1.\n\n        Parameters\n        ----------\n        orig_spec_axis : SpectralAxis\n            The original spectral axis array.\n        fin_spec_axis : SpectralAxis\n            The desired spectral axis array.\n\n        Returns\n        -------\n        resample_mat : ndarray\n            An [[N_{fin_spec_axis}, M_{orig_spec_axis}]] matrix.\n        \"\"\"\n        # Lower bin and upper bin edges\n        orig_edges = orig_spec_axis.bin_edges\n        fin_edges = fin_spec_axis.bin_edges\n\n        # I could get rid of these alias variables,\n        # but it does add readability\n        orig_low = orig_edges[:-1]\n        fin_low = fin_edges[:-1]\n        orig_upp = orig_edges[1:]\n        fin_upp = fin_edges[1:]\n\n        # Here's the real work in figuring out the bin overlaps\n        # i.e., contribution of each original bin to the resampled bin\n        l_inf = np.where(orig_low > fin_low[:, np.newaxis],\n                         orig_low, fin_low[:, np.newaxis])\n        l_sup = np.where(orig_upp < fin_upp[:, np.newaxis],\n                         orig_upp, fin_upp[:, np.newaxis])\n\n        resamp_mat = (l_sup - l_inf).clip(0)\n        resamp_mat = resamp_mat * (orig_upp - orig_low)\n\n        # set bins that don't overlap 100% with original bins\n        # to zero by checking edges, and applying generated mask\n        left_clip = np.where(fin_edges[:-1] - orig_edges[0] < 0, 0, 1)\n        right_clip = np.where(orig_edges[-1] - fin_edges[1:] < 0, 0, 1)\n        keep_overlapping_matrix = left_clip * right_clip\n\n        resamp_mat *= keep_overlapping_matrix[:, np.newaxis]\n\n        return resamp_mat.value\n\n    def resample1d(self, orig_spectrum, fin_spec_axis):\n        \"\"\"\n        Create a re-sampling matrix to be used in re-sampling spectra in a way\n        that conserves flux. If an uncertainty is present in the input spectra\n        it will be propagated through to the final resampled output spectra\n        as an InverseVariance uncertainty.\n\n        Parameters\n        ----------\n        orig_spectrum : `~specutils.Spectrum1D`\n            The original 1D spectrum.\n        fin_spec_axis :  Quantity\n            The desired spectral axis array.\n\n        Returns\n        -------\n        resample_spectrum : `~specutils.Spectrum1D`\n            An output spectrum containing the resampled `~specutils.Spectrum1D`\n        \"\"\"\n\n        # Check if units on original spectrum and new wavelength (if defined)\n        # match\n        if isinstance(fin_spec_axis, Quantity):\n            if orig_spectrum.spectral_axis.unit != fin_spec_axis.unit:\n                raise ValueError(\"Original spectrum spectral axis grid and new\"\n                                 \"spectral axis grid must have the same units.\")\n\n        if not isinstance(fin_spec_axis, SpectralAxis):\n            fin_spec_axis = SpectralAxis(fin_spec_axis)\n\n        # todo: Would be good to return uncertainty in type it was provided?\n        # todo: add in weighting options\n\n        # Get provided uncertainty into variance\n        if orig_spectrum.uncertainty is not None:\n            if isinstance(orig_spectrum.uncertainty, StdDevUncertainty):\n                pixel_uncer = np.square(orig_spectrum.uncertainty.array)\n            elif isinstance(orig_spectrum.uncertainty, VarianceUncertainty):\n                pixel_uncer = orig_spectrum.uncertainty.array\n            elif isinstance(orig_spectrum.uncertainty, InverseVariance):\n                pixel_uncer = np.reciprocal(orig_spectrum.uncertainty.array)\n        else:\n            pixel_uncer = None\n\n        orig_axis_in_fin = orig_spectrum.spectral_axis.to(fin_spec_axis.unit)\n        resample_grid = self._resample_matrix(orig_axis_in_fin, fin_spec_axis)\n\n        # Now for some broadcasting magic to handle multi dimensional flux inputs\n        # Essentially this part is inserting length one dimensions as fillers\n        # For example, if we have a (5,6,10) input flux, and an output grid\n        # of 3, flux will be broadcast to (5,6,1,10) and resample_grid will\n        # Be broadcast to (1,1,3,10).  The sum then reduces down the 10, the\n        # original dispersion grid, leaving 3, the new dispersion grid, as\n        # the last index.\n        new_flux_shape = list(orig_spectrum.flux.shape)\n        new_flux_shape.insert(-1, 1)\n        in_flux = orig_spectrum.flux.reshape(new_flux_shape)\n\n        ones = [1] * len(orig_spectrum.flux.shape[:-1])\n        new_shape_resample_grid = ones + list(resample_grid.shape)\n        resample_grid = resample_grid.reshape(new_shape_resample_grid)\n\n        # Calculate final flux\n        out_flux = np.sum(in_flux * resample_grid, axis=-1) / np.sum(\n            resample_grid, axis=-1)\n\n        # Calculate output uncertainty\n        if pixel_uncer is not None:\n            pixel_uncer = pixel_uncer.reshape(new_flux_shape)\n\n            out_variance = np.sum(pixel_uncer * resample_grid**2, axis=-1) / np.sum(\n                resample_grid**2, axis=-1)\n            out_uncertainty = InverseVariance(np.reciprocal(out_variance))\n        else:\n            out_uncertainty = None\n\n        # nan-filling happens by default - replace with zeros if requested:\n        if self.extrapolation_treatment == 'zero_fill':\n            origedges = orig_spectrum.spectral_axis.bin_edges\n            off_edges = (fin_spec_axis < origedges[0]) | (origedges[-1] < fin_spec_axis)\n            out_flux[off_edges] = 0\n            if out_uncertainty is not None:\n                out_uncertainty.array[off_edges] = 0\n\n        # todo: for now, use the units from the pre-resampled\n        # spectra, although if a unit is defined for fin_spec_axis and it doesn't\n        # match the input spectrum it won't work right, will have to think\n        # more about how to handle that... could convert before and after\n        # calculation, which is probably easiest. Matrix math algorithm is\n        # geometry based, so won't work to just let quantity math handle it.\n        resampled_spectrum = Spectrum1D(flux=out_flux,\n                                        spectral_axis=np.array(fin_spec_axis) * orig_spectrum.spectral_axis.unit,\n                                        uncertainty=out_uncertainty)\n\n        return resampled_spectrum\n\n\nclass LinearInterpolatedResampler(ResamplerBase):\n    \"\"\"\n    Resample a spectrum onto a new ``spectral_axis`` using linear interpolation.\n\n    Parameters\n    ----------\n    extrapolation_treatment : str\n        What to do when resampling off the edge of the spectrum.  Can be\n        ``'nan_fill'`` to have points beyond the edges by set to NaN, or\n        ``'zero_fill'`` to be set to zero.\n\n    Examples\n    --------\n\n    To resample an input spectrum to a user specified dispersion grid using\n    linear interpolation:\n\n    >>> import numpy as np\n    >>> import astropy.units as u\n    >>> from specutils import Spectrum1D\n    >>> from specutils.manipulation import LinearInterpolatedResampler\n    >>> input_spectra = Spectrum1D(\n    ...     flux=np.array([1, 3, 7, 6, 20]) * u.mJy,\n    ...     spectral_axis=np.array([2, 4, 12, 16, 20]) * u.nm)\n    >>> resample_grid = [1, 5, 9, 13, 14, 17, 21, 22, 23] * u.nm\n    >>> fluxc_resample = LinearInterpolatedResampler()\n    >>> output_spectrum1D = fluxc_resample(input_spectra, resample_grid) # doctest: +IGNORE_OUTPUT\n    \"\"\"\n    def __init__(self, extrapolation_treatment='nan_fill'):\n        super().__init__(extrapolation_treatment)\n\n    def resample1d(self, orig_spectrum, fin_spec_axis):\n        \"\"\"\n        Call interpolation, repackage new spectra\n\n\n        Parameters\n        ----------\n        orig_spectrum : `~specutils.Spectrum1D`\n            The original 1D spectrum.\n        fin_spec_axis : ndarray\n            The desired spectral axis array.\n\n        Returns\n        -------\n        resample_spectrum : `~specutils.Spectrum1D`\n            An output spectrum containing the resampled `~specutils.Spectrum1D`\n        \"\"\"\n\n        fill_val = np.nan  # bin_edges=nan_fill case\n        if self.extrapolation_treatment == 'zero_fill':\n            fill_val = 0\n\n        orig_axis_in_fin = orig_spectrum.spectral_axis.to(fin_spec_axis.unit)\n\n        out_flux_arr = np.interp(fin_spec_axis.value, orig_axis_in_fin.value,\n                                 orig_spectrum.flux.value, left=fill_val, right=fill_val)\n        out_flux = Quantity(out_flux_arr, unit=orig_spectrum.flux.unit)\n\n        new_unc = None\n        if orig_spectrum.uncertainty is not None:\n            out_unc_arr = np.interp(fin_spec_axis.value, orig_axis_in_fin.value,\n                                    orig_spectrum.uncertainty.array,\n                                    left=fill_val, right=fill_val)\n            new_unc = orig_spectrum.uncertainty.__class__(array=out_unc_arr,\n                                                          unit=orig_spectrum.unit)\n\n        return Spectrum1D(spectral_axis=fin_spec_axis,\n                          flux=out_flux,\n                          uncertainty=new_unc)\n\n\nclass SplineInterpolatedResampler(ResamplerBase):\n    \"\"\"\n    This resample algorithim uses a cubic spline interpolator. Any uncertainty\n    is also interpolated using an identical spline.\n\n\n    Parameters\n    ----------\n    extrapolation_treatment : str\n        What to do when resampling off the edge of the spectrum.  Can be\n        ``'nan_fill'`` to have points beyond the edges by set to NaN, or\n        ``'zero_fill'`` to be set to zero.\n\n    Examples\n    --------\n\n    To resample an input spectrum to a user specified spectral axis grid using\n    a cubic spline interpolator:\n\n    >>> import numpy as np\n    >>> import astropy.units as u\n    >>> from specutils import Spectrum1D\n    >>> from specutils.manipulation import SplineInterpolatedResampler\n    >>> input_spectra = Spectrum1D(\n    ...     flux=np.array([1, 3, 7, 6, 20]) * u.mJy,\n    ...     spectral_axis=np.array([2, 4, 12, 16, 20]) * u.nm)\n    >>> resample_grid = [1, 5, 9, 13, 14, 17, 21, 22, 23] * u.nm\n    >>> fluxc_resample = SplineInterpolatedResampler()\n    >>> output_spectrum1D = fluxc_resample(input_spectra, resample_grid) # doctest: +IGNORE_OUTPUT\n\n    \"\"\"\n    def __init__(self, bin_edges='nan_fill'):\n        super().__init__(bin_edges)\n\n    def resample1d(self, orig_spectrum, fin_spec_axis):\n        \"\"\"\n        Call interpolation, repackage new spectra\n\n\n        Parameters\n        ----------\n        orig_spectrum : `~specutils.Spectrum1D`\n            The original 1D spectrum.\n        fin_spec_axis : Quantity\n            The desired spectral axis array.\n\n        Returns\n        -------\n        resample_spectrum : `~specutils.Spectrum1D`\n            An output spectrum containing the resampled `~specutils.Spectrum1D`\n        \"\"\"\n        orig_axis_in_new = orig_spectrum.spectral_axis.to(fin_spec_axis.unit)\n        flux_spline = CubicSpline(orig_axis_in_new.value, orig_spectrum.flux.value,\n                                   extrapolate=self.extrapolation_treatment != 'nan_fill')\n        out_flux_val = flux_spline(fin_spec_axis.value)\n\n        new_unc = None\n        if orig_spectrum.uncertainty is not None:\n            unc_spline = CubicSpline(orig_axis_in_new.value, orig_spectrum.uncertainty.array,\n                                       extrapolate=self.extrapolation_treatment != 'nan_fill')\n            out_unc_val = unc_spline(fin_spec_axis.value)\n            new_unc = orig_spectrum.uncertainty.__class__(array=out_unc_val, unit=orig_spectrum.unit)\n\n        if self.extrapolation_treatment == 'zero_fill':\n            origedges = orig_spectrum.spectral_axis.bin_edges\n            off_edges = (fin_spec_axis < origedges[0]) | (origedges[-1] < fin_spec_axis)\n            out_flux_val[off_edges] = 0\n            if new_unc is not None:\n                new_unc.array[off_edges] = 0\n\n        return Spectrum1D(spectral_axis=fin_spec_axis,\n                          flux=out_flux_val*orig_spectrum.flux.unit,\n                          uncertainty=new_unc)\n", "meta": {"hexsha": "c55d3c5c609288d6c3d6534b6e312731850a6eca", "size": 14938, "ext": "py", "lang": "Python", "max_stars_repo_path": "specutils/manipulation/resample.py", "max_stars_repo_name": "keflavich/specutils", "max_stars_repo_head_hexsha": "ec4fe50c6c032fc421c2cd0ee0dda11fd0f856cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "specutils/manipulation/resample.py", "max_issues_repo_name": "keflavich/specutils", "max_issues_repo_head_hexsha": "ec4fe50c6c032fc421c2cd0ee0dda11fd0f856cb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "specutils/manipulation/resample.py", "max_forks_repo_name": "keflavich/specutils", "max_forks_repo_head_hexsha": "ec4fe50c6c032fc421c2cd0ee0dda11fd0f856cb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.372972973, "max_line_length": 113, "alphanum_fraction": 0.6401794082, "include": true, "reason": "import numpy,from scipy,import astropy,from astropy", "num_tokens": 3527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.17896253574164256}}
{"text": "'''\n\n该文件用于ROI_summer 数据集上,192 大小对256大小的sar-optical图像匹配,\n统计匹配位置误差,匹配FLAG(<5 PIXELS), 匹配关键点数量, 关键点误差(<= 2 PIXELS)\nrelated results are saved in eval_results_XX.txt\n\n'''\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\nimport cv2\nimport numpy as np\nimport math\nimport os\nimport time\nfrom glob import glob\n\n\nclass models():\n    def __init__(self,dataset,weights_list):\n        self.dataset = dataset\n        self.weights_list - weights_list\n\n\n\n\ndef model_choose(model_path):\n\n    if 'agl_cls_cspdense' in model_path:\n\n        from old.networks_angle_cls_csp_dense import EmbeddingNet, LDMNet\n        embede_model = EmbeddingNet()\n        embede_model.cuda()\n        ldm_model = LDMNet(embede_model)\n        ldm_model.cuda().eval()\n        load_model(ldm_model,model_path)\n        print('using agl_cls_cspdense net')\n        return embede_model,ldm_model\n\n    elif 'HardNet' in model_path:\n\n        from old.networks_l2_sos import EmbeddingNet, LDMNet\n        embede_model = EmbeddingNet()\n        embede_model.cuda()\n        ldm_model = LDMNet(embede_model)\n        ldm_model.cuda().eval()\n        load_model(ldm_model,model_path)\n        print('using Hardnet net')\n\n        return embede_model,ldm_model\n\n    elif 'classification' in model_path:\n        from old.networks_angle_classification import EmbeddingNet, LDMNet\n        embede_model = EmbeddingNet()\n        embede_model.cuda()\n        ldm_model = LDMNet(embede_model)\n        ldm_model.cuda().eval()\n        load_model(ldm_model,model_path)\n        print('using classification simple net')\n\n        return embede_model,ldm_model\n\n    elif 'TFeat' in model_path:\n        from old.networks_tfeat import TNet_Rocket, LDMNet\n        embede_model = TNet_Rocket()\n        embede_model.cuda()\n        ldm_model = LDMNet(embede_model)\n        ldm_model.cuda().eval()\n        load_model(ldm_model,model_path)\n        print('using Tfeat net')\n\n        return embede_model,ldm_model\n\n    elif 'MatchNet' in model_path:\n        from old.network_matchnet_512 import FeatureNet, CLSNet\n        embede_model = FeatureNet()\n        embede_model.cuda()\n        ldm_model = CLSNet(embede_model)\n        ldm_model.cuda().eval()\n        load_model(ldm_model,model_path)\n        print('using matchnet net...')\n\n        return embede_model,ldm_model\n\n    elif '_l2_cspdense' in model_path:\n        from old.networks_l2_cls_csp_dense import EmbeddingNet, LDMNet\n        embede_model  = EmbeddingNet()\n        embede_model.cuda()\n        ldm_model = LDMNet(embede_model)\n        ldm_model.cuda().eval()\n        load_model(ldm_model,model_path)\n        print('using l2_cspdense net...')\n        return embede_model,ldm_model\n\n    elif 'entropy_cspdense' in model_path:\n        from old.networks_entropyloss_cls_csp_dense import EmbeddingNet, CLSNet\n        embede_model  = EmbeddingNet()\n        embede_model.cuda()\n        ldm_model = CLSNet(embede_model)\n        ldm_model.cuda().eval()\n        load_model(ldm_model,model_path)\n        print('using entropy_csp_dense net...')\n        return embede_model,ldm_model\n\n    elif 'agl_dense' in model_path:\n        from old.networks_angle_cls_dense import EmbeddingNet,LDMNet\n        embede_model  = EmbeddingNet()\n        embede_model.cuda()\n        ldm_model = LDMNet(embede_model)\n        ldm_model.cuda().eval()\n        load_model(ldm_model,model_path)\n        print('using agl_dense net...')\n        return embede_model,ldm_model\n\n    elif 'cspdense64_joint' in model_path:\n        from old.networks_l2_cls_csp_dense import EmbeddingNet\n        from joint_model.jointNet import JointNet,LDMNet\n        embede_model  = JointNet(EmbeddingNet())\n        embede_model.cuda()\n        ldm_model = LDMNet(embede_model).cuda().float()\n        # ldm_model = LDMNet(embede_model)\n        ldm_model.cuda().eval()\n        load_model(ldm_model,model_path)\n        print('using cspdense64_joint net...')\n        global joint_flag \n        joint_flag = True\n        return embede_model,ldm_model\n\n    elif 'arcl2_cspdense' in model_path:\n        from networks_arcl2_csp_dense import EmbeddingNet,LDMNet\n        embede_model  = EmbeddingNet()\n        embede_model.cuda()\n        ldm_model = LDMNet(embede_model)\n        ldm_model.cuda().eval()\n        load_model(ldm_model,model_path)\n        print('using arcl2 cspdense net...')\n        return embede_model,ldm_model\n\n\n\ndef load_model(model,model_path):\n    checkpoint = torch.load(model_path,map_location='cuda:0')\n    model.load_state_dict(checkpoint['model_state_dict']) \n    return \n\ndef kpts2descriptors(kpts,img,model,batch_size=128,patch_size=64,use_gpu=True):\n    descrs = []\n    length = len(kpts)\n    shards = int(np.ceil(length/batch_size))\n    h,w = img.shape[:2]\n    sx,sy,ex,ey = 0,0,0,0\n    ltoffsets = patch_size//2\n    rboffsets = patch_size-ltoffsets\n    for i in range(shards):\n        patches = []\n        batch_kpts = kpts[i*batch_size:min((i+1)*batch_size,length)]\n        for kp in batch_kpts:\n            x, y = kp.pt\n            x = int(x)\n            y = int(y)\n            if x <= ltoffsets:\n                sx = 0\n                ex = sx + patch_size\n            else:\n                ex = min(x+rboffsets,w)\n                sx = ex-patch_size\n            if y <= ltoffsets:\n                sy = 0\n                ey = sy + patch_size\n            else:\n                ey = min(y+rboffsets,h)\n                sy = ey-patch_size\n            patch = img[int(sy):int(ey),int(sx):int(ex)]\n            assert patch.shape[0] == patch_size and patch.shape[1] == patch_size,str(patch.shape)+'  '+str(x)+' '+str(y)\n            patches.append(patch)\n\n        patches = torch.from_numpy(np.asarray(patches)).float()\n        patches = torch.unsqueeze(patches, 1)\n        if use_gpu:\n            patches = patches.cuda()\n\n        descrs.append(model(patches).detach().cpu().numpy())\n\n    descrs = np.concatenate(descrs,axis=0)\n    # print(len(descrs))\n    return descrs\n\ndef matches2offsets(matches,queryKp,trainKp):\n    offsets = []\n    for m in matches:\n        train_x,train_y = trainKp[m.trainIdx].pt\n        train_x,train_y = round(train_x),round(train_y)\n        query_x,query_y = queryKp[m.queryIdx].pt\n        query_x,query_y = round(query_x),round(query_y)\n        offset_x = query_x - train_x\n        offset_y = query_y - train_y\n        if 0 < offset_x < 289 and 0 < offset_y < 289:\n            offsets.append([offset_x,offset_y])\n    return offsets\n\ndef matched_kpt_summary(offsets,gt_point):\n    # 统计匹配上的关键点数量和kpt平均误差\n    matched_cnt = 0\n    matched_diff = 0.\n    diff = np.array(offsets) - np.array(gt_point)\n    distance = np.sqrt(diff[:,0]*diff[:,0]+diff[:,1]*diff[:,1])\n    matched_cnt = np.sum(distance <= 2)\n    mask = (distance <= 2).reshape(-1,1)\n    if matched_cnt != 0:\n        matched_diff = np.mean(distance[distance <= 2])\n        mask = np.concatenate([mask,mask],1)\n        diff = abs(diff[mask].reshape(-1,2))\n    else:\n        matched_diff = 0\n        diff = np.zeros([1,2])\n    # print(distance[distance <= 2])\n    # print('match cnt%f, matched diff%f'%(matched_cnt,matched_diff))\n    return matched_cnt, matched_diff, [np.mean(diff[:,0]),np.mean(diff[:,1])]\n        \n\n\ndef match_images(img1,img2,model,fp_detector,MIN_MATCH_COUNT=4,homo=True,thresh=1.20,knn=1,gt_point=[0,0]):\n    normalize_img1 = cv2.normalize(img1,dst=None,alpha=450,beta=10,norm_type=cv2.NORM_MINMAX)\n    normalize_img2 = cv2.normalize(img2,dst=None,alpha=450,beta=10,norm_type=cv2.NORM_MINMAX)\n    # normalize_img1 = img1\n    # normalize_img2 = img2\n    kp1 = fp_detector.detect(normalize_img1, None)\n    kp2 = fp_detector.detect(normalize_img2, None)\n    desc_tfeat1 = kpts2descriptors(kp1,img1,model)\n    desc_tfeat2 = kpts2descriptors(kp2,img2,model)\n    #print('query.shape:',desc_tfeat1.shape)\n    #print('train.shape:',desc_tfeat2.shape)\n    bf = cv2.BFMatcher(cv2.NORM_L2)\n    \n    matches = bf.knnMatch(desc_tfeat1,desc_tfeat2, k=knn)\n    good = []\n    for m in matches:\n        for mm in m:\n            if mm.distance < thresh:\n                good.append(mm)\n    #print('num good matches:',len(good))\n\n    # src_pts = np.float32([ kp1[m.queryIdx].pt for m in good]).reshape(-1,1,2)\n    # dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good]).reshape(-1,1,2)\n    # offsets_k,flag = matches2offsets_v2(src_pts,dst_pts)\n\n    offsets = matches2offsets(good,kp1,kp2)\n    matched_cnt, matched_diff = 0. ,0.\n    diff_xy = [0,0]\n    length = len(offsets)\n    if length >= 2:\n        matched_cnt, matched_diff, diff_xy = matched_kpt_summary(offsets,gt_point)\n        \n    if length == 0:\n        offsets = [144,144]\n    elif length <= 2:\n        offsets = offsets[0]\n    else:\n        #offsets = kmeans(offsets)\n        offsets = find_most_common(offsets)\n    \n    good_temp = []\n    px,py = 0,0\n    for m in good:\n        qx,qy = kp1[m.queryIdx].pt\n        #qx,qy = round(qx),round(qy)\n        tx,ty = kp2[m.trainIdx].pt\n        #tx,ty = round(tx),round(ty)\n        if abs(qx-tx - offsets[0]) < 1 and abs(qy-ty- offsets[1]) < 1:\n            good_temp.append(m)\n            px += (qx-tx)\n            py += (qy-ty)\n    good = good_temp\n\n    match_img = cv2.drawMatches(img1,kp1,img2,kp2,good,None,(0,0,255),flags=2)\n    bk_gd = np.ones((match_img.shape))\n    bk_gd[0:img1.shape[1],0:img1.shape[1]] = cv2.cvtColor(img1,cv2.COLOR_GRAY2BGR)\n    bk_gd[0:img2.shape[1],img1.shape[1]:(img1.shape[1]+img2.shape[1])] = cv2.cvtColor(img2,cv2.COLOR_GRAY2BGR)\n    bk_gd = cv2.rectangle(bk_gd,(offsets[0],offsets[1]),(int(offsets[0]+img2.shape[1]),int(offsets[1]+img2.shape[1])),(0,0,255),3)\n    \n    return offsets,[match_img,bk_gd],[matched_cnt,matched_diff,diff_xy]\n\ndef find_most_common(offsets):\n    kernel = np.zeros((7,7))\n    for i in range(7):\n        for j in range(7):\n            kernel[i,j] = 1 - math.sqrt((i-3)**2+(j-3)**2)/5\n\n    # cv2.imshow('kernel',kernel)\n    # cv2.waitKey(0)\n    array = np.zeros((289,289))\n    for x,y in offsets:\n        ksy,key,ksx,kex = 0,7,0,7\n        asy = y-3\n        aey = y + 4\n        asx = x-3\n        aex = x+4\n        if asy < 0:\n            asy = 0\n            ksy = 3-y\n        if aey > 289:\n            key = 7+289-aey\n            aey = 289\n        if asx < 0:\n            asx = 0\n            ksx = 3-x\n        if aex > 289:\n            kex = 7+289-aex\n            aex = 289\n        #print(sy,ey,sx,ex)\n\n        array[asy:aey,asx:aex] += kernel[ksy:key,ksx:kex]\n    index = array.reshape(-1).argmax()\n    offsets = [index%289,index//289]\n    return offsets\n\n    \ndef validate(model,fp_detector,data_path,save_path):\n\n    match_count = 0\n    match_error = 0\n    error_x = 0\n    error_y = 0\n    kpt_cnt, kpt_diff = [],[]\n    cnt = 1\n    opt_imgs_path = glob(data_path+'/opt_*')\n    for i,opt_path in enumerate(opt_imgs_path):\n        # try:\n        x,y = opt_path.split('/')[-1].split('.')[0].split('_')[2:]\n        x,y = float(x),float(y)\n        sar_path = opt_path.replace('opt','sar')\n        opt_img = cv2.imread(opt_path,0)\n        sar_img = cv2.imread(sar_path,0)\n        offsets,result_img, matched_info = match_images(opt_img,sar_img,model,fp_detector,homo=False,thresh=7,knn=2,gt_point=[x,y]) # use opt as queryImg, sar as trainImg\n        \n        distance = math.sqrt(math.pow(offsets[0]-x,2) + math.pow(offsets[1]-y,2))\n        match_flag =  distance < 5\n        kpt_cnt.append(matched_info[0])\n        kpt_diff.append(matched_info[1])\n        if match_flag:\n            error_x += abs(offsets[0] - x)\n            error_y += abs(offsets[1] - y)\n            match_error += distance\n            match_count += 1\n\n        cv2.imwrite('./%d_%.2f_%d_kset.png'%(i,distance,match_flag),result_img[0])\n        cv2.imwrite('./%d_%.2f_%d_kset_circle.png'%(i,distance,match_flag),result_img[1])\n        cnt += 1\n\n    kpt_avg_cnt = np.mean(np.array(kpt_cnt))\n    kpt_avg_diff = np.mean(np.array(kpt_diff))\n\n    return match_count,match_error/match_count, error_x/match_count, error_y/match_count,[kpt_avg_cnt,kpt_avg_diff]\n\n\n\nif __name__ == '__main__':\n\n    model_path = 'weights_arcl2_cspdense_Rocket/thetabeta_ap_66_684_0.363_28.287.tar'    \n    embede_model,_ = model_choose(model_path)\n\n    save_path='best_results_diffsize_rocket/{}'.format(model_path.split('/')[-2])\n    # fp_detector = cv2.xfeatures2d.SIFT_create(6000)\n    # fp_detector = cv2.xfeatures2d.HarrisLaplaceFeatureDetector_create()\n    fp_detector = cv2.FastFeatureDetector_create()\n    #fp_detector = cv2.BRISK.create()\n    start = time.time()\n\n    data_path = 'test_image'\n    mc,me,mex,mey,kpt_info = validate(embede_model,fp_detector,data_path,save_path)\n    # print('{} test finished!'.format(model_path.split('/')[0].split('_')[1]))\n    save_txt = '{}.txt'.format(model_path.split('/')[-2])\n    save_data1 = 'matched key point average count: {}, key point average diff:{}\\n'.format(kpt_info[0],kpt_info[1])\n    save_data2 = 'match_count:%d, location match error:%f, x_error:%f, y_error:%f'%(mc,me,mex,mey)\n    print('time consumed: %.2fs'%(time.time()-start))\n    print(save_data1)\n    print(save_data2)\n    \n        \n", "meta": {"hexsha": "232ae4362a0e2a4d612f542edcaf713e1589bc87", "size": 13000, "ext": "py", "lang": "Python", "max_stars_repo_path": "location_demo.py", "max_stars_repo_name": "LiaoYun0x0/Feature-Matching-and-Position-Matching-between-Optical-and-SAR", "max_stars_repo_head_hexsha": "a622c6baeefcd544fd84b686ebe404c254caddfd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-07-22T05:17:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T01:37:28.000Z", "max_issues_repo_path": "location_demo.py", "max_issues_repo_name": "LiaoYun0x0/Feature-Matching-and-Position-Matching-between-Optical-and-SAR", "max_issues_repo_head_hexsha": "a622c6baeefcd544fd84b686ebe404c254caddfd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-08-04T13:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T07:56:32.000Z", "max_forks_repo_path": "location_demo.py", "max_forks_repo_name": "LiaoYun0x0/Feature-Matching-and-Position-Matching-between-Optical-and-SAR", "max_forks_repo_head_hexsha": "a622c6baeefcd544fd84b686ebe404c254caddfd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-09-20T15:58:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T12:42:49.000Z", "avg_line_length": 34.1207349081, "max_line_length": 170, "alphanum_fraction": 0.6277692308, "include": true, "reason": "import numpy", "num_tokens": 3778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.1788522504500009}}
{"text": "    # -*- coding: utf-8 -*-\r\n# mpc_nbody/mpc_nbody/parse_input.py\r\n\r\n'''\r\n----------------------------------------------------------------------------\r\nmpc_nbody's module for parsing OrbFit + ele220 elements\r\n\r\nMar 2020\r\nMike Alexandersen & Matthew Payne & Matthew Holman\r\n\r\nThis module provides functionalities to\r\n(a) read an OrbFit .fel/.eq file with heliocentric ecliptic cartesian els\r\n(b) read ele220 element strings\r\n(c) convert the above to barycentric equatorial cartesian elements\r\n\r\nThis is meant to prepare the elements for input into the n-body integrator\r\n----------------------------------------------------------------------------\r\n'''\r\n\r\n# Import third-party packages\r\n# -----------------------------------------------------------------------------\r\nimport os, sys\r\nimport numpy as np\r\nfrom astropy.time import Time\r\nimport getpass\r\n\r\nif getpass.getuser() in ['matthewjohnpayne']:  # Payne's dev laptop set up differently ...:\r\n    sys.path.append('/Users/matthewjohnpayne/Envs/mpcvenv/')\r\nimport mpcpp.MPC_library as mpc\r\n\r\n# Import neighbouring packages\r\n# -----------------------------------------------------------------------------\r\n\r\n# Default for caching stuff using lru_cache\r\n# -----------------------------------------------------------------------------\r\n\r\n# Constants and stuff\r\n# -----------------------------------------------------------------------------\r\nDATA_PATH = os.path.realpath(os.path.dirname(__file__))\r\nau_km = 149597870.700  # This is now a definition\r\n\r\n# Data classes/methods\r\n# -----------------------------------------------------------------------------\r\n\r\n\r\nclass ParseElements():\r\n    '''\r\n    Class for parsing elements and returning them in the correct format.\r\n    '''\r\n\r\n    def __init__(self, input_file=None, filetype=None, save_parsed=False ):\r\n    \r\n        # The variables that will be used to hold the elements\r\n        # - They get populated by *parse_orbfit* & *make_bary_equatorial*\r\n        self.helio_ecl_vec_EXISTS   = False\r\n        self.helio_ecl_vec          = None\r\n        self.helio_ecl_cov_EXISTS   = False\r\n        self.helio_ecl_cov          = None\r\n        self.bary_eq_vec_EXISTS     = False\r\n        self.bary_eq_vec            = None\r\n        self.bary_eq_cov_EXISTS     = False\r\n        self.bary_eq_cov            = None\r\n        \r\n        # If input filename provided, process it:\r\n        if isinstance(input_file, str) & isinstance(filetype, str):\r\n            if filetype == 'ele220':\r\n                self.parse_ele220(input_file)\r\n            if (filetype == 'fel') | (filetype == 'eq'):\r\n                self.parse_orbfit(input_file)\r\n            self.make_bary_equatorial()\r\n            if save_parsed:\r\n                self.save_elements()\r\n        else:\r\n            print(\"Keywords 'input_file' and/or 'filetype' missing; \"\r\n                  \"initiating empty object.\")\r\n\r\n    def save_elements(self, output_file='holman_ic'):\r\n        \"\"\"\r\n        Save the barycentric equatorial cartesian elements to file.\r\n\r\n        Inputs:\r\n        -------\r\n        output_file : string, filename to write elements to.\r\n\r\n        The file is overwritten if it already exists.\r\n        \"\"\"\r\n        self.tstart = self.time.tdb.jd\r\n        outfile = open(output_file, 'w')\r\n        outfile.write(f\"tstart {self.tstart:}\\n\")\r\n        outfile.write(\"tstep +20.0\\n\")\r\n        outfile.write(\"trange 600.\\n\")\r\n        outfile.write(\"geocentric 0\\n\")\r\n        outfile.write(\"state\\n\")\r\n        \r\n        # For whatever reason, we are writing this over two lines\r\n        # - perhaps to compare against JPL?\r\n        for n,coeff in enumerate(self.bary_eq_vec):\r\n            suffix = '\\n' if n in [2,5] else ''\r\n            outfile.write(f\"{coeff: 18.15e} \" + suffix)\r\n\r\n    def parse_ele220(self, ele220file=None):\r\n        '''\r\n        Parse a file containing a single ele220 line.\r\n        Currently returns junk data.\r\n        NOT ACTUALLY IMPLEMENTED YET!!!\r\n        '''\r\n        if ele220file is None:\r\n            raise TypeError(\"Required argument 'ele220file'\"\r\n                            \" (pos 1) not found\")\r\n\r\n        # make fake data & set appropriate variables\r\n        self._get_and_set_junk_data()\r\n\r\n    def parse_orbfit(self, felfile):\r\n        '''\r\n        Parse a file containing OrbFit elements for a single object & epoch.\r\n        Currently returns junk data.\r\n\r\n        Inputs:\r\n        -------\r\n        felfile : string, filename of fel/eq formatted OrbFit output\r\n\r\n        Populates:\r\n        --------\r\n        self.helio_ecl_vec_EXISTS   : Boolean\r\n        self.helio_ecl_vec          : 1D np.ndarray\r\n        self.helio_ecl_cov_EXISTS   : Boolean\r\n        self.helio_ecl_cov          : 1D np.ndarray\r\n        self.time                   : astropy Time object\r\n        '''\r\n\r\n        # Read the contents of the orbfit output \"fel\" file\r\n        obj = {}\r\n        with open(felfile,'r') as fh:\r\n            el = fh.readlines()\r\n        cart_head = '! Cartesian position and velocity vectors\\n'\r\n\r\n        # Only do this if the file actually has cartesian coordinates.\r\n        if el.count(cart_head) > 0:\r\n            # get Cartesian Elements out of the file contents\r\n            carLoc = len(el) - 1 - list(reversed(el)).index(cart_head)\r\n            carEls = el[carLoc:carLoc + 25]\r\n            \r\n            # Form an array of the heliocentric ecliptic cartesian coefficients\r\n            (_, car_x, car_y, car_z, car_dx, car_dy, car_dz\r\n                       ) = carEls[1].split()\r\n            self.helio_ecl_vec = np.array([ float(car_x), float(car_y),  float(car_z), \\\r\n                                            float(car_dx), float(car_dy), float(car_dz)]\r\n                                            )\r\n            self.helio_ecl_vec_EXISTS = True\r\n                                                      \r\n            # Using Astropy.time for time conversion,\r\n            # because life's too short for timezones and time scales.\r\n            _, mjd_tdt, _ = carEls[2].split()\r\n            self.time = Time(float(mjd_tdt), format='mjd', scale='tt')\r\n\r\n            # Parse carEls (the contents of the orbfit file) to get\r\n            # the cartesian covariance matrix\r\n            self.helio_ecl_cov_EXISTS, self.helio_ecl_cov = _parse_Covariance_List(carEls)\r\n            \r\n        else:\r\n            raise TypeError(\"There does not seem to be any valid elements \"\r\n                            f\"in the input file {felfile:}\")\r\n\r\n    def make_bary_equatorial(self):\r\n        '''\r\n        Transform heliocentric-ecliptic coordinates into\r\n        barycentric equatorial coordinates\r\n        \r\n        requires:\r\n        ----------\r\n        self.helio_ecl_vec_EXISTS   : Boolean\r\n        self.helio_ecl_vec          : 1D np.ndarray\r\n        self.helio_ecl_cov_EXISTS   : Boolean\r\n        self.helio_ecl_cov          : 2D np.ndarray\r\n\r\n        populates:\r\n        ----------\r\n        self.bary_eq_vec_EXISTS     = Boolean\r\n        self.bary_eq_vec            = 1D np.ndarray\r\n        self.bary_eq_cov_EXISTS     = Boolean\r\n        self.bary_eq_cov            = 2D np.ndarray\r\n        '''\r\n        if self.helio_ecl_vec_EXISTS :\r\n            # Transform the helio-ecl-coords to bary-eq-coords\r\n            # NB 2-step transformation for the vector (posn,vel)\r\n            self.bary_eq_vec   = equatorial_helio2bary(\r\n                                    ecliptic_to_equatorial(self.helio_ecl_vec),\r\n                                    self.time.tdb.jd\r\n                                )\r\n            # Set boolean as well (not sure if we'll really use these ...)\r\n            self.bary_eq_vec_EXISTS = True\r\n\r\n        if self.helio_ecl_cov_EXISTS:\r\n            # Only need to do a rotation for the CoV\r\n            self.bary_eq_cov = ecliptic_to_equatorial(self.helio_ecl_cov)\r\n        \r\n            # Set booleans as well (not sure if we'll really use these ...)\r\n            self.bary_eq_cov_EXISTS = True\r\n\r\n        if not self.helio_ecl_vec_EXISTS and not self.helio_ecl_cov_EXISTS:\r\n            raise TypeError(\"There does not seem to be any valid helio_ecl to transform into bary_eq\")\r\n            \r\n        return True\r\n        \r\n        \r\n    def _get_and_set_junk_data(self, BaryEqDirect=False ):\r\n        \"\"\"Just make some junk data for saving.\"\"\"\r\n        self.time                           = Time(2458849.5, format='jd', scale='tdb')\r\n        v   = np.array( [3., 2., 1., 0.3, 0.2, 0.1] )\r\n        CoV = 0.01 * np.ones((6,6))\r\n        \r\n        # Default is to make helio-ecl, then calc bary-eq from that\r\n        if not BaryEqDirect:\r\n            self.helio_ecl_vec              = v\r\n            self.helio_ecl_vec_EXISTS       = True\r\n            \r\n            self.helio_ecl_cov              = CoV\r\n            self.helio_ecl_cov_EXISTS       = True\r\n        \r\n            self.make_bary_equatorial()\r\n            \r\n        # Alternative is to directly set bary-eq\r\n        else:\r\n            self.bary_eq_vec                = v\r\n            self.bary_eq_vec_EXISTS         = True\r\n            \r\n            self.bary_eq_cov                = CoV\r\n            self.bary_eq_cov_EXISTS         = True\r\n\r\n\r\n\r\n# Functions\r\n# -----------------------------------------------------------------------------\r\n    \r\ndef ecliptic_to_equatorial(input, backwards=False):\r\n    '''\r\n    Rotates a cartesian vector or Cov-Matrix from mean ecliptic to mean equatorial.\r\n    \r\n    Backwards=True converts backwards, from equatorial to ecliptic.\r\n    \r\n    inputs:\r\n    -------\r\n    input : 1-D or 2-D arrays\r\n     - If 1-D, then len(input) must be 3 or 6\r\n     - If 2-D, then input.shape must be (6,6)\r\n     \r\n    output:\r\n    -------\r\n    output : np.ndarray\r\n     - same shape as input\r\n    '''\r\n\r\n    # Ensure we have an array\r\n    input = np.atleast_1d(input)\r\n    \r\n    # The rotation matricees we may use\r\n    direction = -1 if backwards else +1\r\n    R3 = mpc.rotate_matrix(mpc.Constants.ecl * direction)\r\n    R6 = np.block( [ [R3, np.zeros((3,3))],[np.zeros((3,3)),R3] ])\r\n    \r\n    # Vector input => Single rotation operation\r\n    if   input.ndim == 1 and input.shape[0] in [3,6]:\r\n        R      = R6 if input.shape[0] == 6 else R3\r\n        output = R @ input\r\n        \r\n    # Matrix (CoV) input => R & R.T\r\n    elif input.ndim == 2 and input.shape == (6,6):\r\n        R = R6\r\n        output = R @ input @ R.T\r\n    \r\n    # Unknown input\r\n    else:\r\n        sys.exit(f'Does not compute: input.ndim=={input.ndim} , input.shape={input.shape}')\r\n\r\n    assert output.shape == input.shape\r\n    return output\r\n\r\n\r\ndef equatorial_helio2bary(input_xyz, jd_tdb, backwards=False):\r\n    '''\r\n    Convert from heliocentric to barycentic cartesian coordinates.\r\n    backwards=True converts backwards, from bary to helio.\r\n    input:\r\n        input_xyz - np.ndarray length 3 or 6\r\n        backwards - boolean\r\n    output:\r\n        output_xyz  - np.ndarray\r\n                    - same shape as input_xyz\r\n\r\n    input_xyz MUST BE EQUATORIAL!!!\r\n    '''\r\n    direction = -1 if backwards else +1\r\n\r\n    # Ensure we have an array of the correct shape to work with\r\n    input_xyz = np.atleast_1d(input_xyz)\r\n    assert input_xyz.ndim == 1\r\n    assert input_xyz.shape[0] in [3,6]\r\n    \r\n    # Position & Motion of the barycenter w.r.t. the heliocenter (and vice-versa)\r\n    delta, delta_vel = mpc.jpl_kernel[0, 10].compute_and_differentiate(jd_tdb)\r\n    \r\n    # Work out whether we need xyz or xyzuvw\r\n    delta = delta if input_xyz.shape[0] == 3 else np.block([delta,delta_vel])\r\n    \r\n    # Shift vectors & return\r\n    return input_xyz + delta * direction / au_km\r\n\r\n\r\n\r\n\r\n\r\ndef _old_parse_Covariance_List(Els):\r\n    '''\r\n    Convenience function for reading and splitting the covariance\r\n    lines of an OrbFit file.\r\n    Not intended for user usage.\r\n    '''\r\n    ElCov  = []\r\n    covErr = \"\"\r\n    for El in Els:\r\n        if El[:4] == ' COV':\r\n            ElCov.append(El)\r\n    if len(ElCov) == 7:\r\n        _, c11, c12, c13 = ElCov[0].split()\r\n        _, c14, c15, c16 = ElCov[1].split()\r\n        _, c22, c23, c24 = ElCov[2].split()\r\n        _, c25, c26, c33 = ElCov[3].split()\r\n        _, c34, c35, c36 = ElCov[4].split()\r\n        _, c44, c45, c46 = ElCov[5].split()\r\n        _, c55, c56, c66 = ElCov[6].split()\r\n    if len(ElCov) != 7:\r\n        c11, c12, c13, c14, c15, c16, c22 = \"\", \"\", \"\", \"\", \"\", \"\", \"\"\r\n        c23, c24, c25, c26, c33, c34, c35 = \"\", \"\", \"\", \"\", \"\", \"\", \"\"\r\n        c36, c44, c45, c46, c55, c56, c66 = \"\", \"\", \"\", \"\", \"\", \"\", \"\"\r\n        covErr = ' Empty covariance Matrix for '\r\n    return (covErr, c11, c12, c13, c14, c15, c16, c22, c23, c24, c25, c26,\r\n            c33, c34, c35, c36, c44, c45, c46, c55, c56, c66)\r\n    \r\ndef _parse_Covariance_List(Els):\r\n    '''\r\n    Convenience function for reading and splitting the covariance\r\n    lines of an OrbFit file.\r\n    Not intended for user usage.\r\n    # MJP : 20200901 : Suggest to just make & return the required matrix\r\n    '''\r\n    # Set-up array of zeroes\r\n    CoV        = np.zeros( (6,6) )\r\n    CoV_EXISTS = False\r\n    \r\n    # Populate triangle directly\r\n    ElCov=[]\r\n    for El in Els:\r\n        if El[:4] == ' COV':\r\n            ElCov.append(El)\r\n    if len(ElCov) == 7:\r\n        _, CoV[0,0],CoV[0,1],CoV[0,2] = ElCov[0].split() # c11, c12, c13\r\n        _, CoV[0,3],CoV[0,4],CoV[0,5] = ElCov[1].split() # c14, c15, c16\r\n        _, CoV[1,1],CoV[1,2],CoV[1,3] = ElCov[2].split() # c22, c23, c24\r\n        _, CoV[1,4],CoV[1,5],CoV[2,2] = ElCov[3].split() # c25, c26, c33\r\n        _, CoV[2,3],CoV[2,4],CoV[2,5] = ElCov[4].split() # c34, c35, c36\r\n        _, CoV[3,3],CoV[3,4],CoV[3,5] = ElCov[5].split() # c44, c45, c46\r\n        _, CoV[4,4],CoV[4,5],CoV[5,5] = ElCov[6].split() # c55, c56, c66\r\n        \r\n        # Populate the symmetric part\r\n        for i in range(1,6):\r\n            for j in range(i):\r\n                # # MA: Killed totally annoying and unneccessary print\r\n                #print(f'Setting Cov[{i,j}] = CoV{[j,i]}')\r\n                CoV[i,j]=CoV[j,i]\r\n                \r\n        # Set boolean\r\n        CoV_EXISTS = True\r\n    return CoV_EXISTS, CoV\r\n \r\n", "meta": {"hexsha": "4c21c1f29c67dfdc1969f636dc32427e6b6aa2f0", "size": 14046, "ext": "py", "lang": "Python", "max_stars_repo_path": "cheby_checker/archaic/parse_input_MA_EMAIL.py", "max_stars_repo_name": "jankansky/cheby_checker", "max_stars_repo_head_hexsha": "b709dc9b6cf790af9175e6a1f63795a0dfac9d59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cheby_checker/archaic/parse_input_MA_EMAIL.py", "max_issues_repo_name": "jankansky/cheby_checker", "max_issues_repo_head_hexsha": "b709dc9b6cf790af9175e6a1f63795a0dfac9d59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-08-05T18:11:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-16T18:25:07.000Z", "max_forks_repo_path": "cheby_checker/archaic/parse_input_MA_EMAIL.py", "max_forks_repo_name": "jankansky/cheby_checker", "max_forks_repo_head_hexsha": "b709dc9b6cf790af9175e6a1f63795a0dfac9d59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-23T15:41:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-23T15:41:32.000Z", "avg_line_length": 37.3563829787, "max_line_length": 103, "alphanum_fraction": 0.5264844084, "include": true, "reason": "import numpy,from astropy", "num_tokens": 3584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.17885224699709887}}
{"text": "# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"K-FAC functionality for auto-detecting layer tags and graph matching.\"\"\"\nimport functools\nimport itertools\nimport pprint\nfrom typing import Any, Callable, Dict, Iterable, Iterator, List, Mapping, MutableMapping, Optional, Sequence, Set, Tuple, TypeVar, Union\n\nfrom absl import logging\nimport chex\nimport immutabledict\nimport jax\nfrom jax import core\nfrom jax import lax\nfrom jax import util as jax_util\nimport jax.numpy as jnp\nfrom kfac_jax._src import layers_and_loss_tags as tags\nfrom kfac_jax._src import utils\nimport numpy as np\n\n# Types for annotation\nT = TypeVar(\"T\")\nEquivalenceFunction = Callable[[core.JaxprEqn, core.JaxprEqn], bool]\nGraphMatch = Tuple[\n    \"JaxprGraph\",\n    Dict[core.Var, core.Var],\n    Tuple[core.JaxprEqn, ...]\n]\nTagCtor = Callable[\n    [Sequence[core.JaxprEqn], Mapping[core.Var, chex.Array]],\n    chex.Array\n]\nPatternComputeFunc = Callable[[chex.Array, Sequence[chex.Array]], chex.Array]\nParameterExtractorFunc = Callable[[Sequence[core.JaxprEqn]], Mapping[str, Any]]\nValuesProcessor = Callable[[Sequence[chex.Array]], Sequence[chex.Array]]\n\n\ndef eval_jaxpr_eqn(eqn, in_values):\n  \"\"\"Computes the outputs of the given Jaxpr equation.\"\"\"\n  subfuns, bind_params = eqn.primitive.get_bind_params(eqn.params)\n  with jax.core.source_info_util.user_context(\n      eqn.source_info.traceback):\n    return eqn.primitive.bind(*subfuns, *in_values, **bind_params)\n\n\ndef reshape_equivalent(\n    equation1: core.JaxprEqn,\n    equation2: core.JaxprEqn\n) -> bool:\n  \"\"\"Equivalence rule for :func:`~jax.numpy.reshape` primitives.\"\"\"\n  if not (equation1.primitive.name == \"reshape\" and\n          equation2.primitive.name == \"reshape\"):\n    raise ValueError(\"This is only applicable to `reshape` primitive.\")\n\n  return equation1.params[\"dimensions\"] == equation2.params[\"dimensions\"]\n\n\ndef broadcast_in_dim_equivalent(\n    equation1: core.JaxprEqn,\n    equation2: core.JaxprEqn\n) -> bool:\n  \"\"\"Equivalence rule for :func:`~jax.numpy.broadcast` primitives.\"\"\"\n  if not (equation1.primitive.name == \"broadcast_in_dim\" and\n          equation2.primitive.name == \"broadcast_in_dim\"):\n    raise ValueError(\"This is only applicable to `broadcast_in_dim` primitive.\")\n  return True\n\n\ndef conv_general_dilated_equivalent(\n    equation1: core.JaxprEqn,\n    equation2: core.JaxprEqn\n) -> bool:\n  \"\"\"Equivalence rule for :func:`~jax.lax.conv_general_dilated` primitives.\"\"\"\n  if not (equation1.primitive.name == \"conv_general_dilated\" and\n          equation2.primitive.name == \"conv_general_dilated\"):\n    raise ValueError(\"This is only applicable to `conv_general_dilated` \"\n                     \"primitive.\")\n  params1 = equation1.params\n  params2 = equation2.params\n  for k in (\"window_strides\", \"padding\",\n            \"lhs_dilation\", \"rhs_dilation\",\n            \"lhs_shape\", \"rhs_shape\"):\n    if len(params1[k]) != len(params2[k]):\n      return False\n  if (len(params1[\"dimension_numbers\"].lhs_spec) !=\n      len(params2[\"dimension_numbers\"].lhs_spec)):\n    return False\n  if (len(params1[\"dimension_numbers\"].rhs_spec) !=\n      len(params2[\"dimension_numbers\"].rhs_spec)):\n    return False\n  if (len(params1[\"dimension_numbers\"].out_spec) !=\n      len(params2[\"dimension_numbers\"].out_spec)):\n    return False\n  if ((params1[\"feature_group_count\"] > 1) !=\n      (params2[\"feature_group_count\"] > 1)):\n    return False\n  if ((params1[\"batch_group_count\"] > 1) !=\n      (params2[\"batch_group_count\"] > 1)):\n    return False\n  return True\n\n\ndef dot_general_equivalent(\n    equation1: core.JaxprEqn,\n    equation2: core.JaxprEqn\n) -> bool:\n  if not (equation1.primitive.name == \"dot_general\" and\n          equation2.primitive.name == \"dot_general\"):\n    raise ValueError(\"This is only applicable to `conv_general_dilated` \"\n                     \"primitive.\")\n  # We ignore precision and preferred_element_type\n  return (equation1.params[\"dimension_numbers\"] ==\n          equation2.params[\"dimension_numbers\"])\n\n\nDEFAULT_SPECIAL_EQUIVALENCE_RULES = immutabledict.immutabledict({\n    \"reshape\": reshape_equivalent,\n    \"broadcast_in_dim\": broadcast_in_dim_equivalent,\n    \"conv_general_dilated\": conv_general_dilated_equivalent,\n    \"dot_general\": dot_general_equivalent,\n})\n\n\nclass GraphMatcherComparator:\n  \"\"\"A class to compare and determine equivalence of abstract Jax equations.\"\"\"\n\n  def __init__(\n      self,\n      commutative_ops_names: Sequence[str] = (\"add\", \"mul\"),\n      special_eqn_equivalence_rules:\n      Mapping[str, EquivalenceFunction] = DEFAULT_SPECIAL_EQUIVALENCE_RULES,\n  ):\n    \"\"\"Initializes the instance.\n\n    Args:\n      commutative_ops_names: A sequence of all Jax primitive names, which are\n        consider commutative ops and the order of their arguments is irrelevant.\n      special_eqn_equivalence_rules: A mapping of a Jax primitive names to a\n        comparison rule, which to be used instead of the default comparator,\n        which looks that the whole dictionaries of extra parameters to the\n        primitives match.\n    \"\"\"\n    self._commutative_ops_names = set(commutative_ops_names)\n    self._special_eqn_equivalence_rules = dict(**special_eqn_equivalence_rules)\n\n  @property\n  def commutative_ops_names(self) -> Set[str]:\n    \"\"\"The set of commutative ops.\"\"\"\n    return self._commutative_ops_names\n\n  @property\n  def special_eqn_equivalence_rules(self) -> Mapping[str, EquivalenceFunction]:\n    \"\"\"The special equivalence rules.\"\"\"\n    return self._special_eqn_equivalence_rules\n\n  def add_commutative_op_name(self, name: str):\n    \"\"\"Adds a name to the set of primitive ops considered to be commutative.\"\"\"\n    if name in self.commutative_ops_names:\n      raise ValueError(f\"Commutative op {name!r} has already been added.\")\n    self._commutative_ops_names.add(name)\n\n  def add_special_equivalence_rule(\n      self,\n      name: str,\n      equivalence_rule: EquivalenceFunction\n  ):\n    \"\"\"Adds the special equivalence rule for ``name`` to the global store.\"\"\"\n    if name in self.special_eqn_equivalence_rules:\n      raise ValueError(\n          f\"Special equation equivalence rule already exists for name: {name}\")\n    self._special_eqn_equivalence_rules[name] = equivalence_rule\n\n  def are_equivalent(\n      self,\n      equation1: core.JaxprEqn,\n      equation2: core.JaxprEqn\n  ) -> bool:\n    \"\"\"Returns whether the two equations are considered equivalent.\"\"\"\n    if equation1.primitive.name != equation2.primitive.name:\n      return False\n    equivalence_rule = self.special_eqn_equivalence_rules.get(\n        equation1.primitive.name)\n    if equivalence_rule is not None:\n      return equivalence_rule(equation1, equation2)\n\n    # Default comparison\n    return equation1.params == equation2.params\n\n\nclass JaxprGraph:\n  \"\"\"A wrapper around Jaxpr as a graph for pattern matching.\n\n  Attributes:\n    name: The name for this Jaxpr graph.\n    jaxpr: The original Jaxpr that is being wrapped.\n    consts: The constants needed for evaluation of the raw Jaxpr.\n    params_vars: A flat list of all of the abstract parameter variables.\n    params_tree: The PyTree structure of the parameter variables.\n    out_tree: The PyTree structure of the outputs of the Jaxpr function.\n    losses_eqns: A tuple of all of the Jaxpr equations corresponding to a loss\n      tag.\n    var_to_creation_op: A mapping of variables to the Jax equation that created\n      it.\n    tag_ctor: This is an optional attribute, that defines if this is used during\n      automatic layer tag registration, how to construct the corresponding layer\n      tag primitive from the subgraph matching this pattern.\n  \"\"\"\n\n  def __init__(\n      self,\n      name: str,\n      jaxpr: core.Jaxpr,\n      consts: Sequence[Any],\n      params_vars: Sequence[core.Var],\n      params_tree: utils.PyTreeDef,\n      out_tree: utils.PyTreeDef,\n      tag_ctor: Optional[TagCtor],\n  ):\n    \"\"\"Initializes the instance.\n\n    Args:\n      name: The name for this Jaxpr graph.\n      jaxpr: The original Jaxpr that is being wrapped.\n      consts: The constants needed for evaluation of the raw Jaxpr.\n      params_vars: A flat list of all of the abstract parameter variables.\n      params_tree: The PyTree structure of the parameter variables.\n      out_tree: The PyTree structure of the outputs of the Jaxpr function.\n      tag_ctor: This is an optional attribute, that defines if this is used\n        during automatic layer tag registration, how to construct the\n        corresponding layer tag primitive from the subgraph matching this\n        pattern.\n    \"\"\"\n    self.name = name\n    self.jaxpr = jaxpr\n    self.params_vars = list(params_vars)\n    self.params_tree = params_tree\n    self.out_tree = out_tree\n    self.consts = list(consts)\n    self.tag_ctor = tag_ctor\n    self.losses_eqns = tuple(\n        eqn for eqn in jaxpr.eqns if isinstance(eqn.primitive, tags.LossTag))\n    self.var_to_creation_op = immutabledict.immutabledict(\n        sum(([(var, eqn) for var in eqn.outvars] for eqn in jaxpr.eqns), []))\n\n  def __repr__(self):\n    return (f\"{self.__class__.__name__}({self.name!r}, \"\n            f\"{self.jaxpr!r}, {self.consts!r}, {self.params_vars!r}, \"\n            f\"{self.params_tree!r}, {self.out_tree!r}, {self.tag_ctor!r})\")\n\n  @property\n  def outvars(self) -> Sequence[core.Atom]:\n    \"\"\"A sequence of all of the output variables of the Jaxpr graph.\"\"\"\n    return self.jaxpr.outvars\n\n  def ancestors_sub_graph(self, eqns: Iterable[core.JaxprEqn]) -> \"JaxprGraph\":\n    \"\"\"Constructs a subgraph of all the ancestors(self-inclusive) of ``eqns``.\"\"\"\n    sub_graph_eqns = []\n    sub_graph_vars = set()\n    for eqn in reversed(self.jaxpr.eqns):\n      if eqn in eqns or any(v in sub_graph_vars for v in eqn.outvars):\n        sub_graph_eqns.append(eqn)\n        sub_graph_vars.update(\n            v for v in eqn.invars if not isinstance(v, core.Literal))\n    outvars, out_tree = jax.tree_flatten(tuple(\n        eqn.outvars for eqn in self.losses_eqns))\n    return JaxprGraph(\n        name=\"sub_\" + self.name,\n        jaxpr=core.Jaxpr(\n            constvars=self.jaxpr.constvars,\n            invars=self.jaxpr.invars,\n            outvars=outvars,\n            eqns=tuple(reversed(sub_graph_eqns))\n        ),\n        consts=self.consts,\n        params_vars=self.params_vars,\n        params_tree=self.params_tree,\n        out_tree=out_tree,\n        tag_ctor=self.tag_ctor\n    )\n\n  def extract_manual_registrations(self) -> Tuple[tags.LayerTagEqn, ...]:\n    \"\"\"Returns all manually registered tags.\"\"\"\n    registered_tags = []\n    for eqn in self.jaxpr.eqns:\n      if isinstance(eqn.primitive, tags.LayerTag):\n        for param in eqn.primitive.split_all_inputs(eqn.invars)[2]:\n          if param not in self.params_vars:\n            raise ValueError(f\"One of the parameters of the manual layer \"\n                             f\"registration equation: {eqn} is not part of the \"\n                             f\"parameters of the global function.\")\n        registered_tags.append(eqn)\n    return tuple(registered_tags)\n\n\ndef make_jax_graph(\n    func: utils.Func,\n    func_args: Sequence[Any],\n    params_index: Union[int, Sequence[int]],\n    graph_name: str,\n    tag_ctor: Optional[TagCtor] = None,\n) -> JaxprGraph:\n  \"\"\"Creates a :class:`~JaxGraph` instance from the provided function and arguments.\"\"\"\n  in_tree = jax.tree_structure(func_args)\n  typed_jaxpr, out_shapes = jax.make_jaxpr(func, return_shape=True)(*func_args)\n  in_vars = jax.tree_unflatten(in_tree, typed_jaxpr.jaxpr.invars)\n  if isinstance(params_index, int):\n    params_vars = in_vars[params_index]\n  else:\n    params_vars = tuple(in_vars[i] for i in params_index)\n  params_vars, params_tree = jax.tree_flatten(params_vars)\n  return JaxprGraph(\n      name=graph_name,\n      jaxpr=typed_jaxpr.jaxpr,\n      consts=typed_jaxpr.literals,\n      params_vars=params_vars,\n      params_tree=params_tree,\n      out_tree=jax.tree_structure(out_shapes),\n      tag_ctor=tag_ctor\n  )\n\n\nclass GraphPattern:\n  \"\"\"A graph pattern used for automatically detecting layers.\"\"\"\n\n  def __init__(\n      self,\n      name: str,\n      tag_primitive: tags.LayerTag,\n      precedence: int,\n      compute_func: PatternComputeFunc,\n      parameters_extractor_func: ParameterExtractorFunc,\n      example_args: utils.FuncArgs,\n      in_values_preprocessor: ValuesProcessor = lambda in_values: in_values,\n  ):\n    \"\"\"Instantiates the graph pattern.\n\n    The graph matcher needs to trace at least once the full function, which\n    means the caller needs to provide it with dummy arguments. The shapes of the\n    arguments do not matter, as the graph matcher ignores their values, however\n    the rank does. Especially if there is some broadcasting happening you should\n    register with every possible broadcast pattern. As a general advice avoid\n    using a shape to be 1, unless you want the pattern to specifically match\n    that, as some operations, like squeeze for example, can have special\n    behaviour then.\n\n    Args:\n      name: The name of the pattern that is being registered to.\n      tag_primitive: The primitive tag to bind.\n      precedence: This specifies what precedence the graph matcher is going to\n        assign to the provided pattern. The graph matcher will go from lowest\n        to highest precedence, randomly breaking ties, when matching. Note that\n        the pattern that matches a parameter with the lowest precedence will get\n        registered and no other will. Specifically useful when there is a\n        pattern for a layer with and without bias, in which case the with bias\n        registration always should go with lower precedence.\n      compute_func: The function that performs the computation.\n      parameters_extractor_func: A function that extracts from the traced Jaxpr\n        any parameters that are passed into the tag.\n      example_args: Example arguments that can be inputted into ``func``.\n      in_values_preprocessor: A function that can optionally modify the in_vals\n        passed to the tag_primitive, from those that are usually the input to\n        the jaxpr.\n    \"\"\"\n    self._name = name\n    self._tag_primitive = tag_primitive\n    self._precedence = precedence\n    self._compute_func = compute_func\n    self._parameters_extractor_func = parameters_extractor_func\n    self._example_args = example_args\n    self._in_values_preprocessor = in_values_preprocessor\n    self._graph = None\n\n  @property\n  def name(self) -> str:\n    \"\"\"Name of this graph pattern.\"\"\"\n    return self._name\n\n  @property\n  def tag_primitive(self) -> tags.LayerTag:\n    \"\"\"The layer tag primitive that this pattern corresponds to.\"\"\"\n    return self._tag_primitive\n\n  @property\n  def graph(self) -> JaxprGraph:\n    \"\"\"The Jaxpr graph representing the computation of this pattern.\"\"\"\n    if self._graph is None:\n      jnp_args = jax.tree_map(jnp.asarray, self._example_args)\n      self._graph = make_jax_graph(\n          broadcast_merger(self._compute_func), jnp_args, 1, self._name)\n    return self._graph\n\n  def tag_ctor(\n      self,\n      eqns: Sequence[core.JaxprEqn],\n      values_map: Mapping[core.Var, chex.Array]\n  ) -> chex.Array:\n    \"\"\"Registers the layer tag for this graph pattern.\n\n    Args:\n      eqns: The equations in the function, where this pattern is inserted.\n      values_map: A mapping between variables of the pattern and corresponding\n        concrete Jax arrays.\n    Returns:\n      The output value of the layer tag, after its registration.\n    \"\"\"\n    primitive_params = self._parameters_extractor_func(eqns)\n    in_values = [values_map[v] for v in self.graph.jaxpr.invars]\n    out_values = [values_map[v] for v in self.graph.jaxpr.outvars]\n    in_values = self._in_values_preprocessor(in_values)\n    return self.tag_primitive.bind(\n        out_values[0], *in_values, **primitive_params)\n\n\ndef match_equations(\n    graph: JaxprGraph,\n    current_variables_map: Mapping[core.Var, core.Var],\n    reversed_eqns_to_match: Sequence[core.JaxprEqn],\n    input_vars: Sequence[core.Var],\n    param_variables: Sequence[core.Var],\n    graph_matcher_rules: GraphMatcherComparator,\n) -> Optional[Dict[core.Var, core.Var]]:\n  \"\"\"Tries to continue matching the remaining equations to the Jaxpr graph.\n\n  Args:\n    graph: The :class:`~JaxprGraph` on which we are searching for matching\n      equations.\n    current_variables_map: A mapping from a pattern variables to graph\n      variables, which describes what is the current partial mapping between\n      the pattern and the graph.\n    reversed_eqns_to_match: The remaining equations of the pattern that have\n      not yet been matched to the graph.\n    input_vars: The input variables of the pattern.\n    param_variables: The parameter variables of the pattern.\n    graph_matcher_rules: A :class:`~GraphMatcherRules` instance, which is used\n      for determining equivalence of individual Jax primitives.\n\n  Returns:\n    ``None`` if it is not possible to finish matching the remaining equations\n    in the graph. Otherwise returns the full match of the pattern onto the\n    graph, in terms of a variable to variable mapping.\n  \"\"\"\n  # Copy the variables mapping\n  current_variables_map = dict(current_variables_map)\n  def add_vars_if_possible(\n      eqn_vars: Sequence[core.Var],\n      graph_vars: Sequence[core.Var]\n  ) -> bool:\n    \"\"\"Tries to update the current variables map.\n\n    If at least one of the pattern variables is a parameter, but the\n    corresponding graph variable is not or vise-versa, the method does not\n    update the current variables map and returns ``False``. Similarly if at\n    least one of the graph variables is a :class:`~jax.core.Literal` (meaning a\n    constant, independent of the function inputs) and the corresponding\n    pattern variable is not an input to the pattern, it returns ``False``. In\n    all other cases it updates the map and returns ``True``.\n\n    Args:\n      eqn_vars: The variables from a single equation of the pattern.\n      graph_vars: The variables from a corresponding equation of the graph.\n\n    Returns:\n      A boolean describing whether the method succeeded to update the\n      current variables map.\n    \"\"\"\n    for var1, var2 in zip(eqn_vars, graph_vars):\n      if (var1 in param_variables and var2 not in graph.params_vars or\n          var1 not in param_variables and var2 in graph.params_vars or\n          (isinstance(var2, core.Literal) and var1 not in input_vars)):\n        return False\n    current_variables_map.update(zip(eqn_vars, graph_vars))\n    return True\n\n  # Loop over all remaining equations to match\n  for i, eqn in enumerate(reversed_eqns_to_match):\n    assert all(v in current_variables_map for v in eqn.outvars)\n\n    # Retrieve the graph equation, whose output currently corresponds to the\n    # first output variable of the pattern equation.\n    first_output_var = current_variables_map[eqn.outvars[0]]\n    graph_eqn = graph.var_to_creation_op.get(first_output_var)\n    if graph_eqn is None:\n      assert first_output_var in graph.jaxpr.invars\n      # Clearly the pattern equation is not an input or parameter\n      return None\n\n    assert isinstance(graph_eqn, jax.core.JaxprEqn)\n    # For equations with more than one output, make sure all output variables\n    # in the graph are generated from the same graph equation.\n    for v in eqn.outvars[1:]:\n      if graph_eqn != graph.var_to_creation_op.get(current_variables_map[v]):\n        return None\n    # Check that the graph and pattern equation are equivalent\n    if not graph_matcher_rules.are_equivalent(graph_eqn, eqn):\n      return None\n    # Sanity check\n    assert len(eqn.invars) == len(graph_eqn.invars)\n\n    if eqn.primitive.name in graph_matcher_rules.commutative_ops_names:\n      # For commutative ops we search through all possible pair alignments.\n      # This requires a recursive solution, on top of the iterative one.\n      results = []\n      for permutation in itertools.permutations(range(len(eqn.invars))):\n        pattern_vars = [eqn.invars[j] for j in permutation]\n        # Check if this ordering is feasible\n        if not add_vars_if_possible(pattern_vars, graph_eqn.invars):\n          continue\n        # Recursively continue by trying to match the remaining equations.\n        candidate_map = match_equations(\n            graph=graph,\n            current_variables_map=current_variables_map,\n            reversed_eqns_to_match=reversed_eqns_to_match[i + 1:],\n            input_vars=input_vars,\n            param_variables=param_variables,\n            graph_matcher_rules=graph_matcher_rules,\n        )\n        if candidate_map is not None:\n          # Sanity check\n          assert all(candidate_map[p] in graph.params_vars\n                     for p in param_variables)\n          results.append(candidate_map)\n      # Return appropriately\n      if len(results) > 1:\n        raise ValueError(\"Found multiple branch matches in pattern at \"\n                         f\"associative op {eqn.primitive.name}.\")\n      elif len(results) == 1:\n        return results[0]\n      else:\n        return None\n    elif not add_vars_if_possible(eqn.invars, graph_eqn.invars):\n      # In the case where we can't update the current variables map directly\n      # return\n      return None\n  return current_variables_map\n\n\ndef match_pattern(\n    graph: JaxprGraph,\n    root_eqn: core.JaxprEqn,\n    pattern: \"JaxprGraph\",\n    graph_matcher_rules: GraphMatcherComparator,\n) -> Optional[Dict[core.Var, core.Var]]:\n  \"\"\"Tries to match the ``pattern`` in the Jaxpr graph from the ``root_eqn``.\n\n  Args:\n    graph: The :class:`~JaxprGraph` on which we are searching for matching\n      equations.\n    root_eqn: The equation in the graph, which is assumed to match the output\n      equation of the pattern.\n    pattern: The pattern, which we are trying to match.\n    graph_matcher_rules: A :class:`~GraphMatcherRules` instance, which is used\n      for determining equivalence of individual Jax primitives.\n\n  Returns:\n    The variable to variable mapping between the pattern and graph variable,\n    if the pattern can be matched to the root equation, otherwise ``None``.\n  \"\"\"\n  # Check the number of output variables match.\n  if len(pattern.jaxpr.outvars) != len(root_eqn.outvars):\n    return None\n  # Set the current variables mapping to the output variables and the try to\n  # check the match from there.\n  return match_equations(\n      graph=graph,\n      current_variables_map=dict(zip(pattern.jaxpr.outvars,\n                                     root_eqn.outvars)),\n      reversed_eqns_to_match=tuple(reversed(pattern.jaxpr.eqns)),\n      input_vars=pattern.jaxpr.invars,\n      param_variables=pattern.params_vars,\n      graph_matcher_rules=graph_matcher_rules,\n  )\n\n\ndef find_layer_tags_and_patterns(\n    graph: JaxprGraph,\n    patterns_to_match: Sequence[GraphPattern],\n    graph_matcher_rules: GraphMatcherComparator,\n) -> Tuple[Tuple[tags.LayerTagEqn, ...],\n           Dict[core.Var,\n                Tuple[GraphPattern,\n                      Dict[core.Var, core.Var],\n                      Tuple[core.JaxprEqn, ...]]]]:\n  \"\"\"Tries to automatically match ``patterns_to_match`` in the Jaxpr graph.\n\n  The method returns a pair of ``(manual_registrations, matches)``, where\n  ``manual_registrations`` is a tuple of all layer tags that are already\n  present in the graph and ``matches`` contains all newly discovered matches\n  of any of the patterns. Each entry has as a key the variable of the graph\n  corresponding to the output of the pattern, while each value is a triple\n  ``(pattern, match_map, eqns)`` where ``pattern`` is the :class:`~JaxprGraph`\n  of the pattern that has been matched, ``match_map`` is mapping the pattern\n  variables to the corresponding graph variables and ``eqns`` is the sequence\n  of all graph equations corresponding to the pattern equations.\n\n  Args:\n    graph: The :class:`~JaxprGraph` on which we are searching for matching\n      equations.\n    patterns_to_match: A sequence of different patterns that we want to find\n    matches for in the graph.\n    graph_matcher_rules: A :class:`~GraphMatcherRules` instance, which is used\n      for determining equivalence of individual Jax primitives.\n\n  Returns:\n    The pair ``(manual_registrations, matches)``.\n  \"\"\"\n  manual_registrations = graph.extract_manual_registrations()\n  # This keeps track to any equations that are already in a pattern and hence\n  # should not be part of any other.\n  registered_equations = []\n  # First add any manual registrations to this.\n  for eqn in manual_registrations:\n    assert isinstance(eqn.primitive, tags.LayerTag)\n    for root_var in eqn.primitive.split_all_inputs(eqn.invars)[0]:\n      assert root_var in graph.var_to_creation_op\n      registered_equations.append(graph.var_to_creation_op[root_var])\n\n  matches = {}\n  # Loop through all equations in reverse and for each one check every pattern\n  for eqn in reversed(graph.jaxpr.eqns):\n    if eqn in registered_equations:\n      continue\n    for pattern in patterns_to_match:\n      match_map = match_pattern(graph, eqn, pattern.graph, graph_matcher_rules)\n      if match_map is not None:\n        assert len(pattern.graph.outvars) == 1\n        output_variable = match_map[pattern.graph.outvars[0]]\n        # Extract all equations from the pattern and add them to the already\n        # registered equations.\n        match_eqns = []\n        for k, v in match_map.items():\n          if k not in pattern.graph.jaxpr.invars:\n            creation_op = graph.var_to_creation_op[v]\n            assert isinstance(creation_op, core.JaxprEqn)\n            match_eqns.append(creation_op)\n            registered_equations.append(match_eqns[-1])\n        # Add the match\n        matches[output_variable] = (pattern, match_map, tuple(match_eqns))\n        break\n\n  return manual_registrations, matches\n\n\ndef read_env(\n    env: Mapping[core.Var, chex.Array],\n    var: Union[core.Literal, core.Var, Sequence[core.Var]],\n) -> Union[float, chex.Array, Sequence[chex.Array]]:\n  \"\"\"Reads from the variable-to-array environment during tracing.\"\"\"\n  if isinstance(var, (list, tuple)):\n    return jax.tree_map(lambda x: read_env(env, x), var)\n  elif isinstance(var, core.Literal):\n    # Literals are values baked into the Jaxpr\n    return var.val\n  elif isinstance(var, core.Var):\n    return env[var]\n  else:\n    raise NotImplementedError()\n\n\ndef write_env(\n    env: MutableMapping[core.Var, chex.Array],\n    var: Union[core.Var, List[core.Var]],\n    val: Union[chex.Array, List[chex.Array]],\n) -> None:\n  \"\"\"Writes to the variable-to-array environment during tracing.\"\"\"\n  if isinstance(var, tuple):\n    raise NotImplementedError()\n  if isinstance(var, list):\n    if not isinstance(val, list):\n      val = [val]\n    return jax.tree_map(lambda x, y: write_env(env, x, y), var, val)\n  elif isinstance(var, (core.Literal, core.Var)):\n    env[var] = val\n  else:\n    raise NotImplementedError()\n\n\ndef clean_jaxpr_eqns(\n    jaxpr: core.Jaxpr,\n    preserve_tags: bool = True\n) -> Iterator[core.JaxprEqn]:\n  \"\"\"Runs dead code elimination on a Jaxpr, retaining loss and layer tags.\"\"\"\n  eqns = []\n  dependants = set(jaxpr.outvars)\n  for eqn in reversed(jaxpr.eqns):\n    check = False\n    for v in eqn.outvars:\n      if v in dependants:\n        dependants.remove(v)\n        check = True\n    if isinstance(eqn.primitive, (tags.LossTag, tags.LayerTag)):\n      check = check or preserve_tags\n    if check:\n      eqns.append(eqn)\n      new_dependants = set(v for v in eqn.invars\n                           if not isinstance(v, core.Literal))\n      dependants = dependants.union(new_dependants)\n  # Dependants should only be invars\n  dependants = dependants - set(jaxpr.invars + jaxpr.constvars)\n\n  if dependants:\n    raise ValueError(\"Something went wrong with the dead code elimination.\")\n  return reversed(eqns)\n\n\ndef broadcast_merger(f: utils.Func) -> utils.Func:\n  \"\"\"Transforms ``f`` by merging any consecutive broadcasts in its Jaxpr.\"\"\"\n\n  def read_with_delayed_evaluation(env, var):\n    if isinstance(var, (list, tuple)):\n      return jax.tree_map(lambda x: read_with_delayed_evaluation(env, x), var)\n    elif isinstance(var, core.Literal):\n      # Literals are values baked into the Jaxpr\n      return var.val\n    elif isinstance(var, core.Var):\n      r = env[var]\n      if isinstance(r, (jnp.ndarray, np.ndarray)):\n        return r\n      elif isinstance(r, Callable):\n        y = r()\n        if isinstance(y, list):\n          assert len(y) == 1\n          y = y[0]\n        assert isinstance(y, jnp.ndarray)\n        env[var] = y\n        return y\n    raise NotImplementedError()\n\n  @functools.wraps(f)\n  def merged_func(*func_args: Any) -> Any:\n    typed_jaxpr, out_avals = jax.make_jaxpr(f, return_shape=True)(*func_args)\n    out_tree = jax.tree_structure(out_avals)\n    jaxpr, consts = typed_jaxpr.jaxpr, typed_jaxpr.literals\n\n    # Mapping from variable -> value\n    env = {}\n    read = functools.partial(read_with_delayed_evaluation, env)\n    write = functools.partial(write_env, env)\n\n    # Bind args and consts to environment\n    flat_args = jax.tree_flatten(func_args)[0]\n    write(jaxpr.invars, flat_args)\n    write(jaxpr.constvars, consts)\n\n    # Bind args and consts to environment\n    write(jaxpr.invars, flat_args)\n    write(jaxpr.constvars, consts)\n\n    # Loop through equations and evaluate primitives using `bind`\n    broadcasts_outputs = {}\n    for eqn in clean_jaxpr_eqns(jaxpr):\n      # We ignore broadcasting of constants\n      if (eqn.primitive.name == \"broadcast_in_dim\" and\n          not all(isinstance(v, core.Literal) for v in eqn.invars)):\n        if eqn.invars[0] in broadcasts_outputs:\n          x, dims = broadcasts_outputs[eqn.invars[0]]\n          kept_dims = eqn.params[\"broadcast_dimensions\"]\n          kept_dims = [kept_dims[d] for d in dims]\n          # In order not to compute any un-needed broadcasting we instead put\n          # in a function for delayed evaluation.\n          write(eqn.outvars, [functools.partial(\n              lax.broadcast_in_dim, x, eqn.params[\"shape\"], kept_dims)])\n          broadcasts_outputs[eqn.outvars[0]] = (x, kept_dims)\n        else:\n          input_values = read(eqn.invars)\n          # In order not to compute any un-needed broadcasting we instead put\n          # in a function for delayed evaluation.\n          write(eqn.outvars, [functools.partial(\n              eval_jaxpr_eqn, eqn, input_values)])\n          broadcasts_outputs[eqn.outvars[0]] = (\n              (input_values[0], eqn.params[\"broadcast_dimensions\"]))\n      else:\n        write(eqn.outvars, eval_jaxpr_eqn(eqn, read(eqn.invars)))\n    return jax.tree_unflatten(out_tree, read(jaxpr.outvars))\n\n  return merged_func\n\n\n#  _____            _     _             _   _\n# |  __ \\          (_)   | |           | | (_)\n# | |__) |___  __ _ _ ___| |_ _ __ __ _| |_ _  ___  _ __  ___\n# |  _  // _ \\/ _` | / __| __| '__/ _` | __| |/ _ \\| '_ \\/ __|\n# | | \\ \\  __/ (_| | \\__ \\ |_| | | (_| | |_| | (_) | | | \\__ \\\n# |_|  \\_\\___|\\__, |_|___/\\__|_|  \\__,_|\\__|_|\\___/|_| |_|___/\n#              __/ |\n#             |___/\n\n\ndef _dense(x: chex.Array, params: Sequence[chex.Array]) -> chex.Array:\n  \"\"\"Example of a dense layer function.\"\"\"\n  w, *opt_b = params\n  y = jnp.matmul(x, w)\n  return y if not opt_b else y + opt_b[0]\n\n\ndef _dense_parameter_extractor(\n    eqns: Sequence[core.JaxprEqn],\n) -> Mapping[str, Any]:\n  \"\"\"Extracts all parameters from the conv_general_dilated operator.\"\"\"\n  for eqn in eqns:\n    if eqn.primitive.name == \"dot_general\":\n      return dict(**eqn.params)\n  assert False\n\n\ndense_with_bias_pattern = GraphPattern(\n    name=\"dense_with_bias\",\n    tag_primitive=tags.dense,\n    precedence=0,\n    compute_func=_dense,\n    parameters_extractor_func=_dense_parameter_extractor,\n    example_args=[np.zeros([11, 13]), [np.zeros([13, 7]), np.zeros([7])]],\n)\n\ndense_no_bias_pattern = GraphPattern(\n    name=\"dense_no_bias\",\n    tag_primitive=tags.dense,\n    precedence=1,\n    compute_func=_dense,\n    parameters_extractor_func=_dense_parameter_extractor,\n    example_args=[np.zeros([11, 13]), [np.zeros([13, 7])]],\n)\n\n\ndef _conv2d(x: chex.Array, params: Sequence[chex.Array]) -> chex.Array:\n  \"\"\"Example of a conv2d layer function.\"\"\"\n  w = params[0]\n  y = lax.conv_general_dilated(\n      x,\n      w,\n      window_strides=(2, 2),\n      padding=\"SAME\",\n      dimension_numbers=(\"NHWC\", \"HWIO\", \"NHWC\"))\n  if len(params) == 1:\n    # No bias\n    return y\n  # Add bias\n  return y + params[1][None, None, None]\n\n\ndef _conv2d_parameter_extractor(\n    eqns: Sequence[core.JaxprEqn],\n) -> Mapping[str, Any]:\n  \"\"\"Extracts all parameters from the conv_general_dilated operator.\"\"\"\n  for eqn in eqns:\n    if eqn.primitive.name == \"conv_general_dilated\":\n      return dict(**eqn.params)\n  assert False\n\n\nconv2d_with_bias_pattern = GraphPattern(\n    name=\"conv2d_with_bias\",\n    tag_primitive=tags.conv2d,\n    precedence=0,\n    compute_func=_conv2d,\n    parameters_extractor_func=_conv2d_parameter_extractor,\n    example_args=[np.zeros([2, 8, 8, 5]),\n                  [np.zeros([3, 3, 5, 4]), np.zeros([4])]],\n)\n\nconv2d_no_bias_pattern = GraphPattern(\n    name=\"conv2d_no_bias\",\n    tag_primitive=tags.conv2d,\n    precedence=1,\n    compute_func=_conv2d,\n    parameters_extractor_func=_conv2d_parameter_extractor,\n    example_args=[np.zeros([2, 8, 8, 5]), [np.zeros([3, 3, 5, 4])]],\n)\n\n\ndef _scale_and_shift(\n    x: chex.Array,\n    params: Sequence[chex.Array],\n    has_scale: bool,\n    has_shift: bool,\n) -> chex.Array:\n  \"\"\"Example of a scale and shift function.\"\"\"\n  if has_scale and has_shift:\n    scale, shift = params\n    return x * scale + shift\n  elif has_scale:\n    assert len(params) == 1\n    return x * params[0]\n  elif has_shift:\n    assert len(params) == 1\n    return x + params[0]\n  else:\n    raise ValueError(\"You must have either `has_scale` or `has_shift` set \"\n                     \"to True.\")\n\n\nscale_and_shift_with_broadcast_pattern = GraphPattern(\n    name=\"scale_and_shift_with_broadcast\",\n    tag_primitive=tags.scale_and_shift,\n    precedence=0,\n    compute_func=functools.partial(_scale_and_shift,\n                                   has_scale=True, has_shift=True),\n    parameters_extractor_func=\n    lambda jaxpr: dict(has_scale=True, has_shift=True),\n    example_args=[np.zeros([2, 13]), [np.zeros([13]), np.zeros([13])]],\n)\n\n\nscale_and_shift_no_broadcast_pattern = GraphPattern(\n    name=\"scale_and_shift_no_broadcast\",\n    tag_primitive=tags.scale_and_shift,\n    precedence=0,\n    compute_func=functools.partial(_scale_and_shift,\n                                   has_scale=True, has_shift=True),\n    parameters_extractor_func=\n    lambda jaxpr: dict(has_scale=True, has_shift=True),\n    example_args=[np.zeros([13]), [np.zeros([13]), np.zeros([13])]],\n)\n\nscale_only_pattern = GraphPattern(\n    name=\"scale_only\",\n    tag_primitive=tags.scale_and_shift,\n    precedence=1,\n    compute_func=functools.partial(_scale_and_shift,\n                                   has_scale=True, has_shift=False),\n    parameters_extractor_func=\n    lambda jaxpr: dict(has_scale=True, has_shift=False),\n    example_args=[np.zeros([2, 13]), [np.zeros([13])]],\n)\n\nshift_only_pattern = GraphPattern(\n    name=\"shift_only\",\n    tag_primitive=tags.scale_and_shift,\n    precedence=2,\n    compute_func=functools.partial(_scale_and_shift,\n                                   has_scale=False, has_shift=True),\n    parameters_extractor_func=\n    lambda jaxpr: dict(has_scale=False, has_shift=True),\n    example_args=[np.zeros([2, 13]), [np.zeros([13])]],\n)\n\n\ndef _normalization_haiku(\n    inputs: Sequence[chex.Array],\n    params: Sequence[chex.Array],\n    has_scale: bool,\n    has_shift: bool,\n) -> chex.Array:\n  \"\"\"Example of normalization as is defined in Haiku.\"\"\"\n  if len(params) not in (1, 2):\n    raise ValueError(\"The inputs to the `normalization_haiku` computation must \"\n                     f\"have either 1 or 2 parameters, but got {len(params)}.\")\n  [inputs, rsqrt_var] = inputs\n  inv = params[0] * rsqrt_var if has_scale else rsqrt_var\n  outputs = inputs * inv\n  return outputs + params[-1] if has_shift else outputs\n\n\ndef _normalization_haiku_preprocessor(\n    in_values: Sequence[chex.Array],\n) -> Tuple[chex.Array, ...]:\n  \"\"\"Preprocesses the inputs to a Haiku normalization layer.\n\n  The standard ``scale_and_shift`` represents the following canonical\n  computation:\n    y = x * scale + shift\n  Normalization performs a similar computation, where the `normalized_x` below\n  represents the standard ``x`` input to ``scale_and_shift``:\n    normalized_x = (x - m) / sqrt(var(x) + eps)\n    y = normalized_x * scale + shift\n  Each ``layer_tag`` represents a specific computation and hence it expects its\n  inputs to be in canonical form. For ``scale_and_shift`` the input must be\n  the array that gets multiplied by the ``scale`` before the ``shift`` addition\n  as shown above. However, Haiku performs normalization slightly out of order:\n    y = [(x - m) * scale] / sqrt(var(x) + eps) + shift\n  As a result, in the Jax computation graph the canonical input (normalized_x)\n  does not exist, because of the ordering of the multiplication and division.\n  To remedy this we have to add this additional function, which to be able to\n  compute from the variables in the Haiku normalization computation, the\n  canonical input to ``scale_and_shift`` tag.\n\n  Args:\n    in_values: The standard Haiku normalization inputs.\n\n  Returns:\n    The canonical input to ``scale_and_shift`` and the parameters.\n  \"\"\"\n  [inputs, rsqrt_var, *params] = in_values\n  normalized_inputs = inputs * rsqrt_var\n  return (normalized_inputs,) + tuple(params)\n\n\nnormalization_haiku_with_broadcast_pattern = GraphPattern(\n    name=\"normalization_haiku_with_broadcast\",\n    tag_primitive=tags.scale_and_shift,\n    precedence=0,\n    compute_func=functools.partial(_normalization_haiku,\n                                   has_scale=True, has_shift=True),\n    parameters_extractor_func=\n    lambda jaxpr: dict(has_scale=True, has_shift=True),\n    example_args=[[np.zeros([2, 13]), np.zeros([2, 13])],\n                  [np.zeros([13]), np.zeros([13])]],\n    in_values_preprocessor=_normalization_haiku_preprocessor\n)\n\n\nnormalization_haiku_no_broadcast_pattern = GraphPattern(\n    name=\"normalization_haiku_no_broadcast\",\n    tag_primitive=tags.scale_and_shift,\n    precedence=0,\n    compute_func=functools.partial(_normalization_haiku,\n                                   has_scale=True, has_shift=True),\n    parameters_extractor_func=\n    lambda jaxpr: dict(has_scale=True, has_shift=True),\n    example_args=[[np.zeros([13]), np.zeros([13])],\n                  [np.zeros([13]), np.zeros([13])]],\n    in_values_preprocessor=_normalization_haiku_preprocessor\n)\n\n\nnormalization_haiku_scale_only_pattern = GraphPattern(\n    name=\"normalization_haiku_scale_only\",\n    tag_primitive=tags.scale_and_shift,\n    precedence=1,\n    compute_func=functools.partial(_normalization_haiku,\n                                   has_scale=True, has_shift=False),\n    parameters_extractor_func=\n    lambda jaxpr: dict(has_scale=True, has_shift=False),\n    example_args=[[np.zeros([2, 13]), np.zeros([2, 13])], [np.zeros([13])]],\n)\n\n\nDEFAULT_GRAPH_PATTERNS = (\n    dense_with_bias_pattern,\n    dense_no_bias_pattern,\n    conv2d_with_bias_pattern,\n    conv2d_no_bias_pattern,\n    scale_and_shift_with_broadcast_pattern,\n    scale_and_shift_no_broadcast_pattern,\n    normalization_haiku_with_broadcast_pattern,\n    normalization_haiku_no_broadcast_pattern,\n    scale_only_pattern,\n    normalization_haiku_scale_only_pattern,\n    shift_only_pattern,\n)\n\n\ndef auto_register_tags(\n    func: utils.Func,\n    func_args: utils.FuncArgs,\n    params_index: int = 0,\n    register_only_generic: bool = False,\n    compute_only_loss_tags: bool = True,\n    patterns_to_skip: Sequence[str] = (),\n    allow_multiple_registrations: bool = False,\n    graph_matcher_rules: GraphMatcherComparator = GraphMatcherComparator(),\n    graph_patterns: Sequence[GraphPattern] = DEFAULT_GRAPH_PATTERNS,\n) -> utils.Func:\n  \"\"\"Transforms the function by automatically registering layer tags.\n\n  Args:\n    func: The original function to transform.\n    func_args: Example arguments to ``func`` which to be used for tracing it.\n    params_index: Specifies, which inputs to the function are to be considered\n      a parameter variable. Specifically - ``inputs[params_index]``.\n    register_only_generic: If ``True`` registers all parameters not already in a\n      layer tag with a generic tag, effectively ignoring ``graph_patterns``.\n    compute_only_loss_tags: If set to ``True`` (default) the resulting function\n      will only compute the loss tags in ``func``, not its full computation and\n      actual output.\n    patterns_to_skip: The names of any patterns from the provided list, which to\n      be skipped/not used during the pattern matching.\n    allow_multiple_registrations: Whether to raise an error if a parameter is\n      registered with more than one layer tag.\n    graph_matcher_rules: A :class:`~GraphMatcherRules` instance, which is used\n      for determining equivalence of individual Jax primitives.\n    graph_patterns: A sequence of :class:`~GraphPattern` objects, which contain\n      all patterns to use, in order of precedence, which to try to find in the\n      graph before registering a parameter with a generic layer tag.\n  Returns:\n    A transformed function as described above.\n  \"\"\"\n  graph = make_jax_graph(\n      func=broadcast_merger(func),\n      func_args=func_args,\n      params_index=params_index,\n      graph_name=\"main\",\n  )\n\n  # Extract the sub-graph that leads to losses\n  sub_graph = graph.ancestors_sub_graph(graph.losses_eqns)\n  patterns = () if register_only_generic else  tuple(\n      pattern for pattern in graph_patterns\n      if pattern.name not in patterns_to_skip)\n  manual, matches = find_layer_tags_and_patterns(\n      sub_graph, patterns, graph_matcher_rules)\n\n  tagged_params = {}\n  pattern_counters = {}\n  # Manual registrations\n  for manual_eqn in manual:\n    assert isinstance(manual_eqn.primitive, tags.LayerTag)\n    n = pattern_counters.get(manual_eqn.primitive.name, 0)\n    pattern_counters[manual_eqn.primitive.name] = n + 1\n    for p in manual_eqn.primitive.split_all_inputs(manual_eqn.invars)[2]:\n      assert p in sub_graph.params_vars\n      tag_str = f\"Manual[{manual_eqn.primitive.name}_{n}]\"\n      if p in tagged_params:\n        if not allow_multiple_registrations:\n          raise ValueError(f\"Parameter {p} has been registered manually more \"\n                           f\"than once - {tagged_params[p]} and {tag_str}, but \"\n                           f\"`allow_multiple_registrations=False`.\")\n        tag_str = f\"{tagged_params[p]}|{tag_str}\"\n      tagged_params[p] = tag_str\n  # Automatically detect registrations\n  for pattern, variables_map, _ in matches.values():\n    n = pattern_counters.get(pattern.name, 0)\n    pattern_counters[pattern.name] = n + 1\n    for pattern_p in pattern.graph.params_vars:\n      p = variables_map[pattern_p]\n      assert p in sub_graph.params_vars\n      tag_str = f\"Auto[{pattern.name}_{n}]\"\n      if p in tagged_params:\n        if not allow_multiple_registrations:\n          raise ValueError(f\"Parameter {p} has been matched a second time - \"\n                           f\"{tagged_params[p]} and {tag_str}, but \"\n                           f\"`allow_multiple_registrations=False`.\")\n        tag_str = f\"{tagged_params[p]}|{tag_str}\"\n      tagged_params[p] = tag_str\n\n  params_labels = [tagged_params.get(p, \"Orphan\") for p in graph.params_vars]\n  logging.info(\"=\" * 50)\n  logging.info(\"Graph parameter registrations:\")\n  logging.info(pprint.pformat(\n      jax.tree_unflatten(graph.params_tree, params_labels)))\n  logging.info(\"=\" * 50)\n\n  # Construct a function with all of the extra tag registrations\n  @functools.wraps(func)\n  def wrapped_auto_registered(*args: Any) -> Any:\n    flat_args, _ = jax.tree_flatten(args)\n    # Mapping from variable -> value\n    env = {}\n\n    read = functools.partial(read_env, env)\n    write = functools.partial(write_env, env)\n\n    def tag(var):\n      match = matches.get(var)\n      if match is not None:\n        pattern_, variables_map_, match_eqns_ = match\n        values_map = {k: read(variables_map_[k]) for k in variables_map_}\n        val = pattern_.tag_ctor(match_eqns_, values_map)\n        env[var] = val\n\n    # Bind args and consts to environment\n    write(graph.jaxpr.invars, flat_args)\n    write(graph.jaxpr.constvars, graph.consts)\n\n    # Register any orphan parameters as generic\n    for param in graph.params_vars:\n      if param not in tagged_params:\n        write(param, tags.register_generic(read(param)))\n\n    # Set the correct output variables\n    if compute_only_loss_tags:\n      output_vars = []\n      for eqn in graph.losses_eqns:\n        # Do not include any dropped variables as they are always mapped to\n        # the same value.\n        output_vars.append(\n            [v for v in eqn.outvars if not isinstance(v, jax.core.DropVar)])\n      output_vars, out_tree = jax.tree_flatten(output_vars)\n    else:\n      output_vars = graph.jaxpr.outvars\n      out_tree = graph.out_tree\n\n    # Loop through equations and evaluate primitives using `bind`\n    losses_evaluated = 0\n    for eqn in graph.jaxpr.eqns:\n      out = eqn.outvars if eqn.primitive.multiple_results else eqn.outvars[0]\n      write(out, eval_jaxpr_eqn(eqn, read(eqn.invars)))\n      jax_util.safe_map(tag, eqn.outvars)\n\n      # If we want to output only tagged losses\n      if isinstance(eqn.primitive, tags.LossTag):\n        losses_evaluated += 1\n      if compute_only_loss_tags and len(graph.losses_eqns) == losses_evaluated:\n        break\n\n    outputs = read(output_vars)\n    return jax.tree_unflatten(out_tree, outputs)\n  return wrapped_auto_registered\n", "meta": {"hexsha": "96bc6bd7464e0181aefe6fb64e3402e028dae20e", "size": 46112, "ext": "py", "lang": "Python", "max_stars_repo_path": "kfac_jax/_src/tag_graph_matcher.py", "max_stars_repo_name": "deepmind/kfac_jax", "max_stars_repo_head_hexsha": "bb761e2b05c317996e4aac3cf2092a1602d5632d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2022-03-31T10:46:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T19:45:49.000Z", "max_issues_repo_path": "kfac_jax/_src/tag_graph_matcher.py", "max_issues_repo_name": "deepmind/kfac_jax", "max_issues_repo_head_hexsha": "bb761e2b05c317996e4aac3cf2092a1602d5632d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kfac_jax/_src/tag_graph_matcher.py", "max_forks_repo_name": "deepmind/kfac_jax", "max_forks_repo_head_hexsha": "bb761e2b05c317996e4aac3cf2092a1602d5632d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4587155963, "max_line_length": 137, "alphanum_fraction": 0.695805864, "include": true, "reason": "import numpy,import jax,from jax", "num_tokens": 11173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.17885224354419688}}
{"text": "\"\"\"\nImplements ZOO (Zero-Order Optimization) Attack.\n\nThis code is based on the L2-attack from the original implementation of the attack:\nhttps://github.com/huanzhang12/ZOO-Attack/blob/master/l2_attack_black.py\n\nUsage:\n    >>> import json\n    >>> from code_soup.ch5.models.zoo_attack import ZOOAttack\n    >>> config = json.load(open('./code-soup/ch5/models/configs/zoo_attack.json'))\n    >>> attack = ZOOAttack(model, config, input_image_shape=[28, 28, 3], device = 'cpu')\n    >>> adv_img, const = attack.attack(orig_img, target)\n\n\"\"\"\nfrom typing import Dict, List\n\nimport cv2\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom PIL import Image\n\n\nclass ZooAttack:\n    \"\"\"\n    Implements the ZooAttack class.\n    \"\"\"\n\n    def __init__(\n        self,\n        model: torch.nn.Module,\n        config: Dict,\n        input_image_shape: List[int],\n        device: str,\n    ):\n        \"\"\"Initializes the ZooAttack class.\n\n        Args:\n            model (torch.nn.Module): A PyTorch model.\n            config (Dict): A dictionary containing the configuration for the attack.\n            input_image_shape (List[int]): A tuple of ints containing the shape of the input image.\n            device (str): The device to perform the attack on.\n\n        Raises:\n            NotImplementedError: If `use_tanh` is `False` and `use_resize` is `True`.\n        \"\"\"\n\n        assert len(input_image_shape) == 3, \"`input_image_shape` must be of length 3\"\n\n        self.config = config\n\n        if self.config[\"use_tanh\"] is False and self.config[\"use_resize\"] is True:\n            # NOTE: self.up and self.down need to be updated dynamically to match the modifier shape.\n            # Original Implementation is possibly flawed in this aspect.\n            raise NotImplementedError(\n                \"Current implementation does not support `use_tanh` as `False` and `use_resize` as `True` at the same time.\"\n            )\n\n        if self.config[\"early_stop_iters\"] == 0:\n            self.config[\"early_stop_iters\"] = self.config[\"max_iterations\"] // 10\n\n        self.device = device\n        self.input_image_shape = input_image_shape\n\n        # Put model in eval mode\n        self.model = model.to(device)\n        self.model.eval()\n\n        # DUMMIES - Values will be reset during attack\n        var_size = np.prod(input_image_shape)  # width * height * num_channels\n        self.var_list = np.array(range(0, var_size), dtype=np.int32)\n\n        # Initialize Adam optimizer values\n        self.mt_arr = np.zeros(var_size, dtype=np.float32)\n        self.vt_arr = np.zeros(var_size, dtype=np.float32)\n        self.adam_epochs = np.ones(var_size, dtype=np.int64)\n\n        # Sampling Probabilities\n        self.sample_prob = np.ones(var_size, dtype=np.float32) / var_size\n\n    def get_perturbed_image(self, orig_img: torch.tensor, modifier: np.ndarray):\n        \"\"\"Calculates the perturbed image given `orig_img` and `modifier`.\n\n        Args:\n            orig_img (torch.tensor): The original image with a batch dimension. Expected batch size is 1.\n                Using any other batch size may lead to unexpected behavior.\n            modifier (np.ndarray): A numpy array with modifier(s) for the image.\n\n        Returns:\n            torch.tensor: The perturbed image from original image and modifier.\n        \"\"\"\n\n        assert orig_img.ndim == 4, \"`orig_img` must be a 4D tensor\"\n        assert modifier.ndim == 4, \"`modifier` must be a 4D tensor\"\n\n        b = modifier.shape[0]\n        x = orig_img.shape[1]\n        y = orig_img.shape[2]\n        z = orig_img.shape[3]\n\n        new_modifier = np.zeros((b, x, y, z), dtype=np.float32)\n\n        if x != modifier.shape[1] or y != modifier.shape[2]:\n            for k, v in enumerate(modifier):\n                new_modifier[k, :, :, :] = cv2.resize(\n                    modifier[k, :, :, :],\n                    (x, y),\n                    interpolation=cv2.INTER_LINEAR,\n                )\n        else:\n            new_modifier = modifier\n\n        if self.config[\"use_tanh\"]:\n            return torch.tanh(orig_img + new_modifier) / 2\n        else:\n            return orig_img + new_modifier\n\n    def l2_distance_loss(self, orig_img: torch.tensor, new_img: torch.tensor):\n        \"\"\"Calculates the L2 loss between the image and the new images.\n\n        Args:\n            orig_img (torch.tensor): The original image tensor.\n            new_img (torch.tensor): The tensor containing the perturbed images from the original image.\n\n        Returns:\n            np.ndarray: The numpy array containing the L2 loss between the original image and the perturbed images.\n        \"\"\"\n\n        # assert orig_img.shape == new_img.shape, \"Images must be the same shape\"\n\n        assert new_img.ndim == 4, \"`new_img` must be a 4D tensor\"\n        dim = (1, 2, 3)\n\n        if self.config[\"use_tanh\"]:\n            return (\n                torch.sum(torch.square(new_img - torch.tanh(orig_img) / 2), dim=dim)\n                .detach()\n                .cpu()\n                .numpy()\n            )\n        else:\n            return (\n                torch.sum(torch.square(new_img - orig_img), dim=dim)\n                .detach()\n                .cpu()\n                .numpy()\n            )\n\n    def confidence_loss(self, new_img: torch.tensor, target: torch.tensor):\n        \"\"\"Calculate the confidence loss between the perturbed images and target.\n\n        Args:\n            new_img (torch.tensor): A 4D tensor containing the perturbed images.\n            target (torch.tensor): A 2D tensor containing the target labels.\n\n        Returns:\n            np.ndarray: A numpy array containing the confidence loss between the perturbed images and target.\n        \"\"\"\n        assert new_img.ndim == 4, \"`new_img` must be of shape (N, H, W, C)\"\n        assert (\n            target.ndim == 2\n        ), \"`target` must be of shape (N,L) where L is number of classes\"\n\n        new_img = new_img.permute(0, 3, 1, 2)\n\n        model_output = self.model(new_img)\n\n        if self.config[\"use_log\"]:\n            model_output = F.softmax(model_output, dim=1)\n\n        real = torch.sum(target * model_output, dim=1)\n        other = torch.max((1 - target) * model_output - (target * 10000), dim=1)[0]\n\n        if self.config[\"use_log\"]:\n            real = torch.log(real + 1e-30)\n            other = torch.log(other + 1e-30)\n\n        confidence = torch.tensor(self.config[\"confidence\"], device=self.device).type(\n            torch.float64\n        )\n\n        if self.config[\"targeted\"]:\n            # If targetted, optimize for making the other class most likely\n            output = (\n                torch.max(torch.zeros_like(real), other - real + confidence)\n                .detach()\n                .cpu()\n                .numpy()\n            )\n        else:\n            # If untargetted, optimize for making this class least likely.\n            output = (\n                torch.max(torch.zeros_like(real), real - other + confidence)\n                .detach()\n                .cpu()\n                .numpy()\n            )\n\n        return output, model_output\n\n    def total_loss(\n        self,\n        orig_img: torch.tensor,\n        new_img: torch.tensor,\n        target: torch.tensor,\n        const: int,\n    ):\n        \"\"\"Calculate the total loss for the original image and the perturbed images.\n\n        Args:\n            orig_img (torch.tensor): A 4D tensor containing the original image.\n            new_img (torch.tensor): A 4D tensor containing the perturbed images.\n            target (torch.tensor): A 2D tensor containing the target labels.\n            const (int): The constant to be used in calculating the loss, with which confidence loss is scaled.\n\n        Returns:\n            np.ndarray: A numpy array containing the total loss for the original image and the perturbed images.\n        \"\"\"\n        l2_loss = self.l2_distance_loss(orig_img, new_img)\n\n        confidence_loss, model_output = self.confidence_loss(new_img, target)\n\n        return (\n            l2_loss + const * confidence_loss,\n            l2_loss,\n            confidence_loss,\n            model_output,\n        )\n\n    # Adapted from original code\n    def max_pooling(self, modifier: np.ndarray, patch_size: int):\n        \"\"\"Max pooling operation on a single-channel modifier with a given patch size.\n\n        The array remains the same size after the operation, only the patches have max value throughout.\n\n        Args:\n            modifier (np.ndarray): A numpy array containing a channel of the perturbation.\n            patch_size (int): The size of the patches to be max pooled.\n\n        Returns:\n            np.ndarray: A 2D modifier array containing the max pooled patches.\n        \"\"\"\n\n        assert modifier.ndim == 2, \"`modifier` must be a 2D array\"\n        img_pool = np.copy(modifier)\n        img_x = modifier.shape[0]\n        img_y = modifier.shape[1]\n        for i in range(0, img_x, patch_size):\n            for j in range(0, img_y, patch_size):\n                img_pool[i : i + patch_size, j : j + patch_size] = np.max(\n                    modifier[i : i + patch_size, j : j + patch_size]\n                )\n        return img_pool\n\n    def zero_order_gradients(self, losses: np.ndarray):\n        \"\"\"Calculate the zero order gradients for the losses.\n\n        Args:\n            losses (np.ndarray): A numpy array containing the losses with length - 2 * batch_size + 1\n\n        Returns:\n            np.ndarray: A numpy array containing the zero order gradients for the losses.\n        \"\"\"\n\n        grad = np.zeros(self.config[\"batch_size\"])\n        for i in range(self.config[\"batch_size\"]):\n            grad[i] = (losses[i * 2 + 1] - losses[i * 2 + 2]) / 0.0002\n        return grad\n\n    def coordinate_adam(\n        self, indices: np.ndarray, grad: np.ndarray, modifier: np.ndarray, proj: bool\n    ):\n        \"\"\"Perform inplace coordinate-wise Adam update on modifier.\n\n        Args:\n            indices (np.ndarray): A numpy array containing the indices of the coordinates to be updated.\n            grad (np.ndarray): A numpy array containing the gradients.\n            modifier (np.ndarray): A numpy array containing the current modifier/perturbation.\n            proj (bool): Whether to limit the new values of the modifier between up and down limits.\n        \"\"\"\n        # First moment\n        mt = self.mt_arr[indices]\n        mt = self.config[\"adam_beta1\"] * mt + (1 - self.config[\"adam_beta1\"]) * grad\n\n        self.mt_arr[indices] = mt\n\n        # Second moment\n        vt = self.vt_arr[indices]\n        vt = self.config[\"adam_beta2\"] * vt + (1 - self.config[\"adam_beta2\"]) * (\n            grad * grad\n        )\n\n        self.vt_arr[indices] = vt\n\n        epochs = self.adam_epochs[indices]\n\n        # Bias Correction\n        mt_hat = mt / (1 - np.power(self.config[\"adam_beta1\"], epochs))\n        vt_hat = vt / (1 - np.power(self.config[\"adam_beta2\"], epochs))\n\n        m = modifier.reshape(-1)\n        old_val = m[indices]\n        old_val -= (\n            self.config[\"learning_rate\"]\n            * mt_hat\n            / (np.sqrt(vt_hat) + self.config[\"adam_eps\"])\n        )\n        if proj:\n            old_val = np.maximum(\n                np.minimum(old_val, self.up[indices]), self.down[indices]\n            )\n        m[indices] = old_val\n        self.adam_epochs[indices] = epochs + 1\n\n        # return m.reshape(modifier.shape)\n\n    # Adapted from original code\n    def get_new_prob(\n        self, modifier: np.ndarray, max_pooling_ratio: int = 8, gen_double: bool = False\n    ):\n        \"\"\"\n        Calculate the new probabilities by performing max pooling on the modifier.\n\n        Args:\n            modifier (np.ndarray): A numpy array containing the perturbation.\n            max_pooling_ratio (int): The ratio of the size of the patches to be max pooled.\n            gen_double (bool): Whether to double the size of the perturbation after max pooling.\n\n        Returns:\n            np.ndarray: A numpy array containing the new probabilities.\n\n        \"\"\"\n        modifier = np.squeeze(modifier)\n        old_shape = modifier.shape\n        if gen_double:\n            new_shape = (old_shape[0] * 2, old_shape[1] * 2, old_shape[2])\n        else:\n            new_shape = old_shape\n        prob = np.empty(shape=new_shape, dtype=np.float32)\n        for i in range(modifier.shape[2]):\n            image = np.abs(modifier[:, :, i])\n            image_pool = self.max_pooling(image, old_shape[0] // max_pooling_ratio)\n            if gen_double:\n                prob[:, :, i] = np.array(\n                    Image.fromarray(image_pool).resize(\n                        (new_shape[0], new_shape[1]), Image.NEAREST\n                    )\n                )\n            else:\n                prob[:, :, i] = image_pool\n\n        # NOTE: This is here to handle all zeros input\n        if np.sum(prob) != 0:\n            prob /= np.sum(prob)\n        else:  # pragma: no cover\n            prob = np.ones(shape=new_shape, dtype=np.float32)\n            prob /= np.sum(prob)\n\n        return prob\n\n    # Adapted from original code\n    def resize_img(\n        self,\n        small_x: int,\n        small_y: int,\n        num_channels: int,\n        modifier: np.ndarray,\n        max_pooling_ratio: int = 8,\n        reset_only: bool = False,\n    ):\n        \"\"\"\n        Resize the image to the specified size.\n\n        Args:\n            small_x (int): The new x size of the image.\n            small_y (int): The new y size of the image.\n            num_channels (int): The number of channels in the image.\n            modifier (np.ndarray): A numpy array containing the perturbation.\n            max_pooling_ratio (int): The ratio of the size of the patches to be max pooled.\n            reset_only (bool): Whether to only reset the image, or to resize and crop as well.\n        \"\"\"\n\n        small_single_shape = (small_x, small_y, num_channels)\n\n        new_modifier = np.zeros((1,) + small_single_shape, dtype=np.float32)\n        if not reset_only:\n            # run the resize_op once to get the scaled image\n            assert modifier.ndim == 4, \"Expected 4D array as modifier\"\n            prev_modifier = np.copy(modifier)\n            for k, v in enumerate(modifier):\n                new_modifier[k, :, :, :] = cv2.resize(\n                    modifier[k, :, :, :],\n                    (small_x, small_y),\n                    interpolation=cv2.INTER_LINEAR,\n                )\n\n        # prepare the list of all valid variables\n        var_size = np.prod(small_single_shape)\n        self.var_list = np.array(range(0, var_size), dtype=np.int32)\n        # ADAM status\n        self.mt_arr = np.zeros(var_size, dtype=np.float32)\n        self.vt_arr = np.zeros(var_size, dtype=np.float32)\n        self.adam_epochs = np.ones(var_size, dtype=np.int32)\n        # update sample probability\n        if reset_only:\n            self.sample_prob = np.ones(var_size, dtype=np.float32) / var_size\n        else:\n            self.sample_prob = self.get_new_prob(prev_modifier, max_pooling_ratio, True)\n            self.sample_prob = self.sample_prob.reshape(var_size)\n\n        return new_modifier\n\n    def single_step(\n        self,\n        modifier: np.ndarray,\n        orig_img: torch.tensor,\n        target: torch.tensor,\n        const: int,\n        max_pooling_ratio: int = 8,\n        var_indice: list = None,\n    ):\n        \"\"\"\n        Perform a single step of optimization.\n\n        Args:\n            modifier (np.ndarray): A numpy array containing the perturbation.\n            orig_img (torch.tensor): The original image.\n            target (torch.tensor): The target image.\n            const (int): The constant to be used in the loss function.\n            max_pooling_ratio (int): The ratio of the size of the patches to be max pooled.\n            var_indice (list): The indices of the coordinates to be optimized.\n\n        Returns:\n            (float, float, float, np.ndarray, torch.tensor):\n                The total loss, the L2 loss, the confidence loss,\n                model output on perturbed image, the perturbed image.\n\n        \"\"\"\n\n        assert modifier.ndim == 4, \"Expected 4D array as modifier\"\n        assert modifier.shape[0] == 1, \"Expected 1 batch for modifier\"\n        assert target.ndim == 2, \"Expected 2D tensor as target\"\n\n        var = np.repeat(modifier, self.config[\"batch_size\"] * 2 + 1, axis=0)\n        var_size = modifier.size\n\n        # Select indices for current iteration\n\n        if var_indice is None:\n            if self.config[\"use_importance\"]:\n                var_indice = np.random.choice(\n                    self.var_list.size,\n                    self.config[\"batch_size\"],\n                    replace=False,\n                    p=self.sample_prob,\n                )\n            else:\n                var_indice = np.random.choice(\n                    self.var_list.size, self.config[\"batch_size\"], replace=False\n                )\n        indices = self.var_list[var_indice]\n\n        for i in range(self.config[\"batch_size\"]):\n            var[i * 2 + 1].reshape(-1)[indices[i]] += 0.0001\n            var[i * 2 + 2].reshape(-1)[indices[i]] -= 0.0001\n\n        new_img = self.get_perturbed_image(orig_img, var)\n        losses, l2_losses, confidence_losses, model_output = self.total_loss(\n            orig_img, new_img, target, const\n        )\n\n        if modifier.shape[1] > self.config[\"init_size\"]:\n            self.sample_prob = self.get_new_prob(\n                modifier, max_pooling_ratio=max_pooling_ratio\n            )\n            self.sample_prob = self.sample_prob.reshape(var_size)\n\n        grad = self.zero_order_gradients(losses)\n\n        # Modifier is updated here, so is adam epochs, mt_arr, and vt_arr\n        self.coordinate_adam(indices, grad, modifier, not self.config[\"use_tanh\"])\n\n        return (\n            losses[0],\n            l2_losses[0],\n            confidence_losses[0],\n            model_output[0].detach().numpy(),\n            new_img[0],\n        )\n\n    def attack(\n        self,\n        orig_img: np.ndarray,\n        target: np.ndarray,\n        modifier_init: np.ndarray = None,\n        max_pooling_ratio: int = 8,\n    ):\n        \"\"\"\n        Perform the attack on coordinate-batches.\n\n        Args:\n            orig_img (np.ndarray): The original image.\n            target (np.ndarray): The target image.\n            modifier_init (np.ndarray): The initial modifier. Default is `None`.\n            max_pooling_ratio (int): The ratio of the size of the patches to be max pooled.\n\n        Returns:\n            (np.ndarray, np.ndarray): The best perturbed image and best constant for scaling confidence loss.\n        \"\"\"\n\n        def compare(x, y):\n            if not isinstance(x, (float, int, np.int64)):\n                x = np.copy(x)\n                if self.config[\"targeted\"]:\n                    x[y] -= self.config[\"confidence\"]\n                else:\n                    x[y] += self.config[\"confidence\"]\n                x = np.argmax(x)\n            if self.config[\"targeted\"]:\n                return x == y\n            else:\n                return x != y\n\n        assert orig_img.ndim == 3, \"Expected 3D array as image\"\n        assert target.ndim == 1, \"Expected 1D array as target\"\n\n        if modifier_init is not None:\n            assert modifier_init.ndim == 3, \"Expected 3D array as modifier\"\n            modifier = modifier_init.copy()\n        else:\n            if self.config[\"use_resize\"]:\n                modifier = self.resize_img(\n                    self.config[\"init_size\"],\n                    self.config[\"init_size\"],\n                    3,\n                    modifier_init,\n                    max_pooling_ratio,\n                    reset_only=True,\n                )\n            else:\n                modifier = np.zeros(orig_img.shape, dtype=np.float32)\n\n        if self.config[\"use_tanh\"]:\n            orig_img = np.arctanh(orig_img * 1.999999)\n\n        var_size = np.prod(orig_img.shape)  # width * height * num_channels\n        self.var_list = np.array(range(0, var_size), dtype=np.int32)\n\n        # Initialize Adam optimizer values\n        self.mt_arr = np.zeros(var_size, dtype=np.float32)\n        self.vt_arr = np.zeros(var_size, dtype=np.float32)\n        self.adam_epochs = np.ones(var_size, dtype=np.int64)\n        self.up = np.zeros(var_size, dtype=np.float32)\n        self.down = np.zeros(var_size, dtype=np.float32)\n\n        # Sampling Probabilities\n        self.sample_prob = np.ones(var_size, dtype=np.float32) / var_size\n\n        low = 0.0\n        mid = self.config[\"initial_const\"]\n        high = 1e10\n\n        if not self.config[\"use_tanh\"]:\n            self.up = 0.5 - orig_img.reshape(-1)\n            self.down = -0.5 - orig_img.reshape(-1)\n\n        outer_best_const = mid\n        outer_best_l2 = 1e10\n        outer_best_score = -1\n        outer_best_adv = orig_img\n\n        # Make Everything 4D and Tensorize\n        orig_img = torch.from_numpy(orig_img).unsqueeze(0).to(self.device)\n        target = torch.from_numpy(target).unsqueeze(0).to(self.device)\n        modifier = modifier.reshape((-1,) + modifier.shape)\n\n        for outer_step in range(self.config[\"binary_search_steps\"]):\n\n            best_l2 = 1e10\n            best_score = -1\n\n            # NOTE: In the original implemenation there is a step to move mid to high\n            # at last step with some condition\n\n            prev = 1e6\n            last_confidence_loss = 1.0\n\n            if modifier_init is not None:\n                assert modifier_init.ndim == 3, \"Expected 3D array as modifier\"\n                modifier = modifier_init.copy()\n                modifier = modifier.reshape((-1,) + modifier.shape)\n            else:\n                if self.config[\"use_resize\"]:\n                    modifier = self.resize_img(\n                        self.config[\"init_size\"],\n                        self.config[\"init_size\"],\n                        3,\n                        modifier_init,\n                        max_pooling_ratio,\n                        reset_only=True,\n                    )\n\n                else:\n                    modifier = np.zeros(orig_img.shape, dtype=np.float32)\n\n            self.mt_arr.fill(0.0)\n            self.vt_arr.fill(0.0)\n            self.adam_epochs.fill(1)\n            stage = 0\n            eval_costs = 0\n\n            # NOTE: Original code allows for a custom start point in iterations\n            for iter in range(0, self.config[\"max_iterations\"]):\n                if self.config[\"use_resize\"]:\n                    if iter == self.config[\"resize_iter_1\"]:\n                        modifier = self.resize_img(\n                            self.config[\"init_size\"] * 2,\n                            self.config[\"init_size\"] * 2,\n                            3,\n                            modifier,\n                            max_pooling_ratio,\n                        )\n                    if iter == self.config[\"resize_iter_2\"]:\n                        modifier = self.resize_img(\n                            self.config[\"init_size\"] * 4,\n                            self.config[\"init_size\"] * 4,\n                            3,\n                            modifier,\n                            max_pooling_ratio,\n                        )\n                if iter % (self.config[\"max_iterations\"] // 10) == 0:\n                    new_img = self.get_perturbed_image(orig_img, modifier)\n                    (\n                        total_losses,\n                        l2_losses,\n                        confidence_losses,\n                        model_output,\n                    ) = self.total_loss(orig_img, new_img, target, mid)\n                    print(\n                        f\"iter = {iter}, cost = {eval_costs},  size = {modifier.shape}, \"\n                        f\"total_loss = {total_losses[0]:.5g}, l2_loss = {l2_losses[0]:.5g}, \"\n                        f\"confidence_loss = {confidence_losses[0]:.5g}\"\n                    )\n\n                (\n                    total_loss,\n                    l2_loss,\n                    confidence_loss,\n                    model_output,\n                    adv_img,\n                ) = self.single_step(\n                    modifier, orig_img, target, mid, max_pooling_ratio=max_pooling_ratio\n                )\n\n                eval_costs += self.config[\"batch_size\"]\n\n                if (\n                    confidence_loss == 0.0\n                    and last_confidence_loss != 0.0\n                    and stage == 0\n                ):\n\n                    if self.config[\"reset_adam_after_found\"]:\n                        print(\"Resetting Adam\")\n                        self.mt_arr.fill(0.0)\n                        self.vt_arr.fill(0.0)\n                        self.adam_epochs.fill(1)\n                    print(\"Setting Stage to 1\")\n                    stage = 1\n\n                last_confidence_loss = confidence_loss\n\n                if (\n                    self.config[\"abort_early\"]\n                    and iter % self.config[\"early_stop_iters\"] == 0\n                ):\n                    if total_loss > prev * 0.9999:\n                        print(\"Early stopping because there is no improvement\")\n                        break\n                    prev = total_loss\n\n                if l2_loss < best_l2 and compare(model_output, np.argmax(target[0])):\n                    best_l2 = l2_loss\n                    best_score = np.argmax(model_output)\n\n                if l2_loss < outer_best_l2 and compare(\n                    model_output, np.argmax(target[0])\n                ):\n                    outer_best_l2 = l2_loss\n                    outer_best_score = np.argmax(model_output)\n                    outer_best_adv = adv_img\n                    outer_best_const = mid\n\n            if compare(best_score, np.argmax(target[0])) and best_score != -1:\n\n                print(\"Old Constant: \", mid)\n                high = min(high, mid)\n                if high < 1e9:\n                    mid = (low + high) / 2\n                print(\"New Constant: \", mid)\n            else:\n                print(\"Old Constant: \", mid)\n                low = max(low, mid)\n                if high < 1e9:  # pragma: no cover\n                    mid = (low + high) / 2\n                else:  # pragma: no cover\n                    mid *= 10\n                print(\"new constant: \", mid)\n\n        return outer_best_adv, outer_best_const\n", "meta": {"hexsha": "a47882b283f8e45d047f4e6a53891c5e68a810a4", "size": 26302, "ext": "py", "lang": "Python", "max_stars_repo_path": "code_soup/ch5/algorithms/zoo_attack.py", "max_stars_repo_name": "gchhablani/code-soup", "max_stars_repo_head_hexsha": "eec666b6cd76bad9c7133a185bb85021b4a390f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2021-07-29T16:21:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T12:58:15.000Z", "max_issues_repo_path": "code_soup/ch5/algorithms/zoo_attack.py", "max_issues_repo_name": "gchhablani/code-soup", "max_issues_repo_head_hexsha": "eec666b6cd76bad9c7133a185bb85021b4a390f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 93, "max_issues_repo_issues_event_min_datetime": "2021-08-04T02:48:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T04:58:51.000Z", "max_forks_repo_path": "code_soup/ch5/algorithms/zoo_attack.py", "max_forks_repo_name": "gchhablani/code-soup", "max_forks_repo_head_hexsha": "eec666b6cd76bad9c7133a185bb85021b4a390f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2021-08-06T06:51:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T05:47:18.000Z", "avg_line_length": 36.9929676512, "max_line_length": 124, "alphanum_fraction": 0.5466124249, "include": true, "reason": "import numpy", "num_tokens": 5722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.17885224354419688}}
{"text": "#!/usr/bin/env python\n\nimport h5py\nimport sys\nimport argparse\nimport multiprocessing as mp\nimport time\nimport os\nimport shutil\nimport logging\nimport hashlib\nimport numpy\nimport itertools\nfrom ising import Ising\nfrom blessings import Terminal\nfrom ext.progressbar import ProgressBar\nfrom ext.hdf5handler import HDF5Handler\nfrom misc import drawwidget\n\n\"\"\"\nIn mp_runsim.py the simulations are set up by reading a configfile.\nThe simulations are then processed by an x number of workers.\n\"\"\"\n\ndef hash_it(a):\n    \"\"\"\n    Hashes the string <a> using SHA256. The hash is used to give the\n    sharded HDF5 files unique filenames. Each shard correspond to a\n    unique (shape, algorithm, temperature, etc..) task.\n    \"\"\"\n    h = hashlib.sha256()\n    h.update(str(a).encode('UTF-8'))\n    hash_ = h.hexdigest()\n    return hash_\n\n\ndef worker(tasks_queue, done_queue):\n    \"\"\"\n    Pulls a task from the task queue and initiates the ising model\n    simulation.\n\n    Ising.evolve() is run within the context of HDF5Handler so a\n    handler can be passed to Ising object. The HDF5Handler context\n    block is run within the context of Pbar to track the progress\n    of the simulation.\n    \"\"\"\n\n    for task, hash_ in iter(tasks_queue.get, 'STOP'):\n        process_id = int((mp.current_process().name)[-1]) #find nicer way\n        writer = Writer((0, process_id), TERM)\n\n        with Pbar(task, writer) as bar:\n            with HDF5Handler(filename=ARGS.tempdir+'/'+hash_+'.hdf5') as h:\n                time_start = time.time()\n                isingsim = Ising(shape=task['shape'], sweeps=task['mcs'],\n                                 temperature=task['temperature'],\n                                 aligned=task['aligned'],\n                                 algorithm=task['algorithm'], handler=h,\n                                 saveinterval=task['saveinterval'],\n                                 skip_n_steps=task['skip_n_steps'])\n                isingsim.evolve(pbar=bar)\n                runtime = round(time.time() - time_start, 2)\n\n\n        subs = {'temp'     : task[\"temperature\"],\n                'shape'    : task['shape'],\n                'algo'     : task['algorithm'],\n                'aligned'  : task['aligned'],\n                'mcs'      : task['mcs'],\n                'runtime'  : runtime,\n                'timestamp': time.strftime(\"%d %b %Y %H:%M:%S\")\n                }\n\n        s = \"T={temp:.3f}  {shape}  {algo}  {aligned}  {mcs} {runtime:.2f}  {timestamp} \"\n        job_report = s.format(**subs)\n\n        logging.info(job_report)\n        done_queue.put(job_report)\n\ndef get_arguments():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('-c', '--config', required=True, help=\"Config file\")\n    parser.add_argument('-d', '--outputdir', required=True, help=\"Target\\\n                        directory for hdf5 files\")\n    parser.add_argument('-t', '--tempdir', default='/tmp/olisms/')\n    parser.add_argument('-p', '--prefix', default=\"\", help=\"adds [prefix]\\\n                        to filenames\")\n    parser.add_argument('-l', '--logfile', default=None, help=\"logfile\")\n    parser.add_argument('-w', \"--workers\", dest='nr_workers', default=4,\n                        type=int, help=\"Number of workers\")\n    args = parser.parse_args()\n    return args\n\nclass Writer(object):\n    \"\"\" Create an object with a write method that writes to a\n    specific place on the screen, defined at instantiation.\n\n    This is the glue between blessings and progressbar.\n    \"\"\"\n    def __init__(self, location, term):\n        \"\"\"\n        Input: location - tuple of ints (x, y), the position\n                        of the bar in the terminal\n        \"\"\"\n        self.term = term\n        self.location = location\n\n    def write(self, string):\n        with self.term.location(*self.location):\n            print(string)\n\nclass CompletedJobsWriter(object):\n    \"\"\"\n    Merely a container for holding:\n        1) the location in the terminal at which to print a list of\n           completed jobs.\n        2) a list of previously completed jobs, that will be no longer than\n           the 'available' terminal space.\n    \"\"\"\n    def __init__(self, terminal, location):\n        \"\"\"\n        terminal: blessings.Terminal() instance\n        location: tuple containing (x,y) terminal coordinates\n        \"\"\"\n        self.width = terminal.width\n        self.height = terminal.height\n        self.maxheight = self.height - location[1] - 3\n        self.location = location\n        self.terminal = terminal\n        self.lines = list()\n\n    def print_line(self, line):\n        \"\"\"\n        Prints a list of completed jobs (self.lines) to the terminal with the\n        most recent completed job at the top.\n\n        line : str\n            Some job completion message.\n\n        \"\"\"\n        if len(self.lines) == self.maxheight:\n            self.lines.pop()\n            self.lines = [line] + self.lines\n        else:\n            self.lines = [line] + self.lines\n            assert len(self.lines) <= self.maxheight\n\n        for i, line in enumerate(self.lines):\n            with self.terminal.location(self.location[0], self.location[1]+i):\n                print(line)\n\nclass Pbar(object):\n    def __init__(self, task, writer):\n        self.description = \"T:\"+str(task[\"temperature\"])+\" \"\n        self.pbar = ProgressBar(widgets=drawwidget(self.description),\n                                maxval=task[\"mcs\"], fd=writer)\n\n    def __enter__(self):\n        self.pbar.start()\n        return self.pbar\n\n    def __exit__(self, exc_type, exc_val, traceback):\n        self.pbar.finish()\n        return False\n\n\n\nif __name__ == \"__main__\":\n\n    if sys.version_info < (3, 3):\n        s = \"Running with Python {}, but Python 3.3 or greater is required.\"\n        print(s.format(sys.version_info[:2]))\n        exit()\n    else:\n        import configparser\n\n    ARGS = get_arguments()\n\n\n    if not os.path.exists(ARGS.tempdir):\n        os.makedirs(ARGS.tempdir)\n    else:\n        shutil.rmtree(ARGS.tempdir)\n        os.makedirs(ARGS.tempdir)\n\n    interpolation = configparser.ExtendedInterpolation()\n    cfg = configparser.ConfigParser(interpolation=interpolation)\n    cfg.read(ARGS.config)\n\n    if ARGS.logfile is not None:\n        logging.basicConfig(filename=ARGS.logfile, level=logging.DEBUG,)\n    else:\n        logging.basicConfig(filename=cfg['log']['logfile'], level=logging.DEBUG,)\n\n    logging.info('START LOG FILE : ' + time.strftime(\"%c\"))\n    TERM = Terminal()\n    print(TERM.clear())\n\n    tasks_queue = mp.Queue()\n    done_queue = mp.Queue()\n\n    processpool = []\n    for i in range(ARGS.nr_workers):\n        p = mp.Process(target=worker, args=(tasks_queue, done_queue)).start()\n        processpool.append(p)\n\n\n    def job_to_tasks(job):\n        \"\"\"  Seperates a job into tasks. \"\"\"\n        tasks = []\n        for index, T in enumerate(numpy.linspace(float(cfg[job]['mintemp']),\n                                                 float(cfg[job]['maxtemp']),\n                                                 int(cfg[job]['steps']))):\n            task = {\n                    \"algorithm\":   str(cfg[job]['algorithm']),\n                    \"shape\":       tuple(int(i) for i in \\\n                                         cfg[job]['shape'].split('x')),\n                    \"aligned\":     True if cfg[job]['aligned'] == 'True' \\\n                                        else False,\n                    \"mcs\":         int(cfg[job]['mcs']),\n                    \"skip_n_steps\":int(cfg[job]['skip_n_steps']),\n                    \"saveinterval\":int(cfg[job]['saveinterval']),\n                    \"temperature\": T,\n                   }\n            tasks.append(task)\n        return tasks\n\n    def job_to_hashes(job):\n        \"\"\" Calculates a hash for each task. The hash will be used to uniquely\n        determine the filenames of the sharded hdf5 files.  \"\"\"\n        tasks = job_to_tasks(job)\n        hashes = [hash_it(task) for task in tasks]\n        return hashes\n\n    def unique_filename_from_job(job):\n        identifier = \"{algorithm}_{shape}_MCS{mcs}_si{saveinterval}_\\\n                      minT{mintemp}_maxT{maxtemp}_{steps}_\\\n                      {aligned}\".format(**cfg[job])\n\n        identifier_no_whitespace = identifier.replace(\" \", \"\")\n        return identifier_no_whitespace\n\n\n    def filename_from_job(job):\n        data_dir = ARGS.outputdir\n        prefix = ARGS.prefix\n\n        job_id = unique_filename_from_job(job)\n\n        abs_path = \"{data_dir}/{prefix}{job_id}.hdf5\".format(**locals())\n        return abs_path\n\n    jobs = [job for job in cfg.sections() if job.startswith('job')]\n\n    tasks_grouped_by_job = [job_to_tasks(job) for job in jobs]\n    # tasks_grouped_by_job =  [ [t1, t2, t3], [t1, t2, t3], etc ]\n\n    hashes_grouped_by_job = [job_to_hashes(job) for job in jobs]\n    # hashes_grouped_by_job =  [ [h1, h2, h3], [h1, h2, h3], etc ]\n\n    tasks_all_chained = list(itertools.chain(*tasks_grouped_by_job))\n    #chain(*[[1,2], [6,7,8]]) = [1,2,6,7,8]\n\n    hashes_all_chained = list(itertools.chain(*hashes_grouped_by_job))\n\n    for task, hash_ in zip(tasks_all_chained, hashes_all_chained):\n        tasks_queue.put((task, hash_))\n\n    jobswriter = CompletedJobsWriter(TERM, (2,7)) #TODO: unhardcode\n    for i in range(len(tasks_all_chained)):\n        jobswriter.print_line(done_queue.get())\n\n    for i in range(ARGS.nr_workers):\n        tasks_queue.put('STOP')\n\n\n    # Merge the sharded HDF5 files\n    for i, job in enumerate(jobs):\n\n        h = h5py.File(filename_from_job(job), 'w')\n\n        for key in cfg[job]:\n            h.attrs[key] = cfg[job][key]\n\n        for index, hash_ in enumerate(hashes_grouped_by_job[i]):\n            f = h5py.File(ARGS.tempdir+'/'+hash_+'.hdf5', 'r')\n\n            h5path =\"sim_\"+str(index).zfill(4)+\"/\"\n            h.create_group(h5path)\n            for key in f.keys():\n                h[h5path][key] = f[key].value\n\n            f.close()\n\n        h.close()\n\n    logging.info('END LOG FILE : ' + time.strftime(\"%c\"))\n\n\n\n", "meta": {"hexsha": "63a3b8007ae7abed1142dffa0cd067f80f034d32", "size": 9953, "ext": "py", "lang": "Python", "max_stars_repo_path": "mp_runsim.py", "max_stars_repo_name": "iambernie/olisms", "max_stars_repo_head_hexsha": "1ccbe2862ea41ffbeb9df8ffc6da43bac1bc5887", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mp_runsim.py", "max_issues_repo_name": "iambernie/olisms", "max_issues_repo_head_hexsha": "1ccbe2862ea41ffbeb9df8ffc6da43bac1bc5887", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mp_runsim.py", "max_forks_repo_name": "iambernie/olisms", "max_forks_repo_head_hexsha": "1ccbe2862ea41ffbeb9df8ffc6da43bac1bc5887", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0664451827, "max_line_length": 89, "alphanum_fraction": 0.578318095, "include": true, "reason": "import numpy", "num_tokens": 2306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3522017752483203, "lm_q1q2_score": 0.17885224009129488}}
{"text": "#encoding=utf-8\nimport h5py\nimport torch\nimport numpy as np\nimport os\nimport sys\nsys.path.append(os.path.abspath(__file__).replace(os.path.basename(__file__),'').replace('utils/',''))\nfrom config import args\nimport json\nimport torch.nn.functional as F\nimport cv2\nimport math\nfrom scipy import interpolate\nimport hashlib\nimport shutil\nimport pickle\nimport csv\n\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom skimage import io\n\n# logger tools\n\nclass AverageMeter(object):\n    \"\"\"Computes and stores the average and current value\"\"\"\n\n    def __init__(self):\n        self.reset()\n\n    def reset(self):\n        self.val = 0.\n        self.avg = 0.\n        self.sum = 0.\n        self.count = 0.\n\n    def update(self, val, n=1):\n        self.val = val\n        self.sum += val * n\n        self.count += n\n        self.avg = self.sum / self.count\n\nclass Logger(object):\n\n    def __init__(self, path, header):\n        self.log_file = open(path, 'w')\n        self.logger = csv.writer(self.log_file, delimiter='\\t')\n\n        self.logger.writerow(header)\n        self.header = header\n\n    def __del(self):\n        self.log_file.close()\n\n    def log(self, values):\n        write_values = []\n        for col in self.header:\n            assert col in values\n            write_values.append(values[col])\n\n        self.logger.writerow(write_values)\n        self.log_file.flush()\n\ndef wrap(func, *args, unsqueeze=False):\n    \"\"\"\n    Wrap a torch function so it can be called with NumPy arrays.\n    Input and return types are seamlessly converted.\n    \"\"\"\n    # Convert input types where applicable\n    args = list(args)\n    for i, arg in enumerate(args):\n        if type(arg) == np.ndarray:\n            args[i] = torch.from_numpy(arg)\n            if unsqueeze:\n                args[i] = args[i].unsqueeze(0)\n\n    result = func(*args)\n\n    # Convert output types where applicable\n    if isinstance(result, tuple):\n        result = list(result)\n        for i, res in enumerate(result):\n            if type(res) == torch.Tensor:\n                if unsqueeze:\n                    res = res.squeeze(0)\n                result[i] = res.numpy()\n        return tuple(result)\n    elif type(result) == torch.Tensor:\n        if unsqueeze:\n            result = result.squeeze(0)\n        return result.numpy()\n    else:\n        return result\n\ndef deterministic_random(min_value, max_value, data):\n    digest = hashlib.sha256(data.encode()).digest()\n    raw_value = int.from_bytes(digest[:4], byteorder='little', signed=False)\n    return int(raw_value / (2**32 - 1) * (max_value - min_value)) + min_value\n\n# Math transform\n\ndef compute_similarity_transform(S1, S2):\n    '''\n    Computes a similarity transform (sR, t) that takes\n    a set of 3D points S1 (3 x N) closest to a set of 3D points S2,\n    where R is an 3x3 rotation matrix, t 3x1 translation, s scale.\n    i.e. solves the orthogonal Procrutes problem.\n    '''\n    transposed = False\n    if S1.shape[0] != 3 and S1.shape[0] != 2:\n        S1 = S1.T\n        S2 = S2.T\n        transposed = True\n    assert(S2.shape[1] == S1.shape[1])\n\n    # 1. Remove mean.\n    mu1 = S1.mean(axis=1, keepdims=True)\n    mu2 = S2.mean(axis=1, keepdims=True)\n    X1 = S1 - mu1\n    X2 = S2 - mu2\n\n    # 2. Compute variance of X1 used for scale.\n    var1 = np.sum(X1**2)\n\n    # 3. The outer product of X1 and X2.\n    K = X1.dot(X2.T)\n\n    # 4. Solution that Maximizes trace(R'K) is R=U*V', where U, V are\n    # singular vectors of K.\n    U, s, Vh = np.linalg.svd(K)\n    V = Vh.T\n    # Construct Z that fixes the orientation of R to get det(R)=1.\n    Z = np.eye(U.shape[0])\n    Z[-1, -1] *= np.sign(np.linalg.det(U.dot(V.T)))\n    # Construct R.\n    R = V.dot(Z.dot(U.T))\n\n    # 5. Recover scale.\n    scale = np.trace(R.dot(K)) / var1\n\n    # 6. Recover translation.\n    t = mu2 - scale*(R.dot(mu1))\n\n    # 7. Error:\n    S1_hat = scale*R.dot(S1) + t\n\n    if transposed:\n        S1_hat = S1_hat.T\n\n    return S1_hat\n\ndef compute_average_loss(loss_list):\n    loss_np = np.array(loss_list)\n    loss = np.mean(loss_np,axis=0)\n    return loss\n\ndef _init_weights_deconv(m):\n    n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n    m.weight.data.normal_(0, math.sqrt(2. / n))\n\ndef _init_batchnorm(m):\n    m.weight.data.fill_(1)\n    m.bias.data.zero_()\n\ndef load_mean_param():\n    mean = np.zeros(args.total_param_count, dtype = np.float)\n\n    mean_values = h5py.File(args.smpl_mean_param_path)\n    mean_pose = mean_values['pose']\n    mean_pose[:3] = 0\n    mean_shape = mean_values['shape']\n    mean_pose[0]=np.pi\n\n    #init scale is 0.9\n    mean[0] = 0.9\n\n    mean[3:75] = mean_pose[:]\n    mean[75:] = mean_shape[:]\n\n    return mean\n\ndef batch_rodrigues(param):\n    #param N x 3\n    batch_size = param.shape[0]\n\n    l1norm = torch.norm(param + 1e-8, p = 2, dim = 1)\n    angle = torch.unsqueeze(l1norm, -1)\n    normalized = torch.div(param, angle)\n    angle = angle * 0.5\n\n    v_cos = torch.cos(angle)\n    v_sin = torch.sin(angle)\n\n    quat = torch.cat([v_cos, v_sin * normalized], dim = 1)\n\n    return quat2mat(quat)\n\ndef quat2mat(quat):\n    \"\"\"Convert quaternion coefficients to rotation matrix.\n    Args:\n        quat: size = [B, 4] 4 <===>(w, x, y, z)\n    Returns:\n        Rotation matrix corresponding to the quaternion -- size = [B, 3, 3]\n    \"\"\"\n    norm_quat = quat\n    norm_quat = norm_quat/norm_quat.norm(p=2, dim=1, keepdim=True)\n    w, x, y, z = norm_quat[:,0], norm_quat[:,1], norm_quat[:,2], norm_quat[:,3]\n\n    B = quat.size(0)\n\n    w2, x2, y2, z2 = w.pow(2), x.pow(2), y.pow(2), z.pow(2)\n    wx, wy, wz = w*x, w*y, w*z\n    xy, xz, yz = x*y, x*z, y*z\n\n    rotMat = torch.stack([w2 + x2 - y2 - z2, 2*xy - 2*wz, 2*wy + 2*xz,\n                          2*wz + 2*xy, w2 - x2 + y2 - z2, 2*yz - 2*wx,\n                          2*xz - 2*wy, 2*wx + 2*yz, w2 - x2 - y2 + z2], dim=1).view(B, 3, 3)\n    return rotMat\n\ndef batch_global_rigid_transformation(Rs, Js, parent, rotate_base = False,root_rot_mat =None):\n    N = Rs.shape[0]\n    if rotate_base:\n        np_rot_x = np.array([[1, 0, 0], [0, -1, 0], [0, 0, -1]], dtype = np.float)\n        np_rot_x = np.reshape(np.tile(np_rot_x, [N, 1]), [N, 3, 3])\n        rot_x = torch.from_numpy(np_rot_x).float().cuda()\n        root_rotation = torch.matmul(Rs[:, 0, :, :],  rot_x)\n    elif root_rot_mat is not None:\n        np_rot_x = np.reshape(np.tile(root_rot_mat, [N, 1]), [N, 3, 3])\n        rot_x =torch.from_numpy(np_rot_x).float().cuda()\n        root_rotation = torch.matmul(Rs[:, 0, :, :],  rot_x)\n    else:\n        root_rotation = Rs[:, 0, :, :]\n    Js = torch.unsqueeze(Js, -1)\n\n    def make_A(R, t):\n        R_homo = F.pad(R, [0, 0, 0, 1, 0, 0])\n        t_homo = torch.cat([t, torch.ones(N, 1, 1).cuda()], dim = 1)\n        return torch.cat([R_homo, t_homo], 2)\n\n    A0 = make_A(root_rotation, Js[:, 0])\n    results = [A0]\n\n    for i in range(1, parent.shape[0]):\n        j_here = Js[:, i] - Js[:, parent[i]]\n        A_here = make_A(Rs[:, i], j_here)\n        res_here = torch.matmul(results[parent[i]], A_here)\n        results.append(res_here)\n\n    results = torch.stack(results, dim = 1)\n\n    new_J = results[:, :, :3, 3]\n    Js_w0 = torch.cat([Js, torch.zeros(N, 24, 1, 1).cuda()], dim = 2)\n    init_bone = torch.matmul(results, Js_w0)\n    init_bone = F.pad(init_bone, [3, 0, 0, 0, 0, 0, 0, 0])\n    A = results - init_bone\n\n    return new_J, A\n\ndef batch_global_rigid_transformation_cpu(Rs, Js, parent, rotate_base = False,root_rot_mat =None):\n    N = Rs.shape[0]\n    if rotate_base:\n        np_rot_x = np.array([[1, 0, 0], [0, -1, 0], [0, 0, -1]], dtype = np.float)\n        np_rot_x = np.reshape(np.tile(np_rot_x, [N, 1]), [N, 3, 3])\n        rot_x =torch.from_numpy(np_rot_x).float()\n        root_rotation = torch.matmul(Rs[:, 0, :, :],  rot_x)\n    elif root_rot_mat is not None:\n        np_rot_x = np.reshape(np.tile(root_rot_mat, [N, 1]), [N, 3, 3])\n        rot_x =torch.from_numpy(np_rot_x).float()\n        root_rotation = torch.matmul(Rs[:, 0, :, :],  rot_x)\n    else:\n        root_rotation = Rs[:, 0, :, :]\n    Js = torch.unsqueeze(Js, -1)\n\n    def make_A(R, t):\n        R_homo = F.pad(R, [0, 0, 0, 1, 0, 0])\n        t_homo = torch.cat([t, torch.ones(N, 1, 1)], dim = 1)\n        return torch.cat([R_homo, t_homo], 2)\n\n    A0 = make_A(root_rotation, Js[:, 0])\n    results = [A0]\n\n    for i in range(1, parent.shape[0]):\n        j_here = Js[:, i] - Js[:, parent[i]]\n        A_here = make_A(Rs[:, i], j_here)\n        res_here = torch.matmul(results[parent[i]], A_here)\n        results.append(res_here)\n\n    results = torch.stack(results, dim = 1)\n\n    new_J = results[:, :, :3, 3]\n    Js_w0 = torch.cat([Js, torch.zeros(N, 24, 1, 1)], dim = 2)\n    init_bone = torch.matmul(results, Js_w0)\n    init_bone = F.pad(init_bone, [3, 0, 0, 0, 0, 0, 0, 0])\n    A = results - init_bone\n\n    return new_J, A\n\ndef batch_lrotmin(param):\n    param = param[:,3:].contiguous()\n    Rs = batch_rodrigues(param.view(-1, 3))\n    print(Rs.shape)\n    e = torch.eye(3).float()\n    Rs = Rs.sub(1.0, e)\n\n    return Rs.view(-1, 23 * 9)\n\ndef batch_orth_proj(X, camera, mode='2d'):\n    camera = camera.view(-1, 1, 3)\n    s = camera[:, :, 0].unsqueeze(-1)\n    X_trans = X[:,:,:2].contiguous()\n    if mode=='2d':\n        X_trans = s * X_trans + camera[:, :, 1:]\n        return X_trans\n    elif mode=='v3d':\n        X[:, :, :2] = s * X_trans + camera[:, :, 1:]\n        return X\n    elif mode=='j3d':\n        X[:, :, :2] = s * X_trans/torch.abs(s) + camera[:, :, 1:]\n        return X\n    else:\n        print('projection mode is not included')\n        return X\n\ndef calc_aabb(ptSets):\n\n    ptLeftTop     = np.array([np.min(ptSets[:,0]),np.min(ptSets[:,1])])\n    ptRightBottom = np.array([np.max(ptSets[:,0]),np.max(ptSets[:,1])])\n    return [ptLeftTop, ptRightBottom]\n\n    ptLeftTop     = np.array([ptSets[0][0], ptSets[0][1]])\n    ptRightBottom = ptLeftTop.copy()\n    for pt in ptSets:\n        ptLeftTop[0]     = min(ptLeftTop[0], pt[0])\n        ptLeftTop[1]     = min(ptLeftTop[1], pt[1])\n        ptRightBottom[0] = max(ptRightBottom[0], pt[0])\n        ptRightBottom[1] = max(ptRightBottom[1], pt[1])\n\n    return ptLeftTop, ptRightBottom#, len(ptSets) >= 5\n\ndef calc_aabb_batch(ptSets_batch):\n    batch_size = ptSets_batch.shape[0]\n    ptLeftTop     = np.array([np.min(ptSets_batch[:,:,0],axis=1),np.min(ptSets_batch[:,:,1],axis=1)]).T\n    ptRightBottom = np.array([np.max(ptSets_batch[:,:,0],axis=1),np.max(ptSets_batch[:,:,1],axis=1)]).T\n    bbox = np.concatenate((ptLeftTop.reshape(batch_size,1,2),ptRightBottom.reshape(batch_size,1,2)),axis=1)\n    return bbox\n\ndef calc_obb(ptSets):\n    ca = np.cov(ptSets,y = None,rowvar = 0,bias = 1)\n    v, vect = np.linalg.eig(ca)\n    tvect = np.transpose(vect)\n    ar = np.dot(ptSets,np.linalg.inv(tvect))\n    mina = np.min(ar,axis=0)\n    maxa = np.max(ar,axis=0)\n    diff    = (maxa - mina)*0.5\n    center  = mina + diff\n    corners = np.array([center+[-diff[0],-diff[1]],center+[diff[0],-diff[1]],center+[diff[0],diff[1]],center+[-diff[0],diff[1]]])\n    corners = np.dot(corners, tvect)\n    return corners[0], corners[1], corners[2], corners[3]\n\ndef get_image_cut_box(leftTop, rightBottom, ExpandsRatio, Center = None):\n    try:\n        l = len(ExpandsRatio)\n    except:\n        ExpandsRatio = [ExpandsRatio, ExpandsRatio, ExpandsRatio, ExpandsRatio]\n\n    def _expand_crop_box(lt, rb, scale):\n        center = (lt + rb) / 2.0\n        xl, xr, yt, yb = lt[0] - center[0], rb[0] - center[0], lt[1] - center[1], rb[1] - center[1]\n\n        xl, xr, yt, yb = xl * scale[0], xr * scale[1], yt * scale[2], yb * scale[3]\n        #expand it\n        lt, rb = np.array([center[0] + xl, center[1] + yt]), np.array([center[0] + xr, center[1] + yb])\n        lb, rt = np.array([center[0] + xl, center[1] + yb]), np.array([center[0] + xr, center[1] + yt])\n        center = (lt + rb) / 2\n        return center, lt, rt, rb, lb\n\n    if Center == None:\n        Center = (leftTop + rightBottom) // 2\n\n    Center, leftTop, rightTop, rightBottom, leftBottom = _expand_crop_box(leftTop, rightBottom, ExpandsRatio)\n    offset = (rightBottom - leftTop) // 2\n\n    cx = offset[0]\n    cy = offset[1]\n\n    r = max(cx, cy)\n\n    cx = r\n    cy = r\n\n    x = int(Center[0])\n    y = int(Center[1])\n\n    return [x - cx, y - cy], [x + cx, y + cy]\n\ndef shrink(leftTop, rightBottom, width, height):\n    xl = -leftTop[0]\n    xr = rightBottom[0] - width\n\n    yt = -leftTop[1]\n    yb = rightBottom[1] - height\n\n    cx = (leftTop[0] + rightBottom[0]) / 2\n    cy = (leftTop[1] + rightBottom[1]) / 2\n\n    r = (rightBottom[0] - leftTop[0]) / 2\n\n    sx = max(xl, 0) + max(xr, 0)\n    sy = max(yt, 0) + max(yb, 0)\n\n    if (xl <= 0 and xr <= 0) or (yt <= 0 and yb <=0):\n        return leftTop, rightBottom\n    elif leftTop[0] >= 0 and leftTop[1] >= 0 : # left top corner is in box\n        l = min(yb, xr)\n        r = r - l / 2\n        cx = cx - l / 2\n        cy = cy - l / 2\n    elif rightBottom[0] <= width and rightBottom[1] <= height : # right bottom corner is in box\n        l = min(yt, xl)\n        r = r - l / 2\n        cx = cx + l / 2\n        cy = cy + l / 2\n    elif leftTop[0] >= 0 and rightBottom[1] <= height : #left bottom corner is in box\n        l = min(xr, yt)\n        r = r - l  / 2\n        cx = cx - l / 2\n        cy = cy + l / 2\n    elif rightBottom[0] <= width and leftTop[1] >= 0 : #right top corner is in box\n        l = min(xl, yb)\n        r = r - l / 2\n        cx = cx + l / 2\n        cy = cy - l / 2\n    elif xl < 0 or xr < 0 or yb < 0 or yt < 0:\n        return leftTop, rightBottom\n    elif sx >= sy:\n        sx = max(xl, 0) + max(0, xr)\n        sy = max(yt, 0) + max(0, yb)\n        # cy = height / 2\n        if yt >= 0 and yb >= 0:\n            cy = height / 2\n        elif yt >= 0:\n            cy = cy + sy / 2\n        else:\n            cy = cy - sy / 2\n        r = r - sy / 2\n\n        if xl >= sy / 2 and xr >= sy / 2:\n            pass\n        elif xl < sy / 2:\n            cx = cx - (sy / 2 - xl)\n        else:\n            cx = cx + (sy / 2 - xr)\n    elif sx < sy:\n        cx = width / 2\n        r = r - sx / 2\n        if yt >= sx / 2 and yb >= sx / 2:\n            pass\n        elif yt < sx / 2:\n            cy = cy - (sx / 2 - yt)\n        else:\n            cy = cy + (sx / 2 - yb)\n\n\n    return [cx - r, cy - r], [cx + r, cy + r]\n\ndef off_set_pts(keyPoints, leftTop):\n    result = keyPoints.copy()\n    result[:, 0] -= leftTop[0]\n    result[:, 1] -= leftTop[1]\n    return result\n\n'''\n    cut the image, by expanding a bounding box\n'''\ndef cut_image(originImage, kps, expand_ratio, leftTop, rightBottom,cam=None,centralize=False):\n\n    original_shape = originImage.shape\n    height       = originImage.shape[0]\n    width        = originImage.shape[1]\n    channels     = originImage.shape[2] if len(originImage.shape) >= 3 else 1\n    leftTop[0] = max(0, leftTop[0])\n    leftTop[1] = max(0, leftTop[1])\n\n    leftTop, rightBottom = get_image_cut_box(leftTop, rightBottom, expand_ratio)\n\n    lt = [int(leftTop[0]), int(leftTop[1])]\n    rb = [int(rightBottom[0]), int(rightBottom[1])]\n\n    lt[0] = max(0, lt[0])\n    lt[1] = max(0, lt[1])\n    rb[0] = min(rb[0], width)\n    rb[1] = min(rb[1], height)\n\n    leftTop      = np.array([int(leftTop[0]), int(leftTop[1])])\n    rightBottom  = np.array([int(rightBottom[0] + 0.5), int(rightBottom[1] + 0.5)])\n\n    length = max(rightBottom[1] - leftTop[1]+1, rightBottom[0] - leftTop[0]+1)\n    if length<20:\n        return False,False,False\n\n    dstImage = np.zeros(shape = [length,length, channels], dtype = np.uint8)\n    dstImage[:,:,:] = 0\n\n    offset = np.array([lt[0] - leftTop[0], lt[1] - leftTop[1]])\n    size   = [rb[0] - lt[0], rb[1] - lt[1]]\n\n    try:\n        dstImage[offset[1]:size[1] + offset[1], offset[0]:size[0] + offset[0], :] = originImage[lt[1]:rb[1], lt[0]:rb[0],:]\n    except Exception as error:\n        return False,False,False\n\n    if cam is not None:\n        cam[1] = (cam[1]+1.0)*float(original_shape[1])/float(length)-2.0*float(leftTop[0])/float(length)-1.0\n        cam[2] = (cam[2]+1.0)*float(original_shape[0])/float(length)-2.0*float(leftTop[1])/float(length)-1.0\n        cam[0] *= original_shape[0]/length\n\n        return dstImage, off_set_pts(kps, leftTop),cam,(offset,lt,rb,size,original_shape[:2])\n\n    return dstImage, off_set_pts(kps, leftTop),(offset,lt,rb,size,original_shape[:2])\n\ndef getltrb(expand_ratio, leftTop, rightBottom,height,width,kp2d):\n    inimage = (kp2d<0).sum()\n    inimage += (kp2d[:,0]>320).sum()\n    inimage += (kp2d[:,1]>240).sum()\n    if inimage>0:\n        return True\n    originImage = np.zeros((240,320,3))\n    original_shape = originImage.shape\n    height       = originImage.shape[0]\n    width        = originImage.shape[1]\n    channels     = originImage.shape[2] if len(originImage.shape) >= 3 else 1\n    leftTop, rightBottom = get_image_cut_box(leftTop, rightBottom, expand_ratio)\n\n    lt = [int(leftTop[0]), int(leftTop[1])]\n    rb = [int(rightBottom[0]), int(rightBottom[1])]\n\n    lt[0] = max(0, lt[0])\n    lt[1] = max(0, lt[1])\n    rb[0] = min(rb[0], width)\n    rb[1] = min(rb[1], height)\n\n    h = float(rb[1]-lt[1])\n    w = float(rb[0]-lt[0])\n\n    leftTop      = [int(leftTop[0]), int(leftTop[1])]\n    rightBottom  = [int(rightBottom[0] + 0.5), int(rightBottom[1] + 0.5)]\n\n    length = max(rightBottom[1] - leftTop[1]+1, rightBottom[0] - leftTop[0]+1)\n\n    dstImage = np.zeros(shape = [length,length, channels], dtype = np.uint8)\n    dstImage[:,:,:] = 0\n\n    offset = [lt[0] - leftTop[0], lt[1] - leftTop[1]]\n    size   = [rb[0] - lt[0], rb[1] - lt[1]]\n\n    try:\n        dstImage[offset[1]:size[1] + offset[1], offset[0]:size[0] + offset[0], :] = originImage[lt[1]:rb[1], lt[0]:rb[0],:]\n    except:\n        print('error in image crop')\n        return True\n    mask = np.ones((240,320))\n\n    if mask is not None:\n        dstmask = np.zeros(shape = [length, length], dtype = np.uint8)\n        dstmask[:,:] = 0\n        try:\n            dstmask[offset[1]:size[1] + offset[1], offset[0]:size[0] + offset[0]] = mask[lt[1]:rb[1], lt[0]:rb[0]]\n        except:\n            print('error in mask crop')\n            return True\n\n    if h<4 or w<4:\n        return True\n    else:\n        return False\n\ndef reflect_lsp_kp(kps):\n    kp_map = [5, 4, 3, 2, 1, 0, 11, 10, 9, 8, 7, 6, 12, 13]\n    joint_ref = kps[kp_map]\n    joint_ref[:,0] = -joint_ref[:,0]\n\n    return joint_ref - np.mean(joint_ref, axis = 0)\n\ndef reflect_pose(poses):\n    swap_inds = np.array([\n            0, 1, 2, 6, 7, 8, 3, 4, 5, 9, 10, 11, 15, 16, 17, 12, 13, 14, 18,\n            19, 20, 24, 25, 26, 21, 22, 23, 27, 28, 29, 33, 34, 35, 30, 31, 32,\n            36, 37, 38, 42, 43, 44, 39, 40, 41, 45, 46, 47, 51, 52, 53, 48, 49,\n            50, 57, 58, 59, 54, 55, 56, 63, 64, 65, 60, 61, 62, 69, 70, 71, 66,\n            67, 68\n    ])\n\n    sign_flip = np.array([\n            1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1,\n            -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1,\n            -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1,\n            1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1,\n            -1, 1, -1, -1\n    ])\n\n    return poses[swap_inds] * sign_flip\n\ndef crop_image(image_path, angle, lt, rb, scale, kp_2d, crop_size):\n    '''\n        given a crop box, expand it at 4 directions.(left, right, top, bottom)\n    '''\n    assert 'error algorithm exist.' and 0\n\n    def _expand_crop_box(lt, rb, scale):\n        center = (lt + rb) / 2.0\n        xl, xr, yt, yb = lt[0] - center[0], rb[0] - center[0], lt[1] - center[1], rb[1] - center[1]\n        xl, xr, yt, yb = xl * scale[0], xr * scale[1], yt * scale[2], yb * scale[3]\n        #expand it\n        lt, rb = np.array([center[0] + xl, center[1] + yt]), np.array([center[0] + xr, center[1] + yb])\n        lb, rt = np.array([center[0] + xl, center[1] + yb]), np.array([center[0] + xr, center[1] + yt])\n        center = (lt + rb) / 2\n        return center, lt, rt, rb, lb\n\n    def _extend_box(center, lt, rt, rb, lb, crop_size):\n        lx, ly = np.linalg.norm(rt - lt), np.linalg.norm(lb - lt)\n        dx, dy = (rt - lt) / lx, (lb - lt) / ly\n        l = max(lx, ly) / 2.0\n        return center - l * dx - l * dy, center + l * dx - l *dy, center + l * dx + l * dy, center - l * dx + l * dy, dx, dy, crop_size * 1.0 / l\n\n    def _get_sample_points(lt, rt, rb, lb, crop_size):\n        vec_x = rt - lt\n        vec_y = lb - lt\n        i_x, i_y = np.meshgrid(range(crop_size), range(crop_size))\n        i_x = i_x.astype(np.float)\n        i_y = i_y.astype(np.float)\n        i_x /= float(crop_size)\n        i_y /= float(crop_size)\n        interp_points = i_x[..., np.newaxis].repeat(2, axis=2) * vec_x + i_y[..., np.newaxis].repeat(2, axis=2) * vec_y\n        interp_points += lt\n        return interp_points\n\n    def _sample_image(src_image, interp_points):\n        sample_method = 'nearest'\n        interp_image = np.zeros((interp_points.shape[0] * interp_points.shape[1], src_image.shape[2]))\n        i_x = range(src_image.shape[1])\n        i_y = range(src_image.shape[0])\n        flatten_interp_points = interp_points.reshape([interp_points.shape[0]*interp_points.shape[1], 2])\n        for i_channel in range(src_image.shape[2]):\n            interp_image[:, i_channel] = interpolate.interpn((i_y, i_x), src_image[:, :, i_channel],\n                                                            flatten_interp_points[:, [1, 0]], method = sample_method,\n                                                            bounds_error=False, fill_value=0)\n        interp_image = interp_image.reshape((interp_points.shape[0], interp_points.shape[1], src_image.shape[2]))\n\n        return interp_image\n\n    def _trans_kp_2d(kps, center, dx, dy, lt, ratio):\n        kp2d_offset = kps[:, :2] - center\n        proj_x, proj_y = np.dot(kp2d_offset, dx), np.dot(kp2d_offset, dy)\n        for idx in range(len(kps)):\n            kps[idx, :2] = (dx * proj_x[idx] + dy * proj_y[idx] + lt) * ratio\n        return kps\n\n\n    src_image = cv2.imread(image_path)\n\n    center, lt, rt, rb, lb  = _expand_crop_box(lt, rb, scale)\n\n    #calc rotated box\n    radian = angle * np.pi / 180.0\n    v_sin, v_cos = math.sin(radian), math.cos(radian)\n\n    rot_matrix = np.array([[v_cos, v_sin],[-v_sin, v_cos]])\n\n    n_corner = (np.dot(rot_matrix, np.array([lt - center, rt - center, rb - center, lb - center]).T).T) + center\n    n_lt, n_rt, n_rb, n_lb = n_corner[0], n_corner[1], n_corner[2], n_corner[3]\n\n    lt, rt, rb, lb = calc_obb(np.array([lt, rt, rb, lb, n_lt, n_rt, n_rb, n_lb]))\n    lt, rt, rb, lb, dx, dy, ratio = _extend_box(center, lt, rt, rb, lb, crop_size = crop_size)\n    s_pts = _get_sample_points(lt, rt, rb, lb, crop_size)\n    dst_image = _sample_image(src_image, s_pts)\n    kp_2d = _trans_kp_2d(kp_2d, center, dx, dy, lt, ratio)\n\n    return dst_image, kp_2d\n\ndef flip_image(src_image, kps, mask=None):\n    h, w = src_image.shape[0], src_image.shape[1]\n    src_image = cv2.flip(src_image, 1)\n\n    kps[:, 0] = w - 1 - kps[:, 0]\n    kp_map = [5, 4, 3, 2, 1, 0, 11, 10, 9, 8, 7, 6, 12, 13]\n    kps[:, :] = kps[kp_map]\n    if mask is None:\n        return src_image, kps\n    mask = cv2.flip(mask, 1)\n    return src_image, kps, mask\n\n# Visualization func.\n\ndef draw_lsp_14kp__bone(src_image, pts):\n        bones = [\n            [0, 1, 255, 0, 0],\n            [1, 2, 255, 0, 0],\n            [2, 12, 255, 0, 0],\n            [3, 12, 0, 0, 255],\n            [3, 4, 0, 0, 255],\n            [4, 5, 0, 0, 255],\n            [12, 9, 0, 0, 255],\n            [9,10, 0, 0, 255],\n            [10,11, 0, 0, 255],\n            [12, 8, 255, 0, 0],\n            [8,7, 255, 0, 0],\n            [7,6, 255, 0, 0],\n            [12, 13, 0, 255, 0]\n        ]\n\n        for pt in pts:\n            src_image = cv2.circle(src_image,(int(pt[0]), int(pt[1])),2,(0,255,255),-1)\n        if pts.shape[0]!=14:\n            return src_image\n        for line in bones:\n            pa = pts[line[0]]\n            pb = pts[line[1]]\n            if (pa>0).all() and (pb>0).all():\n                xa,ya,xb,yb = int(pa[0]),int(pa[1]),int(pb[0]),int(pb[1])\n                src_image = cv2.line(src_image,(xa,ya),(xb,yb),(line[2], line[3], line[4]),2)\n        return src_image\n\ndef plot_mesh(vertices, triangles, subplot = [1,1,1], title = 'mesh', el = 90, az = -90, lwdt=.1, dist = 6, color = \"blue\"):\n    '''\n    plot the mesh\n    Args:\n        vertices: [nver, 3]\n        triangles: [ntri, 3]\n    '''\n    ax = plt.subplot(subplot[0], subplot[1], subplot[2], projection = '3d')\n    ax.plot_trisurf(vertices[:, 0], vertices[:, 1], vertices[:, 2], triangles = triangles, lw = lwdt, color = color, alpha = 1)\n    ax.axis(\"off\")\n    ax.view_init(elev = el, azim = az)\n    ax.dist = dist\n    plt.title(title)\n    return plt\n\ndef plot_3d_points(points, color = 'r', save_path='test.png'):\n\n    x, y, z = points[:,0], points[:,1],points[:,2]\n    ax = plt.subplot(111, projection='3d')\n    ax.scatter(x, y, z, c=color)\n\n    ax.set_zlabel('Z')\n    ax.set_ylabel('Y')\n    ax.set_xlabel('X')\n    plt.savefig(save_path)\n\ndef plot_3d_points_set(points_set, colors = ['r'], save_path='test.png'):\n    ax = plt.subplot(111, projection='3d')\n    for points,color in zip(points_set,colors):\n        x, y, z = points[:,0], points[:,1],points[:,2]\n        ax.scatter(x, y, z, c=color)\n\n    ax.set_zlabel('Z')\n    ax.set_ylabel('Y')\n    ax.set_xlabel('X')\n    plt.savefig(save_path)\n\ndef show3Dpose(kp3ds, lcolor=[\"#3498db\"], rcolor=[\"#e74c3c\"], save_path='test.png',skeleton_type='lsp'): # blue, orange\n  \"\"\"\n  Visualize a 3d skeleton\n  Args\n    kp3d: kp_num x 3 vector.\n    ax: matplotlib 3d axis to draw on\n    lcolor: color for left part of the body\n    rcolor: color for right part of the body\n    add_labels: whether to add coordinate labels\n  Returns\n    Nothing. Draws on ax.\n  \"\"\"\n\n  #I   = np.array([1,2,3,1,7,8,1, 13,14,15,14,18,19,14,26,27])-1 # start points\n  #J   = np.array([2,3,4,7,8,9,13,14,15,16,18,19,20,26,27,28])-1 # end points\n  #LR  = np.array([1,1,1,0,0,0,0, 0, 0, 0, 0, 0, 0, 1, 1, 1], dtype=bool)#1-left 0-right\n  if skeleton_type=='lsp':\n    I   = np.array([0,1,2,  5,4,3,  6,7,8,  11,10, 9,  12]) # start points\n    J   = np.array([1,2,12, 4,3,12, 7,8,12, 10, 9,12,  13]) # end points\n    LR  = np.array([0,0,0,  1,1,1,  0,0,0,   1, 1, 1,   0], dtype=bool)#1-left 0-right\n  elif skeleton_type=='smpl':\n    I   = np.array([0,0,1,  2,4,5,  0, 12,12,  12,16,17,  18,19]) # start points\n    J   = np.array([1,2,4,  5,7,8,  12,15,16,  17,18,19,  20,21]) # end points\n    LR  = np.array([1,0,1,  0,1,0,  0,  0, 1,   0, 1, 0,   1, 0], dtype=bool)#1-left 0-right\n\n  for idx,kp3d in enumerate(kp3ds):\n      ax = plt.subplot(1,len(kp3ds),idx+1, projection='3d')\n      for i in np.arange( len(I) ):\n          x, y, z = [np.array( [kp3d[I[i], j], kp3d[J[i], j]] ) for j in range(3)]\n          ax.plot(z, x, -y, lw=2, c=lcolor[idx] if LR[i] else rcolor[idx])\n\n          RADIUS = 1 # space around the subject\n          xroot, yroot, zroot = 0,0,0#(kp3d[2,0]+kp3d[3,0], kp3d[0,1], kp3d[0,2]\n          ax.set_xlim3d([-RADIUS+xroot, RADIUS+xroot])\n          ax.set_zlim3d([-RADIUS+zroot, RADIUS+zroot])\n          ax.set_ylim3d([-RADIUS+yroot, RADIUS+yroot])\n\n          ax.set_xlabel(\"x\")\n          ax.set_ylabel(\"y\")\n          ax.set_zlabel(\"z\")\n\n          # Get rid of the ticks and tick labels\n          ax.set_xticks([])\n          ax.set_yticks([])\n          ax.set_zticks([])\n\n          ax.get_xaxis().set_ticklabels([])\n          ax.get_yaxis().set_ticklabels([])\n          ax.set_zticklabels([])\n          ax.set_aspect('equal')\n\n          # Get rid of the panes (actually, make them white)\n          white = (1.0, 1.0, 1.0, 0.0)\n          ax.w_xaxis.set_pane_color(white)\n          ax.w_yaxis.set_pane_color(white)\n          # Keep z pane\n\n          # Get rid of the lines in 3d\n          ax.w_xaxis.line.set_color(white)\n          ax.w_yaxis.line.set_color(white)\n          ax.w_zaxis.line.set_color(white)\n\n  plt.savefig(save_path)\n\ndef show2Dpose(channels, ax, lcolor=\"#3498db\", rcolor=\"#e74c3c\", add_labels=False):\n  \"\"\"\n  Visualize a 2d skeleton\n  Args\n    channels: 64x1 vector. The pose to plot.\n    ax: matplotlib axis to draw on\n    lcolor: color for left part of the body\n    rcolor: color for right part of the body\n    add_labels: whether to add coordinate labels\n  Returns\n    Nothing. Draws on ax.\n  \"\"\"\n\n  assert channels.size == len(data_utils.H36M_NAMES)*2, \"channels should have 64 entries, it has %d instead\" % channels.size\n  vals = np.reshape( channels, (len(data_utils.H36M_NAMES), -1) )\n\n  I  = np.array([1,2,3,1,7,8,1, 13,14,14,18,19,14,26,27])-1 # start points\n  J  = np.array([2,3,4,7,8,9,13,14,16,18,19,20,26,27,28])-1 # end points\n  LR = np.array([1,1,1,0,0,0,0, 0, 0, 0, 0, 0, 1, 1, 1], dtype=bool)\n\n  # Make connection matrix\n  for i in np.arange( len(I) ):\n    x, y = [np.array( [vals[I[i], j], vals[J[i], j]] ) for j in range(2)]\n    ax.plot(x, y, lw=2, c=lcolor if LR[i] else rcolor)\n\n  # Get rid of the ticks\n  ax.set_xticks([])\n  ax.set_yticks([])\n\n  # Get rid of tick labels\n  ax.get_xaxis().set_ticklabels([])\n  ax.get_yaxis().set_ticklabels([])\n\n  RADIUS = 350 # space around the subject\n  xroot, yroot = vals[0,0], vals[0,1]\n  ax.set_xlim([-RADIUS+xroot, RADIUS+xroot])\n  ax.set_ylim([-RADIUS+yroot, RADIUS+yroot])\n  if add_labels:\n    ax.set_xlabel(\"x\")\n    ax.set_ylabel(\"z\")\n\n  ax.set_aspect('equal')\n\ndef fig2data ( fig ):\n    \"\"\"\n    @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it\n    @param fig a matplotlib figure\n    @return a numpy 3D array of RGBA values\n    \"\"\"\n    # draw the renderer\n    fig.canvas.draw ( )\n\n    # Get the RGBA buffer from the figure\n    w,h = fig.canvas.get_width_height()\n    buf = numpy.fromstring ( fig.canvas.tostring_argb(), dtype=numpy.uint8 )\n    buf.shape = ( w, h,4 )\n\n    # canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode\n    buf = numpy.roll ( buf, 3, axis = 2 )\n    return buf\n\n\ndef line_intersect(sa, sb):\n    al, ar, bl, br = sa[0], sa[1], sb[0], sb[1]\n    assert al <= ar and bl <= br\n    if al >= br or bl >= ar:\n        return False\n    return True\n\n'''\n    return whether two rectangle intersect\n    ra, rb left_top point, right_bottom point\n'''\ndef rectangle_intersect(ra, rb):\n    ax = [ra[0][0], ra[1][0]]\n    ay = [ra[0][1], ra[1][1]]\n\n    bx = [rb[0][0], rb[1][0]]\n    by = [rb[0][1], rb[1][1]]\n\n    return line_intersect(ax, bx) and line_intersect(ay, by)\n\ndef get_intersected_rectangle(lt0, rb0, lt1, rb1):\n    if not rectangle_intersect([lt0, rb0], [lt1, rb1]):\n        return None, None\n\n    lt = lt0.copy()\n    rb = rb0.copy()\n\n    lt[0] = max(lt[0], lt1[0])\n    lt[1] = max(lt[1], lt1[1])\n\n    rb[0] = min(rb[0], rb1[0])\n    rb[1] = min(rb[1], rb1[1])\n    return lt, rb\n\ndef get_union_rectangle(lt0, rb0, lt1, rb1):\n    lt = lt0.copy()\n    rb = rb0.copy()\n\n    lt[0] = min(lt[0], lt1[0])\n    lt[1] = min(lt[1], lt1[1])\n\n    rb[0] = max(rb[0], rb1[0])\n    rb[1] = max(rb[1], rb1[1])\n    return lt, rb\n\ndef get_rectangle_area(lt, rb):\n    return (rb[0] - lt[0]) * (rb[1] - lt[1])\n\ndef get_rectangle_intersect_ratio(lt0, rb0, lt1, rb1):\n    (lt0, rb0), (lt1, rb1) = get_intersected_rectangle(lt0, rb0, lt1, rb1), get_union_rectangle(lt0, rb0, lt1, rb1)\n\n    if lt0 is None:\n        return 0.0\n    else:\n        return 1.0 * get_rectangle_area(lt0, rb0) / get_rectangle_area(lt1, rb1)\n\ndef convert_image_by_pixformat_normalize(src_image, pix_format, normalize):\n    if pix_format == 'NCHW':\n        src_image = src_image.transpose((2, 0, 1))\n\n    if normalize:\n        src_image = (src_image.astype(np.float) / 255) * 2.0 - 1.0\n\n    return src_image\n\ndef align_by_root(joints):\n    root_id = 0\n    pelvis = joints[:, root_id, :]\n    return joints - torch.unsqueeze(pelvis, dim=1)\n'''\n    align ty pelvis\n    joints: n x 14 x 3, by lsp order\n'''\ndef align_by_pelvis(joints):\n    left_id = 3\n    right_id = 2\n    pelvis = (joints[:, left_id, :] + joints[:, right_id, :]) / 2.0\n    return joints - torch.unsqueeze(pelvis, dim=1)\n\ndef align_by_pelvis_single(joints, get_pelvis=False):\n    \"\"\"\n    Assumes joints is 14 x 3 in LSP order.\n    Then hips are: [3, 2]\n    Takes mid point of these points, then subtracts it.\n    \"\"\"\n    left_id = 3\n    right_id = 2\n\n    pelvis = (joints[left_id, :] + joints[right_id, :]) / 2.\n    if get_pelvis:\n        return joints - np.expand_dims(pelvis, axis=0), pelvis\n    else:\n        return joints - np.expand_dims(pelvis, axis=0)\n\ndef copy_state_dict(cur_state_dict, pre_state_dict, prefix = ''):\n    def _get_params(key):\n        key = prefix + key\n        if key in pre_state_dict:\n            return pre_state_dict[key]\n        return None\n\n    for k in cur_state_dict.keys():\n        v = _get_params(k)\n        try:\n            if v is None:\n                print('parameter {} not found'.format(k))\n                continue\n            cur_state_dict[k].copy_(v)\n        except:\n            print('copy param {} failed'.format(k))\n            continue\n\n# IO functions\n\ndef save_pkl(info,name='../data/info.pkl'):\n    check_file_and_remake(name.replace(os.path.basename(name),''))\n    if name[-4:] !='.pkl':\n        name += '.pkl'\n    with open(name,'wb') as outfile:\n        pickle.dump(info, outfile, pickle.HIGHEST_PROTOCOL)\ndef read_pkl(name = '../data/info.pkl'):\n    with open(name,'rb') as f:\n        return pickle.load(f)\ndef read_pkl_coding(name = '../data/info.pkl'):\n    with open(name, 'rb') as f:\n        u = pickle._Unpickler(f)\n        u.encoding = 'latin1'\n        p = u.load()\n    return p\ndef check_file_and_remake(path,remove=False):\n    if remove:\n        if os.path.isdir(path):\n            shutil.rmtree(path)\n    if not os.path.isdir(path):\n        os.makedirs(path)\n\ndef save_h5(info,name):\n    check_file_and_remake(name.replace(os.path.basename(name),''))\n    if name[-3:] !='.h5':\n        name += '.h5'\n    f=h5py.File(name,'w')\n    for item, value in info.items():\n        f[item] = value\n    f.close()\n\ndef read_h5(name):\n    if name[-3:] !='.h5':\n        name += '.h5'\n    f=h5py.File(name,'r')\n    info = {}\n    for item, value in f.items():\n        info[item] = np.array(value)\n    f.close()\n    return info\n\ndef h36m32_2_lsp14(h36m32):\n    relation = [3,2,1,6,7,8,27,26,25,17,18,19,13,15]\n    lsp14 = h36m32[:,relation,:]\n    return lsp14\n", "meta": {"hexsha": "f7f05b2d8463e1859d23a4e796175c69f1888a25", "size": 34198, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/utils/util.py", "max_stars_repo_name": "DianaTaukin/DSD-SATN", "max_stars_repo_head_hexsha": "5a4ab5e3cfcb00e72ca27cf5ec10a8d8e29ef312", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 71, "max_stars_repo_stars_event_min_datetime": "2020-04-06T08:23:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T03:40:11.000Z", "max_issues_repo_path": "src/utils/util.py", "max_issues_repo_name": "DianaTaukin/DSD-SATN", "max_issues_repo_head_hexsha": "5a4ab5e3cfcb00e72ca27cf5ec10a8d8e29ef312", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-04-11T14:45:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T04:44:13.000Z", "max_forks_repo_path": "src/utils/util.py", "max_forks_repo_name": "DianaTaukin/DSD-SATN", "max_forks_repo_head_hexsha": "5a4ab5e3cfcb00e72ca27cf5ec10a8d8e29ef312", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-05-19T12:18:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:04:27.000Z", "avg_line_length": 32.6628462273, "max_line_length": 145, "alphanum_fraction": 0.5645651793, "include": true, "reason": "import numpy,from scipy", "num_tokens": 11645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.178852236638393}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 25 00:14:34 2021\n\n@author: dv516\n\"\"\"\n\nimport numpy as np\nimport pickle\n\nimport pyro\npyro.enable_validation(True)  # can help with debugging\npyro.set_rng_seed(1)\n\nfrom algorithms.PyBobyqa_wrapped.Wrapper_for_pybobyqa import PyBobyqaWrapper\nfrom algorithms.Bayesian_opt_Pyro.utilities_full import BayesOpt\nfrom algorithms.nesterov_random.nesterov_random import nesterov_random\nfrom algorithms.simplex.simplex_method import simplex_method\nfrom algorithms.CUATRO.CUATRO import CUATRO\nfrom algorithms.Finite_differences.Finite_differences import finite_Diff_Newton\nfrom algorithms.Finite_differences.Finite_differences import Adam_optimizer\nfrom algorithms.Finite_differences.Finite_differences import BFGS_optimizer\nfrom algorithms.SQSnobfit_wrapped.Wrapper_for_SQSnobfit import SQSnobFitWrapper\nfrom algorithms.DIRECT_wrapped.Wrapper_for_Direct import DIRECTWrapper\n\nfrom case_studies.Controller_tuning.Control_system import phi\n\nimport matplotlib.pyplot as plt\n\n\ndef average_from_list(solutions_list):\n    N = len(solutions_list)\n    f_best_all = np.zeros((N, 100))\n    for i in range(N):\n        f_best = np.array(solutions_list[i]['f_best_so_far'])\n        x_ind = np.array(solutions_list[i]['samples_at_iteration'])\n        for j in range(100):\n            ind = np.where(x_ind <= j+1)\n            if len(ind[0]) == 0:\n                f_best_all[i, j] = f_best[0]\n            else:\n                f_best_all[i, j] = f_best[ind][-1]\n    f_median = np.median(f_best_all, axis = 0)\n    # f_av = np.average(f_best_all, axis = 0)\n    # f_std = np.std(f_best_all, axis = 0)\n    f_min = np.min(f_best_all, axis = 0)\n    f_max = np.max(f_best_all, axis = 0)\n    return f_best_all, f_median, f_min, f_max\n\ndef fix_starting_points(complete_list, x0, init_out, only_starting_point = False):\n    if only_starting_point:\n        for i in range(len(complete_list)):\n            dict_out = complete_list[i]\n            f_arr = dict_out['f_best_so_far']\n            N_eval = len(f_arr)\n            g_arr = dict_out['g_best_so_far']\n            dict_out['x_best_so_far'][0] = np.array(x0)\n            dict_out['f_best_so_far'][0] = init_out[0]\n            dict_out['g_best_so_far'][0] = np.array(init_out[1])\n            complete_list[i] = dict_out        \n    else:\n        for i in range(len(complete_list)):\n            dict_out = complete_list[i]\n            f_arr = dict_out['f_best_so_far']\n            N_eval = len(f_arr)\n            g_arr = dict_out['g_best_so_far']\n            dict_out['x_best_so_far'][0] = np.array(x0)\n            dict_out['f_best_so_far'][0] = init_out[0]\n            dict_out['g_best_so_far'][0] = np.array(init_out[1])\n        \n            for j in range(1, N_eval):\n                if (g_arr[j] > 1e-3).any() or (init_out[0] < f_arr[j]):\n                    dict_out['x_best_so_far'][j] = np.array(x0)\n                    dict_out['f_best_so_far'][j] = init_out[0]\n                    dict_out['g_best_so_far'][j] = np.array(init_out[1])\n            complete_list[i] = dict_out\n            \n    return complete_list\n\ndef plot_sys_resp(pi, plot, method, x0 = [15, 15], xref = [10, 10], N=200, T=3):\n    _, sys_resp, control_resp = phi(pi, x0 = x0, N = N, \\\n                                    T = T, return_sys_resp = True)\n    ax1, ax2 = plot\n    x1 = np.array(sys_resp)[:,0] ; x2 = np.array(sys_resp)[:,1]\n    u1 = np.array(control_resp)[:,0] ; u2 = np.array(control_resp)[:,1]\n    ax1.plot(np.arange(len(x1))/len(x1)*T, x1, label = method + ': $x_1$')\n    # ax1.plot([0, T], [10, 10], '--k', label = 'Steady-state for $x_1$ and $x_2$')\n    ax1.plot(np.arange(len(x2))/len(x2)*T, x2, label =  method + ': $x_2$')\n    ax2.plot(np.arange(len(u1))/len(u1)*T, u1, label = method + ': $u_1$')\n    ax2.plot(np.arange(len(u1))/len(u1)*T, u2, label = method + ': $u_2$')\n    return ax1, ax2\n\nx0 = np.array([4, 4, 4, 4])\nbounds = np.array([[0, 8], [0, 8], [0, 8], [0, 8]])\n\nmax_f_eval = 100\n\ninitial_output = phi(x0)\n\nContrLin_pybobyqa = PyBobyqaWrapper().solve(phi, x0, bounds=bounds.T, \\\n                                      maxfun= max_f_eval, constraints=1, \\\n                                      seek_global_minimum = True, \\\n                                      objfun_has_noise=False)\n\n\nN = 10\nContrLin_Nest_list = []\nfor i in range(N):\n    rnd_seed = i\n    ContrLin_Nest = nesterov_random(phi, x0, bounds, max_iter = 100, \\\n                          constraints = 1, rnd_seed = i, alpha = 1e-5, mu = 1e-1, max_f_eval= max_f_eval)\n    ContrLin_Nest_list.append(ContrLin_Nest)\nprint('10 Nesterov iterations completed')\n\nN = 10\nContrLin_simplex_list = []\nfor i in range(N):\n    rnd_seed = i\n    ContrLin_simplex = simplex_method(phi, x0, bounds, max_iter = 100, \\\n                            constraints = 1, rnd_seed = i, max_f_eval= max_f_eval)\n    ContrLin_simplex_list.append(ContrLin_simplex)\nprint('10 simplex iterations completed')\n\nContrLin_FiniteDiff = finite_Diff_Newton(phi, x0, bounds = bounds, \\\n                                    con_weight = 100, check_bounds = True)\n    \nContrLin_BFGS = BFGS_optimizer(phi, x0, bounds = bounds, \\\n                          con_weight = 100, check_bounds = True)\n    \nContrLin_Adam = Adam_optimizer(phi, x0, method = 'forward', \\\n                                      bounds = bounds, alpha = 0.4, \\\n                                      beta1 = 0.2, beta2  = 0.1, \\\n                                      max_f_eval = 100, con_weight = 100, \\\n                                      check_bounds = True)\n    \nN_min_s = 15\ninit_radius = 4\nmethod = 'Discrimination'\nN = 10\nContrLin_CUATRO_global_list = []\nfor i in range(N):\n    rnd_seed = i\n    ContrLin_CUATRO_global = CUATRO(phi, x0, init_radius, bounds = bounds, \\\n                          N_min_samples = N_min_s, tolerance = 1e-10,\\\n                          beta_red = 0.9, rnd = rnd_seed, method = 'global', \\\n                          constr_handling = method)\n    ContrLin_CUATRO_global_list.append(ContrLin_CUATRO_global)\nprint('10 CUATRO global iterations completed')    \n    \nN_min_s = 6\ninit_radius = 0.5\nmethod = 'Fitting'\nN = 10\nContrLin_CUATRO_local_list = []\nfor i in range(N):\n    rnd_seed = i\n    ContrLin_CUATRO_local = CUATRO(phi, x0, init_radius, bounds = bounds, \\\n                          N_min_samples = N_min_s, tolerance = 1e-10,\\\n                          beta_red = 0.9, rnd = rnd_seed, method = 'local', \\\n                          constr_handling = method)\n    ContrLin_CUATRO_local_list.append(ContrLin_CUATRO_local)\nprint('10 CUATRO local iterations completed') \n\nN = 10\nContrLin_SQSnobFit_list = []\nfor i in range(N):\n    try:\n        ContrLin_SQSnobFit = SQSnobFitWrapper().solve(phi, x0, bounds, \\\n                                    maxfun = max_f_eval, constraints=1)\n        ContrLin_SQSnobFit_list.append(ContrLin_SQSnobFit)\n    except:\n        print('SQSnobfit iteration ', i, ' failed')\nprint('10 SnobFit iterations completed') \n\nN = 10\nContrLin_DIRECT_list = []\nContrLin_DIRECT_f = lambda x, grad:phi(x)\nfor i in range(N):\n    ContrLin_DIRECT =  DIRECTWrapper().solve(ContrLin_DIRECT_f, x0, bounds, \\\n                                    maxfun = max_f_eval, constraints=1)\n    ContrLin_DIRECT_list.append(ContrLin_DIRECT)\nprint('10 DIRECT iterations completed')     \n\nwith open('BayesContrLin_list.pickle', 'rb') as handle:\n    ContrLin_Bayes_list = pickle.load(handle)\n\nContrLin_Bayes_list = fix_starting_points(ContrLin_Bayes_list, x0, initial_output)\nContrLin_DIRECT_list = fix_starting_points(ContrLin_DIRECT_list, x0, initial_output)\nContrLin_simplex_list = fix_starting_points(ContrLin_simplex_list, x0, initial_output)\nContrLin_pybobyqa['x_best_so_far'][0] = np.array(x0)\nContrLin_pybobyqa['f_best_so_far'][0] = initial_output[0]\nContrLin_pybobyqa['g_best_so_far'][0] = np.array(initial_output[1])\n\nplt.rcParams[\"font.family\"] = \"Times New Roman\"\nft = int(15)\nfont = {'size': ft}\nplt.rc('font', **font)\nparams = {'legend.fontsize': 12.5,\n              'legend.handlelength': 2}\nplt.rcParams.update(params)\n\n\nx_best_pyBbyqa = np.array(ContrLin_pybobyqa['x_best_so_far'])\nf_best_pyBbyqa = np.array(ContrLin_pybobyqa['f_best_so_far'])\n# x_ind_pyBbyqa = np.array(RB_pybobyqa['samples_at_iteration'])\n# nbr_feval_pyBbyqa = len(RB_pybobyqa['f_store'])\n\nx_best_finDiff = np.array(ContrLin_FiniteDiff['x_best_so_far'])\nf_best_finDiff = np.array(ContrLin_FiniteDiff['f_best_so_far'])\nx_ind_findDiff = np.array(ContrLin_FiniteDiff['samples_at_iteration'])\n\nx_best_BFGS = np.array(ContrLin_BFGS['x_best_so_far'])\nf_best_BFGS = np.array(ContrLin_BFGS['f_best_so_far'])\nx_ind_BFGS = np.array(ContrLin_BFGS['samples_at_iteration'])\n\nx_best_Adam = np.array(ContrLin_Adam['x_best_so_far'])\nf_best_Adam = np.array(ContrLin_Adam['f_best_so_far'])\nx_ind_Adam = np.array(ContrLin_Adam['samples_at_iteration'])\n\n\nfig1 = plt.figure()\nax1 = fig1.add_subplot()\nax1.step(np.arange(len(f_best_pyBbyqa)), f_best_pyBbyqa, where = 'post', \\\n          label = 'PyBobyqa')\nax1.step(x_ind_findDiff, f_best_finDiff, where = 'post', \\\n          label = 'Newton Fin. Diff.')\nax1.step(x_ind_BFGS, f_best_BFGS, where = 'post', \\\n          label = 'BFGS')\nax1.step(x_ind_Adam, f_best_Adam, where = 'post', \\\n          label = 'Adam')\nax1.set_xlabel('Nbr. of function evaluations')\nax1.set_ylabel('Best function evaluation')\nax1.legend()\nax1.set_yscale('log')\nfig1.savefig('Controller_plots/Controller_Deterministic_Convergence_plot.svg', format = \"svg\")\n\n\n\nfig1 = plt.figure()\nax1 = fig1.add_subplot()\n\nfor i in range(len(ContrLin_CUATRO_global_list)):\n    x_best = np.array(ContrLin_CUATRO_global_list[i]['x_best_so_far'])\n    f_best = np.array(ContrLin_CUATRO_global_list[i]['f_best_so_far'])\n    x_ind = np.array(ContrLin_CUATRO_global_list[i]['samples_at_iteration'])\n    ax1.step(x_ind, f_best, where = 'post', label = 'CUATRO_g'+str(i))\n    # ax1.plot(x_ind, f_best, label = 'CUATRO_g'+str(i))\nax1.legend()\nax1.set_xlabel('Nbr. of function evaluations')\nax1.set_ylabel('Best function evaluation')\nax1.set_yscale('log')\nfig1.savefig('Controller_plots/Controller_CUATROg_Convergence_plot.svg', format = \"svg\")\n\n\nfig1 = plt.figure()\nax1 = fig1.add_subplot()\nfor i in range(len(ContrLin_CUATRO_local_list)):\n    x_best = np.array(ContrLin_CUATRO_local_list[i]['x_best_so_far'])\n    f_best = np.array(ContrLin_CUATRO_local_list[i]['f_best_so_far'])\n    x_ind = np.array(ContrLin_CUATRO_local_list[i]['samples_at_iteration'])\n    ax1.step(x_ind, f_best, where = 'post', label = 'CUATRO_l'+str(i))\n    # ax1.plot(x_ind, f_best, label = 'CUATRO_l'+str(i))\nax1.legend()\nax1.set_xlabel('Nbr. of function evaluations')\nax1.set_ylabel('Best function evaluation')\nax1.set_yscale('log')\nfig1.savefig('Controller_plots/Controller_CUATROl_Convergence_plot.svg', format = \"svg\")\n\nfig1 = plt.figure()\nax1 = fig1.add_subplot()\nfor i in range(len(ContrLin_Bayes_list)):\n    x_best = np.array(ContrLin_Bayes_list[i]['x_best_so_far'])\n    f_best = np.array(ContrLin_Bayes_list[i]['f_best_so_far'])\n    nbr_feval = len(ContrLin_Bayes_list[i]['f_store'])\n    ax1.step(np.arange(len(f_best)), f_best, where = 'post', \\\n          label = 'BO'+str(i))\nax1.legend()\nax1.set_xlabel('Nbr. of function evaluations')\nax1.set_ylabel('Best function evaluation')\nax1.set_yscale('log')\nfig1.savefig('Controller_plots/Controller_BO_Convergence_plot.svg', format = \"svg\")\n\nfig1 = plt.figure()\nax1 = fig1.add_subplot()\nfor i in range(len(ContrLin_simplex_list)):\n    x_best = np.array(ContrLin_simplex_list[i]['x_best_so_far'])\n    f_best = np.array(ContrLin_simplex_list[i]['f_best_so_far'])\n    x_ind = np.array(ContrLin_simplex_list[i]['samples_at_iteration'])\n    ax1.step(x_ind, f_best, where = 'post', label = 'Simplex'+str(i))\nax1.legend()\nax1.set_xlabel('Nbr. of function evaluations')\nax1.set_ylabel('Best function evaluation')\nax1.set_yscale('log')\nfig1.savefig('Controller_plots/Controller_Simplex_Convergence_plot.svg', format = \"svg\")\n\n\n## Change to x_best_So_far\nfig1 = plt.figure()\nax1 = fig1.add_subplot()\nfor i in range(len(ContrLin_Nest_list)):\n    x_best = np.array(ContrLin_Nest_list[i]['x_best_so_far'])\n    f_best = np.array(ContrLin_Nest_list[i]['f_best_so_far'])\n    x_ind = np.array(ContrLin_Nest_list[i]['samples_at_iteration'])\n    ax1.step(x_ind, f_best, where = 'post', label = 'Nest.'+str(i))\nax1.legend()\nax1.set_yscale('log')\nax1.set_xlabel('Nbr. of function evaluations')\nax1.set_ylabel('Best function evaluation')\nfig1.savefig('Controller_plots/Controller_Nesterov_Convergence_plot.svg', format = \"svg\")\n\nfig1 = plt.figure()\nax1 = fig1.add_subplot()\nfor i in range(len(ContrLin_SQSnobFit_list)):\n    x_best = np.array(ContrLin_SQSnobFit_list[i]['x_best_so_far'])\n    f_best = np.array(ContrLin_SQSnobFit_list[i]['f_best_so_far'])\n    x_ind = np.array(ContrLin_SQSnobFit_list[i]['samples_at_iteration'])\n    ax1.step(x_ind, f_best, where = 'post', label = 'SQSnobfit'+str(i))\nax1.legend()\nax1.set_yscale('log')\nax1.set_xlabel('Nbr. of function evaluations')\nax1.set_ylabel('Best function evaluation')\nfig1.savefig('Controller_plots/Controller_SQSnobFit_Convergence_plot.svg', format = \"svg\")\n\n\nfig1 = plt.figure()\nax1 = fig1.add_subplot()\nfor i in range(len(ContrLin_DIRECT_list)):\n    x_best = np.array(ContrLin_DIRECT_list[i]['x_best_so_far'])\n    f_best = np.array(ContrLin_DIRECT_list[i]['f_best_so_far'])\n    x_ind = np.array(ContrLin_DIRECT_list[i]['samples_at_iteration'])\n    ax1.step(x_ind, f_best, where = 'post', label = 'DIRECT'+str(i))\nax1.legend()\nax1.set_yscale('log')\nax1.set_xlabel('Nbr. of function evaluations')\nax1.set_ylabel('Best function evaluation')\nfig1.savefig('Controller_plots/Controller_DIRECT_Convergence_plot.svg', format = \"svg\")\n\n\nsol_Cg = average_from_list(ContrLin_CUATRO_global_list)\ntest_CUATROg, test_av_CUATROg, test_min_CUATROg, test_max_CUATROg = sol_Cg\nsol_Cl = average_from_list(ContrLin_CUATRO_local_list)\ntest_CUATROl, test_av_CUATROl, test_min_CUATROl, test_max_CUATROl = sol_Cl\nsol_Nest = average_from_list(ContrLin_Nest_list)\ntest_Nest, test_av_Nest, test_min_Nest, test_max_Nest = sol_Nest\nsol_Splx = average_from_list(ContrLin_simplex_list)\ntest_Splx, test_av_Splx, test_min_Splx, test_max_Splx = sol_Splx\nsol_SQSF = average_from_list(ContrLin_SQSnobFit_list)\ntest_SQSF, test_av_SQSF, test_min_SQSF, test_max_SQSF = sol_SQSF\nsol_DIR = average_from_list(ContrLin_DIRECT_list)\ntest_DIR, test_av_DIR, test_min_DIR, test_max_DIR = sol_DIR\nsol_BO = average_from_list(ContrLin_Bayes_list)\ntest_BO, test_av_BO, test_min_BO, test_max_BO = sol_BO\n\nfig = plt.figure()\nax = fig.add_subplot()\nax.step(np.arange(1, 101), test_av_CUATROg, where = 'post', label = 'CUATRO_g', c = 'b')\nax.fill_between(np.arange(1, 101), test_min_CUATROg, \\\n                test_max_CUATROg, color = 'b', alpha = .5, step = 'post')\nax.step(np.arange(1, 101), test_av_CUATROl, where = 'post', label = 'CUATRO_l', c = 'c')\nax.fill_between(np.arange(1, 101), test_min_CUATROl, \\\n                test_max_CUATROl, color = 'c', alpha = .5, step = 'post')\nax.step(np.arange(1, 101), test_av_SQSF, where = 'post', label = 'Snobfit*', c = 'orange')\nax.fill_between(np.arange(1, 101), test_min_SQSF, \\\n                test_max_SQSF, color = 'orange', alpha = .5, step = 'post')\nax.step(np.arange(len(f_best_pyBbyqa)), f_best_pyBbyqa, where = 'post', \\\n          label = 'Py-BOBYQA', c = 'green')\nax.step(np.arange(1, 101), test_av_BO, where = 'post', label = 'Bayes. Opt.', c = 'red')\nax.fill_between(np.arange(1, 101), test_min_BO, \\\n                test_max_BO, color = 'red', alpha = .5, step = 'post')\n\nax.legend()\nax.set_xlabel('Number of function evaluations')\nax.set_ylabel('Best function evaluation')\nax.set_yscale('log')\nax.set_xlim([1, 100])  \nax.set_ylim([500, 35000])  \nax.legend(loc = 'upper right') \nfig.savefig('Controller_publication_plots/ContrLin_Model.svg', format = \"svg\")\n \n    \nfig = plt.figure()\nax = fig.add_subplot()\nax.step(np.arange(1, 101), test_av_Nest, where = 'post', label = 'Nesterov', c = 'brown')\nax.fill_between(np.arange(1, 101), test_min_Nest, \\\n                test_max_Nest, color = 'brown', alpha = .5, step = 'post')\nax.step(np.arange(1, 101), test_av_Splx, where = 'post', label = 'Simplex', c = 'green')\nax.fill_between(np.arange(1, 101), test_min_Splx, \\\n                test_max_Splx, color = 'green', alpha = .5, step = 'post')\nax.step(x_ind_findDiff, f_best_finDiff, where = 'post', \\\n          label = 'Newton', c = 'black')\nax.step(x_ind_BFGS, f_best_BFGS, where = 'post', \\\n          label = 'BFGS', c = 'orange')\nax.step(x_ind_Adam, f_best_Adam, where = 'post', \\\n          label = 'Adam', c = 'blue')   \nax.step(np.arange(1, 101), test_av_DIR, where = 'post', label = 'DIRECT', c = 'violet')\nax.fill_between(np.arange(1, 101), test_min_DIR, \\\n                test_max_DIR, color = 'violet', alpha = .5, step = 'post')\n# ax.boxplot(test_BO, widths = 0.1, meanline = False, showfliers = False, manage_ticks = False)\n# ax.step(np.arange(1, 101), test_av_BO, where = 'post', label = 'Bayes. Opt.')\n\nax.legend()\nax.set_xlabel('Number of function evaluations')\nax.set_ylabel('Best function evaluation')\nax.set_yscale('log')\nax.legend(loc = 'upper right')\nax.set_xlim([1, 100])\nax.set_ylim([500, 35000])  \nfig.savefig('Controller_publication_plots/ContrLin_Others.svg', format = \"svg\")\n\n\ndef medianx_from_list(solutions_list, x0):\n    N = len(solutions_list)\n    _, N_x = np.array(solutions_list[0]['x_best_so_far']).shape\n    f_best_all = np.zeros((N, 100))\n    x_best_all = np.zeros((N, 100, N_x))\n    for i in range(N):\n        f_best = np.array(solutions_list[i]['f_best_so_far'])\n        x_best = np.array(solutions_list[i]['x_best_so_far'])\n        x_ind = np.array(solutions_list[i]['samples_at_iteration'])\n        for j in range(100):\n            ind = np.where(x_ind <= j+1)\n            if len(ind[0]) == 0:\n                f_best_all[i, j] = f_best[0]\n                x_best_all[i,j,:] = np.array(x0)\n            else:\n                f_best_all[i, j] = f_best[ind][-1]\n                x_best_all[i,j,:] = np.array(x_best[ind][-1])\n    x_best_all\n    x_median = np.median(x_best_all, axis = 0)\n\n    return  x_median\n\ndef plot_ContrLin_resp(pi, plot, method, bounds, c, x0 =[15, 15], \n                          xref = [10, 10], N=200, T=3):\n    \n    ax1, ax2, ax3, ax4 = plot\n    \n    _, sys_resp, control_resp = phi(pi, x0 = x0, xref = xref, N=N, T=T, return_sys_resp = True)\n    \n    x1 = np.array(sys_resp)[:,0] ; x2 = np.array(sys_resp)[:,1]\n    ax1.plot(np.arange(len(x1))/len(x1)*T, x1, c = c, label = method + ': $x$')\n    ax1.plot([0, T], [xref[0], xref[0]], '--k')\n    ax2.plot([0, T], [xref[1], xref[1]], '--k')\n    ax2.plot(np.arange(len(x2))/len(x2)*T, x2, c = c)\n\n    \n    u1 = np.array(control_resp)[:,0] ; u2 = np.array(control_resp)[:,1]\n    ax3.plot(np.arange(len(u1))/len(u1)*T, u1, c = c, label = method + ': $u$')\n    ax4.plot(np.arange(len(u2))/len(u2)*T, u2, c = c)\n    # ax3.plot([0, T], [0, 0], '--k')\n    # ax4.plot([0, T], [0, 0], '--k')\n    return ax1, ax2, ax3, ax4\n\n\nplt.rcParams[\"font.family\"] = \"Times New Roman\"\nft = int(15)\nfont = {'size': ft}\nplt.rc('font', **font)\nparams = {'legend.fontsize': 12,\n              'legend.handlelength': 1.2}\nplt.rcParams.update(params)\n\nfig1, fig2, fig3 = plt.figure(), plt.figure(), plt.figure()\n\nax1, ax2 = fig1.add_subplot(211), fig1.add_subplot(212)\nax4, ax5 = fig3.add_subplot(211), fig3.add_subplot(212)\n\nmethod = 'Initial'\nplot = (ax1, ax2, ax4, ax5)\nplot = plot_ContrLin_resp(x0, plot, method, bounds, 'r')\nmethod = 'DIRECT'\n# pi = ContrLin_DIRECT_list[9]['x_best_so_far'][-1]\npi =  medianx_from_list(ContrLin_DIRECT_list, x0)[-1]\nplot = plot_ContrLin_resp(pi, plot, method, bounds, 'g')\nmethod = 'CUATRO_g'\n# pi =  ContrLin_CUATRO_global_list[8]['x_best_so_far'][-1]\npi = medianx_from_list(ContrLin_CUATRO_global_list, x0)[-1]\nplot = plot_ContrLin_resp(pi, plot, method, bounds, 'b')\nmethod = 'CUATRO_l'\n# pi =  ContrLin_CUATRO_local_list[8]['x_best_so_far'][-1]\npi = medianx_from_list(ContrLin_CUATRO_local_list, x0)[-1]\nplot = plot_ContrLin_resp(pi, plot, method, bounds, 'orange')\n\nax1.set_xlabel('Time') ; ax1.set_ylabel('$x_1$')\nax2.set_xlabel('Time') ; ax2.set_ylabel('$x_2$')\nax4.set_xlabel('Time') ; ax4.set_ylabel('$u_1$')\nax5.set_xlabel('Time') ; ax5.set_ylabel('$u_2$')\n\nfig1.legend(bbox_to_anchor=(1.01,0.5), loc=\"center left\", borderaxespad=0)\nfig3.legend(bbox_to_anchor=(1.01,0.5), loc=\"center left\", borderaxespad=0) \n# ax1.legend() ; ax2.legend() ; ax4.legend() ; ax5.legend()\nfig1.tight_layout() ; fig3.tight_layout()\n\nfig1.savefig('Controller_publication_plots/ContrLin_TrajStatesDet.svg', format = \"svg\", bbox_inches='tight')\nfig3.savefig('Controller_publication_plots/ContrLin_TrajControlsDet.svg', format = \"svg\", bbox_inches='tight')\n\n\n\nplt.rcParams[\"font.family\"] = \"Times New Roman\"\nft = int(15)\nfont = {'size': ft}\nplt.rc('font', **font)\nparams = {'legend.fontsize': 12,\n              'legend.handlelength': 1.2}\nplt.rcParams.update(params)\n\nfig1, fig2, fig3 = plt.figure(), plt.figure(), plt.figure()\nax1, ax2 = fig1.add_subplot(211), fig1.add_subplot(212)\nax4, ax5 = fig3.add_subplot(211), fig3.add_subplot(212)\n\nmethod = 'Initial'\nplot = (ax1, ax2, ax4, ax5)\nplot = plot_ContrLin_resp(x0, plot, method, bounds, 'r', x0 = [20, 0])\nmethod = 'DIRECT'\n# pi = ContrLin_DIRECT_list[9]['x_best_so_far'][-1]\npi =  medianx_from_list(ContrLin_DIRECT_list, x0)[-1]\nplot = plot_ContrLin_resp(pi, plot, method, bounds, 'g', x0 = [20, 0])\nmethod = 'CUATRO_g'\n# pi =  ContrLin_CUATRO_global_list[8]['x_best_so_far'][-1]\npi = medianx_from_list(ContrLin_CUATRO_global_list, x0)[-1]\nplot = plot_ContrLin_resp(pi, plot, method, bounds, 'b', x0 = [20, 0])\nmethod = 'CUATRO_l'\n# pi =  ContrLin_CUATRO_local_list[8]['x_best_so_far'][-1]\npi = medianx_from_list(ContrLin_CUATRO_local_list, x0)[-1]\nplot = plot_ContrLin_resp(pi, plot, method, bounds, 'orange')\n\nax1.set_xlabel('Time') ; ax1.set_ylabel('$x_1$')\nax2.set_xlabel('Time') ; ax2.set_ylabel('$x_2$')\nax4.set_xlabel('Time') ; ax4.set_ylabel('$u_1$')\nax5.set_xlabel('Time') ; ax5.set_ylabel('$u_2$')\n\nfig1.legend(bbox_to_anchor=(1.01,0.5), loc=\"center left\")\nfig3.legend(bbox_to_anchor=(1.01,0.5), loc=\"center left\") \n# fig1.legend(bbox_to_anchor=(0,1.01,1,0.2), loc=\"lower left\",\n#                 mode=\"expand\", borderaxespad=0, ncol=4)\n# fig3.legend(bbox_to_anchor=(0,1.01,1,0.2), loc=\"lower left\",\n#                 mode=\"expand\", borderaxespad=0, ncol=4)\n\n# ax1.legend() ; ax2.legend() ; ax4.legend() ; ax5.legend()\n# ax1.tight_layout() ; ax2.tight_layout() ; ax4.tight_layout() ; ax5.tight_layout()\nfig1.tight_layout() ; fig3.tight_layout()\n# plt.tight_layout()\nfig1.savefig('Controller_publication_plots/ContrLin_OtherTrajStatesDet.svg', format = \"svg\", bbox_inches='tight')\nfig3.savefig('Controller_publication_plots/ContrLin_OtherTrajControlsDet.svg', format = \"svg\", bbox_inches='tight')\n\n\ndef plot_traj(pi, plot, bounds, c, ms, alpha, label, x0 =[15, 15], \n                          xref = [10, 10], N=200, T=3):\n    \n    ax1, ax2, ax3, ax4 = plot\n    \n    _, sys_resp, control_resp = phi(pi, x0 = x0, xref = xref, N=N, T=T, return_sys_resp = True)\n    \n    x1 = np.array(sys_resp)[:,0] ; x2 = np.array(sys_resp)[:,1]\n    ax1.plot(np.arange(len(x1))/len(x1)*T, x1, markersize = ms, alpha = alpha, c = c, label = label)\n    ax1.plot([0, T], [xref[0], xref[0]], '--k')\n    ax2.plot([0, T], [xref[1], xref[1]], '--k')\n    ax2.plot(np.arange(len(x2))/len(x2)*T, x2, markersize = ms, alpha = alpha,c = c)\n\n    \n    u1 = np.array(control_resp)[:,0] ; u2 = np.array(control_resp)[:,1]\n    ax3.plot(np.arange(len(u1))/len(u1)*T, u1, markersize = ms, alpha = alpha, c = c, label = label)\n    ax4.plot(np.arange(len(u2))/len(u2)*T, u2, markersize = ms, alpha = alpha,  c = c)\n    # ax3.plot([0, T], [0, 0], '--k')\n    # ax4.plot([0, T], [0, 0], '--k')\n    return ax1, ax2, ax3, ax4\n\n\nfig1, fig2, fig3 = plt.figure(), plt.figure(), plt.figure()\nax1, ax2 = fig1.add_subplot(211), fig1.add_subplot(212)\nax4, ax5 = fig3.add_subplot(211), fig3.add_subplot(212)\nplot = (ax1, ax2, ax4, ax5)\n\npi_array = ContrLin_CUATRO_local_list[-1]['x_best_so_far']\nc = 'red'\nms = 1\nalpha = 0.15\nlabel = '_no_Legend_'\n\nfor i in range(len(pi_array)):\n    if i>= 15:\n        alpha = i/100\n    pi = pi_array[i]\n    plot = plot_traj(pi, plot, bounds, c, ms, alpha, label)\n\n\nax1.set_xlabel('Time') ; ax1.set_ylabel('$x_1$')\nax2.set_xlabel('Time') ; ax2.set_ylabel('$x_2$')\nax4.set_xlabel('Time') ; ax4.set_ylabel('$u_1$')\nax5.set_xlabel('Time') ; ax5.set_ylabel('$u_2$')\n\n# fig1.legend(bbox_to_anchor=(1.01,0.5), loc=\"center left\")\n# fig3.legend(bbox_to_anchor=(1.01,0.5), loc=\"center left\") \n# fig1.legend(bbox_to_anchor=(0,1.01,1,0.2), loc=\"lower left\",\n#                 mode=\"expand\", borderaxespad=0, ncol=4)\n# fig3.legend(bbox_to_anchor=(0,1.01,1,0.2), loc=\"lower left\",\n#                 mode=\"expand\", borderaxespad=0, ncol=4)\n\n# ax1.legend() ; ax2.legend() ; ax4.legend() ; ax5.legend()\n# ax1.tight_layout() ; ax2.tight_layout() ; ax4.tight_layout() ; ax5.tight_layout()\nfig1.tight_layout() ; fig3.tight_layout()\n# plt.tight_layout()\nfig1.savefig('Controller_publication_plots/ContrLin_ConvergenceStatesDet.svg', format = \"svg\", bbox_inches='tight')\nfig3.savefig('Controller_publication_plots/ContrLin_ConvergenceControlsDet.svg', format = \"svg\", bbox_inches='tight')\n\n\n\n\nfig1, fig2, fig3 = plt.figure(), plt.figure(), plt.figure()\nax1, ax2 = fig1.add_subplot(211), fig1.add_subplot(212)\nax4, ax5 = fig3.add_subplot(211), fig3.add_subplot(212)\nplot = (ax1, ax2, ax4, ax5)\n\npi_array = ContrLin_pybobyqa['x_best_so_far']\n\nc = 'red'\nms = 1\nalpha = 0.15\nlabel = '_no_Legend_'\n\nfor i in range(len(pi_array)):\n    if i>= 15:\n        alpha = i/100\n    pi = pi_array[i]\n    plot = plot_traj(pi, plot, bounds, c, ms, alpha, label, x0 = [20, 0])\n    # plot = plot_traj(pi, plot, bounds, c, ms, alpha, label)\n\n\nax1.set_xlabel('Time') ; ax1.set_ylabel('$x_1$')\nax2.set_xlabel('Time') ; ax2.set_ylabel('$x_2$')\nax4.set_xlabel('Time') ; ax4.set_ylabel('$u_1$')\nax5.set_xlabel('Time') ; ax5.set_ylabel('$u_2$')\n\n# fig1.legend(bbox_to_anchor=(1.01,0.5), loc=\"center left\")\n# fig3.legend(bbox_to_anchor=(1.01,0.5), loc=\"center left\") \n# fig1.legend(bbox_to_anchor=(0,1.01,1,0.2), loc=\"lower left\",\n#                 mode=\"expand\", borderaxespad=0, ncol=4)\n# fig3.legend(bbox_to_anchor=(0,1.01,1,0.2), loc=\"lower left\",\n#                 mode=\"expand\", borderaxespad=0, ncol=4)\n\n# ax1.legend() ; ax2.legend() ; ax4.legend() ; ax5.legend()\n# ax1.tight_layout() ; ax2.tight_layout() ; ax4.tight_layout() ; ax5.tight_layout()\nfig1.tight_layout() ; fig3.tight_layout()\n# plt.tight_layout()\nfig1.savefig('Controller_publication_plots/ContrLin_ConvergenceStatesDetpybbqa.svg', format = \"svg\", bbox_inches='tight')\nfig3.savefig('Controller_publication_plots/ContrLin_ConvergenceControlsDetpybbqa.svg', format = \"svg\", bbox_inches='tight')\n\n\n## Plots_test\n\n# T = 3\n# pi = [7.636737498696908, 1.8007378706654067, 4.319855283471685, 7.197230390528715]\n\n# fig = plt.figure()\n# fig1 = plt.figure()\n# ax1 = fig.add_subplot()\n# ax2 = fig1.add_subplot()\n# ax1.plot([0, T], [10, 10], '--k', label = '$x_{1,ss}$ and $x_{2,ss}$')\n# method = 'CUATRO_l'\n# plot_stuff = (ax1, ax2)\n# plot_intermediate = plot_sys_resp(pi, plot_stuff, method, x0 = [15, 15], xref = [10, 10], N=200, T=3)\n# ax1, ax2 = plot_sys_resp([4]*4, plot_intermediate, 'Initial', x0 = [15, 15], xref = [10, 10], N=200, T=3)\n# ax1.legend()\n# ax2.legend()\n# ax1.set_xlabel('T')\n# ax2.set_xlabel('T')\n# ax1.set_ylabel('x')\n# ax2.set_ylabel('u')", "meta": {"hexsha": "facdfff040ae1798a1fd2b090a2ce8459cfe1beb", "size": 27431, "ext": "py", "lang": "Python", "max_stars_repo_path": "Controller_comp/Linear_comp.py", "max_stars_repo_name": "OptiMaL-PSE-Lab/Expensive-Black-Box-Optim-ChemEng", "max_stars_repo_head_hexsha": "19c34dcff8c983926df501b93152fa3b3b0305d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Controller_comp/Linear_comp.py", "max_issues_repo_name": "OptiMaL-PSE-Lab/Expensive-Black-Box-Optim-ChemEng", "max_issues_repo_head_hexsha": "19c34dcff8c983926df501b93152fa3b3b0305d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Controller_comp/Linear_comp.py", "max_forks_repo_name": "OptiMaL-PSE-Lab/Expensive-Black-Box-Optim-ChemEng", "max_forks_repo_head_hexsha": "19c34dcff8c983926df501b93152fa3b3b0305d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0643712575, "max_line_length": 123, "alphanum_fraction": 0.6664357843, "include": true, "reason": "import numpy", "num_tokens": 8559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.17879123806316127}}
{"text": "\"\"\"\n- Provision a results table.\n- Preprocessing\n    - Identify highest-degree node in motif, M1\n    - Identify second-highest degree node in motif, M2, connected to M1 by\n        a single edge.\n    - Identify all nodes with degree of M1 or greater in the host graph,\n        which also have all required attributes of the M1 and M2 nodes. If\n        neither M1 nor M2 have degree > 1 nor attributes, select M1 and M2 as\n        two nodes with attributes defined.\n    - Enumerate all paths in the host graph from M1 candidates to M2 candidates,\n        as candidate \"backbones\" in a queue.\n- Motif Search\n    - For each backbone candidate:\n        - Schedule an AWS Lambda:\n            - Pop the backbone from the queue.\n            - Traverse all shortest paths in the motif starting at the nearest\n                of either M1 or M2\n            - If multiple nodes are valid candidates, queue a new backbone with\n                each option, and terminate the current Lambda.\n            - When all paths are valid paths in the host graph, add the list\n                of participant nodes to a result in the DynamoDB table.\n- Reporting\n    - Return a serialization of the results from the DynamoDB table.\n- Cleanup\n    - Delete the backbone queue\n    - Delete the results table (after collection)\n\"\"\"\nfrom typing import Any, Dict, Hashable, List, Optional, Tuple, Union\nfrom inspect import isclass\nimport itertools\nimport queue\n\nimport networkx as nx\n\n__version__ = \"1.1.0\"\n\n\"\"\"\nIn this process, we consider the following operations to be fast:\n\n- Get degree of node\n- Get downstream targets of node\n- Get attributes on a node\n\nThese operations are medium:\n\n- Get upstream sources of node\n- Get degrees of all nodes in host graph\n- Get nodes with a certain attribute\n\nThese operations are slow:\n- Get edges where nodes have a certain attribute\n    - But you can do the same with get-downstream-targets and filter an\n      attribute search.\n\"\"\"\n\n\ndef is_node_attr_match(\n    motif_node_attrs: dict, host_graph_id: str, host: nx.Graph\n) -> bool:\n    \"\"\"\n    Check if a node in the host graph matches the attributes in the motif.\n\n    Arguments:\n        motif_node_attrs (dict): A dictionary of metadata on a motif node\n        host_graph_id (str): The ID of metadata on the host graph\n        host (nx.Graph): The host graph object\n\n    Returns:\n        bool: True if the host node matches the attributes in the motif\n\n    \"\"\"\n    host_node = host.nodes[host_graph_id]\n\n    for attr, val in motif_node_attrs.items():\n        if attr not in host_node:\n            return False\n        if host_node[attr] != val:\n            return False\n\n    return True\n\n\ndef is_node_structural_match(\n    motif_node_id: str, host_graph_id: str, motif: nx.Graph, host: nx.Graph\n) -> bool:\n    \"\"\"\n    Check if the motif node here is a valid structural match.\n\n    Specifically, this requires that a host node has at least the degree as the\n    motif node.\n\n    Arguments:\n        motif_node_id (str): The motif node ID\n        host_graph_id (str): The host graph ID\n        motif (nx.Graph): The motif graph\n        host (nx.Graph): The host graph\n\n    Returns:\n        bool: True if the motif node maps to this host node\n\n    \"\"\"\n    return host.degree(host_graph_id) >= motif.degree(motif_node_id)\n\n\ndef get_next_backbone_candidates(\n    backbone: dict,\n    motif: nx.Graph,\n    host: nx.Graph,\n    interestingness: dict,\n    next_node: str = None,\n    directed: bool = True,\n    isomorphisms_only: bool = False,\n) -> List[dict]:\n    \"\"\"\n    Get a list of candidate node assignments for the next \"step\" of this map.\n\n    Arguments:\n        backbone (dict): Mapping of motif node IDs to one set of host graph IDs\n        motif (Graph): A graph representation of the motif\n        host (Graph): The host graph, complete\n        interestingness (dict): A mapping of motif node IDs to interestingness\n        next_node (str: None): Optional suggestion for the next node to assign\n        directed (bool: True): Whether host and motif are both directed\n        isomorphisms_only (bool: False): If true, only isomorphisms will be\n            returned (instead of all monomorphisms)\n\n    Returns:\n        List[dict]: A new list of mappings with one additional element mapped\n\n    \"\"\"\n\n    # Get a list of the \"exploration front\" of the motif -- nodes that are not\n    # yet assigned in the backbone but are connected to at least one assigned\n    # node in the backbone.\n\n    # For example, in the motif A -> B -> C, if A is already assigned, then the\n    # front is [B] (c is not included because it has not connection to any\n    # assigned node).\n\n    # We should prefer nodes that are connected to multiple assigned backbone\n    # nodes, because these will filter more rapidly to a smaller set.\n\n    # First check if the backbone is empty. If so, we should choose the most\n    # interesting node to start with:\n\n    if next_node is None and len(backbone) == 0:\n        # This is the starting-case, where we have NO backbone nodes set yet.\n        next_node = [k for k in interestingness.keys()][0]\n        # Let's return ALL possible node choices for this next_node. To do this\n        # without being an insane person, let's filter on max degree in host:\n        return [\n            {next_node: n}\n            for n in host.nodes()\n            if is_node_structural_match(next_node, n, motif, host)\n        ]\n\n    else:\n        _node_with_greatest_backbone_count: Optional[str] = None\n        _greatest_backbone_count = 0\n        for motif_node_id in motif.nodes():\n            if motif_node_id in backbone:\n                continue\n            # How many connections to existing backbone?\n            # Note that this number is certainly greater than or equal to 1,\n            # since a value of 0 would imply that the backbone dict is empty\n            # (which we have already handled) or that the motif has more than\n            # one connected component, which we check for at prep-time.\n            if directed:\n                motif_backbone_connections_count = sum(\n                    [\n                        1\n                        for v in list(\n                            set(motif.adj[motif_node_id]).union(\n                                set(motif.pred[motif_node_id])\n                            )\n                        )\n                        if v in backbone\n                    ]\n                )\n            else:\n                motif_backbone_connections_count = sum(\n                    [1 for v in motif.adj[motif_node_id] if v in backbone]\n                )\n            # If this is the most highly connected node visited so far, then\n            # set it as the next node to explore:\n            if motif_backbone_connections_count > _greatest_backbone_count:\n                _node_with_greatest_backbone_count = motif_node_id\n        # Now we have _node_with_greatest_backbone_count as the best candidate\n        # for `next_node`.\n        next_node = _node_with_greatest_backbone_count\n\n    # Now we have a node `next_node` which we know is connected to the current\n    # backbone. Get all edges between `next_node` and nodes in the backbone,\n    # and verify that they exist in the host graph:\n    # `required_edges` has the form (prev, self, next), with non-values filled\n    # with None. That way we can easily remember and store the roles of the\n    # node IDs in the next step.\n    required_edges = []\n    for other in list(motif.adj[next_node]):\n        if other in backbone:\n            # edge is (next_node, other)\n            required_edges.append((None, next_node, other))\n    if directed:\n        for other in list(motif.pred[next_node]):\n            if other in backbone:\n                # edge is (other, next_node)\n                required_edges.append((other, next_node, None))\n\n    # `required_edges` now contains a list of all edges that exist in the motif\n    # graph, and we must find candidate nodes that have such edges in the host.\n\n    candidate_nodes = []\n\n    # In the worst-case, `required_edges` has length == 1. This is the worst\n    # case because it means that ALL edges from/to `other` are valid options.\n    if len(required_edges) == 1:\n        # :(\n        (source, _, target) = required_edges[0]\n        if directed:\n            if source is not None:\n                # this is a \"from\" edge:\n                candidate_nodes = list(host.adj[backbone[source]])\n            elif target is not None:\n                # this is a \"from\" edge:\n                candidate_nodes = list(host.pred[backbone[target]])\n        else:\n            candidate_nodes = list(host.adj[backbone[target]])\n        # Thus, all candidates for motif ID `$next_node` are stored in the\n        # candidate_nodes list.\n\n    elif len(required_edges) > 1:\n        # This is neato :) It means that there are multiple edges in the host\n        # graph that we can use to downselect the number of candidate nodes.\n        candidate_nodes_set = set()\n        for (source, _, target) in required_edges:\n            if directed:\n                if source is not None:\n                    # this is a \"from\" edge:\n                    candidate_nodes_from_this_edge = host.adj[backbone[source]]\n                # elif target is not None:\n                else:  # target is not None:\n                    # this is a \"from\" edge:\n                    candidate_nodes_from_this_edge = host.pred[backbone[target]]\n                # else:\n                #     raise AssertionError(\"Encountered an impossible condition: At least one of source or target must be defined.\")\n            else:\n                candidate_nodes_from_this_edge = host.adj[backbone[target]]\n            if len(candidate_nodes_set) == 0:\n                # This is the first edge we're checking, so set the candidate\n                # nodes set to ALL possible candidates.\n                candidate_nodes_set.update(candidate_nodes_from_this_edge)\n            else:\n                candidate_nodes_set = candidate_nodes_set.intersection(\n                    candidate_nodes_from_this_edge\n                )\n        candidate_nodes = list(candidate_nodes_set)\n\n    elif len(required_edges) == 0:\n        # Somehow you found a node that doesn't have any edges. This is bad.\n        raise ValueError(\n            f\"Somehow you found a motif node {next_node} that doesn't have \"\n            + \"any motif-graph edges. This is bad. (Did you maybe pass an \"\n            + \"empty backbone to this function?)\"\n        )\n\n    tentative_results = [\n        {**backbone, next_node: c}\n        for c in candidate_nodes\n        if c not in backbone.values()\n        and is_node_structural_match(next_node, c, motif, host)\n    ]\n\n    # One last filtering step here. This is to catch the cases where you have\n    # successfully mapped each node, and the final node has some valid\n    # candidate_nodes (and therefore `tentative_results`).\n    # This is important: We must now check that for the assigned nodes, all\n    # edges between them DO exist in the host graph. Otherwise, when we check\n    # in find_motifs that len(motif) == len(mapping), we will discover that the\n    # mapping is \"complete\" even though we haven't yet checked it at all.\n\n    monomorphism_candidates = []\n\n    for mapping in tentative_results:\n        if len(mapping) == len(motif):\n            if all(\n                [\n                    host.has_edge(mapping[motif_u], mapping[motif_v])\n                    for motif_u, motif_v in motif.edges()\n                ]\n            ):\n                # This is a \"complete\" match!\n                monomorphism_candidates.append(mapping)\n        else:\n            # This is a partial match, so we'll continue building.\n            monomorphism_candidates.append(mapping)\n\n    if not isomorphisms_only:\n        return monomorphism_candidates\n\n    # Additionally, if isomorphisms_only == True, we can use this opportunity\n    # to confirm that no spurious edges exist in the induced subgraph:\n    isomorphism_candidates = []\n    for result in monomorphism_candidates:\n        for (motif_u, motif_v) in itertools.product(result.keys(), result.keys()):\n            # if the motif has this edge, then it doesn't rule any of the\n            # above results out as an isomorphism.\n            # if the motif does NOT have the edge, then NO RESULT may have\n            # the equivalent edge in the host graph:\n            if not motif.has_edge(motif_u, motif_v) and host.has_edge(\n                result[motif_u], result[motif_v]\n            ):\n                # this is a violation.\n                break\n        else:\n            isomorphism_candidates.append(result)\n    return isomorphism_candidates\n\n\ndef uniform_node_interestingness(motif: nx.Graph) -> dict:\n    \"\"\"\n    Sort the nodes in a motif by their interestingness.\n\n    Most interesting nodes are defined to be those that most rapidly filter the\n    list of nodes down to a smaller set.\n\n    \"\"\"\n    return {n: 1 for n in motif.nodes()}\n\n\ndef find_motifs(\n    motif: nx.Graph,\n    host: nx.Graph,\n    interestingness: dict = None,\n    count_only: bool = False,\n    directed: bool = None,\n    profile: bool = False,\n    queue_=queue.SimpleQueue,\n    isomorphisms_only: bool = False,\n    hints: List[Dict[Hashable, Hashable]] = None,\n    limit: int = None,\n) -> Union[int, List[dict], Tuple[Union[int, List[dict]], Any]]:\n    \"\"\"\n    Get a list of mappings from motif node IDs to host graph IDs.\n\n    Results are of the form:\n\n    ```\n    [{motif_id: host_id, ...}]\n    ```\n\n    Arguments:\n        motif (nx.DiGraph): The motif graph (needle) to search for\n        host (nx.DiGraph): The host graph (haystack) to search within\n        interestingness (dict: None): A map of each node in `motif` to a float\n            number that indicates an ordinality in which to address each node\n        count_only (bool: False): If True, return only an integer count of the\n            number of motifs, rather than a list of mappings.\n        directed (bool: None): Whether direction should be considered during\n            search. If omitted, this will be based upon the motif directedness.\n        profile (bool: False): SLOWER! Whether to include additional metrics\n            in addition to results. Note that you should only ever use this to\n            debug or understand your results, not for use in production.\n        queue_ (queue.Queue): What kind of queue to use.\n        hints (dict): A dictionary of initial starting mappings. By default,\n            searches for all instances. You can constrain a node by passing a\n            list with a single dict item: `[{motifId: hostId}]`.\n        limit (int: None): A limit to place on the number of returned mappings.\n            The search will terminate once the limit is reached.\n        isomorphisms_only (bool: False): Whether to return isomorphisms (the\n            default is monomorphisms).\n\n    Returns:\n        int, List[dict], Tuple[List[dict], queue.Queue]\n        int: If `count_only` is True, return the length of the List.\n        List[dict]: A list of mappings from motif node IDs to host graph IDs\n        Tuple[List[dict], queue.Queue]: If `profile` is true. Also includes the\n            queue that was used to perform the search.\n\n    \"\"\"\n    interestingness = interestingness or uniform_node_interestingness(motif)\n\n    if directed is None:\n        # guess directedness from motif\n        if isinstance(motif, nx.DiGraph):\n            # This will be a directed query.\n            directed = True\n        else:\n            directed = False\n\n    q = queue_() if isclass(queue_) else queue_\n\n    results = []\n    results_count = 0\n\n    # Kick off the queue with an empty candidate:\n    if hints is None or hints == []:\n        q.put({})\n    else:\n        for hint in hints:\n            q.put(hint)\n\n    while not q.empty():\n        new_backbone = q.get()\n        next_candidate_backbones = get_next_backbone_candidates(\n            new_backbone,\n            motif,\n            host,\n            interestingness,\n            directed=directed,\n            isomorphisms_only=isomorphisms_only,\n        )\n\n        for candidate in next_candidate_backbones:\n            if len(candidate) == len(motif):\n                if count_only:\n                    results_count += 1\n                    if limit and results_count >= limit:\n                        # perform return logic\n                        if profile:\n                            return results_count, q\n                        else:\n                            return results_count\n                else:\n                    results.append(candidate)\n                    if limit and len(results) >= limit:\n                        # perform return logic\n                        if profile:\n                            return results, q\n                        return results\n\n            else:\n                q.put(candidate)\n\n    if profile:\n        if count_only:\n            return results_count, q\n        return results, q\n    if count_only:\n        return results_count\n    return results\n\n", "meta": {"hexsha": "58e1ed9111f5ccbcde457464b5b6c4e42580d7f1", "size": 17066, "ext": "py", "lang": "Python", "max_stars_repo_path": "grandiso/__init__.py", "max_stars_repo_name": "Raphtor/grandiso-networkx", "max_stars_repo_head_hexsha": "c7677cb31ea1226f4da7423bdfaf0c7946778223", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "grandiso/__init__.py", "max_issues_repo_name": "Raphtor/grandiso-networkx", "max_issues_repo_head_hexsha": "c7677cb31ea1226f4da7423bdfaf0c7946778223", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grandiso/__init__.py", "max_forks_repo_name": "Raphtor/grandiso-networkx", "max_forks_repo_head_hexsha": "c7677cb31ea1226f4da7423bdfaf0c7946778223", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5237020316, "max_line_length": 132, "alphanum_fraction": 0.6173092699, "include": true, "reason": "import networkx", "num_tokens": 3722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.17879123806316127}}
{"text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n\nimport os\nimport re\nimport gzip\nimport sqlite3 as sql\nimport subprocess\nfrom StringIO import StringIO\nfrom math import degrees, atan2, pi, ceil # , sin, cos\nfrom array import array\nfrom glob import glob\n\nimport numpy\n\nfrom prosci.util.pdb3d import dihedral_angle, dist, sqrdist, vectors2rotation_matrix, axis_angle2rotation_matrix\nfrom prosci.util.residue import Residue, ResidueList\nfrom prosci.util.residue import is_residue_consecutive as is_consecutive\nfrom prosci.util.pdb import Atom, residueCode\nfrom prosci.util.ali import Ali\nfrom prosci.util.geohash import GeometricHash\nfrom prosci.common import join\n\n# Used implicitly in this file:\n#\n#from prosci.util.residue import Residue\n\n\n\n# Database anchor hash granularity\n#ANCHOR_GRANULARITY = 1.0\n\nANCHOR_LENGTH = 2\n\n#STRUC_HASH_GRANULARITY = 0.3\n\n\n\n\nclass Data:\n  pass\n\n\ndef get_max_loop_length(loop_length):\n  return 3.8 * (1+loop_length)\n\n# def is_consecutive(a, b, minlen=1.0, maxlen=2.0):\n# #def is_consecutive(residues, a, b):\n#     if a.C is None or b.N is None:\n#       #raise RuntimeError(\"Cannot reliably test if two residues are consecutive, purely based on CA distance! Need N and C atoms!\")\n#       return False\n#     \n#     #d=dist(r.CA, q.CA)\n#     #if (d < 3.6 or d > 4.0):\n#     d = dist(a.C, b.N)\n#     if (d < minlen or d > maxlen):\n#       return False\n#     return True\n\n\ndef get_loop_structure(dbdir, strucname, start, length):\n  \n  def parse(f):\n    residues=[]\n    r=[]\n    i=-1\n    for line in f:\n      if line.startswith('>'):\n        i+=1\n        if i >= start+length:\n          residues.append(Residue(r))\n          break\n        if r:\n          residues.append(Residue(r))\n          r=[]\n      elif i>= start:\n        r.append(Atom(line))\n    return residues\n  \n  source = os.path.join(dbdir, \"structures\", strucname[1:3], strucname)\n  f = None\n  try:\n    #p = subprocess.Popen([\"zcat\", source + \".atm.gz\"], stdout = subprocess.PIPE)\n    #f = StringIO(p.communicate()[0])\n    #if p.returncode != 0:\n    #  raise IOError()\n    f = gzip.open(source + \".atm.gz\")\n    residues = parse(f)\n  except IOError:\n    f = open(source + \".atm\")\n    residues = parse(f)\n  finally:\n    if f is not None:\n      f.close()\n  \n  return ResidueList(residues)\n\n\n# # TODO: Doesn't work yet. Needs to get anchor residues too!\n# def get_loop_structure_from_decoyname(dbdir, name):\n#   \"Parse the name of a loop decoy and get its structure from the database\"\n#   \n#   strucname, startres, length = name.split(\"_\")\n#   startinscode = \"\"\n#   if startres[-1:].isalpha():\n#     startinscode = startres[-1:]\n#     startres = startres[:-1]\n#   startres = int(startres)\n#   length = int(length) + 2*ANCHOR_LENGTH\n#   \n#   source = os.path.join(dbdir, \"structures\", strucname[1:3], strucname)\n#   residues=[]\n#   r=[]\n#   i=-1\n#   f = gzip.open(source + \".atm.gz\")\n#   skip = False\n#   try:\n#     for line in f:\n#       if line.startswith('>'):\n#         if i < 0:\n#           skip = False\n#           continue\n#         i+=1\n#         if i >= length:\n#           residues.append(Residue(r))\n#           break\n#         if r:\n#           residues.append(Residue(r))\n#           r=[]\n#       elif i < 0:\n#         if not skip:\n#           a = Atom(line)\n#           if a.ires < startres or (a.ires == startres and  a.inscode < startinscode):\n#             skip = True\n#           else:\n#             r.append(Atom(line))\n#             i = 0\n#       else:\n#         r.append(Atom(line))\n#     # No need to check if r has not yet been added, as loops never\n#     # reach the end of the protein.\n#   finally:\n#     f.close()\n#   return ResidueList(residues)\n\n\ndef get_native_contacts(dbdir, strucname, start, length):\n  source = os.path.join(dbdir, \"structures\", strucname[1:3], strucname)\n  a = Ali(source + \".tem\")\n  dihedrals = a[0][\"FREAD dihedral class\"].seq[start:start+length]\n  contacts = a[0][\"FREAD contact class\"].seq[start:start+length]\n  assert \"?\" not in dihedrals\n  return contacts\n\n\ndef add_oxygens(residues, start=0, end=None, dO=1.23, force=False):\n  if end is None:\n    end = len(residues) - 1\n  for i in xrange(start, end):\n    # add missing mainchain oxygens, making them planar\n    # with CA, C and the next residue's N\n    #\n    r = residues[i]\n    if r is None:\n      continue\n    \n    if r.O is None:\n      q = residues[i+1]\n      if q is None or q.N is None or r.C is None:\n        continue\n      \n      if not force and not is_consecutive(r, q):\n        continue\n      \n      O = r.C.copy()\n      O.atom = \"O\"\n      if r.C.element:\n        O.element = \"O\"\n      O.iatom = r.C.iatom+1\n\n      vO_1 = r.C.xyz - r.CA.xyz\n      vO_2 = r.C.xyz - q.N.xyz\n      vO_3 = (vO_1 / numpy.linalg.norm(vO_1)) + (vO_2 / numpy.linalg.norm(vO_2))\n      O.xyz = r.C.xyz + (vO_3 / numpy.linalg.norm(vO_3)) * dO\n\n      r.O = O\n\n\ndef is_structure_ok(residues, start, end, max_b=float(\"inf\")):\n  for i in xrange(start, end):\n    r1=residues[i]\n    if r1.N is None or r1.CA is None or r1.C is None or r1.O is None or \\\n       r1.N.b > max_b or r1.CA.b > max_b or r1.C.b > max_b or r1.O.b > max_b:\n      return False\n  \n  r1=residues[start]  \n  for i in xrange(start+1, end):\n    r2=residues[i]\n    if (r2.CA.ires != r1.CA.ires + 1):\n      return False\n    if not is_consecutive(r1, r2):\n      return False\n    # d=dist(r1.CA, r2.CA)\n    # if (d < 2.8 or d > 4.0):\n    #   return False\n    r1=r2\n  \n  return True\n\n\n\n# dihed_phi   = zip([-180, -110,-110,-180,-180,-180,  20,   0,  0],\n#                   [   0,    0,   0,-110,-110,   0, 140, 180,180])\n# dihed_psi     = zip([ -90,  100,-180, 100,-180,  45, -40,-180, 80],\n#                   [  45,  180, -90, 180, -90, 100,  80, -40,180])\n# dihed_class =     [   0,    1,   1,   2,   2,   3,   4,   5,  5]\n\n# dihed_phi   = zip([-180, -110,-110,-180,-180,-180,  20,   0],\n#                   [   0,    0,   0,-110,-110,   0, 140, 180])\n# dihed_psi   = zip([ -90,  100,-180, 100,-180,  80, -40,-180],\n#                   [  80,  180, -90, 180, -90, 100,  80, 180])\n# dihed_class =     [   0,    1,   1,   2,   2,   3,   4,   5]\n# #                     A     B    B    C    C    D    E    F\n\ndihed_phi   = zip([-180, -110,-110,-180,-180,-180,  20,   0],\n                  [   0,    0,   0,-110,-110,   0, 140, 180])\ndihed_psi   = zip([ -90,  100,-180, 100,-180,  45, -40,-180],\n                  [  45,  180, -90, 180, -90, 100,  80, 180])\ndihed_class =     [   0,    1,   1,   2,   2,   3,   4,   5]\n#                     A     B    B    C    C    D    E    F\n\n\ndef get_dihedral_angle(residues, i):\n  r1 = residues[i-1]\n  r2 = residues[i]\n  r3 = residues[i+1]\n  phi = dihedral_angle(r2.N.xyz  - r1.C.xyz, r2.CA.xyz - r2.N.xyz, r2.C.xyz - r2.CA.xyz)\n  psi = dihedral_angle(r2.CA.xyz - r2.N.xyz, r2.C.xyz - r2.CA.xyz, r3.N.xyz - r2.C.xyz)\n  return (phi, psi)\n\n\ndef angle2class(phi, psi):\n  for i in xrange(9):\n    minphi,maxphi = dihed_phi[i]\n    minpsi,maxpsi = dihed_psi[i]\n    if phi <= maxphi and phi >= minphi and psi <= maxpsi and psi >= minpsi:\n      return dihed_class[i]\n  raise IllegalStateError(\"illegal dihedral angles : %f, %f\" % (phi, psi))\n\n\ndef get_dihedral_class(residues, i):\n  phi, psi = get_dihedral_angle(residues, i)\n  return angle2class(phi, psi)\n\n\ndef describe_anchors(anchor_n, anchor_c, loop_length):\n  max_actual_length = get_max_loop_length(loop_length)\n  \n  n1, n2 = anchor_n[-2:]\n  c1, c2 = anchor_c[:2]\n  \n  # get CA coordinates of anchors\n  coords = numpy.array([n1.CA.xyz, n2.CA.xyz, c1.CA.xyz, c2.CA.xyz, n2.O.xyz, c1.O.xyz])\n  \n  origin = numpy.copy(coords[1])\n  \n  # translate second CA of N-anchor onto origin\n  for i,c in enumerate(coords):\n    coords[i] -= origin\n  \n  #print coords\n  \n  # rotate first CA of N-anchor onto Y axis in the negative direction, such that\n  # the actual loop goes off in the positive direction along Y axis\n  #\n#   if numpy.round(coords[0][0], 4) != 0 or numpy.round(coords[0][2], 4) != 0:\n#     rotmat1 = vectors2rotation_matrix(coords[0], numpy.array([0.0,-1.0,0.0]))\n#     for i,c in enumerate(coords):\n#       coords[i] = numpy.dot(c, rotmat1)\n#   else:\n#     rotmat1 = None\n  \n#   print \"Experimental rotation matrix:\"\n#   print vectors2rotation_matrix(numpy.array([-1.0,0.0,0.0]), numpy.array([1.0,0.0,0.0]))\n#   print \"Experimental rotation matrix2:\"\n#   exprotmat = axis_angle2rotation_matrix(numpy.array([0.0,1.0,0.0]), pi)\n#   print numpy.dot(numpy.array([-1.0,0.0,0.0]), exprotmat)\n#   raise RuntimeError()\n  \n  # rotate first CA of C-anchor onto X axis in the positive direction\n  #\n  if numpy.round(coords[2][1], 4) != 0 or numpy.round(coords[2][2], 4) != 0:\n    rotmat1 = vectors2rotation_matrix(coords[2], numpy.array([1.0,0.0,0.0]))\n    for i,c in enumerate(coords):\n      coords[i] = numpy.dot(c, rotmat1)\n  elif coords[2][0] < 0:\n    rotmat1 = axis_angle2rotation_matrix((0.0,1.0,0.0), pi)\n    for i,c in enumerate(coords):\n      coords[i] = numpy.dot(c, rotmat1)\n  else:\n    rotmat1 = None\n  \n  \n  #print coords\n  \n  # rotate first CA of N-anchor onto X-Y plane, in the negative Y direction, so that the loop always goes off into the positive Y direction.\n  if numpy.round(coords[0][2], 4) != 0:\n    rotmat2 = vectors2rotation_matrix(numpy.array([0.0, coords[0][1], coords[0][2]]), numpy.array([0.0,-1.0,0.0]))\n    for i,c in enumerate(coords):\n      coords[i] = numpy.dot(c, rotmat2)\n  elif coords[0][1] > 0:\n    rotmat2 = axis_angle2rotation_matrix((1.0,0.0,0.0), pi)\n    for i,c in enumerate(coords):\n      coords[i] = numpy.dot(c, rotmat2)\n  else:\n    rotmat2 = None\n  \n  #print coords\n  \n  coords = coords.round(4)\n  \n  try:\n    assert (coords[1] == (0,0,0)).all()  # second N atom should be the origin\n    assert coords[2][1] == 0   # first C atom should be on the X axis\n    assert coords[2][2] == 0   # first C atom should be on the X axis\n    assert coords[2][0] >  0   # first C atom should be be in the positive X range\n    assert coords[0][2] == 0   # first N atom should be on the X-Y plane\n    assert coords[0][1] <= 0   # first N atom should be on in the negative Y range\n    assert not numpy.isnan(coords).any()   # must not have NaN in coords\n  except:\n    print \"Anchor coordinates:\"\n    for c in coords:\n      print c\n      print\n    raise\n  \n  d = Data()\n  \n  # save coordinates\n  d.N1 = coords[0]\n  # N2 = [0, 0, 0]   # N2 is always on the origin\n  d.C1 = coords[2]\n  d.C2 = coords[3]\n  \n  # compute loop stretch (can just use X coords of first CA of C-anchor, as it's on the X axis)\n  stretch = min(1.0, coords[2][0] / max_actual_length)\n  \n  \n  # get angle between N anchor and Y axis\n  Nanchor_angle = atan2(-coords[0][0], -coords[0][1])\n  \n  # get rotation angle of N anchor's O atom around the N anchor's own axis\n  #Nanchor_rotmat = numpy.array([[cos(Nanchor_angle), -sin(Nanchor_angle), 0], [sin(Nanchor_angle), cos(Nanchor_angle), 0], [0, 0, 1]]); # matrix rotates N anchor onto Y axis\n  Nanchor_rotmat = axis_angle2rotation_matrix((0.0,0.0,1.0), Nanchor_angle)\n  Nanchor_O = numpy.dot(coords[4], Nanchor_rotmat)\n  Nanchor_twist = atan2(Nanchor_O[0], Nanchor_O[2])\n  \n  \n  # get X-Y-Z unit vector from second C atom to first C atom\n  Canchor_tilt = coords[2] - coords[3]\n  Canchor_tilt /= numpy.linalg.norm(Canchor_tilt) # make unit vector\n  Canchor_tilt = numpy.dot(Canchor_tilt, Nanchor_rotmat)\n  \n  \n  # get rotation angle of C anchor's O atom around the C anchor's own axis\n  Canchor_rotmat = vectors2rotation_matrix(coords[3] - coords[2], numpy.array([0.0,-1.0,0.0]))\n  Canchor_O = numpy.dot(coords[5] - coords[2], Canchor_rotmat)\n  Canchor_twist = atan2(Canchor_O[0], Canchor_O[2])\n  \n  d.stretch = stretch\n  d.Nangle = degrees(Nanchor_angle)%180\n  d.Ctilt = Canchor_tilt\n  d.Ntwist = degrees(Nanchor_twist)%360\n  d.Ctwist = degrees(Canchor_twist)%360\n  \n  return d, (origin, rotmat1, rotmat2)\n\n\n\n# def hash_loop_anchor_numeric(anchor_desc):\n#   return (\n#     int(anchor_desc.N1[0] / ANCHOR_GRANULARITY),\n#     int(anchor_desc.N1[1] / ANCHOR_GRANULARITY),\n#     int(anchor_desc.C1[0] / ANCHOR_GRANULARITY),\n#     int(anchor_desc.C2[0] / ANCHOR_GRANULARITY),\n#     int(anchor_desc.C2[1] / ANCHOR_GRANULARITY),\n#     int(anchor_desc.C2[2] / ANCHOR_GRANULARITY)\n#     )\n  \n\n# def hash_loop_anchor_string(anchor_desc):\n#   return hash_numeric_to_string(hash_loop_anchor_numeric(anchor_desc))\n\n\n\n# def hash_numeric_to_string(numeric):\n#   return join(\".\", numeric)\n\n# def hash_string_to_numeric(string):\n#   numeric=[]\n#   x = string.split('.')\n#   for y in x:\n#     numeric.append(int(y))\n#   return tuple(numeric)\n\n\n\n# def hash_structure(coords, transform, bin_size=STRUC_HASH_GRANULARITY):\n#   hash=array('c')\n#   for i in xrange(len(coords)):\n#     c = transform_xyz(coords[i], transform)\n#     hash.extend(str(int((c[0] + bin_size/2) / bin_size)))\n#     hash.append('.')\n#     hash.extend(str(int((c[1] + bin_size/2) / bin_size)))\n#     hash.append('.')\n#     hash.extend(str(int((c[2] + bin_size/2) / bin_size)))\n#     hash.append('.')\n#   hash.pop()\n#   return hash.tostring()\n\n\ndef transform_xyz(xyz, transform):\n  c = xyz - transform[0]\n  if transform[1] is not None:\n    c = numpy.dot(c, transform[1])\n  if transform[2] is not None:\n    c = numpy.dot(c, transform[2])\n  return c\n\n\n\n\n###########################################################\n\n\n# def score_decoy(seq, esss_vectors, ascii2index):\n#   # Calculate ESSS\n#   score=0\n#   for i,x in enumerate(seq):\n#     score += esss_vectors[i][ascii2index[ord(x)]]\n#   return score\n\n\ndef get_db_path(dbdir, loop_length):\n  return os.path.join(dbdir, \"length%d.sqlite\"%loop_length)\n\n\ndef get_db_file_dict(dbdir):\n  prefix = os.path.join(dbdir, \"length\")\n  suffix = \".sqlite\"\n  d={}\n  for fname in glob(prefix+\"*\"+suffix):\n    L = int(fname[len(prefix):-len(suffix)])\n    d[L] = fname\n  return d\n\n\ndef is_loop_length_in_database(dbdir, loop_length):\n  return os.path.exists(get_db_path(dbdir, loop_length))\n\n\ndef get_min_loop_length_in_database(dbdir):\n  dbfiles = glob(os.path.join(dbdir, \"length*.sqlite\"))\n  if not dbfiles:\n    raise RuntimeError(\"No database found in directory: \"+dbdir)\n  minlen=1000000\n  for fname in dbfiles:\n    length = os.path.splitext(os.path.basename(fname))[0].replace(\"length\", \"\")\n    minlen = min(minlen, int(length))\n  return minlen\n\n\n\ndef iterate_database(dbdir, loop_length, esst, anchor, sequence, strict_rmsd_cutoff, score_cutoff):\n  q = anchor\n  dbfile = get_db_path(dbdir, loop_length)\n  \n  # If we cannot possibly meet the score_cutoff with a perfect match to this sequence, reduce cut-off to allow perfect matches to be found\n  score_cutoff = min(score_cutoff, esst.get_perfect_score(sequence))\n  \n  #print \"Score cut-off:\", score_cutoff\n  \n  tables = esst.tables\n  ascii2index = esst.ascii2index\n  seqmap = tuple([ascii2index[ord(s)] for s in sequence])\n  \n  assert os.path.exists(dbfile), \"Database file missing: \"+dbfile\n  conn = sql.connect(dbfile)\n  \n  prevdihed=[\"\", [None]*len(seqmap)]\n  def score_sequence(loopseq, dihed):\n      if prevdihed[0] != dihed:\n        prevdihed[0] = dihed\n        for i,x in enumerate(dihed):\n          prevdihed[1][i] = tables[int(x)][seqmap[i]]\n      score=0\n      for i,x in enumerate(loopseq):\n        score += prevdihed[1][i][ascii2index[ord(x)]]  # Speed-optimised version\n        #score += tables[int(dihed[i])][seqmap[i]][ascii2index[ord(x)]]  # Naive version\n      return score\n  \n  \n  # DEBUGGING: See if this function throws an exception\n  score_sequence(sequence, \"0\"*len(sequence))\n  \n  \n  conn.create_function(\"score_seq\", 2, score_sequence)\n  \n  casep1 = q.C1[0]\n  casep2 = numpy.linalg.norm(q.C2)\n  casep3 = numpy.linalg.norm(q.N1 - q.C1)\n  casep4 = numpy.linalg.norm(q.N1 - q.C2)\n  min_casep1 = max(0, casep1 - strict_rmsd_cutoff*3)\n  max_casep1 =        casep1 + strict_rmsd_cutoff*3\n  min_casep2 = max(0, casep2 - strict_rmsd_cutoff*3)\n  max_casep2 =        casep2 + strict_rmsd_cutoff*3\n  min_casep3 = max(0, casep3 - strict_rmsd_cutoff*3)\n  max_casep3 =        casep3 + strict_rmsd_cutoff*3\n  min_casep4 = max(0, casep4 - strict_rmsd_cutoff*3)\n  max_casep4 =        casep4 + strict_rmsd_cutoff*3\n  \n  try:\n#      contacts,\n    for row in conn.execute(\"\"\"\n    SELECT\n      score_seq(sequence, dihedral) AS score,\n      dihedral,\n      sequence,\n      pdbcode,\n      start,\n      ((casep1-?)*(casep1-?) + (casep2-?)*(casep2-?) + (casep3-?)*(casep3-?) + (casep4-?)*(casep4-?)) / 16 AS internal_rmsd_sq\n    FROM\n      loops\n    WHERE\n      casep1 BETWEEN ? AND ?\n      AND casep2 BETWEEN ? AND ?\n      AND casep3 BETWEEN ? AND ?\n      AND casep4 BETWEEN ? AND ?\n      AND internal_rmsd_sq <= ?\n      AND score >= ?\n    \"\"\", (casep1, casep1, casep2, casep2, casep3, casep3, casep4, casep4, min_casep1, max_casep1, min_casep2, max_casep2, min_casep3, max_casep3, min_casep4, max_casep4, strict_rmsd_cutoff**2, score_cutoff)):\n      d = Data()\n      d.score, d.dihedrals, d.seq, d.struc, d.start = row[:5]\n      #d.score, d.dihedrals, d.seq, d.struc, d.start, d.native_contacts = row[:6]\n      d.internal_rmsd = numpy.sqrt(row[-1])\n#       d.casep1_diff = abs(row[5] - casep1)\n#       d.casep2_diff = abs(row[6] - casep2)\n#       d.casep3_diff = abs(row[7] - casep3)\n#       d.casep4_diff = abs(row[8] - casep4)\n      yield d\n  finally:\n    conn.close()\n\n\n\n###########################################################\n\n\n\ndef relabel_loop(decoy_residues, sequence, startnum=0, endnum=0, endinscode=\"\", chain=\"A\", prevatom=None, nextatom=None):\n  assert len(decoy_residues) == len(sequence)\n  \n  if prevatom:\n    chain = prevatom.chain\n    startnum = prevatom.ires + 1\n  \n  if nextatom:\n    if prevatom:\n      assert prevatom.chain == nextatom.chain\n    else:\n      chain = nextatom.chain\n    \n    if nextatom.inscode > \"A\":\n      endinscode = chr(ord(nextatom.inscode) - 1)\n    \n    if nextatom.inscode:\n      endnum = nextatom.ires\n    else:\n      endnum = nextatom.ires - 1\n  \n  inscode = \"A\"\n  for i,r in enumerate(decoy_residues):\n    r.set_type(residueCode(sequence[i]))\n    if startnum:\n      if startnum + i <= endnum:\n        for a in r:\n          a.ires = startnum + i\n          a.inscode = \"\"\n          a.chain = chain\n      else:\n        for a in r:\n          a.ires = endnum\n          a.inscode = inscode\n          a.chain = chain\n        inscode = chr(ord(inscode)+1)\n\n\nvdw_radii = {'C':1.70, 'N':1.55,'O':1.52,'S':1.80,'P':1.80,'H':1.20}\n\ndef is_clash(gh, atoms, decoy, vdw_factor=0.7):\n  if vdw_factor <= 0:\n    return False\n  \n  for r in decoy:\n    for a in r:\n      if a.atom not in (\"N\", \"CA\", \"C\", \"O\", \"CB\"):\n        continue\n      nbr = gh.get_neighbours(a.xyz, 1, max_dist=3.6*vdw_factor)\n      if nbr:\n        ix, dst = nbr[0]\n        try:\n          r1 = vdw_radii[a.atom[0]]\n        except KeyError:\n          r1 = 1.7\n        try:\n          r2 = vdw_radii[atoms[ix].atom[0]]\n        except KeyError:\n          r2 = 1.7\n        if dst < (r1 + r2) * vdw_factor:\n          return True\n  return False\n\n\ndef calculate_rmsd(a, b):\n    assert len(a) == len(b)\n    total = 0.0\n    count = 0\n    for i, ra in enumerate(a):\n      rb = b[i]\n      if ra.N and rb.N:\n        total += numpy.linalg.norm(ra.N.xyz - rb.N.xyz)**2\n        count += 1\n      if ra.CA and rb.CA:\n        total += numpy.linalg.norm(ra.CA.xyz - rb.CA.xyz)**2\n        count += 1\n      if ra.C and rb.C:\n        total += numpy.linalg.norm(ra.C.xyz - rb.C.xyz)**2\n        count += 1\n      if ra.O and rb.O:\n        total += numpy.linalg.norm(ra.O.xyz - rb.O.xyz)**2\n        count += 1\n    return numpy.sqrt(total / count)\n\n\ndef calculate_rmsdCA(a, b):\n    assert len(a) == len(b)\n    total = 0.0\n    for i, ra in enumerate(a):\n      rb = b[i]\n      total += numpy.linalg.norm(ra.CA.xyz - rb.CA.xyz)**2\n    return numpy.sqrt(total / len(a))\n\n\ndef norm_angle(a):\n  if a > 180:\n    a = 360 - a\n  elif a <= -180:\n    a += 360\n  return a\n\n\n\ndef compare_hit_anchor(query, hit):\n  d = Data()\n  # N anchor twist difference\n  d.ntwist_diff = abs(norm_angle(query.Ntwist - hit.Ntwist))\n  # C anchor twist difference\n  d.ctwist_diff = abs(norm_angle(query.Ctwist - hit.Ctwist))\n  return d\n\n\n\ndef find_contacts(gh, residue, maxdist=6.0):\n  atoms = gh.atoms\n  \n  # gh is a GeometricHash object\n  # atoms is a list of Atom objects that corresponds to the co-ordinates used to initialise gh\n  # residue is a Residue object to find contacts for\n  if maxdist <= 0:\n    return []\n  \n  a = residue.CB\n  if a is None:\n    a = residue.CA\n  if a is None:\n    return []\n  \n  results = []\n  nbrs = gh.get_neighbours(a.xyz, 999, max_dist=maxdist)\n  for n in nbrs:\n    ix, dst = n\n    a = atoms[ix]\n    \n    element = a.atom[0:1]\n    if element.isdigit():\n      element = a.atom[1:2]\n    if element == \"H\" or element.isdigit() or not element:\n      continue\n    \n    if a.chain != residue.chain or abs(a.ires - residue.ires) > 10:\n      results.append(a)\n  \n  return results\n\n\ndef find_contacts_simple(residues, i, maxdist=6.0):\n  maxsqrdist = maxdist ** 2\n  a1 = residues[i].CB\n  if a1 is None:\n    a1 = residues[i].CA\n  if a1 is None:\n    return []\n  \n  results = []\n  #for residue in residues[:i-10] + residues[i+11:]:\n  for residue in residues:\n    a2 = residue.CB\n    if a2 is None:\n      a2 = residue.CA\n    if a2 is None:\n      continue\n    \n    if a1.chain != a2.chain or abs(a1.ires - a2.ires) > 10:\n      sqd = sqrdist(a1, a2)\n      if sqd < maxsqrdist:\n        results.append(a2)\n  \n  return results\n\n\ndef get_contact_class(thischain, contact_atoms):\n  x = 0 # no contacts\n  for a in contact_atoms:\n    if a.chain != thischain:\n      x |= 1 # inter-chain contact\n    else:\n      x |= 2 # intra-chain contact\n  \n  # x = 0 ... no contacts\n  # x = 1 ... only inter-chain contacts\n  # x = 2 ... only intra-chain contacts\n  # x = 3 ... both intra and inter-chain contacts\n  return str(x)\n\n\n\ndef make_contact_gh(protein):\n  coords = []\n  gh_atoms = []\n  for chain in protein:\n    for r in chain:\n      a = r.CB\n      if a is None:\n        a = r.CA\n      if a is None:\n        continue\n      coords.append(a.xyz)\n      gh_atoms.append(a)\n  \n  for chain in protein.ligands:\n    for r in chain:\n      for a in r:\n        element = a.atom[0:1]\n        if element.isdigit():\n          element = a.atom[1:2]\n        if element == \"H\" or element.isdigit() or not element:\n          continue\n        coords.append(a.xyz)\n        gh_atoms.append(a)\n  \n  gh = GeometricHash(numpy.array(coords))\n  gh.atoms = gh_atoms\n  \n  return gh\n", "meta": {"hexsha": "6f3f6e4293ea213223745501428a322f4e0c214a", "size": 22286, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/Alignment/FREAD/tools/prosci/loops/loopmodel.py", "max_stars_repo_name": "Eitan177/StructuralMapping", "max_stars_repo_head_hexsha": "c20ce43de2698902d606b718c9a9fdf2296b0a52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2018-08-03T17:59:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-10T20:56:32.000Z", "max_issues_repo_path": "code/Alignment/FREAD/tools/prosci/loops/loopmodel.py", "max_issues_repo_name": "Eitan177/StructuralMapping", "max_issues_repo_head_hexsha": "c20ce43de2698902d606b718c9a9fdf2296b0a52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Alignment/FREAD/tools/prosci/loops/loopmodel.py", "max_forks_repo_name": "Eitan177/StructuralMapping", "max_forks_repo_head_hexsha": "c20ce43de2698902d606b718c9a9fdf2296b0a52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-01-08T21:40:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-10T21:00:58.000Z", "avg_line_length": 28.7190721649, "max_line_length": 208, "alphanum_fraction": 0.6056717222, "include": true, "reason": "import numpy", "num_tokens": 7137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3415825128436339, "lm_q1q2_score": 0.17879123806316125}}
{"text": "\"\"\"\nExperimental code related to cifar\n\"\"\"\nimport numpy as np\nimport ubelt as ub\nimport torch\n# import torchvision\nimport pandas as pd\nfrom torchvision.datasets import cifar\nfrom netharn import xpu_device\nfrom netharn import monitor\nfrom netharn import initializers\nfrom netharn import hyperparams\nfrom netharn import fit_harness\nfrom netharn.transforms import (ImageCenterScale,)\n# from netharn.transforms import (RandomWarpAffine, RandomGamma, RandomBlur,)\nimport imgaug as ia\nimport imgaug.augmenters as iaa\nfrom netharn import util\nimport netharn as nh\n\n\nclass CropTo(iaa.Augmenter):\n    def __init__(self, shape,  name=None, deterministic=False, random_state=None):\n        super(CropTo, self).__init__(name=name, deterministic=deterministic, random_state=random_state)\n        self.shape = shape\n\n    def _augment_images(self, images, random_state, parents, hooks):\n        result = []\n        nb_images = len(images)\n        seeds = random_state.randint(0, 10**6, (nb_images,))\n        for i in range(nb_images):\n            seed = seeds[i]\n            height, width = images[i].shape[0:2]\n            top, bot, left, right = self._draw_samples_image(seed, height, width)\n\n            image_cr = images[i][top:bot, left:right]\n            image_cr = np.pad(image_cr, ((1, 1), (1, 1)), mode='constant')\n\n            result.append(image_cr)\n        return result\n\n    def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks):\n        result = []\n        nb_images = len(keypoints_on_images)\n        seeds = random_state.randint(0, 10**6, (nb_images,))\n        for i, keypoints_on_image in enumerate(keypoints_on_images):\n            seed = seeds[i]\n            height, width = keypoints_on_image.shape[0:2]\n            top, bot, left, right = self._draw_samples_image(seed, height, width)\n            shifted = keypoints_on_image.shift(x=-left, y=-top)\n            shifted.shape = (\n                height - top - bot,\n                width - left - right\n            ) + shifted.shape[2:]\n            result.append(shifted)\n        return result\n\n    def _draw_samples_image(self, seed, height, width):\n        \"\"\"\n        height = 32\n        width = 32\n        h, w = shape = (30, 30)\n        random_state = np.random\n        \"\"\"\n        random_state = ia.new_random_state(seed)\n        h, w = self.shape\n\n        assert w <= width, '{} {}'.format(w, width)\n        assert h <= height, '{} {}'.format(h, height)\n        space_h = height - h\n        space_w = width - w\n\n        top = random_state.randint(0, space_h + 1)\n        bot = height - (space_h - top)\n\n        left = random_state.randint(0, space_w + 1)\n        right = width - (space_w - left)\n\n        sub = [top, bot, left, right]\n        return sub\n\n    def get_parameters(self):\n        return [self.shape]\n\n\nclass Task(object):\n    def __init__(task, labelnames=None, ignore_labelnames=[], alias={}):\n        if labelnames is not None:\n            task.set_labelnames(labelnames, ignore_labelnames, alias)\n\n    def set_labelnames(task, labelnames, ignore_labelnames=[], alias={}):\n        task.labelnames = list(labelnames)\n        task.labelname_alias = alias\n        task.ignore_labelnames = ignore_labelnames\n\n        # Remove aliased classes\n        for k in alias.keys():\n            if k in task.labelnames:\n                task.labelnames.remove(k)\n\n        # Assign an integer label to each labelname\n        task.labelname_to_id = ub.invert_dict(dict(enumerate(task.labelnames)))\n\n        # Map aliased classes to a different label\n        for k, v in alias.items():\n            task.labelname_to_id[k] = task.labelname_to_id[v]\n\n        task.ignore_labelnames = ignore_labelnames\n        task.ignore_labels = np.array(\n            list(ub.take(task.labelname_to_id, task.ignore_labelnames)))\n\n        task.labels = np.arange(len(task.labelnames))\n        task.relevant_labels = np.setdiff1d(task.labels, task.ignore_labels)\n\n\ndef radial_fourier_mask(img_chw, radius=11, axis=None, clip=None):\n    \"\"\"\n    In [1] they use a radius of 11.0 on CIFAR-10.\n\n    Args:\n        img_chw (ndarray): assumed to be float 01\n\n    References:\n        [1] Jo and Bengio \"Measuring the tendency of CNNs to Learn Surface Statistical Regularities\" 2017.\n        https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_transforms/py_fourier_transform/py_fourier_transform.html\n\n    CommandLine:\n        python examples/cifar.py radial_fourier_mask --show\n\n    Example:\n        >>> dset = cifar_training_datasets()['test']\n        >>> dset.center_inputs = None\n        >>> img_tensor, label = dset[7]\n        >>> img_chw = img_tensor.numpy()\n        >>> out = radial_fourier_mask(img_chw, radius=11)\n        >>> # xdoc: REQUIRES(--show)\n        >>> nh.util.qtensure()\n        >>> def keepdim(func):\n        >>>     def _wrap(im):\n        >>>         needs_transpose = (im.shape[0] == 3)\n        >>>         if needs_transpose:\n        >>>             im = im.transpose(1, 2, 0)\n        >>>         out = func(im)\n        >>>         if needs_transpose:\n        >>>             out = out.transpose(2, 0, 1)\n        >>>         return out\n        >>>     return _wrap\n        >>> @keepdim\n        >>> def rgb_to_bgr(im):\n        >>>     return util.convert_colorspace(im, src_space='rgb', dst_space='bgr')\n        >>> @keepdim\n        >>> def bgr_to_lab(im):\n        >>>     return util.convert_colorspace(im, src_space='bgr', dst_space='lab')\n        >>> @keepdim\n        >>> def lab_to_bgr(im):\n        >>>     return util.convert_colorspace(im, src_space='lab', dst_space='bgr')\n        >>> @keepdim\n        >>> def bgr_to_yuv(im):\n        >>>     return util.convert_colorspace(im, src_space='bgr', dst_space='yuv')\n        >>> @keepdim\n        >>> def yuv_to_bgr(im):\n        >>>     return util.convert_colorspace(im, src_space='yuv', dst_space='bgr')\n        >>> dpath = ub.ensuredir('./fouriertest')\n        >>> from matplotlib import pyplot as plt\n        >>> for x in ub.ProgIter(range(100)):\n        >>>     img_tensor, label = dset[x]\n        >>>     img_chw = img_tensor.numpy()\n        >>>     bgr_img = rgb_to_bgr(img_chw)\n        >>>     nh.util.imshow(bgr_img.transpose(1, 2, 0), fnum=1)\n        >>>     pnum_ = nh.util.PlotNums(nRows=4, nCols=5)\n        >>>     for r in range(0, 17):\n        >>>         imgt = radial_fourier_mask(bgr_img, r, clip=(0, 1))\n        >>>         nh.util.imshow(imgt.transpose(1, 2, 0), pnum=pnum_(), fnum=2)\n        >>>         plt.gca().set_title('r = {}'.format(r))\n        >>>     nh.util.set_figtitle('BGR')\n        >>>     plt.gcf().savefig(join(dpath, '{}_{:08d}.png'.format('bgr', x)))\n        >>>     pnum_ = nh.util.PlotNums(nRows=4, nCols=5)\n        >>>     for r in range(0, 17):\n        >>>         imgt = lab_to_bgr(radial_fourier_mask(bgr_to_lab(bgr_img), r)).transpose(1, 2, 0)\n        >>>         nh.util.imshow(imgt, pnum=pnum_(), fnum=3)\n        >>>         plt.gca().set_title('r = {}'.format(r))\n        >>>         #imgt = lab_to_bgr(to_lab(bgr_img)).transpose(1, 2, 0)\n        >>>         #nh.util.imshow(lab_to_bgr(to_lab(bgr_img)).transpose(1, 2, 0), pnum=pnum_(), fnum=2)\n        >>>     nh.util.set_figtitle('LAB')\n        >>>     plt.gcf().savefig(join(dpath, '{}_{:08d}.png'.format('lab', x)))\n        >>>     pnum_ = nh.util.PlotNums(nRows=4, nCols=5)\n        >>>     for r in range(0, 17):\n        >>>         imgt = yuv_to_bgr(radial_fourier_mask(bgr_to_yuv(bgr_img), r, clip=(0., 1.))).transpose(1, 2, 0)\n        >>>         nh.util.imshow(imgt, pnum=pnum_(), fnum=4)\n        >>>         plt.gca().set_title('r = {}'.format(r))\n        >>>     nh.util.set_figtitle('YUV')\n        >>>     plt.gcf().savefig(join(dpath, '{}_{:08d}.png'.format('yuv', x)))\n        >>> nh.util.show_if_requested()\n\n    Ignore:\n        im_chw = bgr_to_lab(bgr_img)\n    \"\"\"\n    import cv2\n    rows, cols = img_chw.shape[1:3]\n\n    def fourier(s):\n        # note: cv2 functions would probably be faster here\n        return np.fft.fftshift(np.fft.fft2(s))\n\n    def inv_fourier(f):\n        # use real because LAB has negative components\n        return np.real(np.fft.ifft2(np.fft.ifftshift(f)))\n\n    diam = radius * 2\n    left = int(np.floor((cols - diam) / 2))\n    right = int(np.ceil((cols - diam) / 2))\n    top = int(np.floor((rows - diam) / 2))\n    bot = int(np.ceil((rows - diam) / 2))\n\n    # element = skimage.morphology.disk(radius)\n    # mask = np.pad(element, ((top, bot), (left, right)), 'constant')\n    if diam > 0:\n        element = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (diam, diam))\n        mask = cv2.copyMakeBorder(element, top, bot, left, right, cv2.BORDER_CONSTANT, value=0)\n    else:\n        mask = 0\n\n    out = np.empty_like(img_chw)\n    if axis is None:\n        for i, s in enumerate(img_chw):\n            # hadamard product (aka simple element-wise multiplication)\n            out[i] = inv_fourier(fourier(s) * mask)\n    else:\n        for i, s in enumerate(img_chw):\n            if i in axis:\n                # hadamard product (aka simple element-wise multiplication)\n                out[i] = inv_fourier(fourier(s) * mask)\n            else:\n                out[i] = s\n    if clip:\n        out = np.clip(out, *clip)\n    return out\n\n    # nrows = cv2.getOptimalDFTSize(rows)\n    # ncols = cv2.getOptimalDFTSize(cols)\n    # right = ncols - cols\n    # bottom = nrows - rows\n    # if right or bottom:\n    #     bordertype = cv2.BORDER_CONSTANT  # just to avoid line breakup in PDF file\n    #     nimg = cv2.copyMakeBorder(img, 0, bottom, 0, right, bordertype, value=0)\n    # dft_chans = [cv2.dft(chan, flags=cv2.DFT_COMPLEX_OUTPUT) for chan in img_chw]\n    # dft = np.dstack(dft_chans).transpose(2, 0, 1)\n    # dft_mag = np.dstack([(c ** 2).sum(axis=-1) for c in dft_chans]).transpose(2, 0, 1)\n    # dft_shift = [np.fft.fftshift(c) for c in dft_chans]\n    # dft_mag = np.dstack([(c ** 2).sum(axis=-1) for c in dft_shift]).transpose(2, 0, 1)\n    # dft_filt_shift = [c * mask[:, :, None] for c in dft_shift]\n    # dft_filt = [np.fft.ifftshift(c) for c in dft_filt_shift]\n    # idft_filt = [cv2.idft(c) for c in dft_filt]\n    # img_filt = np.dstack([np.linalg.norm(c, axis=-1) for c in idft_filt])\n    # nh.util.imshow(dft_mag.transpose(1, 2, 0), norm=True)\n    # if False:\n    #     nh.util.imshow(np.log(dft_mag[0]), norm=True, pnum=(1, 3, 1))\n    #     nh.util.imshow(np.log(dft_mag[1]), norm=True, pnum=(1, 3, 2))\n    #     nh.util.imshow(np.log(dft_mag[2]), norm=True, pnum=(1, 3, 3))\n\n\ndef zca_whitening_matrix(X):\n    \"\"\"\n    Function to compute ZCA whitening matrix (aka Mahalanobis whitening).\n    Args:\n        X (ndarray): [M x N] matrix, Rows: Variables, Columns: Observations\n\n    Returns:\n        ZCAMatrix: [M x M] matrix\n\n    References:\n        https://stackoverflow.com/a/38590790/887074\n\n    Example:\n        >>> rng = np.random.RandomState(0)\n        >>> # Construct a matrix of observations from grayscale 8x8 images\n        >>> gray_images = [rng.rand(8, 8) for _ in range(1000)]\n        >>> X = np.array([img.ravel() for img in gray_images]).T\n        >>> M = zca_whitening_matrix(X)\n        >>> img = gray_images[0]\n        >>> norm = M.dot(img.ravel()).reshape(8, 8)\n        >>> # ... for the RGB channels of color images\n        >>> rgb_images = [rng.rand(3, 8, 8) for _ in range(1000)]\n        >>> #X = np.array([img.mean(axis=(1, 2)) for img in rgb_images]).T\n        >>> X = np.hstack([img.reshape(3, -1) for img in rgb_images])\n        >>> M = zca_whitening_matrix(X)\n        >>> img = rgb_images[0]\n        >>> norm = M.dot(img.reshape(3, 64)).reshape(3, 8, 8)\n    \"\"\"\n    # Covariance matrix [column-wise variables]: Sigma = (X-mu)' * (X-mu) / N\n    sigma = np.cov(X, rowvar=True)  # [M x M]\n    # Singular Value Decomposition. X = U * np.diag(S) * V\n    U, S, V = np.linalg.svd(sigma)\n    # U: [M x M] eigenvectors of sigma.\n    # S: [M x 1] eigenvalues of sigma.\n    # V: [M x M] transpose of U\n    # Whitening constant: prevents division by zero\n    epsilon = 1e-5\n    L = np.diag(1.0 / np.sqrt(S + epsilon))\n    # ZCA Whitening matrix: U * Lambda * U'\n    ZCAMatrix = np.dot(U, np.dot(L, U.T))  # [M x M]\n    return ZCAMatrix\n\n\nclass CIFAR10_Task(Task):\n    \"\"\"\n    task = CIFAR10_Task()\n    task._initialize()\n    ignore_labelnames = []\n    alias = {}\n    \"\"\"\n    def __init__(task, root=None):\n        if root is None:\n            root = ub.ensure_app_cache_dir('netharn')\n        task.root = root\n        task._initialize()\n\n    def _initialize(task):\n        from os.path import join\n        import pickle\n        train_dset = cifar.CIFAR10(root=task.root, download=False, train=True)\n\n        fpath = join(train_dset.root,\n                     cifar.CIFAR10.base_folder, 'batches.meta')\n        with open(fpath, 'rb') as fo:\n            entry = pickle.load(fo, encoding='latin1')\n            labelnames = entry['label_names']\n        task.set_labelnames(labelnames)\n\n\nclass CIFAR100_Task(Task):\n    \"\"\"\n    task = CIFAR100_Task()\n    task._initialize()\n    ignore_labelnames = []\n    alias = {}\n    \"\"\"\n    def __init__(task, root=None):\n        if root is None:\n            root = ub.ensure_app_cache_dir('netharn')\n        task.root = root\n        task._initialize()\n\n    def _initialize(task):\n        from os.path import join\n        import pickle\n        train_dset = cifar.CIFAR100(root=task.root, download=False, train=True)\n\n        fpath = join(train_dset.root, cifar.CIFAR100.base_folder, 'meta')\n        with open(fpath, 'rb') as fo:\n            entry = pickle.load(fo, encoding='latin1')\n            labelnames = entry['fine_label_names']\n        task.set_labelnames(labelnames)\n\n\ndef mutex_clf_gt_info(gt_labels, task):\n    \"\"\"\n    gt_labels = train_dset.train_labels\n    \"\"\"\n    index = pd.Index(task.labels, name='label')\n    gtstats = pd.DataFrame(0, index=index, columns=['freq'], dtype=np.int)\n\n    label_freq = pd.value_counts(gt_labels)\n    gtstats.freq = pd.to_numeric(label_freq)\n\n    gtstats['classname'] = list(ub.take(task.labelnames, gtstats.index))\n    gtstats['mf_weight'] = gtstats.freq.median() / gtstats.freq\n    gtstats.loc[~np.isfinite(gtstats.mf_weight), 'mf_weight'] = 1\n\n    # Clip weights, so nothing gets crazy high weights, low weights are ok\n    gtstats = gtstats.sort_index()\n    gtstats.index.name = 'label'\n    gtstats = gtstats.reset_index().set_index('classname', drop=False)\n    return gtstats\n\n\nclass InMemoryInputs(ub.NiceRepr):\n    \"\"\"\n    Change inputs.Inputs to OnDiskInputs\n    \"\"\"\n    def __init__(inputs, tag=''):\n        inputs.tag = tag\n        inputs.im = None\n        inputs.gt = None\n        inputs.colorspace = None\n        inputs.input_id = None\n\n    def __nice__(inputs):\n        n = len(inputs)\n        return '{} {}'.format(inputs.tag, n)\n\n    def __len__(inputs):\n        if inputs.im is not None:\n            n = len(inputs.im)\n        elif inputs.gt is not None:\n            n = len(inputs.gt)\n        else:\n            n = 0\n        return n\n\n    @classmethod\n    def from_bhwc_rgb(cls, bhwc, labels=None, **kw):\n        # convert to bhwc\n        inputs = cls(**kw)\n        inputs.im = bhwc\n        inputs.gt = labels\n        inputs.colorspace = 'rgb'\n        return inputs\n\n    def convert_colorspace(inputs, colorspace, inplace=False):\n        if colorspace.lower() == inputs.colorspace.lower():\n            if not inplace:\n                return inputs.im\n            return\n        im_out = np.empty_like(inputs.im)\n        dst = np.ascontiguousarray(np.empty_like(inputs.im[0]))\n        for ix, im in enumerate(inputs.im):\n            util.convert_colorspace(im, src_space=inputs.colorspace,\n                                    dst_space=colorspace, dst=dst)\n            im_out[ix] = dst\n        if inplace:\n            inputs.im = im_out\n            inputs.colorspace = colorspace\n        else:\n            return im_out\n\n    def take(inputs, idxs, **kw):\n        new_inputs = inputs.__class__(**kw)\n        new_inputs.im = inputs.im.take(idxs, axis=0)\n        new_inputs.gt = inputs.gt.take(idxs, axis=0)\n        new_inputs.colorspace = inputs.colorspace\n        return new_inputs\n\n    def prepare_id(self, force=False):\n        if self.input_id is not None and not force:\n            return\n\n        depends = []\n        depends.append(self.im)\n        depends.append(self.gt)\n\n    def _set_id_from_dependency(self, depends):\n        \"\"\"\n        Allow for arbitrary representation of dependencies\n        (user must ensure that it is consistent)\n        \"\"\"\n        print('Preparing id for {} images'.format(self.tag))\n        abbrev = 8\n        hashid = util.hash_data(depends)[:abbrev]\n        n_input = len(self)\n        self.input_id = '{}-{}'.format(n_input, hashid)\n        print(' * n_input = {}'.format(n_input))\n        print(' * input_id = {}'.format(self.input_id))\n\n\nclass CIFAR_Wrapper(torch.utils.data.Dataset):  # cifar.CIFAR10):\n    def __init__(dset, inputs, task, workdir, output_colorspace='RGB'):\n        dset.inputs = inputs\n        dset.task = task\n\n        dset.output_colorspace = output_colorspace\n\n        dset.rng = np.random.RandomState(432432)\n\n        inputs_base = ub.ensuredir((workdir, 'inputs'))\n        inputs.base_dpath = inputs_base\n        if len(inputs):\n            inputs.prepare_id()\n            dset.input_id = inputs.input_id\n            dset.with_gt = dset.inputs.gt is not None\n        else:\n            dset.input_id = ''\n\n        # TODO: only use horizontal flipping and translation by 4 pixels to\n        # match results from other papers\n        # https://arxiv.org/pdf/1603.09382.pdf page 8\n\n        dset.augment = None\n        # dset.im_augment = torchvision.transforms.Compose([\n        #     RandomGamma(rng=dset.rng),\n        #     RandomBlur(rng=dset.rng),\n        # ])\n        # dset.rand_aff = RandomWarpAffine(dset.rng)\n\n        augmentors = [\n            # iaa.Sometimes(.8, iaa.ContrastNormalization((0.2, 1.8))),\n            iaa.Fliplr(p=.5),\n            iaa.Affine(translate_px={'x': (-1, 1), 'y': (-1, 1)}),\n\n            # CropTo((30, 30)),\n            # iaa.Crop(px=(1, 1, 1, 1)),\n            # imgaug.Brightness(63),\n            # imgaug.RandomCrop((30, 30)),\n            # imgaug.MeanVarianceNormalize(all_channel=True)\n        ]\n        dset.augmenter = iaa.Sequential(augmentors)\n        # iaa.Sequential([\n        #     iaa.Affine(translate_px={\"x\":-40}),\n        #     iaa.AdditiveGaussianNoise(scale=0.1*255)\n        # ])\n\n        # dset.rand_aff = RandomWarpAffine(\n        #     dset.rng, tx_pdf=(-2, 2), ty_pdf=(-2, 2), flip_lr_prob=.5,\n        #     zoom_pdf=None, shear_pdf=None, flip_ud_prob=None,\n        #     enable_stretch=None, default_distribution='uniform')\n\n        dset.center_inputs = None\n\n    def _make_normalizer(dset, mode='independent'):\n        \"\"\"\n        Example:\n            >>> inputs, task = cifar_inputs(train=True)\n            >>> workdir = ub.ensuredir(ub.truepath('~/data/work/cifar'))\n            >>> dset = CIFAR_Wrapper(inputs, task, workdir, 'RGB')\n            >>> center_inputs = dset._make_normalizer('independent')\n        \"\"\"\n        if len(dset.inputs):\n            # compute normalizers in the output colorspace\n            out_im = dset.inputs.convert_colorspace(dset.output_colorspace,\n                                                    inplace=False)\n            if mode == 'dependant':\n                # dependent centering per channel (for RGB)\n                im_mean = out_im.mean()\n                im_scale = out_im.std()\n            elif mode == 'independent':\n                # Independent centering per channel (for LAB)\n                im_mean = out_im.mean(axis=(0, 1, 2))\n                im_scale = out_im.std(axis=(0, 1, 2))\n\n            center_inputs = ImageCenterScale(im_mean, im_scale)\n\n        dset.center_inputs = center_inputs\n        return center_inputs\n\n    def __len__(dset):\n        return len(dset.inputs)\n\n    def load_inputs(dset, index):\n        \"\"\"\n        Ignore:\n            >>> inputs, task = cifar_inputs(train=False)\n            >>> workdir = ub.ensuredir(ub.truepath('~/data/work/cifar'))\n            >>> dset = CIFAR_Wrapper(inputs, task, workdir, 'LAB')\n            >>> dset._make_normalizer('independent')\n            >>> index = 0\n            >>> im, gt = dset.load_inputs(index)\n\n        Example:\n            >>> inputs, task = cifar_inputs(train=False)\n            >>> workdir = ub.ensuredir(ub.truepath('~/data/work/cifar'))\n            >>> dset = CIFAR_Wrapper(inputs, task, workdir, 'RGB')\n            >>> index = 0\n            >>> im, gt = dset.load_inputs(index)\n            >>> from netharn.util import mplutil\n            >>> mplutil.qtensure()\n            >>> dset = CIFAR_Wrapper(inputs, task, workdir, 'RGB')\n            >>> dset.augment = True\n            >>> im, gt = dset.load_inputs(index)\n            >>> mplutil.imshow(im, colorspace='rgb')\n\n            >>> dset = CIFAR_Wrapper(inputs, task, workdir, 'LAB')\n            >>> dset.augment = True\n            >>> im, gt = dset.load_inputs(index)\n            >>> mplutil.imshow(im, colorspace='LAB')\n        \"\"\"\n        assert dset.inputs.colorspace.lower() == 'rgb', (\n            'we must be in rgb for augmentation')\n        im = dset.inputs.im[index]\n\n        if dset.inputs.gt is not None:\n            gt = dset.inputs.gt[index]\n        else:\n            gt = None\n\n        if dset.augment:\n            # Image augmentation must be done in RGB\n            # Augment intensity independently\n            # im = dset.im_augment(im)\n            # Augment geometry consistently\n\n            # params = dset.rand_aff.random_params()\n            # im = dset.rand_aff.warp(im, params, interp='cubic', backend='cv2')\n\n            im = util.convert_colorspace(im, src_space=dset.inputs.colorspace,\n                                         dst_space='rgb')\n            # Do augmentation in uint8 RGB\n            im = (im * 255).astype(np.uint8)\n            im = dset.augmenter.augment_image(im)\n            im = (im / 255).astype(np.float32)\n            im = util.convert_colorspace(im, src_space='rgb',\n                                         dst_space=dset.output_colorspace)\n        else:\n            im = util.convert_colorspace(im, src_space=dset.inputs.colorspace,\n                                         dst_space=dset.output_colorspace)\n        # Do centering of inputs\n        if dset.center_inputs:\n            im = dset.center_inputs(im)\n        return im, gt\n\n    def __getitem__(dset, index):\n        from netharn import im_loaders\n        im, gt = dset.load_inputs(index)\n        input_tensor = im_loaders.numpy_image_to_float_tensor(im)\n\n        if dset.with_gt:\n            # print('gotitem: ' + str(data_tensor.shape))\n            # print('gt_tensor: ' + str(gt_tensor.shape))\n            return input_tensor, gt\n        else:\n            return input_tensor\n\n    @property\n    def n_channels(dset):\n        return 3\n\n    @property\n    def n_classes(dset):\n        return int(dset.task.labels.max() + 1)\n\n    @property\n    def ignore_labels(dset):\n        return dset.task.ignore_labels\n\n    def class_weights(dset):\n        \"\"\"\n            >>> from netharn.live.sseg_train import *\n            >>> dset = load_task_dataset('urban_mapper_3d')['train']\n            >>> dset.class_weights()\n        \"\"\"\n        # # Handle class weights\n        # print('prep class weights')\n        # gtstats = dset.inputs.prepare_gtstats(dset.task)\n        # gtstats = dset.inputs.gtstats\n        # # Take class weights (ensure they are in the same order as labels)\n        # mfweight_dict = gtstats['mf_weight'].to_dict()\n        # class_weights = np.array(list(ub.take(mfweight_dict, dset.task.classnames)))\n        # class_weights[dset.task.ignore_labels] = 0\n        # # HACK\n        # # class_weights[0] = 1.0\n        # # class_weights[1] = 0.7\n        # print('class_weights = {!r}'.format(class_weights))\n        # print('class_names   = {!r}'.format(dset.task.classnames))\n        class_weights = np.ones(dset.n_classes)\n        return class_weights\n\n\ndef cifar_inputs(train=False, cifar_num=10):\n    root = ub.ensure_app_cache_dir('netharn')\n\n    if cifar_num == 10:\n        train_dset = cifar.CIFAR10(root=root, download=True, train=train)\n        task = CIFAR10_Task()\n    else:\n        train_dset = cifar.CIFAR100(root=root, download=True, train=train)\n        task = CIFAR100_Task()\n    if train:\n        bchw = (train_dset.train_data).astype(np.float32) / 255.0\n        labels = np.array(train_dset.train_labels)\n    else:\n        bchw = (train_dset.test_data).astype(np.float32) / 255.0\n        labels = np.array(train_dset.test_labels)\n    inputs = InMemoryInputs.from_bhwc_rgb(bchw, labels=labels)\n    if train:\n        inputs.tag = 'learn'\n    else:\n        inputs.tag = 'test'\n    return inputs, task\n\n\ndef cifar_training_datasets(output_colorspace='RGB', norm_mode='independent',\n                            cifar_num=10):\n    \"\"\"\n    Example:\n        >>> datasets = cifar_training_datasets()\n    \"\"\"\n    inputs, task = cifar_inputs(train=True, cifar_num=cifar_num)\n\n    # split training into train / validation\n    # 45K / 5K validation split was used in densenet and resnet papers.\n    # https://arxiv.org/pdf/1512.03385.pdf page 7\n    # https://arxiv.org/pdf/1608.06993.pdf page 5\n\n    vali_frac = .1  # 10%  is 5K images\n    n_vali = int(len(inputs) * vali_frac)\n    # n_vali = 10000  # 10K validation as in http://torch.ch/blog/2015/07/30/cifar.html\n\n    # the gt indexes seem to already be scrambled, I think other papers sample\n    # validation from the end, so lets do that\n    # The NIN paper https://arxiv.org/pdf/1312.4400.pdf in section 4 mentions\n    # that it uses the last 10K images for validation\n    input_idxs = np.arange(len(inputs))\n    # or just uncomment this line for reproducable random sampling\n    # input_idxs = util.random_indices(len(inputs), seed=1184576173)\n\n    train_idxs = sorted(input_idxs[:-n_vali])\n    vali_idxs = sorted(input_idxs[-n_vali:])\n\n    train_inputs = inputs.take(train_idxs, tag='train')\n    vali_inputs = inputs.take(vali_idxs, tag='vali')\n    test_inputs, _ = cifar_inputs(train=False, cifar_num=cifar_num)\n    # The dataset name and indices should fully specifiy dependencies\n    train_inputs._set_id_from_dependency(\n        ['cifar{}-train'.format(cifar_num), train_idxs])\n    vali_inputs._set_id_from_dependency(\n        ['cifar{}-train'.format(cifar_num), vali_idxs])\n    test_inputs._set_id_from_dependency(['cifar{}-test'.format(cifar_num)])\n\n    workdir = ub.ensuredir(ub.truepath('~/data/work/cifar'))\n\n    train_dset = CIFAR_Wrapper(\n        train_inputs, task, workdir, output_colorspace=output_colorspace)\n    vali_dset = CIFAR_Wrapper(\n        vali_inputs, task, workdir, output_colorspace=output_colorspace)\n    test_dset = CIFAR_Wrapper(test_inputs, task, workdir,\n                              output_colorspace=output_colorspace)\n    print('built datasets')\n\n    datasets = {\n        'train': train_dset,\n        'vali': vali_dset,\n        'test': test_dset,\n    }\n\n    print('computing normalizers')\n    datasets['train'].center_inputs = datasets['train']._make_normalizer(\n        norm_mode)\n    for key in datasets.keys():\n        datasets[key].center_inputs = datasets['train'].center_inputs\n    print('computed normalizers')\n\n    datasets['train'].augment = True\n    return datasets\n\ndef train():\n    \"\"\"\n    Example:\n        >>> train()\n    \"\"\"\n    import random\n    np.random.seed(1031726816 % 4294967295)\n    torch.manual_seed(137852547 % 4294967295)\n    random.seed(2497950049 % 4294967295)\n\n    xpu = xpu_device.XPU.from_argv()\n    print('Chosen xpu = {!r}'.format(xpu))\n\n    cifar_num = 10\n\n    if ub.argflag('--lab'):\n        datasets = cifar_training_datasets(\n            output_colorspace='LAB', norm_mode='independent', cifar_num=cifar_num)\n    elif ub.argflag('--rgb'):\n        datasets = cifar_training_datasets(\n            output_colorspace='RGB', norm_mode='independent', cifar_num=cifar_num)\n    elif ub.argflag('--rgb-dep'):\n        datasets = cifar_training_datasets(\n            output_colorspace='RGB', norm_mode='dependant', cifar_num=cifar_num)\n    else:\n        raise AssertionError('specify --rgb / --lab')\n\n    import netharn.models.densenet\n\n    # batch_size = (128 // 3) * 3\n    batch_size = 64\n\n    # initializer_ = (initializers.KaimingNormal, {\n    #     'nonlinearity': 'relu',\n    # })\n\n    lr = 0.1\n    initializer_ = (initializers.LSUV, {})\n\n    hyper = hyperparams.HyperParams(\n        model=(netharn.models.densenet.DenseNet, {\n            'cifar': True,\n            'block_config': (32, 32, 32),  # 100 layer depth\n            'num_classes': datasets['train'].n_classes,\n            'drop_rate': float(ub.argval('--drop_rate', default=.2)),\n            'groups': 1,\n        }),\n        optimizer=(torch.optim.SGD, {\n            # 'weight_decay': .0005,\n            'weight_decay': float(ub.argval('--weight_decay', default=.0005)),\n            'momentum': 0.9,\n            'nesterov': True,\n            'lr': 0.1,\n        }),\n        scheduler=(nh.schedulers.ListedLR, {\n            'points': {\n                0: lr,\n                150: lr * 0.1,\n                250: lr * 0.01,\n            },\n            'interpolate': False\n        }),\n        monitor=(nh.Monitor, {\n            'minimize': ['loss'],\n            'maximize': ['mAP'],\n            'patience': 314,\n            'max_epoch': 314,\n        }),\n        initializer=initializer_,\n        criterion=(torch.nn.CrossEntropyLoss, {\n        }),\n        # Specify anything else that is special about your hyperparams here\n        # Especially if you make a custom_batch_runner\n        augment=str(datasets['train'].augmenter),\n        other=ub.dict_union({\n            # TODO: type of augmentation as a parameter dependency\n            # 'augmenter': str(datasets['train'].augmenter),\n            # 'augment': datasets['train'].augment,\n            'batch_size': batch_size,\n            'colorspace': datasets['train'].output_colorspace,\n            'n_classes': datasets['train'].n_classes,\n            # 'center_inputs': datasets['train'].center_inputs,\n        }, datasets['train'].center_inputs.__dict__),\n    )\n    # if ub.argflag('--rgb-indie'):\n    #     hyper.other['norm'] = 'dependant'\n    hyper.input_ids['train'] = datasets['train'].input_id\n\n    xpu = xpu_device.XPU.cast('auto')\n    print('xpu = {}'.format(xpu))\n\n    data_kw = {'batch_size': batch_size}\n    if xpu.is_gpu():\n        data_kw.update({'num_workers': 8, 'pin_memory': True})\n\n    tags = ['train', 'vali', 'test']\n\n    loaders = ub.odict()\n    for tag in tags:\n        dset = datasets[tag]\n        shuffle = tag == 'train'\n        data_kw_ = data_kw.copy()\n        if tag != 'train':\n            data_kw_['batch_size'] = max(batch_size // 4, 1)\n        loader = torch.utils.data.DataLoader(dset, shuffle=shuffle, **data_kw_)\n        loaders[tag] = loader\n\n    harn = fit_harness.FitHarness(\n        hyper=hyper, datasets=datasets, xpu=xpu,\n        loaders=loaders,\n    )\n    # harn.monitor = early_stop.EarlyStop(patience=40)\n    harn.monitor = monitor.Monitor(min_keys=['loss'],\n                                   max_keys=['global_acc', 'class_acc'],\n                                   patience=40)\n\n    # ignore_label = datasets['train'].ignore_label\n    # from netharn import metrics\n\n    workdir = ub.ensuredir('train_cifar_work')\n    harn.setup_dpath(workdir)\n\n\n    harn.run()\n\n \"\"\"\n        python examples/cifar.py train --lab\n        python examples/cifar.py train --rgb-indie\n \"\"\"\n", "meta": {"hexsha": "7d45355c09ae6c13e65639082b5b19cde94652df", "size": 31459, "ext": "py", "lang": "Python", "max_stars_repo_path": "netharn/examples/tests/expt_cifar.py", "max_stars_repo_name": "JoshuaBeard/netharn", "max_stars_repo_head_hexsha": "90773542c47363e663ee58f20fd151eb89bc313b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "netharn/examples/tests/expt_cifar.py", "max_issues_repo_name": "JoshuaBeard/netharn", "max_issues_repo_head_hexsha": "90773542c47363e663ee58f20fd151eb89bc313b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "netharn/examples/tests/expt_cifar.py", "max_forks_repo_name": "JoshuaBeard/netharn", "max_forks_repo_head_hexsha": "90773542c47363e663ee58f20fd151eb89bc313b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4108796296, "max_line_length": 129, "alphanum_fraction": 0.5844432436, "include": true, "reason": "import numpy", "num_tokens": 8254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.34158250614097546, "lm_q1q2_score": 0.17879123455485343}}
{"text": "from . import gwem_resampling_utils as sampler_functions\nimport pandas as pd\nimport numpy as np\nimport bilby\nimport argparse\nimport os\n\n\ndef main():\n\n    parser = argparse.ArgumentParser(\n        description=\"Inference on binary source parameters with kilonova ejecta posterior and GW source posterior given.\"\n    )\n    parser.add_argument(\"--outdir\", metavar=\"PATH\", type=str, required=True)\n    parser.add_argument(\n            \"--GWsamples\", \n            metavar=\"PATH\", \n            type=str, \n            required=True,\n            help=\"If no posterior files are available, use gwsamples_creation.py to generate dummy GWsamples.\"\n    )\n    parser.add_argument(\n            \"--EMsamples\", \n            metavar=\"PATH\", \n            type=str, \n            required=True,\n            help=\"posterior samples file from a previous Bayesian inference run on EM signals (e.g. Kilonova inference or Kilonova+GRB inference.\")\n    parser.add_argument(\n            \"--EOSpath\", \n            metavar=\"PATH\", \n            type=str, \n            required=True,\n            help=\"Path of EOS folder, e.g. 15nsat_cse_uniform_R14 (located: https://zenodo.org/record/6106130#.YoysIHVBwUG)\"\n    )\n    parser.add_argument(\n            \"--Neos\", \n            metavar=\"Neos\", \n            type=int, \n            required=True,\n            help=\"Number of EOS files used for the inference.\"\n    )\n    parser.add_argument(\n            \"--nlive\", \n            metavar=\"nlive\", \n            type=int, \n            required=False, \n            default=1024\n    )\n    parser.add_argument(\n        \"--GWprior\",\n        metavar=\"PATH\",\n        type=str,\n        required=True,\n        help=\"Prior file used for the GW analysis\",\n    )\n    parser.add_argument(\n        \"--EMprior\",\n        metavar=\"PATH\",\n        type=str,\n        required=True,\n        help=\"Prior file used for the EM eos analysis\",\n    )\n    parser.add_argument(\n        \"--total-ejecta-mass\",\n        action=\"store_true\",\n        help=\"To run with total ejecta mass, if not activated, the two ejecta are consider seperately\",\n    )\n    args = parser.parse_args()\n\n    # read the GW samples\n    GWsamples = pd.read_csv(args.GWsamples, header=0, delimiter=\" \")\n    # down sample\n    weights = np.ones(len(GWsamples))\n    weights /= np.sum(weights)\n    GWsamples = GWsamples.sample(\n        frac=30000 / len(GWsamples), weights=weights, random_state=42\n    )\n\n    # read the EM samples\n    EMsamples = pd.read_csv(args.EMsamples, header=0, delimiter=\" \")\n\n    # read the prior files\n    GWprior = bilby.gw.prior.PriorDict(args.GWprior)\n    EMprior = bilby.gw.prior.PriorDict(args.EMprior)\n\n    try:\n        os.makedirs(args.outdir + \"/pm/\")\n    except Exception:\n        pass\n    pymulti_kwargs = dict(\n        outputfiles_basename=args.outdir + \"/pm/\",\n        n_dims=5,\n        n_live_points=args.nlive,\n        verbose=True,\n        resume=True,\n        seed=42,\n        importance_nested_sampling=False,\n    )\n\n    if args.total_ejecta_mass:\n        solution = sampler_functions.TotalEjectaMassInference(\n            GWsamples,\n            EMsamples,\n            GWprior,\n            EMprior,\n            args.Neos,\n            args.EOSpath,\n            **pymulti_kwargs\n        )\n    else:\n        solution = sampler_functions.EjectaMassInference(\n            GWsamples,\n            EMsamples,\n            GWprior,\n            EMprior,\n            args.Neos,\n            args.EOSpath,\n            **pymulti_kwargs\n        )\n\n    samples = solution.samples.T\n    posterior_samples = dict()\n    posterior_samples[\"chirp_mass\"] = samples[0]\n    posterior_samples[\"mass_ratio\"] = samples[1]\n    posterior_samples[\"EOS\"] = samples[2]\n    posterior_samples[\"alpha\"] = samples[3]\n    posterior_samples[\"zeta\"] = samples[4]\n\n    posterior_samples = pd.DataFrame.from_dict(posterior_samples)\n    posterior_samples.to_csv(\n        \"{0}/posterior_samples.dat\".format(args.outdir), sep=\" \", index=False\n    )\n\n    sampler_functions.corner_plot(posterior_samples, solution, args.outdir)\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "1f7f4a70fef0b44151317a2ae53b8d9461634350", "size": 4062, "ext": "py", "lang": "Python", "max_stars_repo_path": "nmma/em/gwem_resampling.py", "max_stars_repo_name": "nuclear-multimessenger-astronomy/nmma", "max_stars_repo_head_hexsha": "bde7b312c6bdf3b032ebb4d4a1e8a77e9a24a123", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-12T18:06:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T18:06:50.000Z", "max_issues_repo_path": "nmma/em/gwem_resampling.py", "max_issues_repo_name": "nuclear-multimessenger-astronomy/nmma", "max_issues_repo_head_hexsha": "bde7b312c6bdf3b032ebb4d4a1e8a77e9a24a123", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2022-02-08T18:18:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T13:11:03.000Z", "max_forks_repo_path": "nmma/em/gwem_resampling.py", "max_forks_repo_name": "nuclear-multimessenger-astronomy/nmma", "max_forks_repo_head_hexsha": "bde7b312c6bdf3b032ebb4d4a1e8a77e9a24a123", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2022-02-07T21:15:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:26:06.000Z", "avg_line_length": 29.2230215827, "max_line_length": 147, "alphanum_fraction": 0.5957656327, "include": true, "reason": "import numpy", "num_tokens": 935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.34158250614097546, "lm_q1q2_score": 0.17879123455485343}}
{"text": "# encoding=utf8\nimport abc\nimport copy\nfrom typing import List, Any, Tuple\n\nimport numpy as np\nfrom scipy.stats import norm\n\nfrom smac.configspace import Configuration\nfrom smac.configspace.util import convert_configurations_to_array\nfrom smac.epm.base_epm import AbstractEPM\nfrom smac.utils.logging import PickableLoggerAdapter\n\n__author__ = \"Aaron Klein, Marius Lindauer\"\n__copyright__ = \"Copyright 2017, ML4AAD\"\n__license__ = \"3-clause BSD\"\n\n\nclass AbstractAcquisitionFunction(object, metaclass=abc.ABCMeta):\n    \"\"\"Abstract base class for acquisition function\n\n    Attributes\n    ----------\n    model\n    logger\n    \"\"\"\n\n    def __init__(self, model: AbstractEPM):\n        \"\"\"Constructor\n\n        Parameters\n        ----------\n        model : AbstractEPM\n            Models the objective function.\n        \"\"\"\n        self.model = model\n        self._required_updates = ('model', )  # type: Tuple[str, ...]\n        self.logger = PickableLoggerAdapter(self.__module__ + \".\" + self.__class__.__name__)\n\n    def update(self, **kwargs: Any) -> None:\n        \"\"\"Update the acquisition function attributes required for calculation.\n\n        This method will be called after fitting the model, but before maximizing the acquisition\n        function. As an examples, EI uses it to update the current fmin.\n\n        The default implementation only updates the attributes of the acqusition function which\n        are already present.\n\n        Parameters\n        ----------\n        kwargs\n        \"\"\"\n        for key in self._required_updates:\n            if key not in kwargs:\n                raise ValueError(\n                    'Acquisition function %s needs to be updated with key %s, but only got '\n                    'keys %s.'\n                    % (self.__class__.__name__, key, list(kwargs.keys()))\n                )\n        for key in kwargs:\n            if key in self._required_updates:\n                setattr(self, key, kwargs[key])\n\n    def __call__(self, configurations: List[Configuration]) -> np.ndarray:\n        \"\"\"Computes the acquisition value for a given X\n\n        Parameters\n        ----------\n        configurations : list\n            The configurations where the acquisition function\n            should be evaluated.\n\n        Returns\n        -------\n        np.ndarray(N, 1)\n            acquisition values for X\n        \"\"\"\n        X = convert_configurations_to_array(configurations)\n        if len(X.shape) == 1:\n            X = X[np.newaxis, :]\n\n        acq = self._compute(X)\n        if np.any(np.isnan(acq)):\n            idx = np.where(np.isnan(acq))[0]\n            acq[idx, :] = -np.finfo(np.float).max\n        return acq\n\n    @abc.abstractmethod\n    def _compute(self, X: np.ndarray) -> np.ndarray:\n        \"\"\"Computes the acquisition value for a given point X. This function has\n        to be overwritten in a derived class.\n\n        Parameters\n        ----------\n        X : np.ndarray\n            The input points where the acquisition function\n            should be evaluated. The dimensionality of X is (N, D), with N as\n            the number of points to evaluate at and D is the number of\n            dimensions of one X.\n\n        Returns\n        -------\n        np.ndarray(N,1)\n            Acquisition function values wrt X\n        \"\"\"\n        raise NotImplementedError()\n\n\nclass IntegratedAcquisitionFunction(AbstractAcquisitionFunction):\n\n    r\"\"\"Marginalize over Model hyperparameters to compute the integrated acquisition function.\n\n    See \"Practical Bayesian Optimization of Machine Learning Algorithms\" by Jasper Snoek et al.\n    (https://papers.nips.cc/paper/4522-practical-bayesian-optimization-of-machine-learning-algorithms.pdf)\n    for further details.\n    \"\"\"\n\n    def __init__(self, model: AbstractEPM, acquisition_function: AbstractAcquisitionFunction, **kwargs: Any):\n        \"\"\"Constructor\n\n        Parameters\n        ----------\n        model : AbstractEPM\n            The model needs to implement an additional attribute ``models`` which contains the different models to\n            integrate over.\n        kwargs\n            Additional keyword arguments\n        \"\"\"\n\n        super().__init__(model)\n        self.long_name = 'Integrated Acquisition Function (%s)' % acquisition_function.__class__.__name__\n        self.acq = acquisition_function\n        self._functions = []  # type: List[AbstractAcquisitionFunction]\n        self.eta = None\n\n    def update(self, **kwargs: Any) -> None:\n        \"\"\"Update the acquisition functions values.\n\n        This method will be called if the model is updated. E.g. entropy search uses it to update its approximation\n        of P(x=x_min), EI uses it to update the current fmin.\n\n        This implementation creates an acquisition function object for each model to integrate over and sets the\n        respective attributes for each acquisition function object.\n\n        Parameters\n        ----------\n        model : AbstractEPM\n            The model needs to implement an additional attribute ``models`` which contains the different models to\n            integrate over.\n        kwargs\n        \"\"\"\n        model = kwargs['model']\n        del kwargs['model']\n        if not hasattr(model, 'models') or len(model.models) == 0:\n            raise ValueError('IntegratedAcquisitionFunction requires at least one model to integrate!')\n        if len(self._functions) == 0 or len(self._functions) != len(model.models):\n            self._functions = [copy.deepcopy(self.acq) for _ in model.models]\n        for submodel, func in zip(model.models, self._functions):\n            func.update(model=submodel, **kwargs)\n\n    def _compute(self, X: np.ndarray) -> np.ndarray:\n        \"\"\"Computes the EI value and its derivatives.\n\n        Parameters\n        ----------\n        X: np.ndarray(N, D), The input points where the acquisition function\n            should be evaluated. The dimensionality of X is (N, D), with N as\n            the number of points to evaluate at and D is the number of\n            dimensions of one X.\n\n        Returns\n        -------\n        np.ndarray(N,1)\n            Expected Improvement of X\n        \"\"\"\n        if self._functions is None:\n            raise ValueError('Need to call update first!')\n        return np.array([func._compute(X) for func in self._functions]).mean(axis=0)\n\n\nclass EI(AbstractAcquisitionFunction):\n\n    r\"\"\"Computes for a given x the expected improvement as\n    acquisition value.\n\n    :math:`EI(X) := \\mathbb{E}\\left[ \\max\\{0, f(\\mathbf{X^+}) - f_{t+1}(\\mathbf{X}) - \\xi \\} \\right]`,\n    with :math:`f(X^+)` as the best location.\n    \"\"\"\n\n    def __init__(self,\n                 model: AbstractEPM,\n                 par: float = 0.0):\n        \"\"\"Constructor\n\n        Parameters\n        ----------\n        model : AbstractEPM\n            A model that implements at least\n                 - predict_marginalized_over_instances(X)\n        par : float, default=0.0\n            Controls the balance between exploration and exploitation of the\n            acquisition function.\n        \"\"\"\n\n        super(EI, self).__init__(model)\n        self.long_name = 'Expected Improvement'\n        self.par = par\n        self.eta = None\n        self._required_updates = ('model', 'eta')\n\n    def _compute(self, X: np.ndarray) -> np.ndarray:\n        \"\"\"Computes the EI value and its derivatives.\n\n        Parameters\n        ----------\n        X: np.ndarray(N, D), The input points where the acquisition function\n            should be evaluated. The dimensionality of X is (N, D), with N as\n            the number of points to evaluate at and D is the number of\n            dimensions of one X.\n\n        Returns\n        -------\n        np.ndarray(N,1)\n            Expected Improvement of X\n        \"\"\"\n        if len(X.shape) == 1:\n            X = X[:, np.newaxis]\n\n        m, v = self.model.predict_marginalized_over_instances(X)\n        s = np.sqrt(v)\n\n        if self.eta is None:\n            raise ValueError('No current best specified. Call update('\n                             'eta=<int>) to inform the acquisition function '\n                             'about the current best value.')\n\n        def calculate_f():\n            z = (self.eta - m - self.par) / s\n            return (self.eta - m - self.par) * norm.cdf(z) + s * norm.pdf(z)\n\n        if np.any(s == 0.0):\n            # if std is zero, we have observed x on all instances\n            # using a RF, std should be never exactly 0.0\n            # Avoid zero division by setting all zeros in s to one.\n            # Consider the corresponding results in f to be zero.\n            self.logger.warning(\"Predicted std is 0.0 for at least one sample.\")\n            s_copy = np.copy(s)\n            s[s_copy == 0.0] = 1.0\n            f = calculate_f()\n            f[s_copy == 0.0] = 0.0\n        else:\n            f = calculate_f()\n        if (f < 0).any():\n            raise ValueError(\n                \"Expected Improvement is smaller than 0 for at least one \"\n                \"sample.\")\n\n        return f\n\n\nclass EIPS(EI):\n    def __init__(self,\n                 model: AbstractEPM,\n                 par: float = 0.0):\n        r\"\"\"Computes for a given x the expected improvement as\n        acquisition value.\n        :math:`EI(X) := \\frac{\\mathbb{E}\\left[\\max\\{0,f(\\mathbf{X^+})-f_{t+1}(\\mathbf{X})-\\xi\\right]\\}]}{np.log(r(x))}`,\n        with :math:`f(X^+)` as the best location and :math:`r(x)` as runtime.\n\n        Parameters\n        ----------\n        model : AbstractEPM\n            A model that implements at least\n                 - predict_marginalized_over_instances(X) returning a tuples of\n                   predicted cost and running time\n        par : float, default=0.0\n            Controls the balance between exploration and exploitation of the\n            acquisition function.\n        \"\"\"\n        super(EIPS, self).__init__(model, par=par)\n        self.long_name = 'Expected Improvement per Second'\n\n    def _compute(self, X: np.ndarray) -> np.ndarray:\n        \"\"\"Computes the EIPS value.\n\n        Parameters\n        ----------\n        X: np.ndarray(N, D), The input point where the acquisition function\n            should be evaluate. The dimensionality of X is (N, D), with N as\n            the number of points to evaluate at and D is the number of\n            dimensions of one X.\n\n        Returns\n        -------\n        np.ndarray(N,1)\n            Expected Improvement per Second of X\n        \"\"\"\n        if len(X.shape) == 1:\n            X = X[:, np.newaxis]\n\n        m, v = self.model.predict_marginalized_over_instances(X)\n        if m.shape[1] != 2:\n            raise ValueError(\"m has wrong shape: %s != (-1, 2)\" % str(m.shape))\n        if v.shape[1] != 2:\n            raise ValueError(\"v has wrong shape: %s != (-1, 2)\" % str(v.shape))\n\n        m_cost = m[:, 0]\n        v_cost = v[:, 0]\n        # The model already predicts log(runtime)\n        m_runtime = m[:, 1]\n        s = np.sqrt(v_cost)\n\n        if self.eta is None:\n            raise ValueError('No current best specified. Call update('\n                             'eta=<int>) to inform the acquisition function '\n                             'about the current best value.')\n\n        def calculate_f():\n            z = (self.eta - m_cost - self.par) / s\n            f = (self.eta - m_cost - self.par) * norm.cdf(z) + s * norm.pdf(z)\n            f = f / m_runtime\n            return f\n\n        if np.any(s == 0.0):\n            # if std is zero, we have observed x on all instances\n            # using a RF, std should be never exactly 0.0\n            # Avoid zero division by setting all zeros in s to one.\n            # Consider the corresponding results in f to be zero.\n            self.logger.warning(\"Predicted std is 0.0 for at least one sample.\")\n            s_copy = np.copy(s)\n            s[s_copy == 0.0] = 1.0\n            f = calculate_f()\n            f[s_copy == 0.0] = 0.0\n        else:\n            f = calculate_f()\n\n        if (f < 0).any():\n            raise ValueError(\n                \"Expected Improvement per Second is smaller than 0 \"\n                \"for at least one sample.\")\n\n        return f.reshape((-1, 1))\n\n\nclass LogEI(AbstractAcquisitionFunction):\n\n    def __init__(self,\n                 model: AbstractEPM,\n                 par: float = 0.0):\n        r\"\"\"Computes for a given x the logarithm expected improvement as\n        acquisition value.\n\n        Parameters\n        ----------\n        model : AbstractEPM\n            A model that implements at least\n                 - predict_marginalized_over_instances(X)\n        par : float, default=0.0\n            Controls the balance between exploration and exploitation of the\n            acquisition function.\n        \"\"\"\n        super(LogEI, self).__init__(model)\n        self.long_name = 'Expected Improvement'\n        self.par = par\n        self.eta = None\n        self._required_updates = ('model', 'eta')\n\n    def _compute(self, X: np.ndarray) -> np.ndarray:\n        \"\"\"Computes the EI value and its derivatives.\n\n        Parameters\n        ----------\n        X: np.ndarray(N, D), The input points where the acquisition function\n            should be evaluated. The dimensionality of X is (N, D), with N as\n            the number of points to evaluate at and D is the number of\n            dimensions of one X.\n\n        Returns\n        -------\n        np.ndarray(N,1)\n            Expected Improvement of X\n        \"\"\"\n        if self.eta is None:\n            raise ValueError('No current best specified. Call update('\n                             'eta=<int>) to inform the acquisition function '\n                             'about the current best value.')\n\n        if len(X.shape) == 1:\n            X = X[:, np.newaxis]\n\n        m, var_ = self.model.predict_marginalized_over_instances(X)\n        std = np.sqrt(var_)\n\n        def calculate_log_ei():\n            # we expect that f_min is in log-space\n            f_min = self.eta - self.par\n            v = (f_min - m) / std\n            return (np.exp(f_min) * norm.cdf(v)) - \\\n                (np.exp(0.5 * var_ + m) * norm.cdf(v - std))\n\n        if np.any(std == 0.0):\n            # if std is zero, we have observed x on all instances\n            # using a RF, std should be never exactly 0.0\n            # Avoid zero division by setting all zeros in s to one.\n            # Consider the corresponding results in f to be zero.\n            self.logger.warning(\"Predicted std is 0.0 for at least one sample.\")\n            std_copy = np.copy(std)\n            std[std_copy == 0.0] = 1.0\n            log_ei = calculate_log_ei()\n            log_ei[std_copy == 0.0] = 0.0\n        else:\n            log_ei = calculate_log_ei()\n\n        if (log_ei < 0).any():\n            raise ValueError(\n                \"Expected Improvement is smaller than 0 for at least one sample.\")\n\n        return log_ei.reshape((-1, 1))\n\n\nclass PI(AbstractAcquisitionFunction):\n    def __init__(self,\n                 model: AbstractEPM,\n                 par: float = 0.0):\n        r\"\"\"Computes the probability of improvement for a given x over the best so far value as acquisition value.\n\n        :math:`P(f_{t+1}(\\mathbf{X})\\geq f(\\mathbf{X^+}))` :math:`:= \\Phi(\\\\frac{ \\mu(\\mathbf{X})-f(\\mathbf{X^+}) }\n        { \\sigma(\\mathbf{X}) })` with :math:`f(X^+)` as the incumbent and :math:`\\Phi` the cdf of the standard normal\n\n        Parameters\n        ----------\n        model : AbstractEPM\n            A model that implements at least\n                 - predict_marginalized_over_instances(X)\n        par : float, default=0.0\n            Controls the balance between exploration and exploitation of the\n            acquisition function.\n        \"\"\"\n        super(PI, self).__init__(model)\n        self.long_name = 'Probability of Improvement'\n        self.par = par\n        self.eta = None\n        self._required_updates = ('model', 'eta')\n\n    def _compute(self, X: np.ndarray) -> np.ndarray:\n        \"\"\"Computes the PI value.\n\n        Parameters\n        ----------\n        X: np.ndarray(N, D)\n           Points to evaluate PI. N is the number of points and D the dimension for the points\n\n        Returns\n        -------\n        np.ndarray(N,1)\n            Expected Improvement of X\n        \"\"\"\n        if self.eta is None:\n            raise ValueError('No current best specified. Call update('\n                             'eta=<float>) to inform the acquisition function '\n                             'about the current best value.')\n\n        if len(X.shape) == 1:\n            X = X[:, np.newaxis]\n        m, var_ = self.model.predict_marginalized_over_instances(X)\n        std = np.sqrt(var_)\n        return norm.cdf((self.eta - m - self.par) / std)\n\n\nclass LCB(AbstractAcquisitionFunction):\n    def __init__(self,\n                 model: AbstractEPM,\n                 par: float = 1.0):\n        r\"\"\"Computes the lower confidence bound for a given x over the best so far value as\n        acquisition value.\n\n        :math:`LCB(X) = \\mu(\\mathbf{X}) - \\sqrt(\\beta_t)\\sigma(\\mathbf{X})`\n\n        Returns -LCB(X) as the acquisition_function optimizer maximizes the acquisition value.\n\n        Parameters\n        ----------\n        model : AbstractEPM\n            A model that implements at least\n                 - predict_marginalized_over_instances(X)\n        par : float, default=1.0\n            Controls the balance between exploration and exploitation of the\n            acquisition function.\n        \"\"\"\n        super(LCB, self).__init__(model)\n        self.long_name = 'Lower Confidence Bound'\n        self.par = par\n        self.num_data = None\n        self._required_updates = ('model', 'num_data')\n\n    def _compute(self, X: np.ndarray) -> np.ndarray:\n        \"\"\"Computes the LCB value.\n\n        Parameters\n        ----------\n        X: np.ndarray(N, D)\n           Points to evaluate LCB. N is the number of points and D the dimension for the points\n\n        Returns\n        -------\n        np.ndarray(N,1)\n            Expected Improvement of X\n        \"\"\"\n        if self.num_data is None:\n            raise ValueError('No current number of Datapoints specified. Call update('\n                             'num_data=<int>) to inform the acquisition function '\n                             'about the number of datapoints.')\n        if len(X.shape) == 1:\n            X = X[:, np.newaxis]\n        m, var_ = self.model.predict_marginalized_over_instances(X)\n        std = np.sqrt(var_)\n        beta = 2 * np.log((X.shape[1] * self.num_data**2) / self.par)\n        return -(m - np.sqrt(beta) * std)\n\n\nclass TS(AbstractAcquisitionFunction):\n    def __init__(self,\n                 model: AbstractEPM,\n                 par: float = 0.0):\n        r\"\"\"Do a Thompson Sampling for a given x over the best so far value as\n        acquisition value.\n\n        Thompson Sampling can only be used together with smac.optimizer.ei_optimization.RandomSearch, please do not\n        use smac.optimizer.ei_optimization.LocalAndSortedRandomSearch to optimize TS acquisition function!!!\n\n        :math:`TS(X) ~ \\mathcal{N}(\\mu(\\mathbf{X}),\\sigma(\\mathbf{X}))'\n        Returns -TS(X) as the acquisition_function optimizer maximizes the acquisition value.\n        Parameters\n        ----------\n        model : AbstractEPM\n            A model that implements at least\n                 - predict_marginalized_over_instances(X)\n        par : float, default=0.0\n            TS does not require par here, we only wants to make it consistent with other acquisition functions\n        \"\"\"\n        super(TS, self).__init__(model)\n        self.long_name = 'Thompson Sampling'\n        self.par = par\n        self.num_data = None\n        self._required_updates = ('model', )\n\n    def _compute(self, X: np.ndarray) -> np.ndarray:\n        \"\"\"Sample a new value from a gaussian distribution whose mean and covariance values are given by model\n        Parameters\n        ----------\n        X: np.ndarray(N, D)\n           Points to be evaluated where we could sample a value. N is the number of points and D the dimension\n           for the points\n        Returns\n        -------\n        np.ndarray(N,1)\n            negative sample value of X\n        \"\"\"\n        if len(X.shape) == 1:\n            X = X[:, np.newaxis]\n        sample_function = getattr(self.model, \"sample_functions\", None)\n        if callable(sample_function):\n            return - sample_function(X, n_funcs=1)\n\n        m, var_ = self.model.predict_marginalized_over_instances(X)\n        rng = getattr(self.model, 'rng', np.random.RandomState(self.model.seed))\n        m = m.flatten()\n        var_ = np.diag(var_.flatten())\n        return - rng.multivariate_normal(m, var_, 1).T\n", "meta": {"hexsha": "9c63e4a87bdf114788a856eba83e05165257929e", "size": 20593, "ext": "py", "lang": "Python", "max_stars_repo_path": "smac/optimizer/acquisition.py", "max_stars_repo_name": "TheVinhLuong102/AutoML-SMAC3", "max_stars_repo_head_hexsha": "d4cb7ed76e0fbdd9edf6ab5360ff75de67ac2195", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 711, "max_stars_repo_stars_event_min_datetime": "2016-08-22T14:23:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T21:56:12.000Z", "max_issues_repo_path": "smac/optimizer/acquisition.py", "max_issues_repo_name": "TheVinhLuong102/AutoML-SMAC3", "max_issues_repo_head_hexsha": "d4cb7ed76e0fbdd9edf6ab5360ff75de67ac2195", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 770, "max_issues_repo_issues_event_min_datetime": "2016-08-17T14:39:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:35:58.000Z", "max_forks_repo_path": "smac/optimizer/acquisition.py", "max_forks_repo_name": "TheVinhLuong102/AutoML-SMAC3", "max_forks_repo_head_hexsha": "d4cb7ed76e0fbdd9edf6ab5360ff75de67ac2195", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 210, "max_forks_repo_forks_event_min_datetime": "2016-08-20T15:14:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T08:04:34.000Z", "avg_line_length": 36.1280701754, "max_line_length": 120, "alphanum_fraction": 0.5717962414, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.1787912310465456}}
{"text": "import logging\nimport os\n\nimport astropy.constants\nimport numpy as np\nfrom astropy.coordinates import EarthLocation, SkyCoord\nfrom astropy.io import fits\nfrom astropy.io.ascii.cparser import CParserError  # pylint: disable=E0611\nfrom astropy.table import Table, vstack\nfrom astropy.time import Time\nfrom easyquery import Query\n\nfrom ..database import CsvTable, FitsTable\nfrom .common import SPEED_OF_LIGHT, ensure_specs_dtype\n\n__all__ = [\n    \"read_generic_spectra\",\n    \"read_mmt\",\n    \"read_mmt_bino\",\n    \"read_aat\",\n    \"read_aat_mz\",\n    \"read_imacs\",\n    \"read_wiyn\",\n    \"read_palomar\",\n]\n\n# pylint: disable=logging-format-interpolation\n\n\ndef get_obs_info_from_fits(\n    fits_filepath,\n    ra_name=\"RA\",\n    dec_name=\"DEC\",\n    time_name=\"MJD\",\n    ra_unit=\"hourangle\",\n    dec_unit=\"deg\",\n    time_format=\"mjd\",\n):\n    hdr = fits.getheader(fits_filepath)\n    sc = SkyCoord(hdr[ra_name], hdr[dec_name], unit=(ra_unit, dec_unit))\n    obstime = Time(hdr[time_name], format=time_format)\n    return sc, obstime\n\n\ndef heliocentric_correction(sc, obstime, site_name):\n    helio_corr = sc.radial_velocity_correction(\n        \"heliocentric\", obstime=obstime, location=EarthLocation.of_site(site_name)\n    )\n    return helio_corr.to_value(astropy.constants.c)  # pylint: disable=no-member\n\n\ndef read_generic_spectra(\n    dir_path,\n    extension,\n    telname,\n    usecols,\n    n_cols_total,\n    cuts=None,\n    postprocess=None,\n    fits_hdr_kwargs=None,\n    helio_corr_site=None,\n    before_time=None,\n    table_read_kwargs=None,\n    exclude_spec_masks=None,\n    **kwargs,\n):\n\n    names = [usecols.get(i + 1, \"_{}\".format(i)) for i in range(n_cols_total)]\n    exclude_names = [n for n in names if n.startswith(\"_\")]\n\n    output = []\n\n    for filename in os.listdir(dir_path):\n        filepath = os.path.join(dir_path, filename)\n        rootname, extension_this = os.path.splitext(filename)\n\n        if extension_this != extension:\n            continue\n\n        if \"conflicted copy\" in filename:\n            logging.warning(\n                \"SKIPPING spectra file {} - it's a conflicted copy; check what went wrong!\".format(filepath)\n            )\n            continue\n\n        if exclude_spec_masks and (rootname in exclude_spec_masks or filename in exclude_spec_masks):\n            continue\n\n        helio_corr = None\n        for fits_name in (\n            rootname + \".fits.gz\",\n            rootname + \".fits\",\n            rootname.rpartition(\"_\")[0] + \".fits.gz\",\n            rootname.rpartition(\"_\")[0] + \".fits\",\n        ):\n            fits_path = os.path.join(dir_path, fits_name)\n            if os.path.isfile(fits_path):\n                break\n        try:\n            sc, obstime = get_obs_info_from_fits(fits_path, **(fits_hdr_kwargs or {}))\n        except (IOError, OSError):\n            if fits_hdr_kwargs or helio_corr_site or before_time is not None:\n                logging.warning(\"Cannot find or read corresponding fits file for {}\".format(filepath))\n        else:\n            if before_time is not None and obstime > before_time:\n                continue\n            if helio_corr_site:\n                helio_corr = heliocentric_correction(sc, obstime, helio_corr_site)\n\n        try:\n            table_read_kwargs_this = dict(\n                format=\"ascii.fast_no_header\",\n                guess=False,\n                names=names,\n                exclude_names=exclude_names,\n            )\n            if table_read_kwargs:\n                table_read_kwargs_this.update(table_read_kwargs)\n            this = Table.read(filepath, **table_read_kwargs_this)\n        except (IOError, CParserError) as e:\n            logging.warning(\"SKIPPING spectra file {} - could not read or parse\\n{}\".format(filepath, e))\n            continue\n\n        this = ensure_specs_dtype(this, skip_missing_cols=True)\n        this = Query(cuts).filter(this)\n        if not len(this):\n            continue\n\n        if \"MASKNAME\" not in this.colnames:\n            this[\"MASKNAME\"] = filename\n\n        if helio_corr is None:\n            this[\"HELIO_CORR\"] = False\n        else:\n            this[\"SPEC_Z\"] += float(helio_corr)\n            this[\"HELIO_CORR\"] = True\n\n        output.append(this)\n\n    if not output:\n        return\n\n    output = vstack(output, \"exact\")\n    output[\"TELNAME\"] = telname\n    if postprocess:\n        output = postprocess(output)\n\n    return ensure_specs_dtype(output)\n\n\ndef read_mmt(dir_path, before_time=None, exclude_spec_masks=None):\n    extension = \".zlog\"\n    telname = \"MMT\"\n    helio_corr_site = \"mmt\"\n\n    n_cols_total = 11\n    usecols = {\n        2: \"RA\",\n        3: \"DEC\",\n        4: \"mag\",\n        5: \"SPEC_Z\",\n        6: \"SPEC_Z_ERR\",\n        7: \"ZQUALITY\",\n        8: \"SPECOBJID\",\n    }\n\n    cuts = Query(\"mag != 0\", \"ZQUALITY >= 0\", (lambda x: x != \"0\", \"SPECOBJID\"))\n\n    def postprocess(t):\n        del t[\"mag\"]\n        t[\"RA\"] *= 15.0\n        return t\n\n    return read_generic_spectra(**locals())\n\n\ndef read_mmt_bino(dir_path, exclude_spec_masks=None):\n    extension = \".dat\"\n    telname = \"BINO\"\n\n    n_cols_total = 8\n    usecols = {\n        1: \"masknum\",\n        2: \"SPECOBJID\",\n        3: \"RA\",\n        4: \"DEC\",\n        6: \"SPEC_Z\",\n        7: \"ZQUALITY\",\n    }\n\n    table_read_kwargs = dict(\n        format=\"ascii.fixed_width_no_header\",\n        col_starts=(0, 5, 11, 25, 38, 58, 66, 71),\n    )\n\n    def postprocess(t):\n        t[\"SPEC_Z_ERR\"] = 10 / SPEED_OF_LIGHT\n        t[\"MASKNAME\"] = np.char.add(np.char.add(t[\"MASKNAME\"], \"-\"), t[\"masknum\"].astype(\"<U\"))\n        del t[\"masknum\"]\n        return t\n\n    return read_generic_spectra(**locals())\n\n\ndef read_aat(dir_path, before_time=None, exclude_spec_masks=None):\n    extension = \".zlog\"\n    telname = \"AAT\"\n    helio_corr_site = \"sso\"\n\n    n_cols_total = 11\n    usecols = {2: \"RA\", 3: \"DEC\", 5: \"SPEC_Z\", 7: \"ZQUALITY\", 8: \"SPECOBJID\"}\n    cuts = Query(\"ZQUALITY >= 0\", (lambda x: x != \"0\", \"SPECOBJID\"))\n\n    fits_hdr_kwargs = dict(ra_name=\"MEANRA\", dec_name=\"MEANDEC\", time_name=\"UTMJD\")\n\n    def postprocess(t):\n        t[\"SPEC_Z_ERR\"] = 10 / SPEED_OF_LIGHT\n        return t\n\n    return read_generic_spectra(**locals())\n\n\ndef read_aat_mz(dir_path, before_time=None, exclude_spec_masks=None):\n    extension = \".mz\"\n    telname = \"AAT\"\n    helio_corr_site = \"sso\"\n\n    n_cols_total = 15\n    usecols = {3: \"RA\", 4: \"DEC\", 13: \"SPEC_Z\", 14: \"ZQUALITY\", 1: \"SPECOBJID\"}\n    cuts = Query(\"ZQUALITY >= 0\")\n\n    fits_hdr_kwargs = dict(ra_name=\"MEANRA\", dec_name=\"MEANDEC\", time_name=\"UTMJD\")\n    table_read_kwargs = dict(delimiter=\",\")\n\n    def postprocess(t):\n        t[\"RA\"] *= 180.0 / np.pi\n        t[\"DEC\"] *= 180.0 / np.pi\n        t[\"SPEC_Z_ERR\"] = 10 / SPEED_OF_LIGHT\n        return t\n\n    return read_generic_spectra(**locals())\n\n\ndef read_imacs(dir_path):\n    extension = \".zlog\"\n    telname = \"IMACS\"\n\n    n_cols_total = 12\n    usecols = {\n        2: \"RA\",\n        3: \"DEC\",\n        5: \"SPEC_Z\",\n        6: \"SPEC_Z_ERR\",\n        7: \"ZQUALITY\",\n        8: \"SPECOBJID\",\n        11: \"MASKNAME\",\n    }\n\n    cuts = Query(\"ZQUALITY >= 1\", (lambda x: x != \"0\", \"SPECOBJID\"))\n\n    return read_generic_spectra(**locals())\n\n\ndef read_wiyn(dir_path):\n\n    output = []\n\n    for f in os.listdir(dir_path):\n        if not f.endswith(\".fits.gz\"):\n            continue\n        this = FitsTable(os.path.join(dir_path, f)).read()[[\"RA\", \"DEC\", \"ZQUALITY\", \"FID\", \"Z\", \"Z_ERR\"]]\n        this = Query(\"ZQUALITY >= 1\").filter(this)\n        this[\"MASKNAME\"] = f\n        output.append(this)\n\n    output = vstack(output, \"exact\")\n\n    output.rename_column(\"FID\", \"SPECOBJID\")\n    output.rename_column(\"Z\", \"SPEC_Z\")\n    output.rename_column(\"Z_ERR\", \"SPEC_Z_ERR\")\n    output[\"TELNAME\"] = \"WIYN\"\n\n    sc = SkyCoord(output[\"RA\"], output[\"DEC\"], unit=(\"hourangle\", \"deg\"))\n    output[\"RA\"] = sc.ra.deg\n    output[\"DEC\"] = sc.dec.deg\n    del sc\n\n    return ensure_specs_dtype(output)\n\n\ndef read_palomar(file_path):\n    if not hasattr(file_path, \"read\"):\n        file_path = CsvTable(file_path)\n\n    cols = [\n        \"SPECOBJID\",\n        \"RA\",\n        \"DEC\",\n        \"SPEC_Z\",\n        \"SPEC_Z_ERR\",\n        \"ZQUALITY\",\n        \"MASKNAME\",\n        \"TELNAME\",\n        \"HELIO_CORR\",\n    ]\n    specs = file_path.read()[cols]\n\n    return ensure_specs_dtype(specs)\n", "meta": {"hexsha": "07a892ba093c3be9f4dd2093fde2bcda68639004", "size": 8223, "ext": "py", "lang": "Python", "max_stars_repo_path": "SAGA/spectra/read_observed.py", "max_stars_repo_name": "sagasurvey/saga", "max_stars_repo_head_hexsha": "341eb9984ff12668aa498f81d99d13fc1a4691c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-08-25T22:25:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T18:58:51.000Z", "max_issues_repo_path": "SAGA/spectra/read_observed.py", "max_issues_repo_name": "sagasurvey/saga", "max_issues_repo_head_hexsha": "341eb9984ff12668aa498f81d99d13fc1a4691c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2017-08-27T04:51:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T15:28:50.000Z", "max_forks_repo_path": "SAGA/spectra/read_observed.py", "max_forks_repo_name": "sagasurvey/saga", "max_forks_repo_head_hexsha": "341eb9984ff12668aa498f81d99d13fc1a4691c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-08-26T22:42:55.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-17T13:28:07.000Z", "avg_line_length": 26.6116504854, "max_line_length": 108, "alphanum_fraction": 0.5940654262, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 2241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.1787912310465456}}
{"text": "'''\nOriginal version: Lutz Raestatter Oct 1(?), 2021\nModify to work with flythrough: Oct 5, 2021 (Rebecca Ringuette)\n'''\nfrom datetime import datetime,timedelta,timezone\n\n#standard model dictionary for reference\nmodel_varnames={\n    ### 3D variables - to be aggregated into 4D ###\n    'bx':['B_x','x component of magnetic field',0,'GSE','car',['time','x','y','z'],'nT'],\n    'by':['B_y','y component of magnetic field',1,'GSE','car',['time','x','y','z'],'nT'],\n    'bz':['B_z','z component of magnetic field',2,'GSE','car',['time','x','y','z'],'nT'],\n    'bx1':['B1_x','x component of magnetic field (on grid cell faces)',3,'GSE','car',['time','x','x','x'],'nT'],\n    'by1':['B1_y','y component of magnetic field (on grid cell faces)',4,'GSE','car',['time','y','y','y'],'nT'],\n    'bz1':['B1_z','z component of magnetic field (on grid cell faces)',5,'GSE','car',['time','z','z','z'],'nT'],\n    'ex':['E_x','x component of electric field (on grid cell edges)',6,'GSE','car',['time','x','x','x'],'mV/m'],\n    'ey':['E_y','y component of electric field (on grid cell edges)',7,'GSE','car',['time','y','y','y'],'mV/m'],\n    'ez':['E_z','z component of electric field (on grid cell edges)',8,'GSE','car',['time','z','z','z'],'mV/m'],\n    'vx':['V_x','x component of plasma velocity',9,'GSE','car',['time','x','y','z'],'km/s'],\n    'vy':['V_y','y component of plasma velocity',10,'GSE','car',['time','x','y','z'],'km/s'],\n    'vz':['V_z','z component of plasma velocity',11,'GSE','car',['time','x','y','z'],'km/s'],\n    'rr':['N_plasma','plasma number denstity (hydrogen equivalent)',12,'GSE','car',['time','x','y','z'],'1/cm**3'],\n    'resis':['eta','resistivity',13,'GSE','car',['time','x','y','z'],'m**2/s'],\n    'pp':['P_plasma','plasma pressure',14,'GSE','car',['time','x','y','z'],'pPa'],\n    'xjx':['J_x','x component of current density',15,'GSE','car',['time','x','y','z'],'muA/m**2'],\n    'xjy':['J_y','y component of current density',16,'GSE','car',['time','x','y','z'],'muA/m**2'],\n    'xjz':['J_z','z component of current density',17,'GSE','car',['time','x','y','z'],'muA/m**2'],\n    #add current density components here\n}\n\n# variable linkage to grid position vectors are established during variable registration\n# these are gx_bx, gy_bx, ... gz_ez affecting magnetic field (b1x,b1y,b1z) and electric field (ex,ey,ez)\n\n#convert an array of timestamps to an array of hrs since midnight\ndef ts_to_hrs(time_val, filedate):\n    '''Convert utc timestamp to hours since midnight on filedate.'''\n    \n    return (datetime.utcfromtimestamp(time_val).replace(tzinfo=timezone.utc)-filedate).total_seconds()/3600.\n\ndef hrs_to_ts(hrs, filedate):\n    '''Add hours to filedate and return utc timestamp.'''\n    \n    return datetime.timestamp(filedate+timedelta(hours=float(hrs)))\n\n#sample file name: 'D:/OpenGGCM_GM/Data/Yihua_1/Yihua_Zheng_090721_1.3df_2015-10-16_12.nc'\n#main function/class definition\ndef MODEL():\n    from numpy import array, NaN, diff, sqrt, sum, expand_dims, zeros, where\n    from time import perf_counter\n    import xarray, dask\n    from os.path import isfile\n    from kamodo import Kamodo, kamodofy\n    from kamodo_ccmc.readers.reader_utilities import register_interpolator, define_4d_gridded_interpolator\n    \n    class MODEL(Kamodo):\n        '''OpenGGCM_GM magnetosphere reader'''\n        def __init__(self,full_file_prefix, variables_requested=[], runname = \"noname\",\n                     filetime=False, verbose=False, gridded_int=True, printfiles=False, \n                     fulltime=True, missing_value=NaN, **kwargs):\n            super(MODEL, self).__init__()\n            t0=perf_counter() # profiling time stamp\n            \n            #convert files to netcdf4 if needed\n            nc_file = full_file_prefix+'.nc'  # input file name: file_dir/YYYY-MM-DD_HH.nc\n            if isfile(nc_file):  #file already prepared!\n                self.conversion_test = True  #default value\n            else:  #file not prepared, prepare it\n                try:  #I don't have the file converter, so leave in try/except for now\n                    from kamodo_ccmc.readers.openggcm_to_cdf import openggcm_combine_magnetosphere_files as gmconv\n                    self.conversion_test = gmconv(full_file_prefix)\n                    #should return a boolean (True is successful, False if not)\n                except:\n                    self.conversion_test = False\n\n            #data are time-wrapped in files. This logic prevents the flythrough from breaking from this decision.\n            #cdf_data.added_time_at_beginning and cdf_data.added_time_at_end = 0 if not, 1 if yes\n            cdf_data = xarray.open_dataset(nc_file, chunks={'time':100,'x':100,'y':100,'z':100})\n            if not fulltime and cdf_data.added_time_at_end:  #use unwrapped time values\n                t = cdf_data.variables['_time'].values[:-1]  #skip added time at end\n            else: #need wrapped time array for interpolation\n                t = cdf_data.variables['_time'].values\n            self._time = t\n\n            #establish time attributes first\n            self.filedate = datetime.strptime(cdf_data.filedate+' 00:00:00', \n                                              '%Y-%m-%d %H:%M:%S').replace(tzinfo=timezone.utc)\n            if len(t)>1: self.dt = diff(t).max()*3600.  #t is in hours since midnight\n            else: self.dt = 0\n            self.datetimes=[datetime.utcfromtimestamp(hrs_to_ts(t[0], self.filedate)).isoformat(sep=' '),\n                            datetime.utcfromtimestamp(hrs_to_ts(t[-1], self.filedate)).isoformat(sep=' ')]\n            self.filetimes=[hrs_to_ts(t[0], self.filedate), hrs_to_ts(t[-1], self.filedate)]   #timestamps for matching in wrapper\n\n            #return time information only for flythrough\n            if filetime: \n                return  \n            \n            #if variables are given as integers, convert to standard names\n            if len(variables_requested)>0:\n                if isinstance(variables_requested[0], int):\n                    print('Integers detected. Converting...', end=\"\")\n                    tmp_var = [value[0] for key, value in model_varnames.items()\\\n                                           if value[2] in variables_requested]\n                    variables_requested = tmp_var\n                    print('Converted:', variables_requested)\n\n            #perform initial check on variables_requested list\n            if len(variables_requested)>0 and fulltime:\n                test_list = [value[0] for key, value in model_varnames.items()]\n                err_list = [item for item in variables_requested if item not in test_list]\n                if len(err_list)>0: print('Variable name(s) not recognized:', err_list)\n                \n            #collect variable list            \n            if len(variables_requested)>0:\n                gvar_list = [key for key, value in model_varnames.items() \\\n                                 if value[0] in variables_requested and \\\n                                     key in cdf_data.variables.keys()]  # file variable names\n                \n                #check for variables requested but not available\n                if len(gvar_list)!=len(variables_requested):\n                    err_list = [value[0] for key, value in model_varnames.items() \\\n                                 if value[0] in variables_requested and \\\n                                     key not in cdf_data.variables.keys()]\n                    if len(err_list)>0: print('Some requested variables are not available:', err_list)\n            else:  #only input variables on the avoid_list if specifically requested\n                avoid_list = []   #empty for now\n                gvar_list = [key for key in cdf_data.variables.keys() \\\n                             if key in model_varnames.keys() and \\\n                                 key not in avoid_list]            \n\n            # Store variable's units and reference to Dataset object in memory\n            variables = {model_varnames[key][0]:{'units':model_varnames[key][-1],\n                                   'data':getattr(cdf_data, key)}\\\n                              for key in gvar_list} \n            if verbose: print('Done reading in variable data.', full_file_prefix)\n    \n            #store variables\n            self.near_Earth_boundary_radius = cdf_data.near_Earth_boundary_radius\n            self.near_Earth_boundary_radius_unit = cdf_data.near_Earth_boundary_radius_units\n            self.missing_value = NaN\n            self.verbose = verbose\n            self.filename = cdf_data.file.split(',')\n            self.modelname = cdf_data.model\n            self.runname = runname\n            self.modelname = 'OpenGGCM_GM'\n            self._registered = 0\n            if printfiles: \n                print('Files:')\n                for file in self.filename: print(file)\n\n            #add coordinate grids as needed\n            #grid_list = list of coordinate names in cdf file\n            grid_list = ['_x','_y','_z','_x_bx','_y_bx','_z_bx','_x_by','_y_by',\n                         '_z_by','_x_bz','_y_bz','_z_bz','_x_ex','_y_ex','_z_ex',\n                         '_x_ey','_y_ey','_z_ey','_x_ez','_y_ez','_z_ez']\n            #trim down to only save coordinate grids needed for variables requested\n            #  and available in file\n            if 'B1_x' not in variables.keys(): \n                grid_list.remove('_x_bx')\n                grid_list.remove('_y_bx')\n                grid_list.remove('_z_bx')\n            if 'B1_y' not in variables.keys(): \n                grid_list.remove('_x_by')\n                grid_list.remove('_y_by')\n                grid_list.remove('_z_by')\n            if 'B1_z' not in variables.keys(): \n                grid_list.remove('_x_bz')\n                grid_list.remove('_y_bz')\n                grid_list.remove('_z_bz')\n            if 'E1_x' not in variables.keys(): \n                grid_list.remove('_x_ex')\n                grid_list.remove('_y_ex')\n                grid_list.remove('_z_ex')\n            if 'E1_y' not in variables.keys(): \n                grid_list.remove('_x_ey')\n                grid_list.remove('_y_ey')\n                grid_list.remove('_z_ey')\n            if 'E1_z' not in variables.keys(): \n                grid_list.remove('_x_ez')\n                grid_list.remove('_y_ez')\n                grid_list.remove('_z_ez')     \n            for grid in grid_list:\n                setattr(self, grid, getattr(cdf_data, grid).values)  #store coordinate data\n            cdf_data.close()  #done with file\n    \n            #register interpolators for each variable\n            varname_list, self.variables = [key for key in variables.keys()], {}  #store original list b/c gridded interpolators\n            t_reg = perf_counter()\n            for varname in varname_list:  #all are 3D variables\n                #make dimension names uniform for easier interpolation later\n                dim_names, dims_dict = list(variables[varname]['data'].dims), {}\n                dims_dict[dim_names[0]], dims_dict[dim_names[1]] = 'time', 'x'\n                dims_dict[dim_names[2]], dims_dict[dim_names[3]] = 'y', 'z'\n                variables[varname]['data'] = variables[varname]['data'].rename(\n                    **dims_dict)\n                \n                #store and register data                \n                self.variables[varname] = dict(units = variables[varname]['units'], \n                                               data = variables[varname]['data'])     #not saving data to decrease memory demand      \n                self.register_variable(self.variables[varname]['units'], \n                                       self.variables[varname]['data'], varname, \n                                       gridded_int)\n            #cdf_data.close()\n            if verbose: print(f'Took {perf_counter()-t_reg:.5f}s to register '+\\\n                              f'{len(varname_list)} variables.')\n            if verbose: print(f'Took a total of {perf_counter()-t0:.5f}s to kamodofy '+\\\n                              f'{len(gvar_list)} variables.')\n        \n        #define and register a 4D variable-----------------------------------------\n        def register_variable(self, units, variable, varname, gridded_int):\n            x_, y_, z_ = self.get_grid(varname) # variable may have different grid positions in the staggered grid of the model\n            xvec_dependencies = {'time':'hr','x':'R_E','y':'R_E','z':'R_E'}\n            \n            #variable is a DataArray object with a built-in interpolator, add coordinates\n            variable = variable.assign_coords({'time':self._time,'x':x_,'y':y_,'z':z_})\n\n            self = self.custom_interp(units, variable, varname, xvec_dependencies, \n                                      gridded_int)   #regdef_4D_interpolators     \n            return\n        \n        def get_grid(self, varname):\n            \"\"\"fetch the grid positon for this variable\"\"\"\n\n            if varname == 'B1_x':\n                return self._x_bx, self._y_bx, self._z_bx\n            elif varname == 'B1_y':\n                return self._x_by, self._y_by, self._z_by\n            elif varname == 'B1_z':\n                return self._x_bz, self._y_bz, self._z_bz\n            elif varname == 'E1_x':\n                return self._x_ex, self._y_ex, self._z_ex\n            elif varname == 'E1_y':\n                return self._x_ey, self._y_ey, self._z_ey\n            elif varname == 'E1_z':\n                return self._x_ez, self._y_ez, self._z_ez\n            else: # (default) positions on plasma grid\n                return self._x, self._y, self._z     \n            \n        def custom_interp(self, units, variable, varname, \n                          xvec_dependencies, gridded_int):\n            '''define interpolator based on xarray's except need inner boundary limit.\n            Decrease memory demand by not saving data arrays.'''\n\n            @kamodofy(units=units, data=variable)\n            def interpolator(xvec):  #xvec = [[t1,x1,y1,z1],[t2,x2,y2,z2],...]\n                \"\"\"Interpolates 4d variable without a grid\"\"\"\n                \n                t0 = perf_counter()\n                xvec_arr = array(xvec)\n                if len(xvec_arr.shape)==1: xvec_arr = expand_dims(xvec_arr, 0)\n                r = sqrt(sum(xvec_arr[:,1:]**2, axis=1))  #calculate radius 1D array\n                result = zeros(len(r))  #option 2, not much time diff from option 1\n                for i in range(len(r)):\n                    if r[i]>self.near_Earth_boundary_radius:\n                        result[i] = float(variable.interp(time=xvec_arr[i][0], x=xvec_arr[i][1], \n                                                          y=xvec_arr[i][2], z=xvec_arr[i][3]).values)\n                    else: \n                        result[i] = NaN\n                print(f'Took {perf_counter()-t0:.3f} s for {len(xvec)} positions.')\n                return result\n            \n            self = register_interpolator(self, varname, interpolator, xvec_dependencies)\n            \n            #define and register the gridded interpolator if desired\n            if gridded_int:\n                self.variables[varname+'_ijk'] = dict(units = units, data = variable) \n                \n                @kamodofy(units=units, data={}, arg_units=xvec_dependencies)\n                def gridded_interpolator(time, x, y, z):  \n                    \"\"\"Interpolates 4d variable on a grid\"\"\"\n                    \n                    t0 = perf_counter()\n                    time, x, y, z = array(time), array(x), array(y), array(z)\n                    r = sqrt(x**2+y**2+z**2)\n                    return where(r>self.near_Earth_boundary_radius, \n                                 variable.interp(time=time, x=x, y=y, z=z).values, NaN)\n\n                self = register_interpolator(self, varname+'_ijk', \n                                                         gridded_interpolator, \n                                                         xvec_dependencies)\n            return            \n        \n    return MODEL\n        \n        \n", "meta": {"hexsha": "c26ea7e70ad1880cb4be371d31cb96df9b1cfd49", "size": 16052, "ext": "py", "lang": "Python", "max_stars_repo_path": "kamodo_ccmc/flythrough/openggcm_gm_4Dcdf_xarray.py", "max_stars_repo_name": "asher-pembroke/Kamodo-1", "max_stars_repo_head_hexsha": "7dd155d98661f663b3f71267f92208949f279db7", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-06-21T19:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-19T14:09:36.000Z", "max_issues_repo_path": "kamodo_ccmc/flythrough/openggcm_gm_4Dcdf_xarray.py", "max_issues_repo_name": "asher-pembroke/Kamodo-1", "max_issues_repo_head_hexsha": "7dd155d98661f663b3f71267f92208949f279db7", "max_issues_repo_licenses": ["NASA-1.3"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kamodo_ccmc/flythrough/openggcm_gm_4Dcdf_xarray.py", "max_forks_repo_name": "asher-pembroke/Kamodo-1", "max_forks_repo_head_hexsha": "7dd155d98661f663b3f71267f92208949f279db7", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-20T15:59:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T15:59:25.000Z", "avg_line_length": 56.3228070175, "max_line_length": 134, "alphanum_fraction": 0.5516446549, "include": true, "reason": "from numpy", "num_tokens": 3822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.17879122753823784}}
{"text": "#!/usr/bin/env python3\n\n\"\"\"Core classes and functions for completions code.\"\"\"\n\nimport sys\nfrom typing import Dict\nfrom copy import deepcopy\n\nfrom functools import reduce\n\nfrom neutrinomass.tensormethod.core import (\n    BOSE,\n    FERMI,\n    Index,\n    IndexedField,\n    eps,\n    get_dynkin,\n)\nfrom neutrinomass.tensormethod.lagrangian import Lagrangian\n\n# from neutrinomass.completions.tikzfeynman import tikz_export\n\n\nclass FieldType(IndexedField):\n    \"\"\"Base class for exotic fields.\"\"\"\n\n    def __new__(cls, *args, **kwargs):\n        return super(FieldType, cls).__new__(cls, *args, **kwargs)\n\n    def lower_su2(self, skip=[]):\n        undotted, dotted, _, isospin, _ = self.indices_by_type.values()\n        epsilons = []\n        partner = self\n        for idx in [*undotted, *dotted, *isospin]:\n            if idx.index_type in skip:\n                continue\n            lower = str(idx) + \"^\"\n            partner = partner.substituted_indices((idx, lower))\n            epsilon = eps(\"-\" + lower + \" -\" + str(idx))\n            epsilons.append(epsilon)\n\n        # For VectorLikeDiracFermion, keep track of (un)barred boolean\n        is_unbarred = None\n        if hasattr(self, \"is_unbarred\"):\n            is_unbarred = self.is_unbarred\n\n        return cons_completion_field(partner, is_unbarred=is_unbarred), epsilons\n\n    @property\n    def indexed_field(self):\n        return IndexedField(label=self.label, indices=self.index_labels)\n\n    # @property\n    # def info(self):\n    #     return {\n    #         \"label\": self.label,\n    #         \"indices\": self.indices,\n    #         \"charges\": self.charges,\n    #         \"is_conj\": self.is_conj,\n    #         \"symmetry\": self.symmetry,\n    #         \"latex\": self.latex,\n    #     }\n\n    def __hash__(self):\n        dict_ = {\n            \"indices\": tuple(sorted(self.indices)),\n            \"label\": self.label,\n            \"dynkin\": self.dynkin,\n            \"charges\": tuple(sorted(self.charges.items())),\n        }\n        return hash(tuple(dict_.items()))\n\n    def __deepcopy__(self, memo):\n        return self.__class__(\n            label=self.label,\n            indices=deepcopy(self.indices, memo),\n            charges=deepcopy(self.charges, memo),\n            latex=self.latex,\n            is_conj=self.is_conj,\n            symmetry=deepcopy(self.symmetry, memo),\n            comm=self.comm,\n        )\n\n\nclass ComplexScalar(FieldType):\n    def __init__(\n        self,\n        label,\n        indices,\n        charges=None,\n        latex=None,\n        is_conj=False,\n        symmetry=None,\n        **kwargs,\n    ):\n        if isinstance(indices, list):\n            indices = \" \".join(str(i) for i in indices)\n\n        IndexedField.__init__(\n            self,\n            label=label,\n            indices=indices,\n            charges=charges,\n            is_conj=is_conj,\n            symmetry=None,\n            comm=BOSE,\n            latex=latex,\n            # **kwargs,\n        )\n\n        assert self.is_scalar\n\n    @property\n    def mass_term(self):\n        lower, epsilons = self.conj.lower_su2()\n        return reduce(lambda x, y: x * y, epsilons, lower * self)\n\n    # @property\n    # def kinetic_term(self):\n    #     \"\"\"I think this will mess with U(1) symmetries algorithm as currently\n    #     implemented\"\"\"\n    #     lower, epsilons = self.conj.lower_su2()\n    #     all_og_indices = \"u0 d0 \" + \" \".join(str(i) for i in self.indices)\n    #     all_lower_indices = \"u1 d1 \" + \" \".join(str(i) for i in lower.indices)\n    #     deriv_og = D(lower, \"11\")(all_og_indices)\n    #     deriv_lower = D(lower, \"11\")(all_lower_indices)\n    #     term = deriv_og * deriv_lower\n    #     return reduce(lambda x, y: x * y, epsilons, term)\n\n\ndef assert_real_rep(indices: str, charges) -> None:\n    if charges and \"y\" in charges:\n        assert charges[\"y\"] == 0\n\n    colour_dynkin_str = get_dynkin(indices)[2:4]\n\n    # simplistic way to check if colour rep is real\n    assert colour_dynkin_str == \"\".join(reversed(colour_dynkin_str))\n\n\nclass RealScalar(FieldType):\n    def __init__(\n        self, label, indices, charges=None, latex=None, is_conj=False, **kwargs\n    ):\n        if isinstance(indices, list):\n            indices = \" \".join(str(i) for i in indices)\n\n        IndexedField.__init__(\n            self,\n            label=label,\n            indices=indices,\n            charges=charges,\n            is_conj=is_conj,\n            symmetry=None,\n            comm=BOSE,\n            latex=latex,\n            # **kwargs,\n        )\n\n        assert self.is_scalar\n        assert_real_rep(indices, charges)\n\n    def swap_colour_indices(self):\n        \"\"\"New copy of field with colour indices flipped.\n\n        # TODO Refactor this out with majorana_partner to FieldType\n        \"\"\"\n        undotted, dotted, colour, isospin, _ = Index.indices_by_type(\n            self.indices\n        ).values()\n        colour = tuple(i.conj for i in colour)\n        indices = undotted + dotted + colour + isospin\n\n        return RealScalar(\n            self.label,\n            indices,\n            latex=self.latex,\n            is_conj=self.is_conj,\n            symmetry=self.symmetry,\n            comm=BOSE,\n            charges=None,\n        )\n\n    @property\n    def mass_term(self):\n        lower, epsilons = self.swap_colour_indices().lower_su2()\n        return reduce(lambda x, y: x * y, epsilons, lower * self)\n\n\nclass MajoranaFermion(FieldType):\n    def __init__(\n        self, label, indices, charges=None, latex=None, is_conj=False, **kwargs\n    ):\n        if isinstance(indices, list):\n            indices = \" \".join(str(i) for i in indices)\n\n        IndexedField.__init__(\n            self,\n            label=label,\n            indices=indices,\n            charges=charges,\n            is_conj=is_conj,\n            symmetry=None,\n            comm=FERMI,\n            latex=latex,\n            # **kwargs,\n        )\n\n        assert self.is_fermion\n        assert_real_rep(indices, charges)\n\n    def majorana_partner(self):\n        \"\"\"New copy of fermion with colour indices flipped\"\"\"\n        undotted, dotted, colour, isospin, _ = Index.indices_by_type(\n            self.indices\n        ).values()\n        colour = tuple(i.conj for i in colour)\n        indices = undotted + dotted + colour + isospin\n\n        return MajoranaFermion(\n            self.label,\n            indices,\n            latex=self.latex,\n            is_conj=self.is_conj,\n            symmetry=self.symmetry,\n            comm=FERMI,\n            charges=None,\n        )\n\n    @property\n    def conj_indices(self):\n        return self.conj\n\n    @property\n    def mass_term(self):\n        lower, epsilons = self.majorana_partner().lower_su2()\n        return reduce(lambda x, y: x * y, epsilons, lower * self)\n\n\nclass VectorLikeDiracFermion(FieldType):\n    \"\"\"Stands in for two fermion fields distinguished here only by dotted and\n    undotted indices.\n\n    Example:\n        >>> psi = VectorLikeDiracFermion(\"ψ\", \"u0 i1\")\n        >>> psi\n        ψ(u0, i1)\n        >>> psi.dirac_partner()\n        ψ~(u0, i1)\n\n    Here ψ(u0, i1) and ψ~(u0, i1) are different fields.\n\n    \"\"\"\n\n    def __init__(\n        self,\n        label,\n        indices,\n        charges=None,\n        latex=None,\n        is_unbarred=True,\n        is_conj=False,\n        symmetry=None,\n        comm=FERMI,\n        **kwargs,\n    ):\n        if isinstance(indices, list):\n            indices = \" \".join(str(i) for i in indices)\n\n        IndexedField.__init__(\n            self,\n            label=label,\n            indices=indices,\n            charges=charges,\n            is_conj=is_conj,\n            symmetry=None,\n            latex=latex,\n            comm=FERMI,\n            # **kwargs,\n        )\n\n        assert self.is_fermion\n        self.is_unbarred = is_unbarred\n\n    @property\n    def conj(self):\n        \"\"\"Returns a copy of self but conjugated\"\"\"\n\n        is_conj = self.is_conj\n        if is_conj:\n            label = self.label.replace(\"†\", \"\")\n        else:\n            label = self.label + \"†\"\n\n        return self.__class__(\n            label=label,\n            indices=\" \".join(i.conj.label for i in self.indices),\n            charges={k: -v for k, v in self.charges.items()},\n            is_conj=(not is_conj),\n            is_unbarred=self.is_unbarred,\n            symmetry=self.symmetry,\n            comm=self.comm,\n        )\n\n    @property\n    def conj_indices(self):\n        \"\"\"Returns a copy of self conjugated but leaves charges alone.\"\"\"\n        is_conj = self.is_conj\n        if is_conj:\n            label = self.label.replace(\"†\", \"\")\n        else:\n            label = self.label + \"†\"\n\n        return self.__class__(\n            label=label,\n            indices=\" \".join(i.conj.label for i in self.indices),\n            charges=self.charges,\n            is_conj=(not is_conj),\n            is_unbarred=self.is_unbarred,\n            symmetry=self.symmetry,\n            comm=self.comm,\n        )\n\n    def dirac_partner(self):\n        undotted, dotted, colour, isospin, _ = Index.indices_by_type(\n            self.indices\n        ).values()\n        colour = tuple(i.conj for i in colour)\n        indices = undotted + dotted + colour + isospin\n        charges = {k: -v for k, v in self.charges.items()}\n\n        is_unbarred = self.is_unbarred\n        symb = \"~\"  # indicate bar with circumflex\n        if is_unbarred:\n            label = self.label + symb\n        else:\n            label = self.label.replace(symb, \"\")\n\n        return VectorLikeDiracFermion(\n            label,\n            indices,\n            charges=charges,\n            latex=self.latex,\n            is_unbarred=(not self.is_unbarred),\n            is_conj=self.is_conj,\n            symmetry=self.symmetry,\n            comm=FERMI,\n        )\n\n    @property\n    def mass_term(self):\n        lower, epsilons = self.dirac_partner().lower_su2()\n        return reduce(lambda x, y: x * y, epsilons, lower * self)\n\n\nclass EffectiveOperator:\n    def __init__(self, name, operator):\n        self.name = name\n        self.operator = operator\n\n    @property\n    def fields(self):\n        return self.operator.fields\n\n    @property\n    def indexed_fields(self):\n        return self.operator.indexed_fields\n\n    @property\n    def mass_dimension(self):\n        d = sum(f.mass_dim for f in self.fields)\n        d += sum(f.derivs for f in self.fields)\n        d_int = int(d)\n        assert d == d_int\n        return d_int\n\n    @property\n    def topology_type(self):\n        \"\"\"Returns a dictionary {\"n_scalars\": n_scalars, \"n_fermions\": n_fermions}.\"\"\"\n\n        n_scalars, n_fermions = 0, 0\n        for f in self.fields:\n            if f.is_boson:\n                n_scalars += 1\n            elif f.is_fermion:\n                n_fermions += 1\n\n        return {\"n_scalars\": n_scalars, \"n_fermions\": n_fermions}\n\n    def __hash__(self):\n        return hash((self.name, self.operator.simplify()))\n\n\nclass FailedCompletion:\n    def __init__(self, reason: str = \"\"):\n        self.reason = reason\n\n\nclass Completion:\n    def __init__(self, operator, partition, graph, exotics, terms, topology=None):\n        self.operator = operator\n        self.partition = partition\n        self.graph = graph\n        self.exotics = exotics\n        self.terms = terms\n        self.topology = topology\n\n    def __eq__(self, other):\n        if not isinstance(other, Completion):\n            return False\n        return (\n            self.operator == other.operator\n            and self.exotic_info() == other.exotic_info()\n            and self.partition == other.partition\n        )\n\n    def __hash__(self):\n        return hash((self.operator, self.exotic_info(), self.partition))\n\n    def __deepcopy__(self, memo):\n        return self.__class__(\n            operator=deepcopy(self.operator, memo),\n            partition=deepcopy(self.partition, memo),\n            graph=deepcopy(self.graph, memo),\n            exotics=deepcopy(self.exotics, memo),\n            terms=deepcopy(self.terms, memo),\n        )\n\n    @property\n    def lagrangian(self):\n        return Lagrangian(exotics=self.exotics, interaction_terms=self.terms)\n\n    def draw_diagram(self):\n        import matplotlib.pyplot as plt\n        from matplotlib import rc\n        import networkx as nx\n\n        # Unicode Greek edge labels won't render in TeX\n        rc(\"text\", usetex=False)\n\n        g = self.graph\n        edge_labels = nx.get_edge_attributes(g, name=\"particle\")\n        pos = nx.spring_layout(g)\n\n        plt.figure()\n        nx.draw(g, pos=pos, edge_color=\"black\", node_size=0)\n        nx.draw_networkx_edge_labels(\n            g, pos=pos, edge_labels=edge_labels, font_color=\"red\"\n        )\n        plt.axis(\"off\")\n        plt.show()\n\n    def exotic_info(self) -> Dict[FieldType, tuple]:\n        info = {}\n        for e in self.exotics:\n            # normalise hypercharge to be positive\n            if e.y < 0:\n                charges = sorted(e.conj.charges.items())\n                sm = e.conj.sm_irrep\n            else:\n                charges = sorted(e.charges.items())\n                sm = e.sm_irrep\n\n            if e.is_fermion:\n                lorentz = \"F\"\n            elif e.is_scalar:\n                lorentz = \"S\"\n            else:\n                raise ValueError(\"Unrecognised exotic field type.\")\n\n            info[e] = (lorentz,) + sm + tuple(charges)\n\n        return info\n\n    def exotic_fields(self):\n        return set([e.field for e in self.exotics])\n\n    def info(self):\n        print(\"Fields:\")\n        for k, v in self.exotic_info().items():\n            print(\"{:<5s}{:<20s}\".format(k.label, format_quantum_numbers(v)))\n\n        print(\"\\nLagrangian:\")\n        in_jupyter = sys.argv[-1].endswith(\"json\")\n        for term in self.terms:\n            if in_jupyter:\n                display(term)\n            else:\n                print(term)\n\n        print(\"\\nDiagram:\")\n        self.draw_diagram()\n\n\nclass Model:\n    def __init__(self, completions):\n        self.completions = completions\n\n    @property\n    def exotic_numbers(self):\n        return sorted(\n            set(\n                format_quantum_numbers(i)\n                for i in self.completions[0].exotic_info().values()\n            )\n        )\n\n    def __repr__(self):\n        return \"Model(\" + \" + \".join(i for i in self.exotic_numbers) + \")\"\n\n\ndef format_quantum_numbers(info: tuple):\n    \"\"\"Takes an expression like\n\n    ('S', 1, 0, 2, ('3b', 1), ('y', 2/3))\n\n    and returns a string like\n\n    S(3, 3, 2/3)(3b: 1)\n\n    \"\"\"\n    lorentz, su3_up, su3_down, su2, *charges = info\n    su3_dim = lambda m, n: 0.5 * (m + 1) * (n + 1) * (m + n + 2)\n    # For now just add the bar for more lowered than raised indices, but for\n    # larger reps this will be problematic\n    su3_dim_format = lambda m, n: str(int(su3_dim(m, n))) + (\"b\" if n > m else \"\")\n    charges_dict = dict(charges)\n    return f\"{lorentz}({su3_dim_format(int(su3_up), int(su3_down))}, {str(int(su2) + 1)}, {charges_dict['y']})({charges_dict['3b']})\"\n\n\ndef cons_completion_field(indexed_field: IndexedField, is_unbarred=None) -> FieldType:\n    label = indexed_field.label\n    indices = indexed_field.indices\n    charges = indexed_field.charges\n    latex = indexed_field.latex\n    is_conj = indexed_field.is_conj\n\n    if indexed_field.is_fermion:\n        if indexed_field.is_real_sm_irrep:\n            return MajoranaFermion(\n                label, indices, charges=charges, latex=latex, is_conj=is_conj\n            )\n\n        if is_unbarred is None:\n            is_unbarred = True\n\n        return VectorLikeDiracFermion(\n            label,\n            indices,\n            charges=charges,\n            latex=latex,\n            is_unbarred=is_unbarred,\n            is_conj=is_conj,\n        )\n\n    if indexed_field.is_scalar:\n        if indexed_field.is_real_sm_irrep:\n            return RealScalar(label, indices, charges=charges, latex=latex)\n\n        return ComplexScalar(\n            label, indices, charges=charges, latex=latex, is_conj=is_conj\n        )\n\n    raise Exception(\"Unrecognised Lorentz structure in field.\")\n", "meta": {"hexsha": "04b4c37e2aa48a44485a5bd289d5a7c517fc5e4e", "size": 15973, "ext": "py", "lang": "Python", "max_stars_repo_path": "neutrinomass/completions/core.py", "max_stars_repo_name": "johngarg/neutrinomass", "max_stars_repo_head_hexsha": "a4f1adf6abf10de16f34c7f89164342ba5857329", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-28T14:38:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T08:45:05.000Z", "max_issues_repo_path": "neutrinomass/completions/core.py", "max_issues_repo_name": "johngarg/neutrinomass", "max_issues_repo_head_hexsha": "a4f1adf6abf10de16f34c7f89164342ba5857329", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "neutrinomass/completions/core.py", "max_forks_repo_name": "johngarg/neutrinomass", "max_forks_repo_head_hexsha": "a4f1adf6abf10de16f34c7f89164342ba5857329", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-29T23:25:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-29T23:25:14.000Z", "avg_line_length": 28.2707964602, "max_line_length": 133, "alphanum_fraction": 0.5637638515, "include": true, "reason": "import networkx", "num_tokens": 3881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3415824927356586, "lm_q1q2_score": 0.1787912275382378}}
{"text": "\"\"\"\nBPASS version 2\n\nEldridge, Stanway et al, 2017, PASA 34, 58\n\nPaper describes version 2.1. Latest updates in 2.2 described in\nStanway & Eldridge (2018).\n\"\"\"\n\nimport re, os\nimport numpy as np\nfrom scipy.interpolate import interp1d\nfrom ares.physics.Constants import h_p, c, erg_per_ev, g_per_msun, s_per_yr, \\\n    s_per_myr, m_H, Lsun\n\n_input = os.getenv('ARES') + '/input/bpass_v2/SEDS'\n\nmetallicities = \\\n{\n '040': 0.040, '030': 0.040, '020': 0.020, '010': 0.010,\n '008': 0.008, '006': 0.006, '004': 0.004, '003': 0.003,\n '001': 0.002, '001': 0.001,\n}\n\ninfo = \\\n{\n 'flux_units': r'$L_{\\odot} \\ \\AA^{-1}$',\n}\n\n_log10_times = np.arange(6, 10.1, 0.1)\ntimes = 10**_log10_times / 1e6            # Convert from yr to Myr\n\ndef _kwargs_to_fn(**kwargs):\n    \"\"\"\n    Determine filename of appropriate BPASS lookup table based on kwargs.\n    \"\"\"\n\n    # All files share this prefix\n    fn = 'spectra'\n\n    assert kwargs['source_ssp'], \\\n        \"No support for continuous star formation in BPASS v2.\"\n    assert kwargs['source_nebular'] in [0, 2], \\\n        \"No support for nebular emission in BPASS v2.\"\n\n    if kwargs['source_binaries']:\n        fn += '-bin'\n    else:\n        fn += '-sin'\n\n    fn += '-imf{}'.format(str((kwargs['source_imf'] - 1)).replace('.', ''))\n    fn += '_{}'.format(str(int(kwargs['source_imf_Mmax'])))\n\n    # Metallicity\n    fn += '.z{!s}'.format(str(int(kwargs['source_Z'] * 1e3)).zfill(3))\n\n    if kwargs['source_sed_degrade'] is not None:\n        fn += '.deg{}'.format(kwargs['source_sed_degrade'])\n\n    fn += '.dat'\n\n    return _input + '/' + fn\n\ndef _load(**kwargs):\n    \"\"\"\n    Return wavelengths, fluxes, for given set of parameters (at all times).\n    \"\"\"\n\n    Zvals_l = list(metallicities.values())\n    Zvals = np.sort(Zvals_l)\n\n    # Interpolate\n    if kwargs['source_Z'] not in Zvals_l:\n        tmp = kwargs.copy()\n\n        _fn = []\n        spectra = []\n        del tmp['source_Z']\n        for Z in Zvals:\n            _w1, _d1, fn = _load(source_Z=Z, **tmp)\n            spectra.append(_d1.copy())\n            _fn.append(fn)\n\n        wavelengths = wave = _w1\n        data = spectra\n\n    # No interpolation necessary\n    else:\n        fn = _fn = _kwargs_to_fn(**kwargs)\n\n        _raw_data = np.loadtxt(fn)\n\n        data = np.array(_raw_data[:,1:])\n        wavelengths = _raw_data[:,0]\n\n        data *= Lsun\n\n    return wavelengths, data, _fn\n", "meta": {"hexsha": "4bb5e0b802f693e7e85227318b492db7e2c97409", "size": 2370, "ext": "py", "lang": "Python", "max_stars_repo_path": "input/litdata/eldridge2017.py", "max_stars_repo_name": "JJHibbard/ares", "max_stars_repo_head_hexsha": "4b185747f2182524d732ef8316bff3a709bd85f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-03-26T01:08:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T13:02:10.000Z", "max_issues_repo_path": "input/litdata/eldridge2017.py", "max_issues_repo_name": "JJHibbard/ares", "max_issues_repo_head_hexsha": "4b185747f2182524d732ef8316bff3a709bd85f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2020-06-08T14:52:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T02:30:54.000Z", "max_forks_repo_path": "input/litdata/eldridge2017.py", "max_forks_repo_name": "JJHibbard/ares", "max_forks_repo_head_hexsha": "4b185747f2182524d732ef8316bff3a709bd85f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-03-24T14:11:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-06T06:32:59.000Z", "avg_line_length": 23.9393939394, "max_line_length": 78, "alphanum_fraction": 0.5864978903, "include": true, "reason": "import numpy,from scipy", "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.3073580168652638, "lm_q1q2_score": 0.17866816959697768}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2021 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#         Timothy Berkelbach <tim.berkelbach@gmail.com>\n#\n\n'''\nQCISD for real integrals\n8-fold permutation symmetry has been used\n(ij|kl) = (ji|kl) = (kl|ij) = ...\n'''\n\n\nimport numpy\nfrom pyscf import gto\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf.cc.ccsd import CCSD, _add_vvvv, _flops, _ChemistsERIs\nfrom pyscf import __config__\n\nBLKMIN = getattr(__config__, 'cc_ccsd_blkmin', 4)\nMEMORYMIN = getattr(__config__, 'cc_ccsd_memorymin', 2000)\n\n\n# t1: ia\n# t2: ijab\ndef kernel(mycc, eris=None, t1=None, t2=None, max_cycle=50, tol=1e-8,\n           tolnormt=1e-6, verbose=None):\n    log = logger.new_logger(mycc, verbose)\n    if eris is None:\n        eris = mycc.ao2mo(mycc.mo_coeff)\n    if t1 is None and t2 is None:\n        t1, t2 = mycc.get_init_guess(eris)\n    elif t2 is None:\n        t2 = mycc.get_init_guess(eris)[1]\n\n    cput1 = cput0 = (logger.process_clock(), logger.perf_counter())\n    eold = 0\n    eccsd = mycc.energy(t1, t2, eris)\n    log.info('Init E_corr(QCISD) = %.15g', eccsd)\n\n    if isinstance(mycc.diis, lib.diis.DIIS):\n        adiis = mycc.diis\n    elif mycc.diis:\n        adiis = lib.diis.DIIS(mycc, mycc.diis_file, incore=mycc.incore_complete)\n        adiis.space = mycc.diis_space\n    else:\n        adiis = None\n\n    conv = False\n    for istep in range(max_cycle):\n        t1new, t2new = mycc.update_amps(t1, t2, eris)\n        tmpvec = mycc.amplitudes_to_vector(t1new, t2new)\n        tmpvec -= mycc.amplitudes_to_vector(t1, t2)\n        normt = numpy.linalg.norm(tmpvec)\n        tmpvec = None\n        if mycc.iterative_damping < 1.0:\n            alpha = mycc.iterative_damping\n            t1new = (1-alpha) * t1 + alpha * t1new\n            t2new *= alpha\n            t2new += (1-alpha) * t2\n        t1, t2 = t1new, t2new\n        t1new = t2new = None\n        t1, t2 = mycc.run_diis(t1, t2, istep, normt, eccsd-eold, adiis)\n        eold, eccsd = eccsd, mycc.energy(t1, t2, eris)\n        log.info('cycle = %d  E_corr(QCISD) = %.15g  dE = %.9g  norm(t1,t2) = %.6g',\n                 istep+1, eccsd, eccsd - eold, normt)\n        cput1 = log.timer('QCISD iter', *cput1)\n        if abs(eccsd-eold) < tol and normt < tolnormt:\n            conv = True\n            break\n    log.timer('QCISD', *cput0)\n    return conv, eccsd, t1, t2\n\n\ndef update_amps(mycc, t1, t2, eris):\n    assert(isinstance(eris, _ChemistsERIs))\n\n    time0 = logger.process_clock(), logger.perf_counter()\n    log = logger.Logger(mycc.stdout, mycc.verbose)\n    nocc, nvir = t1.shape\n    fock = eris.fock\n    mo_e_o = eris.mo_energy[:nocc]\n    mo_e_v = eris.mo_energy[nocc:] + mycc.level_shift\n\n    t1new = numpy.zeros_like(t1)\n    t2new = _add_vvvv(mycc, 0*t1, t2, eris, t2sym='jiba')\n    t2new *= .5  # *.5 because t2+t2.transpose(1,0,3,2) in the end\n    time1 = log.timer_debug1('vvvv', *time0)\n\n#** make_inter_F\n    fov = fock[:nocc,nocc:].copy()\n    t1new += fov\n\n    foo = fock[:nocc,:nocc] - numpy.diag(mo_e_o)\n    fvv = fock[nocc:,nocc:] - numpy.diag(mo_e_v)\n\n    if mycc.incore_complete:\n        fswap = None\n    else:\n        fswap = lib.H5TmpFile()\n    fwVOov, fwVooV = _add_ovvv_(mycc, t1, t2, eris, fvv, t1new, t2new, fswap)\n    time1 = log.timer_debug1('ovvv', *time1)\n\n    woooo = numpy.asarray(eris.oooo).transpose(0,2,1,3).copy()\n\n    unit = nocc**2*nvir*7 + nocc**3 + nocc*nvir**2\n    mem_now = lib.current_memory()[0]\n    max_memory = max(0, mycc.max_memory - mem_now)\n    blksize = min(nvir, max(BLKMIN, int((max_memory*.9e6/8-nocc**4)/unit)))\n    log.debug1('max_memory %d MB,  nocc,nvir = %d,%d  blksize = %d',\n               max_memory, nocc, nvir, blksize)\n\n    for p0, p1 in lib.prange(0, nvir, blksize):\n        wVOov = fwVOov[p0:p1]\n        wVooV = fwVooV[p0:p1]\n        eris_ovoo = eris.ovoo[:,p0:p1]\n        eris_oovv = numpy.empty((nocc,nocc,p1-p0,nvir))\n        def load_oovv(p0, p1):\n            eris_oovv[:] = eris.oovv[:,:,p0:p1]\n        with lib.call_in_background(load_oovv, sync=not mycc.async_io) as prefetch_oovv:\n            #:eris_oovv = eris.oovv[:,:,p0:p1]\n            prefetch_oovv(p0, p1)\n            wVOov -= lib.einsum('jbik,ka->bjia', eris_ovoo, t1)\n            t2new[:,:,p0:p1] += wVOov.transpose(1,2,0,3)\n            eris_ovoo = None\n        load_oovv = prefetch_oovv = None\n\n        wVOov *= 0 # QCI\n\n        eris_ovvo = numpy.empty((nocc,p1-p0,nvir,nocc))\n        def load_ovvo(p0, p1):\n            eris_ovvo[:] = eris.ovvo[:,p0:p1]\n        with lib.call_in_background(load_ovvo, sync=not mycc.async_io) as prefetch_ovvo:\n            #:eris_ovvo = eris.ovvo[:,p0:p1]\n            prefetch_ovvo(p0, p1)\n            t1new[:,p0:p1] -= numpy.einsum('jb,jiab->ia', t1, eris_oovv)\n            wVooV -= eris_oovv.transpose(2,0,1,3)\n            wVOov += wVooV*.5  #: bjia + bija*.5\n        load_ovvo = prefetch_ovvo = None\n\n        t2new[:,:,p0:p1] += (eris_ovvo*0.5).transpose(0,3,1,2)\n        eris_voov = eris_ovvo.conj().transpose(1,0,3,2)\n        t1new[:,p0:p1] += 2*numpy.einsum('jb,aijb->ia', t1, eris_voov)\n        eris_ovvo = None\n        eris_oovv = tmp = None\n\n        fov[:,p0:p1] += numpy.einsum('kc,aikc->ia', t1, eris_voov) * 2\n        fov[:,p0:p1] -= numpy.einsum('kc,akic->ia', t1, eris_voov)\n\n        tau = t2[:,:,p0:p1]\n        theta  = tau.transpose(1,0,2,3) * 2\n        theta -= tau\n        fvv -= lib.einsum('cjia,cjib->ab', theta.transpose(2,1,0,3), eris_voov)\n        foo += lib.einsum('aikb,kjab->ij', eris_voov, theta)\n        theta = None\n        woooo += lib.einsum('ijab,aklb->ijkl', tau, eris_voov)\n        tau = None\n\n        def update_wVooV(q0, q1, tau):\n            wVooV[:] += lib.einsum('bkic,jkca->bija', eris_voov[:,:,:,q0:q1], tau)\n        with lib.call_in_background(update_wVooV, sync=not mycc.async_io) as update_wVooV:\n            for q0, q1 in lib.prange(0, nvir, blksize):\n                tau  = t2[:,:,q0:q1] * .5\n                #:wVooV += lib.einsum('bkic,jkca->bija', eris_voov[:,:,:,q0:q1], tau)\n                update_wVooV(q0, q1, tau)\n        tau = update_wVooV = None\n        def update_t2(q0, q1, tmp):\n            t2new[:,:,q0:q1] += tmp.transpose(2,0,1,3)\n            tmp *= .5\n            t2new[:,:,q0:q1] += tmp.transpose(0,2,1,3)\n        with lib.call_in_background(update_t2, sync=not mycc.async_io) as update_t2:\n            for q0, q1 in lib.prange(0, nvir, blksize):\n                tmp = lib.einsum('jkca,ckib->jaib', t2[:,:,p0:p1,q0:q1], wVooV)\n                #:t2new[:,:,q0:q1] += tmp.transpose(2,0,1,3)\n                #:tmp *= .5\n                #:t2new[:,:,q0:q1] += tmp.transpose(0,2,1,3)\n                update_t2(q0, q1, tmp)\n                tmp = None\n\n        wVOov += eris_voov\n        eris_VOov = -.5 * eris_voov.transpose(0,2,1,3)\n        eris_VOov += eris_voov\n        eris_voov = None\n        def update_wVOov(q0, q1, tau):\n            wVOov[:,:,:,q0:q1] += .5 * lib.einsum('aikc,kcjb->aijb', eris_VOov, tau)\n        with lib.call_in_background(update_wVOov, sync=not mycc.async_io) as update_wVOov:\n            for q0, q1 in lib.prange(0, nvir, blksize):\n                tau  = t2[:,:,q0:q1].transpose(1,3,0,2) * 2\n                tau -= t2[:,:,q0:q1].transpose(0,3,1,2)\n                #:wVOov[:,:,:,q0:q1] += .5 * lib.einsum('aikc,kcjb->aijb', eris_VOov, tau)\n                update_wVOov(q0, q1, tau)\n                tau = None\n        def update_t2(q0, q1, theta):\n            t2new[:,:,q0:q1] += lib.einsum('kica,ckjb->ijab', theta, wVOov)\n        with lib.call_in_background(update_t2, sync=not mycc.async_io) as update_t2:\n            for q0, q1 in lib.prange(0, nvir, blksize):\n                theta  = t2[:,:,p0:p1,q0:q1] * 2\n                theta -= t2[:,:,p0:p1,q0:q1].transpose(1,0,2,3)\n                #:t2new[:,:,q0:q1] += lib.einsum('kica,ckjb->ijab', theta, wVOov)\n                update_t2(q0, q1, theta)\n                theta = None\n        eris_VOov = wVOov = wVooV = update_wVOov = None\n        time1 = log.timer_debug1('voov [%d:%d]'%(p0, p1), *time1)\n    fwVOov = fwVooV = fswap = None\n\n    for p0, p1 in lib.prange(0, nvir, blksize):\n        theta = t2[:,:,p0:p1].transpose(1,0,2,3) * 2 - t2[:,:,p0:p1]\n        t1new += numpy.einsum('jb,ijba->ia', fov[:,p0:p1], theta)\n        t1new -= lib.einsum('jbki,kjba->ia', eris.ovoo[:,p0:p1], theta)\n\n        tau = t2[:,:,p0:p1]\n        t2new[:,:,p0:p1] += .5 * lib.einsum('ijkl,klab->ijab', woooo, tau)\n        theta = tau = None\n\n    t2new += lib.einsum('ijac,bc->ijab', t2, fvv)\n    t2new -= lib.einsum('ki,kjab->ijab', foo, t2)\n\n    eia = mo_e_o[:,None] - mo_e_v\n    t1new += numpy.einsum('ib,ab->ia', t1, fvv)\n    t1new -= numpy.einsum('ja,ji->ia', t1, foo)\n    t1new /= eia\n\n    #: t2new = t2new + t2new.transpose(1,0,3,2)\n    for i in range(nocc):\n        if i > 0:\n            t2new[i,:i] += t2new[:i,i].transpose(0,2,1)\n            t2new[i,:i] /= lib.direct_sum('a,jb->jab', eia[i], eia[:i])\n            t2new[:i,i] = t2new[i,:i].transpose(0,2,1)\n        t2new[i,i] = t2new[i,i] + t2new[i,i].T\n        t2new[i,i] /= lib.direct_sum('a,b->ab', eia[i], eia[i])\n\n    time0 = log.timer_debug1('update t1 t2', *time0)\n    return t1new, t2new\n\ndef _add_ovvv_(mycc, t1, t2, eris, fvv, t1new, t2new, fswap):\n    time1 = logger.process_clock(), logger.perf_counter()\n    log = logger.Logger(mycc.stdout, mycc.verbose)\n    nocc, nvir = t1.shape\n    nvir_pair = nvir * (nvir+1) // 2\n\n    if fswap is None:\n        wVOov = numpy.zeros((nvir,nocc,nocc,nvir))\n    else:\n        wVOov = fswap.create_dataset('wVOov', (nvir,nocc,nocc,nvir), 'f8')\n    wooVV = numpy.zeros((nocc,nocc*nvir_pair))\n\n    max_memory = mycc.max_memory - lib.current_memory()[0]\n    unit = nocc*nvir**2*3 + nocc**2*nvir + 2\n    blksize = min(nvir, max(BLKMIN, int((max_memory*.95e6/8-wooVV.size)/unit)))\n    if not mycc.direct:\n        unit = nocc*nvir**2*3 + nocc**2*nvir + 2 + nocc*nvir**2 + nocc*nvir\n        blksize = min(nvir, max(BLKMIN, int((max_memory*.95e6/8-wooVV.size-nocc**2*nvir)/unit)))\n    log.debug1('max_memory %d MB,  nocc,nvir = %d,%d  blksize = %d',\n               max_memory, nocc, nvir, blksize)\n\n    def load_ovvv(buf, p0):\n        if p0 < nvir:\n            p1 = min(nvir, p0+blksize)\n            buf[:p1-p0] = eris.ovvv[:,p0:p1].transpose(1,0,2)\n\n    with lib.call_in_background(load_ovvv, sync=not mycc.async_io) as prefetch:\n        buf = numpy.empty((blksize,nocc,nvir_pair))\n        buf_prefetch = numpy.empty((blksize,nocc,nvir_pair))\n\n        load_ovvv(buf_prefetch, 0)\n        for p0, p1 in lib.prange(0, nvir, blksize):\n            buf, buf_prefetch = buf_prefetch, buf\n            prefetch(buf_prefetch, p1)\n\n            eris_vovv = buf[:p1-p0]\n            eris_vovv = lib.unpack_tril(eris_vovv.reshape((p1-p0)*nocc,nvir_pair))\n            eris_vovv = eris_vovv.reshape(p1-p0,nocc,nvir,nvir)\n\n            wVOov[p0:p1] = lib.einsum('biac,jc->bija', eris_vovv, t1)\n\n            theta = t2[:,:,p0:p1].transpose(1,2,0,3) * 2\n            theta -= t2[:,:,p0:p1].transpose(0,2,1,3)\n            t1new += lib.einsum('icjb,cjba->ia', theta, eris_vovv)\n            theta = None\n            time1 = log.timer_debug1('vovv [%d:%d]'%(p0, p1), *time1)\n\n    if fswap is None:\n        wooVV = lib.unpack_tril(wooVV.reshape(nocc**2,nvir_pair))\n        return wVOov, wooVV.reshape(nocc,nocc,nvir,nvir).transpose(2,1,0,3)\n    else:\n        fswap.create_dataset('wVooV', (nvir,nocc,nocc,nvir), 'f8')\n        wooVV = wooVV.reshape(nocc,nocc,nvir_pair)\n        tril2sq = lib.square_mat_in_trilu_indices(nvir)\n        for p0, p1 in lib.prange(0, nvir, blksize):\n            fswap['wVooV'][p0:p1] = wooVV[:,:,tril2sq[p0:p1]].transpose(2,1,0,3)\n        return fswap['wVOov'], fswap['wVooV']\n\ndef energy(mycc, t1=None, t2=None, eris=None):\n    '''CCSD correlation energy'''\n    if t1 is None: t1 = mycc.t1\n    if t2 is None: t2 = mycc.t2\n    if eris is None: eris = mycc.ao2mo()\n\n    nocc, nvir = t1.shape\n    fock = eris.fock\n    e = numpy.einsum('ia,ia', fock[:nocc,nocc:], t1) * 2\n    max_memory = mycc.max_memory - lib.current_memory()[0]\n    blksize = int(min(nvir, max(BLKMIN, max_memory*.3e6/8/(nocc**2*nvir+1))))\n    for p0, p1 in lib.prange(0, nvir, blksize):\n        eris_ovvo = eris.ovvo[:,p0:p1]\n        tau = t2[:,:,p0:p1]\n        e += 2 * numpy.einsum('ijab,iabj', tau, eris_ovvo)\n        e -=     numpy.einsum('jiab,iabj', tau, eris_ovvo)\n    if abs(e.imag) > 1e-4:\n        logger.warn(mycc, 'Non-zero imaginary part found in QCISD energy %s', e)\n    return e.real\n\ndef as_scanner(cc):\n    '''Generating a scanner/solver for QCISD PES.\n\n    The returned solver is a function. This function requires one argument\n    \"mol\" as input and returns total QCISD energy.\n\n    '''\n    if isinstance(cc, lib.SinglePointScanner):\n        return cc\n\n    logger.info(cc, 'Set %s as a scanner', cc.__class__)\n\n    class QCISD_Scanner(cc.__class__, lib.SinglePointScanner):\n        def __init__(self, cc):\n            self.__dict__.update(cc.__dict__)\n            self._scf = cc._scf.as_scanner()\n        def __call__(self, mol_or_geom, **kwargs):\n            if isinstance(mol_or_geom, gto.Mole):\n                mol = mol_or_geom\n            else:\n                mol = self.mol.set_geom_(mol_or_geom, inplace=False)\n\n            if self.t2 is not None:\n                last_size = self.vector_size()\n            else:\n                last_size = 0\n\n            self.reset(mol)\n\n            mf_scanner = self._scf\n            mf_scanner(mol)\n            self.mo_coeff = mf_scanner.mo_coeff\n            self.mo_occ = mf_scanner.mo_occ\n            if last_size != self.vector_size():\n                self.t1 = self.t2 = None\n            self.kernel(self.t1, self.t2, **kwargs)\n            return self.e_tot\n    return QCISD_Scanner(cc)\n\n\nclass QCISD(CCSD):\n    '''restricted QCISD\n    '''\n\n    def dump_flags(self, verbose=None):\n        log = logger.new_logger(self, verbose)\n        log.info('')\n        log.info('******** %s ********', self.__class__)\n        log.info('QCISD nocc = %s, nmo = %s', self.nocc, self.nmo)\n        if self.frozen is not None:\n            log.info('frozen orbitals %s', self.frozen)\n        log.info('max_cycle = %d', self.max_cycle)\n        log.info('direct = %d', self.direct)\n        log.info('conv_tol = %g', self.conv_tol)\n        log.info('conv_tol_normt = %s', self.conv_tol_normt)\n        log.info('diis_space = %d', self.diis_space)\n        #log.info('diis_file = %s', self.diis_file)\n        log.info('diis_start_cycle = %d', self.diis_start_cycle)\n        log.info('diis_start_energy_diff = %g', self.diis_start_energy_diff)\n        log.info('max_memory %d MB (current use %d MB)',\n                 self.max_memory, lib.current_memory()[0])\n        if (log.verbose >= logger.DEBUG1 and\n            self.__class__ == QCISD):\n            nocc = self.nocc\n            nvir = self.nmo - self.nocc\n            flops = _flops(nocc, nvir)\n            log.debug1('total FLOPs %s', flops)\n        return self\n\n    energy = energy\n    _add_vvvv = _add_vvvv\n    update_amps = update_amps\n\n    def kernel(self, t1=None, t2=None, eris=None):\n        return self.qcisd(t1, t2, eris)\n    def qcisd(self, t1=None, t2=None, eris=None):\n        assert(self.mo_coeff is not None)\n        assert(self.mo_occ is not None)\n\n        if self.verbose >= logger.WARN:\n            self.check_sanity()\n        self.dump_flags()\n\n        if eris is None:\n            eris = self.ao2mo(self.mo_coeff)\n\n        self.e_hf = getattr(eris, 'e_hf', None)\n        if self.e_hf is None:\n            self.e_hf = self._scf.e_tot\n\n        self.converged, self.e_corr, self.t1, self.t2 = \\\n                kernel(self, eris, t1, t2, max_cycle=self.max_cycle,\n                       tol=self.conv_tol, tolnormt=self.conv_tol_normt,\n                       verbose=self.verbose)\n        self._finalize()\n        return self.e_corr, self.t1, self.t2\n\n    as_scanner = as_scanner\n\n    def qcisd_t(self, t1=None, t2=None, eris=None):\n        from pyscf.cc import qcisd_t\n        if t1 is None: t1 = self.t1\n        if t2 is None: t2 = self.t2\n        if eris is None: eris = self.ao2mo(self.mo_coeff)\n        return qcisd_t.kernel(self, eris, t1, t2, self.verbose)\n\nRQCISD = QCISD\n\n\nif __name__ == '__main__':\n    from pyscf import scf\n\n    mol = gto.Mole()\n    #mol.atom = [\n    #    [8 , (0. , 0.     , 0.)],\n    #    [1 , (0. , -0.757 , 0.587)],\n    #    [1 , (0. , 0.757  , 0.587)]]\n    mol.atom = [['Ne', (0,0,0)]]\n    mol.basis = 'cc-pvdz'\n    mol.verbose = 7\n    mol.spin = 0\n    mol.build()\n    mf = scf.RHF(mol).run(conv_tol=1e-14)\n\n    mycc = QCISD(mf, frozen=1)\n    ecc, t1, t2 = mycc.kernel()\n    et = mycc.qcisd_t()\n    print(\"QCISD(T) =\", mycc.e_tot+et)\n\n    mol = gto.Mole()\n    mol.atom = \"\"\"C  0.000  0.000  0.000\n                  H  0.637  0.637  0.637\n                  H -0.637 -0.637  0.637\n                  H -0.637  0.637 -0.637\n                  H  0.637 -0.637 -0.637\"\"\"\n    mol.basis = 'cc-pvdz'\n    mol.verbose = 7\n    mol.spin = 0\n    mol.build()\n    mf = scf.RHF(mol).run(conv_tol=1e-14)\n\n    mycc = QCISD(mf, frozen=1)\n    ecc, t1, t2 = mycc.kernel()\n    print(mycc.e_tot - -40.383989)\n    et = mycc.qcisd_t()\n    print(mycc.e_tot+et - -40.387679)\n", "meta": {"hexsha": "e63568718e9754f5a563193c0711074d957baecb", "size": 17710, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/cc/qcisd.py", "max_stars_repo_name": "umamibeef/pyscf", "max_stars_repo_head_hexsha": "1263d54b02914caf4476a3ed9a2de5e0c848954c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 501, "max_stars_repo_stars_event_min_datetime": "2018-12-06T23:48:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:53:18.000Z", "max_issues_repo_path": "pyscf/cc/qcisd.py", "max_issues_repo_name": "fabijan5/pyscf", "max_issues_repo_head_hexsha": "09834c8f5a4f5320cdde29d285b6ccd89b3263e0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 710, "max_issues_repo_issues_event_min_datetime": "2018-11-26T22:04:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:53:12.000Z", "max_forks_repo_path": "pyscf/cc/qcisd.py", "max_forks_repo_name": "fabijan5/pyscf", "max_forks_repo_head_hexsha": "09834c8f5a4f5320cdde29d285b6ccd89b3263e0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 273, "max_forks_repo_forks_event_min_datetime": "2018-11-26T10:10:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:25:28.000Z", "avg_line_length": 37.4418604651, "max_line_length": 96, "alphanum_fraction": 0.5749858837, "include": true, "reason": "import numpy", "num_tokens": 6152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.17852639884616978}}
{"text": "#!/usr/bin/env python\n\n\"\"\"\nm2g.track\n~~~~~~~~~~\n\nContains m2g's fiber reconstruction and tractography functionality.\nTheory described here: https://neurodata.io/talks/ndmg.pdf#page=21\n\"\"\"\n\n# system imports\nimport os\n\n# external package imports\nimport numpy as np\nimport nibabel as nib\n\n# dipy imports\nfrom dipy.tracking.streamline import Streamlines\nfrom dipy.tracking import utils\nfrom dipy.tracking.local_tracking import LocalTracking\nfrom dipy.tracking.local_tracking import ParticleFilteringTracking\nfrom dipy.tracking.stopping_criterion import BinaryStoppingCriterion\nfrom dipy.tracking.stopping_criterion import ActStoppingCriterion\nfrom dipy.tracking.stopping_criterion import CmcStoppingCriterion\n\nfrom dipy.reconst.dti import fractional_anisotropy, TensorModel, quantize_evecs\nfrom dipy.reconst.shm import CsaOdfModel\nfrom dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel, recursive_response\n\nfrom dipy.data import get_sphere\nfrom dipy.direction import peaks_from_model, ProbabilisticDirectionGetter\nfrom m2g.utils.gen_utils import timer\n\nfrom m2g.stats import qa_tensor\n\n\ndef build_seed_list(mask_img_file, stream_affine, dens):\n    \"\"\"uses dipy tractography utilities in order to create a seed list for tractography\n\n    Parameters\n    ----------\n    mask_img_file : str\n        path to mask of area to generate seeds for\n    stream_affine : ndarray\n        4x4 array with 1s diagonally and 0s everywhere else\n    dens : int\n        seed density\n\n    Returns\n    -------\n    ndarray\n        locations for the seeds\n    \"\"\"\n\n    mask_img = nib.load(mask_img_file)\n    mask_img_data = mask_img.get_data().astype(\"bool\")\n    seeds = utils.random_seeds_from_mask(\n        mask_img_data,\n        affine=stream_affine,\n        seeds_count=int(dens),\n        seed_count_per_voxel=True,\n    )\n    return seeds\n\n\ndef tens_mod_fa_est(gtab, dwi_file, B0_mask):\n    \"\"\"Estimate a tensor FA image to use for registrations using dipy functions\n\n    Parameters\n    ----------\n    gtab : GradientTable\n        gradient table created from bval and bvec file\n    dwi_file : str\n        Path to eddy-corrected and RAS reoriented dwi image\n    B0_mask : str\n        Path to nodif B0 mask (averaged b0 mask)\n\n    Returns\n    -------\n    str\n        Path to tensor_fa image file\n    \"\"\"\n\n    data = nib.load(dwi_file).get_fdata()\n\n    print(\"Generating simple tensor FA image to use for registrations...\")\n    nodif_B0_img = nib.load(B0_mask)\n    B0_mask_data = nodif_B0_img.get_fdata().astype(\"bool\")\n    nodif_B0_affine = nodif_B0_img.affine\n    model = TensorModel(gtab)\n    mod = model.fit(data, B0_mask_data)\n    FA = fractional_anisotropy(mod.evals)\n    FA[np.isnan(FA)] = 0\n    fa_img = nib.Nifti1Image(FA.astype(np.float32), nodif_B0_affine)\n    fa_path = f\"{os.path.dirname(B0_mask)}/tensor_fa.nii.gz\"\n    nib.save(fa_img, fa_path)\n    return fa_path\n\n\nclass RunTrack:\n    def __init__(\n        self,\n        dwi_in,\n        nodif_B0_mask,\n        gm_in_dwi,\n        vent_csf_in_dwi,\n        csf_in_dwi,\n        wm_in_dwi,\n        gtab,\n        mod_type,\n        track_type,\n        mod_func,\n        qa_tensor_out,\n        seeds,\n        stream_affine,\n    ):\n        \"\"\"A class for deterministic tractography in native space\n\n        Parameters\n        ----------\n        dwi_in : str\n            path to the input dwi image to perform tractography on.\n            Should be a nifti, gzipped nifti, or other image that nibabel\n            is capable of reading, with data as a 4D object.\n        nodif_B0_mask : str\n            path to the mask of the b0 mean volume. Should be a nifti,\n            gzipped nifti, or other image file that nibabel is capable of\n            reading, with data as a 3D object.\n        gm_in_dwi : str\n            Path to gray matter segmentation in EPI space. Should be a nifti,\n            gzipped nifti, or other image file that nibabel is capable of\n            reading, with data as a 3D object\n        vent_csf_in_dwi : str\n            Ventricular CSF Mask in EPI space. Should be a nifti,\n            gzipped nifti, or other image file that nibabel is capable of\n            reading, with data as a 3D object\n        csf_in_dwi : str\n            Path to CSF mask in EPI space. Should be a nifti, gzipped nifti, or other image file that nibabel compatable\n        wm_in_dwi : str\n            Path to white matter probabilities in EPI space. Should be a nifti,\n            gzipped nifti, or other image file that nibabel is capable of\n            reading, with data as a 3D object.\n        gtab : gradient table\n            gradient table created from bval and bvec files\n        mod_type : str\n            Determinstic (det) or probabilistic (prob) tracking\n        track_type : str\n            Tracking approach: local or particle\n        mod_func : str\n            Diffusion model: csd or csa\n        qa_tensor: str\n            path to store the qa for tensor/directions of model \n        seeds : ndarray\n            ndarray of seeds for tractography\n        stream_affine : ndarray\n            4x4 2D array with 1s diagonaly and 0s everywhere else\n        \"\"\"\n\n        self.dwi = dwi_in\n        self.nodif_B0_mask = nodif_B0_mask\n        self.gm_in_dwi = gm_in_dwi\n        self.vent_csf_in_dwi = vent_csf_in_dwi\n        self.csf_in_dwi = csf_in_dwi\n        self.wm_in_dwi = wm_in_dwi\n        self.gtab = gtab\n        self.mod_type = mod_type\n        self.track_type = track_type\n        self.qa_tensor_out = qa_tensor_out \n        self.seeds = seeds\n        self.mod_func = mod_func\n        self.stream_affine = stream_affine\n\n\n    @timer\n    def run(self):\n        \"\"\"Creates the tracktography tracks using dipy commands and the specified tracking type and approach\n\n        Returns\n        -------\n        ArraySequence\n            contains the tractography track raw data for further analysis\n\n        Raises\n        ------\n        ValueError\n            Raised when no seeds are supplied or no valid seeds were found in white-matter interface\n        ValueError\n            Raised when no seeds are supplied or no valid seeds were found in white-matter interface\n        \"\"\"\n        self.tiss_classifier = self.prep_tracking()\n        if self.mod_type == \"det\":\n            if self.mod_func == \"csa\":\n                self.mod = self.odf_mod_est()\n            elif self.mod_func == \"csd\":\n                self.mod = self.csd_mod_est()\n            if self.track_type == \"local\":\n                tracks = self.local_tracking()\n            elif self.track_type == \"particle\":\n                tracks = self.particle_tracking()\n            else:\n                raise ValueError(\n                    \"Error: Either no seeds supplied, or no valid seeds found in white-matter interface\"\n                )\n        elif self.mod_type == \"prob\":\n            if self.mod_func == \"csa\":\n                self.mod = self.odf_mod_est()\n            elif self.mod_func == \"csd\":\n                self.mod = self.csd_mod_est()\n            if self.track_type == \"local\":\n                tracks = self.local_tracking()\n            elif self.track_type == \"particle\":\n                tracks = self.particle_tracking()\n        else:\n            raise ValueError(\n                \"Error: Either no seeds supplied, or no valid seeds found in white-matter interface\"\n            )\n        tracks = Streamlines([track for track in tracks if len(track) > 60])\n        return tracks\n\n    @staticmethod\n    def make_hdr(streamlines, hdr):\n        trk_hdr = nib.streamlines.trk.TrkFile.create_empty_header()\n        trk_hdr[\"hdr_size\"] = 1000\n        trk_hdr[\"dimensions\"] = hdr[\"dim\"][1:4].astype(\"float32\")\n        trk_hdr[\"voxel_sizes\"] = hdr[\"pixdim\"][1:4]\n        trk_hdr[\"voxel_to_rasmm\"] = np.eye(4)\n        trk_hdr[\"voxel_order\"] = \"RAS\"\n        trk_hdr[\"pad2\"] = \"RAS\"\n        trk_hdr[\"image_orientation_patient\"] = np.array(\n            [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n        ).astype(\"float32\")\n        trk_hdr[\"endianness\"] = \"<\"\n        trk_hdr[\"_offset_data\"] = 1000\n        trk_hdr[\"nb_streamlines\"] = streamlines.total_nb_rows\n\n        return trk_hdr\n\n    def prep_tracking(self):\n        \"\"\"Uses nibabel and dipy functions in order to load the grey matter, white matter, and csf masks\n        and use a tissue classifier (act, cmc, or binary) on the include/exclude maps to make a tissueclassifier object\n\n        Returns\n        -------\n        ActStoppingCriterion, CmcStoppingCriterion, or BinaryStoppingCriterion\n            The resulting tissue classifier object, depending on which method you use (currently only does act)\n        \"\"\"\n\n        if self.track_type == \"local\":\n            tiss_class = \"bin\"\n        elif self.track_type == \"particle\":\n            tiss_class = \"cmc\"\n\n        self.dwi_img = nib.load(self.dwi)\n        self.data = self.dwi_img.get_data()\n        # Loads mask and ensures it's a true binary mask\n        self.mask_img = nib.load(self.nodif_B0_mask)\n        self.mask = self.mask_img.get_data() > 0\n        # Load tissue maps and prepare tissue classifier\n        self.gm_mask = nib.load(self.gm_in_dwi)\n        self.gm_mask_data = self.gm_mask.get_data()\n        self.wm_mask = nib.load(self.wm_in_dwi)\n        self.wm_mask_data = self.wm_mask.get_data()\n        self.wm_in_dwi_data = nib.load(self.wm_in_dwi).get_data().astype(\"bool\")\n        if tiss_class == \"act\":\n            self.vent_csf_in_dwi = nib.load(self.vent_csf_in_dwi)\n            self.vent_csf_in_dwi_data = self.vent_csf_in_dwi.get_data()\n            self.background = np.ones(self.gm_mask.shape)\n            self.background[\n                (self.gm_mask_data + self.wm_mask_data + self.vent_csf_in_dwi_data) > 0\n            ] = 0\n            self.include_map = self.wm_mask_data\n            self.include_map[self.background > 0] = 0\n            self.exclude_map = self.vent_csf_in_dwi_data\n            self.tiss_classifier = ActStoppingCriterion(\n                self.include_map, self.exclude_map\n            )\n        elif tiss_class == \"bin\":\n            self.tiss_classifier = BinaryStoppingCriterion(self.wm_in_dwi_data)\n            # self.tiss_classifier = BinaryStoppingCriterion(self.mask)\n        elif tiss_class == \"cmc\":\n            self.vent_csf_in_dwi = nib.load(self.vent_csf_in_dwi)\n            self.vent_csf_in_dwi_data = self.vent_csf_in_dwi.get_data()\n            voxel_size = np.average(self.wm_mask.get_header()[\"pixdim\"][1:4])\n            step_size = 0.2\n            self.tiss_classifier = CmcStoppingCriterion.from_pve(\n                self.wm_mask_data,\n                self.gm_mask_data,\n                self.vent_csf_in_dwi_data,\n                step_size=step_size,\n                average_voxel_size=voxel_size,\n            )\n        else:\n            pass\n        return self.tiss_classifier\n\n    @timer\n    def tens_mod_est(self):\n\n        print(\"Fitting tensor model...\")\n        self.model = TensorModel(self.gtab)\n        self.ten = self.model.fit(self.data, self.wm_in_dwi_data)\n        self.fa = self.ten.fa\n        self.fa[np.isnan(self.fa)] = 0\n        self.sphere = get_sphere(\"repulsion724\")\n        self.ind = quantize_evecs(self.ten.evecs, self.sphere.vertices)\n        return self.ten\n\n    @timer\n    def odf_mod_est(self):\n\n        print(\"Fitting CSA ODF model...\")\n        self.mod = CsaOdfModel(self.gtab, sh_order=6)\n        return self.mod\n\n    @timer\n    def csd_mod_est(self):\n\n        print(\"Fitting CSD model...\")\n        try:\n            print(\"Attempting to use spherical harmonic basis first...\")\n            self.mod = ConstrainedSphericalDeconvModel(self.gtab, None, sh_order=6)\n        except:\n            print(\"Falling back to estimating recursive response...\")\n            self.response = recursive_response(\n                self.gtab,\n                self.data,\n                mask=self.wm_in_dwi_data,\n                sh_order=6,\n                peak_thr=0.01,\n                init_fa=0.08,\n                init_trace=0.0021,\n                iter=8,\n                convergence=0.001,\n                parallel=False,\n            )\n            print(\"CSD Reponse: \" + str(self.response))\n            self.mod = ConstrainedSphericalDeconvModel(self.gtab, self.response,sh_order=6)\n        return self.mod\n\n    @timer\n    def local_tracking(self):\n\n        self.sphere = get_sphere(\"repulsion724\")\n        if self.mod_type == \"det\":\n            print(\"Obtaining peaks from model...\")\n            self.mod_peaks = peaks_from_model(\n                self.mod,\n                self.data,\n                self.sphere,\n                relative_peak_threshold=0.5,\n                min_separation_angle=25,\n                mask=self.wm_in_dwi_data,\n                npeaks=5,\n                normalize_peaks=True,\n            )\n            qa_tensor.create_qa_figure(self.mod_peaks.peak_dirs, self.mod_peaks.peak_values, self.qa_tensor_out, self.mod_func)\n            self.streamline_generator = LocalTracking(\n                self.mod_peaks,\n                self.tiss_classifier,\n                self.seeds,\n                self.stream_affine,\n                step_size=0.5,\n                return_all=True,\n            )\n        elif self.mod_type == \"prob\":\n            print(\"Preparing probabilistic tracking...\")\n            print(\"Fitting model to data...\")\n            self.mod_fit = self.mod.fit(self.data, self.wm_in_dwi_data)\n            print(\"Building direction-getter...\")\n            self.mod_peaks = peaks_from_model(\n                self.mod,\n                self.data,\n                self.sphere,\n                relative_peak_threshold=0.5,\n                min_separation_angle=25,\n                mask=self.wm_in_dwi_data,\n                npeaks=5,\n                normalize_peaks=True,\n            )\n            qa_tensor.create_qa_figure(self.mod_peaks.peak_dirs, self.mod_peaks.peak_values, self.qa_tensor_out, self.mod_func)\n            try:\n                print(\n                    \"Proceeding using spherical harmonic coefficient from model estimation...\"\n                )\n                self.pdg = ProbabilisticDirectionGetter.from_shcoeff(\n                    self.mod_fit.shm_coeff, max_angle=60.0, sphere=self.sphere\n                )\n            except:\n                print(\"Proceeding using FOD PMF from model estimation...\")\n                self.fod = self.mod_fit.odf(self.sphere)\n                self.pmf = self.fod.clip(min=0)\n                self.pdg = ProbabilisticDirectionGetter.from_pmf(\n                    self.pmf, max_angle=60.0, sphere=self.sphere\n                )\n            self.streamline_generator = LocalTracking(\n                self.pdg,\n                self.tiss_classifier,\n                self.seeds,\n                self.stream_affine,\n                step_size=0.5,\n                return_all=True,\n            )\n        print(\"Reconstructing tractogram streamlines...\")\n        self.streamlines = Streamlines(self.streamline_generator)\n        return self.streamlines\n\n    @timer\n    def particle_tracking(self):\n\n        self.sphere = get_sphere(\"repulsion724\")\n        if self.mod_type == \"det\":\n            maxcrossing = 1\n            print(\"Obtaining peaks from model...\")\n            self.mod_peaks = peaks_from_model(\n                self.mod,\n                self.data,\n                self.sphere,\n                relative_peak_threshold=0.5,\n                min_separation_angle=25,\n                mask=self.wm_in_dwi_data,\n                npeaks=5,\n                normalize_peaks=True,\n            )\n            qa_tensor.create_qa_figure(self.mod_peaks.peak_dirs, self.mod_peaks.peak_values, self.qa_tensor_out, self.mod_func)\n            self.streamline_generator = ParticleFilteringTracking(\n                self.mod_peaks,\n                self.tiss_classifier,\n                self.seeds,\n                self.stream_affine,\n                max_cross=maxcrossing,\n                step_size=0.5,\n                maxlen=1000,\n                pft_back_tracking_dist=2,\n                pft_front_tracking_dist=1,\n                particle_count=15,\n                return_all=True,\n            )\n        elif self.mod_type == \"prob\":\n            maxcrossing = 2\n            print(\"Preparing probabilistic tracking...\")\n            print(\"Fitting model to data...\")\n            self.mod_fit = self.mod.fit(self.data, self.wm_in_dwi_data)\n            print(\"Building direction-getter...\")\n            self.mod_peaks = peaks_from_model(\n                self.mod,\n                self.data,\n                self.sphere,\n                relative_peak_threshold=0.5,\n                min_separation_angle=25,\n                mask=self.wm_in_dwi_data,\n                npeaks=5,\n                normalize_peaks=True,\n            )\n            qa_tensor.create_qa_figure(self.mod_peaks.peak_dirs, self.mod_peaks.peak_values, self.qa_tensor_out, self.mod_func)\n            try:\n                print(\n                    \"Proceeding using spherical harmonic coefficient from model estimation...\"\n                )\n                self.pdg = ProbabilisticDirectionGetter.from_shcoeff(\n                    self.mod_fit.shm_coeff, max_angle=60.0, sphere=self.sphere\n                )\n            except:\n                print(\"Proceeding using FOD PMF from model estimation...\")\n                self.fod = self.mod_fit.odf(self.sphere)\n                self.pmf = self.fod.clip(min=0)\n                self.pdg = ProbabilisticDirectionGetter.from_pmf(\n                    self.pmf, max_angle=60.0, sphere=self.sphere\n                )\n            self.streamline_generator = ParticleFilteringTracking(\n                self.pdg,\n                self.tiss_classifier,\n                self.seeds,\n                self.stream_affine,\n                max_cross=maxcrossing,\n                step_size=0.5,\n                maxlen=1000,\n                pft_back_tracking_dist=2,\n                pft_front_tracking_dist=1,\n                particle_count=15,\n                return_all=True,\n            )\n        print(\"Reconstructing tractogram streamlines...\")\n        self.streamlines = Streamlines(self.streamline_generator)\n        return self.streamlines\n", "meta": {"hexsha": "499047788086ff4a7b11a92f11aba126661e30fb", "size": 18108, "ext": "py", "lang": "Python", "max_stars_repo_path": "m2g/track.py", "max_stars_repo_name": "caseypw/m2g", "max_stars_repo_head_hexsha": "be29587322ab1fafb96f6afb726efbdb39b64b66", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "m2g/track.py", "max_issues_repo_name": "caseypw/m2g", "max_issues_repo_head_hexsha": "be29587322ab1fafb96f6afb726efbdb39b64b66", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "m2g/track.py", "max_forks_repo_name": "caseypw/m2g", "max_forks_repo_head_hexsha": "be29587322ab1fafb96f6afb726efbdb39b64b66", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2592592593, "max_line_length": 127, "alphanum_fraction": 0.5927766733, "include": true, "reason": "import numpy", "num_tokens": 4188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.17852639884616978}}
{"text": "from typing import List\n\nimport numpy\n\nimport torch\n\n\ndef jaccard(_box_a, _box_b):\n    # 计算真实框的左上角和右下角\n    b1_x1, b1_x2 = _box_a[:, 0] - _box_a[:, 2] / 2, _box_a[:, 0] + _box_a[:, 2] / 2\n    b1_y1, b1_y2 = _box_a[:, 1] - _box_a[:, 3] / 2, _box_a[:, 1] + _box_a[:, 3] / 2\n    # 计算先验框的左上角和右下角\n    b2_x1, b2_x2 = _box_b[:, 0] - _box_b[:, 2] / 2, _box_b[:, 0] + _box_b[:, 2] / 2\n    b2_y1, b2_y2 = _box_b[:, 1] - _box_b[:, 3] / 2, _box_b[:, 1] + _box_b[:, 3] / 2\n    box_a = torch.zeros_like(_box_a)\n    box_b = torch.zeros_like(_box_b)\n    box_a[:, 0], box_a[:, 1], box_a[:, 2], box_a[:, 3] = b1_x1, b1_y1, b1_x2, b1_y2\n    box_b[:, 0], box_b[:, 1], box_b[:, 2], box_b[:, 3] = b2_x1, b2_y1, b2_x2, b2_y2\n    A = box_a.size(0)\n    B = box_b.size(0)\n    max_xy = torch.min(box_a[:, 2:].unsqueeze(1).expand(A, B, 2),\n                       box_b[:, 2:].unsqueeze(0).expand(A, B, 2))\n    min_xy = torch.max(box_a[:, :2].unsqueeze(1).expand(A, B, 2),\n                       box_b[:, :2].unsqueeze(0).expand(A, B, 2))\n    inter = torch.clamp((max_xy - min_xy), min=0)\n\n    inter = inter[:, :, 0] * inter[:, :, 1]\n    # 计算先验框和真实框各自的面积\n    area_a = ((box_a[:, 2] - box_a[:, 0]) *\n              (box_a[:, 3] - box_a[:, 1])).unsqueeze(1).expand_as(inter)  # [A,B]\n    area_b = ((box_b[:, 2] - box_b[:, 0]) *\n              (box_b[:, 3] - box_b[:, 1])).unsqueeze(0).expand_as(inter)  # [A,B]\n    # 求IOU\n    union = area_a + area_b - inter\n    return inter / union  # [A,B]\n\n\ndef intersect(box_a, box_b):\n    \"\"\" We resize both tensors to [A,B,2] without new malloc:\n    [A,2] -> [A,1,2] -> [A,B,2]\n    [B,2] -> [1,B,2] -> [A,B,2]\n    Then we compute the area of intersect between box_a and box_b.\n    Args:\n      box_a: (tensor) bounding boxes, Shape: [A,4].\n      box_b: (tensor) bounding boxes, Shape: [B,4].\n    Return:\n      (tensor) intersection area, Shape: [A,B].\n    \"\"\"\n    A = box_a.size(0)\n    B = box_b.size(0)\n    max_xy = torch.min(box_a[:, 2:].unsqueeze(1).expand(A, B, 2),\n                       box_b[:, 2:].unsqueeze(0).expand(A, B, 2))\n    min_xy = torch.max(box_a[:, :2].unsqueeze(1).expand(A, B, 2),\n                       box_b[:, :2].unsqueeze(0).expand(A, B, 2))\n    inter = torch.clamp((max_xy - min_xy), min=0)\n    return inter[:, :, 0] * inter[:, :, 1]\n    # inter[:, :, 0] is the width of intersection and inter[:, :, 1] is height\n\n\ndef jaccard_tensor(box_a: torch.Tensor, box_b: torch.Tensor) -> torch.Tensor:\n    \"\"\"Compute the jaccard overlap of two sets of boxes.  The jaccard overlap\n    is simply the intersection over union of two boxes.  Here we operate on\n    ground truth boxes and default boxes.\n    E.g.:\n        A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B)\n    Args:\n        box_a: (tensor) Ground truth bounding boxes, Shape: [A,4]\n        box_b: (tensor) Prior boxes from priorbox layers, Shape: [B,4]\n    Return:\n        jaccard overlap: (tensor) Shape: [A, B]\n    \"\"\"\n    inter = intersect(box_a, box_b)\n    area_a = ((box_a[:, 2] - box_a[:, 0]) *\n              (box_a[:, 3] - box_a[:, 1])).unsqueeze(1).expand_as(inter)  # [A,B]\n    area_b = ((box_b[:, 2] - box_b[:, 0]) *\n              (box_b[:, 3] - box_b[:, 1])).unsqueeze(0).expand_as(inter)  # [A,B]\n    union = area_a + area_b - inter\n    return inter / union  # [A,B]\n\n\nclass YoloV3Loss(torch.nn.Module):\n    \"\"\"\n    YoloV3 损失函数\n    \"\"\"\n\n    def __init__(self, config: dict) -> None:\n        super().__init__()\n\n        self.lambda_xy = 0.05  # 预测框中心误差权重\n        self.lambda_wh = 0.05  # 预测框大小误差权重\n        self.lambda_noobj = 1.0  # 预测框置信度误差权重\n        self.lambda_obj = 1.0  # 预测框置信度误差权重\n        self.lambda_class = 0.5  # 预测框类别误差权重\n        self.lambda_conf = 1.0  # 预测框类别误差权重\n\n        self.normd_anchors = numpy.asarray(config[\"anchors\"]).astype(numpy.float32)\n        self.normd_anchors[:, :, 0] /= config[\"image_width\"]\n        self.normd_anchors[:, :, 1] /= config[\"image_height\"]\n        self.normd_anchors = self.normd_anchors.reshape((9, 2))\n        self.normd_anchors_box = torch.cat(\n            (\n                torch.zeros((self.normd_anchors.shape[0], 2)),\n                torch.from_numpy(self.normd_anchors)\n            ), 1)\n\n        self.classes = config[\"classes\"]\n        self.bbox_attrs = 4 + 1 + self.classes\n\n        self.ignore_threshold = 0.3  # iou 忽略的阈值\n\n        self.cuda = config[\"cuda\"]\n\n    def decode_pyramid_boxes(self,\n                             pyramid_boxes_list: List[torch.Tensor],\n                             pyramid_features: int,\n                             predict_feature: torch.Tensor,\n                             ignore_on: bool\n                             ) -> (\n            torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor,\n            torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor,\n            torch.Tensor, torch.Tensor\n    ):\n        \"\"\"\n        将真值框分成三个特征层，并变换成 tensor 的格式\n        \"\"\"\n        assert pyramid_features in [13, 26, 52]\n\n        if pyramid_features == 13:\n            pyramid_anch_index_list = [0, 1, 2]\n            cur_anchors = self.normd_anchors[0:3]\n        elif pyramid_features == 26:\n            pyramid_anch_index_list = [3, 4, 5]\n            cur_anchors = self.normd_anchors[3:6]\n        elif pyramid_features == 52:\n            pyramid_anch_index_list = [6, 7, 8]\n            cur_anchors = self.normd_anchors[6:9]\n        else:\n            raise Exception(\"unexpected error\")\n\n        batch_size = len(pyramid_boxes_list)\n\n        # 将真值框变换为如下的 tensor 格式\n        boxes_x = torch.zeros(batch_size, 3, pyramid_features, pyramid_features)\n        boxes_y = torch.zeros(batch_size, 3, pyramid_features, pyramid_features)\n        boxes_w = torch.zeros(batch_size, 3, pyramid_features, pyramid_features)\n        boxes_h = torch.zeros(batch_size, 3, pyramid_features, pyramid_features)\n\n        boxes_loss_weight_xw = torch.zeros(batch_size, 3, pyramid_features, pyramid_features)\n        boxes_loss_weight_yh = torch.zeros(batch_size, 3, pyramid_features, pyramid_features)\n\n        boxes_obj_conf = torch.zeros(batch_size, 3, pyramid_features, pyramid_features)\n        boxes_class_conf_list = torch.zeros(batch_size, 3, pyramid_features, pyramid_features,\n                                            self.classes)\n\n        boxes_obj_mask = torch.zeros(batch_size, 3, pyramid_features, pyramid_features)\n        boxes_noobj_mask = torch.ones(batch_size, 3, pyramid_features, pyramid_features)\n\n        # 遍历这一个批次所有的图片\n        for bs_i, pyramid_boxes in enumerate(pyramid_boxes_list):\n            if pyramid_boxes.shape[0] == 0:\n                continue\n\n            # 将真值框的 xy 变换为相对于网格的偏移量，顺便获取真值框在 tensor 表示中的网格索引（truth_grid_x，truth_grid_y——\n            truth_feature_box = pyramid_boxes[:, 0:4] * pyramid_features\n\n            truth_grid_x = torch.floor(truth_feature_box[:, 0]).int()\n            truth_grid_y = torch.floor(truth_feature_box[:, 1]).int()\n\n            truth_x = truth_feature_box[:, 0] - truth_grid_x\n            truth_y = truth_feature_box[:, 1] - truth_grid_y\n\n            # 和真值框 iou 最大的 anchor 索引，确定真值框所在的特征层\n            truth_box = pyramid_boxes[:, :4].clone().detach()\n            truth_box[:, 0] = 0\n            truth_box[:, 1] = 0\n            normd_anch_ious = jaccard_tensor(truth_box, self.normd_anchors_box)\n            max_anch_ious_index = torch.argmax(normd_anch_ious, dim=-1)\n\n            for box_i, anch_i in enumerate(max_anch_ious_index):\n                if anch_i not in pyramid_anch_index_list:\n                    continue\n                pyramid_anch_i = anch_i % 3\n\n                boxes_x[bs_i, pyramid_anch_i, truth_grid_y[box_i], truth_grid_x[box_i]] = truth_x[box_i]\n                boxes_y[bs_i, pyramid_anch_i, truth_grid_y[box_i], truth_grid_x[box_i]] = truth_y[box_i]\n\n                truth_w_box = torch.log(pyramid_boxes[box_i][2] / self.normd_anchors[anch_i][0])\n                truth_h_box = torch.log(pyramid_boxes[box_i][3] / self.normd_anchors[anch_i][1])\n                boxes_w[bs_i, pyramid_anch_i, truth_grid_y[box_i], truth_grid_x[box_i]] = truth_w_box\n                boxes_h[bs_i, pyramid_anch_i, truth_grid_y[box_i], truth_grid_x[box_i]] = truth_h_box\n\n                boxes_loss_weight_xw[bs_i, pyramid_anch_i, truth_grid_y[box_i], truth_grid_x[box_i]] = \\\n                    pyramid_boxes[box_i][2]\n                boxes_loss_weight_yh[bs_i, pyramid_anch_i, truth_grid_y[box_i], truth_grid_x[box_i]] = \\\n                    pyramid_boxes[box_i][3]\n\n                boxes_obj_conf[bs_i, pyramid_anch_i, truth_grid_y[box_i], truth_grid_x[box_i]] = 1\n                boxes_class_conf_list[bs_i, pyramid_anch_i, truth_grid_y[box_i], truth_grid_x[box_i],\n                                      pyramid_boxes[box_i][4].int()] = 1\n\n                boxes_obj_mask[bs_i, pyramid_anch_i, truth_grid_y[box_i], truth_grid_x[box_i]] = 1\n                boxes_noobj_mask[bs_i, pyramid_anch_i, truth_grid_y[box_i], truth_grid_x[box_i]] = 0  # 可以确定一定有物体\n\n        # print(\"loss in cuda\") if self.cuda else print(\"loss not in cuda\")\n\n        if ignore_on:\n            # ----------------------------------------------------------------------------------------------------- #\n            # 一些预测框和真值框 iou 较大的地方，有可能有物体\n            cur_anchors_num = 3\n            predict_feature_height = pyramid_features\n            predict_feature_width = pyramid_features\n            # 4. 将预测网络输出的特征层进行维度变换，将预测框个数与预测属性分开，并将预测属性转置为末位维度的属性，便于提取和解析\n            predict_feature = predict_feature.contiguous().view(\n                batch_size,\n                cur_anchors_num,\n                self.bbox_attrs,\n                predict_feature_height,\n                predict_feature_width,\n            ).permute(0, 1, 3, 4, 2).contiguous()\n\n            # 5. 分隔预测属性\n            predict_x = predict_feature[..., 0]\n            predict_y = predict_feature[..., 1]\n            predict_w = predict_feature[..., 2]\n            predict_h = predict_feature[..., 3]\n\n            # 6. 解析 xy\n            norm_predict_x = torch.sigmoid(predict_x)\n            norm_predict_y = torch.sigmoid(predict_y)\n            # 6.1 构造 grid tensor\n            grid_x = torch.linspace(0, predict_feature_width - 1, predict_feature_width) \\\n                .repeat(predict_feature_height, 1) \\\n                .repeat(batch_size * cur_anchors_num, 1, 1) \\\n                .view(predict_x.shape)\n            grid_y = torch.linspace(0, predict_feature_height - 1, predict_feature_height) \\\n                .repeat(predict_feature_width, 1) \\\n                .t() \\\n                .repeat(batch_size * cur_anchors_num, 1, 1) \\\n                .view(predict_y.shape)\n            if self.cuda:\n                grid_x = grid_x.cuda()\n                grid_y = grid_y.cuda()\n            # 6.2 叠加 grid tensor\n            grid_predict_x = norm_predict_x + grid_x\n            grid_predict_y = norm_predict_y + grid_y\n            # 6.3 归一化 x，y\n            normd_predict_x = grid_predict_x / predict_feature_width\n            normd_predict_y = grid_predict_y / predict_feature_height\n\n            # 7. 解析 wh\n            # 7.1 构造 anchor tensor\n            anchor_width = torch.Tensor(cur_anchors)[:, 0].unsqueeze(dim=1)\n            anchor_height = torch.Tensor(cur_anchors)[:, 1].unsqueeze(dim=1)\n            grid_anchor_width = anchor_width.repeat(batch_size, 1). \\\n                repeat(1, 1, predict_feature_height * predict_feature_width). \\\n                view(predict_w.shape)\n            grid_anchor_height = anchor_height.repeat(batch_size, 1). \\\n                repeat(1, 1, predict_feature_height * predict_feature_width). \\\n                view(predict_h.shape)\n            if self.cuda:\n                grid_anchor_width = grid_anchor_width.cuda()\n                grid_anchor_height = grid_anchor_height.cuda()\n            # 7.2 乘以 anchor tensor\n            anchord_predict_width = torch.exp(predict_w) * grid_anchor_width\n            anchord_predict_height = torch.exp(predict_h) * grid_anchor_height\n            # 6.3 归一化 w, h\n            normd_predict_w = anchord_predict_width / predict_feature_width\n            normd_predict_h = anchord_predict_height / predict_feature_height\n\n            normd_predict_boxes = torch.cat(\n                [\n                    normd_predict_x.unsqueeze(dim=4),\n                    normd_predict_y.unsqueeze(dim=4),\n                    normd_predict_w.unsqueeze(dim=4),\n                    normd_predict_h.unsqueeze(dim=4),\n                ], dim=-1\n            )\n\n            for bs_i, pyramid_boxes in enumerate(pyramid_boxes_list):\n                if self.cuda:\n                    pyramid_boxes = pyramid_boxes.cuda()\n                bs_normd_predict_boxes = normd_predict_boxes[bs_i].view(-1, 4)\n                predict_truth_ious = jaccard(pyramid_boxes[..., :4], bs_normd_predict_boxes)\n                predict_truth_ious_max, _ = torch.max(predict_truth_ious, dim=0)\n                predict_truth_ious_max = predict_truth_ious_max.view(normd_predict_boxes[bs_i].size()[:3])\n                # a = predict_truth_ious_max > self.ignore_threshold\n                # aa = torch.unique(a)\n                # print(aa.size())\n                boxes_noobj_mask[bs_i][predict_truth_ious_max > self.ignore_threshold] = 0\n\n        if self.cuda:\n            return boxes_x.cuda(), \\\n                   boxes_y.cuda(), \\\n                   boxes_w.cuda(), \\\n                   boxes_h.cuda(), \\\n                   boxes_loss_weight_xw.cuda(), \\\n                   boxes_loss_weight_yh.cuda(), \\\n                   boxes_obj_conf.cuda(), \\\n                   boxes_class_conf_list.cuda(), \\\n                   boxes_obj_mask.cuda(), \\\n                   boxes_noobj_mask.cuda()\n\n        return boxes_x, \\\n               boxes_y, \\\n               boxes_w, \\\n               boxes_h, \\\n               boxes_loss_weight_xw, \\\n               boxes_loss_weight_yh, \\\n               boxes_obj_conf, \\\n               boxes_class_conf_list, \\\n               boxes_obj_mask, \\\n               boxes_noobj_mask\n\n    def compute_loss(self, predict_feature: torch.Tensor, decoded_boxes) -> (\n            torch.Tensor, torch.Tensor):\n        \"\"\"\n        逐个特征层计算损失\n        \"\"\"\n        (boxes_x, boxes_y, boxes_w, boxes_h, boxes_loss_weight_xw, boxes_loss_weight_yh, boxes_obj_conf,\n         boxes_class_conf_list, boxes_obj_mask, boxes_noobj_mask) = decoded_boxes\n\n        predict_feature = predict_feature.view(\n            predict_feature.shape[0],\n            3,\n            self.bbox_attrs,\n            predict_feature.shape[2],\n            predict_feature.shape[3],\n        ).permute(0, 1, 3, 4, 2).contiguous()\n\n        predict_x = torch.sigmoid(predict_feature[..., 0])\n        predict_y = torch.sigmoid(predict_feature[..., 1])\n        predict_w = predict_feature[..., 2]\n        predict_h = predict_feature[..., 3]\n        predict_obj_conf = torch.sigmoid(predict_feature[..., 4])\n        predict_class_conf_list = torch.sigmoid(predict_feature[..., 5:])\n\n        boxes_loss_scale = 2 - boxes_loss_weight_xw * boxes_loss_weight_yh\n\n        loss_x = torch.sum(torch.nn.BCELoss()(predict_x, boxes_x) * boxes_loss_scale * boxes_obj_mask)\n        loss_y = torch.sum(torch.nn.BCELoss()(predict_y, boxes_y) * boxes_loss_scale * boxes_obj_mask)\n\n        loss_w = torch.sum(torch.nn.MSELoss()(predict_w, boxes_w) * 0.5 * boxes_loss_scale * boxes_obj_mask)\n        loss_h = torch.sum(torch.nn.MSELoss()(predict_h, boxes_h) * 0.5 * boxes_loss_scale * boxes_obj_mask)\n\n        loss_conf = self.lambda_obj * torch.sum(\n            torch.nn.BCELoss()(predict_obj_conf, boxes_obj_mask) * boxes_obj_mask) + \\\n                    self.lambda_noobj * torch.sum(\n            torch.nn.BCELoss()(predict_obj_conf, boxes_obj_mask) * boxes_noobj_mask)\n\n        loss_class = torch.sum(torch.nn.BCELoss()(predict_class_conf_list[boxes_obj_mask == 1],\n                                                  boxes_class_conf_list[boxes_obj_mask == 1]))\n\n        # print(\"\\n---------------------------------------\")\n        # print(loss_x, loss_y)\n        # print(loss_w, loss_h)\n        # print(loss_conf, loss_class)\n        # print(\"---------------------------------------\\n\")\n\n        loss = loss_x * self.lambda_xy + loss_y * self.lambda_xy + \\\n               loss_w * self.lambda_wh + loss_h * self.lambda_wh + \\\n               loss_conf * self.lambda_conf + loss_class * self.lambda_class\n\n        return loss, torch.sum(boxes_obj_mask)\n\n    def forward(self, predict_feature_list,\n                tensord_boxes_list: List[torch.Tensor]) -> torch.Tensor:\n        boxes_13 = self.decode_pyramid_boxes(tensord_boxes_list, 13, predict_feature_list[0], False)\n        boxes_26 = self.decode_pyramid_boxes(tensord_boxes_list, 26, predict_feature_list[1], False)\n        boxes_52 = self.decode_pyramid_boxes(tensord_boxes_list, 52, predict_feature_list[2], False)\n\n        loss_13, loss_13_num = self.compute_loss(predict_feature_list[0], boxes_13)\n        loss_26, loss_26_num = self.compute_loss(predict_feature_list[1], boxes_26)\n        loss_52, loss_52_num = self.compute_loss(predict_feature_list[2], boxes_52)\n\n        loss_list = []\n\n        if not torch.isnan(loss_13):\n            loss_list.append(loss_13)\n        if not torch.isnan(loss_26):\n            loss_list.append(loss_26)\n        if not torch.isnan(loss_52):\n            loss_list.append(loss_52)\n\n        assert len(loss_list) != 0\n\n        loss = sum(loss_list)\n\n        loss_num = loss_13_num + loss_26_num + loss_52_num\n\n        return loss / loss_num\n", "meta": {"hexsha": "0cf9de7265034e79f2ead5a871c33a55267b1965", "size": 17396, "ext": "py", "lang": "Python", "max_stars_repo_path": "model/yolov3loss.py", "max_stars_repo_name": "lilinxi/210414_CfgYoloV3", "max_stars_repo_head_hexsha": "e6bbb64efa22e7d4c1f583f033370be4b16e548b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "model/yolov3loss.py", "max_issues_repo_name": "lilinxi/210414_CfgYoloV3", "max_issues_repo_head_hexsha": "e6bbb64efa22e7d4c1f583f033370be4b16e548b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model/yolov3loss.py", "max_forks_repo_name": "lilinxi/210414_CfgYoloV3", "max_forks_repo_head_hexsha": "e6bbb64efa22e7d4c1f583f033370be4b16e548b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.4910485934, "max_line_length": 117, "alphanum_fraction": 0.5805932398, "include": true, "reason": "import numpy", "num_tokens": 4809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.17852639884616978}}
{"text": "\"\"\"\npodpy is an implementatin of the pixel optical depth method as described in \nTurner et al. 2014, MNRAS, 445, 794, and Aguirre et al. 2002, ApJ, 576, 1. \nPlease contact the author (Monica Turner) at turnerm@mit.edu if you have \nany questions, comment or issues. \n\"\"\"\n\nimport numpy as np\n\n# Rest wavelength source: Morton 2003, ApJS, 149, 205\n# Oscillator strength source: Morton 2003, ApJS, 149, 205 \n#                                Verner et al 1994, AAPS, 108, 287\n\n# Lyman lines\nlambda_h1 = np.array([1215.6701, 1025.7223, 972.5368, 949.7431, \n       937.8035, 930.7483, 926.2257, 923.1504, \n       920.9631, 919.3514, 918.1294, 917.1806, \n       916.429, 915.824, 915.329, 914.919, \n       914.576, 914.286, 914.039, 913.826, \n       913.641, 913.480, 913.339, 913.215, \n       913.104, 913.006, 912.918, 912.839, \n       912.768, 912.703, 912.645]) \nf_h1 = np.array([0.416400, 0.079120, 0.029000, 0.013940, \n       0.007799, 0.004814, 0.003183, 0.002216, \n       0.001605, 0.00120,  0.000921, 7.226e-4,\n       0.000577, 0.000469, 0.000386, 0.000321, \n       0.000270, 0.000230, 0.000197, 0.000170, \n       0.000148, 0.000129, 0.000114, 0.000101, \n       0.000089, 0.000080, 0.000071, 0.000064, \n       0.000058, 0.000053, 0.000048]) \ng_h1 = f_h1 * lambda_h1\n\nlambda_h1_limit = 911.8\n\n# Metals\n# OVI\nlambda_o6 = np.array([1031.927, 1037.616])\nf_o6 = np.array([0.132900, 0.066090])\ng_o6 = f_o6 * lambda_o6\n# NV\nlambda_n5 = np.array([1238.821, 1242.804])\nf_n5 = np.array([0.157000, 0.078230])\ng_n5 = f_n5 * lambda_n5\n# CIV\nlambda_c4 = np.array([1548.195, 1550.770])\nf_c4 = np.array([0.190800, 0.095220])\ng_c4 = f_c4 * lambda_c4\n# CIII\nlambda_c3 =  np.array([977.020])\nf_c3 = np.array([0.7620])\t\ng_c3 = f_c3 * lambda_c3\n# CII\nlambda_c2 = np.array([1334.5323, 1036.3367]) \nf_c2 = np.array([ 0.1278, 0.1231])  \ng_c2 = f_c2 * lambda_c2\n# SiIV\nlambda_si4 = np.array([1393.755, 1402.770])\nf_si4 = np.array([0.5140, 0.2553])\ng_si4 = f_si4 * lambda_si4\n# SiIII\nlambda_si3 = np.array([1206.500])\t\nf_si3 = np.array([1.669000])\ng_si3 = f_si3 * lambda_si3\n# SiII\nlambda_si2 = np.array([1260.4221, 1193.2897, 1190.4158, 989.8731,\n\t1526.7066, 1304.3702, 1020.6989])\nf_si2 = ([1.007000, 0.499100, 0.250200, 0.133000, \n\t0.11600, 0.09400, 0.028280]) \ng_si2 = f_si2 * lambda_si2\n# MgII\nlambda_mg2 = np.array([2796.352, 2803.531])\nf_mg2 = np.array([0.6123, 0.3054])\ng_mg2 = f_mg2 * lambda_mg2\n# OI\nlambda_o1 = np.array([1302.1685, 988.7734])\nf_o1 = np.array([0.048870, 0.043180])\ng_o1 = f_o1 * lambda_o1\n# Fe2\nlambda_fe2 = np.array([1144.9379, 1608.45085, 1063.1764, 1096.8769,\n       1260.533, 1121.9748, 1081.8748, 1143.2260, 1125.4477]) \nf_fe2 = np.array([0.083, 0.0577, 0.0547, 0.032700, \n       0.024000, 0.0290, 0.012600, 0.0192, 0.0156])\ng_fe2 = f_fe2 * lambda_fe2\n\n\n# Constants \nc =  299792.458 # speed of light in km/s \n\n\n# Confidence intervals \n\nfrom scipy.stats import norm \n\none_sigma_above = 100. * norm.cdf(1)\ntwo_sigma_above = 100. * norm.cdf(2)\nthree_sigma_above = 100. * norm.cdf(3)\n\none_sigma_below = 100. - one_sigma_above\ntwo_sigma_below = 100. - two_sigma_above\nthree_sigma_below = 100. - three_sigma_above\n\n\n\n\n", "meta": {"hexsha": "5c7ac11cf6dcf131f1b1c6956eec505273d87f53", "size": 3119, "ext": "py", "lang": "Python", "max_stars_repo_path": "podpy/universe.py", "max_stars_repo_name": "turnerm/podpy", "max_stars_repo_head_hexsha": "f6cb93cf4d30a7927fef9e282fe76555d4957488", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "podpy/universe.py", "max_issues_repo_name": "turnerm/podpy", "max_issues_repo_head_hexsha": "f6cb93cf4d30a7927fef9e282fe76555d4957488", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-06-07T18:42:31.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-15T15:35:36.000Z", "max_forks_repo_path": "podpy/universe.py", "max_forks_repo_name": "turnerm/podpy", "max_forks_repo_head_hexsha": "f6cb93cf4d30a7927fef9e282fe76555d4957488", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7047619048, "max_line_length": 76, "alphanum_fraction": 0.6579031741, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3242353859211693, "lm_q1q2_score": 0.178526391655357}}
{"text": "\n\"\"\"\nThis is a general script for doing the cross-correlations in my companion search.\nIt is called by several smaller scripts in each of the instrument-specific repositories\n\"\"\"\n\nfrom __future__ import print_function, division\n\nimport numpy as np\n\nfrom kglib.utils import FittingUtilities, DataStructures\nfrom kglib.cross_correlation import Correlate\nfrom kglib.utils import HelperFunctions\nfrom kglib.stellar_models import StellarModel, Broaden\n\n\ntry:\n    from pyraf import iraf\n    pyraf_import = True\nexcept ImportError:\n    pyraf_import = False\nfrom astropy.io import fits\nfrom astropy.time import Time\nimport subprocess\nfrom collections import defaultdict\nfrom kglib.utils import StarData\nfrom kglib.spectral_type import SpectralTypeRelations\nfrom astropy import units as u\nfrom scipy.interpolate import InterpolatedUnivariateSpline as spline\nimport re\nimport sys\nimport os\nimport logging\nimport matplotlib.pyplot as plt\nimport h5py\nimport multiprocessing\nimport functools\n\nif pyraf_import:\n    iraf.noao()\n    iraf.noao.rv()\n\n\ndef convert(coord, delim=\":\"):\n    \"\"\"\n    Convert a hex RA/DEC value to float.\n    \"\"\"\n    segments = coord.split(delim)\n    s = -1.0 if \"-\" in segments[0] else 1.0\n    return s * (abs(float(segments[0])) + float(segments[1]) / 60.0 + float(segments[2]) / 3600.0)\n\n\nif pyraf_import:\n    def HelCorr_IRAF(header, observatory=\"CTIO\", debug=False):\n        \"\"\"\n        Get the heliocentric correction for an observation\n\n        Parameters:\n        ===========\n        - header:       astropy.io.fits header, or a simple dictionary\n                        The fits header for the file you want to correct.\n                        It should have at least the following fields/keys:\n                        jd, ut, ra, and dec\n\n        - observatory:  string\n                        The name of the observatory, as something that IRAF would know.\n\n        - debug:        boolean\n                        Print the output of the pyraf call to screen?\n\n        Returns:\n        ========\n        The barycentric correction to apply to the data.\n        \"\"\"\n        jd = header['jd']\n        t = Time(jd, format='jd', scale='utc')\n        dt = t.datetime\n        output = iraf.noao.rv.rvcorrect(epoch='INDEF',\n                                              epoch_vsun='INDEF',\n                                              observatory=observatory,\n                                              year=dt.year,\n                                              month=dt.month,\n                                              day=dt.day,\n                                              ut=header['ut'],\n                                              ra=header['ra'],\n                                              dec=header['dec'],\n                                              files=\"\",\n                                              images=\"\",\n                                              input='no',\n                                              Stdout=1)\n        vbary = float(output[-1].split()[2])\n        if debug:\n            for line in output:\n                print(line)\n        return vbary\nelse:\n    def HelCorr_IRAF(header, observatory=\"CTIO\", debug=False):\n        print(\"pyraf is not installed! Trying to use the idl version!\")\n        return 1e-3 * HelCorr(header, observatory=observatory, debug=debug)\n\n\ndef HelCorr(header, observatory=\"CTIO\", idlpath=\"/Applications/exelis/idl83/bin/idl\", debug=False):\n    \"\"\"\n    Similar to HelCorr_IRAF, but attempts to use an IDL library.\n    See HelCorr_IRAF docstring for details.\n    \"\"\"\n    ra = 15.0 * convert(header['RA'])\n    dec = convert(header['DEC'])\n    jd = float(header['jd'])\n\n    cmd_list = [idlpath,\n                '-e',\n                (\"print, barycorr({:.8f}, {:.8f}, {:.8f}, 0,\"\n                 \" obsname='{}')\".format(jd, ra, dec, observatory)),\n    ]\n    if debug:\n        print(\"RA: \", ra)\n        print(\"DEC: \", dec)\n        print(\"JD: \", jd)\n    output = subprocess.check_output(cmd_list).split(\"\\n\")\n    if debug:\n        for line in output:\n            print(line)\n    return float(output[-2])\n\n\nSMOOTH_FACTOR = 0.25\n\n\ndef Process_Data_parallel(orders, badregions=[], interp_regions=[], extensions=True,\n                 trimsize=1, vsini=None, logspacing=False, oversample=1.0, reject_outliers=True, cores=4):\n\n    \"\"\"\n    Use multiprocessing module to parallelize the data processing. See Process_Data_serial for details.\n    \"\"\"\n    # Set up the multiprocessing stuff\n    num_orders = len(orders) / cores + 1\n    mp_args = [orders[num_orders*i:num_orders*(i+1)] for i in range(cores)]\n    p = multiprocessing.Pool(cores)\n\n    # Call Process_Data\n    fcn = functools.partial(Process_Data_serial, badregions=badregions, interp_regions=interp_regions,\n                            extensions=extensions, trimsize=trimsize, vsini=vsini, logspacing=logspacing,\n                            oversample=oversample, reject_outliers=reject_outliers)\n    tmp = p.map(fcn, mp_args)\n\n    # Sort the output\n    mp_out = []\n    for t in tmp:\n        mp_out.extend(t)\n\n    return sorted(mp_out, key=lambda o: o.x[0])\n\n\ndef Process_Data(*args, **kwargs):\n    return Process_Data_serial(*args, **kwargs)\n\n\ndef Process_Data_serial(input_data, badregions=[], interp_regions=[], extensions=True,\n                 trimsize=1, vsini=None, logspacing=False, oversample=1.0, reject_outliers=True):\n    \"\"\"\n    Prepare data for cross-correlation. This involves cutting out bad part of the spectrum\n    and resampling to constant log-wavelength spacing.\n\n    Parameters:\n    ===========\n    - input_data:         string, or list of kglib.utils.DataStructures.xypoint instances\n                          If a string, should give the filename of the data\n                          Otherwise, it should give the spectrum in each echelle order\n\n    - badregions:         list of lists, where each sub-list has size 2\n                          Regions to exclude (contains strong telluric or stellar line residuals).\n                          Each sublist should give the start and end wavelength to exclude\n\n    - interp_regions:     list of lists, where each sub-list has size 2\n                          Regions to interpolate over.\n                          Each sublist should give the start and end wavelength to exclude\n\n    - extensions:         boolean\n                          Is the fits file is separated into extensions?\n\n    - trimsize:           integer\n                          The number of pixels to exclude from both ends of every order\n                          (where it is very noisy)\n\n    - vsini:              float\n                          The primary star vsini, in km/s. If given subtract an estimate\n                          of the primary star model obtained by\n                          denoising and smoothing with a kernel size set by the vsini.\n\n    - logspacing:         boolean\n                          If true, interpolate each order into a constant log-spacing.\n\n    - oversample:         float\n                          Oversampling factor to use if resampling to log-spacing.\n                          The final number of pixels is oversample times the initial\n                          number.\n\n    - reject_outliers:    boolean\n                          Should we search for and reject outliers from the processed data?\n                          Useful when looking for companions with large flux ratios, but\n                          not otherwise.\n\n    Returns:\n    ========\n    A list of kglib.utils.DataStructures.xypoint instances with the processed data.\n    \"\"\"\n    if isinstance(input_data, list) and all([isinstance(f, DataStructures.xypoint) for f in input_data]):\n        orders = input_data\n    else:\n        if extensions:\n            orders = HelperFunctions.ReadExtensionFits(input_data)\n\n        else:\n            orders = HelperFunctions.ReadFits(input_data, errors=2)\n\n    numorders = len(orders)\n    for i, order in enumerate(orders[::-1]):\n        # Trim data, and make sure the wavelength spacing is constant\n        if trimsize > 0:\n            order = order[trimsize:-trimsize]\n\n        # Smooth the data\n        if vsini is not None:\n            # make sure the x-spacing is linear\n            xgrid = np.linspace(order.x[0], order.x[-1], order.size())\n            order = FittingUtilities.RebinData(order, xgrid)\n\n            smoothed = HelperFunctions.astropy_smooth(order, vel=SMOOTH_FACTOR * vsini, linearize=True)\n            order.y += order.cont.mean() - smoothed\n            order.cont = np.ones(order.size()) * order.cont.mean()\n\n        # Remove bad regions from the data\n        for region in badregions:\n            left = np.searchsorted(order.x, region[0])\n            right = np.searchsorted(order.x, region[1])\n            if left > 0 and right < order.size():\n                print(\"Warning! Bad region covers the middle of order %i\" % i)\n                print(\"Removing full order!\")\n                left = 0\n                right = order.size()\n            order.x = np.delete(order.x, np.arange(left, right))\n            order.y = np.delete(order.y, np.arange(left, right))\n            order.cont = np.delete(order.cont, np.arange(left, right))\n            order.err = np.delete(order.err, np.arange(left, right))\n\n        # Interpolate over interp_regions:\n        for region in interp_regions:\n            left = np.searchsorted(order.x, region[0])\n            right = np.searchsorted(order.x, region[1])\n            order.y[left:right] = order.cont[left:right]\n\n\n        # Remove whole order if it is too small\n        remove = False\n        if order.x.size <= 1:\n            remove = True\n        else:\n            velrange = 3e5 * (np.median(order.x) - order.x[0]) / np.median(order.x)\n            if velrange <= 1050.0:\n                remove = True\n        if remove:\n            print(\"Removing order %i\" % (numorders - 1 - i))\n            orders.pop(numorders - 1 - i)\n        else:\n            if reject_outliers:\n                # Find outliers from e.g. bad telluric line or stellar spectrum removal.\n                order.cont = FittingUtilities.Continuum(order.x, order.y, lowreject=3, highreject=3)\n                outliers = HelperFunctions.FindOutliers(order, expand=10, numsiglow=5, numsighigh=5)\n                # plt.plot(order.x, order.y / order.cont, 'k-')\n                if len(outliers) > 0:\n                    # plt.plot(order.x[outliers], (order.y / order.cont)[outliers], 'r-')\n                    order.y[outliers] = order.cont[outliers]\n                    order.cont = FittingUtilities.Continuum(order.x, order.y, lowreject=3, highreject=3)\n                    order.y[outliers] = order.cont[outliers]\n\n            # Save this order\n            orders[numorders - 1 - i] = order.copy()\n\n    # Rebin the data to a constant log-spacing (if requested)\n    if logspacing:\n        for i, order in enumerate(orders):\n            start = np.log(order.x[0])\n            end = np.log(order.x[-1])\n            neworder = order.copy()\n            neworder.x = np.logspace(start, end, order.size() * oversample, base=np.e)\n            neworder = FittingUtilities.RebinData(order, neworder.x)\n            orders[i] = neworder\n\n    return orders\n\n\ndef process_model(model, data, vsini_model=None, resolution=None, vsini_primary=None,\n                  maxvel=1000.0, debug=False, logspace=True):\n    \"\"\"\n    Process a stellar model to prepare it for cross correlation\n\n    Parameters:\n    - model:          string, or kglib.utils.DataStructures.xypoint instance\n                      If a string, should give the path to an ascii file with the model\n                      Otherwise, should hold the model data\n\n    - data:           list of kglib.utils.DataStructures.xypoint instances\n                      The already-processed data.\n\n    - vsini_model:    float\n                      The rotational velocity to apply to the model spectrum\n\n    - vsini_primary:  float\n                      The rotational velocity of the primary star\n\n    - resolution:     float\n                      The detector resolution in $\\lambda / \\Delta \\lambda$\n\n    - maxvel:         float\n                      The maximum velocity to include in the eventual CCF.\n                      This is used to trim the data appropriately for each echelle order.\n\n    - debug:          boolean\n                      Print some extra stuff?\n\n    - logspace:       boolean\n                      Rebin the model to constant log-spacing?\n\n    Returns:\n    ========\n    A list of kglib.utils.DataStructures.xypoint instances with the processed model.\n    \"\"\"\n    # Read in the model if necessary\n    if isinstance(model, str):\n        if debug:\n            print(\"Reading in the input model from %s\" % model)\n        x, y = np.loadtxt(model, usecols=(0, 1), unpack=True)\n        x = x * u.angstrom.to(u.nm)\n        y = 10 ** y\n        left = np.searchsorted(x, data[0].x[0] - 10)\n        right = np.searchsorted(x, data[-1].x[-1] + 10)\n        model = DataStructures.xypoint(x=x[left:right], y=y[left:right])\n    elif not isinstance(model, DataStructures.xypoint):\n        raise TypeError(\n            \"Input model is of an unknown type! Must be a DataStructures.xypoint or a string with the filename.\")\n\n\n    # Linearize the x-axis of the model (in log-spacing)\n    if logspace:\n        if debug:\n            print(\"Linearizing model\")\n        xgrid = np.logspace(np.log10(model.x[0]), np.log10(model.x[-1]), model.size())\n        model = FittingUtilities.RebinData(model, xgrid)\n\n    # Broaden\n    if vsini_model is not None and vsini_model > 1.0 * u.km.to(u.cm):\n        if debug:\n            print(\"Rotationally broadening model to vsini = %g km/s\" % (vsini_model * u.cm.to(u.km)))\n        model = Broaden.RotBroad(model, vsini_model, linear=True)\n\n\n    # Reduce resolution\n    if resolution is not None and 5000 < resolution < 500000:\n        if debug:\n            print(\"Convolving to the detector resolution of %g\" % resolution)\n        model = FittingUtilities.ReduceResolutionFFT(model, resolution)\n\n    # Divide by the same smoothing kernel as we used for the data\n    if vsini_primary is not None:\n        smoothed = HelperFunctions.astropy_smooth(model, vel=SMOOTH_FACTOR * vsini_primary, linearize=False)\n        model.y += model.cont.mean() - smoothed\n        model.cont = np.ones(model.size()) * model.cont.mean()\n\n\n    # Rebin subsets of the model to the same spacing as the data\n    model_orders = []\n    model_fcn = spline(model.x, model.y)\n    if debug:\n        model.output(\"Test_model.dat\")\n    for i, order in enumerate(data):\n        if debug:\n            sys.stdout.write(\"\\rGenerating model subset for order %i in the input data\" % (i + 1))\n            sys.stdout.flush()\n        # Find how much to extend the model so that we can get maxvel range.\n        dlambda = order.x[order.size() / 2] * maxvel * 1.5 / 3e5\n        left = np.searchsorted(model.x, order.x[0] - dlambda)\n        right = np.searchsorted(model.x, order.x[-1] + dlambda)\n        right = min(right, model.size() - 2)\n\n        # Figure out the log-spacing of the data\n        logspacing = np.log(order.x[1] / order.x[0])\n\n        # Finally, space the model segment with the same log-spacing\n        start = np.log(model.x[left])\n        end = np.log(model.x[right])\n        xgrid = np.exp(np.arange(start, end + logspacing, logspacing))\n\n        segment = DataStructures.xypoint(x=xgrid, y=model_fcn(xgrid))\n        segment.cont = FittingUtilities.Continuum(segment.x, segment.y, lowreject=1.5, highreject=5, fitorder=2)\n        model_orders.append(segment)\n\n    print(\"\\n\")\n    return model_orders\n\n\ndef slow_companion_search(*args, **kwargs):\n    \"\"\"\n    Kept for legacy support. See companion_search for details\n    \"\"\"\n    logging.warn('Use companion_search() instead!')\n    return companion_search(*args, **kwargs)\n\n\ndef companion_search(fileList, primary_vsini,\n                     badregions=[], interp_regions=[],\n                     extensions=True,\n                     resolution=None,\n                     trimsize=1,\n                     reject_outliers=True,\n                     vsini_values=(10, 20, 30, 40),\n                     Tvalues=range(3000, 6900, 100),\n                     metal_values=(-0.5, 0.0, +0.5),\n                     logg_values=(4.5,),\n                     hdf5_file=StellarModel.HDF5_FILE,\n                     vbary_correct=True,\n                     observatory=\"CTIO\",\n                     addmode=\"ML\",\n                     output_mode='hdf5',\n                     output_file='CCF.hdf5',\n                     obstype='real',\n                     min_x=None,\n                     max_x=None,\n                     debug=False,\n                     makeplots=False):\n    \"\"\"\n    This function runs a companion search over a whole grid of model spectra\n\n    Parameters:\n    ===========\n    - fileList:               list of strings\n                              The list of fits data files. Each file is expected to\n                              have several echelle orders, each in their own fits\n                              extension. Each order is represented as a binary table\n                              with columns 'wavelength', 'flux', 'continuum', and 'error'\n\n    - primary_vsini:          list of floats\n                              A list of the same length as fileList,\n                              which contains the vsini for each star (in km/s)\n\n    - badregions:             list of lists, where each sub-list has size 2\n                              Regions to exclude (contains strong telluric or stellar line residuals).\n                              Each sublist should give the start and end wavelength to exclude\n\n    - interp_regions:         list of lists, where each sub-list has size 2\n                              Regions to interpolate over.\n                              Each sublist should give the start and end wavelength to exclude\n\n    - trimsize:               integer\n                              The number of pixels to cut from both sides of each order.\n                              This is because the  order edges are usually pretty noisy.\n\n    - reject_outliers:        boolean\n                              Whether or not to detect and smooth over outliers in the data.\n\n    - vsini_values:           Any iterable\n                              A list of vsini values (in km/s) to apply to each\n                              model spectrum before correlation.\n\n    - Tvalues:                Any iterable\n                              A list of model temperatures (in K) to correlate the data against.\n\n    - metal_values:           Any iterable\n                              A list of [Fe/H] values to correlate the model against\n\n    - logg_values:           Any iterable\n                             A list of log(g) values (in cgs units) to correlate the model against\n\n    - modeldir:              string\n                             The path to a directory with several stellar models.\n                             This is no longer used by default!\n\n    - hdf5_file:             string\n                             The path to the hdf5 file containing the pre-broadened model grid.\n\n    - vbary_correct:         boolean\n                             Correct for the heliocentric motion of the Earth around the Sun?\n\n    - observatory:           string\n                             The name of the observatory, in a way that IRAF's rvcorrect will understand.\n                             Only needed if vbary_correct = True\n\n    - addmode:               string\n                             The way to add the CCFs for each order. Options are:\n                                 1: 'simple': Do a simple average\n                                 2: 'weighted': Do a weighted average: $C = \\sum_i{w_i C_i^2}$\n                                     where $w_i$ is the line depth of the each pixel\n                                 3: 'simple-weighted': Same as weighted, but without squaring the CCFs:\n                                     $C = \\sum_i{w_i C_i}$\n                                 4: 'T-weighted': Do a weighted average: $C = \\sum_i{w_i C_i}$\n                                    where $w_i$ is how fast each pixel changes with temperature\n                                 5: 'dc': $C = \\sum_i{C_i^2}$  (basically, weighting by the CCF itself)\n                                 6: 'ml': The maximum likelihood estimate. See Zucker 2003, MNRAS, 342, 1291\n                                 7: 'all': does simple, dc, and ml all at once.\n\n    - output_mode:           string\n                             How to output. Valid options are:\n                                 1: text, which is just ascii data with a filename convention.\n                                 2: hdf5, which ouputs a single hdf5 file with all the metadata\n                                    necessary to classify the output. This is the default.\n\n    - output_file:           string\n                             An HDF5 file to output to. Only used if output_mode = 'hdf5'.\n                             Note: The file with be placed in a directory called 'Cross_correlations'\n\n    - obstype:               string\n                             Is this a synthetic binary star or real observation? (default is real).\n                             The HDF5 output is a bit different if it is a synthetic binary star observation.\n\n    - min_x:                 float\n                             The minimum wavelength to use in the model.\n                             If not given, the whole model will be used\n\n    - max_x:                 float\n                             The maximum wavelength to use in the model.\n                             If not given, the whole model will be used\n\n    - debug:                 boolean\n                             Flag to print a bunch of information to screen,\n                             and save some intermediate data files\n\n    - makeplots:             boolean\n                             A 'higher level' of debug. Will make a plot of the\n                             data and model orders for each model.\n    \"\"\"\n\n    # Make sure the temperature, metal, and logg are all at least 1d arrays.\n    Tvalues = np.atleast_1d(Tvalues)\n    metal_values = np.atleast_1d(metal_values)\n    logg_values = np.atleast_1d(logg_values)    \n\n    model_list = StellarModel.GetModelList(type='hdf5',\n                                           hdf5_file=hdf5_file,\n                                           temperature=Tvalues,\n                                           metal=metal_values,\n                                           logg=logg_values)\n    if addmode.lower() == 't-weighted':\n        modeldict, processed, sensitivity = StellarModel.MakeModelDicts(model_list, type='hdf5', hdf5_file=hdf5_file,\n                                                       vsini_values=vsini_values, vac2air=True, logspace=True,\n                                                       get_T_sens=True)\n    else:\n        modeldict, processed = StellarModel.MakeModelDicts(model_list, type='hdf5', hdf5_file=hdf5_file,\n                                                       vsini_values=vsini_values, vac2air=True, logspace=True)\n        sensitivity = None\n\n    get_weights = True if addmode.lower() == \"weighted\" or addmode.lower() == 'simple-weighted' else False\n    orderweights = None\n\n    MS = SpectralTypeRelations.MainSequence()\n\n    # Do the cross-correlation\n    datadict = defaultdict(list)\n    temperature_dict = defaultdict(float)\n    vbary_dict = defaultdict(float)\n    alpha = 0.0\n    for temp in sorted(modeldict.keys()):\n        for gravity in sorted(modeldict[temp].keys()):\n            for metallicity in sorted(modeldict[temp][gravity].keys()):\n                for vsini_sec in vsini_values:\n                    if debug:\n                        logging.info('T: {}, logg: {}, [Fe/H]: {}, vsini: {}'.format(temp, gravity,\n                                                                                     metallicity, vsini_sec))\n                    # broaden the model\n                    model = modeldict[temp][gravity][metallicity][alpha][vsini_sec].copy()\n                    l_idx = 0 if min_x is None else np.searchsorted(model.x, min_x)\n                    r_idx = model.size() if max_x is None else np.searchsorted(model.x, max_x)+1\n                    model = Broaden.RotBroad(model[l_idx:r_idx], vsini_sec * u.km.to(u.cm), linear=True)\n                    if resolution is not None:\n                        model = FittingUtilities.ReduceResolutionFFT(model, resolution)\n\n                    # Interpolate the temperature weights, if addmode='T-weighted'\n                    if addmode.lower() == 't-weighted':\n                        x = modeldict[temp][gravity][metallicity][alpha][vsini_sec].x\n                        y = sensitivity[temp][gravity][metallicity][alpha][vsini_sec]\n                        temperature_weights = spline(x, y)\n\n                    for i, (fname, vsini_prim) in enumerate(zip(fileList, primary_vsini)):\n                        if vbary_correct:\n                            if fname in vbary_dict:\n                                vbary = vbary_dict[fname]\n                            else:\n                                vbary = HelCorr_IRAF(fits.getheader(fname), observatory=observatory)\n                                vbary_dict[fname] = vbary\n                        process_data = False if fname in datadict else True\n                        if process_data:\n                            orders = Process_Data(fname, badregions, interp_regions=interp_regions, logspacing=True,\n                                                  extensions=extensions, trimsize=trimsize, vsini=vsini_prim,\n                                                  reject_outliers=reject_outliers)\n                            header = fits.getheader(fname)\n                            try:\n                                spt = StarData.GetData(header['object']).spectype\n                                if spt == 'Unknown':\n                                    temperature_dict[fname] = np.nan  # Unknown\n                                    logging.warning('Spectral type retrieval from simbad failed! Entering NaN for primary temperature!')\n                                else:\n                                    match = re.search('[0-9]', spt)\n                                    if match is None:\n                                        spt = spt[0] + \"5\"\n                                    else:\n                                        spt = spt[:match.start() + 1]\n                                    temperature_dict[fname] = MS.Interpolate(MS.Temperature, spt)\n                            except AttributeError:\n                                temperature_dict[fname] = np.nan  # Unknown\n                                logging.warning('Spectral type retrieval from simbad failed! Entering NaN for primary temperature!')\n                            datadict[fname] = orders\n                        else:\n                            orders = datadict[fname]\n\n                        # Now, process the model\n                        model_orders = process_model(model.copy(), orders, vsini_primary=vsini_prim, maxvel=1000.0,\n                                                     debug=debug, oversample=1, logspace=False)\n\n                        # Get order weights if addmode='T-weighted'\n                        if addmode.lower() == 't-weighted':\n                            get_weights = False\n                            orderweights = [np.sum(temperature_weights(o.x)) for o in orders]\n                            addmode = 'simple-weighted'\n\n                        if debug and makeplots:\n                            fig = plt.figure('T={}   vsini={}'.format(temp, vsini_sec))\n                            for o, m in zip(orders, model_orders):\n                                d_scale = np.std(o.y/o.cont)\n                                m_scale = np.std(m.y/m.cont)\n                                plt.plot(o.x, (o.y/o.cont-1.0)/d_scale, 'k-', alpha=0.4)\n                                plt.plot(m.x, (m.y/m.cont-1.0)/m_scale, 'r-', alpha=0.6)\n                            plt.show(block=False)\n\n                        # Make sure the output directory exists\n                        output_dir = \"Cross_correlations/\"\n                        outfilebase = fname.split(\".fits\")[0]\n                        if \"/\" in fname:\n                            dirs = fname.split(\"/\")\n                            outfilebase = dirs[-1].split(\".fits\")[0]\n                            if obstype.lower() == 'synthetic':\n                                output_dir = \"\"\n                                for directory in dirs[:-1]:\n                                    output_dir = output_dir + directory + \"/\"\n                                output_dir = output_dir + \"Cross_correlations/\"\n                        HelperFunctions.ensure_dir(output_dir)\n\n                        # Save the model and data orders, if debug=True\n                        if debug:\n                            # Save the individual spectral inputs and CCF orders (unweighted)\n                            output_dir2 = output_dir.replace(\"Cross_correlations\", \"CCF_inputs\")\n                            HelperFunctions.ensure_dir(output_dir2)\n                            HelperFunctions.ensure_dir(\"%sCross_correlations/\" % (output_dir2))\n\n                            for i, (o, m) in enumerate(zip(orders, model_orders)):\n                                outfilename = \"{0:s}{1:s}.{2:.0f}kps_{3:.1f}K{4:+.1f}{5:+.1f}.data.order{6:d}\".format(\n                                    output_dir2,\n                                    outfilebase, vsini_sec,\n                                    temp, gravity,\n                                    metallicity, i + 1)\n                                o.output(outfilename)\n                                outfilename = \"{0:s}{1:s}.{2:.0f}kps_{3:.1f}K{4:+.1f}{5:+.1f}.model.order{6:d}\".format(\n                                    output_dir2,\n                                    outfilebase, vsini_sec,\n                                    temp, gravity,\n                                    metallicity, i + 1)\n                                m.output(outfilename)\n\n                        corr = Correlate.Correlate(orders, model_orders, addmode=addmode, outputdir=output_dir,\n                                                   get_weights=get_weights, prim_teff=temperature_dict[fname],\n                                                   orderweights=orderweights, debug=debug)\n                        if debug:\n                            corr, ccf_orders = corr\n\n                        # Barycentric correction\n                        if vbary_correct:\n                            corr.x += vbary\n\n                        # Output the ccf\n                        if obstype.lower() == 'synthetic':\n                            pars = {'outdir': output_dir, 'outbase': outfilebase, 'addmode': addmode,\n                                    'vsini_prim': vsini_prim, 'vsini': vsini_sec,\n                                    'T': temp, 'logg': gravity, '[Fe/H]': metallicity}\n                            save_synthetic_ccf(corr, params=pars, mode=output_mode)\n                        else:\n                            pars = {'outdir': output_dir, 'fname': fname, 'addmode': addmode,\n                                    'vsini_prim': vsini_prim, 'vsini': vsini_sec,\n                                    'T': temp, 'logg': gravity, '[Fe/H]': metallicity}\n                            pars['vbary'] = vbary if vbary_correct else np.nan\n                            save_ccf(corr, params=pars, mode=output_mode, hdf_outfilename=output_file)\n\n                        # Save the individual orders, if debug=True\n                        if debug:\n                            for i, c in enumerate(ccf_orders):\n                                print(\"Saving CCF inputs for order {}\".format(i + 1))\n                                outfilename = \"{0:s}Cross_correlations/{1:s}.{2:.0f}kps_{3:.1f}K{4:+.1f}{5:+.1f}.order{6:d}\".format(\n                                    output_dir2,\n                                    outfilebase, vsini_sec,\n                                    temp, gravity,\n                                    metallicity, i + 1)\n                                c.output(outfilename)\n\n\n\n                    # Delete the model. We don't need it anymore and it just takes up ram.\n                    modeldict[temp][gravity][metallicity][alpha][vsini_sec] = []\n\n    return\n\n\ndef save_synthetic_ccf(corr, params, mode='text', hdf_outfilename='CCF.hdf5'):\n    \"\"\"\n    Save the cross-correlation function for a synthetic binary star observation.\n\n    Parameters\n    ===========\n    - corr:      kglib.utils.DataStructurs.xypoint object\n                 Holds the cross-correlation function and associated velocities\n\n    - params:    dictionary\n                 A dictionary describing the metadata to include\n\n    - mode:      string\n                 See docstring for companion_search, param output_mode\n\n    \"\"\"\n    if mode.lower() == 'text':\n        outfilename = \"{0:s}{1:s}_{2:s}-method.{3:.0f}kps_{4:.1f}K{5:+.1f}{6:+.1f}\".format(params['outdir'],\n                                                                                           params['outbase'],\n                                                                                           params['addmode'],\n                                                                                           params['vsini'],\n                                                                                           params['T'],\n                                                                                           params['logg'],\n                                                                                           params['[Fe/H]'])\n        print('Outputting to {}'.format(outfilename))\n        np.savetxt(outfilename, np.transpose((corr.x, corr.y)), fmt=\"%.10g\")\n\n    elif mode.lower() == 'hdf5':\n        # Get the hdf5 file\n        hdf5_file = os.path.join(params['outdir'], hdf_outfilename)\n        print('Saving CCF to {}'.format(hdf5_file))\n        f = h5py.File(hdf5_file, 'a')\n\n        # Star combination\n        segments = params['outbase'].split('_bright')[0].replace('_', ' ')  # .split('_')[:-1]\n        star1 = segments.split('+')[0]\n        star2 = segments.split('+')[1]\n\n        # Make the heirarchy if the file does not have it\n        p = f[star1] if star1 in f.keys() else f.create_group(star1)\n        s = p[star2] if star2 in p.keys() else p.create_group(star2)\n        g = s[params['addmode']] if params['addmode'] in s.keys() else s.create_group(params['addmode'])\n\n        # Add a new dataset. The name doesn't matter\n        current_datasets = g.keys()\n        if len(current_datasets) == 0:\n            ds = g.create_dataset('ds1', data=corr.y)\n        else:\n            ds_num = max(int(d[2:]) for d in current_datasets) + 1\n            ds = g.create_dataset('ds{}'.format(ds_num), data=corr.y)\n\n        # Add attributes to the dataset\n        print(star1, star2)\n        print(params)\n        ds.attrs['vsini'] = params['vsini']\n        ds.attrs['T'] = params['T']\n        ds.attrs['logg'] = params['logg']\n        ds.attrs['[Fe/H]'] = params['[Fe/H]']\n        ds.attrs['velocity'] = corr.x\n\n        p.attrs['vsini'] = params['vsini_prim']\n\n        f.flush()\n        f.close()\n\n    else:\n        raise ValueError('output mode ({}) not supported!'.format(mode))\n\n\ndef save_ccf(corr, params, mode='hdf5', update=False, hdf_outfilename='CCF.hdf5'):\n    \"\"\"\n    Save the cross-correlation function.\n\n    Parameters\n    ===========\n    - corr:      kglib.utils.DataStructurs.xypoint object\n                 Holds the cross-correlation function and associated velocities\n\n    - params:    dictionary\n                 A dictionary describing the metadata to include\n\n    - mode:      string\n                 See docstring for companion_search, param output_mode\n\n    - update:    boolean\n                 If mode = 'hdf5' and a dataset with the same parameters already\n                 exists, should we overwrite it? If not, create a new dataset\n                 with slightly different name.\n\n    \"\"\"\n\n    # Loop through the add-modes if addmode=all\n    if params['addmode'].lower() == 'all':\n        for am in corr.keys():\n            p = dict(**params)\n            p['addmode'] = am\n            save_ccf(corr[am], p, mode=mode, update=update, hdf_outfilename=hdf_outfilename)\n        return\n\n    if mode.lower() == 'text':\n        params['outbase'] = params['fname'].split('/')[-1].split('.fits')[0]\n        save_synthetic_ccf(corr, params, mode=mode, update=update)\n\n    elif mode.lower() == 'hdf5':\n        # Get the hdf5 file\n        hdf5_file = os.path.join(params['outdir'], hdf_outfilename)\n        print('Saving CCF to {}'.format(hdf5_file))\n        f = h5py.File(hdf5_file, 'a')\n\n        # Star name and date\n        header = fits.getheader(params['fname'])\n        star = header['OBJECT']\n        date = header['DATE-OBS'].split('T')[0]\n\n        print(star, date)\n        print(params)\n        if star in f.keys():\n            s = f[star]\n        else:\n            star_data = StarData.GetData(star)\n            s = f.create_group(star)\n            s.attrs['vsini'] = -1 if params['vsini_prim'] is None else params['vsini_prim']\n            s.attrs['RA'] = star_data.ra\n            s.attrs['DEC'] = star_data.dec\n            s.attrs['SpT'] = star_data.spectype\n\n        d = s[date] if date in s.keys() else s.create_group(date)\n\n        # Add a new dataset. The name doesn't matter\n        attr_pars = ['vbary'] if 'vbary' in params else []\n        attr_pars.extend(['vsini', 'T', 'logg', '[Fe/H]', 'addmode', 'fname'])\n\n        # If we get here, no matching dataset was found.\n        ds_name = 'T{}_logg{}_metal{}_addmode-{}_vsini{}'.format(params['T'],\n                                                                 params['logg'],\n                                                                 params['[Fe/H]'],\n                                                                 params['addmode'],\n                                                                 params['vsini'])\n        if ds_name in d.keys():\n            if update:\n                ds = d[ds_name]\n                new_data = np.array((corr.x, corr.y))\n                try:\n                    ds.resize(new_data.shape)\n                except TypeError:\n                    # Hope for the best...\n                    pass\n                ds[:] = np.array((corr.x, corr.y))\n                f.flush()\n                f.close()\n                return\n            else:\n                i = 1\n                while '{}_{}'.format(ds_name, i) in d.keys():\n                    i += 1\n                ds_name = '{}_{}'.format(ds_name, i)\n\n        ds = d.create_dataset(ds_name, data=np.array((corr.x, corr.y)), maxshape=(2, None))\n\n        # Add attributes to the dataset\n        for a in attr_pars:\n            ds.attrs[a] = params[a]\n        idx = np.argmax(corr.y)\n        ds.attrs['vel_max'] = corr.x[idx]\n        ds.attrs['ccf_max'] = corr.y[idx]\n\n        f.flush()\n        f.close()\n\n    else:\n        raise ValueError('output mode ({}) not supported!'.format(mode))\n\n    return\n", "meta": {"hexsha": "26a0f16149577bae6ce55559c8454cffd9dda216", "size": 39424, "ext": "py", "lang": "Python", "max_stars_repo_path": "kglib/cross_correlation/GenericSearch.py", "max_stars_repo_name": "kgullikson88/gullikson-scripts", "max_stars_repo_head_hexsha": "8a9f00a6977dad8d4477eef1d664fd62e9ecab75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-02-22T02:34:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-02T02:31:58.000Z", "max_issues_repo_path": "kglib/cross_correlation/GenericSearch.py", "max_issues_repo_name": "kgullikson88/gullikson-scripts", "max_issues_repo_head_hexsha": "8a9f00a6977dad8d4477eef1d664fd62e9ecab75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kglib/cross_correlation/GenericSearch.py", "max_forks_repo_name": "kgullikson88/gullikson-scripts", "max_forks_repo_head_hexsha": "8a9f00a6977dad8d4477eef1d664fd62e9ecab75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-03-19T13:59:25.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-19T13:59:25.000Z", "avg_line_length": 44.6984126984, "max_line_length": 136, "alphanum_fraction": 0.5131645698, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 8222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.33111975283019596, "lm_q1q2_score": 0.17846799081372888}}
{"text": "from typing import Any, Callable, Dict, List, Mapping, Tuple\n\nimport networkx as nx\n\nfrom nereid.core.utils import safe_divide\nfrom nereid.src.network.utils import sum_node_attr\nfrom nereid.src.watershed.loading import compute_pollutant_load_reduction\n\n\ndef accumulate_dry_weather_loading(\n    g: nx.DiGraph,\n    data: Dict[str, Any],\n    predecessors: List[str],\n    dry_weather_parameters: List[Dict[str, Any]],\n) -> Dict[str, Any]:\n    \"\"\"This function helps aggregate the state of the watershed upstream of\n    the current node for dry weather conditions. This function considers dry weather\n    for two seasons per year, summer and winter.\n\n    This function is only called by `nereid.src.watershed.solve_watershed.solve_node`\n\n    Parameters\n    ----------\n    g : nx.DiGraph\n        graph object used to fetch upstream information.\n    data : dict\n        information about the current node. this may be a land surface node, a treatment facility,\n        or a treatment site.\n    predecessors : list\n        set of nodes immediately upstream of current node. These are used to aggregate flow\n        volume and pollutant load.\n    dry_weather_parameters : list of dicts\n        this contains information aabout each parameter, like long_name, short_name and\n        conversion factor information. see the *land_surface_emc_tables in the config file.\n        these dicts are pre-processed to cache some helpful unit conversions prior to\n        being passed to this function.\n        Reference: `nereid.src.wq_parameters.init_wq_parameters`\n\n    \"\"\"\n\n    seasons = [\"summer\", \"winter\"]\n\n    for season in seasons:\n\n        accumulate_dry_weather_volume_by_season(g, data, predecessors, season)\n        accumulate_dry_weather_pollutant_loading_by_season(\n            g, data, predecessors, dry_weather_parameters, season\n        )\n\n    return data\n\n\ndef accumulate_dry_weather_volume_by_season(\n    g: nx.DiGraph, data: Dict[str, Any], predecessors: List[str], season: str,\n) -> Dict[str, Any]:\n    \"\"\"aggregate dry weather volume for a single season\n\n    This function is called only by `accumulate_dry_weather_loading`\n\n    Parameters\n    ----------\n    * : see `accumulate_dry_weather_loading`\n    season : string\n        the season we want to aggregate.\n\n    \"\"\"\n\n    for suffix in [\"\", \"_psecond\"]:\n\n        dw_col = f\"{season}_dry_weather_flow_cuft\" + suffix\n\n        data[dw_col] = data.get(dw_col, 0.0)\n\n        data[f\"{dw_col}_direct\"] = sum_node_attr(g, predecessors, dw_col)\n\n        data[f\"{dw_col}_upstream\"] = sum_node_attr(\n            g, predecessors, f\"{dw_col}_discharged\"\n        )\n        data[f\"{dw_col}_inflow\"] = data[f\"{dw_col}_direct\"] + data[f\"{dw_col}_upstream\"]\n\n        data[f\"{dw_col}_retained_upstream\"] = sum_node_attr(\n            g, predecessors, f\"{dw_col}_total_retained\"\n        )\n\n        # initialize with assumption of no volume reduction\n        data[f\"{dw_col}_discharged\"] = data[f\"{dw_col}_inflow\"]\n        data[f\"{dw_col}_total_discharged\"] = data[f\"{dw_col}_inflow\"] + data[dw_col]\n        data[f\"{dw_col}_total_retained\"] = data[f\"{dw_col}_retained_upstream\"]\n\n    return data\n\n\ndef accumulate_dry_weather_pollutant_loading_by_season(\n    g: nx.DiGraph,\n    data: Dict[str, Any],\n    predecessors: List[str],\n    dry_weather_parameters: List[Dict[str, Any]],\n    season: str,\n) -> Dict[str, Any]:\n    \"\"\"aggregate dry weather pollutant load for a single season\n\n    This function is called only by `accumulate_dry_weather_loading`\n\n    Parameters\n    ----------\n    * : see `accumulate_dry_weather_loading`\n    season : string\n        the season we want to aggregate.\n\n    \"\"\"\n\n    for param in dry_weather_parameters:\n\n        inflow_volume = data[f\"{season}_dry_weather_flow_cuft_inflow\"]\n\n        load_col = season + \"_\" + param[\"load_col\"]\n        conc_col = season + \"_\" + param[\"conc_col\"]\n        load_to_conc_factor = param[\"load_to_conc_factor\"]\n        data[load_col] = data.get(load_col, 0.0)\n\n        data[f\"{load_col}_direct\"] = sum_node_attr(g, predecessors, load_col)\n\n        data[f\"{load_col}_upstream\"] = sum_node_attr(\n            g, predecessors, f\"{load_col}_discharged\"\n        )\n        inflow_load = data[f\"{load_col}_inflow\"] = (\n            data[f\"{load_col}_direct\"] + data[f\"{load_col}_upstream\"]\n        )\n\n        data[f\"{load_col}_removed_upstream\"] = sum_node_attr(\n            g, predecessors, f\"{load_col}_total_removed\"\n        )\n\n        influent_conc = safe_divide(inflow_load, inflow_volume) * load_to_conc_factor\n        data[f\"{conc_col}_influent\"] = influent_conc\n\n        # initialize with assumption of no treatment\n        data[f\"{conc_col}_effluent\"] = influent_conc\n        data[f\"{load_col}_discharged\"] = inflow_load\n        data[f\"{load_col}_total_discharged\"] = inflow_load + data[load_col]\n        data[f\"{load_col}_total_removed\"] = data[f\"{load_col}_removed_upstream\"]\n\n    return data\n\n\ndef compute_dry_weather_volume_performance(data):\n    \"\"\"\n    This function is only called by `nereid.src.watershed.solve_watershed.solve_node`\n    This function must be called after:\n        `accumulate_dry_weather_loading`\n\n    \"\"\"\n    seasons = [\"summer\", \"winter\"]\n\n    for season in seasons:\n        init_dry_weather_tmnt_rate_by_season(data, season)\n        compute_dry_weather_volume_performance_by_season(data, season)\n\n    return data\n\n\ndef init_dry_weather_tmnt_rate_by_season(\n    data: Dict[str, Any], season: str\n) -> Dict[str, Any]:\n    \"\"\"This function helps normalize how the treatment rate for dry weather flow\n    is credited, particularly for facilities that are volume-based and so have\n    no treatment-rate type attributes. This function will consider the rate of\n    treatment for each compartment of a volume based facility so that it's available\n    to later calculations regarding dry weather volume reduction.\n\n    This function is only called by `compute_dry_weather_volume_performance`\n\n    \"\"\"\n\n    dw_retention_rate_cfs = data.get(f\"{season}_dry_weather_retention_rate_cfs\")\n    months_operational = data.get(\"months_operational\") or \"both\"\n    is_operational = months_operational in [season, \"both\"]\n    dwf_override = data.get(\"eliminate_all_dry_weather_flow_override\") or False\n\n    if is_operational and dwf_override:\n        # This override will set the retention capacity to be equal to the inflow rate.\n        dw_inflow_cfs = (\n            data.get(f\"{season}_dry_weather_flow_cuft_psecond_inflow\") or 0.0\n        )\n        dw_retention_rate_cfs = dw_inflow_cfs\n        data[f\"{season}_dry_weather_retention_rate_cfs\"] = dw_retention_rate_cfs\n\n    if dw_retention_rate_cfs is None:\n        retention_vol = data.get(\"retention_volume_cuft\", 0.0)\n        retention_ddt_seconds = data.get(\"retention_ddt_hr\", 0.0) * 3600\n\n        dw_retention_rate_cfs = safe_divide(retention_vol, retention_ddt_seconds)\n        data[f\"{season}_dry_weather_retention_rate_cfs\"] = dw_retention_rate_cfs\n\n    dw_treatment_rate_cfs = data.get(f\"{season}_dry_weather_treatment_rate_cfs\")\n    if dw_treatment_rate_cfs is None:\n\n        dw_treatment_rate_cfs = data.get(\"treatment_rate_cfs\")\n        treatment_volume_cuft = data.get(\"treatment_volume_cuft\", 0.0)\n\n        if dw_treatment_rate_cfs is None:\n            if treatment_volume_cuft > 1e-3:\n\n                treatment_ddt_seconds = data.get(\"treatment_ddt_hr\", 0.0) * 3600\n\n                dw_treatment_rate_cfs = safe_divide(\n                    treatment_volume_cuft, treatment_ddt_seconds\n                )\n            else:\n                dw_treatment_rate_cfs = 0.0\n\n        data[f\"{season}_dry_weather_treatment_rate_cfs\"] = dw_treatment_rate_cfs\n\n    return data\n\n\ndef compute_dry_weather_volume_performance_by_season(\n    data: Dict[str, Any], season: str\n) -> Dict[str, Any]:\n    \"\"\"This function checks to see if the dry weather flow rate can be eliminated\n    by the retention rate, and if not, applies treatment to the discharge volume\n    up to the treatment rate capacity. discharge rates higher than the treatment\n    rate are considered bypassed flow.\n\n    All performance is based on flow rate, and assume completely steaady state.\n    Thus volume reduced and volume treated are computed ad stored based upon the\n    flow rate performance.\n\n    This function is only called by `compute_dry_weather_volume_performance`\n\n    \"\"\"\n\n    dw_retention_rate_cfs = data.get(f\"{season}_dry_weather_retention_rate_cfs\", 0.0)\n    dw_treatment_rate_cfs = data.get(f\"{season}_dry_weather_treatment_rate_cfs\", 0.0)\n    months_operational = data.get(\"months_operational\", \"both\")\n\n    cfs_col = f\"{season}_dry_weather_flow_cuft_psecond\"\n    dw_inflow_cfs_col = cfs_col + \"_inflow\"\n    dw_inflow_cfs = data.get(dw_inflow_cfs_col, 0.0)\n\n    vol_col = f\"{season}_dry_weather_flow_cuft\"\n    dw_inflow_vol_col = vol_col + \"_inflow\"\n    dw_inflow_vol = data.get(dw_inflow_vol_col, 0.0)\n\n    vol_retained = 0.0\n    vol_treated = 0.0\n    dw_flow_rate_discharged = dw_inflow_cfs  # assume no flowrate attenuation\n    dw_flow_retained_frac = 0.0\n    dw_flow_treated_frac = 0.0\n    dw_flow_tmnt_rate = 0.0\n\n    if (months_operational in [season, \"both\"]) and (dw_inflow_cfs > 0):\n        # this is the rate that is not able to be eliminated by retention\n        # it may still be treated.\n        _discharge_rate = max(dw_inflow_cfs - dw_retention_rate_cfs, 0)\n\n        # this is the flowrate that will be discharged, and some of it may be treated.\n        dw_flow_rate_discharged = min(_discharge_rate, dw_inflow_cfs)\n        dw_flow_retained_frac = 1 - safe_divide(dw_flow_rate_discharged, dw_inflow_cfs)\n        vol_retained = dw_flow_retained_frac * dw_inflow_vol\n\n        if dw_flow_retained_frac < 1:\n            dw_flow_tmnt_rate = min(dw_treatment_rate_cfs, dw_flow_rate_discharged)\n            dw_flow_treated_frac = safe_divide(\n                dw_flow_tmnt_rate, dw_flow_rate_discharged\n            )\n            vol_treated = dw_flow_treated_frac * (dw_inflow_vol - vol_retained)\n\n    data[cfs_col + \"_retained\"] = dw_inflow_cfs - dw_flow_rate_discharged\n    data[cfs_col + \"_retained_pct\"] = dw_flow_retained_frac * 100\n    data[cfs_col + \"_treated\"] = dw_flow_tmnt_rate\n    data[cfs_col + \"_treated_pct\"] = dw_flow_treated_frac * 100\n    data[cfs_col + \"_discharged\"] = dw_flow_rate_discharged\n    data[cfs_col + \"_total_retained\"] = data[cfs_col + \"_retained\"] + data.get(\n        cfs_col + \"_retained_upstream\", 0.0\n    )\n    # for symmetry with non-treatment nodes.\n    data[f\"{cfs_col}_total_discharged\"] = (\n        data.get(cfs_col, 0) + data[f\"{cfs_col}_discharged\"]\n    )\n\n    data[vol_col + \"_retained\"] = vol_retained\n    data[vol_col + \"_retained_pct\"] = 100 * safe_divide(vol_retained, dw_inflow_vol)\n\n    data[vol_col + \"_treated\"] = vol_treated\n    data[vol_col + \"_treated_pct\"] = 100 * safe_divide(vol_treated, dw_inflow_vol)\n\n    data[vol_col + \"_captured\"] = vol_treated + vol_retained\n    data[vol_col + \"_captured_pct\"] = 100 * safe_divide(\n        vol_treated + vol_retained, dw_inflow_vol\n    )\n\n    data[vol_col + \"_bypassed\"] = max(dw_inflow_vol - (vol_treated + vol_retained), 0)\n    data[vol_col + \"_bypassed_pct\"] = 100 * safe_divide(\n        data[vol_col + \"_bypassed\"], dw_inflow_vol\n    )\n\n    data[vol_col + \"_discharged\"] = dw_inflow_vol - vol_retained\n    data[vol_col + \"_total_retained\"] = data[vol_col + \"_retained\"] + data.get(\n        vol_col + \"_retained_upstream\", 0.0\n    )\n    # for symmetry with non-treatment nodes.\n    data[f\"{vol_col}_total_discharged\"] = (\n        data.get(vol_col, 0) + data[f\"{vol_col}_discharged\"]\n    )\n\n    return data\n\n\ndef compute_dry_weather_load_reduction(\n    data: Dict[str, Any],\n    dry_weather_parameters: List[Dict[str, Any]],\n    dry_weather_facility_performance_map: Mapping[Tuple[str, str], Callable],\n) -> Dict[str, Any]:\n    \"\"\"This function computes how load reduction is effected by the volume reduced\n    and/or treated by the current facility. This function requires that the volume\n    balance is already computed.\n\n    This function is only called by `nereid.src.watershed.solve_watershed.solve_node`\n    This function must be called after all of the following have been called:\n        `accumulate_dry_weather_loading`\n        `compute_dry_weather_volume_performance`\n\n    Parameters\n    ----------\n    data : dict\n        information about current node, including facility sizing information and\n        inflow characteristics.\n    dry_weather_parameters: list of dicts\n        this contains information aabout each parameter, like long_name, short_name and\n        conversion factor information. see the *land_surface_emc_tables in the config file.\n        these dicts are pre-processed to cache some helpful unit conversions too prior to\n        being passed to this function.\n        Reference: `nereid.src.wq_parameters.init_wq_parameters`\n    dry_weather_facility_performance_map : mapping\n        this mapping uses a facility type and a pollutant as the keys to retrieve a function\n        that returns effluent concentration as output when given influent concentration as input.\n        Reference: `nereid.src.tmnt_performance.tmnt.effluent_conc`\n        Reference: `nereid.src.tmnt_performance.tasks.effluent_function_map`\n\n    \"\"\"\n\n    tmnt_facility_type = data.get(\"tmnt_performance_facility_type\", r\"¯\\_(ツ)_/¯\")\n\n    seasons = [\"summer\", \"winter\"]\n    for season in seasons:\n        vol_col = f\"{season}_dry_weather_flow_cuft\"\n\n        for param in dry_weather_parameters:\n            conc_unit = param[\"concentration_unit\"]\n            poc_long = param[\"long_name\"]\n\n            load_col = season + \"_\" + param[\"load_col\"]\n            conc_col = season + \"_\" + param[\"conc_col\"]\n\n            load_to_conc_factor = param[\"load_to_conc_factor\"]\n            conc_to_load_factor = param[\"conc_to_load_factor\"]\n\n            inflow_load = data[f\"{load_col}_inflow\"]\n            influent_conc = data[f\"{conc_col}_influent\"]\n\n            compute_pollutant_load_reduction(\n                data,\n                dry_weather_facility_performance_map,\n                tmnt_facility_type,\n                conc_unit,\n                poc_long,\n                load_col,\n                conc_col,\n                vol_col,\n                load_to_conc_factor,\n                conc_to_load_factor,\n                inflow_load,\n                influent_conc,\n            )\n\n    return data\n", "meta": {"hexsha": "9f1619d514e14a1b1c4db12c9136783746c62207", "size": 14346, "ext": "py", "lang": "Python", "max_stars_repo_path": "nereid/nereid/src/watershed/dry_weather_loading.py", "max_stars_repo_name": "Geosyntec/nereid", "max_stars_repo_head_hexsha": "3399b616ae19dfc75f5b6ba83d598495db9b09fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-16T22:10:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T22:10:24.000Z", "max_issues_repo_path": "nereid/nereid/src/watershed/dry_weather_loading.py", "max_issues_repo_name": "Geosyntec/nereid", "max_issues_repo_head_hexsha": "3399b616ae19dfc75f5b6ba83d598495db9b09fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 99, "max_issues_repo_issues_event_min_datetime": "2019-11-18T20:06:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T04:01:51.000Z", "max_forks_repo_path": "nereid/nereid/src/watershed/dry_weather_loading.py", "max_forks_repo_name": "Geosyntec/nereid", "max_forks_repo_head_hexsha": "3399b616ae19dfc75f5b6ba83d598495db9b09fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-28T21:06:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-13T23:12:17.000Z", "avg_line_length": 37.9523809524, "max_line_length": 98, "alphanum_fraction": 0.6901575352, "include": true, "reason": "import networkx", "num_tokens": 3547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3311197396289915, "lm_q1q2_score": 0.17846798369850123}}
{"text": "#! Python PyDoppler\r\n\r\nimport numpy as np\r\nimport imp\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.cm as cm\r\nfrom scipy.signal import savgol_filter\r\nimport sys\r\n\r\nplt.rcParams.update({'font.size': 12})\r\n\r\nimport os\r\n\r\nplt.ion()\r\n\r\nclass spruit:\r\n    \"\"\"\r\n        A class to store and process data for Doppler tomography code\r\n        by Henk Spruit.\r\n\r\n    ...\r\n\r\n    Methods\r\n    -------\r\n    foldspec()\r\n        Reads the data and stores in spruit object\r\n    sort(column, order='ascending')\r\n        Sort by `column`\r\n    \"\"\"\r\n    def __init__(self,force_install = False):\r\n        self.object = 'disc'\r\n        self.wave = 0.0\r\n        self.flux = 0.0\r\n        self.pha = 0.0\r\n        self.input_files = 0.0\r\n        self.input_phase = 0.0\r\n        self.trsp = 0.0\r\n        self.nbins = 20\r\n        self.normalised_flux = 0.0\r\n        self.normalised_wave = 0.0\r\n        self.base_dir = '.'\r\n        self.lam0 = 6562.83\r\n        self.delw = 80\r\n        self.list = 'phases.txt'\r\n        self.overs = 0.3\r\n        self.gama = 0.0\r\n        self.delta_phase = 0.001\r\n\r\n        self.verbose = True\r\n\r\n        ###### Plotting parameters\r\n        self.psname='j0644'              # Name of output plot file\r\n        self.output='pdf'                    # Can choose between: pdf, eps or png\r\n        self.data=False                      # If True then exit data will put in file *.txt\r\n        self.plot=True                       # Plot in Python window\r\n        self.plotlim=1.3                     # Plot limits. 1 = close fit.\r\n        self.overs=0.4\r\n\r\n        ####### Dop.in parameters\r\n        self.ih = 0\r\n        self.iw = 0\r\n        self.pb0 = 0.95\r\n        self.pb1 = 1.05\r\n        self.ns = 7\r\n        self.ac = 8e-4\r\n        self.nim = 150\r\n        self.al0 = 0.002\r\n        self.alf = 1.7\r\n        self.nal = 0\r\n        self.clim = 1.6\r\n        self.ipri = 2\r\n        self.norm = 1\r\n        self.wid = 10e5\r\n        self.af = 0.0\r\n\r\n\r\n        # %%%%%%%%%%%%%%%%%%  Doppler Options   %%%%%%%%%%%%%%%%%%\r\n\r\n        self.lobcol='white'                 # Stream color\r\n        self.module_path = os.path.dirname(os.path.realpath(__file__))\r\n\r\n        #### Copy Fortran files to local directory\r\n\r\n        if os.path.isfile(\"dop.f\"):\r\n            #print(\"Fortran code exists\")\r\n            if force_install:\r\n                print(\"-- Force_Install --\")\r\n                os.system('cp '+self.module_path+'/fortran_code/* ./.')\r\n                count = 0\r\n                dst_file = './sample_script.py'\r\n                while os.path.exists(dst_file):\r\n                    count += 1\r\n                    dst_file = './%s-%d%s' % ('sample_script', count, '.py')\r\n                #print 'Renaming %s to %s' % (file, dst_file)\r\n                print(\"PyDoppler scipt -->\",dst_file)\r\n                #os.rename(file, dst_file)\r\n                os.system('cp '+self.module_path+'/test_data/sample_script.py '+\\\r\n                          dst_file)\r\n        else:\r\n            print(\"-- Copying fortran code --\")\r\n            os.system('cp '+self.module_path+'/fortran_code/* ./.')\r\n            count = 0\r\n            dst_file = './sample_script.py'\r\n            while os.path.exists(dst_file):\r\n                count += 1\r\n                dst_file = './%s-%d%s' % ('sample_script', count, '.py')\r\n            #print 'Renaming %s to %s' % (file, dst_file)\r\n            print(\"PyDoppler scipt -->\",dst_file)\r\n            #os.rename(file, dst_file)\r\n            os.system('cp '+self.module_path+'/test_data/sample_script.py '+\\\r\n                      dst_file)\r\n\r\n\r\n    def Foldspec(self):\r\n        \"\"\"Foldspec. Prepares the spectra to be read by dopin.\r\n        *** Remember to prepare the keywords before running ***\r\n\r\n        Parameters\r\n        ----------\r\n        None\r\n\r\n        Returns\r\n        -------\r\n        None\r\n\r\n        \"\"\"\r\n        try:\r\n            f = open(self.base_dir+'/'+self.list)\r\n            f.close()\r\n        except IOError:\r\n            print('Phase file - {} - is not accessible. Check \"base_dir\" and \"list\"'.format(self.base_dir+'/'+self.list))\r\n        inputs = np.loadtxt(self.base_dir+'/'+self.list,dtype={'names': ('files', 'phase'),'formats': ('S14', 'f4')})\r\n        # Check 1st spectrum and get wavelength to interpolate\r\n        #print()\r\n        #print(inputs['files'][0].astype('str'))\r\n        w1st = np.loadtxt(self.base_dir+'/'+inputs['files'][0].astype('str'),unpack=True)\r\n        if self.nbins==None:\r\n            self.nbins=int(1.5/np.abs(inputs['phase'][2]-inputs['phase'][1]))   #By default\r\n        if self.verbose:\r\n            print (\"Number of Bins:\",self.nbins,np.abs(inputs['phase'][2]-inputs['phase'][1]))\r\n        wave,flux=[],[]\r\n        for z,i in enumerate(inputs):\r\n            w,f=np.loadtxt(self.base_dir+'/'+i['files'].astype('str'),unpack=True)\r\n            print (str(z+1).zfill(3)+' '+i['files'].astype('str')+'  '+str(i['phase'])+' '+str(w.size))\r\n            if z == 0:\r\n                wo = w\r\n                wave.append(w),flux.append(f)\r\n            else:\r\n                wave.append(wo),flux.append(np.interp(wo,w,f))\r\n        delp=1.0/self.nbins\r\n        pha=np.arange(0,1,delp)\r\n        bin=np.arange(self.nbins+1)/float(self.nbins)\r\n\r\n        bin=np.concatenate((bin[:self.nbins]-1,bin))\r\n        wt=np.zeros(2*self.nbins)\r\n        trsp=np.zeros((2*self.nbins,len(wo)))\r\n        # Determine\r\n        dph = delp\r\n        for ph,il in zip(pha,np.arange(len(pha))):\r\n            ph0=ph-dph/2\r\n            ph1=ph+dph/2\r\n            for ib in np.arange(2*(self.nbins)):\r\n                r=bin[ib+1]\r\n                l=bin[ib]\r\n                if ph0 <= r and ph1> l:\r\n                    wph=min([r,ph1])-max([r,ph1])\r\n                    #print [r,ph1],[r,ph1],wph\r\n                    wt[ib]=wt[ib]+wph\r\n                    trsp[ib]=trsp[ib]+wph*flux[il]\r\n        wt[self.nbins:2*self.nbins]=wt[self.nbins:2*self.nbins]+wt[:self.nbins]\r\n        wt = wt[self.nbins:2*self.nbins]\r\n        trsp[self.nbins:2*self.nbins] = trsp[self.nbins:2*self.nbins] + trsp[:self.nbins]\r\n        trsp=trsp[self.nbins:2*self.nbins]\r\n        wt=wt/wt.sum()*float(self.nbins)\r\n        #print(wt)\r\n        self.wave = wave\r\n        self.flux = flux\r\n        self.pha = pha\r\n        self.input_files = inputs['files'].astype('str')\r\n        self.input_phase = inputs['phase']\r\n        self.trsp = trsp\r\n\r\n    def Dopin(self,poly_degree=2, continnum_band=False,\r\n              rebin=True,plot_median = False, rebin_wave= 0.,\r\n              xlim=None,two_orbits=True,vel_space=True,\r\n              verbose=False):\r\n        \"\"\"Normalises each spectrum to a user-defined continnum.\r\n            Optional, it plots a trail spectra\r\n\r\n        Parameters\r\n        ----------\r\n        poly_degree : int, Optional\r\n            polynomial degree to fit the continuum. Default, 2.\r\n\r\n        continnum_band : array-like,\r\n            Define two wavelength bands (x1,x2) and (x3,x4)\r\n            to fit the continuum.\r\n            contiunnum_band = [x1,x2,x3,x4].\r\n            If False, an interactive plot will allow to select this four numbers\r\n            - Default, False\r\n\r\n        plot_median : bool,\r\n            Plots above teh trail spectra a median of the dataset.\r\n            - Defautl, False\r\n\r\n        rebin_wave : float,\r\n            TBD\r\n\r\n        xlim : float,\r\n            TBD\r\n\r\n        two_orbits : float,\r\n            TBD\r\n\r\n        vel_space : float,\r\n            TBD\r\n\r\n        verbose : float,\r\n            TBD\r\n\r\n        Returns\r\n        -------\r\n        None.\r\n\r\n        \"\"\"\r\n        lam=self.lam0\r\n        cl=2.997e5\r\n        xaxis='vel'\r\n\r\n        cmaps = plt.cm.binary_r #cm.winter_r cm.Blues#cm.gist_stern\r\n        medi=17\r\n        line_lbl='K I'\r\n\r\n        if lam < min(self.wave[0]) or lam > max(self.wave[0]):\r\n            print('Error: input wavelength out of bounds.')\r\n            print('Must be between '+str(min(self.wave[0]))+' and '+str(max(self.wave[0]))+'.')\r\n            sys.exit()\r\n        ss=0\r\n        for i in np.arange(len(self.wave[0])-1):\r\n            if lam >= self.wave[0][i]   and lam <= self.wave[0][i+1]:\r\n                ss=i\r\n\r\n\r\n        fig=plt.figure(num=\"Average Spec\",figsize=(6.57,8.57))\r\n        plt.clf()\r\n        ax=fig.add_subplot(211)\r\n        avgspec=np.sum(self.flux,axis=0)\r\n        plt.plot(self.wave[0],avgspec/len(self.pha))\r\n\r\n        plt.draw()\r\n        if not continnum_band:\r\n            print( 'Choose 4 points to define continuum')\r\n            xor=[]\r\n            for i in np.arange(4):\r\n                xx=plt.ginput(1,timeout=-1)\r\n                xor.append(xx[0][0])\r\n                plt.axvline(x=xx[0][0],linestyle='--',color='k')\r\n                plt.draw()\r\n        else:\r\n            xor = continnum_band\r\n            lab1 = 'Cont Bands'\r\n            for i in np.arange(4):\r\n                if i != 0: lab1 = ''\r\n                plt.axvline(x=xor[i],linestyle='--',color='k',label=lab1)\r\n                plt.draw()\r\n        lop = ((self.wave[0]>xor[0]) * (self.wave[0]<xor[1])) + ((self.wave[0]>xor[2]) * (self.wave[0]<xor[3]))\r\n        yor=avgspec[lop]/len(self.pha)\r\n        plt.ylim(avgspec[lop].min()/len(self.pha)*0.8,avgspec.max()/len(self.pha)*1.1)\r\n        z = np.polyfit(self.wave[0][lop], yor, poly_degree)\r\n        pz = np.poly1d(z)\r\n        linfit = pz(self.wave[0])\r\n        plt.plot(self.wave[0],linfit,'r',label='Cont Fit')\r\n        lg = plt.legend(fontsize=14)\r\n        plt.xlim(xor[0]-10,xor[3]+10)\r\n        plt.xlabel(r'Wavelength / $\\AA$')\r\n        plt.ylabel('Input flux')\r\n\r\n\r\n        ax=fig.add_subplot(212)\r\n        vell=((self.wave[0]/self.lam0)**2-1)*cl/(1+(self.wave[0]/self.lam0)**2)\r\n\r\n        plt.plot(vell,avgspec/len(self.pha)-linfit,'k')\r\n        plt.axhline(y=0,linestyle='--',color='k')\r\n        plt.axvline(x=-self.delw/self.lam0*cl,linestyle='-',color='DarkOrange')\r\n        plt.axvline(x= self.delw/self.lam0*cl,linestyle='-',\r\n                    color='DarkOrange',label='DopMap limits')\r\n        lg = plt.legend(fontsize=14)\r\n        plt.xlim(-self.delw/self.lam0*cl*1.5,self.delw/self.lam0*cl*1.5)\r\n        qq = (np.abs(vell) < self.delw/self.lam0*cl*1.5)\r\n        plt.ylim(-0.05*np.max(avgspec[qq]/len(self.pha)-linfit[qq] -1.0),\r\n                np.max(avgspec[qq]/len(self.pha)-linfit[qq] -1.0)*1.1)\r\n        plt.xlabel('Velocity km/s')\r\n        plt.ylabel('Bkg subtracted Flux')\r\n        plt.draw()\r\n        plt.tight_layout()\r\n\r\n        ######## Do individual fit on the blaze\r\n        for ct,flu in enumerate(self.flux):\r\n            #print(lop.sum)\r\n            if ct == 0 :\r\n                nufac=(1.0+self.gama/2.998e5) * np.sqrt(1.0-(self.gama/2.998e5)**2)\r\n                lop = (self.wave[0]/nufac > self.lam0 - self.delw) * \\\r\n                      (self.wave[0]/nufac < self.lam0 + self.delw)\r\n                self.normalised_wave = np.array(self.wave[0][lop]/nufac)\r\n                # Interpolate in velocity space\r\n                vell_temp=((self.normalised_wave/self.lam0)**2-1.0)*cl/(1.0 + \\\r\n                         (self.normalised_wave/self.lam0)**2)\r\n                self.vell = np.linspace(vell_temp[0],vell_temp[-1],vell_temp.size)\r\n                self.normalised_flux = np.zeros((len(self.flux),lop.sum()))\r\n\r\n            polmask = ((self.wave[0]/nufac>xor[0]) * (self.wave[0]/nufac<xor[1])) +\\\r\n                  ((self.wave[0]/nufac>xor[2]) * (self.wave[0]/nufac<xor[3]))\r\n            z = np.polyfit(self.wave[0][polmask]/nufac,flu[polmask], 3)\r\n            pz = np.poly1d(z)\r\n            linfit = pz(self.normalised_wave)\r\n\r\n            self.normalised_flux[ct] = np.array(flu[lop]) - np.array(linfit)\r\n            self.normalised_flux[ct] = np.interp(self.vell,vell_temp,self.normalised_flux[ct])\r\n\r\n        if self.verbose:\r\n            print(\">> Max/Min velocities in map: {} / {}\".format(self.vell.min(),\r\n                                                             self.vell.max()))\r\n\r\n\r\n        ##  JVHS 2019 August 6\r\n        ## Add binning\r\n        phase = np.linspace(0,2,self.nbins*2+1,endpoint=True) - 1./(self.nbins)/2.\r\n        phase = np.concatenate((phase,[2.0+1./(self.nbins)/2.]))\r\n        phase_dec = phase - np.floor(phase)\r\n        #print(phase_dec)\r\n        #rebin_trail(waver, flux, input_phase, nbins, delp, rebin_wave=None):\r\n        trail,temp_phase = rebin_trail(self.vell, self.normalised_flux,\r\n                            self.input_phase, self.nbins, self.delta_phase,\r\n                            rebin_wave=None)\r\n\r\n        self.pha = self.input_phase\r\n        self.trsp = self.normalised_flux\r\n        #print(\">> SHAPES = \",self.pha.shape,self.trsp.shape)\r\n        ## Phases of individual spectra\r\n        #print(\"LAM_SIZE= {}, VELL_SIZE={}\".format(self.normalised_wave.size,self.vell.size))\r\n        f=open('dopin','w')\r\n        f.write(\"{:8.0f}{:8.0f}{:13.2f}\\n\".format(self.pha.size,\r\n                                        self.vell.size,\r\n                                        self.lam0))\r\n#        f.write(str(len(self.flux))+\" \"+str(self.nbins)+\" \"+str(self.lam0)+'\\n')\r\n        f.write(\"{:13.5f}{:8.0f}{:8.0f}    {:}\\n\".format(self.gama*1e5,0,0,\r\n                                                self.base_dir+'/'+self.list))\r\n        ctr = 0\r\n        for pp in self.pha:\r\n                if ctr <5:\r\n                    f.write(\"{:13.6f}\".format(pp))\r\n                    ctr +=1\r\n                else:\r\n                    f.write(\"{:13.6f}\\n\".format(pp))\r\n                    ctr=0\r\n        f.write(\"\\n{:8.0f}\\n\".format(1))\r\n        ctr = 0\r\n\r\n        for pp in np.ones(self.pha.size)*self.delta_phase:\r\n                if ctr <5:\r\n                    f.write(\"{:13.6f}\".format(pp))\r\n                    ctr +=1\r\n                else:\r\n                    f.write(\"{:13.6f}\\n\".format(pp))\r\n                    ctr=0\r\n        if ctr != 0: f.write(\"\\n\")\r\n        ##\r\n        ctr = 0\r\n        for pp in self.vell:\r\n                #print('velo size:',len(vell))\r\n                if ctr <5:\r\n                    f.write(\"{:13.5e}\".format(pp*1e5))\r\n                    ctr +=1\r\n                else:\r\n                    f.write(\"{:13.5e}\\n\".format(pp*1e5))\r\n                    ctr=0\r\n        if ctr != 0: f.write(\"\\n\")\r\n        ctr = 0\r\n\r\n        # Where we write the normalised flux\r\n        for pp in np.array(self.trsp.T).flatten():\r\n                if ctr <5:\r\n                    f.write(\"{:13.5f}\".format(pp))\r\n                    ctr +=1\r\n                else:\r\n                    f.write(\"{:13.5f}\\n\".format(pp))\r\n                    ctr=0\r\n        if ctr != 0: f.write(\"\\n\")\r\n        f.close()\r\n\r\n\r\n\r\n        if xlim == None:\r\n            rr = np.ones(self.normalised_wave.size,dtype='bool')\r\n        else:\r\n            rr = (self.normalised_wave > xlim[0]) & (self.normalised_wave < xlim[1])\r\n\r\n        if rebin_wave == 0:\r\n            waver = self.normalised_wave[rr]\r\n        else:\r\n            dw = (self.normalised_wave[rr][1] - self.normalised_wave[rr][0]) *\\\r\n                                                 rebin_wave\r\n            print(dw , dw/rebin_wave)\r\n            waver = np.arange(self.normalised_wave[rr][0],\r\n                              self.normalised_wave[rr][-1],dw )\r\n        \"\"\"\r\n        trail = np.zeros((waver.size,phase.size))\r\n\r\n        tots = trail.copy()\r\n        #print(phases.size)\r\n        for i in range(self.input_phase.size):\r\n            #print(\"spec phase = \",grid['phase'][i])\r\n            dist = phase_dec - (self.input_phase[i]+self.delta_phase/2.)\r\n            #print(dist)\r\n            dist[np.abs(dist)>1./self.nbins] = 0.\r\n            #print(dist/delpha)\r\n            dist[dist>0] = 0.0\r\n            #print(dist)\r\n            weights = np.abs(dist)/(1./self.nbins)\r\n            #print(weights)\r\n            #print('---------------')\r\n            dist = phase_dec - (self.input_phase[i]-self.delta_phase/2.)\r\n            #print(dist)\r\n            dist[np.abs(dist)>1./self.nbins] = 0.0\r\n            #print(dist)\r\n            dist[dist>0] = 0.0\r\n            #print(dist/delpha)\r\n            dist[np.abs(dist)>0] = 1.0 - (np.abs(dist[np.abs(dist)>0]))/(1./self.nbins)\r\n            weights += dist\r\n            #print(weights)\r\n            temp = trail.copy().T\r\n\r\n            for j in range(phase.size):\r\n                if rebin_wave == 0:\r\n                    temp[j] =  self.normalised_flux[i][rr] * weights[j]\r\n                    temp[j] =  self.normalised_flux[i][rr] * weights[j]\r\n                else:\r\n                    temp[j] = np.interp(waver,wave[rr],\r\n                              self.normalised_flux[i][rr]) * weights[j]\r\n                    temp[j] = np.interp(waver,wave[rr],\r\n                              self.normalised_flux[i][rr]) * weights[j]\r\n            trail+=temp.T\r\n            tots += weights\r\n        trail /= tots\r\n        \"\"\"\r\n\r\n        if plot_median:\r\n            si = 0\r\n            lo = 2\r\n        else:\r\n            si = 2\r\n            lo = 0\r\n\r\n        plt.figure('Trail',figsize=(6.57,8.57))\r\n        plt.clf()\r\n        if plot_median:\r\n            ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=2)\r\n            ax1.minorticks_on()\r\n            if rebin_wave ==0:\r\n                plt.plot(waver,np.nanmedian(self.normalised_flux,axis=0)[rr],\r\n                    label='Median',color='#8e44ad')\r\n            else:\r\n                print(dw)\r\n                new_med = np.interp(waver,wave[rr],\r\n                                    np.nanmedian(self.normalised_flux,axis=0)[rr])\r\n                plt.plot(waver,np.nanmedian(self.normalised_flux,axis=0)[rr],\r\n                    label='Median',color='k',alpha=1)\r\n                plt.plot(waver,new_med,\r\n                    label='Median',color='#8e44ad',alpha=1)\r\n            plt.axhline(y=0,ls='--',color='r',alpha=0.7)\r\n            ax1.set_xticklabels([])\r\n\r\n            #plt.xlim(self.lam0 - self.delw, self.lam0 + self.delw)\r\n            plt.ylim(-0.05,np.nanmax(np.nanmedian(self.normalised_flux,\r\n                                                  axis=0)[rr])*1.1)\r\n            ### Print trail spectra\r\n            if limits == None:\r\n                limits=[np.nanmax(np.nanmedian(grid,axis=0)[rr])*0.35,\r\n                    np.nanmax(np.nanmedian(grid,axis=0)[rr])*1.1]\r\n        ax2 = plt.subplot2grid((6, 1), (lo, 0), rowspan=4+si)\r\n        ax2.minorticks_on()\r\n        if vel_space:\r\n            x1_lim = (min(waver)-self.lam0)/self.lam0*2.998e5\r\n            x2_lim = (max(waver)-self.lam0)/self.lam0*2.998e5\r\n        else:\r\n            x1_lim = min(waver)\r\n            x2_lim = max(waver)\r\n        img = plt.imshow(trail.T,interpolation='nearest',\r\n                         cmap=plt.cm.binary,\r\n                         aspect='auto',origin='lower',\r\n                         extent=(x1_lim,\r\n                                 x2_lim,phase[0],phase[-1]+1/self.nbins))#\r\n                         #vmin=limits[0],vmax=limits[1])\r\n        if vel_space:\r\n            plt.xlim((self.lam0 - self.delw-self.lam0)/self.lam0*2.998e5,\r\n                     (self.lam0 + self.delw-self.lam0)/self.lam0*2.998e5)\r\n            plt.xlabel('Velocity / km s$^{-1}$')\r\n        else:\r\n            plt.xlim(self.lam0 - self.delw, self.lam0 + self.delw)\r\n            plt.xlabel('Wavelength / $\\AA$')\r\n        plt.axvline(x=self.lam0,ls='--',color='DarkOrange')\r\n        if two_orbits:\r\n            lim_two = 2\r\n        else:\r\n            lim_two = 1\r\n        plt.ylim(phase[0],lim_two+1/self.nbins/2.)\r\n        plt.ylabel('Orbital Phase')\r\n        plt.tight_layout(h_pad=0)\r\n\r\n\r\n\r\n    def Syncdop(self,nri=0.9,ndi=0.7):\r\n        '''\r\n        Runs the fortran code dopp, using the output files from dopin\r\n        Parameters\r\n        ----------\r\n        None\r\n\r\n        Returns\r\n        -------\r\n        None.\r\n        '''\r\n        compile_flag = True\r\n        while compile_flag == True:\r\n            f=open('dop.in','w')\r\n            f.write(\"{}     ih       type of likelihood function (ih=1 for chi-squared)\\n\".format(self.ih))\r\n            f.write(\"{}     iw       iw=1 if error bars are to be read and used\\n\".format(self.iw))\r\n            f.write(\"{}  {}    pb0,pb1    range of phases to be ignored\\n\".format(self.pb0,self.pb1))\r\n            f.write(\"{}     ns       smearing width in default map\\n\".format(self.ns))\r\n            f.write(\"{:.1e}     ac       accuracy of convergence\\n\".format(self.ac))\r\n            f.write(\"{}     nim      max no of iterations\\n\".format(self.nim))\r\n            f.write(\"{} {}  {}        al0,alf,nal   starting value, factor, max number of alfas\\n\".format(self.al0,self.alf,self.nal))\r\n            f.write(\"{}     clim     'C-aim'\\n\".format(self.clim))\r\n            f.write(\"{}     ipri     printout control for standard output channel (ipr=2 for full)\\n\".format(self.ipri))\r\n            f.write(\"{}     norm     norm=1 for normalization to flat light curve\\n\".format(self.norm))\r\n            f.write(\"{:2.1e}   {}  wid,af    width and amplitude central absorption fudge\\n\".format(self.wid,self.af))\r\n            f.write(\"end of parameter input file\")\r\n            f.close()\r\n\r\n            f=open('dopin')\r\n            lines=f.readlines()\r\n            f.close()\r\n            # np == npp\r\n            npp,nvp=int(lines[0].split()[0]),int(lines[0].split()[1])\r\n            lines=[]\r\n\r\n            f=open('emap_ori.par')\r\n            lines=f.readlines()\r\n            f.close()\r\n            s=lines[0]\r\n            npm=int(s[s.find('npm=')+len('npm='):s.rfind(',nvpm')])\r\n            nvpm=int(s[s.find('nvpm=')+len('nvpm='):s.rfind(',nvm')])\r\n            nvm=int(s[s.find('nvm=')+len('nvm='):s.rfind(')')])\r\n            nvp = self.vell.size\r\n            print('nvp',nvp)\r\n\r\n            print(self.trsp.shape)\r\n            nv0=int(self.overs*nvp)\r\n            nv=max([nv0,int(min([1.5*nv0,npp/3.]))])\r\n            print('nv',nv,nv0)\r\n            if nv%2 == 1:\r\n                nv+=1\r\n            #nv=120\r\n            nd = npm * nvpm\r\n            nr = 0.8 * nv * nv\r\n            nt = (nvpm * npm) + (nv * nvpm * 3) + (2 * npm * nv)\r\n            prmsize = (0.9 * nv * nt) + (0.9 * nv * nt)\r\n\r\n            print ('Estimated Memory required ',int(8*prmsize/1e6),' Mbytes')\r\n            #print nv,nvm,np,npm,nvp,nvpm\r\n            print(\"np={}; nvpm={}, nvm={}\".format(npp, nvp, nv))\r\n            print('ND',nd)\r\n            print('NR',nr)\r\n            if nv != nvm or npp != npm or nvp !=nvpm:\r\n                a1='      parameter (npm=%4d'% npp\r\n                a2=',nvpm=%4d'%nvp\r\n                a3=',nvm=%4d)'%nv\r\n                a1=a1+a2+a3\r\n\r\n                f=open('emap.par','w')\r\n                f.write(a1+'\\n')\r\n                for i,lino in enumerate(lines[1:]):\r\n                    #print(lino)\r\n                    if i == 2:\r\n                        tempo_str = '      parameter (nri={:.3f}*nvm*nt/nd,ndi={:.3f}*nvm*nt/nr)\\n'.format(nri,ndi)\r\n                        #aprint(tempo_str)\r\n                        f.write(tempo_str)\r\n                    elif lino !=3:\r\n                        f.write(lino[:])\r\n                    else:\r\n                        f.write(lino[:]+')')\r\n                f.close()\r\n            if self.verbose:\r\n                print ('>> Computing MEM tomogram <<')\r\n                print ('----------------------------')\r\n            #os.system('gfortran -O -o dopp_input.txt dop.in dop.f clock.f')\r\n            os.system('make dop.out')\r\n            os.system('./dopp dopp.out')\r\n            fo=open('dop.log')\r\n            lines=fo.readlines()\r\n            fo.close()\r\n            #print(clim,rr)\r\n            if self.verbose: print ('----------------------------')\r\n            if lines[-1].split()[0] == 'projection':\r\n                nri = np.float(lines[-1].split()[-1])/np.float(lines[-2].split()[-1])\r\n                ndi = np.float(lines[-1].split()[-2])/np.float(lines[-2].split()[-2])\r\n                print('>> PROJECTION MATRIX TOO SMALL <<')\r\n                print('>> Recomputing with values from Spruit:')\r\n                print('>> ndi = {}, nri = {}'.format(ndi,nri))\r\n            else:\r\n                compile_flag=False\r\n        clim,rr=lines[-2].split()[-1],lines[-2].split()[-2]\r\n        if rr > clim:\r\n            print ('>> NOT CONVERGED: Specified reduced chi^2 not reached: {} > {}'.format(rr,clim))\r\n            sys.exit()\r\n        else:\r\n            if self.verbose:\r\n                print ('>> Succesful Dopmap!')\r\n\r\n\r\n\r\n    def Dopmap(self,dopout = 'dop.out',cmaps = cm.Greys_r,\r\n               limits=None, colorbar=False, negative=False,remove_mean=False,\r\n               corrx=0,corry=0, smooth=False):\r\n        \"\"\"\r\n        Read output files from Henk Spruit's *.out and plot a Doppler map\r\n\r\n        Parameters\r\n        ----------\r\n        dopout : str, Optional\r\n            Name of output file to be read. Default, dop.out\r\n\r\n        cmaps : cmap function,\r\n            Color scheme to use for Doppler map\r\n            - Default, cm.Greys_r\r\n\r\n        limits : array,\r\n            Normalised limtis e.g. [.8,1.1] for colour display. if None,\r\n             automatic Limits will be generated\r\n            - Default, None\r\n\r\n        colorbar : bool,\r\n            Generates an interactive colorbar. (unstable...)\r\n            - Default, True\r\n\r\n        remove_mean : bool,\r\n            Remove an azimuthal mean of the map\r\n            - Default, False\r\n\r\n        corrx, corry : float, float\r\n            Pixel correction for center of removal of azimuthal mean map\r\n\r\n        smooth : bool,\r\n            Apply Gaussian filter to map.\r\n            - Default, False\r\n\r\n\r\n        Returns\r\n        -------\r\n        cbar : object,\r\n            Colorbar object for interactivity\r\n\r\n        data : 2D-array,\r\n            Data cube from Doppler map\r\n\r\n        \"\"\"\r\n        if self.verbose:\r\n            print(\">> Reading {} file\".format(dopout))\r\n        fro=open(dopout,'r')\r\n        lines=fro.readlines()\r\n        fro.close()\r\n\r\n        #READ ALL FILES\r\n        nph,nvp,nv,w0,aa=int(lines[0].split()[0]),int(lines[0].split()[1]),int(lines[0].split()[2]),float(lines[0].split()[3]),float(lines[0].split()[4])\r\n        gamma,abso,atm,dirin=float(lines[1].split()[0]),lines[1].split()[1],lines[1].split()[2],lines[1].split()[3]\r\n\r\n\r\n\r\n\r\n        new = ''.join(lines[2:len(lines)])\r\n        new = new.replace(\"E\",'e')\r\n        war = ''.join(new.splitlines()).split()\r\n        #print(war)\r\n        if self.verbose:\r\n            print(\">> Finished reading dop.out file\")\r\n        pha=np.array(war[:nph]).astype(np.float)/2.0/np.pi\r\n        dum1=war[nph]\r\n        dpha=np.array(war[nph+1:nph+1+nph]).astype(np.float)/2.0/np.pi\r\n        last=nph+1+nph\r\n        vp=np.array(war[last:last+nvp]).astype(np.float)\r\n        dvp=vp[1]-vp[0]\r\n        vp=vp-dvp/2.0\r\n        last=last+nvp\r\n        dm=np.array(war[last:last+nvp*nph]).astype(np.float)\r\n        dm=dm.reshape(nvp,nph)\r\n        last=last+nvp*nph\r\n\r\n\r\n        #print(war[last])\r\n        ih,iw,pb0,pb1,ns,ac,al,clim,norm,wid,af=int(war[last]),int(war[last+1]),float(war[last+2]),float(war[last+3]),int(war[last+4]),float(war[last+5]),float(war[last+6]),float(war[last+7]),int(war[last+8]),float(war[last+9]),float(war[last+10])\r\n        nv,va,dd=int(war[last+11]),float(war[last+12]),war[last+13]\r\n        last=last+14\r\n\r\n        im=np.array(war[last:last+nv*nv]).astype(np.float)\r\n        im=im.reshape(nv,nv)\r\n\r\n        last=last+nv*nv\r\n        ndum,dum2,dum3=int(war[last]),war[last+1],war[last+2]\r\n        last=last+3\r\n        dmr=np.array(war[last:last+nvp*nph]).astype(np.float)\r\n        dmr=dmr.reshape(nvp,nph)\r\n        last=last+nvp*nph\r\n        ndum,dum4,dum2,dum3=int(war[last]),int(war[last+1]),war[last+2],war[last+3]\r\n        last=last+4\r\n        dpx=np.array(war[last:last+nv*nv]).astype(np.float)\r\n        dpx=dpx.reshape(nv,nv)\r\n        dpx = np.array(dpx)\r\n        vp = np.array(vp)/1e5\r\n        data = im\r\n\r\n        data[data == 0.0] = np.nan\r\n\r\n        new_data = (data - np.nanmin(data) )/np.nanmax(data)\r\n        #new_data = np.arcsinh(new_data)\r\n        if limits == None:\r\n            limits = [np.nanmax((new_data))*0.95,np.nanmax((new_data))*1.05]\r\n        if self.verbose:\r\n            print(\"Limits auto {:6.5f} {:6.5f}\".format(np.nanmedian(data)*0.8,np.nanmedian(data)*1.2))\r\n            print(\"Limits user {:6.5f} {:6.5f}\".format(limits[0],limits[1]))\r\n            print(\"Limits min={:6.5f}, max={:6.5f}\".format(np.nanmin(data),np.nanmax(data)))\r\n        # Here comes the plotting\r\n        fig = plt.figure(num='Doppler Map',figsize=(8.57,8.57))\r\n        plt.clf()\r\n        ax = fig.add_subplot(111)\r\n        ax.minorticks_on()\r\n        ll = ~(np.isnan(data) )\r\n        #data[~ll] = np.nan\r\n        delvp = vp[1]-vp[0]\r\n        #print(\">>> VP\",min(vp),max(vp),delvp)\r\n        vpmin, vpmax = min(vp)-.5/delvp,max(vp)+.5/delvp,\r\n\r\n        if smooth:\r\n            interp_mode = 'gaussian'\r\n        else:\r\n            interp_mode = 'nearest'\r\n        if remove_mean:\r\n            rad_prof = radial_profile(data,[data[0].size/2-corrx,data[0].size/2-corry])\r\n            meano = create_profile(data,rad_prof,[data[0].size/2-corrx,data[0].size/2-corry])\r\n            qq = ~np.isnan(data - meano)\r\n        if negative:\r\n            if remove_mean:\r\n                #print data[ll].max(),meano[qq].max()\r\n                img = plt.imshow((data - meano)/(data - meano)[qq].max(),\r\n                    interpolation=interp_mode, cmap=cmaps,aspect='equal',\r\n                    origin='lower',extent=(vpmin, vpmax,vpmin, vpmax ),\r\n                    vmin=limits[0],vmax=limits[1])\r\n            else:\r\n                img = plt.imshow(-(data)/data[ll].max(),\r\n                    interpolation=interp_mode, cmap=cmaps,aspect='equal',\r\n                    origin='lower',extent=(vpmin, vpmax,vpmin, vpmax),\r\n                    vmin=-limits[1],vmax=-limits[0] )\r\n        else:\r\n            if remove_mean:\r\n                #print data[ll].max(),meano[qq].max()\r\n                img = plt.imshow((data - meano)/(data - meano)[qq].max(),\r\n                    interpolation=interp_mode, cmap=cmaps,aspect='equal',\r\n                    origin='lower',extent=(vpmin, vpmax,vpmin, vpmax),\r\n                    vmin=limits[0],vmax=limits[1])\r\n            else:\r\n                #print(np.nanmin(data),np.nanmax(data))\r\n                #new_data = (data - np.nanmin(data) )/np.nanmax(data)\r\n                #new_data = data\r\n                #print(np.nanmedian(data),np.nanstd(data))\r\n                print(\"Limits min={:6.3f}, max={:6.3f}\".format(np.nanmin(new_data),np.nanmax(new_data)))\r\n                img = plt.imshow(new_data,interpolation=interp_mode,\r\n                    cmap=cmaps,aspect='equal',origin='lower',\r\n                    extent=(vpmin, vpmax,vpmin, vpmax ),\r\n                    vmin=limits[0],vmax=limits[1] )\r\n\r\n        axlimits=[min(vp), max(vp),min(vp), max(vp) ]\r\n        plt.axis(axlimits)\r\n        #plt.axvline(x=0.0,linestyle='--',color='white')\r\n\r\n        plt.xlabel('V$_x$ / km s$^{-1}$')\r\n        plt.ylabel('V$_y$ / km s$^{-1}$')\r\n        plt.tight_layout()\r\n        plt.show()\r\n        if colorbar:\r\n            cbar = plt.colorbar(format='%.1f',orientation='vertical',\r\n                                fraction=0.046, pad=0.04)\r\n            cbar.set_label('Normalised Flux')\r\n            cbar.set_norm(MyNormalize(vmin=limits[0],vmax=limits[1],\r\n                                                  stretch='log'))\r\n            cbar = DraggableColorbar(cbar,img)\r\n            cbar.connect()\r\n        else:\r\n            cbar=1\r\n\r\n        '''\r\n        if remove_mean:\r\n            #print data.size/2\r\n            rad_prof = radial_profile(data,[data[0].size/2,data[0].size/2])\r\n            mean = create_profile(data,rad_prof,[data[0].size/2,data[0].size/2])\r\n            ll = ~np.isnan(mean)\r\n            fig = plt.figure('Mean')\r\n            plt.clf()\r\n            fig.add_subplot(211)\r\n            plt.plot(rad_prof)\r\n            fig.add_subplot(212)\r\n\r\n            plt.show()\r\n        '''\r\n        return cbar,new_data\r\n\r\n\r\n    def Reco(self, cmaps=plt.cm.binary, limits=None, colorbar=True):\r\n        \"\"\"\r\n        Plot original and reconstructed trail spectra from Henk Spruit's *.out\r\n\r\n        Parameters\r\n        ----------\r\n        cmaps : cmap function,\r\n            Color scheme to use for Doppler map\r\n            - Default, cm.Greys_r\r\n\r\n        limits : array,\r\n            Normalised limtis e.g. [.8,1.1] for colour display. if None,\r\n             automatic Limits will be generated\r\n            - Default, None\r\n\r\n        colorbar : bool,\r\n            Generates an interactive colorbar. (unstable...)\r\n            - Default, True\r\n\r\n        Returns\r\n        -------\r\n        cbar : object,\r\n            Colorbar object for interactivity\r\n\r\n        data : 2D-array,\r\n            Data cube from reconstructed spectra\r\n\r\n        \"\"\"\r\n        fro=open('dop.out','r')\r\n        lines=fro.readlines()\r\n        fro.close()\r\n\r\n        #READ ALL FILES\r\n        nph,nvp,nv,w0,aa=int(lines[0].split()[0]),int(lines[0].split()[1]),int(lines[0].split()[2]),float(lines[0].split()[3]),float(lines[0].split()[4])\r\n        gamma,abso,atm,dirin=float(lines[1].split()[0]),lines[1].split()[1],lines[1].split()[2],lines[1].split()[3]\r\n\r\n        #print(\">> Reading dop.out file\")\r\n        #flag=0\r\n        #for i in np.arange(3,len(lines),1):\r\n        #    if flag==0:\r\n        #        temp=lines[i-1]+lines[i]\r\n        #        flag=1\r\n        #    else:\r\n        #        temp=temp+lines[i]\r\n        #        war=temp.split()\r\n        new = ''.join(lines[2:len(lines)])\r\n        new = new.replace(\"E\",'e')\r\n        war = ''.join(new.splitlines()).split()\r\n        #print(war)\r\n        #print(\">> Finished reading dop.out file\")\r\n        pha=np.array(war[:nph]).astype(np.float)/2.0/np.pi\r\n        dum1=war[nph]\r\n        dpha=np.array(war[nph+1:nph+1+nph]).astype(np.float)/2.0/np.pi\r\n        last=nph+1+nph\r\n        vp=np.array(war[last:last+nvp]).astype(np.float)\r\n        dvp=vp[1]-vp[0]\r\n        vp=vp-dvp/2.0\r\n        last=last+nvp\r\n        dm=np.array(war[last:last+nvp*nph]).astype(np.float)\r\n        dm=dm.reshape(nvp,nph)\r\n        last=last+nvp*nph\r\n\r\n\r\n        #print(war[last])\r\n        ih,iw,pb0,pb1,ns,ac,al,clim,norm,wid,af=int(war[last]),int(war[last+1]),float(war[last+2]),float(war[last+3]),int(war[last+4]),float(war[last+5]),float(war[last+6]),float(war[last+7]),int(war[last+8]),float(war[last+9]),float(war[last+10])\r\n        nv,va,dd=int(war[last+11]),float(war[last+12]),war[last+13]\r\n        last=last+14\r\n\r\n        im=np.array(war[last:last+nv*nv]).astype(np.float)\r\n        im=im.reshape(nv,nv)\r\n\r\n        last=last+nv*nv\r\n        ndum,dum2,dum3=int(war[last]),war[last+1],war[last+2]\r\n        last=last+3\r\n        dmr=np.array(war[last:last+nvp*nph]).astype(np.float)\r\n        dmr=dmr.reshape(nvp,nph)\r\n        last=last+nvp*nph\r\n        ndum,dum4,dum2,dum3=int(war[last]),int(war[last+1]),war[last+2],war[last+3]\r\n        last=last+4\r\n        dpx=np.array(war[last:last+nv*nv]).astype(np.float)\r\n        dpx=dpx.reshape(nv,nv)\r\n        dpx = np.array(dpx)\r\n        vp = np.array(vp)/1e5\r\n        data = im\r\n\r\n        data[data <= 0.0] = np.nan\r\n        dpx[dpx <= 0.0] = np.nan\r\n        #dmr[dmr <= 0.0] = np.nan\r\n        #dm[dm <= 0.0] = np.nan\r\n        #print(pha)\r\n        #print(self.nbins)\r\n        trail_dm,phase = rebin_trail(vp, dm.T, pha, self.nbins, self.delta_phase,\r\n                                    rebin_wave=None)\r\n\r\n        trail_dmr,phase = rebin_trail(vp, dmr.T, pha, self.nbins, self.delta_phase,\r\n                                    rebin_wave=None)\r\n\r\n        delvp = vp[1]-vp[0]\r\n        x1_lim = min(vp)\r\n        x2_lim = max(vp)\r\n        #print(phase)\r\n        if limits == None:\r\n            limits = [np.median(dmr/np.nanmax(dmr))*0.8,\r\n                      np.median(dmr/np.nanmax(dmr))*1.2]\r\n\r\n        # Now lets do the plotting\r\n        figor = plt.figure('Reconstruction',figsize=(10,8))\r\n        plt.clf()\r\n        ax1 = figor.add_subplot(121)\r\n        print(np.nanmax(trail_dm))\r\n        imgo = plt.imshow(trail_dm.T/np.nanmax(trail_dm),interpolation='nearest',\r\n                    cmap=cmaps,aspect='auto',origin='upper',\r\n                    extent=(x1_lim,x2_lim,phase[0],\r\n                            phase[-1]+1/self.nbins),\r\n                    vmin=limits[0], vmax=limits[1])\r\n\r\n        ax1.set_xlabel('Velocity / km s$^{-1}$')\r\n        ax1.set_ylabel('Orbital Phase')\r\n\r\n        if colorbar:\r\n            cbar2 = plt.colorbar(format='%.1e',orientation='vertical',\r\n                                fraction=0.046, pad=0.04)\r\n            cbar2.set_label('Normalised Flux')\r\n            cbar2.set_norm(MyNormalize(vmin=np.median(dm/np.nanmax(dm))*0.8,\r\n                                    vmax=np.median(dm/np.nanmax(dm))*1.1,\r\n                                    stretch='linear'))\r\n            cbar2 = DraggableColorbar(cbar2,imgo)\r\n            cbar2.connect()\r\n        else:\r\n            cbar2=1\r\n        ax2 = figor.add_subplot(122)\r\n        print(np.nanmax(trail_dmr))\r\n        imgo = plt.imshow(trail_dmr.T/np.nanmax(trail_dmr),interpolation='nearest',\r\n                    cmap=cmaps,aspect='auto',origin='upper',\r\n                    extent=(x1_lim,x2_lim,phase[0],\r\n                            phase[-1]+1/self.nbins),\r\n                    vmin=limits[0], vmax=limits[1])\r\n        ax2.set_xlabel('Velocity / km s$^{-1}$')\r\n        ax2.set_yticklabels([])\r\n        plt.tight_layout(w_pad=0)\r\n        if colorbar:\r\n            cbar3 = plt.colorbar(format='%.1e',orientation='vertical',\r\n                                fraction=0.046, pad=0.04)\r\n            cbar3.set_label('Normalised Flux')\r\n            cbar3.set_norm(MyNormalize(vmin=np.median(dmr/np.nanmax(dmr))*0.8,\r\n                                    vmax=np.median(dmr/np.nanmax(dmr))*1.1,\r\n                                    stretch='linear'))\r\n            cbar3 = DraggableColorbar(cbar3,imgo)\r\n            cbar3.connect()\r\n        else:\r\n            cbar3=1\r\n        return cbar2,cbar3,dmr,dm\r\n\r\ndef rebin_trail(waver, flux, input_phase, nbins, delp, rebin_wave=None):\r\n    \"\"\"\r\n\r\n    \"\"\"\r\n    phase = np.linspace(0,2,nbins*2+1,endpoint=True) - 1./(nbins)/2.\r\n    phase = np.concatenate((phase,[2.0+1./(nbins)/2.]))\r\n    phase_dec = phase - np.floor(phase)\r\n\r\n    trail = np.zeros((waver.size,phase.size))\r\n\r\n    tots = trail.copy()\r\n    #print(phases.size)\r\n    for i in range(input_phase.size):\r\n        #print(\"spec phase = \",grid['phase'][i])\r\n        dist = phase_dec - (input_phase[i]+delp/2.)\r\n        #print(dist)\r\n        dist[np.abs(dist)>1./nbins] = 0.\r\n        #print(dist/delpha)\r\n        dist[dist>0] = 0.0\r\n        #print(dist)\r\n        weights = np.abs(dist)/(1./nbins)\r\n        #print(weights)\r\n        #print('---------------')\r\n        dist = phase_dec - (input_phase[i]-delp/2.)\r\n        #print(dist)\r\n        dist[np.abs(dist)>1./nbins] = 0.0\r\n        #print(dist)\r\n        dist[dist>0] = 0.0\r\n        #print(dist/delpha)\r\n        dist[np.abs(dist)>0] = 1.0 - (np.abs(dist[np.abs(dist)>0]))/(1./nbins)\r\n        weights += dist\r\n        #print(weights)\r\n        temp = trail.copy().T\r\n\r\n        for j in range(phase.size):\r\n            if rebin_wave == None:\r\n                temp[j] =  flux[i] * weights[j]\r\n                temp[j] =  flux[i] * weights[j]\r\n            else:\r\n                temp[j] = np.interp(waver,wave[rr],\r\n                          flux[i]) * weights[j]\r\n                temp[j] = np.interp(waver,wave[rr],\r\n                          slux[i]) * weights[j]\r\n        trail+=temp.T\r\n        tots += weights\r\n\r\n    trail /= tots\r\n    return trail,phase\r\n\r\nclass DraggableColorbar(object):\r\n    def __init__(self, cbar, mappable):\r\n        self.cbar = cbar\r\n        self.mappable = mappable\r\n        self.press = None\r\n        self.cycle = sorted([i for i in dir(plt.cm) if hasattr(getattr(plt.cm,i),'N')])\r\n        self.index = self.cycle.index(cbar.get_cmap().name)\r\n\r\n    def connect(self):\r\n        \"\"\"connect to all the events we need\"\"\"\r\n        self.cidpress = self.cbar.patch.figure.canvas.mpl_connect(\r\n            'button_press_event', self.on_press)\r\n        self.cidrelease = self.cbar.patch.figure.canvas.mpl_connect(\r\n            'button_release_event', self.on_release)\r\n        self.cidmotion = self.cbar.patch.figure.canvas.mpl_connect(\r\n            'motion_notify_event', self.on_motion)\r\n        self.keypress = self.cbar.patch.figure.canvas.mpl_connect(\r\n            'key_press_event', self.key_press)\r\n\r\n    def on_press(self, event):\r\n        \"\"\"on button press we will see if the mouse is over us and store some data\"\"\"\r\n        if event.inaxes != self.cbar.ax: return\r\n        self.press = event.x, event.y\r\n\r\n    def key_press(self, event):\r\n        if event.key=='down':\r\n            self.index += 1\r\n        elif event.key=='up':\r\n            self.index -= 1\r\n        if self.index<0:\r\n            self.index = len(self.cycle)\r\n        elif self.index>=len(self.cycle):\r\n            self.index = 0\r\n        cmap = self.cycle[self.index]\r\n        self.cbar.set_cmap(cmap)\r\n        self.cbar.draw_all()\r\n        self.mappable.set_cmap(cmap)\r\n        #self.mappable.get_axes().set_title(cmap)\r\n        self.cbar.patch.figure.canvas.draw()\r\n\r\n    def on_motion(self, event):\r\n        'on motion we will move the rect if the mouse is over us'\r\n        if self.press is None: return\r\n        if event.inaxes != self.cbar.ax: return\r\n        xprev, yprev = self.press\r\n        dx = event.x - xprev\r\n        dy = event.y - yprev\r\n        self.press = event.x,event.y\r\n        #print 'x0=%f, xpress=%f, event.xdata=%f, dx=%f, x0+dx=%f'%(x0, xpress, event.xdata, dx, x0+dx)\r\n        scale = self.cbar.norm.vmax - self.cbar.norm.vmin\r\n        perc = 0.03\r\n        if event.button==1:\r\n            self.cbar.norm.vmin -= (perc*scale)*np.sign(dy)\r\n            self.cbar.norm.vmax -= (perc*scale)*np.sign(dy)\r\n        elif event.button==3:\r\n            self.cbar.norm.vmin -= (perc*scale)*np.sign(dy)\r\n            self.cbar.norm.vmax += (perc*scale)*np.sign(dy)\r\n        self.cbar.draw_all()\r\n        self.mappable.set_norm(self.cbar.norm)\r\n        self.cbar.patch.figure.canvas.draw()\r\n\r\n\r\n    def on_release(self, event):\r\n        \"\"\"on release we reset the press data\"\"\"\r\n        self.press = None\r\n        self.mappable.set_norm(self.cbar.norm)\r\n        self.cbar.patch.figure.canvas.draw()\r\n\r\n    def disconnect(self):\r\n        \"\"\"disconnect all the stored connection ids\"\"\"\r\n        self.cbar.patch.figure.canvas.mpl_disconnect(self.cidpress)\r\n        self.cbar.patch.figure.canvas.mpl_disconnect(self.cidrelease)\r\n        self.cbar.patch.figure.canvas.mpl_disconnect(self.cidmotion)\r\n\r\n\r\ndef radial_profile(data, center):\r\n    \"\"\"Calculate radial profile for Dopple map\"\"\"\r\n    y, x = np.indices((data.shape))\r\n    r = np.sqrt((x - center[0])**2 + (y - center[1])**2)\r\n    r = r.astype(np.int)\r\n\r\n    tbin = np.bincount(r.ravel(), data.ravel())\r\n    nr = np.bincount(r.ravel())\r\n    radialprofile = tbin / nr\r\n    return radialprofile\r\n\r\ndef create_profile(data,profile, center):\r\n    y, x = np.indices((data.shape))\r\n    r = np.sqrt((x - center[0])**2 + (y - center[1])**2)\r\n    r = r.astype(np.int)\r\n    mean = data*0.0 + 1.0\r\n    for i in np.arange(r.max()):\r\n    \t#print i\r\n    \tss = np.where(r == i)\r\n    \t#print profile[i]\r\n    \tmean[ss] = mean[ss] * profile[i]\r\n    ll = ~np.isnan(mean)\r\n    #print mean[ll]\r\n    return mean\r\n\r\ndef stream(q,k1,porb,m1,inc,colors='k',both_lobes=False,title=True,label=None):\r\n    \"\"\"Calculate the Ballistic and Keplerian trajetories for a given binary\r\n    system under Roche lobe geometry. This will be plotted directly in the\r\n    Doppler tomogram\r\n    \"\"\"\r\n    xl,yl,xi,yi,wout,wkout = stream_calculate(q,ni = 100,nj = 100)\r\n\r\n    #print''\r\n    azms=-70\r\n    az=np.arctan(yi/xi)\r\n\r\n    for i in np.arange(len(az)):\r\n        if xi[i] < 0.0:\r\n            az[i]=az[i] + np.pi\r\n            #print az[i],az[i]*180/np.pi\r\n    az=az*180/np.pi\r\n    i=0\r\n    for j in np.arange(az.size):\r\n        #print az[j]\r\n        i=i+1\r\n        if az[j] < azms:\r\n            break\r\n\r\n    vxi = np.real(wout)\r\n    vyi = np.imag(wout)\r\n    vkxi = np.real(wkout)\r\n    vkyi = np.imag(wkout)\r\n    #print az[0],i\r\n    porb=24*3600*porb           # in seconds\r\n    omega=2*np.pi/porb\r\n    gg=6.667e-8                     # Gravitational Constant, cgs\r\n    msun=1.989e33\r\n    cm=q/(1.0+q)\r\n    nvp=1000\r\n    vxp,vyp,vkxp,vkyp,rr=[],[],[],[],[]\r\n\r\n    xl=xl-cm\r\n    inc=np.pi*inc/180.0\r\n    a=(gg*m1*msun*(1.0+q))**(1./3)/omega**(2./3)     # Orbital Separation\r\n    vfs=1e5\r\n    vs=omega*a/vfs\r\n    rd=0\r\n    r=1\r\n    vxi=vxi[:i]\r\n    vyi=vyi[:i]\r\n    vkxi=vkxi[:i]\r\n    vkyi=vkyi[:i]\r\n    az=az[:i]\r\n    si=np.sin(inc)\r\n    vx=vxi*si*vs\r\n    vy=vyi*si*vs\r\n    vkx=vkxi*si*vs\r\n    vky=vkyi*si*vs\r\n    xl=xl*vs*si\r\n    yl=yl*vs*si\r\n    npl=len(az)\r\n    #fig = plt.figure(num='Doppler Map')\r\n    #ax = fig.add_subplot(111)\r\n    #dist = np.sqrt((vx - vkx)**2 + (vy - vky)**2)\r\n    #dist = np.abs(vy-vky)\r\n    #print np.abs(vy-vky)[:12],dist[:12]\r\n    #ss = np.where( dist == min(dist) )[0]\r\n    #print vy[-1],vky[-1],vx[-1],vx[-1]\r\n    #print vx[ss],vy[ss]\r\n    plt.plot(vx[:],vy[:],color=colors,marker='')\r\n    plt.plot(vkx[:],vky[:],color=colors,marker='')\r\n    plt.plot(yl[int(yl.size/4):3*int(yl.size/4)],xl[int(xl.size/4):3*int(xl.size/4)],color=colors)\r\n    if title: plt.title(r'$i$='+str(inc/np.pi*180.)[:5]+', M$_1$='+str(m1)+' M$_{\\odot}$, $q$='+str(q)+', P$_{orb}$='+str(porb/3600.)[:4]+' hr')\r\n    ## 0,0 systemic velocity, km/s\r\n    vy1 = cm * vs * si\r\n    plt.plot(0.,0.,'x',ms = 9,c = colors,alpha=0.3)\r\n    ## 0,-K1 systemic velocity, km/s\r\n    plt.plot(0.,-vy1,'+',ms = 10,c = colors,alpha=0.7)\r\n    plt.plot(0.,(1.0-cm)*vs*si,'+',ms = 10,c = colors,alpha=0.7)\r\n\r\n    if both_lobes:\r\n        plt.plot(np.concatenate((yl[3*int(xl.size/4):],yl[:int(yl.size/4)]),axis=0),\r\n        np.concatenate((xl[3*int(xl.size/4):],xl[:int(yl.size/4)]),axis=0),color=colors,ls='--')\r\n        #plt.plot(yl,xl,color=colors)\r\n    else:\r\n        plt.plot(yl[int(yl.size/4):3*int(yl.size/4)],xl[int(xl.size/4):3*int(xl.size/4)],color=colors)\r\n\r\n    if label != None: plt.text(0.12, 0.1,label, ha='center', va='center', transform=ax.transAxes)\r\n    plt.tight_layout()\r\n\r\ndef stream_calculate(qm,ni = 100,nj = 100):\r\n    '''\r\n    calculates Roche lobes and integrates path of stream from L1\r\n    '''\r\n    nmax = 10000\r\n    xout = np.zeros(nmax)\r\n    yout = np.zeros(nmax)\r\n    rout = np.zeros(nmax)\r\n    wout = np.zeros(nmax,dtype=np.complex)\r\n    wkout = np.zeros(nmax,dtype=np.complex)\r\n    if np.abs(qm - 1.) < 1e-4: qm = 1e-4\r\n    rd = 0.1\r\n    if qm <= 0.0:\r\n        print ('Mass ratio <= 0. Does not compute. Will exit.')\r\n        return\r\n    rl1 = rlq1(qm)\r\n\r\n    x,y = lobes(qm,rl1,ni,nj)\r\n    ## Center of mass relative to M1\r\n    cm = qm / (1.0 + qm)\r\n    ## Coordinates of M1 and M2\r\n    z1=-cm\r\n    z2=1-cm\r\n    wm1=np.conj(np.complex(0.,-cm))\r\n    ## Start at L1-eps with v=0\r\n    eps=1e-3\r\n    z = np.complex(rl1 - cm -eps,0.)\r\n    w = 0\r\n    zp,wp = eqmot(z,w,z1,z2,qm)\r\n    t=0\r\n    dt=1e-4\r\n    isa=0\r\n    it=0\r\n    r=1\r\n    ist=0\r\n    ph=0.\r\n    phmax=6\r\n    while it < nmax and ph < phmax:\r\n        dz,dw = intrk(z,w,dt,z1,z2,qm)\r\n        z=z+dz\r\n        w=w+dw\r\n        t=t+dt\r\n        if np.abs(dz)/np.abs(z) > 0.02: dt=dt/2.\r\n        if np.abs(dz)/np.abs(z) < 0.005: dt=2.*dt\r\n\r\n        dph= -np.imag(z*np.conj(z-dz))/np.abs(z)/np.abs(z-dz)\r\n        ph=ph+dph\r\n        ##velocity in inertial frame\r\n        ##change by Guillaume\r\n        wi=w+np.complex(0,1.)*z\r\n        ## unit vector normal to kepler orbit\r\n        rold=r\r\n        r=np.abs(z-z1)\r\n\r\n        if ist == 0 and rold < r:\r\n            ist=1\r\n            rmin=rold\r\n\r\n        # kepler velocity of circular orbit in potential of M1, rel. to M1\r\n        vk=1.0/np.sqrt(r*(1.0+qm))\r\n        # unit vector in r\r\n        no = np.conj(z-z1)/r\r\n        wk = -vk*no*np.complex(0.,1.)\r\n        # same but rel. to cm, this is velocity in inertial frame\r\n        wk = wk+wm1\r\n        # velocity normal to disk edge, in rotating frame\r\n        dot = no * w\r\n        # velocity parallel to disk edge\r\n        par = np.imag(no*w)\r\n        # reflected velocity\r\n        wr = w - 2.0*dot*no\r\n        #        write(*,'(f8.4,1p9e11.3)')t,z,w,wk,wr,r\r\n        xout[it] = np.real(z)+cm\r\n        yout[it] = -np.imag(z)\r\n        rout[it] = np.sqrt(xout[it]**2+yout[it]**2)\r\n        # change by Guillaume\r\n        wout[it]= wi\r\n        wkout[it]=np.conj(wk)\r\n        if it > 0:\r\n            xo=xout[it]\r\n            yo=yout[it]\r\n            phi=np.arctan(yo/xo)\r\n            if rout[it] < rd and rout[it-1] >  rd:\r\n            ## write(*,'('' r,x,y,phi,vs,vk,dot,par'',8f8.3)')\r\n            ##    rout(it),x,y,phi,real(w),vk,dot,par\r\n            ## write(*,'('' w,no'',4f8.3)')w,no\r\n                xo=xout[it-1]\r\n                yo=yout[it-1]\r\n                phi=np.arctan(yo/xo)\r\n            # write(*,'('' r,x,y,phi'',4f8.3)')rout(it-1),x,y,phi\r\n\r\n        if isa == 0 and yout[it] < 0:\r\n            isa=1\r\n            ra=np.abs(z-z1)\r\n            wc=np.conj(w)+np.complex(0.,1.)*np.conj(z-z1)\r\n            ang=np.abs(np.imag((z-z1)*np.conj(wc)))\r\n        it+=1\r\n    return x,y,xout,yout,wout,wkout\r\n\r\ndef rlq1(q):\r\n    '''\r\n    Calulates roche lobe radius.\r\n    '''\r\n    if np.abs(1.0 - q) < 1e-4:\r\n        rlq = 0.5\r\n        return rlq\r\n    rl = 0\r\n    rn = 1.0 - q\r\n    while np.abs(rl/rn-1.) > 1e-4:\r\n        rl=rn\r\n        f=q/(1.-rl)**2-1./rl**2+(1.+q)*rl-q\r\n        fa=2.*q/(1-rl)**3+2/rl**3+(1.+q)\r\n        rn=rl-f/fa\r\n    rlq1 = rn\r\n    return rlq1\r\n\r\n\r\n\r\ndef lobes(q,rs,ni,nj):\r\n    '''\r\n    SUBROUTINE\r\n    '''\r\n    r = np.zeros((ni,nj))\r\n    ch = np.zeros(ni)\r\n    ps = np.zeros(nj)\r\n    x  = np.zeros(ni)\r\n    y  = np.zeros(nj)\r\n    x2 = np.zeros(ni)\r\n    y2 = np.zeros(nj)\r\n    nc = ni\r\n    nop = nj\r\n\r\n    r,ch,ps = surface(q,rs,nc,nop,r,ch,ps)\r\n    j=0\r\n    for i in np.arange(nc):\r\n        x[i] = 1.0 -r[i,j]*np.cos(ch[i])\r\n        y[i] = -r[i,j] * np.sin(ch[i])\r\n\r\n    r,ch,ps = surface(1./q,1.-rs,nc,nop,r,ch,ps)\r\n    j=0\r\n    for i in np.arange(nc):\r\n        x2[i] = r[i,j] * np.cos(ch[i])\r\n        y2[i] = r[i,j] * np.sin(ch[i])\r\n    xt = np.concatenate((x2[::-1],x,x[::-1],x2))\r\n    yt = np.concatenate((y2[::-1],-y,y[::-1],-y2))\r\n    return xt,yt\r\n\r\n\r\ndef pot(q,x,y,z):\r\n    '''\r\n    FUNCTION\r\n    Roche potential. coordinates centered on M2,\r\n    z along rotation axis, x toward M1\r\n    pr is gradient in radius from M2\r\n    first transform to polar coordinates w/r rotation axis\r\n    '''\r\n    r = np.sqrt(x*x+y*y+z*z)\r\n    if (r == 0):\r\n        print ('r=0 in pot')\r\n        stop\r\n    rh = np.sqrt(x*x+y*y)\r\n    st=rh/r\r\n    if rh == 0:\r\n        cf=1\r\n    else:\r\n        cf=x/rh\r\n\r\n    r2 = 1. / (1. + q)\r\n    r1 = np.sqrt(1.0+r**2-2.0*r*cf*st)\r\n    pot=-1.0/r-1.0/q/r1-0.5*(1.0/q+1.0)*(r2**2+(r*st)**2-2.0*r2*r*cf*st)\r\n    pr=1.0/r**2+1.0/q/(r1**3)*(r-cf*st)-0.5*(1.0/q+1)*2.0*(r*st*st-r2*cf*st)\r\n    return pot,pr\r\n\r\n\r\ndef surface(q,rs,nc,nop,r,ch,ps):\r\n    '''\r\n    SUBROUTINE\r\n    Roche surface around M2, coordinates on surface are ch, ps.\r\n    ch: polar angle from direction to M1; ps: corresponding azimuth, counting\r\n    from orbital plane.\r\n    q:mass ratio, rs: radius of surface at point facing M1\r\n    nc, np: number of chi's, psi's.\r\n    output:\r\n    r(nf,nt): radius. ch, ps: chi and psi arrays\r\n    '''\r\n    r = np.zeros((100,100))\r\n    chi = [],ps\r\n    dc = np.pi/nc\r\n    ch[0] = 0\r\n    for i in np.arange(nc-1)+1:\r\n        ch[i] = float((i-1.0))*np.pi/(nc-1.)\r\n    ps[0] = 0\r\n    for j in np.arange(nop-1)+1:\r\n        ps[i] = float((j-1.0))*2.*np.pi/nop\r\n    rs1 = 1.0 -rs\r\n    fs,pr = pot(q,rs1,0.0,0.0)\r\n\r\n    ## max no of iterations\r\n    im = 20\r\n\r\n    for i in np.arange(nop):\r\n        cp = np.cos(ps[i])\r\n        sp = np.sin(ps[i])\r\n        rx = (1.0 - dc) * rs1\r\n        r[0,i] = rs1\r\n\r\n        for k in np.arange(nc-1)+1:\r\n            x  = np.cos(ch[k])\r\n            sc = np.sin(ch[k])\r\n            y  = sc * cp\r\n            z  = sc * sp\r\n            j  = 0\r\n            f  = 1\r\n            while (j < im ) and np.abs(f - fs) > 1e-4 or j == 0:\r\n                j = j+1\r\n                r1 = rx\r\n                f,pr = pot(q,r1*x,r1*y,r1*z)\r\n                rx = r1 - (f - fs)/pr\r\n                if rx > rs1: rx = rs1\r\n            if j >= im:\r\n                print( 'No conv in surf',k,i,ch[k],ps[i])\r\n                stop\r\n\r\n            r[k,i] = rx\r\n\r\n    return r,ch,ps\r\n\r\n\r\ndef eqmot(z,w,z1,z2,qm):\r\n    zr1 = z-z1\r\n    zr2 = z-z2\r\n    ## c change by Guillaume : - sign in Coriolis\r\n    wp=-(qm*zr2/(np.abs(zr2))**3+zr1/(np.abs(zr1))**3)/(1.0+qm)-np.complex(0.,2.)*w+z\r\n    zp = w\r\n    return zp,wp\r\n\r\n\r\ndef intrk(z,w,dt,z1,z2,qm):\r\n    zx=z\r\n    wx=w\r\n    zp,wp = eqmot(zx,wx,z1,z2,qm)\r\n    hz0=zp*dt\r\n    hw0=wp*dt\r\n    zx=z+hz0/2.\r\n    wx=w+hw0/2.\r\n    zp,wp = eqmot(zx,wx,z1,z2,qm)\r\n    hz1=zp*dt\r\n    hw1=wp*dt\r\n    zx=z+hz1/2.\r\n    wx=w+hw1/2.\r\n    zp,wp = eqmot(zx,wx,z1,z2,qm)\r\n    hz2=zp*dt\r\n    hw2=wp*dt\r\n    zx=z+hz2\r\n    wx=w+hw2\r\n    zp,wp = eqmot(zx,wx,z1,z2,qm)\r\n    hz3=zp*dt\r\n    hw3=wp*dt\r\n    dz=(hz0+2*hz1+2*hz2+hz3)/6.\r\n    dw=(hw0+2*hw1+2*hw2+hw3)/6.\r\n    return dz,dw\r\n\r\ndef xy(r,phi):\r\n  return r*np.cos(phi), r*np.sin(phi)\r\n\r\ndef resonance(j,k,k1,q,porb,m1):\r\n    '''Plots iso-velocity for resonance, in the general\r\n    notation of Whitehurst & King (19XX). Eq. taken from Warner 1995\r\n    page 206-207.\r\n    '''\r\n    k1 *= 1e5\r\n    porb *= 24. * 3600.\r\n    a_1 = k1 / q / (2.0*np.pi) * porb\r\n    a_2 = k1 / (2.0*np.pi) * porb\r\n    a = a_1 + a_2\r\n\r\n    r = (j-k)**(2./3.) / j**(2./3.) / (1.0 + q)**(1./3.) * a\r\n    r_circ = a * 0.60/(1. + q)\r\n    velo = np.sqrt(6.67e-08 * m1 *1.989e+33 / r)/1e5\r\n    velo_circ = np.sqrt(6.67e-08 * m1 *1.989e+33 / r_circ)/1e5\r\n    phis=np.arange(0,6.28,0.01)\r\n\r\n    #print r/69950000000.0,velo\r\n    fig = plt.figure(num='Doppler Map')\r\n    xx,yy = xy(velo,phis)\r\n    plt.plot( xx,yy-k1/1e5,c='k',ls=':')\r\n    #ax = fig.add_subplot(111)\r\n    #circ = plt.Circle((0-k1,0),velo,ls='--',color='k',fill=True)\r\n\r\n\r\n    #print velo_circ,velo\r\n    xx_circ,yy_circ = xy(velo_circ,phis)\r\n    plt.plot( xx_circ,yy_circ-k1/1e5,c='k',ls='-',lw=2)\r\n\r\n    plt.draw()\r\n\r\n\r\ndef colorline(\r\n    x, y, z=None, cmap=plt.get_cmap('copper'), norm=plt.Normalize(0.0, 1.0),\r\n        linewidth=3, alpha=1.0):\r\n    \"\"\"\r\n    http://nbviewer.ipythonp.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb\r\n    http://matplotlib.org/examples/pylab_examples/multicolored_line.html\r\n    Plot a colored line with coordinates x and y\r\n    Optionally specify colors in the array z\r\n    Optionally specify a colormap, a norm function and a line width\r\n    \"\"\"\r\n\r\n    # Default colors equally spaced on [0,1]:\r\n    if z is None:\r\n        z = np.linspace(0.0, 1.0, len(x))\r\n\r\n    # Special case if a single number:\r\n    if not hasattr(z, \"__iter__\"):  # to check for numerical input -- this is a hack\r\n        z = np.array([z])\r\n\r\n    z = np.asarray(z)\r\n\r\n    segments = make_segments(x, y)\r\n    lc = mcoll.LineCollection(segments, array=z, cmap=cmap, norm=norm,\r\n                              linewidth=linewidth, alpha=alpha)\r\n\r\n    ax = plt.gca()\r\n    ax.add_collection(lc)\r\n\r\n    return lc\r\n\r\n\r\ndef make_segments(x, y):\r\n    \"\"\"\r\n    Create list of line segments from x and y coordinates, in the correct format\r\n    for LineCollection: an array of the form numlines x (points per line) x 2 (x\r\n    and y) array\r\n    \"\"\"\r\n\r\n    points = np.array([x, y]).T.reshape(-1, 1, 2)\r\n    segments = np.concatenate([points[:-1], points[1:]], axis=1)\r\n    return segments\r\n\r\ndef test_data():\r\n    module_path = os.path.dirname(os.path.realpath(__file__))\r\n    print(\"-- Copying test data --\")\r\n    os.system('cp -r '+module_path+'/test_data/* ./.')\r\n\r\n\r\nimport numpy as np\r\nimport numpy.ma as ma\r\n\r\nimport matplotlib.cbook as cbook\r\nfrom matplotlib.colors import Normalize\r\n\r\n\r\nclass MyNormalize(Normalize):\r\n    '''\r\n    # The Normalize class is largely based on code provided by Sarah Graves.\r\n    A Normalize class for imshow that allows different stretching functions\r\n    for astronomical images.\r\n    '''\r\n\r\n    def __init__(self, stretch='linear', exponent=5, vmid=None, vmin=None,\r\n                 vmax=None, clip=False):\r\n        '''\r\n        Initalize an APLpyNormalize instance.\r\n\r\n        Optional Keyword Arguments:\r\n\r\n            *vmin*: [ None | float ]\r\n                Minimum pixel value to use for the scaling.\r\n\r\n            *vmax*: [ None | float ]\r\n                Maximum pixel value to use for the scaling.\r\n\r\n            *stretch*: [ 'linear' | 'log' | 'sqrt' | 'arcsinh' | 'power' ]\r\n                The stretch function to use (default is 'linear').\r\n\r\n            *vmid*: [ None | float ]\r\n                Mid-pixel value used for the log and arcsinh stretches. If\r\n                set to None, a default value is picked.\r\n\r\n            *exponent*: [ float ]\r\n                if self.stretch is set to 'power', this is the exponent to use.\r\n\r\n            *clip*: [ True | False ]\r\n                If clip is True and the given value falls outside the range,\r\n                the returned value will be 0 or 1, whichever is closer.\r\n        '''\r\n\r\n        if vmax < vmin:\r\n            raise Exception(\"vmax should be larger than vmin\")\r\n\r\n        # Call original initalization routine\r\n        Normalize.__init__(self, vmin=vmin, vmax=vmax, clip=clip)\r\n\r\n        # Save parameters\r\n        self.stretch = stretch\r\n        self.exponent = exponent\r\n\r\n        if stretch == 'power' and np.equal(self.exponent, None):\r\n            raise Exception(\"For stretch=='power', an exponent should be specified\")\r\n\r\n        if np.equal(vmid, None):\r\n            if stretch == 'log':\r\n                if vmin > 0:\r\n                    self.midpoint = vmax / vmin\r\n                else:\r\n                    raise Exception(\"When using a log stretch, if vmin < 0, then vmid has to be specified\")\r\n            elif stretch == 'arcsinh':\r\n                self.midpoint = -1. / 30.\r\n            else:\r\n                self.midpoint = None\r\n        else:\r\n            if stretch == 'log':\r\n                if vmin < vmid:\r\n                    raise Exception(\"When using a log stretch, vmin should be larger than vmid\")\r\n                self.midpoint = (vmax - vmid) / (vmin - vmid)\r\n            elif stretch == 'arcsinh':\r\n                self.midpoint = (vmid - vmin) / (vmax - vmin)\r\n            else:\r\n                self.midpoint = None\r\n\r\n    def __call__(self, value, clip=None):\r\n\r\n        #read in parameters\r\n        method = self.stretch\r\n        exponent = self.exponent\r\n        midpoint = self.midpoint\r\n\r\n        # ORIGINAL MATPLOTLIB CODE\r\n\r\n        if clip is None:\r\n            clip = self.clip\r\n\r\n        if cbook.iterable(value):\r\n            vtype = 'array'\r\n            val = ma.asarray(value).astype(np.float)\r\n        else:\r\n            vtype = 'scalar'\r\n            val = ma.array([value]).astype(np.float)\r\n\r\n        self.autoscale_None(val)\r\n        vmin, vmax = self.vmin, self.vmax\r\n        if vmin > vmax:\r\n            raise ValueError(\"minvalue must be less than or equal to maxvalue\")\r\n        elif vmin == vmax:\r\n            return 0.0 * val\r\n        else:\r\n            if clip:\r\n                mask = ma.getmask(val)\r\n                val = ma.array(np.clip(val.filled(vmax), vmin, vmax),\r\n                                mask=mask)\r\n            result = (val - vmin) * (1.0 / (vmax - vmin))\r\n\r\n            # CUSTOM APLPY CODE\r\n\r\n            # Keep track of negative values\r\n            negative = result < 0.\r\n\r\n            if self.stretch == 'linear':\r\n\r\n                pass\r\n\r\n            elif self.stretch == 'log':\r\n\r\n                result = ma.log10(result * (self.midpoint - 1.) + 1.) \\\r\n                       / ma.log10(self.midpoint)\r\n\r\n            elif self.stretch == 'sqrt':\r\n\r\n                result = ma.sqrt(result)\r\n\r\n            elif self.stretch == 'arcsinh':\r\n\r\n                result = ma.arcsinh(result / self.midpoint) \\\r\n                       / ma.arcsinh(1. / self.midpoint)\r\n\r\n            elif self.stretch == 'power':\r\n\r\n                result = ma.power(result, exponent)\r\n\r\n            else:\r\n\r\n                raise Exception(\"Unknown stretch in APLpyNormalize: %s\" %\r\n                                self.stretch)\r\n\r\n            # Now set previously negative values to 0, as these are\r\n            # different from true NaN values in the FITS image\r\n            result[negative] = -np.inf\r\n\r\n        if vtype == 'scalar':\r\n            result = result[0]\r\n\r\n        return result\r\n\r\n    def inverse(self, value):\r\n\r\n        # ORIGINAL MATPLOTLIB CODE\r\n\r\n        if not self.scaled():\r\n            raise ValueError(\"Not invertible until scaled\")\r\n\r\n        vmin, vmax = self.vmin, self.vmax\r\n\r\n        # CUSTOM APLPY CODE\r\n\r\n        if cbook.iterable(value):\r\n            val = ma.asarray(value)\r\n        else:\r\n            val = value\r\n\r\n        if self.stretch == 'linear':\r\n\r\n            pass\r\n\r\n        elif self.stretch == 'log':\r\n\r\n            val = (ma.power(10., val * ma.log10(self.midpoint)) - 1.) / (self.midpoint - 1.)\r\n\r\n        elif self.stretch == 'sqrt':\r\n\r\n            val = val * val\r\n\r\n        elif self.stretch == 'arcsinh':\r\n\r\n            val = self.midpoint * \\\r\n                  ma.sinh(val * ma.arcsinh(1. / self.midpoint))\r\n\r\n        elif self.stretch == 'power':\r\n\r\n            val = ma.power(val, (1. / self.exponent))\r\n\r\n        else:\r\n\r\n            raise Exception(\"Unknown stretch in APLpyNormalize: %s\" %\r\n                            self.stretch)\r\n\r\n        return vmin + val * (vmax - vmin)\r\n", "meta": {"hexsha": "678762275493660c5da26d3f34393ebfc1664b3f", "size": 61534, "ext": "py", "lang": "Python", "max_stars_repo_path": "pydoppler/pydoppler.py", "max_stars_repo_name": "Alymantara/pydoppler", "max_stars_repo_head_hexsha": "fad378c08cc171a24e6438b0a2eb3a09d8eeedd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-09-20T07:49:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T08:27:39.000Z", "max_issues_repo_path": "pydoppler/pydoppler.py", "max_issues_repo_name": "Alymantara/pydoppler", "max_issues_repo_head_hexsha": "fad378c08cc171a24e6438b0a2eb3a09d8eeedd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pydoppler/pydoppler.py", "max_forks_repo_name": "Alymantara/pydoppler", "max_forks_repo_head_hexsha": "fad378c08cc171a24e6438b0a2eb3a09d8eeedd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3847038528, "max_line_length": 248, "alphanum_fraction": 0.4944583482, "include": true, "reason": "import numpy,from scipy", "num_tokens": 17396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.1784679801408874}}
{"text": "'''\nReference:\n[1] Towards Deep Learning Models Resistant to Adversarial Attacks\nAleksander Madry, Aleksandar Makelov, Ludwig Schmidt, Dimitris Tsipras, Adrian Vladu\narXiv:1706.06083v3\n'''\nimport torch\nimport numpy as np\nimport os\nimport sys\nimport cv2\nimport torch.nn as nn\nfrom  visdom import Visdom\n\nvis=Visdom(env=\"attacker\")\nimport torch.nn.functional as F\nimport random\nfather_dir = os.path.join('/', *os.path.realpath(__file__).split(os.path.sep)[:-2])\nif not father_dir in sys.path:\n    sys.path.append(father_dir)\nfrom attack.attack_base import AttackBase, clip_eta\n\ndef save_torchimg(img,name):\n    save_im = img[0].detach().permute(1,2,0).cpu().numpy()\n    cv2.imwrite('/cheng/pytracking-master/ltr/attack/{}.jpg'.format(name), save_im)\n\n\n\nclass IPGD(AttackBase):\n    # ImageNet pre-trained mean and std\n    # _mean = torch.tensor(np.array([0.485, 0.456, 0.406]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis])\n    # _std = torch.tensor(np.array([0.229, 0.224, 0.225]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis])\n\n    # _mean = torch.tensor(np.array([0]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis])\n    # _std = torch.tensor(np.array([1.0]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis])\n    def __init__(self, eps = 6 / 255.0, sigma = 6 / 255.0, nb_iter = 5,\n                 norm = np.inf, DEVICE = torch.device('cuda:0'),\n                 mean = torch.tensor(np.array([0.485, 0.456, 0.406]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis]),\n                 std = torch.tensor(np.array([0.229, 0.224, 0.225]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis]), random_start = True):\n        '''\n        :param eps: maximum distortion of adversarial examples\n        :param sigma: single step size\n        :param nb_iter: number of attack iterations\n        :param norm: which norm to bound the perturbations\n        '''\n        self.eps = eps\n        self.sigma = sigma\n        self.nb_iter = nb_iter\n        self.norm = norm\n        self.criterion = torch.nn.MSELoss()#.to(DEVICE)  # MSELoss   L1Loss\n        self.DEVICE = DEVICE\n        self._mean = mean.to(DEVICE)\n        self._std = std.to(DEVICE)\n        self.random_start = random_start\n\n    def single_attack(self, net, inp, label, eta,dimp_filters, target = None):\n        '''\n        Given the original image and the perturbation computed so far, computes\n        a new perturbation.\n        :param net:\n        :param inp: original image\n        :param label:\n        :param eta: perturbation computed so far\n        :return: a new perturbation\n        '''\n        num_sequences = inp.shape[0]\n        adv_inp = inp + eta\n       \n        \n        \n        #vis.heatmap(label[0][0])\n        #net.zero_grad()\n        backbone_feat_cur_all = net.extract_backbone_features(adv_inp)\n        backbone_feat_cur = backbone_feat_cur_all[net.classification_layer]\n        backbone_feat_cur = backbone_feat_cur.view(1, num_sequences, -1,\n                                                       backbone_feat_cur.shape[-2], backbone_feat_cur.shape[-1])\n        \n        dimp_scores_cur = net.dimp_classifier.track_frame(dimp_filters, backbone_feat_cur)     \n        pred = dimp_scores_cur[:, :, :-1, :-1].contiguous()\n        #vis.heatmap(pred[0][0])\n        #pred = net(adv_inp)\n        if target is not None:\n            targets = torch.sum(pred[:, target])\n            grad_sign = torch.autograd.grad(targets, adv_in, only_inputs=True, retain_graph = False)[0].sign()\n            \n        else:\n            \n            loss = self.criterion(pred, label)\n            #print(loss.requires_grad)\n            #loss.requires_grad = True\n            #print(adv_inp.size())\n            #print(loss)\n            #print(adv_inp)\n            #backbone_feat_cur.sum().backward()\n            #grad_sign = adv_inp.grad#.sign()  \n            #print(grad_sign)\n            \n            grad_sign = torch.autograd.grad(loss, adv_inp, only_inputs=True, retain_graph = False)[0].sign()\n            #print(grad_sign.size())\n            \n            \n        #print(loss)\n        adv_inp = adv_inp - 1*grad_sign * (self.sigma / self._std)\n        tmp_adv_inp = adv_inp * self._std +  self._mean\n        \n        tmp_inp = inp * self._std + self._mean\n        tmp_adv_inp = torch.clamp(tmp_adv_inp, 0, 1) ## clip into 0-1\n        #tmp_adv_inp = (tmp_adv_inp - self._mean) / self._std\n        tmp_eta = tmp_adv_inp - tmp_inp\n        tmp_eta = clip_eta(tmp_eta, norm=self.norm, eps=self.eps, DEVICE=self.DEVICE)\n\n        eta = tmp_eta/ self._std\n\n        return eta\n\n    def attack(self, net, inp, data ,label, dimp_filters,target = None):\n        #save_torchimg(inp*255,'oriinput')\n        if self.random_start:\n            eta = torch.FloatTensor(*inp.shape).uniform_(-self.eps, self.eps)\n        else:\n            eta = torch.zeros_like(inp)\n        eta = eta.to(self.DEVICE)\n        eta = (eta - self._mean) / self._std\n        net.eval()\n        #print(label.size())\n        #print(inp.mean())\n        \n        \n        label_adv = torch.zeros_like(label)\n        for r in range(label_adv.size(1)):\n\n            xx = random.randint(1,16)\n            yy = random.randint(1,16)\n            label_adv[0,r,yy,xx] = 1\n            label_adv[0,r,yy+1,xx] = 1\n            label_adv[0,r,yy,xx+1] = 1\n            label_adv[0,r,yy+1,xx+1] = 1\n        #print(label_adv[0][0])\n        inp.requires_grad = True\n        eta.requires_grad = True\n\n        #vis.heatmap(label_adv[0][0])\n        for i in range(self.nb_iter):\n            eta = self.single_attack(net, inp, label_adv, eta,dimp_filters, target)\n            #print(i)\n        #print(eta)\n        \n        #print(eta.max())\n        adv_inp = inp + eta\n        tmp_adv_inp = adv_inp * self._std +  self._mean\n        tmp_adv_inp = torch.clamp(tmp_adv_inp, 0, 1)\n        adv_inp = (tmp_adv_inp - self._mean) / self._std\n        #save_torchimg(adv_inp*255,'advinput')\n        \n        \n        return adv_inp\n\n    def to(self, device):\n        self.DEVICE = device\n        self._mean = self._mean.to(device)\n        self._std = self._std.to(device)\n        self.criterion = self.criterion.to(device)\n\n\nclass IPGD_after(AttackBase):\n    # ImageNet pre-trained mean and std\n    # _mean = torch.tensor(np.array([0.485, 0.456, 0.406]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis])\n    # _std = torch.tensor(np.array([0.229, 0.224, 0.225]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis])\n\n    # _mean = torch.tensor(np.array([0]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis])\n    # _std = torch.tensor(np.array([1.0]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis])\n    def __init__(self, eps = 6 / 255.0, sigma = 3/ 255.0, nb_iter = 5,\n                 norm = np.inf, DEVICE = torch.device('cuda:0'),\n                 mean = torch.tensor(np.array([0.485, 0.456, 0.406]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis]),\n                 std = torch.tensor(np.array([0.229, 0.224, 0.225]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis]), random_start = True):\n        '''\n        :param eps: maximum distortion of adversarial examples\n        :param sigma: single step size\n        :param nb_iter: number of attack iterations\n        :param norm: which norm to bound the perturbations\n        '''\n        self.eps = eps\n        self.sigma = sigma\n        self.nb_iter = nb_iter\n        self.norm = norm\n        self.criterion = torch.nn.MSELoss()#.to(DEVICE)  # MSELoss   L1Loss\n        self.DEVICE = DEVICE\n        self._mean = mean.to(DEVICE)\n        self._std = std.to(DEVICE)\n        self.random_start = random_start\n\n    def single_attack(self, net, inp, label, eta,data,dimp_filters, target = None):\n        '''\n        Given the original image and the perturbation computed so far, computes\n        a new perturbation.\n        :param net:\n        :param inp: original image\n        :param label:\n        :param eta: perturbation computed so far\n        :return: a new perturbation\n        '''\n        num_sequences = inp.shape[0]\n        adv_inp = inp + eta\n       \n        \n        \n        #vis.heatmap(label[0][0])\n        #net.zero_grad()\n        backbone_feat_cur_all = net.extract_backbone_features(adv_inp)\n        backbone_feat_cur = backbone_feat_cur_all[net.classification_layer]\n        backbone_feat_cur = backbone_feat_cur.view(1, num_sequences, -1,\n                                                       backbone_feat_cur.shape[-2], backbone_feat_cur.shape[-1])\n        \n        dimp_scores_cur = net.dimp_classifier.track_frame(dimp_filters, backbone_feat_cur)     \n        dimp_scores_cur = dimp_scores_cur[:, :, :-1, :-1].contiguous()\n\n        predictor_input_data = {'input1': data['input1'], 'input2': backbone_feat_cur,\n                                    'label_prev': data['label_prev'], 'anno_prev': data['anno_prev'],\n                                    'dimp_score_prev': data['dimp_score_prev'], 'dimp_score_cur': dimp_scores_cur,\n                                    'state_prev': data['state_prev'],\n                                    'jitter_info': data['jitter_info']}\n\n        predictor_output = net.predictor(predictor_input_data)\n\n        pred = predictor_output['response']\n        #print(pred.size())\n        \n        #vis.heatmap(pred[0][0])\n        #pred = net(adv_inp)\n        if target is not None:\n            targets = torch.sum(pred[:, target])\n            grad_sign = torch.autograd.grad(targets, adv_in, only_inputs=True, retain_graph = False)[0].sign()\n            \n        else:\n            \n            loss = self.criterion(pred, label)\n            #print(loss.requires_grad)\n            #loss.requires_grad = True\n            #print(adv_inp.size())\n            #print(loss)\n            #print(adv_inp)\n            #backbone_feat_cur.sum().backward()\n            #grad_sign = adv_inp.grad#.sign()  \n            #print(grad_sign)\n            \n            grad_sign = torch.autograd.grad(loss, adv_inp, only_inputs=True, retain_graph = False)[0].sign()\n            #print(grad_sign.size())\n            \n            \n        #print(loss)\n        adv_inp = adv_inp - 1*grad_sign * (self.sigma / self._std)\n        tmp_adv_inp = adv_inp * self._std +  self._mean\n        \n        tmp_inp = inp * self._std + self._mean\n        tmp_adv_inp = torch.clamp(tmp_adv_inp, 0, 1) ## clip into 0-1\n        #tmp_adv_inp = (tmp_adv_inp - self._mean) / self._std\n        tmp_eta = tmp_adv_inp - tmp_inp\n        tmp_eta = clip_eta(tmp_eta, norm=self.norm, eps=self.eps, DEVICE=self.DEVICE)\n\n        eta = tmp_eta/ self._std\n\n        return eta\n\n    def attack(self, net, inp, data,label, dimp_filters,target = None):\n        #save_torchimg(inp*255,'oriinput')\n        if self.random_start:\n            eta = torch.FloatTensor(*inp.shape).uniform_(-self.eps, self.eps)\n        else:\n            eta = torch.zeros_like(inp)\n        eta = eta.to(self.DEVICE)\n        eta = (eta - self._mean) / self._std\n        net.eval()\n        #print(label.size())\n        #print(inp.mean())\n        \n        \n        label_adv = torch.zeros_like(label)\n        for r in range(label_adv.size(1)):\n\n            xx = random.randint(1,16)\n            yy = random.randint(1,16)\n            label_adv[0,r,yy,xx] = 1\n            label_adv[0,r,yy+1,xx] = 1\n            label_adv[0,r,yy,xx+1] = 1\n            label_adv[0,r,yy+1,xx+1] = 1\n        #print(label_adv[0][0])\n        inp.requires_grad = True\n        eta.requires_grad = True\n\n        #vis.heatmap(label_adv[0][0])\n        for i in range(self.nb_iter):\n            eta = self.single_attack(net, inp, label_adv, eta,data, dimp_filters, target)\n            #print(i)\n        #print(eta)\n        \n        #print(eta.max())\n        adv_inp = inp + eta\n        tmp_adv_inp = adv_inp * self._std +  self._mean\n        tmp_adv_inp = torch.clamp(tmp_adv_inp, 0, 1)\n        adv_inp = (tmp_adv_inp - self._mean) / self._std\n        #save_torchimg(adv_inp*255,'advinput')\n        \n        \n        return adv_inp\n\n    def to(self, device):\n        self.DEVICE = device\n        self._mean = self._mean.to(device)\n        self._std = self._std.to(device)\n        self.criterion = self.criterion.to(device)\n\nclass IPGD_siamkys(AttackBase):\n    # ImageNet pre-trained mean and std\n    # _mean = torch.tensor(np.array([0.485, 0.456, 0.406]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis])\n    # _std = torch.tensor(np.array([0.229, 0.224, 0.225]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis])\n\n    # _mean = torch.tensor(np.array([0]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis])\n    # _std = torch.tensor(np.array([1.0]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis])\n    def __init__(self, eps = 6 , sigma = 3 , nb_iter = 5,\n                 norm = np.inf, DEVICE = torch.device('cuda:0'), random_start = True,\n                 mean = 0 ,#torch.tensor(np.array([0.485, 0.456, 0.406]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis]),\n                 std = 1 ):#torch.tensor(np.array([0.229, 0.224, 0.225]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis])):\n        '''\n        :param eps: maximum distortion of adversarial examples\n        :param sigma: single step size\n        :param nb_iter: number of attack iterations\n        :param norm: which norm to bound the perturbations\n        '''\n        self.eps = eps\n        self.sigma = sigma\n        self.nb_iter = nb_iter\n        self.norm = norm\n        self.criterion = torch.nn.MSELoss()#.to(DEVICE)  # MSELoss   L1Loss\n        self.DEVICE = DEVICE\n        self._mean = mean#.to(DEVICE)\n        self._std = std#.to(DEVICE)\n        self.random_start = random_start\n        self.maxpool = nn.MaxPool2d(25)\n\n    def single_attack(self, net, inp, label, eta, data ):\n        '''\n        Given the original image and the perturbation computed so far, computes\n        a new perturbation.\n        :param net:\n        :param inp: original image\n        :param label:\n        :param eta: perturbation computed so far\n        :return: a new perturbation\n        '''\n        num_sequences = inp.shape[0]\n        adv_inp = inp + eta\n       \n        \n        \n        #vis.heatmap(label[0][0])\n        #net.zero_grad()\n        zf = data['zf']\n        xf = net.backbone(adv_inp)\n        xf = net.neck(xf)\n        feat2 = net.adjcon1(xf[2])\n        feat2 = net.adjcon2(feat2)\n        cls, loc = net.rpn_head(zf, xf)\n        bats = cls.size(0)\n        score = cls.permute(1, 2, 3, 0).contiguous().view(2, -1).permute(1, 0)\n        score = F.softmax(score, dim=1).data[:, 1].view(bats, 5,25,25)\n        score_maxid= self.maxpool(score).view(bats,-1)\n        #score_map = score.sum(1)/5\n        #print(score_maxid.size())\n        #print(score_maxid)\n        _ , maxid = torch.max(score_maxid,dim=1)\n        #print(maxid)\n        score_ls=[]\n        for i in range(len(maxid)):\n            score_ls.append(score[i,maxid[i],:,:])\n        score_one = torch.stack(score_ls)\n        #print(score_one.size())\n        #vis.heatmap(score_one[0])\n        \n       \n        \n        rnn_data={\n            'feat1':data['xf_prev'],\n            'feat2':feat2,\n            'dimp_score_cur':score_one,\n            'state_prev': data['state_prev'],\n            'label_prev':data['label_prev']\n        }\n\n\n        #print(len(xf))\n        \n        output = net.RNN_defence(rnn_data)\n\n        #print(label.size())\n        \n        pred = output['response'].unsqueeze(0) \n        #vis.heatmap(pred[0][0])\n        #pred = net(adv_inp)\n        \n        if label is not None:\n            loss = self.criterion(pred, label)\n            #print(loss.requires_grad)\n            #loss.requires_grad = True\n            #print(adv_inp.size())\n            #print(loss)\n            #print(adv_inp)\n            #backbone_feat_cur.sum().backward()\n            #grad_sign = adv_inp.grad#.sign()  \n            #print(grad_sign)\n            \n            grad_sign = torch.autograd.grad(loss, adv_inp, only_inputs=True, retain_graph = False)[0].sign()\n            #print(grad_sign.size())\n            \n            \n        #print(loss)\n        adv_inp = adv_inp - 1*grad_sign * (self.sigma / self._std)\n        tmp_adv_inp = adv_inp * self._std +  self._mean\n        \n        tmp_inp = inp * self._std + self._mean\n        tmp_adv_inp = torch.clamp(tmp_adv_inp, 0, 255) ## clip into 0-1\n        #tmp_adv_inp = (tmp_adv_inp - self._mean) / self._std\n        tmp_eta = tmp_adv_inp - tmp_inp\n        tmp_eta = clip_eta(tmp_eta, norm=self.norm, eps=self.eps, DEVICE=self.DEVICE)\n\n        eta = tmp_eta/ self._std\n\n        return eta\n\n    def attack(self, net, inp, data ):\n        #save_torchimg(inp*255,'oriinput')\n        if self.random_start:\n            eta = torch.FloatTensor(*inp.shape).uniform_(-self.eps, self.eps)\n        else:\n            eta = torch.zeros_like(inp)\n        eta = eta.to(self.DEVICE)\n        eta = (eta - self._mean) / self._std\n        net.eval()\n        #print(label.size())\n        #print(inp.mean())\n        \n        \n        label_adv = torch.zeros_like(data['label_prev'])\n        #print(label_adv.size())\n        \n        for r in range(label_adv.size(1)):\n\n            xx = random.randint(1,22)\n            yy = random.randint(1,22)\n            label_adv[0,r,yy,xx] = 1\n            label_adv[0,r,yy+1,xx] = 1\n            label_adv[0,r,yy,xx+1] = 1\n            label_adv[0,r,yy+1,xx+1] = 1\n        #print(label_adv[0][0])\n        inp.requires_grad = True\n        eta.requires_grad = True\n\n        #vis.heatmap(label_adv[0][0])\n        for i in range(self.nb_iter):\n            eta = self.single_attack(net, inp, label_adv, eta, data )\n            #print(i)\n        #print(eta)\n        \n        #print(eta.max())\n        adv_inp = inp + eta\n        tmp_adv_inp = adv_inp * self._std +  self._mean\n        tmp_adv_inp = torch.clamp(tmp_adv_inp, 0, 255)\n        adv_inp = (tmp_adv_inp - self._mean) / self._std\n        #save_torchimg(adv_inp*255,'advinput')\n        \n        \n        return adv_inp\n\n    def to(self, device):\n        self.DEVICE = device\n        self._mean = self._mean.to(device)\n        self._std = self._std.to(device)\n        self.criterion = self.criterion.to(device)\n\nclass IPGD_siamrpn(AttackBase):\n    # ImageNet pre-trained mean and std\n    # _mean = torch.tensor(np.array([0.485, 0.456, 0.406]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis])\n    # _std = torch.tensor(np.array([0.229, 0.224, 0.225]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis])\n\n    # _mean = torch.tensor(np.array([0]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis])\n    # _std = torch.tensor(np.array([1.0]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis])\n    def __init__(self, eps = 6 , sigma = 3 , nb_iter = 5,\n                 norm = np.inf, DEVICE = torch.device('cuda:0'), random_start = True,\n                 mean = 0 ,#torch.tensor(np.array([0.485, 0.456, 0.406]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis]),\n                 std = 1 ):#torch.tensor(np.array([0.229, 0.224, 0.225]).astype(np.float32)[np.newaxis, :, np.newaxis, np.newaxis])):\n        '''\n        :param eps: maximum distortion of adversarial examples\n        :param sigma: single step size\n        :param nb_iter: number of attack iterations\n        :param norm: which norm to bound the perturbations\n        '''\n        self.eps = eps\n        self.sigma = sigma\n        self.nb_iter = nb_iter\n        self.norm = norm\n        self.criterion = torch.nn.MSELoss()#.to(DEVICE)  # MSELoss   L1Loss\n        self.DEVICE = DEVICE\n        self._mean = mean#.to(DEVICE)\n        self._std = std#.to(DEVICE)\n        self.random_start = random_start\n        self.maxpool = nn.MaxPool2d(25)\n\n    def single_attack(self, net, inp, label, eta, data ):\n        '''\n        Given the original image and the perturbation computed so far, computes\n        a new perturbation.\n        :param net:\n        :param inp: original image\n        :param label:\n        :param eta: perturbation computed so far\n        :return: a new perturbation\n        '''\n        num_sequences = inp.shape[0]\n        adv_inp = inp + eta\n       \n        \n        \n        #vis.heatmap(label[0][0])\n        #net.zero_grad()\n        zf = data['zf']\n        xf = net.backbone(adv_inp)\n        xf = net.neck(xf)\n        #feat2 = net.adjcon1(xf[2])\n        #feat2 = net.adjcon2(feat2)\n        cls, loc = net.rpn_head(zf, xf)\n        bats = cls.size(0)\n        score = cls.permute(1, 2, 3, 0).contiguous().view(2, -1).permute(1, 0)\n        pred = F.softmax(score, dim=1)[:, 1].view(bats, 5,25,25).sum(1).unsqueeze(0)\n        #print(pred)\n        #print(score_one.size())\n        #vis.heatmap(score_one[0])\n        \n        \n        #vis.heatmap(pred[0][0])\n        #pred = net(adv_inp)\n        \n        if label is not None:\n            loss = self.criterion(pred, label)\n            #print(loss.requires_grad)\n            #loss.requires_grad = True\n            #print(adv_inp.size())\n            #print(loss)\n            #print(adv_inp)\n            #backbone_feat_cur.sum().backward()\n            #grad_sign = adv_inp.grad#.sign()  \n            #print(grad_sign)\n            \n            grad_sign = torch.autograd.grad(loss, adv_inp, only_inputs=True, retain_graph = False)[0].sign()\n            #print(grad_sign.size())\n            \n        \n        #print(loss)\n        adv_inp = adv_inp - 1*grad_sign * (self.sigma / self._std)\n        tmp_adv_inp = adv_inp * self._std +  self._mean\n        \n        tmp_inp = inp * self._std + self._mean\n        tmp_adv_inp = torch.clamp(tmp_adv_inp, 0, 255) ## clip into 0-1\n        #tmp_adv_inp = (tmp_adv_inp - self._mean) / self._std\n        tmp_eta = tmp_adv_inp - tmp_inp\n        tmp_eta = clip_eta(tmp_eta, norm=self.norm, eps=self.eps, DEVICE=self.DEVICE)\n\n        eta = tmp_eta/ self._std\n\n        return eta\n\n    def attack(self, net, inp, data ):\n        #save_torchimg(inp*255,'oriinput')\n        if self.random_start:\n            eta = torch.FloatTensor(*inp.shape).uniform_(-self.eps, self.eps)\n        else:\n            eta = torch.zeros_like(inp)\n        eta = eta.to(self.DEVICE)\n        eta = (eta - self._mean) / self._std\n        net.eval()\n        #print(label.size())\n        #print(inp.mean())\n        \n        \n        label_adv = torch.zeros_like(data['label_prev'])\n        #print(label_adv.size())\n        \n        for r in range(label_adv.size(1)):\n\n            xx = random.randint(1,22)\n            yy = random.randint(1,22)\n            label_adv[0,r,yy,xx] = 1\n            label_adv[0,r,yy+1,xx] = 1\n            label_adv[0,r,yy,xx+1] = 1\n            label_adv[0,r,yy+1,xx+1] = 1\n        #print(label_adv[0][0])\n        inp.requires_grad = True\n        eta.requires_grad = True\n\n        #vis.heatmap(label_adv[0][0])\n        for i in range(self.nb_iter):\n            eta = self.single_attack(net, inp, label_adv, eta, data )\n            #print(i)\n        #print(eta)\n        \n        #print(eta.max())\n        adv_inp = inp + eta\n        tmp_adv_inp = adv_inp * self._std +  self._mean\n        tmp_adv_inp = torch.clamp(tmp_adv_inp, 0, 255)\n        adv_inp = (tmp_adv_inp - self._mean) / self._std\n        #save_torchimg(adv_inp*255,'advinput')\n        \n        \n        return adv_inp\n\n    def to(self, device):\n        self.DEVICE = device\n        self._mean = self._mean.to(device)\n        self._std = self._std.to(device)\n        self.criterion = self.criterion.to(device)\n\ndef test_IPGD():\n    pass\nif __name__ == '__main__':\n    test_IPGD()\n", "meta": {"hexsha": "a1c543b9465771a42eb2f40e5b812267a566e084", "size": 23489, "ext": "py", "lang": "Python", "max_stars_repo_path": "ltr/attack/pgd.py", "max_stars_repo_name": "tsingqguo/ABA", "max_stars_repo_head_hexsha": "c32edbbe5705b0332a08951b5ee436b5f58c2e70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2021-07-27T07:18:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T13:52:20.000Z", "max_issues_repo_path": "ltr/attack/pgd.py", "max_issues_repo_name": "tsingqguo/ABA", "max_issues_repo_head_hexsha": "c32edbbe5705b0332a08951b5ee436b5f58c2e70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-08-03T09:21:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-29T14:25:30.000Z", "max_forks_repo_path": "ltr/attack/pgd.py", "max_forks_repo_name": "tsingqguo/ABA", "max_forks_repo_head_hexsha": "c32edbbe5705b0332a08951b5ee436b5f58c2e70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-11-18T14:46:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T15:47:23.000Z", "avg_line_length": 37.6426282051, "max_line_length": 149, "alphanum_fraction": 0.5678828388, "include": true, "reason": "import numpy", "num_tokens": 6185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771035, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.17846797523681188}}
{"text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\n\nif sys.version[0] == '2':\n    import cPickle as pkl\nelse:\n    import pickle as pkl\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom PNN.author import utils\n\ndtype = utils.DTYPE\n\n\nclass Model:\n    def __init__(self):\n        self.sess = None\n        self.X = None\n        self.y = None\n        self.layer_keeps = None\n        self.vars = None\n        self.keep_prob_train = None\n        self.keep_prob_test = None\n\n    def run(self, fetches, X=None, y=None, mode='train'):\n            feed_dict = {}\n            if type(self.X) is list:\n                for i in range(len(X)):\n                    feed_dict[self.X[i]] = X[i]\n            else:\n                feed_dict[self.X] = X\n            if y is not None:\n                feed_dict[self.y] = y\n            if self.layer_keeps is not None:\n                if mode == 'train':\n                    feed_dict[self.layer_keeps] = self.keep_prob_train\n                elif mode == 'test':\n                    feed_dict[self.layer_keeps] = self.keep_prob_test\n            return self.sess.run(fetches, feed_dict)\n\n    def dump(self, model_path):\n        var_map = {}\n        for name, var in self.vars.iteritems():\n            var_map[name] = self.run(var)\n        pkl.dump(var_map, open(model_path, 'wb'))\n        print('model dumped at', model_path)\n\n\nclass LR(Model):\n    def __init__(self, input_dim=None, output_dim=1, init_path=None, opt_algo='gd', learning_rate=1e-2, l2_weight=0,\n                 random_seed=None):\n        Model.__init__(self)\n        init_vars = [('w', [input_dim, output_dim], 'xavier', dtype),\n                     ('b', [output_dim], 'zero', dtype)]\n        self.graph = tf.Graph()\n        with self.graph.as_default():\n            if random_seed is not None:\n                tf.set_random_seed(random_seed)\n            self.X = tf.sparse_placeholder(dtype)\n            self.y = tf.placeholder(dtype)\n            self.vars = utils.init_var_map(init_vars, init_path)\n\n            w = self.vars['w']\n            b = self.vars['b']\n            xw = tf.sparse_tensor_dense_matmul(self.X, w)\n            logits = tf.reshape(xw + b, [-1])\n            self.y_prob = tf.sigmoid(logits)\n\n            self.loss = tf.reduce_mean(\n                tf.nn.sigmoid_cross_entropy_with_logits(labels=self.y, logits=logits)) + \\\n                        l2_weight * tf.nn.l2_loss(xw)\n            self.optimizer = utils.get_optimizer(opt_algo, learning_rate, self.loss)\n\n            config = tf.ConfigProto()\n            config.gpu_options.allow_growth = True\n            self.sess = tf.Session(config=config)\n            tf.global_variables_initializer().run(session=self.sess)\n\n\nclass FM(Model):\n    def __init__(self, input_dim=None, output_dim=1, factor_order=10, init_path=None, opt_algo='gd', learning_rate=1e-2,\n                 l2_w=0, l2_v=0, random_seed=None):\n        Model.__init__(self)\n        init_vars = [('w', [input_dim, output_dim], 'xavier', dtype),\n                     ('v', [input_dim, factor_order], 'xavier', dtype),\n                     ('b', [output_dim], 'zero', dtype)]\n        self.graph = tf.Graph()\n        with self.graph.as_default():\n            if random_seed is not None:\n                tf.set_random_seed(random_seed)\n            self.X = tf.sparse_placeholder(dtype)\n            self.y = tf.placeholder(dtype)\n            self.vars = utils.init_var_map(init_vars, init_path)\n\n            w = self.vars['w']\n            v = self.vars['v']\n            b = self.vars['b']\n\n            X_square = tf.SparseTensor(self.X.indices, tf.square(self.X.values), tf.to_int64(tf.shape(self.X)))\n            xv = tf.square(tf.sparse_tensor_dense_matmul(self.X, v))\n            p = 0.5 * tf.reshape(\n                tf.reduce_sum(xv - tf.sparse_tensor_dense_matmul(X_square, tf.square(v)), 1),\n                [-1, output_dim])\n            xw = tf.sparse_tensor_dense_matmul(self.X, w)\n            logits = tf.reshape(xw + b + p, [-1])\n            self.y_prob = tf.sigmoid(logits)\n\n            self.loss = tf.reduce_mean(\n                tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=self.y)) + \\\n                        l2_w * tf.nn.l2_loss(xw) + \\\n                        l2_v * tf.nn.l2_loss(xv)\n            self.optimizer = utils.get_optimizer(opt_algo, learning_rate, self.loss)\n\n            config = tf.ConfigProto()\n            config.gpu_options.allow_growth = True\n            self.sess = tf.Session(config=config)\n            tf.global_variables_initializer().run(session=self.sess)\n\n\nclass FNN(Model):\n    def __init__(self, field_sizes=None, embed_size=10, layer_sizes=None, layer_acts=None, drop_out=None,\n                 embed_l2=None, layer_l2=None, init_path=None, opt_algo='gd', learning_rate=1e-2, random_seed=None):\n        Model.__init__(self)\n        init_vars = []\n        num_inputs = len(field_sizes)\n        for i in range(num_inputs):\n            init_vars.append(('embed_%d' % i, [field_sizes[i], embed_size], 'xavier', dtype))\n        node_in = num_inputs * embed_size\n        for i in range(len(layer_sizes)):\n            init_vars.append(('w%d' % i, [node_in, layer_sizes[i]], 'xavier', dtype))\n            init_vars.append(('b%d' % i, [layer_sizes[i]], 'zero', dtype))\n            node_in = layer_sizes[i]\n        self.graph = tf.Graph()\n        with self.graph.as_default():\n            if random_seed is not None:\n                tf.set_random_seed(random_seed)\n            self.X = [tf.sparse_placeholder(dtype) for i in range(num_inputs)]\n            self.y = tf.placeholder(dtype)\n            self.keep_prob_train = 1 - np.array(drop_out)\n            self.keep_prob_test = np.ones_like(drop_out)\n            self.layer_keeps = tf.placeholder(dtype)\n            self.vars = utils.init_var_map(init_vars, init_path)\n            w0 = [self.vars['embed_%d' % i] for i in range(num_inputs)]\n            xw = tf.concat([tf.sparse_tensor_dense_matmul(self.X[i], w0[i]) for i in range(num_inputs)], 1)\n            l = xw\n\n            for i in range(len(layer_sizes)):\n                wi = self.vars['w%d' % i]\n                bi = self.vars['b%d' % i]\n                print(l.shape, wi.shape, bi.shape)\n                l = tf.nn.dropout(\n                    utils.activate(\n                        tf.matmul(l, wi) + bi,\n                        layer_acts[i]),\n                    self.layer_keeps[i])\n\n            l = tf.squeeze(l)\n            self.y_prob = tf.sigmoid(l)\n\n            self.loss = tf.reduce_mean(\n                tf.nn.sigmoid_cross_entropy_with_logits(logits=l, labels=self.y))\n            if layer_l2 is not None:\n                self.loss += embed_l2 * tf.nn.l2_loss(xw)\n                for i in range(len(layer_sizes)):\n                    wi = self.vars['w%d' % i]\n                    self.loss += layer_l2[i] * tf.nn.l2_loss(wi)\n            self.optimizer = utils.get_optimizer(opt_algo, learning_rate, self.loss)\n\n            config = tf.ConfigProto()\n            config.gpu_options.allow_growth = True\n            self.sess = tf.Session(config=config)\n            tf.global_variables_initializer().run(session=self.sess)\n\n\nclass DeepFM(Model):\n    def __init__(self, field_sizes=None, embed_size=10, layer_sizes=None, layer_acts=None, drop_out=None,\n                 embed_l2=None, layer_l2=None, init_path=None, opt_algo='gd', learning_rate=1e-2, random_seed=None):\n        Model.__init__(self)\n        init_vars = []\n        num_inputs = len(field_sizes)\n        for i in range(num_inputs):\n            init_vars.append(('embed_%d' % i, [field_sizes[i], embed_size], 'xavier', dtype))\n            init_vars.append(('weight_%d' % i, [field_sizes[i], 1], 'xavier', dtype))\n            init_vars.append(('bias', [1], 'zero', dtype))\n        node_in = num_inputs * embed_size\n        for i in range(len(layer_sizes)):\n            init_vars.append(('w%d' % i, [node_in, layer_sizes[i]], 'xavier', dtype))\n            init_vars.append(('b%d' % i, [layer_sizes[i]], 'zero', dtype))\n            node_in = layer_sizes[i]\n        self.graph = tf.Graph()\n        with self.graph.as_default():\n            if random_seed is not None:\n                tf.set_random_seed(random_seed)\n            self.X = [tf.sparse_placeholder(dtype) for i in range(num_inputs)]\n            self.y = tf.placeholder(dtype)\n            self.keep_prob_train = 1 - np.array(drop_out)\n            self.keep_prob_test = np.ones_like(drop_out)\n            self.layer_keeps = tf.placeholder(dtype)\n            self.vars = utils.init_var_map(init_vars, init_path)\n            w = [self.vars['weight_%d' % i] for i in range(num_inputs)]\n            v = [self.vars['embed_%d' % i] for i in range(num_inputs)]\n            b = self.vars['bias']\n            xw = tf.concat([tf.sparse_tensor_dense_matmul(self.X[i], w[i]) for i in range(num_inputs)], 1)\n            xv = tf.concat([tf.sparse_tensor_dense_matmul(self.X[i], v[i]) for i in range(num_inputs)], 1)\n            l = xv\n\n            for i in range(len(layer_sizes)):\n                wi = self.vars['w%d' % i]\n                bi = self.vars['b%d' % i]\n                print(l.shape, wi.shape, bi.shape)\n                l = tf.nn.dropout(\n                    utils.activate(\n                        tf.matmul(l, wi) + bi,\n                        layer_acts[i]),\n                    self.layer_keeps[i])\n            l = tf.squeeze(l)\n\n            xv = tf.reshape(xv, [-1, num_inputs, embed_size])\n            p = 0.5 * tf.reduce_sum(\n                tf.square(tf.reduce_sum(xv, 1)) -\n                tf.reduce_sum(tf.square(xv), 1),\n            1)\n            xw = tf.reduce_sum(xw, 1)\n            logits = tf.reshape(l + xw + b + p, [-1])\n\n            self.y_prob = tf.sigmoid(logits)\n\n            self.loss = tf.reduce_mean(\n                tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=self.y))\n            if layer_l2 is not None:\n                self.loss += embed_l2 * tf.nn.l2_loss(xw)\n                for i in range(len(layer_sizes)):\n                    wi = self.vars['w%d' % i]\n                    self.loss += layer_l2[i] * tf.nn.l2_loss(wi)\n            self.optimizer = utils.get_optimizer(opt_algo, learning_rate, self.loss)\n\n            config = tf.ConfigProto()\n            config.gpu_options.allow_growth = True\n            self.sess = tf.Session(config=config)\n            tf.global_variables_initializer().run(session=self.sess)\n\n\nclass CCPM(Model):\n    def __init__(self, field_sizes=None, embed_size=10, filter_sizes=None, layer_acts=None, drop_out=None,\n                 init_path=None, opt_algo='gd', learning_rate=1e-2, random_seed=None):\n        Model.__init__(self)\n        init_vars = []\n        num_inputs = len(field_sizes)\n        for i in range(num_inputs):\n            init_vars.append(('embed_%d' % i, [field_sizes[i], embed_size], 'xavier', dtype))\n        init_vars.append(('f1', [embed_size, filter_sizes[0], 1, 2], 'xavier', dtype))\n        init_vars.append(('f2', [embed_size, filter_sizes[1], 2, 2], 'xavier', dtype))\n        init_vars.append(('w1', [2 * 3 * embed_size, 1], 'xavier', dtype))\n        init_vars.append(('b1', [1], 'zero', dtype))\n\n        self.graph = tf.Graph()\n        with self.graph.as_default():\n            if random_seed is not None:\n                tf.set_random_seed(random_seed)\n            self.X = [tf.sparse_placeholder(dtype) for i in range(num_inputs)]\n            self.y = tf.placeholder(dtype)\n            self.keep_prob_train = 1 - np.array(drop_out)\n            self.keep_prob_test = np.ones_like(drop_out)\n            self.layer_keeps = tf.placeholder(dtype)\n            self.vars = utils.init_var_map(init_vars, init_path)\n            w0 = [self.vars['embed_%d' % i] for i in range(num_inputs)]\n            xw = tf.concat([tf.sparse_tensor_dense_matmul(self.X[i], w0[i]) for i in range(num_inputs)], 1)\n            l = xw\n\n            l = tf.transpose(tf.reshape(l, [-1, num_inputs, embed_size, 1]), [0, 2, 1, 3])\n            f1 = self.vars['f1']\n            l = tf.nn.conv2d(l, f1, [1, 1, 1, 1], 'SAME')\n            l = tf.transpose(\n                utils.max_pool_4d(\n                    tf.transpose(l, [0, 1, 3, 2]),\n                    int(num_inputs / 2)),\n                [0, 1, 3, 2])\n            f2 = self.vars['f2']\n            l = tf.nn.conv2d(l, f2, [1, 1, 1, 1], 'SAME')\n            l = tf.transpose(\n                utils.max_pool_4d(\n                    tf.transpose(l, [0, 1, 3, 2]), 3),\n                [0, 1, 3, 2])\n            l = tf.nn.dropout(\n                utils.activate(\n                    tf.reshape(l, [-1, embed_size * 3 * 2]),\n                    layer_acts[0]),\n                self.layer_keeps[0])\n            w1 = self.vars['w1']\n            b1 = self.vars['b1']\n            l = tf.matmul(l, w1) + b1\n\n            l = tf.squeeze(l)\n            self.y_prob = tf.sigmoid(l)\n\n            self.loss = tf.reduce_mean(\n                tf.nn.sigmoid_cross_entropy_with_logits(logits=l, labels=self.y))\n            self.optimizer = utils.get_optimizer(opt_algo, learning_rate, self.loss)\n\n            config = tf.ConfigProto()\n            config.gpu_options.allow_growth = True\n            self.sess = tf.Session(config=config)\n            tf.global_variables_initializer().run(session=self.sess)\n\n\nclass PNN1(Model):\n    def __init__(self, field_sizes=None, embed_size=10, layer_sizes=None, layer_acts=None, drop_out=None,\n                 embed_l2=None, layer_l2=None, init_path=None, opt_algo='gd', learning_rate=1e-2, random_seed=None):\n        Model.__init__(self)\n        init_vars = []\n        num_inputs = len(field_sizes) # 26\n        for i in range(num_inputs): # 一个field就对应一个embedding的参数\n            init_vars.append(('embed_%d' % i, [field_sizes[i], embed_size], 'xavier', dtype))\n        num_pairs = int(num_inputs * (num_inputs - 1) / 2)\n        node_in = num_inputs * embed_size + num_pairs # 第一个隐藏层的输入维度，lz大小k * pairs, lp只是pairs，也就是lp一个pair生成一个值，lz一个pair生成一个embedding大小\n        # node_in = num_inputs * (embed_size + num_inputs)\n        for i in range(len(layer_sizes)):\n            init_vars.append(('w%d' % i, [node_in, layer_sizes[i]], 'xavier', dtype))\n            init_vars.append(('b%d' % i, [layer_sizes[i]], 'zero', dtype))\n            node_in = layer_sizes[i]\n        self.graph = tf.Graph()\n        with self.graph.as_default():\n            if random_seed is not None:\n                tf.set_random_seed(random_seed)\n            self.X = [tf.sparse_placeholder(dtype) for i in range(num_inputs)] # num_input就是field的个数N，也就是说原始输入不用做one-hot\n            self.y = tf.placeholder(dtype)\n            self.keep_prob_train = 1 - np.array(drop_out)\n            self.keep_prob_test = np.ones_like(drop_out)\n            self.layer_keeps = tf.placeholder(dtype)\n            self.vars = utils.init_var_map(init_vars, init_path)\n            w0 = [self.vars['embed_%d' % i] for i in range(num_inputs)]\n            xw = tf.concat([tf.sparse_tensor_dense_matmul(self.X[i], w0[i]) for i in range(num_inputs)], 1) # 相乘就是在做embedding，concat就是把结果拼接起来\n            xw3d = tf.reshape(xw, [-1, num_inputs, embed_size]) # [num_samples, num_field, embed_sz]\n\n            row = []\n            col = []\n            for i in range(num_inputs-1):\n                for j in range(i+1, num_inputs):\n                    row.append(i)\n                    col.append(j)\n            # batch * pair * k\n            p = tf.transpose(\n                # pair * batch * k\n                tf.gather(\n                    # num * batch * k\n                    tf.transpose(\n                        xw3d, [1, 0, 2]),\n                    row),\n                [1, 0, 2])\n            # batch * pair * k\n            q = tf.transpose(\n                tf.gather(\n                    tf.transpose(\n                        xw3d, [1, 0, 2]),\n                    col),\n                [1, 0, 2])\n            p = tf.reshape(p, [-1, num_pairs, embed_size])\n            q = tf.reshape(q, [-1, num_pairs, embed_size])\n            ip = tf.reshape(tf.reduce_sum(p * q, [-1]), [-1, num_pairs])\n\n            # simple but redundant\n            # batch * n * 1 * k, batch * 1 * n * k\n            # ip = tf.reshape(\n            #     tf.reduce_sum(\n            #         tf.expand_dims(xw3d, 2) *\n            #         tf.expand_dims(xw3d, 1),\n            #         3),\n            #     [-1, num_inputs**2])\n            l = tf.concat([xw, ip], 1)\n\n            for i in range(len(layer_sizes)):\n                wi = self.vars['w%d' % i]\n                bi = self.vars['b%d' % i]\n                l = tf.nn.dropout(\n                    utils.activate(\n                        tf.matmul(l, wi) + bi,\n                        layer_acts[i]),\n                    self.layer_keeps[i])\n\n            l = tf.squeeze(l)\n            self.y_prob = tf.sigmoid(l)\n\n            self.loss = tf.reduce_mean(\n                tf.nn.sigmoid_cross_entropy_with_logits(logits=l, labels=self.y))\n            if layer_l2 is not None:\n                self.loss += embed_l2 * tf.nn.l2_loss(xw)\n                for i in range(len(layer_sizes)):\n                    wi = self.vars['w%d' % i]\n                    self.loss += layer_l2[i] * tf.nn.l2_loss(wi)\n            self.optimizer = utils.get_optimizer(opt_algo, learning_rate, self.loss)\n\n            config = tf.ConfigProto()\n            config.gpu_options.allow_growth = True\n            self.sess = tf.Session(config=config)\n            tf.global_variables_initializer().run(session=self.sess)\n\n\nclass PNN2(Model):\n    def __init__(self, field_sizes=None, embed_size=10, layer_sizes=None, layer_acts=None, drop_out=None,\n                 embed_l2=None, layer_l2=None, init_path=None, opt_algo='gd', learning_rate=1e-2, random_seed=None,\n                 layer_norm=True):\n        Model.__init__(self)\n        init_vars = []\n        num_inputs = len(field_sizes)\n        for i in range(num_inputs):\n            init_vars.append(('embed_%d' % i, [field_sizes[i], embed_size], 'xavier', dtype))\n        num_pairs = int(num_inputs * (num_inputs - 1) / 2)\n        node_in = num_inputs * embed_size + num_pairs\n        init_vars.append(('kernel', [embed_size, num_pairs, embed_size], 'xavier', dtype))\n        for i in range(len(layer_sizes)):\n            init_vars.append(('w%d' % i, [node_in, layer_sizes[i]], 'xavier', dtype))\n            init_vars.append(('b%d' % i, [layer_sizes[i]], 'zero',  dtype))\n            node_in = layer_sizes[i]\n        self.graph = tf.Graph()\n        with self.graph.as_default():\n            if random_seed is not None:\n                tf.set_random_seed(random_seed)\n            self.X = [tf.sparse_placeholder(dtype) for i in range(num_inputs)]\n            self.y = tf.placeholder(dtype)\n            self.keep_prob_train = 1 - np.array(drop_out)\n            self.keep_prob_test = np.ones_like(drop_out)\n            self.layer_keeps = tf.placeholder(dtype)\n            self.vars = utils.init_var_map(init_vars, init_path)\n            w0 = [self.vars['embed_%d' % i] for i in range(num_inputs)]\n            xw = tf.concat([tf.sparse_tensor_dense_matmul(self.X[i], w0[i]) for i in range(num_inputs)], 1)\n            xw3d = tf.reshape(xw, [-1, num_inputs, embed_size])\n\n            row = []\n            col = []\n            for i in range(num_inputs - 1):\n                for j in range(i + 1, num_inputs):\n                    row.append(i)\n                    col.append(j)\n            # batch * pair * k\n            p = tf.transpose(\n                # pair * batch * k\n                tf.gather(\n                    # field * batch * k\n                    tf.transpose(\n                        xw3d, [1, 0, 2]),\n                    row),\n                [1, 0, 2])\n            # batch * pair * k\n            q = tf.transpose(\n                tf.gather(\n                    tf.transpose(\n                        xw3d, [1, 0, 2]),\n                    col),\n                [1, 0, 2])\n            # batch * pair * k\n            p = tf.reshape(p, [-1, num_pairs, embed_size])\n            # batch * pair * k\n            q = tf.reshape(q, [-1, num_pairs, embed_size])\n            # k * pair * k\n            k = self.vars['kernel'] # 外积生成二维矩阵; kernel就是用来和二维矩阵进行\"卷积\"（对应位置相乘相加）的。\n\n            # batch * 1 * pair * k\n            p = tf.expand_dims(p, 1) # 1表示在原来第一维度后面加一维\n            # batch * pair\n            kp = tf.reduce_sum(\n                # batch * pair * k\n                tf.multiply(\n                    # batch * pair * k\n                    tf.transpose(\n                        # batch * k * pair\n                        tf.reduce_sum(\n                            # batch * k * pair * k\n                            tf.multiply(\n                                p, k),\n                            -1),\n                        [0, 2, 1]),\n                    q),\n                -1)\n\n            #\n            # if layer_norm:\n            #     # x_mean, x_var = tf.nn.moments(xw, [1], keep_dims=True)\n            #     # xw = (xw - x_mean) / tf.sqrt(x_var)\n            #     # x_g = tf.Variable(tf.ones([num_inputs * embed_size]), name='x_g')\n            #     # x_b = tf.Variable(tf.zeros([num_inputs * embed_size]), name='x_b')\n            #     # x_g = tf.Print(x_g, [x_g[:10], x_b])\n            #     # xw = xw * x_g + x_b\n            #     p_mean, p_var = tf.nn.moments(op, [1], keep_dims=True)\n            #     op = (op - p_mean) / tf.sqrt(p_var)\n            #     p_g = tf.Variable(tf.ones([embed_size**2]), name='p_g')\n            #     p_b = tf.Variable(tf.zeros([embed_size**2]), name='p_b')\n            #     # p_g = tf.Print(p_g, [p_g[:10], p_b])\n            #     op = op * p_g + p_b\n\n            l = tf.concat([xw, kp], 1)\n            for i in range(len(layer_sizes)):\n                wi = self.vars['w%d' % i]\n                bi = self.vars['b%d' % i]\n                l = tf.nn.dropout(\n                    utils.activate(\n                        tf.matmul(l, wi) + bi,\n                        layer_acts[i]),\n                    self.layer_keeps[i])\n\n            l = tf.squeeze(l)\n            self.y_prob = tf.sigmoid(l)\n\n            self.loss = tf.reduce_mean(\n                tf.nn.sigmoid_cross_entropy_with_logits(logits=l, labels=self.y))\n            if layer_l2 is not None:\n                self.loss += embed_l2 * tf.nn.l2_loss(xw)#tf.concat(w0, 0))\n                for i in range(len(layer_sizes)):\n                    wi = self.vars['w%d' % i]\n                    self.loss += layer_l2[i] * tf.nn.l2_loss(wi)\n            self.optimizer = utils.get_optimizer(opt_algo, learning_rate, self.loss)\n\n            config = tf.ConfigProto()\n            config.gpu_options.allow_growth = True\n            self.sess = tf.Session(config=config)\n            tf.global_variables_initializer().run(session=self.sess)", "meta": {"hexsha": "12fc0f12a0d888a04b37f8a72f2316d56ac94ada", "size": 22748, "ext": "py", "lang": "Python", "max_stars_repo_path": "PNN/author/models.py", "max_stars_repo_name": "suhuating/ML_CIA", "max_stars_repo_head_hexsha": "3240cd0b1dec37aade6aacca93fb42dcc68cf01e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 572, "max_stars_repo_stars_event_min_datetime": "2018-05-10T10:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T08:04:23.000Z", "max_issues_repo_path": "PNN/author/models.py", "max_issues_repo_name": "juli25/ML_CIA", "max_issues_repo_head_hexsha": "37838eb655d3e432393cee7dda11ea693217eb42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-08-10T01:56:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-20T07:15:51.000Z", "max_forks_repo_path": "PNN/author/models.py", "max_forks_repo_name": "juli25/ML_CIA", "max_forks_repo_head_hexsha": "37838eb655d3e432393cee7dda11ea693217eb42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 290, "max_forks_repo_forks_event_min_datetime": "2018-05-22T01:39:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T11:25:52.000Z", "avg_line_length": 43.7461538462, "max_line_length": 141, "alphanum_fraction": 0.5235185511, "include": true, "reason": "import numpy", "num_tokens": 5552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3174262785020255, "lm_q1q2_score": 0.1784495945374695}}
{"text": "# Author: Christopher Arderne\n# Date: 26 November 2016\n# Python version: 3.5\n\n# Updated June 2018 by Andreas Sahlberg (KTH dESA)\n# Modified grid algorithm and population calibration to improve computational speed\n\nimport logging\nimport pandas as pd\nfrom math import pi, exp, log, sqrt\n# from pyproj import Proj\nimport numpy as np\nfrom collections import defaultdict\n\nlogging.basicConfig(format='%(asctime)s\\t\\t%(message)s', level=logging.DEBUG)\n\n# general\nLHV_DIESEL = 9.9445485  # (kWh/l) lower heating value\nHOURS_PER_YEAR = 8760\n\n# Columns in settlements file must match these exactly\nSET_COUNTRY = 'Country'  # This cannot be changed, lots of code will break\nSET_X = 'X'  # Coordinate in metres/kilometres\nSET_Y = 'Y'  # Coordinate in metres/kilometres\nSET_X_DEG = 'X_deg'  # Coordinates in degrees\nSET_Y_DEG = 'Y_deg'\nSET_POP = 'Pop'  # Population in people per point (equally, people per km2)\nSET_POP_CALIB = 'PopStartCalibrated'  # Calibrated population to reference year, same units\nSET_POP_FUTURE = 'PopFuture'  # Project future population, same units\nSET_GRID_DIST_CURRENT = 'GridDistCurrent'  # Distance in km from current grid\nSET_GRID_DIST_PLANNED = 'GridDistPlan'  # Distance in km from current and future grid\nSET_ROAD_DIST = 'RoadDist'  # Distance in km from road network\nSET_NIGHT_LIGHTS = 'NightLights'  # Intensity of night time lights (from NASA), range 0 - 63\nSET_TRAVEL_HOURS = 'TravelHours'  # Travel time to large city in hours\nSET_GHI = 'GHI'  # Global horizontal irradiance in kWh/m2/day\nSET_WINDVEL = 'WindVel'  # Wind velocity in m/s\nSET_WINDCF = 'WindCF'  # Wind capacity factor as percentage (range 0 - 1)\nSET_HYDRO = 'Hydropower'  # Hydropower potential in kW\nSET_HYDRO_DIST = 'HydropowerDist'  # Distance to hydropower site in km\nSET_HYDRO_FID = 'HydropowerFID'  # the unique tag for eah hydropower, to not over-utilise\nSET_SUBSTATION_DIST = 'SubstationDist'\nSET_ELEVATION = 'Elevation'  # in metres\nSET_SLOPE = 'Slope'  # in degrees\nSET_LAND_COVER = 'LandCover'\nSET_SOLAR_RESTRICTION = 'SolarRestriction'\nSET_ROAD_DIST_CLASSIFIED = 'RoadDistClassified'\nSET_SUBSTATION_DIST_CLASSIFIED = 'SubstationDistClassified'\nSET_ELEVATION_CLASSIFIED = 'ElevationClassified'\nSET_SLOPE_CLASSIFIED = 'SlopeClassified'\nSET_LAND_COVER_CLASSIFIED = 'LandCoverClassified'\nSET_COMBINED_CLASSIFICATION = 'GridClassification'\nSET_GRID_PENALTY = 'GridPenalty'\nSET_URBAN = 'IsUrban'  # Whether the site is urban (0 or 1)\nSET_ENERGY_PER_HH = 'EnergyPerHH'\nSET_NUM_PEOPLE_PER_HH = 'NumPeoplePerHH'\nSET_ELEC_CURRENT = 'ElecStart'  # If the site is currently electrified (0 or 1)\nSET_ELEC_FUTURE = 'ElecFuture'  # If the site has the potential to be 'easily' electrified in future\nSET_NEW_CONNECTIONS = 'NewConnections'  # Number of new people with electricity connections\nSET_MIN_GRID_DIST = 'MinGridDist'\nSET_LCOE_GRID = 'Grid'  # All lcoes in USD/kWh\nSET_LCOE_SA_PV = 'SA_PV'\nSET_LCOE_SA_DIESEL = 'SA_Diesel'\nSET_LCOE_MG_WIND = 'MG_Wind'\nSET_LCOE_MG_DIESEL = 'MG_Diesel'\nSET_LCOE_MG_PV = 'MG_PV'\nSET_LCOE_MG_HYDRO = 'MG_Hydro'\nSET_MIN_OFFGRID = 'MinimumOffgrid'  # The technology with lowest lcoe (excluding grid)\nSET_MIN_OVERALL = 'MinimumOverall'  # Same as above, but including grid\nSET_MIN_OFFGRID_LCOE = 'MinimumTechLCOE'  # The lcoe value for minimum tech\nSET_MIN_OVERALL_LCOE = 'MinimumOverallLCOE'  # The lcoe value for overall minimum\nSET_MIN_OVERALL_CODE = 'MinimumOverallCode'  # And a code from 1 - 7 to represent that option\nSET_MIN_CATEGORY = 'MinimumCategory'  # The category with minimum lcoe (grid, minigrid or standalone)\nSET_NEW_CAPACITY = 'NewCapacity'  # Capacity in kW\nSET_INVESTMENT_COST = 'InvestmentCost'  # The investment cost in USD\n\n# Columns in the specs file must match these exactly\nSPE_COUNTRY = 'Country'\nSPE_POP = 'Pop2015'  # The actual population in the base year\nSPE_URBAN = 'UrbanRatio2015'  # The ratio of urban population (range 0 - 1) in base year\nSPE_POP_FUTURE = 'Pop2030'\nSPE_URBAN_FUTURE = 'UrbanRatio2030'\nSPE_URBAN_MODELLED = 'UrbanRatioModelled'  # The urban ratio in the model after calibration (for comparison)\nSPE_URBAN_CUTOFF = 'UrbanCutOff'  # The urban cutoff population calirated by the model, in people per km2\nSPE_URBAN_GROWTH = 'UrbanGrowth'  # The urban growth rate as a simple multplier (urban pop future / urban pop present)\nSPE_RURAL_GROWTH = 'RuralGrowth'  # Same as for urban\nSPE_NUM_PEOPLE_PER_HH_RURAL = 'NumPeoplePerHHRural'\nSPE_NUM_PEOPLE_PER_HH_URBAN = 'NumPeoplePerHHUrban'\nSPE_DIESEL_PRICE_LOW = 'DieselPriceLow'  # Diesel price in USD/litre\nSPE_DIESEL_PRICE_HIGH = 'DieselPriceHigh'  # Same, with a high forecast var\nSPE_GRID_PRICE = 'GridPrice'  # Grid price of electricity in USD/kWh\nSPE_GRID_CAPACITY_INVESTMENT = 'GridCapacityInvestmentCost'  # grid capacity investments costs from TEMBA USD/kW\nSPE_GRID_LOSSES = 'GridLosses'  # As a ratio (0 - 1)\nSPE_BASE_TO_PEAK = 'BaseToPeak'  # As a ratio (0 - 1)\nSPE_EXISTING_GRID_COST_RATIO = 'ExistingGridCostRatio'\nSPE_MAX_GRID_DIST = 'MaxGridDist'\nSPE_ELEC = 'ElecActual'  # Actual current percentage electrified population (0 - 1)\nSPE_ELEC_MODELLED = 'ElecModelled'  # The modelled version after calibration (for comparison)\nSPE_MIN_NIGHT_LIGHTS = 'MinNightLights'\nSPE_MAX_GRID_EXTENSION_DIST = 'MaxGridExtensionDist'\nSPE_MAX_ROAD_DIST = 'MaxRoadDist'\nSPE_POP_CUTOFF1 = 'PopCutOffRoundOne'\nSPE_POP_CUTOFF2 = 'PopCutOffRoundTwo'\n\n\nclass Technology:\n    \"\"\"\n    Used to define the parameters for each electricity access technology, and to calculate the LCOE depending on\n    input parameters.\n    \"\"\"\n\n    start_year = 2015\n    end_year = 2030\n    discount_rate = 0.08\n    grid_cell_area = 1  # in km2, normally 1km2\n\n    mv_line_cost = 9000  # USD/km\n    lv_line_cost = 5000  # USD/km\n    mv_line_capacity = 50  # kW/line\n    lv_line_capacity = 10  # kW/line\n    lv_line_max_length = 30  # km\n    hv_line_cost = 53000  # USD/km\n    mv_line_max_length = 50  # km\n    hv_lv_transformer_cost = 5000  # USD/unit\n    mv_increase_rate = 0.1  # percentage\n\n    def __init__(self,\n                 tech_life,  # in years\n                 base_to_peak_load_ratio,\n                 distribution_losses=0,  # percentage\n                 connection_cost_per_hh=0,  # USD/hh\n                 om_costs=0.0,  # OM costs as percentage of capital costs\n                 capital_cost=0,  # USD/kW\n                 capacity_factor=1.0,  # percentage\n                 efficiency=1.0,  # percentage\n                 diesel_price=0.0,  # USD/litre\n                 grid_price=0.0,  # USD/kWh for grid electricity\n                 standalone=False,\n                 grid_capacity_investment=0.0,  # USD/kW for on-grid capacity investments (excluding grid itself)\n                 diesel_truck_consumption=0,  # litres/hour\n                 diesel_truck_volume=0,  # litres\n                 om_of_td_lines=0):  # percentage\n\n        self.distribution_losses = distribution_losses\n        self.connection_cost_per_hh = connection_cost_per_hh\n        self.base_to_peak_load_ratio = base_to_peak_load_ratio\n        self.tech_life = tech_life\n        self.om_costs = om_costs\n        self.capital_cost = capital_cost\n        self.capacity_factor = capacity_factor\n        self.efficiency = efficiency\n        self.diesel_price = diesel_price\n        self.grid_price = grid_price\n        self.standalone = standalone\n        self.grid_capacity_investment = grid_capacity_investment\n        self.diesel_truck_consumption = diesel_truck_consumption\n        self.diesel_truck_volume = diesel_truck_volume\n        self.om_of_td_lines = om_of_td_lines\n\n    @classmethod\n    def set_default_values(cls, start_year, end_year, discount_rate, grid_cell_area, mv_line_cost, lv_line_cost,\n                           mv_line_capacity, lv_line_capacity, lv_line_max_length, hv_line_cost, mv_line_max_length,\n                           hv_lv_transformer_cost, mv_increase_rate):\n        cls.start_year = start_year\n        cls.end_year = end_year\n        cls.discount_rate = discount_rate\n        cls.grid_cell_area = grid_cell_area\n        cls.mv_line_cost = mv_line_cost\n        cls.lv_line_cost = lv_line_cost\n        cls.mv_line_capacity = mv_line_capacity\n        cls.lv_line_capacity = lv_line_capacity\n        cls.lv_line_max_length = lv_line_max_length\n        cls.hv_line_cost = hv_line_cost\n        cls.mv_line_max_length = mv_line_max_length\n        cls.hv_lv_transformer_cost = hv_lv_transformer_cost\n        cls.mv_increase_rate = mv_increase_rate\n\n    def get_lcoe(self, energy_per_hh, people, num_people_per_hh, additional_mv_line_length=0, capacity_factor=0,\n                 mv_line_length=0, travel_hours=0, get_investment_cost=False):\n        \"\"\"\n        Calculates the LCOE depending on the parameters. Optionally calculates the investment cost instead.\n\n        The only required parameters are energy_per_hh, people and num_people_per_hh\n        additional_mv_line_length requried for grid\n        capacity_factor required for PV and wind\n        mv_line_length required for hydro\n        travel_hours required for diesel\n        \"\"\"\n\n        if people == 0:\n            # If there are no people, the investment cost is zero.\n            if get_investment_cost:\n                return 0\n            # Otherwise we set the people low (prevent div/0 error) and continue.\n            else:\n                people = 0.00001\n\n        # If a new capacity factor isn't given, use the class capacity factor (for hydro, diesel etc)\n        if capacity_factor == 0:\n            capacity_factor = self.capacity_factor\n\n        consumption = people / num_people_per_hh * energy_per_hh  # kWh/year\n        average_load = consumption / (1 - self.distribution_losses) / HOURS_PER_YEAR  # kW\n        peak_load = average_load / self.base_to_peak_load_ratio  # kW\n\n        no_mv_lines = peak_load / self.mv_line_capacity\n        no_lv_lines = peak_load / self.lv_line_capacity\n        lv_networks_lim_capacity = no_lv_lines / no_mv_lines\n        lv_networks_lim_length = ((self.grid_cell_area / no_mv_lines) / (self.lv_line_max_length / sqrt(2))) ** 2\n        actual_lv_lines = min([people / num_people_per_hh, max([lv_networks_lim_capacity, lv_networks_lim_length])])\n        hh_per_lv_network = (people / num_people_per_hh) / (actual_lv_lines * no_mv_lines)\n        lv_unit_length = sqrt(self.grid_cell_area / (people / num_people_per_hh)) * sqrt(2) / 2\n        lv_lines_length_per_lv_network = 1.333 * hh_per_lv_network * lv_unit_length\n        total_lv_lines_length = no_mv_lines * actual_lv_lines * lv_lines_length_per_lv_network\n        line_reach = (self.grid_cell_area / no_mv_lines) / (2 * sqrt(self.grid_cell_area / no_lv_lines))\n        total_length_of_lines = min([line_reach, self.mv_line_max_length]) * no_mv_lines\n        additional_hv_lines = max(\n            [0, round(sqrt(self.grid_cell_area) / (2 * min([line_reach, self.mv_line_max_length])) / 10, 3) - 1])\n        hv_lines_total_length = (sqrt(self.grid_cell_area) / 2) * additional_hv_lines * sqrt(self.grid_cell_area)\n        num_transformers = additional_hv_lines + no_mv_lines + (no_mv_lines * actual_lv_lines)\n        generation_per_year = average_load * HOURS_PER_YEAR\n\n        # The investment and O&M costs are different for grid and non-grid solutions\n        if self.grid_price > 0:\n            td_investment_cost = hv_lines_total_length * self.hv_line_cost + \\\n                                 total_length_of_lines * self.mv_line_cost + \\\n                                 total_lv_lines_length * self.lv_line_cost + \\\n                                 num_transformers * self.hv_lv_transformer_cost + \\\n                                 (people / num_people_per_hh) * self.connection_cost_per_hh + \\\n                                 additional_mv_line_length * (\n                                     self.mv_line_cost * (1 + self.mv_increase_rate) **\n                                     ((additional_mv_line_length / 5) - 1))\n            td_om_cost = td_investment_cost * self.om_of_td_lines\n            total_investment_cost = td_investment_cost\n            total_om_cost = td_om_cost\n            fuel_cost = self.grid_price\n\n        else:\n            total_lv_lines_length *= 0 if self.standalone else 0.75\n            mv_total_line_cost = self.mv_line_cost * mv_line_length\n            lv_total_line_cost = self.lv_line_cost * total_lv_lines_length\n            installed_capacity = peak_load / capacity_factor\n            capital_investment = installed_capacity * self.capital_cost\n            td_investment_cost = mv_total_line_cost + lv_total_line_cost + (\n                                                            people / num_people_per_hh) * self.connection_cost_per_hh\n            td_om_cost = td_investment_cost * self.om_of_td_lines\n            total_investment_cost = td_investment_cost + capital_investment\n            total_om_cost = td_om_cost + (self.capital_cost * self.om_costs * installed_capacity)\n\n            # If a diesel price has been passed, the technology is diesel\n            if self.diesel_price > 0:\n                # And we apply the Szabo formula to calculate the transport cost for the diesel\n                # p = (p_d + 2*p_d*consumption*time/volume)*(1/mu)*(1/LHVd)\n                fuel_cost = (self.diesel_price + 2 * self.diesel_price * self.diesel_truck_consumption * travel_hours /\n                             self.diesel_truck_volume) / LHV_DIESEL / self.efficiency\n            # Otherwise it's hydro/wind etc with no fuel cost\n            else:\n                fuel_cost = 0\n\n        # Perform the time-value LCOE calculation\n        project_life = self.end_year - self.start_year\n        reinvest_year = 0\n\n        # If the technology life is less than the project life, we will have to invest twice to buy it again\n        if self.tech_life < project_life:\n            reinvest_year = self.tech_life\n\n        year = np.arange(project_life)\n        el_gen = generation_per_year * np.ones(project_life)\n        el_gen[0] = 0\n        discount_factor = (1 + self.discount_rate) ** year\n        investments = np.zeros(project_life)\n        investments[0] = total_investment_cost\n        if reinvest_year:\n            investments[reinvest_year] = total_investment_cost\n\n        salvage = np.zeros(project_life)\n        used_life = project_life\n        if reinvest_year:\n            # so salvage will come from the remaining life after the re-investment\n            used_life = project_life - self.tech_life\n        salvage[-1] = total_investment_cost * (1 - used_life / self.tech_life)\n\n        operation_and_maintenance = total_om_cost * np.ones(project_life)\n        operation_and_maintenance[0] = 0\n        fuel = el_gen * fuel_cost\n        fuel[0] = 0\n\n        # So we also return the total investment cost for this number of people\n        if get_investment_cost:\n            discounted_investments = investments / discount_factor\n            return np.sum(discounted_investments) + self.grid_capacity_investment * peak_load\n        else:\n            discounted_costs = (investments + operation_and_maintenance + fuel - salvage) / discount_factor\n            discounted_generation = el_gen / discount_factor\n            return np.sum(discounted_costs) / np.sum(discounted_generation)\n\n    def get_grid_table(self, energy_per_hh, num_people_per_hh, max_dist):\n        \"\"\"\n        Uses calc_lcoe to generate a 2D grid with the grid LCOEs, for faster access in teh electrification algorithm\n        \"\"\"\n\n        logging.info('Creating a grid table for {} kWh/hh/year'.format(energy_per_hh))\n\n        # Coarser resolution at the high end (just to catch the few places with exceptional population density)\n        # The electrification algorithm must round off with the same scheme\n        people_arr_direct = list(range(1000)) + list(range(1000, 10000, 10)) + list(range(10000, 350000, 1000))\n        elec_dists = range(0, int(max_dist) + 20)  # add twenty to handle edge cases\n        grid_lcoes = pd.DataFrame(index=elec_dists, columns=people_arr_direct)\n\n        for people in people_arr_direct:\n            for additional_mv_line_length in elec_dists:\n                grid_lcoes[people][additional_mv_line_length] = self.get_lcoe(\n                    energy_per_hh=energy_per_hh,\n                    people=people,\n                    num_people_per_hh=num_people_per_hh,\n                    additional_mv_line_length=additional_mv_line_length)\n\n        return grid_lcoes.to_dict()\n\n\nclass SettlementProcessor:\n    \"\"\"\n    Processes the dataframe and adds all the columns to determine the cheapest option and the final costs and summaries\n    \"\"\"\n    def __init__(self, path):\n        try:\n            self.df = pd.read_csv(path)\n        except FileNotFoundError:\n            print('Could not find the calibrated and prepped csv file')\n            raise\n\n        try:\n            self.df[SET_GHI]\n        except ValueError:\n            self.df = pd.read_csv(path, sep=';')\n            try:\n                self.df[SET_GHI]\n            except ValueError:\n                print('Column \"GHI\" not found, check column names in calibrated csv-file')\n                raise\n\n    def condition_df(self):\n        \"\"\"\n        Do any initial data conditioning that may be required.\n        \"\"\"\n\n        logging.info('Ensure that columns that are supposed to be numeric are numeric')\n        self.df[SET_GHI] = pd.to_numeric(self.df[SET_GHI], errors='coerce')\n        self.df[SET_WINDVEL] = pd.to_numeric(self.df[SET_WINDVEL], errors='coerce')\n        self.df[SET_NIGHT_LIGHTS] = pd.to_numeric(self.df[SET_NIGHT_LIGHTS], errors='coerce')\n        self.df[SET_ELEVATION] = pd.to_numeric(self.df[SET_ELEVATION], errors='coerce')\n        self.df[SET_SLOPE] = pd.to_numeric(self.df[SET_SLOPE], errors='coerce')\n        self.df[SET_LAND_COVER] = pd.to_numeric(self.df[SET_LAND_COVER], errors='coerce')\n        self.df[SET_GRID_DIST_CURRENT] = pd.to_numeric(self.df[SET_GRID_DIST_CURRENT], errors='coerce')\n        self.df[SET_GRID_DIST_PLANNED] = pd.to_numeric(self.df[SET_GRID_DIST_PLANNED], errors='coerce')\n        self.df[SET_SUBSTATION_DIST] = pd.to_numeric(self.df[SET_SUBSTATION_DIST], errors='coerce')\n        self.df[SET_ROAD_DIST] = pd.to_numeric(self.df[SET_ROAD_DIST], errors='coerce')\n        self.df[SET_HYDRO_DIST] = pd.to_numeric(self.df[SET_HYDRO_DIST], errors='coerce')\n        self.df[SET_HYDRO] = pd.to_numeric(self.df[SET_HYDRO], errors='coerce')\n        self.df[SET_SOLAR_RESTRICTION] = pd.to_numeric(self.df[SET_SOLAR_RESTRICTION], errors='coerce')\n\n        logging.info('Replace null values with zero')\n        self.df.fillna(0, inplace=True)\n\n        logging.info('Sort by country, Y and X')\n        self.df.sort_values(by=[SET_COUNTRY, SET_Y, SET_X], inplace=True)\n\n        ### To add columns with location in degrees, uncomment the lines below, and line 11 above. Then input the\n        ### information for the desired projection system three lines below (line 373)\n\n        #logging.info('Add columns with location in degrees')\n        # project = Proj('+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs')\n        #\n        # def get_x(row):\n        #     x, y = project(row[SET_X], row[SET_Y], inverse=True)\n        #     return x\n        #\n        # def get_y(row):\n        #     x, y = project(row[SET_X], row[SET_Y], inverse=True)\n        #     return y\n        #\n        # self.df[SET_X_DEG] = self.df.apply(get_x, axis=1)\n        # self.df[SET_Y_DEG] = self.df.apply(get_y, axis=1)\n\n    def grid_penalties(self):\n        \"\"\"\n        Add a grid penalty factor to increase the grid cost in areas that higher road distance, higher substation\n        distance, unsuitable land cover, high slope angle or high elecation\n        \"\"\"\n\n        def classify_road_dist(row):\n            road_dist = row[SET_ROAD_DIST]\n            if road_dist <= 5:\n                return 5\n            elif road_dist <= 10:\n                return 4\n            elif road_dist <= 25:\n                return 3\n            elif road_dist <= 50:\n                return 2\n            else:\n                return 1\n\n        def classify_substation_dist(row):\n            substation_dist = row[SET_SUBSTATION_DIST]\n            if substation_dist <= 0.5:\n                return 5\n            elif substation_dist <= 1:\n                return 4\n            elif substation_dist <= 5:\n                return 3\n            elif substation_dist <= 10:\n                return 2\n            else:\n                return 1\n\n        def classify_land_cover(row):\n            land_cover = row[SET_LAND_COVER]\n            if land_cover == 0:\n                return 1\n            elif land_cover == 1:\n                return 3\n            elif land_cover == 2:\n                return 4\n            elif land_cover == 3:\n                return 3\n            elif land_cover == 4:\n                return 4\n            elif land_cover == 5:\n                return 3\n            elif land_cover == 6:\n                return 2\n            elif land_cover == 7:\n                return 5\n            elif land_cover == 8:\n                return 2\n            elif land_cover == 9:\n                return 5\n            elif land_cover == 10:\n                return 5\n            elif land_cover == 11:\n                return 1\n            elif land_cover == 12:\n                return 3\n            elif land_cover == 13:\n                return 3\n            elif land_cover == 14:\n                return 5\n            elif land_cover == 15:\n                return 3\n            elif land_cover == 16:\n                return 5\n\n        def classify_elevation(row):\n            elevation = row[SET_ELEVATION]\n            if elevation <= 500:\n                return 5\n            elif elevation <= 1000:\n                return 4\n            elif elevation <= 2000:\n                return 3\n            elif elevation <= 3000:\n                return 2\n            else:\n                return 1\n\n        def classify_slope(row):\n            slope = row[SET_SLOPE]\n            if slope <= 10:\n                return 5\n            elif slope <= 20:\n                return 4\n            elif slope <= 30:\n                return 3\n            elif slope <= 40:\n                return 2\n            else:\n                return 1\n\n        def set_penalty(row):\n            classification = row[SET_COMBINED_CLASSIFICATION]\n            return 1 + (exp(0.85 * abs(1 - classification)) - 1) / 100\n\n        logging.info('Classify road dist')\n        self.df[SET_ROAD_DIST_CLASSIFIED] = self.df.apply(classify_road_dist, axis=1)\n\n        logging.info('Classify substation dist')\n        self.df[SET_SUBSTATION_DIST_CLASSIFIED] = self.df.apply(classify_substation_dist, axis=1)\n\n        logging.info('Classify land cover')\n        self.df[SET_LAND_COVER_CLASSIFIED] = self.df.apply(classify_land_cover, axis=1)\n\n        logging.info('Classify elevation')\n        self.df[SET_ELEVATION_CLASSIFIED] = self.df.apply(classify_elevation, axis=1)\n\n        logging.info('Classify slope')\n        self.df[SET_SLOPE_CLASSIFIED] = self.df.apply(classify_slope, axis=1)\n\n        logging.info('Combined classification')\n        self.df[SET_COMBINED_CLASSIFICATION] = (0.05 * self.df[SET_ROAD_DIST_CLASSIFIED] +\n                                                0.09 * self.df[SET_SUBSTATION_DIST_CLASSIFIED] +\n                                                0.39 * self.df[SET_LAND_COVER_CLASSIFIED] +\n                                                0.15 * self.df[SET_ELEVATION_CLASSIFIED] +\n                                                0.32 * self.df[SET_SLOPE_CLASSIFIED])\n\n        logging.info('Grid penalty')\n        self.df[SET_GRID_PENALTY] = self.df.apply(set_penalty, axis=1)\n\n    def calc_wind_cfs(self):\n        \"\"\"\n        Calculate the wind capacity factor based on the average wind velocity.\n        \"\"\"\n\n        mu = 0.97  # availability factor\n        t = 8760\n        p_rated = 600\n        z = 55  # hub height\n        zr = 80  # velocity measurement height\n        es = 0.85  # losses in wind electricity\n        u_arr = range(1, 26)\n        p_curve = [0, 0, 0, 0, 30, 77, 135, 208, 287, 371, 450, 514, 558,\n                   582, 594, 598, 600, 600, 600, 600, 600, 600, 600, 600, 600]\n\n        def get_wind_cf(row):\n            u_zr = row[SET_WINDVEL]\n            if u_zr == 0:\n                return 0\n\n            else:\n                # Adjust for the correct hub height\n                alpha = (0.37 - 0.088 * log(u_zr)) / (1 - 0.088 * log(zr / 10))\n                u_z = u_zr * (z / zr) ** alpha\n\n                # Rayleigh distribution and sum of series\n                rayleigh = [(pi / 2) * (u / u_z ** 2) * exp((-pi / 4) * (u / u_z) ** 2) for u in u_arr]\n                energy_produced = sum([mu * es * t * p * r for p, r in zip(p_curve, rayleigh)])\n\n                return energy_produced/(p_rated * t)\n\n        logging.info('Calculate Wind CF')\n        self.df[SET_WINDCF] = self.df.apply(get_wind_cf, axis=1)\n\n    def calibrate_pop_and_urban(self, pop_actual, pop_future, urban, urban_future, urban_cutoff):\n        \"\"\"\n        Calibrate the actual current population, the urban split and forecast the future population\n        \"\"\"\n\n        # Calculate the ratio between the actual population and the total population from the GIS layer\n        logging.info('Calibrate current population')\n        pop_ratio = pop_actual/self.df[SET_POP].sum()\n\n        # And use this ratio to calibrate the population in a new column\n        self.df[SET_POP_CALIB] = self.df.apply(lambda row: row[SET_POP] * pop_ratio, axis=1)\n\n        # Calculate the urban split, by calibrating the cutoff until the target ratio is achieved\n        # Keep looping until it is satisfied or another break conditions is reached\n        logging.info('Calibrate urban split')\n        sorted_pop = self.df[SET_POP_CALIB].copy()\n        sorted_pop.sort_values(inplace=True)\n        urban_pop_break = (1-urban) * self.df[SET_POP_CALIB].sum()\n        cumulative_urban_pop = 0\n        ii = 0\n        while cumulative_urban_pop < urban_pop_break:\n            cumulative_urban_pop += sorted_pop.iloc[ii]\n            ii += 1\n        urban_cutoff = sorted_pop.iloc[ii-1]\n\n        # Assign the 1 (urban)/0 (rural) values to each cell\n        self.df[SET_URBAN] = self.df.apply(lambda row: 1 if row[SET_POP_CALIB] > urban_cutoff else 0, axis=1)\n\n        # Get the calculated urban ratio, and limit it to within reasonable boundaries\n        pop_urb = self.df.loc[self.df[SET_URBAN] == 1, SET_POP_CALIB].sum()\n        urban_modelled = pop_urb / pop_actual\n\n        # Project future population, with separate growth rates for urban and rural\n        logging.info('Project future population')\n\n        urban_growth = (urban_future * pop_future) / (urban * pop_actual)\n        rural_growth = ((1 - urban_future) * pop_future) / ((1 - urban) * pop_actual)\n\n        self.df[SET_POP_FUTURE] = self.df.apply(lambda row: row[SET_POP_CALIB] * urban_growth\n                                                if row[SET_URBAN] == 1\n                                                else row[SET_POP_CALIB] * rural_growth,\n                                                axis=1)\n\n        return urban_cutoff, urban_modelled\n\n    def elec_current_and_future(self, elec_actual, pop_cutoff, min_night_lights, max_grid_dist,\n                                max_road_dist, pop_tot, pop_cutoff2):\n        \"\"\"\n        Calibrate the current electrification status, and future 'pre-electrification' status\n        \"\"\"\n\n        # Calibrate current electrification\n        logging.info('Calibrate current electrification')\n        print('1. Actual electrification rate in 2015 = {}'.format(elec_actual))\n        is_round_two = False\n        grid_cutoff2 = 10\n        road_cutoff2 = 10\n        count = 0\n        prev_vals = []\n        accuracy = 0.005\n        max_iterations_one = 30\n        max_iterations_two = 60\n\n        while True:\n            # Assign the 1 (electrified)/0 (un-electrified) values to each cell\n            self.df[SET_ELEC_CURRENT] = self.df.apply(lambda row:\n                                                      1\n                                                      if (row[SET_NIGHT_LIGHTS] > min_night_lights and\n                                                          (row[SET_POP_CALIB] > pop_cutoff or\n                                                          row[SET_GRID_DIST_CURRENT] < max_grid_dist or\n                                                          row[SET_ROAD_DIST] < max_road_dist))\n                                                      or (row[SET_POP_CALIB] > pop_cutoff2 and\n                                                          (row[SET_GRID_DIST_CURRENT] < grid_cutoff2 or\n                                                           row[SET_ROAD_DIST] < road_cutoff2))\n                                                      else 0,\n                                                      axis=1)\n\n            # Get the calculated electrified ratio, and limit it to within reasonable boundaries\n            pop_elec = self.df.loc[self.df[SET_ELEC_CURRENT] == 1, SET_POP_CALIB].sum()\n            elec_modelled = pop_elec / pop_tot\n\n            if elec_modelled == 0:\n                elec_modelled = 0.01\n            elif elec_modelled == 1:\n                elec_modelled = 0.99\n\n            if abs(elec_modelled - elec_actual) < accuracy:\n                print('2. Modelled electrification rate = {}'.format(elec_modelled))\n                break\n            elif not is_round_two:\n                min_night_lights = sorted([5, min_night_lights - min_night_lights * 2 *\n                                           (elec_actual - elec_modelled) / elec_actual, 60])[1]\n                max_grid_dist = sorted([5, max_grid_dist + max_grid_dist * 2 *\n                                        (elec_actual - elec_modelled) / elec_actual, 150])[1]\n                max_road_dist = sorted([0.5, max_road_dist + max_road_dist * 2 *\n                                        (elec_actual - elec_modelled) / elec_actual, 50])[1]\n            elif elec_modelled - elec_actual < 0:\n                pop_cutoff2 = sorted([0.01, pop_cutoff2 - pop_cutoff2 *\n                                      (elec_actual - elec_modelled) / elec_actual, 100000])[1]\n            elif elec_modelled - elec_actual > 0:\n                pop_cutoff = sorted([0.01, pop_cutoff - pop_cutoff * 0.5 *\n                                     (elec_actual - elec_modelled) / elec_actual, 10000])[1]\n\n            constraints = '{}{}{}{}{}'.format(pop_cutoff, min_night_lights, max_grid_dist, max_road_dist, pop_cutoff2)\n            if constraints in prev_vals and not is_round_two:\n                logging.info('Repeating myself, on to round two')\n                prev_vals = []\n                is_round_two = True\n            elif constraints in prev_vals and is_round_two:\n                logging.info('NOT SATISFIED: repeating myself')\n                print('2. Modelled electrification rate = {}'.format(elec_modelled))\n                if 'y' in input('Do you want to rerun calibration with new input values? <y/n>'):\n                    count = 0\n                    is_round_two = False\n                    pop_cutoff = int(input('Enter value for pop_cutoff: '))\n                    min_night_lights = int(input('Enter value for min_night_lights: '))\n                    max_grid_dist = int(input('Enter value for max_grid_dist: '))\n                    max_road_dist = int(input('Enter value for max_road_dist: '))\n                    pop_cutoff2 = int(input('Enter value for pop_cutoff2: '))\n                else:\n                    break\n            else:\n                prev_vals.append(constraints)\n\n            if count >= max_iterations_one and not is_round_two:\n                logging.info('Got to {}, on to round two'.format(max_iterations_one))\n                is_round_two = True\n            elif count >= max_iterations_two and is_round_two:\n                logging.info('NOT SATISFIED: Got to {}'.format(max_iterations_two))\n                print('2. Modelled electrification rate = {}'.format(elec_modelled))\n                if 'y' in input('Do you want to rerun calibration with new input values? <y/n>'):\n                    count = 0\n                    is_round_two = False\n                    pop_cutoff = int(input('Enter value for pop_cutoff: '))\n                    min_night_lights = int(input('Enter value for min_night_lights: '))\n                    max_grid_dist = int(input('Enter value for max_grid_dist: '))\n                    max_road_dist = int(input('Enter value for max_road_dist: '))\n                    pop_cutoff2 = int(input('Enter value for pop_cutoff2: '))\n                else:\n                    break\n\n            count += 1\n\n        logging.info('Calculate new connections')\n        self.df.loc[self.df[SET_ELEC_CURRENT] == 1, SET_NEW_CONNECTIONS] =\\\n            self.df[SET_POP_FUTURE] - self.df[SET_POP_CALIB]\n        self.df.loc[self.df[SET_ELEC_CURRENT] == 0, SET_NEW_CONNECTIONS] = self.df[SET_POP_FUTURE]\n        self.df.loc[self.df[SET_NEW_CONNECTIONS] < 0, SET_NEW_CONNECTIONS] = 0\n\n        return min_night_lights, max_grid_dist, max_road_dist, elec_modelled, pop_cutoff, pop_cutoff2\n\n    @staticmethod\n    def separate_elec_status(elec_status):\n        \"\"\"\n        Separate out the electrified and unelectrified states from list.\n        \"\"\"\n\n        electrified = []\n        unelectrified = []\n\n        for i, status in enumerate(elec_status):\n            if status:\n                electrified.append(i)\n            else:\n                unelectrified.append(i)\n        return electrified, unelectrified\n\n    @staticmethod\n    def get_2d_hash_table(x, y, unelectrified, distance_limit):\n        \"\"\"\n        Generates the 2D Hash Table with the unelectrified locations hashed into the table for easy O(1) access.\n        \"\"\"\n\n        hash_table = defaultdict(lambda: defaultdict(list))\n        for unelec_row in unelectrified:\n            hash_x = int(x[unelec_row] / distance_limit)\n            hash_y = int(y[unelec_row] / distance_limit)\n            hash_table[hash_x][hash_y].append(unelec_row)\n        return hash_table\n\n    @staticmethod\n    def get_unelectrified_rows(hash_table, elec_row, x, y, distance_limit):\n        \"\"\"\n        Returns all the unelectrified locations close to the electrified location\n        based on the distance boundary limit specified by asking the 2D hash table.\n        \"\"\"\n\n        unelec_list = []\n        hash_x = int(x[elec_row] / distance_limit)\n        hash_y = int(y[elec_row] / distance_limit)\n\n        unelec_list.extend(hash_table.get(hash_x, {}).get(hash_y, []))\n        unelec_list.extend(hash_table.get(hash_x, {}).get(hash_y - 1, []))\n        unelec_list.extend(hash_table.get(hash_x, {}).get(hash_y + 1, []))\n\n        unelec_list.extend(hash_table.get(hash_x + 1, {}).get(hash_y, []))\n        unelec_list.extend(hash_table.get(hash_x + 1, {}).get(hash_y - 1, []))\n        unelec_list.extend(hash_table.get(hash_x + 1, {}).get(hash_y + 1, []))\n\n        unelec_list.extend(hash_table.get(hash_x - 1, {}).get(hash_y, []))\n        unelec_list.extend(hash_table.get(hash_x - 1, {}).get(hash_y - 1, []))\n        unelec_list.extend(hash_table.get(hash_x - 1, {}).get(hash_y + 1, []))\n\n        return unelec_list\n\n    def pre_elec(self, grid_lcoes_rural, grid_lcoes_urban, pre_elec_dist):\n        \"\"\"\n        Determine which settlements are economically close to existing or planned grid lines, and should be\n        considered electrified in the electrification algorithm\n        \"\"\"\n\n        df_neargrid = self.df.loc[self.df[SET_GRID_DIST_PLANNED] < pre_elec_dist]\n\n        pop = df_neargrid[SET_POP_FUTURE].tolist()\n        urban = df_neargrid[SET_URBAN].tolist()\n        grid_penalty_ratio = df_neargrid[SET_GRID_PENALTY].tolist()\n        status = df_neargrid[SET_ELEC_CURRENT].tolist()\n        min_tech_lcoes = df_neargrid[SET_MIN_OFFGRID_LCOE].tolist()\n        dist_planned = df_neargrid[SET_GRID_DIST_PLANNED].tolist()\n\n        electrified, unelectrified = self.separate_elec_status(status)\n\n        for unelec in unelectrified:\n\n            pop_index = pop[unelec]\n            if pop_index < 1000:\n                pop_index = int(pop_index)\n            elif pop_index < 10000:\n                pop_index = 10 * round(pop_index / 10)\n            else:\n                pop_index = 1000 * round(pop_index / 1000)\n\n            if urban[unelec]:\n                grid_lcoe = grid_lcoes_urban[pop_index][int(grid_penalty_ratio[unelec] * dist_planned[unelec])]\n            else:\n                grid_lcoe = grid_lcoes_rural[pop_index][int(grid_penalty_ratio[unelec] * dist_planned[unelec])]\n\n            if grid_lcoe < min_tech_lcoes[unelec]:\n                status[unelec] = 1\n\n        return status\n\n    def elec_extension(self, grid_lcoes_rural, grid_lcoes_urban, existing_grid_cost_ratio, max_dist, coordinate_units):\n        \"\"\"\n        Iterate through all electrified settlements and find which settlements can be economically connected to the grid\n        Repeat with newly electrified settlements until no more are added\n        \"\"\"\n\n        x = (self.df[SET_X]/coordinate_units).tolist()\n        y = (self.df[SET_Y]/coordinate_units).tolist()\n        pop = self.df[SET_POP_FUTURE].tolist()\n        urban = self.df[SET_URBAN].tolist()\n        grid_penalty_ratio = self.df[SET_GRID_PENALTY].tolist()\n        status = self.df[SET_ELEC_FUTURE].tolist()\n        min_tech_lcoes = self.df[SET_MIN_OFFGRID_LCOE].tolist()\n        new_lcoes = self.df[SET_LCOE_GRID].tolist()\n\n        cell_path_real = list(np.zeros(len(status)).tolist())\n        cell_path_adjusted = list(np.zeros(len(status)).tolist())\n        electrified, unelectrified = self.separate_elec_status(status)\n\n        logging.info('Initially {} cells electrified'.format(len(electrified)))\n\n        close = []\n        elec_nodes2 = []\n        changes = []\n        for elec in electrified:\n            elec_nodes2.append((x[elec], y[elec]))\n        elec_nodes2 = np.asarray(elec_nodes2)\n\n        def closest_elec(unelec_node, elec_nodes):\n            deltas = elec_nodes - unelec_node\n            dist_2 = np.einsum('ij,ij->i', deltas, deltas)\n            return np.argmin(dist_2)\n\n        for unelec in unelectrified:\n            pop_index = pop[unelec]\n            if pop_index < 1000:\n                pop_index = int(pop_index)\n            elif pop_index < 10000:\n                pop_index = 10 * round(pop_index / 10)\n            else:\n                pop_index = 1000 * round(pop_index / 1000)\n\n            if urban[unelec]:\n                grid_lcoe = grid_lcoes_urban[pop_index][1]\n            else:\n                grid_lcoe = grid_lcoes_rural[pop_index][1]\n            if grid_lcoe <= min_tech_lcoes[unelec]:\n                node = (x[unelec], y[unelec])\n                closest_elec_node = closest_elec(node, elec_nodes2)\n                dist = sqrt((x[electrified[closest_elec_node]] - x[unelec]) ** 2\n                            + (y[electrified[closest_elec_node]] - y[unelec]) ** 2)\n                if dist <= max_dist:\n                    dist_adjusted = grid_penalty_ratio[unelec] * dist\n                    if dist_adjusted < max_dist:\n                        if urban[unelec]:\n                            grid_lcoe = grid_lcoes_urban[pop_index][int(dist_adjusted)]\n                        else:\n                            grid_lcoe = grid_lcoes_rural[pop_index][int(dist_adjusted)]\n\n                        if grid_lcoe < min_tech_lcoes[unelec]:\n                            if grid_lcoe < new_lcoes[unelec]:\n                                new_lcoes[unelec] = grid_lcoe\n                                cell_path_real[unelec] = dist\n                                cell_path_adjusted[unelec] = dist_adjusted\n                                if unelec not in changes:\n                                    changes.append(unelec)\n                            else:\n                                close.append(unelec)\n                        else:\n                            close.append(unelec)\n                    else:\n                        close.append(unelec)\n        electrified = changes[:]\n        unelectrified = close\n\n        loops = 1\n        while len(electrified) > 0:\n            logging.info('Electrification loop {} with {} electrified'.format(loops, len(electrified)))\n            loops += 1\n            hash_table = self.get_2d_hash_table(x, y, unelectrified, max_dist)\n\n            changes = []\n            for elec in electrified:\n                unelectrified_hashed = self.get_unelectrified_rows(hash_table, elec, x, y, max_dist)\n                for unelec in unelectrified_hashed:\n                    prev_dist = cell_path_real[elec]\n                    dist = sqrt((x[elec] - x[unelec]) ** 2 + (y[elec] - y[unelec]) ** 2)\n                    if prev_dist + dist < max_dist:\n                        pop_index = pop[unelec]\n                        if pop_index < 1000:\n                            pop_index = int(pop_index)\n                        elif pop_index < 10000:\n                            pop_index = 10 * round(pop_index / 10)\n                        else:\n                            pop_index = 1000 * round(pop_index / 1000)\n\n                        dist_adjusted = grid_penalty_ratio[unelec]*(dist + existing_grid_cost_ratio * prev_dist)\n\n                        if urban[unelec]:\n                            grid_lcoe = grid_lcoes_urban[pop_index][int(dist_adjusted)]\n                        else:\n                            grid_lcoe = grid_lcoes_rural[pop_index][int(dist_adjusted)]\n\n                        if grid_lcoe < min_tech_lcoes[unelec]:\n                            if grid_lcoe < new_lcoes[unelec]:\n                                new_lcoes[unelec] = grid_lcoe\n                                cell_path_real[unelec] = dist + prev_dist\n                                cell_path_adjusted[unelec] = dist_adjusted\n                                if unelec not in changes:\n                                    changes.append(unelec)\n\n            electrified = changes[:]\n            unelectrified = [x for x in unelectrified if x not in electrified]\n\n        return new_lcoes, cell_path_adjusted\n\n    def run_elec(self, grid_lcoes_rural, grid_lcoes_urban, grid_price,\n                 existing_grid_cost_ratio, max_dist, coordinate_units):\n        \"\"\"\n        Runs the pre-elec and grid extension algorithms\n        \"\"\"\n\n        # Calculate 2030 pre-electrification\n        logging.info('Determine future pre-electrification status')\n        self.df[SET_ELEC_FUTURE] = self.df.apply(lambda row: 1 if row[SET_ELEC_CURRENT] == 1 else 0, axis=1)\n\n        pre_elec_dist = 10  # The maximum distance from the grid in km to pre-electrifiy settlements\n        self.df.loc[self.df[SET_GRID_DIST_PLANNED] < pre_elec_dist, SET_ELEC_FUTURE] = self.pre_elec(grid_lcoes_rural,\n                                                                                                     grid_lcoes_urban,\n                                                                                                     pre_elec_dist)\n\n        self.df[SET_LCOE_GRID] = 99\n        self.df[SET_LCOE_GRID] = self.df.apply(lambda row: grid_price if row[SET_ELEC_FUTURE] == 1 else 99, axis=1)\n\n        self.df[SET_LCOE_GRID], self.df[SET_MIN_GRID_DIST] = self.elec_extension(grid_lcoes_rural, grid_lcoes_urban,\n                                                                                 existing_grid_cost_ratio,\n                                                                                 max_dist, coordinate_units)\n\n    def set_scenario_variables(self, energy_per_hh_rural, energy_per_hh_urban,\n                               num_people_per_hh_rural, num_people_per_hh_urban):\n        \"\"\"\n        Set the basic scenario parameters that differ based on urban/rural\n        So that they are in the table and can be read directly to calculate LCOEs\n        \"\"\"\n\n        logging.info('Setting electrification targets')\n        self.df.loc[self.df[SET_URBAN] == 0, SET_ENERGY_PER_HH] = energy_per_hh_rural\n        self.df.loc[self.df[SET_URBAN] == 1, SET_ENERGY_PER_HH] = energy_per_hh_urban\n\n        self.df.loc[self.df[SET_URBAN] == 0, SET_NUM_PEOPLE_PER_HH] = num_people_per_hh_rural\n        self.df.loc[self.df[SET_URBAN] == 1, SET_NUM_PEOPLE_PER_HH] = num_people_per_hh_urban\n\n    def calculate_off_grid_lcoes(self, mg_hydro_calc, mg_wind_calc, mg_pv_calc,\n                                 sa_pv_calc, mg_diesel_calc, sa_diesel_calc):\n        \"\"\"\n        Calcuate the LCOEs for all off-grid technologies, and calculate the minimum, so that the electrification\n        algorithm knows where the bar is before it becomes economical to electrify\n        \"\"\"\n\n        # A df with all hydropower sites, to ensure that they aren't assigned more capacity than is available\n        hydro_used = 'HydropowerUsed'  # the amount of the hydro potential that has been assigned\n        hydro_df = self.df[[SET_HYDRO_FID, SET_HYDRO]].drop_duplicates(subset=SET_HYDRO_FID)\n        hydro_df[hydro_used] = 0\n        hydro_df = hydro_df.set_index(SET_HYDRO_FID)\n\n        max_hydro_dist = 5  # the max distance in km to consider hydropower viable\n\n        def hydro_lcoe(row):\n            if row[SET_HYDRO_DIST] < max_hydro_dist:\n                # calculate the capacity that would be added by the settlement\n                additional_capacity = ((row[SET_NEW_CONNECTIONS] * row[SET_ENERGY_PER_HH] / row[SET_NUM_PEOPLE_PER_HH])\n                                       / (HOURS_PER_YEAR * mg_hydro_calc.capacity_factor *\n                                          mg_hydro_calc.base_to_peak_load_ratio))\n\n                # and add it to the tracking df\n                hydro_df.loc[row[SET_HYDRO_FID], hydro_used] += additional_capacity\n\n                # if it exceeds the available capacity, it's not an option\n                if hydro_df.loc[row[SET_HYDRO_FID], hydro_used] > hydro_df.loc[row[SET_HYDRO_FID], SET_HYDRO]:\n                    return 99\n\n                else:\n                    return mg_hydro_calc.get_lcoe(energy_per_hh=row[SET_ENERGY_PER_HH],\n                                                  people=row[SET_POP_FUTURE],\n                                                  num_people_per_hh=row[SET_NUM_PEOPLE_PER_HH],\n                                                  mv_line_length=row[SET_HYDRO_DIST])\n            else:\n                return 99\n\n        logging.info('Calculate minigrid hydro LCOE')\n        self.df[SET_LCOE_MG_HYDRO] = self.df.apply(hydro_lcoe, axis=1)\n\n        num_hydro_limited = hydro_df.loc[hydro_df[hydro_used] > hydro_df[SET_HYDRO]][SET_HYDRO].count()\n        logging.info('{} potential hydropower sites were utilised to maximum capacity'.format(num_hydro_limited))\n\n        logging.info('Calculate minigrid PV LCOE')\n        self.df[SET_LCOE_MG_PV] = self.df.apply(\n            lambda row: mg_pv_calc.get_lcoe(energy_per_hh=row[SET_ENERGY_PER_HH],\n                                            people=row[SET_POP_FUTURE],\n                                            num_people_per_hh=row[SET_NUM_PEOPLE_PER_HH],\n                                            capacity_factor=row[SET_GHI] / HOURS_PER_YEAR)\n            if (row[SET_SOLAR_RESTRICTION] == 1 and row[SET_GHI] > 1000) else 99,\n            axis=1)\n\n        logging.info('Calculate minigrid wind LCOE')\n        self.df[SET_LCOE_MG_WIND] = self.df.apply(\n            lambda row: mg_wind_calc.get_lcoe(energy_per_hh=row[SET_ENERGY_PER_HH],\n                                              people=row[SET_POP_FUTURE],\n                                              num_people_per_hh=row[SET_NUM_PEOPLE_PER_HH],\n                                              capacity_factor=row[SET_WINDCF])\n            if row[SET_WINDCF] > 0.1 else 99,\n            axis=1)\n\n        logging.info('Calculate minigrid diesel LCOE')\n        self.df[SET_LCOE_MG_DIESEL] = self.df.apply(\n            lambda row:\n            mg_diesel_calc.get_lcoe(energy_per_hh=row[SET_ENERGY_PER_HH],\n                                    people=row[SET_POP_FUTURE],\n                                    num_people_per_hh=row[SET_NUM_PEOPLE_PER_HH],\n                                    travel_hours=row[SET_TRAVEL_HOURS]),\n            axis=1)\n\n        logging.info('Calculate standalone diesel LCOE')\n        self.df[SET_LCOE_SA_DIESEL] = self.df.apply(\n            lambda row:\n            sa_diesel_calc.get_lcoe(energy_per_hh=row[SET_ENERGY_PER_HH],\n                                    people=row[SET_POP_FUTURE],\n                                    num_people_per_hh=row[SET_NUM_PEOPLE_PER_HH],\n                                    travel_hours=row[SET_TRAVEL_HOURS]),\n            axis=1)\n\n        logging.info('Calculate standalone PV LCOE')\n        self.df[SET_LCOE_SA_PV] = self.df.apply(\n            lambda row: sa_pv_calc.get_lcoe(energy_per_hh=row[SET_ENERGY_PER_HH],\n                                            people=row[SET_POP_FUTURE],\n                                            num_people_per_hh=row[SET_NUM_PEOPLE_PER_HH],\n                                            capacity_factor=row[SET_GHI] / HOURS_PER_YEAR)\n            if row[SET_GHI] > 1000 else 99,\n            axis=1)\n\n        logging.info('Determine minimum technology (no grid)')\n        self.df[SET_MIN_OFFGRID] = self.df[[SET_LCOE_SA_DIESEL, SET_LCOE_SA_PV, SET_LCOE_MG_WIND,\n                                            SET_LCOE_MG_DIESEL, SET_LCOE_MG_PV, SET_LCOE_MG_HYDRO]].T.idxmin()\n\n        logging.info('Determine minimum tech LCOE')\n        self.df[SET_MIN_OFFGRID_LCOE] = self.df.apply(lambda row: (row[row[SET_MIN_OFFGRID]]), axis=1)\n\n    def results_columns(self, mg_hydro_calc, mg_wind_calc, mg_pv_calc, sa_pv_calc,\n                        mg_diesel_calc, sa_diesel_calc, grid_calc):\n        \"\"\"\n        Once the grid extension algorithm has been run, determine the minimum overall option, and calculate the\n        capacity and investment requirements for each settlement\n        \"\"\"\n\n        def res_investment_cost(row):\n            min_tech = row[SET_MIN_OVERALL]\n            if min_tech == SET_LCOE_SA_DIESEL:\n                return sa_diesel_calc.get_lcoe(energy_per_hh=row[SET_ENERGY_PER_HH],\n                                               people=row[SET_POP_FUTURE],\n                                               num_people_per_hh=row[SET_NUM_PEOPLE_PER_HH],\n                                               travel_hours=row[SET_TRAVEL_HOURS],\n                                               get_investment_cost=True)\n            elif min_tech == SET_LCOE_SA_PV:\n                return sa_pv_calc.get_lcoe(energy_per_hh=row[SET_ENERGY_PER_HH],\n                                           people=row[SET_POP_FUTURE],\n                                           num_people_per_hh=row[SET_NUM_PEOPLE_PER_HH],\n                                           capacity_factor=row[SET_GHI] / HOURS_PER_YEAR,\n                                           get_investment_cost=True)\n            elif min_tech == SET_LCOE_MG_WIND:\n                return mg_wind_calc.get_lcoe(energy_per_hh=row[SET_ENERGY_PER_HH],\n                                             people=row[SET_POP_FUTURE],\n                                             num_people_per_hh=row[SET_NUM_PEOPLE_PER_HH],\n                                             capacity_factor=row[SET_WINDCF],\n                                             get_investment_cost=True)\n            elif min_tech == SET_LCOE_MG_DIESEL:\n                return mg_diesel_calc.get_lcoe(energy_per_hh=row[SET_ENERGY_PER_HH],\n                                               people=row[SET_POP_FUTURE],\n                                               num_people_per_hh=row[SET_NUM_PEOPLE_PER_HH],\n                                               travel_hours=row[SET_TRAVEL_HOURS],\n                                               get_investment_cost=True)\n            elif min_tech == SET_LCOE_MG_PV:\n                return mg_pv_calc.get_lcoe(energy_per_hh=row[SET_ENERGY_PER_HH],\n                                           people=row[SET_POP_FUTURE],\n                                           num_people_per_hh=row[SET_NUM_PEOPLE_PER_HH],\n                                           capacity_factor=row[SET_GHI] / HOURS_PER_YEAR,\n                                           get_investment_cost=True)\n            elif min_tech == SET_LCOE_MG_HYDRO:\n                return mg_hydro_calc.get_lcoe(energy_per_hh=row[SET_ENERGY_PER_HH],\n                                              people=row[SET_POP_FUTURE],\n                                              num_people_per_hh=row[SET_NUM_PEOPLE_PER_HH],\n                                              mv_line_length=row[SET_HYDRO_DIST],\n                                              get_investment_cost=True)\n            elif min_tech == SET_LCOE_GRID:\n                return grid_calc.get_lcoe(energy_per_hh=row[SET_ENERGY_PER_HH],\n                                          people=row[SET_POP_FUTURE],\n                                          num_people_per_hh=row[SET_NUM_PEOPLE_PER_HH],\n                                          additional_mv_line_length=row[SET_MIN_GRID_DIST],\n                                          get_investment_cost=True)\n            else:\n                raise ValueError('A technology has not been accounted for in res_investment_cost()')\n\n        logging.info('Determine minimum overall')\n        self.df[SET_MIN_OVERALL] = self.df[[SET_LCOE_GRID, SET_LCOE_SA_DIESEL, SET_LCOE_SA_PV, SET_LCOE_MG_WIND,\n                                            SET_LCOE_MG_DIESEL, SET_LCOE_MG_PV, SET_LCOE_MG_HYDRO]].T.idxmin()\n\n        logging.info('Determine minimum overall LCOE')\n        self.df[SET_MIN_OVERALL_LCOE] = self.df.apply(lambda row: (row[row[SET_MIN_OVERALL]]), axis=1)\n\n        logging.info('Add technology codes')\n        codes = {SET_LCOE_GRID: 1, SET_LCOE_MG_HYDRO: 7, SET_LCOE_MG_WIND: 6, SET_LCOE_MG_PV: 5,\n                 SET_LCOE_MG_DIESEL: 4, SET_LCOE_SA_DIESEL: 2, SET_LCOE_SA_PV: 3}\n        self.df.loc[self.df[SET_MIN_OVERALL] == SET_LCOE_GRID, SET_MIN_OVERALL_CODE] = codes[SET_LCOE_GRID]\n        self.df.loc[self.df[SET_MIN_OVERALL] == SET_LCOE_MG_HYDRO, SET_MIN_OVERALL_CODE] = codes[SET_LCOE_MG_HYDRO]\n        self.df.loc[self.df[SET_MIN_OVERALL] == SET_LCOE_SA_PV, SET_MIN_OVERALL_CODE] = codes[SET_LCOE_SA_PV]\n        self.df.loc[self.df[SET_MIN_OVERALL] == SET_LCOE_MG_WIND, SET_MIN_OVERALL_CODE] = codes[SET_LCOE_MG_WIND]\n        self.df.loc[self.df[SET_MIN_OVERALL] == SET_LCOE_MG_PV, SET_MIN_OVERALL_CODE] = codes[SET_LCOE_MG_PV]\n        self.df.loc[self.df[SET_MIN_OVERALL] == SET_LCOE_MG_DIESEL, SET_MIN_OVERALL_CODE] = codes[SET_LCOE_MG_DIESEL]\n        self.df.loc[self.df[SET_MIN_OVERALL] == SET_LCOE_SA_DIESEL, SET_MIN_OVERALL_CODE] = codes[SET_LCOE_SA_DIESEL]\n\n        logging.info('Determine minimum category')\n        self.df[SET_MIN_CATEGORY] = self.df[SET_MIN_OVERALL].str.extract('(SA|MG|Grid)', expand=False)\n\n        logging.info('Calculate new capacity')\n        self.df.loc[self.df[SET_MIN_OVERALL] == SET_LCOE_GRID, SET_NEW_CAPACITY] = (\n            (self.df[SET_NEW_CONNECTIONS] * self.df[SET_ENERGY_PER_HH] / self.df[SET_NUM_PEOPLE_PER_HH]) /\n            (HOURS_PER_YEAR * grid_calc.capacity_factor * grid_calc.base_to_peak_load_ratio\n             * (1 - grid_calc.distribution_losses)))\n        self.df.loc[self.df[SET_MIN_OVERALL] == SET_LCOE_MG_HYDRO, SET_NEW_CAPACITY] = (\n            (self.df[SET_NEW_CONNECTIONS] * self.df[SET_ENERGY_PER_HH] / self.df[SET_NUM_PEOPLE_PER_HH]) /\n            (HOURS_PER_YEAR * mg_hydro_calc.capacity_factor * mg_hydro_calc.base_to_peak_load_ratio\n             * (1 - mg_hydro_calc.distribution_losses)))\n        self.df.loc[self.df[SET_MIN_OVERALL] == SET_LCOE_MG_PV, SET_NEW_CAPACITY] = (\n            (self.df[SET_NEW_CONNECTIONS] * self.df[SET_ENERGY_PER_HH] / self.df[SET_NUM_PEOPLE_PER_HH]) /\n            (HOURS_PER_YEAR * (self.df[SET_GHI] / HOURS_PER_YEAR) * mg_pv_calc.base_to_peak_load_ratio\n             * (1 - mg_pv_calc.distribution_losses)))\n        self.df.loc[self.df[SET_MIN_OVERALL] == SET_LCOE_MG_WIND, SET_NEW_CAPACITY] = (\n            (self.df[SET_NEW_CONNECTIONS] * self.df[SET_ENERGY_PER_HH] / self.df[SET_NUM_PEOPLE_PER_HH]) /\n            (HOURS_PER_YEAR * self.df[SET_WINDCF] * mg_wind_calc.base_to_peak_load_ratio\n             * (1 - mg_wind_calc.distribution_losses)))\n        self.df.loc[self.df[SET_MIN_OVERALL] == SET_LCOE_MG_DIESEL, SET_NEW_CAPACITY] = (\n            (self.df[SET_NEW_CONNECTIONS] * self.df[SET_ENERGY_PER_HH] / self.df[SET_NUM_PEOPLE_PER_HH]) /\n            (HOURS_PER_YEAR * mg_diesel_calc.capacity_factor * mg_diesel_calc.base_to_peak_load_ratio\n             * (1 - mg_diesel_calc.distribution_losses)))\n        self.df.loc[self.df[SET_MIN_OVERALL] == SET_LCOE_SA_DIESEL, SET_NEW_CAPACITY] = (\n            (self.df[SET_NEW_CONNECTIONS] * self.df[SET_ENERGY_PER_HH] / self.df[SET_NUM_PEOPLE_PER_HH]) /\n            (HOURS_PER_YEAR * sa_diesel_calc.capacity_factor * sa_diesel_calc.base_to_peak_load_ratio\n             * (1 - sa_diesel_calc.distribution_losses)))\n        self.df.loc[self.df[SET_MIN_OVERALL] == SET_LCOE_SA_PV, SET_NEW_CAPACITY] = (\n            (self.df[SET_NEW_CONNECTIONS] * self.df[SET_ENERGY_PER_HH] / self.df[SET_NUM_PEOPLE_PER_HH]) /\n            (HOURS_PER_YEAR * (self.df[SET_GHI] / HOURS_PER_YEAR) * sa_pv_calc.base_to_peak_load_ratio\n             * (1 - sa_pv_calc.distribution_losses)))\n\n        logging.info('Calculate investment cost')\n        self.df[SET_INVESTMENT_COST] = self.df.apply(res_investment_cost, axis=1)\n\n    def calc_summaries(self):\n        \"\"\"\n        The next section calculates the summaries for technology split, consumption added and total investment cost\n        \"\"\"\n\n        population_ = 'population_'\n        new_connections_ = 'new_connections_'\n        capacity_ = 'capacity_'\n        investments_ = 'investment_'\n\n        logging.info('Calculate summaries')\n        rows = []\n        techs = [SET_LCOE_GRID, SET_LCOE_SA_DIESEL, SET_LCOE_SA_PV, SET_LCOE_MG_WIND,\n                 SET_LCOE_MG_DIESEL, SET_LCOE_MG_PV, SET_LCOE_MG_HYDRO]\n        rows.extend([population_ + t for t in techs])\n        rows.extend([new_connections_ + t for t in techs])\n        rows.extend([capacity_ + t for t in techs])\n        rows.extend([investments_ + t for t in techs])\n        summary = pd.Series(index=rows)\n\n        for t in techs:\n            summary.loc[population_ + t] = self.df.loc[self.df[SET_MIN_OVERALL] == t, SET_POP_FUTURE].sum()\n            summary.loc[new_connections_ + t] = self.df.loc[self.df[SET_MIN_OVERALL] == t, SET_NEW_CONNECTIONS].sum()\n            summary.loc[capacity_ + t] = self.df.loc[self.df[SET_MIN_OVERALL] == t, SET_NEW_CAPACITY].sum()\n            summary.loc[investments_ + t] = self.df.loc[self.df[SET_MIN_OVERALL] == t, SET_INVESTMENT_COST].sum()\n\n        return summary\n", "meta": {"hexsha": "e0314600049cb3b94b6bebc5b3f2a88425de621b", "size": 58838, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyonsset/onsset.py", "max_stars_repo_name": "Slbalderrama/OnSSET-2016", "max_stars_repo_head_hexsha": "458caf306389758a064257a15bddd9f79656ecdb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyonsset/onsset.py", "max_issues_repo_name": "Slbalderrama/OnSSET-2016", "max_issues_repo_head_hexsha": "458caf306389758a064257a15bddd9f79656ecdb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyonsset/onsset.py", "max_forks_repo_name": "Slbalderrama/OnSSET-2016", "max_forks_repo_head_hexsha": "458caf306389758a064257a15bddd9f79656ecdb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.4181662382, "max_line_length": 120, "alphanum_fraction": 0.6059519358, "include": true, "reason": "import numpy", "num_tokens": 14355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.17844958727732563}}
{"text": "###bbox_tools.py部分的代码主要由四个函数构成：1loc2bbox(src_bbox,loc)和bbox2loc(src_bbox,dst_bbox)是一对函数，其功能是刚好相反的，\n#比如loc2bbox()看其函数的参数src_bbox,loc就知道是有已知源框框和位置偏差，求出目标框框的作用，\n#而bbox2loc(src_bbox,dst_bbox)函数看其参数就知道是完成已知源框框和参考框框求出其位置偏差的功能！\n#而这个bbox_iou看函数名字我们也大概能猜出是求两个bbox的相交的交并比的功能，\n#最后的generate_anchor_base()的功能大概就是根据基准点生成9个基本的anchor的功能！\n#ratios=[0.5,1,2],anchor_scales=[8,16,32]是长宽比和缩放比例，3x3的参数刚好得到9个anchor!\n\n\nimport numpy as np\nimport numpy as xp\n\nimport six\nfrom six import __init__\n #给定源框和loc 反向计算目标框 还原方法 与bbox2loc对应，用于将anchor调整后得到ROI\ndef loc2bbox(src_bbox, loc):\n    \"\"\"Decode bounding boxes from bounding box offsets and scales.\n\n    Given bounding box offsets and scales computed by\n    :meth:`bbox2loc`, this function decodes the representation to\n    coordinates in 2D image coordinates.\n\n    Given scales and offsets :math:`t_y, t_x, t_h, t_w` and a bounding\n    box whose center is :math:`(y, x) = p_y, p_x` and size :math:`p_h, p_w`,\n    the decoded bounding box's center :math:`\\\\hat{g}_y`, :math:`\\\\hat{g}_x`\n    and size :math:`\\\\hat{g}_h`, :math:`\\\\hat{g}_w` are calculated\n    by the following formulas.\n\n    * :math:`\\\\hat{g}_y = p_h t_y + p_y`\n    * :math:`\\\\hat{g}_x = p_w t_x + p_x`\n    * :math:`\\\\hat{g}_h = p_h \\\\exp(t_h)`\n    * :math:`\\\\hat{g}_w = p_w \\\\exp(t_w)`\n\n    The decoding formulas are used in works such as R-CNN [#]_.\n\n    The output is same type as the type of the inputs.\n\n    .. [#] Ross Girshick, Jeff Donahue, Trevor Darrell, Jitendra Malik. \\\n    Rich feature hierarchies for accurate object detection and semantic \\\n    segmentation. CVPR 2014.\n\n    Args:\n        src_bbox (array): A coordinates of bounding boxes.\n            Its shape is :math:`(R, 4)`. These coordinates are\n            :math:`p_{ymin}, p_{xmin}, p_{ymax}, p_{xmax}`.\n        loc (array): An array with offsets and scales.\n            The shapes of :obj:`src_bbox` and :obj:`loc` should be same.\n            This contains values :math:`t_y, t_x, t_h, t_w`.\n\n    Returns:\n        array:\n        Decoded bounding box coordinates. Its shape is :math:`(R, 4)`. \\\n        The second axis contains four values \\\n        :math:`\\\\hat{g}_{ymin}, \\\\hat{g}_{xmin},\n        \\\\hat{g}_{ymax}, \\\\hat{g}_{xmax}`.\n\n    \"\"\"\n\n    if src_bbox.shape[0] == 0:\n        return xp.zeros((0, 4), dtype=loc.dtype)\n\n    src_bbox = src_bbox.astype(src_bbox.dtype, copy=False)\n\n    src_height = src_bbox[:, 2] - src_bbox[:, 0]\n    src_width = src_bbox[:, 3] - src_bbox[:, 1] \n    src_ctr_y = src_bbox[:, 0] + 0.5 * src_height \n    src_ctr_x = src_bbox[:, 1] + 0.5 * src_width   \n\n    dy = loc[:, 0::4]  #读取输入的偏移量dy、dx、dw、dh\n    dx = loc[:, 1::4]\n    dh = loc[:, 2::4]\n    dw = loc[:, 3::4]\n\n    ctr_y = dy * src_height[:, xp.newaxis] + src_ctr_y[:, xp.newaxis]  #代入公式Gy=dy(p)*Ph+py\n    ctr_x = dx * src_width[:, xp.newaxis] + src_ctr_x[:, xp.newaxis]\n    h = xp.exp(dh) * src_height[:, xp.newaxis]\n    w = xp.exp(dw) * src_width[:, xp.newaxis]\n\n    dst_bbox = xp.zeros(loc.shape, dtype=loc.dtype)\n    dst_bbox[:, 0::4] = ctr_y - 0.5 * h    #还原回左上角右下角的坐标形式\n    dst_bbox[:, 1::4] = ctr_x - 0.5 * w\n    dst_bbox[:, 2::4] = ctr_y + 0.5 * h\n    dst_bbox[:, 3::4] = ctr_x + 0.5 * w\n\n    return dst_bbox\n\n\ndef bbox2loc(src_bbox, dst_bbox):#给定两个框 返回源框到目标框变换的loc偏移量 这原论文中说的很详细\n    \"\"\"Encodes the source and the destination bounding boxes to \"loc\".\n\n    Given bounding boxes, this function computes offsets and scales\n    to match the source bounding boxes to the target bounding boxes.\n    Mathematcially, given a bounding box whose center is\n    :math:`(y, x) = p_y, p_x` and\n    size :math:`p_h, p_w` and the target bounding box whose center is\n    :math:`g_y, g_x` and size :math:`g_h, g_w`, the offsets and scales\n    :math:`t_y, t_x, t_h, t_w` can be computed by the following formulas.\n\n    * :math:`t_y = \\\\frac{(g_y - p_y)} {p_h}`\n    * :math:`t_x = \\\\frac{(g_x - p_x)} {p_w}`\n    * :math:`t_h = \\\\log(\\\\frac{g_h} {p_h})`\n    * :math:`t_w = \\\\log(\\\\frac{g_w} {p_w})`\n\n    The output is same type as the type of the inputs.\n    The encoding formulas are used in works such as R-CNN [#]_.\n\n    .. [#] Ross Girshick, Jeff Donahue, Trevor Darrell, Jitendra Malik. \\\n    Rich feature hierarchies for accurate object detection and semantic \\\n    segmentation. CVPR 2014.\n\n    Args:\n        src_bbox (array): An image coordinate array whose shape is\n            :math:`(R, 4)`. :math:`R` is the number of bounding boxes.\n            These coordinates are\n            :math:`p_{ymin}, p_{xmin}, p_{ymax}, p_{xmax}`.\n        dst_bbox (array): An image coordinate array whose shape is\n            :math:`(R, 4)`.\n            These coordinates are\n            :math:`g_{ymin}, g_{xmin}, g_{ymax}, g_{xmax}`.\n\n    Returns:\n        array:\n        Bounding box offsets and scales from :obj:`src_bbox` \\\n        to :obj:`dst_bbox`. \\\n        This has shape :math:`(R, 4)`.\n        The second axis contains four values :math:`t_y, t_x, t_h, t_w`.\n\n    \"\"\"\n\n    height = src_bbox[:, 2] - src_bbox[:, 0] #源框高\n    width = src_bbox[:, 3] - src_bbox[:, 1]#源框宽\n    ctr_y = src_bbox[:, 0] + 0.5 * height#源框中心y坐标\n    ctr_x = src_bbox[:, 1] + 0.5 * width#源框中心x坐标 \n\n    base_height = dst_bbox[:, 2] - dst_bbox[:, 0] #t框高\n    base_width = dst_bbox[:, 3] - dst_bbox[:, 1]\n    base_ctr_y = dst_bbox[:, 0] + 0.5 * base_height\n    base_ctr_x = dst_bbox[:, 1] + 0.5 * base_width\n\n    eps = xp.finfo(height.dtype).eps #eps是个很小的非负数，用于防止除法分母为零的错误，使用eps将可能出现的零用eps代替，防止报错\n    height = xp.maximum(height, eps)\n    width = xp.maximum(width, eps)\n\n    dy = (base_ctr_y - ctr_y) / height #平移量tx=(Gx-Px)/Pw\n    dx = (base_ctr_x - ctr_x) / width\n    dh = xp.log(base_height / height)\n    dw = xp.log(base_width / width)\n\n    loc = xp.vstack((dy, dx, dh, dw)).transpose() #vstack:按垂直方向（行顺序）堆叠数组构成一个新的数组\n    return loc\n\n\ndef bbox_iou(bbox_a, bbox_b):\n    #计算两个框的IOU值 我们在cuda计算时已经见过了 但是这个方法的bbox_a与bbox_b可以是多维数组的(X,4)(Y,4)\n     #则返回的结果也是多维的结果（X,Y）\n    \"\"\"Calculate the Intersection of Unions (IoUs) between bounding boxes.\n\n    IoU is calculated as a ratio of area of the intersection\n    and area of the union.\n\n    This function accepts both :obj:`numpy.ndarray` and :obj:`cupy.ndarray` as\n    inputs. Please note that both :obj:`bbox_a` and :obj:`bbox_b` need to be\n    same type.\n    The output is same type as the type of the inputs.\n\n    Args:\n        bbox_a (array): An array whose shape is :math:`(N, 4)`.\n            :math:`N` is the number of bounding boxes.\n            The dtype should be :obj:`numpy.float32`.\n        bbox_b (array): An array similar to :obj:`bbox_a`,\n            whose shape is :math:`(K, 4)`.\n            The dtype should be :obj:`numpy.float32`.\n\n    Returns:\n        array:\n        An array whose shape is :math:`(N, K)`. \\\n        An element at index :math:`(n, k)` contains IoUs between \\\n        :math:`n` th bounding box in :obj:`bbox_a` and :math:`k` th bounding \\\n        box in :obj:`bbox_b`.\n\n    \"\"\"\n    if bbox_a.shape[1] != 4 or bbox_b.shape[1] != 4:\n        raise IndexError\n\n    # top left\n    tl = xp.maximum(bbox_a[:, None, :2], bbox_b[:, :2])\n    # bottom right\n    br = xp.minimum(bbox_a[:, None, 2:], bbox_b[:, 2:])\n\n    area_i = xp.prod(br - tl, axis=2) * (tl < br).all(axis=2)\n    area_a = xp.prod(bbox_a[:, 2:] - bbox_a[:, :2], axis=1)\n    area_b = xp.prod(bbox_b[:, 2:] - bbox_b[:, :2], axis=1)\n    return area_i / (area_a[:, None] + area_b - area_i)\n\n\ndef __test():\n    pass\n\n\nif __name__ == '__main__':\n    __test()\n\n#生成Anocher 论文中介绍的很清楚了，要在feature map每个点生成9种不同size和长宽比的box\n#这里只是生成最基本的Anchorbase 还没有在feature map上滑动\ndef generate_anchor_base(base_size=16, ratios=[0.5, 1, 2],\n                         anchor_scales=[8, 16, 32]):\n    \"\"\"Generate anchor base windows by enumerating aspect ratio and scales.\n\n    Generate anchors that are scaled and modified to the given aspect ratios.\n    Area of a scaled anchor is preserved when modifying to the given aspect\n    ratio.\n\n    :obj:`R = len(ratios) * len(anchor_scales)` anchors are generated by this\n    function.\n    The :obj:`i * len(anchor_scales) + j` th anchor corresponds to an anchor\n    generated by :obj:`ratios[i]` and :obj:`anchor_scales[j]`.\n\n    For example, if the scale is :math:`8` and the ratio is :math:`0.25`,\n    the width and the height of the base window will be stretched by :math:`8`.\n    For modifying the anchor to the given aspect ratio,\n    the height is halved and the width is doubled.\n\n    Args:\n        base_size (number): The width and the height of the reference window.\n        ratios (list of floats): This is ratios of width to height of\n            the anchors.\n        anchor_scales (list of numbers): This is areas of anchors.\n            Those areas will be the product of the square of an element in\n            :obj:`anchor_scales` and the original area of the reference\n            window.\n\n    Returns:\n        ~numpy.ndarray:\n        An array of shape :math:`(R, 4)`.\n        Each element is a set of coordinates of a bounding box.\n        The second axis corresponds to\n        :math:`(y_{min}, x_{min}, y_{max}, x_{max})` of a bounding box.\n\n    \"\"\"\n    py = base_size / 2. #y中点\n    px = base_size / 2. #x中点\n\n    anchor_base = np.zeros((len(ratios) * len(anchor_scales), 4),#/shape=(3*3,4)\n                           dtype=np.float32)\n    \n    \n    # np.zeros这样初始的坐标都是(0,0,0,0)，其实这个函数一开始就只是以特征图的左上角为基准产生的9个anchor,\n    #根本没有对全图的所有anchor的产生做任何的解释！那所有的anchor是在哪里产生的呢？答案是在 model / region_proposal_network里！！\n    \n    for i in six.moves.range(len(ratios)): #9个box(ymax,xmax,ymin,xmin) 共36个参数\n        for j in six.moves.range(len(anchor_scales)):\n            h = base_size * anchor_scales[j] * np.sqrt(ratios[i])\n            w = base_size * anchor_scales[j] * np.sqrt(1. / ratios[i])\n\n            index = i * len(anchor_scales) + j\n            anchor_base[index, 0] = py - h / 2.\n            anchor_base[index, 1] = px - w / 2.\n            anchor_base[index, 2] = py + h / 2.\n            anchor_base[index, 3] = px + w / 2.\n    return anchor_base\n", "meta": {"hexsha": "86937bbbfb577d998b1394776c2ef5d5d0733b76", "size": 9917, "ext": "py", "lang": "Python", "max_stars_repo_path": "model/utils/bbox_tools.py", "max_stars_repo_name": "wen0618/simple-faster-rcnn-pytorch", "max_stars_repo_head_hexsha": "b5c41eeaf9f0641f65bdd6fe0d7f1301bd1cabf3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "model/utils/bbox_tools.py", "max_issues_repo_name": "wen0618/simple-faster-rcnn-pytorch", "max_issues_repo_head_hexsha": "b5c41eeaf9f0641f65bdd6fe0d7f1301bd1cabf3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model/utils/bbox_tools.py", "max_forks_repo_name": "wen0618/simple-faster-rcnn-pytorch", "max_forks_repo_head_hexsha": "b5c41eeaf9f0641f65bdd6fe0d7f1301bd1cabf3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1423076923, "max_line_length": 98, "alphanum_fraction": 0.6249873954, "include": true, "reason": "import numpy", "num_tokens": 3410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.17827366077449475}}
{"text": "\"\"\"Main driver of the fitting routine.\"\"\"\nimport pickle\nimport random\nimport time\nimport warnings\nfrom multiprocessing import Pool, Process\nfrom tqdm import tqdm\n\nimport extinction\nimport astropy.units as u\nimport pandas as pd\nimport numpy as np\nimport scipy.stats as st\nfrom numpy.random import choice\nfrom astropy.constants import sigma_sb\nfrom isochrones.interp import DFInterpolator\nfrom termcolor import colored\n\nfrom .config import filesdir, gridsdir, priorsdir\nfrom .error import *\nfrom .isochrone import estimate\nfrom .phot_utils import *\nfrom .sed_library import *\nfrom .utils import *\n\ntry:\n    import dynesty\n    from dynesty.utils import resample_equal\n\n    bma_flag = True\nexcept ModuleNotFoundError:\n    wrn = 'Dynesty package not found.\\n'\n    wrn += 'Install dynesty with `pip install dynesty`'\n    warnings.warn(wrn)\n    bma_flag = False\ntry:\n    import pymultinest\nexcept ModuleNotFoundError:\n    warnings.warn(\n        '(py)MultiNest installation (or libmultinest.dylib) not detected.'\n    )\n\n\nclass Fitter:\n    \"\"\"The Fitter class handles the fitting routines and parameter estimation.\n\n    Examples\n    --------\n    The fitter isn't instantiaded with any arguments, rather you instantiate a\n    Fitter object, then you set up the configurations and finally you\n    initialize the object by running the initialize method.\n    >>> f = Fitter()\n    >>> f.star = s  # s must be a valid Star object.\n    >>> f.initialize()\n\n    Attributes\n    ----------\n    out_folder : type\n        Description of attribute `out_folder`.\n    verbose : type\n        Description of attribute `verbose`.\n    star : type\n        Description of attribute `star`.\n    setup : type\n        Description of attribute `setup`.\n    norm : type\n        Description of attribute `norm`.\n    grid : type\n        Description of attribute `grid`.\n    estimate_logg : type\n        Description of attribute `estimate_logg`.\n    priorfile : type\n        Description of attribute `priorfile`.\n    av_law : type\n        Description of attribute `av_law`.\n    n_samples : type\n        Description of attribute `n_samples`.\n    bma : type\n        Description of attribute `bma`.\n    prior_setup : type\n        Description of attribute `prior_setup`.\n    sequential : type\n        Description of attribute `sequential`.\n\n    \"\"\"\n\n    colors = [\n        'red', 'green', 'blue', 'yellow',\n        'grey', 'magenta', 'cyan', 'white'\n    ]\n\n    def __init__(self):\n\n        # Default values for attributes\n        self._interpolators = []\n        self._grids = []\n        self.out_folder = None\n        self.verbose = True\n        self.star = None\n        self.setup = ['dynesty']\n        self.norm = False\n        self.grid = 'phoenix'\n        self.estimate_logg = False\n        self.av_law = 'fitzpatrick'\n        self.n_samples = None\n        self.bma = False\n        self.prior_setup = None\n        self.sequential = True\n        self.experimental = False\n\n    @property\n    def star(self):\n        \"\"\"Star to fit for.\"\"\"\n        return self._star\n\n    @star.setter\n    def star(self, star):\n        # if not isinstance(star, Star) and star is not None:\n        #     InstanceError(star, Star).__raise__()\n        self._star = star\n\n    @property\n    def setup(self):\n        \"\"\"Set up options.\"\"\"\n        return self._setup\n\n    @setup.setter\n    def setup(self, setup):\n        err_msg = 'The setup has to contain at least the fitting engine'\n        err_msg += f', multinest or dynesty.\\nThe setup was {setup}'\n        if len(setup) < 1:\n            InputError(err_msg).__raise__()\n        self._setup = setup\n        self._engine = setup[0]\n        defaults = False\n        if len(setup) == 1:\n            defaults = True\n        if self._engine == 'multinest':\n            if defaults:\n                self._nlive = 500\n                self._dlogz = 0.5\n            else:\n                self._nlive = setup[1]\n                self._dlogz = setup[2]\n        if self._engine == 'dynesty':\n            if defaults:\n                self._nlive = 500\n                self._dlogz = 0.5\n                self._bound = 'multi'\n                self._sample = 'rwalk'\n                self._threads = 1\n                self._dynamic = False\n            else:\n                self._nlive = setup[1]\n                self._dlogz = setup[2]\n                self._bound = setup[3]\n                self._sample = setup[4]\n                self._threads = setup[5]\n                self._dynamic = setup[6]\n\n    @property\n    def norm(self):\n        \"\"\"Bool to decide if a normalization constant will be fitted.\n\n        Set as True to not fit for radius and distance and fit for a\n        normalization constant. After the fit a radius is calculated using\n        the Gaia parallax.\n        \"\"\"\n        return self._norm\n\n    @norm.setter\n    def norm(self, norm):\n        if type(norm) is not bool:\n            InputError('norm must be True or False.').__raise__()\n        self._norm = norm\n\n    @property\n    def grid(self):\n        \"\"\"Model grid selected.\"\"\"\n        return self._grid\n\n    @grid.setter\n    def grid(self, grid):\n        assert type(grid) == str\n        self._grid = grid\n        if grid.lower() == 'phoenix':\n            with open(gridsdir + '/Phoenixv2_DF.pkl', 'rb') as intp:\n                self._interpolator = DFInterpolator(pd.read_pickle(intp))\n        if grid.lower() == 'btsettl':\n            with open(gridsdir + '/BTSettl_DF.pkl', 'rb') as intp:\n                self._interpolator = DFInterpolator(pd.read_pickle(intp))\n        if grid.lower() == 'btnextgen':\n            with open(gridsdir + '/BTNextGen_DF.pkl', 'rb') as intp:\n                self._interpolator = DFInterpolator(pd.read_pickle(intp))\n        if grid.lower() == 'btcond':\n            with open(gridsdir + '/BTCond_DF.pkl', 'rb') as intp:\n                self._interpolator = DFInterpolator(pd.read_pickle(intp))\n        if grid.lower() == 'ck04':\n            with open(gridsdir + '/CK04_DF.pkl', 'rb') as intp:\n                self._interpolator = DFInterpolator(pd.read_pickle(intp))\n        if grid.lower() == 'kurucz':\n            with open(gridsdir + '/Kurucz_DF.pkl', 'rb') as intp:\n                self._interpolator = DFInterpolator(pd.read_pickle(intp))\n        if grid.lower() == 'coelho':\n            with open(gridsdir + '/Coelho_DF.pkl', 'rb') as intp:\n                self._interpolator = DFInterpolator(pd.read_pickle(intp))\n\n    @property\n    def bma(self):\n        \"\"\"Bayesian Model Averaging (BMA).\n\n        Set to True if BMA is wanted. This loads every model grid interpolator\n        and fits an SED to all of them, so the runtime will be slower!\n        \"\"\"\n        return self._bma\n\n    @bma.setter\n    def bma(self, bma):\n        self._bma = bma if bma_flag else False\n\n    @property\n    def models(self):\n        \"\"\"Models to be used in BMA.\"\"\"\n        return self._bma_models\n\n    @models.setter\n    def models(self, mods):\n        self._bma_models = mods\n\n    @property\n    def sequential(self):\n        \"\"\"Set to True to make BMA sequentially instead of parallel.\"\"\"\n        return self._sequential\n\n    @sequential.setter\n    def sequential(self, sequential):\n        self._sequential = sequential\n\n    @property\n    def n_samples(self):\n        \"\"\"Set number of samples for BMA.\"\"\"\n        return self._nsamp\n\n    @n_samples.setter\n    def n_samples(self, nsamp):\n        self._nsamp = nsamp\n\n    @property\n    def verbose(self):\n        \"\"\"Program verbosity. Default is True.\"\"\"\n        return self._verbose\n\n    @verbose.setter\n    def verbose(self, verbose):\n        if type(verbose) is not bool:\n            InputError('Verbose must be True or False.').__raise__()\n        self._verbose = verbose\n\n    @property\n    def out_folder(self):\n        \"\"\"Output folder.\n\n        If none is provided the default will be the starname.\n        \"\"\"\n        return self._out_folder\n\n    @out_folder.setter\n    def out_folder(self, out_folder):\n        if type(out_folder) is not str and out_folder is not None:\n            err_msg = 'Output folder must be an address or None.'\n            InputError(err_msg).__raise__()\n        self._out_folder = out_folder\n\n    @property\n    def av_law(self):\n        \"\"\"Select extinction law.\"\"\"\n        return self._av_law\n\n    @av_law.setter\n    def av_law(self, law):\n        laws = [\n            'cardelli',\n            'odonnell',\n            'calzetti',\n            'fitzpatrick'\n        ]\n        law = law.lower()\n        if law not in laws:\n            err_msg = f'Extinction law {law} not recognized. Available extinction'\n            err_msg += ' laws are: `cardelli`, `odonnell`'\n            err_msg += ', `calzetti`, and `fitzpatrick`'\n            InputError(err_msg).__raise__()\n        law_f = None\n        if law == laws[0]:\n            law_f = extinction.ccm89\n        if law == laws[1]:\n            law_f = extinction.odonnell94\n        if law == laws[2]:\n            law_f = extinction.calzetti00\n        if law == laws[3]:\n            law_f = extinction.fitzpatrick99\n        self._av_law = law_f\n\n    def initialize(self):\n        \"\"\"Initialize the fitter.\n\n        To be run only after every input is added.\n        This function calculates the number of dimensions, runs the prior\n        creation, creates output directory, initializes coordinators and sets\n        up global variables.\n        \"\"\"\n        global prior_dict, coordinator, fixed, order, star, use_norm, av_law\n        self.start = time.time()\n        err_msg = 'No star is detected. Please create an instance of Star.'\n        if self.star is None:\n            er = InputError(err_msg)\n            er.log(self.out + '/output.log')\n            er.__raise__()\n        star = self.star\n        if not self._bma:\n            global interpolator\n            interpolator = self._interpolator\n        use_norm = self.norm\n        # Extinction law\n        av_law = self._av_law\n\n        # Declare order of parameters.\n        if not self.norm:\n            order = np.array(\n                [\n                    'teff', 'logg', 'z',\n                    'dist', 'rad', 'Av'\n                ]\n            )\n        else:\n            order = np.array(['teff', 'logg', 'z', 'norm', 'Av'])\n\n        # Create output directory\n        if self.out_folder is None:\n            self.out_folder = self.star.starname + '/'\n        create_dir(self.out_folder)\n\n        self.star.save_mags(self.out_folder + '/')\n\n        # Parameter coordination.\n        # Order for the parameters are:\n        # teff, logg, z, dist, rad, Av, noise\n        # or\n        # teff, logg, z, norm, Av, noise\n        npars = 6 if not self.norm else 5\n        npars += self.star.used_filters.sum()\n        npars = int(npars)\n        self.coordinator = np.zeros(npars)  # 1 for fixed params\n        self.fixed = np.zeros(npars)\n        coordinator = self.coordinator\n        fixed = self.fixed\n\n        # Setup priors.\n        self.default_priors = self._default_priors()\n        self.create_priors_from_setup()\n        prior_dict = self.priors\n\n        # Get dimensions.\n        self.ndim = self.get_ndim()\n\n        # warnings\n        if len(self._setup) == 1:\n            print('USING DEFAULT SETUP VALUES.')\n\n        # BMA settings\n        # if BMA is used, load all interpolators requested.\n        if self._bma:\n            if self.n_samples is None:\n                self.n_samples = 'max'\n\n            if self.star.offline:\n                if self.star.temp is None:\n                    self.star.temp = 4001\n                off_msg = 'Offline mode assumes that the stellar'\n                off_msg += ' temperature is greater than 4000 K'\n                off_msg += '. If you believe this is not the case then please '\n                off_msg += 'add a temperature to the Star constructor. '\n                off_msg += f'The input temperature is {self.star.temp}'\n                print(colored(off_msg, 'yellow'))\n\n            for mod in self._bma_models:\n                # We'll assume that if ARIADNE is running in offline mode\n                # Then the star will have > 4000 K\n                if mod.lower() == 'phoenix':\n                    with open(gridsdir + '/Phoenixv2_DF.pkl', 'rb') as intp:\n                        df = DFInterpolator(pd.read_pickle(intp))\n                if mod.lower() == 'btsettl':\n                    with open(gridsdir + '/BTSettl_DF.pkl', 'rb') as intp:\n                        df = DFInterpolator(pd.read_pickle(intp))\n                if mod.lower() == 'btnextgen':\n                    if self.star.temp > 4000:\n                        continue\n                    else:\n                        with open(gridsdir + '/BTNextGen_DF.pkl', 'rb') as inp:\n                            df = DFInterpolator(pd.read_pickle(inp))\n                if mod.lower() == 'btcond':\n                    if self.star.temp > 4000:\n                        continue\n                    else:\n                        with open(gridsdir + '/BTCond_DF.pkl', 'rb') as intp:\n                            df = DFInterpolator(pd.read_pickle(intp))\n                if mod.lower() == 'ck04':\n                    if self.star.temp > 4000:\n                        with open(gridsdir + '/CK04_DF.pkl', 'rb') as intp:\n                            df = DFInterpolator(pd.read_pickle(intp))\n                    else:\n                        # Warning temp too low for model\n                        continue\n                if mod.lower() == 'kurucz':\n                    if self.star.temp > 4000:\n                        with open(gridsdir + '/Kurucz_DF.pkl', 'rb') as intp:\n                            df = DFInterpolator(pd.read_pickle(intp))\n                    else:\n                        # Warning temp too low for model.\n                        continue\n                # if mod.lower() == 'coelho':\n                #     if self.star.temp > 3500:\n                #         with open(gridsdir + '/Coelho_DF.pkl', 'rb') as intp:\n                #             df = DFInterpolator(pd.read_pickle(intp))\n                #     else:\n                #         # Warning\n                #         continue\n                self._interpolators.append(df)\n                self._grids.append(mod)\n            thr = self._threads if self._sequential else len(\n                self._interpolators)\n        else:\n            thr = self._threads\n        en = 'Bayesian Model Averaging' if self._bma else self._engine\n        display_routine(en, self._nlive, self._dlogz, self.ndim, self._bound,\n                        self._sample, thr, self._dynamic)\n\n    def get_ndim(self):\n        \"\"\"Calculate number of dimensions.\"\"\"\n        ndim = 6 if not self.norm else 5\n        ndim += self.star.used_filters.sum()\n        ndim -= self.coordinator.sum()\n        return int(ndim)\n\n    def _default_priors(self):\n        global order\n        defaults = dict()\n        # Logg prior setup.\n        if self.star.get_logg:\n            defaults['logg'] = st.norm(\n                loc=self.star.logg, scale=self.star.logg_e)\n        else:\n            with open(priorsdir + '/logg_ppf.pkl', 'rb') as jar:\n                defaults['logg'] = pickle.load(jar)\n        # Teff prior from RAVE\n        with open(priorsdir + '/teff_ppf.pkl', 'rb') as jar:\n            defaults['teff'] = pickle.load(jar)\n        # [Fe/H] prior setup.\n        defaults['z'] = st.norm(loc=-0.125, scale=0.234)\n        # Distance prior setup.\n        if not self._norm:\n            if self.star.dist != -1:\n                defaults['dist'] = st.norm(\n                    loc=self.star.dist, scale=5 * self.star.dist_e)\n            else:\n                defaults['dist'] = st.uniform(loc=1, scale=3000)\n            # Radius prior setup.\n            defaults['rad'] = st.uniform(loc=0.05, scale=100)\n        # Normalization prior setup.\n        else:\n            up = 1 / 1e-20\n            defaults['norm'] = st.truncnorm(a=0, b=up, loc=0, scale=1e-15)\n        # Extinction prior setup.\n        if self.star.Av == 0.:\n            av_idx = 4 if self._norm else 5\n            self.coordinator[av_idx] = 1\n            self.fixed[av_idx] = 0\n            defaults['Av'] = None\n        else:\n            defaults['Av'] = st.uniform(loc=0, scale=self.star.Av)\n        # Noise model prior setup.\n        mask = self.star.filter_mask\n        flxs = self.star.flux[mask]\n        errs = self.star.flux_er[mask]\n        for filt, flx, flx_e in zip(self.star.filter_names[mask], flxs, errs):\n            p_ = get_noise_name(filt) + '_noise'\n            mu = 0\n            sigma = flx_e * 10\n            b = (1 - flx) / flx_e\n            defaults[p_] = st.truncnorm(loc=mu, scale=sigma, a=0, b=b)\n            # defaults[p_] = st.uniform(loc=0, scale=5)\n            order = np.append(order, p_)\n        return defaults\n\n    def create_priors_from_setup(self):\n        \"\"\"Create priors from the manual setup.\"\"\"\n        prior_dict = dict()\n        keys = self.prior_setup.keys()\n        noise = []\n        mask = self.star.filter_mask\n        flxs = self.star.flux[mask]\n        errs = self.star.flux_er[mask]\n        for filt, flx, flx_e in zip(self.star.filter_names[mask], flxs, errs):\n            p_ = get_noise_name(filt) + '_noise'\n            noise.append(p_)\n        prior_out = 'Parameter\\tPrior\\tValues\\n'\n        if 'norm' in keys and ('rad' in keys or 'dist' in keys):\n            er = PriorError('rad or dist', 1)\n            er.log(self.out_folder + '/output.log')\n            er.__raise__()\n        for k in keys:\n            if type(self.prior_setup[k]) == str:\n                if self.prior_setup[k] == 'default':\n                    prior_dict[k] = self.default_priors[k]\n                    prior_out += k + '\\tdefault\\n'\n                if self.prior_setup[k].lower() == 'rave':\n                    # RAVE prior only available for teff and logg. It's already\n                    # the default for [Fe/H]\n                    if k == 'logg' or k == 'teff':\n                        if k == 'teff':\n                            PriorError('teff', 2).warn()\n                        with open(priorsdir + '/teff_ppf.pkl', 'rb') as jar:\n                            prior_dict[k] = pickle.load(jar)\n                        prior_out += k + '\\tRAVE\\n'\n\n            else:\n                prior = self.prior_setup[k][0]\n                if prior == 'fixed':\n                    value = self.prior_setup[k][1]\n                    idx = np.where(k == order)[0]\n                    self.coordinator[idx] = 1\n                    self.fixed[idx] = value\n                    prior_out += k + '\\tfixed\\t{}\\n'.format(value)\n                if prior == 'normal':\n                    mu = self.prior_setup[k][1]\n                    sig = self.prior_setup[k][2]\n                    prior_dict[k] = st.norm(loc=mu, scale=sig)\n                    prior_out += k + '\\tnormal\\t{}\\t{}\\n'.format(mu, sig)\n                if prior == 'truncnorm':\n                    mu = self.prior_setup[k][1]\n                    sig = self.prior_setup[k][2]\n                    low = self.prior_setup[k][3]\n                    up = self.prior_setup[k][4]\n                    b, a = (up - mu) / sig, (low - mu) / sig\n                    prior_dict[k] = st.truncnorm(a=a, b=b, loc=mu, scale=sig)\n                    prior_out += k\n                    prior_out += '\\ttruncatednormal\\t{}\\t{}\\t{}\\t{}\\n'.format(\n                        mu, sig, low, up)\n                if prior == 'uniform':\n                    low = self.prior_setup[k][1]\n                    up = self.prior_setup[k][2]\n                    prior_dict[k] = st.uniform(loc=low, scale=up - low)\n                    prior_out += k + '\\tuniform\\t{}\\t{}\\n'.format(low, up)\n        for par in noise:\n            prior_dict[par] = self.default_priors[par]\n        ff = open(self.out_folder + '/prior.dat', 'w')\n        ff.write(prior_out)\n        ff.close()\n        del ff\n        self.priors = prior_dict\n        pass\n\n    def fit(self):\n        \"\"\"Run fitting routine.\"\"\"\n        if self._engine == 'multinest':\n            self.fit_multinest()\n        else:\n            self.fit_dynesty()\n        elapsed_time = execution_time(self.start)\n        end(self.coordinator, elapsed_time,\n            self.out_folder, self._engine, self.norm, )\n        pass\n\n    def fit_bma(self):\n        \"\"\"Perform the fit with different models and the average the output.\n\n        Only works with dynesty.\n        \"\"\"\n        if len(self.star.filter_names[self.star.filter_mask]) <= 5:\n            print(colored('\\t\\t\\tNOT ENOUGH POINTS TO MAKE THE FIT! !', 'red'))\n            return\n        thr = self._threads if self._sequential else len(self._interpolators)\n        # display('Bayesian Model Averaging', self.star, self._nlive,\n        #         self._dlogz, self.ndim, self._bound, self._sample,\n        #         thr, self._dynamic)\n        if not self._sequential:\n            jobs = []\n            n_threads = len(self._interpolators)\n            for intp, gr in zip(self._interpolators, self._grids):\n                p = Process(target=self._bma_dynesty, args=([intp, gr]))\n                jobs.append(p)\n                p.start()\n            for p in jobs:\n                p.join()\n        else:\n            global interpolator\n            for intp, gr in zip(self._interpolators, self._grids):\n                interpolator = intp\n                self.grid = gr\n                out_file = self.out_folder + '/' + gr + '_out.pkl'\n                print('\\t\\t\\tFITTING MODEL : ' + gr)\n                try:\n                    self.fit_dynesty(out_file=out_file)\n                except ValueError as e:\n                    dump_out = self.out_folder + '/' + gr + '_DUMP.pkl'\n                    pickle.dump(self.sampler.results, open(dump_out, 'wb'))\n                    DynestyError(dump_out, gr, e).__raise__()\n                    continue\n\n        # Now that the fitting finished, read the outputs and average\n        # the posteriors\n        outs = []\n        for g in self._grids:\n            in_folder = f'{self.out_folder}/{g}_out.pkl'\n            outs.append(in_folder)\n            # with open(in_folder, 'rb') as out:\n            #     outs.append(pickle.load(out))\n        c = np.random.choice(self.colors)\n        avgd = self.bayesian_model_average(outs, self._grids, self._norm,\n                                           self.n_samples, c)\n        self.save_bma(avgd)\n\n        elapsed_time = execution_time(self.start)\n        end(self.coordinator, elapsed_time, self.out_folder,\n            'Bayesian Model Averaging', self.norm)\n        pass\n\n    def _bma_dynesty(self, intp, grid):\n        global interpolator\n        interpolator = intp\n\n        # Parallel parallelized routine experiment\n        if self.experimental:\n            if self._dynamic:\n                with Pool(self._threads) as executor:\n                    sampler = dynesty.DynamicNestedSampler(\n                        dynesty_loglike_bma, pt_dynesty, self.ndim,\n                        bound=self._bound, sample=self._sample, pool=executor,\n                        queue_size=self._threads, logl_args=([intp])\n                    )\n                    sampler.run_nested(dlogz_init=self._dlogz,\n                                       nlive_batch=self._nlive,\n                                       wt_kwargs={'pfrac': .95})\n            else:\n                with Pool(self._threads) as executor:\n                    sampler = dynesty.NestedSampler(\n                        dynesty_loglike_bma, pt_dynesty, self.ndim,\n                        nlive=self._nlive, bound=self._bound,\n                        sample=self._sample, pool=executor,\n                        queue_size=self._threads, logl_args=([intp])\n                    )\n                    sampler.run_nested(dlogz=self._dlogz)\n\n        elif self._dynamic:\n            sampler = dynesty.DynamicNestedSampler(\n                dynesty_loglike_bma, pt_dynesty, self.ndim,\n                bound=self._bound, sample=self._sample, logl_args=([intp])\n\n            )\n            sampler.run_nested(dlogz_init=self._dlogz,\n                               nlive_init=self._nlive,\n                               wt_kwargs={'pfrac': .95})\n        else:\n            try:\n                self.sampler = dynesty.NestedSampler(\n                    dynesty_loglike_bma, pt_dynesty, self.ndim,\n                    nlive=self._nlive, bound=self._bound,\n                    sample=self._sample,\n                    logl_args=([intp])\n                )\n                self.sampler.run_nested(dlogz=self._dlogz)\n            except Error:\n                dump_out = self.out_folder + '/' + grid + '_DUMP.pkl'\n                pickle.dump(self.sampler.results, open(dump_out, 'wb'))\n                er = DynestyError(dump_out, grid)\n                er.log(self.out + '/output.log')\n                er.__raise__()\n\n        results = self.sampler.results\n        out_file = self.out_folder + '/' + grid + '_out.pkl'\n        self.save(out_file, results=results)\n        pass\n\n    def fit_multinest(self, out_file=None):\n        \"\"\"Run MultiNest.\"\"\"\n        # Set up some globals\n        global mask, flux, flux_er, filts, wave\n        mask = star.filter_mask\n        flux = star.flux[mask]\n        flux_er = star.flux_er[mask]\n        filts = star.filter_names[mask]\n        wave = star.wave[mask]\n        path = self.out_folder + '/mnest/'\n        create_dir(path)  # Create multinest path.\n        pymultinest.run(\n            multinest_log_like, pt_multinest, self.ndim,\n            n_params=self.ndim,\n            sampling_efficiency=0.8,\n            evidence_tolerance=self._dlogz,\n            n_live_points=self._nlive,\n            outputfiles_basename=path + 'chains',\n            max_modes=100,\n            verbose=self.verbose,\n            resume=False\n        )\n        if out_file is None:\n            out_file = f'{self.out_folder}/{self._grid}_out.pkl'\n        self.save(out_file=out_file)\n        pass\n\n    def fit_dynesty(self, out_file=None):\n        \"\"\"Run dynesty.\"\"\"\n        # Set up some globals\n        global mask, flux, flux_er, filts, wave\n        mask = star.filter_mask\n        flux = star.flux[mask]\n        flux_er = star.flux_er[mask]\n        filts = star.filter_names[mask]\n        wave = star.wave[mask]\n        if self._dynamic:\n            if self._threads > 1:\n                with Pool(self._threads) as executor:\n                    self.sampler = dynesty.DynamicNestedSampler(\n                        dynesty_log_like, pt_dynesty, self.ndim,\n                        bound=self._bound, sample=self._sample,\n                        pool=executor, walks=25,\n                        queue_size=self._threads - 1\n                    )\n                    self.sampler.run_nested(dlogz_init=self._dlogz,\n                                            nlive_init=self._nlive,\n                                            wt_kwargs={'pfrac': 1})\n            else:\n                self.sampler = dynesty.DynamicNestedSampler(\n                    dynesty_log_like, pt_dynesty, self.ndim, walks=25,\n                    bound=self._bound, sample=self._sample\n\n                )\n                self.sampler.run_nested(dlogz_init=self._dlogz,\n                                        nlive_init=self._nlive,\n                                        wt_kwargs={'pfrac': 1})\n        else:\n            if self._threads > 1:\n                with Pool(self._threads) as executor:\n                    self.sampler = dynesty.NestedSampler(\n                        dynesty_log_like, pt_dynesty, self.ndim,\n                        nlive=self._nlive, bound=self._bound,\n                        sample=self._sample,\n                        pool=executor, walks=25,\n                        queue_size=self._threads - 1,\n                    )\n                    self.sampler.run_nested(dlogz=self._dlogz)\n            else:\n                self.sampler = dynesty.NestedSampler(\n                    dynesty_log_like, pt_dynesty, self.ndim, walks=25,\n                    nlive=self._nlive, bound=self._bound,\n                    sample=self._sample\n                )\n                self.sampler.run_nested(dlogz=self._dlogz)\n        results = self.sampler.results\n        if out_file is None:\n            out_file = f'{self.out_folder}/{self._grid}_out.pkl'\n        self.save(out_file, results=results)\n        pass\n\n    def save(self, out_file, results=None):\n        \"\"\"Save multinest/dynesty output and relevant information.\n\n        Saves a dictionary as a pickle file. The dictionary contains the\n        following:\n\n        lnZ : The global evidence.\n        lnZerr : The global evidence error.\n        posterior_samples : A dictionary containing the samples of each\n                            parameter (even if it's fixed), the evidence,\n                            log likelihood, the prior, and the posterior\n                            for each set of sampled parameters.\n        fixed : An array with the fixed parameter values.\n        coordinator : An array with the status of each parameter (1 for fixed\n                      0 for free)\n        best_fit : The best fit is chosen to be the median of each sample.\n                   It also includes the log likelihood of the best fit.\n        star : The Star object containing the information of the star (name,\n               magnitudes, fluxes, coordinates, etc)\n        engine : The fitting engine used (i.e. MultiNest or Dynesty)\n\n        Also creates a log file with the best fit parameters and 1 sigma\n        error bars.\n\n        \"\"\"\n        out = dict()\n        logdat = '#Parameter\\tmedian\\tupper\\tlower\\t3sig_CI\\n'\n        log_out = self.out_folder + '/' + 'best_fit.dat'\n        if self._engine == 'multinest':\n            lnz, lnzer, posterior_samples = self.multinest_results(\n                self.out_folder,\n                self.ndim\n            )\n        else:\n            lnz, lnzer, posterior_samples = self.dynesty_results(results)\n\n        n = int(self.star.used_filters.sum())\n        mask = self.star.filter_mask\n\n        # Save global evidence\n\n        if self._engine == 'dynesty':\n            out['dynesty'] = results\n        out['global_lnZ'] = lnz\n        out['global_lnZerr'] = lnzer\n\n        # Create raw samples holder\n\n        out['posterior_samples'] = dict()\n        j = 0\n        k = 0  # filter counter\n        for i, param in enumerate(order):\n            if not self.coordinator[i]:\n                samples = posterior_samples[:, j]\n                if 'noise' in param:\n                    filt = self.star.filter_names[mask][k]\n                    flx = self.star.flux[mask][k]\n                    _, samples = flux_to_mag(flx, samples, filt)\n                    k += 1\n                out['posterior_samples'][param] = samples\n                j += 1\n            else:\n                out['posterior_samples'][param] = self.fixed[i]\n\n        # Save loglike, priors and posteriors.\n\n        out['posterior_samples']['loglike'] = np.zeros(\n            posterior_samples.shape[0]\n        )\n\n        # If normalization constant was fitted, create a distribution of radii\n        # only if there's a distance available.\n\n        if use_norm and star.dist != -1:\n            rad = self._get_rad(\n                out['posterior_samples']['norm'], star.dist, star.dist_e\n            )\n            out['posterior_samples']['rad'] = rad\n\n        # Create a distribution of masses.\n\n        logg_samp = out['posterior_samples']['logg']\n        rad_samp = out['posterior_samples']['rad']\n        mass_samp = self._get_mass(logg_samp, rad_samp)\n        out['posterior_samples']['grav_mass'] = mass_samp\n\n        # Create a distribution of luminosities.\n\n        teff_samp = out['posterior_samples']['teff']\n        lum_samp = self._get_lum(teff_samp, rad_samp)\n        out['posterior_samples']['lum'] = lum_samp\n\n        # Create a distribution of angular diameters.\n\n        if not use_norm:\n            dist_samp = out['posterior_samples']['dist']\n            ad_samp = self._get_angular_diameter(rad_samp, dist_samp)\n            out['posterior_samples']['AD'] = ad_samp\n\n        for i in range(posterior_samples.shape[0]):\n            theta = build_params(\n                posterior_samples[i, :], flux, flux_er, filts, coordinator,\n                fixed, self.norm)\n            out['posterior_samples']['loglike'][i] = log_likelihood(\n                theta, flux, flux_er, wave, filts, interpolator, self.norm,\n                av_law)\n        lnlike = out['posterior_samples']['loglike']\n\n        # Best fit\n        # The logic is as follows:\n        # Calculate KDE for each marginalized posterior distributions\n        # Find peak\n        # peak is best fit.\n        # do only if not bma\n\n        if not self.bma:\n            out['best_fit'] = dict()\n            out['uncertainties'] = dict()\n            out['confidence_interval'] = dict()\n            best_theta = np.zeros(order.shape[0])\n\n            for i, param in enumerate(order):\n                if not self.coordinator[i]:\n                    if 'noise' in param:\n                        continue\n                    samp = out['posterior_samples'][param]\n\n                    if param == 'z':\n                        logdat = out_filler(samp, logdat, param, '[Fe/H]', out)\n                    elif param == 'norm':\n                        logdat = out_filler(samp, logdat, param, '(R/D)^2',\n                                            out, fmt='e')\n                        if star.dist != 1:\n                            logdat = out_filler(\n                                out['posterior_samples']['rad'], logdat, 'rad',\n                                'R', out\n                            )\n                    else:\n                        logdat = out_filler(samp, logdat, param, param, out)\n                else:\n                    logdat = out_filler(\n                        0, logdat, param, out, fixed=self.fixed[i]\n                    )\n                best_theta[i] = out['best_fit'][param]\n\n            # Add derived mass to best fit dictionary.\n\n            samp = out['posterior_samples']['grav_mass']\n            logdat = out_filler(\n                samp, logdat, 'grav_mass', 'grav_mass', out\n            )\n\n            # Add derived luminosity to best fit dictionary.\n\n            samp = out['posterior_samples']['lum']\n            logdat = out_filler(samp, logdat, 'lum', 'lum', out)\n\n            # Add derived angular diameter to best fit dictionary.\n\n            if not use_norm:\n                samp = out['posterior_samples']['AD']\n                logdat = out_filler(samp, logdat, 'AD', 'AD', out)\n\n            for i, param in enumerate(order):\n                if not self.coordinator[i]:\n                    if 'noise' not in param:\n                        continue\n                    samp = out['posterior_samples'][param]\n                    logdat = out_filler(samp, logdat, param,\n                                        param, out, fmt='f')\n\n            # Fill in best loglike, prior and posterior.\n\n            out['best_fit']['loglike'] = log_likelihood(\n                best_theta, flux, flux_er, wave,\n                filts, interpolator, self.norm, av_law\n            )\n\n            # Spectral type\n            # Load Mamajek spt table\n            mamajek_spt = np.loadtxt(\n                filesdir + '/mamajek_spt.dat', dtype=str, usecols=[0])\n            mamajek_temp = np.loadtxt(\n                filesdir + '/mamajek_spt.dat', usecols=[1])\n\n            # Find spt\n            spt_idx = np.argmin(abs(mamajek_temp - out['best_fit']['teff']))\n            spt = mamajek_spt[spt_idx]\n            out['spectral_type'] = spt\n\n        # Utilities for plotting.\n\n        out['fixed'] = self.fixed\n        out['coordinator'] = self.coordinator\n        out['star'] = self.star\n        out['engine'] = self._engine\n        out['norm'] = self.norm\n        out['model_grid'] = self.grid\n        out['av_law'] = av_law\n        if not self.bma:\n            with open(log_out, 'w') as logfile:\n                logfile.write(logdat)\n        pickle.dump(out, open(out_file, 'wb'))\n        pass\n\n    def save_bma(self, avgd):\n        \"\"\"Save BMA output and relevant information.\n\n        Saves a dictionary as a pickle file. The dictionary contains the\n        following:\n\n        lnZ : The global evidences.\n        posterior_samples : A dictionary containing the samples of each\n                            parameter (even if it's fixed), the evidence,\n                            log likelihood, the prior, and the posterior\n                            for each set of sampled parameters.\n        fixed : An array with the fixed parameter values.\n        coordinator : An array with the status of each parameter (1 for fixed\n                      0 for free)\n        best_fit : The best fit is chosen to be the median of each sample.\n                   It also includes the log likelihood of the best fit.\n        star : The Star object containing the information of the star (name,\n               magnitudes, fluxes, coordinates, etc)\n\n        Also creates a log file with the best fit parameters, 1 sigma\n        error bars and 3 sigma CIs.\n\n        \"\"\"\n        out = dict()\n        logdat_samples = '#Parameter\\tmedian\\tupper\\tlower\\t3sig_low\\t3sig_up\\n'\n        logdat_average = '#Parameter\\tmedian\\tupper\\tlower\\t3sig_low\\t3sig_up\\n'\n        log_out_samples = f'{self.out_folder}/best_fit_sample.dat'\n        log_out_average = f'{self.out_folder}/best_fit_average.dat'\n        prob_out = f'{self.out_folder}/model_probabilities.dat'\n\n        # Save global evidence of each model.\n        out['lnZ'] = avgd['evidences']\n\n        # Save original samples.\n        out['originals'] = avgd['originals']\n\n        # Save weights.\n        out['weights'] = avgd['weights']\n\n        # Create raw samples holder\n        out['weighted_samples'] = dict()\n        out['weighted_average'] = dict()\n        j = 0\n        for i, par in enumerate(order):\n            if not self.coordinator[i]:\n                out['weighted_samples'][par] = avgd['weighted_samples'][par]\n                out['weighted_average'][par] = avgd['weighted_average'][par]\n                j += 1\n            else:\n                out['weighted_samples'][par] = self.fixed[i]\n                out['weighted_average'][par] = self.fixed[i]\n\n        # If normalization constant was fitted, create a distribution of radii.\n\n        if use_norm and star.dist != -1:\n            rad_sampled = self._get_rad(\n                out['weighted_samples']['norm'], star.dist, star.dist_e\n            )\n            rad_averageed = self._get_rad(\n                out['weighted_average']['norm'], star.dist, star.dist_e\n            )\n            out['weighted_samples']['rad'] = rad_sampled\n            out['weighted_average']['rad'] = rad_averageed\n\n        # Create a distribution of masses\n\n        logg_samp = out['weighted_samples']['logg']\n        logg_average = out['weighted_average']['logg']\n        rad_samp = out['weighted_samples']['rad']\n        rad_average = out['weighted_average']['rad']\n        mass_samp = self._get_mass(logg_samp, rad_samp)\n        mass_average = self._get_mass(logg_average, rad_average)\n        out['weighted_samples']['grav_mass'] = mass_samp\n        out['weighted_average']['grav_mass'] = mass_average\n\n        # Create a distribution of luminosities.\n\n        teff_samp = out['weighted_samples']['teff']\n        teff_average = out['weighted_average']['teff']\n        lum_samp = self._get_lum(teff_samp, rad_samp)\n        lum_average = self._get_lum(teff_average, rad_average)\n        out['weighted_samples']['lum'] = lum_samp\n        out['weighted_average']['lum'] = lum_average\n\n        # Create a distribution of angular diameters.\n\n        if not use_norm:\n            dist_samp = out['weighted_samples']['dist']\n            dist_average = out['weighted_average']['dist']\n            ad_samp = self._get_angular_diameter(rad_samp, dist_samp)\n            ad_average = self._get_angular_diameter(rad_average, dist_average)\n            out['weighted_samples']['AD'] = ad_samp\n            out['weighted_average']['AD'] = ad_average\n\n        # Best fit\n        # The logic is as follows:\n        # Calculate KDE for each marginalized posterior distributions\n        # Find peak\n        # peak is best fit.\n\n        out['best_fit_samples'] = dict()\n        out['uncertainties_samples'] = dict()\n        out['confidence_interval_samples'] = dict()\n        out['best_fit_averaged'] = dict()\n        out['uncertainties_averaged'] = dict()\n        out['confidence_interval_averaged'] = dict()\n        for i, param in enumerate(order):\n            if not self.coordinator[i]:\n                if 'noise' in param:\n                    continue\n                samp = out['weighted_samples'][param]\n                sampw = out['weighted_average'][param]\n\n                if param == 'z':\n                    logdat_samples = out_filler(samp, logdat_samples, param,\n                                                '[Fe/H]', out, method='samples')\n                    logdat_average = out_filler(sampw, logdat_average, param,\n                                                '[Fe/H]', out,\n                                                method='averaged')\n                elif param == 'norm':\n                    logdat_samples = out_filler(samp, logdat_samples, param,\n                                                '(R/D)^2', out, fmt='e',\n                                                method='samples')\n                    logdat_average = out_filler(sampw, logdat_average, param,\n                                                '(R/D)^2', out, fmt='e',\n                                                method='averaged')\n                    if star.dist != 1:\n                        logdat_samples = out_filler(\n                            out['weighted_samples']['rad'], logdat_samples,\n                            'rad', 'R', out, method='samples'\n                        )\n                        logdat_average = out_filler(\n                            out['weighted_average']['rad'], logdat_average,\n                            'rad', 'R', out, method='averaged'\n                        )\n\n                else:\n                    logdat_samples = out_filler(samp, logdat_samples, param,\n                                                param, out, method='samples')\n                    logdat_average = out_filler(sampw, logdat_average, param,\n                                                param, out, method='averaged')\n            else:\n                logdat_samples = out_filler(\n                    0, logdat_samples, param, param, out, fixed=self.fixed[i],\n                    method='samples'\n                )\n                logdat_average = out_filler(\n                    0, logdat_average, param, param, out, fixed=self.fixed[i],\n                    method='averaged'\n                )\n\n        # Add derived mass to best fit dictionary.\n\n        samp = out['weighted_samples']['grav_mass']\n        sampw = out['weighted_average']['grav_mass']\n        logdat_samples = out_filler(samp, logdat_samples, 'grav_mass',\n                                    'grav_mass', out, method='samples')\n        logdat_average = out_filler(sampw, logdat_average, 'grav_mass',\n                                    'grav_mass', out, method='averaged')\n\n        # Add derived luminosity to best fit dictionary.\n\n        samp = out['weighted_samples']['lum']\n        sampw = out['weighted_average']['lum']\n        logdat_samples = out_filler(samp, logdat_samples, 'lum', 'lum', out,\n                                    method='samples')\n        logdat_average = out_filler(sampw, logdat_average, 'lum', 'lum', out,\n                                    method='averaged')\n\n        # Add derived angular diameter to best fit dictionary.\n\n        if not use_norm:\n            samp = out['weighted_samples']['AD']\n            sampw = out['weighted_average']['AD']\n            logdat_samples = out_filler(samp, logdat_samples, 'AD', 'AD', out,\n                                        method='samples')\n            logdat_average = out_filler(sampw, logdat_average, 'AD', 'AD', out,\n                                        method='averaged')\n\n        # Add estimated age to best fit dictionary. This is done with the wider\n        # sampled distribution instead of the averaged one in order to save time\n\n        age_samp, mass_samp, eep_samp = self.estimate_age(\n            out['best_fit_samples'],\n            out['uncertainties_samples'],\n            c=choice(self.colors)\n        )\n        # Create new thingy for MIST samples. Sadly now everything done before\n        # this update will be incompatible :(\n        out['mist_samples'] = dict()\n        out['mist_samples']['age'] = age_samp\n        out['mist_samples']['iso_mass'] = mass_samp\n        out['mist_samples']['eep'] = eep_samp\n        logdat_samples = out_filler(age_samp, logdat_samples, 'age', 'age', out,\n                                    method='samples')\n        logdat_samples = out_filler(mass_samp, logdat_samples, 'iso_mass',\n                                    'iso_mass', out, method='samples')\n        logdat_samples = out_filler(eep_samp, logdat_samples, 'eep', 'eep', out,\n                                    method='samples')\n        # Ugly... but faster than doing the kde 2x times...\n        age = out['best_fit_samples']['age']\n        age_unc = out['uncertainties_samples']['age']\n        age_ci = out['confidence_interval_samples']['age']\n        iso_mass = out['best_fit_samples']['iso_mass']\n        iso_mass_unc = out['uncertainties_samples']['iso_mass']\n        iso_mass_ci = out['confidence_interval_samples']['iso_mass']\n        eep = out['best_fit_samples']['eep']\n        eep_unc = out['uncertainties_samples']['eep']\n        eep_ci = out['confidence_interval_samples']['eep']\n        out['best_fit_averaged']['age'] = age\n        out['best_fit_averaged']['iso_mass'] = iso_mass\n        out['best_fit_averaged']['eep'] = eep\n        out['uncertainties_averaged']['age'] = age_unc\n        out['uncertainties_averaged']['iso_mass'] = iso_mass_unc\n        out['uncertainties_averaged']['eep'] = eep_unc\n        out['confidence_interval_averaged']['age'] = age_ci\n        out['confidence_interval_averaged']['iso_mass'] = iso_mass_ci\n        out['confidence_interval_averaged']['eep'] = eep_ci\n        logdat_average += f'age\\t{age:.4f}\\t'\n        logdat_average += f'{age_unc[1]:.4f}\\t{age_unc[0]:.4f}\\t'\n        logdat_average += f'{age_ci[0]:.4f}\\t{age_ci[1]}\\n'\n        logdat_average += f'iso_mas\\t{iso_mass:.4f}\\t'\n        logdat_average += f'{iso_mass_unc[1]:.4f}\\t{iso_mass_unc[0]:.4f}\\t'\n        logdat_average += f'{iso_mass_ci[0]:.4f}\\t{iso_mass_ci[1]}\\n'\n        logdat_average += f'eep\\t{eep:.4f}\\t'\n        logdat_average += f'{eep_unc[1]:.4f}\\t{eep_unc[0]:.4f}\\t'\n        logdat_average += f'{eep_ci[0]:.4f}\\t{eep_ci[1]}\\n'\n        ###\n        probdat = ''\n\n        for k in avgd['weights'].keys():\n            probdat += f'{k}_probability\\t{avgd[\"weights\"][k]:.4f}\\n'\n\n        for i, param in enumerate(order):\n            if not self.coordinator[i]:\n                if 'noise' not in param:\n                    continue\n                samp = out['weighted_samples'][param]\n                sampw = out['weighted_average'][param]\n                logdat_samples = out_filler(samp, logdat_samples, param, param,\n                                            out, fmt='f', method='samples')\n                logdat_average = out_filler(sampw, logdat_average, param, param,\n                                            out, fmt='f', method='averaged')\n\n        out['fixed'] = self.fixed\n        out['coordinator'] = self.coordinator\n        out['star'] = self.star\n        out['norm'] = self.norm\n        out['engine'] = 'Bayesian Model Averaging'\n        out['av_law'] = av_law\n\n        # Spectral type\n\n        # Load Mamajek spt table\n        mamajek_spt, mamajek_temp = np.loadtxt(f'{filesdir}/mamajek_spt.dat',\n                                               dtype=str, usecols=[0, 1],\n                                               unpack=True)\n\n        mamajek_temp = mamajek_temp.astype(float)\n\n        # Find spt\n        spt_idx = np.argmin(\n            abs(mamajek_temp - out['best_fit_averaged']['teff']))\n        spt = mamajek_spt[spt_idx]\n        out['spectral_type'] = spt\n        out_file = f'{self.out_folder}/BMA.pkl'\n        with open(log_out_samples, 'w') as logfile:\n            logfile.write(logdat_samples)\n        with open(log_out_average, 'w') as logfile:\n            logfile.write(logdat_average)\n        with open(prob_out, 'w') as logfile:\n            logfile.write(probdat)\n        pickle.dump(out, open(out_file, 'wb'))\n        pass\n\n    @staticmethod\n    def bayesian_model_average(outputs, grids, norm, nsamples, c='white'):\n        \"\"\"Perform Bayesian Model Averaging.\n\n        Parameters\n        ----------\n        outputs: array_like\n            An array or list of output pickle files from the individual model\n            fits.\n        grids: array_like\n            An array or list of the model grids used to model.\n        norm: bool\n            Flag indicating if the normalization factor was fit for.\n        nsamples: int\n            The number of samples to sample from the averaged distribution.\n        c: str, optional\n            Termcolor color.\n\n        \"\"\"\n        evidences = []\n        post_samples = []\n        model_posteriors = []\n        # Read and extract model posterior information.\n        for o in outputs:\n            with open(o, 'rb') as f:\n                model_posteriors.append(pickle.load(f))\n        # Extract the evidences of each model.\n        for o in model_posteriors:\n            evidences.append(o['global_lnZ'])\n            post_samples.append(o['posterior_samples'])\n        # Convert evidences to weights/probabilities.\n        evidences = np.array(evidences)\n        weights = evidences - evidences.min()\n        weights = [np.exp(e) / np.exp(weights).sum() for e in weights]\n        weights = np.array(weights)\n        # We're not averaging these\n        ban = ['loglike', 'priors', 'posteriors']\n        if norm:  # if normalization was used, we won't average the radius\n            ban.append('rad')\n        # Create an output dictionary for the averaged samples.\n        out = dict()\n        out['originals'] = dict()\n        out['weights'] = dict()\n        # Populate the dict with the probabilities and individual model\n        # posteriors\n        for i, o in enumerate(model_posteriors):\n            out['weights'][o['model_grid']] = weights[i]\n            out['originals'][o['model_grid']] = o['posterior_samples']\n        out['weighted_samples'] = dict()\n        out['weighted_average'] = dict()\n\n        print(colored('\\t\\t*** AVERAGING POSTERIOR SAMPLES ***', c))\n        for k in tqdm(post_samples[0].keys()):\n            if k in ban:  # Skip things that are not main parameters.\n                continue\n            try:  # Skip fixed params.\n                len(post_samples[0][k])\n            except TypeError:\n                continue\n            traces = []\n            extended_weights = []\n            out['weighted_samples'][k] = np.zeros(nsamples)\n            out['weighted_average'][k] = np.zeros(nsamples)\n            for i, o in enumerate(post_samples):\n                # This is for the weighted sampling.\n                traces.append(o[k])\n                extended_weights.append(np.ones(len(o[k])) * weights[i])\n                # This is for the weighted averaging.\n                # The weighted averaging consists of taking the weighted\n                # average of the posterior samples, supersampled to maked them\n                # coincide in length.\n                weighted_samples = choice(o[k], nsamples) * weights[i]\n                out['weighted_average'][k] += weighted_samples\n            # Do the weighted sampling. For this we're going to estimate the\n            # KDE of the 'master' posterior built by taking random samples\n            # from each model where the number of samples is proportional\n            # to the model's relative probability. This is equivalent\n            # to taking the KDE of each model and then do the weighted average\n            avg_kde = gaussian_kde(np.concatenate(traces),\n                                   weights=np.concatenate(extended_weights))\n            out['weighted_samples'][k] = avg_kde.resample(nsamples)[0]\n        # Now we save the evidences.\n        out['evidences'] = dict()\n        for e, g in zip(evidences, grids):\n            out['evidences'][g] = e\n        return out\n\n    @staticmethod\n    def multinest_results(out_folder, ndim):\n        \"\"\"Extract posterior samples, global evidence and its error.\"\"\"\n        path = f'{out_folder}/mnest/chains'\n        output = pymultinest.Analyzer(outputfiles_basename=path, n_params=ndim)\n        posterior_samples = output.get_equal_weighted_posterior()[:, :-1]\n        lnz = output.get_stats()['global evidence']\n        lnzer = output.get_stats()['global evidence error']\n        return lnz, lnzer, posterior_samples\n\n    @staticmethod\n    def dynesty_results(results):\n        \"\"\"Extract posterior samples, global evidence and its error.\"\"\"\n        weights = np.exp(results['logwt'] - results['logz'][-1])\n        posterior_samples = resample_equal(results.samples, weights)\n        lnz = results.logz[-1]\n        lnzer = results.logzerr[-1]\n        return lnz, lnzer, posterior_samples\n\n    @staticmethod\n    def _get_mass(logg, rad):\n        \"\"\"Calculate mass from logg and radius.\"\"\"\n        # Solar logg = 4.437\n        # g = g_Sol * M / R**2\n        mass = logg + 2 * np.log10(rad) - 4.437\n        mass = 10 ** mass\n        return mass\n\n    @staticmethod\n    def _get_lum(teff, rad):\n        sb = sigma_sb.to(u.solLum / u.K ** 4 / u.solRad ** 2).value\n        L = 4 * np.pi * rad ** 2 * sb * teff ** 4\n        return L\n\n    @staticmethod\n    def _get_rad(samples, dist, dist_e):\n        \"\"\"Calculate radius from the normalization constant and distance.\"\"\"\n        norm = samples\n        # Create a synthetic distribution for distance.\n        # N = (R / D) ** 2\n        d = st.norm(loc=dist, scale=dist_e).rvs(size=norm.shape[0])\n        n = np.sqrt(norm)\n        r = n * d  # This is in pc\n        r *= u.pc.to(u.solRad)  # Transform to Solar radii\n        return r\n\n    @staticmethod\n    def _get_angular_diameter(rad, dist):\n        diameter = 2 * rad\n        ad = (diameter / (dist * u.pc.to(u.solRad))) * u.rad.to(u.marcsec)\n        return ad\n\n    def estimate_age(self, bf, unc, c='white'):\n        \"\"\"Estimate age using MIST isochrones.\n\n        Parameters\n        ----------\n        bf : dict\n            A dictionary with the best fit parameters.\n\n        unc : dict\n            A dictionary with the uncertainties.\n\n        \"\"\"\n        print(\n            colored(\n                '\\t\\t*** ESTIMATING AGE AND MASS USING MIST ISOCHRONES ***', c\n            )\n        )\n        params = dict()  # params for isochrones.\n        for i, k in enumerate(order):\n            if k == 'logg' or 'noise' in k:\n                continue\n            if k == 'teff':\n                par = 'Teff'\n            if k == 'z':\n                par = 'feh'\n            if k == 'dist':\n                par = 'distance'\n            if k == 'rad':\n                par = 'radius'\n            if k == 'Av':\n                par = 'AV'\n            if not self.coordinator[i]:\n                if k != 'norm':\n                    params[par] = (bf[k], max(unc[k]))\n                if k == 'norm' and self.star.dist != -1:\n                    params['distance'] = (self.star.dist, self.star.dist_e)\n                if par == 'distance':\n                    err = max(unc[k])\n                    params['parallax'] = (1000 / bf[k], 1000 * err / bf[k] ** 2)\n            else:\n                continue\n\n        params['mass'] = (bf['grav_mass'], max(unc['grav_mass']))\n        if self.star.lum != 0 and self.star.lum_e != 0:\n            params['logL'] = (np.log10(bf['lum']),\n                              abs(np.log10(max(unc['lum']))))\n        mask = np.array([1, 1, 1,\n                         0, 0,\n                         1, 1, 1,\n                         0, 0,\n                         0, 0, 0, 0,\n                         1, 1, 1,\n                         0, 0, 0, 0, 0, 0,\n                         0, 0, 0, 0, 0,\n                         1, 1,\n                         0, 0,\n                         0, 0,\n                         0, 1, 0])\n        mags = self.star.mags[mask == 1]\n        mags_e = self.star.mag_errs[mask == 1]\n        bands = [\n            'H', 'J', 'K',\n            'U', 'V', 'B',\n            'G', 'RP', 'BP',\n            'W1', 'W2',\n            'TESS'\n        ]\n        used_bands = []\n        for m, e, b in zip(mags, mags_e, bands):\n            if m != 0:\n                params[b] = (m, e)\n                used_bands.append(b)\n\n        age_samp, mass_samp, eep_samp = estimate(used_bands, params, logg=False)\n\n        return age_samp, mass_samp, eep_samp\n\n\n#####################\n# Dynesty and multinest wrappers\n\n\ndef dynesty_loglike_bma(cube, interpolator):\n    \"\"\"Dynesty log likelihood wrapper for BMA.\"\"\"\n    theta = build_params(cube, coordinator, fixed, use_norm)\n    return log_likelihood(theta, star, interpolator, use_norm, av_law)\n\n\ndef dynesty_log_like(cube):\n    \"\"\"Dynesty log likelihood wrapper.\"\"\"\n    theta = build_params(\n        cube, flux, flux_er, filts, coordinator, fixed, use_norm\n    )\n    return log_likelihood(theta, flux, flux_er, wave,\n                          filts, interpolator, use_norm, av_law)\n\n\ndef pt_dynesty(cube):\n    \"\"\"Dynesty prior transform.\"\"\"\n    return prior_transform_dynesty(cube, flux, flux_er, filts, prior_dict,\n                                   coordinator, use_norm)\n\n\ndef multinest_log_like(cube, ndim, nparams):\n    \"\"\"Multinest log likelihood wrapper.\"\"\"\n    theta = [cube[i] for i in range(ndim)]\n    theta = build_params(\n        theta, flux, flux_er, filts, coordinator, fixed, use_norm\n    )\n    return log_likelihood(theta, flux, flux_er, wave,\n                          filts, interpolator, use_norm, av_law)\n\n\ndef pt_multinest(cube, ndim, nparams):\n    \"\"\"Multinest prior transform.\"\"\"\n    prior_transform_multinest(cube, flux, flux_er, filts, prior_dict,\n                              coordinator, use_norm)\n", "meta": {"hexsha": "023d9cc2f0844a7d0bdd5ba8f18d5e30a04a90e8", "size": 58310, "ext": "py", "lang": "Python", "max_stars_repo_path": "astroARIADNE/fitter.py", "max_stars_repo_name": "AstroSong/astroARIADNE", "max_stars_repo_head_hexsha": "e66f61225bf3cd48cf02095f32a2a930726a564f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2020-06-27T10:53:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T19:38:32.000Z", "max_issues_repo_path": "astroARIADNE/fitter.py", "max_issues_repo_name": "AstroSong/astroARIADNE", "max_issues_repo_head_hexsha": "e66f61225bf3cd48cf02095f32a2a930726a564f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-10-29T15:55:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T19:32:39.000Z", "max_forks_repo_path": "astroARIADNE/fitter.py", "max_forks_repo_name": "AstroSong/astroARIADNE", "max_forks_repo_head_hexsha": "e66f61225bf3cd48cf02095f32a2a930726a564f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-03-12T10:35:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-16T15:50:25.000Z", "avg_line_length": 38.8474350433, "max_line_length": 82, "alphanum_fraction": 0.5308180415, "include": true, "reason": "import numpy,from numpy,import scipy,import astropy,from astropy", "num_tokens": 13400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.17827365725771904}}
{"text": "'''\nLive Demonstration of Blind Source Separation\n=============================================\n\nDemonstrate how to do blind source separation (BSS) using the indpendent vector\nanalysis technique. The method implemented is described in the following\npublication.\n\n    N. Ono, *Stable and fast update rules for independent vector analysis based\n    on auxiliary function technique*, Proc. IEEE, WASPAA, 2011.\n\nIt works in the STFT domain. The test files were extracted from the\n`CMU ARCTIC <http://www.festvox.org/cmu_arctic/>`_ corpus.\n\nRunning this script will do two things.\n\n1. It will separate the sources.\n2. Show a plot of the clean and separated spectrograms\n3. Show a plot of the SDR and SIR as a function of the number of iterations.\n4. Create a `play(ch)` function that can be used to play the `ch` source (if you are in ipython say).\n\nThis script requires the `sounddevice` packages to run.\n'''\n\nimport numpy as np\n\n# important to avoid a crash when tkinter is called\nimport matplotlib\nmatplotlib.use('TkAgg')\n\nimport pyroomacoustics as pra\nfrom scipy.io import wavfile\n\nfrom tkinter import Tk, Label, Button\nimport sounddevice as sd\n\nif __name__ == '__main__':\n\n    import argparse\n    parser = argparse.ArgumentParser(description='Records a segment of speech and then performs separation')\n    parser.add_argument('-b', '--block', type=int, default=2048,\n            help='STFT block length')\n    parser.add_argument('-D', '--device', type=int,\n            help='The sounddevice recording device id (obtain it with `python -m sounddevice`)')\n    parser.add_argument('-d', '--duration', type=float,\n            help='Recording time in seconds')\n    parser.add_argument('-i', '--n_iter', type=int, default=20,\n            help='Number of iteration of the algorithm')\n    args = parser.parse_args()\n\n    # STFT frame length\n    L = args.block\n\n    # Let's hard code sampling frequency to avoid some problems\n    fs = 16000\n\n    # Do the recording\n    if args.device is not None:\n        sd.default.device[0] = args.device\n\n    # Mix down the recorded signals\n    print('* Recording started... ', end='')\n    mics_signals = sd.rec(int(args.duration * fs), samplerate=fs, channels=2, blocking=True)\n    print('done')\n\n    # START BSS\n    ###########\n    # The STFT needs front *and* back padding\n\n    print('* Starting BSS')\n\n    # shape == (n_chan, n_frames, n_freq)\n    X = np.array([pra.stft(ch, L, L, transform=np.fft.rfft, zp_front=L//2, zp_back=L//2) for ch in mics_signals.T])\n    X = np.moveaxis(X, 0, 2)\n\n    # Callback to monitor progress of algorithm\n    it = 10\n    def cb_print(*args):\n        global it\n        print('  AuxIVA Iter', it)\n        it += 10\n\n    # Run AuxIVA\n    Y = pra.bss.auxiva(X, n_iter=args.n_iter, proj_back=True, callback=cb_print)\n\n    # run iSTFT\n    y = np.array([pra.istft(Y[:,:,ch], L, L, transform=np.fft.irfft, zp_front=L//2, zp_back=L//2) for ch in range(Y.shape[2])])\n\n    print('* Start GUI')\n\n    # Now comes the GUI part\n    class PlaySoundGUI(object):\n        def __init__(self, master, fs, mix, sources):\n            self.master = master\n            self.fs = fs\n            self.mix = mix\n            self.sources = sources\n            master.title(\"A simple GUI\")\n\n            self.label = Label(master, text=\"This is our first GUI!\")\n            self.label.pack()\n\n            self.mix_button = Button(master, text='Mix', command=lambda: self.play(self.mix))\n            self.mix_button.pack()\n\n            self.buttons = []\n            for i, source in enumerate(self.sources):\n                self.buttons.append(Button(master, text='Source ' + str(i+1), command=lambda src=source : self.play(src)))\n                self.buttons[-1].pack()\n\n            self.stop_button = Button(master, text=\"Stop\", command=sd.stop)\n            self.stop_button.pack()\n\n            self.close_button = Button(master, text=\"Close\", command=master.quit)\n            self.close_button.pack()\n\n        def play(self, src):\n            sd.play(pra.normalize(src) * 0.75, samplerate=self.fs, blocking=False)\n    \n\n    root = Tk()\n    my_gui = PlaySoundGUI(root, fs, mics_signals[:,0], y)\n    root.mainloop()\n", "meta": {"hexsha": "06e6fc06435e97e8894815eeb6b7c45967e8ccaf", "size": 4149, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/bss_live.py", "max_stars_repo_name": "snsun/pyroomacoustics", "max_stars_repo_head_hexsha": "aa2ea882fb79bcab0d55edf852d718ad060d03b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/bss_live.py", "max_issues_repo_name": "snsun/pyroomacoustics", "max_issues_repo_head_hexsha": "aa2ea882fb79bcab0d55edf852d718ad060d03b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/bss_live.py", "max_forks_repo_name": "snsun/pyroomacoustics", "max_forks_repo_head_hexsha": "aa2ea882fb79bcab0d55edf852d718ad060d03b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4596774194, "max_line_length": 127, "alphanum_fraction": 0.6391901663, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.17827365022416777}}
{"text": "import numpy as np\nimport os\nimport astropy.constants as const\nimport astropy.units as u\nimport scipy.interpolate as interp\nfrom astropy.cosmology import z_at_value\nfrom astropy.cosmology import WMAP9 as cosmo\n\nimport gwent\nfrom .waveform import Get_Waveform\nfrom . import utils\n\ncurrent_path = os.path.abspath(gwent.__path__[0])\nload_directory = os.path.join(current_path,'LoadFiles/')\n\nclass BinaryBlackHole:\n    \"\"\"Base Class for frequency domain strains from Binary Black Holes.\n\n    Parameters\n    ----------\n    M : float\n        Total mass of the black hole binary (m1+m2)\n    q : float\n        Mass ratio of the black hole binary (m1/m2, m1<m2)\n    z : float\n        Redshift of the black hole binary\n\n    load_location : string, optional\n        the directory of the loaded file, (ie. '/path/to/file')\n\n    Notes\n    -----\n    IMRPhenomD waveforms calibrated for q = m1/m2 < 18\n\n    \"\"\"\n    def __init__(self,*args,**kwargs):\n        if len(args) == 3:\n            [M,q,z] = args\n        elif len(args) == 5:\n            [M,q,z,_,_] = args\n        else:\n            raise ValueError('args must be a list of 3 ([M,q,z]) or 5 ([M,q,z,chi1,chi2])')\n        self.M = M\n        self.q = q\n        self.z = z\n\n        for keys,value in kwargs.items():\n            if keys == 'load_location':\n                self.load_location = value\n\n        if hasattr(self,'load_location'):\n            self.Load_Data()\n\n    @property\n    def M(self):\n        self._M = utils.make_quant(self._M,'M_sun')\n        return self._M\n    @M.setter\n    def M(self,value):\n        self.var_dict = ['M',value]\n        self._M = self._return_value\n\n    @property\n    def q(self):\n        return self._q\n    @q.setter\n    def q(self,value):\n        self.var_dict = ['q',value]\n        self._q = self._return_value\n\n    @property\n    def z(self):\n        return self._z\n    @z.setter\n    def z(self,value):\n        self.var_dict = ['z',value]\n        self._z = self._return_value\n\n    @property\n    def h_f(self):\n        if not hasattr(self,'_h_f'):\n            raise NotImplementedError('The strain must be defined inside BBHFrequencyDomain or BBHTimeDomain classes.')\n        return self._h_f\n    @h_f.setter\n    def h_f(self,value):\n        self._h_f = value\n\n    @property\n    def f(self):\n        if not hasattr(self,'_f'):\n            raise NotImplementedError('Interferometer frequency must be defined inside SpaceBased or GroundBased classes.')\n        return self._f\n    @f.setter\n    def f(self,value):\n        self._f = value\n\n    @property\n    def var_dict(self):\n        return self._var_dict\n    @var_dict.setter\n    def var_dict(self,value):\n        utils.Get_Var_Dict(self,value)\n\n    def Load_Data(self):\n        if hasattr(self,'load_location'):\n            if os.path.exists(self.load_location):\n                self._load_data = np.loadtxt(self.load_location)\n            else:\n                raise IOError('File %s does not exist, please assign load_location a correct filepath.' %self.load_location)\n        else:\n            raise ValueError('load_location is not assigned, please set with name_of_BBH.load_location=\"path/to/file\".')\n\nclass BBHFrequencyDomain(BinaryBlackHole):\n    \"\"\"Subclass of BinaryBlackHole for BBH GWs generated in the frequency domain.\n\n    Parameters\n    ----------\n    chi1 : float\n        The dimensionless spin parameter abs(a/m) for black hole m1.\n    chi2 : float\n        The dimensionless spin parameter abs(a/m) for black hole m2\n\n    f_low : float, optional\n        The lowest frequency in natural units (Mf, G=c=1) at which the BBH waveform is calculated\n    nfreqs : int, optional\n        The number of frequencies at which the BBH waveform is calculated\n\n    Notes\n    -----\n    IMRPhenomD waveforms calibrated for aligned spins chi_1, chi_2 = abs(a/m) <= 0.85 or if q=1 abs(a/m)<0.98\n\n    \"\"\"\n    def __init__(self,*args,**kwargs):\n        super().__init__(*args,**kwargs)\n        [_,_,_,chi1,chi2] = args\n        self.chi1 = chi1\n        self.chi2 = chi2\n\n        for keys,value in kwargs.items():\n            if keys == 'f_low':\n                self.f_low = value\n            elif keys == 'f_high':\n                self.f_high = value\n            elif keys == 'nfreqs':\n                self.nfreqs = value\n            elif keys == 'instrument':\n                self.instrument = value\n                self.Check_Freq_Evol()\n        if not hasattr(self,'nfreqs'):\n            self.nfreqs = int(1e3)\n        if not hasattr(self,'f_low'):\n            self.f_low = 1e-5\n\n        self.Get_Fitcoeffs()\n\n    @property\n    def chi1(self):\n        return self._chi1\n    @chi1.setter\n    def chi1(self,value):\n        self.var_dict = ['chi1',value]\n        self._chi1 = self._return_value\n\n    @property\n    def chi2(self):\n        return self._chi2\n    @chi2.setter\n    def chi2(self,value):\n        self.var_dict = ['chi2',value]\n        self._chi2 = self._return_value\n\n    @property\n    def instrument(self):\n        return self._instrument\n    @instrument.setter\n    def instrument(self,value):\n        self._instrument = value\n\n    @property\n    def h_gw(self):\n        if not hasattr(self,'_h_gw'):\n            if not hasattr(self,'f_init'):\n                if hasattr(self,'_instrument'):\n                    self.Check_Freq_Evol()\n                else:\n                    raise ValueError('No instrument assigned, please fix it. '\\\n                        'Try: \"source.instrument = instrument\".')\n                self._h_gw = Get_Mono_Strain(self,self.instrument.f_opt).to('')\n            else:\n                self._h_gw = Get_Mono_Strain(self,self.f_init).to('')\n        return self._h_gw\n    @h_gw.setter\n    def h_gw(self,value):\n        self._h_gw = value\n    @h_gw.deleter\n    def h_gw(self):\n        del self._h_gw\n\n    @property\n    def h_f(self):\n        if not hasattr(self,'_h_f'):\n            if not (hasattr(self,'_phenomD_f') and hasattr(self,'_phenomD_h')):\n                self.Get_PhenomD_Strain()\n            [_,self._h_f] = Strain_Conv(self,self._phenomD_f,self._phenomD_h)\n        return self._h_f\n    @h_f.deleter\n    def h_f(self):\n        del self._h_f\n\n    @property\n    def f(self):\n        if not hasattr(self,'_f'):\n            if not (hasattr(self,'_phenomD_f') and hasattr(self,'_phenomD_h')):\n                self.Get_PhenomD_Strain()\n            [self._f,_] = Strain_Conv(self,self._phenomD_f,self._phenomD_h)\n        return self._f\n    @f.deleter\n    def f(self):\n        del self._f\n\n    def Get_Fitcoeffs(self):\n        \"\"\"Loads Quasi-Normal Mode fitting files for speed later.\"\"\"\n        fit_coeffs_filedirectory = os.path.join(load_directory,'PhenomDFiles/fitcoeffsWEB.dat')\n        self._fitcoeffs = np.loadtxt(fit_coeffs_filedirectory)\n\n    def Get_PhenomD_Strain(self):\n        \"\"\"Gets the BBH's frequency and waveform from IMRPhenomD.\"\"\"\n        if not hasattr(self,'_fitcoeffs'):\n            self.Get_Fitcoeffs()\n        [self._phenomD_f,self._phenomD_h] = Get_Waveform(self)\n\n    def Get_Time_From_Merger(self,f_obs):\n        \"\"\"Calculates the time from merger of a binary black hole given an observed frequency.\n\n        Parameters\n        ----------\n        f_obs : float\n            the initially observed frequency in the instrument frame.\n\n        \"\"\"\n        m_conv = const.G/const.c**3 #Converts M = [M] to M = [sec]\n        eta = self.q/(1+self.q)**2\n\n        M_time = self.M.to('kg')*m_conv\n        M_chirp = eta**(3/5)*M_time\n\n        f_obs_source = f_obs*(1+self.z)\n        return 5*(M_chirp)**(-5/3)*(8*np.pi*f_obs_source)**(-8/3)\n\n    def Get_Source_Freq(self,tau):\n        \"\"\"Calculates the binary black hole's gravitational wave frequency given a time from merger\n\n        Parameters\n        ----------\n        tau : float\n            the time from merger in the source frame\n\n        \"\"\"\n        m_conv = const.G/const.c**3 #Converts M = [M] to M = [sec]\n        eta = self.q/(1+self.q)**2\n\n        M_time = self.M.to('kg')*m_conv\n        M_chirp = eta**(3/5)*M_time\n\n        return 1./8./np.pi/M_chirp*(5*M_chirp/tau)**(3./8.)\n\n    def Check_Freq_Evol(self):\n        \"\"\"Checks the frequency evolution of the black hole binary.\n\n        Notes\n        -----\n        If the frequency of the binary does evolve over more than one bin,\n        (ie f(T_obs)-f(t_init) = delf_obs < 1/T_obs), it is monochromatic, so we set the frequency\n        to the optimal frequency of the detector\n\n        Otherwise it is chirping and evolves over the observation and we\n        set the starting frequency we observe it at to f(Tobs), which is the\n        frequency at an observation time before merger\n\n        To get the change in frequency, we use eqn 41 from Hazboun,Romano, and Smith (2019) <https://arxiv.org/abs/1907.04341>\n        which uses binomial expansion of f_T_obs_inst - f_init_inst and thus will never be imaginary\n\n        \"\"\"\n        m_conv = const.G/const.c**3 #Converts M = [M] to M = [sec]\n        eta = self.q/(1+self.q)**2\n\n        M_time = self.M.to('kg')*m_conv\n        M_chirp_source = eta**(3/5)*M_time\n\n        T_obs = utils.make_quant(self.instrument.T_obs,'s')\n        T_obs_source = T_obs/(1+self.z)\n\n\n        #Assumes t_init is in source frame, can either be randomly drawn\n        #t_init_source = np.random.uniform(0,100)*u.yr\n\n        #Assumes f_init is the optimal frequency in the instrument frame to get t_init_source\n        self.f_init = self.instrument.f_opt\n        t_init_source = self.Get_Time_From_Merger(self.f_init)\n\n        #f(T_obs), the frequency of the source at T_obs before merger\n        f_T_obs_source = self.Get_Source_Freq(T_obs_source)\n        #f(T_obs) in the instrument frame\n        self.f_T_obs = f_T_obs_source/(1+self.z)\n\n        #t_init_source = make_quant(t_init_source,'s')\n        #f_init_source = self.Get_Source_Freq(t_init_source)\n        #self.f_init = f_init_source/(1+self.z)\n        #f_after_T_obs_source = self.Get_Source_Freq((t_init_source-T_obs_source))\n        #self.f_T_obs = f_after_T_obs_source/(1+self.z)\n        #delf_obs_source_exact = f_after_T_obs_source-f_init_source\n\n        delf_obs_source_approx = 1./8./np.pi/M_chirp_source*(5*M_chirp_source/t_init_source)**(3./8.)*(3*T_obs_source/8/t_init_source)\n        delf_obs =  delf_obs_source_approx/(1+self.z)\n\n        if delf_obs < (1/T_obs):\n            self.ismono = True\n        else:\n            self.ismono = False\n\n\n\n\nclass BBHTimeDomain(BinaryBlackHole):\n    \"\"\"Subclass of BinaryBlackHole for input in the time domain\"\"\"\n    def __init__(self,*args,**kwargs):\n        super().__init__(*args,**kwargs)\n        self.Get_hf_from_hcross_hplus()\n\n    @property\n    def t(self):\n        if not hasattr(self,'_t'):\n            self._t = self._load_data[:,0]\n        self._t = utils.make_quant(self._t,'s')\n        return self._t\n\n    @property\n    def h_plus_t(self):\n        if not hasattr(self,'_h_plus_t'):\n            self._h_plus_t = self._load_data[:,1]\n        return self._h_plus_t\n\n    @property\n    def h_cross_t(self):\n        if not hasattr(self,'_h_cross_t'):\n            self._h_cross_t = self._load_data[:,1]\n        return self._h_cross_t\n\n    @property\n    def h_f(self):\n        if not hasattr(self,'_h_f'):\n            [natural_f,natural_h] = self.Get_hf_from_hcross_hplus()\n            [_,self._h_f] = Strain_Conv(self,natural_f,natural_h)\n        return self._h_f\n    @h_f.deleter\n    def h_f(self):\n        del self._h_f\n\n    @property\n    def f(self):\n        if not hasattr(self,'_f'):\n            [natural_f,natural_h] = self.Get_hf_from_hcross_hplus()\n            [self._f,_] = Strain_Conv(self,natural_f,natural_h)\n        return self._f\n    @f.deleter\n    def f(self):\n        del self._f\n\n\n    def Get_hf_from_hcross_hplus(self,interp_res='coarse',windowing='left'):\n        \"\"\"Converts dimensionless, time domain strain to frequency space using a windowed fft\n\n        Parameters\n        ----------\n        interp_res : {'coarse','fine'}, optional\n            'coarse' uses maximum difference between subsequent time steps for interpolation\n            'fine' uses minimum difference between subsequent time steps for interpolation\n        windowing : {'left','right','all'}, optional\n            'left' windows the left side of the time data\n            'right' windows the right side of the time data\n            'all' windows the both the left and right side of the time data\n\n        Returns\n        -------\n        natural_f : array\n            The frequency of the input source in natural units (G=c=1)\n        natural_h : array\n            The strain of the input source in natural units (G=c=1)\n\n        \"\"\"\n\n        #Interpolate time to evenly sampled data, can be fine or coarse\n        diff_t = np.diff(self.t.value)\n        if interp_res == 'fine':\n            dt = min(diff_t)\n        elif interp_res == 'coarse':\n            dt = max(diff_t)\n\n        interp_t = np.arange(self.t[0].value,self.t[-1].value,dt)\n        #interpolate strain to evenly sampled data for FFT\n        h_cross_t = interp.interp1d(self.t,self.h_cross_t,kind='cubic')\n        h_plus_t = interp.interp1d(self.t,self.h_plus_t,kind='cubic')\n        interp_h_cross_t = h_cross_t(interp_t)\n        interp_h_plus_t = h_plus_t(interp_t)\n\n        #Filter/Window\n        hann_window = np.hanning(len(interp_t)) #Two sided\n        if windowing == 'left':\n            #########################\n            \"\"\"Applies window to first (left) half\"\"\"\n            first_half = hann_window[:int(len(interp_t)/2)] # Only need tapering on first half of waveform\n            second_half = np.ones(len(interp_t)-len(first_half)) #no windowing on second half of waveform\n            #########################\n            window = np.append(first_half,second_half) # Only apply window to first half of waveform\n        elif windowing == 'right':\n            #########################\n            \"\"\"Applies window to second (right) half\"\"\"\n            second_half = hann_window[int(len(interp_t)/2):] # Only need tapering on second half of waveform\n            first_half = np.ones(len(interp_t)-len(second_half)) #no windowing on first half of waveform\n            #########################\n            window = np.append(first_half,second_half)\n        elif windowing == 'all':\n            window = hann_window\n        #Window!\n        win_h_cross_t = np.multiply(interp_h_cross_t,window)\n        win_h_plus_t = np.multiply(interp_h_plus_t,window)\n\n        #FFT the two polarizations\n        h_cross_f = np.fft.fft(win_h_cross_t)\n        h_plus_f = np.fft.fft(win_h_plus_t)\n        freqs = np.fft.fftfreq(len(interp_t),d=dt)\n\n        #cut = np.abs(freqs).argmax() #Cut off the negative frequencies\n        f_cut_low = 3e-3 #Low Cutoff frequency\n        f_cut_high = 1.5e-1 #High Cutoff frequency\n        cut_low = np.abs(freqs-f_cut_low).argmin() #Cut off frequencies lower than a frequency\n        cut_high = np.abs(freqs-f_cut_high).argmin() #Cut off frequencies higher than a frequency\n        #cut=int(len(freqs)*0.9) #Cut off percentage of frequencies\n        h_cross_f = h_cross_f[cut_low:cut_high]\n        h_plus_f = h_plus_f[cut_low:cut_high]\n        natural_f = freqs[cut_low:cut_high]\n\n        #Combine them for raw spectral power\n        natural_h_f = np.sqrt((np.abs(h_cross_f))**2 + (np.abs(h_plus_f))**2)\n        return [natural_f,natural_h_f]\n\n\n\ndef Strain_Conv(source,natural_f,natural_h):\n    \"\"\"Converts frequency and strain in natural units (G=c=1) to Hertz and dimensionless, respectively.\n\n    Parameters\n    ----------\n    source\n        Instance of gravitational wave source class\n    natural_f : array [Mf]\n        the frequency of the source in natural units (G=c=1)\n    natural_h : array [Mf]\n        the strain of the source in natural units (G=c=1)\n\n    \"\"\"\n    DL = cosmo.luminosity_distance(source.z)\n    DL = DL.to('m')\n\n    m_conv = const.G/const.c**3 #Converts M = [M] to M = [sec]\n    M_redshifted_time = source.M.to('kg')*(1+source.z)*m_conv\n\n    #frequency and strain of source in detector frame\n    freq_conv = 1/M_redshifted_time\n    #Normalized factor to match Stationary phase approx at low frequencies?\n    #Changed from sqrt(5/16/pi)\n    strain_conv = np.sqrt(1/4/np.pi)*(const.c/DL)*M_redshifted_time**2\n\n    f = natural_f*freq_conv\n    h_f = natural_h*strain_conv\n    return [f,h_f]\n\ndef Get_Char_Strain(source):\n    \"\"\"Converts source strain to characteristic strain\n\n    Parameters\n    ----------\n    source\n        Instance of gravitational wave source class\n\n    \"\"\"\n    h_char = np.sqrt(4*source.f**2*source.h_f**2)\n    return h_char\n\ndef Get_Mono_Strain(source,f_gw,strain_const='Averaged'):\n    \"\"\"Calculates the strain from a binary black hole.\n\n    Parameters\n    ----------\n    f_gw : float\n        The source frequency of the gravitational wave.\n    strain_const : {'Averaged','Optimal'}\n        'Averaged' gives the sky and inclination averaged strain from Robson et al. 2019 (eqn 27) <https://arxiv.org/pdf/1803.01944.pdf>\n        'Optimal' gives the optimally oriented, face-on, inclination (ie. inc=0) value\n\n    Returns\n    -------\n    float\n        the strain of a monochromatic source in the dector frame\n\n    \"\"\"\n    f_gw = utils.make_quant(f_gw,'Hz')\n    if isinstance(strain_const,str):\n        DL = cosmo.luminosity_distance(source.z)\n        DL = DL.to('m')\n\n        #Converts M = [M] to M = [sec]\n        m_conv = const.G/const.c**3\n\n        eta = source.q/(1+source.q)**2\n        M_redshifted_time = source.M.to('kg')*(1+source.z)*m_conv\n        M_chirp = eta**(3/5)*M_redshifted_time\n\n        if strain_const == 'Optimal':\n            inc = 0.0\n            a = 1+np.cos(inc)**2\n            b = -2*np.cos(inc)\n            const_val = 2*np.sqrt(.5*(a**2+b**2))\n        elif strain_const == 'Averaged':\n            const_val = 8/np.sqrt(5)\n        else:\n            raise ValueError('Can only use \"Averaged\", or \"Optimal\" monochromatic strain calculation.')\n\n        return const_val*(const.c/DL)*(np.pi*f_gw)**(2./3.)*M_chirp**(5./3.)\n    else:\n        raise ValueError('Can only use \"Averaged\", or \"Optimal\" monochromatic strain calculation.')\n", "meta": {"hexsha": "873d06a1424a41b4478f6339ea0d23df35a5bb7b", "size": 18032, "ext": "py", "lang": "Python", "max_stars_repo_path": "gwent/binary.py", "max_stars_repo_name": "Hazboun6/gwent", "max_stars_repo_head_hexsha": "b6b6f93f4f83b5230917b4aa17d4d3ac1d0438a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gwent/binary.py", "max_issues_repo_name": "Hazboun6/gwent", "max_issues_repo_head_hexsha": "b6b6f93f4f83b5230917b4aa17d4d3ac1d0438a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gwent/binary.py", "max_forks_repo_name": "Hazboun6/gwent", "max_forks_repo_head_hexsha": "b6b6f93f4f83b5230917b4aa17d4d3ac1d0438a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8947368421, "max_line_length": 136, "alphanum_fraction": 0.6093056788, "include": true, "reason": "import numpy,import scipy,import astropy,from astropy", "num_tokens": 4712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.2782567817320044, "lm_q1q2_score": 0.17826127122988158}}
{"text": "'''\nI was inspired by this paper \"Third-Person Imitation Learning\", which is available on arXiv. Link: https://arxiv.org/pdf/1703.01703.pdf\n\nThere are 3 important parts, Df, Dr, Dd, which are feature extractor, performer discriminator, and domain discriminator, respectively, as mentioned in the paper.\n\nImages are first sent into Df which will then extract features from them. These features should be domain invariant, or environment agnostic. In other words, one cannot tell from where the initial images come solely based on these features.\n\nThe extracted features are then sent into Dd. Dd will classify their source domains. A good Df will output confusing features as discussed above so that a good Dd will give any answer with equal probability.\n\nThe features are also sent into Dr. In fact, features from several time-steps will be sent to introduce temporal information. Dr will then give its judgement about whether it is the expert doing the task, or it is an amateur.\n\nWe discovered that 3 components need each other and no one can be singled out. Feature extractor Df is neccessary since dealing higher level concept is better than handling raw pixels. Domain discriminator Dd is also needed because we need to force our Df to be domain invariant. And finally, if without Dr, the Df will easily adjust to output constants to fool Dd, which is clearly not desired. Thus Dr is crucial for training Df to extract meaningful features.\n\nSo we can only implement and test 3 components all at once. If we see them as a new whole integrity then we will feel less pain (:-)\n'''\n\nimport tensorflow as tf\nimport numpy as np\n\n# Hyperparameters\n_lambda = 1.0\n\nsess = tf.Session()\n\n# Training batch\nbatch = 1\n# image time interval\nin_depth = 1\n# image height\nin_height = 1\n# image width\nin_width = 1\n# Colored image typically has 3 channels\n# RGB or HSI\nin_channel = 3\n\n\n# Construct input layer\n# input: A Tensor. Must be one of the following types: half, bfloat16, float32, float64. Shape [batch, in_depth, in_height, in_width, in_channels].\ninput_layer = tf.placeholder('float',\n                             [batch,in_depth,in_height,in_width,in_channel],\n                             name='Input')\n\n\n# Feature extractor Df\ndf_train_var = []\n# conv-pool-conv-pool\n\n# Convolutional Layer 1\n# Use padding \nconv_layer_1 = tf.layers.Conv3D(filters = 64,\n                                kernel_size=[5,5,5],\n                                padding = 'same',\n                                activation= tf.nn.relu,\n                               name = 'Df_Conv_1')\n\n# Max Pooling Layer 1\npool_layer_1 = tf.layers.MaxPooling3D(pool_size = [2,2,2],\n                                      strides = [1,1,1],\n                                      padding = 'same',\n                                     name = 'Df_Pool_1')\n\n\n# Convolutional layer 2\nconv_layer_2 = tf.layers.Conv3D(filters = 32,\n                               kernel_size = [5,5,5],\n                               padding = 'same',\n                               activation = tf.nn.relu,\n                               name = 'Df_Conv_2')\n# The last max pooling layer, used as feature layer\nfeature_layer = tf.layers.MaxPooling3D(pool_size = [2,2,2],\n                                      strides = [1,1,1],\n                                      padding = 'same',\n                                      name = 'Feature')\n\n\n# Construct feature extractor\ndf = conv_layer_1(input_layer)\ndf = pool_layer_1(df)\ndf = conv_layer_2(df)\ndf = feature_layer(df)\n\n# Domain Discriminator\ndd_train_var = []\ndense_layer_1 = tf.layers.Dense(units=1024,\n                                activation = tf.nn.relu,\n                               name = 'Dd_Dense')\ndropout_layer_1 = tf.layers.Dropout(rate = 0.5,\n                                   name = 'Dd_Dropout')\n# Logits Layer\nlogits_layer_1 = tf.layers.Dense(units=2,\n                                name = 'Dd_Logits')\n\n\n# Construct domain discriminator\ndd = dense_layer_1(df)\ndd = dropout_layer_1(dd)\ndd = logits_layer_1(dd)\n\n# Performer Discriminator\ndr_train_var = []\ndense_layer_2 = tf.layers.Dense(units=1024,\n                                activation = tf.nn.relu,\n                               name = 'Dr_Dense')\ndropout_layer_2 = tf.layers.Dropout(rate = 0.5,\n                                   name = 'Dr_Dropout')\n# Logits Layer\nlogits_layer_2 = tf.layers.Dense(units=2,\n                                name = 'Dr_Logits')\n\n# Construct performer discriminator\ndr = dense_layer_2(df)\ndr = dropout_layer_2(dr)\ndr = logits_layer_2(dr)\n\n\nlabels = np.array([[1,2]])\n# Domain discrimination loss\n##dd_loss = tf.losses.softmax_cross_entropy(onehot_labels=labels,logits=dd_logits_layer)\n# Performer discrimination loss\n##dr_loss = tf.losses.softmax_cross_entropy(onehot_labels=labels,logits=dr_logits_layer)\n# Total loss used to train a domain invariant Df and corresponding Dr\n##loss = dr_loss-_lambda*dd_loss\n\n\ndd_loss = tf.losses.softmax_cross_entropy(onehot_labels=[[[[[1,2]]]]],\n                                          logits = dd)\ndr_loss = tf.losses.softmax_cross_entropy(onehot_labels=[[[[[1,2]]]]],\n                                          logits = dr)\ntotal_loss = dr_loss - _lambda*dd_loss\nadam_op = tf.train.AdamOptimizer()\n\n# Variables in layers are created only after we initialize them!\ninit = tf.global_variables_initializer()\nsess.run(init)\n\n# Gather all trainable variables into one single list\ndf_train_var += conv_layer_1.trainable_variables\ndf_train_var += pool_layer_1.trainable_variables\ndf_train_var += conv_layer_2.trainable_variables\ndf_train_var += feature_layer.trainable_variables\n# Gather all trainable variables into one single list\ndd_train_var += dense_layer_1.trainable_variables\ndd_train_var += dropout_layer_1.trainable_variables\ndd_train_var += logits_layer_1.trainable_variables\n# Gather all trainable variables into one single list\ndr_train_var +=dense_layer_2.trainable_variables\ndr_train_var +=dropout_layer_2.trainable_variables\ndr_train_var +=logits_layer_2.trainable_variables\n\n# Pretraining\npretrain_op = adam_op.minimize(loss=dr_loss,\n                              var_list = df_train_var+dr_train_var,\n                              name = 'Pretrain')\n\n# Fix feature extractor and train Dd\ndd_train_op = adam_op.minimize(loss = dd_loss,\n                              var_list = dd_train_var,\n                              name = 'Train_Dd')\n# Fix domain discriminator and train Df and Dr\ntrain_op = adam_op.minimize(loss=total_loss,\n                           global_step = tf.train.get_global_step(),\n                           var_list = df_train_var+dr_train_var,\n                           name = 'Train_Df_Dr')\n\ninit = tf.global_variables_initializer()\nsess.run(init)\n\n# Run pretraining\nsess.run(pretrain_op,feed_dict = {input_layer:[[[[[255,255,255]]]]]})\n\ndef is_converge():\n    return True\n\n# Begin train loop\nwhile True:\n    sess.run(dd_train_op,feed_dict = {input_layer:[[[[[255,255,255]]]]]})\n    sess.run(train_op,feed_dict = {input_layer:[[[[[255,255,255]]]]]})\n    if is_converge():\n        break\n\nwriter = tf.summary.FileWriter(\"./model/\", sess.graph)\n\nwriter.close()", "meta": {"hexsha": "894297b769a6bca111d441b70c91985448c5cbb7", "size": 7129, "ext": "py", "lang": "Python", "max_stars_repo_path": "Research/imitate_experiments/001/script02.py", "max_stars_repo_name": "RockmanZheng/AgentSteve", "max_stars_repo_head_hexsha": "7b28fdd571056f802ff674c1cdebe66710e295c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-27T17:41:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-27T17:41:37.000Z", "max_issues_repo_path": "Research/imitate_experiments/001/script02.py", "max_issues_repo_name": "RockmanZheng/AgentSteve", "max_issues_repo_head_hexsha": "7b28fdd571056f802ff674c1cdebe66710e295c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Research/imitate_experiments/001/script02.py", "max_forks_repo_name": "RockmanZheng/AgentSteve", "max_forks_repo_head_hexsha": "7b28fdd571056f802ff674c1cdebe66710e295c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7445652174, "max_line_length": 462, "alphanum_fraction": 0.6508626736, "include": true, "reason": "import numpy", "num_tokens": 1617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.17824186776430587}}
{"text": "#Copyright 2019 Russell Carroll\n#\n#Licensed under the Apache License, Version 2.0 (the \"License\");\n#you may not use this file except in compliance with the License.\n#You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n#Unless required by applicable law or agreed to in writing, software\n#distributed under the License is distributed on an \"AS IS\" BASIS,\n#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#See the License for the specific language governing permissions and\n#limitations under the License.\n\nfrom math import *\nfrom numpy import *\nimport os\n\nclass Qucs2Gerber():\n\n  # ----------------------------------------\n  # General Class functions\n  # ----------------------------------------\n\n  def __init__(self):\n    self.log_fn   = \"qucs2grb_log.txt\"\n    self.out_fn   = \"qucs_out.gbr\"\n    self.num_int  = 2\n    self.num_decimals = 5\n    self.unit_scale = 1.0 # Inches\n    self.units = \"in\"\n    self.verbose  = False\n    self.out_fh   = None\n    self.netlist_data = None\n    self.log_print(\"-- QUCS to Gerber File Conversion Log --\\n\",'w')\n  \n  def __del__(self):\n    self.kill()\n  \n  def kill(self):\n    if self.out_fh:\n      self.out_fh.close()\n  \n  def log_print(self,text,mode='a'):\n    try:\n      fh = open(self.log_fn,mode)\n      fh.write(str(text) + \"\\n\")\n      fh.close()\n    except:\n      print(\"Error: Could not write to log file! \" + self.log_fn)\n      self.verbose = True\n    \n  # Print to screen and log\n  def fprint(self,text,force=False):\n    if self.verbose or force:\n      print(str(text))\n    self.log_print(text)\n\n  # ----------------------------------------\n  # Functions for Gerber File Generation\n  # ----------------------------------------\n\n  def SetDecimals(self,decimals,leading=2):\n    try:\n      self.num_decimals = int(decimals)\n      self.num_int = int(leading)\n    except:\n      self.fprint(\"Error: Could not read number of decimals!\")\n\n  def SetUnits(self,units):\n    if \"in\" in units:\n      unit_scale = 1.0  # scale everything to inches\n    elif \"mm\" in units:\n      unit_scale = 0.0393701\n    else:\n      self.fprint(\"Error: Unknown units! \" + units,force=True)\n      return False\n    self.units = units\n    self.unit_scale = unit_scale\n\n  def OpenOutpuFile(self,fn=\"output.grb\"):\n    self.out_fn = fn\n    try:\n      self.out_fh = open(self.out_fn,'w')\n      return True\n    except:\n      self.fprint(\"Error: Could not output file! \" + self.out_fn,force=True)\n      self.verbose = True\n      return False\n    \n  def out_write(self,text,append_str='\\n'):\n    try:\n      self.out_fh.write(str(text) + append_str)\n    except:\n      self.fprint(\"Error: Could not write to output file! \" + self.out_fn,force=True)\n      self.verbose = True\n    \n  def GenerateHeader(self):\n    header = [\n      \"G04 Generated using qucs2gerber.py*\",\n      \"G04 Input file: {}*\".format(self.netlist_fn),\n      \"%MO{}*%\".format(self.units.upper()),             # Use relevant units\n      \"%LNTOP*%\",                                       # Layer name TOP\n      # Format specification, Leading zeros omitted, absolute coordinates, integer places, decimal places\n      \"%FSLAX{}{}Y{}{}*%\".format(self.num_int,self.num_decimals,self.num_int,self.num_decimals),      \n      \"%ADD11C,0.0001*%\"    # Define aperature, D11 is a circle with diameter of 0.0001 inch\n    ]\n    for l in header:\n      self.out_write(l)\n  \n  def Finish(self):\n    self.out_write(\"M02*\",append_str='')\n  \n  def get_int(self,f):\n    return int(round(f*10**self.num_decimals))\n  \n  # Draw rectangle with left edge at the origin\n  def DrawRectangleLEO(self,width=1.0,length=1.0,x0=0.0,y0=0.0,rot=0.0):\n    rot_rad = rot*pi/180.0\n    R = [[cos(rot_rad),sin(rot_rad)],[-sin(rot_rad),cos(rot_rad)]]  # rotation matrix\n    # initial coordinates\n    a = [0, -width/2.0]\n    b = [0, +width/2.0]\n    c = [length, +width/2.0]\n    d = [length, -width/2.0]\n    # rotated coordinates\n    at = dot(a,R)\n    bt = dot(b,R)\n    ct = dot(c,R)\n    dt = dot(d,R)\n    commands = [\n      \"G54D11*\",    # Select aperature D11\n      \"G36*\",       # Enable region mode\n      \"G01*\",\n      \"X{}Y{}D02*\".format(self.get_int(at[0]+x0),self.get_int(at[1]+y0)), \n      \"X{}Y{}D01*\".format(self.get_int(bt[0]+x0),self.get_int(bt[1]+y0)),\n      \"X{}Y{}D01*\".format(self.get_int(ct[0]+x0),self.get_int(ct[1]+y0)),\n      \"X{}Y{}D01*\".format(self.get_int(dt[0]+x0),self.get_int(dt[1]+y0)),\n      \"X{}Y{}D01*\".format(self.get_int(at[0]+x0),self.get_int(at[1]+y0)),\n      \"G37*\"        # Disable region mode\n    ]\n    for cmd in commands:\n      self.out_write(cmd)\n\n  # Draw polygon from list of corners\n  def DrawPolygon(self,corners,x0=0.0,y0=0.0,rot=0.0):\n    rot_rad = -rot*pi/180.0\n    R = [[cos(rot_rad),sin(rot_rad)],[-sin(rot_rad),cos(rot_rad)]]  # rotation matrix\n    # Generate transformed coordinates\n    offset = array([x0,y0])\n    ct = []\n    for c in corners:\n      ct.append(dot(R,c) + offset)\n    ct.append(ct[0])\n    # write the output\n    self.out_write(\"G54D11*\")  \n    self.out_write(\"G36*\")  \n    self.out_write(\"G01*\")  # Linear interpolation\n    self.out_write(\"X{}Y{}D02*\".format(self.get_int(ct[0][0]),self.get_int(ct[0][1])))\n    for c in ct[1:]:\n      cmd = \"X{}Y{}D01*\".format(self.get_int(c[0]),self.get_int(c[1]))\n      self.out_write(cmd)\n    self.out_write(\"G37*\")\n\n  def DrawMRSTUB(self,ri,ro,alpha,x0,y0,phi):\n    # Calculate the paramters\n    W = ri\n    alpha_rad = alpha*pi/180.0\n    l = W/(2*tan(alpha_rad/2))\n    # Generate the relative points\n    A = [0,W/2.0]\n    B = [ro*cos(alpha_rad/2)-l,ro*sin(alpha_rad/2)]\n    C = [ro*cos(alpha_rad/2)-l,-ro*sin(alpha_rad/2)]\n    D = [0,-W/2.0]\n    offset = array([-l,0])\n    corners = [A,B,C,D,offset]\n    # Rotate into the real coordinates\n    rot_rad = -phi*pi/180.0\n    R = array([[cos(rot_rad),sin(rot_rad)],[-sin(rot_rad),cos(rot_rad)]])  # rotation matrix\n    ct = dot(R,array(corners).transpose()).transpose()\n    for i in range(len(ct)):\n      ct[i][0] = ct[i][0] + x0\n      ct[i][1] = ct[i][1] + y0\n    ct[4] = ct[4] - ct[1] # This makes the arc come out correctly in the gerber file\n    # Initialize\n    # write the output\n    self.out_write(\"G54D11*\")  \n    self.out_write(\"G36*\")  \n    self.out_write(\"X{}Y{}D02*\".format(self.get_int(ct[0][0]),self.get_int(ct[0][1])))\n    self.out_write(\"X{}Y{}D01*\".format(self.get_int(ct[1][0]),self.get_int(ct[1][1])))\n    self.out_write(\"G75*\")  # Multiquadrant\n    self.out_write(\"G02*\")  # Clockwise circular interpolation\n    # Do the rotation\n    self.out_write(\"X{}Y{}I{}J{}D01*\".format(self.get_int(ct[2][0]),self.get_int(ct[2][1]),\n      self.get_int(ct[4][0]),self.get_int(ct[4][1])))\n    self.out_write(\"G01*\")  # Linear interpolation\n    self.out_write(\"X{}Y{}D01*\".format(self.get_int(ct[2][0]),self.get_int(ct[2][1])))\n    self.out_write(\"X{}Y{}D01*\".format(self.get_int(ct[3][0]),self.get_int(ct[3][1])))\n    self.out_write(\"X{}Y{}D01*\".format(self.get_int(ct[0][0]),self.get_int(ct[0][1])))\n    self.out_write(\"G37*\")\n    \n  # ----------------------------------------\n  # Functions for QUCS Netlist Parsing\n  # ----------------------------------------\n  \n  def ReadNetlist(self,netlist_fn):\n    self.netlist_fn = netlist_fn\n    try:\n      fh = open(netlist_fn,'r')\n      self.netlist_data = fh.read()\n      fh.close()\n    except:\n      self.fprint(\"Error: Could not read netlist file: \" + netlist_fn,force=True)\n  \n  def GetParameter(self,line,param):\n    try:\n      param_list = line.split(\" \")\n      for a in param_list:\n        if (param + \"=\") in a:\n          return a.replace(param + \"=\",\"\").replace(\"'\",\"\").replace('\"','')\n    except:\n      self.fprint(\"Error: Could not find paramter: \" + str(param),force=True)\n      return False\n  \n  def RemoveSpaces(self,line):\n    return line.replace(\" mm\",\"mm\").replace(\" mil\",\"mil\")\n  \n  def GetLength(self,length_str):\n    if \"mm\" in length_str:\n      return float(length_str.replace(\"mm\",\"\"))*0.0393701/self.unit_scale\n    elif \"mil\" in length_str:\n      return float(length_str.replace(\"mil\",\"\"))*0.001/self.unit_scale\n    else:\n      try:\n        return float(length_str)\n      except:\n        self.fprint(\"Error: Unknown length unit! {}\".format(length_str),force=True)\n  \n  def ParseNetlist(self):\n    net_list = []\n    elements = []\n    lines = self.netlist_data.split(\"\\n\")\n    for l in lines:\n      l = self.RemoveSpaces(l)\n      if \"MLIN\" in l:\n        # MLIN:MLIN1 _net0 _net2 Subst=\"Subst1\" W=\"1 mm\" L=\"10 mm\" Model=\"Hammerstad\" DispModel=\"Kirschning\" Temp=\"26.85\"\n        self.fprint(\"Found element: \" + l)\n        # Get parameters\n        W = self.GetLength(self.GetParameter(l,\"W\"))\n        L = self.GetLength(self.GetParameter(l,\"L\"))\n        # Get nodes\n        l = l.replace(\"MLIN:\",\"\").strip().split(\" \")\n        if l[1] not in net_list:\n          net_list.append(l[1])\n        if l[2] not in net_list:\n          net_list.append(l[2])\n        elements.append([\"MLIN\",l[0],l[1],l[2],W,L])\n      elif \"MTEE\" in l:\n        # MTEE:MS3 _net3 _net4 _net5 Subst=\"Subst1\" W1=\"1 mm\" W2=\"1 mm\" W3=\"2 mm\" MSModel=\"Hammerstad\" MSDispModel=\"Kirschning\" Temp=\"26.85\"\n        self.fprint(\"Found element: \" + l)\n        # Get parameters\n        W1 = self.GetLength(self.GetParameter(l,\"W1\"))\n        W2 = self.GetLength(self.GetParameter(l,\"W2\"))\n        W3 = self.GetLength(self.GetParameter(l,\"W3\"))\n        # Get nodes\n        l = l.replace(\"MTEE:\",\"\").strip().split(\" \")\n        if l[1] not in net_list:\n          net_list.append(l[1])\n        if l[2] not in net_list:\n          net_list.append(l[2])\n        if l[3] not in net_list:\n          net_list.append(l[3])\n        elements.append([\"MTEE\",l[0],l[1],l[2],l[3],W1,W2,W3])\n      elif \"MCORN\" in l:\n        # MCORN:MS4 _net6 _net7 Subst=\"Subst1\" W=\"1 mm\"\n        self.fprint(\"Found element: \" + l)\n        # Get parameters\n        W = self.GetLength(self.GetParameter(l,\"W\"))\n        # Get nodes\n        l = l.replace(\"MCORN:\",\"\").strip().split(\" \")\n        if l[1] not in net_list:\n          net_list.append(l[1])\n        if l[2] not in net_list:\n          net_list.append(l[2])\n        elements.append([\"MCORN\",l[0],l[1],l[2],W])\n      elif \"MTAPER\" in l:\n        pass\n      elif \"MMBEND\" in l:\n        # MMBEND:MS5 _net8 _net9 Subst=\"Subst1\" W=\"1 mm\"\n        self.fprint(\"Found element: \" + l)\n        # Get parameters\n        W = self.GetLength(self.GetParameter(l,\"W\"))\n        # Get nodes\n        l = l.replace(\"MMBEND:\",\"\").strip().split(\" \")\n        if l[1] not in net_list:\n          net_list.append(l[1])\n        if l[2] not in net_list:\n          net_list.append(l[2])\n        elements.append([\"MMBEND\",l[0],l[1],l[2],W])\n      elif \"MSTEP\" in l:\n        # MSTEP:MS6 _net10 _net11 Subst=\"Subst1\" W1=\"2 mm\" W2=\"1 mm\" MSModel=\"Hammerstad\" MSDispModel=\"Kirschning\"\n        self.fprint(\"Found element: \" + l)\n        # Get parameters\n        W1 = self.GetLength(self.GetParameter(l,\"W1\"))\n        W2 = self.GetLength(self.GetParameter(l,\"W2\"))\n        # Get nodes\n        l = l.replace(\"MSTEP:\",\"\").strip().split(\" \")\n        if l[1] not in net_list:\n          net_list.append(l[1])\n        if l[2] not in net_list:\n          net_list.append(l[2])\n        elements.append([\"MSTEP\",l[0],l[1],l[2],W1,W2])\n      elif \"MSLIT\" in l:\n        pass\n      elif \"MGAP\" in l:\n        # MGAP:MS9 _net16 _net17 Subst=\"Subst1\" W1=\"1 mm\" W2=\"1 mm\" S=\"1 mm\" MSModel=\"Hammerstad\" MSDispModel=\"Kirschning\"\n        self.fprint(\"Found element: \" + l)\n        # Get parameters\n        W1 = self.GetLength(self.GetParameter(l,\"W1\"))\n        W2 = self.GetLength(self.GetParameter(l,\"W2\"))\n        S  = self.GetLength(self.GetParameter(l,\"S\"))\n        # Get nodes\n        l = l.replace(\"MGAP:\",\"\").strip().split(\" \")\n        if l[1] not in net_list:\n          net_list.append(l[1])\n        if l[2] not in net_list:\n          net_list.append(l[2])\n        elements.append([\"MGAP\",l[0],l[1],l[2],W1,W2,S])\n      elif \"MCURVE\" in l:\n        pass\n      elif \"MCURVE2\" in l:\n        pass\n      elif \"MRSTUB\" in l:\n        # MRSTUB:MS10 _net18 Subst=\"Subst1\" ri=\"1 mm\" ro=\"10 mm\" alpha=\"90\"\n        self.fprint(\"Found element: \" + l)\n        # Get parameters\n        ri = self.GetLength(self.GetParameter(l,\"ri\"))\n        ro = self.GetLength(self.GetParameter(l,\"ro\"))\n        a = self.GetLength(self.GetParameter(l,\"alpha\"))\n        # Get nodes\n        l = l.replace(\"MRSTUB:\",\"\").strip().split(\" \")\n        if l[1] not in net_list:\n          net_list.append(l[1])\n        elements.append([\"MRSTUB\",l[0],l[1],ri,ro,a])\n      elif \"MBSTUB\" in l:\n        pass\n      elif \"MCFIL\" in l:\n        pass\n      elif \"MCOUPLED\" in l:\n        # MCOUPLED:MS5 _net8 _net9 _net7 _net10 Subst=\"Subst1\" W=\"1 mm\" L=\"10 mm\" S=\"1 mm\" Model=\"Kirschning\" DispModel=\"Kirschning\" Temp=\"26.85\"\n        self.fprint(\"Found element: \" + l)\n        # Get parameters\n        W = self.GetLength(self.GetParameter(l,\"W\"))\n        L = self.GetLength(self.GetParameter(l,\"L\"))\n        S  = self.GetLength(self.GetParameter(l,\"S\"))\n        # Get nodes\n        l = l.replace(\"MCOUPLED:\",\"\").strip().split(\" \")\n        if l[1] not in net_list:\n          net_list.append(l[1])\n        if l[2] not in net_list:\n          net_list.append(l[2])\n        if l[3] not in net_list:\n          net_list.append(l[3])\n        if l[4] not in net_list:\n          net_list.append(l[4])\n        elements.append([\"MCOUPLED\",l[0],l[1],l[2],l[3],l[4],W,L,S])\n        pass\n      elif \"MSABND\" in l:\n        pass\n      elif \"MSOBND\" in l:\n        pass\n      elif \"MCROSS\" in l:\n        # MCROSS:MS7 _net12 _net13 _net14 _net15 Subst=\"Subst1\" W1=\"1 mm\" W2=\"2 mm\" W3=\"1 mm\" W4=\"2 mm\" MSModel=\"Hammerstad\" MSDispModel=\"Kirschning\"\n        self.fprint(\"Found element: \" + l)\n        # Get parameters\n        W1 = self.GetLength(self.GetParameter(l,\"W1\"))\n        W2 = self.GetLength(self.GetParameter(l,\"W2\"))\n        W3 = self.GetLength(self.GetParameter(l,\"W3\"))\n        W4 = self.GetLength(self.GetParameter(l,\"W4\"))\n        # Get nodes\n        l = l.replace(\"MCROSS:\",\"\").strip().split(\" \")\n        if l[1] not in net_list:\n          net_list.append(l[1])\n        if l[2] not in net_list:\n          net_list.append(l[2])\n        if l[3] not in net_list:\n          net_list.append(l[3])\n        if l[4] not in net_list:\n          net_list.append(l[4])\n        elements.append([\"MCROSS\",l[0],l[1],l[2],l[3],l[4],W1,W2,W3,W4])\n      elif \"MCROSO\" in l:\n        pass\n      elif \"MSOP\" in l:\n        pass\n      elif \"VIAGND\" in l:\n        pass\n      elif \"VIA2\" in l:\n        pass\n        \n    self.net_list = net_list\n    self.elements = elements\n    self.fprint(\"Net List:\")\n    self.fprint(self.net_list)\n    self.fprint(\"Elements:\")\n    self.fprint(self.elements)\n    \n    # Check the elements and netlist\n    for net in self.net_list:\n      used_cnt = 0\n      used_list = []\n      for e in elements:\n        if net in e:\n          used_cnt = used_cnt + 1\n          used_list.append(e[1])\n      if used_cnt > 2:\n        self.fprint(\"Error: More than 2 components on a net! {} connected to {}\".format(net,used_list),force=True)\n  \n  def GetNetIndex(self,net,element):\n    if net in element:\n      return element.index(net) - 2 # drop first two elements, reference to vector index\n    else:\n      return False\n  \n  def GetVectors(self,element):\n    v = []  # gives [[x,y,phi],...]\n    v.append([0,0,180]) # relative to first node\n    l = element[0]\n    if \"MLIN\" in l:\n      L = element[5]\n      v.append([L,0,0])  # Length in x direction\n    elif \"MTEE\" in l:\n      W1 = element[5]\n      W2 = element[6]\n      W3 = element[7]\n      v.append([W3,0,0])\n      v.append([W3/2,-max(W1,W2)/2.0,-90])\n    elif \"MCORN\" in l:\n      W = element[4]\n      v.append([W/2.0,-W/2.0,-90])  # Length in x direction\n    elif \"MTAPER\" in l:\n      pass\n    elif \"MMBEND\" in l:\n      # elements.append([\"MMBEND\",l[0],l[1],l[2],W])\n      W = element[4]\n      v.append([W/2.0,-W/2.0,-90])  # Length in x direction\n    elif \"MSTEP\" in l:\n      # elements.append([\"MSTEP\",l[0],l[1],l[2],W1,W2])\n      v.append([0,0,0])\n    elif \"MSLIT\" in l:\n      pass\n    elif \"MGAP\" in l:\n      # elements.append([\"MGAP\",l[0],l[1],l[2],W1,W2,S])\n      S = element[6]\n      v.append([S,0,0])  # Length in x direction\n      pass\n    elif \"MCURVE\" in l:\n      pass\n    elif \"MCURVE\" in l:\n      pass\n    elif \"MCURVE2\" in l:\n      pass\n    elif \"MRSTUB\" in l:\n      pass\n    elif \"MBSTUB\" in l:\n      pass\n    elif \"MCFIL\" in l:\n      pass\n    elif \"MCLIN\" in l:\n      pass\n    elif \"MCOUPLED\" in l:\n      # elements.append([\"MCOUPLED\",l[0],l[1],l[2],l[3],l[4],W,L,S])\n      W = element[6]\n      L = element[7]\n      S = element[8]\n      v.append([0,-(W+S),180])\n      v.append([L,-(W+S),0])\n      v.append([L,0,0])\n    elif \"MSABND\" in l:\n      pass\n    elif \"MSOBND\" in l:\n      pass\n    elif \"MCROSS\" in l:\n      # elements.append([\"MCROSS\",l[0],l[1],l[2],l[3],l[4],W1,W2,W3,W4])\n      W1 = element[6]\n      W2 = element[7]\n      W3 = element[8]\n      W4 = element[9]\n      x = max(W4,W2)\n      y = max(W1,W3)\n      v.append([x/2.0,y/2.0,90])\n      v.append([x,0,0])\n      v.append([x/2.0,-y/2.0,-90])\n    elif \"MCROSO\" in l:\n      pass\n    elif \"MSOP\" in l:\n      pass\n    elif \"VIAGND\" in l:\n      pass\n    elif \"VIA2\" in l:\n      pass\n    return array(v)\n  \n  def InSlaveList(self,net=\"\",elem=\"\"):\n    for s in self.slaves:\n      if (net == s[0]) and (elem == s[1]):\n        return True\n    return False\n  \n  # This is the crazy function that actually decides how to route the microstrip lines by finding the coordinates\n  def GetNextCoordinate(self):\n    if len(self.coordinates) < 1:\n      self.coordinates.append([self.elements[0][2],array([0,0,0])])  # Start with first element at the origin\n      self.slaves.append([self.elements[0][2],self.elements[0][1]])\n      return True\n    # Look from the begining\n    for c in self.coordinates:\n      # Check each element\n      for e in self.elements:\n        v = self.GetVectors(e)\n        L = len(v)\n        # Look for new cordinates on this element\n        if c[0] in e:\n          for l in range(L):\n            hit = False\n            for s in self.coordinates:\n              hit = hit or (e[l+2] == s[0])\n            if not hit:\n              # Check if the element is a slave of the coordinate\n              slave = True\n              for s in self.slaves:\n                if (c[0] == s[0]) or (e[1] == s[1]):\n                  slave = False\n              if slave:\n                self.slaves.append([c[0],e[1]])\n              # New coordinate found. Add to list\n              ind0 = self.GetNetIndex(c[0],e)\n              va = v[l][0:2]\n              vb = v[ind0][0:2]\n              alpha = v[l][2]\n              beta  = v[ind0][2]\n              reverse_direction = False\n              if self.InSlaveList(c[0],e[1]):\n                self.fprint(\"{} is master of {}\".format(e[1],e[l+2]))\n                gamma = c[1][2]\n              else:\n                # Special slave case\n                reverse_direction = True\n                self.fprint(\"{} is slave of {}\".format(e[1],e[l+2]))\n                self.slaves.append([e[l+2],e[1]])\n                gamma = c[1][2] -180\n              theta =  180 - beta + gamma\n              rot_rad = theta*pi/180.0\n              R = [[cos(rot_rad),sin(rot_rad)],[-sin(rot_rad),cos(rot_rad)]]  # rotation matrix\n              # rotated coordinates\n              vt = dot(va-vb,R)\n              v_new = array([vt[0],vt[1],0])\n              new_c = v_new + c[1]\n              if reverse_direction:\n                phi = alpha + gamma - beta\n              else:\n                phi = alpha + gamma + 180 - beta\n              while phi > 180.0: \n                phi = phi - 360.0\n              while phi < -180.0: \n                phi = phi + 360.0\n              \n              new_c[2] = phi\n              cor = [e[l+2],new_c]\n              self.fprint(\"New coordinate: {} gives {}\".format(e,cor))\n              self.coordinates.append(cor)\n              return True\n    return False  # No more connections can be found\n\n  def GetElement(self,refdes):\n    for e in self.elements:\n      if refdes == e[1]:\n        return e\n    self.fprintf(\"Error: Could not find element: {}\".format(refdes),force=True)\n    exit()\n\n  def GetCoordinate(self,net):\n    for c in self.coordinates:\n      if net == c[0]:\n        return c\n    self.fprintf(\"Error: Could not find coordinate: {}\".format(net),force=True)\n    return False\n\n  def WriteElement(self,element,x,y,phi):\n    v = self.GetVectors(element)\n    rot_rad = -phi*pi/180.0\n    R = [[cos(rot_rad),sin(rot_rad)],[-sin(rot_rad),cos(rot_rad)]]  # rotation matrix\n    l = element[0]\n    if \"MLIN\" in l:\n      W = element[4]\n      L = element[5]\n      self.DrawRectangleLEO(W,L,x,y,phi)\n    elif \"MTEE\" in l:\n      W1 = element[5]\n      W2 = element[6]\n      W3 = element[7]\n      v21 = dot(R,v[1][0:2])\n      v31 = dot(R,v[2][0:2])\n      #self.fprint(\"MTEE {}: phi = {}, v = {}, v21 = {}, v31 {}\".format(element[1],phi,v,v21,v31))\n      self.DrawRectangleLEO(W1,W3/2.0,x,y,phi)  # Node 1\n      self.DrawRectangleLEO(W2,W3/2.0,x+v21[0],y+v21[1],phi+180)  # Node 2\n      self.DrawRectangleLEO(W3,max(W1,W2)/2.0,x+v31[0],y+v31[1],phi+90) # Node 3\n    elif \"MCORN\" in l:\n      W = element[4]\n      self.DrawRectangleLEO(W,W,x,y,phi)\n    elif \"MTAPER\" in l:\n      pass\n    elif \"MMBEND\" in l:\n      # elements.append([\"MMBEND\",l[0],l[1],l[2],W])\n      W = element[4]\n      corners = [[0,W/2.0],[W,-W/2.0],[0,-W/2]]\n      self.DrawPolygon(corners,x,y,phi)\n      # TODO\n    elif \"MSTEP\" in l:\n      pass  # Draw nothing\n    elif \"MSLIT\" in l:\n      pass\n    elif \"MGAP\" in l:\n      pass\n    elif \"MCURVE\" in l:\n      pass\n    elif \"MCURVE2\" in l:\n      pass\n    elif \"MRSTUB\" in l:\n      # MRSTUB:MS10 _net18 Subst=\"Subst1\" ri=\"1 mm\" ro=\"10 mm\" alpha=\"90\"\n      ri = element[3]\n      ro = element[4]\n      alpha = element[5]\n      self.DrawMRSTUB(ri,ro,alpha,x,y,phi)\n    elif \"MBSTUB\" in l:\n      pass\n    elif \"MCFIL\" in l:\n      pass\n    elif \"MCLIN\" in l:\n      pass\n    elif \"MCOUPLED\" in l:\n      W = element[6]\n      L = element[7]\n      S = element[8]\n      v21 = dot(R,v[1][0:2])\n      self.DrawRectangleLEO(W,L,x,y,phi)\n      self.DrawRectangleLEO(W,L,v21[0]+x,v21[1]+y,phi)\n    elif \"MSABND\" in l:\n      pass\n    elif \"MSOBND\" in l:\n      pass\n    elif \"MCROSS\" in l:\n      # elements.append([\"MCROSS\",l[0],l[1],l[2],l[3],l[4],W1,W2,W3,W4])\n      W1 = element[6]\n      W2 = element[7]\n      W3 = element[8]\n      W4 = element[9]\n      x_m = max(W4,W2)\n      y_m = max(W1,W3)\n      v21 = dot(R,v[1][0:2])\n      v31 = dot(R,v[2][0:2])\n      v41 = dot(R,v[3][0:2])\n      #self.fprint(\"MCROSS {}: phi = {}, v = {}, v21 = {}, v31 = {}, v41 = {}\".format(element[1],phi,v,v21,v31,v41))\n      self.DrawRectangleLEO(W1,x_m/2.0,x,y,phi)  # Node 1\n      self.DrawRectangleLEO(W2,y_m/2.0,x+v21[0],y+v21[1],phi - 90)  # Node 2\n      self.DrawRectangleLEO(W3,x_m/2.0,x+v31[0],y+v31[1],phi +180) # Node 3\n      self.DrawRectangleLEO(W4,y_m/2.0,x+v41[0],y+v41[1],phi + 90) # Node 3\n    elif \"MCROSO\" in l:\n      pass\n    elif \"MSOP\" in l:\n      pass\n    elif \"VIAGND\" in l:\n      pass\n    elif \"VIA2\" in l:\n      pass\n  \n  def GetElementsUsingNet(self,net):\n    connected = []\n    for e in self.elements:\n      L = len(self.GetVectors(e))\n      for l in range(L):\n        if net == e[2+l]:\n          connected.append(e[1])\n          break\n    return connected\n  \n  def GenerateGerberElements(self):\n    self.fprint(\"\\nPlotting all elements with coordinates...\")\n    self.missed = []\n    for e in self.elements:\n      c = self.GetCoordinate(e[2])\n      if c:\n        x = c[1][0]\n        y = c[1][1]\n        phi = c[1][2]\n        # Do final slave check\n        slave = True\n        for s in self.slaves:\n          if (c[0] == s[0]) or (e[1] == s[1]):\n            slave = False\n        if slave:\n          self.slaves.append([c[0],e[1]])\n        # add extra 180 degrees is needed\n        pair_not_in_slave_list = not self.InSlaveList(e[2],e[1])\n        if pair_not_in_slave_list:\n          phi = phi + 180\n        self.WriteElement(e,x,y,phi)\n      else:\n        self.missed.append(e[1])\n        # Report any elements that could not be connected\n    if len(self.missed) > 0:\n      self.fprint(\"Warning: These elements could not be connected! {}\".format(self.missed),force=True)\n\n  def ProcessNetlist(self):\n    self.coordinates = []\n    self.slaves = []\n    self.ParseNetlist()\n    while self.GetNextCoordinate(): pass\n    \n    # Do final slave check, this should add any connected elements missed the first time\n    for e in self.elements:\n      c = self.GetCoordinate(e[2])\n      if c:\n        # Do final slave check\n        slave = True\n        for s in self.slaves:\n          if (c[0] == s[0]) or (e[1] == s[1]):\n            slave = False\n        if slave:\n          self.slaves.append([c[0],e[1]])\n          \n    self.fprint(\"Coordinates: {}\".format(self.coordinates))\n    self.fprint(\"Slaves:      {}\".format(self.slaves))\n    self.GenerateGerberElements()\n  \n    \n  # ----------------------------------------\n  # Main function call\n  # ----------------------------------------\n\n\n  \n", "meta": {"hexsha": "2d13915476e667fbc77b107304a479b412646e26", "size": 25053, "ext": "py", "lang": "Python", "max_stars_repo_path": "qucs2gerber/qucs2gerber.py", "max_stars_repo_name": "rccarroll654/qucs2gerber", "max_stars_repo_head_hexsha": "629894361bc82640d3e28a916b9cfa7a8a84dd73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-22T16:08:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-22T16:08:47.000Z", "max_issues_repo_path": "qucs2gerber/qucs2gerber.py", "max_issues_repo_name": "rccarroll654/qucs2gerber", "max_issues_repo_head_hexsha": "629894361bc82640d3e28a916b9cfa7a8a84dd73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-05-24T07:00:25.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T07:00:25.000Z", "max_forks_repo_path": "qucs2gerber/qucs2gerber.py", "max_forks_repo_name": "rccarroll654/qucs2gerber", "max_forks_repo_head_hexsha": "629894361bc82640d3e28a916b9cfa7a8a84dd73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7641509434, "max_line_length": 149, "alphanum_fraction": 0.5487965513, "include": true, "reason": "from numpy", "num_tokens": 7781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.3007455664065234, "lm_q1q2_score": 0.17824185662094236}}
{"text": "'''code for finding the correct corresponding landmarks given BFI and\nMRI - not run by itself, '''\n\nimport numpy as np\nimport pickle                   # for loading rigid reg affine\n\ndef orig_to_reg(landmark):\n    '''takes a set of original landmarks in original pixel coordinates\n    (i.e. [pixel HR BFI, voxel MRI]) and converts it to\n    [BFI real coords (self reg), voxel real coords]'''\n    pass\n\n\n\ndef get_new_landmarks(block, orig=False):\n    '''returns the landmark corresponance between the blockface\n    imaging and the MRI\n\n    Takes block = {1, 2, 3, 4} argument plus the downsampling (default\n    is 8)'''\n\n    # downsampling doesnt matter because we convert all the landmarks\n    # to real coordinates, so as long as the data has correct spacing\n    # (which depends on the downsampling), we should be fine.  We do\n    # some division by 8 (which is the normally downsampled data), but\n    # thats because the affine registration was done on those images,\n    # so photo_rigid_transformations relies on that grid\n\n    # landmarks matching the high res data from\n    # /home/sci/crottman/korenberg/data/photo/seg_high_res_crop/color/block2\n    # and the MRI data from\n    # /home/sci/crottman/korenberg/results/MRI/brain_seg.mha\n    #\n    # these are the landmarks given to me by Julie\n    #\n    # [pixel HR BFI, voxel MRI]\n    # if block == 1:              # 12\n    #     landmarks = [[[1826.0, 1754.5, 7470], [158.43, 22, 125.21]],\n    #                  [[2238.5, 1716.0, 9780], [179.31, 32, 127.27]],\n    #                  [[1639.0, 1133.0, 11820], [158.54, 37, 89.375]],\n    #                  [[2398.0, 1668.0, 14910], [143.8, 53, 123.2]],\n    #                  [[1994.0, 1492.0, 13110], [127.26, 43, 109.43]],\n    #                  [[2668.0, 2512.0, 15570], [148.53, 56, 171.67]],\n    #                  [[2532.0, 1986.0, 13440], [147.76, 47, 141]],\n    #                  [[2096.0, 1478.0, 14070], [132.05, 47, 108.56]],\n    #                  [[2372.0, 1008.0, 16860], [149.09, 53, 88.092]],\n    #                  [[3193.5, 2241.0, 16710], [177.06, 59, 162.33]],\n    #                  [[2397.0, 2235.0, 12780], [140.32, 46, 152.06]],\n    #                  [[2662.0, 2658.0, 15570], [146.59, 56, 177.68]]\n    #                  ]\n    if block ==1:\n        landmarks = [[[2522.60336538,1315.15771902,6871.10693359],[158.43, 22, 125.21]],\n                     [[2987.42334402,1229.36865652,9881.06542969],[179.31, 32, 127.27]],\n                     [[2438.39059161,577.50814637,12034.25976562],[158.54, 37, 89.375]],\n                     [[2354.12433226,1311.07271635,14710.29980469],[143.8, 53, 123.2]],\n                     [[1906.85867805,1171.23530983,12912.47460938],[127.26, 43, 109.43]],\n                     [[2718.82291667,2143.2850227,15241.23730469],[148.53, 56, 171.67]],\n                     [[2497.11044338,1654.34309896,13280.20605469],[147.76, 47, 141]],\n                     [[2003.25730335,1151.70072115,13824.54931641],[132.05, 47, 108.56]],\n                     [[2298.45469418,629.74238782,16997.55175781],[149.09, 53, 88.092]],\n                     [[3182.02577457,1813.38330495,15916.63476563],[177.06, 59, 162.33]],\n                     [[2393.5100828,1908.59584085,12689.05053711],[140.32, 46, 152.06]],\n                     [[2722.94484509,2282.91720085,15419.27734375],[146.59, 56, 177.68]]]\n\n\n\n\n    elif block == 2:            # 22\n        landmarks = [[[1692.0, 1798.0, 5460], [122.54, 78, 131.64]],\n                     [[1808.0, 788.0, 2940], [138.64, 71, 74.479]],\n                     [[3440.0, 2412.0, 9960], [189.92, 102, 164.8]],\n                     [[1692.0, 1734.0, 5940], [123.53, 80, 128.11]],\n                     [[1764.0, 1830.0, 5850], [126.11, 80, 134.28]],\n                     [[1392.0, 1569.0, 6600], [106.61, 82, 117.43]],\n                     [[1192.0, 2012.0, 10320], [76.206, 91, 126.36]],\n                     [[1800.0, 2410.0, 4200], [127.03, 75, 162.93]],\n                     [[1392.0, 2720.0, 7650], [101.41, 83, 176.69]],\n                     [[712.0, 1640.0, 8190], [73.153, 83, 116.31]],\n                     [[1696.5, 2634.0, 5430], [118.11, 78, 178.81]],\n                     [[1873.5, 2647.5, 11670], [108.84, 100, 167.84]],\n                     [[1885.5, 2374.5, 11430], [109.71, 100, 152.28]],\n                     [[1796.7, 2032.7, 10890], [107.55, 96, 133.46]],\n                     [[1579.5, 1597.5, 11610], [99.954, 98, 106.04]],\n                     [[1258.0, 2050.0, 2310], [101.68, 64, 140.72]],\n                     [[1918.5, 1713.0, 8820], [132.3, 91, 127.57]],\n                     [[1372.5, 2796.0, 6630], [101.52, 79, 182.85]],\n                     [[1282.0, 970.0, 12540], [88.143, 100, 72.372]],\n                     [[1716.0, 1570.0, 6480], [123.78, 82, 127.5]],\n                     [[1790.0, 1818.0, 6360], [127.3, 82, 134.34]],\n                     [[1358.0, 1940.0, 10230], [87.009, 91, 125.07]]\n                     ]\n\n    #### BLAKE NEW ATTEMPT AT LANDMARKS #####\n    # elif block == 2:\n    #     landmarks = [[[1688.0,1704.0,5130],[122.54,78,131.64]],\n    #                  [[1872.0,592.0,3000],[138.64,71,74.479]],\n    #                  [[1696.0,1616.0,5640],[123.53,80,128.11]],\n    #                  [[1744.0,1728.0,5550],[126.11,80,134.28]],\n    #                  [[1424.0,1472.0,6000],[106.61,82,117.43]],\n    #                  [[808.0,1760.0,9810],[76.206,91,126.36]],\n    #                  [[1672.0,2544.0,5220],[118.11,78,178.81]],\n    #                  [[1472.0,2392.0,11670],[108.84,100,167.84]],\n    #                  [[1456.0,2136.0,11190],[109.71,100,152.28]],\n    #                  [[1400.0,1792.0,10410],[107.55,96,133.46]],\n    #                  [[1200.0,1256.0,11340],[99.954,98,106.04]],\n    #                  [[1288.0,1912.0,1890],[101.68,64,140.72]],\n    #                  [[1360.0,2680.0,6390],[101.52,79,182.85]],\n    #                  [[920.0,688.0,11310],[88.143,100,72.372]],\n    #                  [[1704.0,1624.0,6180],[123.78,82,127.5]],\n    #                  [[1760.0,1712.0,6030],[127.3,82,134.34]],\n    #                  [[992.0,1752.0,9720],[87.009,91,125.07]]\n    #                  ]\n\n\n    #######################\n\n    elif block == 3:\n        landmarks = [[[1851.62879357,1991.99500033,3705.06347656],[120.45,118,131.66]],\n                     [[1524.91439637,1126.08987714,3463.581604],[119.84,121,83.647]],\n                     [[2782.59481838,2264.22305689,2796.15209961],[158.59,119,161.38]],\n                     [[901.1676015,1244.17935363,4935.58862305],[87.865,122,76.284]],\n                     [[1909.73646585,1925.96554226,4652.20556641],[123.25,120,130.49]],\n                     [[2609.97662927,2834.66399573,5220.45776367],[141.11,125,187.6]],\n                     [[1471.62680288,1129.20699786,2732.40942383],[116.62,116,84.199]],\n                     [[2762.40110844,2390.66673344,1642.92230225],[154.47,114,169.05]]]\n\n\n\n\n\n\n\n\n\n\n\n\n    # elif block == 3:            # 8\n    #     landmarks = [[[1915.5, 1941.0, 3960], [120.45, 118, 131.66]],\n    #                  [[1566.0, 1114.0, 3660], [119.84, 121, 83.647]],\n    #                  [[2814.0, 2229.0, 2850], [158.59, 119, 161.38]],\n    #                  [[950.0, 1212.0, 4680], [87.865, 122, 76.284]],\n    #                  [[1960.0, 1908.0, 4620], [123.25, 120, 130.49]],\n    #                  [[2804.0, 2600.0, 3570], [141.11, 121, 187.6]],\n    #                  [[1530.0, 1130.0, 2850], [116.62, 116, 84.199]],\n    #                  [[2788.0, 2394.0, 1710], [154.47, 114, 169.05]],\n    #                  ]\n\n\n\n    elif block == 4:            # 20\n        # landmarks = [[[2866.0, 2644.0, 1950], [148.46, 132, 184.62]],\n        #              [[1658.0, 2054.0, 5700], [105.51, 145, 126.21]],\n        #              [[1944.0, 2282.0, 6000], [114.69, 145, 144.58]],\n        #              [[3076.5, 1476.0, 9030], [192.09, 158, 136.95]],\n        #              [[2034.0, 1388.0, 21270], [135.86, 207, 114.8]],\n        #              [[2600.0, 2352.0, 9330], [143.9, 157, 161.09]],\n        #              [[1431.0, 1312.5, 8100], [107.61, 156, 93.076]],\n        #              [[2582.0, 1350.0, 20100], [165.34, 194, 111.29]],\n        #              [[2362.0, 1046.0, 18270], [154.86, 201, 104.98]],\n        #              [[898.0, 2026.0, 13200], [75.349, 179, 116.18]],\n        #              [[2086.0, 1754.0, 1140], [133.67, 128, 125.02]],\n        #              [[2278.5, 2412.0, 1440], [130.17, 128, 154.87]],\n        #              [[1432.0, 1436.0, 6360], [103.74, 150, 96.354]],\n        #              [[2288.0, 2292.0, 7710], [133.86, 151, 146.39]],\n        #              [[1902.0, 1516.0, 13860], [123.94, 180, 115.41]],\n        #              [[1798.0, 2586.0, 15600], [103.14, 178, 162.73]],\n        #              [[2334.0, 1998.0, 8670], [142.76, 156, 135.61]],\n        #              [[1686.0, 2314.0, 3960], [102.09, 138, 140.24]],\n        #              [[1782.0, 1953.0, 4740], [121.03, 141, 139.15]],\n        #              [[1588.0, 784.0, 12330], [125.43, 174, 71.346]],\n        #              ]\n        # these are not reversed:\n        # return [[[-4978.7969255009493, -14291.195548170297, -10974.191228834581], [-49.0, 8.5, -34.7]],\n        #         [[12955.285489863672, 6782.6667541970291, -9608.9022334155761], [-7.2, 8.5, 54.2]],\n        #         [[-3529.4124992429142, -21992.693397096813, 21.610449345362213], [-71.0, 49.5, -37.5]],\n        #         [[1375.0854059966568, -2424.3665112550225, -644.14053162552591], [-19.0, 41.9, 6.5]],\n        #         [[-1904.9849544357239, 19756.728151140465, -9850.3999775772809], [62.5, 14.2, 31.5]],\n        #         [[-19978.084988611834, 1193.8850080611674, -5171.9937461739564], [27.5, 34.7, -46.5]],\n        #         [[4876.4172072069205, 12908.96310608848, 3440.3626957034357], [23.1, 59.2, 35.5]],\n        #         [[9048.4258535122353, -3346.5882992785419, -1034.3280093132544], [-31.4, 38.6, 31.5]],\n        #         [[-18786.106171386909, 4379.237425767692, -11754.583853417926], [30.0, 2.5, -46.9]],\n        #         [[-3987.5298698229044, 1771.7456071262263, -11229.664187291755], [5.5, 2.5, -3.1]],\n        #         [[4053.8534067774444, 18364.900285395477, -9103.886061444251], [47.0, 13.5, 49.5]],\n        #         [[-4253.4490262881664, 1858.4383859028028, -10978.167005247227], [5.9, 2.5, -3.6]],\n        #         [[-4424.9749261128964, -14276.880981292834, -10691.448917965858], [-49.8, 7.5, -31.7]],\n        #         [[-7431.4216598651183, 12080.35048564759, 5666.7585269799256], [44.3, 64.0, -6.5]],\n        #         [[-11750.706201447651, -6425.4834199773559, 2206.6704343840447], [-15.9, 53.8, -37.5]],\n        #         [[-9553.0213692492798, -8271.5033718832747, 9617.0907338800625], [-26.4, 82.5, -30.5]],\n        #         [[5646.7187209368558, -5709.066465405941, 1405.149115939319], [-32.7, 48.5, 18.8]],\n        #         [[-3045.289844922052, -15641.47673776804, 2829.7547401188876], [-48.7, 62.5, -21.5]],\n        #         [[1714.4211894935061, -2015.5792753776332, -1241.3595924584788], [-17.8, 40.5, 9.4]],\n        #         [[9630.4167197410025, 14435.741532626829, 3212.6170714054715], [18.9, 51.5, 58.5]]\n        #     ]\n        # these are properly reversed:\n        return [[[-9305.5569124382746, -926.00166826035411, -1138.4258596439486], [20.6, 44.5, 8.6]],\n                [[5111.9588267015597, 14394.506928486426, 3027.1478194585925], [-19.2, 52.5, -50.8]],\n                [[5319.0894148311518, -5334.2601974636691, 364.14433790943804], [-31.0, 45.5, 17.4]],\n                [[-1540.0662948951845, 9674.0229935199168, 8068.2477026551223], [1.5, 75.5, -27.6]],\n                [[-11142.733858577409, 1.7009214676677402, 7385.7016125897044], [23.9, 75.5, 5.5]],\n                [[6554.2612007950547, 7535.3030659200731, 10931.232554415083], [-31.3, 84.5, -25.4]],\n                [[-4386.1442975165064, 8445.52207500855, 11032.014096545239], [8.4, 85.5, -20.4]],\n                [[14983.7843151907, 687.38589765583129, 1458.8393813034727], [-59.7, 49.5, -11.3]],\n                [[2710.4518412050411, -14587.200900390035, 1278.0350246270846], [-28.6, 48.5, 54.1]],\n                [[11305.014583188564, 12733.418672147429, -12354.181250633284], [-39.3, -3.5, -53.8]],\n                ]\n\n    else:\n        raise Exception(\"invalid block number\")\n\n    if orig:\n        return landmarks\n\n    # Convert to LR landmarks\n    #\n    # landmarks matching the low res 8 data from (w/ numpy x/y)\n    # /home/sci/crottman/korenberg/data/photo/seg_low_res_crop/color/block2\n    # and the MRI data from\n    # /home/sci/crottman/korenberg/results/MRI/brain_seg.mha\n    #\n    for ptpair in landmarks:\n        ptpair[0][0:2] = ptpair[0][-2:-4:-1] # switch x and y\n        ptpair[0][0] /= 8.0\n        ptpair[0][1] /= 8.0\n    f = open(\"photo_rigid_transformations_\" + str(block) + \".pkl\", 'r')\n    Adict = pickle.load(f)\n    f.close()\n    # Transform landmarks by rigid transform from photorigidtransformations\n    for lm in landmarks:\n        if lm[0][2] in Adict.keys():\n            A = Adict[lm[0][2]]\n            origin = Adict['origin']\n            B = np.array(A)\n            # print \"landmark \", i, \"found!!!\"\n            # print \"previous landmark: \", lm[0]\n            # Apply affine transformation to landmark\n            lm[0][0:2] = np.dot(B, [lm[0][0]-origin[0], lm[0][1]-origin[1], 1.0])[0:2]\n            lm[0][0] += origin[0]\n            lm[0][1] += origin[1]\n            # print \"new landmark: \", lm[0], \"\\n\"\n\n            # [block2_reg_blanks pixels, MRI voxels]\n\n            # convert to real coordinates\n            # [block2_reg_blanks Real, MRI voxels]\n\n    # Convert to World Coordinates\n    for lm in landmarks:\n        # the spacing for the HR BFI data is [117, 117, 30]\n        lm[0][0] = lm[0][0]*117\n        lm[0][1] = lm[0][1]*117\n\n    bfspacing = np.array([117, 117, 30])\n    if block == 1:\n        bfsize = np.array([480, 480, 585])\n    elif block == 2:\n        bfsize = np.array([480, 480, 419])\n    elif block == 3:\n        bfsize = np.array([480, 480, 165])\n    elif block == 4:\n        bfsize = np.array([480, 480, 874])\n\n    # origins are center of the block\n    bforigin = -(bfsize-1)/2.0*bfspacing\n    mriorigin = -255.0/2.0*np.array([1.0, 1.0, 1.0])\n\n    for lm in landmarks:\n        lm[0][0] += bforigin[0]\n        lm[0][1] += bforigin[1]\n        lm[0][2] += bforigin[2]\n        lm[1][0] = round(lm[1][0] + mriorigin[0], 2) # just an annoyance :(\n        lm[1][1] = round(lm[1][1] + mriorigin[1], 2)\n        lm[1][2] = round(lm[1][2] + mriorigin[2], 2)\n\n    return landmarks\n", "meta": {"hexsha": "1522f33719fe60c5b8c7b3632bf685932c5e4f48", "size": 14555, "ext": "py", "lang": "Python", "max_stars_repo_path": "BFI_reg_landmarks.py", "max_stars_repo_name": "BlakeZim/working_code", "max_stars_repo_head_hexsha": "ebdd8f6854b9d342a483592c81146d89021d688e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BFI_reg_landmarks.py", "max_issues_repo_name": "BlakeZim/working_code", "max_issues_repo_head_hexsha": "ebdd8f6854b9d342a483592c81146d89021d688e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BFI_reg_landmarks.py", "max_forks_repo_name": "BlakeZim/working_code", "max_forks_repo_head_hexsha": "ebdd8f6854b9d342a483592c81146d89021d688e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.7355072464, "max_line_length": 105, "alphanum_fraction": 0.496461697, "include": true, "reason": "import numpy", "num_tokens": 5719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.17823866349614254}}
{"text": "from typing import Tuple, Optional, List\nimport warnings\nimport ctypes\nimport operator\nfrom functools import reduce\nimport torch\nimport numpy as np\nfrom dqc.hamilton.intor.lcintwrap import LibcintWrapper\nfrom dqc.hamilton.intor.utils import np2ctypes, int2ctypes, CGTO, CPBC, \\\n                                     c_null_ptr\nfrom dqc.hamilton.intor.pbcintor import PBCIntOption, _check_and_set_pbc, \\\n                                        _get_default_options, _get_default_kpts, \\\n                                        _concat_atm_bas_env\nfrom dqc.utils.types import get_complex_dtype\nfrom dqc.utils.pbc import estimate_ovlp_rcut\nfrom dqc.hamilton.intor.lattice import Lattice\nfrom dqc.hamilton.intor.namemgr import IntorNameManager\n\n__all__ = [\"pbcft_int1e\", \"pbcft_overlap\"]\n\n# Fourier transform integrals\ndef pbcft_int1e(shortname: str, wrapper: LibcintWrapper,\n                other: Optional[LibcintWrapper] = None,\n                gvgrid: Optional[torch.Tensor] = None,\n                kpts: Optional[torch.Tensor] = None,\n                options: Optional[PBCIntOption] = None):\n    r\"\"\"\n    Performing the periodic boundary condition (PBC) on 1-electron Fourier\n    Transform integrals, i.e.\n\n    $$\n    \\sum_\\mathbf{T} e^{-i \\mathbf{k}\\cdot\\mathbf{T}} \\int \\exp(-i\\mathbf{G}\\cdot\\mathbf{r})\n    \\phi_i(\\mathbf{r}) \\phi_j(\\mathbf{r}-\\mathbf{T})\\ \\mathrm{d}\\mathbf{r}\n    $$\n\n    Arguments\n    ---------\n    shortname: str\n        The shortname of the integral (i.e. without the prefix `int1e_` or else)\n    wrapper: LibcintWrapper\n        The environment wrapper containing the basis\n    other: Optional[LibcintWrapper]\n        Another environment wrapper containing the basis. This environment\n        must have the same complete environment as `wrapper` (e.g. `other` can be\n        a subset of `wrapper`). If unspecified, then `other = wrapper`.\n    gvgrid: Optional[torch.Tensor]\n        The reciprocal coordinate of $\\mathbf{G}$ with shape `(nggrid, ndim)`.\n        If unspecified, then it is assumed to be all zeros.\n    kpts: Optional[torch.Tensor]\n        k-points where the integration is supposed to be performed. If specified,\n        it should have the shape of `(nkpts, ndim)`. Otherwise, it is assumed\n        to be all zeros.\n    options: Optional[PBCIntOption]\n        The integration options. If unspecified, then just use the default\n        value of `PBCIntOption`.\n\n    Returns\n    -------\n    torch.Tensor\n        A complex tensor representing the 1-electron integral with shape\n        `(nkpts, *ncomp, nwrapper, nother, nggrid)` where `ncomp` is the Cartesian\n        components of the integral, e.g. `\"ipovlp\"` integral will have 3\n        components each for x, y, and z.\n    \"\"\"\n\n    # check and set the default values\n    other1 = _check_and_set_pbc(wrapper, other)\n    options1 = _get_default_options(options)\n    kpts1 = _get_default_kpts(kpts, dtype=wrapper.dtype, device=wrapper.device)\n    gvgrid1 = _get_default_kpts(gvgrid, dtype=wrapper.dtype, device=wrapper.device)\n\n    assert isinstance(wrapper.lattice, Lattice)  # check if wrapper has a lattice\n    return _PBCInt2cFTFunction.apply(\n        *wrapper.params,\n        *wrapper.lattice.params,\n        gvgrid1,\n        kpts1,\n        [wrapper, other1],\n        IntorNameManager(\"int1e\", shortname), options1)\n\n# shortcuts\ndef pbcft_overlap(wrapper: LibcintWrapper,\n                  other: Optional[LibcintWrapper] = None,\n                  gvgrid: Optional[torch.Tensor] = None,\n                  kpts: Optional[torch.Tensor] = None,\n                  options: Optional[PBCIntOption] = None):\n    return pbcft_int1e(\"ovlp\", wrapper, other, gvgrid, kpts, options)\n\n################# torch autograd function wrappers #################\nclass _PBCInt2cFTFunction(torch.autograd.Function):\n    # wrapper class for the periodic boundary condition 2-centre integrals\n    @staticmethod\n    def forward(ctx,  # type: ignore\n                # basis params\n                allcoeffs: torch.Tensor, allalphas: torch.Tensor, allposs: torch.Tensor,\n                # lattice params\n                alattice: torch.Tensor,\n                # other parameters\n                gvgrid: torch.Tensor,\n                kpts: torch.Tensor,\n                # non-tensor parameters\n                wrappers: List[LibcintWrapper], int_nmgr: IntorNameManager,\n                options: PBCIntOption) -> torch.Tensor:\n        # allcoeffs: (ngauss_tot,)\n        # allalphas: (ngauss_tot,)\n        # allposs: (natom, ndim)\n\n        out_tensor = PBCFTIntor(int_nmgr, wrappers, gvgrid, kpts, options).calc()\n        ctx.save_for_backward(allcoeffs, allalphas, allposs, alattice, gvgrid, kpts)\n        ctx.other_info = (wrappers, int_nmgr, options)\n        return out_tensor\n\n    @staticmethod\n    def backward(ctx, grad_out: torch.Tensor) -> Tuple[Optional[torch.Tensor], ...]:  # type: ignore\n        raise NotImplementedError(\"gradients of PBC 2-centre FT integrals are not implemented\")\n\n################# integrator object (direct interface to lib*) #################\nclass PBCFTIntor(object):\n    def __init__(self, int_nmgr: IntorNameManager, wrappers: List[LibcintWrapper],\n                 gvgrid_inp: torch.Tensor, kpts_inp: torch.Tensor, options: PBCIntOption):\n        # This is a class for once integration only\n        # I made a class for refactoring reason because the integrals share\n        # some parameters\n        # No gradients propagated in the methods of this class\n\n        assert len(wrappers) > 0\n        wrapper0 = wrappers[0]\n        kpts_inp_np = kpts_inp.detach().numpy()  # (nk, ndim)\n        GvT = np.asarray(gvgrid_inp.detach().numpy().T, order=\"C\")  # (ng, ndim)\n        opname = int_nmgr.get_ft_intgl_name(wrapper0.spherical)\n        lattice = wrapper0.lattice\n        assert isinstance(lattice, Lattice)\n\n        # get the output's component shape\n        comp_shape = int_nmgr.get_intgl_components_shape()\n        ncomp = reduce(operator.mul, comp_shape, 1)\n\n        # estimate the rcut and the lattice translation vectors\n        coeffs, alphas, _ = wrapper0.params\n        rcut = estimate_ovlp_rcut(options.precision, coeffs, alphas)\n        ls = np.asarray(lattice.get_lattice_ls(rcut=rcut))\n\n        self.int_type = int_nmgr.int_type\n        self.wrappers = wrappers\n        self.GvT = GvT\n        self.kpts_inp_np = kpts_inp_np\n        self.opname = opname\n        self.dtype = wrapper0.dtype\n        self.device = wrapper0.device\n        self.comp_shape = comp_shape\n        self.ncomp = ncomp\n        self.ls = ls\n        self.options = options\n\n        # this class is meant to be used once\n        self.integral_done = False\n\n    def calc(self) -> torch.Tensor:\n        assert not self.integral_done\n        self.integral_done = True\n        if self.int_type == \"int1e\":\n            return self._int2c()\n        else:\n            raise ValueError(\"Unknown integral type: %s\" % self.int_type)\n\n    def _int2c(self) -> torch.Tensor:\n        # 2-centre integral\n        # this function works mostly in numpy\n        # no gradients propagated in this function (and it's OK)\n        # this function mostly replicate the `ft_aopair_kpts` function in pyscf\n        # https://github.com/pyscf/pyscf/blob/master/pyscf/pbc/df/ft_ao.py\n        # https://github.com/pyscf/pyscf/blob/c9aa2be600d75a97410c3203abf35046af8ca615/pyscf/pbc/df/ft_ao.py#L52\n        assert len(self.wrappers) == 2\n\n        # if the ls is too big, it might produce segfault\n        if (self.ls.shape[0] > 1e6):\n            warnings.warn(\"The number of neighbors in the integral is too many, \"\n                          \"it might causes segfault\")\n\n        # libpbc will do in-place shift of the basis of one of the wrappers, so\n        # we need to make a concatenated copy of the wrapper's atm_bas_env\n        atm, bas, env, ao_loc = _concat_atm_bas_env(self.wrappers[0], self.wrappers[1])\n        i0, i1 = self.wrappers[0].shell_idxs\n        j0, j1 = self.wrappers[1].shell_idxs\n        nshls0 = len(self.wrappers[0].parent)\n        shls_slice = (i0, i1, j0 + nshls0, j1 + nshls0)\n\n        # get the lattice translation vectors and the exponential factors\n        expkl = np.asarray(np.exp(1j * np.dot(self.kpts_inp_np, self.ls.T)), order='C')\n\n        # prepare the output\n        nGv = self.GvT.shape[-1]\n        nkpts = len(self.kpts_inp_np)\n        outshape = (nkpts,) + self.comp_shape + tuple(w.nao() for w in self.wrappers) + (nGv,)\n        out = np.empty(outshape, dtype=np.complex128)\n\n        # do the integration\n        cintor = getattr(CGTO(), self.opname)\n        eval_gz = CPBC().GTO_Gv_general\n        fill = CPBC().PBC_ft_fill_ks1\n        drv = CPBC().PBC_ft_latsum_drv\n        p_gxyzT = c_null_ptr()\n        p_mesh = (ctypes.c_int * 3)(0, 0, 0)\n        p_b = (ctypes.c_double * 1)(0)\n        drv(cintor, eval_gz, fill,\n            np2ctypes(out),  # ???\n            int2ctypes(nkpts),\n            int2ctypes(self.ncomp),\n            int2ctypes(len(self.ls)),\n            np2ctypes(self.ls),\n            np2ctypes(expkl),\n            (ctypes.c_int * len(shls_slice))(*shls_slice),\n            np2ctypes(ao_loc),\n            np2ctypes(self.GvT),\n            p_b, p_gxyzT, p_mesh,\n            int2ctypes(nGv),\n            np2ctypes(atm), int2ctypes(len(atm)),\n            np2ctypes(bas), int2ctypes(len(bas)),\n            np2ctypes(env))\n\n        out_tensor = torch.as_tensor(out, dtype=get_complex_dtype(self.dtype),\n                                     device=self.device)\n        return out_tensor\n", "meta": {"hexsha": "f0fa646d9fee1e26849a7e2ecad8f791ba9b6953", "size": 9495, "ext": "py", "lang": "Python", "max_stars_repo_path": "dqc/hamilton/intor/pbcftintor.py", "max_stars_repo_name": "Jaikinator/dqc", "max_stars_repo_head_hexsha": "47c964c7d1323a35f4f69521d40476c41843810e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2021-05-31T17:01:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T19:20:35.000Z", "max_issues_repo_path": "dqc/hamilton/intor/pbcftintor.py", "max_issues_repo_name": "Jaikinator/dqc", "max_issues_repo_head_hexsha": "47c964c7d1323a35f4f69521d40476c41843810e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-09-01T13:39:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T16:45:39.000Z", "max_forks_repo_path": "dqc/hamilton/intor/pbcftintor.py", "max_forks_repo_name": "Jaikinator/dqc", "max_forks_repo_head_hexsha": "47c964c7d1323a35f4f69521d40476c41843810e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-07-16T09:08:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T01:13:54.000Z", "avg_line_length": 42.3883928571, "max_line_length": 112, "alphanum_fraction": 0.6313849394, "include": true, "reason": "import numpy", "num_tokens": 2488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.17823865896696506}}
{"text": "# Copyright 2014-2019 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Samragni Banerjee <samragnibanerjee4@gmail.com>\n#         Alexander Sokolov <alexander.y.sokolov@gmail.com>\n#\n\n'''\nUnrestricted algebraic diagrammatic construction\n'''\n\nimport time\nimport numpy as np\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf.adc import uadc_ao2mo\nfrom pyscf import __config__\n\ndef kernel(adc, nroots=1, guess=None, eris=None, verbose=None):\n\n    adc.method = adc.method.lower()\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n       raise NotImplementedError(adc.method)\n\n    cput0 = (time.clock(), time.time())\n    log = logger.Logger(adc.stdout, adc.verbose)\n    if adc.verbose >= logger.WARN:\n        adc.check_sanity()\n    adc.dump_flags()\n\n    if eris is None:\n        eris = uadc_ao2mo.transform_integrals(adc)\n\n    imds = adc.get_imds(eris)\n    matvec, diag = adc.gen_matvec(imds, eris)\n\n    guess = adc.get_init_guess(nroots, diag, ascending = True)\n\n    E, U = lib.linalg_helper.davidson(matvec, guess, diag, nroots=nroots, verbose=log, max_cycle=adc.max_cycle, max_space=adc.max_space)\n\n    T_a, T_b = adc.get_trans_moments(nroots, eris)\n\n    spec_factors = adc.get_spec_factors(nroots, (T_a,T_b), U)\n\n    if adc.verbose >= logger.INFO:\n        if nroots == 1:\n            logger.info(adc, '%s root %d    Energy (Eh) = %.8f    Energy (eV) = %.8f    Spec factors = %.8f',\n                         adc.method, 0, E, E*27.2114, spec_factors)\n        else : \n            for n, en, pn in zip(range(nroots), E, spec_factors):\n                logger.info(adc, '%s root %d    Energy (Eh) = %.8f    Energy (eV) = %.8f    Spec factors = %.8f',\n                          adc.method, n, en, en*27.2114, pn)\n        log.timer('ADC', *cput0)\n\n    return E, U, spec_factors\n\ndef compute_amplitudes_energy(myadc, eris, verbose=None):\n\n    t1, t2 = myadc.compute_amplitudes(eris)\n    e_corr = myadc.compute_energy(t1, t2, eris)\n\n    return e_corr, t1, t2\n\ndef compute_amplitudes(myadc, eris):\n\n    if myadc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(myadc.method)\n\n    t2_2 = (None,)\n    t1_3 = (None,)\n    nocc_a = myadc._nocc[0]\n    nocc_b = myadc._nocc[1]  \n    nvir_a = myadc._nvir[0] \n    nvir_b = myadc._nvir[1]\n\n    v2e_oovv_a,v2e_oovv_ab,v2e_oovv_b  = eris.oovv\n    v2e_vvvv_a,v2e_vvvv_ab,v2e_vvvv_b  = eris.vvvv\n    v2e_oooo_a,v2e_oooo_ab,v2e_oooo_b  = eris.oooo\n    v2e_voov_a,v2e_voov_ab,v2e_voov_b  = eris.voov\n    v2e_ooov_a,v2e_ooov_ab,v2e_ooov_b  = eris.ooov\n    v2e_vovv_a,v2e_vovv_ab,v2e_vovv_b  = eris.vovv\n    v2e_vvoo_a,v2e_vvoo_ab,v2e_vvoo_b  = eris.vvoo\n    v2e_oovo_a,v2e_oovo_ab,v2e_oovo_b  = eris.oovo\n    v2e_ovov_a,v2e_ovov_ab,v2e_ovov_b  = eris.ovov\n    v2e_vovo_a,v2e_vovo_ab,v2e_vovo_b  = eris.vovo\n    v2e_vvvo_a,v2e_vvvo_ab,v2e_vvvo_b  = eris.vvvo\n    v2e_vvov_a,v2e_vvov_ab,v2e_vvov_b  = eris.vvov\n    v2e_vooo_a,v2e_vooo_ab,v2e_vooo_b  = eris.vooo\n    v2e_ovoo_a,v2e_ovoo_ab,v2e_ovoo_b  = eris.ovoo\n    v2e_ovvv_a,v2e_ovvv_ab,v2e_ovvv_b  = eris.ovvv\n    v2e_oovo_a,v2e_oovo_ab,v2e_oovo_b  = eris.oovo\n    v2e_ovvo_a,v2e_ovvo_ab,v2e_ovvo_b  = eris.ovvo\n\n    e_a = myadc.mo_energy_a\n    e_b = myadc.mo_energy_b\n\n    d_ij_a = e_a[:nocc_a][:,None] + e_a[:nocc_a]\n    d_ij_b = e_b[:nocc_b][:,None] + e_b[:nocc_b]\n    d_ij_ab = e_a[:nocc_a][:,None] + e_b[:nocc_b]\n\n    d_ab_a = e_a[nocc_a:][:,None] + e_a[nocc_a:]\n    d_ab_b = e_b[nocc_b:][:,None] + e_b[nocc_b:]\n    d_ab_ab = e_a[nocc_a:][:,None] + e_b[nocc_b:]\n\n    D2_a = d_ij_a.reshape(-1,1) - d_ab_a.reshape(-1)\n    D2_b = d_ij_b.reshape(-1,1) - d_ab_b.reshape(-1)\n    D2_ab = d_ij_ab.reshape(-1,1) - d_ab_ab.reshape(-1)\n\n    D2_a = D2_a.reshape((nocc_a,nocc_a,nvir_a,nvir_a))\n    D2_b = D2_b.reshape((nocc_b,nocc_b,nvir_b,nvir_b))\n    D2_ab = D2_ab.reshape((nocc_a,nocc_b,nvir_a,nvir_b))\n\n    D1_a = e_a[:nocc_a][:None].reshape(-1,1) - e_a[nocc_a:].reshape(-1)\n    D1_b = e_b[:nocc_b][:None].reshape(-1,1) - e_b[nocc_b:].reshape(-1)\n    D1_a = D1_a.reshape((nocc_a,nvir_a))\n    D1_b = D1_b.reshape((nocc_b,nvir_b))\n\n    # Compute first-order doubles t2 (tijab) \n\n    t2_1_a = v2e_oovv_a/D2_a\n    t2_1_b = v2e_oovv_b/D2_b\n    t2_1_ab = v2e_oovv_ab/D2_ab\n\n    t2_1 = (t2_1_a , t2_1_ab, t2_1_b)\n\n    # Compute second-order singles t1 (tij) \n\n    t1_2_a = 0.5*np.einsum('akcd,ikcd->ia',v2e_vovv_a,t2_1_a)\n    t1_2_a -= 0.5*np.einsum('klic,klac->ia',v2e_ooov_a,t2_1_a)\n    t1_2_a += np.einsum('akcd,ikcd->ia',v2e_vovv_ab,t2_1_ab)\n    t1_2_a -= np.einsum('klic,klac->ia',v2e_ooov_ab,t2_1_ab)\n\n    t1_2_b = 0.5*np.einsum('akcd,ikcd->ia',v2e_vovv_b,t2_1_b)\n    t1_2_b -= 0.5*np.einsum('klic,klac->ia',v2e_ooov_b,t2_1_b)\n    t1_2_b += np.einsum('kadc,kidc->ia',v2e_ovvv_ab,t2_1_ab)\n    t1_2_b -= np.einsum('lkci,lkca->ia',v2e_oovo_ab,t2_1_ab)\n\n    t1_2_a = t1_2_a/D1_a\n    t1_2_b = t1_2_b/D1_b\n\n    t1_2 = (t1_2_a , t1_2_b)\n\n    if (myadc.method == \"adc(2)-x\" or myadc.method == \"adc(3)\"):\n\n    # Compute second-order doubles t2 (tijab) \n\n        temp = t2_1_a.reshape(nocc_a*nocc_a,nvir_a*nvir_a)\n        temp_1 = v2e_vvvv_a[:].reshape(nvir_a*nvir_a,nvir_a*nvir_a)\n        t2_2_a = 0.5*np.dot(temp,temp_1.T).reshape(nocc_a,nocc_a,nvir_a,nvir_a)\n        del temp_1\n        t2_2_a += 0.5*np.einsum('klij,klab->ijab',v2e_oooo_a,t2_1_a,optimize=True)\n \n        temp = np.einsum('bkjc,kica->ijab',v2e_voov_a,t2_1_a,optimize=True)\n        temp_1 = np.einsum('bkjc,ikac->ijab',v2e_voov_ab,t2_1_ab,optimize=True)\n \n        t2_2_a += temp - temp.transpose(1,0,2,3) - temp.transpose(0,1,3,2) + temp.transpose(1,0,3,2)\n        t2_2_a += temp_1 - temp_1.transpose(1,0,2,3) - temp_1.transpose(0,1,3,2) + temp_1.transpose(1,0,3,2)\n \n        temp = t2_1_b.reshape(nocc_b*nocc_b,nvir_b*nvir_b)\n        temp_1 = v2e_vvvv_b[:].reshape(nvir_b*nvir_b,nvir_b*nvir_b)\n        t2_2_b = 0.5*np.dot(temp,temp_1.T).reshape(nocc_b,nocc_b,nvir_b,nvir_b)\n        del temp_1\n        t2_2_b += 0.5*np.einsum('klij,klab->ijab',v2e_oooo_b,t2_1_b,optimize=True)\n \n        temp = np.einsum('bkjc,kica->ijab',v2e_voov_b,t2_1_b,optimize=True)\n        temp_1 = np.einsum('kbcj,kica->ijab',v2e_ovvo_ab,t2_1_ab,optimize=True)\n \n        t2_2_b += temp - temp.transpose(1,0,2,3) - temp.transpose(0,1,3,2) + temp.transpose(1,0,3,2)\n        t2_2_b += temp_1 - temp_1.transpose(1,0,2,3) - temp_1.transpose(0,1,3,2) + temp_1.transpose(1,0,3,2)\n \n        temp = t2_1_ab.reshape(nocc_a*nocc_b,nvir_a*nvir_b)\n        temp_1 = v2e_vvvv_ab[:].reshape(nvir_a*nvir_b,nvir_a*nvir_b)\n        t2_2_ab = np.dot(temp,temp_1.T).reshape(nocc_a,nocc_b,nvir_a,nvir_b)\n        del temp_1\n        t2_2_ab += np.einsum('klij,klab->ijab',v2e_oooo_ab,t2_1_ab,optimize=True)\n        t2_2_ab += np.einsum('kbcj,kica->ijab',v2e_ovvo_ab,t2_1_a,optimize=True)\n        t2_2_ab += np.einsum('bkjc,ikac->ijab',v2e_voov_b,t2_1_ab,optimize=True)\n        t2_2_ab -= np.einsum('kbic,kjac->ijab',v2e_ovov_ab,t2_1_ab,optimize=True)\n        t2_2_ab -= np.einsum('akcj,ikcb->ijab',v2e_vovo_ab,t2_1_ab,optimize=True)\n        t2_2_ab += np.einsum('akic,kjcb->ijab',v2e_voov_ab,t2_1_b,optimize=True)\n        t2_2_ab += np.einsum('akic,kjcb->ijab',v2e_voov_a,t2_1_ab,optimize=True)\n \n        t2_2_a = t2_2_a/D2_a\n        t2_2_b = t2_2_b/D2_b\n        t2_2_ab = t2_2_ab/D2_ab\n \n        t2_2 = (t2_2_a , t2_2_ab, t2_2_b)\n\n    if (myadc.method == \"adc(3)\"):\n    # Compute third-order singles (tij)\n\n        t1_3_a = np.einsum('d,ilad,ld->ia',e_a[nocc_a:],t2_1_a,t1_2_a,optimize=True)\n        t1_3_a += np.einsum('d,ilad,ld->ia',e_b[nocc_b:],t2_1_ab,t1_2_b,optimize=True)\n \n        t1_3_b  = np.einsum('d,ilad,ld->ia',e_b[nocc_b:],t2_1_b, t1_2_b,optimize=True)\n        t1_3_b += np.einsum('d,lida,ld->ia',e_a[nocc_a:],t2_1_ab,t1_2_a,optimize=True)\n \n        t1_3_a -= np.einsum('l,ilad,ld->ia',e_a[:nocc_a],t2_1_a, t1_2_a,optimize=True)\n        t1_3_a -= np.einsum('l,ilad,ld->ia',e_b[:nocc_b],t2_1_ab,t1_2_b,optimize=True)\n \n        t1_3_b -= np.einsum('l,ilad,ld->ia',e_b[:nocc_b],t2_1_b, t1_2_b,optimize=True)\n        t1_3_b -= np.einsum('l,lida,ld->ia',e_a[:nocc_a],t2_1_ab,t1_2_a,optimize=True)\n \n        t1_3_a += 0.5*np.einsum('a,ilad,ld->ia',e_a[nocc_a:],t2_1_a, t1_2_a,optimize=True)\n        t1_3_a += 0.5*np.einsum('a,ilad,ld->ia',e_a[nocc_a:],t2_1_ab,t1_2_b,optimize=True)\n \n        t1_3_b += 0.5*np.einsum('a,ilad,ld->ia',e_b[nocc_b:],t2_1_b, t1_2_b,optimize=True)\n        t1_3_b += 0.5*np.einsum('a,lida,ld->ia',e_b[nocc_b:],t2_1_ab,t1_2_a,optimize=True)\n \n        t1_3_a -= 0.5*np.einsum('i,ilad,ld->ia',e_a[:nocc_a],t2_1_a, t1_2_a,optimize=True)\n        t1_3_a -= 0.5*np.einsum('i,ilad,ld->ia',e_a[:nocc_a],t2_1_ab,t1_2_b,optimize=True)\n \n        t1_3_b -= 0.5*np.einsum('i,ilad,ld->ia',e_b[:nocc_b],t2_1_b, t1_2_b,optimize=True)\n        t1_3_b -= 0.5*np.einsum('i,lida,ld->ia',e_b[:nocc_b],t2_1_ab,t1_2_a,optimize=True)\n \n        t1_3_a += np.einsum('ld,adil->ia',t1_2_a,v2e_vvoo_a ,optimize=True)\n        t1_3_a += np.einsum('ld,adil->ia',t1_2_b,v2e_vvoo_ab,optimize=True)\n \n        t1_3_b += np.einsum('ld,adil->ia',t1_2_b,v2e_vvoo_b ,optimize=True)\n        t1_3_b += np.einsum('ld,dali->ia',t1_2_a,v2e_vvoo_ab,optimize=True)\n \n        t1_3_a += np.einsum('ld,alid->ia',t1_2_a,v2e_voov_a ,optimize=True)\n        t1_3_a += np.einsum('ld,alid->ia',t1_2_b,v2e_voov_ab,optimize=True)\n \n        t1_3_b += np.einsum('ld,alid->ia',t1_2_b,v2e_voov_b ,optimize=True)\n        t1_3_b += np.einsum('ld,ladi->ia',t1_2_a,v2e_ovvo_ab,optimize=True)\n \n        t1_3_a -= 0.5*np.einsum('lmad,lmid->ia',t2_2_a,v2e_ooov_a,optimize=True)\n        t1_3_a -=     np.einsum('lmad,lmid->ia',t2_2_ab,v2e_ooov_ab,optimize=True)\n \n        t1_3_b -= 0.5*np.einsum('lmad,lmid->ia',t2_2_b,v2e_ooov_b,optimize=True)\n        t1_3_b -=     np.einsum('mlda,mldi->ia',t2_2_ab,v2e_oovo_ab,optimize=True)\n \n        t1_3_a += 0.5*np.einsum('ilde,alde->ia',t2_2_a,v2e_vovv_a,optimize=True)\n        t1_3_a += np.einsum('ilde,alde->ia',t2_2_ab,v2e_vovv_ab,optimize=True)\n \n        t1_3_b += 0.5*np.einsum('ilde,alde->ia',t2_2_b,v2e_vovv_b,optimize=True)\n        t1_3_b += np.einsum('lied,laed->ia',t2_2_ab,v2e_ovvv_ab,optimize=True)\n \n        t1_3_a -= np.einsum('ildf,aefm,lmde->ia',t2_1_a,v2e_vvvo_a,  t2_1_a ,optimize=True)\n        t1_3_a += np.einsum('ilfd,aefm,mled->ia',t2_1_ab,v2e_vvvo_a, t2_1_ab,optimize=True)\n        t1_3_a -= np.einsum('ildf,aefm,lmde->ia',t2_1_a,v2e_vvvo_ab, t2_1_ab,optimize=True)\n        t1_3_a += np.einsum('ilfd,aefm,lmde->ia',t2_1_ab,v2e_vvvo_ab,t2_1_b ,optimize=True)\n        t1_3_a -= np.einsum('ildf,aemf,mlde->ia',t2_1_ab,v2e_vvov_ab,t2_1_ab,optimize=True)\n \n        t1_3_b -= np.einsum('ildf,aefm,lmde->ia',t2_1_b,v2e_vvvo_b,t2_1_b,optimize=True)\n        t1_3_b += np.einsum('lidf,aefm,lmde->ia',t2_1_ab,v2e_vvvo_b,t2_1_ab,optimize=True)\n        t1_3_b -= np.einsum('ildf,eamf,mled->ia',t2_1_b,v2e_vvov_ab,t2_1_ab,optimize=True)\n        t1_3_b += np.einsum('lidf,eamf,lmde->ia',t2_1_ab,v2e_vvov_ab,t2_1_a,optimize=True)\n        t1_3_b -= np.einsum('lifd,eafm,lmed->ia',t2_1_ab,v2e_vvvo_ab,t2_1_ab,optimize=True)\n \n        t1_3_a += 0.5*np.einsum('ilaf,defm,lmde->ia',t2_1_a,v2e_vvvo_a,t2_1_a,optimize=True)\n        t1_3_a += 0.5*np.einsum('ilaf,defm,lmde->ia',t2_1_ab,v2e_vvvo_b,t2_1_b,optimize=True)\n        t1_3_a += np.einsum('ilaf,edmf,mled->ia',t2_1_ab,v2e_vvov_ab,t2_1_ab,optimize=True)\n        t1_3_a += np.einsum('ilaf,defm,lmde->ia',t2_1_a,v2e_vvvo_ab,t2_1_ab,optimize=True)\n \n        t1_3_b += 0.5*np.einsum('ilaf,defm,lmde->ia',t2_1_b,v2e_vvvo_b,t2_1_b,optimize=True)\n        t1_3_b += 0.5*np.einsum('lifa,defm,lmde->ia',t2_1_ab,v2e_vvvo_a,t2_1_a,optimize=True)\n        t1_3_b += np.einsum('lifa,defm,lmde->ia',t2_1_ab,v2e_vvvo_ab,t2_1_ab,optimize=True)\n        t1_3_b += np.einsum('ilaf,edmf,mled->ia',t2_1_b,v2e_vvov_ab,t2_1_ab,optimize=True)\n \n        t1_3_a += 0.25*np.einsum('inde,anlm,lmde->ia',t2_1_a,v2e_vooo_a,t2_1_a,optimize=True)\n        t1_3_a += np.einsum('inde,anlm,lmde->ia',t2_1_ab,v2e_vooo_ab,t2_1_ab,optimize=True)\n \n        t1_3_b += 0.25*np.einsum('inde,anlm,lmde->ia',t2_1_b,v2e_vooo_b,t2_1_b,optimize=True)\n        t1_3_b += np.einsum('nied,naml,mled->ia',t2_1_ab,v2e_ovoo_ab,t2_1_ab,optimize=True)\n \n        t1_3_a += 0.5*np.einsum('inad,enlm,lmde->ia',t2_1_a,v2e_vooo_a,t2_1_a,optimize=True)\n        t1_3_a -= 0.5 * np.einsum('inad,neml,mlde->ia',t2_1_a,v2e_ovoo_ab,t2_1_ab,optimize=True)\n        t1_3_a -= 0.5 * np.einsum('inad,nelm,lmde->ia',t2_1_a,v2e_ovoo_ab,t2_1_ab,optimize=True)\n        t1_3_a -= 0.5 *np.einsum('inad,enlm,lmed->ia',t2_1_ab,v2e_vooo_ab,t2_1_ab,optimize=True)\n        t1_3_a -= 0.5*np.einsum('inad,enml,mled->ia',t2_1_ab,v2e_vooo_ab,t2_1_ab,optimize=True)\n        t1_3_a += 0.5*np.einsum('inad,enlm,lmde->ia',t2_1_ab,v2e_vooo_b,t2_1_b,optimize=True)\n \n        t1_3_b += 0.5*np.einsum('inad,enlm,lmde->ia',t2_1_b,v2e_vooo_b,t2_1_b,optimize=True)\n        t1_3_b -= 0.5 * np.einsum('inad,enml,mled->ia',t2_1_b,v2e_vooo_ab,t2_1_ab,optimize=True)\n        t1_3_b -= 0.5 * np.einsum('inad,enlm,lmed->ia',t2_1_b,v2e_vooo_ab,t2_1_ab,optimize=True)\n        t1_3_b -= 0.5 *np.einsum('nida,nelm,lmde->ia',t2_1_ab,v2e_ovoo_ab,t2_1_ab,optimize=True)\n        t1_3_b -= 0.5*np.einsum('nida,neml,mlde->ia',t2_1_ab,v2e_ovoo_ab,t2_1_ab,optimize=True)\n        t1_3_b += 0.5*np.einsum('nida,enlm,lmde->ia',t2_1_ab,v2e_vooo_a,t2_1_a,optimize=True)\n \n        t1_3_a -= 0.5*np.einsum('lnde,amin,lmde->ia',t2_1_a,v2e_vooo_a,t2_1_a,optimize=True)\n        t1_3_a -= np.einsum('nled,amin,mled->ia',t2_1_ab,v2e_vooo_a,t2_1_ab,optimize=True)\n        t1_3_a -= 0.5*np.einsum('lnde,amin,lmde->ia',t2_1_b,v2e_vooo_ab,t2_1_b,optimize=True)\n        t1_3_a -= np.einsum('lnde,amin,lmde->ia',t2_1_ab,v2e_vooo_ab,t2_1_ab,optimize=True)\n \n        t1_3_b -= 0.5*np.einsum('lnde,amin,lmde->ia',t2_1_b,v2e_vooo_b,t2_1_b,optimize=True)\n        t1_3_b -= np.einsum('lnde,amin,lmde->ia',t2_1_ab,v2e_vooo_b,t2_1_ab,optimize=True)\n        t1_3_b -= 0.5*np.einsum('lnde,mani,lmde->ia',t2_1_a,v2e_ovoo_ab,t2_1_a,optimize=True)\n        t1_3_b -= np.einsum('nled,mani,mled->ia',t2_1_ab,v2e_ovoo_ab,t2_1_ab,optimize=True)\n \n        t1_3_a += 0.5*np.einsum('lmdf,afie,lmde->ia',t2_1_a,v2e_vvov_a,t2_1_a,optimize=True)\n        t1_3_a += np.einsum('mlfd,afie,mled->ia',t2_1_ab,v2e_vvov_a,t2_1_ab,optimize=True)\n        t1_3_a += 0.5*np.einsum('lmdf,afie,lmde->ia',t2_1_b,v2e_vvov_ab,t2_1_b,optimize=True)\n        t1_3_a += np.einsum('lmdf,afie,lmde->ia',t2_1_ab,v2e_vvov_ab,t2_1_ab,optimize=True)\n \n        t1_3_b += 0.5*np.einsum('lmdf,afie,lmde->ia',t2_1_b,v2e_vvov_b,t2_1_b,optimize=True)\n        t1_3_b += np.einsum('lmdf,afie,lmde->ia',t2_1_ab,v2e_vvov_b,t2_1_ab,optimize=True)\n        t1_3_b += 0.5*np.einsum('lmdf,faei,lmde->ia',t2_1_a,v2e_vvvo_ab,t2_1_a,optimize=True)\n        t1_3_b += np.einsum('mlfd,faei,mled->ia',t2_1_ab,v2e_vvvo_ab,t2_1_ab,optimize=True)\n \n        t1_3_a -= np.einsum('lnde,emin,lmad->ia',t2_1_a,v2e_vooo_a,t2_1_a,optimize=True)\n        t1_3_a += np.einsum('lnde,mein,lmad->ia',t2_1_ab,v2e_ovoo_ab,t2_1_a,optimize=True)\n        t1_3_a += np.einsum('nled,emin,mlad->ia',t2_1_ab,v2e_vooo_a,t2_1_ab,optimize=True)\n        t1_3_a += np.einsum('lned,emin,lmad->ia',t2_1_ab,v2e_vooo_ab,t2_1_ab,optimize=True)\n        t1_3_a -= np.einsum('lnde,mein,mlad->ia',t2_1_b,v2e_ovoo_ab,t2_1_ab,optimize=True)\n \n        t1_3_b -= np.einsum('lnde,emin,lmad->ia',t2_1_b,v2e_vooo_b,t2_1_b,optimize=True)\n        t1_3_b += np.einsum('nled,emni,lmad->ia',t2_1_ab,v2e_vooo_ab,t2_1_b,optimize=True)\n        t1_3_b += np.einsum('lnde,emin,lmda->ia',t2_1_ab,v2e_vooo_b,t2_1_ab,optimize=True)\n        t1_3_b += np.einsum('nlde,meni,mlda->ia',t2_1_ab,v2e_ovoo_ab,t2_1_ab,optimize=True)\n        t1_3_b -= np.einsum('lnde,emni,lmda->ia',t2_1_a,v2e_vooo_ab,t2_1_ab,optimize=True)\n \n        t1_3_a -= 0.25*np.einsum('lmef,efid,lmad->ia',t2_1_a,v2e_vvov_a,t2_1_a,optimize=True)\n        t1_3_a -= np.einsum('lmef,efid,lmad->ia',t2_1_ab,v2e_vvov_ab,t2_1_ab,optimize=True)\n \n        t1_3_b -= 0.25*np.einsum('lmef,efid,lmad->ia',t2_1_b,v2e_vvov_b,t2_1_b,optimize=True)\n        temp = t2_1_ab.reshape(nocc_a*nocc_b,-1)\n        temp_1 = v2e_vvvo_ab[:].reshape(nvir_a*nvir_b,-1)\n        temp_2 = t2_1_ab.reshape(nocc_a*nocc_b*nvir_a,-1)\n        int_1 = np.dot(temp,temp_1).reshape(nocc_a*nocc_b*nvir_a,-1)\n        t1_3_b -= np.dot(int_1.T,temp_2).reshape(nocc_b,nvir_b)\n        del temp_1\n        t1_3_a = t1_3_a/D1_a\n        t1_3_b = t1_3_b/D1_b\n \n        t1_3 = (t1_3_a, t1_3_b)\n\n    t1 = (t1_2, t1_3)\n    t2 = (t2_1, t2_2)\n\n    return t1, t2\n\ndef compute_energy(myadc, t1, t2, eris):\n\n    if myadc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(myadc.method)\n\n    v2e_oovv_a, v2e_oovv_ab, v2e_oovv_b = eris.oovv\n\n    t2_1_a, t2_1_ab, t2_1_b  = t2[0]\n\n    #Compute MP2 correlation energy\n\n    e_mp2 = 0.25 * np.einsum('ijab,ijab', t2_1_a, v2e_oovv_a)\n    e_mp2 += np.einsum('ijab,ijab', t2_1_ab, v2e_oovv_ab)\n    e_mp2 += 0.25 * np.einsum('ijab,ijab', t2_1_b, v2e_oovv_b)\n    \n    e_corr = e_mp2 \n\n    if (myadc.method == \"adc(3)\"):\n\n        #Compute MP3 correlation energy\n\n        v2e_oooo_a, v2e_oooo_ab, v2e_oooo_b = eris.oooo\n        v2e_vvvv_a, v2e_vvvv_ab, v2e_vvvv_b = eris.vvvv\n        v2e_voov_a, v2e_voov_ab, v2e_voov_b = eris.voov\n        v2e_ovvo_a, v2e_ovvo_ab, v2e_ovvo_b = eris.ovvo\n        v2e_ovov_a, v2e_ovov_ab, v2e_ovov_b = eris.ovov\n        v2e_vovo_a, v2e_vovo_ab, v2e_vovo_b = eris.vovo\n\n        temp_1_a =  np.einsum('ijab,ijcd', t2_1_a, t2_1_a)\n        temp_1_b =  np.einsum('ijab,ijcd', t2_1_b, t2_1_b)\n        temp_1_ab_1 =  np.einsum('ijab,ijcd', t2_1_ab, t2_1_ab)\n\n        temp_2_a =  np.einsum('ijab,klab', t2_1_a, t2_1_a)\n        temp_2_b =  np.einsum('ijab,klab', t2_1_b, t2_1_b)\n        temp_2_ab_1 =  np.einsum('ijab,klab', t2_1_ab, t2_1_ab)\n\n        temp_3_a = np.einsum('ijab,ikcb->akcj', t2_1_a, t2_1_a)\n        temp_3_a += np.einsum('jiab,kicb->akcj', t2_1_ab, t2_1_ab)\n        temp_3_b = np.einsum('ijab,ikcb->akcj', t2_1_b, t2_1_b)\n        temp_3_b += np.einsum('ijba,ikbc->akcj', t2_1_ab, t2_1_ab)\n\n        temp_3_ab_1 = np.einsum('ijab,ikcb->akcj', t2_1_ab, t2_1_ab)\n        temp_3_ab_2 = np.einsum('jiba,kibc->akcj', t2_1_ab, t2_1_ab)\n        temp_3_ab_3 = -np.einsum('ijab,ikbc->akcj', t2_1_a, t2_1_ab)\n        temp_3_ab_3 -= np.einsum('jiab,ikcb->akcj', t2_1_ab, t2_1_b)\n        temp_3_ab_4 = -np.einsum('ijba,ikcb->akcj', t2_1_ab, t2_1_a)\n        temp_3_ab_4 -= np.einsum('ijab,kicb->akcj', t2_1_b, t2_1_ab)\n\n        e_mp3 = 0.125 * np.einsum('abcd,abcd',temp_1_a, v2e_vvvv_a)\n        e_mp3 += 0.125 * np.einsum('abcd,abcd',temp_1_b, v2e_vvvv_b)\n        e_mp3 +=  np.einsum('abcd,abcd',temp_1_ab_1, v2e_vvvv_ab)\n\n        e_mp3 += 0.125 * np.einsum('ijkl,ijkl',temp_2_a, v2e_oooo_a)\n        e_mp3 += 0.125 * np.einsum('ijkl,ijkl',temp_2_b, v2e_oooo_b)\n        e_mp3 +=  np.einsum('ijkl,ijkl',temp_2_ab_1, v2e_oooo_ab)\n\n        e_mp3 -= np.einsum('akcj,akcj',temp_3_a, v2e_vovo_a)\n        e_mp3 -= np.einsum('akcj,akcj',temp_3_b, v2e_vovo_b)\n        e_mp3 -= np.einsum('akcj,akcj',temp_3_ab_1, v2e_vovo_ab)\n        e_mp3 -= np.einsum('akcj,kajc',temp_3_ab_2, v2e_ovov_ab)\n        e_mp3 += np.einsum('akcj,akjc',temp_3_ab_3, v2e_voov_ab)\n        e_mp3 += np.einsum('akcj,kacj',temp_3_ab_4, v2e_ovvo_ab)\n    \n        e_corr += e_mp3\n\n    return e_corr\n\nclass UADC(lib.StreamObject):\n    '''Ground state calculations\n\n    Attributes:\n        verbose : int\n            Print level.  Default value equals to :class:`Mole.verbose`\n        max_memory : float or int\n            Allowed memory in MB.  Default value equals to :class:`Mole.max_memory`\n        incore_complete : bool\n            Avoid all I/O. Default is False.\n        method : string\n            nth-order ADC method. Options are : ADC(2), ADC(2)-X, ADC(3). Default is ADC(2). \n\n            >>> mol = gto.M(atom = 'H 0 0 0; F 0 0 1.1', basis = 'ccpvdz')\n            >>> mf = scf.RHF(mol).run()\n            >>> myadc = adc.UADC(mf).run()\n\n    Saved results\n\n        e_corr : float\n            MPn correlation correction\n        e_tot : float\n            Total energy (HF + correlation)\n        t1, t2 :\n            T amplitudes t1[i,a], t2[i,j,a,b]  (i,j in occ, a,b in virt)\n    '''\n    incore_complete = getattr(__config__, 'adc_uadc_UADC_incore_complete', False)\n    \n    def __init__(self, mf, frozen=0, mo_coeff=None, mo_occ=None):\n        from pyscf import gto\n        \n        if 'dft' in str(mf.__module__):\n            raise NotImplementedError('DFT reference for UADC')\n        \n        if mo_coeff  is None: mo_coeff  = mf.mo_coeff\n        if mo_occ    is None: mo_occ    = mf.mo_occ\n        \n        self.mol = mf.mol\n        self._scf = mf\n        self.verbose = self.mol.verbose\n        self.stdout = self.mol.stdout\n        self.max_memory = mf.max_memory\n\n        self.max_space = getattr(__config__, 'adc_uadc_UADC_max_space', 12)\n        self.max_cycle = getattr(__config__, 'adc_uadc_UADC_max_cycle', 50)\n        self.conv_tol = getattr(__config__, 'adc_uadc_UADC_conv_tol', 1e-12)\n        self.scf_energy = mf.scf()\n        \n        self.frozen = frozen\n        self.incore_complete = self.incore_complete or self.mol.incore_anyway\n        \n        self.mo_coeff = mo_coeff\n        self.mo_occ = mo_occ\n        self.e_corr = None\n        self.e_tot = None\n        self.t1 = None\n        self.t2 = None\n        self._nocc = mf.nelec\n        self._nmo = (mo_coeff[0].shape[1], mo_coeff[1].shape[1])\n        self._nvir = (self._nmo[0] - self._nocc[0], self._nmo[1] - self._nocc[1])\n        self.mo_energy_a = mf.mo_energy[0]\n        self.mo_energy_b = mf.mo_energy[1]\n        self._nocc = mf.nelec\n        self._nmo = (mo_coeff[0].shape[1], mo_coeff[1].shape[1])\n        self._nvir = (self._nmo[0] - self._nocc[0], self._nmo[1] - self._nocc[1])\n        self.mo_energy_a = mf.mo_energy[0]\n        self.mo_energy_b = mf.mo_energy[1]\n        self.chkfile = mf.chkfile\n        self.method = \"adc(2)\"\n\n        keys = set(('e_corr', 'method', 'mo_coeff', 'mol', 'mo_energy_b', 'max_memory', 'scf_energy', 'e_tot', 't1', 'frozen', 'mo_energy_a', 'chkfile', 'max_space', 't2', 'mo_occ', 'max_cycle'))\n\n        self._keys = set(self.__dict__.keys()).union(keys)\n    \n    compute_amplitudes = compute_amplitudes\n    compute_energy = compute_energy\n    \n    def dump_flags(self, verbose=None):\n        logger.info(self, '')\n        logger.info(self, '******** %s ********', self.__class__)\n        logger.info(self, 'max_space = %d', self.max_space)\n        logger.info(self, 'max_cycle = %d', self.max_cycle)\n        logger.info(self, 'conv_tol = %s', self.conv_tol)\n        logger.info(self, 'max_memory %d MB (current use %d MB)',\n                    self.max_memory, lib.current_memory()[0])\n        return self\n\n    def dump_flags_gs(self, verbose=None):\n        logger.info(self, '')\n        logger.info(self, '******** %s ********', self.__class__)\n        logger.info(self, 'max_memory %d MB (current use %d MB)',\n                    self.max_memory, lib.current_memory()[0])\n        return self\n\n    def kernel(self):\n        assert(self.mo_coeff is not None)\n        assert(self.mo_occ is not None)\n    \n        self.method = self.method.lower()\n        if self.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n            raise NotImplementedError(self.method)\n    \n        if self.verbose >= logger.WARN:\n            self.check_sanity()\n        self.dump_flags_gs()\n    \n        eris = uadc_ao2mo.transform_integrals(self)\n        self.e_corr, self.t1, self.t2 = compute_amplitudes_energy(self, eris, verbose=self.verbose)\n        self.e_tot = self.scf_energy + self.e_corr\n\n        self._finalize()\n\n        return self.e_corr, self.t1, self.t2\n\n    def _finalize(self):\n        '''Hook for dumping results and clearing up the object.'''\n        logger.note(self, 'E_corr = %.8f  E_tot = %.8f',\n                    self.e_corr, self.e_tot)\n        return self\n    \n    def ea_adc(self, nroots=1, guess=None):\n        return UADCEA(self).kernel(nroots, guess)\n    \n    def ip_adc(self, nroots=1, guess=None):\n        return UADCIP(self).kernel(nroots, guess)\n\ndef get_imds_ea(adc, eris=None):\n\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    t1 = adc.t1\n    t2 = adc.t2\n\n    t1_2_a, t1_2_b = t1[0]\n    t2_1_a, t2_1_ab, t2_1_b = t2[0]\n\n    nocc_a = adc.nocc_a\n    nocc_b = adc.nocc_b\n    nvir_a = adc.nvir_a\n    nvir_b = adc.nvir_b\n\n    e_occ_a = adc.mo_energy_a[:nocc_a]\n    e_occ_b = adc.mo_energy_b[:nocc_b]\n    e_vir_a = adc.mo_energy_a[nocc_a:]\n    e_vir_b = adc.mo_energy_b[nocc_b:]\n\n    idn_occ_a = np.identity(nocc_a)\n    idn_occ_b = np.identity(nocc_b)\n    idn_vir_a = np.identity(nvir_a)\n    idn_vir_b = np.identity(nvir_b)\n\n    if eris is None:\n        eris = uadc_ao2mo.transform_integrals(adc)\n\n    v2e_oovv_a,v2e_oovv_ab,v2e_oovv_b = eris.oovv\n    v2e_ooov_a,v2e_ooov_ab,v2e_ooov_b = eris.ooov\n    v2e_oooo_a,v2e_oooo_ab,v2e_oooo_b = eris.oooo\n    v2e_ovoo_a,v2e_ovoo_ab,v2e_ovoo_b = eris.ovoo\n    v2e_ovov_a,v2e_ovov_ab,v2e_ovov_b = eris.ovov\n    v2e_vvoo_a,v2e_vvoo_ab,v2e_vvoo_b = eris.vvoo\n    v2e_vvvv_a,v2e_vvvv_ab,v2e_vvvv_b = eris.vvvv\n    v2e_voov_a,v2e_voov_ab,v2e_voov_b = eris.voov\n    v2e_ovvo_a,v2e_ovvo_ab,v2e_ovvo_b = eris.ovvo\n    v2e_vovo_a,v2e_vovo_ab,v2e_vovo_b = eris.vovo\n    v2e_vvvo_a,v2e_vvvo_ab,v2e_vvvo_b = eris.vvvo\n    v2e_vovv_a,v2e_vovv_ab,v2e_vovv_b = eris.vovv\n    v2e_oovo_a,v2e_oovo_ab,v2e_oovo_b = eris.oovo\n    v2e_ovvv_a,v2e_ovvv_ab,v2e_ovvv_b = eris.ovvv\n    v2e_vvov_a,v2e_vvov_ab,v2e_vvov_b = eris.vvov\n\n    # a-b block\n    # Zeroth-order terms\n\n    M_ab_a = np.einsum('ab,a->ab', idn_vir_a, e_vir_a)\n    M_ab_b = np.einsum('ab,a->ab', idn_vir_b, e_vir_b)\n\n   # Second-order terms\n\n    M_ab_a +=  np.einsum('l,lmad,lmbd->ab',e_occ_a,t2_1_a, t2_1_a)\n    M_ab_a +=  np.einsum('l,lmad,lmbd->ab',e_occ_a,t2_1_ab, t2_1_ab)\n    M_ab_a +=  np.einsum('l,mlad,mlbd->ab',e_occ_b,t2_1_ab, t2_1_ab)\n\n    M_ab_b +=  np.einsum('l,lmad,lmbd->ab',e_occ_b,t2_1_b, t2_1_b)\n    M_ab_b +=  np.einsum('l,mlda,mldb->ab',e_occ_b,t2_1_ab, t2_1_ab)\n    M_ab_b +=  np.einsum('l,lmda,lmdb->ab',e_occ_a,t2_1_ab, t2_1_ab)\n\n    M_ab_a -= 0.5 *  np.einsum('d,lmad,lmbd->ab',e_vir_a,t2_1_a, t2_1_a)\n    M_ab_a -= 0.5 *  np.einsum('d,lmad,lmbd->ab',e_vir_b,t2_1_ab, t2_1_ab)\n    M_ab_a -= 0.5 *  np.einsum('d,mlad,mlbd->ab',e_vir_b,t2_1_ab, t2_1_ab)\n\n    M_ab_b -= 0.5 *  np.einsum('d,lmad,lmbd->ab',e_vir_b,t2_1_b, t2_1_b)\n    M_ab_b -= 0.5 *  np.einsum('d,mlda,mldb->ab',e_vir_a,t2_1_ab, t2_1_ab)\n    M_ab_b -= 0.5 *  np.einsum('d,lmda,lmdb->ab',e_vir_a,t2_1_ab, t2_1_ab)\n\n    M_ab_a -= 0.25 *  np.einsum('a,lmad,lmbd->ab',e_vir_a,t2_1_a, t2_1_a)\n    M_ab_a -= 0.25 *  np.einsum('a,lmad,lmbd->ab',e_vir_a,t2_1_ab, t2_1_ab)\n    M_ab_a -= 0.25 *  np.einsum('a,mlad,mlbd->ab',e_vir_a,t2_1_ab, t2_1_ab)\n\n    M_ab_b -= 0.25 *  np.einsum('a,lmad,lmbd->ab',e_vir_b,t2_1_b, t2_1_b)\n    M_ab_b -= 0.25 *  np.einsum('a,mlda,mldb->ab',e_vir_b,t2_1_ab, t2_1_ab)\n    M_ab_b -= 0.25 *  np.einsum('a,lmda,lmdb->ab',e_vir_b,t2_1_ab, t2_1_ab)\n\n    M_ab_a -= 0.25 *  np.einsum('b,lmad,lmbd->ab',e_vir_a,t2_1_a, t2_1_a)\n    M_ab_a -= 0.25 *  np.einsum('b,lmad,lmbd->ab',e_vir_a,t2_1_ab, t2_1_ab)\n    M_ab_a -= 0.25 *  np.einsum('b,mlad,mlbd->ab',e_vir_a,t2_1_ab, t2_1_ab)\n\n    M_ab_b -= 0.25 *  np.einsum('b,lmad,lmbd->ab',e_vir_b,t2_1_b, t2_1_b)\n    M_ab_b -= 0.25 *  np.einsum('b,mlda,mldb->ab',e_vir_b,t2_1_ab, t2_1_ab)\n    M_ab_b -= 0.25 *  np.einsum('b,lmda,lmdb->ab',e_vir_b,t2_1_ab, t2_1_ab)\n\n    M_ab_a -= 0.5 *  np.einsum('lmad,lmbd->ab',t2_1_a, v2e_oovv_a)\n    M_ab_a -=        np.einsum('lmad,lmbd->ab',t2_1_ab, v2e_oovv_ab)\n\n    M_ab_b -= 0.5 *  np.einsum('lmad,lmbd->ab',t2_1_b, v2e_oovv_b)\n    M_ab_b -=        np.einsum('mlda,mldb->ab',t2_1_ab, v2e_oovv_ab)\n\n    M_ab_a -= 0.5 *  np.einsum('lmbd,lmad->ab',t2_1_a, v2e_oovv_a)\n    M_ab_a -=        np.einsum('lmbd,lmad->ab',t2_1_ab, v2e_oovv_ab)\n\n    M_ab_b -= 0.5 *  np.einsum('lmbd,lmad->ab',t2_1_b, v2e_oovv_b)\n    M_ab_b -=        np.einsum('mldb,mlda->ab',t2_1_ab, v2e_oovv_ab)\n\n\n    #Third-order terms\n\n    if(method =='adc(3)'):\n\n        t2_2_a, t2_2_ab, t2_2_b = t2[1]\n\n        M_ab_a +=  np.einsum('ld,albd->ab',t1_2_a, v2e_vovv_a)\n        M_ab_a +=  np.einsum('ld,albd->ab',t1_2_b, v2e_vovv_ab)\n\n        M_ab_b +=  np.einsum('ld,albd->ab',t1_2_b, v2e_vovv_b)\n        M_ab_b +=  np.einsum('ld,ladb->ab',t1_2_a, v2e_ovvv_ab)\n\n        M_ab_a += np.einsum('ld,adbl->ab',t1_2_a, v2e_vvvo_a)\n        M_ab_a += np.einsum('ld,adbl->ab',t1_2_b, v2e_vvvo_ab)\n\n        M_ab_b += np.einsum('ld,adbl->ab',t1_2_b, v2e_vvvo_b)\n        M_ab_b += np.einsum('ld,dalb->ab',t1_2_a, v2e_vvov_ab)\n\n        M_ab_a -=0.5* np.einsum('lmbd,lmad->ab',t2_2_a,v2e_oovv_a)\n        M_ab_a -= np.einsum('lmbd,lmad->ab',t2_2_ab,v2e_oovv_ab)\n\n        M_ab_b -=0.5* np.einsum('lmbd,lmad->ab',t2_2_b,v2e_oovv_b)\n        M_ab_b -= np.einsum('mldb,mlda->ab',t2_2_ab,v2e_oovv_ab)\n\n        M_ab_a -=0.5* np.einsum('lmad,lmbd->ab',t2_2_a,v2e_oovv_a)\n        M_ab_a -= np.einsum('lmad,lmbd->ab',t2_2_ab,v2e_oovv_ab)\n\n        M_ab_b -=0.5* np.einsum('lmad,lmbd->ab',t2_2_b,v2e_oovv_b)\n        M_ab_b -= np.einsum('mlda,mldb->ab',t2_2_ab,v2e_oovv_ab)\n\n        M_ab_a += np.einsum('l,lmbd,lmad->ab',e_occ_a, t2_1_a, t2_2_a, optimize=True)\n        M_ab_a += np.einsum('l,lmbd,lmad->ab',e_occ_a, t2_1_ab, t2_2_ab, optimize=True)\n        M_ab_a += np.einsum('l,mlbd,mlad->ab',e_occ_b, t2_1_ab, t2_2_ab, optimize=True)\n\n        M_ab_b += np.einsum('l,lmbd,lmad->ab',e_occ_b, t2_1_b, t2_2_b, optimize=True)\n        M_ab_b += np.einsum('l,mldb,mlda->ab',e_occ_b, t2_1_ab, t2_2_ab, optimize=True)\n        M_ab_b += np.einsum('l,lmdb,lmda->ab',e_occ_a, t2_1_ab, t2_2_ab, optimize=True)\n\n        M_ab_a += np.einsum('l,lmad,lmbd->ab',e_occ_a, t2_1_a, t2_2_a, optimize=True)\n        M_ab_a += np.einsum('l,lmad,lmbd->ab',e_occ_a, t2_1_ab, t2_2_ab, optimize=True)\n        M_ab_a += np.einsum('l,mlad,mlbd->ab',e_occ_b, t2_1_ab, t2_2_ab, optimize=True)\n\n        M_ab_b += np.einsum('l,lmad,lmbd->ab',e_occ_b, t2_1_b, t2_2_b, optimize=True)\n        M_ab_b += np.einsum('l,mlda,mldb->ab',e_occ_b, t2_1_ab, t2_2_ab, optimize=True)\n        M_ab_b += np.einsum('l,lmda,lmdb->ab',e_occ_a, t2_1_ab, t2_2_ab, optimize=True)\n\n        M_ab_a -= 0.5*np.einsum('d,lmbd,lmad->ab', e_vir_a, t2_1_a ,t2_2_a, optimize=True)\n        M_ab_a -= 0.5*np.einsum('d,lmbd,lmad->ab', e_vir_b, t2_1_ab ,t2_2_ab, optimize=True)\n        M_ab_a -= 0.5*np.einsum('d,mlbd,mlad->ab', e_vir_b, t2_1_ab ,t2_2_ab, optimize=True)\n\n        M_ab_b -= 0.5*np.einsum('d,lmbd,lmad->ab', e_vir_b, t2_1_b ,t2_2_b, optimize=True)\n        M_ab_b -= 0.5*np.einsum('d,mldb,mlda->ab', e_vir_a, t2_1_ab ,t2_2_ab, optimize=True)\n        M_ab_b -= 0.5*np.einsum('d,lmdb,lmda->ab', e_vir_a, t2_1_ab ,t2_2_ab, optimize=True)\n\n        M_ab_a -= 0.5*np.einsum('d,lmad,lmbd->ab', e_vir_a, t2_1_a, t2_2_a, optimize=True)\n        M_ab_a -= 0.5*np.einsum('d,lmad,lmbd->ab', e_vir_b, t2_1_ab, t2_2_ab, optimize=True)\n        M_ab_a -= 0.5*np.einsum('d,mlad,mlbd->ab', e_vir_b, t2_1_ab, t2_2_ab, optimize=True)\n\n        M_ab_b -= 0.5*np.einsum('d,lmad,lmbd->ab', e_vir_b, t2_1_b, t2_2_b, optimize=True)\n        M_ab_b -= 0.5*np.einsum('d,mlda,mldb->ab', e_vir_a, t2_1_ab, t2_2_ab, optimize=True)\n        M_ab_b -= 0.5*np.einsum('d,lmda,lmdb->ab', e_vir_a, t2_1_ab, t2_2_ab, optimize=True)\n\n        M_ab_a -= 0.25*np.einsum('a,lmbd,lmad->ab',e_vir_a, t2_1_a, t2_2_a, optimize=True)\n        M_ab_a -= 0.25*np.einsum('a,lmbd,lmad->ab',e_vir_a, t2_1_ab, t2_2_ab, optimize=True)\n        M_ab_a -= 0.25*np.einsum('a,mlbd,mlad->ab',e_vir_a, t2_1_ab, t2_2_ab, optimize=True)\n\n        M_ab_b -= 0.25*np.einsum('a,lmbd,lmad->ab',e_vir_b, t2_1_b, t2_2_b, optimize=True)\n        M_ab_b -= 0.25*np.einsum('a,mldb,mlda->ab',e_vir_b, t2_1_ab, t2_2_ab, optimize=True)\n        M_ab_b -= 0.25*np.einsum('a,lmdb,lmda->ab',e_vir_b, t2_1_ab, t2_2_ab, optimize=True)\n\n        M_ab_a -= 0.25*np.einsum('a,lmad,lmbd->ab',e_vir_a, t2_1_a, t2_2_a, optimize=True)\n        M_ab_a -= 0.25*np.einsum('a,lmad,lmbd->ab',e_vir_a, t2_1_ab, t2_2_ab, optimize=True)\n        M_ab_a -= 0.25*np.einsum('a,mlad,mlbd->ab',e_vir_a, t2_1_ab, t2_2_ab, optimize=True)\n\n        M_ab_b -= 0.25*np.einsum('a,lmad,lmbd->ab',e_vir_b, t2_1_b, t2_2_b, optimize=True)\n        M_ab_b -= 0.25*np.einsum('a,mlda,mldb->ab',e_vir_b, t2_1_ab, t2_2_ab, optimize=True)\n        M_ab_b -= 0.25*np.einsum('a,lmda,lmdb->ab',e_vir_b, t2_1_ab, t2_2_ab, optimize=True)\n\n        M_ab_a -= 0.25*np.einsum('b,lmbd,lmad->ab',e_vir_a, t2_1_a, t2_2_a, optimize=True)\n        M_ab_a -= 0.25*np.einsum('b,lmbd,lmad->ab',e_vir_a, t2_1_ab, t2_2_ab, optimize=True)\n        M_ab_a -= 0.25*np.einsum('b,mlbd,mlad->ab',e_vir_a, t2_1_ab, t2_2_ab, optimize=True)\n\n        M_ab_b -= 0.25*np.einsum('b,lmbd,lmad->ab',e_vir_b, t2_1_b, t2_2_b, optimize=True)\n        M_ab_b -= 0.25*np.einsum('b,mldb,mlda->ab',e_vir_b, t2_1_ab, t2_2_ab, optimize=True)\n        M_ab_b -= 0.25*np.einsum('b,lmdb,lmda->ab',e_vir_b, t2_1_ab, t2_2_ab, optimize=True)\n\n        M_ab_a -= 0.25*np.einsum('b,lmad,lmbd->ab',e_vir_a, t2_1_a, t2_2_a, optimize=True)\n        M_ab_a -= 0.25*np.einsum('b,lmad,lmbd->ab',e_vir_a, t2_1_ab, t2_2_ab, optimize=True)\n        M_ab_a -= 0.25*np.einsum('b,mlad,mlbd->ab',e_vir_a, t2_1_ab, t2_2_ab, optimize=True)\n\n        M_ab_b -= 0.25*np.einsum('b,lmad,lmbd->ab',e_vir_b, t2_1_b, t2_2_b, optimize=True)\n        M_ab_b -= 0.25*np.einsum('b,mlda,mldb->ab',e_vir_b, t2_1_ab, t2_2_ab, optimize=True)\n        M_ab_b -= 0.25*np.einsum('b,lmda,lmdb->ab',e_vir_b, t2_1_ab, t2_2_ab, optimize=True)\n\n        M_ab_a -= np.einsum('lned,mlbd,anem->ab',t2_1_a, t2_1_a, v2e_vovo_a, optimize=True)\n        M_ab_a += np.einsum('nled,mlbd,anem->ab',t2_1_ab, t2_1_ab, v2e_vovo_a, optimize=True)\n        M_ab_a -= np.einsum('lnde,mlbd,anme->ab',t2_1_ab, t2_1_a, v2e_voov_ab, optimize=True)\n        M_ab_a += np.einsum('lned,mlbd,anme->ab',t2_1_b, t2_1_ab, v2e_voov_ab, optimize=True)\n        M_ab_a += np.einsum('lned,lmbd,anem->ab',t2_1_ab, t2_1_ab, v2e_vovo_ab, optimize=True)\n\n        M_ab_b -= np.einsum('lned,mlbd,anem->ab',t2_1_b, t2_1_b, v2e_vovo_b, optimize=True)\n        M_ab_b += np.einsum('lnde,lmdb,anem->ab',t2_1_ab, t2_1_ab, v2e_vovo_b, optimize=True)\n        M_ab_b -= np.einsum('nled,mlbd,naem->ab',t2_1_ab, t2_1_b, v2e_ovvo_ab, optimize=True)\n        M_ab_b += np.einsum('lned,lmdb,naem->ab',t2_1_a, t2_1_ab, v2e_ovvo_ab, optimize=True)\n        M_ab_b += np.einsum('nlde,mldb,name->ab',t2_1_ab, t2_1_ab, v2e_ovov_ab, optimize=True)\n\n        M_ab_a -= np.einsum('mled,lnad,enbm->ab',t2_1_a, t2_1_a, v2e_vovo_a, optimize=True)\n        M_ab_a -= np.einsum('mled,nlad,nebm->ab',t2_1_b, t2_1_ab, v2e_ovvo_ab, optimize=True)\n        M_ab_a += np.einsum('mled,nlad,enbm->ab',t2_1_ab, t2_1_ab, v2e_vovo_a, optimize=True)\n        M_ab_a += np.einsum('lmde,lnad,nebm->ab',t2_1_ab, t2_1_a, v2e_ovvo_ab, optimize=True)\n        M_ab_a += np.einsum('lmed,lnad,enbm->ab',t2_1_ab, t2_1_ab, v2e_vovo_ab, optimize=True)\n\n        M_ab_b -= np.einsum('mled,lnad,enbm->ab',t2_1_b, t2_1_b, v2e_vovo_b, optimize=True)\n        M_ab_b -= np.einsum('mled,lnda,enmb->ab',t2_1_a, t2_1_ab, v2e_voov_ab, optimize=True)\n        M_ab_b += np.einsum('lmde,lnda,enbm->ab',t2_1_ab, t2_1_ab, v2e_vovo_b, optimize=True)\n        M_ab_b += np.einsum('mled,lnad,enmb->ab',t2_1_ab, t2_1_b, v2e_voov_ab, optimize=True)\n        M_ab_b += np.einsum('mlde,nlda,nemb->ab',t2_1_ab, t2_1_ab, v2e_ovov_ab, optimize=True)\n\n        M_ab_a -= np.einsum('mlbd,lnae,dnem->ab',t2_1_a, t2_1_a, v2e_vovo_a, optimize=True)\n        M_ab_a += np.einsum('lmbd,lnae,dnem->ab',t2_1_ab, t2_1_ab, v2e_vovo_b, optimize=True)\n        M_ab_a += np.einsum('mlbd,lnae,dnme->ab',t2_1_a, t2_1_ab, v2e_voov_ab, optimize=True)\n        M_ab_a -= np.einsum('lmbd,lnae,ndem->ab',t2_1_ab, t2_1_a, v2e_ovvo_ab, optimize=True)\n        M_ab_a += np.einsum('mlbd,nlae,ndme->ab',t2_1_ab, t2_1_ab, v2e_ovov_ab, optimize=True)\n\n        M_ab_b -= np.einsum('mlbd,lnae,dnem->ab',t2_1_b, t2_1_b, v2e_vovo_b, optimize=True)\n        M_ab_b += np.einsum('mldb,nlea,dnem->ab',t2_1_ab, t2_1_ab, v2e_vovo_a, optimize=True)\n        M_ab_b += np.einsum('mlbd,nlea,ndem->ab',t2_1_b, t2_1_ab, v2e_ovvo_ab, optimize=True)\n        M_ab_b -= np.einsum('mldb,lnae,dnme->ab',t2_1_ab, t2_1_b, v2e_voov_ab, optimize=True)\n        M_ab_b += np.einsum('lmdb,lnea,dnem->ab',t2_1_ab, t2_1_ab, v2e_vovo_ab, optimize=True)\n\n        M_ab_a -= 0.25*np.einsum('mlef,mlbd,adef->ab',t2_1_a, t2_1_a, v2e_vvvv_a, optimize=True)\n        M_ab_a -= np.einsum('mlef,mlbd,adef->ab',t2_1_ab, t2_1_ab, v2e_vvvv_ab, optimize=True)\n\n        M_ab_b -= 0.25*np.einsum('mlef,mlbd,adef->ab',t2_1_b, t2_1_b, v2e_vvvv_b, optimize=True)\n        M_ab_b -= np.einsum('mlef,mldb,daef->ab',t2_1_ab, t2_1_ab, v2e_vvvv_ab, optimize=True)\n\n        M_ab_a -= 0.25*np.einsum('mled,mlaf,edbf->ab',t2_1_a, t2_1_a, v2e_vvvv_a, optimize=True)\n        M_ab_a -= np.einsum('mled,mlaf,edbf->ab',t2_1_ab, t2_1_ab, v2e_vvvv_ab, optimize=True)\n\n        M_ab_b -= 0.25*np.einsum('mled,mlaf,edbf->ab',t2_1_b, t2_1_b, v2e_vvvv_b, optimize=True)\n        M_ab_b -= np.einsum('mled,mlfa,edfb->ab',t2_1_ab, t2_1_ab, v2e_vvvv_ab, optimize=True)\n\n        M_ab_a -= 0.25*np.einsum('mlbd,noad,noml->ab',t2_1_a, t2_1_a, v2e_oooo_a, optimize=True)\n        M_ab_a -= np.einsum('mlbd,noad,noml->ab',t2_1_ab, t2_1_ab, v2e_oooo_ab, optimize=True)\n\n        M_ab_b -= 0.25*np.einsum('mlbd,noad,noml->ab',t2_1_b, t2_1_b, v2e_oooo_b, optimize=True)\n        M_ab_b -= np.einsum('lmdb,onda,onlm->ab',t2_1_ab, t2_1_ab, v2e_oooo_ab, optimize=True)\n\n        M_ab_a += 0.5*np.einsum('lned,mled,anbm->ab',t2_1_a, t2_1_a, v2e_vovo_a, optimize=True)\n        M_ab_a += 0.5*np.einsum('lned,mled,anbm->ab',t2_1_b, t2_1_b, v2e_vovo_ab, optimize=True)\n        M_ab_a -= np.einsum('lned,lmed,anbm->ab',t2_1_ab, t2_1_ab, v2e_vovo_ab, optimize=True)\n        M_ab_a -= np.einsum('nled,mled,anbm->ab',t2_1_ab, t2_1_ab, v2e_vovo_a, optimize=True)\n\n        M_ab_b += 0.5*np.einsum('lned,mled,anbm->ab',t2_1_b, t2_1_b, v2e_vovo_b, optimize=True)\n        M_ab_b += 0.5*np.einsum('lned,mled,namb->ab',t2_1_a, t2_1_a, v2e_ovov_ab, optimize=True)\n        M_ab_b -= np.einsum('nled,mled,namb->ab',t2_1_ab, t2_1_ab, v2e_ovov_ab, optimize=True)\n        M_ab_b -= np.einsum('lned,lmed,anbm->ab',t2_1_ab, t2_1_ab, v2e_vovo_b, optimize=True)\n\n        M_ab_a -= 0.5*np.einsum('mldf,mled,aebf->ab',t2_1_a, t2_1_a, v2e_vvvv_a, optimize=True)\n        M_ab_a -= 0.5*np.einsum('mldf,mled,aebf->ab',t2_1_b, t2_1_b, v2e_vvvv_ab, optimize=True)\n        M_ab_a += np.einsum('mldf,mlde,aebf->ab',t2_1_ab, t2_1_ab, v2e_vvvv_ab, optimize=True)\n        M_ab_a += np.einsum('mlfd,mled,aebf->ab',t2_1_ab, t2_1_ab, v2e_vvvv_a, optimize=True)\n\n        M_ab_b -= 0.5*np.einsum('mldf,mled,aebf->ab',t2_1_b, t2_1_b, v2e_vvvv_b, optimize=True)\n        M_ab_b -= 0.5*np.einsum('mldf,mled,eafb->ab',t2_1_a, t2_1_a, v2e_vvvv_ab, optimize=True)\n        M_ab_b += np.einsum('mlfd,mled,eafb->ab',t2_1_ab, t2_1_ab, v2e_vvvv_ab, optimize=True)\n        M_ab_b += np.einsum('mldf,mlde,aebf->ab',t2_1_ab, t2_1_ab, v2e_vvvv_b, optimize=True)\n\n    M_ab = (M_ab_a, M_ab_b)\n\n    return M_ab\n\ndef get_imds_ip(adc, eris=None):\n\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    t1 = adc.t1\n    t2 = adc.t2\n\n    t1_2_a, t1_2_b = t1[0]\n    t2_1_a, t2_1_ab, t2_1_b = t2[0]\n\n    nocc_a = adc.nocc_a\n    nocc_b = adc.nocc_b\n    nvir_a = adc.nvir_a\n    nvir_b = adc.nvir_b\n\n    e_occ_a = adc.mo_energy_a[:nocc_a]\n    e_occ_b = adc.mo_energy_b[:nocc_b]\n    e_vir_a = adc.mo_energy_a[nocc_a:]\n    e_vir_b = adc.mo_energy_b[nocc_b:]\n\n    idn_occ_a = np.identity(nocc_a)\n    idn_occ_b = np.identity(nocc_b)\n    idn_vir_a = np.identity(nvir_a)\n    idn_vir_b = np.identity(nvir_b)\n\n    if eris is None:\n        eris = uadc_ao2mo.transform_integrals(adc)\n\n    v2e_oovv_a,v2e_oovv_ab,v2e_oovv_b = eris.oovv\n    v2e_vvoo_a,v2e_vvoo_ab,v2e_vvoo_b = eris.vvoo\n    v2e_ooov_a,v2e_ooov_ab,v2e_ooov_b = eris.ooov\n    v2e_ovoo_a,v2e_ovoo_ab,v2e_ovoo_b = eris.ovoo\n    v2e_ovov_a,v2e_ovov_ab,v2e_ovov_b = eris.ovov\n    v2e_vovo_a,v2e_vovo_ab,v2e_vovo_b = eris.vovo\n    v2e_oooo_a,v2e_oooo_ab,v2e_oooo_b = eris.oooo\n    v2e_ovvo_a,v2e_ovvo_ab,v2e_ovvo_b = eris.ovvo\n    v2e_vvvv_a,v2e_vvvv_ab,v2e_vvvv_b = eris.vvvv\n    v2e_voov_a,v2e_voov_ab,v2e_voov_b = eris.voov\n    v2e_oovo_a,v2e_oovo_ab,v2e_oovo_b = eris.oovo\n    v2e_vooo_a,v2e_vooo_ab,v2e_vooo_b = eris.vooo\n\n    # i-j block\n    # Zeroth-order terms\n\n    M_ij_a = np.einsum('ij,j->ij', idn_occ_a ,e_occ_a)\n    M_ij_b = np.einsum('ij,j->ij', idn_occ_b ,e_occ_b)\n\n    # Second-order terms\n\n    M_ij_a +=  np.einsum('d,ilde,jlde->ij',e_vir_a,t2_1_a, t2_1_a)\n    M_ij_a +=  np.einsum('d,ilde,jlde->ij',e_vir_a,t2_1_ab, t2_1_ab)\n    M_ij_a +=  np.einsum('d,iled,jled->ij',e_vir_b,t2_1_ab, t2_1_ab)\n\n    M_ij_b +=  np.einsum('d,ilde,jlde->ij',e_vir_b,t2_1_b, t2_1_b)\n    M_ij_b +=  np.einsum('d,lide,ljde->ij',e_vir_a,t2_1_ab, t2_1_ab)\n    M_ij_b +=  np.einsum('d,lied,ljed->ij',e_vir_b,t2_1_ab, t2_1_ab)\n\n    M_ij_a -= 0.5 *  np.einsum('l,ilde,jlde->ij',e_occ_a,t2_1_a, t2_1_a)\n    M_ij_a -= 0.5*np.einsum('l,ilde,jlde->ij',e_occ_b,t2_1_ab, t2_1_ab)\n    M_ij_a -= 0.5*np.einsum('l,ilde,jlde->ij',e_occ_b,t2_1_ab, t2_1_ab)\n\n    M_ij_b -= 0.5 *  np.einsum('l,ilde,jlde->ij',e_occ_b,t2_1_b, t2_1_b)\n    M_ij_b -= 0.5*np.einsum('l,lide,ljde->ij',e_occ_a,t2_1_ab, t2_1_ab)\n    M_ij_b -= 0.5*np.einsum('l,lied,ljed->ij',e_occ_a,t2_1_ab, t2_1_ab)\n\n    M_ij_a -= 0.25 *  np.einsum('i,ilde,jlde->ij',e_occ_a,t2_1_a, t2_1_a)\n    M_ij_a -= 0.25 *  np.einsum('i,ilde,jlde->ij',e_occ_a,t2_1_ab, t2_1_ab)\n    M_ij_a -= 0.25 *  np.einsum('i,ilde,jlde->ij',e_occ_a,t2_1_ab, t2_1_ab)\n\n    M_ij_b -= 0.25 *  np.einsum('i,ilde,jlde->ij',e_occ_b,t2_1_b, t2_1_b)\n    M_ij_b -= 0.25 *  np.einsum('i,lied,ljed->ij',e_occ_b,t2_1_ab, t2_1_ab)\n    M_ij_b -= 0.25 *  np.einsum('i,lide,ljde->ij',e_occ_b,t2_1_ab, t2_1_ab)\n\n    M_ij_a -= 0.25 *  np.einsum('j,ilde,jlde->ij',e_occ_a,t2_1_a, t2_1_a)\n    M_ij_a -= 0.25 *  np.einsum('j,ilde,jlde->ij',e_occ_a,t2_1_ab, t2_1_ab)\n    M_ij_a -= 0.25 *  np.einsum('j,ilde,jlde->ij',e_occ_a,t2_1_ab, t2_1_ab)\n\n    M_ij_b -= 0.25 *  np.einsum('j,ilde,jlde->ij',e_occ_b,t2_1_b, t2_1_b)\n    M_ij_b -= 0.25 *  np.einsum('j,lied,ljed->ij',e_occ_b,t2_1_ab, t2_1_ab)\n    M_ij_b -= 0.25 *  np.einsum('j,lide,ljde->ij',e_occ_b,t2_1_ab, t2_1_ab)\n\n    M_ij_a += 0.5 *  np.einsum('ilde,jlde->ij',t2_1_a, v2e_oovv_a)\n    M_ij_a += np.einsum('ilde,jlde->ij',t2_1_ab, v2e_oovv_ab)\n\n    M_ij_b += 0.5 *  np.einsum('ilde,jlde->ij',t2_1_b, v2e_oovv_b)\n    M_ij_b += np.einsum('lied,ljed->ij',t2_1_ab, v2e_oovv_ab)\n\n    M_ij_a += 0.5 *  np.einsum('jlde,deil->ij',t2_1_a, v2e_vvoo_a)\n    M_ij_a += np.einsum('jlde,deil->ij',t2_1_ab, v2e_vvoo_ab)\n\n    M_ij_b += 0.5 *  np.einsum('jlde,deil->ij',t2_1_b, v2e_vvoo_b)\n    M_ij_b += np.einsum('ljed,edli->ij',t2_1_ab, v2e_vvoo_ab)\n\n    # Third-order terms\n\n    if (method == \"adc(3)\"):\n\n        t2_2_a, t2_2_ab, t2_2_b = t2[1]\n\n        M_ij_a += np.einsum('ld,jlid->ij',t1_2_a, v2e_ooov_a)\n        M_ij_a += np.einsum('ld,jlid->ij',t1_2_b, v2e_ooov_ab)\n\n        M_ij_b += np.einsum('ld,jlid->ij',t1_2_b, v2e_ooov_b)\n        M_ij_b += np.einsum('ld,ljdi->ij',t1_2_a, v2e_oovo_ab)\n\n        M_ij_a += np.einsum('ld,jdil->ij',t1_2_a, v2e_ovoo_a)\n        M_ij_a += np.einsum('ld,jdil->ij',t1_2_b, v2e_ovoo_ab)\n\n        M_ij_b += np.einsum('ld,jdil->ij',t1_2_b, v2e_ovoo_b)\n        M_ij_b += np.einsum('ld,djli->ij',t1_2_a, v2e_vooo_ab)\n\n        M_ij_a += 0.5* np.einsum('ilde,jlde->ij',t2_2_a, v2e_oovv_a)\n        M_ij_a += np.einsum('ilde,jlde->ij',t2_2_ab, v2e_oovv_ab)\n\n        M_ij_b += 0.5* np.einsum('ilde,jlde->ij',t2_2_b, v2e_oovv_b)\n        M_ij_b += np.einsum('lied,ljed->ij',t2_2_ab, v2e_oovv_ab)\n\n        M_ij_a += 0.5* np.einsum('jlde,deil->ij',t2_2_a, v2e_vvoo_a)\n        M_ij_a += np.einsum('jlde,deil->ij',t2_2_ab, v2e_vvoo_ab)\n\n        M_ij_b += 0.5* np.einsum('jlde,deil->ij',t2_2_b, v2e_vvoo_b)\n        M_ij_b += np.einsum('ljed,edli->ij',t2_2_ab, v2e_vvoo_ab)\n\n        M_ij_a +=  np.einsum('d,ilde,jlde->ij',e_vir_a,t2_1_a, t2_2_a,optimize=True)\n        M_ij_a +=  np.einsum('d,ilde,jlde->ij',e_vir_a,t2_1_ab, t2_2_ab,optimize=True)\n        M_ij_a +=  np.einsum('d,iled,jled->ij',e_vir_b,t2_1_ab, t2_2_ab,optimize=True)\n\n        M_ij_b +=  np.einsum('d,ilde,jlde->ij',e_vir_b,t2_1_b, t2_2_b,optimize=True)\n        M_ij_b +=  np.einsum('d,lide,ljde->ij',e_vir_a,t2_1_ab, t2_2_ab,optimize=True)\n        M_ij_b +=  np.einsum('d,lied,ljed->ij',e_vir_b,t2_1_ab, t2_2_ab,optimize=True)\n\n        M_ij_a +=  np.einsum('d,jlde,ilde->ij',e_vir_a,t2_1_a, t2_2_a,optimize=True)\n        M_ij_a +=  np.einsum('d,jlde,ilde->ij',e_vir_a,t2_1_ab, t2_2_ab,optimize=True)\n        M_ij_a +=  np.einsum('d,jled,iled->ij',e_vir_b,t2_1_ab, t2_2_ab,optimize=True)\n\n        M_ij_b +=  np.einsum('d,jlde,ilde->ij',e_vir_b,t2_1_b, t2_2_b,optimize=True)\n        M_ij_b +=  np.einsum('d,ljde,lide->ij',e_vir_a,t2_1_ab, t2_2_ab,optimize=True)\n        M_ij_b +=  np.einsum('d,ljed,lied->ij',e_vir_b,t2_1_ab, t2_2_ab,optimize=True)\n\n        M_ij_a -= 0.5 *  np.einsum('l,ilde,jlde->ij',e_occ_a,t2_1_a, t2_2_a,optimize=True)\n        M_ij_a -= 0.5*np.einsum('l,ilde,jlde->ij',e_occ_b,t2_1_ab, t2_2_ab,optimize=True)\n        M_ij_a -= 0.5*np.einsum('l,ilde,jlde->ij',e_occ_b,t2_1_ab, t2_2_ab,optimize=True)\n\n        M_ij_b -= 0.5 *  np.einsum('l,ilde,jlde->ij',e_occ_b,t2_1_b, t2_2_b,optimize=True)\n        M_ij_b -= 0.5*np.einsum('l,lied,ljed->ij',e_occ_a,t2_1_ab, t2_2_ab,optimize=True)\n        M_ij_b -= 0.5*np.einsum('l,lied,ljed->ij',e_occ_a,t2_1_ab, t2_2_ab,optimize=True)\n\n        M_ij_a -= 0.5 *  np.einsum('l,jlde,ilde->ij',e_occ_a,t2_1_a, t2_2_a,optimize=True)\n        M_ij_a -= 0.5*np.einsum('l,jlde,ilde->ij',e_occ_b,t2_1_ab, t2_2_ab,optimize=True)\n        M_ij_a -= 0.5*np.einsum('l,jlde,ilde->ij',e_occ_b,t2_1_ab, t2_2_ab,optimize=True)\n\n        M_ij_b -= 0.5 *  np.einsum('l,jlde,ilde->ij',e_occ_b,t2_1_b, t2_2_b,optimize=True)\n        M_ij_b -= 0.5*np.einsum('l,ljed,lied->ij',e_occ_a,t2_1_ab, t2_2_ab,optimize=True)\n        M_ij_b -= 0.5*np.einsum('l,ljed,lied->ij',e_occ_a,t2_1_ab, t2_2_ab,optimize=True)\n\n        M_ij_a -= 0.25 *  np.einsum('i,ilde,jlde->ij',e_occ_a,t2_1_a, t2_2_a,optimize=True)\n        M_ij_a -= 0.25 *  np.einsum('i,ilde,jlde->ij',e_occ_a,t2_1_ab, t2_2_ab,optimize=True)\n        M_ij_a -= 0.25 *  np.einsum('i,ilde,jlde->ij',e_occ_a,t2_1_ab, t2_2_ab,optimize=True)\n\n        M_ij_b -= 0.25 *  np.einsum('i,ilde,jlde->ij',e_occ_b,t2_1_b, t2_2_b,optimize=True)\n        M_ij_b -= 0.25 *  np.einsum('i,lied,ljed->ij',e_occ_b,t2_1_ab, t2_2_ab,optimize=True)\n        M_ij_b -= 0.25 *  np.einsum('i,lied,ljed->ij',e_occ_b,t2_1_ab, t2_2_ab,optimize=True)\n\n        M_ij_a -= 0.25 *  np.einsum('i,jlde,ilde->ij',e_occ_a,t2_1_a, t2_2_a,optimize=True)\n        M_ij_a -= 0.25 *  np.einsum('i,jlde,ilde->ij',e_occ_a,t2_1_ab, t2_2_ab,optimize=True)\n        M_ij_a -= 0.25 *  np.einsum('i,jlde,ilde->ij',e_occ_a,t2_1_ab, t2_2_ab,optimize=True)\n\n        M_ij_b -= 0.25 *  np.einsum('i,jlde,ilde->ij',e_occ_b,t2_1_b, t2_2_b,optimize=True)\n        M_ij_b -= 0.25 *  np.einsum('i,ljed,lied->ij',e_occ_b,t2_1_ab, t2_2_ab,optimize=True)\n        M_ij_b -= 0.25 *  np.einsum('i,ljed,lied->ij',e_occ_b,t2_1_ab, t2_2_ab,optimize=True)\n\n        M_ij_a -= 0.25 *  np.einsum('j,jlde,ilde->ij',e_occ_a,t2_1_a, t2_2_a,optimize=True)\n        M_ij_a -= 0.25 *  np.einsum('j,jlde,ilde->ij',e_occ_a,t2_1_ab, t2_2_ab,optimize=True)\n        M_ij_a -= 0.25 *  np.einsum('j,jlde,ilde->ij',e_occ_a,t2_1_ab, t2_2_ab,optimize=True)\n\n        M_ij_b -= 0.25 *  np.einsum('j,jlde,ilde->ij',e_occ_b,t2_1_b, t2_2_b,optimize=True)\n        M_ij_b -= 0.25 *  np.einsum('j,ljed,lied->ij',e_occ_b,t2_1_ab, t2_2_ab,optimize=True)\n        M_ij_b -= 0.25 *  np.einsum('j,ljed,lied->ij',e_occ_b,t2_1_ab, t2_2_ab,optimize=True)\n\n        M_ij_a -= 0.25 *  np.einsum('j,ilde,jlde->ij',e_occ_a,t2_1_a, t2_2_a,optimize=True)\n        M_ij_a -= 0.25 *  np.einsum('j,ilde,jlde->ij',e_occ_a,t2_1_ab, t2_2_ab,optimize=True)\n        M_ij_a -= 0.25 *  np.einsum('j,ilde,jlde->ij',e_occ_a,t2_1_ab, t2_2_ab,optimize=True)\n\n        M_ij_b -= 0.25 *  np.einsum('j,ilde,jlde->ij',e_occ_b,t2_1_b, t2_2_b,optimize=True)\n        M_ij_b -= 0.25 *  np.einsum('j,lied,ljed->ij',e_occ_b,t2_1_ab, t2_2_ab,optimize=True)\n        M_ij_b -= 0.25 *  np.einsum('j,lied,ljed->ij',e_occ_b,t2_1_ab, t2_2_ab,optimize=True)\n\n        M_ij_a -= np.einsum('lmde,jldf,fmie->ij',t2_1_a, t2_1_a, v2e_voov_a ,optimize = True)\n        M_ij_a += np.einsum('mled,jlfd,fmie->ij',t2_1_ab, t2_1_ab, v2e_voov_a ,optimize = True)\n        M_ij_a -= np.einsum('lmde,jldf,fmie->ij',t2_1_ab, t2_1_a, v2e_voov_ab,optimize = True)\n        M_ij_a -= np.einsum('mlde,jldf,mfie->ij',t2_1_ab, t2_1_ab, v2e_ovov_ab ,optimize = True)\n        M_ij_a += np.einsum('lmde,jlfd,fmie->ij',t2_1_b, t2_1_ab, v2e_voov_ab ,optimize = True)\n\n        M_ij_b -= np.einsum('lmde,jldf,fmie->ij',t2_1_b, t2_1_b, v2e_voov_b ,optimize = True)\n        M_ij_b += np.einsum('lmde,ljdf,fmie->ij',t2_1_ab, t2_1_ab, v2e_voov_b ,optimize = True)\n        M_ij_b -= np.einsum('mled,jldf,mfei->ij',t2_1_ab, t2_1_b, v2e_ovvo_ab,optimize = True)\n        M_ij_b -= np.einsum('lmed,ljfd,fmei->ij',t2_1_ab, t2_1_ab, v2e_vovo_ab ,optimize = True)\n        M_ij_b += np.einsum('lmde,ljdf,mfei->ij',t2_1_a, t2_1_ab, v2e_ovvo_ab ,optimize = True)\n\n        M_ij_a -= np.einsum('lmde,ildf,fmje->ij',t2_1_a, t2_1_a, v2e_voov_a ,optimize = True)\n        M_ij_a += np.einsum('mled,ilfd,fmje->ij',t2_1_ab, t2_1_ab, v2e_voov_a ,optimize = True)\n        M_ij_a -= np.einsum('lmde,ildf,fmje->ij',t2_1_ab, t2_1_a, v2e_voov_ab,optimize = True)\n        M_ij_a -= np.einsum('mlde,ildf,mfje->ij',t2_1_ab, t2_1_ab, v2e_ovov_ab ,optimize = True)\n        M_ij_a += np.einsum('lmde,ilfd,fmje->ij',t2_1_b, t2_1_ab, v2e_voov_ab ,optimize = True)\n\n        M_ij_b -= np.einsum('lmde,ildf,fmje->ij',t2_1_b, t2_1_b, v2e_voov_b ,optimize = True)\n        M_ij_b += np.einsum('lmde,lidf,fmje->ij',t2_1_ab, t2_1_ab, v2e_voov_b ,optimize = True)\n        M_ij_b -= np.einsum('mled,ildf,mfej->ij',t2_1_ab, t2_1_b, v2e_ovvo_ab,optimize = True)\n        M_ij_b -= np.einsum('lmed,lifd,fmej->ij',t2_1_ab, t2_1_ab, v2e_vovo_ab ,optimize = True)\n        M_ij_b += np.einsum('lmde,lidf,mfej->ij',t2_1_a, t2_1_ab, v2e_ovvo_ab ,optimize = True)\n\n        M_ij_a += 0.25*np.einsum('lmde,jnde,lmin->ij',t2_1_a, t2_1_a,v2e_oooo_a, optimize = True)\n        M_ij_a += np.einsum('lmde,jnde,lmin->ij',t2_1_ab ,t2_1_ab,v2e_oooo_ab, optimize = True)\n\n        M_ij_b += 0.25*np.einsum('lmde,jnde,lmin->ij',t2_1_b, t2_1_b,v2e_oooo_b, optimize = True)\n        M_ij_b += np.einsum('mled,njed,mlni->ij',t2_1_ab ,t2_1_ab,v2e_oooo_ab, optimize = True)\n\n        M_ij_a += 0.25*np.einsum('ilde,jlgf,gfde->ij',t2_1_a, t2_1_a,v2e_vvvv_a, optimize = True)\n        M_ij_a +=np.einsum('ilde,jlgf,gfde->ij',t2_1_ab, t2_1_ab,v2e_vvvv_ab, optimize = True)\n\n        M_ij_b += 0.25*np.einsum('ilde,jlgf,gfde->ij',t2_1_b, t2_1_b,v2e_vvvv_b, optimize = True)\n        M_ij_b +=np.einsum('lied,ljfg,fged->ij',t2_1_ab, t2_1_ab,v2e_vvvv_ab, optimize = True)\n\n        M_ij_a += 0.25*np.einsum('inde,lmde,jnlm->ij',t2_1_a, t2_1_a,v2e_oooo_a, optimize = True)\n        M_ij_a +=np.einsum('inde,lmde,jnlm->ij',t2_1_ab, t2_1_ab,v2e_oooo_ab, optimize = True)\n\n        M_ij_b += 0.25*np.einsum('inde,lmde,jnlm->ij',t2_1_b, t2_1_b,v2e_oooo_b, optimize = True)\n        M_ij_b +=np.einsum('nied,mled,njml->ij',t2_1_ab, t2_1_ab,v2e_oooo_ab, optimize = True)\n\n        M_ij_a += 0.5*np.einsum('lmdf,lmde,jeif->ij',t2_1_a, t2_1_a, v2e_ovov_a , optimize = True)\n        M_ij_a +=np.einsum('mlfd,mled,jeif->ij',t2_1_ab, t2_1_ab, v2e_ovov_a , optimize = True)\n        M_ij_a +=np.einsum('lmdf,lmde,jeif->ij',t2_1_ab, t2_1_ab, v2e_ovov_ab , optimize = True)\n        M_ij_a +=0.5*np.einsum('lmdf,lmde,jeif->ij',t2_1_b, t2_1_b, v2e_ovov_ab , optimize = True)\n\n        M_ij_b += 0.5*np.einsum('lmdf,lmde,jeif->ij',t2_1_b, t2_1_b, v2e_ovov_b , optimize = True)\n        M_ij_b +=np.einsum('lmdf,lmde,jeif->ij',t2_1_ab, t2_1_ab, v2e_ovov_b , optimize = True)\n        M_ij_b +=np.einsum('lmfd,lmed,ejfi->ij',t2_1_ab, t2_1_ab, v2e_vovo_ab , optimize = True)\n        M_ij_b +=0.5*np.einsum('lmdf,lmde,ejfi->ij',t2_1_a, t2_1_a, v2e_vovo_ab , optimize = True)\n\n        M_ij_a -= np.einsum('ilde,jmdf,flem->ij',t2_1_a, t2_1_a, v2e_vovo_a, optimize = True)\n        M_ij_a += np.einsum('ilde,jmdf,lfem->ij',t2_1_a, t2_1_ab, v2e_ovvo_ab, optimize = True)\n        M_ij_a += np.einsum('ilde,jmdf,flme->ij',t2_1_ab, t2_1_a, v2e_voov_ab, optimize = True)\n        M_ij_a -= np.einsum('ilde,jmdf,flem->ij',t2_1_ab, t2_1_ab, v2e_vovo_b, optimize = True)\n        M_ij_a -= np.einsum('iled,jmfd,flem->ij',t2_1_ab, t2_1_ab, v2e_vovo_ab, optimize = True)\n\n        M_ij_b -= np.einsum('ilde,jmdf,flem->ij',t2_1_b, t2_1_b, v2e_vovo_b, optimize = True)\n        M_ij_b += np.einsum('ilde,mjfd,flme->ij',t2_1_b, t2_1_ab, v2e_voov_ab, optimize = True)\n        M_ij_b += np.einsum('lied,jmdf,lfem->ij',t2_1_ab, t2_1_b, v2e_ovvo_ab, optimize = True)\n        M_ij_b -= np.einsum('lied,mjfd,flem->ij',t2_1_ab, t2_1_ab, v2e_vovo_a, optimize = True)\n        M_ij_b -= np.einsum('lide,mjdf,lfme->ij',t2_1_ab, t2_1_ab, v2e_ovov_ab, optimize = True)\n\n        M_ij_a -= 0.5*np.einsum('lnde,lmde,jnim->ij',t2_1_a, t2_1_a, v2e_oooo_a, optimize = True)\n        M_ij_a -= np.einsum('nled,mled,jnim->ij',t2_1_ab, t2_1_ab, v2e_oooo_a, optimize = True)\n        M_ij_a -= np.einsum('lnde,lmde,jnim->ij',t2_1_ab, t2_1_ab, v2e_oooo_ab, optimize = True)\n        M_ij_a -= 0.5 * np.einsum('lnde,lmde,jnim->ij',t2_1_b, t2_1_b, v2e_oooo_ab, optimize = True)\n\n        M_ij_b -= 0.5*np.einsum('lnde,lmde,jnim->ij',t2_1_b, t2_1_b, v2e_oooo_b, optimize = True)\n        M_ij_b -= np.einsum('lnde,lmde,jnim->ij',t2_1_ab, t2_1_ab, v2e_oooo_b, optimize = True)\n        M_ij_b -= np.einsum('nled,mled,njmi->ij',t2_1_ab, t2_1_ab, v2e_oooo_ab, optimize = True)\n        M_ij_b -= 0.5 * np.einsum('lnde,lmde,njmi->ij',t2_1_a, t2_1_a, v2e_oooo_ab, optimize = True)\n\n    M_ij = (M_ij_a, M_ij_b)\n\n    return M_ij\n\ndef ea_adc_diag(adc,M_ab=None):\n\n    if M_ab is None:\n        M_ab = adc.get_imds()\n\n    M_ab_a, M_ab_b = M_ab[0], M_ab[1]\n\n    nocc_a = adc.nocc_a\n    nocc_b = adc.nocc_b\n    nvir_a = adc.nvir_a\n    nvir_b = adc.nvir_b\n\n    n_singles_a = nvir_a\n    n_singles_b = nvir_b\n    n_doubles_aaa = nvir_a * (nvir_a - 1) * nocc_a // 2\n    n_doubles_bab = nocc_b * nvir_a * nvir_b\n    n_doubles_aba = nocc_a * nvir_b * nvir_a\n    n_doubles_bbb = nvir_b * (nvir_b - 1) * nocc_b // 2\n\n    dim = n_singles_a + n_singles_b + n_doubles_aaa + n_doubles_bab + n_doubles_aba + n_doubles_bbb\n\n    e_occ_a = adc.mo_energy_a[:nocc_a]\n    e_occ_b = adc.mo_energy_b[:nocc_b]\n    e_vir_a = adc.mo_energy_a[nocc_a:]\n    e_vir_b = adc.mo_energy_b[nocc_b:]\n\n    idn_occ_a = np.identity(nocc_a)\n    idn_occ_b = np.identity(nocc_b)\n    idn_vir_a = np.identity(nvir_a)\n    idn_vir_b = np.identity(nvir_b)\n\n    ab_ind_a = np.tril_indices(nvir_a, k=-1)\n    ab_ind_b = np.tril_indices(nvir_b, k=-1)\n\n    s_a = 0\n    f_a = n_singles_a\n    s_b = f_a\n    f_b = s_b + n_singles_b\n    s_aaa = f_b\n    f_aaa = s_aaa + n_doubles_aaa\n    s_bab = f_aaa\n    f_bab = s_bab + n_doubles_bab\n    s_aba = f_bab\n    f_aba = s_aba + n_doubles_aba\n    s_bbb = f_aba\n    f_bbb = s_bbb + n_doubles_bbb\n\n    d_i_a = e_occ_a[:,None]\n    d_ab_a = e_vir_a[:,None] + e_vir_a\n    D_n_a = -d_i_a + d_ab_a.reshape(-1)\n    D_n_a = D_n_a.reshape((nocc_a,nvir_a,nvir_a))\n    D_iab_a = D_n_a.copy()[:,ab_ind_a[0],ab_ind_a[1]].reshape(-1)\n\n    d_i_b = e_occ_b[:,None]\n    d_ab_b = e_vir_b[:,None] + e_vir_b\n    D_n_b = -d_i_b + d_ab_b.reshape(-1)\n    D_n_b = D_n_b.reshape((nocc_b,nvir_b,nvir_b))\n    D_iab_b = D_n_b.copy()[:,ab_ind_b[0],ab_ind_b[1]].reshape(-1)\n\n    d_ab_ab = e_vir_a[:,None] + e_vir_b\n    d_i_b = e_occ_b[:,None]\n    D_n_bab = -d_i_b + d_ab_ab.reshape(-1)\n    D_iab_bab = D_n_bab.reshape(-1)\n\n    d_ab_ab = e_vir_b[:,None] + e_vir_a\n    d_i_a = e_occ_a[:,None]\n    D_n_aba = -d_i_a + d_ab_ab.reshape(-1)\n    D_iab_aba = D_n_aba.reshape(-1)\n\n    diag = np.zeros(dim)\n\n    # Compute precond in p1-p1 block\n\n    M_ab_a_diag = np.diagonal(M_ab_a)\n    M_ab_b_diag = np.diagonal(M_ab_b)\n\n    diag[s_a:f_a] = M_ab_a_diag.copy()\n    diag[s_b:f_b] = M_ab_b_diag.copy()\n\n    # Compute precond in 2p1h-2p1h block\n\n    diag[s_aaa:f_aaa] = D_iab_a\n    diag[s_bab:f_bab] = D_iab_bab\n    diag[s_aba:f_aba] = D_iab_aba\n    diag[s_bbb:f_bbb] = D_iab_b\n\n    return diag\n\ndef ip_adc_diag(adc,M_ij=None):\n   \n    if M_ij is None:\n        M_ij = adc.get_imds()\n\n    M_ij_a, M_ij_b = M_ij[0], M_ij[1]\n\n    nocc_a = adc.nocc_a\n    nocc_b = adc.nocc_b\n    nvir_a = adc.nvir_a\n    nvir_b = adc.nvir_b\n\n    n_singles_a = nocc_a\n    n_singles_b = nocc_b\n    n_doubles_aaa = nocc_a * (nocc_a - 1) * nvir_a // 2\n    n_doubles_bab = nvir_b * nocc_a * nocc_b\n    n_doubles_aba = nvir_a * nocc_b * nocc_a\n    n_doubles_bbb = nocc_b * (nocc_b - 1) * nvir_b // 2\n\n    dim = n_singles_a + n_singles_b + n_doubles_aaa + n_doubles_bab + n_doubles_aba + n_doubles_bbb\n\n    e_occ_a = adc.mo_energy_a[:nocc_a]\n    e_occ_b = adc.mo_energy_b[:nocc_b]\n    e_vir_a = adc.mo_energy_a[nocc_a:]\n    e_vir_b = adc.mo_energy_b[nocc_b:]\n\n    idn_occ_a = np.identity(nocc_a)\n    idn_occ_b = np.identity(nocc_b)\n    idn_vir_a = np.identity(nvir_a)\n    idn_vir_b = np.identity(nvir_b)\n\n    ij_ind_a = np.tril_indices(nocc_a, k=-1)\n    ij_ind_b = np.tril_indices(nocc_b, k=-1)\n\n    s_a = 0\n    f_a = n_singles_a\n    s_b = f_a\n    f_b = s_b + n_singles_b\n    s_aaa = f_b\n    f_aaa = s_aaa + n_doubles_aaa\n    s_bab = f_aaa\n    f_bab = s_bab + n_doubles_bab\n    s_aba = f_bab\n    f_aba = s_aba + n_doubles_aba\n    s_bbb = f_aba\n    f_bbb = s_bbb + n_doubles_bbb\n\n    d_ij_a = e_occ_a[:,None] + e_occ_a\n    d_a_a = e_vir_a[:,None]\n    D_n_a = -d_a_a + d_ij_a.reshape(-1)\n    D_n_a = D_n_a.reshape((nvir_a,nocc_a,nocc_a))\n    D_aij_a = D_n_a.copy()[:,ij_ind_a[0],ij_ind_a[1]].reshape(-1)\n\n    d_ij_b = e_occ_b[:,None] + e_occ_b\n    d_a_b = e_vir_b[:,None]\n    D_n_b = -d_a_b + d_ij_b.reshape(-1)\n    D_n_b = D_n_b.reshape((nvir_b,nocc_b,nocc_b))\n    D_aij_b = D_n_b.copy()[:,ij_ind_b[0],ij_ind_b[1]].reshape(-1)\n\n    d_ij_ab = e_occ_b[:,None] + e_occ_a\n    d_a_b = e_vir_b[:,None]\n    D_n_bab = -d_a_b + d_ij_ab.reshape(-1)\n    D_aij_bab = D_n_bab.reshape(-1)\n\n    d_ij_ab = e_occ_a[:,None] + e_occ_b\n    d_a_a = e_vir_a[:,None]\n    D_n_aba = -d_a_a + d_ij_ab.reshape(-1)\n    D_aij_aba = D_n_aba.reshape(-1)\n\n    diag = np.zeros(dim)\n\n    # Compute precond in h1-h1 block\n    M_ij_a_diag = np.diagonal(M_ij_a)\n    M_ij_b_diag = np.diagonal(M_ij_b)\n\n    diag[s_a:f_a] = M_ij_a_diag.copy()\n    diag[s_b:f_b] = M_ij_b_diag.copy()\n\n    # Compute precond in 2p1h-2p1h block\n\n    diag[s_aaa:f_aaa] = D_aij_a.copy()\n    diag[s_bab:f_bab] = D_aij_bab.copy()\n    diag[s_aba:f_aba] = D_aij_aba.copy()\n    diag[s_bbb:f_bbb] = D_aij_b.copy()\n\n    diag = -diag\n    return diag\n\ndef ea_adc_matvec(adc, M_ab=None, eris=None):\n\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    t2_1_a, t2_1_ab, t2_1_b = adc.t2[0]\n    t1_2_a, t1_2_b = adc.t1[0]\n\n    nocc_a = adc.nocc_a\n    nocc_b = adc.nocc_b\n    nvir_a = adc.nvir_a\n    nvir_b = adc.nvir_b\n\n    ab_ind_a = np.tril_indices(nvir_a, k=-1)\n    ab_ind_b = np.tril_indices(nvir_b, k=-1)\n\n    n_singles_a = nvir_a\n    n_singles_b = nvir_b\n    n_doubles_aaa = nvir_a * (nvir_a - 1) * nocc_a // 2\n    n_doubles_bab = nocc_b * nvir_a * nvir_b\n    n_doubles_aba = nocc_a * nvir_b * nvir_a\n    n_doubles_bbb = nvir_b * (nvir_b - 1) * nocc_b // 2\n\n    dim = n_singles_a + n_singles_b + n_doubles_aaa + n_doubles_bab + n_doubles_aba + n_doubles_bbb\n\n    e_occ_a = adc.mo_energy_a[:nocc_a]\n    e_occ_b = adc.mo_energy_b[:nocc_b]\n    e_vir_a = adc.mo_energy_a[nocc_a:]\n    e_vir_b = adc.mo_energy_b[nocc_b:]\n\n    idn_occ_a = np.identity(nocc_a)\n    idn_occ_b = np.identity(nocc_b)\n    idn_vir_a = np.identity(nvir_a)\n    idn_vir_b = np.identity(nvir_b)\n\n    if eris is None:\n        eris = uadc_ao2mo.transform_integrals(adc)\n\n    v2e_oovv_a,v2e_oovv_ab,v2e_oovv_b = eris.oovv\n    v2e_ooov_a,v2e_ooov_ab,v2e_ooov_b = eris.ooov\n    v2e_oooo_a,v2e_oooo_ab,v2e_oooo_b = eris.oooo\n    v2e_ovoo_a,v2e_ovoo_ab,v2e_ovoo_b = eris.ovoo\n    v2e_ovov_a,v2e_ovov_ab,v2e_ovov_b = eris.ovov\n    v2e_vvoo_a,v2e_vvoo_ab,v2e_vvoo_b = eris.vvoo\n    v2e_vvvv_a,v2e_vvvv_ab,v2e_vvvv_b = eris.vvvv\n    v2e_voov_a,v2e_voov_ab,v2e_voov_b = eris.voov\n    v2e_ovvo_a,v2e_ovvo_ab,v2e_ovvo_b = eris.ovvo\n    v2e_vovo_a,v2e_vovo_ab,v2e_vovo_b = eris.vovo\n    v2e_vvvo_a,v2e_vvvo_ab,v2e_vvvo_b = eris.vvvo\n    v2e_vovv_a,v2e_vovv_ab,v2e_vovv_b = eris.vovv\n    v2e_oovo_a,v2e_oovo_ab,v2e_oovo_b = eris.oovo\n    v2e_ovvv_a,v2e_ovvv_ab,v2e_ovvv_b = eris.ovvv\n\n    v2e_vovv_1_a = v2e_vovv_a[:][:,:,ab_ind_a[0],ab_ind_a[1]].reshape(nvir_a,-1)\n    v2e_vovv_1_b = v2e_vovv_b[:][:,:,ab_ind_b[0],ab_ind_b[1]].reshape(nvir_b,-1)\n\n    v2e_vovv_2_a = v2e_vovv_a[:][:,:,ab_ind_a[0],ab_ind_a[1]]\n    v2e_vovv_2_b = v2e_vovv_b[:][:,:,ab_ind_b[0],ab_ind_b[1]]\n\n    d_i_a = e_occ_a[:,None]\n    d_ab_a = e_vir_a[:,None] + e_vir_a\n    D_n_a = -d_i_a + d_ab_a.reshape(-1)\n    D_n_a = D_n_a.reshape((nocc_a,nvir_a,nvir_a))\n    D_iab_a = D_n_a.copy()[:,ab_ind_a[0],ab_ind_a[1]].reshape(-1)\n\n    d_i_b = e_occ_b[:,None]\n    d_ab_b = e_vir_b[:,None] + e_vir_b\n    D_n_b = -d_i_b + d_ab_b.reshape(-1)\n    D_n_b = D_n_b.reshape((nocc_b,nvir_b,nvir_b))\n    D_iab_b = D_n_b.copy()[:,ab_ind_b[0],ab_ind_b[1]].reshape(-1)\n\n    d_ab_ab = e_vir_a[:,None] + e_vir_b\n    d_i_b = e_occ_b[:,None]\n    D_n_bab = -d_i_b + d_ab_ab.reshape(-1)\n    D_iab_bab = D_n_bab.reshape(-1)\n\n    d_ab_ab = e_vir_b[:,None] + e_vir_a\n    d_i_a = e_occ_a[:,None]\n    D_n_aba = -d_i_a + d_ab_ab.reshape(-1)\n    D_iab_aba = D_n_aba.reshape(-1)\n\n    s_a = 0\n    f_a = n_singles_a\n    s_b = f_a\n    f_b = s_b + n_singles_b\n    s_aaa = f_b\n    f_aaa = s_aaa + n_doubles_aaa\n    s_bab = f_aaa\n    f_bab = s_bab + n_doubles_bab\n    s_aba = f_bab\n    f_aba = s_aba + n_doubles_aba\n    s_bbb = f_aba\n    f_bbb = s_bbb + n_doubles_bbb\n\n    if M_ab is None:\n        M_ab = adc.get_imds()\n    M_ab_a, M_ab_b = M_ab\n\n    #Calculate sigma vector\n    def sigma_(r):\n\n        s = None\n        s = np.zeros((dim))\n\n        r_a = r[s_a:f_a]\n        r_b = r[s_b:f_b]\n\n        r_aaa = r[s_aaa:f_aaa]\n        r_bab = r[s_bab:f_bab]\n        r_aba = r[s_aba:f_aba]\n        r_bbb = r[s_bbb:f_bbb]\n\n        r_aba = r_aba.reshape(nocc_a,nvir_b,nvir_a)\n        r_bab = r_bab.reshape(nocc_b,nvir_a,nvir_b)\n\n############ ADC(2) ab block ############################\n\n        s[s_a:f_a] = np.einsum('ab,b->a',M_ab_a,r_a)\n        s[s_b:f_b] = np.einsum('ab,b->a',M_ab_b,r_b)\n\n############ ADC(2) a - ibc block #########################\n\n        s[s_a:f_a] += np.einsum('ap,p->a',v2e_vovv_1_a, r_aaa, optimize = True)\n        s[s_a:f_a] += np.einsum('aibc,ibc->a', v2e_vovv_ab, r_bab, optimize = True)\n\n        s[s_b:f_b] += np.einsum('ap,p->a', v2e_vovv_1_b, r_bbb, optimize = True)\n        s[s_b:f_b] += np.einsum('iacb,ibc->a', v2e_ovvv_ab, r_aba, optimize = True)\n\n############### ADC(2) ibc - a block ############################\n\n        s[s_aaa:f_aaa] += np.einsum('aip,a->ip', v2e_vovv_2_a, r_a, optimize = True).reshape(-1)\n        s[s_bab:f_bab] += np.einsum('aibc,a->ibc', v2e_vovv_ab, r_a, optimize = True).reshape(-1)\n        s[s_aba:f_aba] += np.einsum('iacb,a->ibc', v2e_ovvv_ab, r_b, optimize = True).reshape(-1)\n        s[s_bbb:f_bbb] += np.einsum('aip,a->ip', v2e_vovv_2_b, r_b, optimize = True).reshape(-1)\n\n################ ADC(2) iab - jcd block ############################\n\n        s[s_aaa:f_aaa] += D_iab_a * r_aaa\n        s[s_bab:f_bab] += D_iab_bab * r_bab.reshape(-1)\n        s[s_aba:f_aba] += D_iab_aba * r_aba.reshape(-1)\n        s[s_bbb:f_bbb] += D_iab_b * r_bbb\n\n############### ADC(3) iab - jcd block ############################\n\n        if (method == \"adc(2)-x\" or method == \"adc(3)\"):\n\n               t2_2_a, t2_2_ab, t2_2_b = adc.t2[1]\n\n               r_aaa = r_aaa.reshape(nocc_a,-1)\n               r_bbb = r_bbb.reshape(nocc_b,-1)\n\n               r_aaa_u = np.zeros((nocc_a,nvir_a,nvir_a))\n               r_aaa_u[:,ab_ind_a[0],ab_ind_a[1]]= r_aaa.copy()\n               r_aaa_u[:,ab_ind_a[1],ab_ind_a[0]]= -r_aaa.copy()\n\n               r_bbb_u = None\n               r_bbb_u = np.zeros((nocc_b,nvir_b,nvir_b))\n               r_bbb_u[:,ab_ind_b[0],ab_ind_b[1]]= r_bbb.copy()\n               r_bbb_u[:,ab_ind_b[1],ab_ind_b[0]]= -r_bbb.copy()\n\n               #temp = 0.5*np.einsum('yxwz,izw->ixy',v2e_vvvv_a,r_aaa_u ,optimize = True)\n               #####temp = -0.5*np.einsum('yxzw,izw->ixy',v2e_vvvv_a,r_aaa_u )\n               #s[s_aaa:f_aaa] += temp[:,ab_ind_a[0],ab_ind_a[1]].reshape(-1)\n               #temp = v2e_vvvv_a[ab_ind_a[0],ab_ind_a[1],:,:]\n               #temp = temp.reshape(-1,nvir_a*nvir_a)\n               #r_aaa_t = r_aaa_u.reshape(nocc_a,-1)\n               #s[s_aaa:f_aaa] += 0.5*np.dot(r_aaa_t,temp.T).reshape(-1)\n\n               temp = v2e_vvvv_a[:].reshape(nvir_a*nvir_a,nvir_a*nvir_a)\n               r_aaa_t = r_aaa_u.reshape(nocc_a,-1)\n               temp_1 = np.dot(r_aaa_t,temp.T).reshape(nocc_a,nvir_a,nvir_a)\n               del temp\n               temp_1 = temp_1[:,ab_ind_a[0],ab_ind_a[1]]\n               s[s_aaa:f_aaa] += 0.5*temp_1.reshape(-1)\n\n               temp = v2e_vvvv_b[:].reshape(nvir_b*nvir_b,nvir_b*nvir_b)\n               r_bbb_t = r_bbb_u.reshape(nocc_b,-1)\n               temp_1 = np.dot(r_bbb_t,temp.T).reshape(nocc_b,nvir_b,nvir_b)\n               del temp\n               temp_1 = temp_1[:,ab_ind_b[0],ab_ind_b[1]]\n               s[s_bbb:f_bbb] += 0.5*temp_1.reshape(-1)\n\n               #temp = v2e_vvvv_b[ab_ind_b[0],ab_ind_b[1],:,:]\n               #temp = temp.reshape(-1,nvir_b*nvir_b)\n               #r_bbb_t = r_bbb_u.reshape(nocc_b,-1)\n               #s[s_bbb:f_bbb] += 0.5*np.dot(r_bbb_t,temp.T).reshape(-1)\n\n               #temp = 0.5*np.einsum('yxwz,izw->ixy',v2e_vvvv_b,r_bbb_u,optimize = True)\n               ########temp = -0.5*np.einsum('yxzw,izw->ixy',v2e_vvvv_b,r_bbb_u)\n               #s[s_bbb:f_bbb] += temp[:,ab_ind_b[0],ab_ind_b[1]].reshape(-1)\n\n               #s[s_bab:f_bab] += np.einsum('xyzw,izw->ixy',v2e_vvvv_ab,r_bab,optimize = True).reshape(-1)\n               #s[s_bab:f_bab] += np.einsum('xyzw,izw->ixy',v2e_vvvv_ab,r_bab).reshape(-1)\n               temp = v2e_vvvv_ab[:].reshape(nvir_a*nvir_b,nvir_a*nvir_b)\n               r_bab_t = r_bab.reshape(nocc_b,-1)\n               s[s_bab:f_bab] += np.dot(r_bab_t,temp.T).reshape(-1)\n               del temp\n\n               #s[s_aba:f_aba] += np.einsum('yxwz,izw->ixy',v2e_vvvv_ab,r_aba,optimize = True).reshape(-1)\n               #temp = v2e_vvvv_ab.transpose(3,2,1,0)\n               #temp = temp.reshape(nvir_a*nvir_b,nvir_a*nvir_b)\n               #r_aba_t = r_aba.reshape(nocc_a,-1)\n               #s[s_aba:f_aba] += np.dot(r_aba_t,temp).reshape(-1)\n\n               temp = v2e_vvvv_ab[:].reshape(nvir_a*nvir_b,nvir_a*nvir_b)\n               r_aba_t = r_aba.transpose(0,2,1).reshape(nocc_a,-1)\n               temp_1 = np.dot(r_aba_t,temp.T).reshape(nocc_a, nvir_a,nvir_b)\n               s[s_aba:f_aba] += temp_1.transpose(0,2,1).copy().reshape(-1)\n               del temp\n\n               temp = 0.5*np.einsum('yjzi,jzx->ixy',v2e_vovo_a,r_aaa_u,optimize = True)\n               temp +=0.5*np.einsum('yjiz,jxz->ixy',v2e_voov_ab,r_bab,optimize = True)\n               s[s_aaa:f_aaa] += temp[:,ab_ind_a[0],ab_ind_a[1]].reshape(-1)\n\n               s[s_bab:f_bab] -= 0.5*np.einsum('jyzi,jzx->ixy',v2e_ovvo_ab,r_aaa_u,optimize = True).reshape(-1)\n               s[s_bab:f_bab] -= 0.5*np.einsum('yjzi,jxz->ixy',v2e_vovo_b,r_bab,optimize = True).reshape(-1)\n\n               temp = 0.5*np.einsum('yjzi,jzx->ixy',v2e_vovo_b,r_bbb_u,optimize = True)\n               temp +=0.5* np.einsum('jyzi,jxz->ixy',v2e_ovvo_ab,r_aba,optimize = True)\n               s[s_bbb:f_bbb] += temp[:,ab_ind_b[0],ab_ind_b[1]].reshape(-1)\n\n               s[s_aba:f_aba] -= 0.5*np.einsum('yjzi,jxz->ixy',v2e_vovo_a,r_aba,optimize = True).reshape(-1)\n               s[s_aba:f_aba] -= 0.5*np.einsum('yjiz,jzx->ixy',v2e_voov_ab,r_bbb_u,optimize = True).reshape(-1)\n\n               temp = -0.5*np.einsum('xjzi,jzy->ixy',v2e_vovo_a,r_aaa_u,optimize = True)\n               temp -= 0.5*np.einsum('xjiz,jyz->ixy',v2e_voov_ab,r_bab,optimize = True)\n               s[s_aaa:f_aaa] += temp[:,ab_ind_a[0],ab_ind_a[1]].reshape(-1)\n\n               s[s_bab:f_bab] -=  0.5*np.einsum('xjzi,jzy->ixy',v2e_vovo_ab,r_bab,optimize = True).reshape(-1)\n\n               temp = -0.5*np.einsum('xjzi,jzy->ixy',v2e_vovo_b,r_bbb_u,optimize = True)\n               temp -= 0.5*np.einsum('jxzi,jyz->ixy',v2e_ovvo_ab,r_aba,optimize = True)\n               s[s_bbb:f_bbb] += temp[:,ab_ind_b[0],ab_ind_b[1]].reshape(-1)\n\n               s[s_aba:f_aba] -= 0.5*np.einsum('jxiz,jzy->ixy',v2e_ovov_ab,r_aba,optimize = True).reshape(-1)\n\n               temp = 0.5*np.einsum('xjwi,jyw->ixy',v2e_vovo_a,r_aaa_u,optimize = True)\n               temp -= 0.5*np.einsum('xjiw,jyw->ixy',v2e_voov_ab,r_bab,optimize = True)\n\n               s[s_aaa:f_aaa] += temp[:,ab_ind_a[0],ab_ind_a[1]].reshape(-1)\n\n               s[s_bab:f_bab] -= 0.5*np.einsum('xjwi,jwy->ixy',v2e_vovo_ab,r_bab,optimize = True).reshape(-1)\n\n               temp = 0.5*np.einsum('xjwi,jyw->ixy',v2e_vovo_b,r_bbb_u,optimize = True)\n               temp -= 0.5*np.einsum('jxwi,jyw->ixy',v2e_ovvo_ab,r_aba,optimize = True)\n               s[s_bbb:f_bbb] += temp[:,ab_ind_b[0],ab_ind_b[1]].reshape(-1)\n\n               s[s_aba:f_aba] -= 0.5*np.einsum('jxiw,jwy->ixy',v2e_ovov_ab,r_aba,optimize = True).reshape(-1)\n\n               temp = -0.5*np.einsum('yjwi,jxw->ixy',v2e_vovo_a,r_aaa_u,optimize = True)\n               temp += 0.5*np.einsum('yjiw,jxw->ixy',v2e_voov_ab,r_bab,optimize = True)\n\n               s[s_aaa:f_aaa] += temp[:,ab_ind_a[0],ab_ind_a[1]].reshape(-1)\n\n               s[s_bab:f_bab] -= 0.5*np.einsum('yjwi,jxw->ixy',v2e_vovo_b,r_bab,optimize = True).reshape(-1)\n               s[s_bab:f_bab] += 0.5*np.einsum('jywi,jxw->ixy',v2e_ovvo_ab,r_aaa_u,optimize = True).reshape(-1)\n\n               s[s_aba:f_aba] -= 0.5*np.einsum('yjwi,jxw->ixy',v2e_vovo_a,r_aba,optimize = True).reshape(-1)\n               s[s_aba:f_aba] += 0.5*np.einsum('yjiw,jxw->ixy',v2e_voov_ab,r_bbb_u,optimize = True).reshape(-1)\n\n               temp = -0.5*np.einsum('yjwi,jxw->ixy',v2e_vovo_b,r_bbb_u,optimize = True)\n               temp += 0.5*np.einsum('jywi,jxw->ixy',v2e_ovvo_ab,r_aba,optimize = True)\n               s[s_bbb:f_bbb] += temp[:,ab_ind_b[0],ab_ind_b[1]].reshape(-1)\n\n        if (method == \"adc(3)\"):\n\n            #print(\"Calculating additional terms for adc(3)\")\n\n############### ADC(3) a - ibc block ############################\n\n               #temp = -0.5*np.einsum('lmwz,lmaj->ajzw',t2_1_a,v2e_oovo_a)\n               #temp = temp[:,:,ab_ind_a[0],ab_ind_a[1]]\n               #r_aaa = r_aaa.reshape(nocc_a,-1)\n               #s[s_a:f_a] += np.einsum('ajp,jp->a',temp, r_aaa, optimize=True)\n\n               t2_1_a_t = t2_1_a[:,:,ab_ind_a[0],ab_ind_a[1]]\n               r_aaa = r_aaa.reshape(nocc_a,-1)\n               temp = 0.5*np.einsum('lmp,jp->lmj',t2_1_a_t,r_aaa)\n               s[s_a:f_a] += np.einsum('lmj,lmaj->a',temp, v2e_oovo_a, optimize=True)\n\n               temp_1 = -np.einsum('lmzw,jzw->jlm',t2_1_ab,r_bab)\n               s[s_a:f_a] -= np.einsum('jlm,lmaj->a',temp_1, v2e_oovo_ab, optimize=True)\n\n               #temp = -0.5*np.einsum('lmwz,lmaj->ajzw',t2_1_b,v2e_oovo_b)\n               #temp = temp[:,:,ab_ind_b[0],ab_ind_b[1]]\n               #r_bbb = r_bbb.reshape(nocc_b,-1)\n               #s[s_b:f_b] += np.einsum('ajp,jp->a',temp, r_bbb, optimize=True)\n\n               t2_1_b_t = t2_1_b[:,:,ab_ind_b[0],ab_ind_b[1]]\n               r_bbb = r_bbb.reshape(nocc_b,-1)\n               temp = 0.5*np.einsum('lmp,jp->lmj',t2_1_b_t,r_bbb)\n               s[s_b:f_b] += np.einsum('lmj,lmaj->a',temp, v2e_oovo_b, optimize=True)\n\n               temp_1 = -np.einsum('mlwz,jzw->jlm',t2_1_ab,r_aba)\n               s[s_b:f_b] -= np.einsum('jlm,mlja->a',temp_1, v2e_ooov_ab, optimize=True)\n\n               r_aaa_u = np.zeros((nocc_a,nvir_a,nvir_a))\n               r_aaa_u[:,ab_ind_a[0],ab_ind_a[1]]= r_aaa.copy()\n               r_aaa_u[:,ab_ind_a[1],ab_ind_a[0]]= -r_aaa.copy()\n\n               r_bbb_u = np.zeros((nocc_b,nvir_b,nvir_b))\n               r_bbb_u[:,ab_ind_b[0],ab_ind_b[1]]= r_bbb.copy()\n               r_bbb_u[:,ab_ind_b[1],ab_ind_b[0]]= -r_bbb.copy()\n\n               r_bab = r_bab.reshape(nocc_b,nvir_a,nvir_b)\n               r_aba = r_aba.reshape(nocc_a,nvir_b,nvir_a)\n\n               temp = np.zeros_like(r_bab)\n\n               temp = np.einsum('jlwd,jzw->lzd',t2_1_a,r_aaa_u,optimize=True)\n               temp += np.einsum('ljdw,jzw->lzd',t2_1_ab,r_bab,optimize=True)\n\n               temp_1 = np.zeros_like(r_bab)\n\n               temp_1 = np.einsum('jlwd,jzw->lzd',t2_1_ab,r_aaa_u,optimize=True)\n               temp_1 += np.einsum('jlwd,jzw->lzd',t2_1_b,r_bab,optimize=True)\n\n               #temp_2 = np.einsum('ljwd,jwz->lzd',t2_1_ab,r_bab)\n\n               temp_a = t2_1_ab.transpose(0,3,1,2).copy()\n               temp_b = temp_a.reshape(nocc_a*nvir_b,nocc_b*nvir_a)\n               r_bab_t = r_bab.reshape(nocc_b*nvir_a,-1)\n               temp_c = np.dot(temp_b,r_bab_t).reshape(nocc_a,nvir_b,nvir_b)\n               temp_2 = temp_c.transpose(0,2,1).copy()\n\n               s[s_a:f_a] += 0.5*np.einsum('lzd,zlad->a',temp,v2e_vovv_a,optimize=True)\n               s[s_a:f_a] += 0.5*np.einsum('lzd,zlad->a',temp_1,v2e_vovv_ab,optimize=True)\n               s[s_a:f_a] -= 0.5*np.einsum('lzd,lzad->a',temp_2,v2e_ovvv_ab,optimize=True)\n\n               temp = np.zeros_like(r_aba)\n               temp = np.einsum('jlwd,jzw->lzd',t2_1_b,r_bbb_u,optimize=True)\n               temp += np.einsum('jlwd,jzw->lzd',t2_1_ab,r_aba,optimize=True)\n\n               temp_1 = np.zeros_like(r_aba)\n               temp_1 = np.einsum('ljdw,jzw->lzd',t2_1_ab,r_bbb_u,optimize=True)\n               temp_1 += np.einsum('jlwd,jzw->lzd',t2_1_a,r_aba,optimize=True)\n\n               temp_2 = np.einsum('jldw,jwz->lzd',t2_1_ab,r_aba,optimize=True)\n\n               s[s_b:f_b] += 0.5*np.einsum('lzd,zlad->a',temp,v2e_vovv_b,optimize=True)\n               #s[s_b:f_b] += 0.5*np.einsum('lzd,lzda->a',temp_1,v2e_ovvv_ab,optimize=True)\n               temp_a = temp_1.reshape(-1)\n               temp_b = v2e_ovvv_ab[:].reshape(nocc_a*nvir_b*nvir_a,-1)\n               s[s_b:f_b] += 0.5*np.dot(temp_a,temp_b)\n               del temp_b\n               s[s_b:f_b] -= 0.5*np.einsum('lzd,zlda->a',temp_2,v2e_vovv_ab,optimize=True)\n               temp = np.zeros_like(r_bab)\n               temp = -np.einsum('jlzd,jwz->lwd',t2_1_a,r_aaa_u,optimize=True)\n               temp += -np.einsum('ljdz,jwz->lwd',t2_1_ab,r_bab,optimize=True)\n\n               temp_1 = np.zeros_like(r_bab)\n               temp_1 = -np.einsum('jlzd,jwz->lwd',t2_1_ab,r_aaa_u,optimize=True)\n               temp_1 += -np.einsum('jlzd,jwz->lwd',t2_1_b,r_bab,optimize=True)\n\n               temp_2 = -np.einsum('ljzd,jzw->lwd',t2_1_ab,r_bab,optimize=True)\n\n               s[s_a:f_a] -= 0.5*np.einsum('lwd,wlad->a',temp,v2e_vovv_a,optimize=True)\n               s[s_a:f_a] -= 0.5*np.einsum('lwd,wlad->a',temp_1,v2e_vovv_ab,optimize=True)\n               s[s_a:f_a] += 0.5*np.einsum('lwd,lwad->a',temp_2,v2e_ovvv_ab,optimize=True)\n\n               temp = np.zeros_like(r_aba)\n               temp = -np.einsum('jlzd,jwz->lwd',t2_1_b,r_bbb_u,optimize=True)\n               temp += -np.einsum('jlzd,jwz->lwd',t2_1_ab,r_aba,optimize=True)\n\n               temp_1 = np.zeros_like(r_bab)\n               temp_1 = -np.einsum('ljdz,jwz->lwd',t2_1_ab,r_bbb_u,optimize=True)\n               temp_1 += -np.einsum('jlzd,jwz->lwd',t2_1_a,r_aba,optimize=True)\n\n               temp_2 = -np.einsum('jldz,jzw->lwd',t2_1_ab,r_aba,optimize=True)\n\n               s[s_b:f_b] -= 0.5*np.einsum('lwd,wlad->a',temp,v2e_vovv_b,optimize=True)\n               #s[s_b:f_b] -= 0.5*np.einsum('lwd,lwda->a',temp_1,v2e_ovvv_ab,optimize=True)\n               temp_a = temp_1.reshape(-1)\n               temp_b = v2e_ovvv_ab[:].reshape(nocc_a*nvir_b*nvir_a,-1)\n               s[s_b:f_b] -= 0.5*np.dot(temp_a,temp_b)\n               del temp_b\n               s[s_b:f_b] += 0.5*np.einsum('lwd,wlda->a',temp_2,v2e_vovv_ab,optimize=True)\n\n################ ADC(3) ibc - a block ############################\n\n               #t2_1_a_t = t2_1_a[:,:,ab_ind_a[0],ab_ind_a[1]]\n               #temp = np.einsum('lmp,lmbi->bip',t2_1_a_t,v2e_oovo_a)\n               #s[s_aaa:f_aaa] += 0.5*np.einsum('bip,b->ip',temp, r_a, optimize=True).reshape(-1)\n\n               t2_1_a_t = t2_1_a[:,:,ab_ind_a[0],ab_ind_a[1]]\n               temp = np.einsum('b,lmbi->lmi',r_a,v2e_oovo_a)\n               s[s_aaa:f_aaa] += 0.5*np.einsum('lmi,lmp->ip',temp, t2_1_a_t, optimize=True).reshape(-1)\n\n               #temp_1 = np.einsum('lmxy,lmbi->bixy',t2_1_ab,v2e_oovo_ab)\n               #s[s_bab:f_bab] += np.einsum('bixy,b->ixy',temp_1, r_a, optimize=True).reshape(-1)\n\n               temp_1 = np.einsum('b,lmbi->lmi',r_a,v2e_oovo_ab)\n               s[s_bab:f_bab] += np.einsum('lmi,lmxy->ixy',temp_1, t2_1_ab, optimize=True).reshape(-1)\n\n               #t2_1_b_t = t2_1_b[:,:,ab_ind_b[0],ab_ind_b[1]]\n               #temp = np.einsum('lmp,lmbi->bip',t2_1_b_t,v2e_oovo_b)\n               #s[s_bbb:f_bbb] += 0.5*np.einsum('bip,b->ip',temp, r_b, optimize=True).reshape(-1)\n\n               t2_1_b_t = t2_1_b[:,:,ab_ind_b[0],ab_ind_b[1]]\n               temp = np.einsum('b,lmbi->lmi',r_b,v2e_oovo_b)\n               s[s_bbb:f_bbb] += 0.5*np.einsum('lmi,lmp->ip',temp, t2_1_b_t, optimize=True).reshape(-1)\n\n               #temp_1 = np.einsum('mlyx,mlib->bixy',t2_1_ab,v2e_ooov_ab)\n               #s[s_aba:f_aba] += np.einsum('bixy,b->ixy',temp_1, r_b, optimize=True).reshape(-1)\n\n               temp_1 = np.einsum('b,mlib->mli',r_b,v2e_ooov_ab)\n               s[s_aba:f_aba] += np.einsum('mli,mlyx->ixy',temp_1, t2_1_ab, optimize=True).reshape(-1)\n\n               temp_1 = np.einsum('xlbd,b->lxd', v2e_vovv_a,r_a,optimize=True)\n               temp_2 = np.einsum('xlbd,b->lxd', v2e_vovv_ab,r_a,optimize=True)\n\n               temp  = np.einsum('lxd,ilyd->ixy',temp_1,t2_1_a,optimize=True)\n               temp += np.einsum('lxd,ilyd->ixy',temp_2,t2_1_ab,optimize=True)\n               s[s_aaa:f_aaa] += temp[:,ab_ind_a[0],ab_ind_a[1] ].reshape(-1)\n\n               temp  = np.einsum('lxd,lidy->ixy',temp_1,t2_1_ab,optimize=True)\n               temp  += np.einsum('lxd,ilyd->ixy',temp_2,t2_1_b,optimize=True)\n               s[s_bab:f_bab] += temp.reshape(-1)\n\n               temp_1 = np.einsum('xlbd,b->lxd', v2e_vovv_b,r_b,optimize=True)\n               temp_2 = np.einsum('lxdb,b->lxd', v2e_ovvv_ab,r_b,optimize=True)\n\n               temp  = np.einsum('lxd,ilyd->ixy',temp_1,t2_1_b,optimize=True)\n               temp += np.einsum('lxd,lidy->ixy',temp_2,t2_1_ab,optimize=True)\n               s[s_bbb:f_bbb] += temp[:,ab_ind_b[0],ab_ind_b[1] ].reshape(-1)\n\n               temp  = np.einsum('lxd,ilyd->ixy',temp_1,t2_1_ab,optimize=True)\n               temp  += np.einsum('lxd,ilyd->ixy',temp_2,t2_1_a,optimize=True)\n               s[s_aba:f_aba] += temp.reshape(-1)\n\n               temp_1 = np.einsum('ylbd,b->lyd', v2e_vovv_a,r_a,optimize=True)\n               temp_2 = np.einsum('ylbd,b->lyd', v2e_vovv_ab,r_a,optimize=True)\n\n               temp  = np.einsum('lyd,ilxd->ixy',temp_1,t2_1_a,optimize=True)\n               temp += np.einsum('lyd,ilxd->ixy',temp_2,t2_1_ab,optimize=True)\n               s[s_aaa:f_aaa] -= temp[:,ab_ind_a[0],ab_ind_a[1] ].reshape(-1)\n\n               temp  = -np.einsum('lybd,b->lyd',v2e_ovvv_ab,r_a,optimize=True)\n               temp_1= -np.einsum('lyd,lixd->ixy',temp,t2_1_ab,optimize=True)\n               s[s_bab:f_bab] -= temp_1.reshape(-1)\n\n               temp_1 = np.einsum('ylbd,b->lyd', v2e_vovv_b,r_b,optimize=True)\n               temp_2 = np.einsum('lydb,b->lyd', v2e_ovvv_ab,r_b,optimize=True)\n\n               temp  = np.einsum('lyd,ilxd->ixy',temp_1,t2_1_b,optimize=True)\n               temp += np.einsum('lyd,lidx->ixy',temp_2,t2_1_ab,optimize=True)\n               s[s_bbb:f_bbb] -= temp[:,ab_ind_b[0],ab_ind_b[1] ].reshape(-1)\n\n               temp  = -np.einsum('yldb,b->lyd',v2e_vovv_ab,r_b,optimize=True)\n               temp_1= -np.einsum('lyd,ildx->ixy',temp,t2_1_ab,optimize=True)\n               s[s_aba:f_aba] -= temp_1.reshape(-1)\n\n        return s\n\n    return sigma_\n\ndef ip_adc_matvec(adc, M_ij=None, eris=None):\n\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    t2_1_a, t2_1_ab, t2_1_b = adc.t2[0]\n    t1_2_a, t1_2_b = adc.t1[0]\n\n    nocc_a = adc.nocc_a\n    nocc_b = adc.nocc_b\n    nvir_a = adc.nvir_a\n    nvir_b = adc.nvir_b\n\n    ij_ind_a = np.tril_indices(nocc_a, k=-1)\n    ij_ind_b = np.tril_indices(nocc_b, k=-1)\n\n    n_singles_a = nocc_a\n    n_singles_b = nocc_b\n    n_doubles_aaa = nocc_a * (nocc_a - 1) * nvir_a // 2\n    n_doubles_bab = nvir_b * nocc_a * nocc_b\n    n_doubles_aba = nvir_a * nocc_b * nocc_a\n    n_doubles_bbb = nocc_b * (nocc_b - 1) * nvir_b // 2\n\n    dim = n_singles_a + n_singles_b + n_doubles_aaa + n_doubles_bab + n_doubles_aba + n_doubles_bbb\n\n    e_occ_a = adc.mo_energy_a[:nocc_a]\n    e_occ_b = adc.mo_energy_b[:nocc_b]\n    e_vir_a = adc.mo_energy_a[nocc_a:]\n    e_vir_b = adc.mo_energy_b[nocc_b:]\n\n    idn_occ_a = np.identity(nocc_a)\n    idn_occ_b = np.identity(nocc_b)\n    idn_vir_a = np.identity(nvir_a)\n    idn_vir_b = np.identity(nvir_b)\n\n    if eris is None:\n        eris = uadc_ao2mo.transform_integrals(adc)\n\n    v2e_oovv_a,v2e_oovv_ab,v2e_oovv_b = eris.oovv\n    v2e_vooo_a,v2e_vooo_ab,v2e_vooo_b = eris.vooo\n    v2e_oovo_a,v2e_oovo_ab,v2e_oovo_b = eris.oovo\n    v2e_vvoo_a,v2e_vvoo_ab,v2e_vvoo_b = eris.vvoo\n    v2e_ooov_a,v2e_ooov_ab,v2e_ooov_b = eris.ooov\n    v2e_ovoo_a,v2e_ovoo_ab,v2e_ovoo_b = eris.ovoo\n    v2e_vovv_a,v2e_vovv_ab,v2e_vovv_b = eris.vovv\n    v2e_vovo_a,v2e_vovo_ab,v2e_vovo_b = eris.vovo\n    v2e_oooo_a,v2e_oooo_ab,v2e_oooo_b = eris.oooo\n    v2e_vvvo_a,v2e_vvvo_ab,v2e_vvvo_b = eris.vvvo\n    v2e_ovov_a,v2e_ovov_ab,v2e_ovov_b = eris.ovov\n    v2e_ovvv_a,v2e_ovvv_ab,v2e_ovvv_b = eris.ovvv\n    v2e_vvov_a,v2e_vvov_ab,v2e_vvov_b = eris.vvov\n    v2e_ovvo_a,v2e_ovvo_ab,v2e_ovvo_b = eris.ovvo\n    v2e_voov_a,v2e_voov_ab,v2e_voov_b = eris.voov\n\n    v2e_vooo_1_a = v2e_vooo_a[:,:,ij_ind_a[0],ij_ind_a[1]].transpose(1,0,2).reshape(nocc_a,-1)\n    v2e_vooo_1_b = v2e_vooo_b[:,:,ij_ind_b[0],ij_ind_b[1]].transpose(1,0,2).reshape(nocc_b,-1)\n\n    v2e_vooo_1_ab_a = -v2e_ovoo_ab.transpose(0,1,3,2).reshape(nocc_a, -1)\n    v2e_vooo_1_ab_b = -v2e_vooo_ab.transpose(1,0,2,3).reshape(nocc_b, -1)\n\n    v2e_oovo_1_a = v2e_oovo_a[ij_ind_a[0],ij_ind_a[1],:,:].transpose(1,0,2)\n    v2e_oovo_1_b = v2e_oovo_b[ij_ind_b[0],ij_ind_b[1],:,:].transpose(1,0,2)\n    v2e_oovo_1_ab = -v2e_ovoo_ab.transpose(1,3,2,0)\n    v2e_oovo_2_ab = -v2e_vooo_ab.transpose(0,2,3,1)\n\n    d_ij_a = e_occ_a[:,None] + e_occ_a\n    d_a_a = e_vir_a[:,None]\n    D_n_a = -d_a_a + d_ij_a.reshape(-1)\n    D_n_a = D_n_a.reshape((nvir_a,nocc_a,nocc_a))\n    D_aij_a = D_n_a.copy()[:,ij_ind_a[0],ij_ind_a[1]].reshape(-1)\n\n    d_ij_b = e_occ_b[:,None] + e_occ_b\n    d_a_b = e_vir_b[:,None]\n    D_n_b = -d_a_b + d_ij_b.reshape(-1)\n    D_n_b = D_n_b.reshape((nvir_b,nocc_b,nocc_b))\n    D_aij_b = D_n_b.copy()[:,ij_ind_b[0],ij_ind_b[1]].reshape(-1)\n\n    d_ij_ab = e_occ_b[:,None] + e_occ_a\n    d_a_b = e_vir_b[:,None]\n    D_n_bab = -d_a_b + d_ij_ab.reshape(-1)\n    D_aij_bab = D_n_bab.reshape(-1)\n\n    d_ij_ab = e_occ_a[:,None] + e_occ_b\n    d_a_a = e_vir_a[:,None]\n    D_n_aba = -d_a_a + d_ij_ab.reshape(-1)\n    D_aij_aba = D_n_aba.reshape(-1)\n    s_a = 0\n    f_a = n_singles_a\n    s_b = f_a\n    f_b = s_b + n_singles_b\n    s_aaa = f_b\n    f_aaa = s_aaa + n_doubles_aaa\n    s_bab = f_aaa\n    f_bab = s_bab + n_doubles_bab\n    s_aba = f_bab\n    f_aba = s_aba + n_doubles_aba\n    s_bbb = f_aba\n    f_bbb = s_bbb + n_doubles_bbb\n\n    if M_ij is None:\n        M_ij = adc.get_imds()\n    M_ij_a, M_ij_b = M_ij\n\n    #Calculate sigma vector\n    def sigma_(r):\n\n        s = np.zeros((dim))\n\n        r_a = r[s_a:f_a]\n        r_b = r[s_b:f_b]\n        r_aaa = r[s_aaa:f_aaa]\n        r_bab = r[s_bab:f_bab]\n        r_aba = r[s_aba:f_aba]\n        r_bbb = r[s_bbb:f_bbb]\n\n        #r_bab = r_bab.reshape(nvir_b,nocc_a,nocc_b)\n\n############ ADC(2) ij block ############################\n\n        s[s_a:f_a] = np.einsum('ij,j->i',M_ij_a,r_a)\n        s[s_b:f_b] = np.einsum('ij,j->i',M_ij_b,r_b)\n\n############ ADC(2) i - kja block #########################\n\n        s[s_a:f_a] += np.einsum('ip,p->i', v2e_vooo_1_a, r_aaa, optimize = True)\n        s[s_a:f_a] -= np.einsum('ip,p->i', v2e_vooo_1_ab_a, r_bab, optimize = True)\n\n        s[s_b:f_b] += np.einsum('ip,p->i', v2e_vooo_1_b, r_bbb, optimize = True)\n        s[s_b:f_b] -= np.einsum('ip,p->i', v2e_vooo_1_ab_b, r_aba, optimize = True)\n\n################ ADC(2) ajk - i block ############################\n\n        s[s_aaa:f_aaa] += np.einsum('api,i->ap', v2e_oovo_1_a, r_a, optimize = True).reshape(-1)\n        s[s_bab:f_bab] -= np.einsum('ajki,i->ajk', v2e_oovo_1_ab, r_a, optimize = True).reshape(-1)\n        s[s_aba:f_aba] -= np.einsum('ajki,i->ajk', v2e_oovo_2_ab, r_b, optimize = True).reshape(-1)\n        s[s_bbb:f_bbb] += np.einsum('api,i->ap', v2e_oovo_1_b, r_b, optimize = True).reshape(-1)\n\n################ ADC(2) ajk - bil block ############################\n\n        s[s_aaa:f_aaa] += D_aij_a * r_aaa\n        s[s_bab:f_bab] += D_aij_bab * r_bab.reshape(-1)\n        s[s_aba:f_aba] += D_aij_aba * r_aba.reshape(-1)\n        s[s_bbb:f_bbb] += D_aij_b * r_bbb\n\n############### ADC(3) ajk - bil block ############################\n\n        if (method == \"adc(2)-x\" or method == \"adc(3)\"):\n\n               t2_2_a, t2_2_ab, t2_2_b = adc.t2[1]\n\n              #print(\"Calculating additional terms for adc(2)-e\")\n\n               r_aaa = r_aaa.reshape(nvir_a,-1)\n               r_bab = r_bab.reshape(nvir_b,nocc_b,nocc_a)\n               r_aba = r_aba.reshape(nvir_a,nocc_a,nocc_b)\n               r_bbb = r_bbb.reshape(nvir_b,-1)\n\n               r_aaa_u = None\n               r_aaa_u = np.zeros((nvir_a,nocc_a,nocc_a))\n               r_aaa_u[:,ij_ind_a[0],ij_ind_a[1]]= r_aaa.copy()\n               r_aaa_u[:,ij_ind_a[1],ij_ind_a[0]]= -r_aaa.copy()\n\n               r_bbb_u = None\n               r_bbb_u = np.zeros((nvir_b,nocc_b,nocc_b))\n               r_bbb_u[:,ij_ind_b[0],ij_ind_b[1]]= r_bbb.copy()\n               r_bbb_u[:,ij_ind_b[1],ij_ind_b[0]]= -r_bbb.copy()\n\n               temp = 0.5*np.einsum('jkli,ail->ajk',v2e_oooo_a,r_aaa_u ,optimize = True)\n               s[s_aaa:f_aaa] += temp[:,ij_ind_a[0],ij_ind_a[1]].reshape(-1)\n\n               temp = 0.5*np.einsum('jkli,ail->ajk',v2e_oooo_b,r_bbb_u,optimize = True)\n               s[s_bbb:f_bbb] += temp[:,ij_ind_b[0],ij_ind_b[1]].reshape(-1)\n\n               s[s_bab:f_bab] -= 0.5*np.einsum('kjil,ali->ajk',v2e_oooo_ab,r_bab,optimize = True).reshape(-1)\n               s[s_bab:f_bab] -= 0.5*np.einsum('kjli,ail->ajk',v2e_oooo_ab,r_bab,optimize = True).reshape(-1)\n\n               s[s_aba:f_aba] -= 0.5*np.einsum('jkli,ali->ajk',v2e_oooo_ab,r_aba,optimize = True).reshape(-1)\n               s[s_aba:f_aba] -= 0.5*np.einsum('jkil,ail->ajk',v2e_oooo_ab,r_aba,optimize = True).reshape(-1)\n\n               temp = 0.5*np.einsum('bkal,bjl->ajk',v2e_vovo_a,r_aaa_u,optimize = True)\n               temp += 0.5* np.einsum('kbal,blj->ajk',v2e_ovvo_ab,r_bab,optimize = True)\n\n               s[s_aaa:f_aaa] += temp[:,ij_ind_a[0],ij_ind_a[1]].reshape(-1)\n\n               s[s_bab:f_bab] += 0.5*np.einsum('kbla,bjl->ajk',v2e_ovov_ab,r_bab,optimize = True).reshape(-1)\n\n               temp_1 = 0.5*np.einsum('bkal,bjl->ajk',v2e_vovo_b,r_bbb_u,optimize = True)\n               temp_1 += 0.5*np.einsum('bkla,blj->ajk',v2e_voov_ab,r_aba,optimize = True)\n\n               s[s_bbb:f_bbb] += temp_1[:,ij_ind_b[0],ij_ind_b[1]].reshape(-1)\n\n               s[s_aba:f_aba] += 0.5*np.einsum('bkal,bjl->ajk',v2e_vovo_ab,r_aba,optimize = True).reshape(-1)\n\n               temp = -0.5*np.einsum('bjal,bkl->ajk',v2e_vovo_a,r_aaa_u,optimize = True)\n               temp -= 0.5*np.einsum('jbal,blk->ajk',v2e_ovvo_ab,r_bab,optimize = True)\n\n               s[s_aaa:f_aaa] += temp[:,ij_ind_a[0],ij_ind_a[1]].reshape(-1)\n\n               s[s_bab:f_bab] +=  0.5*np.einsum('bjla,bkl->ajk',v2e_voov_ab,r_aaa_u,optimize = True).reshape(-1)\n               s[s_bab:f_bab] +=  0.5*np.einsum('bjal,blk->ajk',v2e_vovo_b,r_bab,optimize = True).reshape(-1)\n\n               temp = -0.5*np.einsum('bjal,bkl->ajk',v2e_vovo_b,r_bbb_u,optimize = True)\n               temp -= 0.5*np.einsum('bjla,blk->ajk',v2e_voov_ab,r_aba,optimize = True)\n\n               s[s_bbb:f_bbb] += temp[:,ij_ind_b[0],ij_ind_b[1]].reshape(-1)\n\n               s[s_aba:f_aba] += 0.5*np.einsum('bjal,blk->ajk',v2e_vovo_a,r_aba,optimize = True).reshape(-1)\n               s[s_aba:f_aba] += 0.5*np.einsum('jbal,bkl->ajk',v2e_ovvo_ab,r_bbb_u,optimize = True).reshape(-1)\n\n               temp = -0.5*np.einsum('bkai,bij->ajk',v2e_vovo_a,r_aaa_u,optimize = True)\n               temp += 0.5*np.einsum('kbai,bij->ajk',v2e_ovvo_ab,r_bab,optimize = True)\n\n               s[s_aaa:f_aaa] += temp[:,ij_ind_a[0],ij_ind_a[1]].reshape(-1)\n\n               s[s_bab:f_bab] += 0.5*np.einsum('kbia,bji->ajk',v2e_ovov_ab,r_bab,optimize = True).reshape(-1)\n\n               temp = -0.5*np.einsum('bkai,bij->ajk',v2e_vovo_b,r_bbb_u,optimize = True)\n               temp += 0.5*np.einsum('bkia,bij->ajk',v2e_voov_ab,r_aba,optimize = True)\n\n               s[s_bbb:f_bbb] += temp[:,ij_ind_b[0],ij_ind_b[1]].reshape(-1)\n\n               s[s_aba:f_aba] += 0.5*np.einsum('bkai,bji->ajk',v2e_vovo_ab,r_aba,optimize = True).reshape(-1)\n\n               temp = 0.5*np.einsum('bjai,bik->ajk',v2e_vovo_a,r_aaa_u,optimize = True)\n               temp -= 0.5*np.einsum('jbai,bik->ajk',v2e_ovvo_ab,r_bab,optimize = True)\n\n               s[s_aaa:f_aaa] += temp[:,ij_ind_a[0],ij_ind_a[1]].reshape(-1)\n\n               s[s_bab:f_bab] += 0.5*np.einsum('bjai,bik->ajk',v2e_vovo_b,r_bab,optimize = True).reshape(-1)\n               s[s_bab:f_bab] -= 0.5*np.einsum('bjia,bik->ajk',v2e_voov_ab,r_aaa_u,optimize = True).reshape(-1)\n\n               s[s_aba:f_aba] += 0.5*np.einsum('bjai,bik->ajk',v2e_vovo_a,r_aba,optimize = True).reshape(-1)\n               s[s_aba:f_aba] -= 0.5*np.einsum('jbai,bik->ajk',v2e_ovvo_ab,r_bbb_u,optimize = True).reshape(-1)\n\n               temp = 0.5*np.einsum('bjai,bik->ajk',v2e_vovo_b,r_bbb_u,optimize = True)\n               temp -= 0.5*np.einsum('bjia,bik->ajk',v2e_voov_ab,r_aba,optimize = True)\n\n               s[s_bbb:f_bbb] += temp[:,ij_ind_b[0],ij_ind_b[1]].reshape(-1)\n\n        if (method == \"adc(3)\"):\n\n           #print(\"Calculating additional terms for adc(3)\")\n\n################ ADC(3) i - kja block ############################\n\n               #t2_1_a_t = t2_1_a[ij_ind_a[0],ij_ind_a[1],:,:]\n               #temp = np.einsum('pbc,bcai->pai',t2_1_a_t,v2e_vvvo_a)\n               #r_aaa = r_aaa.reshape(nvir_a,-1)\n               #s[s_a:f_a] += 0.5*np.einsum('pai,ap->i',temp, r_aaa, optimize=True)\n\n               r_aaa = r_aaa.reshape(nvir_a,-1)\n               t2_1_a_t = t2_1_a[ij_ind_a[0],ij_ind_a[1],:,:].copy()\n               temp = np.einsum('pbc,ap->abc',t2_1_a_t,r_aaa, optimize=True)\n               s[s_a:f_a] += 0.5*np.einsum('abc,bcai->i',temp, v2e_vvvo_a, optimize=True)\n\n               temp_1 = np.einsum('kjcb,ajk->abc',t2_1_ab,r_bab, optimize=True)\n               s[s_a:f_a] += np.einsum('abc,cbia->i',temp_1, v2e_vvov_ab, optimize=True)\n\n               #t2_1_b_t = t2_1_b[ij_ind_b[0],ij_ind_b[1],:,:]\n               #temp = np.einsum('pbc,bcai->pai',t2_1_b_t,v2e_vvvo_b)\n               #r_bbb = r_bbb.reshape(nvir_b,-1)\n               #s[s_b:f_b] += 0.5*np.einsum('pai,ap->i',temp, r_bbb, optimize=True)\n\n               r_bbb = r_bbb.reshape(nvir_b,-1)\n               t2_1_b_t = t2_1_b[ij_ind_b[0],ij_ind_b[1],:,:].copy()\n               temp = np.einsum('pbc,ap->abc',t2_1_b_t,r_bbb, optimize=True)\n               s[s_b:f_b] += 0.5*np.einsum('abc,bcai->i',temp, v2e_vvvo_b, optimize=True)\n\n               temp_1 = np.einsum('jkbc,ajk->abc',t2_1_ab,r_aba, optimize=True)\n               s[s_b:f_b] += np.einsum('abc,bcai->i',temp_1, v2e_vvvo_ab, optimize=True)\n\n               r_aaa_u = np.zeros((nvir_a,nocc_a,nocc_a))\n               r_aaa_u[:,ij_ind_a[0],ij_ind_a[1]]= r_aaa.copy()\n               r_aaa_u[:,ij_ind_a[1],ij_ind_a[0]]= -r_aaa.copy()\n\n               r_bbb_u = np.zeros((nvir_b,nocc_b,nocc_b))\n               r_bbb_u[:,ij_ind_b[0],ij_ind_b[1]]= r_bbb.copy()\n               r_bbb_u[:,ij_ind_b[1],ij_ind_b[0]]= -r_bbb.copy()\n\n               r_bab = r_bab.reshape(nvir_b,nocc_b,nocc_a)\n               r_aba = r_aba.reshape(nvir_a,nocc_a,nocc_b)\n\n               temp = np.zeros_like(r_bab)\n               temp = np.einsum('jlab,ajk->blk',t2_1_a,r_aaa_u,optimize=True)\n               temp += np.einsum('ljba,ajk->blk',t2_1_ab,r_bab,optimize=True)\n\n               temp_1 = np.zeros_like(r_bab)\n               temp_1 = np.einsum('jlab,ajk->blk',t2_1_ab,r_aaa_u,optimize=True)\n               temp_1 += np.einsum('jlab,ajk->blk',t2_1_b,r_bab,optimize=True)\n\n               temp_2 = np.einsum('jlba,akj->blk',t2_1_ab,r_bab, optimize=True)\n\n               s[s_a:f_a] += 0.5*np.einsum('blk,ilkb->i',temp,v2e_ooov_a,optimize=True)\n               s[s_a:f_a] += 0.5*np.einsum('blk,ilkb->i',temp_1,v2e_ooov_ab,optimize=True)\n               s[s_a:f_a] -= 0.5*np.einsum('blk,ilbk->i',temp_2,v2e_oovo_ab,optimize=True)\n\n               temp = np.zeros_like(r_aba)\n               temp = np.einsum('jlab,ajk->blk',t2_1_b,r_bbb_u,optimize=True)\n               temp += np.einsum('jlab,ajk->blk',t2_1_ab,r_aba,optimize=True)\n\n               temp_1 = np.zeros_like(r_aba)\n               temp_1 = np.einsum('ljba,ajk->blk',t2_1_ab,r_bbb_u,optimize=True)\n               temp_1 += np.einsum('jlab,ajk->blk',t2_1_a,r_aba,optimize=True)\n\n               temp_2 = np.einsum('ljab,akj->blk',t2_1_ab,r_aba,optimize=True)\n\n               s[s_b:f_b] += 0.5*np.einsum('blk,ilkb->i',temp,v2e_ooov_b,optimize=True)\n               s[s_b:f_b] += 0.5*np.einsum('blk,libk->i',temp_1,v2e_oovo_ab,optimize=True)\n               s[s_b:f_b] -= 0.5*np.einsum('blk,likb->i',temp_2,v2e_ooov_ab,optimize=True)\n\n               temp = np.zeros_like(r_bab)\n               temp = -np.einsum('klab,akj->blj',t2_1_a,r_aaa_u,optimize=True)\n               temp -= np.einsum('lkba,akj->blj',t2_1_ab,r_bab,optimize=True)\n\n               temp_1 = np.zeros_like(r_bab)\n               temp_1 = -np.einsum('klab,akj->blj',t2_1_ab,r_aaa_u,optimize=True)\n               temp_1 -= np.einsum('klab,akj->blj',t2_1_b,r_bab,optimize=True)\n\n               temp_2 = -np.einsum('klba,ajk->blj',t2_1_ab,r_bab,optimize=True)\n\n               s[s_a:f_a] -= 0.5*np.einsum('blj,iljb->i',temp,v2e_ooov_a,optimize=True)\n               s[s_a:f_a] -= 0.5*np.einsum('blj,iljb->i',temp_1,v2e_ooov_ab,optimize=True)\n               s[s_a:f_a] += 0.5*np.einsum('blj,ilbj->i',temp_2,v2e_oovo_ab,optimize=True)\n\n               temp = np.zeros_like(r_aba)\n               temp = -np.einsum('klab,akj->blj',t2_1_b,r_bbb_u,optimize=True)\n               temp -= np.einsum('klab,akj->blj',t2_1_ab,r_aba,optimize=True)\n\n               temp_1 = np.zeros_like(r_bab)\n               temp_1 = -np.einsum('lkba,akj->blj',t2_1_ab,r_bbb_u,optimize=True)\n               temp_1 -= np.einsum('klab,akj->blj',t2_1_a,r_aba,optimize=True)\n\n               temp_2 = -np.einsum('lkab,ajk->blj',t2_1_ab,r_aba,optimize=True)\n\n               s[s_b:f_b] -= 0.5*np.einsum('blj,iljb->i',temp,v2e_ooov_b,optimize=True)\n               s[s_b:f_b] -= 0.5*np.einsum('blj,libj->i',temp_1,v2e_oovo_ab,optimize=True)\n               s[s_b:f_b] += 0.5*np.einsum('blj,lijb->i',temp_2,v2e_ooov_ab,optimize=True)\n\n################ ADC(3) ajk - i block ############################\n               #t2_1_a_t = t2_1_a[ij_ind_a[0],ij_ind_a[1],:,:]\n               #temp = 0.5*np.einsum('pbc,bcai->api',t2_1_a_t,v2e_vvvo_a)\n               #s[s_aaa:f_aaa] += np.einsum('api,i->ap',temp, r_a, optimize=True).reshape(-1)\n\n               t2_1_a_t = t2_1_a[ij_ind_a[0],ij_ind_a[1],:,:].copy()\n               temp = np.einsum('i,bcai->bca',r_a,v2e_vvvo_a,optimize=True)\n               s[s_aaa:f_aaa] += 0.5*np.einsum('bca,pbc->ap',temp,t2_1_a_t,optimize=True).reshape(-1)\n\n               #temp_1 = np.einsum('kjcb,cbia->iajk',t2_1_ab,v2e_vvov_ab)\n               #temp_1 = temp_1.reshape(nocc_a,-1)\n               #s[s_bab:f_bab] += np.einsum('ip,i->p',temp_1, r_a, optimize=True).reshape(-1)\n\n               temp_1 = np.einsum('i,cbia->cba',r_a,v2e_vvov_ab,optimize=True)\n               s[s_bab:f_bab] += np.einsum('cba,kjcb->ajk',temp_1, t2_1_ab, optimize=True).reshape(-1)\n\n               #t2_1_b_t = t2_1_b[ij_ind_b[0],ij_ind_b[1],:,:]\n               #temp = 0.5*np.einsum('pbc,bcai->api',t2_1_b_t,v2e_vvvo_b)\n               #s[s_bbb:f_bbb] += np.einsum('api,i->ap',temp, r_b, optimize=True).reshape(-1)\n\n               t2_1_b_t = t2_1_b[ij_ind_b[0],ij_ind_b[1],:,:].copy()\n               temp = np.einsum('i,bcai->bca',r_b,v2e_vvvo_b,optimize=True)\n               s[s_bbb:f_bbb] += 0.5*np.einsum('bca,pbc->ap',temp,t2_1_b_t,optimize=True).reshape(-1)\n\n               #temp_1 = np.einsum('jkbc,bcai->iajk',t2_1_ab,v2e_vvvo_ab)\n               #temp_1 = temp_1.reshape(nocc_b,-1)\n               #s[s_aba:f_aba] += np.einsum('ip,i->p',temp_1, r_b, optimize=True).reshape(-1)\n\n               temp_1 = np.einsum('i,bcai->bca',r_b,v2e_vvvo_ab,optimize=True)\n               s[s_aba:f_aba] += np.einsum('bca,jkbc->ajk',temp_1, t2_1_ab, optimize=True).reshape(-1)\n\n               temp_1 = np.einsum('i,kbil->kbl',r_a, v2e_ovoo_a)\n               temp_2 = np.einsum('i,kbil->kbl',r_a, v2e_ovoo_ab)\n\n               temp  = np.einsum('kbl,jlab->ajk',temp_1,t2_1_a,optimize=True)\n               temp += np.einsum('kbl,jlab->ajk',temp_2,t2_1_ab,optimize=True)\n               s[s_aaa:f_aaa] += temp[:,ij_ind_a[0],ij_ind_a[1] ].reshape(-1)\n\n               temp_1  = np.einsum('i,kbil->kbl',r_a,v2e_ovoo_a)\n               temp_2  = np.einsum('i,kbil->kbl',r_a,v2e_ovoo_ab)\n\n               temp  = np.einsum('kbl,ljba->ajk',temp_1,t2_1_ab,optimize=True)\n               temp += np.einsum('kbl,jlab->ajk',temp_2,t2_1_b,optimize=True)\n               s[s_bab:f_bab] += temp.reshape(-1)\n\n               temp_1 = np.einsum('i,kbil->kbl',r_b, v2e_ovoo_b)\n               temp_2 = np.einsum('i,bkli->kbl',r_b, v2e_vooo_ab)\n\n               temp  = np.einsum('kbl,jlab->ajk',temp_1,t2_1_b,optimize=True)\n               temp += np.einsum('kbl,ljba->ajk',temp_2,t2_1_ab,optimize=True)\n               s[s_bbb:f_bbb] += temp[:,ij_ind_b[0],ij_ind_b[1] ].reshape(-1)\n\n               temp_1  = np.einsum('i,kbil->kbl',r_b,v2e_ovoo_b)\n               temp_2  = np.einsum('i,bkli->kbl',r_b,v2e_vooo_ab)\n\n               temp  = np.einsum('kbl,jlab->ajk',temp_1,t2_1_ab,optimize=True)\n               temp += np.einsum('kbl,jlab->ajk',temp_2,t2_1_a,optimize=True)\n               s[s_aba:f_aba] += temp.reshape(-1)\n\n               temp_1 = np.einsum('i,jbil->jbl',r_a, v2e_ovoo_a)\n               temp_2 = np.einsum('i,jbil->jbl',r_a, v2e_ovoo_ab)\n\n               temp  = np.einsum('jbl,klab->ajk',temp_1,t2_1_a,optimize=True)\n               temp += np.einsum('jbl,klab->ajk',temp_2,t2_1_ab,optimize=True)\n               s[s_aaa:f_aaa] -= temp[:,ij_ind_a[0],ij_ind_a[1] ].reshape(-1)\n\n               temp  = -np.einsum('i,bjil->jbl',r_a,v2e_vooo_ab,optimize=True)\n               temp_1 = -np.einsum('jbl,klba->ajk',temp,t2_1_ab,optimize=True)\n               s[s_bab:f_bab] -= temp_1.reshape(-1)\n\n               temp_1 = np.einsum('i,jbil->jbl',r_b, v2e_ovoo_b)\n               temp_2 = np.einsum('i,bjli->jbl',r_b, v2e_vooo_ab)\n\n               temp  = np.einsum('jbl,klab->ajk',temp_1,t2_1_b,optimize=True)\n               temp += np.einsum('jbl,lkba->ajk',temp_2,t2_1_ab,optimize=True)\n               s[s_bbb:f_bbb] -= temp[:,ij_ind_b[0],ij_ind_b[1] ].reshape(-1)\n\n               temp  = -np.einsum('i,jbli->jbl',r_b,v2e_ovoo_ab,optimize=True)\n               temp_1 = -np.einsum('jbl,lkab->ajk',temp,t2_1_ab,optimize=True)\n               s[s_aba:f_aba] -= temp_1.reshape(-1)\n\n        s *= -1.0\n\n        return s\n\n    return sigma_\n\ndef ea_compute_trans_moments(adc, orb, eris=None, spin=\"alpha\"):\n\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    t2_1_a, t2_1_ab, t2_1_b = adc.t2[0]\n    t1_2_a, t1_2_b = adc.t1[0]\n\n    nocc_a = adc.nocc_a\n    nocc_b = adc.nocc_b\n    nvir_a = adc.nvir_a\n    nvir_b = adc.nvir_b\n\n    ab_ind_a = np.tril_indices(nvir_a, k=-1)\n    ab_ind_b = np.tril_indices(nvir_b, k=-1)\n\n    n_singles_a = nvir_a\n    n_singles_b = nvir_b\n    n_doubles_aaa = nvir_a* (nvir_a - 1) * nocc_a // 2\n    n_doubles_bab = nocc_b * nvir_a* nvir_b\n    n_doubles_aba = nocc_a * nvir_b* nvir_a\n    n_doubles_bbb = nvir_b* (nvir_b - 1) * nocc_b // 2\n\n    dim = n_singles_a + n_singles_b + n_doubles_aaa + n_doubles_bab + n_doubles_aba + n_doubles_bbb\n\n    idn_occ_a = np.identity(nocc_a)\n    idn_occ_b = np.identity(nocc_b)\n    idn_vir_a = np.identity(nvir_a)\n    idn_vir_b = np.identity(nvir_b)\n\n    if eris is None:\n        eris = uadc_ao2mo.transform_integrals(adc)\n\n    v2e_oovv_a , v2e_oovv_ab, v2e_oovv_b = eris.oovv\n    v2e_vvvo_a , v2e_vvvo_ab, v2e_vvvo_b = eris.vvvo\n    v2e_ovoo_a , v2e_ovoo_ab, v2e_ovoo_b = eris.ovoo\n    v2e_voov_a , v2e_voov_ab, v2e_voov_b = eris.voov\n    v2e_ovov_a , v2e_ovov_ab, v2e_ovov_b = eris.ovov\n    v2e_vovv_a , v2e_vovv_ab, v2e_vovv_b = eris.vovv\n    v2e_ooov_a , v2e_ooov_ab, v2e_ooov_b = eris.ooov\n\n    s_a = 0\n    f_a = n_singles_a\n    s_b = f_a\n    f_b = s_b + n_singles_b\n    s_aaa = f_b\n    f_aaa = s_aaa + n_doubles_aaa\n    s_bab = f_aaa\n    f_bab = s_bab + n_doubles_bab\n    s_aba = f_bab\n    f_aba = s_aba + n_doubles_aba\n    s_bbb = f_aba\n    f_bbb = s_bbb + n_doubles_bbb\n\n    T = np.zeros((dim))\n\n######## spin = alpha  ############################################\n    if spin==\"alpha\":\n######## ADC(2) part  ############################################\n\n        if orb < nocc_a:\n\n            T[s_a:f_a] = -t1_2_a[orb,:]\n\n            t2_1_t = t2_1_a[:,:,ab_ind_a[0],ab_ind_a[1]].copy()\n            t2_1_ab_t = -t2_1_ab.transpose(1,0,2,3).copy()\n\n            T[s_aaa:f_aaa] += t2_1_t[:,orb,:].reshape(-1)\n            T[s_bab:f_bab] += t2_1_ab_t[:,orb,:,:].reshape(-1)\n\n        else :\n\n            T[s_a:f_a] += idn_vir_a[(orb-nocc_a), :]\n            T[s_a:f_a] -= 0.25*np.einsum('klc,klac->a',t2_1_a[:,:,(orb-nocc_a),:], t2_1_a, optimize = True)\n            T[s_a:f_a] -= 0.25*np.einsum('klc,klac->a',t2_1_ab[:,:,(orb-nocc_a),:], t2_1_ab, optimize = True)\n            T[s_a:f_a] -= 0.25*np.einsum('lkc,lkac->a',t2_1_ab[:,:,(orb-nocc_a),:], t2_1_ab, optimize = True)\n\n######## ADC(3) 2p-1h  part  ############################################\n\n        if(method=='adc(2)-x'or method=='adc(3)'):\n\n            t2_2_a, t2_2_ab, t2_2_b = adc.t2[1]\n\n            if orb < nocc_a:\n\n                t2_2_t = t2_2_a[:,:,ab_ind_a[0],ab_ind_a[1]].copy()\n                t2_2_ab_t = -t2_2_ab.transpose(1,0,2,3).copy()\n\n                T[s_aaa:f_aaa] += t2_2_t[:,orb,:].reshape(-1)\n                T[s_bab:f_bab] += t2_2_ab_t[:,orb,:,:].reshape(-1)\n\n######### ADC(3) 1p part  ############################################\n\n        if(method=='adc(3)'):\n\n            t1_3_a, t1_3_b = adc.t1[1]\n\n            if orb < nocc_a:\n\n                T[s_a:f_a] += 0.5*np.einsum('kac,ck->a',t2_1_a[:,orb,:,:], t1_2_a.T,optimize = True)\n                T[s_a:f_a] -= 0.5*np.einsum('kac,ck->a',t2_1_ab[orb,:,:,:], t1_2_b.T,optimize = True)\n\n                T[s_a:f_a] -= t1_3_a[orb,:]\n\n            else:\n\n                T[s_a:f_a] -= 0.25*np.einsum('klc,klac->a',t2_1_a[:,:,(orb-nocc_a),:], t2_2_a, optimize = True)\n                T[s_a:f_a] -= 0.25*np.einsum('klc,klac->a',t2_1_ab[:,:,(orb-nocc_a),:], t2_2_ab, optimize = True)\n                T[s_a:f_a] -= 0.25*np.einsum('lkc,lkac->a',t2_1_ab[:,:,(orb-nocc_a),:], t2_2_ab, optimize = True)\n\n                T[s_a:f_a] -= 0.25*np.einsum('klac,klc->a',t2_1_a, t2_2_a[:,:,(orb-nocc_a),:],optimize = True)\n                T[s_a:f_a] -= 0.25*np.einsum('klac,klc->a',t2_1_ab, t2_2_ab[:,:,(orb-nocc_a),:],optimize = True)\n                T[s_a:f_a] -= 0.25*np.einsum('lkac,lkc->a',t2_1_ab, t2_2_ab[:,:,(orb-nocc_a),:],optimize = True)\n\n######### spin = beta  ############################################\n    else:\n######## ADC(2) part  ############################################\n\n\n        if orb < nocc_b:\n\n            T[s_b:f_b] = -t1_2_b[orb,:]\n\n            t2_1_t = t2_1_b[:,:,ab_ind_b[0],ab_ind_b[1]].copy()\n            t2_1_ab_t = -t2_1_ab.transpose(0,1,3,2).copy()\n\n            T[s_bbb:f_bbb] += t2_1_t[:,orb,:].reshape(-1)\n            T[s_aba:f_aba] += t2_1_ab_t[:,orb,:,:].reshape(-1)\n\n        else :\n\n            T[s_b:f_b] += idn_vir_b[(orb-nocc_b), :]\n            T[s_b:f_b] -= 0.25*np.einsum('klc,klac->a',t2_1_b[:,:,(orb-nocc_b),:], t2_1_b, optimize = True)\n            T[s_b:f_b] -= 0.25*np.einsum('lkc,lkca->a',t2_1_ab[:,:,:,(orb-nocc_b)], t2_1_ab, optimize = True)\n            T[s_b:f_b] -= 0.25*np.einsum('lkc,lkca->a',t2_1_ab[:,:,:,(orb-nocc_b)], t2_1_ab, optimize = True)\n\n######### ADC(3) 2p-1h part  ############################################\n\n        if(method=='adc(2)-x'or method=='adc(3)'):\n\n            t2_2_a, t2_2_ab, t2_2_b = adc.t2[1]\n\n            if orb < nocc_b:\n\n                t2_2_t = t2_2_b[:,:,ab_ind_b[0],ab_ind_b[1]].copy()\n                t2_2_ab_t = -t2_2_ab.transpose(0,1,3,2).copy()\n\n                T[s_bbb:f_bbb] += t2_2_t[:,orb,:].reshape(-1)\n                T[s_aba:f_aba] += t2_2_ab_t[:,orb,:,:].reshape(-1)\n\n######### ADC(2) 1p part  ############################################\n\n        if(method=='adc(3)'):\n\n            t1_3_a, t1_3_b = adc.t1[1]\n\n            if orb < nocc_b:\n\n                T[s_b:f_b] += 0.5*np.einsum('kac,ck->a',t2_1_b[:,orb,:,:], t1_2_b.T,optimize = True)\n                T[s_b:f_b] -= 0.5*np.einsum('kca,ck->a',t2_1_ab[:,orb,:,:], t1_2_a.T,optimize = True)\n\n                T[s_b:f_b] -= t1_3_b[orb,:]\n\n            else:\n\n                T[s_b:f_b] -= 0.25*np.einsum('klc,klac->a',t2_1_b[:,:,(orb-nocc_b),:], t2_2_b, optimize = True)\n                T[s_b:f_b] -= 0.25*np.einsum('lkc,lkca->a',t2_1_ab[:,:,:,(orb-nocc_b)], t2_2_ab, optimize = True)\n                T[s_b:f_b] -= 0.25*np.einsum('lkc,lkca->a',t2_1_ab[:,:,:,(orb-nocc_b)], t2_2_ab, optimize = True)\n\n                T[s_b:f_b] -= 0.25*np.einsum('klac,klc->a',t2_1_b, t2_2_b[:,:,(orb-nocc_b),:],optimize = True)\n                T[s_b:f_b] -= 0.25*np.einsum('lkca,lkc->a',t2_1_ab, t2_2_ab[:,:,:,(orb-nocc_b)],optimize = True)\n                T[s_b:f_b] -= 0.25*np.einsum('klca,klc->a',t2_1_ab, t2_2_ab[:,:,:,(orb-nocc_b)],optimize = True)\n    return T\n\ndef ip_compute_trans_moments(adc, orb, eris=None, spin=\"alpha\"):\n\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    t2_1_a, t2_1_ab, t2_1_b = adc.t2[0]\n    t1_2_a, t1_2_b = adc.t1[0]\n\n    nocc_a = adc.nocc_a\n    nocc_b = adc.nocc_b\n    nvir_a = adc.nvir_a\n    nvir_b = adc.nvir_b\n\n    ij_ind_a = np.tril_indices(nocc_a, k=-1)\n    ij_ind_b = np.tril_indices(nocc_b, k=-1)\n\n    n_singles_a = nocc_a\n    n_singles_b = nocc_b\n    n_doubles_aaa = nocc_a* (nocc_a - 1) * nvir_a // 2\n    n_doubles_bab = nvir_b * nocc_a* nocc_b\n    n_doubles_aba = nvir_a * nocc_b* nocc_a\n    n_doubles_bbb = nocc_b* (nocc_b - 1) * nvir_b // 2\n\n    dim = n_singles_a + n_singles_b + n_doubles_aaa + n_doubles_bab + n_doubles_aba + n_doubles_bbb\n\n    idn_occ_a = np.identity(nocc_a)\n    idn_occ_b = np.identity(nocc_b)\n    idn_vir_a = np.identity(nvir_a)\n    idn_vir_b = np.identity(nvir_b)\n\n    if eris is None:\n        eris = uadc_ao2mo.transform_integrals(adc)\n\n    v2e_oovv_a , v2e_oovv_ab, v2e_oovv_b = eris.oovv\n    v2e_vvvo_a , v2e_vvvo_ab, v2e_vvvo_b = eris.vvvo\n    v2e_ovoo_a , v2e_ovoo_ab, v2e_ovoo_b = eris.ovoo\n    v2e_voov_a , v2e_voov_ab, v2e_voov_b = eris.voov\n    v2e_ovov_a , v2e_ovov_ab, v2e_ovov_b = eris.ovov\n    v2e_vovv_a , v2e_vovv_ab, v2e_vovv_b = eris.vovv\n    v2e_ooov_a , v2e_ooov_ab, v2e_ooov_b = eris.ooov\n\n    s_a = 0\n    f_a = n_singles_a\n    s_b = f_a\n    f_b = s_b + n_singles_b\n    s_aaa = f_b\n    f_aaa = s_aaa + n_doubles_aaa\n    s_bab = f_aaa\n    f_bab = s_bab + n_doubles_bab\n    s_aba = f_bab\n    f_aba = s_aba + n_doubles_aba\n    s_bbb = f_aba\n    f_bbb = s_bbb + n_doubles_bbb\n\n    T = np.zeros((dim))\n\n######## spin = alpha  ############################################\n    if spin==\"alpha\":\n######## ADC(2) 1h part  ############################################\n\n        if orb < nocc_a:\n            T[s_a:f_a]  = idn_occ_a[orb, :]\n            T[s_a:f_a] += 0.25*np.einsum('kdc,ikdc->i',t2_1_a[:,orb,:,:], t2_1_a, optimize = True)\n            T[s_a:f_a] -= 0.25*np.einsum('kdc,ikdc->i',t2_1_ab[orb,:,:,:], t2_1_ab, optimize = True)\n            T[s_a:f_a] -= 0.25*np.einsum('kcd,ikcd->i',t2_1_ab[orb,:,:,:], t2_1_ab, optimize = True)\n        else :\n            T[s_a:f_a] += t1_2_a[:,(orb-nocc_a)]\n\n######## ADC(2) 2h-1p  part  ############################################\n\n            t2_1_t = t2_1_a[ij_ind_a[0],ij_ind_a[1],:,:].copy()\n            t2_1_t_a = t2_1_t.transpose(2,1,0).copy()\n            t2_1_t_ab = t2_1_ab.transpose(2,3,1,0).copy()\n\n            T[s_aaa:f_aaa] = t2_1_t_a[(orb-nocc_a),:,:].reshape(-1)\n            T[s_bab:f_bab] = t2_1_t_ab[(orb-nocc_a),:,:,:].reshape(-1)\n\n######## ADC(3) 2h-1p  part  ############################################\n\n        if(method=='adc(2)-x'or method=='adc(3)'):\n\n            t2_2_a, t2_2_ab, t2_2_b = adc.t2[1]\n\n            if orb >= nocc_a:\n                t2_2_t = t2_2_a[ij_ind_a[0],ij_ind_a[1],:,:].copy()\n                t2_2_t_a = t2_2_t.transpose(2,1,0).copy()\n                t2_2_t_ab = t2_2_ab.transpose(2,3,1,0).copy()\n\n                T[s_aaa:f_aaa] += t2_2_t_a[(orb-nocc_a),:,:].reshape(-1)\n                T[s_bab:f_bab] += t2_2_t_ab[(orb-nocc_a),:,:,:].reshape(-1)\n\n######## ADC(3) 1h part  ############################################\n\n        if(method=='adc(3)'):\n\n            t1_3_a, t1_3_b = adc.t1[1]\n\n            if orb < nocc_a:\n                T[s_a:f_a] += 0.25*np.einsum('kdc,ikdc->i',t2_1_a[:,orb,:,:], t2_2_a, optimize = True)\n                T[s_a:f_a] -= 0.25*np.einsum('kdc,ikdc->i',t2_1_ab[orb,:,:,:], t2_2_ab, optimize = True)\n                T[s_a:f_a] -= 0.25*np.einsum('kcd,ikcd->i',t2_1_ab[orb,:,:,:], t2_2_ab, optimize = True)\n\n                T[s_a:f_a] += 0.25*np.einsum('ikdc,kdc->i',t2_1_a, t2_2_a[:,orb,:,:],optimize = True)\n                T[s_a:f_a] -= 0.25*np.einsum('ikcd,kcd->i',t2_1_ab, t2_2_ab[orb,:,:,:],optimize = True)\n                T[s_a:f_a] -= 0.25*np.einsum('ikdc,kdc->i',t2_1_ab, t2_2_ab[orb,:,:,:],optimize = True)\n            else:\n                T[s_a:f_a] += 0.5*np.einsum('ikc,kc->i',t2_1_a[:,:,(orb-nocc_a),:], t1_2_a,optimize = True)\n                T[s_a:f_a] += 0.5*np.einsum('ikc,kc->i',t2_1_ab[:,:,(orb-nocc_a),:], t1_2_b,optimize = True)\n                T[s_a:f_a] += t1_3_a[:,(orb-nocc_a)]\n\n######## spin = beta  ############################################\n    else: \n######## ADC(2) 1h part  ############################################\n\n        if orb < nocc_b:\n            T[s_b:f_b] = idn_occ_b[orb, :]\n            T[s_b:f_b]+= 0.25*np.einsum('kdc,ikdc->i',t2_1_b[:,orb,:,:], t2_1_b, optimize = True)\n            T[s_b:f_b]-= 0.25*np.einsum('kdc,kidc->i',t2_1_ab[:,orb,:,:], t2_1_ab, optimize = True)\n            T[s_b:f_b]-= 0.25*np.einsum('kcd,kicd->i',t2_1_ab[:,orb,:,:], t2_1_ab, optimize = True)\n        else :\n            T[s_b:f_b] += t1_2_b[:,(orb-nocc_b)]\n\n######## ADC(2) 2h-1p part  ############################################\n\n            t2_1_t = t2_1_b[ij_ind_b[0],ij_ind_b[1],:,:].copy()\n            t2_1_t_b = t2_1_t.transpose(2,1,0).copy()\n            t2_1_t_ab = t2_1_ab.transpose(2,3,0,1).copy()\n\n            T[s_bbb:f_bbb] = t2_1_t_b[(orb-nocc_b),:,:].reshape(-1)\n            T[s_aba:f_aba] = t2_1_t_ab[:,(orb-nocc_b),:,:].reshape(-1)\n\n######## ADC(3) 2h-1p part  ############################################\n\n        if(method=='adc(2)-x'or method=='adc(3)'):\n\n            t2_2_a, t2_2_ab, t2_2_b = adc.t2[1]\n\n            if orb >= nocc_b:\n                t2_2_t = t2_2_b[ij_ind_b[0],ij_ind_b[1],:,:].copy()\n                t2_2_t_b = t2_2_t.transpose(2,1,0).copy()\n\n                t2_2_t_ab = t2_2_ab.transpose(2,3,0,1).copy()\n\n                T[s_bbb:f_bbb] += t2_2_t_b[(orb-nocc_b),:,:].reshape(-1)\n                T[s_aba:f_aba] += t2_2_t_ab[:,(orb-nocc_b),:,:].reshape(-1)\n\n######## ADC(2) 1h part  ############################################\n\n        if(method=='adc(3)'):\n\n            t1_3_a, t1_3_b = adc.t1[1]\n\n            if orb < nocc_b:\n                T[s_b:f_b] += 0.25*np.einsum('kdc,ikdc->i',t2_1_b[:,orb,:,:], t2_2_b, optimize = True)\n                T[s_b:f_b] -= 0.25*np.einsum('kdc,kidc->i',t2_1_ab[:,orb,:,:], t2_2_ab, optimize = True)\n                T[s_b:f_b] -= 0.25*np.einsum('kcd,kicd->i',t2_1_ab[:,orb,:,:], t2_2_ab, optimize = True)\n\n                T[s_b:f_b] += 0.25*np.einsum('ikdc,kdc->i',t2_1_b, t2_2_b[:,orb,:,:],optimize = True)\n                T[s_b:f_b] -= 0.25*np.einsum('kicd,kcd->i',t2_1_ab, t2_2_ab[:,orb,:,:],optimize = True)\n                T[s_b:f_b] -= 0.25*np.einsum('kidc,kdc->i',t2_1_ab, t2_2_ab[:,orb,:,:],optimize = True)\n            else:\n                T[s_b:f_b] += 0.5*np.einsum('ikc,kc->i',t2_1_b[:,:,(orb-nocc_b),:], t1_2_b,optimize = True)\n                T[s_b:f_b] += 0.5*np.einsum('kic,kc->i',t2_1_ab[:,:,:,(orb-nocc_b)], t1_2_a,optimize = True)\n                T[s_b:f_b] += t1_3_b[:,(orb-nocc_b)]\n\n    return T\n\nclass UADCEA(UADC):\n    '''unrestricted ADC for EA energies and spectroscopic amplitudes\n\n    Attributes:\n        verbose : int\n            Print level.  Default value equals to :class:`Mole.verbose`\n        max_memory : float or int\n            Allowed memory in MB.  Default value equals to :class:`Mole.max_memory`\n        incore_complete : bool\n            Avoid all I/O. Default is False.\n        method : string\n            nth-order ADC method. Options are : ADC(2), ADC(2)-X, ADC(3). Default is ADC(2). \n        conv_tol : float\n            Convergence threshold for Davidson iterations.  Default is 1e-12.\n        max_cycle : int\n            Number of Davidson iterations.  Default is 50.\n        max_space : int\n            Space size to hold trial vectors for Davidson iterative diagonalization.  Default is 12.\n\n    Kwargs:\n\tnroots : int\n\t    Number of roots (eigenvalues) requested. Default value is 1.\n\n            >>> myadc = adc.UADC(mf).run()\n            >>> myadcea = adc.UADC(myadc).run()\n\n    Saved results\n\n        e_ea : float or list of floats\n            EA energy (eigenvalue). For nroots = 1, it is a single float number. If nroots > 1, it is a list of floats for the lowest nroots eigenvalues.\n        v_ip : array\n            Eigenvectors for each EA transition.\n        p_ea : float\n            Spectroscopic amplitudes for each EA transition.\n    '''\n    def __init__(self, adc):\n        self.verbose = adc.verbose\n        self.stdout = adc.stdout\n        self.max_memory = adc.max_memory\n        self.max_space = adc.max_space\n        self.max_cycle = adc.max_cycle\n        self.conv_tol  = adc.conv_tol\n        self.t1 = adc.t1\n        self.t2 = adc.t2\n        self.e_corr = adc.e_corr\n        self.method = adc.method\n        self._scf = adc._scf\n        self._nocc = adc._nocc\n        self._nvir = adc._nvir\n        self.nocc_a = adc._nocc[0]\n        self.nocc_b = adc._nocc[1]\n        self.nvir_a = adc._nvir[0]\n        self.nvir_b = adc._nvir[1]\n        self.mo_coeff = adc.mo_coeff\n        self.mo_energy_a = adc.mo_energy_a\n        self.mo_energy_b = adc.mo_energy_b\n        self.nmo_a = adc._nmo[0]\n        self.nmo_b = adc._nmo[1]\n\n        keys = set(('e_corr', 'method', 'mo_coeff', 'mo_energy_b', 'max_memory', 't1', 'mo_energy_a', 'max_space', 't2', 'max_cycle'))\n\n        self._keys = set(self.__dict__.keys()).union(keys)\n    \n    kernel = kernel\n    get_imds = get_imds_ea\n    matvec = ea_adc_matvec\n    get_diag = ea_adc_diag\n    compute_trans_moments = ea_compute_trans_moments\n    \n    def get_init_guess(self, nroots=1, diag=None, ascending = True):\n       if diag is None :\n           diag = self.ea_adc_diag()\n       idx = None\n       if ascending:\n           idx = np.argsort(diag)\n       else:\n           idx = np.argsort(diag)[::-1]\n       guess = np.zeros((diag.shape[0], nroots))\n       min_shape = min(diag.shape[0], nroots)\n       guess[:min_shape,:min_shape] = np.identity(min_shape)\n       g = np.zeros((diag.shape[0], nroots))\n       g[idx] = guess.copy()\n       guess = []\n       for p in range(g.shape[1]):\n           guess.append(g[:,p])\n       return guess\n    \n    def gen_matvec(self, imds=None, eris=None):\n        if imds is None: imds = self.get_imds(eris)\n        diag = self.get_diag(imds)\n        matvec = self.matvec(imds, eris)\n        #matvec = lambda x: self.matvec() \n        return matvec, diag\n    \n    def get_trans_moments(self, nroots=1, eris = None):\n    \n        nmo_a  = self.nmo_a\n        nmo_b  = self.nmo_b\n    \n        T_a = []\n        T_b = []\n    \n        for orb in range(nmo_a):\n    \n                T_aa = self.compute_trans_moments(orb, eris = eris, spin = \"alpha\")\n                T_a.append(T_aa)\n    \n        for orb in range(nmo_b):\n    \n                T_bb = self.compute_trans_moments(orb, eris = eris, spin = \"beta\")\n                T_b.append(T_bb) \n        \n        return (T_a, T_b)\n\n    def get_spec_factors(self, nroots=1, T=(None,None), U=None):\n    \n        nmo_a  = self.nmo_a\n        nmo_b  = self.nmo_b\n    \n        P = np.zeros((nroots))\n    \n        T_a = T[0]\n        T_b = T[1]    \n        U = np.array(U)\n    \n        for orb in range(nmo_a):\n    \n            T_aa = T_a[orb]\n            T_aa = np.dot(T_aa, U.T)\n            if nroots == 1:\n                P += np.square(np.absolute(T_aa))\n            else :    \n                for i in range(nroots):\n                    P[i] += np.square(np.absolute(T_aa[i]))\n    \n        for orb in range(nmo_b):\n    \n            T_bb = T_b[orb]\n            T_bb = np.dot(T_bb, U.T)\n            if nroots == 1:\n                P += np.square(np.absolute(T_bb))\n            else :    \n                for i in range(nroots):\n                    P[i] += np.square(np.absolute(T_bb[i]))\n    \n        return P\n\nclass UADCIP(UADC):\n    '''unrestricted ADC for IP energies and spectroscopic amplitudes\n\n    Attributes:\n        verbose : int\n            Print level.  Default value equals to :class:`Mole.verbose`\n        max_memory : float or int\n            Allowed memory in MB.  Default value equals to :class:`Mole.max_memory`\n        incore_complete : bool\n            Avoid all I/O. Default is False.\n        method : string\n            nth-order ADC method. Options are : ADC(2), ADC(2)-X, ADC(3). Default is ADC(2). \n        conv_tol : float\n            Convergence threshold for Davidson iterations.  Default is 1e-12.\n        max_cycle : int\n            Number of Davidson iterations.  Default is 50.\n        max_space : int\n            Space size to hold trial vectors for Davidson iterative diagonalization.  Default is 12.\n\n    Kwargs:\n\tnroots : int\n\t    Number of roots (eigenvalues) requested. Default value is 1.\n\n            >>> myadc = adc.UADC(mf).run()\n            >>> myadcip = adc.UADC(myadc).run()\n\n    Saved results\n\n        e_ip : float or list of floats\n            IP energy (eigenvalue). For nroots = 1, it is a single float number. If nroots > 1, it is a list of floats for the lowest nroots eigenvalues.\n        v_ip : array\n            Eigenvectors for each IP transition.\n        p_ip : float\n            Spectroscopic amplitudes for each IP transition.\n    '''\n    def __init__(self, adc):\n        self.verbose = adc.verbose\n        self.stdout = adc.stdout\n        self.max_memory = adc.max_memory\n        self.max_space = adc.max_space\n        self.max_cycle = adc.max_cycle\n        self.conv_tol  = adc.conv_tol\n        self.t1 = adc.t1\n        self.t2 = adc.t2\n        self.e_corr = adc.e_corr\n        self.method = adc.method\n        self._scf = adc._scf\n        self._nocc = adc._nocc\n        self._nvir = adc._nvir\n        self.nocc_a = adc._nocc[0]\n        self.nocc_b = adc._nocc[1]\n        self.nvir_a = adc._nvir[0]\n        self.nvir_b = adc._nvir[1]\n        self.mo_coeff = adc.mo_coeff\n        self.mo_energy_a = adc.mo_energy_a\n        self.mo_energy_b = adc.mo_energy_b\n        self.nmo_a = adc._nmo[0]\n        self.nmo_b = adc._nmo[1]\n\n        keys = set(('e_corr', 'method', 'mo_coeff', 'mo_energy_b', 'max_memory', 't1', 'mo_energy_a', 'max_space', 't2', 'max_cycle'))\n\n        self._keys = set(self.__dict__.keys()).union(keys)\n\n    kernel = kernel\n    get_imds = get_imds_ip\n    get_diag = ip_adc_diag\n    matvec = ip_adc_matvec\n    compute_trans_moments = ip_compute_trans_moments\n\n    def get_init_guess(self, nroots=1, diag=None, ascending = True):\n       if diag is None :\n           diag = self.ea_adc_diag()\n       idx = None\n       if ascending:\n           idx = np.argsort(diag)\n       else:\n           idx = np.argsort(diag)[::-1]\n       guess = np.zeros((diag.shape[0], nroots))\n       min_shape = min(diag.shape[0], nroots)\n       guess[:min_shape,:min_shape] = np.identity(min_shape)\n       g = np.zeros((diag.shape[0], nroots))\n       g[idx] = guess.copy()\n       guess = []\n       for p in range(g.shape[1]):\n           guess.append(g[:,p])\n       return guess\n\n    def gen_matvec(self, imds=None, eris=None):\n        if imds is None: imds = self.get_imds(eris)\n        diag = self.get_diag(imds)\n        matvec = self.matvec(imds, eris)\n        #matvec = lambda x: self.matvec() \n        return matvec, diag\n\n    def get_trans_moments(self, nroots=1, eris=None):\n\n        nmo_a  = self.nmo_a\n        nmo_b  = self.nmo_b\n\n        T_a = []\n        T_b = []\n\n        for orb in range(nmo_a):\n    \n                T_aa = self.compute_trans_moments(orb, eris, spin = \"alpha\")\n                T_a.append(T_aa)\n\n        for orb in range(nmo_b):\n    \n                T_bb = self.compute_trans_moments(orb, eris, spin = \"beta\")\n                T_b.append(T_bb) \n        \n        return (T_a, T_b)\n\n    def get_spec_factors(self, nroots=1, T=(None,None), U=None):\n    \n        nmo_a  = self.nmo_a\n        nmo_b  = self.nmo_b\n    \n        P = np.zeros((nroots))\n   \n        T_a = T[0]\n        T_b = T[1]    \n        U = np.array(U)\n\n        for orb in range(nmo_a):\n\n            T_aa = T_a[orb]\n            T_aa = np.dot(T_aa, U.T)\n            if nroots == 1:\n                P += np.square(np.absolute(T_aa))\n            else :    \n                for i in range(nroots):\n                    P[i] += np.square(np.absolute(T_aa[i]))\n   \n        for orb in range(nmo_b):\n\n            T_bb = T_b[orb]\n            T_bb = np.dot(T_bb, U.T)\n            if nroots == 1:\n                P += np.square(np.absolute(T_bb))\n            else :    \n                for i in range(nroots):\n                    P[i] += np.square(np.absolute(T_bb[i]))\n\n        return P\n\n\nif __name__ == '__main__':\n    from pyscf import scf\n    from pyscf import gto\n    from pyscf import adc\n\n    r = 1.098\n    mol = gto.Mole()\n    mol.atom = [\n        ['N', ( 0., 0.    , -r/2   )],\n        ['N', ( 0., 0.    ,  r/2)],]\n    mol.basis = {'N':'aug-cc-pvdz'}\n    mol.verbose = 0\n    mol.build()\n    mf = scf.UHF(mol)\n    mf.conv_tol = 1e-12\n    mf.kernel()\n\n    myadc = adc.ADC(mf)\n    ecorr, t_amp1, t_amp2 = myadc.kernel()\n    print(ecorr -  -0.32201692499346535)\n\n    myadcip = UADCIP(myadc)\n    e,v,p = kernel(myadcip,nroots=3)\n    print(\"ADC(2) IP energies\")\n    print (e[0] - 0.5434389897908212)\n    print (e[1] - 0.5434389942222756)\n    print (e[2] - 0.6240296265084732)\n\n    print(\"ADC(2) IP spectroscopic factors\")\n    print (p[0] - 0.884404855445607)\n    print (p[1] - 0.8844048539643351)\n    print (p[2] - 0.9096460559671828)\n\n    myadcea = UADCEA(myadc)\n    e,v,p = kernel(myadcea,nroots=3)\n    print(\"ADC(2) EA energies\")\n    print (e[0] - 0.09617819143037348)\n    print (e[1] - 0.09617819161265123)\n    print (e[2] - 0.12583269048810924) \n\n    print(\"ADC(2) EA spectroscopic factors\")\n    print (p[0] - 0.991642716974455)\n    print (p[1] - 0.9916427170555298)\n    print (p[2] - 0.9817184409336244)\n\n    myadc = adc.ADC(mf)\n    myadc.method = \"adc(3)\"\n    ecorr, t_amp1, t_amp2 = myadc.kernel()\n    print(ecorr - -0.31694173142858517)\n\n    myadcip = UADCIP(myadc)\n    e,v,p = kernel(myadcip,nroots=3)\n    print(\"ADC(3) IP energies\")\n    print (e[0] - 0.5667526838174817) \n    print (e[1] - 0.5667526888293601)\n    print (e[2] - 0.6099995181296374)\n\n    print(\"ADC(3) IP spectroscopic factors\")\n    print (p[0] - 0.9086596203469742)\n    print (p[1] - 0.9086596190173993)\n    print (p[2] - 0.9214613318791076)\n\n    myadcea = UADCEA(myadc)\n    e,v,p = kernel(myadcea,nroots=3)\n\n    print(\"ADC(3) EA energies\")\n    print (e[0] - 0.09836545519235675)\n    print (e[1] - 0.09836545535587536)\n    print (e[2] - 0.12957093060942082)\n\n    print(\"ADC(3) EA spectroscopic factors\")\n    print (p[0] - 0.9920495578633931)\n    print (p[1] - 0.992049557938337)\n    print (p[2] - 0.9819274864738444)\n\n    myadc.method = \"adc(2)-x\"\n    myadc.kernel()\n\n    e,v,p = myadc.ip_adc(nroots=4)\n    print(\"ADC(2)-x IP energies\")\n    print (e[0] - 0.5405255355249104) \n    print (e[1] - 0.5405255399061982)\n    print (e[2] - 0.62080267098272)\n    print (e[3] - 0.620802670982715)\n\n    e,v,p = myadc.ea_adc(nroots=4)\n    print(\"ADC(2)-x EA energies\")\n    print (e[0] - 0.09530653292650725) \n    print (e[1] - 0.09530653311305577)\n    print (e[2] - 0.1238833077840878)\n    print (e[3] - 0.12388330873739162)\n", "meta": {"hexsha": "dced75062ea3c927c1689e20bf961c990b2fcb3c", "size": 126507, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/adc/uadc.py", "max_stars_repo_name": "azag0/pyscf", "max_stars_repo_head_hexsha": "1e3e27b61b3cfd22c9679d2c9851c13b3ebc5a1b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-03T12:32:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T08:19:02.000Z", "max_issues_repo_path": "pyscf/adc/uadc.py", "max_issues_repo_name": "azag0/pyscf", "max_issues_repo_head_hexsha": "1e3e27b61b3cfd22c9679d2c9851c13b3ebc5a1b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscf/adc/uadc.py", "max_forks_repo_name": "azag0/pyscf", "max_forks_repo_head_hexsha": "1e3e27b61b3cfd22c9679d2c9851c13b3ebc5a1b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-06-01T05:31:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T02:38:33.000Z", "avg_line_length": 44.0790940767, "max_line_length": 195, "alphanum_fraction": 0.6031840135, "include": true, "reason": "import numpy", "num_tokens": 51356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.31069437683198775, "lm_q1q2_score": 0.17823865530542465}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan  1 21:53:30 2013\n\n@author: Alex\n\"\"\"\n\nimport DataClasses as dc\nimport numpy as np\nimport copy\n\n##################################\n# Begin Electricity Built-ins\n##################################\n#Units are Ops (/MWh delivered) Const (/MW built) Fuel (/thermal MWh delivered)\ndef main():\n    sources = [dc.Source('Coal',1,.35,.6)]\n    sources[0].addOpsMode('Open-Loop',[-4,.4,.6,.8], [-4,.3,.35,.4])\n    sources[0].setLCA(0,0,[\n            [-4,580,830,1070], #NREL Harmonization\n            [33.8,0,0,0], #MJ/MWh, CED based on ecoinvent US plant average sem inf & EVoF\n            [1.1356,0,0,0], #m^3/MWh #from EPRI's 400 gal/MWh avg. + ReCiPe evaluation on RFC plants\n            [0.39e-9,0,0,0], #km^2/MWh, F&K operations\n            [49,0,0,0]]) #EIA Fixed O&M + Interest @7%,30yrs\n    sources[0].addConstMode('Pulverized',4,500)\n    sources[0].setLCA(1,0,[\n            [-5,224134,50011,0],# #kg CO2-eq/MW cap, estimated from NG\n            [-4,3.29e6,2.13e6,5.16e6],# #MJ/MW\n            [-5,2268,623,0],# #m^3/MW  needs checking\n            [-4,0.002904,.00118,.00679],# #km^2/MW, F&K based on 1000MW in 500acres (avg of their values)\n            [-3,2.8e6,3.2e6,0]])# #$/MW installed, EIA Overnight capital costs from AEO 2011\n    sources[0].addFuelMode('Surface')\n    sources[0].setLCA(2,0,[\n            [150,0,0,0],\n            [247,0,0,0],\n            [.08395,0,0,0],\n            [-4,400e-9,43e-9,840e-9], ##F&K based on 35# CU\n            [5,0,0,0]]) #EIA Fixed O&M + Interest @7%,30yrs\n    sources[0].addFuelMode('Underground')\n    sources[0].setLCA(2,1,[90,0,3.23e-5,0],0) #Water from Harvard Study\n    sources[0].setLCA(2,1,[-4,67e-9,2.3e-9,200e-9],3)\n    sources[0].addOpsMode('Closed-Loop',[-4,.2,.5,.8], [-4,.35,.3,.4])\n    sources[0].setLCA(0,1,[1.817],2)  \n    \n    sources.append(dc.Source('Natural Gas',1,.35,.35, v=2))\n    sources[1].addOpsMode('CT',[-4,.15,.35,.8], [-4,.38,.3,.45])\n    sources[1].setLCA(0,0,[\n            [500,0,0,0], #kg/MWh, data from Jaramillo\n            [48.4,0,0,0], #MJ/MWh, CED based on ecoinvent US plant average sem inf\n            [-3,.681,1.13,0], #EPRI, range covering NGCC to CT with towers\n            [30/1e9,0,0,0], #km^2/MWh, F&K (needs assumptions checked)\n            [28,0,0,0]]) #EIA Fixed O&M + Interest @7%,30yrs\n            #,0.379,1.817 for water alternatives\n    sources[-1].addOpsMode('Closed-Loop',[-4,.2,.5,.8], [-4,.35,.3,.4])\n    sources[-1].setLCA(0,1,[-3,1.1356,1.817,0],2)    \n    sources[1].addConstMode('CT', 3, 100)\n    sources[1].setLCA(1,0,[\n            [-5,4.74e4,1.76e4,0], #kg CO2-eq/MW, ecoinvent 300MWe plant\n            [-5,5.59e6,2.2e5,0], #MJ/MW, ecoinvent 300MWe plant + CED 1.08\n            [-5,281,76.7,0], #m^3/MW, ecoinvent 300MWe plant + ReCiPe H2O depletion\n            [0.001023,0,0,0], #km^2/MW, F&K inference\n            [-4,665e3,927e3,1003e3]]) #EIA Study   \n    sources[1].addFuelMode('pipeline')\n    sources[1].setLCA(2,0,[\n            [93.2,0,0,0],\n            [180,0,0,0], #Based on EROI of 20:1\n            [-4,0.037,0.018,0.054],\n            [240e-9,0,0,0],\n            [-5,3.8,.2,0]])   \n    sources[1].addFuelMode('Marcellus')\n    sources[1].setLCA(2,1,[\n            [-4,117,129,240], #Our Study, 37% efficient\n            [-4,180,197.3,900], #Our study, 90% confidence\n            [-4,0.028,0.057,0.117],#Harvard study\n            [120e-9,0,0,0]],0) #500km of pipeline\n        \n        \n        #Oil\n    sources.append(dc.Source('Oil',1,.35,.35))\n    sources[2].addOpsMode('CT',[-4,.1,.35,.4],[-4,.3,.35,.4])\n    sources[2].addConstMode('CT',3,100)\n    sources[2].addFuelMode('Pipeline')\n    sources[2].setLCA(0,0,[\n            [700,0,0,0], #kg/MWh, data from Jaramillo\n            [630,0,0,0], #MJ/MWh, CED based on ecoinvent US plant average sem inf\n            [-3,0.681,1.136,0], #EPRI, range covering NGCC to CT with towers\n            [30/1e9,0,0,0], #km^2/MWh, F&K (needs assumptions checked)\n            [30,0,0,0]]) #EIA Fixed O&M + Interest @7%,30yrs      \n    sources[-1].addOpsMode('Closed-Loop',[-4,.2,.5,.8], [-4,.35,.3,.4])\n    sources[-1].setLCA(0,1,[-3,1.136,1.817,0],2)    \n            \n    sources[2].setLCA(1,0,[\n            [5e4,0,0,0], #kg CO2-eq/MW, estimated from NG\n            [-5,7.56e5,2.2e5,0], #MJ/MW, ecoinvent 300MWe plant + CED 1.08\n            [287,0,0,0], #m^3/MW, ecoinvent 300MWe plant + ReCiPe H2O depletion\n            [0.001023,0,0,0], #km^2/MW, assumed same as NG from F&K\n            [-4,665e3,974e3,1003e3]]) #EIA Study (No one will build an oil fired plant)\n    \n    sources[2].setLCA(2,0,[\n            [93,0,0,0], #assume same as NG\n            [328,0,0,0],\n            [-4,0.9e-3,1.1e-3,1.3e-3],\n            [0,0,0,0],\n            [-5,27.73,1,0]])#estimates based on 75-91 $/bbl and .30 reference efficiency\n        \n        #Nuclear\n    sources.append(dc.Source('Nuclear',1,.35,.85))\n    sources[3].addOpsMode('Closed-Loop',[-4,.7,.85,.95],[.97,0,0,0])    \n    sources[3].setLCA(0,0,[\n            [-4,8,4,15], #kg/MWh, from F&K, baseline matches with Hondo\n            [23,0,0,0], #MJ/MWh, CED based on ecoinvent PWR sem inf and fuel\n            [-5,2.725,.15,0], #m^3/MWh 400-720gal/MWh from EPRI\n            [5/1e9,0,0,0], #km^2/MW, F&K, no fuel disposal\n            [69,0,0,0]]) #$/MWh operations, via PNE Nuclear - 5000/kW, 10# discount\n    sources[3].addOpsMode('Open-Loop',[-4,.7,.85,.95],[.97,0,0,0])\n    sources[3].setLCABase(0,1,[1.514],2)    \n    sources[3].addConstMode('Normal',10,1200)\n    sources[3].setLCA(1,0,[\n            [-4,6.64e5,2.97e5,9.978e5], # Converted from F&K using 40yrs and .85\n            [-5,1.13e7,4.98e6,0], #MJ/MW, ecoinvent 1000MWe PWR, US case\n            [3460,0,0,0], #m^3/MW, ecoinvent 1000MWe PWR, US case\n            [-4,0.00211,.00106,.00413], #km^2/MW, Angra 3 (benefits of shared inf.) F&K value of 0.016\n            [-3,4.6e6,6e6,0]]) #$/MW installed, EIA overnight costs with range from PNE    \n    sources[3].addFuelMode('Diffusion')\n    sources[3].setLCA(2,0,[\n            [-4,15,11,27], #F&K range\n            [129,0,0,0], #CED for 1MWh worth of fuel from ecoinvent\n            [-4,.351,.185,.517], #Harvard Study\n            [(30+10+3)/1e9,0,0,0], #F&K Mining and milling/GWh\n            [6.68,0,0,0]]) #NEI/DOE data       \n    sources[3].addFuelMode('Centrifuge')\n    sources[3].setLCABase(2,1,[32,0,0,6.8],1)\n        \n        #Hydro - combination of US and BR data\n    sources.append(dc.Source('Hydro',1,refCF=.55, v=3))\n    sources[-1].addFuelMode('Default')\n    sources[4].addOpsMode('Boreal',[-4,.4,.55,.7],[.97,0,0,0])\n    sources[4].addConstMode('Boreal',5,1000)\n    sources[4].setLCA(0,0,[\n            [-5,11.48,1.2,0],  #-4,29,4.3,77 kg/MWh, data from Fearnside and Rosa, 10# SD for uncertainty\n            [0.54,0,0,0], #MJ/MWh, CED based on ecoinvent US plant average sem inf\n            [-5,2.62,1,0], #m^3/MWh\n            [0,0,0,0], #km^2/MW\n            [42+2.5,0,0,0]]) #EIA Fixed O&M + Interest @7%,30yrs, + Variable O&M  \n    sources[4].setLCA(1,0,[\n            [3.91e6,0,0,0], #kg CO2-eq/MW cap, based on Ribeiro LCI for Itaipu 6.9e5 for Chinese EIO-LCA based study\n            [-5,1.52e7, 1e6,0], #MJ/MW, ecoinvent non-alpine dam (at 2500MW avg.), median Chinese, low Ribeiro, high ecoinvent\n            [9682,0,0,0], #m^3/MW, ecoinvent non-alpine (@2500MW avg.), large wet gravel usage accounts for 63# of original\n            [-5,0.3672,0.035,0], #km^2/MW weighted average of 23 BR Dams - Scenario_Data\n            [-5,2.347e6,1e5,0]]) #$/MW installed, EIA Overnight costs\n    \n        #Biomass - Brazilian Data right now\n    sources.append(dc.Source('Biomass',1,.35,.35, v=3))    \n    sources[5].addOpsMode('Upgrade',[-4,.2,.35,.5],[-3,.18,.25,0])\n    sources[5].addConstMode('Upgrade',2,50)\n    sources[5].setLCA(0,0,[\n            [25,0,0,0], #kg/MWh, Arguments of allocation from Seabra, 25 in JEPO 2011, 7 from van den Broek\n            [140,0,0,0], #MJ/MWh, 140 based on Mauritius study (about x2 NG from CED in ecoinvent)\n            [-3,1.158,1.817,0], #From EPRI's 400gal/MWh avg. (224 for Mauritius, but that is likely irrigated)\n            [9.16e-6,0,0,0], #from F&K (land is occupied even if it's not consumed) (.00203 from Mauritius - allocation?)\n            [133,0,0,0]]) #$/MWh operations, Seabra & Macedo, allocated based on value of products\n        \n    sources[5].setLCA(1,0,[\n            [4e4,0,0,0],\n            [1e6,0,0,0],\n            [300,0,0,0],\n            [0.00203,0,0,0], #(.00203 from Mauritius - allocation?)\n            [-4,100e3,200e3,700e3]])# USDA TechLine    \n    sources[5].addConstMode('New',3,50)\n    sources[5].setLCA(1,1,[[-5,3.86e6,1e5,0]],4) #EIA overnight costs\n    sources[5].addFuelMode('Wood')\n    sources[5].setLCA(2,0,[\n            [-3,48,54,0], #JEPO 2011\n            [-1,np.log(10**2.0901),.25,0],\n            [0,0,0,0], #Assumption that it's not irrigated\n            [-4,1.43e-7,2.14e-7,4.29e-7], #FromUSFS study - White, 2010 \n            [5,0,0,0]]) #Varible O&M from EIA\n        \n    #Wind: impacts per turbine (/MW direct), with number of turbines\n    #required coming from the interaction of scenario requirements.\n    sources.append(dc.Source('Wind',1,refCF=.35,v=0))    \n    sources[-1].addFuelMode('Default')\n    sources[6].addOpsMode('Onshore',[-4,.25,.32,.40],[.97,0,0,0])\n    sources[6].addOpsMode('Offshore',[-4,.35,.45,.5],[.97,0,0,0])\n    sources[6].addConstMode('Onshore',1,10)\n    sources[6].setLCA(0,0,[\n            [-4,1.3,.12,6.7], #kg/MWh\n            [4,0,0,0], #MJ/MWh, CED based on ecoinvent 800kW plant average sem inf\n            [0,0,0,0], #m^3/MWh\n            [0,0,0,0], #km^2/MW\n            [73,0,0,0]]) #$/MWh, Investment costs from PNE for hydro at 10# discount. Itaipu contract in 2009 is 113, but operations costs via INL are $7/MWh\n    sources[-1].setLCABase(0,1,[173],4)\n    \n    sources[6].setLCA(1,0,[\n            [-4,620000,190000,2300000], #kg CO2-eq/MW, offshore from ecoinvent, needs more wires\n            [-5,5.2e6,1e5,0], #MJ/MW, onshore from Lenzen & Wachsmann (BR)\n            [8.08e3,0,0,0], #m^3/MW, onshore (2MW) from ecoinvent, ReCiPe\n            [-4,0.15,.2,.25], #km^2/MW, from NREL estimates of 5MW/km2\n            [-4,2e6,2.4e6,2.8e6]]) #$/MW installed, http://www.nrel.gov/docs/fy12osti/53510.pdf\n    sources[-1].addConstMode('Offshore',2,40)\n    sources[-1].setLCA(1,1,[\n            [-4,620000,190000,2300000],\n            [-5,9.72e6,1e5,0],\n            [14.04e3,0,0,0],\n            [0,0,0,0],\n            [-4,3.59e6,4.25e6,5.9e6]]) #ARUP report on future costs\n        \n        #Solar\n        #7.19 $/MWh for hybrid plant\n      \n    sources.append(dc.Source('Solar',1,refCF=.35,v=0))  \n    sources[-1].addFuelMode('Default')\n    sources[-1].addOpsMode('PV',[-4,.18,.12,.22],[.97,0,0,0])\n    sources[-1].addOpsMode('CST0',[-4,.30,.25,.35],[-4,.37,.32,.39])\n    sources[7].addOpsMode('CST6',[-4,.45,.4,.5],[-4,.37,.32,.39])\n    sources[7].addOpsMode('CST12',[-4,.60,.5,.65],[-4,.37,.32,.39])\n    sources[-1].addConstMode('PV',1,0.05)\n    sources[-1].addConstMode('CST',2,1)\n    sources[7].addConstMode('CST6',2,1)\n    sources[7].addConstMode('CST12',2,1)\n\n    ##CST Data\n    sources[-1].setLCA(0,'CST',[\n            [10.55,0,0,0], #kg/MWh\n            [156,0,0,0], #MJ/MWh, CED based on ecoinvent US plant average sem inf\n            [4.17,0,0,0], #m^3/MWh CST\n            [0,0,0,0], #km^2/MW\n            [143,0,0,0]]) #$/MWh\n    sources[-1].setLCA(1,'CST',[\n            [1.29e6,0,0,0], #kg CO2-eq/MW, Heath\n            [2.13e7,0,0,0], #MJ/MW\n            [4.32e4,0,0,0], #m^3/MW\n            [0.00926,0,0,0], # From NREL paper by Denholm and Margolis, at 70W/m^2 including spacing for roads\n            [-5,4.7e6,2e5,0]]) #$/MW installed, PDE wind section (2000 costs adjusted by US CPI)\n\n    #PV Data\n    sources[7].setLCA(0,'PV',[\n            [2,0,0,0], #kg/MWh\n            [0,0,0,0], #MJ/MWh, CED based on ecoinvent US plant average sem inf\n            [0.12,0,0,0], #m^3/MWh PV\n            [0,0,0,0], #km^2/MW\n            [129,0,0,0]]) #$/MWh, Investment costs from PNE for hydro at 10# discount. Itaipu contract in 2009 is 113, but operations costs via INL are $7/MWh \n    sources[7].setLCA(1,'PV',[\n            [-1,6.2227,1,0], #kg CO2-eq/MW, Based on NREL Harmonization & SimaPro\n            [-5,3.23e7,1e6,0], #MJ/MW\n            [-3,236,1971,0], #m^3/MW\n            [0.014,0,0,0], # From NREL paper by Denholm and Margolis, at 70W/m^2 including spacing for roads\n            [-5,4.8e6,2e5,0]]) #$/MW installed, EIA Overnight Cost\n        \n    \n    sources[7].setLCABase(1,'CST6',[1.7e6,2.71e7,6.25e4])\n    sources[7].setLCABase(1,'CST12',[2.12e6,3.29e7,8.18e4])\n    sources[7].setLCABase(0,'Hybrid',[7.19],4)\n    \n    sources.append(dc.Source('Geothermal',1,refCF=.8,v=0))\n    sources[-1].addFuelMode('Default')\n    sources[-1].addOpsMode('Standard',[-4,.7,.8,.9],[.97,0,0,0])\n    sources[-1].setLCA(0,0,[\n            [-3,50,70,0],\n            [141,0,0,0],\n            [-3,1.136,1.817,0],\n            [0,0,0,0],\n            [54,0,0,0]]) #EIA Fixed O&M + Interest @7%,30yrs + variable O&M\n    sources[-1].addConstMode('Standard',1,10)\n    sources[-1].setLCABase(1,0,[4.141e6],4)\n    sources[-1].setLCA(1,0,[-4,.84,1.16,1.69],3)\n    \n    #######################################\n    # End of Electricity Built-ins\n    #\n    # Start of Transport Built-ins \n    #TODO split transit into passenger and freght?\n    #######################################\n    # Units are Ops (/MJ delivered) Const (/MJ/hr built) Fuel (/MJ delivered)\n    # Reference efficiency for all sources is 4.71 MJ/km (8.06 MJ/hr for a 15k \n    # driving cycle, and 17.09 mi/gge), which is assigned a\n    # capacity factor of 1. This excludes air and rail transport, which\n    # account for ~10% of total energy.\n    \n    sources.append(dc.Source('Petroleum',2, v=2))\n    sources[-1].addOpsMode('ICE',[-4,.542,.62,.72],[.97,0,0,0]) #Cfs for 31.5, 27.5 (CAFE), and 23.5 (CAFE trucks)\n    sources[-1].setLCABase(0,0,[.074,0.0753,0,0,.015]) #gwp, CED from Notter ES&T\n    sources[-1].addConstMode('ICE',1,5) #5 MJ/hr is energy requirement for 30mpg car at 10k miles/yr\n    sources[-1].setLCABase(1,0,[1360,24600,0,0,3350]) #GWP & Energy data from NOtter, ES&T 2010\n    sources[-1].setLCA(1,0,[-4,12.925,15.6,20.725],2) #Based on Volkswagon figures and 5 MJ/hr    \n    sources[-1].addOpsMode('Hyb',[-4,.33,.542,.62],[1.3,0,0,0]) #1.3 on efficiency to account for less gasoline usage\n    sources[-1].addConstMode('Hyb',1,2.63)\n    sources[-1].setLCABase(1,1,[5990,27200,0,0,3450]) #GWP & Energy data from NOtter, ES&T 2010\n    sources[-1].addFuelMode('Conventional US')\n    sources[-1].setLCABase(2,0,[.0205,.233,2.9e-5,2e-10]) #GREET, Scown\n    sources[-1].setLCA(2,0,[-5,.016,.003,0],4)\n    \n    sources.append(dc.Source('Ethanol',2, v=3))\n    sources[-1].addOpsMode('ICE',[-4,.542,.62,.72],[.97,0,0,0])\n    sources[-1].setLCABase(0,0,[.073,0.075,0,0,.018]) #Greet cost from $2000/yr operating costs for car\n    sources[-1].addConstMode('ICE',1,3.828)\n    sources[-1].setLCABase(1,0,[1360,24600,0,0,3350])\n    sources[-1].setLCA(1,0,[-4,12.925,15.6,20.725],2) #Based on Volkswagon figures and 5 MJ/hr    \n    sources[-1].addFuelMode('Corn')\n    sources[-1].setLCA(2,0,[\n            [-.0084,0,0,0],\n            [-3,1.08,1.38,0],\n            [-4,3.0e-4,4.1e-3,1.4e-2],\n            [-5,1.25e-7,1.9e-8,0],\n            [0.023,0,0,0]],0) #Greet\n    \n    sources.append(dc.Source('Biodiesel',2, v=3))\n    sources[-1].addOpsMode('ICE',[-4,.542,.62,.72],[.97,0,0,0])\n    sources[-1].setLCABase(0,0,[.072,0.075,0,0,.018])\n    sources[-1].addConstMode('ICE',1,3.828)\n    sources[-1].setLCABase(1,0,[1360,24600,0,0,3350])\n    sources[-1].setLCA(1,0,[-4,12.925,15.6,20.725],2) #Based on Volkswagon figures and 5 MJ/hr    \n    sources[-1].addFuelMode('Soybean')\n    sources[-1].setLCABase(2,0,[-.0054,.35],0) #Greet for GWP, energy from Mulder\n    sources[-1].setLCA(2,0,[\n            [-3,2.2e-2,3.4e-2,0], #Mulder 2009\n            [-5,3.3e-7,1.2e-8,0],#Dominguez-Faus 2009\n            [0.0178,0,0,0]],2) #Greet cost\n\n    sources[-1].addFuelMode('Soybean-NoIrr')\n    sources[-1].setLCA(2,1,[-3,2.2e-4,3.4e-4,0],2) #Mulder 2009/100\n            \n    sources[-1].addFuelMode('Algae')\n    sources[-1].setLCA(2,2,[\n            [-4,.156,.3,.56], #Sander + Mulder, system expansion\n            [-3,.033,.036,0], #Guieysse 2013, WF = water demanded. Yes, it's ridiculously high\n            [-5,2.5e-8,.2e-8,0]],1)\n    \n    sources.append(dc.Source('CNG',2))\n    sources[-1].addOpsMode('ICE',[-4,.542,.62,.72],[.95,0,0,0])\n    sources[-1].setLCABase(0,0,[.058,0.075,0,0,7.8e-3]) #Energy from GREET\n    sources[-1].addConstMode('ICE',1,3.828)\n    sources[-1].setLCABase(1,0,[1360,24600,0,0,3450]) #TODO assumed similar as gasoline for construction\n    sources[-1].setLCA(1,0,[-4,12.925,15.6,20.725],2) #Based on Volkswagon figures and 5 MJ/hr    \n    sources[-1].addFuelMode('Conventional US')\n    sources[-1].setLCABase(2,0,[.028,.177,0,2.67e-11,0]) \n    sources[-1].setLCA(2,0,[-4,2.3e-3,4.7e-3,7.6e-3],4) #cost is origin-blind\n    sources[-1].addFuelMode('Marcellus')\n    sources[-1].setLCABase(2,1,[.0137,.177,5.02e-6],0)\n    \n    sources.append(dc.Source('Hydrogen',2))\n    sources[-1].addOpsMode('ICE',[-4,.542,.62,.72],[1.2,0,0,0])\n    sources[-1].setLCABase(0,0,[.001],0)\n    sources[-1].addConstMode('ICE',1,3.828)\n    sources[-1].setLCABase(1,0,[1360,24600,0,0,3600]) # Costs from RAND study\n    sources[-1].setLCA(1,0,[-4,12.925,15.6,20.725],2) #Based on Volkswagon figures and 5 MJ/hr    \n    sources[-1].addFuelMode('Conventional US')\n    sources[-1].setLCABase(2,0,[.142,.820,7.27e-4,0,.0272]) #cost data in operation, GWP,CED from GREET\n    \n    sources.append(dc.Source('Electric',2))\n    sources[-1].addOpsMode('Elec',[-4,.15,.17,.2],[1.2,0,0,0])\n    sources[-1].setLCABase(0,0,[.001],0)\n    sources[-1].addConstMode('ICE',1,3.828)\n    sources[-1].setLCABase(1,0,[1360,24600,0,0,3600]) # Costs from RAND study\n    sources[-1].setLCA(1,0,[-4,12.925,15.6,20.725],2) #Based on Volkswagon figures and 5 MJ/hr    \n    sources[-1].addFuelMode('Default')\n    \n    \n    \n    #######################################\n    # End of Transport Built-ins\n    #\n    # Start of Heating Built-ins\n    #######################################\n    # Heating differentiated using capacity factor normalized by a reference unit\n    # with 80% AFUE as a national average. Seasonal effects can be ignored - we're comparing capacity \n    # based on a power level from an annual average. Unlike electricity and \n    # transport, no simple metric for the service provided exists,, so we use \n    # capacity factor to transform efficiency into th operational side\n    #Units are: Ops (/MJ delivered) Const (/MJ/hr built) Fuel (/MJ produced)\n    \n     \n    sources.append(dc.Source('Coal',3))\n    sources[-1].addOpsMode('Combustion',[1,0,0,0],[.99,0,0,0])\n    sources[-1].setLCABase(0,0,[.089,0,0,0,.0045]) #EIA coal costs\n    sources[-1].addConstMode('Furnace',1,1) #arbitrarily low mincap\n    sources[-1].setLCABase(1,0,[4.22,76,31,0,63.19]) #TODO Same as NG for now\n    #TODO get coal furnace data\n    sources[-1].addFuelMode('Surface')\n    sources[-1].setLCABase(2,0,[0.0145,.024,8.16e-6,400e-13,.0039])\n    sources[-1].addFuelMode('Underground')\n    sources[-1].setLCABase(2,1,[.0087,.024,8.16e-6,67e-13,.0039])\n    \n    \n    sources.append(dc.Source('Natural Gas',3, v=2))\n    sources[-1].addOpsMode('Combustion',[-4,.84,.9,1],[.99,0,0,0]) #boiler or furnace, Ries\n    sources[-1].setLCABase(0,0,[.0504,0,0,0,.0085]) \n    sources[-1].addConstMode('Furnace',1,1) #arbitrarily low mincap\n    sources[-1].setLCABase(1,0,[4.22,76,31,0,63.19])\n    sources[-1].addFuelMode('Conventional US')\n    sources[-1].setLCABase(2,0,[.009,.065,0,2.67e-11,0])\n    sources[-1].setLCA(2,0,[-5,5.72e-3,1.35e-3,0],4) #EIA Costs - 2010 average, stdev from 2006-2011\n    sources[-1].addFuelMode('Marcellus')\n    sources[-1].setLCABase(2,1,[0.0137,0.065,5.02e-6],0)\n    \n    \n    sources.append(dc.Source('Oil',3))\n    sources[-1].addOpsMode('Combustion',[-4,.84,.9,1],[.99,0,0,0])\n    sources[-1].setLCABase(0,0,[.0706,0,0,0,.008]) \n    sources[-1].addConstMode('Furnace',1,1) #arbitrarily low mincap\n    sources[-1].setLCABase(1,0,[4.22,76,31,0,63.19]) #Ecoinvent w/ CED and BEES \n    sources[-1].addFuelMode('Conventional')\n    sources[-1].setLCABase(2,0,[0.02,.208,.00027,2e-14,0])\n    sources[-1].setLCA(2,0,[-5,.016,.003,0],4)\n    \n    sources.append(dc.Source('Biomass',3, v=3))\n    sources[-1].addOpsMode('Combustion',[-4,1,1.1,1.6],[.97,0,0,0])\n    sources[-1].setLCABase(0,0,[.0682,0,0,0])  #Modeled as identical to natral gas during combustion\n    sources[-1].addConstMode('Furnace',1,1000)\n    sources[-1].setLCABase(1,0,[4.22,76,31,0,190]) #USDA TechLine article\n    sources[-1].addFuelMode('Woody Biomass')\n    sources[-1].setLCABase(2,0,[-.0582,0,0,0,.0041]) #Modeled as identical to natural gas but negative, coproduct for land use\n    sources[-1].setLCA(2,0,[-4,4.0e-11,5.9e-11,1.2e-10],3)\n    \n    #######################################\n    # End of Heating Built-ins\n    #\n    # Start of Water Built-ins\n    #######################################\n    \n    \n    sources.append(dc.Source('Water-Surface',4, v=3))\n    sources[-1].addOpsMode('Basic-Tmt',[-4,.85,.95,1],[.98,0,0,0])\n    sources[-1].setLCABase(0,0,[0,1.22,0,0,.30]) #Cost from B. of Rec. WaTER model, assumed 1% loss\n    sources[-1].addOpsMode('Adv-Tmt',[-4,.85,.95,1],[.98,0,0,0])\n    sources[-1].setLCABase(0,1,[1.34,0,0,.39],1) #10% higher than baic\n    sources[-1].addOpsMode('Non-Drinking',[-4,.5,.8,1],[.98,0,0,0])\n    sources[-1].setLCABase(0,2,[.1684,0,0,.01],1) #EPRI for IW\n    sources[-1].addConstMode('WW Plant',4,80) \n    sources[-1].setLCA(1,0,[ #Assumed same as WWTP\n                [-4,26915,38771,39892], #Simapro range for different classes\n                [3.69e5,0,0,0],\n                [391,0,0,0],\n                [2.07e-6,0,0,0],\n                [50,0,0,0]])\n    sources[-1].addConstMode('Non-Drinking',2,10)\n    sources[-1].setLCABase(1,0,[3880,3.69e4,39,0,5]) #Assumed 10% of full plant\n    sources[-1].addFuelMode('Surface')\n    sources[-1].setLCABase(2,0,[0,.116,0,2e-8,0])\n    \n    sources.append(copy.deepcopy(sources[-1]))    \n    sources[-1].name='Water-Ground'\n    sources[-1].variable = 2\n    sources[-1].Modes[2][0].name ='Ground'\n    sources[-1].setLCABase(2,'Ground',[.3996],1)\n    \n    sources.append(copy.deepcopy(sources[-2]))   #skipping groundater to avoid default flag  \n    sources[-1].name='Water-Import'\n    sources[-1].variable = 1\n    sources[-1].Modes[2][0].name ='Import'\n    sources[-1].setLCABase(2,'Import',[.05],2) #4000 kWh/af - CAP values\n    sources[-1].setLCA(2,'Import',[-4,8.76,11.67,14.6],1)\n    sources[-1].setLCA(2,'Import',[-3,.243,.405,0],4) #Shannon 2007 via Voinov\n    \n    sources.append(copy.deepcopy(sources[-1]))    \n    sources[-1].name='Water-Desal'\n    sources[-1].Modes[2][0].name ='Desal'\n    sources[-1].setLCABase(2,'Desal',[3.89],0)\n    sources[-1].setLCA(2,'Desal',[\n                [-4,10.4,12.,15.9],\n                [-3,.1,.3,0], #arbitrary, interesting assumpion here - fits better for impaired but renewable sources in AZ\n                [2e-7,0,0,0],\n                [-4,.486,.583,.648]],1)\n    \n\n    \n    \n    \n    #######################################\n    # End of Water Built-ins\n    #\n    # Start of Wastewater Built-ins\n    #######################################\n    \n    sources.append(dc.Source('WW-Trickling',5))\n    sources[-1].addOpsMode('Plant',[-4,.75,.85,.95],[.98,0,0,0]) #boiler or furnace, Ries\n    sources[-1].setLCA(0,0,[\n                [-4,.95,1.05,1.11], #FIXME Source??\n                [-4,0.64,0.81,1.72]]) #EPRI\n    sources[-1].setLCABase(0,0,[1e-2,0,.11],2) #assumed 1% evaporation/solids loss\n    sources[-1].addFuelMode('Default')\n    sources[-1].addConstMode('WW Plant',4,80) #Mincap in m^3/hr (~.5MGD)\n    sources[-1].setLCA(1,0,[\n                [-4,26915,38771,39892],\n                [3.69e5,0,0,0],\n                [391,0,0,0],\n                [2.07e-6,0,0,0],\n                [50,0,0,0]])\n    \n    \n    \n    sources.append(copy.deepcopy(sources[-1]))\n    sources[-1].name = 'WW-Aerated'\n    sources[-1].setLCA(0,0,[-4,.979,1,2.13],1) ##epri\n    sources[-1].setLCABase(0,0,[.5],4) #Cost data averaged from PA utilities\n    sources[-2].setLCABase(1,0,[100],4)\n    \n    sources.append(copy.deepcopy(sources[-1]))\n    sources[-1].name = 'WW-Adv-NoDeN'\n    sources[-1].setLCA(0,0,[\n                [-4,1.844,2.094,2.251],\n                [-4,1.13,1.23,2.47]]) ##epri\n    sources[-1].setLCABase(0,0,[1.14],4) #Cost data averaged from PA utilities\n    sources[-1].setLCABase(1,0,[150],4)\n    \n    sources.append(copy.deepcopy(sources[-1]))\n    sources[-1].name = 'WW-Adv-DeN'\n    sources[-1].setLCA(0,0,[-4,1.48,1.52,2.81],1) ##epri\n    sources[-1].setLCABase(0,0,[1.5],4) #Cost data averaged from PA utilities\n    sources[-1].setLCABase(1,0,[210],4)\n    \n    return sources\n    \n    \ndef addSource(sources,name,classFlag,refEff=.97,v=1):\n    sources.append(dc.Source(name,classFlag,refEff,v))\n    sources[-1].addOpsMode('Default',[1,0,0,0],[1,0,0,0])\n    sources[-1].addConstMode('Default',1,1)\n    sources[-1].addFuelMode('Default')\n    \nif __name__=='__main__':\n    sources = main()     \n    for n in sources:\n        print n.name\n        for stages in n.Modes:\n            for m in stages:\n                print m.name\n        print ''\n        ", "meta": {"hexsha": "ec204fb2fd6e5c1e1d2d76b7d2995c837a83e59d", "size": 25436, "ext": "py", "lang": "Python", "max_stars_repo_path": "SourceData.py", "max_stars_repo_name": "ATDale/rewss", "max_stars_repo_head_hexsha": "252b54541dceb607b2bc42cfde7ee651a7f4268a", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-09-12T14:37:07.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-12T14:37:07.000Z", "max_issues_repo_path": "SourceData.py", "max_issues_repo_name": "ATDale/rewss", "max_issues_repo_head_hexsha": "252b54541dceb607b2bc42cfde7ee651a7f4268a", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SourceData.py", "max_forks_repo_name": "ATDale/rewss", "max_forks_repo_head_hexsha": "252b54541dceb607b2bc42cfde7ee651a7f4268a", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.0831758034, "max_line_length": 159, "alphanum_fraction": 0.56486869, "include": true, "reason": "import numpy", "num_tokens": 9927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.17823865443778758}}
{"text": "import support_functions as sf\nimport data_structures as ds\nfrom model_socioeconomic import Socioeconomic\nfrom model_ippu import IPPU\nimport pandas as pd\nimport numpy as np\nimport time\n\n\n###########################\n###                     ###\n###     ENERGY MODEL    ###\n###                     ###\n###########################\n\nclass NonElectricEnergy:\n\n    def __init__(self, attributes: ds.ModelAttributes):\n\n        self.model_attributes = attributes\n        self.required_dimensions = self.get_required_dimensions()\n        self.required_subsectors, self.required_base_subsectors = self.get_required_subsectors()\n        self.required_variables, self.output_variables = self.get_neenergy_input_output_fields()\n\n        ##  set some model fields to connect to the attribute tables\n\n        # Energy Fuel model variables\n        self.modvar_enfu_ef_combustion_co2 = \":math:\\\\text{CO}_2 Combustion Emission Factor\"\n        self.modvar_enfu_ef_combustion_mobile_ch4 = \":math:\\\\text{CH}_4 Mobile Combustion Emission Factor\"\n        self.modvar_enfu_ef_combustion_mobile_n2o = \":math:\\\\text{N}_2\\\\text{O} Mobile Combustion Emission Factor\"\n        self.modvar_enfu_ef_combustion_stationary_ch4 = \":math:\\\\text{CH}_4 Stationary Combustion Emission Factor\"\n        self.modvar_enfu_ef_combustion_stationary_n2o = \":math:\\\\text{N}_2\\\\text{O} Stationary Combustion Emission Factor\"\n        self.modvar_enfu_volumetric_energy_density = \"Volumetric Energy Density\"\n\n        # Industrial Energy model variables\n        self.modvar_inen_demscalar = \"Industrial Energy Demand Scalar\"\n        self.modvar_inen_emissions_ch4 = \":math:\\\\text{CH}_4 Emissions from Industrial Energy\"\n        self.modvar_inen_emissions_co2 = \":math:\\\\text{CO}_2 Emissions from Industrial Energy\"\n        self.modvar_inen_emissions_n2o = \":math:\\\\text{N}_2\\\\text{O} Emissions from Industrial Energy\"\n        self.modvar_inen_energy_demand_electricity = \"Electrical Energy Demand from Industrial Energy\"\n        self.modvar_inen_energy_demand_electricity_agg = \"Total Electrical Energy Demand from Industrial Energy\"\n        self.modvar_inen_energy_demand_total = \"Energy Demand from Industrial Energy\"\n        self.modvar_inen_energy_demand_total_agg = \"Total Energy Demand from Industrial Energy\"\n        self.modvar_inen_en_gdp_intensity_factor = \"GDP Energy Intensity Factor\"\n        self.modvar_inen_en_prod_intensity_factor = \"Production Energy Intesity Factor\"\n        self.modvar_inen_frac_en_coal = \"Industrial Energy Fraction Coal\"\n        self.modvar_inen_frac_en_coke = \"Industrial Energy Fraction Coke\"\n        self.modvar_inen_frac_en_diesel = \"Industrial Energy Fraction Diesel\"\n        self.modvar_inen_frac_en_electricity = \"Industrial Energy Fraction Electricity\"\n        self.modvar_inen_frac_en_furnace_gas = \"Industrial Energy Fraction Furnace Gas\"\n        self.modvar_inen_frac_en_gasoline = \"Industrial Energy Fraction Gasoline\"\n        self.modvar_inen_frac_en_hydrogen = \"Industrial Energy Fraction Hydrogen\"\n        self.modvar_inen_frac_en_kerosene = \"Industrial Energy Fraction Kerosene\"\n        self.modvar_inen_frac_en_natural_gas = \"Industrial Energy Fraction Natural Gas\"\n        self.modvar_inen_frac_en_oil = \"Industrial Energy Fraction Oil\"\n        self.modvar_inen_frac_en_pliqgas = \"Industrial Energy Fraction Petroleum Liquid Gas\"\n        self.modvar_inen_frac_en_solar = \"Industrial Energy Fraction Solar\"\n        self.modvar_inen_frac_en_solid_biomass = \"Industrial Energy Fraction Solid Biomass\"\n        # fuel fractions to check summation over\n        self.modvar_inen_list_fuel_fractions = [\n            self.modvar_inen_frac_en_coal,\n            self.modvar_inen_frac_en_coke,\n            self.modvar_inen_frac_en_diesel,\n            self.modvar_inen_frac_en_electricity,\n            self.modvar_inen_frac_en_furnace_gas,\n            self.modvar_inen_frac_en_gasoline,\n            self.modvar_inen_frac_en_hydrogen,\n            self.modvar_inen_frac_en_kerosene,\n            self.modvar_inen_frac_en_natural_gas,\n            self.modvar_inen_frac_en_oil,\n            self.modvar_inen_frac_en_pliqgas,\n            self.modvar_inen_frac_en_solar,\n            self.modvar_inen_frac_en_solid_biomass\n        ]\n\n        # Transportation variables\n        self.modvar_trns_average_vehicle_load_freight = \"Average Freight Vehicle Load\"\n        self.modvar_trns_average_passenger_occupancy = \"Average Passenger Vehicle Occupancy Rate\"\n        self.modvar_trns_electrical_efficiency = \"Electrical Vehicle Efficiency\"\n        self.modvar_trns_ef_combustion_mobile_biofuels_ch4 = \":math:\\\\text{CH}_4 Biofuels Mobile Combustion Emission Factor\"\n        self.modvar_trns_ef_combustion_mobile_diesel_ch4 = \":math:\\\\text{CH}_4 Diesel Mobile Combustion Emission Factor\"\n        self.modvar_trns_ef_combustion_mobile_gasoline_ch4 = \":math:\\\\text{CH}_4 Gasoline Mobile Combustion Emission Factor\"\n        self.modvar_trns_ef_combustion_mobile_kerosene_ch4 = \":math:\\\\text{CH}_4 Kerosene Mobile Combustion Emission Factor\"\n        self.modvar_trns_ef_combustion_mobile_natural_gas_ch4 = \":math:\\\\text{CH}_4 Natural Gas Mobile Combustion Emission Factor\"\n        self.modvar_trns_ef_combustion_mobile_biofuels_n2o = \":math:\\\\text{N}_2\\\\text{O} Biofuels Mobile Combustion Emission Factor\"\n        self.modvar_trns_ef_combustion_mobile_diesel_n2o = \":math:\\\\text{N}_2\\\\text{O} Diesel Mobile Combustion Emission Factor\"\n        self.modvar_trns_ef_combustion_mobile_gasoline_n2o = \":math:\\\\text{N}_2\\\\text{O} Gasoline Mobile Combustion Emission Factor\"\n        self.modvar_trns_ef_combustion_mobile_kerosene_n2o = \":math:\\\\text{N}_2\\\\text{O} Kerosene Mobile Combustion Emission Factor\"\n        self.modvar_trns_ef_combustion_mobile_natural_gas_n2o = \":math:\\\\text{N}_2\\\\text{O} Natural Gas Mobile Combustion Emission Factor\"\n        self.modvar_trns_fuel_demand_biofuels_agg = \"Total Fuel Demand Biofuels\"\n        self.modvar_trns_fuel_demand_diesel_agg = \"Total Fuel Demand Diesel\"\n        self.modvar_trns_fuel_demand_gasoline_agg = \"Total Fuel Demand Gasoline\"\n        self.modvar_trns_fuel_demand_hydrogen_agg = \"Total Fuel Demand Hydrogen\"\n        self.modvar_trns_fuel_demand_kerosene_agg = \"Total Fuel Demand Biofuels\"\n        self.modvar_trns_fuel_demand_natural_gas_agg = \"Total Fuel Demand NaturalGas\"\n        self.modvar_trns_fuel_efficiency_biofuels = \"Fuel Efficiency Biofuels\"\n        self.modvar_trns_fuel_efficiency_diesel = \"Fuel Efficiency Diesel\"\n        self.modvar_trns_fuel_efficiency_gasoline = \"Fuel Efficiency Gasoline\"\n        self.modvar_trns_fuel_efficiency_hydrogen = \"Fuel Efficiency Hydrogen\"\n        self.modvar_trns_fuel_efficiency_kerosene = \"Fuel Efficiency Kerosene\"\n        self.modvar_trns_fuel_efficiency_natural_gas = \"Fuel Efficiency Natural Gas\"\n        self.modvar_trns_modeshare_freight = \"Freight Transportation Mode Share\"\n        self.modvar_trns_modeshare_public_private = \"Private and Public Transportation Mode Share\"\n        self.modvar_trns_modeshare_regional = \"Regional Transportation Mode Share\"\n        self.modvar_trns_fuel_fraction_biofuels = \"Transportation Mode Fuel Fraction Biofuels\"\n        self.modvar_trns_fuel_fraction_diesel = \"Transportation Mode Fuel Fraction Diesel\"\n        self.modvar_trns_fuel_fraction_electricity = \"Transportation Mode Fuel Fraction Electricity\"\n        self.modvar_trns_fuel_fraction_gasoline = \"Transportation Mode Fuel Fraction Gasoline\"\n        self.modvar_trns_fuel_fraction_hydrogen = \"Transportation Mode Fuel Fraction Hydrogen\"\n        self.modvar_trns_fuel_fraction_kerosene = \"Transportation Mode Fuel Fraction Kerosene\"\n        self.modvar_trns_fuel_fraction_natural_gas = \"Transportation Mode Fuel Fraction Natural Gas\"\n        self.modvar_tnrs_energy_demand_electricity = \"Electrical Energy Demand from Transportation\"\n        self.modvar_tnrs_energy_demand_electricity_agg = \"Total Electrical Energy Demand from Transportation\"\n        self.modvar_trns_emissions_ch4 = \":math:\\\\text{CH}_4 Emissions from Transportation\"\n        self.modvar_trns_emissions_co2 = \":math:\\\\text{CO}_2 Emissions from Transportation\"\n        self.modvar_trns_emissions_n2o = \":math:\\\\text{N}_2\\\\text{O} Emissions from Transportation\"\n        self.modvar_trns_vehicle_distance_traveled = \"Total Vehicle Distance Traveled\"\n\n        # Transportation Demand variables\n        self.modvar_trde_demand_scalar = \"Transportation Demand Scalar\"\n        self.modvar_trde_elasticity_mtkm_to_gdp = \"Elasticity of Megatonne-Kilometer Demand to GDP\"\n        self.modvar_trde_elasticity_pkm_to_gdp = \"Elasticity of Passenger-Kilometer Demand per Capita to GDP per Capita\"\n        self.modvar_trde_demand_initial_mtkm = \"Initial Megatonne-Kilometer Demand\"\n        self.modvar_trde_demand_initial_pkm_per_capita = \"Initial per Capita Passenger-Kilometer Demand\"\n        self.modvar_trde_demand_mtkm = \"Megatonne-Kilometer Demand\"\n        self.modvar_trde_demand_pkm = \"Passenger-Kilometer Demand\"\n\n\n\n\n        # variables from other sectors\n        self.modvar_ippu_qty_total_production = \"Industrial Production\"\n\n        # add other model classes\n        self.model_socioeconomic = Socioeconomic(self.model_attributes)\n        self.model_ippu = IPPU(self.model_attributes)\n\n        # optional integration variables (uses calls to other model classes)\n        self.integration_variables = self.set_integrated_variables()\n\n        ##  MISCELLANEOUS VARIABLES\n        self.time_periods, self.n_time_periods = self.model_attributes.get_time_periods()\n        self.enfu_fuel_electricity = self.get_electricity_fuel()\n\n        # fuel variables dictionary for transportation\n        self.dict_trns_fuel_categories_to_fuel_variables, self.dict_trns_fuel_categories_to_unassigned_fuel_variables = self.get_dict_trns_fuel_categories_to_fuel_variables()\n        # some derivate lists of variables\n        self.modvars_trns_list_fuel_fraction = self.model_attributes.get_vars_by_assigned_class_from_akaf(\n            self.dict_trns_fuel_categories_to_fuel_variables,\n            \"fuel_fraction\"\n        )\n        self.modvars_trns_list_fuel_efficiency = self.model_attributes.get_vars_by_assigned_class_from_akaf(\n            self.dict_trns_fuel_categories_to_fuel_variables,\n            \"fuel_efficiency\"\n        )\n\n\n\n    ##  FUNCTIONS FOR MODEL ATTRIBUTE DIMENSIONS\n\n    def check_df_fields(self,\n        df_neenergy_trajectories: pd.DataFrame,\n        subsector: str = \"All\",\n        var_type: str = \"input\",\n        msg_prepend: str = None\n    ):\n        if subsector == \"All\":\n            check_fields = self.required_variables\n            msg_prepend = \"Energy\"\n        else:\n            self.model_attributes.check_subsector(subsector)\n            if var_type == \"input\":\n                check_fields, ignore_fields = self.model_attributes.get_input_output_fields([\"Economy\", \"General\", subsector])\n            elif var_type == \"output\":\n                ignore_fields, check_fields = self.model_attributes.get_input_output_fields([subsector])\n            else:\n                raise ValueError(f\"Invalid var_type '{var_type}' in check_df_fields: valid types are 'input', 'output'\")\n            msg_prepend = msg_prepend if (msg_prepend is not None) else subsector\n        sf.check_fields(df_neenergy_trajectories, check_fields, f\"{msg_prepend} projection cannot proceed: fields \")\n\n    def get_electricity_fuel(self):\n        return self.model_attributes.get_categories_from_attribute_characteristic(\"Energy Fuels\", {self.model_attributes.field_enfu_electricity_demand_category: 1})[0]\n\n    def get_required_subsectors(self):\n        ## TEMPORARY\n        subsectors = [\"Industrial Energy\", \"Energy Fuels\", \"Transportation\", \"Transportation Demand\"]#self.model_attributes.get_setor_subsectors(\"Energy\")\n        subsectors_base = subsectors.copy()\n        subsectors += [\"Economy\", \"General\"]\n        return subsectors, subsectors_base\n\n    def get_required_dimensions(self):\n        ## TEMPORARY - derive from attributes later\n        required_doa = [self.model_attributes.dim_time_period]\n        return required_doa\n\n    def get_neenergy_input_output_fields(self):\n        required_doa = [self.model_attributes.dim_time_period]\n        required_vars, output_vars = self.model_attributes.get_input_output_fields(self.required_subsectors)\n\n        return required_vars + self.get_required_dimensions(), output_vars\n\n\n    ##  function to set alternative sets of input variables; leave empty for now\n    def get_neenergy_optional_switch_variables(self) -> dict:\n        \"\"\"\n           get_neenergy_optional_switch_variables() defines dictionaries of lists of variables. Returns a nested dictionary specified in the class.\n\n           Output Structure\n           ----------------\n           {\n               \"varset_1\": {\n                   \"primary\": [primary variables...],\n                   \"secondary\": [primary variables...]\n                },\n               \"varset_2\": {\n                   \"primary\": [primary variables...],\n                   \"secondary\": [primary variables...]\n                },\n               ...\n           }\n\n           Notes\n           -----\n           - In each dictionary, variables from the \"primary\" key *or* variables from the \"secondary\" key must be defined. In general, \"primary\" variables are associated with integration. In the absence of these variables, secondary variables are generally calculated endogenously.\n           - Each variable set represents a different approach\n           - If all variables are defined in the input data frame, then the approach associated with \"primary\" variables is used.\n        \"\"\"\n\n        return {}\n\n\n    # variables required to integration\n    def set_integrated_variables(self):\n        # set the integration variables\n        list_vars_required_for_integration = [\n            self.modvar_ippu_qty_total_production\n        ]\n\n        # in Energy, update required variables\n        for modvar in list_vars_required_for_integration:\n            subsec = self.model_attributes.get_variable_subsector(modvar)\n            new_vars = self.model_attributes.build_varlist(subsec, modvar)\n            self.required_variables += new_vars\n\n        # sot required variables and ensure no double counting\n        self.required_variables = list(set(self.required_variables))\n        self.required_variables.sort()\n\n        return list_vars_required_for_integration\n\n\n\n\n    ######################################\n    #    SUBSECTOR SPECIFIC FUNCTIONS    #\n    ######################################\n\n    ##  transportation variables from fuel categories as specified by a matchstring\n    def get_dict_trns_fuel_categories_to_fuel_variables(self):\n        \"\"\"\n            use get_dict_trns_fuel_categories_to_fuel_variables to return a dictionary with fuel categories as keys based on the Transportation attribute table;\n            {cat_fuel: {\"fuel_efficiency\": VARNAME_FUELEFFICIENCY, ...}}\n\n            for each key, the dict includes variables associated with the fuel cat_fuel:\n\n            - \"fuel_efficiency\"\n            - \"fuel_fraction\"\n            - \"ef_ch4\"\n            - \"ef_n2o\"\n\n        \"\"\"\n\n        dict_out = self.model_attributes.assign_keys_from_attribute_fields(\n            \"Transportation\",\n            \"cat_fuel\",\n            {\n                \"Fuel Efficiency\": \"fuel_efficiency\",\n                \"Fuel Fraction\": \"fuel_fraction\",\n                \":math:\\\\text{CH}_4\": \"ef_ch4\",\n                \":math:\\\\text{N}_2\\\\text{O}\": \"ef_n2o\",\n                \"Total Fuel Demand\": \"total_fuel_demand\"\n            },\n            \"varreqs_partial\",\n            True\n        )\n\n        return dict_out\n\n\n    ########################################\n    ###                                  ###\n    ###    PRIMARY PROJECTION METHODS    ###\n    ###                                  ###\n    ########################################\n\n    ##  industrial energy model\n    def project_industrial_energy(\n        self,\n        df_neenergy_trajectories: pd.DataFrame,\n        vec_gdp: np.ndarray,\n        dict_dims: dict = None,\n        n_projection_time_periods: int = None,\n        projection_time_periods: list = None\n    ) -> pd.DataFrame:\n\n        \"\"\"\n            project_industrial_energy can be called from other sectors to simplify calculation of industrial energy.\n\n            Function Arguments\n            ------------------\n            df_neenergy_trajectories: pd.DataFrame of input variables\n\n            vec_gdp: np.ndarray vector of gdp (requires len(vec_gdp) == len(df_neenergy_trajectories))\n\n            dict_dims: dict of dimensions (returned from check_projection_input_df). Default is None.\n\n            n_projection_time_periods: int giving number of time periods (returned from check_projection_input_df). Default is None.\n\n            projection_time_periods: list of time periods (returned from check_projection_input_df). Default is None.\n\n\n            Notes\n            -----\n            If any of dict_dims, n_projection_time_periods, or projection_time_periods are unspecified (expected if ran outside of Energy.project()), self.model_attributes.check_projection_input_df wil be run\n\n        \"\"\"\n\n        # allows production to be run outside of the project method\n        if type(None) in set([type(x) for x in [dict_dims, n_projection_time_periods, projection_time_periods]]):\n            dict_dims, df_neenergy_trajectories, n_projection_time_periods, projection_time_periods = self.model_attributes.check_projection_input_df(df_neenergy_trajectories, True, True, True)\n\n\n        ##  CATEGORY AND ATTRIBUTE INITIALIZATION\n        pycat_enfu = self.model_attributes.get_subsector_attribute(\"Energy Fuels\", \"pycategory_primary\")\n        pycat_inen = self.model_attributes.get_subsector_attribute(\"Industrial Energy\", \"pycategory_primary\")\n        pycat_ippu = self.model_attributes.get_subsector_attribute(\"IPPU\", \"pycategory_primary\")\n        # attribute tables\n        attr_enfu = self.model_attributes.dict_attributes[pycat_enfu]\n        attr_inen = self.model_attributes.dict_attributes[pycat_inen]\n        attr_ippu = self.model_attributes.dict_attributes[pycat_ippu]\n\n\n        ##  OUTPUT INITIALIZATION\n\n        df_out = [df_neenergy_trajectories[self.required_dimensions].copy()]\n\n\n        ############################\n        #    MODEL CALCULATIONS    #\n        ############################\n\n        # first, retrieve energy fractions and ensure they sum to 1\n        dict_arrs_inen_frac_energy = self.model_attributes.get_multivariables_with_bounded_sum_by_category(\n            df_neenergy_trajectories,\n            self.modvar_inen_list_fuel_fractions,\n            1,\n            force_sum_equality = True,\n            msg_append = \"Energy fractions by category do not sum to 1. See definition of dict_arrs_inen_frac_energy.\"\n        )\n\n\n        ##  GET ENERGY INTENSITIES\n\n        # get production-based emissions - start with production, energy demand\n        arr_inen_prod = self.model_attributes.get_standard_variables(df_neenergy_trajectories, self.modvar_ippu_qty_total_production, True, \"array_base\", expand_to_all_cats = True)\n        arr_inen_prod_energy_intensity = self.model_attributes.get_standard_variables(df_neenergy_trajectories, self.modvar_inen_en_prod_intensity_factor, True, \"array_base\", expand_to_all_cats = True)\n        scalar_inen_prod_intensity_to_total_prod = self.model_attributes.get_mass_equivalent(\n            self.model_attributes.get_variable_characteristic(self.modvar_inen_en_prod_intensity_factor, \"$UNIT-MASS$\"),\n            self.model_attributes.get_variable_characteristic(self.modvar_ippu_qty_total_production, \"$UNIT-MASS$\")\n        )\n        # energy intensity due to production in terms of units self.modvar_ippu_qty_total_production\n        arr_inen_energy_demand = arr_inen_prod*arr_inen_prod_energy_intensity*scalar_inen_prod_intensity_to_total_prod\n        # gdp-based emissions - get intensity, multiply by gdp, and scale to match energy units of production\n        arr_inen_gdp_energy_intensity = self.model_attributes.get_standard_variables(df_neenergy_trajectories, self.modvar_inen_en_gdp_intensity_factor, True, \"array_base\", expand_to_all_cats = True)\n        scalar_inen_gdp_energy_to_prod_energy = self.model_attributes.get_energy_equivalent(\n            self.model_attributes.get_variable_characteristic(self.modvar_inen_en_gdp_intensity_factor, \"$UNIT-ENERGY$\"),\n            self.model_attributes.get_variable_characteristic(self.modvar_inen_en_prod_intensity_factor, \"$UNIT-ENERGY$\")\n        )\n        arr_inen_energy_demand += (arr_inen_gdp_energy_intensity.transpose() * vec_gdp).transpose()*scalar_inen_gdp_energy_to_prod_energy\n\n\n        ##  GET EMISSION FACTORS\n\n        # methane - scale to ensure energy units are the same\n        arr_inen_ef_by_fuel_ch4 = self.model_attributes.get_standard_variables(df_neenergy_trajectories, self.modvar_enfu_ef_combustion_stationary_ch4, return_type = \"array_units_corrected\")\n        arr_inen_ef_by_fuel_ch4 *= self.model_attributes.get_energy_equivalent(\n            self.model_attributes.get_variable_characteristic(self.modvar_enfu_ef_combustion_stationary_ch4, \"$UNIT-ENERGY$\"),\n            self.model_attributes.get_variable_characteristic(self.modvar_inen_en_prod_intensity_factor, \"$UNIT-ENERGY$\")\n        )\n        # carbon dioxide - scale to ensure energy units are the same\n        arr_inen_ef_by_fuel_co2 = self.model_attributes.get_standard_variables(df_neenergy_trajectories, self.modvar_enfu_ef_combustion_co2, return_type = \"array_units_corrected\")\n        arr_inen_ef_by_fuel_co2 *= self.model_attributes.get_energy_equivalent(\n            self.model_attributes.get_variable_characteristic(self.modvar_enfu_ef_combustion_co2, \"$UNIT-ENERGY$\"),\n            self.model_attributes.get_variable_characteristic(self.modvar_inen_en_prod_intensity_factor, \"$UNIT-ENERGY$\")\n        )\n        # nitrous oxide - scale to ensure energy units are the same\n        arr_inen_ef_by_fuel_n2o = self.model_attributes.get_standard_variables(df_neenergy_trajectories, self.modvar_enfu_ef_combustion_stationary_n2o, return_type = \"array_units_corrected\")\n        arr_inen_ef_by_fuel_n2o *= self.model_attributes.get_energy_equivalent(\n            self.model_attributes.get_variable_characteristic(self.modvar_enfu_ef_combustion_stationary_n2o, \"$UNIT-ENERGY$\"),\n            self.model_attributes.get_variable_characteristic(self.modvar_inen_en_prod_intensity_factor, \"$UNIT-ENERGY$\")\n        )\n\n\n        ##  CALCULATE EMISSIONS AND ELECTRICITY DEMAND\n\n        # initialize electrical demand to pass and output emission arrays\n        arr_inen_demand_electricity = 0.0\n        arr_inen_demand_electricity_total = 0.0\n        arr_inen_demand_total = 0.0\n        arr_inen_demand_total_total = 0.0\n        arr_inen_emissions_ch4 = 0.0\n        arr_inen_emissions_co2 = 0.0\n        arr_inen_emissions_n2o = 0.0\n        # loop over fuels to\n        for var_ener_frac in self.modvar_inen_list_fuel_fractions:\n            # retrive the fuel category\n            cat_fuel = ds.clean_schema(self.model_attributes.get_variable_attribute(var_ener_frac, pycat_enfu))\n            # get the demand for the current fuel\n            arr_inen_endem_cur_fuel = dict_arrs_inen_frac_energy[var_ener_frac].copy()\n            arr_inen_endem_cur_fuel *= arr_inen_energy_demand\n            # get the category value index and\n            index_cat_fuel = attr_enfu.get_key_value_index(cat_fuel)\n            arr_inen_emissions_ch4 += arr_inen_endem_cur_fuel.transpose()*arr_inen_ef_by_fuel_ch4[:, index_cat_fuel]\n            arr_inen_emissions_co2 += arr_inen_endem_cur_fuel.transpose()*arr_inen_ef_by_fuel_co2[:, index_cat_fuel]\n            arr_inen_emissions_n2o += arr_inen_endem_cur_fuel.transpose()*arr_inen_ef_by_fuel_n2o[:, index_cat_fuel]\n            # add electricity demand and total energy demand\n            arr_inen_demand_electricity += arr_inen_endem_cur_fuel if (cat_fuel == self.enfu_fuel_electricity) else 0.0\n            arr_inen_demand_electricity_total += arr_inen_endem_cur_fuel.sum(axis = 1) if (cat_fuel == self.enfu_fuel_electricity) else 0.0\n            arr_inen_demand_total += arr_inen_endem_cur_fuel\n            arr_inen_demand_total_total += arr_inen_endem_cur_fuel.sum(axis = 1)\n\n        # transpose outputs\n        arr_inen_emissions_ch4 = arr_inen_emissions_ch4.transpose()\n        arr_inen_emissions_co2 = arr_inen_emissions_co2.transpose()\n        arr_inen_emissions_n2o = arr_inen_emissions_n2o.transpose()\n        # set energy data frames\n        scalar_energy = self.model_attributes.get_scalar(self.modvar_inen_en_prod_intensity_factor, \"energy\")\n\n\n        ##  BUILD OUTPUT DFs\n\n        df_out += [\n            self.model_attributes.array_to_df(arr_inen_emissions_ch4, self.modvar_inen_emissions_ch4, False, True),\n            self.model_attributes.array_to_df(arr_inen_emissions_co2, self.modvar_inen_emissions_co2, False, True),\n            self.model_attributes.array_to_df(arr_inen_emissions_n2o, self.modvar_inen_emissions_n2o, False, True),\n            self.model_attributes.array_to_df(arr_inen_demand_electricity*scalar_energy, self.modvar_inen_energy_demand_electricity, False, True),\n            self.model_attributes.array_to_df(arr_inen_demand_electricity_total*scalar_energy, self.modvar_inen_energy_demand_electricity_agg, False),\n            self.model_attributes.array_to_df(arr_inen_demand_total*scalar_energy, self.modvar_inen_energy_demand_total, False, True),\n            self.model_attributes.array_to_df(arr_inen_demand_total_total*scalar_energy, self.modvar_inen_energy_demand_total_agg, False)\n        ]\n\n        # concatenate and add subsector emission totals\n        df_out = sf.merge_output_df_list(df_out, self.model_attributes, \"concatenate\")\n        self.model_attributes.add_subsector_emissions_aggregates(df_out, [\"Industrial Energy\"], False)\n\n        return df_out\n\n\n\n    ##  transportation emissions\n    def project_transportation(self,\n        df_neenergy_trajectories: pd.DataFrame,\n        vec_pop: np.ndarray,\n        vec_rates_gdp: np.ndarray,\n        vec_rates_gdp_per_capita: np.ndarray,\n        dict_dims: dict = None,\n        n_projection_time_periods: int = None,\n        projection_time_periods: list = None\n    ) -> pd.DataFrame:\n\n        \"\"\"\n            project_transportation can be called from other sectors to simplify calculation of transportation emissions and associated metrics. Requires NonElectricEnergy.project_transportation_demand() and all variables from the transportation demand sector\n\n            Function Arguments\n            ------------------\n            df_neenergy_trajectories: pd.DataFrame of input variables\n\n            vec_pop: np.ndarray vector of population (requires len(vec_rates_gdp) == len(df_neenergy_trajectories))\n\n            vec_rates_gdp: np.ndarray vector of gdp growth rates (v_i = growth rate from t_i to t_{i + 1}) (requires len(vec_rates_gdp) == len(df_neenergy_trajectories) - 1)\n\n            vec_rates_gdp_per_capita: np.ndarray vector of gdp per capita growth rates (v_i = growth rate from t_i to t_{i + 1}) (requires len(vec_rates_gdp_per_capita) == len(df_neenergy_trajectories) - 1)\n\n            dict_dims: dict of dimensions (returned from check_projection_input_df). Default is None.\n\n            n_projection_time_periods: int giving number of time periods (returned from check_projection_input_df). Default is None.\n\n            projection_time_periods: list of time periods (returned from check_projection_input_df). Default is None.\n\n\n            Notes\n            -----\n            If any of dict_dims, n_projection_time_periods, or projection_time_periods are unspecified (expected if ran outside of Energy.project()), self.model_attributes.check_projection_input_df wil be run\n\n        \"\"\"\n\n        # allows production to be run outside of the project method\n        if type(None) in set([type(x) for x in [dict_dims, n_projection_time_periods, projection_time_periods]]):\n            dict_dims, df_neenergy_trajectories, n_projection_time_periods, projection_time_periods = self.model_attributes.check_projection_input_df(df_neenergy_trajectories, True, True, True)\n\n        # check fields - transportation demand; if not present, add to the dataframe\n        self.check_df_fields(df_neenergy_trajectories, \"Transportation\")\n        try:\n            self.check_df_fields(df_neenergy_trajectories, \"Transportation Demand\", \"output\", \"Transportation\")\n        except:\n            df_transport_demand = self.project_transportation_demand(\n                df_neenergy_trajectories,\n                vec_pop,\n                vec_rates_gdp,\n                vec_rates_gdp_per_capita,\n                dict_dims,\n                n_projection_time_periods,\n                projection_time_periods\n            )\n            df_neenergy_trajectories = sf.merge_output_df_list([df_neenergy_trajectories, df_transport_demand], self.model_attributes, \"concatenate\")\n\n\n        ##  CATEGORY AND ATTRIBUTE INITIALIZATION\n        pycat_enfu = self.model_attributes.get_subsector_attribute(\"Energy Fuels\", \"pycategory_primary\")\n        pycat_trde = self.model_attributes.get_subsector_attribute(\"Transportation Demand\", \"pycategory_primary\")\n        pycat_trns = self.model_attributes.get_subsector_attribute(\"Transportation\", \"pycategory_primary\")\n        # attribute tables\n        attr_enfu = self.model_attributes.dict_attributes[pycat_enfu]\n        attr_trde = self.model_attributes.dict_attributes[pycat_trde]\n        attr_trns = self.model_attributes.dict_attributes[pycat_trns]\n\n\n        ##  OUTPUT INITIALIZATION\n\n        df_out = [df_neenergy_trajectories[self.required_dimensions].copy()]\n\n\n\n        ############################\n        #    MODEL CALCULATIONS    #\n        ############################\n\n\n        ##  START WITH DEMANDS\n\n        # start with demands and map categories in attribute to associated variable\n        dict_trns_vars_to_trde_cats = self.model_attributes.get_ordered_category_attribute(\"Transportation\", \"cat_transportation_demand\", \"key_varreqs_partial\", True, dict, True)\n        dict_trns_vars_to_trde_cats = sf.reverse_dict(dict_trns_vars_to_trde_cats)\n        array_trns_total_vehicle_demand = 0.0\n        # get occupancy and freight occupancies\n        array_trns_avg_load_freight = self.model_attributes.get_standard_variables(df_neenergy_trajectories, self.modvar_trns_average_vehicle_load_freight, return_type = \"array_base\", expand_to_all_cats = True)\n        array_trns_occ_rate_passenger = self.model_attributes.get_standard_variables(df_neenergy_trajectories, self.modvar_trns_average_passenger_occupancy, return_type = \"array_base\", expand_to_all_cats = True)\n        # convert average load to same units as demand\n        array_trns_avg_load_freight *= self.model_attributes.get_variable_unit_conversion_factor(\n            self.modvar_trns_average_vehicle_load_freight,\n            self.modvar_trde_demand_mtkm,\n            \"mass\"\n        )\n        # convert freight vehicle demand to same length units as passenger\n        scalar_tnrs_length_demfrieght_to_dempass = self.model_attributes.get_variable_unit_conversion_factor(\n            self.modvar_trde_demand_mtkm,\n            self.modvar_trde_demand_pkm,\n            \"length\"\n        )\n\n        # loop over the demand categories to get transportation demand\n        for category in dict_trns_vars_to_trde_cats.keys():\n            # get key index, model variable, and the current demand\n            index_key = self.model_attributes.get_attribute_table(\"Transportation Demand\").get_key_value_index(category)\n            modvar = self.model_attributes.get_variable_from_category(\"Transportation Demand\", category, \"partial\")\n            vec_trde_dem_cur = self.model_attributes.get_standard_variables(df_neenergy_trajectories, modvar, return_type = \"array_base\", expand_to_all_cats = True)[:, index_key]\n            # retrieve the demand mix, convert to total activity-demand by category, then divide by freight/occ_rate\n            array_trde_dem_cur_by_cat = self.model_attributes.get_standard_variables(\n                df_neenergy_trajectories,\n                dict_trns_vars_to_trde_cats[category],\n                return_type = \"array_base\",\n                expand_to_all_cats = True,\n                var_bounds = (0, 1),\n                force_boundary_restriction = True\n            )\n            # ru\n            array_trde_dem_cur_by_cat = (array_trde_dem_cur_by_cat.transpose()*vec_trde_dem_cur).transpose()\n            \"\"\"\n            freight and passenger should be mutually exclusive categories\n            - e.g., if the iterating variable category == \"freight\", then array_trde_dem_cur_by_cat*array_trns_occ_rate_passenger should be 0\n            - if category != \"freight\", then array_trde_dem_cur_by_cat*array_trns_avg_load_freight should be 0)\n\n            - demand length units should be in terms of 'modvar_trns_average_passenger_occupancy' (see scalar multiplication)\n            \"\"\"\n            array_trde_vehicle_dem_cur_by_cat = np.nan_to_num(array_trde_dem_cur_by_cat/array_trns_avg_load_freight, 0.0, neginf = 0.0, posinf = 0.0)*scalar_tnrs_length_demfrieght_to_dempass\n            array_trde_vehicle_dem_cur_by_cat += np.nan_to_num(array_trde_dem_cur_by_cat/array_trns_occ_rate_passenger, 0.0, neginf = 0.0, posinf = 0.0)\n            # update total vehicle-km demand\n            array_trns_total_vehicle_demand += array_trde_vehicle_dem_cur_by_cat\n\n        # add the vehicle distance to output using the units modvar_trde_demand_pkm\n        scalar_trns_total_vehicle_demand = self.model_attributes.get_scalar(self.modvar_trde_demand_pkm, \"length\")\n        df_out.append(\n            self.model_attributes.array_to_df(array_trns_total_vehicle_demand*scalar_trns_total_vehicle_demand, self.modvar_trns_vehicle_distance_traveled, False, True),\n        )\n\n\n        ##  LOOP OVER FUELS\n\n        # first, retrieve fuel-mix fractions and ensure they sum to 1\n        dict_arrs_trns_frac_fuel = self.model_attributes.get_multivariables_with_bounded_sum_by_category(\n            df_neenergy_trajectories,\n            self.modvars_trns_list_fuel_fraction,\n            1,\n            force_sum_equality = False,\n            msg_append = \"Energy fractions by category do not sum to 1. See definition of dict_arrs_trns_frac_fuel.\"\n        )\n        # get carbon dioxide combustion factors (corrected to output units)\n        arr_trns_ef_by_fuel_co2 = self.model_attributes.get_standard_variables(df_neenergy_trajectories, self.modvar_enfu_ef_combustion_co2, return_type = \"array_units_corrected\", expand_to_all_cats = True)\n        arr_trns_energy_density_fuel = self.model_attributes.get_standard_variables(df_neenergy_trajectories, self.modvar_enfu_volumetric_energy_density, return_type = \"array_units_corrected\", expand_to_all_cats = True)\n\n        # initialize electrical demand to pass and output emission arrays\n        arr_trns_demand_electricity = 0.0\n        arr_trns_demand_electricity_total = 0.0\n        arr_trns_emissions_ch4 = 0.0\n        arr_trns_emissions_co2 = 0.0\n        arr_trns_emissions_n2o = 0.0\n\n        # loop over fuels to calculate emissions and demand associated with each fuel\n        fuels_loop = sorted(list(self.dict_trns_fuel_categories_to_fuel_variables.keys()))\n        for cat_fuel in fuels_loop:\n\n            # initialize the fuel demand\n            vec_fuel_demand = 0\n\n            # set some model variables\n            dict_tfc_to_fv_cur = self.dict_trns_fuel_categories_to_fuel_variables.get(cat_fuel)\n            modvar_trns_ef_ch4_cur = dict_tfc_to_fv_cur.get(\"ef_ch4\")\n            modvar_trns_ef_n2o_cur = dict_tfc_to_fv_cur.get(\"ef_n2o\")\n            modvar_trns_fuel_efficiency_cur = dict_tfc_to_fv_cur.get(\"fuel_efficiency\")\n            modvar_trns_fuel_fraction_cur = dict_tfc_to_fv_cur.get(\"fuel_fraction\")\n            modvar_trns_total_volumetric_fuel_dem_cur = dict_tfc_to_fv_cur.get(\"total_fuel_demand\")\n\n            # set some scalars for use in the calculations\n            scalar_trns_fuel_efficiency_to_demand = self.model_attributes.get_variable_unit_conversion_factor(\n                modvar_trns_fuel_efficiency_cur,\n                self.modvar_trde_demand_pkm,\n                \"length\"\n            )\n\n            # get the index and vector of co2 emission factors\n            ind_enfu_cur = attr_enfu.get_key_value_index(cat_fuel)\n            vec_trns_ef_by_fuel_co2_cur = arr_trns_ef_by_fuel_co2[:, ind_enfu_cur]\n            vec_trns_volumetric_enerdensity_by_fuel = arr_trns_energy_density_fuel[:, ind_enfu_cur]\n            # get arrays\n            arr_trns_fuel_fraction_cur = dict_arrs_trns_frac_fuel.get(modvar_trns_fuel_fraction_cur)\n            arr_trns_ef_ch4_cur = self.model_attributes.get_standard_variables(df_neenergy_trajectories, modvar_trns_ef_ch4_cur, return_type = \"array_units_corrected\", expand_to_all_cats = True) if (modvar_trns_ef_ch4_cur is not None) else 0\n            arr_trns_ef_n2o_cur = self.model_attributes.get_standard_variables(df_neenergy_trajectories, modvar_trns_ef_n2o_cur, return_type = \"array_units_corrected\", expand_to_all_cats = True) if (modvar_trns_ef_n2o_cur is not None) else 0\n            arr_trns_fuel_efficiency_cur = self.model_attributes.get_standard_variables(df_neenergy_trajectories, modvar_trns_fuel_efficiency_cur, return_type = \"array_base\", expand_to_all_cats = True)\n\n            # current demand associate with the fuel (in terms of modvar_trde_demand_pkm)\n            arr_trns_vehdem_cur_fuel = array_trns_total_vehicle_demand*arr_trns_fuel_fraction_cur\n\n            if (arr_trns_fuel_efficiency_cur is not None):\n\n                # get demand for fuel in terms of modvar_trns_fuel_efficiency_cur, then get scalars to conert to emission factor fuel volume units\n                arr_trns_fueldem_cur_fuel = np.nan_to_num(arr_trns_vehdem_cur_fuel/arr_trns_fuel_efficiency_cur, neginf = 0.0, posinf = 0.0)\n                arr_trns_energydem_cur_fuel = (arr_trns_fueldem_cur_fuel.transpose()*vec_trns_volumetric_enerdensity_by_fuel).transpose()\n                arr_trns_energydem_cur_fuel *= self.model_attributes.get_variable_unit_conversion_factor(\n                    modvar_trns_fuel_efficiency_cur,\n                    self.modvar_enfu_volumetric_energy_density,\n                    \"volume\"\n                )\n                # add total fuel to output variable\n                vec_fuel_demand += np.sum(arr_trns_fueldem_cur_fuel, axis = 1)\n\n\n                ##  CH4 EMISSIONS\n\n                # get scalar to prepare fuel energies for the emission factor\n                scalar_fuel_energy_to_ef_ch4 = self.model_attributes.get_variable_unit_conversion_factor(\n                    self.modvar_enfu_volumetric_energy_density,\n                    modvar_trns_ef_ch4_cur,\n                    \"energy\"\n                ) if (modvar_trns_ef_ch4_cur is not None) else 0\n                arr_trns_fuel_energydem_cur_fuel_ch4 = arr_trns_energydem_cur_fuel*scalar_fuel_energy_to_ef_ch4\n                arr_emissions_ch4_cur_fuel = arr_trns_ef_ch4_cur*arr_trns_fuel_energydem_cur_fuel_ch4\n                arr_trns_emissions_ch4 += arr_emissions_ch4_cur_fuel\n\n\n                ##  CO2 EMISSIONS\n\n                # get scalar to prepare fuel energies for the emission factor\n                scalar_fuel_energy_to_ef_co2 = self.model_attributes.get_variable_unit_conversion_factor(\n                    self.modvar_enfu_volumetric_energy_density,\n                    self.modvar_enfu_ef_combustion_co2,\n                    \"energy\"\n                )\n                arr_trns_fuel_energydem_cur_fuel_co2 = arr_trns_energydem_cur_fuel*scalar_fuel_energy_to_ef_co2\n                arr_emissions_co2_cur_fuel = (arr_trns_fuel_energydem_cur_fuel_co2.transpose()*vec_trns_ef_by_fuel_co2_cur).transpose()\n                arr_trns_emissions_co2 += arr_emissions_co2_cur_fuel\n\n                ##  N2O EMISSIONS\n\n                # n2o scalar\n                scalar_fuel_energy_to_ef_n2o = self.model_attributes.get_variable_unit_conversion_factor(\n                    self.modvar_enfu_volumetric_energy_density,\n                    modvar_trns_ef_n2o_cur,\n                    \"energy\"\n                ) if (modvar_trns_ef_n2o_cur is not None) else 0\n                arr_trns_fuel_energydem_cur_fuel_n2o = arr_trns_energydem_cur_fuel*scalar_fuel_energy_to_ef_n2o\n                arr_emissions_n2o_cur_fuel = arr_trns_ef_n2o_cur*arr_trns_fuel_energydem_cur_fuel_n2o\n                arr_trns_emissions_n2o += arr_emissions_n2o_cur_fuel\n\n            elif cat_fuel == self.enfu_fuel_electricity:\n\n                # get scalar for energy\n                scalar_electric_eff_to_distance_equiv = self.model_attributes.get_variable_unit_conversion_factor(\n                    self.modvar_trns_electrical_efficiency,\n                    self.modvar_trde_demand_pkm,\n                    \"length\"\n                )\n                # get demand for fuel in terms of modvar_trns_fuel_efficiency_cur, then get scalars to conert to emission factor fuel volume units\n                arr_trns_elect_efficiency_cur = self.model_attributes.get_standard_variables(df_neenergy_trajectories, self.modvar_trns_electrical_efficiency, return_type = \"array_base\", expand_to_all_cats = True)\n                arr_trns_elect_efficiency_cur *= scalar_electric_eff_to_distance_equiv\n                arr_trns_energydem_elec = arr_trns_vehdem_cur_fuel/arr_trns_elect_efficiency_cur\n                # write in terms of output units\n                arr_trns_energydem_elec *= self.model_attributes.get_scalar(self.modvar_trns_electrical_efficiency, \"energy\")\n                arr_trns_energydem_elec = np.nan_to_num(arr_trns_energydem_elec, posinf = 0, neginf = 0)\n\n            # add total fuel volumetric fuel demand\n            if modvar_trns_fuel_efficiency_cur is not None:\n                vec_fuel_demand *= self.model_attributes.get_scalar(modvar_trns_fuel_efficiency_cur, \"volume\")\n                df_out.append(\n                    self.model_attributes.array_to_df(vec_fuel_demand, modvar_trns_total_volumetric_fuel_dem_cur, False, False),\n                )\n\n        # add aggregate emissions\n        df_out += [\n            self.model_attributes.array_to_df(arr_trns_emissions_ch4, self.modvar_trns_emissions_ch4, False),\n            self.model_attributes.array_to_df(arr_trns_emissions_co2, self.modvar_trns_emissions_co2, False),\n            self.model_attributes.array_to_df(arr_trns_emissions_n2o, self.modvar_trns_emissions_n2o, False),\n            self.model_attributes.array_to_df(arr_trns_energydem_elec, self.modvar_tnrs_energy_demand_electricity, False, True),\n            self.model_attributes.array_to_df(np.sum(arr_trns_energydem_elec, axis = 1), self.modvar_tnrs_energy_demand_electricity_agg, False)\n        ]\n\n\n        # concatenate and add subsector emission totals\n        df_out = sf.merge_output_df_list(df_out, self.model_attributes, \"concatenate\")\n        self.model_attributes.add_subsector_emissions_aggregates(df_out, [\"Transportation\"], False)\n\n        return df_out\n\n\n\n    ##  transportation demands\n    def project_transportation_demand(self,\n        df_neenergy_trajectories: pd.DataFrame,\n        vec_pop: np.ndarray,\n        vec_rates_gdp: np.ndarray,\n        vec_rates_gdp_per_capita: np.ndarray,\n        dict_dims: dict = None,\n        n_projection_time_periods: int = None,\n        projection_time_periods: list = None\n    ) -> pd.DataFrame:\n\n        \"\"\"\n            project_transportation_demand can be called from other sectors to simplify calculation of transportation demands and associated metrics.\n\n            Function Arguments\n            ------------------\n            df_neenergy_trajectories: pd.DataFrame of input variables\n\n            vec_pop: np.ndarray vector of population (requires len(vec_rates_gdp) == len(df_neenergy_trajectories))\n\n            vec_rates_gdp: np.ndarray vector of gdp growth rates (v_i = growth rate from t_i to t_{i + 1}) (requires len(vec_rates_gdp) == len(df_neenergy_trajectories) - 1)\n\n            vec_rates_gdp_per_capita: np.ndarray vector of gdp per capita growth rates (v_i = growth rate from t_i to t_{i + 1}) (requires len(vec_rates_gdp_per_capita) == len(df_neenergy_trajectories) - 1)\n\n            dict_dims: dict of dimensions (returned from check_projection_input_df). Default is None.\n\n            n_projection_time_periods: int giving number of time periods (returned from check_projection_input_df). Default is None.\n\n            projection_time_periods: list of time periods (returned from check_projection_input_df). Default is None.\n\n\n            Notes\n            -----\n            If any of dict_dims, n_projection_time_periods, or projection_time_periods are unspecified (expected if ran outside of Energy.project()), self.model_attributes.check_projection_input_df wil be run\n\n        \"\"\"\n\n        # allows production to be run outside of the project method\n        if type(None) in set([type(x) for x in [dict_dims, n_projection_time_periods, projection_time_periods]]):\n            dict_dims, df_neenergy_trajectories, n_projection_time_periods, projection_time_periods = self.model_attributes.check_projection_input_df(df_neenergy_trajectories, True, True, True)\n\n\n        ##  CATEGORY AND ATTRIBUTE INITIALIZATION\n        pycat_enfu = self.model_attributes.get_subsector_attribute(\"Energy Fuels\", \"pycategory_primary\")\n        pycat_trde = self.model_attributes.get_subsector_attribute(\"Transportation Demand\", \"pycategory_primary\")\n        pycat_trns = self.model_attributes.get_subsector_attribute(\"Transportation\", \"pycategory_primary\")\n        # attribute tables\n        attr_enfu = self.model_attributes.dict_attributes[pycat_enfu]\n        attr_trde = self.model_attributes.dict_attributes[pycat_trde]\n        attr_trns = self.model_attributes.dict_attributes[pycat_trns]\n\n\n        ##  OUTPUT INITIALIZATION\n\n        df_out = [df_neenergy_trajectories[self.required_dimensions].copy()]\n\n\n        ############################\n        #    MODEL CALCULATIONS    #\n        ############################\n\n        # get the demand scalar\n        array_trde_demscalar = self.model_attributes.get_standard_variables(df_neenergy_trajectories, self.modvar_trde_demand_scalar, return_type = \"array_base\", expand_to_all_cats = True, var_bounds = (0, np.inf))\n        # start with freight/megaton km demands\n        array_trde_dem_init_freight = self.model_attributes.get_standard_variables(df_neenergy_trajectories, self.modvar_trde_demand_initial_mtkm, return_type = \"array_base\", expand_to_all_cats = True)\n        array_trde_elast_freight_demand_to_gdp = self.model_attributes.get_standard_variables(df_neenergy_trajectories, self.modvar_trde_elasticity_mtkm_to_gdp, return_type = \"array_base\", expand_to_all_cats = True)\n        array_trde_growth_freight_dem_by_cat = sf.project_growth_scalar_from_elasticity(vec_rates_gdp, array_trde_elast_freight_demand_to_gdp, False, \"standard\")\n        # multiply and add to the output\n        array_trde_freight_dem_by_cat = array_trde_dem_init_freight[0]*array_trde_growth_freight_dem_by_cat\n        array_trde_freight_dem_by_cat *= array_trde_demscalar\n        df_out.append(\n            self.model_attributes.array_to_df(array_trde_freight_dem_by_cat, self.modvar_trde_demand_mtkm, False, True)\n        )\n\n        # deal with person-km\n        array_trde_dem_init_passenger = self.model_attributes.get_standard_variables(df_neenergy_trajectories, self.modvar_trde_demand_initial_pkm_per_capita, return_type = \"array_base\", expand_to_all_cats = True)\n        array_trde_elast_passenger_demand_to_gdppc = self.model_attributes.get_standard_variables(df_neenergy_trajectories, self.modvar_trde_elasticity_pkm_to_gdp, return_type = \"array_base\", expand_to_all_cats = True)\n        array_trde_growth_passenger_dem_by_cat = sf.project_growth_scalar_from_elasticity(vec_rates_gdp_per_capita, array_trde_elast_passenger_demand_to_gdppc, False, \"standard\")\n        # project the growth in per capita, multiply by population, then add it to the output\n        array_trde_passenger_dem_by_cat = array_trde_dem_init_passenger[0]*array_trde_growth_passenger_dem_by_cat\n        array_trde_passenger_dem_by_cat = (array_trde_passenger_dem_by_cat.transpose()*vec_pop).transpose()\n        array_trde_passenger_dem_by_cat *= array_trde_demscalar\n        df_out.append(\n            self.model_attributes.array_to_df(array_trde_passenger_dem_by_cat, self.modvar_trde_demand_pkm, False, True)\n        )\n\n        # build output dataframe\n        df_out = sf.merge_output_df_list(df_out, self.model_attributes, \"concatenate\")\n\n        return df_out\n\n\n\n    ##  other energy: stationary emissions and carbon capture and sequestration\n    def project_oesc():\n\n        return 0\n\n\n    ##  primary method\n    def project(self, df_neenergy_trajectories):\n\n        \"\"\"\n            The Energy.project() method takes a data frame of input variables (ordered by time series) and returns a data frame of output variables (model projections for energy--including industrial energy, transportation, stationary emissions, carbon capture and sequestration, and electricity) the same order.\n\n            Function Arguments\n            ------------------\n            df_neenergy_trajectories: pd.DataFrame with all required input fields as columns. The model will not run if any required variables are missing, but errors will detail which fields are missing.\n\n            Notes\n            -----\n            - The .project() method is designed to be parallelized or called from command line via __main__ in run_sector_models.py.\n            - df_neenergy_trajectories should have all input fields required (see Energy.required_variables for a list of variables to be defined)\n            - the df_neenergy_trajectories.project method will run on valid time periods from 1 .. k, where k <= n (n is the number of time periods). By default, it drops invalid time periods. If there are missing time_periods between the first and maximum, data are interpolated.\n        \"\"\"\n\n        ##  CHECKS\n\n        # make sure socioeconomic variables are added and\n        df_neenergy_trajectories, df_se_internal_shared_variables = self.model_socioeconomic.project(df_neenergy_trajectories)\n        # check that all required fields are contained—assume that it is ordered by time period\n        self.check_df_fields(df_neenergy_trajectories)\n        dict_dims, df_neenergy_trajectories, n_projection_time_periods, projection_time_periods = self.model_attributes.check_projection_input_df(df_neenergy_trajectories, True, True, True)\n\n\n        ##  CATEGORY AND ATTRIBUTE INITIALIZATION\n        pycat_fuel = self.model_attributes.get_subsector_attribute(\"Energy Fuels\", \"pycategory_primary\")\n        pycat_gnrl = self.model_attributes.get_subsector_attribute(\"General\", \"pycategory_primary\")\n        pycat_inen = self.model_attributes.get_subsector_attribute(\"Industrial Energy\", \"pycategory_primary\")\n        pycat_ippu = self.model_attributes.get_subsector_attribute(\"IPPU\", \"pycategory_primary\")\n        pycat_oesc = self.model_attributes.get_subsector_attribute(\"Other Energy: Stationary Emissions and Carbon Capture and Sequestration\", \"pycategory_primary\")\n        pycat_trns = self.model_attributes.get_subsector_attribute(\"Transportation\", \"pycategory_primary\")\n        # attribute tables\n        attr_fuel = self.model_attributes.dict_attributes[pycat_fuel]\n        attr_gnrl = self.model_attributes.dict_attributes[pycat_gnrl]\n        attr_inen = self.model_attributes.dict_attributes[pycat_inen]\n        attr_ippu = self.model_attributes.dict_attributes[pycat_ippu]\n        attr_oesc = self.model_attributes.dict_attributes[pycat_oesc]\n        attr_trns = self.model_attributes.dict_attributes[pycat_trns]\n\n\n        ##  ECON/GNRL VECTOR AND ARRAY INITIALIZATION\n\n        # get some vectors from the se model\n        vec_gdp = self.model_attributes.get_standard_variables(df_neenergy_trajectories, self.model_socioeconomic.modvar_econ_gdp, False, return_type = \"array_base\")\n        vec_pop = self.model_attributes.get_standard_variables(df_neenergy_trajectories, self.model_socioeconomic.modvar_gnrl_pop_total, False, return_type = \"array_base\")\n        array_pop = self.model_attributes.get_standard_variables(df_neenergy_trajectories, self.model_socioeconomic.modvar_gnrl_subpop, False, return_type = \"array_base\")\n        vec_gdp_per_capita = np.array(df_se_internal_shared_variables[\"vec_gdp_per_capita\"])\n        vec_rates_gdp = np.array(df_se_internal_shared_variables[\"vec_rates_gdp\"].dropna())\n        vec_rates_gdp_per_capita = np.array(df_se_internal_shared_variables[\"vec_rates_gdp_per_capita\"].dropna())\n\n\n        ##  OUTPUT INITIALIZATION\n\n        df_out = [df_neenergy_trajectories[self.required_dimensions].copy()]\n\n\n\n        #########################################\n        #    MODEL CALCULATIONS BY SUBSECTOR    #\n        #########################################\n\n        # add industrial energy, transportation, and OESC\n        df_out.append(self.project_industrial_energy(df_neenergy_trajectories, vec_gdp, dict_dims, n_projection_time_periods, projection_time_periods))\n        df_out.append(self.project_transportation(df_neenergy_trajectories, vec_pop, vec_rates_gdp, vec_rates_gdp_per_capita, dict_dims, n_projection_time_periods, projection_time_periods))\n\n        # concatenate and add subsector emission totals\n        df_out = sf.merge_output_df_list(df_out, self.model_attributes, \"concatenate\")\n\n        return df_out\n", "meta": {"hexsha": "6ca74e5b0e31c374f8307342c98f2838c9239049", "size": 53493, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/model_energy.py", "max_stars_repo_name": "egobiernoytp/lac_decarbonization", "max_stars_repo_head_hexsha": "7b574c4c91a0b1341dfd97a203fc8477ba32a91d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/model_energy.py", "max_issues_repo_name": "egobiernoytp/lac_decarbonization", "max_issues_repo_head_hexsha": "7b574c4c91a0b1341dfd97a203fc8477ba32a91d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/model_energy.py", "max_forks_repo_name": "egobiernoytp/lac_decarbonization", "max_forks_repo_head_hexsha": "7b574c4c91a0b1341dfd97a203fc8477ba32a91d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.462295082, "max_line_length": 312, "alphanum_fraction": 0.7210102256, "include": true, "reason": "import numpy", "num_tokens": 11992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3451052844289766, "lm_q1q2_score": 0.17794315767283628}}
{"text": "\"\"\"\nThis code provides obejcts to generate counts and model counts images with\ntwo dimensional projections. The code interfaces with the ROIAnalysis\nobject for making the calculations, skymaps.SkyImage object for storing\nthe data, and the image.ZEA object for plotting.  The high level object\nroi_plotting.ROIDisplay can use to access these objects form a high\nlevel plotting interface.\n\n$Header: /nfs/slac/g/glast/ground/cvs/pointlike/python/uw/like/roi_image.py,v 1.42 2017/08/23 16:23:42 zimmer Exp $\n\nauthor: Joshua Lande\n\"\"\"\nfrom skymaps import SkyImage,SkyDir,PythonUtilities,Band,WeightedSkyDirList\nimport numpy as np\nimport astropy.io.fits as pyfits\nimport scipy\nimport scipy.ndimage\n\n\nfrom . pypsf import PretendBand\nfrom . roi_diffuse import ROIDiffuseModel_OTF\nfrom . roi_extended import ROIExtendedModel,ROIExtendedModelAnalytic\nfrom . SpatialModels import RadiallySymmetricModel\nfrom . pointspec_helpers import get_default_diffuse_mapper\nfrom . roi_tsmap import TSCalc,TSCalcPySkyFunction\nfrom uw.utilities import keyword_options\nfrom uw.utilities.fitstools import get_fields\nfrom uw.utilities.decorators import memoize\nfrom pypsf import PsfOverlap\nimport collections\nfrom abc import abstractmethod\nimport numbers\n\n\n\nclass ROIImage(object):\n    \"\"\" This object is suitable for creating a SkyImage object\n        and filling it with some physically meaningful\n        quantity gotten from an ROIAnalysis object. \n        The acutal work is done by subclasses. \"\"\"\n\n    defaults = (\n        ('size',     2,     'size of image in degrees'), \n        ('pixelsize',0.1,   'size, in degrees, of pixels'), \n        ('galactic', False, 'galactic or equatorial coordinates'), \n        ('proj',     'ZEA', 'projection name: can change if desired'),\n        ('center',    None, 'Center of image. If None, use roi center.'),\n        ('conv_type',   -1, 'Conversion type'),\n    )\n\n    @keyword_options.decorate(defaults)\n    def __init__(self,roi,**kwargs):\n        \"\"\" Note, unlike ZEA, can support non-square images. To specify a nonsquare\n            image, set the size parameter to a lenght two tuple:\n                \n                size=(10,5) # dx=10 degrees, dy=5 degrees. \n        \"\"\"\n        keyword_options.process(self, kwargs)\n\n        if self.size < self.pixelsize:\n            raise Exception(\"Can only create images with >=1 pixel in them.\")\n        \n        self.roi = roi\n\n        self.selected_bands = tuple(self.roi.bands if self.conv_type < 0 else \\\n            [ band for band in self.roi.bands if band.ct == self.conv_type ])\n\n        # by default, use get energy range and image center from roi.\n        if self.center is None: self.center=self.roi.roi_dir\n\n        # set up, then create a SkyImage object to perform the projection\n        # to a grid and manage an image\n        if not isinstance(self.size,collections.Iterable):\n\n            # make sure size and pixelsize are commensurate (helpful for\n            # various downsampling code later).\n            self.size = int(self.size/self.pixelsize + 0.01)*self.pixelsize\n            self.skyimage = SkyImage(self.center, '', self.pixelsize, \n                                     self.size, 1, self.proj, self.galactic, False)\n        else:\n            self.skyimage = SkyImage(self.center, '', self.pixelsize, \n                                     float(self.size[0]), 1, self.proj, self.galactic, False, float(self.size[1]))\n\n        self.fill()\n\n        self.nx, self.ny = self.skyimage.naxis1(), self.skyimage.naxis2()\n        self.image=ROIImage.skyimage2numpy(self.skyimage)\n\n    @staticmethod\n    def skyimage2numpy(skyimage):\n        nx, ny = skyimage.naxis1(), skyimage.naxis2()\n        image=np.array(skyimage.image()).reshape((ny, nx))\n        return image\n\n    @abstractmethod\n    def fill(self): pass\n\n    def get_ZEA(self,axes=None,nticks=None):\n        \"\"\" axes and nticks can be created by this object's constructor, but are\n            more logically specified here. If they are not specified, get values from\n            initial object creation. \"\"\"\n        # get out of the object all parameters which should be passed to ZEA.\n\n        if hasattr(self.size,'__iter__'):\n            raise Exception(\"Can only create ZEA object for square objects.\")\n\n        zea_dict = dict((d[0],self.__dict__[d[0]]) for d in ZEA.defaults if hasattr(d,'__iter__') and \\\n                hasattr(self,d[0]))\n        if axes is not None: zea_dict['axes']=axes\n        if nticks is not None: zea_dict['nticks']=nticks\n\n        from uw.utilities.image import ZEA\n        zea=ZEA(self.center,**zea_dict)\n        zea.skyimage = self.skyimage\n        # recalculate, in case the sky image has changed\n        zea.image = ROIImage.skyimage2numpy(self.skyimage)\n\n        # The old one gets removed by python's garbage collector (when zea.skyimage is replaced).\n        zea.projector = zea.skyimage.projector() \n\n        zea.vmin,zea.vmax = zea.skyimage.minimum(), zea.skyimage.maximum()\n        return zea\n\n    def get_pyfits(self):\n        \"\"\" Create and return a pyfits object that corresponds to the ROIImage object. \n            The fits file created is supposed to be consistent with the internal\n            representation that SkyImage/SkyProj uses. \"\"\"\n\n        if self.galactic: \n            ctype1=\"GLON-%s\" % self.proj\n            ctype2=\"GLAT-%s\" % self.proj\n            # for some reason, SkyDir(0,0,SkyDir.GALACTIC).l() = 360\n            crval1,crval2=self.center.l() % 360,self.center.b()\n        else:\n            ctype1=\"RA-%s\" % self.proj\n            ctype2=\"DEC-%s\" % self.proj\n            crval1,crval2=self.center.ra(),self.center.dec()\n\n        cdelt1,cdelt2=-self.pixelsize,self.pixelsize\n\n        # from SkyImage.cxx like 92:\n        #   \"center pixel; WCS convention is that center of a pixel is a half-integer\"\n        crpix1,crpix2=(self.skyimage.naxis1()+1)/2.0,(self.skyimage.naxis2()+1)/2.0\n\n        values = [\n            [\"TELESCOP\", \"GLAST\"],\n            [\"INSTRUME\", \"LAT\"],\n            [\"DATE-OBS\", \"\"],\n            [\"DATE-END\", \"\"],\n            [\"EQUINOX\", 2000.0, \"Equinox of RA & DEC specifications\"],\n            [\"CTYPE1\", ctype1, \"[RA|GLON]---%%%, %%% represents the projection method such as AIT\"],\n            [\"CRPIX1\", crpix1, \"Reference pixel\"],\n            [\"CRVAL1\", crval1, \"RA or GLON at the reference pixel\"],\n            [\"CDELT1\", cdelt1, \"X-axis incr per pixel of physical coord at position of ref pixel(deg)\"],\n            [\"CTYPE2\", ctype2, \"[DEC|GLAT]---%%%, %%% represents the projection method such as AIT\"],\n            [\"CRPIX2\", crpix2, \"Reference pixel\"],\n            [\"CRVAL2\", crval2, \"DEC or GLAT at the reference pixel\"],\n            [\"CDELT2\", cdelt2, \"Y-axis incr per pixel of physical coord at position of ref pixel(deg)\"],\n            [\"CROTA2\",  0, \"Image rotation (deg)\"],\n        ]\n        for i in values: \n            if len(i)>2 and len(i[2])>47: i[2]=i[2][0:47]\n\n        cards = [ pyfits.Card(*i) for i in values]\n\n        header=pyfits.Header(cards=cards)\n\n        hdu=pyfits.PrimaryHDU(data=self.image, header=header)\n        fits = pyfits.HDUList([hdu])\n\n        return fits\n\nclass ROITSMapImage(ROIImage):\n    \"\"\" Subclass of ROIImage representing a residual TS map. \"\"\"\n\n    defaults = ROIImage.defaults + TSCalc.defaults\n\n    @keyword_options.decorate(defaults)\n    def __init__(self,*args,**kwargs):\n        super(ROITSMapImage,self).__init__(*args,**kwargs)\n\n    def fill(self):\n\n        tscalc = TSCalc(self.roi,**keyword_options.defaults_to_kwargs(self,TSCalc))\n        temp=TSCalcPySkyFunction(tscalc)\n        self.skyimage.fill(temp.get_pyskyfun())\n\nclass CountsImage(ROIImage):\n    \"\"\" This ROIImage subclass fills the sky image with the observed Fermi counts. \"\"\"\n\n\n    @staticmethod\n    @memoize\n    def process_filedata(roi,selected_bands):\n        \"\"\" The radius parameter will apply a radius cut. \n            Assume that all bands are contiguous (hope this is always true!) \"\"\"\n\n        radius=roi.sa.maxROI\n\n        emin = min(b.emin for b in selected_bands)\n        emax = max(b.emax for b in selected_bands)\n\n        ft1files=roi.sa.pixeldata.ft1files\n\n        cuts = ['ENERGY > %s'% emin,\n                'ENERGY < %s'% emax,\n                'ZENITH_ANGLE < %s' % roi.sa.pixeldata.zenithcut,\n                'THETA < %s' % roi.sa.pixeldata.thetacut,\n                'EVENT_CLASS >= %s' % roi.sa.pixeldata.event_class]\n\n        data = get_fields(ft1files,['RA','DEC','TIME','ENERGY','CONVERSION_TYPE'],cuts)\n        # convert into skydirs\n        skydirs = [ SkyDir(float(data['RA'][i]),float(data['DEC'][i])) for i in xrange(len(data['RA']))]\n\n        # apply the same gti cut used to read in the initial WSDL.\n        gti=roi.sa.pixeldata.gti\n        good_dirs = []\n\n        front_bins = [b for b in selected_bands if b.ct == 0]\n        front_emin = min(b.emin for b in front_bins) if len(front_bins)>0 else None\n        front_emax = max(b.emax for b in front_bins) if len(front_bins)>0 else None\n\n        back_bins = [b for b in selected_bands if b.ct == 1]\n        back_emin = min(b.emin for b in back_bins) if len(back_bins)>0 else None\n        back_emax = max(b.emax for b in back_bins) if len(back_bins)>0 else None\n\n        good_photons = []\n        for skydir,time,energy,ct in zip(skydirs,data['TIME'],data['ENERGY'],data['CONVERSION_TYPE']):\n            if gti.accept(time) and np.degrees(skydir.difference(roi.roi_dir)) < radius:\n                if ct == 0 and \\\n                   front_emin is not None and front_emax is not None and \\\n                   energy > front_emin and energy < front_emax:\n                    good_photons.append(skydir)\n                if ct == 1 and \\\n                   back_emin is not None and back_emax is not None and \\\n                   energy > back_emin and energy < back_emax:\n                    good_photons.append(skydir)\n\n        return good_photons\n\n    def fill(self):\n        dirs = CountsImage.process_filedata(self.roi,self.selected_bands)\n\n        for photon_dir in dirs:\n            self.skyimage.addPoint(photon_dir)\n\n\nclass ModelImage(ROIImage):\n    \"\"\" This ROIImage subclass fills the sky image with the model\n        predicted counts for a fermi sky model described by an ROIAnalysis\n        object.\n\n        This code is forced to deal with the fact that model intensity\n        can vary significantly across a spatial pixel. The rest of the\n        pointlike code can avoid this whole issue by scaling the healpix\n        pixel size with the PSF to ensure that pixels are always small\n        compared to the instrument's intrisic resolution. But since\n        model predicted counts maps can be generated of arbitary pixel size,\n        this issue must directly be dealt with.\n\n        The solution that this code uses to deal with this issue is to\n        simply sample from a grid finer by an integer number of pixels\n        in each dimensions.  After calculating the model predictions,\n        the nearby blocks of model predictions are averaged to downsample\n        to create the model predictions.  This formulation assumes that\n        each of the subpixels has the same solid angle and so it only\n        suitable for relativly small images where pixels have equal area.\n        For that reason, it is advised to use the ZEA projection.\n\n        For point and extended sources, the characteristic scale with\n        which the convolution must be small compared to is the PSF. So\n        the formula for determining the factor is\n\n        factor = ceil(pixelsize/r10)\n\n        Where pxielsize is the plotting pixel size and r10 is the 10%\n        containment radius of the PSF.\n\n        For background sources, the characteristic scale is not the PSF\n        but the convolution grid pixelsize. So the formula for determining\n        the factor is instead\n        \n        factor = ceil(pixelsize/(conv_pixelsize/4))\n\n        Where conv_pixelsize is the size of the convolution grid's pixels.\n        \n        For background sources, this algorithm is generally efficiency\n        since we except the background to vary on this smaller scale all\n        across the image.  But for point and (small) extended sources,\n        this algorithm is generally very poor because it requires\n        calculating the PSF (or PDF) at many points where the value\n        is very close to 0. A better algorithm would be an adaptive\n        quadrature integration algorithm which evaluate the integral in\n        each pixel, then did a more accurate integral and iterated until\n        the integral converged. This would avoid having to evaluate the\n        model predictions for a source very finely far from the source.\n        On the other hand, adding this feature (presumably to C++\n        for optimization) would be very costly, and this code runs\n        fast enough...\n\n        \"\"\"\n\n    defaults = ROIImage.defaults + (\n            ('override_point_sources', None, \"\"\" If either is specified, use override_point_sources these\n                                                 and override_diffuse_sources to generate the image instead\n                                                 of the sources in the ROI.\"\"\"),\n            ('override_diffuse_sources', None, 'Same as override_point_sources'),\n    )\n\n    @keyword_options.decorate(defaults)\n    def __init__(self,*args,**kwargs):\n        if kwargs.has_key('proj') and kwargs['proj'] != 'ZEA':\n            print \"Warning, it is strongly advised to use the 'ZEA projection when creating model counts maps.\"\n\n        super(ModelImage,self).__init__(*args,**kwargs)\n\n    def fill(self):\n        self.wsdl = self.skyimage.get_wsdl()\n\n        self.solid_angle = np.radians(self.pixelsize)**2\n\n        model_counts = np.zeros(len(self.wsdl),dtype=float)\n\n        model_counts += self.all_point_source_counts()\n        model_counts += self.all_diffuse_sources_counts()\n        model_counts *= self.roi.phase_factor # don't forget about the phase factor!\n        #NB -- this will need to be fixed if want to account for bracketing IRFs\n\n        PythonUtilities.set_wsdl_weights(model_counts,self.wsdl)\n        \n        self.skyimage.set_wsdl(self.wsdl)\n\n    @staticmethod\n    def downsample(myarr,factor):\n        \"\"\"\n        Code taken from http://code.google.com/p/agpy/source/browse/trunk/agpy/downsample.py\n\n        Downsample a 1D or 2D array by averaging over *factor* pixels in each axis.\n        Crops upper edge if the shape is not a multiple of factor.\n\n        This code is pure numpy and should be fast.\n        \"\"\"\n        assert isinstance(factor,numbers.Integral)\n        assert len(myarr.shape) <= 2\n\n        if len(myarr.shape) == 1:\n            xs = myarr.shape[0]\n            assert xs % factor == 0\n            dsarr = np.concatenate([[myarr[i::factor]]\n                                   for i in range(factor)]).mean(axis=0)\n            return dsarr\n\n        elif len(myarr.shape) == 2:\n            xs,ys = myarr.shape\n            assert xs % factor == 0 and ys % factor == 0\n            dsarr = np.concatenate([[myarr[i::factor,j::factor] \n                for i in range(factor)] \n                for j in range(factor)]).mean(axis=0)\n            return dsarr\n\n    def bigger_wsdl(self,band,compare=None):\n        \"\"\" Want to sample on a grid that is comparable in size (or\n            smaller than) 10% of the psf to ensure we get a reasonable\n            sampling of the grid. \"\"\"\n        if compare is None:\n            r10=band.psf.inverse_integral_on_axis(0.10)\n            compare=r10\n        \n        self.factor = int(np.ceil(self.pixelsize/compare))\n\n        if self.factor == 1:\n            return self.wsdl\n        else:\n            # hold onto this thing since it is needed by downsample_model\n            if not hasattr(self.size,'__iter__'):\n                self.fine_skyimage = SkyImage(self.center, '', float(self.pixelsize)/self.factor,\n                                         self.size, 1, self.proj, self.galactic, False)\n            else:\n                self.fine_skyimage = SkyImage(self.center, '', float(self.pixelsize)/self.factor,\n                                         float(self.size[0]), 1, self.proj, self.galactic, False, float(self.size[1]))\n\n            wsdl = self.fine_skyimage.get_wsdl() \n            return wsdl\n\n    def downsample_model(self,rvals):\n        if self.factor==1:\n            return rvals\n        else:\n            rvals = rvals.reshape((self.fine_skyimage.naxis2(), self.fine_skyimage.naxis1()))\n            rvals = ModelImage.downsample(rvals,self.factor).flatten()\n            return rvals\n\n    @staticmethod\n    def get_point_sources(roi,override_point_sources,override_diffuse_sources):\n        if override_point_sources is None and override_diffuse_sources is None:\n            return roi.psm.point_sources \n        if override_point_sources is None:\n            return []\n        elif not isinstance(override_point_sources,collections.Iterable):\n            return [override_point_sources]\n        else:\n            return override_point_sources\n\n    def all_point_source_counts(self):\n        \"\"\" Calculate the point source contributions. \"\"\"\n        point_sources=ModelImage.get_point_sources(self.roi,self.override_point_sources,self.override_diffuse_sources)\n        if len(point_sources)==0: return 0\n\n        point_counts = np.zeros(len(self.wsdl),dtype=float)\n\n        for band in self.selected_bands:\n            cpsf = band.psf.cpsf\n\n            # generate a list of skydirs on a finer grid.\n            wsdl = self.bigger_wsdl(band)\n\n            rvals  = np.empty(len(wsdl),dtype=float)\n\n            for nps,ps in enumerate(point_sources):\n                # evaluate the PSF at the center of each pixel\n                cpsf.wsdl_val(rvals,ps.skydir,wsdl)\n\n                # average the finer grid back to original resolution.\n                temp = self.downsample_model(rvals)\n\n                temp *= self.solid_angle #multiply by pixel solid angle\n                temp *= band.expected(ps.model) # scale by total expected counts\n                point_counts += temp\n\n        return point_counts\n\n    def extended_source_counts(self,extended_model):\n\n        rd = self.roi.roi_dir \n\n        es = extended_model.extended_source\n        sm = es.smodel\n\n        extended_counts = np.zeros(len(self.wsdl),dtype=float)\n\n        for band in self.selected_bands:\n            extended_model.set_state(band)\n            exposure=band.exp.value\n\n            er = exposure(es.spatial_model.center,extended_model.current_energy)/exposure(rd,extended_model.current_energy)\n            es_counts = band.expected(sm)*er\n\n            wsdl = self.bigger_wsdl(band)\n\n            es_pix_counts = extended_model._pix_value(wsdl)*self.solid_angle\n\n            es_pix_counts= self.downsample_model(es_pix_counts)\n\n            bg_pix_counts = es_pix_counts * es_counts\n\n            extended_counts += bg_pix_counts\n\n        return extended_counts\n\n    def otf_source_counts(self,bg):\n        roi=self.roi\n\n        mo=bg.smodel\n\n        background_counts = np.zeros(len(self.wsdl),dtype=float)\n\n        for band in self.selected_bands:\n\n            ns,bg_points,bg_vector = ROIDiffuseModel_OTF.sub_energy_binning(band,bg.nsimps)\n\n            pi_evals  = np.empty([len(self.wsdl),ns + 1])\n\n            wsdl = self.bigger_wsdl(band,compare=bg.pixelsize/4.0)\n\n            for ne,e in enumerate(bg_points):\n                bg.set_state(e,band.ct,band)\n                temp = self.downsample_model(bg._pix_value(wsdl))\n                pi_evals[:,ne] = temp\n\n            pi_evals *= (self.solid_angle * bg_vector)\n            mo_evals  = mo(bg_points)\n            pi_counts = (pi_evals * mo_evals).sum(axis=1)\n\n            background_counts += pi_counts\n\n        return background_counts\n\n    def diffuse_source_counts(self,bg):\n        if isinstance(bg,ROIDiffuseModel_OTF):\n            return self.otf_source_counts(bg)\n        elif isinstance(bg,ROIExtendedModel):\n            return self.extended_source_counts(bg)\n        else:\n            raise Exception(\"Unable to calculate model predictions for diffuse source %s\", bg.name)\n\n    @staticmethod\n    def get_diffuse_sources(roi,override_point_sources,override_diffuse_sources):\n\n        if override_point_sources is None and override_diffuse_sources is None:\n            return roi.dsm.bgmodels\n        else:\n            mapper=get_default_diffuse_mapper(roi.sa,roi.roi_dir,roi.quiet)\n            if override_diffuse_sources is None:\n                return []\n            elif not isinstance(override_diffuse_sources,collections.Iterable):\n                return [mapper(override_diffuse_sources)]\n            else:\n                return [mapper(ds) for ds in override_diffuse_sources]\n\n    def all_diffuse_sources_counts(self):\n        \"\"\" Calculate the diffuse source contributions. \"\"\"\n        \n        bgmodels=ModelImage.get_diffuse_sources(self.roi,self.override_point_sources,self.override_diffuse_sources)\n\n        return sum(self.diffuse_source_counts(bg)\n                   for bg in bgmodels)\n\n\nclass ResidualImage(ROIImage):\n    \"\"\" Has the same arguments at both ModelImage and Counts image but\n        is a ROIImage object representing the difference between the\n        source Counts and the ROI Model. \"\"\"\n\n    # get unique items in the Model + Counts defaults\n    defaults = tuple(set(ModelImage.defaults).union(CountsImage.defaults))\n\n    def __init__(self,roi,**kwargs):\n        super(ResidualImage,self).__init__(roi,**kwargs)\n\n        self.model=ModelImage(self.roi,**keyword_options.defaults_to_kwargs(self,ModelImage))\n        self.counts=CountsImage(self.roi,**keyword_options.defaults_to_kwargs(self,CountsImage))\n\n        self.image = self.counts.image - self.model.image\n        SmoothedImage.add_to_skyimage(self.skyimage,self.image)\n\n\nclass RadialImage(object):\n    \"\"\" This object is similar to ROIImage but performs a radial\n        integral around around a given direction in the sky. \"\"\"\n\n\n    defaults = (\n            ('center',       None,            'Center of image'),\n            ('size',            2, 'Size of image (in degrees)'), \n            ('pixelsize', 0.00625, \"\"\" size of each image pixel. This is a little misleading because the\n                                       size of each pixel varies, but regardless this is used to determine\n                                       the total number of pixels with npix=size/pixelsize \"\"\"),\n            ('npix',         None, \"\"\" If specified, use this value instead of pixelsize. \"\"\"),\n            ('conv_type',    None,            'Conversion type'),\n    )\n\n    @keyword_options.decorate(defaults)\n    def __init__(self,roi,**kwargs):\n        keyword_options.process(self, kwargs)\n\n        if self.npix is None:\n            self.npix = float(self.size)/self.pixelsize\n        \n        self.roi = roi\n\n        self.selected_bands = tuple(self.roi.bands if self.conv_type < 0 else \\\n            [ band for band in self.roi.bands if band.ct == self.conv_type ])\n\n        # by default, use get energy range and image center from roi.\n        if self.center is None: self.center=self.roi.roi_dir\n\n        # bins in theta^2\n        self.bin_edges_deg = np.linspace(0.0,self.size**2,self.npix+1)\n        self.bin_centers_deg = (self.bin_edges_deg[1:] + self.bin_edges_deg[:-1])/2.0\n        \n        # two factors of radians b/c theta^2\n        self.bin_edges_rad = np.radians(np.radians(self.bin_edges_deg))\n        self.bin_centers_rad = np.radians(np.radians(self.bin_centers_deg))\n\n        # the lower and upper agle for each bin.\n        self.theta_pairs_rad = zip(np.sqrt(self.bin_edges_rad[:-1]),\n                                   np.sqrt(self.bin_edges_rad[1:]))\n\n\n        self.fill()\n\n    @abstractmethod\n    def fill(self):\n        \"\"\" This should fill up self.image appropriatly.\"\"\"\n        pass\n\n\nclass RadialCounts(RadialImage):\n    \"\"\" This subclass of RadialImage calculates the counts within\n        each radial bin. \"\"\"\n\n    defaults = RadialImage.defaults\n\n    def fill(self):\n        dirs = CountsImage.process_filedata(self.roi,self.selected_bands)\n        diffs = [self.center.difference(i) for i in dirs]\n        self.image=np.histogram(diffs,bins=np.sqrt(self.bin_edges_rad))[0]\n\n\nclass RadialSource(RadialImage):\n    \"\"\" Subclass of RadialImage where returns the\n        model predicted counts integrated radially\n        for an extended source. Unlike RadialModel,\n        the PSF is not convolved with the RadialSource\n        (useful for comparing the extended source shape\n        with the PSF). \"\"\"\n\n    defaults = RadialImage.defaults + (\n            ('extended_source', None, 'A spatial moel'),\n    )\n\n    def fill(self):\n        if self.extended_source is None:\n            raise Exception(\"RadialSource must be given a spatial_model.\")\n\n        es=self.extended_source\n        sm = es.model\n\n        if not isinstance(es.spatial_model,RadiallySymmetricModel):\n            raise Exception(\"spatial_model must be an instance of RadiallySymmetricModel.\")\n\n        total_counts = sum(band.expected(sm) for band in self.roi.bands)\n        solid_angle = RadialModel.solid_angle_cone(np.radians(self.size))/self.npix\n\n        fraction = es.spatial_model.at_r(np.sqrt(self.bin_centers_rad))\n        fraction*=solid_angle\n\n        self.image = total_counts*fraction\n\n\n\nclass RadialModel(RadialImage):\n\n    defaults = RadialImage.defaults + (\n            ('override_point_sources', None, \"\"\" If either is specified, use override_point_sources these\n                                                 and override_diffuse_sources to generate the image instead\n                                                 of the sources in the ROI.\"\"\"),\n            ('override_diffuse_sources', None, 'Same as override_point_sources'),\n    )\n\n    def fill(self):\n\n        # Create fake bands just big enough to enclose the radial model.\n        # This will speed up the convolution. \n        # The fake band will cause the diffuse sources be be convolved\n        # in a smaller area, which will thus make them more accurate,\n        # and create better plots.\n        self.smaller_bands = []\n        for band in self.selected_bands:\n            rad=self.center.difference(self.roi.roi_dir) + np.radians(self.size)\n            pb = PretendBand(band.e,band.ct, psf=band.psf, radius_in_rad=rad,\n                             sd=self.center, emin=band.emin, emax=band.emax)\n            self.smaller_bands.append(pb)\n\n        self.image = np.zeros_like(self.bin_centers_rad)\n        self.image += self.all_point_source_counts()\n        self.image += self.all_diffuse_sources_counts()\n        self.image *= self.roi.phase_factor # don't forget about the phase factor!\n\n    def all_point_source_counts(self):\n        \"\"\" Calculate the point source contributions. \"\"\"\n        point_sources=ModelImage.get_point_sources(self.roi,self.override_point_sources,self.override_diffuse_sources)\n        if len(point_sources)==0: return 0\n\n        point_counts = np.zeros_like(self.bin_centers_rad)\n\n        overlap = PsfOverlap()\n\n        for i,(theta_min,theta_max) in enumerate(self.theta_pairs_rad):\n\n            model_counts=0\n\n            for j,ps in enumerate(point_sources):\n                for band in self.selected_bands:\n\n                    # this code requires a redundant call to overlap. Improve if time.\n                    # Note that ragged_edge is not appropriate here because our counts\n                    # are always sumed in the exact range.\n                    fraction=overlap(band,self.center,ps.skydir,radius_in_rad=theta_max, ragged_edge=np.inf) - \\\n                             overlap(band,self.center,ps.skydir,radius_in_rad=theta_min, ragged_edge=np.inf)\n\n                    model_counts += band.expected(ps.model)*fraction\n\n            point_counts[i] = model_counts\n\n        return point_counts\n\n    def extended_source_counts(self,extended_model):\n        if type(extended_model) not in [ROIExtendedModel,ROIExtendedModelAnalytic]:\n            raise Exception(\"Unknown extended model.\")\n\n        roi=self.roi\n        sm = extended_model.extended_source.model\n\n        extended_counts = np.zeros_like(self.bin_centers_rad)\n\n        for band,smaller_band in zip(self.selected_bands,self.smaller_bands):\n\n            extended_model.set_state(smaller_band)\n\n            if type(extended_model) == ROIExtendedModel:\n\n                nside = RadialModel.get_nside(self.size,self.npix)\n\n                temp_band = Band(nside)\n                wsdl = WeightedSkyDirList(temp_band,self.center,np.radians(self.size),True)\n                vals=extended_model._pix_value(wsdl)\n\n                rvals=np.empty(len(wsdl),dtype=float)\n                PythonUtilities.arclength(rvals,wsdl,self.center)\n\n                # get average value in each ring by averaging values.\n                fraction = np.histogram(rvals,weights=vals,bins=np.sqrt(self.bin_edges_rad))[0]/\\\n                           np.histogram(rvals,bins=np.sqrt(self.bin_edges_rad))[0]\n\n                # multiply intensities by solid angle in ring\n                fraction *= RadialModel.solid_angle_cone(np.radians(self.size))/self.npix\n\n            elif type(extended_model) == ROIExtendedModelAnalytic:\n\n                fraction = np.empty_like(self.bin_centers_rad)\n\n                for i,(theta_min,theta_max) in enumerate(self.theta_pairs_rad):\n\n                    fraction[i]=extended_model._overlaps(self.center,band,theta_max) - \\\n                             extended_model._overlaps(self.center,band,theta_min)\n\n            # total counts from source * fraction of PDF in ring = model predictions in each ring.\n            extended_counts += band.expected(sm)*fraction\n\n        return extended_counts\n\n    @staticmethod\n    def solid_angle_cone(radius_in_radians):\n        return 2*np.pi*(1-np.cos(radius_in_radians))\n\n    @staticmethod\n    def get_nside(size,npix,num_points_per_ring=200):\n        \"\"\" Solid angle of each healpix pixel is 4pi/(12*ns^2)\n            Solid angel of each ring is pi*(size)^2/npix\n            Want size of each ring > num_points_per_ring*size of each healpix (so that\n            we get 20 pixels to sample each ring).\n\n            Solving for ns, the size of the healpixels required, we get the required formula\n        \"\"\"\n        total_solid_angle=4*np.pi\n        image_solid_angle=RadialModel.solid_angle_cone(np.radians(size))\n\n        solid_angle_per_ring=image_solid_angle/npix\n\n        nside = int(np.ceil(np.sqrt(num_points_per_ring*total_solid_angle/(12*solid_angle_per_ring))))\n        return nside\n\n    def otf_source_counts(self,bg):\n\n        roi=self.roi\n\n        mo=bg.smodel\n\n        background_counts = np.zeros_like(self.bin_centers_rad)\n\n        for band,smaller_band in zip(self.selected_bands,self.smaller_bands):\n\n            ns,bg_points,bg_vector = ROIDiffuseModel_OTF.sub_energy_binning(band,bg.nsimps)\n\n            nside = RadialModel.get_nside(self.size,self.npix)\n\n            temp_band = Band(nside)\n            wsdl = WeightedSkyDirList(temp_band,self.center,np.radians(self.size),True)\n\n            ap_evals = np.empty([len(self.bin_centers_rad),len(bg_points)])\n\n            for ne,e in enumerate(bg_points):\n\n                bg.set_state(e,band.ct,smaller_band)\n\n                rvals=np.empty(len(wsdl),dtype=float)\n                PythonUtilities.arclength(rvals,wsdl,self.center)\n                vals=bg._pix_value(wsdl)\n\n                # get average value in each ring by averaging values.\n                ap_evals[:,ne] = np.histogram(rvals,weights=vals,bins=np.sqrt(self.bin_edges_rad))[0]/\\\n                                 np.histogram(rvals,bins=np.sqrt(self.bin_edges_rad))[0]\n\n            # multiply intensities by solid angle in ring\n            ap_evals *= RadialModel.solid_angle_cone(np.radians(self.size))/self.npix\n\n            ap_evals          *= bg_vector\n            mo_evals           = mo(bg_points)\n            background_counts += (ap_evals * mo_evals).sum(axis=1)\n\n        return background_counts\n\n    def diffuse_source_counts(self,bg):\n        if isinstance(bg,ROIDiffuseModel_OTF):\n            return self.otf_source_counts(bg)\n        elif isinstance(bg,ROIExtendedModel):\n            return self.extended_source_counts(bg)\n        else:\n            raise Exception(\"Unable to calculate model predictions for diffuse source %s\", bg.name)\n\n    def all_diffuse_sources_counts(self):\n        \"\"\" Calculate the diffuse source contributions. \"\"\"\n        bgmodels=ModelImage.get_diffuse_sources(self.roi,self.override_point_sources,self.override_diffuse_sources)\n\n        return sum(self.diffuse_source_counts(bg)\n                   for bg in bgmodels)\n\n\nclass SmoothedImage(ROIImage):\n\n    \"\"\" Represnts a ROIImage objects that is smoothed. This\n        is an abstract base class, but subclasses represent\n        smoothed versions of particular ROIImage objects.\n\n        SmoothedCounts -> CountsImage\n        SmoothedModel -> ModelImage\n        SmoothedResidual -> ResidualImage\n\n        Note, after smoothing, the image is normalized to represent\n        \n    \"\"\"\n    \n    smoothed_options = (\n        ('kerneltype',      'tophat', 'Type of kernel to use'),\n        ('kernel_rad',          0.25, 'Sum counts within radius degrees.'),\n        ('per_solid_angle',    False, 'If true, after smoothing divide by solid angle (counts/[deg]^2'),\n    )\n\n    defaults = ROIImage.defaults + smoothed_options\n\n\n\n    @staticmethod\n    def convolve_array(image,width):\n        \"\"\" Summ all this pixels within a given pixel width\n        \n            code taken from \n            \n            http://code.google.com/p/agpy/source/browse/trunk/agpy/convolve.py \"\"\"\n\n        return out\n\n    @staticmethod\n    def add_to_skyimage(skyimage,image):\n        \"\"\" Take in a two dimensional numpy array representing the\n            fits data and put it into the skyimage. \"\"\"\n        temp=image.reshape(image.shape[0]*image.shape[1])\n\n        wsdl = skyimage.get_wsdl()\n        PythonUtilities.set_wsdl_weights(temp,wsdl)\n        skyimage.set_wsdl(wsdl)\n\n    @staticmethod\n    def convolve_skyimage(skyimage,kernel):\n        \"\"\" Take in a skyimage object and sum each pixel with all the\n            pixels within a given width. \"\"\"\n        image=ROIImage.skyimage2numpy(skyimage)\n\n        convolved=scipy.ndimage.filters.convolve(image, kernel)\n\n        SmoothedImage.add_to_skyimage(skyimage,convolved)\n\n        return skyimage\n\n    @staticmethod\n    def get_kernel(kerneltype,kernel_rad,pixelsize):\n        \"\"\" returns the kernel. Code inspired by\n                http://code.google.com/p/agpy/source/browse/trunk/agpy/convolve.py\n        \"\"\"\n\n        width = int(np.ceil(kernel_rad/pixelsize))\n\n        if kerneltype == 'tophat':\n            kernelsize=4*width\n\n            kernel = np.zeros([kernelsize,kernelsize],dtype=float)\n\n            xx,yy = np.indices(kernel.shape)\n            rr = np.sqrt((xx-kernel.shape[0]/2.)**2+(yy-kernel.shape[1]/2.)**2)\n            kernel[rr<=width] = 1\n\n        elif kerneltype == 'gaussian':\n            kernelsize = 8*width\n\n            kernel = np.zeros([kernelsize,kernelsize],dtype=float)\n            xx,yy = np.indices(kernel.shape)\n            rr = np.sqrt((xx-kernel.shape[0]/2.)**2+(yy-kernel.shape[1]/2.)**2)\n            kernel = np.exp(-(rr**2)/(2*width**2))\n\n            # Gaussian kernels should be normalized so they don't change overall normalization\n            kernel /= kernel.sum()\n\n        else:\n            raise Exception(\"...\")\n\n        return kernel\n\n\n    @keyword_options.decorate(defaults)\n    def __init__(self,*args,**kwargs):\n\n        super(SmoothedImage,self).__init__(*args,**kwargs)\n\n        self.kernel=self.get_kernel(self.kerneltype,self.kernel_rad,self.pixelsize)\n\n        self.kernelsize=self.kernel.shape[0]\n\n        # Make an image, bigger then the desired one, by twice\n        # the smooth radius in each direction.\n        self.pass_dict=keyword_options.defaults_to_kwargs(self,self.object)\n        self.pass_dict['size']=self.size+self.kernelsize*self.pixelsize\n        self.smoothed=self.object(self.roi,**self.pass_dict)\n\n\n        self.smoothed.skyimage=SmoothedImage.convolve_skyimage(self.smoothed.skyimage,self.kernel)\n        self.smoothed.image=ROIImage.skyimage2numpy(self.smoothed.skyimage)\n\n        # now, shrink down smoothed image and replace the current skyimage with it\n\n        self.image = self.smoothed.image[self.kernelsize/2:-self.kernelsize/2,self.kernelsize/2:-self.kernelsize/2]\n\n        if self.per_solid_angle:\n            # convert from counts to counts per square degree\n            self.image = self.image/self.pixelsize**2\n\n        SmoothedImage.add_to_skyimage(self.skyimage,self.image)\n\nclass SmoothedCounts(SmoothedImage):\n\n    defaults = CountsImage.defaults + SmoothedImage.smoothed_options\n\n    object=CountsImage\n\nclass SmoothedModel(SmoothedImage):\n\n    defaults = ModelImage.defaults + SmoothedImage.smoothed_options\n\n    object=ModelImage\n\nclass SmoothedResidual(SmoothedImage):\n\n    defaults = ResidualImage.defaults + SmoothedImage.smoothed_options\n\n    object=ResidualImage\n", "meta": {"hexsha": "f0514c60b8b8721b92f7b79a4b43f5b3810c3a4b", "size": 37060, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/uw/like/roi_image.py", "max_stars_repo_name": "tburnett/pointlike", "max_stars_repo_head_hexsha": "a556f07650c2f17d437c86fdafe9f9a33f59758e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-19T14:45:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-19T14:45:28.000Z", "max_issues_repo_path": "python/uw/like/roi_image.py", "max_issues_repo_name": "tburnett/pointlike", "max_issues_repo_head_hexsha": "a556f07650c2f17d437c86fdafe9f9a33f59758e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/uw/like/roi_image.py", "max_forks_repo_name": "tburnett/pointlike", "max_forks_repo_head_hexsha": "a556f07650c2f17d437c86fdafe9f9a33f59758e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-08-24T18:58:27.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-24T18:58:27.000Z", "avg_line_length": 39.1754756871, "max_line_length": 123, "alphanum_fraction": 0.6379384781, "include": true, "reason": "import numpy,import scipy,import astropy", "num_tokens": 8435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096344, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.17794315586431725}}
{"text": "\"\"\"\nThis module provies \"UTime\" support.\n\"\"\"\nfrom astropy.time.formats import TimeFromEpoch, erfa\n\n__all__ = ['TimeUTime']\n\n\nclass TimeUTime(TimeFromEpoch):\n    \"\"\"\n    Seconds from 1979-01-01 00:00:00 UTC.\n\n    Same as Unix time but this starts 9 years later.\n    This time format is included for historical reasons.\n    Some people in solar physics prefer using this epoch.\n\n    Examples\n    --------\n    >>> from astropy.time import Time\n    >>> t = Time('2000-01-01T13:53:23')\n    >>> print(t.utime)\n    662738003.0\n    >>> t2 = Time('1979-01-01T00:00:00')\n    >>> print(t2.utime)\n    0.0\n    \"\"\"\n    name = 'utime'\n    unit = 1.0 / erfa.DAYSEC  # in days (1 day == 86400 seconds)\n    epoch_val = '1979-01-01 00:00:00'\n    epoch_val2 = None\n    epoch_scale = 'utc'  # Scale for epoch_val class attribute\n    epoch_format = 'iso'  # Format for epoch_val class attribute\n", "meta": {"hexsha": "8519c19b1bff7359366783d0fd055bdad5da02d8", "size": 873, "ext": "py", "lang": "Python", "max_stars_repo_path": "sunpy/time/utime.py", "max_stars_repo_name": "mridullpandey/sunpy", "max_stars_repo_head_hexsha": "65bf70731a8147899b8c0fca8b3b1a386e47c010", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-03T16:39:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-24T15:12:08.000Z", "max_issues_repo_path": "sunpy/time/utime.py", "max_issues_repo_name": "mridullpandey/sunpy", "max_issues_repo_head_hexsha": "65bf70731a8147899b8c0fca8b3b1a386e47c010", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-06-15T17:16:11.000Z", "max_issues_repo_issues_event_max_datetime": "2016-11-23T17:12:07.000Z", "max_forks_repo_path": "sunpy/time/utime.py", "max_forks_repo_name": "mridullpandey/sunpy", "max_forks_repo_head_hexsha": "65bf70731a8147899b8c0fca8b3b1a386e47c010", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-03-15T07:17:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-30T18:36:49.000Z", "avg_line_length": 26.4545454545, "max_line_length": 64, "alphanum_fraction": 0.636884307, "include": true, "reason": "from astropy", "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.17794315419985143}}
{"text": "\"\"\"Group of functions for physiological processing.\"\"\"\nfrom re import findall\nimport logging\n\nimport numpy as np\nfrom itertools import product\nfrom scipy.stats import zscore\n\n__all__ = ('rereferencing', 'bipolarization', 'commonaverage',\n           'tal2mni', 'mni2tal')\n\n###############################################################################\n###############################################################################\n#                               RE-REFERENCING\n###############################################################################\n###############################################################################\n\ndef rereferencing(data, chans, reference, to_ignore=None):\n    \"\"\"Re-reference data.\n\n    Parameters\n    ----------\n    data : array_like\n        The array of data of shape (nchan, npts).\n    chans : list\n        List of channel names of length nchan.\n    reference : int\n        The index of the channel to consider as a reference.\n    to_ignore : list | None\n        List of channels to ignore in the re-referencing.\n\n    Returns\n    -------\n    datar : array_like\n        The re-referenced data.\n    channelsr : list\n        List of re-referenced channel names.\n    consider : list\n        List of boolean values of channels that have to be considered\n        during the ploting processus.\n    \"\"\"\n    # Get shapes :\n    nchan, npts = data.shape\n    # Get data to use as the reference :\n    ref = data[[reference], :]\n    name = chans[reference]\n    # Build ignore vector :\n    consider = np.ones((nchan,), dtype=bool)\n    consider[reference] = False\n    # Find if some channels have to be ignored :\n    if to_ignore is None:\n        sl = slice(nchan)\n    elif isinstance(to_ignore, (tuple, list, np.ndarray)):\n        to_ignore = np.asarray(to_ignore)\n        sl = np.arange(nchan)[~to_ignore]\n        consider[to_ignore] = False\n    # Re-reference data :\n    data[sl, :] -= ref\n    # Build channel names :\n    chan = [k + '-' + name if consider[num]\n            else k for num, k in enumerate(chans)]\n\n    return data, chan, consider\n\n\ndef bipolarization(data, chans, to_ignore=None, sep='.'):\n    \"\"\"Bipolarize data.\n\n    Parameters\n    ----------\n    data : array_like\n        The array of data of shape (nchan, npts).\n    chans : list\n        List of channel names of length nchan.\n    to_ignore : list | None\n        List of channels to ignore in the bipolarization.\n    sep : string | '.'\n        Separator to simplify electrode names by removing undesired name\n        after the sep. For example, if channel = ['h1.025', 'h2.578']\n        and sep='.', the final name will be 'h2-h1'.\n\n    Returns\n    -------\n    datar : array_like\n        The re-referenced data.\n    channelsr : list\n        List of re-referenced channel names.\n    consider : list\n        List of boolean values of channels that have to be considered\n        during the ploting processus.\n    \"\"\"\n    # Variables :\n    nchan, npts = data.shape\n    consider = np.ones((nchan,), dtype=bool)\n\n    # Preprocess channel names by separating channel names / number:\n    chnames, chnums = [], []\n    for num, k in enumerate(chans):\n        # Remove spaces and separation :\n        chans[num] = k.strip().replace(' ', '').split(sep)[0]\n        # Get only the name / number :\n        if findall(r'\\d+', k):\n            number = findall(r'\\d+', k)[0]\n            chnums.append(number)\n            chnames.append(k.split(number)[0])\n        else:\n            chnums.append('')\n            chnames.append(k)\n\n    # Find if some channels have to be ignored :\n    if to_ignore is None:\n        sl = range(nchan)\n    elif isinstance(to_ignore, (tuple, list, np.ndarray)):\n        to_ignore = np.asarray(to_ignore)\n        sl = np.arange(nchan)[~to_ignore]\n        consider[to_ignore] = False\n\n    # Bipolarize :\n    for num in reversed(range(nchan)):\n        # If there's a number :\n        if chnums[num] and (num in sl):\n            # Get the name of the channel to find :\n            chan_to_find = chnames[num] + str(int(chnums[num]) - 1)\n            # Search if exist in channel list :\n            if chan_to_find in chans:\n                # Get the index :\n                ind = chans.index(chan_to_find)\n                # Substract to data :\n                data[num, :] -= data[ind, :]\n                # Update channel name :\n                chans[num] = chans[num] + '-' + chan_to_find\n            else:\n                consider[num] = False\n        else:\n            consider[num] = False\n\n    return data, chans, consider\n\n\ndef commonaverage(data, chans, to_ignore=None):\n    \"\"\"Re-referencement using common average.\n\n    Parameters\n    ----------\n    data : array_like\n        The array of data of shape (nchan, npts).\n    chans : list\n        List of channel names of length nchan.\n    to_ignore : list | None\n        List of channels to ignore in the re-referencing.\n\n    Returns\n    -------\n    datar : array_like\n        The re-referenced data.\n    channelsr : list\n        List of re-referenced channel names.\n    consider : list\n        List of boolean values of channels that have to be considered\n        during the ploting processus.\n    \"\"\"\n    # Variables :\n    nchan, npts = data.shape\n    consider = np.ones((nchan,), dtype=bool)\n    # Find if some channels have to be ignored :\n    if to_ignore is not None:\n        consider[to_ignore] = False\n    # Get the mean across  EEG channels :\n    eegmean = data[consider].mean(0, keepdims=True)\n    # Remove the mean on EEG channels :\n    data[consider, :] -= eegmean\n    # Update channel name :\n    for k in range(len(chans)):\n        chans[k] = chans[k] + '-m' if consider[k] else chans[k]\n    return data, chans, consider\n\n\n###############################################################################\n###############################################################################\n#                               XYZ CONVERSION\n###############################################################################\n###############################################################################\n\ndef _spm_matrix(p):\n    \"\"\"Matrix transformation.\n\n    Parameters\n    ----------\n    p : array_like\n        Vector of floats for defining each tranformation. p must be a vector of\n        length 9.\n\n    Returns\n    -------\n    Pr : array_like\n        The tranformed array.\n    \"\"\"\n    q = [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0]\n    p.extend(q[len(p):12])\n\n    # Translation t :\n    t = np.array([[1, 0, 0, p[0]],\n                  [0, 1, 0, p[1]],\n                  [0, 0, 1, p[2]],\n                  [0, 0, 0, 1]])\n    # Rotation 1 :\n    r1 = np.array([[1, 0, 0, 0],\n                   [0, np.cos(p[3]), np.sin(p[3]), 0],\n                   [0, -np.sin(p[3]), np.cos(p[3]), 0],\n                   [0, 0, 0, 1]])\n    # Rotation 2 :\n    r2 = np.array([[np.cos(p[4]), 0, np.sin(p[4]), 0],\n                   [0, 1, 0, 0],\n                   [-np.sin(p[4]), 0, np.cos(p[4]), 0],\n                   [0, 0, 0, 1]])\n    # Rotation 3 :\n    r3 = np.array([[np.cos(p[5]), np.sin(p[5]), 0, 0],\n                   [-np.sin(p[5]), np.cos(p[5]), 0, 0],\n                   [0, 0, 1, 0],\n                   [0, 0, 0, 1]])\n    # Translation z :\n    z = np.array([[p[6], 0, 0, 0],\n                  [0, p[7], 0, 0],\n                  [0, 0, p[8], 0],\n                  [0, 0, 0, 1]])\n    # Translation s :\n    s = np.array([[1, p[9], p[10], 0],\n                  [0, 1, p[11], 0],\n                  [0, 0, 1, 0],\n                  [0, 0, 0, 1]])\n    return np.linalg.multi_dot([t, r1, r2, r3, z, s])\n\n\ndef tal2mni(xyz):\n    \"\"\"Transform Talairach coordinates into MNI.\n\n    Parameters\n    ----------\n    xyz : array_like\n        Array of Talairach coordinates of shape (n_sources, 3)\n\n    Returns\n    -------\n    xyz_r : array_like\n        Array of MNI coordinates of shape (n_sources, 3)\n    \"\"\"\n    # Check xyz to be (n_sources, 3) :\n    if (xyz.ndim != 2) or (xyz.shape[1] != 3):\n        raise ValueError(\"The shape of xyz must be (N, 3).\")\n    n_sources = xyz.shape[0]\n\n    # Transformation matrices, different zooms above/below AC :\n    rotn = np.linalg.inv(_spm_matrix([0., 0., 0., .05]))\n    upz = np.linalg.inv(_spm_matrix([0., 0., 0., 0., 0., 0., .99, .97, .92]))\n    downz = np.linalg.inv(_spm_matrix([0., 0., 0., 0., 0., 0., .99, .97, .84]))\n\n    # Apply rotation and translation :\n    xyz = np.dot(rotn, np.c_[xyz, np.ones((n_sources, ))].T)\n    tmp = np.array(xyz)[2, :] < 0.\n    xyz[:, tmp] = np.dot(downz, xyz[:, tmp])\n    xyz[:, ~tmp] = np.dot(upz, xyz[:, ~tmp])\n    return np.array(xyz[0:3, :].T)\n\n\ndef mni2tal(xyz):\n    \"\"\"Transform MNI coordinates into Talairach.\n\n    Parameters\n    ----------\n    xyz : array_like\n        Array of MNI coordinates of shape (n_sources, 3)\n\n    Returns\n    -------\n    xyz_r : array_like\n        Array of Talairach coordinates of shape (n_sources, 3)\n    \"\"\"\n    # Check xyz to be (n_sources, 3) :\n    if (xyz.ndim != 2) or (xyz.shape[1] != 3):\n        raise ValueError(\"The shape of xyz must be (N, 3).\")\n    n_sources = xyz.shape[0]\n\n    # Transformation matrices, different zooms above/below AC :\n    up_t = _spm_matrix([0., 0., 0., .05, 0., 0., .99, .97, .92])\n    down_t = _spm_matrix([0., 0., 0., .05, 0., 0., .99, .97, .84])\n    xyz = np.c_[xyz, np.ones((n_sources, ))].T\n\n    tmp = np.array(xyz)[2, :] < 0.\n    xyz[:, tmp] = np.dot(down_t, xyz[:, tmp])\n    xyz[:, ~tmp] = np.dot(up_t, xyz[:, ~tmp])\n    return np.array(xyz[0:3, :].T)\n", "meta": {"hexsha": "2cbef4ff6ac70868b7c7b8cfda6b4cd4cfa040b3", "size": 9444, "ext": "py", "lang": "Python", "max_stars_repo_path": "function/physio.py", "max_stars_repo_name": "BarryLiu97/SEEG_Scripts", "max_stars_repo_head_hexsha": "fd0a79cfedc7a18f9995d808ab608a64facd5fe6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-29T01:55:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T17:20:20.000Z", "max_issues_repo_path": "function/physio.py", "max_issues_repo_name": "BarryLiu97/SEEG_Scripts", "max_issues_repo_head_hexsha": "fd0a79cfedc7a18f9995d808ab608a64facd5fe6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "function/physio.py", "max_forks_repo_name": "BarryLiu97/SEEG_Scripts", "max_forks_repo_head_hexsha": "fd0a79cfedc7a18f9995d808ab608a64facd5fe6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3424657534, "max_line_length": 79, "alphanum_fraction": 0.5044472681, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.17794315072686664}}
{"text": "from .config import on_rtd\n\nimport os, re, sys\nimport warnings\nimport logging\n\nif not on_rtd:\n    import pandas as pd\n    import numpy as np\n    from scipy.interpolate import LinearNDInterpolator as interpnd\n    import numpy.random as rand\n    import matplotlib.pyplot as plt\n\n    from astropy import constants as const\n\n    #Define useful constants\n    G = const.G.cgs.value\n    MSUN = const.M_sun.cgs.value\n    RSUN = const.R_sun.cgs.value\n\n    from .extinction import EXTINCTION, LAMBDA_EFF, extcurve, extcurve_0\n    from .interp import interp_value, interp_values\n\nelse:\n    G = 6.67e-11\n    MSUN = 1.99e33\n    RSUN = 6.96e10\n\nfrom .config import ISOCHRONES\nfrom .grid import ModelGrid\n\ndef get_ichrone(models, bands=None, default=False, **kwargs):\n    \"\"\"Gets Isochrone Object by name, or type, with the right bands\n\n    If `default` is `True`, then will set bands\n    to be the union of bands and default_bands\n    \"\"\"\n    if isinstance(models, Isochrone):\n        return models\n\n    def actual(bands, ictype):\n        if bands is None:\n            return list(ictype.default_bands)\n        elif default:\n            return list(set(bands).union(set(ictype.default_bands)))\n        else:\n            return bands\n\n    if type(models) is type(type):\n        ichrone = models(actual(bands, models))\n    elif models=='dartmouth':\n        from isochrones.dartmouth import Dartmouth_Isochrone\n        ichrone = Dartmouth_Isochrone(bands=actual(bands, Dartmouth_Isochrone), **kwargs)\n    elif models=='dartmouthfast':\n        from isochrones.dartmouth import Dartmouth_FastIsochrone\n        ichrone = Dartmouth_FastIsochrone(bands=actual(bands, Dartmouth_FastIsochrone), **kwargs)\n    elif models=='mist':\n        from isochrones.mist import MIST_Isochrone\n        ichrone = MIST_Isochrone(bands=actual(bands, MIST_Isochrone), **kwargs)\n    elif models=='padova':\n        from isochrones.padova import Padova_Isochrone\n        ichrone = Padova_Isochrone(bands=actual(bands, Padova_Isochrone), **kwargs)\n    elif models=='basti':\n        from isochrones.basti import Basti_Isochrone\n        ichrone = Basti_Isochrone(bands=actual(bands, Basti_Isochrone), **kwargs)\n    else:\n        raise ValueError('Unknown stellar models: {}'.format(models))\n    return ichrone\n\n\nclass Isochrone(object):\n    \"\"\"\n    Basic isochrone class. Everything is a function of mass, log(age), Fe/H.\n\n    Can be instantiated directly, but will typically be used with a pre-defined\n    subclass, such as :class:`dartmouth.Dartmouth_Isochrone`.  All parameters\n    must be array-like objects of the same length, with the exception of ``mags``,\n    which is a dictionary of such array-like objects.\n\n    :param m_ini:\n        Array of initial mass values [msun].\n    :type m_ini: array-like\n\n    :param age:\n        log10(age) [yr]\n\n    :param feh:\n        Metallicity [dex]\n\n    :param m_act:\n        Actual mass; same as m_ini if mass loss not implemented [msun]\n\n    :param logL:\n        log10(luminosity) [solar units]\n\n    :param Teff:\n        Effective temperature [K]\n\n    :param logg:\n        log10(surface gravity) [cgs]\n\n    :param mags:\n        Dictionary of absolute magnitudes in different bands\n    :type mags: ``dict``\n\n    :param tri:\n        Triangulation object used\n        to initialize the interpolation functions.\n        If pre-computed triangulation not provided, then the constructor\n        will calculate one.  This might take several minutes, so be patient.\n        Much better to use pre-computed ones, as provided in, e.g.,\n        :class:`dartmouth.Dartmouth_Isochrone`.\n    :type tri: :class:`scipy.spatial.qhull.Delaunay`, optional\n\n    :param minage,maxage:\n        If desired, a minimum or maximum age can be manually entered.\n\n    \"\"\"\n    def __init__(self,m_ini,age,feh,m_act,logL,Teff,logg,mags,tri=None,\n                 minage=None, maxage=None, ext_table=False):\n        \"\"\"Warning: if tri object not provided, this will be very slow to be created.\n        \"\"\"\n\n        self.minage = age.min()\n        self.maxage = age.max()\n        self.minmass = m_act.min()\n        self.maxmass = m_act.max()\n        self.minfeh = feh.min()\n        self.maxfeh = feh.max()\n\n        self.ext_table = ext_table\n\n        if minage is not None:\n            logging.warning(\"minage and maxage keywords are deprecated.\" + \\\n                          \"Use instead the .set_bounds(age=(lo, hi)) attribute of StarModel.\")\n            self.minage = minage\n        if maxage is not None:\n            logging.warning(\"minage and maxage keywords are deprecated.\" + \\\n                          \"Use instead the .set_bounds(age=(lo, hi)) attribute of StarModel.\")\n            self.maxage = maxage\n\n        L = 10**logL\n\n        if tri is None:\n            points = np.zeros((len(m_ini),3))\n            points[:,0] = m_ini\n            points[:,1] = age\n            points[:,2] = feh\n            fn = interpnd(points,m_act)\n            self.tri = fn.tri\n        else:\n            self.tri = tri\n            self.mass = interpnd(self.tri,m_act)\n\n        self._data = {'mass':m_act,\n                    'logL':logL,\n                    'logg':logg,\n                    'logTeff':np.log10(Teff),\n                    'mags':mags}\n        self._props = ['mass', 'logL', 'logg', 'logTeff']\n\n        self.bands = list(mags.keys())\n\n        self._mag = {band:interpnd(self.tri,mags[band]) for band in self.bands}\n\n        self.mag = {b : self._mag_fn(b) for b in self.bands}\n\n    def __getstate__(self):\n        odict = self.__dict__.copy()\n        del odict['mag'] # This can't be pickled\n        return odict\n\n    def __setstate__(self, odict):\n        self.__dict__ = odict\n        self.__dict__['mag'] = {b : self._mag_fn(b) for b in self.bands}\n\n    def _prop(self, prop, *args):\n        if prop not in self._props:\n            raise ValueError('Cannot call this function with {}.'.format(prop))\n        attr = '_{}'.format(prop)\n        if not hasattr(self, attr):\n            setattr(self, attr, interpnd(self.tri, self._data[prop]))\n        fn = getattr(self, attr)\n        return fn(*args)\n\n    def mass(self, *args):\n        return self._prop('mass', *args)\n\n    def logL(self, *args):\n        return self._prop('logL', *args)\n\n    def logg(self, *args):\n        return self._prop('logg', *args)\n\n    def logTeff(self, *args):\n        return self._prop('logTeff', *args)\n\n    def radius(self, *args):\n        return np.sqrt(G*self.mass(*args)*MSUN/10**self.logg(*args))/RSUN\n\n    def Teff(self, *args):\n        return 10**self.logTeff(*args)\n\n    def density(self, *args):\n        \"\"\" Mean density in g/cc\n        \"\"\"\n        M = self.mass(*args) * MSUN\n        V = 4./3 * np.pi * (self.radius(*args) * RSUN)**3\n        return  M/V\n\n    def delta_nu(self, *args):\n        \"\"\"Returns asteroseismic delta_nu in uHz\n\n        reference: https://arxiv.org/pdf/1312.3853v1.pdf, Eq (2)\n        \"\"\"\n        return 134.88 * np.sqrt(self.mass(*args) / self.radius(*args)**3)\n\n    def nu_max(self, *args):\n        \"\"\"Returns asteroseismic nu_max in uHz\n\n        reference: https://arxiv.org/pdf/1312.3853v1.pdf, Eq (3)\n        \"\"\"\n        return 3120.* (self.mass(*args) /\n                        (self.radius(*args)**2 * np.sqrt(self.Teff(*args)/5777.)))\n\n    def _mag_fn(self, band):\n        def fn(mass, age, feh, distance=10, AV=0.0, x_ext=0., ext_table=self.ext_table):\n            if x_ext==0.:\n                ext = extcurve_0\n            else:\n                ext = extcurve(x_ext)\n            if ext_table:\n                A = AV*EXTINCTION[band]\n            else:\n                A = AV*ext(LAMBDA_EFF[band])\n            dm = 5*np.log10(distance) - 5\n            return self._mag[band](mass, age, feh) + dm + A\n        return fn\n\n\n    def __call__(self, mass, age, feh,\n                 distance=None, AV=0.0,\n                 return_df=True, bands=None):\n        \"\"\"\n        Returns all properties (or arrays of properties) at given mass, age, feh\n\n        :param mass, age, feh:\n            Mass, log(age), metallicity.  Can be float or array_like.\n\n        :param distance:\n            Distance in pc.  If passed, then mags will be converted to\n            apparent mags based on distance (and ``AV``).\n\n        :param AV:\n            V-band extinction (magnitudes).\n\n        :param return_df: (optional)\n            If ``True``, return :class:``pandas.DataFrame`` containing all model\n            parameters at each input value; if ``False``, return dictionary\n            of the same.\n\n        :param bands: (optional)\n            List of photometric bands in which to return magnitudes.\n            Must be subset of ``self.bands``.  If not set, then will\n            default to returning all available bands.\n\n        :return:\n            Either a :class:`pandas.DataFrame` or a dictionary containing\n            model values evaluated at input points.\n        \"\"\"\n        # Broadcast inputs to the same shape\n        mass, age, feh = [np.array(a) for a in np.broadcast_arrays(mass, age, feh)]\n        args = (mass, age, feh)\n        Ms = self.mass(*args)*1\n        Rs = self.radius(*args)*1\n        logLs = self.logL(*args)*1\n        loggs = self.logg(*args)*1\n        Teffs = self.Teff(*args)*1\n        if bands is None:\n            bands = self.bands\n        if distance is not None:\n            args += (distance, AV)\n        mags = {band:1*self.mag[band](*args) for band in bands}\n        # if distance is not None:\n        #     dm = 5*np.log10(distance) - 5\n        #     for band in mags:\n        #         A = AV*EXTINCTION[band]\n        #         mags[band] = mags[band] + dm + A\n\n\n        props = {'age':age,'mass':Ms,'radius':Rs,'logL':logLs,\n                'logg':loggs,'Teff':Teffs,'mag':mags}\n\n        if not return_df:\n            return props\n        else:\n            d = {}\n            for key in props.keys():\n                if key=='mag':\n                    for m in props['mag'].keys():\n                        d['{}_mag'.format(m)] = props['mag'][m]\n                else:\n                    d[key] = props[key]\n            df = pd.DataFrame(d)\n            return df\n\n    def agerange(self, m, feh=0.0):\n        \"\"\"\n        For a given mass and feh, returns the min and max allowed ages.\n        \"\"\"\n        ages = np.arange(self.minage, self.maxage, 0.01)\n        rs = self.radius(m, ages, feh)\n        w = np.where(np.isfinite(rs))[0]\n        return ages[w[0]],ages[w[-1]]\n\n    def evtrack(self,m,feh=0.0,minage=None,maxage=None,dage=0.02,\n                return_df=True):\n        \"\"\"\n        Returns evolution track for a single initial mass and feh.\n\n        :param m:\n            Initial mass of desired evolution track.\n\n        :param feh: (optional)\n            Metallicity of desired track.  Default = 0.0 (solar)\n\n        :param minage, maxage: (optional)\n            Minimum and maximum log(age) of desired track. Will default\n            to min and max age of model isochrones.\n\n        :param dage: (optional)\n            Spacing in log(age) at which to evaluate models.  Default = 0.02\n\n        :param return_df: (optional)\n            Whether to return a ``DataFrame`` or dicionary.  Default is ``True``.\n\n\n        :return:\n            Either a :class:`pandas.DataFrame` or dictionary\n            representing the evolution\n            track---fixed mass, sampled at chosen range of ages.\n\n        \"\"\"\n        if minage is None:\n            minage = self.minage\n        if maxage is None:\n            maxage = self.maxage\n        ages = np.arange(minage,maxage,dage)\n        Ms = self.mass(m,ages,feh)\n        Rs = self.radius(m,ages,feh)\n        logLs = self.logL(m,ages,feh)\n        loggs = self.logg(m,ages,feh)\n        Teffs = self.Teff(m,ages,feh)\n        mags = {band:self.mag[band](m,ages,feh) for band in self.bands}\n\n        props = {'age':ages,'mass':Ms,'radius':Rs,'logL':logLs,\n                'logg':loggs, 'Teff':Teffs, 'mag':mags}\n\n        if not return_df:\n            return props\n        else:\n            d = {}\n            for key in props.keys():\n                if key=='mag':\n                    for m in props['mag'].keys():\n                        d['{}_mag'.format(m)] = props['mag'][m]\n                else:\n                    d[key] = props[key]\n            try:\n                df = pd.DataFrame(d)\n            except ValueError:\n                df = pd.DataFrame(d, index=[0])\n            return df\n\n\n    def isochrone(self,age,feh=0.0,minm=None,maxm=None,dm=0.02,\n                  return_df=True,distance=None,AV=0.0):\n        \"\"\"\n        Returns stellar models at constant age and feh, for a range of masses\n\n        :param age:\n            log10(age) of desired isochrone.\n\n        :param feh: (optional)\n            Metallicity of desired isochrone (default = 0.0)\n\n        :param minm, maxm: (optional)\n            Mass range of desired isochrone (will default to max and min available)\n\n        :param dm: (optional)\n            Spacing in mass of desired isochrone.  Default = 0.02 Msun.\n\n        :param return_df: (optional)\n            Whether to return a :class:``pandas.DataFrame`` or dictionary.  Default is ``True``.\n\n        :param distance:\n            Distance in pc.  If passed, then mags will be converted to\n            apparent mags based on distance (and ``AV``).\n\n        :param AV:\n            V-band extinction (magnitudes).\n\n        :return:\n            :class:`pandas.DataFrame` or dictionary containing results.\n\n        \"\"\"\n        if minm is None:\n            minm = self.minmass\n        if maxm is None:\n            maxm = self.maxmass\n        ms = np.arange(minm,maxm,dm)\n        ages = np.ones(ms.shape)*age\n\n        Ms = self.mass(ms,ages,feh)\n        Rs = self.radius(ms,ages,feh)\n        logLs = self.logL(ms,ages,feh)\n        loggs = self.logg(ms,ages,feh)\n        Teffs = self.Teff(ms,ages,feh)\n        mags = {band:self.mag[band](ms,ages,feh) for band in self.bands}\n        #for band in self.bands:\n        #    mags[band] = self.mag[band](ms,ages)\n        if distance is not None:\n            dm = 5*np.log10(distance) - 5\n            for band in mags:\n                A = AV*EXTINCTION[band]\n                mags[band] = mags[band] + dm + A\n\n        props = {'M':Ms,'R':Rs,'logL':logLs,'logg':loggs,\n                'Teff':Teffs,'mag':mags}\n\n        if not return_df:\n            return props\n        else:\n            d = {}\n            for key in props.keys():\n                if key=='mag':\n                    for m in props['mag'].keys():\n                        d['{}_mag'.format(m)] = props['mag'][m]\n                else:\n                    d[key] = props[key]\n            try:\n                df = pd.DataFrame(d)\n            except ValueError:\n                df = pd.DataFrame(d, index=[0])\n            return df\n\n    def random_points(self,n,minmass=None,maxmass=None,\n                      minage=None,maxage=None,\n                      minfeh=None,maxfeh=None):\n        \"\"\"\n        Returns n random mass, age, feh points, none of which are out of range.\n\n        :param n:\n            Number of desired points.\n\n        :param minmass, maxmass: (optional)\n            Desired allowed range.  Default is mass range of ``self``.\n\n        :param minage, maxage: (optional)\n            Desired allowed range.  Default is log10(age) range of\n            ``self``.\n\n        :param minfehs, maxfeh: (optional)\n            Desired allowed range.  Default is feh range of ``self``.\n\n        :return:\n            :class:`np.ndarray` arrays of randomly selected mass, log10(age),\n            and feh values\n            within allowed ranges.  Used, e.g., to initialize random walkers for\n            :class:`StarModel` fits.\n\n        .. todo::\n\n            Should change this to drawing from priors!  Current implementation\n            is a bit outdated.\n        \"\"\"\n        if minmass is None:\n            minmass = self.minmass\n        if maxmass is None:\n            maxmass = self.maxmass\n        if minage is None:\n            minage = self.minage\n        if maxage is None:\n            maxage = self.maxage\n        if minfeh is None:\n            minfeh = self.minfeh\n        if maxfeh is None:\n            maxfeh = self.maxfeh\n\n        ms = rand.uniform(minmass,maxmass,size=n)\n        ages = rand.uniform(minage,maxage,size=n)\n        fehs = rand.uniform(minage,maxage,size=n)\n\n        Rs = self.radius(ms,ages,fehs)\n        bad = np.isnan(Rs)\n        nbad = bad.sum()\n        while nbad > 0:\n            ms[bad] = rand.uniform(minmass,maxmass,size=nbad)\n            ages[bad] = rand.uniform(minage,maxage,size=nbad)\n            fehs[bad] = rand.uniform(minfeh,maxfeh,size=nbad)\n            Rs = self.radius(ms,ages,fehs)\n            bad = np.isnan(Rs)\n            nbad = bad.sum()\n        return ms,ages,fehs\n\n\nclass MagFunction(object):\n    def __init__(self, ic, band, icol):\n        self.ic = ic\n        self.band = band\n        self.icol = icol\n        self.x_ext = ic.x_ext\n        self.ext_table = ic.ext_table\n\n        if self.x_ext==0.:\n            ext = extcurve_0\n        else:\n            ext = extcurve(x_ext)\n        if self.ext_table:\n            self.AAV = EXTINCTION[self.band]\n        else:\n            self.AAV = ext(LAMBDA_EFF[self.band])\n\n    def __call__(self, mass, age, feh, distance=10, AV=0.0, x_ext=None, ext_table=False):\n        if x_ext is not None:\n            if x_ext==0.:\n                ext = extcurve_0\n            else:\n                ext = extcurve(x_ext)\n\n            if ext_table:\n                AAV = EXTINCTION[self.band]\n            else:\n                AAV = ext(LAMBDA_EFF[self.band])\n        else:\n            AAV = self.AAV\n\n        A = AV*AAV\n        dm = 5*np.log10(distance) - 5\n        mag = self.ic.interp_value(mass, age, feh, self.icol)\n        return mag + dm + A\n\nclass FastIsochrone(Isochrone):\n    \"\"\"Alternative isochrone implementation for large grids, faster likelihoods\n\n    This implementation allows faster point interpolations than\n    the triangulation method in the base :class:`Isochrone` class;\n    however, for simulating large populations (passing arrays of parameters\n    at a time), the base :class:`Isochrone` is still faster.  This is\n    also the go-to implementation for grids that are too large to make the\n    Delaunay method feasible (e.g., significantly over 100,000 points in the grid.)\n\n    However, edge effects might be a bit more problematic here than in the base class,\n    meaning fitting very evolved stars might be an issue. Also, don't trust this subclass\n    for the :function:`Isochrone.agerange` function, for the same reason.\n\n    Subclasses must set the appropriate attributes, and then things should work.\n    \"\"\"\n    name = 'default'\n    modelgrid = ModelGrid\n    age_col = None\n    feh_col = None\n    mass_col = None\n    loggTeff_col = None\n    logg_col = None\n    logL_col = None\n    default_bands = ('g')\n\n    def __init__(self, bands=None, x_ext=0., ext_table=False, debug=False, **kwargs):\n        # df should be indexed by [feh, age]\n\n        if bands is None:\n            bands = list(self.default_bands)\n        bands = sorted(bands)\n        self.bands = bands\n\n        self._df = None\n        self.x_ext = 0.\n        self.ext_table = ext_table\n        self.debug = debug\n\n\n        self._fehs = None\n        self._ages = None\n        self._Nfeh = None\n        self._Nage = None\n\n        self._minage = None\n        self._maxage = None\n        self._minmass = None\n        self._maxmass = None\n        self._minfeh = None\n        self._maxfeh = None\n\n        n_common_cols = len(self.modelgrid.get_common_columns(**kwargs))\n        self._mag_cols = {b:n_common_cols+i for i,b in enumerate(self.bands)}\n        self.mag = {b: MagFunction(self, b, i)\n                            for b,i in self._mag_cols.items()}\n\n        #organized array\n        self._grid = None\n        self._grid_Ns = None\n\n        # kwargs to pass to self.modelgrid\n        self.modelgrid_kwargs = kwargs\n\n    def _initialize(self):\n        for attr in ['df','Ncols','fehs','ages','Nfeh','Nage',\n                     'minage','maxage','minfeh','maxfeh','minmass','maxmass']:\n            _ = getattr(self, attr)\n\n\n    @property\n    def df(self):\n        if self._df is None:\n            self._df = self.modelgrid(self.bands, **self.modelgrid_kwargs).df\n        return self._df\n\n    @property\n    def Ncols(self):\n        return self.df.shape[1]\n\n    @property\n    def fehs(self):\n        if self._fehs is None:\n            self._fehs = self.df.iloc[:, self.feh_col].unique()\n        return self._fehs\n\n    @property\n    def ages(self):\n        if self._ages is None:\n            self._ages = self.df.iloc[:, self.age_col].unique()\n        return self._ages\n\n    @property\n    def Nfeh(self):\n        if self._Nfeh is None:\n            self._Nfeh = len(self.fehs)\n        return self._Nfeh\n\n    @property\n    def Nage(self):\n        if self._Nage is None:\n            self._Nage = len(self.ages)\n        return self._Nage\n\n    @property\n    def minage(self):\n        if self._minage is None:\n            self._minage = self.ages.min()\n        return self._minage\n\n    @property\n    def maxage(self):\n        if self._maxage is None:\n            self._maxage = self.ages.max()\n        return self._maxage\n\n    @property\n    def minfeh(self):\n        if self._minfeh is None:\n            self._minfeh = self.fehs.min()\n        return self._minfeh\n\n    @property\n    def maxfeh(self):\n        if self._maxfeh is None:\n            self._maxfeh = self.fehs.max()\n        return self._maxfeh\n\n    @property\n    def minmass(self):\n        if self._minmass is None:\n            self._minmass = self.df.iloc[:, self.mass_col].min()\n        return self._minmass\n\n    @property\n    def maxmass(self):\n        if self._maxmass is None:\n            self._maxmass = self.df.iloc[:, self.mass_col].max()\n        return self._maxmass\n\n    def logTeff(self, mass, age, feh):\n        return self.interp_value(mass, age, feh, self.loggTeff_col)\n\n    def logg(self, mass, age, feh):\n        return self.interp_value(mass, age, feh, self.logg_col)\n\n    def logL(self, mass, age, feh):\n        return self.interp_value(mass, age, feh, self.logL_col)\n\n    def mass(self, *args):\n        if np.size(args[0]) > 1:\n            return np.array(args[0])\n        else:\n            return args[0]\n\n    @property\n    def grid(self):\n        if self._grid is None:\n            self._make_grid()\n        return self._grid\n\n    @property\n    def grid_Ns(self):\n        if self._grid_Ns is None:\n            self._make_grid()\n        return self._grid_Ns\n\n    @property\n    def _npz_filename(self):\n        keys = list(self.modelgrid_kwargs.keys())\n        keys.sort()\n\n        filename = os.path.join(ISOCHRONES, self.name, '{}'.format('-'.join(self.bands)))\n\n        for k in keys:\n            filename += '_{}{}'.format(k, self.modelgrid_kwargs[k])\n\n        filename += '.npz'\n        return filename\n\n    def _make_grid(self, recalc=False):\n        # Read from file if available.\n        if os.path.exists(self._npz_filename) and not recalc:\n            d = np.load(self._npz_filename)\n            self._grid = d['grid']\n            self._grid_Ns = d['grid_Ns']\n        else:\n            df_list = [[self.df.ix[f,a] for f in self.fehs] for a in self.ages]\n            lens = np.array([[len(df_list[i][j]) for j in range(self.Nfeh)]\n                             for i in range(self.Nage)]).T #just because\n            data = np.zeros((self.Nfeh, self.Nage, lens.max(), self.Ncols))\n\n            for i in range(self.Nage):\n                for j in range(self.Nfeh):\n                    N = lens[j,i]\n                    data[j, i, :N, :] = df_list[i][j].values\n                    data[j, i, N:, :] = np.nan\n\n            np.savez(self._npz_filename, grid=data, grid_Ns=lens)\n            self._grid = data\n            self._grid_Ns = lens\n\n    def interp_value(self, mass, age, feh, icol): # 4 is log_g\n        if self._ages is None:\n            self._initialize()\n\n        try:\n            return interp_value(float(mass), float(age), float(feh), icol,\n                                self.grid, self.mass_col,\n                                self.ages, self.fehs, self.grid_Ns, self.debug)\n\n        except:\n            # First, broadcast to common shape.\n            b = np.broadcast(mass, age, feh)\n            mass = np.resize(mass, b.shape).astype(float)\n            age = np.resize(age, b.shape).astype(float)\n            feh = np.resize(feh, b.shape).astype(float)\n\n            # Then pass to helper function\n            return interp_values(mass, age, feh, icol,\n                                self.grid, self.mass_col,\n                                self.ages, self.fehs, self.grid_Ns)\n", "meta": {"hexsha": "0aaee3b3653b59de724fcd6927b2c41d7648e1dd", "size": 24656, "ext": "py", "lang": "Python", "max_stars_repo_path": "isochrones/isochrone.py", "max_stars_repo_name": "aidantmcb/isochrones", "max_stars_repo_head_hexsha": "d03a68e1fd9e35f14af904962d88084328dd0fb6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "isochrones/isochrone.py", "max_issues_repo_name": "aidantmcb/isochrones", "max_issues_repo_head_hexsha": "d03a68e1fd9e35f14af904962d88084328dd0fb6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "isochrones/isochrone.py", "max_forks_repo_name": "aidantmcb/isochrones", "max_forks_repo_head_hexsha": "d03a68e1fd9e35f14af904962d88084328dd0fb6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-15T16:02:37.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-15T16:02:37.000Z", "avg_line_length": 32.2300653595, "max_line_length": 97, "alphanum_fraction": 0.5606343284, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 6422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.1779431386434468}}
{"text": "\"\"\"\nPython interface for ceq chemical equilibrium calculator\n\nReferences:\n    \"Computer Program for Calculation of Complex Equilibrium Compositions and Applications\"\n    Nasa Reference Publication 1311, October 1995\n    Sanford Gordon and Bonnie J. McBride\n\n    \"NASA Glenn Coefficients for Calculating Thermodynamic Properties of Individual Species\"\n    NASA/TP - 2002-211556, September 2002\n    Bonnie J. McBride, Michael J. Zehe, and Sanford Gordon\n\n\n@author: Nick Gibbons (n.gibbons(at)uq.edu.au)\n\"\"\"\n\nfrom string import ascii_letters\nfrom numpy import array, zeros, log\nfrom ctypes import cdll,c_double,POINTER,c_int,byref\nfrom clib import *\n\nletters = set(ascii_letters)\nDBPATH='../thermo.inp'\nLIBPATH='./libceq.so'\nHEADERFILE='./ceq.h'\n\nclass EqCalculator(object):\n    \"\"\" Python interface to low level ceq routines \"\"\"\n    def __init__(self, spnames):\n        self.spnames = spnames\n        self.nsp = len(spnames)\n        self.lib = self.load_ceq_library()\n\n        atoms = []\n        M = []\n        lewis = []\n        for sp in spnames:\n            asp, Msp, lsp = self.get_thermo_data(sp)\n            atoms.append(asp)\n            M.append(Msp)\n            lewis.append(lsp)\n\n        self.atoms = atoms\n        self.M = array(M)\n        self.lewis = array(lewis)\n\n        elements = set()\n        for a in atoms:\n            for k in a.keys(): elements.add(k)\n        elements = list(elements)\n        elements.sort()\n\n        self.elements = elements\n        self.nel = len(elements)\n\n        a = zeros((len(elements),len(spnames)))\n        for i,s in enumerate(atoms):\n            for k,v in s.items():\n                j = elements.index(k)\n                a[j,i] = v\n\n        self.a = a\n\n        return\n\n    def get_thermo_data(self, name):\n        \"\"\" Stripped down version of get_species from lewis_thermo.py \"\"\"\n        data = self.readdb(name)\n        header = data[0].strip().split()\n        if header[0]!=name:\n            raise IOError(\"Database read failed! {}!={}\".format(name, header[0]))\n\n        info = data[1].strip().split()\n        intervals = int(info[0])\n        M = float(info[-2])/1e3 # convert to kg/mol from kg/kmol\n\n        atomstrings = [data[1][10+8*i:10+8*(i+1)] for i in range(5)]\n        atoms = {}\n        for s in atomstrings:\n            if s[0]==' ': continue\n            elementname,amount = s.split()\n            atoms[elementname] = float(amount)\n        \n        lewis = []\n        for i in range(intervals):\n            li = []\n            line1 = data[3+3*i].replace('D','E') # Fix Fortran Double nonsense\n            li.extend([float(line1[16*j:16*(j+1)]) for j in range(5)])\n\n            line2 = data[4+3*i].replace('D','E') # Fix Fortran Double nonsense\n            li.extend([float(line2[16*j:16*(j+1)]) for j in range(2)])\n            li.extend([float(line2[16*j:16*(j+1)]) for j in range(3,5)])\n            lewis.append(li)\n\n        if len(lewis)!=3:\n            lsp3 = self.fix_missing_thermo_segment(lewis, M)\n            lewis.append(lsp3)\n        assert len(lewis)==3 and len(lewis[0])==9 and len(lewis[1])==9 and len(lewis[2])==9\n        return atoms, M, lewis\n\n    def readdb(self,name):\n        \"\"\" Retrieve species 'name' from the lewis_thermo.db file \"\"\"\n        with open(DBPATH) as fp:\n\n            iterline=iter(fp) # Make an iterator for inner loop behaviour\n\n            # Start looking for the beginning of a species entry\n            for line in iterline:\n                if not line[0] in letters: continue # Skip if not a letter in first position\n\n                if line.startswith(name):        # This could be the one, check the rest\n                    header = line.strip().split()\n                    if header[0]!=name: continue # Nope false alarm\n\n                    lines = [line]               # We've found it!\n                    for nextline in iterline:\n                        if nextline[0] in letters: break\n                        lines.append(nextline)\n                    break                        # Break the outer for loop and jump to return lines\n            else:\n                raise Exception(\"Name: {} not found!\".format(name))\n        return lines\n\n    def fix_missing_thermo_segment(self, lsp, Mi):\n        \"\"\" Create a NASA9 polynominal assuming constant Cp above 6000 K\"\"\"\n        assert len(lsp)==2\n        lspa = zeros((3,9))\n        lspa[0] = lsp[0] # This should copy data automatically\n        lspa[1] = lsp[1] # This should copy data automatically\n\n        T = 5999.99999\n        Ru = 8.3144621\n        X = array([1.0])\n        M = array([Mi])\n        Td = c_double(T)\n\n        cp = self.lib.get_cp(T, X, 1, lspa, M)\n        h  = self.lib.get_h(T, X, 1, lspa, M)\n        s0 = self.lib.get_s0(T, X, 1, lspa, M)\n\n        a2 = cp*Mi/Ru\n        b1 = h*Mi/Ru - a2*T\n        b2 = s0*Mi/Ru - a2*log(T)\n        lsp2 = [0.0, 0.0, a2, 0.0, 0.0, 0.0, 0.0, b1, b2]\n        return lsp2\n\n\n    @staticmethod\n    def load_ceq_library(LIBPATH=LIBPATH):\n        \"\"\" Load the c library and set return types \"\"\"\n        lib = CLib(LIBPATH,[HEADERFILE])\n        return lib\n\n    def pt(self, p, T, Xs0, verbose=0):\n        \"\"\" Call c library to compute equilibrium concentrations at fixed p, T \"\"\"\n        if Xs0.size!=self.nsp: raise Exception('Mismatched array size {}!={}'.format(Xs0.size, self.nsp))\n        Xs1 = zeros(Xs0.shape)\n\n        recode = self.lib.pt(p, T, Xs0, self.nsp, self.nel, self.lewis, self.M, self.a, Xs1, verbose)\n        if recode!=0: raise Exception(\"Equilibrium Calc Failed.\")\n        return Xs1\n\n    def rhou(self, rho, u, Xs0, verbose=0):\n        \"\"\" Call c library to compute equilibrium concentrations at fixed rho, u \"\"\"\n        if Xs0.size!=self.nsp: raise Exception('Mismatched array size {}!={}'.format(Xs0.size, self.nsp))\n        Xs1 = zeros(Xs0.shape)\n        Tref = zeros(1)\n\n        recode = self.lib.rhou(rho, u, Xs0, self.nsp, self.nel, self.lewis, self.M, self.a, Xs1, Tref, verbose)\n        if recode!=0: raise Exception(\"Equilibrium Calc Failed.\")\n        T = Tref[0]\n        return Xs1, T\n\n    def ps(self, pt, st, Xs0, verbose=0):\n        \"\"\" Call c library to compute equilibrium concentrations at fixed p, s \"\"\"\n        if Xs0.size!=self.nsp: raise Exception('Mismatched array size {}!={}'.format(Xs0.size, self.nsp))\n        Xs1 = zeros(Xs0.shape)\n        Tref = zeros(1)\n\n        recode = self.lib.ps(pt, st, Xs0, self.nsp, self.nel, self.lewis, self.M, self.a, Xs1, Tref, verbose)\n        if recode!=0: raise Exception(\"Equilibrium Calc Failed.\")\n        T = Tref[0]\n        return Xs1, T\n\n    def rhot(self, rho, T, Xs0, verbose=0):\n        \"\"\" Call c library to compute equilibrium concentrations at fixed rho, T \"\"\"\n        if Xs0.size!=self.nsp: raise Exception('Mismatched array size {}!={}'.format(Xs0.size, self.nsp))\n        Xs1 = zeros(Xs0.shape)\n\n        recode = self.lib.rhot(rho, T, Xs0, self.nsp, self.nel, self.lewis, self.M, self.a, Xs1, verbose)\n        if recode!=0: raise Exception(\"Equilibrium Calc Failed.\")\n        return Xs1\n\n    def get_u(self, X, T):\n        \"\"\" Call c library to compute internal energy at fixed composition and temperature \"\"\"\n        u = self.lib.get_u(T, X, self.nsp, self.lewis, self.M)\n        return u\n\n    def get_h(self, X, T):\n        \"\"\" Call c library to compute internal energy at fixed composition and temperature \"\"\"\n        h = self.lib.get_h(T, X, self.nsp, self.lewis, self.M)\n        return h\n\n    def get_cp(self, X, T):\n        \"\"\" Call c library to compute internal energy at fixed composition and temperature \"\"\"\n        cp = self.lib.get_cp(T, X, self.nsp, self.lewis, self.M)\n        return cp\n\n    def get_s0(self, X, T):\n        \"\"\" Call c library to compute specific entropy at standard state and arbitrary temperature \"\"\"\n        s0 = self.lib.get_s0(T, X, self.nsp, self.lewis, self.M)\n        return s0\n\n    def get_s(self, X, T, p):\n        \"\"\" Call c library to compute internal entropy at an arbitrary pressure and temperature \"\"\"\n        s = self.lib.get_s(T, p, X, self.nsp, self.lewis, self.M)\n        return s\n\n    def batch_pt(self, p, T, Xs0, verbose=0):\n        \"\"\" Call c library to compute equilibrium concentrations at fixed p, T \"\"\"\n        N, nspcheck = Xs0.shape\n        if not Xs0.flags['OWNDATA']: raise Exception(\"Xs0 Memory Error: Array must own its data\")\n        if nspcheck!=self.nsp: raise Exception(\"nsp ({}) != Xs0.shape[1] ({})\".format(self.nsp, nspcheck))\n        if N!=p.size: raise Exception(\"p.size ({}) != Xs0.shape[0] ({})\".format(p.size, N))\n        if N!=T.size: raise Exception(\"T.size ({}) != Xs0.shape[0] ({})\".format(T.size, N))\n\n        Xs1 = zeros(Xs0.shape)\n\n        recode = self.lib.batch_pt(N, p, T, Xs0, self.nsp, self.nel, self.lewis, self.M, self.a, Xs1, verbose)\n        if recode!=0: raise Exception(\"Equilibrium Calc Failed.\")\n        return Xs1\n\n    def batch_rhou(self, rho, u, Xs0, verbose=0):\n        \"\"\" Call c library to compute equilibrium concentrations at fixed rho, u \"\"\"\n        N, nspcheck = Xs0.shape\n        if not Xs0.flags['OWNDATA']: raise Exception(\"Xs0 Memory Error: Array must own its data\")\n        if nspcheck!=self.nsp: raise Exception(\"nsp ({}) != Xs0.shape[1] ({})\".format(self.nsp, nspcheck))\n        if N!=rho.size: raise Exception(\"rho.size ({}) != Xs0.shape[0] ({})\".format(rho.size, N))\n        if N!=u.size: raise Exception(\"u.size ({}) != Xs0.shape[0] ({})\".format(u.size, N))\n\n        Xs1 = zeros(Xs0.shape)\n        T = zeros(rho.shape)\n\n        recode = self.lib.batch_rhou(N,rho,u,Xs0,self.nsp,self.nel,self.lewis,self.M,self.a,Xs1,T,verbose)\n        if recode!=0: raise Exception(\"Equilibrium Calc Failed.\")\n        return Xs1, T\n\n    def batch_u(self, X, T):\n        \"\"\" Call c library to compute internal energy at fixed composition and temperature \"\"\"\n        N, nspcheck = X.shape\n        if not X.flags['OWNDATA']: raise Exception(\"X Memory Error: Array must own its data\")\n        if nspcheck!=self.nsp: raise Exception(\"nsp ({}) != X.shape[1] ({})\".format(self.nsp, nspcheck))\n        if N!=T.size: raise Exception(\"T.size ({}) != X.shape[0] ({})\".format(T.size, N))\n\n        u = zeros(T.shape)\n\n        recode = self.lib.batch_u(N, T, X, self.nsp, self.lewis, self.M, u)\n        if recode!=0: raise Exception(\"u calc failed.\")\n        return u\n\n    def YtoX(self, Y):\n        Mmix = 1.0/((Y/self.M).sum())\n        X = Y*Mmix/self.M\n        return X\n    \n    def XtoY(self, X):\n        Mmix = (X*self.M).sum()\n        Y = X*self.M/Mmix\n        return Y\n\nif __name__=='__main__':\n    print(\"Called pyeq main!\")\n", "meta": {"hexsha": "35a84c1493415b103bf34d43a0329edff387409c", "size": 10524, "ext": "py", "lang": "Python", "max_stars_repo_path": "source/pyeq.py", "max_stars_repo_name": "uqngibbo/ceq", "max_stars_repo_head_hexsha": "7bd4ab42f40b8a8082e20ad3768bdd53cc0d7137", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/pyeq.py", "max_issues_repo_name": "uqngibbo/ceq", "max_issues_repo_head_hexsha": "7bd4ab42f40b8a8082e20ad3768bdd53cc0d7137", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/pyeq.py", "max_forks_repo_name": "uqngibbo/ceq", "max_forks_repo_head_hexsha": "7bd4ab42f40b8a8082e20ad3768bdd53cc0d7137", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5494505495, "max_line_length": 111, "alphanum_fraction": 0.5788673508, "include": true, "reason": "from numpy", "num_tokens": 2951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.30404168127272885, "lm_q1q2_score": 0.17789513423923586}}
{"text": "from __future__ import print_function\nfrom __future__ import absolute_import\nimport shutil\nimport uuid\nimport getpass\nimport socket\nimport os\nimport sys\nimport numpy as np\nimport scipy.spatial as scsp\nimport copy\nimport time\nimport subprocess\nimport shlex\nimport yaml\n\n\nfrom morfeus import BuriedVolume\nfrom morfeus import Pyramidalization\nfrom morfeus import ConeAngle\nfrom morfeus import Sterimol\nfrom morfeus import SASA\nfrom morfeus import Dispersion\n\nimport scipy.spatial as scsp\nimport scipy.linalg as scli\nfrom rdkit import Chem\nfrom rdkit.Chem import AllChem\n\nfrom rdkit.Chem import MolFromSmiles as smi2mol\nfrom rdkit.Chem import MolToSmiles as mol2smi\n\n\n\nkcal_to_eV=0.0433641153\nkB=8.6173303e-5 #eV/K\nT=298.15\nkBT=kB*T\nAToBohr=1.889725989\n\n\n\ndef get_bonds(coords, elements, force_bonds=False, forced_bonds=[]):\n\n    # covalent radii, from Pyykko and Atsumi, Chem. Eur. J. 15, 2009, 188-197\n    # values for metals decreased by 10% according to Robert Paton's Sterimol implementation\n    rcov = {\n    \"H\": 0.34,\"He\": 0.46,\"Li\": 1.2,\"Be\": 0.94,\"B\": 0.77,\"C\": 0.75,\"N\": 0.71,\"O\": 0.63,\"F\": 0.64,\"Ne\": 0.67,\"Na\": 1.4,\"Mg\": 1.25,\"Al\": 1.13,\"Si\": 1.04,\"P\": 1.1,\"S\": 1.02,\"Cl\": 0.99,\"Ar\": 0.96,\"K\": 1.76,\"Ca\": 1.54,\"Sc\": 1.33,\"Ti\": 1.22,\"V\": 1.21,\"Cr\": 1.1,\"Mn\": 1.07,\"Fe\": 1.04,\"Co\": 1.0,\"Ni\": 0.99,\"Cu\": 1.01,\"Zn\": 1.09,\"Ga\": 1.12,\"Ge\": 1.09,\"As\": 1.15,\"Se\": 1.1,\"Br\": 1.14,\"Kr\": 1.17,\"Rb\": 1.89,\"Sr\": 1.67,\"Y\": 1.47,\"Zr\": 1.39,\"Nb\": 1.32,\"Mo\": 1.24,\"Tc\": 1.15,\"Ru\": 1.13,\"Rh\": 1.13,\"Pd\": 1.19,\"Ag\": 1.15,\"Cd\": 1.23,\"In\": 1.28,\"Sn\": 1.26,\"Sb\": 1.26,\"Te\": 1.23,\"I\": 1.32,\"Xe\": 1.31,\"Cs\": 2.09,\"Ba\": 1.76,\"La\": 1.62,\"Ce\": 1.47,\"Pr\": 1.58,\"Nd\": 1.57,\"Pm\": 1.56,\"Sm\": 1.55,\"Eu\": 1.51,\"Gd\": 1.52,\"Tb\": 1.51,\"Dy\": 1.5,\"Ho\": 1.49,\"Er\": 1.49,\"Tm\": 1.48,\"Yb\": 1.53,\"Lu\": 1.46,\"Hf\": 1.37,\"Ta\": 1.31,\"W\": 1.23,\"Re\": 1.18,\"Os\": 1.16,\"Ir\": 1.11,\"Pt\": 1.12,\"Au\": 1.13,\"Hg\": 1.32,\"Tl\": 1.3,\"Pb\": 1.3,\"Bi\": 1.36,\"Po\": 1.31,\"At\": 1.38,\"Rn\": 1.42,\"Fr\": 2.01,\"Ra\": 1.81,\"Ac\": 1.67,\"Th\": 1.58,\"Pa\": 1.52,\"U\": 1.53,\"Np\": 1.54,\"Pu\": 1.55\n    }\n\n    # partially based on code from Robert Paton's Sterimol script, which based this part on Grimme's D3 code\n    natom = len(coords)\n    #max_elem = 94\n    k1 = 16.0\n    k2 = 4.0/3.0\n    conmat = np.zeros((natom,natom))\n    bonds = []\n    for i in range(0,natom):\n        if elements[i] not in rcov.keys():\n            continue\n        for iat in range(0,natom):\n            if elements[iat] not in rcov.keys():\n                continue\n            if iat != i:\n                dx = coords[iat][0] - coords[i][0]\n                dy = coords[iat][1] - coords[i][1]\n                dz = coords[iat][2] - coords[i][2]\n                r = np.linalg.norm([dx,dy,dz])\n                rco = rcov[elements[i]]+rcov[elements[iat]]\n                rco = rco*k2\n                rr=rco/r\n                damp=1.0/(1.0+np.math.exp(-k1*(rr-1.0)))\n                if damp > 0.85: #check if threshold is good enough for general purpose\n                    conmat[i,iat],conmat[iat,i] = 1,1\n                    pair=[min(i,iat),max(i,iat)]\n                    if pair not in bonds:\n\n                        # add some empirical rules here:\n                        is_bond=True\n                        elements_bond = [elements[pair[0]], elements[pair[1]]]\n                        if \"Pd\" in elements_bond:\n                            if not (\"As\" in elements_bond or \"Cl\" in elements_bond or \"P\" in elements_bond):\n                                is_bond=False\n                        elif \"Ni\" in elements_bond:\n                            if not (\"C\" in elements_bond or \"P\" in elements_bond):\n                                is_bond=False\n                        elif \"As\" in elements_bond:\n                            if not (\"Pd\" in elements_bond or \"F\" in elements_bond):\n                                is_bond=False\n                        if is_bond:\n                            bonds.append(pair)\n\n    # remove bonds in certain cases\n    bonds_to_remove = []\n    # P has too many bonds incl one P-Cl bond which is probably to the spacer\n    P_bond_indeces=[]\n    P_bonds_elements=[]\n    for bondidx, bond in enumerate(bonds):\n        elements_bond=[elements[bond[0]],elements[bond[1]]]\n        if \"P\" in elements_bond:\n            P_bond_indeces.append(bondidx)\n            P_bonds_elements.append(elements_bond)\n    if len(P_bond_indeces)>4:\n        print(\"WARNING: found a P with more than 4 bonds. try to remove one\")\n        if [\"P\",\"Cl\"] in P_bonds_elements:\n            bonds_to_remove.append(P_bond_indeces[P_bonds_elements.index([\"P\",\"Cl\"])])\n        elif [\"Cl\",\"O\"] in P_bonds_elements:\n            bonds_to_remove.append(P_bond_indeces[P_bonds_elements.index([\"Cl\",\"P\"])])\n\n    # Cl-Cl bonds\n    for bondidx, bond in enumerate(bonds):\n        elements_bond=[elements[bond[0]],elements[bond[1]]]\n        if [\"Cl\", \"Cl\"] == elements_bond:\n            bonds_to_remove.append(bondidx)\n\n    bonds_new = []\n    for bondidx, bond in enumerate(bonds):\n        if bondidx not in bonds_to_remove:\n            bonds_new.append(bond)\n    bonds = bonds_new\n\n    # very special case where the C atoms of Ni(CO)3 make additional bonds to lone pairs of N\n    # get the indeces of the Ni(CO)3 C bonds\n    c_atom_indeces = []\n    for bondidx, bond in enumerate(bonds):\n        elements_bond=[elements[bond[0]],elements[bond[1]]]\n        if \"Ni\" == elements_bond[0] and \"C\" == elements_bond[1]:\n            # check if this C has a bond to O\n            for bondidx2, bond2 in enumerate(bonds):\n                elements_bond2=[elements[bond2[0]],elements[bond2[1]]]\n                if bond[1] in bond2 and \"O\" in elements_bond2:\n                    c_atom_indeces.append(bond[1])\n                    break\n        elif \"Ni\" == elements_bond[1] and \"C\" == elements_bond[0]:\n            for bondidx2, bond2 in enumerate(bonds):\n                elements_bond2=[elements[bond2[0]],elements[bond2[1]]]\n                if bond[0] in bond2 and \"O\" in elements_bond2:\n                    c_atom_indeces.append(bond[0])\n                    break\n\n    if len(c_atom_indeces)>0:\n        bonds_to_remove = []\n        for c_atom_idx in c_atom_indeces:\n            for bondidx, bond in enumerate(bonds):\n                elements_bond=[elements[bond[0]],elements[bond[1]]]\n                if c_atom_idx in bond and \"N\" in elements_bond:\n                    bonds_to_remove.append(bondidx)\n        bonds_new = []\n        for bondidx, bond in enumerate(bonds):\n            if bondidx not in bonds_to_remove:\n                bonds_new.append(bond)\n        bonds = bonds_new\n\n    # add forced bonds\n    if forced_bonds:\n        for b in forced_bonds:\n            b_to_add = [min(b),max(b)]\n            if b_to_add not in bonds:\n                print(\"WARNING: was forced to add a %s-%s bond that was not detected automatically.\"%(elements[b_to_add[0]],elements[b_to_add[1]]))\n                bonds.append(b_to_add)\n\n\n    # add bonds for atoms that are floating around\n    indeces_used=[]\n    for b in bonds:\n        indeces_used.append(b[0])\n        indeces_used.append(b[1])\n    indeces_used=list(set(indeces_used))\n    if len(indeces_used)<len(coords):\n        for i in range(len(coords)):\n            if i not in indeces_used:\n                e = elements[i]\n                c = coords[i]\n                distances = scsp.distance.cdist([c],coords)[0]\n                next_atom_indeces = np.argsort(distances)[1:]\n                for next_atom_idx in next_atom_indeces:\n                    b_to_add = [min([i, next_atom_idx]),max([i, next_atom_idx])]\n                    elements_bond=[elements[b_to_add[0]],elements[b_to_add[1]]]\n                    if elements_bond not in [[\"Cl\",\"H\"],[\"H\",\"Cl\"],[\"Cl\",\"F\"],[\"F\",\"Cl\"],[\"F\",\"H\"],[\"H\",\"F\"],[\"Pd\",\"F\"],[\"F\",\"Pd\"],[\"H\",\"H\"],[\"F\",\"F\"],[\"Cl\",\"Cl\"]]:\n                        print(\"WARNING: had to add a %s-%s bond that was not detected automatically.\"%(elements[b_to_add[0]],elements[b_to_add[1]]))\n                        bonds.append(b_to_add)\n                        break\n                    else:\n                        pass\n    return(bonds)\n\n\n\n\n'''\ndef get_bonds(coords, elements):\n    bondmax=1.7\n    bondmax_special1=2.2\n    bondmax_special2=2.8\n    moltree=scsp.KDTree(coords)\n    bonds=[]\n    for atomidx,atom in enumerate(coords):\n        #print(elements[atomidx])\n        if elements[atomidx].capitalize() in [\"Al\",\"S\",\"Si\",\"P\"]:\n            #print(\"this is a special atom\")\n            bondmax_here=bondmax_special1\n        elif elements[atomidx].capitalize() in [\"Ir\",\"Cu\",\"Au\",\"Pd\",\"As\", \"Ni\", \"Fe\"]:\n            #print(\"this is a special atom\")\n            bondmax_here=bondmax_special2\n        else:\n            #print(\"this is a normal atom\")\n            bondmax_here=bondmax\n        neighbours=moltree.query_ball_point(atom,bondmax_here)\n        for neighbour in neighbours:\n            if neighbour != atomidx:\n                pair=[min(neighbour, atomidx),max(neighbour, atomidx)]\n                if not pair in bonds:\n                    elements_bond=[elements[pair[0]],elements[pair[1]]]\n                    dist=np.linalg.norm(coords[pair[0]]-coords[pair[1]])\n                    if \"Pd\" in elements_bond:\n                        if \"P\" in elements_bond or \"Cl\" in elements_bond or \"As\" in elements_bond:\n                            bonds.append(pair)\n\n                    elif \"Ni\" in elements_bond:\n                        if \"P\" in elements_bond or \"C\" in elements_bond:\n                            bonds.append(pair)\n\n                    elif \"Fe\" in elements_bond:\n                        if \"H\" not in elements_bond:\n                            bonds.append(pair)\n\n                    elif \"As\" in elements_bond:\n                        if \"Pd\" in elements_bond or \"F\" in elements_bond:\n                            bonds.append(pair)\n\n                    elif \"P\" in elements_bond and \"H\" in elements_bond:\n                        if dist<bondmax:\n                            bonds.append(pair)\n\n                    elif \"P\" in elements_bond and (\"C\" in elements_bond or \"O\" in elements_bond or \"N\" in elements_bond):\n                        if dist<bondmax_special1:\n                            bonds.append(pair)\n                    else:\n                        bonds.append(pair)\n    return(bonds)\n'''\n\ndef separate_at_bond(coords, elements, bonds, bondidx, smiles):\n\n    start1=bonds[bondidx][0]\n    start2=bonds[bondidx][1]\n    dihedral_atoms=[]\n    connections1_all=[]\n    connections1_to_check=[]\n    for bondidx2,bond in enumerate(bonds):\n        if bondidx2!=bondidx:\n            if start1 == bond[0]:\n                connection_new=bond[1]\n            elif start1 == bond[1]:\n                connection_new=bond[0]\n            else:\n                continue\n            connections1_all.append(connection_new)\n            connections1_to_check.append(connection_new)\n    if len(connections1_to_check)==0:\n        exit(\"ERROR: no metal-P dihedral found for %s\"%(smiles))\n    else:\n        dihedral_atoms.append(connections1_to_check[0])\n\n    dihedral_atoms.append(start1)\n    dihedral_atoms.append(start2)\n\n    while len(connections1_to_check)>0:\n        for connection in connections1_to_check:\n            for bondidx2,bond in enumerate(bonds):\n                if bondidx2!=bondidx:\n                    if connection == bond[0]:\n                        connection_new=bond[1]\n                    elif connection == bond[1]:\n                        connection_new=bond[0]\n                    else:\n                        continue\n                    if connection_new not in connections1_all and connection_new not in connections1_to_check:\n                        connections1_to_check.append(connection_new)\n                        connections1_all.append(connection_new)\n            connections1_to_check.remove(connection)\n\n    connections2_all=[]\n    connections2_to_check=[]\n    for bondidx2,bond in enumerate(bonds):\n        if bondidx2!=bondidx:\n            if start2 == bond[0]:\n                connection_new=bond[1]\n            elif start2 == bond[1]:\n                connection_new=bond[0]\n            else:\n                continue\n            connections2_all.append(connection_new)\n            connections2_to_check.append(connection_new)\n    if len(connections2_to_check)==0:\n        exit(\"ERROR: no metal-P dihedral found for %s\"%(smiles))\n    else:\n        dihedral_atoms.append(connections2_to_check[0])\n    \n    while len(connections2_to_check)>0:\n        for connection in connections2_to_check:\n            for bondidx2,bond in enumerate(bonds):\n                if bondidx2!=bondidx:\n                    if connection == bond[0]:\n                        connection_new=bond[1]\n                    elif connection == bond[1]:\n                        connection_new=bond[0]\n                    else:\n                        continue\n                    if connection_new not in connections2_all and connection_new not in connections2_to_check:\n                        connections2_to_check.append(connection_new)\n                        connections2_all.append(connection_new)\n            connections2_to_check.remove(connection)\n    connections1_all=sorted(connections1_all)\n    connections2_all=sorted(connections2_all)\n    return(connections1_all, connections2_all)\n\n\ndef get_ligand_indeces(coords, elements, P_index, smiles, metal_char):\n\n    bonds = get_bonds(coords, elements, force_bonds=True, forced_bonds=[[P_index, elements.index(metal_char)]])\n    #indeces=[]\n    #for b in bonds:\n    #    indeces.append(b[0])\n    #    indeces.append(b[1])\n    #indeces=list(set(indeces))\n    #print(len(indeces))\n    #for i in range(len(indeces)):\n    #    if i not in indeces:\n    #        print(i, elements[i])\n    #exit()\n    #print(len(bonds))\n\n    #print(elements)\n    #print(P_index)\n    #for bondidx, bond in enumerate(bonds):\n    #    elements_bond=[elements[bond[0]],elements[bond[1]]]\n    #    print(elements_bond)\n    #exit()\n\n    found=False\n    for bondidx, bond in enumerate(bonds):\n        elements_bond=[elements[bond[0]],elements[bond[1]]]\n        if metal_char in elements_bond and \"P\" in elements_bond and P_index in bond:\n            found=True\n            break\n    if found:\n        indeces1, indeces2 = separate_at_bond(coords, elements, bonds, bondidx, smiles)\n        #print(\"group 1:\")\n        #for idx in indeces1:\n        #    element_bond = elements[idx]\n        #    print(element_bond)\n        #print(\"group 2:\")\n        #for idx in indeces2:\n        #    element_bond = elements[idx]\n        #    print(element_bond)\n        \n        if metal_char==elements_bond[0]:\n            mask=indeces2\n        else:\n            mask=indeces1\n        #print(len(mask))\n        #print(len(indeces1) + len(indeces2), len(indeces1), len(indeces2))\n        #exit()\n        return(mask, True)\n    else:\n        print(\"ERROR: No %s P bond found! %s\"%(metal_char, smiles))\n        return(None, False)\n\ndef sanitize_smiles(smi):\n    return mol2smi(smi2mol(smi, sanitize=True), isomericSmiles=False, canonical=True)\n\n\n\ndef run_crest(coords, elements, moldir, filename, settings, smiles):\n   \n    startdir=os.getcwd()\n    if settings[\"use_scratch\"]:\n        os.chdir(moldir)\n        oldcwd, scratch_directory = goToScratch()\n        oldmoldir=moldir\n        moldir=scratch_directory\n    else:\n        os.chdir(moldir)\n\n    exportXYZ(coords, elements, filename)\n    #exit()\n    time1=time.time()\n\n    done=False\n    if os.path.exists(\"crest.log\"):\n        for line in open(\"crest.log\",\"r\"):\n            if \"CREST terminated normally.\" in line:\n                done=True\n                break\n        for x in os.listdir(\".\"):\n            if x.startswith(\"OPTIM\"):\n                if os.path.isdir(x):\n                    try:\n                        shutil.rmtree(x)\n                    except:\n                        pass\n    if done and not os.path.exists(\"crest_best.xyz\"):\n        done=False\n\n\n    if not done:\n        call_crest(filename, settings)\n    else:\n        print(\"   ---   found old crest run and read output\")\n        pass\n    crest_done, coords_all, elements_all, boltzmann_data = get_crest_results(settings)\n\n    if len(elements_all)==0:\n        exit(\"ERROR: No conformers found for %s\"%(smiles))\n\n    if \"P\" not in elements_all[0]:\n        exit(\"ERROR: No P found in the first conformer of %s\"%(smiles))\n\n\n    P_index=elements_all[0].index(\"P\")\n    settings[\"P_index\"]=P_index\n\n    xtb_done=True\n    time2=time.time()\n    time_crest=time2-time1\n    coords_all_used=[]\n    elements_all_used=[]\n    boltzmann_data_used=[]\n    conf_indeces_used=[]\n    if crest_done:\n        electronic_properties_conformers=[]\n        #conf_idx=0\n        #done2=True\n        #done3=True\n        #while done2 and done3 and conf_idx<len(coords_all):\n\n        for conf_idx in range(len(coords_all)):\n\n            moldir2=\"conf_%i\"%(conf_idx)\n            try_mkdir(moldir2)\n            startdir2=os.getcwd()\n            os.chdir(moldir2)\n            filename2=\"conf_%i.xyz\"%(conf_idx)\n            skip_this_conformer = False\n            print(\"   ---   Run xtb calculation of molecule %s, conformer %i out of %i\"%(filename,conf_idx+1,len(coords_all)))\n            if settings[\"add_Pd_Cl2_PH3\"] or settings[\"add_Pd_Cl2\"] or settings[\"add_Ni_CO_3\"]:\n                P_index = settings[\"P_index\"]\n                mask, done = get_ligand_indeces(np.array(coords_all[conf_idx]),elements_all[conf_idx], P_index, smiles, settings[\"metal_char\"])\n                if not done:\n                    exit()\n                if settings[\"add_Ni_CO_3\"] and len(mask)!=len(coords_all[conf_idx])-7:\n                    print(\"WARNING: expected a mask of length 7 but got %i. Skip this conformer.\"%(len(coords_all[conf_idx])-len(mask)))\n                    skip_this_conformer=True\n            else:\n                mask=[]\n\n            if not skip_this_conformer:\n                done = False\n                if os.path.exists(\"xtb.log\") or os.path.exists(\"xtb_ipea/xtb_ipea.log\"):\n                    done1 = False\n                    for line in open(\"xtb.log\", \"r\"):\n                        if \"wall-time\" in line:\n                            done1 = True\n                            break\n                    done2 = False\n                    for line in open(\"xtb_ipea/xtb_ipea.log\", \"r\"):\n                        if \"wall-time\" in line:\n                            done2 = True\n                            break\n                    if done1 and done2:\n                        done=True\n                    else:\n                        done = False\n                        os.system(\"rm -rf *\")\n\n                if not done:\n                    exportXYZ(coords_all[conf_idx],elements_all[conf_idx],filename2, mask=mask)\n                    call_xtb(filename2, settings)\n                xtb_done_here, muls, alphas, wils, dip, alpha, fukui, HOMO_LUMO_gap, IP_delta_SCC, EA_delta_SCC, global_electrophilicity_index, esp_profile, esp_points, occ_energies, virt_energies, nucleophilicity = get_results_conformer()\n                dummy_position_done_here, dummy_positions = get_dummy_positions()\n                #print(xtb_done_here,dummy_position_done_here)\n                electronic_properties_conformers.append({\"muls\":muls,\n                                                         \"alphas\":alphas,\n                                                         \"wils\":wils,\n                                                         \"dip\":dip,\n                                                         \"alpha\":alpha,\n                                                         \"dummy_positions\":dummy_positions,\n                                                         \"fukui\":fukui,\n                                                         \"HOMO_LUMO_gap\":HOMO_LUMO_gap,\n                                                         \"IP_delta_SCC\":IP_delta_SCC,\n                                                         \"EA_delta_SCC\":EA_delta_SCC,\n                                                         \"global_electrophilicity_index\":global_electrophilicity_index,\n                                                         \"esp_profile\":esp_profile,\n                                                         \"esp_points\":esp_points,\n                                                         \"occ_energies\":occ_energies,\n                                                         \"virt_energies\":virt_energies,\n                                                         \"nucleophilicity\":nucleophilicity\n                                                         })\n                os.chdir(startdir2)\n                #conf_idx+=1\n                #print(\"did conf %i, len of data: %i\"%(conf_idx,len(electronic_properties_conformers)))\n                coords_all_used.append(coords_all[conf_idx])\n                elements_all_used.append(elements_all[conf_idx])\n                boltzmann_data_used.append(boltzmann_data[conf_idx])\n                conf_indeces_used.append(conf_idx)\n                if not xtb_done_here or not dummy_position_done_here:\n                    xtb_done=False\n    else:\n        electronic_properties_conformers=[]\n\n    time3=time.time()\n    time_xtb_sterimol=time3-time2\n\n    if settings[\"use_scratch\"]:\n        comeBachFromScratch(oldcwd, scratch_directory,settings)\n        moldir=oldmoldir\n        os.chdir(oldcwd)\n    #else:\n    #    os.chdir(moldir)\n\n    os.chdir(startdir)\n    return(crest_done, xtb_done, coords_all_used, elements_all_used, boltzmann_data_used, conf_indeces_used, electronic_properties_conformers, [time_crest, time_xtb_sterimol])\n\n\ndef get_dummy_positions():\n    dummy_positions=[]\n    done=False\n    if os.path.exists(\"lmocent.coord\"):\n        for line in open(\"lmocent.coord\",\"r\"):\n            if len(line.split())==4 and \"He\" in line:\n                dummy_positions.append([float(line.split()[0])/AToBohr,float(line.split()[1])/AToBohr,float(line.split()[2])/AToBohr])\n            if \"$end\" in line and len(dummy_positions)>0:\n                done=True\n                break\n    if done:\n        return(True, dummy_positions)\n    else:\n        return(False, None)\n\n\ndef read_crest_log():\n    read=False\n    data=[]\n    for line in open(\"crest.log\",\"r\"):\n        if \"T /K\" in line:\n            read=False\n        if read:\n            if len(line.split())>=7:\n                energy=float(line.split()[1])\n                weight=float(line.split()[4])\n                degen=int(line.split()[6])\n                if len(line.split())==8:\n                    origin=line.split()[7]\n                else:\n                    origin=None\n                data.append({\"energy\":energy,\"weight\":weight,\"degen\":degen,\"origin\":origin})\n\n        if \"Erel/kcal     Etot      weight/tot conformer  set degen    origin\" in line:\n            read=True\n    return(data)\n\n\ndef read_xtb_log():\n    read_mul=False\n    read_wil=False\n    read_dip=False\n    muls=[]\n    alphas=[]\n    wils=[]\n    dip=[0.0,0.0,0.0]\n    alpha=None\n    fukui=[]\n    read_fukui=False\n    HOMO_LUMO_gap=None\n    occ_energies=[]\n    virt_energies=[]\n    read_orbital_energies=False\n    for line in open(\"xtb.log\",\"r\"):\n        if \"convergence criteria cannot be satisfied within\" in line:\n            break\n        if read_mul and len(line.split())==0:\n            read_mul=False\n        if read_fukui and len(line.split())==0:\n            read_fukui=False\n        if read_wil and len(line.split())==0:\n            read_wil=False\n        if read_orbital_energies and len(line.split())==0:\n            read_orbital_energies=False\n        if read_dip and \"molecular quadrupole\" in line:\n            read_dip=False\n        if read_fukui:\n            if len(line.split())>4:\n                fukui.append([float(line.split()[2]),float(line.split()[3]),float(line.split()[4])])\n        if read_mul:\n            if len(line.split())==7:\n                muls.append(float(line.split()[4]))\n                alphas.append(float(line.split()[6]))\n        if read_wil:\n            if len(line.split())>2:\n                if \"*\" in line.split()[2]:\n                    wils.append(0.0)\n                else:\n                    wils.append(float(line.split()[2]))\n        if read_dip and \"full:\" in line and len(line.split())>4:\n            dip=[float(line.split()[1]),float(line.split()[2]),float(line.split()[3])]\n\n\n        if read_orbital_energies and \"occ.\" in line:\n            occ=[]\n            for x in line.split()[2:]:\n                occ.append(int(round(float(x))))\n\n        if read_orbital_energies and \"eps\" in line:\n            es=[]\n            for x in line.split()[2:]:\n                es.append(float(x))\n            if len(es)==len(occ):\n                for idx in range(len(es)):\n                    if occ[idx]>0:\n                        occ_energies.append(es[idx])\n                    else:\n                        virt_energies.append(es[idx])\n\n\n        if \"Mol. α(0) /au        :\" in line and len(line.split())==5:\n            alpha=float(line.split()[4])\n        if \"#   Z        covCN         q      C6AA      α(0)\" in line:\n            read_mul=True\n        if \"total WBO             WBO to atom ...\" in line:\n            read_wil=True\n        if \"molecular dipole:\" in line:\n            read_dip=True\n        if \"#       f(+)     f(-)     f(0)\" in line:\n            read_fukui=True\n        if \"H-L gap (eV)  :\" in line:\n            HOMO_LUMO_gap=float(line.split()[4])\n        if \"eigenvalues\" in line:\n            read_orbital_energies=True\n\n\n    global_electrophilicity_index=None\n    EA_delta_SCC=None\n    IP_delta_SCC=None\n    empirical_EA_shift=None\n    empirical_IP_shift=None\n    for line in open(\"xtb_ipea/xtb_ipea.log\",\"r\"):\n        if \"convergence criteria cannot be satisfied within\" in line:\n            break\n        if \"Global electrophilicity index (eV):\" in line:\n            global_electrophilicity_index=float(line.split()[4])\n\n        if \"empirical EA shift (eV):\" in line:\n            empirical_EA_shift=float(line.split()[4])\n        if \"delta SCC EA (eV):\" in line:\n            EA_delta_SCC=float(line.split()[4])\n\n        if \"empirical IP shift (eV):\" in line:\n            empirical_IP_shift=float(line.split()[4])\n        if \"delta SCC IP (eV):\" in line:\n            IP_delta_SCC=float(line.split()[4])\n\n    esp_profile=[]\n    for line in open(\"xtb_esp_profile.dat\",\"r\"):\n        if len(line.split())==2:\n            esp_profile.append([float(line.split()[0]), float(line.split()[1])])\n\n    esp_points=[]\n    for line in open(\"xtb_esp.dat\",\"r\"):\n        if len(line.split())==4:\n            esp_points.append([float(line.split()[0]), float(line.split()[1]), float(line.split()[2]), float(line.split()[3])])\n\n    nucleophilicity=-IP_delta_SCC\n\n    return(muls, alphas, wils, dip, alpha, fukui, HOMO_LUMO_gap, IP_delta_SCC, EA_delta_SCC, global_electrophilicity_index, esp_profile, esp_points, occ_energies, virt_energies, nucleophilicity)\n\n\ndef read_xtb_log1():\n\n    if not os.path.exists(\"xtb.log\"):\n        return(None, None, None, None, None, None, None, None, None, None, None)\n\n    read_mul=False\n    read_wil=False\n    read_dip=False\n    muls=[]\n    alphas=[]\n    wils=[]\n    dip=[0.0,0.0,0.0]\n    alpha=None\n    fukui=[]\n    read_fukui=False\n    HOMO_LUMO_gap=None\n    occ_energies=[]\n    virt_energies=[]\n    occ_done=False\n    read_orbital_energies=False\n    for line in open(\"xtb.log\",\"r\"):\n        if \"convergence criteria cannot be satisfied within\" in line:\n            break\n        if read_mul and len(line.split())==0:\n            read_mul=False\n        if read_fukui and len(line.split())==0:\n            read_fukui=False\n        if read_wil and len(line.split())==0:\n            read_wil=False\n        if read_orbital_energies and \"HL-Gap\" in line:\n            read_orbital_energies=False\n        if read_dip and \"molecular quadrupole\" in line:\n            read_dip=False\n        if read_fukui:\n            if len(line.split())>4:\n                fukui.append([float(line.split()[2]),float(line.split()[3]),float(line.split()[4])])\n        if read_mul:\n            if len(line.split())==7:\n                muls.append(float(line.split()[4]))\n                alphas.append(float(line.split()[6]))\n        if read_wil:\n            if len(line.split())>2:\n                wils.append(float(line.split()[2]))\n        if read_dip and \"full:\" in line and len(line.split())>4:\n            dip=[float(line.split()[1]),float(line.split()[2]),float(line.split()[3])]\n\n\n\n\n        if read_orbital_energies and \"-----\" not in line and \"...\" not in line and len(line.split())!=0 and \"Occupation\" not in line:\n            #print(line)\n            num_entries=len(line.split())\n            if \"(HOMO)\" in line or \"(LUMO)\" in line:\n                num_entries-=1\n            if not occ_done:\n                if num_entries==4:\n                    occ_energies.append(float(line.split()[3]))\n                elif num_entries==3:\n                    print(\"WARNING: error in parsing orbital energies\")\n                    occ_energies=[]\n                    virt_energies=[]\n                    read_orbital_energies=False\n            else:\n                if num_entries==4:\n                    if \"0.0000\" in line:\n                        pass\n                    else:\n                        print(\"WARNING: unexpected number of columns in parsing virtual energies\")\n                        print(line)\n                    virt_energies.append(float(line.split()[3]))\n                elif num_entries==3:\n                    virt_energies.append(float(line.split()[2]))\n            if \"(HOMO)\" in line:\n                occ_done=True\n\n        if \"Mol. α(0) /au        :\" in line and len(line.split())==5:\n            alpha=float(line.split()[4])\n        if \"#   Z        covCN         q      C6AA      α(0)\" in line:\n            read_mul=True\n            muls=[]\n            alphas=[]\n        if \"total WBO             WBO to atom ...\" in line:\n            read_wil=True\n            wils=[]\n        if \"molecular dipole:\" in line:\n            read_dip=True\n        if \"#       f(+)     f(-)     f(0)\" in line:\n            read_fukui=True\n            fukui=[]\n        if \":: HOMO-LUMO gap\" in line:\n            HOMO_LUMO_gap=float(line.split()[3])\n        if \"Orbital Energies and Occupations\" in line:\n            read_orbital_energies=True\n            occ_energies=[]\n            virt_energies=[]\n            occ_done=False\n\n    if len(occ_energies)==0:\n        occ_energies=None\n    else:\n        occ_energies=occ_energies[1:]\n    if len(virt_energies)==0:\n        virt_energies=None\n    else:\n        virt_energies=virt_energies[:-1]\n    if len(fukui)==0:\n        fukui=None\n    if len(wils)==0:\n        wils=None\n    if len(wils)==0:\n        wils=None\n    if len(alphas)==0:\n        alphas=None\n\n    if not os.path.exists(\"xtb_esp_profile.dat\"):\n        esp_profile=None\n    else:\n        esp_profile=[]\n        for line in open(\"xtb_esp_profile.dat\",\"r\"):\n            if len(line.split())==2:\n                esp_profile.append([float(line.split()[0]), float(line.split()[1])])\n        if len(esp_profile)==0:\n            esp_profile=None\n    if not os.path.exists(\"xtb_esp.dat\"):\n        esp_points=None\n    else:\n        esp_points=[]\n        for line in open(\"xtb_esp.dat\",\"r\"):\n            if len(line.split())==4:\n                esp_points.append([float(line.split()[0]), float(line.split()[1]), float(line.split()[2]), float(line.split()[3])])\n        if len(esp_points)==0:\n            esp_points=None\n\n    #print(HOMO_LUMO_gap, occ_energies, virt_energies)\n    return(muls, alphas, wils, dip, alpha, fukui, HOMO_LUMO_gap, esp_profile, esp_points, occ_energies, virt_energies)\n\n\ndef read_xtb_log2():\n\n    if not os.path.exists(\"xtb_ipea/xtb_ipea.log\"):\n        return(None, None, None, None)\n    #if \"conf_3\" in os.getcwd():\n    #    return(None, None, None, None)\n\n    global_electrophilicity_index=None\n    EA_delta_SCC=None\n    IP_delta_SCC=None\n    empirical_EA_shift=None\n    empirical_IP_shift=None\n    nucleophilicity=None\n    for line in open(\"xtb_ipea/xtb_ipea.log\",\"r\"):\n        if \"convergence criteria cannot be satisfied within\" in line:\n            break\n        if \"Global electrophilicity index (eV):\" in line:\n            global_electrophilicity_index=float(line.split()[4])\n\n        if \"empirical EA shift (eV):\" in line:\n            empirical_EA_shift=float(line.split()[4])\n        if \"delta SCC EA (eV):\" in line:\n            EA_delta_SCC=float(line.split()[4])\n\n        if \"empirical IP shift (eV):\" in line:\n            empirical_IP_shift=float(line.split()[4])\n        if \"delta SCC IP (eV):\" in line:\n            IP_delta_SCC=float(line.split()[4])\n            nucleophilicity=-IP_delta_SCC\n\n    return(IP_delta_SCC, EA_delta_SCC, global_electrophilicity_index, nucleophilicity)\n\n\ndef get_crest_results(settings):\n    done=False\n    if os.path.exists(\"crest.log\"):\n        for line in open(\"crest.log\",\"r\"):\n            if \"CREST terminated normally.\" in line:\n                done=True\n    else:\n        if os.path.exists(\"OPTIM\"):\n            os.system(\"rm -r OPTIM\")\n        if os.path.exists(\"METADYN1\"):\n            os.system(\"rm -r METADYN*\")\n        if os.path.exists(\"NORMMD1\"):\n            os.system(\"rm -r NORMMD*\")\n        exit(\"ERROR: DID NOT FIND CREST RESULTS: %s\"%(os.getcwd()))\n        #return(False, [], [], [])\n    if done:\n        coords_all, elements_all = readXYZs(\"crest_conformers.xyz\")\n        data = read_crest_log()\n        #if len(coords_all)>1000:\n        #    coords_all = coords_all[:1000]\n        #    elements_all = elements_all[:1000]\n        #    data = data[:1000]\n        return(True, coords_all, elements_all, data)\n    else:\n        if os.path.exists(\"OPTIM\"):\n            os.system(\"rm -r OPTIM\")\n        if os.path.exists(\"METADYN1\"):\n            os.system(\"rm -r METADYN*\")\n        exit(\"ERROR: CREST MIGHT NOT HAVE FINISHED PROPERLY: %s\"%(os.getcwd()))\n        #return(False, [], [], [])\n\n\ndef get_results_conformer():\n    done1=False\n    if os.path.exists(\"xtb.log\"):\n        #for line in open(\"xtb.log\",\"r\"):\n        #    if \"finished run on\" in line:\n        done1=True\n    done2=False\n    if os.path.exists(\"xtb_ipea/xtb_ipea.log\"):\n        #for line in open(\"xtb_ipea/xtb_ipea.log\",\"r\"):\n        #    if \"finished run on\" in line:\n        done2=True\n\n    if not done1 and not done2:\n        return(False, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None)\n\n    #if done1:\n    muls, alphas, wils, dip, alpha, fukui, HOMO_LUMO_gap, esp_profile, esp_points, occ_energies, virt_energies = read_xtb_log1()\n        \n    #if done2:\n    IP_delta_SCC, EA_delta_SCC, global_electrophilicity_index, nucleophilicity = read_xtb_log2()\n\n    return(True, muls, alphas, wils, dip, alpha, fukui, HOMO_LUMO_gap, IP_delta_SCC, EA_delta_SCC, global_electrophilicity_index, esp_profile, esp_points, occ_energies, virt_energies, nucleophilicity)\n\n\ndef xtb_opt(coords, elements, smiles, charge=0, freeze=[]):\n    rundir=\"xtb_tmpdir_%s\"%(uuid.uuid4())\n    if not os.path.exists(rundir):\n        os.makedirs(rundir)\n    else:\n        if len(os.listdir(rundir))>0:\n            os.system(\"rm %s/*\"%(rundir))\n\n    startdir=os.getcwd()\n    os.chdir(rundir)\n    exportXYZ(coords, elements, \"in.xyz\")\n\n    if len(freeze)>0:\n        outfile=open(\"xcontrol\",\"w\")\n        outfile.write(\"$fix\\n\")\n        outfile.write(\" atoms: \")\n        for counter,i in enumerate(freeze):\n            if (counter+1)<len(freeze):\n                outfile.write(\"%i,\"%(i+1))\n            else:\n                outfile.write(\"%i\\n\"%(i+1))\n        #outfile.write(\"$gbsa\\n solvent=toluene\\n\")\n        outfile.close()\n        add=\" -I xcontrol \"\n    else:\n        add=\"\"\n\n    if charge==0:\n        os.system(\"xtb %s in.xyz --opt >> xtb.log\"%(add))\n    else:\n        os.system(\"xtb %s in.xyz --opt --chrg %i >> xtb.log\"%(add,charge))\n    if not os.path.exists(\"xtbopt.xyz\"):\n        print(\"WARNING: xtb geometry optimization did not work %s\"%(smiles))\n        os.chdir(startdir)\n        os.system(\"rm -r %s\"%(rundir))\n        return(coords, elements)\n            \n    coords_new, elements_new=readXYZ(\"xtbopt.xyz\")\n    os.chdir(startdir)\n    os.system(\"rm -r %s\"%(rundir))\n    return(coords_new, elements_new)\n\n\n\n\n\ndef call_crest(filename, settings):\n\n    os.environ[\"OMP_NUM_THREADS\"]=\"%s\"%(settings[\"OMP_NUM_THREADS\"])\n    os.environ[\"MKL_NUM_THREADS\"]=\"%s\"%(settings[\"MKL_NUM_THREADS\"])\n    command=\"crest %s --gbsa toluene -metac -nozs\"%(filename)\n    #command=\"crest %s --gbsa toluene -metac\"%(filename)\n    #command=\"crest %s -ethr %f -pthi %f -metac\"%(filename, settings[\"max_E\"], settings[\"max_p\"])\n    # crest -chrg %i is used for charges\n    args = shlex.split(command)\n    mystdout = open(\"crest.log\",\"a\")\n\n    process = subprocess.Popen(args, stdout=mystdout, stderr=subprocess.PIPE)\n    out, err = process.communicate()\n    mystdout.close()\n    time.sleep(5)\n    if settings[\"reduce_output\"]:\n        for x in os.listdir(\".\"):\n            if x.startswith(\"M\") or x.startswith(\"N\") or x==\"wbo\" or x==\"coord\" or \"_rotamers_\" in x or \".tmp\" in x or x.startswith(\".\") or x==\"coord.original\":\n                if os.path.isdir(x):\n                    try:\n                        shutil.rmtree(x)\n                    except:\n                        pass\n                elif os.path.isfile(x):\n                    try:\n                        os.remove(x)\n                    except:\n                        pass\n    return()\n\n\ndef call_xtb(filename, settings):\n\n    os.environ[\"OMP_NUM_THREADS\"]=\"%s\"%(settings[\"OMP_NUM_THREADS\"])\n    os.environ[\"MKL_NUM_THREADS\"]=\"%s\"%(settings[\"MKL_NUM_THREADS\"])\n    command=\"xtb --gbsa toluene --lmo --vfukui --esp %s\"%(filename)\n    # check if xcontrol works\n    args = shlex.split(command)\n    mystdout = open(\"xtb.log\",\"a\")\n    process = subprocess.Popen(args, stdout=mystdout, stderr=subprocess.PIPE)\n    out, err = process.communicate()\n    mystdout.close()\n    if settings[\"reduce_output\"]:\n        for x in os.listdir(\".\"):\n            if \"coordprot\" in x or x==\"wbo\" or x==\"xtbrestart\" or x==\"xtbscreen.xyz\":\n                if os.path.isdir(x):\n                    try:\n                        shutil.rmtree(x)\n                    except:\n                        pass\n                elif os.path.isfile(x):\n                    try:\n                        os.remove(x)\n                    except:\n                        pass\n\n    try_mkdir(\"xtb_ipea\")\n    startdir=os.getcwd()\n    os.chdir(\"xtb_ipea\")\n    os.system(\"mv %s/%s .\"%(startdir,filename))\n    command=\"xtb --gbsa toluene --vomega --vipea %s\"%(filename)\n    # check if xcontrol works\n    args = shlex.split(command)\n    mystdout = open(\"xtb_ipea.log\",\"a\")\n    process = subprocess.Popen(args, stdout=mystdout, stderr=subprocess.PIPE)\n    out, err = process.communicate()\n    mystdout.close()\n    if settings[\"reduce_output\"]:\n        for x in os.listdir(\".\"):\n            if \"coordprot\" in x or x==\"wbo\" or x==\"xtbrestart\" or x==\"xtbscreen.xyz\" or x==\"conf_0.xyz\":\n                if os.path.isdir(x):\n                    try:\n                        shutil.rmtree(x)\n                    except:\n                        pass\n                elif os.path.isfile(x):\n                    try:\n                        os.remove(x)\n                    except:\n                        pass\n    os.chdir(startdir)\n    return()\n\n\n\ndef readXYZ(filename):\n    infile=open(filename,\"r\")\n    coords=[]\n    elements=[]\n    lines=infile.readlines()\n    if len(lines)<3:\n        exit(\"ERROR: no coordinates found in %s/%s\"%(os.getcwd(), filename))\n    for line in lines[2:]:\n        elements.append(line.split()[0].capitalize())\n        coords.append([float(line.split()[1]),float(line.split()[2]),float(line.split()[3])])\n    infile.close()\n    coords=np.array(coords)\n    return coords,elements\n\n\n\ndef readXYZs(filename):\n    infile=open(filename,\"r\")\n    coords=[[]]\n    elements=[[]]\n    for line in infile.readlines():\n        if len(line.split())==1 and len(coords[-1])!=0:\n            coords.append([])\n            elements.append([])\n        elif len(line.split())==4:\n            elements[-1].append(line.split()[0].capitalize())\n            coords[-1].append([float(line.split()[1]),float(line.split()[2]),float(line.split()[3])])\n    infile.close()\n    return coords,elements\n\ndef exportXYZ(coords,elements,filename, mask=[]):\n    outfile=open(filename,\"w\")\n\n    if len(mask)==0:\n        outfile.write(\"%i\\n\\n\"%(len(elements)))\n        for atomidx,atom in enumerate(coords):\n            outfile.write(\"%s %f %f %f\\n\"%(elements[atomidx].capitalize(),atom[0],atom[1],atom[2]))\n    else:\n        outfile.write(\"%i\\n\\n\"%(len(mask)))\n        for atomidx in mask:\n            atom = coords[atomidx]\n            outfile.write(\"%s %f %f %f\\n\"%(elements[atomidx].capitalize(),atom[0],atom[1],atom[2]))\n    outfile.close()\n\ndef exportXYZs(coords,elements,filename):\n    outfile=open(filename,\"w\")\n    for idx in range(len(coords)):\n        outfile.write(\"%i\\n\\n\"%(len(elements[idx])))\n        for atomidx,atom in enumerate(coords[idx]):\n            outfile.write(\"%s %f %f %f\\n\"%(elements[idx][atomidx].capitalize(),atom[0],atom[1],atom[2]))\n    outfile.close()\n\n\n\ndef try_mkdir(dirname):\n    if not os.path.exists(dirname):\n        try:\n            os.makedirs(dirname)\n        except:\n            pass\n\n\n\ndef run_sterimol(coords, elements, dummy_positions, moldir, settings, smiles):\n    \n\n\n    if settings[\"add_Pd_Cl2_PH3\"] or settings[\"add_Pd_Cl2\"] or settings[\"add_Ni_CO_3\"]:\n        P_index = settings[\"P_index\"]\n        metal_char=settings[\"metal_char\"]\n\n        mask, done = get_ligand_indeces(np.array(coords), elements, P_index, smiles, settings[\"metal_char\"])\n        if not done:\n            exit()\n        for idx,e in enumerate(elements):\n            if e==metal_char:\n                break\n        pd_idx_full_ligand=idx\n        \n        # extend the molecule\n        coords_list=[]\n        elements_list=[]\n        coords_extended=[]\n        elements_extended=[]\n        for atomidx in mask:\n            atom = coords[atomidx]\n            elements_extended.append(elements[atomidx])\n            coords_extended.append([atom[0],atom[1],atom[2]])\n            coords_list.append([atom[0],atom[1],atom[2]])\n            elements_list.append(elements[atomidx])\n        #print(coords_extended)\n        coords_extended.append(coords[pd_idx_full_ligand])\n        elements_extended+=[metal_char]\n\n        for idx,e in enumerate(elements_extended):\n            if e==\"P\":\n                break\n        p_idx=idx\n        for idx,e in enumerate(elements_extended):\n            if e==metal_char:\n                break\n        pd_idx=idx\n\n        dummy_idx=len(elements_extended)-1\n\n        outfile=open(\"%s/sterimol_input.xyz\"%(moldir),\"w\")\n        outfile.write(\"%i\\nindeces: %i and %i\\n\"%(len(coords_extended),dummy_idx,p_idx))\n        for idx,atom in enumerate(coords_extended):\n            outfile.write(\"%s %f %f %f\\n\"%(elements_extended[idx],atom[0],atom[1],atom[2]))\n        outfile.close()\n        selected_dummy_idx=-1\n    else:\n        # get P position\n        for idx,e in enumerate(elements):\n            if e==\"P\":\n                break\n        p_idx=idx\n        #print(\"p-idx: %i\"%(p_idx))\n\n\n        # get the correct dummy atom\n        dummy_distances_to_p=scsp.distance.cdist([coords[p_idx]],dummy_positions)[0]\n        #print(dummy_distances_to_p)\n        #print(\"number of dummy positions: %i\"%(len(dummy_positions)))\n        nearest_dummy_indeces=np.argsort(dummy_distances_to_p)[:4]\n        atom_distances_to_p=scsp.distance.cdist([coords[p_idx]],coords)[0]\n        neighbor_indeces=np.argsort(atom_distances_to_p)[1:4]\n        neighbor_dummy_distances=scsp.distance.cdist(np.array(dummy_positions)[nearest_dummy_indeces],np.array(coords)[neighbor_indeces])\n        #print(neighbor_dummy_distances)\n        minimal_distances=np.min(neighbor_dummy_distances,axis=1)\n        #print(minimal_distances)\n        dummy_atom_with_largest_minimal_distance=np.argmax(minimal_distances)\n        selected_dummy_idx=nearest_dummy_indeces[dummy_atom_with_largest_minimal_distance]\n        #print(selected_dummy_idx)\n        \n        # get the direction from P to dummy\n        dummy_direction=np.array(dummy_positions[selected_dummy_idx])-np.array(coords[p_idx])\n        dummy_direction_norm=np.linalg.norm(dummy_direction)\n        dummy_direction/=dummy_direction_norm\n\n        # go from p into dummy direction\n        dummy_position=np.array(coords[p_idx])+settings[\"dummy_distance\"]*dummy_direction\n\n\n        # extend the molecule\n        coords_list=[]\n        elements_list=[]\n        coords_extended=[]\n        for atomidx,atom in enumerate(coords):\n            coords_extended.append([atom[0],atom[1],atom[2]])\n            coords_list.append([atom[0],atom[1],atom[2]])\n            elements_list.append(elements[atomidx])\n        #print(coords_extended)\n        coords_extended.append(dummy_position.tolist())\n        elements_extended=elements+[\"H\"]\n        dummy_idx=len(elements_extended)-1\n\n        outfile=open(\"%s/sterimol_input.xyz\"%(moldir),\"w\")\n        outfile.write(\"%i\\nindeces: %i and %i\\n\"%(len(coords_extended),dummy_idx,p_idx))\n        for idx,atom in enumerate(coords_extended):\n            outfile.write(\"%s %f %f %f\\n\"%(elements_extended[idx],atom[0],atom[1],atom[2]))\n        outfile.close()\n\n    \n    # call sterimol OLD\n    #file_Params = calcSterimol(\"\", \"bondi\", dummy_idx+1, p_idx+1, False, get_coords=True, coords=coords_extended, elements=elements_extended)\n    #lval_old = float(file_Params.lval)\n    #B1_old = float(file_Params.B1)\n    #B5_old = float(file_Params.newB5)\n    #print(\"  %.2f\"% lval, \"  %.2f\"% B1, \"  %.2f\"% B5)\n\n    #print(len(coords_extended))\n    #print(len(elements_extended))\n    #print(dummy_idx)\n    #print(p_idx)\n    #print(elements_extended)\n\n\n    # call steriplus NEW\n    #print(\"coords_extended before steriplus: %i\"%(len(coords_extended)))\n    try:\n        if len(elements_extended)!=len(coords_extended):\n            print(\"WARNING: ConeAngle calculation got coords and elements with different sizes!\")\n        cone_angle = ConeAngle(elements_extended, coords_extended, dummy_idx+1)\n        cone_angle_val = cone_angle.cone_angle\n    except:\n        cone_angle_val = 0.0\n\n    #cone_angle.plot_3D()\n    #print(\"coords_extended after cone: %i\"%(len(coords_extended)))\n\n    try:\n        if len(elements_list)!=len(coords_list):\n            print(\"WARNING: SASA calculation got coords and elements with different sizes!\")\n        sasa = SASA(elements_list, coords_list)\n        sasa_val = sasa.area\n        sasa_val_P = sasa.atom_areas[p_idx+1]\n        sasa_volume = sasa.volume\n        sasa_volume_P = sasa.atom_volumes[p_idx+1]\n    except:\n        sasa_val = 0.0\n        sasa_val_P = 0.0\n        sasa_volume = 0.0\n        sasa_volume_P = 0.0\n    #print(\"coords_extended after sasa: %i\"%(len(coords_extended)))\n\n    try:\n        if len(elements_extended)!=len(coords_extended):\n            print(\"WARNING: Sterimol calculation got coords and elements with different sizes!\")\n        sterimol = Sterimol(elements_extended, coords_extended, dummy_idx+1, p_idx+1)\n        lval = sterimol.L_value\n        B1 = sterimol.B_1_value\n        B5 = sterimol.B_5_value\n    except:\n        lval = 0.0\n        B1 = 0.0\n        B5 = 0.0\n    #print(\"coords_extended after sterimol: %i\"%(len(coords_extended)))\n\n\n    try:\n        if len(elements_extended)!=len(coords_extended):\n            print(\"WARNING: BuriedVolume calculation got coords and elements with different sizes!\")\n        bv = BuriedVolume(elements_extended, coords_extended, dummy_idx+1, exclude_list=[dummy_idx+1])\n        buried_volume = bv.buried_volume\n    except:\n        buried_volume = 0.0\n\n    try:\n        if len(elements_list)!=len(coords_list):\n            print(\"WARNING: Dispersion calculation got coords and elements with different sizes!\")\n        disp = Dispersion(elements_list, coords_list)\n        p_int = disp.p_int\n        p_int_atoms = disp.atom_p_ints\n        p_int_atom = p_int_atoms[p_idx+1]\n        p_int_area = disp.area\n        p_int_atom_areas = disp.atom_areas\n        p_int_atom_area = p_int_atom_areas[p_idx+1]\n        p_int_times_p_int_area = p_int*p_int_area\n        p_int_atom_times_p_int_atom_area = p_int_atom*p_int_atom_area\n    except:\n        p_int = 0.0\n        p_int_atom = 0.0\n        p_int_area = 0.0\n        p_int_atom_area = 0.0\n        p_int_times_p_int_area = 0.0\n        p_int_atom_times_p_int_atom_area = 0.0\n\n\n    results={\"lval\": float(lval),\n             \"B1\": float(B1),\n             \"B5\": float(B5),\n             \"buried_volume\": float(buried_volume),\n             \"sasa\": float(sasa_val),\n             \"sasa_P\": float(sasa_val_P),\n             \"sasa_volume\": float(sasa_volume),\n             \"sasa_volume_P\": float(sasa_volume_P),\n             \"cone_angle\": float(cone_angle_val),\n             \"p_int\": float(p_int),\n             \"p_int_atom\": float(p_int_atom),\n             \"p_int_area\": float(p_int_area),\n             \"p_int_atom_area\": float(p_int_atom_area),\n             \"p_int_times_p_int_area\": float(p_int_times_p_int_area),\n             \"p_int_atom_times_p_int_atom_area\": float(p_int_atom_times_p_int_atom_area),\n             \"selected_dummy_idx\": int(selected_dummy_idx),\n             \"coords_extended\": coords_extended,\n             \"elements_extended\": elements_extended,\n             \"dummy_idx\": int(dummy_idx),\n             \"p_idx\": int(p_idx)\n             }\n    return(results)\n\n\ndef run_morfeus(coords, elements, dummy_positions, moldir, settings, smiles):\n\n    outfilename=\"%s/morfeus.yml\"%(moldir)\n\n    if os.path.exists(outfilename):\n        infile=open(outfilename,\"r\")\n        results = yaml.load(infile, Loader=yaml.FullLoader)\n        infile.close()\n        return(results)\n\n    times={}\n    time0=time.time()\n    do_pyramid=True\n    if settings[\"add_Pd_Cl2_PH3\"] or settings[\"add_Pd_Cl2\"] or settings[\"add_Ni_CO_3\"]:\n        P_index = settings[\"P_index\"]\n        metal_char=settings[\"metal_char\"]\n\n        mask, done = get_ligand_indeces(np.array(coords), elements, P_index, smiles, settings[\"metal_char\"])\n        if not done:\n            exit()\n        for idx,e in enumerate(elements):\n            if e==metal_char:\n                break\n        pd_idx_full_ligand=idx\n\n        # extend the molecule\n        coords_list=[]\n        elements_list=[]\n        coords_extended=[]\n        elements_extended=[]\n        for atomidx in mask:\n            atom = coords[atomidx]\n            elements_extended.append(elements[atomidx])\n            coords_extended.append([atom[0],atom[1],atom[2]])\n            coords_list.append([atom[0],atom[1],atom[2]])\n            elements_list.append(elements[atomidx])\n        #print(coords_extended)\n        coords_extended.append(coords[pd_idx_full_ligand])\n\n        elements_extended+=[metal_char]\n\n        for idx,e in enumerate(elements_extended):\n            if e==\"P\":\n                break\n        p_idx=idx\n        for idx,e in enumerate(elements_extended):\n            if e==metal_char:\n                break\n        pd_idx=idx\n\n\n        dummy_idx=len(elements_extended)-1\n\n        outfile=open(\"%s/sterimol_input.xyz\"%(moldir),\"w\")\n        outfile.write(\"%i\\nindeces: %i and %i\\n\"%(len(coords_extended),dummy_idx,p_idx))\n        for idx,atom in enumerate(coords_extended):\n            outfile.write(\"%s %f %f %f\\n\"%(elements_extended[idx],atom[0],atom[1],atom[2]))\n        outfile.close()\n\n\n        atom_distances_to_p = scsp.distance.cdist([coords_extended[p_idx]],coords_extended)[0]\n        neighbor_indeces = [i for i in np.argsort(atom_distances_to_p)[1:4] if i != pd_idx]\n        \n        if len(neighbor_indeces)!=3:\n            print(\"WARNING: found %i instead of 3 neighbor indeces for ligand with %s (%s %s)\"%(len(neighbor_indeces), metal_char, os.getcwd(), moldir))\n            do_pyramid=False\n\n        selected_dummy_idx=-1\n    else:\n        # get P position\n        for idx,e in enumerate(elements):\n            if e==\"P\":\n                break\n        p_idx=idx\n        #print(\"p-idx: %i\"%(p_idx))\n\n        # get the correct dummy atom\n        dummy_distances_to_p=scsp.distance.cdist([coords[p_idx]],dummy_positions)[0]\n        #print(dummy_distances_to_p)\n        #print(\"number of dummy positions: %i\"%(len(dummy_positions)))\n        nearest_dummy_indeces=np.argsort(dummy_distances_to_p)[:4]\n        atom_distances_to_p=scsp.distance.cdist([coords[p_idx]],coords)[0]\n        neighbor_indeces=np.argsort(atom_distances_to_p)[1:4]\n        neighbor_dummy_distances=scsp.distance.cdist(np.array(dummy_positions)[nearest_dummy_indeces],np.array(coords)[neighbor_indeces])\n        #print(neighbor_dummy_distances)\n        minimal_distances=np.min(neighbor_dummy_distances,axis=1)\n        #print(minimal_distances)\n        dummy_atom_with_largest_minimal_distance=np.argmax(minimal_distances)\n        selected_dummy_idx=nearest_dummy_indeces[dummy_atom_with_largest_minimal_distance]\n        #print(selected_dummy_idx)\n        \n        # get the direction from P to dummy\n        dummy_direction=np.array(dummy_positions[selected_dummy_idx])-np.array(coords[p_idx])\n        dummy_direction_norm=np.linalg.norm(dummy_direction)\n        dummy_direction/=dummy_direction_norm\n\n        # go from p into dummy direction\n        dummy_position=np.array(coords[p_idx])+settings[\"dummy_distance\"]*dummy_direction\n\n        # extend the molecule\n        coords_list=[]\n        elements_list=[]\n        coords_extended=[]\n        for atomidx,atom in enumerate(coords):\n            coords_extended.append([atom[0],atom[1],atom[2]])\n            coords_list.append([atom[0],atom[1],atom[2]])\n            elements_list.append(elements[atomidx])\n        #print(coords_extended)\n        coords_extended.append(dummy_position.tolist())\n        elements_extended=elements+[\"H\"]\n        dummy_idx=len(elements_extended)-1\n\n        outfile=open(\"%s/sterimol_input.xyz\"%(moldir),\"w\")\n        outfile.write(\"%i\\nindeces: %i and %i\\n\"%(len(coords_extended),dummy_idx,p_idx))\n        for idx,atom in enumerate(coords_extended):\n            outfile.write(\"%s %f %f %f\\n\"%(elements_extended[idx],atom[0],atom[1],atom[2]))\n        outfile.close()\n\n    time1=time.time()\n    times[\"preparation\"]=time1-time0\n\n    # start morfeus stuff\n    try:\n        if len(elements_extended)!=len(coords_extended):\n            print(\"WARNING: ConeAngle calculation got coords and elements with different sizes!\")\n        cone_angle = ConeAngle(elements_extended, coords_extended, dummy_idx+1)\n        cone_angle_val = float(cone_angle.cone_angle)\n    except:\n        print(\"WARNING: morfeus cone angle failed\")\n        cone_angle_val = None\n\n    time2=time.time()\n    times[\"ConeAngle\"]=time2-time1\n\n    #cone_angle.plot_3D()\n    #print(\"coords_extended after cone: %i\"%(len(coords_extended)))\n\n    try:\n        if len(elements_list)!=len(coords_list):\n            print(\"WARNING: SASA calculation got coords and elements with different sizes!\")\n        sasa = SASA(elements_list, coords_list)\n        sasa_val = float(sasa.area)\n        sasa_val_P = float(sasa.atom_areas[p_idx+1])\n        sasa_volume = float(sasa.volume)\n        sasa_volume_P = float(sasa.atom_volumes[p_idx+1])\n    except:\n        print(\"WARNING: morfeus sasa failed\")\n        sasa_val = None\n        sasa_val_P = None\n        sasa_volume = None\n        sasa_volume_P = None\n    #print(\"coords_extended after sasa: %i\"%(len(coords_extended)))\n\n    time3=time.time()\n    times[\"SASA\"]=time3-time2\n\n    try:\n        if len(elements_extended)!=len(coords_extended):\n            print(\"WARNING: Sterimol calculation got coords and elements with different sizes!\")\n        sterimol = Sterimol(elements_extended, coords_extended, dummy_idx+1, p_idx+1)\n        lval = float(sterimol.L_value)\n        B1 = float(sterimol.B_1_value)\n        B5 = float(sterimol.B_5_value)\n    except:\n        print(\"WARNING: morfeus sterimol failed\")\n        lval = None\n        B1 = None\n        B5 = None\n    #print(\"coords_extended after sterimol: %i\"%(len(coords_extended)))\n\n    time4=time.time()\n    times[\"Sterimol\"]=time4-time3\n\n    try:\n        if len(elements_list)!=len(coords_list):\n            print(\"WARNING: Dispersion calculation got coords and elements with different sizes!\")\n        disp = Dispersion(elements_list, np.array(coords_list))\n        p_int = float(disp.p_int)\n        p_int_atoms = disp.atom_p_int\n        p_int_atom = float(p_int_atoms[p_idx+1])\n        p_int_area = float(disp.area)\n        p_int_atom_areas = disp.atom_areas\n        p_int_atom_area = float(p_int_atom_areas[p_idx+1])\n        p_int_times_p_int_area = float(p_int*p_int_area)\n        p_int_atom_times_p_int_atom_area = float(p_int_atom*p_int_atom_area)\n    except:\n        print(\"WARNING: morfeus dispersion failed\")\n        p_int = None\n        p_int_atom = None\n        p_int_area = None\n        p_int_atom_area = None\n        p_int_times_p_int_area = None\n        p_int_atom_times_p_int_atom_area = None\n\n    time5=time.time()\n    times[\"Dispersion\"]=time5-time4\n\n    # Pyramidalization - two equivalent measurments P and alpha\n    if do_pyramid:\n        try:\n            pyr = Pyramidalization(elements = elements_extended, coordinates = coords_extended, atom_index = p_idx+1, excluded_atoms = [dummy_idx+1]) # remove Pd\n            pyr_val = float(pyr.P)\n            pyr_alpha = float(pyr.alpha)\n        except:\n            print(\"WARNING: morfeus Pyramidalization failed\")\n            pyr_val = None\n            pyr_alpha = None\n    else:\n        pyr_val = None\n        pyr_alpha = None\n\n    time6=time.time()\n    times[\"Pyramidalization\"]=time6-time5\n            \n    #Buried volume - get quadrant volumes and distal volume \n    # iterate through P-substituents, aligning the quadrants paralell to each once (= xz_plane definition)\n    # Metal/point of reference should be 2.28 A away from P\n    # z_axis_atoms: P  \n    # xz_plane_atoms: each of the substituents once\n    # keep lowest and highest quadrant and octant volume across all three orientations of the coordinate system\n    # keep highest difference of any neighboring quadrant volume\n    # keep volume in each of the two hemispheres \n\n    try:\n        qvbur_all = np.array([])\n        qvdist_all = np.array([])\n        qvtot_all = np.array([])\n        max_delta_qvbur_all = []\n        max_delta_qvtot_all = []\n        ovbur_all = np.array([])\n        ovtot_all = np.array([])\n\n        for i in neighbor_indeces:  \n            bv = BuriedVolume(elements_extended, coords_extended, dummy_idx+1, excluded_atoms=[dummy_idx+1], z_axis_atoms=[p_idx+1], xz_plane_atoms=[i+1], density=0.01) # dummy_idx+1 = 2\n            bv.octant_analysis()\n            bv.compute_distal_volume(method=\"buried_volume\", octants=True)\n\n            vbur = bv.buried_volume   # these are identical for each iteration\n            #vbur = bv.percent_buried_volume   # these are identical for each iteration\n            vdist = bv.distal_volume  #  \n            vtot = vbur + vdist       #  \n\n            qvbur = np.asarray(list(bv.quadrants[\"buried_volume\"].values()))\n            qvdist = np.asarray(list(bv.quadrants[\"distal_volume\"].values()))\n            qvtot = qvbur + qvdist\n            \n            qvbur_all = np.append(qvbur_all,qvbur)\n            qvtot_all = np.append(qvtot_all,qvtot)\n\n            max_delta_qvbur_all.append(max([abs(qvbur[i]-qvbur[i-1]) for i in range(4)]))\n            max_delta_qvtot_all.append(max([abs(qvtot[i]-qvtot[i-1]) for i in range(4)]))\n\n            ovbur = np.asarray(list(bv.octants[\"buried_volume\"].values()))\n            ovdist = np.asarray(list(bv.octants[\"distal_volume\"].values()))\n            ovtot = ovbur + ovdist\n\n            ovbur_all = np.append(ovbur_all,ovbur)\n            ovtot_all = np.append(ovtot_all,ovtot)\n\n            near_vbur = ovbur[4:].sum()   # these are identical for each iteration\n            far_vbur = ovbur[:4].sum()    # \n            near_vtot = ovtot[4:].sum()   # \n            far_vtot = ovtot[:4].sum()    # \n            \n        qvbur_min = float(min(qvbur_all))\n        qvbur_max = float(max(qvbur_all))\n        qvtot_min = float(min(qvtot_all))\n        qvtot_max = float(max(qvtot_all))\n\n        max_delta_qvbur = float(max(max_delta_qvbur_all))\n        max_delta_qvtot = float(max(max_delta_qvtot_all))\n\n        ovbur_min = float(min(ovbur_all))\n        ovbur_max = float(max(ovbur_all))\n        ovtot_min = float(min(ovtot_all))\n        ovtot_max = float(max(ovtot_all))\n\n        # this is just a reminder to keep these properties\n        vbur = float(vbur)\n        vtot = float(vtot)\n        near_vbur = float(near_vbur)\n        far_vbur = float(far_vbur)\n        near_vtot = float(near_vtot)\n        far_vtot = float(far_vtot)\n\n\n    except:\n        print(\"WARNING: morfeus BuriedVolume failed\")\n        qvbur_min = None\n        qvbur_max = None\n        qvtot_min = None\n        qvtot_max = None\n\n        max_delta_qvbur = None\n        max_delta_qvtot = None\n\n        ovbur_min = None\n        ovbur_max = None\n        ovtot_min = None\n        ovtot_max = None\n\n        vbur = None\n        vtot = None\n        near_vbur = None\n        far_vbur = None\n        near_vtot = None\n        far_vtot = None\n\n    time7=time.time()\n    times[\"BuriedVolume\"]=time7-time6\n    #print(times)\n\n\n    results={\"lval\": lval,\n             \"B1\": B1,\n             \"B5\": B5,\n             \"sasa\": sasa_val,\n             \"sasa_P\": sasa_val_P,\n             \"sasa_volume\": sasa_volume,\n             \"sasa_volume_P\": sasa_volume_P,\n             \"cone_angle\": cone_angle_val,\n             \"p_int\": p_int,\n             \"p_int_atom\": p_int_atom,\n             \"p_int_area\": p_int_area,\n             \"p_int_atom_area\": p_int_atom_area,\n             \"p_int_times_p_int_area\": p_int_times_p_int_area,\n             \"p_int_atom_times_p_int_atom_area\": p_int_atom_times_p_int_atom_area,\n             \"pyr_val\": pyr_val,\n             \"pyr_alpha\": pyr_alpha,\n             \"qvbur_min\": qvbur_min,\n             \"qvbur_max\": qvbur_max,\n             \"qvtot_min\": qvtot_min,\n             \"qvtot_max\": qvtot_max,\n             \"max_delta_qvbur\": max_delta_qvbur,\n             \"max_delta_qvtot\": max_delta_qvtot,\n             \"ovbur_min\": ovbur_min,\n             \"ovbur_max\": ovbur_max,\n             \"ovtot_min\": ovtot_min,\n             \"ovtot_max\": ovtot_max,\n             \"vbur\": vbur,\n             \"vtot\": vtot,\n             \"near_vbur\": near_vbur,\n             \"far_vbur\": far_vbur,\n             \"near_vtot\": near_vtot,\n             \"far_vtot\": far_vtot,\n             \"selected_dummy_idx\": int(selected_dummy_idx),\n             \"coords_extended\": coords_extended,\n             \"elements_extended\": elements_extended,\n             \"dummy_idx\": int(dummy_idx),\n             \"p_idx\": int(p_idx)\n             }\n\n    outfilename=\"%s/morfeus.yml\"%(moldir)\n    outfile=open(outfilename, \"w\")\n    outfile.write(yaml.dump(results, default_flow_style=False))\n    outfile.close()\n\n\n    return(results)\n\n\n\n\ndef copy_dir_contents_to_dir(in_directory, out_directory):\n    try:\n        #We copy all files in in_directory to out_directory without following directories recursively:\n        for filename in os.listdir(in_directory):\n            file_with_dir = \"%s/%s\" % (in_directory, filename)\n            if os.path.isfile(file_with_dir):\n                shutil.copy(file_with_dir, out_directory)\n            elif os.path.isdir(file_with_dir):\n                shutil.copytree(file_with_dir, \"%s/%s\"%(out_directory,filename))\n    except Exception as exc:\n        print(\"Moving files to from %s to %s has failed. Reraising Exception: %s.\" % (exc))\n        raise\n\n\ndef copy_to_scratch(in_directory):\n    try:\n        #We generate the directory $SCRATCH/username/random-uuid\n        SCRATCH_BASE = os.environ[\"SCRATCH\"]\n        username = getpass.getuser()\n        randstring = uuid.uuid4()\n        out_directory = \"%s/%s/%s\" % (SCRATCH_BASE, username, randstring)\n        os.makedirs(out_directory)\n        socketname = socket.gethostname()\n        outfile = open(\"tmpdir.dat\", \"w\")\n        outfile.write(\"%s\\n%s\\n\" % (socketname, out_directory))\n        outfile.close()\n        #and copy everything over:\n        copy_dir_contents_to_dir(in_directory, out_directory)\n        return in_directory, out_directory\n    except IOError as exc:\n        #In case of IOError or KeyError, we just return both times in-directory.\n        print(\"Moving files to scratch has failed. Exception was IOError: %s. Turning off scratch handling.\" % (exc))\n        return in_directory, in_directory\n    except KeyError as exc:\n        print(\"A KeyError occured, when querying the Scratch Directory. Check the environment settings. Exception was: %s. Turning off scratch handling.\" % ( exc ))\n        return in_directory, in_directory\n    except Exception as exc:\n        #In case there was something unforseen, we reraise to bomb out of the application.\n        print(\"An unexpected exception as occured of type %s. Exception was: %s. Reraising.\" % (type(exc), exc))\n        raise\n\ndef goToScratch():\n    oldcwd = os.getcwd()\n    scratch_directory = \"\"\n    #make scratch dir, enter scratch dir - save oldcwd\n    oldcwd, scratch_directory = copy_to_scratch(oldcwd)\n    os.chdir(scratch_directory)\n    return [oldcwd, scratch_directory]\n\n\ndef comeBachFromScratch(oldcwd, scratch_directory,settings):\n    if oldcwd != scratch_directory:\n        #copy result back to oldcwd, change back, remove scratch\n        copy_dir_contents_to_dir(scratch_directory, oldcwd)\n        os.chdir(oldcwd)\n        if settings[\"remove_scratch\"]:\n            try:\n                shutil.rmtree(scratch_directory)\n            except:\n                pass\n        os.system(\"rm tmpdir.dat\")\n    else:\n        print(\"Warning, oldcwd \", oldcwd, \"was equal to scratch_directory\", scratch_directory, \"review log for exceptions.\")\n\n\n\n\n\n\n\ndef rotationMatrix(vector,angle):\n    angle=angle/180.0*np.pi\n    norm=(vector[0]**2.0+vector[1]**2.0+vector[2]**2.0)**0.5\n    direction=vector/norm\n\n    matrix=np.zeros((3,3))\n    matrix[0][0]=direction[0]**2.0*(1.0-np.cos(angle))+np.cos(angle)\n    matrix[1][1]=direction[1]**2.0*(1.0-np.cos(angle))+np.cos(angle)\n    matrix[2][2]=direction[2]**2.0*(1.0-np.cos(angle))+np.cos(angle)\n\n    matrix[0][1]=direction[0]*direction[1]*(1.0-np.cos(angle))-direction[2]*np.sin(angle)\n    matrix[1][0]=direction[0]*direction[1]*(1.0-np.cos(angle))+direction[2]*np.sin(angle)\n\n    matrix[0][2]=direction[0]*direction[2]*(1.0-np.cos(angle))+direction[1]*np.sin(angle)\n    matrix[2][0]=direction[0]*direction[2]*(1.0-np.cos(angle))-direction[1]*np.sin(angle)\n\n    matrix[1][2]=direction[1]*direction[2]*(1.0-np.cos(angle))-direction[0]*np.sin(angle)\n    matrix[2][1]=direction[1]*direction[2]*(1.0-np.cos(angle))+direction[0]*np.sin(angle)\n\n    return(matrix)\n\n\ndef overlap(coords1, coords_ref, idx1, idx2, elements):\n\n    coords1_np=np.array(coords1)\n    coords_ref_np=np.array(coords_ref)\n    #print(\"overlap: coords1: %i, coords2: %i\"%(len(coords1),len(coords_ref)))\n    #print(idx1,idx2)\n\n    # shift\n    coords_shifted=coords1_np-coords1_np[idx2]+coords_ref_np[idx2]\n\n    # rotate P-dummy-axis\n    dir1=coords_shifted[idx1]-coords_shifted[idx2]\n    dir1/=scli.norm(dir1)\n    dir2=coords_ref_np[idx1]-coords_ref_np[idx2]\n    dir2/=scli.norm(dir2)\n    cross_dir1_dir2=np.cross(dir1,dir2)\n    cross_dir1_dir2/=scli.norm(cross_dir1_dir2)\n    angle=np.arccos(np.sum(dir1*dir2))/np.pi*180.0\n    rotation=rotationMatrix(cross_dir1_dir2, angle)\n    # shift to zero\n    coords_shifted-=coords_shifted[idx2]\n    coords_rotated=[]\n    for atom in coords_shifted:\n        coords_rotated.append(np.dot(rotation, atom).tolist())\n    coords_rotated=np.array(coords_rotated)\n    # shift back\n    coords_rotated+=coords_ref_np[idx2]\n\n\n    # rotate third axis\n    axis2=coords_rotated[idx1]-coords_rotated[idx2]\n    axis2/=scli.norm(axis2)\n    RMSD_best=1e10\n    angle2_best=0.0\n    for angle2 in np.linspace(0.0,360.0,361):\n        rotation2=rotationMatrix(axis2, angle2)\n        # shift to zero\n        coords_rotated-=coords_rotated[idx2]\n        coords_rotated2=[]\n        for atom in coords_rotated:\n            coords_rotated2.append(np.dot(rotation2, atom))\n        coords_rotated2=np.array(coords_rotated2)\n        # shift back\n        coords_rotated2+=coords_ref_np[idx2]\n        RMSD=np.mean((coords_rotated2-coords_ref_np)**2.0)**0.5\n        if RMSD<RMSD_best:\n            RMSD_best=RMSD\n            angle2_best=angle2\n            #print(\"found better RMSD: %f\"%(RMSD_best))\n\n    rotation2=rotationMatrix(axis2, angle2_best)\n    # shift to zero\n    coords_rotated-=coords_rotated[idx2]\n    coords_rotated_final=[]\n    for atom in coords_rotated:\n        coords_rotated_final.append(np.dot(rotation2, atom))\n    coords_rotated_final=np.array(coords_rotated_final)\n    # shift back\n    coords_rotated_final+=coords_ref_np[idx2]\n    #exportXYZs([coords_rotated_final,coords_ref_np],[elements+[\"H\"],elements+[\"H\"]],\"test.xyz\")\n    return(coords_rotated_final.tolist())\n\n\n\n\n\ndef reduce_data(data_here):\n\n    data_here[\"boltzmann_averaged_data\"]={}\n    data_here[\"min_data\"]={}\n    data_here[\"max_data\"]={}\n    data_here_esp_points={}\n\n    confnames=[]\n    counter=0\n    for key in data_here.keys():\n        if \"conf_\" in key:\n            confnames.append(\"conf_%i\"%(counter))\n            counter+=1\n\n    weights=[]\n    energies=[]\n    degeneracies=[]\n    for confname in confnames:\n        weights.append(data_here[confname][\"boltzmann_data\"][\"weight\"])\n        degeneracies.append(data_here[confname][\"boltzmann_data\"][\"degen\"])\n        energies.append(data_here[confname][\"boltzmann_data\"][\"energy\"]*kcal_to_eV)\n\n    for confname in confnames:\n        if not \"elements\" in data_here:\n            data_here[\"elements\"]=data_here[confname][\"elements\"]\n\n\n    # own weight calculation for comparison\n    # KEEP THIS CODE\n    #print(weights)\n    #print(np.sum(weights))\n    #Z=np.sum(np.array(degeneracies)*np.exp(-np.array(energies)/kBT))\n    #weights2=1.0/Z*np.array(degeneracies)*np.exp(-np.array(energies)/kBT)\n    #print(weights2)\n\n    # electronic_properties\n    #######################\n    keys_to_delete=[]\n    for key in data_here[\"conf_0\"][\"electronic_properties\"].keys():\n        if key==\"esp_points\":\n            data=[]\n            min_q=-0.2\n            max_q=0.2\n            bins_q=np.linspace(min_q,max_q,50)\n            binwidth=bins_q[1]-bins_q[0]\n            for confname in confnames:\n                try:\n                    xyzq=np.array(data_here[confname][\"electronic_properties\"][key])\n                    histdata=np.histogram(xyzq.T[3],bins=bins_q, density=True)[0]\n                    data.append(histdata)\n                except:\n                    data.append(None)\n                    print(\"ERROR in reduce data: esp_points\")\n                # shift it to the esp points dictionary\n                if confname not in data_here_esp_points:\n                    data_here_esp_points[confname]={}\n                data_here_esp_points[confname][key]=data_here[confname][\"electronic_properties\"][key]\n\n            try:\n                data=np.array(data)\n                data_averaged=np.average(data, weights=weights, axis=0)\n                data_std = np.average((data-data_averaged)**2.0, weights=weights, axis=0)**0.5\n\n                data_here[\"boltzmann_averaged_data\"][\"esp_hist_bins\"]=bins_q.tolist()\n                data_here[\"boltzmann_averaged_data\"][\"esp_hist\"]=data_averaged.tolist()\n                data_here[\"boltzmann_averaged_data\"][\"esp_hist_std\"]=data_std.tolist()\n            except:\n                data_here[\"boltzmann_averaged_data\"][\"esp_hist_bins\"]=None\n                data_here[\"boltzmann_averaged_data\"][\"esp_hist\"]=None\n                data_here[\"boltzmann_averaged_data\"][\"esp_hist_std\"]=None\n                print(\"ERROR in reduce data: esp_points\")\n            keys_to_delete.append(key)\n        elif key==\"esp_profile\":\n            # we calculate this with fixed bins, so we can remove the xtb data\n            keys_to_delete.append(key)\n        elif key==\"dummy_positions\":\n            keys_to_delete.append(key)\n        elif key==\"dip\":\n            # averaging the dipole does not make too much sense because it can rotate completely from conf to conf\n            # thus, we also average the norm of the dipole moment\n            data=[]\n            data_norm=[]\n            for confname in confnames:\n                data.append(data_here[confname][\"electronic_properties\"][key])\n                data_norm.append(np.linalg.norm(data_here[confname][\"electronic_properties\"][key]))\n            data=np.array(data)\n            data_norm=np.array(data_norm)\n            data_averaged=np.average(data,weights=weights,axis=0)\n            data_averaged_norm=np.average(data_norm,weights=weights,axis=0)\n            data_min_norm=np.min(data_norm,axis=0)\n            data_max_norm=np.max(data_norm,axis=0)\n            data_std = np.average((data-data_averaged)**2.0, weights=weights, axis=0)**0.5\n            data_norm_std = np.average((data_norm-data_averaged_norm)**2.0, weights=weights, axis=0)**0.5\n            data_here[\"boltzmann_averaged_data\"][key]=data_averaged.tolist()\n            data_here[\"boltzmann_averaged_data\"][key+\"_std\"]=data_std.tolist()\n            data_here[\"boltzmann_averaged_data\"][\"dip_norm\"]=data_averaged_norm.tolist()\n            data_here[\"boltzmann_averaged_data\"][\"dip_norm_std\"]=data_norm_std.tolist()\n            data_here[\"min_data\"][\"dip_norm\"]=data_min_norm.tolist()\n            data_here[\"max_data\"][\"dip_norm\"]=data_max_norm.tolist()\n        else:\n            #print(key)\n            data=[]\n            weights_here=[]\n            for confidx,confname in enumerate(confnames):\n                x = data_here[confname][\"electronic_properties\"][key]\n                if x is not None:\n                    data.append(x)\n                    #print(len(x))\n                    weights_here.append(weights[confidx])\n            #print(key)\n            #print(data)\n            if len(data)>0:\n                data=np.array(data)\n                weights_here=np.array(weights_here)\n                #print(data)\n                #print(data.shape)\n                #print(weights_here)\n                #print(weights_here.shape)\n                data_averaged=np.average(data, weights=weights_here, axis=0)\n                data_min=np.min(data, axis=0)\n                data_max=np.max(data, axis=0)\n                data_std = np.average((data-data_averaged)**2.0, weights=weights_here, axis=0)**0.5\n                #print(weights_here)\n                #print(data_averaged.tolist(), data_min.tolist(), data_max.tolist())\n                data_here[\"boltzmann_averaged_data\"][key]=data_averaged.tolist()\n                data_here[\"boltzmann_averaged_data\"][key+\"_std\"]=data_std.tolist()\n                data_here[\"min_data\"][key]=data_min.tolist()\n                data_here[\"max_data\"][key]=data_max.tolist()\n            else:\n                data_here[\"boltzmann_averaged_data\"][key]=None\n                data_here[\"boltzmann_averaged_data\"][key+\"_std\"]=None\n                data_here[\"min_data\"][key]=None\n                data_here[\"max_data\"][key]=None\n\n    for key in keys_to_delete:\n        for confname in confnames:\n            del data_here[confname][\"electronic_properties\"][key]\n\n\n\n    # morfeus_parameters\n    #######################\n    keys_to_delete=[]\n    for key in data_here[\"conf_0\"][\"morfeus_parameters\"].keys():\n        if key==\"elements_extended\":\n            elements_extended_list=[]\n            for confname in confnames:\n                elements_extended_list.append(data_here[confname][\"morfeus_parameters\"][key])\n            pass\n            #keys_to_delete.append(key)\n        elif key==\"selected_dummy_idx\":\n            keys_to_delete.append(key)\n        elif key==\"dummy_idx\":\n            pass\n        elif key==\"p_idx\":\n            pass\n        elif key==\"coords_extended\":\n            coords_extended_list=[]\n            for confname in confnames:\n                coords_extended_list.append(data_here[confname][\"morfeus_parameters\"][key])\n            pass\n        else:\n\n            data=[]\n            weights_here=[]\n            for confidx,confname in enumerate(confnames):\n                x = data_here[confname][\"morfeus_parameters\"][key]\n                if x is not None:\n                    data.append(x)\n                    weights_here.append(weights[confidx])\n\n            #print(key)\n            #print(data)\n            if len(data)>0:\n                data=np.array(data)\n                weights_here=np.array(weights_here)\n                data_averaged=np.average(data, weights=weights_here, axis=0)\n                data_min=np.min(data, axis=0)\n                data_max=np.max(data, axis=0)\n                data_std = np.average((data-data_averaged)**2.0, weights=weights_here, axis=0)**0.5\n\n                #print(weights_here)\n                #print(data_averaged.tolist(), data_min.tolist(), data_max.tolist())\n                data_here[\"boltzmann_averaged_data\"][key]=data_averaged.tolist()\n                data_here[\"boltzmann_averaged_data\"][key+\"_std\"]=data_std.tolist()\n                data_here[\"min_data\"][key]=data_min.tolist()\n                data_here[\"max_data\"][key]=data_max.tolist()\n            else:\n                data_here[\"boltzmann_averaged_data\"][key]=None\n                data_here[\"boltzmann_averaged_data\"][key+\"_std\"]=None\n                data_here[\"min_data\"][key]=None\n                data_here[\"max_data\"][key]=None\n\n            #data=[]\n            #for confname in confnames:\n            #    data.append(data_here[confname][\"morfeus_parameters\"][key])\n            #data=np.array(data)\n            #data_averaged=np.average(data, weights=weights, axis=0)\n            #data_min=np.min(data, axis=0)\n            #data_max=np.max(data, axis=0)\n            #data_std = np.average((data-data_averaged)**2.0, weights=weights, axis=0)**0.5\n\n            #data_here[\"boltzmann_averaged_data\"][key]=data_averaged.tolist()\n            #data_here[\"boltzmann_averaged_data\"][key+\"_std\"]=data_std.tolist()\n            #data_here[\"min_data\"][key]=data_min.tolist()\n            #data_here[\"max_data\"][key]=data_max.tolist()\n\n            #keys_to_delete.append(key)\n    for key in keys_to_delete:\n        for confname in confnames:\n            del data_here[confname][\"morfeus_parameters\"][key]\n\n\n    # this code averages over the conformers\n    # to do so, we first need to overlap the conformers as good as possible\n    # for this, we shift and rotate the molecules in a way that their P and dummy atom position are the same\n    # then we rotate around the P-dummy axis to minimize the RMSD\n    coords_extended_list_rotated=[coords_extended_list[0]]\n    for idx,coords_to_turn in enumerate(coords_extended_list[1:]):\n        idx1=data_here[\"conf_0\"][\"morfeus_parameters\"][\"dummy_idx\"]\n        idx2=data_here[\"conf_0\"][\"morfeus_parameters\"][\"p_idx\"]\n        coords_turned = overlap(coords_to_turn, coords_extended_list_rotated[0], idx1, idx2, elements_extended_list[0])\n        confname=\"conf_%i\"%(idx+1)\n        data_here[confname][\"morfeus_parameters\"][\"coords_extended\"]=coords_turned\n        coords_extended_list_rotated.append(coords_turned)\n    coords_extended_list_rotated=np.array(coords_extended_list_rotated)\n    data_averaged=np.average(coords_extended_list_rotated, weights=weights, axis=0)\n    data_std = np.average((coords_extended_list_rotated-data_averaged)**2.0, weights=weights, axis=0)**0.5\n    data_here[\"boltzmann_averaged_data\"][\"coords_extended\"]=data_averaged.tolist()\n    data_here[\"boltzmann_averaged_data\"][\"coords_extended_std\"]=data_std.tolist()\n\n\n\n    # shift and delete some more data\n    for confname in confnames:\n        data_here[confname][\"coords_extended\"]=data_here[confname][\"morfeus_parameters\"][\"coords_extended\"]\n        if \"dummy_idx\" not in data_here:\n            data_here[\"dummy_idx\"]=data_here[confname][\"morfeus_parameters\"][\"dummy_idx\"]\n        if \"p_idx\" not in data_here:\n            data_here[\"p_idx\"]=data_here[confname][\"morfeus_parameters\"][\"p_idx\"]\n        del data_here[confname][\"coords\"]\n        del data_here[confname][\"morfeus_parameters\"][\"coords_extended\"]\n        del data_here[confname][\"morfeus_parameters\"][\"dummy_idx\"]\n        del data_here[confname][\"morfeus_parameters\"][\"p_idx\"]\n        #del data_here[confname][\"morfeus_parameters\"]\n        data_here[confname][\"dip\"]=data_here[confname][\"electronic_properties\"][\"dip\"]\n        del data_here[confname][\"electronic_properties\"][\"dip\"]\n        #del data_here[confname][\"electronic_properties\"]\n        del data_here[confname][\"elements\"]\n\n    data_here[\"number_of_conformers\"]=len(confnames)\n    data_here[\"boltzmann_weights\"]=weights\n\n\n    # move the conformer data to a separate dictionary\n    data_confs={}\n    for confname in confnames:\n        data_confs[confname]=data_here[confname]\n        del data_here[confname]\n\n\n    return(data_here, data_confs, data_here_esp_points)\n\n\n\n\ndef get_weights(energies_here, degeneracies_here, selection=[]):\n    T_kcal = 0.001987191686486*300.0\n    if len(selection)==0:\n        selection = np.array(list(range(len(degeneracies_here))))\n    weights_own = np.array(degeneracies_here)[selection]*np.exp(-np.array(energies_here)[selection]/T_kcal)\n    weights_own /= np.sum(weights_own)\n    return(weights_own)\n\n\n\ndef combine_csvs(molname, resultsdir, data_here, data_here_confs):\n\n\n\n    datagroups=[\"lval\",\"B1\",\"B5\",\"sasa\",\"sasa_P\",\"sasa_volume\",\"cone_angle\",\n                \"global_electrophilicity_index\",\"dip_norm\",\"alpha\",\"EA_delta_SCC\",\n                \"HOMO_LUMO_gap\",\"IP_delta_SCC\",\"nucleophilicity\", \"cone_angle\", \"p_int\", \"p_int_atom\", \"p_int_area\", \"pyr_val\", \"pyr_alpha\", \"qvbur_min\", \"qvbur_max\", \"qvtot_min\", \"qvtot_max\", \"max_delta_qvbur\", \"max_delta_qvtot\", \"ovbur_min\", \"ovbur_max\", \"ovtot_min\", \"ovtot_max\", \"vbur\", \"vtot\", \"near_vbur\", \"far_vbur\", \"near_vtot\", \"far_vtot\"]\n    datagroups_vec=[\"muls\",\"wils\",\"fukui\", \"alphas\"]\n\n    ligand_data={}\n\n\n    # read the boltzmann averages results files to get information about each ligand\n    #outfilename=\"%s/%s.yml\"%(resultsdir, molname)\n    #print(\"   ---   read molecule %s\"%(outfilename))\n    #outfile=open(outfilename, \"r\")\n    #data_here=yaml.load(outfile, Loader=yaml.FullLoader)\n    #outfile.close()\n\n    ligand_data[molname]={}\n    ligand_data[molname][\"number_of_atoms\"] = len(data_here[\"elements\"])\n    ligand_data[molname][\"num_rotatable_bonds\"] = data_here[\"num_rotatable_bonds\"]\n    ligand_data[molname][\"number_of_conformers\"] = data_here[\"number_of_conformers\"]\n    ligand_data[molname][\"smiles\"] = data_here[\"smiles\"]\n    ligand_data[molname][\"boltzmann_weights\"] = data_here[\"boltzmann_weights\"]\n    for key in datagroups:\n        ligand_data[molname][key+\"_boltzmann\"] = data_here[\"boltzmann_averaged_data\"][key]\n        ligand_data[molname][key+\"_max\"] = data_here[\"max_data\"][key]\n        ligand_data[molname][key+\"_min\"] = data_here[\"min_data\"][key]\n    p_idx=data_here[\"p_idx\"]\n    ligand_data[molname][\"p_idx\"] = p_idx\n    for key in datagroups_vec:\n        ligand_data[molname][key] = data_here[\"boltzmann_averaged_data\"][key][p_idx]\n\n\n    # read the conformer results files to get more information about each single conformer\n    #outfilename_confs=\"%s/%s_confs.yml\"%(resultsdir, molname)\n    #outfile=open(outfilename_confs,\"r\")\n    #data_here_confs=yaml.load(outfile, Loader=yaml.FullLoader)\n    #outfile.close()\n\n    n_conformers = ligand_data[molname][\"number_of_conformers\"]\n    energies_here=[]\n    degeneracies_here=[]\n    weights_here=[]\n    for c_idx in range(0,n_conformers):\n        energies_here.append(data_here_confs[\"conf_%i\"%(c_idx)][\"boltzmann_data\"][\"energy\"])\n        degeneracies_here.append(data_here_confs[\"conf_%i\"%(c_idx)][\"boltzmann_data\"][\"degen\"])\n        weights_here.append(data_here_confs[\"conf_%i\"%(c_idx)][\"boltzmann_data\"][\"weight\"])\n    ligand_data[molname][\"degeneracies\"] = degeneracies_here\n    ligand_data[molname][\"energies\"] = energies_here\n\n\n\n\n    weights_own = get_weights(energies_here, degeneracies_here)\n\n    # draw N random conformers (including lowest)\n    N_max=10\n    N = min(N_max, n_conformers)\n    conformers_to_use = np.array([0] + sorted(np.random.choice(list(range(1,n_conformers)), size=N-1, replace=False).tolist()))\n    weights_N = get_weights(energies_here, degeneracies_here, selection=conformers_to_use)\n\n\n\n    coords_all = []\n    elements_all = []\n    for c_idx in range(0,n_conformers):\n        #print(data_here_confs[\"conf_%i\"%(c_idx)].keys())\n        x = data_here_confs[\"conf_%i\"%(c_idx)][\"coords_extended\"]\n        e = data_here_confs[\"conf_%i\"%(c_idx)][\"morfeus_parameters\"][\"elements_extended\"]\n        coords_all.append(x)\n        elements_all.append(e)\n        #exportXYZ(x,e,\"structures/single_files/%s_conformer_%i.xyz\"%(molname, c_idx))\n    coords_all = np.array(coords_all)\n    #exportXYZs(coords_all,elements_all,\"structures/%s_all_conformers.xyz\"%(molname))\n\n    ligand_data[molname][\"confdata\"]={}\n    ligand_data[molname][\"confdata\"][\"coords\"] = coords_all.tolist()\n    ligand_data[molname][\"confdata\"][\"elements\"] = elements_all\n\n\n    electronic_properties = ['EA_delta_SCC', 'HOMO_LUMO_gap', 'IP_delta_SCC', 'alpha', 'alphas', 'global_electrophilicity_index', 'muls', 'nucleophilicity', 'wils']\n    morfeus_parameters = ['B1', 'B5', 'lval', 'sasa', 'sasa_P', 'sasa_volume', \"cone_angle\", \"p_int\", \"p_int_atom\", \"p_int_area\", \"pyr_val\", \"pyr_alpha\", \"qvbur_min\", \"qvbur_max\", \"qvtot_min\", \"qvtot_max\", \"max_delta_qvbur\", \"max_delta_qvtot\", \"ovbur_min\", \"ovbur_max\", \"ovtot_min\", \"ovtot_max\", \"vbur\", \"vtot\", \"near_vbur\", \"far_vbur\", \"near_vtot\", \"far_vtot\"]\n\n    for p in electronic_properties:\n        if p in datagroups:\n            feature_ref = ligand_data[molname][p+\"_boltzmann\"]\n        else:\n            feature_ref = ligand_data[molname][p]\n        if feature_ref is not None:\n            data_here=[]\n            mask_here=[]\n            for c_idx in range(0,n_conformers):\n                if p in datagroups_vec:\n                    x = data_here_confs[\"conf_%i\"%(c_idx)][\"electronic_properties\"][p][p_idx]\n                    if x is None:\n                        #print(\"WARNING: found None in %s of conformer %i\"%(p, c_idx))\n                        #x = 0.0\n                        data_here.append(x)\n                    else:\n                        mask_here.append(c_idx)\n                        data_here.append(float(x))\n                else:\n                    x = data_here_confs[\"conf_%i\"%(c_idx)][\"electronic_properties\"][p]\n                    if x is None:\n                        #print(\"WARNING: found None in %s of conformer %i\"%(p, c_idx))\n                        #x = 0.0\n                        data_here.append(x)\n                    else:\n                        mask_here.append(c_idx)\n                        data_here.append(float(x))\n            mask_here=np.array(mask_here)\n            if len(mask_here)!=len(weights_here):\n                ligand_data[molname][p]=None\n            else:\n                feature_all = np.sum(np.array(data_here)*np.array(weights_here))\n                feature_N = np.sum(np.array(data_here)[conformers_to_use]*weights_N)\n                #print(\"%s:\\naverage over all (%i): %.3f / %.3f\\naverage over %i: %.3f\"%(p, n_conformers, feature_all, feature_ref, N, feature_N))\n            ligand_data[molname][\"confdata\"][p]=data_here\n\n\n    for p in morfeus_parameters:\n        if p in datagroups:\n            feature_ref = ligand_data[molname][p+\"_boltzmann\"]\n        else:\n            feature_ref = ligand_data[molname][p]\n        if feature_ref is not None:\n            #print(\"read %s\"%(p))\n            data_here=[]\n            mask_here=[]\n            for c_idx in range(0,n_conformers):\n                x = data_here_confs[\"conf_%i\"%(c_idx)][\"morfeus_parameters\"][p]\n                if x is None:\n                    #print(\"WARNING: found None in %s of conformer %i\"%(p, c_idx))\n                    #x = 0.0\n                    data_here.append(x)\n                else:\n                    mask_here.append(c_idx)\n                    data_here.append(float(x))\n            mask_here=np.array(mask_here)\n            if len(mask_here)!=len(weights_here):\n                ligand_data[molname][p]=None\n            else:\n                feature_all = np.sum(np.array(data_here)*np.array(weights_here))\n                feature_N = np.sum(np.array(data_here)[conformers_to_use]*weights_N)\n                #print(\"%s:\\naverage over all (%i): %.3f / %.3f\\naverage over %i: %.3f\"%(p, n_conformers, feature_all, feature_ref, N, feature_N))\n            ligand_data[molname][\"confdata\"][p]=data_here\n        #else:\n        #    print(\"WARNING: %s is None\"%(p))\n\n\n    outfilename=\"%s/%s_combined.yml\"%(resultsdir, molname)\n    outfile=open(outfilename,\"w\")\n    outfile.write(yaml.dump(ligand_data[molname], default_flow_style=False))\n    outfile.close()\n\n\n\n\ndef get_rotatable_bonds(smiles):\n    m = Chem.MolFromSmiles(smiles)\n    patt = Chem.MolFromSmarts('[*&!F&!Cl]-&!@[*&!F&!Cl]')\n    single_bonds=m.GetSubstructMatches(patt)\n    rotatable_bonds=[]\n    for x in single_bonds:\n        rotatable_bonds.append([x[0],x[1]])\n    return(rotatable_bonds)\n\ndef get_num_bonds_P(smiles):\n    try:\n        m = Chem.MolFromSmiles(smiles)\n    except:\n        print(\"WARNING: could not create mol from %s. assume P has 3 bonds.\"%(smiles))\n        return(3)\n    try:\n        atoms=m.GetAtoms()\n    except:\n        print(\"WARNING: could not create mol from %s. assume P has 3 bonds.\"%(smiles))\n        return(3)\n    els=[a.GetSymbol() for a in atoms]\n    if \"P\" in els:\n        P_index=els.index(\"P\")\n    #elif \"p\" in smiles:\n    #    P_index=smiles.index(\"p\")\n    else:\n        exit(\"ERROR: no P found in smiles %s\"%(smiles))\n    P_atom=atoms[P_index]\n    bonds=P_atom.GetBonds()\n    num_bonds=0.0\n    for bond in bonds:\n        bondtype=bond.GetBondType()\n        print(\"   ---   found a P bond: %s\"%(str(bondtype)))\n        if str(bondtype)==\"SINGLE\":\n            num_bonds+=1.0\n        elif str(bondtype)==\"DOUBLE\":\n            num_bonds+=2.0\n        elif str(bondtype)==\"TRIPLE\":\n            num_bonds+=3.0\n        elif str(bondtype)==\"AROMATIC\":\n            num_bonds+=1.5\n    if abs(num_bonds-round(num_bonds))>0.1:\n        exit(\"ERROR: problem with bonds! %s\"%(smiles))\n    else:\n        num_bonds=int(num_bonds)\n        return(num_bonds)\n\n\ndef get_P_bond_indeces_of_ligand(coords, elements):\n    bonds = get_bonds(coords, elements)\n    #for bond in bonds:\n    #    els=[elements[bond[0]],elements[bond[1]]]\n    #    if \"P\" in els and \"Pd\" in els:\n    #        if \"P\"==les[0]:\n    #            P_index=bond[0]\n    #        else:\n    #            P_index=bond[1]\n    #        break\n    for P_index, element in enumerate(elements):\n        if element==\"P\":\n            break\n    bond_indeces=[]\n    for bond in bonds:\n        idx1=bond[0]\n        idx2=bond[1]\n        if P_index==idx1:\n            #print(idx1,idx2)\n            bond_indeces.append(idx2)\n        if P_index==idx2:\n            #print(idx1,idx2)\n            bond_indeces.append(idx1)\n    return(P_index, bond_indeces)\n\n\ndef add_Hs_to_P(smiles, num_bonds_P):\n    if \"[P@\" in smiles:\n        return(smiles)\n    if \"P\" in smiles:\n        P_index=smiles.index(\"P\")\n        if P_index>0:\n            if smiles[P_index-1]==\"[\":\n                exit(\"ERROR: P is already in a square braket. cannot add explicit H's %s\"%(smiles))\n        if num_bonds_P==3:\n            add=\"[P]\"\n        elif num_bonds_P==2:\n            add=\"[PH]\"\n        elif num_bonds_P==1:\n            add=\"[PH2]\"\n        elif num_bonds_P==0:\n            add=\"[PH3]\"\n        else:\n            add=\"[P]\"\n            print(\"WARNING: weird number of bonds (%i) for P in %s\"%(num_bonds_P, smiles))\n\n\n    elif \"p\" in smiles:\n        P_index=smiles.index(\"p\")\n        if P_index>0:\n            if smiles[P_index-1]==\"[\":\n                exit(\"ERROR: P is already in a square braket. cannot add explicit H's %s\"%(smiles))\n        if num_bonds_P==3:\n            add=\"p\"\n        elif num_bonds_P==2:\n            add=\"[pH]\"\n        elif num_bonds_P==1:\n            add=\"[pH2]\"\n        elif num_bonds_P==0:\n            add=\"[pH3]\"\n        else:\n            add=\"[p]\"\n            print(\"WARNING: weird number of bonds (%i) for p in %s\"%(num_bonds_P, smiles))\n\n    else:\n        exit(\"ERROR: no P or p found in %s\"%(smiles))\n\n    p1=smiles[:P_index]\n    p2=smiles[P_index+1:]\n\n    smiles_new=p1+add+p2\n    return(smiles_new)\n\ndef add_to_smiles(smiles, add):\n    if \"P\" in smiles:\n        P_index=smiles.index(\"P\")\n        if P_index>0:\n            if smiles[P_index-1]==\"[\":\n                print(\"   ---   found P in square brakets\")\n                if smiles[P_index+1]==\"]\":\n                    P_index=P_index+1\n                elif smiles[P_index+2]==\"]\":\n                    P_index=P_index+2\n                elif smiles[P_index+3]==\"]\":\n                    P_index=P_index+3\n\n    elif \"p\" in smiles:\n        P_index=smiles.index(\"p\")\n        if P_index>0:\n            if smiles[P_index-1]==\"[\":\n                print(\"   ---   found p in square brakets\")\n                if smiles[P_index+1]==\"]\":\n                    P_index=P_index+1\n                elif smiles[P_index+2]==\"]\":\n                    P_index=P_index+2\n                elif smiles[P_index+3]==\"]\":\n                    P_index=P_index+3\n    else:\n        print(\"no P or p found in %s\"%(smiles))\n    p1=smiles[:P_index+1]\n    p2=smiles[P_index+1:]\n    smiles_new=p1+\"(%s)\"%(add)+p2\n    #print(smiles_new)\n    #smiles_new=smiles_new.replace(\"Pd\",\"X\")\n    #smiles_new=smiles_new.replace(\"P\",\"[P]\")\n    #smiles_new=smiles_new.replace(\"X\",\"Pd\")\n    #print(smiles_new)\n    return(smiles_new)\n\n\n\n\ndef which(program):\n    def is_exe(fpath):\n        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)\n\n    fpath, fname = os.path.split(program)\n    if fpath:\n        if is_exe(program):\n            return program\n    else:\n        for path in os.environ[\"PATH\"].split(os.pathsep):\n            exe_file = os.path.join(path, program)\n            if is_exe(exe_file):\n                return exe_file\n\n    return None\n\n\ndef get_coords_from_smiles(smiles, suffix, conversion_method):\n    if conversion_method==\"any\":\n        to_try = [\"rdkit\", \"molconvert\", \"obabel\"]\n    elif conversion_method==\"rdkit\":\n        to_try = [\"rdkit\"]\n    elif conversion_method==\"molconvert\":\n        to_try = [\"molconvert\"]\n    elif conversion_method==\"obabel\":\n        to_try = [\"obabel\"]\n\n    error=\"\"\n    for m in to_try:\n        print(\"   ---   try to convert %s to 3D using %s (of %s)\"%(smiles, m, str(to_try)))\n        if m==\"molconvert\":\n\n            if which(\"molconvert\") != None:\n\n                coords, elements = get_coords_from_smiles_marvin(smiles, suffix)\n                if coords is None or elements is None:\n                    error+=\" molconvert_failed \"\n                    pass\n                else:\n                    if abs(np.max(coords.T[2])-np.min(coords.T[2]))>0.01:\n                        print(\"   ---   conversion done with molconvert\")\n                        return(coords, elements)\n                    else:\n                        error+=\" molconvert_mol_flat \"\n                        pass\n                        #print(\"WARNING: molconvert produced a flat molecule. proceed with other methods (obabel or rdkit)\")\n            else:\n                error+=\" molconvert_not_available \"\n\n        if m==\"obabel\":\n            if which(\"obabel\") != None:\n                #print(\"use obabel\")\n                coords, elements = get_coords_from_smiles_obabel(smiles, suffix)\n                if coords is None or elements is None:\n                    error+=\" obabel_failed \"\n                    pass\n                else:\n                    if abs(np.max(coords.T[2])-np.min(coords.T[2]))>0.01:\n                        print(\"   ---   conversion done with obabel\")\n                        return(coords, elements)\n                    else:\n                        error+=\" obabel_failed \"\n                        pass\n\n            else:\n                error+=\" obabel_not_available \"\n\n        if m==\"rdkit\":\n            #print(\"use rdkit\")\n            coords, elements = get_coords_from_smiles_rdkit(smiles, suffix)\n            if coords is None or elements is None:\n                error+=\" rdkit_failed \"\n                pass\n            else:\n                if abs(np.max(coords.T[2])-np.min(coords.T[2]))>0.01:\n                    print(\"   ---   conversion done with rdkit\")\n                    return(coords, elements)\n                else:\n                    error+=\" rdkit_failed \"\n                    pass\n\n    exit(\"ERROR: NO 3D conversion worked: %s\"%(error))\n\ndef get_coords_from_smiles_obabel(smiles, suffix):\n    name=uuid.uuid4()\n\n    if not os.path.exists(\"input_structures%s\"%(suffix)):\n        try:\n            os.makedirs(\"input_structures%s\"%(suffix))\n        except:\n            pass\n\n    filename=\"input_structures%s/%s.xyz\"%(suffix, name)\n    os.system(\"obabel -:\\\"%s\\\" --gen3D -oxyz > %s\"%(smiles, filename))\n    if not os.path.exists(filename):\n        return(None, None)\n        #print(\"ERROR: could not convert %s to 3D using obabel. Exit!\"%(smiles))\n        #exit()\n\n    coords, elements = readXYZ(filename)\n    if len(coords)==0:\n        return(None, None)\n        #print(\"ERROR: could not convert %s to 3D using obabel. Exit!\"%(smiles))\n        #exit()\n    os.system(\"rm %s\"%(filename))\n    return(coords, elements)\n\n\ndef get_coords_from_smiles_rdkit(smiles, suffix):\n    try:\n        m = Chem.MolFromSmiles(smiles)\n    except:\n        return(None, None)\n        #print(\"could not convert %s to rdkit molecule. Exit!\"%(smiles))\n        #exit()\n    try:\n        m = Chem.AddHs(m)\n    except:\n        return(None, None)\n        #print(\"ERROR: could not add hydrogen to rdkit molecule of %s. Exit!\"%(smiles))\n        #exit()\n    try:\n        AllChem.EmbedMolecule(m)\n    except:\n        return(None, None)\n        #print(\"ERROR: could not calculate 3D coordinates from rdkit molecule %s. Exit!\"%(smiles))\n        #exit()\n    try:\n        block=Chem.MolToMolBlock(m)\n        blocklines=block.split(\"\\n\")\n        coords=[]\n        elements=[]\n        for line in blocklines[4:]:\n            if len(line.split())==4:\n                break\n            elements.append(line.split()[3])\n            coords.append([float(line.split()[0]),float(line.split()[1]),float(line.split()[2])])\n        coords=np.array(coords)\n        mean = np.mean(coords, axis=0)\n        distances = scsp.distance.cdist([mean],coords)[0]\n        if np.max(distances)<0.1:\n            return(None, None)\n            #print(\"ERROR: something is wrong with rdkit molecule %s. Exit!\"%(smiles))\n            #print(\"%i\\n\"%(len(coords)))\n            #for atomidx, atom in enumerate(coords):\n            #    print(\"%s %f %f %f\"%(elements[atomidx], atom[0], atom[1], atom[2]))\n            #exit()\n            \n    except:\n        return(None, None)\n        #print(\"ERROR: could not read xyz coordinates from rdkit molecule %s. Exit!\"%(smiles))\n        #exit()\n    return(coords, elements)\n\n\n\n\ndef get_coords_from_smiles_marvin(smiles, suffix):\n\n    name=uuid.uuid4()\n\n    if not os.path.exists(\"tempfiles%s\"%(suffix)):\n        try:\n            os.makedirs(\"tempfiles%s\"%(suffix))\n        except:\n            pass\n    if not os.path.exists(\"input_structures%s\"%(suffix)):\n        try:\n            os.makedirs(\"input_structures%s\"%(suffix))\n        except:\n            pass\n\n    outfile=open(\"tempfiles%s/%s.smi\"%(suffix, name),\"w\")\n    outfile.write(\"%s\\n\"%(smiles))\n    outfile.close()\n\n    path_here=os.getcwd()\n    os.system(\"molconvert -2 mrv:+H %s/tempfiles%s/%s.smi > tempfiles%s/%s.mrv\"%(path_here,suffix, name, suffix, name))\n    filename=\"tempfiles%s/%s.mrv\"%(suffix, name)\n    if not os.path.exists(filename):\n        os.system(\"rm tempfiles%s/%s.smi\"%(suffix, name))\n        return(None, None)\n        #print(\"ERROR: could not convert %s to 2D (mrv) using marvin. Exit!\"%(smiles))\n        #exit()\n\n    os.system(\"molconvert -3 xyz %s/tempfiles%s/%s.mrv > input_structures%s/%s.xyz\"%(path_here, suffix, name, suffix, name))\n    filename=\"input_structures%s/%s.xyz\"%(suffix, name)\n    if not os.path.exists(filename):\n        os.system(\"rm tempfiles%s/%s.smi tempfiles%s/%s.mrv\"%(suffix, name, suffix, name))\n        return(None, None)\n        #print(\"ERROR: could not convert %s to 3D (xyz) using marvin. Exit!\"%(smiles))\n        #exit()\n\n    coords, elements = readXYZ(filename)\n    if len(coords)==0:\n        os.system(\"rm tempfiles%s/%s.smi tempfiles%s/%s.mrv input_structures%s/%s.xyz\"%(suffix, name, suffix, name, suffix, name))\n        print(\"ERROR: could not convert %s to 3D (coords in empty) using marvin. Exit!\"%(smiles))\n        #return(None, None)\n        #exit()\n    os.system(\"rm tempfiles%s/%s.smi tempfiles%s/%s.mrv input_structures%s/%s.xyz\"%(suffix, name, suffix, name, suffix, name))\n    return(coords, elements)\n\n\n\ndef remove_complex(coords, elements, smiles, settings):\n    P_index = elements.index(\"P\")\n    mask, done = get_ligand_indeces(coords, elements, P_index, smiles, \"Pd\")\n    if not done:\n        return(None, None, done)\n    coords_ligand=[]\n    elements_ligand=[]\n    for atomidx in mask:\n        atom = coords[atomidx]\n        elements_ligand.append(elements[atomidx])\n        coords_ligand.append([atom[0],atom[1],atom[2]])\n    coords_ligand=np.array(coords_ligand)\n    return(coords_ligand, elements_ligand, True)\n\n", "meta": {"hexsha": "5668570f969f4b3b1556e3584d828e6fe5c015f0", "size": 101451, "ext": "py", "lang": "Python", "max_stars_repo_path": "conf_search_and_xTB/utils.py", "max_stars_repo_name": "aspuru-guzik-group/kraken", "max_stars_repo_head_hexsha": "4eaad505c1343e6083032b4a3fda47e004e19734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-01-13T12:39:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:10:52.000Z", "max_issues_repo_path": "conf_search_and_xTB/utils.py", "max_issues_repo_name": "aspuru-guzik-group/kraken", "max_issues_repo_head_hexsha": "4eaad505c1343e6083032b4a3fda47e004e19734", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conf_search_and_xTB/utils.py", "max_forks_repo_name": "aspuru-guzik-group/kraken", "max_forks_repo_head_hexsha": "4eaad505c1343e6083032b4a3fda47e004e19734", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3847900114, "max_line_length": 1014, "alphanum_fraction": 0.5844989207, "include": true, "reason": "import numpy,import scipy", "num_tokens": 25783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.17788593583742898}}
{"text": "from __future__ import print_function\nimport numpy as np\nimport math\nimport itertools\nimport atomic_data\nfrom force_field_construction import force_field\n\nmetals = atomic_data.metals\nmass_key = atomic_data.mass_key\n\nclass UFF(force_field):\n\n    def __init__(self, system, cutoff, args):\n\n        self.system = system\n        self.cutoff = cutoff\n        self.args = args\n\n    def type_atoms(self):\n\n        SG = self.system['graph']\n        types = []\n\n        for atom in SG.nodes(data=True):\n            \n            name, inf = atom\n            element_symbol = inf['element_symbol']\n            nbors = list(SG.neighbors(name))\n            nbor_symbols = [SG.nodes[n]['element_symbol'] for n in nbors]\n            bond_types = [SG.get_edge_data(name, n)['bond_type'] for n in nbors]\n            mass = mass_key[element_symbol]\n\n            # Atom typing for UFF, this can be made much more robust with pattern matching,\n            # but this works for most ToBaCCo MOFs, use at your own risk.\n            ty = None\n            if 'A' in bond_types and element_symbol != 'O':\n                ty = element_symbol + '_' + 'R'\n                hyb = 'resonant'\n            else:\n                # Group 1\n                if element_symbol == 'H':\n                    ty = element_symbol + '_'\n                    hyb = 'sp1'\n                # Group 6\n                elif element_symbol in ('C', 'Si'):\n                    if len(element_symbol) == 1:\n                        ty = element_symbol + '_' + str(len(nbors) - 1)\n                    else:\n                        ty = element_symbol + str(len(nbors) - 1)\n                    hyb = 'sp' + str(len(nbors) - 1)\n                # Group 7\n                elif element_symbol in ('N'):\n                    ty = element_symbol + '_' + str(len(nbors))\n                    hyb = 'sp' + str(len(nbors))\n                # Group 8\n                elif element_symbol in ('O', 'S'):\n                    # oxygen case is complex with the UFF4MOF oxygen types\n                    if element_symbol == 'O':\n                        # =O for example\n                        if len(nbors) == 1:\n                            ty = 'O_1'\n                            hyb = 'sp1'\n                        # -OH, for example\n                        elif len(nbors) == 2 and 'A' not in bond_types and 'D' not in bond_types and not any(i in metals for i in nbor_symbols):\n                            ty = 'O_3'\n                            hyb = 'sp3'\n                        # furan oxygen, for example\n                        elif len(nbors) == 2 and 'A' in bond_types and not any(i in metals for i in nbor_symbols):\n                            ty = 'O_R'\n                            hyb = 'sp2'\n                        # carboxyllic oxygen\n                        elif len(nbors) == 2 and 'D' in bond_types and not any(i in metals for i in nbor_symbols):\n                            ty = 'O_2'\n                            hyb = 'sp2'\n                        # carboxylate oxygen bound to metal node\n                        elif len(nbors) == 2 and any(i in metals for i in nbor_symbols):\n                            ty = 'O_2_M'\n                            hyb = 'sp2'\n                        # central 3-connected oxygen \n                        elif len(nbors) == 3 and all(i in metals for i in nbor_symbols) and 'Zr' not in nbor_symbols:\n                            ty = 'O_2_M'\n                            hyb = 'sp2'\n                        elif len(nbors) == 3 and all(i in metals for i in nbor_symbols) and 'Zr' in nbor_symbols:\n                            ty = 'O_3_M'\n                            hyb = 'sp2'\n                        # node oxygens bound to metals \n                        elif len(nbors) >= 3 and any(i in metals for i in nbor_symbols):\n                            ty = 'O_3_M'\n                            hyb = 'sp2'\n                        else:\n                            raise ValueError('Oxygen with neighbors ' + ' '.join(nbor_symbols) + ' is not parametrized')\n                    # sulfur case is simple\n                    elif element_symbol == 'S':\n                        ty = 'S_' + str(len(nbors) + 1)\n                        hyb = 'sp' + str(len(nbors) + 1)\n                # Group 9\n                elif element_symbol in ('F', 'Br'):\n                    if len(element_symbol) == 1:\n                        ty = element_symbol + '_'\n                    else:\n                        ty = element_symbol\n                    hyb = 'sp1'\n                # Metals\n                elif element_symbol in metals:\n                    # Cu paddlewheel, just changed equilibrium angle of Cu3+1 to 90.0 \n                    if len(nbors) == 5 and element_symbol == 'Cu' and any(i in metals for i in nbor_symbols):\n                        ty = element_symbol + '4+1'\n                        hyb = 'NA'\n                    # M3O(CO2H)6 metals, e.g. MIL-100\n                    elif len(nbors) in (5,6) and element_symbol in ('Al', 'Sc', 'V', 'Mn', 'Fe', 'Cr') and not any(i in metals for i in nbor_symbols):\n                        ty = element_symbol + '6+3'\n                        if element_symbol == 'V':\n                            ty = 'V_6+3'\n                        hyb = 'NA'\n                    # IRMOF-1 node\n                    elif len(nbors) == 4 and element_symbol == 'Zn':\n                        ty = 'Zn3+2'\n                        hyb = 'NA'\n                    # Zr node\n                    elif len(nbors) in (7,8) and element_symbol == 'Zr':\n                        ty = 'Zr3+4'\n                        hyb = 'NA'\n                # if no type can be identified\n                else:\n                    raise ValueError('No UFF type identified for ' + element_symbol + 'with neighbors ' + ' '.join(nbor_symbols))\n                    \n            types.append((ty, element_symbol, mass))\n            SG.nodes[name]['force_field_type'] = ty\n            SG.nodes[name]['hybridization'] = hyb\n\n        types = set(types)\n        Ntypes = len(types)\n        atom_types = dict((ty[0],i+1) for i,ty in zip(range(Ntypes), types))\n        atom_element_symbols = dict((ty[0], ty[1]) for ty in types)\n        atom_masses = dict((ty[0],ty[2]) for ty in types)\n\n        self.system['graph'] = SG\n        self.atom_types = atom_types\n        self.atom_element_symbols = atom_element_symbols\n        self.atom_masses = atom_masses\n\n    def bond_parameters(self, bond, bond_order):\n        \n        SG = self.system['graph']\n        UFF_atom_parameters = self.args['FF_parameters']\n\n        i,j = bond\n        params_i = UFF_atom_parameters[i]\n        params_j = UFF_atom_parameters[j]\n\n        r0_i, theta0_i, x1_i, D1_i, zeta_i, Z1_i, V_i, X_i = params_i\n        r0_j, theta0_j, x1_j, D1_j, zeta_j, Z1_j, V_j, X_j = params_j\n\n        # bond-order correction\n        rbo = -0.1332 * (r0_i+r0_j) * np.log(bond_order)\n        # electronegativity correction\n        ren = r0_i*r0_j * (((np.sqrt(X_i) - np.sqrt(X_j))**2)) / (X_i*r0_i + X_j*r0_j)\n        # equilibrium distance\n        r_ij = r0_i + r0_j + rbo - ren\n        r_ij3 = r_ij * r_ij * r_ij\n        # force constant (1/2 factor should be included here for LAMMPS)\n        k_ij = 0.5 * 664.12 * ((Z1_i*Z1_j)/r_ij3)\n\n        return ('harmonic', k_ij, r_ij)\n\n    def angle_parameters(self, angle, r_ij, r_jk):\n        \n        UFF_atom_parameters = self.args['FF_parameters']\n\n        i,j,k = angle\n        angle_style = 'cosine/periodic'\n\n        params_i = UFF_atom_parameters[i]\n        params_j = UFF_atom_parameters[j]\n        params_k = UFF_atom_parameters[k]\n\n        r0_i, theta0_i, x1_i, D1_i, zeta_i, Z1_i, V_i, X_i = params_i\n        r0_j, theta0_j, x1_j, D1_j, zeta_j, Z1_j, V_j, X_j = params_j\n        r0_k, theta0_k, x1_k, D1_k, zeta_k, Z1_k, V_k, X_k = params_k\n\n        # linear\n        if theta0_j == 180.0:\n            n = 1\n            b = 1\n        # trigonal planar\n        elif theta0_j == 120.0:\n            n = 3\n            b = -1\n        # square planar or octahedral\n        elif theta0_j == 90.0:\n            n = 4\n            b = 1\n        # general non-linear\n        else:\n            b = 'NA'\n            n = 'NA'\n\n        cosT0 = np.cos(math.radians(theta0_j))\n        sinT0 = np.sin(math.radians(theta0_j))\n\n        r_ik = np.sqrt(r_ij**2.0 + r_jk**2.0 - 2.0*r_ij*r_jk*cosT0)\n        # force constant\n        K = ((664.12*Z1_i*Z1_k)/(r_ik**5.0)) * (3.0*r_ij*r_jk*(1.0-cosT0**2.0)-r_ik**2.0*cosT0)\n\n        # general non-linear\n        if theta0_j not in (90.0, 120.0, 180.0):\n\n            angle_style = 'fourier'\n            C2 = 1.0/(4*sinT0**2) \n            C1 = -4*C2*cosT0\n            C0 = C2*(2*cosT0**2+1)\n            \n            return (angle_style, K, C0, C1, C2)\n\n        # this is needed to correct the LAMMPS angle energy calculation\n        K *= 0.5\n\n        return (angle_style, K, b, n)\n\n    def dihedral_parameters(self, bond, hybridization, element_symbols, nodes):\n\n        fft_j, fft_k, bond_order = bond\n        hyb_j, hyb_k = hybridization\n        els_j, els_k = element_symbols\n        node_j, node_k = nodes \n\n        SG = self.system['graph']\n        UFF_atom_parameters = self.args['FF_parameters']\n\n        con_j = SG.degree(node_j) - 1\n        con_k = SG.degree(node_k) - 1\n\n        mult = con_j * con_k\n        if mult == 0.0:\n            return 'NA'\n\n        # cases taken from the DREIDING paper (same cases, different force constants for UFF)\n        # they are not done in order to save some lines, I don't know of a better way for doing\n        # this besides a bunch of conditionals.\n        if hyb_j == 'sp3' and hyb_k == 'sp3':\n            # case (a)\n            phi0 = 60.0\n            n = 3.0\n            V_j = UFF_atom_parameters[fft_j][6]\n            V_k = UFF_atom_parameters[fft_k][6]\n            V = np.sqrt(V_j*V_k)\n            # case (h)\n            if els_j == 'O' and els_k == 'O':\n                phi0 = 90.0\n                n = 2.0\n                V = 2.0\n            elif els_j == 'S' and els_k == 'S':\n                phi0 = 90.0\n                n = 2.0\n                V = 6.8\n\n        elif (hyb_j in ('sp2', 'resonant') and hyb_k == 'sp3') or (hyb_k in ('sp2', 'resonant') and hyb_j == 'sp3'):\n            # case (b)\n            phi0 = 180.0\n            n = 6.0\n            V = 2.0\n            # case (i) \n            if hyb_j == 'sp3' and els_j in ('O', 'S'):\n                phi0 = 180.0\n                n = 2.0\n                U_j = UFF_atom_parameters[fft_j][6]\n                U_k = UFF_atom_parameters[fft_k][6]\n                V = 5 * np.sqrt(U_j*U_k) * (1.0 + 4.18 * np.log(bond_order))\n            elif hyb_k == 'sp3' and els_k in ('O', 'S'):\n                phi0 = 180.0\n                n = 2.0\n                U_j = UFF_atom_parameters[fft_j][6]\n                U_k = UFF_atom_parameters[fft_k][6]\n                V = 5 * np.sqrt(U_j*U_k) * (1.0 + 4.18 * np.log(bond_order))\n            # case (j) not needed for the current ToBaCCo MOFs\n\n        # case (c, d, e, f)\n        elif hyb_j in ('sp2', 'resonant') and hyb_k in ('sp2', 'resonant'):\n            phi0 = 180.0\n            n = 2.0\n            U_j = UFF_atom_parameters[fft_j][6]\n            U_k = UFF_atom_parameters[fft_k][6]\n            V = 5 * np.sqrt(U_j*U_k) * (1.0 + 4.18 * np.log(bond_order))\n\n        # case (g)\n        elif hyb_j == 'sp1' or hyb_k == 'sp1':\n            return 'NA'\n\n        elif hyb_j == 'NA' or hyb_k == 'NA':\n            return 'NA'\n        \n        # divide by multiplicity and halve to match UFF paper\n        V /= mult\n        V *= 0.5\n        d = -1.0 * np.cos(math.radians(n*phi0))\n\n        return ('harmonic', V, int(d), int(n))\n\n    def improper_parameters(self, fft_i, O_2_flag):\n        \n        if fft_i in ('N_R', 'C_R', 'C_2'):\n\n            # constants for C_R and N_R\n            C0 = 1.0\n            C1 = -1.0\n            C2 = 0.0\n            K = 6.0/3.0\n            al = 1\n\n            # constants for bound O_2\n            if O_2_flag:\n                K = 50.0/3.0\n\n        else:\n            return None\n\n        return ('fourier', K, C0, C1, C2, al)\n\n    def pair_parameters(self, charges=False):\n        \n        UFF_atom_parameters = self.args['FF_parameters']\n        atom_types = self.atom_types\n        params = {}\n        comments = {}\n\n        # determine style and special bonds\n        if charges:\n            style = 'lj/cut/coul/long'\n            cutoff = 12.5\n            sb = 'lj/coul 0.0 0.0 1.0'\n        else:\n            style = 'lj/cut'\n            cutoff = 12.5\n            sb = 'lj 0.0 0.0 1.0'\n\n        for a in atom_types:\n            ID = atom_types[a]\n            data = UFF_atom_parameters[a]\n            x_i = data[2] * (2**(-1.0/6.0))\n            D_i = data[3]\n            params[ID] = (style, D_i, x_i)\n            comments[ID] = [a,a]\n\n        self.pair_data = {'params':params, 'style':style, 'special_bonds':sb, 'comments':comments}\n\n    def enumerate_bonds(self):\n\n        SG = self.system['graph']\n        bond_order_dict = self.args['bond_orders']\n\n        bonds = {}\n        for e in SG.edges(data=True):\n\n            i,j,data = e\n            fft_i = SG.nodes[i]['force_field_type']\n            fft_j = SG.nodes[j]['force_field_type']\n            bond_type = data['bond_type']\n\n            # look for the bond order, otherwise use the convention based on the bond type\n            try:\n                bond_order = bond_order_dict[(fft_i,fft_j)]\n            except KeyError:\n                try:\n                    bond_order = bond_order_dict[(fft_j,fft_i)]\n                except KeyError:\n                    bond_order = bond_order_dict[bond_type]\n\n            bond = tuple(sorted([fft_i, fft_j]) + [bond_order])\n\n            # add to list if bond type already exists, else add a new type\n            try:\n                bonds[bond].append((i,j))\n            except KeyError:\n                bonds[bond] = [(i,j)]\n\n            data['bond_order'] = bond_order\n\n        bond_params = {}\n        bond_comments = {}\n        all_bonds = {}\n        ID = 0\n        count = 0\n        # index bonds by ID\n        for b in bonds:\n\n            ID += 1\n            bond_order = float(b[2])\n            bond = (b[0], b[1])\n            params = self.bond_parameters(bond, bond_order)\n            bond_params[ID] = list(params)\n            bond_comments[ID] = list(bond) + ['bond order=' + str(bond_order)]\n            all_bonds[ID] = bonds[b]\n            count += len(bonds[b])\n\n        self.bond_data = {'all_bonds':all_bonds, 'params':bond_params, 'style':'harmonic', 'count':(count, len(all_bonds)), 'comments':bond_comments}\n\n    def enumerate_angles(self):\n        \n        SG = self.system['graph']\n        bonds = self.bond_data['all_bonds']\n        bond_params = self.bond_data['params']\n        inv_bonds = dict((b,bt) for bt in bonds for b in bonds[bt])\n        angles = {}\n\n        for n in SG.nodes(data=True):\n\n            name, data = n\n            nbors = list(SG.neighbors(name))\n\n            for comb in itertools.combinations(nbors, 2):\n\n                j = name\n                i, k = comb\n\n                fft_i = SG.nodes[i]['force_field_type']\n                fft_j = SG.nodes[j]['force_field_type']\n                fft_k = SG.nodes[k]['force_field_type']\n\n                octa_metals = ('Al6+3', 'Sc6+3', 'Ti4+2', 'V_4+2', 'V_6+3', 'Cr4+2', \n                               'Cr6f3', 'Mn6+3', 'Mn4+2', 'Fe6+3', 'Fe4+2', 'Co4+2', \n                               'Cu4+2', 'Zn4+2')\n\n                if fft_j in octa_metals:\n                    i_coord = SG.nodes[i]['cartesian_position']\n                    j_coord = SG.nodes[j]['cartesian_position']\n                    k_coord = SG.nodes[k]['cartesian_position']\n                    ij = i_coord - j_coord\n                    jk = j_coord - k_coord\n                    cosine_angle = np.dot(ij,jk) / (np.linalg.norm(ij) * np.linalg.norm(jk))\n                    angle = (180.0/np.pi) * np.arccos(cosine_angle)\n\n                sort_ik = sorted([(fft_i,i),(fft_k,k)], key=lambda x:x[0])\n                fft_i, i = sort_ik[0]\n                fft_k, k = sort_ik[1]\n\n                # look up bond constants (don't need to calculate again, yay!)\n                try:\n                    bond_type_ij = inv_bonds[(i,j)]\n                except KeyError:\n                    bond_type_ij = inv_bonds[(j,i)]\n                try:\n                    bond_type_jk = inv_bonds[(j,k)]\n                except KeyError:\n                    bond_type_jk = inv_bonds[(k,j)]\n\n                r_ij = bond_params[bond_type_ij][2]\n                r_jk = bond_params[bond_type_jk][2]\n\n                angle = sorted((fft_i, fft_k))\n                angle = (angle[0], fft_j, angle[1], r_ij, r_jk)\n\n                # add to list if angle type already exists, else add a new type\n                try:\n                    angles[angle].append((i,j,k))\n                except KeyError:\n                    angles[angle] = [(i,j,k)]\n\n        angle_params = {}\n        angle_comments = {}\n        all_angles = {}\n        ID = 0\n        count = 0\n        styles = []\n\n        # index angles by ID\n        for a in angles:\n\n            ID += 1\n            fft_i, fft_j, fft_k, r_ij, r_jk = a\n            angle = (fft_i, fft_j, fft_k)\n            params = self.angle_parameters(angle, r_ij, r_jk)\n            styles.append(params[0])\n            angle_params[ID] = list(params)\n            angle_comments[ID] = list(angle)\n            all_angles[ID] = angles[a]\n            count += len(angles[a])\n        \n        styles = set(styles)\n        if len(styles) == 1:\n            style = list(styles)[0]\n        else:\n            style = 'hybrid ' + ' '.join(styles)\n\n        self.angle_data = {'all_angles':all_angles, 'params':angle_params, 'style':style, 'count':(count, len(all_angles)), 'comments':angle_comments}\n\n    def enumerate_dihedrals(self):\n        \n        SG = self.system['graph']\n        dihedrals = {}\n        dihedral_params = {}\n\n        for e in SG.edges(data=True):\n\n            j,k = e[0:2]\n            fft_j = SG.nodes[j]['force_field_type']\n            fft_k = SG.nodes[k]['force_field_type']\n            hyb_j = SG.nodes[j]['hybridization']\n            hyb_k = SG.nodes[k]['hybridization']\n            els_j = SG.nodes[j]['element_symbol']\n            els_k = SG.nodes[k]['element_symbol']\n            bond_order = e[2]['bond_order']\n            nodes = (j,k)\n\n            nbors_j = [n for n in SG.neighbors(j) if n != k]\n            nbors_k = [n for n in SG.neighbors(k) if n != j]\n\n            il_pairs = list(itertools.product(nbors_j, nbors_k))\n            dihedral_list = [(p[0],j,k,p[1]) for p in il_pairs]\n\n            bond = sorted([fft_j, fft_k])\n            bond = (bond[0], bond[1], bond_order)\n            hybridization = (hyb_j, hyb_k)\n            element_symbols = (els_j, els_k)\n\n            # here I calculate  parameters for each dihedral (I know) but I prefer identifying\n            # those dihedrals before passing to the final dihedral data construction.\n            params = self.dihedral_parameters(bond, hybridization, element_symbols, nodes)\n            \n            if params != 'NA':\n                try:\n                    dihedrals[bond].extend(dihedral_list)\n                except KeyError:\n                    dihedrals[bond] = dihedral_list\n                    dihedral_params[bond] = params\n\n        all_dihedrals = {}\n        dihedral_comments = {}\n        indexed_dihedral_params = {}\n        ID = 0\n        count = 0\n        for d in dihedrals:\n\n            ID += 1\n            dihedral = ('X', d[0], d[1], 'X')\n            params = dihedral_params[d]\n            all_dihedrals[ID] = dihedrals[d]\n            indexed_dihedral_params[ID] = list(dihedral_params[d])\n            dihedral_comments[ID] = list(dihedral) + ['bond order=' + str(d[2])]\n            count += len(dihedrals[d])\n\n        self.dihedral_data = {'all_dihedrals':all_dihedrals, 'params':indexed_dihedral_params, 'style':'harmonic', 'count':(count, len(all_dihedrals)), 'comments':dihedral_comments}\n\n    def enumerate_impropers(self):\n        \n        SG = self.system['graph']\n        impropers = {}\n\n        for n in SG.nodes(data=True):\n            \n            i, data = n\n            nbors = list(SG.neighbors(i))\n\n            if len(nbors) == 3:\n                \n                fft_i = data['force_field_type']\n                fft_nbors = tuple(sorted([SG.nodes[m]['force_field_type'] for m in nbors]))\n                O_2_flag = False\n                # force constant is much larger if j,k, or l is O_2\n                if 'O_2' in fft_nbors or 'O_2_M' in fft_nbors:\n                    O_2_flag = True\n                j,k,l = nbors\n\n                # only need to consider one combination\n                imps = [[i, j, k, l]]\n\n                try:\n                    impropers[(fft_i, O_2_flag)].extend(imps)\n                except KeyError:\n                    impropers[(fft_i, O_2_flag)] = imps\n\n        all_impropers = {}\n        improper_params = {}\n        improper_comments = {}\n        ID = 0\n        count = 0\n        for i in impropers:\n        \n            fft_i, O_2_flag = i \n\n            params = self.improper_parameters(fft_i, O_2_flag)\n\n            if params != None:\n                ID += 1\n                improper_params[ID] = list(params)\n                improper_comments[ID] = [i[0], 'X', 'X', 'X', 'O_2 present=' + str(O_2_flag)]\n                all_impropers[ID] = impropers[i]\n                count += len(impropers[i])\n                \n        self.improper_data = {'all_impropers':all_impropers, 'params':improper_params, 'style':'fourier', 'count':(count, len(all_impropers)), 'comments':improper_comments}\n        \n    def compile_force_field(self, charges=False):\n\n        self.type_atoms()\n        self.pair_parameters(charges)\n        self.enumerate_bonds()\n        self.enumerate_angles()\n        self.enumerate_dihedrals()\n        self.enumerate_impropers()\n\n", "meta": {"hexsha": "9c242feb0abb37683d188707587be7eb9d3cdfdc", "size": 21926, "ext": "py", "lang": "Python", "max_stars_repo_path": "UFF_construction.py", "max_stars_repo_name": "rytheranderson/cif2lammps", "max_stars_repo_head_hexsha": "e4968dfab05d04889e0e193b644ba4e92a251252", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-11-02T11:16:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T19:08:02.000Z", "max_issues_repo_path": "UFF_construction.py", "max_issues_repo_name": "rytheranderson/cif2lammps", "max_issues_repo_head_hexsha": "e4968dfab05d04889e0e193b644ba4e92a251252", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-27T16:37:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-27T19:43:27.000Z", "max_forks_repo_path": "UFF_construction.py", "max_forks_repo_name": "rytheranderson/cif2lammps", "max_forks_repo_head_hexsha": "e4968dfab05d04889e0e193b644ba4e92a251252", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-23T20:26:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-15T16:16:06.000Z", "avg_line_length": 36.5433333333, "max_line_length": 181, "alphanum_fraction": 0.48216729, "include": true, "reason": "import numpy", "num_tokens": 5807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3208212943308302, "lm_q1q2_score": 0.1778859322368215}}
{"text": "\"\"\" Defines the ImplicitOpModel class and supporting functionality.\"\"\"\n#***************************************************************************************************\n# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).\n# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights\n# in this software.\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n# in compliance with the License.  You may obtain a copy of the License at\n# http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory.\n#***************************************************************************************************\n\nimport numpy as _np\nimport scipy as _scipy\nimport itertools as _itertools\nimport collections as _collections\nimport warnings as _warnings\nimport time as _time\nimport uuid as _uuid\nimport bisect as _bisect\nimport copy as _copy\n\nfrom ..tools import matrixtools as _mt\nfrom ..tools import optools as _gt\nfrom ..tools import slicetools as _slct\nfrom ..tools import likelihoodfns as _lf\nfrom ..tools import jamiolkowski as _jt\nfrom ..tools import basistools as _bt\nfrom ..tools import listtools as _lt\nfrom ..tools import symplectic as _symp\n\nfrom . import model as _mdl\nfrom . import modelmember as _gm\nfrom . import circuit as _cir\nfrom . import operation as _op\nfrom . import spamvec as _sv\nfrom . import povm as _povm\nfrom . import instrument as _instrument\nfrom . import labeldicts as _ld\nfrom . import gaugegroup as _gg\nfrom . import matrixforwardsim as _matrixfwdsim\nfrom . import mapforwardsim as _mapfwdsim\nfrom . import termforwardsim as _termfwdsim\nfrom . import explicitcalc as _explicitcalc\nfrom . import simplifierhelper as _sh\nfrom . import layerlizard as _ll\n\nfrom .verbosityprinter import VerbosityPrinter as _VerbosityPrinter\nfrom .basis import Basis as _Basis\nfrom .label import Label as _Label\n\n\nclass ImplicitOpModel(_mdl.OpModel):\n    \"\"\"\n    An ImplicitOpModel represents a flexible QIP model whereby only the\n    building blocks for layer operations are stored, and custom layer-lizard\n    logic is used to construct layer operations from these blocks on an\n    on-demand basis.\n    \"\"\"\n\n    def __init__(self,\n                 state_space_labels,\n                 basis=\"pp\",\n                 primitive_labels=None,\n                 layer_lizard_class=_ll.ImplicitLayerLizard,\n                 layer_lizard_args=(),\n                 simplifier_helper_class=None,\n                 sim_type=\"auto\",\n                 evotype=\"densitymx\"):\n        \"\"\"\n        Creates a new ImplicitOpModel.  Usually only called from derived\n        classes `__init__` functions.\n\n        Parameters\n        ----------\n        state_space_labels : StateSpaceLabels or list or tuple\n            The decomposition (with labels) of (pure) state-space this model\n            acts upon.  Regardless of whether the model contains operators or\n            superoperators, this argument describes the Hilbert space dimension\n            and imposed structure.  If a list or tuple is given, it must be\n            of a from that can be passed to `StateSpaceLabels.__init__`.\n\n        basis : Basis\n            The basis used for the state space by dense operator representations.\n\n        primitive_labels : dict, optional\n            A dictionary of lists with keys `\"preps\"`, `\"povms\"`, `\"ops\"` and\n            `\"instruments`\" giving the primitive-layer labels for each member\n            type.  This information is needed for interfacing with the LGST\n            algorithm and for circuit compiling.\n\n        layer_lizard_class : class, optional\n            The class of the layer lizard to use, which should usually be derived\n            from :class:`ImplicitLayerLizard` and will be created using:\n            `layer_lizard_class(simplified_prep_blks, simplified_op_blks, simplified_effect_blks, self)`\n\n        layer_lizard_args : tuple, optional\n            Additional arguments reserved for the custom layer lizard class.\n            These arguments are not passed to the `layer_lizard_class`'s\n            constructor, but are stored in the model's `._lizardArgs` member and\n            may be accessed from within the layer lizard object (which gets a\n            reference to the model upon initialization).\n\n        simplifier_helper_class : class, optional\n            The :class:`SimplifierHelper`-derived type used to provide the\n            mimial interface needed for circuit compiling.  Initalized\n            using `simplifier_helper_class(self)`.\n\n        sim_type : {\"auto\", \"matrix\", \"map\", \"termorder:X\"}\n            The type of forward simulator this model should use.  `\"auto\"`\n            tries to determine the best type automatically.\n\n        evotype : {\"densitymx\", \"statevec\", \"stabilizer\", \"svterm\", \"cterm\"}\n            The evolution type of this model, describing how states are\n            represented, allowing compatibility checks with (super)operator\n            objects.\n        \"\"\"\n\n        self.prep_blks = _collections.OrderedDict()\n        self.povm_blks = _collections.OrderedDict()\n        self.operation_blks = _collections.OrderedDict()\n        self.instrument_blks = _collections.OrderedDict()\n        self.factories = _collections.OrderedDict()\n\n        if primitive_labels is None: primitive_labels = {}\n        self._primitive_prep_labels = primitive_labels.get('preps', ())\n        self._primitive_povm_labels = primitive_labels.get('povms', ())\n        self._primitive_op_labels = primitive_labels.get('ops', ())\n        self._primitive_instrument_labels = primitive_labels.get('instruments', ())\n\n        self._lizardClass = layer_lizard_class\n        self._lizardArgs = layer_lizard_args\n\n        if simplifier_helper_class is None:\n            simplifier_helper_class = _sh.ImplicitModelSimplifierHelper\n            # by default, assume *_blk members have keys which match the simple\n            # labels found in the circuits this model can simulate.\n        self.simplifier_helper_class = simplifier_helper_class\n        super(ImplicitOpModel, self).__init__(state_space_labels, basis, evotype,\n                                              None, sim_type)\n        self._shlp = simplifier_helper_class(self)\n\n    def get_primitive_prep_labels(self):\n        \"\"\" Return the primitive state preparation labels of this model\"\"\"\n        return self._primitive_prep_labels\n\n    def set_primitive_prep_labels(self, lbls):\n        \"\"\" Set the primitive state preparation labels of this model\"\"\"\n        self._primitive_prep_labels = tuple(lbls)\n\n    def get_primitive_povm_labels(self):\n        \"\"\" Return the primitive POVM labels of this model\"\"\"\n        return self._primitive_povm_labels\n\n    def set_primitive_povm_labels(self, lbls):\n        \"\"\" Set the primitive POVM labels of this model\"\"\"\n        self._primitive_povm_labels = tuple(lbls)\n\n    def get_primitive_op_labels(self):\n        \"\"\" Return the primitive operation labels of this model\"\"\"\n        return self._primitive_op_labels\n\n    def set_primitive_op_labels(self, lbls):\n        \"\"\" Set the primitive operation labels of this model\"\"\"\n        self._primitive_op_labels = tuple(lbls)\n\n    def get_primitive_instrument_labels(self):\n        \"\"\" Return the primitive instrument labels of this model\"\"\"\n        return self._primitive_instrument_labels\n\n    def set_primitive_instrument_labels(self, lbls):\n        \"\"\" Set the primitive instrument labels of this model\"\"\"\n        self._primitive_instrument_labels = tuple(lbls)\n\n    #Functions required for base class functionality\n\n    def _iter_parameterized_objs(self):\n        for dictlbl, objdict in _itertools.chain(self.prep_blks.items(),\n                                                 self.povm_blks.items(),\n                                                 self.operation_blks.items(),\n                                                 self.instrument_blks.items(),\n                                                 self.factories.items()):\n            for lbl, obj in objdict.items():\n                yield (_Label(dictlbl + \":\" + lbl.name, lbl.sslbls), obj)\n\n    def _layer_lizard(self):\n        \"\"\" (simplified op server) \"\"\"\n        self._clean_paramvec()  # just to be safe\n        return self._lizardClass(self.prep_blks, self.operation_blks, self.povm_blks, self.instrument_blks, self)\n        # maybe add a self.factories arg? (but factories aren't really \"simplified\"...\n        # use self._lizardArgs internally?\n\n    def _init_copy(self, copyInto):\n        \"\"\"\n        Copies any \"tricky\" member of this model into `copyInto`, before\n        deep copying everything else within a .copy() operation.\n        \"\"\"\n        # Copy special base class members first\n        super(ImplicitOpModel, self)._init_copy(copyInto)\n\n        # Copy our \"tricky\" members\n        copyInto.prep_blks = _collections.OrderedDict([(lbl, prepdict.copy(copyInto))\n                                                       for lbl, prepdict in self.prep_blks.items()])\n        copyInto.povm_blks = _collections.OrderedDict([(lbl, povmdict.copy(copyInto))\n                                                       for lbl, povmdict in self.povm_blks.items()])\n        copyInto.operation_blks = _collections.OrderedDict([(lbl, opdict.copy(copyInto))\n                                                            for lbl, opdict in self.operation_blks.items()])\n        copyInto.instrument_blks = _collections.OrderedDict([(lbl, idict.copy(copyInto))\n                                                             for lbl, idict in self.instrument_blks.items()])\n        copyInto.factories = _collections.OrderedDict([(lbl, fdict.copy(copyInto))\n                                                       for lbl, fdict in self.factories.items()])\n\n        copyInto._state_space_labels = self._state_space_labels.copy()  # needed by simplifier helper\n        copyInto._shlp = self.simplifier_helper_class(copyInto)\n\n    def __setstate__(self, stateDict):\n        self.__dict__.update(stateDict)\n        if 'uuid' not in stateDict:\n            self.uuid = _uuid.uuid4()  # create a new uuid\n\n        if 'factories' not in stateDict:\n            self.factories = _collections.OrderedDict()  # backward compatibility (temporary)\n\n        #Additionally, must re-connect this model as the parent\n        # of relevant OrderedDict-derived classes, which *don't*\n        # preserve this information upon pickling so as to avoid\n        # circular pickling...\n        for prepdict in self.prep_blks.values():\n            prepdict.parent = self\n            for o in prepdict.values(): o.relink_parent(self)\n        for povmdict in self.povm_blks.values():\n            povmdict.parent = self\n            for o in povmdict.values(): o.relink_parent(self)\n        for opdict in self.operation_blks.values():\n            opdict.parent = self\n            for o in opdict.values(): o.relink_parent(self)\n        for idict in self.instrument_blks.values():\n            idict.parent = self\n            for o in idict.values(): o.relink_parent(self)\n        for fdict in self.factories.values():\n            fdict.parent = self\n            for o in fdict.values(): o.relink_parent(self)\n\n    def get_clifford_symplectic_reps(self, oplabel_filter=None):\n        \"\"\"\n        Constructs a dictionary of the symplectic representations for all\n        the Clifford gates in this model.  Non-:class:`CliffordOp` gates\n        will be ignored and their entries omitted from the returned dictionary.\n\n        Parameters\n        ----------\n        oplabel_filter : iterable, optional\n            A list, tuple, or set of operation labels whose symplectic\n            representations should be returned (if they exist).\n\n        Returns\n        -------\n        dict\n            keys are operation labels and/or just the root names of gates\n            (without any state space indices/labels).  Values are\n            `(symplectic_matrix, phase_vector)` tuples.\n        \"\"\"\n        gfilter = set(oplabel_filter) if oplabel_filter is not None \\\n            else None\n\n        srep_dict = {}\n\n        for gl in self.get_primitive_op_labels():\n            gate = self.operation_blks['layers'][gl]\n            if (gfilter is not None) and (gl not in gfilter): continue\n\n            if isinstance(gate, _op.EmbeddedOp):\n                assert(isinstance(gate.embedded_op, _op.CliffordOp)), \\\n                    \"EmbeddedClifforGate contains a non-CliffordOp!\"\n                lbl = gl.name  # strip state space labels off since this is a\n                # symplectic rep for the *embedded* gate\n                srep = (gate.embedded_op.smatrix, gate.embedded_op.svector)\n            elif isinstance(gate, _op.CliffordOp):\n                lbl = gl.name\n                srep = (gate.smatrix, gate.svector)\n            else:\n                lbl = srep = None\n\n            if srep:\n                if lbl in srep_dict:\n                    assert(srep == srep_dict[lbl]), \\\n                        \"Inconsistent symplectic reps for %s label!\" % lbl\n                else:\n                    srep_dict[lbl] = srep\n\n        return srep_dict\n\n    def __str__(self):\n        s = \"\"\n        for dictlbl, d in self.prep_blks.items():\n            for lbl, vec in d.items():\n                s += \"%s:%s = \" % (str(dictlbl), str(lbl)) + str(vec) + \"\\n\"\n        s += \"\\n\"\n        for dictlbl, d in self.povm_blks.items():\n            for lbl, povm in d.items():\n                s += \"%s:%s = \" % (str(dictlbl), str(lbl)) + str(povm) + \"\\n\"\n        s += \"\\n\"\n        for dictlbl, d in self.operation_blks.items():\n            for lbl, gate in d.items():\n                s += \"%s:%s = \\n\" % (str(dictlbl), str(lbl)) + str(gate) + \"\\n\\n\"\n        for dictlbl, d in self.instrument_blks.items():\n            for lbl, inst in d.items():\n                s += \"%s:%s = \" % (str(dictlbl), str(lbl)) + str(inst) + \"\\n\"\n        s += \"\\n\"\n        for dictlbl, d in self.factories.items():\n            for lbl, factory in d.items():\n                s += \"%s:%s = \" % (str(dictlbl), str(lbl)) + str(factory) + \"\\n\"\n        s += \"\\n\"\n\n        return s\n", "meta": {"hexsha": "fdecb918ca50146ac0025347d71710ee1c10bf29", "size": 14183, "ext": "py", "lang": "Python", "max_stars_repo_path": "pygsti/objects/implicitmodel.py", "max_stars_repo_name": "drewrisinger/pyGSTi", "max_stars_repo_head_hexsha": "dd4ad669931c7f75e026456470cf33ac5b682d0d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-19T15:11:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T15:11:09.000Z", "max_issues_repo_path": "pygsti/objects/implicitmodel.py", "max_issues_repo_name": "drewrisinger/pyGSTi", "max_issues_repo_head_hexsha": "dd4ad669931c7f75e026456470cf33ac5b682d0d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pygsti/objects/implicitmodel.py", "max_forks_repo_name": "drewrisinger/pyGSTi", "max_forks_repo_head_hexsha": "dd4ad669931c7f75e026456470cf33ac5b682d0d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.1687898089, "max_line_length": 113, "alphanum_fraction": 0.6202495946, "include": true, "reason": "import numpy,import scipy", "num_tokens": 3107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.32082128783705344, "lm_q1q2_score": 0.17788592391234126}}
{"text": "# pylint: disable=C0103,C0303 \n\n# Scan the parameter space for valid points, and for each valid point, compute\n# (xsec H * BR(H->tau) / (xsec A * BR(A->tau) \n\nimport os\nimport numpy as np\nfrom argparse import ArgumentParser\nimport pickle\nimport multiprocessing\nimport subprocess\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport csv\nimport time, datetime\nfrom glob import glob\nfrom generate_samples.lhatool import LHA, Block, Entry\n\n\nsushi_binary = os.environ['SUSHIPATH']\n\n\ndef write_sushi_input_files(lhafile):\n    \"\"\" Add SusHi-related blocks to LHA file \"\"\" \n    \n    outfiles = {}\n    \n    for higgsname, higgstype in {'H': 12, 'A': 21}.iteritems():\n        \n        lha = LHA(lhafile)\n        \n        sushi = Block('SUSHI', comment='SusHi specific')\n        sushi.add(Entry([1, 2], comment='Select 2HDM'))\n        sushi.add(Entry([2, higgstype], comment='h / H / A'))\n        sushi.add(Entry([3, 0], comment='p-p collisions'))\n        sushi.add(Entry([4, 13000], comment='E_cm'))\n        sushi.add(Entry([5, 2], comment='ggH at NNLO'))\n        sushi.add(Entry([6, 2], comment='bbH at NNLO'))\n        sushi.add(Entry([7, 2], comment='SM EW content'))\n        sushi.add(Entry([19, 1], comment='Verbosity'))\n        sushi.add(Entry([20, 0], comment='All processes'))\n        lha.add_block(sushi)\n\n        thdm = Block('2HDM', '2HDM parameters')\n        #thdm.add(Entry([1], comment='Type I'))\n        #thdm.add(Entry([2], comment='Type II'))\n        thdm.add(Entry([4], comment='Type IV'))\n        lha.add_block(thdm)\n\n        distrib = Block('DISTRIB', comment='Kinematic requirements')\n        distrib.add(Entry([1, 0], comment='Sigma total'))\n        distrib.add(Entry([2, 0], comment='Disable pT cut'))\n        #distrib.add(Entry([21, GENER_SETTINGS['higgs_pt_min']], comment='Min higgs pT'))\n        distrib.add(Entry([3, 0], comment='Disable eta cut'))\n        #distrib.add(Entry([32, GENER_SETTINGS['higgs_eta_max']], comment='Max eta'))\n        distrib.add(Entry([4, 1], comment='Use eta, not y'))\n        lha.add_block(distrib)\n\n        pdfspec = Block('PDFSPEC')\n        pdfspec.add(Entry([1, 'MMHT2014lo68cl.LHgrid'], comment='Name of pdf (lo)'))\n        pdfspec.add(Entry([2, 'MMHT2014nlo68cl.LHgrid'], comment='Name of pdf (nlo)'))\n        pdfspec.add(Entry([3, 'MMHT2014nnlo68cl.LHgrid'], comment='Name of pdf (nnlo)'))\n        pdfspec.add(Entry([4, 'MMHT2014nnlo68cl.LHgrid'], comment='Name of pdf (n3lo)'))\n        pdfspec.add(Entry([10, 0], comment='Set number'))\n        lha.add_block(pdfspec)\n\n        lha.get_block('SMINPUTS').add(Entry([8, 1.275], comment='m_c'))\n\n        # Write output\n        suffix = '_%s_sushi.in' % higgsname\n        outname = lhafile.replace('.lha', suffix)\n\n        lha.write(outname)\n        \n        outfiles[higgsname] = outname\n    \n    return outfiles\n\n\n\n\ndef worker(mass, tanbeta, q):\n    \"\"\" Compute cross section * BR for this point  \"\"\" \n    \n    result = ''\n \n    # Prevent crash from destroying the entire scan\n    try:\n\n        br_tautau = {}\n        xsec = {}\n    \n        # Run 2HDMC (which only allows writing directly to file)\n        try:\n            with open(os.devnull, 'w') as DEVNULL:\n                output = subprocess.check_output(['./ratio_scanner', str(mass), str(mass), str(tanbeta)])\n        except subprocess.CalledProcessError:\n            # Invalid point\n            return result\n\n             \n        # Get file name from output. Open and parse it, get BRs\n        lhafilename = output.split('\\n')[-2]\n        lha = LHA(lhafilename)\n        \n        br_tautau['H'] = float(lha.get_decay(35).get_branching_ratio(15, -15))\n        br_tautau['A'] = float(lha.get_decay(36).get_branching_ratio(15, -15))\n        m12_2 = float(lha.get_block('MINPAR').get_entry_by_key(18))\n        \n        del lha\n        \n        # Now write SusHi input files\n        sushi_inputs = write_sushi_input_files(lhafilename)\n        \n        # Run SusHi for both A and H\n        for higgsname, infile in sushi_inputs.iteritems():\n            \n            outfile = infile.replace('.in', '.out')\n            with open(os.devnull, 'w') as DEVNULL:\n                subprocess.check_call([sushi_binary, infile, outfile], stdout=DEVNULL)\n            \n            # Get cross sections\n            lha = LHA(outfile)\n            xsec[higgsname] = float(lha.get_block('SUSHIggh').get_entry_by_key(1))\n            \n            # Remove files\n            os.remove(infile)\n            os.remove(outfile)\n        \n        os.remove(lhafilename)\n        \n        # Output \n        # mH mA m12_2 tanb xsec-H xsec-A xsec-ratio BR-H BR-A BR-ratio tot-ratio\n        res = '{},{},{},{},{},{},{},{},{},{},{}\\n'.format(\n            mass, mass, m12_2, tanbeta,\n            xsec['H'], xsec['A'], (xsec['H']/xsec['A']),\n            br_tautau['H'], br_tautau['A'], (br_tautau['H']/br_tautau['A']),\n            (xsec['H']/xsec['A'])*(br_tautau['H']/br_tautau['A'])\n        )\n        \n        result += res\n\n    except:\n        return result\n        \n    \n    # Clean up remaining lha files\n    try:\n        for fs in glob('massH_%d_massA_%d_tanb_%f*' % (int(mass), int(mass), tanbeta)):\n            os.remove(fs)\n    except:\n        pass\n\n    # Write result to q\n    q.put(result)\n    return result\n        \n\n\ndef listener(q):\n    \"\"\" Listen for messages broadcasted on 'q', write to file. \"\"\"\n\n    f = open(FILENAME, 'wb')\n    f.write('mH,mA,m12_2,tanb,xsec-H,xsec-A,xsec-ratio,BR-H,BR-A,BR-ratio,tot-ratio\\n')\n    while True:\n        m = q.get()\n        if m == 'stop':\n            break\n        f.write(str(m))\n        f.flush()\n    f.close()\n    \n    \n\n\ndef scan(ncpu):\n    \"\"\" Run the scan \"\"\"\n    \n    starttime = time.time()\n\n    # Number of points to compute\n    npoints = 10000\n    #npoints = 100\n\n    # Ranges to consider \n    allowed_mass_range = [360, 800]\n    allowed_tanb_range = [0.1, 60]\n\n    # Job manager\n    manager = multiprocessing.Manager()\n    q = manager.Queue()\n    pool = multiprocessing.Pool(ncpu)\n    \n    # Start the listener \n    watcher = pool.apply_async(listener, (q,))\n    \n    # Submit jobs\n    jobs = []\n    for i in xrange(npoints):\n\n        # Draw mass and tanb values\n        mass = np.random.uniform(allowed_mass_range[0], allowed_mass_range[1])\n        tanb = np.random.exponential(scale=10)\n        while tanb < allowed_tanb_range[0] or tanb > allowed_tanb_range[1]:\n            tanb = np.random.exponential(scale=10)\n\n        job = pool.apply_async(worker, (mass, tanb, q))\n        jobs.append(job)\n        \n    # Collect results from the workers through the pool result queue\n    for job in jobs:\n        job.get()\n    \n\n    # Stop the listener\n    q.put('stop')\n    pool.close()\n    \n    print 'Done.'\n    endtime = time.time()\n    print '\\nTime elapsed for %d points: %s' % (npoints, str(datetime.timedelta(seconds=endtime-starttime)))\n\n    \n    \ndef plot(resultsfile):\n    \"\"\" Plot results from scan \"\"\"\n    \n    plt.style.use('../plot/paper.mplstyle')\n    \n    masses = []\n    br_H = []\n    br_A = []\n    br_ratios = []\n    xsec_H = []\n    xsec_A = []\n    xsec_ratios = []\n    total_ratios = []\n    tanbs = []\n\n    #  0, 1,    2,   3,     4,     5,         6,   7,   8,       9,       10\n    # mH,mA,m12_2,tanb,xsec-H,xsec-A,xsec-ratio,BR-H,BR-A,BR-ratio,tot-ratio\n\n    \n    with open(resultsfile, 'rb') as csvfile:\n        reader = csv.reader(csvfile)\n        for row in reader:\n            if not len(row):\n                continue\n            if row[0] == 'mH':\n                continue    # Header\n            masses.append(float(row[0]))\n            xsec_H.append(float(row[4]))\n            xsec_A.append(float(row[5]))\n            xsec_ratios.append(float(row[6]))\n            br_H.append(float(row[7]))\n            br_A.append(float(row[8]))\n            br_ratios.append(float(row[9]))\n            total_ratios.append(float(row[10]))\n            tanbs.append(float(row[3]))\n    \n    # Set up colormap and colorbar\n    colormap = plt.cm.get_cmap('viridis')\n    formatter = matplotlib.ticker.LogFormatter(10, labelOnlyBase=False, minor_thresholds=(100,1))\n    \n    \"\"\"\n    # Plot cross section ratio\n    fig = plt.figure()\n    sc = plt.scatter(masses, xsec_ratios, c=tanbs, vmin=0.5, vmax=60, cmap=colormap, norm=matplotlib.colors.LogNorm())\n    colorbar = plt.colorbar(ticks=[0.5, 1, 5, 10, 20, 30, 40, 50, 60], format=formatter)\n    colorbar.set_label(r'$\\tan\\beta$')\n    plt.xlabel(r'$m_{A/H}$ (GeV)')\n    plt.ylabel(r'$\\frac{\\sigma(gg\\rightarrow H)}{\\sigma(gg\\rightarrow A)}$')\n    fig.show()\n    \"\"\"\n\n    \"\"\"\n    # Plot BR ratio\n    fig = plt.figure()\n    sc = plt.scatter(masses, br_ratios, c=tanbs, vmin=0.5, vmax=60, cmap=colormap, norm=matplotlib.colors.LogNorm())\n    colorbar = plt.colorbar(ticks=[0.5, 1, 5, 10, 20, 30, 40, 50, 60], format=formatter)\n    colorbar.set_label(r'$\\tan\\beta$')\n    plt.xlabel(r'$m_{A/H}$ (GeV)')\n    plt.ylabel(r'$\\frac{\\mathcal{B}(H\\rightarrow \\tau\\tau)}{\\mathcal{B}(A\\rightarrow \\tau\\tau)}$')\n    fig.show()\n    \"\"\"\n\n    \"\"\"\n    # Plot total ratio, H/A\n    fig = plt.figure()\n    sc = plt.scatter(masses, total_ratios, c=tanbs, vmin=0.5, vmax=60, cmap=colormap, norm=matplotlib.colors.LogNorm())\n    colorbar = plt.colorbar(ticks=[0.5, 1, 5, 10, 20, 30, 40, 50, 60], format=formatter)\n    colorbar.set_label(r'$\\tan\\beta$')\n    plt.xlabel(r'$m_{A/H}$ (GeV)')\n    plt.ylabel(r'$\\frac{\\sigma(gg\\rightarrow H)\\times \\mathcal{B}(H\\rightarrow \\tau\\tau)}{\\sigma(gg\\rightarrow A)\\times \\mathcal{B}(A\\rightarrow \\tau\\tau)}$')\n    fig.show()\n    \"\"\"\n    \n    \n  \n\n    # Plot xsec*BR for H\n    fig = plt.figure()\n    xsec_times_Br_H = np.array(br_H)*np.array(xsec_H)\n    sc = plt.scatter(masses, xsec_times_Br_H, c=tanbs, vmin=0.5, vmax=60, s=8, cmap=colormap, norm=matplotlib.colors.LogNorm())\n    colorbar = plt.colorbar(ticks=[0.5, 1, 5, 10, 20, 30, 40, 50, 60], format=formatter)\n    colorbar.set_label(r'$\\tan\\beta$')\n    plt.yscale('log')\n    plt.ylim(1.0e-7, 1)\n    plt.xlabel(r'$m_{H}$ [GeV]')\n    plt.ylabel(r'$\\sigma(gg/b\\bar{b}\\rightarrow H)\\times \\mathcal{B}(H\\rightarrow \\tau\\tau)$ [pb]')\n    fig.show()\n    plt.tight_layout()\n    fig.savefig('xsec_vs_mass_H.pdf')\n    \n    # Plot xsec*BR for A\n    fig = plt.figure()\n    xsec_times_Br_A = np.array(br_A)*np.array(xsec_A)\n    sc = plt.scatter(masses, xsec_times_Br_A, c=tanbs, vmin=0.5, vmax=60, s=6, cmap=colormap, norm=matplotlib.colors.LogNorm())\n    colorbar = plt.colorbar(ticks=[0.5, 1, 5, 10, 20, 30, 40, 50, 60], format=formatter)\n    colorbar.set_label(r'$\\tan\\beta$')\n    plt.yscale('log')\n    plt.ylim(1.0e-7, 1)\n    plt.xlabel(r'$m_{A}$ [GeV]')\n    plt.ylabel(r'$\\sigma(gg/b\\bar{b}\\rightarrow A)\\times \\mathcal{B}(A\\rightarrow \\tau\\tau)$ [pb]')\n    fig.show()\n    plt.tight_layout()\n    fig.savefig('xsec_vs_mass_A.pdf')\n   \n    \"\"\"\n    # Plot xsec*BR for both\n    fig = plt.figure()\n    sc = plt.scatter(masses, np.array(br_H)*np.array(xsec_H)+np.array(br_A)*np.array(xsec_A), c=tanbs, vmin=0.5, vmax=60, s=20, cmap=colormap, norm=matplotlib.colors.LogNorm())\n    colorbar = plt.colorbar(ticks=[0.5, 1, 5, 10, 20, 30, 40, 50, 60], format=formatter)\n    colorbar.set_label(r'$\\tan\\beta$')\n    plt.yscale('log')\n    plt.ylim(1.0e-9, 1)\n    plt.xlabel(r'$m_{A/H}$ (GeV)')\n    plt.ylabel(r'$\\sigma(gg\\rightarrow A)\\times \\mathcal{B}(A\\rightarrow \\tau\\tau)$ [pb]')\n    fig.show()\n    \"\"\"\n   \n    \"\"\"\n    # Plot total ratio, A/H\n    fig = plt.figure()\n    total_ratio_A_over_H = xsec_times_Br_A/xsec_times_Br_H\n    sc = plt.scatter(masses, total_ratio_A_over_H, c=tanbs, vmin=0.5, vmax=60, s=8, cmap=colormap, norm=matplotlib.colors.LogNorm())\n    colorbar = plt.colorbar(ticks=[0.5, 1, 5, 10, 20, 30, 40, 50, 60], format=formatter)\n    colorbar.set_label(r'$\\tan\\beta$')\n    #plt.yscale('log')\n    plt.ylim(0, 10)\n    plt.xlabel(r'$m_{A/H}$ (GeV)')\n    plt.ylabel(r'$\\frac{\\sigma(gg\\rightarrow A)\\times \\mathcal{B}(A\\rightarrow \\tau\\tau)}{\\sigma(gg\\rightarrow H)\\times \\mathcal{B}(H\\rightarrow \\tau\\tau)}$')\n    fig.show()\n    plt.tight_layout()\n    \"\"\"\n    \n    # Plot theta = nA/(nA+nH)\n    fig = plt.figure()\n    theta = xsec_times_Br_A/(xsec_times_Br_A+xsec_times_Br_H)\n    sc = plt.scatter(masses, theta, c=tanbs, vmin=0.5, vmax=60, s=8, cmap=colormap, norm=matplotlib.colors.LogNorm())\n    colorbar = plt.colorbar(ticks=[0.5, 1, 5, 10, 20, 30, 40, 50, 60], format=formatter)\n    colorbar.set_label(r'$\\tan\\beta$')\n    #plt.yscale('log')\n    plt.ylim(0.335, 1.025)\n    plt.xlabel(r'$m_{A/H}$ [GeV]')\n    plt.ylabel(r'$\\alpha$')\n    fig.show()\n    plt.tight_layout()\n    fig.savefig('alpha_vs_mass.pdf')\n    \n    plt.show()\n    \n    \nif __name__ == '__main__':\n    \n    parser = ArgumentParser(description='Scan H/A ratio vs mass')\n    parser.add_argument('-s', '--scan', help='Run scan', action='store_true')\n    parser.add_argument('-p', '--plot', help='Create plot', action='store_true')\n    parser.add_argument('-nc', '--ncpu', type=int, help='Number of parallel jobs', default=8)\n    parser.add_argument('-f', '--filename', type=str, help='Input/output file', default='results_ratio_scan.csv')\n    pargs = parser.parse_args()\n    \n    FILENAME = pargs.filename\n\n    if pargs.scan:\n        if os.path.exists(FILENAME):\n            owr = raw_input('Output file %s exists -- overwrite (y/n)? ' % FILENAME)\n            if owr.lower().replace('\\n', '') != ('y'):\n                print 'exit'\n                exit()\n        scan(pargs.ncpu)\n        \n    if pargs.plot:\n        plot(FILENAME)\n    \n", "meta": {"hexsha": "be69d03f46672d8d0d7857655321956dce4dcd69", "size": 13400, "ext": "py", "lang": "Python", "max_stars_repo_path": "scan/ratio_scanner.py", "max_stars_repo_name": "smaeland/ML-2HDM", "max_stars_repo_head_hexsha": "20ca00847c82fcd6a28a6e1c65c43e0aba1a3d65", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scan/ratio_scanner.py", "max_issues_repo_name": "smaeland/ML-2HDM", "max_issues_repo_head_hexsha": "20ca00847c82fcd6a28a6e1c65c43e0aba1a3d65", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scan/ratio_scanner.py", "max_forks_repo_name": "smaeland/ML-2HDM", "max_forks_repo_head_hexsha": "20ca00847c82fcd6a28a6e1c65c43e0aba1a3d65", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8383838384, "max_line_length": 176, "alphanum_fraction": 0.5862686567, "include": true, "reason": "import numpy", "num_tokens": 4050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.17787908957508883}}
{"text": "import numpy as np\nimport os\nimport torch\nimport torch.nn as nn\nimport math\nimport torch.nn.functional as F\n#from multi_model.utils.pointnet_test import PointNetPartFeature\nfrom multi_model.utils.pointnet2 import PointNet2TwoStage, PointNet2Refine\n\nclass GripperRegionNetwork(nn.Module):\n    \"\"\"\n    关于GraspRegion的网络部分，通过标志位可以选择性地实现对RefineNet的集成\n    \"\"\"\n    def __init__(self, training, group_num, gripper_num, grasp_score_threshold, radius, reg_channel):\n        '''\n        training：bool型，选择是否加载RN网络\n        group_num：Grasp Region包围球中的点数\n        gripper_num：\n        grasp_score_threshold：\n        radius：\n        reg_channel：单个anchor回归出的对应bias等参数(作者设置的通道是8； x,y,z,rx,ry,rz)\n        '''\n        super(GripperRegionNetwork, self).__init__()\n        #是否\n        self.group_number = group_num\n        \n        self.templates = _enumerate_templates()#枚举不同角度的anchors模板，这个只是把多种角度显式地表示出来，还没有和抓取中心点结合起来\n        \n        self.anchor_number = self.templates.shape[1]*self.templates.shape[2]#计算一下所有anchors的数量\n        #\n        self.gripper_number = gripper_num\n        self.grasp_score_thre = grasp_score_threshold\n        self.is_training_refine = training\n        self.radius = radius\n        self.reg_channel = reg_channel #每个anchor抓取要回归出的值一共8通道，其中3通道位置残差\n\n        #利用包围球内点特征，回归抓取位置姿态残差与分数\n        self.extrat_feature_region = PointNet2TwoStage(\n            num_points=group_num, #包围球内点数\n            input_chann=6, #点云通道数xyzrgb\n            k_cls=self.anchor_number,#每个中心点对应M个anchor\n            k_reg=self.reg_channel*self.anchor_number,#同时回归出M个anchor抓取的每个通道的res残差\n            k_reg_theta=self.anchor_number)  #回归出theta的残差\n\n        #构建RN网络（不一定用上去，要看模式的选择）\n        self.extrat_feature_refine = PointNet2Refine(num_points=gripper_num, input_chann=6, k_cls=2, k_reg=self.reg_channel)\n\n        self.criterion_cos = nn.CosineEmbeddingLoss(reduction='mean')\n        self.criterion_cls = torch.nn.CrossEntropyLoss(reduction='mean')\n        self.smooth_l1_loss = nn.SmoothL1Loss(reduction='mean')\n\n    def _enumerate_anchors(self, centers):\n        '''根据给定的锚点位置坐标，把预设的姿态模板和位置坐标连接在一起，构成预设的系列anchors位姿向量\n        每个抓取中心，将预设M个anchors\n          Enumerate anchors.\n          Input:\n            centers: [B*num of centers, 3] -> x, y, z  输入是Batch的所有中心点的xyz坐标\n            self.templates :[1,M,1,4] -> M:r_x r_y r_z_num 1:theta_num 4:r_x r_y r_z theta\n          Return:\n            t_anchors: [B*num of centers, M, 7] -> the number of anchors is M\n                                                     7 means (x, y, z, rx, ry, rz, theta)\n                                                     每个中心点将固定有M个模板，每个模板都是7维的\n        '''\n        if centers.cuda:\n            self.templates = self.templates.cuda() #获取模板\n        t_center = centers.view(centers.shape[0],1,1,-1).repeat(1,self.templates.shape[1],self.templates.shape[2],1)\n        t_anchors = torch.cat( [t_center, self.templates.float().repeat(centers.shape[0],1,1,1)], dim=-1).view(-1, self.templates.shape[1]*self.templates.shape[2], 7)\n        return t_anchors\n\n    def compute_loss(self, first_grasp, anchors, first_cls, ground):\n        '''在训练时，计算回归出的抓取和ground truth抓取之间的差别loss\n        Input:  \n            first_grasp : [B*center_num, num_anchor, 8]  回归出的残差+score\n            anchors     : [B*center_num, num_anchor, 7]    anchors\n            first_cls   : [B*center_num, num_anchor]           对B*M个anchors的分类结果\n            ground      : [B, center_num, 8]  ground truth. 只在训练的时候有用，而在测试时候是没有的\n                                    8 means the (p,r,theta,score) of a grasp. 说明groudtruth，在每个中心点处，只有一个真实抓取\n        Return:\n            next_grasp  : [len(select_center_index), 7]预测的完整抓取\n            loss_tuple, correct_tuple\n            next_gt : [len(select_center_index), 7]\n        Loss一共有两部分：\n        1. B*M个anchor的分类误差\n        2. res的回归损失\n        问题：groundtruth是如何确定是哪个编号的anchor离自己最近的呢？在哪里计算的？\n        '''\n        #### gmask: [len(gmask)]  true mask index of centers which has a corresponding grasp \n        BmulN_C = len(first_grasp) #一个batch中有多少个抓取中心\n        # B, N_C = ground.shape[0], ground.shape[1]\n        if ground is not None:#训练时\n            '''在数据集中查到带有正抓取的center的index列表\n            例如gmask=[0,1,3,5,6,7] 表明在第0，1，3，5，7号抓取中心点处可以在数据集中查找到合理的抓取\n            ground.view(-1,ground.shape[2])     [B*center_num, 8] 注意这里实际上是10维度的\n            gmask     len(gmask)=带有正抓取的抓取中心点的数量\n            '''\n            gmask = torch.nonzero(ground.view(-1,ground.shape[2])[:,-1] != -1).view(-1) #gmask[len(gmask) ]\n            print(BmulN_C, \"centers has\", len(gmask), \"grasps\" )              \n        else:#测试时\n            gmask = torch.arange(0, BmulN_C)#\n        if first_grasp.cuda:\n            gmask = gmask.cuda()\n\n        \n        anchors = anchors[gmask, :, :]#利用gmask筛选出具有正抓取的预设anchor,  [len(gmask) ,num_anchor,7]\n        tt = anchors.clone().detach().transpose(1,0).contiguous().view(-1,7) #拷贝并变形为[len(gmask)*num_anchor, 7]\n        first_grasp, first_cls = first_grasp[gmask], first_cls[gmask]#提取出与groundtruth正抓取中心点对应的回归预测grasp，以及预测的类别\n\n        \n        first_grasp = first_grasp.transpose(1,0).contiguous().view(-1, first_grasp.shape[2])# 变形为[len(gmask)*num_anchor, 8] \n\n        num_anchor = self.templates.shape[1]*self.templates.shape[2]\n        #计算预测的一个batch的anchor索引\n        _, predict_8 = torch.max(first_cls.transpose(1,0).contiguous(), dim=0)#[len(gmask),]找到预测分类值为1的anchor索引\n        final_mask = predict_8.clone().view(-1)#找到预测分类值为1的anchor索引\n        for i in range(len(final_mask)):#\n            final_mask[i] = final_mask[i] * len(final_mask) + i\n\n        #筛选出来一个batch的预测抓取残差，以及预测anchor姿态\n        first_grasp_pre, tt_pre = first_grasp[final_mask], tt[final_mask]\n\n        #利用预测残差与anchor姿态，还原出完整抓取位姿\n        sum_r_pre = torch.sqrt(torch.sum(torch.mul(first_grasp_pre[:,3:6]+tt_pre[:,3:6],\n                 first_grasp_pre[:,3:6]+tt_pre[:,3:6]), dim=1).add_(1e-12) ).view(-1,1)#求原始binormal轴模长\n\n        first_grasp_center_pre = first_grasp_pre[:, :3]*self.radius + tt_pre[:,:3]#还原抓取中心[len(gmask),3]\n        first_grasp_r_pre = torch.div(first_grasp_pre[:,3:6]+tt_pre[:,3:6], sum_r_pre)#还原binormal轴（单位化）[len(gmask),3]\n        first_grasp_angle_pre = np.pi * (first_grasp_pre[:,6:7]+tt_pre[:,6:7])#还原抓取角度[len(gmask),1]\n        first_grasp_score_pre = first_grasp_pre[:,7:]#分数[len(gmask),1]\n       \n        #构成完整的预测位姿+score的tensor\n        next_grasp = torch.cat((first_grasp_center_pre, first_grasp_r_pre, \\\n                                    first_grasp_angle_pre, first_grasp_score_pre), dim=-1)#[]\n        \n        loss_tuple = (None, None)\n        correct_tuple, next_gt, tt_gt = (None, None, None, None), None, None\n\n        if ground is not None:\n            '''计算GRN阶段的Loss\n            两部分Loss：1.\n            '''\n            #[B,center_num,10]->[B*center_num,7]->[len(gmask),7]->[len(gmask)*anchor_num,7]\n            repeat_ground = ground[:,:,:7].contiguous().view(-1, 7)[gmask, :].\\\n                repeat(self.templates.shape[1]*self.templates.shape[2],1)\n            repeat_ground_truth = ground[:,:,7:].contiguous().view(-1, ground.shape[2]-7)[gmask, :].\\\n                repeat(self.templates.shape[1]*self.templates.shape[2],1)\n            ## r_sim: [num_anchor, len(gmask)]，计算ground truth的binormal轴与每个预设的anchor之间的cos值\n            r_sim = compute_cos_sim(tt[:,3:6], repeat_ground[:,3:6]).view(-1).view(num_anchor, -1)\n\n            ## ground_8: [len(gmask)]\n            sim = r_sim.clone().transpose(1,0)\n            #[len(gmask),anchor_num] 找到ground truth的binormal轴与哪个预设的anchor之间最近，得到index\n            sort_cls, sort_index = torch.sort(sim, dim=1, descending=False)\n            ground_8 = sort_index[:,0].view(-1)#[len(gmask),] 每个ground truth最相似预设anchor的index\n            \n            #print(ground_8)\n            iou_nonzero = ground_8.clone()\n            for i in range(len(iou_nonzero)):\n                iou_nonzero[i] = iou_nonzero[i] * len(iou_nonzero) + i\n            \n            len_ground_anchor, num_0, num_t = np.zeros([num_anchor]), 0, 0\n            #一共M种anchor，计算每种anchor与之最近的ground truth的数量\n            for i in range(num_anchor):\n                len_ground_anchor[i] = (ground_8==i).sum()\n                if len_ground_anchor[i] == 0:\n                    num_0 += 1\n            for i in range(num_anchor):#计算每种anchor与之最近的预测抓取的数量\n                print(i, \"num:\", (predict_8==i).sum()) \n\n\n            min_len_ground_anchor = len_ground_anchor.min()#找到最少的数量\n            if min_len_ground_anchor == 0:\n                min_len_ground_anchor = 1\n            ground_anchor_index = torch.zeros([num_anchor-num_0, int(min_len_ground_anchor)])\n            for i in range(num_anchor):\n                cur_anchor_index = torch.nonzero(ground_8==i).view(-1)\n                if len(cur_anchor_index) == 0:\n                    continue\n                ground_anchor_index[num_t] = cur_anchor_index[np.random.choice(len(cur_anchor_index), \\\n                                                          int(min_len_ground_anchor), replace=False)]\n                num_t += 1\n                \n            ground_anchor_index = ground_anchor_index.view(-1).long()\n            if ground.is_cuda:\n                ground_anchor_index = ground_anchor_index.cuda()\n            #交叉熵计算分类Loss，\n            loss_class = self.criterion_cls(first_cls, ground_8.long())\n            #loss_class = self.criterion_cls(first_cls[ground_anchor_index], ground_8[ground_anchor_index].long())\n            print(\"regression stage 1 class loss:\", loss_class)\n            \n            Tcls = ( ground_8 == predict_8).sum().float()#anchor分类正确的个数\n            Fcls = (ground_8 != predict_8).sum().float()#anchor分类失败的个数\n            correct_tuple = (Tcls, Fcls)\n            acc = Tcls / (Tcls + Fcls)\n            print(Tcls, Fcls, \"acc1:\", acc)\n            \n\n            first_grasp_gt, tt_gt  = first_grasp[iou_nonzero], tt[iou_nonzero]\n            sum_r_gt               = torch.sqrt(torch.sum(torch.mul(first_grasp_gt[:,3:6]+tt_gt[:,3:6], \\\n                                                first_grasp_gt[:,3:6]+tt_gt[:,3:6]), dim=1).add_(1e-12) ).view(-1,1)\n            first_grasp_center_gt  = first_grasp_gt[:,:3]*self.radius + tt_gt[:,:3]\n            first_grasp_r_gt       = torch.div(first_grasp_gt[:,3:6]+tt_gt[:,3:6], sum_r_gt)\n            first_grasp_delta_r_gt = torch.mul(first_grasp_gt[:,3:6], sum_r_gt)\n            first_grasp_angle_gt   = np.pi * (first_grasp_gt[:,6:7]+tt_gt[:,6:7])\n            first_grasp_score_gt   = first_grasp_gt[:,7:]\n            # (sinx, cosx)\n            #first_grasp_angle_gt = torch.atan2(first_grasp_gt[:,-1].view(-1,1), first_grasp_gt[:,-2].view(-1,1)).view(-1,1)\n\n            ground_gt = repeat_ground[iou_nonzero]                 # same as repeat_ground[final_mask]\n            ground_score_gt = repeat_ground_truth[iou_nonzero]  # same as repeat_ground_truth[final_mask]\n            #计算回归姿态+score差的Loss，对比对象为res残差\n            loss_first1_gt  = F.smooth_l1_loss(first_grasp_gt[:,:3],  (ground_gt[:,:3]-tt_gt[:,:3]) / self.radius, reduction='mean')#res_xyz的Loss\n            loss_first2_gt  = F.smooth_l1_loss(first_grasp_delta_r_gt, ground_gt[:,3:6]-tt_gt[:,3:6], reduction='mean')#res_rxyz的Loss\n            loss_first3_gt  = F.smooth_l1_loss(first_grasp_gt[:,6:7], (ground_gt[:,6:7]-tt_gt[:,6:7]) / np.pi, reduction='mean')#res_theta的Loss\n            loss_first4_gt  = F.smooth_l1_loss(first_grasp_gt[:,7:],   ground_score_gt, reduction='mean')#score的Loss\n            print(\"regress loss of stage2\", loss_first1_gt.data, loss_first2_gt.data, loss_first3_gt.data, loss_first4_gt.data)\n            #同样是计算回归姿态+score差的Loss，对比对象为完整姿态\n            tensor_y_gt = torch.ones(len(iou_nonzero), 1)\n            loss_center_gt  = F.smooth_l1_loss  (first_grasp_center_gt, ground_gt[:,:3], reduction='mean').data\n            loss_cos_r_gt   = self.criterion_cos(first_grasp_r_gt, ground_gt[:,3:6], tensor_y_gt.cuda()).data\n            loss_theta_gt   = F.smooth_l1_loss  (first_grasp_angle_gt, ground_gt[:,6:7], reduction='mean').data\n            loss_score_gt   = loss_first4_gt.data\n            print(\"under gt class loss\", loss_center_gt, loss_cos_r_gt, loss_theta_gt, loss_score_gt)\n\n            tensor_y_pre = torch.ones(len(final_mask), 1)\n            loss_center_pre = F.smooth_l1_loss  ( first_grasp_center_pre, ground_gt[:,:3], reduction='mean').data\n            loss_cos_r_pre  = self.criterion_cos( first_grasp_r_pre, ground_gt[:,3:6], tensor_y_pre.cuda()).data\n            loss_theta_pre  = F.smooth_l1_loss  ( first_grasp_angle_pre, ground_gt[:,6:7], reduction='mean').data\n            loss_score_pre  = F.smooth_l1_loss  ( first_grasp_score_pre, ground_score_gt, reduction='mean').data\n            print(\"under pre class loss\", loss_center_pre, loss_cos_r_pre, loss_theta_pre, loss_score_pre)\n            \n            #完整的ground truth抓取向量(pose+score)\n            next_gt = torch.cat((ground_gt, ground_score_gt), dim=1)# [len(gmask), 10]\n\n            loss = loss_first1_gt*10 + loss_first2_gt*5 + loss_first3_gt + loss_first4_gt + loss_class\n            loss_tuple = (loss, loss_class.data, loss_first1_gt.data, loss_first2_gt.data, loss_first3_gt.data, \\\n                            loss_first4_gt.data, loss_center_pre, loss_cos_r_pre, loss_theta_pre, loss_score_pre, )\n\n        return next_grasp, loss_tuple, correct_tuple, next_gt, tt_gt, gmask\n\n    def compute_loss_refine(self, next_grasp, next_x_cls, next_x_reg, next_gt):\n        '''计算RN子网络的Loss\n          Input:\n            next_grasp      :[len(gripper_mask),8] regressed grasp from the stage1\n            next_x_cls      :[len(gripper_mask),2]\n            next_x_reg      :[len(gripper_mask),8] delta grasp from the stage2 (loss)\n            next_gt         :[len(gripper_mask),8]  ground truth 并非残差gt，而是完整的抓取gt\n          Return:\n            final_grasp_select       : [len(class_select), 8] \n            select_grasp_class_stage2: [len(class_select), 8]\n            class_select             : [len(class_select)]\n            loss_stage2              : tuple\n            correct_stage2_tuple     : tuple\n        '''\n        print(\"Refine Module init number:\", next_grasp.shape[0])\n        final_grasp = next_grasp.clone()\n        final_grasp[:,:3] = final_grasp[:,:3] + next_x_reg[:,:3] * self.radius#最终预测的抓取\n        final_grasp[:,3:] = final_grasp[:,3:] + next_x_reg[:,3:] #最终预测的分数\n        \n        # next_x_cls[:,1] += 1\n        predit_formal = torch.max(next_x_cls, dim=-1)[1]\n        class_select  = torch.nonzero(predit_formal==1).view(-1)#预测的正抓取的index\n        score_mask    = (predit_formal==1) & (final_grasp[:,7] > self.grasp_score_thre)#选择回归出的抓取\n        score_select  = torch.nonzero(score_mask).view(-1)#预测的正且高分数的抓取index\n        print(\"########################################\")\n        print(\"predict class 0:\", torch.sum((predit_formal==0)).data, \"; predict class 1:\", torch.sum((predit_formal==1)).data)\n\n        select_grasp_class  = final_grasp[class_select].data#筛选出预测出的正完整抓取姿态\n        select_grasp_score  = final_grasp[score_select].data#筛选出预测的正且高分数的完整抓取姿态\n        select_grasp_class_stage2 = next_grasp[class_select].data#\n\n        print(\"final grasp: {}\".format(len(select_grasp_class)))\n        print(\"final >{} score grasp: {}\".format(self.grasp_score_thre, len(score_select)))\n        print(\"########################################\")\n        loss_refine_tuple, correct_refine_tuple = (None, None), (None, None, None, None)\n\n        if next_gt is not None:\n            #计算gt的分类\n            gt_class = torch.zeros((len(next_gt)))\n            if next_grasp.is_cuda:\n                gt_class = gt_class.cuda()\n            #计算GRN预测位置与gt位置之间的距离\n            center_dist = (next_grasp[:,:3] - next_gt[:,:3]) \n            #预测与ground truth之间的距离之差在2.5mm以内的mask\n            center_dist_mask = (torch.sqrt(torch.mul(center_dist[:,0],center_dist[:,0])+torch.mul(center_dist[:,1],center_dist[:,1])\\\n                                                +torch.mul(center_dist[:,2],center_dist[:,2])) < 0.025).view(-1) \n            # 找到GRN pre_r与gt_r之间的夹角小于60度的mask\n            r_sim = compute_cos_sim(next_grasp[:,3:6], next_gt[:,3:6]).view(-1)\n            r_sim_mask = (r_sim < 0.5).view(-1) # cos60 = 0.5 #0.234\n            #GRN pre_theta与gt_theta之间的角度小于60度的mask\n            theta_sim = torch.abs(next_grasp[:,6] - next_gt[:,6]) \n            theta_sim_mask = (theta_sim < 1.047).view(-1) # 1.047 = 60/180*np.pi\n\n            #同时考虑位置姿态的mask\n            class_mask = (center_dist_mask & r_sim_mask & theta_sim_mask)\n            gt_class[class_mask] = 1\n            gt_class_1 = torch.nonzero(gt_class == 1).view(-1)#预测的合法grasp index\n            gt_class_0 = torch.nonzero(gt_class == 0).view(-1)#预测的非法grasp index\n\n            num_0, num_1 = len(gt_class_0), len(gt_class_1)\n            print(\"class 0:\", num_0, \"; class 1:\", num_1)\n            num = min(num_0, num_1)\n            loss = torch.tensor((0), dtype=torch.float)\n            loss_class, loss_grasp_center, loss_grasp_r, loss_grasp_theta, loss_grasp_score = loss.clone(), loss.clone(), loss.clone(), loss.clone(), loss.clone()\n\n            loss_center_pre_stage2, loss_r_cos_pre_stage2, loss_theta_pre_stage2, loss_score_pre_stage2 = loss.clone(), loss.clone(), loss.clone(), loss.clone()\n            loss_center_pre, loss_r_cos_pre, loss_theta_pre, loss_score_pre = loss.clone(), loss.clone(), loss.clone(), loss.clone()\n            loss_center_pre_score, loss_r_cos_pre_score, loss_theta_pre_score, loss_score_pre_score = loss.clone(), loss.clone(), loss.clone(), loss.clone()\n\n            if next_x_cls.is_cuda:\n                loss, loss_class = loss.cuda(), loss_class.cuda()\n                loss_grasp_center, loss_grasp_r, loss_grasp_theta, loss_grasp_score = loss_grasp_center.cuda(), loss_grasp_r.cuda(), loss_grasp_theta.cuda(), loss_grasp_score.cuda()\n                \n                loss_center_pre_stage2, loss_r_cos_pre_stage2, loss_theta_pre_stage2, loss_score_pre_stage2 = loss_center_pre_stage2.cuda(), loss_r_cos_pre_stage2.cuda(), loss_theta_pre_stage2.cuda(), loss_score_pre_stage2.cuda()\n                loss_center_pre, loss_r_cos_pre, loss_theta_pre, loss_score_pre = loss_center_pre.cuda(), loss_r_cos_pre.cuda(), loss_theta_pre.cuda(), loss_score_pre.cuda()\n                loss_center_pre_score, loss_r_cos_pre_score, loss_theta_pre_score, loss_score_pre_score = loss_center_pre_score.cuda(), loss_r_cos_pre_score.cuda(), loss_theta_pre_score.cuda(), loss_score_pre_score.cuda()\n                \n            if num > 0:\n                index_0 = gt_class_0[np.random.choice(num_0, num, replace=False)].view(-1)\n                index_1 = gt_class_1[np.random.choice(num_1, num, replace=False)].view(-1)\n                index = torch.cat((index_0, index_1), dim=-1)\n                #分类Loss\n                loss_class = self.criterion_cls(next_x_cls.view(-1,2)[index], gt_class.view(-1)[index].long())\n\n                #使用gt_cls，筛选并直接计算pre_res与gt_res之间的Loss\n                loss_grasp_center = F.smooth_l1_loss(next_x_reg[gt_class_1,:3], (next_gt[gt_class_1,:3]-next_grasp[gt_class_1,:3]) / self.radius, reduction='mean')\n                loss_grasp_r      = F.smooth_l1_loss(next_x_reg[gt_class_1,3:6], (next_gt[gt_class_1,3:6]-next_grasp[gt_class_1,3:6]) , reduction='mean')\n                loss_grasp_theta  = F.smooth_l1_loss(next_x_reg[gt_class_1,6], (next_gt[gt_class_1,6]-next_grasp[gt_class_1,6]) , reduction='mean')\n                loss_grasp_score  = F.smooth_l1_loss(next_x_reg[gt_class_1,7:], (next_gt[gt_class_1,7:]-next_grasp[gt_class_1,7:]) , reduction='mean')\n                loss              = loss_class + loss_grasp_center + loss_grasp_r + loss_grasp_theta + loss_grasp_score\n\n            if len(class_select) > 0:\n                tensor_y = torch.ones(len(class_select), 1)\n                if next_x_cls.is_cuda:\n                    tensor_y = tensor_y.cuda()\n                #不带score差异分类(仅位姿差异) pre_cls_no_score,筛选出完整pre_grasp与完整gt_grasp之间的Loss \n                loss_center_pre        = F.smooth_l1_loss(select_grasp_class[:,:3], next_gt[class_select,:3], reduction='mean').data\n                loss_r_cos_pre        = self.criterion_cos(select_grasp_class[:,3:6], next_gt[class_select,3:6],tensor_y).data\n                loss_theta_pre        = F.smooth_l1_loss(select_grasp_class[:,6], next_gt[class_select,6], reduction='mean').data\n                loss_score_pre        = F.smooth_l1_loss(select_grasp_class[:,7:], next_gt[class_select,7:], reduction='mean').data\n                \n                #不带score差异分类(仅位姿差异) pre_cls_no_score,筛选出残差pre_res与完整gt_grasp之间的Loss; \n                loss_center_pre_stage2 = F.smooth_l1_loss(select_grasp_class_stage2[:,:3], next_gt[class_select,:3], reduction='mean').data\n                loss_r_cos_pre_stage2 = self.criterion_cos(select_grasp_class_stage2[:,3:6], next_gt[class_select,3:6],tensor_y).data\n                loss_theta_pre_stage2 = F.smooth_l1_loss(select_grasp_class_stage2[:,6], next_gt[class_select,6], reduction='mean').data\n                loss_score_pre_stage2 = F.smooth_l1_loss(select_grasp_class_stage2[:,7:], next_gt[class_select,7:], reduction='mean').data\n                \n                #带有score差异分类pre_cls_with_score,筛选出完整pre_grasp与完整gt_grasp;  \n                loss_center_pre_score  = F.smooth_l1_loss(select_grasp_score[:,:3], next_gt[score_select,:3], reduction='mean').data\n                loss_r_cos_pre_score  = self.criterion_cos(select_grasp_score[:,3:6], next_gt[score_select,3:6],tensor_y).data\n                loss_theta_pre_score  = F.smooth_l1_loss(select_grasp_score[:,6], next_gt[score_select,6], reduction='mean').data\n                loss_score_pre_score  = F.smooth_l1_loss(select_grasp_score[:,7:], next_gt[score_select,7:], reduction='mean').data\n\n                print(\"loss stage 2 - class: {:.4f}, {:.4f}, {:.4f}, {:.4f}\".format(loss_center_pre_stage2, loss_r_cos_pre_stage2, loss_theta_pre_stage2, loss_score_pre_stage2))\n                print(\"loss stage 3 - class: {:.4f}, {:.4f}, {:.4f}, {:.4f}\".format(loss_center_pre, loss_r_cos_pre, loss_theta_pre, loss_score_pre) )\n                print(\"loss stage 3 - score: {:.4f}, {:.4f}, {:.4f}, {:.4f}\".format(loss_center_pre_score, loss_r_cos_pre_score, loss_theta_pre_score, loss_score_pre_score))\n            \n            #\n            TP = ((gt_class.view(-1) == 1 ) & (predit_formal.view(-1) == 1)).sum().float()#真阳性\n            TN = ((gt_class.view(-1) == 0 ) & (predit_formal.view(-1) == 0)).sum().float()#真阴性\n            FP = ((gt_class.view(-1) == 0 ) & (predit_formal.view(-1) == 1)).sum().float()#假阳性\n            FN = ((gt_class.view(-1) == 1 ) & (predit_formal.view(-1) == 0)).sum().float()#假阴性\n            print(TP,TN,FN,FP)\n            acc = (TP + TN) / (TP + TN + FP + FN)#计算准确率\n            correct_refine_tuple = (TP, TN, FP, FN)\n            print(\"stage2 acc:\", acc)\n\n            loss_refine_tuple = (loss, loss_class.data, loss_grasp_center.data, loss_grasp_r.data, loss_grasp_theta.data, loss_grasp_score, \\\n                                                loss_center_pre_stage2, loss_r_cos_pre_stage2, loss_theta_pre_stage2, loss_score_pre_stage2,\n                                                loss_center_pre, loss_r_cos_pre, loss_theta_pre, loss_score_pre,\n                                                loss_center_pre_score, loss_r_cos_pre_score, loss_theta_pre_score, loss_score_pre_score)\n                                    \n        return select_grasp_class, select_grasp_score, select_grasp_class_stage2, class_select, score_select, loss_refine_tuple, correct_refine_tuple\n\n    def refine_forward(self, pc_group_more_xyz, pc_group_more_index, gmask, all_feature, \\\n                    group_feature_mp, next_grasp, gripper_params, next_gt=None):\n        '''refine net前向计算\n          pc_group_more_xyz   :[B*center_num, group_num_more, 6]\n          pc_group_more_index :[B, center_num, group_num_more]\n          gmask           :[len(gmask)]\n          all_feature         :[B, A, Feature]\n          group_feature_mp    :[B*N_C, 128, 1] 每个抓取包围球经过特征提取之后的128维度特征\n          next_grasp          :[len(gmask), 10]\n          gripper_params      :List [torch.tensor(),float,float] widths, height, depth\n          next_gt             :[len(gmask), 10]\n        '''\n        B, feature_len = all_feature.shape[0], all_feature.shape[2]\n        N_C, N_G_M = pc_group_more_index.shape[1], pc_group_more_index.shape[2]\n        cuda = pc_group_more_xyz.is_cuda\n        \n        #将包围球内部区域\n        gripper_pc, gripper_pc_index, gripper_pc_index_inall, gripper_mask = get_gripper_region_transform(pc_group_more_xyz[gmask], \n                        pc_group_more_index.view(-1,N_G_M)[gmask], next_grasp, self.gripper_number, gripper_params)\n        select_grasp_class, select_grasp_score, select_grasp_class_stage2 = None, None, None\n        final_mask, final_mask_sthre, loss_refine_tuple, correct_refine_tuple = None, None, (None, None), (None, None)\n\n\n        if len(gripper_mask) >= 2:#内部点数满足条件的抓取数量大于2\n            all_feature_new = all_feature.contiguous().view(-1, feature_len)#[B*A,feature]\n            add = torch.arange(B).view(-1,1).repeat(1, N_C).view(-1)[gmask].view(-1,1).repeat(1, self.gripper_number)\n            if pc_group_more_index.cuda:\n                add = add.cuda()\n            #### gripper_pc_index_inall: [len(gmask), region_num]\n            gripper_pc_index_inall_new = (gripper_pc_index_inall.long() + add * all_feature.shape[1]).view(-1)\n            gripper_feature = all_feature_new[gripper_pc_index_inall_new].view(-1, self.gripper_number, feature_len)[gripper_mask]#.detach()\n            #### gripper_feature: [len(gripper_mask), self.gripper_number, feature_len]\n            \n            group_feature_mp = group_feature_mp.view(-1,128)[gripper_mask].contiguous()\n            \n            # next_x_cls: [len(gripper_mask), 2], next_x_reg: [len(gripper_mask), 8]\n            #利用夹爪内部点云的feature和包围球整体feature结合回归出回归res残差\n            next_x_cls, next_x_reg = self.extrat_feature_refine(gripper_feature.permute(0,2,1), group_feature_mp)\n            if next_gt is not None:\n                next_gt = next_gt[gripper_mask]\n            #计算RN  Loss\n            select_grasp_class, select_grasp_score, select_grasp_class_stage2, class_select, score_select, loss_refine_tuple, \\\n                                correct_refine_tuple = self.compute_loss_refine(next_grasp[gripper_mask], next_x_cls, next_x_reg, next_gt)\n\n            if next_gt is not None:\n                next_gt = next_gt[class_select]#挑出最终的预测抓取对应的gt抓取\n\n            final_mask = gmask.clone()[gripper_mask][class_select] \n            final_mask_sthre = gmask.clone()[gripper_mask][score_select] \n\n        return select_grasp_class, select_grasp_score, select_grasp_class_stage2, final_mask, \\\n                            final_mask_sthre, loss_refine_tuple, correct_refine_tuple, next_gt\n        \n    def forward(self, pc_group, pc_group_more, pc_group_index, pc_group_more_index, center_pc, \\\n                    center_pc_index, pc, all_feature, gripper_params, ground_grasp=None, data_path=None):\n        '''GRN网络的前向传播\n        pc_group                            :[B, center_num, group_num, 6]          k1 个包围球内点的xyzrgb值\n        pc_group_more               :[B, center_num, group_num_more, 6]   \n        pc_group_index              :[B, center_num, group_num]   k1个包围球内部点在pc中的索引\n        pc_group_more_index :[B, center_num, group_num_more]\n        center_pc                            :[B, center_num, 6]   FPS返回的k1个抓取中心点的xyzrgb\n        center_pc_index              :[B, center_num]        k1个抓取中心点在原始pc中的索引\n        pc                                           :[B, A, 6]  原始（剪切后）点云\n        all_feature                          :[B, A, Feature]  所有点云点的点特征\n        gripper_params               :List [float,float,float] width, height, depth 夹爪参数\n        ground_grasp:                  :[B,center_num,8] the labels of grasps (ground truth + score) ground truth抓取\n        '''\n        B,N_C,N_G,C = pc_group.shape\n        _,_,N_G_M,_ = pc_group_more.shape\n        \n        cuda = pc.is_cuda\n        final_grasp, final_grasp_stage1 = torch.Tensor(), torch.Tensor()\n        \n        loss_tuple, loss_tuple_stage2 = (None, None), (None, None)#设置两个loss\n\n        #在这里，获取到每个锚点的多个anchors（位置+姿态）\n        anchors = self._enumerate_anchors(center_pc[:,:,:3].view(-1,3).float())# [B*center_num, M, 7]\n        \n        #anchor_number = anchors.shape[1]#\n        #pc_group_xyz = pc_group[:,:,:,:6].clone().view(B*N_C,N_G,-1)\n\n        pc_group_more_xyz = pc_group_more[:,:,:,:6].clone().view(B*N_C,-1,6)\n        \n        feature_len = all_feature.shape[2]#获得每个点的特征长度\n        #变形\n        all_feature_new = all_feature.contiguous().view(-1, feature_len)#[B,A,FL] -> [B*A,FL]\n        \n        add = torch.arange(B).view(-1,1).repeat(1, N_C*N_G)\n        if pc_group_index.is_cuda:\n            add = add.cuda()\n\n        #[B,N_C,N_G]->[B,N_C*N_G]->[B*N_C*N_G]  因此需要加上长度为点云数A的步长\n        pc_group_index_new = (pc_group_index.long().view(B, N_C*N_G) + add * all_feature.shape[1]).view(-1)\n\n        #根据索引抽取每个包围球中各个点的点特征\n        pc_group_features = all_feature_new[pc_group_index_new].view(B, N_C, N_G, feature_len)\n        #变形[B,N_C,N_G,FL]->[B*N_C,N_G,FL]\n        pc_group_features = pc_group_features.view(-1, N_G, feature_len)#[gmask]#.detach()\n        \n        '''先把center_feature变换顺序[B*N_C,N_G,FL] -> [B*N_C,FL,N_G]再\n        输入网络，去抽取每个包围球中的特征，每个包围球都代表了一个center，需要回归出num_anchor个grasp bias      \n        pc_group_features:[B*N_C, N_G, feature_len]每个包围球中的点的特征\n        x_cls:                             [B*N_C, num_anchor]        对B*N_C个包围球中的每个anchor进行分类的结果\n        x_reg:                            [B*N_C, num_anchor, 8]    对B*N_C个包围球中的每个anchor进行位姿res+score回归的结果\n        mp_center_feature:[B*N_C, FL(128),1]                每个group的maxpool之后的特征向量，表征该group的全局特征\n        '''\n        x_cls, x_reg, mp_center_feature = self.extrat_feature_region(pc_group_features.permute(0,2,1), None)\n        \n        '''将残差与anchor结合，对比ground truth，计算GRN网络的Loss\n        next_grasp: [len(gmask), 8]预测的完整抓取向量(pose+score)\n        next_gt: [len(gmask), 8]真实的完整抓取向量(pose+score)\n        loss_tuple[] Loss组\n        correct_tuple :预测的准确率\n        gmask: gmask   [len(gmask),]      对比[B*center_num,]\n        '''\n        next_grasp, loss_tuple, correct_tuple, next_gt, tt_pre, gmask = self.compute_loss(x_reg, anchors, x_cls, ground_grasp)\n        \n        # print(\"gmask\",gmask)\n        keep_grasp_num_stage2 = [(torch.sum((gmask<(i+1)*N_C) & (gmask>=i*N_C))) for i in range(B)] \n        \n        select_grasp_class, select_grasp_score, select_grasp_class_stage2, final_mask, final_mask_sthre, keep_grasp_num_stage3, \\\n            keep_grasp_num_stage3_score, loss_refine_tuple, correct_refine_tuple, gt = None, None, None, None, None, None, None, None, None, None\n        #如果使用了refine网络的话\n        if self.is_training_refine:\n            select_grasp_class, select_grasp_score, select_grasp_class_stage2, final_mask, final_mask_sthre, loss_refine_tuple, \\\n                            correct_refine_tuple, gt = self.refine_forward(pc_group_more_xyz, pc_group_more_index, gmask, \\\n                            all_feature, mp_center_feature, next_grasp.detach(), gripper_params, next_gt)\n\n            if final_mask is not None:\n                keep_grasp_num_stage3       = [(torch.sum((final_mask<(i+1)*N_C) & (final_mask>=i*N_C))) for i in range(B)] \n                keep_grasp_num_stage3_score = [(torch.sum((final_mask_sthre<(i+1)*N_C) & (final_mask_sthre>=i*N_C))) for i in range(B)] \n            else:\n                keep_grasp_num_stage3       = [0 for i in range(B)] \n                keep_grasp_num_stage3_score = [0 for i in range(B)] \n\n        # print(\"!!!!!!!!!!!!!!!!!!!!\",B, N_C)\n        # print(keep_grasp_num_stage2)\n        return next_grasp.detach(), keep_grasp_num_stage2, gmask, loss_tuple, correct_tuple, next_gt, \\\n                select_grasp_class, select_grasp_score, select_grasp_class_stage2, keep_grasp_num_stage3, \\\n                keep_grasp_num_stage3_score, final_mask, final_mask_sthre, loss_refine_tuple, correct_refine_tuple, gt\n\ndef get_gripper_region_transform(group_points, group_index, grasp, region_num, gripper_params):\n    '''查看预测抓取姿态下，夹爪内部点云的数量，并返回满足条件的抓取的index\n      Return the transformed local points in the closing area of gripper.\n      Input: group_points: [B*center_num,group_num_more,6] 包围球内部点xyzrgb\n             group_index : [len(gmask),group_num_more] 包围球内部点在完整pc中的索引\n             grasp:        [len(gmask),7] 预测抓取向量\n             region_num:   the number of saved points in the closing area 夹爪内部点的最少数量\n      Return:    \n            gripper_pc : [len(gmask),region_num,6]  len(gmask)个抓取，夹爪闭合区域点的xyzrgb\n            gripper_pc_index: [len(gmask),region_num]  len(gmask)个抓取，夹爪闭合区域点相对于包围球内部点的索引\n            gripper_pc_index_inall:[len(gmask),region_num]  len(gmask)个抓取，夹爪闭合区域点相对于完整pc的索引\n            gripper_mask_index: [len(gripper_mask_index),] 内部点数大于指定数量的预测抓取的索引，len(gripper_mask_index)<=len(gmask)\n    '''\n    widths, height, depths = gripper_params\n    B, _ = grasp.shape #len(gmask)\n    center = grasp[:, 0:3].float()#预测中心点坐标 [len(gmask),3]\n    axis_y = grasp[:, 3:6].float()#预测r轴向量 [len(gmask),3]\n    angle = grasp[:, 6].float()#预测theta   [len(gmask),1]\n    cuda = center.is_cuda\n\n    cos_t, sin_t = torch.cos(angle), torch.sin(angle)\n    # R1 = torch.zeros((B, 3, 3))\n    # for i in range(B):\n    #     r = torch.tensor([[cos_t[i], 0, -sin_t[i]],[0, 1, 0],[sin_t[i], 0, cos_t[i]]]).view(1,3,3)\n    #     R1[i,:,:] = r\n    one, zero = torch.ones((B, 1), dtype=torch.float32), torch.zeros((B, 1), dtype=torch.float32)\n    if cuda:\n        one, zero = one.cuda(), zero.cuda()\n    R1 = torch.cat( (cos_t.view(B,1), zero, -sin_t.view(B,1), zero, one, zero, sin_t.view(B,1), \n                        zero, cos_t.view(B,1)), dim=1).view(B,3,3)\n    if cuda:\n        R1=R1.cuda()\n\n    #预测binormal单位化\n    norm_y = torch.norm(axis_y, dim=1).add_(1e-12)\n    axis_y = torch.div(axis_y, norm_y.view(-1,1))\n\n    if cuda:\n        axis_y[torch.nonzero(torch.eq(norm_y, 0))] = torch.tensor(([0,1,0]), dtype=torch.float).cuda()\n    else:\n        axis_y[torch.nonzero(torch.eq(norm_y, 0))] = torch.tensor(([0,1,0]), dtype=torch.float)\n    #找到在W:X-O-Y平面内的一个与W-Y轴垂直的向量，作为临时axis_x\n    axis_x = torch.cat((axis_y[:, 1].view(-1,1), -axis_y[:, 0].view(-1,1), zero), 1)\n    #预测approach单位化\n    norm_x = torch.norm(axis_x, dim=1).add_(1e-12)\n    axis_x = torch.div(axis_x, norm_x.view(-1,1))\n    if cuda:\n        axis_x[torch.nonzero(torch.eq(norm_x, 0))] = torch.tensor(([1,0,0]), dtype=torch.float).cuda()\n    else:\n        axis_x[torch.nonzero(torch.eq(norm_x, 0))] = torch.tensor(([1,0,0]), dtype=torch.float)\n    #叉乘得到预测minor_normal,并单位化\n    axis_z = torch.cross(axis_x, axis_y, dim=1)\n    norm_z = torch.norm(axis_z, dim=1)\n    axis_z = torch.div(axis_z, norm_z.view(-1,1))\n    #\n    if cuda:\n        axis_z[torch.nonzero(torch.eq(norm_z, 0))] = torch.tensor(([0,0,1]), dtype=torch.float).cuda()\n    else:\n        axis_z[torch.nonzero(torch.eq(norm_z, 0))] = torch.tensor(([0,0,1]), dtype=torch.float)\n    #构造临时预测抓取姿态矩阵[len(gmask),3,3]\n    matrix = torch.cat((axis_x.view(-1,3,1), axis_y.view(-1,3,1), axis_z.view(-1,3,1)), dim=2)\n    if cuda:\n        matrix = matrix.cuda()\n    #经过旋转得到预测的抓取姿态矩阵[len(gmask),3,3]\n    matrix = torch.bmm(matrix, R1)\n    \n    approach = matrix[:,:,0]\n    norm_x = torch.norm(approach, dim=1).add_(1e-12)\n    approach = torch.div(approach, norm_x.view(-1,1))\n\n    if cuda:\n        axis_y = axis_y.cuda()\n        group_points = group_points.cuda()\n        center = center.cuda()\n        approach[torch.nonzero(torch.eq(norm_x, 0))] = torch.tensor(([1,0,0]), dtype=torch.float).cuda()\n    else:\n        approach[torch.nonzero(torch.eq(norm_x, 0))] = torch.tensor(([1,0,0]), dtype=torch.float)\n\n    minor_normal = torch.cross(approach, axis_y, dim=1)\n\n    #求逆矩阵\n    matrix = torch.cat((approach.view(-1,3,1), axis_y.view(-1,3,1), minor_normal.view(-1,3,1)), dim=2).permute(0,2,1)\n    ## pcs_t: [B,group_num_more,3] 求得包围球内部点云坐标Gp \n    pcs_t = torch.bmm(matrix, (group_points[:,:,:3].float() - \\\n                        center.view(-1,1,3).repeat(1, group_points.shape[1], 1).float()).permute(0,2,1)).permute(0,2,1)\n\n    # torch.tensor [B,1]  or  float\n    #获取夹爪限制包围盒尺寸\n    x_limit = depths.float().view(-1,1)/2 if type(depths) is torch.Tensor else depths / 2 \n    z_limit = height/2 # float\n    # torch.tensor [B,1]  or  float\n    y_limit = widths.float().view(-1,1)/2 if type(widths) is torch.Tensor else widths / 2\n\n    #\n    gripper_pc = torch.full((B,region_num,group_points.shape[2]),-1)\n    #gripper_pc_formal = torch.full((B,region_num,group_points.shape[2]),-1)\n    gripper_pc_index       = torch.full((B,region_num),-1)\n    gripper_pc_index_inall = torch.full((B,region_num),-1)\n    gripper_mask = torch.zeros((B))\n    \n    x1 = pcs_t[:,:,0] > 0#在夹爪内部\n    x2 = pcs_t[:,:,0] < x_limit#小于夹爪深度\n    y1 = pcs_t[:,:,1] > -y_limit#\n    y2 = pcs_t[:,:,1] < y_limit\n    z1 = pcs_t[:,:,2] > -z_limit\n    z2 = pcs_t[:,:,2] < z_limit\n    \n    #\n    a = torch.cat((x1.view(B,-1,1), x2.view(B,-1,1), y1.view(B,-1,1), \\\n                    y2.view(B,-1,1), z1.view(B,-1,1), z2.view(B,-1,1)), dim=-1)\n    for i in range(B):\n        index = torch.nonzero(torch.sum(a[i], dim=-1) == 6).view(-1)#满足所有夹爪尺寸限制的点索引\n        if len(index) > region_num:#大于指定数量就裁切\n            #print(len(index))\n            index = index[np.random.choice(len(index),region_num,replace=False)]\n        elif len(index) > 5:#点数小于指定数量，大于5，就扩充一下\n            index = index[np.random.choice(len(index),region_num,replace=True)]\n\n        #从len(gmask)个抓取中，继续筛选出点数足够多的抓取，len(gripper_mask)<=len(gmask)\n        if len(index) > 5:##这里他们仅仅设置内部的点数大于5，说明回归出的抓取，内部的点数太少了\n            gripper_pc[i] = torch.cat((pcs_t[i,index], group_points[i,index,3:]),-1)\n            #gripper_pc_formal[i] = group_points[i,index,:]\n            gripper_pc_index[i]       = index\n            gripper_pc_index_inall[i] = group_index[i][index]\n            gripper_mask[i] = 1\n    \n    if cuda:\n        gripper_pc, gripper_mask, gripper_pc_index, gripper_pc_index_inall = gripper_pc.cuda(), gripper_mask.cuda(), \\\n                                                        gripper_pc_index.cuda(), gripper_pc_index_inall.cuda()#, gripper_pc_formal.cuda()\n    gripper_mask_index = torch.nonzero(gripper_mask==1).view(-1)\n    '''gripper_pc : [len(gmask),region_num,6]  len(gmask)个抓取，夹爪闭合区域点的xyzrgb\n    gripper_pc_index: [len(gmask),region_num]  len(gmask)个抓取，夹爪闭合区域点相对于包围球内部点的索引\n    gripper_pc_index_inall:[len(gmask),region_num]  len(gmask)个抓取，夹爪闭合区域点相对于完整pc的索引\n    gripper_mask_index: [len(gripper_mask_index),] 内部点数大于指定数量的预测抓取的索引\n    '''\n    return gripper_pc, gripper_pc_index, gripper_pc_index_inall, gripper_mask_index#, gripper_pc_formal\n\ndef _enumerate_templates():\n    '''枚举anchors的姿态，每个抓取点对应M个锚姿态\n      (仅仅是姿态，没有位置)\n      Enumerate all grasp anchors:\n      For one score center, we generate M anchors.\n\n      grasp configuration:(p, r, theta)\n      r -> (1,0,0),                   (sqrt(2)/2, 0, sqrt(2)/2),           (sqrt(2)/2, 0, -sqrt(2)/2),           \\\n           (sqrt(2)/2,sqrt(2)/2,0),   (sqrt(3)/3, sqrt(3)/3, sqrt(3)/3),   (sqrt(3)/3, sqrt(3)/3, -sqrt(3)/3),   \\\n           (0,1,0),                   (0, sqrt(2)/2, sqrt(2)/2),           (0, sqrt(2)/2, -sqrt(2)/2),           \\\n           (-sqrt(2)/2,sqrt(2)/2,0),  (-sqrt(3)/3, sqrt(3)/3, sqrt(3)/3),  (-sqrt(3)/3, sqrt(3)/3, -sqrt(3)/3),  \\\n           (-1,0,0),                  (-sqrt(2)/2, 0, sqrt(2)/2),          (-sqrt(2)/2, 0, -sqrt(2)/2),          \\\n           (-sqrt(2)/2,-sqrt(2)/2,0), (-sqrt(3)/3, -sqrt(3)/3, sqrt(3)/3), (-sqrt(3)/3, -sqrt(3)/3, -sqrt(3)/3), \\\n           (0,-1,0),                  (0, -sqrt(2)/2, sqrt(2)/2),          (0, -sqrt(2)/2, -sqrt(2)/2),          \\\n           (sqrt(2)/2,-sqrt(2)/2,0),  (sqrt(3)/3, -sqrt(3)/3, sqrt(3)/3),  (sqrt(3)/3, -sqrt(3)/3, -sqrt(3)/3)\n      theta -> {-pi/2, -pi/4, 0, pi/4, pi/2}\n    '''\n    sqrt2 = math.sqrt(2)/2\n    sqrt3 = math.sqrt(3)/3\n\n    t_r = torch.FloatTensor([[sqrt3, sqrt3, sqrt3],[sqrt3, sqrt3, -sqrt3],\n                                                    [sqrt3, -sqrt3, -sqrt3], [sqrt3, -sqrt3, sqrt3]]).view(1,4,1,3).repeat(1,1,1,1)#repeat(1,1,5,1)\n    #t_r = torch.FloatTensor([\n    #                    [sqrt3, sqrt3, sqrt3], [sqrt3, sqrt3, -sqrt3], \\\n    #                    [-sqrt3, sqrt3, -sqrt3], [-sqrt3, sqrt3, sqrt3], \\\n    #                    [-sqrt3, -sqrt3, sqrt3], [-sqrt3,-sqrt3, -sqrt3], \\\n    #                    [sqrt3, -sqrt3, -sqrt3], [sqrt3,-sqrt3, sqrt3]\\\n    #                    ]).view(1,8,1,3).repeat(1,1,1,1)#repeat(1,1,5,1)\n\n    #t_r = torch.FloatTensor([#[1.0,0,0], [-1.0,0,0], [0,1.0,0], [0,-1.0,0],\n    #                    [sqrt2, sqrt2, 0], [sqrt2, -sqrt2, 0]\n    #                    ]).view(1,2,1,3).repeat(1,1,1,1)#repeat(1,1,5,1)\n    #t_theta = torch.FloatTensor([-math.pi/4, 0, math.pi/4]).view(1,1,3,1).repeat(1,8,1,1)\n    t_theta = torch.FloatTensor([0]).view(1,1,1,1).repeat(1,4,1,1)#角度的anchors全都设置为0\n    tem = torch.cat([t_r, t_theta], dim=3).half()\n    return tem\n\ndef compute_cos_sim(a, b):\n    '''计算向量a，b夹角的cos值\n      input:\n         a :[N, 3]\n         b :[N, 3]\n      output:\n         sim :[N, 1]\n    '''\n    a_b = torch.sum(torch.mul(a, b), dim=1)#\n    epsilon = 1e-12\n    a2 = torch.add(torch.sum(torch.mul(a, a), dim=1), (epsilon))\n    b2 = torch.add(torch.sum(torch.mul(b, b), dim=1), (epsilon))\n    div_ab = torch.sqrt(torch.mul(a2, b2))\n    sim = torch.div(a_b, div_ab).mul_(-1).add_(1).view(-1,1)\n    '''\n    b_copy = -b\n    a_b_copy = torch.sum(torch.mul(a, b_copy), dim=1)\n    sim_copy = torch.div(a_b_copy, div_ab).mul_(-1).add_(1).view(-1,1)\n\n    sim = torch.min(sim, sim_copy)\n    '''\n    return sim\n    \n\nif __name__ == '__main__':\n    pass", "meta": {"hexsha": "61a55b8be58ec849f9d3859aa1dc9ee9e716f3f1", "size": 41548, "ext": "py", "lang": "Python", "max_stars_repo_path": "multi_model/gripper_region_network.py", "max_stars_repo_name": "Hymwgk/REGNet_for_3D_Grasping", "max_stars_repo_head_hexsha": "90d2aabeba32c6899b7b8bb8c1ce4ff73c227859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "multi_model/gripper_region_network.py", "max_issues_repo_name": "Hymwgk/REGNet_for_3D_Grasping", "max_issues_repo_head_hexsha": "90d2aabeba32c6899b7b8bb8c1ce4ff73c227859", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multi_model/gripper_region_network.py", "max_forks_repo_name": "Hymwgk/REGNet_for_3D_Grasping", "max_forks_repo_head_hexsha": "90d2aabeba32c6899b7b8bb8c1ce4ff73c227859", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.1904761905, "max_line_length": 229, "alphanum_fraction": 0.6122797728, "include": true, "reason": "import numpy", "num_tokens": 13436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808532, "lm_q2_score": 0.3276683073862188, "lm_q1q2_score": 0.17787908829250482}}
{"text": "import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport random\nimport numpy as np\n\nPAD, CLS = '[PAD]', '[CLS]'\nSEP = '[SEP]'\n\nclass Attention(nn.Module):\n    r\"\"\"\n    Applies an attention mechanism on the output features from the decoder.\n\n    .. math::\n            \\begin{array}{ll}\n            x = context*output \\\\\n            attn = exp(x_i) / sum_j exp(x_j) \\\\\n            output = \\tanh(w * (attn * context) + b * output)\n            \\end{array}\n\n    Args:\n        dim(int): The number of expected features in the output\n\n    Inputs: output, context\n        - **output** (batch, output_len, dimensions): tensor containing the output features from the decoder.\n        - **context** (batch, input_len, dimensions): tensor containing features of the encoded input sequence.\n\n    Outputs: output, attn\n        - **output** (batch, output_len, dimensions): tensor containing the attended output features from the decoder.\n        - **attn** (batch, output_len, input_len): tensor containing attention weights.\n\n    Attributes:\n        linear_out (torch.nn.Linear): applies a linear transformation to the incoming data: :math:`y = Ax + b`.\n        mask (torch.Tensor, optional): applies a :math:`-inf` to the indices specified in the `Tensor`.\n\n    Examples::\n\n         >>> attention = seq2seq.models.Attention(256)\n         >>> context = Variable(torch.randn(5, 3, 256))\n         >>> output = Variable(torch.randn(5, 5, 256))\n         >>> output, attn = attention(output, context)\n\n    \"\"\"\n    def __init__(self, dim):\n        super(Attention, self).__init__()\n        self.linear_out = nn.Linear(dim*2, dim)\n        self.mask = None\n\n    def set_mask(self, mask):\n        \"\"\"\n        Sets indices to be masked\n\n        Args:\n            mask (torch.Tensor): tensor containing indices to be masked\n        \"\"\"\n        self.mask = mask\n\n    def forward(self, output, context):\n        batch_size = output.size(0)\n        hidden_size = output.size(2)\n        input_size = context.size(1)\n        # (batch, out_len, dim) * (batch, in_len, dim) -> (batch, out_len, in_len)\n        attn = torch.bmm(output, context.transpose(1, 2))\n        if self.mask is not None:\n            attn.data.masked_fill_(self.mask, -float('inf'))\n        attn = F.softmax(attn.view(-1, input_size), dim=1).view(batch_size, -1, input_size)\n\n        # (batch, out_len, in_len) * (batch, in_len, dim) -> (batch, out_len, dim)\n        mix = torch.bmm(attn, context)\n\n        # concat -> (batch, out_len, 2*dim)\n        combined = torch.cat((mix, output), dim=2)\n        # output -> (batch, out_len, dim)\n        output = F.tanh(self.linear_out(combined.view(-1, 2 * hidden_size))).view(batch_size, -1, hidden_size)\n\n        return output, attn\n\n\nclass BaseRNN(nn.Module):\n    r\"\"\"\n    Applies a multi-layer RNN to an input sequence.\n    Note:\n        Do not use this class directly, use one of the sub classes.\n    Args:\n        vocab_size (int): size of the vocabulary\n        max_len (int): maximum allowed length for the sequence to be processed\n        hidden_size (int): number of features in the hidden state `h`\n        input_dropout_p (float): dropout probability for the input sequence\n        dropout_p (float): dropout probability for the output sequence\n        n_layers (int): number of recurrent layers\n        rnn_cell (str): type of RNN cell (Eg. 'LSTM' , 'GRU')\n\n    Inputs: ``*args``, ``**kwargs``\n        - ``*args``: variable length argument list.\n        - ``**kwargs``: arbitrary keyword arguments.\n\n    Attributes:\n        SYM_MASK: masking symbol\n        SYM_EOS: end-of-sequence symbol\n    \"\"\"\n    SYM_MASK = \"MASK\"\n    SYM_EOS = \"EOS\"\n\n    def __init__(self, vocab_size, max_len, hidden_size, input_dropout_p, dropout_p, n_layers, rnn_cell):\n        super(BaseRNN, self).__init__()\n        self.vocab_size = vocab_size\n        self.max_len = max_len\n        self.hidden_size = hidden_size\n        self.n_layers = n_layers\n        self.input_dropout_p = input_dropout_p\n        self.input_dropout = nn.Dropout(p=input_dropout_p)\n        if rnn_cell.lower() == 'lstm':\n            self.rnn_cell = nn.LSTM\n        elif rnn_cell.lower() == 'gru':\n            self.rnn_cell = nn.GRU\n        else:\n            raise ValueError(\"Unsupported RNN Cell: {0}\".format(rnn_cell))\n\n        self.dropout_p = dropout_p\n\n    def forward(self, *args, **kwargs):\n        raise NotImplementedError()\n\n\nclass DecoderRNN(BaseRNN):\n    r\"\"\"\n    Provides functionality for decoding in a seq2seq framework, with an option for attention.\n\n    Args:\n        vocab_size (int): size of the vocabulary\n        max_len (int): a maximum allowed length for the sequence to be processed\n        hidden_size (int): the number of features in the hidden state `h`\n        sos_id (int): index of the start of sentence symbol\n        eos_id (int): index of the end of sentence symbol\n        n_layers (int, optional): number of recurrent layers (default: 1)\n        rnn_cell (str, optional): type of RNN cell (default: gru)\n        bidirectional (bool, optional): if the encoder is bidirectional (default False)\n        input_dropout_p (float, optional): dropout probability for the input sequence (default: 0)\n        dropout_p (float, optional): dropout probability for the output sequence (default: 0)\n        use_attention(bool, optional): flag indication whether to use attention mechanism or not (default: false)\n\n    Attributes:\n        KEY_ATTN_SCORE (str): key used to indicate attention weights in `ret_dict`\n        KEY_LENGTH (str): key used to indicate a list representing lengths of output sequences in `ret_dict`\n        KEY_SEQUENCE (str): key used to indicate a list of sequences in `ret_dict`\n\n    Inputs: inputs, encoder_hidden, encoder_outputs, function, teacher_forcing_ratio\n        - **inputs** (batch, seq_len, input_size): list of sequences, whose length is the batch size and within which\n          each sequence is a list of token IDs.  It is used for teacher forcing when provided. (default `None`)\n        - **encoder_hidden** (num_layers * num_directions, batch_size, hidden_size): tensor containing the features in the\n          hidden state `h` of encoder. Used as the initial hidden state of the decoder. (default `None`)\n        - **encoder_outputs** (batch, seq_len, hidden_size): tensor with containing the outputs of the encoder.\n          Used for attention mechanism (default is `None`).\n        - **function** (torch.nn.Module): A function used to generate symbols from RNN hidden state\n          (default is `torch.nn.functional.log_softmax`).\n        - **teacher_forcing_ratio** (float): The probability that teacher forcing will be used. A random number is\n          drawn uniformly from 0-1 for every decoding token, and if the sample is smaller than the given value,\n          teacher forcing would be used (default is 0).\n\n    Outputs: decoder_outputs, decoder_hidden, ret_dict\n        - **decoder_outputs** (seq_len, batch, vocab_size): list of tensors with size (batch_size, vocab_size) containing\n          the outputs of the decoding function.\n        - **decoder_hidden** (num_layers * num_directions, batch, hidden_size): tensor containing the last hidden\n          state of the decoder.\n        - **ret_dict**: dictionary containing additional information as follows {*KEY_LENGTH* : list of integers\n          representing lengths of output sequences, *KEY_SEQUENCE* : list of sequences, where each sequence is a list of\n          predicted token IDs }.\n    \"\"\"\n\n    KEY_ATTN_SCORE = 'attention_score'\n    KEY_LENGTH = 'length'\n    KEY_SEQUENCE = 'sequence'\n\n    def __init__(self, vocab_size, max_len, hidden_size,\n                 sos_id, eos_id,\n                 n_layers=1, rnn_cell='gru', bidirectional=False,\n                 input_dropout_p=0, dropout_p=0, use_attention=False):\n        super(DecoderRNN, self).__init__(vocab_size, max_len, hidden_size,\n                                         input_dropout_p, dropout_p,\n                                         n_layers, rnn_cell)\n\n        self.bidirectional_encoder = bidirectional\n        self.rnn = self.rnn_cell(hidden_size, hidden_size, n_layers, batch_first=True, dropout=dropout_p)\n        self.hidden_size = hidden_size\n        self.output_size = vocab_size\n        self.max_length = max_len\n        self.use_attention = use_attention\n        self.eos_id = eos_id\n        self.sos_id = sos_id\n\n        self.init_input = None\n\n        self.embedding = nn.Embedding(self.output_size, self.hidden_size)\n        if use_attention:\n            self.attention = Attention(self.hidden_size)\n\n        self.out = nn.Linear(self.hidden_size, self.output_size)\n        self.hidden_change = nn.Linear(768, self.hidden_size)\n\n    def forward_step(self, input_var, hidden, encoder_outputs, function):\n        batch_size = input_var.size(0)\n        output_size = input_var.size(1)\n        embedded = self.embedding(input_var)\n        embedded = self.input_dropout(embedded)\n\n        output, hidden = self.rnn(embedded, hidden)\n\n        attn = None\n        if self.use_attention:\n            output, attn = self.attention(output, encoder_outputs)\n\n        predicted_softmax = function(self.out(output.contiguous().view(-1, self.hidden_size)), dim=1).view(batch_size,\n                                                                                                           output_size,\n                                                                                                           -1)\n        return predicted_softmax, hidden, attn\n\n    def forward(self, inputs=None, encoder_hidden=None, encoder_outputs=None,\n                function=F.log_softmax, teacher_forcing_ratio=0):\n        ret_dict = dict()\n        if self.use_attention:\n            ret_dict[DecoderRNN.KEY_ATTN_SCORE] = list()\n\n        inputs, batch_size, max_length = self._validate_args(inputs, encoder_hidden, encoder_outputs,\n                                                             function, teacher_forcing_ratio)\n        decoder_hidden = self._init_state(encoder_hidden)\n\n        use_teacher_forcing = True if random.random() < teacher_forcing_ratio else False\n\n        decoder_outputs = []\n        sequence_symbols = []\n        lengths = np.array([max_length] * batch_size)\n\n        def decode(step, step_output, step_attn):\n            decoder_outputs.append(step_output)\n            if self.use_attention:\n                ret_dict[DecoderRNN.KEY_ATTN_SCORE].append(step_attn)\n            symbols = decoder_outputs[-1].topk(1)[1]\n            sequence_symbols.append(symbols)\n\n            eos_batches = symbols.data.eq(self.eos_id)\n            if eos_batches.dim() > 0:\n                eos_batches = eos_batches.cpu().view(-1).numpy()\n                update_idx = ((lengths > step) & eos_batches) != 0\n                lengths[update_idx] = len(sequence_symbols)\n            return symbols\n\n        # Manual unrolling is used to support random teacher forcing.\n        # If teacher_forcing_ratio is True or False instead of a probability, the unrolling can be done in graph\n        if use_teacher_forcing:\n            decoder_input = inputs[:, :-1]\n            decoder_output, decoder_hidden, attn = self.forward_step(decoder_input, decoder_hidden, encoder_outputs,\n                                                                     function=function)\n\n            for di in range(decoder_output.size(1)):\n                step_output = decoder_output[:, di, :]\n                if attn is not None:\n                    step_attn = attn[:, di, :]\n                else:\n                    step_attn = None\n                decode(di, step_output, step_attn)\n        else:\n            decoder_input = inputs[:, 0].unsqueeze(1)\n            for di in range(max_length):\n                decoder_output, decoder_hidden, step_attn = self.forward_step(decoder_input, decoder_hidden,\n                                                                              encoder_outputs,\n                                                                              function=function)\n                step_output = decoder_output.squeeze(1)\n                symbols = decode(di, step_output, step_attn)\n                decoder_input = symbols\n\n        ret_dict[DecoderRNN.KEY_SEQUENCE] = sequence_symbols\n        ret_dict[DecoderRNN.KEY_LENGTH] = lengths.tolist()\n\n        return decoder_outputs, decoder_hidden, ret_dict\n\n    def _init_state(self, encoder_hidden):\n        \"\"\" Initialize the encoder hidden state. \"\"\"\n        encoder_hidden = torch.tanh(self.hidden_change(encoder_hidden)).unsqueeze(dim=0)\n        if encoder_hidden is None:\n            return None\n        if isinstance(encoder_hidden, tuple):\n            encoder_hidden = tuple([self._cat_directions(h) for h in encoder_hidden])\n        else:\n            encoder_hidden = self._cat_directions(encoder_hidden)\n        return encoder_hidden\n\n    def _cat_directions(self, h):\n        \"\"\" If the encoder is bidirectional, do the following transformation.\n            (#directions * #layers, #batch, hidden_size) -> (#layers, #batch, #directions * hidden_size)\n        \"\"\"\n        if self.bidirectional_encoder:\n            h = torch.cat([h[0:h.size(0):2], h[1:h.size(0):2]], 2)\n        return h\n\n    def _validate_args(self, inputs, encoder_hidden, encoder_outputs, function, teacher_forcing_ratio):\n        if self.use_attention:\n            if encoder_outputs is None:\n                raise ValueError(\"Argument encoder_outputs cannot be None when attention is used.\")\n\n        # inference batch size\n        if inputs is None and encoder_hidden is None:\n            batch_size = 1\n        else:\n            if inputs is not None:\n                batch_size = inputs.size(0)\n            else:\n                if self.rnn_cell is nn.LSTM:\n                    batch_size = encoder_hidden[0].size(0)\n                elif self.rnn_cell is nn.GRU:\n                    batch_size = encoder_hidden.size(0)\n\n        # set default input and max decoding length\n        if inputs is None:\n            if teacher_forcing_ratio > 0:\n                raise ValueError(\"Teacher forcing has to be disabled (set 0) when no inputs is provided.\")\n            inputs = torch.LongTensor([self.sos_id] * batch_size).view(batch_size, 1)\n            if torch.cuda.is_available():\n                inputs = inputs.cuda()\n            max_length = self.max_length\n        else:\n            max_length = inputs.size(1) - 1  # minus the start of sequence symbol\n\n        return inputs, batch_size, max_length\n\n\nclass Seq2seq(nn.Module):\n    \"\"\" Standard sequence-to-sequence architecture with configurable encoder\n    and decoder.\n\n    Args:\n        encoder (EncoderRNN): object of EncoderRNN\n        decoder (DecoderRNN): object of DecoderRNN\n        decode_function (func, optional): function to generate symbols from output hidden states (default: F.log_softmax)\n\n    Inputs: input_variable, input_lengths, target_variable, teacher_forcing_ratio\n        - **input_variable** (list, option): list of sequences, whose length is the batch size and within which\n          each sequence is a list of token IDs. This information is forwarded to the encoder.\n        - **input_lengths** (list of int, optional): A list that contains the lengths of sequences\n            in the mini-batch, it must be provided when using variable length RNN (default: `None`)\n        - **target_variable** (list, optional): list of sequences, whose length is the batch size and within which\n          each sequence is a list of token IDs. This information is forwarded to the decoder.\n        - **teacher_forcing_ratio** (int, optional): The probability that teacher forcing will be used. A random number\n          is drawn uniformly from 0-1 for every decoding token, and if the sample is smaller than the given value,\n          teacher forcing would be used (default is 0)\n\n    Outputs: decoder_outputs, decoder_hidden, ret_dict\n        - **decoder_outputs** (batch): batch-length list of tensors with size (max_length, hidden_size) containing the\n          outputs of the decoder.\n        - **decoder_hidden** (num_layers * num_directions, batch, hidden_size): tensor containing the last hidden\n          state of the decoder.\n        - **ret_dict**: dictionary containing additional information as follows {*KEY_LENGTH* : list of integers\n          representing lengths of output sequences, *KEY_SEQUENCE* : list of sequences, where each sequence is a list of\n          predicted token IDs, *KEY_INPUT* : target outputs if provided for decoding, *KEY_ATTN_SCORE* : list of\n          sequences, where each list is of attention weights }.\n\n    \"\"\"\n\n    def __init__(self, encoder, decoder, decode_function=F.log_softmax):\n        super(Seq2seq, self).__init__()\n        self.encoder = encoder\n        self.decoder = decoder\n        self.decode_function = decode_function\n\n    def flatten_parameters(self):\n        self.encoder.rnn.flatten_parameters()\n        self.decoder.rnn.flatten_parameters()\n\n    def forward(self, batch_src, batch_tar=None,\n                teacher_forcing_ratio=0):\n\n        encoder_outputs, encoder_hidden = self.encoder(batch_src)\n\n\n        target_variable = batch_tar\n        result = self.decoder(inputs=target_variable,\n                              encoder_hidden=encoder_hidden,\n                              # encoder_outputs=combined_embeddings,\n                              encoder_outputs = encoder_outputs,\n                              function=self.decode_function,\n                              teacher_forcing_ratio=teacher_forcing_ratio)\n        return result\n", "meta": {"hexsha": "962c8dcb6fcdad2f4e488ba7368410b0f00d2975", "size": 17608, "ext": "py", "lang": "Python", "max_stars_repo_path": "dcmn_seq2seq/Seq2seq.py", "max_stars_repo_name": "cscyuge/medlane", "max_stars_repo_head_hexsha": "f830cfdb48dac11e447e47cca3f72c106e0e9fe6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dcmn_seq2seq/Seq2seq.py", "max_issues_repo_name": "cscyuge/medlane", "max_issues_repo_head_hexsha": "f830cfdb48dac11e447e47cca3f72c106e0e9fe6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dcmn_seq2seq/Seq2seq.py", "max_forks_repo_name": "cscyuge/medlane", "max_forks_repo_head_hexsha": "f830cfdb48dac11e447e47cca3f72c106e0e9fe6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-28T18:02:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T18:02:14.000Z", "avg_line_length": 45.9738903394, "max_line_length": 122, "alphanum_fraction": 0.6281803726, "include": true, "reason": "import numpy", "num_tokens": 3747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.32766830082071396, "lm_q1q2_score": 0.17787908472833341}}
{"text": "__author__ = 'Jiashun'\r\nimport re\r\nimport numpy as np\r\nfrom collections import Counter\r\nfrom math import ceil\r\nfrom math import floor\r\n\r\n# compare single base\r\ndef SingleBaseCompare(seq1,seq2,i,j):\r\n    if seq1[i] == seq2[j]:\r\n        return 2\r\n    else:\r\n        return -1\r\n    \r\n# Smith–Waterman Alignment \r\ndef SMalignment(seq1, seq2):\r\n    m = len(seq1)\r\n    n = len(seq2)\r\n    g = -3\r\n    matrix = []\r\n    for i in range(0, m):\r\n        tmp = []\r\n        for j in range(0, n):\r\n            tmp.append(0)\r\n        matrix.append(tmp)\r\n    for sii in range(0, m):\r\n        matrix[sii][0] = sii*g\r\n    for sjj in range(0, n):\r\n        matrix[0][sjj] = sjj*g\r\n    for siii in range(1, m):\r\n        for sjjj in range(1, n):\r\n            matrix[siii][sjjj] = max(matrix[siii-1][sjjj] + g, matrix[siii - 1][sjjj - 1] + SingleBaseCompare(seq1,seq2,siii, sjjj), matrix[siii][sjjj-1] + g)\r\n    sequ1 = [seq1[m-1]]\r\n    sequ2 = [seq2[n-1]]\r\n    while m > 1 and n > 1:\r\n        if max(matrix[m-1][n-2], matrix[m-2][n-2], matrix[m-2][n-1]) == matrix[m-2][n-2]:\r\n            m -= 1\r\n            n -= 1\r\n            sequ1.append(seq1[m-1])\r\n            sequ2.append(seq2[n-1])\r\n        elif max(matrix[m-1][n-2], matrix[m-2][n-2], matrix[m-2][n-1]) == matrix[m-1][n-2]:\r\n            n -= 1\r\n            sequ1.append('-')\r\n            sequ2.append(seq2[n-1])\r\n        else:\r\n            m -= 1\r\n            sequ1.append(seq1[m-1])\r\n            sequ2.append('-')\r\n    sequ1.reverse()\r\n    sequ2.reverse()\r\n    align_seq1 = ''.join(sequ1)\r\n    align_seq2 = ''.join(sequ2)\r\n    align_score = 0.\r\n    for k in range(0, len(align_seq1)):\r\n        if align_seq1[k] == align_seq2[k]:\r\n            align_score += 1\r\n    align_score = float(align_score)/len(align_seq1)\r\n    return align_seq1, align_seq2, align_score\r\n\r\n# Display BlAST result\r\ndef Display(seque1, seque2):\r\n    le = 60\r\n    while len(seque1)-le >= 0:\r\n        print('sequence1: ',end='')\r\n        for a in list(seque1)[le-40:le]:\r\n            print(a,end='')\r\n        print(\"\\n\")\r\n        print('           ',end='')\r\n        for k in range(le-40, le):\r\n            if seque1[k] == seque2[k]:\r\n                print('|',end='')\r\n            else:\r\n                print(' ',end='')\r\n        print(\"\\n\")\r\n        print('sequence2: ',end='')\r\n        for b in list(seque2)[le-40:le]:\r\n            print(b,end='')\r\n        print(\"\\n\")\r\n        le += 40\r\n    if len(seque1) > le-40:\r\n        print('sequence1: ',end='')\r\n        for a in list(seque1)[le-40:len(seque1)]:\r\n            print(a,end='')\r\n        print(\"\\n\")\r\n        print('           ',end='')\r\n        for k in range(le-40, len(seque1)):\r\n            if seque1[k] == seque2[k]:\r\n                print('|',end='')\r\n            else:\r\n                print(' ',end='')\r\n        print(\"\\n\")\r\n        print('sequence2: ',end='')\r\n        for b in list(seque2)[le-40:len(seque2)]:\r\n            print(b,end='')\r\n        print(\"\\n\")\r\n\r\n# transform base to numeric value\r\ndef WordToNum(word):\r\n    tmp = []\r\n    trans = {'A':1,'C':2,'G':3,'T':4}\r\n    for w in word:\r\n        tmp.append(trans[w])\r\n    return tmp\r\n\r\n# transform word with 11 bases to its index\r\ndef WordToIndex(word,word_len):\r\n    tmp = 0\r\n    word_num = WordToNum(word)\r\n    for i,v in enumerate(word_num):\r\n        tmp += (v-1)*4**(word_len-i)\r\n    return tmp   \r\n\r\n# Get word's postion in genome from library\r\ndef GetWordPos(word):\r\n    assert len(word)== 11\r\n    seek_index = WordToIndex(word,11-1)\r\n    positions = []\r\n    for chr_name in chr_names:\r\n        chr_seq = open('/home/jxiaoae/class/blast/chromosome_{}_library.txt'.format(chr_name),'r')\r\n        seeks = np.load(\"chromosome_{}_library_seeks.npy\".format(chr_name))\r\n        chr_seq.seek(seeks[seek_index,0])\r\n        position = chr_seq.read(seeks[seek_index,1])\r\n        try:\r\n            positions.append(list(map(int, position[:-1].split(\",\"))))\r\n        except:\r\n            positions.append([])\r\n    return positions\r\n\r\n# Extract subsequence from GRCh37 file\r\ndef ExtractSeq(chr_index,pos,length):\r\n    pos = pos+floor(pos/60)\r\n    hg19.seek(chrom_seek_index[chr_index,1]+pos-1)\r\n    return re.sub(r'\\n', '', hg19.read(length))\r\n\r\n# main blast function\r\ndef Blast(query_seq):\r\n    i = 0\r\n    query_words = []\r\n    query_seq_length = len(query_seq)\r\n    words_length = query_seq_length-11+1\r\n    while i < words_length:\r\n        query_words.append(query_seq[i:i+11])\r\n        i += 1\r\n    words_positions = []\r\n    for word in query_words:\r\n        words_positions.append(GetWordPos(word))\r\n    for chr_index in range(24):\r\n        for word_index in range(words_length):\r\n            for pos in range(len(words_positions[word_index][chr_index])):\r\n                words_positions[word_index][chr_index][pos] += words_length - word_index - 1\r\n        \r\n        words_positions_corrects = []\r\n        for word_index in range(words_length):\r\n            words_positions_corrects += words_positions[word_index][chr_index]\r\n        \r\n        words_positions_corrects_count = Counter(words_positions_corrects)\r\n        finded_postions = []\r\n        for count_ in words_positions_corrects_count:\r\n            # we can select the bigger threshold of words_positions_corrects_count[count_] just \r\n            # like we select the highly similar sequence in NCBI BLAST\r\n            if words_positions_corrects_count[count_] > 5:\r\n                finded_postions.append(count_)\r\n        if finded_postions:\r\n            for finded_postion in finded_postions:\r\n                candidate_seq_pos = finded_postion - query_seq_length + 11 - 5\r\n                candidate_seq_length = query_seq_length + 11\r\n                candidate_sequence = ExtractSeq(chr_index,candidate_seq_pos,candidate_seq_length)\r\n                i_start_indexs = []\r\n                for i_start in range(15):\r\n                    _,_,score = SMalignment(candidate_sequence[i_start:],query_seq)\r\n                    i_start_indexs.append(score)\r\n                i_start = np.array(i_start_indexs).argmax()\r\n                i_end_indexs = []\r\n                for i_end in range(1,16):\r\n                    _,_,score = SMalignment(candidate_sequence[:-i_end],query_seq)\r\n                    i_end_indexs.append(score)\r\n                i_end = np.array(i_end_indexs).argmax()+1\r\n                candidate_sequence = candidate_sequence[i_start:-i_end]\r\n                align_seq1,align_seq2,align_score = SMalignment(candidate_sequence,query_seq)\r\n                if align_score>0.7:\r\n                    print(\"find in chromosome \"+chr_names[chr_index]+\": \"+str(candidate_seq_pos+i_start)+' ---> '+str(candidate_seq_pos+i_start+len(candidate_sequence)-1)+\", align score: \"+str(align_score))\r\n                    Display(align_seq1, align_seq2)\r\n    return None\r\n\r\nif __name__ == \"__main__\":\r\n    chr_names = np.load('/home/jxiaoae/class/blast/GRCh37_chr_names.npy')\r\n    chrom_seek_index = np.load('/home/jxiaoae/class/blast/GRCh37_chrom_seek_index.npy')\r\n    hg19 = open(\"/home/share/GRCh37/human_g1k_v37.fasta\")\r\n    query_sequence = 'GTATCGGAACTTCCAACTTGTAGGCAAAATAGATATGCTTCATATTCTTAAAAACCACAAGAAA'\r\n    Blast(query_sequence)", "meta": {"hexsha": "0165aae531dce55f708402efd13e32e95e104aac", "size": 7120, "ext": "py", "lang": "Python", "max_stars_repo_path": "blast.py", "max_stars_repo_name": "JiaShun-Xiao/fast-BLAST-coded-by-python-", "max_stars_repo_head_hexsha": "3b2b78f8845804736b04b13bbe03efd74dac0534", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 42, "max_stars_repo_stars_event_min_datetime": "2019-05-20T02:14:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T13:48:40.000Z", "max_issues_repo_path": "blast.py", "max_issues_repo_name": "JiaShun-Xiao/fast-BLAST-coded-by-python-", "max_issues_repo_head_hexsha": "3b2b78f8845804736b04b13bbe03efd74dac0534", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-01T06:07:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-01T06:07:13.000Z", "max_forks_repo_path": "blast.py", "max_forks_repo_name": "JiaShun-Xiao/fast-BLAST-coded-by-python-", "max_forks_repo_head_hexsha": "3b2b78f8845804736b04b13bbe03efd74dac0534", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2019-06-05T13:50:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-08T17:22:44.000Z", "avg_line_length": 37.4736842105, "max_line_length": 207, "alphanum_fraction": 0.5650280899, "include": true, "reason": "import numpy", "num_tokens": 1875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.2658804730998169, "lm_q1q2_score": 0.17784220007457247}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nModule to simulate OH sky lines spectra.\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\n\nfrom .constants import Constants as cs\nfrom .spectra import Spectra\nfrom .simSpec import SpecUtil as spec_util\n\n_PARENT_DIR = Path(__file__).resolve().parents[1]\n\n\nclass SkyLines(object):\n    \"\"\"\n    Contains everything related to OH sky lines.\n    \"\"\"\n\n    MAX_V = 13  #fa maximum vibrational quantum level\n\n    def __init__(self):\n        \"\"\"\n        Initiate `SkyLines`. Load data containing line wavelengths, transition\n        levels, Einstein's A, etc. The data is from Brooke et al. (2016).\n        \"\"\"\n        self.temperature_rot = 190.\n        self.temperature_vib = 9000.\n\n        self._wavelength_start = 0.\n        self._wavelength_end = 0.\n        self._wavelengths = []\n\n        self._qn_vs = pd.DataFrame(columns=['v', 'Q', 'N'],\n                                   index=np.arange(self.MAX_V+1))\n\n        self.line_list = pd.DataFrame()  # stores line data\n        self._line_list_v = []  # list of lines (dataframes) indexed with v\n        self._lines_in_range = pd.DataFrame()  # lines in wavelength range\n\n        self.load_data()  # loads data into `self.line_list`\n\n    def load_data(self):\n        \"\"\"\n        Load necessary data files.\n        \"\"\"\n        data_file_path = _PARENT_DIR / 'data' / 'OH-XX-Line_list.txt'\n        self.line_list = pd.read_csv(data_file_path,\n                                     delim_whitespace=True, skiprows=33)\n\n        for v in range(self.MAX_V+1):\n            # subset of line_list with v' = v\n            v_lines = self.line_list[\n                self.line_list[\"v'\"].values == v\n                ][[\"J'\", \"F'\", \"p'\", \"E''\", 'Calculated']].drop_duplicates(\n            ).reset_index()\n            self._line_list_v.append(v_lines)\n\n    def reset_temperatures(self, temperature_rot=190, temperature_vib=9000):\n        \"\"\"\n        Reset the temperatures without reloading data.\n        :param temperature_rot: Rotational temperature.\n        :param temperature_vib: Vibrational temperature.\n        \"\"\"\n        self.temperature_rot = temperature_rot\n        self.temperature_vib = temperature_vib\n\n        # Resetting all the values in the dataframe, but keeping the same\n        # dataframe object for efficient memory allocation.\n        self._qn_vs.loc[:] = np.nan\n        self._lines_in_range.loc[:, ('Q_v', 'N_v', 'Intensity')] = np.nan\n\n    def setup_wavelengths(self, start=None, end=None, resolution=0.01,\n                          wavelengths=None):\n        \"\"\"\n        :param start: Beginning wavelength in nm.\n        :param end: Ending wavelength in nm.\n        :param resolution: Resolution element in nm.\n        :param wavelengths: Wavelengths for computing the sky spectra. If\n        provided, `start` and `end` are not needed.\n        \"\"\"\n        if wavelengths is None:\n            assert start is not None and end is not None, 'You need to ' \\\n                                                          'provide either ' \\\n                                                          'the wavelengths ' \\\n                                                          'or the range.'\n            self._wavelength_start = start\n            self._wavelength_end = end\n            self._wavelengths = np.arange(start, end+resolution/2., resolution)\n        else:\n            self._wavelengths = wavelengths\n            self._wavelength_start = wavelengths[0]\n            self._wavelength_end = wavelengths[-1]\n\n        k_start = 1e7 / spec_util.air_to_vacuum_wavelength(\n            self._wavelength_end)  # in /cm\n        k_end = 1e7 / spec_util.air_to_vacuum_wavelength(\n            self._wavelength_start)  # in /cm\n\n        self._lines_in_range = self.line_list[\n            self.line_list[\"Calculated\"].between(k_start, k_end)]\n        self._lines_in_range = self._lines_in_range.assign(\n            Q_v=np.nan,\n            N_v=np.nan,\n            Intensity=np.nan)\n\n    def get_sky_spectra(self, temperature_rot=None, temperature_vib=None):\n        \"\"\"\n        Generate the sky spectra between start and end wavelengths.\n        :param temperature_rot: Rotational temperature, in K.\n        :param temperature_vib: Vibrational temperature, in K.\n        \"\"\"\n        if temperature_rot is not None and temperature_vib is not None:\n            self.reset_temperatures(temperature_rot=temperature_rot,\n                                    temperature_vib=temperature_vib)\n        elif temperature_rot is not None:\n            self.reset_temperatures(temperature_rot=temperature_rot,\n                                    temperature_vib=self.temperature_vib)\n        elif temperature_vib is not None:\n            self.reset_temperatures(temperature_rot=self.temperature_rot,\n                                    temperature_vib=temperature_vib)\n\n        flux = np.zeros_like(self._wavelengths)\n\n        intensities = self._get_line_intensities_in_range()\n        line_wavelengths = spec_util.vacuum_to_air_wavelength_mathar(\n            1e7/self._lines_in_range['Calculated'].values)  # nm\n\n        pixel_size = self._wavelengths[1] - self._wavelengths[0]\n        for line_wavelength, intensity in zip(line_wavelengths, intensities):\n            idx = int((line_wavelength - self._wavelength_start)/pixel_size)\n            if 0 <= idx < len(flux):\n                flux[idx] += intensity\n\n        return Spectra(self._wavelengths, flux, wavelength_unit='nm')\n\n    def _get_qn_v(self, v):\n        \"\"\"\n        Compute partition function Q_v (T_rot) and N_v (T_vib). Q_v (T_rot) is\n        computed using equation (39) from Mies (1974). Simply, N_v (T_vib) =\n        Q_v (T_vib).\n        :param v: Vibrational quantum number.\n        :type v: int\n        \"\"\"\n        if v in self._qn_vs.v.values:\n            idx = np.where(self._qn_vs.v.values == v)[0]\n            return (self._qn_vs.Q.values[idx],\n                    self._qn_vs.N.values[idx])\n        else:\n            v_lines = self._line_list_v[v]\n\n            wave_n = v_lines[\"E''\"].values + v_lines['Calculated'].values\n            j = v_lines[\"J'\"].values\n\n            q = np.sum((4*j+2) * np.exp(-self._get_beta(wave_n,\n                                                        self.temperature_rot)\n                                        ))\n            n = np.sum((4*j+2) * np.exp(-self._get_beta(wave_n,\n                                                        self.temperature_vib)\n                                        ))\n\n            self._qn_vs.loc[v] = [v, q, n]\n\n            return q, n\n\n    @staticmethod\n    def _get_beta(wavenumber, temperature):\n        \"\"\"\n        Compute $\\beta(E)$ from wavenumber k (cm^-1).\n        :param wavenumber: Wavenumber in cm^-1.\n        :param temperature: Temperature in K.\n        \"\"\"\n        return cs.h * cs.c * wavenumber / cs.k_b / temperature\n\n    @staticmethod\n    def _wavenumber2energy(wavenumber):\n        \"\"\"\n        Convert wavenumber to energy.\n        :param wavenumber: Wavenumber in cm^-1.\n        :return:\n        \"\"\"\n        return cs.h * cs.c * wavenumber\n\n    def _populate_qn_in_line_list(self):\n        \"\"\"\n        Fills up [Q_v, N_v] columns of  `SkyLines._lines_in_range` with\n        calculated values.\n        :return:\n        :rtype:\n        \"\"\"\n        for v in range(self.MAX_V+1):\n            q_v, n_v = self._get_qn_v(v)\n            row_slice = self._lines_in_range[\"v'\"] == v\n            self._lines_in_range.loc[row_slice,\n                                     'Q_v'] = q_v\n            self._lines_in_range.loc[row_slice,\n                                     'N_v'] = n_v\n\n    def _get_line_intensities_in_range(self):\n        \"\"\"\n        Compute line intensities for lines in `self._lines_in_range`.\n        Computed intensity is unit of ergs/cm^3/s. Equation (41) from Mies\n        (1974) is used to derive the intensities in photon number, then the\n        energy of the line is multiplied to get the intensities in unit of\n        energy.\n        :param index:\n        \"\"\"\n        if np.isnan(self._lines_in_range['Intensity'].values).any():\n            self._populate_qn_in_line_list()\n\n            v = self._lines_in_range[\"v'\"].values\n            wavenumber = self._lines_in_range['Calculated'].values\n            einstein_a = self._lines_in_range['A'].values\n            j = self._lines_in_range[\"J'\"].values\n            energy_lower = self._lines_in_range[\"E''\"].values\n            q_v = self._lines_in_range['Q_v'].values\n            n_v = self._lines_in_range['N_v'].values\n\n            intensity = self._wavenumber2energy(wavenumber) * n_v \\\n                        * einstein_a * (4*j+2) / q_v * np.exp(\n                -self._get_beta(energy_lower+wavenumber, self.temperature_rot))\n\n            self._lines_in_range.loc[:, 'Intensity'] = pd.Series(intensity,\n                                            index=self._lines_in_range.index)\n\n            return intensity\n        else:\n            return self._lines_in_range['Intensity'].values\n", "meta": {"hexsha": "c4ebb849b98b3b786981cbd3b1f61ecce630ce1a", "size": 8992, "ext": "py", "lang": "Python", "max_stars_repo_path": "fabspec/skyLines.py", "max_stars_repo_name": "ajshajib/fabspec", "max_stars_repo_head_hexsha": "0fec1595a4525215bbabd1f2480d1d31a86d955e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fabspec/skyLines.py", "max_issues_repo_name": "ajshajib/fabspec", "max_issues_repo_head_hexsha": "0fec1595a4525215bbabd1f2480d1d31a86d955e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fabspec/skyLines.py", "max_forks_repo_name": "ajshajib/fabspec", "max_forks_repo_head_hexsha": "0fec1595a4525215bbabd1f2480d1d31a86d955e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9264069264, "max_line_length": 79, "alphanum_fraction": 0.5713967972, "include": true, "reason": "import numpy", "num_tokens": 2058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.17775843768582836}}
{"text": "import numpy as np\nimport itertools\nimport math\n\n\n\nclass reax_forcefield:\n    \"\"\"\n    ReaxFF forcefield class. Used for generating ReaxFF templates\n    \"\"\"\n    def __init__(self, filename = None, filestring = None, template = 'ff.template.generated', ranges = 'param_ranges', bo_threshold = 1e-8):\n        \"\"\"\n        :param filename: ReaxFF forcefield filename\n        :type filename: str\n\n        :param filestring: ReaxFF forcefield filestring\n        :type filestring: str\n\n        :param template: ReaxFF forcefield template filename\n        :type template: str\n\n        :param ranges: File containing the lower and upper bounds for decision variables\n        :type ranges: str\n        \"\"\"\n        self.params_write = []\n        self.template = template\n        self.ranges = ranges\n        self.bo_threshold = bo_threshold\n        if not filename is None:\n            self.read_forcefield_from_file(filename)\n        elif not filestring is None:\n            self.read_forcefield_from_string(filestring)\n\n\n\n    def read_forcefield_from_file(self,filename):\n        \"\"\"\n        Read ReaxFF forcefield from external file\n\n        :param filename: ReaxFF forcefield filename\n        :type filename: str\n        \"\"\"\n        fffile = open(filename,'r')\n        ff = fffile.read()\n        fffile.close()\n\n        # Parse forcefield from read-in string\n        self.read_forcefield_from_string(ff)\n        return\n\n\n\n    def read_forcefield_from_string(self,filestring):\n        \"\"\"\n        Read ReaxFF forcefield from a given forcefield string\n\n        :param filestring: ReaxFF forcefield string\n        :type filestring: str\n        \"\"\"\n        list_of_strings = [line+'\\n' for line in filestring.split('\\n')]\n\n        self.full = list_of_strings\n        #print(self.full)\n        # Split forcefield\n        self._split_forcefield()\n        return\n\n\n\n    def _split_forcefield(self):\n        \"\"\"\n        Split ReaxFF forcefield into sections corresponding to general, one-body, two-body, three-body, four-body, offdiagonal and H-bond sections\n        \"\"\"\n        header, general, onebody, twobody, offdiagonal, threebody, fourbody, hbond = [], [], [], [], [], [], [], []\n        counter = 0\n        ff = self.full\n\n        # Read HEADER line\n        header = ff[0]\n        counter += 1\n\n        num_general = int(ff[counter].strip().split()[0])\n        general_string = ff[counter:counter+num_general+1] # one for the header another for the number of parameters\n        for line in general_string:\n            general.append(line.strip().split())\n        counter += (num_general + 1)\n\n        num_onebody = int(ff[counter].strip().split()[0])\n        onebody_string = ff[counter:counter+(num_onebody*4)+4] # one for the header another for the number of parameters\n        for line in onebody_string:\n            onebody.append(line.strip().split())\n        counter += ((num_onebody*4) + 4)\n\n        num_twobody = int(ff[counter].strip().split()[0])\n        twobody_string = ff[counter:counter+(num_twobody*2)+2] # one for the header another for the number of parameters\n        for line in twobody_string:\n            twobody.append(line.strip().split())\n        counter += ((num_twobody*2) + 2)\n\n        num_offdiagonal = int(ff[counter].strip().split()[0])\n        offdiagonal_string = ff[counter:counter+(num_offdiagonal*1)+1] # one for the header another for the number of parameters\n        for line in offdiagonal_string:\n            offdiagonal.append(line.strip().split())\n        counter += ((num_offdiagonal*1) + 1)\n\n        num_threebody = int(ff[counter].strip().split()[0])\n        threebody_string = ff[counter:counter+(num_threebody*1)+1] # one for the header another for the number of parameters\n        for line in threebody_string:\n            threebody.append(line.strip().split())\n        counter += ((num_threebody*1) + 1)\n\n        num_fourbody = int(ff[counter].strip().split()[0])\n        fourbody_string = ff[counter:counter+(num_fourbody*1)+1] # one for the header another for the number of parameters\n        for line in fourbody_string:\n            fourbody.append(line.strip().split())\n        counter += ((num_fourbody*1) + 1)\n\n        num_hbond = int(ff[counter].strip().split()[0])\n        hbond_string = ff[counter:counter+(num_hbond*1)+1] # one for the header another for the number of parameters\n        for line in hbond_string:\n            hbond.append(line.strip().split())\n        counter += ((num_hbond*1) + 1)\n\n        self.header = header\n        self.general = general\n        self.onebody = onebody\n        self.twobody = twobody\n        self.offdiagonal = offdiagonal\n        self.threebody = threebody\n        self.fourbody = fourbody\n        self.hbond = hbond\n\n\n\n    def _get_element_number(self,element):\n        \"\"\"\n        Get the numerical index of an element in the ReaxFF forcefield file\n\n        :param element: Chemical symbol for the element\n        :type element: str\n        \"\"\"\n        new_onebody = self.onebody[4::4]\n        for i in range(len(new_onebody)):\n            if new_onebody[i][0].lower().upper() == element.lower().upper():\n                return i+1\n        return 0\n\n\n\n    def _template_qeq(self, e1, bounds):\n       \"\"\"\n       Generate decision variable for electrostatic energy equation for a particular element\n\n       :param e1: Chemical symbol for element 1\n       :type e1: str\n\n       :param bounds: Maximum deviation allowed for each decision variable from its current value in the forcefield\n       :type bounds: float\n\n       \"\"\"\n       ie1 = self._get_element_number(e1)\n       if ie1 == 0: return\n\n       # gamma, chi and eta\n       for index, line in enumerate(self.onebody[4::4]):\n           if (line[0] == e1):\n               break\n       line_number = 3 + (4*index) + 1\n\n       gamma = float(self.onebody[line_number][7-1]) #  6th term, -1 for 0 indexing\n       chi   = float(self.onebody[line_number+1][14-8-1]) # 14th term, -8 for previous line, -1 for 0 indexing\n       eta   = float(self.onebody[line_number+1][15-8-1]) # 15th term, -8 for previous line, -1 for 0 indexing\n\n       # gamma\n       self.onebody[line_number][7-1] = '<<gam_'+e1+'>>'\n       delta = bounds * np.absolute(gamma)\n       self.params_write.append(['gam_'+e1, str(gamma-delta), str(gamma+delta)])\n\n       # chi\n       self.onebody[line_number+1][14-8-1] = '<<chi_'+e1+'>>'\n       delta = bounds * np.absolute(chi)\n       self.params_write.append(['chi_'+e1, str(chi-delta), str(chi+delta)])\n\n       # eta\n       self.onebody[line_number+1][15-8-1] = '<<eta_'+e1+'>>'\n       delta = bounds * np.absolute(eta)\n       self.params_write.append(['eta_'+e1, str(eta-delta), str(eta+delta)])\n\n       return\n\n    def _template_bond_order(self, e1, e2, double_bond = False, triple_bond = False, bounds = 0.1):\n        \"\"\"\n        Generate decision variables in the bond-order equation for bonds between two elements\n\n        :param e1: Chemical symbol for element 1\n        :type e1: str\n\n        :param e2: Chemical symbol for element 2\n        :type e2: str\n\n        :param bounds: Maximum deviation allowed for each decision variable from its current value in the forcefield\n        :type bounds: float\n\n        :param double_bond: Flag for the presence of a double-bond between elements e1 and e2\n        :type double_bond: bool\n\n        :param triple_bond: Flag for the presence of a triple-bond between elements e1 and e2\n        :type triple_bond: bool\n\n        \"\"\"\n        ie1, ie2 = self._get_element_number(e1), self._get_element_number(e2)\n\n        #-------------------#\n        #--- SINGLE BOND ---#\n        #-------------------#\n\n        # PBO1 and PBO2\n        for index, line in enumerate(self.twobody[2::2]):\n            if (int(line[0]) == ie1 and int(line[1]) == ie2) or (int(line[0]) == ie2 and int(line[1]) == ie1):\n                break\n        line_number = (2 + (2*index) + 1)\n\n        #PBO1\n        PBO1 = float(self.twobody[line_number][13-8-1]) # 13th term, -8 for previous line, -1 for 0 indexing\n        delta = bounds * np.absolute(PBO1)\n        self.twobody[line_number][13-8-1] = '<<PBO1_'+e1+'_'+e2+'>>'\n        self.params_write.append(['PBO1_'+e1+'_'+e2, str(PBO1-delta), str(PBO1+delta)])\n\n        #PBO2\n        PBO2 = float(self.twobody[line_number][14-8-1]) # 14th term, -8 for previous line, -1 for 0 indexing\n        delta = bounds * np.absolute(PBO2)\n        self.twobody[line_number][14-8-1] = '<<PBO2_'+e1+'_'+e2+'>>'\n        self.params_write.append(['PBO2_'+e1+'_'+e2, str(PBO2-delta), str(PBO2+delta)])\n\n        # ro_sigma\n        for index, line in enumerate(self.offdiagonal[1:]):\n            if (int(line[0]) == ie1 and int(line[1]) == ie2) or (int(line[0]) == ie2 and int(line[1]) == ie1):\n                break\n        line_number = (1 + (1*index))\n\n        # ro_sigma\n        ro_sigma = float(self.offdiagonal[line_number][4+2-1])  # 4th term, +2 for atom indices, -1 for 0 indexing\n        delta = bounds * np.absolute(ro_sigma)\n        self.offdiagonal[line_number][4+2-1] = '<<ro_sigma_'+e1+'_'+e2+'>>'\n        self.params_write.append(['ro_sigma_'+e1+'_'+e2, str(ro_sigma-delta), str(ro_sigma+delta)])\n\n\n\n        #-------------------#\n        #--- DOUBLE BOND ---#\n        #-------------------#\n        if double_bond:\n            # PBO1 and PBO2\n            for index, line in enumerate(self.twobody[2::2]):\n                if (int(line[0]) == ie1 and int(line[1]) == ie2) or (int(line[0]) == ie2 and int(line[1]) == ie1):\n                    break\n            line_number = (2 + (2*index) + 1)\n\n            #PBO3\n            PBO3 = float(self.twobody[line_number][10-8-1]) # 10th term, -8 for previous line, -1 for 0 indexing\n            delta = bounds * np.absolute(PBO3)\n            self.twobody[line_number][10-8-1] = '<<PBO3_'+e1+'_'+e2+'>>'\n            self.params_write.append(['PBO3_'+e1+'_'+e2, str(PBO3-delta), str(PBO3+delta)])\n\n            #PBO4\n            PBO4 = float(self.twobody[line_number][11-8-1]) # 11th term, -8 for previous line, -1 for 0 indexing\n            delta = bounds * np.absolute(PBO4)\n            self.twobody[line_number][11-8-1] = '<<PBO4_'+e1+'_'+e2+'>>'\n            self.params_write.append(['PBO4_'+e1+'_'+e2, str(PBO4-delta), str(PBO4+delta)])\n\n            # ro_pi\n            for index, line in enumerate(self.offdiagonal[1:]):\n                if (int(line[0]) == ie1 and int(line[1]) == ie2) or (int(line[0]) == ie2 and int(line[1]) == ie1):\n                    break\n            line_number = (1 + (1*index))\n\n            # ro_pi\n            ro_pi = float(self.offdiagonal[line_number][5+2-1])  # 4th term, +2 for atom indices, -1 for 0 indexing\n            delta = bounds * np.absolute(ro_pi)\n            self.offdiagonal[line_number][5+2-1] = '<<ro_pi_'+e1+'_'+e2+'>>'\n            self.params_write.append(['ro_pi_'+e1+'_'+e2, str(ro_pi-delta), str(ro_pi+delta)])\n\n\n        #-------------------#\n        #--- TRIPLE BOND ---#\n        #-------------------#\n        if triple_bond:\n            # PBO5 and PBO6\n            for index, line in enumerate(self.twobody[2::2]):\n                if (int(line[0]) == ie1 and int(line[1]) == ie2) or (int(line[0]) == ie2 and int(line[1]) == ie1):\n                    break\n            line_number = (2 + (2*index))\n\n            #PBO5\n            PBO5 = float(self.twobody[line_number][5+2-1]) # 5th term, +2 for atom indices, -1 for 0 indexing\n            delta = bounds * np.absolute(PBO5)\n            self.twobody[line_number][5+2-1] = '<<PBO5_'+e1+'_'+e2+'>>'\n            self.params_write.append(['PBO5_'+e1+'_'+e2, str(PBO5-delta), str(PBO5+delta)])\n\n            #PBO6\n            PBO6 = float(self.twobody[line_number][8+2-1]) # 8th term, +2 for atom indices, -1 for 0 indexing\n            delta = bounds * np.absolute(PBO6)\n            self.twobody[line_number][8+2-1] = '<<PBO6_'+e1+'_'+e2+'>>'\n            self.params_write.append(['PBO6_'+e1+'_'+e2, str(PBO6-delta), str(PBO6+delta)])\n\n            # ro_pipi\n            for index, line in enumerate(self.offdiagonal[1:]):\n                if (int(line[0]) == ie1 and int(line[1]) == ie2) or (int(line[0]) == ie2 and int(line[1]) == ie1):\n                    break\n            line_number = (1 + (1*index))\n\n            # ro_pipi\n            ro_pipi = float(self.offdiagonal[line_number][6+2-1]) # 6th term, +2 for atom indices, -1 for 0 indexing\n            delta = bounds * np.absolute(ro_pipi)\n            self.offdiagonal[line_number][6+2-1] = '<<ro_pipi_'+e1+'_'+e2+'>>'\n            self.params_write.append(['ro_pipi_'+e1+'_'+e2, str(ro_pipi-delta), str(ro_pipi+delta)])\n\n        return\n\n\n\n    def _template_bond_energy_attractive(self, e1, e2, double_bond = False, triple_bond = False, bounds = 0.1):\n        \"\"\"\n        Generate decision variables related to the two-body attractive term\n\n        :param e1: Chemical symbol for element 1\n        :type e1: str\n\n        :param e2: Chemical symbol for element 2\n        :type e2: str\n\n        :param bounds: Maximum deviation allowed for each decision variable from its current value in the forcefield\n        :type bounds: float\n\n        :param double_bond: Flag for the presence of a double-bond between elements e1 and e2\n        :type double_bond: bool\n\n        :param triple_bond: Flag for the presence of a triple-bond between elements e1 and e2\n        :type triple_bond: bool\n        \"\"\"\n        ie1, ie2 = self._get_element_number(e1), self._get_element_number(e2)\n\n        #-------------------#\n        #--- SINGLE BOND ---#\n        #-------------------#\n\n        # De_sigma\n        for index, line in enumerate(self.twobody[2::2]):\n            if (int(line[0]) == ie1 and int(line[1]) == ie2) or (int(line[0]) == ie2 and int(line[1]) == ie1):\n                break\n        line_number = (2 + (2*index))\n\n        #De_sigma\n        De_sigma = float(self.twobody[line_number][1+2-1]) # 1st term, +2 for atom indices, -1 for 0 indexing\n        delta = bounds * np.absolute(De_sigma)\n        self.twobody[line_number][1+2-1] = '<<De_sigma_'+e1+'_'+e2+'>>'\n        self.params_write.append(['De_sigma_'+e1+'_'+e2, str(De_sigma-delta), str(De_sigma+delta)])\n\n        #PBE1\n        PBE1 = float(self.twobody[line_number][4+2-1]) # 4th term, +2 for atom indices, -1 for 0 indexing\n        delta = bounds * np.absolute(PBE1)\n        self.twobody[line_number][4+2-1] = '<<PBE1_'+e1+'_'+e2+'>>'\n        self.params_write.append(['PBE1_'+e1+'_'+e2, str(PBE1-delta), str(PBE1+delta)])\n\n        line_number = (2 + (2*index) + 1)  # PBE2 is on the next line\n\n        #PBE2\n        PBE2 = float(self.twobody[line_number][9-8-1]) # 9th term, -8 for previous line, -1 for 0 indexing\n        delta = bounds * np.absolute(PBE2)\n        self.twobody[line_number][9-8-1] = '<<PBE2_'+e1+'_'+e2+'>>'\n        self.params_write.append(['PBE2_'+e1+'_'+e2, str(PBE2-delta), str(PBE2+delta)])\n\n        #-------------------#\n        #--- DOUBLE BOND ---#\n        #-------------------#\n        # De_pi\n        for index, line in enumerate(self.twobody[2::2]):\n            if (int(line[0]) == ie1 and int(line[1]) == ie2) or (int(line[0]) == ie2 and int(line[1]) == ie1):\n                break\n        line_number = (2 + (2*index))\n        De_pi = float(self.twobody[line_number][2+2-1]) # 2nd term, +2 for atom indices, -1 for 0 indexing\n\n        if double_bond:\n            delta = bounds * np.absolute(De_pi)\n            self.twobody[line_number][2+2-1] = '<<De_pi_'+e1+'_'+e2+'>>'\n            self.params_write.append(['De_pi_'+e1+'_'+e2, str(De_pi-delta), str(De_pi+delta)])\n        else:\n            if De_pi != 0.0:\n                print('Double bond parameters for ' + e1 + '-' + e2 + ' bond will not be optimized. Current non-zero values in the template forcefield will be retained.')\n\n        #-------------------#\n        #--- TRIPLE BOND ---#\n        #-------------------#\n        # De_pipi\n        for index, line in enumerate(self.twobody[2::2]):\n            if (int(line[0]) == ie1 and int(line[1]) == ie2) or (int(line[0]) == ie2 and int(line[1]) == ie1):\n                break\n        line_number = (2 + (2*index))\n        De_pipi = float(self.twobody[line_number][3+2-1]) # 3rd term, +2 for atom indices, -1 for 0 indexing\n\n        if triple_bond:\n            delta = bounds * np.absolute(De_pipi)\n            self.twobody[line_number][3+2-1] = '<<De_pipi_'+e1+'_'+e2+'>>'\n            self.params_write.append(['De_pipi_'+e1+'_'+e2, str(De_pipi-delta), str(De_pipi+delta)])\n        else:\n            if De_pipi != 0.0:\n                print('Triple bond parameters for ' + e1 + '-' + e2 + ' bond will not be optimized. Current non-zero values in the template forcefield will be retained.')\n\n\n\n\n\n    def _template_bond_energy_vdW(self, e1, e2, f13 = False, bounds = 0.1):\n        \"\"\"\n        Generate decision variables related to the two-body repulsive (i.e. van der Waals) term\n\n        :param e1: Chemical symbol for element 1\n        :type e1: str\n\n        :param e2: Chemical symbol for element 2\n        :type e2: str\n\n        :param bounds: Maximum deviation allowed for each decision variable from its current value in the forcefield\n        :type bounds: float\n\n        :param f13: Flag for the optimization of common variables\n        :type f13: bool\n        \"\"\"\n        ie1, ie2 = self._get_element_number(e1), self._get_element_number(e2)\n\n        # Dij, rvdWm alpha_ij in off-diagonal\n        for index, line in enumerate(self.offdiagonal[1:]):\n            if (int(line[0]) == ie1 and int(line[1]) == ie2) or (int(line[0]) == ie2 and int(line[1]) == ie1):\n                break\n        line_number = (1 + (1*index))\n\n        # Dij\n        Dij = float(self.offdiagonal[line_number][1+2-1]) # 1st term, +2 for atom indices, -1 for 0 indexing\n        delta = bounds * np.absolute(Dij)\n        self.offdiagonal[line_number][1+2-1] = '<<Dij_'+e1+'_'+e2+'>>'\n        self.params_write.append(['Dij_'+e1+'_'+e2, str(Dij-delta), str(Dij+delta)])\n\n        # rvdW\n        rvdW = float(self.offdiagonal[line_number][2+2-1]) # 2nd term, +2 for atom indices, -1 for 0 indexing\n        delta = bounds * np.absolute(rvdW)\n        self.offdiagonal[line_number][2+2-1] = '<<rvdW_'+e1+'_'+e2+'>>'\n        self.params_write.append(['rvdW_'+e1+'_'+e2, str(rvdW-delta), str(rvdW+delta)])\n\n        # alpha_ij\n        alpha_ij = float(self.offdiagonal[line_number][3+2-1]) # 3rd term, +2 for atom indices, -1 for 0 indexing\n        delta = bounds * np.absolute(alpha_ij)\n        self.offdiagonal[line_number][3+2-1] = '<<alpha_ij_'+e1+'_'+e2+'>>'\n        self.params_write.append(['alpha_ij_'+e1+'_'+e2, str(alpha_ij-delta), str(alpha_ij+delta)])\n\n\n        ### WRITE PARAMETER IN F13\n        if f13:\n            # gamma_w in element 1 in onebody\n            for index, line in enumerate(self.onebody[4::4]):\n                if line[0].lower().upper() == e1.lower().upper():\n                    break\n            line_number = (4 + (4*index) + 1)\n\n            # gamma_w\n            gamma_w = float(self.onebody[line_number][10-8-1]) # 10th term, -8 for previous line, -1 for 0 indexing\n            delta = bounds * np.absolute(gamma_w)\n            self.onebody[line_number][3+2-1] = '<<gamma_w_'+e1+'>>'\n            self.params_write.append(['gamma_w_'+e1, str(gamma_w-delta), str(gamma_w+delta)])\n\n            # gamma_w in element 2 in onebody\n            for index, line in enumerate(self.onebody[4::4]):\n                if line[0].lower().upper() == e2.lower().upper():\n                    break\n            line_number = (4 + (4*index) + 1)\n\n            # gamma_w\n            gamma_w = float(self.onebody[line_number][10-8-1]) # 10th term, -8 for previous line, -1 for 0 indexing\n            delta = bounds * np.absolute(gamma_w)\n            self.onebody[line_number][3+2-1] = '<<gamma_w_'+e2+'>>'\n            self.params_write.append(['gamma_w_'+e2, str(gamma_w-delta), str(gamma_w+delta)])\n\n\n            # Pvdw1 in general parameters\n            line_number = 1 + 29  # 29th parameter, +1 for header line\n            P_vdW1 = float(self.general[line_number][0])\n            delta = bounds * np.absolute(P_vdW1)\n            self.general[line_number][0] = '<<PvdW>>'\n            self.params_write.append(['PvdW', str(P_vdW1-delta), str(P_vdW1+delta)])\n\n\n\n\n\n\n\n\n    def _template_threebody_energy(self, e1, e2, e3, bounds = 0.1):\n        \"\"\"\n        Generate decision variables related to the three-body angle term\n\n        :param e1: Chemical symbol for element 1\n        :type e1: str\n\n        :param e2: Chemical symbol for element 2\n        :type e2: str\n\n        :param e3: Chemical symbol for element 3\n        :type e3: str\n\n        :param bounds: Maximum deviation allowed for each decision variable from its current value in the forcefield\n        :type bounds: float\n        \"\"\"\n        # theta0, Pval1, Pval2 in threebody\n        for triplet in list(set(list(itertools.permutations([e1,e2,e3])))):\n            ie1 = self._get_element_number(triplet[0])\n            ie2 = self._get_element_number(triplet[1])\n            ie3 = self._get_element_number(triplet[2])\n            for index, line in enumerate(self.threebody[1:]):\n                if int(line[0]) == ie1 and int(line[1]) == ie2 and int(line[2]) == ie3:\n                    line_number = (1 + (1*index))\n\n                    theta0 = float(self.threebody[line_number][1+3-1]) # 1st term, +3 for atom indices, -1 for 0 indexing\n                    delta = bounds * np.absolute(theta0)\n                    self.threebody[line_number][1+3-1] = '<<theta0_'+triplet[0]+'_'+triplet[1]+'_'+triplet[2]+'>>'\n                    self.params_write.append(['theta0_'+triplet[0]+'_'+triplet[1]+'_'+triplet[2], str(theta0-delta), str(theta0+delta)])\n\n                    Pval1 = float(self.threebody[line_number][2+3-1]) # 2nd term, +3 for atom indices, -1 for 0 indexing\n                    delta = bounds * np.absolute(Pval1)\n                    self.threebody[line_number][2+3-1] = '<<Pval1_'+triplet[0]+'_'+triplet[1]+'_'+triplet[2]+'>>'\n                    self.params_write.append(['Pval1_'+triplet[0]+'_'+triplet[1]+'_'+triplet[2], str(Pval1-delta), str(Pval1+delta)])\n\n                    Pval2 = float(self.threebody[line_number][3+3-1]) # 3rd term, +3 for atom indices, -1 for 0 indexing\n                    delta = bounds * np.absolute(Pval2)\n                    self.threebody[line_number][3+3-1] = '<<Pval2_'+triplet[0]+'_'+triplet[1]+'_'+triplet[2]+'>>'\n                    self.params_write.append(['Pval2_'+triplet[0]+'_'+triplet[1]+'_'+triplet[2], str(Pval2-delta), str(Pval2+delta)])\n\n\n\n\n    def _template_fourbody_energy(self, e1, e2, e3, e4, bounds = 0.1):\n        \"\"\"\n        Generate decision variables related to the four-body dihedral term\n\n        :param e1: Chemical symbol for element 1\n        :type e1: str\n\n        :param e2: Chemical symbol for element 2\n        :type e2: str\n\n        :param e3: Chemical symbol for element 3\n        :type e3: str\n\n        :param e4: Chemical symbol for element 4\n        :type e4: str\n\n        :param bounds: Maximum deviation allowed for each decision variable from its current value in the forcefield\n        :type bounds: float\n        \"\"\"\n        # V1, V2, V3, Ptor1 in fourbody\n        for quartet in list(set(list(itertools.permutations([e1,e2,e3,e4])))):\n            ie1 = self._get_element_number(quartet[0])\n            ie2 = self._get_element_number(quartet[1])\n            ie3 = self._get_element_number(quartet[2])\n            ie4 = self._get_element_number(quartet[3])\n\n            for index, line in enumerate(self.fourbody[1:]):\n                if int(line[0]) == ie1 and int(line[1]) == ie2 and int(line[2]) == ie3 and int(line[3]) == ie4:\n                    line_number = (1 + (1*index))\n\n                    V1 = float(self.fourbody[line_number][1+4-1]) # 1st term, +3 for atom indices, -1 for 0 indexing\n                    delta = bounds * np.absolute(V1)\n                    self.fourbody[line_number][1+4-1] = '<<V1_'+quartet[0]+'_'+quartet[1]+'_'+quartet[2]+'_'+quartet[3]+'>>'\n                    self.params_write.append(['V1_'+quartet[0]+'_'+quartet[1]+'_'+quartet[2]+'_'+quartet[3], str(V1-delta), str(V1+delta)])\n\n                    V2 = float(self.fourbody[line_number][2+4-1]) # 2nd term, +3 for atom indices, -1 for 0 indexing\n                    delta = bounds * np.absolute(V2)\n                    self.fourbody[line_number][2+4-1] = '<<V2_'+quartet[0]+'_'+quartet[1]+'_'+quartet[2]+'_'+quartet[3]+'>>'\n                    self.params_write.append(['V2_'+quartet[0]+'_'+quartet[1]+'_'+quartet[2]+'_'+quartet[3], str(V2-delta), str(V2+delta)])\n\n                    V3 = float(self.fourbody[line_number][3+4-1]) # 3rd term, +3 for atom indices, -1 for 0 indexing\n                    delta = bounds * np.absolute(V3)\n                    self.fourbody[line_number][3+4-1] = '<<V3_'+quartet[0]+'_'+quartet[1]+'_'+quartet[2]+'_'+quartet[3]+'>>'\n                    self.params_write.append(['V3_'+quartet[0]+'_'+quartet[1]+'_'+quartet[2]+'_'+quartet[3], str(V3-delta), str(V3+delta)])\n\n                    Ptor1 = float(self.fourbody[line_number][4+4-1]) # 4th term, +3 for atom indices, -1 for 0 indexing\n                    delta = bounds * np.absolute(Ptor1)\n                    self.fourbody[line_number][4+4-1] = '<<Ptor1_'+quartet[0]+'_'+quartet[1]+'_'+quartet[2]+'_'+quartet[3]+'>>'\n                    self.params_write.append(['Ptor1_'+quartet[0]+'_'+quartet[1]+'_'+quartet[2]+'_'+quartet[3], str(Ptor1-delta), str(Ptor1+delta)])\n\n\n\n    def generate_templates(self):\n        \"\"\"\n        Function to write-out the current modified forcefield sections into a forcefield template file\n        \"\"\"\n        with open(self.ranges, 'w') as ranges_file:\n            for parameter in self.params_write:\n                ranges_file.write(' '.join(parameter) + '\\n')\n\n        with open(self.template,'w') as template:\n            template.write(self.header)\n            for line in self.general:\n                template.write(' '.join(line)+'\\n')\n            for line in self.onebody:\n                template.write(' '.join(line)+'\\n')\n            for line in self.twobody:\n                template.write(' '.join(line)+'\\n')\n            for line in self.offdiagonal:\n                template.write(' '.join(line)+'\\n')\n            for line in self.threebody:\n                template.write(' '.join(line)+'\\n')\n            for line in self.fourbody:\n                template.write(' '.join(line)+'\\n')\n            for line in self.hbond:\n                template.write(' '.join(line)+'\\n')\n\n\n    def make_template_qeq(self, e1, bounds=0.1):\n        \"\"\"\n        Function to generate decision variable for Charge Equilibration (QEq) terms\n\n        : param e1 : Chemical symbol for element 1\n        : type e1  : str\n\n        : param bounds: Maximum deviation allowed for each decision variable from its current value in the forcefield\n        : type bounds: float\n\n        \"\"\"\n        # GET ONE_BODY_PARAMETERS SPECIFIC TO QEQ\n        self._template_qeq(e1,bounds)\n        return\n\n\n    def make_template_twobody(self, e1, e2, double_bond = False, triple_bond = False, bounds = 0.1, common = False):\n        \"\"\"\n        Function to generate decision variables for all two-body terms (i.e. bond-order, attractive and vdW) between two given elements\n\n        :param e1: Chemical symbol for element 1\n        :type e1: str\n\n        :param e2: Chemical symbol for element 2\n        :type e2: str\n\n        :param bounds: Maximum deviation allowed for each decision variable from its current value in the forcefield\n        :type bounds: float\n\n        :param double_bond: Flag for the presence of a double-bond between elements e1 and e2\n        :type double_bond: bool\n\n        :param triple_bond: Flag for the presence of a triple-bond between elements e1 and e2\n        :type triple_bond: bool\n\n        :param common: Flag for the optimization of common parameters\n        :type common: bool\n        \"\"\"\n        # GET BOND_ORDER_PARAMETERS\n        self._template_bond_order(e1,e2,double_bond = double_bond, triple_bond = triple_bond, bounds = bounds)\n        self._template_bond_energy_attractive(e1,e2,double_bond = double_bond, triple_bond = triple_bond, bounds = bounds)\n        self._template_bond_energy_vdW(e1,e2, f13 = common, bounds = bounds)\n        return\n\n    def make_template_threebody(self, e1, e2, e3, bounds = 0.1, common = False):\n        \"\"\"\n        Function to generate decision variables for all three-body terms for a given triplet of elements\n\n        :param e1: Chemical symbol for element 1\n        :type e1: str\n\n        :param e2: Chemical symbol for element 2\n        :type e2: str\n\n        :param e3: Chemical symbol for element 3\n        :type e3: str\n\n        :param bounds: Maximum deviation allowed for each decision variable from its current value in the forcefield\n        :type bounds: float\n\n        :param common: Flag for the optimization of common parameters\n        :type common: bool\n        \"\"\"\n        self._template_threebody_energy(e1, e2, e3, bounds = bounds)\n        return\n\n    def make_template_fourbody(self, e1, e2, e3, e4, bounds = 0.1, common = False):\n        \"\"\"\n        Function to generate decision variables for all four-body terms for a given quartet of elements\n\n        :param e1: Chemical symbol for element 1\n        :type e1: str\n\n        :param e2: Chemical symbol for element 2\n        :type e2: str\n\n        :param e3: Chemical symbol for element 3\n        :type e3: str\n\n        :param e4: Chemical symbol for element 4\n        :type e4: str\n\n        :param bounds: Maximum deviation allowed for each decision variable from its current value in the forcefield\n        :type bounds: float\n\n        :param common: Flag for the optimization of common parameters\n        :type common: bool\n        \"\"\"\n        self._template_fourbody_energy(e1, e2, e3, e4, bounds = bounds)\n        return\n\n\n    def write_formatted_forcefields(self):\n        \"\"\"\n        Function to write-out the current forcefield with correct ReaxFF formatting\n\n        :param outfilename: File to which formatted forcefield to be written to\n        :type outfilename: str\n        \"\"\"\n        string = self.header\n\n        # Write general parameters\n        for lineno, line in enumerate(self.general):\n            if lineno == 0:\n                string += ' %2d       %s\\n' %(int(line[0]), ' '.join(line[1:]))\n            else:\n                string += '%10.4f %s\\n' %(float(line[0]), ' '.join(line[1:]))\n\n        # One-body term\n        for lineno, line in enumerate(self.onebody[:4]):\n            if lineno == 0:\n                string += '%3d    %s\\n' %(int(line[0]), ' '.join(line[1:]))\n            else:\n                string += '            %s\\n' %(' '.join(line))\n\n        for lineno, line in enumerate(self.onebody[4:]):\n            if lineno % 4 == 0:\n                string += ' %-2s' % line[0] + ''.join(['%9.4f' % float(val) for val in line[1:]]) + '\\n'\n            else:\n                string += '   ' + ''.join(['%9.4f' % float(val) for val in line]) + '\\n'\n\n        # Two-body terms\n        for lineno, line in enumerate(self.twobody[:2]):\n            if lineno == 0:\n                string += '%3d      %s\\n' %(int(line[0]), ' '.join(line[1:]))\n            else:\n                string += '            %s\\n' %(' '.join(line))\n\n        for lineno, line in enumerate(self.twobody[2:]):\n            if lineno % 2 == 0:\n                string += '%3d' % int(line[0]) + '%3d' % int(line[1]) + ''.join(['%9.4f' % float(val) for val in line[2:]]) + '\\n'\n            else:\n                string += '      ' + ''.join(['%9.4f' % float(val) for val in line]) + '\\n'\n\n        # Off-diagonal\n        for lineno, line in enumerate(self.offdiagonal):\n            if lineno == 0:\n                string += '%3d    ' % int(line[0]) + ' '.join(line[1:]) + '\\n'\n            else:\n                string += '%3d' % int(line[0]) + '%3d' % int(line[1]) + ''.join(['%9.4f' % float(val) for val in line[2:]]) + '\\n'\n\n        # Threebody\n        for lineno, line in enumerate(self.threebody):\n            if lineno == 0:\n                string += '%3d    ' % int(line[0]) + ' '.join(line[1:]) + '\\n'\n            else:\n                string += '%3d' % int(line[0]) + '%3d' % int(line[1]) + '%3d' % int(line[2]) + ''.join(['%9.4f' % float(val) for val in line[3:]]) + '\\n'\n\n        # Fourbody\n        for lineno, line in enumerate(self.fourbody):\n            if lineno == 0:\n                string += '%3d    ' % int(line[0]) + ' '.join(line[1:]) + '\\n'\n            else:\n                string += '%3d' % int(line[0]) + '%3d' % int(line[1]) + '%3d' % int(line[2]) + '%3d' % int(line[3]) + ''.join(['%9.4f' % float(val) for val in line[4:]])+ '\\n'\n\n\n        # Hbond\n        for lineno, line in enumerate(self.hbond):\n            if lineno == 0:\n                string += '%3d    ' % int(line[0]) + ' '.join(line[1:]) + '\\n'\n            else:\n                string += '%3d' % int(line[0]) + '%3d' % int(line[1]) + '%3d' % int(line[2]) + ''.join(['%9.4f' % float(val) for val in line[3:]]) + '\\n'\n\n        return string\n\n\n\n    def write_gulp_library(self, outfilename = None):\n        \"\"\"\n        Function to write-out the forcefield in the GULP library format\n\n        :param outfilename: File to which the GULP ReaxFF forcefield library\n        :type outfilename: str\n        \"\"\"\n        # HEADER\n        string = ''\n        string += '#\\n'\n        string += '#  ReaxFF force field\\n'\n        string += '#\\n'\n        string += '#  Original paper:\\n'\n        string += '#\\n'\n        string += '#  A.C.T. van Duin, S. Dasgupta, F. Lorant and W.A. Goddard III,\\n'\n        string += '#  J. Phys. Chem. A, 105, 9396-9409 (2001)\\n'\n        string += '#\\n'\n        string += '#\\n'\n\n        # CUTOFFS\n        string += '#  Cutoffs for VDW & Coulomb terms\\n'\n        string += '#\\n'\n        string += 'reaxFFvdwcutoff %12.4f\\n' % float(self.general[13][0])\n        string += 'reaxFFqcutoff   %12.4f\\n' % float(self.general[13][0])\n        string += '#\\n'\n\n        #BOND ORDER THRESHOLD\n        string += '#  Bond order threshold - check anglemin as this is cutof2 given in control file\\n'\n        string += '#\\n'\n        string += 'reaxFFtol       %12.10f 0.001\\n' % (float(self.general[30][0])*0.01)\n        string += '#\\n'\n\n        #SPECIES INDEPENDENT PARAMETERS\n        string += '#  Species independent parameters \\n'\n        string += '#\\n'\n        string += 'reaxff0_bond     %12.6f %12.6f\\n' %(float(self.general[1][0]), float(self.general[2][0]))\n        string += 'reaxff0_over     %12.6f %12.6f %12.6f %12.6f %12.6f\\n' %(float(self.general[33][0]), float(self.general[32][0]), float(self.general[7][0]), float(self.general[9][0]), float(self.general[10][0]))\n        string += 'reaxff0_valence  %12.6f %12.6f %12.6f %12.6f\\n' %(float(self.general[15][0]), float(self.general[34][0]), float(self.general[17][0]), float(self.general[18][0]))\n        string += 'reaxff0_penalty  %12.6f %12.6f %12.6f\\n' %(float(self.general[20][0]), float(self.general[21][0]), float(self.general[22][0]))\n        string += 'reaxff0_torsion  %12.6f %12.6f %12.6f %12.6f\\n' %(float(self.general[24][0]), float(self.general[25][0]), float(self.general[26][0]), float(self.general[28][0]))\n        string += 'reaxff0_vdw      %12.6f\\n' % float(self.general[29][0])\n        string += 'reaxff0_lonepair %12.6f\\n' % float(self.general[16][0])\n        string += '#\\n'\n\n        #SPECIES PARAMETERS - RADII\n        string += '#  Species parameters \\n'\n        string += '#\\n'\n        string += 'reaxff1_radii\\n'\n        for lineno in list(range(4,len(self.onebody),4)):\n            string += '%-2s core %8.4f %8.4f %8.4f\\n' % (self.onebody[lineno][0], float(self.onebody[lineno][1]), float(self.onebody[lineno][7]), float(self.onebody[lineno+2][0]))\n\n        #SPECIES PARAMETERS - VALENCE\n        string += 'reaxff1_valence\\n'\n        for lineno in list(range(4,len(self.onebody),4)):\n            string += '%-2s core %8.4f %8.4f %8.4f %8.4f\\n' % (self.onebody[lineno][0], float(self.onebody[lineno][2]), float(self.onebody[lineno+3][3]), float(self.onebody[lineno][8]), float(self.onebody[lineno+1][2]))\n\n        #SPECIES PARAMETERS - OVER\n        string += 'reaxff1_over\\n'\n        for lineno in list(range(4,len(self.onebody),4)):\n            string += '%-2s core %8.4f %8.4f %8.4f %8.4f\\n' % (self.onebody[lineno][0], float(self.onebody[lineno+2][4]), float(self.onebody[lineno+2][3]), float(self.onebody[lineno+2][5]), float(self.onebody[lineno+3][0]))\n\n        #SPECIES PARAMETERS - UNDER KCAL\n        string += 'reaxff1_under kcal\\n'\n        for lineno in list(range(4,len(self.onebody),4)):\n            string += '%-2s core %8.4f\\n' % (self.onebody[lineno][0], float(self.onebody[lineno+1][3]))\n\n        #SPECIES PARAMETERS - LONEPAIR KCAL\n        string += 'reaxff1_lonepair kcal\\n'\n        for lineno in list(range(4,len(self.onebody),4)):\n            string += '%-2s core %8.4f %8.4f\\n' % (self.onebody[lineno][0], 0.5*(float(self.onebody[lineno][8]) - float(self.onebody[lineno][2])), float(self.onebody[lineno+2][1]))\n\n        #SPECIES PARAMETERS - ANGLE\n        string += 'reaxff1_angle\\n'\n        for lineno in list(range(4,len(self.onebody),4)):\n            string += '%-2s core %8.4f %8.4f\\n' % (self.onebody[lineno][0], float(self.onebody[lineno+3][1]), float(self.onebody[lineno+3][4]))\n\n        #SPECIES PARAMETERS - ANGLE\n        string += 'reaxff1_morse kcal\\n'\n        for lineno in list(range(4,len(self.onebody),4)):\n            string += '%-2s core %8.4f %8.4f %8.4f %8.4f\\n' % (self.onebody[lineno][0], float(self.onebody[lineno+1][0]), float(self.onebody[lineno][5]), float(self.onebody[lineno][4]), float(self.onebody[lineno+1][1]))\n\n        #ELEMENT PARAMETERS\n        string += '#\\n'\n        string += '#  Element parameters \\n'\n        string += '#\\n'\n\n        #ELEMENT PARAMETERS - CHI\n        string += 'reaxff_chi  \\n'\n        for lineno in list(range(4,len(self.onebody),4)):\n            string += '%-2s core %8.4f\\n' % (self.onebody[lineno][0], float(self.onebody[lineno+1][5]))\n\n        #ELEMENT PARAMETERS - MU\n        string += 'reaxff_mu   \\n'\n        for lineno in list(range(4,len(self.onebody),4)):\n            string += '%-2s core %8.4f\\n' % (self.onebody[lineno][0], float(self.onebody[lineno+1][6]))\n\n        #ELEMENT PARAMETERS - MU\n        string += 'reaxff_gamma  \\n'\n        for lineno in list(range(4,len(self.onebody),4)):\n            string += '%-2s core %8.4f\\n' % (self.onebody[lineno][0], float(self.onebody[lineno][6]))\n\n        #BOND PARAMETERS\n        string += '#\\n'\n        string += '#  Bond parameters \\n'\n        string += '#\\n'\n\n        #BOND PARAMETERS - BO OVER BO13\n        element_number = ['X']\n        for line in self.onebody[4::4]:\n            element_number.append(line[0])\n        first = True\n        for lineno in list(range(2,len(self.twobody),2)):\n            if (float(self.twobody[lineno][7]) > 0.001 and float(self.twobody[lineno+1][6]) > 0.001):\n                if first:\n                    string += 'reaxff2_bo over bo13\\n'\n                    first = False\n                n1, n2 = int(self.twobody[lineno][0]), int(self.twobody[lineno][1])\n                bo3 = 0.0 if (np.absolute(float(self.twobody[lineno+1][1])-1.0) < 1.0e-12) else float(self.twobody[lineno+1][1])\n                string += '%-2s core %-2s core %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f\\n' % (element_number[n1], element_number[n2], float(self.twobody[lineno+1][4]), float(self.twobody[lineno+1][5]), bo3, float(self.twobody[lineno+1][2]), float(self.twobody[lineno][6]), float(self.twobody[lineno][8]))\n\n        #BOND PARAMETERS - BO UNDER\n        element_number = ['X']\n        for line in self.onebody[4::4]:\n            element_number.append(line[0])\n        first = True\n        for lineno in list(range(2,len(self.twobody),2)):\n            if (float(self.twobody[lineno][7]) > 0.001 and float(self.twobody[lineno+1][6]) <= 0.001):\n                if first:\n                    string += 'reaxff2_bo bo13\\n'\n                    first = False\n                n1, n2 = int(self.twobody[lineno][0]), int(self.twobody[lineno][1])\n                bo3 = 0.0 if math.isclose(1.0, float(self.twobody[lineno+1][1])) else float(self.twobody[lineno+1][1])\n                string += '%-2s core %-2s core %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f\\n' % (element_number[n1], element_number[n2], float(self.twobody[lineno+1][4]), float(self.twobody[lineno+1][5]), bo3, float(self.twobody[lineno+1][2]), float(self.twobody[lineno][6]), float(self.twobody[lineno][8]))\n\n        #BOND PARAMETERS - BO OVER\n        element_number = ['X']\n        for line in self.onebody[4::4]:\n            element_number.append(line[0])\n        first = True\n        for lineno in list(range(2,len(self.twobody),2)):\n            if (float(self.twobody[lineno][7]) <= 0.001 and float(self.twobody[lineno+1][6]) > 0.001):\n                if first:\n                    string += 'reaxff2_bo over\\n'\n                    first = False\n                n1, n2 = int(self.twobody[lineno][0]), int(self.twobody[lineno][1])\n                bo3 = 0.0 if math.isclose(1.0, float(self.twobody[lineno+1][1])) else float(self.twobody[lineno+1][1])\n                string += '%-2s core %-2s core %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f\\n' % (element_number[n1], element_number[n2], float(self.twobody[lineno+1][4]), float(self.twobody[lineno+1][5]), bo3, float(self.twobody[lineno+1][2]), float(self.twobody[lineno][6]), float(self.twobody[lineno][8]))\n\n        #BOND PARAMETERS - BO\n        element_number = ['X']\n        for line in self.onebody[4::4]:\n            element_number.append(line[0])\n        first = True\n        for lineno in list(range(2,len(self.twobody),2)):\n            if (float(self.twobody[lineno][7]) <= 0.001 and float(self.twobody[lineno+1][6]) <= 0.001):\n                if first:\n                    string += 'reaxff2_bo \\n'\n                    first = False\n                n1, n2 = int(self.twobody[lineno][0]), int(self.twobody[lineno][1])\n                bo3 = 0.0 if math.isclose(1.0, float(self.twobody[lineno+1][1])) else float(self.twobody[lineno+1][1])\n                string += '%-2s core %-2s core %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f\\n' % (element_number[n1], element_number[n2], float(self.twobody[lineno+1][4]), float(self.twobody[lineno+1][5]), bo3, float(self.twobody[lineno+1][2]), float(self.twobody[lineno][6]), float(self.twobody[lineno][8]))\n\n\n        #BOND PARAMETERS - BOND KCAL\n        element_number = ['X']\n        for line in self.onebody[4::4]:\n            element_number.append(line[0])\n        string += 'reaxff2_bond kcal \\n'\n        for lineno in list(range(2,len(self.twobody),2)):\n            n1, n2 = int(self.twobody[lineno][0]), int(self.twobody[lineno][1])\n            string += '%-2s core %-2s core %8.4f %8.4f %8.4f %8.4f %8.4f\\n' % (element_number[n1], element_number[n2], float(self.twobody[lineno][2]), float(self.twobody[lineno][3]), float(self.twobody[lineno][4]), float(self.twobody[lineno][5]), float(self.twobody[lineno+1][0]))\n\n        #BOND PARAMETERS - BOND OVER\n        element_number = ['X']\n        for line in self.onebody[4::4]:\n            element_number.append(line[0])\n        string += 'reaxff2_over \\n'\n        for lineno in list(range(2,len(self.twobody),2)):\n            n1, n2 = int(self.twobody[lineno][0]), int(self.twobody[lineno][1])\n            string += '%-2s core %-2s core %8.4f \\n' % (element_number[n1], element_number[n2], float(self.twobody[lineno][9]))\n\n        #BOND PARAMETERS - BOND PEN KCAL\n        element_number = ['X']\n        for line in self.onebody[4::4]:\n            element_number.append(line[0])\n        first = True\n        for lineno in list(range(2,len(self.twobody),2)):\n            if float(self.twobody[lineno+1][7]) > 0.0:\n                if first:\n                    string += 'reaxff2_pen kcal\\n'\n                    first = False\n                n1, n2 = int(self.twobody[lineno][0]), int(self.twobody[lineno][1])\n                string += '%-2s core %-2s core %8.4f %8.4f %8.4f\\n' % (element_number[n1], element_number[n2], float(self.twobody[lineno+1][7]), float(self.general[14][0]), 1.0)\n\n\n        #BOND PARAMETERS - BOND MORSE KCAL\n        element_number = ['X']\n        for line in self.onebody[4::4]:\n            element_number.append(line[0])\n        string += 'reaxff2_morse kcal\\n'\n        for line in self.offdiagonal[1:]:\n            n1, n2 = int(line[0]), int(line[1])\n            string += '%-2s core %-2s core %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f\\n' % (element_number[n1], element_number[n2], float(line[2]), float(line[4]), float(line[3]), float(line[5]), float(line[6]), float(line[7]))\n\n\n        #ANGLE PARAMETERS\n        string += '#\\n'\n        string += '#  Angle parameters \\n'\n        string += '#\\n'\n\n\n        #ANGLE PARAMETERS - ANGLE KCAL\n        element_number = ['X']\n        for line in self.onebody[4::4]:\n            element_number.append(line[0])\n        string += 'reaxff3_angle kcal\\n'\n        for line in self.threebody[1:]:\n            n2, n1, n3 = int(line[0]), int(line[1]), int(line[2])\n            if float(line[4]) > 0.0:\n                string += '%-2s core %-2s core %-2s core %8.4f %8.4f %8.4f %8.4f %8.4f\\n' % (element_number[n1], element_number[n2], element_number[n3], float(line[3]), float(line[4]), float(line[5]), float(line[9]), float(line[7]))\n\n        #ANGLE PARAMETERS - PENALTY KCAL\n        element_number = ['X']\n        for line in self.onebody[4::4]:\n            element_number.append(line[0])\n        string += 'reaxff3_penalty kcal \\n'\n        for line in self.threebody[1:]:\n            n2, n1, n3 = int(line[0]), int(line[1]), int(line[2])\n            string += '%-2s core %-2s core %-2s core %8.4f\\n' % (element_number[n1], element_number[n2], element_number[n3], float(line[8]))\n\n        #ANGLE PARAMETERS - CONJUGATION KCAL\n        element_number = ['X']\n        for line in self.onebody[4::4]:\n            element_number.append(line[0])\n        string += 'reaxff3_conjugation kcal \\n'\n        for line in self.threebody[1:]:\n            if np.absolute(float(line[6])) > 1.0e-4:\n                n2, n1, n3 = int(line[0]), int(line[1]), int(line[2])\n                string += '%-2s core %-2s core %-2s core %8.4f %8.4f %8.4f %8.4f\\n' % (element_number[n1], element_number[n2], element_number[n3], float(line[6]), float(self.general[3][0]), float(self.general[39][0]), float(self.general[31][0]))\n\n\n        #HBOND PARAMETERS\n        string += '#\\n'\n        string += '#  Hydrogen bond parameters \\n'\n        string += '#\\n'\n\n        #HBOND PARAMETERS - CONJUGATION KCAL\n        element_number = ['X']\n        for line in self.onebody[4::4]:\n            element_number.append(line[0])\n        string += 'reaxff3_hbond kcal \\n'\n        for line in self.hbond[1:]:\n            n2, n1, n3 = int(line[0]), int(line[1]), int(line[2])\n            string += '%-2s core %-2s core %-2s core %8.4f %8.4f %8.4f %8.4f\\n' % (element_number[n1], element_number[n2], element_number[n3], float(line[3]), float(line[4]), float(line[5]), float(line[6]))\n\n\n        #TORSION PARAMETERS\n        string += '#\\n'\n        string += '#  Torsion parameters \\n'\n        string += '#\\n'\n\n        #HBOND PARAMETERS - CONJUGATION KCAL\n        element_number = ['X']\n        for line in self.onebody[4::4]:\n            element_number.append(line[0])\n        string += 'reaxff4_torsion kcal \\n'\n        for line in self.fourbody[1:]:\n            n1, n2, n3, n4 = int(line[0]), int(line[1]), int(line[2]), int(line[3])\n            string += '%-2s core %-2s core %-2s core %-2s core %8.4f %8.4f %8.4f %8.4f %8.4f\\n' % (element_number[n1], element_number[n2], element_number[n3], element_number[n4], float(line[4]), float(line[5]), float(line[6]), float(line[7]), float(line[8]))\n\n\n        #GENERAL PARAMETERS - Thresholds and cutoffs\n        string += '\\n\\n'\n        string += 'reaxfftol {0:.12f}'.format(self.bo_threshold)\n        string += '\\n\\n'\n\n        if outfilename is not None:\n            libfile = open(outfilename, 'w')\n            libfile.write(string)\n            libfile.close()\n            return\n        else:\n            return string\n", "meta": {"hexsha": "4f9c6c81184cbbf7f9fa6e1d91927dc60e031c0d", "size": 48050, "ext": "py", "lang": "Python", "max_stars_repo_path": "ezff/utils/reaxff.py", "max_stars_repo_name": "sctiwari/EZFF_ASE", "max_stars_repo_head_hexsha": "94710d4cf778ff2db5e6df0cd6d10d92e1b98afe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-01-22T21:22:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-02T22:50:40.000Z", "max_issues_repo_path": "ezff/utils/reaxff.py", "max_issues_repo_name": "ElsevierSoftwareX/SOFTX-D-20-00066", "max_issues_repo_head_hexsha": "b43f8bbb1321d7ed3eeec4f8bb894fe431779433", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2019-01-14T18:33:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-08T22:10:11.000Z", "max_forks_repo_path": "ezff/utils/reaxff.py", "max_forks_repo_name": "ElsevierSoftwareX/SOFTX-D-20-00066", "max_forks_repo_head_hexsha": "b43f8bbb1321d7ed3eeec4f8bb894fe431779433", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-03-24T23:43:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-12T13:45:08.000Z", "avg_line_length": 44.9906367041, "max_line_length": 299, "alphanum_fraction": 0.5660561915, "include": true, "reason": "import numpy", "num_tokens": 13859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.17775843308769568}}
{"text": "# coding: utf-8\n# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\nfrom __future__ import division, unicode_literals\n\nimport six\nimport ruamel.yaml as yaml\nimport os\nimport json\n\n\"\"\"\nThis module provides classes to perform analyses of\nthe local environments (e.g., finding near neighbors)\nof single sites in molecules and structures.\nTo do:\n- Insert LocalStructOrderParas class here.\n\"\"\"\n\n__author__ = \"Shyue Ping Ong, Geoffroy Hautier, Sai Jayaraman,\"+\\\n    \" Nils E. R. Zimmermann, Bharat Medasani\"\n__copyright__ = \"Copyright 2011, The Materials Project\"\n__version__ = \"1.0\"\n__maintainer__ = \"Nils E. R. Zimmermann\"\n__email__ = \"nils.e.r.zimmermann@gmail.com\"\n__status__ = \"Production\"\n__date__ = \"August 17, 2017\"\n\nfrom math import pow, pi, asin, atan, sqrt, exp, cos, acos\nimport numpy as np\n\nfrom bisect import bisect_left\nfrom scipy.spatial import Voronoi\nfrom pymatgen import Element\nfrom pymatgen.core.structure import Structure\nfrom pymatgen.util.num import abs_cap\nfrom pymatgen.analysis.bond_valence import BV_PARAMS\nfrom pymatgen.analysis.structure_analyzer import OrderParameters\n\n\nfile_dir = os.path.dirname(__file__)\nrad_file = os.path.join(file_dir, 'ionic_radii.json')\nwith open(rad_file, 'r') as fp:\n    _ion_radii = json.load(fp)\n\n\nclass ValenceIonicRadiusEvaluator(object):\n    \"\"\"\n    Computes site valences and ionic radii for a structure using bond valence\n    analyzer\n\n    Args:\n        structure: pymatgen.core.structure.Structure\n    \"\"\"\n\n    def __init__(self, structure):\n        self._structure = structure.copy()\n        self._valences = self._get_valences()\n        self._ionic_radii = self._get_ionic_radii()\n\n    @property\n    def radii(self):\n        \"\"\"\n        List of ionic radii of elements in the order of sites.\n        \"\"\"\n        el = [site.species_string for site in self._structure.sites]\n        radii_dict = dict(zip(el, self._ionic_radii))\n        #print radii_dict\n        return radii_dict\n\n    @property\n    def valences(self):\n        \"\"\"\n        List of oxidation states of elements in the order of sites.\n        \"\"\"\n        el = [site.species_string for site in self._structure.sites]\n        valence_dict = dict(zip(el, self._valences))\n        return valence_dict\n\n    @property\n    def structure(self):\n        \"\"\"\n        Returns oxidation state decorated structure.\n        \"\"\"\n        return self._structure.copy()\n\n\n    def _get_ionic_radii(self):\n        \"\"\"\n        Computes ionic radii of elements for all sites in the structure.\n        If valence is zero, atomic radius is used.\n        \"\"\"\n        radii = []\n        vnn = VoronoiNN() # self._structure)\n\n        def nearest_key(sorted_vals, key):\n            i = bisect_left(sorted_vals, key)\n            if i == len(sorted_vals):\n                return sorted_vals[-1]\n            if i == 0:\n                return sorted_vals[0]\n            before = sorted_vals[i-1]\n            after = sorted_vals[i]\n            if after-key < key-before:\n                return after\n            else:\n                return before\n\n        for i in range(len(self._structure.sites)):\n            site = self._structure.sites[i]\n            if isinstance(site.specie,Element):\n                radius = site.specie.atomic_radius\n                # Handle elements with no atomic_radius\n                # by using calculated values instead.\n                if radius is None:\n                    radius = site.specie.atomic_radius_calculated\n                if radius is None:\n                    raise ValueError(\n                            \"cannot assign radius to element {}\".format(\n                            site.specie))\n                radii.append(radius)\n                continue\n\n            el = site.specie.symbol\n            oxi_state = int(round(site.specie.oxi_state))\n            coord_no = int(round(vnn.get_cn(self._structure, i)))\n            try:\n                tab_oxi_states = sorted(map(int, _ion_radii[el].keys()))\n                oxi_state = nearest_key(tab_oxi_states, oxi_state)\n                radius = _ion_radii[el][str(oxi_state)][str(coord_no)]\n            except KeyError:\n                if vnn.get_cn(self._structure, i)-coord_no > 0:\n                    new_coord_no = coord_no + 1\n                else:\n                    new_coord_no = coord_no - 1\n                try:\n                    radius = _ion_radii[el][str(oxi_state)][str(new_coord_no)]\n                    coord_no = new_coord_no\n                except:\n                    tab_coords = sorted(map(int, _ion_radii[el][str(oxi_state)].keys()))\n                    new_coord_no = nearest_key(tab_coords, coord_no)\n                    i = 0\n                    for val in tab_coords:\n                        if  val > coord_no:\n                            break\n                        i = i + 1\n                    if i == len(tab_coords):\n                        key = str(tab_coords[-1])\n                        radius = _ion_radii[el][str(oxi_state)][key]\n                    elif i == 0:\n                        key = str(tab_coords[0])\n                        radius = _ion_radii[el][str(oxi_state)][key]\n                    else:\n                        key = str(tab_coords[i-1])\n                        radius1 = _ion_radii[el][str(oxi_state)][key]\n                        key = str(tab_coords[i])\n                        radius2 = _ion_radii[el][str(oxi_state)][key]\n                        radius = (radius1+radius2)/2\n\n            #implement complex checks later\n            radii.append(radius)\n        return radii\n\n    def _get_valences(self):\n        \"\"\"\n        Computes ionic valences of elements for all sites in the structure.\n        \"\"\"\n        try:\n            bv = BVAnalyzer()\n            self._structure = bv.get_oxi_state_decorated_structure(self._structure)\n            valences = bv.get_valences(self._structure)\n        except:\n            try:\n                bv = BVAnalyzer(symm_tol=0.0)\n                self._structure = bv.get_oxi_state_decorated_structure(self._structure)\n                valences = bv.get_valences(self._structure)\n            except:\n                valences = []\n                for site in self._structure.sites:\n                    if len(site.specie.common_oxidation_states) > 0:\n                        valences.append(site.specie.common_oxidation_states[0])\n                    # Handle noble gas species\n                    # which have no entries in common_oxidation_states.\n                    else:\n                        valences.append(0)\n                if sum(valences):\n                    valences = [0]*self._structure.num_sites\n                else:\n                    self._structure.add_oxidation_state_by_site(valences)\n                #raise\n\n        #el = [site.specie.symbol for site in self._structure.sites]\n        #el = [site.species_string for site in self._structure.sites]\n        #el = [site.specie for site in self._structure.sites]\n        #valence_dict = dict(zip(el, valences))\n        #print valence_dict\n        return valences\n\n\nclass NearNeighbors(object):\n    \"\"\"\n    Base class to determine near neighbors that typically include nearest\n    neighbors and others that are within some tolerable distance.\n    \"\"\"\n\n    def __init__(self):\n        pass\n\n    def get_cn(self, structure, n, use_weights=False):\n        \"\"\"\n        Get coordination number, CN, of site with index n in structure.\n\n        Args:\n            structure (Structure): input structure.\n            n (integer): index of site for which to determine CN.\n            use_weights (boolean): flag indicating whether (True)\n                to use weights for computing the coordination number\n                or not (False, default: each coordinated site has equal\n                weight).\n        Returns:\n            cn (integer or float): coordination number.\n        \"\"\"\n\n        siw = self.get_nn_info(structure, n)\n        return sum([e['weight'] for e in siw]) if use_weights else len(siw)\n\n    def get_nn(self, structure, n):\n        \"\"\"\n        Get near neighbors of site with index n in structure.\n\n        Args:\n            structure (Structure): input structure.\n            n (integer): index of site in structure for which to determine\n                    neighbors.\n        Returns:\n            sites (list of Site objects): near neighbors.\n        \"\"\"\n\n        return [e['site'] for e in self.get_nn_info(structure, n)]\n\n    def get_weights_of_nn_sites(self, n):\n        \"\"\"\n        Get weight associated with each near neighbor of site with\n        index n in structure.\n\n        Args:\n            structure (Structure): input structure.\n            n (integer): index of site for which to determine the weights.\n        Returns:\n            weights (list of floats): near-neighbor weights.\n        \"\"\"\n\n        return [e['weight'] for e in self.get_nn_info(structure, n)]\n\n    def get_nn_images(self, structure, n):\n        \"\"\"\n        Get image location of all near neighbors of site with index n in\n        structure.\n\n        Args:\n            structure (Structure): input structure.\n            n (integer): index of site for which to determine the image\n                location of near neighbors.\n        Returns:\n            images (list of 3D integer array): image locations of\n                near neighbors.\n        \"\"\"\n\n        return [e['image'] for e in self.get_nn_info(structure, n)]\n\n    def get_nn_info(self, structure, n):\n        \"\"\"\n        Get all near-neighbor sites as well as the associated image locations\n        and weights of the site with index n.\n\n        Args:\n            structure (Structure): input structure.\n            n (integer): index of site for which to determine near-neighbor\n                information.\n \n        Returns:\n            siw (list of dicts): each dictionary provides information\n                about a single near neighbor, where key 'site' gives\n                access to the corresponding Site object, 'image' gives\n                the image location, and 'weight' provides the weight\n                that a given near-neighbor site contributes\n                to the coordination number (1 or smaller), 'site_index'\n                gives index of the corresponding site in\n                the original structure.\n        \"\"\"\n\n        raise NotImplementedError(\"get_nn_info(structure, n)\"\n                \" is not defined!\")\n\n    @staticmethod\n    def _get_image(frac_coords):\n        \"\"\"Private convenience method for get_nn_info,\n        gives lattice image from provided PeriodicSite.\"\"\"\n        return [int(f) if f >= 0 else int(f - 1)\n                for f in frac_coords]\n\n    @staticmethod\n    def _get_original_site(structure, site):\n        \"\"\"Private convenience method for get_nn_info,\n        gives original site index from ProvidedPeriodicSite.\"\"\"\n        is_periodic_image = [site.is_periodic_image(s) for s in structure]\n        return is_periodic_image.index(True)\n\nclass VoronoiNN(NearNeighbors):\n    \"\"\"\n    Uses a Voronoi algorithm to determine near neighbors for each site in a\n    structure.\n\n    Args:\n        tol (float): tolerance parameter for near-neighbor finding\n            (default: 0).\n        targets (Element or list of Elements): target element(s).\n        cutoff (float): cutoff radius in Angstrom to look for near-neighbor\n            atoms. Defaults to 10.0.\n        allow_pathological (bool): whether to allow infinite vertices in\n            determination of Voronoi coordination.\n    \"\"\"\n\n    def __init__(self, tol=0, targets=None, cutoff=10.0,\n                 allow_pathological=False):\n        self.tol = tol\n        self.cutoff = cutoff\n        self.allow_pathological = allow_pathological\n        self.targets = targets\n\n    def get_voronoi_polyhedra(self, structure, n):\n        \"\"\"\n        Gives a weighted polyhedra around a site. This uses the Voronoi\n        construction with solid angle weights.\n        See ref: A Proposed Rigorous Definition of Coordination Number,\n        M. O'Keeffe, Acta Cryst. (1979). A35, 772-775\n\n        Args:\n            structure (Structure): structure for which to evaluate the\n                coordination environment.\n            n (integer): site index.\n\n        Returns:\n            A dict of sites sharing a common Voronoi facet with the site\n            n and their solid angle weights\n        \"\"\"\n        if self.targets is None:\n            targets = structure.composition.elements\n        else:\n            targets = self.targets\n        center = structure[n]\n        neighbors = structure.get_sites_in_sphere(\n            center.coords, self.cutoff)\n        neighbors = [i[0] for i in sorted(neighbors, key=lambda s: s[1])]\n        qvoronoi_input = [s.coords for s in neighbors]\n        voro = Voronoi(qvoronoi_input)\n        all_vertices = voro.vertices\n\n        results = {}\n        for nn, vind in voro.ridge_dict.items():\n            if 0 in nn:\n                if -1 in vind:\n                    if self.allow_pathological:\n                        continue\n                    else:\n                        raise RuntimeError(\"This structure is pathological,\"\n                                           \" infinite vertex in the voronoi \"\n                                           \"construction\")\n\n                facets = [all_vertices[i] for i in vind]\n                results[neighbors[sorted(nn)[1]]] = solid_angle(\n                    center.coords, facets)\n\n        maxangle = max(results.values())\n\n        resultweighted = {}\n        for nn, angle in results.items():\n            # is nn site is ordered use \"nn.specie\" to get species, else use \"nn.species_and_occu\" to get species\n            if nn.is_ordered:\n                if nn.specie in targets:\n                    resultweighted[nn] = angle / maxangle\n            else:  # is nn site is disordered\n                for disordered_sp in nn.species_and_occu.keys():\n                    if disordered_sp in targets:\n                        resultweighted[nn] = angle / maxangle\n\n        return resultweighted\n\n\n    def get_nn_info(self, structure, n):\n        \"\"\"\"\n        Get all near-neighbor sites as well as the associated image locations\n        and weights of the site with index n in structure\n        using Voronoi decomposition.\n\n        Args:\n            structure (Structure): input structure.\n            n (integer): index of site for which to determine near-neighbor\n                sites.\n \n        Returns:\n            siw (list of tuples (Site, array, float)): tuples, each one\n                of which represents a coordinated site, its image location,\n                and its weight.\n        \"\"\"\n\n        if self.targets is None:\n            targets = structure.composition.elements\n        else:\n            targets = self.targets\n        siw = []\n        for site, weight in self.get_voronoi_polyhedra(\n                structure, n).items():\n            if weight > self.tol and site.specie in targets:\n                siw.append({'site': site,\n                            'image': self._get_image(site.frac_coords),\n                            'weight': weight,\n                            'site_index': self._get_original_site(structure, site)})\n        return siw\n\n\nclass JMolNN(NearNeighbors):\n    \"\"\"\n    Determine near-neighbor sites and coordination number using an emulation\n    of JMol's default autoBond() algorithm. This version of the algorithm\n    does not take into account any information regarding known charge\n    states.\n\n    Args:\n        tol (float): tolerance parameter for bond determination\n            (default: 1E-3).\n        el_radius_updates: (dict) symbol->float to override default atomic \n            radii table values \n    \"\"\"\n\n    def __init__(self, tol=1E-3, el_radius_updates=None):\n\n        self.tol = tol\n\n        # Load elemental radii table\n        bonds_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),\n                                  \"bonds_jmol_ob.yaml\")\n        with open(bonds_file, 'r') as f:\n            self.el_radius = yaml.safe_load(f)\n\n        # Update any user preference elemental radii\n        if el_radius_updates:\n            self.el_radius.update(el_radius_updates)\n\n    def get_max_bond_distance(self, el1_sym, el2_sym, constant=0.56):\n        \"\"\"\n        Use JMol algorithm to determine bond length from atomic parameters\n        Args:\n            el1_sym: (str) symbol of atom 1\n            el2_sym: (str) symbol of atom 2\n            constant: (float) factor to tune model\n\n        Returns: (float) max bond length\n\n        \"\"\"\n        return sqrt(\n            (self.el_radius[el1_sym] + self.el_radius[el2_sym] + constant) ** 2)\n\n    def get_nn_info(self, structure, n):\n        \"\"\"\n        Get all near-neighbor sites as well as the associated image locations\n        and weights of the site with index n using the bond identification\n        algorithm underlying JMol.\n\n        Args:\n            structure (Structure): input structure.\n            n (integer): index of site for which to determine near\n                neighbors.\n \n        Returns:\n            siw (list of tuples (Site, array, float)): tuples, each one\n                of which represents a neighbor site, its image location,\n                and its weight.\n        \"\"\"\n\n        site = structure[n]\n\n        # Determine relevant bond lengths based on atomic radii table\n        bonds = {}\n        for el in structure.composition.elements:\n            bonds[site.specie, el] = self.get_max_bond_distance(\n                site.specie.symbol, el.symbol)\n\n        # Search for neighbors up to max bond length + tolerance\n        max_rad = max(bonds.values()) + self.tol\n        min_rad = min(bonds.values())\n\n        siw = []\n        for neighb, dist in structure.get_neighbors(site, max_rad):\n            # Confirm neighbor based on bond length specific to atom pair\n            if dist <= bonds[(site.specie, neighb.specie)] + self.tol:\n                weight = min_rad / dist\n                siw.append({'site': neighb,\n                            'image': self._get_image(neighb.frac_coords),\n                            'weight': weight,\n                            'site_index': self._get_original_site(structure, neighb)})\n        return siw\n\n\nclass MinimumDistanceNN(NearNeighbors):\n    \"\"\"\n    Determine near-neighbor sites and coordination number using the\n    nearest neighbor(s) at distance, d_min, plus all neighbors\n    within a distance (1 + delta) * d_min, where delta is a\n    (relative) distance tolerance parameter.\n\n    Args:\n        tol (float): tolerance parameter for neighbor identification\n            (default: 0.1).\n        cutoff (float): cutoff radius in Angstrom to look for trial\n            near-neighbor sites (default: 10.0).\n    \"\"\"\n\n    def __init__(self, tol=0.1, cutoff=10.0):\n\n        self.tol = tol\n        self.cutoff = cutoff\n\n    def get_nn_info(self, structure, n):\n        \"\"\"\n        Get all near-neighbor sites as well as the associated image locations\n        and weights of the site with index n using the closest neighbor\n        distance-based method.\n\n        Args:\n            structure (Structure): input structure.\n            n (integer): index of site for which to determine near\n                neighbors.\n \n        Returns:\n            siw (list of tuples (Site, array, float)): tuples, each one\n                of which represents a neighbor site, its image location,\n                and its weight.\n        \"\"\"\n\n        site = structure[n]\n        neighs_dists = structure.get_neighbors(site, self.cutoff)\n        min_dist = min([dist for neigh, dist in neighs_dists])\n\n        siw = []\n        for s, dist in neighs_dists:\n            if dist < (1.0 + self.tol) * min_dist:\n                w = min_dist / dist\n                siw.append({'site': s,\n                            'image': self._get_image(s.frac_coords),\n                            'weight': w,\n                            'site_index': self._get_original_site(structure, s)})\n        return siw\n\n\nclass MinimumOKeeffeNN(NearNeighbors):\n    \"\"\"\n    Determine near-neighbor sites and coordination number using the\n    neighbor(s) at closest relative distance, d_min_OKeffee, plus some\n    relative tolerance, where bond valence parameters from O'Keeffe's\n    bond valence method (J. Am. Chem. Soc. 1991, 3226-3229) are used\n    to calculate relative distances.\n\n    Args:\n        tol (float): tolerance parameter for neighbor identification\n            (default: 0.1).\n        cutoff (float): cutoff radius in Angstrom to look for trial\n            near-neighbor sites (default: 10.0).\n    \"\"\"\n\n    def __init__(self, tol=0.1, cutoff=10.0):\n\n        self.tol = tol\n        self.cutoff = cutoff\n\n    def get_nn_info(self, structure, n):\n        \"\"\"\n        Get all near-neighbor sites as well as the associated image locations\n        and weights of the site with index n using the closest relative\n        neighbor distance-based method with O'Keeffe parameters.\n\n        Args:\n            structure (Structure): input structure.\n            n (integer): index of site for which to determine near\n                neighbors.\n \n        Returns:\n            siw (list of tuples (Site, array, float)): tuples, each one\n                of which represents a neighbor site, its image location,\n                and its weight.\n        \"\"\"\n\n        site = structure[n]\n        neighs_dists = structure.get_neighbors(site, self.cutoff)\n        try:\n            eln = site.specie.element\n        except:\n            eln = site.species_string\n\n        reldists_neighs = []\n        for neigh, dist in neighs_dists:\n            try:\n                el2 = neigh.specie.element\n            except:\n                el2 = neigh.species_string\n            reldists_neighs.append([dist / get_okeeffe_distance_prediction(\n                    eln, el2), neigh])\n\n        siw = []\n        min_reldist = min([reldist for reldist, neigh in reldists_neighs])\n        for reldist, s in reldists_neighs:\n            if reldist < (1.0 + self.tol) * min_reldist:\n                w = min_reldist / reldist\n                siw.append({'site': s,\n                            'image': self._get_image(s.frac_coords),\n                            'weight': w,\n                            'site_index': self._get_original_site(structure, s)})\n\n        return siw\n\n\nclass MinimumVIRENN(NearNeighbors):\n    \"\"\"\n    Determine near-neighbor sites and coordination number using the\n    neighbor(s) at closest relative distance, d_min_VIRE, plus some\n    relative tolerance, where atom radii from the\n    ValenceIonicRadiusEvaluator (VIRE) are used\n    to calculate relative distances.\n\n    Args:\n        tol (float): tolerance parameter for neighbor identification\n            (default: 0.1).\n        cutoff (float): cutoff radius in Angstrom to look for trial\n            near-neighbor sites (default: 10.0).\n    \"\"\"\n\n    def __init__(self, tol=0.1, cutoff=10.0):\n\n        self.tol = tol\n        self.cutoff = cutoff\n\n    def get_nn_info(self, structure, n):\n        \"\"\"\n        Get all near-neighbor sites as well as the associated image locations\n        and weights of the site with index n using the closest relative\n        neighbor distance-based method with VIRE atomic/ionic radii.\n\n        Args:\n            structure (Structure): input structure.\n            n (integer): index of site for which to determine near\n                neighbors.\n\n        Returns:\n            siw (list of tuples (Site, array, float)): tuples, each one\n                of which represents a neighbor site, its image location,\n                and its weight.\n        \"\"\"\n\n        vire = ValenceIonicRadiusEvaluator(structure)\n        site = vire.structure[n]\n        neighs_dists = vire.structure.get_neighbors(site, self.cutoff)\n        rn = vire.radii[vire.structure[n].species_string]\n\n        reldists_neighs = []\n        for neigh, dist in neighs_dists:\n            reldists_neighs.append([dist / (\n                    vire.radii[neigh.species_string] + rn), neigh])\n\n        siw = []\n        min_reldist = min([reldist for reldist, neigh in reldists_neighs])\n        for reldist, s in reldists_neighs:\n            if reldist < (1.0 + self.tol) * min_reldist:\n                w = min_reldist / reldist\n                siw.append({'site': s,\n                            'image': self._get_image(s.frac_coords),\n                            'weight': w,\n                            'site_index': self._get_original_site(structure, s)})\n\n        return siw\n\n\ndef solid_angle(center, coords):\n    \"\"\"\n    Helper method to calculate the solid angle of a set of coords from the\n    center.\n\n    Args:\n        center (3x1 array): Center to measure solid angle from.\n        coords (Nx3 array): List of coords to determine solid angle.\n\n    Returns:\n        The solid angle.\n    \"\"\"\n    o = np.array(center)\n    r = [np.array(c) - o for c in coords]\n    r.append(r[0])\n    n = [np.cross(r[i + 1], r[i]) for i in range(len(r) - 1)]\n    n.append(np.cross(r[1], r[0]))\n    vals = []\n    for i in range(len(n) - 1):\n        v = -np.dot(n[i], n[i + 1]) \\\n            / (np.linalg.norm(n[i]) * np.linalg.norm(n[i + 1]))\n        vals.append(acos(abs_cap(v)))\n    phi = sum(vals)\n    return phi + (3 - len(r)) * pi\n\n\ndef get_okeeffe_params(el_symbol):\n    \"\"\"\n    Returns the elemental parameters related to atom size and\n    electronegativity which are used for estimating bond-valence\n    parameters (bond length) of pairs of atoms on the basis of data\n    provided in 'Atoms Sizes and Bond Lengths in Molecules and Crystals'\n    (O'Keeffe & Brese, 1991).\n\n    Args:\n        el_symbol (str): element symbol.\n    Returns:\n        (dict): atom-size ('r') and electronegativity-related ('c')\n                parameter.\n    \"\"\"\n\n    el = Element(el_symbol)\n    if el not in list(BV_PARAMS.keys()):\n        raise RuntimeError(\"Could not find O'Keeffe parameters for element\"\n                           \" \\\"{}\\\" in \\\"BV_PARAMS\\\"dictonary\"\n                           \" provided by pymatgen\".format(el_symbol))\n\n    return BV_PARAMS[el]\n\n\ndef get_okeeffe_distance_prediction(el1, el2):\n    \"\"\"\n    Returns an estimate of the bond valence parameter (bond length) using\n    the derived parameters from 'Atoms Sizes and Bond Lengths in Molecules\n    and Crystals' (O'Keeffe & Brese, 1991). The estimate is based on two\n    experimental parameters: r and c. The value for r  is based off radius,\n    while c is (usually) the Allred-Rochow electronegativity. Values used\n    are *not* generated from pymatgen, and are found in\n    'okeeffe_params.json'.\n\n    Args:\n        el1, el2 (Element): two Element objects\n    Returns:\n        a float value of the predicted bond length\n    \"\"\"\n    el1_okeeffe_params = get_okeeffe_params(el1)\n    el2_okeeffe_params = get_okeeffe_params(el2)\n\n    r1 = el1_okeeffe_params['r']\n    r2 = el2_okeeffe_params['r']\n    c1 = el1_okeeffe_params['c']\n    c2 = el2_okeeffe_params['c']\n\n    return r1 + r2 - r1 * r2 * pow(\n            sqrt(c1) - sqrt(c2), 2) / (c1 * r1 + c2 * r2)\n\n\ndef get_neighbors_of_site_with_index(struct, n, approach=\"min_dist\", delta=0.1, \\\n        cutoff=10.0):\n    \"\"\"\n    Returns the neighbors of a given site using a specific neighbor-finding\n    method.\n\n    Args:\n        struct (Structure): input structure.\n        n (int): index of site in Structure object for which motif type\n                is to be determined.\n        approach (str): type of neighbor-finding approach, where\n              \"min_dist\" will use the MinimumDistanceNN class,\n              \"voronoi\" the VoronoiNN class, \"min_OKeeffe\" the\n              MinimumOKeeffe class, and \"min_VIRE\" the MinimumVIRENN class.\n        delta (float): tolerance involved in neighbor finding.\n        cutoff (float): (large) radius to find tentative neighbors.\n\n    Returns: neighbor sites.\n    \"\"\"\n\n    if approach == \"min_dist\":\n        return MinimumDistanceNN(tol=delta, cutoff=cutoff).get_nn(\n                struct, n)\n    elif approach == \"voronoi\":\n        return VoronoiNN(tol=delta, cutoff=cutoff).get_nn(\n                struct, n)\n    elif approach == \"min_OKeeffe\":\n        return MinimumOKeeffeNN(tol=delta, cutoff=cutoff).get_nn(\n                struct, n)\n    elif approach == \"min_VIRE\":\n        return MinimumVIRENN(tol=delta, cutoff=cutoff).get_nn(\n                struct, n)\n    else:\n        raise RuntimeError(\"unsupported neighbor-finding method ({}).\".format(\n                approach))\n\n\ndef site_is_of_motif_type(struct, n, approach=\"min_dist\", delta=0.1, \\\n        cutoff=10.0, thresh=None):\n    \"\"\"\n    Returns the motif type of the site with index n in structure struct;\n    currently featuring \"tetrahedral\", \"octahedral\", \"bcc\", and \"cp\"\n    (close-packed: fcc and hcp) as well as \"square pyramidal\" and\n    \"trigonal bipyramidal\".  If the site is not recognized,\n    \"unrecognized\" is returned.  If a site should be assigned to two\n    different motifs, \"multiple assignments\" is returned.\n\n    Args:\n        struct (Structure): input structure.\n        n (int): index of site in Structure object for which motif type\n                is to be determined.\n        approach (str): type of neighbor-finding approach, where\n              \"min_dist\" will use the MinimumDistanceNN class,\n              \"voronoi\" the VoronoiNN class, \"min_OKeeffe\" the\n              MinimumOKeeffe class, and \"min_VIRE\" the MinimumVIRENN class.\n        delta (float): tolerance involved in neighbor finding.\n        cutoff (float): (large) radius to find tentative neighbors.\n        thresh (dict): thresholds for motif criteria (currently, required\n                keys and their default values are \"qtet\": 0.5,\n                \"qoct\": 0.5, \"qbcc\": 0.5, \"q6\": 0.4).\n\n    Returns: motif type (str).\n    \"\"\"\n\n    if thresh is None:\n        thresh = {\n            \"qtet\": 0.5, \"qoct\": 0.5, \"qbcc\": 0.5, \"q6\": 0.4,\n            \"qtribipyr\": 0.8, \"qsqpyr\": 0.8}\n\n    ops = OrderParameters([\n            \"cn\", \"tet\", \"oct\", \"bcc\", \"q6\", \"sq_pyr\", \"tri_bipyr\"])\n\n    neighs_cent = get_neighbors_of_site_with_index(\n            struct, n, approach=approach, delta=delta, cutoff=cutoff)\n    neighs_cent.append(struct.sites[n])\n    opvals = ops.get_order_parameters(\n            neighs_cent, len(neighs_cent)-1, indices_neighs=[\n            i for i in range(len(neighs_cent)-1)])\n    cn = int(opvals[0] + 0.5)\n    motif_type = \"unrecognized\"\n    nmotif = 0\n\n    if cn == 4 and opvals[1] > thresh[\"qtet\"]:\n        motif_type = \"tetrahedral\"\n        nmotif += 1\n    if cn == 5 and opvals[5] > thresh[\"qsqpyr\"]:\n       motif_type = \"square pyramidal\"\n       nmotif += 1\n    if cn == 5 and opvals[6] > thresh[\"qtribipyr\"]:\n       motif_type = \"trigonal bipyramidal\"\n       nmotif += 1\n    if cn == 6 and opvals[2] > thresh[\"qoct\"]:\n        motif_type = \"octahedral\"\n        nmotif += 1\n    if cn == 8 and (opvals[3] > thresh[\"qbcc\"] and opvals[1] < thresh[\"qtet\"]):\n        motif_type = \"bcc\"\n        nmotif += 1\n    if cn == 12 and (opvals[4] > thresh[\"q6\"] and opvals[1] < thresh[\"q6\"] and \\\n                                 opvals[2] < thresh[\"q6\"] and opvals[3] < thresh[\"q6\"]):\n        motif_type = \"cp\"\n        nmotif += 1\n\n    if nmotif > 1:\n        motif_type = \"multiple assignments\"\n\n    return motif_type\n", "meta": {"hexsha": "3d835064a46c156ee43b8805827dd74c5558a9ab", "size": 31294, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymatgen/analysis/local_env.py", "max_stars_repo_name": "ltalirz/pymatgen", "max_stars_repo_head_hexsha": "894cdb2ec7b9bd74f0ac3cdad40d144203ccdcf6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pymatgen/analysis/local_env.py", "max_issues_repo_name": "ltalirz/pymatgen", "max_issues_repo_head_hexsha": "894cdb2ec7b9bd74f0ac3cdad40d144203ccdcf6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pymatgen/analysis/local_env.py", "max_forks_repo_name": "ltalirz/pymatgen", "max_forks_repo_head_hexsha": "894cdb2ec7b9bd74f0ac3cdad40d144203ccdcf6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1780346821, "max_line_length": 113, "alphanum_fraction": 0.5861187448, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547238, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.17775842122177224}}
{"text": "import os\nimport subprocess\nimport numpy as np\nimport matplotlib.pyplot as pyplot\nimport matplotlib.cm as cm\nfrom matplotlib.colors import Normalize\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom simtk import unit\nimport openmmtools\nfrom cg_openmm.utilities.util import set_box_vectors, get_box_vectors\nfrom simtk.openmm.app.pdbfile import PDBFile\nfrom simtk.openmm.app.dcdfile import DCDFile\nfrom mdtraj.formats import PDBTrajectoryFile\nfrom mdtraj import Topology, Trajectory\nfrom pymbar import timeseries\nfrom scipy.special import erf\nfrom scipy.optimize import minimize_scalar\nimport time\n\nfrom openmmtools.multistate import MultiStateReporter, MultiStateSampler, ReplicaExchangeSampler\nfrom openmmtools.multistate import ReplicaExchangeAnalyzer\n\n# quiet down some citation spam\nMultiStateSampler._global_citation_silence = True\n\nkB = (unit.MOLAR_GAS_CONSTANT_R).in_units_of(unit.kilojoule / (unit.kelvin * unit.mole))\n\ndef make_replica_dcd_files(\n    topology, timestep=5*unit.femtosecond, time_interval=200,\n    output_dir=\"output\", output_data=\"output.nc\", checkpoint_data=\"output_checkpoint.nc\",\n    frame_begin=0, frame_stride=1):\n    \"\"\"\n    Make dcd files from replica exchange simulation trajectory data.\n    \n    :param topology: OpenMM Topology\n    :type topology: `Topology() <https://simtk.org/api_docs/openmm/api4_1/python/classsimtk_1_1openmm_1_1app_1_1topology_1_1Topology.html>`_\n    \n    :param timestep: Time step used in the simulation (default=5*unit.femtosecond)\n    :type timestep: `Quantity() <http://docs.openmm.org/development/api-python/generated/simtk.unit.quantity.Quantity.html>` float * simtk.unit\n    \n    :param time_interval: frequency, in number of time steps, at which positions were recorded (default=200)\n    :type time_interval: int\n    \n    :param output_dir: path to which we will write the output (default='output')\n    :type output_dir: str\n    \n    :param output_data: name of output .nc data file (default='output.nc')\n    :type output_data: str    \n    \n    :param checkpoint_data: name of checkpoint .nc data file (default='output_checkpoint.nc')\n    :type checkpoint_data: str   \n    \n    :param frame_begin: Frame at which to start writing the dcd trajectory (default=0)\n    :type frame_begin: int\n    \n    :param frame_stride: advance by this many time intervals when writing dcd trajectories (default=1)\n    :type frame_stride: int \n    \"\"\"\n    \n    file_list = []\n    \n    output_data_path = os.path.join(output_dir, output_data)\n    \n    # Get number of replicas:\n    reporter = MultiStateReporter(output_data_path, open_mode=\"r\")\n    states = reporter.read_thermodynamic_states()[0]\n    n_replicas=len(states)\n    \n    sampler_states = reporter.read_sampler_states(iteration=0)\n    xunit = sampler_states[0].positions[0].unit\n        \n    for replica_index in range(n_replicas):\n        replica_positions = extract_trajectory(topology, replica_index=replica_index,\n            output_data=output_data_path, checkpoint_data=checkpoint_data,\n            frame_begin=frame_begin, frame_stride=frame_stride)\n    \n        n_frames_tot = replica_positions.shape[0]\n            \n        # Determine simulation time (in ps) for each frame:\n        time_delta_ps = (timestep*time_interval).value_in_unit(unit.picosecond)\n        traj_times = np.linspace(\n            frame_begin*time_delta_ps,\n            (frame_begin+frame_stride*(n_frames_tot-1))*time_delta_ps,\n            num=n_frames_tot,\n        )\n    \n        file_name = f\"{output_dir}/replica_{replica_index+1}.dcd\"\n\n        # Trajectories are written in nanometers:\n        replica_traj = Trajectory(\n            replica_positions,\n            Topology.from_openmm(topology),\n            time=traj_times,\n        )\n            \n        Trajectory.save_dcd(replica_traj,file_name)\n        \n    return file_list\n    \n\ndef make_replica_pdb_files(\n    topology, output_dir=\"output\", output_data=\"output.nc\", checkpoint_data=\"output_checkpoint.nc\",\n    frame_begin=0, frame_stride=1):\n    \"\"\"\n    Make pdb files from replica exchange simulation trajectory data.\n    \n    :param topology: OpenMM Topology\n    :type topology: `Topology() <https://simtk.org/api_docs/openmm/api4_1/python/classsimtk_1_1openmm_1_1app_1_1topology_1_1Topology.html>`_\n    \n    :param output_dir: path to which we will write the output (default='output')\n    :type output_dir: str\n    \n    :param output_data: name of output .nc data file (default='output.nc')\n    :type output_data: str    \n    \n    :param checkpoint_data: name of checkpoint .nc data file (default='output_checkpoint.nc')\n    :type checkpoint_data: str   \n    \n    :param frame_begin: Frame at which to start writing the pdb trajectory (default=0)\n    :type frame_begin: int    \n    \n    :param frame_stride: advance by this many frames when writing pdb trajectories (default=1)\n    :type frame_stride: int   \n    \n    :returns:\n        - file_list ( List( str ) ) - A list of names for the files that were written\n    \"\"\"\n    file_list = []\n    \n    output_data_path = os.path.join(output_dir, output_data)\n    \n    # Get number of replicas:\n    reporter = MultiStateReporter(output_data_path, open_mode=\"r\")\n    states = reporter.read_thermodynamic_states()[0]\n    n_replicas = len(states)\n    \n    sampler_states = reporter.read_sampler_states(iteration=0)\n    xunit = sampler_states[0].positions[0].unit\n    \n    for replica_index in range(n_replicas):\n        replica_positions = extract_trajectory(topology, replica_index=replica_index, \n            output_data=output_data_path, checkpoint_data=checkpoint_data,\n            frame_begin=frame_begin, frame_stride=frame_stride)\n    \n        file_name = f\"{output_dir}/replica_{replica_index+1}.pdb\"\n\n        # Trajectories are written in nanometers:\n        replica_traj = Trajectory(\n            replica_positions,\n            Topology.from_openmm(topology),\n        )\n            \n        Trajectory.save_pdb(replica_traj,file_name)\n        \n    return file_list\n    \n\ndef make_state_dcd_files(\n    topology, timestep=5*unit.femtosecond, time_interval=200,\n    output_dir=\"output\", output_data=\"output.nc\", checkpoint_data=\"output_checkpoint.nc\",\n    frame_begin=0, frame_stride=1, center=True):\n    \"\"\"\n    Make dcd files by state from replica exchange simulation trajectory data.\n    Note: these are discontinuous trajectories with constant temperature state.\n    \n    :param topology: OpenMM Topology\n    :type topology: `Topology() <https://simtk.org/api_docs/openmm/api4_1/python/classsimtk_1_1openmm_1_1app_1_1topology_1_1Topology.html>`_\n    \n    :param timestep: Time step used in the simulation (default=5*unit.femtosecond)\n    :type timestep: `Quantity() <http://docs.openmm.org/development/api-python/generated/simtk.unit.quantity.Quantity.html>` float * simtk.unit\n    \n    :param time_interval: frequency, in number of time steps, at which positions were recorded (default=200)\n    :type time_interval: int\n    \n    :param output_dir: path to which we will write the output (default='output')\n    :type output_dir: str\n    \n    :param output_data: name of output .nc data file (default='output.nc')\n    :type output_data: str    \n    \n    :param checkpoint_data: name of checkpoint .nc data file (default='output_checkpoint.nc')\n    :type checkpoint_data: str   \n    \n    :param frame_begin: Frame at which to start writing the dcd trajectory (default=0)\n    :type frame_begin: int\n    \n    :param frame_stride: advance by this many time intervals when writing dcd trajectories (default=1)\n    :type frame_stride: int \n    \n    :param center: align the center of mass of each structure in the discontinuous state trajectory (default=True)\n    :type center: Boolean\n    \n    \"\"\"\n    \n    file_list = []\n    \n    output_data_path = os.path.join(output_dir, output_data)\n    \n    # Get number of states:\n    reporter = MultiStateReporter(output_data_path, open_mode=\"r\")\n    states = reporter.read_thermodynamic_states()[0]\n    \n    sampler_states = reporter.read_sampler_states(iteration=0)\n    xunit = sampler_states[0].positions[0].unit\n        \n    for state_index in range(len(states)):\n        state_positions = extract_trajectory(topology, state_index=state_index,\n            output_data=output_data_path, checkpoint_data=checkpoint_data,\n            frame_begin=frame_begin, frame_stride=frame_stride)\n            \n        n_frames_tot = state_positions.shape[0]\n            \n        # Determine simulation time (in ps) for each frame:\n        time_delta_ps = (timestep*time_interval).value_in_unit(unit.picosecond)\n        traj_times = np.linspace(\n            frame_begin*time_delta_ps,\n            (frame_begin+frame_stride*(n_frames_tot-1))*time_delta_ps,\n            num=n_frames_tot,\n        )\n\n        file_name = f\"{output_dir}/state_{state_index+1}.dcd\"\n\n        # Trajectories are written in nanometers:\n        state_traj = Trajectory(\n            state_positions,\n            Topology.from_openmm(topology),\n            time=traj_times,\n        )\n        \n        if center:\n            ref_traj = state_traj[0]\n            state_traj.superpose(ref_traj)\n            # This rewrites to state_traj\n            \n        Trajectory.save_dcd(state_traj,file_name)\n        \n    return file_list\n    \n    \ndef make_state_pdb_files(\n    topology, output_dir=\"output\", output_data=\"output.nc\", checkpoint_data=\"output_checkpoint.nc\",\n    frame_begin=0, frame_stride=1, center=True):\n    \"\"\"\n    Make pdb files by state from replica exchange simulation trajectory data.\n    Note: these are discontinuous trajectories with constant temperature state.\n    \n    :param topology: OpenMM Topology\n    :type topology: `Topology() <https://simtk.org/api_docs/openmm/api4_1/python/classsimtk_1_1openmm_1_1app_1_1topology_1_1Topology.html>`_\n    \n    :param output_dir: path to which we will write the output (default='output')\n    :type output_dir: str\n    \n    :param output_data: name of output .nc data file (default='output.nc')\n    :type output_data: str    \n    \n    :param checkpoint_data: name of checkpoint .nc data file (default='output_checkpoint.nc')\n    :type checkpoint_data: str   \n    \n    :param frame_begin: Frame at which to start writing the pdb trajectory (default=0)\n    :type frame_begin: int    \n    \n    :param frame_stride: advance by this many frames when writing pdb trajectories (default=1)\n    :type frame_stride: int   \n\n    :param center: align the center of mass of each structure in the discontinuous state trajectory (default=True)\n    :type center: Boolean\n    \n    :returns:\n        - file_list ( List( str ) ) - A list of names for the files that were written\n    \"\"\"\n    file_list = []\n    \n    output_data_path = os.path.join(output_dir, output_data)\n    \n    # Get number of states:\n    reporter = MultiStateReporter(output_data_path, open_mode=\"r\")\n    states = reporter.read_thermodynamic_states()[0]\n    \n    sampler_states = reporter.read_sampler_states(iteration=0)\n    xunit = sampler_states[0].positions[0].unit\n    \n    for state_index in range(len(states)):\n        state_positions = extract_trajectory(topology, state_index=state_index, \n            output_data=output_data_path, checkpoint_data=checkpoint_data,\n            frame_begin=frame_begin, frame_stride=frame_stride)\n    \n        file_name = f\"{output_dir}/state_{state_index+1}.pdb\"\n        \n        # Trajectories are written in nanometers:\n        state_traj = Trajectory(\n            state_positions,\n            Topology.from_openmm(topology),\n        )\n        \n        if center:\n            ref_traj = state_traj[0]\n            state_traj.superpose(ref_traj)\n            # This rewrites to state_traj\n            \n        Trajectory.save_pdb(state_traj,file_name)\n        \n    return file_list\n    \n    \ndef extract_trajectory(\n    topology, output_data=\"output/output.nc\", checkpoint_data=\"output_checkpoint.nc\",\n    state_index=None, replica_index=None,\n    frame_begin=0, frame_stride=1, frame_end=-1):\n    \"\"\"\n    Internal function for extract trajectory (replica or state) from .nc file,\n    Based on YANK extract_trajectory code.\n    \"\"\"\n\n    reporter = MultiStateReporter(output_data, open_mode='r', checkpoint_storage=checkpoint_data)\n    \n    # Get dimensions\n    trajectory_storage = reporter._storage_checkpoint  \n    n_iterations = reporter.read_last_iteration()\n    n_frames = trajectory_storage.variables['positions'].shape[0]\n    n_atoms = trajectory_storage.variables['positions'].shape[2]\n    \n    # Determine frames to extract.\n    # Convert negative indices to last indices.\n    if frame_begin < 0:\n        frame_begin = n_frames + frame_begin\n    if frame_end < 0:\n        frame_end = n_frames + frame_end + 1\n    frame_indices = range(frame_begin, frame_end, frame_stride)\n    if len(frame_indices) == 0:\n        raise ValueError('No frames selected')\n        \n    # Determine the number of frames that the trajectory will have.\n    if state_index is None:\n        n_trajectory_frames = len(frame_indices)        \n    else:\n        # With SAMS, an iteration can have 0 or more replicas in a given state.\n        # Deconvolute state indices.\n        state_indices = [None for _ in frame_indices]\n        for i, iteration in enumerate(frame_indices):\n            replica_indices = reporter._storage_analysis.variables['states'][iteration, :]\n            state_indices[i] = np.where(replica_indices == state_index)[0]\n        n_trajectory_frames = sum(len(x) for x in state_indices)        \n        \n    # Initialize positions and box vectors arrays.\n    # MDTraj Cython code expects float32 positions.\n    positions = np.zeros((n_trajectory_frames, n_atoms, 3), dtype=np.float32)\n\n    # Extract state positions and box vectors.\n    if state_index is not None:\n        # Extract state positions\n        frame_idx = 0\n        for i, iteration in enumerate(frame_indices):\n            for replica_index in state_indices[i]:\n                positions[frame_idx, :, :] = trajectory_storage.variables['positions'][iteration, replica_index, :, :].astype(np.float32)\n                frame_idx += 1\n\n    else:  # Extract replica positions\n        for i, iteration in enumerate(frame_indices):\n            positions[i, :, :] = trajectory_storage.variables['positions'][iteration, replica_index, :, :].astype(np.float32)\n\n    return positions\n    \n    \ndef process_replica_exchange_data(\n    output_data=\"output/output.nc\", output_directory=\"output\", series_per_page=4,\n    write_data_file=True, plot_production_only=False, print_timing=False,\n    equil_nskip=1, frame_begin=0, frame_end=-1,\n):\n    \"\"\"\n    Read replica exchange simulation data, detect equilibrium and decorrelation time, and plot replica exchange results.\n    \n    :param output_data: path to output .nc file from replica exchange simulation, (default='output/output.nc')\n    :type output_data: str\n    \n    :param output_directory: path to which output files will be written (default='output')\n    :type output_directory: stry\n\n    :param series_per_page: number of replica data series to plot per pdf page (default=4)\n    :type series_per_page: int\n    \n    :param write_data_file: Option to write a text data file containing the state_energies array (default=True)\n    :type write_data_file: Boolean\n    \n    :param plot_production_only: Option to plot only the production region, as determined from pymbar detectEquilibration (default=False)\n    :type plot_production_only: Boolean    \n\n    :param equil_nskip: skip this number of frames to sparsify the energy timeseries for pymbar detectEquilibration (default=1) - this is used only when frame_begin=0 and the trajectory has less than 40000 frames.\n    :type equil_nskip: Boolean\n    \n    :param frame_begin: analyze starting from this frame, discarding all prior as equilibration period (default=0)\n    :type frame_begin: int\n    \n    :param frame_end: analyze up to this frame only, discarding the rest (default=-1).\n    :type frame_end: int\n\n    :returns:\n        - replica_energies ( `Quantity() <http://docs.openmm.org/development/api-python/generated/simtk.unit.quantity.Quantity.html>`_ ( np.float( [number_replicas,number_simulation_steps] ), simtk.unit ) ) - The potential energies for all replicas at all (printed) time steps\n        - replica_state_indices ( np.int64( [number_replicas,number_simulation_steps] ), simtk.unit ) - The thermodynamic state assignments for all replicas at all (printed) time steps\n        - production_start ( int - The frame at which the production region begins for all replicas, as determined from pymbar detectEquilibration\n        - sample_spacing ( int - The number of frames between uncorrelated state energies, estimated using heuristic algorithm )\n        - n_transit ( np.float( [number_replicas] ) ) - Number of half-transitions between state 0 and n for each replica\n        - mixing_stats ( tuple ( np.float( [number_replicas x number_replicas] ) , np.float( [ number_replicas ] ) , float( statistical inefficiency ) ) ) - transition matrix, corresponding eigenvalues, and statistical inefficiency\n    \"\"\"\n    \n    t1 = time.perf_counter()\n    \n    # Read the simulation coordinates for individual temperature replicas\n    reporter = MultiStateReporter(output_data, open_mode=\"r\")\n\n    t2 = time.perf_counter()\n    if print_timing:\n        print(f\"open data time: {t2-t1}\")\n    \n    # figure out what the time between output is.\n    # We assume all use the same time step (which i think is required)\n    \n    mcmove = reporter.read_mcmc_moves()[0]\n    time_interval = mcmove.n_steps*mcmove.timestep\n\n    t3 = time.perf_counter()\n    if print_timing:\n        print(f\"read_mcmc_moves time: {t3-t2}\")\n    \n    # figure out what the temperature list is\n    states = reporter.read_thermodynamic_states()[0]\n    \n    t4 = time.perf_counter()\n    if print_timing:\n        print(f\"read_thermodynamics_states time: {t4-t3}\")\n    \n    temperature_list = []\n    for s in states:\n        temperature_list.append(s.temperature)\n\n    analyzer = ReplicaExchangeAnalyzer(reporter)\n    \n    t5 = time.perf_counter()\n    \n    (\n        replica_energies,\n        unsampled_state_energies,\n        neighborhoods,\n        replica_state_indices,\n    ) = analyzer.read_energies()\n    \n    # Truncate output of read_energies() to last frame of interest\n    if frame_end > 0:\n        # Use frames from frame_begin to frame_end\n        replica_energies = replica_energies[:,:,:frame_end]\n        unsampled_state_energies = unsampled_state_energies[:,:,:frame_end]\n        neighborhoods = neighborhoods[:,:,:frame_end]\n        replica_state_indices = replica_state_indices[:,:frame_end]\n    \n    t6 = time.perf_counter()\n    if print_timing:\n        print(f\"read_energies time: {t6-t5}\")\n\n    n_particles = np.shape(reporter.read_sampler_states(iteration=0)[0].positions)[0]\n    temps = np.array([temp._value for temp in temperature_list])\n    beta_k = 1 / (kB * temps)\n    n_replicas = len(temperature_list)\n    for k in range(n_replicas):\n        replica_energies[:, k, :] *= beta_k[k] ** (-1)\n\n    t7 = time.perf_counter()\n    if print_timing:\n        print(f\"reduce replica energies time: {t7-t6}\")\n        \n    total_steps = len(replica_energies[0][0])\n    state_energies = np.zeros([n_replicas, total_steps])\n\n    t8 = time.perf_counter()\n    # there must be some better way to do this as list comprehension.\n    for step in range(total_steps):\n        for state in range(n_replicas):\n            state_energies[state, step] = replica_energies[\n                np.where(replica_state_indices[:, step] == state)[0], 0, step\n            ]\n            \n    t9 = time.perf_counter()\n    if print_timing:\n        print(f\"assign state energies time: {t9-t8}\")\n\n    # can run physical-valication on these state_energies\n        \n    # Use pymbar timeseries module to detect production period\n    \n    t10 = time.perf_counter()\n    \n    # Start of equilibrated data:\n    t0 = np.zeros((n_replicas))\n    # Statistical inefficiency:\n    g = np.zeros((n_replicas))\n    \n    subsample_indices = {}\n    \n    # If sufficiently large, discard the first 20000 frames as equilibration period and use \n    # subsampleCorrelatedData to get the energy decorrelation time.\n    if total_steps >= 40000 or frame_begin > 0:\n        if frame_begin > 0:\n            # If specified, use frame_begin as the start of the production region\n            production_start=frame_begin\n        else:\n            # Otherwise, use frame 20000\n            production_start=20000\n            \n        for state in range(n_replicas):\n            subsample_indices[state] = timeseries.subsampleCorrelatedData(\n                state_energies[state][production_start:],\n                conservative=True,\n            )\n            g[state] = subsample_indices[state][1]-subsample_indices[state][0]\n    \n    else:\n        # For small trajectories, use detectEquilibration\n        for state in range(n_replicas):\n            t0[state], g[state], Neff_max = timeseries.detectEquilibration(state_energies[state], nskip=equil_nskip)  \n\n            # Choose the latest equil timestep to apply to all states    \n            production_start = int(np.max(t0))\n    \n    # Assume a normal distribution (very rough approximation), and use mean plus\n    # the number of standard deviations which leads to (n_replica-1)/n_replica coverage\n    # For 12 replicas this should be the mean + 1.7317 standard deviations\n    \n    # x standard deviations is the solution to (n_replica-1)/n_replica = erf(x/sqrt(2))\n    # This is equivalent to a target of 23/24 CDF value \n    \n    print(f\"g: {g.astype(int)}\")\n    \n    def erf_fun(x):\n        return np.power((erf(x/np.sqrt(2))-(n_replicas-1)/n_replicas),2)\n        \n    # x must be larger than zero    \n    opt_g_results = minimize_scalar(\n        erf_fun,\n        bounds=(0,10)\n        )\n    \n    if not opt_g_results.success:\n        print(\"Error solving for correlation time, exiting...\")\n        print(f\"erf opt results: {opt_g_results}\")\n        exit()\n    \n    sample_spacing = int(np.ceil(np.mean(g)+opt_g_results.x*np.std(g)))\n    \n    t11 = time.perf_counter()\n    if print_timing:\n        print(f\"detect equil and subsampling time: {t11-t10}\")\n                \n    print(\"state    mean energies  variance\")\n    for state in range(n_replicas):\n        state_mean = np.mean(state_energies[state,production_start::sample_spacing])\n        state_std = np.std(state_energies[state,production_start::sample_spacing])\n        print(\n            f\"  {state:4d}    {state_mean:10.6f} {state_std:10.6f}\"\n        )\n\n    t12 = time.perf_counter()\n    \n    if write_data_file == True:\n        f = open(os.path.join(output_directory, \"replica_energies.dat\"), \"w\")\n        for step in range(total_steps):\n            f.write(f\"{step:10d}\")\n            for replica_index in range(n_replicas):\n                f.write(f\"{replica_energies[replica_index,replica_index,step]:12.6f}\")\n            f.write(\"\\n\")\n        f.close()\n\n    t13 = time.perf_counter()\n    if print_timing:\n        print(f\"Optionally write .dat file: {t13-t12}\")\n               \n    t14 = time.perf_counter()\n    \n    if plot_production_only==True:\n        plot_replica_exchange_energies(\n            state_energies[:,production_start:],\n            temperature_list,\n            series_per_page,\n            time_interval=time_interval,\n            time_shift=production_start*time_interval,\n            file_name=f\"{output_directory}/rep_ex_ener.pdf\",\n        )\n        \n        plot_replica_exchange_energy_histograms(\n            state_energies[:,production_start:],\n            temperature_list,\n            file_name=f\"{output_directory}/rep_ex_ener_hist.pdf\",\n        )\n\n        plot_replica_exchange_summary(\n            replica_state_indices[:,production_start:],\n            temperature_list,\n            series_per_page,\n            time_interval=time_interval,\n            time_shift=production_start*time_interval,\n            file_name=f\"{output_directory}/rep_ex_states.pdf\",\n        )\n        \n        plot_replica_state_matrix(\n            replica_state_indices[:,production_start:],\n            file_name=f\"{output_directory}/state_probability_matrix.pdf\",\n        )\n        \n    else:\n        plot_replica_exchange_energies(\n            state_energies,\n            temperature_list,\n            series_per_page,\n            time_interval=time_interval,\n            file_name=f\"{output_directory}/rep_ex_ener.pdf\",\n        )\n        \n        plot_replica_exchange_energy_histograms(\n            state_energies,\n            temperature_list,\n            file_name=f\"{output_directory}/rep_ex_ener_hist.pdf\",\n        )\n\n        plot_replica_exchange_summary(\n            replica_state_indices,\n            temperature_list,\n            series_per_page,\n            time_interval=time_interval,\n            file_name=f\"{output_directory}/rep_ex_states.pdf\",\n        )\n        \n        plot_replica_state_matrix(\n            replica_state_indices,\n            file_name=f\"{output_directory}/state_probability_matrix.pdf\",\n        )\n      \n    t15 = time.perf_counter()\n      \n    if print_timing:\n        print(f\"plotting time: {t15-t14}\")\n    \n    # Analyze replica exchange state transitions\n    # For each replica, how many times does the thermodynamic state go between state 0 and state n\n    # For consistency with the other mixing statistics, use only the production region here\n    \n    replica_state_indices_prod = replica_state_indices[:,production_start:]\n    \n    # Number of one-way transitions from states 0 to n or states n to 0 \n    n_transit = np.zeros((n_replicas,1))\n    \n    # Replica_state_indices is [n_replicas x n_iterations]\n    for rep in range(n_replicas):\n        last_bound = None\n        for i in range(replica_state_indices_prod.shape[1]):\n            if replica_state_indices_prod[rep,i] == 0 or replica_state_indices_prod[rep,i] == (n_replicas-1):\n                if last_bound is None:\n                    # This is the first time state 0 or n is visited\n                    pass\n                else:\n                    if last_bound != replica_state_indices_prod[rep,i]:\n                        # This is a completed transition from 0 to n or n to 0\n                        n_transit[rep] += 1\n                last_bound = replica_state_indices_prod[rep,i]                \n                        \n    t16 = time.perf_counter()\n    \n    if print_timing:\n        print(f\"replica transition analysis: {t16-t15}\")\n        \n    # Compute transition matrix from the analyzer\n    mixing_stats = analyzer.generate_mixing_statistics(number_equilibrated=production_start)\n    \n    t17 = time.perf_counter()\n    \n    if print_timing:\n        print(f\"compute transition matrix: {t17-t16}\")\n        print(f\"total time elapsed: {t17-t1}\")\n\n    return (replica_energies, replica_state_indices, production_start, sample_spacing, n_transit, mixing_stats)\n\n\ndef run_replica_exchange(\n    topology,\n    system,\n    positions,\n    total_simulation_time=1.0 * unit.picosecond,\n    simulation_time_step=None,\n    temperature_list=None,\n    friction=1.0 / unit.picosecond,\n    minimize=True,\n    exchange_frequency=1000,\n    output_data=\"output/output.nc\",\n    ):\n\n    \"\"\"\n    Run a OpenMMTools replica exchange simulation using an OpenMM coarse grained model.\n    \n    :param topology: OpenMM Topology\n    :type topology: `Topology() <https://simtk.org/api_docs/openmm/api4_1/python/classsimtk_1_1openmm_1_1app_1_1topology_1_1Topology.html>`_\n\n    :param system: OpenMM System()\n    :type system: `System() <https://simtk.org/api_docs/openmm/api4_1/python/classsimtk_1_1openmm_1_1openmm_1_1System.html>`_\n\n    :param positions: Positions array for the model we would like to test\n    :type positions: `Quantity() <http://docs.openmm.org/development/api-python/generated/simtk.unit.quantity.Quantity.html>`_ ( np.array( [cgmodel.num_beads,3] ), simtk.unit )\n\n    :param total_simulation_time: Total run time for individual simulations\n    :type total_simulation_time: `SIMTK <https://simtk.org/>`_ `Unit() <http://docs.openmm.org/7.1.0/api-python/generated/simtk.unit.unit.Unit.html>`_\n\n    :param simulation_time_step: Simulation integration time step\n    :type simulation_time_step: `SIMTK <https://simtk.org/>`_ `Unit() <http://docs.openmm.org/7.1.0/api-python/generated/simtk.unit.unit.Unit.html>`_\n\n    :param temperature_list: List of temperatures for which to perform replica exchange simulations, default = None\n    :type temperature: List( float * simtk.unit.temperature )\n\n    :param friction: Langevin thermostat friction coefficient, default = 1 / ps\n    :type friction: `SIMTK <https://simtk.org/>`_ `Unit() <http://docs.openmm.org/7.1.0/api-python/generated/simtk.unit.unit.Unit.html>`_\n\n    :param minimize: Whether minimization is done before running the simulation\n    :type minimize: bool\n\n    :param output_data: Name of NETCDF file where we will write simulation data\n    :type output_data: string\n\n    :param exchange_frequency: Number of time steps between replica exchange attempts, Default = None\n    :type exchange_frequency: int\t\n\n    :param output_data: file to put the output .nc \n    :type output_data: netCDF4 file as generated by OpenMM  \n\n    :returns:\n        - replica_energies ( `Quantity() <http://docs.openmm.org/development/api-python/generated/simtk.unit.quantity.Quantity.html>`_ ( np.float( [number_replicas,number_simulation_steps] ), simtk.unit ) ) - The potential energies for all replicas at all (printed) time steps\n        - replica_positions ( `Quantity() <http://docs.openmm.org/development/api-python/generated/simtk.unit.quantity.Quantity.html>`_ ( np.float( [number_replicas,number_simulation_steps,cgmodel.num_beads,3] ), simtk.unit ) ) - The positions for all replicas at all (printed) time steps\n\n        - replica_state_indices ( np.int64( [number_replicas,number_simulation_steps] ), simtk.unit ) - The thermodynamic state assignments for all replicas at all (printed) time steps\n\n    :Example:\n\n    >>> from foldamers.cg_model.cgmodel import CGModel\n    >>> from cg_openmm.simulation.rep_exch import *\n    >>> cgmodel = CGModel()\n    >>> replica_energies,replica_positions,replica_state_indices = run_replica_exchange(cgmodel.topology,cgmodel.system,cgmodel.positions)\n\n    \"\"\"\n\n    simulation_steps = int(np.floor(total_simulation_time / simulation_time_step))\n\n    exchange_attempts = int(np.floor(simulation_steps / exchange_frequency))\n\n    if temperature_list is None:\n        temperature_list = [((300.0 + i) * unit.kelvin) for i in range(-50, 50, 10)]\n\n    num_replicas = len(temperature_list)\n    sampler_states = list()\n    thermodynamic_states = list()\n\n    # Define thermodynamic states.\n    # box_vectors = system.getDefaultPeriodicBoxVectors()\n    for temperature in temperature_list:\n        thermodynamic_state = openmmtools.states.ThermodynamicState(\n            system=system, temperature=temperature\n        )\n        thermodynamic_states.append(thermodynamic_state)\n        sampler_states.append(\n            openmmtools.states.SamplerState(positions)\n        )  # no box vectors, non-periodic system.\n\n    # Create and configure simulation object.\n    move = openmmtools.mcmc.LangevinDynamicsMove(\n        timestep=simulation_time_step,\n        collision_rate=friction,\n        n_steps=exchange_frequency,\n        reassign_velocities=False,\n    )\n\n    simulation = ReplicaExchangeSampler(\n        mcmc_moves=move,\n        number_of_iterations=exchange_attempts,\n        replica_mixing_scheme='swap-neighbors',\n    )\n\n    if os.path.exists(output_data):\n        os.remove(output_data)\n\n    reporter = MultiStateReporter(output_data, checkpoint_interval=1)\n    simulation.create(thermodynamic_states, sampler_states, reporter)\n\n    if minimize:\n        simulation.minimize()\n\n    print(\"Running OpenMM replica exchange simulation...\")\n    print(f\"Time step: {simulation_time_step}\")\n    print(f\"Iterations: {exchange_attempts}\")\n    try:\n        simulation.run()\n    except BaseException:\n        print(\"Replica exchange simulation failed, try verifying your model/simulation settings.\")\n        exit()\n        \n    return\n        \n        \ndef restart_replica_exchange(\n    total_simulation_time=1*unit.nanosecond,\n    simulation_time_step=5*unit.picosecond,\n    exchange_frequency=200,\n    output_data=\"output/output.nc\",\n    ):\n\n    \"\"\"\n    Restart an OpenMMTools replica exchange simulation using an OpenMM coarse grained model and\n    output .nc files from the previous segment of the simulation. \n\n    :param total_simulation_time: Total run time to add to the original simulation (default=1*unit.nanosecond)\n    :type total_simulation_time: `SIMTK <https://simtk.org/>`_ `Unit() <http://docs.openmm.org/7.1.0/api-python/generated/simtk.unit.unit.Unit.html>`_\n\n    :param simulation_time_step: Simulation integration time step (default=5*unit.picosecond)\n    :type simulation_time_step: `SIMTK <https://simtk.org/>`_ `Unit() <http://docs.openmm.org/7.1.0/api-python/generated/simtk.unit.unit.Unit.html>`_\n\n    :param exchange_frequency: Number of time steps between replica exchange attempts (default=200)\n    :type exchange_frequency: int\n\n    :param output_data: Path to the NETCDF file for previous segment of simulation - this will be appended to (default=\"output/output.nc\")\n    :type output_data: str\n    \"\"\"\n\n    simulation_steps = int(np.floor(total_simulation_time / simulation_time_step))\n    exchange_attempts = int(np.floor(simulation_steps / exchange_frequency))\n\n    # Load in the reporter from the original simulation:\n    reporter = MultiStateReporter(output_data, open_mode=\"r+\")\n    simulation = ReplicaExchangeSampler.from_storage(reporter)\n\n    print(\"Running OpenMM replica exchange simulation...\")\n    print(f\"Time step: {simulation_time_step}\")\n    print(f\"Iterations: {exchange_attempts}\")\n\n    simulation.extend(n_iterations=exchange_attempts)\n\n    return\n   \n        \ndef get_minimum_energy_ensemble(\n    topology, replica_energies, replica_positions, ensemble_size=5, file_name=None\n):\n\n    \"\"\"\n    Get an ensemble of low (potential) energy poses, and write the lowest energy structure to a PDB file if a file_name is provided.\n    \n    :param topology: OpenMM Topology()\n    :type topology: `Topology() <https://simtk.org/api_docs/openmm/api4_1/python/classsimtk_1_1openmm_1_1app_1_1topology_1_1Topology.html>`_\n    \n    :param replica_energies: List of dimension num_replicas X simulation_steps, which gives the energies for all replicas at all simulation steps\n    :type replica_energies: List( List( float * simtk.unit.energy for simulation_steps ) for num_replicas )\n    \n    :param replica_positions: List of positions for all output frames for all replicas\n    :type replica_positions: np.array( ( float * simtk.unit.positions for num_beads ) for simulation_steps )\n    \n    :param file_name: Output destination for PDB coordinates of minimum energy pose, Default = None\n    \n    :returns:\n    - ensemble ( List() ) - A list of poses that are in the minimum energy ensemble.\n\n    :Example:\n    \n    >>> from foldamers.cg_model.cgmodel import CGModel\n    >>> from cg_openmm.simulation.rep_exch import *\n    >>> cgmodel = CGModel()\n    >>> replica_energies,replica_positions,replica_state_indices = run_replica_exchange(cgmodel.topology,cgmodel.system,cgmodel.positions)\n    >>> ensemble_size = 5\n    >>> file_name = \"minimum.pdb\"\n    >>> minimum_energy_ensemble = get_minimum_energy_ensemble(cgmodel.topology,replica_energies,replica_positions,ensemble_size=ensemble_size,file_name=file_name)\n    \n    \"\"\"\n    # Get the minimum energy structure sampled during the simulation\n    ensemble = []\n    ensemble_energies = []\n    for replica in range(len(replica_energies)):\n        energies = np.array([energy for energy in replica_energies[replica][replica]])\n        for energy in range(len(energies)):\n            if len(ensemble) < ensemble_size:\n                ensemble.append(replica_positions[replica][energy])\n                ensemble_energies.append(energies[energy])\n            else:\n                for comparison in range(len(ensemble_energies)):\n                    if energies[energy] < ensemble_energies[comparison]:\n                        ensemble_energies[comparison] = energies[energy]\n                        ensemble[comparison] = replica_positions[replica][energy]\n\n    if file_name is None:\n        index = 1\n        for pose in ensemble:\n            file = open(str(\"re_min_\" + str(index) + \".pdb\"), \"w\")\n            PDBFile.writeFile(topology, pose, file=file)\n    else:\n        file = open(file_name, \"w\")\n        for pose in ensemble:\n            PDBFile.writeFile(topology, pose, file=file)\n\n    return ensemble\n\n\ndef plot_replica_exchange_energies(\n    state_energies,\n    temperature_list,\n    series_per_page,\n    time_interval=1.0 * unit.picosecond,\n    time_shift=0.0 * unit.picosecond,    \n    file_name=\"rep_ex_ener.pdf\",\n    legend=True,\n):\n    \"\"\"\n    Plot the potential energies for a batch of replica exchange trajectories\n\n    :param state_energies: List of dimension num_replicas X simulation_steps, which gives the energies for all replicas at all simulation steps\n    :type state_energies: List( List( float * simtk.unit.energy for simulation_steps ) for num_replicas )\n\n    :param temperature_list: List of temperatures for which to perform replica exchange simulations, default = [(300.0 * unit.kelvin).__add__(i * unit.kelvin) for i in range(-20,100,10)]\n    :type temperature: List( float * simtk.unit.temperature )\n\n    :param time_interval: interval between energy exchanges.\n    :type time_interval: `SIMTK <https://simtk.org/>`_ `Unit() <http://docs.openmm.org/7.1.0/api-python/generated/simtk.unit.unit.Unit.html>`_\n\n    :param time_shift: amount of time before production period to shift the time axis(default = 0)\n    :type time_shift: `SIMTK <https://simtk.org/>`_ `Unit() <http://docs.openmm.org/7.1.0/api-python/generated/simtk.unit.unit.Unit.html>`_\n    \n    :param file_name: The pathname of the output file for plotting results, default = \"replica_exchange_energies.png\"\n    :type file_name: str\n\n    :param legend: Controls whether a legend is added to the plot\n    :type legend: Logical\n\n    \"\"\"\n\n    simulation_times = np.array(\n        [\n            step * time_interval.value_in_unit(unit.picosecond)\n            for step in range(len(state_energies[0]))\n        ]\n    )\n    \n    simulation_times += time_shift.value_in_unit(unit.picosecond)\n    \n    # To improve pdf render speed, sparsify data to display less than 2000 data points\n    n_xdata = len(simulation_times)\n    \n    if n_xdata <= 1000:\n        plot_stride = 1\n    else:\n        plot_stride = int(np.floor(n_xdata/1000))\n    \n    # If more than series_per_page replicas, split into separate pages for better visibility\n    nmax = series_per_page\n    npage = int(np.ceil(len(temperature_list)/nmax))\n    \n    with PdfPages(file_name) as pdf:\n        page_num=1\n        plotted_per_page=0\n        pyplot.figure()\n        for state in range(len(temperature_list)):\n            if plotted_per_page <= (nmax):\n                pyplot.plot(\n                    simulation_times[::plot_stride],\n                    state_energies[state,::plot_stride],\n                    alpha=0.5,\n                    linewidth=1,\n                )\n                plotted_per_page += 1\n                \n            if (plotted_per_page >= nmax) or (state==(len(temperature_list)-1)):\n                # Save and close previous page\n                pyplot.xlabel(\"Simulation Time ( Picoseconds )\")\n                pyplot.ylabel(\"Potential Energy ( kJ / mol )\")\n                pyplot.title(\"Replica Exchange Simulation\")\n                \n                if legend:\n                    pyplot.legend(\n                        [round(temperature.value_in_unit(unit.kelvin), 1) for temperature in temperature_list[(0+(page_num-1)*nmax):(page_num*nmax)]],\n                        loc=\"center left\",\n                        bbox_to_anchor=(1, 0.5),\n                        title=\"T (K)\",\n                    )  \n                \n                pdf.savefig(bbox_inches=\"tight\") # Save current fig to pdf page\n                pyplot.close()\n                plotted_per_page = 0\n                page_num += 1\n                \n    return\n    \n\ndef plot_replica_exchange_energy_histograms(\n    state_energies,\n    temperature_list,\n    file_name=\"rep_ex_ener_hist.pdf\",\n    legend=True,\n):\n    \"\"\"\n    Plot the potential energies for a batch of replica exchange trajectories\n\n    :param state_energies: List of dimension num_replicas X simulation_steps, which gives the energies for all replicas at all simulation steps\n    :type state_energies: List( List( float * simtk.unit.energy for simulation_steps ) for num_replicas )\n\n    :param temperature_list: List of temperatures for which to perform replica exchange simulations, default = [(300.0 * unit.kelvin).__add__(i * unit.kelvin) for i in range(-20,100,10)]\n    :type temperature: List( float * simtk.unit.temperature )\n\n    :param file_name: The pathname of the output file for plotting results, default = \"replica_exchange_energies.png\"\n    :type file_name: str\n\n    :param legend: Controls whether a legend is added to the plot\n    :type legend: Logical\n\n    \"\"\"\n\n    figure = pyplot.figure(figsize=(8.5,11))\n\n    for state in range(len(temperature_list)):\n        n_out, bin_edges_out = np.histogram(\n            state_energies[state,:],bins=20,density=True,\n        )\n        \n        bin_centers = np.zeros((len(bin_edges_out)-1,1))\n        for i in range(len(bin_edges_out)-1):\n            bin_centers[i] = (bin_edges_out[i]+bin_edges_out[i+1])/2\n        \n        pyplot.plot(bin_centers,n_out,'o-',alpha=0.5,linewidth=1,markersize=6)\n            \n\n    pyplot.xlabel(\"Potential Energy ( kJ / mol )\")\n    pyplot.ylabel(\"Probability\")\n    pyplot.title(\"Replica Exchange Energy Histogram\")\n    \n    if legend:\n        pyplot.legend(\n            [round(temperature._value, 1) for temperature in temperature_list],\n            loc=\"center left\",\n            bbox_to_anchor=(1, 0.5),\n            title=\"T (K)\",\n        )\n\n    pyplot.savefig(file_name, bbox_inches=\"tight\")\n    pyplot.close()\n\n    return\n    \n    \ndef plot_replica_state_matrix(\n    replica_state_indices,\n    file_name='state_probability_matrix.pdf'\n    ):\n    \n    # Plot a matrix of replica vs. state, coloring each box in the grid by normalized frequency \n    # For each replica, histogram the state indices data \n    # Then normalize the data and create [n_replica x n_state] patch graph\n    \n    n_replicas = replica_state_indices.shape[0]\n    \n    hist_all = np.zeros((n_replicas, n_replicas))\n    \n    state_bin_edges = np.linspace(-0.5,n_replicas-0.5,n_replicas+1)\n    state_bin_centers = 0.5+state_bin_edges[0:n_replicas]\n    \n    for rep in range(n_replicas):\n        hist_all[rep,:], bin_edges = np.histogram(\n            replica_state_indices[rep,:],bins=state_bin_edges,density=True,\n        )\n        \n    # No need for global normalization, since each replica's state probabilities must sum to 1\n    \n    hist_norm = np.zeros_like(hist_all)\n    for rep in range(n_replicas):\n        for state in range(n_replicas):\n            hist_norm[rep,state] = hist_all[rep,state]/np.max(hist_all[rep,:])    \n    \n    mean_score = np.mean(hist_norm)\n    min_score = np.amin(hist_norm)\n    \n    ax = pyplot.subplot(111)\n    \n    cmap=pyplot.get_cmap('nipy_spectral') \n    norm=Normalize(vmin=0,vmax=1) \n    \n    ax.imshow(hist_norm,cmap=cmap,norm=norm)\n    ax.set_aspect('equal', 'box')\n    \n    # Append colorbar axis to right side\n    divider = make_axes_locatable(ax)\n    cax = divider.append_axes(\"right\",size=\"5%\",pad=0.20)  \n    \n    pyplot.colorbar(\n        cm.ScalarMappable(cmap=cmap,norm=norm),\n        cax=cax,\n        label='normalized frequency',\n        )\n     \n    ax.set_xlabel(\"State\")\n    ax.set_ylabel(\"Replica\")\n    pyplot.suptitle(f\"Replica exchange state probabilities\\n(Mean: {mean_score:.4f} Min: {min_score:.4f})\")  \n    \n    pyplot.savefig(file_name)\n    pyplot.close()    \n    \n    return hist_all\n    \n    \ndef plot_replica_exchange_summary(\n    replica_states,\n    temperature_list,\n    series_per_page,\n    time_interval=1.0 * unit.picosecond,\n    time_shift=0.0 * unit.picosecond,\n    file_name=\"rep_ex_states.pdf\",\n    legend=True,\n):\n    \"\"\"\n    Plot the thermodynamic state assignments for individual temperature replicas as a function of the simulation time, in order to obtain a visual summary of the replica exchanges from a OpenMM simulation.\n\n    :param replica_states: List of dimension num_replicas X simulation_steps, which gives the thermodynamic state indices for all replicas at all simulation steps\n    :type replica_states: List( List( float * simtk.unit.energy for simulation_steps ) for num_replicas )\n\n    :param temperature_list: List of temperatures for which to perform replica exchange simulations, default = [(300.0 * unit.kelvin).__add__(i * unit.kelvin) for i in range(-20,100,10)]\n    :type temperature: List( float * simtk.unit.temperature )\n\n    :param time_interval: interval between energy exchanges.\n    :type time_interval: `SIMTK <https://simtk.org/>`_ `Unit() <http://docs.openmm.org/7.1.0/api-python/generated/simtk.unit.unit.Unit.html>`_\n\n    :param time_shift: amount of time before production period to shift the time axis(default = 0)\n    :type time_shift: `SIMTK <https://simtk.org/>`_ `Unit() <http://docs.openmm.org/7.1.0/api-python/generated/simtk.unit.unit.Unit.html>`_\n\n    :param file_name: The pathname of the output file for plotting results, default = \"replica_exchange_state_transitions.png\"\n    :type file_name: str\n\n    :param legend: Controls whether a legend is added to the plot\n    :type legend: Logical\n\n    \"\"\"\n    \n    simulation_times = np.array(\n        [\n            step * time_interval.value_in_unit(unit.picosecond)\n            for step in range(len(replica_states[0]))\n        ]\n    )\n    \n    simulation_times += time_shift.value_in_unit(unit.picosecond)\n    \n    # To improve pdf render speed, sparsify data to display less than 2000 data points\n    n_xdata = len(simulation_times)\n    \n    if n_xdata <= 1000:\n        plot_stride = 1\n    else:\n        plot_stride = int(np.floor(n_xdata/1000))\n    \n    # If more than series_per_page replicas, split into separate pages for better visibility\n    nmax = series_per_page\n    npage = int(np.ceil(len(temperature_list)/nmax))\n        \n    with PdfPages(file_name) as pdf:\n        page_num=1\n        plotted_per_page=0\n        pyplot.figure()\n        for replica in range(len(replica_states)):\n            state_indices = np.array([int(round(state)) for state in replica_states[replica]])\n            \n            if plotted_per_page <= (nmax):\n                \n                pyplot.plot(\n                    simulation_times[::plot_stride],\n                    state_indices[::plot_stride],\n                    alpha=0.5,\n                    linewidth=1\n                )\n                plotted_per_page += 1\n                \n            if (plotted_per_page >= nmax) or (replica==(len(replica_states)-1)):\n                # Save and close previous page\n                pyplot.xlabel(\"Simulation Time ( Picoseconds )\")\n                pyplot.ylabel(\"Thermodynamic State Index\")\n                pyplot.title(\"State Exchange Summary\")\n                \n                if legend:\n                    pyplot.legend(\n                        [i for i in range((page_num-1)*nmax,page_num*nmax)],\n                        loc=\"center left\",\n                        bbox_to_anchor=(1, 0.5),\n                        title=\"Replica Index\",\n                    )\n                \n                pdf.savefig(bbox_inches=\"tight\") # Save current fig to pdf page\n                pyplot.close()\n                plotted_per_page = 0\n                page_num += 1\n\n    return\n", "meta": {"hexsha": "72ad61ffc2d889980bf41e6c62f05540e2c55de4", "size": 47887, "ext": "py", "lang": "Python", "max_stars_repo_path": "cg_openmm/simulation/rep_exch.py", "max_stars_repo_name": "shirtsgroup/cg_openmm", "max_stars_repo_head_hexsha": "f71dbd7393c83386a73c4cee4b059bd17a56f12a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-05-26T23:07:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T21:42:22.000Z", "max_issues_repo_path": "cg_openmm/simulation/rep_exch.py", "max_issues_repo_name": "shirtsgroup/cg_openmm", "max_issues_repo_head_hexsha": "f71dbd7393c83386a73c4cee4b059bd17a56f12a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 122, "max_issues_repo_issues_event_min_datetime": "2019-11-01T18:39:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T19:55:54.000Z", "max_forks_repo_path": "cg_openmm/simulation/rep_exch.py", "max_forks_repo_name": "shirtsgroup/cg_openmm", "max_forks_repo_head_hexsha": "f71dbd7393c83386a73c4cee4b059bd17a56f12a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-10-04T14:25:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-09T05:45:48.000Z", "avg_line_length": 40.1063651591, "max_line_length": 288, "alphanum_fraction": 0.6730636707, "include": true, "reason": "import numpy,from scipy", "num_tokens": 11010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.1777370439009159}}
{"text": "#!/usr/bin/env python3\n\n\"\"\"\ncorrections.py: Script to apply corrections to the images.\n\"\"\"\n\nimport os\nfrom argparse import ArgumentParser\nfrom datetime import date, datetime\nfrom typing import Optional, Sequence\n\nimport numpy as np\nfrom astropy.io import fits\n\nfrom dresscode.utils import load_config\n\n\ndef main(argv: Optional[Sequence[str]] = None) -> int:\n    parser = ArgumentParser()\n    parser.add_argument(\n        \"-c\", \"--config\", help=\"path to config.txt\", default=\"config.txt\"\n    )\n    args = parser.parse_args(argv)\n\n    config = load_config(args.config)\n\n    galaxy = config[\"galaxy\"]\n    path = config[\"path\"] + galaxy + \"/working_dir/\"\n    years = config[\"years\"]\n\n    # Loop over the different years.\n    for year in years:\n\n        print(\"Year: \" + year)\n        yearpath = path + year + \"/\"\n\n        # PART 1: Apply a coincidence loss correction.\n\n        print(\"Applying coincidence loss corrections...\")\n        if os.path.isfile(yearpath + \"sum_um2_nm.img\"):\n            coicorr(yearpath + \"sum_um2_nm.img\")\n        if os.path.isfile(yearpath + \"sum_uw2_nm.img\"):\n            coicorr(yearpath + \"sum_uw2_nm.img\")\n        if os.path.isfile(yearpath + \"sum_uw1_nm.img\"):\n            coicorr(yearpath + \"sum_uw1_nm.img\")\n\n        # PART 2: Apply a large scale sensitivity correction.\n\n        print(\"Applying large scale sensitivity corrections...\")\n        if os.path.isfile(yearpath + \"sum_um2_nm_coi.img\"):\n            lsscorr(yearpath + \"sum_um2_nm_coi.img\")\n        if os.path.isfile(yearpath + \"sum_uw2_nm_coi.img\"):\n            lsscorr(yearpath + \"sum_uw2_nm_coi.img\")\n        if os.path.isfile(yearpath + \"sum_uw1_nm_coi.img\"):\n            lsscorr(yearpath + \"sum_uw1_nm_coi.img\")\n\n        # PART 3: Apply a zero point correction.\n\n        print(\"Applying zero point corrections...\")\n        if os.path.isfile(yearpath + \"sum_um2_nm_coilss.img\"):\n            zeropoint(yearpath + \"sum_um2_nm_coilss.img\", -2.330e-3, -1.361e-3)\n        if os.path.isfile(yearpath + \"sum_uw2_nm_coilss.img\"):\n            zeropoint(yearpath + \"sum_uw2_nm_coilss.img\", 1.108e-3, -1.960e-3)\n        if os.path.isfile(yearpath + \"sum_uw1_nm_coilss.img\"):\n            zeropoint(yearpath + \"sum_uw1_nm_coilss.img\", 2.041e-3, -1.748e-3)\n\n    return 0\n\n\n# Functions for PART 1: Coincidence loss correction.\ndef coicorr(filename):\n    # Open the image. Create arrays with zeros with the shape of the image.\n    hdulist = fits.open(filename)\n    data = hdulist[0].data\n    header = hdulist[0].header\n    total_flux = np.full_like(data, np.nan, dtype=np.float64)\n    std = np.full_like(data, np.nan, dtype=np.float64)\n\n    # Loop over all pixels and for each pixel: sum the flux densities (count rates) of\n    # the 9x9 surrounding pixels: Craw (counts/s). Calculate the standard deviation in\n    # the 9x9 pixels box.\n    for x in range(5, data.shape[1] - 5):\n        for y in range(5, data.shape[0] - 5):\n            total_flux[y, x] = np.sum(data[y - 4 : y + 5, x - 4 : x + 5])\n            std[y, x] = np.std(data[y - 4 : y + 5, x - 4 : x + 5])\n\n    # Obtain the dead time correction factor and the frame time (in s) from the header\n    # of the image.\n    alpha = header[\"DEADC\"]\n    ft = header[\"FRAMTIME\"]\n\n    # Calculate the total number of counts in the 9x9 pixels box: x = Craw*ft (counts).\n    # Calculate the minimum and maximum possible number of counts in the 9x9 pixels box.\n    total_counts = ft * total_flux\n    total_counts_min = ft * (total_flux - 81 * std)\n    total_counts_max = ft * (total_flux + 81 * std)\n\n    # Calculate the polynomial correction factor and the minimum and maximum possible\n    # polynomial correction factor.\n    f = polynomial(total_counts)\n    f_min = polynomial(total_counts_min)\n    f_max = polynomial(total_counts_max)\n\n    # If alpha*total_counts_max is larger than 1, replace this value by 0.99. Otherwise,\n    # the maximum possible theoretical coincidence-loss-corrected count rate will be NaN\n    # in these pixels.\n    if np.sum(alpha * total_counts_max >= 1.0) != 0:\n        print(\n            \"Warning: The following pixels have very high fluxes. The uncertainty on \"\n            \"the correction factor for these pixels is not to be trusted!\",\n            np.where(alpha * total_counts_max >= 1.0),\n        )\n    total_counts_max[alpha * total_counts_max >= 1.0] = 0.99 / alpha\n\n    # Calculate the theoretical coincidence-loss-corrected count rate:\n    # Ctheory = -ln(1 - alpha*Craw*ft) / (alpha*ft) (counts/s).\n    # Calculate the minimum and maximum possible theoretical coincidence-loss-corrected\n    # count rate.\n    Ctheory = -np.log1p(-alpha * total_counts) / (alpha * ft)\n    Ctheory_min = -np.log1p(-alpha * total_counts_min) / (alpha * ft)\n    Ctheory_max = -np.log1p(-alpha * total_counts_max) / (alpha * ft)\n\n    # Calculate the coincidence loss correction factor:\n    # Ccorrfactor = Ctheory*f(x)/Craw.\n    # Calculate the minimum and maximum possible coincidence loss correction factor.\n    corrfactor = (Ctheory * f) / total_flux\n    corrfactor_min = (Ctheory_min * f_min) / (total_flux - 81 * std)\n    corrfactor_max = (Ctheory_max * f_max) / (total_flux + 81 * std)\n\n    # Apply the coincidence loss correction to the data. Apply the minimum and maximum\n    # coincidence loss correction to the data.\n    new_data = corrfactor * data\n    new_data_min = corrfactor_min * data\n    new_data_max = corrfactor_max * data\n\n    # Calculate the uncertainty and the relative uncertainty on the coincidence loss\n    # correction. Put the relative uncertainty to 0 if the uncertainty is 0 (because in\n    # those pixels the flux is also 0 and the relative uncertainty would be NaN).\n    coicorr_unc = np.maximum(\n        np.abs(new_data - new_data_min), np.abs(new_data_max - new_data)\n    )\n    coicorr_rel = coicorr_unc / new_data\n    coicorr_rel[coicorr_unc == 0.0] = 0.0\n\n    print(\n        \"The median coincidence loss correction factor for image \"\n        + os.path.basename(filename)\n        + \" is \"\n        + str(np.nanmedian(corrfactor))\n        + \" and the median relative uncertainty on the corrected data is \"\n        + str(np.nanmedian(coicorr_rel))\n        + \".\"\n    )\n\n    # Adapt the header. Write the corrected data, the applied coincidence loss\n    # correction and the relative uncertainty to a new image.\n    header[\"PLANE0\"] = \"primary (counts/s)\"\n    header[\"PLANE1\"] = \"coincidence loss correction factor\"\n    header[\"PLANE2\"] = \"relative coincidence loss correction uncertainty (fraction)\"\n    datacube = [new_data, corrfactor, coicorr_rel]\n    new_hdu = fits.PrimaryHDU(datacube, header)\n    new_hdu.writeto(filename.replace(\".img\", \"_coi.img\"), overwrite=True)\n\n    print(os.path.basename(filename) + \" has been corrected for coincidence loss.\")\n\n\n# Function to calculate the empirical polynomial correction to account for the\n# differences between the observed and theoretical coincidence loss correction:\n# f(x) = 1 + a1x + a2x**2 + a3x**3 + a4x**4.\ndef polynomial(x):\n    a1 = 0.0658568\n    a2 = -0.0907142\n    a3 = 0.0285951\n    a4 = 0.0308063\n    return 1 + (a1 * x) + (a2 * x ** 2) + (a3 * x ** 3) + (a4 * x ** 4)\n\n\n# Function for PART 2: Large scale sensitivity correction.\ndef lsscorr(filename):\n    # Open the image and the large scale sensitivity map.\n    hdulist = fits.open(filename)\n    data = hdulist[0].data[0]\n    coicorr = hdulist[0].data[1]\n    coicorr_rel = hdulist[0].data[2]\n    header = hdulist[0].header\n\n    lss_hdulist = fits.open(filename.replace(\"nm_coi\", \"lss\"))\n    lss_data = lss_hdulist[1].data\n\n    # Apply the large scale sensitivity correction to the data.\n    new_data = data / lss_data\n    new_datacube = [new_data, coicorr, coicorr_rel]\n\n    # Write the corrected data to a new image.\n    new_hdu = fits.PrimaryHDU(new_datacube, header)\n    new_hdu.writeto(filename.replace(\".img\", \"lss.img\"), overwrite=True)\n\n    print(\n        os.path.basename(filename)\n        + \" has been corrected for large scale sensitivity variations.\"\n    )\n\n\n# Function for PART 3: Zero point correction.\ndef zeropoint(filename, param1, param2):\n    # Open the file.\n    hdulist = fits.open(filename)\n    data = hdulist[0].data[0]\n    coicorr = hdulist[0].data[1]\n    coicorr_rel = hdulist[0].data[2]\n    header = hdulist[0].header\n    # Calculate the average date of observation.\n    start_date = datetime.strptime(header[\"DATE-OBS\"].split(\"T\")[0], \"%Y-%m-%d\").date()\n    end_date = datetime.strptime(header[\"DATE-END\"].split(\"T\")[0], \"%Y-%m-%d\").date()\n    obs_date = (end_date - start_date) / 2 + start_date\n    # Calculate the number of years that have elapsed since the 1st of January 2005.\n    first_date = date(2005, 1, 1)\n    elapsed_time = obs_date - first_date\n    years_passed = elapsed_time.days / 365.25\n\n    # Calculate the zero point correction.\n    zerocorr = 1 + param1 * years_passed + param2 * years_passed ** 2\n\n    # Apply the correction to the data.\n    new_data = data / zerocorr\n\n    # Adapt the header. Write the corrected data to a new image.\n    header[\"ZPCORR\"] = zerocorr\n    datacube = [new_data, coicorr, coicorr_rel]\n    new_hdu = fits.PrimaryHDU(datacube, header)\n    new_hdu.writeto(filename.replace(\".img\", \"zp.img\"), overwrite=True)\n\n    print(\n        os.path.basename(filename)\n        + \" has been corrected for sensitivity loss of the detector over time.\"\n    )\n\n\nif __name__ == \"__main__\":\n    exit(main())\n", "meta": {"hexsha": "47e71f7fedc4f309e955efb41242943d77c31784", "size": 9350, "ext": "py", "lang": "Python", "max_stars_repo_path": "dresscode/corrections.py", "max_stars_repo_name": "spacetelescope/DRESSCode", "max_stars_repo_head_hexsha": "29e432363072560335583b2819cf8106d41f5b9a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-05-04T13:05:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T15:35:21.000Z", "max_issues_repo_path": "dresscode/corrections.py", "max_issues_repo_name": "spacetelescope/DRESSCode", "max_issues_repo_head_hexsha": "29e432363072560335583b2819cf8106d41f5b9a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2021-04-16T19:31:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T22:15:22.000Z", "max_forks_repo_path": "dresscode/corrections.py", "max_forks_repo_name": "spacetelescope/DRESSCode", "max_forks_repo_head_hexsha": "29e432363072560335583b2819cf8106d41f5b9a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7966804979, "max_line_length": 88, "alphanum_fraction": 0.6642780749, "include": true, "reason": "import numpy,from astropy", "num_tokens": 2545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.17747665124526993}}
{"text": "#!/usr/bin/env python\n\"\"\"\nSQLAlchemy wrapping of x-ray database for data from\n     Elam et al, Chantler et al, Waasmaier and Kirfel\n\nMain Class for full Database:  xrayDB\n\"\"\"\n\nimport os\nimport json\nfrom collections import namedtuple\nimport numpy as np\nfrom scipy.interpolate import UnivariateSpline\n\nfrom sqlalchemy import MetaData, create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.pool import SingletonThreadPool\n\nfrom .utils import elam_spline, as_ndarray\n\nXrayEdge = namedtuple('XrayEdge', ('energy', 'fyield', 'jump_ratio'))\nXrayLine = namedtuple('XrayLine', ('energy', 'intensity', 'initial_level',\n                                   'final_level'))\nElementData = namedtuple('ElementData', ('Z', 'symbol', 'mass', 'density'))\n\n__version__ = '1.4'\n\ndef make_engine(dbname):\n    \"create engine for sqlite connection\"\n    return create_engine('sqlite:///%s' % (dbname),\n                         poolclass=SingletonThreadPool,\n                         connect_args={'check_same_thread': False})\n\ndef isxrayDB(dbname):\n    \"\"\"whether a file is a valid XrayDB database\n\n    Args:\n        dbname (string): name of XrayDB file\n\n    Returns:\n        bool: is file a valid XrayDB\n\n    Notes:\n      1. must be a sqlite db file, with tables named 'elements',\n        'photoabsorption', 'scattering', 'xray_levels', 'Coster_Kronig',\n        'Chantler', 'Waasmaier', and 'KeskiRahkonen_Krause'\n    \"\"\"\n    _tables = ('Chantler', 'Waasmaier', 'Coster_Kronig',\n               'KeskiRahkonen_Krause', 'xray_levels',\n               'elements', 'photoabsorption', 'scattering')\n    result = False\n    try:\n        engine = make_engine(dbname)\n        meta = MetaData(engine)\n        meta.reflect()\n        result = all([t in meta.tables for t in _tables])\n    except:\n        pass\n    return result\n\n\nclass XrayDB():\n    \"\"\"\n    Database of Atomic and X-ray Data\n\n    This XrayDB object gives methods to access the Atomic and\n    X-ray data in th SQLite3 database xraydb.sqlite.\n\n    Much of the data in this database comes from the compilation\n    of Elam, Ravel, and Sieber, with additional data from Chantler,\n    and other sources. See the documention and bibliography for\n    a complete listing.\n    \"\"\"\n\n    def __init__(self, dbname='xraydb.sqlite', read_only=True):\n        \"connect to an existing database\"\n        if not os.path.exists(dbname):\n            parent, _ = os.path.split(__file__)\n            dbname = os.path.join(parent, dbname)\n            if not os.path.exists(dbname):\n                raise IOError(\"Database '%s' not found!\" % dbname)\n\n        if not isxrayDB(dbname):\n            raise ValueError(\"'%s' is not a valid X-ray Database file!\" % dbname)\n\n        self.dbname = dbname\n        self.engine = make_engine(dbname)\n        self.conn = self.engine.connect()\n        kwargs = {}\n        if read_only:\n            kwargs = {'autoflush': True, 'autocommit': False}\n\n            def readonly_flush(*args, **kwargs):\n                return\n\n            self.session = sessionmaker(bind=self.engine, **kwargs)()\n            self.session.flush = readonly_flush\n        else:\n            self.session = sessionmaker(bind=self.engine, **kwargs)()\n\n        self.metadata = MetaData(self.engine)\n        self.metadata.reflect()\n        self.tables = self.metadata.tables\n        elems = self.tables['elements'].select().execute()\n        self.atomic_symbols = [e.element for e in elems.fetchall()]\n\n    def close(self):\n        \"close session\"\n        self.session.flush()\n        self.session.close()\n\n    def query(self, *args, **kws):\n        \"generic query\"\n        return self.session.query(*args, **kws)\n\n    def get_version(self, long=False, with_history=False):\n        \"\"\"\n        return sqlite3 database and python library version numbers\n\n        Parameters:\n            long (bool): show timestamp and notes of latest version [False]\n            with_history (bool): show complete version history [False]\n\n        Returns:\n            string: version information\n        \"\"\"\n        out = []\n        rows = self.tables['Version'].select().execute().fetchall()\n        if not with_history:\n            rows = rows[-1:]\n        if long or with_history:\n            for row in rows:\n                out.append(\"XrayDB Version: %s [%s] '%s'\" % (row.tag,\n                                                             row.date,\n                                                             row.notes))\n            out.append(\"Python Version: %s\" % __version__)\n            out = \"\\n\".join(out)\n        else:\n            out = \"XrayDB Version: %s, Python Version: %s\" % (rows[0].tag,\n                                                              __version__)\n        return out\n\n    def f0_ions(self, element=None):\n        \"\"\"\n        return list of ion names supported for the .f0() function.\n\n\n        Parameters:\n            element (string, int, pr None):  atomic number, symbol, or ionic symbol\n                    of scattering element.\n\n        Returns:\n            list:  if element is None, all 211 ions are returned.\n                   if element is not None, the ions for that element are returned\n\n        Example:\n            >>> xdb = XrayDB()\n            >>> xdb.f0_ions('Fe')\n            ['Fe', 'Fe2+', 'Fe3+']\n\n        Notes:\n            Z values from 1 to 98 (and symbols 'H' to 'Cf') are supported.\n\n        References:\n            Waasmaier and Kirfel\n        \"\"\"\n        wtab = self.tables['Waasmaier']\n        rows = self.query(wtab)\n        if element is not None:\n            elem = self.symbol(element)\n            rows = rows.filter(wtab.c.element == elem)\n        return [str(r.ion) for r in rows.all()]\n\n    def f0(self, ion, q):\n        \"\"\"\n        return f0(q) -- elastic X-ray scattering factor from Waasmaier and Kirfel\n\n        Parameters:\n            ion (string, int, or None):  atomic number, symbol or ionic symbol\n                  of scattering element.\n            q (float, list, ndarray): value(s) of q for scattering factors\n\n        Returns:\n            ndarray: elastic scattering factors\n\n\n        Example:\n            >>> xdb = XrayDB()\n            >>> xdb.f0('Fe', range(10))\n            array([ 25.994603  ,   6.55945765,   3.21048827,   1.65112769,\n                     1.21133507,   1.0035555 ,   0.81012185,   0.61900285,\n                     0.43883403,   0.27673021])\n\n        Notes:\n            q = sin(theta) / lambda, where theta = incident angle,\n            and lambda = X-ray wavelength\n\n            Z values from 1 to 98 (and symbols 'H' to 'Cf') are supported.\n            The list of ionic symbols can be read with the function .f0_ions()\n\n        References:\n            Waasmaier and Kirfel\n        \"\"\"\n        wtab = self.tables['Waasmaier']\n        if isinstance(ion, int):\n            row = self.query(wtab).filter(wtab.c.atomic_number == ion).all()[0]\n        elif ion not in self.f0_ions():\n            raise ValueError('No ion {:s} from Waasmaier table'.format(repr(ion)))\n        else:\n            row = self.query(wtab).filter(wtab.c.ion == ion.title()).all()[0]\n        q = as_ndarray(q)\n        f0 = row.offset\n        for s, e in zip(json.loads(row.scale), json.loads(row.exponents)):\n            f0 += s * np.exp(-e*q*q)\n        return f0\n\n    def _from_chantler(self, element, energy, column='f1', smoothing=0):\n        \"\"\"\n        return energy-dependent data from Chantler table\n\n        Parameters:\n            element (string or int): atomic number or symbol.\n            eneregy (float or ndarray):\n        columns: f1, f2, mu_photo, mu_incoh, mu_total\n\n        Notes:\n           this function is meant for internal use.\n        \"\"\"\n        ctab = self.tables['Chantler']\n        elem = self.symbol(element)\n        row = self.query(ctab).filter(ctab.c.element == elem).one()\n\n        energy = as_ndarray(energy)\n        emin, emax = min(energy), max(energy)\n\n        te = np.array(json.loads(row.energy))\n        nemin = max(0, -3 + max(np.where(te <= emin)[0]))\n        nemax = min(len(te), 3 + max(np.where(te <= emax)[0]))\n\n        te = te[nemin:nemax+1]\n        if column == 'mu':\n            column = 'mu_total'\n        ty = np.array(json.loads(getattr(row, column)))[nemin:nemax+1]\n        ty[np.where(abs(ty) < 1.e-99)] =  1.e-99\n        if column == 'f1':\n            out = UnivariateSpline(te, ty, s=smoothing)(energy)\n        else:\n            out = np.exp(np.interp(np.log(energy),\n                                   np.log(te),\n                                   np.log(ty)))\n        if isinstance(out, np.ndarray) and len(out) == 1:\n            out = out[0]\n        return out\n\n    def chantler_energies(self, element, emin=0, emax=1.e9):\n        \"\"\"\n        return array of energies (in eV) at which data is\n        tabulated in the Chantler tables for a particular element.\n\n        Parameters:\n            element (string or int): atomic number or symbol\n            emin (float): minimum energy (in eV) [0]\n            emax (float): maximum energy (in eV) [1.e9]\n\n        Returns:\n            ndarray: energies\n\n        References:\n            Chantler\n\n        Notes:\n            returns 2 energies below emin and above emax to better\n            enable interpolation\n        \"\"\"\n        ctab = self.tables['Chantler']\n        elem = self.symbol(element)\n        row = self.query(ctab).filter(ctab.c.element == elem).one()\n        te = np.array(json.loads(row.energy))\n\n        if emin <= min(te):\n            nemin = 0\n        else:\n            nemin = max(0, -1 + max(np.where(te <= emin)[0]))\n        if emax > max(te):\n            nemax = len(te)\n        else:\n            nemax = min(len(te), 2 + max(np.where(te <= emax)[0]))\n        return te[nemin:nemax+1]\n\n    def f1_chantler(self, element, energy, **kws):\n        \"\"\"\n        returns f1 -- real part of anomalous X-ray scattering factor\n        for selected input energy (or energies) in eV.\n\n        Parameters:\n            element (string or int): atomic number or symbol\n            energy (float or ndarray): energies (in eV).\n\n        Returns:\n            ndarray: real part of anomalous scattering factor\n\n        References:\n            Chantler\n        \"\"\"\n        return self._from_chantler(element, energy, column='f1', **kws)\n\n    def f2_chantler(self, element, energy, **kws):\n        \"\"\"\n        returns f2 -- imaginary part of anomalous X-ray scattering factor\n        for selected input energy (or energies) in eV.\n\n        Parameters:\n            element (string or int): atomic number or symbol\n            energy (float or ndarray): energies (in eV).\n\n        Returns:\n            ndarray: imaginary part of anomalous scattering factor\n\n        References:\n            Chantler\n        \"\"\"\n        return self._from_chantler(element, energy, column='f2', **kws)\n\n    def mu_chantler(self, element, energy, incoh=False, photo=False):\n        \"\"\"\n        returns X-ray mass attenuation coefficient, mu/rho in cm^2/gr\n        for selected input energy (or energies) in eV.\n        default is to return total attenuation coefficient.\n\n        Parameters:\n            element (string or int): atomic number or symbol\n            energy (float or ndarray): energies (in eV).\n            photo (bool): return only the photo-electric contribution [False]\n            incoh (bool): return only the incoherent contribution [False]\n\n        Returns:\n            ndarray: mass attenuation coefficient in cm^2/gr\n\n        References:\n            Chantler\n        \"\"\"\n        col = 'mu_total'\n        if photo:\n            col = 'mu_photo'\n        elif incoh:\n            col = 'mu_incoh'\n        return self._from_chantler(element, energy, column=col)\n\n    def _elem_data(self, element):\n        \"return data from elements table: internal use\"\n        etab = self.tables['elements']\n        row = self.query(etab)\n        if isinstance(element, int):\n            row = row.filter(etab.c.atomic_number == element).one()\n        else:\n            elem = element.title()\n            if not elem in self.atomic_symbols:\n                raise ValueError(\"unknown element '%s'\" % repr(elem))\n            row = row.filter(etab.c.element == elem).one()\n        return ElementData(int(row.atomic_number),\n                           row.element.title(),\n                           row.molar_mass, row.density)\n\n    def atomic_number(self, element):\n        \"\"\"\n        return element's atomic number\n\n        Parameters:\n            element (string or int): atomic number or symbol\n\n        Returns:\n            integer: atomic number\n        \"\"\"\n        return self._elem_data(element).Z\n\n    def symbol(self, element):\n        \"\"\"\n        return element symbol\n\n        Parameters:\n            element (string or int): atomic number or symbol\n\n        Returns:\n            string: element symbol\n        \"\"\"\n        return self._elem_data(element).symbol\n\n    def molar_mass(self, element):\n        \"\"\"\n        return molar mass of element\n\n        Parameters:\n            element (string or int): atomic number or symbol\n\n        Returns:\n            float: molar mass of element in amu\n        \"\"\"\n        return self._elem_data(element).mass\n\n    def density(self, element):\n        \"\"\"\n        return density of pure element\n\n        Parameters:\n            element (string or int): atomic number or symbol\n\n        Returns:\n            float: density of element in gr/cm^3\n        \"\"\"\n        return self._elem_data(element).density\n\n    def xray_edges(self, element):\n        \"\"\"\n        returns dictionary of X-ray absorption edge energy (in eV),\n        fluorescence yield, and jump ratio for an element.\n\n        Parameters:\n            element (string or int): atomic number or symbol\n\n        Returns:\n            dictionary:  keys of edge (iupac symbol), and values of\n                         XrayEdge namedtuple of (energy, fyield, edge_jump))\n\n        References:\n           Elam, Ravel, and Sieber.\n        \"\"\"\n        elem = self.symbol(element)\n        ltab = self.tables['xray_levels']\n        out = {}\n        for r in self.query(ltab).filter(ltab.c.element == elem).all():\n            out[str(r.iupac_symbol)] = XrayEdge(r.absorption_edge,\n                                                r.fluorescence_yield,\n                                                r.jump_ratio)\n        return out\n\n    def xray_edge(self, element, edge):\n        \"\"\"\n        returns XrayEdge for an element and edge\n\n        Parameters:\n            element (string or int): atomic number or symbol\n            edge (string):  X-ray edge\n\n        Returns:\n            XrayEdge:  namedtuple of (energy, fyield, edge_jump))\n\n        Example:\n            >>> xdb = XrayDB()\n            >>> xdb.xray_edge('Co', 'K')\n            XrayEdge(edge=7709.0, fyield=0.381903, jump_ratio=7.796)\n\n        References:\n           Elam, Ravel, and Sieber.\n        \"\"\"\n        return self.xray_edges(element).get(edge.title(), None)\n\n    def xray_lines(self, element, initial_level=None, excitation_energy=None):\n        \"\"\"\n        returns dictionary of X-ray emission lines of an element, with\n\n        Parameters:\n            initial_level (string or list/tuple of string):  initial level(s) to\n                 limit output.\n            excitation_energy (float): energy of excitation, limit output those\n                 excited by X-rays of this energy (in eV).\n\n        Returns:\n            dictionary: keys of lines (Siegbahn symbol), values of Xray Lines\n\n        Notes:\n            if both excitation_energy and initial_level are given, excitation_level\n            will limit output\n\n        Example:\n            >>> xdb = XrayDB()\n            >>> for key, val in xdb.xray_lines('Ga', 'K').items():\n            >>>      print(key, val)\n            'Ka3', XrayLine(energy=9068.0, intensity=0.000326203,\n                            initial_level=u'K', final_level=u'L1')\n            'Ka2', XrayLine(energy=9223.8, intensity=0.294438,\n                            initial_level=u'K', final_level=u'L2')\n            'Ka1', XrayLine(energy=9250.6, intensity=0.57501,\n                            initial_level=u'K', final_level=u'L3')\n            'Kb3', XrayLine(energy=10263.5, intensity=0.0441511,\n                            initial_level=u'K', final_level=u'M2')\n            'Kb1', XrayLine(energy=10267.0, intensity=0.0852337,\n                            initial_level=u'K', final_level=u'M3')\n            'Kb5', XrayLine(energy=10348.3, intensity=0.000841354,\n                            initial_level=u'K', final_level=u'M4,5')\n\n        References:\n           Elam, Ravel, and Sieber.\n        \"\"\"\n        elem = self.symbol(element)\n        ttab = self.tables['xray_transitions']\n        row = self.query(ttab).filter(ttab.c.element == elem)\n        if excitation_energy is not None:\n            initial_level = []\n            for ilevel, dat in self.xray_edges(elem).items():\n                if dat[0] < excitation_energy:\n                    initial_level.append(ilevel.title())\n\n        if initial_level is not None:\n            if isinstance(initial_level, (list, tuple)):\n                row = row.filter(ttab.c.initial_level.in_(initial_level))\n            else:\n                row = row.filter(ttab.c.initial_level == initial_level.title())\n        out = {}\n        for r in row.all():\n            out[str(r.siegbahn_symbol)] = XrayLine(r.emission_energy, r.intensity,\n                                                   r.initial_level, r.final_level)\n        return out\n\n    def xray_line_strengths(self, element, excitation_energy=None):\n        \"\"\"\n        return the absolute line strength in cm^2/gr for all available lines\n\n        Parameters:\n            element (string or int): Atomic symbol or number for element\n            excitation_energy (float): incident energy, in eV\n\n        Returns:\n            dictionary: elemental line with fluorescence cross section in cm2/gr.\n\n        References:\n           Elam, Ravel, and Sieber.\n        \"\"\"\n        out = {}\n        lines = self.xray_lines(element, excitation_energy=excitation_energy)\n        for label, eline in lines.items():\n            edge = self.xray_edge(element, eline.initial_level)\n            if edge is None and ',' in eline.initial_level:\n                ilevel, _ = eline.initial_level.split(',')\n                edge = self.xray_edge(element, ilevel)\n            if edge is not None:\n                mu = self.mu_elam(element, [edge.energy*(0.999),\n                                            edge.energy*(1.001)], kind='photo')\n                out[label] = (mu[1]-mu[0]) * eline.intensity * edge.fyield\n        return out\n\n    def ck_probability(self, element, initial, final, total=True):\n        \"\"\"\n        return Coster-Kronig transition probability for an element and\n        initial/final levels\n\n        Parameters:\n            element (string or int): Atomic symbol or number for element\n            initial (string):  initial level\n            final (string):  final level\n            total (bool): whether to return total or partial probability\n\n        Returns:\n            float: transition probability\n\n        Example:\n            >>> xdb = XrayDB()\n            >>> xdb.ck_probability('Cu', 'L1', 'L3', total=True)\n            0.681\n\n        References:\n           Elam, Ravel, and Sieber.\n        \"\"\"\n        elem = self.symbol(element)\n        ctab = self.tables['Coster_Kronig']\n\n        row = self.query(ctab).filter(ctab.c.element == elem)\n        row = row.filter(ctab.c.initial_level == initial.title())\n        row = row.filter(ctab.c.final_level == final.title()).all()\n        out = 0.0\n        if len(row) > 0:\n            row = row[0]\n            out = row.transition_probability\n            if total:\n                out = row.total_transition_probability\n        return out\n\n    def corehole_width(self, element, edge=None, use_keski=False):\n        \"\"\"\n        returns core hole width for an element and edge\n\n        Parameters:\n            element (string, integer): atomic number or symbol for element\n            edge (string or None): edge for hole, return all if None\n            use_keski (bool) : force use of KeskiRahkonen and Krause table for all data.\n\n        Returns:\n            float: corehole width in eV.\n\n        Notes:\n            Uses Krause and Oliver where data is available (K, L lines Z > 10)\n            Uses Keski-Rahkonen and Krause otherwise\n\n        References:\n            Krause and Oliver, 1979\n            Keski-Rahkonen and Krause, 1974\n\n        \"\"\"\n        version_qy = self.tables['Version'].select().order_by('date')\n        version_id = version_qy.execute().fetchall()[-1].id\n\n        ctab = self.tables['corelevel_widths']\n        if version_id < 4 or use_keski:\n            ctab = self.tables['KeskiRahkonen_Krause']\n\n        rows = self.query(ctab).filter(ctab.c.element == self.symbol(element))\n        if edge is not None:\n            rows = rows.filter(ctab.c.edge == edge.title())\n        result = rows.all()\n        if len(result) == 1:\n            result = result[0].width\n        else:\n            result = [(r.edge, r.width) for r in result]\n        return result\n\n\n    def cross_section_elam(self, element, energies, kind='photo'):\n        \"\"\"\n        returns Elam Cross Section values for an element and energies\n\n        Parameters:\n            element (string or int):  atomic number or symbol for element\n            energies (float or ndarray): energies (in eV) to calculate cross-sections\n            kind (string):  one of 'photo', 'coh', and 'incoh' for photo-absorption,\n                  coherent scattering, and incoherent scattering cross sections,\n                  respectively. Default is 'photo'.\n\n        Returns:\n            ndarray of scattering data\n\n        References:\n            Elam, Ravel, and Sieber.\n        \"\"\"\n        elem = self.symbol(element)\n        kind = kind.lower()\n        if kind not in ('coh', 'incoh', 'photo'):\n            raise ValueError('unknown cross section kind=%s' % kind)\n\n        stab = self.tables['scattering']\n        if kind == 'photo':\n            stab = self. tables['photoabsorption']\n\n        row = self.query(stab).filter(stab.c.element == elem).all()[0]\n\n        tab_lne = np.array(json.loads(row.log_energy))\n        if kind.startswith('coh'):\n            tab_val = np.array(json.loads(row.log_coherent_scatter))\n            tab_spl = np.array(json.loads(row.log_coherent_scatter_spline))\n        elif kind.startswith('incoh'):\n            tab_val = np.array(json.loads(row.log_incoherent_scatter))\n            tab_spl = np.array(json.loads(row.log_incoherent_scatter_spline))\n        else:\n            tab_val = np.array(json.loads(row.log_photoabsorption))\n            tab_spl = np.array(json.loads(row.log_photoabsorption_spline))\n\n        en = 1.0*as_ndarray(energies)\n        emin_tab = 10*int(0.102*np.exp(tab_lne[0]))\n        en[np.where(en < emin_tab)] = emin_tab\n        out = np.exp(elam_spline(tab_lne, tab_val, tab_spl, np.log(en)))\n        if len(out) == 1:\n            return out[0]\n        return out\n\n    def mu_elam(self, element, energies, kind='total'):\n        \"\"\"\n        returns attenuation cross section for an element at energies (in eV)\n\n        Parameters:\n            element (string or int):  atomic number or symbol for element\n            energies (float or ndarray): energies (in eV) to calculate cross-sections\n            kind (string):  one of 'photo' or 'total' for photo-electric or\n                  total attenuation, respectively.  Default is 'total'.\n\n        Returns:\n           ndarray of scattering values in units of cm^2/gr\n\n        References:\n            Elam, Ravel, and Sieber.\n        \"\"\"\n        calc = self.cross_section_elam\n        kind = kind.lower()\n        if kind.startswith('tot'):\n            xsec = calc(element, energies, kind='photo')\n            xsec += calc(element, energies, kind='coh')\n            xsec += calc(element, energies, kind='incoh')\n        elif kind.startswith('photo'):\n            xsec = calc(element, energies, kind='photo')\n        elif kind.lower().startswith('coh'):\n            xsec = calc(element, energies, kind='coh')\n        elif kind.lower().startswith('incoh'):\n            xsec = calc(element, energies, kind='incoh')\n        else:\n            raise ValueError('unknown cross section kind=%s' % kind)\n        return xsec\n\n    def coherent_cross_section_elam(self, element, energies):\n        \"\"\"returns coherenet scattering crossrxr section for an element\n        at energies (in eV)\n\n        returns values in units of cm^2 / gr\n\n        arguments\n        ---------\n        element:  atomic number, atomic symbol for element\n        energies: energies in eV to calculate cross-sections\n\n        Data from Elam, Ravel, and Sieber.\n        \"\"\"\n        return self.cross_section_elam(element, energies, kind='coh')\n\n    def incoherent_cross_section_elam(self, element, energies):\n        \"\"\"return incoherenet scattering cross section for an element\n        at energies (in eV)\n\n        returns values in units of cm^2 / gr\n\n        arguments\n        ---------\n        element:  atomic number, atomic symbol for element\n        energies: energies in eV to calculate cross-sections\n\n        Data from Elam, Ravel, and Sieber.\n        \"\"\"\n        return self.cross_section_elam(element, energies, kind='incoh')\n\n    def ionization_potential(self, gas):\n        \"\"\"return effective ionization potential for a gas,\n        as appropriate for ionization chambers in the linear\n        regime (not in the 'proportional counter' regime)\n\n        returns values in units of eV\n\n        argument\n        ---------\n        gas (string):  name of gas\n\n        notes\n        -----\n        Data from G. F. Knoll, Radiation Detection and Measurement, Table 5-1.\n        \"\"\"\n        itab = self.tables['ionization_potentials']\n        out = self.query(itab).filter(itab.c.gas == gas).all()\n        if len(out) != 1:\n            raise ValueError('unknown gas for ionization potential: %s' % gas)\n        return float(out[0].potential)\n", "meta": {"hexsha": "b73871f76a42a4d5d096bbd2d03a6a105ae40aa2", "size": 26025, "ext": "py", "lang": "Python", "max_stars_repo_path": "xraydb/xraydb.py", "max_stars_repo_name": "chemmatcars/XModFit", "max_stars_repo_head_hexsha": "7d1298448d1908d78797fd67ce0a00ecfaf17629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "xraydb/xraydb.py", "max_issues_repo_name": "chemmatcars/XModFit", "max_issues_repo_head_hexsha": "7d1298448d1908d78797fd67ce0a00ecfaf17629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xraydb/xraydb.py", "max_forks_repo_name": "chemmatcars/XModFit", "max_forks_repo_head_hexsha": "7d1298448d1908d78797fd67ce0a00ecfaf17629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.932885906, "max_line_length": 88, "alphanum_fraction": 0.566301633, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.17747665124526993}}
{"text": "# -*- coding: utf-8 -*-\n# pylint: disable=wrong-import-position, range-builtin-not-iterating\n\n\"\"\"\nPhysical constants and constant-for-us values\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\n__all__ = [\n    'omkeys_to_sd_indices', 'get_sd_idx', 'get_string_dom_pair',\n\n    # Constants\n    'PI', 'TWO_PI', 'PI_BY_TWO', 'SPEED_OF_LIGHT_M_PER_NS',\n\n    # Pre-calculated values\n    'COS_CKV', 'THETA_CKV', 'SIN_CKV',\n    'TRACK_M_PER_GEV', 'TRACK_PHOTONS_PER_M', 'CASCADE_PHOTONS_PER_GEV',\n    'IC_DOM_JITTER_NS', 'DC_DOM_JITTER_NS', 'POL_TABLE_DCOSTHETA',\n    'POL_TABLE_DRPWR', 'POL_TABLE_DT', 'POL_TABLE_RPWR', 'POL_TABLE_RMAX',\n    'POL_TABLE_NTBINS', 'POL_TABLE_NRBINS', 'POL_TABLE_NTHETABINS',\n    'IC_DOM_QUANT_EFF', 'DC_DOM_QUANT_EFF',\n\n    # Particle naming conventions\n    'ABS_FLAV_STR', 'ABS_FLAV_TEX', 'BAR_NOBAR_STR', 'BAR_NOBAR_TEX',\n    'INT_TYPE_STR', 'INT_TYPE_TEX', 'PDG_STR', 'PDG_TEX', 'PDG_INTER_STR',\n    'PDG_INTER_TEX', 'STR_TO_PDG_INTER',\n\n    # \"Enum\"-like things\n    'STR_ALL', 'STR_IC', 'STR_DC', 'AGG_STR_NONE', 'AGG_STR_ALL',\n    'AGG_STR_SUBDET', 'DOM_ALL',\n\n    'NUM_STRINGS', 'NUM_DOMS_PER_STRING', 'NUM_DOMS_TOT',\n\n    'IC_STRS', 'DC_STRS', 'DC_IC_STRS', 'DC_ALL_STRS', 'DC_SUBDUST_DOMS',\n    'IC_SUBDUST_DOMS', 'DC_SUBDUST_STRS_DOMS', 'DC_IC_SUBDUST_STRS_DOMS',\n    'DC_ALL_SUBDUST_STRS_DOMS', 'ALL_STRS', 'ALL_DOMS', 'ALL_STRS_DOMS',\n    'ALL_STRS_DOMS_SET', 'DC_ALL_STRS_DOMS',\n\n    'EMPTY_HITS', 'EMPTY_SOURCES',\n    'SRC_OMNI', 'SRC_CKV_BETA1',\n\n    'PARAM_NAMES', 'PEGLEG_PARAM_NAMES', 'SCALING_PARAM_NAMES',\n]\n\n__author__ = 'P. Eller, J.L. Lanfranchi'\n__license__ = '''Copyright 2017 Philipp Eller and Justin L. Lanfranchi\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.'''\n\nfrom itertools import product\nfrom os.path import abspath, dirname\nimport sys\n\nimport numpy as np\n\nif __name__ == '__main__' and __package__ is None:\n    RETRO_DIR = dirname(dirname(dirname(abspath(__file__))))\n    if RETRO_DIR not in sys.path:\n        sys.path.append(RETRO_DIR)\nfrom retro import FTYPE\nfrom retro import retro_types\n\n\ndef omkeys_to_sd_indices(omkeys):\n    \"\"\"Get a single integer index from OMKeys.\n\n    Parameters\n    ----------\n    omkeys : array of dtype OMKEY_T\n        The dtype `OMKEY_T` must contain \"string\" and \"dom\" and can optionally\n        include \"pmt\".\n\n    Returns\n    -------\n    sd_idx : array of np.uint32\n\n    \"\"\"\n    if 'pmt' in omkeys.dtype.names:\n        raise NotImplementedError(\"OMKey field 'pmt' not implemented\")\n    return get_sd_idx(string=omkeys['string'], dom=omkeys['dom'])\n\n\ndef get_sd_idx(string, dom, pmt=0):\n    \"\"\"Get a single integer index from an IceCube string number (from 1 to 86)\n    and DOM number (from 1 to 60).\n\n    Parameters\n    ----------\n    string : int in [1, 60]\n        String number\n    dom : int in [1, 60]\n        DOM number\n    pmt : int\n        PMT number in the DOM; if == 0, then this is ignored.\n\n    Returns\n    -------\n    sd_idx : int\n\n    \"\"\"\n    if pmt > 0:\n        raise NotImplementedError('PMT != 0 is not implemented')\n    return (dom - 1) * NUM_STRINGS + (string - 1)\n\n\ndef get_string_dom_pair(sd_idx):\n    \"\"\"Get an IceCube string number (1 to 86) and a DOM number (1 to 60) from\n    the single-integer index (sd_idx).\n\n    Parameters\n    ----------\n    sd_idx : int in [0, 5159]\n\n    Returns\n    -------\n    string : int in [1, 86]\n    dom : int in [1, 60]\n\n    \"\"\"\n    dom_idx, string_idx = divmod(sd_idx, NUM_STRINGS)\n    string = string_idx + 1\n    dom = dom_idx + 1\n    return string, dom\n\n\n# -- Physical / mathematical constants -- #\n\nPI = FTYPE(np.pi)\n\"\"\"pi\"\"\"\n\nTWO_PI = FTYPE(2*np.pi)\n\"\"\"2 * pi\"\"\"\n\nPI_BY_TWO = FTYPE(np.pi / 2)\n\"\"\"pi / 2\"\"\"\n\nSPEED_OF_LIGHT_M_PER_NS = FTYPE(299792458 / 1e9)\n\"\"\"Speed of light in units of m/ns\"\"\"\n\n\n# -- Pre-calculated values -- #\n\nCOS_CKV = 0.764540803152\n\"\"\"Cosine of the Cherenkov angle for beta ~1 and IceCube phase index as used\"\"\"\n\nTHETA_CKV = np.arccos(0.764540803152)\n\"\"\"Cosine of the Cherenkov angle for beta ~1 and IceCube phase index as used\"\"\"\n\nSIN_CKV = np.sin(THETA_CKV)\n\"\"\"Cosine of the Cherenkov angle for beta ~1 and IceCube phase index as used\"\"\"\n\nTRACK_M_PER_GEV = FTYPE(15 / 3.3)\n\"\"\"Track length per energy, in units of m/GeV\"\"\"\n\nTRACK_PHOTONS_PER_M = FTYPE(2451.4544553)\n\"\"\"Track photons per length, in units of 1/m (see ``nphotons.py``)\"\"\"\n\nCASCADE_PHOTONS_PER_GEV = FTYPE(12805.3383311)\n\"\"\"Cascade photons per energy, in units of 1/GeV (see ``nphotons.py``)\"\"\"\n\n# TODO: Is jitter same (or close enough to the same) for all DOMs? Is it\n#       different for DeepCore vs. non-DeepCore DOMs? Didn't see as much in\n#       section 3.3. of arXiv:1612.05093v2 so assuming same for now.\n\n# See arXiv:1612.05093v2, section 3.3\nIC_DOM_JITTER_NS = 1.7\n\"\"\"Timing jitter (stddev) for string 0-79 DOMs, in units of ns\"\"\"\n\n# See arXiv:1612.05093v2, section 3.3\nDC_DOM_JITTER_NS = 1.7\n\"\"\"Timing jitter (stddev) for DeepCore (strings 80-86) DOMs, in units of ns\"\"\"\n\n# TODO: figure these out from the tables rather than defining as constants\nPOL_TABLE_RMAX = 400 # m\nPOL_TABLE_DT = 10 # ns\nPOL_TABLE_RPWR = 2\nPOL_TABLE_DRPWR = 0.1\nPOL_TABLE_DCOSTHETA = -0.05\nPOL_TABLE_NTBINS = 300\nPOL_TABLE_NRBINS = 200\nPOL_TABLE_NTHETABINS = 40\n\n#IC_DOM_QUANT_EFF = 0.25\nIC_DOM_QUANT_EFF = 1.\n\"\"\"scalar in [0, 1] : (Very rough approximation!) IceCube (i.e. non-DeepCore)\nDOM quantum efficiency. Multiplies the tabulated detection probabilities to\nyield the actual probabilitiy that a photon is detected.\"\"\"\n#DC_DOM_QUANT_EFF = 0.35\nDC_DOM_QUANT_EFF = 1.\n\"\"\"scalar in [0, 1] : (Very rough approximation!) DeepCore DOM quantum\nefficiency. Multiplies the tabulated detection probabilities to yield the\nactual probabilitiy that a photon is detected.\"\"\"\n\n\n# -- Particle / interaction type naming conventions -- #\n\nABS_FLAV_STR = {12: 'nue', 13: 'numu', 14: 'nutau'}\nABS_FLAV_TEX = {12: r'\\nu_e', 13: r'\\nu_\\mu', 14: r'\\nu_\\tau'}\n\nBAR_NOBAR_STR = {-1: 'bar', 1: ''}\nBAR_NOBAR_TEX = {-1: r'\\bar', 1: ''}\n\nINT_TYPE_STR = {1: 'cc', 2: 'nc'}\nINT_TYPE_TEX = {1: r'\\, {\\rm CC}', 2: r'\\, {\\rm NC}'}\n\nPDG_STR = {}\nPDG_TEX = {}\nfor _bnb, _abs_code in product(BAR_NOBAR_STR.keys(), ABS_FLAV_STR.keys()):\n    PDG_STR[_abs_code*_bnb] = ABS_FLAV_STR[_abs_code] + BAR_NOBAR_STR[_bnb]\n    PDG_TEX[_abs_code*_bnb] = BAR_NOBAR_TEX[_bnb] + ABS_FLAV_TEX[_abs_code]\n\nPDG_INTER_STR = {}\nPDG_INTER_TEX = {}\nfor _pdg, _it in product(PDG_STR.keys(), INT_TYPE_STR.keys()):\n    PDG_INTER_STR[(_pdg, _it)] = '%s_%s' % (PDG_STR[_pdg], INT_TYPE_STR[_it])\n    PDG_INTER_TEX[(_pdg, _it)] = '%s %s' % (PDG_TEX[_pdg], INT_TYPE_TEX[_it])\n\nSTR_TO_PDG_INTER = {v: k for k, v in PDG_INTER_STR.items()}\n\n\n# -- \"enums\" -- #\nSTR_ALL, STR_IC, STR_DC = -1, -2, -3\nAGG_STR_NONE, AGG_STR_ALL, AGG_STR_SUBDET = 0, 1, 2\nDOM_ALL = -1\n\n# -- geom constants --- #\n\nNUM_STRINGS = 86\nNUM_DOMS_PER_STRING = 60\nNUM_DOMS_TOT = NUM_STRINGS * NUM_DOMS_PER_STRING\n\n\nIC_STRS = np.array(range(1, 78+1), dtype=np.uint8)\nDC_STRS = np.array(range(79, 86+1), dtype=np.uint8)\nDC_IC_STRS = np.array([26, 27, 35, 36, 37, 45, 46], dtype=np.uint8)\nDC_ALL_STRS = np.concatenate([DC_STRS, DC_IC_STRS], axis=0)\n\nDC_SUBDUST_DOMS = np.array(range(11, 60+1), dtype=np.uint8)\nIC_SUBDUST_DOMS = np.array(range(25, 60+1), dtype=np.uint8)\n\nDC_SUBDUST_STRS_DOMS = np.array(\n    [get_sd_idx(s, d) for s, d in product(DC_STRS, DC_SUBDUST_DOMS)]\n)\nDC_IC_SUBDUST_STRS_DOMS = np.array(\n    [get_sd_idx(s, d) for s, d in product(DC_IC_STRS, IC_SUBDUST_DOMS)]\n)\n\nDC_ALL_SUBDUST_STRS_DOMS = np.concatenate(\n    (DC_SUBDUST_STRS_DOMS, DC_IC_SUBDUST_STRS_DOMS)\n)\n\nALL_STRS = list(range(1, 86+1))\nALL_DOMS = list(range(1, 60+1))\nALL_STRS_DOMS = np.array([get_sd_idx(s, d) for s, d in product(ALL_STRS, ALL_DOMS)])\nALL_STRS_DOMS_SET = set(ALL_STRS_DOMS)\nDC_ALL_STRS_DOMS = np.array([get_sd_idx(s, d) for s, d in product(DC_STRS, ALL_DOMS)])\n\n\nEMPTY_HITS = np.empty(shape=0, dtype=retro_types.HIT_T)\n\nEMPTY_SOURCES = np.empty(shape=0, dtype=retro_types.SRC_T)\n\nSRC_OMNI = np.uint32(0)\n\"\"\"Source kind designator for a point emitting omnidirectional light\"\"\"\n\nSRC_CKV_BETA1 = np.uint32(1)\n\"\"\"Source kind designator for a point emitting Cherenkov light with beta ~ 1\"\"\"\n\n\nPARAM_NAMES = [\n    'time', 'x', 'y', 'z', 'track_azimuth', 'track_zenith', 'cascade_azimuth',\n    'cascade_zenith', 'track_energy', 'cascade_energy', 'cascade_d_zenith',\n    'cascade_d_azimuth'\n]\n\"\"\"All possible hypothesis param names\"\"\"\n\nPEGLEG_PARAM_NAMES = ['track_energy']\n\"\"\"Hypothesis param names handled by pegleg, if it's used\"\"\"\n\nSCALING_PARAM_NAMES = ['cascade_energy']\n\"\"\"Hypothesis param names handled by scaling, if it's used\"\"\"\n", "meta": {"hexsha": "8f4ed05158d7cd949cc36ddb91737eb69384dcb1", "size": 9052, "ext": "py", "lang": "Python", "max_stars_repo_path": "retro/const.py", "max_stars_repo_name": "eat5210/retro", "max_stars_repo_head_hexsha": "4b426422bcb102d8031bc2f5715fd766630162fc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "retro/const.py", "max_issues_repo_name": "eat5210/retro", "max_issues_repo_head_hexsha": "4b426422bcb102d8031bc2f5715fd766630162fc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "retro/const.py", "max_forks_repo_name": "eat5210/retro", "max_forks_repo_head_hexsha": "4b426422bcb102d8031bc2f5715fd766630162fc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8941979522, "max_line_length": 86, "alphanum_fraction": 0.6957578436, "include": true, "reason": "import numpy", "num_tokens": 2913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.17747664781892503}}
{"text": "import numpy as np\nimport scipy\nif tuple(map(int, scipy.__version__.split('.'))) < (1, 0, 0):\n    from scipy.misc import logsumexp\nelse:\n    from scipy.special import logsumexp\nimport math\nimport time\nfrom datetime import date\nimport os\nimport pickle\n\ndef normalize_features(features):\n\t'''features: n by d matrix'''\n\tassert(len(features.shape)==2)\n\tnorma=np.sqrt(np.sum(features ** 2, axis=1).reshape(-1, 1))+1e-6\n\treturn features/norma\n\nclass vMFMM:\n\tdef __init__(self, cls_num, init_method = 'random', tmp_dir = '/tmp/'):\n\t\tself.cls_num = cls_num\n\t\tself.init_method = init_method\n\n\t\tif not os.path.exists(tmp_dir):\n\t\t\tos.makedirs(tmp_dir)\n\n\t\tself.tmp_file = os.path.join(tmp_dir, str(date.today())+'.pickle')\n\n\n\tdef fit(self, features, kappa, max_it=300, tol = 5e-5, normalized=False, verbose=True):\n\t\tself.features = features\n\t\tif not normalized:\n\t\t\tself.features = normalize_features(features)\n\n\t\tself.n, self.d = self.features.shape\n\t\tself.kappa = kappa\n\n\t\tself.pi = np.random.random(self.cls_num)\n\t\tself.pi /= np.sum(self.pi)\n\t\tif self.init_method =='random':\n\t\t\tself.mu = np.random.random((self.cls_num, self.d))\n\t\t\t# self.mu = np.array([[1,0],[0,1]])\n\t\t\tself.mu = normalize_features(self.mu)\n\t\telif self.init_method =='k++':\n\t\t\t#print('start k++')\n\t\t\tcenters = []\n\t\t\tcenters_i = []\n\n\t\t\tif self.n > 50000:\n\t\t\t\trdn_index = np.random.choice(self.n, size=(50000,), replace=False)\n\t\t\telse:\n\t\t\t\trdn_index = np.array(range(self.n), dtype=int)\n\n\t\t\tcos_dis = 1-np.dot(self.features[rdn_index], self.features[rdn_index].T)\n\n\t\t\t#print('finish cos_dis')\n\t\t\tcenters_i.append(np.random.choice(rdn_index))\n\t\t\tcenters.append(self.features[centers_i[0]])\n\t\t\tfor i in range(self.cls_num-1):\n\t\t\t\t#if i%10==0:\n\t\t\t#\t\tprint('k++ center {0}'.format(i))\n\n\t\t\t\tcdisidx = [np.where(rdn_index==cci)[0][0] for cci in centers_i]\n\t\t\t\tprob = np.min(cos_dis[:,cdisidx], axis=1)**2\n\t\t\t\tprob /= np.sum(prob)\n\t\t\t\tcenters_i.append(np.random.choice(rdn_index, p=prob))\n\t\t\t\tcenters.append(self.features[centers_i[-1]])\n\n\t\t\tself.mu = np.array(centers)\n\t\t\tdel(cos_dis)\n\t\t\t#print('finish k++')\n\n\t\tself.mllk_rec = []\n\t\tfor itt in range(max_it):\n\t\t\t_st = time.time()\n\t\t\tself.e_step()\n\t\t\tself.m_step()\n\t\t\t_et = time.time()\n\t\t\t#if verbose and itt%1==0:\n\t\t\t\t#print(\"iter {0}: {1}, time: {2}\".format(itt, self.mllk, (_et-_st)/60))\n\n\t\t\tif itt%20==0:\n\t\t\t\twith open(self.tmp_file, 'wb') as fh:\n\t\t\t\t\tpickle.dump(self.mu, fh)\n\n\t\t\t\tbins = 4\n\t\t\t\tper_bin = self.cls_num//bins+1\n\t\t\t\tfor bb in range(bins):\n\t\t\t\t\twith open(self.tmp_file.replace('.pickle','_p{}.pickle'.format(bb)), 'wb') as fh:\n\t\t\t\t\t\tpickle.dump(self.p[:,bb*per_bin:(bb+1)*per_bin], fh)\n\n\t\t\tself.mllk_rec.append(self.mllk)\n\t\t\tif len(self.mllk_rec)>1 and self.mllk - self.mllk_rec[-2] < tol:\n\t\t\t\tprint(\"early stop at iter {0}, llk {1}\".format(itt, self.mllk))\n\t\t\t\tbreak\n\n\n\tdef fit_soft(self, features, p, mu, pi, kappa, max_it=300, tol = 1e-6, normalized=False, verbose=True):\n\t\tself.features = features\n\t\tif not normalized:\n\t\t\tself.features = normalize_features(features)\n\n\t\tself.p = p\n\t\tself.mu = mu\n\t\tself.pi = pi\n\t\tself.kappa = kappa\n\n\t\tself.n, self.d = self.features.shape\n\n\t\tfor itt in range(max_it):\n\t\t\tself.e_step()\n\t\t\tself.m_step()\n\t\t\t#if verbose and itt%20==0:\n\t\t\t\t#print(\"iter {0}: {1}\".format(itt, self.mllk))\n\n\t\t\tself.mllk_rec.append(self.mllk)\n\t\t\tif len(self.mllk_rec)>1 and self.mllk - self.mllk_rec[-2] < tol:\n\t\t\t\tprint(\"early stop at iter {0}, llk {1}\".format(itt, self.mllk))\n\t\t\t\tbreak\n\n\n\tdef e_step(self):\n\t\t# update p\n\t\tlogP = np.dot(self.features, self.mu.T)*self.kappa + np.log(self.pi).reshape(1,-1)  # n by k\n\t\tlogP_norm = logP - logsumexp(logP, axis=1).reshape(-1,1)\n\t\tself.p = np.exp(logP_norm)\n\t\tself.mllk = np.mean(logsumexp(logP, axis=1))\n\n\n\tdef m_step(self):\n\t\t# update pi and mu\n\t\tself.pi = np.sum(self.p, axis=0)/self.n\n\n\t\t# fast version, requires more memory\n\t\tself.mu = np.dot(self.p.T, self.features)/np.sum(self.p, axis=0).reshape(-1,1)\n\n#         d_cut = 52\n#         bnum = int(math.ceil(self.d/d_cut))\n\n#         for dd_i in range(bnum):\n#             dd_start = dd_i*d_cut\n#             dd_end = min((dd_i+1)*d_cut, self.d)\n#             self.mu[:,dd_start:dd_end] = np.sum(np.tile(self.features.reshape(self.n,1,self.d)[:,:,dd_start:dd_end],(1,self.cls_num,1))*self.p.reshape(self.n,self.cls_num,1),axis=0)/np.sum(self.p, axis=0).reshape(-1,1)\n\n\t\t# for cc in range(self.cls_num):\n\t\t#     self.mu[cc] = np.sum(self.p[:,cc].reshape(-1,1) * self.features, axis=0)/np.sum(self.p[:,cc])\n\n\t\t# r = np.mean(np.sqrt(np.sum(self.mu**2, axis=1))*self.pi)\n\t\t# r = np.mean(np.sqrt(np.sum(self.mu**2, axis=1))/(self.n*self.pi))\n\t\t# self.kappa2 = (r*self.d-r**3)/(1-r**2)\n\n\t\tself.mu = normalize_features(self.mu)\n\n\n\n\n\n", "meta": {"hexsha": "9fb37213a14f1aa5ce088602b347eff66b0160fa", "size": 4660, "ext": "py", "lang": "Python", "max_stars_repo_path": "vMFMM.py", "max_stars_repo_name": "XD7479/Robust-Instance-Segmentation-through-Reasoning-about-Multi-Object-Occlusion", "max_stars_repo_head_hexsha": "593622afbd83981b4c42940d39770ddf9c1b566c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vMFMM.py", "max_issues_repo_name": "XD7479/Robust-Instance-Segmentation-through-Reasoning-about-Multi-Object-Occlusion", "max_issues_repo_head_hexsha": "593622afbd83981b4c42940d39770ddf9c1b566c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vMFMM.py", "max_forks_repo_name": "XD7479/Robust-Instance-Segmentation-through-Reasoning-about-Multi-Object-Occlusion", "max_forks_repo_head_hexsha": "593622afbd83981b4c42940d39770ddf9c1b566c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4936708861, "max_line_length": 220, "alphanum_fraction": 0.6420600858, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 1481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.1774593986282425}}
{"text": "# coding: utf-8\n# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department\n# Distributed under the terms of \"New BSD License\", see the LICENSE file.\n\nfrom __future__ import print_function\nfrom collections import OrderedDict\nimport numpy as np\nfrom pyiron.base.generic.parameters import GenericParameters\nimport decimal as dec\n\ntry:\n    from ase.calculators.lammps import Prism\n\nexcept ImportError:\n    try:\n        from ase.calculators.lammpsrun import Prism\n    except ImportError:\n        from ase.calculators.lammpsrun import prism as Prism\n\n__author__ = \"Joerg Neugebauer, Sudarsan Surendralal, Yury Lysogorskiy, Jan Janssen, Markus Tautschnig\"\n__copyright__ = \"Copyright 2019, Max-Planck-Institut für Eisenforschung GmbH - \" \\\n                \"Computational Materials Design (CM) Department\"\n__version__ = \"1.0\"\n__maintainer__ = \"Sudarsan Surendralal\"\n__email__ = \"surendralal@mpie.de\"\n__status__ = \"production\"\n__date__ = \"Sep 1, 2017\"\n\n\nclass UnfoldingPrism(Prism):\n    \"\"\"\n    Create a lammps-style triclinic prism object from a cell\n\n    The main purpose of the prism-object is to create suitable\n    string representations of prism limits and atom positions\n    within the prism.\n    When creating the object, the digits parameter (default set to 10)\n    specify the precision to use.\n    lammps is picky about stuff being within semi-open intervals,\n    e.g. for atom positions (when using create_atom in the in-file),\n    x must be within [xlo, xhi).\n\n    Args:\n        cell: \n        pbc: \n        digits: \n    \"\"\"\n    def __init__(self, cell, pbc=(True, True, True), digits=10):\n        # Temporary fix. Since the arguments for the constructor have changed, try to see if it is compatible with\n        # the latest ase. If not, revert to the old __init__ parameters.\n        try:\n            super(UnfoldingPrism, self).__init__(cell, pbc=pbc, tolerance=float('1e-{}'.format(digits)))\n        except TypeError:\n            super(UnfoldingPrism, self).__init__(cell, pbc=pbc, digits=digits)\n        a, b, c = cell\n        an, bn, cn = [np.linalg.norm(v) for v in cell]\n\n        alpha = np.arccos(np.dot(b, c) / (bn * cn))\n        beta = np.arccos(np.dot(a, c) / (an * cn))\n        gamma = np.arccos(np.dot(a, b) / (an * bn))\n\n        xhi = an\n        xyp = np.cos(gamma) * bn\n        yhi = np.sin(gamma) * bn\n        xzp = np.cos(beta) * cn\n        yzp = (bn * cn * np.cos(alpha) - xyp * xzp) / yhi\n        zhi = np.sqrt(cn ** 2 - xzp ** 2 - yzp ** 2)\n\n        # Set precision\n        self.car_prec = dec.Decimal('10.0') ** \\\n                        int(np.floor(np.log10(max((xhi, yhi, zhi)))) - digits)\n        self.dir_prec = dec.Decimal('10.0') ** (-digits)\n        self.acc = float(self.car_prec)\n        self.eps = np.finfo(xhi).eps\n\n        # For rotating positions from ase to lammps\n        apre = np.array(((xhi, 0, 0),\n                         (xyp, yhi, 0),\n                         (xzp, yzp, zhi)))\n        self.R = np.dot(np.linalg.inv(cell), apre)\n\n        # Actual lammps cell may be different from what is used to create R\n        eps = 1e-10\n\n        def fold(vec, pvec, i):\n            p = pvec[i]\n            x = vec[i] + 0.5 * p\n            n = (np.mod(x, p) - x) / p\n            # print ('prism: ', n, x, p)\n            return [float(self.f2qdec(vec_a)) for vec_a in (vec + n * pvec)], n\n\n        apre[1, :], n1 = fold(apre[1, :], apre[0, :], 0)\n        if np.abs(apre[1, 0] / apre[0, 0]) > 0.5:\n            apre[1, 0] -= np.sign(n1) * apre[0, 0]\n            n1 -= np.sign(n1)\n\n        apre[2, :], n2 = fold(apre[2, :], apre[1, :], 1)\n        if np.abs(apre[2, 1] / apre[1, 1]) > 0.5:\n            apre[2, 1] -= np.sign(n2) * apre[1, 1]\n            n2 -= np.sign(n2)\n\n        apre[2, :], n3 = fold(apre[2, :], apre[0, :], 0)\n        if np.abs(apre[2, 0] / apre[0, 0]) > 0.5:\n            apre[2, 0] -= np.sign(n3) * apre[0, 0]\n            n3 -= np.sign(n3)\n        self.ns = [n1, n2, n3]\n        \n        d_a = apre[0, 0]/2 - apre[1,0]\n        if np.abs(d_a) < eps:\n            if d_a < 0:\n                print ('debug: apply shift')\n                apre[1, 0] += 2 * d_a\n                apre[2, 0] += 2 * d_a\n        self.A = apre\n        self.Ainv = np.linalg.inv(self.A)\n        self.prism = None\n\n        if self.is_skewed() and \\\n                (not (pbc[0] and pbc[1] and pbc[2])):\n            raise RuntimeError('Skewed lammps cells MUST have '\n                               'PBC == True in all directions!')\n\n    def unfold_cell(self, cell):\n        \"\"\"\n        Unfold LAMMPS cell to original\n        \n        Args:\n            cell: LAMMPS cell,\n\n        Returns:\n            unfolded cell\n        \"\"\"\n        a = cell[0]\n        bp = cell[1]\n        cpp = cell[2]\n        (n1, n2, n3) = self.ns\n        b = bp - n1 * a\n        c = cpp - n2 * bp - n3 * a\n        return np.array([a, b, c])\n\n    def pos_to_lammps(self, position):\n        \"\"\"\n        Rotate an ase-cell position to the lammps cell orientation\n        \n        Args:\n            position: \n\n        Returns:\n            tuple of float.\n        \"\"\"\n        return tuple([x for x in np.dot(position, self.R)])\n\n    def f2qdec(self, f):\n        return dec.Decimal(repr(f)).quantize(self.car_prec, dec.ROUND_DOWN)\n\n    def f2s(self, f):\n        return str(dec.Decimal(repr(f)).quantize(self.car_prec, dec.ROUND_HALF_EVEN))\n\n    def get_lammps_prism_str(self):\n        \"\"\"Return a tuple of strings\"\"\"\n        p = self.get_lammps_prism()\n        return tuple([self.f2s(x) for x in p])\n\n\nclass LammpsStructure(GenericParameters):\n    \"\"\"\n\n    Args:\n        input_file_name: \n    \"\"\"\n    def __init__(self, input_file_name=None):\n        super(LammpsStructure, self).__init__(input_file_name=input_file_name,\n                                              table_name=\"structure_inp\",\n                                              comment_char=\"#\",\n                                              val_only=True)\n        self._structure = None\n        self._potential = None\n        self._el_eam_lst = []\n        self.atom_type = None\n        self.cutoff_radius = None\n        self.digits = 10\n\n    @property\n    def potential(self):\n        return self._potential\n\n    @potential.setter\n    def potential(self, val):\n        self._potential = val\n\n    @property\n    def structure(self):\n        \"\"\"\n        \n        Returns:\n\n        \"\"\"\n        return self._structure\n\n    @structure.setter\n    def structure(self, structure):\n        \"\"\"\n        \n        Args:\n            structure: \n\n        Returns:\n\n        \"\"\"\n        self._structure = structure\n        if self.atom_type == 'full':\n            input_str = self.structure_full()\n        elif self.atom_type == 'bond':\n            input_str = self.structure_bond()\n        elif self.atom_type == 'charge':\n            input_str = self.structure_charge()\n        else:  # self.atom_type == 'atomic'\n            input_str = self.structure_atomic()\n        self.load_string(input_str)\n\n    @property\n    def el_eam_lst(self):\n        \"\"\"\n        \n        Returns:\n\n        \"\"\"\n        return self._el_eam_lst\n\n    @el_eam_lst.setter\n    def el_eam_lst(self, el_eam_lst):\n        \"\"\"\n        \n        Args:\n            el_eam_lst: \n\n        Returns:\n\n        \"\"\"\n        self._el_eam_lst = el_eam_lst\n\n    def load_default(self):\n        \"\"\"\n        \n        Returns:\n\n        \"\"\"\n        input_str = ''\n        self.load_string(input_str)\n\n    # def f2s(self, f):\n    #     return str(dec.Decimal(repr(f)).quantize(self.car_prec,\n    #                                              dec.ROUND_HALF_EVEN))\n\n    def simulation_cell(self):\n        \"\"\"\n        \n        Returns:\n\n        \"\"\"\n        # dim = self._structure.dimension\n        # amat = self._structure.cell\n\n        self.prism = UnfoldingPrism(self._structure.cell, digits=15)\n        xhi, yhi, zhi, xy, xz, yz = self.prism.get_lammps_prism_str()\n        # Please, be carefull and not round xhi, yhi,..., otherwise you will get too skew cell from LAMMPS.\n        # These values are already checked in UnfoldingPrism to fullfill LAMMPS skewness criteria\n        simulation_cell = '0. {} xlo xhi\\n'.format(xhi) + \\\n                          '0. {} ylo yhi\\n'.format(yhi) + \\\n                          '0. {} zlo zhi\\n'.format(zhi)\n\n        if self.prism.is_skewed():\n            simulation_cell += '{0} {1} {2} xy xz yz\\n'.format(xy, xz, yz)\n\n        # if s.VERBOSE():\n        #     s.warning(\"triclinic cells not supported for test purposes\",\n        #               module=\"lammps.lammps.LammpsStructure.simulation_cell\")\n        return simulation_cell\n\n    def structure_bond(self):\n        \"\"\"\n        \n        Returns:\n\n        \"\"\"\n        # analyze structure to get molecule_ids, bonds, angles etc\n        coords = self.rotate_positions(self._structure)\n\n        elements = self._structure.get_chemical_symbols()\n        el_list = self._structure.get_species_symbols()\n        el_dict = OrderedDict()\n        for object_id, el in enumerate(el_list):\n            el_dict[el] = object_id\n\n        n_s = len(el_list)\n        bond_type = np.ones([n_s, n_s], dtype=np.int)\n        count = 0\n        for i in range(n_s):\n            for j in range(i, n_s):\n                count += 1\n                bond_type[i, j] = count\n                bond_type[j, i] = count\n        # print \"bond_type: \", bond_type\n\n        if self.structure.bonds is None:\n            if self.cutoff_radius is None:\n                bonds_lst = self.structure.get_bonds(max_shells=1)\n            else:\n                bonds_lst = self.structure.get_bonds(radius=self.cutoff_radius)\n            bonds = []\n            # id_mol = 0\n            for ia, i_bonds in enumerate(bonds_lst):\n                el_i = el_dict[elements[ia]]\n                for el_j, b_lst in i_bonds.items():\n                    b_type = bond_type[el_i][el_dict[el_j]]\n                    for i_shell, ib_shell_lst in enumerate(b_lst):\n                        for ib in np.unique(ib_shell_lst):\n                            if ia < ib:  # avoid double counting of bonds\n                                bonds.append([ia + 1, ib + 1, b_type])\n\n            self.structure.bonds = np.array(bonds)\n        bonds = self.structure.bonds\n\n        atomtypes = ' Start File for LAMMPS \\n' + \\\n                    '{0:d} atoms'.format(len(self._structure)) + ' \\n' + \\\n                    '{0:d} bonds'.format(len(bonds)) + ' \\n' + \\\n                    '{0} atom types'.format(self._structure.get_number_of_species()) + ' \\n' + \\\n                    '{0} bond types'.format(np.max(bond_type)) + ' \\n'\n\n        cell_dimesions = self.simulation_cell()\n\n        masses = 'Masses \\n\\n'\n        el_obj_list = self._structure.get_species_objects()\n        for object_id, el in enumerate(el_obj_list):\n            masses += '{0:3d} {1:f}'.format(object_id + 1, el.AtomicMass) + '\\n'\n\n        atoms = 'Atoms \\n\\n'\n\n        # atom_style bond\n        # format: atom-ID, molecule-ID, atom_type, x, y, z\n        format_str = '{0:d} {1:d} {2:d} {3:f} {4:f} {5:f} '\n        if self._structure.dimension == 3:\n            for id_atom, (x, y, z) in enumerate(coords):\n                id_mol, id_species = 1, el_dict[elements[id_atom]]  # elList[id_atom]\n                # print id_atom + 1, id_mol, id_species + 1, x, y, z\n                atoms += format_str.format(id_atom + 1, id_mol, id_species + 1, x, y, z) + '\\n'\n        elif self._structure.dimension == 2:\n            for id_atom, (x, y) in enumerate(coords):\n                id_mol, id_species = 1, el_dict[elements[id_atom]]  # elList[id_atom]\n                # print id_atom + 1, id_mol, id_species + 1, x, y, z\n                atoms += format_str.format(id_atom + 1, id_mol, id_species + 1, x, y, 0.) + '\\n'\n        else:\n            raise ValueError(\"dimension 1 not yet implemented\")\n\n        bonds_str = 'Bonds \\n\\n'\n        for i_bond, (i_a, i_b, b_type) in enumerate(bonds):\n            bonds_str += '{0:d} {1:d} {2:d} {3:d}'.format(i_bond + 1, b_type, i_a, i_b) + '\\n'\n\n        return atomtypes + '\\n' + cell_dimesions + '\\n' + masses + '\\n' + atoms + '\\n' + bonds_str + '\\n'\n\n    def structure_full(self):\n        \"\"\"\n        Write routine to create atom structure static file for atom_type='full' that can be loaded by LAMMPS\n\n        Returns:\n\n        \"\"\"\n        coords = self.rotate_positions(self._structure)\n\n        # extract electric charges from potential file\n        q_dict = {}\n        for el in self._structure.get_species_symbols():\n            q_dict[el] = float(self.potential.get(\"set group {} charge\".format(el)))\n\n        species_translate_list = list()\n        sorted_species_list = self._structure.get_species_symbols()\n        for el in self._structure.species:\n            ind = np.argwhere(sorted_species_list == el.Abbreviation).flatten()[-1]\n            species_translate_list.append(ind)\n\n        # analyze structure to get molecule_ids, bonds, angles etc\n        molecule_lst, bonds_lst, angles_lst = [], [], []\n\n        # species_lst = structure.get_species_objects()\n        # for id_el, el in enumerate(structure.species):\n        #     el.id = id\n        # el_lst = structure.get_chemical_elements()\n\n        num_atoms_in_molecule = 3\n        neighbors = self._structure.get_neighbors(num_neighbors=num_atoms_in_molecule + 2)\n        # print \"neighbors: \", neighbors.distances\n        id_mol = 0\n        indices = self._structure.indices\n        for id_el, id_species in enumerate(indices):\n            el = self._structure.species[id_species]\n            # print \"id: \", id, el.Abbreviation, neighbors.indices[id][0:2]\n            if el.Abbreviation in [\"O\"]:\n                # print \"id_mol: \", id_mol\n                id_mol += 1\n                molecule_lst.append([id_el, id_mol, id_species])\n                # Just to ensure that the attached atoms are indeed H atoms\n                # id_n1, id_n2 = np.intersect1d(neighbors.indices[id_el], self._structure.select_index(\"H\"))[0:2]\n                id_n1, id_n2 = neighbors.indices[id_el][0:2]\n                # print \"id: \", id, id_n1, len(el_lst), el_lst[1].id\n                molecule_lst.append([id_n1, id_mol, species_translate_list[indices[id_n1]]])\n                molecule_lst.append([id_n2, id_mol, species_translate_list[indices[id_n2]]])\n\n                bonds_lst.append([id_el + 1, id_n1 + 1])\n                bonds_lst.append([id_el + 1, id_n2 + 1])\n\n                angles_lst.append([id_n1 + 1, id_el + 1, id_n2 + 1])\n            elif el.Abbreviation not in [\"H\"]:  # non-bonded ions\n                id_mol += 1\n                molecule_lst.append([id_el, id_mol, id_species])\n\n        m_lst = np.array(molecule_lst)\n        molecule_lst = m_lst[m_lst[:, 0].argsort()]\n        # print \"m_lst: \", m_lst\n        # print \"mol: \", molecule_lst\n\n        atomtypes = ' Start File for LAMMPS \\n' + \\\n                    '{0:d} atoms'.format(len(self._structure)) + ' \\n' + \\\n                    '{0:d} bonds'.format(len(bonds_lst)) + ' \\n' + \\\n                    '{0:d} angles'.format(len(angles_lst)) + ' \\n' + \\\n                    '{0} atom types'.format(self._structure.get_number_of_species()) + ' \\n' + \\\n                    '{0} bond types'.format(1) + ' \\n' + \\\n                    '{0} angle types'.format(1) + ' \\n'\n\n        cell_dimensions = self.simulation_cell()\n\n        masses = 'Masses' + '\\n\\n'\n        el_obj_list = self._structure.get_species_objects()\n        for object_id, el in enumerate(el_obj_list):\n            masses += '{0:3d} {1:f}'.format(object_id + 1, el.AtomicMass) + '\\n'\n\n        atoms = 'Atoms \\n\\n'\n\n        # format: atom-ID, molecule-ID, atom_type, q, x, y, z\n        format_str = '{0:d} {1:d} {2:d} {3:f} {4:f} {5:f} {6:f}'\n        for atom in molecule_lst:\n            id_atom, id_mol, id_species = atom\n            # print id_atom, id_mol, id_species\n            x, y, z = coords[id_atom]\n            el_id = self._structure.species[id_species].Abbreviation\n            atoms += format_str.format(id_atom + 1, id_mol, id_species + 1, q_dict[el_id], x, y, z) + '\\n'\n\n        if len(bonds_lst) > 0:\n            bonds_str = 'Bonds \\n\\n'\n            for i_bond, id_vec in enumerate(bonds_lst):\n                bonds_str += '{0:d} {1:d} {2:d} {3:d}'.format(i_bond + 1, 1, id_vec[0], id_vec[1]) + '\\n'\n        else:\n            bonds_str = \"\\n\"\n\n        if len(angles_lst) > 0:\n            angles_str = 'Angles \\n\\n'\n            for i_angle, id_vec in enumerate(angles_lst):\n                # print \"id: \", i_angle, id_vec\n                angles_str += '{0:d} {1:d} {2:d} {3:d} {4:d}'.format(i_angle + 1, 1, id_vec[0], id_vec[1], id_vec[2]) \\\n                              + '\\n'\n        else:\n            angles_str = \"\\n\"\n        return atomtypes + '\\n' + cell_dimensions + '\\n' + masses + '\\n' + atoms + '\\n' \\\n               + bonds_str + '\\n' + angles_str + '\\n'\n\n    def structure_charge(self):\n        \"\"\"\n        Create atom structure including the atom charges.\n        \n        By convention the LAMMPS atom type numbers are chose alphabetically for the chemical species.\n        \n        Returns: LAMMPS readable structure.\n\n        \"\"\"\n        atomtypes = 'Start File for LAMMPS \\n' + \\\n                    '{0:d} atoms'.format(self._structure.get_number_of_atoms()) + ' \\n' + \\\n                    '{0} atom types'.format(self._structure.get_number_of_species()) + ' \\n'\n\n        cell_dimesions = self.simulation_cell()\n\n        masses = 'Masses\\n\\n'\n        \n        for ind, obj in enumerate(self._structure.get_species_objects()):\n            masses += '{0:3d} {1:f}'.format(ind+1, obj.AtomicMass) + '\\n'\n\n\n        atoms = 'Atoms\\n\\n'\n\n        coords = self.rotate_positions(self._structure)\n\n        el_charge_lst = self._structure.charge\n        el_lst = self._structure.get_chemical_symbols()\n        el_alphabet_dict = {}\n        for ind,el in enumerate(self._structure.get_species_symbols()):\n            el_alphabet_dict[el] = ind+1\n        for id_atom, (el, coord) in enumerate(zip(el_lst, coords)):\n            id_el = el_alphabet_dict[el]\n            dim = self._structure.dimension\n            c = np.zeros(3)\n            c[:dim] = coord\n            atoms += '{0:d} {1:d} {2:f} {3:.15f} {4:.15f} {5:.15f}'.format(\n                id_atom + 1, id_el, el_charge_lst[id_atom], c[0], c[1], c[2]) + '\\n'\n        return atomtypes + '\\n' + cell_dimesions + '\\n' + masses + '\\n' + atoms + '\\n'\n\n \n    def structure_atomic(self):\n        \"\"\"\n        Write routine to create atom structure static file that can be loaded by LAMMPS\n        \n        Returns:\n\n        \"\"\"\n        atomtypes = 'Start File for LAMMPS \\n' + \\\n                    '{0:d} atoms'.format(len(self._structure)) + ' \\n' + \\\n                    '{0} atom types'.format(len(\n                        self._el_eam_lst)) + ' \\n'  # '{0} atom types'.format(structure.get_number_of_species()) + ' \\n'\n\n        cell_dimesions = self.simulation_cell()\n\n        masses = 'Masses\\n\\n'\n\n        el_struct_lst = self._structure.get_species_symbols()\n        el_obj_lst = self._structure.get_species_objects()\n        # el_struct_lst = structure.get_chemical_symbols()\n        # el_obj_lst = structure.get_chemical_elements()\n        el_dict = {}\n        for id_eam, el_eam in enumerate(self._el_eam_lst):\n            if el_eam in el_struct_lst:\n                id_el = list(el_struct_lst).index(el_eam)\n                el = el_obj_lst[id_el]\n                el_dict[el] = id_eam + 1\n                masses += '{0:3d} {1:f}'.format(id_eam + 1, el.AtomicMass) + '\\n'\n            else:\n                # element in EAM file but not used in structure, use dummy for atomic mass\n                masses += '{0:3d} {1:f}'.format(id_eam + 1, 1.00) + '\\n'\n\n        atoms = 'Atoms\\n\\n'\n\n        coords = self.rotate_positions(self._structure)\n\n        el_lst = self._structure.get_chemical_elements()\n        for id_atom, (el, coord) in enumerate(zip(el_lst, coords)):\n            id_el = el_dict[el]\n            dim = self._structure.dimension\n            c = np.zeros(3)\n            c[:dim] = coord\n            atoms += '{0:d} {1:d} {2:.15f} {3:.15f} {4:.15f}'.format(id_atom + 1, id_el, c[0], c[1], c[2]) + '\\n'\n        return atomtypes + '\\n' + cell_dimesions + '\\n' + masses + '\\n' + atoms + '\\n'\n\n    def rotate_positions(self, structure):\n        \"\"\"\n        Rotate all atomic positions in given structure according to new Prism cell\n        \n        Args:\n            structure: Atoms-like object. Should has .positions attribute\n\n        Returns:\n            (list): List of rotated coordinates\n        \"\"\"\n        prism = UnfoldingPrism(self._structure.cell)\n        coords = [prism.pos_to_lammps(position) for position in structure.positions]\n        return coords\n\n\ndef write_lammps_datafile(structure, file_name='lammps.data', cwd=None):\n    lammps_str = LammpsStructure()\n    lammps_str.el_eam_lst = structure.get_species_symbols()\n    lammps_str.structure = structure\n    lammps_str.write_file(file_name=file_name, cwd=cwd)\n", "meta": {"hexsha": "a6c7cf6e55d7d84d2bca87260740b4ef3e44e9dd", "size": 20982, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyiron/lammps/structure.py", "max_stars_repo_name": "SanderBorgmans/pyiron", "max_stars_repo_head_hexsha": "81121b767b1d6371eb7c07be8e9301eba48aa557", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyiron/lammps/structure.py", "max_issues_repo_name": "SanderBorgmans/pyiron", "max_issues_repo_head_hexsha": "81121b767b1d6371eb7c07be8e9301eba48aa557", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyiron/lammps/structure.py", "max_forks_repo_name": "SanderBorgmans/pyiron", "max_forks_repo_head_hexsha": "81121b767b1d6371eb7c07be8e9301eba48aa557", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-17T17:00:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-22T15:17:59.000Z", "avg_line_length": 36.8752196837, "max_line_length": 120, "alphanum_fraction": 0.5468020208, "include": true, "reason": "import numpy", "num_tokens": 5622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.1774593986282425}}
{"text": "# Copyright [2017] [Ronald Fowler]\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\" Utilities for beam hardening correction method. Classes are provided\nto load the various data types that are needed by the algorithm.\nclasses:\n\n    specData  object to load and store X-ray spectrum for specified case\n    carousel  object to load and store description of test carousel\n    carouselCalibrationData  object to load and store the calibration data\n    fitData  object with methods and data related to the fitting process\n\n\"\"\"\n# just for reading 16 bit images and conversion to log(I0/I)\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nimport os\nimport logging\nimport pdb\nimport pkg_resources\ntry:\n    import numpy as np\nexcept ImportError:\n    sys.exit(\"Error: cant find numpy\")\ntry:\n    import matplotlib.pyplot as plt\nexcept ImportError:\n    sys.exit(\"Error: cant find matplotlib\")\n\n\ndef resourcepath(filename):\n    if os.path.isfile(filename):\n        return filename\n    try:\n        pkgfilename = pkg_resources.resource_filename(__name__,'/data/'+filename)\n        return pkgfilename\n    except:\n        pass\n    return filename\n    \nclass specData(object):\n    \"\"\"\n    Spectral data for given condition\n\n    Data referes to the initial values of target, voltage and angle.\n    This object contains the spectral data for the given\n    target material, applied voltage and take off angle.\n    Currently this is only available for Tungsten in the range\n    1-150KeV from data obtained from Spekcalc at fixed set of values.\n    Interpolation may be used for intermeidate points.\n    The resolution is as set in the data files.\n    Note that only one spectrum is loaded as we do not vary\n    the voltage in this fitting procedure.\n\n    Attributes\n   \n    target : string\n        X-ray tube target material, chemical symbol e.g. W\n    voltage : float\n        applied voltage to the X-ray tube in KeV\n    angle : float\n        take off angle in degrees for the X-ray beam. This is kept constant\n\n    Methods\n    \n    getE()\n        Get array of energies over which the spectrum is defined (KeV)\n    getS()\n        Get array of spectral intensities corresponding to energies of getE()\n    getEnergyRes()\n        Return the step size between spectral points, assumed constant.\n    getMaxEnergy()\n        Return the applied voltage (KeV)\n    isValid()\n        Flag to indicate if object correctly set up.\n    \"\"\"\n\n    def __init__(self, target, voltage, angle):\n        \"\"\" set up spectrum from file for given state \"\"\"\n        self.target = target\n        self.voltage = voltage\n        self.angle = angle\n        # initialise these for pylint\n        self.en = None\n        self.amp = None\n        self.valid = False\n        self.readData(target, voltage, angle)\n\n    def readData(self, target, voltage, angle):\n        \"\"\" Read the spectra for this voltage/angle pair from file.\n            If file not found, return spec=0 \"\"\"\n        filename = resourcepath(\"spectra/%s/%03d%03d.spc\" % (target, voltage, angle*10))\n        if not os.path.isfile(filename):\n            print(\"File not found: \", filename, \" in spectra\")\n            print(\"Only fitting with function spectra possible\")\n            # just set energy array 0 to voltage, in 0.5KeV steps\n            estep=0.5\n            self.en = np.arange(voltage/estep+estep*0.5)*estep\n        else:\n            with open(filename, 'r') as fl:\n                self.en, self.amp = np.loadtxt(fl, unpack=True)\n        self.valid = True\n\n    def getE(self):\n        \"\"\" return energy array; should remove \"\"\"\n        return self.en\n\n    def getS(self):\n        \"\"\" return intensity of spectra at energy points\"\"\"\n        return self.amp\n\n    def getEnergyRes(self):\n        \"\"\" return the (assumed constant) energy resolution\"\"\"\n        return self.en[1]-self.en[0]\n\n    def getMaxEnergy(self):\n        \"\"\" voltage is max energy\"\"\"\n        return self.voltage\n\n    def isValid(self):\n        \"\"\" has object been set up OK\"\"\"\n        return self.valid\n\nclass materialAtt(object):\n    \"\"\"Attenuation for a material expressed as formula\n\n    For each material of interest will create this object to represent attenuation\n    as a function of energy. Material is idenitified by chemical symbol and data is\n    read from file produced by xcom.f.\n    \"\"\"\n\n    def __init__(self, formula, density):\n        self.name = formula\n        # for pylint\n        self.mu = None\n        self.energy = None\n        self.valid = False\n        if len(formula) != 0:\n            self.readFile(formula, density)\n\n    def readFile(self, formula, density):\n        \"\"\" load the mu data for this material from a simple ascii file in ./xcom\n             mu is mulitplied by density \"\"\"\n        filename = resourcepath(\"xcom/%s.txt\" % (formula))\n        if os.path.isfile(filename):\n            with open(filename, 'r') as fl:\n                self.energy, self.mu = np.loadtxt(fl, unpack=True)\n                self.mu = self.mu*density\n            self.valid = True\n        else:\n            print(\"failed to find attenuation file: \", filename)\n            self.valid = False\n\n    def getE(self):\n        \"\"\" return array of energy data\"\"\"\n        return self.energy\n\n    def getMu(self):\n        \"\"\" attenuation array\"\"\"\n        return self.mu\n\n    def getEnergyRes(self):\n        \"\"\" energy resolution, assumed constant\"\"\"\n        return self.energy[1]-self.energy[0]\n\n    def getMaxEnergy(self):\n        \"\"\" highest energy value recorded\"\"\"\n        return self.energy[-1]\n\n    def getMuByE(self,energyVal):\n        \"\"\" return attenuation for the given energy \"\"\"\n        if energyVal<0:\n            print(\"error: bad value in getMuByE\")\n            return -1.\n        for i in range(len(self.energy)):\n            if energyVal <= self.energy[i]:\n                if energyVal == self.energy[i]:\n                    return self.mu[i]\n                else:\n                    frac = (energyVal-self.energy[i-1])/(self.energy[i]-self.energy[i-1])\n                    muVal = self.mu[i-1]+(self.mu[i]-self.mu[i-1])*frac\n                    return muVal\n        print(\"error: failed to match energy in getMuByE\")\n        return -1.\n\n    def isValid(self):\n        \"\"\" if object ok\"\"\"\n        return self.valid\n\nclass carousel(object):\n    \"\"\" class for data describing the test carousel \"\"\"\n\n    def __init__(self, defFile):\n        self.defFile = resourcepath(defFile)\n        self.info = None\n        self.density = None\n        self.numSamples = None\n        self.sampWidth = None\n        self.materialTypes = None\n        self.mask = None\n        self.valid = False\n        self.filterAtt = {}\n        self.__readFile(self.defFile)\n\n    def __readFile(self, defFile):\n        \"\"\" read a simple ascii file describing carousel from file\n        \"\"\"\n        if os.path.isfile(defFile):\n            with open(defFile, 'r') as fl:\n                self.info = fl.readline()\n                self.numSamples = int(fl.readline())\n                self.materialTypes = []\n                mline = fl.readline()\n                self.materialTypes = mline.split(',')\n                self.density = np.fromstring(fl.readline(), dtype = float, sep=',')\n                self.sampWidth = np.fromstring(fl.readline(), dtype = float,\n                                               sep=',')\n                self.filterAtt = {}\n                # assume last sample is labeled \"Nothing\"\n                for i in range(self.numSamples - 1):\n                    try:\n                        self.filterAtt[i] = materialAtt(self.materialTypes[i],self.density[i])\n                    except:\n                        print(\"** failed to set carousel attenuation for \",self.materialTypes[i])\n                self.mask = np.zeros((self.numSamples),dtype=bool)\n            self.valid = True\n        else:\n            print(\"failed to find carousel file: \", defFile)\n            self.valid = False\n\n    def getSamples(self):\n        \"\"\" elements in the carousel \"\"\"\n        return self.numSamples\n\n    def isValid(self):\n        \"\"\" is object ok\"\"\"\n        return self.valid\n\nclass carouselCalibrationData(object):\n    \"\"\" This class reads the calibration data from a carousel calibration file.\n\n    The calibration file contains information about the X-ray voltage, take-off angle,\n    target material and image resolution.\n    It also gives the name & possibly the format of the image data file for the carousel.\n    \"\"\"\n    def __init__(self, calFile, carouselInfo):\n        self.calFile = resourcepath(calFile)\n        self.samples = carouselInfo.getSamples()-1 # note that last sample \"Nothing\" has no image\n        self.voltage = None\n        self.targeMat = None\n        self.rows = 0\n        self.lines = 0\n        self.angle = 0\n        self.filterDensity = 0\n        self.valid = False\n\n        self.filterMaterial = {}\n        self.filterWidth = {}\n        self.filterDensity = {}\n        self.filterAtten = {}\n\n        self.detectorMaterial = ''\n        self.detectorWidth = 0.\n        self.detectorDensity = 0.\n        self.detectorAtten = {}\n\n        self.targetMat = ''\n        self.targetDensity = 0.\n        self.targetAtten = {}\n\n        self.info = ''\n        self.imageFileFormat = ''\n        self.imageFile = ''\n        self.image = {}\n        self.spec = {}\n        self.filterCount = 0\n        self.__centre = None\n\n        self.__readCalFile(self.calFile)\n        if self.valid:\n            try:\n                self.whiteLevel = 0\n                self.__readImageFile(self.imageFile)\n                self.__setAverages()\n                self.width = 100\n                self.__cacheAveSet = False\n                self.__cacheAve = np.zeros(shape=(self.samples, self.lines))\n                logging.debug('initialised cacheAve')\n            except:\n                self.valid = False\n                logging.debug('reading data failed')\n\n    def __readCalFile(self, calFile):\n        \"\"\" read calibration data file, and from that the actual image data\"\"\"\n        if os.path.isfile(calFile):\n            with open(calFile, 'r') as fl:\n                try:\n                    self.info = self.__readLineStrip(fl)\n                    self.voltage = float(self.__readLineStrip(fl))\n                    self.angle = float(self.__readLineStrip(fl))\n                    self.targetMat = self.__readLineStrip(fl).rstrip()\n                    self.targetDensity = float(self.__readLineStrip(fl).rstrip())\n                    if self.targetMat != \"W\":\n                        print(\"Warning: only W (Tungsten) target supported at present: not '\", self.targetMat, \"'\")\n                    try:\n                        self.targetAtten = materialAtt(self.targetMat,self.targetDensity)\n                    except:\n                        print(\"** failed to set target attenuation for \",self.targetMat)\n                    try:\n                        self.spec = specData(self.targetMat,self.voltage,self.angle)\n                    except:\n                        print(\"** failed to load spectra for \",self.targetMat,self.voltage,self.angle)\n                    self.rows = int(self.__readLineStrip(fl))\n                    self.lines = int(self.__readLineStrip(fl))\n                    self.imageFile = self.__readLineStrip(fl)\n                    self.imageFileFormat = self.__readLineStrip(fl)\n                    self.filterCount = int(self.__readLineStrip(fl))\n                    for i in range(self.filterCount):\n                        self.filterMaterial[i] = self.__readLineStrip(fl)\n                        self.filterWidth[i] = float(self.__readLineStrip(fl))\n                        self.filterDensity[i] = float(self.__readLineStrip(fl))\n                        try:\n                            self.filterAtten[i] = materialAtt(self.filterMaterial[i],self.filterDensity[i])\n                        except:\n                            print(\"** failed to set attenuation for \",self.filterMaterial[i])\n\n                    self.detectorMaterial = self.__readLineStrip(fl)\n                    self.detectorWidth = float(self.__readLineStrip(fl))\n                    self.detectorDensity = float(self.__readLineStrip(fl))\n                    try:\n                        self.detectorAtten = materialAtt(self.detectorMaterial,self.detectorDensity)\n                    except:\n                        print(\"** failed to set detector attenuation for \",self.detectorMaterial)\n                    self.valid = True\n                except (ValueError, IOError):\n                    print(\"Read Calibration file failed\")\n                    self.valid = False\n        else:\n            print(\"failed to find calibration file: \", calFile)\n            self.valid = False\n\n    def __readLineStrip(self, fl):\n        \"\"\" read line: strip newline and anything beyond #, if present\n        \"\"\"\n        strng = fl.readline()\n        if strng.find(\"#\") == -1:\n            return strng.rstrip()\n        else:\n            return strng[:strng.find(\"#\")].rstrip()\n\n    def __readImageFile(self, imageFile):\n        \"\"\" read the image data based on specificed format \"\"\"\n        if os.path.isfile(imageFile):\n            if self.imageFileFormat == \"uint16\":\n                # if raw uint16 data, assume first image is flat field and normalise\n                # rest of images by this and take log(I0/I)\n                nimages = self.samples+1\n                with open(imageFile, 'rb') as fl:\n                    tmpimage = np.fromfile(fl, dtype = self.imageFileFormat,\n                                           count = self.rows*self.lines*nimages)\n                    tmpimage = tmpimage.reshape(nimages, self.lines, self.rows)\n                self.image = np.zeros(self.rows*self.lines*self.samples,\n                                      dtype=float).reshape(self.samples, self.lines, self.rows)\n                # note - imported division from _future_ to avoid int div\n\n                # assume that the first image is the white level, I0, a constant\n                # over the image. To impose this assumption we take the average\n                # value over the first (flat field, shading corrected) image.\n                # This is only set for uint16; it is not known for float32\n                whiteLev = np.average(tmpimage[0,:,:])\n                self.whiteLevel = whiteLev\n                for i in range(nimages-1):\n                    # catch zero data:\n                    if np.min(tmpimage[i+1,:,:])==0:\n                        imt = tmpimage[i+1,:,:]\n                        imt[imt==0] = np.mean(imt)\n                        logging.warning('zero data replaced in image %d',i+1)\n                    self.image[i,:,:] = np.log( whiteLev / tmpimage[i+1,:,:] )\n\n            elif self.imageFileFormat == \"uint16_65535\":\n                # if raw uint16_65535 data, whitelevel set as 65535\n                # Question: Should we allow other values of whitelevel?\n                nimages = self.samples\n                with open(imageFile, 'rb') as fl:\n                    tmpimage = np.fromfile(fl, dtype = \"uint16\",\n                                           count = self.rows*self.lines*nimages)\n                    tmpimage = tmpimage.reshape(nimages, self.lines, self.rows)\n                self.image = np.zeros(self.rows*self.lines*self.samples,\n                                      dtype=float).reshape(self.samples, self.lines, self.rows)\n                whiteLev = 65535\n                self.whiteLevel = whiteLev\n                for i in range(nimages):\n                    # catch zero data:\n                    if np.min(tmpimage[i,:,:])==0:\n                        imt = tmpimage[i,:,:]\n                        imt[imt==0] = np.mean(imt) + 1 # in case mean < 1.0 (imt is uint16)\n                        logging.warning('zero data replaced in image %d',i)\n                    self.image[i,:,:] = np.log( whiteLev / tmpimage[i,:,:] )\n\n            elif self.imageFileFormat == \"float32\":\n                # assume float data already transformed by I0 and log\n                with open(imageFile, 'rb') as fl:\n                    try:\n                        self.image = np.fromfile(fl, dtype = self.imageFileFormat,\n                                 count = self.rows*self.lines*self.samples).reshape(self.samples, self.lines, self.rows)\n                    except:\n                        print(\"Failed in reading/converting image file: check data\")\n            else:\n                print(\"** error: image format name \",self.imageFileFormat,\" not recognised\")\n\n        else:\n            print(\"Image file not found!: \", imageFile)\n\n    def printImageStats(self, carInf):\n        \"\"\" print out some data for each frame in the set of images\"\"\"\n        max1 = int(self.voltage*2) # number of 0.5 KeV steps\n        min10 = int(max1/10)\n        for i in range(self.samples):\n            nancount = np.count_nonzero(np.isnan(self.image[i,:,:]))\n            if nancount>0:\n                print(\"*** img \", i, \" contains: \", nancount, \" NaNs (\", nancount*100./(self.rows*self.lines), \"%)\")\n                maskedimage = np.ma.array(self.image[i,:,:],mask = np.isnan(self.image[i,:,:]))\n                ave = np.ma.average(maskedimage)\n                print(\"    average(masked)= \", ave, \"  max= \", np.ma.max(maskedimage))\n            else:\n                ave = np.average(self.image[i,:,:])\n                print(\"img \", i, \" \", carInf.materialTypes[i],\" \", carInf.sampWidth[i], \" average= \",ave)\n            minmu = np.min(carInf.filterAtt[i].getMu()[min10:max1])\n            maxmu = np.max(carInf.filterAtt[i].getMu()[min10:max1])\n            maxatt = maxmu*carInf.sampWidth[i]\n            minatt = minmu*carInf.sampWidth[i]\n            print(\"    minatt = \",minatt,\"  maxatt = \",maxatt)\n            if ave<minatt or ave>maxatt:\n                print(\"    *** Warning: Attenuation of sample outside expected bounds!\")\n\n    def __setAverages(self):\n        \"\"\" pre compute mean centre of each image row\n        \"\"\"\n        self.__centre = np.zeros(self.samples*self.lines).reshape(self.samples,\n                                 self.lines)\n        for samp in range(self.samples):\n            for li in range(self.lines):\n                self.__centre[samp, li] = self.__getCentrePos(li, samp)\n\n    def __getCentrePos(self, line, sample):\n        \"\"\" do a weighted average of position by signal to find the centre of\n            the signal, in pixels\"\"\"\n        vals = self.image[sample,line,:]\n        meanpt = np.sum(np.arange(len(vals))*vals)/np.sum(vals)\n        if meanpt>0.75*np.size(vals) or meanpt<0.25*np.size(vals):\n            meanpt = np.size(vals)*0.5\n            logging.info('reset getCentrePos to %f for sample %d',meanpt,sample)\n        return meanpt\n\n    def getCentrePos(self, line, sample):\n        \"\"\" get centre point\"\"\"\n        return int(self.__centre[sample, line])\n\n    def getLines(self):\n        \"\"\" return the number of lines of the data\"\"\"\n        return self.lines\n\n    def getRows(self):\n        \"\"\" return the number of rows of the data\"\"\"\n        return self.rows\n\n    def getImage(self, imgNum):\n        \"\"\" access a given image by number\"\"\"\n        if imgNum >= 0 and imgNum <self.samples:\n            return self.image[imgNum,:,:]\n        else:\n            return 0\n\n    def getAvAtten(self, line, sample):\n        \"\"\" average over a named range of rows \"\"\"\n        if self.__cacheAveSet:\n            return self.__cacheAve[sample, line]\n        logging.debug('calc cache values of Ave')\n        self.__cacheAveSet =True\n        for s in range(self.samples):\n            for l in range(self.lines):\n                logging.debug('s= %d l=%d c=%f', s, l, self.__centre[s, l])\n                rowStart = int(self.__centre[s, l]-self.width)\n                rowEnd = int(rowStart+2*self.width)\n                self.__cacheAve[s, l] = np.average(self.image[s, l, rowStart:rowEnd])\n        return self.__cacheAve[sample, line]\n\n    def setWidthAve(self, width):\n        \"\"\" set the (half) width to be used when calculating the average\n            attenuation along a row\n            This is measured either size of the centre point. All points should\n            lie on the sample image.\n        \"\"\"\n        self.width = width\n        self.__cacheAveSet = False\n\n    def isValid(self):\n        \"\"\" is object ok\"\"\"\n        return self.valid\n\n    def plotCalData(self, showplt, markWidth):\n        \"\"\" plot calibration images in one window using matplotlib. Only\n            return when window closed. Mark image with width of \"averaging\",\n            markWidth \"\"\"\n        nsample = self.samples\n        if nsample<5:\n            pltgrid=2\n        elif nsample<10:\n            pltgrid=3\n        else:\n            pltgrid=4\n            nsample = min(nsample, 15)\n        for isam in range(nsample):\n            # deep copy image so can modify\n            z = np.copy(self.getImage(isam))\n            zzmax = 0\n            # mark width of each line used for average\n            for li in range(self.lines):\n                cen = self.getCentrePos(li, isam)\n                if markWidth>0:\n                    z[li, int(round(cen-markWidth))] = 0\n                    z[li, int(round(cen+markWidth))] = 0\n            maskedimage = np.ma.array(z, mask = np.isnan(z))\n            zmax = np.max(maskedimage)\n            zzmax = max(zmax, zzmax)\n            plt.subplot(pltgrid, pltgrid, isam+1, facecolor='y')\n            plt.imshow(maskedimage, cmap='RdBu', vmin = 0, vmax = zzmax,\n                       aspect='auto')\n            plt.draw()\n        if showplt:\n            plt.show()\n\n    def plotCalProf(self):\n        \"\"\" will be used to plot profile along a row; not yet complete\"\"\"\n        nsample = self.samples\n        if self.samples < 5:\n            pltgrid = 2\n        elif self.samples < 10:\n            pltgrid = 3\n        else:\n            pltgrid = 4\n            nsample = max(self.samples)\n        for isam in range(nsample):\n            plt.subplot(pltgrid, pltgrid, isam+1, facecolor = 'y')\n\n\n\nclass fitData(object):\n    \"\"\" This object contains fit related data and functions\n    \"\"\"\n\n    def __init__(self, carInfo, carCal, defMat):\n        if not ( carInfo.isValid and carCal.isValid ):\n            self.isValid = False\n            return\n        self.carInfo = carInfo\n        self.carCal = carCal\n        #\n        # set default fitting parameters; values are order of polynomials\n        # in line number. Hence \"0\" is a constant, not dependent on line number\n        # default is for 3rd polys for detector and target width, with global\n        # width for Cu filters. Also Gaussian for spectra, if no pre-defined values.\n        #\n        self.vary_target = 1\n        self.vary_detector = 1\n        self.vary_filter = 0\n        self.vary_energy = -1\n        self.vary_epk = -1\n        self.vary_ewidlow = -1\n        self.vary_ewidhigh = -1\n        # make space for default values to use if vary==-1\n        self.defaults = np.zeros(4)\n        #\n        # since there may be several filters, define which one should vary\n        self.vary_filter_name=\"Cu\"\n        self.verbose = False\n        # define the fitting parameters and their global/local status\n        self.varFilter = -1\n        # check if we have filter of material defMat\n        for i in carCal.filterMaterial:\n            if defMat == carCal.filterMaterial[i]:\n                self.varFilter = i\n                self.defFilterMat = defMat\n        # if defMat not found, use first material in list, if any\n        if self.varFilter==-1:\n            print(\"default filter: \", defMat,\" not found\")\n            if len(carCal.filterMaterial)>0:\n                self.defFilterMat=carCal.filterMaterial[0]\n                self.varFilter = 0\n                print(\"using material = \",self.defFilterMat,\" for fitting\")\n            else:\n                print(\"no filter material present, hence cannot fit this\")\n        self.atten = np.zeros([self.carCal.lines,self.carInfo.getSamples()])\n        self.objFnCalls = 0\n        self.nlines = 0\n        self.lineStep = 1\n        self.linestep = 1\n        self.bounds = False\n        self.boundsValues = {}\n        self.solver = \"old\"\n\n    def calcWidths(self,x0,nlines,xe):\n        \"\"\" Function to return the 3 widths for the target,\n            the detector and the filter from the set of fitting\n            variables. Each is assumed to be a polynomial of some\n            order in the line number. Global varables are zero\n            order polynomials.\n            Also returns the energy array which can be a polynomial:\n            E+aE**2+... ; this should be constrained >=0, not done at\n            present.\"\"\"\n        lines=np.array(range(nlines),dtype=\"double\")\n        nt = self.vary_target+1\n        nd = self.vary_detector+1\n        nf = self.vary_filter+1\n        ne = self.vary_energy+1\n        ns = self.vary_epk+self.vary_ewidlow+self.vary_ewidhigh+3\n        if len(x0)<nt+nd+nf+ne+ns:\n            print(\"** calcWidthd called with too few values in x0\")\n            sys.exit(1)\n        # Polynomial expressions: highest order term is first in the array.\n        if nt>0:\n            twidth = np.polyval(x0[:nt],lines)\n        else:\n            twidth = np.polyval(self.defaults[0:1],lines)\n        #twidth=np.polyval(x0[nt-1:0:-1],lines)\n        if nd>0:\n            dwidth = np.polyval(x0[nt:nt+nd],lines)\n        else:\n            dwidth = np.polyval(self.defaults[1:2],lines)\n        #dwidth=np.polyval(x0[nt+nd-1:nt:-1],lines)\n        dwidth = np.exp( dwidth ) # force >0 by working in log space\n        if nf>0:\n            fwidth = np.polyval(x0[nt+nd:nt+nd+nf],lines)\n        else:\n            fwidth = np.polyval(self.defaults[2:3],lines)\n        if ne>0:\n            # This term should be constrained as >=0 for all xe but is not at present.\n            # -Ve values will give errors in output stage.\n            ecoeffs = xe + xe*xe*(np.polyval(x0[nt+nd+nf:nt+nd+nf+ne],xe))\n        else:\n            ecoeffs = xe\n        if ns>0:\n            i0 = nt+nd+nf+ne\n            indarr = xe>x0[i0:i0+1]\n            spectra = xe-x0[i0:i0+1]\n            spectra[indarr] = spectra[indarr]*x0[i0+1:i0+2]\n            spectra[~indarr] = spectra[~indarr]*x0[i0+2:i0+3]\n            spectra = np.exp(-spectra**2)\n            # mask out lowest 10% of spectra, as in spekCalc\n            masklen = int(len(spectra)*0.1)\n            spectra[0:masklen] = 0.\n        else:\n            spectra = 0.\n        return twidth,dwidth,fwidth,ecoeffs,spectra\n\n    def dofit(self,nlines,lstep,xin):\n        \"\"\" perform fit \"\"\"\n        got=0\n        try:\n            # from scipy.optimize import minimize\n            from scipy.optimize import leastsq\n            got=1\n            from scipy.optimize import least_squares\n        except:\n            # if found old lib try and continue\n            if got==0:\n                print(\"** cannot find scipy leastsq or least_squares - check python has scipy\")\n                return\n\n        if self.verbose:\n            pdb.set_trace()\n        x = xin\n        self.nlines = nlines\n        self.lineStep = lstep\n\n        # use either old or new solver interface from scipy for least squares\n        if self.solver==\"old\":\n            res = leastsq(self.objFunSq, x, full_output = True)\n        else:\n            if self.bounds:\n                resobj = least_squares(self.objFunSq, x, verbose = 1, bounds=self.boundsValues)\n            else:\n                resobj = least_squares(self.objFunSq, x, verbose = 1, method='lm')\n            infodict = {\"nfev\":resobj.nfev}\n            cov = [0]\n            res = (resobj.x,cov,infodict,resobj.message,resobj.status)\n\n        print(\"Line 0 atten=\",self.atten[0,:])\n        expt = np.zeros(self.carCal.samples+1)\n        for i in range(self.carCal.samples):\n            expt[i] = self.carCal.getAvAtten(0,i)\n        print(\"Line 0 expt=\",expt)\n        # Do final calulation on all lines:\n        self.lineStep = 1\n        if self.solver==\"old\":\n            self.objFunSq(res[0])\n        else:\n            self.objFunSq(resobj.x)\n        #\n        return res\n\n    def objFunSq(self,x):\n        \"\"\" The function to minimize; returns the squared error for every point on each\n            selected line  \"\"\"\n        # Get the 3 widths: target(e.g. W), detector(e.g. CsI), global filter(e.g. Cu)\n        # target and detector widths depend on line number, filter is a global value\n        # for flexiblity all 3 are dimesioned by nlines\n        #\n        # mask out low en spectral points which may get undue weight if -ve filter widths occur\n        minpt = int(0.1*len(self.carCal.spec.getE()))\n        #\n        xe = self.carCal.spec.getE()\n        tw,dw,fw,ec,spectra = self.calcWidths(x,self.nlines,xe)\n        nsamples = self.carInfo.numSamples - 1 # ignore null sample\n        ans = np.zeros(nsamples*self.nlines)\n        tarAtt = self.carCal.targetAtten\n        if isinstance(spectra,np.ndarray):\n            se = spectra\n        else:\n            se = self.carCal.spec.getS()\n        #\n        for line in range(0,self.nlines,self.lineStep):\n            # compute filter attenuation and hence i0 as signal level with no sample for this line\n            attDet = dw[line]*self.carCal.detectorAtten.getMu()[:len(xe)]\n            attSum = np.zeros(len(xe))\n            for filt in range(self.carCal.filterCount):\n                if filt == self.varFilter:\n                    fwid = fw[line]\n                else:\n                    fwid = self.carCal.filterWidth[filt]\n                attSum = attSum + fwid*self.carCal.filterAtten[filt].getMu()[:len(xe)]\n            # this is the key integral done as a simple sum. Can ignore width of each value\n            # as constant energy steps, so cancels in I/I0\n            at_se = se*np.exp(-attSum-tarAtt.getMu()[:len(xe)]*tw[line])*ec*(1-np.exp(-attDet))\n            # drop low energy terms below 10%\n            at_se_t = at_se[minpt:]\n            # remove nan's - why are nan's present? exp overflow gives inf, multiply by 0 gives nan\n            # in most cases nans are OK to ignore.\n            at_se_finite = at_se_t[np.logical_not(np.isnan(at_se_t))]\n            i0 = np.sum(at_se_finite)\n            #\n            for sample in range(nsamples):\n                # skip masked samples\n                if self.carInfo.mask[sample]:\n                    continue\n                widSam = self.carInfo.sampWidth[sample]\n                #\n                attSam = widSam*self.carInfo.filterAtt[sample].getMu()[:len(xe)]\n                #\n                # drop low energy terms < 10%\n                at_se_sample = (at_se * np.exp(-attSam))[minpt:]\n                #\n                # remove nan's - see above\n                at_se_sample_finite = at_se_sample[np.logical_not(np.isnan(at_se_sample))]\n                i_sample = np.sum(at_se_sample_finite)\n                if i0==0. and self.verbose:\n                    print(\"warn: i0 zero at \",line)\n                    i0=1.\n                if i_sample == 0 and self.verbose:\n                    print(\"i_sample=0\")\n                if i_sample < 0. and self.verbose:\n                    print(\"i_sample<0\",at_se_sample[:8])\n                #sumSq = sumSq + ( (i_sample/i0) - self.carCal.getAvAtten(line,sample) ) ** 2\n                ans[line*nsamples+sample] = ( np.log(i0/i_sample) - self.carCal.getAvAtten(line,sample) ) ** 2\n                self.atten[line,sample] = np.log(i0/i_sample)\n        if self.verbose:\n            print(\"tw,dw,fw,sumSq: \",tw[0],dw[0],fw[0],np.sum(ans))\n            # for debugging we print the normalised detector response for the current parameters\n            plotFreq=10\n            if self.objFnCalls%plotFreq == 0:\n                plt.figure('NormRespone')\n                plt.xlabel('energy')\n                plt.ylabel('Normalised response')\n                # map nans to zero for plotting\n                at_se[np.isnan(at_se)] = 0.\n                plt.plot(xe,at_se/i0)\n                plt.draw()\n                plt.show(block=False)\n        self.objFnCalls=self.objFnCalls+1\n\n        #\n        # return vector of squared errors: length=samples*lines\n        return ans\n\n    def linesPolyFit(self,soln,corMat,corEn,npoints,attrange):\n        \"\"\" Function to calculate the attenuation over \"npoints\" for attenuation up to \"attrange\" for each line.\n            Uses the fitted parameters for attenuation in \"soln\". Having calculated apparent attenuation for the correction\n            material \"corMat\", map the observed attenuation to the true attenuation at the corEn energy. Then fit a\n            polynomial to the data and save the coefficients.\n            \"\"\"\n        # Get the 3 widths: target(e.g. W), detector(e.g. CsI), global filter(e.g. Cu)\n        # target and detector widths depend on line number, filter is a global value\n        # for flexiblity all 3 are dimesioned by nlines. Also the energy parameter, if fitted.\n        xe = self.carCal.spec.getE()\n        tw,dw,fw,ec,spectra = self.calcWidths(soln,self.nlines,xe)\n        #nsamples = self.carInfo.numSamples\n        # allocate space to store all calculated points and polynomials fitted to them\n        attout = np.zeros(shape=(self.nlines,npoints+1))\n        # set order of polynomial fits to use\n        # for xtek a 4th order polynomial can be used by the reconstruction - note\n        # that as constant term is forced to zero, 3 gives 4th order\n        odpoly = 8\n        xtekodpoly = 3\n        # determine if the solution varies with line number; if not only one fit required\n        vary_line = (self.vary_target>0 or self.vary_detector>0 or self.vary_filter>0)\n        #\n        # find the actual attenuation of the correction material at the correction energy\n        corrAtt = corMat.getMuByE(corEn)\n\n        tarAtt = self.carCal.targetAtten\n        #\n        if isinstance(spectra,np.ndarray):\n            se = spectra\n        else:\n            se = self.carCal.spec.getS()\n        #\n\n        # generate points to evaluate attenuation at.\n        mulist = np.arange(npoints+1,dtype='float')*attrange/(npoints*corrAtt)\n        # attin is the observed attenuation; for each line want to find corresponding attout\n        # the \"true\" attenuation at energy corEn\n        attin = mulist*corrAtt\n        #\n        # for each line generate npoints values of attenuation from fit data\n        #\n        if vary_line:\n            nlines = self.nlines\n        else:\n            nlines = 1\n        #\n        polyfit = np.zeros(shape=(nlines,odpoly+2))\n        xpolyfit = np.zeros(shape=(nlines,xtekodpoly+2))\n        #\n        for line in range(nlines):\n            # compute filter attenuation and hence i0 as signal level with no sample for this line\n            attDet = dw[line]*self.carCal.detectorAtten.getMu()[:len(xe)]\n            attSum = np.zeros(len(xe))\n            for filt in range(self.carCal.filterCount):\n                if filt == self.varFilter:\n                    fwid = fw[line]\n                else:\n                    fwid = self.carCal.filterWidth[filt]\n                attSum = attSum + fwid*self.carCal.filterAtten[filt].getMu()[:len(xe)]\n            # this is the key integral done as a simple sum. Can ignore width of each value\n            # as constant energy steps, so cancels in I/I0\n            at_se = se*np.exp(-attSum-tarAtt.getMu()[:len(xe)]*tw[line])*ec*(1-np.exp(-attDet))\n            # remove nan's - why are nan's present? exp overflow gives inf, multiply by 0 gives nan\n            # in most cases nans are OK to ignore.\n            at_se_finite = at_se[np.logical_not(np.isnan(at_se))]\n            i0 = np.sum(at_se_finite)\n            #\n            count = 0\n            # loop over required attenuation values\n            for muwid in mulist:\n                attSam = muwid*corMat.getMu()[:len(xe)]\n                at_se_sample = at_se * np.exp(-attSam)\n                #\n                # remove nan's - see above\n                #  should not be needed here if fit is OK\n                at_se_sample_finite = at_se_sample[np.logical_not(np.isnan(at_se_sample))]\n                i_sample = np.sum(at_se_sample_finite)\n                if i0==0. and self.verbose:\n                    print(\"warn: i0 zero at \",line)\n                    i0=1.\n                if i_sample == 0 and self.verbose:\n                    print(\"i_sample=0\")\n                if i_sample < 0. and self.verbose:\n                    print(\"i_sample<0\",at_se_sample[:8])\n                #sumSq = sumSq + ( (i_sample/i0) - self.carCal.getAvAtten(line,sample) ) ** 2\n                attout[line,count] = np.log(i0/i_sample)\n                count = count+1\n            #\n            try:\n                polyfit[line,0:odpoly+1] = np.polyfit(attout[line,1:],attin[1:]/attout[line,1:],odpoly)\n                xpolyfit[line,0:xtekodpoly+1] = np.polyfit(attout[line,1:],attin[1:]/attout[line,1:],xtekodpoly)\n            except:\n                print(\"*** Polynomial fit of result failed\")\n        #\n        # following carousel.pro, attout is the apparent attenuation or the x-axis of our correction\n        # graph. the y-axis should be the actual attenuation at monochromatic energy corEn for the\n        # correction material. Since the density of the correction material is unknown, which is the\n        # main point of this code, width and density are not used here. For fitting of a polynomial\n        # through (0,0) can divide y values by x values, ignoring origin (first point in this case).\n        #\n\n        return attout,attin,polyfit,xpolyfit\n", "meta": {"hexsha": "2363e9c9359d55a7aa1c52fb5c3aff7e757835c1", "size": 37975, "ext": "py", "lang": "Python", "max_stars_repo_path": "Wrappers/Python/ccpi/preprocessing/beamhardening/carouselUtils.py", "max_stars_repo_name": "TomasKulhanek/CCPi-PreProcessing", "max_stars_repo_head_hexsha": "f498cb2c9a454ae7fd74ee6ee6f8c9dfdfe51a7c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-22T16:23:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-22T16:23:29.000Z", "max_issues_repo_path": "Wrappers/Python/ccpi/preprocessing/beamhardening/carouselUtils.py", "max_issues_repo_name": "TomasKulhanek/CCPi-PreProcessing", "max_issues_repo_head_hexsha": "f498cb2c9a454ae7fd74ee6ee6f8c9dfdfe51a7c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-01-09T09:39:50.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-09T10:42:11.000Z", "max_forks_repo_path": "Wrappers/Python/ccpi/preprocessing/beamhardening/carouselUtils.py", "max_forks_repo_name": "TomasKulhanek/CCPi-PreProcessing", "max_forks_repo_head_hexsha": "f498cb2c9a454ae7fd74ee6ee6f8c9dfdfe51a7c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-01-11T09:10:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-02T22:11:56.000Z", "avg_line_length": 42.1944444444, "max_line_length": 123, "alphanum_fraction": 0.566714944, "include": true, "reason": "import numpy,from scipy", "num_tokens": 8733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.34158250614097546, "lm_q1q2_score": 0.17745939514606848}}
{"text": "\"\"\"\nUtilities for rock chemistry and mineral abundance classification.\n\nTodo\n-------\n\n* Petrological classifiers: QAPF (aphanitic/phaneritic),\n  gabbroic Pyroxene-Olivine-Plagioclase,\n  ultramafic Olivine-Orthopyroxene-Clinopyroxene\n\"\"\"\nimport os\nimport json\nfrom pathlib import Path\nimport numpy as np\nimport pandas as pd\nimport matplotlib.text\nimport matplotlib.pyplot as plt\nimport matplotlib.patches\nimport matplotlib.lines\nfrom .plot.style import patchkwargs\nfrom .plot.axes import init_axes\nfrom .plot.helpers import get_centroid\nfrom .meta import (\n    pyrolite_datafolder,\n    subkwargs,\n    sphinx_doi_link,\n    update_docstring_references,\n)\nfrom .log import Handle\n\nlogger = Handle(__name__)\n\n\nclass PolygonClassifier(object):\n    \"\"\"\n    A classifier model built form a series of polygons defining specific classes.\n\n    Parameters\n    -----------\n    name : :class:`str`\n        A name for the classifier model.\n    axes : :class:`list` | :class:`tuple`\n        Names of the axes corresponding to the polygon coordinates.\n    fields : :class:`dict`\n        Dictionary describing indiviudal polygons, with identifiers as keys and\n        dictionaries containing 'name' and 'fields' items.\n    scale : :class:`float`\n        Default maximum scale for the axes. Typically 100 (wt%) or 1 (fractional).\n    xlim : :class:`tuple`\n        Default x-limits for this classifier for plotting.\n    ylim : :class:`tuple`\n        Default y-limits for this classifier for plotting.\n    \"\"\"\n\n    def __init__(\n        self, name=None, axes=None, fields=None, scale=1.0, xlim=None, ylim=None,\n    ):\n        self.default_scale = scale\n        self._scale = self.default_scale\n        self.xlim = xlim\n        self.ylim = ylim\n\n        self.name = name\n        self.axes = axes or []\n        # check axes for ratios, adition/subtraction etc\n        self.fields = fields or []\n        self.classes = list(self.fields.keys())\n\n    def predict(self, X, data_scale=None):\n        \"\"\"\n        Predict the classification of samples using the polygon-based classifier.\n\n        Parameters\n        -----------\n        X : :class:`numpy.ndarray` | :class:`pandas.DataFrame`\n            Data to classify.\n        data_scale : :class:`float`\n            Maximum scale for the data. Typically 100 (wt%) or 1 (fractional).\n\n        Returns\n        -------\n        :class:`pandas.Series`\n            Series containing classifer predictions. If a dataframe was input,\n            it inherit the index.\n        \"\"\"\n        classes = [k for (k, cfg) in self.fields.items() if cfg[\"poly\"]]\n        polys = [\n            matplotlib.patches.Polygon(self.fields[k][\"poly\"], closed=True)\n            for k in classes\n        ]\n        if isinstance(X, pd.DataFrame):\n            # check whether the axes names are in the columns\n            axes = self.axis_components\n            idx = X.index\n            X = X.loc[:, axes].values\n        else:\n            idx = np.arange(X.shape[0])\n        out = pd.Series(index=idx, dtype=\"object\")\n\n        rescale_by = 1.0  # rescaling the data to fit the classifier scale\n        if data_scale is not None:\n            if not np.isclose(self.default_scale, data_scale):\n                rescale_by = self.default_scale / data_scale\n        X = X * rescale_by\n\n        indexes = np.array([p.contains_points(X) for p in polys]).T\n        notfound = np.logical_not(indexes.sum(axis=-1))\n\n        outlist = list(map(lambda ix: classes[ix], np.argmax(indexes, axis=-1)))\n        out.loc[:] = outlist\n        out.loc[(notfound)] = \"none\"\n        return out\n\n    @property\n    def axis_components(self):\n        \"\"\"\n        Get the axis components used by the classifier.\n\n        Returns\n        -------\n        :class:`tuple`\n            Names of the x and y axes for the classifier.\n        \"\"\"\n        return self.axes.get(\"x\"), self.axes.get(\"y\")\n\n    def _add_polygons_to_axes(\n        self, ax=None, fill=False, axes_scale=100.0, labels=None, **kwargs\n    ):\n        \"\"\"\n        Add the polygonal fields from the classifier to an axis.\n\n        Parameters\n        ----------\n        ax : :class:`matplotlib.axes.Axes`\n            Axis to add the polygons to.\n        fill : :class:`bool`\n            Whether to fill the polygons.\n        axes_scale : :class:`float`\n            Maximum scale for the axes. Typically 100 (for wt%) or 1 (fractional).\n        labels : :class:`str`\n            Which labels to add to the polygons (e.g. for TAS, 'volcanic', 'intrusive'\n            or the field 'ID').\n\n        Returns\n        --------\n        ax : :class:`matplotlib.axes.Axes`\n        \"\"\"\n        if ax is None:\n            ax = init_axes(**kwargs)\n\n        rescale_by = 1.0\n        if axes_scale is not None:  # rescale polygons to fit ax\n            if not np.isclose(self.default_scale, axes_scale):\n                rescale_by = axes_scale / self.default_scale\n        pgns = []\n        for k, cfg in self.fields.items():\n            if cfg[\"poly\"]:\n                if not fill:\n                    kwargs[\"facecolor\"] = \"none\"\n                verts = np.array(cfg[\"poly\"]) * rescale_by\n                pg = matplotlib.patches.Polygon(\n                    verts, closed=True, edgecolor=\"k\", **patchkwargs(kwargs)\n                )\n                pgns.append(pg)\n                ax.add_patch(pg)\n\n        # if the axis has the default scaling, there's a good chance that it hasn't\n        # been rescaled/rendered. We need to rescale to show the polygons.\n        if np.allclose(ax.get_xlim(), [0, 1]) & np.allclose(ax.get_ylim(), [0, 1]):\n            ax.set_xlim(np.array(self.xlim) * rescale_by)\n            ax.set_ylim(np.array(self.ylim) * rescale_by)\n\n        return ax\n\n    def add_to_axes(self, ax=None, fill=False, axes_scale=1, **kwargs):\n        \"\"\"\n        Add the polygonal fields from the classifier to an axis.\n\n        Parameters\n        ----------\n        ax : :class:`matplotlib.axes.Axes`\n            Axis to add the polygons to.\n        fill : :class:`bool`\n            Whether to fill the polygons.\n        axes_scale : :class:`float`\n            Maximum scale for the axes. Typically 100 (for wt%) or 1 (fractional).\n\n        Returns\n        --------\n        ax : :class:`matplotlib.axes.Axes`\n        \"\"\"\n        ax = self._add_polygons_to_axes(\n            ax=ax, fill=fill, axes_scale=axes_scale, **kwargs\n        )\n        if self.axes:  # may be none?\n            ax.set_ylabel(self.axes[0])\n            ax.set_xlabel(self.axes[1])\n        return ax\n\n\nclass TAS(PolygonClassifier):\n    \"\"\"\n    Total-alkali Silica Diagram classifier from Le Bas (1992) [#ref_1]_.\n\n    Parameters\n    -----------\n    name : :class:`str`\n        A name for the classifier model.\n    axes : :class:`list` | :class:`tuple`\n        Names of the axes corresponding to the polygon coordinates.\n    fields : :class:`dict`\n        Dictionary describing indiviudal polygons, with identifiers as keys and\n        dictionaries containing 'name' and 'fields' items.\n    scale : :class:`float`\n        Default maximum scale for the axes. Typically 100 (wt%) or 1 (fractional).\n    xlim : :class:`tuple`\n        Default x-limits for this classifier for plotting.\n    ylim : :class:`tuple`\n        Default y-limits for this classifier for plotting.\n\n    References\n    -----------\n    .. [#ref_1] Le Bas, M.J., Le Maitre, R.W., Woolley, A.R., 1992.\n                The construction of the Total Alkali-Silica chemical\n                classification of volcanic rocks.\n                Mineralogy and Petrology 46, 1–22.\n                doi: {LeBas1992}\n    \"\"\"\n\n    @update_docstring_references\n    def __init__(self, **kwargs):\n        src = pyrolite_datafolder(subfolder=\"models\") / \"TAS\" / \"config.json\"\n\n        with open(src, \"r\") as f:\n            config = json.load(f)\n        kw = dict(scale=100.0, xlim=[35, 85], ylim=[0, 20])\n        kw.update(kwargs)\n        poly_config = {**config, **kw}\n        super().__init__(**poly_config)\n\n    def add_to_axes(self, ax=None, fill=False, axes_scale=100.0, labels=None, **kwargs):\n        \"\"\"\n        Add the TAS fields from the classifier to an axis.\n\n        Parameters\n        ----------\n        ax : :class:`matplotlib.axes.Axes`\n            Axis to add the polygons to.\n        fill : :class:`bool`\n            Whether to fill the polygons.\n        axes_scale : :class:`float`\n            Maximum scale for the axes. Typically 100 (for wt%) or 1 (fractional).\n        labels : :class:`str`\n            Which labels to add to the polygons (e.g. for TAS, 'volcanic', 'intrusive'\n            or the field 'ID').\n\n        Returns\n        --------\n        ax : :class:`matplotlib.axes.Axes`\n        \"\"\"\n        # use and override the default add_to_axes\n        ax = self._add_polygons_to_axes(\n            ax=ax, fill=fill, axes_scale=axes_scale, **kwargs\n        )\n        rescale_by = 1.0\n        if axes_scale is not None:  # rescale polygons to fit ax\n            if not np.isclose(self.default_scale, axes_scale):\n                rescale_by = axes_scale / self.default_scale\n        if labels is not None:\n            for k, cfg in self.fields.items():\n                if cfg[\"poly\"]:\n                    verts = np.array(cfg[\"poly\"]) * rescale_by\n                    x, y = get_centroid(matplotlib.patches.Polygon(verts))\n                    if \"volc\" in labels:  # use the volcanic name\n                        label = cfg[\"name\"][0]\n                    elif \"intr\" in labels:  # use the intrusive name\n                        label = cfg[\"name\"][-1]\n                    else:  # use the field identifier\n                        label = k\n                    ax.annotate(\n                        \"\\n\".join(label.split()),\n                        xy=(x, y),\n                        ha=\"center\",\n                        va=\"center\",\n                        **subkwargs(kwargs, ax.annotate, matplotlib.text.Text)\n                    )\n\n        ax.set_ylabel(\"$Na_2O + K_2O$\")\n        ax.set_xlabel(\"$SiO_2$\")\n        return ax\n\n\nclass PeralkalinityClassifier(object):\n    def __init__(self):\n        self.fields = None\n\n    def predict(self, df: pd.DataFrame):\n        TotalAlkali = df.Na2O + df.K2O\n        perkalkaline_where = (df.Al2O3 < (TotalAlkali + df.CaO)) & (\n            TotalAlkali > df.Al2O3\n        )\n        metaluminous_where = (df.Al2O3 > (TotalAlkali + df.CaO)) & (\n            TotalAlkali < df.Al2O3\n        )\n        peraluminous_where = (df.Al2O3 < (TotalAlkali + df.CaO)) & (\n            TotalAlkali < df.Al2O3\n        )\n        out = pd.Series(index=df.index, dtype=\"object\")\n        out.loc[peraluminous_where] = \"Peraluminous\"\n        out.loc[metaluminous_where] = \"Metaluminous\"\n        out.loc[perkalkaline_where] = \"Peralkaline\"\n        return out\n\n\nTAS.__init__.__doc__ = TAS.__init__.__doc__.format(\n    LeBas1992=sphinx_doi_link(\"10.1007/BF01160698\")\n)\n", "meta": {"hexsha": "d69e43c81aae0aedbb36733fdddb4a13d93bbd87", "size": 10846, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyrolite/util/classification.py", "max_stars_repo_name": "bomtuckle/pyrolite", "max_stars_repo_head_hexsha": "c0af0ade14ff26b4e9fdd5a033b27e73df085c55", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 69, "max_stars_repo_stars_event_min_datetime": "2019-02-25T00:17:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:26:48.000Z", "max_issues_repo_path": "pyrolite/util/classification.py", "max_issues_repo_name": "bomtuckle/pyrolite", "max_issues_repo_head_hexsha": "c0af0ade14ff26b4e9fdd5a033b27e73df085c55", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 68, "max_issues_repo_issues_event_min_datetime": "2018-07-20T09:01:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:28:36.000Z", "max_forks_repo_path": "pyrolite/util/classification.py", "max_forks_repo_name": "bomtuckle/pyrolite", "max_forks_repo_head_hexsha": "c0af0ade14ff26b4e9fdd5a033b27e73df085c55", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2018-10-02T04:32:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-10T08:24:17.000Z", "avg_line_length": 34.106918239, "max_line_length": 88, "alphanum_fraction": 0.5704407155, "include": true, "reason": "import numpy", "num_tokens": 2590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.1774593916638945}}
{"text": "# -*- coding: utf-8 -*-\n# Copyright (C) 2017\n# Full license can be found in LICENSE.txt\n#---------------------------------------------------------------------------\n\"\"\" Perform OCB gridding for SuperDARN vorticity data\n\nFunctions\n----------------------------------------------------------------------------\nvort2ascii_ocb(vortfile, outfile, kwargs)\n    Write and ASCII file with SuperDARN data and the OCB coordinates for each\n    data point\nload_vorticity_ascii_data(filename, save_all=False)\n    Load vorticity block ASCII data files\n\nData\n----------------------------------------------------------------------------\nSpecialised SuperDARN data product, available from: gchi@bas.ac.uk\n\"\"\"\nimport logbook as logging\nimport numpy as np\n\ndef vort2ascii_ocb(vortfile, outfile, ocb=None, ocbfile=None, max_sdiff=600,\n                   save_all=False, min_sectors=7, rcent_dev=8.0, max_r=23.0,\n                   min_r=10.0, min_j=0.15):\n    \"\"\" Coverts the location of vorticity data in AACGM coordinates into a frame\n    that is relative to the open-closed field-line boundary (OCB) as determined\n    from a circle fit to the poleward boundary of the auroral oval\n\n    Parameters\n    ----------\n    vortfile : (str)\n        file containing the required vorticity file sorted by time\n    outfile : (str)\n        filename for the output data\n    ocb : (ocbpy.ocboundary.OCBoundary or NoneType)\n        Object containing open closed boundary data or None to load from file\n    ocbfile : (str or NoneType)\n        file containing the required OC boundary data sorted by time, or None\n        to use ocb object or IMAGE WIC file (default=None)\n    max_sdiff : (int)\n        maximum seconds between OCB and data record in sec (default=600)\n    save_all : (bool)\n        Save all data (True), or only that needed to calcuate OCB and vorticity\n        (False). (default=False)\n    min_sectors : (int)\n        Minimum number of MLT sectors required for good OCB. (default=7)\n    rcent_dev : (float)\n        Maximum number of degrees between the new centre and the AACGM pole\n        (default=8.0).\n    max_r : (float)\n        Maximum radius for open-closed field line boundary in degrees.\n        (default=23.0)\n    min_r : (float)\n        Minimum radius for open-closed field line boundary in degrees\n        (default=10.0)\n    min_j : (float)\n        Minimum unitless current magnitude scale difference (default=0.15)\n\n    Returns\n    ---------\n    Void\n\n    Notes\n    --------\n    Input header or col_names must include the names in the default string.\n    \"\"\"\n    import ocbpy\n    import ocbpy.ocb_scaling as ocbscal\n    import datetime as dt\n\n    assert ocbpy.instruments.test_file(vortfile), \\\n        logging.error(\"vorticity file cannot be opened[{:s}]\".format(vortfile))\n    assert isinstance(outfile, str), \\\n        logging.error(\"output filename is not a string [{:}]\".format(outfile))\n\n    # Read the vorticity data\n    vdata = load_vorticity_ascii_data(vortfile, save_all=save_all)\n    need_keys = [\"VORTICITY\", \"CENTRE_MLAT\", \"DATETIME\", \"MLT\"]\n    \n    if vdata is None or not all([kk in vdata.keys() for kk in need_keys]):\n        estr = \"unable to load necessary data from [{:s}]\".format(vortfile)\n        logging.error(estr)\n        return\n\n    # Load the OCB data\n    if ocb is None or not isinstance(ocb, ocbpy.ocboundary.OCBoundary):\n        vstart = vdata['DATETIME'][0] - dt.timedelta(seconds=max_sdiff+1)\n        vend = vdata['DATETIME'][-1] + dt.timedelta(seconds=max_sdiff+1)\n        ocb = ocbpy.ocboundary.OCBoundary(ocbfile, stime=vstart, etime=vend)\n\n    if ocb.filename is None or ocb.records == 0:\n        try:\n            logging.error(\"no data in OCB file {:s} \".format(ocb.filename))\n        except:\n            logging.error(\"bad OCB file specified\")\n        return\n\n    # Set the reference radius\n    ref_r = 90.0 - abs(ocb.boundary_lat)\n\n    # Open and test the file to ensure it can be written\n    try:\n        fout = open(outfile, 'w')\n    except:\n        logging.error(\"unable to create output file [{:}]\".format(outfile))\n        return\n\n    # Write header line\n    outline = \"#DATE TIME \"\n\n    if save_all:\n        vkeys = vdata.keys()\n        vkeys.pop(vkeys.index(\"DATETIME\"))\n        outline = \"{:s}{:s} \".format(outline, \" \".join(vkeys))\n\n    outline = \"{:s}OCB_LAT OCB_MLT NORM_VORT\\n\".format(outline)\n    \n    try:\n        fout.write(outline)\n    except:\n        estr = \"unable to write [{:s}] because of error \".format(outline)\n        estr = \"{:s}[{:}]\".format(estr, e)\n        logging.error(estr)\n        return\n\n    # Initialise the ocb and vorticity indices\n    ivort = 0\n    num_vort = vdata['DATETIME'].shape[0]\n\n    # Cycle through the data, matching vorticity and OCB records\n    while ivort < num_vort and ocb.rec_ind < ocb.records:\n        ivort = ocbpy.match_data_ocb(ocb, vdata['DATETIME'], idat=ivort,\n                                     max_tol=max_sdiff, min_sectors=min_sectors,\n                                     rcent_dev=rcent_dev, max_r=max_r,\n                                     min_r=min_r, min_j=min_j)\n        \n        if ivort < num_vort and ocb.rec_ind < ocb.records:\n            # Use the indexed OCB to convert the AACGM grid coordinate to one\n            # related to the OCB\n            nlat, nmlt = ocb.normal_coord(vdata['CENTRE_MLAT'][ivort],\n                                          vdata['MLT'][ivort])\n            nvort = ocbscal.normal_curl_evar(vdata['VORTICITY'][ivort],\n                                             ocb.r[ocb.rec_ind], ref_r)\n\n            # Format the output line\n            #    DATE TIME (SAVE_ALL) OCB_LAT OCB_MLT NORM_VORT\n            outline = \"{:} \".format(vdata['DATETIME'][ivort])\n\n            if save_all:\n                for k in vkeys:\n                    outline = \"{:s}{:} \".format(outline, vdata[k][ivort])\n\n            outline = \"{:s}{:.2f} {:.6f} {:.6f}\\n\".format(outline, nlat, nmlt,\n                                                          nvort)\n            \n            try:\n                fout.write(outline)\n            except e:\n                estr = \"unable to write [{:s}] \".format(outline)\n                estr = \"{:s}because of error [{:}]\".format(estr, e)\n                logging.error(estr)\n                return\n\n            # Move to next line\n            ivort += 1\n\n    # Close output file\n    fout.close()\n        \n    return\n\ndef load_vorticity_ascii_data(vortfile, save_all=False):\n    \"\"\"Load SuperDARN vorticity data files.\n\n    Parameters\n    -----------\n    vortfile : (str)\n        SuperDARN vorticity file in block format\n    save_all : (bool)\n        Save all data from the file (True), or only data needed to calculate\n        the OCB coordinates and normalised vorticity (False). (default=False)\n\n    Returns\n    ---------\n    vdata : (dict)\n        Dictionary of numpy arrays\n    \"\"\"\n    from ocbpy.instruments import test_file\n    import datetime as dt\n\n    if not test_file(vortfile):\n        return None\n\n    # Open the data file\n    try:\n        fvort = open(vortfile, \"r\")\n    except:\n        logging.error(\"unable to open vorticity file [{:s}]\".format(vortfile))\n        return None\n\n    # Initialise the output dictionary\n    vkeys = [\"YEAR\", \"MONTH\", \"DAY\", \"UTH\", \"VORTICITY\", \"MLT\", \"CENTRE_MLAT\",\n             \"DATETIME\"]\n    if save_all:\n        vkeys.extend([\"R1BM1\", \"R1BM2\", \"R2BM1\", \"R2BM2\", \"AREA\", \"CENTRE_GLAT\",\n                      \"CENTRE_GLON\", \"C1_GLAT\", \"C1_GLON\", \"C2_GLAT\", \"C2_GLON\",\n                      \"C3_GLAT\", \"C3_GLON\", \"C4_GLAT\", \"C4_GLON\", \"CENTRE_MLON\",\n                      \"C1_MLAT\", \"C1_MLON\", \"C2_MLAT\", \"C2_MLON\", \"C3_MLAT\",\n                      \"C3_MLON\", \"C4_MLAT\", \"C4_MLON\"])\n    vdata = {k:list() for k in vkeys}\n    vkeys = set(vkeys)\n    \n    # Set the data block keys\n    bkeys = [[\"R1BM1\", \"R1BM2\", \"R2BM1\", \"R2BM2\", \"AREA\", \"VORTICITY\", \"MLT\"],\n             [\"GFLG\", \"CENTRE_GLAT\", \"CENTRE_GLON\", \"C1_GLAT\", \"C1_GLON\",\n              \"C2_GLAT\", \"C2_GLON\", \"C3_GLAT\", \"C3_GLON\", \"C4_GLAT\", \"C4_GLON\"],\n             [\"MFLG\", \"CENTRE_MLAT\", \"CENTRE_MLON\", \"C1_MLAT\", \"C1_MLON\",\n              \"C2_MLAT\", \"C2_MLON\", \"C3_MLAT\", \"C3_MLON\", \"C4_MLAT\", \"C4_MLON\"]]\n    \n    # Read the lines and assign data.  Recall that blank lines in file are\n    # returned as '\\n'\n    vline = fvort.readline()\n    vsplit = vline.split()\n    vinc = 0\n\n    while len(vline) > 0:\n        if vinc == 0:\n            # This is a date line\n            if len(vsplit) != 4:\n                estr = \"unexpected line encountered when date line \"\n                estr = \"{:s}expected [{:s}]\".format(estr, vline)\n                logging.error(estr)\n                fvort.close()\n                return None\n\n            # Save the data in the format desired for the output dict\n            yy = int(vsplit[0])\n            mm = int(vsplit[1])\n            dd = int(vsplit[2])\n            hh = float(vsplit.pop())\n\n            # Calculate and save the datetime\n            stime = \" \".join(vsplit)\n            dtime = (dt.datetime.strptime(stime, \"%Y %m %d\") +\n                     dt.timedelta(seconds=np.floor(hh * 3600.0)))\n            vinc += 1\n        elif vinc == 1:\n            # This is a number of entries line\n            if len(vsplit) != 1:\n                estr = \"unexpected line encountered when number of entries \"\n                estr = \"{:s}line expected [{:s}]\".format(estr, vline)\n                logging.error(estr)\n                fvort.close()\n                return None\n\n            # Save the number of entries\n            nentries = int(vsplit[0])\n            vinc += 1\n        else:\n            # This is an entry.  For each entry there are three lines\n            ninc = 0\n            while ninc < nentries:\n                # Save the time data\n                vdata['YEAR'].append(yy)\n                vdata['MONTH'].append(mm)\n                vdata['DAY'].append(dd)\n                vdata['UTH'].append(hh)\n                vdata['DATETIME'].append(dtime)\n\n                for bklist in bkeys:\n                    # Test to see that this line has the right number of col\n                    if len(vsplit) != len(bklist):\n                        estr = \"unexpected line encountered for a data block \"\n                        estr = \"{:s}[{:s}]\".format(estr, vline)\n                        logging.error(estr)\n                        fvort.close()\n                        return None\n\n                    # Save all desired keys\n                    gkeys = list(vkeys.intersection(bklist))\n\n                    for gk in gkeys:\n                        ik = bklist.index(gk)\n                        vdata[gk].append(float(vsplit[ik]))\n\n                    # Move to next line\n                    vline = fvort.readline()\n                    vsplit = vline.split()\n                    \n                # All data lines for this entry have been processed, incriment\n                ninc += 1\n                    \n            # All entries in block have been processed, reset incriment\n            vinc = 0\n\n        # Move to next line\n        vline = fvort.readline()\n        vsplit = vline.split()\n\n    # Close file handle\n    fvort.close()\n\n    # Recast lists as numpy arrays\n    for k in vdata.keys():\n        vdata[k] = np.array(vdata[k])\n\n    return vdata\n", "meta": {"hexsha": "0257588bb96b18195c694181e2dc2086eda5e076", "size": 11253, "ext": "py", "lang": "Python", "max_stars_repo_path": "ocbpy/instruments/vort.py", "max_stars_repo_name": "jpreistad/ocbpy", "max_stars_repo_head_hexsha": "9f6f28902885aee0c9bedc0319d53736b7acbc8f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ocbpy/instruments/vort.py", "max_issues_repo_name": "jpreistad/ocbpy", "max_issues_repo_head_hexsha": "9f6f28902885aee0c9bedc0319d53736b7acbc8f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ocbpy/instruments/vort.py", "max_forks_repo_name": "jpreistad/ocbpy", "max_forks_repo_head_hexsha": "9f6f28902885aee0c9bedc0319d53736b7acbc8f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5357142857, "max_line_length": 80, "alphanum_fraction": 0.5435883764, "include": true, "reason": "import numpy", "num_tokens": 2900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.1774593916638945}}
{"text": "\"\"\"Position reconstruction for Xenon-nT\"\"\"\r\n\r\nimport os\r\nimport tempfile\r\nimport tarfile\r\nimport numpy as np\r\nimport strax\r\nimport straxen\r\nfrom warnings import warn\r\nexport, __all__ = strax.exporter()\r\n\r\nDEFAULT_POSREC_ALGO_OPTION = tuple([strax.Option(\"default_reconstruction_algorithm\",\r\n                 help=\"default reconstruction algorithm that provides (x,y)\",\r\n                 default=\"mlp\", infer_type=False,\r\n                 )])\r\n\r\n\r\n@export\r\n@strax.takes_config(\r\n    strax.Option('min_reconstruction_area',\r\n                 help='Skip reconstruction if area (PE) is less than this',\r\n                 default=10, infer_type=False,),\r\n    strax.Option('n_top_pmts', default=straxen.n_top_pmts, infer_type=False,\r\n                 help=\"Number of top PMTs\")\r\n)\r\nclass PeakPositionsBaseNT(strax.Plugin):\r\n    \"\"\"\r\n    Base class for reconstructions.\r\n    This class should only be used when subclassed for the different\r\n    algorithms. Provides x_algorithm, y_algorithm for all peaks > than\r\n    min-reconstruction area based on the top array.\r\n    \"\"\"\r\n    depends_on = ('peaks',)\r\n    algorithm = None\r\n    compressor = 'zstd'\r\n    # Using parallel = 'process' is not allowed as we cannot Pickle\r\n    # self.model during multiprocessing (to fix?)\r\n    parallel = True\r\n    __version__ = '0.0.0'\r\n\r\n    def infer_dtype(self):\r\n        if self.algorithm is None:\r\n            raise NotImplementedError(f'Base class should not be used without '\r\n                                      f'algorithm as done in {__class__.__name__}')\r\n        dtype = [('x_' + self.algorithm, np.float32,\r\n                  f'Reconstructed {self.algorithm} S2 X position (cm), uncorrected'),\r\n                 ('y_' + self.algorithm, np.float32,\r\n                  f'Reconstructed {self.algorithm} S2 Y position (cm), uncorrected')]\r\n        dtype += strax.time_fields\r\n        return dtype\r\n\r\n    def setup(self):\r\n        self.model_file = self._get_model_file_name()\r\n        if self.model_file is None:\r\n            warn(f'No file provided for {self.algorithm}. Setting all values '\r\n                 f'for {self.provides} to None.')\r\n            # No further setup required\r\n            return\r\n\r\n        # Load the tensorflow model\r\n        import tensorflow as tf\r\n        if os.path.exists(self.model_file):\r\n            print(f\"Path is local. Loading {self.algorithm} TF model locally \"\r\n                  f\"from disk.\")\r\n        else:\r\n            downloader = straxen.MongoDownloader()\r\n            try:\r\n                self.model_file = downloader.download_single(self.model_file)\r\n            except straxen.mongo_storage.CouldNotLoadError as e:\r\n                raise RuntimeError(f'Model files {self.model_file} is not found') from e\r\n        with tempfile.TemporaryDirectory() as tmpdirname:\r\n            tar = tarfile.open(self.model_file, mode=\"r:gz\")\r\n            tar.extractall(path=tmpdirname)\r\n            self.model = tf.keras.models.load_model(tmpdirname)\r\n\r\n    def compute(self, peaks):\r\n        result = np.ones(len(peaks), dtype=self.dtype)\r\n        result['time'], result['endtime'] = peaks['time'], strax.endtime(peaks)\r\n\r\n        result['x_' + self.algorithm] *= float('nan')\r\n        result['y_' + self.algorithm] *= float('nan')\r\n\r\n        if self.model_file is None:\r\n            # This plugin is disabled since no model is provided\r\n            return result\r\n\r\n        # Keep large peaks only\r\n        peak_mask = peaks['area'] > self.config['min_reconstruction_area']\r\n        if not np.sum(peak_mask):\r\n            # Nothing to do, and .predict crashes on empty arrays\r\n            return result\r\n\r\n        # Getting actual position reconstruction\r\n        _in = peaks['area_per_channel'][peak_mask, 0:self.config['n_top_pmts']]\r\n        with np.errstate(divide='ignore', invalid='ignore'):\r\n            _in = _in / np.max(_in, axis=1).reshape(-1, 1)\r\n        _in = _in.reshape(-1, self.config['n_top_pmts'])\r\n        _out = self.model.predict(_in)\r\n\r\n        # writing output to the result\r\n        result['x_' + self.algorithm][peak_mask] = _out[:, 0]\r\n        result['y_' + self.algorithm][peak_mask] = _out[:, 1]\r\n        return result\r\n\r\n    def _get_model_file_name(self):\r\n\r\n        config_file = f'{self.algorithm}_model'\r\n        model_from_config = self.config.get(config_file, 'No file')\r\n        if model_from_config == 'No file':\r\n            raise ValueError(f'{__class__.__name__} should have {config_file} '\r\n                             f'provided as an option.')\r\n        if isinstance(model_from_config, str) and os.path.exists(model_from_config):\r\n            # Allow direct path specification\r\n            return model_from_config\r\n        if model_from_config is None:\r\n            # Allow None to be specified (disables processing for given posrec)\r\n            return model_from_config\r\n\r\n        # Use CMT\r\n        model_file = straxen.get_correction_from_cmt(self.run_id, model_from_config)\r\n        return model_file\r\n\r\n\r\n@export\r\n@strax.takes_config(\r\n    strax.Option('mlp_model',\r\n                 help='Neural network model.' \r\n                      'If CMT, specify as (mlp_model, ONLINE, True)'\r\n                      'Set to None to skip the computation of this plugin.',\r\n                 default=('mlp_model', \"ONLINE\", True), infer_type=False,\r\n                )\r\n)\r\nclass PeakPositionsMLP(PeakPositionsBaseNT):\r\n    \"\"\"Multilayer Perceptron (MLP) neural net for position reconstruction\"\"\"\r\n    provides = \"peak_positions_mlp\"\r\n    algorithm = \"mlp\"\r\n\r\n\r\n@export\r\n@strax.takes_config(\r\n    strax.Option('gcn_model',\r\n                 help='Neural network model.' \r\n                      'If CMT, specify as  (gcn_model, ONLINE, True)'\r\n                      'Set to None to skip the computation of this plugin.',\r\n                 default=('gcn_model', \"ONLINE\", True), infer_type=False,\r\n                )\r\n)\r\nclass PeakPositionsGCN(PeakPositionsBaseNT):\r\n    \"\"\"Graph Convolutional Network (GCN) neural net for position reconstruction\"\"\"\r\n    provides = \"peak_positions_gcn\"\r\n    algorithm = \"gcn\"\r\n    __version__ = '0.0.1'\r\n\r\n\r\n@export\r\n@strax.takes_config(\r\n    strax.Option('cnn_model',\r\n                 help='Neural network model.' \r\n                      'If CMT, specify as (cnn_model, ONLINE, True)'\r\n                      'Set to None to skip the computation of this plugin.',\r\n                 default=('cnn_model', \"ONLINE\", True), infer_type=False,\r\n                )\r\n)\r\nclass PeakPositionsCNN(PeakPositionsBaseNT):\r\n    \"\"\"Convolutional Neural Network (CNN) neural net for position reconstruction\"\"\"\r\n    provides = \"peak_positions_cnn\"\r\n    algorithm = \"cnn\"\r\n    __version__ = '0.0.1'\r\n\r\n\r\n@export\r\n@strax.takes_config(\r\n    *DEFAULT_POSREC_ALGO_OPTION\r\n)\r\nclass PeakPositionsNT(strax.MergeOnlyPlugin):\r\n    \"\"\"\r\n    Merge the reconstructed algorithms of the different algorithms \r\n    into a single one that can be used in Event Basics.\r\n    \r\n    Select one of the plugins to provide the 'x' and 'y' to be used \r\n    further down the chain. Since we already have the information\r\n    needed here, there is no need to wait until events to make the\r\n    decision.\r\n    \r\n    Since the computation is trivial as it only combined the three \r\n    input plugins, don't save this plugins output.\r\n    \"\"\"\r\n    provides = \"peak_positions\"\r\n    depends_on = (\"peak_positions_cnn\", \"peak_positions_mlp\", \"peak_positions_gcn\")\r\n    save_when = strax.SaveWhen.NEVER\r\n    __version__ = '0.0.0'\r\n\r\n    def infer_dtype(self):\r\n        dtype = strax.merged_dtype([self.deps[d].dtype_for(d) for d in self.depends_on])\r\n        dtype += [('x', np.float32, 'Reconstructed S2 X position (cm), uncorrected'),\r\n                  ('y', np.float32, 'Reconstructed S2 Y position (cm), uncorrected')]\r\n        return dtype\r\n\r\n    def compute(self, peaks):\r\n        result = {dtype: peaks[dtype] for dtype in peaks.dtype.names}\r\n        algorithm = self.config['default_reconstruction_algorithm']\r\n        if not 'x_' + algorithm in peaks.dtype.names:\r\n            raise ValueError\r\n        for xy in ('x', 'y'):\r\n            result[xy] = peaks[f'{xy}_{algorithm}']\r\n        return result\r\n\r\n    \r\n@export\r\n@strax.takes_config(\r\n    strax.Option('recon_alg_included', help = 'The list of all reconstruction algorithm considered.',\r\n                 default = ('_mlp', '_gcn', '_cnn'), infer_type=False,\r\n                )\r\n)\r\nclass S2ReconPosDiff(strax.Plugin):\r\n    '''\r\n    Plugin that provides position reconstruction difference for S2s in events, see note: \r\n    https://xe1t-wiki.lngs.infn.it/doku.php?id=xenon:shengchao:sr0:reconstruction_quality\r\n    '''\r\n    \r\n    __version__ = '0.0.3'\r\n    parallel = True\r\n    depends_on = 'event_basics'\r\n    provides = 's2_recon_pos_diff'\r\n    save_when = strax.SaveWhen.EXPLICIT\r\n    \r\n    def infer_dtype(self):\r\n        dtype = [\r\n        ('s2_recon_avg_x', np.float32,\r\n         'Mean value of x for main S2'),\r\n        ('alt_s2_recon_avg_x', np.float32,\r\n         'Mean value of x for alternatice S2'),\r\n        ('s2_recon_avg_y', np.float32,\r\n         'Mean value of y for main S2'),\r\n        ('alt_s2_recon_avg_y', np.float32,\r\n         'Mean value of y for alternatice S2'),\r\n        ('s2_recon_pos_diff', np.float32,\r\n         'Reconstructed position difference for main S2'),\r\n        ('alt_s2_recon_pos_diff', np.float32,\r\n         'Reconstructed position difference for alternative S2'),\r\n    ]\r\n        dtype += strax.time_fields\r\n        return dtype\r\n\r\n    def compute(self, events):\r\n        \r\n        result = np.zeros(len(events), dtype = self.dtype)\r\n        result['time'] = events['time']\r\n        result['endtime'] = strax.endtime(events)\r\n        # Computing position difference\r\n        self.compute_pos_diff(events, result)\r\n        return result  \r\n\r\n    def cal_avg_and_std(self, values, axis = 1):\r\n        average = np.mean(values, axis = axis)\r\n        std = np.std(values, axis = axis)\r\n        return average, std\r\n\r\n    def eval_recon(self, data, name_x_list, name_y_list):\r\n        \"\"\"\r\n        This function reads the name list based on s2/alt_s2 and all recon algorithm registered\r\n        Each row consists the reconstructed x/y and their average and standard deviation is calculated\r\n        \"\"\"\r\n        x_avg, x_std = self.cal_avg_and_std(np.array(data[name_x_list].tolist())) #lazy fix to delete field name in array, otherwise np.mean will complain\r\n        y_avg, y_std = self.cal_avg_and_std(np.array(data[name_y_list].tolist()))\r\n        r_std = np.sqrt(x_std**2 + y_std**2)\r\n        res = x_avg, y_avg, r_std\r\n        return res\r\n\r\n    def compute_pos_diff(self, events, result):\r\n        \r\n        alg_list = self.config['recon_alg_included']\r\n        for peak_type in ['s2', 'alt_s2']:\r\n            # Selecting S2s for pos diff\r\n            # - must exist (index != -1)\r\n            # - must have positive AFT\r\n            # - must contain all alg info\r\n            cur_s2_bool = (events[peak_type + '_index'] !=- 1)\r\n            cur_s2_bool &= (events[peak_type + '_area_fraction_top'] > 0)\r\n            for name in self.config['recon_alg_included']:\r\n                cur_s2_bool &= ~np.isnan(events[peak_type+'_x'+name])\r\n                cur_s2_bool &= ~np.isnan(events[peak_type+'_y'+name])\r\n            \r\n            # default value is nan, it will be ovewrite if the event satisfy the requirments\r\n            result[peak_type + '_recon_pos_diff'][:] = np.nan\r\n            result[peak_type + '_recon_avg_x'][:] = np.nan\r\n            result[peak_type + '_recon_avg_y'][:] = np.nan\r\n            \r\n            if np.any(cur_s2_bool):\r\n                name_x_list = []\r\n                name_y_list = []\r\n                for alg in alg_list:\r\n                    name_x_list.append(peak_type + '_x' + alg)\r\n                    name_y_list.append(peak_type + '_y' + alg)\r\n\r\n                # Calculating average x,y, and position difference\r\n                x_avg, y_avg, r_std = self.eval_recon(events[cur_s2_bool], name_x_list, name_y_list)\r\n                result[peak_type + '_recon_pos_diff'][cur_s2_bool] = r_std\r\n                result[peak_type + '_recon_avg_x'][cur_s2_bool] = x_avg\r\n                result[peak_type + '_recon_avg_y'][cur_s2_bool] = y_avg\r\n", "meta": {"hexsha": "2cfcf0ca3d6f0b70a5386b739fadffcf2e9e450a", "size": 12220, "ext": "py", "lang": "Python", "max_stars_repo_path": "straxen/plugins/position_reconstruction.py", "max_stars_repo_name": "zhut19/straxen", "max_stars_repo_head_hexsha": "20dea986790ef168ba7052d652a7aa19ab836943", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "straxen/plugins/position_reconstruction.py", "max_issues_repo_name": "zhut19/straxen", "max_issues_repo_head_hexsha": "20dea986790ef168ba7052d652a7aa19ab836943", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-10-08T22:52:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-12T07:48:48.000Z", "max_forks_repo_path": "straxen/plugins/position_reconstruction.py", "max_forks_repo_name": "ahiguera-mx/straxen", "max_forks_repo_head_hexsha": "25b92dd4f18b51700e6df83b230e58ec3bbb7163", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5980066445, "max_line_length": 155, "alphanum_fraction": 0.6018821604, "include": true, "reason": "import numpy", "num_tokens": 2839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.32423538592116935, "lm_q1q2_score": 0.1772718557065582}}
{"text": "\n# Generate angular tensors using symbolic expressions for the GTO's and derivatives\n\n# There are two steps to the code generation, and only the second is automated.\n#  1. Use read_order.py to generate:\n#      A. A python version of get_ijk, which is pasted into this file.\n#      B. A C++ version of get_ABC, which is pasted into CartesianTensor.h.in\n#      C. Repeat B for a version of get_ABC to be pasted into SoaCartesianTensor.h.in\n#  2. Run create_cartesian_tensor.py\n#      A. Copy CartesianTensor.h up on directory (to src/Numerics)\n#      B. Copy SoaCartesianTensor.h up to src/QMCWaveFunctions/LCAO)\n#      C. Apply clang-format on modified source files.\n\n\nfrom collections import namedtuple, defaultdict\nfrom sympy import *\n\n# See the GaussianOrbitals notebook in the qmc_algorithms repo for more explanation,\n#  especially about the normalization.\n\ndef create_gto_symbolic():\n    pre = sympify('x**i * y**j * z**k * exp(-alpha *r**2)')\n    return pre\n\n# this function generated from 'read_order.py', should match GAMESS order\ndef get_ijk():\n  ijk = []\n  # S\n  ijk.append( (0,0,0,\"S\") )\n  # P\n  ijk.append( (1,0,0,\"X\") )\n  ijk.append( (0,1,0,\"Y\") )\n  ijk.append( (0,0,1,\"Z\") )\n  # D\n  ijk.append( (2,0,0,\"XX\") )\n  ijk.append( (0,2,0,\"YY\") )\n  ijk.append( (0,0,2,\"ZZ\") )\n  ijk.append( (1,1,0,\"XY\") )\n  ijk.append( (1,0,1,\"XZ\") )\n  ijk.append( (0,1,1,\"YZ\") )\n  # F\n  ijk.append( (3,0,0,\"XXX\") )\n  ijk.append( (0,3,0,\"YYY\") )\n  ijk.append( (0,0,3,\"ZZZ\") )\n  ijk.append( (2,1,0,\"XXY\") )\n  ijk.append( (2,0,1,\"XXZ\") )\n  ijk.append( (1,2,0,\"YYX\") )\n  ijk.append( (0,2,1,\"YYZ\") )\n  ijk.append( (1,0,2,\"ZZX\") )\n  ijk.append( (0,1,2,\"ZZY\") )\n  ijk.append( (1,1,1,\"XYZ\") )\n  # G\n  ijk.append( (4,0,0,\"XXXX\") )\n  ijk.append( (0,4,0,\"YYYY\") )\n  ijk.append( (0,0,4,\"ZZZZ\") )\n  ijk.append( (3,1,0,\"XXXY\") )\n  ijk.append( (3,0,1,\"XXXZ\") )\n  ijk.append( (1,3,0,\"YYYX\") )\n  ijk.append( (0,3,1,\"YYYZ\") )\n  ijk.append( (1,0,3,\"ZZZX\") )\n  ijk.append( (0,1,3,\"ZZZY\") )\n  ijk.append( (2,2,0,\"XXYY\") )\n  ijk.append( (2,0,2,\"XXZZ\") )\n  ijk.append( (0,2,2,\"YYZZ\") )\n  ijk.append( (2,1,1,\"XXYZ\") )\n  ijk.append( (1,2,1,\"YYXZ\") )\n  ijk.append( (1,1,2,\"ZZXY\") )\n  # H\n  ijk.append( (5,0,0,\"XXXXX\") )\n  ijk.append( (0,5,0,\"YYYYY\") )\n  ijk.append( (0,0,5,\"ZZZZZ\") )\n  ijk.append( (4,1,0,\"XXXXY\") )\n  ijk.append( (4,0,1,\"XXXXZ\") )\n  ijk.append( (1,4,0,\"YYYYX\") )\n  ijk.append( (0,4,1,\"YYYYZ\") )\n  ijk.append( (1,0,4,\"ZZZZX\") )\n  ijk.append( (0,1,4,\"ZZZZY\") )\n  ijk.append( (3,2,0,\"XXXYY\") )\n  ijk.append( (3,0,2,\"XXXZZ\") )\n  ijk.append( (2,3,0,\"YYYXX\") )\n  ijk.append( (0,3,2,\"YYYZZ\") )\n  ijk.append( (2,0,3,\"ZZZXX\") )\n  ijk.append( (0,2,3,\"ZZZYY\") )\n  ijk.append( (3,1,1,\"XXXYZ\") )\n  ijk.append( (1,3,1,\"YYYXZ\") )\n  ijk.append( (1,1,3,\"ZZZXY\") )\n  ijk.append( (2,2,1,\"XXYYZ\") )\n  ijk.append( (2,1,2,\"XXZZY\") )\n  ijk.append( (1,2,2,\"YYZZX\") )\n  # I\n  ijk.append( (6,0,0,\"X6\") )\n  ijk.append( (0,6,0,\"Y6\") )\n  ijk.append( (0,0,6,\"Z6\") )\n  ijk.append( (5,1,0,\"X5Y\") )\n  ijk.append( (5,0,1,\"X5Z\") )\n  ijk.append( (1,5,0,\"Y5X\") )\n  ijk.append( (0,5,1,\"Y5Z\") )\n  ijk.append( (1,0,5,\"Z5X\") )\n  ijk.append( (0,1,5,\"Z5Y\") )\n  ijk.append( (4,2,0,\"X4Y2\") )\n  ijk.append( (4,0,2,\"X4Z2\") )\n  ijk.append( (2,4,0,\"Y4X2\") )\n  ijk.append( (0,4,2,\"Y4Z2\") )\n  ijk.append( (2,0,4,\"Z4X2\") )\n  ijk.append( (0,2,4,\"Z4Y2\") )\n  ijk.append( (4,1,1,\"X4YZ\") )\n  ijk.append( (1,4,1,\"Y4XZ\") )\n  ijk.append( (1,1,4,\"Z4XY\") )\n  ijk.append( (3,3,0,\"X3Y3\") )\n  ijk.append( (3,0,3,\"X3Z3\") )\n  ijk.append( (0,3,3,\"Y3Z3\") )\n  ijk.append( (3,2,1,\"X3Y2Z\") )\n  ijk.append( (3,1,2,\"X3Z2Y\") )\n  ijk.append( (2,3,1,\"Y3X2Z\") )\n  ijk.append( (1,3,2,\"Y3Z2X\") )\n  ijk.append( (2,1,3,\"Z3X2Y\") )\n  ijk.append( (1,2,3,\"Z3Y2X\") )\n  ijk.append( (2,2,2,\"X2Y2Z2\") )\n\n  return ijk\n\n#  Input is a list of i,j,k,s ( descriptive string )\n#  Output is a list that adds the maximum L (sum of i,j,k) up to that point.\ndef gen_lmax(ijk_list):\n  list_with_lmax = []\n  lmax = -1\n  for i,j,k,s in ijk_list:\n    current_l = i+j+k\n    if current_l > lmax:\n      lmax = current_l\n    list_with_lmax.append( (i,j,k,s,lmax) )\n  return list_with_lmax\n\n\n# Replace powers with pre-computed values.\n# One reason for this replacement is the current code prints powers as '**' and so is not even valid C++.\n#  Using the C printer and printing as 'pow' could lead to poor performance.\n# This does a manual common subexpression elimination.  Could imagine using the cse module to do more\n# automatically.  The tricky part might be only computing pieces needed for lmax.\ndef replace_common_subexpressions(expr, slist=None):\n  x,y,z = symbols('x y z')\n  x2,y2,z2 = symbols('x2 y2 z2')\n  x3,y3,z3 = symbols('x3 y3 z3')\n  x4,y4,z4 = symbols('x4 y4 z4')\n  x5,y5,z5 = symbols('x5 y5 z5')\n\n  rlist0 = {x**6:x*x5, y**6:y*y5, z**6:z*z5}\n  rlist1 = {x**5:x*x4, y**5:y*y4, z**5:z*z4}\n  rlist2 = {x**4:x4, y**4:y4, z**4: z4}\n  rlist3 = {x**3:x3, y**3:y3, z**3:z3}\n  rlist4 = {x**2:x2, y**2:y2, z**2:z2}\n\n  if slist:\n    expr = expr.subs(slist)\n\n  return expr.subs(rlist0).subs(rlist1).subs(rlist2).subs(rlist3).subs(rlist4)\n\ndef gen_evaluate():\n  out_str = \"\"\"\ntemplate<class T, class Point_t, class Tensor_t, class GGG_t>\nvoid CartesianTensor<T,Point_t, Tensor_t, GGG_t>::evaluate(const Point_t& p)\n{\n  value_type x=p[0], y=p[1], z=p[2];\n  value_type x2=x*x, y2=y*y, z2=z*z;\n  value_type x3=x2*x, y3=y2*y, z3=z2*z;\n  value_type x4=x3*x, y4=y3*y, z4=z3*z;\n  value_type x5=x4*x, y5=y4*y, z5=z4*z;\n  switch(Lmax)\n  {\n%s\n  }\n  for (int i=0; i<XYZ.size(); i++)\n    XYZ[i]*= NormFactor[i];\n}\n\"\"\"\n  gto_s = create_gto_symbolic()\n  # just the 'angular' part\n  gto_s = gto_s.subs(Symbol('alpha'),0)\n\n  ijk_with_lmax = gen_lmax(get_ijk())\n  body_str = ''\n  curr_lmax = -1\n  # put index and values in a list so it can be reversed\n  ijk_l = [(idx,c) for idx,c in enumerate(ijk_with_lmax)]\n\n  for idx, (i,j,k,s,lmax) in reversed(ijk_l):\n    if lmax != curr_lmax:\n      curr_lmax = lmax\n      body_str += \"  case %d:\\n\"%curr_lmax\n\n    slist = {Symbol('i'):i, Symbol('j'):j, Symbol('k'):k}\n    val = replace_common_subexpressions(gto_s, slist)\n    body_str += \"    XYZ[%d] = %s; // %s\\n\"%(idx,val,s)\n\n  return out_str%body_str\n\ndef gen_evaluate_all():\n  out_str = \"\"\"\ntemplate<class T, class Point_t, class Tensor_t, class GGG_t>\nvoid CartesianTensor<T,Point_t, Tensor_t, GGG_t>::evaluateAll(const Point_t& p)\n{\n  value_type x=p[0], y=p[1], z=p[2];\n  value_type x2=x*x, y2=y*y, z2=z*z;\n  value_type x3=x2*x, y3=y2*y, z3=z2*z;\n  value_type x4=x3*x, y4=y3*y, z4=z3*z;\n  value_type x5=x4*x, y5=y4*y, z5=z4*z;\n  int ntot=XYZ.size();\n  for (int i=0; i<ntot; i++)\n    gradXYZ[i]=0.0;\n  for (int i=0; i<ntot; i++)\n    laplXYZ[i]=0.0;\n\n  switch(Lmax)\n  {\n%s\n  }\n  for (int i=0; i<ntot; i++)\n    XYZ[i]*= NormFactor[i];\n  for (int i=0; i<ntot; i++)\n    gradXYZ[i]*= NormFactor[i];\n  for (int i=0; i<ntot; i++)\n    laplXYZ[i]*= NormFactor[i];\n\n}\n\"\"\"\n  gto_s = create_gto_symbolic()\n  # just the 'angular' part\n  gto_s = gto_s.subs(Symbol('alpha'),0)\n\n  ijk_with_lmax = gen_lmax(get_ijk())\n  body_str = ''\n  curr_lmax = -1\n  # put index and values in a list so it can be reversed\n  ijk_l = [(idx,c) for idx,c in enumerate(ijk_with_lmax)]\n\n  x,y,z = symbols('x y z')\n\n  for idx, (i,j,k,s,lmax) in reversed(ijk_l):\n    if lmax != curr_lmax:\n      curr_lmax = lmax\n      body_str += \"  case %d:\\n\"%curr_lmax\n\n    # Compute derivatives symbolically\n    dx = diff(gto_s, x)\n    dy = diff(gto_s, y)\n    dz = diff(gto_s, z)\n    lap = diff(gto_s, x, 2) + diff(gto_s, y, 2) + diff(gto_s, z, 2)\n\n    slist = {Symbol('i'):i, Symbol('j'):j, Symbol('k'):k}\n    val = replace_common_subexpressions(gto_s, slist)\n    gx = replace_common_subexpressions(dx, slist)\n    gy = replace_common_subexpressions(dy, slist)\n    gz = replace_common_subexpressions(dz, slist)\n    lap_val = replace_common_subexpressions(lap, slist)\n\n\n    body_str += \"    XYZ[%d] = %s;     // %s\\n\"%(idx,val,s)\n\n    if gx != 0:\n      body_str += \"    gradXYZ[%d][0] = %s;\\n\"%(idx,gx)\n    if gy != 0:\n      body_str += \"    gradXYZ[%d][1] = %s;\\n\"%(idx,gy)\n    if gz != 0:\n      body_str += \"    gradXYZ[%d][2] = %s;\\n\"%(idx,gz)\n\n    if lap_val != 0:\n      body_str += \"    laplXYZ[%d] = %s;\\n\"%(idx,lap_val)\n\n  return out_str%body_str\n\ndef gen_evaluate_with_hessian():\n  out_str = \"\"\"\ntemplate<class T, class Point_t, class Tensor_t, class GGG_t>\nvoid CartesianTensor<T,Point_t, Tensor_t, GGG_t>::evaluateWithHessian(const Point_t& p)\n{\n  value_type x=p[0], y=p[1], z=p[2];\n  value_type x2=x*x, y2=y*y, z2=z*z;\n  value_type x3=x2*x, y3=y2*y, z3=z2*z;\n  value_type x4=x3*x, y4=y3*y, z4=z3*z;\n  value_type x5=x4*x, y5=y4*y, z5=z4*z;\n  int ntot=XYZ.size();\n  for (int i=0; i<ntot; i++)\n    gradXYZ[i]=0.0;\n  for (int i=0; i<ntot; i++)\n    hessXYZ[i]=0.0;\n\n  switch(Lmax)\n  {\n%s\n  }\n  for (int i=0; i<ntot; i++)\n    XYZ[i]*= NormFactor[i];\n  for (int i=0; i<ntot; i++)\n    gradXYZ[i]*= NormFactor[i];\n  for (int i=0; i<ntot; i++)\n    hessXYZ[i]*= NormFactor[i];\n}\n\"\"\"\n\n  gto_s = create_gto_symbolic()\n  # just the 'angular' part\n  gto_s = gto_s.subs(Symbol('alpha'),0)\n\n  ijk_with_lmax = gen_lmax(get_ijk())\n  body_str = ''\n  curr_lmax = -1\n  ijk_l = [(idx,c) for idx,c in enumerate(ijk_with_lmax)]\n\n  x,y,z = symbols('x y z')\n\n  for idx, (i,j,k,s,lmax) in reversed(ijk_l):\n    if lmax != curr_lmax:\n      curr_lmax = lmax\n      body_str += \"  case %d:\\n\"%curr_lmax\n\n    slist = {Symbol('i'):i, Symbol('j'):j, Symbol('k'):k}\n\n    # Compute derivatives symbolically\n    dx = diff(gto_s, x)\n    dy = diff(gto_s, y)\n    dz = diff(gto_s, z)\n\n    val = replace_common_subexpressions(gto_s, slist)\n    body_str += \"    XYZ[%d] = %s;     // %s\\n\"%(idx,val,s)\n\n    gx = replace_common_subexpressions(dx, slist)\n    gy = replace_common_subexpressions(dy, slist)\n    gz = replace_common_subexpressions(dz, slist)\n    if gx != 0:\n      body_str += \"    gradXYZ[%d][0] = %s;\\n\"%(idx,gx)\n    if gy != 0:\n      body_str += \"    gradXYZ[%d][1] = %s;\\n\"%(idx,gy)\n    if gz != 0:\n      body_str += \"    gradXYZ[%d][2] = %s;\\n\"%(idx,gz)\n\n    axis_syms = [Symbol('x'), Symbol('y'), Symbol('z')]\n    for ii,si in enumerate(axis_syms):\n      for jj,sj in enumerate(axis_syms):\n        # Compute Hessian elements symbolically\n        h_s = diff(diff(gto_s, si), sj)\n        hess_val = replace_common_subexpressions(h_s, slist)\n        if hess_val != 0:\n          body_str += \"    hessXYZ[%d](%d,%d) = %s;\\n\"%(idx,ii,jj,hess_val)\n\n  return out_str%body_str\n\ndef gen_evaluate_with_third_deriv():\n  out_str = \"\"\"\ntemplate<class T, class Point_t, class Tensor_t, class GGG_t>\nvoid CartesianTensor<T,Point_t, Tensor_t, GGG_t>::evaluateWithThirdDeriv(const Point_t& p)\n{\n  value_type x=p[0], y=p[1], z=p[2];\n  value_type x2=x*x, y2=y*y, z2=z*z;\n  value_type x3=x2*x, y3=y2*y, z3=z2*z;\n  value_type x4=x3*x, y4=y3*y, z4=z3*z;\n  value_type x5=x4*x, y5=y4*y, z5=z4*z;\n\n  int ntot=XYZ.size();\n  for (int i=0; i<ntot; i++)\n    gradXYZ[i]=0.0;\n  for (int i=0; i<ntot; i++)\n    hessXYZ[i]=0.0;\n  for (int i=0; i<ntot; i++)\n  {\n    gggXYZ[i][0]=0.0;\n    gggXYZ[i][1]=0.0;\n    gggXYZ[i][2]=0.0;\n  }\n\n  switch(Lmax)\n  {\n%s\n  }\n\n  for (int i=0; i<ntot; i++)\n    XYZ[i]*= NormFactor[i];\n  for (int i=0; i<ntot; i++)\n    gradXYZ[i]*= NormFactor[i];\n  for (int i=0; i<ntot; i++)\n    hessXYZ[i]*= NormFactor[i];\n  for (int i=0; i<ntot; i++)\n  {\n    gggXYZ[i][0] *= NormFactor[i];\n    gggXYZ[i][1] *= NormFactor[i];\n    gggXYZ[i][2] *= NormFactor[i];\n  }\n}\n\n\"\"\"\n\n  gto_s = create_gto_symbolic()\n  # just the 'angular' part\n  gto_s = gto_s.subs(Symbol('alpha'),0)\n\n  ijk_with_lmax = gen_lmax(get_ijk())\n  body_str = ''\n  curr_lmax = -1\n  # put index and values in a list so it can be reversed\n  ijk_l = [(idx,c) for idx,c in enumerate(ijk_with_lmax)]\n\n  x,y,z = symbols('x y z')\n\n  for idx, (i,j,k,s,lmax) in reversed(ijk_l):\n    if lmax != curr_lmax:\n      curr_lmax = lmax\n      body_str += \"  case %d:\\n\"%curr_lmax\n\n    slist = {Symbol('i'):i, Symbol('j'):j, Symbol('k'):k}\n\n    dx = diff(gto_s, x)\n    dy = diff(gto_s, y)\n    dz = diff(gto_s, z)\n\n    val = replace_common_subexpressions(gto_s, slist)\n    body_str += \"    XYZ[%d] = %s;     // %s\\n\"%(idx,val,s)\n\n    gx = replace_common_subexpressions(dx, slist)\n    gy = replace_common_subexpressions(dy, slist)\n    gz = replace_common_subexpressions(dz, slist)\n    if gx != 0:\n      body_str += \"    gradXYZ[%d][0] = %s;\\n\"%(idx,gx)\n    if gy != 0:\n      body_str += \"    gradXYZ[%d][1] = %s;\\n\"%(idx,gy)\n    if gz != 0:\n      body_str += \"    gradXYZ[%d][2] = %s;\\n\"%(idx,gz)\n\n    axis_syms = [Symbol('x'), Symbol('y'), Symbol('z')]\n    for ii,si in enumerate(axis_syms):\n      for jj,sj in enumerate(axis_syms):\n        h_s = diff(diff(gto_s, si), sj)\n        hess_val = replace_common_subexpressions(h_s, slist)\n        if hess_val != 0:\n          body_str += \"    hessXYZ[%d](%d,%d) = %s;\\n\"%(idx,ii,jj,hess_val)\n\n    for ii,si in enumerate(axis_syms):\n      for jj,sj in enumerate(axis_syms):\n        for kk,sk in enumerate(axis_syms):\n          ggg_s = diff(diff(diff(gto_s, si), sj), sk)\n          ggg_val = replace_common_subexpressions(ggg_s, slist)\n\n          if ggg_val != 0:\n            body_str += \"    gggXYZ[%d][%d](%d,%d) = %s;\\n\"%(idx,ii,jj,kk,ggg_val)\n\n  return out_str%body_str\n\n\ndef gen_evaluate_third_deriv_only():\n  out_str = \"\"\"\ntemplate<class T, class Point_t, class Tensor_t, class GGG_t>\nvoid CartesianTensor<T,Point_t, Tensor_t, GGG_t>::evaluateThirdDerivOnly(const Point_t& p)\n{\n  value_type x=p[0], y=p[1], z=p[2];\n  value_type x2=x*x, y2=y*y, z2=z*z;\n  value_type x3=x2*x, y3=y2*y, z3=z2*z;\n  int ntot=XYZ.size();\n  for (int i=0; i<ntot; i++)\n  {\n    gggXYZ[i][0]=0.0;\n    gggXYZ[i][1]=0.0;\n    gggXYZ[i][2]=0.0;\n  }\n\n  switch(Lmax)\n  {\n%s\n  }\n\n  for (int i=0; i<ntot; i++)\n  {\n    gggXYZ[i][0] *= NormFactor[i];\n    gggXYZ[i][1] *= NormFactor[i];\n    gggXYZ[i][2] *= NormFactor[i];\n  }\n}\n\n\"\"\"\n\n  gto_s = create_gto_symbolic()\n  # just the 'angular' part\n  gto_s = gto_s.subs(Symbol('alpha'),0)\n\n  ijk_with_lmax = gen_lmax(get_ijk())\n  body_str = ''\n  curr_lmax = -1\n  # put index and values in a list so it can be reversed\n  ijk_l = [(idx,c) for idx,c in enumerate(ijk_with_lmax)]\n\n  x,y,z = symbols('x y z')\n\n  case_has_content = False\n  for idx, (i,j,k,s,lmax) in reversed(ijk_l):\n    if lmax != curr_lmax:\n      body_str += \"  case %d:\\n\"%lmax\n      if not case_has_content and curr_lmax != -1:\n        body_str += \"        ; // empty statement\\n\"\n      curr_lmax = lmax\n      case_has_content = False\n\n    slist = {Symbol('i'):i, Symbol('j'):j, Symbol('k'):k}\n\n    axis_syms = [Symbol('x'), Symbol('y'), Symbol('z')]\n    for ii,si in enumerate(axis_syms):\n      for jj,sj in enumerate(axis_syms):\n        for kk,sk in enumerate(axis_syms):\n          ggg_s = diff(diff(diff(gto_s, si), sj), sk)\n          ggg_val = replace_common_subexpressions(ggg_s, slist)\n\n          if ggg_val != 0:\n            body_str += \"    gggXYZ[%d][%d](%d,%d) = %s;\\n\"%(idx,ii,jj,kk,ggg_val)\n            case_has_content = True\n\n  return out_str%body_str\n\ndef gen_soa_evaluate_bare():\n  out_str = \"\"\"\ntemplate<class T>\nvoid SoaCartesianTensor<T>::evaluate_bare(T x, T y, T z, T* restrict XYZ) const\n{\n  const T x2=x*x, y2=y*y, z2=z*z;\n  const T x3=x2*x, y3=y2*y, z3=z2*z;\n  const T x4=x3*x, y4=y3*y, z4=z3*z;\n  const T x5=x4*x, y5=y4*y, z5=z4*z;\n  switch(Lmax)\n  {\n%s\n  }\n}\n\"\"\"\n  gto_s = create_gto_symbolic()\n  # just the 'angular' part\n  gto_s = gto_s.subs(Symbol('alpha'),0)\n\n  ijk_with_lmax = gen_lmax(get_ijk())\n  body_str = ''\n  curr_lmax = -1\n  # put index and values in a list so it can be reversed\n  ijk_l = [(idx,c) for idx,c in enumerate(ijk_with_lmax)]\n\n  for idx, (i,j,k,s,lmax) in reversed(ijk_l):\n    if lmax != curr_lmax:\n      curr_lmax = lmax\n      body_str += \"  case %d:\\n\"%curr_lmax\n\n    slist = {Symbol('i'):i, Symbol('j'):j, Symbol('k'):k}\n    val = replace_common_subexpressions(gto_s, slist)\n    body_str += \"    XYZ[%d] = %s; // %s\\n\"%(idx,val,s)\n\n  return out_str%body_str\n\n\ndef gen_soa_evaluate_vgl():\n  out_str = \"\"\"\ntemplate<class T>\nvoid SoaCartesianTensor<T>::evaluateVGL(T x, T y, T z)\n{\n\n  constexpr T czero(0);\n  cXYZ=czero;\n\n  const T x2=x*x, y2=y*y, z2=z*z;\n  const T x3=x2*x, y3=y2*y, z3=z2*z;\n  const T x4=x3*x, y4=y3*y, z4=z3*z;\n  const T x5=x4*x, y5=y4*y, z5=z4*z;\n  T* restrict XYZ=cXYZ.data(0);\n  T* restrict gr0=cXYZ.data(1);\n  T* restrict gr1=cXYZ.data(2);\n  T* restrict gr2=cXYZ.data(3);\n  T* restrict lap=cXYZ.data(4);\n\n  switch(Lmax)\n  {\n%s\n  }\n\n  const size_t ntot=NormFactor.size();\n  for (size_t i=0; i<ntot; i++)\n  {\n    XYZ[i]*= NormFactor[i];\n    gr0[i]*= NormFactor[i];\n    gr1[i]*= NormFactor[i];\n    gr2[i]*= NormFactor[i];\n    lap[i]*= NormFactor[i];\n  }\n}\n\"\"\"\n  gto_s = create_gto_symbolic()\n  # just the 'angular' part\n  gto_s = gto_s.subs(Symbol('alpha'),0)\n\n  ijk_with_lmax = gen_lmax(get_ijk())\n  body_str = ''\n  curr_lmax = -1\n  # put index and values in a list so it can be reversed\n  ijk_l = [(idx,c) for idx,c in enumerate(ijk_with_lmax)]\n\n  x,y,z = symbols('x y z')\n\n  for idx, (i,j,k,s,lmax) in reversed(ijk_l):\n    if lmax != curr_lmax:\n      curr_lmax = lmax\n      body_str += \"  case %d:\\n\"%curr_lmax\n\n    # Compute derivatives symbolically\n    dx = diff(gto_s, x)\n    dy = diff(gto_s, y)\n    dz = diff(gto_s, z)\n    lap = diff(gto_s, x, 2) + diff(gto_s, y, 2) + diff(gto_s, z, 2)\n\n    slist = {Symbol('i'):i, Symbol('j'):j, Symbol('k'):k}\n    val = replace_common_subexpressions(gto_s, slist)\n    gx = replace_common_subexpressions(dx, slist)\n    gy = replace_common_subexpressions(dy, slist)\n    gz = replace_common_subexpressions(dz, slist)\n    lap_val = replace_common_subexpressions(lap, slist)\n\n\n    body_str += \"    XYZ[%d] = %s;     // %s\\n\"%(idx,val,s)\n\n    if gx != 0:\n      body_str += \"    gr0[%d] = %s;\\n\"%(idx,gx)\n    if gy != 0:\n      body_str += \"    gr1[%d] = %s;\\n\"%(idx,gy)\n    if gz != 0:\n      body_str += \"    gr2[%d] = %s;\\n\"%(idx,gz)\n\n    if lap_val != 0:\n      body_str += \"    lap[%d] = %s;\\n\"%(idx,lap_val)\n\n  return out_str%body_str\n\ndef gen_soa_evaluate_vgh():\n  out_str = \"\"\"\ntemplate<class T>\nvoid SoaCartesianTensor<T>::evaluateVGH(T x, T y, T z)\n{\n  constexpr T czero(0);\n  cXYZ=czero;\n\n  const T x2=x*x, y2=y*y, z2=z*z;\n  const T x3=x2*x, y3=y2*y, z3=z2*z;\n  const T x4=x3*x, y4=y3*y, z4=z3*z;\n  const T x5=x4*x, y5=y4*y, z5=z4*z;\n\n  T* restrict XYZ=cXYZ.data(0);\n  T* restrict gr0=cXYZ.data(1);\n  T* restrict gr1=cXYZ.data(2);\n  T* restrict gr2=cXYZ.data(3);\n  T* restrict h00=cXYZ.data(4);\n  T* restrict h01=cXYZ.data(5);\n  T* restrict h02=cXYZ.data(6);\n  T* restrict h11=cXYZ.data(7);\n  T* restrict h12=cXYZ.data(8);\n  T* restrict h22=cXYZ.data(9);\n\n\n  switch(Lmax)\n  {\n%s\n  }\n\n  const size_t ntot=cXYZ.size();\n  for(size_t i=0; i<ntot; ++i)\n  {\n    XYZ[i]*= NormFactor[i];\n    gr0[i]*= NormFactor[i];\n    gr1[i]*= NormFactor[i];\n    gr2[i]*= NormFactor[i];\n    h00[i]*= NormFactor[i];\n    h01[i]*= NormFactor[i];\n    h02[i]*= NormFactor[i];\n    h11[i]*= NormFactor[i];\n    h12[i]*= NormFactor[i];\n    h22[i]*= NormFactor[i];\n  }\n\n}\n\"\"\"\n\n  gto_s = create_gto_symbolic()\n  # just the 'angular' part\n  gto_s = gto_s.subs(Symbol('alpha'),0)\n\n  ijk_with_lmax = gen_lmax(get_ijk())\n  body_str = ''\n  curr_lmax = -1\n  ijk_l = [(idx,c) for idx,c in enumerate(ijk_with_lmax)]\n\n  x,y,z = symbols('x y z')\n\n  for idx, (i,j,k,s,lmax) in reversed(ijk_l):\n    if lmax != curr_lmax:\n      curr_lmax = lmax\n      body_str += \"  case %d:\\n\"%curr_lmax\n\n    slist = {Symbol('i'):i, Symbol('j'):j, Symbol('k'):k}\n\n    # Compute derivatives symbolically\n    dx = diff(gto_s, x)\n    dy = diff(gto_s, y)\n    dz = diff(gto_s, z)\n\n    val = replace_common_subexpressions(gto_s, slist)\n    body_str += \"    XYZ[%d] = %s;     // %s\\n\"%(idx,val,s)\n\n    gx = replace_common_subexpressions(dx, slist)\n    gy = replace_common_subexpressions(dy, slist)\n    gz = replace_common_subexpressions(dz, slist)\n    if gx != 0:\n      body_str += \"    gr0[%d] = %s;\\n\"%(idx,gx)\n    if gy != 0:\n      body_str += \"    gr1[%d] = %s;\\n\"%(idx,gy)\n    if gz != 0:\n      body_str += \"    gr2[%d] = %s;\\n\"%(idx,gz)\n\n    axis_syms = [Symbol('x'), Symbol('y'), Symbol('z')]\n    for ii,si in enumerate(axis_syms):\n      for jj,sj in enumerate(axis_syms):\n        if ii <= jj:\n          # Compute Hessian elements symbolically\n          h_s = diff(diff(gto_s, si), sj)\n          hess_val = replace_common_subexpressions(h_s, slist)\n          if hess_val != 0 :\n            body_str += \"    h%d%d[%d] = %s;\\n\"%(ii,jj,idx,hess_val)\n\n  return out_str%body_str\n\ndef gen_soa_evaluate_vghgh():\n  out_str = \"\"\"\ntemplate<class T>\nvoid SoaCartesianTensor<T>::evaluateVGHGH(T x, T y, T z)\n{\n  constexpr T czero(0);\n  cXYZ=czero;\n\n  const T x2=x*x, y2=y*y, z2=z*z;\n  const T x3=x2*x, y3=y2*y, z3=z2*z;\n  const T x4=x3*x, y4=y3*y, z4=z3*z;\n  const T x5=x4*x, y5=y4*y, z5=z4*z;\n\n  T* restrict XYZ   = cXYZ.data(0);\n  T* restrict gr0   = cXYZ.data(1);\n  T* restrict gr1   = cXYZ.data(2);\n  T* restrict gr2   = cXYZ.data(3);\n  T* restrict h00   = cXYZ.data(4);\n  T* restrict h01   = cXYZ.data(5);\n  T* restrict h02   = cXYZ.data(6);\n  T* restrict h11   = cXYZ.data(7);\n  T* restrict h12   = cXYZ.data(8);\n  T* restrict h22   = cXYZ.data(9);\n  T* restrict gh000 = cXYZ.data(10);\n  T* restrict gh001 = cXYZ.data(11);\n  T* restrict gh002 = cXYZ.data(12);\n  T* restrict gh011 = cXYZ.data(13);\n  T* restrict gh012 = cXYZ.data(14);\n  T* restrict gh022 = cXYZ.data(15);\n  T* restrict gh111 = cXYZ.data(16);\n  T* restrict gh112 = cXYZ.data(17);\n  T* restrict gh122 = cXYZ.data(18);\n  T* restrict gh222 = cXYZ.data(19);\n\n  switch(Lmax)\n  {\n%s\n  }\n\n  const size_t ntot=cXYZ.size();\n  for(size_t i=0; i<ntot; ++i)\n  {\n    XYZ[i]   *= NormFactor[i];\n    gr0[i]   *= NormFactor[i];\n    gr1[i]   *= NormFactor[i];\n    gr2[i]   *= NormFactor[i];\n    h00[i]   *= NormFactor[i];\n    h01[i]   *= NormFactor[i];\n    h02[i]   *= NormFactor[i];\n    h11[i]   *= NormFactor[i];\n    h12[i]   *= NormFactor[i];\n    h22[i]   *= NormFactor[i];\n    gh000[i] *= NormFactor[i];\n    gh001[i] *= NormFactor[i];\n    gh002[i] *= NormFactor[i];\n    gh011[i] *= NormFactor[i];\n    gh012[i] *= NormFactor[i];\n    gh022[i] *= NormFactor[i];\n    gh111[i] *= NormFactor[i];\n    gh112[i] *= NormFactor[i];\n    gh122[i] *= NormFactor[i];\n    gh222[i] *= NormFactor[i];\n  }\n\n}\n\"\"\"\n\n  gto_s = create_gto_symbolic()\n  # just the 'angular' part\n  gto_s = gto_s.subs(Symbol('alpha'),0)\n\n  ijk_with_lmax = gen_lmax(get_ijk())\n  body_str = ''\n  curr_lmax = -1\n  ijk_l = [(idx,c) for idx,c in enumerate(ijk_with_lmax)]\n\n  x,y,z = symbols('x y z')\n\n  for idx, (i,j,k,s,lmax) in reversed(ijk_l):\n    if lmax != curr_lmax:\n      curr_lmax = lmax\n      body_str += \"  case %d:\\n\"%curr_lmax\n\n    slist = {Symbol('i'):i, Symbol('j'):j, Symbol('k'):k}\n\n    # Compute derivatives symbolically\n    dx = diff(gto_s, x)\n    dy = diff(gto_s, y)\n    dz = diff(gto_s, z)\n\n    val = replace_common_subexpressions(gto_s, slist)\n    body_str += \"    XYZ[%d] = %s;     // %s\\n\"%(idx,val,s)\n\n    gx = replace_common_subexpressions(dx, slist)\n    gy = replace_common_subexpressions(dy, slist)\n    gz = replace_common_subexpressions(dz, slist)\n    if gx != 0:\n      body_str += \"    gr0[%d] = %s;\\n\"%(idx,gx)\n    if gy != 0:\n      body_str += \"    gr1[%d] = %s;\\n\"%(idx,gy)\n    if gz != 0:\n      body_str += \"    gr2[%d] = %s;\\n\"%(idx,gz)\n\n    axis_syms = [Symbol('x'), Symbol('y'), Symbol('z')]\n    for ii,si in enumerate(axis_syms):\n      for jj,sj in enumerate(axis_syms):\n        if ii <= jj:\n          # Compute Hessian elements symbolically\n          h_s = diff(diff(gto_s, si), sj)\n          hess_val = replace_common_subexpressions(h_s, slist)\n          if hess_val != 0 :\n            body_str += \"    h%d%d[%d] = %s;\\n\"%(ii,jj,idx,hess_val)\n\n    for ii,si in enumerate(axis_syms):\n      for jj,sj in enumerate(axis_syms):\n         for kk,sk in enumerate(axis_syms):\n           if ii <= jj and jj <= kk:\n           # Compute Grad Hessian elements symbolically\n             ghess_s = diff(diff(diff(gto_s, si), sj),sk)\n             ghess_val = replace_common_subexpressions(ghess_s, slist)\n             if ghess_val != 0 :\n               body_str += \"    gh%d%d%d[%d] = %s;\\n\"%(ii,jj,kk,idx,ghess_val)\n\n  return out_str%body_str\n\n# A simple template replacement engine.\n# Template items to be replaced start on a line with '%'.\ndef run_template(fname_in, fname_out, bodies):\n  out = ''\n  with open(fname_in, 'r') as f:\n    for line in f:\n      if line.startswith('%'):\n        key = line.strip()[1:]\n        if key in bodies:\n          line = bodies[key]\n        else:\n          print 'Error, template item not found, key:',key, ' line = ',line\n      out += line\n\n  with open(fname_out, 'w') as f:\n    f.write(out)\n\ndire_codegen_text = \"\"\"\n/*\n DO NOT MAKE PERMANENT EDITS IN THIS FILE\n This file is generated from src/Numerics/codegen/%(script_name)s and %(template_file_name)s\n\n Edit %(template_file_name)s, rerun %(script_name)s, and copy the generated file here.\n*/\n\"\"\"\n\ndef create_cartesian_tensor_h():\n  bodies = dict()\n  bodies['evaluate'] = gen_evaluate()\n  bodies['evaluate_all'] = gen_evaluate_all()\n  bodies['evaluate_with_hessian'] = gen_evaluate_with_hessian()\n  bodies['evaluate_with_third_deriv'] = gen_evaluate_with_third_deriv()\n  bodies['evaluate_third_deriv_only'] = gen_evaluate_third_deriv_only()\n  fname_out = 'CartesianTensor.h'\n  fname_in= 'CartesianTensor.h.in'\n\n  bodies['dire_codegen_warning'] = dire_codegen_text%({'script_name':'gen_cartesian_tensor.py', 'template_file_name':fname_in})\n\n  run_template(fname_in, fname_out, bodies)\n\ndef create_soa_cartesian_tensor_h():\n  bodies = dict()\n  bodies['evaluate_bare'] = gen_soa_evaluate_bare()\n  bodies['evaluate_vgl'] = gen_soa_evaluate_vgl()\n  bodies['evaluate_vgh'] = gen_soa_evaluate_vgh()\n  bodies['evaluate_vghgh'] = gen_soa_evaluate_vghgh()\n  fname_in= 'SoaCartesianTensor.h.in'\n  fname_out = 'SoaCartesianTensor.h'\n\n  bodies['dire_codegen_warning'] = dire_codegen_text%({'script_name':'gen_cartesian_tensor.py', 'template_file_name':fname_in})\n\n  run_template(fname_in, fname_out, bodies)\n\n\nif __name__ == '__main__':\n    #print gen_evaluate()\n    #print gen_evaluate_all()\n    #print gen_evaluate_with_hessian()\n    #print gen_evaluate_with_third_deriv()\n    #print gen_evaluate_third_deriv_only()\n\n    # Create CartesianTensor.h from CartesianTensor.h.in\n    create_cartesian_tensor_h()\n\n    # Create SoaCartesianTensor.h from SoaCartesianTensor.h.in\n    create_soa_cartesian_tensor_h()\n\n", "meta": {"hexsha": "57f0ce921f175240fe7efe4a9a2cc05fe6e1f83f", "size": 26290, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Numerics/codegen/gen_cartesian_tensor.py", "max_stars_repo_name": "djstaros/qmcpack", "max_stars_repo_head_hexsha": "280f67e638bae280448b47fa618f05b848c530d2", "max_stars_repo_licenses": ["NCSA"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Numerics/codegen/gen_cartesian_tensor.py", "max_issues_repo_name": "djstaros/qmcpack", "max_issues_repo_head_hexsha": "280f67e638bae280448b47fa618f05b848c530d2", "max_issues_repo_licenses": ["NCSA"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-05-09T20:57:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-10T00:00:17.000Z", "max_forks_repo_path": "src/Numerics/codegen/gen_cartesian_tensor.py", "max_forks_repo_name": "djstaros/qmcpack", "max_forks_repo_head_hexsha": "280f67e638bae280448b47fa618f05b848c530d2", "max_forks_repo_licenses": ["NCSA"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6071817193, "max_line_length": 127, "alphanum_fraction": 0.60041841, "include": true, "reason": "from sympy", "num_tokens": 9665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.3242353859211693, "lm_q1q2_score": 0.1772718557065582}}
{"text": "import os\nimport warnings\nimport numpy as np\nfrom pyrates.utility.genetic_algorithm import CGSGeneticAlgorithm\nfrom pandas import DataFrame, read_hdf\nfrom copy import deepcopy\n\n\nclass CustomGOA(CGSGeneticAlgorithm):\n\n    def eval_fitness(self, target: list, **kwargs):\n\n        # define simulation conditions\n        worker_file = self.cgs_config['worker_file'] if 'worker_file' in self.cgs_config else None\n        param_grid = self.pop.drop(['fitness', 'sigma', 'results'], axis=1)\n        result_vars = ['r_e', 'r_p', 'r_a', 'r_m', 'r_f']\n        freq_targets = [0.0, np.nan, np.nan, np.nan, np.nan]\n        #param_grid, invalid_params = eval_params(param_grid)\n        conditions = [{},  # healthy control\n                      {'k_pe': 0.2, 'k_ae': 0.2},  # AMPA blockade in GPe\n                      {'k_pe': 0.2, 'k_ae': 0.2, 'k_pp': 0.2, 'k_pa': 0.2, 'k_pm': 0.2, 'k_aa': 0.2, 'k_ap': 0.2,\n                       'k_am': 0.2},  # AMPA blockade and GABAA blockade in GPe\n                      {'k_pp': 0.2, 'k_pa': 0.2, 'k_pm': 0.2, 'k_aa': 0.2, 'k_ap': 0.2,\n                       'k_am': 0.2},  # GABAA blockade in GPe\n                      {'k_pe': 0.0, 'k_ae': 0.0},  # STN blockade\n                      {'k_ep': 0.2},  # GABAA blocker in STN\n                      ]\n        param_scalings = [\n            ('delta_e', 'tau_e', 2.0),\n            ('delta_p', 'tau_p', 2.0),\n            ('delta_a', 'tau_a', 2.0),\n            ('delta_m', 'tau_m', 2.0),\n            ('delta_f', 'tau_f', 2.0),\n            ('k_ee', 'delta_e', 0.5),\n            ('k_ep', 'delta_e', 0.5),\n            ('k_pe', 'delta_p', 0.5),\n            ('k_pp', 'delta_p', 0.5),\n            ('k_pa', 'tau_p', 0.5),\n            ('k_pm', 'tau_p', 0.5),\n            ('k_ae', 'tau_a', 0.5),\n            ('k_ap', 'tau_a', 0.5),\n            ('k_aa', 'tau_a', 0.5),\n            ('k_am', 'tau_a', 0.5),\n            ('k_mf', 'delta_m', 0.5),\n            ('k_mm', 'delta_m', 0.5),\n            ('k_fa', 'delta_f', 0.5),\n            ('k_ff', 'delta_f', 0.5),\n            ('eta_e', 'delta_e', 1.0),\n            ('eta_p', 'delta_p', 1.0),\n            ('eta_a', 'delta_a', 1.0),\n            ('eta_m', 'delta_m', 1.0),\n            ('eta_f', 'delta_f', 1.0),\n        ]\n        chunk_size = [\n            60,  # carpenters\n            100,  # osttimor\n            60,  # spanien\n            100,  # animals\n            60,  # kongo\n            60,  # tschad\n            #100,  # uganda\n            # 50,  # tiber\n            #50,  # giraffe\n            40,  # lech\n            20,  # rilke\n            12,  # dinkel\n            #10,  # rosmarin\n            #10,  # mosambik\n            # 50,  # compute servers\n            # 40,\n            # 30,\n            # 20,\n            # 10,\n            # 50,\n            # 40,\n            # 30,\n            # 20,\n            # 10,\n            # 50,\n            # 40,\n            # 30,\n            # 20,\n            # 10,\n            # 50,\n            # 40,\n        ]\n\n        # perform simulations\n        if len(param_grid) > 0:\n            self.gs_config['init_kwargs'].update(kwargs)\n            res_file = self.cgs.run(\n                circuit_template=self.gs_config['circuit_template'],\n                param_grid=deepcopy(param_grid),\n                param_map=self.gs_config['param_map'],\n                simulation_time=self.gs_config['simulation_time'],\n                dt=self.gs_config['step_size'],\n                inputs=self.gs_config['inputs'],\n                outputs=self.gs_config['outputs'],\n                sampling_step_size=self.gs_config['sampling_step_size'],\n                permute=False,\n                chunk_size=chunk_size,\n                worker_file=worker_file,\n                worker_env=self.cgs_config['worker_env'],\n                gs_kwargs={'init_kwargs': self.gs_config['init_kwargs'], 'conditions': conditions,\n                           'param_scalings': param_scalings},\n                worker_kwargs={'y': target, 'time_lim': 7200.0, 'freq_targets': freq_targets},\n                result_concat_axis=0)\n            results_tmp = read_hdf(res_file, key=f'Results/results')\n\n            # calculate fitness\n            for gene_id in param_grid.index:\n                self.pop.at[gene_id, 'fitness'] = 1.0 / results_tmp.at[gene_id, 'fitness']\n                self.pop.at[gene_id, 'results'] = [results_tmp.at[gene_id, v] for v in result_vars]\n\n        # set fitness of invalid parametrizations\n        #for gene_id in invalid_params.index:\n        #    self.pop.at[gene_id, 'fitness'] = 0.0\n        #    self.pop.at[gene_id, 'results'] = [0. for _ in result_vars]\n\n\ndef fitness(y, t):\n    y = np.asarray(y).flatten()\n    t = np.asarray(t).flatten()\n    diff = np.asarray([0.0 if np.isnan(t_tmp) else y_tmp - t_tmp for y_tmp, t_tmp in zip(y, t)]).flatten()\n    t[np.isnan(t)] = 1.0\n    t[t == 0] = 1.0\n    weights = 1 / np.abs(t)\n    return weights @ np.abs(diff)\n\n\nif __name__ == \"__main__\":\n    warnings.filterwarnings(\"ignore\")\n\n    pop_size = 1024\n    pop_genes = {\n        'k_ee': {'min': 0, 'max': 15, 'size': pop_size, 'sigma': 0.1, 'loc': 1.0, 'scale': 0.5},\n        'k_ae': {'min': 0, 'max': 150, 'size': pop_size, 'sigma': 0.5, 'loc': 20.0, 'scale': 2.0},\n        'k_pe': {'min': 0, 'max': 150, 'size': pop_size, 'sigma': 0.5, 'loc': 20.0, 'scale': 2.0},\n        'k_pp': {'min': 0, 'max': 100, 'size': pop_size, 'sigma': 0.5, 'loc': 10.0, 'scale': 1.0},\n        'k_ep': {'min': 0, 'max': 150, 'size': pop_size, 'sigma': 0.5, 'loc': 20.0, 'scale': 2.0},\n        'k_ap': {'min': 0, 'max': 100, 'size': pop_size, 'sigma': 0.5, 'loc': 10.0, 'scale': 1.0},\n        'k_aa': {'min': 0, 'max': 50, 'size': pop_size, 'sigma': 0.5, 'loc': 10.0, 'scale': 1.0},\n        'k_pa': {'min': 0, 'max': 50, 'size': pop_size, 'sigma': 0.5, 'loc': 10.0, 'scale': 1.0},\n        'k_fa': {'min': 0, 'max': 100, 'size': pop_size, 'sigma': 0.5, 'loc': 20.0, 'scale': 2.0},\n        'k_mm': {'min': 0, 'max': 50, 'size': pop_size, 'sigma': 0.5, 'loc': 10.0, 'scale': 1.0},\n        'k_am': {'min': 0, 'max': 200, 'size': pop_size, 'sigma': 0.8, 'loc': 40.0, 'scale': 4.0},\n        'k_pm': {'min': 0, 'max': 200, 'size': pop_size, 'sigma': 0.5, 'loc': 5.0, 'scale': 1.0},\n        'k_mf': {'min': 0, 'max': 150, 'size': pop_size, 'sigma': 0.5, 'loc': 20.0, 'scale': 2.0},\n        'k_ff': {'min': 0, 'max': 100, 'size': pop_size, 'sigma': 0.5, 'loc': 10.0, 'scale': 1.0},\n        'eta_e': {'min': -5, 'max': 5, 'size': pop_size, 'sigma': 0.2, 'loc': 0.0, 'scale': 0.5},\n        'eta_p': {'min': -5, 'max': 5, 'size': pop_size, 'sigma': 0.2, 'loc': 0.0, 'scale': 0.5},\n        'eta_a': {'min': -5, 'max': 5, 'size': pop_size, 'sigma': 0.2, 'loc': 0.0, 'scale': 0.5},\n        'eta_m': {'min': -10, 'max': 0, 'size': pop_size, 'sigma': 0.2, 'loc': -3.0, 'scale': 0.5},\n        'eta_f': {'min': -5, 'max': 5, 'size': pop_size, 'sigma': 0.2, 'loc': 0.0, 'scale': 0.5},\n        'delta_e': {'min': 0.01, 'max': 1.0, 'size': pop_size, 'sigma': 0.05, 'loc': 0.1, 'scale': 0.1},\n        'delta_p': {'min': 0.01, 'max': 1.0, 'size': pop_size, 'sigma': 0.05, 'loc': 0.2, 'scale': 0.1},\n        'delta_a': {'min': 0.01, 'max': 1.5, 'size': pop_size, 'sigma': 0.05, 'loc': 0.4, 'scale': 0.1},\n        'delta_m': {'min': 0.01, 'max': 1.5, 'size': pop_size, 'sigma': 0.05, 'loc': 0.2, 'scale': 0.1},\n        'delta_f': {'min': 0.01, 'max': 1.5, 'size': pop_size, 'sigma': 0.05, 'loc': 0.2, 'scale': 0.1},\n        'tau_e': {'min': 12, 'max': 12, 'size': pop_size, 'sigma': 0.0, 'loc': 12.0, 'scale': 0.0},\n        'tau_p': {'min': 24, 'max': 24, 'size': pop_size, 'sigma': 0.0, 'loc': 24.0, 'scale': 0.0},\n        'tau_a': {'min': 20, 'max': 20, 'size': pop_size, 'sigma': 0.0, 'loc': 20.0, 'scale': 0.0},\n        'tau_m': {'min': 20, 'max': 20, 'size': pop_size, 'sigma': 0.0, 'loc': 20.0, 'scale': 0.0},\n        'tau_f': {'min': 20, 'max': 20, 'size': pop_size, 'sigma': 0.0, 'loc': 20.0, 'scale': 0.0},\n        #'tau_ee_v': {'min': 0.5, 'max': 1.0, 'size': 2, 'sigma': 0.1, 'loc': 0.5, 'scale': 0.1},\n        # 'tau_ei': {'min': 3.0, 'max': 5.0, 'size': 1, 'sigma': 0.1, 'loc': 4.0, 'scale': 0.1},\n        #'tau_ei_v': {'min': 0.5, 'max': 1.0, 'size': 2, 'sigma': 0.1, 'loc': 1.0, 'scale': 0.2},\n        # 'tau_ie': {'min': 2.0, 'max': 4.0, 'size': 1, 'sigma': 0.1, 'loc': 3.0, 'scale': 0.1},\n        #'tau_ie_v': {'min': 0.8, 'max': 1.6, 'size': 2, 'sigma': 0.1, 'loc': 0.7, 'scale': 0.1},\n        #'tau_ii_v': {'min': 0.5, 'max': 1.0, 'size': 2, 'sigma': 0.1, 'loc': 0.5, 'scale': 0.1},\n    }\n\n    param_map = {\n        'k_ee': {'vars': ['weight'], 'edges': [('stn', 'stn')]},\n        'k_ae': {'vars': ['weight'], 'edges': [('stn', 'gpe_a')]},\n        'k_pe': {'vars': ['weight'], 'edges': [('stn', 'gpe_p')]},\n        'k_pp': {'vars': ['weight'], 'edges': [('gpe_p', 'gpe_p')]},\n        'k_ep': {'vars': ['weight'], 'edges': [('gpe_p', 'stn')]},\n        'k_ap': {'vars': ['weight'], 'edges': [('gpe_p', 'gpe_a')]},\n        'k_aa': {'vars': ['weight'], 'edges': [('gpe_a', 'gpe_a')]},\n        'k_pa': {'vars': ['weight'], 'edges': [('gpe_a', 'gpe_p')]},\n        'k_fa': {'vars': ['weight'], 'edges': [('gpe_a', 'fsi')]},\n        'k_mm': {'vars': ['weight'], 'edges': [('msn', 'msn')]},\n        'k_am': {'vars': ['weight'], 'edges': [('msn', 'gpe_a')]},\n        'k_pm': {'vars': ['weight'], 'edges': [('msn', 'gpe_p')]},\n        'k_ff': {'vars': ['weight'], 'edges': [('fsi', 'fsi')]},\n        'k_mf': {'vars': ['weight'], 'edges': [('fsi', 'msn')]},\n        'eta_e': {'vars': ['stn_op/eta_e'], 'nodes': ['stn']},\n        'eta_p': {'vars': ['gpe_proto_op/eta_i'], 'nodes': ['gpe_p']},\n        'eta_a': {'vars': ['gpe_arky_op/eta_a'], 'nodes': ['gpe_a']},\n        'eta_m': {'vars': ['str_msn_op/eta_s'], 'nodes': ['msn']},\n        'eta_f': {'vars': ['str_fsi_op/eta_f'], 'nodes': ['fsi']},\n        'delta_e': {'vars': ['stn_op/delta_e'], 'nodes': ['stn']},\n        'delta_p': {'vars': ['gpe_proto_op/delta_i'], 'nodes': ['gpe_p']},\n        'delta_a': {'vars': ['gpe_arky_op/delta_a'], 'nodes': ['gpe_a']},\n        'delta_m': {'vars': ['str_msn_op/delta_s'], 'nodes': ['msn']},\n        'delta_f': {'vars': ['str_fsi_op/delta_f'], 'nodes': ['fsi']},\n        'tau_e': {'vars': ['stn_op/tau_e'], 'nodes': ['stn']},\n        'tau_p': {'vars': ['gpe_proto_op/tau_i'], 'nodes': ['gpe_p']},\n        'tau_a': {'vars': ['gpe_arky_op/tau_a'], 'nodes': ['gpe_a']},\n        'tau_m': {'vars': ['str_msn_op/tau_s'], 'nodes': ['msn']},\n        'tau_f': {'vars': ['str_fsi_op/tau_f'], 'nodes': ['fsi']},\n    }\n\n    T = 2000.\n    dt = 1e-2\n    dts = 1e-1\n    compute_dir = f\"{os.getcwd()}/stn_gpe_str_opt\"\n\n    # perform genetic optimization\n    ga = CustomGOA(fitness_measure=fitness,\n                   gs_config={\n                       'circuit_template': f\"{os.getcwd()}/config/stn_gpe/stn_gpe_str\",\n                       'permute_grid': True,\n                       'param_map': param_map,\n                       'simulation_time': T,\n                       'step_size': dt,\n                       'sampling_step_size': dts,\n                       'inputs': {},\n                       'outputs': {'r_e': \"stn/stn_op/R_e\", 'r_p': 'gpe_p/gpe_proto_op/R_i',\n                                   'r_a': 'gpe_a/gpe_arky_op/R_a', 'r_m': 'msn/str_msn_op/R_s',\n                                   'r_f': 'fsi/str_fsi_op/R_f'},\n                       'init_kwargs': {'backend': 'numpy', 'solver': 'scipy', 'step_size': dt},\n                   },\n                   cgs_config={'nodes': [\n                       'carpenters',\n                       'osttimor',\n                       'spanien',\n                       'animals',\n                       'kongo',\n                       'tschad',\n                       #'uganda',\n                       # 'tiber',\n                       #'giraffe',\n                       'lech',\n                       'rilke',\n                       'dinkel',\n                       #'rosmarin',\n                       #'mosambik',\n                       # 'comps06h01',\n                       # 'comps06h02',\n                       # 'comps06h03',\n                       # 'comps06h04',\n                       # 'comps06h05',\n                       # 'comps06h06',\n                       # 'comps06h07',\n                       # 'comps06h08',\n                       # 'comps06h09',\n                       # 'comps06h10',\n                       # 'comps06h11',\n                       # 'comps06h12',\n                       # 'comps06h13',\n                       # 'comps06h14',\n                       # 'scorpions',\n                       # 'spliff',\n                       # 'supertramp',\n                       # 'ufo'\n                   ],\n                       'compute_dir': compute_dir,\n                       'worker_file': f'{os.getcwd()}/stn_gpe_str_worker.py',\n                       'worker_env': \"/data/u_rgast_software/anaconda3/envs/pyrates/bin/python3\",\n                   })\n\n    drop_save_dir = f'{compute_dir}/PopulationDrops/'\n    os.makedirs(drop_save_dir, exist_ok=True)\n\n    winner = ga.run(\n        initial_gene_pool=pop_genes,\n        gene_sampling_func=np.random.normal,\n        new_member_sampling_func=np.random.normal,\n        target=[[20, 60, 20, 2, 20],  # healthy control\n                [np.nan, 2/3, np.nan, np.nan, np.nan],  # ampa blockade in GPe\n                [np.nan, 1, np.nan, np.nan, np.nan],  # ampa and gabaa blockade in GPe\n                [np.nan, 2, np.nan, np.nan, np.nan],  # GABAA blockade in GPe\n                [np.nan, 1/2, np.nan, np.nan, np.nan],  # STN blockade\n                [2, 2, np.nan, np.nan, np.nan],  # GABAA blockade in STN\n                ],\n        max_iter=100,\n        enforce_max_iter=True,\n        min_fit=1.0,\n        n_winners=10,\n        n_parent_pairs=40,\n        n_new=62,\n        sigma_adapt=0.05,\n        candidate_save=f'{compute_dir}/GeneticCGSCandidatestn.h5',\n        drop_save=drop_save_dir,\n        new_pop_on_drop=True,\n        pop_save=f'{drop_save_dir}/pop_summary',\n        permute=False\n    )\n\n    # winner.to_hdf(f'{drop_save_dir}/winner.h5', key='data')\n", "meta": {"hexsha": "b135cdee8b5e64770d0efb59d79152c46546ed32", "size": 14060, "ext": "py", "lang": "Python", "max_stars_repo_path": "BasalGanglia/stn_gpe_str_opt.py", "max_stars_repo_name": "Richert/BrainNetworks", "max_stars_repo_head_hexsha": "52119446191dabf0fcef2d3dda203c9fb5730c7d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BasalGanglia/stn_gpe_str_opt.py", "max_issues_repo_name": "Richert/BrainNetworks", "max_issues_repo_head_hexsha": "52119446191dabf0fcef2d3dda203c9fb5730c7d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BasalGanglia/stn_gpe_str_opt.py", "max_forks_repo_name": "Richert/BrainNetworks", "max_forks_repo_head_hexsha": "52119446191dabf0fcef2d3dda203c9fb5730c7d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.9863481229, "max_line_length": 113, "alphanum_fraction": 0.4518492176, "include": true, "reason": "import numpy", "num_tokens": 4757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337582, "lm_q2_score": 0.3174262720448506, "lm_q1q2_score": 0.17722766105953747}}
{"text": "#!/usr/bin/env python\nfrom __future__ import print_function\nimport numpy as np\nfrom cycler import cycler\nimport matplotlib.pyplot as plt\nimport StarKillerMicrophysics as SKM\n\n\nclass BurnerDriver(object):\n    def __init__(self, probin_file):\n        skinit = SKM.Starkiller_Initialization_Module.starkiller_initialize\n        skinit(probin_file)\n\n        self.nspec = SKM.Actual_Network().nspec\n        self.short_species_names = [SKM.Network().get_network_short_species_name(i+1).decode(\"ASCII\").strip().lower() for i in range(self.nspec)]\n        self.species_names = [SKM.Network().get_network_species_name(i+1).decode(\"ASCII\").strip().lower() for i in range(self.nspec)]\n\n        self.history = History()\n        self.plotting = BurnPlotting()\n\n        self.burn_module = SKM.Actual_Burner_Module()\n        self.burn_type_module = SKM.Burn_Type_Module()\n\n        self.eos_module = SKM.Eos_Module()\n        self.eos_type_module = SKM.Eos_Type_Module()\n\n        self.rhs_module = SKM.actual_rhs_module\n\n        self.initial_burn_state = self.burn_type_module.burn_t()\n        self.initial_burn_state.rho = 0.0\n        self.initial_burn_state.t = 0.0\n        self.initial_burn_state.xn = np.zeros(self.nspec, dtype=np.float64)\n\n        self.end_time = 0.0\n        self.num_steps = 0\n        self.dt = 0.0\n\n    def list_species(self):\n        print(\"Species in network:\\n\")\n        for sname, short_sname in zip(self.species_names, self.short_species_names):\n            print(\"{} ({})\".format(sname, short_sname))\n\n    def set_initial_density(self, dens):\n        self.initial_burn_state.rho = dens\n\n    def set_initial_temperature(self, temp):\n        self.initial_burn_state.t = temp\n\n    def set_initial_massfractions(self, xn):\n        self.initial_burn_state.xn = xn[:]\n\n    def set_initial_species(self, species_name, xspec):\n        sname = species_name.lower()\n        idx = -1\n        try:\n            idx = self.short_species_names.index(sname)\n        except ValueError:\n            try:\n                idx = self.species_names.index(sname)\n            except ValueError:\n                print(\"ERROR: species {} is not in this network.\".format(species_name))\n                self.list_species()\n                return\n        self.initial_burn_state.xn[idx] = xspec\n\n    def get_initial_state(self):\n        return self.initial_burn_state\n\n    def burn(self, end_time, num_steps):\n        self.history = History()\n        self.end_time = end_time\n        self.num_steps = num_steps\n        self.dt = self.end_time/self.num_steps\n\n        current_time = 0.0\n\n        state_in = self.burn_type_module.burn_t()\n        state_out = self.burn_type_module.burn_t()\n        \n        self.burn_type_module.copy_burn_t(state_in, self.initial_burn_state)\n        self.burn_type_module.copy_burn_t(state_out, self.initial_burn_state)\n        \n        for istep in range(self.num_steps):\n            self.burn_module.actual_burner(state_in, state_out, self.dt, 0.0)\n            current_time = current_time + self.dt\n            self.history.store(state_out, current_time, self.dt, istep+1)\n            self.burn_type_module.copy_burn_t(state_in, state_out)\n\n        self.plotting.plot_burn_history(self.history)\n\n    def eos(self, input, burn_state):\n        eos_state = self.eos_type_module.eos_t()\n        self.burn_type_module.burn_to_eos(burn_state, eos_state)\n        self.eos_module.eos(input, eos_state)\n        self.burn_type_module.eos_to_burn(eos_state, burn_state)\n\n    def rhs(self, burn_state):\n        # Call the EOS in (r,t) mode and then evaluate the rhs\n        self.eos(self.eos_type_module.eos_input_rt, burn_state)\n        self.rhs_module.actual_rhs(burn_state)\n\n    def jac(self, burn_state):\n        # Call the EOS in (r,t) mode and then evaluate the jacobian\n        self.eos(self.eos_type_module.eos_input_rt, burn_state)\n        self.rhs_module.actual_jac(burn_state)\n\n    def save(self, file_name):\n        self.history.save(self.species_names, self.initial_burn_state, file_name)\n\n    def get_temp_dot(self, burn_state):\n        return burn_state.ydot[-2]\n\n    def get_enuc_dot(self, burn_state):\n        return burn_state.ydot[-1]\n\nclass History(object):\n    def __init__(self):\n        self.nspec = SKM.Actual_Network().nspec\n        self.xn = [[] for i in range(self.nspec)]\n        self.t = []\n        self.edot = []\n        self.time = []\n        self.step = []\n        \n    def append_xn(self, xn):\n        for i, xi in enumerate(xn):\n            self.xn[i].append(xn[i])\n\n    def store(self, state, time, dt, step):\n        self.append_xn(state.xn)\n        self.t.append(state.t)\n        self.edot.append(state.e/dt)\n        self.time.append(time)\n        self.step.append(step)\n\n    def get_save_string(self, step, time, temp, enuc, xn):\n        saveline = \"   \".join([str(step), str(time), str(temp), str(enuc)] + [str(xi) for xi in xn])\n        saveline = saveline + \"\\n\"\n        return saveline\n\n    def get_species_vector(self, ixn):\n        xvec = np.array([xi[ixn] for xi in self.xn])\n        return xvec\n\n    def save(self, spec_names, initial_state, filename):\n        f = open(\"{}.dat\".format(filename), \"w\")\n        spec_names_string = \"   \".join(spec_names)\n        f.write(\"step   time   temperature   enucdot   \" + spec_names_string + \"\\n\")\n        f.write(self.get_save_string(0, 0.0, initial_state.t, 0.0, initial_state.xn))\n        for ii, (istep, itime, itemp, ienuc) in enumerate(zip(self.step, self.time, self.t, self.edot)):\n            xvec = self.get_species_vector(ii)\n            f.write(self.get_save_string(istep, itime, itemp, ienuc, xvec))\n        f.close()\n\n\nclass BurnPlotting(object):\n    def __init__(self):\n        self.nspec = SKM.Actual_Network().nspec\n        self.short_species_names = [SKM.Network().get_network_short_species_name(i+1).decode(\"ASCII\").strip() for i in range(self.nspec)]\n    \n    def rgba_to_hex(self, rgba):\n        r = int(rgba[0]*255.0)\n        g = int(rgba[1]*255.0)\n        b = int(rgba[2]*255.0)\n        return '#{:02X}{:02X}{:02X}'.format(r,g,b)\n\n    def plot_burn_history(self, history, logtime=True):\n        plt.clf()\n        \n        if logtime:\n            xlabel = '$\\mathrm{Log_{10}~Time~(s)}$'\n            xvec = np.log10(history.time)\n            xlim = [np.log10(history.time[0]), np.log10(history.time[-1])]        \n        else:\n            xlabel = '$\\mathrm{Time~(s)}$'\n            xvec = history.time\n            xlim = [history.time[0], history.time[-1]]\n\n        # Get set of colors to use for abundances\n        cm = plt.get_cmap('nipy_spectral')\n        clist = [cm(1.0*i/self.nspec) for i in range(self.nspec)]\n        hexclist = [self.rgba_to_hex(ci) for ci in clist]\n\n        # Get the figure\n        fig = plt.figure()\n        fig.set_figheight(10.0)\n        fig.set_figwidth(5.0)\n\n        # Plot X vs. time    \n        ax = fig.add_subplot(211)\n        ax.set_prop_cycle(cycler('color', hexclist))\n        for i in range(self.nspec):    \n            ax.plot(xvec, np.log10(history.xn[i]), label=self.short_species_names[i])\n        lgd = ax.legend(bbox_to_anchor=(1.15, 1.0), loc=2, borderaxespad=0.0)\n        ax.set_xlim(xlim)\n        plt.setp(ax.get_xticklabels(), visible=False)\n        # plt.xlabel(xlabel)\n        plt.ylabel('$\\mathrm{Log_{10}~X}$')\n\n        # Plot T, edot vs. time\n        # Find where edot = 0\n        def y_where_x_zero(y, x):\n            yzero = []\n            xiszero = False\n            ylo = 0.0\n            for yi, xi in zip(y, x):\n                if xi == 0.0 and not xiszero:\n                    xiszero = True\n                    ylo = yi\n                if xi != 0.0 and xiszero:\n                    xiszero = False\n                    yzero.append([ylo, yi])\n            if xiszero:\n                yzero.append([ylo, y[-1]])\n            return yzero\n\n        edotzero = y_where_x_zero(history.time, history.edot)\n        axe = fig.add_subplot(212)\n        axe.plot(xvec, np.log10(history.t), label='Temperature', color='red')\n        lgd1 = axe.legend(bbox_to_anchor=(0.3, 1.02, 0.7, 1.02), loc='lower left',\n                          ncol=1, mode='expand', borderaxespad=0.0)\n        axe.set_xlabel(xlabel)\n        axe.set_ylabel('$\\mathrm{Log_{10}~T~(K)}$')\n        axe.set_xlim(xlim)\n        ax2 = axe.twinx()\n        ax2.plot(xvec, np.log10(history.edot), label='E Gen Rate', color='blue')\n        ax2.set_ylabel('$\\mathrm{Log_{10}~\\\\dot{e}~(erg/g/s)}$')\n        ax2.set_xlim(xlim)\n        lgd2 = ax2.legend(bbox_to_anchor=(0.7, 1.02, 1.0, 1.02), loc='lower left',\n                          ncol=1, borderaxespad=0.0)\n        # hatch where edot=0\n        for edz in edotzero:\n            plt.axvspan(np.log10(edz[0]), np.log10(edz[1]), color='blue', fill=False,\n                        linewidth=0, hatch='/', alpha=0.2)\n\n        plt.savefig('burn.eps',\n                    bbox_extra_artists=(lgd, lgd1, lgd2,), bbox_inches='tight')\n        plt.savefig('burn.png', dpi=300,\n                    bbox_extra_artists=(lgd, lgd1, lgd2,), bbox_inches='tight')\n\n        plt.show()        \n", "meta": {"hexsha": "1ec8deed247daa299bfbdc0f26b8b8bdb0a77070", "size": 9045, "ext": "py", "lang": "Python", "max_stars_repo_path": "unit_test/burn_cell_python/BurnUtils.py", "max_stars_repo_name": "yut23/Microphysics", "max_stars_repo_head_hexsha": "3c4985213c5e5b1ad2602b0bba2ce164b847361a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-08-17T11:12:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T23:11:08.000Z", "max_issues_repo_path": "unit_test/burn_cell_python/BurnUtils.py", "max_issues_repo_name": "Youhichka/Microphysics", "max_issues_repo_head_hexsha": "6f28333d40c9e15fdfbb1c4dc208e887fb5549c3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 533, "max_issues_repo_issues_event_min_datetime": "2017-06-08T13:52:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T16:13:29.000Z", "max_forks_repo_path": "unit_test/burn_cell_python/BurnUtils.py", "max_forks_repo_name": "Youhichka/Microphysics", "max_forks_repo_head_hexsha": "6f28333d40c9e15fdfbb1c4dc208e887fb5549c3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 34, "max_forks_repo_forks_event_min_datetime": "2017-08-16T16:29:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T16:19:15.000Z", "avg_line_length": 37.3760330579, "max_line_length": 145, "alphanum_fraction": 0.6011055832, "include": true, "reason": "import numpy", "num_tokens": 2422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.17722765639388435}}
{"text": "#!/usr/bin/env python\n\n\"\"\" A set of tools for modelling the antenna reponse and for callibrating the amplitude vs frequency of the antennas\nbased on pyCRtools. see Schellart et al. Detecting cosmic rays with the LOFAR radio telescope,  and Nelles et al. Calibrating the absolute amplitude scale for air showers measured at LOFAR\n\nNote: LBA_ant_calibrator still needs some work.\n\nauthor: Brian hare\n\"\"\"\n\n##internal\nimport glob\nfrom pickle import load\nimport datetime\n\n##external \nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy.interpolate import interp1d\nfrom scipy.interpolate import RegularGridInterpolator, pchip_interpolate\nfrom scipy.io import loadmat\n\n\n\n##mine\nfrom LoLIM.utilities import processed_data_dir, MetaData_directory, RTD, SId_to_Sname, v_air\nimport LoLIM.transmogrify as tmf\nimport LoLIM.IO.metadata as md\n\n\n\n## psuedo-code example use of calibrator\n# AC = ant_calibrator( \"D20160712T173455.100Z\" )\n#\n# AC.FFT_prep( antenna_name, even_antenna_data,  odd_antnna_data ) ## note that ant_calibrator can be re-used for multiple data sets\n# AC.apply_GalaxyCal()  ## this applies the relative callibration, and corrects for defficencies in the antenna model\n# AC.unravelAntennaResponce(azimuth_degrees, elivation_degrees) # apply antenna model. Is better to NOT do this, and to apply anntenna model to E-field model instead\n# out_1, out_2 = AC.get_result() ## out_1 is zenith component, out_2 is azimuthal component (if unravelAntennaResponce was called,  else is still even and odd antennas)\n# out_1_hilbertEnvelope = np.abs( out_1 ) ## apply_GalaxyCal automatically applies a hilbert transform\n# out_1_reals = np.real( out_1 )\n\n\n#### TODO: imporve this so that it has a workspace for N frequencies, so that it doesn't have to allocate memory every call\n## make it automatic so that subsequent calls use same internal memeory if lenght is same (but output doesn't share memory....)\nclass LBA_antenna_model:\n    \"\"\"a class encapsulating the antenna model for the Low Band Antennas.\"\"\"\n    \n    def __init__(self):\n        voltage_theta = np.loadtxt(MetaData_directory+\"/lofar/antenna_response_model/LBA_Vout_theta.txt\", skiprows=1)\n        voltage_phi   = np.loadtxt(MetaData_directory+\"/lofar/antenna_response_model/LBA_Vout_phi.txt\", skiprows=1)\n\n        voltage_theta_responce = voltage_theta[:, 3] + 1j*voltage_theta[:, 4]\n        voltage_phi_responce = voltage_phi[:, 3] + 1j*voltage_phi[:, 4]\n        \n        freq_start = 10.0 * 1.e6\n        freq_step = 1.0 * 1.e6\n        num_freq = 101\n        \n        theta_start = 0.0\n        theta_step = 5.0\n        num_theta = 19\n        \n        phi_start = 0.0\n        phi_step = 10.0\n        num_phi = 37\n        \n        frequency_samples = np.arange(num_freq)*freq_step + freq_start\n        theta_samples = np.arange(num_theta)*theta_step + theta_start\n        phi_samples = np.arange(num_phi)*phi_step + phi_start\n        \n        voltage_theta_responce = voltage_theta_responce.reshape( (num_freq, num_theta, num_phi) )\n        voltage_phi_responce = voltage_phi_responce.reshape( (num_freq, num_theta, num_phi) )\n        \n        self.theta_responce_interpolant = RegularGridInterpolator((frequency_samples, theta_samples, phi_samples),   voltage_theta_responce)\n        self.phi_responce_interpolant =   RegularGridInterpolator((frequency_samples, theta_samples, phi_samples),   voltage_phi_responce)\n        \n    def JonesMatrix(self, frequency, zenith, azimuth):\n        \"\"\"return the Jones Matrix for a single frequency (in Hz), for a wave with a zenith and azimuth angle in degrees. Dot the jones matrix with the electric field vector, first component of vector is Zenith component of \n        electric field and second component is azimuthal electric field, then the first component of the resulting vector will be voltage on odd  (X) antenna and second component will be voltage on even (Y) antenna.\n        Returns identity matrix where frequency is outside of 10 to 100 MHz\"\"\"\n    \n        jones_matrix = np.zeros( (2,2), dtype=complex )\n        \n        if frequency < 10.0E6 or frequency>100.0E6: ##if frequency is outside of range, then return some invertable nonsense\n            jones_matrix[0,0] = 1.0\n            jones_matrix[1,1] = 1.0\n            return jones_matrix\n        \n        ## calculate for X dipole\n        azimuth += 135 # put azimuth in coordinates of the X antenna\n        while azimuth > 360: ## normalize the azimuthal angle\n            azimuth -= 360\n        while azimuth < 0:\n            azimuth += 360\n            \n        jones_matrix[0, 0] = self.theta_responce_interpolant(  [frequency, zenith, azimuth] )\n        jones_matrix[0, 1] = -1*self.phi_responce_interpolant( [frequency, zenith, azimuth] ) ## I don't really know why this -1 must be here\n        \n        ## calculate for Y dipole\n        azimuth += 90.0 # put azimuth in coordinates of the Y antenna\n        while azimuth > 360: ## normalize the azimuthal angle\n            azimuth -= 360\n        while azimuth < 0:\n            azimuth += 360\n        jones_matrix[1, 0] = -1*self.theta_responce_interpolant(  [frequency, zenith, azimuth] ) ## I don't really know why this -1 must be here\n        jones_matrix[1, 1] = self.phi_responce_interpolant( [frequency, zenith, azimuth] )\n        \n        return jones_matrix\n    \n    def JonesMatrix_MultiFreq(self, frequencies, zenith, azimuth, out=None):\n        \"\"\"same as JonesMatrix, except that frequencies is expected to be an array. Returns an array of jones matrices\"\"\"\n        \n        if out is None:\n            out_JM = np.zeros( (len(frequencies), 2,2), dtype=complex )\n        else:\n            out_JM = out\n        \n        good_frequencies = np.logical_and( frequencies>10.0E6, frequencies<100E6)\n        num_freqs = np.sum( good_frequencies )\n        \n        points = np.zeros( (num_freqs, 3) ) ## figure out how to not need this\n        points[:, 0] = frequencies[ good_frequencies ]\n        points[:, 1] = zenith\n        \n        ## calculate for X dipole\n        points[:, 2] = azimuth + 135 # put azimuth in coordinates of the X antenna\n        while np.any( points[:, 2] > 360 ): ## normalize the azimuthal angle\n            points[:, 2] [ points[:, 2]>360 ] -= 360\n        while np.any( points[:, 2] <0 ): \n            points[:, 2] [ points[:, 2]<0 ] += 360\n            \n        out_JM[good_frequencies, 0, 0] = self.theta_responce_interpolant( points )\n        out_JM[good_frequencies, 0, 1] = -1*self.phi_responce_interpolant( points )\n        \n        ## calculate for Y dipole\n        points[:, 2] += 90.0 # put azimuth in coordinates of the Y antenna\n        while np.any( points[:, 2] > 360 ): ## normalize the azimuthal angle\n            points[:, 2] [ points[:, 2]>360 ] -= 360\n        while np.any( points[:, 2] <0 ): \n            points[:, 2] [ points[:, 2]<0 ] += 360\n            \n        out_JM[good_frequencies, 1, 0] = -1*self.theta_responce_interpolant( points )\n        out_JM[good_frequencies, 1, 1] = self.phi_responce_interpolant( points )\n        \n        ## set the frequencies outide 10 to 100 MHz to just identity matix\n        out_JM[ np.logical_not(good_frequencies), 0, 0] = 1.0\n        out_JM[ np.logical_not(good_frequencies), 1, 1] = 1.0\n        \n#        fi = np.argmin( np.abs(frequencies-60.0E6) )\n        \n        return out_JM\n  \n\n\n        \n    \n        \n    \ndef get_LBA_frequency_calibration(frequencies, fill=0.0):\n    \"\"\" given a set of frequencies, in units of Hz, return the antenna callibration\"\"\"\n    \n    Calibration_curve = np.zeros(101)\n    \n#    Calibration_curve[29:82] = np.array([0,  1.09124663e-06,   1.11049910e-06,   1.11101995e-06,\n#                 1.14234774e-06,   1.15149299e-06,   1.17121699e-06,\n#                 1.18578121e-06,   1.19696124e-06,   1.20458122e-06,\n#                 1.24675978e-06,   1.27966600e-06,   1.32418333e-06,\n#                 1.32115453e-06,   1.33871075e-06,   1.34295545e-06,\n#                 1.34157430e-06,   1.37660390e-06,   1.39226359e-06,\n#                 1.39827006e-06,   1.51409426e-06,   1.61610247e-06,\n#                 1.74643510e-06,   1.74588169e-06,   1.73061463e-06,\n#                 1.69229172e-06,   1.64633321e-06,   1.60982965e-06,\n#                 1.59572009e-06,   1.64618678e-06,   1.81628916e-06,\n#                 2.09520281e-06,   2.17610590e-06,   2.20907337e-06,\n#                 2.12050148e-06,   2.04923844e-06,   2.06549879e-06,\n#                 2.24906987e-06,   2.40356459e-06,   2.52199062e-06,\n#                 2.48380048e-06,   2.40835417e-06,   2.38248922e-06,\n#                 2.48599834e-06,   2.60617662e-06,   2.66466169e-06,\n#                 2.78010597e-06,   2.90548503e-06,   3.08686745e-06,\n#                 3.26101312e-06,   3.50261561e-06,   3.74739666e-06, 0])  \n    \n#    Calibration_curve[29:82] = np.array([0,  \n#         5.17441583458e-07,  5.26112551988e-07,   5.54435685779e-07,\n#         5.85016839251e-07,  6.10870583894e-07,   6.47309035485e-07,\n#         6.5091456311e-07,   6.92446769829e-07,   7.24758841756e-07,\n#         7.68263947385e-07,  7.91148165708e-07,   8.40734630391e-07,\n#         8.43296509798e-07,  8.9313176062e-07,    9.2381731899e-07,\n#         9.49238145305e-07,  9.75552986024e-07,   9.90712789075e-07,\n#         1.05134677402e-06,  1.07555421962e-06,   1.09540733982e-06,\n#         1.11101225721e-06,  1.13901998747e-06,   1.20840289547e-06,\n#         1.25099501879e-06,  1.28820016316e-06,   1.42132795525e-06,\n#         1.58730515709e-06,  1.69274022328e-06,   1.79771448679e-06,\n#         1.69009894816e-06,  1.59916753151e-06,   1.52598688512e-06,\n#         1.35488689628e-06,  1.25281147938e-06,   1.25843707081e-06,\n#         1.28115364631e-06,  1.29327138907e-06,   1.30804348155e-06,\n#         1.30108509354e-06,  1.30377069039e-06,   1.30654052835e-06,\n#         1.30565358077e-06,  1.31712312807e-06,   1.31343342371e-06,\n#         1.32267337872e-06,  1.33943924503e-06,   1.36389183621e-06,\n#         1.4202852471e-06,   1.45672364953e-06,   1.5184892913e-06, 0])\n    \n    Calibration_curve[29:82] = np.array([fill, 1.37321451961e-05,\n                                             1.39846332239e-05,\n                                             1.48748993821e-05,\n                                             1.54402170354e-05,\n                                             1.60684568225e-05,\n                                             1.66241942741e-05,\n                                             1.67039066047e-05,\n                                             1.74480931848e-05,\n                                             1.80525736486e-05,\n                                             1.87066855054e-05,\n                                             1.88519099831e-05,\n                                             1.99625051386e-05,\n                                             2.01878566584e-05,\n                                             2.11573680797e-05,\n                                             2.15829455528e-05,\n                                             2.20133824866e-05,\n                                             2.23736319125e-05,\n                                             2.24484419697e-05,\n                                             2.37802483891e-05,\n                                             2.40581543111e-05,\n                                             2.42020383477e-05,\n                                             2.45305869187e-05,\n                                             2.49399905965e-05,\n                                             2.63774023804e-05,\n                                             2.70334253414e-05,\n                                             2.78034857678e-05,\n                                             3.07147991391e-05,\n                                             3.40755705892e-05,\n                                             3.67311849851e-05,\n                                             3.89987440028e-05,\n                                             3.72257913465e-05,\n                                             3.54293510934e-05,\n                                             3.35552370942e-05,\n                                             2.96529815929e-05,\n                                             2.79271252352e-05,\n                                             2.8818544973e-05,\n                                             2.92478843809e-05,\n                                             2.98454768706e-05,\n                                             3.07045462103e-05,\n                                             3.07210553534e-05,\n                                             3.16442871206e-05,\n                                             3.2304638838e-05,\n                                             3.33203882046e-05,\n                                             3.46651060935e-05,\n                                             3.55193137077e-05,\n                                             3.73919275937e-05,\n                                             3.97397037914e-05,\n                                             4.30625048727e-05,\n                                             4.74612081994e-05,\n                                             5.02345866124e-05,\n                                             5.53621848304e-05, fill])\n\n    Calibration_curve_interp = interp1d(np.linspace(0.e6,100e6,101), Calibration_curve, kind='linear', bounds_error=False, fill_value=fill)\n    return Calibration_curve_interp( frequencies )\n    \n            \ndef invert_2X2_matrix_list( matrices ):\n    \"\"\" if matrices is an array of 2x2 matrices, then return the array of inverse matrices \"\"\"\n    num = len(matrices)\n    out = np.zeros( (num, 2,2), dtype=matrices.dtype)\n    \n    out[:, 0,0] = matrices[:, 1,1]\n    out[:, 0,1] = -matrices[:, 0,1]\n    out[:, 1,0] = -matrices[:, 1,0]\n    out[:, 1,1] = matrices[:, 0,0]\n    \n    determinants = matrices[:, 0,0]*matrices[:, 1,1] - matrices[:, 0,1]*matrices[:, 1,0]\n    \n    out /= determinants[:, np.newaxis, np.newaxis]\n    \n    return out\n\ndef fourier_series( x, p):\n    \"\"\"Evaluates a partial Fourier series\n\n        F(x) \\\\approx \\\\frac{a_{0}}{2} + \\\\sum_{n=1}^{\\\\mathrm{order}} a_{n} \\\\sin(nx) + b_{n} \\\\cos(nx)\n    \"\"\"\n\n    r = p[0] / 2\n\n    order = int( (len(p) - 1) / 2 )\n\n    for i in range(order):\n\n        n = i + 1\n\n        r += p[2*i + 1] * np.sin(n * x) + p[2*i + 2] * np.cos(n * x)\n\n    return r\n\ndef getGalaxyCalibrationData(antenna_noise_power, timestamp, channel_width, antenna_type=\"outer\"):\n    \"\"\"return factor to correct for amplitude shifts. Essenturally returns sqrt( P_{expected} / P_{measured} ). Where P is noise power. \n    for antenna_type outer it returns factor for Y/X dipoles, for \"inner\" returns \"X/Y\". antenna_noise_power is an array of measured powers for each antenna. \n    Even/odd indecies should be Y/X dipole for outer and oppisite for inner.\n    timestamp should be posix timestamp\"\"\"\n    \n    \n    longitude = 6.869837540/RTD\n    \n    ## this is in outer order:  Y,X\n    coefficients_lba = [ np.array([ 0.01489468, -0.00129305,  0.00089477, -0.00020722, -0.00046507]),   ## for Y antennas\n                         np.array([ 0.01347391, -0.00088765,  0.00059822,  0.00011678, -0.00039787])  ] ## for X antennas\n\n    \n    \n    # Convert timestamp to datetime object\n    t = datetime.datetime.utcfromtimestamp(timestamp)\n    # Calculate JD(UT1)\n    ut = tmf.gregorian2jd(t.year, t.month, float(t.day) + ((float(t.hour) + float(t.minute) / 60. + float(t.second) / 3600.) / 24.))\n    # Calculate JD(TT)\n    dtt = tmf.delta_tt_utc(tmf.date2jd(t.year, t.month, float(t.day) + ((float(t.hour) + float(t.minute) / 60. + float(t.second) / 3600.) / 24.)))\n    tt = tmf.gregorian2jd(t.year, t.month, float(t.day) + ((float(t.hour) + float(t.minute) / 60. + (float(t.second) + dtt / 3600.)) / 24.))\n    # Calculate Local Apparant Sidereal Time\n    last = tmf.rad2circle(tmf.last(ut, tt, longitude))\n\n\n    galactic_noise_power =[  fourier_series(last, coefficients_lba[0]),  fourier_series(last, coefficients_lba[1])  ]\n    \n    antenna_noise_power[ antenna_noise_power==0 ] = np.nan\n    \n    if antenna_type == 'outer':\n        Y_measured_powers = antenna_noise_power[0::2]\n        X_measured_powers = antenna_noise_power[1::2]\n        \n        Y_expected_power = galactic_noise_power[0]\n        X_expected_power = galactic_noise_power[1]\n        \n    else:\n        X_measured_powers = antenna_noise_power[0::2]\n        Y_measured_powers = antenna_noise_power[1::2]\n        \n        X_expected_power = galactic_noise_power[0]\n        Y_expected_power = galactic_noise_power[1]\n    \n    \n    ## note this should make new arrays\n    Y_factors = Y_expected_power * channel_width / Y_measured_powers\n    X_factors = X_expected_power * channel_width / X_measured_powers\n    \n    np.sqrt(Y_factors, out=Y_factors)\n    np.sqrt(X_factors, out=X_factors)\n    \n    if antenna_type == 'outer':\n        return Y_factors, X_factors\n    else:\n        return X_factors, Y_factors\n\n\nclass LBA_ant_calibrator:\n    \"\"\" This is a class for callibrating the LBA antennas and removing the antenna responce function. Only valid between 30 to 80 MHz. NOTE: removing the antenna responce function is ill-conditioned. A better approach is to callibrate the data, \n    then filter a model using the antenna responce. Using this class will inherently do a hilbert transform (negative frequencies will be set to zero)\"\"\"\n    \n    def __init__(self, load_gal_cal=True, timeID=None, findRFI=None, cal_curve=get_LBA_frequency_calibration, jones_matrices=None):\n        \"\"\"if load_gal_cal is true, then timeID and  findRFI should indicate RFI info. If load_gal_cal is false, than data is not normalized relative to noise.\n        cal_curve should take numpy arrays of frequency and return frequency dependant adjustment of the data. can be None.\n        Jones matrices should be a function that has three parameters: 1) numpy array of frequencies in Hz, 2) zenith in degrees, and 3) azimuth in degrees, then returns array of jones matrices. Default is pycrtools model \"\"\"\n        \n        self.cal_curve = cal_curve\n        \n        if load_gal_cal:\n        \n            if findRFI is None:\n                findRFI = \"/findRFI/findRFI_results\"\n                \n            if isinstance(findRFI, str): ## load findRFI data from file\n                galcal_data_loc = processed_data_dir(timeID) + findRFI\n                with open( galcal_data_loc, 'rb' ) as fin:\n                    findRFI = load(fin)\n                    \n            \n            self.calibration_factors = {}\n            for findRFI_info in findRFI.values():\n                antenna_names = findRFI_info[\"antenna_names\"]\n                num_antennas = len( antenna_names )\n                cleaned_power = findRFI_info[\"cleaned_power\"]\n                timestamp = findRFI_info[\"timestamp\"]\n                analyzed_blocksize = findRFI_info[\"blocksize\"]\n                \n                even_cal_factors, odd_cal_factors = getGalaxyCalibrationData(cleaned_power,  timestamp, 5.0E-9/analyzed_blocksize )\n                \n                for ant_i in range(0, int(num_antennas/2)):\n                    ant_name = antenna_names[ ant_i*2 ]\n                    self.calibration_factors[ ant_name ] = (even_cal_factors[ant_i], odd_cal_factors[ant_i])\n        else:\n            self.calibration_factors = None\n            \n        \n        ### Galaxy callibration data ###\n#        self.calibration_factors = {}\n#        galcal_data_loc = processed_data_dir(timeID) + '/cal_tables/galaxy_cal'\n#        galcal_fpaths = glob.glob(galcal_data_loc + '/*.gcal')\n#        for fpath in galcal_fpaths:\n#            with open(fpath, 'rb') as fin:\n#                data = np.load(fin)\n#                ant_names = data[\"arr_0\"].astype(str, copy=False)\n#                factors = data[\"arr_1\"]\n#            ant_i = 0\n#            while ant_i<len(ant_names):\n#                self.calibration_factors[ ant_names[ant_i] ] = [factors[ant_i], factors[ant_i+1]]\n#                ant_i += 2\n                \n        if jones_matrices is None:\n            self.antenna_model = LBA_antenna_model().JonesMatrix_MultiFreq\n        \n    def FFT_prep(self, even_ant_name, even_pol_data, odd_pol_data):\n        \"\"\" prepare to apply callibrations to a pair of dipoles. Essentually just takes FFT. Assume a han window is not needed.\"\"\"\n        \n        if len(even_pol_data) != len(odd_pol_data):\n            raise ValueError('even and odd polarization data need to be same length')\n            \n        self.even_ant_name = even_ant_name\n        self.N_points = len(even_pol_data)\n        \n        ##FFT\n        self.even_pol_FFT = np.fft.fft(even_pol_data)\n        self.odd_pol_FFT =  np.fft.fft(odd_pol_data)\n        \n        ##Frequencies\n        self.frequencies = np.fft.fftfreq(self.N_points, 5.0E-9)\n#    \n    def apply_time_shift(self, even_time_shift, odd_time_shift):\n        \"\"\"apply phase shifts to the data, corresponding to an amount of time (in seconds)\"\"\"\n        self.even_pol_FFT *= np.exp( self.frequencies*(-1j*2*np.pi*even_time_shift) )\n        self.odd_pol_FFT *= np.exp( self.frequencies*(-1j*2*np.pi*odd_time_shift) )\n        \n    def apply_GalaxyCal(self):\n        \"\"\"applies the galaxy calibration to this data. Can be applied independantly of unravelAntennaResponce. Negative frequencies are set to zero.\"\"\"\n        \n        ### first we apply the correction factors ###\n        if self.calibration_factors is not None:\n            PolE_factor, PolO_factor = self.calibration_factors[self.even_ant_name]\n    \n            self.even_pol_FFT *= PolE_factor\n            self.odd_pol_FFT  *= PolO_factor\n        else:\n             PolE_factor = 1.0\n             PolO_factor = 1.0\n        \n        if self.cal_curve is not None: \n            ## callibration curve to correct for frequency dependent model defeciencies \n            Calibration_curve_interp = get_LBA_frequency_calibration( self.frequencies )\n            \n            self.even_pol_FFT *= Calibration_curve_interp\n            self.odd_pol_FFT  *= Calibration_curve_interp\n\n        return [PolE_factor, PolO_factor]\n        \n    def unravelAntennaResponce(self, zenith, azimuth):\n        \"\"\"given a direction to source (azimuth off X and zenith from Z, in degrees ), if call this function, then apply_GalaxyCal MUST also be applied to the data\n        Note that this function assumes the data is LBA_outer, which has flipped polarizations compared to LBA inner\"\"\"\n        \n        jones_matrices = self.antenna_model(self.frequencies, zenith, azimuth)\n        \n        inverse_jones_matrix = invert_2X2_matrix_list( jones_matrices )\n        \n        ### apply the Jones matrix.  Note that the polarities (even and odd) are flipped)\n        zenith_component = self.odd_pol_FFT*inverse_jones_matrix[:, 0,0] +  self.even_pol_FFT*inverse_jones_matrix[:, 0,1]\n        azimuth_component = self.odd_pol_FFT*inverse_jones_matrix[:, 1,0] +  self.even_pol_FFT*inverse_jones_matrix[:, 1,1]\n        \n        self.even_pol_FFT = zenith_component\n        self.odd_pol_FFT = azimuth_component\n        \n    def getResult(self):\n        \"\"\"get the results of analysis. Essentially preforms inverse FFT. \n        If unravelAntennaResponce was called, first return is zenith component, second is azimuthal. Else first return is even polarization, second is odd\"\"\"\n        \n        return np.fft.ifft(self.even_pol_FFT),    np.fft.ifft(self.odd_pol_FFT)\n        \n    \n    \n    \n        \ndef plot_responce():\n    N_azimuth = 100\n    N_zenith = 500\n    frequency = 58.0E6\n    \n    zeniths = np.linspace( 0, 90, N_zenith)\n    azimuths = np.linspace( 0, 360, N_azimuth )\n    \n    resulting_grid = np.zeros((N_zenith, N_azimuth))\n    AM = LBA_antenna_model()\n#    AM = pycrtools_antenna_model()\n    \n    for ze_i in range(N_zenith):\n        print(ze_i, '/', N_zenith)\n        for az_i in range(N_azimuth):\n            \n            JM = AM.JonesMatrix(frequency, zeniths[ze_i], azimuths[az_i])\n            resulting_grid[ze_i, az_i] = np.abs( JM[0,0] )\n            \n    plt.imshow(resulting_grid)\n    plt.show()\n        \n        \nif __name__ == \"__main__\":\n    # frequencies_MHz = np.linspace(0.0, 100.0, 10000)\n    \n    AM = LBA_antenna_model()\n    # matrix = AM.JonesMatrix_MultiFreq(frequencies_MHz*1E6, 0.0, 0.0)\n    \n    # plt.semilogy(frequencies_MHz, np.abs(matrix[:, 0,0]), linewidth=7 )\n    # plt.show()\n    \n    \n    elivations = np.linspace(0.5,15,100)\n    \n    responses = []\n    for e in elivations:\n        M = AM.JonesMatrix(60e6, 90-e, 0)\n        responses.append(np.abs(M[0,0]))\n        \n    plt.plot( elivations, responses )\n    plt.show()\n    \n    \n        \n\n", "meta": {"hexsha": "8e548b322e6140bc88cf21fc53b562853f3fe19e", "size": 24656, "ext": "py", "lang": "Python", "max_stars_repo_path": "LIM_scripts/old_antenna_response.py", "max_stars_repo_name": "Bhare8972/LOFAR-LIM", "max_stars_repo_head_hexsha": "89f25be8c02cb8980c2e237da3eaac279d40a06a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-04-21T13:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-15T12:44:23.000Z", "max_issues_repo_path": "LIM_scripts/old_antenna_response.py", "max_issues_repo_name": "Bhare8972/LOFAR-LIM", "max_issues_repo_head_hexsha": "89f25be8c02cb8980c2e237da3eaac279d40a06a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LIM_scripts/old_antenna_response.py", "max_forks_repo_name": "Bhare8972/LOFAR-LIM", "max_forks_repo_head_hexsha": "89f25be8c02cb8980c2e237da3eaac279d40a06a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-11-06T18:34:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-04T14:16:57.000Z", "avg_line_length": 47.506743738, "max_line_length": 245, "alphanum_fraction": 0.5850908501, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3174262720448507, "lm_q1q2_score": 0.17722765639388435}}
{"text": "# Copyright 2018 The Cirq Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Wavefunction simulator specialized to Google's xmon gate set.\n\nThis class should not be used directly, see instead XmonSimulator in the\nxmon_simulator class.\n\"\"\"\n\nimport math\nimport multiprocessing\nimport multiprocessing.dummy as dummy\n\nfrom typing import Any, Dict, List, Union, Tuple\n\nimport numpy as np\n\nfrom cirq.google.sim import mem_manager\n\n\nI_PI_OVER_2 = 0.5j * np.pi\n\n\ndef ensure_pool(func):\n    \"\"\"Decorator that ensures a pool is available for a stepper.\"\"\"\n    def func_wrapper(*args, **kwargs):\n        if len(args) == 0 or not isinstance(args[0], Stepper):\n            raise Exception('@ensure_pool can only be used on Stepper methods.')\n        if args[0]._pool is None:\n            with args[0]:\n                return func(*args, **kwargs)\n        else:\n            return func(*args, **kwargs)\n    return func_wrapper\n\n\nclass Stepper(object):\n    \"\"\"A wave function simulator for quantum circuits with the xmon gate set.\n\n    Xmons have a natural gate set made up of\n\n    * Single qubit phase gates, exp(-i t Z)\n    * Single qubit gates about a operation in the Pauli X/Y plane,\n      exp(-i t (cos(theta) X + sin(theta) Y)\n    * Two qubit phase gates exp(i t |11><11|)\n\n    This stepper will do sharded simulation of the wave function using\n    python's multiprocessing module.\n\n    This stepper can be used like a context manager:\n        with Stepper(num_qubits=3) as s:\n            s.simulate_phases((1, 0.25))\n            s.simulate_w(2, 0.25, 0.25)\n            ...\n    In this case the stepper will shut down the multiprocessing pool upon\n    exiting the with context.\n\n    If the  stepper is not used as a context manager, then it is required that\n    __exit__ be called in order to ensure that the multiprocessing pool is\n    properly closed (__enter__ does not need to be called).\n    \"\"\"\n\n    def __init__(self,\n                 num_qubits: int,\n                 num_prefix_qubits: int = None,\n                 initial_state: Union[int, np.ndarray] = 0,\n                 min_qubits_before_shard: int = 18,\n                 use_processes=False) -> None:\n        \"\"\"Construct a new XmonSimulator.\n\n        Args:\n          num_qubits: The number of qubits to simulate.\n          num_prefix_qubits: The wavefunction of the qubits is sharded into\n              (2 ** num_prefix_qubits) parts. If this is None, then this will\n              shard over the nearest power of two below the cpu count. If less\n              than 10 qubits are being simulated then no sharding is done,\n              depending on whether the shard_for_small_num_qubits is set or\n              not.\n          initial_state: If this is an int, then this is the state to\n              initialize the stepper to, expressed as an integer of the\n              computational basis. The 1s bit of the integer determines the\n              values of the last qubit, the 2s bit determines the value of the\n              second-to-last-qubit, and so forth. This sounds odd, but it\n              matches how people write numbers: the smallest value digit goes\n              last.\n              Otherwise, if this is a np.ndarray it is the full initial state\n              and this must be the correct size, normalized (an L2 norm of 1),\n              and have dtype of np.complex64. An array with zeroes everywhere,\n              except for a 1 at index k, is equivalent to state prepared when\n              the initial state is set to the integer k.\n          min_qubits_before_shard: Sharding will be done only for this number\n              of qubits or more. The default is 18.\n          use_processes: Whether or not to use processes instead of threads.\n              Processes can improve the performance slightly (varies by machine\n              but on the order of 10 percent faster).  However this varies\n              significantly by architecture, and processes should not be used\n              for interactive python use on Windows.\n        \"\"\"\n        self._num_qubits = num_qubits\n        if num_prefix_qubits is None:\n            num_prefix_qubits = int(math.log(multiprocessing.cpu_count(), 2))\n        if num_prefix_qubits > num_qubits:\n            num_prefix_qubits = num_qubits\n        if num_qubits < min_qubits_before_shard:\n            num_prefix_qubits = 0\n        self._num_prefix_qubits = num_prefix_qubits\n        # Each shard is of a dimension equal to 2 ** num_shard_qubits.\n        self._num_shard_qubits = self._num_qubits - self._num_prefix_qubits\n\n        self._num_shards = 2 ** self._num_prefix_qubits\n        self._shard_size = 2 ** self._num_shard_qubits\n\n        # TODO(dabacon): This could be parallelized.\n        self._init_shared_mem(initial_state)\n        self._pool = None  # type: Union[ThreadlessPool, Any]\n        self._pool_fn = multiprocessing.Pool if use_processes else dummy.Pool\n\n    def _init_shared_mem(self, initial_state: int):\n        self._shared_mem_dict = {}  # type: Dict[str, int]\n        self.init_z_vects()\n        self._init_scratch()\n        self._init_state(initial_state)\n\n    def init_z_vects(self):\n        \"\"\"Initializes bitwise vectors which is precomputed in shared memory.\n\n        There are two types of vectors here, a zero one vectors and a pm\n        (plus/minus) vectors. The pm vectors have rows that are Pauli Z\n        operators acting on the all ones vector. The column-th row corresponds\n        to the Pauli Z acting on the column'th-qubit.  Example for three shard\n        qubits:\n             [[1, -1, 1, -1, 1, -1, 1, -1],\n              [1, 1, -1, -1, 1, 1, -1, -1],\n              [1, 1, 1, 1, -1, -1, -1, -1]]\n        The zero one vectors are the pm vectors with 1 replacing -1 and 0\n        replacing 1.\n\n        There are number of shard qubit zero one vectors and each of these is\n        of size equal to the shard size. For the zero one vectors, the ith one\n        of these vectors has a  kth index value that is equal to 1 if the i'th\n        bit of k is set and zero otherwise. The vector directly encode the\n        little-endian binary digits of its index in the list:\n        v[j][i] = (i >> j) & 1. For the pm vectors, the ith one of these\n        vectors has a  k'th index value that is equal to -1 if the i'th bit of\n        k is set and 1 otherwise.\n        \"\"\"\n        shard_size = 2 ** self._num_shard_qubits\n\n        a, b = np.indices((shard_size, self._num_shard_qubits))\n        a >>= b\n        a &= 1\n        zero_one_vects = np.ascontiguousarray(a.transpose())\n        zero_one_vects_handle = mem_manager.SharedMemManager.create_array(\n            zero_one_vects)\n        self._shared_mem_dict['zero_one_vects_handle'] = zero_one_vects_handle\n\n        pm_vects = 1 - 2 * zero_one_vects\n        pm_vects_handle = mem_manager.SharedMemManager.create_array(pm_vects)\n        self._shared_mem_dict['pm_vects_handle'] = pm_vects_handle\n\n    def _init_scratch(self):\n        \"\"\"Initializes a scratch pad equal in size to the wavefunction.\"\"\"\n        scratch = np.zeros((self._num_shards, self._shard_size),\n                           dtype=np.complex64)\n        scratch_handle = mem_manager.SharedMemManager.create_array(\n            scratch.view(dtype=np.float32))\n        self._shared_mem_dict['scratch_handle'] = scratch_handle\n\n    def _init_state(self, initial_state: Union[int, np.ndarray]):\n        \"\"\"Initializes a the shard wavefunction and sets the initial state.\"\"\"\n        state = np.reshape(\n            decode_initial_state(initial_state, self._num_qubits),\n            (self._num_shards, self._shard_size))\n        state_handle = mem_manager.SharedMemManager.create_array(\n            state.view(dtype=np.float32))\n        self._shared_mem_dict['state_handle'] = state_handle\n\n    def __del__(self):\n        for handle in self._shared_mem_dict.values():\n            mem_manager.SharedMemManager.free_array(handle)\n\n    def __enter__(self):\n        if self._pool is None:\n            self._pool = (self._pool_fn(processes=self._num_shards)\n                          if self._num_prefix_qubits > 0 else ThreadlessPool())\n        return self\n\n    def __exit__(self, *args):\n        # Terminate is safe here since all work should have been completed.\n        if self._pool is not None:\n            self._pool.terminate()\n            self._pool.join()\n            self._pool = None\n\n\n    def _shard_num_args(self,\n                        constant_dict: Dict[str, Any] = None\n                        ) -> List[Dict[str, Any]]:\n        \"\"\"Helper that returns a list of dicts including a num_shard entry.\n\n        The dict for each entry also includes shared_mem_dict, the number of\n        shards, the number of shard qubits, and the supplied constant dict.\n\n        Args:\n            constant_dict: Dictionary that will be updated to every element of\n                the returned list of dictionaries.\n\n        Returns:\n            A list of dictionaries. Each dictionary is constant except for the\n            'shard_num' key which ranges from 0 to number of shards - 1.\n            Included keys are 'num_shards' and 'num_shard_qubits' along with\n            all the keys in constant_dict.\n        \"\"\"\n        args = []\n        for shard_num in range(self._num_shards):\n            append_dict = dict(constant_dict) if constant_dict else {}\n            append_dict['shard_num'] = shard_num\n            append_dict['num_shards'] = self._num_shards\n            append_dict['num_shard_qubits'] = self._num_shard_qubits\n            append_dict.update(self._shared_mem_dict)\n            args.append(append_dict)\n        return args\n\n    @property\n    def current_state(self):\n        \"\"\"Returns the current wavefunction.\"\"\"\n        return self._current_state()\n\n    @ensure_pool\n    def _current_state(self):\n        return np.array(\n            self._pool.map(_state_shard, self._shard_num_args())).flatten()\n\n    @ensure_pool\n    def reset_state(self, reset_state):\n        \"\"\"Reset the state to the given initial state.\n\n        Args:\n            reset_state: If this is an int, then this is the state to reset\n                the stepper to, expressed as an integer of the computational\n                basis. Integer to bitwise indices is little endian. Otherwise\n                if this is a np.ndarray this must be the correct size, be\n                normalized (L2 norm of 1), and have dtype of np.complex64.\n\n        Raises:\n            ValueError if the state is incorrectly sized or not of the correct\n            dtype.\n        \"\"\"\n        # If the pool has been closed, recreate to calculate state.'\n        if isinstance(reset_state, int):\n            self._pool.map(_reset_state,\n                           self._shard_num_args({'reset_state': reset_state}))\n        elif isinstance(reset_state, np.ndarray):\n            check_state(reset_state, self._num_qubits)\n            args = []\n            for kwargs in self._shard_num_args():\n                shard_num = kwargs['shard_num']\n                shard_size = 1 << kwargs['num_shard_qubits']\n                start = shard_num * shard_size\n                end = start + shard_size\n                kwargs['reset_state'] = reset_state[start:end]\n                args.append(kwargs)\n            self._pool.map(_reset_state, args)\n\n\n    @ensure_pool\n    def simulate_phases(self, phase_map: Dict[Tuple[int, ...], float]):\n        \"\"\"Simulate a set of phase gates on the xmon architecture.\n\n        Args:\n            phase_map: A map from a tuple of indices to a value, one for each\n                phase gate being simulated. If the tuple key has one index, then\n                this is a Z phase gate on the index-th qubit with a rotation\n                angle of pi times the value of the map. If the tuple key has two\n                indices, then this is a |11> phasing gate, acting on the qubits\n                at the two indices, and a rotation angle of pi times the value\n                of the map.\n        \"\"\"\n        self._pool.map(_clear_scratch, self._shard_num_args())\n        # Iterate over the map of phase data.\n        for indices, half_turns in phase_map.items():\n            args = self._shard_num_args(\n                {'indices': indices, 'half_turns': half_turns})\n            if len(indices) == 1:\n                self._pool.map(_single_qubit_accumulate_into_scratch, args)\n            elif len(indices) == 2:\n                self._pool.map(_two_qubit_accumulate_into_scratch, args)\n        # Exponentiate the phases and add them into the state.\n        self._pool.map(_apply_scratch_as_phase, self._shard_num_args())\n\n    @ensure_pool\n    def simulate_w(self,\n                   index: int,\n                   half_turns: float,\n                   axis_half_turns: float):\n        \"\"\"Simulate a single qubit rotation gate about a X + b Y.\n\n        The gate simulated is U = exp(-i pi/2 W half_turns)\n            where W = cos(pi axis_half_turns) X + sin(pi axis_half_turns) Y\n\n        Args:\n          index: The qubit to act on.\n          half_turns: The amount of the overall rotation, see the formula\n              above.\n          axis_half_turns: The angle between the pauli X and Y operators,\n              see the formula above.\n        \"\"\"\n        args = self._shard_num_args({\n            'index': index,\n            'half_turns': half_turns,\n            'axis_half_turns': axis_half_turns\n        })\n        if index >= self._num_shard_qubits:\n            # W gate spans shards.\n            self._pool.map(_clear_scratch, args)\n            self._pool.map(_w_between_shards, args)\n            self._pool.map(_copy_scratch_to_state, args)\n        else:\n            # W gate is within a shard.\n            self._pool.map(_w_within_shard, args)\n\n        # Normalize after every w.\n        norm_squared = np.sum(self._pool.map(_norm_squared, args))\n        args = self._shard_num_args({\n            'norm_squared': norm_squared\n        })\n        self._pool.map(_renorm, args)\n\n    @ensure_pool\n    def simulate_measurement(self, index: int) -> bool:\n        \"\"\"Simulates a single qubit measurement in the computational basis.\n\n        Args:\n            index: Which qubit is measured.\n\n        Returns:\n            True iff the measurement result corresponds to the |1> state.\n        \"\"\"\n        args = self._shard_num_args({'index': index})\n        prob_one = np.sum(self._pool.map(_one_prob_per_shard, args))\n        result = bool(np.random.random() <= prob_one)\n\n        args = self._shard_num_args({\n            'index': index,\n            'result': result,\n            'prob_one': prob_one\n        })\n        self._pool.map(_collapse_state, args)\n        return result\n\n    def sample_measurements(\n            self,\n            indices: List[int],\n            repetitions: int=1) -> List[List[bool]]:\n        \"\"\"Samples from measurements in the computational basis.\n\n        Note that this does not collapse the wave function.\n\n        Args:\n            indices: Which qubits are measured.\n\n        Returns:\n            Measurement results with True corresponding to the |1> state.\n            The outer list is for repetitions, and the inner corresponds to\n            measurements ordered by the input indices.\n\n        Raises:\n            ValueError if repetitions is less than one.\n        \"\"\"\n        if repetitions < 1:\n            raise ValueError(\n                'Number of repetitions cannot be negative. Was {}'.format(\n\n                    repetitions))\n        if len(indices) == 0:\n            return [[]]\n\n        # Calculate probabilities and reshape to tensor of qubits.\n        tensor = np.reshape(np.abs(self.current_state) ** 2,\n                            self._num_qubits * [2])\n\n        # Tensor axis order is reverse of index order, so we transpose here.\n        tensor = np.transpose(tensor)\n\n        # Indices that should be summed over.\n        sum_indices = tuple(\n            x for x in range(self._num_qubits) if x not in indices)\n\n        # Sum over those indices, and reshape into a a tensor of len(indices)\n        # qubits.\n        probs = np.reshape(np.sum(tensor, axis=sum_indices), [2] * len(indices))\n\n        # Calculate how the indices not summed over should be reordered.\n        index_map = {v: k for k,v in enumerate(sorted(indices))}\n        perm = [index_map[x] for x in indices]\n        # Apply this permutation to the probabilities and flatten.,\n        probs = np.reshape(np.transpose(probs, perm), -1)\n\n        # We now have the probability vector, correctly ordered, so sample over\n        # it. Note that we us ints here, since numpy's choice does not allow for\n        # choosing from a list of tuples or list of lists.\n        result = np.random.choice(2 ** len(indices), size=repetitions, p=probs)\n        # Convert to bools and note also one final reverse of list to get\n        # ordering correct.\n        return np.transpose(\n            [(1 & (result >> i)).astype(np.bool) for i in range(len(indices))][\n            ::-1]).tolist()\n\n\ndef decode_initial_state(initial_state: Union[int, np.ndarray],\n                         num_qubits: int) -> np.ndarray:\n    \"\"\"Verifies the initial_state is valid and converts it to ndarray form.\"\"\"\n    if isinstance(initial_state, np.ndarray):\n        if len(initial_state) != 2 ** num_qubits:\n            raise ValueError(\n                'initial state was of size {} '\n                'but expected state for {} qubits'.format(\n                    len(initial_state), num_qubits))\n        state = initial_state\n    elif isinstance(initial_state, int):\n        if initial_state < 0:\n            raise ValueError('initial_state must be positive')\n        elif initial_state >= 2 ** num_qubits:\n            raise ValueError(\n                'initial state was {} but expected state for {} qubits'.format(\n                    initial_state, num_qubits))\n        else:\n            state = np.zeros(2 ** num_qubits, dtype=np.complex64)\n            state[initial_state] = 1.0\n    else:\n        raise TypeError('initial_state was not of type int or ndarray')\n    check_state(state, num_qubits)\n    return state\n\n\ndef check_state(state: np.ndarray, num_qubits: int):\n    \"\"\"Validates that the given state is a valid wave function.\"\"\"\n    if state.size != 1 << num_qubits:\n        raise ValueError(\n            'State has incorrect size. Expected {} but was {}.'.format(\n                1 << num_qubits, state.size))\n    if state.dtype != np.complex64:\n        raise ValueError(\n            'State has invalid dtype. Expected {} but was {}'.format(\n                np.complex64, state.dtype))\n    norm = np.sum(np.abs(state) ** 2)\n    if not np.isclose(norm, 1):\n        raise ValueError('State is not normalized instead had norm %s' % norm)\n\n\ndef _state_shard(args: Dict[str, Any]) -> np.ndarray:\n    state_handle = args['state_handle']\n    return mem_manager.SharedMemManager.get_array(state_handle).view(\n        dtype=np.complex64)[args['shard_num']]\n\n\ndef _scratch_shard(args: Dict[str, Any]) -> np.ndarray:\n    scratch_handle = args['scratch_handle']\n    return mem_manager.SharedMemManager.get_array(scratch_handle).view(\n        dtype=np.complex64)[args['shard_num']]\n\n\ndef _pm_vects(args: Dict[str, Any]) -> np.ndarray:\n    return mem_manager.SharedMemManager.get_array(args['pm_vects_handle'])\n\n\ndef _zero_one_vects(args: Dict[str, Any]) -> np.ndarray:\n    return mem_manager.SharedMemManager.get_array(\n        args['zero_one_vects_handle'])\n\n\ndef _kth_bit(x: int, k: int) -> int:\n    \"\"\"Returns 1 if the kth bit of x is set, 0 otherwise.\"\"\"\n    return (x >> k) & 1\n\n\ndef _reset_state(args: Dict[str, Any]):\n    shard_num = args['shard_num']\n    shard_size = 2 ** args['num_shard_qubits']\n    reset_state = args['reset_state']\n\n    if isinstance(reset_state, int):\n        _state_shard(args).fill(0)\n        if shard_num == reset_state // shard_size:\n            _state_shard(args)[reset_state % shard_size] = 1.0\n    else:\n        np.copyto(_state_shard(args), reset_state)\n\n\ndef _clear_scratch(args: Dict[str, Any]):\n    \"\"\"Sets all of the scratch shard to zero.\"\"\"\n    _scratch_shard(args).fill(0)\n\n\ndef _single_qubit_accumulate_into_scratch(args: Dict[str, Any]):\n    \"\"\"Accumulates single qubit phase gates into the scratch shards.\"\"\"\n    index = args['indices'][0]\n    shard_num = args['shard_num']\n    half_turns = args['half_turns']\n    num_shard_qubits = args['num_shard_qubits']\n    scratch = _scratch_shard(args)\n\n    # ExpZ = exp(-i pi Z half_turns / 2).\n    if index >= num_shard_qubits:\n        # Acts on prefix qubits.\n        sign = 1 - 2 * _kth_bit(shard_num, index - num_shard_qubits)\n        scratch -= half_turns * sign\n    else:\n        # Acts on shard qubits.\n        scratch -= half_turns * _pm_vects(args)[index]\n\n\ndef _one_projector(args: Dict[str, Any], index: int) -> Union[int, np.ndarray]:\n    \"\"\"Returns a projector onto the |1> subspace of the index-th qubit.\"\"\"\n    num_shard_qubits = args['num_shard_qubits']\n    shard_num = args['shard_num']\n    if index >= num_shard_qubits:\n        return _kth_bit(shard_num, index - num_shard_qubits)\n    return _zero_one_vects(args)[index]\n\n\ndef _two_qubit_accumulate_into_scratch(args: Dict[str, Any]):\n    \"\"\"Accumulates two qubit phase gates into the scratch shards.\"\"\"\n    index0, index1 = args['indices']\n    half_turns = args['half_turns']\n    scratch = _scratch_shard(args)\n\n    projector = _one_projector(args, index0) * _one_projector(args, index1)\n    # Exp11 = exp(-i pi |11><11| half_turns), but we accumulate phases as\n    # pi / 2.\n    scratch += 2 * half_turns * projector\n\n\ndef _apply_scratch_as_phase(args: Dict[str, Any]):\n    \"\"\"Takes scratch shards and applies them as exponentiated phase to state.\n    \"\"\"\n    state = _state_shard(args)\n    state *= np.exp(I_PI_OVER_2 * _scratch_shard(args))\n\n\ndef _w_within_shard(args: Dict[str, Any]):\n    \"\"\"Applies a W gate when the gate acts only within a shard.\"\"\"\n    index = args['index']\n    half_turns = args['half_turns']\n    axis_half_turns = args['axis_half_turns']\n    state = _state_shard(args)\n    pm_vect = _pm_vects(args)[index]\n    num_shard_qubits = args['num_shard_qubits']\n    shard_size = 2 ** num_shard_qubits\n\n    reshape_tuple = (2 ** (num_shard_qubits - 1 - index), 2, 2 ** index)\n    perm_state = np.reshape(\n        np.reshape(state, reshape_tuple)[:, ::-1, :], shard_size)\n    cos = np.cos(-0.5 * np.pi * half_turns)\n    sin = np.sin(-0.5 * np.pi * half_turns)\n\n    cos_axis = np.cos(np.pi * axis_half_turns)\n    sin_axis = np.sin(np.pi * axis_half_turns)\n\n    new_state = cos * state + 1j * sin * perm_state * (\n        cos_axis - 1j * sin_axis * pm_vect)\n    np.copyto(state, new_state)\n\n\ndef _w_between_shards(args: Dict[str, Any]):\n    \"\"\"Applies a W gate when the gate acts between shards.\"\"\"\n    shard_num = args['shard_num']\n    state = _state_shard(args)\n    num_shard_qubits = args['num_shard_qubits']\n    index = args['index']\n    half_turns = args['half_turns']\n\n    axis_half_turns = args['axis_half_turns']\n\n    perm_index = shard_num ^ (1 << (index - num_shard_qubits))\n    perm_state = mem_manager.SharedMemManager.get_array(\n        args['state_handle']).view(np.complex64)[perm_index]\n\n    cos = np.cos(-0.5 * np.pi * half_turns)\n    sin = np.sin(-0.5 * np.pi * half_turns)\n\n    cos_axis = np.cos(np.pi * axis_half_turns)\n    sin_axis = np.sin(np.pi * axis_half_turns)\n\n    scratch = _scratch_shard(args)\n    z_op = (1 - 2 * _kth_bit(shard_num, index - num_shard_qubits))\n    np.copyto(scratch, state * cos + 1j * sin * perm_state *\n              (cos_axis - 1j * sin_axis * z_op))\n\n\ndef _copy_scratch_to_state(args: Dict[str, Any]):\n    \"\"\"Copes scratch shards to state shards.\"\"\"\n    np.copyto(_state_shard(args), _scratch_shard(args))\n\n\ndef _one_prob_per_shard(args: Dict[str, Any]) -> float:\n    \"\"\"Returns the probability of getting a one measurement on a state shard.\n    \"\"\"\n    index = args['index']\n\n    state = _state_shard(args) * _one_projector(args, index)\n    norm = np.linalg.norm(state)\n    return norm * norm\n\n\ndef _norm_squared(args: Dict[str, Any]) -> float:\n    \"\"\"Returns the norm for each state shard.\"\"\"\n    state = _state_shard(args)\n    return np.sum(np.abs(state) ** 2)\n\n\ndef _renorm(args: Dict[str, Any]):\n    \"\"\"Renormalizes the state using the norm arg.\"\"\"\n    state = _state_shard(args)\n    # If our gate is so bad that we have norm of zero, we have bigger problems.\n    state /= np.sqrt(args['norm_squared'])\n\n\ndef _collapse_state(args: Dict[str, Any]):\n    \"\"\"Projects state shards onto the appropriate post measurement state.\n\n    This function makes no assumptions about the interpretation of quantum\n    theory.\n\n    Args:\n        args: The args from shard_num_args.\n    \"\"\"\n    index = args['index']\n    result = args['result']\n    prob_one = args['prob_one']\n\n    state = _state_shard(args)\n    normalization = np.sqrt(prob_one if result else 1 - prob_one)\n    state *= (_one_projector(args, index) * result +\n              (1 - _one_projector(args, index)) * (1 - result))\n    state /= normalization\n\n\nclass ThreadlessPool(object):\n    \"\"\"A Pool that does not use any processes or threads.\n\n    Only supports map, close, and join, the later two being trivial.\n    No enforcement of closing or joining is done, so map can be called\n    repeatedly.\n    \"\"\"\n\n    # noinspection PyMethodMayBeStatic\n    def map(self, func, iterable, chunksize=None):\n        assert chunksize is None, 'Chunking not supported by SimplePool'\n        return [func(x) for x in iterable]\n\n    def terminate(self):\n        pass\n\n    def join(self):\n        pass\n", "meta": {"hexsha": "8a74d8007de81f1b50d97079805fed5d08206215", "size": 26029, "ext": "py", "lang": "Python", "max_stars_repo_path": "cirq/google/sim/xmon_stepper.py", "max_stars_repo_name": "higgsman/Cirq", "max_stars_repo_head_hexsha": "6881ca2f7a5bdfaeef5f247d020fe4b3dfd0767b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2019-05-28T14:32:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T08:49:53.000Z", "max_issues_repo_path": "cirq/google/sim/xmon_stepper.py", "max_issues_repo_name": "GerrardFalcon/qutrits", "max_issues_repo_head_hexsha": "fe24c420ac81ee0134af88f4d7102b71c15200fb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-02-08T20:31:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-01T23:48:19.000Z", "max_forks_repo_path": "cirq/google/sim/xmon_stepper.py", "max_forks_repo_name": "GerrardFalcon/qutrits", "max_forks_repo_head_hexsha": "fe24c420ac81ee0134af88f4d7102b71c15200fb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-05-28T15:57:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T12:14:57.000Z", "avg_line_length": 38.9655688623, "max_line_length": 80, "alphanum_fraction": 0.633293634, "include": true, "reason": "import numpy", "num_tokens": 6212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.17722765278866937}}
{"text": "#!/usr/bin/env python3\n\"\"\"\nThe data types for an Ocean Salinity DTBXY\n\"\"\"\n\nimport numpy as np\n\n# data type list of lists. The inner lists are there for each file sub-block.\ndatatype = [\n            [('MaxValid', 'float32')],\n            [('MinValid', 'float32')],\n\n            # REGION\n            [('region_count', 'uint32')],\n            # Region ID, start and stop snap time, start and stop snap id\n            [('Region_ID', 'uint32'), ('Days', 'int32'), ('Seconds', 'uint32'), ('Microseconds', 'uint32'),\n             ('stop_Days', 'int32'), ('stop_Seconds', 'uint32'), ('stop_Microseconds', 'uint32'),\n             ('Start_Snapshot_ID', 'uint32'), ('Stop_Snapshot_ID', 'uint32')],\n            # stats (just one number) repeated for the 3 models, 8 pols, 12 fov zones\n            [('mean', 'float32'), ('median', 'float32'), ('min', 'float32'), ('max', 'float32'), ('std', 'float32')],\n            # counts, dTb, std_dTb, flags repeated 129 x 129\n            [('count_deltaTB', 'uint32'), ('deltaTB', 'float32'), ('std_deltaTB', 'float32'), ('flags', 'ushort')],\n\n            # SNAPSHOTS\n            [('snap_count', 'uint32')],\n            # snapshot general info\n            [('Snapshot_ID', 'uint32'), ('Snapshot_OBET', 'uint64'), ('Snapshot_Latitude', 'float32'),\n             ('Snapshot_Longitude', 'float32'), ('Snapshot_Altitude', 'float32'), ('Snapshot_Flags', 'ushort'),\n             ('L1c_TEC', 'int16')],\n            [('measurement_count', 'ushort')],\n            # measured Tb mean and std\n            [('L1cTB', 'ushort'), ('std_L1cTB', 'ushort')],\n            # BOA fwd model components\n            [('atmosTB', 'int16'), ('std_atmosTB', 'ushort'), ('flatSeaTB', 'int16'), ('std_flatSeaTB', 'ushort'),\n             ('roughTB', 'int16'), ('std_roughTB', 'ushort'), ('galTB', 'int16'), ('std_galTB', 'ushort'),\n             ('sunTB', 'int16'), ('std_sunTB', 'ushort'), ('sumTB', 'int16'), ('std_sumTB', 'ushort')],\n            # TOA fwd model components with L1c TEC\n            [('atmosTB', 'int16'), ('std_atmosTB', 'ushort'), ('flatSeaTB', 'int16'), ('std_flatSeaTB', 'ushort'),\n             ('roughTB', 'int16'), ('std_roughTB', 'ushort'), ('galTB', 'int16'), ('std_galTB', 'ushort'),\n             ('sunTB', 'int16'), ('std_sunTB', 'ushort'), ('sumTB', 'int16'), ('std_sumTB', 'ushort')],\n            # TOA fwd model components with A3 TEC\n            [('atmosTB', 'int16'), ('std_atmosTB', 'ushort'), ('flatSeaTB', 'int16'), ('std_flatSeaTB', 'ushort'),\n             ('roughTB', 'int16'), ('std_roughTB', 'ushort'), ('galTB', 'int16'), ('std_galTB', 'ushort'),\n             ('sunTB', 'int16'), ('std_sunTB', 'ushort'), ('sumTB', 'int16'), ('std_sumTB', 'ushort')],\n            # geophysics\n            [('SSS', 'int16'), ('std_SSS', 'ushort'), ('SST', 'int16'), ('std_SST', 'ushort'), ('WS', 'int16'),\n             ('std_WS', 'ushort'), ('A3TEC', 'int16'), ('std_A3TEC', 'ushort'), ('Tair', 'int16'),\n             ('std_Tair', 'ushort'), ('SP', 'int16'), ('std_SP', 'ushort'), ('TCWV', 'int16'), ('std_TCWV', 'ushort'),\n             ('HS', 'int16'), ('std_HS', 'ushort')],\n            # flags\n            [('coast', 'ushort'), ('sun_point', 'ushort'), ('sun_tails', 'ushort'), ('rfi', 'ushort'),\n             ('rain', 'ushort'), ('ice', 'ushort')],\n\n            [('gp_count', 'uint32')],\n            # grid points\n            [('Grid_Point_ID', 'uint32'), ('Grid_Point_Latitude', 'float32'), ('Grid_Point_Longitude', 'float32')],\n            [('measurement_count', 'ushort')],\n            [('Snapshot_Index', 'ushort'), ('Zone_Bits', 'ushort')]\n            ]", "meta": {"hexsha": "b93fcf867246545a14e92dbb141f01624c0f085d", "size": 3579, "ext": "py", "lang": "Python", "max_stars_repo_path": "smos_tools/data_types/os_dtbxy_datatype.py", "max_stars_repo_name": "ARGANS/smos-tools", "max_stars_repo_head_hexsha": "4a0e5bb54fdef52725e30f14a6a971ebeeb71881", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-10T08:40:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-15T01:38:31.000Z", "max_issues_repo_path": "smos_tools/data_types/os_dtbxy_datatype.py", "max_issues_repo_name": "ARGANS/smos-tools", "max_issues_repo_head_hexsha": "4a0e5bb54fdef52725e30f14a6a971ebeeb71881", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "smos_tools/data_types/os_dtbxy_datatype.py", "max_forks_repo_name": "ARGANS/smos-tools", "max_forks_repo_head_hexsha": "4a0e5bb54fdef52725e30f14a6a971ebeeb71881", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-03T05:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-03T05:29:30.000Z", "avg_line_length": 60.6610169492, "max_line_length": 118, "alphanum_fraction": 0.512992456, "include": true, "reason": "import numpy", "num_tokens": 1024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.331119752830196, "lm_q1q2_score": 0.1771816594266699}}
{"text": "# Filename: pair.py\nimport sys\nimport numpy\nimport time\nfrom operator import add\nimport pandas as pd\nimport datetime\nimport json\nimport urllib2\nimport pytz\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nfrom pandas.io.data import DataReader\nimport riak\nimport numpy as np\nimport statsmodels.api as stat\nimport statsmodels.tsa.stattools as ts\nfrom riak import RiakClient, RiakObject\nimport boto, urllib2\nfrom   boto.ec2 import connect_to_region\nimport os\nimport sys\n\n#start is furthest day back and end is most recent day.  Grabs all data in between and stores in riak as json\n#runs through a file of ticker values\ndef getData(tickerFile, dataSource, start, end, riakIP):\n\n    rc = RiakClient(protocol='pbc',host = riakIP, pb_port=8087)#set up riak connection\n    added = []#list of successful adds\n    notAdded = []#list of unsuccessful adds\n    stock = pd.read_csv(tickerFile,sep='\\t',header=None)#read in stock tickers\n\n    #loop over all stock tickers\n    for i in range(0,len(stock.head(100))):\n        \n        ticker = stock.ix[i,0]\n        if getDataByTicker(ticker,dataSource,start,end,riakIP) == 0:\n            notAdded.append(ticker)\n        else:\n            added.append(ticker)\n    return added, notAdded\n\n#start is furthest day back and end is closest to today, Store single stock data in riak\n#only grabs one stock\ndef getDataByTicker(ticker, dataSource, start, end, riakIP):\n\n    rc = RiakClient(protocol='pbc',host = riakIP, pb_port=8087)\n    #get daily data for each ticker\n    gtemp = pd.DataFrame()\n    bucket = rc.bucket('stocks')\n    try:\n        gtemp = DataReader(ticker,  dataSource, start, end)\n        print ticker\n    except:\n        pass\n        \n        #didnt get any data\n    if len(gtemp) == 0:\n        return 0\n    #got data\n    else:\n        \n        for j in range(0,len(gtemp.index)):\n            \n            #upload json to Riak Bucket\n            date = gtemp.index[j].date()\n            riakKey = str(ticker + '_' + str(date))\n            riakVal = {'OPEN': gtemp.values[j,0],\\\n                        'HIGH': gtemp.values[j,1],\\\n                        'LOW': gtemp.values[j,2], \\\n                        'CLOSE': gtemp.values[j,3], \\\n                        'VOLUME': gtemp.values[j,4],\\\n                        'DATE': str(date),\\\n                        'TICKER': str(ticker)}\n                \n            obj = RiakObject(rc, bucket, riakKey)\n                \n            obj.add_index(\"ticker_bin\", str(ticker))\n            obj.add_index(\"year_int\", int(date.year))\n            obj.add_index(\"month_int\", int(date.month))\n            obj.add_index(\"day_int\", int(date.day))\n                \n            obj.content_type = 'text/json'\n            #obj.data = riakVal\n            obj.data = json.dumps(riakVal)\n            obj.store()\n\n    return len(gtemp.index)\n\ndef downloadStock(ticker,dataSource,start,end):\n    gtemp = pd.DataFrame()\n    try:\n        gtemp = DataReader(ticker,  dataSource, start, end)\n        print ticker\n    except:\n        pass\n    return gtemp\n\ndef writeHistory(ticker, data, riakIP):\n    rc = RiakClient(protocol='pbc',host = riakIP, pb_port=8087)\n    bucket = rc.bucket('stocks')\n    gtemp = data\n    if len(gtemp) == 0:\n        return 0\n    else:\n\n        for j in range(0,len(gtemp.index)):\n                \n                #upload json to Riak Bucket\n                date = gtemp.index[j].date()\n                riakKey = str(ticker + '_' + str(date))\n                riakVal = {'OPEN': gtemp.values[j,0],\\\n                            'HIGH': gtemp.values[j,1],\\\n                            'LOW': gtemp.values[j,2], \\\n                            'CLOSE': gtemp.values[j,3], \\\n                            'VOLUME': gtemp.values[j,4],\\\n                            'DATE': str(date),\\\n                            'TICKER': str(ticker)}\n                    \n                obj = RiakObject(rc, bucket, riakKey)\n                    \n                obj.add_index(\"ticker_bin\", str(ticker))\n                obj.add_index(\"year_int\", int(date.year))\n                obj.add_index(\"month_int\", int(date.month))\n                obj.add_index(\"day_int\", int(date.day))\n                    \n                obj.content_type = 'text/json'\n                #obj.data = riakVal\n                obj.data = json.dumps(riakVal)\n                obj.store()\n\n    return len(gtemp.index)\n\n#searches riak bucket via 2i query and returns a dict of the data\ndef riakSearchData(searchBucket, searchTerm, searchVal1, searchVal2,riakIP):\n    myData = {}#empty dict\n    myBucket = RiakClient(protocol='pbc',host = riakIP, pb_port=8087).bucket(searchBucket)\n    #check wether 1 or 2 search terms\n    if searchVal2 != None:\n        for key in myBucket.get_index(searchTerm, searchVal1, searchVal2): #get all keys with 2i match\n            myData[key] = json.loads(myBucket.get(key).data)#store data for each key\n    else:\n        for key in myBucket.get_index(searchTerm, searchVal1):#get all keys with 2i match\n            myData[key] = json.loads(myBucket.get(key).data)#store data for each key\n    return myData\n\n#store an individual key value pair in a bucket\ndef storeKV(myBucket, myKey, myVal, riakIP):\n    riak.RiakClient(protocol='pbc',host = riakIP, pb_port=8087).bucket(myBucket).new(myKey, data = myVal).store()\n    return\n\n#delete a key from a bucket, provide feedback to ensure deletion\ndef deleteKey(delBucket, delKey,riakIP):\n    riak.RiakClient(protocol='pbc',host = riakIP, pb_port=8087).bucket(delBucket).delete(delKey)\n    if riak.RiakClient(protocol='pbc',host = riakIP, pb_port=8087).bucket(delBucket).get(delKey).data == None:\n        print 'Successful delete: %s' % delKey\n    else:\n        print 'Failed delete: %s' % delKey\n    return\n\n#delete key from bucket, no feedback\ndef quickDeleteKey(delBucket,delKey, riakIP):\n    riak.RiakClient(protocol='pbc',host = riakIP, pb_port=8087).bucket(delBucket).delete(delKey)\n    return\n\n#delete all keys in a bucket, no feedback  \ndef quickDeleteAllKeys(delBucket,riakIP):\n    for keys in  riak.RiakClient(protocol='pbc',host = riakIP, pb_port=8087).bucket(delBucket).stream_keys():\n        for delKey in keys:\n            quickDeleteKey(delBucket, delKey,riakIP)      \n    print 'Done'\n    return\n\n#delete all keys in a bucket, with feedback\ndef deleteAllKeys(delBucket,riakIP):\n    delList = []\n    try:\n        for keys in  riak.RiakClient(protocol='pbc',host = riakIP, pb_port=8087).bucket(delBucket).stream_keys():\n            for delKey in keys:\n                deleteKey(delBucket, delKey,riakIP)\n                delList.append(delKey)\n    except:\n        print 'delete error'\n        pass\n    return delList\n\n#get all key value pairs from a bucket\ndef getAllKV(myBucket,riakIP):\n    myData = {}\n    riak_bucket = riak.RiakClient(protocol='pbc',host = riakIP, pb_port=8087).bucket(myBucket)\n    for keys in riak_bucket.stream_keys():\n        for key in keys:\n            tempData = riak_bucket.get(key).data\n            print('Key: %s Value: %s' % (key, tempData))\n            myData[key] = tempData\n    return myData\n\n#get single value for a key in a bucket\ndef getValue(myBucket, myKey,riakIP):\n    myVal = json.loads(riak.RiakClient(protocol='pbc',host = riakIP, pb_port=8087).bucket(myBucket).get(myKey).data)\n    return myVal\n\n#Take a tuple of tuples in and return something\ndef pairAnalysis(pairTuple, ndays, beginDay = 0, zThresh = 2, critLevel = '5%'):\n    \n    #pair tuple looks like ([tickerA, [data]],[tickerB,[data]])\n    #input is assumed to be same length and sorted by date with most recent date first\n    \n    #unwrap first stock ticker and data\n    stockA = pairTuple[0]\n    stockAData = list(stockA[1])\n    \n    #unwrap the data for stockA\n    stockADates = [x[2] for x in stockAData]\n    stockAClose = [x[0] for x in stockAData]\n    stockAVolume = [x[1] for x in stockAData]\n    \n    #unwrap second stock ticker and data\n    stockB = pairTuple[1]\n    stockBData = list(stockB[1])\n   \n    #unwrap stockB data\n    stockBDates = [x[2] for x in stockBData]\n    stockBClose = [x[0] for x in stockBData]\n    stockBVolume = [x[1] for x in stockBData]\n    \n    pair = pairCalc(stockAClose,stockBClose,beginDay,ndays, zThresh, critLevel)\n    #if pair tradeable, add some more info\n    if type(pair) is list:\n            pair.insert(0,stockADates[beginDay])\n            pair.insert(0,stockB[0])\n            pair.insert(0,stockA[0])\n            return pair\n    else:\n        return pair\n\ndef pairCalc(tsA,tsB,beginDay,ndays,zThresh = 2, critLevel = '5%'):\n    \n    #perform engle granger cointegration test\n    if beginDay < 0 or beginDay >= ndays or zThresh < 0 or not (critLevel in ['1%','5%','10%']):\n        print 'input error'\n        return 0\n\n    coint = egct(tsA[beginDay:ndays],tsB[beginDay:ndays], critLevel)\n    \n    #if coint return 0, then the two timeseries are not cointegrated\n    if (coint[0] != 1):\n        return 0\n    #else calculate stuff\n    else:\n        #signal = tsA[0] - beta*tsB[0] - CONSTANT = normal gaussian with mean 0\n        signal = [a - coint[1][1]*b - coint[1][0] for a in tsA[beginDay:ndays] for b in tsB[beginDay:ndays]]\n        sigMean = numpy.mean(signal)\n        sigStd = numpy.std(signal)\n        #zscore is (signal - signalMean) / signalStd\n        zscore = (signal[beginDay] - sigMean)/sigStd\n        #if current zscore is larger than zThresh, possible pair to trade\n        if abs(zscore) > zThresh:\n            return [tsA[0],tsB[0], zscore, coint[1][1], sigMean, sigStd]\n    return 1\n\n#write tradeable pair back into riak\ndef writePairs(pairList,bucketName,riakIP):\n    \n    #tradeable pairs are lists\n    tradeable = [x for x in pairList if type(x) is list]\n    \n    for pair in tradeable:\n        writeSinglePair(pair,bucketName,riakIP)\n    \n    #return a list of written pairs\n    return tradeable\n       \n#write a signle pair to riak\n#assumes pair is in a list of values\ndef writeSinglePair(pair,bucketName,riakIP):\n    \n    rc = RiakClient(protocol='pbc',host = riakIP, pb_port=8087)\n    bucket = rc.bucket(bucketName)\n    \n    #create key value pairs to stock in riak\n    key = str(str(pair[0])+ '_' + str(pair[1]))\n    val = {'StockA': pair[0], \\\n                'StockB': pair[1], \\\n                'Date': pair[2],\\\n                'CloseA': pair[3], \\\n                'CloseB': pair[4], \\\n                'ZScore': pair[5],\\\n                'Beta': pair[6],\\\n                'SignalMean': pair[7],\\\n                'SignalSD': pair[8]}\n    myDate = pair[2].split('-')\n    obj = RiakObject(rc, bucket, key)\n        \n    #add 2i tags\n    obj.add_index(\"stocka_bin\", str(pair[0]))\n    obj.add_index(\"stockb_bin\", str(pair[3]))\n    obj.add_index(\"year_int\", int(myDate[0]))\n    obj.add_index(\"month_int\", int(myDate[1]))\n    obj.add_index(\"day_int\", int(myDate[2]))\n    obj.content_type = 'text/json'\n    obj.data = val\n    obj.data = json.dumps(val)\n    #store\n    obj.store()\n    \n    #return a list of written pairs\n    return pair   \n    \n#return 1 if the two series are cointegrated and 0 otherwise, return regression parameters either way\n#assumes y,x are aligned and of equal length\n#critLevel can be '1%', '5%' or '10%'\ndef egct(y, x,critLevel):\n    \n    #must add a constant row of 1s to dependent variable, its a multidimensional regression thing\n    x = stat.add_constant(x)\n    #get residuals\n    result = stat.OLS(y, x).fit()\n    #regression parameters, slope and intercept\n    regPar = result.params\n    #run augmented dickey fuller test of stationarity of residuals\n    #null hypothesis is stationaity of timeseries\n    adfResults = ts.adfuller(result.resid, maxlag=0, regression='c', autolag=None, store=False, regresults=True)\n    #test statistic\n    tstat = adfResults[0]\n    #critical value\n    critVal = adfResults[2][critLevel]\n    #if test stat is less than critical value, accept null hyptohesis of stationarity\n    if tstat < critVal:\n        return [1,regPar]\n    else:\n        return [0,regPar]\n\n#get all values for a stock from riak  \n#return close,volume,date values in a list of list\ndef riakGetStock(searchVal,riakIP):\n    myData = []\n    myBucket = RiakClient(protocol='pbc',host = riakIP, pb_port=8087).bucket('stocks')\n    for key in myBucket.get_index('ticker_bin', searchVal): # get all from 2002 to 2012\n        value = json.loads(myBucket.get(key).data)\n        myData.append([(value['CLOSE']), (value['VOLUME']), str(value['DATE'])])\n    return myData\n\n#quick function to sort a list of list on the inner list 3 value(date)\ndef mySort(s,n):\n\n    try:\n        sortList = list(s)\n        sortList.sort(key=lambda x: x[n], reverse=True)\n    except:\n        print \"error using mySort\"\n        return 0\n\n    return sortList\n\n#cut length of time series to n\ndef myFilter(s,n):\n    if type(s) is list:\n        try:\n            return s[0:n]\n        except:\n            print 'error using myFilter'\n            return 0\n    else:\n        print 'not a list'\n        return 0\n\ndef bootCluster(accessKey,secretKey,region,instanceType):\n\n    conn = boto.ec2.connect_to_region(\"us-east-1\", aws_access_key_id=accessKey,aws_secret_access_key=secretKey)\n    instances = [i for r in conn.get_all_instances() for i in r.instances]\n\n    #start all non running instances\n    myInst = []\n    awsHosts = []\n    awsIPs = []\n\n    for i in instances:\n        if i.state == 'stopped' and i.instance_type == instanceType:\n            conn.start_instances(i.id)\n            myInst.append(str(i.id))\n\n    for i in myInst:\n        i.update()\n\n        while i.state != 'running':\n            print 'waiting for: ' + str(i.id)\n            time.sleep(2)\n            i.update()\n\n        awsHosts.append(str(i.dns_name))\n        awsIPs.append(str(i.private_ip_address))\n\n        print str(i.id)+ ' is running'\n\n    return myInst, awsHosts, awsIPs\n\ndef stopCluster(accessKey,secretKey,region,instanceType):\n\n    conn = boto.ec2.connect_to_region(\"us-east-1\", aws_access_key_id=accessKey,aws_secret_access_key=secretKey)\n    instances = [i for r in conn.get_all_instances() for i in r.instances]\n\n    myInst = []\n\n    for i in instances:\n        if i.state == 'running' and i.instance_type == instanceType:\n            conn.stop_instances(i.id)\n            myInst.append(str(i.id))\n\n    for i in myInst:\n        i.update()\n    \n        while i.state != 'stopped':\n            print 'waiting for: ' + str(i.id)\n            time.sleep(2)\n            i.update()\n        print str(i.id)+ ' is stopped'\n\n    return myInst\n\ndef submitSparkJob(sparkJob):\n\n    os.system('fab -R worker '+ sparkJob)\n\n    return 'Submitted: ' + sparkJob\n\ndef getDNSIP(accessKey,secretKey,region,instanceType):\n\n    conn = boto.ec2.connect_to_region(\"us-east-1\", aws_access_key_id=accessKey,aws_secret_access_key=secretKey)\n    awsHosts = []\n    awsIPs = []\n    instances = [i for r in conn.get_all_instances() for i in r.instances]\n\n    for i in instances:\n        if i.state == 'running' and i.instance_type == 't2.medium':\n            awsHosts.append(str(i.dns_name))\n            awsIPs.append(str(i.private_ip_address))\n\n    return awsHosts, awsIPs\n\ndef updateDate(riakIP):\n\n    print '::::Writing Date of New Update::::'\n    newUpdate = {'Year': datetime.now().year,\\\n                   'Month': datetime.now().month,\\\n                   'Day': datetime.now().day,\\\n                   'Hour': datetime.now().hour,\\\n                   'Minute': datetime.now().minute}\n    print newUpdate\n    storeKV(\"meta\", \"update\", json.dumps(newUpdate), riakIP)\n\n    return\n\n# End of pair.py", "meta": {"hexsha": "70b7d83adfe2c2275487ebede3341fb2055979da", "size": 15453, "ext": "py", "lang": "Python", "max_stars_repo_path": "pair.py", "max_stars_repo_name": "rpatil524/spark-bdp-stockticker-demo", "max_stars_repo_head_hexsha": "cdff3a06bb9489e540a37cdf68c4ecefd5c576bf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2015-09-18T08:08:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T21:05:28.000Z", "max_issues_repo_path": "pair.py", "max_issues_repo_name": "rpatil524/spark-bdp-stockticker-demo", "max_issues_repo_head_hexsha": "cdff3a06bb9489e540a37cdf68c4ecefd5c576bf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-11T02:45:04.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-20T19:16:40.000Z", "max_forks_repo_path": "pair.py", "max_forks_repo_name": "rpatil524/spark-bdp-stockticker-demo", "max_forks_repo_head_hexsha": "cdff3a06bb9489e540a37cdf68c4ecefd5c576bf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2015-11-11T08:55:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-05T20:09:52.000Z", "avg_line_length": 34.0374449339, "max_line_length": 116, "alphanum_fraction": 0.6146379344, "include": true, "reason": "import numpy,import statsmodels", "num_tokens": 4181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.17718165236272607}}
{"text": "from __future__ import division\nimport numba as nb\nimport numpy as np\n\nfrom .utils import get_func, isstr, aggregate_common_doc, funcs_no_separate_nan\nfrom .utils_numpy import aliasing, input_validation, check_dtype, check_fill_value\n\n\nclass AggregateOp(object):\n    \"\"\"\n    Every subclass of AggregateOp handles a different aggregation operation. There are\n    several private class methods that need to be overwritten by the subclasses\n    in order to implement different functionality.\n\n    On object instantiation, all necessary static methods are compiled together into\n    two jitted callables, one for scalar arguments, and one for arrays. Calling the\n    instantiated object picks the right cached callable, does some further preprocessing\n    and then executes the actual aggregation operation.\n    \"\"\"\n\n    forced_fill_value = None\n    counter_fill_value = 1\n    counter_dtype = bool\n    mean_fill_value = None\n    mean_dtype = np.float64\n    outer = False\n    reverse = False\n    nans = False\n\n    def __init__(self, func=None, **kwargs):\n        if func is None:\n            func = type(self).__name__.lower()\n        self.func = func\n        self.__dict__.update(kwargs)\n        # Cache the compiled functions, so they don't have to be recompiled on every call\n        self._jit_scalar = self.callable(self.nans, self.reverse, scalar=True)\n        self._jit_non_scalar = self.callable(self.nans, self.reverse, scalar=False)\n\n    def __call__(self, group_idx, a, size=None, fill_value=0, order='C',\n                 dtype=None, axis=None, ddof=0):\n        iv = input_validation(group_idx, a, size=size, order=order, axis=axis, check_bounds=False)\n        group_idx, a, flat_size, ndim_idx, size = iv\n\n        # TODO: The typecheck should be done by the class itself, not by check_dtype\n        dtype = check_dtype(dtype, self.func, a, len(group_idx))\n        check_fill_value(fill_value, dtype, func=self.func)\n        input_dtype = type(a) if np.isscalar(a) else a.dtype\n        ret, counter, mean, outer = self._initialize(flat_size, fill_value, dtype, input_dtype, group_idx.size)\n        group_idx = np.ascontiguousarray(group_idx)\n\n        if not np.isscalar(a):\n            a = np.ascontiguousarray(a)\n            jitfunc = self._jit_non_scalar\n        else:\n            jitfunc = self._jit_scalar\n        jitfunc(group_idx, a, ret, counter, mean, outer, fill_value, ddof)\n        self._finalize(ret, counter, fill_value)\n\n        if self.outer:\n            return outer\n\n        # Deal with ndimensional indexing\n        if ndim_idx > 1:\n            ret = ret.reshape(size, order=order)\n        return ret\n\n    @classmethod\n    def _initialize(cls, flat_size, fill_value, dtype, input_dtype, input_size):\n        if cls.forced_fill_value is None:\n            ret = np.full(flat_size, fill_value, dtype=dtype)\n        else:\n            ret = np.full(flat_size, cls.forced_fill_value, dtype=dtype)\n\n        counter = mean = outer = None\n        if cls.counter_fill_value is not None:\n            counter = np.full_like(ret, cls.counter_fill_value, dtype=cls.counter_dtype)\n        if cls.mean_fill_value is not None:\n            dtype = cls.mean_dtype if cls.mean_dtype else input_dtype\n            mean = np.full_like(ret, cls.mean_fill_value, dtype=dtype)\n        if cls.outer:\n            outer = np.full(input_size, fill_value, dtype=dtype)\n\n        return ret, counter, mean, outer\n\n    @classmethod\n    def _finalize(cls, ret, counter, fill_value):\n        if cls.forced_fill_value is not None and fill_value != cls.forced_fill_value:\n            if cls.counter_dtype == bool:\n                ret[counter] = fill_value\n            else:\n                ret[~counter.astype(bool)] = fill_value\n\n    @classmethod\n    def callable(cls, nans=False, reverse=False, scalar=False):\n        \"\"\" Compile a jitted function doing the hard part of the job \"\"\"\n        _valgetter = cls._valgetter_scalar if scalar else cls._valgetter\n        valgetter = nb.njit(_valgetter)\n        outersetter = nb.njit(cls._outersetter)\n\n        _cls_inner = nb.njit(cls._inner)\n        if nans:\n            def _inner(ri, val, ret, counter, mean):\n                if not np.isnan(val):\n                    _cls_inner(ri, val, ret, counter, mean)\n            inner = nb.njit(_inner)\n        else:\n            inner = _cls_inner\n\n        def _loop(group_idx, a, ret, counter, mean, outer, fill_value, ddof):\n            # fill_value and ddof need to be present for being exchangeable with loop_2pass\n            size = len(ret)\n            rng = range(len(group_idx) - 1, -1 , -1) if reverse else range(len(group_idx))\n            for i in rng:\n                ri = group_idx[i]\n                if ri < 0:\n                    raise ValueError(\"negative indices not supported\")\n                if ri >= size:\n                    raise ValueError(\"one or more indices in group_idx are too large\")\n                val = valgetter(a, i)\n                inner(ri, val, ret, counter, mean)\n                outersetter(outer, i, ret[ri])\n        return nb.njit(_loop, nogil=True)\n\n    @staticmethod\n    def _valgetter(a, i):\n        return a[i]\n\n    @staticmethod\n    def _valgetter_scalar(a, i):\n        return a\n\n    @staticmethod\n    def _inner(ri, val, ret, counter, mean):\n        raise NotImplementedError(\"subclasses need to overwrite _inner\")\n\n    @staticmethod\n    def _outersetter(outer, i, val):\n        pass\n\n\nclass Aggregate2pass(AggregateOp):\n    \"\"\"Base class for everything that needs to process the data twice like mean, var and std.\"\"\"\n    @classmethod\n    def callable(cls, nans=False, reverse=False, scalar=False):\n        # Careful, cls needs to be passed, so that the overwritten methods remain available in\n        # AggregateOp.callable\n        loop = super(Aggregate2pass, cls).callable(nans=nans, reverse=reverse, scalar=scalar)\n\n        _2pass_inner = nb.njit(cls._2pass_inner)\n        def _loop2(ret, counter, mean, fill_value, ddof):\n            for ri in range(len(ret)):\n                if counter[ri]:\n                    ret[ri] = _2pass_inner(ri, ret, counter, mean, ddof)\n                else:\n                    ret[ri] = fill_value\n        loop2 = nb.njit(_loop2)\n\n        def _loop_2pass(group_idx, a, ret, counter, mean, outer, fill_value, ddof):\n            loop(group_idx, a, ret, counter, mean, outer, fill_value, ddof)\n            loop2(ret, counter, mean, fill_value, ddof)\n        return nb.njit(_loop_2pass)\n\n    @staticmethod\n    def _2pass_inner(ri, ret, counter, mean, ddof):\n        raise NotImplementedError(\"subclasses need to overwrite _2pass_inner\")\n\n    @classmethod\n    def _finalize(cls, ret, counter, fill_value):\n        \"\"\"Copying the fill value is already done in the 2nd pass\"\"\"\n        pass\n\n\nclass AggregateNtoN(AggregateOp):\n    \"\"\"Base class for cumulative functions, where the output size matches the input size.\"\"\"\n    outer = True\n\n    @staticmethod\n    def _outersetter(outer, i, val):\n        outer[i] = val\n\n\nclass AggregateGeneric(AggregateOp):\n    \"\"\"Base class for jitting arbitrary functions.\"\"\"\n    counter_fill_value = None\n\n    def __init__(self, func, **kwargs):\n        self.func = func\n        self.__dict__.update(kwargs)\n        self._jitfunc = self.callable(self.nans)\n\n    def __call__(self, group_idx, a, size=None, fill_value=0, order='C',\n                 dtype=None, axis=None, ddof=0):\n        iv = input_validation(group_idx, a, size=size, order=order, axis=axis, check_bounds=False)\n        group_idx, a, flat_size, ndim_idx, size = iv\n\n        # TODO: The typecheck should be done by the class itself, not by check_dtype\n        dtype = check_dtype(dtype, self.func, a, len(group_idx))\n        check_fill_value(fill_value, dtype, func=self.func)\n        input_dtype = type(a) if np.isscalar(a) else a.dtype\n        ret, _, _, _= self._initialize(flat_size, fill_value, dtype, input_dtype, group_idx.size)\n        group_idx = np.ascontiguousarray(group_idx)\n\n        sortidx = np.argsort(group_idx, kind='mergesort')\n        self._jitfunc(sortidx, group_idx, a, ret)\n\n        # Deal with ndimensional indexing\n        if ndim_idx > 1:\n            ret = ret.reshape(size, order=order)\n        return ret\n\n    def callable(self, nans=False):\n        \"\"\"Compile a jitted function and loop it over the sorted data.\"\"\"\n        jitfunc = nb.njit(self.func, nogil=True)\n\n        def _loop(sortidx, group_idx, a, ret):\n            size = len(ret)\n            group_idx_srt = group_idx[sortidx]\n            a_srt = a[sortidx]\n\n            indices = step_indices(group_idx_srt)\n            for i in range(len(indices) - 1):\n                start_idx, stop_idx =  indices[i], indices[i + 1]\n                ri = group_idx_srt[start_idx]\n                if ri < 0:\n                    raise ValueError(\"negative indices not supported\")\n                if ri >= size:\n                    raise ValueError(\"one or more indices in group_idx are too large\")\n                ret[ri] = jitfunc(a_srt[start_idx:stop_idx])\n        return nb.njit(_loop, nogil=True)\n\n\nclass Sum(AggregateOp):\n    forced_fill_value = 0\n\n    @staticmethod\n    def _inner(ri, val, ret, counter, mean):\n        counter[ri] = 0\n        ret[ri] += val\n\n\nclass Prod(AggregateOp):\n    forced_fill_value = 1\n\n    @staticmethod\n    def _inner(ri, val, ret, counter, mean):\n        counter[ri] = 0\n        ret[ri] *= val\n\n\nclass Len(AggregateOp):\n    forced_fill_value = 0\n\n    @staticmethod\n    def _inner(ri, val, ret, counter, mean):\n        counter[ri] = 0\n        ret[ri] += 1\n\n\nclass All(AggregateOp):\n    forced_fill_value = 1\n\n    @staticmethod\n    def _inner(ri, val, ret, counter, mean):\n        counter[ri] = 0\n        ret[ri] &= bool(val)\n\n\nclass Any(AggregateOp):\n    forced_fill_value = 0\n\n    @staticmethod\n    def _inner(ri, val, ret, counter, mean):\n        counter[ri] = 0\n        ret[ri] |= bool(val)\n\n\nclass Last(AggregateOp):\n    counter_fill_value = None\n\n    @staticmethod\n    def _inner(ri, val, ret, counter, mean):\n        ret[ri] = val\n\n\nclass First(Last):\n    reverse = True\n\n\nclass AllNan(AggregateOp):\n    forced_fill_value = 1\n\n    @staticmethod\n    def _inner(ri, val, ret, counter, mean):\n        counter[ri] = 0\n        ret[ri] &= val == val\n\n\nclass AnyNan(AggregateOp):\n    forced_fill_value = 0\n\n    @staticmethod\n    def _inner(ri, val, ret, counter, mean):\n        counter[ri] = 0\n        ret[ri] |= val != val\n\n\nclass Max(AggregateOp):\n    @staticmethod\n    def _inner(ri, val, ret, counter, mean):\n        if counter[ri]:\n            ret[ri] = val\n            counter[ri] = 0\n        elif ret[ri] < val:\n            ret[ri] = val\n\n\nclass Min(AggregateOp):\n    @staticmethod\n    def _inner(ri, val, ret, counter, mean):\n        if counter[ri]:\n            ret[ri] = val\n            counter[ri] = 0\n        elif ret[ri] > val:\n            ret[ri] = val\n\n\nclass ArgMax(AggregateOp):\n    mean_fill_value = np.nan\n\n    @staticmethod\n    def _valgetter(a, i):\n        return a[i], i\n\n    @staticmethod\n    def _inner(ri, val, ret, counter, mean):\n        cmp_val, arg = val\n        if counter[ri]:\n            mean[ri] = cmp_val\n            ret[ri] = arg\n            counter[ri] = 0\n        elif mean[ri] < cmp_val:\n            mean[ri] = cmp_val\n            ret[ri] = arg\n\n\nclass ArgMin(ArgMax):\n    @staticmethod\n    def _inner(ri, val, ret, counter, mean):\n        cmp_val, arg = val\n        if counter[ri]:\n            mean[ri] = cmp_val\n            ret[ri] = arg\n            counter[ri] = 0\n        elif mean[ri] > cmp_val:\n            mean[ri] = cmp_val\n            ret[ri] = arg\n\n\nclass Mean(Aggregate2pass):\n    forced_fill_value = 0\n    counter_fill_value = 0\n    counter_dtype = int\n\n    @staticmethod\n    def _inner(ri, val, ret, counter, mean):\n        counter[ri] += 1\n        ret[ri] += val\n\n    @staticmethod\n    def _2pass_inner(ri, ret, counter, mean, ddof):\n        return ret[ri] / counter[ri]\n\n\nclass Std(Mean):\n    mean_fill_value = 0\n\n    @staticmethod\n    def _inner(ri, val, ret, counter, mean):\n        counter[ri] += 1\n        mean[ri] += val\n        ret[ri] += val * val\n\n    @staticmethod\n    def _2pass_inner(ri, ret, counter, mean, ddof):\n        mean2 = mean[ri] * mean[ri]\n        return np.sqrt((ret[ri] - mean2 / counter[ri]) / (counter[ri] - ddof))\n\n\nclass Var(Std):\n    @staticmethod\n    def _2pass_inner(ri, ret, counter, mean, ddof):\n        mean2 = mean[ri] * mean[ri]\n        return (ret[ri] - mean2 / counter[ri]) / (counter[ri] - ddof)\n\n\nclass CumSum(AggregateNtoN, Sum):\n    pass\n\n\nclass CumProd(AggregateNtoN, Prod):\n    pass\n\n\nclass CumMax(AggregateNtoN, Max):\n    pass\n\n\nclass CumMin(AggregateNtoN, Min):\n    pass\n\n\ndef get_funcs():\n    funcs = dict()\n    for op in (Sum, Prod, Len, All, Any, Last, First, AllNan, AnyNan, Min, Max,\n               ArgMin, ArgMax, Mean, Std, Var,\n               CumSum, CumProd, CumMax, CumMin):\n        funcname = op.__name__.lower()\n        funcs[funcname] = op(funcname)\n        if funcname not in funcs_no_separate_nan:\n            funcname = 'nan' + funcname\n            funcs[funcname] = op(funcname, nans=True)\n    return funcs\n\n\n_impl_dict = get_funcs()\n_default_cache = {}\n\ndef aggregate(group_idx, a, func='sum', size=None, fill_value=0, order='C',\n              dtype=None, axis=None, cache=None, **kwargs):\n    func = get_func(func, aliasing, _impl_dict)\n    if not isstr(func):\n        if cache in (None, False):\n            aggregate_op = AggregateGeneric(func)\n        else:\n            if cache is True:\n                cache = _default_cache\n            aggregate_op = cache.setdefault(func, AggregateGeneric(func))\n        return aggregate_op(group_idx, a, size, fill_value, order, dtype, axis, **kwargs)\n    else:\n        func = _impl_dict[func]\n        return func(group_idx, a, size, fill_value, order, dtype, axis, **kwargs)\n\naggregate.__doc__ = \"\"\"\n    This is the numba implementation of aggregate.\n    \"\"\" + aggregate_common_doc\n\n\n@nb.njit(nogil=True, cache=True)\ndef step_count(group_idx):\n    \"\"\"Return the amount of index changes within group_idx.\"\"\"\n    cmp_pos = 0\n    steps = 1\n    if len(group_idx) < 1:\n        return 0\n    for i in range(len(group_idx)):\n        if group_idx[cmp_pos] != group_idx[i]:\n            cmp_pos = i\n            steps += 1\n    return steps\n\n\n@nb.njit(nogil=True, cache=True)\ndef step_indices(group_idx):\n    \"\"\"Return the edges of areas within group_idx, which are filled with the same value.\"\"\"\n    ilen = step_count(group_idx) + 1\n    indices = np.empty(ilen, np.int64)\n    indices[0] = 0\n    indices[-1] = group_idx.size\n    cmp_pos = 0\n    ri = 1\n    for i in range(len(group_idx)):\n        if group_idx[cmp_pos] != group_idx[i]:\n            cmp_pos = i\n            indices[ri] = i\n            ri += 1\n    return indices\n", "meta": {"hexsha": "55e799a39324891ebb7472778d06817fde338788", "size": 14729, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy_groupies/aggregate_numba.py", "max_stars_repo_name": "yulkang/numpy-groupies", "max_stars_repo_head_hexsha": "7fd58f8a488cf586af5150b2a9b96ce9bd703cad", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 154, "max_stars_repo_stars_event_min_datetime": "2015-07-16T08:47:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T08:11:41.000Z", "max_issues_repo_path": "numpy_groupies/aggregate_numba.py", "max_issues_repo_name": "yulkang/numpy-groupies", "max_issues_repo_head_hexsha": "7fd58f8a488cf586af5150b2a9b96ce9bd703cad", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 47, "max_issues_repo_issues_event_min_datetime": "2015-07-03T08:06:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-23T12:07:12.000Z", "max_forks_repo_path": "numpy_groupies/aggregate_numba.py", "max_forks_repo_name": "yulkang/numpy-groupies", "max_forks_repo_head_hexsha": "7fd58f8a488cf586af5150b2a9b96ce9bd703cad", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2015-07-03T09:09:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T08:39:39.000Z", "avg_line_length": 30.8784067086, "max_line_length": 111, "alphanum_fraction": 0.6109715527, "include": true, "reason": "import numpy,import numba", "num_tokens": 3833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.17718164883075424}}
{"text": "#!/usr/bin/env python\n\"\"\"\njust write from scratch ...\n\nso, we need:\n- an image encoder model. we'll use something like a lenet-5 cnn\n- sender network, that takes the encoding as input (?)\n- receiver network\n    - ... and we will dot product the output of the receiver with the various encoded images\n\"\"\"\nimport argparse, time, os, math, json, sys, contextlib, random\n\nimport torch\nfrom torch import autograd, nn, optim\nimport torch.nn.functional as F\nimport numpy as np\n\nfrom ulfs.utils import die\nfrom ulfs.params import Params\nfrom ulfs import name_utils, rl_common, tensor_utils,  utils, nn_modules, metrics\nfrom ulfs.runner_base_v1 import RunnerBase\nfrom ulfs.stats import Stats\n\nfrom data_code.clevr.three_shapes_dataset import Dataset\nfrom ilm.cnn_models import *\n\n@contextlib.contextmanager\ndef torch_random_state():\n    rnd_tch = torch.get_rng_state()\n    rnd_cuda = torch.cuda.get_rng_state()\n    np_state = np.random.get_state()\n    rand_state = random.getstate()\n    yield\n    torch.set_rng_state(rnd_tch)\n    torch.cuda.set_rng_state(rnd_cuda)\n    np.random.set_state(np_state)\n    random.setstate(rand_state)\n\nclass LangSenderModel(nn.Module):\n    \"\"\"\n    generator model\n    we'll use a differentiable teacher-forcing model, with fixed utterance length\n    \"\"\"\n    def __init__(\n            self, opt_name, embedding_size, vocab_size, utt_len, rnn_type, num_layers, input_size,\n            dropout\n        ):\n        self.embedding_size = embedding_size\n        self.utt_len = utt_len\n        self.vocab_size = vocab_size\n        self.rnn_type = rnn_type\n        self.num_layers = num_layers\n\n        super().__init__()\n        self.h_in = nn.Linear(input_size, embedding_size)\n        if rnn_type == 'SRU':\n            from sru import SRU\n            RNN = SRU\n        else:\n            RNN = getattr(nn, f'{rnn_type}')\n        rnn_params = {\n            'input_size': embedding_size,\n            'hidden_size': embedding_size,\n            'num_layers': num_layers,\n            'dropout': dropout\n        }\n        if rnn_type == 'SRU':\n            rnn_params['rescale'] = False\n            rnn_params['use_tanh'] = True\n        self.rnn = RNN(**rnn_params)\n        self.h_out = nn.Linear(embedding_size, vocab_size)\n        self.drop = nn.Dropout(dropout)\n\n        Opt = getattr(optim, opt_name)\n        self.opt = Opt(lr=0.001, params=self.parameters())\n\n    def forward(self, thoughts):\n        \"\"\"\n        thoughts ae [N][input_size]\n        \"\"\"\n        N, K = thoughts.size()\n        embs = self.h_in(thoughts)\n        embs = self.drop(embs)\n        device = embs.device\n\n        if self.rnn_type in ['SRU']:\n            h = torch.zeros(self.num_layers, N, self.embedding_size, dtype=torch.float32, device=device)\n            h[0] = embs\n        elif self.rnn_type in ['GRU']:\n            h = torch.zeros(self.num_layers, N, self.embedding_size, dtype=torch.float32, device=device)\n            h[0] = embs\n        else:\n            raise Exception(f'unrecognized rnn type {self.rnn_type}')\n\n        fake_input = torch.zeros(self.utt_len, N, self.embedding_size, dtype=torch.float32, device=device)\n        if self.rnn_type == 'SRU':\n            output, state = self.rnn(fake_input, h)\n        elif self.rnn_type in ['GRU']:\n            output, h = self.rnn(fake_input, h)\n        else:\n            raise Exception(f'rnn type {self.rnn_type} not recognized')\n        utts = self.h_out(output)\n        return utts\n\nclass LangReceiverModel(nn.Module):\n    def __init__(\n            self, opt_name, embedding_size, vocab_size, utt_len,\n            rnn_type, dropout, num_layers, output_size\n        ):\n        self.rnn_type = rnn_type\n        self.embedding_size = embedding_size\n\n        super().__init__()\n        self.embedding = nn_modules.EmbeddingAdapter(vocab_size, embedding_size)\n        if rnn_type == 'SRU':\n            from sru import SRU\n            RNN = SRU\n        else:\n            RNN = getattr(nn, f'{rnn_type}')\n        self.rnn = RNN(\n            input_size=embedding_size,\n            hidden_size=embedding_size,\n            num_layers=num_layers\n        )\n        self.h_out = nn.Linear(embedding_size, output_size)\n        Opt = getattr(optim, opt_name)\n        self.opt = Opt(lr=0.001, params=self.parameters())\n\n    def forward(self, utts, do_predict_correct=False):\n        embs = self.embedding(utts)\n        seq_len, batch_size, embedding_size = embs.size()\n        output, state = self.rnn(embs)\n        state = state[-1]\n        x = self.h_out(state)\n        return x\n\nclass SenderPathway(nn.Module):\n    def __init__(self, opt_name, cnn, lang_sender, clip_grad):\n        super().__init__()\n        self.cnn = cnn\n        self.lang_sender = lang_sender\n        self.clip_grad = clip_grad\n\n        Opt = getattr(optim, opt_name)\n        self.params = self.parameters()\n        self.opt = Opt(lr=0.001, params=self.params)\n\n    def forward(self, images_t):\n        \"\"\"\n        assumes that images_t just contains a batch of single images, not multipel images per example\n        \"\"\"\n        image_enc = self.cnn(images_t)\n        utt_logits = self.lang_sender(image_enc)\n        return utt_logits\n\n    def sup_train_batch(self, images, utts):\n        utts_logits = self(images)\n\n        # logits = self.model(meanings)\n        _, utts_pred = utts_logits.max(dim=-1)\n        correct = utts_pred == utts\n        acc = correct.float().mean().item()\n\n        crit = nn_modules.GeneralCrossEntropyLoss()\n        loss = crit(utts_logits, utts)\n        self.opt.zero_grad()\n        loss.backward()\n        if self.clip_grad is not None and self.clip_grad > 0:\n            torch.nn.utils.clip_grad_norm_(self.params, self.clip_grad)\n        self.opt.step()\n        return loss.item(), acc\n\nclass ReceiverPathway(nn.Module):\n    def __init__(self, opt_name, cnn, lang_receiver, clip_grad):\n        super().__init__()\n        self.cnn = cnn\n        self.lang_receiver = lang_receiver\n        self.clip_grad = clip_grad\n\n        Opt = getattr(optim, opt_name)\n        self.params = self.parameters()\n        self.opt = Opt(lr=0.001, params=self.params)\n\n    def forward(self, utts, images):\n        \"\"\"\n        we assume images are all the receiver images, ie the goal image, and some distractors\n        the sender image is not included in images\n        \"\"\"\n        lang_enc = self.lang_receiver(utts)  # [N][E]\n\n        d = images.size()\n        images_flat_t = tensor_utils.merge_dims(images, 0, 1)  # [M * N][C][H][W]\n        images_enc_flat = self.cnn(images_flat_t)   # [M * N][E]\n        images_enc = tensor_utils.split_dim(images_enc_flat, 0, d[0], d[1])  # [M][N][E]\n        lang_enc_flat_exp = lang_enc.unsqueeze(0).expand_as(images_enc)  # [M][N][E]\n        lang_enc_flat_exp = tensor_utils.merge_dims(lang_enc_flat_exp.contiguous(), 0, 1)   # [M * N][E]\n\n        dp_left = lang_enc_flat_exp.unsqueeze(-2)  # [M * N][1][E]\n        dp_right = images_enc_flat.unsqueeze(-1)   # [M * N][E][1]\n        dp = torch.bmm(dp_left, dp_right)     # [M * N][1][1]\n        dp = dp.view(d[0], d[1])   # [M][N]\n        dp = dp.transpose(0, 1)   # [N][M]\n        return dp\n\n    def sup_train_batch(self, images, utts):\n        \"\"\"\n        we assume a batch of single images, no distractors added\n        \"\"\"\n        d = images.size()\n        with autograd.no_grad():\n            images_enc = self.cnn(images)   # [N][E]\n\n        lang_enc = self.lang_receiver(utts)  # [N][E]\n        crit = nn.MSELoss()\n        loss = crit(lang_enc, images_enc)\n        self.opt.zero_grad()\n        loss.backward()\n        if self.clip_grad is not None and self.clip_grad > 0:\n            torch.nn.utils.clip_grad_norm_(self.params, self.clip_grad)\n        self.opt.step()\n        acc = 0  # placeholder\n        return loss.item(), acc\n\nclass Agent(nn.Module):\n    def __init__(self, p, image_size, img_embedding_size):\n        super().__init__()\n        self.p = p\n        self.img_embedding_size = img_embedding_size\n\n        CNN = globals()[p.conv_class]\n        # share cnn between sender and receiver for now (can try unsharing later)\n        self.cnn = CNN(dropout=p.dropout, num_layers=p.num_conv_layers, image_size=image_size)\n        self.lang_sender = LangSenderModel(\n            opt_name=p.opt,\n            embedding_size=p.embedding_size,\n            vocab_size=p.vocab_size,\n            utt_len=p.utt_len,\n            rnn_type=p.rnn_type,\n            num_layers=p.num_layers,\n            input_size=self.img_embedding_size,\n            dropout=p.dropout\n        )\n        self.lang_receiver = LangReceiverModel(\n            opt_name=p.opt,\n            embedding_size=p.embedding_size,\n            vocab_size=p.vocab_size,\n            utt_len=p.utt_len,\n            rnn_type=p.rnn_type,\n            dropout=p.dropout,\n            num_layers=p.num_layers,\n            output_size=self.img_embedding_size\n        )\n        self.sender_pathway = SenderPathway(opt_name=p.opt, cnn=self.cnn, lang_sender=self.lang_sender, clip_grad=p.clip_grad)\n        self.receiver_pathway = ReceiverPathway(opt_name=p.opt, cnn=self.cnn, lang_receiver=self.lang_receiver, clip_grad=p.clip_grad)\n        if p.enable_cuda:\n            self.lang_sender = self.lang_sender.cuda()\n            self.lang_receiver = self.lang_receiver.cuda()\n            self.cnn = self.cnn.cuda()\n        Opt = getattr(optim, p.opt)\n        self.opt_both = Opt(\n            lr=0.001,\n            params=list(self.lang_sender.parameters()) + list(self.lang_receiver.parameters()) + list(self.cnn.parameters())\n        )\n\n    def state_dict(self):\n        return {\n            'lang_sender_state': self.lang_sender.state_dict(),\n            'lang_receiver_state': self.lang_receiver.state_dict(),\n            'cnn_state': self.cnn.state_dict(),\n            'opt_both_state': self.opt_both.state_dict()\n        }\n\n    def load_state_dict(self, statedict):\n        self.lang_sender.load_state_dict(statedict['lang_sender_state'])\n        self.lang_receiver.load_state_dict(statedict['lang_receiver_state'])\n        self.opt_both.load_state_dict(statedict['opt_both_state'])\n\nclass SoftmaxLink(object):\n    def __init__(self, p):\n        pass\n\n    def sample_utterances(self, utt_probs):\n        return utt_probs\n\n    def sample_image_choice(self, dp):\n        return dp\n\n    def calc_loss(self, image_choice):\n        dp = image_choice\n        batch_size, _ = dp.size()\n        crit = nn.CrossEntropyLoss()\n        loss = crit(dp, torch.zeros(batch_size, dtype=torch.int64, device=dp.device))\n        loss_v = loss.item()\n        return loss, loss_v\n\nclass RLLink(object):\n    def __init__(self, p):\n        self.s_ent = p.s_ent\n        self.r_ent = p.r_ent\n\n    def sample_utterances(self, utt_probs, training):\n        # print('rllink training', self.training)\n        self.s_sender = rl_common.draw_categorical_sample(\n            action_probs=utt_probs,\n            batch_idxes=None,\n            training=training\n        )\n        utts = self.s_sender.actions.detach()\n        return utts\n\n    def sample_image_choice(self, training, dp):\n        self.s_recv = rl_common.draw_categorical_sample(\n            action_probs=dp,\n            batch_idxes=None,\n            training=training\n        )\n        return (self.s_sender.greedy_matches, self.s_recv.greedy_matches), self.s_recv.actions\n\n    def calc_loss(self, image_choice, training):\n        # s_recv = image_choice\n        s_recv = self.s_recv\n        rewards = (s_recv.actions == 0).float()\n\n        # for reporting purposes:\n        loss_v = - rewards.mean().item()\n\n        # lets baseline the reward first\n        rewards_mean = rewards.mean().item()\n        rewards_std = rewards.std().item()\n        rewards = rewards - rewards_mean\n        if rewards_std > 1e-1:\n            rewards = rewards / rewards_std\n\n        if training:\n            rl_loss = self.s_sender.calc_loss(rewards) + s_recv.calc_loss(rewards)\n            loss_all = rl_loss\n            ent_loss = 0\n            if self.s_ent is not None and self.s_ent > 0:\n                ent_loss -= self.s_sender.entropy * self.s_ent\n            if self.r_ent is not None and self.r_ent > 0:\n                ent_loss -= s_recv.entropy * self.r_ent\n            loss_all += ent_loss\n        else:\n            # rl_loss = 0\n            loss_all = 0\n\n        loss = loss_all\n        return loss, loss_v\n\nclass RefTaskGame(object):\n    def __init__(self, sender_pathway, receiver_pathway, link):\n        self.sender_pathway = sender_pathway\n        self.receiver_pathway = receiver_pathway\n        self.link = link\n\n    def forward(self, images_t, training):\n        utt_logits = self.sender_pathway(images_t[0])\n        utt_probs = F.softmax(utt_logits, dim=-1)\n\n        utts = self.link.sample_utterances(utt_probs, training=training)\n\n        self.dp = self.receiver_pathway(utts=utts, images=images_t[1:])\n        self.dp = F.softmax(self.dp, dim=-1)\n\n        (sender_greedy, receiver_greedy), pred = self.link.sample_image_choice(training=training, dp=self.dp)\n\n        # _, pred = self.dp.max(dim=-1)\n        acc = (pred == 0).float().mean().item()\n        return (sender_greedy, receiver_greedy), utts.detach(), acc\n\n    def calc_loss(self, training):\n        loss, loss_v = self.link.calc_loss(self.dp, training=training)\n        # return (sender_greedy, receiver_greedy), loss, loss_v\n        return loss, loss_v\n\ndef batched_run_nograd(params, model, inputs, batch_size, input_batch_dim, output_batch_dim):\n    \"\"\"\n    assumes N is multiple of batch_size\n    \"\"\"\n    p = params\n    N = inputs.size(input_batch_dim)\n    num_batches = (N + batch_size - 1) // batch_size\n    outputs = None\n    count = 0\n    for b in range(num_batches):\n        b_start = b * batch_size\n        b_end = min(b_start + batch_size, N)\n        count += (b_end - b_start)\n        input_batch = inputs.narrow(dim=input_batch_dim, start=b_start, length=b_end - b_start)\n        if p.enable_cuda:\n            input_batch = input_batch.cuda()\n        with torch.no_grad():\n            output_batch = model(input_batch).detach().cpu()\n        if outputs is None:\n            out_size_full = list(output_batch.size())\n            out_size_full[output_batch_dim] = N\n            outputs = torch.zeros(*out_size_full, dtype=output_batch.dtype, device='cpu')\n        out_narrow = outputs.narrow(dim=output_batch_dim, start=b_start, length=b_end - b_start)\n        out_narrow[:] = output_batch\n    assert count == N\n    return outputs\n\nclass Runner(RunnerBase):\n    def __init__(self):\n        super().__init__(\n            save_as_statedict_keys=['teacher'],\n            additional_save_keys=[],\n            step_key='training_step'\n        )\n\n    def setup(self, p):\n        if p.seed is not None:\n            torch.manual_seed(p.seed)\n            np.random.seed(p.seed)\n            random.seed(p.seed)\n            torch.backends.cudnn.deterministic = True\n            print('seeding torch and numpy using ', p.seed)\n\n        self.dataset = Dataset(data_dir=p.data_dir)\n\n        # determine image size from dataset\n        images_t, _ = self.dataset.sample_batch(batch_size=2)\n        self.image_size = images_t.size(-1)\n        print('self.image_size', self.image_size)\n\n        CNN = globals()[p.conv_class]\n\n        # determine output size from cnn:\n        _cnn = CNN(dropout=p.dropout, num_layers=p.num_conv_layers, image_size=self.image_size)  # share cnn across everything\n        print(_cnn.convnet)\n        print('convnet output size', _cnn.output_size)\n        if p.enable_cuda:\n            _cnn = _cnn.cuda()\n        if p.enable_cuda:\n            images_t = images_t.cuda()\n        with autograd.no_grad():\n            enc_images_t = _cnn(images_t[0])\n        _, self.img_embedding_size = enc_images_t.size()\n        print('self.img_embedding_size', self.img_embedding_size)\n\n\n        self.teacher = Agent(p=p, img_embedding_size=self.img_embedding_size, image_size=self.image_size)\n\n        Link = globals()[f'{p.link}Link']\n        self.link = Link(p=p)\n\n        self.sup_train_N = int(self.dataset.N_train * p.sup_train_frac)\n        print('sup_train_N', self.sup_train_N)\n\n    def step(self, p):\n        training_step = self.training_step\n        step = self.training_step\n        render = self.should_render()\n        link = self.link\n\n        sup_images = self.dataset.sample_images(self.sup_train_N)\n        if p.enable_cuda:\n            sup_images = sup_images.cuda()\n\n        print('generating teacher utterances...', end='', flush=True)\n        _gen_start = time.time()\n        self.teacher.eval()\n        # with autograd.no_grad():\n        #     sup_images_enc = self.teacher.cnn(sup_images).detach()\n        sup_utts_logits = batched_run_nograd(\n            params=p,\n            model=self.teacher.sender_pathway,\n            inputs=sup_images,\n            batch_size=p.batch_size,\n            input_batch_dim=0,\n            output_batch_dim=1\n        )\n        # self.teacher.train()\n        # print('sup_utts_logits.size()', sup_utts_logits.size())\n        _, sup_utts = sup_utts_logits.max(dim=-1)\n        # print('sup_utts.size()', sup_utts.size())\n        print(' done in %.0f seconds' % (time.time() - _gen_start))\n\n        student = Agent(p=p, img_embedding_size=self.img_embedding_size, image_size=self.image_size)\n\n        # and then train each half supervised on this data\n        # sender first...\n        sup_sender_epochs = 0\n        sup_receiver_epochs = 0\n        sup_sender_acc = 0\n        sup_receiver_acc = 0\n        sup_sender_time = 0\n        sup_receiver_time = 0\n        if (\n                (p.sup_acc is not None and p.sup_acc > 0)\n                or (p.sup_ksteps is not None and p.sup_ksteps > 0)\n            ) and (step > 0 or not p.train_e2e):\n            for (agent_str, pathway) in [('send', student.sender_pathway), ('recv', student.receiver_pathway)]:\n                # print('sup training on' + agent_str)\n                _epoch = 0\n                _sup_start = time.time()\n                _last_print = time.time()\n                sup_stats = Stats([\n                    'loss_sum',\n                    'acc_sum',\n                    'episodes_count',\n                ])\n                while True:\n                    b_idxes = torch.from_numpy(np.random.choice(self.sup_train_N, p.batch_size, replace=False))\n                    b_utts = sup_utts[:, b_idxes]\n                    b_images = sup_images[b_idxes]\n                    if p.enable_cuda:\n                        b_utts = b_utts.cuda()\n                        b_images = b_images.cuda()\n                    b_loss, b_acc = pathway.sup_train_batch(images=b_images, utts=b_utts)\n                    sup_stats.episodes_count += 1\n                    sup_stats.loss_sum += b_loss\n                    sup_stats.acc_sum += b_acc\n\n                    _epoch += 1\n                    _done_training = False\n                    if p.sup_acc is not None and epoch_acc >= p.sup_acc:\n                        # print('done sup training (reason: acc)')\n                        _done_training = True\n                    if p.sup_ksteps is not None and _epoch >= p.sup_ksteps * 1000:\n                        # print('done sup training (reason: steps)')\n                        _done_training = True\n                    if _done_training or time.time() - _last_print >= 30.0:\n                        _elapsed_time = time.time() - _sup_start\n                        _loss = sup_stats.loss_sum / sup_stats.episodes_count\n                        _acc = sup_stats.acc_sum / sup_stats.episodes_count\n                        log_dict = {\n                            'record_type': f'sup_{agent_str}',\n                            'agent': agent_str,\n                            'ilm_epoch': step,\n                            'epoch': _epoch,\n                            'sps': int(_epoch / _elapsed_time),\n                            'sup_time': int(_elapsed_time),\n                            'loss': _loss,\n                            'acc': _acc,\n                        }\n                        formatstr = (\n                            '{record_type} g={ilm_epoch} e={epoch} '\n                            't={sup_time:.0f} '\n                            'sps={sps:.0f} '\n                            'loss={loss:.3f} '\n                            'acc={acc:.3f} '\n                        )\n                        self.print_and_log(log_dict, formatstr=formatstr)\n                        sup_stats.reset()\n                        _last_print = time.time()\n                    if _done_training:\n                        # print('done training for pathway', pathway.__class__.__name__)\n                        break\n                if pathway == student.sender_pathway:\n                    sup_sender_epochs = _epoch\n                    sup_sender_acc = _acc\n                    sup_sender_time = time.time() - _sup_start\n                elif pathway == student.receiver_pathway:\n                    sup_receiver_epochs = _epoch\n                    sup_receiver_acc = _acc\n                    sup_receiver_time = time.time() - _sup_start\n                else:\n                    raise Exception('invalid pathway value')\n            # print('done supervised training')\n\n        e2e_time = 0\n        if p.train_e2e:\n            # then train end to end for a bit, as decoder-encoder, looking at reconstruction accuracy\n            # we'll do this on the same meanings as we got from the teacher? or different ones? or\n            # just rnadomly sampled from everything except heldout?\n            # maybe train on everything except holdout?\n            last_print = time.time()\n            _e2e_start = time.time()\n            e2e_stats = Stats([\n                'episodes_count',\n                'e2e_loss_sum',\n                'e2e_acc_sum',\n                'sender_greedy_sum',\n                'receiver_greedy_sum',\n            ])\n            epoch = 0\n            student.train()\n            ref_task_game = RefTaskGame(\n                sender_pathway=student.sender_pathway, receiver_pathway=student.receiver_pathway, link=link)\n            student_params = student.parameters()\n            while True:\n                images_t, labels = self.dataset.sample_batch(batch_size=p.batch_size)\n                if p.enable_cuda:\n                    images_t, labels = images_t.cuda(), labels.cuda()\n\n                (sender_greedy, receiver_greedy), _, acc = ref_task_game.forward(images_t, training=True)\n                loss, loss_v = ref_task_game.calc_loss(training=True)\n\n                e2e_stats.e2e_loss_sum += loss_v\n                e2e_stats.e2e_acc_sum += acc\n                e2e_stats.sender_greedy_sum += sender_greedy\n                e2e_stats.receiver_greedy_sum += receiver_greedy\n                e2e_stats.episodes_count += 1\n\n                student.opt_both.zero_grad()\n                loss.backward()\n                if p.clip_grad is not None and p.clip_grad > 0:\n                    torch.nn.utils.clip_grad_norm_(student_params, p.clip_grad)\n                student.opt_both.step()\n\n                _done_training = False\n                if p.e2e_acc is not None and acc >= p.e2e_acc:\n                    # print('reached target e2e acc %.3f' % acc, ' => breaking')\n                    _done_training = True\n                if p.e2e_ksteps is not None and epoch >= p.e2e_ksteps * 1000:\n                    # print('reached target e2e step', epoch, ' => breaking')\n                    _done_training = True\n                save_e2e = p.save_e2e_everyk is not None and p.save_e2e_everyk > 0 and (epoch % (p.save_e2e_everyk * 1000)) == 0\n                if time.time() - last_print >= self.render_every_seconds or _done_training or save_e2e:\n                    holdout_acc_sum = 0\n                    holdout_ep_count = 0\n                    holdout_rho_sum = 0\n                    holdout_send_greed_sum = 0\n                    holdout_recv_greed_sum = 0\n                    # self.teacher.lang_sender.eval()\n                    student.eval()\n                    ho_utts_l = []\n                    ho_labels_l = []\n                    with torch_random_state():\n                        for i, (batch_image, batch_labels) in enumerate(self.dataset.iter_holdout(batch_size=p.batch_size)):\n                            if p.enable_cuda:\n                                batch_image = batch_image.cuda()\n                                batch_labels = batch_labels.cuda()\n                            with autograd.no_grad():\n                                _, utts, acc = ref_task_game.forward(batch_image, training=False)\n                                if utts.dtype == torch.float32:\n                                    _, utts = utts.max(dim=-1)\n                                holdout_acc_sum += acc\n                                holdout_ep_count += 1\n                                utts = utts.transpose(0, 1)\n                                holdout_rho_sum += metrics.topographic_similarity(utts, batch_labels)\n                            ho_utts_l.append(utts)\n                            ho_labels_l.append(batch_labels)\n                    ho_utts = torch.cat(ho_utts_l)\n                    ho_labels = torch.cat(ho_labels_l)\n                    if save_e2e:\n                        samples_filename = p.utt_samples.format(epoch=epoch)\n                        with open(samples_filename, 'wb') as f:\n                            torch.save({'samples': {'utts': ho_utts, 'labels': ho_labels}, 'meta': p.__dict__}, f)\n                        print('saved samples to ' + samples_filename)\n                        model_save = p.model_save.format(epoch=epoch)\n                        self.save_to(model_save)\n                        print('saved model to ' + model_save)\n                    student.train()\n                    # self.teacher.lang_sender.train()\n                    rho = holdout_rho_sum / holdout_ep_count\n                    holdout_acc = holdout_acc_sum / holdout_ep_count\n                    acc = e2e_stats.e2e_acc_sum / e2e_stats.episodes_count\n                    loss = e2e_stats.e2e_loss_sum / e2e_stats.episodes_count\n                    sender_greedy = e2e_stats.sender_greedy_sum / e2e_stats.episodes_count\n                    receiver_greedy = e2e_stats.receiver_greedy_sum / e2e_stats.episodes_count\n\n                    _elapsed_time = time.time() - _e2e_start\n                    log_dict = {\n                        'record_type': 'e2e',\n                        'ilm_epoch': step,\n                        'epoch': epoch,\n                        'sps': int(epoch / _elapsed_time),\n                        'e2e_time': int(_elapsed_time),\n                        'acc': acc,\n                        'holdout_acc': holdout_acc,\n                        'rho': rho,\n                        'loss': loss,\n                        'send_greed': sender_greedy,\n                        'recv_greed': receiver_greedy,\n                    }\n                    formatstr = (\n                        '{record_type} '\n                        'g={ilm_epoch} '\n                        'e={epoch} '\n                        't={e2e_time:.0f} '\n                        'sps={sps:.0f} '\n                        'acc={acc:.3f} '\n                        'loss={loss:.3f} '\n                        'ho_acc={holdout_acc:.3f} '\n                        'rho={rho:.3f} '\n                        's_g={send_greed:.3f} '\n                        'r_g={recv_greed:.3f} '\n                    )\n                    self.print_and_log(log_dict, formatstr=formatstr)\n\n                    e2e_stats.reset()\n                    last_print = time.time()\n                if _done_training:\n                    break\n                epoch += 1\n            e2e_time = time.time() - _e2e_start\n            e2e_acc = acc\n            e2e_holdout_acc = holdout_acc\n            e2e_rho = rho\n            e2e_send_greedy = sender_greedy\n            e2e_recv_greedy = receiver_greedy\n\n            self.teacher = student\n\n        if True:\n            log_dict = {\n                'type': 'ilm',\n                'sps': int(step / (time.time() - self.start_time)),\n                'elapsed_time': time.time() - self.start_time,\n                'e2e_time': e2e_time,\n                'e2e_acc': e2e_acc,\n                'e2e_holdout_acc': e2e_holdout_acc,\n                'e2e_rho': e2e_rho,\n                'e2e_send_greedy': e2e_send_greedy,\n                'e2e_recv_greedy': e2e_recv_greedy,\n                'sup_sender_epochs': sup_sender_epochs,\n                'sup_receiver_epochs': sup_receiver_epochs,\n                'sup_sender_acc': sup_sender_acc,\n                'sup_receiver_acc': sup_receiver_acc,\n                'sup_sender_time': sup_sender_time,\n                'sup_receiver_time': sup_receiver_time,\n            }\n\n            formatstr = (\n                '{type} '\n                'g={training_step} '\n                't={elapsed_time:.0f} '\n                'sps={sps:.0f}\\n'\n                '    sup_snd[e={sup_sender_epochs} acc={sup_sender_acc:.3f} t={sup_sender_time:.0f}]\\n'\n                '    sup_rcv[e={sup_receiver_epochs} acc={sup_receiver_acc:.3f} t={sup_receiver_time:.0f}]\\n'\n                '    e2e[acc={e2e_acc:.3f} t={e2e_time:.0f} sg={e2e_send_greedy:.3f} rg={e2e_recv_greedy:.3f}]\\n'\n                'ho_acc={e2e_holdout_acc:.3f} '\n                'rho={e2e_rho:.3f} '\n            )\n            self.print_and_log(log_dict, formatstr=formatstr)\n        if p.max_gen is not None and step + 1 >= p.max_gen:\n            print('reached max generations', p.max_gen, '=> terminating')\n            self.finish = True\n\nif __name__ == '__main__':\n    utils.clean_argv()\n    runner = Runner()\n\n    runner.add_param('--ds-ref', type=str)\n    runner.add_param('-s', type=int, help='num shapes')\n    runner.add_param('--opt', type=str, default='RMSprop')\n    runner.add_param('--conv-class', type=str, default='CNNALPoolingAll')\n    runner.add_param('--num-conv-layers', type=int, default=8)\n    runner.add_param('--data-family', type=str, default='objects_gl')\n    runner.add_param('--data-dir', type=str, default='~/data/{data_family}/{ds_ref}')\n    runner.add_param('--utt-samples', type=str, default='tmp/{ref}_samples_{epoch}.pth')\n    runner.add_param('--model-save', type=str, default='tmp/{ref}_model_{epoch}.pth')\n\n    runner.add_param('--seed', type=int)\n    runner.add_param('--batch-size', type=int, default=32)\n    runner.add_param('--link', type=str, default='RL')\n    runner.add_param('--clip-grad', type=float, default=0)\n    runner.add_param('--sup-acc', type=float)\n    runner.add_param('--e2e-acc', type=float)\n    runner.add_param('--ilm', type=str)\n    runner.add_param('--max-gen', type=int)\n    runner.add_param('-f', type=float, default=0.4, help='supervised train fraction')\n    runner.add_param('--no-train-e2e', action='store_true')\n    runner.add_param('--save-e2e-everyk', type=int, default=100)\n\n    runner.add_param('--embedding-size', type=int, default=50)\n    runner.add_param('--vocab-size', type=int, default=100, help='excludes any terminator')\n    runner.add_param('--model', type=str, default='RNN')\n    runner.add_param('--rnn-type', type=str, default='GRU')\n    runner.add_param('--num-layers', type=int, default=1)\n    runner.add_param('--dropout', type=float, default=0.5)\n    runner.add_param('--utt-len', type=int, default=6)\n    runner.add_param('--nle', type=str, default='2,3', help='negative log10 entropy reg')\n\n    runner.parse_args()\n    args = runner.params\n    if args.ilm is not None:\n        args.e2e_ksteps, args.sup_ksteps = [float(v) for v in args.ilm.split(',')]\n    else:\n        args.e2e_ksteps, args.sup_ksteps = None, None\n    del args.__dict__['ilm']\n    args.utt_samples = args.utt_samples.format(ref=args.ref, epoch='{epoch}')\n    args.model_save = args.model_save.format(ref=args.ref, epoch='{epoch}')\n    args.s_ent, args.r_ent = [math.pow(10, -float(v)) for v in args.nle.split(',')]\n    print(f'ent reg {args.s_ent:.1e} {args.r_ent:.1e}')\n    del args.__dict__['nle']\n    args.shapes = args.s\n    del args.__dict__['s']\n    args.sup_train_frac = args.f\n    del args.__dict__['f']\n    if args.shapes is not None:\n        args.ds_ref = {\n            1: 'dsd39_1sb',\n            2: 'dsd37_2s_ho2',\n            3: 'dsd38_3s_ho2'\n            # 2: 'dsd32_twoshape_123',\n            # 3: 'dsd33_threeshapes_123'\n        }[args.shapes]\n    assert args.ds_ref is not None\n    utils.reverse_args(runner.params, 'no_train_e2e', 'train_e2e')\n    runner.params.data_dir = runner.params.data_dir.format(**runner.params.__dict__)\n    print('runner.params', runner.params)\n    runner.setup_base()\n    runner.run_base()\n", "meta": {"hexsha": "37e9fe7b63d9c98b5805a4d03e458c3a2eb2e667", "size": 32580, "ext": "py", "lang": "Python", "max_stars_repo_path": "ilm/ref_task.py", "max_stars_repo_name": "asappresearch/neural-ilm", "max_stars_repo_head_hexsha": "fd7e09960525391f4084a5753429deabd7ff00aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ilm/ref_task.py", "max_issues_repo_name": "asappresearch/neural-ilm", "max_issues_repo_head_hexsha": "fd7e09960525391f4084a5753429deabd7ff00aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ilm/ref_task.py", "max_forks_repo_name": "asappresearch/neural-ilm", "max_forks_repo_head_hexsha": "fd7e09960525391f4084a5753429deabd7ff00aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-25T04:42:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-25T04:43:06.000Z", "avg_line_length": 40.878293601, "max_line_length": 134, "alphanum_fraction": 0.5667894414, "include": true, "reason": "import numpy", "num_tokens": 7580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.3311197396289915, "lm_q1q2_score": 0.17718164745297058}}
{"text": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom __future__ import division\nimport numpy as np\n\nfrom datetime import datetime\nfrom lib.ReservoirNetworkController import ReservoirNetworkController\nfrom lib.AtlasJointsInfo import AtlasJointsInfo\n\n\nclass SpikingNeuralNetwork:\n    INPUT_LAYER_SIZE = 28\n    OUTPUT_LAYER_SIZE = 28\n    SIMULATION_TIME_INTERVAL = 15 # msec\n    RESERVOIR_NETWORK_SIZE = 500\n    MAX_INPUT_RATE = 1000\n    MIN_INPUT_RATE = 50\n\n    def __init__(self):\n        self._output_layer_activations = np.zeros(self.OUTPUT_LAYER_SIZE)\n        self._hidden_layer_weights = np.zeros([self.RESERVOIR_NETWORK_SIZE,\n                                               self.OUTPUT_LAYER_SIZE])\n        self._hidden_layer_neuron_mapping =  \\\n            self._initialize_hidden_layer_neuron_mapping()\n        for i in xrange(len(self._hidden_layer_neuron_mapping)):\n            one_neuron_mapping = self._hidden_layer_neuron_mapping[i]\n            for c in xrange(len(one_neuron_mapping)):\n                hidden_neuron_index = one_neuron_mapping[c]\n                self._hidden_layer_weights[hidden_neuron_index][i] = \\\n                    np.random.rand(1)[0]\n        self._hidden_layer_biases = np.random.rand(self.OUTPUT_LAYER_SIZE)\n        self._joints_info_provider = AtlasJointsInfo()\n        self._input_layer = np.zeros(self.INPUT_LAYER_SIZE)\n        self._hidden_layer = self._initialize_reservoir_network()\n        self._output_layer = np.zeros(self.OUTPUT_LAYER_SIZE)\n\n    def _initialize_reservoir_network(self):\n        snn_controller = ReservoirNetworkController(\n                self.RESERVOIR_NETWORK_SIZE, self.INPUT_LAYER_SIZE)\n        return snn_controller\n\n    def process_input(self, state):\n        # TODO so far we are using only position, eventually should use more\n        # parameters\n        start_time = datetime.now()\n        self._set_position_values(self._normalize_position_input(state.position))\n        stop_time = datetime.now()\n        delta = stop_time - start_time\n        print \"converting input in: \" + str(delta.seconds) + \".\" + str(\n                delta.microseconds/1000)\n        start_time = stop_time\n        self._apply_poisson_group_input()\n        stop_time = datetime.now()\n        delta = stop_time - start_time\n        print \"applying Poisson group in: \" + str(delta.seconds) + \".\" + str(\n                delta.microseconds/1000)\n        start_time = stop_time\n        self._hidden_layer.run_simulation(self.SIMULATION_TIME_INTERVAL)\n        stop_time = datetime.now()\n        delta = stop_time - start_time\n        print \"simulation running in: \" + str(delta.seconds) + \".\" + str(\n                delta.microseconds/1000)\n        start_time = stop_time\n        self._decode_snn_output()\n        stop_time = datetime.now()\n        delta = stop_time - start_time\n        print \"decoding output in: \" + str(delta.seconds) + \".\" + str(\n                delta.microseconds/1000)\n\n    def _set_position_values(self, position):\n        for i in xrange(len(position)):\n            self._input_layer[i] = position[i]\n\n    def _normalize_position_input(self, position_input):\n        result = []\n        for i in xrange(len(position_input)):\n            result.append((position_input[i] -\n                           self._joints_info_provider.get_min_value_for_joint(\n                               i)) / (\n                              self._joints_info_provider.get_max_value_for_joint(\n                                  i) -\n                              self._joints_info_provider.get_min_value_for_joint(\n                                  i)))\n        # output values are between 0 and 1\n        return result\n\n    def get_input_layer_values(self):\n        return self._input_layer\n\n    def _apply_poisson_group_input(self):\n        firing_rates = np.zeros(len(self._input_layer))\n        for i in xrange(len(self._input_layer)):\n            firing_rates[i] = self._convert_to_rate(self._input_layer[i])\n        self._hidden_layer.set_poisson_group_rates(firing_rates)\n\n    def _convert_to_rate(self, input):\n        # input values are between 0 and 1 (after normalization)\n        rate = input*(self.MAX_INPUT_RATE - self.MIN_INPUT_RATE) + \\\n               self.MIN_INPUT_RATE\n        return rate\n\n    def _decode_snn_output(self):\n        firing_rates = self._hidden_layer.get_reservoir_firing_rates_output()\n        # print \"SpikingNeuralNetwork._decode_snn_output(): \" \\\n        #       \"np.amax(firing_rates) = \" + str(\n        #         np.amax(firing_rates))\n        # print \"SpikingNeuralNetwork._decode_snn_output(): \" \\\n        #       \"np.amin(firing_rates) = \" + str(\n        #         np.amin(firing_rates))\n        self._compute_activations_from_reservoir(firing_rates)\n        for i in xrange(self.OUTPUT_LAYER_SIZE):\n            self._output_layer[i] = self._output_layer_activations[i]\n\n    def _normalize_firing_rates_output(self, input_value):\n        max_value = self.MAX_INPUT_RATE\n        min_value = self.MIN_INPUT_RATE\n        result = []\n        for i in xrange(len(input_value)):\n            result.append((input_value[i] - min_value) / (max_value - min_value))\n        return result\n\n    def get_output_layer_values(self):\n        return self._output_layer\n\n    def _compute_activations_from_reservoir(self, firing_rates):\n        for i in xrange(len(self._hidden_layer_neuron_mapping)):\n            one_neuron_mapping = self._hidden_layer_neuron_mapping[i]\n            z = 0\n            for c in xrange(len(one_neuron_mapping)):\n                hidden_neuron_index = one_neuron_mapping[c]\n                rate = firing_rates[hidden_neuron_index]\n                # TODO think of a more elegant way to deal with it\n                if rate == 0:\n                    rate = 0.0001\n                # TODO: computing activation from reservoir as\n                # rate/self.MAX_INPUT_RATE is\n                # quite questionable!!!\n                z = z + self._hidden_layer_weights[hidden_neuron_index][i]*(\n                    rate/self.MAX_INPUT_RATE)\n            z = z + self._hidden_layer_biases[i]\n            activation = self._sigmoid(z)\n            self._output_layer_activations[i] = activation\n\n    def _initialize_hidden_layer_neuron_mapping(self):\n        mapping = []\n        for i in xrange(self.OUTPUT_LAYER_SIZE):\n            # TODO should be np.random.randint(10)\n            connected_neurons_num = np.random.randint(1,10,1)[0]\n            one_neuron_mapping = np.random.randint(1,\n                                                self.RESERVOIR_NETWORK_SIZE,\n                                                   connected_neurons_num)\n            mapping.append(one_neuron_mapping)\n        return mapping\n\n    def _sigmoid(self, z):\n        return 1.0/(1.0+np.exp(-z))\n\n    def get_hidden_layer_weights_for_output_neuron(self, neuron_idx):\n        # print \"entering get_hidden_layer_weights_for_output_neuron\"\n        hidden_layer_weights_T = self._hidden_layer_weights.T\n        # print \"len(hidden_layer_weights_T[neuron_idx]) = \" + str(len(\n        #         hidden_layer_weights_T[neuron_idx]))\n        # print \"hidden_layer_weights_T[neuron_idx] : \" + str(\n        #         hidden_layer_weights_T[neuron_idx])\n        # print \"leaving get_hidden_layer_weights_for_output_neuron\"\n        return hidden_layer_weights_T[neuron_idx]\n\n    def get_hidden_layer_firing_rates(self):\n        return self._hidden_layer.get_reservoir_firing_rates_output()\n\n    def get_mapping_for_output_neuron(self, neuron_idx):\n        return self._hidden_layer_neuron_mapping[neuron_idx]\n\n    def get_hidden_layer_biases(self):\n        return self._hidden_layer_biases\n\n    def set_hidden_layer_weights_for_neuron(self, neuron_idx,\n                                            hidden_layer_weights):\n        # print \"entering set_hidden_layer_weights_for_neuron\"\n        # print \"len(self._hidden_layer_weights.T[neuron_idx]) = \" + str(len(\n        #         self._hidden_layer_weights.T[neuron_idx]))\n        # print \"len(hidden_layer_weights) = \" + str(len(hidden_layer_weights))\n        self._hidden_layer_weights.T[neuron_idx] = hidden_layer_weights\n        # print \"leaving set_hidden_layer_weights_for_neuron\"\n\n    def set_hidden_layer_biases(self, hidden_layer_biases):\n        # print \"entering SpikingNeuralNetwork.set_hidden_layer_biases\"\n        self._hidden_layer_biases = hidden_layer_biases\n        # print \"leaving SpikingNeuralNetwork.set_hidden_layer_biases\"\n\n    def recalculate_output_layer(self):\n        self._decode_snn_output()\n", "meta": {"hexsha": "4bc9d8d5dea2b644597d6e583b5289337fb1e1c2", "size": 9264, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/SpikingNeuralNetwork.py", "max_stars_repo_name": "VadimLopatkin/AtlasSnnController", "max_stars_repo_head_hexsha": "25c87bd7c80cbb5a1163311b2fd87fad5344f978", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-05-22T12:30:41.000Z", "max_stars_repo_stars_event_max_datetime": "2016-06-03T06:05:21.000Z", "max_issues_repo_path": "lib/SpikingNeuralNetwork.py", "max_issues_repo_name": "VadimLopatkin/AtlasSnnController", "max_issues_repo_head_hexsha": "25c87bd7c80cbb5a1163311b2fd87fad5344f978", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/SpikingNeuralNetwork.py", "max_forks_repo_name": "VadimLopatkin/AtlasSnnController", "max_forks_repo_head_hexsha": "25c87bd7c80cbb5a1163311b2fd87fad5344f978", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.5384615385, "max_line_length": 81, "alphanum_fraction": 0.6564119171, "include": true, "reason": "import numpy", "num_tokens": 2012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.17718164529878241}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\nimport numpy as np\nimport math\nimport tensorflow.keras.backend as K\nimport tensorflow as tf\n\n\ndef xywh_to_x1y1x2y2(boxes):\n    return tf.concat([boxes[..., :2] - boxes[..., 2:] * 0.5, boxes[..., :2] + boxes[..., 2:] * 0.5], axis=-1)\n\n\n# x,y,w,h\ndef bbox_iou(boxes1, boxes2):\n    boxes1_area = boxes1[..., 2] * boxes1[..., 3]  # w * h\n    boxes2_area = boxes2[..., 2] * boxes2[..., 3]\n\n    # (x, y, w, h) -> (x0, y0, x1, y1)\n    boxes1 = xywh_to_x1y1x2y2(boxes1)\n    boxes2 = xywh_to_x1y1x2y2(boxes2)\n\n    # coordinates of intersection\n    top_left = tf.maximum(boxes1[..., :2], boxes2[..., :2])\n    bottom_right = tf.minimum(boxes1[..., 2:], boxes2[..., 2:])\n    intersection_xy = tf.maximum(bottom_right - top_left, 0.0)\n\n    intersection_area = intersection_xy[..., 0] * intersection_xy[..., 1]\n    union_area = boxes1_area + boxes2_area - intersection_area\n\n    return 1.0 * intersection_area / (union_area + tf.keras.backend.epsilon())\n\n\ndef bbox_giou(boxes1, boxes2):\n    boxes1_area = boxes1[..., 2] * boxes1[..., 3]  # w*h\n    boxes2_area = boxes2[..., 2] * boxes2[..., 3]\n\n    # (x, y, w, h) -> (x0, y0, x1, y1)\n    boxes1 = xywh_to_x1y1x2y2(boxes1)\n    boxes2 = xywh_to_x1y1x2y2(boxes2)\n\n    top_left = tf.maximum(boxes1[..., :2], boxes2[..., :2])\n    bottom_right = tf.minimum(boxes1[..., 2:], boxes2[..., 2:])\n\n    intersection_xy = tf.maximum(bottom_right - top_left, 0.0)\n    intersection_area = intersection_xy[..., 0] * intersection_xy[..., 1]\n\n    union_area = boxes1_area + boxes2_area - intersection_area\n\n    iou = 1.0 * intersection_area / (union_area + tf.keras.backend.epsilon())\n\n    enclose_top_left = tf.minimum(boxes1[..., :2], boxes2[..., :2])\n    enclose_bottom_right = tf.maximum(boxes1[..., 2:], boxes2[..., 2:])\n\n    enclose_xy = enclose_bottom_right - enclose_top_left\n    enclose_area = enclose_xy[..., 0] * enclose_xy[..., 1]\n\n    giou = iou - tf.math.divide_no_nan(enclose_area - union_area, enclose_area)\n\n    return giou\n\n\ndef bbox_ciou(boxes1, boxes2):\n    '''\n    ciou = iou - p2/c2 - av\n    :param boxes1: (8, 13, 13, 3, 4)   pred_xywh\n    :param boxes2: (8, 13, 13, 3, 4)   label_xywh\n    :return:\n    '''\n    boxes1_x0y0x1y1 = tf.concat([boxes1[..., :2] - boxes1[..., 2:] * 0.5,\n                                 boxes1[..., :2] + boxes1[..., 2:] * 0.5], axis=-1)\n    boxes2_x0y0x1y1 = tf.concat([boxes2[..., :2] - boxes2[..., 2:] * 0.5,\n                                 boxes2[..., :2] + boxes2[..., 2:] * 0.5], axis=-1)\n    boxes1_x0y0x1y1 = tf.concat([tf.minimum(boxes1_x0y0x1y1[..., :2], boxes1_x0y0x1y1[..., 2:]),\n                                 tf.maximum(boxes1_x0y0x1y1[..., :2], boxes1_x0y0x1y1[..., 2:])], axis=-1)\n    boxes2_x0y0x1y1 = tf.concat([tf.minimum(boxes2_x0y0x1y1[..., :2], boxes2_x0y0x1y1[..., 2:]),\n                                 tf.maximum(boxes2_x0y0x1y1[..., :2], boxes2_x0y0x1y1[..., 2:])], axis=-1)\n\n    # area\n    boxes1_area = (boxes1_x0y0x1y1[..., 2] - boxes1_x0y0x1y1[..., 0]) * (\n                boxes1_x0y0x1y1[..., 3] - boxes1_x0y0x1y1[..., 1])\n    boxes2_area = (boxes2_x0y0x1y1[..., 2] - boxes2_x0y0x1y1[..., 0]) * (\n                boxes2_x0y0x1y1[..., 3] - boxes2_x0y0x1y1[..., 1])\n\n    # top-left and bottom-right coord, shape: (8, 13, 13, 3, 2)\n    left_up = tf.maximum(boxes1_x0y0x1y1[..., :2], boxes2_x0y0x1y1[..., :2])\n    right_down = tf.minimum(boxes1_x0y0x1y1[..., 2:], boxes2_x0y0x1y1[..., 2:])\n\n    # intersection area and iou\n    inter_section = tf.maximum(right_down - left_up, 0.0)\n    inter_area = inter_section[..., 0] * inter_section[..., 1]\n    union_area = boxes1_area + boxes2_area - inter_area\n    iou = inter_area / (union_area + 1e-9)\n\n    # top-left and bottom-right coord of the enclosing rectangle, shape: (8, 13, 13, 3, 2)\n    enclose_left_up = tf.minimum(boxes1_x0y0x1y1[..., :2], boxes2_x0y0x1y1[..., :2])\n    enclose_right_down = tf.maximum(boxes1_x0y0x1y1[..., 2:], boxes2_x0y0x1y1[..., 2:])\n\n    # diagnal ** 2\n    enclose_wh = enclose_right_down - enclose_left_up\n    enclose_c2 = K.pow(enclose_wh[..., 0], 2) + K.pow(enclose_wh[..., 1], 2)\n\n    # center distances between two rectangles\n    p2 = K.pow(boxes1[..., 0] - boxes2[..., 0], 2) + K.pow(boxes1[..., 1] - boxes2[..., 1], 2)\n\n    # add av\n    atan1 = tf.atan(boxes1[..., 2] / (boxes1[..., 3] + 1e-9))\n    atan2 = tf.atan(boxes2[..., 2] / (boxes2[..., 3] + 1e-9))\n    v = 4.0 * K.pow(atan1 - atan2, 2) / (math.pi ** 2)\n    a = v / (1 - iou + v)\n\n    ciou = iou - 1.0 * p2 / enclose_c2 - 1.0 * a * v\n    return ciou\n\n\ndef yolo_loss(args, num_classes, iou_loss_thresh, anchors):\n    conv_lbbox = args[2]   # (?, ?, ?, 3*(num_classes+5))\n    conv_mbbox = args[1]   # (?, ?, ?, 3*(num_classes+5))\n    conv_sbbox = args[0]   # (?, ?, ?, 3*(num_classes+5))\n    label_sbbox = args[3]   # (?, ?, ?, 3, num_classes+5)\n    label_mbbox = args[4]   # (?, ?, ?, 3, num_classes+5)\n    label_lbbox = args[5]   # (?, ?, ?, 3, num_classes+5)\n    true_bboxes = args[6]   # (?, 50, 4)\n    pred_sbbox = decode(conv_sbbox, anchors[0], 8, num_classes)\n    pred_mbbox = decode(conv_mbbox, anchors[1], 16, num_classes)\n    pred_lbbox = decode(conv_lbbox, anchors[2], 32, num_classes)\n    sbbox_ciou_loss, sbbox_conf_loss, sbbox_prob_loss = loss_layer(conv_sbbox, pred_sbbox, label_sbbox, true_bboxes, 8, num_classes, iou_loss_thresh)\n    mbbox_ciou_loss, mbbox_conf_loss, mbbox_prob_loss = loss_layer(conv_mbbox, pred_mbbox, label_mbbox, true_bboxes, 16, num_classes, iou_loss_thresh)\n    lbbox_ciou_loss, lbbox_conf_loss, lbbox_prob_loss = loss_layer(conv_lbbox, pred_lbbox, label_lbbox, true_bboxes, 32, num_classes, iou_loss_thresh)\n\n    ciou_loss = (lbbox_ciou_loss + sbbox_ciou_loss + mbbox_ciou_loss) * 3.54\n    conf_loss = (lbbox_conf_loss + sbbox_conf_loss + mbbox_conf_loss) * 64.3\n    prob_loss = (lbbox_prob_loss + sbbox_prob_loss + mbbox_prob_loss) * 1\n\n    return ciou_loss+conf_loss+prob_loss\n\n\ndef loss_layer(conv, pred, label, bboxes, stride, num_class, iou_loss_thresh):\n    conv_shape = tf.shape(conv)\n    batch_size = conv_shape[0]\n    output_size = conv_shape[1]\n    input_size = stride * output_size\n    conv = tf.reshape(conv, (batch_size, output_size, output_size,\n                             3, 5 + num_class))\n    conv_raw_prob = conv[:, :, :, :, 5:]\n    conv_raw_conf = conv[:, :, :, :, 4:5]\n\n    pred_xywh = pred[:, :, :, :, 0:4]\n    pred_conf = pred[:, :, :, :, 4:5]\n\n    label_xywh = label[:, :, :, :, 0:4]\n    respond_bbox = label[:, :, :, :, 4:5]\n    label_prob = label[:, :, :, :, 5:]\n\n    # Coordinate loss\n    ciou = tf.expand_dims(bbox_giou(pred_xywh, label_xywh), axis=-1)  # (8, 13, 13, 3, 1)\n    # ciou = tf.expand_dims(bbox_ciou(pred_xywh, label_xywh), axis=-1)  # (8, 13, 13, 3, 1)\n    input_size = tf.cast(input_size, tf.float32)\n\n    # loss weight of the gt bbox: 2-(gt area/img area)\n    bbox_loss_scale = 2.0 - 1.0 * label_xywh[:, :, :, :, 2:3] * label_xywh[:, :, :, :, 3:4] / (input_size ** 2)\n    ciou_loss = respond_bbox * bbox_loss_scale * (1 - ciou)  # iou loss for respond bbox\n\n    # Classification loss for respond bbox\n    prob_loss = respond_bbox * tf.nn.sigmoid_cross_entropy_with_logits(labels=label_prob, logits=conv_raw_prob)\n\n    expand_pred_xywh = pred_xywh[:, :, :, :, np.newaxis, :]  # (?, grid_h, grid_w, 3, 1, 4)\n    expand_bboxes = bboxes[:, np.newaxis, np.newaxis, np.newaxis, :, :]  # (?, 1, 1, 1, 70, 4)\n    iou = bbox_iou(expand_pred_xywh, expand_bboxes)  # IoU between all pred bbox and all gt (?, grid_h, grid_w, 3, 70)\n    max_iou = tf.expand_dims(tf.reduce_max(iou, axis=-1), axis=-1)  # max iou: (?, grid_h, grid_w, 3, 1)\n\n    # ignore the bbox which is not respond bbox and max iou < threshold\n    respond_bgd = (1.0 - respond_bbox) * tf.cast(max_iou < iou_loss_thresh, tf.float32)\n\n    # Confidence loss\n    conf_focal = tf.pow(respond_bbox - pred_conf, 2)\n\n    conf_loss = conf_focal * (\n            respond_bbox * tf.nn.sigmoid_cross_entropy_with_logits(labels=respond_bbox, logits=conv_raw_conf)\n            +\n            respond_bgd * tf.nn.sigmoid_cross_entropy_with_logits(labels=respond_bbox, logits=conv_raw_conf)\n    )\n\n    ciou_loss = tf.reduce_mean(tf.reduce_sum(ciou_loss, axis=[1, 2, 3, 4]))\n    conf_loss = tf.reduce_mean(tf.reduce_sum(conf_loss, axis=[1, 2, 3, 4]))\n    prob_loss = tf.reduce_mean(tf.reduce_sum(prob_loss, axis=[1, 2, 3, 4]))\n\n    return ciou_loss, conf_loss, prob_loss\n\n\ndef decode(conv_output, anchors, stride, num_class):\n    conv_shape = tf.shape(conv_output)\n    batch_size = conv_shape[0]\n    output_size = conv_shape[1]\n    anchor_per_scale = len(anchors)\n    conv_output = tf.reshape(conv_output, (batch_size, output_size, output_size, anchor_per_scale, 5 + num_class))\n    conv_raw_dxdy = conv_output[:, :, :, :, 0:2]\n    conv_raw_dwdh = conv_output[:, :, :, :, 2:4]\n    conv_raw_conf = conv_output[:, :, :, :, 4:5]\n    conv_raw_prob = conv_output[:, :, :, :, 5:]\n    y = tf.tile(tf.range(output_size, dtype=tf.int32)[:, tf.newaxis], [1, output_size])\n    x = tf.tile(tf.range(output_size, dtype=tf.int32)[tf.newaxis, :], [output_size, 1])\n    xy_grid = tf.concat([x[:, :, tf.newaxis], y[:, :, tf.newaxis]], axis=-1)\n    xy_grid = tf.tile(xy_grid[tf.newaxis, :, :, tf.newaxis, :], [batch_size, 1, 1, anchor_per_scale, 1])\n    xy_grid = tf.cast(xy_grid, tf.float32)\n    pred_xy = (tf.sigmoid(conv_raw_dxdy) + xy_grid) * stride\n    pred_wh = (tf.exp(conv_raw_dwdh) * anchors)\n    pred_xywh = tf.concat([pred_xy, pred_wh], axis=-1)\n    pred_conf = tf.sigmoid(conv_raw_conf)\n    pred_prob = tf.sigmoid(conv_raw_prob)\n    return tf.concat([pred_xywh, pred_conf, pred_prob], axis=-1)\n\n", "meta": {"hexsha": "4675441242d67a211ae1048df865fb006d5ec235", "size": 9583, "ext": "py", "lang": "Python", "max_stars_repo_path": "loss.py", "max_stars_repo_name": "TheCavani78/yolo-v4-tf.keras", "max_stars_repo_head_hexsha": "459017fd117bc8ab21b425c98141ae5e9b2ea0c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 96, "max_stars_repo_stars_event_min_datetime": "2020-07-17T03:48:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T07:32:00.000Z", "max_issues_repo_path": "loss.py", "max_issues_repo_name": "BrentZ-1849203/yolo-v4-tf.keras", "max_issues_repo_head_hexsha": "de0c1968dd60ab8bfa9b7cdf2468b1e0cc876482", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2020-10-11T14:56:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:48:40.000Z", "max_forks_repo_path": "loss.py", "max_forks_repo_name": "BrentZ-1849203/yolo-v4-tf.keras", "max_forks_repo_head_hexsha": "de0c1968dd60ab8bfa9b7cdf2468b1e0cc876482", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 60, "max_forks_repo_forks_event_min_datetime": "2020-07-31T07:24:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T15:28:08.000Z", "avg_line_length": 44.9906103286, "max_line_length": 150, "alphanum_fraction": 0.6195345925, "include": true, "reason": "import numpy", "num_tokens": 3268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.28457601028405616, "lm_q1q2_score": 0.17713699702365085}}
{"text": "\"\"\" Additional helper functions dealing with transient-CW F(t0,tau) maps \"\"\"\n\nimport numpy as np\nimport os\nimport logging\nfrom time import time\n\n# optional imports\nimport importlib as imp\n\n\ndef _optional_import(modulename, shorthand=None):\n    \"\"\"\n    Import a module/submodule only if it's available.\n\n    using importlib instead of __import__\n    because the latter doesn't handle sub.modules\n\n    Also including a special check to fail more gracefully\n    when CUDA_DEVICE is set to too high a number.\n    \"\"\"\n\n    if shorthand is None:\n        shorthand = modulename\n        shorthandbit = \"\"\n    else:\n        shorthandbit = \" as \" + shorthand\n\n    try:\n        globals()[shorthand] = imp.import_module(modulename)\n        logging.debug(\"Successfully imported module %s%s.\" % (modulename, shorthandbit))\n        success = True\n    except ImportError as e:\n        logging.debug(\"Failed to import module {:s}.\".format(modulename))\n        success = False\n\n    return success\n\n\nclass pyTransientFstatMap(object):\n    \"\"\"\n    simplified object class for a F(t0,tau) F-stat map (not 2F!)\n    based on LALSuite's transientFstatMap_t type\n    replacing the gsl matrix with a numpy array\n\n    F_mn:   2D array of 2F values\n    maxF:   maximum of F (not 2F!)\n    t0_ML:  maximum likelihood transient start time t0 estimate\n    tau_ML: maximum likelihood transient duration tau estimate\n    \"\"\"\n\n    def __init__(self, N_t0Range, N_tauRange):\n        self.F_mn = np.zeros((N_t0Range, N_tauRange), dtype=np.float32)\n        # Initializing maxF to a negative value ensures\n        # that we always update at least once and hence return\n        # sane t0_d_ML, tau_d_ML\n        # even if there is only a single bin where F=0 happens.\n        self.maxF = float(-1.0)\n        self.t0_ML = float(0.0)\n        self.tau_ML = float(0.0)\n\n\n# dictionary of the actual callable F-stat map functions we support,\n# if the corresponding modules are available.\nfstatmap_versions = {\n    \"lal\": lambda multiFstatAtoms, windowRange: getattr(\n        lalpulsar, \"ComputeTransientFstatMap\"\n    )(multiFstatAtoms, windowRange, False),\n    \"pycuda\": lambda multiFstatAtoms, windowRange: pycuda_compute_transient_fstat_map(\n        multiFstatAtoms, windowRange\n    ),\n}\n\n\ndef init_transient_fstat_map_features(wantCuda=False, cudaDeviceName=None):\n    \"\"\"\n    Initialization of available modules (or \"features\") for F-stat maps.\n\n    Returns a dictionary of method names, to match fstatmap_versions\n    each key's value set to True only if\n    all required modules are importable on this system.\n    \"\"\"\n\n    features = {}\n\n    have_lal = _optional_import(\"lal\")\n    have_lalpulsar = _optional_import(\"lalpulsar\")\n    features[\"lal\"] = have_lal and have_lalpulsar\n\n    # import GPU features\n    have_pycuda = _optional_import(\"pycuda\")\n    have_pycuda_drv = _optional_import(\"pycuda.driver\", \"drv\")\n    have_pycuda_gpuarray = _optional_import(\"pycuda.gpuarray\", \"gpuarray\")\n    have_pycuda_tools = _optional_import(\"pycuda.tools\", \"cudatools\")\n    have_pycuda_compiler = _optional_import(\"pycuda.compiler\", \"cudacomp\")\n    features[\"pycuda\"] = (\n        have_pycuda_drv\n        and have_pycuda_gpuarray\n        and have_pycuda_tools\n        and have_pycuda_compiler\n    )\n\n    logging.debug(\"Got the following features for transient F-stat maps:\")\n    logging.debug(features)\n\n    if wantCuda and features[\"pycuda\"]:\n        logging.debug(\"CUDA version: \" + \".\".join(map(str, drv.get_version())))\n\n        drv.init()\n        logging.debug(\n            \"Starting with default pyCUDA context,\"\n            \" then checking all available devices...\"\n        )\n        try:\n            context0 = pycuda.tools.make_default_context()\n        except pycuda._driver.LogicError as e:\n            if e.message == \"cuDeviceGet failed: invalid device ordinal\":\n                devn = int(os.environ[\"CUDA_DEVICE\"])\n                raise RuntimeError(\n                    \"Requested CUDA device number {} exceeds\"\n                    \" number of available devices!\"\n                    \" Please change through environment\"\n                    \" variable $CUDA_DEVICE.\".format(devn)\n                )\n            else:\n                raise pycuda._driver.LogicError(e.message)\n\n        num_gpus = drv.Device.count()\n        logging.debug(\"Found {} CUDA device(s).\".format(num_gpus))\n\n        devices = []\n        devnames = np.empty(num_gpus, dtype=\"S32\")\n        for n in range(num_gpus):\n            devn = drv.Device(n)\n            devices.append(devn)\n            devnames[n] = devn.name().replace(\" \", \"-\").replace(\"_\", \"-\")\n            logging.debug(\n                \"device {}: model: {}, RAM: {}MB\".format(\n                    n, devnames[n], devn.total_memory() / (2.0 ** 20)\n                )\n            )\n\n        if \"CUDA_DEVICE\" in os.environ:\n            devnum0 = int(os.environ[\"CUDA_DEVICE\"])\n        else:\n            devnum0 = 0\n\n        matchbit = \"\"\n        if cudaDeviceName:\n            # allow partial matches in device names\n            devmatches = [\n                devidx\n                for devidx, devname in enumerate(devnames)\n                if cudaDeviceName in devname\n            ]\n            if len(devmatches) == 0:\n                context0.detach()\n                raise RuntimeError(\n                    'Requested CUDA device \"{}\" not found.'\n                    \" Available devices: [{}]\".format(\n                        cudaDeviceName, \",\".join(devnames)\n                    )\n                )\n            else:\n                devnum = devmatches[0]\n                if len(devmatches) > 1:\n                    logging.warning(\n                        'Found {} CUDA devices matching name \"{}\".'\n                        \" Choosing first one with index {}.\".format(\n                            len(devmatches), cudaDeviceName, devnum\n                        )\n                    )\n            os.environ[\"CUDA_DEVICE\"] = str(devnum)\n            matchbit = '(matched to user request \"{}\")'.format(cudaDeviceName)\n        elif \"CUDA_DEVICE\" in os.environ:\n            devnum = int(os.environ[\"CUDA_DEVICE\"])\n        else:\n            devnum = 0\n        devn = devices[devnum]\n        logging.info(\n            \"Choosing CUDA device {},\"\n            \" of {} devices present: {}{}...\".format(\n                devnum, num_gpus, devn.name(), matchbit\n            )\n        )\n        if devnum == devnum0:\n            gpu_context = context0\n        else:\n            context0.pop()\n            gpu_context = pycuda.tools.make_default_context()\n            gpu_context.push()\n\n        _print_GPU_memory_MB(\"Available\")\n    else:\n        gpu_context = None\n\n    return features, gpu_context\n\n\ndef call_compute_transient_fstat_map(\n    version, features, multiFstatAtoms=None, windowRange=None\n):\n    \"\"\"Choose which version of the ComputeTransientFstatMap function to call.\"\"\"\n\n    if version in fstatmap_versions:\n        if features[version]:\n            time0 = time()\n            FstatMap = fstatmap_versions[version](multiFstatAtoms, windowRange)\n            timingFstatMap = time() - time0\n        else:\n            raise Exception(\n                \"Required module(s) for transient F-stat map\"\n                ' method \"{}\" not available!'.format(version)\n            )\n    else:\n        raise Exception(\n            'Transient F-stat map method \"{}\"' \" not implemented!\".format(version)\n        )\n    return FstatMap, timingFstatMap\n\n\ndef reshape_FstatAtomsVector(atomsVector):\n    \"\"\"\n    Make a dictionary of ndarrays out of a atoms \"vector\" structure.\n\n    The input is a \"vector\"-like structure with times as the higher hierarchical\n    level and a set of \"atoms\" quantities defined at each timestamp.\n    The output is a dictionary with an entry for each quantity,\n    which is a 1D ndarray over timestamps for that one quantity.\n    \"\"\"\n\n    numAtoms = atomsVector.length\n    atomsDict = {}\n    atom_fieldnames = [\n        \"timestamp\",\n        \"Fa_alpha\",\n        \"Fb_alpha\",\n        \"a2_alpha\",\n        \"ab_alpha\",\n        \"b2_alpha\",\n    ]\n    atom_dtypes = [np.uint32, complex, complex, np.float32, np.float32, np.float32]\n    for f, field in enumerate(atom_fieldnames):\n        atomsDict[field] = np.ndarray(numAtoms, dtype=atom_dtypes[f])\n\n    for n, atom in enumerate(atomsVector.data):\n        for field in atom_fieldnames:\n            atomsDict[field][n] = atom.__getattribute__(field)\n\n    atomsDict[\"Fa_alpha_re\"] = np.float32(atomsDict[\"Fa_alpha\"].real)\n    atomsDict[\"Fa_alpha_im\"] = np.float32(atomsDict[\"Fa_alpha\"].imag)\n    atomsDict[\"Fb_alpha_re\"] = np.float32(atomsDict[\"Fb_alpha\"].real)\n    atomsDict[\"Fb_alpha_im\"] = np.float32(atomsDict[\"Fb_alpha\"].imag)\n\n    return atomsDict\n\n\ndef _get_absolute_kernel_path(kernel):\n    pyfstatdir = os.path.dirname(os.path.abspath(os.path.realpath(__file__)))\n    kernelfile = kernel + \".cu\"\n    return os.path.join(pyfstatdir, \"pyCUDAkernels\", kernelfile)\n\n\ndef _print_GPU_memory_MB(key):\n    mem_used_MB = drv.mem_get_info()[0] / (2.0 ** 20)\n    mem_total_MB = drv.mem_get_info()[1] / (2.0 ** 20)\n    logging.debug(\n        \"{} GPU memory: {:.4f} / {:.4f} MB free\".format(key, mem_used_MB, mem_total_MB)\n    )\n\n\ndef pycuda_compute_transient_fstat_map(multiFstatAtoms, windowRange):\n    \"\"\"\n    GPU version of the function to compute transient-window \"F-statistic map\"\n    over start-time and timescale {t0, tau}.\n    Based on XLALComputeTransientFstatMap from LALSuite,\n    (C) 2009 Reinhard Prix, licensed under GPL\n\n    Returns a 2D matrix F_mn,\n    with m = index over start-times t0,\n    and  n = index over timescales tau,\n    in steps of dt0  in [t0,  t0+t0Band],\n    and         dtau in [tau, tau+tauBand]\n    as defined in windowRange input.\n    \"\"\"\n\n    if windowRange.type >= lalpulsar.TRANSIENT_LAST:\n        raise ValueError(\n            \"Unknown window-type ({}) passed as input.\"\n            \" Allowed are [0,{}].\".format(\n                windowRange.type, lalpulsar.TRANSIENT_LAST - 1\n            )\n        )\n\n    # internal dict for search/setup parameters\n    tCWparams = {}\n\n    # first combine all multi-atoms\n    # into a single atoms-vector with *unique* timestamps\n    tCWparams[\"TAtom\"] = multiFstatAtoms.data[0].TAtom\n    TAtomHalf = int(tCWparams[\"TAtom\"] / 2)  # integer division\n    atoms = lalpulsar.mergeMultiFstatAtomsBinned(multiFstatAtoms, tCWparams[\"TAtom\"])\n\n    # make a combined input matrix of all atoms vectors, for transfer to GPU\n    tCWparams[\"numAtoms\"] = atoms.length\n    atomsDict = reshape_FstatAtomsVector(atoms)\n    atomsInputMatrix = np.column_stack(\n        (\n            atomsDict[\"a2_alpha\"],\n            atomsDict[\"b2_alpha\"],\n            atomsDict[\"ab_alpha\"],\n            atomsDict[\"Fa_alpha_re\"],\n            atomsDict[\"Fa_alpha_im\"],\n            atomsDict[\"Fb_alpha_re\"],\n            atomsDict[\"Fb_alpha_im\"],\n        )\n    )\n\n    # actual data spans [t0_data, t0_data + tCWparams['numAtoms'] * TAtom]\n    # in steps of TAtom\n    tCWparams[\"t0_data\"] = int(atoms.data[0].timestamp)\n    tCWparams[\"t1_data\"] = int(\n        atoms.data[tCWparams[\"numAtoms\"] - 1].timestamp + tCWparams[\"TAtom\"]\n    )\n\n    logging.debug(\n        \"Transient F-stat map:\"\n        \" t0_data={:d}, t1_data={:d}\".format(tCWparams[\"t0_data\"], tCWparams[\"t1_data\"])\n    )\n    logging.debug(\n        \"Transient F-stat map:\"\n        \" numAtoms={:d}, TAtom={:d},\"\n        \" TAtomHalf={:d}\".format(tCWparams[\"numAtoms\"], tCWparams[\"TAtom\"], TAtomHalf)\n    )\n\n    # special treatment of window_type = none\n    # ==> replace by rectangular window spanning all the data\n    if windowRange.type == lalpulsar.TRANSIENT_NONE:\n        windowRange.type = lalpulsar.TRANSIENT_RECTANGULAR\n        windowRange.t0 = tCWparams[\"t0_data\"]\n        windowRange.t0Band = 0\n        windowRange.dt0 = tCWparams[\"TAtom\"]  # irrelevant\n        windowRange.tau = tCWparams[\"numAtoms\"] * tCWparams[\"TAtom\"]\n        windowRange.tauBand = 0\n        windowRange.dtau = tCWparams[\"TAtom\"]  # irrelevant\n\n    \"\"\" NOTE: indices {i,j} enumerate *actual* atoms and their timestamps t_i,\n    * while the indices {m,n} enumerate the full grid of values\n    * in [t0_min, t0_max]x[Tcoh_min, Tcoh_max] in steps of deltaT.\n    * This allows us to deal with gaps in the data in a transparent way.\n    *\n    * NOTE2: we operate on the 'binned' atoms returned\n    * from XLALmergeMultiFstatAtomsBinned(),\n    * which means we can safely assume all atoms to be lined up\n    * perfectly on a 'deltaT' binned grid.\n    *\n    * The mapping used will therefore be {i,j} -> {m,n}:\n    *   m = offs_i  / deltaT\n    *   start-time offset from t0_min measured in deltaT\n    *   n = Tcoh_ij / deltaT\n    *   duration Tcoh_ij measured in deltaT,\n    *\n    * where\n    *   offs_i  = t_i - t0_min\n    *   Tcoh_ij = t_j - t_i + deltaT\n    *\n    \"\"\"\n\n    # We allocate a matrix  {m x n} = t0Range * TcohRange elements\n    # covering the full transient window-range [t0,t0+t0Band]x[tau,tau+tauBand]\n    tCWparams[\"N_t0Range\"] = int(\n        np.floor(1.0 * windowRange.t0Band / windowRange.dt0) + 1\n    )\n    tCWparams[\"N_tauRange\"] = int(\n        np.floor(1.0 * windowRange.tauBand / windowRange.dtau) + 1\n    )\n    FstatMap = pyTransientFstatMap(tCWparams[\"N_t0Range\"], tCWparams[\"N_tauRange\"])\n\n    logging.debug(\n        \"Transient F-stat map:\"\n        \" N_t0Range={:d}, N_tauRange={:d},\"\n        \" total grid points: {:d}\".format(\n            tCWparams[\"N_t0Range\"],\n            tCWparams[\"N_tauRange\"],\n            tCWparams[\"N_t0Range\"] * tCWparams[\"N_tauRange\"],\n        )\n    )\n\n    if windowRange.type == lalpulsar.TRANSIENT_RECTANGULAR:\n        FstatMap.F_mn = pycuda_compute_transient_fstat_map_rect(\n            atomsInputMatrix, windowRange, tCWparams\n        )\n    elif windowRange.type == lalpulsar.TRANSIENT_EXPONENTIAL:\n        FstatMap.F_mn = pycuda_compute_transient_fstat_map_exp(\n            atomsInputMatrix, windowRange, tCWparams\n        )\n    else:\n        raise ValueError(\n            \"Invalid transient window type {}\"\n            \" not in [{}, {}].\".format(\n                windowRange.type, lalpulsar.TRANSIENT_NONE, lalpulsar.TRANSIENT_LAST - 1\n            )\n        )\n\n    # out of loop: get max2F and ML estimates over the m x n matrix\n    FstatMap.maxF = FstatMap.F_mn.max()\n    maxidx = np.unravel_index(\n        FstatMap.F_mn.argmax(), (tCWparams[\"N_t0Range\"], tCWparams[\"N_tauRange\"])\n    )\n    FstatMap.t0_ML = windowRange.t0 + maxidx[0] * windowRange.dt0\n    FstatMap.tau_ML = windowRange.tau + maxidx[1] * windowRange.dtau\n\n    logging.debug(\n        \"Done computing transient F-stat map.\"\n        \" maxF={:.4f}, t0_ML={}, tau_ML={}\".format(\n            FstatMap.maxF, FstatMap.t0_ML, FstatMap.tau_ML\n        )\n    )\n\n    return FstatMap\n\n\ndef pycuda_compute_transient_fstat_map_rect(atomsInputMatrix, windowRange, tCWparams):\n    \"\"\"\n    only GPU-parallizing outer loop,\n    keeping partial sums with memory in kernel\n    \"\"\"\n\n    # gpu data setup and transfer\n    _print_GPU_memory_MB(\"Initial\")\n    input_gpu = gpuarray.to_gpu(atomsInputMatrix)\n    Fmn_gpu = gpuarray.GPUArray(\n        (tCWparams[\"N_t0Range\"], tCWparams[\"N_tauRange\"]), dtype=np.float32\n    )\n    _print_GPU_memory_MB(\"After input+output allocation:\")\n\n    # GPU kernel\n    kernel = \"cudaTransientFstatRectWindow\"\n    kernelfile = _get_absolute_kernel_path(kernel)\n    partial_Fstat_cuda_code = cudacomp.SourceModule(open(kernelfile, \"r\").read())\n    partial_Fstat_cuda = partial_Fstat_cuda_code.get_function(kernel)\n    partial_Fstat_cuda.prepare(\"PIIIIIIIIP\")\n\n    # GPU grid setup\n    blockRows = min(1024, tCWparams[\"N_t0Range\"])\n    blockCols = 1\n    gridRows = int(np.ceil(1.0 * tCWparams[\"N_t0Range\"] / blockRows))\n    gridCols = 1\n\n    # running the kernel\n    logging.debug(\n        \"Calling pyCUDA kernel with a grid of {}*{}={} blocks\"\n        \" of {}*{}={} threads each: {} total threads...\".format(\n            gridRows,\n            gridCols,\n            gridRows * gridCols,\n            blockRows,\n            blockCols,\n            blockRows * blockCols,\n            gridRows * gridCols * blockRows * blockCols,\n        )\n    )\n    partial_Fstat_cuda.prepared_call(\n        (gridRows, gridCols),\n        (blockRows, blockCols, 1),\n        input_gpu.gpudata,\n        tCWparams[\"numAtoms\"],\n        tCWparams[\"TAtom\"],\n        tCWparams[\"t0_data\"],\n        windowRange.t0,\n        windowRange.dt0,\n        windowRange.tau,\n        windowRange.dtau,\n        tCWparams[\"N_tauRange\"],\n        Fmn_gpu.gpudata,\n    )\n\n    # return results to host\n    F_mn = Fmn_gpu.get()\n\n    _print_GPU_memory_MB(\"Final\")\n\n    return F_mn\n\n\ndef pycuda_compute_transient_fstat_map_exp(atomsInputMatrix, windowRange, tCWparams):\n    \"\"\"exponential window, inner and outer loop GPU-parallelized\"\"\"\n\n    # gpu data setup and transfer\n    _print_GPU_memory_MB(\"Initial\")\n    input_gpu = gpuarray.to_gpu(atomsInputMatrix)\n    Fmn_gpu = gpuarray.GPUArray(\n        (tCWparams[\"N_t0Range\"], tCWparams[\"N_tauRange\"]), dtype=np.float32\n    )\n    _print_GPU_memory_MB(\"After input+output allocation:\")\n\n    # GPU kernel\n    kernel = \"cudaTransientFstatExpWindow\"\n    kernelfile = _get_absolute_kernel_path(kernel)\n    partial_Fstat_cuda_code = cudacomp.SourceModule(open(kernelfile, \"r\").read())\n    partial_Fstat_cuda = partial_Fstat_cuda_code.get_function(kernel)\n    partial_Fstat_cuda.prepare(\"PIIIIIIIIIP\")\n\n    # GPU grid setup\n    blockRows = min(32, tCWparams[\"N_t0Range\"])\n    blockCols = min(32, tCWparams[\"N_tauRange\"])\n    gridRows = int(np.ceil(1.0 * tCWparams[\"N_t0Range\"] / blockRows))\n    gridCols = int(np.ceil(1.0 * tCWparams[\"N_tauRange\"] / blockCols))\n\n    # running the kernel\n    logging.debug(\n        \"Calling kernel with a grid of {}*{}={} blocks\"\n        \" of {}*{}={} threads each: {} total threads...\".format(\n            gridRows,\n            gridCols,\n            gridRows * gridCols,\n            blockRows,\n            blockCols,\n            blockRows * blockCols,\n            gridRows * gridCols * blockRows * blockCols,\n        )\n    )\n    partial_Fstat_cuda.prepared_call(\n        (gridRows, gridCols),\n        (blockRows, blockCols, 1),\n        input_gpu.gpudata,\n        tCWparams[\"numAtoms\"],\n        tCWparams[\"TAtom\"],\n        tCWparams[\"t0_data\"],\n        windowRange.t0,\n        windowRange.dt0,\n        windowRange.tau,\n        windowRange.dtau,\n        tCWparams[\"N_t0Range\"],\n        tCWparams[\"N_tauRange\"],\n        Fmn_gpu.gpudata,\n    )\n\n    # return results to host\n    F_mn = Fmn_gpu.get()\n\n    _print_GPU_memory_MB(\"Final\")\n\n    return F_mn\n", "meta": {"hexsha": "10ee31f4cdaed84de2660134b978d3b8d7a0a76c", "size": 18521, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyfstat/tcw_fstat_map_funcs.py", "max_stars_repo_name": "pepCV/PyFstat", "max_stars_repo_head_hexsha": "b30919962e9730e24d514e9e9fe89289a002d428", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-28T08:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:29:24.000Z", "max_issues_repo_path": "pyfstat/tcw_fstat_map_funcs.py", "max_issues_repo_name": "GregoryAshton/PyFstat", "max_issues_repo_head_hexsha": "4f7a96d4aeb778b3b322b03897f7d65c0ccf1190", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyfstat/tcw_fstat_map_funcs.py", "max_forks_repo_name": "GregoryAshton/PyFstat", "max_forks_repo_head_hexsha": "4f7a96d4aeb778b3b322b03897f7d65c0ccf1190", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9834862385, "max_line_length": 88, "alphanum_fraction": 0.6191890287, "include": true, "reason": "import numpy", "num_tokens": 4781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.17704614301940602}}
{"text": "# GPL 2.0\n#\n# written by Gregg Rice, gmr@unc.edu, rice.gregg@gmail.com\n# copywrite 2013-2015\n# all rights reserved\n#\n\n##################################################################################\n# render one or two CT secondary structures with helices shown as semicircular arcs\n# This simple version of the script does not plot any additional data above the structure(s).\n# functionsplotArcRibbons by Steve Busan, modified in 2014 with permission for python hooks Gregg Rice\n# om function arcplot\n# ----\n\nimport RNAtools as RNA\nimport numpy as np\nimport sys, argparse, os, traceback, copy, re, math\n\nfrom matplotlib import rc\n#rc('text',usetex=True)\n\ndef rgb_int2pct(rgbArr):\n    \"\"\"\n    converts RGB 255 values to a 0 to 1 scale\n\n    (255,255,255) --> (1,1,1)\n    \"\"\"\n    out = []\n    for rgb in rgbArr:\n        out.append((rgb[0]/255.0, rgb[1]/255.0, rgb[2]/255.0))\n    return out\n\ndef parseArgs():\n    prs = argparse.ArgumentParser()\n    prs.add_argument(\"dotplot\", type=str, help='input dotplot file to get pairing probabilities')\n    prs.add_argument(\"outputPDF\",type=str, help=\"Name of the output PDF graphic\")\n    prs.add_argument(\"--referenceCT\",type=str, help=\"reference ct file used for getting the RNA sequence\")\n    prs.add_argument(\"--pkDS\", type=str, help=\"Double stranded pk file to optionally add in black arcs for pseudoknots. Two column space seperated text file with pairs in columns\")\n    prs.add_argument(\"--secondaryStructure\", action=\"store_true\", default=False, help=\"Plot the secondary structure on top\")\n\n    out = prs.parse_args()\n\n    return out\n\ndef plotArcRibbons(pairedNuc, ax, color, alpha=1.0, flip=False):\n    \"\"\"\n    pairedNuc is a vector length N (seqeunce length) with non-zero values setting the connections\n    this is a non-redundant .ct column. Example below\n    0 3 0 0 0\n      |___|   <-- arc between pos 2 and 4\n\n    ax is the plot axis object\n\n    color is the color of the arc, and alpha is the transparency of the arc\n\n    flip will plot the arcs as rainbows rather than smiles\n    \"\"\"\n\n    from matplotlib.path import Path\n    import matplotlib.patches as patches\n\n    handleLengthFactor = 4*(math.sqrt(2)-1)/3\n    #vert = 100.0\n\n    i = 0\n    while i < len(pairedNuc):\n        if pairedNuc[i] > i+1:\n            outerPair = [i+0.5,pairedNuc[i]+0.5]\n            # find the right side of helix\n            lastPairedNuc = pairedNuc[i]\n            offset = 1\n            while i+offset<len(pairedNuc) and abs(pairedNuc[i+offset]-lastPairedNuc) == 1:\n                lastPairedNuc = pairedNuc[i+offset]\n                offset += 1\n            innerPair = [i+offset+0.5, pairedNuc[i+offset-1]-0.5]\n            i += offset-1\n            outerRadius = (outerPair[1]-outerPair[0])/2.0\n            innerRadius = (innerPair[1]-innerPair[0])/2.0\n            #print \"innerPair %s, outerPair %s\"%(str(innerPair),str(outerPair))\n            verts = [\n            (outerPair[0], 0), # outer left\n\n            (outerPair[0], -handleLengthFactor*outerRadius), # outer left control 1\n            (outerPair[0]+outerRadius-handleLengthFactor*outerRadius, -outerRadius), # outer left control 2\n            (outerPair[0]+outerRadius, -outerRadius), # outer center\n            (outerPair[0]+outerRadius+handleLengthFactor*outerRadius, -outerRadius), # outer right control 1\n            (outerPair[1], -handleLengthFactor*outerRadius), # outer right control 2\n\n            (outerPair[1], 0), # outer right\n            (innerPair[1], 0), # inner right\n\n            (innerPair[1], -handleLengthFactor*innerRadius), # inner right control 1\n            (innerPair[0]+innerRadius+handleLengthFactor*innerRadius, -innerRadius), # inner right control 2\n            (innerPair[0]+innerRadius, -innerRadius), # inner center\n            (innerPair[0]+innerRadius-handleLengthFactor*innerRadius, -innerRadius), # inner right control 1\n            (innerPair[0], -handleLengthFactor*innerRadius), # inner right control 2\n\n            (innerPair[0], 0), # inner left\n            (outerPair[0], 0) # outer left duplicate point\n            ]\n\n            if flip:\n                flip_offset=2\n\n                verts = [\n                (outerPair[0], 0 + flip_offset), # outer left\n\n                (outerPair[0], handleLengthFactor*outerRadius + flip_offset), # outer left control 1\n                (outerPair[0]+outerRadius-handleLengthFactor*outerRadius, outerRadius + flip_offset), # outer i left control 2\n                (outerPair[0]+outerRadius, outerRadius + flip_offset), # outer center\n                (outerPair[0]+outerRadius+handleLengthFactor*outerRadius, outerRadius + flip_offset), # outer right control 1\n                (outerPair[1], handleLengthFactor*outerRadius + flip_offset), # outer right control 2\n\n                (outerPair[1], 0 + flip_offset), # outer right\n                (innerPair[1], 0 + flip_offset), # inner right\n\n                (innerPair[1], handleLengthFactor*innerRadius + flip_offset), # inner right control 1\n                (innerPair[0]+innerRadius+handleLengthFactor*innerRadius, innerRadius + flip_offset), # inner right control 2\n                (innerPair[0]+innerRadius, innerRadius + flip_offset), # inner center\n                (innerPair[0]+innerRadius-handleLengthFactor*innerRadius, innerRadius + flip_offset), # inner right control 1\n                (innerPair[0], handleLengthFactor*innerRadius + flip_offset), # inner right control 2\n\n                (innerPair[0], 0 + flip_offset), # inner left\n                (outerPair[0], 0 + flip_offset) # outer left duplicate point\n                ]\n\n            for n in range(len(verts)):\n                verts[n] = [verts[n][0], verts[n][1]-1.2]#/vert-0.013]\n            codes = [\n            Path.MOVETO,\n\n            Path.CURVE4,\n            Path.CURVE4,\n            Path.CURVE4,\n            Path.CURVE4,\n\n            Path.LINETO,\n            Path.LINETO,\n            Path.LINETO,\n\n            Path.CURVE4,\n            Path.CURVE4,\n            Path.CURVE4,\n            Path.CURVE4,\n\n            Path.LINETO,\n            Path.LINETO,\n            Path.CLOSEPOLY,\n            ]\n            path = Path(verts, codes)\n            patch = patches.PathPatch(path, facecolor=color, linewidth=0, edgecolor='none', alpha=alpha)\n            ax.add_patch(patch)\n            patch.set_clip_on(False)\n        i += 1\n\ndef arcplot(outPath=\"arcs.pdf\",title=\"\",seq=[\"A\"],pairedNucArr=[], arcColors = [],alpha=[1.0], maxDistance=None, ct=None, secondary_structure=False):\n    \"\"\"\n    draws arcs for many sets of nucleotides, pairedNucArr is a 2D array containing all sets of plotting\n    elements. arcColor is the same length as pairedNucArr but contains color strings\n\n    pairedNucArr is M x N where M is the number of plotted elements and N is the length of the RNA to plot\n    arcColors is a M x 3 array of RGB tuples for each element\n    alpha is a M x 1 array of alpha values to plot\n\n    secondary structure is a booleon that sets whether to plot the structure in the ct file above the arcs representation\n    seq is length N\n\n    function duplicated by gmr for plotting several structures on the same plot\n    \"\"\"\n\n    def findMaxDistance(pairingArrays):\n        \"\"\"\n        finds the maximum pairing distance from a 2D array of all arc elements\n        \"\"\"\n        maxDistance = 0\n\n        for pairedNucA in pairingArrays:\n            for i in range(len(pairedNucA)):\n                fromNuc = i+1\n                toNuc = pairedNucA[i]\n                if toNuc == 0:\n                    toNuc = fromNuc\n                dist = toNuc-fromNuc\n                if dist > maxDistance:\n                    maxDistance = dist\n\n        return maxDistance\n\n    import matplotlib as mp\n    mp.use('Agg')\n    mp.rcParams['xtick.major.size'] = 8\n    mp.rcParams['xtick.major.width'] = 2.5\n    mp.rcParams['xtick.direction'] = 'out'\n    mp.rcParams['xtick.minor.size'] = 4\n    mp.rcParams['xtick.minor.width'] = 1\n\n\n    import matplotlib.pyplot as plot\n    import matplotlib.patches as patches\n    import matplotlib.gridspec as gridspec\n\n    num = range(1,len(seq)+1)\n\n    # adjust the scale factor to fit on a page --gmr\n    if len(num)>10000:\n        scaleFactor = 0.0005\n    if len(num)>500:\n        scaleFactor = 0.005\n    else:\n        scaleFactor = 0.05\n\n    # find longest base-pair and scale height of plot to fit this arc\n    if not maxDistance:\n        maxDistance = findMaxDistance(pairedNucArr)\n\n    # set up figure dimensions\n    figWidth = len(seq)*scaleFactor\n    figHeight = maxDistance/2.0*scaleFactor\n\n    # double the figure height if plotting the secondary structure above the plot\n    if secondary_structure:\n        figHeight = maxDistance * scaleFactor\n\n    fig = plot.figure(figsize=(figWidth, figHeight)) # 500*scaleFactor\n\n\n    if not secondary_structure:\n        ax2 = plot.subplot(111)\n    else:\n        ax2 = plot.subplot(212)\n\n    plot.xlim(0,len(seq))\n    #ax2 = plot.gca()\n\n    # ticks on top\n    ax2.get_xaxis().tick_top()\n\n    # determine tick locations based on sequece length\n    from matplotlib.ticker import MultipleLocator, FormatStrFormatter\n    if len(seq) <= 500:\n        majorLocator = MultipleLocator(100)\n        minorLocator = MultipleLocator(10)\n        interval = 10\n    elif len(seq) <= 10000:\n        majorLocator = MultipleLocator(500)\n        minorLocator = MultipleLocator(100)\n        interval = 5\n    else:\n        majorLocator = MultipleLocator(2500)\n        minorLocator = MultipleLocator(500)\n        interval = 5\n\n    majorFormatter = FormatStrFormatter('%i')\n    minorFormatter = FormatStrFormatter('%i')\n\n    ax2.xaxis.set_major_locator(majorLocator)\n    ax2.xaxis.set_major_formatter(majorFormatter)\n    ax2.xaxis.set_minor_locator(minorLocator)\n    ax2.xaxis.set_minor_formatter(minorFormatter)\n\n\n    plot.subplots_adjust(hspace=0)\n    plot.ylim((-float(maxDistance)/2.0,0))\n    #plot.ylim((-1.0,0))\n\n    ax2.set_frame_on(False)\n    ax2.axes.get_yaxis().set_visible(False)\n    #ax2.axes.get_xaxis().tick_bottom()\n    xlabels = ax2.axes.get_xaxis().get_majorticklabels()\n    xlabels[0].set_visible(False)\n    for label in xlabels:\n        label.set_weight('bold')\n        label.set_size(14)\n        #label.set_rotation(30)\n    xlabels = ax2.axes.get_xaxis().get_minorticklabels()\n    xlabels[0].set_visible(False)\n    labelCount = 0\n    for label in xlabels:\n        label.set_size(7)\n        #label.set_rotation(30)\n        # also need to hide minor tick labels that overlap major tick labels\n        if labelCount%interval==1:\n            label.set_visible(False)\n        labelCount += 1\n\n    xticks = ax2.axes.get_xaxis().get_major_ticks()\n    xticks[0].set_visible(False)\n    xticks = ax2.axes.get_xaxis().get_minor_ticks()\n    xticks[0].set_visible(False)\n\n\n    #bothColor = \"green\"\n    #aColor = \"red\"\n    #bColor = \"purple\"\n\n    # plot the arcs\n    for arc in range(len(pairedNucArr)):\n        #if arc % 500 == 0:\n        #    print arc, len(pairedNucArr)\n        plotArcRibbons(pairedNucArr[arc], ax2, arcColors[arc], alpha=alpha[arc])\n\n    #plotArcRibbons(aOnlyPaired, ax2, aColor, alpha=alpha)\n    #plotArcRibbons(bOnlyPaired, ax2, bColor, alpha=alpha)\n    #plotArcRibbons(bothPaired, ax2, bothColor, alpha=alpha)\n\n    xmax, xmin, ymin, ymax = plot.axis()\n\n    # put nuc sequence on axis\n    if len(seq) <= 500:\n        fontProp = mp.font_manager.FontProperties(family = \"monospace\",\n                                              style=\"normal\",\n                                              weight=\"extra bold\",\n                                              size=\"4\")\n        for i in range(len(seq)):\n            nuc = seq[i]\n            if nuc == \"T\":\n                nuc = \"U\"\n            col = \"black\"\n            plot.annotate(nuc, xy=(i+0.5,ymax),fontproperties=fontProp,color=col,annotation_clip=False,verticalalignment=\"top\")\n\n    if secondary_structure:\n        ax1 = plot.subplot(211)\n        ax1.set_frame_on(False)\n        ax1.axes.get_yaxis().set_visible(False)\n        ax2.axes.get_xaxis().set_visible(False)\n        plot.xlim(0,len(seq))\n        plot.ylim(0,maxDistance/2.0)\n\n        ax1.spines[\"bottom\"].set_position((\"axes\", -0.025))\n\n        # get the helices from the ct file\n        helix = ct.extractHelices(fillPairs=False)\n\n        plot_set = []\n        plot_color = []\n        ss_color = (0.8,0.8,0.8)\n\n        for k in helix:\n            temp = np.zeros_like(ct.ct)\n            for nt in helix[k]:\n                temp[nt[0]-1] = nt[1]\n                plot_set.append(temp)\n                plot_color.append(ss_color)\n            #print(helix[k])\n        #print(helix)\n        for hel, col in zip(plot_set, plot_color):\n            plotArcRibbons(hel, ax1, col, alpha=1, flip=True)\n        #plotArcRibbons(helix, ax1, (0.8,0.8,0.8), alpha=1)\n        # xticks = ax1.axes.get_xaxis().get_major_ticks()\n        # for k in xticks:\n        #     k.set_visible(False)\n        # xticks = ax1.axes.get_xaxis().get_minor_ticks()\n        # for k in xticks:\n        #     k.set_visible(False)\n\n    plot.savefig(outPath,dpi=100,bbox_inches=\"tight\")\n\n\n\ndef splitPlot(dpObj, ctObj, pk=None, outFile=\"arcs.pdf\", secondary_structure=False):\n    \"\"\"\n    splitplot takes a RNAtools dotplot object and a ct object to generate a the figure\n\n    pk is a list pseudoknotted pairs to plot in the bottom panel\n\n    outfile is the destination for the matplotlib output, usually a pdf file or a png\n\n    secondary_structure is a booleon that sets whether to plot the secondary structure above the arc plot\n    \"\"\"\n    x = dpObj\n    y = ctObj\n\n    # binning is in log10 scale\n    #binning = [0.0,0.09691,0.5228,1.0,2.0]\n    binning = [1.5228, 1.0, 0.5228, 0.09691, 0.0]\n    # 3% 10% 30% 80% 100%\n\n    alphaList = [0.7, 0.7, 0.7, 0.3]\n    alphaList = [0.3, 0.7, 0.7, 0.7]\n    alphaList = [1.0,1.0,1.0,1.0,]\n    #alphaList = [1.0, 1.0, 1.0, 1.0]\n    #colorList  = [\"red\", \"orange\", \"yellow\", \"green\",\"blue\", \"violet\"]\n    #colorList  = [(215, 25, 28), (253, 174, 97), (171, 221, 164), (43, 131, 186)]\n    colorList  = [ (43, 131, 186), (171, 221, 164), (253, 174, 97), (215, 25, 28)]\n    colorList  = [ (150,150,150), (255,204,0),  (72,143,205) ,(81, 184, 72)  ]\n    colorList = rgb_int2pct(colorList)\n\n    nucArr = []\n    colors = []\n    alpha  = []\n\n    # bin the pairs by cutoff\n    for i in range(0, len(binning)-1):\n\n        probPairs = x.requireProb(binning[i],binning[i+1]).pairList()\n\n        for pair in probPairs:\n\n            temp = np.zeros_like(y.ct)\n            temp[pair[0]-1] = pair[1]\n\n            #tempCT = RNA.CT()\n            #tempCT.pair2CT([pair],y.seq)\n\n            #nucArr.append(tempCT.stripCT())\n            nucArr.append(temp)\n\n            #add a color from the choice list\n            colors.append(colorList[i])\n            alpha.append(alphaList[i])\n\n    if pk:\n        for pair in pk:\n            temp = np.zeros_like(y.ct)\n            temp[pair[0]-1] = pair[1]\n            nucArr.append(temp)\n            colors.append((0,0,0))\n            alpha.append(0.8)\n    #nucArr.append(y.stripCT())\n    #colors.append(\"gray\")\n\n    arcplot(outPath=outFile, pairedNucArr=nucArr, arcColors=colors,seq=y.seq, alpha=alpha, maxDistance=None, secondary_structure=secondary_structure, ct=y)\n\ndef readPKfile(fIN):\n    out = []\n    for i in open(fIN).readlines():\n        if i.lstrip()[0] == '#':\n            continue\n        pk = map(int, i.rstrip().split())\n        out.append((pk[0],pk[1]))\n    return out\n\n\ndef main():\n    # parse the command line options\n    arg = parseArgs()\n\n    # read in the reference files\n    x = RNA.dotPlot( arg.dotplot )\n    if arg.referenceCT:\n        y = RNA.CT( arg.referenceCT )\n    else:\n        # if we dont have a sequence create an empty CT file\n        y = RNA.CT()\n        # make the sequence all N as a placeholder\n        seq = \"N\"*x.length\n        y.pair2CT([], seq)\n\n    #print(y)\n\n\n    # add correction for slipped base pairs\n    #x.averageSlippedBPs(y,predictedOnly=True)\n\n    # read in the pseudoknots file if it exists\n    if arg.pkDS:\n        pkntsFile = arg.pkDS\n        pknts = readPKfile(pkntsFile)\n    else:\n        pknts = None\n\n    # main plotting loop\n    splitPlot(x, y, pk=pknts, outFile=arg.outputPDF, secondary_structure=arg.secondaryStructure)\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "79d52dbc98bbae46b89c2f3baa16f13c405a4bf4", "size": 16230, "ext": "py", "lang": "Python", "max_stars_repo_path": "RNAtools/scripts/arcsRNA.py", "max_stars_repo_name": "grice/RNAtools", "max_stars_repo_head_hexsha": "0161c0fb72c70951a126381a0ea721609c05eb5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RNAtools/scripts/arcsRNA.py", "max_issues_repo_name": "grice/RNAtools", "max_issues_repo_head_hexsha": "0161c0fb72c70951a126381a0ea721609c05eb5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RNAtools/scripts/arcsRNA.py", "max_forks_repo_name": "grice/RNAtools", "max_forks_repo_head_hexsha": "0161c0fb72c70951a126381a0ea721609c05eb5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-02-26T14:40:19.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-26T14:40:19.000Z", "avg_line_length": 34.7537473233, "max_line_length": 180, "alphanum_fraction": 0.6081330869, "include": true, "reason": "import numpy", "num_tokens": 4409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.17704614301940602}}
{"text": "\"\"\"\nCopyright (C) 2012 Alan J Lockett\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\nimport numpy as np\n\nfrom .basic import PopulationDistribution, GaussianProposal\nfrom pyec.distribution.bayes.mutators import StructureMutator\nfrom pyec.distribution.bayes.structure.proposal import StructureProposal\nfrom pyec.distribution.ec.mutators import Gaussian, Bernoulli\n\nfrom pyec.config import Config\nfrom pyec.history import DoubleMarkovHistory\n\n_ = Config\n\nclass SimulatedAnnealingAcceptance(PopulationDistribution):\n   \"\"\"A selector that implements the acceptance probability for simulated\n   annealing. Computes the acceptance ratio and samples it. If the population\n   size is greater than one, then this distribution maintains an array\n   of accepted values, and can be used to run multiple concurrent\n   markov chains.\n   \n   Config parameters\n   \n   * schedule -- The cooling schedule to use. May be any callable function, or\n                 a string, one of (\"log\", \"linear\", \"discount\"). If it is a\n                 callable, then it will be passed the ``updates`` value in\n                 :class:`History` and should return a floating point value\n                 that will divide the exponent in the Boltzmann distribution.\n                 That is, ``schedule(n)`` should converge to zero as n goes to\n                 infinity.\n   * learningRate -- A divisor for the cooling schedule, used for built-in \n                     schedules \"log\" and \"linear\". As a divisor, it divides the\n                     temperature but multiplies the exponent.\n   * temp0 -- An initial temperature for the temperature decay in \"discount\"\n   * restart -- A probability of restarting, tested at each update\n   * divisor -- A divisor that divides the ``updates`` property of\n                :class:`History`, scaling the rate of decline in the temperature\n   * discount -- The decay factor for the built-in discount schedule; ``temp0``\n                 is multiplied by ``discount`` once each time the ``update``\n                 method is called\n                \n   \"\"\"\n   config = Config(schedule=\"log\",\n                   learningRate = 1.0,\n                   temp0 = 1.0,\n                   restart = 0.0,\n                   divisor = 100.0,\n                   discount = .99,\n                   populationSize = 1,\n                   history = DoubleMarkovHistory)\n\n   def compatible(self, history):\n      return (hasattr(history, 'lastPopulation')\n              and hasattr(history, 'penultimate')\n              and hasattr(history, 'reportAcceptance'))\n\n   def batch(self, popSize):\n      temp = self.temperature()\n      last = self.history.lastPopulation()\n      penultimate = self.history.penultimate()\n      if penultimate is None:\n         return [x for x,s in last]\n      scoreProposed = np.array([s for x,s in last])\n      scoreAccepted = np.array([s for x,s in penultimate])\n      exponent = (scoreProposed - scoreAccepted) / temp\n      if self.config.minimize:\n         exponent = -exponent\n      probs = np.minimum(1.0, np.exp(exponent))\n      selection = np.random.binomial(1, probs, np.shape(probs))\n      accepted = 0.0\n      result = []\n      for i,sel in enumerate(selection):\n         if sel > 0.5:\n            result.append(last[i][0])\n            accepted += 1.0\n         else:\n            result.append(penultimate[i][0])\n      self.history.reportAcceptance(accepted / popSize)\n      return result\n      \n   def temperature(self):\n      n = 1 + float(self.history.updates) / self.config.divisor\n      if hasattr(self.config.schedule, '__call__'):\n         return self.config.schedule(n)\n      elif self.config.schedule == \"linear\":\n         return 1. / (n * self.config.learningRate)\n      elif self.config.schedule == \"log\":\n         return 1. / (np.log(n) * self.config.learningRate)\n      elif self.config.schedule == \"discount\":\n         return 1. / (self.config.temp0 * (self.config.discount ** n))\n\n\n# Euclidean space\nRealSimulatedAnnealing = (\n   SimulatedAnnealingAcceptance << GaussianProposal[_(sd=.005)]\n   #GaussianProposal[_(sd=.005)] << SimulatedAnnealingAcceptance\n)\n\n# fixed-length bit strings\nBinarySimulatedAnnealing = (\n   SimulatedAnnealingAcceptance << Bernoulli[_(p=.01)]\n   #Bernoulli[_(p=.01)] << SimulatedAnnealingAcceptance\n)\n\n# Structure search in a Bayes net, use a\n# pyec.distribution.bayes.space.BayesNetStructure space for searching.\nBayesNetSimulatedAnnealing = (\n   SimulatedAnnealingAcceptance[_(schedule=\"linear\",\n                                  divisor=100.)] <<\n   StructureMutator[_(branchFactor=5)] \n)[_(minimize=False)]\n", "meta": {"hexsha": "1a65a9240371d09e33eb6114b1e5a10c9715a148", "size": 5561, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyec/distribution/sa.py", "max_stars_repo_name": "hypernicon/pyec", "max_stars_repo_head_hexsha": "7072835c97d476fc45ffc3b34f5c3ec607988e6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-03-16T21:18:27.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-09T19:59:24.000Z", "max_issues_repo_path": "pyec/distribution/sa.py", "max_issues_repo_name": "hypernicon/pyec", "max_issues_repo_head_hexsha": "7072835c97d476fc45ffc3b34f5c3ec607988e6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyec/distribution/sa.py", "max_forks_repo_name": "hypernicon/pyec", "max_forks_repo_head_hexsha": "7072835c97d476fc45ffc3b34f5c3ec607988e6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.3416666667, "max_line_length": 460, "alphanum_fraction": 0.6734400288, "include": true, "reason": "import numpy", "num_tokens": 1216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.17704613614580653}}
{"text": "###################################################################################\n# Copyright 2021 National Technology & Engineering Solutions of Sandia,           #\n# LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the           #\n# U.S. Government retains certain rights in this software.                        #\n# If you want to use this code, please refer to the README.rst and LICENSE files. #\n###################################################################################\n\n\nimport logging\nimport numpy as np\nimport mpi4py.rc\nmpi4py.rc.initialize = False\nfrom mpi4py import MPI\nfrom PyNucleus_fem.DoFMaps import P1_DoFMap, P2_DoFMap\nfrom PyNucleus_fem import str2DoFMap\nfrom PyNucleus_base.myTypes import REAL\nfrom PyNucleus_base.linear_operators import CSR_LinearOperator\nfrom PyNucleus_base.linear_operators import SSS_LinearOperator\nfrom . restrictionProlongation import buildRestrictionProlongation\nfrom PyNucleus_base import TimerManager\nfrom PyNucleus_base.ip_norm import ip_serial, norm_serial, ip_distributed, norm_distributed\nfrom PyNucleus_fem import (assembleDrift,\n                 assembleMatrix,\n                 mass_0d_in_1d_sym_P1,\n                 mass_1d_in_2d_sym_P1,\n                 mass_1d_in_2d_sym_P2,\n                 DistributedLinearOperator,\n                 CSR_DistributedLinearOperator,\n                 function,\n                 DIRICHLET, NEUMANN, HOMOGENEOUS_DIRICHLET, HOMOGENEOUS_NEUMANN, boundaryConditions)\nfrom PyNucleus_fem.mesh import (PHYSICAL, NO_BOUNDARY, INTERIOR_NONOVERLAPPING, INTERIOR)\nLOGGER = logging.getLogger(__name__)\n\n# what should be built\nDOFMAPS = 1\nRESTRICTION_PROLONGATION = 2\nSPARSITY_PATTERN = 4\nOVERLAPS = 8\nASSEMBLY = 16\n\nNO_BUILD = 0\nDOFMAPS_ONLY = DOFMAPS\nRESTRICTION_PROLONGATION_ONLY = DOFMAPS + RESTRICTION_PROLONGATION\nSPARSITY_ONLY = DOFMAPS + OVERLAPS + RESTRICTION_PROLONGATION + SPARSITY_PATTERN\nSINGLE_LEVEL = DOFMAPS + OVERLAPS + ASSEMBLY\nFULL_BUILD = DOFMAPS + OVERLAPS + RESTRICTION_PROLONGATION + ASSEMBLY\n\n# What information is retained in meshLevels\nDELETE_MESH = 0\nKEEP_MESH = 1\n\n\nclass level:\n    def __init__(self, params, previousLevel=None,\n                 comm=None, label='', startLevelNo=0,\n                 isLastLevel=False):\n        self.params = params\n        self.previousLevel = previousLevel\n        if previousLevel is not None:\n            assert not previousLevel.isLastLevel\n        self.startLevelNo = startLevelNo\n        self.nextLevel = None\n        self.comm = comm\n        self.label = label\n        self.isLastLevel = isLastLevel\n\n        label = '{}: '.format(self.levelID)\n        self.Timer = TimerManager(LOGGER,\n                                  comm=self.comm, prefix=label)\n\n    def getLevelNo(self):\n        if self.previousLevel is None:\n            return self.startLevelNo\n        else:\n            return self.previousLevel.getLevelNo()+1\n\n    levelNo = property(fget=getLevelNo)\n\n    def getLevelID(self):\n        if len(self.label) > 0:\n            label = '{} {}'.format(self.label, self.levelNo)\n        else:\n            label = 'Level {}'.format(self.levelNo)\n        return label\n\n    levelID = property(fget=getLevelID)\n\n    def __repr__(self):\n        if len(self.label) > 0:\n            label = '{} {}'.format(self.label, self.levelNo)\n        else:\n            label = '{}'.format(self.levelNo)\n        s = '{} {}\\n'.format(self.__class__.__name__, label)\n        return s\n\n\n######################################################################\n\n\nclass meshLevel(level):\n    def __init__(self, mesh, params, previousLevel=None,\n                 interfaces=None, meshOverlaps=None,\n                 interiorBL=None,\n                 comm=None,\n                 label='', meshInformationPolicy=KEEP_MESH, startLevelNo=0,\n                 isLastLevel=False):\n        super(meshLevel, self).__init__(params, previousLevel, comm,\n                                        label, startLevelNo, isLastLevel)\n        self.mesh = mesh\n        self.global_mesh = None\n        self.interfaces = interfaces\n        if self.interfaces is not None and self.params['debugOverlaps']:\n            self.interfaces.validate(self.mesh, self.comm, label='Mesh interface \\'{} {}\\''.format(self.label, self.levelNo))\n        self.meshOverlaps = meshOverlaps\n        if self.meshOverlaps is not None and self.params['debugOverlaps']:\n            self.meshOverlaps.check(self.mesh, self.comm, label='Mesh overlap \\'{} {}\\''.format(self.label, self.levelNo))\n        self.interiorBL = interiorBL\n        self.algebraicLevel = None\n        self.meshInformationPolicy = meshInformationPolicy\n        self._h = None\n        self.algebraicLevelType = algebraicLevel\n\n    def setAlgebraicLevelType(self, algLevelType):\n        self.algebraicLevelType = algLevelType\n\n    def refine(self, meshInformationPolicy):\n        with self.Timer('Refined mesh'):\n            newMesh, self.lookup = self.mesh.refine(returnLookup=True)\n            if self.params['meshTransformation'] is not None:\n                self.params['meshTransformation'](newMesh, self.lookup)\n        if self.interfaces is not None:\n            with self.Timer('Refined interfaces'):\n                self.interfaces.refine(newMesh)\n        if self.meshOverlaps is not None:\n            with self.Timer('Refined mesh overlaps'):\n                meshOverlaps = self.meshOverlaps.copy()\n                meshOverlaps.refine(newMesh)\n        if self.meshOverlaps is None:\n            meshOverlaps = None\n        if self.interiorBL is not None:\n            with self.Timer('Refined boundary layers'):\n                self.interiorBL.refine(newMesh)\n        newMeshLevel = meshLevel(newMesh, self.params, self, self.interfaces, meshOverlaps, self.interiorBL, self.comm, self.label, meshInformationPolicy)\n        if hasattr(self, 'numberCellsBeforeExtension'):\n            newMeshLevel.numberCellsBeforeExtension = 2**self.mesh.dim * self.numberCellsBeforeExtension\n        if hasattr(self, 'numberCellsLastLayer'):\n            newMeshLevel.numberCellsLastLayer = 2**self.mesh.dim * self.numberCellsLastLayer\n        newMeshLevel.setAlgebraicLevelType(self.algebraicLevelType)\n        self.nextLevel = newMeshLevel\n        return newMeshLevel\n\n    def copy(self):\n        newMeshLevel = meshLevel(self.mesh, self.params, self, self.interfaces, self.meshOverlaps, self.interiorBL, self.comm, self.label, self.meshInformationPolicy)\n        return newMeshLevel\n\n    def getIsDistributed(self):\n        return self.interfaces is not None\n\n    isDistributed = property(fget=getIsDistributed)\n\n    def getAlgebraicLevel(self, buildType):\n        self.algebraicLevel = self.algebraicLevelType(self, buildType)\n        return self.algebraicLevel\n\n    def clean(self):\n        if self.meshInformationPolicy == DELETE_MESH:\n            self.mesh = None\n            self.meshOverlaps = None\n        self.interfaces = None\n\n    def getLevelDict(self):\n        lvl = {}\n        if self.mesh is not None:\n            lvl['mesh'] = self.mesh\n        if self.interfaces is not None:\n            lvl['interfaces'] = self.interfaces\n        if self.meshOverlaps is not None:\n            lvl['meshOverlaps'] = self.meshOverlaps\n        return lvl\n\n    @staticmethod\n    def fromLevelDict(lvl, params={}, previousLevel=None, comm=None, startLevelNo=0, label=''):\n        alvl = meshLevel(None, params, previousLevel, comm=comm, startLevelNo=startLevelNo, label=label)\n        if 'mesh' in lvl:\n            alvl.mesh = lvl['mesh']\n        if 'interfaces' in lvl:\n            alvl.interfaces = lvl['interfaces']\n        if 'meshOverlaps' in lvl:\n            alvl.meshOverlaps = lvl['meshOverlaps']\n        return alvl\n\n    def __repr__(self):\n        s = super(meshLevel, self).__repr__()\n        if self.mesh is not None:\n            s += ' mesh: '+self.mesh.__repr__()\n        if self.interfaces is not None:\n            s += self.interfaces.__repr__()\n        return s\n\n    def getH(self):\n        if self._h is None:\n            h = self.mesh.h\n            if self.comm is not None:\n                self._h = self.comm.allreduce(h, op=MPI.MAX)\n        return self._h\n\n    h = property(fget=getH)\n\n\n######################################################################\n\nclass algebraicLevelBase(level):\n    def __init__(self, meshLevel, buildType):\n        if meshLevel.previousLevel is not None:\n            previousLevel = meshLevel.previousLevel.algebraicLevel\n        else:\n            previousLevel = None\n        super(algebraicLevelBase, self).__init__(meshLevel.params, previousLevel, meshLevel.comm, meshLevel.label, meshLevel.levelNo, meshLevel.isLastLevel)\n        self.meshLevel = meshLevel\n        self.P = None\n        self.R = None\n        self.DoFMap = None\n        self.algebraicOverlaps = None\n        self.build(buildType)\n\n    def build(self, buildType):\n\n        buildNeumann = self.params.get('buildNeumann', False)\n        element = self.params['element']\n        reorder = self.params['reorder']\n        commType = self.params['commType']\n        DoFMap_type = str2DoFMap(element)\n\n        # Set DoFMap\n        if buildType & DOFMAPS:\n            if 'tag' in self.params:\n                self.DoFMap = DoFMap_type(self.meshLevel.mesh, self.params['tag'])\n            elif 'boundaryCondition' in self.params:\n                if self.params['boundaryCondition'] in (HOMOGENEOUS_NEUMANN, DIRICHLET, NEUMANN):\n                    self.DoFMap = DoFMap_type(self.meshLevel.mesh, NO_BOUNDARY)\n                elif self.params['boundaryCondition'] == HOMOGENEOUS_DIRICHLET:\n                    self.DoFMap = DoFMap_type(self.meshLevel.mesh, PHYSICAL)\n                else:\n                    raise NotImplementedError(boundaryConditions[self.params['boundaryCondition']])\n            else:\n                if self.isLastLevel and self.params['interiorBC'] == 'homogeneousDirichlet' and hasattr(self.meshLevel, 'numberCellsLastLayer'):\n                    self.DoFMap = DoFMap_type(self.meshLevel.mesh, [PHYSICAL,\n                                                                    INTERIOR],\n                                              skipCellsAfter=self.meshLevel.mesh.num_cells-self.meshLevel.numberCellsLastLayer)\n                elif not hasattr(self.meshLevel, 'numberCellsLastLayer') or not self.isLastLevel or self.params['interiorBC'] == 'homogeneousNeumann':\n                    self.DoFMap = DoFMap_type(self.meshLevel.mesh, [PHYSICAL])\n                else:\n                    raise NotImplementedError()\n            if buildNeumann:\n                self.DoFMapNeumann = DoFMap_type(self.meshLevel.mesh, [PHYSICAL])\n\n        if not reorder:\n            if buildType & OVERLAPS:\n                # build algebraic overlaps\n                if self.meshLevel.meshOverlaps is not None:\n                    with self.Timer('Build algebraic overlaps of type \\'{}\\''.format(commType)):\n                        self.algebraicOverlaps = self.meshLevel.meshOverlaps.getDoFs(self.meshLevel.mesh, self.DoFMap, commType,\n                                                                                 allowInteriorBoundary=self.params['interiorBC'] == 'homogeneousNeumann' or not self.isLastLevel)\n                    if self.params['debugOverlaps']:\n                        self.algebraicOverlaps.check(mesh=self.meshLevel.mesh,\n                                                     dm=self.DoFMap,\n                                                     label='algebraicOverlaps in \\'{} {}\\''.format(self.label, self.levelNo),\n                                                     interfaces=self.meshLevel.meshOverlaps)\n                elif self.meshLevel.interfaces is not None:\n                    with self.Timer('Build algebraic overlaps of type \\'{}\\''.format(commType)):\n                        self.algebraicOverlaps = self.meshLevel.interfaces.getDoFs(self.meshLevel.mesh, self.DoFMap, commType)\n                    if self.params['debugOverlaps']:\n                        self.algebraicOverlaps.check(mesh=self.meshLevel.mesh,\n                                                     dm=self.DoFMap,\n                                                     label='algebraicOverlaps in \\'{} {}\\''.format(self.label, self.levelNo),\n                                                     interfaces=self.meshLevel.interfaces)\n\n            if self.algebraicOverlaps is not None:\n                self.inner = ip_distributed(self.algebraicOverlaps, 0)\n                self.norm = norm_distributed(self.algebraicOverlaps, 0)\n            else:\n                self.inner = ip_serial()\n                self.norm = norm_serial()\n            if self.DoFMap is not None:\n                self.DoFMap.set_ip_norm(self.inner, self.norm)\n\n            if (buildType & RESTRICTION_PROLONGATION) and (self.previousLevel is not None):\n                assert (self.previousLevel.DoFMap is not None) and (self.DoFMap is not None)\n                # use reorder here, since reorder=False bugs out\n                (self.R,\n                 self.P) = buildRestrictionProlongation(self.previousLevel.DoFMap,\n                                                        self.DoFMap)\n\n    def buildCoarserMatrices(self):\n        \"\"\"\n        Recursively build matrices on coarser levels\n        \"\"\"\n        if self.previousLevel is not None:\n            self.previousLevel.buildCoarserMatrices()\n\n    def clean(self):\n        if not self.params['keepAllDoFMaps'] and not self.previousLevel is None:\n            self.DoFMap = None\n\n    @classmethod\n    def getKeys(cls):\n        return ['P', 'R', 'DoFMap', 'algebraicOverlaps']\n\n    def getLevelDict(self):\n        lvl = {}\n        for key in self.getKeys():\n            if getattr(self, key) is not None:\n                lvl[key] = getattr(self, key)\n        return lvl\n\n    @classmethod\n    def fromLevelDict(cls, meshLevel, lvl):\n        alvl = algebraicLevel(meshLevel, NO_BUILD)\n        for key in cls.getKeys():\n            if key in lvl:\n                setattr(alvl, key, lvl[key])\n        return alvl\n\n    @property\n    def accumulateOperator(self):\n        if self.algebraicOverlaps is not None:\n            return self.algebraicOverlaps.getAccumulateOperator()\n        else:\n            return None\n\n\nclass algebraicLevel(algebraicLevelBase):\n    def __init__(self, meshLevel, buildType):\n        self.A = None\n        self.S = None\n        self.D = None\n        self.M = None\n        self.surface_mass = None\n        self.surface_stiffness = None\n        super(algebraicLevel, self).__init__(meshLevel, buildType)\n\n    def build(self, buildType):\n        super(algebraicLevel, self).build(buildType)\n\n        diffusivity = self.params['diffusivity']\n        reaction = self.params['reaction']\n        symmetric = self.params['symmetric']\n        element = self.params['element']\n        reorder = self.params['reorder']\n        commType = self.params['commType']\n        buildMass = self.params['buildMass'] or reaction is not None\n        driftCoeff = self.params.get('driftCoeff', None)\n        buildNeumann = self.params.get('buildNeumann', False)\n\n        if buildType & SPARSITY_PATTERN:\n            # set up sparsity patterns only\n            DoFMap = self.DoFMap\n            mesh = self.meshLevel.mesh\n            self.fullyAssembled = False\n            with self.Timer('Prepared sparsity patterns'):\n                self.S = DoFMap.buildSparsityPattern(mesh.cells,\n                                                     symmetric=symmetric,\n                                                     reorder=reorder)\n                if driftCoeff is not None:\n                    self.D = self.S.copy()\n                if buildMass:\n                    self.M = self.S.copy()\n\n        if buildType & ASSEMBLY:\n            # fully build matrices\n            DoFMap = self.DoFMap\n            mesh = self.meshLevel.mesh\n            self.fullyAssembled = True\n            with self.Timer('Assembled matrices'):\n                self.S = DoFMap.assembleStiffness(sss_format=symmetric,\n                                                  reorder=reorder,\n                                                  diffusivity=diffusivity)\n                if buildMass:\n                    self.M = DoFMap.assembleMass(sss_format=symmetric,\n                                                 reorder=reorder)\n                if driftCoeff is not None:\n                    self.D = assembleDrift(mesh,\n                                           DoFMap,\n                                           driftCoeff)\n                if buildNeumann:\n                    self.neumannA = self.DoFMapNeumann.assembleStiffness(sss_format=symmetric,\n                                                                         reorder=reorder,\n                                                                         diffusivity=diffusivity)\n                if isinstance(reaction, (float, REAL)):\n                    self.A = self.S.copy()\n                    for j in range(self.A.data.shape[0]):\n                        self.A.data[j] += reaction*self.M.data[j]\n                        if isinstance(self.A, SSS_LinearOperator):\n                            for j in range(self.A.num_rows):\n                                self.A.diagonal[j] += reaction*self.M.diagonal[j]\n                elif isinstance(reaction, function):\n                    self.A = self.S.copy()\n                    dm = self.DoFMap\n                    c = dm.interpolate(reaction)\n                    for k in range(dm.num_dofs):\n                        for j in range(self.A.indptr[k], self.A.indptr[k+1]):\n                            self.A.data[j] += c[k]*self.M.data[j]\n                    if isinstance(self.A, SSS_LinearOperator):\n                        for k in range(self.A.num_rows):\n                            self.A.diagonal[k] += c[k]*self.M.diagonal[k]\n                elif reaction is None:\n                    self.A = self.S\n                else:\n                    raise NotImplementedError()\n\n            # surface mass matrix\n            if self.isLastLevel and self.params['buildSurfaceMass']:\n                with self.Timer('Build surface mass matrix'):\n                    if self.params['depth'] > 0:\n                        surface = mesh.get_surface_mesh(INTERIOR)\n                    else:\n                        surface = mesh.get_surface_mesh(INTERIOR_NONOVERLAPPING)\n                    from PyNucleus_fem import assembleSurfaceMass\n                    self.surface_mass = assembleSurfaceMass(mesh, surface,\n                                                            self.DoFMap,\n                                                            sss_format=symmetric,\n                                                            reorder=reorder)\n                    # ToDo: Don't just copy the sparsity pattern, this is a big waste of memory\n                    # data = np.zeros((self.A.nnz), dtype=REAL)\n                    # if symmetric:\n                    #     diagonal = np.zeros(self.A.shape[0], dtype=REAL)\n                    #     M = SSS_LinearOperator(self.A.indices, self.A.indptr, data, diagonal)\n                    # else:\n                    #     M = CSR_LinearOperator(self.A.indices, self.A.indptr, data)\n                    # if element == 'P1':\n                    #     dmS = P1_DoFMap(mesh, [PHYSICAL])\n                    #     dmS.cells = surface.cells\n                    # elif element == 'P2':\n                    #     assert False, \"Surface mass matrix not implemented for P2.\"\n                    #     dmS = P2_DoFMap(mesh, [PHYSICAL])\n                    #     cellOrig = dmS.mesh.cells\n                    #     dmS.mesh.cells = surface.cells\n                    # if mesh.dim == 1 and element == 'P1':\n                    #     dmS.dofs_per_element = 1\n                    #     self.surface_mass = assembleMatrix(surface, dmS, mass_0d_in_1d_sym_P1(), A=M,\n                    #                                       sss_format=symmetric, reorder=reorder)\n                    # elif mesh.dim == 2 and element == 'P1':\n                    #     dmS.dofs_per_element = 2\n                    #     self.surface_mass = assembleMatrix(surface, dmS, mass_1d_in_2d_sym_P1(), A=M,\n                    #                                        sss_format=symmetric, reorder=reorder)\n                    # elif mesh.dim == 2 and element == 'P2':\n                    #     dmS.dofs_per_element = 3\n                    #     self.surface_mass = assembleMatrix(surface, dmS, mass_1d_in_2d_sym_P2(), A=M,\n                    #                                       sss_format=symmetric, reorder=reorder)\n                    #     dmS.mesh.cells = cellOrig\n                    # else:\n                    #     raise NotImplementedError()\n\n            # surface stiffness matrix\n            if self.isLastLevel and self.params['buildSurfaceStiffness']:\n                with self.Timer('Build surface stiffness matrix'):\n                    if self.params['depth'] > 0:\n                        surface = mesh.get_surface_mesh(INTERIOR)\n                    else:\n                        surface = mesh.get_surface_mesh(INTERIOR_NONOVERLAPPING)\n                    # ToDo: Don't just copy the sparsity pattern, this is a big waste of memory\n                    data = np.zeros((self.A.nnz), dtype=REAL)\n                    if symmetric:\n                        diagonal = np.zeros(self.A.shape[0], dtype=REAL)\n                        AS = SSS_LinearOperator(self.A.indices, self.A.indptr, data, diagonal)\n                    else:\n                        AS = CSR_LinearOperator(self.A.indices, self.A.indptr, data)\n                    assert element == 'P1', \"Surface stiffness matrix only implemented for P1\"\n                    dmS = P1_DoFMap(mesh, [PHYSICAL])\n                    dmS.cells = surface.cells\n                    if mesh.dim == 2:\n                        dmS.dofs_per_element = 2\n                        self.surfaceStiffness = assembleMatrix(surface, dmS, stiffness_1d_in_2d_sym(), A=AS,\n                                                               sss_format=symmetric, reorder=reorder)\n                    else:\n                        raise NotImplementedError()\n\n        if reorder and buildType & OVERLAPS:\n            # build algebraic overlaps\n            if self.meshLevel.meshOverlaps is not None:\n                with self.Timer('Build algebraic overlaps of type \\'{}\\''.format(commType)):\n                    self.algebraicOverlaps = self.meshLevel.meshOverlaps.getDoFs(self.meshLevel.mesh, self.DoFMap, commType,\n                                                                                 allowInteriorBoundary=self.params['interiorBC'] == 'homogeneousNeumann' or not self.isLastLevel)\n                if self.params['debugOverlaps']:\n                    self.algebraicOverlaps.check(mesh=self.meshLevel.mesh,\n                                                 dm=self.DoFMap,\n                                                 label='algebraicOverlaps in \\'{} {}\\''.format(self.label, self.levelNo),\n                                                 interfaces=self.meshLevel.meshOverlaps)\n            elif self.meshLevel.interfaces is not None:\n                with self.Timer('Build algebraic overlaps of type \\'{}\\''.format(commType)):\n                    self.algebraicOverlaps = self.meshLevel.interfaces.getDoFs(self.meshLevel.mesh, self.DoFMap, commType)\n                if self.params['debugOverlaps']:\n                    self.algebraicOverlaps.check(mesh=self.meshLevel.mesh,\n                                                 dm=self.DoFMap,\n                                                 label='algebraicOverlaps in \\'{} {}\\''.format(self.label, self.levelNo),\n                                                 interfaces=self.meshLevel.interfaces)\n\n        if reorder and (buildType & RESTRICTION_PROLONGATION) and (self.previousLevel is not None):\n            assert (self.previousLevel.DoFMap is not None) and (self.DoFMap is not None)\n            # use reorder here, since reorder=False bugs out\n            (self.R,\n             self.P) = buildRestrictionProlongation(self.previousLevel.DoFMap,\n                                                    self.DoFMap)\n\n    def buildCoarserMatrices(self):\n        \"\"\"\n        Recursively build matrices on coarser levels\n        \"\"\"\n        if self.previousLevel is None:\n            return\n        if self.S is not None and self.P is not None and self.previousLevel.S is not None and not self.previousLevel.fullyAssembled:\n            assert self.P.shape[0] == self.S.shape[0], (self.R.shape[1], self.S.shape[0])\n            assert self.P.shape[1] == self.previousLevel.S.shape[0]\n            with self.Timer('Restrict stiffness matrix'):\n                self.P.restrictMatrix(self.S, self.previousLevel.S)\n            if self.previousLevel.A is None:\n                self.previousLevel.A = self.previousLevel.S\n        if self.D is not None and self.P is not None and self.previousLevel.D is not None and not self.previousLevel.fullyAssembled:\n            assert self.P.shape[0] == self.D.shape[0]\n            assert self.P.shape[1] == self.previousLevel.D.shape[0]\n            with self.Timer('Restrict drift matrix'):\n                self.P.restrictMatrix(self.D, self.previousLevel.D)\n        if self.M is not None and self.P is not None and self.previousLevel.M is not None and not self.previousLevel.fullyAssembled:\n            assert self.P.shape[0] == self.M.shape[0]\n            assert self.P.shape[1] == self.previousLevel.M.shape[0]\n            with self.Timer('Restrict mass matrix'):\n                self.P.restrictMatrix(self.M, self.previousLevel.M)\n        if self.M is not None and self.A is not None and self.R is not None and self.previousLevel.A is not None and self.previousLevel.M is not None:\n            reaction = self.params['reaction']\n            if isinstance(reaction, (float, REAL)):\n                for j in range(self.previousLevel.A.data.shape[0]):\n                    self.previousLevel.A.data[j] += reaction*self.previousLevel.M.data[j]\n                    if isinstance(self.previousLevel.A, SSS_LinearOperator):\n                        for j in range(self.previousLevel.A.num_rows):\n                            self.previousLevel.A.diagonal[j] += reaction*self.previousLevel.M.diagonal[j]\n            elif isinstance(reaction, function):\n                dm = self.previousLevel.DoFMap\n                c = dm.interpolate(reaction)\n                for k in range(dm.num_dofs):\n                    for j in range(self.previousLevel.A.indptr[k], self.previousLevel.A.indptr[k+1]):\n                        self.previousLevel.A.data[j] += c[k]*self.previousLevel.M.data[j]\n                if isinstance(self.previousLevel.A, SSS_LinearOperator):\n                    for k in range(self.previousLevel.A.num_rows):\n                        self.previousLevel.A.diagonal[k] += c[k]*self.previousLevel.M.diagonal[k]\n            elif reaction is None:\n                pass\n            else:\n                raise NotImplementedError()\n        if self.previousLevel is not None:\n            self.previousLevel.fullyAssembled = True\n            self.previousLevel.buildCoarserMatrices()\n\n    @classmethod\n    def getKeys(cls):\n        return algebraicLevelBase.getKeys() + ['A', 'S', 'D', 'M', 'surface_mass', 'surface_stiffness']\n\n    def getLevelDict(self):\n        lvl = super(algebraicLevel, self).getLevelDict()\n        if hasattr(self, ' neumannA'):\n            lvl['neumannA'] = self.neumannA\n        return lvl\n\n    def getGlobalA(self, doDistribute=False, keepDistributedResult=False):\n        if self.A is not None:\n            if self.algebraicOverlaps is not None:\n                if isinstance(self.A, CSR_LinearOperator):\n                    return CSR_DistributedLinearOperator(self.A, self.algebraicOverlaps,\n                                                         doDistribute=doDistribute,\n                                                         keepDistributedResult=keepDistributedResult)\n                else:\n                    return DistributedLinearOperator(self.A, self.algebraicOverlaps,\n                                                     doDistribute=doDistribute,\n                                                     keepDistributedResult=keepDistributedResult)\n            else:\n                return self.A\n        else:\n            return None\n", "meta": {"hexsha": "4a72353de10a494ddfb505e6cf0fa4fa65229651", "size": 28397, "ext": "py", "lang": "Python", "max_stars_repo_path": "multilevelSolver/PyNucleus_multilevelSolver/levels.py", "max_stars_repo_name": "sandialabs/PyNucleus", "max_stars_repo_head_hexsha": "98b87cf779c2c1853ce16d47998b692f594a55a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "multilevelSolver/PyNucleus_multilevelSolver/levels.py", "max_issues_repo_name": "sandialabs/PyNucleus", "max_issues_repo_head_hexsha": "98b87cf779c2c1853ce16d47998b692f594a55a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multilevelSolver/PyNucleus_multilevelSolver/levels.py", "max_forks_repo_name": "sandialabs/PyNucleus", "max_forks_repo_head_hexsha": "98b87cf779c2c1853ce16d47998b692f594a55a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.1297577855, "max_line_length": 177, "alphanum_fraction": 0.5536500335, "include": true, "reason": "import numpy", "num_tokens": 5888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.17704613614580653}}
{"text": "# Copyright 2018-2021 Xanadu Quantum Technologies Inc.\r\n\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n\r\n#     http://www.apache.org/licenses/LICENSE-2.0\r\n\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\"\"\"Multiple dispatch functions\"\"\"\r\n# pylint: disable=import-outside-toplevel,too-many-return-statements\r\nimport warnings\r\nfrom collections.abc import Sequence\r\nimport functools\r\n\r\nfrom autograd.numpy.numpy_boxes import ArrayBox\r\nfrom autoray import numpy as np\r\nfrom numpy import ndarray\r\n\r\nfrom . import single_dispatch  # pylint:disable=unused-import\r\nfrom .utils import cast, get_interface, requires_grad\r\n\r\n\r\ndef _multi_dispatch(values):\r\n    \"\"\"Determines the correct framework to dispatch to given a\r\n    sequence of tensor-like objects.\r\n\r\n    Args:\r\n        values (Sequence[tensor_like]): a sequence of tensor like objects\r\n\r\n    Returns:\r\n        str: the name of the interface\r\n\r\n    To determine the framework to dispatch to, the following rules\r\n    are applied:\r\n\r\n    * Tensors that are incompatible (such as Torch and TensorFlow tensors)\r\n      cannot both be present.\r\n\r\n    * Autograd tensors *may* be present alongside Torch and TensorFlow tensors,\r\n      but Torch and TensorFlow take precendence; the autograd arrays will\r\n      be treated as non-differentiable NumPy arrays. A warning will be raised\r\n      suggesting that vanilla NumPy be used instead.\r\n\r\n    * Vanilla NumPy arrays and SciPy sparse matrices can be used alongside other tensor objects;\r\n      they will always be treated as non-differentiable constants.\r\n    \"\"\"\r\n    if \"resource_variable\" in getattr(values, \"__module__\", tuple()):\r\n        values = np.asarray(values)\r\n\r\n    interfaces = {get_interface(v) for v in values}\r\n\r\n    if len(set(interfaces) - {\"numpy\", \"scipy\", \"autograd\"}) > 1:\r\n        # contains multiple non-autograd interfaces\r\n        raise ValueError(\"Tensors contain mixed types; cannot determine dispatch library\")\r\n\r\n    non_numpy_scipy_interfaces = set(interfaces) - {\"numpy\", \"scipy\"}\r\n\r\n    if len(non_numpy_scipy_interfaces) > 1:\r\n        # contains autograd and another interface\r\n        warnings.warn(\r\n            f\"Contains tensors of types {non_numpy_scipy_interfaces}; dispatch will prioritize \"\r\n            \"TensorFlow and PyTorch over autograd. Consider replacing Autograd with vanilla NumPy.\",\r\n            UserWarning,\r\n        )\r\n\r\n    if \"tensorflow\" in interfaces:\r\n        return \"tensorflow\"\r\n\r\n    if \"torch\" in interfaces:\r\n        return \"torch\"\r\n\r\n    if \"autograd\" in interfaces:\r\n        return \"autograd\"\r\n\r\n    if \"jax\" in interfaces:\r\n        return \"jax\"\r\n\r\n    return \"numpy\"\r\n\r\n\r\ndef multi_dispatch(argnum=None, tensor_list=None):\r\n    r\"\"\"Decorater to dispatch arguments handled by the interface.\r\n\r\n    This helps simplify definitions of new functions inside PennyLane. We can\r\n    decorate the function, indicating the arguments that are tensors handled\r\n    by the interface:\r\n\r\n\r\n    >>> @qml.math.multi_dispatch(argnum=[0, 1])\r\n    ... def some_function(tensor1, tensor2, option, like):\r\n    ...     # the interface string is stored in `like`.\r\n    ...     ...\r\n\r\n\r\n    Args:\r\n        argnum (list[int]): A list of integers indicating indicating the indices\r\n            to dispatch (i.e., the arguments that are tensors handled by an interface).\r\n            If ``None``, dispatch over all arguments.\r\n        tensor_lists (list[int]): a list of integers indicating which indices\r\n            in ``argnum`` are expected to be lists of tensors. If an argument\r\n            marked as tensor list is not a ``tuple`` or ``list``, it is treated\r\n            as if it was not marked as tensor list. If ``None``, this option is ignored.\r\n\r\n    Returns:\r\n        func: A wrapped version of the function, which will automatically attempt\r\n        to dispatch to the correct autodifferentiation framework for the requested\r\n        arguments. Note that the ``like`` argument will be optional, but can be provided\r\n        if an explicit override is needed.\r\n\r\n    .. seealso:: :func:`pennylane.math.multi_dispatch._multi_dispatch`\r\n\r\n    .. note::\r\n        This decorator makes the interface argument \"like\" optional as it utilizes\r\n        the utility function `_multi_dispatch` to automatically detect the appropriate\r\n        interface based on the tensor types.\r\n\r\n    **Examples**\r\n\r\n    We can redefine external functions to be suitable for PennyLane. Here, we\r\n    redefine Autoray's ``stack`` function.\r\n\r\n    >>> stack = multi_dispatch(argnum=0, tensor_list=0)(autoray.numpy.stack)\r\n\r\n    We can also use the ``multi_dispatch`` decorator to dispatch\r\n    arguments of more more elaborate custom functions. Here is an example\r\n    of a ``custom_function`` that\r\n    computes :math:`c \\\\sum_i (v_i)^T v_i`, where :math:`v_i` are vectors in ``values`` and\r\n    :math:`c` is a fixed ``coefficient``. Note how ``argnum=0`` only points to the first argument ``values``,\r\n    how ``tensor_list=0`` indicates that said first argument is a list of vectors, and that ``coefficient`` is not\r\n    dispatched.\r\n\r\n    >>> @math.multi_dispatch(argnum=0, tensor_list=0)\r\n    >>> def custom_function(values, like, coefficient=10):\r\n    >>>     # values is a list of vectors\r\n    >>>     # like can force the interface (optional)\r\n    >>>     if like == \"tensorflow\":\r\n    >>>         # add interface-specific handling if necessary\r\n    >>>     return coefficient * np.sum([math.dot(v,v) for v in values])\r\n\r\n    We can then run\r\n\r\n    >>> values = [np.array([1, 2, 3]) for _ in range(5)]\r\n    >>> custom_function(values)\r\n    700\r\n\r\n    \"\"\"\r\n\r\n    def decorator(fn):\r\n        @functools.wraps(fn)\r\n        def wrapper(*args, **kwargs):\r\n            argnums = argnum if argnum is not None else list(range(len(args)))\r\n            tensor_lists = tensor_list if tensor_list is not None else []\r\n\r\n            if not isinstance(argnums, Sequence):\r\n                argnums = [argnums]\r\n            if not isinstance(tensor_lists, Sequence):\r\n                tensor_lists = [tensor_lists]\r\n\r\n            dispatch_args = []\r\n\r\n            for a in argnums:\r\n                # Only use extend if the marked argument really\r\n                # is a (native) python Sequence\r\n                if a in tensor_lists and isinstance(args[a], (list, tuple)):\r\n                    dispatch_args.extend(args[a])\r\n                else:\r\n                    dispatch_args.append(args[a])\r\n\r\n            interface = kwargs.pop(\"like\", None)\r\n            interface = interface or _multi_dispatch(dispatch_args)\r\n            kwargs[\"like\"] = interface\r\n\r\n            return fn(*args, **kwargs)\r\n\r\n        return wrapper\r\n\r\n    return decorator\r\n\r\n\r\n@multi_dispatch(argnum=[0], tensor_list=[0])\r\ndef block_diag(values, like=None):\r\n    \"\"\"Combine a sequence of 2D tensors to form a block diagonal tensor.\r\n\r\n    Args:\r\n        values (Sequence[tensor_like]): Sequence of 2D arrays/tensors to form\r\n            the block diagonal tensor.\r\n\r\n    Returns:\r\n        tensor_like: the block diagonal tensor\r\n\r\n    **Example**\r\n\r\n    >>> t = [\r\n    ...     np.array([[1, 2], [3, 4]]),\r\n    ...     torch.tensor([[1, 2, 3], [-1, -6, -3]]),\r\n    ...     torch.tensor(5)\r\n    ... ]\r\n    >>> qml.math.block_diag(t)\r\n    tensor([[ 1,  2,  0,  0,  0,  0],\r\n            [ 3,  4,  0,  0,  0,  0],\r\n            [ 0,  0,  1,  2,  3,  0],\r\n            [ 0,  0, -1, -6, -3,  0],\r\n            [ 0,  0,  0,  0,  0,  5]])\r\n    \"\"\"\r\n    values = np.coerce(values, like=like)\r\n    return np.block_diag(values, like=like)\r\n\r\n\r\n@multi_dispatch(argnum=[0], tensor_list=[0])\r\ndef concatenate(values, axis=0, like=None):\r\n    \"\"\"Concatenate a sequence of tensors along the specified axis.\r\n\r\n    .. warning::\r\n\r\n        Tensors that are incompatible (such as Torch and TensorFlow tensors)\r\n        cannot both be present.\r\n\r\n    Args:\r\n        values (Sequence[tensor_like]): Sequence of tensor-like objects to\r\n            concatenate. The objects must have the same shape, except in the dimension corresponding\r\n            to axis (the first, by default).\r\n        axis (int): The axis along which the input tensors are concatenated. If axis is None,\r\n            tensors are flattened before use. Default is 0.\r\n\r\n    Returns:\r\n        tensor_like: The concatenated tensor.\r\n\r\n    **Example**\r\n\r\n    >>> x = tf.constant([0.6, 0.1, 0.6])\r\n    >>> y = tf.Variable([0.1, 0.2, 0.3])\r\n    >>> z = np.array([5., 8., 101.])\r\n    >>> concatenate([x, y, z])\r\n    <tf.Tensor: shape=(3, 3), dtype=float32, numpy=\r\n    array([6.00e-01, 1.00e-01, 6.00e-01, 1.00e-01, 2.00e-01, 3.00e-01, 5.00e+00, 8.00e+00, 1.01e+02], dtype=float32)>\r\n    \"\"\"\r\n\r\n    if like == \"torch\":\r\n        import torch\r\n\r\n        device = (\r\n            \"cuda\"\r\n            if any(t.device.type == \"cuda\" for t in values if isinstance(t, torch.Tensor))\r\n            else \"cpu\"\r\n        )\r\n\r\n        if axis is None:\r\n            # flatten and then concatenate zero'th dimension\r\n            # to reproduce numpy's behaviour\r\n            values = [\r\n                np.flatten(torch.as_tensor(t, device=torch.device(device)))  # pragma: no cover\r\n                for t in values\r\n            ]\r\n            axis = 0\r\n        else:\r\n            values = [\r\n                torch.as_tensor(t, device=torch.device(device)) for t in values  # pragma: no cover\r\n            ]\r\n\r\n    if like == \"tensorflow\" and axis is None:\r\n        # flatten and then concatenate zero'th dimension\r\n        # to reproduce numpy's behaviour\r\n        values = [np.flatten(np.array(t)) for t in values]\r\n        axis = 0\r\n\r\n    return np.concatenate(values, axis=axis, like=like)\r\n\r\n\r\n@multi_dispatch(argnum=[0], tensor_list=[0])\r\ndef diag(values, k=0, like=None):\r\n    \"\"\"Construct a diagonal tensor from a list of scalars.\r\n\r\n    Args:\r\n        values (tensor_like or Sequence[scalar]): sequence of numeric values that\r\n            make up the diagonal\r\n        k (int): The diagonal in question. ``k=0`` corresponds to the main diagonal.\r\n            Use ``k>0`` for diagonals above the main diagonal, and ``k<0`` for\r\n            diagonals below the main diagonal.\r\n\r\n    Returns:\r\n        tensor_like: the 2D diagonal tensor\r\n\r\n    **Example**\r\n\r\n    >>> x = [1., 2., tf.Variable(3.)]\r\n    >>> qml.math.diag(x)\r\n    <tf.Tensor: shape=(3, 3), dtype=float32, numpy=\r\n    array([[1., 0., 0.],\r\n           [0., 2., 0.],\r\n           [0., 0., 3.]], dtype=float32)>\r\n    >>> y = tf.Variable([0.65, 0.2, 0.1])\r\n    >>> qml.math.diag(y, k=-1)\r\n    <tf.Tensor: shape=(4, 4), dtype=float32, numpy=\r\n    array([[0.  , 0.  , 0.  , 0.  ],\r\n           [0.65, 0.  , 0.  , 0.  ],\r\n           [0.  , 0.2 , 0.  , 0.  ],\r\n           [0.  , 0.  , 0.1 , 0.  ]], dtype=float32)>\r\n    >>> z = torch.tensor([0.1, 0.2])\r\n    >>> qml.math.diag(z, k=1)\r\n    tensor([[0.0000, 0.1000, 0.0000],\r\n            [0.0000, 0.0000, 0.2000],\r\n            [0.0000, 0.0000, 0.0000]])\r\n    \"\"\"\r\n    if isinstance(values, (list, tuple)):\r\n        values = np.stack(np.coerce(values, like=like), like=like)\r\n\r\n    return np.diag(values, k=k, like=like)\r\n\r\n\r\n@multi_dispatch(argnum=[0, 1])\r\ndef dot(tensor1, tensor2, like=None):\r\n    \"\"\"Returns the matrix or dot product of two tensors.\r\n\r\n    * If both tensors are 0-dimensional, elementwise multiplication\r\n      is performed and a 0-dimensional scalar returned.\r\n\r\n    * If both tensors are 1-dimensional, the dot product is returned.\r\n\r\n    * If the first array is 2-dimensional and the second array 1-dimensional,\r\n      the matrix-vector product is returned.\r\n\r\n    * If both tensors are 2-dimensional, the matrix product is returned.\r\n\r\n    * Finally, if the the first array is N-dimensional and the second array\r\n      M-dimensional, a sum product over the last dimension of the first array,\r\n      and the second-to-last dimension of the second array is returned.\r\n\r\n    Args:\r\n        tensor1 (tensor_like): input tensor\r\n        tensor2 (tensor_like): input tensor\r\n\r\n    Returns:\r\n        tensor_like: the matrix or dot product of two tensors\r\n    \"\"\"\r\n    x, y = np.coerce([tensor1, tensor2], like=like)\r\n\r\n    if like == \"torch\":\r\n        if x.ndim == 0 and y.ndim == 0:\r\n            return x * y\r\n\r\n        if x.ndim <= 2 and y.ndim <= 2:\r\n            return x @ y\r\n\r\n        return np.tensordot(x, y, axes=[[-1], [-2]], like=like)\r\n\r\n    if like == \"tensorflow\":\r\n        if len(np.shape(x)) == 0 and len(np.shape(y)) == 0:\r\n            return x * y\r\n\r\n        if len(np.shape(y)) == 1:\r\n            return np.tensordot(x, y, axes=[[-1], [0]], like=like)\r\n\r\n        if len(np.shape(x)) == 2 and len(np.shape(y)) == 2:\r\n            return x @ y\r\n\r\n        return np.tensordot(x, y, axes=[[-1], [-2]], like=like)\r\n\r\n    return np.dot(x, y, like=like)\r\n\r\n\r\n@multi_dispatch(argnum=[0, 1])\r\ndef tensordot(tensor1, tensor2, axes=None, like=None):\r\n    \"\"\"Returns the tensor product of two tensors.\r\n    In general ``axes`` specifies either the set of axes for both\r\n    tensors that are contracted (with the first/second entry of ``axes``\r\n    giving all axis indices for the first/second tensor) or --- if it is\r\n    an integer --- the number of last/first axes of the first/second\r\n    tensor to contract over.\r\n    There are some non-obvious special cases:\r\n\r\n    * If both tensors are 0-dimensional, ``axes`` must be 0.\r\n      and a 0-dimensional scalar is returned containing the simple product.\r\n\r\n    * If both tensors are 1-dimensional and ``axes=0``, the outer product\r\n      is returned.\r\n\r\n    * Products between a non-0-dimensional and a 0-dimensional tensor are not\r\n      supported in all interfaces.\r\n\r\n    Args:\r\n        tensor1 (tensor_like): input tensor\r\n        tensor2 (tensor_like): input tensor\r\n        axes (int or list[list[int]]): Axes to contract over, see detail description.\r\n\r\n    Returns:\r\n        tensor_like: the tensor product of the two input tensors\r\n    \"\"\"\r\n    tensor1, tensor2 = np.coerce([tensor1, tensor2], like=like)\r\n    return np.tensordot(tensor1, tensor2, axes=axes, like=like)\r\n\r\n\r\n@multi_dispatch(argnum=[0], tensor_list=[0])\r\ndef get_trainable_indices(values, like=None):\r\n    \"\"\"Returns a set containing the trainable indices of a sequence of\r\n    values.\r\n\r\n    Args:\r\n        values (Iterable[tensor_like]): Sequence of tensor-like objects to inspect\r\n\r\n    Returns:\r\n        set[int]: Set containing the indices of the trainable tensor-like objects\r\n        within the input sequence.\r\n\r\n    **Example**\r\n\r\n    >>> def cost_fn(params):\r\n    ...     print(\"Trainable:\", qml.math.get_trainable_indices(params))\r\n    ...     return np.sum(np.sin(params[0] * params[1]))\r\n    >>> values = [np.array([0.1, 0.2], requires_grad=True),\r\n    ... np.array([0.5, 0.2], requires_grad=False)]\r\n    >>> cost_fn(values)\r\n    Trainable: {0}\r\n    tensor(0.0899685, requires_grad=True)\r\n    \"\"\"\r\n    trainable = requires_grad\r\n    trainable_params = set()\r\n\r\n    if like == \"jax\":\r\n        import jax\r\n\r\n        if not any(isinstance(v, jax.core.Tracer) for v in values):\r\n            # No JAX tracing is occuring; treat all `DeviceArray` objects as trainable.\r\n            trainable = lambda p, **kwargs: isinstance(p, jax.numpy.DeviceArray)\r\n        else:\r\n            # JAX tracing is occuring; use the default behaviour (only traced arrays\r\n            # are treated as trainable). This is required to ensure that `jax.grad(func, argnums=...)\r\n            # works correctly, as the argnums argnument determines which parameters are\r\n            # traced arrays.\r\n            trainable = requires_grad\r\n\r\n    for idx, p in enumerate(values):\r\n        if trainable(p, interface=like):\r\n            trainable_params.add(idx)\r\n\r\n    return trainable_params\r\n\r\n\r\ndef ones_like(tensor, dtype=None):\r\n    \"\"\"Returns a tensor of all ones with the same shape and dtype\r\n    as the input tensor.\r\n\r\n    Args:\r\n        tensor (tensor_like): input tensor\r\n        dtype (str, np.dtype, None): The desired output datatype of the array. If not provided, the dtype of\r\n            ``tensor`` is used. This argument can be any supported NumPy dtype representation, including\r\n            a string (``\"float64\"``), a ``np.dtype`` object (``np.dtype(\"float64\")``), or\r\n            a dtype class (``np.float64``). If ``tensor`` is not a NumPy array, the\r\n            **equivalent** dtype in the dispatched framework is used.\r\n\r\n    Returns:\r\n        tensor_like: an all-ones tensor with the same shape and\r\n        size as ``tensor``\r\n\r\n    **Example**\r\n\r\n    >>> x = torch.tensor([1., 2.])\r\n    >>> ones_like(x)\r\n    tensor([1, 1])\r\n    >>> y = tf.Variable([[0], [5]])\r\n    >>> ones_like(y, dtype=np.complex128)\r\n    <tf.Tensor: shape=(2, 1), dtype=complex128, numpy=\r\n    array([[1.+0.j],\r\n           [1.+0.j]])>\r\n    \"\"\"\r\n    if dtype is not None:\r\n        return cast(np.ones_like(tensor), dtype)\r\n\r\n    return np.ones_like(tensor)\r\n\r\n\r\n@multi_dispatch(argnum=[0], tensor_list=[0])\r\ndef stack(values, axis=0, like=None):\r\n    \"\"\"Stack a sequence of tensors along the specified axis.\r\n\r\n    .. warning::\r\n\r\n        Tensors that are incompatible (such as Torch and TensorFlow tensors)\r\n        cannot both be present.\r\n\r\n    Args:\r\n        values (Sequence[tensor_like]): Sequence of tensor-like objects to\r\n            stack. Each object in the sequence must have the same size in the given axis.\r\n        axis (int): The axis along which the input tensors are stacked. ``axis=0`` corresponds\r\n            to vertical stacking.\r\n\r\n    Returns:\r\n        tensor_like: The stacked array. The stacked array will have one additional dimension\r\n        compared to the unstacked tensors.\r\n\r\n    **Example**\r\n\r\n    >>> x = tf.constant([0.6, 0.1, 0.6])\r\n    >>> y = tf.Variable([0.1, 0.2, 0.3])\r\n    >>> z = np.array([5., 8., 101.])\r\n    >>> stack([x, y, z])\r\n    <tf.Tensor: shape=(3, 3), dtype=float32, numpy=\r\n    array([[6.00e-01, 1.00e-01, 6.00e-01],\r\n           [1.00e-01, 2.00e-01, 3.00e-01],\r\n           [5.00e+00, 8.00e+00, 1.01e+02]], dtype=float32)>\r\n    \"\"\"\r\n    values = np.coerce(values, like=like)\r\n    return np.stack(values, axis=axis, like=like)\r\n\r\n\r\ndef where(condition, x=None, y=None):\r\n    \"\"\"Returns elements chosen from x or y depending on a boolean tensor condition,\r\n    or the indices of entries satisfying the condition.\r\n\r\n    The input tensors ``condition``, ``x``, and ``y`` must all be broadcastable to the same shape.\r\n\r\n    Args:\r\n        condition (tensor_like[bool]): A boolean tensor. Where ``True`` , elements from\r\n            ``x`` will be chosen, otherwise ``y``. If ``x`` and ``y`` are ``None`` the\r\n            indices where ``condition==True`` holds will be returned.\r\n        x (tensor_like): values from which to choose if the condition evaluates to ``True``\r\n        y (tensor_like): values from which to choose if the condition evaluates to ``False``\r\n\r\n    Returns:\r\n        tensor_like or tuple[tensor_like]: If ``x is None`` and ``y is None``, a tensor\r\n        or tuple of tensors with the indices where ``condition`` is ``True`` .\r\n        Else, a tensor with elements from ``x`` where the ``condition`` is ``True``,\r\n        and ``y`` otherwise. In this case, the output tensor has the same shape as\r\n        the input tensors.\r\n\r\n    **Example with three arguments**\r\n\r\n    >>> a = torch.tensor([0.6, 0.23, 0.7, 1.5, 1.7], requires_grad=True)\r\n    >>> b = torch.tensor([-1., -2., -3., -4., -5.], requires_grad=True)\r\n    >>> math.where(a < 1, a, b)\r\n    tensor([ 0.6000,  0.2300,  0.7000, -4.0000, -5.0000], grad_fn=<SWhereBackward>)\r\n\r\n    .. warning::\r\n\r\n        The output format for ``x=None`` and ``y=None`` follows the respective\r\n        interface and differs between TensorFlow and all other interfaces:\r\n        For TensorFlow, the output is a tensor with shape\r\n        ``(num_true, len(condition.shape))`` where ``num_true`` is the number\r\n        of entries in ``condition`` that are ``True`` .\r\n        The entry at position ``(i, j)`` is the ``j`` th entry of the ``i`` th\r\n        index.\r\n        For all other interfaces, the output is a tuple of tensor-like objects,\r\n        with the ``j`` th object indicating the ``j`` th entries of all indices.\r\n        Also see the examples below.\r\n\r\n    **Example with single argument**\r\n\r\n    For Torch, Autograd, JAX and NumPy, the output formatting is as follows:\r\n\r\n    >>> a = [[0.6, 0.23, 1.7],[1.5, 0.7, -0.2]]\r\n    >>> math.where(torch.tensor(a) < 1)\r\n    (tensor([0, 0, 1, 1]), tensor([0, 1, 1, 2]))\r\n\r\n    This is not a single tensor-like object but corresponds to the shape\r\n    ``(2, 4)`` . For TensorFlow, on the other hand:\r\n\r\n    >>> math.where(tf.constant(a) < 1)\r\n    tf.Tensor(\r\n    [[0 0]\r\n     [0 1]\r\n     [1 1]\r\n     [1 2]], shape=(4, 2), dtype=int64)\r\n\r\n    As we can see, the dimensions are swapped and the output is a single Tensor.\r\n    Note that the number of dimensions of the output does *not* depend on the input\r\n    shape, it is always two-dimensional.\r\n\r\n    \"\"\"\r\n    if x is None and y is None:\r\n        interface = _multi_dispatch([condition])\r\n        return np.where(condition, like=interface)\r\n\r\n    interface = _multi_dispatch([condition, x, y])\r\n    res = np.where(condition, x, y, like=interface)\r\n\r\n    if interface == \"tensorflow\":\r\n        return np.transpose(np.stack(res))\r\n\r\n    return res\r\n\r\n\r\n@multi_dispatch(argnum=[0, 1])\r\ndef frobenius_inner_product(A, B, normalize=False, like=None):\r\n    r\"\"\"Frobenius inner product between two matrices.\r\n\r\n    .. math::\r\n\r\n        \\langle A, B \\rangle_F = \\sum_{i,j=1}^n A_{ij} B_{ij} = \\operatorname{tr} (A^T B)\r\n\r\n    The Frobenius inner product is equivalent to the Hilbert-Schmidt inner product for\r\n    matrices with real-valued entries.\r\n\r\n    Args:\r\n        A (tensor_like[float]): First matrix, assumed to be a square array.\r\n        B (tensor_like[float]): Second matrix, assumed to be a square array.\r\n        normalize (bool): If True, divide the inner product by the Frobenius norms of A and B.\r\n\r\n    Returns:\r\n        float: Frobenius inner product of A and B\r\n\r\n    **Example**\r\n\r\n    >>> A = np.random.random((3,3))\r\n    >>> B = np.random.random((3,3))\r\n    >>> qml.math.frobenius_inner_product(A, B)\r\n    3.091948202943376\r\n    \"\"\"\r\n    A, B = np.coerce([A, B], like=like)\r\n\r\n    inner_product = np.sum(A * B)\r\n\r\n    if normalize:\r\n        norm = np.sqrt(np.sum(A * A) * np.sum(B * B))\r\n        inner_product = inner_product / norm\r\n\r\n    return inner_product\r\n\r\n\r\n@multi_dispatch(argnum=[0, 2])\r\ndef scatter_element_add(tensor, index, value, like=None):\r\n    \"\"\"In-place addition of a multidimensional value over various\r\n    indices of a tensor.\r\n\r\n    Args:\r\n        tensor (tensor_like[float]): Tensor to add the value to\r\n        index (tuple or list[tuple]): Indices to which to add the value\r\n        value (float or tensor_like[float]): Value to add to ``tensor``\r\n        like (str): Manually chosen interface to dispatch to.\r\n    Returns:\r\n        tensor_like[float]: The tensor with the value added at the given indices.\r\n\r\n    **Example**\r\n\r\n    >>> tensor = torch.tensor([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]])\r\n    >>> index = (1, 2)\r\n    >>> value = -3.1\r\n    >>> qml.math.scatter_element_add(tensor, index, value)\r\n    tensor([[ 0.1000,  0.2000,  0.3000],\r\n            [ 0.4000,  0.5000, -2.5000]])\r\n\r\n    If multiple indices are given, in the form of a list of tuples, the\r\n    ``k`` th tuple is interpreted to contain the ``k`` th entry of all indices:\r\n\r\n    >>> indices = [(1, 0), (2, 1)] # This will modify the entries (1, 2) and (0, 1)\r\n    >>> values = torch.tensor([10, 20])\r\n    >>> qml.math.scatter_element_add(tensor, indices, values)\r\n    tensor([[ 0.1000, 20.2000,  0.3000],\r\n            [ 0.4000,  0.5000, 10.6000]])\r\n    \"\"\"\r\n    if len(np.shape(tensor)) == 0 and index == ():\r\n        return tensor + value\r\n\r\n    return np.scatter_element_add(tensor, index, value, like=like)\r\n\r\n\r\ndef unwrap(values, max_depth=None):\r\n    \"\"\"Unwrap a sequence of objects to NumPy arrays.\r\n\r\n    Note that tensors on GPUs will automatically be copied\r\n    to the CPU.\r\n\r\n    Args:\r\n        values (Sequence[tensor_like]): sequence of tensor-like objects to unwrap\r\n        max_depth (int): Positive integer indicating the depth of unwrapping to perform\r\n            for nested tensor-objects. This argument only applies when unwrapping\r\n            Autograd ``ArrayBox`` objects.\r\n\r\n    **Example**\r\n\r\n    >>> values = [np.array([0.1, 0.2]), torch.tensor(0.1, dtype=torch.float64), torch.tensor([0.5, 0.2])]\r\n    >>> math.unwrap(values)\r\n    [array([0.1, 0.2]), 0.1, array([0.5, 0.2], dtype=float32)]\r\n\r\n    This function will continue to work during backpropagation:\r\n\r\n    >>> def cost_fn(params):\r\n    ...     unwrapped_params = math.unwrap(params)\r\n    ...     print(\"Unwrapped:\", [(i, type(i)) for i in unwrapped_params])\r\n    ...     return np.sum(np.sin(params))\r\n    >>> params = np.array([0.1, 0.2, 0.3])\r\n    >>> grad = autograd.grad(cost_fn)(params)\r\n    Unwrapped: [(0.1, <class 'float'>), (0.2, <class 'float'>), (0.3, <class 'float'>)]\r\n    >>> print(grad)\r\n    [0.99500417 0.98006658 0.95533649]\r\n    \"\"\"\r\n    res = []\r\n\r\n    for t in values:\r\n        if isinstance(t, ArrayBox):\r\n            a = np.to_numpy(t, max_depth=max_depth)\r\n        else:\r\n            a = np.to_numpy(t)\r\n\r\n        if isinstance(a, ndarray) and not a.shape:\r\n            # if NumPy array is scalar, convert to a Python float\r\n            res.append(a.tolist())\r\n        else:\r\n            res.append(a)\r\n\r\n    return res\r\n", "meta": {"hexsha": "4a7d6d77ccd75ca8a49133232ea5fa3c8c3fd49b", "size": 25814, "ext": "py", "lang": "Python", "max_stars_repo_path": "pennylane/math/multi_dispatch.py", "max_stars_repo_name": "MoritzWillmann/pennylane", "max_stars_repo_head_hexsha": "2b07d22cfcc6406ba28e5c647062340b240a4ee5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 539, "max_stars_repo_stars_event_min_datetime": "2018-11-13T08:45:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-27T18:17:16.000Z", "max_issues_repo_path": "pennylane/math/multi_dispatch.py", "max_issues_repo_name": "MoritzWillmann/pennylane", "max_issues_repo_head_hexsha": "2b07d22cfcc6406ba28e5c647062340b240a4ee5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 588, "max_issues_repo_issues_event_min_datetime": "2018-11-14T10:21:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-28T06:27:14.000Z", "max_forks_repo_path": "pennylane/math/multi_dispatch.py", "max_forks_repo_name": "MoritzWillmann/pennylane", "max_forks_repo_head_hexsha": "2b07d22cfcc6406ba28e5c647062340b240a4ee5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 165, "max_forks_repo_forks_event_min_datetime": "2018-11-13T18:58:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-27T17:18:17.000Z", "avg_line_length": 36.6156028369, "max_line_length": 118, "alphanum_fraction": 0.6036259394, "include": true, "reason": "import numpy,from numpy,import jax", "num_tokens": 6576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.34864512856608554, "lm_q1q2_score": 0.17704613270900682}}
{"text": "#!/usr/bin/env python\n# encoding: utf-8\n\n'''\nGeneration of waterfall figures\n'''\n\n__author__      = 'Jake Retallick'\n__copyright__   = 'Apache License 2.0'\n__version__     = '1.2'\n__date__        = '2018-04-17'  # last update\n\nfrom hopper import HoppingModel\nimport os\n\nimport numpy as np\nfrom itertools import product\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LinearSegmentedColormap\n\nclass Waterfall:\n\n    log_fn = os.path.join('.', '.temp', 'waterfall.log')\n    img_fn = os.path.join('.', 'img', 'waterfall.pdf')\n\n    ppnm = 50   # pixels per nm\n    sig = .8    # 'atom diameter'\n\n    lo, hi = 1., 4.     # amplitudes of unoccupied/occupied DBs\n    portrait = True     # portrait style plotting\n    xticks = False\n\n    # coloring for plots\n    cdict = {'red':    ((0, .48, .48),\n                        (.5, .14, .14),\n                        (1., 0, 0)),\n             'green':  ((0,.82,.82),\n                        (.5,.55,.55),\n                        (1., 0, 0)),\n             'blue':   ((0,.89,.89),\n                        (.5,.70,.70),\n                        (1., 0, 0))\n             }\n\n    cm = LinearSegmentedColormap('cm', cdict)\n\n    def __init__(self, hopper):\n        '''Initialise a waterfall generator. For now, assumes the\n        device being simulated is linear in the x direction'''\n\n        self.hopper = hopper\n        self.X = .1*self.hopper.a*self.hopper.X\n        self.N = self.hopper.N\n\n\n\n    def generate(self, nscans=100, srate=10.0, pad=1.0, mu=.25):\n        '''Generate the waterfall image.\n\n        inputs:\n            nscans  : number of line scans\n            srate   : tip scan rate, in nm/s\n            pad     : padding on either side of device, in nm\n            mu      : Ef-DB- difference, eV\n        '''\n\n        if not self.hopper.initialised:\n            self.hopper.initialise()\n\n        bulk = self.hopper.getChannel('bulk')\n        if bulk is not None:\n            bulk.mu = mu\n\n        # burn\n        self.hopper.burn(10, per=True)\n\n        # determine run time of scan\n        xlo, xhi = np.min(self.X)-pad, np.max(self.X)+pad\n\n        self.T = nscans*(xhi-xlo)/srate\n\n        # populate hopping log\n        self.hopper.startLog(self.log_fn)\n        self.hopper.run(self.T)\n        self.hopper.endLog()\n\n        # simulate scan process\n        self._show(nscans, srate, xlo, xhi)\n\n    def _parser(self):\n        '''Parse the time and state information from the log file'''\n\n        with open(self.log_fn, 'r') as fp:\n            state = self.hopper.charge\n            for line in fp:\n                t, s = line.split(' :: ')\n                t = float(t)\n                s = format(int(s, base=16), '0{0}b'.format(self.N))\n                state = [int(x) for x in s]\n                yield t, state\n            yield np.inf, state     # hold on last state\n\n\n    def _show(self, nscans, srate, xlo, xhi):\n        '''Generate the waterfall from the hopping log'''\n\n        xx = np.linspace(xlo, xhi, 1+int((xhi-xlo)*self.ppnm))\n        kernel = np.exp(-np.linspace(-2,2, 1+int(self.sig*self.ppnm))**2)\n        nx = len(xx)\n\n        # index array, nearest db at each position\n        D = np.abs(xx.reshape(-1,1) - self.X.reshape(1,-1))\n        ind = np.argmin(D, axis=1)\n\n        # impulse array\n        imp = np.zeros(xx.shape, dtype=float)\n        for x in self.X:\n            n, r = divmod((x-xlo)*self.ppnm, 1)\n            imp[int(n):int(n)+2] = 1-r, r\n\n        lo_val = np.convolve(imp, self.lo*kernel, 'same')\n        hi_val = np.convolve(imp, self.hi*kernel, 'same')\n\n        # generate waterfall\n        self.state_gen = self._parser()\n        self.t, self.state = 0., None   # cache\n\n        n, dn, dt = 0, 1, (xhi-xlo)/(srate*nx)\n        data = np.zeros([nscans, nx], dtype=float)\n        for m in range(nscans):\n            for _ in range(nx):\n                data[m,n] = self._integrate(ind[n], dt)\n                n += dn\n            data[m,:] = lo_val + data[m,:]*(hi_val-lo_val)\n            n, dn = n - dn, -dn\n\n        self._plot_handler(xlo, xhi, data)\n\n\n\n    def _plot_handler(self, xlo, xhi, data):\n        '''Create the waterfall plot'''\n\n        # formatting options\n        FS = 20\n        TFS = 18\n        size, asp = 4, 1.9\n\n        if self.portrait:\n            fig, (ax, cax) = plt.subplots(nrows=2, figsize=(size, size*asp),\n                        gridspec_kw={'height_ratios': [1, .02]})\n            dat = data\n            xext, yext = xhi-xlo, self.T/60\n            xlab, tlab = ax.set_xlabel, ax.set_ylabel\n            cor = 'horizontal'\n            ax.xaxis.tick_top()\n            ax.xaxis.set_label_position('top')\n        else:\n            fig, (ax, cax) = plt.subplots(ncols=2, figsize=(size*asp, size),\n                        gridspec_kw={'width_ratios': [1, .05]})\n            dat = data.T\n            xext, yext = self.T/60, xhi-xlo\n            xlab, tlab = ax.set_ylabel, ax.set_xlabel\n            cor = 'vertical'\n\n        im = ax.imshow(dat, interpolation='None', aspect='auto', cmap=self.cm,\n                        extent=[0, xext, 0, yext])\n\n        # ticks\n        tick_fill = lambda f, ext: f([round(x*ext,1) for x in [0, .5, 1.]])\n        if self.xticks:\n            tick_fill(ax.set_xticks, xext)\n            tick_fill(ax.set_yticks, yext)\n            xlab('x (nm)', fontsize=FS)\n            tlab('Time (min)', fontsize=FS)\n        else:\n            if self.portrait:\n                ax.set_xticks([])\n                tick_fill(ax.set_yticks, yext)\n            else:\n                tick_fill(ax.set_xticks, xext)\n                ax.set_yticks([])\n            tlab('Time (min)', fontsize=FS)\n        ax.tick_params(axis='both', which='major', labelsize=TFS)\n\n        # colorbar\n        cbar = fig.colorbar(im, cax=cax, ticks=[0,self.lo,self.hi], orientation=cor)\n        cbar.set_label('Charges', fontsize=FS)\n        cbar.ax.tick_params(labelsize=TFS)\n\n        if self.portrait:\n            cbar.ax.set_xticklabels([0,1,2])\n        else:\n            cbar.ax.set_yticklabels([0,1,2])\n\n\n        plt.tight_layout(pad=0, h_pad=0, w_pad=0)\n\n        fname = self.img_fn\n        direc = os.path.dirname(fname)\n        if not os.path.isdir(direc):\n            os.makedirs(direc)\n\n        plt.savefig(fname, bbox_inches='tight')\n        plt.show()\n\n\n\n    def _integrate(self, n, dt):\n        '''Integrate the charge of the n^th DB for dt seconds'''\n\n        charge, norm = 0., 1./dt\n        while dt > 0:\n            if self.t > 0:\n                t, state = self.t, self.state\n                self.t = 0.\n            else:\n                t, state = next(self.state_gen)\n            if t<dt:\n                charge += t*state[n]\n                dt -= t\n            else:\n                charge += dt*state[n]\n                self.t, self.state = t-dt, list(state)\n                dt = 0\n\n        return charge*norm\n\n\nif __name__ == '__main__':\n\n    d1221 = [8,10,15,17]\n    d1221.insert(0, d1221[0]-7)\n    d1221.append(d1221[-1]+7)\n\n    device = d1221\n\n    model = HoppingModel(device, model='marcus')\n    model.addChannel('bulk')\n    waterfall = Waterfall(model)\n    waterfall.generate(nscans=800, srate=8.9, pad = 1.6, mu=0.1)\n", "meta": {"hexsha": "820321e6e7a2016d226d26a56856df8637bcf0ad", "size": 7138, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/archive/waterfall.py", "max_stars_repo_name": "retallickj/afm-sim", "max_stars_repo_head_hexsha": "a9211300265d34f45cccfded9a955d77f40cc692", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/archive/waterfall.py", "max_issues_repo_name": "retallickj/afm-sim", "max_issues_repo_head_hexsha": "a9211300265d34f45cccfded9a955d77f40cc692", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/archive/waterfall.py", "max_forks_repo_name": "retallickj/afm-sim", "max_forks_repo_head_hexsha": "a9211300265d34f45cccfded9a955d77f40cc692", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3744855967, "max_line_length": 84, "alphanum_fraction": 0.5126085738, "include": true, "reason": "import numpy", "num_tokens": 1982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.176956446289985}}
{"text": "\"\"\"Run a model simulation.\"\"\"\n# Default climate data is ERA-Interim; specify CMIP5 by specifying a filename to the argument:\n#    (Command line) python run_simulation_list_multiprocess.py -gcm_list_fn=C:\\...\\gcm_rcpXX_filenames.txt\n#      - Default is running ERA-Interim in parallel with five processors.\n#    (Spyder) %run run_simulation_list_multiprocess.py C:\\...\\gcm_rcpXX_filenames.txt -option_parallels=0\n#      - Spyder cannot run parallels, so always set -option_parallels=0 when testing in Spyder.\n# Spyder cannot run parallels, so always set -option_parallels=0 when testing in Spyder.\n\n# Built-in libraries\nimport os\nimport argparse\nimport multiprocessing\nimport time\nimport inspect\nimport collections\n# External libraries\nimport pandas as pd\nimport numpy as np\nimport xarray as xr\nimport pickle\n# Local libraries\nimport pygem_input as input\nimport pygemfxns_modelsetup as modelsetup\nimport pygemfxns_massbalance as massbalance\nimport pygemfxns_gcmbiasadj as gcmbiasadj\nimport class_climate\nimport class_mbdata\n\n\n#%% FUNCTIONS\ndef getparser():\n    \"\"\"\n    Use argparse to add arguments from the command line\n    \n    Parameters\n    ----------\n    gcm_list_fn (optional) : str\n        text file that contains the climate data to be used in the model simulation\n    gcm_name (optional) : str\n        gcm name\n    num_simultaneous_processes (optional) : int\n        number of cores to use in parallels\n    option_parallels (optional) : int\n        switch to use parallels or not\n    spc_region (optional) : str\n        RGI region number for supercomputer \n    rgi_glac_number_fn (optional) : str\n        filename of .pkl file containing a list of glacier numbers that used to run batches on the supercomputer\n    batch_number (optional): int\n        batch number used to differentiate output on supercomputer\n    debug (optional) : int\n        Switch for turning debug printing on or off (default = 0 (off))\n      \n        \n    Returns\n    -------\n    Object containing arguments and their respective values.\n    \"\"\"\n    parser = argparse.ArgumentParser(description=\"run simulations from gcm list in parallel\")\n    # add arguments\n    parser.add_argument('-gcm_list_fn', action='store', type=str, default=input.ref_gcm_name,\n                        help='text file full of commands to run')\n    parser.add_argument('-gcm_name', action='store', type=str, default=None,\n                        help='GCM name used for model run')\n    parser.add_argument('-rcp', action='store', type=str, default=None,\n                        help='rcp scenario used for model run (ex. rcp26)')\n    parser.add_argument('-num_simultaneous_processes', action='store', type=int, default=4,\n                        help='number of simultaneous processes (cores) to use')\n    parser.add_argument('-option_parallels', action='store', type=int, default=1,\n                        help='Switch to use or not use parallels (1 - use parallels, 0 - do not)')\n    parser.add_argument('-spc_region', action='store', type=int, default=None,\n                        help='rgi region number for supercomputer')\n    parser.add_argument('-rgi_glac_number_fn', action='store', type=str, default=None,\n                        help='Filename containing list of rgi_glac_number, helpful for running batches on spc')\n    parser.add_argument('-batch_number', action='store', type=int, default=None,\n                        help='Batch number used to differentiate output on supercomputer')\n    parser.add_argument('-debug', action='store', type=int, default=0,\n                        help='Boolean for debugging to turn it on or off (default 0 is off')\n    return parser\n\n\ndef calc_stats(vn, ds, stats_cns=input.sim_stat_cns, glac=0):\n    \"\"\"\n    Calculate stats for a given variable\n    \n    Parameters\n    ----------\n    vn : str\n        variable name\n    ds : xarray dataset\n        dataset of output with all ensemble simulations\n    \n    Returns\n    -------\n    stats : np.array\n        Statistics related to a given variable\n    \"\"\"\n    data = ds[vn].values[glac,:,:]\n    if 'mean' in stats_cns:\n        stats = data.mean(axis=1)[:,np.newaxis]\n    if 'std' in stats_cns:\n        stats = np.append(stats, data.std(axis=1)[:,np.newaxis], axis=1)\n    if '2.5%' in stats_cns:\n        stats = np.append(stats, np.percentile(data, 2.5, axis=1)[:,np.newaxis], axis=1)\n    if '25%' in stats_cns:\n        stats = np.append(stats, np.percentile(data, 25, axis=1)[:,np.newaxis], axis=1)\n    if 'median' in stats_cns:\n        stats = np.append(stats, np.median(data, axis=1)[:,np.newaxis], axis=1)\n    if '75%' in stats_cns:\n        stats = np.append(stats, np.percentile(data, 75, axis=1)[:,np.newaxis], axis=1)\n    if '97.5%' in stats_cns:\n        stats = np.append(stats, np.percentile(data, 97.5, axis=1)[:,np.newaxis], axis=1)\n    return stats\n\n\ndef create_xrdataset(main_glac_rgi, dates_table, sim_iters=input.sim_iters, stat_cns=input.sim_stat_cns, \n                     record_stats=0, option_wateryear=input.gcm_wateryear):\n    \"\"\"\n    Create empty xarray dataset that will be used to record simulation runs.\n    \n    Parameters\n    ----------\n    main_glac_rgi : pandas dataframe\n        dataframe containing relevant rgi glacier information\n    dates_table : pandas dataframe\n        table of the dates, months, days in month, etc.\n    sim_iters : int\n        number of simulation runs included\n    stat_cns : list\n        list of strings containing statistics that will be used on simulations\n    record_stats : int\n        Switch to change from recording simulations to statistics\n        \n    Returns\n    -------\n    output_ds_all : xarray Dataset\n        empty xarray dataset that contains variables and attributes to be filled in by simulation runs\n    encoding : dictionary\n        encoding used with exporting xarray dataset to netcdf\n    \"\"\"    \n    if input.output_package == 2:\n        # Create empty datasets for each variable and merge them\n        # Coordinate values\n        output_variables = input.output_variables_package2\n        glac_values = main_glac_rgi.index.values\n        annual_columns = np.unique(dates_table['wateryear'].values)[0:int(dates_table.shape[0]/12)]\n        time_values = dates_table.loc[input.spinupyears*12:dates_table.shape[0]+1,'date'].tolist()\n        year_values = annual_columns[input.spinupyears:annual_columns.shape[0]]\n        year_plus1_values = np.concatenate((annual_columns[input.spinupyears:annual_columns.shape[0]], \n                                            np.array([annual_columns[annual_columns.shape[0]-1]+1])))\n        # Year type for attributes\n        if option_wateryear == 1:\n            year_type = 'water year'\n        elif option_wateryear == 2:\n            year_type = 'calendar year'\n        else:\n            year_type = 'custom year'\n            \n        # Switch to record simulations or statistics\n        if record_stats == 0:\n            record_name = 'sim'\n            record_name_values = np.arange(0,sim_iters)\n        elif record_stats == 1:\n            record_name = 'stats'\n            record_name_values = input.sim_stat_cns\n        \n        # Variable coordinates dictionary\n        output_coords_dict = {\n                'prec_glac_monthly': collections.OrderedDict(\n                        [('glac', glac_values), ('time', time_values), (record_name, record_name_values)]),\n                'temp_glac_monthly': collections.OrderedDict(\n                        [('glac', glac_values), ('time', time_values), (record_name, record_name_values)]),\n                'acc_glac_monthly': collections.OrderedDict(\n                        [('glac', glac_values), ('time', time_values), (record_name, record_name_values)]),\n                'refreeze_glac_monthly': collections.OrderedDict(\n                        [('glac', glac_values), ('time', time_values), (record_name, record_name_values)]),\n                'melt_glac_monthly': collections.OrderedDict(\n                        [('glac', glac_values), ('time', time_values), (record_name, record_name_values)]),\n                'frontalablation_glac_monthly': collections.OrderedDict(\n                        [('glac', glac_values), ('time', time_values), (record_name, record_name_values)]), \n                'massbaltotal_glac_monthly': collections.OrderedDict(\n                        [('glac', glac_values), ('time', time_values), (record_name, record_name_values)]),\n                'runoff_glac_monthly': collections.OrderedDict(\n                        [('glac', glac_values), ('time', time_values), (record_name, record_name_values)]), \n                'snowline_glac_monthly': collections.OrderedDict(\n                        [('glac', glac_values), ('time', time_values), (record_name, record_name_values)]),\n                'area_glac_annual': collections.OrderedDict(\n                        [('glac', glac_values), ('year_plus1', year_plus1_values), (record_name, record_name_values)]),\n                'volume_glac_annual': collections.OrderedDict(\n                        [('glac', glac_values), ('year_plus1', year_plus1_values), (record_name, record_name_values)]),\n                'ELA_glac_annual': collections.OrderedDict(\n                        [('glac', glac_values), ('year', year_values), (record_name, record_name_values)]),       \n                }\n        # Attributes dictionary\n        output_attrs_dict = {\n                'time': {\n                        'long_name': 'date',\n                         'year_type':year_type},\n                'glac': {\n                        'long_name': 'glacier index',\n                         'comment': 'glacier index value that refers to the glacier table'},\n                'year': {\n                        'long_name': 'years',\n                         'year_type': year_type,\n                         'comment': 'years referring to the start of each year'},\n                'year_plus1': {\n                        'long_name': 'years plus one additional year',\n                        'year_type': year_type,\n                        'comment': ('additional year allows one to record glacier dimension changes at end of '\n                                    'model run')},   \n                'sim': {\n                        'long_name': 'simulation number',\n                        'comment': 'simulation numbers only needed for MCMC methods'},\n                'stats': {\n                        'long_name': 'variable statistics',\n                        'comment': '% refers to percentiles'},\n                'temp_glac_monthly': {\n                        'long_name': 'glacier-wide mean air temperature',\n                        'units': 'degC',\n                        'temporal_resolution': 'monthly',\n                        'comment': (\n                                'each elevation bin is weighted equally to compute the mean temperature, and '\n                                'bins where the glacier no longer exists due to retreat have been removed')},\n                'prec_glac_monthly': {\n                        'long_name': 'glacier-wide precipitation (liquid)',\n                        'units': 'm',\n                        'temporal_resolution': 'monthly',\n                        'comment': 'only the liquid precipitation, solid precipitation excluded'},\n                'acc_glac_monthly': {\n                        'long_name': 'glacier-wide accumulation',\n                        'units': 'm w.e.',\n                        'temporal_resolution': 'monthly',\n                        'comment': 'only the solid precipitation'},\n                'refreeze_glac_monthly': {\n                        'long_name': 'glacier-wide refreeze',\n                        'units': 'm w.e.',\n                        'temporal_resolution': 'monthly'},\n                'melt_glac_monthly': {\n                        'long_name': 'glacier-wide melt',\n                        'units': 'm w.e.',\n                        'temporal_resolution': 'monthly'},\n                'frontalablation_glac_monthly': {\n                        'long_name': 'glacier-wide frontal ablation',\n                        'units': 'm w.e.',\n                        'temporal_resolution': 'monthly',\n                        'comment': (\n                                'mass losses from calving, subaerial frontal melting, sublimation above the '\n                                'waterline and subaqueous frontal melting below the waterline')},\n                'massbaltotal_glac_monthly': {\n                        'long_name': 'glacier-wide total mass balance',\n                        'units': 'm w.e.',\n                        'temporal_resolution': 'monthly',\n                        'comment': (\n                                'total mass balance is the sum of the climatic mass balance and frontal '\n                                'ablation')},\n                'runoff_glac_monthly': {\n                        'long_name': 'glacier-wide runoff',\n                        'units': 'm**3',\n                        'temporal_resolution': 'monthly',\n                        'comment': 'runoff from the glacier terminus, which moves over time'},\n                'snowline_glac_monthly': {\n                        'long_name': 'transient snowline',\n                        'units': 'm a.s.l.',\n                        'temporal_resolution': 'monthly',\n                        'comment': 'transient snowline is altitude separating snow from ice/firn'},\n                'area_glac_annual': {\n                        'long_name': 'glacier area',\n                        'units': 'km**2',\n                        'temporal_resolution': 'annual',\n                        'comment': 'area used for the duration of the defined start/end of year'},\n                'volume_glac_annual': {\n                        'long_name': 'glacier volume',\n                        'units': 'km**3 ice',\n                        'temporal_resolution': 'annual',\n                        'comment': 'volume based on area and ice thickness used for that year'}, \n                'ELA_glac_annual': {\n                        'long_name': 'annual equilibrium line altitude',\n                        'units': 'm a.s.l.',\n                        'temporal_resolution': 'annual',\n                        'comment': (\n                                'equilibrium line altitude is the elevation where the climatic mass balance is '\n                                'zero')}, \n                }\n                \n        # Add variables to empty dataset and merge together\n        count_vn = 0\n        encoding = {}\n        noencoding_vn = ['stats', 'glac_attrs']\n        for vn in output_variables:\n            count_vn += 1\n            empty_holder = np.zeros([len(output_coords_dict[vn][i]) for i in list(output_coords_dict[vn].keys())])\n            output_ds = xr.Dataset({vn: (list(output_coords_dict[vn].keys()), empty_holder)},\n                                   coords=output_coords_dict[vn])\n            # Merge datasets of stats into one output\n            if count_vn == 1:\n                output_ds_all = output_ds\n            else:\n                output_ds_all = xr.merge((output_ds_all, output_ds))\n        # Add a glacier table so that the glaciers attributes accompany the netcdf file\n        main_glac_rgi_float = main_glac_rgi[input.output_glacier_attr_vns].copy()\n        main_glac_rgi_xr = xr.Dataset({'glacier_table': (('glac', 'glac_attrs'), main_glac_rgi_float.values)},\n                                       coords={'glac': glac_values,\n                                               'glac_attrs': main_glac_rgi_float.columns.values})\n        output_ds_all = output_ds_all.combine_first(main_glac_rgi_xr)\n        output_ds_all.glacier_table.attrs['long_name'] = 'RGI glacier table'\n        output_ds_all.glacier_table.attrs['comment'] = 'table contains attributes from RGI for each glacier'\n        output_ds_all.glac_attrs.attrs['long_name'] = 'RGI glacier attributes'\n        # Add attributes\n        for vn in output_ds_all.variables:\n            try:\n                output_ds_all[vn].attrs = output_attrs_dict[vn]\n            except:\n                pass\n            # Encoding (specify _FillValue, offsets, etc.)\n            if vn not in noencoding_vn:\n                encoding[vn] = {'_FillValue': False}\n    return output_ds_all, encoding\n\n\ndef convert_glacwide_results(elev_bins, glac_bin_temp, glac_bin_prec, glac_bin_acc, glac_bin_refreeze, \n                             glac_bin_snowpack, glac_bin_melt, glac_bin_frontalablation, glac_bin_massbalclim_annual, \n                             glac_bin_area_annual, glac_bin_icethickness_annual):\n    \"\"\"\n    Convert raw runmassbalance function output to glacier-wide results for output package 2\n    \n    Parameters\n    ----------\n    elev_bins : numpy array\n        elevation of each elevation bin\n    glac_bin_temp : numpy array\n        temperature for each elevation bin for each timestep\n    glac_bin_prec : numpy array\n        precipitation (liquid) for each elevation bin for each timestep\n    glac_bin_acc : numpy array\n        accumulation (solid precipitation) for each elevation bin for each timestep\n    glac_bin_refreeze : numpy array\n        refreeze for each elevation bin for each timestep\n    glac_bin_snowpack : numpy array\n        snowpack for each elevation bin for each timestep\n    glac_bin_melt : numpy array\n        glacier melt for each elevation bin for each timestep\n    glac_bin_frontalablation : numpy array\n        frontal ablation for each elevation bin for each timestep\n    glac_bin_massbalclim_annual : numpy array\n        annual climatic mass balance for each elevation bin for each timestep   \n    glac_bin_area_annual : numpy array\n        annual glacier area for each elevation bin for each timestep\n    glac_bin_icethickness_annual: numpy array\n        annual ice thickness for each elevation bin for each timestep\n     \n    Returns\n    -------\n    glac_wide_temp : np.array\n        monthly mean glacier-wide temperature (bins weighted equally)\n    glac_wide_prec : np.array\n        monthly glacier-wide precipitation (liquid only)\n    glac_wide_acc : np.array\n        monthly glacier-wide accumulation (solid precipitation only)\n    glac_wide_refreeze : np.array\n        monthly glacier-wide refreeze\n    glac_wide_melt : np.array\n        monthly glacier-wide melt\n    glac_wide_frontalablation : np.array\n        monthly glacier-wide frontal ablation\n    glac_wide_massbaltotal : np.array\n        monthly glacier-wide total mass balance (climatic mass balance + frontal ablation)\n    glac_wide_runoff: np.array\n        monthly glacier-wide runoff at the terminus of the glacier\n    glac_wide_snowline : np.array\n        monthly glacier-wide snowline\n    glac_wide_area_annual : np.array\n        annual glacier area\n    glac_wide_volume_annual : np.array\n        annual glacier volume\n    glac_wide_ELA_annual : np.array\n        annual equilibrium line altitude\n    \"\"\"\n    # Preset desired output (needed to avoid dividing by zero)\n    glac_wide_temp = np.zeros(glac_bin_temp.shape[1])\n    glac_wide_prec = np.zeros(glac_bin_temp.shape[1])\n    glac_wide_acc = np.zeros(glac_bin_temp.shape[1])\n    glac_wide_refreeze = np.zeros(glac_bin_temp.shape[1])\n    glac_wide_melt = np.zeros(glac_bin_temp.shape[1])\n    glac_wide_frontalablation = np.zeros(glac_bin_temp.shape[1])\n    # Compute desired output\n    glac_bin_area = glac_bin_area_annual[:,0:glac_bin_area_annual.shape[1]-1].repeat(12,axis=1)\n    glac_wide_area = glac_bin_area.sum(axis=0)\n    glac_wide_temp_sum = glac_bin_temp.sum(axis=0)\n    glac_bin_temp_nonzero = np.zeros(glac_bin_temp.shape)\n    glac_bin_temp_nonzero[glac_bin_temp != 0] = 1\n    glac_wide_temp_bincount = glac_bin_temp_nonzero.sum(axis=0)\n    glac_wide_temp[glac_wide_temp_bincount > 0] = (glac_wide_temp_sum[glac_wide_temp_bincount > 0] / \n                                                   glac_wide_temp_bincount[glac_wide_temp_bincount > 0])\n    glac_wide_prec_mkm2 = (glac_bin_prec * glac_bin_area).sum(axis=0)\n    glac_wide_prec[glac_wide_prec_mkm2 > 0] = (glac_wide_prec_mkm2[glac_wide_prec_mkm2 > 0] / \n                                               glac_wide_area[glac_wide_prec_mkm2 > 0])\n    glac_wide_acc_mkm2 = (glac_bin_acc * glac_bin_area).sum(axis=0)\n    glac_wide_acc[glac_wide_acc_mkm2 > 0] = (glac_wide_acc_mkm2[glac_wide_acc_mkm2 > 0] / \n                                             glac_wide_area[glac_wide_acc_mkm2 > 0])\n    glac_wide_refreeze_mkm2 = (glac_bin_refreeze * glac_bin_area).sum(axis=0)\n    glac_wide_refreeze[glac_wide_refreeze_mkm2 > 0] = (glac_wide_refreeze_mkm2[glac_wide_refreeze_mkm2 > 0] / \n                                                       glac_wide_area[glac_wide_refreeze_mkm2 > 0])\n    glac_wide_melt_mkm2 = (glac_bin_melt * glac_bin_area).sum(axis=0)\n    glac_wide_melt[glac_wide_melt_mkm2 > 0] = (glac_wide_melt_mkm2[glac_wide_melt_mkm2 > 0] / \n                                               glac_wide_area[glac_wide_melt_mkm2 > 0])\n    glac_wide_frontalablation_mkm2 = (glac_bin_frontalablation * glac_bin_area).sum(axis=0)\n    glac_wide_frontalablation[glac_wide_frontalablation_mkm2 > 0] = (\n            glac_wide_frontalablation_mkm2[glac_wide_frontalablation_mkm2 > 0] / \n            glac_wide_area[glac_wide_frontalablation_mkm2 > 0])\n    glac_wide_massbalclim = glac_wide_acc + glac_wide_refreeze - glac_wide_melt\n    glac_wide_massbaltotal = glac_wide_massbalclim - glac_wide_frontalablation\n    glac_wide_runoff = (glac_wide_prec + glac_wide_melt - glac_wide_refreeze) * glac_wide_area * (1000)**2\n    #  units: (m + m w.e. - m w.e.) * km**2 * (1000 m / 1 km)**2 = m**3\n    glac_wide_snowline = (glac_bin_snowpack > 0).argmax(axis=0)\n    glac_wide_snowline[glac_wide_snowline > 0] = (elev_bins[glac_wide_snowline[glac_wide_snowline > 0]] - \n                                                  input.binsize/2)\n    glac_wide_area_annual = glac_bin_area_annual.sum(axis=0)\n    glac_wide_volume_annual = (glac_bin_area_annual * glac_bin_icethickness_annual / 1000).sum(axis=0)\n    glac_wide_ELA_annual = (glac_bin_massbalclim_annual > 0).argmax(axis=0)\n    glac_wide_ELA_annual[glac_wide_ELA_annual > 0] = (elev_bins[glac_wide_ELA_annual[glac_wide_ELA_annual > 0]] - \n                                                      input.binsize/2)    \n    return (glac_wide_temp, glac_wide_prec, glac_wide_acc, glac_wide_refreeze, glac_wide_melt, \n            glac_wide_frontalablation, glac_wide_massbaltotal, glac_wide_runoff, glac_wide_snowline, \n            glac_wide_area_annual, glac_wide_volume_annual, glac_wide_ELA_annual)\n\n\ndef main(list_packed_vars):\n    \"\"\"\n    Model simulation\n    \n    Parameters\n    ----------\n    list_packed_vars : list\n        list of packed variables that enable the use of parallels\n        \n    Returns\n    -------\n    netcdf files of the simulation output (specific output is dependent on the output option)\n    \"\"\"\n    # Unpack variables\n    count = list_packed_vars[0]\n    chunk = list_packed_vars[1]\n    main_glac_rgi_all = list_packed_vars[2]\n    chunk_size = list_packed_vars[3]\n    gcm_name = list_packed_vars[4]\n\n    parser = getparser()\n    args = parser.parse_args()\n        \n    if (gcm_name != input.ref_gcm_name) and (args.rcp is None):\n        rcp_scenario = os.path.basename(args.gcm_list_fn).split('_')[1]\n    elif args.rcp is not None:\n        rcp_scenario = args.rcp\n        \n    # RGI region\n    if args.spc_region is not None:\n        rgi_regionsO1 = [int(args.spc_region)]\n    else:\n        rgi_regionsO1 = input.rgi_regionsO1\n    \n    if debug:\n        if 'rcp_scenario' in locals():\n            print(rcp_scenario)\n\n    # ===== LOAD GLACIER DATA =====\n    main_glac_rgi = main_glac_rgi_all.iloc[chunk:chunk + chunk_size, :].copy()\n    # Glacier hypsometry [km**2], total area\n    main_glac_hyps = modelsetup.import_Husstable(main_glac_rgi, rgi_regionsO1, input.hyps_filepath,\n                                                 input.hyps_filedict, input.hyps_colsdrop)\n    # Ice thickness [m], average\n    main_glac_icethickness = modelsetup.import_Husstable(main_glac_rgi, rgi_regionsO1, input.thickness_filepath,\n                                                         input.thickness_filedict, input.thickness_colsdrop)\n    main_glac_hyps[main_glac_icethickness == 0] = 0\n    # Width [km], average\n    main_glac_width = modelsetup.import_Husstable(main_glac_rgi, rgi_regionsO1, input.width_filepath,\n                                                  input.width_filedict, input.width_colsdrop)\n    elev_bins = main_glac_hyps.columns.values.astype(int)\n    # Volume [km**3] and mean elevation [m a.s.l.]\n    main_glac_rgi['Volume'], main_glac_rgi['Zmean'] = modelsetup.hypsometrystats(main_glac_hyps, main_glac_icethickness)\n    \n    # Select dates including future projections\n    dates_table = modelsetup.datesmodelrun(startyear=input.gcm_startyear, endyear=input.gcm_endyear, \n                                           spinupyears=input.gcm_spinupyears, option_wateryear=input.gcm_wateryear)\n    \n    \n    # =================\n    if debug:\n        # Select dates including future projections\n        #  - nospinup dates_table needed to get the proper time indices\n        dates_table_nospinup  = modelsetup.datesmodelrun(startyear=input.gcm_startyear, endyear=input.gcm_endyear, \n                                                         spinupyears=0, option_wateryear=input.gcm_wateryear)\n    \n        # ===== LOAD CALIBRATION DATA =====\n        cal_data = pd.DataFrame()\n        for dataset in input.cal_datasets:\n            cal_subset = class_mbdata.MBData(name=dataset, rgi_regionO1=rgi_regionsO1[0])\n            cal_subset_data = cal_subset.retrieve_mb(main_glac_rgi, main_glac_hyps, dates_table_nospinup)\n            cal_data = cal_data.append(cal_subset_data, ignore_index=True)\n        cal_data = cal_data.sort_values(['glacno', 't1_idx'])\n        cal_data.reset_index(drop=True, inplace=True)\n    \n    # =================\n    \n    \n    \n    \n    # Synthetic simulation dates\n    if input.option_synthetic_sim == 1:\n        dates_table_synthetic = modelsetup.datesmodelrun(\n                startyear=input.synthetic_startyear, endyear=input.synthetic_endyear, spinupyears=0)\n        \n    # ===== LOAD CLIMATE DATA =====\n    if gcm_name == 'ERA-Interim' or gcm_name == 'COAWST':\n        gcm = class_climate.GCM(name=gcm_name)\n        # Check that end year is reasonable\n        if (input.gcm_endyear > int(time.strftime(\"%Y\"))) and (input.option_synthetic_sim == 0):\n            print('\\n\\nEND YEAR BEYOND AVAILABLE DATA FOR ERA-INTERIM. CHANGE END YEAR.\\n\\n')\n    else:\n        gcm = class_climate.GCM(name=gcm_name, rcp_scenario=rcp_scenario)\n    \n    if input.option_synthetic_sim == 0:        \n        # Air temperature [degC]\n        gcm_temp, gcm_dates = gcm.importGCMvarnearestneighbor_xarray(gcm.temp_fn, gcm.temp_vn, main_glac_rgi, \n                                                                     dates_table)\n        # Precipitation [m]\n        gcm_prec, gcm_dates = gcm.importGCMvarnearestneighbor_xarray(gcm.prec_fn, gcm.prec_vn, main_glac_rgi, \n                                                                     dates_table)\n        # Elevation [m asl]\n        gcm_elev = gcm.importGCMfxnearestneighbor_xarray(gcm.elev_fn, gcm.elev_vn, main_glac_rgi)          \n        # Lapse rate\n        if gcm_name == 'ERA-Interim':\n            gcm_lr, gcm_dates = gcm.importGCMvarnearestneighbor_xarray(gcm.lr_fn, gcm.lr_vn, main_glac_rgi, dates_table)\n        else:\n            # Compute lapse rates based on reference climate data\n            # Adjust reference dates in event that reference is longer than GCM data\n            if input.startyear >= input.gcm_startyear:\n                ref_startyear = input.startyear\n            else:\n                ref_startyear = input.gcm_startyear\n            if input.endyear <= input.gcm_endyear:\n                ref_endyear = input.endyear\n            else:\n                ref_endyear = input.gcm_endyear\n            dates_table_ref = modelsetup.datesmodelrun(startyear=ref_startyear, endyear=ref_endyear, \n                                                       spinupyears=input.spinupyears, \n                                                       option_wateryear=input.option_wateryear)\n            # Monthly average from reference climate data\n            ref_gcm = class_climate.GCM(name=input.ref_gcm_name)\n            ref_lr, ref_dates = ref_gcm.importGCMvarnearestneighbor_xarray(ref_gcm.lr_fn, ref_gcm.lr_vn, main_glac_rgi, \n                                                                           dates_table_ref)\n            ref_lr_monthly_avg = gcmbiasadj.monthly_avg_2darray(ref_lr)\n            gcm_lr = np.tile(ref_lr_monthly_avg, int(gcm_temp.shape[1]/12))\n               \n        # COAWST data has two domains, so need to merge the two domains\n        if gcm_name == 'COAWST':\n            gcm_temp_d01, gcm_dates = gcm.importGCMvarnearestneighbor_xarray(gcm.temp_fn_d01, gcm.temp_vn,\n                                                                             main_glac_rgi, dates_table)\n            gcm_prec_d01, gcm_dates = gcm.importGCMvarnearestneighbor_xarray(gcm.prec_fn_d01, gcm.prec_vn, \n                                                                             main_glac_rgi, dates_table)\n            gcm_elev_d01 = gcm.importGCMfxnearestneighbor_xarray(gcm.elev_fn_d01, gcm.elev_vn, main_glac_rgi)\n            # Check if glacier outside of high-res (d02) domain\n            for glac in range(main_glac_rgi.shape[0]):\n                glac_lat = main_glac_rgi.loc[glac,input.rgi_lat_colname]\n                glac_lon = main_glac_rgi.loc[glac,input.rgi_lon_colname]\n                if (~(input.coawst_d02_lat_min <= glac_lat <= input.coawst_d02_lat_max) or \n                    ~(input.coawst_d02_lon_min <= glac_lon <= input.coawst_d02_lon_max)):\n                    gcm_prec[glac,:] = gcm_prec_d01[glac,:]\n                    gcm_temp[glac,:] = gcm_temp_d01[glac,:]\n                    gcm_elev[glac] = gcm_elev_d01[glac]\n  \n    # ===== SYNTHETIC SIMULATION =====\n    elif input.option_synthetic_sim == 1:\n        # Air temperature [degC]\n        gcm_temp_tile, gcm_dates = gcm.importGCMvarnearestneighbor_xarray(gcm.temp_fn, gcm.temp_vn, main_glac_rgi, \n                                                                          dates_table_synthetic)\n        # Precipitation [m]\n        gcm_prec_tile, gcm_dates = gcm.importGCMvarnearestneighbor_xarray(gcm.prec_fn, gcm.prec_vn, main_glac_rgi, \n                                                                          dates_table_synthetic)\n        # Elevation [m asl]\n        gcm_elev = gcm.importGCMfxnearestneighbor_xarray(gcm.elev_fn, gcm.elev_vn, main_glac_rgi)  \n        # Lapse rate\n        gcm_lr_tile, gcm_dates = gcm.importGCMvarnearestneighbor_xarray(gcm.lr_fn, gcm.lr_vn, main_glac_rgi, \n                                                                        dates_table_synthetic)\n        # Future simulation based on synthetic (replicated) data; add spinup years; dataset restarts after spinupyears \n        datelength = dates_table.shape[0] - input.gcm_spinupyears * 12\n        n_tiles = int(np.ceil(datelength / dates_table_synthetic.shape[0]))\n        gcm_temp = np.append(gcm_temp_tile[:,:input.gcm_spinupyears*12], \n                             np.tile(gcm_temp_tile,(1,n_tiles))[:,:datelength], axis=1)\n        gcm_prec = np.append(gcm_prec_tile[:,:input.gcm_spinupyears*12], \n                             np.tile(gcm_prec_tile,(1,n_tiles))[:,:datelength], axis=1)\n        gcm_lr = np.append(gcm_lr_tile[:,:input.gcm_spinupyears*12], np.tile(gcm_lr_tile,(1,n_tiles))[:,:datelength], \n                           axis=1)\n        # Temperature and precipitation sensitivity adjustments\n        gcm_temp = gcm_temp + input.synthetic_temp_adjust\n        gcm_prec = gcm_prec * input.synthetic_prec_factor\n       \n    # ===== BIAS CORRECTIONS =====\n    # No adjustments\n    if input.option_bias_adjustment == 0 or gcm_name == input.ref_gcm_name:\n        gcm_temp_adj = gcm_temp\n        gcm_prec_adj = gcm_prec\n        gcm_elev_adj = gcm_elev\n    # Bias correct based on reference climate data\n    else:\n        # Air temperature [degC], Precipitation [m], Elevation [masl], Lapse rate [K m-1]\n        ref_temp, ref_dates = ref_gcm.importGCMvarnearestneighbor_xarray(ref_gcm.temp_fn, ref_gcm.temp_vn, \n                                                                         main_glac_rgi, dates_table_ref)\n        ref_prec, ref_dates = ref_gcm.importGCMvarnearestneighbor_xarray(ref_gcm.prec_fn, ref_gcm.prec_vn, \n                                                                         main_glac_rgi, dates_table_ref)\n        ref_elev = ref_gcm.importGCMfxnearestneighbor_xarray(ref_gcm.elev_fn, ref_gcm.elev_vn, main_glac_rgi)\n        \n        # OPTION 1: Adjust temp using Huss and Hock (2015), prec similar but addresses for variance and outliers\n        if input.option_bias_adjustment == 1:\n            # Temperature bias correction\n            gcm_temp_adj, gcm_elev_adj = gcmbiasadj.temp_biasadj_HH2015(ref_temp, ref_elev, gcm_temp, \n                                                                        dates_table_ref, dates_table)\n            # Precipitation bias correction\n            gcm_prec_adj, gcm_elev_adj = gcmbiasadj.prec_biasadj_opt1(ref_prec, ref_elev, gcm_prec, \n                                                                      dates_table_ref, dates_table)\n        \n        # OPTION 2: Adjust temp and prec using Huss and Hock (2015)\n        elif input.option_bias_adjustment == 2:\n            # Temperature bias correction\n            gcm_temp_adj, gcm_elev_adj = gcmbiasadj.temp_biasadj_HH2015(ref_temp, ref_elev, gcm_temp, \n                                                                        dates_table_ref, dates_table)\n            # Precipitation bias correction\n            gcm_prec_adj, gcm_elev_adj = gcmbiasadj.prec_biasadj_HH2015(ref_prec, ref_elev, gcm_prec, \n                                                                        dates_table_ref, dates_table)\n \n    # Checks on precipitation data\n    if gcm_prec_adj.max() > 10:\n        print('precipitation bias too high, needs to be modified')\n        print(np.where(gcm_prec_adj > 10))\n    elif gcm_prec_adj.min() < 0:\n        print('Negative precipitation value')\n        print(np.where(gcm_prec_adj < 0))\n    \n#%%\n    # ===== RUN MASS BALANCE =====\n    # Dataset to store model simulations and statistics\n    # Number of simulations\n    if input.option_calibration == 1:\n            sim_iters = 1\n    elif input.option_calibration == 2:\n        sim_iters = input.sim_iters\n    # Create datasets\n    output_ds_all, encoding = create_xrdataset(main_glac_rgi, dates_table, sim_iters=sim_iters, \n                                               option_wateryear=input.gcm_wateryear)\n    output_ds_all_stats, encoding = create_xrdataset(main_glac_rgi, dates_table, record_stats=1, \n                                                     option_wateryear=input.gcm_wateryear)\n    \n    for glac in range(main_glac_rgi.shape[0]):\n        if glac == 0 or glac == main_glac_rgi.shape[0]:\n            print(gcm_name,':', main_glac_rgi.loc[main_glac_rgi.index.values[glac],'RGIId'])\n        # Select subsets of data\n        glacier_rgi_table = main_glac_rgi.loc[main_glac_rgi.index.values[glac], :]\n        glacier_gcm_elev = gcm_elev_adj[glac]\n        glacier_gcm_prec = gcm_prec_adj[glac,:]\n        glacier_gcm_temp = gcm_temp_adj[glac,:]\n        glacier_gcm_lrgcm = gcm_lr[glac,:]\n        glacier_gcm_lrglac = glacier_gcm_lrgcm.copy()\n        glacier_area_t0 = main_glac_hyps.iloc[glac,:].values.astype(float)\n        icethickness_t0 = main_glac_icethickness.iloc[glac,:].values.astype(float)\n        width_t0 = main_glac_width.iloc[glac,:].values.astype(float)\n\n        # get glacier number\n        if rgi_regionsO1[0] >= 10:\n            glacier_RGIId = main_glac_rgi.iloc[glac]['RGIId'][6:]\n        else:\n            glacier_RGIId = main_glac_rgi.iloc[glac]['RGIId'][7:]\n        \n        if debug:\n            print(glacier_RGIId)\n            \n        if input.option_import_modelparams == 1:\n            if input.option_calibration == 1:\n                ds_mp = xr.open_dataset(input.modelparams_fp_dict[rgi_regionsO1[0]] + glacier_RGIId + '.nc')\n                cn_subset = input.modelparams_colnames\n                modelparameters_all = (pd.DataFrame(ds_mp.mp_value.sel(chain=0).values, \n                                                    columns=ds_mp.mp.values)[cn_subset])\n            elif input.option_calibration == 2:\n                ds_mp = xr.open_dataset(input.modelparams_fp_dict[rgi_regionsO1[0]] + glacier_RGIId + '.nc')\n                cn_subset = input.modelparams_colnames\n                modelparameters_all = (pd.DataFrame(ds_mp['mp_value'].sel(chain=0).values, \n                                                    columns=ds_mp.mp.values)[cn_subset])\n        else:\n            modelparameters_all = (\n                    pd.DataFrame(np.asarray([input.lrgcm, input.lrglac, input.precfactor, input.precgrad, input.ddfsnow, \n                                             input.ddfice, input.tempsnow, input.tempchange]).reshape(1,-1), \n                                             columns=input.modelparams_colnames))\n        \n        # Set the number of iterations and determine every kth iteration to use for the ensemble\n        if (input.option_calibration == 1) or (modelparameters_all.shape[0] == 1):\n            sim_iters = 1\n        elif input.option_calibration == 2:\n            sim_iters = input.sim_iters\n            # Select every kth iteration\n            mp_spacing = int((modelparameters_all.shape[0] - input.sim_burn) / sim_iters)\n            mp_idx_start = np.arange(input.sim_burn, input.sim_burn + mp_spacing)\n            np.random.shuffle(mp_idx_start)\n            mp_idx_start = mp_idx_start[0]\n            mp_idx_all = np.arange(mp_idx_start, modelparameters_all.shape[0], mp_spacing)\n            \n        # Loop through model parameters\n        for n_iter in range(sim_iters):\n\n            if sim_iters == 1:\n                modelparameters = modelparameters_all.mean()  \n            else:\n                mp_idx = mp_idx_all[n_iter]\n                modelparameters = modelparameters_all.iloc[mp_idx,:]\n                \n            if debug:\n                print(glacier_RGIId, ':', [modelparameters[2], modelparameters[4], modelparameters[7]])\n                debug_mb = True\n            else:\n                debug_mb = False\n                \n                        \n            # run mass balance calculation\n            (glac_bin_temp, glac_bin_prec, glac_bin_acc, glac_bin_refreeze, glac_bin_snowpack, glac_bin_melt,\n             glac_bin_frontalablation, glac_bin_massbalclim, glac_bin_massbalclim_annual, glac_bin_area_annual,\n             glac_bin_icethickness_annual, glac_bin_width_annual, glac_bin_surfacetype_annual,\n             glac_wide_massbaltotal, glac_wide_runoff, glac_wide_snowline, glac_wide_snowpack,\n             glac_wide_area_annual, glac_wide_volume_annual, glac_wide_ELA_annual) = (\n                massbalance.runmassbalance(modelparameters[0:8], glacier_rgi_table, glacier_area_t0, icethickness_t0,\n                                           width_t0, elev_bins, glacier_gcm_temp, glacier_gcm_prec, \n                                           glacier_gcm_elev, glacier_gcm_lrgcm, glacier_gcm_lrglac, dates_table, \n                                           option_areaconstant=0, debug=debug_mb))\n            \n    #        # Compute glacier volume change for every time step and use this to compute mass balance\n    #        #  this will work for any indexing\n    #        glac_wide_area = glac_wide_area_annual[:-1].repeat(12)\n    #        # Mass change [km3 mwe]\n    #        #  mb [mwea] * (1 km / 1000 m) * area [km2]\n    #        glac_wide_masschange = glac_wide_massbaltotal / 1000 * glac_wide_area\n    #        # Mean annual mass balance [mwea]\n    #        mb_mwea = (glac_wide_masschange.sum() / glac_wide_area[0] * 1000 / \n    #                   (glac_wide_masschange.shape[0] / 12))\n            \n#            if debug:\n#                print('mb_model [mwe]:', glac_wide_massbaltotal_annual.sum())\n#                print('mb_model [mwea]:', mb_mwea.round(6))\n\n#            # RECORD PARAMETERS TO DATASET\n#            if input.output_package == 2:\n#                (glac_wide_temp, glac_wide_prec, glac_wide_acc, glac_wide_refreeze, glac_wide_melt, \n#                 glac_wide_frontalablation, glac_wide_massbaltotal, glac_wide_runoff, glac_wide_snowline, \n#                 glac_wide_area_annual, glac_wide_volume_annual, glac_wide_ELA_annual) = (\n#                         convert_glacwide_results(elev_bins, glac_bin_temp, glac_bin_prec, glac_bin_acc, \n#                                                  glac_bin_refreeze, glac_bin_snowpack, glac_bin_melt, \n#                                                  glac_bin_frontalablation, glac_bin_massbalclim_annual, \n#                                                  glac_bin_area_annual, glac_bin_icethickness_annual))\n#                # Record output to xarray dataset\n#                output_ds_all.temp_glac_monthly[glac, :, n_iter] = glac_wide_temp\n#                output_ds_all.prec_glac_monthly[glac, :, n_iter] = glac_wide_prec\n#                output_ds_all.acc_glac_monthly[glac, :, n_iter] = glac_wide_acc\n#                output_ds_all.refreeze_glac_monthly[glac, :, n_iter] = glac_wide_refreeze\n#                output_ds_all.melt_glac_monthly[glac, :, n_iter] = glac_wide_melt\n#                output_ds_all.frontalablation_glac_monthly[glac, :, n_iter] = glac_wide_frontalablation\n#                output_ds_all.massbaltotal_glac_monthly[glac, :, n_iter] = glac_wide_massbaltotal\n#                output_ds_all.runoff_glac_monthly[glac, :, n_iter] = glac_wide_runoff\n#                output_ds_all.snowline_glac_monthly[glac, :, n_iter] = glac_wide_snowline\n#                output_ds_all.area_glac_annual[glac, :, n_iter] = glac_wide_area_annual\n#                output_ds_all.volume_glac_annual[glac, :, n_iter] = glac_wide_volume_annual\n#                output_ds_all.ELA_glac_annual[glac, :, n_iter] = glac_wide_ELA_annual\n#                \n#        # Calculate statistics of simulations\n#        # List of variables\n#        ds_vns = []\n#        for vn in output_ds_all.variables:\n#            ds_vns.append(vn)\n#        for vn in ds_vns:\n#            if vn in input.output_variables_package2:\n#                stats = calc_stats(vn, output_ds_all, glac=glac)\n#                output_ds_all_stats[vn].values[glac,:,:] = stats\n#                \n#        if debug:\n##            # Mean annual glacier-wide mass balance\n##            # Compute glacier volume change for every time step and use this to compute mass balance\n##            #  this will work for any indexing\n##            glac_wide_area = glac_wide_area_annual[:-1].repeat(12)\n##            # Volume change [km3]\n##            #  mb [mwea] * input.density_water / input.density_ice * (1 km / 1000 m) * area [km2]\n##            glac_wide_volchange = (glac_wide_massbaltotal * input.density_water / input.density_ice / \n##                                   1000 * glac_wide_area)\n##            mb_mwea = (glac_wide_volchange.sum() / glac_wide_area[0] * 1000 * input.density_ice / \n##                       input.density_water / (glac_wide_volchange.shape[0] / 12))\n#            \n#            print('mb_mwea_all IS CALCULATED POORLY - NEEDS TO BE UPDATED TO ACCOUNT FOR AREA CHANGES (see above)')\n#            \n#            mb_mwea_all = ((output_ds_all_stats.massbaltotal_glac_monthly.values[glac,:,0]).sum(axis=0) / \n#                            (dates_table.shape[0] / 12))\n#            print('mb_model [mwea] mean:', round(mb_mwea_all,4))   \n#            # Calibration\n#            cal_idx = np.where(cal_data.glacno == main_glac_rgi.glacno)[0][0]\n#            mb_cal_mwea = cal_data.loc[cal_idx, 'mb_mwe'] / (cal_data.loc[cal_idx, 't2'] - cal_data.loc[cal_idx, 't1'])\n#            print('mb_cal [mwea]:', round(mb_cal_mwea,4))\n#                \n#    # Export statistics to netcdf\n#    if input.output_package == 2:\n#        output_sim_fp = input.output_sim_fp + gcm_name + '/'\n#        # Create filepath if it does not exist\n#        if os.path.exists(output_sim_fp) == False:\n#            os.makedirs(output_sim_fp)\n#        # Netcdf filename\n#        if (gcm_name == 'ERA-Interim') or (gcm_name == 'COAWST'):\n#            # Filename\n#            netcdf_fn = ('R' + str(rgi_regionsO1[0]) + '_' + gcm_name + '_c' + \n#                         str(input.option_calibration) + '_ba' + str(input.option_bias_adjustment) + '_' +  \n#                         str(sim_iters) + 'sets' + '_' + str(input.gcm_startyear) + '_' + str(input.gcm_endyear) + \n#                         '--' + str(count) + '.nc')\n#        else:\n#            netcdf_fn = ('R' + str(rgi_regionsO1[0]) + '_' + gcm_name + '_' + rcp_scenario + '_c' + \n#                         str(input.option_calibration) + '_ba' + str(input.option_bias_adjustment) + '_' +  \n#                         str(sim_iters) + 'sets' + '_' + str(input.gcm_startyear) + '_' + str(input.gcm_endyear) + \n#                         '--' + str(count) + '.nc')\n#        if input.option_synthetic_sim==1:\n#            netcdf_fn = (netcdf_fn.split('--')[0] + '_T' + str(input.synthetic_temp_adjust) + '_P' + \n#                         str(input.synthetic_prec_factor) + '--' + netcdf_fn.split('--')[1])\n#        if args.batch_number is not None:\n#            netcdf_fn_split = netcdf_fn.split('--')  \n#            netcdf_fn = netcdf_fn_split[0] + '_batch' + str(args.batch_number) + '--' + netcdf_fn_split[1]\n#        # Export netcdf\n#        output_ds_all_stats.to_netcdf(output_sim_fp + netcdf_fn, encoding=encoding)\n\n\n    #%% Export variables as global to view in variable explorer\n    if args.option_parallels == 0:\n        global main_vars\n        main_vars = inspect.currentframe().f_locals\n\n#%% PARALLEL PROCESSING\nif __name__ == '__main__':\n    time_start = time.time()\n    parser = getparser()\n    args = parser.parse_args()\n    \n    if args.debug == 1:\n        debug = True\n    else:\n        debug = False\n\n    # RGI region number\n    if args.spc_region is not None:\n        rgi_regionsO1 = [int(args.spc_region)]\n    else:\n        rgi_regionsO1 = input.rgi_regionsO1\n\n    # RGI glacier number\n    if args.rgi_glac_number_fn is not None:\n        with open(args.rgi_glac_number_fn, 'rb') as f:\n            rgi_glac_number = pickle.load(f)\n    else:\n        rgi_glac_number = input.rgi_glac_number\n\n    # Select all glaciers in a region\n    main_glac_rgi_all = modelsetup.selectglaciersrgitable(rgi_regionsO1=rgi_regionsO1, rgi_regionsO2 = 'all',\n                                                          rgi_glac_number=rgi_glac_number)\n    # Processing needed for netcdf files\n    main_glac_rgi_all_float = main_glac_rgi_all.copy()\n    main_glac_rgi_all_float.drop(labels=['RGIId'], axis=1, inplace=True)\n    main_glac_hyps = modelsetup.import_Husstable(main_glac_rgi_all, rgi_regionsO1, input.hyps_filepath,\n                                                 input.hyps_filedict, input.hyps_colsdrop)\n    dates_table = modelsetup.datesmodelrun(startyear=input.gcm_startyear, endyear=input.gcm_endyear, \n                                           spinupyears=input.gcm_spinupyears)\n    \n    # Define chunk size for parallel processing\n    if args.option_parallels != 0:\n        num_cores = int(np.min([main_glac_rgi_all.shape[0], args.num_simultaneous_processes]))\n        chunk_size = int(np.ceil(main_glac_rgi_all.shape[0] / num_cores))\n    else:\n        # if not running in parallel, chunk size is all glaciers\n        chunk_size = main_glac_rgi_all.shape[0]\n        \n    # Read GCM names from argument parser\n    gcm_name = args.gcm_list_fn\n    if args.gcm_name is not None:\n        gcm_list = [args.gcm_name]\n        rcp_scenario = args.rcp\n    elif args.gcm_list_fn == input.ref_gcm_name:\n        gcm_list = [input.ref_gcm_name]\n    else:\n        with open(args.gcm_list_fn, 'r') as gcm_fn:\n            gcm_list = gcm_fn.read().splitlines()\n            rcp_scenario = os.path.basename(args.gcm_list_fn).split('_')[1]\n            print('Found %d gcms to process'%(len(gcm_list)))\n\n    # Loop through all GCMs\n    for gcm_name in gcm_list:\n        if args.rcp is None:\n            print('Processing:', gcm_name)\n        else:\n            print('Processing:', gcm_name, rcp_scenario)\n        # Pack variables for multiprocessing\n        list_packed_vars = []\n        n = 0\n        for chunk in range(0, main_glac_rgi_all.shape[0], chunk_size):\n            n = n + 1\n            list_packed_vars.append([n, chunk, main_glac_rgi_all, chunk_size, gcm_name])\n\n        # Parallel processing\n        if args.option_parallels != 0:\n            print('Processing in parallel with ' + str(num_cores) + ' cores...')\n            with multiprocessing.Pool(args.num_simultaneous_processes) as p:\n                p.map(main,list_packed_vars)\n        # If not in parallel, then only should be one loop\n        else:\n            # Loop through the chunks and export bias adjustments\n            for n in range(len(list_packed_vars)):\n                main(list_packed_vars[n])\n                \n        #%%\n        print('\\nADD MERGE BACK IN\\n')\n#        # Merge netcdf files together into one\n#        # Filenames to merge\n#        output_list_sorted = []\n#        output_sim_fp = input.output_sim_fp + gcm_name + '/'\n#        if input.option_calibration == 1:\n#            sim_iters = 1\n#        elif input.option_calibration == 2:\n#            sim_iters = input.sim_iters\n#        if (gcm_name == 'ERA-Interim') or (gcm_name == 'COAWST'):\n#            check_str = ('R' + str(rgi_regionsO1[0]) + '_' + gcm_name + '_c' + \n#                         str(input.option_calibration) + '_ba' + str(input.option_bias_adjustment) + '_' +  \n#                         str(sim_iters) + 'sets' + '_' + str(input.gcm_startyear) + '_' + str(input.gcm_endyear) \n#                         + '--')\n#        else:\n#            check_str = ('R' + str(rgi_regionsO1[0]) + '_' + gcm_name + '_' + rcp_scenario + '_c' + \n#                         str(input.option_calibration) + '_ba' + str(input.option_bias_adjustment) + '_' +  \n#                         str(sim_iters) + 'sets' + '_' + str(input.gcm_startyear) + '_' + str(input.gcm_endyear) \n#                         + '--')\n#        if input.option_synthetic_sim==1:\n#            check_str = (check_str.split('--')[0] + '_T' + str(input.synthetic_temp_adjust) + '_P' + \n#                         str(input.synthetic_prec_factor) + '--')\n#        if args.batch_number is not None:\n#            check_str = check_str.split('--')[0] + '_batch' + str(args.batch_number) + '--'\n#        for i in os.listdir(output_sim_fp):\n#            if i.startswith(check_str):\n#                output_list_sorted.append([int(i.split('--')[1].split('.')[0]), i])\n#        output_list_sorted = sorted(output_list_sorted)\n#        output_list = [i[1] for i in output_list_sorted]\n#        # Open datasets and combine\n#        count_ds = 0\n#        for i in output_list:\n#            count_ds += 1\n#            ds = xr.open_dataset(output_sim_fp + i)\n#            # Merge datasets of stats into one output\n#            if count_ds == 1:\n#                ds_all = ds\n#            else:\n#                ds_all = xr.merge((ds_all, ds))\n#        # Filename\n#        ds_all_fn = i.split('--')[0] + '.nc'\n#        # Encoding\n#        # Add variables to empty dataset and merge together\n#        encoding = {}\n#        noencoding_vn = ['stats', 'glac_attrs']\n#        if input.output_package == 2:\n#            for vn in input.output_variables_package2:\n#                # Encoding (specify _FillValue, offsets, etc.)\n#                if vn not in noencoding_vn:\n#                    encoding[vn] = {'_FillValue': False}\n#        # Export to netcdf\n#        if input.output_package == 2:\n#            ds_all.to_netcdf(output_sim_fp + ds_all_fn, encoding=encoding)\n#        else:\n#            ds_all.to_netcdf(output_sim_fp + ds_all_fn)\n#        # Remove files in output_list\n#        for i in output_list:\n#            os.remove(output_sim_fp + i)\n\n    print('Total processing time:', time.time()-time_start, 's')\n\n#%% ===== PLOTTING AND PROCESSING FOR MODEL DEVELOPMENT =====\n    # Place local variables in variable explorer\n    if args.option_parallels == 0:\n        main_vars_list = list(main_vars.keys())\n        gcm_name = main_vars['gcm_name']\n#        rcp_scenario = main_vars['rcp_scenario']\n        main_glac_rgi = main_vars['main_glac_rgi']\n        main_glac_hyps = main_vars['main_glac_hyps']\n        main_glac_icethickness = main_vars['main_glac_icethickness']\n        main_glac_width = main_vars['main_glac_width']\n        dates_table = main_vars['dates_table']\n        if input.option_synthetic_sim == 1:\n            dates_table_synthetic = main_vars['dates_table_synthetic']\n            gcm_temp_tile = main_vars['gcm_temp_tile']\n            gcm_prec_tile = main_vars['gcm_prec_tile']\n            gcm_lr_tile = main_vars['gcm_lr_tile']\n        gcm_temp = main_vars['gcm_temp']\n        gcm_prec = main_vars['gcm_prec']\n        gcm_elev = main_vars['gcm_elev']\n        gcm_lr = main_vars['gcm_lr']\n        gcm_temp_adj = main_vars['gcm_temp_adj']\n        gcm_prec_adj = main_vars['gcm_prec_adj']\n        gcm_elev_adj = main_vars['gcm_elev_adj']\n#        if input.option_bias_adjustment != 0:\n#            main_glac_biasadj = main_vars['main_glac_biasadj']\n        gcm_temp_lrglac = main_vars['gcm_lr']\n        output_ds_all = main_vars['output_ds_all']\n        modelparameters = main_vars['modelparameters']\n        glacier_rgi_table = main_vars['glacier_rgi_table']\n        glacier_gcm_temp = main_vars['glacier_gcm_temp']\n        glacier_gcm_prec = main_vars['glacier_gcm_prec']\n        glacier_gcm_elev = main_vars['glacier_gcm_elev']\n        glacier_gcm_lrgcm = main_vars['glacier_gcm_lrgcm']\n        glacier_gcm_lrglac = glacier_gcm_lrgcm\n        glacier_area_t0 = main_vars['glacier_area_t0']\n        icethickness_t0 = main_vars['icethickness_t0']\n        width_t0 = main_vars['width_t0']\n        elev_bins = main_vars['elev_bins']\n        glac_bin_frontalablation = main_vars['glac_bin_frontalablation']\n        glac_bin_area_annual = main_vars['glac_bin_area_annual']\n        glac_bin_massbalclim_annual = main_vars['glac_bin_massbalclim_annual']\n        glac_bin_melt = main_vars['glac_bin_melt']\n        glac_bin_acc = main_vars['glac_bin_acc']\n        glac_bin_refreeze = main_vars['glac_bin_refreeze']\n        glac_bin_temp = main_vars['glac_bin_temp']\n        glac_bin_prec = main_vars['glac_bin_prec']\n        \n        glac_wide_massbaltotal = main_vars['glac_wide_massbaltotal']\n        glac_wide_area_annual = main_vars['glac_wide_area_annual']\n        glac_wide_volume_annual = main_vars['glac_wide_volume_annual']\n        modelparameters_all = main_vars['modelparameters_all']\n        sim_iters = main_vars['sim_iters']\n        cal_data = main_vars['cal_data']\n#        if input.option_calibration == 2:\n#            mp_idx = main_vars['mp_idx']\n#            mp_idx_all = main_vars['mp_idx_all']\n#        netcdf_fn = main_vars['netcdf_fn']\n        \n#%%\n##    # If you run 100 simulations, see that mass change is slightly different depending on if it's computed using the \n##    # monthly mass balance and area or with the volume.  This is likely due to using the mean for both the area and the \n##    # mass balance as this problem doesn't exist when running a single simulation.\n#    ds = xr.open_dataset(input.output_sim_fp + gcm_name + '/' + 'R15_ERA-Interim_c2_ba2_100sets_2000_2017.nc')\n#    vol_annual = ds.volume_glac_annual.values[0,:,0]\n#    mb_monthly = ds.massbaltotal_glac_monthly.values[0,:,0]\n#    area_annual = ds.area_glac_annual.values[0,:,0]\n#    \n#    # Monthly glacier area\n#    area_monthly = np.repeat(area_annual[:-1],12)\n#    # Monthly glacier mass change\n#    #  Area [km2] * mb [mwe] * (1 km / 1000 m) * density_water [kg/m3] * (1 Gt/km3  /  1000 kg/m3)\n#    masschange_monthly = area_monthly * mb_monthly / 1000 * input.density_water / 1000\n#    masschange_annual = np.zeros((int(masschange_monthly.shape[0]/12)))\n#    # Annual glacier mass change\n#    for nyear in range(int(masschange_monthly.shape[0]/12)):\n#        masschange_annual[nyear] = np.sum(masschange_monthly[12*nyear:12*nyear+12])\n#        \n#    mass_annual = vol_annual * input.density_ice / 1000\n#    masschange_annual_check = mass_annual[1:] - mass_annual[:-1]\n#    A = masschange_annual_check - masschange_annual\n#    B = A / vol_annual[:-1] * 100\n", "meta": {"hexsha": "34a385bb0c26e9657825b68969184e2cf326a8ff", "size": 56667, "ext": "py", "lang": "Python", "max_stars_repo_path": "run_simulation.py", "max_stars_repo_name": "tusharkh/PyGEM-Clone", "max_stars_repo_head_hexsha": "057d276871d398a3e5dcc8cd59226933a98b3be1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "run_simulation.py", "max_issues_repo_name": "tusharkh/PyGEM-Clone", "max_issues_repo_head_hexsha": "057d276871d398a3e5dcc8cd59226933a98b3be1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "run_simulation.py", "max_forks_repo_name": "tusharkh/PyGEM-Clone", "max_forks_repo_head_hexsha": "057d276871d398a3e5dcc8cd59226933a98b3be1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.6619318182, "max_line_length": 122, "alphanum_fraction": 0.6049905589, "include": true, "reason": "import numpy", "num_tokens": 13871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.17695644628998497}}
{"text": "from abc import ABC\nfrom abc import abstractmethod\n\nimport astropy.table\nimport numpy as np\nimport scipy.spatial\n\n\nclass MetricsParams(ABC):\n    def __init__(self, meas_generator, batch_size):\n        \"\"\"Class describing functions to return results of\n        detection/deblending/measurement algorithm in meas_generator. Each\n        blend results yielded by the meas_generator for a batch.\n        \"\"\"\n        self.meas_generator = meas_generator\n        self.batch_size = batch_size\n\n    @abstractmethod\n    def get_detections(self):\n        \"\"\"\n        Returns detection results as two catalogs one with entries of true\n        objects in blend and the other with the detection.\n\n        Overwrite this function to return results from the detection algorithm.\n\n        Returns:\n            list:  List of astropy tables with the blend catalogs used to draw\n                the blend scene in the batch. Length of tables must be equal to\n                the batch size. x and y coordinate values must be under columns\n                named 'dx' and 'dy' respectively, in pixels from bottom left\n                corner as (0, 0).\n            list: List of astropy Tables of output with the outputs of the\n            detection algorithm. Length of tables must be equal to the batch\n            size. x and y coordinate values must be under columns named 'dx'\n            and 'dy' respectively, in pixels from bottom left corner as (0, 0).\n        \"\"\"\n        pass\n\n    def get_segmentation(self):\n        \"\"\"Define function here to return results from the segmentation\n        algorithm.\n        \"\"\"\n        pass\n\n    def get_flux(self):\n        \"\"\"Define function here to return results from the flux measurement\n        algorithm.\n        \"\"\"\n        pass\n\n    def get_shapes(self):\n        \"\"\"Define function here to return results from the shape measurement\n        algorithm.\n        \"\"\"\n        pass\n\n\nclass BasicMetricsParams(MetricsParams):\n    \"\"\"Class describing functions to return results of\n    detection/deblending/measurement algorithm in meas_generator. Each\n    time the algorithm is called, it is run on a batch of blends yielded\n    by the meas_generator.\n    \"\"\"\n\n    def get_detections(self):\n        \"\"\"Returns input blend catalog and detection catalog for\n        the detection performed.\n\n        Returns:\n            Results of the detection algorithm are returned as:\n                true_tables: List of astropy Table of the blend catalogs of the\n                    batch. Length of tables must be the batch size. x and y\n                    coordinate values must be under columns named 'dx' and 'dy'\n                    respectively, in pixels from bottom left corner as (0, 0).\n                detected_tables: List of astropy Table of output from detection\n                    algorithm. Length of tables must be the batch size. x and y\n                    coordinate values must be under columns named 'dx' and 'dy'\n                    respectively, in pixels from bottom left corner as (0, 0).\n        \"\"\"\n        blend_op, deblend_op, _ = next(self.meas_generator)\n        true_tables = blend_op[\"blend_list\"]\n        detected_tables = []\n        for i in range(len(true_tables)):\n            detected_centers = deblend_op[i][\"peaks\"]\n            detected_table = astropy.table.Table(detected_centers, names=[\"dx\", \"dy\"])\n            detected_tables.append(detected_table)\n        return true_tables, detected_tables\n\n\ndef make_true_seg_map(image, threshold):\n    \"\"\"Returns a boolean segmentation map corresponding to pixels in\n    image above a certain threshold value.\n    Args:\n        image: Image to estimate segmentation map of\n        threshold: Pixels above this threshold are marked as belonging to\n            segmentation map\n\n    Returns:\n        Boolean segmentation map of the image\n    \"\"\"\n    seg_map = np.zeros_like(image)\n    seg_map[image < threshold] = 0\n    seg_map[image >= threshold] = 1\n    return seg_map.astype(np.bool)\n\n\ndef get_closest_neighbor_distance(true_table):\n    \"\"\"Returns a astropy.table.column with the distance to the closest object.\n\n    Function uses scipy.spatial to compute distance between the object centers.\n    If object is the only one in the blend then the `min_dist` value is set to\n    np.inf.\n\n    Args:\n        true_table: Catalog with entries corresponding to one blend.\n\n    Returns:\n        `astropy.table.Column`s: size of the galaxy.\n    \"\"\"\n    peaks = np.stack([np.array(true_table[\"dx\"]), np.array(true_table[\"dy\"])]).T\n    if peaks.shape[0] > 1:\n        distance = scipy.spatial.distance.cdist(peaks, peaks, metric=\"euclidean\")\n        min_dist = [np.min(distance[i][distance[i] > 0]) for i in range(len(distance))]\n        true_table[\"min_dist\"] = min_dist\n\n\ndef get_m_z_diff(true_table, detected_true):\n    \"\"\"Updates the input astropy.table.column with the difference in magnitude,\n    and redshift between an object and it's algorithm matches. It also computes\n    the true distance between an object and its closest detection.\n\n    Args:\n        detected_true:\n        true_table: Catalog with entries corresponding to one blend.\n    \"\"\"\n    if len(detected_true) == 0 or len(true_table) == 0:\n        # No match since either no true or no matched true objects\n        return\n    det_centers = np.stack([np.array(detected_true[\"dx\"]), np.array(detected_true[\"dy\"])]).T\n    z_tree = scipy.spatial.KDTree(det_centers)\n    true_centers = np.stack([np.array(true_table[\"dx\"]), np.array(true_table[\"dy\"])]).T\n    match = detected_true[z_tree.query(true_centers)[1]]\n    true_table[\"dm_match\"] = true_table[\"i_ab\"] - match[\"i_ab\"]\n    true_table[\"dz_match\"] = true_table[\"redshift\"] - match[\"redshift\"]\n    dx = true_table[\"dx\"] - match[\"dx\"]\n    dy = true_table[\"dy\"] - match[\"dy\"]\n    true_table[\"ddist_match\"] = np.hypot(dx, dy)\n\n\ndef initialize_detection_tables(detected_table, true_table, batch_index, batch_size, blend_index):\n    \"\"\"Initialize column entries of true objects and detection catalog to their\n    default values.\n\n    This is necessary since, if either true objects or detection table is\n    empty, then there is no match in get_detection_match and those column\n    entries would not otherwise be present in the tables.\n\n    Function does not return anything, only the astropy tables are updates.\n    \"\"\"\n    # initialize true objects table columns\n    num_true = len(true_table)\n    true_table[\"true_id\"] = range(num_true)  # id in blend [0-num_true]\n    # index of blend in test size [0 - len(blend_summary)]\n    true_table[\"blend_index\"] = np.ones(num_true, dtype=int) * (\n        batch_index * batch_size + blend_index\n    )\n    # index of batch in test size [0 - batch_size]\n    true_table[\"batch_index\"] = np.ones(num_true, dtype=int) * batch_index\n    # number of times object was detected [0 - num_det]\n    true_table[\"num_detections1\"] = np.zeros(num_true, dtype=int)\n    true_table[\"num_detections2\"] = np.zeros(num_true, dtype=int)\n    # detection id of closest detection with 2 algorithms [0 - num_det]\n    true_table[\"closest_det_id1\"] = np.ones(num_true, dtype=int) * -1.0\n    true_table[\"closest_det_id2\"] = np.ones(num_true, dtype=int) * -1.0\n    # difference in centroids, i band magnitude and redshift between an object\n    # and its match with algorithm 2\n    true_table[\"dm_match\"] = np.zeros(num_true, dtype=int)\n    true_table[\"dz_match\"] = np.zeros(num_true, dtype=int)\n    true_table[\"ddist_match\"] = np.zeros(num_true, dtype=int)\n    true_table[\"dnorm_dist_match\"] = np.zeros(num_true, dtype=int)\n    # find distance to nearest neighbor. If isolated then set to np.inf\n    true_table[\"min_dist\"] = np.ones(num_true) * np.inf\n    get_closest_neighbor_distance(true_table)\n    # initialize detected objects table columns\n    num_det = len(detected_table)\n    detected_table[\"detection_id\"] = range(num_det)  # id in blend [0-num_det]\n    # index of blend in test size [0 - len(blend_summary)]\n    detected_table[\"blend_index\"] = np.ones(num_det, dtype=int) * (\n        batch_index * batch_size + blend_index\n    )\n    # index of batch in test size [0 - batch_size]\n    detected_table[\"batch_index\"] = np.ones(num_det, dtype=int) * batch_index\n    # id of closest true object; [0 - num_true] if detected, else -1\n    detected_table[\"match_true_id1\"] = np.ones(num_det, dtype=int) * -1\n    detected_table[\"match_true_id2\"] = np.ones(num_det, dtype=int) * -1\n    detected_table[\"match_galtileid1\"] = np.ones(num_det, dtype=int) * -1\n    detected_table[\"match_galtileid2\"] = np.ones(num_det, dtype=int) * -1\n\n\ndef get_detection_match(true_table, detected_table):\n    \"\"\"Match detections to true objects and update values in the input\n    blend catalog and detection catalog.\n\n    Function does not return anything, only the astropy tables are updated.\n\n    Args:\n        true_table (astropy.table.Table): Table with entries corresponding to\n            the true object parameter values in one blend.\n        detected_table(astropy.table.Table): Table with entries corresponding\n            to output of measurement algorithm in one blend.\n    \"\"\"\n    if len(detected_table) == 0 or len(true_table) == 0:\n        # No match since either no detection or no true objects\n        return\n    t_x = true_table[\"dx\"][:, np.newaxis] - detected_table[\"dx\"]\n    t_y = true_table[\"dy\"][:, np.newaxis] - detected_table[\"dy\"]\n    dist = np.hypot(t_x, t_y)\n    norm_size = true_table[\"size\"]\n    norm_dist = dist / norm_size[:, np.newaxis]\n    detected_table[\"dSigma_min\"] = np.min(norm_dist, axis=0)\n    detected_table[\"d_min\"] = np.min(dist, axis=0)\n    detection_threshold1 = 5\n    condlist1 = [\n        np.min(dist, axis=0) <= detection_threshold1,\n        np.min(dist, axis=0) > detection_threshold1,\n    ]\n    choicelist1 = [np.argmin(dist, axis=0), -1]\n    match_id1 = np.select(condlist1, choicelist1)\n    detected_table[\"match_true_id1\"] = match_id1\n    detected_table[\"match_galtileid1\"] = true_table[\"galtileid\"][match_id1]\n    detection_threshold2 = 0.5\n    condlist2 = [\n        np.min(norm_dist, axis=0) <= detection_threshold2,\n        np.min(norm_dist, axis=0) > detection_threshold2,\n    ]\n    choicelist2 = [np.argmin(norm_dist, axis=0), -1]\n    match_id2 = np.select(condlist2, choicelist2)\n    detected_table[\"match_true_id2\"] = match_id2\n    detected_table[\"match_galtileid2\"] = true_table[\"galtileid\"][match_id2]\n    np.testing.assert_array_equal(\n        np.argmin(dist, axis=1),\n        np.argmin(norm_dist, axis=1),\n        err_msg=\"norm_dist computation is wrong.\",\n    )\n    true_table[\"closest_det_id1\"] = np.argmin(norm_dist, axis=1)\n    for j in detected_table[\"match_true_id1\"]:\n        if j > -1:\n            true_table[\"num_detections1\"][j] += 1\n    true_table[\"closest_det_id2\"] = np.argmin(dist, axis=1)\n    for j in detected_table[\"match_true_id2\"]:\n        if j > -1:\n            true_table[\"num_detections2\"][j] += 1\n    get_m_z_diff(true_table, true_table[match_id1[match_id1 >= 0]])\n\n\ndef get_blend_detection_summary(true_table, det_table):\n    \"\"\"Returns list summarizing results of detection metric computation\n\n    Args:\n        true_table (astropy.table.Table): Table with entries corresponding to\n            the true object parameter values in one blend.\n        det_table(astropy.table.Table): Table with entries corresponding\n            to output of measurement algorithm in one blend.\n\n    Returns:\n        List of detection metrics summary:\n            num_true: number of true objects.\n            num_detected: Number of correct detections by algorithm.\n            num_undetected: Number of true objects not detected by algorithm.\n            num_spurious: Number of spurious detections.\n            num_shred: Number of true objects shredded by algorithm.\n\n    \"\"\"\n    num_true = len(true_table)\n    num_det = len(det_table)\n    num_detected1 = len(np.where(true_table[\"num_detections1\"] == 1)[0])\n    num_undetected1 = len(np.where(true_table[\"num_detections1\"] == 0)[0])\n    num_spurious1 = len(np.where(det_table[\"match_true_id1\"] == -1)[0])\n    num_shred1 = len(np.where(true_table[\"num_detections1\"] > 1)[0])\n    num_detected2 = len(np.where(true_table[\"num_detections2\"] == 1)[0])\n    num_undetected2 = len(np.where(true_table[\"num_detections2\"] == 0)[0])\n    num_spurious2 = len(np.where(det_table[\"match_true_id2\"] == -1)[0])\n    num_shred2 = len(np.where(true_table[\"num_detections2\"] > 1)[0])\n    if not num_detected1 + num_undetected1 + num_shred1 == num_true:\n        raise ValueError(\n            \"Number of detected objects + number undetected \"\n            \"objects must be equal to the total number of true \"\n            \"objects\"\n        )\n\n    if not num_detected2 + num_undetected2 + num_shred2 == num_true:\n        raise ValueError(\n            \"Number of detected objects + number undetected \"\n            \"objects must be equal to the total number \"\n            \"of true objects.\"\n        )\n\n    num_matched_detections1 = true_table[\"num_detections1\"].sum()\n    if not num_matched_detections1 + num_spurious1 == num_det:\n        raise ValueError(\n            \"Number of detections match to a true object + \"\n            \"number of spurious must be equal to the \"\n            \"total number of detections.\"\n        )\n\n    num_matched_detections2 = true_table[\"num_detections2\"].sum()\n    if not num_matched_detections2 + num_spurious2 == num_det:\n        raise ValueError(\n            \"Number of detections match to a true object + \"\n            \"number of spurious must be equal to the total \"\n            \"number of detections.\"\n        )\n\n    blend_summary = [\n        num_true,\n        num_detected1,\n        num_undetected1,\n        num_spurious1,\n        num_shred1,\n        num_detected2,\n        num_undetected2,\n        num_spurious2,\n        num_shred2,\n    ]\n    return blend_summary\n\n\ndef get_detection_eff_matrix(summary_table, num):\n    \"\"\"Computes the detection efficiency matrix for the input detection summary\n    table.\n\n    Input argument num sets the maximum number of true objects per blend in the\n    test set for which the\n    detection efficiency matrix is to be created for. Detection efficiency is\n    computed for a number of true objects in the range (0-num) as columns and\n    the detection percentage as rows. The percentage values in a column sum to\n    100.\n\n    The input summary table must be a numpy array of shape [N, 5], where N is\n    the test set size. The 5 columns in the summary_table are number of true\n    objects, detected sources, undetected objects, spurious detections and\n    shredded objects for each of the N blend scenes in the test set.\n\n    Args:\n        summary_table (`numpy.array`): Detection summary as a table [N, 5].\n        num (int): Maximum number of true objects to create matrix for. Number\n            of columns in efficiency matrix will be num+1. The first column\n            will correspond to no true objects.\n\n    Returns:\n        numpy.ndarray of size[num+2, num+1] that shows detection efficiency.\n    \"\"\"\n    eff_matrix = np.zeros((num + 2, num + 1))\n    for i in range(0, num + 1):\n        (q_true,) = np.where(summary_table[:, 0] == i)\n        for j in range(0, num + 2):\n            if len(q_true) > 0:\n                (q_det,) = np.where(summary_table[q_true, 1] == j)\n                eff_matrix[j, i] = len(q_det)\n    norm = np.sum(eff_matrix, axis=0)\n    # If no detections along a column, set sum to 1 to avoid dividing by zero.\n    norm[norm == 0.0] = 1\n    # normalize over columns.\n    eff_matrix = eff_matrix / norm[np.newaxis, :] * 100.0\n    return eff_matrix\n\n\ndef evaluate_detection(true_tables, detected_tables, batch_index):\n    \"\"\"\n    Compares the true centers and detected centers to identify the\n    number of true detections, number of sources that were undetected\n    and number of spurious detections.\n    Args:\n        true_tables:  List of astropy Tables of the blend catalogs of the\n            batch. Length of tables must be the batch size. x and y coordinate\n            values must be under columns named 'dx' and 'dy' respectively, in\n            pixels from bottom left corner as (0, 0).\n        detected_tables: List of astropy Tables of output from detection\n            algorithm. Length of tables must be the batch size. x and y\n            coordinate values must be under columns named 'dx' and 'dy'\n            respectively, in pixels from bottom left corner as (0, 0).\n        batch_index(int): Index number of the batch.\n    Returns:\n        batch_true_table: astropy.table.Table with parameters of true galaxy in\n            the batch.\n        batch_detected_table: astropy.table.Table with parameters of detected\n            objects in the batch.\n        batch_blend_list: List summarizing detection match results.\n    \"\"\"\n    batch_true_table = astropy.table.Table()\n    batch_detected_table = astropy.table.Table()\n    batch_size = len(true_tables)\n    batch_blend_summary = []\n    for i in range(batch_size):\n        true_table = true_tables[i]\n        detected_table = detected_tables[i]\n        # initialize columns to default values\n        initialize_detection_tables(detected_table, true_table, batch_index, batch_size, i)\n        # match detection and true source\n        get_detection_match(true_table, detected_table)\n        # summarize blend detection results to table\n        blend_summary = get_blend_detection_summary(true_table, detected_table)\n        batch_blend_summary.append(blend_summary)\n        # add results to batch table\n        batch_detected_table = astropy.table.vstack((batch_detected_table, detected_table))\n        batch_true_table = astropy.table.vstack((batch_true_table, true_table))\n    return batch_true_table, batch_detected_table, batch_blend_summary\n\n\ndef evaluate_segmentation(segmentation, data=None, index=None):\n    if segmentation is None:\n        return None\n    return None\n\n\ndef evaluate_flux(flux, data=None, index=None):\n    if flux is None:\n        return None\n    return None\n\n\ndef evaluate_shapes(shapes, data=None, index=None):\n    if shapes is None:\n        return None\n    return None\n\n\ndef run(metrics_params, test_size=1000):\n    \"\"\"Runs detection/segmentation/flux/shape measurement algorithm defined in\n    the input metrics params for input test_size number of btk runs.\n\n    Args:\n        metrics_params: Instance from class\n        `btk.metrics.Metrics_params` describing functions to return\n        results of detection/deblending/measurement algorithm.\n        test_size(int): Number of times Metrics_params is run and results\n            summarized.\n\n    Returns:\n        dict summarizing detection/deblending/measurement results.\n\n    \"\"\"\n    results = {\n        \"detection\": [astropy.table.Table(), astropy.table.Table(), []],\n        \"segmentation\": [],\n        \"flux\": [],\n        \"shapes\": [],\n    }\n    for i in range(test_size):\n        print(f\"Running test {i}\")\n        # Evaluate detection algorithm\n        try:\n            batch_detection_result = metrics_params.get_detections()\n        except GeneratorExit as e:\n            print(e)\n            print(\"GeneratorExit encountered. Returning results\")\n            return results\n        if (\n            len(batch_detection_result[0]) != len(batch_detection_result[1])\n            or len(batch_detection_result[0]) != metrics_params.batch_size\n        ):\n            raise ValueError(\n                \"Metrics_params.get_detections output must be \"\n                \"two lists of astropy table of length batch size.\"\n                f\" Found {len(batch_detection_result[0])}, \"\n                f\"{len(batch_detection_result[1])}, \"\n                f\"{metrics_params.batch_size}\"\n            )\n        true_table, detected_table, detection_summary = evaluate_detection(\n            batch_detection_result[0], batch_detection_result[1], batch_index=i\n        )\n        results[\"detection\"][0] = astropy.table.vstack([results[\"detection\"][0], true_table])\n        results[\"detection\"][1] = astropy.table.vstack([results[\"detection\"][1], detected_table])\n        results[\"detection\"][2].extend(detection_summary)\n        # Evaluate segmentation algorithm\n        segmentation = metrics_params.get_segmentation()\n        results[\"segmentation\"].append(evaluate_segmentation(segmentation, index=i))\n        # Evaluate flux measurement algorithm\n        flux = metrics_params.get_flux()\n        results[\"flux\"].append(evaluate_flux(flux, index=i))\n        # Evaluate shape measurement algorithm\n        shapes = metrics_params.get_shapes()\n        results[\"shapes\"].append(evaluate_shapes(shapes, index=i))\n    return results\n", "meta": {"hexsha": "a18cac435843be6b4f9e5f8ecc7e60fe5cbc23c6", "size": 20564, "ext": "py", "lang": "Python", "max_stars_repo_path": "btk/metrics.py", "max_stars_repo_name": "mpaillassa/BlendingToolKit", "max_stars_repo_head_hexsha": "3dfb8bc36d6c7d944c8ef353f2c70623d882fcd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "btk/metrics.py", "max_issues_repo_name": "mpaillassa/BlendingToolKit", "max_issues_repo_head_hexsha": "3dfb8bc36d6c7d944c8ef353f2c70623d882fcd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "btk/metrics.py", "max_forks_repo_name": "mpaillassa/BlendingToolKit", "max_forks_repo_head_hexsha": "3dfb8bc36d6c7d944c8ef353f2c70623d882fcd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4, "max_line_length": 98, "alphanum_fraction": 0.6683038319, "include": true, "reason": "import numpy,import scipy,import astropy", "num_tokens": 4727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.17695644279919365}}
{"text": "from pathlib import Path\nimport shutil\nimport subprocess\nimport importlib.resources\nimport os\nfrom datetime import datetime\nimport typing as T\nimport xarray\nimport numpy as np\n\nfrom .timeutils import todatetime\nimport geomagindices as gi\n\nspecies = [\"He\", \"O\", \"N2\", \"O2\", \"Ar\", \"Total\", \"H\", \"N\", \"AnomalousO\"]\nttypes = [\"Texo\", \"Tn\"]\nfirst = True\n\n\ndef run(\n    time: datetime, altkm: float, glat: float, glon: float, indices: T.Dict[str, T.Any] = None\n) -> xarray.Dataset:\n    \"\"\"\n    This is the \"atomic\" function looped by other functions\n    \"\"\"\n    time = todatetime(time)\n    # %% get solar parameters for date\n    if not indices:\n        indices = gi.getApF107(time, smoothdays=81).squeeze()\n    # %% dimensions\n    altkm = np.atleast_1d(altkm)\n    if altkm.ndim != 1:\n        raise ValueError(\"altitude read incorrectly\")\n    if not isinstance(glon, (int, float, np.int32, np.int64)):\n        raise TypeError(\"single longitude only\")\n    if not isinstance(glat, (int, float, np.int32, np.int64)):\n        raise TypeError(\"single latitude only\")\n\n    # %%\n    iyd = time.strftime(\"%y%j\")\n    altkm = np.atleast_1d(altkm)\n    # %%\n    dens = np.empty((altkm.size, len(species)))\n    temp = np.empty((altkm.size, len(ttypes)))\n    # %% build on run\n    exe_name = \"msis2driver\"\n    if os.name == \"nt\":\n        exe_name += \".exe\"\n    if not importlib.resources.is_resource(__package__, exe_name):\n        with importlib.resources.path(__package__, \"CMakeLists.txt\") as setup_file:\n            cmake(setup_file.parent)\n    if not importlib.resources.is_resource(__package__, exe_name):\n        raise RuntimeError(\"could not build MSIS 2.0 Fortran driver\")\n\n    if not importlib.resources.is_resource(__package__, \"msis20.parm\"):\n        raise FileNotFoundError(\"could not find msis20.parm\")\n\n    with importlib.resources.path(__package__, exe_name) as exe:\n        for i, a in enumerate(altkm):\n            cmd = [\n                str(exe),\n                iyd,\n                str(time.hour),\n                str(time.minute),\n                str(time.second),\n                str(glat),\n                str(glon),\n                str(indices[\"f107s\"]),\n                str(indices[\"f107\"]),\n                str(indices[\"Ap\"]),\n                str(a),\n            ]\n\n            ret = subprocess.run(\n                cmd, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=exe.parent\n            )\n\n            if ret.returncode != 0:\n                raise RuntimeError(f\"MSIS 2.0 error code {ret.returncode}\\n{ret.stderr}\")\n            # different compilers throw in extra \\n\n            raw = list(map(float, ret.stdout.split()))\n            if not len(raw) == 9 + 2:\n                raise ValueError(ret)\n            dens[i, :] = raw[:9]\n            temp[i, :] = raw[9:]\n\n    dsf = {\n        k: ((\"time\", \"alt_km\", \"lat\", \"lon\"), v[None, :, None, None])\n        for (k, v) in zip(species, dens.T)\n    }\n    dsf.update(\n        {\n            \"Tn\": ((\"time\", \"alt_km\", \"lat\", \"lon\"), temp[:, 1][None, :, None, None]),\n            \"Texo\": ((\"time\", \"alt_km\", \"lat\", \"lon\"), temp[:, 0][None, :, None, None]),\n        }\n    )\n\n    atmos = xarray.Dataset(\n        dsf,\n        coords={\"time\": [time], \"alt_km\": altkm, \"lat\": [glat], \"lon\": [glon]},\n        attrs={\n            \"species\": species,\n            \"f107s\": indices[\"f107s\"],\n            \"f107\": indices[\"f107\"],\n            \"Ap\": indices[\"Ap\"],\n        },\n    )\n\n    return atmos\n\n\ndef cmake(src: Path):\n    \"\"\"\n    attempt to build using CMake\n    \"\"\"\n\n    exe = shutil.which(\"cmake\")\n    if not exe:\n        raise FileNotFoundError(\"CMake not available\")\n\n    build = src / \"build\"\n\n    subprocess.check_call([exe, f\"-S{src}\", f\"-B{build}\", \"-DBUILD_TESTING:BOOL=off\"])\n    subprocess.check_call([exe, \"--build\", str(build)])\n\n    exe_name = \"msis2driver\"\n    if os.name == \"nt\":\n        exe_name += \".exe\"\n    if not importlib.resources.is_resource(__package__, exe_name):\n        raise RuntimeError(\"could not build MSIS 2.0 Fortran driver\")\n", "meta": {"hexsha": "5f9bf23ef67061789fcc1f2c5429dda1a4c97d73", "size": 4022, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/msis2/__init__.py", "max_stars_repo_name": "space-physics/nrlmsis2.0", "max_stars_repo_head_hexsha": "2d71c4e11046319349a5cb1031631595d30d1015", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-01-18T04:12:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T22:17:31.000Z", "max_issues_repo_path": "src/msis2/__init__.py", "max_issues_repo_name": "space-physics/nrlmsis2.0", "max_issues_repo_head_hexsha": "2d71c4e11046319349a5cb1031631595d30d1015", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-23T22:59:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T22:59:45.000Z", "max_forks_repo_path": "src/msis2/__init__.py", "max_forks_repo_name": "space-physics/nrlmsis2.0", "max_forks_repo_head_hexsha": "2d71c4e11046319349a5cb1031631595d30d1015", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-21T11:01:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-18T21:19:05.000Z", "avg_line_length": 30.9384615385, "max_line_length": 94, "alphanum_fraction": 0.5599204376, "include": true, "reason": "import numpy", "num_tokens": 1045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.17695643930840238}}
{"text": "\"\"\"\nNAME\n    optool\n\nDESCRIPTION\n\n    This module provides an interface to the optool program (available\n    at https://github.com/cdominik/optool), and tools to plot and\n    convert the results.\n    It also provides tools to prepare refractive index data for use\n    with the tool.\n\"\"\"\nimport copy\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math as m\nimport re\nimport os\nimport subprocess\nfrom distutils.spawn import find_executable\nimport random\n\nclass particle:\n    \"\"\"Run optool and turn output into a python object.\n\n        Provides an interface to the optool program for computing dust\n        opacities. The optool program can be found on GitHub, at this address:\n        https://github.com/cdominik/optool .\n\n        Attributes\n        ----------\n\n        cmd : str\n             The full command given in the particle() call\n        radmc : boolean\n             Output follows RADMC conventions\n        scat : boolean\n             Scattering matrix is available\n        nlam : int\n             Number of wavelength points\n        lam : float[nlam]\n             The wavelength grid\n        nang : int\n             Number of scattering angles\n        scatang : float[nang]\n             The angular grid\n        materials : [[[...]...]... ]\n             Lists with [location,m_{frac},\\rho,material\n        np : int\n             Number of particles, either 1 or (with -d) n_a\n        fmax : float[np]\n             Maximum volume fraction of vacuum for DHS\n        pcore, pmantle : float[np]\n             Porosity of the core/mantle material\n        amin : float[np]\n             min grain size used for each particle\n        amax : float[np]\n             max grain size used for each particle\n        nsub : int[np]\n             Number of sizes averaged for each particle\n        apow : float[np]\n             Negative size distribution power law (e.g. 3.5)\n        a1 : float[np]\n            Mean grain radius\n        a2 : float[np]\n            Radius of the grain with mean surface area\n        a3 : float[np]\n            Radius of the grain with mean volume\n        rho : float[np]\n             Specific density of grains\n        kabs : float[np,nlam]\n             Absorption cross section\n        ksca : float[np,nlam]\n             Scattering cross section\n        kext : float[np,nlam]\n             Extinction cross section\n        gsca : float[np,nlam]\n             Asymmetry parameter\n        f11, ..., f44 : float[np,nlam,nang]\n             Scattering matrix element F_11, ... ,F_44\n        chop : float[np]\n             Degrees chopped off forward scattering\n        tmin : float\n             Minimum temperature for mean opacities\n        tmax : float\n             Maximum temperature for mean opacities\n        ntemp : int\n             Number of temperatures for mean opacities\n        temp : float[ntemp]\n             Temperatures used for mean opacities\n        kplanck : float[np,ntemp]\n             Planck mean opacities, after calling computemean()\n        kross : float[np,ntemp]\n             Rosseland mean opacities, after calling computemean()\n        norm : string\n             Current scattering matrix normalization\n\n        Methods\n        -------\n\n        plot()\n             Plot the opacities and the scattering matrix\n\n        computemean(tmin=10,tmax=1500,ntemp=100)\n             Compute Planck and Rosseland mean opacities\n\n        scatnorm(norm='')\n             Check or change the normalization of the scattering matrix\n\n        sizedist(N_of_a)\n             Compute opacity of a size distribution of elements of SELF\n        \"\"\"\n    def __init__(self,cmd,cache=''):\n        \"\"\"\"Create a new optool.particle opject.\n\n        Parameters\n        ---------=\n\n        cmd  : str\n               A shell command to run optool. The output produced by this\n               command will be read in and stored in an instance of the\n               optool.particle class.\n\n        cache  : str, optional\n               The diretory to cache the optool output files in, so that\n               they can be read instead of recomputed the next time\n               the same command is used.  The cache is automatically\n               cleared when CMD changes between runs.\n        \"\"\"\n        if (type(cmd)==list):\n            self.cmd = \" \".join(cmd)\n        elif (type(cmd)==str):\n            self.cmd = cmd\n        else:\n            raise RuntimeError(\"First argument CMD needs to be string or list\")\n        \n        if (cache and checkcmd(cache,self.cmd)):\n            # We can read the output directly from a directory that was\n            # created by the exact same command.\n            print(\"Using result cache in directory:\",cache,\"...\")\n            cmd=''\n        else:\n            # Convert command string into list if necessary\n            if (isinstance(cmd, str)):\n                cmd = cmd.split()\n\n                if cmd[0].startswith(\"~\"):\n                    cmd[0] = os.path.expanduser(cmd[0])\n\n            # Find the optool executable\n            bin = find_executable(cmd[0])\n            if (not bin):\n                raise RuntimeError(\"Executable not found: \"+cmd[0])\n\n        # Wrap the main part into try - finally to make sure we clean up\n        try:\n            if (cache):\n                dir = cache\n            else:\n                # create a directory for the output and make sure it is empty\n                random.seed(a=None)\n                dir = 'optool_tmp_output_dir_'+str(int(random.random()*1e6))\n            if cmd:\n                # make sure directory is new and empty\n                os.system('rm -rf '+dir)\n                os.system('mkdir '+dir)\n                # Store the command line we are using.  We store the\n                # string version of the command, not the list version.\n                writecmd(dir,self.cmd)\n                # tell the command to use the directory as writing desination\n                cmd.append('-o'); cmd.append(dir)\n    \n                # Run optool to produce the opacities\n                cmd[0] = bin; subprocess.Popen(cmd).wait()\n            \n            # Check if there is output we can use\n            scat,ext = check_for_output(dir)\n            self.scat = scat\n            self.massscale = 1.\n    \n            kabs=[]; ksca=[]; kext=[]; gg=[]\n            f11=[]; f12=[]; f22=[]; f33=[]; f34=[]; f44=[]\n            nfiles=0; header=[];\n            materials = []\n            rho = []\n            \n            for i in range(5000):\n                if scat:\n                    file = (\"%s/dustkapscatmat_%03d.%s\") % (dir,(i+1),ext)\n                else:\n                    file = (\"%s/dustkappa_%03d.%s\") % (dir,(i+1),ext)\n                if (not os.path.exists(file)): break\n                nfiles = nfiles+1\n                x = readoutputfile(file,scat)\n                header.append(x[0])\n                lam = x[1]\n                kabs.append(x[2])\n                ksca.append(x[3])\n                kext.append(x[2]+x[3])\n                gg.append(x[4])\n                if scat:\n                    scatang = x[5]\n                    f11.append(x[6])\n                    f12.append(x[7])\n                    f22.append(x[8])\n                    f33.append(x[9])\n                    f34.append(x[10])\n                    f44.append(x[11])\n                    self.scat = scat\n                self = parse_headers(header,self)\n                self.nlam = len(lam)\n                self.kabs = np.array(kabs)\n                self.ksca = np.array(ksca)\n                self.kext = np.array(kext)\n                self.gsca = np.array(gg)\n                self.lam  = lam\n                if scat:\n                    self.nang = len(scatang)\n                    self.scatang = scatang\n                    self.f11  = np.array(f11)\n                    self.f12  = np.array(f12)\n                    self.f22  = np.array(f22)\n                    self.f33  = np.array(f33)\n                    self.f34  = np.array(f34)\n                    self.f44  = np.array(f44)\n                else:\n                    self.nang = 0\n            self.np = nfiles\n        finally:\n            if cache:\n                print(\"Files remain available in directory: \"+dir)\n            else:\n                print(\"Cleaning up temporary directory \"+dir)\n                os.system('rm -rf '+dir)\n\n    def plot(self):\n        \"\"\"Create interactive plots of the opacities in SELF.\n\n        Furthermore, a plot for the scattering matric elements and, if the\n        computemean() method has been called, a plot of the mean opacities\n        are produces as well.\n        \"\"\"\n\n        # Check if mean opacities have been computed\n        if hasattr(self, 'kplanck'):\n            # llamfmt = np.round(np.log10(self.lam),decimals=3)\n            kplanck = self.kplanck\n            kross   = self.kross\n            temp = self.temp\n            viewarr([kplanck,kross],index=1,ylabel=['kplanck','kross'],\n                    idxnames=['grain index','log lambda [um]'],\n                    idxvals=[np.array(range(self.np))+1,temp])\n\n        # Extract the kappas and g\n        kabs   = np.copy(self.kabs)\n        ksca   = np.copy(self.ksca)\n        kext   = kabs+ksca\n        gg     = np.copy(self.gsca)\n    \n        # limit the kappa plotting range\n        minkap = 1e0\n        kabs   = np.maximum(kabs,minkap)\n        ksca   = np.maximum(ksca,minkap)\n        kext   = np.maximum(kext,minkap)\n    \n        # We will plot the logarithms of the Kappa values\n        kabs   = np.log10(kabs)\n        ksca   = np.log10(ksca)\n        kext   = np.log10(kext)\n    \n        # Scale g such that it will fill the y range of the kappa plot\n        kmin   = np.amin(np.array([np.amin(kabs),np.amin(ksca),np.amin(kext)]))\n        kmax   = np.amax(np.array([np.amax(kabs),np.amax(ksca),np.amax(kext)]))\n        ggscal = gg*(kmax-kmin)+kmin\n        \n        # Extract and plot the scattering matrix elements\n        if self.scat:\n            bottom = 1e-2\n            f11 = logscale_with_sign(np.copy(self.f11),bottom)\n            f12 = logscale_with_sign(np.copy(self.f12),bottom)\n            f22 = logscale_with_sign(np.copy(self.f22),bottom)\n            f33 = logscale_with_sign(np.copy(self.f33),bottom)\n            f34 = logscale_with_sign(np.copy(self.f34),bottom)\n            f44 = logscale_with_sign(np.copy(self.f44),bottom)\n            f00 = f11*0.\n    \n            # Make version of grid variables with fewer digits\n            lamfmt  = np.round(self.lam,decimals=3)\n            angfmt  = np.round(self.scatang,decimals=3)\n\n            # interactive plot of the scattering matric elements\n            viewarr([f00,f00+2,f00-2,f00+4,f00-4,f11,f12,f22,f33,f34,f44],\n                    index=2,ylabel=['<1e-2','±1','','±1e2','','f11','f12',\n                                    'f22','f33','f34','f44'],\n                    idxnames=['grain index','lambda [um]','angle'],\n                    idxvals=[np.array(range(self.np))+1,lamfmt,angfmt])\n\n        # interactive plot of kabs, ksca, kext, and g\n        llamfmt = np.round(np.log10(self.lam),decimals=3)\n        viewarr([ggscal,kext,ksca,kabs],index=1,\n                ylabel=['gg','kext','ksca','kabs'],\n                idxnames=['grain index','log lambda [um]'],\n                idxvals=[np.array(range(self.np))+1,llamfmt])\n\n    def select(self,i):\n        \"\"\"Select just one bin from a multi-particle object.\n        A multi-particle opject is produced when running optool with\n        a -d switch.\n\n        This is useful for doing particle arithmetic, which only works for\n        single particle objects.\n        \"\"\"\n        x = copy.deepcopy(self)\n\n        x.np = 1\n        j = i+1\n        \n        x.fmax    = x.fmax[i:j]\n        x.pcore   = x.pcore[i:j]\n        x.pmantle = x.pmantle[i:j]\n\n        x.amin    = x.amin[i:j]\n        x.amax    = x.amax[i:j]\n        x.nsub    = x.nsub[i:j]\n        x.apow    = x.apow[i:j]\n        x.a1      = x.a1[i:j]\n        x.a2      = x.a2[i:j]\n        x.a3      = x.a3[i:j]\n        x.rho     = x.rho[i:j]\n        x.chop    = x.chop[i:j]\n        \n        x.kabs    = x.kabs[i:j,:]\n        x.ksca    = x.ksca[i:j,:]\n        x.kext    = x.kext[i:j,:]\n        x.gsca    = x.gsca[i:j,:]\n\n        if x.scat:\n            x.f11     = x.f11[i:j,:,:]\n            x.f12     = x.f12[i:j,:,:]\n            x.f22     = x.f22[i:j,:,:]\n            x.f33     = x.f33[i:j,:,:]\n            x.f34     = x.f34[i:j,:,:]\n            x.f44     = x.f44[i:j,:,:]\n\n        if (hasattr(x,'kross')):\n            x.kplanck = x.kplanck[i:j,:]\n            x.kross   = x.kross[i:j,:]\n\n        return x\n\n    def sizedist(self,N_of_a):\n        \"\"\"Compute opacity of a size distribution of elements of SELF.\n\n        Arguments\n        ---------\n                \n        N_of_a : numpy array containing the sumber of partiles of each size\n                 available in SELF (as given by self.a1)\n        \"\"\"\n        # Check if N_of_a is compatible with self.a1\n        if (len(N_of_a) != len(self.a1)):\n            raise RuntimeError('N_of_a and a1 arrays differ in length')\n            \n        # create a particle object to return\n        x = copy.deepcopy(self)\n\n        # Fill all attributes that make sense\n        x.np = 1\n\n        x.cmd     = ''\n\n        x.materials = self.materials[0:1]\n        \n        x.fmax    = x.fmax[0:1]\n        x.pcore   = x.pcore[0:1]\n        x.pmantle = x.pmantle[0:1]\n\n        x.amin    = x.a1[0:1]\n        x.amax    = x.a1[-1:]\n        x.nsub    = self.nsub[0]*self.np\n        x.apow    = x.apow[0:1]\n        x.a1 = x.a2 = x.a3 = -1;\n        x.rho     = x.rho[0:1]\n        x.chop    = x.chop[0:1]\n\n        # Turn N_of_a into mass fractions, normalized to 1\n        mass   = (4./3.) * np.pi * (self.a1*1e-4)**3 * self.rho\n        m_of_a = N_of_a*mass\n        mtot = np.sum(m_of_a)\n        mfrac  = m_of_a/mtot\n        x.massscale = 1\n\n        # add up the opacities\n        x.kabs = np.sum(self.kabs*mfrac[:,None],axis=0)\n        x.ksca = np.sum(self.ksca*mfrac[:,None],axis=0)\n        x.kabs = x.kabs[None,:]; x.ksca = x.ksca[None,:] # add particle size axis\n        x.kext = x.kabs+x.ksca\n\n        # compute gsca\n        x.gsca = np.sum(self.ksca*self.gsca*mfrac[:,None],axis=0) / x.ksca[0]\n        x.gsca = x.gsca[None,:]  # add particle size axis\n\n        # compute the scattering matrix elements\n        if x.scat:\n            if self.norm == 'hovenier':\n                w  = (self.ksca*mfrac[:,None])[:,:,None]\n                wn = x.ksca[0,:,None]\n                x.f11 = np.sum(self.f11*w,axis=0)/wn\n                x.f12 = np.sum(self.f12*w,axis=0)/wn\n                x.f22 = np.sum(self.f22*w,axis=0)/wn\n                x.f33 = np.sum(self.f33*w,axis=0)/wn\n                x.f34 = np.sum(self.f34*w,axis=0)/wn\n                x.f44 = np.sum(self.f44*w,axis=0)/wn\n            else:\n                w  = mfrac[:,None,None]\n                x.f11 = np.sum(self.f11*w,axis=0)\n                x.f12 = np.sum(self.f12*w,axis=0)\n                x.f22 = np.sum(self.f22*w,axis=0)\n                x.f33 = np.sum(self.f33*w,axis=0)\n                x.f34 = np.sum(self.f34*w,axis=0)\n                x.f44 = np.sum(self.f44*w,axis=0)\n            # Add the particle size axis\n            x.f11 = x.f11[None,:]; x.f12 = x.f12[None,:]; x.f22 = x.f22[None,:]; \n            x.f33 = x.f33[None,:]; x.f34 = x.f34[None,:]; x.f44 = x.f44[None,:]; \n\n        # Return the new object\n        return x\n    \n    def scatnorm(self,norm=\"\"):\n        \"\"\"Check or change the normalization of the scattering matrix.\n\n        Without an argument, check the current normalization of the\n        scattering matrix.\n\n            p = optool.particle('./optool -s')\n            p.scatnorm()\n\n        Calling the method with an argument will change the normalization\n        to one of the following conventions\n\n            'b'  Bohren & Huffman\n            'm'  Mishchenko\n            'r'  RADMC-3D\n            'h'  Hovenier\n        \"\"\"\n\n        # analyze the NORM parameter\n        if (norm == \"\"):\n            renorm = False\n            conv = self.norm\n        else:\n            renorm = True\n            conv = norm\n            \n        conv = conv.lower()\n        if (conv in ['h','hovenier']):\n            self.norm = \"hovenier\"\n            name = \"Hovenier\"\n            normalization = \"4 pi\"\n            units = \"sr^-1\"\n        elif (conv in ['b','bh','bohren','bohrenhuffman']):\n            self.norm = \"bohrenhuffman\"\n            name = \"Bohren & Huffman\"\n            normalization = \"kappa_scat m_grain (2pi/lambda)^2\"\n            units = \"sr^-1\"\n        elif (conv in ['m','mish','mishchenko']):\n            self.norm = \"mishchenko\"\n            name = \"Mishchenko\"\n            normalization = \"kappa_scat m_grain\"\n            units = \"cm^2 sr^-1\"\n        elif (conv in ['r','radmc','radmc3d']):\n            self.norm = \"radmc3d\"\n            name = \"RADMC-3D\"\n            normalization = \"kappa_scat\"\n            units = \"cm^2 g^-1 sr^-1\"\n        else:\n            print(\"ERROR: Unknown normalization \",conv)\n            return -1\n        \n        ang   = self.scatang\n        lam   = self.lam\n        wav   = 2.*np.pi/(lam*1e-4)      # need cm here, not micrometer\n        ratio = np.zeros([self.np,self.nlam])\n\n        # Compute values and weights for the integration\n        if (self.gridtype == \"boundary\"):\n            # Matrix values are on cell boundaries\n            if (ang[0] != 0):\n                raise RuntimeError(\"Inconsistency between gridtype \\\"boundary\\\" and angle values\")\n            thetab = ang*np.pi/180.\n            mub = np.cos(thetab)\n            dmu = mub[:-1]-mub[1:]   # Defined negatively for mu integral\n            fc = 0.5*(self.f11[:,:,1:]+self.f11[:,:,:-1]) \n        else:\n            # This is the standard grid with values on cell midpoints\n            if (ang[0] == 0):\n                raise RuntimeError(\"Inconsistency between gridtype \\\"center\\\" and angle values\")\n            th1 = (ang-0.5)*np.pi/self.nang; mu1 = np.cos(th1)\n            th2 = (ang+0.5)*np.pi/self.nang; mu2 = np.cos(th2)\n            dmu = mu1-mu2  # Defined negatively for the mu integral\n            fc  = self.f11\n\n        for ip in (range(self.np)):\n            for il in (range(self.nlam)):\n                integ = 2.*np.pi*np.sum(fc[ip,il,:]*dmu)\n                if (self.norm == \"radmc3d\"):\n                    nn = self.ksca[ip,il]\n                elif (self.norm == \"hovenier\"):\n                    nn = 4.*np.pi\n                elif (self.norm == \"bohrenhuffman\"):\n                    mgrain = (4./3.)*np.pi * self.a3[ip]**3 * self.rho[ip]\n                    nn = self.ksca[ip,il] * wav[il]**2 * mgrain\n                elif (self.norm == \"mishchenko\"):\n                    mgrain = (4./3.)*np.pi * self.a3[ip]**3 * self.rho[ip]\n                    nn = self.ksca[ip,il] * mgrain\n                if (norm):\n                    self.f11[ip,il,:] = self.f11[ip,il,:] * nn/integ\n                    self.f12[ip,il,:] = self.f12[ip,il,:] * nn/integ\n                    self.f22[ip,il,:] = self.f22[ip,il,:] * nn/integ\n                    self.f33[ip,il,:] = self.f33[ip,il,:] * nn/integ\n                    self.f34[ip,il,:] = self.f34[ip,il,:] * nn/integ\n                    self.f44[ip,il,:] = self.f44[ip,il,:] * nn/integ\n                    ratio[ip,il] = 1.\n                else:\n                    ratio[ip,il] = integ / nn\n        \n        if (norm):\n            print(\"New     nomalization is       \",name,\" convention\")\n        else:\n            print(\"Current nomalization is       \",name,\" convention\")\n        print(\"Units of matrix elements are  \",units)\n        print(\"Integral F_11 d Omega =       \",normalization)\n        if (not norm):\n            maxerr = np.amax(np.abs(ratio-1.))\n            print(\"Maximum deviation              %7.2e\" % maxerr)\n\n    def computemean(self, tmin=10., tmax=1500., ntemp=100):\n        \"\"\"Compupte mean opacities from the opacities in self.\n\n        Parameters\n        ----------\n\n        tmin : float\n             minimum temperature for which to compute mean opacities\n        tmax : float\n             maximum temperature for which to compute mean opacities\n        ntemp : int\n             number of temperature steps between tmin and tmax\n        \"\"\"\n        self.tmin    = tmin\n        self.tmax    = tmax\n        self.ntemp   = ntemp\n        self.temp    = np.logspace(np.log10(tmin),np.log10(tmax),ntemp)\n        self.kross   = np.zeros([self.np,self.ntemp])\n        self.kplanck = np.zeros([self.np,self.ntemp])\n\n        cl = 2.99792458e10          # Speed of light [cgs]\n        nu = 1e4*cl/self.lam        # 10^4 because lam is in um - we need cm\n        dnu = -1. * np.hstack([nu[1]-nu[0],0.5 * (nu[2:]-nu[:-2]), nu[-1] - nu[-2]  ])\n\n        for it in range(self.ntemp):\n            bnu    = bplanck(self.temp[it],nu)\n            bnudt  = bplanckdt(self.temp[it],nu)\n            dumbnu = np.sum(bnu*dnu)\n            dumdb  = np.sum(bnudt*dnu)\n            for ip in range(self.np):\n                kap_p  = np.sum(self.kabs[ip,:]*bnu*dnu) / dumbnu\n                kap_r  = dumdb / np.sum(bnudt * dnu / ( self.kabs[ip,:] + self.ksca[ip,:]*(1.-self.gsca[ip,:])))\n                self.kplanck[ip,it] = kap_p\n                self.kross[ip,it]   = kap_r\n\n    def __add__(s,o):\n        \"\"\"Addition of optool.particle objects.\n\n        This can be used to mix different grain types together\n        into a dust model.\n        \n            # Make a silicate grain and a carbonatieous grain\n            p1 = optool.particle('./optool -a 0.01 0.3 pyr-mg70')\n            p2 = optool.particle('./optool -1 0.03 0.1 c-z')\n\n            # Mix the particles with a mass ration 0.75 : 0.25\n            # Make sure abundances add up to 1, or the opacities will\n            # not be per g of dust!\n            p = 0.75*p1 + 0.25*p2\n\n            # Apply a dust-to-gas ratio, so that the opacities will be\n            # per unit of GAS mass\n            dtg = 0.01\n            p   = dtg * p\n\n            # Plot the opacities\n            p.plot()\n        \"\"\"\n        #\n        # First, check if the particles are compatible\n        #\n        if ((s.np > 1) or (o.np>1)):\n            raise TypeError('Cannot add multi-particle objects')\n        if ((s.nlam != o.nlam) or (np.abs((s.lam-o.lam)/s.lam).any()>1e-4)):\n            raise RuntimeError('Wavelength grids differ')\n        if (s.scat):\n            if ((s.nang != o.nang) or\n                (np.abs((s.scatang[1:]-o.scatang[1:])/s.scatang[1:]).any()>1e-4)):\n                # We don't check the first value, could be 0\n                raise RuntimeError('Angular grids differ')\n            if (s.norm != o.norm):\n                raise RuntimeError('Scattering normalizations differ')\n        #\n        # Now do the adding\n        #\n        x = copy.deepcopy(s)\n        x.kabs = x.kabs+o.kabs\n        x.ksca = x.ksca+o.ksca\n        x.kext = x.kext+o.kext\n        # F11 is linear in the integral for the computation of g.\n        # So we can just take the weighted mean for g.\n        x.gsca = (x.ksca*x.gsca + o.ksca*o.gsca) / (x.ksca+o.ksca)\n        x.massscale = s.massscale + o.massscale\n\n        if s.scat:\n            # There is a scattering matrix.\n            if s.norm == 'hovenier':\n                # Add, weighted by kappa_scat\n                ws = s.ksca[:,:,None]\n                wo = o.ksca[:,:,None]\n                wn = ws+wo\n            else:\n                # Just add the values\n                ws, wo, wn = 1.,1.,1.\n            x.f11 = (s.f11*ws + o.f11*wo) / wn\n            x.f12 = (s.f12*ws + o.f12*wo) / wn\n            x.f22 = (s.f22*ws + o.f22*wo) / wn\n            x.f33 = (s.f33*ws + o.f33*wo) / wn\n            x.f34 = (s.f34*ws + o.f34*wo) / wn\n            x.f44 = (s.f44*ws + o.f44*wo) / wn\n        #\n        # Invalidate attributes that no longer make sense.\n        #\n        x.materials = np.hstack((x.materials,o.materials))\n        if (x.fmax    != o.fmax   ): x.fmax    = -1\n        if (x.pcore   != o.pcore  ): x.pcore   = -1\n        if (x.pmantle != o.pmantle): x.pmantle = -1\n        if (x.amin    != o.amin   ): x.amin    = -1\n        if (x.amax    != o.amax   ): x.amax    = -1\n        if (x.nsub    != o.nsub   ): x.nsub    = -1\n        if (x.apow    != o.apow   ): x.apow    = -1\n        if (x.rho     != o.rho    ): x.rho     = -1\n        if (x.chop    != o.chop   ): x.chop    = -1\n        x.a1,x.a2,x.a3 = -1,-1,-1\n\n        if hasattr(s, 'kplanck'):\n            kplanck = -1\n            kross   = -1 \n            temp    = -1\n\n        return x\n        \n    def __mul__(s,o):\n        \"\"\"Multiplication for optool.particle objects.\n        \n        This is intended for the multiplication of such an object with\n        a number.  The way to think about it is like this.  Such an\n        contains opacities in units cm^2/g.  Multiplying it with a\n        number means that the opacities are now per a different mass.\n        This sounds strange, but it makes sense together with addition\n        of particles - which see.\n        \"\"\"\n        if (not (isinstance(o,int) or isinstance(o,float))):\n            raise TypeError('optool.particle object can only be multiplied by a number')\n        x = copy.deepcopy(s)\n        x.kabs = x.kabs*o; x.ksca = x.ksca*o; x.kext = x.kext*o\n        x.massscale = x.massscale*o\n        if (s.scat and (s.norm != 'hovenier')):\n            # We need to change the matrix as well, it's normalized to ksca\n            x.f11 = x.f11*o; x.f12 = x.f12*o; x.f22 = x.f22*o\n            x.f33 = x.f33*o; x.f34 = x.f34*o; x.f44 = x.f44*o\n        return x\n\n    def __rmul__(s,o):\n        \"\"\"Rightsided multiplication of optool.particle object by a number.\"\"\"\n        return s*o\n    def __div__(s,o):\n        \"\"\"Division of optool.particle object by a number.\"\"\"\n        return s * (1./o)\n    def __truediv__(s,o):\n        \"\"\"Division of optool.particle object by a number.\"\"\"\n        return s * (1./o)\n\n    def write(s,filename,header=\"Opacity file written by optool.particle.write\"):\n        \"\"\"Write a single particle object to a file.\n        \n        The format of the file will be similar to the dustkappa.dat and\n        dustkapscatmat.dat files produced by the optool FORTRAN program,\n        with the difference that the header will not contain the detailed\n        information about the computation.  But the file would be readable\n        with the `readoutputfile' function.\n\n        Arguments\n        =========\n\n        filename:  String, pointing the file name to which output should\n                   be written.\n        \n        header:    A string that should be put at the beginning of the\n                   file, as a commend describing the dataset.  The string\n                   may have several lines, the # comment character will\n                   automatically be added to the beginning of every line.\n        \"\"\"\n\n        if (s.np>1):\n            raise TypeError('Writing is not supported for multi-particle objects')\n        try:\n            wfile = open(filename, 'w')\n        except:\n            raise RuntimeError('Cannot write to file: '+filename)\n\n        headerlines = header.splitlines()\n        for i in range(len(headerlines)):\n            wfile.write(\"# %s\\n\" % headerlines[i])\n        if s.scat:\n            wfile.write('  0\\n')\n            wfile.write('  %d\\n' % s.nlam)\n            wfile.write('  %d\\n' % s.nang)\n            wfile.write('\\n')\n        else:\n            wfile.write('  3\\n')\n            wfile.write('  %d\\n' % s.nlam)\n            \n        for i in range(s.nlam):\n            # write the lambda grid and the opacities\n            wfile.write(' %15.5e %15.5e %15.5e %15.5e\\n' % (s.lam[i],s.kabs[0,i],s.ksca[0,i],s.gsca[0,i]))\n            \n        if s.scat:\n            # we have a scattering matrix\n            wfile.write('\\n')\n            # Write the angular grid\n            for i in range(s.nang):\n                wfile.write(\"%9.2f\\n\" % s.scatang[i])\n            wfile.write('\\n')\n            # Write the scattering matrix\n            for il in range(s.nlam):\n                for ia in range(s.nang):\n                    wfile.write('  %15.5e %15.5e %15.5e %15.5e %15.5e %15.5e\\n' %\n                                (s.f11[0,il,ia],s.f12[0,il,ia],s.f22[0,il,ia],\n                                 s.f33[0,il,ia],s.f34[0,il,ia],s.f44[0,il,ia]))\n        wfile.close()\n\nclass lnktable:\n    \"\"\"Class to work with lnk files.\n\nlnk stands for lambda, n, and k, where and and k are the real and\nimaginary components of the refractive index of a material.\n    \n\n\nConversion\n----------\n\n    The standard format of these files is described in the optool user\n    guide.  The class can also read files that are formatted\n    differently, in order to create properly formatted version.  For\n    example, if you have a file starting with 4 unimportant lines, and\n    then data columns where n an k are in column 1 and 2,\n    respectively, and the wavelength is given in units of cm^-1 in\n    column 3, you can do the conversion in this way:\n\n    new = optool.lnktable('x.dat',i_lnk=[3,1,2], nskip=4)\n    new.lam = 10000./new.lam   # convert cm^-1 -> micrometer\n    new.sort()                 # sort arrays according to lambda\n    new.rho = 3.2              # set density in g/cm^3\n    new.header = \"# This is a silicate from Dorschner+1995)\"\n    new.write('sil-Dorschner1995.lnk')\n\n    \"\"\"\n    def __init__(self,file,i_lnk=[1,2,3],nskip=0,nlam_rho=True):\n        \"\"\"Create a new optool.lnktable object\n\n        Parameters\n        ----------\n        \n        file : str\n             the file name from which to read the lnk data\n\n        i_lnk : numpy array, optional\n             the column numbers where to find lambda, the real part of the\n             refractive index and the imaginary part of it, respectively.\n             The default is [1,2,3] .\n\n        nskip : int, optional\n             Number of lines to skil at the beginning.  Lines starting with\n            `#', `!' or `*` are stored as header lines and ar skipped in\n             this way. So this parameter is for dealing with files that are\n             not yet formatted in the standard way for optool.  The default\n             is 0.\n\n        nlam_rho : boolean, optional\n             True means, the first unskipped line contains the number of\n             wavelengths points and the specific density of the material.\n             False means no such line exists, and the lines have to be\n             counted.  Rho will be se to 0 then, to indicate that the value\n             is not know at this point.\n        \"\"\"\n        self.filename = file\n        try:\n            rfile = open(file, 'r')\n        except:\n            print('ERROR: File not found:',file)\n            return -1\n        print('Reading lnk file ',file,'...')\n\n        # Skip lines that are irrelevant\n        for i in range (nskip): dum = rfile.readline()\n\n        # Read the header/comment field\n        header = ''\n        dum = rfile.readline()\n        while ((dum.strip()[0]=='#') or (dum.strip()[0]=='*') or (dum.strip()[0]=='!')):\n            header = header + dum\n            dum = rfile.readline()\n        self.header = header\n\n        # Extract the number of wavelengths points, and the material density\n        if (nlam_rho):\n            dum = dum.split()\n            self.nlam = int(dum[0])\n            self.rho  = float(dum[1])\n            dum = rfile.readline()\n        else:\n            self.nlam = 1\n            self.rho  = 0.0\n            print(\"Warning: density rho is not known! Make sure to set it by hand.\")\n\n        # Prepare the arrays\n        self.lam = []\n        self.n   = []\n        self.k   = []\n        ilam     = 0\n        \n        # Fill the arrays\n        while True:\n            dum  = dum.split()\n            ilam = ilam+1\n            self.lam.append(float(dum[i_lnk[0]-1]))\n            self.n.append(  float(dum[i_lnk[1]-1]))\n            self.k.append(  float(dum[i_lnk[2]-1]))\n            dum = rfile.readline()\n            if ((len(dum) == 0) or dum.isspace()):\n                # No more data. Truncate the arrays and stop reading\n                if (not (self.nlam == ilam)):\n                    print(\"WARNING: found %d lines of data, not %d\" % (ilam,self.nlam))\n                # Convert to numpy arrays and exit\n                self.nlam = ilam\n                self.lam = np.array(self.lam)\n                self.n   = np.array(self.n)\n                self.k   = np.array(self.k)\n                break\n        rfile.close()\n\n    def sort(self):\n        \"\"\"Sort lam, n, and k according to lambda array.\"\"\"\n        sortinds = self.lam.argsort()\n        self.lam = self.lam[sortinds]\n        self.n   = self.n[sortinds]\n        self.k   = self.k[sortinds]\n\n    def smooth(self,size=10):\n        \"\"\"Smooth n and k with a medium filter of SIZE bins.\"\"\"\n        from scipy.ndimage import median_filter\n        self.n = median_filter(self.n,size)\n        self.k = median_filter(self.k,size)\n\n    def decimate(self,step=2,size=0):\n        \"\"\"Decimate the arrays by a factor STEP.\n        When SIZE is given instead, decimate to that size.\"\"\"\n        # FIXME: should we force to keep the first and last values?\n        from math import floor\n        if (size > 0):\n            nlam = self.lam.size        \n            step = floor(nlam/size)\n            print(\"Decimating in steps of \",step,\" to reach size \",size)\n        self.lam = self.lam[:-step:step]\n        self.n   = self.n[:-step:step]\n        self.k   = self.k[:-step:step]\n        self.nlam = self.lam.size        \n\n    def klimit(self,limit=0.):\n        \"\"\"Make sure imaginary part k is never smaller than LIMIT\"\"\"\n        self.k[self.k<limit] = limit\n\n    def fromwav(self):\n        \"\"\"Convert from wavenumbers and sort.\n        Assuming that the self.lam array is actually wavenumbers,\n        convert them to microns, and then sort the arraus so that\n        lambda is increasing.\n        \"\"\"\n        self.lam = 10000./self.lam\n        self.sort()\n\n    def compute_absorbance(self,dlayer=5):\n        \"\"\"Compute the absorbance for a thin layer of the material.\n\n        dlayer   is the thickness of the layer to be used for the\n                 computation, in micrometer units.  The default is 5um.\n\n        Simple assumptions: infinite vacuum \"substrate\".\n        R. Swaneloel 1983, J.Phys. E 16,1214\n        We use the expressions (A2), for an infinite substrate.\"\"\"\n        n = self.n\n        k = self.k\n        s = 1.    # assume a vacuum subtrate\n        lam = self.lam/10000.      # units are cm now\n        d = dlayer /1e4            # Units: cm\n        phi   = 4.*np.pi*n*d/lam\n        alpha = 4.*np.pi*k/lam\n        x  = np.exp(-alpha*d)\n        A  = 16.*s*(n**2+k**2)\n        B  =  ( (n+1.)**2 + k**2 ) * ( (n+s)**2 + k**22 )\n        C1 = ( (n**2-1+k**2) * (n**2-s**2+k**2) + 4.*k**2*s  )    *2.*np.cos(phi)\n        C2 = k * ( 2.*(n**2-s**2-k**2 ) + 2.* s *(n**2-1+k**2 ) ) *2.*np.sin(phi)\n        C  = C1-C2\n        D  = ( (n-1)**2 + k**2 ) * ( (n-s)**2 + k**2 )\n        self.transmission  = A*x / (B-C*x-D*x**2)\n        self.absorptivity = -np.log(self.trans)\n        self.d = dlayer    # Record the density that was used.\n            \n    def plot(self):\n        \"\"\"Plot the refractive index aas a function of wavelength.\"\"\"\n        fig,ax = plt.subplots()\n        ax.semilogx(self.lam,self.n,label='n',color=\"blue\")\n        ax.set_title(self.filename)\n        ax.set_xlabel(r\"log $\\lambda$ [$\\mu$m]\")\n        ax.set_ylabel(r'real part: $n$',color=\"blue\")\n        ax2=ax.twinx()\n        ax2.loglog(self.lam,self.k,label='k',color=\"orange\")\n        ax2.set_ylabel(r'imaginary part: log $k$',color=\"orange\")\n        plt.show(block=False)\n\n    def write(self,file):\n        \"\"\"Write the table to a file.\"\"\"\n        try:\n            wfile = open(file, 'w')\n        except:\n            raise RuntimeError('Cannot write to file: '+file)\n        wfile.write(self.header)\n        wfile.write(\"  %d  %g\\n\" % (self.nlam,self.rho))\n        for i in range(self.nlam):\n            wfile.write(\"  %16.6e %16.6e %16.6e\\n\" %\n                        (self.lam[i],self.n[i],self.k[i]))\n        wfile.close()\n    def powerlaws(self):\n        \"\"\"Compute the extrapolation powerlaws.\"\"\"\n        print(\"n: \",(np.log(self.n[-1])-np.log(self.n[-2]))/(np.log(self.lam[-1])-np.log(self.lam[-2])))\n        print(\"k: \",(np.log(self.k[-1])-np.log(self.k[-2]))/(np.log(self.lam[-1])-np.log(self.lam[-2])))\n\n\ndef logscale_with_sign(array,bottom):\n    # Take the log10 of the absolute value of ARRAY, but transfer the\n    # sign back onto the result.  Compress the region between\n    # -BOTTOM and +BOTTOM into zero, smoothly.\n    # This is a clever way to make a logarithmic plot of a variable\n    # that has positive and negative values covering more then\n    # one order of magnitude.\n    lb = np.log10(bottom)\n    a  =  np.where(array>0)\n    b  =  np.where(array<=0)\n    array[a] =  np.log10(array[a]+bottom)  - lb\n    array[b] = -np.log10(-array[b]+bottom) + lb\n    return array\n\ndef check_for_output(dir):\n    # Check for and if necessary rename input files\n    for ext in['dat','inp']:\n        if (os.path.exists(dir+'/dustkapscatmat_001.'+ext)):\n            return True, ext\n        elif (os.path.exists(dir+'/dustkappa_001.'+ext)):\n            return False, ext\n        elif (os.path.exists(dir+'/dustkapscatmat.'+ext)):\n            os.system('mv '+dir+'/dustkapscatmat.'+ext+' '+dir+'/dustkapscatmat_001.'+ext)\n            return True, ext\n        elif (os.path.exists(dir+'/dustkappa.'+ext)):\n            os.system('mv '+dir+'/dustkappa.'+ext+' '+dir+'/dustkappa_001.'+ext)\n            return False, ext\n    raise RuntimeError('No valid OpTool output files found')\n\ndef parse_headers(headers,b):\n    # Extract information on run parameters from headers\n    n = len(headers)\n    b.amin  = np.zeros(n); b.amax = np.zeros(n); b.apow  = np.zeros(n)\n    b.a1    = np.zeros(n); b.a2 = np.zeros(n); b.a3 = np.zeros(n);\n    b.nsub  = np.zeros(n,dtype=np.int8)\n    b.pcore = np.zeros(n); b.pmantle = np.zeros(n); b.fmax = np.zeros(n);\n    b.chop  = np.zeros(n);\n    b.materials = []\n    b.rho = []\n\n    for i in range(n):\n        mat = []\n        m = re.search(r\" amin \\[um\\]\\s*=\\s*(-?[0-9.]+)\",headers[i])\n        b.amin[i]=float(m.group(1))\n        m = re.search(r\" amax \\[um\\]\\s*=\\s*(-?[0-9.]+)\",headers[i])\n        b.amax[i]=float(m.group(1))\n        m = re.search(r\" na\\s*=\\s*(-?[0-9.]+)\",headers[i])\n        b.nsub[i]=int(m.group(1))\n        m = re.search(r\" <a\\^n>\\s*=\\s*([-+0-9.eE]+)\\s+([-+0-9.eE]+)\\s+([-+0-9.eE]+)\",headers[i])\n        b.a1[i]=float(m.group(1))\n        b.a2[i]=float(m.group(2))\n        b.a3[i]=float(m.group(3))\n\n        for m in re.finditer(r\"^#\\s+(core|mantle|grain)\\s+([.0-9]+)\\s+([.0-9]+)\\s*(\\S.*?)$\",headers[0],re.MULTILINE):\n            mat.append([m.group(1),float(m.group(2)),float(m.group(3)),m.group(4)])\n            if m.group(1) == \"grain\": b.rho.append(float(m.group(3)))\n        b.materials.append(mat)\n    b.rho = np.array(b.rho)\n    b.materials = np.array(b.materials)\n    m = re.search(r\" apow\\s*=\\s*(-?[0-9.]+)\",headers[0])\n    b.apow[i]=float(m.group(1))\n    m = re.search(r\" porosity\\s*=\\s*([0-9.]+)\",headers[0])\n    b.pcore[i]=float(m.group(1))\n    m = re.search(r\" p_mantle\\s*=\\s*(-?[0-9.]+)\",headers[0])\n    b.pmantle[i]=float(m.group(1))\n    m = re.search(r\" fmax\\s*=\\s*([0-9.]+)\",headers[0])\n    b.fmax[i]=float(m.group(1))\n    m = re.search(r\" chop\\s*=\\s*([0-9.]+)\",headers[0])\n    b.chop[i]=float(m.group(1))\n\n    m = re.search(r\" RADMC-3D\",headers[0])\n    if m:\n        b.radmc = True\n        b.gridtype = \"boundary\"\n        b.norm = \"radmc\"\n    else:\n        b.radmc = False\n        b.gridtype = \"center\"\n        b.norm = \"hovenier\"\n\n    return b\n\ndef readoutputfile(file,scat):\n    \"\"\"Read OpTool output file FILE.\n\n    Parameters\n    ----------\n\n    file : str\n         The file name to read\n    scat : bool\n         When True, the file contains a scattering matrix\n\n    Returns\n    -------\n\n    Depending on the SCAT flag, Returns a list with these elements\n   \n    [header,lam,kabs,ksca,phase_g]  or\n    [header,lam,kabs,ksca,phase_g,scatang,f11,f12,f22,f33,f34,f44]\n    \"\"\"\n    try:\n        rfile = open(file, 'r')\n    except:\n        raise RuntimeError('File not found: '+file)\n    print('Reading',file,'...')\n\n    # Read the header/comment field\n    header = ''\n    dum = rfile.readline()\n    while dum.strip()[0]=='#':\n        header = header + dum\n        dum = rfile.readline()\n\n    # Read the file format\n    while len(dum.strip())<1: dum = rfile.readline() # skip any empty lines\n    iformat = int(dum)\n\n    # Read the number of wavelengths in the file and prepare arrays\n    nlam = int(rfile.readline())\n    lam=np.zeros(nlam); kabs=np.zeros(nlam); ksca=np.zeros(nlam); phase_g=np.zeros(nlam)\n\n    if scat:\n        # Read the scattering angular grid size and prepare arrays\n        nang = int(rfile.readline())\n        scatang = np.zeros(nang)\n        f11=np.zeros([nlam,nang]); f12=np.zeros([nlam,nang]); f22=np.zeros([nlam,nang])\n        f33=np.zeros([nlam,nang]); f34=np.zeros([nlam,nang]); f44=np.zeros([nlam,nang])\n\n    # Read the opacities\n    dum = rfile.readline()\n    while len(dum.strip())<1: dum = rfile.readline() # skip any empty lines\n    for ilam in range(nlam):\n        dum           = dum.split()\n        lam[ilam]     = float(dum[0])\n        kabs[ilam]    = float(dum[1])\n        ksca[ilam]    = float(dum[2])\n        phase_g[ilam] = float(dum[3])\n        dum = rfile.readline()\n\n    if scat:\n        # Read the angular grid\n        while len(dum.strip())<1: dum = rfile.readline() # skip any empty lines\n        for iang in range(nang):\n            scatang[iang] = float(dum)\n            dum = rfile.readline()\n\n        # Read the scattering matrix\n        while len(dum.strip())<1: dum = rfile.readline()\n        dums = rfile.readlines()\n        dums.insert(0,dum)\n        data = np.fromstring(\"\".join(dums),sep=' ')\n        data = np.reshape(data,(nlam,nang,6),'C')\n        f11[:,:]=data[:,:,0]; f12[:,:]=data[:,:,1]; f22[:,:]=data[:,:,2]\n        f33[:,:]=data[:,:,3]; f34[:,:]=data[:,:,4]; f44[:,:]=data[:,:,5]\n\n        rfile.close()\n    if scat:\n        return [header,lam,kabs,ksca,phase_g,scatang,f11,f12,f22,f33,f34,f44]\n    else:\n        return [header,lam,kabs,ksca,phase_g]\n\ndef writecmd(dir,cmd):\n    \"\"\"Store the CMD string in file DIR/cmd.\n    \"\"\"\n    if (os.path.isdir(dir)):\n        # Directory does not exist\n        dir = dir.rstrip('/')\n        filename = dir+\"/cmd\"\n        try:\n            wfile = open(filename, 'w')\n        except:\n            print('ERROR: Cannot write to file: ',filename)\n            return False\n        newcmd=cmd.strip()\n        wfile.write(cmd+\"\\n\")\n        wfile.close()\n        return True\n    else:\n        return False\n    \ndef checkcmd(dir,cmd):\n    \"\"\"Check if new command line is the same as the old one.\n\n    This functions checks if the directory DIR contains a file\n    called CMD, and if the first line in thie directory is the\n    same as the string passed with the DIR parameter.\n    \"\"\"\n    if (not os.path.isdir(dir)):\n        # Directory does not exist\n        return False\n    if (len(os.listdir(dir))<=1):\n        # There are less than one file in the directory. So either the cmd\n        # file does not exist, or no output files are present.\n        return False\n    dir = dir.rstrip('/')\n    filename = dir+\"/cmd\"\n    if (not os.path.exists(dir+\"/cmd\")):\n        # The command file does not exist\n        return False\n    try:\n        rfile = open(filename, 'r')\n    except:\n        print('ERROR: Cannot read file: ',filename)\n        return False\n    dum = rfile.readline()\n    rfile.close()\n    cached_cmd = dum.strip()\n    new_cmd    = cmd.strip()\n    return (cached_cmd == new_cmd)\n    \ndef viewarr(data,index=0,x=None,ymin=None,ymax=None,ylabel=None,idxnames=None,idxvals=None,idxformat=''):\n    \"\"\"\n    For details about this function see https://github.com/dullemond/interactive_plot\n    \"\"\"\n    if type(data)==list:\n        shape =  data[0].shape\n        ndim  = len(shape)\n    else:\n        shape = data.shape\n        ndim  = len(shape)\n    assert index<ndim, \"Index out of range\"\n    idxorder  = list(range(ndim))\n    idxorder.pop(index)\n    idxorder.append(index)\n    if type(data)==list:\n        datatrans = []\n        for d in data:\n            datatrans.append(d.transpose(idxorder))\n        shapetrans = datatrans[0].shape\n    else:\n        datatrans  = data.transpose(idxorder)\n        shapetrans = datatrans.shape\n    def func(x,param,fixedpar={\"datatrans\":datatrans}):\n        datatrans = fixedpar[\"datatrans\"]\n        if type(datatrans)==list:\n            answer = []\n            for dslice in datatrans:\n                for i in range(len(param)):\n                    dslice = dslice[param[i]]\n                answer.append(dslice)\n        else:\n            dslice = datatrans\n            for i in range(len(param)):\n                dslice = dslice[param[i]]\n            answer = dslice\n        answer = np.array(answer)\n        return answer\n    params=[]\n    for i in range(ndim-1):\n        params.append(np.arange(shapetrans[i]))\n    if x is None:\n        if idxvals is None:\n            x = np.arange(shapetrans[-1])\n        else:\n            x = np.array(idxvals[index])\n    if ymin is None:\n        if type(data)==list:\n            ymin = []\n            for d in data:\n                ymin.append(d.min())\n            ymin = np.array(ymin).min()\n        else:\n            ymin = data.min()\n    if ymax is None:\n        if type(data)==list:\n            ymax = []\n            for d in data:\n                ymax.append(d.max())\n            ymax = np.array(ymax).max()\n        else:\n            ymax = data.max()\n    if idxvals is not None:\n        paramsalt = []\n        for i in range(ndim-1):\n            paramsalt.append(idxvals[idxorder[i]])\n    else:\n        paramsalt = None\n    fig = None\n    ax  = None\n    if idxnames is None:\n        parnames = []\n        for i in range(ndim-1):\n            s = 'Parameter {}'.format(idxorder[i])\n            parnames.append(s)\n        xname    = 'Parameter {}'.format(index)\n    else:\n        parnames = []\n        for i in range(ndim-1):\n            parnames.append(idxnames[idxorder[i]]+\" =\")\n        xname    = idxnames[index]\n    fig = plt.figure()\n    ax  = plt.axes(xlim=(x.min(),x.max()),ylim=(ymin,ymax))\n    ax.set_xlabel(xname)\n    if ylabel is not None:\n        if type(ylabel)==list:\n            label = r''\n            glue  = ''\n            for l in ylabel:\n                label += glue+l\n                glue = ', '\n            ax.set_ylabel(label)\n        else:\n            ax.set_ylabel(ylabel)\n    if type(data)==list:\n        axmodel = []\n        if ylabel is None:\n            for i in range(len(datatrans)):\n                axm0,  = ax.plot(x,x,label='{}'.format(i))\n                axmodel.append(axm0)\n        else:\n            for i in range(len(datatrans)):\n                if (len(datatrans)>4 and i==0):\n                    axm0,  = ax.plot(x,x,'-',color='0.9',linewidth=5,label=ylabel[i])\n                elif (len(datatrans)>4 and i==1): \n                    axm0,  = ax.plot(x,x,'--',color='0.8',linewidth=2,label=ylabel[i])\n                elif (len(datatrans)>4 and i==2): \n                    axm0,  = ax.plot(x,x,'--',color='0.8',linewidth=2,label=ylabel[i])\n                elif (len(datatrans)>4 and i==3): \n                    axm0,  = ax.plot(x,x,':',color='0.6',linewidth=2,label=ylabel[i])\n                elif (len(datatrans)>4 and i==4): \n                    axm0,  = ax.plot(x,x,':',color='0.6',linewidth=2,label=ylabel[i])\n                else:\n                    axm0,  = ax.plot(x,x,label=ylabel[i])\n                axmodel.append(axm0)\n        ax.legend()\n    else:\n        axmodel = None\n    interactive_plot(x, func, params, ymin=ymin, ymax=ymax, parnames=parnames, parunits=None, fig=fig, ax=ax, axmodel=axmodel, parstart=None, iparstart=None, plotbutton=False, fixedpar=None, returnipar=False, block=False, paramsalt=paramsalt, altformat=idxformat)\n\ndef interactive_plot(x, func, params, ymin=None, ymax=None, parnames=None, parunits=None, fig=None, ax=None, axmodel=None, parstart=None, iparstart=None, plotbutton=False, fixedpar=None, returnipar=False, block=False, paramsalt=None, altformat='', **kwargs):\n    \"\"\"\n    For details about this function see https://github.com/dullemond/interactive_plot\n    \"\"\"\n    from matplotlib.widgets import Slider, Button, RadioButtons\n\n    # Compute spacing of plot, sliders and button\n    hslider  = 0.03\n    nslidrscl= 6\n    if(len(params)>nslidrscl):\n        hslider *= float(nslidrscl)/len(params)\n    dyslider = hslider*(4./3.)\n    xslider  = 0.3\n    wslider  = 0.3\n    hbutton  = 0.06\n    wbutton  = 0.15\n    xbutton  = 0.3\n    dybutton = hbutton+0.01\n    panelbot = 0.0\n    controlh = panelbot + len(params)*dyslider\n    if plotbutton: controlh += dybutton\n    controltop = panelbot + controlh\n    bmargin  = 0.15\n    \n    # generate figure\n    if fig is None: fig = plt.figure()\n    fig.subplots_adjust(top=0.95,bottom=controltop+bmargin)\n\n    # Set the initial values\n    indexinit = np.zeros(len(params),dtype=int)\n    if parstart is not None:\n        for i in range(len(params)):\n            if parstart[i] in params[i]:\n                idx = np.where(np.array(params[i])==parstart[i])[0]\n                if len(idx)>0:\n                    indexinit[i] = idx[0]\n            else:\n                if params[i][-1]>params[i][0]:\n                    idx = np.where(np.array(params[i])<parstart[i])[0]\n                    if len(idx)>0:\n                        indexinit[i] = idx[-1]\n                else:\n                    idx = np.where(np.array(params[i])>parstart[i])[0]\n                    if len(idx)>0:\n                        indexinit[i] = idx[0]\n    if iparstart is not None:\n        indexinit[:] = iparstart[:]\n\n    # select first image\n    par = []\n    for i in range(len(params)):\n        par.append(params[i][indexinit[i]])\n    if fixedpar is not None:\n        f = func(x,par,fixedpar=fixedpar)\n    else:\n        f = func(x,par)\n\n    # set range\n    if ymin is None: ymin = f.min()\n    if ymax is None: ymax = f.max()\n    \n    # display function(s)\n    if ax is None:      ax       = plt.axes(xlim=(x.min(),x.max()),ylim=(ymin,ymax))\n    if axmodel is None:\n        if len(f.shape)==1:\n            # Normal case: a single model function\n            axmodel, = ax.plot(x,f,**kwargs)\n        else:\n            # Special case: multiple model functions: f[imodel,:]\n            assert len(f.shape)==2, 'Model returns array with more than 2 dimensions. No idea what to do.'\n            axmodel = []\n            for i in range(f.shape[0]):\n                axm, = ax.plot(x,f[i,:],**kwargs)\n                axmodel.append(axm)\n            \n    sliders = []\n    for i in range(len(params)):\n    \n        # define slider\n        axcolor = 'lightgoldenrodyellow'\n        axs = fig.add_axes([xslider, controltop-i*dyslider, xslider+wslider, hslider], facecolor=axcolor)\n\n        if parnames is not None:\n            name = parnames[i]\n        else:\n            name = 'Parameter {0:d}'.format(i)\n\n        slider = Slider(axs, name, 0, len(params[i]) - 1,\n                    valinit=indexinit[i], valfmt='%i')\n        sliders.append(slider)\n\n    if plotbutton:\n        axb = fig.add_axes([xbutton, panelbot+0.2*hbutton, xbutton+wbutton, hbutton])\n        pbutton = Button(axb,'Plot')\n    else:\n        pbutton = None\n\n    class callbackplot(object):\n        def __init__(self,x,func,params,sliders,pbutton=None,fixedpar=None,ipar=None):\n            self.x        = x\n            self.func     = func\n            self.params   = params\n            self.sliders  = sliders\n            self.pbutton  = pbutton\n            self.fixedpar = fixedpar\n            self.parunits = parunits\n            self.paramsalt= paramsalt\n            self.altformat= altformat\n            self.closed   = False\n            if ipar is None:\n                self.ipar = np.zeros(len(sliders),dtype=int)\n            else:\n                self.ipar = ipar\n        def handle_close(self,event):\n            self.closed   = True\n        def myreadsliders(self):\n            for isl in range(len(self.sliders)):\n                ind = int(self.sliders[isl].val)\n                self.ipar[isl]=ind\n            par = []\n            for i in range(len(self.ipar)):\n                ip = self.ipar[i]\n                value = self.params[i][ip]\n                par.append(value)\n                name = self.sliders[i].label.get_text()\n                if '=' in name:\n                    namebase = name.split('=')[0]\n                    if self.paramsalt is not None:\n                        vls  = \"{0:\" + self.altformat + \"}\"\n                        name = namebase + \"= \" + vls.format(self.paramsalt[i][ip])\n                    else:\n                        if self.parunits is not None:\n                            valunit = self.parunits[i]\n                        else:\n                            valunit = 1.0\n                        name = namebase + \"= {0:13.6e}\".format(value/valunit)\n                    self.sliders[i].label.set_text(name)\n            return par\n        def myreplot(self,par):\n            x = self.x\n            if self.fixedpar is not None:\n                f = self.func(x,par,fixedpar=self.fixedpar)\n            else:\n                f = self.func(x,par)\n            if len(f.shape)==1:\n                axmodel.set_data(x,f)\n            else:\n                for i in range(f.shape[0]):\n                    axmodel[i].set_data(x,f[i,:])\n            plt.draw()\n        def mysupdate(self,event):\n            par = self.myreadsliders()\n            if self.pbutton is None: self.myreplot(par)\n        def mybupdate(self,event):\n            par = self.myreadsliders()\n            if self.pbutton is not None: self.pbutton.label.set_text('Computing...')\n            plt.pause(0.01)\n            self.myreplot(par)\n            if self.pbutton is not None: self.pbutton.label.set_text('Plot')\n\n    mcb = callbackplot(x,func,params,sliders,pbutton=pbutton,fixedpar=fixedpar,ipar=indexinit)\n\n    mcb.mybupdate(0)\n\n    if plotbutton:\n        pbutton.on_clicked(mcb.mybupdate)\n    for s in sliders:\n        s.on_changed(mcb.mysupdate)\n\n    fig._mycallback    = mcb\n\n    if block:\n        plt.show(block=True)\n    if returnipar:\n        return mcb.ipar\n        \n\ndef interactive_curve(t, func, params, xmin=None, xmax=None, ymin=None, ymax=None, parnames=None, parunits=None, fig=None, ax=None, axmodel=None, parstart=None, iparstart=None, plotbutton=False, fixedpar=None, returnipar=False, block=False, **kwargs):\n    \"\"\"\n    For details about this function see https://github.com/dullemond/interactive_plot\n    \"\"\"\n    from matplotlib.widgets import Slider, Button, RadioButtons\n\n    # Compute spacing of plot, sliders and button\n    hslider  = 0.03\n    nslidrscl= 6\n    if(len(params)>nslidrscl):\n        hslider *= float(nslidrscl)/len(params)\n    dyslider = hslider*(4./3.)\n    xslider  = 0.3\n    wslider  = 0.3\n    hbutton  = 0.06\n    wbutton  = 0.15\n    xbutton  = 0.3\n    dybutton = hbutton+0.01\n    panelbot = 0.0\n    controlh = panelbot + len(params)*dyslider\n    if plotbutton: controlh += dybutton\n    controltop = panelbot + controlh\n    bmargin  = 0.15\n    \n    # generate figure\n    if fig is None: fig = plt.figure()\n    fig.subplots_adjust(top=0.95,bottom=controltop+bmargin)\n\n    # Set the initial values\n    indexinit = np.zeros(len(params),dtype=int)\n    if parstart is not None:\n        for i in range(len(params)):\n            if parstart[i] in params[i]:\n                idx = np.where(np.array(params[i])==parstart[i])[0]\n                if len(idx)>0:\n                    indexinit[i] = idx[0]\n            else:\n                if params[i][-1]>params[i][0]:\n                    idx = np.where(np.array(params[i])<parstart[i])[0]\n                    if len(idx)>0:\n                        indexinit[i] = idx[-1]\n                else:\n                    idx = np.where(np.array(params[i])>parstart[i])[0]\n                    if len(idx)>0:\n                        indexinit[i] = idx[0]\n    if iparstart is not None:\n        indexinit[:] = iparstart[:]\n\n    # select first image\n    par = []\n    for i in range(len(params)):\n        par.append(params[i][indexinit[i]])\n    if fixedpar is not None:\n        x, y = func(t,par,fixedpar=fixedpar)\n    else:\n        x, y = func(t,par)\n\n    # set range\n    if xmin is None: xmin = x.min()\n    if xmax is None: xmax = x.max()\n    if ymin is None: ymin = y.min()\n    if ymax is None: ymax = y.max()\n    \n    # display function\n    if ax is None: ax   = plt.axes(xlim=(xmin,xmax),ylim=(ymin,ymax))\n    if axmodel is None:\n        if len(x.shape)==1:\n            # Normal case: a single model function\n            assert len(x.shape)==1, 'Cannot have multiple y and single x'\n            axmodel, = ax.plot(x,y,**kwargs)\n        else:\n            # Special case: multiple model functions: f[imodel,:]\n            assert len(x.shape)==2, 'Model returns array with more than 2 dimensions. No idea what to do.'\n            assert len(y.shape)==2, 'Cannot have multiple x and single y'\n            axmodel = []\n            for i in range(x.shape[0]):\n                axm, = ax.plot(x[i,:],y[i,:],**kwargs)\n                axmodel.append(axm)\n    \n    sliders = []\n    for i in range(len(params)):\n    \n        # define slider\n        axcolor = 'lightgoldenrodyellow'\n        axs = fig.add_axes([xslider, controltop-i*dyslider, xslider+wslider, hslider], facecolor=axcolor)\n\n        if parnames is not None:\n            name = parnames[i]\n        else:\n            name = 'Parameter {0:d}'.format(i)\n            \n        slider = Slider(axs, name, 0, len(params[i]) - 1,\n                    valinit=indexinit[i], valfmt='%i')\n        sliders.append(slider)\n\n    if plotbutton:\n        axb = fig.add_axes([xbutton, panelbot+0.2*hbutton, xbutton+wbutton, hbutton])\n        pbutton = Button(axb,'Plot')\n    else:\n        pbutton = None\n\n    class callbackcurve(object):\n        def __init__(self,t,func,params,sliders,pbutton=None,fixedpar=None,ipar=None):\n            self.t        = t\n            self.func     = func\n            self.params   = params\n            self.sliders  = sliders\n            self.pbutton  = pbutton\n            self.fixedpar = fixedpar\n            self.parunits = parunits\n            self.closed   = False\n            if ipar is None:\n                self.ipar = np.zeros(len(sliders),dtype=int)\n            else:\n                self.ipar = ipar\n        def handle_close(self,event):\n            self.closed   = True\n        def myreadsliders(self):\n            for isl in range(len(self.sliders)):\n                ind = int(self.sliders[isl].val)\n                self.ipar[isl]=ind\n            par = []\n            for i in range(len(self.ipar)):\n                ip = self.ipar[i]\n                value = self.params[i][ip]\n                par.append(value)\n                name = self.sliders[i].label.get_text()\n                if '=' in name:\n                    namebase = name.split('=')[0]\n                    if self.parunits is not None:\n                        valunit = self.parunits[i]\n                    else:\n                        valunit = 1.0\n                    name = namebase + \"= {0:13.6e}\".format(value/valunit)\n                    self.sliders[i].label.set_text(name)\n            return par\n        def myreplot(self,par):\n            t = self.t\n            if self.fixedpar is not None:\n                x,y = self.func(t,par,fixedpar=self.fixedpar)\n            else:\n                x,y = self.func(t,par)\n            if len(x.shape)==1:\n                axmodel.set_data(x,y)\n            else:\n                for i in range(x.shape[0]):\n                    axmodel[i].set_data(x[i,:],y[i,:])\n            plt.draw()\n        def mysupdate(self,event):\n            par = self.myreadsliders()\n            if self.pbutton is None: self.myreplot(par)\n        def mybupdate(self,event):\n            par = self.myreadsliders()\n            if self.pbutton is not None: self.pbutton.label.set_text('Computing...')\n            plt.pause(0.01)\n            self.myreplot(par)\n            if self.pbutton is not None: self.pbutton.label.set_text('Plot')\n\n    mcb = callbackcurve(t,func,params,sliders,pbutton=pbutton,fixedpar=fixedpar,ipar=indexinit)\n            \n    mcb.mybupdate(0)\n        \n    if plotbutton:\n        pbutton.on_clicked(mcb.mybupdate)\n    for s in sliders:\n        s.on_changed(mcb.mysupdate)\n\n    fig._mycallback    = mcb\n    \n    if block:\n        plt.show(block=True)\n    if returnipar:\n        return mcb.ipar\n\ndef bplanck(temp,nu):\n    \"\"\"\n----------------------------------------------------------------------------\n                THE BLACKBODY PLANCK FUNCTION B_nu(T)\n\n     This function computes the Blackbody function \n\n                    2 h nu^3 / c^2\n        B_nu(T)  = ------------------    [ erg / cm^2 s ster Hz ]\n                   exp(h nu / kT) - 1\n\n     ARGUMENTS:\n        nu    [Hz]            = Frequency (may be an array)\n        temp  [K]             = Temperature\n----------------------------------------------------------------------------\n    \"\"\"\n    if (temp == 0.e0): return nu*0.e0\n    bplanck = 1.47455e-47 * nu**3 /  (np.exp(4.7989e-11 * nu / temp)-1.e0) + 1.e-290\n    return bplanck\n\ndef bplanckdt(temp,nu):\n    \"\"\"\n----------------------------------------------------------------------------\n           THE TEMPERATURE DERIVATIVE OF PLANCK FUNCTION \n     \n      This function computes the temperature derivative of the\n      Blackbody function \n      \n         dB_nu(T)     2 h^2 nu^4      exp(h nu / kT)        1 \n         --------   = ---------- ------------------------  ---\n            dT          k c^2    [ exp(h nu / kT) - 1 ]^2  T^2\n     \n      ARGUMENTS:\n         nu    [Hz]            = Frequency (may be an array)\n         temp  [K]             = Temperature\n----------------------------------------------------------------------------\n    \"\"\"\n    bplanckdt = np.zeros(len(nu))\n    exponent = 4.7989e-11*nu/temp\n    mask = (exponent <= 76.)\n    bplanckdt[mask] = 7.07661334104e-58 * nu[mask]**4 * np.exp(exponent[mask]) /  \\\n        ( (np.exp(exponent[mask])-1.e0)**2 * temp**2 ) + 1.e-290\n    mask = (exponent > 76.)\n    bplanckdt[mask] = 7.07661334104e-58 * nu[mask]**4 /  \\\n            ( np.exp(exponent[mask]) * temp**2 ) + 1.e-290\n    return bplanckdt\n", "meta": {"hexsha": "2ba698fce8d3beeb05851883f26b35f8a6c87995", "size": 62337, "ext": "py", "lang": "Python", "max_stars_repo_path": "AA_INGESTED/Fabian2001/optool.py", "max_stars_repo_name": "cdominik/optool-additional-refind-data", "max_stars_repo_head_hexsha": "e6d4f09a4300ff524a746b86df8885e490051805", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-27T07:25:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T13:10:47.000Z", "max_issues_repo_path": "AA_INGESTED/Fabian2001/optool.py", "max_issues_repo_name": "cdominik/optool-additional-refind-data", "max_issues_repo_head_hexsha": "e6d4f09a4300ff524a746b86df8885e490051805", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AA_INGESTED/Fabian2001/optool.py", "max_forks_repo_name": "cdominik/optool-additional-refind-data", "max_forks_repo_head_hexsha": "e6d4f09a4300ff524a746b86df8885e490051805", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-13T12:45:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T12:45:10.000Z", "avg_line_length": 37.0172209026, "max_line_length": 263, "alphanum_fraction": 0.5172048703, "include": true, "reason": "import numpy,from scipy", "num_tokens": 16687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.2909808662149067, "lm_q1q2_score": 0.17681835552487077}}
{"text": "#!/usr/bin/env python\n# Filename: dem_difference.py \n\"\"\"\nintroduction: conduct DEM difference\n\nauthors: Huang Lingcao\nemail:huanglingcao@gmail.com\nadd time: 27 February, 2021\n\"\"\"\nimport os,sys\nfrom optparse import OptionParser\n\ndeeplabforRS =  os.path.expanduser('~/codes/PycharmProjects/DeeplabforRS')\nsys.path.insert(0, deeplabforRS)\nimport vector_gpd\nimport basic_src.timeTools as timeTools\nimport raster_io\nimport basic_src.basic as basic\nimport basic_src.io_function as io_function\nimport basic_src.map_projection as map_projection\nimport split_image\n\nimport numpy as np\nfrom itertools import combinations\nimport operator\n\nfrom dem_mosaic_crop import subset_image_by_polygon_box\nfrom dem_mosaic_crop import group_demTif_yearmonthDay\n\nimport multiprocessing\nfrom multiprocessing import Pool\n\ndef read_date_dem_to_memory(pair_idx, pair, date_pair_list_sorted,dem_data_dict, dem_groups_date, less_memory=False,boundary=None):\n\n    if less_memory is False:\n        # read data to memory if need, then store in memory, avoid to read them again.\n        # for a large area, because we read all raster to memory, it will cause \"out of memory problem\"\n        if pair[0] not in dem_data_dict.keys():\n            data_old, nodata_old = raster_io.read_raster_one_band_np(dem_groups_date[pair[0]][0],boundary=boundary)\n            data_old[data_old == nodata_old] = np.nan\n            dem_data_dict[pair[0]] = data_old\n        else:\n            data_old = dem_data_dict[pair[0]]\n\n        # read data to memory if need\n        if pair[1] not in dem_data_dict.keys():\n            data_new, nodata_new = raster_io.read_raster_one_band_np(dem_groups_date[pair[1]][0],boundary=boundary)\n            data_new[data_new == nodata_new] = np.nan\n            dem_data_dict[pair[1]] = data_new\n        else:\n            data_new = dem_data_dict[pair[1]]\n    else:\n        # if we don't have enough memory, don't store the all DEM data in memory, only read two needed.\n        # wil increase reading operation from disk\n        data_old, nodata_old = raster_io.read_raster_one_band_np(dem_groups_date[pair[0]][0],boundary=boundary)\n        data_new, nodata_new = raster_io.read_raster_one_band_np(dem_groups_date[pair[1]][0],boundary=boundary)\n\n        # replace nodata with nan\n        data_old[ data_old == nodata_old ] = np.nan\n        data_new[ data_new == nodata_new ] = np.nan\n\n    # release some memory if we can (NO)\n\n    return data_old, data_new\n\ndef dem_diff_new_old_min_neg_diff_patch(idx, patch, patch_count,date_pair_list_sorted,dem_groups_date):\n    # conduct difference by keep the maximum subsidence (negative values)\n    print('tile: %d / %d' % (idx + 1, patch_count))\n\n    patch_w = patch[2]\n    patch_h = patch[3]\n    patch_date_diff = np.zeros((patch_h, patch_w), dtype=np.uint16)\n    patch_dem_diff = np.empty((patch_h, patch_w), dtype=np.float32)\n    patch_dem_diff[:] = 9999  # positive 9999\n\n    # use dict to read data from disk (only need)\n    dem_data_dict = {}\n    for p_idx, pair in enumerate(date_pair_list_sorted):\n        diff_days = (pair[1] - pair[0]).days\n\n        data_old, data_new = read_date_dem_to_memory(p_idx, pair, date_pair_list_sorted, dem_data_dict, dem_groups_date,\n                                                     boundary=patch)\n        diff_two = data_new - data_old\n\n        # fill the element\n        new_ele = np.where(diff_two < patch_dem_diff )   # keep the negative values\n\n        patch_dem_diff[new_ele] = diff_two[new_ele]\n        patch_date_diff[new_ele] = diff_days\n\n    # for locations where valid value\n    patch_dem_diff[patch_dem_diff == 9999] = np.nan\n\n    return patch, patch_dem_diff, patch_date_diff\n\n\ndef dem_diff_newest_oldest_a_patch(idx, patch, patch_count,date_pair_list_sorted,dem_groups_date):\n    print('tile: %d / %d' % (idx + 1, patch_count))\n\n    patch_w = patch[2]\n    patch_h = patch[3]\n    patch_date_diff = np.zeros((patch_h, patch_w), dtype=np.uint16)\n    patch_old_date_idx = np.empty((patch_h, patch_w), dtype=np.uint8)\n    patch_new_date_idx = np.empty((patch_h, patch_w), dtype=np.uint8)\n    patch_old_date_idx[:] = 255\n    patch_new_date_idx[:] = 255\n\n    patch_dem_diff = np.empty((patch_h, patch_w), dtype=np.float32)\n    patch_dem_diff[:] = np.nan\n\n    date_list = [item for item in dem_groups_date.keys()]\n\n    # use dict to read data from disk (only need)\n    dem_data_dict = {}\n    for p_idx, pair in enumerate(date_pair_list_sorted):\n        diff_days = (pair[1] - pair[0]).days\n        # basic.outputlogMessage('Getting DEM difference using the one on %s and %s, total day diff: %d' %\n        #                        (timeTools.date2str(pair[1]), timeTools.date2str(pair[0]), diff_days))\n        # print(pair,':',(pair[1] - pair[0]).days)\n\n        data_old, data_new = read_date_dem_to_memory(p_idx, pair, date_pair_list_sorted, dem_data_dict, dem_groups_date,\n                                                     boundary=patch)\n\n        # print('data_old shape:',data_old.shape)\n        # print('data_new shape:',data_new.shape)\n\n        diff_two = data_new - data_old\n        # print(diff_two)\n\n        # fill the element\n        new_ele = np.where(np.logical_and(np.isnan(patch_dem_diff), ~np.isnan(diff_two)))\n\n        patch_dem_diff[new_ele] = diff_two[new_ele]\n        patch_date_diff[new_ele] = diff_days\n        # output the index of dates\n        patch_old_date_idx[new_ele] = date_list.index(pair[0])\n        patch_new_date_idx[new_ele] = date_list.index(pair[1])\n\n        # check if all have been filled ( nan pixels)\n        diff_remain_hole = np.where(np.isnan(patch_dem_diff))\n        # basic.outputlogMessage(' remain %.4f percent pixels need to be filled'% (100.0*diff_remain_hole[0].size/patch_dem_diff.size) )\n        if diff_remain_hole[0].size < 1:\n            break\n\n    return patch,patch_dem_diff,patch_date_diff, patch_old_date_idx,patch_new_date_idx\n\ndef dem_diff_newest_oldest(dem_tif_list, out_dem_diff, out_date_diff, process_num, b_max_subsidence=False,b_save_cm=False):\n    '''\n    get DEM difference, for each pixel, newest vaild value - oldest valid value\n    :param dem_list:\n    :param output:\n    :return:\n    '''\n    if len(dem_tif_list) < 2:\n        basic.outputlogMessage('error, the count of DEM is smaller than 2')\n        return False\n\n\n    # groups DEM with original images acquired at the same year months\n    dem_groups_date = group_demTif_yearmonthDay(dem_tif_list,diff_days=0)\n    # sort based on yeardate in accending order : operator.itemgetter(0)\n    dem_groups_date = dict(sorted(dem_groups_date.items(), key=operator.itemgetter(0)))\n    txt_save_path = os.path.splitext(out_date_diff)[0]+'.txt'\n\n    # change the key to integer number after sorting and save to txt file\n    dem_groups_date_sort_idx = {}\n    for idx, key in enumerate(dem_groups_date.keys()):\n        dem_groups_date_sort_idx[idx] = dem_groups_date[key]\n    io_function.save_dict_to_txt_json(txt_save_path,dem_groups_date_sort_idx)\n\n    date_list = list(dem_groups_date.keys())\n    dem_tif_list = [ dem_groups_date[key][0] for key in dem_groups_date.keys()]  # each date, only have one tif\n    tif_obj_list = [ raster_io.open_raster_read(tif) for tif in dem_tif_list]\n\n\n    height, width, _ = raster_io.get_width_heigth_bandnum(tif_obj_list[0])\n\n    # check them have the width and height\n    for tif, obj in zip(dem_tif_list[1:],tif_obj_list[1:]):\n        h, w, _ = raster_io.get_width_heigth_bandnum(obj)\n        if h!=height or w!=width:\n            raise ValueError('the height and width of %s is different from others'%tif)\n\n    # divide the image the many small patches, then calcuate one by one, solving memory issues.\n    image_patches = split_image.sliding_window(width,height, 1024, 1024,adj_overlay_x=0,adj_overlay_y=0)\n    patch_count = len(image_patches)\n    tif_obj_list = None\n\n    # read all and their date\n    date_pair_list = list(combinations(date_list, 2))\n    date_diff_list = [ (item[1] - item[0]).days for item in date_pair_list ]\n    # sort based on day difference (from max to min)\n    date_pair_list_sorted = [x for _, x in sorted(zip(date_diff_list, date_pair_list),reverse=True)]    # descending\n\n\n    # get the difference\n    date_diff_np = np.zeros((height, width),dtype=np.uint16)\n    old_date_index = np.zeros((height, width),dtype=np.uint8)\n    new_date_index = np.zeros((height, width),dtype=np.uint8)\n    dem_diff_np = np.empty((height, width),dtype=np.float32)\n    dem_diff_np[:] = np.nan\n\n    if process_num == 1:\n        for idx, patch in enumerate(image_patches):\n            _,patch_dem_diff,patch_date_diff, patch_old_date_idx,patch_new_date_idx = \\\n                dem_diff_newest_oldest_a_patch(idx, patch, patch_count,date_pair_list_sorted,dem_groups_date)\n            # copy to the entire image\n            row_s = patch[1]\n            row_e = patch[1] + patch[3]\n            col_s = patch[0]\n            col_e = patch[0] + patch[2]\n            dem_diff_np[row_s:row_e, col_s:col_e] = patch_dem_diff\n            date_diff_np[row_s:row_e, col_s:col_e] = patch_date_diff\n            old_date_index[row_s:row_e, col_s:col_e] = patch_old_date_idx\n            new_date_index[row_s:row_e, col_s:col_e] = patch_new_date_idx\n    else:\n        theadPool = Pool(process_num)\n        parameters_list = [ (idx, patch, patch_count,date_pair_list_sorted,dem_groups_date) for idx, patch in enumerate(image_patches)]\n        if b_max_subsidence is False:\n            results = theadPool.starmap(dem_diff_newest_oldest_a_patch, parameters_list)\n        else:\n            results = theadPool.starmap(dem_diff_new_old_min_neg_diff_patch , parameters_list)\n        for res in results:\n            patch, patch_dem_diff, patch_date_diff,patch_old_date_idx,patch_new_date_idx = res\n            # copy to the entire image\n            row_s = patch[1]\n            row_e = patch[1] + patch[3]\n            col_s = patch[0]\n            col_e = patch[0] + patch[2]\n            dem_diff_np[row_s:row_e, col_s:col_e] = patch_dem_diff\n            date_diff_np[row_s:row_e, col_s:col_e] = patch_date_diff\n            old_date_index[row_s:row_e, col_s:col_e] = patch_old_date_idx\n            new_date_index[row_s:row_e, col_s:col_e] = patch_new_date_idx\n\n    # save date diff to tif (16 bit)\n    raster_io.save_numpy_array_to_rasterfile(date_diff_np,out_date_diff,dem_tif_list[0], nodata=0,compress='lzw',tiled='yes',bigtiff='if_safer')\n    # save old and new date index to tif (8 bit)\n    out_old_date_idx = io_function.get_name_by_adding_tail(out_date_diff,'oldIndex')\n    out_new_date_idx = io_function.get_name_by_adding_tail(out_date_diff,'newIndex')\n    raster_io.save_numpy_array_to_rasterfile(old_date_index,out_old_date_idx,dem_tif_list[0], nodata=255,compress='lzw',tiled='yes',bigtiff='if_safer')\n    raster_io.save_numpy_array_to_rasterfile(new_date_index,out_new_date_idx,dem_tif_list[0], nodata=255,compress='lzw',tiled='yes',bigtiff='if_safer')\n\n    # # stretch the DEM difference, save to 8 bit.\n    # dem_diff_np_8bit = raster_io.image_numpy_to_8bit(dem_diff_np,10,-10,dst_nodata=0)\n    # out_dem_diff_8bit = io_function.get_name_by_adding_tail(out_dem_diff, '8bit')\n    # raster_io.save_numpy_array_to_rasterfile(dem_diff_np_8bit, out_dem_diff_8bit, dem_tif_list[0], nodata=0)\n\n\n    # if possible, save to 16 bit, to save the disk storage.\n    # dem_diff_np[0:5,0] = -500\n    # dem_diff_np[0,0:5] = 500\n    # print(np.nanmin(dem_diff_np))\n    # print(np.nanmax(dem_diff_np))\n\n    # if np.nanmin(dem_diff_np_cm) < range.min or np.nanmax(dem_diff_np_cm) > range.max:\n    # save dem diff to files (float), meter\n    if b_save_cm is False:\n        raster_io.save_numpy_array_to_rasterfile(dem_diff_np,out_dem_diff,dem_tif_list[0],nodata=-9999,compress='lzw',tiled='yes',bigtiff='if_safer')\n    else:\n        # save dem diff to 16bit, centimeter, only handle diff from -327.67 to 327.67 meters\n        bit16_nodata = 32767\n        range = np.iinfo(np.int16)\n        dem_diff_np_cm = dem_diff_np*100\n        dem_diff_np_cm[dem_diff_np_cm < range.min] = range.min\n        dem_diff_np_cm[dem_diff_np_cm > range.max] = range.max\n        dem_diff_np_cm[np.isnan(dem_diff_np_cm)] = bit16_nodata  # set the nodata for int16\n        dem_diff_np_cm = dem_diff_np_cm.astype(np.int16)        # save to int16\n        out_dem_diff_cm = out_dem_diff\n        basic.outputlogMessage('note, save DEM difference (%s) to centimeter, int16, range: -327.68 to 327.67 m'%os.path.basename(out_dem_diff_cm))\n        raster_io.save_numpy_array_to_rasterfile(dem_diff_np_cm, out_dem_diff_cm, dem_tif_list[0],nodata=bit16_nodata,compress='lzw',tiled='yes',bigtiff='if_safer')\n\n\n    return True\n\ndef check_dem_diff_results(save_dir,pre_name,extent_id):\n\n    save_dem_diff = os.path.join(save_dir, pre_name + '_DEM_diff_sub_%d.tif' % extent_id)\n    save_date_diff = os.path.join(save_dir, pre_name + '_date_diff_sub_%d.tif' % extent_id)\n\n    if os.path.isfile(save_dem_diff) and os.path.isfile(save_date_diff):\n        basic.outputlogMessage('warning, DEM difference already exist, skipping create new ones')\n        return True\n\n    out_dem_diff_cm = io_function.get_name_by_adding_tail(save_dem_diff, 'cm')\n    if os.path.isfile(out_dem_diff_cm):\n        basic.outputlogMessage('warning, DEM difference already exist, skipping create new ones')\n        return True\n\n    return False\n\ndef crop_to_same_exent_for_diff(dem_tif_list, save_dir, extent_id, extent_poly,process_num):\n    # crop to the same extent\n    crop_tif_dir = os.path.join(save_dir, 'dem_crop_for_diff_sub_%d' % extent_id)\n    if os.path.isdir(crop_tif_dir) is False:\n        io_function.mkdir(crop_tif_dir)\n    crop_tif_list = []\n    for tif in dem_tif_list:\n        save_crop_path = os.path.join(crop_tif_dir, os.path.basename(io_function.get_name_by_adding_tail(tif, 'sub_poly_%d' % extent_id)) )\n        if os.path.isfile(save_crop_path):\n            basic.outputlogMessage('%s exists, skip cropping' % save_crop_path)\n            crop_tif_list.append(save_crop_path)\n        else:\n            crop_tif = subset_image_by_polygon_box(tif, save_crop_path, extent_poly, resample_m='near',\n                                                     same_extent=True,thread_num=process_num)\n            if crop_tif is False:\n                # raise ValueError('warning, crop %s failed' % tif)\n                continue\n            crop_tif_list.append(crop_tif)\n    dem_tif_list = crop_tif_list\n\n    return dem_tif_list\n\ndef main(options, args):\n\n    save_dir = options.save_dir\n    extent_shp = options.extent_shp\n    process_num = options.process_num\n\n    dem_dir_or_txt = args[0]\n    if os.path.isfile(dem_dir_or_txt):\n        dem_list = io_function.read_list_from_txt(dem_dir_or_txt)\n    else:\n        dem_list = io_function.get_file_list_by_ext('.tif', dem_dir_or_txt, bsub_folder=False)\n    dem_count = len(dem_list)\n    if dem_count < 1:\n        raise ValueError('No input dem files in %s' % dem_dir_or_txt)\n\n    if extent_shp is not None:\n        pre_name = os.path.splitext(os.path.basename(extent_shp))[0]\n    else:\n        pre_name = os.path.basename(os.path.abspath(save_dir))\n    save_dem_diff = os.path.join(save_dir, pre_name + '_DEM_diff.tif')\n    save_date_diff = os.path.join(save_dir, pre_name + '_date_diff.tif')\n    if os.path.isfile(save_dem_diff) and os.path.isfile(save_date_diff):\n        print('%s and %s exists, skip'%(save_dem_diff, save_date_diff))\n        return\n\n    if extent_shp is not None:\n        # crop the DEM before differencing\n        extent_shp_base = os.path.splitext(os.path.basename(extent_shp))[0]\n        dem_prj = map_projection.get_raster_or_vector_srs_info_epsg(dem_list[0])\n        extent_prj = map_projection.get_raster_or_vector_srs_info_epsg(extent_shp)\n        if dem_prj != extent_prj:\n            raise ValueError('The projection of extent file (%s) and dem tifs is different'%extent_shp)\n\n        extent_polys = vector_gpd.read_polygons_gpd(extent_shp)\n        if len(extent_polys) != 1:\n            raise ValueError('Only allow one polygon in %s' % extent_shp)\n\n        extPolys_ids = vector_gpd.read_attribute_values_list(extent_shp, 'id')\n        if extPolys_ids is None or None in extPolys_ids:\n            basic.outputlogMessage('Warning, field: id is not in %s, will create default ID for each grid' % extent_shp)\n            extPolys_ids = [id + 1 for id in range(len(extent_polys))]\n\n        # crop\n        for idx, ext_poly in zip(extPolys_ids, extent_polys):\n            basic.outputlogMessage('crop and differnce DEM for the %d th extent (%d in total)' % (idx, len(extent_polys)))\n            crop_dem_list = crop_to_same_exent_for_diff(dem_list, save_dir, idx, ext_poly, process_num)\n\n            dem_list = crop_dem_list\n\n    dem_diff_newest_oldest(dem_list, save_dem_diff, save_date_diff,process_num, b_max_subsidence=options.max_subsidence)\n\n\n\nif __name__ == '__main__':\n    usage = \"usage: %prog [options] dem_tif_dir or dem_list_txt \"\n    parser = OptionParser(usage=usage, version=\"1.0 2020-12-26\")\n    parser.description = 'Introduction: difference for multi-temporal DEM '\n\n    parser.add_option(\"-d\", \"--save_dir\",\n                      action=\"store\", dest=\"save_dir\",default='./',\n                      help=\"the folder to save pre-processed results\")\n\n    parser.add_option(\"\", \"--process_num\",\n                      action=\"store\", dest=\"process_num\", type=int, default=4,\n                      help=\"number of processes to create the mosaic\")\n\n    parser.add_option(\"-e\", \"--extent_shp\",\n                      action=\"store\", dest=\"extent_shp\",\n                      help=\"the extent file for cropping\")\n\n    parser.add_option(\"-m\", \"--max_subsidence\",\n                      action=\"store_true\", dest=\"max_subsidence\",default=False,\n                      help=\"for each pixel, keep the maximum elevation reduction values\")\n\n\n    (options, args) = parser.parse_args()\n    # print(options.create_mosaic)\n\n    if len(sys.argv) < 2 or len(args) < 1:\n        parser.print_help()\n        sys.exit(2)\n\n    main(options, args)\n\n    pass\n\n", "meta": {"hexsha": "7409180c4e21af07147ce0a95d8b7bd39de0f0c6", "size": 17973, "ext": "py", "lang": "Python", "max_stars_repo_path": "DEMscripts/dem_difference.py", "max_stars_repo_name": "yghlc/rs_img_proc", "max_stars_repo_head_hexsha": "2f704b0c6ac456b6893142f1900c732ea2b8c637", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DEMscripts/dem_difference.py", "max_issues_repo_name": "yghlc/rs_img_proc", "max_issues_repo_head_hexsha": "2f704b0c6ac456b6893142f1900c732ea2b8c637", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DEMscripts/dem_difference.py", "max_forks_repo_name": "yghlc/rs_img_proc", "max_forks_repo_head_hexsha": "2f704b0c6ac456b6893142f1900c732ea2b8c637", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.045112782, "max_line_length": 164, "alphanum_fraction": 0.6912034719, "include": true, "reason": "import numpy", "num_tokens": 4704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.1766465795617825}}
{"text": "#!/usr/bin/env python\n\"\"\"\nImplements LDpred, an approximate Gibbs sampler that calculate posterior means of effects, conditional on LD information.\nThe method requires the user to have generated a coordinated dataset using coord_genotypes.py\n\n\nUsage:\nldpred --coord=COORD_DATA_FILE  --ld_radius=LD_RADIUS   --local_ld_file_prefix=LD_FILE_NAME  --PS=FRACTIONS_CAUSAL\n                          --N=SAMPLE_SIZE  --out=OUTPUT_FILE_PREFIX  [ --num_iter=NUM_ITER  --H2=HERTIABILITY  --gm_ld_radius=GEN_MAP_RADIUS]\n\n - COORD_DATA_FILE: The HDF4 file obtained by running the coord_genotypes.py\n\n - LD_RADIUS: An integer number which denotes the number of SNPs on each side of the focal SNP for which LD should be adjusted.\n              A value corresponding M/3000, where M is the number of SNPs in the genome is recommended.\n\n - LD_FILE_NAME: A path and filename prefix for the LD file.  If it doesn't exist, it will be generated.  This can take up to several hours,\n                 depending on LD radius number of SNPs, etc.  If it does exits, that file will be used.\n\n - FRACTIONS_CAUSAL: A list of comma separated (without space) values between 1 and 0, excluding 0.  1 corresponds to the infinitesimal model and will yield results\n                     similar to LDpred-inf.  Default is --PS=1,0.3,0.1,0.03,0.01,0.003,0.001,0.0003,0.0001\n\n - N: This is the sample size which LDpred assumes was used to calculate the GWAS summary statistics.\n\n - OUTPUT_FILE_PREFIX:  The prefix of output file.\n\n - NUM_ITER (optional): The number of iterations used by the Gibbs sampler. The default is 60, and burn-in is fixed to 5.\n\n - HERTIABILITY (optional): The heritability assumed by LDpred.  By default it estimates the heritability from the GWAS summary statistics.\n\n - GEN_MAP_RADIUS (optional):  If this option is set, then a genetic map will be used to calculate LD-radius.  A value around 1 is arguably reasonable.\n\n\n 2015 (c) Bjarni J Vilhjalmsson: bjarni.vilhjalmsson@gmail.com\n\n \"\"\"\n\nimport cPickle\nimport getopt\nimport gzip\nimport os\nimport sys\nimport time\n\nfrom scipy import stats\nimport h5py\n\nimport LDpred_inf\nimport itertools as it\nimport ld\nimport scipy as sp\n\nfrom coord_genotypes import chromosomes_list\nimport util\n\n\n__version__ = '0.9.1'\n\ndef parse_parameters():\n    \"\"\"\n    Parse the parameters into a dict, etc.\n    \"\"\"\n\n    long_options_list = ['coord=', 'ld_radius=', 'local_ld_file_prefix=', 'PS=', 'out=', 'N=',\n                         'num_iter=', 'H2=', 'gm_ld_radius=', 'h', 'help']\n\n    p_dict = {'coord':None, 'ld_radius':None, 'local_ld_file_prefix':None, 'PS':[1, 0.3, 0.1, 0.03, 0.01, 0.003, 0.001], 'out':None,\n              'N':None, 'num_iter': 60, 'H2':None, 'gm':None, 'gm_ld_radius':None}\n\n    if len(sys.argv) > 1:\n        try:\n            opts, args = getopt.getopt(sys.argv[1:], \"h\", long_options_list)\n\n        except:\n            print \"Some problems with parameters.  Please read the usage documentation carefully.\"\n            print \"Use the -h option for usage information.\"\n            sys.exit(2)\n\n        for opt, arg in opts:\n            if opt == \"-h\" or opt == \"--h\" or opt == '--help':\n                print __doc__\n                sys.exit(0)\n            elif opt == \"--coord\": p_dict['coord'] = arg\n            elif opt == \"--ld_radius\": p_dict['ld_radius'] = int(arg)\n            elif opt == \"--local_ld_file_prefix\": p_dict['local_ld_file_prefix'] = arg\n            elif opt == \"--PS\": p_dict['PS'] = map(float, arg.split(','))\n            elif opt == \"--out\": p_dict['out'] = arg\n            elif opt == \"--N\": p_dict['N'] = int(arg)\n            elif opt == \"--num_iter\": p_dict['num_iter'] = int(arg)\n            elif opt == \"--H2\": p_dict['H2'] = float(arg)\n            elif opt == \"--gm_ld_radius\": p_dict['gm_ld_radius'] = float(arg)\n            else:\n                print \"Unkown option:\", opt\n                print \"Use -h option for usage information.\"\n                sys.exit(2)\n    else:\n        print __doc__\n        sys.exit(0)\n    return p_dict\n\n\n\n\n\ndef ldpred_genomewide(data_file=None, ld_radius=None, ld_dict=None, out_file_prefix=None, ps=None,\n               n=None, h2=None, num_iter=None, verbose=False, zero_jump_prob=0.05, burn_in=5):\n    \"\"\"\n    Calculate LDpred for a genome\n    \"\"\"\n\n    df = h5py.File(data_file, 'r')\n    has_phenotypes = False\n    if 'y' in df.keys():\n        'Validation phenotypes found.'\n        y = df['y'][...]  # Phenotype\n        num_individs = len(y)\n        risk_scores_pval_derived = sp.zeros(num_individs)\n        has_phenotypes = True\n\n    ld_scores_dict = ld_dict['ld_scores_dict']\n    chrom_ld_dict = ld_dict['chrom_ld_dict']\n    chrom_ref_ld_mats = ld_dict['chrom_ref_ld_mats']\n\n    print 'Applying LDpred with LD radius: %d' % ld_radius\n    results_dict = {}\n    num_snps = 0\n    sum_beta2s = 0\n    cord_data_g = df['cord_data']\n\n    for chrom_str in chromosomes_list:\n        if chrom_str in cord_data_g.keys():\n            g = cord_data_g[chrom_str]\n            betas = g['betas'][...]\n            n_snps = len(betas)\n            num_snps += n_snps\n            sum_beta2s += sp.sum(betas ** 2)\n\n    L = ld_scores_dict['avg_gw_ld_score']\n    chi_square_lambda = sp.mean(n * sum_beta2s / float(num_snps))\n    print 'Genome-wide lambda inflation:', chi_square_lambda,\n    print 'Genome-wide mean LD score:', L\n    gw_h2_ld_score_est = max(0.0001, (max(1, chi_square_lambda) - 1) / (n * (L / num_snps)))\n    print 'Estimated genome-wide heritability:', gw_h2_ld_score_est\n\n    assert chi_square_lambda > 1, 'Something is wrong with the GWAS summary statistics.  Perhaps there were issues parsing of them, or the given GWAS sample size (N) was too small. Either way, lambda (the mean Chi-square statistic) is too small.  '\n\n    LDpred_inf_chrom_dict = {}\n    print 'Calculating LDpred-inf weights'\n    for chrom_str in chromosomes_list:\n        if chrom_str in cord_data_g.keys():\n            print 'Calculating scores for Chromosome %s' % ((chrom_str.split('_'))[1])\n            g = cord_data_g[chrom_str]\n\n            # Filter monomorphic SNPs\n            snp_stds = g['snp_stds_ref'][...]\n            snp_stds = snp_stds.flatten()\n            ok_snps_filter = snp_stds > 0\n            pval_derived_betas = g['betas'][...]\n            n_snps = len(pval_derived_betas)\n            pval_derived_betas = pval_derived_betas[ok_snps_filter]\n            if h2 is not None:\n                h2_chrom = h2 * (n_snps / float(num_snps))\n            else:\n                h2_chrom = gw_h2_ld_score_est * (n_snps / float(num_snps))\n            start_betas = LDpred_inf.ldpred_inf(pval_derived_betas, genotypes=None, reference_ld_mats=chrom_ref_ld_mats[chrom_str],\n                                                h2=h2_chrom, n=n, ld_window_size=2 * ld_radius, verbose=False)\n            LDpred_inf_chrom_dict[chrom_str] = start_betas\n\n\n    for p in ps:\n        print 'Starting LDpred with p=%0.4f' % p\n        p_str = '%0.4f' % p\n        results_dict[p_str] = {}\n\n        if out_file_prefix:\n            # Preparing output files\n            raw_effect_sizes = []\n            ldpred_effect_sizes = []\n            ldpred_inf_effect_sizes = []\n            out_sids = []\n            chromosomes = []\n            out_positions = []\n            out_nts = []\n\n        for chrom_str in chromosomes_list:\n            if chrom_str in cord_data_g.keys():\n                g = cord_data_g[chrom_str]\n                if has_phenotypes:\n                    if 'raw_snps_val' in g.keys():\n                        raw_snps = g['raw_snps_val'][...]\n                    else:\n                        raw_snps = g['raw_snps_ref'][...]\n\n                # Filter monomorphic SNPs\n                snp_stds = g['snp_stds_ref'][...]\n                snp_stds = snp_stds.flatten()\n                ok_snps_filter = snp_stds > 0\n                snp_stds = snp_stds[ok_snps_filter]\n                pval_derived_betas = g['betas'][...]\n                pval_derived_betas = pval_derived_betas[ok_snps_filter]\n                positions = g['positions'][...]\n                positions = positions[ok_snps_filter]\n                sids = g['sids'][...]\n                sids = sids[ok_snps_filter]\n                log_odds = g['log_odds'][...]\n                log_odds = log_odds[ok_snps_filter]\n                nts = g['nts'][...]\n                nts = nts[ok_snps_filter]\n\n\n                if out_file_prefix:\n                    chromosomes.extend([chrom_str] * len(pval_derived_betas))\n                    out_positions.extend(positions)\n                    out_sids.extend(sids)\n                    raw_effect_sizes.extend(log_odds)\n                    out_nts.extend(nts)\n\n                n_snps = len(pval_derived_betas)\n\n                if h2 is not None:\n                    h2_chrom = h2 * (n_snps / float(num_snps))\n                else:\n                    h2_chrom = gw_h2_ld_score_est * (n_snps / float(num_snps))\n                if 'chrom_ld_boundaries' in ld_dict.keys():\n                    ld_boundaries = ld_dict['chrom_ld_boundaries'][chrom_str]\n                    res_dict = ldpred_gibbs(pval_derived_betas, h2=h2_chrom, n=n, p=p, ld_radius=ld_radius,\n                                            verbose=verbose, num_iter=num_iter, burn_in=burn_in, ld_dict=chrom_ld_dict[chrom_str],\n                                            start_betas=LDpred_inf_chrom_dict[chrom_str], ld_boundaries=ld_boundaries,\n                                            zero_jump_prob=zero_jump_prob)\n                else:\n                    res_dict = ldpred_gibbs(pval_derived_betas, h2=h2_chrom, n=n, p=p, ld_radius=ld_radius,\n                                            verbose=verbose, num_iter=num_iter, burn_in=burn_in, ld_dict=chrom_ld_dict[chrom_str],\n                                            start_betas=LDpred_inf_chrom_dict[chrom_str], zero_jump_prob=zero_jump_prob)\n\n                updated_betas = res_dict['betas']\n                updated_inf_betas = res_dict['inf_betas']\n                sum_sqr_effects = sp.sum(updated_betas ** 2)\n                if sum_sqr_effects > gw_h2_ld_score_est:\n                    print 'Sum of squared updated effects estimates seems too large:', sum_sqr_effects\n                    print 'This suggests that the Gibbs sampler did not convergence.'\n\n                print 'Calculating scores for Chromosome %s' % ((chrom_str.split('_'))[1])\n                updated_betas = updated_betas / (snp_stds.flatten())\n                updated_inf_betas = updated_inf_betas / (snp_stds.flatten())\n                ldpred_effect_sizes.extend(updated_betas)\n                ldpred_inf_effect_sizes.extend(updated_inf_betas)\n                if has_phenotypes:\n                    prs = sp.dot(updated_betas, raw_snps)\n                    risk_scores_pval_derived += prs\n                    corr = sp.corrcoef(y, prs)[0, 1]\n                    r2 = corr ** 2\n                    print 'The R2 prediction accuracy of PRS using %s was: %0.4f' % (chrom_str, r2)\n\n\n        print 'There were %d (SNP) effects' % num_snps\n        if has_phenotypes:\n            num_indivs = len(y)\n            results_dict[p_str]['y'] = y\n            results_dict[p_str]['risk_scores_pd'] = risk_scores_pval_derived\n            print 'Prediction accuracy was assessed using %d individuals.' % (num_indivs)\n\n            corr = sp.corrcoef(y, risk_scores_pval_derived)[0, 1]\n            r2 = corr ** 2\n            results_dict[p_str]['r2_pd'] = r2\n            print 'The  R2 prediction accuracy (observed scale) for the whole genome was: %0.4f (%0.6f)' % (r2, ((1 - r2) ** 2) / num_indivs)\n\n            if corr < 0:\n                risk_scores_pval_derived = -1 * risk_scores_pval_derived\n            auc = util.calc_auc(y, risk_scores_pval_derived)\n            print 'AUC for the whole genome was: %0.4f' % auc\n\n            # Now calibration\n            denominator = sp.dot(risk_scores_pval_derived.T, risk_scores_pval_derived)\n            y_norm = (y - sp.mean(y)) / sp.std(y)\n            numerator = sp.dot(risk_scores_pval_derived.T, y_norm)\n            regression_slope = (numerator / denominator)  # [0][0]\n            print 'The slope for predictions with P-value derived  effects is:', regression_slope\n            results_dict[p_str]['slope_pd'] = regression_slope\n\n        weights_out_file = '%s_LDpred_p%0.4e.txt' % (out_file_prefix, p)\n        with open(weights_out_file, 'w') as f:\n            f.write('chrom    pos    sid    nt1    nt2    raw_beta     ldpred_beta\\n')\n            for chrom, pos, sid, nt, raw_beta, ldpred_beta in it.izip(chromosomes, out_positions, out_sids, out_nts, raw_effect_sizes, ldpred_effect_sizes):\n                nt1, nt2 = nt[0], nt[1]\n                f.write('%s    %d    %s    %s    %s    %0.4e    %0.4e\\n' % (chrom, pos, sid, nt1, nt2, raw_beta, ldpred_beta))\n\n    weights_out_file = '%s_LDpred-inf.txt' % (out_file_prefix)\n    with open(weights_out_file, 'w') as f:\n        f.write('chrom    pos    sid    nt1    nt2    raw_beta    ldpred_inf_beta \\n')\n        for chrom, pos, sid, nt, raw_beta, ldpred_inf_beta in it.izip(chromosomes, out_positions, out_sids, out_nts, raw_effect_sizes, ldpred_inf_effect_sizes):\n            nt1, nt2 = nt[0], nt[1]\n            f.write('%s    %d    %s    %s    %s    %0.4e    %0.4e\\n' % (chrom, pos, sid, nt1, nt2, raw_beta, ldpred_inf_beta))\n\n\n\ndef ldpred_gibbs(beta_hats, genotypes=None, start_betas=None, h2=None, n=1000, ld_radius=100,\n                 num_iter=60, burn_in=10, p=None, zero_jump_prob=0.05,\n                 ld_dict=None, reference_ld_mats=None, ld_boundaries=None, verbose=False):\n    \"\"\"\n    LDpred (Gibbs Sampler)\n    \"\"\"\n    t0 = time.time()\n    m = len(beta_hats)\n\n    # If no starting values for effects were given, then use the infinitesimal model starting values.\n    if start_betas is None:\n        print 'Initializing LDpred effects with posterior mean LDpred-inf effects.'\n        print 'Calculating LDpred-inf effects.'\n        start_betas = LDpred_inf.ldpred_inf(beta_hats, genotypes=genotypes, reference_ld_mats=reference_ld_mats,\n                                            h2=h2, n=n, ld_window_size=2 * ld_radius, verbose=False)\n    curr_betas = sp.copy(start_betas)\n    curr_post_means = sp.zeros(m)\n    avg_betas = sp.zeros(m)\n\n    # Iterating over effect estimates in sequential order\n    iter_order = sp.arange(m)\n\n    # Setting up the marginal Bayes shrink\n    Mp = m * p\n    hdmp = (h2 / Mp)\n    hdmpn = hdmp + 1.0 / n\n    hdmp_hdmpn = (hdmp / hdmpn)\n    c_const = (p / sp.sqrt(hdmpn))\n    d_const = (1 - p) / (sp.sqrt(1.0 / n))\n\n    for k in range(num_iter):  # Big iteration\n\n        # Force an alpha shrink if estimates are way off compared to heritability estimates.  (Improves MCMC convergence.)\n        h2_est = max(0.00001, sp.sum(curr_betas ** 2))\n        alpha = min(1 - zero_jump_prob, 1.0 / h2_est, (h2 + 1 / sp.sqrt(n)) / h2_est)\n\n        rand_ps = sp.random.random(m)\n        rand_norms = stats.norm.rvs(0, (hdmp_hdmpn) * (1 / n), size=m)\n\n        if ld_boundaries is None:\n            for i, snp_i in enumerate(iter_order):\n                start_i = max(0, snp_i - ld_radius)\n                focal_i = min(ld_radius, snp_i)\n                stop_i = min(m, snp_i + ld_radius + 1)\n\n                # Local LD matrix\n                D_i = ld_dict[snp_i]\n\n                # Local (most recently updated) effect estimates\n                local_betas = curr_betas[start_i: stop_i]\n\n                # Calculate the local posterior mean, used when sampling.\n                local_betas[focal_i] = 0\n                res_beta_hat_i = beta_hats[snp_i] - sp.dot(D_i , local_betas)\n                b2 = res_beta_hat_i ** 2\n\n                d_const_b2_exp = d_const * sp.exp(-b2 * n / 2.0)\n                if sp.isreal(d_const_b2_exp):\n                    numerator = c_const * sp.exp(-b2 / (2.0 * hdmpn))\n                    if sp.isreal(numerator):\n                        if numerator == 0:\n                            postp = 0\n                        else:\n                            postp = numerator / (numerator + d_const_b2_exp)\n                            assert sp.isreal(postp), 'The posterior mean is not a real number?  Possibly due to problems with summary stats, LD estimates, or parameter settings.'\n                    else:\n                        postp = 0\n                else:\n                    postp = 1\n                curr_post_means[snp_i] = hdmp_hdmpn * postp * res_beta_hat_i\n\n                if rand_ps[i] < postp * alpha:\n                    # Sample from the posterior Gaussian dist.\n                    proposed_beta = rand_norms[i] + hdmp_hdmpn * res_beta_hat_i\n\n                else:\n                    # Sample 0\n                    proposed_beta = 0\n\n                curr_betas[snp_i] = proposed_beta  # UPDATE BETA\n        else:\n            for i, snp_i in enumerate(iter_order):\n                start_i = ld_boundaries[snp_i][0]\n                stop_i = ld_boundaries[snp_i][1]\n                focal_i = snp_i - start_i\n\n                # Local LD matrix\n                D_i = ld_dict[snp_i]\n\n                # Local (most recently updated) effect estimates\n                local_betas = curr_betas[start_i: stop_i]\n\n                # Calculate the local posterior mean, used when sampling.\n                local_betas[focal_i] = 0\n                res_beta_hat_i = beta_hats[snp_i] - sp.dot(D_i , local_betas)\n                b2 = res_beta_hat_i ** 2\n\n                d_const_b2_exp = d_const * sp.exp(-b2 * n / 2.0)\n                if sp.isreal(d_const_b2_exp):\n                    numerator = c_const * sp.exp(-b2 / (2.0 * hdmpn))\n                    if sp.isreal(numerator):\n                        if numerator == 0:\n                            postp = 0\n                        else:\n                            postp = numerator / (numerator + d_const_b2_exp)\n                            assert sp.isreal(postp), 'Posterior mean is not a real number? Possibly due to problems with summary stats, LD estimates, or parameter settings.'\n                    else:\n                        postp = 0\n                else:\n                    postp = 1\n                curr_post_means[snp_i] = hdmp_hdmpn * postp * res_beta_hat_i\n\n                if rand_ps[i] < postp * alpha:\n                    # Sample from the posterior Gaussian dist.\n                    proposed_beta = rand_norms[i] + hdmp_hdmpn * res_beta_hat_i\n\n                else:\n                    # Sample 0\n                    proposed_beta = 0\n\n                curr_betas[snp_i] = proposed_beta  # UPDATE BETA\n        if verbose:\n            sys.stdout.write('\\b\\b\\b\\b\\b\\b\\b%0.2f%%' % (100.0 * (min(1, float(k + 1) / num_iter))))\n            sys.stdout.flush()\n\n        if k >= burn_in:\n            avg_betas += curr_post_means  # Averaging over the posterior means instead of samples.\n\n    avg_betas = avg_betas / float(num_iter - burn_in)\n    t1 = time.time()\n    t = (t1 - t0)\n    if verbose:\n        print '\\nTook %d minutes and %0.2f seconds' % (t / 60, t % 60)\n    return {'betas':avg_betas, 'inf_betas':start_betas}\n\n\ndef main():\n    p_dict = parse_parameters()\n    local_ld_dict_file = '%s_ldradius%d.pickled.gz' % (p_dict['local_ld_file_prefix'], p_dict['ld_radius'])\n\n    print \"\"\"\nNote: For maximal accuracy all SNPs with LDpred weights should be included in the validation data set.\nIf they are a subset of the validation data set, then we suggest recalculate LDpred for the overlapping SNPs.\n\"\"\"\n    if not os.path.isfile(local_ld_dict_file):\n        df = h5py.File(p_dict['coord'])\n\n        chrom_ld_scores_dict = {}\n        chrom_ld_dict = {}\n        chrom_ref_ld_mats = {}\n        if p_dict['gm_ld_radius'] is not None:\n            chrom_ld_boundaries = {}\n        ld_score_sum = 0\n        num_snps = 0\n        print 'Calculating LD information w. radius %d' % p_dict['ld_radius']\n\n        cord_data_g = df['cord_data']\n\n        for chrom_str in cord_data_g.keys():\n            print 'Working on %s' % chrom_str\n            g = cord_data_g[chrom_str]\n            if 'raw_snps_ref' in g.keys():\n                raw_snps = g['raw_snps_ref'][...]\n                snp_stds = g['snp_stds_ref'][...]\n                snp_means = g['snp_means_ref'][...]\n\n\n            # Filter monomorphic SNPs\n            ok_snps_filter = snp_stds > 0\n            ok_snps_filter = ok_snps_filter.flatten()\n            raw_snps = raw_snps[ok_snps_filter]\n            snp_means = snp_means[ok_snps_filter]\n            snp_stds = snp_stds[ok_snps_filter]\n\n            n_snps = len(raw_snps)\n            snp_means.shape = (n_snps, 1)\n            snp_stds.shape = (n_snps, 1)\n\n\n            # Normalize SNPs..\n            snps = sp.array((raw_snps - snp_means) / snp_stds, dtype='float32')\n            assert snps.shape == raw_snps.shape, 'Problems normalizing SNPs (array shape mismatch).'\n\n            # ??? Other stuff???\n            if p_dict['gm_ld_radius'] is not None:\n                assert 'genetic_map' in g.keys(), 'Genetic map is missing.'\n                gm = g['genetic_map'][...]\n                ret_dict = ld.get_LDpred_ld_tables(snps, gm=gm, gm_ld_radius=p_dict['gm_ld_radius'])\n                chrom_ld_boundaries[chrom_str] = ret_dict['ld_boundaries']\n            else:\n                ret_dict = ld.get_LDpred_ld_tables(snps, ld_radius=p_dict['ld_radius'], ld_window_size=2 * p_dict['ld_radius'])\n            chrom_ld_dict[chrom_str] = ret_dict['ld_dict']\n            chrom_ref_ld_mats[chrom_str] = ret_dict['ref_ld_matrices']\n            ld_scores = ret_dict['ld_scores']\n            chrom_ld_scores_dict[chrom_str] = {'ld_scores':ld_scores, 'avg_ld_score':sp.mean(ld_scores)}\n            ld_score_sum += sp.sum(ld_scores)\n            num_snps += n_snps\n        avg_gw_ld_score = ld_score_sum / float(num_snps)\n        ld_scores_dict = {'avg_gw_ld_score': avg_gw_ld_score, 'chrom_dict':chrom_ld_scores_dict}\n\n        print 'Done calculating the LD table and LD score, writing to file:', local_ld_dict_file\n        print 'Genome-wide average LD score was:', ld_scores_dict['avg_gw_ld_score']\n        ld_dict = {'ld_scores_dict':ld_scores_dict, 'chrom_ld_dict':chrom_ld_dict, 'chrom_ref_ld_mats':chrom_ref_ld_mats}\n        if p_dict['gm_ld_radius'] is not None:\n            ld_dict['chrom_ld_boundaries'] = chrom_ld_boundaries\n        f = gzip.open(local_ld_dict_file, 'wb')\n        cPickle.dump(ld_dict, f, protocol=2)\n        f.close()\n        print 'LD information is now pickled.'\n    else:\n        print 'Loading LD information from file: %s' % local_ld_dict_file\n        f = gzip.open(local_ld_dict_file, 'r')\n        ld_dict = cPickle.load(f)\n        f.close()\n\n    ldpred_genomewide(data_file=p_dict['coord'], out_file_prefix=p_dict['out'], ps=p_dict['PS'], ld_radius=p_dict['ld_radius'],\n                      ld_dict=ld_dict, n=p_dict['N'], num_iter=p_dict['num_iter'], h2=p_dict['H2'], verbose=False)\n\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "8711c87e1a1c66233c4626e6bb3e09cd8cb60e79", "size": 22859, "ext": "py", "lang": "Python", "max_stars_repo_path": "ldpred/LDpred.py", "max_stars_repo_name": "precisely/ldpred", "max_stars_repo_head_hexsha": "c2aad9950af044ccaf0a2971974ef0d26def19bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ldpred/LDpred.py", "max_issues_repo_name": "precisely/ldpred", "max_issues_repo_head_hexsha": "c2aad9950af044ccaf0a2971974ef0d26def19bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ldpred/LDpred.py", "max_forks_repo_name": "precisely/ldpred", "max_forks_repo_head_hexsha": "c2aad9950af044ccaf0a2971974ef0d26def19bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2147001934, "max_line_length": 248, "alphanum_fraction": 0.583840063, "include": true, "reason": "import scipy,from scipy", "num_tokens": 5936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.17664657598626105}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2019 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#\n\n'''\nRestricted Open-shell Hartree-Fock\n'''\n\nfrom functools import reduce\nimport numpy\nimport pyscf.gto\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf.scf import hf\nfrom pyscf.scf import uhf\nimport pyscf.scf.chkfile\nfrom pyscf import __config__\n\nWITH_META_LOWDIN = getattr(__config__, 'scf_analyze_with_meta_lowdin', True)\nMO_BASE = getattr(__config__, 'MO_BASE', 1)\n\n\ndef init_guess_by_minao(mol):\n    dm = hf.init_guess_by_minao(mol)\n    return numpy.array((dm*.5, dm*.5))\n\ndef init_guess_by_atom(mol):\n    dm = hf.init_guess_by_atom(mol)\n    return numpy.array((dm*.5, dm*.5))\n\ninit_guess_by_huckel = hf.init_guess_by_huckel\ninit_guess_by_chkfile = uhf.init_guess_by_chkfile\n\ndef get_fock(mf, h1e=None, s1e=None, vhf=None, dm=None, cycle=-1, diis=None,\n             diis_start_cycle=None, level_shift_factor=None, damp_factor=None):\n    '''Build fock matrix based on Roothaan's effective fock.\n    See also :func:`get_roothaan_fock`\n    '''\n    if h1e is None: h1e = mf.get_hcore()\n    if s1e is None: s1e = mf.get_ovlp()\n    if vhf is None: vhf = mf.get_veff(mf.mol, dm)\n    if dm is None: dm = mf.make_rdm1()\n    if isinstance(dm, numpy.ndarray) and dm.ndim == 2:\n        dm = numpy.array((dm*.5, dm*.5))\n# To Get orbital energy in get_occ, we saved alpha and beta fock, because\n# Roothaan effective Fock cannot provide correct orbital energy with `eig`\n# TODO, check other treatment  J. Chem. Phys. 133, 141102\n    focka = h1e + vhf[0]\n    fockb = h1e + vhf[1]\n    f = get_roothaan_fock((focka,fockb), dm, s1e)\n    if cycle < 0 and diis is None:  # Not inside the SCF iteration\n        return f\n\n    if diis_start_cycle is None:\n        diis_start_cycle = mf.diis_start_cycle\n    if level_shift_factor is None:\n        level_shift_factor = mf.level_shift\n    if damp_factor is None:\n        damp_factor = mf.damp\n\n    dm_tot = dm[0] + dm[1]\n    if 0 <= cycle < diis_start_cycle-1 and abs(damp_factor) > 1e-4:\n        raise NotImplementedError('ROHF Fock-damping')\n    if diis and cycle >= diis_start_cycle:\n        f = diis.update(s1e, dm_tot, f, mf, h1e, vhf)\n    if abs(level_shift_factor) > 1e-4:\n        f = hf.level_shift(s1e, dm_tot*.5, f, level_shift_factor)\n    f = lib.tag_array(f, focka=focka, fockb=fockb)\n    return f\n\ndef get_roothaan_fock(focka_fockb, dma_dmb, s):\n    '''Roothaan's effective fock.\n    Ref. http://www-theor.ch.cam.ac.uk/people/ross/thesis/node15.html\n\n    ======== ======== ====== =========\n    space     closed   open   virtual\n    ======== ======== ====== =========\n    closed      Fc      Fb     Fc\n    open        Fb      Fc     Fa\n    virtual     Fc      Fa     Fc\n    ======== ======== ====== =========\n\n    where Fc = (Fa + Fb) / 2\n\n    Returns:\n        Roothaan effective Fock matrix\n    '''\n    nao = s.shape[0]\n    focka, fockb = focka_fockb\n    dma, dmb = dma_dmb\n    fc = (focka + fockb) * .5\n# Projector for core, open-shell, and virtual\n    pc = numpy.dot(dmb, s)\n    po = numpy.dot(dma-dmb, s)\n    pv = numpy.eye(nao) - numpy.dot(dma, s)\n    fock  = reduce(numpy.dot, (pc.conj().T, fc, pc)) * .5\n    fock += reduce(numpy.dot, (po.conj().T, fc, po)) * .5\n    fock += reduce(numpy.dot, (pv.conj().T, fc, pv)) * .5\n    fock += reduce(numpy.dot, (po.conj().T, fockb, pc))\n    fock += reduce(numpy.dot, (po.conj().T, focka, pv))\n    fock += reduce(numpy.dot, (pv.conj().T, fc, pc))\n    fock = fock + fock.conj().T\n    fock = lib.tag_array(fock, focka=focka, fockb=fockb)\n    return fock\n\n\ndef get_occ(mf, mo_energy=None, mo_coeff=None):\n    '''Label the occupancies for each orbital.\n    NOTE the occupancies are not assigned based on the orbital energy ordering.\n    The first N orbitals are assigned to be occupied orbitals.\n\n    Examples:\n\n    >>> mol = gto.M(atom='H 0 0 0; O 0 0 1.1', spin=1)\n    >>> mf = scf.hf.SCF(mol)\n    >>> energy = numpy.array([-10., -1., 1, -2., 0, -3])\n    >>> mf.get_occ(energy)\n    array([2, 2, 2, 2, 1, 0])\n    '''\n\n    if mo_energy is None: mo_energy = mf.mo_energy\n    if getattr(mo_energy, 'mo_ea', None) is not None:\n        mo_ea = mo_energy.mo_ea\n        mo_eb = mo_energy.mo_eb\n    else:\n        mo_ea = mo_eb = mo_energy\n    nmo = mo_ea.size\n    mo_occ = numpy.zeros(nmo)\n    if getattr(mf, 'nelec', None) is None:\n        nelec = mf.mol.nelec\n    else:\n        nelec = mf.nelec\n    ncore = nelec[1]\n    nocc  = nelec[0]\n    nopen = abs(nocc - ncore)\n    mo_occ = _fill_rohf_occ(mo_energy, mo_ea, mo_eb, ncore, nopen)\n\n    if mf.verbose >= logger.INFO and nocc < nmo and ncore > 0:\n        ehomo = max(mo_energy[mo_occ> 0])\n        elumo = min(mo_energy[mo_occ==0])\n        if ehomo+1e-3 > elumo:\n            logger.warn(mf, 'HOMO %.15g >= LUMO %.15g', ehomo, elumo)\n        else:\n            logger.info(mf, '  HOMO = %.15g  LUMO = %.15g', ehomo, elumo)\n        if nopen > 0 and mf.verbose >= logger.DEBUG:\n            core_idx = mo_occ == 2\n            open_idx = mo_occ == 1\n            vir_idx = mo_occ == 0\n            logger.debug(mf, '                  Roothaan           | alpha              | beta')\n            logger.debug(mf, '  Highest 2-occ = %18.15g | %18.15g | %18.15g',\n                         max(mo_energy[core_idx]),\n                         max(mo_ea[core_idx]), max(mo_eb[core_idx]))\n            logger.debug(mf, '  Lowest 0-occ =  %18.15g | %18.15g | %18.15g',\n                         min(mo_energy[vir_idx]),\n                         min(mo_ea[vir_idx]), min(mo_eb[vir_idx]))\n            for i in numpy.where(open_idx)[0]:\n                logger.debug(mf, '  1-occ =         %18.15g | %18.15g | %18.15g',\n                             mo_energy[i], mo_ea[i], mo_eb[i])\n\n        if mf.verbose >= logger.DEBUG:\n            numpy.set_printoptions(threshold=nmo)\n            logger.debug(mf, '  Roothaan mo_energy =\\n%s', mo_energy)\n            logger.debug1(mf, '  alpha mo_energy =\\n%s', mo_ea)\n            logger.debug1(mf, '  beta  mo_energy =\\n%s', mo_eb)\n            numpy.set_printoptions(threshold=1000)\n    return mo_occ\n\ndef _fill_rohf_occ(mo_energy, mo_energy_a, mo_energy_b, ncore, nopen):\n    mo_occ = numpy.zeros_like(mo_energy)\n    open_idx = []\n    core_sort = numpy.argsort(mo_energy)\n    core_idx = core_sort[:ncore]\n    if nopen > 0:\n        open_idx = core_sort[ncore:]\n        open_sort = numpy.argsort(mo_energy_a[open_idx])\n        open_idx = open_idx[open_sort[:nopen]]\n    mo_occ[core_idx] = 2\n    mo_occ[open_idx] = 1\n    return mo_occ\n\ndef get_grad(mo_coeff, mo_occ, fock):\n    '''ROHF gradients is the off-diagonal block [co + cv + ov], where\n    [ cc co cv ]\n    [ oc oo ov ]\n    [ vc vo vv ]\n    '''\n    occidxa = mo_occ > 0\n    occidxb = mo_occ == 2\n    viridxa = ~occidxa\n    viridxb = ~occidxb\n    uniq_var_a = viridxa.reshape(-1,1) & occidxa\n    uniq_var_b = viridxb.reshape(-1,1) & occidxb\n\n    if getattr(fock, 'focka', None) is not None:\n        focka = fock.focka\n        fockb = fock.fockb\n    elif isinstance(fock, (tuple, list)) or getattr(fock, 'ndim', None) == 3:\n        focka, fockb = fock\n    else:\n        focka = fockb = fock\n    focka = reduce(numpy.dot, (mo_coeff.conj().T, focka, mo_coeff))\n    fockb = reduce(numpy.dot, (mo_coeff.conj().T, fockb, mo_coeff))\n\n    g = numpy.zeros_like(focka)\n    g[uniq_var_a]  = focka[uniq_var_a]\n    g[uniq_var_b] += fockb[uniq_var_b]\n    return g[uniq_var_a | uniq_var_b]\n\ndef make_rdm1(mo_coeff, mo_occ, **kwargs):\n    '''One-particle densit matrix.  mo_occ is a 1D array, with occupancy 1 or 2.\n    '''\n    mo_a = mo_coeff[:,mo_occ>0]\n    mo_b = mo_coeff[:,mo_occ==2]\n    dm_a = numpy.dot(mo_a, mo_a.conj().T)\n    dm_b = numpy.dot(mo_b, mo_b.conj().T)\n    return numpy.array((dm_a, dm_b))\n\ndef energy_elec(mf, dm=None, h1e=None, vhf=None):\n    if dm is None: dm = mf.make_rdm1()\n    elif isinstance(dm, numpy.ndarray) and dm.ndim == 2:\n        dm = numpy.array((dm*.5, dm*.5))\n    return uhf.energy_elec(mf, dm, h1e, vhf)\n\nget_veff = uhf.get_veff\n\ndef analyze(mf, verbose=logger.DEBUG, with_meta_lowdin=WITH_META_LOWDIN,\n            **kwargs):\n    '''Analyze the given SCF object:  print orbital energies, occupancies;\n    print orbital coefficients; Mulliken population analysis\n    '''\n    from pyscf.lo import orth\n    from pyscf.tools import dump_mat\n    mo_energy = mf.mo_energy\n    mo_occ = mf.mo_occ\n    mo_coeff = mf.mo_coeff\n    log = logger.new_logger(mf, verbose)\n    if log.verbose >= logger.NOTE:\n        log.note('**** MO energy ****')\n        if getattr(mo_energy, 'mo_ea', None) is not None:\n            mo_ea = mo_energy.mo_ea\n            mo_eb = mo_energy.mo_eb\n            log.note('                Roothaan           | alpha              | beta')\n            for i,c in enumerate(mo_occ):\n                log.note('MO #%-3d energy= %-18.15g | %-18.15g | %-18.15g occ= %g',\n                         i+MO_BASE, mo_energy[i], mo_ea[i], mo_eb[i], c)\n        else:\n            for i,c in enumerate(mo_occ):\n                log.note('MO #%-3d energy= %-18.15g occ= %g',\n                         i+MO_BASE, mo_energy[i], c)\n\n    ovlp_ao = mf.get_ovlp()\n    if log.verbose >= logger.DEBUG:\n        label = mf.mol.ao_labels()\n        if with_meta_lowdin:\n            log.debug(' ** MO coefficients (expansion on meta-Lowdin AOs) **')\n            orth_coeff = orth.orth_ao(mf.mol, 'meta_lowdin', s=ovlp_ao)\n            c = reduce(numpy.dot, (orth_coeff.conj().T, ovlp_ao, mo_coeff))\n        else:\n            log.debug(' ** MO coefficients (expansion on AOs) **')\n            c = mo_coeff\n        dump_mat.dump_rec(mf.stdout, c, label, start=MO_BASE, **kwargs)\n    dm = mf.make_rdm1(mo_coeff, mo_occ)\n    if with_meta_lowdin:\n        pop_and_charge = mf.mulliken_meta(mf.mol, dm, s=ovlp_ao, verbose=log)\n    else:\n        pop_and_charge = mf.mulliken_pop(mf.mol, dm, s=ovlp_ao, verbose=log)\n    dip = mf.dip_moment(mf.mol, dm, verbose=log)\n    return pop_and_charge, dip\n\nmulliken_pop = hf.mulliken_pop\nmulliken_meta = hf.mulliken_meta\n\ndef canonicalize(mf, mo_coeff, mo_occ, fock=None):\n    '''Canonicalization diagonalizes the Fock matrix within occupied, open,\n    virtual subspaces separatedly (without change occupancy).\n    '''\n    if getattr(fock, 'focka', None) is None:\n        dm = mf.make_rdm1(mo_coeff, mo_occ)\n        fock = mf.get_fock(dm=dm)\n    mo_e, mo_coeff = hf.canonicalize(mf, mo_coeff, mo_occ, fock)\n    fa, fb = fock.focka, fock.fockb\n    mo_ea = numpy.einsum('pi,pi->i', mo_coeff.conj(), fa.dot(mo_coeff)).real\n    mo_eb = numpy.einsum('pi,pi->i', mo_coeff.conj(), fb.dot(mo_coeff)).real\n    mo_e = lib.tag_array(mo_e, mo_ea=mo_ea, mo_eb=mo_eb)\n    return mo_e, mo_coeff\n\ndip_moment = hf.dip_moment\n\n\n# use UHF init_guess, get_veff, diis, and intermediates such as fock, vhf, dm\n# keep mo_energy, mo_coeff, mo_occ as RHF structure\n\nclass ROHF(hf.RHF):\n    __doc__ = hf.SCF.__doc__\n\n    def __init__(self, mol):\n        hf.SCF.__init__(self, mol)\n        self.nelec = None\n\n    @property\n    def nelec(self):\n        if getattr(self, '_nelec', None) is not None:\n            return self._nelec\n        else:\n            return self.mol.nelec\n    @nelec.setter\n    def nelec(self, x):\n        self._nelec = x\n\n    @property\n    def nelectron_alpha(self):\n        return self.nelec[0]\n    @nelectron_alpha.setter\n    def nelectron_alpha(self, x):\n        logger.warn(self, 'WARN: Attribute .nelectron_alpha is deprecated. '\n                    'Set .nelec instead')\n        #raise RuntimeError('API updates')\n        self.nelec = (x, self.mol.nelectron-x)\n\n    check_sanity = hf.SCF.check_sanity\n\n    def dump_flags(self, verbose=None):\n        hf.SCF.dump_flags(self, verbose)\n        nelec = self.nelec\n        logger.info(self, 'num. doubly occ = %d  num. singly occ = %d',\n                    nelec[1], nelec[0]-nelec[1])\n\n    def init_guess_by_minao(self, mol=None):\n        if mol is None: mol = self.mol\n        return init_guess_by_minao(mol)\n\n    def init_guess_by_atom(self, mol=None):\n        if mol is None: mol = self.mol\n        logger.info(self, 'Initial guess from the superpostion of atomic densties.')\n        return init_guess_by_atom(mol)\n\n    def init_guess_by_huckel(self, mol=None):\n        if mol is None: mol = self.mol\n        logger.info(self, 'Initial guess from on-the-fly Huckel, doi:10.1021/acs.jctc.8b01089.')\n        mo_energy, mo_coeff = init_guess_by_huckel(mol)\n        mo_occ = self.get_occ(mo_energy, mo_coeff)\n        return self.make_rdm1(mo_coeff, mo_occ)\n\n    def init_guess_by_1e(self, mol=None):\n        if mol is None: mol = self.mol\n        logger.info(self, 'Initial guess from hcore.')\n        h1e = self.get_hcore(mol)\n        s1e = self.get_ovlp(mol)\n        mo_energy, mo_coeff = self.eig(h1e, s1e)\n        mo_occ = self.get_occ(mo_energy, mo_coeff)\n        return self.make_rdm1(mo_coeff, mo_occ)\n\n    def init_guess_by_chkfile(self, chkfile=None, project=None):\n        if chkfile is None: chkfile = self.chkfile\n        return init_guess_by_chkfile(self.mol, chkfile, project=project)\n\n    get_fock = get_fock\n    get_occ = get_occ\n\n    @lib.with_doc(hf.eig.__doc__)\n    def eig(self, fock, s):\n        e, c = self._eigh(fock, s)\n        if getattr(fock, 'focka', None) is not None:\n            mo_ea = numpy.einsum('pi,pi->i', c.conj(), fock.focka.dot(c)).real\n            mo_eb = numpy.einsum('pi,pi->i', c.conj(), fock.fockb.dot(c)).real\n            e = lib.tag_array(e, mo_ea=mo_ea, mo_eb=mo_eb)\n        return e, c\n\n    @lib.with_doc(get_grad.__doc__)\n    def get_grad(self, mo_coeff, mo_occ, fock=None):\n        if fock is None:\n            dm1 = self.make_rdm1(mo_coeff, mo_occ)\n            fock = self.get_hcore(self.mol) + self.get_veff(self.mol, dm1)\n        return get_grad(mo_coeff, mo_occ, fock)\n\n    @lib.with_doc(make_rdm1.__doc__)\n    def make_rdm1(self, mo_coeff=None, mo_occ=None, **kwargs):\n        if mo_coeff is None: mo_coeff = self.mo_coeff\n        if mo_occ is None: mo_occ = self.mo_occ\n        return make_rdm1(mo_coeff, mo_occ, **kwargs)\n\n    energy_elec = energy_elec\n\n    @lib.with_doc(uhf.get_veff.__doc__)\n    def get_veff(self, mol=None, dm=None, dm_last=0, vhf_last=0, hermi=1):\n        if mol is None: mol = self.mol\n        if dm is None: dm = self.make_rdm1()\n        if isinstance(dm, numpy.ndarray) and dm.ndim == 2:\n            dm = numpy.array((dm*.5, dm*.5))\n\n        if self._eri is not None or not self.direct_scf:\n            if getattr(dm, 'mo_coeff', None) is not None:\n                mo_coeff = dm.mo_coeff\n                mo_occ_a = (dm.mo_occ > 0).astype(numpy.double)\n                mo_occ_b = (dm.mo_occ ==2).astype(numpy.double)\n                dm = lib.tag_array(dm, mo_coeff=(mo_coeff,mo_coeff),\n                                   mo_occ=(mo_occ_a,mo_occ_b))\n            vj, vk = self.get_jk(mol, dm, hermi)\n            vhf = vj[0] + vj[1] - vk\n        else:\n            ddm = dm - numpy.asarray(dm_last)\n            vj, vk = self.get_jk(mol, ddm, hermi)\n            vhf = vj[0] + vj[1] - vk\n            vhf += numpy.asarray(vhf_last)\n        return vhf\n\n    @lib.with_doc(analyze.__doc__)\n    def analyze(self, verbose=None, with_meta_lowdin=WITH_META_LOWDIN,\n                **kwargs):\n        if verbose is None: verbose = self.verbose\n        return analyze(self, verbose, with_meta_lowdin, **kwargs)\n\n    canonicalize = canonicalize\n\n    def spin_square(self, mo_coeff=None, s=None):\n        '''Spin square and multiplicity of RHF determinant'''\n        neleca, nelecb = self.nelec\n        ms = (neleca - nelecb) * .5\n        ss = ms * (ms + 1)\n        return ss, ms*2+1\n\n    def stability(self,\n                  internal=getattr(__config__, 'scf_stability_internal', True),\n                  external=getattr(__config__, 'scf_stability_external', False),\n                  verbose=None):\n        '''\n        ROHF/ROKS stability analysis.\n\n        See also pyscf.scf.stability.rohf_stability function.\n\n        Kwargs:\n            internal : bool\n                Internal stability, within the RHF optimization space.\n            external : bool\n                External stability. It is not available in current version.\n\n        Returns:\n            The return value includes two set of orbitals which are more close to\n            the required stable condition.\n        '''\n        from pyscf.scf.stability import rohf_stability\n        return rohf_stability(self, internal, external, verbose)\n\n    def nuc_grad_method(self):\n        from pyscf.grad import rohf\n        return rohf.Gradients(self)\n\n\nclass HF1e(ROHF):\n    def scf(self, *args):\n        logger.info(self, '\\n')\n        logger.info(self, '******** 1 electron system ********')\n        self.converged = True\n        h1e = self.get_hcore(self.mol)\n        s1e = self.get_ovlp(self.mol)\n        self.mo_energy, self.mo_coeff = self.eig(h1e, s1e)\n        self.mo_occ = self.get_occ(self.mo_energy, self.mo_coeff)\n        self.e_tot = self.mo_energy[self.mo_occ>0][0] + self.mol.energy_nuc()\n        self._finalize()\n        return self.e_tot\n\ndel(WITH_META_LOWDIN)\n", "meta": {"hexsha": "60c26ef6a5be68c7428cbdb1cc11149bab92ece5", "size": 17571, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/scf/rohf.py", "max_stars_repo_name": "crisely09/pyscf", "max_stars_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyscf/scf/rohf.py", "max_issues_repo_name": "crisely09/pyscf", "max_issues_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscf/scf/rohf.py", "max_forks_repo_name": "crisely09/pyscf", "max_forks_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8364779874, "max_line_length": 96, "alphanum_fraction": 0.6094132377, "include": true, "reason": "import numpy", "num_tokens": 5324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.17664657598626102}}
{"text": "\"\"\"\nDefines the KeplerFFI class that uses FFIs to model the PRF shape for a given\nchannel and quarter.\n\"\"\"\nimport os\nimport sys\nimport warnings\nimport wget\n\nimport numpy as np\nimport pandas as pd\nimport pickle\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\n\nfrom scipy import sparse\nfrom tqdm.auto import tqdm\nfrom astropy.io import fits\nfrom astropy.table import Table\nfrom astropy.coordinates import SkyCoord, match_coordinates_3d\nfrom astropy.stats import sigma_clip, SigmaClip\nfrom astropy.time import Time\nfrom astropy.wcs import WCS\nfrom photutils import Background2D, MedianBackground, BkgZoomInterpolator\n\nfrom . import PACKAGEDIR, DATAOUTDIR\nfrom .utils import get_gaia_sources, make_A_edges, solve_linear_model, _make_A_polar\n\nr_min, r_max = 20, 1044\nc_min, c_max = 12, 1112\nremove_sat = True\nmask_bright = True\n\n# dictionary with FFI file names and in-quarter mapping\nquarter_ffi = {\n    0: [\n        \"kplr2009114174833_ffi-cal.fits\",\n        \"kplr2009114204835_ffi-cal.fits\",\n        \"kplr2009115002613_ffi-cal.fits\",\n        \"kplr2009115053616_ffi-cal.fits\",\n        \"kplr2009115080620_ffi-cal.fits\",\n        \"kplr2009115131122_ffi-cal.fits\",\n        \"kplr2009115173611_ffi-cal.fits\",\n        \"kplr2009116035924_ffi-cal.fits\",\n    ],\n    1: [],\n    2: [\"kplr2009231194831_ffi-cal.fits\"],\n    3: [\"kplr2009292020429_ffi-cal.fits\", \"kplr2009322233047_ffi-cal.fits\"],\n    4: [\n        \"kplr2010019225502_ffi-cal.fits\",\n        \"kplr2010020005046_ffi-cal.fits\",\n        \"kplr2010049182302_ffi-cal.fits\",\n    ],\n    5: [\"kplr2010111125026_ffi-cal.fits\", \"kplr2010140101631_ffi-cal.fits\"],\n    6: [\"kplr2010203012215_ffi-cal.fits\", \"kplr2010234192745_ffi-cal.fits\"],\n    7: [\"kplr2010296192119_ffi-cal.fits\", \"kplr2010326181728_ffi-cal.fits\"],\n    8: [\"kplr2011024134926_ffi-cal.fits\", \"kplr2011053174401_ffi-cal.fits\"],\n    9: [\"kplr2011116104002_ffi-cal.fits\", \"kplr2011145152723_ffi-cal.fits\"],\n    10: [\"kplr2011208112727_ffi-cal.fits\", \"kplr2011240181752_ffi-cal.fits\"],\n    11: [\"kplr2011303191211_ffi-cal.fits\", \"kplr2011334181008_ffi-cal.fits\"],\n    12: [\"kplr2012032101442_ffi-cal.fits\", \"kplr2012060123308_ffi-cal.fits\"],\n    13: [\"kplr2012121122500_ffi-cal.fits\", \"kplr2012151105138_ffi-cal.fits\"],\n    14: [\"kplr2012211123923_ffi-cal.fits\", \"kplr2012242195726_ffi-cal.fits\"],\n    15: [\"kplr2012310200152_ffi-cal.fits\", \"kplr2012341215621_ffi-cal.fits\"],\n    16: [\"kplr2013038133130_ffi-cal.fits\", \"kplr2013065115251_ffi-cal.fits\"],\n    17: [\"kplr2013098115308_ffi-cal.fits\"],\n}\n\n\nclass KeplerFFI(object):\n    \"\"\"\n    Class for loading Kepler's FFI files and compute PRF models out of them following\n    the method discussed in Hedges et al. 2021 and Martinez-Palomera et al. 2021.\n    \"\"\"\n\n    def __init__(\n        self,\n        ffi_name: str = \"\",\n        channel: int = 1,\n        quarter: int = None,\n        plot: bool = True,\n        save: bool = True,\n    ):\n        \"\"\"\n        Initialization of the KeplerFFI class\n        Parameters\n        ----------\n        ffi_name : string\n            Name of the FFI file used to model the PRF profile. Either ffi_name or\n            quarter can be provided.\n        channel : int\n            Channel number of the FFI to be used to model the PRF. Valid values are\n            between 1 and 84.\n        quarter : int\n            Number of the quarter that will be used to model the PRF.\n            Either ffi_name or quarter can be provided, if quarter is provided,\n            then all FFI files observed during the time window of that quarter will\n            be used to model the PRF by averaging the images.\n            Valid values are between 1 and 17.\n        plot : boolean\n            Whether to clreate diagnostic plots or not.\n        save : boolean\n            Whether to save the models or not.\n\n        Attributes\n        ----------\n        channel : int\n            Number of the quarter that will be used to model the PRF.\n        quarter : int\n            Channel number of the FFI to be used to model the PRF.\n        plot : bool\n            Boolean to create diagnostic plots.\n        save : bool\n            Boolean to save models and figures.\n        hdr : dict\n            Header dictionary of the FFI file.\n        img : numpy.ndarray\n            Original FFI flux image in electros / sec.\n        wcs : astropy.WCS\n            Object with the WCS solution of the image.\n        col_2d : numpy.ndarray\n            Data array with the pixel column number in 2D\n        row_2d : numpy.ndarray\n            Data array with the pixel row number in 2D\n        ra_2d : numpy.ndarray\n            Data array with the pixel Right Ascension value in 2D, in degs\n        dec_2d : numpy.ndarray\n            Data array with the pixel Declination value in 2D, in degs\n        flux_2d : numpy.ndarray\n            Data array with the flux value of each pixel with substracted background\n            in 2D, in electros / sec.\n        sources : pandas.DataFrame\n            Catalog with Gaia sources observed in the image, after cleaning.\n        flux : numpy.ndarray\n            Data array with the flux value of each pixel with substracted background\n            in 1D after removing saturated & bright pixels. in electros / sec.\n        flux_err : numpy.ndarray\n            Data array with the flux error value of each pixel with substracted\n            background in 1D after removing saturated & bright pixels. in electros / sec.\n        col : numpy.ndarray\n            Data array with the pixel column number in 1D after removing saturated &\n            bright pixels\n        row : numpy.ndarray\n            Data array with the pixel row number in 1D after removing saturated &\n            bright pixels\n        nsurces : int\n            Total number of sources observed in the image after cleaning.\n        npixels : int\n            Total number of pixels in the image\n        gf : numpy.ndarray\n            Data array with the Gaia flux value for every source.\n        dflux : scipy.sparse.csr_matrix\n            Sparse matrix with pixel flux value within r < 7 pixels of the source\n            coordinates. Has shape [nsources , npixels]\n        dx : scipy.sparse.csr_matrix\n            Sparse matrix with distance between the pixel within r < 7 pixels and the\n            source location, in pixel units. Has shape [nsources , npixels]\n        dy : scipy.sparse.csr_matrix\n            Sparse matrix with distance between the pixel within r < 7 pixels and the\n            source location, in pixel units. Has shape [nsources , npixels]\n        r : scipy.sparse.csr_matrix\n            Sparse matrix with radial distance between pixels within r < 7 and the\n            source location, in polar coordinates. Has shape [nsources , npixels]\n        phi : scipy.sparse.csr_matrix\n            Sparse matrix with angle value of pixels within r < 7 and the\n            source location, in polar coordinates. Has shape [nsources , npixels]\n        \"\"\"\n\n        self.channel = channel\n        self.plot = plot\n        self.save = save\n        self.show = False\n\n        if quarter is not None and quarter in np.arange(18):\n            fname = \"%s/data/fits/ffi/%s\" % (DATAOUTDIR, quarter_ffi[quarter][0])\n        elif len(ffi_name) == 17 and ffi_name[:4] == \"kplr\":\n            fname = \"%s/data/fits/ffi/%s_ffi-cal.fits\" % (DATAOUTDIR, ffi_name)\n        else:\n            raise ValueError(\"Invalid quarter or FFI fits file name\")\n\n        if not os.path.isfile(fname):\n            print(\"Downloading FFI fits files\")\n            fits_name = fname.split(\"/\")[-1]\n            print(fits_name)\n            self.download_ffi(fits_name)\n\n        self.hdr = fits.open(fname)[channel].header\n        self.img = fits.open(fname)[channel].data\n        self.wcs = WCS(self.hdr)\n        self.quarter = quarter if quarter is not None else self.hdr[\"MJDSTART\"]\n\n        row_2d, col_2d = np.mgrid[: self.img.shape[0], : self.img.shape[1]]\n        row, col = row_2d.ravel(), col_2d.ravel()\n        ra, dec = self.wcs.all_pix2world(np.vstack([col, row]).T, 0).T\n        ra_2d, dec_2d = ra.reshape(self.img.shape), dec.reshape(self.img.shape)\n\n        # get coordinates of the center for query\n        loc = (self.img.shape[0] // 2, self.img.shape[1] // 2)\n        ra_q, dec_q = self.wcs.all_pix2world(np.atleast_2d(loc), 0).T\n        rad = [np.hypot(ra - ra.mean(), dec - dec.mean()).max()]\n\n        time = Time(self.hdr[\"TSTART\"] + 2454833, format=\"jd\")\n        if ra_q[0] > 360 or np.abs(dec_q[0]) > 90 or rad[0] > 5:\n            raise ValueError(\n                \"Query values are out of bound, please check WCS solution.\"\n            )\n\n        # remove border Pixels\n        self.col_2d = col_2d[r_min:r_max, c_min:c_max] - c_min\n        self.row_2d = row_2d[r_min:r_max, c_min:c_max] - r_min\n        self.ra_2d = ra_2d[r_min:r_max, c_min:c_max]\n        self.dec_2d = dec_2d[r_min:r_max, c_min:c_max]\n        flux_2d = self.img[r_min:r_max, c_min:c_max]\n\n        sources = self._do_big_query(self.ra_2d, self.dec_2d, time.jyear)\n        sources[\"col\"], sources[\"row\"] = self.wcs.all_world2pix(\n            sources.loc[:, [\"ra\", \"dec\"]].values, 0.5\n        ).T\n\n        # correct col,row columns for gaia sources\n        sources.row -= r_min\n        sources.col -= c_min\n\n        # clean out-of-ccd and blended sources\n        clean_sources = self._clean_source_list(sources)\n        del sources\n\n        # background substraction\n        self.flux_2d = flux_2d - self._model_bkg(flux_2d, mask=None)\n\n        # ravel arrays\n        col = self.col_2d.ravel()\n        row = self.row_2d.ravel()\n        ra = self.ra_2d.ravel()\n        dec = self.dec_2d.ravel()\n        flux = self.flux_2d.ravel()\n\n        if remove_sat:\n            non_sat_mask = ~self._saturated_pixels_mask(\n                flux, col, row, saturation_limit=1.5e5\n            )\n            print(\"Saturated pixels %i: \" % (np.sum(~non_sat_mask)))\n            self.non_sat_mask = non_sat_mask\n\n            col = col[non_sat_mask]\n            row = row[non_sat_mask]\n            ra = ra[non_sat_mask]\n            dec = dec[non_sat_mask]\n            flux = flux[non_sat_mask]\n\n        if mask_bright:\n            bright_mask = ~self._mask_bright_sources(\n                flux, col, row, clean_sources, mag_limit=10\n            )\n            print(\"Bright pixels %i: \" % (np.sum(~bright_mask)))\n            self.bright_mask = bright_mask\n\n            col = col[bright_mask]\n            row = row[bright_mask]\n            ra = ra[bright_mask]\n            dec = dec[bright_mask]\n            flux = flux[bright_mask]\n\n        clean_sources = clean_sources[\n            (clean_sources.phot_g_mean_flux > 1e3)\n            & (clean_sources.phot_g_mean_flux < 1e6)\n        ].reset_index(drop=True)\n\n        print(\"Total Gaia sources %i: \" % (clean_sources.shape[0]))\n\n        self.sources = clean_sources\n        self.flux = flux\n        self.flux_err = np.sqrt(np.abs(self.flux))\n        self.col = col\n        self.row = row\n        self.nsurces = clean_sources.shape[0]\n        self.npixels = self.flux.shape[0]\n\n        self.rmin = 0.25\n        self.rmax = 3.0\n\n    @staticmethod\n    def download_ffi(fits_name):\n        \"\"\"\n        Download FFI fits file to a dedicated quarter directory\n\n        Parameters\n        ----------\n        fits_name : string\n            Name of FFI fits file\n        \"\"\"\n        url = \"https://archive.stsci.edu/missions/kepler/ffi\"\n        if fits_name == \"\":\n            raise ValueError(\"Invalid fits file name\")\n\n        if not os.path.isdir(\"%s/data/fits/ffi\" % (DATAOUTDIR)):\n            os.makedirs(\"%s/data/fits/ffi\" % (DATAOUTDIR))\n\n        out = \"%s/data/fits/ffi/%s\" % (DATAOUTDIR, fits_name)\n        wget.download(\"%s/%s\" % (url, fits_name), out=out)\n\n        return\n\n    def _do_big_query(self, ra, dec, epoch):\n        \"\"\"\n        Query Gaia catalogs (EDR3 default) to obtain sources observed in the FFI.\n        If query finishs ok, result will be saved for future use in the following\n        directory:\n            ../data/catalogs/ffi/<quarter#>/channel_<channel#>_gaia_xmatch.csv\n\n        It does nx*ny small queries to avoid TimeoutError that might happen when doing\n        large (rad > 0.7 deg) queries to Gaia archive. The ouput file has unique\n        objects.\n\n        Parameters\n        ----------\n        ra : list\n            Value of the Right Ascension coordinate used for the query, in deg.\n        dec : list\n            Value of the Declination coordinate used for the query, in deg.\n        epoch : float\n            Year of the observation (Julian year) used for proper motion correction.\n\n        Returns\n        -------\n        sources : pandas.DataFrame\n            Clean catalog\n        \"\"\"\n        file_name = \"%s/data/catalogs/ffi/%s/channel_%i_gaia_xmatch.csv\" % (\n            DATAOUTDIR,\n            str(self.quarter),\n            self.channel,\n        )\n        if os.path.isfile(file_name):\n            print(\"Loading query from file...\")\n            print(file_name)\n            sources = pd.read_csv(file_name).drop(\"Unnamed: 0\", axis=1)\n        else:\n            # number of cells in the grid to divide the image\n            nx = 4\n            ny = 4\n            stepx = int(self.ra_2d.shape[1] / nx)\n            stepy = int(self.ra_2d.shape[0] / ny)\n            sources = []\n            for x in range(1, nx + 1):\n                for y in range(1, ny + 1):\n                    ra_cell = self.ra_2d[\n                        (y - 1) * stepy : y * stepy, (x - 1) * stepx : x * stepx\n                    ]\n                    dec_cell = self.dec_2d[\n                        (y - 1) * stepy : y * stepy, (x - 1) * stepx : x * stepx\n                    ]\n\n                    ra_q = np.mean(ra_cell)\n                    dec_q = np.mean(dec_cell)\n                    rad_q = np.hypot(\n                        ra_cell - ra_cell.mean(), dec_cell - dec_cell.mean()\n                    ).max()\n                    print(\n                        \"Will do small queries query with this \"\n                        + \"(ra, dec, radius, epoch): \",\n                        ra_q,\n                        dec_q,\n                        rad_q,\n                        epoch,\n                    )\n                    result = get_gaia_sources(\n                        tuple([ra_q]),\n                        tuple([dec_q]),\n                        tuple([rad_q]),\n                        magnitude_limit=18,\n                        epoch=epoch,\n                        dr=3,\n                    )\n                    sources.append(result)\n            sources = pd.concat(sources, axis=0).drop_duplicates(subset=[\"designation\"])\n            print(\"Saving query to file...\")\n            print(file_name)\n            columns = [\n                \"designation\",\n                \"ra\",\n                \"ra_error\",\n                \"dec\",\n                \"dec_error\",\n                \"pmra\",\n                \"pmdec\",\n                \"parallax\",\n                \"parallax_error\",\n                \"phot_g_n_obs\",\n                \"phot_g_mean_flux\",\n                \"phot_g_mean_flux_error\",\n                \"phot_g_mean_mag\",\n                \"phot_bp_n_obs\",\n                \"phot_bp_mean_flux\",\n                \"phot_bp_mean_flux_error\",\n                \"phot_bp_mean_mag\",\n                \"phot_rp_n_obs\",\n                \"phot_rp_mean_flux\",\n                \"phot_rp_mean_flux_error\",\n                \"phot_rp_mean_mag\",\n            ]\n            sources = sources.loc[:, columns]\n\n            if not os.path.isdir(\n                \"%s/data/catalogs/ffi/%s\" % (DATAOUTDIR, str(self.quarter))\n            ):\n                os.makedirs(\"%s/data/catalogs/ffi/%s\" % (DATAOUTDIR, str(self.quarter)))\n            sources.to_csv(file_name)\n        return sources\n\n    def _clean_source_list(self, sources):\n        \"\"\"\n        Function to clean surces from the catalog removing sources near the borders,\n        with 10 pixel tolerance, and to remove blended sources (within 8\")\n\n        Parameters\n        ----------\n        sources : pandas.DataFrame\n            Catalog with sources to be removed\n\n        Returns\n        -------\n        sources : pandas.DataFrame\n            Clean catalog\n        \"\"\"\n\n        print(\"Cleaning sources table...\")\n\n        # find sources inside the image with 10 pix of inward tolerance\n        inside = (\n            (sources.row > 10)\n            & (sources.row < 1014)\n            & (sources.col > 10)\n            & (sources.col < 1090)\n        )\n        sources = sources[inside].reset_index(drop=True)\n\n        # find well separated sources\n        s_coords = SkyCoord(sources.ra, sources.dec, unit=(\"deg\"))\n        midx, mdist = match_coordinates_3d(s_coords, s_coords, nthneighbor=2)[:2]\n        # remove sources closer than 8\" = 2 pix\n        closest = mdist.arcsec < 8.0\n        blocs = np.vstack([midx[closest], np.where(closest)[0]])\n        bmags = np.vstack(\n            [\n                sources.phot_g_mean_mag[midx[closest]],\n                sources.phot_g_mean_mag[np.where(closest)[0]],\n            ]\n        )\n        faintest = [blocs[idx][s] for s, idx in enumerate(np.argmax(bmags, axis=0))]\n        unresolved = np.in1d(np.arange(len(sources)), faintest)\n        del s_coords, midx, mdist, closest, blocs, bmags\n\n        sources = sources[~unresolved].reset_index(drop=True)\n\n        return sources\n\n    def _model_bkg(self, data, mask=None):\n        \"\"\"\n        BkgZoomInterpolator:\n        This class generates full-sized background and background RMS images\n        from lower-resolution mesh images using the `~scipy.ndimage.zoom`\n        (spline) interpolator.\n\n        Parameters\n        ----------\n        data : numpy.ndarray\n            Data arra with the pixel flux values.\n        mask : numpy.ndarray\n            Boolean array to mask pixels with sources.\n\n        Returns\n        -------\n        background : numpy.ndarray\n            Data array with background model\n        \"\"\"\n        model = Background2D(\n            data,\n            mask=mask,\n            box_size=(64, 50),\n            filter_size=15,\n            exclude_percentile=20,\n            sigma_clip=SigmaClip(sigma=3.0, maxiters=5),\n            bkg_estimator=MedianBackground(),\n            interpolator=BkgZoomInterpolator(order=3),\n        )\n\n        return model.background\n\n    def _saturated_pixels_mask(self, flux, column, row, saturation_limit=1.5e5):\n        \"\"\"\n        Finds and removes saturated pixels, including bleed columns.\n\n        Parameters\n        ----------\n        flux : numpu.ndarray\n            Data array with pixel flux value\n        column : numpy.ndarray\n            Data array with pixel column value\n        row : numpy.ndarray\n            Data array with pixel row value\n        saturation_limit : foat\n            Saturation limit at which pixels are removed.\n\n        Returns\n        -------\n        mask : numpy.ndarray\n            Boolean mask with rejected pixels\n        \"\"\"\n        # Which pixels are saturated\n        # saturated = np.nanpercentile(flux, 99, axis=0)\n        saturated = np.where((flux > saturation_limit).astype(float))[0]\n\n        # Find bad pixels, including allowence for a bleed column.\n        bad_pixels = np.vstack(\n            [\n                np.hstack([column[saturated] + idx for idx in np.arange(-3, 3)]),\n                np.hstack([row[saturated] for idx in np.arange(-3, 3)]),\n            ]\n        ).T\n        # Find unique row/column combinations\n        bad_pixels = bad_pixels[\n            np.unique([\"\".join(s) for s in bad_pixels.astype(str)], return_index=True)[\n                1\n            ]\n        ]\n        # Build a mask of saturated pixels\n        m = np.zeros(len(column), bool)\n        for p in bad_pixels:\n            m |= (column == p[0]) & (row == p[1])\n        return m\n\n    def _mask_bright_sources(self, flux, column, row, sources, mag_limit=10):\n        \"\"\"\n        Finds and removes halos produced by bright stars (<10 mag)\n\n        Parameters\n        ----------\n        flux : numpu.ndarray\n            Data array with pixel flux value\n        column : numpy.ndarray\n            Data array with pixel column value\n        row : numpy.ndarray\n            Data array with pixel row value\n        sources : pandas.DataFrame\n            Catalog wih observed sources in the image\n        mag_limit : foat\n            Magnitude limit at which bright sources are identified.\n\n        Returns\n        -------\n        mask : numpy.ndarray\n            Boolean mask with rejected pixels\n        \"\"\"\n        bright_mask = sources[\"phot_g_mean_mag\"] <= mag_limit\n        mask_radius = 30  # Pixels\n\n        mask = [\n            np.hypot(column - s.col, row - s.row) < mask_radius\n            for _, s in sources[bright_mask].iterrows()\n        ]\n        mask = np.array(mask).sum(axis=0) > 0\n\n        return mask\n\n    def _create_sparse(self):\n        \"\"\"\n        Function to create sparse matrces (scipy.sparse.csr_matrix) for variables:\n        dx, dy, dflux, dfluxerr, r, and phy\n        This is extremelly necessary for FFI due to the large number of sources (~10k)\n        and pixels (~1.1M). The sparse matrices contain the pixel data around the\n        sources up to 7 pixels distance from the object location.\n        \"\"\"\n        dx, dy, sparse_mask = [], [], []\n        for i in tqdm(range(len(self.sources)), desc=\"Gaia sources\"):\n            dx_aux = self.col - self.sources[\"col\"].iloc[i]\n            dy_aux = self.row - self.sources[\"row\"].iloc[i]\n            near_mask = sparse.csr_matrix((np.abs(dx_aux) <= 7) & (np.abs(dy_aux) <= 7))\n\n            dx.append(near_mask.multiply(dx_aux))\n            dy.append(near_mask.multiply(dy_aux))\n            sparse_mask.append(near_mask)\n\n        del dx_aux, dy_aux, near_mask\n        dx = sparse.vstack(dx, \"csr\")\n        dy = sparse.vstack(dy, \"csr\")\n        sparse_mask = sparse.vstack(sparse_mask, \"csr\")\n        sparse_mask.eliminate_zeros()\n\n        self.gf = self.sources[\"phot_g_mean_flux\"].values\n        self.dflux = sparse_mask.multiply(self.flux).tocsr()\n        self.dflux_err = np.sqrt(np.abs(self.dflux))\n\n        # eliminate leaked zero flux values in the sparse_mask\n        self.sparse_mask = self.dflux.astype(bool)\n        self.dx = self.sparse_mask.multiply(dx).tocsr()\n        self.dy = self.sparse_mask.multiply(dy).tocsr()\n        del dx, dy, sparse_mask\n\n        # convertion to polar coordinates\n        print(\"to polar coordinates...\")\n        nnz_inds = self.sparse_mask.nonzero()\n        r_vals = np.hypot(self.dx.data, self.dy.data)\n        phi_vals = np.arctan2(self.dy.data, self.dx.data)\n        self.r = sparse.csr_matrix(\n            (r_vals, (nnz_inds[0], nnz_inds[1])),\n            shape=self.sparse_mask.shape,\n            dtype=float,\n        )\n        self.phi = sparse.csr_matrix(\n            (phi_vals, (nnz_inds[0], nnz_inds[1])),\n            shape=self.sparse_mask.shape,\n            dtype=float,\n        )\n        del r_vals, phi_vals, nnz_inds\n\n        return\n\n    def _get_source_mask(\n        self,\n        upper_radius_limit=7,\n        lower_radius_limit=1.1,\n        flux_cut_off=300,\n        dm_type=\"rf-quadratic\",\n        plot=False,\n    ):\n        \"\"\"\n        Find the pixel mask that identifies pixels with contributions from ANY NUMBER\n        of Sources.\n        Fits a simple polynomial model to the log of the pixel flux values, in radial\n        dimension and source flux, to find the optimum circular apertures for every\n        source.\n\n        Parameters\n        ----------\n        upper_radius_limit : float\n            The radius limit at which we assume there is no flux from a source of any\n            brightness (arcsec).\n        lower_radius_limit : float\n            The radius limit at which we assume there is flux from a source of any\n            brightness (arcsec).\n        flux_cut_off : float\n            The flux at which we assume a source is too faint to model\n        dm_type : string\n            Type of design matrix to be used for modeling. Default is `rf-quadratic`,\n            which is quadratic in both radius and flux.\n        plot : bool\n            Whether to show diagnostic plot. Default is False.\n        \"\"\"\n        r = self.r\n        mean_flux = self.dflux\n        gf = self.gf\n\n        nonz_idx = r.nonzero()\n        rad_mask = r.data < upper_radius_limit\n        temp_mask = sparse.csr_matrix(\n            (r.data[rad_mask], (nonz_idx[0][rad_mask], nonz_idx[1][rad_mask])),\n            shape=r.shape,\n        ).astype(bool)\n        temp_mask = temp_mask.multiply(temp_mask.sum(axis=0) == 1).tocsr()\n        temp_mask.eliminate_zeros()\n\n        with np.errstate(divide=\"ignore\", invalid=\"ignore\"):\n            f = np.log10(temp_mask.astype(float).multiply(mean_flux).data)\n        k = np.isfinite(f)\n        f_mask = f[k]\n        r_mask = temp_mask.astype(float).multiply(r).data[k]\n        gf_mask = temp_mask.astype(float).multiply(gf[:, None]).data[k]\n        k = np.isfinite(f_mask)\n\n        A = make_A_edges(r_mask, np.log10(gf_mask), type=dm_type)\n\n        for count in [0, 1, 2]:\n            sigma_w_inv = A[k].T.dot(A[k])\n            B = A[k].T.dot(f_mask[k])\n            w = np.linalg.solve(sigma_w_inv, B)\n            res = np.ma.masked_array(f_mask, ~k) - A.dot(w)\n            k &= ~sigma_clip(res, sigma=3).mask\n\n        test_f = np.linspace(\n            np.log10(gf_mask.min()),\n            np.log10(gf_mask.max()),\n            100,\n        )\n        test_r = np.arange(lower_radius_limit, upper_radius_limit, 0.125)\n        test_r2, test_f2 = np.meshgrid(test_r, test_f)\n\n        test_A = make_A_edges(test_r2.ravel(), test_f2.ravel(), type=dm_type)\n        test_val = test_A.dot(w).reshape(test_r2.shape)\n\n        # find radius where flux > cut\n        lr = np.zeros(len(test_f)) * np.nan\n        for idx in range(len(test_f)):\n            loc = np.where(10 ** test_val[idx] < flux_cut_off)[0]\n            if len(loc) > 0:\n                lr[idx] = test_r[loc[0]]\n\n        ok = np.isfinite(lr)\n        polifit_results = np.polyfit(test_f[ok], lr[ok], 2)\n        source_radius_limit = np.polyval(polifit_results, np.log10(gf))\n        source_radius_limit[\n            source_radius_limit > upper_radius_limit\n        ] = upper_radius_limit\n        source_radius_limit[\n            source_radius_limit < lower_radius_limit\n        ] = lower_radius_limit\n\n        self.radius = source_radius_limit + 0.5\n        # self.source_mask = sparse.csr_matrix(self.r.value < self.radius[:, None])\n\n        # remove pixels outside the radius limit\n        source_mask = []\n        for s in range(self.r.shape[0]):\n            nonz_idx = self.r[s].nonzero()\n            rad_mask = self.r[s].data < self.radius[s]\n            aux = sparse.csr_matrix(\n                (\n                    self.r[s].data[rad_mask],\n                    (nonz_idx[0][rad_mask], nonz_idx[1][rad_mask]),\n                ),\n                shape=self.r[s].shape,\n            ).astype(bool)\n            source_mask.append(aux)\n        source_mask = sparse.vstack(source_mask, \"csr\")\n        self.source_mask = source_mask\n\n        if plot:\n            fig, ax = plt.subplots(1, 2, figsize=(14, 5), facecolor=\"white\")\n\n            ax[0].scatter(r_mask, f_mask, s=0.4, c=\"k\", alpha=0.5, label=\"Data\")\n            ax[0].scatter(\n                r_mask[k],\n                f_mask[k],\n                s=0.4,\n                c=\"g\",\n                alpha=0.5,\n                label=\"Data clipped\",\n                rasterized=True,\n            )\n            ax[0].scatter(\n                r_mask[k], A[k].dot(w), c=\"r\", s=0.4, alpha=0.7, label=\"Model\"\n            )\n            ax[0].set(\n                xlabel=(\"Radius from Source [pix]\"), ylabel=(\"log$_{10}$ Kepler Flux\")\n            )\n            ax[0].legend(frameon=True, loc=\"upper right\")\n\n            im = ax[1].pcolormesh(\n                test_f2,\n                test_r2,\n                10 ** test_val,\n                vmin=0,\n                vmax=500,\n                cmap=\"viridis\",\n                shading=\"auto\",\n                rasterized=True,\n            )\n            line = np.polyval(np.polyfit(test_f[ok], lr[ok], 2), test_f)\n            line[line > upper_radius_limit] = upper_radius_limit\n            line[line < lower_radius_limit] = lower_radius_limit\n            ax[1].plot(test_f, line, color=\"r\", label=\"Best Fit PSF Edge\")\n            ax[1].legend(frameon=True, loc=\"upper left\")\n            cbar = plt.colorbar(im, ax=ax)\n            cbar.set_label(r\"PSF Flux [$e^-s^{-1}$]\")\n\n            ax[1].set(\n                ylabel=(\"Radius from Source [pix]\"),\n                xlabel=(\"log$_{10}$ Source Flux\"),\n            )\n            if not self.show:\n                fig_name = \"%s/data/figures/%s/channel_%02i_psf_edge_model_%s.png\" % (\n                    DATAOUTDIR,\n                    str(self.quarter),\n                    self.channel,\n                    dm_type,\n                )\n                if not os.path.isdir(\"%s/data/figures/%i\" % (DATAOUTDIR, self.quarter)):\n                    os.makedirs(\"%s/data/figures/%i\" % (DATAOUTDIR, self.quarter))\n\n                plt.savefig(fig_name, format=\"png\", bbox_inches=\"tight\")\n                plt.close()\n                return\n\n            plt.show()\n\n        return\n\n    def _get_uncontaminated_source_mask(self):\n        \"\"\"\n        creates a mask of shape nsources x npixels where targets are not contaminated.\n        This mask is used to select pixels to build the PSF model.\n        \"\"\"\n\n        warnings.filterwarnings(\"ignore\", category=sparse.SparseEfficiencyWarning)\n        warnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n\n        self.uncontaminated_source_mask = self.source_mask.multiply(\n            self.source_mask.sum(axis=0) == 1\n        ).tocsr()\n        self.uncontaminated_source_mask.eliminate_zeros()\n\n    # @profile\n    def _build_prf_shape(self, n_r_knots=10, n_phi_knots=12, cut_r=1.5, flux_cut_off=1):\n        \"\"\"\n        Builds a sparse model matrix of shape nsources x npixels to be used when\n        fitting each source pixels to estimate its PSF photometry\n\n        Parameters\n        ----------\n        n_r_knots : int\n            Number of radial knots in the spline model.\n        n_phi_knots : int\n            Number of azimuthal knots in the spline model.\n        cut_r : int\n            Distance at which the spline Design matrix has only dependency in the\n            radial axis.\n        flux_cut_off: float\n            The flux in COUNTS at which to stop evaluating the model.\n        \"\"\"\n\n        flux_estimates = self.gf\n        self.n_r_knots = n_r_knots\n        self.n_phi_knots = n_phi_knots\n        self.cut_r = cut_r\n\n        # mean flux values using uncontaminated mask and normalized by flux estimations\n        mean_f = np.log10(\n            self.uncontaminated_source_mask.astype(float)\n            .multiply(self.dflux)\n            .multiply(1 / flux_estimates[:, None])\n            .data\n        )\n        mean_f_err = np.abs(\n            self.uncontaminated_source_mask.astype(float)\n            .multiply(self.dflux_err)\n            .multiply(1 / flux_estimates[:, None])\n            .data\n        )\n        phi_b = self.uncontaminated_source_mask.multiply(self.phi).data\n        r_b = self.uncontaminated_source_mask.multiply(self.r).data\n\n        # build a design matrix A with b-splines basis in radius and angle axis.\n        try:\n            A = _make_A_polar(\n                phi_b.ravel(),\n                r_b.ravel(),\n                cut_r=self.cut_r,\n                rmin=self.rmin,\n                rmax=self.rmax,\n                n_r_knots=self.n_r_knots,\n                n_phi_knots=self.n_phi_knots,\n            )\n        except ValueError:\n            A = _make_A_polar(\n                phi_b.ravel(),\n                r_b.ravel(),\n                cut_r=self.cut_r,\n                rmin=self.rmin,\n                rmax=np.percentile(r_b.ravel(), 98),\n                n_r_knots=self.n_r_knots,\n                n_phi_knots=self.n_phi_knots,\n            )\n            self.rmax = np.percentile(r_b.ravel(), 98)\n        prior_sigma = np.ones(A.shape[1]) * 100\n        prior_mu = np.zeros(A.shape[1]) - 10\n        nan_mask = np.isfinite(mean_f.ravel())\n\n        # we solve for A * psf_w = mean_f\n        for count in [0, 1, 2]:\n            psf_w = solve_linear_model(\n                A,\n                mean_f.ravel(),\n                k=nan_mask,\n                prior_mu=prior_mu,\n                prior_sigma=prior_sigma,\n                errors=False,\n            )\n            res = np.ma.masked_array(mean_f.ravel(), ~nan_mask) - A.dot(psf_w)\n            nan_mask &= ~sigma_clip(res, sigma=3).mask\n\n        self.psf_w = psf_w\n\n        # We evaluate our DM and build PSF models per source\n        self._get_mean_model()\n        # mean_model = mean_model.multiply(1 / mean_model.sum(axis=1))\n\n        #  re-estimate source flux (from CH updates)\n        prior_mu = flux_estimates\n        prior_sigma = np.ones(self.mean_model.shape[0]) * 10 * flux_estimates\n\n        X = self.mean_model.copy().T\n\n        fmean = self.uncontaminated_source_mask.astype(float).multiply(self.dflux).data\n        femean = (\n            self.uncontaminated_source_mask.astype(float).multiply(self.dflux_err).data\n        )\n\n        ws, werrs = solve_linear_model(\n            X,\n            fmean,\n            y_err=femean,\n            k=None,\n            prior_mu=prior_mu,\n            prior_sigma=prior_sigma,\n            errors=True,\n        )\n\n        # Rebuild source mask\n        ok = np.abs(ws - flux_estimates) / werrs > 3\n        ok &= ((ws / flux_estimates) < 10) & ((flux_estimates / ws) < 10)\n        ok &= ws > 10\n        ok &= werrs > 0\n\n        flux_estimates[ok] = ws[ok]\n\n        self.source_mask = (\n            self.mean_model.multiply(self.mean_model.T.dot(flux_estimates)).tocsr()\n            > flux_cut_off\n        )\n        # rebuild uncontaminated_source_mask\n        self._get_uncontaminated_source_mask()\n\n        # set new rmax for spline basis\n        self.rmax = np.minimum(\n            self.rmax,\n            np.percentile(self.uncontaminated_source_mask.multiply(self.r).data, 99.9),\n        )\n        self._get_mean_model()\n\n        self.mean_flux = np.log10(\n            self.uncontaminated_source_mask.astype(float)\n            .multiply(self.dflux)\n            .multiply(1 / flux_estimates[:, None])\n            .data\n        )\n\n        print(\n            \"Total number of pixels data used for model fitting: \", self.mean_flux.shape\n        )\n\n        if self.save:\n            self.save_model()\n\n        if self.plot:\n            self.plot_prf_shape()\n\n        return\n\n    def _get_mean_model(self):\n        \"\"\"\n        Convenience function to make the scene PRF model\n        \"\"\"\n        Ap = _make_A_polar(\n            self.uncontaminated_source_mask.multiply(self.phi).data,\n            self.uncontaminated_source_mask.multiply(self.r).data,\n            rmin=self.rmin,\n            rmax=self.rmax,\n            cut_r=self.cut_r,\n            n_r_knots=self.n_r_knots,\n            n_phi_knots=self.n_phi_knots,\n        )\n\n        # And create a `mean_model` that has the psf model for all pixels with fluxes\n        mean_model = sparse.csr_matrix(self.r.shape)\n        m = 10 ** Ap.dot(self.psf_w)\n        m[~np.isfinite(m)] = 0\n        mean_model[self.uncontaminated_source_mask] = m\n        mean_model.eliminate_zeros()\n        self.mean_model = mean_model\n        self.design_matrix = Ap\n\n        return\n\n    def build_prf_model(self, n_r_knots=5, n_phi_knots=15):\n        \"\"\"\n        Function that creates a PRF shape using the sources. In combines all other\n        helping functions that build the source mask, remove contaminated pixels,\n        estimate PRF edges, and create the final PRF model.\n\n        For details see:\n            `self._create_sparse()`\n            `self._get_source_mask()`\n            `self._get_uncontaminated_source_mask()`\n            `self._build_prf_shape()`\n\n        Default parameters where used for Martinez-Palomera et al. 2021.\n\n        Parameters\n        ----------\n        n_r_knots : int\n            Number of radial knots in the spline model.\n        n_phi_knots : int\n            Number of azimuthal knots in the spline model.\n        \"\"\"\n        psf._create_sparse()\n        psf._get_source_mask(\n            upper_radius_limit=5,\n            lower_radius_limit=1.1,\n            flux_cut_off=50,\n            dm_type=\"rf-quadratic\",\n        )\n        psf._get_uncontaminated_source_mask()\n        psf._build_prf_shape(\n            n_r_knots=n_r_knots, n_phi_knots=n_phi_knots, flux_cut_off=1\n        )\n\n    def save_model(self, path=None):\n        \"\"\"\n        Function to save the PRF model weights, number of knots for r and phy, and\n        rmin and rmax to re-build the Design Matrix.\n        The file is a csv table, that contain a multi-index column table. Rows are each\n        channel, and columns are:\n            [\"n_r_knots\", \"n_phi_knots\", \"rmin\", \"rmax\", ...prf_ws...]\n        This file can be loaded as:\n            pd.read_csv(fname, index_col=0, header=[0, 1])\n\n        Note: models with different number of knots lead to different number of weights,\n        and ins necessary to create separete files to preserve the esctructure.\n\n        Parameters\n        ----------\n        path : string\n            Path of the file\n        \"\"\"\n        if path is None:\n            fname = \"%s/data/ffi_prf_models_v0.1.1.csv\" % (PACKAGEDIR)\n        else:\n            fname = path\n\n        arr_to_save = np.array(\n            [self.n_r_knots, self.n_phi_knots, self.rmin, self.rmax]\n            + self.psf_w.tolist()\n        )\n\n        if not os.path.isfile(fname):\n            df_dict = {\n                self.quarter: pd.DataFrame(\n                    np.atleast_2d(arr_to_save),\n                    index=[self.channel],\n                    columns=[\"n_r_knots\", \"n_phi_knots\", \"rmin\", \"rmax\"]\n                    + [\"w%02i\" % i for i in range(1, 1 + len(self.psf_w))],\n                )\n            }\n            df = pd.concat(df_dict, axis=1, keys=df_dict.keys())\n            df.to_csv(fname)\n\n        else:\n            df = pd.read_csv(fname, index_col=0, header=[0, 1])\n\n            if str(self.quarter) in df.columns.levels[0]:\n                if self.channel in df.index:\n                    if (\n                        int(df.loc[self.channel, (str(self.quarter), \"n_r_knots\")])\n                        != self.n_r_knots\n                        or int(df.loc[self.channel, (str(self.quarter), \"n_phi_knots\")])\n                        != self.n_phi_knots\n                    ):\n                        raise ValueError(\n                            \"Number of knots for r or phi in the file does not\"\n                            + \"matches the number used in the current model. \"\n                            + \"Create a new file for current model.\"\n                        )\n                df.loc[self.channel, str(self.quarter)] = arr_to_save\n            else:\n                df_dict = {\n                    self.quarter: pd.DataFrame(\n                        np.atleast_2d(arr_to_save),\n                        index=[self.channel],\n                        columns=[\"n_r_knots\", \"n_phi_knots\", \"rmin\", \"rmax\"]\n                        + [\"b%02i\" % i for i in range(1, 1 + len(self.psf_w))],\n                    )\n                }\n                df_new = pd.concat(df_dict, axis=1, keys=df_dict.keys())\n                df = pd.concat([df, df_new], axis=1)\n\n            # df.to_csv(fname)\n\n        return\n\n    def save_model_retro(self, path=None):\n        \"\"\"\n        Function to save the PRF model as a pickle file.\n        Depricated.\n\n        Parameters\n        ----------\n        path : string\n            Path of the file\n        \"\"\"\n        model_data = dict(\n            psf_w=self.psf_w,\n            A=self.design_matrix,\n            x_data=self.uncontaminated_source_mask.multiply(self.dx).data,\n            y_data=self.uncontaminated_source_mask.multiply(self.dy).data,\n            f_data=self.mean_flux,\n            f_model=np.log10(self.mean_model.data),\n            rmin=self.rmin,\n            rmax=self.rmax,\n            n_r_knots=self.n_r_knots,\n            n_phi_knots=self.n_phi_knots,\n        )\n\n        if self.save:\n            if path is None:\n                output = \"%s/data/models/%i/channel_%02i_psf_model.pkl\" % (\n                    DATAOUTDIR,\n                    self.quarter,\n                    self.channel,\n                )\n                if not os.path.isdir(\"%s/data/models/%i\" % (DATAOUTDIR, self.quarter)):\n                    os.makedirs(\"%s/data/models/%i\" % (DATAOUTDIR, self.quarter))\n            else:\n                output = path\n            with open(output, \"wb\") as file:\n                pickle.dump(model_data, file)\n        return\n\n    def plot_prf_shape(self):\n        \"\"\"\n        Function to plot the PRF model in Cartesian and Polar coordinates\n        \"\"\"\n        ylim = self.uncontaminated_source_mask.multiply(self.r).data.max() * 1.1\n        vmin = -3\n        vmax = -0.5\n\n        phy = self.uncontaminated_source_mask.multiply(self.phi).data\n        r = self.uncontaminated_source_mask.multiply(self.r).data\n        x = self.uncontaminated_source_mask.multiply(self.dx).data\n        y = self.uncontaminated_source_mask.multiply(self.dy).data\n\n        fig, ax = plt.subplots(2, 2, figsize=(12, 8))\n        ax[0, 0].set_title(\"Mean flux\")\n        cax = ax[0, 0].scatter(\n            phy,\n            r,\n            c=self.mean_flux,\n            marker=\".\",\n            s=2,\n            vmin=vmin,\n            vmax=vmax,\n            rasterized=True,\n        )\n        ax[0, 0].set_ylim(0, ylim)\n        fig.colorbar(cax, ax=ax[0, 0])\n        ax[0, 0].set_ylabel(r\"$r$ [pixels]\")\n        ax[0, 0].set_xlabel(r\"$\\phi$ [rad]\")\n\n        ax[0, 1].set_title(\"Average PSF Model\")\n        cax = cax = ax[0, 1].scatter(\n            phy,\n            r,\n            c=np.log10(self.mean_model.data),\n            marker=\".\",\n            s=2,\n            vmin=vmin,\n            vmax=vmax,\n            rasterized=True,\n        )\n        ax[0, 1].set_ylim(0, ylim)\n        fig.colorbar(cax, ax=ax[0, 1])\n        ax[0, 1].set_xlabel(r\"$\\phi$ [rad]\")\n\n        cax = ax[1, 0].scatter(\n            x,\n            y,\n            c=self.mean_flux,\n            marker=\".\",\n            s=2,\n            vmin=vmin,\n            vmax=vmax,\n            rasterized=True,\n        )\n        fig.colorbar(cax, ax=ax[1, 0])\n        ax[1, 0].set_ylabel(\"dy\")\n        ax[1, 0].set_xlabel(\"dx\")\n\n        cax = ax[1, 1].scatter(\n            x,\n            y,\n            c=np.log10(self.mean_model.data),\n            marker=\".\",\n            s=2,\n            vmin=vmin,\n            vmax=vmax,\n            rasterized=True,\n        )\n        fig.colorbar(cax, ax=ax[1, 1])\n        ax[1, 1].set_xlabel(\"dx\")\n\n        if not self.show:\n            fig_name = \"%s/data/figures/%s/channel_%02i_psf_model.png\" % (\n                DATAOUTDIR,\n                str(self.quarter),\n                self.channel,\n            )\n            if not os.path.isdir(\n                \"%s/data/figures/%s\" % (DATAOUTDIR, str(self.quarter))\n            ):\n                os.makedirs(\"%s/data/figures/%s\" % (DATAOUTDIR, str(self.quarter)))\n            plt.savefig(fig_name, format=\"png\", bbox_inches=\"tight\")\n            plt.close()\n        else:\n            plt.show()\n\n    # @profile\n    def fit_model(self):\n        \"\"\"\n        Function to fit the PRF model and do LFD photometry for the sources observed in\n        the FFIs.\n        \"\"\"\n        prior_mu = self.gf\n        prior_sigma = np.ones(self.mean_model.shape[0]) * 5 * np.abs(self.gf) ** 0.5\n\n        X = self.mean_model.copy()\n        X = X.T\n        f = self.flux\n        fe = self.flux_err\n\n        self.ws, self.werrs = solve_linear_model(\n            X, f, y_err=fe, prior_mu=prior_mu, prior_sigma=prior_sigma, errors=True\n        )\n        self.model_flux = X.dot(self.ws)\n\n        nodata = np.asarray(self.source_mask.sum(axis=1))[:, 0] == 0\n        # These sources are poorly estimated\n        nodata |= (self.mean_model.max(axis=1) > 1).toarray()[:, 0]\n        self.ws[nodata] *= np.nan\n        self.werrs[nodata] *= np.nan\n\n        return\n\n    def save_catalog(self):\n        \"\"\"\n        Function to save the Photometry Catalog of FFI sources\n        \"\"\"\n        df = pd.DataFrame(\n            [\n                self.sources.designation,\n                self.sources.ra,\n                self.sources.dec,\n                self.sources.col,\n                self.sources.row,\n                self.ws,\n                self.werrs,\n            ],\n            index=[\"Gaia_source_id\", \"RA\", \"DEC\", \"Column\", \"Row\", \"Flux\", \"Flux_err\"],\n        ).T\n\n        if not os.path.isdir(\"%s/data/catalogs/ffi/source_catalog/\" % (DATAOUTDIR)):\n            os.makedirs(\"%s/data/catalogs/ffi/source_catalog/\" % (DATAOUTDIR))\n        df.to_csv(\n            \"%s/data/catalogs/ffi/source_catalog/channel_%s_source_catalog_mjd_%s.csv\"\n            % (DATAOUTDIR, self.channel, str(self.hdr[\"MJDSTART\"]))\n        )\n\n    def plot_image(self, ax=None, sources=False):\n        \"\"\"\n        Function to plot the Full Frame Image and the Gaia Sources\n\n        Parameters\n        ----------\n        ax : matplotlib.axes\n            Matlotlib axis can be provided, if not one will be created and returned\n        sources : boolean\n            Whether to overplot or not the source catalog\n\n        Returns\n        -------\n        ax : matplotlib.axes\n            Matlotlib axis with the figure\n        \"\"\"\n        if ax is None:\n            fig, ax = plt.subplots(1, figsize=(10, 10))\n        ax = plt.subplot(projection=self.wcs)\n        im = ax.imshow(\n            self.flux_2d,\n            cmap=plt.cm.viridis,\n            origin=\"lower\",\n            norm=colors.SymLogNorm(linthresh=200, vmin=0, vmax=2000, base=10),\n            rasterized=True,\n        )\n        plt.colorbar(im, ax=ax, label=r\"Flux ($e^{-}s^{-1}$)\", fraction=0.042)\n\n        ax.set_title(\"FFI Ch %i\" % (self.channel))\n        ax.set_xlabel(\"R.A. [hh:mm]\")\n        ax.set_ylabel(\"Decl. [deg]\")\n        ax.grid(color=\"white\", ls=\"solid\")\n        ax.set_aspect(\"equal\", adjustable=\"box\")\n\n        if sources:\n            ax.scatter(\n                self.sources.col,\n                self.sources.row,\n                facecolors=\"none\",\n                edgecolors=\"r\",\n                linewidths=0.5,\n                alpha=0.9,\n            )\n\n        if self.save:\n            fig_name = \"%s/data/figures/%s/channel_%02i_ffi_image.png\" % (\n                DATAOUTDIR,\n                str(self.quarter),\n                self.channel,\n            )\n            if not os.path.isdir(\n                \"%s/data/figures/%s\" % (DATAOUTDIR, str(self.quarter))\n            ):\n                os.makedirs(\"%s/data/figures/%s\" % (DATAOUTDIR, str(self.quarter)))\n            plt.savefig(fig_name, format=\"png\", bbox_inches=\"tight\")\n\n        return ax\n\n    def plot_pixel_masks(self, ax=None):\n        \"\"\"\n        Function to plot the mask used to reject saturated and bright pixels\n\n        Parameters\n        ----------\n        ax : matplotlib.axes\n            Matlotlib axis can be provided, if not one will be created and returned\n\n        Returns\n        -------\n        ax : matplotlib.axes\n            Matlotlib axis with the figure\n        \"\"\"\n        if ax is None:\n            fig, ax = plt.subplots(1, figsize=(10, 10))\n        ax.scatter(\n            self.col_2d.ravel()[self.non_sat_mask][~self.bright_mask],\n            self.row_2d.ravel()[self.non_sat_mask][~self.bright_mask],\n            c=\"r\",\n            marker=\".\",\n            label=\"bright\",\n        )\n        ax.scatter(\n            self.col_2d.ravel()[~self.non_sat_mask],\n            self.row_2d.ravel()[~self.non_sat_mask],\n            c=\"y\",\n            marker=\".\",\n            label=\"saturated\",\n        )\n        ax.legend(loc=\"best\")\n\n        ax.set_xlabel(\"Column Pixel Number\")\n        ax.set_ylabel(\"Row Pixel Number\")\n        ax.set_title(\"Pixel Mask\")\n\n        if self.save:\n            fig_name = \"%s/data/figures/%s/channel_%02i_ffi_pixel_mask.png\" % (\n                DATAOUTDIR,\n                str(self.quarter),\n                self.channel,\n            )\n            if not os.path.isdir(\n                \"%s/data/figures/%s\" % (DATAOUTDIR, str(self.quarter))\n            ):\n                os.makedirs(\"%s/data/figures/%s\" % (DATAOUTDIR, str(self.quarter)))\n            plt.savefig(fig_name, format=\"png\", bbox_inches=\"tight\")\n\n        return ax\n", "meta": {"hexsha": "cc710493be9245798e85ebe82cfa330d1baabdb4", "size": 48555, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/kepler_apertures/KeplerFFI.py", "max_stars_repo_name": "jorgemarpa/kepler-apertures", "max_stars_repo_head_hexsha": "a9a3842016a05a57e79fd47338bef0aa354bb148", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kepler_apertures/KeplerFFI.py", "max_issues_repo_name": "jorgemarpa/kepler-apertures", "max_issues_repo_head_hexsha": "a9a3842016a05a57e79fd47338bef0aa354bb148", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kepler_apertures/KeplerFFI.py", "max_forks_repo_name": "jorgemarpa/kepler-apertures", "max_forks_repo_head_hexsha": "a9a3842016a05a57e79fd47338bef0aa354bb148", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.623624358, "max_line_length": 89, "alphanum_fraction": 0.5480177119, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 11735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.1766465712546257}}
{"text": "'''\r\nThis algorithm is a standard TD3 algorithm. \r\nOriginal paper: https://arxiv.org/abs/1802.09477.\r\n'''\r\nimport pickle\r\nimport numpy as np\r\n\r\nimport torch\r\nimport torch.nn as nn\r\n\r\nfrom TD3_based_DRL.priority_replay import Memory\r\nfrom TD3_based_DRL.network_model import Actor,Critic\r\nfrom TD3_based_DRL.util import hard_update, soft_update\r\n\r\nseed = 2\r\ntorch.manual_seed(seed)\r\ntorch.cuda.manual_seed(seed)\r\nnp.random.seed(seed)\r\ntorch.manual_seed(seed)\r\ntorch.backends.cudnn.deterministic = True\r\ntorch.backends.cudnn.benchmark = False\r\n\r\nMEMORY_CAPACITY = 38400\r\nBATCH_SIZE = 128\r\nGAMMA = 0.95\r\nLR_C = 0.0005\r\nLR_A = 0.0002\r\nLR_I = 0.01\r\nTAU = 0.001\r\nPOLICY_NOSIE = 0.2\r\nPOLICY_FREQ = 1\r\nNOISE_CLIP = 0.5\r\n\r\nclass DRL:\r\n        \r\n    def __init__(self,action_dim,state_dim, LR_C = LR_C, LR_A = LR_A):\r\n        self.use_cuda = True\r\n        \r\n        self.state_dim = state_dim[0] * state_dim[1]\r\n        self.state_dim_width = state_dim[0]\r\n        self.state_dim_height = state_dim[1]\r\n        self.action_dim = action_dim\r\n        self.batch_size = BATCH_SIZE\r\n        self.gamma = GAMMA\r\n        self.tau = TAU\r\n        self.policy_noise = POLICY_NOSIE\r\n        self.noise_clip = NOISE_CLIP\r\n        self.policy_freq = POLICY_FREQ\r\n        self.itera = 0\r\n\r\n        self.pointer = 0\r\n        self.memory = Memory(MEMORY_CAPACITY)\r\n        \r\n        self.actor = Actor(self.state_dim,self.action_dim).to(self.device)\r\n        self.actor_target = Actor(self.state_dim,self.action_dim).to(self.device)\r\n        self.actor_optimizer = torch.optim.Adam(self.actor.parameters(),LR_A)\r\n        \r\n        self.critic = Critic(self.state_dim,self.action_dim).to(self.device)\r\n        self.critic_target = Critic(self.state_dim,self.action_dim).to(self.device)\r\n        self.critic_optimizers = torch.optim.Adam(self.critic.parameters(),LR_C)\r\n        \r\n        hard_update(self.actor_target,self.actor)\r\n        hard_update(self.critic_target,self.critic)\r\n\r\n            \r\n    def learn(self, batch_size=BATCH_SIZE, epoch=0):\r\n\r\n        ## batched state, batched action, batched reward, batched next state\r\n        bs, ba, ba_e, bi, br, bs_, tree_idx, ISweight = self.retrive(batch_size)\r\n        bs = torch.tensor(bs, dtype=torch.float).reshape(batch_size, self.state_dim_height, self.state_dim_width).to(self.device)\r\n        ba = torch.tensor(ba, dtype=torch.float).to(self.device)\r\n        br = torch.tensor(br, dtype=torch.float).to(self.device)\r\n        bs_ = torch.tensor(bs_, dtype=torch.float).reshape(batch_size, self.state_dim_height, self.state_dim_width).to(self.device)\r\n        \r\n        # initialize the loss variables\r\n        loss_c, loss_a = 0, 0\r\n\r\n        ## calculate the predicted values of the critic\r\n        with torch.no_grad():\r\n            noise = (torch.randn_like(ba) * self.policy_noise).clamp(0, 1)\r\n            a_ = (self.actor_target(bs_).detach() + noise).clamp(0, 1)\r\n            target_q1, target_q2 = self.critic_target([bs_,a_])\r\n            target_q1 = target_q1.detach()\r\n            target_q2 = target_q2.detach()\r\n            target_q = torch.min(target_q1,target_q2)\r\n            y_expected = br + self.gamma * target_q   \r\n        y_predicted1, y_predicted2 = self.critic.forward([bs,ba])    \r\n        \r\n        ## update the critic\r\n        critic_loss = nn.MSELoss()\r\n        loss_critic = critic_loss(y_predicted1,y_expected)+critic_loss(y_predicted2,y_expected)\r\n        self.critic_optimizers.zero_grad()\r\n        loss_critic.backward()\r\n        self.critic_optimizers.step()\r\n        \r\n        ## update the actor\r\n        if self.itera % self.policy_freq == 0:\r\n\r\n            pred_a = self.actor.forward(bs)\r\n            loss_actor = (-self.critic.forward([bs,pred_a])[0])\r\n\r\n            self.actor_optimizer.zero_grad()\r\n            loss_actor.mean().backward()\r\n            self.actor_optimizer.step()\r\n\r\n            soft_update(self.actor_target,self.actor,self.tau)\r\n            soft_update(self.critic_target,self.critic,self.tau)\r\n\r\n            loss_a = loss_actor.mean().item()\r\n\r\n        loss_c = loss_critic.mean().item()\r\n\r\n        self.itera += 1\r\n\r\n        self.memory.batch_update(tree_idx, abs(errors.detach().cpu().numpy()) )\r\n\r\n        return loss_c, loss_a\r\n    \r\n                \r\n    def choose_action(self,state):\r\n\r\n        state = torch.tensor(state,dtype=torch.float).reshape(self.state_dim_height, self.state_dim_width).to(self.device)\r\n        state = state.unsqueeze(0)\r\n        \r\n        action = self.actor.forward(state).detach()\r\n        action = action.squeeze(0).cpu().numpy()\r\n        action = np.clip(action,-1, 1)\r\n\r\n        return action\r\n    \r\n    \r\n    '''\r\n    To conveniently implement all the algorithms in the same training script, the memory buffer here\r\n    keeps the same shape as other human-guidance DRL algorithms. However, in this vanilla TD3 algorithm,\r\n    the human-guidance-related indicators, i.e., action from the human expert, and the intervention signal, \r\n    are not available in fact.\r\n    '''\r\n    def store_transition(self, s, a, a_e, i, r, s_):\r\n\r\n        transition = np.hstack((s, a, a_e, i, r, s_))  \r\n        self.memory.store(transition)\r\n        self.pointer += 1\r\n    \r\n\r\n    def retrive(self, batch_size):\r\n\r\n        tree_index, bt, ISWeight = self.memory.sample(batch_size)   \r\n        bs = bt[:, :self.state_dim]\r\n        ba = bt[:, self.state_dim: self.state_dim + self.action_dim]\r\n        ba_e = bt[:, self.state_dim + self.action_dim: self.state_dim + self.action_dim + self.action_dim]\r\n        bi = bt[:, -self.state_dim - 2: -self.state_dim - 1]\r\n        br = bt[:, -self.state_dim - 1: -self.state_dim]\r\n        bs_ = bt[:, -self.state_dim:]\r\n        \r\n        return bs, ba, ba_e, bi, br, bs_, tree_index, ISWeight\r\n    \r\n\r\n    def memory_save(self):\r\n        \r\n        per = open(\"memory.pkl\", 'wb')\r\n        str = pickle.dumps(self.memory)\r\n        per.write(str)\r\n        per.close()\r\n    \r\n\r\n    def memory_load(self):\r\n        \r\n        with open(\"memory.pkl\",'rb') as file:\r\n            self.memory  = pickle.loads(file.read())\r\n            \r\n\r\n    def load_model(self, output):\r\n        if output is None: return\r\n        self.actor.load_state_dict(torch.load('{}/actor.pkl'.format(output)))\r\n        self.critic.load_state_dict(torch.load('{}/critic.pkl'.format(output)))\r\n\r\n\r\n    def save_model(self, output):\r\n        torch.save(self.actor.state_dict(), '{}/actor.pkl'.format(output))\r\n        torch.save(self.critic.state_dict(), '{}/critic.pkl'.format(output))\r\n        \r\n\r\n    def save(self, log_dir, epoch):\r\n        state = {'actor':self.actor.state_dict(), 'actor_target':self.actor_target.state_dict(),\r\n                 'actor_optimizer':self.actor_optimizer.state_dict(), \r\n                 'critic':self.critic.state_dict(), 'critic_target':self.critic_target.state_dict(),\r\n                 'critic_optimizers':self.critic_optimizers.state_dict(),\r\n                 'epoch':epoch}\r\n        torch.save(state, log_dir)\r\n        \r\n\r\n    def load(self, log_dir):\r\n        checkpoint = torch.load(log_dir)\r\n        self.actor.load_state_dict(checkpoint['actor'])\r\n        self.actor_target.load_state_dict(checkpoint['actor_target'])\r\n        self.actor_optimizer.load_state_dict(checkpoint['actor_optimizer'])\r\n        self.critic.load_state_dict(checkpoint['critic'])\r\n        self.critic_target.load_state_dict(checkpoint['critic_target'])\r\n        self.critic_optimizers.load_state_dict(checkpoint['critic_optimizers'])\r\n        \r\n\r\n        \r\n        \r\n        \r\n        \r\n        \r\n        \r\n        \r\n", "meta": {"hexsha": "10bba76536df0605f3abe373ff6af11e2c8c315f", "size": 7557, "ext": "py", "lang": "Python", "max_stars_repo_path": "TD3_based_DRL/TD3.py", "max_stars_repo_name": "wujingda/Human-in-the-loop-Deep-Reinforcement-Learning-Hug-DRL-", "max_stars_repo_head_hexsha": "d00667017d586fbfc6487bd6ac8dd5396acae0d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T10:05:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T03:06:21.000Z", "max_issues_repo_path": "TD3_based_DRL/TD3.py", "max_issues_repo_name": "wujingda/Human-in-the-loop-Deep-Reinforcement-Learning", "max_issues_repo_head_hexsha": "d00667017d586fbfc6487bd6ac8dd5396acae0d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TD3_based_DRL/TD3.py", "max_forks_repo_name": "wujingda/Human-in-the-loop-Deep-Reinforcement-Learning", "max_forks_repo_head_hexsha": "d00667017d586fbfc6487bd6ac8dd5396acae0d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1578947368, "max_line_length": 132, "alphanum_fraction": 0.6184994045, "include": true, "reason": "import numpy", "num_tokens": 1758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.1766465676791044}}
{"text": "\"\"\"\nSubstitution of molecular geometries with functional groups.\n\nGiven a cartesian geometry and element labels, a substituent can\nbe added knowing (a) the substituent identity (b) the desired\nposition to substitute and (c) the bond axis for substitution.\n\nThis requires some default information, such as the default structure\nand orientation of the substituent (relative to an axis) and the\nbond length of the substituent. For now, only single bonds are treated.\n\"\"\"\nimport numpy as np\nimport gimbal.displace as displace\nimport gimbal.fileio as fileio\nimport gimbal.constants as con\n\n\nclass SubLib(object):\n    \"\"\"\n    Object containing a library of substituent geometries.\n\n    Attributes\n    ----------\n    syn : dict\n        A dictionary of synonyms used to find the appropriate\n        substituents.\n    elem : dict\n        A dictionary of atomic symbols for each substituent.\n    xyz : dict\n        A dictionary of atomic cartesian coordinates for each\n        substituent.\n    \"\"\"\n    def __init__(self):\n        self.syn = dict()\n        self.elem = dict()\n        self.xyz = dict()\n        self._populate_syn()\n        self._populate_elem()\n        self._populate_xyz()\n        self._add_comb()\n\n    def _populate_syn(self):\n        \"\"\"Adds a dictionary of synonyms for labels.\"\"\"\n        synlist = [['h'],\n                   ['d'],\n                   ['me', 'ch3', 'h3c'],\n                   ['et', 'ch2ch3', 'c2h5', 'ch3ch2'],\n                   ['npr', 'ch2ch2ch3', 'c3h7', 'ch3ch2ch2'],\n                   ['ipr', 'chch3ch3', 'ch(ch3)2', '(ch3)2ch', 'ch3chch3'],\n                   ['nbu', 'ch2ch2ch2ch3', 'c4h9', 'ch3ch2ch2ch2'],\n                   ['ibu', 'chch3ch2ch3', 'ch3chch2ch3', 'ch3ch3chch3'],\n                   ['tbu', 'cch3ch3ch3', 'c(ch3)3', 'ch3ch3ch3c', '(ch3)3c'],\n                   ['vi', 'chch2', 'c2h3', 'h2chc', 'h3c2'],\n                   ['ey', 'cch', 'c2h', 'hcc', 'hc2'],\n                   ['ph', 'c6h5', 'h5c6'],\n                   ['am', 'nh2', 'h2n'],\n                   ['im', 'chnh', 'cnh2', 'nhch'],\n                   ['cn', 'nc'],\n                   ['oh', 'ho'],\n                   ['ome', 'meo', 'och3', 'ch3o'],\n                   ['al', 'cho', 'coh', 'och', 'ohc'],\n                   ['ac', 'coch3', 'cch3o'],\n                   ['ca', 'cooh', 'co2h', 'hooc', 'ho2c'],\n                   ['nt', 'no2', 'o2n'],\n                   ['f'],\n                   ['tfm', 'cf3', 'f3c'],\n                   ['sh', 'hs'],\n                   ['sf', 'so2h', 'sooh', 'sho2', 'ho2s', 'hso2'],\n                   ['ms', 'sfme', 'mesf', 'sfch3', 'so2me', 'so2ch3'],\n                   ['cl']]\n        for subl in synlist:\n            for item in subl:\n                self.syn[item] = subl[0]\n\n    def _populate_elem(self):\n        \"\"\"Adds element labels to self.elem.\"\"\"\n        self.elem['h'] = np.array(['H'])\n        self.elem['d'] = np.array(['D'])\n        self.elem['me'] = np.array(['C', 'H', 'H', 'H'])\n        self.elem['vi'] = np.array(['C', 'C', 'H', 'H', 'H'])\n        self.elem['ey'] = np.array(['C', 'C', 'H'])\n        self.elem['ph'] = np.array(['C', 'C', 'C', 'C', 'C', 'C',\n                                    'H', 'H', 'H', 'H', 'H'])\n        self.elem['am'] = np.array(['N', 'H', 'H'])\n        self.elem['im'] = np.array(['C', 'N', 'H', 'H'])\n        self.elem['cn'] = np.array(['C', 'N'])\n        self.elem['oh'] = np.array(['O', 'H'])\n        self.elem['al'] = np.array(['C', 'O', 'H'])\n        self.elem['nt'] = np.array(['N', 'O', 'O'])\n        self.elem['f'] = np.array(['F'])\n        self.elem['sh'] = np.array(['S', 'H'])\n        self.elem['sf'] = np.array(['S', 'O', 'O', 'H'])\n        self.elem['cl'] = np.array(['Cl'])\n\n    def _populate_xyz(self):\n        \"\"\"Adds cartesian geometries to self.xyz.\n\n        For all substituents, the bonding atom is at the origin,\n        the bonding axis is the z-axis and the plane axis\n        is the y-axis.\n        \"\"\"\n        self.xyz['h'] = np.array([[ 0.000,  0.000,  0.000]])\n        self.xyz['d'] = np.array([[ 0.000,  0.000,  0.000]])\n        self.xyz['me'] = np.array([[ 0.000,  0.000,  0.000],\n                                   [ 0.511, -0.886,  0.377],\n                                   [ 0.511,  0.886,  0.377],\n                                   [-1.023,  0.000,  0.377]])\n        self.xyz['vi'] = np.array([[ 0.000,  0.000,  0.000],\n                                   [-1.124,  0.000,  0.730],\n                                   [ 0.971,  0.000,  0.495],\n                                   [-1.067,  0.000,  1.818],\n                                   [-2.095,  0.000,  0.235]])\n        self.xyz['ey'] = np.array([[ 0.000,  0.000,  0.000],\n                                   [ 0.000,  0.000,  1.210],\n                                   [ 0.000,  0.000,  2.280]])\n        self.xyz['ph'] = np.array([[ 0.000,  0.000,  0.000],\n                                   [-1.212,  0.000,  0.700],\n                                   [ 1.212,  0.000,  0.700],\n                                   [-1.212,  0.000,  2.100],\n                                   [ 1.212,  0.000,  2.100],\n                                   [ 0.000,  0.000,  2.800],\n                                   [-2.156,  0.000,  0.155],\n                                   [ 2.156,  0.000,  0.155],\n                                   [-2.156,  0.000,  2.645],\n                                   [ 2.156,  0.000,  2.645],\n                                   [ 0.000,  0.000,  3.890]])\n        self.xyz['am'] = np.array([[ 0.000,  0.000,  0.000],\n                                   [-0.577, -0.771,  0.332],\n                                   [-0.577,  0.771,  0.332]])\n        self.xyz['im'] = np.array([[ 0.000,  0.000,  0.000],\n                                   [-1.082,  0.000,  0.703],\n                                   [ 0.980,  0.000,  0.499],\n                                   [-0.869,  0.000,  1.710]])\n        self.xyz['cn'] = np.array([[ 0.000,  0.000,  0.000],\n                                   [ 0.000,  0.000,  1.136]])\n        self.xyz['oh'] = np.array([[ 0.000,  0.000,  0.000],\n                                   [-0.913,  0.000,  0.297]])\n        self.xyz['al'] = np.array([[ 0.000,  0.000,  0.000],\n                                   [-1.011,  0.000,  0.700],\n                                   [ 0.998,  0.000,  0.463]])\n        self.xyz['nt'] = np.array([[ 0.000,  0.000,  0.000],\n                                   [-1.105,  0.000,  0.563],\n                                   [ 1.105,  0.000,  0.563]])\n        self.xyz['f'] = np.array([[ 0.000,  0.000,  0.000]])\n        self.xyz['sh'] = np.array([[ 0.000,  0.000,  0.000],\n                                   [-1.331,  0.000,  0.156]])\n        self.xyz['sf'] = np.array([[ 0.000,  0.000,  0.000],\n                                   [ 0.548, -1.266,  0.448],\n                                   [ 0.548,  1.266,  0.448],\n                                   [-1.311,  0.000,  0.279]])\n        self.xyz['cl'] = np.array([[ 0.000,  0.000,  0.000]])\n\n    def _add_comb(self):\n        \"\"\"Adds substituents made by combining multiple substituents.\"\"\"\n        self.elem['et'], self.xyz['et'] = self.add_subs('me', 'me')\n        self.elem['npr'], self.xyz['npr'] = self.add_subs('me', 'me', 'me')\n        self.elem['ipr'], self.xyz['ipr'] = self.add_subs('me', 'me', 'me',\n                                                          inds=1)\n        self.elem['nbu'], self.xyz['nbu'] = self.add_subs('me', 'me', 'me',\n                                                          'me')\n        self.elem['ibu'], self.xyz['ibu'] = self.add_subs('me', 'me', 'me',\n                                                          'me', inds=[2, 1, -1])\n        self.elem['tbu'], self.xyz['tbu'] = self.add_subs('me', 'me', 'me',\n                                                          'me', inds=1)\n        self.elem['ome'], self.xyz['ome'] = self.add_subs('oh', 'me')\n        self.elem['ac'], self.xyz['ac'] = self.add_subs('al', 'me')\n        self.elem['ca'], self.xyz['ca'] = self.add_subs('al', 'oh')\n        self.elem['tfm'], self.xyz['tfm'] = self.add_subs('me', 'f', 'f', 'f',\n                                                          inds=1)\n        self.elem['ms'], self.xyz['ms'] = self.add_subs('sf', 'me')\n\n    def get_sub(self, label):\n        \"\"\"Returns the element list and cartesian geometry of a\n        substituent.\n\n        Parameters\n        ----------\n        label : str\n            The substituent label of the desired substituent.\n\n        Returns\n        -------\n        elem : (N,) ndarray\n            The atomic symbols of the substituent.\n        xyz : (N, 3) ndarray\n            The atomic cartesian coordinates of the substituent.\n        \"\"\"\n        lbl = self.syn[label.lower()]\n        return self.elem[lbl], self.xyz[lbl]\n\n    def add_subs(self, *lbls, inds=-1):\n        \"\"\"Returns the element list and cartesian geometry from a\n        combination of substituents.\n\n        Parameters\n        ----------\n        lbls : list\n            A list of substituent labels to be combined.\n        inds : int or array_like, optional\n            The indices for substitution between substituents. Setting\n            inds=-1 (default) makes the last atom the subtituted atom.\n            Otherwise a list of indices can be given for the first of\n            each pair of substituents.\n\n        Returns\n        -------\n        elem : (N,) ndarray\n            The atomic symbols of the combined substituent.\n        xyz : (N, 3) ndarray\n            The atomic cartesian coordinates of the combined substituent.\n        \"\"\"\n        if isinstance(inds, int):\n            inds = (len(lbls) - 1) * [inds]\n        elif len(inds) != len(lbls) - 1:\n            raise ValueError('Number of inds != number of labels - 1')\n\n        rot = 0\n        lbl0 = self.syn[lbls[0].lower()]\n        elem = self.elem[lbl0]\n        xyz = self.xyz[lbl0]\n        for i, label in zip(inds, lbls[1:]):\n            dist = np.linalg.norm(xyz - xyz[i], axis=1)\n            dist[i] += np.max(dist)\n            ibond = np.argmin(dist)\n            rot = (rot + 1) % 2\n            ax = con.unit_vec(xyz[i] - xyz[ibond])\n            lbl = self.syn[label.lower()]\n            new_elem = self.elem[lbl]\n            new_xyz = displace.rotate(self.xyz[lbl], rot*np.pi, 'Z')\n            new_xyz = displace.align_axis(new_xyz, 'Z', ax)\n            blen = con.get_covrad(elem[ibond]) + con.get_covrad(new_elem[0])\n            new_xyz += xyz[ibond] + blen * ax\n            elem = np.hstack((np.delete(elem, i), new_elem))\n            xyz = np.vstack((np.delete(xyz, i, axis=0), new_xyz))\n\n        return elem, xyz\n\n\ndef import_sub(label):\n    \"\"\"Returns the element list and cartesian geometry of a substituent\n    given its label.\n\n    Parameters\n    ----------\n    label : str\n        The substituent label.\n\n    Returns\n    -------\n    elem : (N,) ndarray\n        The atomic symbols of the substituent.\n    xyz : (N, 3) ndarray\n        The atomic cartesian coordinates of the substituent.\n    \"\"\"\n    lib = SubLib()\n    return lib.get_sub(label)\n\n\ndef subst(elem, xyz, sublbl, isub, ibond=None, pl=None, vec=None):\n    \"\"\"Returns a molecular geometry with an specified atom replaced by\n    substituent.\n\n    Labels are case-insensitive. The index isub gives the position to be\n    substituted. If specified, ibond gives the atom bonded to the\n    substituent. Otherwise, the nearest atom to isub is used. The\n    orientation of the substituent can be given as a vector (the plane\n    normal) or an index (the plane containing isub, ibond and pl).\n\n    If isub is given as a list, the entire list of atoms is removed\n    and the first index is treated as the position of the substituent.\n\n    Parameters\n    ----------\n    elem : (N,) array_like\n        The atomic symbols of the unsubstituted molecule.\n    xyz : (N, 3) array_like\n        The atomic cartesian coordinates of the unsubstituted molecule.\n    sublbl : str\n        The substituent label.\n    isub : int or list\n        The atomic index (or indices) to be replaced by the substituent.\n    ibond : int, optional\n        The atomic index of the atom bonded to position isub. If None\n        (default), the nearest atom is chosen.\n    pl : int or array_like, optional\n        The atomic index or vector defining the xz-plane of the\n        substituent. If an index is given, the plane normal to the\n        isub-ibond-pl plane is used. If None (default), the plane\n        is arbitrarily set to [1, 1, 1] and the bond axis is projected\n        out.\n    vec : (N, 3) array_like, optional\n        The atomic cartesian vectors of the unsubstitued molecule. Default\n        is None.\n\n    Returns\n    -------\n    new_elem : (N,) ndarray\n        The atomic symbols of the substituted molecule.\n    new_xyz : (N, 3) ndarray\n        The atomic cartesian coordinates of the substituted molecule.\n    new_vec : (N, 3) ndarray\n        The atomic cartesian vectors of the substituted molecule.\n        Substituent atoms are all set of zero. If vec is None, new_vec\n        is all zeros.\n    \"\"\"\n    elem = np.array(elem)\n    xyz = np.atleast_2d(xyz)\n    if not isinstance(isub, int):\n        ipos = isub[0]\n    else:\n        isub = [isub]\n        ipos = isub[0]\n\n    if ibond is None:\n        dist = np.linalg.norm(xyz - xyz[ipos], axis=1)\n        dist[ipos] += np.max(dist)\n        ibond = np.argmin(dist)\n    elif ibond == ipos:\n        raise ValueError('sub and bond indices cannot be the same')\n\n    ax = con.unit_vec(xyz[ipos] - xyz[ibond])\n    if pl is None:\n        # choose an arbitrary axis and project out the bond axis\n        pl = np.ones(3)\n        pl -= np.dot(pl, ax) * ax\n    elif isinstance(pl, int):\n        if pl == ipos:\n            raise ValueError('plane and sub indices cannot be the same')\n        elif pl == ibond:\n            raise ValueError('plane and bond indices cannot be the same')\n        pl = np.cross(xyz[ipos] - xyz[ibond], xyz[pl] - xyz[ibond])\n\n    sub_el, sub_xyz = import_sub(sublbl)\n    if elem[ipos] == sub_el[0]:\n        blen = np.linalg.norm(xyz[ipos] - xyz[ibond])\n    else:\n        blen = con.get_covrad(elem[ibond]) + con.get_covrad(sub_el[0])\n\n    # rotate to correct orientation and displace to correct position\n    sub_xyz = displace.align_axis(sub_xyz, 'Z', ax)\n    sub_pl = displace.align_axis([0., 1., 0.], 'Z', ax)\n    sub_xyz = displace.align_axis(sub_xyz, sub_pl, pl)\n    sub_xyz += xyz[ibond] + blen * ax\n\n    # build the final geometry\n    ind1 = [i for i in range(ipos) if i not in isub[1:]]\n    ind2 = [i for i in range(ipos+1, len(elem)) if i not in isub[1:]]\n    new_elem = np.hstack((elem[ind1], sub_el, elem[ind2]))\n    new_xyz = np.vstack((xyz[ind1], sub_xyz, xyz[ind2]))\n    if vec is None:\n        return new_elem, new_xyz, None\n    else:\n        new_vec = np.vstack((vec[ind1], np.zeros((len(sub_el), 3)), vec[ind2]))\n        return new_elem, new_xyz, new_vec\n", "meta": {"hexsha": "730273d5b17c589f473fc10245b38435839d1a5a", "size": 14876, "ext": "py", "lang": "Python", "max_stars_repo_path": "gimbal/substitute.py", "max_stars_repo_name": "ryjmacdonell/geomtools", "max_stars_repo_head_hexsha": "f68252db8334f390801ce3af528fc7c298232c5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gimbal/substitute.py", "max_issues_repo_name": "ryjmacdonell/geomtools", "max_issues_repo_head_hexsha": "f68252db8334f390801ce3af528fc7c298232c5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2016-10-17T21:22:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-28T20:50:03.000Z", "max_forks_repo_path": "gimbal/substitute.py", "max_forks_repo_name": "ryjmacdonell/geomtools", "max_forks_repo_head_hexsha": "f68252db8334f390801ce3af528fc7c298232c5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9042253521, "max_line_length": 80, "alphanum_fraction": 0.4827238505, "include": true, "reason": "import numpy", "num_tokens": 4228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.3208213008246071, "lm_q1q2_score": 0.1766465665229904}}
{"text": "\"\"\"Module containing tools for EM-Bright classification of\ncompact binaries using trained supervised classifier\n\"\"\"\nimport h5py\n\nimport numpy as np\nfrom scipy.interpolate import interp1d\nfrom astropy import cosmology, units as u\n\nfrom . import (\n    EOS_BAYES_FACTORS,\n    PACKAGE_FILENAMES,\n    computeDiskMass,\n    utils\n)\n\n\n_classifiers = {\n    eos: utils._open_and_return_clfs(\n        PACKAGE_FILENAMES[f'{eos}.pickle']\n    )\n    for eos in EOS_BAYES_FACTORS\n}\n\"\"\"Classifiers keyed on EOS names. Order (clf_ns, clf_em)\"\"\"\nassert set(_classifiers) == set(EOS_BAYES_FACTORS), \"Inconsistency in\"\n\" number of trained classifiers.\"\n\n\ndef mchirp(m1, m2):\n    return(m1 * m2)**(3./5.)/(m1 + m2)**(1./5.)\n\n\ndef q(m1, m2):\n    return m2/m1 if m2 < m1 else m1/m2\n\n\ndef source_classification(m1, m2, chi1, chi2, snr,\n                          ns_classifier=None,\n                          emb_classifier=None):\n    \"\"\"\n    Computes ``HasNS`` and ``HasRemnant`` probabilities\n    from point mass, spin and signal to noise ratio\n    estimates.\n\n    Parameters\n    ----------\n    m1 : float\n        primary mass\n    m2 : float\n        secondary mass\n    chi1 : float\n        dimensionless primary spin\n    chi2 : float\n        dimensionless secondary spin\n    snr : float\n        signal to noise ratio of the signal\n    ns_classifier : object, optional\n        pickled object for NS classification\n    emb_classifier : object, optional\n        pickled object for EM brightness classification\n\n    Returns\n    -------\n    tuple\n        (P_NS, P_EMB) predicted values.\n\n    Notes\n    -----\n    By default the classifiers, trained based\n    on different nuclear equations of state (EoSs)\n    are downloaded from the project page:\n    https://git.ligo.org/deep.chatterjee/em-bright.\n    The methodology is described in arXiv:1911.00116.\n    The score from each classifier is weighted based on\n    the bayes factors of individual EoSs as mentioned in\n    Table I of arXiv:2104.08681.\n    However, if the trained classifiers are supplied\n    via ``ns_classifier`` and ``emb_classifier``,\n    the score is reported based on the classifier instead\n    of re-weighting the score.\n    Examples\n    --------\n    >>> from ligo.em_bright import em_bright\n    >>> em_bright.source_classification(2.0 ,1.0 ,0. ,0. ,10.0)\n    (1.0, 1.0)\n    \"\"\"\n    features = [[m1, m2, chi1, chi2, snr]]\n    try:\n        # custom classifiers supplied\n        return (\n            ns_classifier.predict_proba(features).T[1][0],\n            emb_classifier.predict_proba(features).T[1][0]\n        )\n    except AttributeError as e:\n        msg, *_ = e.args\n        if msg != \"\"\"'NoneType' object has no attribute 'predict_proba'\"\"\":\n            raise\n\n    reweighted_ns_score = reweighted_emb_score = 0.\n    for eosname, bayes_factor in EOS_BAYES_FACTORS.items():\n        ns_classifier, emb_classifier = _classifiers[eosname]\n        reweighted_ns_score += ns_classifier.predict_proba(\n            features).T[1][0] * bayes_factor\n        reweighted_emb_score += emb_classifier.predict_proba(\n            features).T[1][0] * bayes_factor\n    return reweighted_ns_score, reweighted_emb_score\n\n\ndef get_redshifts(distances, N=10000):\n    \"\"\"\n    Compute redshift using the Planck15 cosmology.\n\n    Parameters\n    ----------\n    distances: float or numpy.ndarray\n              distance(s) in Mpc\n\n    N : int, optional\n      Number of steps for the computation of the interpolation function\n\n    Example\n    -------\n    >>> distances = np.linspace(10, 100, 10)\n    >>> em_bright.get_redshifts(distances)\n    array([0.00225566, 0.00450357, 0.00674384, 0.00897655,\n           0.01120181, 0.0134197 , 0.01563032, 0.01783375\n           0.02003009, 0.02221941])\n\n    Notes\n    -----\n    This function accepts HDF5 posterior samples file and computes\n    redshift by interpolating the distance-redshift relation.\n    \"\"\"\n    function = cosmology.Planck15.luminosity_distance\n    min_dist = np.min(distances)\n    max_dist = np.max(distances)\n    z_min = cosmology.z_at_value(func=function, fval=min_dist*u.Mpc)\n    z_max = cosmology.z_at_value(func=function, fval=max_dist*u.Mpc)\n    z_steps = np.linspace(z_min - (0.1*z_min), z_max + (0.1*z_min), N)\n    lum_dists = cosmology.Planck15.luminosity_distance(z_steps)\n    s = interp1d(lum_dists, z_steps)\n    redshifts = s(distances)\n    return redshifts\n\n\ndef source_classification_pe(posterior_samples_file, hdf5=True,\n                             threshold=3.0, sourceframe=True):\n    \"\"\"\n    Compute ``HasNS`` and ``HasRemnant`` probabilities from posterior\n    samples.\n\n    Parameters\n    ----------\n    posterior_samples_file : str\n        Posterior samples file\n\n    hdf5 : bool, optional\n        Supply when not using HDF5 format\n\n    threshold : float, optional\n        Maximum neutron star mass for `HasNS` computation\n\n    sourceframe : bool, optional\n        Supply to use detector frame quantities\n\n    Returns\n    -------\n    tuple\n        (P_NS, P_EMB) predicted values.\n\n\n    Examples\n    --------\n    >>> from ligo.em_bright import em_bright\n    >>> em_bright.source_classification_pe('posterior_samples.hdf5')\n    (1.0, 0.9616727412238634)\n    >>> em_bright.source_classification_pe('posterior_samples.dat', hdf5=False)  # noqa:E501\n    (0.0, 0.0)\n    \"\"\"\n    if hdf5:\n        with h5py.File(posterior_samples_file, 'r') as data:\n            engine = list(data['lalinference'].keys())[0]\n            samples = data['lalinference'][engine]['posterior_samples'][()]\n        mc_det_frame = samples['mc']\n        lum_dist = samples['dist']\n        redshifts = get_redshifts(lum_dist)\n        if sourceframe:\n            mc = mc_det_frame/(1 + redshifts)\n        else:\n            mc = mc_det_frame\n\n    else:\n        samples = np.recfromtxt(posterior_samples_file, names=True)\n        if sourceframe:\n            mc = samples['mc_source']\n        else:\n            mc = samples['mc']\n\n    q = samples['q']\n    m1 = mc * (1 + q)**(1/5) * (q)**(-3/5)\n    m2 = mc * (1 + q)**(1/5) * (q)**(2/5)\n\n    try:\n        chi1 = samples['a1'] * np.cos(samples['tilt1'])\n        chi2 = samples['a2'] * np.cos(samples['tilt2'])\n    except ValueError:\n        # for aligned-spin PE, a1, a2 is the z component\n        chi1 = samples['a1']\n        chi2 = samples['a2']\n\n    M_rem = computeDiskMass.computeDiskMass(m1, m2, chi1, chi2)\n    prediction_ns = np.sum(m2 <= threshold)/len(m2)\n    prediction_em = np.sum(M_rem > 0)/len(M_rem)\n\n    return prediction_ns, prediction_em\n", "meta": {"hexsha": "5352d688f4234db72ee56037ceff8300fabfe286", "size": 6465, "ext": "py", "lang": "Python", "max_stars_repo_path": "ligo/em_bright/em_bright.py", "max_stars_repo_name": "deepchatterjeeligo/em-bright", "max_stars_repo_head_hexsha": "9be3e1bcda65807fbe696c1641c65d0da5e107bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ligo/em_bright/em_bright.py", "max_issues_repo_name": "deepchatterjeeligo/em-bright", "max_issues_repo_head_hexsha": "9be3e1bcda65807fbe696c1641c65d0da5e107bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ligo/em_bright/em_bright.py", "max_forks_repo_name": "deepchatterjeeligo/em-bright", "max_forks_repo_head_hexsha": "9be3e1bcda65807fbe696c1641c65d0da5e107bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9305555556, "max_line_length": 92, "alphanum_fraction": 0.6358855375, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 1727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.32082128783705344, "lm_q1q2_score": 0.17664656410358304}}
{"text": "from __future__ import division, print_function\nimport numpy as np\nimport sys\nimport os\nimport random\n\nimport LFPy\nfrom kcsd import sample_data_path\nimport neuron\nmorphology_directory = os.path.join(sample_data_path,'morphology')\n\"\"\"Electrode grid is 2D. If z is the zero dimention x=x, y=y.\nIf x is the zero dimension x=0, y=x, z=y.\nIf y is the zero dimention, z=x & x=y\"\"\"\n\n\"\"\"cell_types = {'Ballstick:1,\n'Y_shaped':2,\n'Morpho1':3,\n'Agasbogas':4,\n'Mainen':5,\n'User_defined:6',\n'Gang_simple':7,\n'Domi':8,\n'test':9}\nelectrode_orientation = {'x':1, 'y':2, 'z':3}\nelectrode_distribute = {'Grid':1, 'Random':2, 'Hexagonal':3, 'Domi':4}\nLFPy_sim = {'Random':1,\n'Y_symmetric':2,\n'Mainen':3,\n'Oscill':4,\n'Const':5,\n'Sine':6 }\n\"\"\"\nrm = 4\n\n\nclass CellModel():\n    MORPHOLOGY_FILES = {\n        1: os.path.join(morphology_directory,\"ballstick.hoc\"),\n        2: os.path.join(morphology_directory,\"villa.hoc\"),\n        3: os.path.join(morphology_directory,\"morpho1.swc\"),\n        4: os.path.join(morphology_directory,\"neuron_agasbogas.swc\"),\n        5: os.path.join(morphology_directory,\"Mainen_swcLike.swc\"),\n        6: os.path.join(morphology_directory,\"retina_ganglion.swc\"),\n        7: os.path.join(morphology_directory,\"Badea2011Fig2Du.CNG.swc\"),\n        8: os.path.join(morphology_directory,\"DomiCell.swc\"),\n        9: os.path.join(morphology_directory,\"Test.swc\"),\n        10: os.path.join(morphology_directory,\"L5_Mainen96_LFPy.hoc\"),\n    }\n    CELL_PARAMETERS = {\n        'Ra': 123,\n        # start time of simulation, recorders start at t=0\n        'tstart': 0.,\n        'passive': True,\n        'passive_parameters': {'e_pas': -65,\n        'g_pas': 1./30000},\n        # initial crossmembrane potential\n        'v_init': -65,\n        'nsegs_method': 'fixed_length',\n        'max_nsegs_length': 10,\n        'custom_code': [],  # will run this file\n        'dt': 0.25,\n    }\n    SYNAPSE_PARAMETERS = {\n        # idx to be set later\n        'e': 0.,  # reversal potential\n        'syntype': 'ExpSyn',  # synapse type\n        'tau': 2.,\n        'weight': .04,  # synaptic weight\n        'record_current': True,\n    }\n    SIMULATION_PARAMETERS = {\n        'rec_imem': True,\n    }\n    ELECTRODE_PARAMETERS = {\n        'method': 'linesource',\n        \n    }\n    POINT_PROCESS = {\n        'idx': 0,\n        'pptype': 'IClamp',\n        }\n\n    def __init__(self, **kwargs):\n        self.cell_parameters = self.CELL_PARAMETERS.copy()\n        self.synapse_parameters = self.SYNAPSE_PARAMETERS.copy()\n        self.simulation_parameters = self.SIMULATION_PARAMETERS.copy()\n        self.electrode_parameters = self.ELECTRODE_PARAMETERS.copy()\n        self.point_process = self.POINT_PROCESS.copy()\n        self.cell_name = kwargs.pop('cell_name', 'cell_1')\n        self.path = kwargs.pop('path', 'simulation')\n        self.stimulus = kwargs.pop('stimulus', 'random')\n        dt = kwargs.pop('dt', 0.5)\n        self.cell_parameters['dt'] = dt\n        eldistribute = kwargs.pop('electrode_distribution', 1)\n        # according to which axis\n        orientation = kwargs.pop('electrode_orientation', 2)\n        colnb = kwargs.pop('colnb', 4)\n        rownb = kwargs.pop('rownb', 4)\n        xmin = kwargs.pop('xmin', 0)\n        xmax = kwargs.pop('xmax', 200)\n        ymin = kwargs.pop('ymin', -100)\n        ymax = kwargs.pop('ymax', -500)\n        tstop = kwargs.pop('tstop', 850)\n        self.cell_parameters['tstop'] = tstop\n        cell_electrode_dist = kwargs.pop('electrode_distance', 50)\n        triside = 2*kwargs.pop('triside', 60)\n        ssNB = kwargs.pop('seed', 123456)\n        custom_code = kwargs.pop('custom_code', [])\n        morphology_no = kwargs.pop('morphology', 1)\n        self.sigma = kwargs.pop('sigma', 0.3)\n        self.n_pre_syn = kwargs.pop('n_presyn', 1000)\n        self.n_synapses = kwargs.pop('n_syn', 1000)\n        self.new_path = os.path.join(self.path, self.cell_name)\n        np.random.seed(ssNB)\n        self.synapse_parameters['weight'] = kwargs.pop('weight', 0.04)\n        if kwargs:\n            raise TypeError('Invalid keyword arguments:', kwargs.keys())\n        try:\n            morphology = self.MORPHOLOGY_FILES[morphology_no]\n        except AttributeError:\n            sys.exit('Unknown morphology %d\\n', morphology)\n        if morphology_no == 2:\n                self.make_y_shaped()\n        self.make_cell(morphology, custom_code)\n        self.setup_LFPy_2D_grid(eldistribute,\n                                orientation,\n                                colnb,\n                                rownb,\n                                xmin,\n                                xmax,\n                                ymin,\n                                ymax,\n                                cell_electrode_dist,\n                                triside,\n                                ssNB)\n        self.add_electrodes()\n        self.pre_syn_pick = np.empty((1,1))\n\n    def make_y_shaped(self):\n        self.cell_parameters['passive_parameters'] = {'g_pas':1./30000,\n                                                      'e_pas':-65}\n        self.cell_parameters['cm'] = 1.\n        self.cell_parameters['Ra'] = 100.\n        self.simulation_parameters['rec_vmem'] = True\n\n    def stationary_poisson(self, nsyn, lambd, tstart, tstop):\n        '''Generates nsyn stationary possion processes with\n        rate lambda between tstart and tstop'''\n        interval_s = (tstop - tstart)*.001\n        spiketimes = []\n        for i in range(nsyn):\n            spikecount = np.random.poisson(interval_s*lambd)\n            spikevec = np.empty(spikecount)\n            if spikecount == 0:\n                spiketimes.append(spikevec)\n            else:\n                spikevec = tstart\\\n                           + (tstop - tstart)*np.random.random(spikecount)\n                spiketimes.append(np.sort(spikevec))\n        return spiketimes\n\n    def make_cell(self, morphology, custom_code=[]):\n        self.cell_parameters['morphology'] = morphology\n        \n        for code in custom_code:\n            self.cell_parameters['custom_code'].append(custom_code)\n\n        self.cell = LFPy.Cell(**self.cell_parameters)\n        \n        if not morphology.endswith('.hoc'):\n            if not self.cell_parameters['custom_code']:\n               for section in self.cell.allseclist:\n                   if 'soma' in section.name() or 'axon' in section.name():\n                       section.insert('hh')\n                       print('Inserting Hodgkin-Huxley channels into %s' % section.name())\n\n        self.cell.set_pos(x = LFPy.cell.neuron.h.x3d(0),\n                          y = LFPy.cell.neuron.h.y3d(0),\n                          z = LFPy.cell.neuron.h.z3d(0))\n        return self.cell\n\n    def save_morphology_to_file(self):\n        segments = self.cell.get_idx()\n        nseg = len(segments)\n        self.morphology = np.zeros((nseg+1, 7))\n        coords = np.array((self.cell.xstart,\n                           self.cell.ystart,\n                           self.cell.zstart)).T\n        ends = np.array((self.cell.xend,\n                         self.cell.yend,\n                         self.cell.zend)).T\n        segdiam = self.cell.diam\n        parents = {}\n        self.morphology[0, 0] = 1\n        self.morphology[0, 1] = 1\n        self.morphology[0, 2:5] = coords[0]\n        self.morphology[0, 5] = segdiam[0]\n        self.morphology[0, 6] = -1\n        \n        for section in neuron.h.allsec():\n            parents[section.name()] = section.parentseg()\n        for sec in neuron.h.allsec():\n            secn = sec.name()\n            idxs = self.cell.get_idx(secn)\n            \n            for i, idx in enumerate(idxs):\n                self.morphology[idx+1, 0] = idx+2\n                self.morphology[idx+1, 2:5] = ends[idx]\n                self.morphology[idx+1, 5] = segdiam[idx]\n                if 'soma' in secn:\n                    self.morphology[idx+1, 1] = 1\n                elif 'dend' in secn:\n                    self.morphology[idx+1, 1] = 3\n                elif 'apic' in secn:\n                    self.morphology[idx+1, 1] = 3\n                elif 'axon' in secn:\n                    self.morphology[idx+1, 1] = 2\n                elif 'basal' in secn:\n                    self.morphology[idx+1, 1] = 4\n                else:\n                    self.morphology[idx+1, 1] = 5\n                if i == 0:\n                    if not parents[secn]:\n                        self.morphology[idx+1, 6] = 1\n                    else:\n                        x = parents[secn].x\n                        how_many = len(self.cell.get_idx(parents[secn].sec.name()))\n                        par_idx = int(x*how_many)\n                        if par_idx > how_many - 1:\n                            par_idx = how_many -1\n                        par = self.cell.get_idx(parents[secn].sec.name())[par_idx]\n                        self.morphology[idx+1, 6] = par + 2\n                else:\n                    self.morphology[idx+1, 6] = idx+1\n        morph_path = os.path.join(self.new_path, 'morphology')\n        if not os.path.exists(morph_path):\n            print(\"Creating\", morph_path)\n            os.makedirs(morph_path)\n        fname = os.path.join(morph_path, self.cell_name) + '.swc'\n        print('Saving morphology to', fname)\n        np.savetxt(fname,\n                   self.morphology,\n                   header='',\n                   fmt=['%d', '%d', '%6.2f', '%6.2f', '%6.2f', '%6.2f', '%d'])\n\n    def find_parent(self, i, coords, ends):\n        for j, end in enumerate(ends):\n            check_parent = np.isclose(coords[i], end)\n            if check_parent[0] and check_parent[1] and check_parent[2]:\n                return j\n\n    def add_electrodes(self):\n        self.electrode_parameters['x'] = self.ele_coordinates[:, 0],\n        self.electrode_parameters['y'] = self.ele_coordinates[:, 1],\n        self.electrode_parameters['z'] = self.ele_coordinates[:, 2],\n        self.electrode_parameters['sigma'] = self.sigma\n        electrode = LFPy.RecExtElectrode(**self.electrode_parameters)\n        self.simulation_parameters['electrode'] = electrode\n\n    def setup_LFPy_2D_grid(self,\n                           eldistribute,\n                           orientation,\n                           colnb,\n                           rownb,\n                           xmin,\n                           xmax,\n                           ymin,\n                           ymax,\n                           cellelectrodedist,\n                           triside,\n                           ssNB):\n        if orientation == 1:\n            i, j, k = 1, 2, 0\n        if orientation == 2:\n            i, j, k = 2, 0, 1\n        if orientation == 3:\n            i, j, k = 0, 1, 2\n        self.ele_coordinates = np.ones((rownb*colnb, 3))*cellelectrodedist\n\n        if eldistribute == 1:  # grid\n            linspace = np.linspace(xmin, xmax, rownb)\n            self.ele_coordinates[:, i] = np.array(colnb*list(linspace))\n            self.ele_coordinates[:, j] = np.repeat(np.linspace(ymin,\n                                                               ymax,\n                                                               colnb),\n                                                   rownb)\n        elif eldistribute == 2:  # random\n            self.ele_coordinates[:, i] = np.random.uniform(low=xmin,\n                                                           high=xmax,\n                                                           size=rownb * colnb)\n            self.ele_coordinates[:, j] = np.random.uniform(low=ymin,\n                                                           high=ymax,\n                                                           size=rownb * colnb)\n        elif eldistribute == 3:\n            assert (rownb % 2 == 0)\n            triheight = triside*np.cos(np.pi/6)\n            rownb = rownb//2\n            triX1 = xmin + triside*np.arange(1, colnb+1) - triside\n            triX2 = xmin - triside/2 + triside*np.arange(1, colnb+1)\n            triY1 = ymin + 2*triheight*np.arange(1, rownb+1) - triheight\n            triY2 = ymin + 2*triheight*np.arange(1, rownb+1)\n            grid1 = [[], []]\n            grid2 = [[], []]\n            for l2 in range(len(triY1)):\n                for l1 in range(len(triX1)):\n                    grid1[0].append(triX1[l1])\n                    grid1[1].append(triY1[l2])\n                    grid2[0].append(triX2[l1])\n                    grid2[1].append(triY2[l2])\n            Xcoord = grid1[0] + grid2[0]\n            Ycoord = grid1[1] + grid2[1]\n            self.ele_coordinates[:, i] = Xcoord\n            self.ele_coordinates[:, j] = Ycoord\n        elif eldistribute == 4:\n            self.ele_coordinates = np.loadtxt(os.path.join(sample_data_path, 'ElcoordsDomi14.txt'))\n        if not os.path.exists(self.new_path):\n            print(\"Creating\", self.new_path)\n            os.makedirs(self.new_path)\n            self.add_electrodes()\n\n    def constant_current_injection(self, amp, idx=0):\n        self.point_process['idx'] = idx\n        self.point_process['amp'] = amp\n        self.point_process['dur'] = self.cell.tstop\n        self.point_process['delay'] = 2\n        stimulus = LFPy.StimIntElectrode(self.cell, **self.point_process)\n\n    def cosine_current_injection(self, tstop=850):\n        pre_syn_sptimes = self.stationary_poisson(nsyn=self.n_pre_syn,\n                                                  lambd=2,\n                                                  tstart=0,\n                                                  tstop=400)\n        l = np.arange(self.n_pre_syn)\n        pre_syn_pick = np.random.permutation(l)[0:self.n_synapses]\n        pars = {}\n        for i_syn in range(self.n_synapses):\n            syn_idx = int(self.cell.get_rand_idx_area_norm())\n            spike_times = pre_syn_sptimes[pre_syn_pick[i_syn]]\n            if syn_idx in pars:\n                pars[syn_idx].extend(list(spike_times))\n            else:\n                pars[syn_idx] = list(spike_times)\n        for syn_idx in pars:\n            self.synapse_parameters.update({'idx': syn_idx})\n            synapse = LFPy.Synapse(self.cell, **self.synapse_parameters)\n            synapse.set_spike_times(np.array(pars[syn_idx]))\n       \n        TimesStim = np.arange(tstop)\n        stim = np.array(3.6*np.sin(2.*3.141*6.5*TimesStim/1000.))\n        for istim in range(tstop):\n            pointprocess = {\n                'idx' : 0,\n                'pptype': 'IClamp',\n                'record_current' : True,\n                'amp': stim[istim],\n                'dur' : 1.,\n                'delay': istim,\n                }\n            stimulus = LFPy.StimIntElectrode(self.cell, **pointprocess)\n\n    def distal_cosine_current_injection(self, tstop=850):\n        pre_syn_sptimes = self.stationary_poisson(nsyn=self.n_pre_syn,\n                                                  lambd=2,\n                                                  tstart=0,\n                                                  tstop=400)\n        l = np.arange(self.n_pre_syn)\n        pre_syn_pick = np.random.permutation(l)[0:self.n_synapses]\n        pars = {}\n        for i_syn in range(self.n_synapses):\n            syn_idx = int(self.cell.get_rand_idx_area_norm())\n            spike_times = pre_syn_sptimes[pre_syn_pick[i_syn]]\n            if syn_idx in pars:\n                pars[syn_idx].extend(list(spike_times))\n            else:\n                pars[syn_idx] = list(spike_times)\n        for syn_idx in pars:\n            self.synapse_parameters.update({'idx': syn_idx})\n            synapse = LFPy.Synapse(self.cell, **self.synapse_parameters)\n            synapse.set_spike_times(np.array(pars[syn_idx]))\n       \n        TimesStim = np.arange(850)\n        stim = np.array(3.6*np.sin(2.*3.141*6.5*TimesStim/1000.))\n        all_idxs = self.cell.get_idx()\n        \n        for istim in range(tstop):\n            pointprocess = {\n                'idx' : max(all_idxs),\n                'pptype': 'IClamp',\n                'record_current' : True,\n                'amp': stim[istim],\n                'dur' : 1.,\n                'delay': istim,\n                }\n            stimulus = LFPy.StimIntElectrode(self.cell, **pointprocess)\n\n            \n    def random_synaptic_input(self,\n                              lambd=2,\n                              tstart=0,\n                              tstop=70):\n\n        self.synapse_parameters['idx'] = 0\n        pre_syn_sptimes = self.stationary_poisson(self.n_pre_syn,\n                                                  lambd,\n                                                  tstart,\n                                                  tstop)\n        l = np.arange(self.n_pre_syn)\n        self.pre_syn_pick = np.random.permutation(l)[0:self.n_synapses]\n\n        for i_syn in range(self.n_synapses):\n            syn_idx = int(self.cell.get_rand_idx_area_norm())\n            self.synapse_parameters.update({'idx': syn_idx})\n            synapse = LFPy.Synapse(self.cell, **self.synapse_parameters)\n\n            synapse.set_spike_times(pre_syn_sptimes[self.pre_syn_pick[i_syn]])\n\n    def y_shaped_symmetric_input(self):\n        self.synapse_parameters['idx'] = 0\n        pre_syn_sptimes = [np.array([5., 25., 60.]), np.array([5., 45., 60.])]\n        syn_no = [65, 33]\n\n        for i, i_syn in enumerate(syn_no):\n            new_pars = self.synapse_parameters.copy()\n            new_pars['idx'] = i_syn\n            synapse = LFPy.Synapse(self.cell, **new_pars)\n            synapse.set_spike_times(pre_syn_sptimes[i])\n\n    def sine_synaptic_input(self, tstop=None):\n        if not tstop:\n            tstop = self.cell.tstop\n        frequencies = np.arange(0.5, 13, 0.5)\n        i = 0\n        distance = 0\n        nseg = self.cell.get_idx()\n        freq_step = sum(self.cell.length)/len(frequencies)\n        for j, istim in enumerate(nseg):\n            distance += self.cell.length[j]\n            if distance > (i + 1)*freq_step:\n                i += 1\n            freq = frequencies[i]\n            pointprocess = {\n                'idx': istim,\n                'pptype': 'SinSyn',\n                'pkamp':  3.6,\n                'freq': freq,\n                'phase': -np.pi/2,\n                'dur': self.cell.tstop,\n            }\n            stimulus = LFPy.StimIntElectrode(self.cell, **pointprocess)\n\n    def simulate(self, stimulus=None):\n        if stimulus:\n            self.stimulus = stimulus\n        if self.stimulus == 'constant':\n            self.constant_current_injection(amp=10, idx=0)\n        elif self.stimulus == 'random':\n            self.random_synaptic_input()\n        elif self.stimulus == 'sine':\n            self.sine_synaptic_input()\n        elif self.stimulus == 'symmetric':\n            self.y_shaped_symmetric_input()\n        elif self.stimulus == 'oscillatory':\n            self.cosine_current_injection(tstop=self.cell_parameters['tstop'])\n        elif self.stimulus == 'distal_oscillatory':\n            self.distal_cosine_current_injection(tstop=self.cell_parameters['tstop'])\n        self.cell.simulate(**self.simulation_parameters)\n\n    def save_LFP(self, directory=''):\n        self.simulation_parameters['electrode'].calc_lfp()\n        LFP_path = os.path.join(self.new_path, directory)\n        if not os.path.exists(LFP_path):\n            print(\"Creating\", LFP_path)\n            os.makedirs(LFP_path)\n        fname = os.path.join(LFP_path, 'MyLFP')\n        np.savetxt(fname, self.simulation_parameters['electrode'].LFP)\n\n    def save_electrode_pos(self, directory=''):\n        electr = np.hstack((self.ele_coordinates[:, 0],\n                            self.ele_coordinates[:, 1],\n                            self.ele_coordinates[:, 2]))\n        elcoord_x_y_x_path = os.path.join(self.new_path, directory)\n        if not os.path.exists(elcoord_x_y_x_path):\n            print(\"Creating\", elcoord_x_y_x_path)\n            os.makedirs(elcoord_x_y_x_path)\n        fname = os.path.join(elcoord_x_y_x_path, 'elcoord_x_y_z')\n        np.savetxt(fname, electr)\n\n\n    def save_somav(self, directory=''):\n        if directory:\n            new_path = directory\n        else:\n            new_path = self.new_path\n        np.savetxt(os.path.join(new_path, 'somav.txt'),\n                   self.cell.somav)\n\n    def save_tvec(self, directory=''):\n        if directory:\n            new_path = directory\n        else:\n            new_path = self.new_path\n        np.savetxt(os.path.join(new_path, 'tvec.txt'),\n                   self.cell.tvec)\n \n    def save_for_R_kernel(self, directory=''):\n        if directory:\n            new_path = directory\n        else:\n            new_path = self.new_path\n        self.save_LFP(directory)\n        self.save_electrode_pos(directory)\n        self.save_somav(directory)\n        coords = np.hstack((self.cell.xmid,\n                            self.cell.ymid,\n                            self.cell.zmid))\n        np.savetxt(os.path.join(new_path, 'coordsmid_x_y_z'),\n                   coords)\n        # coordinates of the segment's beginning\n        coordsstart = np.hstack((self.cell.xstart,\n                                 self.cell.ystart,\n                                 self.cell.zstart))\n        np.savetxt(os.path.join(new_path, 'coordsstart_x_y_z'),\n                   coordsstart)\n        # coordinates of the segment's end\n        coordsend = np.hstack((self.cell.xend,\n                               self.cell.yend,\n                               self.cell.zend))\n        np.savetxt(os.path.join(new_path, 'coordsend_x_y_z'),\n                   coordsend)\n        # diameter of the segments\n        segdiam = np.hstack((self.cell.diam))\n        np.savetxt(os.path.join(new_path, 'segdiam_x_y_z'),\n                   segdiam)\n        # time in the simulation\n        np.savetxt(os.path.join(new_path, 'time'),\n                   self.cell.tvec)\n        # let's write to file the simulation locations\n        np.savetxt('synapse_locations', self.pre_syn_pick)\n        self.save_memb_curr()\n        self.save_seg_length()\n\n    def save_memb_curr(self, directory=''):\n        if directory:\n            new_path = directory\n        else:\n            new_path = self.new_path\n        np.savetxt(os.path.join(new_path, 'membcurr'),\n                   self.cell.imem)\n\n    def save_seg_length(self, directory=''):\n        if directory:\n            new_path = directory\n        else:\n            new_path = self.new_path\n        np.savetxt(os.path.join(new_path, 'seglength'),\n                   self.cell.length)\n\n    def save_skCSD_python(self):\n        self.save_morphology_to_file()\n        self.save_LFP('LFP')\n        self.save_electrode_pos('electrode_positions')\n\n    def return_paths_skCSD_python(self):\n        return self.new_path\n\n\nif __name__ == '__main__':\n    c = CellModel(morphology=7,\n                  cell_name='Gang_simple',\n                  electrode_distribution=4,\n                  colnb=1,\n                  rownb=8,\n                  xmin=-500,\n                  xmax=500,\n                  ymin=-500,\n                  ymax=500)\n    c.simulate()\n    c.save_skCSD_python()\n    c.save_for_R_kernel()\n", "meta": {"hexsha": "ac6ae7d08dda10375a21c71c980da8ada2915f82", "size": 23018, "ext": "py", "lang": "Python", "max_stars_repo_path": "figures/sKCSD_paper/run_LFP.py", "max_stars_repo_name": "rdarie/kCSD-python", "max_stars_repo_head_hexsha": "5b9e1b1dce2ff95c0d981c2c4015b7a75199de9a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2017-11-06T21:24:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T21:17:13.000Z", "max_issues_repo_path": "figures/sKCSD_paper/run_LFP.py", "max_issues_repo_name": "aeladly91/kCSD-python", "max_issues_repo_head_hexsha": "4dd0015e9c5598e7eceeeb25668e696e495b2026", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 105, "max_issues_repo_issues_event_min_datetime": "2017-12-13T12:49:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T12:25:51.000Z", "max_forks_repo_path": "figures/sKCSD_paper/run_LFP.py", "max_forks_repo_name": "aeladly91/kCSD-python", "max_forks_repo_head_hexsha": "4dd0015e9c5598e7eceeeb25668e696e495b2026", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2017-06-08T07:32:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T21:17:15.000Z", "avg_line_length": 39.6862068966, "max_line_length": 99, "alphanum_fraction": 0.5210704666, "include": true, "reason": "import numpy", "num_tokens": 5561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3276682876897044, "lm_q1q2_score": 0.17660770901621553}}
{"text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n   This file belong to https://github.com/snolfi/evorobotpy\n   and has been written by Stefano Nolfi and Paolo Pagliuca, stefano.nolfi@istc.cnr.it, paolo.pagliuca@istc.cnr.it\n   salimans.py include an implementation of the OpenAI-ES algorithm described in\n   Salimans T., Ho J., Chen X., Sidor S & Sutskever I. (2017). Evolution strategies as a scalable alternative to reinforcement learning. arXiv:1703.03864v2\n   requires es.py, policy.py, and evoalgo.py \n\"\"\"\n\nimport numpy as np\nfrom numpy import zeros, ones, dot, sqrt\nimport math\nimport time\nfrom mpi4py import MPI\nfrom evoalgo import EvoAlgo\nfrom utils import ascendent_sort\nimport sys\nimport os\nimport configparser\n\n# Parallel implementation of Open-AI-ES algorithm developed by Salimans et al. (2017)\n# the workers evaluate a fraction of the population in parallel\n# the master post-evaluate the best sample of the last generation and eventually update the input normalization vector\n\nclass Algo(EvoAlgo):\n    def __init__(self, env, policy, seed, fileini, filedir):\n        EvoAlgo.__init__(self, env, policy, seed, fileini, filedir)\n\n    def loadhyperparameters(self):\n\n        if os.path.isfile(self.fileini):\n\n            config = configparser.ConfigParser()\n            config.read(self.fileini)\n            self.maxsteps = 1000000\n            self.stepsize = 0.01\n            self.batchSize = 20\n            self.noiseStdDev = 0.02\n            self.wdecay = 0\n            self.symseed = 1\n            self.saveeach = 60\n            options = config.options(\"ALGO\")\n            for o in options:\n                found = 0\n                if o == \"maxmsteps\":\n                    self.maxsteps = config.getint(\"ALGO\",\"maxmsteps\") * 1000000\n                    found = 1\n                if o == \"stepsize\":\n                    self.stepsize = config.getfloat(\"ALGO\",\"stepsize\")\n                    found = 1\n                if o == \"noisestddev\":\n                    self.noiseStdDev = config.getfloat(\"ALGO\",\"noiseStdDev\")\n                    found = 1\n                if o == \"samplesize\":\n                    self.batchSize = config.getint(\"ALGO\",\"sampleSize\")\n                    found = 1\n                if o == \"wdecay\":\n                    self.wdecay = config.getint(\"ALGO\",\"wdecay\")\n                    found = 1\n                if o == \"symseed\":\n                    self.symseed = config.getint(\"ALGO\",\"symseed\")\n                    found = 1\n                if o == \"saveeach\":\n                    self.saveeach = config.getint(\"ALGO\",\"saveeach\")\n                    found = 1\n\n                if found == 0:\n                    print(\"\\033[1mOption %s in section [ALGO] of %s file is unknown\\033[0m\" % (o, self.fileini))\n                    print(\"available hyperparameters are: \")\n                    print(\"maxmsteps [integer]       : max number of (million) steps (default 1)\")\n                    print(\"stepsize [float]          : learning stepsize (default 0.01)\")\n                    print(\"samplesize [int]          : popsize/2 (default 20)\")\n                    print(\"noiseStdDev [float]       : samples noise (default 0.02)\")\n                    print(\"wdecay [0/2]              : weight decay (default 0), 1 = L1, 2 = L2\")\n                    print(\"symseed [0/1]             : same environmental seed to evaluate symmetrical samples [default 1]\")\n                    print(\"saveeach [integer]        : save file every N minutes (default 60)\")\n\n                    sys.exit()\n        else:\n            print(\"\\033[1mERROR: configuration file %s does not exist\\033[0m\" % (self.fileini))\n    \n\n\n    def setProcess(self, n_workers, comm, rank):\n        self.loadhyperparameters()               # load parameters\n        self.n_workers = n_workers               # number of workers, includes the master\n        self.rank = rank                         # worker id\n        self.comm = comm                         # \n        self.center = np.copy(self.policy.get_trainable_flat())  # the initial centroid\n        self.nparams = len(self.center)          # number of adaptive parameters\n        self.n_worker_samples = int(self.batchSize / (self.n_workers - 1)) # number of sample evaluated by each worker\n        self.id = (self.rank - 1)                # id of the process (master has id -1)\n        self.cgen = 0                            # currrent generation\n        self.fitness = ones(self.n_workers * (self.n_worker_samples * 2)) # vector of fitness filled by the master and the workers\n        self.evals = zeros(self.n_workers, dtype=np.int32)  #vector of evaluation steps filled by the master and by the workers\n        self.samplefitness = zeros(self.batchSize * 2) # the fitness of the samples\n        self.samples = None                      # the random samples\n        self.m = zeros(self.nparams)             # Adam: momentum vector \n        self.v = zeros(self.nparams)             # Adam: second momentum vector (adam)\n        self.epsilon = 1e-08                     # Adam: To avoid numerical issues with division by zero...\n        self.beta1 = 0.9                         # Adam: beta1\n        self.beta2 = 0.999                       # Adam: beta2\n        self.bestgfit = -99999999                # the best generalization fitness\n        self.bfit = 0                            # the fitness of the best sample\n        self.gfit = 0                            # the postevaluation fitness of the best sample of last generation\n        self.rs = None                           # random number generator\n        if self.policy.normalize == 1:           # normalization vector\n            self.normvector = np.arange(self.n_workers * (self.policy.ninputs * 2), dtype=np.float64)  # normalization vector broadcasted to workers\n        self.inormepisodes = self.batchSize * 2 * self.policy.ntrials / 100.0 # number of normalization episode for generation (1% of generation episodes)\n        self.tnormepisodes = 0.0                 # total epsidoes in which normalization data should be collected so far\n        self.normepisodes = 0                    # numer of episodes in which normalization data has been actually collected so far\n\n    def savedata(self):\n        # save best postevaluated so far\n        fname = self.filedir + \"/bestgS\" + str(self.seed)\n        np.save(fname, self.bestgsol)\n        # save best so far\n        fname = self.filedir + \"/bestS\" + str(self.seed)\n        np.save(fname, self.bestsol)\n        # save statistics\n        fname = self.filedir + \"/statS\" + str(self.seed)\n        np.save(fname, self.stat)\n        # save summary statistics\n        fname = self.filedir + \"/S\" + str(self.seed) + \".fit\"\n        fp = open(fname, \"w\")\n        fp.write('Seed %d (%.1f%%) gen %d msteps %d bestfit %.2f bestgfit %.2f bestsam %.2f avgfit %.2f paramsize %.2f \\n' %\n             (self.seed, self.steps / float(self.maxsteps) * 100, self.cgen, self.steps / 1000000, self.bestfit, self.bestgfit, self.bfit, self.avgfit, self.avecenter))\n        fp.close()\n\n        \n    def evaluate(self):\n        global none_val\n        seed_worker = self.seed + self.cgen * self.batchSize  # Set the seed for current generation (master and workers have the same seed)\n        self.rs = np.random.RandomState(seed_worker)\n        self.samples = self.rs.randn(self.batchSize, self.nparams)\n        self.cgen += 1\n        fitness_worker = ones(self.n_worker_samples * 2)\n        ceval = 0\n        \n        if self.rank == 0:                                      # Master: postevaluate the best sample of last generation\n            gfit = 0\n            if self.bestsol is not None:\n                self.policy.set_trainable_flat(self.bestsol)\n                self.tnormepisodes += self.inormepisodes\n                normalizationdatacollected = False\n                for t in range(self.policy.nttrials):\n                    if self.policy.normalize == 1 and self.normepisodes < self.tnormepisodes:\n                        self.policy.nn.normphase(1)\n                        self.normepisodes += 1\n                        normalizationdatacollected = True\n                    else:\n                        self.policy.nn.normphase(0)\n                    eval_rews, eval_length = self.policy.rollout(1, seed=(self.seed + 100000 + t))\n                    gfit += eval_rews               \n                    ceval += eval_length\n                self.updateBestg(gfit / self.policy.nttrials, self.bestsol)\n                if normalizationdatacollected:\n                    self.policy.nn.updateNormalizationVectors()  # update the normalization vectors with the new data collected\n            else:\n                self.policy.nn.getNormalizationVectors()         # update the normalization vector accessible in python with that initialized by evonet\n        else:      \n            candidate = np.arange(self.nparams, dtype=np.float64)\n            for b in range(self.n_worker_samples):               # Worker (evaluate a fraction of the population)\n                for bb in range(2):\n                    if (bb == 0):\n                        candidate = self.center + self.samples[(self.id * self.n_worker_samples) + b,:] * self.noiseStdDev\n                    else:\n                        candidate = self.center - self.samples[(self.id * self.n_worker_samples) + b,:] * self.noiseStdDev\n                    self.policy.set_trainable_flat(candidate)\n                    self.policy.nn.normphase(0)   # workers never collect normalization data\n                    eval_rews, eval_length = self.policy.rollout(self.policy.ntrials, seed=(self.seed + (self.cgen * self.batchSize) + (self.id * self.n_worker_samples) + b))\n                    fitness_worker[b*2+bb] = eval_rews\n                    ceval += eval_length\n        ceval = np.asarray([ceval], dtype=np.int32)\n        return fitness_worker, ceval\n\n\n    def optimize(self):\n\n        fitness, index = ascendent_sort(self.samplefitness)       # sort the fitness\n        self.avgfit = np.average(fitness)                         # compute the average fitness                   \n\n        self.bfit = fitness[(self.batchSize * 2) - 1]\n        bidx = index[(self.batchSize * 2) - 1]  \n        if ((bidx % 2) == 0):                                     # regenerate the genotype of the best samples\n            bestid = int(bidx / 2)\n            self.bestsol = self.center + self.samples[bestid] * self.noiseStdDev  \n        else:\n            bestid = int(bidx / 2)\n            self.bestsol = self.center - self.samples[bestid] * self.noiseStdDev\n\n        if self.rank == 0:\n            self.updateBest(self.bfit, self.bestsol)              # Stored if it is the best obtained so far \n            \n        popsize = self.batchSize * 2                              # compute a vector of utilities [-0.5,0.5]\n        utilities = zeros(popsize)\n        for i in range(popsize):\n            utilities[index[i]] = i\n        utilities /= (popsize - 1)\n        utilities -= 0.5\n        \n        weights = zeros(self.batchSize)                           # Assign the weights (utility) to samples on the basis of their fitness rank\n        for i in range(self.batchSize):\n            idx = 2 * i\n            weights[i] = (utilities[idx] - utilities[idx + 1])    # merge the utility of symmetric samples\n\n        g = 0.0\n        i = 0\n        while i < self.batchSize:                                 # Compute the gradient (the dot product of the samples for their utilities)\n            gsize = -1\n            if self.batchSize - i < 500:                          # if the popsize is larger than 500, compute the gradient for multiple sub-populations\n                gsize = self.batchSize - i\n            else:\n                gsize = 500\n            g += dot(weights[i:i + gsize], self.samples[i:i + gsize,:]) \n            i += gsize\n        g /= popsize                                              # normalize the gradient for the popsize\n        \n        if self.wdecay == 1:\n            globalg = -g + 0.005 * self.center                    # apply weight decay\n        else:\n            globalg = -g\n\n        # adam stochastic optimizer\n        a = self.stepsize * sqrt(1.0 - self.beta2 ** self.cgen) / (1.0 - self.beta1 ** self.cgen)\n        self.m = self.beta1 * self.m + (1.0 - self.beta1) * globalg\n        self.v = self.beta2 * self.v + (1.0 - self.beta2) * (globalg * globalg)\n        dCenter = -a * self.m / (sqrt(self.v) + self.epsilon)\n        \n        self.center += dCenter                                    # move the center in the direction of the momentum vectors\n        self.avecenter = np.average(np.absolute(self.center))      \n\n    def update_normvector(self):\n        if self.rank > 0:                                                # workers overwrite their normalization vector with the vector received from the master\n            for i in range(self.policy.ninputs * 2):\n                self.policy.normvector[i] = np.copy(self.normvector[i])  \n            self.policy.nn.setNormalizationVectors()\n\n    def run(self):\n\n        start_time = time.time()\n        last_save_time = start_time\n        elapsed = 0\n        self.steps = 0\n        if self.rank ==0:\n            print(\"Salimans: seed %d maxmsteps %d batchSize %d stepsize %lf noiseStdDev %lf wdecay %d symseed %d nparams %d\" % (self.seed, self.maxsteps / 1000000, self.batchSize, self.stepsize, self.noiseStdDev, self.wdecay, self.symseed, self.nparams))\n\n        while (self.steps < self.maxsteps):\n\n            \n            fitness_worker, weval = self.evaluate()   # evaluate sample (each worker evaluate a fraction of the population) \n            self.comm.Allgatherv(fitness_worker, [self.fitness, MPI.DOUBLE])                # brodcast fitness value to all workers\n            self.comm.Allgatherv(weval, [self.evals, MPI.INT])                              # broadcast number of steps performed to all workers\n            if self.policy.normalize == 1:\n                self.comm.Allgatherv(self.policy.normvector, [self.normvector, MPI.DOUBLE]) # broadcast normalization vector (it is update from the master, the vectors of the workers are ignored)              \n\n            self.samplefitness = self.fitness[(self.n_worker_samples * 2):] # Merge the fitness of the workers by discarding the vector returned by the master\n            self.steps += np.sum(self.evals)          # Update the total number of steps performed so far\n            \n            self.optimize()                           # estimate the gradient and move the centroid in the gradient direction\n\n            self.stat = np.append(self.stat, [self.steps, self.bestfit, self.bestgfit, self.bfit, self.avgfit, self.avecenter])  # store performance across generations\n            if self.rank == 0 and ((time.time() - last_save_time) > (self.saveeach * 60)):\n                self.savedata()                       # save data on files\n                last_save_time = time.time()\n\n            if self.policy.normalize == 1: \n                self.update_normvector()              # the workers overwrite their normalization vector with the vector received from the master\n\n            if self.rank == 0:\n                print('Seed %d (%.1f%%) gen %d msteps %d bestfit %.2f bestgfit %.2f bestsam %.2f avg %.2f weightsize %.2f' %\n                      (self.seed, self.steps / float(self.maxsteps) * 100, self.cgen, self.steps / 1000000, self.bestfit, self.bestgfit, self.bfit, self.avgfit, self.avecenter))\n\n        if self.rank == 0:\n            self.savedata()                           # save data at the end of evolution\n\n        # print simulation time\n        end_time = time.time()\n        print('Simulation time: %dm%ds ' % (divmod(end_time - start_time, 60)))\n\n", "meta": {"hexsha": "099c8b3f6b61fe20fd4ecd91e53855ecba86ac74", "size": 15724, "ext": "py", "lang": "Python", "max_stars_repo_path": "Week-04/evorobotpy2/bin/openaiesp.py", "max_stars_repo_name": "mhd-medfa/BCR22", "max_stars_repo_head_hexsha": "9f892928f293bb9c2c7152e82713f976d8cd0485", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Week-04/evorobotpy2/bin/openaiesp.py", "max_issues_repo_name": "mhd-medfa/BCR22", "max_issues_repo_head_hexsha": "9f892928f293bb9c2c7152e82713f976d8cd0485", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week-04/evorobotpy2/bin/openaiesp.py", "max_forks_repo_name": "mhd-medfa/BCR22", "max_forks_repo_head_hexsha": "9f892928f293bb9c2c7152e82713f976d8cd0485", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-03T17:27:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T17:27:47.000Z", "avg_line_length": 55.5618374558, "max_line_length": 254, "alphanum_fraction": 0.5612439583, "include": true, "reason": "import numpy,from numpy", "num_tokens": 3617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.32766829425520916, "lm_q1q2_score": 0.17660770770195475}}
{"text": "import numpy as np\nimport numba\n\nimport strax\nexport, __all__ = strax.exporter()\n\n# Hardcoded numbers:\nTRIAL_COUNTER_NEIGHBORING_RECORDS = 100  # Trial counter when looking for hitlet data.\nNO_FWXM = -42  # Value in case FWXM cannot be found.\n\n# ----------------------\n# Hitlet building:\n# ----------------------\n@export\ndef concat_overlapping_hits(hits, extensions, pmt_channels, start, end):\n    \"\"\"\n    Function which concatenates hits which may overlap after left and \n    right hit extension. Assumes that hits are sorted correctly.\n\n    Note:\n        This function only updates time, length and record_i of the hit.\n        (record_i is set according to the first hit)\n\n    :param hits: Hits in records.\n    :param extensions: Tuple of the left and right hit extension.\n    :param pmt_channels: Tuple of the detectors first and last PMT\n    :param start: Startime of the chunk\n    :param end: Endtime of the chunk\n\n    :returns:\n        array with concataneted hits.\n    \"\"\"\n    # Getting channel map and compute the number of channels:\n    first_channel, last_channel = pmt_channels\n    nchannels = last_channel - first_channel + 1\n\n    # Buffer for concat_overlapping_hits, if specified in \n    # _concat_overlapping_hits numba crashes.\n    last_hit_in_channel = np.zeros(nchannels,\n                                   dtype=(strax.hit_dtype\n                                          + [(('End time of the interval (ns since unix epoch)',\n                                               'endtime'), np.int64)]))\n\n    if len(hits):\n        hits = _concat_overlapping_hits(hits, extensions, first_channel, last_hit_in_channel, start, end)\n    return hits\n\n\n@strax.utils.growing_result(strax.hit_dtype, chunk_size=int(1e4))\n@numba.njit(nogil=True, cache=True)\ndef _concat_overlapping_hits(hits,\n                             extensions,\n                             first_channel,\n                             last_hit_in_channel,\n                             start=0,\n                             end=float('inf'),\n                             _result_buffer=None):\n    buffer = _result_buffer\n    offset = 0\n\n    le, re = extensions\n    dt = hits['dt'][0]\n    assert np.all(hits['dt'] == dt), 'All hits must have the same dt!'\n\n    for h in hits:\n        st = h['time'] - int(le * h['dt'])\n        et = strax.endtime(h) + int(re * h['dt'])\n        hc = h['channel']\n        r_i = h['record_i']\n\n        lhc = last_hit_in_channel[hc - first_channel]\n        # Have not found any hit in this channel yet:\n        if lhc['time'] == 0:\n            lhc['time'] = max(st, start)\n            lhc['endtime'] = min(et, end)\n            lhc['channel'] = hc\n            lhc['record_i'] = h['record_i']\n            lhc['dt'] = dt\n\n        # Checking if events overlap:\n        else:\n            if lhc['endtime'] >= st:\n                # Yes, so we have to update only the end_time:\n                lhc['endtime'] = et\n            else:\n                # No, this means we have to save the previous data and update lhc:\n                res = buffer[offset]\n                res['time'] = lhc['time']\n                res['length'] = (lhc['endtime'] - lhc['time']) // lhc['dt']\n                res['channel'] = lhc['channel']\n                res['record_i'] = lhc['record_i']\n                res['dt'] = lhc['dt']\n                offset += 1\n                if offset == len(buffer):\n                    yield offset\n                    offset = 0\n\n                # Updating current last hit:\n                lhc['time'] = st\n                lhc['endtime'] = et\n                lhc['channel'] = hc\n                lhc['record_i'] = r_i\n\n    # We went through so now we have to save all remaining hits:\n    mask = last_hit_in_channel['time'] != 0\n    for lhc in last_hit_in_channel[mask]:\n        res = buffer[offset]\n        res['time'] = lhc['time']\n        res['channel'] = lhc['channel']\n        res['length'] = (lhc['endtime'] - lhc['time']) // lhc['dt']\n        res['record_i'] = lhc['record_i']\n        res['dt'] = lhc['dt']\n        offset += 1\n        if offset == len(buffer):\n            yield offset\n            offset = 0\n    yield offset\n\n\n@export\n@numba.njit(nogil=True, cache=True)\ndef refresh_hit_to_hitlets(hits, hitlets):\n    \"\"\"\n    Function which copies basic hit information into a new hitlet array.\n    \"\"\"\n    nhits = len(hits)\n    for ind in range(nhits):\n        h_new = hitlets[ind]\n        h_old = hits[ind]\n\n        h_new['time'] = h_old['time']\n        h_new['length'] = h_old['length']\n        h_new['channel'] = h_old['channel']\n        h_new['area'] = h_old['area']\n        h_new['record_i'] = h_old['record_i']\n        h_new['dt'] = h_old['dt']\n\n\n@export\n@numba.njit(nogil=True, cache=True)\ndef get_hitlets_data(hitlets, records, to_pe):\n    \"\"\"\n    Function which searches for every hitlet in a given chunk the \n    corresponding records data.\n    \n    :param hitlets: Hitlets found in a chunk of records.\n    :param records: Records of the chunk.\n    :param to_pe: Array with area conversion factors from adc/sample to \n        pe/sample\n    \n    Note:\n        hitlets must have a \"data\" and \"area\" field.\n    \n    The function updates the hitlet fields time, length (if necessary \n    e.g. hit was extended in regions of now records) and area\n    according to the found data.\n    \"\"\"\n\n    rlink = strax.record_links(records)\n    for h in hitlets:\n        data, start_time = get_single_hitlet_data(h, records, *rlink)\n        h['length'] = len(data)\n        h['data'][:len(data)] = data * to_pe[h['channel']]\n        h['time'] = start_time\n        h['area'] = np.sum(data * to_pe[h['channel']])\n\n\n@export\n@numba.njit(nogil=True, cache=True)\ndef get_single_hitlet_data(hitlet, records, prev_r, next_r):\n    \"\"\"\n    Function which gets the data of a single hit or hitlet. The data is\n    returned according to the objects time and length (LE/RE is not\n    included in case of a hit.).\n\n    In case the hit or hitlet is extended into non-recorded regions\n    the data gets chopped.\n\n\n    :param hitlet: Hits or hitlets.\n    :param records: Records\n    :param prev_r: Index of the previous record seen from the current\n        record. (Return of strax.record_links)\n    :param next_r: Index of the next record seen by the current record.\n        (Return of strax.record_links)\n    :return:\n        np.ndarray: Samples of the hitlet [ADC]\n        int: Start time of the hitlet. (In case data gets chopped on the\n            left)\n    \"\"\"\n    temp_data = np.zeros(hitlet['length'], dtype=np.float64)\n\n    # Lets get the starting record and the corresponding data:\n    r_i = hitlet['record_i']\n    r = records[r_i]\n    data, (p_start_i, p_end_i) = _get_thing_data(hitlet, r)\n    temp_data[p_start_i:p_end_i] = data\n\n    # We have to store the first and last index of the so far found data \n    data_start = p_start_i\n    data_end = p_end_i\n\n    if not (p_end_i - p_start_i == hitlet['length']):\n        # We have not found the entire data yet....\n        # Starting with data before our current record:\n        trial_counter = 0\n        prev_r_i = r_i\n        while p_start_i:\n            # We are still searching for data in a previous record.\n            temp_prev_r_i = prev_r[prev_r_i]\n            if temp_prev_r_i == -1:\n                # There is no (more) previous record. So stop here and keep\n                # last pre_r_i\n                break\n            prev_r_i = temp_prev_r_i\n\n            # There is a previous record:\n            r = records[prev_r_i]\n            data, (p_start_i, end) = _get_thing_data(hitlet, r)\n            if not end:\n                # If end is zero this means we have not found any\n                # overlap which should not have happened. In case of an\n                # overlap start and end should reflect the start and end\n                # sample of the hitlet for which we found data.\n                print('Data found for this record:', data,\n                      'Start index', p_start_i,\n                      'End index:', end)\n                raise ValueError('This is odd found previous record, but no'\n                                 ' overlapping indices.')\n            temp_data[p_start_i:data_start] = data\n            data_start = p_start_i\n\n            if trial_counter > TRIAL_COUNTER_NEIGHBORING_RECORDS:\n                raise RuntimeError('Tried too hard. There are more than'\n                                   '100 successive records. This is odd...')\n            trial_counter += 1\n\n        # Now we have to do the very same for records in the future:\n        # Almost the same code as above can I change this?\n        trial_counter = 0\n        next_r_i = r_i\n        while hitlet['length'] - p_end_i:\n            # We are still searching for data in a next record.\n            temp_next_r_i = next_r[next_r_i]\n            if temp_next_r_i == -1:\n                # There is no (more) previous record. So stop here and keep\n                # last next_r_i\n                break\n            next_r_i = temp_next_r_i\n            # There is a next record:\n            r = records[next_r_i]\n            data, (start, p_end_i) = _get_thing_data(hitlet, r)\n            if not start:\n                # If start is zero this means we have not found any\n                # overlap which should not have happened. In case of an\n                # overlap start and end should reflect the start and end\n                # sample of the hitlet for which we found data.\n                print('Data found for this record:', data,\n                      'Start index', start,\n                      'End index:', p_end_i)\n                raise ValueError('This is odd found the next record, but no'\n                                 ' overlapping indicies.')\n            temp_data[data_end:p_end_i] = data\n            data_end = p_end_i\n\n            if trial_counter > TRIAL_COUNTER_NEIGHBORING_RECORDS:\n                raise RuntimeError('Tried too hard. There are more than'\n                                   '100 successive records. This is odd...')\n            trial_counter += 1\n\n    # In some cases it might have happened that due to the left and right hit extension\n    # we extended our hitlet into regions without any data so we have to chop\n    # \"time\" according to the data we found....\n    time = hitlet['time'] + data_start * hitlet['dt']\n    temp_data = temp_data[data_start:data_end] + r['baseline'] % 1\n    return temp_data, time\n\n\n@numba.njit(nogil=True, cache=True)\ndef _get_thing_data(thing, container):\n    \"\"\"\n    Function which returns data for some overlapping indices of a thing\n    in a container. \n    \n    Note:\n        Thing must be of the interval dtype kind.\n    \"\"\"\n    overlap_hit_i, overlap_record_i = strax.overlap_indices(thing['time']//thing['dt'],\n                                                            thing['length'],\n                                                            container['time']//container['dt'],\n                                                            container['length'])\n    data = container['data'][overlap_record_i[0]:overlap_record_i[1]]\n    return data, overlap_hit_i\n\n# ----------------------\n# Hitlet splitting:\n# ----------------------\n@export\ndef update_new_hitlets(hitlets, records, next_ri, to_pe):\n    \"\"\"\n    Function which computes the hitlet data area and record_i after\n    splitting.\n\n    :param hitlets: New hitlets received after splitting.\n    :param records: Records of the chunk.\n    :param next_ri: Index of next record for current record record_i.\n    :param  to_pe: ADC to PE conversion factor array (of n_channels).\n    \"\"\"\n    _update_record_i(hitlets, records, next_ri)\n    get_hitlets_data(hitlets, records, to_pe)\n\n\n@numba.njit(cache=True, nogil=True)\ndef _update_record_i(new_hitlets, records, next_ri):\n    \"\"\"\n    Function which updates the record_i value of the new hitlets. \n    \n    Notes:\n        Assumes new_hitlets to be sorted in time.\n    \"\"\"\n    for ind, hit in enumerate(new_hitlets):\n\n        updated = False\n        counter = 0\n        current_ri = hit['record_i']\n        while not updated:\n            r = records[current_ri]\n            # Hitlet must only partially be contained in record_i:\n            time = hit['time']\n            end_time = strax.endtime(hit)\n            start_in = (r['time'] <= time) & (time < strax.endtime(r))\n            end_in = (r['time'] < end_time) & (end_time <= strax.endtime(r))\n            if start_in or end_in:\n                hit['record_i'] = current_ri\n                break\n            else:\n                last_ri = current_ri\n                current_ri = next_ri[current_ri]\n                counter += 1\n                \n            if current_ri == -1:\n                print('Record:\\n', r, '\\nHit:\\n', hit)\n                raise ValueError('Was not able to find record_i')\n\n            if counter > TRIAL_COUNTER_NEIGHBORING_RECORDS:\n                print(ind, last_ri)\n                raise RuntimeError('Tried too often to find correct record_i.')\n\n\n# ----------------------\n# Hitlet properties:\n# ----------------------\n@export\n@numba.njit(cache=True, nogil=True)\ndef hitlet_properties(hitlets):\n    \"\"\"\n    Computes additional hitlet properties such as amplitude, FHWM, etc.\n    \"\"\"\n    for h in hitlets:\n        dt = h['dt']\n        data = h['data'][:h['length']]\n        \n        if np.any(data):\n            # Compute amplitude\n            amp_ind = np.argmax(data)\n            amp_time = int(amp_ind * dt)\n            height = data[amp_ind]\n\n            h['amplitude'] = height\n            h['time_amplitude'] = amp_time\n\n            # Computing FWHM:\n            left_edge, right_edge = get_fwxm(h, 0.5)\n            width = right_edge - left_edge\n\n            # Computing FWTM:\n            left_edge_low, right_edge = get_fwxm(h, 0.1)\n            width_low = right_edge - left_edge_low\n\n            h['fwhm'] = width\n            h['left'] = left_edge\n            h['low_left'] = left_edge_low\n            h['fwtm'] = width_low\n\n\n@export\n@numba.njit(cache=True, nogil=True)\ndef get_fwxm(hitlet, fraction=0.5):\n    \"\"\"\n    Estimates the left and right edge of a specific height percentage.\n\n    :param hitlet: Single hitlet\n    :param fraction: Level for which the width shall be computed.\n    :returns: Two floats, left edge and right edge in ns\n\n    Notes:\n        The function searches for the last sample below and above the\n        specified height level on the left and right hand side of the\n        maximum. When the samples are found the width is estimated based\n        upon a linear interpolation between the respective samples. In\n        case, that the samples cannot be found for either one of the\n        sides the corresponding outer most bin edges are used: left 0;\n        right last sample + 1.\n    \"\"\"\n    data = hitlet['data'][:hitlet['length']]\n\n    index_maximum = np.argmax(data)\n    max_val = data[index_maximum] * fraction\n    if np.all(data > max_val) or np.all(data == 0):\n        # In case all samples are larger, FWXM is not definition.\n        return np.nan, np.nan\n\n    pre_max = data[:index_maximum]  # Does not include maximum\n    post_max = data[1 + index_maximum:]  # same\n\n    if len(pre_max) and np.any(pre_max <= max_val):\n        # First the left edge:\n\n        lbi, lbs = _get_fwxm_boundary(pre_max[::-1], max_val)  # Reversing data starting at sample\n        # before maximum and go left\n        lbi = (index_maximum - 1) - lbi  # start sample minus samples we went to the left\n        m = data[lbi + 1] - lbs  # divided by 1 sample\n        left_edge = lbi + (max_val - lbs) / m + 0.5\n    else:\n        # There is no data before the maximum:\n        left_edge = 0\n\n    if len(post_max) and np.any(post_max <= max_val):\n        # Now the right edge:\n        rbi, rbs = _get_fwxm_boundary(post_max, max_val)  # Starting after maximum and go right\n        rbi += 1 + index_maximum  # sample to the right plus start\n        m = data[rbi - 1] - rbs\n        right_edge = rbi - (max_val - rbs) / m + 0.5\n    else:\n        right_edge = len(data)\n\n    left_edge = left_edge * hitlet['dt']\n    right_edge = right_edge * hitlet['dt']\n    return left_edge, right_edge\n\n\n@numba.njit(cache=True, nogil=True)\ndef _get_fwxm_boundary(data, max_val):\n    \"\"\"\n    Returns sample position and height for the last sample which\n    amplitude is below the specified value.\n\n    If no sample can be found returns position and value of last sample\n    seen.\n\n    Note:\n        For FWHM we assume that we start at the maximum.\n    \"\"\"\n    ind = None\n    s = None\n    for i, d in enumerate(data):\n        if d <= max_val:\n            ind = i\n            s = d\n            return ind, s\n    return len(data)-1, data[-1]\n\n@export\ndef conditional_entropy(hitlets, template='flat', square_data=False):\n    \"\"\"\n    Function which estimates the conditional entropy based on the\n    specified template.\n\n    In order to compute the conditional entropy each hitlet will be\n    aligned such that its maximum falls into the same sample as for the\n    template. If the maximum is ambiguous the first maximum is taken.\n\n    :param hitlets: Hitlets for which the entropy shall be computed.\n        Can be any data_kind which offers the fields data and length.\n    :param template: Template to compare the data with. Can be either\n        specified as \"flat\" to use a flat distribution or as a numpy\n        array containing any normalized template.\n    :param square_data: If true data will be squared and normalized\n        before estimating the entropy. Otherwise the data will only be\n        normalized.\n    :returns: Array containing the entropy values for each hitlet.\n\n    Note:\n        The template has to be normalized such that its total area is 1.\n        Independently of the specified options, only samples for which\n        the content is greater zero are used to compute the entropy.\n\n        In case of the non-squared case negative samples are omitted in\n        the calculation.\n    \"\"\"\n    if not isinstance(template, np.ndarray) and template != 'flat':\n        raise ValueError('Template input not understood. Must be either a numpy array,\\n',\n                         'or \"flat\".')\n\n    if 'data' not in hitlets.dtype.names:\n        raise ValueError('\"hitlets\" must have a field \"data\".')\n\n    if isinstance(template, str) and template == 'flat':\n        template = np.empty(0, dtype=np.float32)\n        flat = True\n    else:\n        flat = False\n    res = _conditional_entropy(hitlets, template, flat=flat,\n                               square_data=square_data)\n    return res\n\n\n@numba.njit(cache=True, nogil=True)\ndef _conditional_entropy(hitlets, template, flat=False, square_data=False):\n    res = np.zeros(len(hitlets), dtype=np.float32)\n    for ind, h in enumerate(hitlets):\n        # h['data'][:] generates just a view and not a copy of the data\n        # Since the data of hitlets should not be modified we have\n        # to use a copy instead.... See also https://stackoverflow.com/questions/4370745/view-onto-a-numpy-array\n        hitlet = np.copy(h['data'][:h['length']])\n\n        # Squaring and normalizing:\n        if square_data:\n            hitlet[:] = hitlet * hitlet\n        if np.sum(hitlet):\n            hitlet[:] = hitlet / np.sum(hitlet)\n        else:\n            # If there is no area we cannot normalize\n            res[ind] = np.nan\n            continue\n\n        if flat:\n            # Take out values which are smaller euqal zero since:\n            # lim x_i --> 0, x_i * log(x_i) --> 0\n            # and log not defined for negative values.\n            m = hitlet > 0\n            hitlet = hitlet[m]\n            len_hitlet = len(hitlet)\n\n            template = np.ones(len_hitlet, dtype=np.float32)\n            template = template / np.sum(template)\n\n            e = - np.sum(hitlet * np.log(hitlet / template))\n        else:\n            # In case of a template we take out zeros and negative values\n            # once we populated the buffer. Otherwise we miss-align\n            # template and buffer.\n\n            # create a buffers to align data and template:\n            len_hitlet = len(hitlet)\n            len_template = len(template)\n            length = np.max(np.array([len_hitlet, len_template]))\n            length = length * 2 + 1\n            buffer = np.zeros((2, length), dtype=np.float32)\n\n            # align data and template and compute entropy:\n            si = length // 2 - np.argmax(hitlet)\n            ei = si + len(hitlet)\n            buffer[0, si:ei] = hitlet[:]\n\n            si = length // 2 - np.argmax(template)\n            ei = si + len(template)\n            buffer[1, si:ei] = template[:]\n\n            # Remove zeros from buffers:\n            m_hit = (buffer[0] > 0)\n            m_temp = (buffer[1] > 0)\n            m = m_hit & m_temp\n            e = - np.sum(buffer[0][m] * np.log(buffer[0][m] / buffer[1][m]))\n        res[ind] = e\n    return res\n", "meta": {"hexsha": "63575d5b1c2af6d80f3938b6072dad192e65e2e3", "size": 20859, "ext": "py", "lang": "Python", "max_stars_repo_path": "strax/processing/hitlets.py", "max_stars_repo_name": "petergaemers/strax", "max_stars_repo_head_hexsha": "e2e65e03cb592d9532db66074a8e193090cf1a50", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "strax/processing/hitlets.py", "max_issues_repo_name": "petergaemers/strax", "max_issues_repo_head_hexsha": "e2e65e03cb592d9532db66074a8e193090cf1a50", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "strax/processing/hitlets.py", "max_forks_repo_name": "petergaemers/strax", "max_forks_repo_head_hexsha": "e2e65e03cb592d9532db66074a8e193090cf1a50", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7883597884, "max_line_length": 112, "alphanum_fraction": 0.5809003308, "include": true, "reason": "import numpy,import numba", "num_tokens": 5080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.17659610096676734}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec  10 15:24:21 2020\n\n@author: L.I.Vazquez-Salazar\n@email: litzavazquezs@gmail.com\n\nExample of a file for the calculation and plotting of KL divergency.\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport os\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib\nfrom metrics import Metrics\n\n#Read all the files related to the bonds with C.\nbonds = []\nfor path, dirs, files in os.walk(\".\"):\n    for file in files:\n        if file.startswith('bonds_C') and file.endswith(\".csv\"):\n            bonds.append(path+\"/\"+file)\n\n\ndef read_files(array):\n    '''\n    Read the list of files and separate them by target or test.\n\n    Parameters\n    ----------\n    array : List of files\n\n    Returns\n    -------\n    values : Dictionary that refeers to each of the dataframes read it. \n\n    '''\n    values = {}\n    for item in array:\n        if item.find('QM9.csv') != -1:\n            values['QM9'] = pd.read_csv(item)\n        elif item.find('PC9.csv') != -1:\n            values['PC9'] = pd.read_csv(item)\n        elif item.find('ANIE.csv') != -1:\n            values['ANIE'] = pd.read_csv(item)\n        elif item.find('PC9_9p.csv') != -1:\n            values['PC9 opt'] = pd.read_csv(item)\n        elif item.find('QM9_9p.csv') != -1:\n            values['QM9 opt'] = pd.read_csv(item)\n        elif item.find('ANIE_9p.csv') != -1:\n            values['ANIE opt'] = pd.read_csv(item)\n            \n    return values\n\nbonds_read = read_files(bonds)\n \n  \ndef getdata(dictionary,key):\n    '''\n    Separate the data for a type of bond for the different databases evaluated.\n    This considers only the reference distribution.\n    \n\n    Parameters\n    ----------\n    dictionary : Created by read_files. It contains the df for each of the databases.\n    key : It is name of the bond on the databases\n\n    Returns\n    -------\n    df : new database for the type of bond selected.\n\n    '''\n    X_ANIE = dictionary['ANIE'][key]\n    X_PC9 = dictionary['PC9'][key]\n    X_QM9 = dictionary['QM9'][key]\n\n    dictionary = {'QM9':X_QM9, 'PC9':X_PC9, 'ANI-1E':X_ANIE}\n    df = pd.DataFrame(dictionary)\n    return df\n\ndef getdata_test(dictionary,key):\n    '''\n    Separate the data for a type of bond for the different databases evaluated.\n    This considers only the target distribution.\n    \n\n    Parameters\n    ----------\n    dictionary : Created by read_files. It contains the df for each of the databases.\n    key : It is name of the bond on the databases\n\n    Returns\n    -------\n    df : new database for the type of bond selected.\n\n    '''\n    X_Tauto_opt_ANIE = dictionary['ANIE opt'][key]\n    X_Tauto_opt_PC9 = dictionary['PC9 opt'][key]\n    X_Tauto_opt_QM9 = dictionary['QM9 opt'][key]\n    \n    dictionary = {'Test set opt QM9':X_Tauto_opt_QM9, 'Test set opt PC9':X_Tauto_opt_PC9\n                  , 'Test set opt ANIE':X_Tauto_opt_ANIE }\n\n    df = pd.DataFrame(dictionary)\n    return df\n\n\nbonds_CC = getdata(bonds_read,'CC')\ntest_CC = getdata_test(bonds_read,'CC')\n\nbonds_CO = getdata(bonds_read, 'CO')\ntest_CO = getdata_test(bonds_read, 'CO')\n\nbonds_CN = getdata(bonds_read, 'CN')\ntest_CN = getdata_test(bonds_read, 'CN')\n\n\ndef compute_KL(reference,target):\n    '''\n    Read the created databases for a specific type of bond and then compute \n    the value of the KL divergency.\n\n    Parameters\n    ----------\n    reference : Dataframe of the values of the bond lenghts of a specific type of bond\n                on the reference databases.\n    target : Datafram of the values of the bond lenghts of a specific type of bond\n                on the target database.\n\n    Returns\n    -------\n    X_values : Evaluated values.\n    KL_values : Values of the cummulative KL\n\n    '''\n    mt = Metrics(reference,target)\n    data_QM9 = mt.get_data('QM9','Test set opt QM9')\n    data_PC9 = mt.get_data('PC9','Test set opt PC9')\n    data_ANIE = mt.get_data('ANI-1E','Test set opt ANIE')\n    \n    QM9_x, QM9_kl = mt.KL_divergence_cum(data_QM9)\n    PC9_x, PC9_kl = mt.KL_divergence_cum(data_PC9)\n    ANIE_x, ANIE_kl = mt.KL_divergence_cum(data_ANIE)\n    \n    KL_values = [QM9_kl,PC9_kl,ANIE_kl]\n    X_values = [QM9_x[1:],PC9_x[1:], ANIE_x[1:]]\n    return X_values, KL_values\n\nX_CC, KL_CC = compute_KL(bonds_CC,test_CC)\nX_CN, KL_CN = compute_KL(bonds_CN,test_CN)\nX_CO, KL_CO = compute_KL(bonds_CO,test_CO)\n\nx_value = np.linspace(1,2,num=999)\n# =============================================================================\n#%%\ncolors = ['firebrick','darkorange','deepskyblue']\ncolors_rgba = []\nfor i in colors:\n    x = matplotlib.colors.to_rgba(i)\n    colors_rgba.append(x)\nnames = ['QM9 KL', 'PC9 KL', 'ANIE KL']\n\nfig, axs = plt.subplots(nrows=3, ncols=3, figsize=(15,15),sharex='col')\nplt.rc('font', family='sans-serif', size=16)\nax1 = sns.kdeplot(data=bonds_CC, ax=axs[0][0], palette=colors_rgba, legend=True, common_norm=False)\nax1.set_title('C-C Bond distribution')\nax1.text(0.85,5,('Reference'),fontsize=35,rotation='vertical')\nax1.set_ylim(0,18)\nax2 = sns.kdeplot(data=test_CC,ax=axs[1][0],fill=False,common_norm=False,legend=False,palette=colors_rgba)\nax2.text(0.85,4.5,('Target'),fontsize=35,rotation='vertical')\nax2.set_ylim(0,18)\nax3 = axs[2][0]\nfor i in range(0,3):\n    ax3.plot(X_CC[i],KL_CC[i], label=names[i],color=colors[i])\n\nax3.set_xlim(1.1,1.7)\nax3.set_ylabel(r'$D_{KL}(P||Q)$')\nax3.set_xlabel(r'r($\\AA$)')\nax3.text(0.85,0.1,('KL-div'),fontsize=35,rotation='vertical')\n\nax4 = sns.kdeplot(data=bonds_CN, ax=axs[0][1], palette=colors_rgba, legend=True, common_norm=False,)\nax4.set_title('C-N Bond distribution')\nax4.set_ylabel('')\nax4.set_ylim(0,18)\nax5 = sns.kdeplot(data=test_CN,ax=axs[1][1],fill=False,common_norm=False,legend=False,palette=colors_rgba)\nax5.set_ylim(0,18)\nax5.set_ylabel('')\nax6 = axs[2][1]\nfor i in range(0,3):\n    ax6.plot(X_CN[i],KL_CN[i], label=names[i],color=colors[i])\n    \nax6.set_xlim(1.1,1.7)\n\nax6.set_xlabel(r'r($\\AA$)')\n\nax7 = sns.kdeplot(data=bonds_CO, ax=axs[0][2], palette=colors_rgba, legend=True, common_norm=False)\nax7.set_title('C-O Bond distribution')\nax7.set_ylabel('')\nax7.set_ylim(0,18)\n\nax8 = sns.kdeplot(data=test_CO,ax=axs[1][2],fill=False,common_norm=False,legend=False,palette=colors_rgba)\nax8.set_ylabel('')\nax8.set_ylim(0,18)\n\nax9 = axs[2][2]\nfor i in range(0,3):\n    ax9.plot(X_CO[i],KL_CO[i], label=names[i],color=colors[i])\n    \nax9.set_xlim(1.1,1.7)\n\nax9.set_xlabel(r'r($\\AA$)')\n\nplt.subplots_adjust(hspace=0)\n#plt.savefig('C-bonds-dist-KL_9p.pdf',bbox_inches='tight')\n# plt.show()\n", "meta": {"hexsha": "f49e93f7b21ff10383cc6b167a728a4bcadecc0c", "size": 6491, "ext": "py", "lang": "Python", "max_stars_repo_path": "KL/Example_KL_cum.py", "max_stars_repo_name": "LIVazquezS/TautomersPaper", "max_stars_repo_head_hexsha": "b1c4ae9aad233aa8dff0b9d381a20f9032cc0ff6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "KL/Example_KL_cum.py", "max_issues_repo_name": "LIVazquezS/TautomersPaper", "max_issues_repo_head_hexsha": "b1c4ae9aad233aa8dff0b9d381a20f9032cc0ff6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "KL/Example_KL_cum.py", "max_forks_repo_name": "LIVazquezS/TautomersPaper", "max_forks_repo_head_hexsha": "b1c4ae9aad233aa8dff0b9d381a20f9032cc0ff6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6392694064, "max_line_length": 106, "alphanum_fraction": 0.6515174857, "include": true, "reason": "import numpy", "num_tokens": 1911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.17659610096676728}}
{"text": "# -*- coding: utf-8 -*-\n\n#Created on Tue Jun 25 21:59:42 2019\n#\n#@Author: Zhi-Jiang Yang, Dong-Sheng Cao\n#@Institution: CBDD Group, Xiangya School of Pharmaceutical Science, CSU, China，\n#@Homepage: http://www.scbdd.com\n#@Mail: yzjkid9@gmail.com; oriental-cds@163.com\n#@Blog: https://blog.moyule.me\n\n\n\nfrom itertools import combinations\nimport sys,csv,os\nimport numpy as np\n\nfrom rdkit import RDConfig\nfrom rdkit.Chem import AllChem as Chem\nfrom rdkit.Chem import Descriptors, Lipinski, QED\nfrom rdkit.Chem.Scaffolds import MurckoScaffold\nsys.path.append(RDConfig.RDContribDir)\n\nfrom SA_Score import sascorer\nfrom NP_Score import npscorer\nfrom IFG.ifg import identify_functional_groups\n\ntry:\n    from ..fingerprint import fingerprints\nexcept:\n    sys.path.append(__file__+'/..')\n    from fingerprint import fingerprints\n\ntry:\n    from .. import ScoConfig\nexcept:\n    sys.path.append('..')\n    import ScoConfig\n\n\n\nContriDir = RDConfig.RDContribDir\nfilename = os.path.join(ContriDir, 'NP_Score/publicnp.model.gz')\nfscore = npscorer.pickle.load(npscorer.gzip.open(filename)) \n\n\ndef CalculateMolWeight(mol):    \n    \"\"\"\n    Calculation of molecular weight(contain hydrogen atoms)   \n    --->MW  \n\n    :param mol: molecule\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the weight of molecule(contain hydrogen atoms)\n    :rtype: float\n    \n    \"\"\"\n    MW = Descriptors.ExactMolWt(mol)\n    return round(MW, 2)\n\n\ndef CalculateNumBonds(mol):\n    \"\"\"\n    Calculation the number of bonds where between heavy atoms       \n    --->nBond\n        \n    :param mol: molecule\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of bonds where between heavy atoms\n    :rtype: int\n    \n    \"\"\"\n    nBond = mol.GetNumBonds()    \n    return nBond\n\n\ndef CalculateNumAtoms(mol):\n    \"\"\"\n    Calculation of the number of atoms in molecular(contain hydrogen atoms) \n    --->nAtom\n    \n    :param mol: molecule\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of atoms in molecular(contain hydrogen atoms)\n    :rtype: int\n    \n    \"\"\"  \n    mol = Chem.AddHs(mol)\n    return mol.GetNumAtoms()\n   \n\ndef CalculateNumHetero(mol):\n    \"\"\"\n    Calculation of the number of heteroatom in a molecule  \n    --->nHet\n    \n    :param mol: molecule\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of heteroatom in a molecule  \n    :rtype: int\n    \n    \"\"\"\n    i = len(\n            [atom for atom in mol.GetAtoms()\\\n             if atom.GetAtomicNum() in [1, 6]]\n            )\n    nHet = mol.GetNumAtoms()-i\n    return nHet\n\n\ndef CalculateNumRotatableBonds(mol):\n    \"\"\"\n    Calculation of the number of rotatableBonds\n    --->nRot\n    \n    Note:\n        In some situaion Amide C-N bonds are not considered \n        because of their high rotational energy barrier\n    \n    :param mol: molecule\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of rotatableBond  \n    :rtype: int\n    \n    \n    \"\"\"\n    patt = Chem.MolFromSmarts('[!$(*#*)&!D1]-&!@[!$(*#*)&!D1]')\n    nRot = len(mol.GetSubstructMatches(patt))    \n    return nRot\n\n\ndef CalculateNumRigidBonds(mol):\n    \"\"\"\n    Number of non-flexible bonds, in opposite to rotatable bonds    \n    --->nRig\n    \n    :param mol: molecule\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of non-flexible bonds \n    :rtype: int\n    \n    \"\"\"\n    nBOND = CalculateNumBonds(mol)    \n    flex = 0\n    for bond in mol.GetBonds():\n        bondtype = bond.GetBondType()\n        if bondtype == Chem.rdchem.BondType.SINGLE and not bond.IsInRing():\n            flex+=1 \n    nRig = nBOND-flex                \n    return nRig\n\n\ndef CalculateFlexibility(mol):\n    \"\"\"\n    The flexibility (ration between rotatable and rigid bonds)\n    --->Flex\n    \n    :param mol: molecule\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of ring   \n    :rtype: float\n    \n    \"\"\"\n    nRot = CalculateNumRotatableBonds(mol)\n    nRig = CalculateNumRigidBonds(mol)\n    return round(nRot/nRig, 2) if nRig else np.float('nan')\n   \n    \ndef CalculateNumRing(mol):\n    \"\"\"\n    Calculation of the number of ring   \n    --->nRing\n    \n    :param mol: molecule\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of ring   \n    :rtype: int\n    \n    \"\"\"\n    nRing = Chem.GetSSSR(mol)    \n    return nRing\n\n\ndef CalculateNumHeavyAtom(mol):\n    \"\"\"\n    Calculation of Heavy atom counts in a molecule   \n    --->nHev\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of heavy atom counts in a molecule  \n    :rtype: int\n    \n    \"\"\"\n    nHev = mol.GetNumHeavyAtoms()\n    return nHev\n\n\ndef CalculateLogD(mol):\n    \"\"\"\n    Calculation of molecular logD under pH=7.4\n    --->LogD\n    \n    Note:\n        We have built a liner model with DNN to predict logD7.4.\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: molecular logD under pH=7.4 \n    :rtype: float\n    \n    \"\"\"\n    intercept = 0.5748907159915493\n    \n    fps = fingerprints.CalculateGhoseCrippen([mol]).flatten()\n    with open(ScoConfig.CrippenDir + '\\\\Crippen.txt') as f_obj:\n        lines = csv.reader(f_obj,delimiter='\\t')\n        next(lines)\n        contri = [x[-1] for x in lines]\n        contri = [float(x) for x in contri]\n    f_obj.close()\n    logD = sum([a*b for a,b in zip(fps,contri)]) + intercept\n    return logD\n\n\ndef CalculateLogP(mol):    \n    \"\"\"\n    Calculation of molecular LogP\n    --->logP\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: molecular logP \n    :rtype: float\n    \n    \"\"\"  \n    logP = round(Descriptors.MolLogP(mol), 2)  \n    return logP\n\n\ndef CheckAcid(mol):\n    \"\"\"\n    Judge a molecular whether is acid via SMARTS.\n    These SMARTS retrived from https://www.daylight.com/dayhtml_tutorials/languages/smarts/smarts_examples.html\n    --->ab\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: classification to acid or base\n    :rtype: str\n    \n    \"\"\"\n    acid_fragment = ['[!H0;F,Cl,Br,I,N+,$([OH]-*=[!#6]),+]',\n                     '[CX3](=O)[OX2H1]',\n                     '[CX3](=O)[OX1H0-,OX2H1]',\n                     '[$([OH]-*=[!#6])]',\n                     '[$(P(=[OX1])([$([OX2H]),$([OX1-]),$([OX2]P)])([$([OX2H]),$([OX1-]),$([OX2]P)])[$([OX2H]),$([OX1-]),$([OX2]P)]),$([P+]([OX1-])([$([OX2H]),$([OX1-]),$([OX2]P)])([$([OX2H]),$([OX1-]),$([OX2]P)])[$([OX2H]),$([OX1-]),$([OX2]P)])]',\n                     '[$([#16X4](=[OX1])(=[OX1])([#6])[OX2H,OX1H0-]),$([#16X4+2]([OX1-])([OX1-])([#6])[OX2H,OX1H0-])]',\n                     '[CX3](=[OX1])[F,Cl,Br,I]'\n                     ]\n    for sma in acid_fragment:\n        patt = Chem.MolFromSmarts(sma)\n        if mol.HasSubstructMatch(patt):\n            return 'acid'\n    else:\n        return 'base'        \n  \n      \ndef CalculatepKa(mol):\n    from math import log10\n    \"\"\"\n    Calculating pKa based on the ralation between logD and logP in specific pH.\n    --->pKa\n    \n    Eq.:\n        abs(pH-pKa) = log10(10^(logP-logD)-1)\n        pKa = pH - log10(10^(logP-logD)-1) for acid\n        pKa = log10(10^(logP-logD)-1) - pH for base\n        \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: molecular pKa\n    :rtype: float\n    \n    \"\"\"\n    logP = CalculateLogP(mol)\n    logD = CalculateLogD(mol)\n    status = CheckAcid(mol)\n    try:\n        if status == 'acid':\n            pKa = 7.4 - log10(10**(logP-logD)-1)\n        else:\n            pKa = log10(10**(logP-logD)-1) - 7.4\n        return pKa\n    except:\n        return np.float('nan')\n    \n    \ndef CalculateMolMR(mol):\n    \"\"\"\n    Cacluation of molecular refraction value based on Crippen method \n    --->MR\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: molecular refraction value based on Crippen method\n    :rtype: float\n    \n    \"\"\"\n    MR = round(Descriptors.MolMR(mol), 2) \n    return MR\n\n\ndef CalculateNumHDonors(mol):    \n    \"\"\"\n    Caculation of the number of Hydrogen Bond Donors\n    --->nHD\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of Hydrogen Bond Donors\n    :rtype: int\n    \n    \"\"\"\n    nHD = Lipinski.NumHDonors(mol)    \n    return nHD\n\n\ndef CalculateNumHAcceptors(mol):    \n    \"\"\"\n    Caculation of the number of Hydrogen Bond Acceptors  \n    --->nHA\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of Hydrogen Bond Acceptors\n    :rtype: int\n    \n    \"\"\"\n    nHA = Lipinski.NumHAcceptors(mol)    \n    return nHA\n\n\ndef CalculateNumHyBond(mol):\n    \"\"\"\n    Sum of Hydrogen Bond Donnors and Acceptors   \n    --->nHB\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: sum of Hydrogen Bond Donnors and Acceptors\n    :rtype: int\n    \n    \"\"\"\n    nHD = CalculateNumHDonors(mol)\n    nHA = CalculateNumHAcceptors(mol)\n    nHB = nHD+nHA\n    return nHB\n\n\ndef CalculateNumAromaAtom(mol):\n    \"\"\"\n    Calculation of aromatic atom counts in a molecule\n    --->nAAtom\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the aromatic atom counts in a molecule\n    :rtype: int\n    \n    \"\"\"\n    aroma = len(mol.GetSubstructMatches(Chem.MolFromSmarts('[a]')))\n    return aroma\n\n\ndef CalculateNumAromaRing(mol):\n    n = 0\n    aatom = mol.GetSubstructMatches(Chem.MolFromSmarts('[a]'))\n    aatom = sum(aatom,())\n    if aatom:\n        ringinfo = mol.GetRingInfo()\n        for info in ringinfo.AtomRings():\n            n += 1 if set(info) == set(info)&set(aatom) else 0\n    else:\n        pass\n    return n\n\n\ndef CalculateAromaticProportion(mol):\n    \"\"\"\n    The proportion of heavy atoms in the molecule that are in an aromatic ring  \n    --->AP\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the proportion of heavy atoms in the molecule that are in an aromatic ring  \n    :rtype: float\n    \n    \"\"\"\n    aroma = CalculateNumAromaAtom(mol)\n    total = CalculateNumHeavyAtom(mol)\n    AP = round(aroma/total, 2) if total else np.float('nan')\n    return AP  \n    \n\ndef CalculateLogSw(mol):\n    \"\"\"\n    The logSw represents the logarithm of compounds water solubility computed by the ESOL method\n    --->logSw\n    \n    Equation: \n        Log(Sw) = 0.16-0.638*clogP-0.0062*MWT+0.066*RB-0.74*AP\n        where, MWT: Molecular Weight; RB: Rotatable bonds; AP: Aromatic proportion\n    \n    Reference:\n        (1) `Delaney, John S (2004)`_. \n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the molecular logSw\n    :rtype: float\n    \n    .. _Delaney, John S (2004):\n        https://pubs.acs.org/doi/abs/10.1021/ci034243x\n        \n    \"\"\"\n    #Calculate each property\n    MWT = CalculateMolWeight(mol)\n    RB = CalculateNumRotatableBonds(mol)\n    AP = CalculateAromaticProportion(mol)\n    logP = CalculateLogP(mol)  \n    logSw = 0.16-0.638*logP-0.0062*MWT+0.066*RB-0.74*AP   \n    return round(logSw,2)\n\n\ndef CalculateFsp3(mol):\n    \"\"\"\n    Fsp3 (carbon bond saturation) is defined as the number of sp3 hybridized carbons / total carbon count.   \n    --->FSP3\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the carbon bond saturation\n    :rtype: float\n    \n    \"\"\"\n    return round(Lipinski.FractionCSP3(mol), 2)\n    \n\ndef CalculateTPSA(mol):\n    \"\"\"\n    Calculation of TPSA   \n    --->TPSA\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: TPSA\n    :rtype: float\n    \n    \"\"\"\n    TPSA = round(Descriptors.TPSA(mol), 2)\n    return TPSA\n    \n           \ndef CalculateQEDmean(mol):\n    \"\"\"\n    Calculation QED descriptor under different weights \n    A descriptor a measure of drug-likeness based on the concept of desirability\n    Here, calculating the QED descriptor using average descriptor weights.\n    --->QEDmean\n    \n    Reference:\n        (1) `Bickerton, G. Richard (2012)`_.\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: QED descriptor using average descriptor weights\n    :rtype: float\n    \n    .. _Bickerton, G. Richard (2012):\n        https://www.nature.com/nchem/journal/v4/n2/abs/nchem.1243.html\n        \n    \"\"\"    \n    QEDmean = QED.weights_mean(mol)        \n    return round(QEDmean, 2) \n\n\ndef CalculateQEDmax(mol):\n    \"\"\"\n    Calculation QED descriptor under different weights   \n    A descriptor a measure of drug-likeness based on the concept of desirability\n    Here, calculating the QED descriptor using maximal descriptor weights.\n    --->QEDmax\n    \n    Reference:\n        (1) `Bickerton, G. Richard (2012)`_.\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: QED descriptor using maximal descriptor weights\n    :rtype: float\n    \n    .. _Bickerton, G. Richard (2012):\n        https://www.nature.com/nchem/journal/v4/n2/abs/nchem.1243.html\n        \n    \"\"\"    \n    QEDmax = QED.weights_max(mol)        \n    return round(QEDmax,2)     \n\n\ndef CalculateQEDnone(mol):\n    \"\"\"\n    Calculation QED descriptor under different weights   \n    A descriptor a measure of drug-likeness based on the concept of desirability\n    Here, calculating the QED descriptor using unit weights.\n    --->QEDnone\n    \n    Reference:\n        (1) `Bickerton, G. Richard (2012)`_.\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: QED descriptor using unit weights\n    :rtype: float\n    \n    .. _Bickerton, G. Richard (2012):\n        https://www.nature.com/nchem/journal/v4/n2/abs/nchem.1243.html\n        \n    \"\"\"    \n    QEDnone = QED.weights_none(mol)        \n    return round(QEDnone,2)\n\n\ndef CalculateMaxSizeSystemRing(mol):\n    \"\"\"\n    Number of atoms involved in the biggest system ring  \n    ---> maxring\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: number of atoms involved in the biggest system ring\n    :rtype: int\n    \n    \"\"\"\n    #0.Get the scaffold\n    core = MurckoScaffold.GetScaffoldForMol(mol)\n    fw = MurckoScaffold.MakeScaffoldGeneric(core)\n    #1.Obtaining which atoms consist of rings\n    MaxRing = 0\n    ri = fw.GetRingInfo()\n    atoms = list(ri.AtomRings())    \n    length = len(atoms)    \n    if length == 0:\n        pass\n    else:\n        rw = Chem.RWMol(fw)        \n        #2.Judge which atoms are replacement\n        atoms = [set(x) for x in atoms]            \n        for pair in combinations(range(length),2):\n            replace = list(atoms[pair[0]]&atoms[pair[1]])\n            if len(replace) >= 2:\n                for repl in list(combinations(replace,2)):\n                    rw.RemoveBond(*repl)\n            else:\n                pass    \n        m = Chem.MolFromSmiles(Chem.MolToSmiles(rw))\n        ri = m.GetRingInfo()\n        bonds = ri.BondRings()\n        for item in bonds:\n            if len(item) > MaxRing:\n                MaxRing = len(item)   \n    return MaxRing\n    \n\ndef CalculateNumStereocenters(mol):\n    \"\"\"\n    the number of stereo centers\n    --->nStereo\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of stereo centers\n    :rtype: int\n    \n    \"\"\"\n    return Chem.CalcNumAtomStereoCenters(mol)    \n\n\ndef _CalculateNumElement(mol, AtomicNumber=6):\n    \"\"\"\n    **Internal used only**\n    Calculation of specific type of atom number in a molecule\n    \n    Calculation of element counts with atomic number equal to n in a molecule\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :param AtomicNumber: the AtomicNumber of atom to be counted, defaults to 6\n    :type AtomicNumber: int, optional\n    :return: the number of stereo centers\n    :rtype: int\n    \n    \"\"\"\n    return len(\n            [atom for atom in mol.GetAtoms()\\\n                if atom.GetAtomicNum() == AtomicNumber]\n            )\n\n\ndef CalculateNumCarbon(mol):\n    \"\"\"\n    Calculation of Carbon number in a molecule    \n    --->nC\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of carbon atoms\n    :rtype: int\n    \n    \"\"\"\n    return _CalculateNumElement(mol,AtomicNumber=6)\n\n\ndef CalculateNumBoron(mol):\n    \"\"\"\n    Calculation of Boron counts in a molecule  \n    --->nB\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of boron atoms\n    :rtype: int\n    \n    \"\"\"       \n    return _CalculateNumElement(mol,AtomicNumber=5)\n\n\ndef CalculateNumFluorin(mol):\n    \"\"\"\n    Calculation of Fluorin counts in a molecule  \n    --->nF\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of fluori atoms\n    :rtype: int\n    \n    \"\"\"         \n    return _CalculateNumElement(mol, AtomicNumber=10)\n\n\ndef CalculateNumChlorin(mol):\n    \"\"\"\n    Calculation of Chlorin counts in a molecule\n    --->nCl\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of chlorin atoms\n    :rtype: int\n    \n    \"\"\"\n    return _CalculateNumElement(mol, AtomicNumber=17)\n\n\ndef CalculateNumBromine(mol):\n    \"\"\"\n    Calculation of Bromine counts in a molecule  \n    --->nBr\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of bromine atoms\n    :rtype: int\n    \n    \"\"\"\n    return _CalculateNumElement(mol, AtomicNumber=35)\n\n\ndef CalculateNumIodine(mol):\n    \"\"\"\n    Calculation of Iodine counts in a molecule \n    --->nI\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of bromine atoms\n    :rtype: int\n    \n    \"\"\"\n    return _CalculateNumElement(mol, AtomicNumber=53)\n\n\ndef CalculateNumPhosphor(mol):\n    \"\"\"\n    Calcualtion of Phosphor number in a molecule\n    --->nP\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of phosphor atoms\n    :rtype: int\n    \n    \"\"\"\n    return _CalculateNumElement(mol,AtomicNumber=15)\n\n\ndef CalculateNumSulfur(mol):\n    \"\"\"\n    Calculation of Sulfur counts in a molecule  \n    --->nS\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of sulfur atoms\n    :rtype: int\n    \n    \"\"\"\n    return _CalculateNumElement(mol,AtomicNumber=16)\n\n\ndef CalculateNumOxygen(mol):\n    \"\"\"\n    Calculation of Oxygen counts in a molecule    \n    --->nO\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of oxygen atoms\n    :rtype: int\n    \n    \"\"\"\n    return _CalculateNumElement(mol,AtomicNumber=8)\n        \n\ndef CalculateNumNitrogen(mol):\n    \"\"\"\n    Calculation of Nitrogen counts in a molecule\n    --->nN\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of nitrogen atoms\n    :rtype: int\n    \n    \"\"\"\n    return _CalculateNumElement(mol,AtomicNumber=7)\n\n\n# def CalculateNumberChargedGroups(mol):\n#     \"\"\"\n#     Number of Charged Groups \n#     --->nChar\n    \n#     :param mol: molecular\n#     :type mol: rdkit.Chem.rdchem.Mol\n#     :return: the number of charged group\n#     :rtype: int\n    \n#     \"\"\"\n#     pass\n\n\ndef CalculateHetCarbonRatio(mol):\n    \"\"\"\n    The ratio between the number of non carbon atoms and the number of carbon atoms.\n    --->HetRatio\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the ratio between the number of non carbon atoms and the number of carbon atoms\n    :rtype: float\n    \n    \"\"\"\n    nHet = CalculateNumHetero(mol)\n    nCarb = CalculateNumCarbon(mol)\n    return round(nHet/nCarb,2) if nCarb else np.float('nan')\n    \n\ndef CalculateSAscore(mol):\n    \"\"\"\n    A function to estimate ease of synthesis (synthetic accessibility) of drug-like molecules\n    --->SAscore\n    \n    Reference:\n        (1) `Ertl Peter (2009)`_.\n        \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: ease of synthesis\n    :rtype: float\n    \n    .. _Ertl Peter (2009):\n        https://jcheminf.biomedcentral.com/articles/10.1186/1758-2946-1-8\n        \n    \"\"\"\n    return round(sascorer.calculateScore(mol), 2)\n\n\ndef CalculateNPscore(mol):\n    \"\"\"\n    A function to calculate the natural product-likeness score\n    --->NPscore\n    \n    Reference:\n        (1) `Ertl Peter (2008)`_.\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: product-likeness score\n    :rtype: float\n    \n    .. _Ertl Peter (2008):\n        https://pubs.acs.org/doi/abs/10.1021/ci700286x\n    \n    \"\"\"\n    return round(npscorer.scoreMol(mol,fscore=fscore), 2)\n\n    \ndef GetIFG(mol):\n    \"\"\"\n    A function to compute functional groups in organic molecules\n    --->IFG\n    \n    Reference:\n        (1) `Ertl Peter (2017)`_.\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: list of namedtuple, namedtuple('IFG', ['atomIds', 'atoms', 'type'])\n    :rtype: list\n    \n    .. _Ertl Peter (2017):\n        https://jcheminf.biomedcentral.com/articles/10.1186/s13321-017-0225-z\n        \n    \"\"\"\n    return [fg._asdict() for fg in identify_functional_groups(mol)]\n\n\ndef CalculateMolVolume(mol):\n    \"\"\"\n    Calculation of Van der Waals Volume of molecule\n    --->MV\n    \n    Equation: \n        for single atom: Vw = 4/3*pi*rw^3, the rw is the Van der Waals radius of atom\n        VvdW = ∑(atom contributions)-5.92NB(Unit in Å^3), NB is the total number of bonds\n        the Van der Waals radius of atom is derived from wikipedia.\n        \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: Van der Waals Volume of molecule\n    :rtype: float\n    \n    \"\"\"\n    from math import pi\n    Radii = {'H':1.20,'C':1.70,'N':1.55,\n             'O':1.52,'S':1.80,'P':1.80,\n             'F':1.47,'Cl':1.75,'Br':1.85,\n             'I':1.98,'Na':2.27,'Mg':1.73,\n             'K':2.75,'Ca':2.31,'Ba':2.68,\n             'He':140,'Li':182,'Be':153,\n             'B':192,'Ne':154,'Al':184,\n             'Si':210,'Ar':188,'Ni':163,\n             'Cu':140,'Zn':139,'Ga':187,\n             'Ge':211,'As':185,'Se':190,\n             'Kr':202,'Rb':303,'Sr':249,\n             'Pd':163,'Ag':172,'Cd':158,\n             'In':193,'Sn':217,'Sb':206,\n             'Te':206,'Xe':216,'Cs':343,\n             'Pt':175,'Au':166,'U':186,\n             'Hg':155,'Tl':196,'Pb':202,\n             'Bi':207,'Po':197,'At':202,\n             'Rn':220,'Fr':348,'Ra':283}\n    mol = Chem.AddHs(mol)\n    contrib = []\n    for atom in mol.GetAtoms():\n        try:\n            contrib.append(Radii[atom.GetSymbol()])\n        except:\n            pass\n    # contrib = [Radii[atom.GetSymbol()] for atom in mol.GetAtoms()]\n    contrib = [pi*(r**3)*4/3 for r in contrib]\n    vol = sum(contrib) - 5.92*len(mol.GetBonds())\n    return round(vol, 2)\n\n\ndef CalculateMolDensity(mol):\n    \"\"\"\n    Calculation of density of molecule\n    --->Dense\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: density of molecule\n    :rtype: float\n    \n    \"\"\"\n    MW = CalculateMolWeight(mol)\n    Vol = CalculateMolVolume(mol)\n    return round(MW/Vol, 2) if Vol else np.float('nan')\n\n\ndef CalculateMolFCharge(mol):\n    \"\"\"\n    Calculation of formal charge of molecule\n    --->fChar\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: formal charge of molecule\n    :rtype: float\n    \n    \"\"\"\n    mol = Chem.AddHs(mol)\n    FChar = [atom.GetFormalCharge() for atom in mol.GetAtoms()]\n    return sum(FChar)\n\n\ndef _CalculateNumBond(mol,btype):\n    \"\"\"\n    **Internal used only**\n    Calculation of specific type of bond number in a molecule\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :param btype: the type of bond to be counted\n    :type btype: str\n    :return: the number of specific bond\n    :rtype: int\n    \n    \"\"\"\n    if btype == 'SINGLE':\n        return len([bond for bond in mol.GetBonds() \n                    if bond.GetBondType() == Chem.rdchem.BondType.SINGLE])\n    elif btype == 'DOUBLE':\n        return len([bond for bond in mol.GetBonds() \n                    if bond.GetBondType() == Chem.rdchem.BondType.DOUBLE])\n    elif btype == 'TRIPLE':\n        return len([bond for bond in mol.GetBonds() \n                    if bond.GetBondType() == Chem.rdchem.BondType.TRIPLE])\n\n\ndef CalculateNumSinBond(mol):\n    \"\"\"\n    Calculation of single bond number of molecule\n    ---> nSingle\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of single bond\n    :rtype: int\n    \n    \"\"\"\n    return _CalculateNumBond(mol, btype='SINGLE')\n\n\ndef CalculateNumDouBond(mol):\n    \"\"\"\n    Calculation of double bond number of molecule\n    --->nDouble\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of double bond\n    :rtype: int\n    \n    \"\"\"\n    return _CalculateNumBond(mol, btype='DOUBLE')\n\n\ndef CalculateNumTriBond(mol, btype='TRIPLE'):\n    \"\"\"\n    Calculation of triple bond number of molecule\n    ---> nTriple\n    \n    :param mol: molecular\n    :type mol: rdkit.Chem.rdchem.Mol\n    :return: the number of triple bond\n    :rtype: int\n    \n    \"\"\"\n    return _CalculateNumBond(mol, btype='TRIPLE')\n\n\ndef GetProperties(mol, \n                  items=['MW','Vol','Dense','fChar','nBond','nAtom','nHD','nHA','nHB',\n                         'nHet','nStero','nHev','nRot','nRig','Flex','nRing','logP',\n                         'logD','pKa','logSw','ab','MR','TPSA','AP','HetRatio','Fsp3',\n                         'MaxRing','QEDmean','QEDmax','QEDnone','SAscore','NPscore',\n                         'nSingle','nDouble','nTriple','nC','nB','nF','nCl','nBr','nI',\n                         'nP','nS','nO','nN']\n        ):\n    \"\"\"\n    Get all properties in scopy\n    \"\"\"\n    funcl = {'MW': 'CalculateMolWeight(mol)',\n    'Vol': 'CalculateMolVolume(mol)',\n    'Dense': 'CalculateMolDensity(mol)',\n    'fChar': 'CalculateMolFCharge(mol)',\n    'nBond': 'CalculateNumBonds(mol)',\n    'nAtom': 'CalculateNumAtoms(mol)',\n    'nHet': 'CalculateNumHetero(mol)',\n    'nRot': 'CalculateNumRotatableBonds(mol)',\n    'nRig': 'CalculateNumRigidBonds(mol)',\n    'Flex': 'CalculateFlexibility(mol)',\n    'nRing': 'CalculateNumRing(mol)',\n    'nHev': 'CalculateNumHeavyAtom(mol)',\n    'logP': 'CalculateLogP(mol)',\n    'logD': 'CalculateLogD(mol)',\n    'pKa': 'CalculatepKa(mol)',\n    'ab': 'CheckAcid(mol)',\n    'MR': 'CalculateMolMR(mol)',\n    'nHD': 'CalculateNumHDonors(mol)',\n    'nHA': 'CalculateNumHAcceptors(mol)',\n    'nHB': 'CalculateNumHyBond(mol)',\n    'AP': 'CalculateAromaticProportion(mol)',\n    'logSw': 'CalculateLogSw(mol)',\n    'Fsp3': 'CalculateFsp3(mol)',\n    'TPSA': 'CalculateTPSA(mol)',\n    'MaxRing': 'CalculateMaxSizeSystemRing(mol)',\n    'nStero': 'CalculateNumStereocenters(mol)',\n    'HetRatio': 'CalculateHetCarbonRatio(mol)',\n    'QEDmean': 'CalculateQEDmean(mol)',\n    'QEDmax': 'CalculateQEDmax(mol)',\n    'QEDnone': 'CalculateQEDnone(mol)',\n    'SAscore': 'CalculateSAscore(mol)',\n    'NPscore': 'CalculateNPscore(mol)',\n    'nSingle': 'CalculateNumSinBond(mol)',\n    'nDouble': 'CalculateNumDouBond(mol)',\n    'nTriple': 'CalculateNumTriBond(mol)',\n    'nC': 'CalculateNumCarbon(mol)',\n    'nB': 'CalculateNumBoron(mol)',\n    'nF': 'CalculateNumFluorin(mol)',\n    'nCl': 'CalculateNumChlorin(mol)',\n    'nBr': 'CalculateNumBromine(mol)',\n    'nI': 'CalculateNumIodine(mol)',\n    'nP': 'CalculateNumPhosphor(mol)',\n    'nS': 'CalculateNumSulfur(mol)',\n    'nO': 'CalculateNumOxygen(mol)',\n    'nN': 'CalculateNumNitrogen(mol)'}\n    \n    vals = []\n    for item in items:\n        val = eval(funcl[item])\n        vals.append(val)\n        \n    return dict(zip(items, vals))\n\n\n\n\nif __name__ =='__main__':\n    \n    smis = [\n            'C1=CC=CC(C(Br)C)=C1',\n            'C1=CC2NC(=O)CC3C=2C(C(=O)C2C=CC=CC=23)=C1',\n            'C1=CC=C2C(=O)C3C=CNC=3C(=O)C2=C1',\n            'C1=NC(CCN)=CN1',\n            'C1CCCC(CCO)C1',\n            'C1=CC=C2N=C(O)C=CC2=C1',\n            'C(OC)1=C(C)C=C2OC[C@]([H])3OC4C(C)=C(OC)C=CC=4C(=O)[C@@]3([H])C2=C1C',\n            'C1=C2N=CC=NC2=C2N=CNC2=C1',\n            'C1=C(O)C=CC(O)=C1',\n            'CCC1(c2ccccc2)C(=O)NC(=O)NC1=O',\n            'N1=CN=CN=C1',\n            'C1=C2C=CC=CC2=CC2C=CC=CC1=2', #NonGenotoxic_Carcinogenicity\n            'C1=CC=C2C(=O)CC(=O)C2=C1', #Pains\n            'C1=CC=CC(COCO)=C1', #Potential_Electrophilic\n            'N1=NC=CN1C=O', #Promiscuity\n            'CC(=O)OC(=O)C1C=COC1', #Skin_Sensitization\n            'S',\n            'CCCCC(=O)[H]', #Biodegradable\n            'C1=CN=C(C(=O)O)C=C1', #Chelating\n            'C(OC)1=CC=C2OCC3OC4C=C(OC)C=CC=4C(=O)C3C2=C1',\n            'C1=C2N=CC=NC2=C2N=CNC2=C1', #Genotoxic_Carcinogenicity_Mutagenicity\n            'N(CC)(CCCCC)C(=S)N', #Idiosyncratic\n            ]\n    \n    for index, smi in enumerate(smis):\n        mol = Chem.MolFromSmiles(smi)\n        print('Index:{}'.format(index))\n        res = GetProperties(mol=mol)\n        print(res)\n    \n\n        \n        \n", "meta": {"hexsha": "d20552f59d1201c79dfe29cfd546393afde779fc", "size": 28597, "ext": "py", "lang": "Python", "max_stars_repo_path": "scopy/druglikeness/molproperty.py", "max_stars_repo_name": "SorchaYang/Scopy", "max_stars_repo_head_hexsha": "897f9f0f41a90e0cff1e2fd28a7e82cfac051306", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-05-07T10:42:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T01:13:38.000Z", "max_issues_repo_path": "scopy/druglikeness/molproperty.py", "max_issues_repo_name": "SorchaYang/Scopy", "max_issues_repo_head_hexsha": "897f9f0f41a90e0cff1e2fd28a7e82cfac051306", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scopy/druglikeness/molproperty.py", "max_forks_repo_name": "SorchaYang/Scopy", "max_forks_repo_head_hexsha": "897f9f0f41a90e0cff1e2fd28a7e82cfac051306", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2840073529, "max_line_length": 248, "alphanum_fraction": 0.5949225443, "include": true, "reason": "import numpy", "num_tokens": 8571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.1765960975200735}}
{"text": "\"\"\" This code implements Q-learning from a static batch of data with KL-control,\nmonte-carlo target Q-value estimation, Psi-learning, and model averaging.\"\"\"\nimport sys\nimport os\nimport copy\nimport pickle\nimport numpy as np\nimport pandas as pd\nfrom collections import namedtuple\nfrom itertools import count\nimport random\nfrom math import isnan\nfrom pathlib import Path\nfrom datetime import datetime\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.autograd as autograd\nimport torch.optim as optim\n\nfrom model.solver import Solver, VariationalSolver\nfrom model.models import VariationalModels\nfrom model.utils import to_var, pad, EOS_ID, TensorboardWriter, convert_old_checkpoint_format\nfrom model.data_loader import get_loader\nimport replay_buffer\nimport rewards\n\n\nclass BatchQ:\n    def __init__(self, config, val_config):\n        self.config = config\n        self.val_config = val_config\n\n        # Load experience replay buffer from file\n        self.experience = replay_buffer.CsvReplayBuffer(\n            config.experience_path, raw=config.raw_buffer,\n            history_len=config.max_conversation_length, config=config,\n            max_sentence_length=config.max_sentence_length,\n            rewards=config.rewards, reward_weights=config.reward_weights,\n            model_averaging=config.model_averaging)\n        self.vocab = self.experience.vocab\n        self.config.vocab_size = self.experience.vocab.vocab_size\n        self.action_dim = self.experience.vocab.vocab_size\n\n        # Check that all required rewards are in the buffer; if not, compute\n        for r in config.rewards:\n            if r not in self.experience.buffer.columns.values:\n                reward_func = getattr(rewards, r)\n                self.experience = reward_func(self.experience)\n\n        # Build internal hierarchical models\n        self.eval_data = self.get_data_loader()\n        self.build_models()\n\n        if self.config.load_rl_ckpt:\n            self.load_models()\n\n        self.q_optimizer = torch.optim.Adam(\n            filter(lambda p: p.requires_grad, self.q_net.model.parameters()),\n            lr=self.config.learning_rate)\n\n        self.set_up_logging()\n\n    def q_update(self):\n        \"\"\"General Q learning update.\"\"\"\n        # Sample a batch\n        batch = self.experience.sample(self.config.rl_batch_size)\n\n        # Run underlying q network to get q value of each word in each\n        # conversation in the batch. Use the same data to run the prior network\n        # and get the rewards based on KL divergence from the prior.\n        q_values, prior_rewards = self.get_q_values(batch)\n\n        # Compute target Q values. These will include the rewards observed in\n        # the batch (i.e. r + done * gamma * max_a' Q_T(a,s'))\n        with torch.no_grad():\n            target_q_values = self.get_target_q_values(batch, prior_rewards)\n\n        loss_func = getattr(F, self.config.q_loss_func)\n        loss = loss_func(q_values, target_q_values)\n\n        assert not isnan(loss.item())\n        self.q_loss_batch_history.append(loss.item())\n\n        # Optimize the model\n        self.q_optimizer.zero_grad()\n        loss.backward()\n\n        # Clip gradients - absolutely crucial\n        torch.nn.utils.clip_grad_value_(self.q_net.model.parameters(),\n                                        self.config.gradient_clip)\n\n        self.q_optimizer.step()\n\n        # Update Target Networks\n        tau = self.config.target_update_rate\n        for param, target_param in zip(self.q_net.model.parameters(),\n                                       self.target_q_net.model.parameters()):\n            target_param.data.copy_(\n                tau * param.data + (1 - tau) * target_param.data)\n\n    def get_q_values(self, batch):\n        \"\"\"update where states are whole conversations which\n        each have several sentences, and actions are a sentence (series of\n        words). Q values are per word. Target Q values are over the next word\n        in the sentence, or, if at the end of the sentence, the first word in a\n        new sentence after the user response.\n        \"\"\"\n        actions = to_var(torch.LongTensor(batch['action']))  # [batch_size]\n\n        # Prepare inputs to Q network\n        conversations = [np.concatenate(\n            (conv, np.atleast_2d(batch['action'][i])))\n            for i, conv in enumerate(batch['state'])]\n        sent_lens = [np.concatenate(\n            (lens, np.atleast_1d(batch['action_lens'][i])))\n            for i, lens in enumerate(batch['state_lens'])]\n        target_conversations = [conv[1:] for conv in conversations]\n        conv_lens = [len(c) - 1 for c in conversations]\n        if self.config.model not in VariationalModels:\n            conversations = [conv[:-1] for conv in conversations]\n            sent_lens = np.concatenate([l[:-1] for l in sent_lens])\n        else:\n            sent_lens = np.concatenate([l for l in sent_lens])\n        conv_lens = to_var(torch.LongTensor(conv_lens))\n\n        # Run Q network. Will produce [num_sentences, max sent len, vocab size]\n        all_q_values = self.run_seq2seq_model(\n            self.q_net, conversations, sent_lens, target_conversations,\n            conv_lens)\n\n        # Index to get only q values for actions taken (last sentence in each\n        # conversation)\n        start_q = torch.cumsum(torch.cat(\n            (to_var(conv_lens.data.new(1).zero_()), conv_lens[:-1])), 0)\n        conv_q_values = torch.stack(\n            [all_q_values[s+l-1, :, :]\n             for s, l in zip(start_q.data.tolist(), conv_lens.data.tolist())],\n             0)  # [num_sentences, max_sent_len, vocab_size]\n\n        # Limit by actual sentence length (remove padding) and flatten into\n        # long list of words\n        word_q_values = torch.cat(\n            [conv_q_values[i, :l, :]\n             for i, l in enumerate(batch['action_lens'])],\n             0)  # [total words, vocab_size]\n        word_actions = torch.cat(\n            [actions[i, :l] for i, l in enumerate(batch['action_lens'])],\n            0)  # [total words]\n\n        # Extract q values corresponding to actions taken\n        q_values = word_q_values.gather(\n            1, word_actions.unsqueeze(1)).squeeze()  # [total words]\n\n        \"\"\" Compute KL metrics \"\"\"\n        prior_rewards = None\n\n        # Get probabilities from policy network\n        q_dists = torch.nn.functional.softmax(word_q_values, 1)\n        q_probs = q_dists.gather(\n                1, word_actions.unsqueeze(1)).squeeze()\n\n        with torch.no_grad():\n            # Run pretrained prior network.\n            # [num_sentences, max sent len, vocab size]\n            all_prior_logits = self.run_seq2seq_model(\n                self.pretrained_prior, conversations, sent_lens,\n                target_conversations, conv_lens)\n\n            # Get relevant actions. [num_sentences, max_sent_len, vocab_size]\n            conv_prior = torch.stack(\n                [all_prior_logits[s+l-1, :, :]\n                for s, l in zip(\n                    start_q.data.tolist(), conv_lens.data.tolist())], 0)\n\n            # Limit by actual sentence length (remove padding) and flatten.\n            # [total words, vocab_size]\n            word_prior_logits = torch.cat(\n                [conv_prior[i, :l, :]\n                for i, l in enumerate(batch['action_lens'])], 0)\n\n            # Take the softmax\n            prior_dists = torch.nn.functional.softmax(\n                word_prior_logits, 1)\n\n            kl_div = F.kl_div(q_dists.log(), prior_dists, reduce=False)\n\n            # [total words]\n            prior_probs = prior_dists.gather(\n                1, word_actions.unsqueeze(1)).squeeze()\n            logp_logq = prior_probs.log() - q_probs.log()\n\n            if self.config.model_averaging:\n                model_avg_sentences = batch['model_averaged_probs']\n\n                # Convert to tensors and flatten into [num_words]\n                word_model_avg = torch.cat([to_var(\n                    torch.FloatTensor(m)) for m in model_avg_sentences], 0)\n\n                # Compute KL from model-averaged prior\n                prior_rewards = word_model_avg.log() - q_probs.log()\n\n                # Clip because KL should never be negative, so because we\n                # are subtracting KL, rewards should never be positive\n                prior_rewards = torch.clamp(prior_rewards, max=0.0)\n\n            elif self.config.kl_control and self.config.kl_calc == 'integral':\n                # Note: we reward the negative KL divergence to ensure the\n                # RL model stays close to the prior\n                prior_rewards = -1.0 * torch.sum(kl_div, dim=1)\n            elif self.config.kl_control:\n                prior_rewards = logp_logq\n\n            if self.config.kl_control:\n                prior_rewards = prior_rewards * self.config.kl_weight_c\n                self.kl_reward_batch_history.append(\n                    torch.sum(prior_rewards).item())\n\n            # Track all metrics\n            self.kl_div_batch_history.append(torch.mean(kl_div).item())\n            self.logp_batch_history.append(torch.mean(prior_probs.log()).item())\n            self.logp_logq_batch_history.append(torch.mean(logp_logq).item())\n\n        return q_values, prior_rewards\n\n    def get_target_q_values(self, batch, prior_rewards=None):\n        rewards = to_var(torch.FloatTensor(batch['rewards']))  # [batch_size]\n        not_done = to_var(torch.FloatTensor(1 - batch['done']))  # [batch_size]\n        self.sampled_reward_batch_history.append(torch.sum(rewards).item())\n\n        # Prepare inputs to target Q network. Append a blank sentence to get\n        # best response at next utterance to user input. (Next state\n        # includes user input).\n        blank_sentence = np.zeros((1, self.config.max_sentence_length))\n        next_state_convs = [np.concatenate(\n            (conv, blank_sentence)) for conv in batch['next_state']]\n        next_state_lens = [np.concatenate(\n            (lens, [1])) for lens in batch['next_state_lens']]\n        next_targets = [conv[1:] for conv in next_state_convs]\n        next_conv_lens = [len(c) - 1 for c in next_state_convs]\n        if self.config.model not in VariationalModels:\n            next_state_convs = [conv[:-1] for conv in next_state_convs]\n            next_state_lens = np.concatenate(\n                [l[:-1] for l in next_state_lens])\n        else:\n            next_state_lens = np.concatenate([l for l in next_state_lens])\n        next_conv_lens = to_var(torch.LongTensor(next_conv_lens))\n\n        # [monte_carlo_count, num_sentences, max sent len, vocab size]\n        _mc_target_q_values = [[]] * self.config.monte_carlo_count\n        for t in range(self.config.monte_carlo_count):\n            # Run target Q network. Output is size:\n            # [num_sentences, max sent len, vocab size]\n            if self.config.monte_carlo_count == 1:\n                # In this setting, we don't use dropout out at inference time at all\n                all_target_q_values = self.run_seq2seq_model(\n                    self.target_q_net, next_state_convs, next_state_lens,\n                    next_targets, next_conv_lens)\n            else:\n                # In this setting, each time we draw a new dropout mask (at inference time)\n                all_target_q_values = self.run_seq2seq_model(\n                    self.target_q_net, next_state_convs, next_state_lens,\n                    next_targets, next_conv_lens)\n\n            # Target indexing: last sentence is a blank to get value of next\n            # response. Second last is the user response. 3rd last is models own\n            # actions. Note that targets begin at the 2nd word of each sentence.\n            start_t = torch.cumsum(torch.cat(\n                (to_var(next_conv_lens.data.new(1).zero_()),\n                    next_conv_lens[:-1])), 0)\n            conv_target_q_values = torch.stack(\n                [all_target_q_values[s+l-3, 1:, :]\n                for s, l in zip(start_t.data.tolist(),\n                                next_conv_lens.data.tolist())],\n                0)  # Dimension [num_sentences, max_sent_len - 1, vocab_size]\n\n            # At the end of a sentence, want value of starting a new response\n            # after user's response. So index into first word of last blank\n            # sentence that was appended to the end of the conversation.\n            next_response_targets = torch.stack(\n                [all_target_q_values[s+l-1, 0, :]\n                for s, l in zip(start_t.data.tolist(),\n                                next_conv_lens.data.tolist())], 0)\n            next_response_targets = torch.reshape(\n                next_response_targets,\n                [self.config.rl_batch_size, 1, -1]\n                ) # [num_sentences, 1, vocab_size]\n            conv_target_q_values = torch.cat(\n                [conv_target_q_values, next_response_targets],\n                1)  # [num_sentences, max_sent_len, vocab_size]\n\n            # Limit target Q values by conversation length\n            limit_conv_targets = [conv_target_q_values[i, :l, :]\n                for i, l in enumerate(batch['action_lens'])]\n\n            if self.config.psi_learning:\n                # Target is r + gamma * log sum_a' exp(Q_target(s', a'))\n                conv_max_targets = [torch.distributions.utils.log_sum_exp(c)\n                    for c in limit_conv_targets]\n                target_q_values = torch.cat(\n                    [rewards[i] + not_done[i] * self.config.gamma * c.squeeze()\n                     for i, c in enumerate(conv_max_targets)], 0)  # [total words]\n            else:\n                # Target is r + gamma * max_a' Q_target(s',a'). Reward and done are\n                # at the level of conversation, so add and multiply in before\n                # flattening and taking max.\n                word_target_q_values = torch.cat(\n                    [rewards[i] + not_done[i] * self.config.gamma * c\n                     for i, c in enumerate(limit_conv_targets)],\n                    0)  # [total words, vocab_size]\n                target_q_values, _ = word_target_q_values.max(1)\n\n            _mc_target_q_values[t] = target_q_values\n        mc_target_q_values = torch.stack(_mc_target_q_values, 0)\n\n        min_target_q_values, _ = mc_target_q_values.min(0)\n\n        if self.config.kl_control:\n            min_target_q_values += prior_rewards\n\n        return min_target_q_values\n\n    def q_learn(self):\n        self.q_loss_history = []\n        self.q_loss_batch_history = []\n        self.sampled_reward_history = []\n        self.sampled_reward_batch_history = []\n        if self.config.kl_control:\n            self.kl_reward_history = []\n            self.kl_reward_batch_history = []\n\n        # Need to track KL metrics even for baselines for plots\n        self.kl_div_history = []\n        self.kl_div_batch_history = []\n        self.logp_history = []\n        self.logp_batch_history = []\n        self.logp_logq_history = []\n        self.logp_logq_batch_history = []\n\n        print('Commencing training at step', self.t)\n        while self.t <= self.config.num_steps:\n            self.q_update()\n\n            # Log metrics\n            if self.t % self.config.log_every_n == 0:\n                self.epoch_q_loss = np.sum(self.q_loss_batch_history) \\\n                    / self.config.log_every_n\n                self.q_loss_history.append(self.epoch_q_loss)\n                self.q_loss_batch_history = []\n                print('Average Q loss at step', self.t, '=', self.epoch_q_loss)\n\n                self.epoch_sampled_reward = np.sum(\n                    self.sampled_reward_batch_history) / self.config.log_every_n\n                self.sampled_reward_history.append(self.epoch_sampled_reward)\n                self.sampled_reward_batch_history = []\n                print('\\tAverage sampled batch reward =',\n                    self.epoch_sampled_reward)\n\n                if self.config.kl_control:\n                    self.epoch_kl_reward = np.sum(\n                        self.kl_reward_batch_history) \\\n                        / self.config.log_every_n\n                    self.kl_reward_history.append(\n                        self.epoch_kl_reward)\n                    self.kl_reward_batch_history = []\n                    print('\\tAverage data prior reward =',\n                        self.epoch_kl_reward)\n\n                # Logging KL for plots\n                self.epoch_kl_div = np.sum(\n                    self.kl_div_batch_history) / self.config.log_every_n\n                self.kl_div_history.append(self.epoch_kl_div)\n                self.kl_div_batch_history = []\n                self.epoch_logp = np.sum(\n                    self.logp_batch_history) / self.config.log_every_n\n                self.logp_history.append(self.epoch_logp)\n                self.logp_batch_history = []\n                self.epoch_logp_logq = np.sum(\n                    self.logp_logq_batch_history) / self.config.log_every_n\n                self.logp_logq_history.append(self.epoch_logp_logq)\n                self.logp_logq_batch_history = []\n\n                sys.stdout.flush()\n                self.write_summary(self.t)\n\n            if self.t > 0 and self.t % self.config.save_every_n == 0:\n                self.save_model(self.t)\n\n            self.t += 1\n\n    def build_models(self):\n        config = copy.deepcopy(self.config)\n\n        # If loading RL checkpoint, ensure it doesn't try to load the ckpt\n        # through Solver\n        if self.config.load_rl_ckpt:\n            config.checkpoint = None\n\n        if self.config.model in VariationalModels:\n            self.q_net = VariationalSolver(\n                config, None, self.eval_data, vocab=self.vocab, is_train=True)\n            self.target_q_net = VariationalSolver(\n                config, None, self.eval_data, vocab=self.vocab, is_train=True)\n        else:\n            self.q_net = Solver(\n                config, None, self.eval_data, vocab=self.vocab, is_train=True)\n            self.target_q_net = Solver(\n                config, None, self.eval_data, vocab=self.vocab, is_train=True)\n        print('Building Q network')\n        self.q_net.build()\n\n        print('\\nBuilding Target Q network')\n        self.target_q_net.build()\n\n        if self.config.model in VariationalModels:\n            self.pretrained_prior = VariationalSolver(\n                self.config, None, self.eval_data, vocab=self.vocab,\n                is_train=True)\n        else:\n            self.pretrained_prior = Solver(\n                self.config, None, self.eval_data, vocab=self.vocab,\n                is_train=True)\n        print('Building prior network')\n        self.pretrained_prior.build()\n\n        # Freeze the weights of the prior so it stays constant\n        self.pretrained_prior.model.eval()\n        for params in self.pretrained_prior.model.parameters():\n            params.requires_grad = False\n\n        print('Successfully initialized Q networks')\n        self.t = 0\n\n    def run_seq2seq_model(self, q_net, input_conversations, sent_lens,\n                     target_conversations, conv_lens):\n        # Prepare the batch\n        sentences = [sent for conv in input_conversations for sent in conv]\n        targets = [sent for conv in target_conversations for sent in conv]\n\n        if not (np.all(np.isfinite(sentences))\n                and np.all(np.isfinite(targets))\n                and np.all(np.isfinite(sent_lens))):\n            print(\"Input isn't finite\")\n\n        sentences = to_var(torch.LongTensor(sentences))\n        targets = to_var(torch.LongTensor(targets))\n        sent_lens = to_var(torch.LongTensor(sent_lens))\n\n        # Run Q network\n        q_outputs = q_net.model(sentences, sent_lens, conv_lens, targets,\n                                rl_mode=True)\n        return q_outputs[0]  # [num_sentences, max_sentence_len, vocab_size]\n\n    def write_summary(self, t):\n        metrics_to_log = ['epoch_q_loss', 'epoch_sampled_reward',\n                          'epoch_kl_div', 'epoch_logp', 'epoch_logp_logq']\n\n        if self.config.kl_control:\n            metrics_to_log.append('epoch_kl_reward')\n\n        metrics_dict = {}\n        for metric in metrics_to_log:\n            met_val = getattr(self, metric, None)\n            metrics_dict[metric] = met_val\n            if met_val is not None:\n                self.writer.update_loss(\n                    loss=met_val,\n                    step_i=t,\n                    name=metric)\n\n        # Write pandas csv with metrics to save dir\n        self.df = self.df.append(metrics_dict, ignore_index=True)\n        self.df.to_csv(self.pandas_path)\n\n    def set_up_logging(self):\n        # Get save path\n        time_now = datetime.now().strftime('%Y-%m-%d_%H:%M:%S')\n        default_save_path = Path('model_checkpoints/rl/')\n\n        # Folder for type of RL used\n        experiment_name = self.config.experiment_name\n        if experiment_name is None:\n            # if self.config.double_q: experiment_name = 'double_q'\n            if self.config.model_averaging:\n                experiment_name = 'model_averaging'\n            elif self.config.kl_control:\n                experiment_name = 'kl_control'\n                if self.config.kl_calc == 'sample': experiment_name += '_sample'\n            else: experiment_name = 'batch_q'\n            if self.config.psi_learning:\n                experiment_name += '/psi_learning'\n            if self.config.monte_carlo_count > 1:\n                experiment_name = 'monte_carlo_targets/' + experiment_name\n\n        # Folder for type of rewards used\n        extra_save_dir = self.config.extra_save_dir\n        if not extra_save_dir:\n            if len(self.config.rewards) == 1:\n                extra_save_dir = self.config.rewards[0]\n            else:\n                extra_save_dir = 'reward_combo'\n\n        # Folder for which model was used\n        extra_model_desc = \"\"\n        if self.config.context_input_only:\n            extra_model_desc = 'input_only_'\n        if self.config.emotion and 'input_only' not in extra_model_desc:\n            extra_model_desc += \"emotion_\"\n        if self.config.infersent and 'input_only' not in extra_model_desc:\n            extra_model_desc += \"infersent_\"\n\n        # Make save path\n        self.save_dir = default_save_path.joinpath(\n            self.q_net.config.data, experiment_name, extra_save_dir,\n            extra_model_desc + self.q_net.config.model, time_now)\n\n        # Make directory and save config\n        print(\"Saving output to\", self.save_dir)\n        os.makedirs(self.save_dir, exist_ok=True)\n        with open(os.path.join(self.save_dir, 'config.txt'), 'w') as f:\n            print(self.config, file=f)\n\n        # Make loggers\n        self.writer = TensorboardWriter(self.save_dir)\n        self.pandas_path = os.path.join(self.save_dir, \"metrics.csv\")\n        self.df = pd.DataFrame()\n\n    def save_model(self, t):\n        \"\"\"Save parameters to checkpoint\"\"\"\n        ckpt_path = os.path.join(self.save_dir, f'q_net{t}.pkl')\n        print(f'Save parameters to {ckpt_path}')\n        torch.save(self.q_net.model.state_dict(), ckpt_path)\n\n        ckpt_path = os.path.join(self.save_dir, f'target_q_net{t}.pkl')\n        torch.save(self.target_q_net.model.state_dict(), ckpt_path)\n\n    def load_models(self):\n        \"\"\"Load parameters from RL checkpoint\"\"\"\n        # Override specific checkpoint with particular one\n        base_checkpoint_dir = str(Path(self.config.checkpoint).parent)\n        if self.config.rl_ckpt_epoch is not None:\n            q_ckpt_path = os.path.join(\n                base_checkpoint_dir, 'q_net' + str(\n                self.config.rl_ckpt_epoch) + '.pkl')\n            target_q_ckpt_path = os.path.join(\n                base_checkpoint_dir, 'target_q_net' + str(\n                self.config.rl_ckpt_epoch) + '.pkl')\n            self.t = int(self.config.rl_ckpt_epoch)\n        else:\n            ckpt_file = self.config.checkpoint.replace(base_checkpoint_dir, '')\n            ckpt_file = ckpt_file.replace('/', '')\n            ckpt_num = ckpt_file[len('q_net'):ckpt_file.find('.')]\n            q_ckpt_path = self.config.checkpoint\n            target_q_ckpt_path = os.path.join(\n                base_checkpoint_dir, 'target_q_net' + ckpt_num + '.pkl')\n            self.t = int(ckpt_num)\n\n        print(f'Loading parameters for Q net from {q_ckpt_path}')\n        q_ckpt = torch.load(q_ckpt_path)\n        q_ckpt = convert_old_checkpoint_format(q_ckpt)\n        self.q_net.model.load_state_dict(q_ckpt)\n\n        print(f'Loading parameters for target Q net from {target_q_ckpt_path}')\n        target_q_ckpt = torch.load(target_q_ckpt_path)\n        target_q_ckpt = convert_old_checkpoint_format(target_q_ckpt)\n        self.target_q_net.model.load_state_dict(target_q_ckpt)\n\n        # Ensure weights are initialized to be on the GPU when necessary\n        if torch.cuda.is_available():\n            print('Converting checkpointed model to cuda tensors')\n            self.q_net.model.cuda()\n            self.target_q_net.model.cuda()\n\n    def get_data_loader(self):\n        # If checkpoint is for an emotion model, load that pickle file\n        emotion_sentences = None\n        if self.config.emotion:\n            emotion_sentences = load_pickle(self.val_config.emojis_path)\n\n        # Load infersent embeddings if necessary\n        infersent_sentences = None\n        if self.config.infersent:\n            print('Loading infersent sentence embeddings...')\n            infersent_sentences = load_pickle(self.val_config.infersent_path)\n            embedding_size = infersent_sentences[0][0].shape[0]\n            self.config.infersent_output_size = embedding_size\n            self.val_config.infersent_output_size = embedding_size\n\n        return get_loader(\n            sentences=load_pickle(self.val_config.sentences_path),\n            conversation_length=load_pickle(self.val_config.conversation_length_path),\n            sentence_length=load_pickle(self.val_config.sentence_length_path),\n            vocab=self.vocab,\n            batch_size=self.config.batch_size,\n            emojis=emotion_sentences,\n            infersent=infersent_sentences)\n\n    def interact(self):\n        print(\"Commencing interaction with bot trained with RL\")\n        self.q_net.interact(\n                max_sentence_length=self.config.max_sentence_length,\n                max_conversation_length=self.config.max_conversation_length,\n                sample_by='priority', debug=True, print_history=True)\n\n\ndef load_pickle(path):\n    with open(path, 'rb') as f:\n        return pickle.load(f)\n", "meta": {"hexsha": "ca6015493a100c9335c2f61a816f871ff563d29e", "size": 26497, "ext": "py", "lang": "Python", "max_stars_repo_path": "BatchRL/way_off_policy_batch_rl.py", "max_stars_repo_name": "UmaTaru/run", "max_stars_repo_head_hexsha": "be29e4d41a4de3dee27cd6796801bfe51382d294", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 163, "max_stars_repo_stars_event_min_datetime": "2019-06-23T14:07:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T23:06:07.000Z", "max_issues_repo_path": "BatchRL/way_off_policy_batch_rl.py", "max_issues_repo_name": "UmaTaru/run", "max_issues_repo_head_hexsha": "be29e4d41a4de3dee27cd6796801bfe51382d294", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-07-24T12:41:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T00:17:20.000Z", "max_forks_repo_path": "BatchRL/way_off_policy_batch_rl.py", "max_forks_repo_name": "UmaTaru/run", "max_forks_repo_head_hexsha": "be29e4d41a4de3dee27cd6796801bfe51382d294", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2019-06-26T01:21:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T17:23:24.000Z", "avg_line_length": 43.437704918, "max_line_length": 93, "alphanum_fraction": 0.6126353927, "include": true, "reason": "import numpy", "num_tokens": 5617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.34510526422232046, "lm_q1q2_score": 0.1765960940733797}}
{"text": "import logging\n_logger = logging.getLogger(\"theano.tensor.type\")\n\nimport numpy\n\nimport theano\nfrom theano import config\nfrom theano.gof import Constant, hashtype, Type, Variable\nfrom theano.gof.python25 import any\nfrom theano.gof.utils import MethodNotDefined\nfrom theano import scalar as scal\n\n\nclass TensorType(Type):\n    \"\"\"Symbolic `Type` representing a numpy.ndarray value.\"\"\"\n\n    filter_checks_isfinite = False\n    \"\"\"\n    When this is True, strict filtering rejects data containing NaN or\n    Inf entries. (Used in `DebugMode`)\n    \"\"\"\n\n    def __init__(self, dtype, broadcastable, name=None, sparse_grad=False):\n        \"\"\"Initialize self.dtype and self.broadcastable.\n\n        :Parameters:\n         - `dtype`: str corresponding to numpy dtype (e.g., 'int64')\n           The value (ndarray) associated to a `Variable` of this `Type` will\n           have this dtype.\n         - `broadcastable`: tuple, list, or array of boolean values\n           This argument serves two purposes.  First, the True elements of this\n           list indicate the dimensions where the shape of an associated value\n           must be 1.  Secondly, the length of this list is the number of\n           dimensions that an associated value must have.  See\n           :doc:`broadcasting` for an explanation of how this list is used.\n         - `name`: str\n           Optional name for this type.\n        \"\"\"\n        self.dtype = str(dtype)\n        if self.dtype == 'floatX':\n            self.dtype = config.floatX\n        ###    broadcastable is immutable, and all elements are either\n        ###    True or False\n        self.broadcastable = tuple(bool(b) for b in broadcastable)\n        self.dtype_specs()  # error checking is done there\n        self.name = name\n        self.numpy_dtype = numpy.dtype(self.dtype)\n        self.sparse_grad = sparse_grad\n        if sparse_grad:\n            warnings.warn(\n                \"DEPRECATION WARNING: You use an old interface to\"\n                \" AdvancedSubtensor1 sparse_grad. Now use\"\n                \" theano.sparse_grad(a_tensor[an_int_vector]).\")\n\n    def filter(self, data, strict=False, allow_downcast=None):\n        \"\"\"Convert `data` to something which can be associated to a\n        `TensorVariable`.\n\n        This function is not meant to be called in user code.  It is for\n        `Linker` instances to use when running a compiled graph.\n        \"\"\"\n        # Explicit error message when one accidentally uses a Variable as\n        # input (typical mistake, especially with shared variables).\n        if isinstance(data, Variable):\n            raise TypeError(\n                    'Expected an array-like object, but found a Variable: '\n                    'maybe you are trying to call a function on a (possibly '\n                    'shared) variable instead of a numeric array?')\n\n        if ((type(data) is numpy.ndarray)\n                and (data.dtype == self.numpy_dtype)):\n            if data.dtype.num != self.numpy_dtype.num:\n                data = theano._asarray(data, dtype=self.dtype)\n            # -- now fall through to ndim check\n        elif((type(data) is numpy.memmap)\n                and (data.dtype == self.numpy_dtype)):\n            # numpy.memmap is a \"safe\" subclass of ndarray,\n            # so we can use it whereever we expect a base ndarray.\n            # however, casting it would defeat the purpose of not\n            # loading the whole data into memory\n            pass\n        elif strict:\n            # If any of the two conditions above was not met,\n            # we raise a meaningful TypeError.\n            if not (type(data) is numpy.ndarray):\n                raise TypeError(\"%s expected a ndarray object.\" % self,\n                        data, type(data))\n            if data.dtype != self.numpy_dtype:\n                raise TypeError((\"%s expected a ndarray object with \"\n                        \"dtype = %s (got %s).\") % (\n                            self, self.numpy_dtype, data.dtype))\n            assert False, \"This point should never be reached.\"\n        else:\n            if allow_downcast:\n                # Convert to self.dtype, regardless of the type of data\n                data = theano._asarray(data, dtype=self.dtype)\n                # TODO: consider to pad shape with ones to make it consistent\n                # with self.broadcastable... like vector->row type thing\n            else:\n                if isinstance(data, numpy.ndarray):\n                    # Check if self.dtype can accurately represent data\n                    # (do not try to convert the data)\n                    up_dtype = scal.upcast(self.dtype, data.dtype)\n                    if up_dtype == self.dtype:\n                        # Bug in the following line when data is a\n                        # scalar array, see\n                        # http://projects.scipy.org/numpy/ticket/1611\n                        # data = data.astype(self.dtype)\n                        data = theano._asarray(data, dtype=self.dtype)\n                    if up_dtype != self.dtype:\n                        err_msg = (\n                            '%s cannot store a value of dtype %s without '\n                            'risking loss of precision. If you do not mind '\n                            'this loss, you can: '\n                            '1) explicitly cast your data to %s, or '\n                            '2) set \"allow_input_downcast=True\" when calling '\n                            '\"function\".'\n                            % (self, data.dtype, self.dtype))\n                        raise TypeError(err_msg, data)\n                elif (allow_downcast is None and\n                        type(data) is float and\n                        self.dtype == theano.config.floatX):\n                    # Special case where we allow downcasting of Python float\n                    # literals to floatX, even when floatX=='float32'\n                    data = theano._asarray(data, self.dtype)\n                else:\n                    # data has to be converted.\n                    # Check that this conversion is lossless\n                    converted_data = theano._asarray(data, self.dtype)\n                    # We use the `values_eq` static function from TensorType\n                    # to handle NaN values.\n                    if TensorType.values_eq(numpy.asarray(data),\n                                            converted_data,\n                                            force_same_dtype=False):\n                        data = converted_data\n                    else:\n                        # Do not print a too long description of data\n                        # (ndarray truncates it, but it's not sure for data)\n                        str_data = str(data)\n                        if len(str_data) > 80:\n                            str_data = str_data[:75] + '(...)'\n\n                        err_msg = (\n                            '%s cannot store accurately value %s, '\n                            'it would be represented as %s. '\n                            'If you do not mind this precision loss, you can: '\n                            '1) explicitly convert your data to a numpy array '\n                            'of dtype %s, or '\n                            '2) set \"allow_input_downcast=True\" when calling '\n                            '\"function\".'\n                            % (self, data, converted_data, self.dtype))\n                        raise TypeError(err_msg, data)\n\n        if self.ndim != data.ndim:\n            raise TypeError(\"Wrong number of dimensions: expected %s,\"\n                            \" got %s with shape %s.\" % (self.ndim, data.ndim,\n                                                        data.shape))\n        if not data.flags.aligned:\n            try:\n                msg = \"object buffer\" + str(data.data)\n            except AttributeError:\n                msg = \"\"\n            raise TypeError(\"The numpy.ndarray object is not aligned.\"\n                            \" Theano C code does not support that.\",\n                            msg,\n                            \"object shape\", data.shape,\n                            \"object strides\", data.strides,\n                            \"object dtype\", data.dtype)\n\n        i = 0\n        for b in self.broadcastable:\n            if b and data.shape[i] != 1:\n                raise TypeError(\"Non-unit value on shape on a broadcastable\"\n                                \" dimension.\", data.shape, self.broadcastable)\n            i += 1\n        if (self.filter_checks_isfinite and\n            not numpy.all(numpy.isfinite(data))):\n            raise ValueError(\"non-finite elements not allowed\")\n        return data\n\n    def filter_variable(self, other):\n        \"\"\"Convert a symbolic Variable into a TensorType, if compatible.\n\n        For the moment, only a TensorType or CudaNdarrayType will be\n        converted, provided they have the same number of dimensions,\n        broadcastable pattern, and dtype.\n        \"\"\"\n        if hasattr(other, '_as_TensorVariable'):\n            other = other._as_TensorVariable()\n\n        if not isinstance(other, Variable):\n            # The value is not a Variable: we cast it into\n            # a Constant of the appropriate Type.\n            other = self.Constant(type=self, data=other)\n\n        if other.type == self:\n            return other\n\n        raise TypeError(\n                'Cannot convert Type %(othertype)s '\n                '(of Variable %(other)s) into Type %(self)s. '\n                'You can try to manually convert %(other)s into a %(self)s.'\n                % dict(\n                    othertype=other.type,\n                    other=other,\n                    self=self)\n                )\n\n    def value_validity_msg(self, a):\n        try:\n            self.filter(a, strict=True)\n        except Exception, e:\n            return str(e)\n        return \"value is valid\"\n\n    def dtype_specs(self):\n        \"\"\"Return a tuple (python type, c type, numpy typenum) that corresponds\n        to self.dtype.\n\n        This function is used internally as part of C code generation.\n        \"\"\"\n        # TODO: add more type correspondances for e.g. int32, int64, float32,\n        # complex64, etc.\n        try:\n            return {\n                'float32': (float, 'npy_float32', 'NPY_FLOAT32'),\n                'float64': (float, 'npy_float64', 'NPY_FLOAT64'),\n                'uint8': (int, 'npy_uint8', 'NPY_UINT8'),\n                'int8': (int, 'npy_int8', 'NPY_INT8'),\n                'uint16': (int, 'npy_uint16', 'NPY_UINT16'),\n                'int16': (int, 'npy_int16', 'NPY_INT16'),\n                'uint32': (int, 'npy_uint32', 'NPY_UINT32'),\n                'int32': (int, 'npy_int32', 'NPY_INT32'),\n                'uint64': (int, 'npy_uint64', 'NPY_UINT64'),\n                'int64': (int, 'npy_int64', 'NPY_INT64'),\n                'complex128': (complex, 'theano_complex128', 'NPY_COMPLEX128'),\n                'complex64': (complex, 'theano_complex64', 'NPY_COMPLEX64')\n                }[self.dtype]\n        except KeyError:\n            raise TypeError(\"Unsupported dtype for %s: %s\"\n                    % (self.__class__.__name__, self.dtype))\n\n    def to_scalar_type(self):\n        return scal.get_scalar_type(dtype=self.dtype)\n\n    def __eq__(self, other):\n        \"\"\"Compare True iff other is the same kind of TensorType\"\"\"\n        return type(self) == type(other) and other.dtype == self.dtype \\\n            and other.broadcastable == self.broadcastable\n\n    @staticmethod\n    def may_share_memory(a, b):\n        # This is a method of TensorType, so both a and b should be ndarrays\n        if isinstance(a, numpy.ndarray) and isinstance(b, numpy.ndarray):\n            return numpy.may_share_memory(a, b)\n        else:\n            return False\n\n    @staticmethod\n    def values_eq(a, b, force_same_dtype=True):\n        # TODO: check to see if the shapes must match\n        #      for now, we err on safe side...\n        if a.shape != b.shape:\n            return False\n        if force_same_dtype and a.dtype != b.dtype:\n            return False\n        a_eq_b = (a == b)\n        r = numpy.all(a_eq_b)\n        if r:\n            return True\n        # maybe the trouble is that there are NaNs\n        a_missing = numpy.isnan(a)\n        if a_missing.any():\n            b_missing = numpy.isnan(b)\n            return numpy.all(a_eq_b + (a_missing == b_missing))\n        else:\n            return False\n\n    @staticmethod\n    def values_eq_approx(a, b, allow_remove_inf=False, allow_remove_nan=False,\n                         rtol=None, atol=None):\n        \"\"\"\n        :param allow_remove_inf: If True, when there is an inf in a,\n                                 we allow any value in b in that position.\n                                 Event -inf\n        :param allow_remove_nan: If True, when there is a nan in a,\n                                 we allow any value in b in that position.\n                                 Event +-inf\n        :param rtol: relative tolerance, passed to _allclose\n        :param atol: absolute tolerance, passed to _allclose\n        \"\"\"\n        if isinstance(a, numpy.ndarray) and isinstance(b, numpy.ndarray):\n            if a.shape != b.shape:\n                return False\n            if a.dtype != b.dtype:\n                return False\n            if 'int' in str(a.dtype):\n                return numpy.all(a == b)\n            else:\n                # work around a numpy.allclose bug:\n                # http://projects.scipy.org/numpy/ticket/1672\n                if a.ndim == 0 and numpy.isinf(a):\n                    a = a.reshape(1)\n                    b = b.reshape(1)\n\n                cmp = theano.tensor.basic._allclose(a, b, rtol=rtol, atol=atol)\n                if cmp:\n                    # Numpy claims they are close, this is good enough for us.\n                    return True\n                # Numpy is unhappy, but it does not necessarily mean that a and\n                # b are different. Indeed, Numpy does not like missing values\n                # and will return False whenever some are found in a or b.\n                # The proper way would be to use the MaskArray stuff available\n                # in Numpy. However, it looks like it has been added to Numpy's\n                # core recently, so it may not be available to everyone. Thus,\n                # for now we use a home-made recipe, that should probably be\n                # revisited in the future.\n                a_missing = numpy.isnan(a)\n                a_inf = numpy.isinf(a)\n\n                if not (a_missing.any() or (allow_remove_inf and a_inf.any())):\n                    # There are no missing values in a, thus this is not the\n                    # reason why numpy.allclose(a, b) returned False.\n                    _logger.info(\n                        'numpy allclose failed for abs_err %f and rel_err %f',\n                        numpy.max(abs(a - b)),\n                        numpy.max(abs(a - b) / (abs(a) + abs(b))))\n                    return False\n                # The following line is what numpy.allclose bases its decision\n                # upon, according to its documentation.\n                rtol = 1.0000000000000001e-05\n                atol = 1e-8\n                cmp_elemwise = (numpy.absolute(a - b) <=\n                        (atol + rtol * numpy.absolute(b)))\n                # Find places where both a and b have missing values.\n                both_missing = a_missing * numpy.isnan(b)\n\n                # Find places where both a and b have inf of the same sign.\n                both_inf = a_inf * numpy.isinf(b)\n\n                # cmp_elemwise is weird when we have inf and -inf.\n                # set it to False\n                cmp_elemwise = numpy.where(\n                        both_inf & cmp_elemwise,\n                        a == b,\n                        cmp_elemwise)\n\n                # check the sign of the inf\n                both_inf = numpy.where(both_inf, (a == b), both_inf)\n\n                if allow_remove_inf:\n                    both_inf += a_inf\n                if allow_remove_nan:\n                    both_missing += a_missing\n\n                # Combine all information.\n                return (cmp_elemwise + both_missing + both_inf).all()\n\n        return False\n\n    @staticmethod\n    def values_eq_approx_remove_inf(a, b):\n        return TensorType.values_eq_approx(a, b, True)\n\n    @staticmethod\n    def values_eq_approx_remove_nan(a, b):\n        return TensorType.values_eq_approx(a, b, False, True)\n\n    @staticmethod\n    def values_eq_approx_remove_inf_nan(a, b):\n        return TensorType.values_eq_approx(a, b, True, True)\n\n    def __hash__(self):\n        \"\"\"Hash equal for same kinds of TensorType\"\"\"\n        return hashtype(self) ^ hash(self.dtype) ^ hash(self.broadcastable)\n\n    ndim = property(lambda self: len(self.broadcastable),\n            doc=\"number of dimensions\")\n    \"\"\"Number of dimensions\n\n    This read-only property is the preferred way to get the number of\n    dimensions of a `TensorType`.\n\n    \"\"\"\n\n    def make_variable(self, name=None):\n        \"\"\"Return a `TensorVariable` of this type\n\n        :Parameters:\n         - `name`: str\n           A pretty name to identify this `Variable` when printing and\n           debugging\n        \"\"\"\n        return self.Variable(self, name=name)\n\n    def __str__(self):\n        if self.name:\n            return self.name\n        else:\n            b = self.broadcastable\n            named_broadcastable = {(): 'scalar',\n                     (False,): 'vector',\n                     (False, True): 'col',\n                     (True, False): 'row',\n                     (False, False): 'matrix'}\n            if b in named_broadcastable:\n                bcast = named_broadcastable[b]\n            else:\n                if any(b):\n                    bcast = str(b)\n                else:\n                    bcast = '%iD' % len(b)\n            return \"TensorType(%s, %s)\" % (str(self.dtype), bcast)\n\n    def __repr__(self):\n        return str(self)\n        #\"TensorType{%s, %s}\" % (str(self.dtype), str(self.broadcastable))\n\n    def c_declare(self, name, sub, check_input=True):\n        \"\"\"Override `CLinkerType.c_declare` \"\"\"\n        if(check_input):\n            check = \"\"\"\n            typedef %(dtype)s dtype_%(name)s;\n            \"\"\" % dict(sub, name=name, dtype=self.dtype_specs()[1])\n        else:\n            check = \"\"\n        declaration = \"\"\"\n        PyArrayObject* %(name)s;\n        \"\"\" % dict(sub, name=name, dtype=self.dtype_specs()[1])\n\n        return declaration + check\n\n    def c_init(self, name, sub):\n        \"\"\"Override `CLinkerType.c_init` \"\"\"\n        return \"\"\"\n        %(name)s = NULL;\n        \"\"\" % dict(sub, name=name, type_num=self.dtype_specs()[2])\n\n    def c_extract(self, name, sub, check_input=True):\n        \"\"\"Override `CLinkerType.c_extract` \"\"\"\n        if(check_input):\n            check = \"\"\"\n            %(name)s = NULL;\n            if (py_%(name)s == Py_None) {\n                // We can either fail here or set %(name)s to NULL and rely on Ops\n                // using tensors to handle the NULL case, but if they fail to do so\n                // they'll end up with nasty segfaults, so this is public service.\n                PyErr_SetString(PyExc_ValueError, \"expected an ndarray, not None\");\n                %(fail)s\n            }\n            if (!PyArray_Check(py_%(name)s)) {\n                PyErr_SetString(PyExc_ValueError, \"expected an ndarray\");\n                %(fail)s\n            }\n            // We expect %(type_num)s\n            if (!PyArray_ISALIGNED((PyArrayObject*) py_%(name)s)) {\n                PyArrayObject * tmp = (PyArrayObject*) py_%(name)s;\n                PyErr_Format(PyExc_NotImplementedError,\n                             \"expected an aligned array of type %%ld \"\n                             \"(%(type_num)s), got non-aligned array of type %%ld\"\n                             \" with %%ld dimensions, with 3 last dims \"\n                             \"%%ld, %%ld, %%ld\"\n                             \" and 3 last strides %%ld %%ld, %%ld.\",\n                             (long int) %(type_num)s,\n                             (long int) PyArray_TYPE((PyArrayObject*) py_%(name)s),\n                             (long int) PyArray_NDIM(tmp),\n                             (long int) PyArray_NDIM(tmp) >= 3 ?\n            PyArray_DIMS(tmp)[PyArray_NDIM(tmp)-3] : -1,\n                             (long int) PyArray_NDIM(tmp) >= 2 ?\n            PyArray_DIMS(tmp)[PyArray_NDIM(tmp)-2] : -1,\n                             (long int) PyArray_NDIM(tmp) >= 1 ?\n            PyArray_DIMS(tmp)[PyArray_NDIM(tmp)-1] : -1,\n                             (long int) PyArray_NDIM(tmp) >= 3 ?\n            PyArray_STRIDES(tmp)[PyArray_NDIM(tmp)-3] : -1,\n                             (long int) PyArray_NDIM(tmp) >= 2 ?\n            PyArray_STRIDES(tmp)[PyArray_NDIM(tmp)-2] : -1,\n                             (long int) PyArray_NDIM(tmp) >= 1 ?\n            PyArray_STRIDES(tmp)[PyArray_NDIM(tmp)-1] : -1\n            );\n                %(fail)s\n            }\n            // This is a TypeError to be consistent with DEBUG_MODE\n            // Note: DEBUG_MODE also tells the name of the container\n            if (PyArray_TYPE((PyArrayObject*) py_%(name)s) != %(type_num)s) {\n                PyErr_Format(PyExc_TypeError,\n                             \"expected type_num %%d (%(type_num)s) got %%d\",\n                             %(type_num)s, PyArray_TYPE((PyArrayObject*) py_%(name)s));\n                %(fail)s\n            }\n            \"\"\" % dict(sub, name=name, type_num=self.dtype_specs()[2])\n        else:\n            check = \"\"\n        return check + \"\"\"\n        %(name)s = (PyArrayObject*)(py_%(name)s);\n        Py_XINCREF(%(name)s);\n        \"\"\" % dict(sub, name=name, type_num=self.dtype_specs()[2])\n\n    def c_cleanup(self, name, sub):\n        \"\"\"Override `CLinkerType.c_cleanup` \"\"\"\n        return \"\"\"\n        if (%(name)s) {\n            Py_XDECREF(%(name)s);\n        }\n        \"\"\" % locals()\n\n    def c_sync(self, name, sub):\n        \"\"\"Override `CLinkerType.c_sync` \"\"\"\n        fail = sub['fail']\n        type_num = self.dtype_specs()[2]\n        return \"\"\"\n        {Py_XDECREF(py_%(name)s);}\n        if (!%(name)s) {\n            Py_INCREF(Py_None);\n            py_%(name)s = Py_None;\n        }\n        else if ((void*)py_%(name)s != (void*)%(name)s) {\n            py_%(name)s = (PyObject*)%(name)s;\n        }\n\n        {Py_XINCREF(py_%(name)s);}\n\n        if (%(name)s && !PyArray_ISALIGNED((PyArrayObject*) py_%(name)s)) {\n            PyErr_Format(PyExc_NotImplementedError,\n                         \"c_sync: expected an aligned array, got non-aligned array of type %%ld\"\n                         \" with %%ld dimensions, with 3 last dims \"\n                         \"%%ld, %%ld, %%ld\"\n                         \" and 3 last strides %%ld %%ld, %%ld.\",\n                         (long int) PyArray_TYPE((PyArrayObject*) py_%(name)s),\n                         (long int) PyArray_NDIM(%(name)s),\n                         (long int) PyArray_NDIM(%(name)s) >= 3 ?\n        PyArray_DIMS(%(name)s)[PyArray_NDIM(%(name)s)-3] : -1,\n                         (long int) PyArray_NDIM(%(name)s) >= 2 ?\n        PyArray_DIMS(%(name)s)[PyArray_NDIM(%(name)s)-2] : -1,\n                         (long int) PyArray_NDIM(%(name)s) >= 1 ?\n        PyArray_DIMS(%(name)s)[PyArray_NDIM(%(name)s)-1] : -1,\n                         (long int) PyArray_NDIM(%(name)s) >= 3 ?\n        PyArray_STRIDES(%(name)s)[PyArray_NDIM(%(name)s)-3] : -1,\n                         (long int) PyArray_NDIM(%(name)s) >= 2 ?\n        PyArray_STRIDES(%(name)s)[PyArray_NDIM(%(name)s)-2] : -1,\n                         (long int) PyArray_NDIM(%(name)s) >= 1 ?\n        PyArray_STRIDES(%(name)s)[PyArray_NDIM(%(name)s)-1] : -1\n        );\n            %(fail)s\n        }\n        \"\"\" % locals()\n\n    def c_headers(self):\n        \"\"\"Override `CLinkerObject.c_headers` \"\"\"\n        return scal.get_scalar_type(self.dtype).c_headers()\n\n    def c_libraries(self):\n        return scal.get_scalar_type(self.dtype).c_libraries()\n\n    def c_compile_args(self):\n        return scal.get_scalar_type(self.dtype).c_compile_args()\n\n    def c_support_code(self):\n        \"\"\"Override `CLinkerObject.c_support_code` \"\"\"\n        return scal.get_scalar_type(self.dtype).c_support_code()\n\n    def c_init_code(self):\n        return scal.get_scalar_type(self.dtype).c_init_code()\n\n    def c_code_cache_version(self):\n        scalar_version = scal.get_scalar_type(self.dtype).c_code_cache_version()\n        if scalar_version:\n            return (11,) + scalar_version\n        else:\n            return ()\n\n    def value_zeros(self, shape):\n        \"\"\"\n        Create an numpy ndarray full of 0 values.\n        \"\"\"\n        return numpy.zeros(shape, dtype=self.dtype)\n\n    def get_shape_info(self, obj):\n        \"\"\"\n        Return the information needed to compute the memory size of ``obj``.\n\n        The memory size is only the data, so this excludes the container.\n        For an ndarray, this is the data, but not the ndarray object and\n        other data structures such as shape and strides.\n\n        ``get_shape_info()`` and ``get_size()`` work in tandem for the memory\n        profiler.\n\n        ``get_shape_info()`` is called during the execution of the function.\n        So it is better that it is not too slow.\n\n        ``get_size()`` will be called on the output of this function\n        when printing the memory profile.\n\n        :param obj: The object that this Type represents during execution\n        :return: Python object that ``self.get_size()`` understands\n        \"\"\"\n        return obj.shape\n\n    def get_size(self, shape_info):\n        \"\"\" Number of bytes taken by the object represented by shape_info.\n\n        :param shape_info: the output of the call to get_shape_info()\n        :return: the number of bytes taken by the object described by\n            ``shape_info``.\n        \"\"\"\n        if shape_info:\n            return numpy.prod(shape_info) * numpy.dtype(self.dtype).itemsize\n        else:  # a scalar\n            return numpy.dtype(self.dtype).itemsize\ntheano.compile.ops.expandable_types += (TensorType,)\n\n# Register TensorType C code for ViewOp.\ntheano.compile.register_view_op_c_code(\n        TensorType,\n        \"\"\"\n        Py_XDECREF(%(oname)s);\n        %(oname)s = %(iname)s;\n        Py_XINCREF(%(oname)s);\n        \"\"\",\n        version=1)\n\n\n# Register TensorType C code for Shape Op.\ntheano.compile.register_shape_c_code(\n    TensorType,\n    \"\"\"\n    npy_intp shape[] = {PyArray_NDIM(%(iname)s)};\n    if(%(oname)s == NULL || (PyArray_DIMS(%(oname)s)[0] != shape[0]))\n    {\n        Py_XDECREF(%(oname)s);\n        %(oname)s = (PyArrayObject*) PyArray_SimpleNew(1, shape, NPY_INT64);\n    }\n    for(int i=0;i<shape[0];i++)\n    {\n        ((npy_int64*)PyArray_GETPTR1(%(oname)s, i))[0] = PyArray_DIMS(%(iname)s)[i];\n    }\n    \"\"\",\n    version=1)\n\n\n# Register TensorType C code for ViewOp.\ntheano.compile.register_shape_i_c_code(\n        TensorType,\n        \"\"\"\n        if(!%(oname)s)\n            %(oname)s=(PyArrayObject*)PyArray_EMPTY(0, NULL, NPY_INT64, 0);\n        ((npy_int64*)PyArray_DATA(%(oname)s))[0]=PyArray_DIMS(%(iname)s)[%(i)s];\n        \"\"\",\n        \"\"\"\n        if (%(i)s>=PyArray_NDIM(%(iname)s)){\n            PyErr_SetString(PyExc_TypeError,\n                \"Number of dimensions lower than expected\");\n            %(fail)s\n        }\n        \"\"\",\n        version=3)\n\n# Register TensorType C code for DeepCopyOp\ntheano.compile.register_deep_copy_op_c_code(\n        TensorType,\n        \"\"\"\n        int alloc = %(oname)s == NULL;\n        for(int i=0; !alloc && i<PyArray_NDIM(%(oname)s); i++) {\n           if(PyArray_DIMS(%(iname)s)[i] != PyArray_DIMS(%(oname)s)[i]) {\n               alloc = true;\n               break;\n           }\n        }\n        if(alloc) {\n            Py_XDECREF(%(oname)s);\n            %(oname)s = (PyArrayObject*)PyArray_NewCopy(%(iname)s,\n                                                        NPY_ANYORDER);\n            if (!%(oname)s)\n            {\n                PyErr_SetString(PyExc_ValueError,\n                                \"DeepCopyOp: the copy failed!\");\n                %(fail)s;\n            }\n        } else {\n            if(PyArray_CopyInto(%(oname)s, %(iname)s)){\n                PyErr_SetString(PyExc_ValueError,\n            \"DeepCopyOp: the copy failed into already allocated space!\");\n                %(fail)s;\n            }\n        }\n        \"\"\",\n        version=2)\n\n\ntheano.compile.register_rebroadcast_c_code(\n    TensorType,\n    \"\"\"\n    if(PyArray_DIMS(%(iname)s)[%(axis)s] != 1){\n        PyErr_Format(PyExc_ValueError,\n            \"Dimension %(axis)s in Rebroadcast's input was\"\n            \" supposed to be 1 (got %%d instead)\",\n            PyArray_DIMS(%(iname)s)[%(axis)s]);\n        %(fail)s\n    }\n    \"\"\",\n        version=1)\n\n\ntheano.compile.register_specify_shape_c_code(\n    TensorType,\n    \"\"\"\n        if (PyArray_NDIM(%(iname)s) != PyArray_DIMS(%(shape)s)[0]) {\n            PyErr_Format(PyExc_AssertionError,\n                         \"SpecifyShape: vector of shape has %%d elements,\"\n                         \" but the input has %%d dimensions.\",\n                         PyArray_NDIM(%(iname)s),\n                         PyArray_DIMS(%(shape)s)[0]);\n            %(fail)s;\n        }\n        for(int i = 0; i < PyArray_NDIM(%(iname)s); i++){\n            dtype_%(shape)s shp = ((dtype_%(shape)s*)PyArray_GETPTR1(%(shape)s,\n                                                                     i))[0];\n            if (PyArray_DIMS(%(iname)s)[i] != shp) {\n                PyErr_Format(PyExc_AssertionError,\n                             \"SpecifyShape: dim %%d of input has shape %%d,\"\n                             \" expected %%d.\",\n                             i, PyArray_DIMS(%(iname)s)[i],\n                             shp);\n                %(fail)s;\n            }\n        }\n        Py_XDECREF(%(oname)s);\n        %(oname)s = %(iname)s;\n        Py_XINCREF(%(oname)s);\n    \"\"\",\n    version=1)\n", "meta": {"hexsha": "d5e12195940ba4680a1eb841af585246c321ac97", "size": 30007, "ext": "py", "lang": "Python", "max_stars_repo_path": "theano/tensor/type.py", "max_stars_repo_name": "shaibagon/Theano", "max_stars_repo_head_hexsha": "b4244cfaa1c99007015bb01e859699eec3518053", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-31T12:29:10.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-31T12:29:10.000Z", "max_issues_repo_path": "theano/tensor/type.py", "max_issues_repo_name": "AtousaTorabi/Theano_old", "max_issues_repo_head_hexsha": "ba2d2f74406243112e813df31429721c791a889a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "theano/tensor/type.py", "max_forks_repo_name": "AtousaTorabi/Theano_old", "max_forks_repo_head_hexsha": "ba2d2f74406243112e813df31429721c791a889a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9931693989, "max_line_length": 96, "alphanum_fraction": 0.5189455794, "include": true, "reason": "import numpy,import theano,from theano", "num_tokens": 6640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117165898111866, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.176596092380428}}
{"text": "# -*- coding: utf-8 -*-\n\nimport numpy as np\n\n# make colormaps\n#from matplotlib.colors import LinearSegmentedColormap\nimport matplotlib.pyplot as plt\nesrBlueRed = {'red':   ((0.0, 0.0, 0.0),\n                        (0.5, 0.0, 0.0),\n                        (1.0, 1.0, 1.0)),\n\n              'green': ((0.0, 0.0, 0.0),\n                        (0.5, 0.0, 0.0),\n                        (1.0, 0.0, 0.0)),\n\n              'blue':  ((0.0, 1.0, 1.0),\n                        (0.5, 0.0, 0.0),\n                        (1.0, 0.0, 0.0))\n              }\n\nisomorphicTest = {'red':   ((0.0, 0.0, 0.0),\n                            (0.33, 0.0, 0.0),\n                            (0.67, 1.0, 1.0),\n                            (1, 1.0, 1.0)),\n\n              'green': ((0.0, 0.0, 0.0),\n                            (0.33, 0.0, 0.0),\n                            (0.67, 0.0, 0.0),\n                            (1, 1.0, 1.0)),\n\n              'blue':  ((0.0, 0.0, 0.0),\n                            (0.33, 1.0, 1.0),\n                            (0.67, 0.0, 0.0),\n                            (1, 1.0, 1.0)),\n              }\n\n\nesrJet = {'red':       ((0./12, 0.0, 0.0),\n                        (1./12, 0.0, 0.0),\n                        (2./12, 0.0, 0.0),\n                        (3./12, 0.0, 0.0),\n                        (4./12, 0.0, 0.0),\n                        (4.7/12, 0.5, 0.5),\n                        (6./12, 1.0, 1.0),\n                        (7.3/12, 1.0, 1.0),\n                        (8./12, 1.0, 1.0),\n                        (9./12, 1.0, 1.0),\n                        (10./12, 1.0, 1.0),\n                        (11./12, 1.0, 1.0),\n                        (12./12, 1.0, 1.0)),\n\n          'green':     ((0./12, 0.0, 0.0),\n                        (1./12, 0.0, 0.0),\n                        (2./12, 0.0, 0.0),\n                        (3./12, 0.5, 0.5),\n                        (4.7/12, 1.0, 1.0),\n                        (5./12, 1.0, 1.0),\n                        (6./12, 1.0, 1.0),\n                        (7.3/12, 0.5, 0.5),\n                        (8./12, 0.0, 0.0),\n                        (9./12, 0.0, 0.0),\n                        (10./12, 0.0, 0.0),\n                        (11./12, 0.5, 0.5),\n                        (12./12, 1.0, 1.0)),\n\n          'blue':      ((0./12, 0.0, 0.0),\n                        (1./12, 0.5, 0.5),\n                        (2./12, 1.0, 1.0),\n                        (3./12, 0.5, 0.5),\n                        (4.7/12, 0.0, 0.0),\n                        (5./12, 0.0, 0.0),\n                        (6./12, 0.0, 0.0),\n                        (7.3/12, 0.0, 0.0),\n                        (8./12, 0.0, 0.0),\n                        (9./12, 0.5, 0.5),\n                        (10./12, 1.0, 1.0),\n                        (11./12, 1.0, 1.0),\n                        (12./12, 1.0, 1.0)),\n              }\n\n_nipy_spectral_pinktop = {\n      'red': [(0.0, 0.0, 0.0), (0.05, 0.4667, 0.4667),\n              (0.10, 0.5333, 0.5333), (0.15, 0.0, 0.0),\n              (0.20, 0.0, 0.0), (0.25, 0.0, 0.0),\n              (0.30, 0.0, 0.0), (0.35, 0.0, 0.0),\n              (0.40, 0.0, 0.0), (0.45, 0.0, 0.0),\n              (0.50, 0.0, 0.0), (0.55, 0.0, 0.0),\n              (0.60, 0.0, 0.0), (0.65, 0.7333, 0.7333),\n              (0.70, 0.9333, 0.9333), (0.75, 1.0, 1.0),\n              (0.80, 1.0, 1.0), (0.85, 1.0, 1.0),\n              (0.90, 0.8667, 0.8667), (0.95, 0.80, 0.80),\n              (1.0, 1.0, 1.0)],\n    'green': [(0.0, 0.0, 0.0), (0.05, 0.0, 0.0),\n              (0.10, 0.0, 0.0), (0.15, 0.0, 0.0),\n              (0.20, 0.0, 0.0), (0.25, 0.4667, 0.4667),\n              (0.30, 0.6000, 0.6000), (0.35, 0.6667, 0.6667),\n              (0.40, 0.6667, 0.6667), (0.45, 0.6000, 0.6000),\n              (0.50, 0.7333, 0.7333), (0.55, 0.8667, 0.8667),\n              (0.60, 1.0, 1.0), (0.65, 1.0, 1.0),\n              (0.70, 0.9333, 0.9333), (0.75, 0.8000, 0.8000),\n              (0.80, 0.6000, 0.6000), (0.85, 0.0, 0.0),\n              (0.90, 0.0, 0.0), (0.95, 0.0, 0.0),\n              (1.0, 0.5, 0.5)],\n     'blue': [(0.0, 0.0, 0.0), (0.05, 0.5333, 0.5333),\n              (0.10, 0.6000, 0.6000), (0.15, 0.6667, 0.6667),\n              (0.20, 0.8667, 0.8667), (0.25, 0.8667, 0.8667),\n              (0.30, 0.8667, 0.8667), (0.35, 0.6667, 0.6667),\n              (0.40, 0.5333, 0.5333), (0.45, 0.0, 0.0),\n              (0.5, 0.0, 0.0), (0.55, 0.0, 0.0),\n              (0.60, 0.0, 0.0), (0.65, 0.0, 0.0),\n              (0.70, 0.0, 0.0), (0.75, 0.0, 0.0),\n              (0.80, 0.0, 0.0), (0.85, 0.0, 0.0),\n              (0.90, 0.0, 0.0), (0.95, 0.0, 0.0),\n              (1.0, 1.0, 1.0)],\n}\n\n# no pink at top\nesrJet2 = {'red':       ((0, 0.0, 0.0),  # black\n                        (0.25, 0.0, 0.0),  # blue\n                        (0.5, 0.0, 0.0),  # green\n                        (0.75, 1.0, 1.0),  # yellow\n                        (1.0, 1.0, 1.0)),  # red\n\n          'green':     ((0, 0.0, 0.0),  # black\n                        (0.25, 0.0, 0.0),  # blue\n                        (0.5, 1.0, 1.0),  # green\n                        (0.75, 1.0, 1.0),  # yellow\n                        (1.0, 0.0, 0.0)),  # red\n\n          'blue':      ((0, 0.0, 0.0),  # black\n                        (0.25, 1.0, 1.0),  # blue\n                        (0.5, 0.0, 0.0),  # green\n                        (0.75, 0.0, 0.0),  # yellow\n                        (1.0, 0.0, 0.0)),  # red\n              }\n\ntest =  {'red':      ((0.0, 0.0, 0.0),\n                        (0.5, 0.5, 0.5),\n                        (1.0, 1.0, 1.0)),\n\n          'green':     ((0.0, 0.0, 0.0),\n                        (0.5, 0.25, 0.25),\n                        (1.0, 0.0, 0.0)),\n\n          'blue':      ((0.0, 0.0, 0.0),\n                        (0.5, 0.25, 0.25),\n                        (1.0, 0.0, 0.0)),\n              }\n\nplt.register_cmap(name='isomorphicTest', data=isomorphicTest)\n\n#blue_red1 = LinearSegmentedColormap('BlueRed1', cdict1)\nplt.register_cmap(name='esrBlueRed', data=esrBlueRed)\nplt.register_cmap(name='esrJet', data=esrJet)\nplt.register_cmap(name='nipy_spectral_pinktop', data=_nipy_spectral_pinktop)\nplt.register_cmap(name='esrJet2', data=esrJet2)\n\n\n#@profile\ndef load_param_single_simple(fn, status=[0, np.inf], trueAzEl=False):\n    \"\"\"\n    Loads parameters from a single GUISDAP result file. NOT meant to be a\n    complete replacement for GUISDAPs own load_param.m. Loads physical\n    parameters and time, az/el etc. and little else from monostatic experiments.\n\n    Parameters\n    ----------\n\n    fn : string, required\n        name of file to load\n\n    status : list of length 2\n        [max_status, max_residual]\n        Status: 0 = OK, 1 = max number of iterations exceeded, 2 = No fit done\n        because data too noisy\n\n    trueAzEl : boolean\n        If False, azimuth and elevation will be cast into 0-360 and 0-90 degrees\n\n    \"\"\"\n\n    import datetime as dt\n    from scipy.io import loadmat\n\n    params = loadmat(fn, mat_dtype=True)\n\n    # needed for calculations and other computations\n    Te_Ti = params['r_param'][:, 2]  # Te/Ti\n    errTe_Ti = params['r_error'][:, 2]\n    r_status = params['r_status'][:, 0]\n\n    # don't really know what this is\n    if 'r_Offsetppd' in params:\n        rOff = params['r_Offsetppd']\n    elif 'r_phasepush' in params:\n        rOff = params['r_phasepush']\n    else:\n        rOff = np.nan\n\n    c1 = r_status > status[0]\n    c2 = params['r_res'][:, 0] > status[1]\n    c3 = params['r_error'][:, :8] > 0\n    c12 = np.array([np.bitwise_or(c1, c2), ]*8).T\n\n    params['r_error'][:, :8][c12*c3] = np.nan\n    params['r_param'][c12*c3] = np.nan\n\n    # Time\n    # XXX: Time is a python datetime object, not MATLAB datenum!\n    t = params['r_time']\n    tStart = dt.datetime(int(t[0, 0]), int(t[0, 1]), int(t[0, 2]), int(t[0, 3]), int(t[0, 4]), int(t[0, 5]), int(round(np.mod(t[0, 5], 1)*1e6, 0)))\n    tEnd = dt.datetime(int(t[1, 0]), int(t[1, 1]), int(t[1, 2]), int(t[1, 3]), int(t[1, 4]), int(t[1, 5]), int(round(np.mod(t[1, 5], 1)*1e6, 0)))\n\n    # 1D params\n    Az = params['r_az'][0][0]  # azimuth\n    El = params['r_el'][0][0]  # elevation\n    Pt = params['r_Pt'][0][0]/10000  # transmitter power\n    Tsys = np.median(params['r_Tsys'])\n    Oppd_Php = rOff\n\n    # 2D params\n    Ran = params['r_range'][:, 0]  # range of scattering volume\n    Alt = params['r_h'][:, 0]  # altitude of scattering volume\n    Ne = params['r_param'][:, 0]\n    Ti = params['r_param'][:, 1]\n    Te = Te_Ti * Ti\n    Vi = -params['r_param'][:, 4]\n    Coll = params['r_param'][:, 3]  # collision frequency\n    Comp = params['r_dp'][:, 0]  # Ion composition ([O+]/Ne)\n    Res = params['r_res'][:, 0]  # residual of the fit (or standard deviation?)\n\n    # 2D errors\n    errNe = params['r_error'][:, 0]\n    errTi = params['r_error'][:, 1]\n    errTe = (errTi/Ti + errTe_Ti/Te_Ti)*Te\n    errVi = params['r_error'][:, 4]\n    errColl = params['r_error'][:, 3]\n\n    Time = np.array([[tStart, tEnd], ]).T\n    par1D = np.array([[Az, El, Pt, Tsys], ])\n    if not np.isnan(Oppd_Php):\n        par1D = np.append(par1D, Oppd_Php, axis=1)\n    par2D = np.column_stack((Ran, Alt, Ne, Te, Ti, Vi, Coll, Comp, Res))\n    par2D = np.expand_dims(par2D, 1)\n    err2D = np.column_stack((errNe, errTe, errTi, errVi, errColl))\n    err2D = np.expand_dims(err2D, 1)\n    rpar2D = np.array([])  # XXX currently not implemented\n\n    # cast azimuth and elevation into range 0-360, 0-90 degrees\n    if not trueAzEl:\n        d = np.where(par1D[:, 1] > 90)\n        par1D[d, 1] = 180 - par1D[d, 1]\n        par1D[d, 0] = par1D[d, 0] + 180\n        par1D[:, 0] = np.mod(par1D[:, 0]+360, 360)\n\n    return Time, par2D, par1D, rpar2D, err2D\n\n\ndef load_param_simple(path, trueAzEl=False):\n    \"\"\"\n    Loads parameters from a directory of GUISDAP result files. NOT meant to be\n    a complete replacement for GUISDAPs own load_param.m. Loads physical\n    parameters and time, az/el etc. and little else from monostatic experiments.\n\n    Parameters\n    ----------\n\n    path: string, required\n        name of file to load\n\n    trueAzEl : boolean\n        If False, azimuth and elevation will be cast into 0-360 and 0-90 degrees\n\n    Returns\n    -------\n\n    * `N` is number of integrations (i.e., number of files read)\n    * `M` is number of range gates\n\n    Time : 2D array (2, `N`)\n        First index is start timestamp (0) and end timestamp (1) of integration.\n    par2D : 3D array (`M`, `N`, 9)\n        Third index is parameter: Range (0), Altitude (1), Ne (2), Te (3),\n        Ti (4), Vi (5), Coll (6), Comp (7), Res (8)\n    par1D : 2D array (5, `N`)\n        First index is parameter: Az (0), El (1), Pt (2), Tsys (3), Oppd/Php (4)\n    rpar2D : Empty array (not implemented)\n        ..\n    err2D : 3D array (`M`, `N`, 5)\n        Errors for the following parameters (third index): Ne (0), Te (1), Ti (2), Vi (3), Coll (4)\n\n    \"\"\"\n\n    import os\n    import fnmatch\n\n    mat_files = fnmatch.filter(os.listdir(path), '*.mat')\n    n_ip = len(mat_files)  # number of integration periods\n\n    try:\n        import frogress\n        iterator = frogress.bar(enumerate(mat_files), steps=len(mat_files))\n    except:\n        iterator = enumerate(mat_files)\n\n    for i, mat_file in iterator:\n        s_Time, s_par2D, s_par1D, s_rpar2D, s_err2D = load_param_single_simple(os.path.join(path, mat_file), trueAzEl=trueAzEl)\n\n        if i == 0:  # initialize data structures\n            n_ran = len(s_par2D[:, 0, 1])  # number of range gates\n\n            Time = np.empty((2, n_ip), dtype=object)\n            par2D = np.empty((n_ran, n_ip, 9))*np.nan\n            par1D = np.zeros((n_ip, s_par1D.shape[1]))\n            rpar2D = np.array([])\n            err2D = np.empty((n_ran, n_ip, 5))*np.nan\n\n        # correct dimensions if number of range gates have changed\n        # XXX: Double-check how this is done in the original matlab code\n        if par2D[:, 0, 0].shape[0] < s_par2D[:, 0, 0].shape[0]:\n            par2D = np.append(par2D, np.ones((s_par2D.shape[0]-par2D.shape[0], par2D.shape[1], par2D.shape[2]))*np.nan, axis=0)\n            err2D = np.append(err2D, np.ones((s_err2D.shape[0]-err2D.shape[0], err2D.shape[1], err2D.shape[2]))*np.nan, axis=0)\n        elif par2D[:, 0, 0].shape[0] > s_par2D[:, 0, 0].shape[0]:\n            s_par2D = np.append(s_par2D, np.ones((par2D.shape[0]-s_par2D.shape[0], s_par2D.shape[1], s_par2D.shape[2]))*np.nan, axis=0)\n            s_err2D = np.append(s_err2D, np.ones((err2D.shape[0]-s_err2D.shape[0], s_err2D.shape[1], s_err2D.shape[2]))*np.nan, axis=0)\n\n        # somewhat the same for par1D\n        if s_par1D.shape[1] > par1D.shape[1]:\n            par1D = np.vstack((par1D, np.empty((par1D.shape[1], 1))*np.nan))\n        elif s_par1D.shape[1] < par1D.shape[1]:\n            s_par1D = np.append(s_par1D, np.nan)\n\n        # add current data to data structures\n        Time[:, i] = s_Time[:, 0]\n        par1D[i, :] = s_par1D[0, :]\n        par2D[:, i, :] = s_par2D[:, 0, :]\n        err2D[:, i, :] = s_err2D[:, 0, :]\n\n    return Time, par2D, par1D, rpar2D, err2D\n\n\ndef gg2gc(gg):\n    \"\"\"transforms coordinates from geographic (lat, lon, h) to geocentric\"\"\"\n\n    import math\n\n    factor = math.pi/180  # conversion factor from degrees to radians\n    r_earth = 6378.135  # earth radius (km) and flatness factor\n    g = 1.00673944  # earth flatness factor\n\n    lat = gg[0]*factor\n    lon = gg[1]*factor\n    h = gg[2]\n\n    hor = (r_earth/math.sqrt(1+math.tan(lat)**2/g)+h*math.cos(lat))\n    gc = [hor*math.cos(lon), hor*math.sin(lon), r_earth/math.sqrt(g+g**2/math.tan(lat)**2)+h*math.sin(lat)]\n\n    return gc\n\n\ndef gc2gg(gc):\n    \"\"\"transforms coordinates from geocentric to geographic (lat, lon, h)\"\"\"\n\n    import math\n\n    factor = math.pi/180  # conversion factor from degrees to radians\n    r_earth = 6378.135  # earth radius (km) and flatness factor\n    g = 1.00673944  # earth flatness factor\n\n    gg = [0, 0, 0]  # initialize gg, not needed in original MATLAB code...\n\n    if gc[0] == 0 and gc[1] == 0:\n        print('Beware of the spinning earth axis!')\n        gg = [90, 0, gc[2] - r_earth/g]\n    else:\n        gg[1] = math.atan2(gc[1], gc[0]) / factor\n        r0 = math.sqrt(sum([gc[0]*gc[0], gc[1]*gc[1]]))\n        xi0 = gc[2] / (r0 * math.sqrt(g))\n        xi_iter = r_earth*(g-1)/(g*r0)\n        tanxi = xi0\n        tanxi = xi0 + xi_iter * tanxi / math.sqrt(1+tanxi**2)\n        tanxi = xi0 + xi_iter * tanxi / math.sqrt(1+tanxi**2)\n        gg[0] = math.atan(math.sqrt(g)*tanxi)/factor\n        gg[2] = math.sqrt(1+g*tanxi**2)*(r0-r_earth/math.sqrt(1+tanxi**2))\n\n    return gg\n\n\ndef loc2gg(site1, loc):\n    \"\"\"transforms the scattering point location given in local coordinates\n    loc   [elevation, azimuth, range] at location\n    site1 [latitude, longitude, height]  to geographic coordinates\n    \"\"\"\n\n    import math\n    import numpy as np\n\n    factor = math.pi/180\n\n    #  first calculate the  transformation matrices\n    lat1 = site1[0]*factor\n    lon1 = site1[1]*factor\n    sinlat = math.sin(lat1)\n    coslat = math.cos(lat1)\n    sinlon = math.sin(lon1)\n    coslon = math.cos(lon1)\n    rlocgc = np.array([[sinlat*coslon, -sinlon,  coslat*coslon],\n                       [sinlat*sinlon,  coslon,  coslat*sinlon],\n                       [-coslat,             0,  sinlat]])\n\n    s1 = loc[0]*factor\n    s2 = loc[1]*factor\n    s3 = loc[2]\n    loc = s3*np.array([-math.cos(s2)*math.cos(s1), math.sin(s2)*math.cos(s1), math.sin(s1)]).T\n    gc_site1 = gg2gc(site1)  # Site1 to geogentric\n    gc_sp = gc_site1 + np.dot(rlocgc, loc).T  # Add scattering distance in geocentric\n    gg_sp = gc2gg(gc_sp)  # Transform back to geographic\n\n    return gg_sp\n", "meta": {"hexsha": "9309fcd061f86128d56ca34327a9fd322352e523", "size": 15478, "ext": "py", "lang": "Python", "max_stars_repo_path": "eiscat_toolkit.py", "max_stars_repo_name": "cmeeren/eiscatscanplot", "max_stars_repo_head_hexsha": "b49bf1c7410cbfd015f84fe915b01d1cd1b1878b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-08-25T16:31:40.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-30T16:49:52.000Z", "max_issues_repo_path": "eiscat_toolkit.py", "max_issues_repo_name": "cmeeren/eiscatscanplot", "max_issues_repo_head_hexsha": "b49bf1c7410cbfd015f84fe915b01d1cd1b1878b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-09-14T16:11:50.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-14T16:57:38.000Z", "max_forks_repo_path": "eiscat_toolkit.py", "max_forks_repo_name": "cmeeren/eiscatscanplot", "max_forks_repo_head_hexsha": "b49bf1c7410cbfd015f84fe915b01d1cd1b1878b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8523809524, "max_line_length": 147, "alphanum_fraction": 0.4729939269, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.17659609062668588}}
{"text": "from collections import defaultdict\nimport logging\nimport os\nfrom typing import Mapping, Tuple\n\nimport numpy as np\nimport pyro\nfrom pyro.infer import SVI, TraceGraph_ELBO, Trace_ELBO\nfrom pyro.nn import pyro_method\nfrom pyro.optim import ExponentialLR, AdagradRMSProp  # noqa: F401\nfrom pyro.distributions.torch_transform import ComposeTransformModule\nfrom pyro.distributions.transforms import (\n    ComposeTransform, AffineTransform, ExpTransform, Spline, Permute\n)\nfrom pyro.distributions.transforms import batchnorm, iterated\nfrom pyro.distributions import (\n    LowRankMultivariateNormal, MultivariateNormal, Normal, Laplace, TransformedDistribution  # noqa: F401\n)\nimport torch\nfrom torch.distributions import Independent\nfrom torch.optim import AdamW\n\nfrom counterfactualms.arch.medical import Decoder, Encoder\nfrom counterfactualms.arch.nvae import Decoder as NDecoder\nfrom counterfactualms.arch.nvae import Encoder as NEncoder\nfrom counterfactualms.arch.thirdparty.neural_operations import Swish\nfrom counterfactualms.distributions.transforms.reshape import ReshapeTransform\nfrom counterfactualms.distributions.transforms.affine import LowerCholeskyAffine\nfrom counterfactualms.utils.optim import OneCycleLR\nfrom counterfactualms.utils.pyro_modifications import affine_autoregressive, affine_coupling\nfrom counterfactualms.utils.pyro_modifications import spline_autoregressive, spline_coupling\nfrom counterfactualms.distributions.deep import (\n    DeepMultivariateNormal, DeepIndepNormal, DeepIndepMixtureNormal, Conv2dIndepNormal, DeepLowRankMultivariateNormal\n)\nfrom counterfactualms.experiments.calabresi.base_experiment import (\n    BaseCovariateExperiment, BaseSEM, EXPERIMENT_REGISTRY  # noqa: F401\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass StorageTraceGraph_ELBO(TraceGraph_ELBO):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.trace_storage = {'model': None, 'guide': None}\n\n    def _get_trace(self, model, guide, args, kwargs):\n        model_trace, guide_trace = super()._get_trace(model, guide, args, kwargs)\n        self.trace_storage['model'] = model_trace\n        self.trace_storage['guide'] = guide_trace\n        return model_trace, guide_trace\n\n\nclass StorageTrace_ELBO(Trace_ELBO):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.trace_storage = {'model': None, 'guide': None}\n\n    def _get_trace(self, model, guide, args, kwargs):\n        model_trace, guide_trace = super()._get_trace(model, guide, args, kwargs)\n        self.trace_storage['model'] = model_trace\n        self.trace_storage['guide'] = guide_trace\n        return model_trace, guide_trace\n\n\nclass Lambda(torch.nn.Module):\n    def __init__(self, func):\n        super().__init__()\n        self.func = func\n\n    def forward(self, x):\n        return self.func(x)\n\n\nclass BaseVISEM(BaseSEM):\n    context_dim = 0  # number of context dimensions for decoder\n\n    def __init__(self, latent_dim:int, prior_components:int=1, posterior_components:int=1,\n                 logstd_init:float=-5, enc_filters:Tuple[int]=(16,32,64,128),\n                 dec_filters:Tuple[int]=(128,64,32,16), num_convolutions:int=3, use_upconv:bool=False,\n                 decoder_type:str='fixed_var', decoder_cov_rank:int=10, img_shape:Tuple[int]=(128,128),\n                 use_nvae=False, use_weight_norm=False, use_spectral_norm=False, laplace_likelihood=False,\n                 eps=0.1, n_prior_flows=3, n_posterior_flows=3, use_autoregressive=False, use_swish=False,\n                 use_spline=False, use_stable=False, pseudo3d=False, head_filters=(16,16), **kwargs):\n        super().__init__(**kwargs)\n        self.encoder_shape = ((3,) if pseudo3d else (1,)) + tuple(img_shape)\n        self.decoder_shape = (head_filters[0],) + tuple(img_shape)\n        self.img_shape = (1,) + tuple(img_shape)\n        self.latent_dim = latent_dim\n        self.prior_components = prior_components\n        self.posterior_components = posterior_components\n        self.logstd_init = logstd_init\n        self.enc_filters = enc_filters\n        self.dec_filters = dec_filters\n        self.head_filters = head_filters\n        self.num_convolutions = num_convolutions\n        self.use_upconv = use_upconv\n        self.decoder_type = decoder_type\n        self.decoder_cov_rank = decoder_cov_rank\n        self.use_nvae = use_nvae\n        self.use_weight_norm = use_weight_norm\n        self.use_spectral_norm = use_spectral_norm\n        self.laplace_likelihood = laplace_likelihood\n        self.eps = eps\n        self.n_prior_flows = n_prior_flows\n        self.n_posterior_flows = n_posterior_flows\n        self.use_autoregressive = use_autoregressive\n        self.use_spline = use_spline\n        self.use_swish = use_swish\n        self.use_stable = use_stable\n        self.pseudo3d = pseudo3d\n        self.annealing_factor = [1.]  # initialize here; will be changed during training\n        self.n_levels = 0\n\n        # decoder parts\n        if use_nvae:\n            decoder = NDecoder(\n                num_convolutions=self.num_convolutions, filters=self.dec_filters,\n                latent_dim=self.latent_dim + self.context_dim,\n                output_size=self.decoder_shape\n            )\n        else:\n            decoder = Decoder(\n                num_convolutions=self.num_convolutions, filters=self.dec_filters,\n                latent_dim=self.latent_dim + self.context_dim, upconv=self.use_upconv,\n                output_size=self.decoder_shape,\n                use_weight_norm=self.use_weight_norm,\n                use_spectral_norm=self.use_spectral_norm,\n            )\n\n        self._create_decoder(decoder)\n\n        # encoder parts\n        if self.use_nvae:\n            self.encoder = NEncoder(\n                num_convolutions=self.num_convolutions,\n                filters=self.enc_filters,\n                latent_dim=self.latent_dim,\n                input_size=self.encoder_shape\n            )\n        else:\n            self.encoder = Encoder(\n                num_convolutions=self.num_convolutions,\n                filters=self.enc_filters,\n                latent_dim=self.latent_dim,\n                input_size=self.encoder_shape,\n                use_weight_norm=self.use_weight_norm,\n                use_spectral_norm = self.use_spectral_norm\n            )\n\n        nonlinearity = Swish() if self.use_swish else torch.nn.LeakyReLU(0.1)\n        latent_layers = torch.nn.Sequential(\n            torch.nn.Linear(self.latent_dim + self.context_dim, self.latent_dim),\n            nonlinearity\n        )\n\n        if self.posterior_components > 1:\n            self.latent_encoder = DeepIndepMixtureNormal(\n                latent_layers, self.latent_dim, self.latent_dim, self.posterior_components)\n        else:\n            self.latent_encoder = DeepIndepNormal(latent_layers, self.latent_dim, self.latent_dim)\n\n        if self.prior_components > 1:\n            self.z_loc = torch.nn.Parameter(torch.randn([self.prior_components, self.latent_dim]))\n            self.z_scale = torch.nn.Parameter(torch.randn([self.latent_dim]).clamp(min=-1.,max=None))  # log scale\n            self.register_buffer('z_components',  # don't be bayesian about the mixture components\n                ((1/self.prior_components)*torch.ones([self.prior_components], requires_grad=False)).log())\n        else:\n            self.register_buffer('z_loc', torch.zeros([latent_dim, ], requires_grad=False))\n            self.register_buffer('z_scale', torch.ones([latent_dim, ], requires_grad=False))\n            self.z_components = None\n\n        # priors\n        self.sex_logits = torch.nn.Parameter(torch.zeros([1, ]))\n        self.register_buffer('slice_number_min', torch.zeros([1, ], requires_grad=False))\n        self.register_buffer('slice_number_max', 241.*torch.ones([1, ], requires_grad=False)+1.)\n\n        for k in self.required_data - {'sex', 'x', 'slice_number'}:\n            self.register_buffer(f'{k}_base_loc', torch.zeros([1, ], requires_grad=False))\n            self.register_buffer(f'{k}_base_scale', torch.ones([1, ], requires_grad=False))\n\n        self.register_buffer('x_base_loc', torch.zeros(self.img_shape, requires_grad=False))\n        self.register_buffer('x_base_scale', torch.ones(self.img_shape, requires_grad=False))\n\n        for k in self.required_data - {'sex', 'x', 'slice_number'}:\n            self.register_buffer(f'{k}_flow_lognorm_loc', torch.zeros([], requires_grad=False))\n            self.register_buffer(f'{k}_flow_lognorm_scale', torch.ones([], requires_grad=False))\n\n        perm = lambda: torch.randperm(self.latent_dim, dtype=torch.long, requires_grad=False)\n\n        self.use_prior_flow = self.n_prior_flows > 0\n        self.use_prior_permutations = self.n_prior_flows > 1\n        if self.use_prior_permutations:\n            for i in range(self.n_prior_flows):\n                self.register_buffer(f'prior_flow_permutation_{i}', perm())\n\n        self.use_posterior_flow = self.n_posterior_flows > 0\n        self.use_posterior_permutations = self.n_posterior_flows > 1\n        if self.use_posterior_permutations:\n            for i in range(self.n_posterior_flows):\n                self.register_buffer(f'posterior_flow_permutation_{i}', perm())\n\n        # age flow\n        self.age_flow_components = ComposeTransformModule([Spline(1)])\n        self.age_flow_lognorm = AffineTransform(loc=self.age_flow_lognorm_loc.item(), scale=self.age_flow_lognorm_scale.item())\n        self.age_flow_constraint_transforms = ComposeTransform([self.age_flow_lognorm, ExpTransform()])\n        self.age_flow_transforms = ComposeTransform([self.age_flow_components, self.age_flow_constraint_transforms])\n\n        # other flows shared components\n        self.ventricle_volume_flow_lognorm = AffineTransform(loc=self.ventricle_volume_flow_lognorm_loc.item(), scale=self.ventricle_volume_flow_lognorm_scale.item())  # noqa: E501\n        self.ventricle_volume_flow_constraint_transforms = ComposeTransform([self.ventricle_volume_flow_lognorm, ExpTransform()])\n\n        self.brain_volume_flow_lognorm = AffineTransform(loc=self.brain_volume_flow_lognorm_loc.item(), scale=self.brain_volume_flow_lognorm_scale.item())\n        self.brain_volume_flow_constraint_transforms = ComposeTransform([self.brain_volume_flow_lognorm, ExpTransform()])\n\n        self.lesion_volume_flow_lognorm = AffineTransform(loc=self.lesion_volume_flow_lognorm_loc.item(), scale=self.lesion_volume_flow_lognorm_scale.item())\n        self.lesion_volume_flow_eps = AffineTransform(loc=-eps, scale=1.)\n        self.lesion_volume_flow_constraint_transforms = ComposeTransform([self.lesion_volume_flow_lognorm, ExpTransform(), self.lesion_volume_flow_eps])\n\n        self.duration_flow_lognorm = AffineTransform(loc=self.duration_flow_lognorm_loc.item(), scale=self.duration_flow_lognorm_scale.item())\n        self.duration_flow_eps = AffineTransform(loc=-eps, scale=1.)\n        self.duration_flow_constraint_transforms = ComposeTransform([self.duration_flow_lognorm, ExpTransform(), self.duration_flow_eps])\n\n        self.edss_flow_lognorm = AffineTransform(loc=self.edss_flow_lognorm_loc.item(), scale=self.edss_flow_lognorm_scale.item())\n        self.edss_flow_eps = AffineTransform(loc=-eps, scale=1.)\n        self.edss_flow_constraint_transforms = ComposeTransform([self.edss_flow_lognorm, ExpTransform(), self.edss_flow_eps])\n\n        hidden_dims = (3 * self.latent_dim + 1,) if self.use_autoregressive else (2*self.latent_dim, 2*self.latent_dim)\n        flow_kwargs = dict(hidden_dims=hidden_dims, nonlinearity=nonlinearity)\n        if self.use_spline:\n            flow_ = spline_autoregressive if self.use_autoregressive else spline_coupling\n        else:\n            flow_ = affine_autoregressive if self.use_autoregressive else affine_coupling\n        if self.use_autoregressive:\n            flow_kwargs['stable'] = self.use_stable\n\n        if self.use_prior_permutations:\n            self.prior_affine = iterated(self.n_prior_flows, batchnorm, self.latent_dim, momentum=0.05) if self.use_prior_flow else []\n            self.prior_permutations = [Permute(getattr(self, f'prior_flow_permutation_{i}')) for i in range(self.n_prior_flows)]\n            self.prior_flow_components = iterated(self.n_prior_flows, flow_, self.latent_dim, **flow_kwargs) if self.use_prior_flow else []\n            self.prior_flow_transforms = [\n                x for c in zip(self.prior_permutations, self.prior_affine, self.prior_flow_components) for x in c\n            ]\n        else:\n            self.prior_affine = []\n            self.prior_permutations = []\n            self.prior_flow_components = flow_(self.latent_dim, **flow_kwargs) if self.use_prior_flow else []\n            self.prior_flow_transforms = [self.prior_flow_components]\n\n        if self.use_posterior_permutations:\n            self.posterior_affine = iterated(self.n_posterior_flows, batchnorm, self.latent_dim, momentum=0.05)\n            self.posterior_permutations = [Permute(getattr(self, f'posterior_flow_permutation_{i}')) for i in range(self.n_posterior_flows)]\n            self.posterior_flow_components = iterated(self.n_posterior_flows, flow_, self.latent_dim, **flow_kwargs)\n            self.posterior_flow_transforms = [\n                x for c in zip(self.posterior_permutations, self.posterior_affine, self.posterior_flow_components) for x in c\n            ]\n        else:\n            self.posterior_affine = []\n            self.posterior_permutations = []\n            self.posterior_flow_components = flow_(self.latent_dim, **flow_kwargs) if self.use_posterior_flow else []\n            self.posterior_flow_transforms = [self.posterior_flow_components]\n\n    def _create_decoder(self, decoder):\n        co = 3 if self.pseudo3d else 1\n        if self.decoder_type == 'fixed_var':\n            self.decoder = Conv2dIndepNormal(decoder, self.head_filters, co,\n                use_weight_norm=self.use_weight_norm, use_spectral_norm=self.use_spectral_norm)\n            torch.nn.init.zeros_(self.decoder.logstd_head[-1].weight)\n            self.decoder.logstd_head[-1].weight.requires_grad = False\n            torch.nn.init.constant_(self.decoder.logstd_head[-1].bias, self.logstd_init)\n            self.decoder.logstd_head[-1].bias.requires_grad = False\n\n        elif self.decoder_type == 'learned_var':\n            self.decoder = Conv2dIndepNormal(decoder, self.head_filters, co,\n                use_weight_norm=self.use_weight_norm, use_spectral_norm=self.use_spectral_norm,\n                logstd_ref=self.logstd_init)\n            torch.nn.init.zeros_(self.decoder.logstd_head[-1].weight)\n            self.decoder.logstd_head[-1].weight.requires_grad = False\n            torch.nn.init.constant_(self.decoder.logstd_head[-1].bias, self.logstd_init)\n            self.decoder.logstd_head[-1].bias.requires_grad = True\n\n        elif self.decoder_type == 'independent_var':\n            self.decoder = Conv2dIndepNormal(decoder, self.head_filters, co,\n                use_weight_norm=self.use_weight_norm, use_spectral_norm=self.use_spectral_norm,\n                logstd_ref=self.logstd_init)\n            torch.nn.init.zeros_(self.decoder.logstd_head[-1].weight)\n            self.decoder.logstd_head[-1].weight.requires_grad = True\n            torch.nn.init.normal_(self.decoder.logstd_head[-1].bias, 0., 1e-1)\n            self.decoder.logstd_head[-1].bias.requires_grad = True\n\n        elif self.decoder_type == 'multivariate_gaussian':\n            seq = torch.nn.Sequential(decoder, Lambda(lambda x: x.view(x.shape[0], -1)))\n            self.decoder = DeepMultivariateNormal(seq, np.prod(self.decoder_shape), np.prod(self.img_shape))\n\n        elif self.decoder_type == 'sharedvar_multivariate_gaussian':\n            seq = torch.nn.Sequential(decoder, Lambda(lambda x: x.view(x.shape[0], -1)))\n            self.decoder = DeepMultivariateNormal(seq, np.prod(self.decoder_shape), np.prod(self.img_shape))\n            torch.nn.init.zeros_(self.decoder.logdiag_head.weight)\n            self.decoder.logdiag_head.weight.requires_grad = False\n            torch.nn.init.zeros_(self.decoder.lower_head.weight)\n            self.decoder.lower_head.weight.requires_grad = False\n            torch.nn.init.normal_(self.decoder.logdiag_head.bias, self.logstd_init, 1e-1)\n            self.decoder.logdiag_head.bias.requires_grad = True\n\n        elif self.decoder_type == 'lowrank_multivariate_gaussian':\n            seq = torch.nn.Sequential(decoder, Lambda(lambda x: x.view(x.shape[0], -1)))\n            self.decoder = DeepLowRankMultivariateNormal(\n                seq, np.prod(self.decoder_shape), np.prod(self.img_shape), self.decoder_cov_rank\n            )\n\n        elif self.decoder_type == 'sharedvar_lowrank_multivariate_gaussian':\n            seq = torch.nn.Sequential(decoder, Lambda(lambda x: x.view(x.shape[0], -1)))\n            self.decoder = DeepLowRankMultivariateNormal(\n                seq, np.prod(self.decoder_shape), np.prod(self.img_shape), self.decoder_cov_rank\n            )\n            torch.nn.init.zeros_(self.decoder.logdiag_head.weight)\n            self.decoder.logdiag_head.weight.requires_grad = False\n            torch.nn.init.zeros_(self.decoder.factor_head.weight)\n            self.decoder.factor_head.weight.requires_grad = False\n            torch.nn.init.normal_(self.decoder.logdiag_head.bias, self.logstd_init, 1e-1)\n            self.decoder.logdiag_head.bias.requires_grad = True\n\n        else:\n            raise ValueError(f'unknown decoder type {self.decoder_type}.')\n\n    def __setattr__(self, name, value):\n        super().__setattr__(name, value)\n        if 'flow_lognorm_loc' in name:\n            name_ = name.replace('flow_lognorm_loc', '')\n            getattr(self, name_ + 'flow_lognorm').loc = value.item()\n        elif 'flow_lognorm_scale' in name:\n            name_ = name.replace('flow_lognorm_scale', '')\n            getattr(self, name_ + 'flow_lognorm').scale = value.item()\n        elif 'flow_norm_loc' in name:\n            name_ = name.replace('flow_norm_loc', '')\n            getattr(self, name_ + 'flow_norm').loc = value.item()\n        elif 'flow_norm_scale' in name:\n            name_ = name.replace('flow_norm_scale', '')\n            getattr(self, name_ + 'flow_norm').scale = value.item()\n        elif 'prior_flow_permutation' in name:\n            i = int(name[-1])\n            self.prior_permutations[i].permutation = value\n        elif 'posterior_flow_permutation' in name:\n            i = int(name[-1])\n            self.posterior_permutations[i].permutation = value\n\n    def _get_preprocess_transforms(self):\n        return super()._get_preprocess_transforms().inv\n\n    def _get_transformed_x_dist(self, latent, ctx=None):\n        x_pred_dist = self.decoder.predict(latent, ctx)  # returns a normal dist with mean of the predicted image\n        if self.laplace_likelihood:\n            x_base_dist = Laplace(self.x_base_loc, self.x_base_scale).to_event(3)\n        else:\n            x_base_dist = Normal(self.x_base_loc, self.x_base_scale).to_event(3)  # 3 dimensions starting from right dep.\n\n        preprocess_transform = self._get_preprocess_transforms()\n\n        if isinstance(x_pred_dist, MultivariateNormal) or isinstance(x_pred_dist, LowRankMultivariateNormal):\n            chol_transform = LowerCholeskyAffine(x_pred_dist.loc, x_pred_dist.scale_tril)\n            reshape_transform = ReshapeTransform(self.img_shape, (np.prod(self.img_shape), ))\n            x_reparam_transform = ComposeTransform([reshape_transform, chol_transform, reshape_transform.inv])\n        elif isinstance(x_pred_dist, Independent):\n            x_pred_dist = x_pred_dist.base_dist\n            x_reparam_transform = AffineTransform(x_pred_dist.loc, x_pred_dist.scale, 3)\n        else:\n            raise ValueError(f'{x_pred_dist} not valid.')\n\n        return TransformedDistribution(x_base_dist, ComposeTransform([x_reparam_transform, preprocess_transform]))\n\n    @pyro_method\n    def guide(self, obs):\n        raise NotImplementedError()\n\n    @pyro_method\n    def svi_guide(self, obs):\n        self._check_observation(obs)\n        self.guide(obs)\n\n    @pyro_method\n    def svi_model(self, obs):\n        self._check_observation(obs)\n        batch_size = obs['x'].shape[0]\n        with pyro.plate('observations', batch_size):\n            pyro.condition(self.model, data=obs)()\n\n    @pyro_method\n    def infer_z(self, *args, **kwargs):\n        return self.guide(*args, **kwargs)\n\n    @property\n    def required_data(self):\n        return {'x', 'sex', 'age', 'ventricle_volume', 'brain_volume', 'lesion_volume',\n                'edss', 'duration', 'slice_number'}\n\n    def _check_observation(self, obs):\n        keys = obs.keys()\n        assert self.required_data == set(keys), f'Incompatible observation: {tuple(keys)}'\n\n    @pyro_method\n    def infer(self, obs):\n        self._check_observation(obs)\n        obs_ = obs.copy()\n        z = self.infer_z(obs_)\n        obs_.update(dict(z=z))\n        exogenous = self.infer_exogenous(obs_)\n        exogenous['z'] = z\n        return exogenous\n\n    @pyro_method\n    def reconstruct(self, obs, num_particles:int=1):\n        self._check_observation(obs)\n        z_dist = pyro.poutine.trace(self.guide).get_trace(obs).nodes['z']['fn']\n        batch_size = obs['x'].shape[0]\n        obs_ = {k: v for k, v in obs.items() if k != 'x'}\n        recons = []\n        for _ in range(num_particles):\n            z = pyro.sample('z', z_dist)\n            obs_.update({'z': z})\n            recon = pyro.poutine.condition(\n                self.sample, data=obs_)(batch_size)\n            recons += [recon['x']]\n        return torch.stack(recons).mean(0)\n\n    def _cf_dict(self, counterfactuals):\n        out = {k: [] for k in self.required_data}\n        for cf in counterfactuals:\n            for k in self.required_data:\n                out[k].append(cf[k])\n        out = {k: torch.stack(v).mean(0) for k, v in out.items()}\n        return out\n\n    @pyro_method\n    def counterfactual(self, obs, condition:Mapping=None, num_particles:int=1):\n        self._check_observation(obs)\n        obs_ = obs.copy()\n        z_dist = pyro.poutine.trace(self.guide).get_trace(obs_).nodes['z']['fn']  # variational posterior\n        n = obs_['x'].shape[0]\n\n        counterfactuals = []\n        for _ in range(num_particles):\n            z = pyro.sample('z', z_dist)\n            obs_.update(dict(z=z))\n            exogenous = self.infer_exogenous(obs_)\n            exogenous['z'] = z\n            # condition on these vars if they aren't included in 'do' as they are root nodes\n            # and we don't have the exogenous noise for them yet\n            if 'sex' not in condition.keys():\n                exogenous['sex'] = obs_['sex']\n            if 'slice_number' not in condition.keys():\n                exogenous['slice_number'] = obs_['slice_number']\n\n            cf = pyro.poutine.do(pyro.poutine.condition(self.sample_scm, data=exogenous), data=condition)(n)\n            counterfactuals.append(cf)\n\n        return self._cf_dict(counterfactuals)\n\n    @classmethod\n    def add_arguments(cls, parser):\n        parser = super().add_arguments(parser)\n        parser.add_argument('--latent-dim', default=100, type=int, help=\"latent dimension of model (default: %(default)s)\")\n        parser.add_argument('--prior-components', default=1, type=int, help=\"number of mixture components for prior (default: %(default)s)\")\n        parser.add_argument('--posterior-components', default=1, type=int, help=\"number of mixture components for posterior (default: %(default)s)\")\n        parser.add_argument('--logstd-init', default=-5, type=float, help=\"init/ref of logstd for fixed/learned (default: %(default)s)\")\n        parser.add_argument('--enc-filters', default=[16,32,64,128,256], nargs='+', type=int, help=\"number of filters in each layer of encoder (default: %(default)s)\")\n        parser.add_argument('--dec-filters', default=[256,128,64,32,16], nargs='+', type=int, help=\"number of filters in each layer of decoder (default: %(default)s)\")\n        parser.add_argument('--head-filters', default=[16], nargs='+', type=int, help=\"number of filters in each (mean/logstd) head (default: %(default)s)\")\n        parser.add_argument('--num-convolutions', default=3, type=int, help=\"number of convolutions in each layer (default: %(default)s)\")\n        parser.add_argument('--use-upconv', default=False, action='store_true', help=\"use upsample->conv instead of transpose conv (default: %(default)s)\")\n        parser.add_argument('--use-nvae', default=False, action='store_true', help=\"use nvae instead of standard vae (default: %(default)s)\")\n        parser.add_argument('--use-weight-norm', default=False, action='store_true', help=\"use weight norm in conv layers (not w/ nvae) (default: %(default)s)\")\n        parser.add_argument('--use-spectral-norm', default=False, action='store_true', help=\"use spectral norm in conv layers (not w/ nvae) (default: %(default)s)\")\n        parser.add_argument('--hierarchical-layers', default=(1,3,5), type=int, nargs='+', help=\"which filter layers are passed in hierarchical model (default: %(default)s)\")\n        parser.add_argument('--hierarchical-div', default=16, type=int, help=\"div factor in hierarchical model (default: %(default)s)\")\n        parser.add_argument('--temperature', default=2./3., type=float, help=\"temperature for ST Gumbel-softmax layers (default: %(default)s)\")\n        parser.add_argument('--laplace-likelihood', default=False, action='store_true', help=\"use laplace likelihood for image (default: %(default)s)\")\n        parser.add_argument('--n-prior-flows', default=3, type=int, help=\"use this number of flows for prior in flow net (default: %(default)s)\")\n        parser.add_argument('--n-posterior-flows', default=3, type=int, help=\"use this number of flows for posterior in flow net (default: %(default)s)\")\n        parser.add_argument('--use-autoregressive', default=False, action='store_true', help=\"use autoregressive flow for prior/post instead of coupling (default: %(default)s)\")\n        parser.add_argument('--use-spline', default=False, action='store_true', help=\"use spline flow for prior/post instead of affine (default: %(default)s)\")\n        parser.add_argument('--use-stable', default=False, action='store_true', help=\"use stable version of affine for prior/post instead (default: %(default)s)\")\n        parser.add_argument('--use-swish', default=False, action='store_true', help=\"use swish in flows for nonlinearity (default: %(default)s)\")\n        parser.add_argument('--pseudo3d', default=False, action='store_true', help=\"use pseudo3d images (default: %(default)s)\")\n        parser.add_argument(\n            '--decoder-type', default='fixed_var', help=\"var type (default: %(default)s)\",\n            choices=['fixed_var', 'learned_var', 'independent_var', 'sharedvar_multivariate_gaussian',\n                     'multivariate_gaussian', 'sharedvar_lowrank_multivariate_gaussian', 'lowrank_multivariate_gaussian'])\n        parser.add_argument('--decoder-cov-rank', default=10, type=int, help=\"rank for lowrank cov approximation (requires lowrank decoder) (default: %(default)s)\")  # noqa: E501\n        return parser\n\n\nclass SVIExperiment(BaseCovariateExperiment):\n    def __init__(self, hparams, pyro_model: BaseSEM):\n        super().__init__(hparams, pyro_model)\n        if hparams.tracegraph_elbo:\n            self.svi_loss = StorageTraceGraph_ELBO(num_particles=hparams.num_svi_particles)\n        else:\n            self.svi_loss = StorageTrace_ELBO(num_particles=hparams.num_svi_particles)\n        self._build_svi()\n\n    def _build_svi(self, loss=None):\n        def per_param_callable(module_name, param_name):\n            if self.hparams.use_adagrad_rmsprop:\n                params = {'eta': self.hparams.eta, 'delta': self.hparams.delta, 't': self.hparams.t}\n            else:\n                params = {'weight_decay': self.hparams.weight_decay,\n                          'betas': self.hparams.betas, 'eps': 1e-5}\n                if any([(pn in module_name) for pn in ('prior_flow', 'posterior_flow')]):\n                    params['lr'] = self.hparams.lr\n                elif 'affine' in module_name:\n                    params['lr'] = self.hparams.lr\n                    params['weight_decay'] = 0.\n                elif 'flow_components' in module_name:\n                    params['lr'] = self.hparams.pgm_lr\n                elif 'sex_logits' in param_name:\n                    params['lr'] = self.hparams.pgm_lr\n                    params['weight_decay'] = 0.\n                elif 'decoder' in module_name and 'logstd_head' in param_name:\n                    params['weight_decay'] = self.hparams.logstd_weight_decay\n                else:\n                    params['lr'] = self.hparams.lr\n                logger.info(f'building opt for {module_name} - {param_name} with p: {params}')\n            return params\n\n        def per_param_clip_args(module_name, param_name):\n            clip_args = defaultdict(lambda: None)\n            if any([(pn in module_name) for pn in ('prior_flow', 'posterior_flow')]):\n                clip_args['clip_norm'] = self.hparams.flow_clip_norm\n            elif any([(pn in param_name) for pn in ('affine', 'sex_logits', 'flow_components')]):\n                clip_args['clip_norm'] = self.hparams.pgm_clip_norm\n            else:\n                clip_args['clip_norm'] = self.hparams.clip_norm\n            logger.info(f'building clip args for {module_name} - {param_name} with p: {clip_args}')\n            return clip_args\n\n        if loss is None:\n            loss = self.svi_loss\n\n        optimizer = AdagradRMSProp if self.hparams.use_adagrad_rmsprop else AdamW\n        verbose = self.hparams.verbosity > 1  # only print lr in debug mode\n        if self.hparams.use_exponential_lr:\n            self.scheduler = ExponentialLR({'optimizer': optimizer, 'optim_args': per_param_callable,\n                                            'gamma': self.hparams.lrd, 'verbose': verbose},\n                                            clip_args=per_param_clip_args)\n        else:\n            self.scheduler = OneCycleLR({'optimizer': optimizer, 'optim_args': per_param_callable,\n                                         'epochs': self.hparams.n_epochs, 'steps_per_epoch': self._steps_per_epoch(),\n                                         'pct_start': self.hparams.pct_start, 'div_factor': self.hparams.div_factor,\n                                         'final_div_factor': self.hparams.final_div_factor, 'verbose': verbose},\n                                         clip_args=per_param_clip_args)\n        if self.hparams.use_cf_guide:\n            def guide(*args, **kwargs):\n                return self.pyro_model.counterfactual_guide(*args, **kwargs, counterfactual_type=self.hparams.cf_elbo_type)\n            self.svi = SVI(self.pyro_model.svi_model, guide, self.scheduler, loss)\n        else:\n            self.svi = SVI(self.pyro_model.svi_model, self.pyro_model.svi_guide, self.scheduler, loss)\n        self.svi.loss_class = loss\n\n    def backward(self, *args, **kwargs):\n        pass  # No loss to backpropagate since we're using Pyro's optimisation machinery\n\n    def print_trace_updates(self, batch):\n        with torch.no_grad():\n            logger.info('Traces:\\n' + ('#' * 10))\n\n            guide_trace = pyro.poutine.trace(self.pyro_model.svi_guide).get_trace(batch)\n            model_trace = pyro.poutine.trace(pyro.poutine.replay(self.pyro_model.svi_model, trace=guide_trace)).get_trace(batch)\n\n            guide_trace = pyro.poutine.util.prune_subsample_sites(guide_trace)\n            model_trace = pyro.poutine.util.prune_subsample_sites(model_trace)\n\n            model_trace.compute_log_prob()\n            guide_trace.compute_score_parts()\n\n            logging.info(f'model: {model_trace.nodes.keys()}')\n            for name, site in model_trace.nodes.items():\n                if site[\"type\"] == \"sample\":\n                    fn = site['fn']\n                    if isinstance(fn, Independent):\n                        fn = fn.base_dist\n                    try:\n                        logging.info(f'{name}: {fn} - {fn.support}')\n                    except NotImplementedError:\n                        logging.info(f'{name}: {fn}')\n                    log_prob_sum = site[\"log_prob_sum\"]\n                    is_obs = site[\"is_observed\"]\n                    logging.info(f'model - log p({name}) = {log_prob_sum} | obs={is_obs}')\n                    if torch.isnan(log_prob_sum):\n                        value = site['value'][0]\n                        conc0 = fn.concentration0\n                        conc1 = fn.concentration1\n                        raise RuntimeError(f'Error: \\n{value}\\n{conc0}\\n{conc1}')\n\n            logging.info(f'guide: {guide_trace.nodes.keys()}')\n\n            for name, site in guide_trace.nodes.items():\n                if site[\"type\"] == \"sample\":\n                    fn = site['fn']\n                    if isinstance(fn, Independent):\n                        fn = fn.base_dist\n                    try:\n                        logging.info(f'{name}: {fn} - {fn.support}')\n                    except NotImplementedError:\n                        logging.info(f'{name}: {fn}')\n                    entropy = site[\"score_parts\"].entropy_term.sum()\n                    is_obs = site[\"is_observed\"]\n                    logging.info(f'guide - log q({name}) = {entropy} | obs={is_obs}')\n\n    def get_trace_metrics(self, batch):\n        metrics = {}\n        model = self.svi.loss_class.trace_storage['model']\n        guide = self.svi.loss_class.trace_storage['guide']\n        for k in self.required_data:\n            metrics[f'log p({k})'] = model.nodes[k]['log_prob'].mean()\n        if self.pyro_model.n_levels > 0:\n            metrics['log p(z) - log q(z)'] = 0.\n            for i in range(self.pyro_model.n_levels):\n                metrics[f'log p(z{i})'] = model.nodes[f'z{i}']['log_prob'].mean()\n                metrics[f'log q(z{i})'] = guide.nodes[f'z{i}']['log_prob'].mean()\n                metrics['log p(z) - log q(z)'] += metrics[f'log p(z{i})'] - metrics[f'log q(z{i})']\n        else:\n            metrics['log p(z)'] = model.nodes['z']['log_prob'].mean()\n            metrics['log q(z)'] = guide.nodes['z']['log_prob'].mean()\n            metrics['log p(z) - log q(z)'] = metrics['log p(z)'] - metrics['log q(z)']\n        return metrics\n\n    def _theis_noise(self, obs):\n        \"\"\" add noise to discrete variables per Theis 2016 \"\"\"\n        if self.training:\n            obs['x'] += (torch.rand_like(obs['x']) - 0.5)\n            obs['slice_number'] += (torch.rand_like(obs['slice_number']) - 0.5)\n            obs['duration'] += torch.rand_like(obs['duration'] - 0.5)\n            obs['duration'].clamp_(min=1e-4)\n            obs['edss'] += ((torch.rand_like(obs['edss']) / 2.) - 0.25)\n            obs['edss'].clamp_(min=1e-4)\n        return obs\n\n    @property\n    def pseudo3d(self):\n        return self.pyro_model.pseudo3d\n\n    def prep_batch(self, batch):\n        x = 255. * batch['image'].float()  # multiply by 255 b/c preprocess tfms\n        out = dict(x=x)\n        for k in self.required_data:\n            if k in batch:\n                out[k] = batch[k].unsqueeze(1).float()\n        out = self._theis_noise(out)\n        return out\n\n    def _steps_per_epoch(self):\n        return len(self.calabresi_train) // self.train_batch_size  # integer div b/c drop_last used\n\n    def _set_annealing_factor(self, batch_idx=None):\n        steps_per_epoch = self._steps_per_epoch()\n        if batch_idx is None:\n            batch_idx = steps_per_epoch\n        not_in_sanity_check = self.hparams.annealing_epochs > 0\n        in_annealing_epochs = self.current_epoch < self.hparams.annealing_epochs\n        n_levels = max(self.pyro_model.n_levels, 1)\n        self.pyro_model.annealing_factor = [1. for _ in range(n_levels)]\n        for i in range(n_levels):\n            if not_in_sanity_check and in_annealing_epochs and self.training:\n                min_af = self.hparams.min_annealing_factor[i]\n                max_af = self.hparams.max_annealing_factor[i]\n                self.pyro_model.annealing_factor[i] = min_af + (max_af - min_af) * \\\n                                   (float(batch_idx + self.current_epoch * steps_per_epoch + 1) /\n                                    float(self.hparams.annealing_epochs * steps_per_epoch))\n            else:\n                self.pyro_model.annealing_factor[i] = self.hparams.max_annealing_factor[i]\n            if self.training:\n                self.log(f'annealing_factor/af{i}', self.pyro_model.annealing_factor[i],\n                         on_step=False, on_epoch=True)\n\n    def training_step(self, batch, batch_idx):\n        self._set_annealing_factor(batch_idx)\n        batch = self.prep_batch(batch)\n        if self.hparams.validate:\n            logging.info('Validation:')\n            self.print_trace_updates(batch)\n        loss = self.svi.step(batch)\n        self.scheduler.step()\n        loss = torch.as_tensor(loss)\n        self.log('train_loss', loss, on_step=False, on_epoch=True)\n        metrics = self.get_trace_metrics(batch)\n        if np.isnan(loss):\n            self.logger.experiment.add_text('nan', f'nand at {self.current_epoch}:\\n{metrics}')\n            raise ValueError('loss went to nan with metrics:\\n{}'.format(metrics))\n        for k, v in metrics.items():\n            self.log('train/' + k, v, on_step=False, on_epoch=True)\n        return loss\n\n    def validation_step(self, batch, batch_idx):\n        self._set_annealing_factor()\n        batch = self.prep_batch(batch)\n        loss = self.svi.evaluate_loss(batch)\n        self.log('val_loss', loss, on_step=False, on_epoch=True)\n        metrics = self.get_trace_metrics(batch)\n        for k, v in metrics.items():\n            self.log('val/' + k, v, on_step=False, on_epoch=True)\n        return metrics\n\n    def test_step(self, batch, batch_idx):\n        import nibabel as nib\n        self._set_annealing_factor()\n        subject = int(batch['subject'][0])\n        scan = int(batch['scan'][0])\n        batch = self.prep_batch(batch)\n        loss = self.svi.evaluate_loss(batch)\n        self.log('test_loss', loss, on_step=False, on_epoch=True)\n        metrics = self.get_trace_metrics(batch)\n        for k, v in metrics.items():\n            self.log('test/' + k, v, on_step=False, on_epoch=True)\n        samples = self.build_test_samples(batch)\n        for intervention, data in samples.items():\n            cf = data['x'].detach().cpu().numpy()\n            if self.hparams.pseudo3d:\n                cf = cf[:,1,...]  # get the middle slices\n            cf = cf.squeeze()\n            fn = os.path.join(self.hparams.test_dir, f'{subject}_{scan}_{intervention}.nii.gz')\n            nib.Nifti1Image(cf,None).to_filename(fn)\n        return {'samples': samples, 'metrics': metrics}\n\n    @classmethod\n    def add_arguments(cls, parser):\n        parser = super().add_arguments(parser)\n        parser.add_argument('--num-svi-particles', default=4, type=int, help=\"number of particles to use for ELBO (default: %(default)s)\")\n        parser.add_argument('--num-sample-particles', default=32, type=int, help=\"number of particles to use for MC sampling (default: %(default)s)\")\n        parser.add_argument('--use-cf-guide', default=False, action='store_true', help=\"whether to use counterfactual guide (default: %(default)s)\")\n        parser.add_argument(\n            '--cf-elbo-type', default=-1, choices=[-1, 0, 1, 2],\n            help=\"-1: randomly select per batch, 0: shuffle thickness, 1: shuffle intensity, 2: shuffle both (default: %(default)s)\")\n        parser.add_argument('--annealing-epochs', default=50, type=int, help=\"anneal kl div in z for this # epochs (default: %(default)s)\")\n        parser.add_argument('--min-annealing-factor', default=[0.2], type=float, nargs='+', help=\"anneal kl div in z starting here (per level for hierarchical) (default: %(default)s)\")\n        parser.add_argument('--max-annealing-factor', default=[1.0], type=float, nargs='+', help=\"anneal kl div in z ending here (per level for hierarchical) (default: %(default)s)\")\n        parser.add_argument('--tracegraph-elbo', default=False, action='store_true', help=\"use tracegraph elbo (much more computationally expensive) (default: %(default)s)\")\n        return parser\n\n\nEXPERIMENT_REGISTRY[SVIExperiment.__name__] = SVIExperiment\n", "meta": {"hexsha": "c32857f709a9db61093dc0dd5895350b8528c51d", "size": 40284, "ext": "py", "lang": "Python", "max_stars_repo_path": "counterfactualms/experiments/calabresi/base_sem_experiment.py", "max_stars_repo_name": "jcreinhold/counterfactualms", "max_stars_repo_head_hexsha": "9be5919c8885354fe1ac91c852d196969cfe16be", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2021-03-08T11:51:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T03:30:21.000Z", "max_issues_repo_path": "counterfactualms/experiments/calabresi/base_sem_experiment.py", "max_issues_repo_name": "jcreinhold/counterfactualms", "max_issues_repo_head_hexsha": "9be5919c8885354fe1ac91c852d196969cfe16be", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-10-03T15:20:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-03T15:20:30.000Z", "max_forks_repo_path": "counterfactualms/experiments/calabresi/base_sem_experiment.py", "max_forks_repo_name": "jcreinhold/counterfactualms", "max_forks_repo_head_hexsha": "9be5919c8885354fe1ac91c852d196969cfe16be", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-04-03T15:23:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-30T04:14:28.000Z", "avg_line_length": 54.3643724696, "max_line_length": 184, "alphanum_fraction": 0.649364512, "include": true, "reason": "import numpy", "num_tokens": 9295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.29421497835151617, "lm_q1q2_score": 0.17658440512657322}}
{"text": "# This script creates a yield table with CHEMPY (Rybizki et al. 2017) in numpy format and writes it in xdr file format.\n# Yield tables are 4 dimensional depending on: stellar age, stellar (total) metallicity, source (AGB, SNia, SNii) and elemental species.\n# \n# \n# table format:\n#\n# the general table format is as follows: A Header stating the structure of the table, the table body consisiting of N_z blocks \n# of Ns * Ne lines for every stellar metallicity and columns for the stellar age of the SSP (although in xdr format we do not really have new lines...)\n#\n# Header:     nuber of steps in stellar metallicity Z (N_z), number of steps in stellar age t (N_t), number of elemental species Ne, number of sources Ns\n# (no xdr    nSpecies, nSources\n# format)    Z_min, Zmax, dZ\n#             t_min=0, t_max=t_universe, dt (in log space to sample early stellar evolutionary phases better than late phases - see what Jan provides)\n#            list of strings denoting the elements, e.g. 'Ag', 'Al', 'Ba', 'C', 'Fe', 'He', 'Mg', 'N', 'Na', 'Ne', 'O', 'S', 'Si', 'Ti', 'Zn' (should have same length as Ne)\n#            write every element in a new line, makes it easier to read in in c.\n#\n# Table Body:     -------------> stellar age of SSP: N_t\n# (xdr format)   |SSP of Z_min:       Mass Loss, source 1\n#                |                    ...\n#                |                    Mass Loss, source Ns\n#                |                    Number of events, source 1\n#                |                    ...\n#                |                    Number of events, soure Ns\n#                |                    Element 1, source 1\n#                |                    Element 1, source 2\n#                |                    ...\n#                |                    Element 1, source Ns\n#                |                    ...\n#                |                    Element 2, source 1\n#                |                    ...\n#                |\n#                |                    Element Ne, source Ns\n#                |SSP of Z_min+dZ:    Mass loss, source 1\n#                |                    ...\n#                |                    Mass Loss, source Ns\n#                |                    Number of events\n#                |                    Element 1, source 1\n#                |                    ...\n#                |                    Element Ne, source Ns\n#                |                    ...\n#                |SSP of Z_max:       Mass Loss, source 1\n#                |                    ....\n#                |                    Element 1, source 1\n#                |                    ...\n#                |                    Element Ne, source Ns\n#       Z of SSP |\n#\n#\n# in fact, mass loss and unprocessed mass is the same.\n# caveat: SNIA yields are not metallicity dependent and unprocessed mass loss is 0, thus we only store the yields once at the lowest metallicity.\n# caveat: direct BH collapse returns only intial element fractions and happens before SNII so we combine the mass loss with SNII mass loss.\n\nimport numpy as np\nimport xdrlib\nimport numpy as np\nimport multiprocessing as mp\nimport os\n\n####### SETTING THE CHEMPY PARAMETER #######################\n\nfrom Chempy.parameter import ModelParameters\na = ModelParameters()\n\n# Load solar abundances\nfrom Chempy.solar_abundance import solar_abundances\nbasic_solar = solar_abundances()\ngetattr(basic_solar, 'Asplund09')()\n\n# Load the yields\nfrom Chempy.yields import SN2_feedback, AGB_feedback, SN1a_feedback\nbasic_sn2 = SN2_feedback()\ngetattr(basic_sn2, 'chieffi04_net')()\nbasic_1a = SN1a_feedback()\ngetattr(basic_1a, \"Seitenzahl\")()\nbasic_agb = AGB_feedback()\ngetattr(basic_agb, \"Karakas16_net\")()\n\n# Print all supported elements\nelements_to_trace = list(np.unique(basic_agb.elements+basic_sn2.elements+basic_1a.elements))\nprint(elements_to_trace)\n\n# Producing the SSP birth elemental fractions (here we use solar)\nsolar_fractions = []\nelements = np.hstack(basic_solar.all_elements)\nfor item in elements_to_trace:\n    solar_fractions.append(float(basic_solar.fractions[np.where(elements==item)]))\n\n# Initialise the SSP class with time-steps\ntime_steps = np.logspace(-2.44,1.139879,100) #np.linspace(0.,13.8,1024)\na.log_time = True\n\n# yieldset\na.yield_table_name_sn2 = 'chieffi04_net'\na.yield_table_name_agb = 'Karakas16_net'\na.yield_table_name_1a = 'Seitenzahl'\n\n# imf parameters\na.only_net_yields_in_process_tables = True\na.imf_type_name = 'Chabrier_1'\na.chabrier_para1 = 0.69\na.chabrier_para2 = 0.079\na.high_mass_slope = -2.3\na.imf_parameter = (a.chabrier_para1, a.chabrier_para2, a.high_mass_slope)\na.mmin = 0.1\na.mmax = 100\n# 100,000,000 mass steps are smooth enough for 1000 time steps\na.mass_steps = 1000000 #100000000 #2000 # 200000\na.sn2mmin = 8.\na.sn2mmax = 40.\na.bhmmin = float(a.sn2mmax) ## maximum of hypernova\na.bhmmax = float(a.mmax) ## maximum of the IMF\n\n# sn1a delay parameters for maoz\na.N_0 = np.power(10,-2.9)\na.sn1a_time_delay = np.power(10,-1.39794) #40 Myr\na.sn1a_exponent = 1.12\na.dummy = 0.0\na.sn1a_parameter = [a.N_0,a.sn1a_time_delay,a.sn1a_exponent,a.dummy]\n######################## END OF SETTING CHEMPY PARAMETER ########################\n\n######################## SETTING THE YIELDTABLE PARAMETERS ######################\nlist_of_metallicities = np.logspace(-5,-1.3,50)\n\nfrom Chempy.wrapper import SSP_wrap\n\ndef create_one_SSP_table_old(parameters, source='SNII'):\n    differential_table = True\n    metallicity = parameters\n    print(metallicity,a.yield_table_name_sn2)\n    basic_ssp = SSP_wrap(a)\n    basic_ssp.calculate_feedback(metallicity,list(elements_to_trace),list(solar_fractions),np.copy(time_steps),1)\n\n    x = basic_ssp.agb_table\n    y = basic_ssp.sn1a_table\n    z = basic_ssp.sn2_table\n    s = basic_ssp.bh_table\n    d = basic_ssp.table\n\n    u = np.zeros_like(x)\n    names = list(u.dtype.names)\n\n    for j,jtem in enumerate(names):\n        if source == 'SNII':\n            u[jtem] = z[jtem]\n        if source == 'SNIA':\n            u[jtem] = y[jtem]\n        if source == 'AGB':\n            u[jtem] = x[jtem]\n        if source == 'BH':\n            u[jtem] = s[jtem]\n        if source == 'ALL':\n            u[jtem] = x[jtem] + y[jtem] + z[jtem] + s[jtem]\n    if differential_table:\n        for el in elements_to_trace:\n            d[el] = u[el]\n    else:\n        for el in elements_to_trace:\n            d[el] = np.cumsum(u[el])\n        for name in ['mass_of_ms_stars_dying', 'mass_in_remnants', 'sn2', 'sn1a', 'pn', 'bh', 'hydrogen_mass_accreted_onto_white_dwarfs', 'unprocessed_ejecta']:\n            d[name] = np.cumsum(d[name])\n\n    return(d)\n\ndef create_one_SSP_table(parameters, source='SNII'):\n    metallicity = parameters\n    print(metallicity,a.yield_table_name_sn2)\n    basic_ssp = SSP_wrap(a)\n    basic_ssp.calculate_feedback(metallicity,list(elements_to_trace),list(solar_fractions),np.copy(time_steps),1)\n\n    x = basic_ssp.agb_table\n    y = basic_ssp.sn1a_table\n    z = basic_ssp.sn2_table\n    s = basic_ssp.bh_table\n    d = basic_ssp.table\n\n    if source == 'SNII':\n        return z\n    if source == 'SNIA':\n        return y\n    if source == 'AGB':\n        return x\n    if source == 'BH':\n        return s\n    if source == 'ALL':\n        u = np.zeros_like(x)\n        names = list(u.dtype.names)\n        for j,jtem in enumerate(names):\n            u[jtem] = x[jtem] + y[jtem] + z[jtem] + s[jtem]\n        return u\n\ndef my_wrap_AGB_table(parameters):\n    return create_one_SSP_table(parameters, source='AGB')\n\ndef my_wrap_SNIA_table(parameters):\n    return create_one_SSP_table(parameters, source='SNIA')\n\ndef my_wrap_SNII_table(parameters):\n    return create_one_SSP_table(parameters, source='SNII')\n\ndef my_wrap_BH_table(parameters):\n    return create_one_SSP_table(parameters, source='BH')\n\n########## END OF SETTING YIELD TABLE PARAMETERS ################\n\n# Call the SSP table creation routine\nprint('This python script reads a numpy file created with chempy to transform it to xdr file format to be read in by Gasoline!')\n\nprint(\"There are %d CPUs on this machine\" % mp.cpu_count())\nnumber_processes = max(1,20)# mp.cpu_count() - 1)\nprint(\"Using %d of them.\", number_processes)\n\nfile = 'chempy_table_agb'\nif not os.path.isfile(file+'.npy'):\n    ############ CREATING THE ACTUAL TABLES ####################\n    list_of_SSP_tables = []\n    list_of_SSP_tables.append(list_of_metallicities)\n    list_of_SSP_tables.append(time_steps)\n    pool = mp.Pool(number_processes)\n    results = pool.map(my_wrap_AGB_table, list_of_metallicities)\n    pool.close()\n    pool.join()\n    list_of_SSP_tables.append(results)\n    np.save(file, list_of_SSP_tables)\n\n    list_of_SSP_tables = []\n    list_of_SSP_tables.append(list_of_metallicities)\n    list_of_SSP_tables.append(time_steps)\n    pool = mp.Pool(number_processes)\n    results = pool.map(my_wrap_SNIA_table, list_of_metallicities)\n    pool.close()\n    pool.join()\n    list_of_SSP_tables.append(results)\n    np.save('chempy_table_snia', list_of_SSP_tables)\n\n    list_of_SSP_tables = []\n    list_of_SSP_tables.append(list_of_metallicities)\n    list_of_SSP_tables.append(time_steps)\n    pool = mp.Pool(number_processes)\n    results = pool.map(my_wrap_SNII_table, list_of_metallicities)\n    pool.close()\n    pool.join()\n    list_of_SSP_tables.append(results)\n    np.save('chempy_table_snii', list_of_SSP_tables)\n\n    list_of_SSP_tables = []\n    list_of_SSP_tables.append(list_of_metallicities)\n    list_of_SSP_tables.append(time_steps)\n    pool = mp.Pool(number_processes)\n    results = pool.map(my_wrap_BH_table, list_of_metallicities)\n    pool.close()\n    pool.join()\n    list_of_SSP_tables.append(results)\n    np.save('chempy_table_bh', list_of_SSP_tables)\n\n\n############### DOING THE EXPORT TO XDR FORMAT ######################\n# import yield table created with chempy\nprint('Reading chempy yield table...')\nyield_table_agb = np.load('chempy_table_agb.npy')\nyield_table_snIa = np.load('chempy_table_snia.npy')\nyield_table_snII = np.load('chempy_table_snii.npy')\nyield_table_bh = np.load('chempy_table_bh.npy')\n\nyield_sn2 = 'chieffi+04'\nyield_snia = 'seitenzahl+13'\nyield_agb = 'karakas+16'\n\n# get parameters from yield table\nN_Z = len(yield_table_snII[0])\nN_t = len(yield_table_snII[1])\nN_e = len(elements_to_trace) #len(yield_table_snII[2][1][0])-9 #change length of elements once final yield table is there\n\nZmin = yield_table_snII[0][0]\nZmax = yield_table_snII[0][len(yield_table_snII[0])-1]\ndZ = np.log10(yield_table_snII[0][1])-np.log10(yield_table_snII[0][0])\n\ntmin = yield_table_snII[1][0]*1e9\ntmax = yield_table_snII[1][len(yield_table_snII[1])-1]*1e9\ndt = np.log10(yield_table_snII[1][1])-np.log10(yield_table_snII[1][0])\n\n# open new xdr file\nxdr_table = open(\"yieldtable_xdr_high_Ia_norm\",\"wb\")\n\n# initialize packing\np = xdrlib.Packer()\n\n# wirte Header\nprint('Writing Header, stating information about metallicity steps, timesteps and number of elements and sources.')\n\nxdr_table.write(b'###################################################################################\\n')\n#xdr_table.write(b'\\n')\nxdr_table.write(b'###   Yield table created with CHEMPY (https://github.com/jan-rybizki/Chempy)   ###\\n')\n#xdr_table.write(b'\\n')\nxdr_table.write(b'###               using the write_yield_lookup_table.py script.                 ###\\n')\n#xdr_table.write(b'\\n')\nxdr_table.write(b'###                Tobias Buck (tbuck@aip.de) in February 2021.                 ###\\n')\n#xdr_table.write(b'\\n')\nxdr_table.write(b'###################################################################################\\n')\n\n# here should go which yield sets we use.\n# We should actually add all chempy paramters, like e.g. IMF and SNIA delay time parameters.\n# In this way the yieldtable is self-consistent.\n\nyieldsets = b'SNII, SNIA and AGB yieldsets used: %s\\t %s\\t %s\\n'%(a.yield_table_name_sn2.encode('latin-1'),a.yield_table_name_1a.encode('latin-1'),a.yield_table_name_agb.encode('latin-1')) #(yield_sn2,yield_snia,yield_agb)\nxdr_table.write(yieldsets)\n\nimf = b'IMF parameters used: type: %s (%.3f,%.3f,%.3f)\\t IMF min/max mass: %.2f/%.2f\\t SN min/max mass: %.1f/%.1f\\n'%(a.imf_type_name.encode('latin-1'),a.chabrier_para1,a.chabrier_para2,a.high_mass_slope,a.mmin,a.mmax,a.sn2mmin,a.sn2mmax)\nxdr_table.write(imf)\n\nsnia = b'SNIA parameters used: type: Maoz+2012, normalization: %.3f\\t delay time (Myr): %.2f\\t exponent: %.2f\\n'%(a.N_0,a.sn1a_time_delay,a.sn1a_exponent)\nxdr_table.write(snia)\n\nfirstline = b'%i %i %i 3\\n'%(N_Z, N_t, N_e)\nxdr_table.write(firstline)\n\nsecondline = b'%E %E %E\\n'%(Zmin, Zmax, dZ)\nxdr_table.write(secondline)\n\nthirdline = b'%E %E %E\\n'%(tmin, tmax, dt)\nxdr_table.write(thirdline)\n\n#SNIA do not eject unprocessed material calculate the massloss from the newly synthesized fraction\n\nfor elem in elements_to_trace: #yield_table_snII[2][0].dtype.names[4:]:\n    element = b'%s\\t'%(elem.encode('latin-1'))\n    xdr_table.write(element)\n    yield_table_snIa[2][0]['unprocessed_ejecta'] += yield_table_snIa[2][0][elem]\nxdr_table.write(b'\\n')\n\nprint('Packing data to xdr format.')\n\nfor i in range(N_Z):\n    #step through all metallicity bins\n    #combine massloss from direct BH collapse with SNII mass loss\n    yield_table_snII[2][i][\"unprocessed_ejecta\"] += yield_table_bh[2][i][\"unprocessed_ejecta\"]\n\n    if i == 0:\n        # at the lowest Z bin include the SNIA yields\n        #p.pack_farray(N_t,np.cumsum(yield_table_snII[2][i]['mass_of_ms_stars_dying']) - np.cumsum(yield_table_snII[2][i]['mass_in_remnants']),p.pack_double)\n        p.pack_farray(N_t,np.cumsum(yield_table_snII[2][i]['unprocessed_ejecta']),p.pack_double)\n        p.pack_farray(N_t,np.cumsum(yield_table_snIa[2][i]['unprocessed_ejecta']),p.pack_double)\n        p.pack_farray(N_t,np.cumsum(yield_table_agb[2][i]['unprocessed_ejecta']),p.pack_double)\n        p.pack_farray(N_t,np.cumsum(yield_table_snII[2][i]['number_of_events']),p.pack_double)\n        p.pack_farray(N_t,np.cumsum(yield_table_snIa[2][i]['number_of_events']),p.pack_double)\n        p.pack_farray(N_t,np.cumsum(yield_table_agb[2][i]['number_of_events']),p.pack_double)\n        for elem in elements_to_trace: #yield_table_snII[2][0].dtype.names[4:]:\n            # step through all elements\n            # and finally step also through all sources once we have them...\n            p.pack_farray(N_t,np.cumsum(yield_table_snII[2][i][elem]),p.pack_double)\n            p.pack_farray(N_t,np.cumsum(yield_table_snIa[2][i][elem]),p.pack_double)\n            p.pack_farray(N_t,np.cumsum(yield_table_agb[2][i][elem]),p.pack_double)\n    else:\n        # now only SNII and AGB\n        #p.pack_farray(N_t,np.cumsum(yield_table_snII[2][i]['mass_of_ms_stars_dying']) - np.cumsum(yield_table_snII[2][i]['mass_in_remnants']),p.pack_double)\n        p.pack_farray(N_t,np.cumsum(yield_table_snII[2][i]['unprocessed_ejecta']),p.pack_double)\n        p.pack_farray(N_t,np.cumsum(yield_table_agb[2][i]['unprocessed_ejecta']),p.pack_double)\n        p.pack_farray(N_t,np.cumsum(yield_table_snII[2][i]['number_of_events']),p.pack_double)\n        #p.pack_farray(N_t,np.cumsum(yield_table_snII[2][i]['sn1a']),p.pack_double)\n        p.pack_farray(N_t,np.cumsum(yield_table_agb[2][i]['number_of_events']),p.pack_double)\n        for elem in elements_to_trace: #yield_table_snII[2][0].dtype.names[4:]:\n            # step through all elements\n            # and finally step also through all sources once we have them...\n            p.pack_farray(N_t,np.cumsum(yield_table_snII[2][i][elem]),p.pack_double)\n            #p.pack_farray(N_t,np.cumsum(yield_table_snIa[2][i][elem]),p.pack_double)\n            p.pack_farray(N_t,np.cumsum(yield_table_agb[2][i][elem]),p.pack_double)\n\nprint('Writing xdr part.')\n#xdr_table.write(p.get_buffer())\n\nxdr_table.write(p.get_buffer())\n\nxdr_table.close()\n\n\n\n\n\n", "meta": {"hexsha": "7ada539426051e7ae3462591462ab28c92120cbd", "size": 15694, "ext": "py", "lang": "Python", "max_stars_repo_path": "write_yield_lookup_table.py", "max_stars_repo_name": "TobiBu/chemical_enrichment", "max_stars_repo_head_hexsha": "6428d7074991162ddca1034da880e3116c6e61c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "write_yield_lookup_table.py", "max_issues_repo_name": "TobiBu/chemical_enrichment", "max_issues_repo_head_hexsha": "6428d7074991162ddca1034da880e3116c6e61c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "write_yield_lookup_table.py", "max_forks_repo_name": "TobiBu/chemical_enrichment", "max_forks_repo_head_hexsha": "6428d7074991162ddca1034da880e3116c6e61c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5185185185, "max_line_length": 238, "alphanum_fraction": 0.6478909137, "include": true, "reason": "import numpy", "num_tokens": 4403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.1765518364847722}}
{"text": "#!/usr/bin/env python\n\"\"\"\nThis module contains functions and class definitions for running forward\nmodels of models based on logistic regression.\n\"\"\"\n\n# stdlib imports\nimport numpy as np\nimport os.path\nimport re\nimport collections\nimport copy\n# from scipy import sparse\nimport shutil\nimport tempfile\nfrom timeit import default_timer as timer\n\n# third party imports\nfrom mapio.shake import ShakeGrid\nfrom mapio.shake import getHeaderData\nfrom mapio.gmt import GMTGrid\nfrom mapio.gdal import GDALGrid\nfrom mapio.grid2d import Grid2D\nfrom mapio.geodict import GeoDict\n\nfrom gfail.temphdf import TempHdf\nfrom gfail.spatial import quickcut, trim_ocean\n\n# temporary until mapio is updated\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\nPARAM_PATTERN = 'b[0-9]+'\nLAYER_PATTERN = '_layer'\nTERM_PATTERN = 'term'\n\nSM_TERMS = ['MW', 'YEAR', 'MONTH', 'DAY', 'HOUR', 'pga', 'pgv', 'mmi']\nSM_GRID_TERMS = ['pga', 'pgv', 'mmi']\n# these will get np. prepended\nOPERATORS = ['log', 'log10', 'arctan', 'power', 'sqrt', 'minimum', 'pi']\nFLOATPAT = '[+-]?(?=\\d*[.eE])(?=\\.?\\d)\\d*\\.?\\d*(?:[eE][+-]?\\d+)?'\nINTPAT = '[0-9]+'\nOPERATORPAT = '[\\+\\-\\*\\/]*'\nMONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',\n          'Nov', 'Dec']\n\n\nclass LogisticModel(object):\n    def __init__(self, shakefile, config, uncertfile=None, saveinputs=False,\n                 slopefile=None, bounds=None, numstd=1, slopemod=None,\n                 trimfile=None):\n        \"\"\"\n        Sets up the logistic model\n\n        Args:\n            shakefile (str): Path to shakemap grid.xml file for the event.\n            config: configobj object defining the model and its inputs. Only\n                one model should be described in each config file.\n            uncertfile (str): Path to uncertainty.xml file.\n            saveinputs (bool): Save input layers as Grid2D objects in addition\n                to the model? If false (the default), it will just output the\n                model.\n            slopefile (str): Optional path to slopefile that will be resampled\n                to the other input files for applying thresholds. OVERWRITES\n                VALUE IN CONFIG.\n            bounds (dict): Default of None uses ShakeMap boundaries, otherwise\n                a dictionary of boundaries to cut to like\n\n                .. code-block:: python\n\n                    bounds = {\n                        'xmin': lonmin, 'xmax': lonmax,\n                        'ymin': latmin, 'ymax': latmax\n                    }\n\n            numstd (float): Number of +/- standard deviations to use if\n                uncertainty is computed.\n            slopemod (str): How slope input should be modified to be in\n                degrees: e.g., ``np.arctan(slope) * 180. / np.pi`` or\n                ``slope/100.`` (note that this may be in the config file\n                already).\n            trimfile (str): shapefile of earth's landmasses to use to cut\n                offshore areas.\n        \"\"\"\n        mnames = getLogisticModelNames(config)\n        if len(mnames) == 0:\n            raise Exception('No config file found or problem with config '\n                            'file format')\n        if len(mnames) > 1:\n            raise Exception('Config file contains more than one model which '\n                            'is no longer allowed, update your config file '\n                            'to the newer format')\n\n        self.model = mnames[0]\n        self.config = config\n        cmodel = config[self.model]\n        self.modeltype = cmodel['gfetype']\n        self.coeffs = validateCoefficients(cmodel)\n        # key = layer name, value = file name\n        self.layers = validateLayers(cmodel)\n        self.terms, timeField = validateTerms(cmodel, self.coeffs, self.layers)\n        self.interpolations = validateInterpolations(cmodel, self.layers)\n        self.units = validateUnits(cmodel, self.layers)\n        self.gmused = [value for term, value in cmodel['terms'].items()\n                       if 'pga' in value.lower() or 'pgv' in\n                       value.lower() or 'mmi' in value.lower()]\n        self.modelrefs, self.longrefs, self.shortrefs = validateRefs(cmodel)\n        self.numstd = numstd\n        self.clips = validateClips(cmodel, self.layers, self.gmused)\n\n        if cmodel['baselayer'] not in list(self.layers.keys()):\n            raise Exception('You must specify a base layer corresponding to '\n                            'one of the files in the layer section.')\n        self.saveinputs = saveinputs\n        if slopefile is None:\n            try:\n                self.slopefile = cmodel['slopefile']\n            except:\n                # print('Slopefile not specified in config, no slope '\n                #      'thresholds will be applied\\n')\n                self.slopefile = None\n        else:\n            self.slopefile = slopefile\n        if slopemod is None:\n            try:\n                self.slopemod = cmodel['slopemod']\n            except:\n                self.slopemod = None\n\n        # See if trimfile exists\n        if trimfile is not None:\n            if not os.path.exists(trimfile):\n                print(\n                    'trimfile defined does not exist: %s\\nOcean will not be trimmed' % trimfile)\n                self.trimfile = None\n            elif os.path.splitext(trimfile)[1] != '.shp':\n                print('trimfile must be a shapefile, ocean will not be trimmed')\n                self.trimfile = None\n            else:\n                self.trimfile = trimfile\n        else:\n            self.trimfile = None\n\n        # Get month of event\n        griddict, eventdict, specdict, fields, uncertainties = \\\n            getHeaderData(shakefile)\n        MONTH = MONTHS[(eventdict['event_timestamp'].month) - 1]\n\n        # Figure out how/if need to cut anything\n        geodict = ShakeGrid.getFileGeoDict(shakefile, adjust='res')\n        if bounds is not None:  # Make sure bounds are within ShakeMap Grid\n            if (geodict.xmin > bounds['xmin'] or\n                    geodict.xmax < bounds['xmax'] or\n                    geodict.ymin > bounds['ymin'] or\n                    geodict.ymax < bounds['ymax']):\n                print('Specified bounds are outside shakemap area, using '\n                      'ShakeMap bounds instead.')\n                bounds = None\n        if bounds is not None:\n            tempgdict = GeoDict.createDictFromBox(\n                bounds['xmin'], bounds['xmax'],\n                bounds['ymin'], bounds['ymax'],\n                geodict.dx, geodict.dy, inside=False)\n            gdict = geodict.getBoundsWithin(tempgdict)\n        else:\n            gdict = geodict\n\n        # Now find the layer that is our base layer and get the largest bounds\n        # we can guarantee not to exceed shakemap bounds\n        basefile = self.layers[cmodel['baselayer']]\n        ftype = getFileType(basefile)\n        if ftype == 'esri':\n            basegeodict, firstcol = GDALGrid.getFileGeoDict(basefile)\n            if basegeodict == gdict:\n                sampledict = gdict\n            else:\n                sampledict = basegeodict.getBoundsWithin(gdict)\n        elif ftype == 'gmt':\n            basegeodict, firstcol = GMTGrid.getFileGeoDict(basefile)\n            if basegeodict == gdict:\n                sampledict = gdict\n            else:\n                sampledict = basegeodict.getBoundsWithin(gdict)\n        else:\n            raise Exception('All predictor variable grids must be a valid '\n                            'GMT or ESRI file type.')\n\n        # Do we need to subdivide baselayer?\n        if 'divfactor' in self.config[self.model].keys():\n            divfactor = float(self.config[self.model]['divfactor'])\n            if divfactor != 1.:\n                # adjust sampledict so everything will be resampled\n                newxmin = sampledict.xmin - sampledict.dx / \\\n                    2. + sampledict.dx/(2.*divfactor)\n                newymin = sampledict.ymin - sampledict.dy / \\\n                    2. + sampledict.dy/(2.*divfactor)\n                newxmax = sampledict.xmax + sampledict.dx / \\\n                    2. - sampledict.dx/(2.*divfactor)\n                newymax = sampledict.ymax + sampledict.dy / \\\n                    2. - sampledict.dy/(2.*divfactor)\n                newdx = sampledict.dx/divfactor\n                newdy = sampledict.dy/divfactor\n\n                sampledict = GeoDict.createDictFromBox(\n                    newxmin, newxmax, newymin,\n                    newymax, newdx, newdy, inside=True)\n\n        # Find slope thresholds, if applicable\n        self.slopemin = 'none'\n        self.slopemax = 'none'\n        if slopefile is not None:\n            try:\n                self.slopemin = float(config[self.model]['slopemin'])\n                self.slopemax = float(config[self.model]['slopemax'])\n            except:\n                print('Could not find slopemin and/or slopemax in config, '\n                      'limits. No slope thresholds will be applied.')\n                self.slopemin = 'none'\n                self.slopemax = 'none'\n\n        # Make temporary directory for hdf5 pytables file storage\n        self.tempdir = tempfile.mkdtemp()\n\n        # now load the shakemap, resampling and padding if necessary\n        temp = ShakeGrid.load(shakefile)  # , adjust='res')\n        self.shakedict = temp.getShakeDict()\n        self.eventdict = temp.getEventDict()\n        self.shakemap = {}\n\n        # Read both PGA and PGV in, may need them for thresholds\n        for gm in ['pga', 'pgv']:\n            junkfile = os.path.join(self.tempdir, 'temp.bil')\n            GDALGrid.copyFromGrid(temp.getLayer(gm)).save(junkfile)\n            if gm in self.interpolations.keys():\n                intermeth = self.interpolations[gm]\n            else:\n                intermeth = 'bilinear'\n            junkgrid = quickcut(junkfile, sampledict, precise=True,\n                                method=intermeth)\n            if gm in self.clips:\n                junkgrid.setData(np.clip(junkgrid.getData(),\n                                         self.clips[gm][0], self.clips[gm][1]))\n            self.shakemap[gm] = TempHdf(\n                junkgrid, os.path.join(self.tempdir, '%s.hdf5' % gm))\n            os.remove(junkfile)\n        del(temp)\n\n        # get updated geodict\n        sampledict = junkgrid.getGeoDict()\n\n        # take uncertainties into account, if available\n        if uncertfile is not None:\n            self.uncert = {}\n            try:\n                # Only read in the ones that will be needed\n                temp = ShakeGrid.load(uncertfile)\n                for gm in self.gmused:\n                    if 'pgv' in gm:\n                        gmsimp = 'pgv'\n                    elif 'pga' in gm:\n                        gmsimp = 'pga'\n                    elif 'mmi' in gm:\n                        gmsimp = 'mmi'\n                    junkfile = os.path.join(self.tempdir, 'temp.bil')\n                    GDALGrid.copyFromGrid(temp.getLayer(\n                        'std%s' % gmsimp)).save(junkfile)\n                    if gmsimp in self.interpolations.keys():\n                        intermeth = self.interpolations[gmsimp]\n                    else:\n                        intermeth = 'bilinear'\n                    junkgrid = quickcut(junkfile, sampledict, precise=True,\n                                        method=intermeth)\n                    if gmsimp in self.clips:\n                        junkgrid.setData(\n                            np.clip(junkgrid.getData(), self.clips[gmsimp][0],\n                                    self.clips[gmsimp][1]))\n                    self.uncert['std' + gmsimp] = TempHdf(\n                        junkgrid, os.path.join(self.tempdir,\n                                               'std%s.hdf5' % gmsimp))\n                    os.remove(junkfile)\n                del(temp)\n            except:\n                print('Could not read uncertainty file, ignoring '\n                      'uncertainties')\n                self.uncert = None\n        else:\n            self.uncert = None\n\n        # Load the predictor layers, save as hdf5 temporary files, put file\n        # locations into a dictionary.\n\n        # Will be replaced in the next section if a slopefile was defined\n        self.nonzero = None\n\n        # key = layer name, value = grid object\n        self.layerdict = {}\n\n        didslope = False\n        for layername, layerfile in self.layers.items():\n            start = timer()\n            if isinstance(layerfile, list):\n                for lfile in layerfile:\n                    if timeField == 'MONTH':\n                        if lfile.find(MONTH) > -1:\n                            layerfile = lfile\n                            ftype = getFileType(layerfile)\n                            interp = self.interpolations[layername]\n                            temp = quickcut(layerfile, sampledict,\n                                            precise=True, method=interp)\n                            if layername in self.clips:\n                                temp.setData(\n                                    np.clip(temp.getData(),\n                                            self.clips[layername][0],\n                                            self.clips[layername][1]))\n                            self.layerdict[layername] = TempHdf(\n                                temp, os.path.join(self.tempdir,\n                                                   '%s.hdf5' % layername))\n                            del(temp)\n            else:\n                interp = self.interpolations[layername]\n                temp = quickcut(layerfile, sampledict,\n                                precise=True, method=interp)\n                if layername in self.clips:\n                    temp.setData(\n                        np.clip(temp.getData(),\n                                self.clips[layername][0],\n                                self.clips[layername][1]))\n                self.layerdict[layername] = TempHdf(\n                    temp, os.path.join(self.tempdir, '%s.hdf5' % layername))\n                td = temp.getGeoDict()\n                if td != sampledict:\n                    raise Exception(\n                        'Geodictionaries of resampled files do not match')\n\n                if layerfile == self.slopefile:\n                    flag = 0\n                    if self.slopemin == 'none' and self.slopemax == 'none':\n                        flag = 1\n                    if self.slopemod is None:\n                        slope1 = temp.getData().astype(float)\n                        slope = 0\n                    else:\n                        try:\n                            slope = temp.getData().astype(float)\n                            slope1 = eval(self.slopemod)\n                        except:\n                            print('slopemod provided not valid, continuing '\n                                  'without slope thresholds.')\n                            flag = 1\n                    if flag == 0:\n                        nonzero = np.array(\n                            [(slope1 > self.slopemin) &\n                             (slope1 <= self.slopemax)])\n                        self.nonzero = nonzero[0, :, :]\n                        del(slope1)\n                        del(slope)\n                    else:\n                        # Still remove areas where the slope equals exactly\n                        # 0.0 to remove offshore liq areas.\n                        nonzero = np.array([slope1 != 0.0])\n                        self.nonzero = nonzero[0, :, :]\n                        del(slope1)\n                    didslope = True\n                del(temp)\n\n            print('Loading %s layer: %1.1f sec'\n                  % (layername, timer() - start))\n\n        if didslope is False and self.slopefile is not None:\n            # Slope didn't get read in yet\n            temp = quickcut(self.slopefile, sampledict, precise=True,\n                            method='bilinear')\n            flag = 0\n            if self.slopemin == 'none' and self.slopemax == 'none':\n                flag = 1\n            if self.slopemod is None:\n                slope1 = temp.getData().astype(float)\n                slope = 0\n            else:\n                try:\n                    slope = temp.getData().astype(float)\n                    slope1 = eval(self.slopemod)\n                except:\n                    print('slopemod provided not valid, continuing without '\n                          'slope thresholds')\n                    flag = 1\n            if flag == 0:\n                nonzero = np.array([(slope1 > self.slopemin) &\n                                    (slope1 <= self.slopemax)])\n                self.nonzero = nonzero[0, :, :]\n                del(slope1)\n                del(slope)\n            else:\n                # Still remove areas where the slope equals exactly\n                # 0.0 to remove offshore liq areas.\n                nonzero = np.array([slope1 != 0.0])\n                self.nonzero = nonzero[0, :, :]\n                del(slope1)\n\n        self.nuggets = [str(self.coeffs['b0'])]\n\n        ckeys = list(self.terms.keys())\n        ckeys.sort()\n        for key in ckeys:\n            term = self.terms[key]\n            coeff = self.coeffs[key]\n            self.nuggets.append('(%g * %s)' % (coeff, term))\n\n        self.equation = ' + '.join(self.nuggets)\n\n        if self.uncert is not None:\n            self.nugmin = copy.copy(self.nuggets)\n            self.nugmax = copy.copy(self.nuggets)\n\n            # Find the term with the shakemap input and replace for these\n            # nuggets.\n            for gm in ['pga', 'mmi', 'pgv']:\n                for k, nug in enumerate(self.nuggets):\n                    tempnug = (\"self.shakemap['%s'].getSlice(rowstart, \"\n                               \"rowend, colstart, colend, name='%s')\"\n                               % (gm, gm))\n                    if tempnug in nug:\n                        newnug = (\"np.exp(np.log(%s) - self.numstd * \"\n                                  \"self.uncert['std%s'].getSlice(rowstart, \"\n                                  \"rowend, colstart, colend, name='std%s'))\"\n                                  % (tempnug, gm, gm))\n                        self.nugmin[k] = self.nugmin[k].replace(\n                            tempnug, newnug)\n                        newnug = (\"np.exp(np.log(%s) + self.numstd * \"\n                                  \"self.uncert['std%s'].getSlice(rowstart, \"\n                                  \"rowend, colstart, colend, name='std%s'))\"\n                                  % (tempnug, gm, gm))\n                        self.nugmax[k] = self.nugmax[k].replace(\n                            tempnug, newnug)\n\n            self.equationmin = ' + '.join(self.nugmin)\n            self.equationmax = ' + '.join(self.nugmax)\n        else:\n            self.equationmin = None\n            self.equationmax = None\n\n        self.geodict = sampledict\n\n    def getEquations(self):\n        \"\"\"\n        Method for LogisticModel class to extract strings defining the\n        equations for the model for median ground motions and +/- one standard\n        deviation (3 total).\n\n        Returns:\n            tuple: (equation, equationmin, equationmax) where:\n                * equation: the equation for median ground motions,\n                * equationmin: the equation for the same model but using\n                  median ground motions minus 1 standard deviation\n                * equationmax: same as above but for plus 1 standard deviation.\n        \"\"\"\n        return self.equation, self.equationmin, self.equationmax\n\n    def getGeoDict(self):\n        \"\"\"\n        Returns the geodictionary of the LogisticModel class defining bounds\n        and resolution of model inputs and outputs.\n\n        Returns:\n            geodict: mapio geodict object\n        \"\"\"\n        return self.geodict\n\n    def calculate(self, cleanup=True, rowmax=300, colmax=None):\n        \"\"\"\n        Calculate the model.\n\n        Args:\n            cleanup (bool): If True, delete temporary hdf5 files\n            rowmax (int): Number of rows to compute at once; If None, all rows\n                will be computed at once.\n            colmax (int): Number of columns to compute at once; If None, all\n                columns will be computed at once.\n        Returns:\n            dict: Dictionary containing the model results (and model inputs if\n            saveinputs was set to True). See\n            `the description <https://github.com/usgs/groundfailure#api-for-model-output>`_\n            of the structure.\n        \"\"\"\n        tk = list(self.shakemap.keys())[0]\n        # Figure out what slices to do\n        rowstarts, rowends, colstarts, colends = \\\n            self.shakemap[tk].getSliceDiv(rowmax, colmax)\n\n        # Make empty matrix to fill\n        X = np.empty([self.geodict.ny, self.geodict.nx])\n\n        # Loop through slices, appending output each time\n        for rowstart, rowend, colstart, colend in \\\n                zip(rowstarts, rowends, colstarts, colends):\n            X[rowstart:rowend, colstart:colend] = eval(self.equation)\n\n        P = 1/(1 + np.exp(-X))\n\n        if 'vs30max' in self.config[self.model].keys():\n            vs30 = self.layerdict['vs30'].getSlice(\n                None, None, None, None, name='vs30')\n            P[vs30 > float(self.config[self.model]['vs30max'])] = 0.0\n\n        if 'minpgv' in self.config[self.model].keys():\n            pgv = self.shakemap['pgv'].getSlice(\n                None, None, None, None, name='pgv')\n            P[pgv < float(self.config[self.model]['minpgv'])] = 0.0\n\n        if 'minpga' in self.config[self.model].keys():\n            pga = self.shakemap['pga'].getSlice(\n                None, None, None, None, name='pga')\n            P[pga < float(self.config[self.model]['minpga'])] = 0.0\n\n        if 'coverage' in self.config[self.model].keys():\n            eqn = self.config[self.model]['coverage']['eqn']\n            P = eval(eqn)\n\n        if self.uncert is not None:\n            # Make empty matrix to fill\n            Xmin = np.empty([self.geodict.ny, self.geodict.nx])\n            Xmax = Xmin.copy()\n            # Loop through slices, appending output each time\n            for rowstart, rowend, colstart, colend in \\\n                    zip(rowstarts, rowends, colstarts, colends):\n                Xmin[rowstart:rowend, colstart:colend] = eval(self.equationmin)\n                Xmax[rowstart:rowend, colstart:colend] = eval(self.equationmax)\n\n            Pmin = 1/(1 + np.exp(-Xmin))\n            Pmax = 1/(1 + np.exp(-Xmax))\n\n            if 'vs30max' in self.config[self.model].keys():\n                vs30 = self.layerdict['vs30'].getSlice(\n                    None, None, None, None, name='vs30')\n                Pmin[vs30 > float(self.config[self.model]['vs30max'])] = 0.0\n                Pmax[vs30 > float(self.config[self.model]['vs30max'])] = 0.0\n\n            if 'minpgv' in self.config[self.model].keys():\n                pgv = self.shakemap['pgv'].getSlice(\n                    None, None, None, None, name='pgv')\n                Pmin[pgv < float(self.config[self.model]['minpgv'])] = 0.0\n                Pmax[pgv < float(self.config[self.model]['minpgv'])] = 0.0\n\n            if 'minpga' in self.config[self.model].keys():\n                pga = self.shakemap['pgv'].getSlice(\n                    None, None, None, None, name='pga')\n                Pmin[pga < float(self.config[self.model]['minpga'])] = 0.0\n                Pmax[pga < float(self.config[self.model]['minpga'])] = 0.0\n\n            if 'coverage' in self.config[self.model].keys():\n                eqnmin = eqn.replace('P', 'Pmin')\n                eqnmax = eqn.replace('P', 'Pmax')\n                Pmin = eval(eqnmin)\n                Pmax = eval(eqnmax)\n\n            #Pmin[np.isnan(Pmin)] = 0.0\n            #Pmax[np.isnan(Pmax)] = 0.0\n\n        #P[np.isnan(P)] = 0.0\n\n        if self.slopefile is not None and self.nonzero is not None:\n            # Apply slope min/max limits\n            print('applying slope thresholds')\n            P = P * self.nonzero\n            #P[P==0.0] = float('nan')\n            #P[np.isnan(P)] = 0.0\n            if self.uncert is not None:\n                Pmin = Pmin * self.nonzero\n                Pmax = Pmax * self.nonzero\n                #Pmin[Pmin==0.0] = float('nan')\n                #Pmax[Pmax==0.0] = float('nan')\n                #Pmin[np.isnan(Pmin)] = 0.0\n                #Pmax[np.isnan(Pmax)] = 0.0\n\n        # Stuff into Grid2D object\n        if 'Jessee' in self.modelrefs['shortref']:\n            if 'coverage' not in self.config[self.model].keys():\n                units5 = 'relative hazard'\n            else:\n                units5 = 'areal coverage'\n        elif 'Zhu' in self.modelrefs['shortref']:\n            units5 = 'areal coverage'\n        else:\n            units5 = 'probability'\n\n        shakedetail = (\n            '%s_ver%s'\n            % (self.shakedict['shakemap_id'],\n               self.shakedict['shakemap_version']))\n        description = {\n            'name': self.modelrefs['shortref'],\n            'longref': self.modelrefs['longref'],\n            'units': units5,\n            'shakemap': shakedetail,\n            'event_id': self.eventdict['event_id'],\n            'parameters': {'slopemin': self.slopemin,\n                           'slopemax': self.slopemax,\n                           'modeltype': self.modeltype}}\n        if 'vs30max' in self.config[self.model].keys():\n            description['vs30max'] = float(self.config[self.model]['vs30max'])\n        if 'minpgv' in self.config[self.model].keys():\n            description['minpgv'] = float(self.config[self.model]['minpgv'])\n\n        Pgrid = Grid2D(P, self.geodict)\n        if self.trimfile is not None:\n            # Turn all offshore cells to nan\n            Pgrid = trim_ocean(Pgrid, self.trimfile, nodata=float('nan'))\n        rdict = collections.OrderedDict()\n        rdict['model'] = {\n            'grid': Pgrid,\n            'label': ('%s %s') % (self.modeltype.capitalize(),\n                                  units5.title()),\n            'type': 'output',\n            'description': description\n        }\n        if self.uncert is not None:\n            Pmingrid = Grid2D(Pmin, self.geodict)\n            Pmaxgrid = Grid2D(Pmax, self.geodict)\n            if self.trimfile is not None:\n                Pmingrid = trim_ocean(\n                    Pmingrid, self.trimfile, nodata=float('nan'))\n                Pmaxgrid = trim_ocean(\n                    Pmaxgrid, self.trimfile, nodata=float('nan'))\n            rdict['modelmin'] = {\n                'grid': Pmingrid,\n                'label': ('%s %s (-%0.1f std ground motion)'\n                          % (self.modeltype.capitalize(),\n                             units5.title(),\n                             self.numstd)),\n                'type': 'output',\n                'description': description\n            }\n            rdict['modelmax'] = {\n                'grid': Pmaxgrid,\n                'label': ('%s %s (+%0.1f std ground motion)'\n                          % (self.modeltype.capitalize(),\n                             units5.title(),\n                             self.numstd)),\n                'type': 'output',\n                'description': description\n            }\n\n        # This step might swamp memory for higher resolution runs\n        if self.saveinputs is True:\n            for layername, layergrid in list(self.layerdict.items()):\n                units = self.units[layername]\n                if units is None:\n                    units = ''\n                rdict[layername] = {\n                    'grid': Grid2D(\n                        layergrid.getSlice(\n                            None, None, None, None, name=layername),\n                        self.geodict\n                    ),\n                    'label': '%s (%s)' % (layername, units),\n                    'type': 'input',\n                    'description': {\n                        'units': units,\n                        'name': self.shortrefs[layername],\n                        'longref': self.longrefs[layername]\n                    }\n                }\n            for gmused in self.gmused:\n                if 'pga' in gmused:\n                    units = '%g'\n                    getkey = 'pga'\n                elif 'pgv' in gmused:\n                    units = 'cm/s'\n                    getkey = 'pgv'\n                elif 'mmi' in gmused:\n                    units = 'intensity'\n                    getkey = 'mmi'\n                else:\n                    continue\n                    # Layer is derived from several input layers, skip\n                    # outputting this layer\n\n                if getkey in rdict:\n                    continue\n\n                layer = self.shakemap[getkey].getSlice(\n                    None, None, None, None, name=getkey)\n                rdict[getkey] = {\n                    'grid': Grid2D(layer, self.geodict),\n                    'label': '%s (%s)' % (getkey.upper(), units),\n                    'type': 'input',\n                    'description': {\n                        'units': units,\n                        'shakemap': shakedetail\n                    }\n                }\n                if self.uncert is not None:\n                    uncertlayer = self.uncert[getkey].getSlice(\n                        None, None, None, None, name='std'+getkey)\n                    layer1 = np.exp(np.log(layer) - uncertlayer)\n                    rdict[getkey + 'modelmin'] = {\n                        'grid': Grid2D(layer1, self.geodict),\n                        'label': ('%s - %0.1f std (%s)'\n                                  % (getkey.upper(),\n                                     self.numstd, units)),\n                        'type': 'input',\n                        'description': {'units': units,\n                                        'shakemap': shakedetail}\n                    }\n                    layer2 = np.exp(np.log(layer) + uncertlayer)\n                    rdict[getkey + 'modelmax'] = {\n                        'grid': Grid2D(layer2, self.geodict),\n                        'label': ('%s + %0.1f std (%s)'\n                                  % (getkey.upper(),\n                                     self.numstd, units)),\n                        'type': 'input',\n                        'description': {'units': units,\n                                        'shakemap': shakedetail}\n                    }\n        if cleanup:\n            shutil.rmtree(self.tempdir)\n        return rdict\n\n\ndef getLogisticModelNames(config):\n    \"\"\"\n    Get the names of the models present in the configobj\n\n    Args:\n        config: configobj object defining the model and its inputs.\n\n    Returns:\n        list: list of model names.\n    \"\"\"\n    names = []\n    lmodel_space = config\n    for key, value in lmodel_space.items():\n        if isinstance(value, str):\n            continue\n        else:  # this is a model\n            names.append(key)\n    return names\n\n\ndef getFileType(filename):\n    \"\"\"\n    Determine whether input file is a shapefile or a grid (ESRI or GMT).\n\n    Args:\n        filename (str): Path to candidate filename.\n\n    Returns:\n        str: 'shapefile', 'grid', or 'unknown'.\n    \"\"\"\n    #TODO MOVE TO MAPIO.\n    if os.path.isdir(filename):\n        return 'dir'\n    ftype = GMTGrid.getFileType(filename)\n    if ftype != 'unknown':\n        return 'gmt'\n    # Skip over ESRI header files\n    if filename.endswith('.hdr'):\n        return 'unknown'\n    try:\n        GDALGrid.getFileGeoDict(filename)\n        return 'esri'\n    except:\n        pass\n    return 'unknown'\n\n\ndef getAllGridFiles(indir):\n    \"\"\"\n    Get list of all gmt or esri (.grd, .bil) files in a directory.\n\n    Args:\n        indir (str): Directory to search.\n    Returns:\n        list: List of file names.\n    \"\"\"\n    #TODO MOVE TO MAPIO\n    tflist = os.listdir(indir)\n    flist = []\n    for tf in tflist:\n        fullfile = os.path.join(indir, tf)\n        ftype = getFileType(fullfile)\n        if ftype in ['gmt', 'esri']:\n            flist.append(fullfile)\n    return flist\n\n\ndef validateCoefficients(cmodel):\n    \"\"\"\n    Ensures coefficients provided in model description are valid and outputs\n    a dictionary of the coefficients.\n\n    Args:\n        cmodel (dict): Sub-dictionary from config for specific model,\n            for example:\n\n            .. code-block:: python\n\n                cmodel = config['test_model']\n\n    Returns:\n        dict: a dictionary of model coefficients named b0, b1, b2...\n    \"\"\"\n    coeffs = {}\n    for key, value in cmodel['coefficients'].items():\n        if re.search('b[0-9]*', key) is None:\n            raise Exception('coefficients must be named b0, b1, ...')\n        coeffs[key] = float(value)\n    if 'b0' not in list(coeffs.keys()):\n        raise Exception('coefficients must include an intercept '\n                        'coefficient named b0.')\n    return coeffs\n\n\ndef validateClips(cmodel, layers, gmused):\n    \"\"\"\n    Ensures coefficients provided in model description are valid and outputs\n    a dictionary of the coefficients.\n\n    Args:\n        cmodel (dict): Sub-dictionary from config for specific model,\n            for example:\n\n            .. code-block:: python\n\n                cmodel = config['test_model']\n\n    Returns:\n        dict: a dictionary of clip values for each layer (if exists)\n    \"\"\"\n    clips = {}\n    if 'clip' in cmodel:\n        for key, value in cmodel['clip'].items():\n            if key not in layers:\n                if key not in gmused:\n                    x1 = [par for par in gmused if key in par]\n                    if len(x1) == 0:\n                        raise Exception(\n                            'Clipping key %s does not match any names of layers'\n                            % key)\n            clips[key] = (float(value[0]), float(value[1]))\n    return clips\n\n\ndef validateLayers(cmodel):\n    \"\"\"\n    Ensures all input files required to run the model exist and are valid\n    file types.\n\n    Args:\n        cmodel (dict): Sub-dictionary from config for specific model,\n            for example,\n\n            .. code-block:: python\n\n                cmodel = config['test_model']\n\n    Returns:\n        dict: a dictionary of file names, e.g.\n\n        .. code-block:: python\n\n            {\n                'slope': 'slopefile.bil',\n                'vs30': 'vs30.grd'\n            }\n\n    \"\"\"\n    layers = {}\n    longrefs = {}\n    shortrefs = {}\n    for key in cmodel['layers'].keys():\n        for item, value in cmodel['layers'][key].items():\n            if item == 'file':\n                ftype = getFileType(value)\n                if ftype == 'unknown':\n                    raise Exception('layer file %s is not a valid GMT or '\n                                    'ESRI file.' % value)\n                if ftype == 'dir':\n                    value = getAllGridFiles(value)\n                layers[key] = value\n            elif item == 'shortref':\n                shortrefs[key] = value\n            elif item == 'longref':\n                longrefs[key] = value\n    return layers\n\n\ndef validateTerms(cmodel, coeffs, layers):\n    \"\"\"\n    Reformats model inputs from config file, replacing functions with numpy\n    functions, inserting code for extracting data from each layer (required\n    to run eval in the calculate step), addressing any time variables, and\n    checks that term names match coefficient names.\n\n    Args:\n        cmodel (dict): Sub-dictionary from config for specific model,\n            e.g.\n\n            .. code-block:: python\n\n                cmodel = config['test_model']\n\n        coeffs (dict): Dictionary of model coefficients, e.g.\n\n            .. code-block:: python\n\n                {'b0': 3.5, 'b1': -0.01}\n\n        layers (dict): Dictionary of file names for all input layers, e.g.\n\n            .. code-block:: python\n\n                {'slope': 'slopefile.bil', 'vs30': 'vs30.grd'}\n\n    Returns:\n        tuple: (terms, timeField), where\n            - 'terms' is a dictionary of terms that form the model equation,\n              e.g.\n\n            .. code-block:: python\n\n                {\n                    'b1': \"self.layerdict['friction'].getData()\",\n                    'b2': \"self.layerdict['slope'].getData()/100.\"\n                }\n\n            - 'timeField' indicates the time that is used to know which input\n              file to read in, e.g. for monthly average precipitation, 'MONTH'.\n    \"\"\"\n    #TODO:\n    #    - Return a time field for every term, not just one global one.\n\n    terms = {}\n    timeField = None\n    for key, value in cmodel['terms'].items():\n        if key not in list(coeffs.keys()):\n            raise Exception('Term names must match names of coefficients')\n        # replace log with np.log, make sure variables are all in layers list,\n        # etc.\n        term, rem, tTimeField = checkTerm(value, layers)\n        if tTimeField is not None:\n            timeField = tTimeField\n        if len(rem):\n            msg = ('Term \"%s\" contains the unknown text fragment \"%s\". '\n                   'This may cause the expression to fail.')\n            tpl = (term, rem)\n            raise Exception(msg % tpl)\n        terms[key] = term\n    return (terms, timeField)\n\n\ndef validateInterpolations(cmodel, layers):\n    \"\"\"Validate logistic model interpolation.\n\n    Args:\n        cmodel (dict): Sub-dictionary from config for specific model.\n        layers (dict): Dictionary of file names for all input layers.\n\n    Returns:\n        dict: Model interpolation methods.\n    \"\"\"\n    interpolations = {}\n    for key, value in cmodel['interpolations'].items():\n        if key not in list(layers.keys()):\n            raise Exception(\n                'Interpolation key %s does not match any names of layers'\n                % key)\n        methods = ['linear', 'nearest', 'cubic', 'bilinear']\n        if value not in methods:\n            raise Exception(\n                'Interpolation method %s not in approved list of methods: %s'\n                % (key, str(methods)))\n        interpolations[key] = value\n    for key in list(layers.keys()):\n        if key not in list(interpolations.keys()):\n            raise Exception(\n                'No interpolation method configured for layer %s' % key)\n    return interpolations\n\n\ndef validateUnits(cmodel, layers):\n    \"\"\"Validate model units.\n\n    Args:\n        cmodel (dict): Sub-dictionary from config for specific model.\n        layers (dict): Dictionary of file names for all input layers.\n\n    Returns:\n        dict: Model units.\n    \"\"\"\n    units = {}\n    for key in cmodel['layers'].keys():\n        if 'units' in cmodel['layers'][key]:\n            units[key] = cmodel['layers'][key]['units']\n        else:\n            raise Exception('No unit string configured for layer %s' % key)\n    return units\n\n\ndef validateLogisticModels(config):\n    \"\"\"Validate model names.\n\n    Args:\n        cmodel (dict): Sub-dictionary from config for specific model.\n        layers (dict): Dictionary of file names for all input layers.\n\n    Returns:\n        bool: True if the model names are valid\n    \"\"\"\n    mnames = getLogisticModelNames(config)\n    if len(mnames) > 1:\n        raise Exception('Config file contains more than one model which is '\n                        'no longer allowed, update your config file to the '\n                        'newer format')\n    for cmodelname in mnames:\n        try:\n            cmodel = config[cmodelname]\n            coeffs = validateCoefficients(cmodel)\n            # key = layer name, value = file name\n            layers = validateLayers(cmodel)\n            terms, timeField = validateTerms(cmodel, coeffs, layers)\n            if timeField is not None:\n                for (layer, layerfile) in list(layers.items()):\n                    if isinstance(layerfile, list):\n                        for lfile in layerfile:\n                            if timeField == 'MONTH':\n                                pass\n            validateInterpolations(cmodel, layers)\n            if cmodel['baselayer'] not in layers:\n                raise Exception(\n                    'Model %s missing baselayer parameter.' % cmodelname)\n        except Exception as e:\n            raise Exception('Validation failed with error: \"%s\" on model %s'\n                            % (str(e), cmodelname))\n\n    return True\n\n\ndef validateRefs(cmodel):\n    \"\"\"Validate references for models and layers.\n\n    Args:\n        cmodel (dict): Sub-dictionary from config for specific model.\n\n    Returns:\n        tuple: (modelrefs, longrefs, shortrefs) where:\n            * modelrefs: dictionary of citation information for model\n                keys='longref', 'shortref'\n            * shortrefs: dictionary containing short reference for each\n                input layer\n            * longrefs: dictionary containing full references for each\n                input layer\n\n    \"\"\"\n    longrefs = {}\n    shortrefs = {}\n    modelrefs = {}\n    for key in cmodel['layers'].keys():\n        if 'longref' in cmodel['layers'][key]:\n            longrefs[key] = cmodel['layers'][key]['longref']\n        else:\n            print('No longref provided for layer %s' % key)\n            longrefs[key] = 'unknown'\n        if 'shortref' in cmodel['layers'][key]:\n            shortrefs[key] = cmodel['layers'][key]['shortref']\n        else:\n            print('No shortref provided for layer %s' % key)\n            shortrefs[key] = 'unknown'\n    try:\n        modelrefs['longref'] = cmodel['longref']\n    except:\n        print('No model longref provided')\n        modelrefs['longref'] = 'unknown'\n    try:\n        modelrefs['shortref'] = cmodel['shortref']\n    except:\n        print('No model shortref provided')\n        modelrefs['shortref'] = 'unknown'\n    return modelrefs, longrefs, shortrefs\n\n\ndef checkTerm(term, layers):\n    \"\"\"Checks terms of equation and replaces text with machine readable operators\n\n    Args:\n        term: term from model configuration file\n        layers: dictionary of file names for all input layers\n\n    Returns:\n        tuple: (term, tterm, timeField) where:\n            * term: dictionary of verified terms for equation with keys corresponding\n                to each layer name\n            * tterm: any unconverted and unverified text that may cause expression to fail\n            * timeField: if any inputs are time dependent, output is unit of time (e.g., 'YEAR'),\n                otherwise, None.\n    \"\"\"\n    # startterm = term\n    # Strip out everything that isn't: 0-9.() operators, +-/* or layer names.\n    # Anything left is an unknown symbol.\n    tterm = term\n    # remove log, sqrt, etc.\n    for op in OPERATORS:\n        tterm = tterm.replace(op, '')\n    # remove ShakeMap variables\n    for sm_term in SM_TERMS:\n        tterm = tterm.replace(sm_term, '')\n    # remove layer names\n    for layer in layers:\n        tterm = tterm.replace(layer, '')\n    # remove arithmetic operators\n    tterm = re.sub(OPERATORPAT, '', tterm)\n    # remove floating point numbers\n    tterm = re.sub(FLOATPAT, '', tterm)\n    # remove integer numbers\n    tterm = re.sub(INTPAT, '', tterm)\n    # remove parentheses\n    tterm = re.sub('[()]*', '', tterm)\n    # remove any blank spaces\n    tterm = tterm.strip()\n    # remove commas\n    tterm = tterm.strip(',')\n    # anything left *might* cause an error\n    for op in OPERATORS:\n        if term.find(op) > -1:\n            term = term.replace(op, 'np.'+op)\n\n    for sm_term in SM_GRID_TERMS:\n        term = term.replace(\n            sm_term,\n            \"self.shakemap['%s'].getSlice(rowstart, rowend, \"\n            \"colstart, colend, name='%s')\" % (sm_term, sm_term))\n\n    # replace the macro MW with the magnitude value from the shakemap\n    term = term.replace('MW', \"self.eventdict['magnitude']\")\n\n    # term.replace('YEAR',\"self.shakemap.getEventDict()['event_time'].year\")\n    # hasTime = False\n    timeField = None\n    for unit in ['YEAR', 'MONTH', 'DAY', 'HOUR']:\n        if term.find(unit) > -1:\n            term = term.replace(unit, '')\n            timeField = unit\n\n    for layer in layers:\n        if layer == 'friction':\n            term = term.replace(\n                layer,\n                \"np.nan_to_num(self.layerdict['%s'].getSlice(rowstart, \"\n                \"rowend, colstart, colend, name='%s'))\" % (layer, layer))\n        else:\n            term = term.replace(\n                layer,\n                \"self.layerdict['%s'].getSlice(rowstart, rowend, colstart, \"\n                \"colend, name='%s')\" % (layer, layer))\n    return (term, tterm, timeField)\n", "meta": {"hexsha": "fa03b77dd1275d33f29363c512ab9d10f6d6de56", "size": 44494, "ext": "py", "lang": "Python", "max_stars_repo_path": "gfail/logisticmodel.py", "max_stars_repo_name": "vinceq-usgs/groundfailure", "max_stars_repo_head_hexsha": "4cee8f319abe7992f6e124239152321e379847b2", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gfail/logisticmodel.py", "max_issues_repo_name": "vinceq-usgs/groundfailure", "max_issues_repo_head_hexsha": "4cee8f319abe7992f6e124239152321e379847b2", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gfail/logisticmodel.py", "max_forks_repo_name": "vinceq-usgs/groundfailure", "max_forks_repo_head_hexsha": "4cee8f319abe7992f6e124239152321e379847b2", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4563526361, "max_line_length": 97, "alphanum_fraction": 0.5122937924, "include": true, "reason": "import numpy,from scipy", "num_tokens": 9968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3140505385717078, "lm_q1q2_score": 0.17655183287554305}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n'''\n\n    ImagePlayer: denoising HAADF images.\n\n    Copyright (C) 2021  Feng Wang\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published\n    by the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\n'''\n\nimport os\nos.environ[\"QT_LOGGING_RULES\"]= '*.debug=false;qt.qpa.*=false'\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"\"\n#os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\n\nfrom PySide6.QtPrintSupport import QPrintDialog, QPrinter\nfrom PySide6.QtWidgets import (QApplication, QDialog, QFileDialog, QLabel, QMainWindow, QMenuBar, QMessageBox, QScrollArea, QScrollBar, QSizePolicy, QStatusBar)\nfrom PySide6.QtGui import (QAction, QClipboard, QColorSpace, QGuiApplication, QImage, QImageReader, QImageWriter, QKeySequence, QPalette, QPainter, QPixmap, QScreen, QPainter, QIcon)\nfrom PySide6.QtCore import QDir, QMimeData, QStandardPaths, Qt, Slot, QSize, QPoint\nfrom argparse import ArgumentParser, RawTextHelpFormatter\nfrom PySide6.QtWidgets import (QApplication)\nfrom qt_material import apply_stylesheet\n\nimport tempfile\nimport glob\nimport importlib, pathlib, sys\nimport imageio\nimport numpy as np\nimport shutil\nimport random\nimport string\nimport sys\nfrom requests import get\nimport os\nimport string\nimport sys\nimport random\nimport pathlib\nimport importlib\nimport tempfile\nimport imageio\nimport imageio.plugins.pillow\nimport tifffile\nfrom scipy.ndimage import zoom\n\nfrom tensorflow.keras.models import model_from_json\nfrom tensorflow.keras.layers import Layer, InputSpec\nfrom tensorflow.keras import initializers, regularizers, constraints\nfrom tensorflow.python.keras.utils.generic_utils import get_custom_objects\nfrom tensorflow.keras import backend as K\n\nclass InstanceNormalization(Layer):\n    def __init__(self,\n                 axis=None,\n                 epsilon=1e-3,\n                 center=True,\n                 scale=True,\n                 beta_initializer='zeros',\n                 gamma_initializer='ones',\n                 beta_regularizer=None,\n                 gamma_regularizer=None,\n                 beta_constraint=None,\n                 gamma_constraint=None,\n                 **kwargs):\n        super(InstanceNormalization, self).__init__(**kwargs)\n        self.supports_masking = True\n        self.axis = axis\n        self.epsilon = epsilon\n        self.center = center\n        self.scale = scale\n        self.beta_initializer = initializers.get(beta_initializer)\n        self.gamma_initializer = initializers.get(gamma_initializer)\n        self.beta_regularizer = regularizers.get(beta_regularizer)\n        self.gamma_regularizer = regularizers.get(gamma_regularizer)\n        self.beta_constraint = constraints.get(beta_constraint)\n        self.gamma_constraint = constraints.get(gamma_constraint)\n\n    def build(self, input_shape):\n        ndim = len(input_shape)\n        if self.axis == 0:\n            raise ValueError('Axis cannot be zero')\n\n        if (self.axis is not None) and (ndim == 2):\n            raise ValueError('Cannot specify axis for rank 1 tensor')\n\n        self.input_spec = InputSpec(ndim=ndim)\n\n        if self.axis is None:\n            shape = (1,)\n        else:\n            shape = (input_shape[self.axis],)\n\n        if self.scale:\n            self.gamma = self.add_weight(shape=shape,\n                                         name='gamma',\n                                         initializer=self.gamma_initializer,\n                                         regularizer=self.gamma_regularizer,\n                                         constraint=self.gamma_constraint)\n        else:\n            self.gamma = None\n        if self.center:\n            self.beta = self.add_weight(shape=shape,\n                                        name='beta',\n                                        initializer=self.beta_initializer,\n                                        regularizer=self.beta_regularizer,\n                                        constraint=self.beta_constraint)\n        else:\n            self.beta = None\n        self.built = True\n\n    def call(self, inputs, training=None):\n        input_shape = K.int_shape(inputs)\n        reduction_axes = list(range(0, len(input_shape)))\n\n        if self.axis is not None:\n            del reduction_axes[self.axis]\n\n        del reduction_axes[0]\n\n        mean = K.mean(inputs, reduction_axes, keepdims=True)\n        stddev = K.std(inputs, reduction_axes, keepdims=True) + self.epsilon\n        normed = (inputs - mean) / stddev\n\n        broadcast_shape = [1] * len(input_shape)\n        if self.axis is not None:\n            broadcast_shape[self.axis] = input_shape[self.axis]\n\n        if self.scale:\n            broadcast_gamma = K.reshape(self.gamma, broadcast_shape)\n            normed = normed * broadcast_gamma\n        if self.center:\n            broadcast_beta = K.reshape(self.beta, broadcast_shape)\n            normed = normed + broadcast_beta\n        return normed\n\n    def get_config(self):\n        config = {\n            'axis': self.axis,\n            'epsilon': self.epsilon,\n            'center': self.center,\n            'scale': self.scale,\n            'beta_initializer': initializers.serialize(self.beta_initializer),\n            'gamma_initializer': initializers.serialize(self.gamma_initializer),\n            'beta_regularizer': regularizers.serialize(self.beta_regularizer),\n            'gamma_regularizer': regularizers.serialize(self.gamma_regularizer),\n            'beta_constraint': constraints.serialize(self.beta_constraint),\n            'gamma_constraint': constraints.serialize(self.gamma_constraint)\n        }\n        base_config = super(InstanceNormalization, self).get_config()\n        return dict(list(base_config.items()) + list(config.items()))\n\nget_custom_objects().update({'InstanceNormalization': InstanceNormalization})\n\n\ndef read_model(directory):\n    #weights_path = f'{directory}/weights.h5'\n    weights_path = os.path.join( directory, 'weights.h5' )\n    if not os.path.isfile(weights_path):\n        print( f'Failed to find weights from file {weights_path}' )\n        return None\n\n    #json_path = f'{directory}/js.json'\n    json_path = os.path.join( directory, 'js.json' )\n    if not os.path.isfile(json_path):\n        print( f'Failed to find model from file {json_path}' )\n        return None\n\n    js_file = open( json_path, 'r' )\n    model_json = js_file.read()\n    js_file.close()\n    model = model_from_json( model_json, custom_objects={\"InstanceNormalization\": InstanceNormalization} )\n    model.load_weights( weights_path )\n    #print( model.summary() )\n    return model\n\n\ndef s9_denoising( model, input_image_path, output_image_path ):\n    print( f'Trying to denoising image from {input_image_path}' )\n    x = imageio.imread( input_image_path )\n    x = np.squeeze( x )\n\n    if not len(x.shape) == 2:\n        print( f'Input image with shape {x.shape} is not a gray image' )\n        return False\n\n    x = np.reshape(x, (1,) + x.shape + (1,) )\n    x = np.asarray( x, dtype='float32' )\n    x /= np.amax(x) + 1.0e-10\n    y = model.predict( x )\n    y = np.squeeze( y )\n    y /= np.amax(y) + 1.0e-10\n    imageio.imwrite( output_image_path, np.asarray( y*255.0, dtype='uint8' ) )\n    print( f'Writing output image to {output_image_path}' )\n    return True\n\nuncultivated_widget = None\ns9_denoising_model = None\n\ndef update_widget_image( image_widget, output_image_path ):\n    global uncultivated_widget\n    if uncultivated_widget is None:\n        uncultivated_widget = image_widget\n    uncultivated_widget.show()\n    uncultivated_widget.update_content_file( output_image_path, rescaling_flag=False, in_a_new_window=False );\n    QApplication.processEvents()\n\n\n\ndef s9_implementation( image_widget ):\n\n    global s9_denoising_model\n    if s9_denoising_model is None: # load module dynamically\n        if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):\n            current_directory = os.path.dirname( sys.executable ) # <-- updated\n        else:\n            current_directory = os.path.dirname(os.path.realpath(__file__))\n        #current_directory = os.path.dirname( sys.executable ) # <-- updated\n        local_s9_denoising_model_path = os.path.join(current_directory, 'models', 's9_model' )\n        s9_denoising_model = read_model( local_s9_denoising_model_path )\n\n    '''\n    input_image_path = image_widget.get_snapshot_file()\n    random_file_prefix = ''.join(random.choices(string.ascii_uppercase + string.digits, k = 13))\n    output_image_path = os.path.join( tempfile.gettempdir(), f'{random_file_prefix}_s9_denoising_cache.png' )\n\n    if s9_denoising( s9_denoising_model, input_image_path, output_image_path ):\n        image_widget.update_content_file( output_image_path )\n    '''\n\n    if not image_widget.is_tiff: # case of single image\n        input_image_path = image_widget.get_snapshot_file()\n        random_file_prefix = ''.join(random.choices(string.ascii_uppercase + string.digits, k = 13))\n        output_image_path = os.path.join( tempfile.gettempdir(), f'{random_file_prefix}_s9_denoising_cache.png' )\n\n        if s9_denoising( s9_denoising_model, input_image_path, output_image_path ):\n            image_widget.update_content_file( output_image_path )\n    else: # case of tif file\n        image_widget.tiff_data_denoised = []\n        n, _, _ = image_widget.tiff_data.shape\n        for idx in range( n ):\n            tmp_file_path = image_widget.get_new_snapshot_file()\n            imageio.imwrite( tmp_file_path, image_widget.tiff_data[idx] )\n\n            input_image_path = image_widget.get_snapshot_file()\n            random_file_prefix = ''.join(random.choices(string.ascii_uppercase + string.digits, k = 13))\n            output_image_path = os.path.join( tempfile.gettempdir(), f'{random_file_prefix}_s9_denoising_cache.png' )\n\n            if s9_denoising( s9_denoising_model, tmp_file_path, output_image_path ):\n                image_widget.tiff_data_denoised.append( imageio.imread( output_image_path ) )\n                update_widget_image( image_widget, output_image_path )\n\n            else:\n                break\n\n        if len( image_widget.tiff_data_denoised ):\n            image_widget.tiff_data_denoised = np.asarray( image_widget.tiff_data_denoised )\n\n\n\ndef s9_interface():\n    def detailed_implementation( image_widget ):\n        def fun():\n            return s9_implementation( image_widget )\n        return fun\n\n    return 'S9Denoising', detailed_implementation\n\n\n\n\ndef sd_denoising( model, input_image_path, output_image_path ):\n    x = imageio.imread( input_image_path )\n    x = np.squeeze( x )\n\n    if not len(x.shape) == 2:\n        print( f'Input image with shape {x.shape} is not a gray image' )\n        return False\n\n    x = zoom( x, 2, order=3 )\n    x = np.reshape(x, (1,) + x.shape + (1,) )\n    x = np.asarray( x, dtype='float32' )\n    x /= np.amax(x) + 1.0e-10\n    y = model.predict( x )\n    #y = make_zoom_prediction( model, x )\n\n    y = np.squeeze( y )\n    y /= np.amax(y) + 1.0e-10\n    imageio.imwrite( output_image_path, np.asarray( y*255.0, dtype='uint8' ) )\n    return True\n\n\nsd_denoising_model = None\ndef sd_implementation( image_widget ):\n\n    global sd_denoising_model\n    if sd_denoising_model is None: # load module dynamically\n        #current_directory = os.path.dirname(os.path.realpath(__file__))\n        if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):\n            current_directory = os.path.dirname( sys.executable ) # <-- updated\n        else:\n            current_directory = os.path.dirname(os.path.realpath(__file__))\n        local_sd_denoising_model_path = os.path.join(current_directory, 'models', 'debora_model' )\n        sd_denoising_model = read_model( local_sd_denoising_model_path )\n\n    if not image_widget.is_tiff: # case of single image\n        input_image_path = image_widget.get_snapshot_file()\n        random_file_prefix = ''.join(random.choices(string.ascii_uppercase + string.digits, k = 13))\n        output_image_path = os.path.join( tempfile.gettempdir(), f'{random_file_prefix}_debora_denoising_cache.png' )\n\n        if sd_denoising( sd_denoising_model, input_image_path, output_image_path ):\n            image_widget.update_content_file( output_image_path )\n    else: # case of tif file\n        image_widget.tiff_data_denoised = []\n        n, _, _ = image_widget.tiff_data.shape\n        for idx in range( n ):\n            tmp_file_path = image_widget.get_new_snapshot_file()\n            imageio.imwrite( tmp_file_path, image_widget.tiff_data[idx] )\n\n            input_image_path = image_widget.get_snapshot_file()\n            random_file_prefix = ''.join(random.choices(string.ascii_uppercase + string.digits, k = 13))\n            output_image_path = os.path.join( tempfile.gettempdir(), f'{random_file_prefix}_debora_denoising_cache.png' )\n\n            if sd_denoising( sd_denoising_model, tmp_file_path, output_image_path ):\n                image_widget.tiff_data_denoised.append( imageio.imread( output_image_path ) )\n                update_widget_image( image_widget, output_image_path )\n\n            else:\n                break\n\n\n        if len( image_widget.tiff_data_denoised ):\n            image_widget.tiff_data_denoised = np.asarray( image_widget.tiff_data_denoised )\n\n\n\n\n\n\n\n\n\n\n\n\nABOUT = \"Deep Image Denoising.\"\n\nclass ImagePlayer(QMainWindow):\n    def __init__(self, parent=None):\n        super().__init__(parent)\n        self._scale_factor = 1.0\n        self._first_file_dialog = True\n        self._image_label = QLabel()\n        self._image_label.setBackgroundRole(QPalette.Base)\n        self._image_label.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)\n        self._image_label.setScaledContents(True)\n\n        self._scroll_area = QScrollArea()\n        self._scroll_area.setBackgroundRole(QPalette.Dark)\n        self._scroll_area.setWidget(self._image_label)\n        self._scroll_area.setVisible(False)\n        self.setCentralWidget(self._scroll_area)\n\n        self._create_actions()\n\n        self.resize(QGuiApplication.primaryScreen().availableSize() ) # PySide6.QtCore.QSize(1920, 1200)\n\n        # data zone\n        self.tmp_image_counter = 0\n        self.current_cached_image_path = None\n        self.current_image_presented = None\n        self.random_file_prefix = ''.join(random.choices(string.ascii_uppercase + string.digits, k = 13))\n\n        dir_path = os.path.dirname(os.path.realpath(__file__))\n        self._plugin_list = []\n        self.load_plugins(os.path.join(dir_path, 'plugins'))\n\n        self._model_list = []\n        self.load_models(os.path.join(dir_path, 'models'))\n\n        # drop image file to open, accept\n        self.setAcceptDrops(True)\n\n        icon_path = self.load_plugins(os.path.join(dir_path, 'src', 'logo.png'))\n        self.setWindowIcon(QIcon(icon_path))\n\n        # home model path\n        self.user_model_path = os.path.join( os.path.expanduser('~'), '.deepoffice', 'imageplayer', 'model' )\n        #if not os.path.exists(self.user_model_path):\n        #    os.makedirs( self.user_model_path )\n\n        # denoising stacked tiff file\n        self.is_tiff = False\n        self.tiff_path = None\n        self.tiff_data = None\n        self.tiff_data_denoised = None\n        self.tiff_data_denoised_presentation_index = None\n\n\n    # download model files from github release\n    def download_remote_model(self, model_name, model_url):\n        model_path = os.path.join( self.user_model_path, model_name )\n\n        if not os.path.exists(model_path):\n            os.makedirs(model_path)\n\n        file_name = model_url.rsplit('/', 1)[1]\n        local_model_path = os.path.join( model_path, file_name )\n        if not os.path.isfile(local_model_path):\n            print( f'downloading model file {local_model_path} from {model_url}' )\n            with open(local_model_path, \"wb\") as file:\n                response = get(model_url)\n                file.write(response.content)\n            print( f'downloaded model file {local_model_path} from {model_url}' )\n\n        return local_model_path\n\n\n    # interface to plugins 1\n    def get_snapshot_file( self, index=None ):\n        return self.get_new_snapshot_file( self.tmp_image_counter-1 )\n\n    # interface to plugins 2: a single file\n    def update_content_file(self, fileName, rescaling_flag=False, in_a_new_window=True):\n        self.load_file(fileName, rescaling_flag)\n        '''\n        if not in_a_new_window:\n            self.load_file( fileName, rescaling_flag )\n        else:\n            image_player = ImagePlayer()\n            image_player.show()\n            image_player.update_content_file( fileName, rescaling_flag=rescaling_flag, in_a_new_window=False );\n        '''\n\n    # interface to plugins 3: many files\n    def update_content_files(self, fileNames, rescaling_flag=False, in_a_new_window=True):\n        for fileName in fileNames:\n            self.update_content_file( fileName, rescaling_flag, in_a_new_window )\n\n\n    def get_new_snapshot_file( self, index=None ):\n        if index is None:\n            index = self.tmp_image_counter\n            self.tmp_image_counter += 1\n        tmp_dir = tempfile.gettempdir()\n        tmp_png_file = os.path.join( tmp_dir, f'{self.random_file_prefix}_{index}.png' )\n        return tmp_png_file\n\n\n    def dragEnterEvent(self, e):\n        if e.mimeData().hasUrls():\n            e.accept()\n        else:\n            e.ignore()\n            print( f'ignoring {e.mimeData().text()}' )\n\n    def dropEvent(self, e):\n        if e.mimeData().hasUrls():\n            for url in  e.mimeData().urls():\n                self.load_file( url.path() )\n                break\n\n\n    def wheelEvent(self, event):\n        numDegrees = event.angleDelta() / 8.0\n\n        if not numDegrees.isNull():\n            x = numDegrees.x() / 150.0\n            y = numDegrees.y() / 150.0\n\n            new_scale = x + 1.0\n            if abs(y) > abs(x):\n                new_scale = y + 1.0\n\n            new_scale = min( 2.0, max( 0.5, new_scale) )\n            self._scale_image(new_scale)\n\n        event.accept()\n\n\n    def _show_tiff( self, index=0 ):\n        img_to_show = self.tiff_data\n        if len(self.tiff_data.shape) == 3:\n            n, _, _ = self.tiff_data.shape\n            index = index % n\n            img_to_show = self.tiff_data[index]\n\n        tmp_file_path = self.get_new_snapshot_file()\n        imageio.imwrite( tmp_file_path, img_to_show )\n        self.load_file( tmp_file_path )\n\n\n    def load_file(self, fileName, rescaling_flag=True):\n        _, file_extension = os.path.splitext( fileName )\n\n        if file_extension == '.tif' or file_extension == '.tiff':\n            print( f'reading tifffile from {fileName}' )\n            self.is_tiff = True\n            self.tiff_path = fileName\n            self.tiff_data = np.squeeze( tifffile.imread( fileName ) )\n            self.tiff_data_denoised = None\n\n            if self.tiff_data.size == 0:\n                return False\n\n            self._show_tiff(0)\n            return True\n\n        reader = QImageReader(fileName)\n        reader.setAutoTransform(True)\n        new_image = reader.read()\n        native_filename = QDir.toNativeSeparators(fileName)\n        if new_image.isNull():\n            error = reader.errorString()\n            #QMessageBox.information(self, QGuiApplication.applicationDisplayName(), f\"Cannot load {native_filename}: {error}\")\n            error_message = f'cannot open file {native_filename} -->  Error: {error}'\n            self.statusBar().showMessage(error_message)\n            return False\n        self.current_image_presented = fileName\n        self._set_image(new_image)\n        self.setWindowFilePath(fileName)\n\n        w = max( self._image.width() * 1.15, 300 )\n        h = max( self._image.height() * 1.15, 300 )\n        d = self._image.depth()\n        max_size = QGuiApplication.primaryScreen().availableSize()\n        self._current_size = QSize(min(w, max_size.width()), min( h, max_size.height()) )\n        self.resize( self._current_size )\n        if rescaling_flag:\n            self._scale_image( self._scale_factor )\n        message = f'Opened \"{native_filename}\": {self._image.width()}x{self._image.height()}'\n        self.statusBar().showMessage(message)\n\n        self._save_tmp_file()\n        return True\n\n    def _set_image(self, new_image):\n        self._image = new_image\n        if self._image.colorSpace().isValid():\n            self._image.convertToColorSpace(QColorSpace.SRgb)\n        self._image_label.setPixmap(QPixmap.fromImage(self._image))\n        self._scroll_area.setAlignment(Qt.AlignCenter)\n        self._scale_factor = 1.0\n\n        self._scroll_area.setVisible(True)\n        self._print_act.setEnabled(True)\n        self._update_actions()\n\n        if not self._fit_to_window_act.isChecked():\n            self._image_label.adjustSize()\n\n    def _save_file(self, fileName):\n        _, new_extension = os.path.splitext( fileName )\n        if new_extension == '.tif' or new_extension == '.tiff':\n            if self.tiff_data_denoised is not None:\n                tifffile.imwrite( fileName, self.tiff_data_denoised )\n                print( f'writting denoised tiff data to {fileName}' )\n                return True\n\n        _, current_extension = os.path.splitext( self.current_image_presented )\n        if (current_extension == new_extension ):\n            if self.current_image_presented != fileName:\n                shutil.copy( self.current_image_presented, fileName )\n            return True\n\n\n        writer = QImageWriter(fileName)\n\n        native_filename = QDir.toNativeSeparators(fileName)\n        if not writer.write(self._image):\n            error = writer.errorString()\n            message = f\"Cannot write {native_filename}: {error}\"\n            QMessageBox.information(self, QGuiApplication.applicationDisplayName(), message)\n            self.statusBar().showMessage( message );\n            return False\n        return True\n\n    def _save_tmp_file( self ):\n        tmp_png_file = self.get_new_snapshot_file()\n        if not self._save_file(tmp_png_file):\n            print( f'Failed saving tmp file to {tmp_png_file}' )\n            return None\n        print( f'saving tmp file: {tmp_png_file}' )\n        self.tmp_image_counter += 1\n        self.current_cached_image_path = tmp_png_file\n        return tmp_png_file\n\n    @Slot()\n    def _undo( self ):\n        prev_cache_file = self.get_new_snapshot_file( self.tmp_image_counter-2 )\n        if os.path.isfile( prev_cache_file ):\n            self.load_file( prev_cache_file )\n            self.tmp_image_counter -=  2\n            print( f'Undo: updating image counter to {self.tmp_image_counter}')\n        else:\n            print( f'cannot load {prev_cache_file=}' )\n\n    @Slot()\n    def _redo( self ):\n        next_cache_file = self.get_new_snapshot_file( self.tmp_image_counter )\n        if os.path.isfile( next_cache_file ):\n            self.load_file( next_cache_file )\n            print( f'Redo: updating image counter to {self.tmp_image_counter}')\n        else:\n            print( f'cannot load {next_cache_file=}' )\n\n    @Slot()\n    def _clean_tmp_file( self ):\n        for idx in range( self.tmp_image_counter ):\n            tmp_dir = tempfile.gettempdir()\n            tmp_png_file = os.path.join( tmp_dir, f'{self.random_file_prefix}_{idx}.png' )\n            if os.path.isfile( tmp_png_file ):\n                os.remove( tmp_png_file )\n                print( f'removing file {tmp_png_file}' )\n        self.tmp_image_counter = 0\n        self.current_cached_image_path = None\n\n\n    @Slot()\n    def _open(self):\n        dialog = QFileDialog(self, \"Open File\")\n        self._initialize_image_filedialog(dialog, QFileDialog.AcceptOpen)\n        while (dialog.exec() == QDialog.Accepted\n               and not self.load_file(dialog.selectedFiles()[0])):\n            pass\n\n    @Slot()\n    def _save_as(self):\n        dialog = QFileDialog(self, \"Save File As\")\n        self._initialize_image_filedialog(dialog, QFileDialog.AcceptSave)\n        while (dialog.exec() == QDialog.Accepted and not self._save_file(dialog.selectedFiles()[0])):\n            pass\n\n    @Slot()\n    def _print_(self):\n        printer = QPrinter()\n        dialog = QPrintDialog(printer, self)\n        if dialog.exec() == QDialog.Accepted:\n            painter = QPainter(printer)\n            pixmap = self._image_label.pixmap()\n            rect = painter.viewport()\n            size = pixmap.size()\n            size.scale(rect.size(), Qt.KeepAspectRatio)\n            painter.setViewport(rect.x(), rect.y(), size.width(), size.height())\n            painter.setWindow(pixmap.rect())\n            painter.drawPixmap(0, 0, pixmap)\n            painter.end()\n\n    @Slot()\n    def _copy(self):\n        QGuiApplication.clipboard().setImage(self._image)\n\n    @Slot()\n    def _paste(self):\n        new_image = QGuiApplication.clipboard().image()\n        if new_image.isNull():\n            self.statusBar().showMessage(\"No image in clipboard\")\n        else:\n            self._set_image(new_image)\n            self.setWindowFilePath('')\n            w = new_image.width()\n            h = new_image.height()\n            d = new_image.depth()\n            message = f\"Obtained image from clipboard, {w}x{h}, Depth: {d}\"\n            self.statusBar().showMessage(message)\n\n    @Slot()\n    def _zoom_in(self):\n        if self.current_image_presented is not None:\n            self._scale_image(1.25)\n\n    @Slot()\n    def _zoom_out(self):\n        if self.current_image_presented is not None:\n            self._scale_image(0.8)\n\n    @Slot()\n    def _normal_size(self):\n        if self.current_image_presented is not None:\n            self._image_label.adjustSize()\n            self._scale_factor = 1.0\n\n    @Slot()\n    def _fit_to_window(self):\n        if self.current_image_presented is not None:\n            fit_to_window = self._fit_to_window_act.isChecked()\n            self._scroll_area.setWidgetResizable(fit_to_window)\n            if not fit_to_window:\n                self._normal_size()\n            self._update_actions()\n\n    @Slot()\n    def _about(self):\n        QMessageBox.about(self, \"About Image Viewer\", ABOUT)\n\n    def _create_actions(self):\n        file_menu = self.menuBar().addMenu(\"&File\")\n\n        self._open_act = file_menu.addAction(\"&Open...\")\n        self._open_act.triggered.connect(self._open)\n        self._open_act.setShortcut(QKeySequence.Open)\n\n        self._save_as_act = file_menu.addAction(\"&Save As...\")\n        self._save_as_act.triggered.connect(self._save_as)\n        self._save_as_act.setEnabled(False)\n\n        self._print_act = file_menu.addAction(\"&Print...\")\n        self._print_act.triggered.connect(self._print_)\n        self._print_act.setShortcut(QKeySequence.Print)\n        self._print_act.setEnabled(False)\n\n        file_menu.addSeparator()\n\n        self._exit_act = file_menu.addAction(\"E&xit\")\n        self._exit_act.triggered.connect(self.close)\n        self._exit_act.triggered.connect(self._clean_tmp_file)\n        self._exit_act.setShortcut(\"Ctrl+Q\")\n\n        edit_menu = self.menuBar().addMenu(\"&Edit\")\n\n        self._copy_act = edit_menu.addAction(\"Undo\")\n        self._copy_act.triggered.connect(self._undo)\n\n        self._copy_act = edit_menu.addAction(\"Redo\")\n        self._copy_act.triggered.connect(self._redo)\n\n        self._copy_act = edit_menu.addAction(\"&Copy\")\n        self._copy_act.triggered.connect(self._copy)\n        self._copy_act.setShortcut(QKeySequence.Copy)\n        self._copy_act.setEnabled(False)\n\n        self._paste_act = edit_menu.addAction(\"&Paste\")\n        self._paste_act.triggered.connect(self._paste)\n        self._paste_act.setShortcut(QKeySequence.Paste)\n\n        view_menu = self.menuBar().addMenu(\"&View\")\n\n        self._zoom_in_act = view_menu.addAction(\"Zoom &In (25%)\")\n        self._zoom_in_act.setShortcut(QKeySequence.ZoomIn)\n        self._zoom_in_act.triggered.connect(self._zoom_in)\n        self._zoom_in_act.setEnabled(False)\n\n        self._zoom_out_act = view_menu.addAction(\"Zoom &Out (25%)\")\n        self._zoom_out_act.triggered.connect(self._zoom_out)\n        self._zoom_out_act.setShortcut(QKeySequence.ZoomOut)\n        self._zoom_out_act.setEnabled(False)\n\n        self._normal_size_act = view_menu.addAction(\"&Normal Size\")\n        self._normal_size_act.triggered.connect(self._normal_size)\n        self._normal_size_act.setShortcut(\"Ctrl+S\")\n        self._normal_size_act.setEnabled(False)\n\n        view_menu.addSeparator()\n\n        self._fit_to_window_act = view_menu.addAction(\"&Fit to Window\")\n        self._fit_to_window_act.triggered.connect(self._fit_to_window)\n        self._fit_to_window_act.setEnabled(False)\n        self._fit_to_window_act.setCheckable(True)\n        self._fit_to_window_act.setShortcut(\"Ctrl+F\")\n\n        self.plugin_menu = self.menuBar().addMenu(\"&Plugins\")\n\n\n        self.model_menu = self.menuBar().addMenu(\"&Models\")\n\n        self.s9_act = self.model_menu.addAction(\"Denoising S9\")\n        self.s9_act.triggered.connect(self._s9_denosing)\n        self.s9_act.setEnabled(True)\n\n        self.sd_act = self.model_menu.addAction(\"Denoising SD\")\n        self.sd_act.triggered.connect(self._sd_denosing)\n        self.sd_act.setEnabled(True)\n\n\n\n        help_menu = self.menuBar().addMenu(\"&Help\")\n\n        about_act = help_menu.addAction(\"&About\")\n        about_act.triggered.connect(self._about)\n        about_qt_act = help_menu.addAction(\"About &Qt\")\n        about_qt_act.triggered.connect(QApplication.aboutQt)\n\n    def load_plugin( self, plugin_path ):\n        module_name = pathlib.Path(plugin_path).stem\n        module = importlib.import_module(module_name)\n        plugin_name, event = module.interface()\n        _act = self.plugin_menu.addAction( plugin_name )\n        _act.triggered.connect( event(self) )\n        self._plugin_list.append( plugin_name )\n\n\n    def load_plugins( self, folder ):\n        pass\n        '''\n        sys.path.append( folder )\n        plugin_paths = glob.glob( f'{folder}/*.py' ) +  glob.glob( f'{str(pathlib.Path.home())}/.deepoffice/plugins/*.py' )\n        for plugin_path in plugin_paths:\n            self.load_plugin( plugin_path )\n        '''\n\n\n    def load_model( self, model_path ):\n        module_name = pathlib.Path(model_path).stem\n        module = importlib.import_module(module_name)\n        model_name, event = module.interface()\n        _act = self.model_menu.addAction( model_name )\n        _act.triggered.connect( event(self) )\n        self._model_list.append( model_name )\n\n    def load_models( self, folder ):\n        pass\n        '''\n        sys.path.append( folder )\n        model_paths = glob.glob( f'{folder}/*.py' ) +  glob.glob( f'{str(pathlib.Path.home())}/.deepoffice/models/*.py' )\n        for model_path in model_paths:\n            self.load_model( model_path )\n        '''\n\n    def _update_actions(self):\n        has_image = not self._image.isNull()\n        self._save_as_act.setEnabled(has_image)\n        self._copy_act.setEnabled(has_image)\n        enable_zoom = not self._fit_to_window_act.isChecked()\n        self._zoom_in_act.setEnabled(enable_zoom)\n        self._zoom_out_act.setEnabled(enable_zoom)\n        self._normal_size_act.setEnabled(enable_zoom)\n\n    def _scale_image(self, factor):\n        if self.current_image_presented is not None:\n            self._scale_factor *= factor\n            new_size = self._scale_factor * self._image_label.pixmap().size()\n            self._image_label.resize(new_size)\n\n            self._adjust_scrollbar(self._scroll_area.horizontalScrollBar(), factor)\n            self._adjust_scrollbar(self._scroll_area.verticalScrollBar(), factor)\n\n            self._zoom_in_act.setEnabled(self._scale_factor < 3.0)\n            self._zoom_out_act.setEnabled(self._scale_factor > 0.333)\n\n            self._current_size *= factor\n\n    def _adjust_scrollbar(self, scrollBar, factor):\n        pos = int(factor * scrollBar.value() + ((factor - 1) * scrollBar.pageStep() / 2))\n        print( f'adjusting scrollbar to {pos=}' )\n        scrollBar.setValue(pos)\n\n    def _initialize_image_filedialog(self, dialog, acceptMode):\n        if self._first_file_dialog:\n            self._first_file_dialog = False\n            locations = QStandardPaths.standardLocations(QStandardPaths.PicturesLocation)\n            directory = locations[-1] if locations else QDir.currentPath()\n            dialog.setDirectory(directory)\n\n        mime_types = [m.data().decode('utf-8') for m in QImageWriter.supportedMimeTypes()]\n        mime_types.sort()\n\n        dialog.setMimeTypeFilters(mime_types)\n        dialog.setAcceptMode(acceptMode)\n        if acceptMode == QFileDialog.AcceptSave:\n            dialog.setDefaultSuffix(\"png\")\n\n    def _s9_denosing( self ):\n        s9_implementation( self )\n\n    def _sd_denosing( self ):\n        sd_implementation( self )\n\n    # TODO: left/right arrow to navigate\n\nif __name__ == '__main__':\n    arg_parser = ArgumentParser(description=\"Image Viewer\", formatter_class=RawTextHelpFormatter)\n    arg_parser.add_argument('file', type=str, nargs='?', help='Image file')\n    args = arg_parser.parse_args()\n\n    app = QApplication(sys.argv)\n    image_player = ImagePlayer()\n    extra = { 'danger': '#dc3545', 'warning': '#ffc107', 'success': '#17a2b8', 'font-family': 'Roboto', }\n    apply_stylesheet(app, 'light_cyan_500.xml', invert_secondary=True, extra=extra)\n\n    if args.file and not image_player.load_file(args.file):\n        sys.exit(-1)\n\n    image_player.show()\n    sys.exit(app.exec())\n\n\n", "meta": {"hexsha": "8a8dd6fafd06e8b982f81b40f59a094bddef8f09", "size": 33868, "ext": "py", "lang": "Python", "max_stars_repo_path": "apps/apps/denoising_stacked_images/stacked_denoising.py", "max_stars_repo_name": "fengwang/noise2predestination", "max_stars_repo_head_hexsha": "c4001472bab9a17a6f1d11d53036309234cc3e83", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "apps/apps/denoising_stacked_images/stacked_denoising.py", "max_issues_repo_name": "fengwang/noise2predestination", "max_issues_repo_head_hexsha": "c4001472bab9a17a6f1d11d53036309234cc3e83", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "apps/apps/denoising_stacked_images/stacked_denoising.py", "max_forks_repo_name": "fengwang/noise2predestination", "max_forks_repo_head_hexsha": "c4001472bab9a17a6f1d11d53036309234cc3e83", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5476718404, "max_line_length": 182, "alphanum_fraction": 0.6508208338, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.17655183287554302}}
{"text": "import os\nimport shutil\nimport pandas as pd\nimport numpy as np\nimport time\nimport multiprocessing as mp\nimport astropy.coordinates as astroCoords\nimport astropy.units as u\nimport csv\nimport trajectoryFiltering as tf\nfrom kbmodpy import kbmod as kb\nfrom astropy.io import fits\nfrom astropy.wcs import WCS\nfrom sklearn.cluster import DBSCAN\nfrom skimage import measure\nfrom analysis_utils import analysis_utils, \\\n    return_indices, stamp_filter_parallel\nfrom collections import OrderedDict\n\n\nclass run_search(analysis_utils):\n\n    def __init__(self, v_list, ang_list, num_obs):\n\n        \"\"\"\n        Input\n        --------\n\n        v_list : list\n\n            [min_velocity, max_velocity, velocity_steps]\n\n        ang_list: list\n\n            [radians below ecliptic,\n             radians above ecliptic,\n             steps]\n\n        num_obs : integer\n\n            Number of images a trajectory must be unmasked.\n        \"\"\"\n        \n        self.v_arr = np.array(v_list)\n        self.ang_arr = np.array(ang_list)\n        self.num_obs = num_obs\n\n        return\n\n    def run_search(self, im_filepath, res_filepath, out_suffix, time_file,\n                   likelihood_level=10., mjd_lims=None, num_fakes=25,\n                   rand_seed=42):\n\n        visit_nums, visit_times = np.genfromtxt(time_file, unpack=True)\n        image_time_dict = OrderedDict()\n        for visit_num, visit_time in zip(visit_nums, visit_times):\n            image_time_dict[str(int(visit_num))] = visit_time\n\n        chunk_size = 100000\n\n        start = time.time()\n        \n        patch_visits = sorted(os.listdir(im_filepath))\n        patch_visit_ids = np.array([int(visit_name[1:7]) for visit_name in patch_visits])\n        patch_visit_times = np.array([image_time_dict[str(visit_id)] for visit_id in patch_visit_ids])\n\n        if mjd_lims is None:\n            use_images = patch_visit_ids\n        else:\n            visit_only = np.where(((patch_visit_times > mjd_lims[0])\n                                   & (patch_visit_times < mjd_lims[1])))[0]\n            print(visit_only)\n            use_images = patch_visit_ids[visit_only]\n\n        image_mjd = np.array([image_time_dict[str(visit_id)] for visit_id in use_images])\n        times = image_mjd - image_mjd[0]\n\n        flags = ~0 # mask pixels with any flags\n        flag_exceptions = [32,39] # unless it has one of these special combinations of flags\n        master_flags = int('100111', 2) # mask any pixels which have any of \n        # these flags in more than two images\n            \n        hdulist = fits.open('%s/v%i-fg.fits' % (im_filepath, use_images[0]))\n        f0 = hdulist[0].header['FLUXMAG0']\n        w = WCS(hdulist[1].header)\n        ec_angle = self.calc_ecliptic_angle(w)\n        del(hdulist)\n\n        images = [kb.layered_image('%s/v%i-fg.fits' % (im_filepath, f)) for f in np.sort(use_images)]\n        print('Images Loaded')\n\n        p = kb.psf(1.4)\n\n        # Add fakes steps\n        print('Adding fake objects')\n        x_fake_range = (5, 3650)\n        y_fake_range = (5, 3650)\n        angle_range = (ec_angle-(np.pi/15.), ec_angle+(np.pi/15.))\n        velocity_range = (100, 500)\n        mag_range = (20, 26)\n\n        fake_results = []\n        fake_output = []\n\n        np.random.seed(rand_seed)\n        for val in range(num_fakes):\n            traj = kb.trajectory()\n            traj.x = int(np.random.uniform(*x_fake_range))\n            traj.y = int(np.random.uniform(*y_fake_range))\n            ang = np.random.uniform(*angle_range)\n            vel = np.random.uniform(*velocity_range)\n            traj.x_v = vel*np.cos(ang)\n            traj.y_v = vel*np.sin(ang)\n            mag_val = np.random.uniform(*mag_range)\n            traj.flux = f0*np.power(10, -0.4*mag_val)\n            fake_results.append(traj)\n            fake_output.append([traj.x, traj.y, traj.x_v, traj.y_v, traj.flux, mag_val])\n\n        for fake_obj in fake_results:\n            tf.add_trajectory(images, fake_obj, p, times)\n        \n        stack = kb.image_stack(images)\n        del(images)\n        stack.apply_mask_flags(flags, flag_exceptions)\n        stack.apply_master_mask(master_flags, 2)\n            \n        stack.grow_mask()\n        stack.grow_mask()\n\n        # stack.apply_mask_threshold(120.)\n\n        stack.set_times(times)\n        print(\"Times set\")\n        x_size = stack.get_width()\n        y_size = stack.get_width()\n        \n        search = kb.stack_search(stack, p)\n        del(stack)\n        ang_min = ec_angle - self.ang_arr[0]\n        ang_max = ec_angle + self.ang_arr[1]\n        vel_min = self.v_arr[0]\n        vel_max = self.v_arr[1]\n        print(\"Starting Search\")\n        print('---------------------------------------')\n        param_headers = (\"Ecliptic Angle\", \"Min. Search Angle\", \"Max Search Angle\",\n                         \"Min Velocity\", \"Max Velocity\")\n        param_values = (ec_angle, ang_min, ang_max, vel_min, vel_max)\n        for header, val in zip(param_headers, param_values):\n            print('%s = %.4f' % (header, val))\n        search.gpu(int(self.ang_arr[2]),int(self.v_arr[2]),ang_min,ang_max,\n                   vel_min,vel_max,int(self.num_obs))\n\n        keep_stamps = []\n        keep_snr = []\n        keep_new_lh = []\n        keep_results = []\n        keep_times = []\n        memory_error = False\n        keep_lc = []\n        filter_stats = np.zeros(4)\n            \n        likelihood_limit = False\n        res_num = 0\n        chunk_size = 500000\n        print('---------------------------------------')\n        print(\"Processing Results\")\n        print('---------------------------------------')\n        while likelihood_limit is False:\n            pool = mp.Pool(processes=16)\n            results = search.get_results(res_num,chunk_size)\n            chunk_headers = (\"Chunk Start\", \"Chunk Size\", \"Chunk Max Likelihood\",\n                             \"Chunk Min. Likelihood\")\n            chunk_values = (res_num, len(keep_results), results[0].lh, results[-1].lh)\n            for header, val, in zip(chunk_headers, chunk_values):\n                if type(val) == np.int:\n                    print('%s = %i' % (header, val))\n                else:\n                    print('%s = %.2f' % (header, val))\n            print('---------------------------------------')\n            psi_curves = []\n            phi_curves = []\n            for line in results:\n                psi_curve, phi_curve = search.lightcurve(line)\n                psi_curves.append(np.array(psi_curve).flatten())\n                phi_curve = np.array(phi_curve).flatten()\n                phi_curve[phi_curve == 0.] = 99999999.\n                phi_curves.append(phi_curve)\n                if line.lh < likelihood_level:\n                    likelihood_limit = True\n                    break\n            keep_idx_results = pool.starmap_async(return_indices,\n                                                  zip(psi_curves, phi_curves,\n                                                      [j for j in range(len(psi_curves))]))\n            pool.close()\n            pool.join()\n            keep_idx_results = keep_idx_results.get()\n            \n                \n            filter_stats[0] += len(psi_curves)\n            if len(keep_idx_results[0]) < 3:\n                keep_idx_results = [(0, [-1], 0.)]\n                    \n            for result_on in range(len(psi_curves)):\n                if keep_idx_results[result_on][1][0] == -1:\n                    continue\n                elif len(keep_idx_results[result_on][1]) < 3:\n                    continue\n                elif keep_idx_results[result_on][2] < likelihood_level:\n                    continue\n                else:\n                    keep_idx = keep_idx_results[result_on][1]\n                    new_likelihood = keep_idx_results[result_on][2]\n                    keep_results.append(results[result_on])\n                    keep_new_lh.append(new_likelihood)\n                    stamps = search.sci_stamps(results[result_on], 10)\n                    stamp_arr = np.array([np.array(stamps[s_idx]) for s_idx in keep_idx])\n                    keep_stamps.append(np.sum(stamp_arr, axis=0))\n                    keep_lc.append((psi_curves[result_on]/phi_curves[result_on])[keep_idx])\n                    keep_snr.append((psi_curves[result_on]/np.sqrt(phi_curves[result_on]))[keep_idx])\n                    #keep_times.append(image_mjd[keep_idx])\n                    keep_times.append(keep_idx)\n\n            # if len(keep_results) > 800000:\n            #     with open('%s/memory_error_tr_%s.txt' %\n            #               (res_filepath, out_suffix), 'w') as f:\n            #         f.write('In %i total results, %i were kept. Needs manual look.' %\n            #                 (res_num + chunk_size, len(keep_results)))\n            #     memory_error = True\n            #     likelihood_limit = True\n                    \n            # if res_num+chunk_size >= 8000000:\n            #     likelihood_level = 20.\n            #     with open('%s/overload_error_tr_%s.txt' %\n            #               (res_filepath, out_suffix), 'w') as f:\n            #         f.write('In %i total results, %i were kept. Likelihood level down to %f.' %\n            #                 (res_num + chunk_size, len(keep_results), line.lh))\n\n            res_num += chunk_size\n\n        del(search)\n\n        lh_sorted_idx = np.argsort(np.array(keep_new_lh))[::-1]\n        filter_stats[1] = len(lh_sorted_idx)\n\n        if len(lh_sorted_idx) > 0:\n            print(\"Stamp filtering %i results\" % len(lh_sorted_idx))\n            pool = mp.Pool(processes=16)\n            stamp_filt_pool = pool.map_async(stamp_filter_parallel,\n                                             np.array(keep_stamps)[lh_sorted_idx])\n            pool.close()\n            pool.join()\n            stamp_filt_results = stamp_filt_pool.get()\n            stamp_filt_idx = lh_sorted_idx[np.where(np.array(stamp_filt_results) == 1)]\n            filter_stats[2] = len(stamp_filt_idx)\n            if len(stamp_filt_idx) > 0:\n                print(\"Clustering %i results\" % len(stamp_filt_idx))\n                cluster_idx = self.cluster_results(np.array(keep_results)[stamp_filt_idx],\n                                                   x_size, y_size, [vel_min, vel_max],\n                                                   [ang_min, ang_max])\n                final_results = stamp_filt_idx[cluster_idx]\n            else:\n                cluster_idx = []\n                final_results = []\n            del(cluster_idx)\n            del(stamp_filt_results)\n            del(stamp_filt_idx)\n            del(stamp_filt_pool)\n        else:\n            final_results = lh_sorted_idx            \n\n        print('Keeping %i results' % len(final_results))\n        filter_stats[3] = len(final_results)\n        \n        np.savetxt('%s/results_%s.txt' % (res_filepath, out_suffix),\n                   np.array(keep_results)[final_results], fmt='%s')\n        np.savetxt('%s/results_fakes_%s.txt' % (res_filepath, out_suffix),\n                   np.array(fake_output), header='x,y,xv,yv,flux,mag')\n        # np.savetxt('%s/lc_%s.txt' % (res_filepath, out_suffix),\n        #            np.array(keep_lc)[final_results], fmt='%s')\n        with open('%s/lc_%s.txt' % (res_filepath, out_suffix), 'w') as f:\n            writer = csv.writer(f)\n            writer.writerows(np.array(keep_lc)[final_results])\n        with open('%s/snr_%s.txt' % (res_filepath, out_suffix), 'w') as f:\n            writer = csv.writer(f)\n            writer.writerows(np.array(keep_snr)[final_results])\n        # np.savetxt('%s/times_%s.txt' % (res_filepath, out_suffix),\n        #            np.array(keep_times)[final_results], fmt='%s')\n        with open('%s/times_%s.txt' % (res_filepath, out_suffix), 'w') as f:\n            writer = csv.writer(f)\n            writer.writerows(np.array(keep_times)[final_results])\n        np.savetxt('%s/filtered_likes_%s.txt' % (res_filepath, out_suffix),\n                   np.array(keep_new_lh)[final_results], fmt='%.4f')\n        np.savetxt('%s/ps_%s.txt' % (res_filepath, out_suffix),\n                   np.array(keep_stamps).reshape(len(keep_stamps), 441)[final_results], fmt='%.4f')\n        np.savetxt('%s/filt_stats_%s.txt' % (res_filepath, out_suffix), np.array(filter_stats), fmt='%i')\n\n        end = time.time()\n\n        del(keep_stamps)\n        del(keep_times)\n        del(keep_results)\n        del(keep_new_lh)\n        del(keep_lc)\n                \n        print(\"Time taken for patch: \", end-start)\n", "meta": {"hexsha": "2e87e3a8f48f5dcc5966d33083d98d7896baeb0c", "size": 12449, "ext": "py", "lang": "Python", "max_stars_repo_path": "analysis/fake_search.py", "max_stars_repo_name": "fraserw/kbmod", "max_stars_repo_head_hexsha": "65d69746d1dd8de867f8da147d73c09439d28b41", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2018-07-23T11:39:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T17:15:42.000Z", "max_issues_repo_path": "analysis/fake_search.py", "max_issues_repo_name": "fraserw/kbmod", "max_issues_repo_head_hexsha": "65d69746d1dd8de867f8da147d73c09439d28b41", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2017-06-19T22:55:41.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-15T02:49:39.000Z", "max_forks_repo_path": "analysis/fake_search.py", "max_forks_repo_name": "fraserw/kbmod", "max_forks_repo_head_hexsha": "65d69746d1dd8de867f8da147d73c09439d28b41", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-07-23T11:39:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T18:43:02.000Z", "avg_line_length": 40.6830065359, "max_line_length": 105, "alphanum_fraction": 0.5463892682, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 2838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.2598256436924554, "lm_q1q2_score": 0.17646804269545102}}
{"text": "#! /opt/conda/bin/python3\n\"\"\" Pipe class implementing the actual pipe simulation calculations \"\"\"\n\n# Copyright 2019 FAU-iPAT (http://ipat.uni-erlangen.de/)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom typing import Optional\nimport numpy as np\nfrom .base_pipe import BasePipe\nfrom ..base.connectors.connector import Connector\nfrom ..measure import Measure\nfrom ..base.channels.import_channel import ImportChannel\nfrom ..base.channels.export_channel import ExportChannel\n\n\nclass Pipe(BasePipe):  # pylint: disable=too-many-instance-attributes\n    \"\"\"\n    Pipe class implementing the pipe simulation calculations\n    \"\"\"\n\n    def __init__(\n            self,\n            diameter: float,\n            length: float,\n            wall_thickness: float,\n            bulk_modulus: float,\n            roughness: float,\n            inner_points: int = None,\n    ) -> None:\n        \"\"\"\n        Initialization of the class\n\n        :param diameter: Diameter of the fluid volume [m]\n        :param length: Length of the pipe [m]\n        :param wall_thickness: Thickness of the wall [m]\n        :param bulk_modulus: Bulk modulus of wall material [Pa]\n        :param roughness: Roughness of the wall [m]\n        :param inner_points: Minimal number of inner points for discretization\n        :raises TypeError: Wrong type of at least one parameter\n        :raises ValueError: Value of at least one parameter out of bounds\n        \"\"\"\n        super(Pipe, self).__init__(diameter, length, wall_thickness, bulk_modulus, roughness)\n        if inner_points is not None and not isinstance(inner_points, int):\n            raise TypeError('Wrong type for parameter inner_points ({} != {})'.format(type(inner_points), int))\n        if inner_points is not None and inner_points < 3:\n            raise ValueError('Number of inner points ({}) needs to greater than 2!'.format(inner_points))\n        # Register internal fields\n        self._inner_points = inner_points\n        self._pressure: np.ndarray = self.field_create('pressure', 3)\n        self._velocity: np.ndarray = self.field_create('velocity', 3)\n        self.field_create('reynolds', 3)\n        self.field_create('brunone', 3)\n        self.field_create('darcy_friction_factor', 3)\n        self._friction_steady = self.field_create('friction_steady', 3)\n        self._friction_unsteady_a = self.field_create('friction_unsteady_a', 3)\n        self._friction_unsteady_b = self.field_create('friction_unsteady_b', 3)\n        self._sos: np.ndarray = self.field_create('speed_of_sound', 3)\n        # Create the left connector\n        self._left: Connector = Connector(self, [\n            ExportChannel(Measure.deltaX, lambda: self._delta_x),\n            ImportChannel(Measure.boundaryPoint, False),\n            ExportChannel(Measure.diameter, lambda: self.diameter),\n            ExportChannel(Measure.length, lambda: self.length),\n            ExportChannel(Measure.area, lambda: self.area),\n            ImportChannel(Measure.pressureLast, False),\n            ExportChannel(Measure.pressureCurrent, lambda: self._pressure[0, 1]),\n            ExportChannel(Measure.pressureLast, lambda: self._pressure[1, 1]),\n            ImportChannel(Measure.velocityPlusCurrent, False),\n            ImportChannel(Measure.velocityPlusLast, False),\n            ExportChannel(Measure.velocityMinusCurrent, lambda: -self._velocity[0, 1]),\n            ExportChannel(Measure.velocityMinusLast, lambda: -self._velocity[1, 1]),\n            ExportChannel(Measure.frictionCurrent, lambda: self._friction_steady[0, 1] + self._friction_unsteady_b[0, 1]),\n            ExportChannel(Measure.frictionLast, lambda: self._friction_steady[1, 1] + self._friction_unsteady_b[1, 1]),\n            ExportChannel(Measure.BPspeedOfSoundCurrent, lambda: self._sos[0, 0]),\n            ExportChannel(Measure.BPspeedOfSoundLast, lambda: self._sos[1, 0]),\n        ])\n        # Create the right connector\n        self._right: Connector = Connector(self, [\n            ExportChannel(Measure.deltaX, lambda: self._delta_x),\n            ImportChannel(Measure.boundaryPoint, False),\n            ExportChannel(Measure.diameter, lambda: self.diameter),\n            ExportChannel(Measure.length, lambda: self.length),\n            ExportChannel(Measure.area, lambda: self.area),\n            ImportChannel(Measure.pressureLast, False),\n            ExportChannel(Measure.pressureCurrent, lambda: self._pressure[0, -2]),\n            ExportChannel(Measure.pressureLast, lambda: self._pressure[1, -2]),\n            ImportChannel(Measure.velocityMinusCurrent, False),\n            ImportChannel(Measure.velocityMinusLast, False),\n            ExportChannel(Measure.velocityPlusCurrent, lambda: self._velocity[0, -2]),\n            ExportChannel(Measure.velocityPlusLast, lambda: self._velocity[1, -2]),\n            ExportChannel(Measure.frictionCurrent, lambda: self._friction_steady[0, -2] + self._friction_unsteady_a[0, -2]),\n            ExportChannel(Measure.frictionLast, lambda: self._friction_steady[1, -2] + self._friction_unsteady_a[1, -2]),\n            ExportChannel(Measure.BPspeedOfSoundCurrent, lambda: self._sos[0, -1]),\n            ExportChannel(Measure.BPspeedOfSoundLast, lambda: self._sos[1, -1]),\n        ])\n\n    @property\n    def left(self) -> Connector:\n        \"\"\"\n        Left connector property\n\n        :return: Left sided connector of the pipe\n        \"\"\"\n        return self._left\n\n    @property\n    def right(self) -> Connector:\n        \"\"\"\n        Right connector property\n\n        :return: Right sided connector of the pipe\n        \"\"\"\n        return self._right\n\n    def get_max_delta_t(self) -> Optional[float]:\n        \"\"\"\n        Method to return the maximum allowed timestep width for this component\n\n        :return: Maximum allowed timestep width or None if any is suitable\n        \"\"\"\n        n_min = self._inner_points if self._inner_points is not None else 3\n        result = self.length / ((n_min + 1) * self.norm_speed_of_sound)\n        return result\n\n    def discretize(self, delta_t: float) -> None:\n        \"\"\"\n        Method handling the discretization of the component (for a given timestep width)\n\n        :param delta_t: Timestep width to discretize for\n        :raises ValueError: Timestep too large to fit at least 3 inner points\n        \"\"\"\n        self._delta_t = delta_t\n        nodes = int(np.ceil(self.length / (self.norm_speed_of_sound * delta_t)) - 1)\n        if nodes < 3:\n            raise ValueError('Timestep to large!')\n        self._delta_x = self.length / float(nodes + 1)\n        self.fields_resize(nodes + 2)\n\n    def initialize(self) -> None:\n        \"\"\"\n        Initialize the internal state of the component (after discretization was called)\n        \"\"\"\n        self.field('velocity')[:, :] = np.zeros(self.field('velocity').shape)[:, :]\n        self.field('pressure')[:, :] = self.fluid.norm_pressure * np.ones(self.field('pressure').shape)[:, :]\n        # Initialize derived properties\n        for _ in range(2):\n            self._calculate_reynolds()\n            self._calculate_friction()\n            self._calculate_speed_of_sound()\n            self.fields_move()\n\n    def prepare_next_timestep(self, delta_t: float, next_total_time: float) -> None:\n        \"\"\"\n        Prepare the internal state for the next timestep to be calculated\n\n        :param delta_t: Timestep width for the next timestep\n        :param next_total_time: Total simulation time at the end of the next timestep\n        \"\"\"\n        # Shift all internal fields\n        self.fields_move()\n\n    def exchange_last_boundaries(self) -> None:\n        \"\"\"\n        Exchange the boundary values from the last time steps\n        \"\"\"\n        # Exchange previous values with the left boundary\n        self._pressure[1, 0] = self.left.value(Measure.pressureLast)\n        self._velocity[1, 0] = self.left.value(Measure.velocityPlusLast)\n        # Exchange previous values with the right boundary\n        self._pressure[1, -1] = self.right.value(Measure.pressureLast)\n        self._velocity[1, -1] = -self.right.value(Measure.velocityMinusLast)\n\n    def finalize_current_timestep(self) -> None:\n        \"\"\"\n        Method to perform final calculations at the end of the current timestep\n        \"\"\"\n        # Exchange current values\n        self._velocity[0, 0] = self.left.value(Measure.velocityPlusCurrent)\n        self._velocity[0, -1] = -self.right.value(Measure.velocityMinusCurrent)\n        # Calculate static values\n        self._calculate_reynolds()\n        self._calculate_friction()\n        self._calculate_speed_of_sound()\n\n    def prepare_next_inner_iteration(self, iteration: int) -> None:\n        \"\"\"\n        Method to prepare the internal state for the next inner iteration of the current timestep\n\n        :param iteration: Number of the next inner iteration to prepare for\n        \"\"\"\n\n    def exchange_current_boundaries(self) -> None:\n        \"\"\"\n        Exchange boundary values from the current time step\n        \"\"\"\n\n    def calculate_next_inner_iteration(self, iteration: int) -> bool:\n        \"\"\"\n        Method to do the calculations of the next inner iteration\n\n        :param iteration: Number of the next inner iteration\n        :return: Whether this component needs another inner iteration afterwards\n        \"\"\"\n        self._calculate_pressure()\n        self._calculate_velocity()\n        return False\n\n    def _calculate_speed_of_sound(self) -> None:\n        \"\"\"\n        Calculate the current speed of sound\n        \"\"\"\n        pressure = self.field_wide_slice('pressure', 0)\n        result = self.speed_of_sound(pressure=pressure, temperature=None)\n        self.field_wide_slice('speed_of_sound', 0)[:] = result[:]\n\n    def _calculate_reynolds(self) -> None:\n        \"\"\"\n        Calculate the Reynolds number based on the values from the previous time step\n        \"\"\"\n        # Get the input fields\n        pressure = self.field_wide_slice('pressure', 0)\n        velocity = self.field_wide_slice('velocity', 0)\n        # Calculate fluid properties\n        viscosity = self.fluid.viscosity(temperature=None, shear_rate=None)\n        density = self.fluid.density(pressure=pressure, temperature=None)\n        # Calculate the reynolds number\n        result = (density * np.abs(velocity) * self.diameter) / viscosity\n        # Store/return the calculated result\n        self.field_wide_slice('reynolds', 0)[:] = result[:]\n\n    def _calculate_darcy_friction_factor(self) -> None:\n        \"\"\"\n        Calculates darcy's friction coefficient within the pipe\n        \"\"\"\n        # Get the input fields\n        reynolds = self.field_wide_slice('reynolds', 0)\n        result = np.ones(reynolds.shape)\n        # Calculate the friction factor (low Re)\n        selector = np.logical_and(reynolds > 0.0, reynolds < 2100.0)\n        if np.sum(selector) > 0:\n            local_reynolds = reynolds[selector]\n            factor = 64.0 / local_reynolds\n            result[selector] = factor\n        # Calculate the friction factor (high Re)\n        selector = (reynolds >= 2100.0)\n        if np.sum(selector) > 0:\n            local_reynolds = reynolds[selector]\n            factor = 10.0 * np.ones(local_reynolds.shape)\n            error = np.ones(local_reynolds.shape)\n            while np.any(error > 1e-12):\n                term1 = self.roughness / (3.7 * self.diameter)\n                term2 = 2.51 / (local_reynolds * np.sqrt(factor))\n                temp = -2.0 * np.log10(term1 + term2)\n                old_factor, factor = factor, np.square(1.0 / temp)\n                error = np.abs(factor - old_factor)\n            result[selector] = factor\n        # Store/return the calculated result\n        self.field_wide_slice('darcy_friction_factor', 0)[:] = result[:]\n\n    def _calculate_friction_steady(self) -> None:\n        \"\"\"\n        Calculate the steady friction using darcy's factor\n        \"\"\"\n        # Get the input fields\n        velocity = self.field_wide_slice('velocity', 0)\n        friction_factor = self.field_wide_slice('darcy_friction_factor', 0)\n        # Calculate the friction\n        result = (friction_factor / (2.0 * self.diameter)) * np.abs(velocity) * velocity\n        # Store/return the calculated result\n        self.field_wide_slice('friction_steady', 0)[:] = result[:]\n\n    def _calculate_friction(self) -> None:\n        \"\"\"\n        Calculate the total friction (steady + unsteady)\n        \"\"\"\n        # Calculate steady friction\n        self._calculate_darcy_friction_factor()\n        self._calculate_friction_steady()\n        # Calculate unsteady friction\n        self._calculate_brunone()\n        self._calculate_unsteady_friction_a()\n        self._calculate_unsteady_friction_b()\n\n    def _calculate_pressure(self) -> None:\n        \"\"\"\n        Calculate the pressure of the current time step\n        \"\"\"\n        # Get the input fields\n        pressure_center = self.field_slice('pressure', 1, 0)\n        pressure_a = self.field_slice('pressure', 1, -1)\n        pressure_b = self.field_slice('pressure', 1, +1)\n        velocity_a = self.field_slice('velocity', 1, -1)\n        velocity_b = self.field_slice('velocity', 1, +1)\n        friction_a = self.field_slice('friction_steady', 1, -1) + self.field_slice('friction_unsteady_a', 1, -1)\n        friction_b = self.field_slice('friction_steady', 1, +1) + self.field_slice('friction_unsteady_b', 1, +1)\n        # Calculate fluid properties\n        speed_of_sound = self.speed_of_sound(pressure=pressure_center, temperature=None)\n        density = self.fluid.density(pressure=pressure_center, temperature=None)\n        # Calculate the reynolds number\n        result = 0.5 * (\n            (speed_of_sound * density * (velocity_a - velocity_b))\n            + (pressure_a + pressure_b)\n            + (self._delta_t * speed_of_sound * density * (friction_b - friction_a))\n            # todo: height terms\n        )\n        # Store/return the calculated result\n        self.field_slice('pressure', 0, 0)[:] = result[:]\n\n    def _calculate_velocity(self) -> None:\n        \"\"\"\n        Calculate the velocity of the current time step\n        \"\"\"\n        # Get the input fields\n        pressure_center = self.field_slice('pressure', 1, 0)\n        pressure_a = self.field_slice('pressure', 1, -1)\n        pressure_b = self.field_slice('pressure', 1, +1)\n        velocity_a = self.field_slice('velocity', 1, -1)\n        velocity_b = self.field_slice('velocity', 1, +1)\n        friction_a = self.field_slice('friction_steady', 1, -1) + self.field_slice('friction_unsteady_a', 1, -1)\n        friction_b = self.field_slice('friction_steady', 1, +1) + self.field_slice('friction_unsteady_b', 1, +1)\n        # Calculate fluid properties\n        speed_of_sound = self.speed_of_sound(pressure=pressure_center, temperature=None)\n        density = self.fluid.density(pressure=pressure_center, temperature=None)\n        # Calculate the reynolds number\n        result = 0.5 * (\n            (velocity_a + velocity_b)\n            + ((1.0 / (speed_of_sound * density)) * (pressure_a - pressure_b))\n            - (self._delta_t * (friction_a + friction_b))\n            # todo: height terms\n        )\n        # Store/return the calculated result\n        self.field_slice('velocity', 0, 0)[:] = result[:]\n\n    def _calculate_brunone(self) -> None:\n        \"\"\"\n        Calculate the Brunone factor for unsteady friction\n        \"\"\"\n        # Get the input fields\n        reynolds = self.field_wide_slice('reynolds', 0)\n        # Calculate the Brunone factor\n        result = 0.000476 * np.ones(reynolds.shape)\n        selector = (reynolds >= 2320.0)\n        if np.sum(selector) > 0:\n            local_reynolds = reynolds[selector]\n            factor = 14.3 / np.power(local_reynolds, 0.05)\n            factor = 7.41 / np.power(local_reynolds, np.log10(factor))\n            result[selector] = factor\n        result = np.sqrt(result) / 2.0\n        # Store/return the calculated result\n        self.field_wide_slice('brunone', 0)[:] = result[:]\n\n    def _calculate_unsteady_friction_a(self) -> None:\n        \"\"\"\n        Calculate the unsteady friction to left side\n        \"\"\"\n        # Get the input fields\n        brunone = self.field_ext_slice('brunone', 0, 0)\n        velocity_a = self.field_ext_slice('velocity', 0, 0)\n        velocity_aa = self.field_ext_slice('velocity', 1, 0)\n        velocity_p = self.field_ext_slice('velocity', 0, 1)\n        pressure_a = self.field_ext_slice('pressure', 0, 0)\n        # Calculate fluid properties\n        speed_of_sound = self.speed_of_sound(pressure=pressure_a, temperature=None)\n        # Calculate the friction\n        vdt = (velocity_a - velocity_aa) / self._delta_t\n        vdx = (velocity_p - velocity_a) / self._delta_x\n        result = brunone * (vdt + (speed_of_sound * np.sign(velocity_a * vdx) * vdx))\n        # Store/return the calculated result\n        self.field_ext_slice('friction_unsteady_a', 0, 0)[:] = result[:]\n\n    def _calculate_unsteady_friction_b(self) -> None:\n        \"\"\"\n        Calculate the unsteady friction to right side\n        \"\"\"\n        # Get the input fields\n        brunone = self.field_ext_slice('brunone', 0, 1)\n        velocity_b = self.field_ext_slice('velocity', 0, 1)\n        velocity_bb = self.field_ext_slice('velocity', 1, 1)\n        velocity_p = self.field_ext_slice('velocity', 0, 0)\n        pressure_b = self.field_ext_slice('pressure', 0, 1)\n        # Calculate fluid properties\n        speed_of_sound = self.speed_of_sound(pressure=pressure_b, temperature=None)\n        # Calculate the friction\n        vdt = (velocity_b - velocity_bb) / self._delta_t\n        vdx = (velocity_b - velocity_p) / self._delta_x\n        result = brunone * (vdt + (speed_of_sound * np.sign(velocity_b * vdx) * vdx))\n        # Store/return the calculated result\n        self.field_ext_slice('friction_unsteady_b', 0, 1)[:] = result[:]\n", "meta": {"hexsha": "9ce46e0d39465658d9099989ec3205caa81a1213", "size": 18271, "ext": "py", "lang": "Python", "max_stars_repo_path": "cavsim/pipes/pipe.py", "max_stars_repo_name": "DHaspel/cavsim", "max_stars_repo_head_hexsha": "a23e344b47b970e1a90e04c071e06860935d1694", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cavsim/pipes/pipe.py", "max_issues_repo_name": "DHaspel/cavsim", "max_issues_repo_head_hexsha": "a23e344b47b970e1a90e04c071e06860935d1694", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cavsim/pipes/pipe.py", "max_forks_repo_name": "DHaspel/cavsim", "max_forks_repo_head_hexsha": "a23e344b47b970e1a90e04c071e06860935d1694", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.5635910224, "max_line_length": 124, "alphanum_fraction": 0.6439713207, "include": true, "reason": "import numpy", "num_tokens": 4355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.3345894545235253, "lm_q1q2_score": 0.17643454791881116}}
{"text": "# vim: fdm=marker\n'''\nauthor:     Fabio Zanini/Richard Neher\ndate:       25/04/2015\ncontent:    Data access module HIV patients.\n'''\n# Modules\nimport numpy as np\nimport pandas as pd\nfrom Bio import SeqIO, AlignIO\nfrom .sequence import alpha, alphaa\nfrom .filenames import (get_custom_reference_filename,\n                        get_subtype_reference_alignment_filename,\n                        get_subtype_reference_allele_frequencies_filename)\n\n\nclass ReferenceTranslator(object):\n    \"\"\"docstring for ReferenceTranslater\"\"\"\n    def __init__(self, ref1='HXB2', ref2='NL4-3'):\n        super(ReferenceTranslator, self).__init__()\n        self.ref1 = ref1\n        self.ref2 = ref2\n\n        self.refseq1 = SeqIO.read(get_custom_reference_filename(self.ref1, format='gb'), format='genbank').seq\n        self.refseq2 = SeqIO.read(get_custom_reference_filename(self.ref2, format='gb'), format='genbank').seq\n\n        from seqanpy import align_global\n        (score, ali1, ali2) = align_global(str(self.refseq1), str(self.refseq2), band=200)\n        self.count1 = np.cumsum(np.fromstring(ali1,'S1')!='-')-1\n        self.count2 = np.cumsum(np.fromstring(ali2,'S1')!='-')-1\n\n    def translate(self, pos, ref=None):\n        if ref is None:\n            ref = self.ref1\n        if ref == self.ref1:\n            ii = np.searchsorted(self.count1,pos)\n            if ii<len(self.count2):\n                return self.ref2, self.count2[ii]\n            else:\n                return self.ref2, -1\n        elif ref ==self.ref2:\n            ii = np.searchsorted(self.count2,pos)\n            if ii<len(self.count1):\n                return self.ref1, self.count1[ii]\n            else:\n                return self.ref1, -1\n        else:\n            print(\"unknown reference\", ref)\n            return \"not found\", np.nan\n\n\n\nclass HIVreference(object):\n    \"\"\"docstring for HIVreference\"\"\"\n    def __init__(self, refname='HXB2', subtype='B', load_alignment=True):\n        self.refname = refname\n        self.subtype = subtype\n        self.seq = SeqIO.read(get_custom_reference_filename(self.refname, format='gb'), format='genbank')\n        # translate genbank encoded sequence features into a dictionary\n        self.annotation = {x.qualifiers['note'][-1]:x for x in self.seq.features}\n\n        if load_alignment:\n            fn = get_subtype_reference_alignment_filename(subtype=subtype,\n                                                          refname=refname)\n            self.aln = np.array(AlignIO.read(fn, 'fasta'))\n            self.calc_nucleotide_frequencies()\n\n        else:\n            fn = get_subtype_reference_allele_frequencies_filename(subtype=subtype,\n                                                                   refname=refname)\n            self.af = np.load(fn)\n\n        self.consensus_indices = np.argmax(self.af, axis=0)\n        self.consensus = alpha[self.consensus_indices]\n        self.calc_entropy()\n\n\n    def calc_nucleotide_frequencies(self):\n        self.af = np.zeros((len(alpha)-1, self.aln.shape[1]), dtype=float)\n        for ni, nuc in enumerate(alpha[:-1]):\n            self.af[ni,:] = np.sum(self.aln==nuc.astype(\"U1\"), axis=0)\n        cov = np.sum(self.af, axis=0)\n        self.af /= cov + 1e-10\n\n\n    def calc_entropy(self):\n        self.entropy = np.maximum(0,-np.sum(self.af*np.log(1e-10+self.af), axis=0))\n\n\n    def map_to_sequence_collection():\n        pass\n\n\n    def get_ungapped(self, threshold=0.05):\n        return self.af[-1,:] < 0.05\n\n\n    def get_entropy_quantiles(self, q):\n        from scipy.stats import scoreatpercentile\n        thresholds = [scoreatpercentile(self.entropy, 100.0*i/q) for i in range(q+1)]\n        return {i: {'range':(thresholds[i],thresholds[i+1]),\n                    'ind':np.where((self.entropy>=thresholds[i])*(self.entropy<thresholds[i+1]))[0]}\n               for i in range(q)}\n\n\n    def get_entropy_in_patient_region(self, map_to_ref):\n        '''\n        returns entropy in a specific regions defined by a set of indices in the reference\n        params:\n        map_to_ref  --  either a one dimensional vector specifying indices in the reference\n                        or a (3, len(region)) array with the reference coordinates in the first column\n                        this is the output of Patient.map_to_external_reference\n        '''\n        if len(map_to_ref.shape) == 2:\n            return self.entropy[map_to_ref[:, 0]]\n        elif len(map_to_ref.shape) == 1:\n            return self.entropy[map_to_ref]\n\n\n    def get_consensus_in_patient_region(self, map_to_ref):\n        '''\n        returns consensus in a specific regions defined by a set of indices in the reference\n        params:\n        map_to_ref  --  either a one dimensional vector specifying indices in the reference\n                        or a (3, len(region)) array with the reference coordinates in the first column\n                        this is the output of Patient.map_to_external_reference\n        '''\n        if len(map_to_ref.shape) == 2:\n            return self.consensus[map_to_ref[:, 0]]\n        elif len(map_to_ref.shape) == 1:\n            return self.consensus[map_to_ref]\n\n\n    def get_consensus_indices_in_patient_region(self, map_to_ref):\n        '''\n        returns consensus_indices in a specific regions defined by a set of indices in the reference\n        params:\n        map_to_ref  --  either a one dimensional vector specifying indices in the reference\n                        or a (3, len(region)) array with the reference coordinates in the first column\n                        this is the output of Patient.map_to_external_reference\n        '''\n        if len(map_to_ref.shape) == 2:\n            return self.consensus_indices[map_to_ref[:, 0]]\n        elif len(map_to_ref.shape) == 1:\n            return self.consensus_indices[map_to_ref]\n\n\nclass HIVreferenceAminoacid(object):\n    def __init__(self, region, refname='HXB2', subtype='B'):\n        self.region = region\n        self.refname = refname\n        self.subtype = subtype\n\n        seq = SeqIO.read(get_custom_reference_filename(self.refname, format='gb'), format='genbank')\n        # translate genbank encoded sequence features into a dictionary\n        annotation = {x.qualifiers['note'][-1]:x for x in seq.features}\n        self.seq = annotation[region].extract(seq)\n\n        fn = get_subtype_reference_alignment_filename(region=region,\n                                                      refname=refname,\n                                                      subtype=self.subtype,\n                                                      type='aa')\n        self.aln = np.array(AlignIO.read(fn, 'fasta'))\n        self.calc_aminoacid_frequencies()\n\n        self.consensus_indices = np.argmax(self.af, axis=0)\n        self.consensus = alphaa[self.consensus_indices]\n        self.calc_entropy()\n\n\n    def calc_aminoacid_frequencies(self):\n        self.af = np.zeros((len(alphaa)-1, self.aln.shape[1]), dtype=float)\n        for ai, aa in enumerate(alphaa[:-1]):\n            self.af[ai,:] = np.sum(self.aln==aa, axis=0)\n        cov = np.sum(self.af, axis=0)\n        self.af /= cov\n\n\n    def calc_entropy(self):\n        self.entropy = np.maximum(0,-np.sum(self.af*np.log(1e-10+self.af), axis=0))\n\n\n    def get_ungapped(self, threshold=0.05):\n        return self.af[-1,:] < 0.05\n\n\n    def get_entropy_quantiles(self, q):\n        from scipy.stats import scoreatpercentile\n        thresholds = [scoreatpercentile(self.entropy, 100.0*i/q) for i in range(q+1)]\n        return {i: {'range':(thresholds[i],thresholds[i+1]),\n                    'ind':np.where((self.entropy>=thresholds[i])*(self.entropy<thresholds[i+1]))[0]}\n               for i in range(q)}\n\n\n    def get_entropy_in_patient_region(self, map_to_ref):\n        '''\n        returns entropy in a specific regions defined by a set of indices in the reference\n        params:\n        map_to_ref  --  either a one dimensional vector specifying indices in the reference\n                        or a (2, len(region)) array with the reference coordinates in the first column\n                        this is the output of Patient.map_to_external_reference_aminoacids\n        '''\n        if len(map_to_ref.shape) == 2:\n            return self.entropy[map_to_ref[:, 0]]\n        elif len(map_to_ref.shape) == 1:\n            return self.entropy[map_to_ref]\n\n\n    def get_consensus_in_patient_region(self, map_to_ref):\n        '''\n        returns consensus in a specific regions defined by a set of indices in the reference\n        params:\n        map_to_ref  --  either a one dimensional vector specifying indices in the reference\n                        or a (2, len(region)) array with the reference coordinates in the first column\n                        this is the output of Patient.map_to_external_reference_aminoacids\n        '''\n        if len(map_to_ref.shape) == 2:\n            return self.consensus[map_to_ref[:, 0]]\n        elif len(map_to_ref.shape) == 1:\n            return self.consensus[map_to_ref]\n\n\n    def get_consensus_indices_in_patient_region(self, map_to_ref):\n        '''\n        returns consensus_indices in a specific regions defined by a set of indices in the reference\n        params:\n        map_to_ref  --  either a one dimensional vector specifying indices in the reference\n                        or a (2, len(region)) array with the reference coordinates in the first column\n                        this is the output of Patient.map_to_external_reference_aminoacids\n        '''\n        if len(map_to_ref.shape) == 2:\n            return self.consensus_indices[map_to_ref[:, 0]]\n        elif len(map_to_ref.shape) == 1:\n            return self.consensus_indices[map_to_ref]\n", "meta": {"hexsha": "45d2e0a77464bafcb24bfbfdc0cbb1ff576bdc63", "size": 9663, "ext": "py", "lang": "Python", "max_stars_repo_path": "hivevo/HIVreference.py", "max_stars_repo_name": "neherlab/HIVEVO_access", "max_stars_repo_head_hexsha": "f732095eac730384a4d889a55723a839165a0657", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2016-03-23T07:21:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-23T05:29:23.000Z", "max_issues_repo_path": "hivevo/HIVreference.py", "max_issues_repo_name": "neherlab/HIVEVO_access", "max_issues_repo_head_hexsha": "f732095eac730384a4d889a55723a839165a0657", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-08-13T09:53:37.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-31T13:28:16.000Z", "max_forks_repo_path": "hivevo/HIVreference.py", "max_forks_repo_name": "neherlab/HIVEVO_access", "max_forks_repo_head_hexsha": "f732095eac730384a4d889a55723a839165a0657", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2015-09-15T09:34:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T14:56:09.000Z", "avg_line_length": 41.1191489362, "max_line_length": 110, "alphanum_fraction": 0.6103694505, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3345894478883556, "lm_q1q2_score": 0.17643454441997652}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Copyright 2018 University of Groningen\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom collections import defaultdict\nimport itertools\nimport networkx as nx\n\nfrom .utils import maxes, first_alpha\n\n\ndef add_element_attr(molecule):\n    for node_idx in molecule:\n        node = molecule.nodes[node_idx]\n        if 'element' not in node:\n            try:\n                element = first_alpha(node['atomname'])\n            except KeyError:\n                raise ValueError('Cannot guess the element of atom {}: '\n                                 'the node has no atom name.'\n                                 .format(node_idx))\n            except ValueError:\n                raise ValueError('Cannot guess the element of atom {}: '\n                                 'the atom name has no alphabetic charater.'\n                                 .format(node_idx))\n            node['element'] = element\n\n\ndef categorical_cartesian_product(graph1, graph2, attributes=tuple()):\n    product = nx.Graph()  # FIXME graphtype?\n    for idx1, idx2 in itertools.product(graph1, graph2):\n        node1 = graph1.nodes[idx1]\n        node2 = graph2.nodes[idx2]\n        if all(attr in node1 and attr in node2 and node1[attr] == node2[attr] for attr in attributes):\n            attrs = {}\n            for attr in set(node1.keys()) | set(node2.keys()):\n                attrs[attr] = (node1.get(attr, None), node2.get(attr, None))\n            product.add_node((idx1, idx2), **attrs)\n    return product\n\n\ndef categorical_modular_product(graph1, graph2, attributes=tuple()):\n    product = categorical_cartesian_product(graph1, graph2, attributes)\n    for (graph1_node1, graph2_node1), (graph1_node2, graph2_node2) in itertools.combinations(product.nodes(), 2):\n        graph1_nodes = graph1_node1, graph1_node2\n        graph2_nodes = graph2_node1, graph2_node2\n        both_edge = graph1.has_edge(*graph1_nodes) and graph2.has_edge(*graph2_nodes)\n        neither_edge = not graph1.has_edge(*graph1_nodes) and\\\n                       not graph2.has_edge(*graph2_nodes)\n        # Effectively: not (graph1.has_edge(graph1_node1, graph1_node2) xor graph2.has_edge(graph2_node1, graph2_node2))\n        if graph1_node1 != graph1_node2 and graph2_node1 != graph2_node2 and\\\n                (both_edge or neither_edge):\n            attrs = {}\n            if both_edge:\n                g1_edge_keys = set(graph1.edges[graph1_nodes].keys())\n                g2_edge_keys = set(graph2.edges[graph2_nodes].keys())\n                for attr in g1_edge_keys | g2_edge_keys:\n                    attrs[attr] = (graph1.edges[graph1_nodes].get(attr, None),\n                                   graph2.edges[graph2_nodes].get(attr, None))\n            product.add_edge((graph1_node1, graph2_node1), (graph1_node2, graph2_node2), **attrs)\n    return product\n\n\ndef categorical_maximum_common_subgraph(graph1, graph2, attributes=tuple()):\n    product = categorical_modular_product(graph1, graph2, attributes)\n    cliques = nx.find_cliques(product)\n    # cliques is an iterator which will return a *lot* of items. So make sure\n    # we never turn it into a full list.\n    largest = maxes(cliques, key=len)\n    matches = [dict(clique) for clique in largest]\n    return matches\n\n\ndef maximum_common_subgraph(graph1, graph2, attributes=tuple()):\n    product = nx.Graph()\n    # First, find the MCS between all nodes of degree != 1, such as the carbons\n    # Nothing new or exciting here.\n    for g1_node, g2_node in itertools.product(graph1, graph2):\n        node1 = graph1.nodes[g1_node]\n        node2 = graph2.nodes[g2_node]\n        if all(attr in node1 and attr in node2 and node1[attr] == node2[attr] for attr in attributes):\n            if graph1.degree(g1_node) != 1 and graph2.degree(g2_node) != 1:\n                product.add_node((g1_node, g2_node))\n    for (g1_node1, g2_node1), (g1_node2, g2_node2) in itertools.combinations(product.nodes(), 2):\n        both_edge = graph1.has_edge(g1_node1, g1_node2) and graph2.has_edge(g2_node1, g2_node2)\n        neither_edge = not graph1.has_edge(g1_node1, g1_node2) and not graph2.has_edge(g2_node1, g2_node2)\n        # Effectively: not (graph1.has_edge(g1_node1, g1_node2) xor graph2.has_edge(g2_node1, g2_node2))\n        if g1_node1 != g1_node2 and g2_node1 != g2_node2 and (both_edge or neither_edge):\n            product.add_edge((g1_node1, g2_node1), (g1_node2, g2_node2))\n    cliques = nx.find_cliques(product)\n#    largest = maxes(cliques, key=len)\n    # We can't do maxes, because it might still grow to be as large. Does make\n    # things slower though... We could say that it can grow to be at most the\n    # current size plus the number of degree-1 nodes.\n    largest = cliques\n\n    # Add an empty match in case nothing of degree > 1 matches. In that case we\n    # still need to do the loop below.\n    largest = itertools.chain([[]], largest)\n\n    # Now, for every MCS we found, look at the nodes of degree 1. The\n    # attributes still need to match. In addition, they need to have the same\n    # (mapped) neighbour, or the neighbour must be missing from the graph2 graph\n    all_cliques = []\n    for clique in largest:\n        match = dict(clique)\n        product = nx.Graph()\n        product.add_nodes_from(clique)\n        for g1_node, g2_node in itertools.product(graph1, graph2):\n            node1 = graph1.nodes[g1_node]\n            node2 = graph2.nodes[g2_node]\n            # We can't do this above, because we need the match to translate\n            # nodes from graph graph1 to graph graph2 to see whether their neighbours\n            # correspond.\n            if (graph1.degree(g1_node) <= 1 or graph2.degree(g2_node) <= 1) and\\\n                    all(attr in node1 and attr in node2 and node1[attr] == node2[attr] for attr in attributes):\n                g1_neighbors = [match.get(n, None) for n in graph1.neighbors(g1_node)]\n                # If no neighbors are found for g1_node, or if any of them are\n                # the same in graph2, they're compatible.\n\n                # FIXME?\n                # This eliminates some nodes from the MCS, since it's possible\n                # the MCS does not include *all* nodes in match. This means\n                # that some nodes should be considered compatible, even if they\n                # have different neighbours, but only if that neighbor is not\n                # part of the final MCS. This makes testing a little tricky,\n                # since categorical_maximum_common_subgraph *does* find them.\n                # It'll be a cornercase anyway.\n                if not g1_neighbors or None in g1_neighbors or any(n in g1_neighbors for n in graph2.neighbors(g2_node)):\n                    product.add_node((g1_node, g2_node))\n        for (g1_node1, g2_node1), (g1_node2, g2_node2) in itertools.combinations(product.nodes(), 2):\n            both_edge = graph1.has_edge(g1_node1, g1_node2) and graph2.has_edge(g2_node1, g2_node2)\n            neither_edge = not graph1.has_edge(g1_node1, g1_node2) and not graph2.has_edge(g2_node1, g2_node2)\n            # Effectively: not (graph1.has_edge(g1_node1, g1_node2) xor graph2.has_edge(g2_node1, g2_node2))\n            if g1_node1 != g1_node2 and g2_node1 != g2_node2 and (both_edge or neither_edge):\n                product.add_edge((g1_node1, g2_node1), (g1_node2, g2_node2))\n        # TODO: This duplicates a lot of effort. Maybe create the compatibility\n        # graph first from all cliques, and find the cliques only once?\n        this_pass = nx.find_cliques(product)\n        all_cliques.append(this_pass)\n    # And finally, find the largest MCS in all cliques graph2.\n    largest = maxes(itertools.chain(*all_cliques), key=len)\n    matches = set(frozenset(m) for m in largest)  # remove duplicates\n    matches = [dict(clique) for clique in matches]\n\n    return matches\n\n\ndef isomorphism(reference, residue):\n    \"\"\"\n    Finds matching atoms between ``reference`` and ``residue``. ``residue`` should be\n    a subgraph of ``reference``. Matchin is done based on connectivity and\n    the ``element`` attribute of the nodes.\n\n    The subgraph isomorphism is first calculated using non-hydrogen atoms only.\n    These matches are then extended to include one option for the hydrogen\n    isomorphism. This is done because otherwise a combinatorial problem is\n    created: take for example an alkane chain: the carbon atoms match in one\n    way. Then, for every :math:``CH_2`` group there are two, independent options\n    for the hydrogen isomorphism. This would result in :math:``2^n`` subgraph\n    isomorphisms for :math:``n`` carbon atoms.\n\n    This means that the matches found will not be optimal for the hydrogens.\n    This is acceptable, since hydrogrens are supposed to be equal. Let's say\n    you have some sort of chiral atom with two hydrogens: it's not chiral and\n    the hydrogen atoms are equal. Let's now say one of the two is a deuterium:\n    in that case you should have a proper 'element' header, and the subgraph\n    will be matched correctly.\n\n    Parameters\n    ----------\n    reference : networkx.Graph\n        The reference graph.\n    residue : networkx.Graph\n        The graph to match to ``reference``.\n    Returns\n    -------\n    matches : list[dict]\n        The matches found. The dictionaries have node indices of ``reference`` as\n        keys and node indices of ``residue`` as values. Is an empty list if\n        ``residue`` is not a subgraph of ``reference``.\n    \"\"\"\n    # TODO: refactor this thing to accept node and edge compatibility checkers\n    matches = []\n#    H_idxs = [idx for idx in residue if residue.node[idx]['element'] == 'H']\n    H_idxs = [idx for idx in residue if residue.degree(idx) == 1]\n    heavy_res = nx.Graph(residue).copy()\n    heavy_res.remove_nodes_from(H_idxs)\n\n#    ref_H_idxs = [idx for idx in reference if reference.degree(idx) == 1]\n#    heavy_ref = nx.Graph(reference).copy()\n#    heavy_ref.remove_nodes_from(ref_H_idxs)\n    # First, generate all the isomorphisms on heavy atoms. For each of these\n    # we'll find *something* where the hydrogens match.\n    GM = ElementGraphMatcher(reference, heavy_res)\n    first_matches = list(GM.subgraph_isomorphisms_iter())\n    for match in first_matches:\n        reverse_match = {v: k for k, v in match.items()}\n        for res_H_idx in H_idxs:\n            # We know which parent atom this hydrogen is bound to, and we know\n            # how it matches to the reference. We're going to find all the\n            # neighboring atoms of the reference parent, and see if the name\n            # of this hydrogen atom matches with any of those neighbors. If so,\n            # we extend the match that way.\n            # It should be noted that in exceptional cases where atomnames are\n            # very wrong, this might cause a problem?\n            res_neighbor = list(residue[res_H_idx].keys())[0]\n            if res_neighbor not in reverse_match:\n                continue\n            ref_neighbor = reverse_match[res_neighbor]\n            H_names = defaultdict(list)\n            for idx in reference[ref_neighbor]:\n                if reference.degree(idx) == 1:\n                    H_names[reference.nodes[idx]['atomname']].append(idx)\n            H_names = dict(H_names)\n            res_H_name = residue.nodes[res_H_idx]['atomname']\n            if res_H_name in H_names:\n                if len(H_names[res_H_name]) != 1:\n                    continue\n                ref_H_idx = H_names[res_H_name][0]\n                if ref_H_idx not in match and reference.nodes[ref_H_idx]['element'] == residue.nodes[res_H_idx]['element']:\n                    reverse_match[res_H_idx] = ref_H_idx\n                    match[ref_H_idx] = res_H_idx\n        GM_large = ElementGraphMatcher(reference, residue)\n        # Put the knowledge from the heavy atom isomorphism back in. Note that\n        # ElementGraphMatched is modified to enable this and is no longer\n        # re-entrant.\n        # Indices in match do not have to be changed to account for interlaced\n        # hydrogens: the node-indices in heavy_res and residue are the same.\n        GM_large.core_1 = match  # pylint: disable=attribute-defined-outside-init\n        GM_large.core_2 = reverse_match  # pylint: disable=attribute-defined-outside-init\n        outcome = GM_large.subgraph_isomorphisms_iter()\n        # Take just the first match found, otherwise it becomes a combinatorics\n        # problem (consider an alkane chain). This is fine though, since\n        # hydrogrens are supposed to be equal. Let's say you have some sort of\n        # chiral atom with two hydrogens: It's not chiral. Let's now say one of\n        # the two is a deuterium: in that case you should have a proper\n        # 'element' header, and the subgraph will be matched correctly.\n        # So worst case scenario we rename all hydrogens. This is acceptable\n        # since they're equal.\n        # And do islice since there may be none.\n        # This will fail for e.g. oxygens which have degree 1 in the reference,\n        # but are substituted with PTMs in the actual molecule. In that case\n        # the atomnames might be flipped, and make PTM identification\n        # troublesome. For example: C(=O)OH. That's why we extend the match to\n        # include degree-1 nodes above.\n        if match:\n            matches.extend(itertools.islice(outcome, 1))\n        else:\n            matches.extend(outcome)\n    matches = sorted(matches,\n                     key=lambda m: rate_match(reference, residue, m),\n                     reverse=True)\n    return matches\n\n\nclass ElementGraphMatcher(nx.isomorphism.GraphMatcher):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        super().initialize()\n\n    def initialize(self):\n        return\n\n    def semantic_feasibility(self, node1, node2):\n        # TODO: implement (partial) wildcards\n        elem1 = self.G1.node[node1]['element']\n        elem2 = self.G2.node[node2]['element']\n        return elem1 == elem2\n\n\ndef blockmodel(G, partitions, **attrs):\n    \"\"\"\n    Analogous to networkx.blockmodel, but can deal with incomplete partitions,\n    and assigns ``attrs`` to nodes.\n\n    Parameters\n    ----------\n    G: networkx.Graph\n        The graph to partition\n    parititions: collections.abc.Iterable[collections.abc.Iterable]\n        Each element contains the node indices that construct the new node.\n    **attrs: dict[str, collections.abc.Iterable]\n        Attributes to assign to new nodes. Attribute values are assigned to the\n        new nodes in order.\n\n    Returns\n    -------\n    networkx.Graph\n        A new graph where every node is a subgraph as specified by partitions.\n        Node attributes:\n\n            :graph: Subgraph of constructing nodes.\n            :nnodes: Number of nodes in ``graph``.\n            :nedges: Number of edges in ``graph``.\n            :density: Density of ``graph``.\n            :attrs.keys(): As specified by ``**attrs``.\n    \"\"\"\n    # TODO: Change this to use nx.quotient_graph.\n    attrs = {key: list(val) for key, val in attrs.items()}\n    CG_mol = nx.Graph()\n    for bead_idx, idxs in enumerate(partitions):\n        bd = G.subgraph(idxs)\n        CG_mol.add_node(bead_idx)\n        CG_mol.node[bead_idx]['graph'] = bd\n        # TODO: CoM instead of CoG\n#        CG_mol.node[bead_idx]['position'] = np.mean([bd.node[idx]['position'] for idx in bd], axis=0)\n        for k, vals in attrs.items():\n            CG_mol.node[bead_idx][k] = vals[bead_idx]\n\n        CG_mol.node[bead_idx]['nnodes'] = bd.number_of_nodes()\n        CG_mol.node[bead_idx]['nedges'] = bd.number_of_edges()\n        CG_mol.node[bead_idx]['density'] = nx.density(bd)\n\n    block_mapping = {}\n    for n in CG_mol:\n        nodes_in_block = CG_mol.node[n]['graph'].nodes()\n        block_mapping.update(dict.fromkeys(nodes_in_block, n))\n\n    for u, v, d in G.edges(data=True):\n        try:\n            bmu = block_mapping[u]\n            bmv = block_mapping[v]\n        except KeyError:\n            # Atom not represented\n            continue\n        if bmu == bmv:  # no self loops\n            continue\n        # For graphs and digraphs add single weighted edge\n        weight = d.get('weight', 1.0)  # default to 1 if no weight specified\n        if CG_mol.has_edge(bmu, bmv):\n            CG_mol[bmu][bmv]['weight'] += weight\n        else:\n            CG_mol.add_edge(bmu, bmv, weight=weight)\n    return CG_mol\n\n\ndef rate_match(residue, bead, match):\n    \"\"\"\n    A helper function which rates how well ``match`` describes the isomorphism\n    between ``residue`` and ``bead`` based on the number of matching atomnames.\n\n\n    Parameters\n    ----------\n    residue : networkx.Graph\n        A graph. Required node attributes:\n\n            :atomname: The name of an atom.\n\n    bead : networkx.Graph\n        A subgraph of ``residue`` where the isomorphism is described by ``match``.\n        Required node attributes:\n\n            :atomname: The name of an atom.\n\n\n    Returns\n    -------\n    int\n        The number of entries in match where the atomname in ``residue`` matches\n        the atomname in ``bead``.\n    \"\"\"\n    return sum(residue.node[rdx].get('atomname') == bead.node[bdx].get('atomname')\n               for rdx, bdx in match.items())\n\n\ndef make_residue_graph(mol):\n    \"\"\"\n    Creates a graph with one node per residue; as identified by the tuple\n    (chain identifier, residue index, residue name).\n\n    Parameters\n    ----------\n    mol: networkx.Graph\n        The atomistic graph. Required node attributes:\n\n            :chain: The chain identifier.\n            :resid: The residue index.\n            :resname: The residue name.\n\n    Returns\n    -------\n    networkx.Graph\n        A graph with one node per residue. Node attributes:\n\n            :chain: The chain identifier.\n            :graph: The atomistic subgraph.\n            :density: The density of ``graph``.\n            :nedges: The number of edges in ``graph``.\n            :nnodes: The number of nodes in ``graph``.\n            :resid: The residue index.\n            :resname: The residue name.\n            :atomname: The residue name.\n    \"\"\"\n    def keyfunc(node_idx):\n        return mol.node[node_idx]['chain'], mol.node[node_idx]['resid'], mol.node[node_idx]['resname']\n    nodes = sorted(mol.node, key=keyfunc)\n    keys = []\n    grps = []\n    for key, grp in itertools.groupby(nodes, keyfunc):\n        keys.append(key)\n        grps.append(list(grp))\n    if keys:\n        chain, resids, resnames = map(list, zip(*keys))\n    else:\n        chain, resids, resnames = [], [], []\n    res_graph = blockmodel(mol, grps, chain=chain, resid=resids,\n                           resname=resnames, atomname=resnames)\n    return res_graph\n", "meta": {"hexsha": "6db96bd8d1fafd51c0e407c0b69c6859f6e6216f", "size": 19182, "ext": "py", "lang": "Python", "max_stars_repo_path": "vermouth/graph_utils.py", "max_stars_repo_name": "fgrunewald/vermouth-martinize", "max_stars_repo_head_hexsha": "8b9b78207833b41b93ca3628730169a16b5f8410", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vermouth/graph_utils.py", "max_issues_repo_name": "fgrunewald/vermouth-martinize", "max_issues_repo_head_hexsha": "8b9b78207833b41b93ca3628730169a16b5f8410", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vermouth/graph_utils.py", "max_forks_repo_name": "fgrunewald/vermouth-martinize", "max_forks_repo_head_hexsha": "8b9b78207833b41b93ca3628730169a16b5f8410", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.3475177305, "max_line_length": 123, "alphanum_fraction": 0.6403920342, "include": true, "reason": "import networkx", "num_tokens": 4652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.33458945452352534, "lm_q1q2_score": 0.17643454294792116}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nfrom collections import OrderedDict\nimport numpy as np\nimport astropy.units as u\nfrom astropy.table import Table\nfrom astropy.time import Time\nfrom ..spectrum.utils import CountsPredictor\nfrom ..stats.poisson import excess_error\nfrom ..utils.scripts import make_path\n\n__all__ = [\n    'LightCurve',\n    'LightCurveEstimator',\n]\n\n\nclass LightCurve(object):\n    \"\"\"Lightcurve container.\n\n    The lightcurve data is stored in ``table``.\n\n    For now we only support times stored in MJD format!\n\n    TODO: specification of format is work in progress\n    See https://github.com/open-gamma-ray-astro/gamma-astro-data-formats/pull/61\n\n    Usage: :ref:`time-lc`\n\n    Parameters\n    ----------\n    table : `~astropy.table.Table`\n        Table with lightcurve data\n    \"\"\"\n\n    def __init__(self, table):\n        self.table = table\n\n    def __repr__(self):\n        return '{}(len={})'.format(self.__class__.__name__, len(self.table))\n\n    @property\n    def time_scale(self):\n        \"\"\"Time scale (str).\n\n        Taken from table \"TIMESYS\" header.\n        Common values: \"TT\" or \"UTC\".\n        Assumed default is \"UTC\".\n        \"\"\"\n        return self.table.meta.get('TIMESYS', 'utc')\n\n    @property\n    def time_format(self):\n        \"\"\"Time format (str).\"\"\"\n        return 'mjd'\n\n    # @property\n    # def time_ref(self):\n    #     \"\"\"Time reference (`~astropy.time.Time`).\"\"\"\n    #     return time_ref_from_dict(self.table.meta)\n\n    def _make_time(self, colname):\n        val = self.table[colname].data\n        scale = self.time_scale\n        format = self.time_format\n        return Time(val, scale=scale, format=format)\n\n    @property\n    def time(self):\n        \"\"\"Time (`~astropy.time.Time`).\"\"\"\n        return self._make_time('time')\n\n    @property\n    def time_min(self):\n        \"\"\"Time bin start (`~astropy.time.Time`).\"\"\"\n        return self._make_time('time_min')\n\n    @property\n    def time_max(self):\n        \"\"\"Time bin end (`~astropy.time.Time`).\"\"\"\n        return self._make_time('time_max')\n\n    @property\n    def time_mid(self):\n        \"\"\"Time bin center (`~astropy.time.Time`).\n\n        ::\n            time_mid = time_min + 0.5 * time_delta\n        \"\"\"\n        return self.time_min + 0.5 * self.time_delta\n\n    @property\n    def time_delta(self):\n        \"\"\"Time bin width (`~astropy.time.TimeDelta`).\n\n        ::\n            time_delta = time_max - time_min\n        \"\"\"\n        return self.time_max - self.time_min\n\n    @classmethod\n    def read(cls, filename, **kwargs):\n        \"\"\"Read from file.\n\n        Parameters\n        ----------\n        filename : str\n            Filename\n        kwargs : dict\n            Keyword arguments passed to `astropy.table.Table.read`.\n        \"\"\"\n        filename = make_path(filename)\n        table = Table.read(str(filename), **kwargs)\n        return cls(table=table)\n\n    def write(self, filename, **kwargs):\n        \"\"\"Write to file.\n\n        Parameters\n        ----------\n        filename : str\n            Filename\n        kwargs : dict\n            Keyword arguments passed to `astropy.table.Table.write`.\n        \"\"\"\n        filename = make_path(filename)\n        self.table.write(str(filename), **kwargs)\n\n    def compute_fvar(self):\n        r\"\"\"Calculate the fractional excess variance.\n\n        This method accesses the the ``FLUX`` and ``FLUX_ERR`` columns\n        from the lightcurve data.\n\n        The fractional excess variance :math:`F_{var}`, an intrinsic\n        variability estimator, is given by\n\n        .. math::\n            F_{var} = \\sqrt{\\frac{S^{2} - \\bar{\\sigma^{2}}}{\\bar{x}^{2}}}.\n\n        It is the excess variance after accounting for the measurement errors\n        on the light curve :math:`\\sigma`. :math:`S` is the variance.\n\n        Returns\n        -------\n        fvar, fvar_err : `~numpy.ndarray`\n            Fractional excess variance.\n\n        References\n        ----------\n        .. [Vaughan2003] \"On characterizing the variability properties of X-ray light\n           curves from active galaxies\", Vaughan et al. (2003)\n           http://adsabs.harvard.edu/abs/2003MNRAS.345.1271V\n        \"\"\"\n        flux = self.table['flux'].data.astype('float64')\n        flux_err = self.table['flux_err'].data.astype('float64')\n\n        flux_mean = np.mean(flux)\n        n_points = len(flux)\n\n        s_square = np.sum((flux - flux_mean) ** 2) / (n_points - 1)\n        sig_square = np.nansum(flux_err ** 2) / n_points\n        fvar = np.sqrt(np.abs(s_square - sig_square)) / flux_mean\n\n        sigxserr_a = np.sqrt(2 / n_points) * (sig_square / flux_mean) ** 2\n        sigxserr_b = np.sqrt(sig_square / n_points) * (2 * fvar / flux_mean)\n        sigxserr = np.sqrt(sigxserr_a ** 2 + sigxserr_b ** 2)\n        fvar_err = sigxserr / (2 * fvar)\n\n        return fvar, fvar_err\n\n    def compute_chisq(self):\n        \"\"\"Calculate the chi-square test for `LightCurve`.\n\n        Chisquare test is a variability estimator. It computes\n        deviations from the expected value here mean value\n\n        Returns\n        -------\n        ChiSq, P-value : tuple of float or `~numpy.ndarray`\n            Tuple of Chi-square and P-value\n        \"\"\"\n        import scipy.stats as stats\n        flux = self.table['flux']\n        yexp = np.mean(flux)\n        yobs = flux.data\n        chi2, pval = stats.chisquare(yobs, yexp)\n        return chi2, pval\n\n    def plot(self, ax=None):\n        \"\"\"Plot flux versus time.\n\n        Parameters\n        ----------\n        ax : `~matplotlib.axes.Axes` or None, optional.\n            The `~matplotlib.axes.Axes` object to be drawn on.\n            If None, uses the current `~matplotlib.axes.Axes`.\n\n        Returns\n        -------\n        ax : `~matplotlib.axes.Axes` or None, optional.\n            The `~matplotlib.axes.Axes` object to be drawn on.\n            If None, uses the current `~matplotlib.axes.Axes`.\n        \"\"\"\n        import matplotlib.pyplot as plt\n        ax = plt.gca() if ax is None else ax\n\n        # TODO: Should we plot with normal time axis labels (ISO, not MJD)?\n\n        x, xerr = self._get_plot_x()\n        y, yerr = self._get_plot_y()\n\n        ax.errorbar(x=x, y=y, xerr=xerr, yerr=yerr, linestyle=\"None\")\n        ax.scatter(x=x, y=y)\n        ax.set_xlabel(\"Time (MJD)\")\n        ax.set_ylabel(\"Flux (cm-2 s-1)\")\n\n        return ax\n\n    def _get_plot_x(self):\n        try:\n            x = self.time.mjd\n        except KeyError:\n            x = self.time_mid.mjd\n\n        try:\n            xerr = x - self.time_min.mjd, self.time_max.mjd - x\n        except KeyError:\n            xerr = None\n\n        return x, xerr\n\n    def _get_plot_y(self):\n        y = self.table['flux'].quantity.to('cm-2 s-1').value\n\n        if 'flux_errp' in self.table.colnames:\n            yp = self.table['flux_errp'].quantity.to('cm-2 s-1').value\n            yn = self.table['flux_errn'].quantity.to('cm-2 s-1').value\n            yerr = yn, yp\n        elif 'flux_err' in self.table.colnames:\n            yerr = self.table['flux_err'].quantity.to('cm-2 s-1').value\n        else:\n            yerr = None\n\n        return y, yerr\n\n\nclass LightCurveEstimator(object):\n    \"\"\"Light curve estimator.\n\n    For a usage example see :gp-extra-notebook:`light_curve`.\n\n    Parameters\n    ----------\n    spec_extract : `~gammapy.spectrum.SpectrumExtraction`\n       Contains statistics, IRF and event lists\n    \"\"\"\n\n    def __init__(self, spec_extract):\n        self.obs_list = spec_extract.obs_list\n        self.obs_spec = spec_extract.observations\n        self.off_evt_list = self._get_off_evt_list(spec_extract)\n        self.on_evt_list = self._get_on_evt_list(spec_extract)\n\n    @staticmethod\n    def _get_off_evt_list(spec_extract):\n        \"\"\"\n        Returns list of OFF events for each observations\n        \"\"\"\n        off_evt_list = []\n        for bg in spec_extract.bkg_estimate:\n            off_evt_list.append(bg.off_events)\n        return off_evt_list\n\n    @staticmethod\n    def _get_on_evt_list(spec_extract):\n        \"\"\"\n        Returns list of ON events for each observations\n        \"\"\"\n        on_evt_list = []\n        for obs in spec_extract.bkg_estimate:\n            on_evt_list.append(obs.on_events)\n\n        return on_evt_list\n\n    @staticmethod\n    def create_fixed_time_bin(time_step, spectrum_extraction):\n        \"\"\"Create time intervals of fixed size.\n\n        Parameters\n        ----------\n        time_step : float\n            Size of the light curve bins in seconds\n        spectrum_extraction : `~gammapy.spectrum.SpectrumExtraction`\n            Contains statistics, IRF and event lists\n\n        Returns\n        -------\n        intervals : list of `~astropy.time.Time`\n            List of time intervals\n        \"\"\"\n        intervals = []\n        time_start = Time(100000, format=\"mjd\")\n        time_end = Time(0, format=\"mjd\")\n        time_step = time_step / (24 * 3600)\n\n        for obs in spectrum_extraction.obs_list:\n            time_events = obs.events.time\n            if time_start > time_events.min():\n                time_start = time_events.min()\n            if time_end < time_events.max():\n                time_end = time_events.max()\n\n        time = time_start.value\n        while time < time_end.value:\n            time += time_step\n            intervals.append([\n                Time(time - time_step, format=\"mjd\"),\n                Time(time, format=\"mjd\"),\n            ])\n        return intervals\n\n    def light_curve(self, time_intervals, spectral_model, energy_range):\n        \"\"\"Compute light curve.\n\n        Implementation follows what is done in:\n        http://adsabs.harvard.edu/abs/2010A%26A...520A..83H.\n\n        To be discussed: assumption that threshold energy in the\n        same in reco and true energy.\n\n        Parameters\n        ----------\n        time_intervals : `list` of `~astropy.time.Time`\n            List of time intervals\n        spectral_model : `~gammapy.spectrum.models.SpectralModel`\n            Spectral model\n        energy_range : `~astropy.units.Quantity`\n            True energy range to evaluate integrated flux (true energy)\n\n        Returns\n        -------\n        lc : `~gammapy.time.LightCurve`\n            Light curve\n        \"\"\"\n        rows = []\n        for time_interval in time_intervals:\n            useinterval, row = self.compute_flux_point(time_interval, spectral_model, energy_range)\n            if useinterval:\n                rows.append(row)\n\n        return self._make_lc_from_row_data(rows)\n\n    @staticmethod\n    def _make_lc_from_row_data(rows):\n        table = Table()\n        table['time_min'] = [_['time_min'].value for _ in rows]\n        table['time_max'] = [_['time_max'].value for _ in rows]\n\n        table['flux'] = [_['flux'].value for _ in rows] * u.Unit('1 / (s cm2)')\n        table['flux_err'] = [_['flux_err'].value for _ in rows] * u.Unit('1 / (s cm2)')\n\n        table['livetime'] = [_['livetime'].value for _ in rows] * u.s\n        table['n_on'] = [_['n_on'] for _ in rows]\n        table['n_off'] = [_['n_off'] for _ in rows]\n        table['alpha'] = [_['alpha'] for _ in rows]\n        table['measured_excess'] = [_['measured_excess'] for _ in rows]\n        table['expected_excess'] = [_['expected_excess'].value for _ in rows]\n\n        return LightCurve(table)\n\n    def compute_flux_point(self, time_interval, spectral_model, energy_range):\n        \"\"\"Compute one flux point for one time interval.\n\n        Parameters\n        ----------\n        time_interval : `~astropy.time.Time`\n            Time interval (2-element array, or a tuple of Time objects)\n        spectral_model : `~gammapy.spectrum.models.SpectralModel`\n            Spectral model\n        energy_range : `~astropy.units.Quantity`\n            True energy range to evaluate integrated flux (true energy)\n\n        Returns\n        -------\n        useinterval : bool\n            Is True if the time_interval produce a valid flux point\n        measurements : dict\n            Dictionary with flux point measurement in the time interval\n        \"\"\"\n        tmin, tmax = time_interval[0], time_interval[1]\n        livetime = 0\n        alpha_mean = 0.\n        alpha_mean_backup = 0.\n        measured_excess = 0\n        predicted_excess = 0\n        n_on = 0\n        n_off = 0\n        useinterval = False\n\n        # Loop on observations\n        for t_index, obs in enumerate(self.obs_list):\n\n            spec = self.obs_spec[t_index]\n\n            # discard observations not matching the time interval\n            obs_start = obs.events.time[0]\n            obs_stop = obs.events.time[-1]\n            if (tmin < obs_start and tmax < obs_start) or (tmin > obs_stop):\n                continue\n\n            useinterval = True\n            # get ON and OFF evt list\n            off_evt = self.off_evt_list[t_index]\n            on_evt = self.on_evt_list[t_index]\n\n            # introduce the e_reco binning here, since it's also used\n            # in the calculation of predicted counts\n            e_reco = spec.e_reco\n            emin = e_reco[e_reco.searchsorted(max(spec.lo_threshold, energy_range[0]))]\n            emax = e_reco[e_reco.searchsorted(min(spec.hi_threshold, energy_range[1])) - 1]\n\n            # compute ON events\n            on = on_evt.select_energy([emin, emax])\n            on = on.select_energy(energy_range)\n            on = on.select_time([tmin, tmax])\n            n_on_obs = len(on.table)\n\n            # compute OFF events\n            off = off_evt.select_energy([emin, emax])\n            off = off.select_energy(energy_range)\n            off = off.select_time([tmin, tmax])\n            n_off_obs = len(off.table)\n\n            # compute effective livetime (for the interval)\n            if tmin >= obs_start and tmax <= obs_stop:\n                # interval included in obs\n                livetime_to_add = (tmax - tmin).to('s')\n            elif tmin >= obs_start and tmax >= obs_stop:\n                # interval min above tstart from obs\n                livetime_to_add = (obs_stop - tmin).to('s')\n            elif tmin <= obs_start and tmax <= obs_stop:\n                # interval min below tstart from obs\n                livetime_to_add = (tmax - obs_start).to('s')\n            elif tmin <= obs_start and tmax >= obs_stop:\n                # obs included in interval\n                livetime_to_add = (obs_stop - obs_start).to('s')\n            else:\n                livetime_to_add = 0 * u.sec\n\n            # Take into account dead time\n            livetime_to_add *= (1. - obs.observation_dead_time_fraction)\n\n            # Compute excess\n            obs_measured_excess = n_on_obs - spec.alpha * n_off_obs\n\n            # Compute the expected excess in the range given by the user\n            # but must respect the energy threshold of the observation\n            # (to match the energy range of the measured excess)\n            # We use the effective livetime and the right energy threshold\n            e_idx = np.where(np.logical_and.reduce(\n                (e_reco >= spec.lo_threshold,  # threshold\n                 e_reco <= spec.hi_threshold,  # threshold\n                 e_reco >= energy_range[0],  # user\n                 e_reco <= energy_range[-1])  # user\n            ))[0]\n            counts_predictor = CountsPredictor(\n                livetime=livetime_to_add,\n                aeff=spec.aeff,\n                edisp=spec.edisp,\n                model=spectral_model\n            )\n            counts_predictor.run()\n            counts_predicted_excess = counts_predictor.npred.data.data[e_idx[:-1]]\n\n            obs_predicted_excess = np.sum(counts_predicted_excess)\n\n            # compute effective normalisation between ON/OFF (for the interval)\n            livetime += livetime_to_add\n            alpha_mean += spec.alpha * n_off_obs\n            alpha_mean_backup += spec.alpha * livetime_to_add\n            measured_excess += obs_measured_excess\n            predicted_excess += obs_predicted_excess\n            n_on += n_on_obs\n            n_off += n_off_obs\n\n        # Fill time interval information\n        if useinterval:\n            int_flux = spectral_model.integral(energy_range[0], energy_range[1])\n\n            if n_off > 0.:\n                alpha_mean /= n_off\n            if livetime > 0.:\n                alpha_mean_backup /= livetime\n            if alpha_mean == 0.:  # use backup if necessary\n                alpha_mean = alpha_mean_backup\n\n            flux = measured_excess / predicted_excess.value\n            flux *= int_flux\n            flux_err = int_flux / predicted_excess.value\n            # Gaussian errors, TODO: should be improved\n            flux_err *= excess_error(n_on=n_on, n_off=n_off, alpha=alpha_mean)\n        else:\n            flux = 0\n            flux_err = 0\n\n        # Store measurements in a dict and return that\n        return useinterval, OrderedDict([\n            ('time_min', Time(tmin, format='mjd')),\n            ('time_max', Time(tmax, format='mjd')),\n            ('flux', flux * u.Unit('1 / (s cm2)')),\n            ('flux_err', flux_err * u.Unit('1 / (s cm2)')),\n\n            ('livetime', livetime * u.s),\n            ('alpha', alpha_mean),\n            ('n_on', n_on),\n            ('n_off', n_off),\n            ('measured_excess', measured_excess),\n            ('expected_excess', predicted_excess),\n        ])\n", "meta": {"hexsha": "30abd4e4df9fd1af67e946370cabab65423b669f", "size": 17298, "ext": "py", "lang": "Python", "max_stars_repo_path": "gammapy/time/lightcurve.py", "max_stars_repo_name": "gabemery/gammapy", "max_stars_repo_head_hexsha": "99e5c5d38e4920dddd7bca41fb1539ccda8bea2d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gammapy/time/lightcurve.py", "max_issues_repo_name": "gabemery/gammapy", "max_issues_repo_head_hexsha": "99e5c5d38e4920dddd7bca41fb1539ccda8bea2d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gammapy/time/lightcurve.py", "max_forks_repo_name": "gabemery/gammapy", "max_forks_repo_head_hexsha": "99e5c5d38e4920dddd7bca41fb1539ccda8bea2d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2015355086, "max_line_length": 99, "alphanum_fraction": 0.5771765522, "include": true, "reason": "import numpy,import scipy,import astropy,from astropy", "num_tokens": 4069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.17643454239319714}}
{"text": "\"\"\"\nRetrieves either NZTA or NZS1170.5 code values\nfor the given locations\n\"\"\"\n\nfrom pathlib import Path\nimport argparse\nimport multiprocessing as mp\nfrom typing import Sequence\n\nimport numpy as np\nimport pandas as pd\n\nimport sha_calc as sha\nimport gmhazard_calc as sc\n\nDEFAULT_RETURN_PERIODS = np.array([20, 25, 50, 100, 250, 500, 1000, 2000, 2500])\nDEFAULT_EXCEEDANCE_VALUES = 1 / DEFAULT_RETURN_PERIODS\n\nDEFAULT_IMS = [\n    \"PGA\",\n    \"pSA_0.01\",\n    \"pSA_0.02\",\n    \"pSA_0.03\",\n    \"pSA_0.04\",\n    \"pSA_0.05\",\n    \"pSA_0.075\",\n    \"pSA_0.1\",\n    \"pSA_0.12\",\n    \"pSA_0.15\",\n    \"pSA_0.17\",\n    \"pSA_0.2\",\n    \"pSA_0.25\",\n    \"pSA_0.3\",\n    \"pSA_0.4\",\n    \"pSA_0.5\",\n    \"pSA_0.6\",\n    \"pSA_0.7\",\n    \"pSA_0.75\",\n    \"pSA_0.8\",\n    \"pSA_0.9\",\n    \"pSA_1.0\",\n    \"pSA_1.25\",\n    \"pSA_1.5\",\n    \"pSA_2.0\",\n    \"pSA_2.5\",\n    \"pSA_3.0\",\n    \"pSA_4.0\",\n    \"pSA_5.0\",\n    \"pSA_6.0\",\n    \"pSA_7.5\",\n    \"pSA_10.0\",\n]\n\n\ndef main(\n    input_data_ffp: str,\n    output_dir: Path,\n    nz_code_type: str,\n    nzta_csv_ffp: Path = None,\n    ims: Sequence[str] = DEFAULT_IMS,\n    n_procs: int = 4,\n):\n    # Load the required data\n    data_df = pd.read_csv(input_data_ffp)\n\n    # Need an ensemble\n    ens = sc.gm_data.Ensemble(\"v20p5emp\")\n\n    if nz_code_type == \"NZS1170.5\":\n        with mp.Pool(n_procs) as pool:\n            results = pool.starmap(\n                _process_nzs1170p5_station,\n                [\n                    (\n                        ens,\n                        cur_row.lat,\n                        cur_row.lon,\n                        cur_row.vs30,\n                        ims,\n                        ix,\n                        data_df.shape[0],\n                    )\n                    for ix, (cur_id, cur_row) in enumerate(data_df.iterrows())\n                ],\n            )\n\n        # Extract and save\n        grouped_sublists = list(zip(*results))\n        np.save(\n            str(output_dir / \"NZS1170p5_im_values.npy\"),\n            np.stack(grouped_sublists[0], axis=0),\n        )\n        np.save(\n            str(output_dir / \"NZS1170p5_Z_values.npy\"),\n            np.stack(grouped_sublists[1], axis=0),\n        )\n        np.save(\n            str(output_dir / \"NZS1170p5_N_values.npy\"),\n            np.stack(grouped_sublists[2], axis=0),\n        )\n        np.save(\n            str(output_dir / \"NZS1170p5_R_values.npy\"),\n            np.stack(grouped_sublists[3], axis=0),\n        )\n        np.save(\n            str(output_dir / \"NZS1170p5_Ch_values.npy\"),\n            np.stack(grouped_sublists[4], axis=0),\n        )\n\n    elif nz_code_type == \"NZTA\":\n        assert nzta_csv_ffp is not None, (\n            \"Path to the NZTA csv is required when \" \"computing NZTA code PGA values\"\n        )\n        nzta_df = pd.read_csv(nzta_csv_ffp, header=0, index_col=0)\n\n        with mp.Pool(n_procs) as pool:\n            results = pool.starmap(\n                _process_nzta_station,\n                [\n                    (\n                        ens,\n                        cur_row.lat,\n                        cur_row.lon,\n                        cur_row.vs30,\n                        nzta_df,\n                        ix,\n                        data_df.shape[0],\n                    )\n                    for ix, (cur_id, cur_row) in enumerate(data_df.iterrows())\n                ],\n            )\n            grouped_sublists = list(zip(*results))\n            np.save(\n                str(output_dir / \"NZTA_PGA_values.npy\"),\n                np.stack(grouped_sublists[0], axis=0),\n            )\n            np.save(\n                str(output_dir / \"NZTA_town_index.npy\"),\n                np.stack(grouped_sublists[1], axis=0),\n            )\n\n\ndef _process_nzta_station(\n    ens: sc.gm_data.Ensemble,\n    lat: float,\n    lon: float,\n    vs30: float,\n    nzta_df: pd.DataFrame,\n    ix: int,\n    n_locs: int,\n):\n    print(f\"Processing location {ix + 1}/{n_locs}\")\n\n    # Set result to nan if no vs30 values are available\n    if np.isnan(vs30):\n        return np.full(len(DEFAULT_EXCEEDANCE_VALUES), np.nan), np.nan\n\n    site_info = sc.site.SiteInfo(f\"site_{ix}\", lat, lon, vs30)\n\n    result = sc.nz_code.nzta_2018.run_ensemble_nzta(\n        ens, site_info, exceedance_values=DEFAULT_EXCEEDANCE_VALUES\n    )\n    return (\n        result.pga_values.loc[DEFAULT_EXCEEDANCE_VALUES].values,\n        np.flatnonzero(nzta_df.index.values == result.nearest_town)[0],\n    )\n\n\ndef _process_nzs1170p5_station(\n    ens: sc.gm_data.Ensemble,\n    lat: float,\n    lon: float,\n    vs30: float,\n    ims: Sequence[str],\n    ix: int,\n    n_locs: int,\n):\n    print(f\"Processing location {ix + 1}/{n_locs}\")\n    # Get the periods\n    sa_periods = [0 if im == \"PGA\" else sc.utils.get_period_from_pSA(im) for im in ims]\n\n    # Set result to nan if no vs30 values are available\n    if np.isnan(vs30):\n        return (\n            np.full((len(sa_periods), len(DEFAULT_EXCEEDANCE_VALUES)), np.nan),\n            np.nan,\n            np.full(len(sa_periods), np.nan),\n            np.full(len(DEFAULT_EXCEEDANCE_VALUES), np.nan),\n            np.full(len(sa_periods), np.nan),\n        )\n\n    site_info = sc.site.SiteInfo(f\"site_{ix}\", lat, lon, vs30)\n\n    distance = sc.nz_code.nzs1170p5.get_distance_from_site_info(ens, site_info)\n    z_factor = float(sc.nz_code.nzs1170p5.ll2z((site_info.lon, site_info.lat)))\n    soil_class = sc.nz_code.nzs1170p5.get_soil_class(site_info.vs30)\n\n    results, R_values, N_values, Ch_values = [], [], [], []\n    for cur_exceedance in DEFAULT_EXCEEDANCE_VALUES:\n        cur_rp = 1 / cur_exceedance\n\n        if cur_rp < 20 or cur_rp > 2500:\n            raise NotImplementedError()\n        else:\n            C, Ch, R, N = sha.nzs1170p5_spectra(\n                sa_periods, z_factor, cur_rp, distance, soil_class.value\n            )\n            results.append(C)\n            R_values.append(R)\n            N_values.append(N)\n            Ch_values.append(Ch)\n\n    return (\n        np.stack(results, axis=1),\n        z_factor,\n        N_values[0],\n        np.asarray(R_values),\n        Ch_values[0],\n    )\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n\n    parser.add_argument(\n        \"input_data\",\n        type=str,\n        help=\"Path to input csv, must contain columns lon, lat and vs30\",\n    )\n    parser.add_argument(\"output_dir\", type=Path, help=\"Output directory path\")\n    parser.add_argument(\n        \"nz_code_type\",\n        type=str,\n        help=\"The NZCode for which to generate data\",\n        choices=[\"NZS1170.5\", \"NZTA\"],\n    )\n    parser.add_argument(\n        \"--nzta_town_csv\",\n        type=Path,\n        help=\"Path to the NZTA town csv, required when computing NZTA\",\n    )\n    parser.add_argument(\n        \"--n_procs\", type=int, help=\"Number of processes to use\", default=4\n    )\n\n    args = parser.parse_args()\n\n    main(\n        args.input_data,\n        args.output_dir,\n        args.nz_code_type,\n        nzta_csv_ffp=args.nzta_town_csv,\n        n_procs=args.n_procs,\n    )\n", "meta": {"hexsha": "f1b2b9beee3aefdc21321a7e4f4b69cbb2281c3d", "size": 6933, "ext": "py", "lang": "Python", "max_stars_repo_path": "tools/gmhazard_scripts/one_off/nz_code_retrieval.py", "max_stars_repo_name": "ucgmsim/gmhazard", "max_stars_repo_head_hexsha": "d3d90b4c94b3d9605597a3efeccc8523a1e50c0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tools/gmhazard_scripts/one_off/nz_code_retrieval.py", "max_issues_repo_name": "ucgmsim/gmhazard", "max_issues_repo_head_hexsha": "d3d90b4c94b3d9605597a3efeccc8523a1e50c0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-10-13T02:33:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:01:08.000Z", "max_forks_repo_path": "tools/gmhazard_scripts/one_off/nz_code_retrieval.py", "max_forks_repo_name": "ucgmsim/gmhazard", "max_forks_repo_head_hexsha": "d3d90b4c94b3d9605597a3efeccc8523a1e50c0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.08203125, "max_line_length": 87, "alphanum_fraction": 0.5469493726, "include": true, "reason": "import numpy", "num_tokens": 1896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.3073580295544412, "lm_q1q2_score": 0.1763246649125332}}
{"text": "import os, sys, glob, copy\nimport argparse\nfrom pathlib import Path\nfrom typing import Dict, Optional, Union, Type\n\nimport pandas as pd\nimport numpy as np\nfrom functools import partial\nfrom scipy.interpolate import RectBivariateSpline\nfrom scipy.ndimage.filters import convolve\n\nimport astropy\nfrom astropy.io import fits\nfrom astropy import units as un\nimport lenstools\nfrom lenstools import ConvergenceMap\nimport healpy as hp\n#import pymaster as nmt\n\nfrom astrild.simulation import Simulation\nfrom astrild.rays.utils import Filters\nfrom astrild.rays.skys.sky_array import SkyArray\nfrom astrild.rays.skys.sky_namaster import SkyNamaster\nfrom astrild.rays.skys.sky_utils import SkyUtils\nfrom astrild.rays.skyio import SkyIO\nfrom astrild.io import IO\n\ndir_src = Path(__file__).parent.absolute()\ndefault_config_file_ray = dir_src / \"configs/ray_snapshot_info.h5\"\nc_light = 299792.458  # in km/s\n\n\nclass SkyHealpixWarning(BaseException):\n    pass\n\n\nclass SkyHealpix:\n    \"\"\"\n    The sky-map is constructed through multiple ray-tracing simulations\n    run with RayRamses. This class analyzes the 2D map that contains\n    the summes pertrurbations of each ray. It can prepare the data for the\n    search of voids and peaks.\n\n    Attributes:\n        npix:\n        theta:\n        dirs:\n\n    Methods:\n        from_file:\n        pdf:\n        wl_peak_counts:\n        add_field:\n        add_galaxy_shape_noise:\n        create_galaxy_shape_noise:\n        add_cmb:\n        create_cmb:\n        add_mask:\n        create_mask:\n        convolution:\n    \"\"\"\n\n    def __init__(\n        self,\n        skymap: np.ndarray,\n        opening_angle: float,\n        quantity: str,\n        dirs: Dict[str, str],\n        map_file: Optional[str] = None,\n    ):\n        self.data = {\"orig\": skymap}\n        self._nside = hp.get_nside(skymap)\n        self._npix = hp.nside2npix(self.nside)\n        self.opening_angle = opening_angle\n        self.quantity = quantity\n        self.dirs = dirs\n        self.map_file = map_file\n\n    @classmethod\n    def from_file(\n        cls,\n        map_file: str,\n        opening_angle: float,\n        quantity: str,\n        dir_in: str,\n        nside: Optional[int] = None,\n        convert_unit: bool = True,\n    ) -> \"SkyHealpix\":\n        \"\"\"\n        Initialize class by reading the skymap data from pandas hdf5 file\n        or numpy array.\n        The file can be pointed at via map_filename or file_dsc.\n\n        Args:\n            map_filename:\n                File path with which skymap pd.DataFrame can be loaded.\n            file_dsc:\n                Dictionary pointing to a file via {path, root, extension}.\n                Use when multiple skymaps need to be loaded.\n        \"\"\"\n        file_extension = map_file.split(\".\")[-1]\n        assert file_extension in [\"h5\", \"fits\", \"npy\"], SkyHealpixWarning(\n            f\"The file formart {file_extension} is not supported.\"\n        )\n        if file_extension == \"h5\":\n            map_df = pd.read_hdf(map_file, key=\"df\")\n            return cls.from_sky_dataframe(\n                map_df,\n                opening_angle,\n                nside,\n                quantity,\n                dir_in,\n                map_file,\n                convert_unit,\n            )\n        elif file_extension == \"fits\":\n            map_array = hp.read_map(map_file)\n            return cls.from_sky_array(\n                map_array, opening_angle, quantity, dir_in, map_file\n            )\n        elif file_extension == \"npy\":\n            map_array = np.load(map_file)\n            return cls.from_sky_array(\n                map_array, opening_angle, quantity, dir_in, map_file\n            )\n\n    @classmethod\n    def from_dataframe(\n        cls,\n        map_df: pd.DataFrame,\n        opening_angle: float,\n        nside: int,\n        quantity: str,\n        dir_in: str,\n        map_file: str,\n        convert_unit: bool = True,\n    ) -> \"SkyHealpix\":\n        \"\"\"\n        Initialize class by reading the skymap data from pandas DataFrame. \n\n        Args:\n            map_filename:\n                File path with which skymap pd.DataFrame can be loaded.\n            file_dsc:\n                Dictionary pointing to a file via {path, root, extension}.\n                Use when multiple skymaps need to be loaded.\n        \"\"\"\n        if convert_unit:\n            map_df = SkyUtils.convert_code_to_phy_units(quantity, map_df)\n        map_array = SkyIO.transform_PandasDataFrame_to_Healpix(\n            map_df, quantity, nside\n        )\n        return cls.from_sky_array(\n            map_array, opening_angle, quantity, dir_in, map_file\n        )\n\n\n    @classmethod\n    def from_array(\n        cls,\n        map_array: np.array,\n        opening_angle: float,\n        quantity: str,\n        dir_in: str,\n        map_file: Optional[str] = None,\n    ) -> \"SkyHealpix\":\n        \"\"\"\n        Initialize class by reading the skymap data from np.ndarray.\n\n        Args:\n            map_filename:\n                File path with which skymap pd.DataFrame can be loaded.\n            file_dsc:\n                Dictionary pointing to a file via {path, root, extension}.\n                Use when multiple skymaps need to be loaded.\n        \"\"\"\n        dirs = {\"sim\": dir_in}\n        map_array = hp.ma(map_array)  # mask out bad values (e.g Nan)\n        return cls(map_array, opening_angle, quantity, dirs, map_file)\n\n\n    @classmethod\n    def from_Cl_file(\n        cls,\n        cl_file: str,\n        quantity: str,\n        dir_in: str,\n        nside: int,\n        lmax: int = 3000,\n        opening_angle: int = 41253,\n        key: Optional[str] = None, \n        rnd_seed: Optional[int] = None,\n    ) -> \"SkyHealpix\":\n        \"\"\"\n        Args:\n            cl_file:\n            quantity:\n            dir_in:\n            nside:\n            lmax:\n            opening_angle:\n            key:\n        \"\"\"\n        np.random.seed(rnd_seed)\n        file_extension = cl_file.split(\".\")[-1]\n        assert file_extension in [\"npz\", \"npy\"], SkyHealpixWarning(\n            f\"The file formart {file_extension} is not supported.\"\n        )\n        if file_extension == \"npy\":\n            cl_array = np.load(cl_file)\n        elif file_extension == \"npz\":\n            cl_array = np.load(cl_file)[key]\n        return cls.from_Cl_array(\n            cl_array, quantity, nside, lmax, opening_angle, dir_in, cl_file\n        )\n\n\n    @classmethod\n    def from_Cl_array(\n        cls,\n        cl_array: np.array,\n        quantity: str,\n        nside: int,\n        lmax: int,\n        opening_angle: int = 41253,\n        dir_in: Optional[str] = None,\n        cl_file: Optional[str] = None,\n        rnd_seed: Optional[int] = None,\n    ) -> \"SkyHealpix\":\n        \"\"\"\n        Args:\n            opening_angle:\n                [deg^2]\n        \"\"\"\n        np.random.seed(rnd_seed)\n        dirs = {\"sim\": dir_in}\n        map_array = hp.sphtfunc.synfast(cl_array, nside=nside, lmax=lmax)\n        return cls(map_array, opening_angle, quantity, dirs, cl_file)\n\n\n    @property\n    def nside(self):\n        return self._nside\n\n    @property\n    def npix(self):\n        return self._npix\n\n    \n    def to_skyarray(\n        self,\n        npix: int,\n        opening_angle: float,\n        of: str = \"orig\",\n    ) -> Type[SkyArray]:\n        \"\"\"\n        Args:\n            lonra: , [deg]\n            latra: , [deg]\n        \"\"\"\n        lonra = latra = [0, opening_angle]\n        cart_proj = hp.projector.CartesianProj(\n            lonra=lonra,\n            latra=latra,\n            xsize=npix,\n            ysize=npix,\n        )\n        map_array = cart_proj.projmap(\n            self.data[of],\n            rot=(0., 0.),\n            vec2pix_func=partial(hp.vec2pix, self._nside),\n        )\n        return SkyArray.from_array(\n            map_array,\n            opening_angle=opening_angle,\n            quantity=self.quantity,\n            dir_in=self.dirs[\"sim\"],\n        )\n\n\n    def create_cmb(\n        self,\n        filepath_cl: str,\n        lmax: float = 3e3,\n        nside: Optional[int] = None,\n        rnd_seed: Optional[int] = None,\n    ) -> None:\n        \"\"\"\n        Cosmig Microwave Background (CMB) on partial-sky map,\n        for which the flat-sky approximation holds (ell > 10).\n\n        Args:\n            filepath_cl:\n                angular power spectrum of CMB\n            nside:\n                Nr. of pixels per edge of the output full-sky map\n            rnd_seed:\n                Fix random seed, for reproducability.\n\n        Returns:\n            cmb_map:\n        \"\"\"\n        if nside is None:\n            nside = self._nside\n        cl_cmb = np.load(filepath_cl)\n        np.random.seed(rnd_seed)\n        self.data[\"cmb\"] = hp.sphtfunc.synfast(cmb_tt, nside=nside, lmax=lmax)\n\n\n    def sum_of_maps(self, map1: str, map2: str) -> None:\n        self.data[f\"{map1}_{map2}\"] = self.data[map1] + self.data[map2]\n\n\n    def arithmetic_operation_with(\n        self, skymap: np.array, on: str, operation: np\n    ) -> None:\n        \"\"\"\n        Use Numpy function to perform one of the basic arithmetic operations:\n            add, substract, multiply, divide\n        of two Healpix fields.\n\n        Args:\n            skymap:\n            on:\n            operation:\n        \"\"\"\n        _pixel_idx = np.arange(self._npix)\n        _unmasked_pixel_idx = _pixel_idx[~self.data[on].mask]\n        self.data[on].data[_unmasked_pixel_idx] = operation(\n            self.data[on].data[_unmasked_pixel_idx], skymap[_unmasked_pixel_idx]\n        )\n\n\n    def add_mask(self, on: str, theta: Optional[float] = None) -> None:\n        \"\"\"\n        \"\"\"\n        if (\"mask\" not in self.data.keys()) or (theta != self.mask_theta):\n            self.create_mask(theta)\n        self.data[on + \"_mask\"] = hp.ma(copy.deepcopy(self.data[on]))\n        self.data[on + \"_mask\"].mask = self.data[\"mask\"]\n\n\n    def create_mask(self, theta: float) -> None:\n        \"\"\"\n        Mask out unobserved patches of the full-sky.\n\n        Args:\n            theta:\n                Edge length of the square field-of-view [deg]\n            nside:\n                Nr. of pixels per edge of the output full-sky map\n        \"\"\"\n        print(\"create_mask\", theta)\n        # angular positions of all healpix pixels\n        _pixel_index = np.arange(self._npix)\n        pixel_theta, pixel_phi = hp.pix2ang(self._nside, _pixel_index)\n        # range of ra and dec of the field-of-view\n        ras = np.array([90 - theta / 2, 90 + theta / 2]) * np.pi / 180  # [rad]\n        decs = np.array([theta / 2, 360 - theta / 2]) * np.pi / 180  # [rad]\n        # create mask\n        mask = np.zeros(self._npix, dtype=np.bool)\n        mask[pixel_theta < ras[0]] = 1\n        mask[pixel_theta > ras[1]] = 1\n        mask[(decs[0] < pixel_phi) & (pixel_phi < decs[1])] = 1\n        self.data[\"mask\"] = mask\n        self.mask_theta = theta\n\n    \n    def rotate(\n        self, theta: float, phi: float, which: str, rtn: bool = False\n    ) -> np.ndarray:\n        \"\"\"\n        Rotate the full-sky.\n\n        Args:\n            theta and phi:\n                Rotational angles [deg]\n            which:\n                Identify which map in self.data should be rotated.\n        \"\"\"\n        if (theta is None) or (phi is None):\n            theta = np.random.random() * 180\n            phi = np.random.random() * 180\n\n        # Get theta, phi for non-rotated map\n        _pixel_index = np.arange(self._npix)\n        t, p = hp.pix2ang(self._nside, _pixel_index)\n        # Define a rotator\n        r = hp.Rotator(deg=True, rot=[theta, phi])\n        # Get theta, phi under rotated co-ordinates\n        trot, prot = r(t, p)\n        # Interpolate map onto these co-ordinates\n        _skymap = copy.deepcopy(self.data[which])\n        _skymap = hp.get_interp_val(_skymap, trot, prot)\n        if rtn is True:\n            return _skymap\n        else:\n            self.data[which] = _skymap\n    \n    \n    #def to_skynamaster(self, apodization_width: float = 2.5):\n    #    \"\"\"\n    #    Transform SkyHealpix to SkyNamaster.\n    #    \"\"\"\n    #    _skyarray = copy.deepcopy(self.data[\"orig\"])\n    #    _skyarray[~self.data[\"mask\"]] = hp.UNSEEN\n    #    _mask = copy.deepcopy(self.data[\"mask\"]) * 1\n    #    #_mask = nmt.mask_apodization(_mask, apodization_width, apotype=\"C2\")\n    #    #print(\"------------->\", _mask.shape)\n    #    #self.data[\"nm\"] = nmt.NmtField(_mask, [_skyarray])\n    #    # return SkyNamaster.from_array(\n    #    #    sky_field,\n    #    #    self._npix,\n    #    #    self.opening_angle,\n    #    #    self.quantity,\n    #    #    self.dirs,\n    #    #    self.map_file,\n    #    # )\n", "meta": {"hexsha": "69da093d41bed5ab5f0e68d5f855926cafaaee93", "size": 12493, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/astrild/rays/skys/sky_healpix.py", "max_stars_repo_name": "Christovis/wys-ars", "max_stars_repo_head_hexsha": "bb15f2d392842f9b32de12b5db5c86079bc97105", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-27T14:45:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T21:09:46.000Z", "max_issues_repo_path": "src/astrild/rays/skys/sky_healpix.py", "max_issues_repo_name": "Christovis/wys-ars", "max_issues_repo_head_hexsha": "bb15f2d392842f9b32de12b5db5c86079bc97105", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-03T10:47:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-03T10:47:45.000Z", "max_forks_repo_path": "src/astrild/rays/skys/sky_healpix.py", "max_forks_repo_name": "Christovis/wys-ars", "max_forks_repo_head_hexsha": "bb15f2d392842f9b32de12b5db5c86079bc97105", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-03T10:17:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T10:17:34.000Z", "avg_line_length": 29.8162291169, "max_line_length": 80, "alphanum_fraction": 0.5583926999, "include": true, "reason": "import numpy,from scipy,import astropy,from astropy", "num_tokens": 3101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.17632466127277968}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n#    Project: Azimuthal integration\n#             https://github.com/silx-kit/pyFAI\n#\n#    Copyright (C) European Synchrotron Radiation Facility, Grenoble, France\n#\n#    Principal author:       Jérôme Kieffer (Jerome.Kieffer@ESRF.eu)\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\"\"\"Module used to perform the geometric refinement of the model\n\"\"\"\n\nfrom __future__ import print_function, division, absolute_import\n\n__author__ = \"Jerome Kieffer\"\n__contact__ = \"Jerome.Kieffer@ESRF.eu\"\n__license__ = \"MIT\"\n__copyright__ = \"European Synchrotron Radiation Facility, Grenoble, France\"\n__date__ = \"10/01/2018\"\n__status__ = \"development\"\n\nimport os\nimport tempfile\nimport subprocess\nimport logging\nimport numpy\nimport types\nfrom math import pi\nfrom . import azimuthalIntegrator\nfrom .calibrant import Calibrant, CALIBRANT_FACTORY\nfrom .utils.ellipse import fit_ellipse\nAzimuthalIntegrator = azimuthalIntegrator.AzimuthalIntegrator\nfrom scipy.optimize import fmin, leastsq, fmin_slsqp\ntry:\n    from scipy.optimize import basinhopping as anneal\nexcept ImportError:\n    from scipy.optimize import anneal\ntry:\n    from scipy.optimize import curve_fit\nexcept ImportError:\n    curve_fit = None\n\nif os.name != \"nt\":\n    WindowsError = RuntimeError\n\nlogger = logging.getLogger(__name__)\n# logger.setLevel(logging.DEBUG)\nROCA = \"/opt/saxs/roca\"\n\n####################\n# GeometryRefinement\n####################\n\n\nclass GeometryRefinement(AzimuthalIntegrator):\n    def __init__(self, data=None, dist=1, poni1=None, poni2=None,\n                 rot1=0, rot2=0, rot3=0,\n                 pixel1=None, pixel2=None, splineFile=None, detector=None,\n                 wavelength=None, calibrant=None):\n        \"\"\"\n        :param data: ndarray float64 shape = n, 3\n            col0: pos in dim0 (in pixels)\n            col1: pos in dim1 (in pixels)\n            col2: ring index in calibrant object\n        :param dist: guessed sample-detector distance (optional, in m)\n        :param poni1: guessed PONI coordinate along the Y axis (optional, in m)\n        :param poni2: guessed PONI coordinate along the X axis (optional, in m)\n        :param rot1: guessed tilt of the detector around the Y axis (optional, in rad)\n        :param rot2: guessed tilt of the detector around the X axis (optional, in rad)\n        :param rot3: guessed tilt of the detector around the incoming beam axis (optional, in rad)\n        :param pixel1: Pixel size along the vertical direction of the detector (in m), almost mandatory\n        :param pixel2: Pixel size along the horizontal direction of the detector (in m), almost mandatory\n        :param splineFile: file describing the detector as 2 cubic splines. Replaces pixel1 & pixel2\n        :param detector: name of the detector or Detector instance. Replaces splineFile, pixel1 & pixel2\n        :param wavelength: wavelength in m (1.54e-10)\n        :param calibrant: instance of pyFAI.calibrant.Calibrant containing the d-Spacing\n\n        \"\"\"\n        if data is None:\n            self.data = None\n        else:\n            self.data = numpy.array(data, dtype=numpy.float64)\n            assert self.data.ndim == 2\n            assert self.data.shape[1] in [3, 4]  # 3 for non weighted, 4 for weighted refinement\n            assert self.data.shape[0] > 0\n\n        if (pixel1 is None) and (pixel2 is None) and (splineFile is None) and (detector is None):\n            raise RuntimeError(\"Setting up the geometry refinement without knowing the detector makes little sense\")\n        AzimuthalIntegrator.__init__(self, dist, 0, 0,\n                                     rot1, rot2, rot3,\n                                     pixel1, pixel2, splineFile, detector, wavelength=wavelength)\n\n        if calibrant is None:\n            self.calibrant = Calibrant()\n        else:\n            if isinstance(calibrant, Calibrant):\n                self.calibrant = calibrant\n            elif type(calibrant) in types.StringTypes:\n                if calibrant in CALIBRANT_FACTORY:\n                    self.calibrant = CALIBRANT_FACTORY(calibrant)\n                else:\n                    self.calibrant = Calibrant(filename=calibrant)\n            else:\n                self.calibrant = Calibrant(calibrant)\n\n        self.calibrant.wavelength = self.wavelength\n\n        if (poni1 is None) or (poni2 is None):\n            self.guess_poni()\n        else:\n            self.poni1 = float(poni1)\n            self.poni2 = float(poni2)\n        self._dist_min = 0\n        self._dist_max = 10\n        self._poni1_min = -10000 * self.pixel1\n        self._poni1_max = 15000 * self.pixel1\n        self._poni2_min = -10000 * self.pixel2\n        self._poni2_max = 15000 * self.pixel2\n        self._rot1_min = -pi\n        self._rot1_max = pi\n        self._rot2_min = -pi\n        self._rot2_max = pi\n        self._rot3_min = -pi\n        self._rot3_max = pi\n        self._wavelength_min = 1e-15\n        self._wavelength_max = 100.e-10\n\n    def guess_poni(self):\n        \"\"\"PONI can be guessed by the centroid of the ring with lowest 2Theta\n\n        It may try to fit an ellipse and sometimes it works\n        \"\"\"\n\n        if len(self.calibrant.dSpacing):\n            # logger.warning(self.calibrant.__repr__())s\n            tth = self.calc_2th(self.data[:, 2])\n        else:  # assume rings are in decreasing dSpacing in the file\n            tth = self.data[:, 2]\n        asrt = tth.argsort()\n        tth = tth[asrt]\n        srtdata = self.data[asrt]\n        tth_min = tth.min()\n        smallRing = srtdata[tth < (tth_min + 1e-6)]\n        smallRing1 = smallRing[:, 0]\n        smallRing2 = smallRing[:, 1]\n        smallRing_in_m = self.detector.calc_cartesian_positions(smallRing1,\n                                                                smallRing2)\n        nbpt = len(smallRing)\n        worked = False\n        if nbpt > 5:\n            # If there are many control point on the inner-most ring, fit an ellipse\n            try:\n                ellipse = fit_ellipse(*smallRing_in_m[:2])\n                direct_dist = ellipse.half_long_axis / numpy.tan(tth_min)\n                tilt = numpy.arctan2(ellipse.half_long_axis - ellipse.half_short_axis, ellipse.half_short_axis)\n                cos_tilt = numpy.cos(tilt)\n                sin_tilt = numpy.sin(tilt)\n                angle = (ellipse.angle + numpy.pi / 2.0) % numpy.pi\n                cos_tpr = numpy.cos(angle)\n                sin_tpr = numpy.sin(angle)\n                dist = direct_dist * cos_tilt\n                poni1 = ellipse.center_1 - direct_dist * sin_tilt * sin_tpr\n                poni2 = ellipse.center_2 - direct_dist * sin_tilt * cos_tpr\n                rot2 = numpy.arcsin(sin_tilt * sin_tpr)  # or pi-\n                rot1 = numpy.arccos(min(1.0, max(-1.0, (cos_tilt / numpy.sqrt(1 - sin_tpr * sin_tpr * sin_tilt * sin_tilt)))))  # + or -\n                if cos_tpr * sin_tilt > 0:\n                    rot1 = -rot1\n                rot3 = 0\n            except:\n                worked = False\n            else:\n                if numpy.isnan(dist + poni1 + poni2 + rot1 + rot2 + rot3):\n                    worked = False\n                else:\n                    worked = True\n                    self.dist = dist\n                    self.poni1 = poni1\n                    self.poni2 = poni2\n                    self.rot1 = rot1\n                    self.rot2 = rot2\n                    self.rot3 = rot3\n        if not worked:\n            self.poni1 = smallRing_in_m[0].sum() / nbpt\n            self.poni2 = smallRing_in_m[1].sum() / nbpt\n\n    def set_tolerance(self, value=10):\n        \"\"\"\n        Set the tolerance for a refinement of the geometry; in percent of the original value\n\n        :param value: Tolerance as a percentage\n\n        \"\"\"\n        low = 1.0 - value / 100.\n        hi = 1.0 + value / 100.\n        self.dist_min = low * self.dist\n        self.dist_max = hi * self.dist\n        if abs(self.poni1) > (value / 100.) ** 2:\n            self.poni1_min = min(low * self.poni1, hi * self.poni1)\n            self.poni1_max = max(low * self.poni1, hi * self.poni1)\n        else:\n            self.poni1_min = -(value / 100.) ** 2\n            self.poni1_max = (value / 100.) ** 2\n        if abs(self.poni2) > (value / 100.) ** 2:\n            self.poni2_min = min(low * self.poni2, hi * self.poni2)\n            self.poni2_max = max(low * self.poni2, hi * self.poni2)\n        else:\n            self.poni2_min = -(value / 100.) ** 2\n            self.poni2_max = (value / 100.) ** 2\n        if abs(self.rot1) > (value / 100.) ** 2:\n            self.rot1_min = min(low * self.rot1, hi * self.rot1)\n            self.rot1_max = max(low * self.rot1, hi * self.rot1)\n        else:\n            self.rot1_min = -(value / 100.) ** 2\n            self.rot1_max = (value / 100.) ** 2\n        if abs(self.rot2) > (value / 100.) ** 2:\n            self.rot2_min = min(low * self.rot2, hi * self.rot2)\n            self.rot2_max = max(low * self.rot2, hi * self.rot2)\n        else:\n            self.rot2_min = -(value / 100.) ** 2\n            self.rot2_max = (value / 100.) ** 2\n        if abs(self.rot3) > (value / 100.) ** 2:\n            self.rot3_min = min(low * self.rot3, hi * self.rot3)\n            self.rot3_max = max(low * self.rot3, hi * self.rot3)\n        else:\n            self.rot3_min = -(value / 100.) ** 2\n            self.rot3_max = (value / 100.) ** 2\n        self.wavelength_min = low * self.wavelength\n        self.wavelength_max = hi * self.wavelength\n\n    def calc_2th(self, rings, wavelength=None):\n        \"\"\"\n        :param rings: indices of the rings. starts at 0 and self.dSpacing should be long enough !!!\n        :param wavelength: wavelength in meter\n        \"\"\"\n        if wavelength is None:\n            wavelength = self.wavelength\n        if wavelength <= 0:\n            return [numpy.finfo(\"float32\").max] * len(rings)\n        rings = numpy.ascontiguousarray(rings, dtype=numpy.int32)\n\n        if wavelength != self.calibrant.wavelength:\n            self.calibrant.setWavelength_change2th(wavelength)\n        ary = self.calibrant.get_2th()\n        if len(ary) < rings.max():\n            # complete turn ~ 2pi ~ 7: help the optimizer to find the right way\n            ary += [10.0 * (rings.max() - len(ary))] * (1 + rings.max() - len(ary))\n        return numpy.array(ary, dtype=numpy.float64)[rings]\n\n    def residu1(self, param, d1, d2, rings):\n        return self.tth(d1, d2, param) - self.calc_2th(rings, self.wavelength)\n\n    def residu1_wavelength(self, param, d1, d2, rings):\n        return self.tth(d1, d2, param) - self.calc_2th(rings, param[6] * 1e-10)\n\n    def residu2(self, param, d1, d2, rings):\n        # dot product is faster ...\n        # return (self.residu1(param, d1, d2, rings) ** 2).sum()\n        t = self.residu1(param, d1, d2, rings)\n        return numpy.dot(t, t)\n\n    def residu2_weighted(self, param, d1, d2, rings, weight):\n        # return (weight * self.residu1(param, d1, d2, rings) ** 2).sum()\n        t = weight * self.residu1(param, d1, d2, rings)\n        return numpy.dot(t, t)\n\n    def residu2_wavelength(self, param, d1, d2, rings):\n        # return (self.residu1_wavelength(param, d1, d2, rings) ** 2).sum()\n        t = self.residu1_wavelength(param, d1, d2, rings)\n        return numpy.dot(t, t)\n\n    def residu2_wavelength_weighted(self, param, d1, d2, rings, weight):\n        # return (weight * self.residu1_wavelength(param, d1, d2, rings) ** 2).sum()\n        t = weight * self.residu1_wavelength(param, d1, d2, rings)\n        return numpy.dot(t, t)\n\n    def refine1(self):\n        self.param = numpy.array([self._dist, self._poni1, self._poni2,\n                                  self._rot1, self._rot2, self._rot3],\n                                 dtype=numpy.float64)\n        new_param, rc = leastsq(self.residu1, self.param,\n                                args=(self.data[:, 0],\n                                      self.data[:, 1],\n                                      self.data[:, 2]))\n        oldDeltaSq = self.chi2(tuple(self.param))\n        newDeltaSq = self.chi2(tuple(new_param))\n        logger.info(\"Least square retcode=%s %s --> %s\",\n                    rc, oldDeltaSq, newDeltaSq)\n        if newDeltaSq < oldDeltaSq:\n            i = abs(self.param - new_param).argmax()\n            d = [\"dist\", \"poni1\", \"poni2\", \"rot1\", \"rot2\", \"rot3\"]\n            logger.info(\"maxdelta on %s: %s --> %s \",\n                        d[i], self.param[i], new_param[i])\n            self.set_param(new_param)\n            return newDeltaSq\n        else:\n            return oldDeltaSq\n\n    def refine2(self, maxiter=1000000, fix=None):\n        if fix is None:\n            fix = [\"wavelength\"]\n        d = [\"dist\", \"poni1\", \"poni2\", \"rot1\", \"rot2\", \"rot3\"]\n        param = []\n        bounds = []\n        for i in d:\n            param.append(getattr(self, i))\n            if i in fix:\n                val = getattr(self, i)\n                bounds.append((val, val))\n            else:\n                bounds.append((getattr(self, \"_%s_min\" % i), getattr(self, \"_%s_max\" % i)))\n        self.param = numpy.array(param)\n        if self.data.shape[-1] == 3:\n            pos0 = self.data[:, 0]\n            pos1 = self.data[:, 1]\n            ring = self.data[:, 2].astype(numpy.int32)\n            weight = None\n            new_param = fmin_slsqp(self.residu2, self.param, iter=maxiter,\n                                   args=(pos0, pos1, ring),\n                                   bounds=bounds,\n                                   acc=1.0e-12,\n                                   iprint=(logger.getEffectiveLevel() <= logging.INFO))\n\n        elif self.data.shape[-1] == 4:\n            pos0 = self.data[:, 0]\n            pos1 = self.data[:, 1]\n            ring = self.data[:, 2].astype(numpy.int32)\n            weight = self.data[:, 3]\n            new_param = fmin_slsqp(self.residu2_weighted, self.param, iter=maxiter,\n                                   args=(pos0, pos1, ring, weight),\n                                   bounds=bounds,\n                                   acc=1.0e-12,\n                                   iprint=(logger.getEffectiveLevel() <= logging.INFO))\n        oldDeltaSq = self.chi2() / self.data.shape[0]\n        newDeltaSq = self.chi2(new_param) / self.data.shape[0]\n        logger.info(\"Constrained Least square %s --> %s\",\n                    oldDeltaSq, newDeltaSq)\n        if newDeltaSq < oldDeltaSq:\n            i = abs(self.param - new_param).argmax()\n\n            logger.info(\"maxdelta on %s: %s --> %s \",\n                        d[i], self.param[i], new_param[i])\n            self.set_param(new_param)\n            return newDeltaSq\n        else:\n            return oldDeltaSq\n\n    def refine2_wavelength(self, maxiter=1000000, fix=None):\n        if fix is None:\n            fix = [\"wavelength\"]\n        d = [\"dist\", \"poni1\", \"poni2\", \"rot1\", \"rot2\", \"rot3\", \"wavelength\"]\n\n        self.param = numpy.array([self.dist, self.poni1, self.poni2,\n                                  self.rot1, self.rot2, self.rot3, self.wavelength],\n                                 dtype=numpy.float64)\n        param = []\n        bounds = []\n        for i in d:\n            param.append(getattr(self, i))\n            if i in fix:\n                val = getattr(self, i)\n                bounds.append((val, val))\n            else:\n                bounds.append((getattr(self, \"_%s_min\" % i), getattr(self, \"_%s_max\" % i)))\n        # wavelength is multiplied to 10^10 to have values in the range 0.1-10: better numerical differentiation\n        bounds[-1] = (bounds[-1][0] * 1e10, bounds[-1][1] * 1e10)\n        param[-1] = 1e10 * param[-1]\n        self.param = numpy.array(param)\n        if self.data.shape[-1] == 3:\n            pos0 = self.data[:, 0]\n            pos1 = self.data[:, 1]\n            ring = self.data[:, 2].astype(numpy.int32)\n            weight = None\n            new_param = fmin_slsqp(self.residu2_wavelength,\n                                   self.param, iter=maxiter,\n                                   args=(pos0, pos1, ring),\n                                   bounds=bounds,\n                                   acc=1.0e-12,\n                                   iprint=(logger.getEffectiveLevel() <= logging.INFO))\n\n        elif self.data.shape[-1] == 4:\n            pos0 = self.data[:, 0]\n            pos1 = self.data[:, 1]\n            ring = self.data[:, 2].astype(numpy.int32)\n            weight = self.data[:, 3]\n            new_param = fmin_slsqp(self.residu2_wavelength_weighted,\n                                   self.param, iter=maxiter,\n                                   args=(pos0, pos1, ring, weight),\n                                   bounds=bounds,\n                                   acc=1.0e-12,\n                                   iprint=(logger.getEffectiveLevel() <= logging.INFO))\n        oldDeltaSq = self.chi2_wavelength() / self.data.shape[0]\n        newDeltaSq = self.chi2_wavelength(new_param) / self.data.shape[0]\n        logger.info(\"Constrained Least square %s --> %s\",\n                    oldDeltaSq, newDeltaSq)\n        if newDeltaSq < oldDeltaSq:\n            i = abs(self.param - new_param).argmax()\n            logger.info(\"maxdelta on %s: %s --> %s \",\n                        d[i], self.param[i], new_param[i])\n\n            self.set_param(new_param[:-1])\n            self.wavelength = 1e-10 * new_param[-1]\n            return newDeltaSq\n        else:\n            return oldDeltaSq\n\n    def simplex(self, maxiter=1000000):\n        self.param = numpy.array([self.dist, self.poni1, self.poni2,\n                                  self.rot1, self.rot2, self.rot3],\n                                 dtype=numpy.float64)\n        new_param = fmin(self.residu2, self.param,\n                         args=(self.data[:, 0],\n                               self.data[:, 1],\n                               self.data[:, 2]),\n                         maxiter=maxiter,\n                         xtol=1.0e-12)\n        oldDeltaSq = self.chi2(tuple(self.param)) / self.data.shape[0]\n        newDeltaSq = self.chi2(tuple(new_param)) / self.data.shape[0]\n        logger.info(\"Simplex %s --> %s\", oldDeltaSq, newDeltaSq)\n        if newDeltaSq < oldDeltaSq:\n            i = abs(self.param - new_param).argmax()\n            d = [\"dist\", \"poni1\", \"poni2\", \"rot1\", \"rot2\", \"rot3\"]\n            logger.info(\"maxdelta on %s : %s --> %s \",\n                        d[i], self.param[i], new_param[i])\n            self.set_param(new_param)\n            return newDeltaSq\n        else:\n            return oldDeltaSq\n\n    def anneal(self, maxiter=1000000):\n        self.param = [self.dist, self.poni1, self.poni2,\n                      self.rot1, self.rot2, self.rot3]\n        result = anneal(self.residu2, self.param,\n                        args=(self.data[:, 0],\n                              self.data[:, 1],\n                              self.data[:, 2]),\n                        lower=[self._dist_min,\n                               self._poni1_min,\n                               self._poni2_min,\n                               self._rot1_min,\n                               self._rot2_min,\n                               self._rot3_min],\n                        upper=[self._dist_max,\n                               self._poni1_max,\n                               self._poni2_max,\n                               self._rot1_max,\n                               self._rot2_max,\n                               self._rot3_max],\n                        maxiter=maxiter)\n        new_param = result[0]\n        oldDeltaSq = self.chi2() / self.data.shape[0]\n        newDeltaSq = self.chi2(new_param) / self.data.shape[0]\n        logger.info(\"Anneal  %s --> %s\", oldDeltaSq, newDeltaSq)\n        if newDeltaSq < oldDeltaSq:\n            i = abs(self.param - new_param).argmax()\n            d = [\"dist\", \"poni1\", \"poni2\", \"rot1\", \"rot2\", \"rot3\"]\n            logger.info(\"maxdelta on %s : %s --> %s \",\n                        d[i], self.param[i], new_param[i])\n            self.set_param(new_param)\n            return newDeltaSq\n        else:\n            return oldDeltaSq\n\n    def chi2(self, param=None):\n        if param is None:\n            param = self.param[:]\n        return self.residu2(param,\n                            self.data[:, 0], self.data[:, 1], self.data[:, 2])\n\n    def chi2_wavelength(self, param=None):\n        if param is None:\n            param = self.param\n            if len(param) == 6:\n                param.append(1e10 * self.wavelength)\n        return self.residu2_wavelength(param,\n                                       self.data[:, 0],\n                                       self.data[:, 1],\n                                       self.data[:, 2])\n\n    def curve_fit(self, with_rot=True):\n        \"\"\"Refine the geometry and provide confidence interval\n        Use curve_fit from scipy.optimize to not only refine the geometry (unconstrained fit)\n\n        :param with_rot: include rotation intro error measurment\n        :return: std_dev, confidence\n        \"\"\"\n        if not curve_fit:\n            import scipy\n            logger.error(\"curve_fit method needs a newer scipy: at lease scipy 0.9, you are running: %s\", scipy.version.version)\n        d1 = self.data[:, 0]\n        d2 = self.data[:, 1]\n        size = d1.size\n        x = d1, d2\n        rings = self.data[:, 2].astype(numpy.int32)\n        f_with_rot = lambda x, *param: self.tth(x[0], x[1], numpy.concatenate((param, [self.rot3])))\n        f_no_rot = lambda x, *param: self.tth(x[0], x[1], numpy.concatenate((param, [self.rot1, self.rot2, self.rot3])))\n        y = self.calc_2th(rings, self.wavelength)\n        param0 = numpy.array([self.dist, self.poni1, self.poni2, self.rot1, self.rot2, self.rot3], dtype=numpy.float64)\n        ref = self.residu2(param0, d1, d2, rings)\n        print(\"param0: %s %s\" % (param0, ref))\n        if with_rot:\n            popt, pcov = curve_fit(f_with_rot, x, y, param0[:-1])\n            popt = numpy.concatenate((popt, [self.rot3]))\n        else:\n            popt, pcov = curve_fit(f_no_rot, x, y, param0[:-3])\n            popt = numpy.concatenate((popt, [self.rot1, self.rot2, self.rot3]))\n        obt = self.residu2(popt, d1, d2, rings)\n        print(\"param1: %s %s\" % (popt, obt))\n        print(pcov)\n        err = numpy.sqrt(numpy.diag(pcov))\n        print(\"err: %s\" % err)\n        if obt < ref:\n            self.set_param(popt)\n        error = {}\n        confidence = {}\n        for k, v in zip((\"dist\", \"poni1\", \"poni2\", \"rot1\", \"rot2\", \"rot3\"), err):\n            error[k] = v\n            confidence[k] = 1.96 * v / numpy.sqrt(size)\n\n        print(\"Std dev  as sqrt of the diag of covariance:\\n%s\" % error)\n        print(\"Confidence as 1.95 sigma/sqrt(n):\\n%s\" % confidence)\n        return error, confidence\n\n    def confidence(self, with_rot=True):\n        \"\"\"Confidence interval obtained from the second derivative of the error function\n        next to its minimum value.\n\n        Note the confidence interval increases with the number of points which is \"surprizing\"\n\n        :param with_rot: if true include rot1 & rot2 in the parameter set.\n        :return: std_dev, confidence\n        \"\"\"\n        epsilon = 1e-5\n        d1 = self.data[:, 0]\n        d2 = self.data[:, 1]\n        r = self.data[:, 2].astype(numpy.int32)\n        param0 = numpy.array([self.dist, self.poni1, self.poni2, self.rot1, self.rot2, self.rot3], dtype=numpy.float64)\n        ref = self.residu2(param0, d1, d2, r)\n        print(ref)\n        if with_rot:\n            size = 5\n        else:\n            size = 3\n        hessian = numpy.zeros((size, size), dtype=numpy.float64)\n\n        delta = abs(epsilon * param0)\n        delta[abs(param0) < epsilon] = epsilon\n        print(delta)\n        for i in range(size):\n            # Diagonal terms:\n            deltai = delta[i]\n            param = param0.copy()\n            param[i] += deltai\n            value_plus = self.residu2(param, d1, d2, r)\n            param = param0.copy()\n            param[i] -= deltai\n            value_moins = self.residu2(param, d1, d2, r)\n            hessian[i, i] = (value_plus + value_moins - 2.0 * ref) / (deltai ** 2)\n\n            for j in range(i + 1, size):\n                # if i == j: continue\n                deltaj = delta[j]\n                param = param0.copy()\n                param[i] += deltai\n                param[j] += deltaj\n                value_plus_plus = self.residu2(param, d1, d2, r)\n                param = param0.copy()\n                param[i] -= deltai\n                param[j] -= deltaj\n                value_moins_moins = self.residu2(param, d1, d2, r)\n                param = param0.copy()\n                param[i] += deltai\n                param[j] -= deltaj\n                value_plus_moins = self.residu2(param, d1, d2, r)\n                param = param0.copy()\n                param[i] -= deltai\n                param[j] += deltaj\n                value_moins_plus = self.residu2(param, d1, d2, r)\n                hessian[j, i] = hessian[i, j] = (value_plus_plus + value_moins_moins - value_plus_moins - value_moins_plus) / (4.0 * deltai * deltaj)\n        print(hessian)\n        w, v = numpy.linalg.eigh(hessian)\n        print(\"eigen val: %s\" % w)\n        print(\"eigen vec: %s\" % v)\n        cov = numpy.linalg.inv(hessian)\n        print(cov)\n        err = numpy.sqrt(numpy.diag(cov))\n        print(\"err: %s\" % err)\n        error = {}\n        for k, v in zip((\"dist\", \"poni1\", \"poni2\", \"rot1\", \"rot2\", \"rot3\"), err):\n            error[k] = v\n        confidence = {}\n        for i, k in enumerate((\"dist\", \"poni1\", \"poni2\", \"rot1\", \"rot2\", \"rot3\")):\n            if i < size:\n                confidence[k] = numpy.sqrt(ref / hessian[i, i])\n        print(\"std_dev as sqrt of the diag of inv hessian:\\n%s\" % error)\n        print(\"Convidence as sqrt of the error function /  hessian:\\n%s\" % confidence)\n        return error, confidence\n\n    def roca(self):\n        \"\"\"\n        run roca to optimise the parameter set\n        \"\"\"\n        tmpf = tempfile.NamedTemporaryFile()\n        for line in self.data:\n            tmpf.write(\"%s %s %s %s\" % (line[2], line[0], line[1], os.linesep))\n        tmpf.flush()\n        roca = subprocess.Popen(\n            [ROCA, \"debug=8\", \"maxdev=1\", \"input=\" + tmpf.name,\n             str(self.pixel1), str(self.pixel2),\n             str(self.poni1 / self.pixel1), str(self.poni2 / self.pixel2),\n             str(self.dist), str(self.rot1), str(self.rot2), str(self.rot3)],\n            stdout=subprocess.PIPE)\n        new_param = [self.dist, self.poni1, self.poni2,\n                     self.rot1, self.rot2, self.rot3]\n        for line in roca.stdout:\n            word = line.split()\n            if len(word) == 3:\n                if word[0] == \"cen1\":\n                    new_param[1] = float(word[1]) * self.pixel1\n                if word[0] == \"cen2\":\n                    new_param[2] = float(word[1]) * self.pixel2\n                if word[0] == \"dis\":\n                    new_param[0] = float(word[1])\n                if word[0] == \"rot1\":\n                    new_param[3] = float(word[1])\n                if word[0] == \"rot2\":\n                    new_param[4] = float(word[1])\n                if word[0] == \"rot3\":\n                    new_param[5] = float(word[1])\n        print(\"Roca %s --> %s\" % (self.chi2() / self.data.shape[0], self.chi2(new_param) / self.data.shape[0]))\n        if self.chi2(tuple(new_param)) < self.chi2(tuple(self.param)):\n            self.param = new_param\n            self.dist, self.poni1, self.poni2, \\\n                self.rot1, self.rot2, self.rot3 = tuple(new_param)\n\n        tmpf.close()\n\n    def set_dist_max(self, value):\n        if isinstance(value, float):\n            self._dist_max = value\n        else:\n            self._dist_max = float(value)\n\n    def get_dist_max(self):\n        return self._dist_max\n\n    dist_max = property(get_dist_max, set_dist_max)\n\n    def set_dist_min(self, value):\n        if isinstance(value, float):\n            self._dist_min = value\n        else:\n            self._dist_min = float(value)\n\n    def get_dist_min(self):\n        return self._dist_min\n\n    dist_min = property(get_dist_min, set_dist_min)\n\n    def set_poni1_min(self, value):\n        if isinstance(value, float):\n            self._poni1_min = value\n        else:\n            self._poni1_min = float(value)\n\n    def get_poni1_min(self):\n        return self._poni1_min\n\n    poni1_min = property(get_poni1_min, set_poni1_min)\n\n    def set_poni1_max(self, value):\n        if isinstance(value, float):\n            self._poni1_max = value\n        else:\n            self._poni1_max = float(value)\n\n    def get_poni1_max(self):\n        return self._poni1_max\n\n    poni1_max = property(get_poni1_max, set_poni1_max)\n\n    def set_poni2_min(self, value):\n        if isinstance(value, float):\n            self._poni2_min = value\n        else:\n            self._poni2_min = float(value)\n\n    def get_poni2_min(self):\n        return self._poni2_min\n\n    poni2_min = property(get_poni2_min, set_poni2_min)\n\n    def set_poni2_max(self, value):\n        if isinstance(value, float):\n            self._poni2_max = value\n        else:\n            self._poni2_max = float(value)\n\n    def get_poni2_max(self):\n        return self._poni2_max\n\n    poni2_max = property(get_poni2_max, set_poni2_max)\n\n    def set_rot1_min(self, value):\n        if isinstance(value, float):\n            self._rot1_min = value\n        else:\n            self._rot1_min = float(value)\n\n    def get_rot1_min(self):\n        return self._rot1_min\n\n    rot1_min = property(get_rot1_min, set_rot1_min)\n\n    def set_rot1_max(self, value):\n        if isinstance(value, float):\n            self._rot1_max = value\n        else:\n            self._rot1_max = float(value)\n\n    def get_rot1_max(self):\n        return self._rot1_max\n\n    rot1_max = property(get_rot1_max, set_rot1_max)\n\n    def set_rot2_min(self, value):\n        if isinstance(value, float):\n            self._rot2_min = value\n        else:\n            self._rot2_min = float(value)\n\n    def get_rot2_min(self):\n        return self._rot2_min\n\n    rot2_min = property(get_rot2_min, set_rot2_min)\n\n    def set_rot2_max(self, value):\n        if isinstance(value, float):\n            self._rot2_max = value\n        else:\n            self._rot2_max = float(value)\n\n    def get_rot2_max(self):\n        return self._rot2_max\n\n    rot2_max = property(get_rot2_max, set_rot2_max)\n\n    def set_rot3_min(self, value):\n        if isinstance(value, float):\n            self._rot3_min = value\n        else:\n            self._rot3_min = float(value)\n\n    def get_rot3_min(self):\n        return self._rot3_min\n\n    rot3_min = property(get_rot3_min, set_rot3_min)\n\n    def set_rot3_max(self, value):\n        if isinstance(value, float):\n            self._rot3_max = value\n        else:\n            self._rot3_max = float(value)\n\n    def get_rot3_max(self):\n        return self._rot3_max\n\n    rot3_max = property(get_rot3_max, set_rot3_max)\n\n    def set_wavelength_min(self, value):\n        if isinstance(value, float):\n            self._wavelength_min = value\n        else:\n            self._wavelength_min = float(value)\n\n    def get_wavelength_min(self):\n        return self._wavelength_min\n\n    wavelength_min = property(get_wavelength_min, set_wavelength_min)\n\n    def set_wavelength_max(self, value):\n        if isinstance(value, float):\n            self._wavelength_max = value\n        else:\n            self._wavelength_max = float(value)\n\n    def get_wavelength_max(self):\n        return self._wavelength_max\n\n    wavelength_max = property(get_wavelength_max, set_wavelength_max)\n", "meta": {"hexsha": "bcf7879b58f46d7f63c4630cfbab966997148104", "size": 32523, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyFAI/geometryRefinement.py", "max_stars_repo_name": "vallsv/pyFAI", "max_stars_repo_head_hexsha": "64143652c2b219978ec370bf2fa215af01f937c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyFAI/geometryRefinement.py", "max_issues_repo_name": "vallsv/pyFAI", "max_issues_repo_head_hexsha": "64143652c2b219978ec370bf2fa215af01f937c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-09-12T11:58:05.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-12T11:58:05.000Z", "max_forks_repo_path": "pyFAI/geometryRefinement.py", "max_forks_repo_name": "vallsv/pyFAI", "max_forks_repo_head_hexsha": "64143652c2b219978ec370bf2fa215af01f937c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2014833127, "max_line_length": 149, "alphanum_fraction": 0.5461365803, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 8426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.1763246531524849}}
{"text": "from functions import *\nimport pandas as pd\nimport numpy as np\nimport os\n\n\nclass SMARTS:\n    \"\"\"\n    Clase que contiene las funciones que interactuaran con el modelo SMARTS\n    \"\"\"\n\n    def __init__(self, parameters={}, station=\"\"):\n        \"\"\"\n        Valores con los cuales se inicializa el modelo SMARTS\n        ### inputs\n        + station      ----> Estacion que se analizara\n        + hour_i       ----> Hora inicial para correr el modelo\n        + hour_f       ----> Hora final para correr el modelo\n        + lon_ i       ----> Longitud de onda inicial para el modelo\n        + lon_ f       ----> Longitud de onda final para el modelo\n        + igas         ----> Card 6a del Modelo SMARTS\n        + delta_lon    ----> Número de longitudes de onda que se saltara el resultado del modelo\n        + total_minute ----> Total minutos que correra el modelo\n        \"\"\"\n        self.parameters = parameters\n        self.delta_lon = parameters[\"wavelength initial\"]-280+1\n        self.total_minute = int(\n            (parameters[\"hour final\"]-parameters[\"hour initial\"])*60)\n        self.define_location(station)\n\n    def define_location(self, station):\n        stations = {\n            \"centro\": {\n                \"Lat\": 25.670,\n                \"Lon\": -100.338,\n                \"Height\": 0.560},\n            \"noreste\": {\n                \"Lat\": 25.750,\n                \"Lon\": -100.255,\n                \"Height\": 0.476},\n            \"noroeste\": {\n                \"Lat\": 25.757,\n                \"Lon\": -100.366,\n                \"Height\": 0.571},\n            \"sureste2\": {\n                \"Lat\": 25.646,\n                \"Lon\": -100.096,\n                \"Height\": 0.387},\n            \"suroeste\": {\n                \"Lat\": 25.676,\n                \"Lon\": -100.464,\n                \"Height\": 0.694}\n        }\n        self.lat = stations[station][\"Lat\"]\n        self.lon = stations[station][\"Lon\"]\n        self.height = stations[station][\"Height\"]\n\n    def atmosphere_state(self):\n        pass\n\n    def run(self, day=1, month=1, year=2000, o3=250.51, aod=0.2, name=\"\", path=\"\"):\n        \"\"\"\n        Función que ejecuta el modelo SMARTS\n        ### inputs:\n        + day   ----> Dia del año\n        + month ----> Mes del año númerico\n        + year  ----> Año del dia por analizar\n        + o3    ----> ozono del dia\n        + aod   ----> AOD del dia\n        + name  ----> nombre del archivo de resultados\n        + path  ----> direccion para guardar los archivos\n        \"\"\"\n        file_date = open(\"{}/{}.txt\".format(path,\n                                            name),\n                         \"w\")\n        for minute in range(self.total_minute):\n            # Hora y minutos a hora con decimal\n            minutes = self.hour_and_minute_to_hours(minute)\n            # Escribir el archivo de input para el modelo SMARTS\n            self.write_data_input(day,\n                                  month,\n                                  year,\n                                  minutes,\n                                  o3,\n                                  aod)\n            os.system(\"./smarts.out\")\n            # Resultado de la in7tegral a partir de los resultaos del modelo SMARTS\n            integral = self.read_results()\n            # Escritura de los resultados\n            file_date.write(\"{} {}\\n\".format(minutes,\n                                             integral))\n        file_date.close()\n\n    def hour_and_minute_to_hours(self, minute=5):\n        return round(self.parameters[\"hour initial\"]+minute/60, 4)\n\n    def read_results(self, name_result=\"data.ext.txt\"):\n        \"\"\"\n        Funcion que realiza la lectura de los resultados del SMARTS\n        y realiza la integral del especto a cada minuto\n        Describción de variables\n        + wavelength ----> longitudes de onda de los resultados del modelo SMARTS\n        + irra       ----> Valor del especto de los resultados del modelo SMARTS\n        + integral   ----> Valor que irradiancia solar\n        \"\"\"\n        # Lectura de los resultados del modelo SMARTS\n        wavelength, irradiance = np.loadtxt(\n            name_result, skiprows=self.delta_lon, unpack=True)\n        integral = irradiance[0]\n        # Calculo de la irradiancia solar a partir de los resultados del modelo SMARTS\n        size = np.size(irradiance)\n        for i in range(1, size):\n            integral += irradiance[i]*(wavelength[i]-wavelength[i-1])\n        # Eliminación de los archivos\n        os.system(\"rm data*\")\n        # Formato de la integral\n        integral = str(round(integral))\n        return integral\n\n    def write_data_input(self, day=1, month=1, year=2000, hour=8, ozono=250.51, aod=0.5):\n        \"\"\"\n        Formato del input del modelo SMARTS\n        ### inputs:\n        + day   -> Dia del año\n        + month -> Mes del año númerico\n        + year  -> Año del dia por analizar\n        + hour  -> Hora del calculo de la irradiancia\n        + ozono -> ozono del dia\n        + aod   -> AOD del dia\n        + igas  -> Card 6a\n        \"\"\"\n        file = open(\"data.inp.txt\", \"w\")\n        file.write(\" 'AOD={} '\\n\".format(aod))\n        # Card 2\n        file.write(\" 2\\n\")\n        # Card 2a\n        # lat,altit,height\n        file.write(\" {:.3f} {} {}\\n\".format(self.lat,\n                                            self.height,\n                                            0))\n        # Card 3\n        # IATMOS\n        file.write(\" 1\\n\")\n        # Card 3a\n        file.write(\" 'USSA'\\n\")\n        # Card 4\n        # H2O\n        file.write(\" 1\\n\")\n        # Card 4a\n        file.write(\" 0\\n\")\n        # Card 5\n        # Ozono\n        file.write(\" {} {:.4f}\\n\".format(1,\n                                         ozono/1000))\n        # Card 6\n        file.write(\" 0\\n\")\n        # Card 6a\n        # Pristine ----> 1\n        # Moderate ----> 3\n        file.write(\" {}\\n\".format(self.parameters[\"igas\"]))\n        # Card 7\n        # Co2\n        file.write(\" 390\\n\")\n        # Card 7a\n        file.write(\" 0\\n\")\n        # Card 8\n        file.write(\" 'S&F_URBAN'\\n\")\n        # Card 9\n        file.write(\" 5\\n\")\n        # Card 9a\n        file.write(\" {} {}\\n\".format(aod,\n                                     2))\n        # Card 10\n        file.write(\" 18\\n\")\n        # Card 10b\n        file.write(\" 1\\n\")\n        # Card 10d\n        # IALBDG, TILT,WAZIM\n        file.write(\" {} {} {}\\n\".format(51,\n                                        37.,\n                                        180.))\n        # Card 11---\n        # Wave min, Wave max, suncor, solar cons\n        file.write(\" {} {} {} {}\\n\".format(self.parameters[\"wavelength initial\"],\n                                           self.parameters[\"wavelength final\"],\n                                           1,\n                                           1366.1))\n        # ------Card 12---\n        file.write(\" 2\\n\")\n        # Card 12a\n        # Wave min, Wave max, inter wave\n        file.write(\" {} {} {}\\n\".format(self.parameters[\"wavelength initial\"],\n                                        self.parameters[\"wavelength final\"],\n                                        1))\n        # Card 12b\n        file.write(\" 1\\n\")\n        # Card 12c\n        file.write(\" 4\\n\")\n        # Card 13\n        file.write(\" 1\\n\")\n        # Card 13a\n        #  slope, apert, limit\n        file.write(\" 0 2.9 0\\n\")\n        # Card 14\n        file.write(\" 0\\n\")\n        # Card 15\n        file.write(\" 0\\n\")\n        # Card 16\n        file.write(\" 1\\n\")\n        # Card 17\n        file.write(\" 3\\n\")\n        # Card 17a\n        # Year, month, day, hour, latit, longit, zone\n        file.write(\" {} {} {} {} {} {} {}\\n\".format(year,\n                                                    month,\n                                                    day,\n                                                    hour,\n                                                    self.lat,\n                                                    self.lon,\n                                                    -6))\n        file.close()\n\n\nclass SMARTS_DR(SMARTS):\n    \"\"\"\n    Clase heredada de SMARTS, uso especifico para la versión del modelo\n    que calcula el AOD a partir de las mediciones y una RD dada\n    \"\"\"\n\n    def __init__(self, parameters={}, station=\"\"):\n        \"\"\"\n        Valores con los cuales se inicializa el modelo SMARTS\n        ### inputs\n        + hour_i       ----> Hora inicial para correr el modelo\n        + hour_f       ----> Hora final para correr el modelo\n        + lon_ i       ----> Longitud de onda inicial para el modelo\n        + lon_ f       ----> Longitud de onda final para el modelo\n        + delta_lon    ----> Número de longitudes de onda que se saltara\n                           el resultado del modelo\n        + total_minute ----> Total minutos que correra el modelo\n        + RD_lim       ----> RD al cual se quiere llegar\n        + RD_delta     ----> Mas menos del RD\n        \"\"\"\n        SMARTS.__init__(self,\n                        parameters=parameters,\n                        station=station)\n        self.parameters = parameters\n        self.station = station\n        self.delta_hour = int(\n            self.parameters[\"hour final\"]-self.parameters[\"hour initial\"])\n        self.select_path_name_for_results()\n\n    def select_path_name_for_results(self):\n        names = {\n            1: \"pristine\",\n            3: \"moderate\"\n        }\n        name = names[self.parameters[\"igas\"]]\n        self.parameters[\"path results\"] = self.parameters[\"path results\"]+name+\"/\"\n        self.parameters[\"file results\"] = self.parameters[\"file results\"]+name\n\n    def run_search(self):\n        # Direccion donde se encuentran los datos de cada estacion\n        station_path = \"{}{}/\".format(self.parameters[\"path stations\"],\n                                      self.station)\n        path_results = \"{}{}\".format(station_path,\n                                     self.parameters[\"path results\"])\n        # Creacion de la carpeta resultados si es que no existe\n        mkdir(self.parameters[\"path results\"],\n              path=station_path)\n        # Archivo de resultados donde se guardara el AOD y la RD de cada dia\n        AOD_file = open(\"{}{}.csv\".format(station_path,\n                                          self.parameters[\"file results\"]),\n                        \"w\")\n        AOD_file.write(\"Date,year,month,day,ozone,AOD,RD\\n\")\n        # Lectura de los parametros de entrada de cada dia\n        data = pd.read_csv(\"{}{}\".format(station_path,\n                                         self.parameters[\"file data\"]))\n        for index in data.index:\n            print(\"\\n\\tCalculando el dia {}-{}-{}\".format(data[\"Year\"][index],\n                                                          str(data[\"Month\"][index]).zfill(\n                2),\n                str(data[\"Day\"][index]).zfill(2)))\n            print(\"\\tAOD_i\\tAOD\\tAOD_f\\tRD\")\n            self.initialize_aod(self.parameters[\"AOD inicial\"],\n                                self.parameters[\"AOD limite\"])\n            # Lectura de las mediciones\n            hour, measurements = np.loadtxt(\"{}/Mediciones/{}.txt\".format(station_path,\n                                                                          data[\"Date\"][index]),\n                                            skiprows=self.parameters[\"hour initial\"],\n                                            unpack=True)\n            # Valor maximo de medicion, esta se usara para el calculo de la RD\n            data_max = np.max(measurements[0:self.delta_hour+1])\n            var = False\n            # Primer valor de AOD, se puede cambiar por cualquier otro siempre y cuando este entre aod_i y aod_lim\n            aod = self.obtain_aod(self.aod_i,\n                                  self.aod_lim)\n            # Control de iteracciones\n            iter = 0\n            while not(var) and iter < 10:\n                # Ejecucion del modelo SMARTS con los parametros de cada dia\n                self.run(day=data[\"Day\"][index],\n                         month=data[\"Month\"][index],\n                         year=data[\"Year\"][index],\n                         o3=data[\"Ozone\"][index],\n                         aod=aod,\n                         name=data[\"Date\"][index],\n                         path=path_results)\n                # Valor maximo de los resultados del modelo SMARTS\n                data_model = self.obtain_maximum_from_results(data[\"Date\"][index],\n                                                              path=path_results)\n                # Calculo del RD y verificación si se cumple la condicion\n                var, RD = self.RD_decision(data_model,\n                                           data_max)\n                print(\"\\t{}\\t{}\\t{}\\t{}\".format(self.aod_i,\n                                                aod,\n                                                self.aod_lim,\n                                                RD,))\n                if var:\n                    # Si se cumple entonces se escribiran los parametros, el AOD y la RD en el archivo de resultados\n                    self.write_results(AOD_file,\n                                       data[\"Date\"][index],\n                                       data[\"Year\"][index],\n                                       data[\"Month\"][index],\n                                       data[\"Day\"][index],\n                                       data[\"Ozone\"][index],\n                                       aod,\n                                       RD)\n                else:\n                    # Se calculara un nuevo AOD siguiendo el algoritmo de busqueda binaria\n                    aod = self.aod_binary_search(aod, RD)\n                    # Si se queda en un intervalo muy pequeño se verificara que cumpla la condicion si lo hace entonces escribira en el archivo el resultado, esto llega a pasar  si se pone un delta_RD menor a 1\n                    if self.aod_lim == aod and abs(RD-self.RD_lim) < 2:\n                        self.write_results(AOD_file,\n                                           data[\"Date\"][index],\n                                           data[\"Year\"][index],\n                                           data[\"Month\"][index],\n                                           data[\"Day\"][index],\n                                           data[\"Ozone\"][index],\n                                           aod,\n                                           RD)\n                        var = True\n                    iter += 1\n        AOD_file.close()\n\n    def initialize_aod(self, aod_i, aod_lim):\n        \"\"\"\n        Funcion que inicializa el limite inferior y superior del AOD\n        \"\"\"\n        self.aod_i = aod_i\n        self.aod_lim = aod_lim\n\n    def obtain_aod(self, aod_i, aod_f):\n        return round((aod_i+aod_f)/2, 3)\n\n    def obtain_maximum_from_results(self, name, path=\"\"):\n        data_model = np.loadtxt(\"{}{}.txt\".format(path,\n                                                  name),\n                                usecols=1)\n        pos = (np.where(np.max(data_model) == data_model)[0])[0]\n        data_model = np.mean(data_model[pos-30:pos+31])\n        return data_model\n\n    def RD_decision(self, model, measurement):\n        \"\"\"\n        Funcion que calcula la RD entre el modelo y la medicion\n        \"\"\"\n        var = False\n        RD = round(100*(model-measurement)/measurement, 3)\n        if self.RD_search(RD):\n            var = True\n        return var, RD\n\n    def aod_binary_search(self, aod, RD):\n        \"\"\"\n        Función que calcula el AOD que se introducira en el modelo SMARTS\n        este emplea una busqueda binaria para que sea más eficiente\n        \"\"\"\n        if self.RD_search(RD):\n            self.aod_i = aod\n        elif RD > self.parameters[\"RD limite\"]+self.parameters[\"RD delta\"]:\n            self.aod_i = aod\n        else:\n            self.aod_lim = aod\n        aod = self.obtain_aod(self.aod_lim,\n                              self.aod_i)\n        return aod\n\n    def RD_search(self, RD):\n        lim_i = self.parameters[\"RD limite\"]-self.parameters[\"RD delta\"]\n        lim_f = self.parameters[\"RD limite\"]+self.parameters[\"RD delta\"]\n        return lim_i < RD < lim_f\n\n    def write_results(self, file, date, year, month, day, o3, aod, RD):\n        file.write(\"{},{},{},{},{},{:.3f},{:.2f}\\n\".format(date,\n                                                           year,\n                                                           month,\n                                                           day,\n                                                           o3,\n                                                           aod,\n                                                           RD))\n\n\nclass SMARTS_DR_SSAAER_CUSTOM(SMARTS_DR):\n    def __init__(self, parameters={}, station=\"\"):\n        SMARTS_DR.__init__(self,\n                           parameters=parameters,\n                           station=station)\n        self.parameters = parameters\n\n    def write_data_input(self, day=1, month=1, year=2000, hour=8, ozono=250.51, aod=0.5):\n        \"\"\"\n        Formato del input del modelo SMARTS\n        day   ----> Dia del año\n        month ----> Mes del año númerico\n        year  ----> Año del dia por analizar\n        hour  ----> Hora del calculo de la irradiancia\n        ozono ----> ozono del dia\n        aod   ----> AOD del dia\n        igas  ----> Card 6a\n        \"\"\"\n        file = open(\"data.inp.txt\", \"w\")\n        file.write(\" 'AOD={} '\\n\".format(aod))\n        # Card 2\n        file.write(\" 2\\n\")\n        # Card 2a\n        # lat,altit,height\n        file.write(\" {:.3f} {} {}\\n\".format(self.lat,\n                                            self.height,\n                                            0))\n        # Card 3\n        # IATMOS\n        file.write(\" 1\\n\")\n        # Card 3a\n        file.write(\" 'USSA'\\n\")\n        # Card 4\n        # H2O\n        file.write(\" 1\\n\")\n        # Card 4a\n        file.write(\" 0\\n\")\n        # Card 5\n        # Ozono\n        file.write(\" {} {:.4f}\\n\".format(1,\n                                         ozono/1000))\n        # Card 6\n        file.write(\" 0\\n\")\n        # Card 6a\n        # Pristine ----> 1\n        # Moderate ----> 3\n        file.write(\" {}\\n\".format(self.parameters[\"igas\"]))\n        # Card 7\n        # Co2\n        file.write(\" 390\\n\")\n        # Card 7a\n        file.write(\" 0\\n\")\n        # Card 8\n        file.write(\" 'USER'\\n\")\n        # Card 8a\n        # SSAAER Palancar\n        # Asymmetry Promedio de 550 nm y humedad ente 50-70%\n        file.write(\" {} {} {} {}\\n\".format(1, 1, 0.8, 0.68))\n        # Card 9\n        file.write(\" 5\\n\")\n        # Card 9a\n        file.write(\" {} {}\\n\".format(aod,\n                                     2))\n        # Card 10\n        file.write(\" 18\\n\")\n        # Card 10b\n        file.write(\" 1\\n\")\n        # Card 10d\n        # IALBDG, TILT,WAZIM\n        file.write(\" {} {} {}\\n\".format(51,\n                                        37.,\n                                        180.))\n        # Card 11---\n        # Wave min, Wave max, suncor, solar cons\n        file.write(\" {} {} {} {}\\n\".format(self.parameters[\"wavelength initial\"],\n                                           self.parameters[\"wavelength final\"],\n                                           1,\n                                           1366.1))\n        # ------Card 12---\n        file.write(\" 2\\n\")\n        # Card 12a\n        # Wave min, Wave max, inter wave\n        file.write(\" {} {} {}\\n\".format(self.parameters[\"wavelength initial\"],\n                                        self.parameters[\"wavelength final\"],\n                                        1))\n        # Card 12b\n        file.write(\" 1\\n\")\n        # Card 12c\n        file.write(\" 4\\n\")\n        # Card 13\n        file.write(\" 1\\n\")\n        # Card 13a\n        #  slope, apert, limit\n        file.write(\" 0 2.9 0\\n\")\n        # Card 14\n        file.write(\" 0\\n\")\n        # Card 15\n        file.write(\" 0\\n\")\n        # Card 16\n        file.write(\" 1\\n\")\n        # Card 17\n        file.write(\" 3\\n\")\n        # Card 17a\n        # Year, month, day, hour, latit, longit, zone\n        file.write(\" {} {} {} {} {} {} {}\\n\".format(year,\n                                                    month,\n                                                    day,\n                                                    hour,\n                                                    self.lat,\n                                                    self.lon,\n                                                    -6))\n        file.close()\n", "meta": {"hexsha": "f84208835540c27fb02a3d40b8e756a7ed277e9d", "size": 20475, "ext": "py", "lang": "Python", "max_stars_repo_path": "Scripts/SMARTS/SMARTS_algorithm.py", "max_stars_repo_name": "giovannilopez9808/Presentations", "max_stars_repo_head_hexsha": "8b8f33f9b7cbf01dfec81ebf73c0d2bfc3ee93bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Scripts/SMARTS/SMARTS_algorithm.py", "max_issues_repo_name": "giovannilopez9808/Presentations", "max_issues_repo_head_hexsha": "8b8f33f9b7cbf01dfec81ebf73c0d2bfc3ee93bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Scripts/SMARTS/SMARTS_algorithm.py", "max_forks_repo_name": "giovannilopez9808/Presentations", "max_forks_repo_head_hexsha": "8b8f33f9b7cbf01dfec81ebf73c0d2bfc3ee93bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6802325581, "max_line_length": 210, "alphanum_fraction": 0.4372161172, "include": true, "reason": "import numpy", "num_tokens": 4574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.29746993014852224, "lm_q1q2_score": 0.1763004920896993}}
{"text": "import numpy as np\nfrom parameter_loader import load_parameters\nfrom math import pi\n\n\nclass FullModel:\n    \"\"\"\n    A class that defines the full model for actomyosin contraction in soft pillar rings that accounts for both myosin\n    filament binding and density changes\n\n    Attributes:\n        parameter_file (str):\n            path to a file that contains all necessary parameters for the model (see provided examples).\n\n    Methods:\n        k_off_fil(total_force):\n            calculates the load dependent steady state off-rate of a myosin filament.\n\n        rhs(t, y):\n            calculates the right hand side of the set of differential equations that describe the model.\n    \n        velocity(t, force, N):\n            calculates the deflection velocity of the tip of the pillar.\n    \"\"\"\n    \n    def __init__(self, parameter_file, pillar_stiffness):\n        \"\"\"\n        Sets all the necessary parameters for the FullModel object.\n\n        Parameters:\n            parameter_file (str):\n                path to a file that contains all necessary parameters for the model (see provided examples).\n            pillar_stiffness (float):\n                stiffness of the pillars in the pillar ring in pN/um.\n        \"\"\"\n        self.x_catch, self.x_slip, self.k_off0_catch, self.k_off0_slip, self.k_on, self.k_on_fil, self.a_per_kBT, \\\n            self.Nh, self.Nmax, self.h_eta, self.xi_rho_a2, self.rho_max_per_rho, \\\n            self.R0 = load_parameters('full model', parameter_file)\n        self.k_p = pillar_stiffness\n\n        self.parameter_dict = {\"x_catch\": self.x_catch, \"x_slip\": self.x_slip, \"k_off0_catch\": self.k_off0_catch,\n                               \"k_off0_slip\": self.k_off0_slip, \"k_on\": self.k_on, \"k_on_fil\": self.k_on_fil,\n                               \"a_per_kBT\": self.a_per_kBT, \"Nh\": self.Nh, \"Nmax\": self.Nmax, \"h_eta\": self.h_eta,\n                               \"xi_rho_a2\": self.xi_rho_a2, \"rho_max_per_rho\": self.rho_max_per_rho, \"R0\": self.R0,\n                               \"k_p\": self.k_p}\n\n        self.A0 = pi * self.R0**2\n        self.tau = 6. / 5. * pi * self.h_eta / self.k_p\n\n    def __k_off(self, force):\n        \"\"\"Calculates the load dependent off-rate of an individual myosin head.\n        \n        Parameters:\n            force (float):\n                the average load that is applied to an individual myosin head.\n\n        Returns:\n            float: the average off-rate of the head.\n        \"\"\"\n        return self.k_off0_catch * np.exp(-self.a_per_kBT * force * self.x_catch) + \\\n            self.k_off0_slip * np.exp(self.a_per_kBT * force * self.x_slip)\n\n    def __calc_prob_dist(self, total_force):\n        \"\"\"Calculates the load dependent steady state probability distribution of the number of bound heads per\n           myosin filament\n        \n        Parameters:\n            total_force (float):\n                the total load that is applied to the myosin filament.\n\n        Returns:\n            list(float): list of probabilities that n heads are bound per filament, where n is given by the list index.\n        \"\"\"\n        pns = []\n        for n in range(0, self.Nh + 1):\n            nom = 1\n            for i in range(0, n):\n                nom = nom * ((self.Nh - i) * self.k_on) / ((i + 1) * self.__k_off(total_force / (i + 1)))\n            \n            denom = 1\n            for k in range(1, self.Nh + 1):\n                prod = 1\n                for j in range(0, k):\n                    prod = prod * ((self.Nh - j) * self.k_on) / ((j + 1) * self.__k_off(total_force / (j + 1)))\n                denom = denom + prod\n            \n            pns.append(nom / denom)\n        \n        return pns\n        \n    def k_off_fil(self, total_force):\n        \"\"\"Calculates the load dependent steady state off-rate of a myosin filament.\n        \n        Parameters:\n            total_force (float):\n                the total load that is applied to the myosin filament.\n\n        Returns:\n            float: the off-rate of the filament.\n        \"\"\"\n        T_off_av = 0\n        pns = self.__calc_prob_dist(total_force)\n        for NB_init in range(1, self.Nh + 1):\n            T_off = 0\n            for NB in range(1, NB_init + 1):\n                s = 0\n                for j in range(NB, self.Nh + 1):\n                    s = s + pns[j]\n                \n                T_off = T_off + 1 / (NB * self.__k_off(total_force / NB) * pns[NB]) * s\n            \n            T_off_av = T_off_av + pns[NB_init] * T_off\n        return 1 / T_off_av\n\n    def rhs(self, t, y):\n        \"\"\"Calculates the right hand side of the set of differential equations that describe the model.\n        \n        Parameters:\n            t (float):\n                the time point.\n            y (list(float)):\n                a list with elements y[0] = force on the pillar at time t and y[1] = number of bound filaments at time t\n\n        Returns:\n            list(float): the temporal derivative of the input y\n        \"\"\"\n        force = y[0]\n        N = y[1]\n\n        area = pi * (self.R0 - force / self.k_p) ** 2\n        density_factor = -self.A0 / area * (self.A0 / area - self.rho_max_per_rho)\n\n        force_prime = -force / self.tau + self.xi_rho_a2 * N * density_factor / self.tau\n        N_prime = self.k_on_fil * (self.Nmax - N) - self.k_off_fil(force) * N\n\n        return [force_prime, N_prime]\n\n    def velocity(self, t, force, N):\n        \"\"\"Calculates the deflection velocity of the tip of the pillar.\n        \n        Parameters:\n            t (float):\n                the time point.\n            force (float):\n                force on the pillar at time t\n            N:\n                number of bound filaments at time t\n\n        Returns:\n            float: the deflection velocity of the pillar tip at time t\n        \"\"\"\n        area = pi * (self.R0 - force / self.k_p) ** 2\n        density_factor = -self.A0 / area * (self.A0 / area - self.rho_max_per_rho)\n\n        return (-force / self.tau + self.xi_rho_a2 * N * density_factor / self.tau) / self.k_p\n\n    def get_parameter(self, parameter_name):\n        \"\"\"Get all model parameters\n\n        Parameters:\n            parameter_name (str):\n                parameter name.\n\n        Returns:\n            float/int: the value of the specified parameter.\n        \"\"\"\n\n        return self.parameter_dict[parameter_name]\n\n\nclass DensityModel:\n    \"\"\"\n    A class that defines the purley density dependent model for actomyosin contraction in soft pillar rings.\n    ...\n\n    Attributes:\n        parameter_file (str):\n            path to a file that contains all necessary parameters for the model (see provided examples).\n\n    Methods:\n        k_off_fil(total_force):\n            calculates the load dependent steady state off-rate of a myosin filament.\n\n        rhs(t, y):\n            calculates the right hand side of the set of differential equations that describe the model.\n\n        velocity(t, force, N):\n            calculates the deflection velocity of the tip of the pillar.\n    \"\"\"\n    \n    def __init__(self, parameter_file, pillar_stiffness):\n        \"\"\"\n        Sets all the necessary parameters for the DensityModel object.\n\n        Parameters:\n            parameter_file (str):\n                path to a file that contains all necessary parameters for the model (see provided examples).\n            pillar_stiffness (float):\n                stiffness of the pillars in the pillar ring in pN/um.\n        \"\"\"\n        self.h_eta, self.xi_N_rho_a2, self.rho_max_per_rho, self.R0 = load_parameters('density model', parameter_file)\n        self.k_p = pillar_stiffness\n\n        self.parameter_dict = {\"h_eta\": self.h_eta, \"xi_N_rho_a2\": self.xi_N_rho_a2,\n                               \"rho_max_per_rho\": self.rho_max_per_rho, \"R0\": self.R0, \"k_p\": self.k_p}\n\n        self.A0 = pi * self.R0 ** 2\n        self.tau = 6. / 5. * pi * self.h_eta / self.k_p\n\n    def rhs(self, t, y):\n        \"\"\"Calculates the right hand side of the set of differential equations that describe the model.\n        \n        Parameters:\n            t (float):\n                the time point.\n            y (list(float)):\n                a list with a single element y[0] = force on the pillar at time t\n\n        Returns:\n        list(float): the temporal derivative of the input y\n        \"\"\"\n        force = y[0]\n\n        area = pi * (self.R0 - force / self.k_p) ** 2\n        density_factor = -self.A0 / area * (self.A0 / area - self.rho_max_per_rho)\n        \n        force_prime = -force/self.tau + self.xi_N_rho_a2 * density_factor / self.tau\n\n        return [force_prime]\n\n    def velocity(self, t, force):\n        \"\"\"Calculates the deflection velocity of the tip of the pillar.\n        \n        Parameters:\n            t (float):\n                the time point.\n            force (float):\n                force on the pillar at time t\n\n        Returns:\n        float: the deflection velocity of the pillar tip at time t\n        \"\"\"\n        area = pi * (self.R0 - force / self.k_p) ** 2\n        density_factor = -self.A0 / area * (self.A0 / area - self.rho_max_per_rho)\n\n        return (-force/self.tau + self.xi_N_rho_a2 * density_factor / self.tau)/self.k_p\n\n    def get_parameter(self, parameter_name):\n        \"\"\"Get all model parameters\n\n        Parameters:\n            parameter_name (str):\n                parameter name.\n\n        Returns:\n            float/int: the value of the specified parameter.\n        \"\"\"\n\n        return self.parameter_dict[parameter_name]\n", "meta": {"hexsha": "83f28e442865534a1a794c7ae1f3ad770dad1f39", "size": 9456, "ext": "py", "lang": "Python", "max_stars_repo_path": "models.py", "max_stars_repo_name": "JFlommersfeld/Actomyosin-contractions-in-soft-pillar-rings", "max_stars_repo_head_hexsha": "0f8e9375f53da432a9cc54a208e5655bc80f9f45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models.py", "max_issues_repo_name": "JFlommersfeld/Actomyosin-contractions-in-soft-pillar-rings", "max_issues_repo_head_hexsha": "0f8e9375f53da432a9cc54a208e5655bc80f9f45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models.py", "max_forks_repo_name": "JFlommersfeld/Actomyosin-contractions-in-soft-pillar-rings", "max_forks_repo_head_hexsha": "0f8e9375f53da432a9cc54a208e5655bc80f9f45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3692307692, "max_line_length": 120, "alphanum_fraction": 0.5704314721, "include": true, "reason": "import numpy", "num_tokens": 2259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.27512972382317524, "lm_q1q2_score": 0.17625796581332492}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n# CODE NAME HERE\n\n# CODE DESCRIPTION HERE\n\nCreated on 2019-08-12 at 17:16\n\n@author: cook\n\"\"\"\nimport numpy as np\nfrom astropy import constants as cc\nfrom astropy import units as uu\nfrom scipy.optimize import curve_fit\nimport warnings\nimport os\n\nfrom apero import core\nfrom apero.core import constants\nfrom apero.core import math as mp\nfrom apero import lang\nfrom apero.core.core import drs_log\nfrom apero.core.core import drs_file\nfrom apero.core.core import drs_database\nfrom apero.io import drs_data\nfrom apero.io import drs_fits\nfrom apero.science.calib import flat_blaze\n\n# =============================================================================\n# Define variables\n# =============================================================================\n__NAME__ = 'science.telluric.general.py'\n__INSTRUMENT__ = 'None'\n# Get constants\nConstants = constants.load(__INSTRUMENT__)\n# Get version and author\n__version__ = Constants['DRS_VERSION']\n__author__ = Constants['AUTHORS']\n__date__ = Constants['DRS_DATE']\n__release__ = Constants['DRS_RELEASE']\n# get param dict\nParamDict = constants.ParamDict\nDrsFitsFile = drs_file.DrsFitsFile\n# Get function string\ndisplay_func = drs_log.display_func\n# Get Logging function\nWLOG = drs_log.wlog\n# Get the text types\nTextEntry = lang.drs_text.TextEntry\nTextDict = lang.drs_text.TextDict\n# alias pcheck\npcheck = core.pcheck\n# Speed of light\n# noinspection PyUnresolvedReferences\nspeed_of_light_ms = cc.c.to(uu.m / uu.s).value\n# noinspection PyUnresolvedReferences\nspeed_of_light = cc.c.to(uu.km / uu.s).value\n\n\n# =============================================================================\n# Define functions\n# =============================================================================\ndef get_whitelist(params, **kwargs):\n    func_name = __NAME__ + '.get_whitelist()'\n    # get pseudo constants\n    pconst = constants.pload(instrument=params['INSTRUMENT'])\n    # get parameters from params/kwargs\n    relfolder = pcheck(params, 'TELLU_LIST_DIRECOTRY', 'directory', kwargs,\n                       func_name)\n    filename = pcheck(params, 'TELLU_WHITELIST_NAME', 'filename', kwargs,\n                      func_name)\n    # load the white list\n    wout = drs_data.load_text_file(params, filename, relfolder, kwargs,\n                                   func_name, dtype=str)\n    whitelist, whitelistfile = wout\n    # must clean names\n    whitelist = list(map(pconst.DRS_OBJ_NAME, whitelist))\n    # return the whitelist\n    return whitelist, whitelistfile\n\n\ndef get_blacklist(params, **kwargs):\n    func_name = __NAME__ + '.get_blacklist()'\n    # get pseudo constants\n    pconst = constants.pload(instrument=params['INSTRUMENT'])\n    # get parameters from params/kwargs\n    relfolder = pcheck(params, 'TELLU_LIST_DIRECOTRY', 'directory', kwargs,\n                       func_name)\n    filename = pcheck(params, 'TELLU_BLACKLIST_NAME', 'filename', kwargs,\n                      func_name)\n    # load the white list\n    bout = drs_data.load_text_file(params, filename, relfolder, kwargs,\n                                   func_name, dtype=str)\n    blacklist, blacklistfile = bout\n    # must clean names\n    blacklist = list(map(pconst.DRS_OBJ_NAME, blacklist))\n    # return the whitelist\n    return blacklist, blacklistfile\n\n\ndef normalise_by_pblaze(params, image, header, fiber, **kwargs):\n    func_name = __NAME__ + '.normalise_by_pblaze()'\n    # get properties from params/kwargs\n    blaze_p = pcheck(params, 'MKTELLU_BLAZE_PERCENTILE', 'blaze_p', kwargs,\n                     func_name)\n    cut_blaze_norm = pcheck(params, 'MKTELLU_CUT_BLAZE_NORM', 'cut_blaze_norm',\n                            kwargs, func_name)\n    # ----------------------------------------------------------------------\n    # copy the image\n    image1 = np.array(image)\n    # ----------------------------------------------------------------------\n    # load the blaze file for this fiber\n    blaze_file, blaze = flat_blaze.get_blaze(params, header, fiber)\n    # copy blaze\n    blaze_norm = np.array(blaze)\n    # loop through blaze orders, normalize blaze by its peak amplitude\n    for order_num in range(image1.shape[0]):\n        # normalize the spectrum\n        spo, bzo = image1[order_num], blaze[order_num]\n        # normalise image\n        image1[order_num] = spo / np.nanpercentile(spo, blaze_p)\n        # normalize the blaze\n        blaze_norm[order_num] = bzo / np.nanpercentile(bzo, blaze_p)\n    # ----------------------------------------------------------------------\n    # find where the blaze is bad\n    with warnings.catch_warnings(record=True) as _:\n        badblaze = blaze_norm < cut_blaze_norm\n    # ----------------------------------------------------------------------\n    # set bad blaze to NaN\n    blaze_norm[badblaze] = np.nan\n    # set to NaN values where spectrum is zero\n    zeromask = image1 == 0\n    image1[zeromask] = np.nan\n    # divide spectrum by blaze\n    with warnings.catch_warnings(record=True) as _:\n        image1 = image1 / blaze_norm\n    # ----------------------------------------------------------------------\n    # parameter dictionary\n    nprops = ParamDict()\n    nprops['BLAZE'] = blaze\n    nprops['NBLAZE'] = blaze_norm\n    nprops['BLAZE_PERCENTILE'] = blaze_p\n    nprops['BLAZE_CUT_NORM'] = cut_blaze_norm\n    nprops['BLAZE_FILE'] = blaze_file\n    # set sources\n    keys = ['BLAZE', 'NBLAZE', 'BLAZE_PERCENTILE', 'BLAZE_CUT_NORM',\n            'BLAZE_FILE']\n    nprops.set_sources(keys, func_name)\n    # return the normalised image and the properties\n    return image1, nprops\n\n\ndef get_non_tellu_objs(params, recipe, fiber, filetype=None, dprtypes=None,\n                       robjnames=None):\n    \"\"\"\n    Get the objects of \"filetype\" and \"\n    :param params:\n    :param fiber:\n    :param filetype:\n    :param dprtypes:\n    :param robjnames:\n\n    :return:\n    \"\"\"\n    # get the telluric star names (we don't want to process these)\n    objnames, _ = get_whitelist(params)\n    objnames = list(objnames)\n    # deal with filetype being string\n    if isinstance(filetype, str):\n        filetype = filetype.split(',')\n    # deal with dprtypes being string\n    if isinstance(dprtypes, str):\n        dprtypes = dprtypes.split(',')\n    # construct kwargs\n    fkwargs = dict()\n    if filetype is not None:\n        fkwargs['KW_OUTPUT'] = filetype\n    if dprtypes is not None:\n        fkwargs['KW_DPRTYPE'] = dprtypes\n    # # find files\n    out = drs_fits.find_files(params, recipe, kind='red', return_table=True,\n                              fiber=fiber, **fkwargs)\n    obj_filenames, obj_table = out\n    # filter out telluric stars\n    obj_stars, obj_names = [], []\n    # loop around object table and only keep non-telluric stars\n    for row in range(len(obj_table)):\n        # get object name\n        iobjname = obj_table['KW_OBJNAME'][row]\n        # if required object name is set\n        if robjnames is not None:\n            if iobjname in robjnames:\n                obj_stars.append(obj_filenames[row])\n                if iobjname not in obj_names:\n                    obj_names.append(iobjname)\n        # if in telluric list skip\n        elif iobjname not in objnames:\n            obj_stars.append(obj_filenames[row])\n            if iobjname not in obj_names:\n                obj_names.append(iobjname)\n    # return absolute path names and object names\n    return obj_stars, obj_names\n\n\ndef get_tellu_objs(params, key, objnames=None, **kwargs):\n    \"\"\"\n    Get objects defined be \"key\" from telluric database (in list objname)\n\n    :param params:\n    :param key:\n    :param objnames:\n    :param kwargs:\n    :return:\n    \"\"\"\n    # deal with column to select from entries\n    column = kwargs.get('column', 'filename')\n    objcol = kwargs.get('objcol', 'objname')\n    # ----------------------------------------------------------------------\n    # deal with objnames\n    if isinstance(objnames, str):\n        objnames = [objnames]\n    # ----------------------------------------------------------------------\n    # load telluric obj entries (based on key)\n    obj_entries = load_tellu_file(params, key=key, inheader=None, mode='ALL',\n                                  return_entries=True, n_entries='all',\n                                  required=False)\n    # add to type\n    typestr = str(key)\n    # ----------------------------------------------------------------------\n    # keep only objects with objnames\n    mask = np.zeros(len(obj_entries)).astype(bool)\n    # deal with no object found\n    if len(obj_entries) == 0:\n        return []\n    elif objnames is not None:\n        # storage for found objects\n        found_objs = []\n        # loop around objnames\n        for objname in objnames:\n            # update the mask\n            mask |= obj_entries[objcol] == objname\n            # only add to the mask if objname found\n            if objname in obj_entries[objcol]:\n                # update the found objs\n                found_objs.append(objname)\n        # update type string\n        typestr += ' OBJNAME={0}'.format(', '.join(found_objs))\n    # ----------------------------------------------------------------------\n    # deal with all entries / one column return\n    if column in [None, 'None', '', 'ALL']:\n        outputs = obj_entries[mask]\n    else:\n        outputs = np.unique(obj_entries[column][mask])\n    # ----------------------------------------------------------------------\n    # deal with getting absolute paths\n    if column == 'filename':\n        abspaths = []\n        # loop around filenames\n        for filename in outputs:\n            # get absolute path\n            abspath = drs_database.get_db_abspath(params, filename,\n                                                  where='telluric')\n            # append to list\n            abspaths.append(abspath)\n        # push back into outputs\n        outputs = list(abspaths)\n    # ----------------------------------------------------------------------\n    # display how many files found\n    margs = [len(outputs), typestr]\n    WLOG(params, '', TextEntry('40-019-00039', args=margs))\n    return outputs\n\n\ndef get_sp_linelists(params, **kwargs):\n    func_name = __NAME__ + '.get_sp_linelists()'\n    # get pseudo constants\n    pconst = constants.pload(instrument=params['INSTRUMENT'])\n    # get parameters from params/kwargs\n    relfolder = pcheck(params, 'TELLU_LIST_DIRECOTRY', 'directory', kwargs,\n                       func_name)\n    othersfile = pcheck(params, 'TELLUP_OTHERS_CCF_FILE', 'filename', kwargs,\n                        func_name)\n    waterfile = pcheck(params, 'TELLUP_H2O_CCF_FILE', 'filename', kwargs,\n                       func_name)\n    # load the others file list\n    mask_others, _ = drs_data.load_ccf_mask(params, directory=relfolder,\n                                            filename=othersfile)\n    mask_water, _ = drs_data.load_ccf_mask(params, directory=relfolder,\n                                           filename=waterfile)\n    # return masks\n    return mask_others, mask_water\n\n\n# =============================================================================\n# pre-cleaning functions\n# =============================================================================\ndef tellu_preclean(params, recipe, infile, wprops, fiber, rawfiles, combine,\n                   **kwargs):\n    \"\"\"\n    Main telluric pre-cleaning functionality.\n\n    Pass an e2ds  image and return the telluric-corrected data.\n    This is a rough model fit and we will need to perform PCA correction on\n    top of it.\n\n    Will fit both water and all dry components of the absorption separately.\n\n    Underlying idea: We correct with a super naive tapas fit and iterate\n    until the CCF of the telluric absorption falls to zero. We have 2 degrees\n    of freedom, the dry and water components of the atmosphere.\n    The instrument profile is defined by two additional parameters\n    [ww -> FWHM, ex_gau -> kernel shape parameter].\n\n    Again, this is just a cleanup PRIOR to PCA correction, so if the code is\n    not perfect in it's correction, this is fine as we will empirically\n    determine the residuals and fit them in a subsequent step.\n\n    we set bounds to the limits of the reasonable domain for both parameters.\n\n    :param params:\n    :param recipe:\n    :param infile:\n    :param wprops:\n    :param fiber:\n    :param rawfiles:\n    :param combine:\n\n    :return:\n    \"\"\"\n    # set the function name\n    func_name = __NAME__ + '.tellu_preclean()'\n    # ----------------------------------------------------------------------\n    # look for precleaned file\n    loadprops = read_tellu_preclean(params, recipe, infile, fiber)\n    # if precleaned load and return\n    if loadprops is not None:\n        return loadprops\n    # ----------------------------------------------------------------------\n    # get parameters from parameter dictionary\n    do_precleaning = pcheck(params, 'TELLUP_DO_PRECLEANING', 'do_precleaning',\n                            kwargs, func_name)\n    default_water_abso = pcheck(params, 'TELLUP_D_WATER_ABSO',\n                                'default_water_abso', kwargs, func_name)\n    ccf_scan_range = pcheck(params, 'TELLUP_CCF_SCAN_RANGE', 'ccf_scan_range',\n                            kwargs, func_name)\n    clean_ohlines = pcheck(params, 'TELLUP_CLEAN_OH_LINES', 'clean_ohlines',\n                           kwargs, func_name)\n\n    remove_orders = pcheck(params, 'TELLUP_REMOVE_ORDS', 'remove_orders',\n                           kwargs, func_name, mapf='list', dtype=int)\n    snr_min_thres = pcheck(params, 'TELLUP_SNR_MIN_THRES', 'snr_min_thres',\n                           kwargs, func_name)\n    dexpo_thres = pcheck(params, 'TELLUP_DEXPO_CONV_THRES', 'dexpo_thres',\n                         kwargs, func_name)\n    max_iterations = pcheck(params, 'TELLUP_DEXPO_MAX_ITR', 'max_iterations',\n                            kwargs, func_name)\n    ker_width = pcheck(params, 'TELLUP_ABSO_EXPO_KWID', 'ker_width', kwargs,\n                       func_name)\n    ker_shape = pcheck(params, 'TELLUP_ABSO_EXPO_KEXP', 'ker_shape', kwargs,\n                       func_name)\n    trans_thres = pcheck(params, 'TELLUP_TRANS_THRES', 'trans_thres', kwargs,\n                         func_name)\n    trans_siglim = pcheck(params, 'TELLUP_TRANS_SIGLIM', 'trans_siglim', kwargs,\n                          func_name)\n    force_airmass = pcheck(params, 'TELLUP_FORCE_AIRMASS', 'force_airmass',\n                           kwargs, func_name)\n    others_bounds = pcheck(params, 'TELLUP_OTHER_BOUNDS', 'others_bounds',\n                           kwargs, func_name, mapf='list', dtype=float)\n    water_bounds = pcheck(params, 'TELLUP_WATER_BOUNDS', 'water_bounds', kwargs,\n                          func_name, mapf='list', dtype=float)\n    ker_thres = pcheck(params, 'TELLUP_ABSO_EXPO_KTHRES', 'ker_thres', kwargs,\n                       func_name)\n    wavestart = pcheck(params, 'EXT_S1D_WAVESTART', 'wavestart', kwargs,\n                       func_name)\n    waveend = pcheck(params, 'EXT_S1D_WAVEEND', 'waveend', kwargs, func_name)\n    dvgrid = pcheck(params, 'EXT_S1D_BIN_UVELO', 'dvgrid', kwargs, func_name)\n    # ----------------------------------------------------------------------\n    # get image and header from infile\n    header = infile.header\n    # get airmass from header\n    hdr_airmass = infile.get_key('KW_AIRMASS', dtype=float)\n    # copy e2ds input image\n    image_e2ds_ini = np.array(infile.data)\n    # get shape of the e2ds\n    nbo, nbpix = image_e2ds_ini.shape\n    # get wave map for the input e2ds\n    wave_e2ds = wprops['WAVEMAP']\n    # ----------------------------------------------------------------------\n    # define storage of quality control\n    qc_values, qc_names, qc_logic, qc_pass = [], [], [], []\n    # need to add dummy values for these qc\n\n    # 1. snr < snr_min_thres (pos = 0)\n    qc_values.append(np.nan)\n    qc_names.append('EXTSNR')\n    qc_logic.append('EXTSNR < {0}'.format(snr_min_thres))\n    qc_pass.append(np.nan)\n    # 2. ccf is NaN (pos = 1)\n    qc_values.append(np.nan)\n    qc_names.append('NUM_NAN_CCF')\n    qc_logic.append('NUM_NAN_CCF > 0')\n    qc_pass.append(np.nan)\n    # 3. exponent for others out of bounds (pos = 2 and 3)\n    qc_values += [np.nan, np.nan]\n    qc_names += ['EXPO_OTHERS L', 'EXPO_OTHERS U']\n    qc_logic += ['EXPO_OTHERS L < {0}'.format(others_bounds[0]),\n                 'EXPO_OTHERS U > {0}'.format(others_bounds[1])]\n    qc_pass += [np.nan, np.nan]\n    # 4. exponent for water  out of bounds (pos 4 and 5)\n    qc_values += [np.nan, np.nan]\n    qc_names += ['EXPO_WATER L', 'EXPO_WATER U']\n    qc_logic += ['EXPO_WATER L < {0}'.format(water_bounds[0]),\n                 'EXPO_WATER U > {0}'.format(water_bounds[1])]\n    qc_pass += [np.nan, np.nan]\n    # 5. max iterations exceeded (pos = 6)\n    qc_values.append(np.nan)\n    qc_names.append('ITERATIONS')\n    qc_logic.append('ITERATIONS = {0}'.format(max_iterations - 1))\n    qc_pass.append(np.nan)\n    # dev note: if adding a new one must add tfailmsgs for all uses in qc\n    #  (mk_tellu and fit_tellu)\n    # ----------------------------------------------------------------------\n    # remove OH lines if required\n    if clean_ohlines:\n        image_e2ds, sky_model = clean_ohline_pca(params, image_e2ds_ini,\n                                                 wave_e2ds)\n    # else just copy the image and set the sky model to zeros\n    else:\n        image_e2ds = np.array(image_e2ds_ini)\n        sky_model = np.zeros_like(image_e2ds_ini)\n    # ----------------------------------------------------------------------\n    if not do_precleaning:\n        # log progress\n        WLOG(params, '', TextEntry('10-019-00008'))\n        # populate qc params\n        qc_params = [qc_names, qc_values, qc_logic, qc_pass]\n        # populate parameter dictionary\n        props = ParamDict()\n        props['CORRECTED_E2DS'] = image_e2ds\n        props['TRANS_MASK'] = np.ones_like(image_e2ds_ini).astype(bool)\n        props['ABSO_E2DS'] = np.ones_like(image_e2ds_ini)\n        props['SKY_MODEL'] = sky_model\n        props['EXPO_WATER'] = np.nan\n        props['EXPO_OTHERS'] = np.nan\n        props['DV_WATER'] = np.nan\n        props['DV_OTHERS'] = np.nan\n        props['CCFPOWER_WATER'] = np.nan\n        props['CCFPOWER_OTHERS'] = np.nan\n        props['QC_PARAMS'] = qc_params\n        # set sources\n        keys = ['CORRECTED_E2DS', 'TRANS_MASK', 'ABSO_E2DS', 'EXPO_WATER',\n                'EXPO_OTHERS', 'DV_WATER', 'DV_OTHERS', 'CCFPOWER_WATER',\n                'CCFPOWER_OTHERS', 'QC_PARAMS', 'SKY_MODEL']\n        props.set_sources(keys, func_name)\n        # ------------------------------------------------------------------\n        # add constants used (can come from kwargs)\n        props['TELLUP_DO_PRECLEANING'] = do_precleaning\n        props['TELLUP_D_WATER_ABSO'] = default_water_abso\n        props['TELLUP_CCF_SCAN_RANGE'] = ccf_scan_range\n        props['TELLUP_CLEAN_OH_LINES'] = clean_ohlines\n        props['TELLUP_REMOVE_ORDS'] = remove_orders\n        props['TELLUP_SNR_MIN_THRES'] = snr_min_thres\n        props['TELLUP_DEXPO_CONV_THRES'] = dexpo_thres\n        props['TELLUP_DEXPO_MAX_ITR'] = max_iterations\n        props['TELLUP_ABSO_EXPO_KWID'] = ker_width\n        props['TELLUP_ABSO_EXPO_KEXP'] = ker_shape\n        props['TELLUP_TRANS_THRES'] = trans_thres\n        props['TELLUP_TRANS_SIGLIM'] = trans_siglim\n        props['TELLUP_FORCE_AIRMASS'] = force_airmass\n        props['TELLUP_OTHER_BOUNDS'] = others_bounds\n        props['TELLUP_WATER_BOUNDS'] = water_bounds\n        props['TELLUP_ABSO_EXPO_KTHRES'] = ker_thres\n        props['TELLUP_WAVE_START'] = wavestart\n        props['TELLUP_WAVE_END'] = waveend\n        props['TELLUP_DVGRID'] = dvgrid\n        # set sources\n        keys = ['TELLUP_D_WATER_ABSO', 'TELLUP_CCF_SCAN_RANGE',\n                'TELLUP_CLEAN_OH_LINES', 'TELLUP_REMOVE_ORDS',\n                'TELLUP_SNR_MIN_THRES', 'TELLUP_DEXPO_CONV_THRES',\n                'TELLUP_DEXPO_MAX_ITR', 'TELLUP_ABSO_EXPO_KWID',\n                'TELLUP_ABSO_EXPO_KEXP', 'TELLUP_TRANS_THRES',\n                'TELLUP_TRANS_SIGLIM', 'TELLUP_FORCE_AIRMASS',\n                'TELLUP_OTHER_BOUNDS', 'TELLUP_WATER_BOUNDS',\n                'TELLUP_ABSO_EXPO_KTHRES', 'TELLUP_WAVE_START',\n                'TELLUP_WAVE_END', 'TELLUP_DVGRID', 'TELLUP_DO_PRECLEANING']\n        props.set_sources(keys, func_name)\n        # ------------------------------------------------------------------\n        # return props\n        return props\n    # ----------------------------------------------------------------------\n    # we ravel the wavelength grid to make it a 1d array of increasing\n    #     wavelength. We will trim the overlapping domain between orders\n    keep = np.ones_like(wave_e2ds).astype(bool)\n    # keep track of where orders are\n    orders, _ = np.indices(wave_e2ds.shape)\n    # loop around 2nd to last-1 order and compare -1th and +1th order\n    for order_num in range(1, nbo - 1):\n        # get wavelengths not in order beforetellu_preclean\n        before = wave_e2ds[order_num] > wave_e2ds[order_num - 1][::-1]\n        # get wavelengths not in order after\n        after = wave_e2ds[order_num] < wave_e2ds[order_num + 1][::-1]\n        # combine mask\n        keep[order_num] = before & after\n    # set whole first order to zeros (rejected)\n    keep[0] = np.zeros(nbpix).astype(bool)\n    # set whole last order to zeros (rejected)\n    keep[-1] = np.zeros(nbpix).astype(bool)\n    # ----------------------------------------------------------------------\n    # force into 1D and apply keep map\n    flatkeep = keep.ravel()\n    wavemap = wave_e2ds.ravel()[flatkeep]\n    spectrum = image_e2ds.ravel()[flatkeep]\n    spectrum_ini = image_e2ds_ini.ravel()[flatkeep]\n    orders = orders.ravel()[flatkeep]\n    # ----------------------------------------------------------------------\n    # load tapas in correct format\n    spl_others, spl_water = load_tapas_spl(params, recipe, header)\n    # ----------------------------------------------------------------------\n    # load the snr from e2ds file\n    snr = infile.read_header_key_1d_list('KW_EXT_SNR', nbo, dtype=float)\n    # remove infinite / NaN snr\n    snr[~np.isfinite(snr)] = 0.0\n    # remove snr from these orders (due to thermal background)\n    for order_num in remove_orders:\n        snr[order_num] = 0.0\n    # make sure we have at least one order above the min snr requiredment\n    if np.nanmax(snr) < snr_min_thres:\n        # update qc params\n        qc_values[0] = np.nanmax(snr)\n        qc_pass[0] = 0\n        qc_params = [qc_names, qc_values, qc_logic, qc_pass]\n        # return qc_exit_tellu_preclean\n        return qc_exit_tellu_preclean(params, recipe, image_e2ds, infile,\n                                      wave_e2ds, qc_params, sky_model)\n    else:\n        qc_values[0] = np.nanmax(snr)\n        qc_pass[0] = 1\n    # mask all orders below min snr\n    for order_num in range(nbo):\n        # only mask if snr below threshold\n        if snr[order_num] < snr_min_thres:\n            # find order mask (we only want to remove values in this order\n            order_mask = orders == order_num\n            # apply low snr mask to spectrum\n            spectrum[order_mask] = np.nan\n    # for numerical stabiility, remove NaNs. Setting to zero biases a bit\n    # the CCF, but this should be OK after we converge\n    spectrum[~np.isfinite(spectrum)] = 0.0\n    spectrum[spectrum < 0.0] = 0.0\n    # ----------------------------------------------------------------------\n    # scanning range for the ccf computations\n    drange = np.arange(-ccf_scan_range, ccf_scan_range + 1.0, 1.0)\n    # get species line lists from file\n    mask_others, mask_water = get_sp_linelists(params)\n    # storage for the ccfs\n    ccf_others = np.zeros_like(drange, dtype=float)\n    ccf_water = np.zeros_like(drange, dtype=float)\n    # start with no correction of abso to get the CCF\n    expo_water = 0.0\n    # we start at zero to get a velocity mesaurement even if we may force\n    #   to the airmass\n    expo_others = 0.0\n    # keep track of consecutive exponents and test convergence\n    expo_water_prev = np.inf\n    expo_others_prev = np.inf\n    dexpo = np.inf\n    # storage for the amplitude from fit\n    amp_water_list = []\n    amp_others_list = []\n    # storage for the exponential from fit\n    expo_water_list = []\n    expo_others_list = []\n    # storage for plotting\n    dd_iterations = []\n    ccf_water_iterations = []\n    ccf_others_iterations = []\n    # ----------------------------------------------------------------------\n    # first guess at the velocity of absoprtion is 0 km/s\n    dv_abso = 0.0\n    # set the iteration number\n    iteration = 0\n    # just so we have outputs\n    dv_water, dv_others = np.nan, np.nan\n    trans = np.ones_like(wavemap)\n    # set up a qc flag\n    flag_qc = False\n    # log progress\n    WLOG(params, '', TextEntry('40-019-00040'))\n    # loop around until convergence or 20th iteration\n    while (dexpo > dexpo_thres) and (iteration < max_iterations):\n        # set up a qc flag\n        flag_qc = False\n        # log progress\n        args = [iteration, dexpo, expo_water, expo_others, dv_abso * 1000]\n        WLOG(params, '', TextEntry('40-019-00041', args=args))\n        # get the absorption spectrum\n        trans = get_abso_expo(params, wavemap, expo_others, expo_water,\n                              spl_others, spl_water, ww=ker_width,\n                              ex_gau=ker_shape, dv_abso=dv_abso,\n                              ker_thres=ker_thres, wavestart=wavestart,\n                              waveend=waveend, dvgrid=dvgrid)\n        # divide spectrum by transmission\n        spectrum_tmp = spectrum / trans\n        # ------------------------------------------------------------------\n        # only keep valid pixels (non NaNs)\n        valid = np.isfinite(spectrum_tmp)\n        # transmission with the exponent value\n        valid &= (trans > np.exp(trans_thres))\n        # ------------------------------------------------------------------\n        # apply some cuts to very discrepant points. These will be set to zero\n        #   not to bias the CCF too much\n        cut = np.nanmedian(np.abs(spectrum_tmp)) * trans_siglim\n        # set NaN and infinite values to zero\n        spectrum_tmp[~np.isfinite(spectrum_tmp)] = 0.0\n        # apply cut and set values to zero\n        spectrum_tmp[spectrum_tmp > cut] = 0.0\n        # set negative values to zero\n        spectrum_tmp[spectrum_tmp < 0.0] = 0.0\n        # ------------------------------------------------------------------\n        # get the CCF of the test spectrum\n        # first spline onto the wave grid\n        spline = mp.iuv_spline(wavemap[valid], spectrum_tmp[valid], k=1, ext=1)\n        # loop around all scanning points in d\n        for d_it in range(len(drange)):\n            # computer rv scaling factor\n            scaling = (1 + drange[d_it] / speed_of_light)\n            # we compute the ccf_others all the time, even when forcing the\n            # airmass, just to look at its structure and potential residuals\n            # compute for others\n            lothers = np.array(mask_others['ll_mask_s']) * scaling\n            tmp_others = spline(lothers) * np.array(mask_others['w_mask'])\n            ccf_others[d_it] = np.nanmean(tmp_others[tmp_others != 0.0])\n            # computer for water\n            lwater = np.array(mask_water['ll_mask_s']) * scaling\n            tmp_water = spline(lwater) * mask_water['w_mask']\n            ccf_water[d_it] = np.nanmean(tmp_water[tmp_water != 0.0])\n        # ------------------------------------------------------------------\n        # subtract the median of the ccf outside the core of the gaussian.\n        #     We take this to be the 'external' part of of the scan range\n        # work out the external part mask\n        with warnings.catch_warnings(record=True) as _:\n            external_mask = np.abs(drange) > ccf_scan_range / 2\n        # calculate and subtract external part\n        external_water = np.nanmedian(ccf_water[external_mask])\n        ccf_water = ccf_water - external_water\n        external_others = np.nanmedian(ccf_others[external_mask])\n        ccf_others = ccf_others - external_others\n        # ------------------------------------------------------------------\n        # get the amplitude of the middle of the CCF\n        # work out the internal part mask\n        internal_mask = np.abs(drange) < ccf_scan_range / 4\n        amp_water = np.nansum(ccf_water[internal_mask])\n        if not force_airmass:\n            amp_others = np.nansum(ccf_others[internal_mask])\n        else:\n            amp_others = 0.0\n        # ------------------------------------------------------------------\n        # count the number of NaNs in the CCF\n        num_nan_ccf = np.sum(~np.isfinite(ccf_water))\n        # if CCF is NaN do not continue\n        if num_nan_ccf > 0:\n            # update qc params\n            qc_values[1] = num_nan_ccf\n            qc_pass[1] = 0\n            # flag qc as failed and break\n            flag_qc = True\n            break\n        else:\n            qc_values[1] = num_nan_ccf\n            qc_pass[1] = 1\n        # ------------------------------------------------------------------\n        # we measure absorption velocity by fitting a gaussian to the\n        #     absorption profile. This updates the dv_abso value for the\n        #     next steps.\n        # if this is the first iteration then fit the  absorption velocity\n        if iteration == 0:\n            # make a guess for the water fit parameters (for curve fit)\n            water_guess = [np.nanmin(ccf_water), 0, 4]\n            # fit the ccf_water with a guassian\n            popt, pcov = curve_fit(mp.gauss_function_nodc, drange, ccf_water,\n                                   p0=water_guess)\n            # store the velocity of the water\n            dv_water = popt[1]\n            # make a guess of the others fit parameters (for curve fit)\n            others_guess = [np.nanmin(ccf_water), 0, 4]\n            # fit the ccf_others with a gaussian\n            popt, pconv = curve_fit(mp.gauss_function_nodc, drange, ccf_others,\n                                    p0=others_guess)\n            # store the velocity of the other species\n            dv_others = popt[1]\n            # store the mean velocity of water and others\n            dv_abso = np.mean([dv_water, dv_others])\n        # ------------------------------------------------------------------\n        # store the amplitudes of current exponent values\n        # for other species\n        if not force_airmass:\n            amp_others_list.append(amp_others)\n            expo_others_list.append(expo_others)\n        # for water\n        amp_water_list.append(amp_water)\n        expo_water_list.append(expo_water)\n        # ------------------------------------------------------------------\n        # if this is the first iteration force the values of\n        # expo_others and expo water\n        if iteration == 0:\n            # header value to be used\n            expo_others = float(hdr_airmass)\n            # default value for water\n            expo_water = float(default_water_abso)\n        # ------------------------------------------------------------------\n        # else we fit the amplitudes with polynomial fits\n        else:\n            # --------------------------------------------------------------\n            # set value for fit_others\n            fit_others = [np.nan, hdr_airmass, np.nan]\n            # convert lists to arrays\n            amp_others_arr = np.array(amp_others_list)\n            expo_others_arr = np.array(expo_others_list)\n            amp_water_arr = np.array(amp_water_list)\n            expo_water_arr = np.array(expo_water_list)\n\n            # if we have over 5 iterations we fit a 2nd order polynomial\n            # to the lowest 5 amplitudes\n            if iteration > 5:\n                if not force_airmass:\n                    # get others lists as array and sort them\n                    sortmask = np.argsort(np.abs(amp_others_arr))\n                    amp_others_arr = amp_others_arr[sortmask]\n                    expo_others_arr = expo_others_arr[sortmask]\n                    # polyfit lowest 5 others terms\n                    fit_others = np.polyfit(amp_others_arr[0: 4],\n                                            expo_others_arr[0:4], 1)\n                # get water lists as arrays and sort them\n                sortmask = np.argsort(np.abs(amp_water_arr))\n                amp_water_arr = amp_water_arr[sortmask]\n                expo_water_arr = expo_water_arr[sortmask]\n                # polyfit lowest 5 water terms\n                fit_water = np.polyfit(amp_water_arr[0:4],\n                                       expo_water_arr[0:4], 1)\n            # else just fit a line\n            else:\n                if not force_airmass:\n                    fit_others = np.polyfit(amp_others_arr, expo_others_arr, 1)\n                fit_water = np.polyfit(amp_water_arr, expo_water_arr, 1)\n            # --------------------------------------------------------------\n            # find best guess for other species exponent\n            expo_others = float(fit_others[1])\n            # deal with lower bounds for other species\n            if expo_others < others_bounds[0]:\n                # update qc params\n                qc_values[2] = float(fit_others[1])\n                qc_pass[2] = 0\n                # set expo_others to lower others bound\n                expo_others = float(others_bounds[0])\n                # flag qc as failed and break\n                flag_qc = True\n            else:\n                qc_values[2] = float(fit_others[1])\n                qc_pass[2] = 1\n            # deal with upper bounds for other species\n            if expo_others > others_bounds[1]:\n                # update qc params\n                qc_values[3] = float(fit_others[1])\n                qc_pass[3] = 0\n                # set the expo_others to the upper others bound\n                expo_others = float(others_bounds[1])\n                # flag qc as failed and break\n                flag_qc = True\n            else:\n                qc_values[3] = float(fit_others[1])\n                qc_pass[3] = 1\n            # --------------------------------------------------------------\n            # find best guess for water exponent\n            expo_water = float(fit_water[1])\n            # deal with lower bounds for water\n            if expo_water < water_bounds[0]:\n                # update qc params\n                qc_values[4] = float(fit_water[1])\n                qc_pass[4] = 0\n                # set the expo_water to the lower water bound\n                expo_water = float(water_bounds[0])\n                # flag qc as failed and break\n                flag_qc = True\n            else:\n                qc_values[4] = float(fit_water[1])\n                qc_pass[4] = 1\n            # deal with upper bounds for water\n            if expo_water > water_bounds[1]:\n                # update qc params\n                qc_values[5] = float(fit_water[1])\n                qc_pass[5] = 0\n                # set the expo_water to the upper water bound\n                expo_water = float(water_bounds[1])\n                # flag qc as failed and break\n                flag_qc = True\n            else:\n                qc_values[5] = float(fit_water[1])\n                qc_pass[5] = 1\n            # --------------------------------------------------------------\n            # check whether we have converged yet (by updating dexpo)\n            if force_airmass:\n                dexpo = np.abs(expo_water_prev - expo_water)\n            else:\n                part1 = expo_water_prev - expo_water\n                part2 = expo_others_prev - expo_others\n                dexpo = np.sqrt(part1 ** 2 + part2 ** 2)\n            # break if qc flag True don't try to converge\n            if flag_qc:\n                break\n        # --------------------------------------------------------------\n        # keep track of the convergence params\n        expo_water_prev = float(expo_water)\n        expo_others_prev = float(expo_others)\n        # ------------------------------------------------------------------\n        # storage for plotting\n        dd_iterations.append(drange)\n        ccf_water_iterations.append(np.array(ccf_water))\n        ccf_others_iterations.append(np.array(ccf_others))\n        # ------------------------------------------------------------------\n        # finally add one to the iterator\n        iteration += 1\n    # ----------------------------------------------------------------------\n    # deal with iterations hitting the max (no convergence)\n    if iteration == max_iterations - 1:\n        # update qc params\n        qc_values[6] = iteration\n        qc_pass[6] = 0\n        flag_qc = True\n    else:\n        qc_values[6] = iteration\n        qc_pass[6] = 1\n    # ----------------------------------------------------------------------\n    # deal with the qc flags\n    if flag_qc:\n        # log that qc flagged\n        for qit in range(len(qc_pass)):\n            if qc_pass[qit] == 0:\n                wargs = [qc_logic[qit], qc_names[qit], qc_values[qit]]\n                wmsg = 'Pre cleaning failed. \\n\\tCriteria: {0} \\n\\tActual: {1} = {2}'\n                WLOG(params, 'warning', wmsg.format(*wargs))\n\n        qc_params = [qc_names, qc_values, qc_logic, qc_pass]\n        # return qc_exit_tellu_preclean\n        return qc_exit_tellu_preclean(params, recipe, image_e2ds, infile,\n                                      wave_e2ds, qc_params, sky_model)\n    # ----------------------------------------------------------------------\n    # show CCF plot to see if correlation peaks have been killed\n    recipe.plot('TELLUP_WAVE_TRANS', dd_arr=dd_iterations,\n                ccf_water_arr=ccf_water_iterations,\n                ccf_others_arr=ccf_others_iterations)\n    recipe.plot('SUM_TELLUP_WAVE_TRANS', dd_arr=dd_iterations,\n                ccf_water_arr=ccf_water_iterations,\n                ccf_others_arr=ccf_others_iterations)\n    # plot to show absorption spectrum\n    recipe.plot('TELLUP_ABSO_SPEC', trans=trans, wave=wavemap,\n                thres=trans_thres, spectrum=spectrum, spectrum_ini=spectrum_ini,\n                objname=infile.get_key('KW_OBJNAME', dtype=str),\n                clean_ohlines=clean_ohlines)\n    recipe.plot('SUM_TELLUP_ABSO_SPEC', trans=trans, wave=wavemap,\n                thres=trans_thres, spectrum=spectrum, spectrum_ini=spectrum_ini,\n                objname=infile.get_key('KW_OBJNAME', dtype=str),\n                clean_ohlines=clean_ohlines)\n    # ----------------------------------------------------------------------\n    # create qc_params (all passed now but we have updated values)\n    qc_params = [qc_names, qc_values, qc_logic, qc_pass]\n    # ----------------------------------------------------------------------\n    # get the final absorption spectrum to be used on the science data.\n    #     No trimming done on the wave grid\n    abso_e2ds = get_abso_expo(params, wave_e2ds, expo_others, expo_water,\n                              spl_others, spl_water, ww=ker_width,\n                              ex_gau=ker_shape, dv_abso=0.0,\n                              ker_thres=ker_thres, wavestart=wavestart,\n                              waveend=waveend, dvgrid=dvgrid)\n    # all absorption deeper than exp(trans_thres) is considered too deep to\n    #    be corrected. We set values there to NaN\n    mask = abso_e2ds < np.exp(2 * trans_thres)\n    # set deep lines to NaN\n    abso_e2ds[mask] = np.nan\n    # ----------------------------------------------------------------------\n    # now correct the original e2ds file\n    corrected_e2ds = (image_e2ds_ini - sky_model) / abso_e2ds\n    # ----------------------------------------------------------------------\n    # calculate CCF power\n    keep = np.abs(drange) < (ccf_scan_range / 4)\n    water_ccfpower = np.nansum(np.gradient(ccf_water[keep] ** 2))\n    others_ccfpower = np.nansum(np.gradient(ccf_others)[keep] ** 2)\n    # ----------------------------------------------------------------------\n    # populate parameter dictionary\n    props = ParamDict()\n    props['CORRECTED_E2DS'] = corrected_e2ds\n    props['TRANS_MASK'] = mask\n    props['ABSO_E2DS'] = abso_e2ds\n    props['SKY_MODEL'] = sky_model\n    props['EXPO_WATER'] = expo_water\n    props['EXPO_OTHERS'] = expo_others\n    props['DV_WATER'] = dv_water\n    props['DV_OTHERS'] = dv_others\n    props['CCFPOWER_WATER'] = water_ccfpower\n    props['CCFPOWER_OTHERS'] = others_ccfpower\n    props['QC_PARAMS'] = qc_params\n    # set sources\n    keys = ['CORRECTED_E2DS', 'TRANS_MASK', 'ABSO_E2DS', 'EXPO_WATER',\n            'EXPO_OTHERS', 'DV_WATER', 'DV_OTHERS', 'CCFPOWER_WATER',\n            'CCFPOWER_OTHERS', 'QC_PARAMS', 'SKY_MODEL']\n    props.set_sources(keys, func_name)\n    # ----------------------------------------------------------------------\n    # add constants used (can come from kwargs)\n    props['TELLUP_DO_PRECLEANING'] = do_precleaning\n    props['TELLUP_D_WATER_ABSO'] = default_water_abso\n    props['TELLUP_CCF_SCAN_RANGE'] = ccf_scan_range\n    props['TELLUP_CLEAN_OH_LINES'] = clean_ohlines\n    props['TELLUP_REMOVE_ORDS'] = remove_orders\n    props['TELLUP_SNR_MIN_THRES'] = snr_min_thres\n    props['TELLUP_DEXPO_CONV_THRES'] = dexpo_thres\n    props['TELLUP_DEXPO_MAX_ITR'] = max_iterations\n    props['TELLUP_ABSO_EXPO_KWID'] = ker_width\n    props['TELLUP_ABSO_EXPO_KEXP'] = ker_shape\n    props['TELLUP_TRANS_THRES'] = trans_thres\n    props['TELLUP_TRANS_SIGLIM'] = trans_siglim\n    props['TELLUP_FORCE_AIRMASS'] = force_airmass\n    props['TELLUP_OTHER_BOUNDS'] = others_bounds\n    props['TELLUP_WATER_BOUNDS'] = water_bounds\n    props['TELLUP_ABSO_EXPO_KTHRES'] = ker_thres\n    props['TELLUP_WAVE_START'] = wavestart\n    props['TELLUP_WAVE_END'] = waveend\n    props['TELLUP_DVGRID'] = dvgrid\n    # set sources\n    keys = ['TELLUP_D_WATER_ABSO', 'TELLUP_CCF_SCAN_RANGE',\n            'TELLUP_CLEAN_OH_LINES', 'TELLUP_REMOVE_ORDS',\n            'TELLUP_SNR_MIN_THRES', 'TELLUP_DEXPO_CONV_THRES',\n            'TELLUP_DEXPO_MAX_ITR', 'TELLUP_ABSO_EXPO_KWID',\n            'TELLUP_ABSO_EXPO_KEXP', 'TELLUP_TRANS_THRES',\n            'TELLUP_TRANS_SIGLIM', 'TELLUP_FORCE_AIRMASS',\n            'TELLUP_OTHER_BOUNDS', 'TELLUP_WATER_BOUNDS',\n            'TELLUP_ABSO_EXPO_KTHRES', 'TELLUP_WAVE_START',\n            'TELLUP_WAVE_END', 'TELLUP_DVGRID', 'TELLUP_DO_PRECLEANING']\n    props.set_sources(keys, func_name)\n    # ----------------------------------------------------------------------\n    # save pre-cleaned file\n    tellu_preclean_write(params, recipe, infile, rawfiles, fiber, combine,\n                         props, wprops)\n    # ----------------------------------------------------------------------\n    # return props\n    return props\n\n\ndef clean_ohline_pca(params, image, wavemap, **kwargs):\n    # load ohline principle components\n    func_name = __NAME__ + '.clean_ohline_pca()'\n    # ----------------------------------------------------------------------\n    # get parameters from params/kwargs\n    relfolder = pcheck(params, 'TELLU_LIST_DIRECOTRY', 'directory', kwargs,\n                       func_name)\n    filename = pcheck(params, 'TELLUP_OHLINE_PCA_FILE', 'filename', kwargs,\n                      func_name)\n    # ----------------------------------------------------------------------\n    # log progress\n    WLOG(params, '', TextEntry('40-019-00042'))\n    # ----------------------------------------------------------------------\n    # get shape of the e2ds\n    nbo, nbpix = image.shape\n    # ----------------------------------------------------------------------\n    # load principle components data file\n    ohpcdata, ohfile = drs_data.load_fits_file(params, filename, relfolder,\n                                               func_name)\n    # ----------------------------------------------------------------------\n    # get the number of components\n    n_components = ohpcdata.shape[1] - 1\n    # get the ohline wave grid\n    ohwave = ohpcdata[:, 0].reshape(nbo, nbpix)\n    # get the principle components\n    ohpcas = ohpcdata[:, 1:].reshape(nbo, nbpix, n_components)\n    # ----------------------------------------------------------------------\n    # replace NaNs in the science data with zeros to avoid problems in the\n    #   fitting below\n    ribbon_e2ds = np.array(image).ravel()\n    ribbon_e2ds[~np.isfinite(ribbon_e2ds)] = 0\n    # make the PCs a ribbon that is N_pc * (nbo  * nbpix)\n    ribbons_pcs = np.zeros([n_components, len(ribbon_e2ds)])\n\n    # lead the PCs and transform to the night grid\n    for ncomp in range(n_components):\n        # shift the principle component from ohwave grid to input e2ds wave grid\n        ohpcshift = wave_to_wave(params, ohpcas[:, :, ncomp], ohwave, wavemap)\n        # push into ribbons\n        ribbons_pcs[ncomp] = ohpcshift.ravel()\n    # ----------------------------------------------------------------------\n    # output for the sky model\n    sky_model = np.zeros_like(ribbon_e2ds)\n    # here we could have a loop, that's why the sky_model is within the\n    #    fitting function.\n    # work out the grad of the diff\n    vector = np.gradient(ribbon_e2ds - sky_model)\n    sample = np.gradient(ribbons_pcs, axis=1)\n    # linear minimisation of the ribbon's derivative to the science\n    #     data derivative\n    amps, model = mp.linear_minimization(vector, sample)\n    # ----------------------------------------------------------------------\n    # reconstruct the sky model with the amplitudes derived above\n    for ncomp in range(n_components):\n        sky_model += ribbons_pcs[ncomp] * amps[ncomp]\n    # sky model cannot be negative\n    with warnings.catch_warnings(record=True) as _:\n        sky_model[sky_model < 0] = 0\n    # push sky_model into correct shape\n    sky_model = sky_model.reshape(nbo, nbpix)\n    # ----------------------------------------------------------------------\n    # return the cleaned image and sky model\n    return image - sky_model, sky_model\n\n\ndef get_abso_expo(params, wavemap, expo_others, expo_water, spl_others,\n                  spl_water, ww, ex_gau, dv_abso, ker_thres, wavestart,\n                  waveend, dvgrid):\n    \"\"\"\n    Returns an absorption spectrum from exponents describing water and 'others'\n    in absorption\n\n    :param params: ParamDict, parameter dictionary of constants\n    :param wavemap: numpy nd array, wavelength grid onto which the spectrum is\n                    splined\n    :param expo_others: float, optical depth of all species other than water\n    :param expo_water: float, optical depth of water\n    :param spl_others: spline function from tapas of other species\n    :param spl_water: spline function from tapas of water\n    :param ww: gaussian width of the kernel\n    :param ex_gau: exponent of the gaussian (ex_gau = 2 is a gaussian, >2\n                   is boxy)\n    :param dv_abso: velocity of the absorption\n    :return:\n    \"\"\"\n    # set the function name\n    func_name = __NAME__ + '.get_abso_expo()'\n    # ----------------------------------------------------------------------\n    # for some test one may give 0 as exponents and for this we just return\n    #    a flat vector\n    if (expo_others == 0) and (expo_water == 0):\n        return np.ones_like(wavemap)\n    # ----------------------------------------------------------------------\n    # define the convolution kernel for the model. This shape factor can be\n    #    modified if needed\n    #   divide by fwhm of a gaussian of exp = 2.0\n    width = ww / mp.fwhm()\n    # defining the convolution kernel x grid, defined over 4 fwhm\n    kernel_width = int(ww * 4)\n    dd = np.arange(-kernel_width, kernel_width + 1.0, 1.0)\n    # normalization of the kernel\n    ker = np.exp(-0.5 * np.abs(dd / width) ** ex_gau)\n    # shorten then kernel to keep only pixels that are more than 1e-6 of peak\n    ker = ker[ker > ker_thres * np.max(ker)]\n    # normalize the kernel\n    ker /= np.sum(ker)\n    # ----------------------------------------------------------------------\n    # create a magic grid onto which we spline our transmission, same as\n    #   for the s1d_v\n    logwratio = np.log(waveend / wavestart)\n    len_magic = int(np.ceil(logwratio * speed_of_light / dvgrid))\n    magic_grid = np.exp(np.arange(len_magic) / len_magic * logwratio)\n    magic_grid = magic_grid * wavestart\n    # spline onto magic grid\n    sp_others = spl_others(magic_grid)\n    sp_water = spl_water(magic_grid)\n    # ----------------------------------------------------------------------\n    # for numerical stability, we may have values very slightly below 0 from\n    #     the spline above. negative values don't work with fractional exponents\n    sp_others[sp_others < 0.0] = 0.0\n    sp_water[sp_water < 0.0] = 0.0\n    # ----------------------------------------------------------------------\n    # applying optical depths\n    trans_others = sp_others ** expo_others\n    trans_water = sp_water ** expo_water\n    # getting the full absorption at full resolution\n    trans = trans_others * trans_water\n    # convolving after product (to avoid the infamous commutativity problem\n    trans_convolved = np.convolve(trans, ker, mode='same')\n    # ----------------------------------------------------------------------\n    # spline that onto the input grid and allow a velocity shift\n    magic_shift = magic_grid * (1 + dv_abso / speed_of_light)\n    magic_spline = mp.iuv_spline(magic_shift, trans_convolved)\n    # if this is a 2d array from an e2ds we loop on the orders\n    if len(wavemap.shape) == 2:\n        out_vector = np.zeros(wavemap.shape)\n        # loop around orders and populate\n        for order_num in range(wavemap.shape[0]):\n            out_vector[order_num] = magic_spline(wavemap[order_num])\n    # else just spline the full wave grid\n    else:\n        out_vector = magic_spline(wavemap)\n    # ----------------------------------------------------------------------\n    # cannot spline outside magic grid\n    # ----------------------------------------------------------------------\n    # get bounds of magic grid\n    min_magic = np.nanmin(magic_grid)\n    max_magic = np.nanmax(magic_grid)\n    # set all out of bound values to NaN\n    mask = (wavemap < min_magic) | (wavemap > max_magic)\n    out_vector[mask] = np.nan\n    # ----------------------------------------------------------------------\n    # return out vector\n    return out_vector\n\n\ndef qc_exit_tellu_preclean(params, recipe, image, infile, wavemap,\n                           qc_params, sky_model, **kwargs):\n    \"\"\"\n    Provides an exit point for tellu_preclean via a quality control failure\n\n    :param params:\n    :param image:\n    :param wavemap:\n    :param qc_value:\n    :param qc_name:\n    :param qc_logic:\n    :return:\n    \"\"\"\n    # set the function name\n    func_name = __NAME__ + '.qc_exit_tellu_preclean()'\n    # ----------------------------------------------------------------------\n    # get parameters from parameter dictionary\n    do_precleaning = pcheck(params, 'TELLUP_DO_PRECLEANING', 'do_precleaning',\n                            kwargs, func_name)\n    default_water_abso = pcheck(params, 'TELLUP_D_WATER_ABSO',\n                                'default_water_abso', kwargs, func_name)\n    ccf_scan_range = pcheck(params, 'TELLUP_CCF_SCAN_RANGE', 'ccf_scan_range',\n                            kwargs, func_name)\n    clean_ohlines = pcheck(params, 'TELLUP_CLEAN_OH_LINES', 'clean_ohlines',\n                           kwargs, func_name)\n\n    remove_orders = pcheck(params, 'TELLUP_REMOVE_ORDS', 'remove_orders',\n                           kwargs, func_name, mapf='list', dtype=int)\n    snr_min_thres = pcheck(params, 'TELLUP_SNR_MIN_THRES', 'snr_min_thres',\n                           kwargs, func_name)\n    dexpo_thres = pcheck(params, 'TELLUP_DEXPO_CONV_THRES', 'dexpo_thres',\n                         kwargs, func_name)\n    max_iterations = pcheck(params, 'TELLUP_DEXPO_MAX_ITR', 'max_iterations',\n                            kwargs, func_name)\n    ker_width = pcheck(params, 'TELLUP_ABSO_EXPO_KWID', 'ker_width', kwargs,\n                       func_name)\n    ker_shape = pcheck(params, 'TELLUP_ABSO_EXPO_KEXP', 'ker_shape', kwargs,\n                       func_name)\n    qc_ker_width = pcheck(params, 'TELLUP_ABSO_EXPO_KWID', 'qc_ker_width',\n                          kwargs, func_name)\n    qc_ker_shape = pcheck(params, 'TELLUP_ABSO_EXPO_KEXP', 'qc_ker_shape',\n                          kwargs, func_name)\n    trans_thres = pcheck(params, 'TELLUP_TRANS_THRES', 'trans_thres', kwargs,\n                         func_name)\n    trans_siglim = pcheck(params, 'TELLUP_TRANS_SIGLIM', 'trans_siglim', kwargs,\n                          func_name)\n    force_airmass = pcheck(params, 'TELLUP_FORCE_AIRMASS', 'force_airmass',\n                           kwargs, func_name)\n    others_bounds = pcheck(params, 'TELLUP_OTHER_BOUNDS', 'others_bounds',\n                           kwargs, func_name, mapf='list', dtype=float)\n    water_bounds = pcheck(params, 'TELLUP_WATER_BOUNDS', 'water_bounds', kwargs,\n                          func_name, mapf='list', dtype=float)\n    ker_thres = pcheck(params, 'TELLUP_ABSO_EXPO_KTHRES', 'ker_thres', kwargs,\n                       func_name)\n    wavestart = pcheck(params, 'EXT_S1D_WAVESTART', 'wavestart', kwargs,\n                       func_name)\n    waveend = pcheck(params, 'EXT_S1D_WAVEEND', 'waveend', kwargs, func_name)\n    dvgrid = pcheck(params, 'EXT_S1D_BIN_UVELO', 'dvgrid', kwargs, func_name)\n    # ----------------------------------------------------------------------\n    # get image and header from infile\n    image_e2ds = np.array(image)\n    header = infile.header\n    # get airmass from header\n    hdr_airmass = infile.get_key('KW_AIRMASS', dtype=float)\n    # ----------------------------------------------------------------------\n    # load tapas in correct format\n    spl_others, spl_water = load_tapas_spl(params, recipe, header)\n    # ----------------------------------------------------------------------\n    # force expo values\n    expo_others = float(hdr_airmass)\n    expo_water = float(default_water_abso)\n    # get the absorption\n    abso_e2ds = get_abso_expo(params, wavemap, expo_others, expo_water,\n                              spl_others, spl_water, ww=qc_ker_width,\n                              ex_gau=qc_ker_shape, dv_abso=0.0,\n                              ker_thres=ker_thres, wavestart=wavestart,\n                              waveend=waveend, dvgrid=dvgrid)\n    # mask transmission below certain threshold\n    mask = abso_e2ds < np.exp(trans_thres)\n    # correct e2ds\n    corrected_e2ds = image_e2ds / abso_e2ds\n    # mask poor tranmission regions\n    corrected_e2ds[mask] = np.nan\n    # ----------------------------------------------------------------------\n    # populate parameter dictionary\n    props = ParamDict()\n    props['CORRECTED_E2DS'] = corrected_e2ds\n    props['TRANS_MASK'] = mask\n    props['ABSO_E2DS'] = abso_e2ds\n    props['SKY_MODEL'] = sky_model\n    props['EXPO_WATER'] = expo_water\n    props['EXPO_OTHERS'] = expo_others\n    props['DV_WATER'] = np.nan\n    props['DV_OTHERS'] = np.nan\n    props['CCFPOWER_WATER'] = np.nan\n    props['CCFPOWER_OTHERS'] = np.nan\n    props['QC_PARAMS'] = qc_params\n    # set sources\n    keys = ['CORRECTED_E2DS', 'TRANS_MASK', 'ABSO_E2DS', 'EXPO_WATER',\n            'EXPO_OTHERS', 'DV_WATER', 'DV_OTHERS', 'CCFPOWER_WATER',\n            'CCFPOWER_OTHERS', 'QC_PARAMS', 'SKY_MODEL']\n    props.set_sources(keys, func_name)\n    # ----------------------------------------------------------------------\n    # add constants used (can come from kwargs)\n    props['TELLUP_DO_PRECLEANING'] = do_precleaning\n    props['TELLUP_D_WATER_ABSO'] = default_water_abso\n    props['TELLUP_CCF_SCAN_RANGE'] = ccf_scan_range\n    props['TELLUP_CLEAN_OH_LINES'] = clean_ohlines\n    props['TELLUP_REMOVE_ORDS'] = remove_orders\n    props['TELLUP_SNR_MIN_THRES'] = snr_min_thres\n    props['TELLUP_DEXPO_CONV_THRES'] = dexpo_thres\n    props['TELLUP_DEXPO_MAX_ITR'] = max_iterations\n    props['TELLUP_ABSO_EXPO_KWID'] = ker_width\n    props['TELLUP_ABSO_EXPO_KEXP'] = ker_shape\n    props['TELLUP_TRANS_THRES'] = trans_thres\n    props['TELLUP_TRANS_SIGLIM'] = trans_siglim\n    props['TELLUP_FORCE_AIRMASS'] = force_airmass\n    props['TELLUP_OTHER_BOUNDS'] = others_bounds\n    props['TELLUP_WATER_BOUNDS'] = water_bounds\n    props['TELLUP_ABSO_EXPO_KTHRES'] = ker_thres\n    props['TELLUP_WAVE_START'] = wavestart\n    props['TELLUP_WAVE_END'] = waveend\n    props['TELLUP_DVGRID'] = dvgrid\n    # set sources\n    keys = ['TELLUP_D_WATER_ABSO', 'TELLUP_CCF_SCAN_RANGE',\n            'TELLUP_CLEAN_OH_LINES', 'TELLUP_REMOVE_ORDS',\n            'TELLUP_SNR_MIN_THRES', 'TELLUP_DEXPO_CONV_THRES',\n            'TELLUP_DEXPO_MAX_ITR', 'TELLUP_ABSO_EXPO_KWID',\n            'TELLUP_ABSO_EXPO_KEXP', 'TELLUP_TRANS_THRES',\n            'TELLUP_TRANS_SIGLIM', 'TELLUP_FORCE_AIRMASS',\n            'TELLUP_OTHER_BOUNDS', 'TELLUP_WATER_BOUNDS',\n            'TELLUP_ABSO_EXPO_KTHRES', 'TELLUP_WAVE_START',\n            'TELLUP_WAVE_END', 'TELLUP_DVGRID', 'TELLUP_DO_PRECLEANING']\n    props.set_sources(keys, func_name)\n    # ----------------------------------------------------------------------\n    # return props\n    return props\n\n\ndef tellu_preclean_write(params, recipe, infile, rawfiles, fiber, combine,\n                         props, wprops):\n    # ------------------------------------------------------------------\n    # get copy of instance of wave file (WAVE_HCMAP)\n    tpclfile = recipe.outputs['TELLU_PCLEAN'].newcopy(recipe=recipe,\n                                                      fiber=fiber)\n    # construct the filename from file instance\n    tpclfile.construct_filename(params, infile=infile)\n    # ------------------------------------------------------------------\n    # copy keys from input file\n    tpclfile.copy_original_keys(infile)\n    # add version\n    tpclfile.add_hkey('KW_VERSION', value=params['DRS_VERSION'])\n    # add dates\n    tpclfile.add_hkey('KW_DRS_DATE', value=params['DRS_DATE'])\n    tpclfile.add_hkey('KW_DRS_DATE_NOW', value=params['DATE_NOW'])\n    # add process id\n    tpclfile.add_hkey('KW_PID', value=params['PID'])\n    # add output tag\n    tpclfile.add_hkey('KW_OUTPUT', value=tpclfile.name)\n    # add input files (and deal with combining or not combining)\n    if combine:\n        infiles = rawfiles\n    else:\n        infiles = [infile.basename]\n    tpclfile.add_hkey_1d('KW_INFILE1', values=infiles, dim1name='file')\n    # add  calibration files used\n    tpclfile.add_hkey('KW_CDBWAVE', value=wprops['WAVEFILE'])\n    # ----------------------------------------------------------------------\n    # set images\n    dimages = [props['CORRECTED_E2DS'], props['TRANS_MASK'].astype(float),\n               props['ABSO_E2DS'], props['SKY_MODEL']]\n    # add extention info\n    kws1 = ['EXTDESC1', 'Corrected', 'Extension 1 description']\n    kws2 = ['EXTDESC2', 'Trans Mask', 'Extension 2 description']\n    kws3 = ['EXTDESC3', 'ABSO E2DS', 'Extension 3 description']\n    kws4 = ['EXTDESC4', 'Sky model', 'Extension 4 description']\n    # add to hdict\n    tpclfile.add_hkey(key=kws1)\n    tpclfile.add_hkey(key=kws2)\n    tpclfile.add_hkey(key=kws3)\n    tpclfile.add_hkey(key=kws4)\n    # ----------------------------------------------------------------------\n    # need to write these as header keys\n    tpclfile.add_hkey('KW_TELLUP_EXPO_WATER', value=props['EXPO_WATER'])\n    tpclfile.add_hkey('KW_TELLUP_EXPO_OTHERS', value=props['EXPO_OTHERS'])\n    tpclfile.add_hkey('KW_TELLUP_DV_WATER', value=props['DV_WATER'])\n    tpclfile.add_hkey('KW_TELLUP_DV_OTHERS', value=props['DV_OTHERS'])\n    tpclfile.add_hkey('KW_TELLUP_CCFP_WATER', value=props['CCFPOWER_WATER'])\n    tpclfile.add_hkey('KW_TELLUP_CCFP_OTHERS', value=props['CCFPOWER_OTHERS'])\n    # ----------------------------------------------------------------------\n    # get qc names/values/logic/pass from qc params\n    qc_names, qc_values, qc_logic, qc_pass = props['QC_PARAMS']\n    # first add number of QCs\n    qkw = ['TQCCNUM', len(qc_names), 'Number of tellu pre-clean qcs']\n    tpclfile.add_hkey(key=qkw)\n    # now add the keys\n    for qc_it in range(len(qc_names)):\n        # add name\n        qkwn = ['TQCCN{0}'.format(qc_it), qc_names[qc_it],\n                'Name {0}'.format(qc_it)]\n        tpclfile.add_hkey(key=qkwn)\n        # add value\n        qkwv = ['TQCCV{0}'.format(qc_it), qc_values[qc_it],\n                'Value {0}'.format(qc_it)]\n        tpclfile.add_hkey(key=qkwv)\n        # add logic\n        qkwl = ['TQCCL{0}'.format(qc_it), qc_values[qc_it],\n                'Logic {0}'.format(qc_it)]\n        tpclfile.add_hkey(key=qkwl)\n        # add pass\n        qkwp = ['TQCCP{0}'.format(qc_it), qc_values[qc_it],\n                'Pass {0}'.format(qc_it)]\n        tpclfile.add_hkey(key=qkwp)\n    # ----------------------------------------------------------------------\n    # add constants used (can come from kwargs)\n    tpclfile.add_hkey('KW_TELLUP_DO_PRECLEAN',\n                      value=props['TELLUP_DO_PRECLEANING'])\n    tpclfile.add_hkey('KW_TELLUP_DFLT_WATER',\n                      value=props['TELLUP_D_WATER_ABSO'])\n    tpclfile.add_hkey('KW_TELLUP_CCF_SRANGE',\n                      value=props['TELLUP_CCF_SCAN_RANGE'])\n    tpclfile.add_hkey('KW_TELLUP_CLEAN_OHLINES',\n                      value=props['TELLUP_CLEAN_OH_LINES'])\n    tpclfile.add_hkey('KW_TELLUP_REMOVE_ORDS',\n                      value=props['TELLUP_REMOVE_ORDS'], mapf='list')\n    tpclfile.add_hkey('KW_TELLUP_SNR_MIN_THRES',\n                      value=props['TELLUP_SNR_MIN_THRES'])\n    tpclfile.add_hkey('KW_TELLUP_DEXPO_CONV_THRES',\n                      value=props['TELLUP_DEXPO_CONV_THRES'])\n    tpclfile.add_hkey('KW_TELLUP_DEXPO_MAX_ITR',\n                      value=props['TELLUP_DEXPO_MAX_ITR'])\n    tpclfile.add_hkey('KW_TELLUP_ABSOEXPO_KTHRES',\n                      value=props['TELLUP_ABSO_EXPO_KTHRES'])\n    tpclfile.add_hkey('KW_TELLUP_WAVE_START', value=props['TELLUP_WAVE_START'])\n    tpclfile.add_hkey('KW_TELLUP_WAVE_END', value=props['TELLUP_WAVE_END'])\n    tpclfile.add_hkey('KW_TELLUP_DVGRID', value=props['TELLUP_DVGRID'])\n    tpclfile.add_hkey('KW_TELLUP_ABSOEXPO_KWID',\n                      value=props['TELLUP_ABSO_EXPO_KWID'])\n    tpclfile.add_hkey('KW_TELLUP_ABSOEXPO_KEXP',\n                      value=props['TELLUP_ABSO_EXPO_KEXP'])\n    tpclfile.add_hkey('KW_TELLUP_TRANS_THRES',\n                      value=props['TELLUP_TRANS_THRES'])\n    tpclfile.add_hkey('KW_TELLUP_TRANS_SIGL',\n                      value=props['TELLUP_TRANS_SIGLIM'])\n    tpclfile.add_hkey('KW_TELLUP_FORCE_AIRMASS',\n                      value=props['TELLUP_FORCE_AIRMASS'])\n    tpclfile.add_hkey('KW_TELLUP_OTHER_BOUNDS',\n                      value=props['TELLUP_OTHER_BOUNDS'], mapf='list')\n    tpclfile.add_hkey('KW_TELLUP_WATER_BOUNDS',\n                      value=props['TELLUP_WATER_BOUNDS'], mapf='list')\n    # ----------------------------------------------------------------------\n    # print progress\n    WLOG(params, '', TextEntry('40-019-00044', args=[tpclfile.filename]))\n    # write to file\n    tpclfile.data = dimages[0]\n    tpclfile.write_multi(data_list=dimages[1:])\n    # add to output files (for indexing)\n    recipe.add_output_file(tpclfile)\n    # ----------------------------------------------------------------------\n    # copy the pre-cleaned file to telluDB\n    drs_database.add_file(params, tpclfile)\n\n\ndef read_tellu_preclean(params, recipe, infile, fiber):\n    \"\"\"\n    Read all TELLU_PCLEAN files and if infile is one of them load the images\n    and properties, else return None\n\n    :param params:\n    :param recipe:\n    :param infile:\n    :param fiber:\n    :return:\n    \"\"\"\n\n    # ------------------------------------------------------------------\n    # get the tellu preclean map key\n    # ----------------------------------------------------------------------\n    out_pclean = core.get_file_definition('TELLU_PCLEAN', params['INSTRUMENT'],\n                                          kind='red', fiber=fiber)\n    # get key\n    pclean_key = out_pclean.get_dbkey(fiber=fiber)\n\n    # load tellu file, header and abspaths\n    _, pclean_filenames = load_tellu_file(params, pclean_key, infile.header,\n                                          n_entries='all', get_image=False,\n                                          required=False)\n    # if we don't have the file return None\n    if pclean_filenames is None:\n        return None\n    # ------------------------------------------------------------------\n    # get copy of instance of wave file (WAVE_HCMAP)\n    tpclfile = recipe.outputs['TELLU_PCLEAN'].newcopy(recipe=recipe,\n                                                      fiber=fiber)\n    # construct the filename from file instance\n    tpclfile.construct_filename(params, infile=infile)\n    # ------------------------------------------------------------------\n    # only keep basenames\n    pclean_basenames = []\n    for pclean_filename in pclean_filenames:\n        pclean_basenames.append(os.path.basename(pclean_filename))\n    # see if file is in database\n    if not tpclfile.basename in pclean_basenames:\n        return None\n    # ----------------------------------------------------------------------\n    # log progress\n    # log: Reading pre-cleaned file from: {0}\n    WLOG(params, '', TextEntry('40-019-00043', args=[tpclfile.filename]))\n    # ----------------------------------------------------------------------\n    # start a parameter dictionary\n    props = ParamDict()\n    # else we read the multi-fits file\n    tpclfile.read_multi()\n    # ----------------------------------------------------------------------\n    # read qc parameters\n    qc_names, qc_values, qc_logic, qc_pass = [], [], [], []\n    # first add number of QCs\n    num_qcs = tpclfile.get_key('TQCCNUM', dtype=int)\n    # now add the keys\n    for qc_it in range(num_qcs):\n        # add name\n        qc_names.append(tpclfile.get_key('TQCCN{0}'.format(qc_it), dtype=str))\n        # add value\n        value = tpclfile.get_key('TQCCV{0}'.format(qc_it), dtype=str)\n        # evaluate vaule\n        try:\n            qc_values.append(eval(value))\n        except:\n            qc_values.append(value)\n        # add logic\n        qc_logic.append(tpclfile.get_key('TQCCL{0}'.format(qc_it), dtype=str))\n        # add pass\n        qc_pass.append(tpclfile.get_key('TQCCP{0}'.format(qc_it), dtype=int))\n    # push into props\n    props['QC_PARAMS'] = [qc_names, qc_values, qc_logic, qc_pass]\n    # ----------------------------------------------------------------------\n    # push arrays into parameter dictionary\n    props['CORRECTED_E2DS'] = tpclfile.data_array[0]\n    props['TRANS_MASK'] = tpclfile.data_array[1].astype(bool)\n    props['ABSO_E2DS'] = tpclfile.data_array[2]\n    props['SKY_MODEL'] = tpclfile.data_array[3]\n    # ----------------------------------------------------------------------\n    # push into props\n    props['EXPO_WATER'] = tpclfile.get_key('KW_TELLUP_EXPO_WATER', dtype=float)\n    props['EXPO_OTHERS'] = tpclfile.get_key('KW_TELLUP_EXPO_OTHERS',\n                                            dtype=float)\n    props['DV_WATER'] = tpclfile.get_key('KW_TELLUP_DV_WATER', dtype=float)\n    props['DV_OTHERS'] = tpclfile.get_key('KW_TELLUP_DV_OTHERS', dtype=float)\n    props['CCFPOWER_WATER'] = tpclfile.get_key('KW_TELLUP_CCFP_WATER',\n                                               dtype=float)\n    props['CCFPOWER_OTHERS'] = tpclfile.get_key('KW_TELLUP_CCFP_OTHERS',\n                                                dtype=float)\n    # set sources\n    keys = ['CORRECTED_E2DS', 'TRANS_MASK', 'ABSO_E2DS', 'EXPO_WATER',\n            'EXPO_OTHERS', 'DV_WATER', 'DV_OTHERS', 'CCFPOWER_WATER',\n            'CCFPOWER_OTHERS', 'QC_PARAMS', 'SKY_MODEL']\n    props.set_sources(keys, 'header')\n    # ----------------------------------------------------------------------\n    # add constants used (can come from kwargs)\n    props['TELLUP_DO_PRECLEANING'] = tpclfile.get_key('KW_TELLUP_DO_PRECLEAN',\n                                                      dtype=bool)\n    props['TELLUP_D_WATER_ABSO'] = tpclfile.get_key('KW_TELLUP_DFLT_WATER',\n                                                    dtype=float)\n    props['TELLUP_CCF_SCAN_RANGE'] = tpclfile.get_key('KW_TELLUP_CCF_SRANGE',\n                                                      dtype=float)\n    props['TELLUP_CLEAN_OH_LINES'] = tpclfile.get_key('KW_TELLUP_CLEAN_OHLINES',\n                                                      dtype=bool)\n    props['TELLUP_REMOVE_ORDS'] = tpclfile.get_key('KW_TELLUP_REMOVE_ORDS',\n                                                   dtype=list, listtype=int)\n    props['TELLUP_SNR_MIN_THRES'] = tpclfile.get_key('KW_TELLUP_SNR_MIN_THRES',\n                                                     dtype=float)\n    kw_dexpo = 'KW_TELLUP_DEXPO_CONV_THRES'\n    props['TELLUP_DEXPO_CONV_THRES'] = tpclfile.get_key(kw_dexpo, dtype=float)\n    props['TELLUP_DEXPO_MAX_ITR'] = tpclfile.get_key('KW_TELLUP_DEXPO_MAX_ITR',\n                                                     dtype=int)\n    kw_kthres = 'KW_TELLUP_ABSOEXPO_KTHRES'\n    props['TELLUP_ABSO_EXPO_KTHRES'] = tpclfile.get_key(kw_kthres, dtype=float)\n    props['TELLUP_WAVE_START'] = tpclfile.get_key('KW_TELLUP_WAVE_START',\n                                                  dtype=float)\n    props['TELLUP_WAVE_END'] = tpclfile.get_key('KW_TELLUP_WAVE_END',\n                                                dtype=float)\n    props['TELLUP_DVGRID'] = tpclfile.get_key('KW_TELLUP_DVGRID', dtype=float)\n    props['TELLUP_ABSO_EXPO_KWID'] = tpclfile.get_key('KW_TELLUP_ABSOEXPO_KWID',\n                                                      dtype=float)\n    props['TELLUP_ABSO_EXPO_KEXP'] = tpclfile.get_key('KW_TELLUP_ABSOEXPO_KEXP',\n                                                      dtype=float)\n    props['TELLUP_TRANS_THRES'] = tpclfile.get_key('KW_TELLUP_TRANS_THRES',\n                                                   dtype=float)\n    props['TELLUP_TRANS_SIGLIM'] = tpclfile.get_key('KW_TELLUP_TRANS_SIGL',\n                                                    dtype=float)\n    props['TELLUP_FORCE_AIRMASS'] = tpclfile.get_key('KW_TELLUP_FORCE_AIRMASS',\n                                                     dtype=bool)\n    props['TELLUP_OTHER_BOUNDS'] = tpclfile.get_key('KW_TELLUP_OTHER_BOUNDS',\n                                                    dtype=list, listtype=float)\n    props['TELLUP_WATER_BOUNDS'] = tpclfile.get_key('KW_TELLUP_WATER_BOUNDS',\n                                                    dtype=list, listtype=float)\n    # set the source from header\n    keys = ['TELLUP_D_WATER_ABSO', 'TELLUP_CCF_SCAN_RANGE',\n            'TELLUP_CLEAN_OH_LINES', 'TELLUP_REMOVE_ORDS',\n            'TELLUP_SNR_MIN_THRES', 'TELLUP_DEXPO_CONV_THRES',\n            'TELLUP_DEXPO_MAX_ITR', 'TELLUP_ABSO_EXPO_KWID',\n            'TELLUP_ABSO_EXPO_KEXP', 'TELLUP_TRANS_THRES',\n            'TELLUP_TRANS_SIGLIM', 'TELLUP_FORCE_AIRMASS',\n            'TELLUP_OTHER_BOUNDS', 'TELLUP_WATER_BOUNDS',\n            'TELLUP_ABSO_EXPO_KTHRES', 'TELLUP_WAVE_START',\n            'TELLUP_WAVE_END', 'TELLUP_DVGRID', 'TELLUP_DO_PRECLEANING']\n    props.set_sources(keys, 'header')\n    # ----------------------------------------------------------------------\n    # return props\n    return props\n\n\n# =============================================================================\n# Database functions\n# =============================================================================\ndef load_tellu_file(params, key=None, inheader=None, filename=None,\n                    get_image=True, get_header=False, return_entries=False,\n                    **kwargs):\n    # get keys from params/kwargs\n    n_entries = kwargs.get('n_entries', 1)\n    required = kwargs.get('required', True)\n    mode = kwargs.get('mode', None)\n    # valid extension (zero by default)\n    ext = kwargs.get('ext', 0)\n    # fmt = valid astropy table format\n    fmt = kwargs.get('fmt', 'fits')\n    # kind = 'image' or 'table'\n    kind = kwargs.get('kind', 'image')\n    # ----------------------------------------------------------------------\n    # deal with filename set\n    if filename is not None:\n        # get db fits file\n        abspath = drs_database.get_db_abspath(params, filename, where='guess')\n        image, header = drs_database.get_db_file(params, abspath, ext, fmt,\n                                                 kind, get_image, get_header)\n        # return here\n        if get_header:\n            return [image], [header], [abspath]\n        else:\n            return [image], [abspath]\n    # ----------------------------------------------------------------------\n    # get telluDB\n    tdb = drs_database.get_full_database(params, 'telluric')\n    # get calibration entries\n    entries = drs_database.get_key_from_db(params, key, tdb, inheader,\n                                           n_ent=n_entries, mode=mode,\n                                           required=required)\n    # ----------------------------------------------------------------------\n    # deal with return entries\n    if return_entries:\n        return entries\n    # ----------------------------------------------------------------------\n    # get filename col\n    filecol = tdb.file_col\n    # ----------------------------------------------------------------------\n    # storage\n    images, headers, abspaths = [], [], []\n    # ----------------------------------------------------------------------\n    # loop around entries\n    for it, entry in enumerate(entries):\n        # get entry filename\n        filename = entry[filecol]\n        # ------------------------------------------------------------------\n        # get absolute path\n        abspath = drs_database.get_db_abspath(params, filename,\n                                              where='telluric')\n        # append to storage\n        abspaths.append(abspath)\n        # load image/header\n        image, header = drs_database.get_db_file(params, abspath, ext, fmt,\n                                                 kind, get_image, get_header)\n        # append to storage\n        images.append(image)\n        # append to storage\n        headers.append(header)\n    # ----------------------------------------------------------------------\n    # deal with returns with and without header\n    if get_header:\n        if not required and len(images) == 0:\n            return None, None, None\n        # deal with if n_entries is 1 (just return file not list)\n        if n_entries == 1:\n            return images[-1], headers[-1], abspaths[-1]\n        else:\n            return images, headers, abspaths\n    else:\n        if not required and len(images) == 0:\n            return None, None\n        # deal with if n_entries is 1 (just return file not list)\n        if n_entries == 1:\n            return images[-1], abspaths[-1]\n        else:\n            return images, abspaths\n\n\ndef load_templates(params, header, objname, fiber):\n    # TODO: update - bad loads all files just to get one header\n    #   OBJNAME in database --> select most recent and only load that file\n    # get file definition\n    out_temp = core.get_file_definition('TELLU_TEMP', params['INSTRUMENT'],\n                                        kind='red', fiber=fiber)\n    # deal with user not using template\n    if 'USE_TEMPLATE' in params['INPUTS']:\n        if not params['INPUTS']['USE_TEMPLATE']:\n            return None, None\n    # get key\n    temp_key = out_temp.get_dbkey(fiber=fiber)\n    # log status\n    WLOG(params, '', TextEntry('40-019-00045', args=[temp_key]))\n    # load tellu file, header and abspaths\n    temp_out = load_tellu_file(params, temp_key, header, get_header=True,\n                               n_entries='all', required=False)\n    temp_images, temp_headers, temp_filenames = temp_out\n\n    # deal with no files in database\n    if temp_images is None:\n        # log that we found no templates in database\n        WLOG(params, '', TextEntry('40-019-00003'))\n        return None, None\n    if len(temp_images) == 0:\n        # log that we found no templates in database\n        WLOG(params, '', TextEntry('40-019-00003'))\n        return None, None\n    # storage of valid files\n    valid_images, valid_filenames, valid_times = [], [], []\n    # loop around header and filter by objname\n    for it, temp_header in enumerate(temp_headers):\n        # get objname\n        temp_objname = temp_header[params['KW_OBJNAME'][0]]\n        # if temp_objname is the same as objname (input) then we have a\n        #   valid template\n        if temp_objname.upper().strip() == objname.upper().strip():\n            valid_images.append(temp_images[it])\n            valid_filenames.append(temp_filenames[it])\n\n    # deal with no files for this object name\n    if len(valid_images) == 0:\n        # log that we found no templates for this object\n        wargs = [params['KW_OBJNAME'][0], objname]\n        WLOG(params, 'info', TextEntry('40-019-00004', args=wargs))\n        return None, None\n    # log which template we are using\n    wargs = [valid_filenames[-1]]\n    WLOG(params, 'info', TextEntry('40-019-00005', args=wargs))\n    # only return most recent template\n    return valid_images[-1], valid_filenames[-1]\n\n\ndef get_transmission_files(params, recipe, header, fiber):\n    # get file definition\n    out_trans = core.get_file_definition('TELLU_TRANS', params['INSTRUMENT'],\n                                         kind='red', fiber=fiber)\n    # get key\n    trans_key = out_trans.get_dbkey(fiber=fiber)\n    # log status\n    WLOG(params, '', TextEntry('40-019-00046', args=[trans_key]))\n    # load tellu file, header and abspaths\n    _, trans_filenames = load_tellu_file(params, trans_key, header,\n                                         n_entries='all', get_image=False)\n    # storage for valid files/images/times\n    valid_filenames = []\n    # loop around header and get times\n    for filename in trans_filenames:\n        # only add if filename not in list already (files will be overwritten\n        #   but we can have multiple entries in database)\n        if filename not in valid_filenames:\n            # append to list\n            valid_filenames.append(filename)\n    # convert arrays\n    valid_filenames = np.array(valid_filenames)\n    # return all valid sorted in time\n    return valid_filenames\n\n\n# =============================================================================\n# Tapas functions\n# =============================================================================\ndef load_conv_tapas(params, recipe, header, mprops, fiber, **kwargs):\n    func_name = __NAME__ + '.load_conv_tapas()'\n    # get parameters from params/kwargs\n    tellu_absorbers = pcheck(params, 'TELLU_ABSORBERS', 'absorbers', kwargs,\n                             func_name, mapf='list', dtype=str)\n    fwhm_pixel_lsf = pcheck(params, 'FWHM_PIXEL_LSF', 'fwhm_lsf', kwargs,\n                            func_name)\n    # ----------------------------------------------------------------------\n    # Load any convolved files from database\n    # ----------------------------------------------------------------------\n    # get file definition\n    if 'TELLU_CONV' in recipe.outputs:\n        # get file definition\n        out_tellu_conv = recipe.outputs['TELLU_CONV'].newcopy(recipe=recipe,\n                                                              fiber=fiber)\n        # get key\n        conv_key = out_tellu_conv.get_dbkey()\n    else:\n        # get file definition\n        out_tellu_conv = core.get_file_definition('TELLU_CONV',\n                                                  params['INSTRUMENT'],\n                                                  kind='red', fiber=fiber)\n        # get key\n        conv_key = out_tellu_conv.get_dbkey(fiber=fiber)\n    # load tellu file\n    _, conv_paths = load_tellu_file(params, conv_key, header, n_entries='all',\n                                    get_image=False, required=False)\n    if conv_paths is None:\n        conv_paths = []\n    # construct the filename from file instance\n    out_tellu_conv.construct_filename(params, infile=mprops['WAVEINST'],\n                                      path=params['DRS_TELLU_DB'])\n    # if our npy file already exists then we just need to read it\n    if out_tellu_conv.filename in conv_paths:\n        # log that we are loading tapas convolved file\n        wargs = [out_tellu_conv.filename]\n        WLOG(params, '', TextEntry('40-019-00001', args=wargs))\n        # ------------------------------------------------------------------\n        # Load the convolved TAPAS atmospheric transmission from file\n        # ------------------------------------------------------------------\n        # load npy file\n        out_tellu_conv.read_file(params)\n        # push data into array\n        tapas_all_species = np.array(out_tellu_conv.data)\n    # else we need to load tapas and generate the convolution\n    else:\n        # ------------------------------------------------------------------\n        # Load the raw TAPAS atmospheric transmission\n        # ------------------------------------------------------------------\n        tapas_raw_table, tapas_raw_filename = drs_data.load_tapas(params)\n        # ------------------------------------------------------------------\n        # Convolve with master wave solution\n        # ------------------------------------------------------------------\n        tapas_all_species = _convolve_tapas(params, tapas_raw_table, mprops,\n                                            tellu_absorbers, fwhm_pixel_lsf)\n        # ------------------------------------------------------------------\n        # Save convolution for later use\n        # ------------------------------------------------------------------\n        out_tellu_conv.data = tapas_all_species\n        # log saving\n        wargs = [out_tellu_conv.filename]\n        WLOG(params, '', TextEntry('40-019-00002', args=wargs))\n        # save\n        out_tellu_conv.write_file(params)\n        # ------------------------------------------------------------------\n        # Move to telluDB and update telluDB\n        # ------------------------------------------------------------------\n        # npy file must set header/hdict (to update)\n        out_tellu_conv.header = header\n        out_tellu_conv.hdict = header\n        # copy the order profile to the calibDB\n        drs_database.add_file(params, out_tellu_conv)\n\n    # ------------------------------------------------------------------\n    # get the tapas_water and tapas_others data\n    # ------------------------------------------------------------------\n    # water is the second column\n    tapas_water = tapas_all_species[1, :]\n    # other is defined as the product of the other columns\n    tapas_other = np.prod(tapas_all_species[2:, :], axis=0)\n\n    # return the tapas info in a ParamDict\n    tapas_props = ParamDict()\n    tapas_props['TAPAS_ALL_SPECIES'] = tapas_all_species\n    tapas_props['TAPAS_WATER'] = tapas_water\n    tapas_props['TAPAS_OTHER'] = tapas_other\n    tapas_props['TAPAS_FILE'] = out_tellu_conv.filename\n    tapas_props['TELLU_ABSORBERS'] = tellu_absorbers\n    tapas_props['FWHM_PIXEL_LSF'] = fwhm_pixel_lsf\n    # set source\n    keys = ['TAPAS_ALL_SPECIES', 'TAPAS_WATER', 'TAPAS_OTHER',\n            'TAPAS_FILE', 'TELLU_ABSORBERS', 'FWHM_PIXEL_LSF']\n    tapas_props.set_sources(keys, func_name)\n    # return tapas props\n    return tapas_props\n\n\ndef load_tapas_spl(params, recipe, header):\n    # get file definition\n    tellu_tapas = core.get_file_definition('TELLU_TAPAS', params['INSTRUMENT'],\n                                           kind='red')\n    # make new copy of the file definition\n    out_tellu_tapas = tellu_tapas.newcopy(recipe=recipe)\n    # get key\n    conv_key = out_tellu_tapas.get_dbkey()\n    # load tellu file\n    _, conv_paths = load_tellu_file(params, conv_key, header, n_entries='all',\n                                    get_image=False, required=False)\n    # construct the filename from file instance\n    out_tellu_tapas.construct_filename(params,\n                                       path=params['DRS_TELLU_DB'])\n    # ----------------------------------------------------------------------\n    # if our npy file already exists then we just need to read it\n    if (conv_paths is not None) and (out_tellu_tapas.filename in conv_paths):\n        out_tellu_tapas.read_file(params)\n        # push into arrays\n        tmp_tapas = np.array(out_tellu_tapas.data)\n        tapas_wave = tmp_tapas[0]\n        trans_others = tmp_tapas[1]\n        trans_water = tmp_tapas[2]\n    # else we need to load it from file\n    else:\n        # ------------------------------------------------------------------\n        # Load the raw TAPAS atmospheric transmission\n        # ------------------------------------------------------------------\n        tapas_raw, tapas_raw_filename = drs_data.load_tapas(params)\n        # push into arrays\n        tapas_wave = tapas_raw['wavelength']\n        trans_others = (tapas_raw['trans_ch4'] * tapas_raw['trans_o3'] *\n                        tapas_raw['trans_n2o'] * tapas_raw['trans_o2'] *\n                        tapas_raw['trans_co2'])\n        trans_water = tapas_raw['trans_h2o']\n        # push into numpy array\n        tmp_tapas = np.zeros([3, len(tapas_wave)])\n        tmp_tapas[0] = tapas_wave\n        tmp_tapas[1] = trans_others\n        tmp_tapas[2] = trans_water\n        # ------------------------------------------------------------------\n        # Save tapas file for later use\n        # ------------------------------------------------------------------\n        # log saving\n        args = [out_tellu_tapas.filename]\n        WLOG(params, '', TextEntry('40-019-00047', args=[args]))\n        # save to disk\n        out_tellu_tapas.data = tmp_tapas\n        out_tellu_tapas.write_file(params)\n        # ------------------------------------------------------------------\n        # Move to telluDB and update telluDB\n        # ------------------------------------------------------------------\n        # npy file must set header/hdict (to update)\n        out_tellu_tapas.header = header\n        out_tellu_tapas.hdict = header\n        # copy the order profile to the telluDB\n        drs_database.add_file(params, out_tellu_tapas)\n    # ----------------------------------------------------------------------\n    # need to spline others and water\n    spl_others = mp.iuv_spline(tapas_wave, trans_others, k=1, ext=3)\n    spl_water = mp.iuv_spline(tapas_wave, trans_water, k=1, ext=3)\n    # return splines\n    return spl_others, spl_water\n\n\n# =============================================================================\n# Worker functions\n# =============================================================================\ndef _convolve_tapas(params, tapas_table, mprops, tellu_absorbers,\n                    fwhm_pixel_lsf):\n    # get master wave data\n    masterwave = mprops['WAVEMAP']\n    ydim = mprops['NBO']\n    xdim = mprops['NBPIX']\n    # ----------------------------------------------------------------------\n    # generate kernel for convolution\n    # ----------------------------------------------------------------------\n    # get the number of kernal pixels\n    npix_ker = int(np.ceil(3 * fwhm_pixel_lsf * 3.0 / 2) * 2 + 1)\n    # set up the kernel exponent\n    kernel = np.arange(npix_ker) - npix_ker // 2\n    # kernal is the a gaussian\n    kernel = np.exp(-0.5 * (kernel / (fwhm_pixel_lsf / mp.fwhm())) ** 2)\n    # we only want an approximation of the absorption to find the continuum\n    #    and estimate chemical abundances.\n    #    there's no need for a varying kernel shape\n    kernel /= mp.nansum(kernel)\n    # ----------------------------------------------------------------------\n    # storage for output\n    tapas_all_species = np.zeros([len(tellu_absorbers), xdim * ydim])\n    # ----------------------------------------------------------------------\n    # loop around each molecule in the absorbers list\n    #    (must be in\n    for n_species, molecule in enumerate(tellu_absorbers):\n        # log process\n        wmsg = 'Processing molecule: {0}'\n        WLOG(params, '', wmsg.format(molecule))\n        # get wavelengths\n        lam = tapas_table['wavelength']\n        # get molecule transmission\n        trans = tapas_table['trans_{0}'.format(molecule)]\n        # interpolate with Univariate Spline\n        tapas_spline = mp.iuv_spline(lam, trans)\n        # log the mean transmission level\n        wmsg = '\\tMean Trans level: {0:.3f}'.format(np.mean(trans))\n        WLOG(params, '', wmsg)\n        # convolve all tapas absorption to the SPIRou approximate resolution\n        for iord in range(ydim):\n            # get the order position\n            start = iord * xdim\n            end = (iord * xdim) + xdim\n            # interpolate the values at these points\n            svalues = tapas_spline(masterwave[iord, :])\n            # convolve with a gaussian function\n            nvalues = np.convolve(np.ones_like(svalues), kernel, mode='same')\n            cvalues = np.convolve(svalues, kernel, mode='same') / nvalues\n            # add to storage\n            tapas_all_species[n_species, start: end] = cvalues\n    # deal with non-real values (must be between 0 and 1\n    tapas_all_species[tapas_all_species > 1] = 1\n    tapas_all_species[tapas_all_species < 0] = 0\n\n    # return tapas_all_species\n    return tapas_all_species\n\n\ndef wave_to_wave(params, spectrum, wave1, wave2, reshape=False):\n    \"\"\"\n    Shifts a \"spectrum\" at a given wavelength solution (map), \"wave1\", to\n    another wavelength solution (map) \"wave2\"\n\n    :param params: ParamDict, the parameter dictionary\n    :param spectrum: numpy array (2D),  flux in the reference frame of the\n                     file wave1\n    :param wave1: numpy array (2D), initial wavelength grid\n    :param wave2: numpy array (2D), destination wavelength grid\n    :param reshape: bool, if True try to reshape spectrum to the shape of\n                    the output wave solution\n\n    :return output_spectrum: numpy array (2D), spectrum resampled to \"wave2\"\n    \"\"\"\n    func_name = __NAME__ + '._wave_to_wave()'\n    # deal with reshape\n    if reshape or (spectrum.shape != wave2.shape):\n        try:\n            spectrum = spectrum.reshape(wave2.shape)\n        except ValueError:\n            # log that we cannot reshape spectrum\n            eargs = [spectrum.shape, wave2.shape, func_name]\n            WLOG(params, 'error', TextEntry('09-019-00004', args=eargs))\n    # if they are the same\n    if mp.nansum(wave1 != wave2) == 0:\n        return spectrum\n    # size of array, assumes wave1, wave2 and spectrum have same shape\n    sz = np.shape(spectrum)\n    # create storage for the output spectrum\n    output_spectrum = np.zeros(sz) + np.nan\n    # looping through the orders to shift them from one grid to the other\n    for iord in range(sz[0]):\n        # only interpolate valid pixels\n        g = np.isfinite(spectrum[iord, :])\n        # if not enough valid pixel, then skip order (need k+1 points)\n        if mp.nansum(g) > 6:\n            # spline the spectrum\n            spline = mp.iuv_spline(wave1[iord, g], spectrum[iord, g],\n                                   k=5, ext=1)\n            # keep track of pixels affected by NaNs\n            splinemask = mp.iuv_spline(wave1[iord, :], g, k=5, ext=1)\n            # spline the input onto the output\n            output_spectrum[iord, :] = spline(wave2[iord, :])\n            # find which pixels are not NaNs\n            mask = splinemask(wave2[iord, :])\n            # set to NaN pixels outside of domain\n            bad = (output_spectrum[iord, :] == 0)\n            output_spectrum[iord, bad] = np.nan\n            # affected by a NaN value\n            # normally we would use only pixels ==1, but we get values\n            #    that are not exactly one due to the interpolation scheme.\n            #    We just set that >50% of the\n            # flux comes from valid pixels\n            bad = (mask <= 0.5)\n            # mask pixels affected by nan\n            output_spectrum[iord, bad] = np.nan\n    # return the filled output spectrum\n    return output_spectrum\n\n\n# =============================================================================\n# Start of code\n# =============================================================================\n# Main code here\nif __name__ == \"__main__\":\n    # ----------------------------------------------------------------------\n    # print 'Hello World!'\n    print(\"Hello World!\")\n\n# =============================================================================\n# End of code\n# =============================================================================\n", "meta": {"hexsha": "9bb915ef00c376e83d4200d28ab713d967b6f63d", "size": 92384, "ext": "py", "lang": "Python", "max_stars_repo_path": "apero/science/telluric/gen_tellu.py", "max_stars_repo_name": "njcuk9999/apero-drs", "max_stars_repo_head_hexsha": "83b043e9f277a011b03e0227c77307961b200901", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-09T17:49:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T17:49:31.000Z", "max_issues_repo_path": "apero/science/telluric/gen_tellu.py", "max_issues_repo_name": "njcuk9999/apero-drs", "max_issues_repo_head_hexsha": "83b043e9f277a011b03e0227c77307961b200901", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 43, "max_issues_repo_issues_event_min_datetime": "2020-10-06T18:42:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T21:23:10.000Z", "max_forks_repo_path": "apero/science/telluric/gen_tellu.py", "max_forks_repo_name": "njcuk9999/apero-drs", "max_forks_repo_head_hexsha": "83b043e9f277a011b03e0227c77307961b200901", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.7293879616, "max_line_length": 85, "alphanum_fraction": 0.5508854347, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 21887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.2782568056728001, "lm_q1q2_score": 0.17625071665136183}}
{"text": "#!/usr/bin/env python3\nimport getopt, os, sys, time, multiprocessing, random, math\nimport parmed as pmd\nimport numpy as np\nimport pdbfixer as pfx\n\nusage = '\\nUsage: python fix_orein_50S_pdb.py\\n' \\\n        '       --pdbfile | -f <PDB.pdb> input pdb file\\n'\\\n        '       [--help | -h] Print this information\\n\\n'\n\n########################################################\ndef rotate_coor(structure, vector1, vector2):\n\ttheta = np.arccos(np.dot(vector1, vector2)/(np.linalg.norm(vector1)*(np.linalg.norm(vector2))))\n\tnormal_vector = np.cross(vector1, vector2)/np.linalg.norm(np.cross(vector1, vector2))\n\tw = np.cos(theta/2)\n\tx = normal_vector[0]*np.sin(theta/2)\n\ty = normal_vector[1]*np.sin(theta/2)\n\tz = normal_vector[2]*np.sin(theta/2)\n\tQ = np.mat([[1-2*y*y-2*z*z, 2*x*y-2*z*w, 2*x*z+2*y*w], \n\t\t\t    [2*x*y+2*z*w, 1-2*x*x-2*z*z, 2*y*z-2*x*w],\n\t\t\t    [2*x*z-2*y*w, 2*y*z+2*x*w, 1-2*x*x-2*y*y]])\n\tnew_pos = pmd.unit.Quantity([], pmd.unit.angstroms)\n\tfor pos in structure.positions:\n\t\tP = np.mat(pos.value_in_unit(pmd.unit.angstroms)).T\n\t\tpos = Q*P\n\t\tpos = pos.A1\n\t\tpos = pmd.unit.Quantity(list(pos), pmd.unit.angstroms)\n\t\tnew_pos.append(pos)\n\tstructure.positions = new_pos\n#########################################################\n\ndef calc_average_position(atom_cor_list):\n\tavg_cor = pmd.unit.Quantity((0,0,0), pmd.unit.angstroms)\n\tfor cor in atom_cor_list:\n\t\tavg_cor += cor\n\tavg_cor /= len(atom_cor_list)\n\treturn avg_cor\n########################################################\n\n############################# MAIN #######################\npdbfile = ''\n\nif len(sys.argv) == 1:\n    print(usage)\n    sys.exit()\n\ntry:\n    opts, args = getopt.getopt(sys.argv[1:],\"hf:\", [\"pdbfile=\"])\nexcept getopt.GetoptError:\n    print(usage)\n    sys.exit()\nfor opt, arg in opts:\n    if opt == '-h':\n        print(usage)\n        sys.exit()\n    elif opt in (\"-f\", \"--pdbfile\"):\n        pdbfile = arg\n\nnonstandard_res = ['2MA', '3AU', '4SU', '5MU', '6MZ', '7MG', 'CM0', 'PSU', 'QUO', 'T6A', 'U8U']\nstandard_res = ['A', 'U', 'U', 'U', 'A', 'G', 'U', 'U', 'G', 'A', 'U']\nnonstandard_map = {}\nfor i in range(len(nonstandard_res)):\n\tnonstandard_map[nonstandard_res[i]] = standard_res[i]\n\nfixer = pfx.PDBFixer(filename=pdbfile)\npdb_struct = pmd.load_file(pdbfile)\nresid_list = []\nsegid_list = []\nmutate_dict = {}\nprint('--> Checking nonstandard RNA linker')\nfor res in pdb_struct.residues:\n\tresid_list.append(res.number)\n\tsegid_list.append(res.segid)\n\tif not (res.chain in mutate_dict):\n\t\tmutate_dict[res.chain] = []\n\tif res.name in nonstandard_res:\n\t\tmutate_dict[res.chain].append(res.name + '-' + str(res.number) + '-' + nonstandard_map[res.name])\n\t\tprint('    ' + res.name + '-' + str(res.number) + '-' + nonstandard_map[res.name] + ' in chain ' + res.chain)\n\nfor chain in mutate_dict:\n\tfixer.applyMutations(mutate_dict[chain], chain)\nprint('    Done')\n\nfixer.findMissingResidues()\nfixer.findMissingAtoms()\n\nmiss_atm_dict = fixer.missingAtoms\nprint('--> Missing atoms:')\nfor res in miss_atm_dict:\n\tmiss_atm_list = miss_atm_dict[res]\n\tresname = res.name\n\tresid = res.id\n\tchain_id = res.chain.id\n\tout_str = '    Chain %s residue %s %s: '%(chain_id, resname, resid)\n\tfor atm in miss_atm_list:\n\t\tatmname = atm.name\n\t\tout_str += atmname + ' '\n\tprint(out_str)\n\nprint('--> Add missing atoms')\nfixer.addMissingAtoms()\nprint('    Done')\n\nnew_pdb_struct = pmd.openmm.load_topology(fixer.topology, xyz=fixer.positions)\n\nprint('--> Renumber new pdb')\nfor res in new_pdb_struct.residues:\n\tres.number = resid_list[res.idx]\n\tres.segid = segid_list[res.idx]\nfor atm in new_pdb_struct.atoms:\n\tatm.number = atm.idx + 1\nprint('    Done')\n\nprint('--> Translate new pdb as 23S A2602 N6 at origin')\nidx_1 = 0\nidx_2 = 0\nfor atm in new_pdb_struct.atoms:\n\tif atm.residue.segid == '23S' and atm.residue.number == 2602 and atm.name == 'N6':\n\t\tidx_1 = atm.idx\n\telif atm.residue.segid == 'L24' and atm.residue.number == 51 and atm.name == 'N':\n\t\tidx_2 = atm.idx\ncoor_1 = new_pdb_struct.positions[idx_1]\nnew_pos = pmd.unit.Quantity([], pmd.unit.angstroms)\nfor pos in new_pdb_struct.positions:\n\tpos = pos - coor_1\n\tnew_pos.append(pos)\nnew_pdb_struct.positions = new_pos\nprint('    Done')\n\nprint('--> Rotate new pdb')\nprint('    rotate coor to make vector from 23S:2602@N6 to L24:51@N along x-axis')\n# rotate coor to make vector from 23S:2602@N6 to L24:51@N along x-axis \ncoor_1 = new_pdb_struct.positions[idx_1]\ncoor_2 = new_pdb_struct.positions[idx_2]\nvector1 = np.array(coor_2.value_in_unit(pmd.unit.angstroms) - coor_1.value_in_unit(pmd.unit.angstroms), dtype=np.float64)\nvector2 = np.array([1, 0, 0], dtype=np.float64)\nrotate_coor(new_pdb_struct, vector1, vector2)\n\ntag_AtR = 0\nfor res in new_pdb_struct.residues:\n\tif res.segid == 'AtR':\n\t\ttag_AtR = 1\n\t\tbreak\n\nif tag_AtR == 1:\n\tprint('    rotate coor to make yz-component of vector from centroid of AtR:76@ribose_ring'+\n\t\t'to centroid of PtR:76@ribose_ring along y-axis')\n\t# rotate coor to make yz-component of vector from centroid of AtR:76@ribose_ring \n\t# to centroid of PtR:76@ribose_ring along y-axis\n\tribose_ring_cor_list = []\n\tfor atm in new_pdb_struct.atoms:\n\t\tif atm.residue.number == 76 and atm.residue.segid == 'AtR':\n\t\t\tif atm.name == \"C1'\" or atm.name == \"C2'\" or atm.name == \"C3'\" or atm.name == \"C4'\" or atm.name == \"C5'\":\n\t\t\t\tribose_ring_cor_list.append(new_pdb_struct.positions[atm.idx])\n\tcoor_1 = calc_average_position(ribose_ring_cor_list)\n\tribose_ring_cor_list = []\n\tfor atm in new_pdb_struct.atoms:\n\t\tif atm.residue.number == 76 and atm.residue.segid == 'PtR':\n\t\t\tif atm.name == \"C1'\" or atm.name == \"C2'\" or atm.name == \"C3'\" or atm.name == \"C4'\" or atm.name == \"C5'\":\n\t\t\t\tribose_ring_cor_list.append(new_pdb_struct.positions[atm.idx])\n\tcoor_2 = calc_average_position(ribose_ring_cor_list)\n\tvector1 = np.array(coor_2.value_in_unit(pmd.unit.angstroms) - coor_1.value_in_unit(pmd.unit.angstroms), dtype=np.float64)\n\tvector1[0] = 0.0\n\tvector2 = np.array([0, 1, 0], dtype=np.float64)\n\trotate_coor(new_pdb_struct, vector1, vector2)\n\nprint('    Done')\n\nnew_pdb_struct.write_pdb(pdbfile.split('.pdb')[0] + '_model.pdb', renumber=False, charmm=True)\n", "meta": {"hexsha": "7d4cb7036e46c485c151d6aa1a191127a29d0a67", "size": 6065, "ext": "py", "lang": "Python", "max_stars_repo_path": "CG_ribosome_parameterization/fix_orein_50S_pdb.py", "max_stars_repo_name": "obrien-lab/cg_simtk_protain_folding", "max_stars_repo_head_hexsha": "c64aa49696afe6fc1680c083cda556697d937f52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CG_ribosome_parameterization/fix_orein_50S_pdb.py", "max_issues_repo_name": "obrien-lab/cg_simtk_protain_folding", "max_issues_repo_head_hexsha": "c64aa49696afe6fc1680c083cda556697d937f52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CG_ribosome_parameterization/fix_orein_50S_pdb.py", "max_forks_repo_name": "obrien-lab/cg_simtk_protain_folding", "max_forks_repo_head_hexsha": "c64aa49696afe6fc1680c083cda556697d937f52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6764705882, "max_line_length": 122, "alphanum_fraction": 0.6619950536, "include": true, "reason": "import numpy", "num_tokens": 1897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.2814055953761019, "lm_q1q2_score": 0.17619484294584703}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nY'CbCr Colour Encoding\n======================\n\nDefines the *Y'CbCr* colour encoding related transformations:\n\n-   :func:`colour.RGB_to_YCbCr`\n-   :func:`colour.YCbCr_to_RGB`\n-   :func:`colour.RGB_to_YcCbcCrc`\n-   :func:`colour.YcCbcCrc_to_RGB`\n\nNotes\n-----\n-   *Y'CbCr* is not an absolute colourspace.\n\nReferences\n----------\n-   :cite:`InternationalTelecommunicationUnion2011e` : International\n    Telecommunication Union. (2011). Recommendation ITU-T T.871 - Information\n    technology - Digital compression and coding of continuous-tone still\n    images: JPEG File Interchange Format (JFIF).\n    https://www.itu.int/rec/dologin_pub.asp?lang=e&\\\nid=T-REC-T.871-201105-I!!PDF-E&type=items\n-   :cite:`InternationalTelecommunicationUnion2015h` : International\n    Telecommunication Union. (2015). Recommendation ITU-R BT.2020 - Parameter\n    values for ultra-high definition television systems for production and\n    international programme exchange (pp. 1-8).\n    https://www.itu.int/dms_pubrec/itu-r/rec/bt/\\\nR-REC-BT.2020-2-201510-I!!PDF-E.pdf\n-   :cite:`InternationalTelecommunicationUnion2015i` : International\n    Telecommunication Union. (2015). Recommendation ITU-R BT.709-6 - Parameter\n    values for the HDTV standards for production and international programme\n    exchange BT Series Broadcasting service (pp. 1-32).\n    https://www.itu.int/dms_pubrec/itu-r/rec/bt/\\\nR-REC-BT.709-6-201506-I!!PDF-E.pdf\n-   :cite:`SocietyofMotionPictureandTelevisionEngineers1999b` : Society of\n    Motion Picture and Television Engineers. (1999). ANSI/SMPTE 240M-1995 -\n    Signal Parameters - 1125-Line High-Definition Production Systems (pp. 1-7).\n    http://car.france3.mars.free.fr/HD/\\\nINA-%2026%20jan%2006/SMPTE%20normes%20et%20confs/s240m.pdf\n-   :cite:`Wikipedia2004d` : Wikipedia. (2004). YCbCr. Retrieved February 29,\n    2016, from https://en.wikipedia.org/wiki/YCbCr\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\n\nfrom colour.constants import DEFAULT_FLOAT_DTYPE, DEFAULT_INT_DTYPE\nfrom colour.models.rgb.transfer_functions import (\n    CV_range, eotf_inverse_BT2020, eotf_BT2020)\nfrom colour.utilities import (CaseInsensitiveMapping, as_float_array,\n                              domain_range_scale, from_range_1, to_domain_1,\n                              tsplit, tstack)\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2020 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-developers@colour-science.org'\n__status__ = 'Development'\n\n__all__ = [\n    'WEIGHTS_YCBCR', 'YCbCr_ranges', 'RGB_to_YCbCr', 'YCbCr_to_RGB',\n    'RGB_to_YcCbcCrc', 'YcCbcCrc_to_RGB'\n]\n\nWEIGHTS_YCBCR = CaseInsensitiveMapping({\n    'ITU-R BT.601': np.array([0.2990, 0.1140]),\n    'ITU-R BT.709': np.array([0.2126, 0.0722]),\n    'ITU-R BT.2020': np.array([0.2627, 0.0593]),\n    'SMPTE-240M': np.array([0.2122, 0.0865])\n})\n\"\"\"\nLuma weightings presets.\n\nReferences\n----------\n:cite:`InternationalTelecommunicationUnion2011e`,\n:cite:`InternationalTelecommunicationUnion2015i`,\n:cite:`InternationalTelecommunicationUnion2015h`,\n:cite:`SocietyofMotionPictureandTelevisionEngineers1999b`,\n:cite:`Wikipedia2004d`\n\nWEIGHTS_YCBCR : dict\n    **{'ITU-R BT.601', 'ITU-R BT.709', 'ITU-R BT.2020', 'SMPTE-240M}**\n\"\"\"\n\n\ndef YCbCr_ranges(bits, is_legal, is_int):\n    \"\"\"\"\n    Returns the *Y'CbCr* colour encoding ranges array for given bit depth,\n    range legality and representation.\n\n    Parameters\n    ----------\n    bits : int\n        Bit depth of the *Y'CbCr* colour encoding ranges array.\n    is_legal : bool\n        Whether the *Y'CbCr* colour encoding ranges array is legal.\n    is_int : bool\n        Whether the *Y'CbCr* colour encoding ranges array represents integer\n        code values.\n\n    Returns\n    -------\n    ndarray\n        *Y'CbCr* colour encoding ranges array.\n\n    Examples\n    --------\n    >>> YCbCr_ranges(8, True, True)\n    array([ 16, 235,  16, 240])\n    >>> YCbCr_ranges(8, True, False)  # doctest: +ELLIPSIS\n    array([ 0.0627451...,  0.9215686...,  0.0627451...,  0.9411764...])\n    >>> YCbCr_ranges(10, False, False)\n    array([ 0. ,  1. , -0.5,  0.5])\n    \"\"\"\n\n    if is_legal:\n        ranges = np.array([16, 235, 16, 240])\n        ranges *= 2 ** (bits - 8)\n    else:\n        ranges = np.array([0, 2 ** bits - 1, 0, 2 ** bits - 1])\n\n    if not is_int:\n        ranges = ranges.astype(DEFAULT_FLOAT_DTYPE) / (2 ** bits - 1)\n\n    if is_int and not is_legal:\n        ranges[3] = 2 ** bits\n\n    if not is_int and not is_legal:\n        ranges[2] = -0.5\n        ranges[3] = 0.5\n\n    return ranges\n\n\ndef RGB_to_YCbCr(RGB,\n                 K=WEIGHTS_YCBCR['ITU-R BT.709'],\n                 in_bits=10,\n                 in_legal=False,\n                 in_int=False,\n                 out_bits=8,\n                 out_legal=True,\n                 out_int=False,\n                 **kwargs):\n    \"\"\"\n    Converts an array of *R'G'B'* values to the corresponding *Y'CbCr* colour\n    encoding values array.\n\n    Parameters\n    ----------\n    RGB : array_like\n        Input *R'G'B'* array of floats or integer values.\n    K : array_like, optional\n        Luma weighting coefficients of red and blue. See\n        :attr:`colour.WEIGHTS_YCBCR` for presets. Default is\n        *(0.2126, 0.0722)*, the weightings for *ITU-R BT.709*.\n    in_bits : int, optional\n        Bit depth for integer input, or used in the calculation of the\n        denominator for legal range float values, i.e. 8-bit means the float\n        value for legal white is *235 / 255*. Default is *10*.\n    in_legal : bool, optional\n        Whether to treat the input values as legal range. Default is *False*.\n    in_int : bool, optional\n        Whether to treat the input values as ``in_bits`` integer code values.\n        Default is *False*.\n    out_bits : int, optional\n        Bit depth for integer output, or used in the calculation of the\n        denominator for legal range float values, i.e. 8-bit means the float\n        value for legal white is *235 / 255*. Ignored if ``out_legal`` and\n        ``out_int`` are both *False*. Default is *8*.\n    out_legal : bool, optional\n        Whether to return legal range values. Default is *True*.\n    out_int : bool, optional\n        Whether to return values as ``out_bits`` integer code values. Default\n        is *False*.\n\n    Other Parameters\n    ----------------\n    in_range : array_like, optional\n        Array overriding the computed range such as\n        *in_range = (RGB_min, RGB_max)*. If ``in_range`` is undefined,\n        *RGB_min* and *RGB_max* will be computed using :func:`colour.CV_range`\n        definition.\n    out_range : array_like, optional\n        Array overriding the computed range such as\n        *out_range = (Y_min, Y_max, C_min, C_max)`. If ``out_range`` is\n        undefined, *Y_min*, *Y_max*, *C_min* and *C_max* will be computed\n        using :func:`colour.models.rgb.ycbcr.YCbCr_ranges` definition.\n\n    Returns\n    -------\n    ndarray\n        *Y'CbCr* colour encoding array of integer or float values.\n\n    Warnings\n    --------\n    For *Recommendation ITU-R BT.2020*, :func:`colour.RGB_to_YCbCr` definition\n    is only applicable to the non-constant luminance implementation.\n    :func:`colour.RGB_to_YcCbcCrc` definition should be used for the constant\n    luminance case as per :cite:`InternationalTelecommunicationUnion2015h`.\n\n    Notes\n    -----\n\n    +----------------+-----------------------+---------------+\n    | **Domain \\\\***  | **Scale - Reference** | **Scale - 1** |\n    +================+=======================+===============+\n    | ``RGB``        | [0, 1]                | [0, 1]        |\n    +----------------+-----------------------+---------------+\n\n    +----------------+-----------------------+---------------+\n    | **Range \\\\***   | **Scale - Reference** | **Scale - 1** |\n    +================+=======================+===============+\n    | ``YCbCr``      | [0, 1]                | [0, 1]        |\n    +----------------+-----------------------+---------------+\n\n    \\\\* This definition has input and output integer switches, thus the\n    domain-range scale information is only given for the floating point mode.\n\n    -   The default arguments, ``**{'in_bits': 10, 'in_legal': False,\n        'in_int': False, 'out_bits': 8, 'out_legal': True, 'out_int': False}``\n        transform a float *R'G'B'* input array normalised to domain [0, 1]\n        (``in_bits`` is ignored) to a float *Y'CbCr* output array where *Y'* is\n        normalised to range [16 / 255, 235 / 255] and *Cb* and *Cr* are\n        normalised to range [16 / 255, 240./255]. The float values are\n        calculated based on an [0, 255] integer range, but no 8-bit\n        quantisation or clamping are performed.\n\n    References\n    ----------\n    :cite:`InternationalTelecommunicationUnion2011e`,\n    :cite:`InternationalTelecommunicationUnion2015i`,\n    :cite:`SocietyofMotionPictureandTelevisionEngineers1999b`,\n    :cite:`Wikipedia2004d`\n\n    Examples\n    --------\n    >>> RGB = np.array([1.0, 1.0, 1.0])\n    >>> RGB_to_YCbCr(RGB)  # doctest: +ELLIPSIS\n    array([ 0.9215686...,  0.5019607...,  0.5019607...])\n\n    Matching float output of The Foundry Nuke's Colorspace node set to YCbCr:\n\n    >>> RGB_to_YCbCr(RGB,\n    ...              out_range=(16 / 255, 235 / 255, 15.5 / 255, 239.5 / 255))\n    ... # doctest: +ELLIPSIS\n    array([ 0.9215686...,  0.5       ,  0.5       ])\n\n    Matching float output of The Foundry Nuke's Colorspace node set to YPbPr:\n\n    >>> RGB_to_YCbCr(RGB, out_legal=False, out_int=False)\n    ... # doctest: +ELLIPSIS\n    array([ 1.,  0.,  0.])\n\n    Creating integer code values as per standard 10-bit SDI:\n\n    >>> RGB_to_YCbCr(RGB, out_legal=True, out_bits=10, out_int=True)\n    ... # doctest: +ELLIPSIS\n    array([940, 512, 512]...)\n\n    For JFIF JPEG conversion as per ITU-T T.871\n    :cite:`InternationalTelecommunicationUnion2011e`:\n\n    >>> RGB = np.array([102, 0, 51])\n    >>> RGB_to_YCbCr(RGB, K=WEIGHTS_YCBCR['ITU-R BT.601'], in_range=(0, 255),\n    ...              out_range=(0, 255, 0, 256), out_int=True)\n    ... # doctest: +ELLIPSIS\n    array([ 36, 136, 175]...)\n\n    Note the use of 256 for the max *Cb / Cr* value, which is required so that\n    the *Cb* and *Cr* output is centered about 128. Using 255 centres it\n    about 127.5, meaning that there is no integer code value to represent\n    achromatic colours. This does however create the possibility of output\n    integer codes with value of 256, which cannot be stored in 8-bit integer\n    representation. Recommendation ITU-T T.871 specifies these should be\n    clamped to 255.\n\n    These JFIF JPEG ranges are also obtained as follows:\n\n    >>> RGB_to_YCbCr(RGB, K=WEIGHTS_YCBCR['ITU-R BT.601'], in_bits=8,\n    ...              in_int=True, out_legal=False, out_int=True)\n    ... # doctest: +ELLIPSIS\n    array([ 36, 136, 175]...)\n    \"\"\"\n\n    if in_int:\n        RGB = as_float_array(RGB)\n    else:\n        RGB = to_domain_1(RGB)\n\n    Kr, Kb = K\n    RGB_min, RGB_max = kwargs.get('in_range',\n                                  CV_range(in_bits, in_legal, in_int))\n    Y_min, Y_max, C_min, C_max = kwargs.get(\n        'out_range', YCbCr_ranges(out_bits, out_legal, out_int))\n\n    RGB_float = RGB.astype(DEFAULT_FLOAT_DTYPE) - RGB_min\n    RGB_float *= 1 / (RGB_max - RGB_min)\n    R, G, B = tsplit(RGB_float)\n\n    Y = Kr * R + (1 - Kr - Kb) * G + Kb * B\n    Cb = 0.5 * (B - Y) / (1 - Kb)\n    Cr = 0.5 * (R - Y) / (1 - Kr)\n    Y *= Y_max - Y_min\n    Y += Y_min\n    Cb *= C_max - C_min\n    Cr *= C_max - C_min\n    Cb += (C_max + C_min) / 2\n    Cr += (C_max + C_min) / 2\n\n    YCbCr = tstack([Y, Cb, Cr])\n    YCbCr = np.round(YCbCr).astype(\n        DEFAULT_INT_DTYPE) if out_int else from_range_1(YCbCr)\n\n    return YCbCr\n\n\ndef YCbCr_to_RGB(YCbCr,\n                 K=WEIGHTS_YCBCR['ITU-R BT.709'],\n                 in_bits=8,\n                 in_legal=True,\n                 in_int=False,\n                 out_bits=10,\n                 out_legal=False,\n                 out_int=False,\n                 **kwargs):\n    \"\"\"\n    Converts an array of *Y'CbCr* colour encoding values to the corresponding\n    *R'G'B'* values array.\n\n    Parameters\n    ----------\n    YCbCr : array_like\n        Input *Y'CbCr* colour encoding array of integer or float values.\n    K : array_like, optional\n        Luma weighting coefficients of red and blue. See\n        :attr:`colour.WEIGHTS_YCBCR` for presets. Default is\n        *(0.2126, 0.0722)*, the weightings for *ITU-R BT.709*.\n    in_bits : int, optional\n        Bit depth for integer input, or used in the calculation of the\n        denominator for legal range float values, i.e. 8-bit means the float\n        value for legal white is *235 / 255*. Default is *8*.\n    in_legal : bool, optional\n        Whether to treat the input values as legal range. Default is *True*.\n    in_int : bool, optional\n        Whether to treat the input values as ``in_bits`` integer code values.\n        Default is *False*.\n    out_bits : int, optional\n        Bit depth for integer output, or used in the calculation of the\n        denominator for legal range float values, i.e. 8-bit means the float\n        value for legal white is *235 / 255*. Ignored if ``out_legal`` and\n        ``out_int`` are both *False*. Default is *10*.\n    out_legal : bool, optional\n        Whether to return legal range values. Default is *False*.\n    out_int : bool, optional\n        Whether to return values as ``out_bits`` integer code values. Default\n        is *False*.\n\n    Other Parameters\n    ----------------\n    in_range : array_like, optional\n        Array overriding the computed range such as\n        *in_range = (Y_min, Y_max, C_min, C_max)*. If ``in_range`` is\n        undefined, *Y_min*, *Y_max*, *C_min* and *C_max* will be computed using\n        :func:`colour.models.rgb.ycbcr.YCbCr_ranges` definition.\n    out_range : array_like, optional\n        Array overriding the computed range such as\n        *out_range = (RGB_min, RGB_max)*. If ``out_range`` is undefined,\n        *RGB_min* and *RGB_max* will be computed using :func:`colour.CV_range`\n        definition.\n\n    Returns\n    -------\n    ndarray\n        *R'G'B'* array of integer or float values.\n\n    Notes\n    -----\n\n    +----------------+-----------------------+---------------+\n    | **Domain \\\\***  | **Scale - Reference** | **Scale - 1** |\n    +================+=======================+===============+\n    | ``YCbCr``      | [0, 1]                | [0, 1]        |\n    +----------------+-----------------------+---------------+\n\n    +----------------+-----------------------+---------------+\n    | **Range \\\\***   | **Scale - Reference** | **Scale - 1** |\n    +================+=======================+===============+\n    | ``RGB``        | [0, 1]                | [0, 1]        |\n    +----------------+-----------------------+---------------+\n\n    \\\\* This definition has input and output integer switches, thus the\n    domain-range scale information is only given for the floating point mode.\n\n    Warnings\n    --------\n    For *Recommendation ITU-R BT.2020*, :func:`colour.YCbCr_to_RGB`\n    definition is only applicable to the non-constant luminance implementation.\n    :func:`colour.YcCbcCrc_to_RGB` definition should be used for the constant\n    luminance case as per :cite:`InternationalTelecommunicationUnion2015h`.\n\n    References\n    ----------\n    :cite:`InternationalTelecommunicationUnion2011e`,\n    :cite:`InternationalTelecommunicationUnion2015i`,\n    :cite:`SocietyofMotionPictureandTelevisionEngineers1999b`,\n    :cite:`Wikipedia2004d`\n\n    Examples\n    --------\n    >>> YCbCr = np.array([502, 512, 512])\n    >>> YCbCr_to_RGB(YCbCr, in_bits=10, in_legal=True, in_int=True)\n    array([ 0.5,  0.5,  0.5])\n    \"\"\"\n\n    if in_int:\n        YCbCr = as_float_array(YCbCr)\n    else:\n        YCbCr = to_domain_1(YCbCr)\n\n    Y, Cb, Cr = tsplit(YCbCr.astype(DEFAULT_FLOAT_DTYPE))\n    Kr, Kb = K\n    Y_min, Y_max, C_min, C_max = kwargs.get(\n        'in_range', YCbCr_ranges(in_bits, in_legal, in_int))\n    RGB_min, RGB_max = kwargs.get('out_range',\n                                  CV_range(out_bits, out_legal, out_int))\n\n    Y -= Y_min\n    Cb -= (C_max + C_min) / 2\n    Cr -= (C_max + C_min) / 2\n    Y *= 1 / (Y_max - Y_min)\n    Cb *= 1 / (C_max - C_min)\n    Cr *= 1 / (C_max - C_min)\n    R = Y + (2 - 2 * Kr) * Cr\n    B = Y + (2 - 2 * Kb) * Cb\n    G = (Y - Kr * R - Kb * B) / (1 - Kr - Kb)\n\n    RGB = tstack([R, G, B])\n    RGB *= RGB_max - RGB_min\n    RGB += RGB_min\n    RGB = np.round(RGB).astype(DEFAULT_INT_DTYPE) if out_int else from_range_1(\n        RGB)\n\n    return RGB\n\n\ndef RGB_to_YcCbcCrc(RGB,\n                    out_bits=10,\n                    out_legal=True,\n                    out_int=False,\n                    is_12_bits_system=False,\n                    **kwargs):\n    \"\"\"\n    Converts an array of *RGB* linear values to the corresponding *Yc'Cbc'Crc'*\n    colour encoding values array.\n\n    Parameters\n    ----------\n    RGB : array_like\n        Input *RGB* array of linear float values.\n    out_bits : int, optional\n        Bit depth for integer output, or used in the calculation of the\n        denominator for legal range float values, i.e. 8-bit means the float\n        value for legal white is *235 / 255*. Ignored if ``out_legal`` and\n        ``out_int`` are both *False*. Default is *10*.\n    out_legal : bool, optional\n        Whether to return legal range values. Default is *True*.\n    out_int : bool, optional\n        Whether to return values as ``out_bits`` integer code values. Default\n        is *False*.\n    is_12_bits_system : bool, optional\n        *Recommendation ITU-R BT.2020* OETF (OECF) adopts different parameters\n        for 10 and 12 bit systems. Default is *False*.\n\n    Other Parameters\n    ----------------\n    out_range : array_like, optional\n        Array overriding the computed range such as\n        *out_range = (Y_min, Y_max, C_min, C_max)*. If ``out_range`` is\n        undefined, *Y_min*, *Y_max*, *C_min* and *C_max* will be computed\n        using :func:`colour.models.rgb.ycbcr.YCbCr_ranges` definition.\n\n    Returns\n    -------\n    ndarray\n        *Yc'Cbc'Crc'* colour encoding array of integer or float values.\n\n    Notes\n    -----\n\n    +----------------+-----------------------+---------------+\n    | **Domain \\\\***  | **Scale - Reference** | **Scale - 1** |\n    +================+=======================+===============+\n    | ``RGB``        | [0, 1]                | [0, 1]        |\n    +----------------+-----------------------+---------------+\n\n    +----------------+-----------------------+---------------+\n    | **Range \\\\***   | **Scale - Reference** | **Scale - 1** |\n    +================+=======================+===============+\n    | ``YcCbcCrc``   | [0, 1]                | [0, 1]        |\n    +----------------+-----------------------+---------------+\n\n    \\\\* This definition has input and output integer switches, thus the\n    domain-range scale information is only given for the floating point mode.\n\n    Warnings\n    --------\n    This definition is specifically for usage with\n    *Recommendation ITU-R BT.2020* when adopting the constant luminance\n    implementation.\n\n    References\n    ----------\n    :cite:`InternationalTelecommunicationUnion2015h`, :cite:`Wikipedia2004d`\n\n    Examples\n    --------\n    >>> RGB = np.array([0.18, 0.18, 0.18])\n    >>> RGB_to_YcCbcCrc(RGB, out_legal=True, out_bits=10, out_int=True,\n    ...                 is_12_bits_system=False)\n    ... # doctest: +ELLIPSIS\n    array([422, 512, 512]...)\n    \"\"\"\n\n    R, G, B = tsplit(to_domain_1(RGB))\n    Y_min, Y_max, C_min, C_max = kwargs.get(\n        'out_range', YCbCr_ranges(out_bits, out_legal, out_int))\n\n    Yc = 0.2627 * R + 0.6780 * G + 0.0593 * B\n\n    with domain_range_scale('ignore'):\n        Yc = eotf_inverse_BT2020(Yc, is_12_bits_system=is_12_bits_system)\n        R = eotf_inverse_BT2020(R, is_12_bits_system=is_12_bits_system)\n        B = eotf_inverse_BT2020(B, is_12_bits_system=is_12_bits_system)\n\n    Cbc = np.where((B - Yc) <= 0, (B - Yc) / 1.9404, (B - Yc) / 1.5816)\n    Crc = np.where((R - Yc) <= 0, (R - Yc) / 1.7184, (R - Yc) / 0.9936)\n    Yc *= Y_max - Y_min\n    Yc += Y_min\n    Cbc *= C_max - C_min\n    Crc *= C_max - C_min\n    Cbc += (C_max + C_min) / 2\n    Crc += (C_max + C_min) / 2\n\n    YcCbcCrc = tstack([Yc, Cbc, Crc])\n    YcCbcCrc = (np.round(YcCbcCrc).astype(DEFAULT_INT_DTYPE)\n                if out_int else from_range_1(YcCbcCrc))\n\n    return YcCbcCrc\n\n\ndef YcCbcCrc_to_RGB(YcCbcCrc,\n                    in_bits=10,\n                    in_legal=True,\n                    in_int=False,\n                    is_12_bits_system=False,\n                    **kwargs):\n    \"\"\"\n    Converts an array of *Yc'Cbc'Crc'* colour encoding values to the\n    corresponding *RGB* array of linear values.\n\n    Parameters\n    ----------\n    YcCbcCrc : array_like\n        Input *Yc'Cbc'Crc'* colour encoding array of linear float values.\n    in_bits : int, optional\n        Bit depth for integer input, or used in the calculation of the\n        denominator for legal range float values, i.e. 8-bit means the float\n        value for legal white is *235 / 255*. Default is *10*.\n    in_legal : bool, optional\n        Whether to treat the input values as legal range. Default is *False*.\n    in_int : bool, optional\n        Whether to treat the input values as ``in_bits`` integer code values.\n        Default is *False*.\n    is_12_bits_system : bool, optional\n        *Recommendation ITU-R BT.2020* EOTF (EOCF) adopts different parameters\n        for 10 and 12 bit systems. Default is *False*.\n\n    Other Parameters\n    ----------------\n    in_range : array_like, optional\n        Array overriding the computed range such as\n        *in_range = (Y_min, Y_max, C_min, C_max)*. If ``in_range`` is\n        undefined, *Y_min*, *Y_max*, *C_min* and *C_max* will be computed using\n        :func:`colour.models.rgb.ycbcr.YCbCr_ranges` definition.\n\n    Returns\n    -------\n    ndarray\n        *RGB* array of linear float values.\n\n    Notes\n    -----\n\n    +----------------+-----------------------+---------------+\n    | **Domain \\\\***  | **Scale - Reference** | **Scale - 1** |\n    +================+=======================+===============+\n    | ``YcCbcCrc``   | [0, 1]                | [0, 1]        |\n    +----------------+-----------------------+---------------+\n\n    +----------------+-----------------------+---------------+\n    | **Range \\\\***   | **Scale - Reference** | **Scale - 1** |\n    +================+=======================+===============+\n    | ``RGB``        | [0, 1]                | [0, 1]        |\n    +----------------+-----------------------+---------------+\n\n    \\\\* This definition has input and output integer switches, thus the\n    domain-range scale information is only given for the floating point mode.\n\n    Warnings\n    --------\n    This definition is specifically for usage with\n    *Recommendation ITU-R BT.2020* when adopting the constant luminance\n    implementation.\n\n    References\n    ----------\n    :cite:`InternationalTelecommunicationUnion2015h`,\n    :cite:`Wikipedia2004d`\n\n    Examples\n    --------\n    >>> YcCbcCrc = np.array([1689, 2048, 2048])\n    >>> YcCbcCrc_to_RGB(YcCbcCrc, in_legal=True, in_bits=12, in_int=True,\n    ...                 is_12_bits_system=True)\n    ... # doctest: +ELLIPSIS\n    array([ 0.1800903...,  0.1800903...,  0.1800903...])\n    \"\"\"\n\n    if in_int:\n        YcCbcCrc = as_float_array(YcCbcCrc)\n    else:\n        YcCbcCrc = to_domain_1(YcCbcCrc)\n\n    Yc, Cbc, Crc = tsplit(YcCbcCrc.astype(DEFAULT_FLOAT_DTYPE))\n    Y_min, Y_max, C_min, C_max = kwargs.get(\n        'in_range', YCbCr_ranges(in_bits, in_legal, in_int))\n\n    Yc -= Y_min\n    Cbc -= (C_max + C_min) / 2\n    Crc -= (C_max + C_min) / 2\n    Yc *= 1 / (Y_max - Y_min)\n    Cbc *= 1 / (C_max - C_min)\n    Crc *= 1 / (C_max - C_min)\n    B = np.where(Cbc <= 0, Cbc * 1.9404 + Yc, Cbc * 1.5816 + Yc)\n    R = np.where(Crc <= 0, Crc * 1.7184 + Yc, Crc * 0.9936 + Yc)\n\n    with domain_range_scale('ignore'):\n        Yc = eotf_BT2020(Yc, is_12_bits_system=is_12_bits_system)\n        B = eotf_BT2020(B, is_12_bits_system=is_12_bits_system)\n        R = eotf_BT2020(R, is_12_bits_system=is_12_bits_system)\n\n    G = (Yc - 0.0593 * B - 0.2627 * R) / 0.6780\n\n    RGB = tstack([R, G, B])\n\n    return from_range_1(RGB)\n", "meta": {"hexsha": "b9d26d97ecb53d17c9e1170b38051bb4d037d96c", "size": 24372, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/models/rgb/ycbcr.py", "max_stars_repo_name": "wenh06/colour", "max_stars_repo_head_hexsha": "445fdad2711ae39c95b4375166905568d24a95f4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-09T01:53:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T01:53:40.000Z", "max_issues_repo_path": "colour/models/rgb/ycbcr.py", "max_issues_repo_name": "wenh06/colour", "max_issues_repo_head_hexsha": "445fdad2711ae39c95b4375166905568d24a95f4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/models/rgb/ycbcr.py", "max_forks_repo_name": "wenh06/colour", "max_forks_repo_head_hexsha": "445fdad2711ae39c95b4375166905568d24a95f4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8157099698, "max_line_length": 79, "alphanum_fraction": 0.5724602002, "include": true, "reason": "import numpy", "num_tokens": 6952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096344, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.17612674465785047}}
{"text": "#!/usr/bin/python\n\n\"\"\"\nspatial weights module for Space-Time Analysis of Regional Systems\n----------------------------------------------------------------------\nAUTHOR(S):  Sergio J. Rey sjrey@users.sourceforge.net\n----------------------------------------------------------------------\n\n\nOVERVIEW:\n\nThis module implements spatial weights classes for STARS.\n\nXXX PySAL \n\n\"\"\"\n\nimport time\nfrom shapereader import *\nimport numpy.oldnumeric as Numeric\nimport numpy.oldnumeric.linear_algebra as LinearAlgebra\n\nimport Gis # for centroids on disconnected island polygons\n\n# delta to get buckets right\nDELTA = 0.000001\n# constants for weights types\nWT_UNKNOWN = 0\nWT_ROOK = 1\nWT_QUEEN = 2\n# constants for bucket sizes\nBUCK_SM = 8\nBUCK_LG = 20\nSHP_SMALL = 1000\n# constant for spatial weights size\nWT_SMALL = 1000\nclass spweight:\n    \"\"\"\n    spweight data structure: list of lists\n    [ metadata ], [key:obs dictionary] [obs:key dictionary] \n    [number of neighbors] [neighbor id lists ] [neighbor weights lists]\n    [characteristics ] [traces ] [eigvalues]\n    need a dbf reader to use a \"key\" variable instead of sequence number\n    sequence number is fine as long as \"pure\" shape files since the matching order\n    is part of the ESRI shape file format\n    when called without filename, initialize only, useful for grid cases\n    \"\"\"\n    \n    \n    def __init__(self,filename=\"\",wtType=WT_ROOK):\n    # initialization here: check input file type and\n    # call appropriate reader\n        self.meta = []\n        self.keyobs = {}\n        self.obskey = {}\n        self.numneigh = []       # number of neighbors\n        self.neighbors = []      # neighbor ids\n        self.weights  = []\n        self.characteristics = []\n        self.traces = []\n        self.eigvalues = []\n        if filename:\n            # only shape input implemented so far\n            self.shp2wt(filename,wtType)\n        else:   # must create shapefile from scratch grid only\n            pass\n        self.numneighbrs()    # computes the number of neighbors\n    \n################### constructors    \n    \n    # read gal file and convert to wt data structure\n    def wtfromgal(self):\n        pass\n        \n    # read gwt file and convert to wt data structure\n    def wtfromgwt(self):\n        pass\n#------------------        \n    # read shp file and construct rook or queen contiguity\n    def shp2wt(self,filename,wtType):\n        raw_shape = shapefile(filename)\n        if raw_shape.shptype == SHP_POINT:\n            return       # need handler \n        shapepoints = raw_shape.shplist    # list of lists\n        shapebox = raw_shape.shpbox      # bounding box\n        self.shapepoints = shapepoints\n        \n        numPoly = len(shapepoints)\n        # bucket size\n        if (numPoly < SHP_SMALL):\n            bucketMin = numPoly / BUCK_SM + 2\n        else:\n            bucketMin = numPoly / BUCK_LG + 2\n        # bucket length\n        lengthX = ((shapebox[2]+DELTA) - shapebox[0]) / bucketMin\n        lengthY = ((shapebox[3]+DELTA) - shapebox[1]) / bucketMin\n        \n        # initialize buckets\n        bucketX = [ [] for i in range(bucketMin) ]\n        bucketY = [ [] for i in range(bucketMin) ]\n        polyXbucket = [ [] for i in range(numPoly) ]  # list with buckets for X\n        polyYbucket = [ [] for i in range(numPoly) ]  # list with buckets for Y\n        self.neighbors = [ [] for i in range(numPoly) ]      # list of lists for neighbors\n                \n        minbox = shapebox[:2] * 2  # minX,minY,minX,minY\n        blen = [lengthX,lengthY] * 2  # lenx,leny,lenx,leny\n        \n        for i in range(numPoly):\n            pb = [int((shapepoints[i][0][j] - minbox[j])/blen[j]) for j in range(4)]\n            for j in range(pb[0],pb[2]+1):\n                polyXbucket[i].append(j)\n                bucketX[j].append(i)\n            for j in range(pb[1],pb[3]+1):\n                polyYbucket[i].append(j)\n                bucketY[j].append(i)\n            \n        #create candidate neighbors from buckets\n        for i in range(numPoly):\n            buckX = []\n            for j in range(0,len(polyXbucket[i])):\n                buckX += bucketX[polyXbucket[i][j]]\n            buckY = []\n            for j in range(0,len(polyYbucket[i])):\n                buckY += bucketY[polyYbucket[i][j]]\n            buckX = dict( [ (j,j) for j in buckX ]).keys()\n            buckY = dict( [ (j,j) for j in buckY ]).keys()\n            buckX.sort()\n            buckY.sort()\n            \n            nb = []\n            if len(buckX) < len(buckY):\n                k = buckX.index(i) + 1\n                nb = [ buckX[jj] for jj in range(k,len(buckX)) \n                        if (buckX[jj] in buckY) and (shapepoints[i][0].bbcommon(shapepoints[buckX[jj]][0]) ) ]\n            else:\n                k = buckY.index(i) + 1\n                nb = [ buckY[jj] for jj in range(k,len(buckY)) if  (buckY[jj] in buckX)\n                        and (shapepoints[i][0].bbcommon(shapepoints[buckY[jj]][0])) ]\n            for ii in range(0,len(nb)):\n                ch=0\n                jj=0\n                kk=len(shapepoints[i][2]) - 1\n                nbi = nb[ii]\n\n                while not ch and jj < kk:\n                    if wtType == WT_ROOK:\n                        ch = (shapepoints[i][2][jj] in shapepoints[nbi][2]) and (shapepoints[i][2][jj+1] in shapepoints[nbi][2])\n                    else:   # queen\n                        ch = shapepoints[i][2][jj] in shapepoints[nbi][2]\n                    jj += 1\n                if ch:\n                    self.neighbors[i].append(nbi)\n                    self.neighbors[nbi].append(i)\n                #print 'origin', i+1\n                #print 'neighbors: ', [ nid+1 for nid in self.neighbors[i] ]\n\n\n#----------------\n    # construct rook for grid\n    def grid2rk(self,nrows,ncols):\n        m = nrows * ncols\n        self.neighbors= [ [] for i in range(m) ]  # initialize\n        for i in range(nrows):\n            for j in range(ncols):\n                k = i * ncols + j\n                # to left\n                if j:\n                    self.neighbors[k].append(k-1)\n                # to right\n                if j < ncols - 1:\n                    self.neighbors[k].append(k+1)\n                # above\n                if i:\n                    self.neighbors[k].append(k - ncols)\n                # below\n                if i < nrows - 1:\n                    self.neighbors[k].append(k + ncols)\n                self.neighbors[k].sort()\n        self.numneighbrs()\n#-----------------                \n    # construct rook - torus for grid\n    def grid2rktor(self,nrows,ncols):\n        m = nrows * ncols\n        self.neighbors= [ [] for i in range(m) ]  # initialize\n        for i in range(nrows):\n            for j in range(ncols):\n                k = i * ncols + j\n                # to left\n                if j:\n                    self.neighbors[k].append(k-1)\n                else:\n                    self.neighbors[k].append(k + ncols -1)\n                # to right\n                if j < ncols - 1:\n                    self.neighbors[k].append(k+1)\n                else:\n                    self.neighbors[k].append(k - ncols + 1)\n                # above\n                if i:\n                    self.neighbors[k].append(k - ncols)\n                else:\n                    self.neighbors[k].append((nrows-1)*ncols + j)\n                # below\n                if i < nrows - 1:\n                    self.neighbors[k].append(k + ncols)\n                else:\n                    self.neighbors[k].append(j)\n                self.neighbors[k].sort()\n        self.numneighbrs()\n        \n######################### read/write methods        \n    # read pickled weight file ?\n    def readwt(self):\n        pass\n        \n    # write wt to gal file\n    def wt2gal(self):\n        pass\n        \n    # write wt to gwt file\n    def wt2gwt(self):\n        pass\n        \n    # pickle wt file\n    def wt2pickle(self):\n        pass\n        \n    # conversion from wt data structure to numpy weight matrix\n    # gal form only so far\n    def wt2mat(self):\n        n = len(self.neighbors)\n        w = Numeric.zeros((n,n),Numeric.Float)\n        for i in range(n):\n            if self.numneigh[i]:\n                kk = 1.0 / self.numneigh[i]\n                for j in self.neighbors[i]:\n                    w[i][j] = kk\n        return w\n        \n    # write numpy to gal file\n    def mat2gal(self):\n        pass\n        \n    # write numpty to gwt file\n    def mat2gwt(self):\n        pass\n        \n###################### weights computations\n    # number of neighbors\n    def numneighbrs(self):\n        self.numneigh = []   # always reinitialize\n        for i in range(len(self.neighbors)):\n            self.numneigh.append(len(self.neighbors[i]))\n        \n    # weights characteristics\n    def wtchars(self):\n        pass\n        \n    # weights traces\n    def wttraces(self):\n        pass\n        \n    # higher order weights\n    def wt2higher(self):\n        pass\n        \n        \n    # weights eigenvalues\n    def wteigen(self):\n        pass\n        \n\n\n    # neighbor histogram\n    def histogram(self):\n        maxn = max(self.numneigh)\n        counts = [self.numneigh.count(i) for i in range(maxn+1) ]\n        return counts\n\n\n    def islands(self):\n        \"\"\"returns ids of any island observations.\"\"\"\n        ij = zip(range(len(self.numneigh)),self.numneigh)\n        return [ i for i,j in ij if j==0 ]\n\n    def findNearestNeighbors(self, ids):\n        \"\"\"find nearest neighbors based on bounding box centroid distances.\n\n        ids: list of shape ids to find neighbors for.\n        \"\"\"\n        #bb centroids\n        cent = [ ((s[0][0]+s[0][2])/2.,(s[0][1]+s[0][3])/2.) for s in\n                self.shapepoints]\n        self.centroids = cent\n        c=cent\n        neighbors = []\n        rn=range(len(self.shapepoints))\n        for id in ids:\n            x0,y0=cent[id]\n            di = [ (x0-c[j][0])*(x0-c[j][0])+(y0-c[j][1])*(y0-c[j][1]) \n                  for j in rn ]\n            maxd=max(di)\n            di[id]=maxd\n            nid = di.index(min(di))\n            neighbors.append(nid)\n        return neighbors\n\n    def findIslandNeighbors(self):\n        islands = self.islands()\n        return zip(islands,self.findNearestNeighbors(islands))\n\n    def fixIslands(self):\n        \"\"\"attaches island shapes to nearest neighbor and reconstructs gal\n        information accordingly\"\"\"\n\n        islandInfo = self.findIslandNeighbors()\n        addedJoins = []\n        if islandInfo:\n            for i,j in islandInfo:\n                ineigh = self.neighbors[i]\n                jneigh = self.neighbors[j]\n                if j not in ineigh:\n                    ineigh.append(j)\n                    ineigh.sort()\n                    self.numneigh[i] = len(ineigh)\n                    self.neighbors[i] = ineigh\n                    addedJoins.append((i,j))\n                if i not in jneigh:\n                    jneigh.append(i)\n                    jneigh.sort()\n                    self.numneigh[j] = len(jneigh)\n                    self.neighbors[j] = jneigh\n                    addedJoins.append((j,i))\n        self.islandInfo = islandInfo\n        self.addedJoins = addedJoins\n\n    # distance weights\n\n    \n    # spatial lag for single variable\n    # checks what is passed and initializes same\n    # assumes gal form only so far\n    def splag(self,x):\n        n = len(x)\n        if type(x) == list:\n            wx = [ 0 for i in range(n) ]\n        elif type(x) == type(Numeric.array(1)):\n            wx = Numeric.zeros(n,Numeric.Float)\n        for i in range(n):\n            if self.numneigh[i]:\n                for j in self.neighbors[i]:\n                    wx[i] += x[j]\n                wx[i] /= self.numneigh[i]\n        return wx\n        \n    \n    # spatial filter\n    \n    # spatial AR transformation\n    # force = 0 default let size determine\n    # force = 1 always iterative\n    # precis = DELTA precision criterion same as for buckets\n    # precis set precision criterion\n    def sartran(self,rho,x,force=0,precis=DELTA):\n        n = len(x)\n        listflag = 0\n        if type(x) == list:\n            x = Numeric.array(x,Numeric.Float)\n            listflag = 1\n        sarx = Numeric.zeros(n,Numeric.Float)\n        if n > WT_SMALL or force:\n            sarx = x\n            wx = self.splag(x) * rho\n            sarx += wx\n            while max(wx) > precis:\n                wx = self.splag(wx) * rho\n                sarx += wx\n        else:   # small weights full matrix inverse\n            w = self.wt2mat()\n            w *= - rho\n            w += Numeric.identity(n)\n            wx = LinearAlgebra.inverse(w)\n            sarx = Numeric.matrixmultiply(wx,x)\n        if listflag:\n            return sarx.tolist()\n        else:\n            return sarx\n    \n    # editing weights\n    \n    # visualizing the  structure of weights\n    \n    # weights computations: addition, subtraction, multiplication\n    \n    \n# alternatively use subclasses with special constructors\n\n###################\n###################\nif __name__ == \"__main__\":\n    fname = raw_input(\"Enter the shape file name (include .shp): \")\n    t0 = time.time()\n    w1=spweight(fname,1)\n    t1 = time.time()\n    print \"-------------------------------------\"\n    print \"using \"+str(fname)\n    print \"time elapsed for rook: \" + str(t1-t0)\n    #t2 = time.time()\n    #w2 = spweight(fname,2)\n    #t3 = time.time()\n    #print \"time elapsed for queen: \" + str(t3-t2)\n    #print \"-------- spatial transformation ------------\"\n    #n = raw_input(\"Enter the dimension of the grid: \")\n    #n = int(n)\n    #n2 = n*n\n    #rho = raw_input(\"Enter the value for rho: \")\n    #rho = float(rho)\n    #ff = raw_input(\"Force iterative procedure 1 yes 0 no: \")\n    #ff = int(ff)\n    #x = range(n2)\n    #xx = Numeric.array(x,Numeric.Float)\n    #w3 = spweight()\n    #w3.grid2rk(n,n)\n    #t4 = time.time()\n    #wx = w3.sartran(rho,xx,force=ff,precis=0.0000001)\n    #t5 = time.time()\n    #print \"time elapsed for sartran \" + str(n) + \"  by \" + str(n) + \" : \" + str(t5-t4)\n\n", "meta": {"hexsha": "45c8d6a42c5a4d2c6f3088acf3dfcbea5fcaeef1", "size": 13998, "ext": "py", "lang": "Python", "max_stars_repo_path": "stars/weight.py", "max_stars_repo_name": "lhcramer-GISforks/stars", "max_stars_repo_head_hexsha": "3c7532a6ea9cd0af7c21f009d603d80cbd69278a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2015-06-15T14:25:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-01T22:57:48.000Z", "max_issues_repo_path": "stars/weight.py", "max_issues_repo_name": "lhcramer-GISforks/stars", "max_issues_repo_head_hexsha": "3c7532a6ea9cd0af7c21f009d603d80cbd69278a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2015-08-12T23:59:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-13T00:33:37.000Z", "max_forks_repo_path": "stars/weight.py", "max_forks_repo_name": "lhcramer-GISforks/stars", "max_forks_repo_head_hexsha": "3c7532a6ea9cd0af7c21f009d603d80cbd69278a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2016-02-08T05:03:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-17T21:07:00.000Z", "avg_line_length": 32.6293706294, "max_line_length": 128, "alphanum_fraction": 0.5050721532, "include": true, "reason": "import numpy", "num_tokens": 3416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.17612674302886622}}
{"text": "import os\n\nimport numpy as np\nfrom scipy.constants import c as SPEED_OF_LIGHT\nfrom simphony.elements import Model\nfrom simphony.tools import freq2wl, interpolate, wl2freq\n\n\nclass ebeam_bdc_te1550(Model):\n    \"\"\"\n    A bidirectional coupler optimized for TE polarized light at 1550 nanometers.\n\n    The bidirectional coupler has 4 ports, labeled as pictured. Its efficiently\n    splits light that is input from one port into the two outputs on the opposite\n    side (with a corresponding pi/2 phase shift). Additionally, it efficiently\n    interferes lights from two adjacent inputs, efficiently splitting the\n    interfered signal between the two ports on the opposing side.\n\n    .. image:: /user/libraries/images/ebeam_bdc_te1550.png\n        :alt: ebeam_bdc_te1550.png\n    \"\"\"\n\n    pins = (\"n1\", \"n2\", \"n3\", \"n4\")  #: The default pin names of the device\n    loaded = np.load(\n        os.path.join(\n            os.path.dirname(os.path.realpath(__file__)),\n            \"sparams\",\n            \"ebeam_bdc_te1550.npz\",\n        )\n    )\n    s_params = (loaded[\"f\"], loaded[\"s\"])\n    freq_range = (\n        s_params[0][0],\n        s_params[0][-1],\n    )  #: The valid frequency range for this model.\n\n    def s_parameters(self, freq):\n        return interpolate(freq, self.s_params[0], self.s_params[1])\n\n\nclass ebeam_dc_halfring_te1550(Model):\n    pins = (\n        \"n1\",\n        \"n2\",\n    )  #: The default pin names of the device\n    loaded = np.load(\n        os.path.join(\n            os.path.dirname(os.path.realpath(__file__)),\n            \"sparams\",\n            \"ebeam_dc_halfring_te1550.npz\",\n        )\n    )\n    s_params = (loaded[\"f\"], loaded[\"s\"])\n    freq_range = (\n        s_params[0][0],\n        s_params[0][-1],\n    )  #: The valid frequency range for this model.\n\n    def s_parameters(self, freq):\n        return interpolate(freq, self.s_params[0], self.s_params[1])\n\n\nclass ebeam_gc_te1550(Model):\n    \"\"\"\n    A grating coupler optimized for TE polarized light at 1550 nanometers.\n\n    The grating coupler efficiently couples light from a fiber array positioned\n    above the chip into the circuit. For the TE mode, the angle is -25 degrees\n    [needs citation].\n\n    .. image:: /user/libraries/images/ebeam_gc_te1550.png\n        :alt: ebeam_bdc_te1550.png\n    \"\"\"\n\n    pins = (\n        \"n1\",\n        \"n2\",\n    )  #: The default pin names of the device\n    loaded = np.load(\n        os.path.join(\n            os.path.dirname(os.path.realpath(__file__)),\n            \"sparams\",\n            \"ebeam_gc_te1550.npz\",\n        )\n    )\n    s_params = (loaded[\"f\"], loaded[\"s\"])\n    freq_range = (\n        s_params[0][0],\n        s_params[0][-1],\n    )  #: The valid frequency range for this model.\n\n    def s_parameters(self, freq):\n        return interpolate(freq, self.s_params[0], self.s_params[1])\n\n\nclass ebeam_terminator_te1550(Model):\n    \"\"\"\n    A terminator component that dissipates light into free space optimized for\n    TE polarized light at 1550 nanometers.\n\n    The terminator dissipates excess light into free space. If you have a path\n    where the light doesn't need to be measured but you don't want it reflecting\n    back into the circuit, you can use a terminator to release it from the circuit.\n\n    .. image:: /user/libraries/images/ebeam_terminator_te1550.png\n        :alt: ebeam_bdc_te1550.png\n    \"\"\"\n\n    pins = (\"n1\",)  #: The default pin names of the device\n    loaded = np.load(\n        os.path.join(\n            os.path.dirname(os.path.realpath(__file__)),\n            \"sparams\",\n            \"ebeam_terminator_te1550.npz\",\n        )\n    )\n    s_params = (loaded[\"f\"], loaded[\"s\"])\n    freq_range = (\n        s_params[0][0],\n        s_params[0][-1],\n    )  #: The valid frequency range for this model.\n\n    def s_parameters(self, freq):\n        return interpolate(freq, self.s_params[0], self.s_params[1])\n\n\nclass ebeam_wg_integral_1550(Model):\n    \"\"\"\n    Model for an waveguide optimized for TE polarized light at 1550 nanometers.\n\n    A waveguide easily connects other optical components within a circuit.\n\n    .. image:: /user/libraries/images/ebeam_wg_integral_1550.png\n        :alt: ebeam_bdc_te1550.png\n\n    Parameters\n    ----------\n    length : float\n        Waveguide length in meters.\n    lam0 : float, optional\n        Central wavelength for calculation in meters (default 1.55 microns).\n    ne : float, optional\n        Effective index (default 2.44553).\n    ng : float, optional\n        Group velocity (default 4.19088).\n    nd : float, optional\n        Group dispersion (default 3.54275e-04).\n    sigma_ne : float, optional\n        Standard deviation of the effective index (default 0.05).\n    sigma_ng : float, optional\n        Standard deviation of the group velocity (default 0.05).\n    sigma_nd : float, optional\n        Standard deviation of the group dispersion (default 0.0001).\n\n    Notes\n    -----\n    The ``sigma_`` values in the parameters are used for monte carlo simulations.\n    \"\"\"\n\n    pins = (\n        \"n1\",\n        \"n2\",\n    )  #: The default pin names of the device\n    freq_range = (\n        187370000000000.0,\n        199862000000000.0,\n    )  #: The valid frequency range for this model.\n\n    def __init__(\n        self,\n        length,\n        lam0=1.55e-06,\n        ne=2.44553,\n        ng=4.19088,\n        nd=0.000354275,\n        sigma_ne=0.05,\n        sigma_ng=0.05,\n        sigma_nd=0.0001,\n    ):\n        self.length = length\n        self.lam0 = lam0\n        self.ne = ne\n        self.ng = ng\n        self.nd = nd\n        self.sigma_ne = sigma_ne\n        self.sigma_ng = sigma_ng\n        self.sigma_nd = sigma_nd\n        self.regenerate_monte_carlo_parameters()\n\n    def s_parameters(self, freq):\n        \"\"\"Get the s-parameters of a waveguide.\n\n        Parameters\n        ----------\n        start : float\n            The starting frequency to obtain s-parameters for (in Hz).\n        stop : float\n            The ending frequency to obtain s-parameters for (in Hz).\n        num : int\n            The number of points to use between start_freq and stop_freq.\n\n        Returns\n        -------\n        (frequency, s) : tuple\n            Returns a tuple containing the frequency array, ``frequency``,\n            corresponding to the calculated s-parameter matrix, ``s``.\n        \"\"\"\n        return self.cacl_s_params(\n            freq, self.length, self.lam0, self.ne, self.ng, self.nd\n        )\n\n    def monte_carlo_s_parameters(self, freq):\n        \"\"\"\n        Returns a monte carlo (randomized) set of s-parameters.\n\n        In this implementation of the monte carlo routine, random values are\n        generated for ne, ng, and nd for each run through of the monte carlo\n        simulation. This means that all waveguide elements throughout a single\n        circuit will have the same (random) ne, ng, and nd values. Hence, there\n        is correlated randomness in the monte carlo parameters but they are\n        consistent within a single circuit.\n        \"\"\"\n        return self.cacl_s_params(\n            freq, self.length, self.lam0, self.rand_ne, self.rand_ng, self.rand_nd\n        )\n\n    def regenerate_monte_carlo_parameters(self):\n        self.rand_ne = np.random.normal(self.ne, self.sigma_ne)\n        self.rand_ng = np.random.normal(self.ng, self.sigma_ng)\n        self.rand_nd = np.random.normal(self.nd, self.sigma_nd)\n\n    @staticmethod\n    def cacl_s_params(frequency, length, lam0, ne, ng, nd):\n        # Initialize array to hold s-params\n        s = np.zeros((len(frequency), 2, 2), dtype=complex)\n\n        # Loss calculation\n        TE_loss = 700  # dB/m for width 500nm\n        alpha = TE_loss / (20 * np.log10(np.exp(1)))\n\n        w = np.asarray(frequency) * 2 * np.pi  # get angular frequency from frequency\n        w0 = (2 * np.pi * SPEED_OF_LIGHT) / lam0  # center frequency (angular)\n\n        # calculation of K\n        K = (\n            2 * np.pi * ne / lam0\n            + (ng / SPEED_OF_LIGHT) * (w - w0)\n            - (nd * lam0 ** 2 / (4 * np.pi * SPEED_OF_LIGHT)) * ((w - w0) ** 2)\n        )\n\n        for x in range(0, len(frequency)):  # build s-matrix from K and waveguide length\n            s[x, 0, 1] = s[x, 1, 0] = np.exp(-alpha * length + (K[x] * length * 1j))\n\n        return s\n\n\nclass ebeam_y_1550(Model):\n    \"\"\"\n    The y-branch efficiently splits the input between the two outputs.\n\n    .. image:: /user/libraries/images/ebeam_y_1550.png\n        :alt: ebeam_bdc_te1550.png\n    \"\"\"\n\n    pins = (\"n1\", \"n2\", \"n3\")  #: The default pin names of the device\n    loaded = np.load(\n        os.path.join(\n            os.path.dirname(os.path.realpath(__file__)), \"sparams\", \"ebeam_y_1550.npz\"\n        )\n    )\n    s_params = (loaded[\"f\"], loaded[\"s\"])\n    freq_range = (\n        s_params[0][0],\n        s_params[0][-1],\n    )  #: The valid frequency range for this model.\n\n    def s_parameters(self, freq):\n        return interpolate(freq, self.s_params[0], self.s_params[1])\n\n\nclass ebeam_dc_te1550(Model):\n    \"\"\"\n    A directional coupler optimized for TE polarized light at 1550 nanometers.\n\n    The directional coupler has 4 ports, labeled as pictured. Its efficiently\n    splits light that is input from one port into the two outputs on the opposite\n    side (with a corresponding pi/2 phase shift). Additionally, it efficiently\n    interferes lights from two adjacent inputs, efficiently splitting the\n    interfered signal between the two ports on the opposing side.\n\n    .. image:: /user/libraries/images/ebeam_bdc_te1550.png\n        :alt: ebeam_bdc_te1550.png\n    \"\"\"\n\n    pins = (\"n1\", \"n2\", \"n3\", \"n4\")\n    loaded = np.load(\n        os.path.join(\n            os.path.dirname(os.path.realpath(__file__)),\n            \"sparams\",\n            \"ebeam_dc_te1550.npz\",\n        )\n    )\n    s_params = (loaded[\"f\"], loaded[\"s\"])\n    freq_range = (\n        s_params[0][0],\n        s_params[0][-1],\n    )  #: The valid frequency range for this model.\n\n    def s_parameters(self, freq):\n        return interpolate(freq, self.s_params[0], self.s_params[1])\n\n\nif __name__ == \"__main__\":\n    import matplotlib.pyplot as plt\n\n    bdc = ebeam_bdc_te1550()\n    wav = np.linspace(1520, 1570, 1024) * 1e-9\n    f = 3e8 / wav\n    s = bdc.s_parameters(freq=f)\n    plt.plot(wav, np.abs(s[:, 1] ** 2))\n\n    plt.show()\n", "meta": {"hexsha": "9b0e806b05c26292a6311a165f88d941183e29b0", "size": 10208, "ext": "py", "lang": "Python", "max_stars_repo_path": "simphony/library/ebeam/__init__.py", "max_stars_repo_name": "joamatab/simphony", "max_stars_repo_head_hexsha": "bfe20c656d19aa18d79b4c8dbccdc0b70daebe80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-07T17:16:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-07T17:16:18.000Z", "max_issues_repo_path": "simphony/library/ebeam/__init__.py", "max_issues_repo_name": "joamatab/simphony", "max_issues_repo_head_hexsha": "bfe20c656d19aa18d79b4c8dbccdc0b70daebe80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simphony/library/ebeam/__init__.py", "max_forks_repo_name": "joamatab/simphony", "max_forks_repo_head_hexsha": "bfe20c656d19aa18d79b4c8dbccdc0b70daebe80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-11-24T22:49:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T13:17:35.000Z", "avg_line_length": 31.6037151703, "max_line_length": 88, "alphanum_fraction": 0.6147139498, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.34158250614097546, "lm_q1q2_score": 0.17612674302886622}}
{"text": "\"\"\"**This module simulates Urban Energy Requirements**.\n\nOutputs are stored stored as csv.\n\"\"\"\nimport pandas as pd\nimport geopandas as gpd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom pathlib import Path\nimport pickle\nimport logging\n\nlogging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s',\n                    filename=\"../code/log/demand_supply.log\",\n                    level=logging.DEBUG)\n\n\nclass UrbanEnergyRequirement:\n    \"\"\"Simulate urban energy requirements.\n\n    :returns: csv files of simulated load profile and PV requirements\n    \"\"\"\n\n    def __init__(self):\n        \"\"\"Init function.\"\"\"\n        self.input_destination_1 = \"../data/01_raw_input_data/\"\n        self.input_destination_2 = \"../data/02_urban_output_data/\"\n        self.output_destination = \"../data/03_urban_energy_requirements/\"\n        self.output_destination2 = \"../data/04_Visualisation/\"\n        self.norm = 1000  # standard unit converter\n        if Path(self.output_destination).exists():\n            pass\n        else:\n            os.mkdir(self.output_destination)\n\n    def feedin_data(self):\n        \"\"\"Get wind and pv feed in data.\"\"\"\n        with open(os.path.join(self.input_destination_1, 'fp'), 'rb') as fp:\n            feedin_parameter = pickle.load(fp)\n        self.peak_power = feedin_parameter[0]  # in watts\n        self.module_area = feedin_parameter[1]\n        self.norminal_power_wind = feedin_parameter[2]  # in watts\n        pv_feedin = pd.read_csv(os.path.join(\n            self.input_destination_1, 'pv_power.csv'))\n        wind_feedin = pd.read_csv(os.path.join(\n            self.input_destination_1, 'wind_power.csv'))\n        pv_feedin = pv_feedin.reindex()\n        self.time_stamp = pv_feedin[['time']]\n        self.pv_data = pv_feedin[\"pv\"]\n        self.wind_power_data = wind_feedin[\"wind\"]\n        logging.info(\"Feedin data and powersystem parameter imported.\")\n        print('*** Feedin data imported ***')\n\n    def standard_load_profiles(self):\n        \"\"\"Read Standard Load Profiles.\"\"\"\n        self.dfs = pd.read_csv(os.path.join(\n            self.input_destination_1, 'SLP.csv'))\n        # get different scenario load profiles in kWh\n        self.AL, self.CL = self.dfs['L0']/self.norm, self.dfs['G0']/self.norm\n        self.EL, self.IL = self.dfs['G1']/self.norm, self.dfs['G3']/self.norm\n        self.RL, self.SL = self.dfs['H0']/self.norm, self.dfs['SB2']/self.norm\n        logging.info(\"Get load profile for different scenarios.\")\n        print('Info: Load profile data imported')\n\n    def electricity_usage_index(self):\n        \"\"\"Calculate Electricity Usage Index for different building type kWh/m2 per year.\"\"\"\n        self.x_a, self.x_c = 120/self.norm, 201/self.norm\n        self.x_e, self.x_i = 142/self.norm, 645/self.norm\n        self.x_r, self.x_sl = 146/self.norm, 4/self.norm\n        logging.info(\n            \"Calculate electricty usage index for urban infrastructure.\")\n        print('Info: Electricity usage index calculated')\n\n    def roofTop_pv_capacity(self):\n        \"\"\"Calculate maximum installed pv capacity as a function of rooftop area.\"\"\"\n        dfa = gpd.read_file(os.path.join(\n            self.input_destination_2, 'agricultural/agricultural.shp'))\n        dfc = gpd.read_file(os.path.join(\n            self.input_destination_2, 'commercial/commercial.shp'))\n        dfe = gpd.read_file(os.path.join(\n            self.input_destination_2, 'educational/educational.shp'))\n        dfi = gpd.read_file(os.path.join(\n            self.input_destination_2, 'industrial/industrial.shp'))\n        dfr = gpd.read_file(os.path.join(\n            self.input_destination_2, 'residential/residential.shp'))\n        self.area_a, self.area_c = dfa['area'].sum(), dfc['area'].sum()\n        self.area_e, self.area_i = dfe['area'].sum(), dfi['area'].sum()\n        self.area_r = dfr['area'].sum()\n        self.area_a_pv, self.area_c_pv = self.area_a*0.267, self.area_c*0.267\n        self.area_e_pv, self.area_i_pv = self.area_e*0.267, self.area_i*0.267\n        self.area_r_pv = self.area_r*0.578\n        # calculate aggregate peak power at rooftop\n        total_roof_to_area = self.area_a_pv+self.area_c_pv + \\\n            self.area_e_pv+self.area_i_pv+self.area_r_pv\n        self.peak_power_agg = (\n            self.peak_power*(total_roof_to_area/self.module_area)) / self.norm  # KW\n        print('Info: Maximum installed pv capacity = {} KW'.format(\n            str(self.peak_power_agg)))\n        # KW TODO: proper calculate max. installed cpacity for wind\n        max_installed_wind_power = 305000\n        maximum_capacity = [max_installed_wind_power, self.peak_power_agg]\n        with open(os.path.join(self.output_destination, 'mc'), 'wb') as mc:\n            pickle.dump(maximum_capacity, mc)\n        logging.info(\"Calculate maximum installed PV capacity at roof top.\")\n\n    def agricultural_load(self):\n        \"\"\"Simulate Agricultural building type electricity demand and PV feedin supply.\"\"\"\n        load_a = self.time_stamp\n        load_a['Load[kWh]'] = self.AL*self.area_a*self.x_a\n        load_a['PV[kWh]'] = (self.pv_data*self.peak_power *\n                             (self.area_a_pv/self.module_area)) / self.norm  # kWh\n        load_a.to_csv(os.path.join(self.output_destination, 'a_load.csv'))\n        logging.info(\n            \"Calculate electricty demand and supply for agricultural buildings\")\n        print('Info: Agricultural building load and pv supply simulation.')\n\n    def commercial_energy_req(self):\n        \"\"\"Simulate Com.  building type electricity demand and PV feedin supply.\"\"\"\n        load_c = self.time_stamp\n        load_c['Load[kWh]'] = self.CL*self.area_c*self.x_c\n        load_c['PV[kWh]'] = (self.pv_data*self.peak_power *\n                             (self.area_c_pv/self.module_area))/self.norm\n        load_c.to_csv(os.path.join(self.output_destination, 'c_load.csv'))\n        logging.info(\n            \"Calculate electricty demand and supply for commercial buildings\")\n        print('Info: Commercial building load and pv supply siml.')\n\n    def eductaional_energy_req(self):\n        \"\"\"Simulate edu. quarter hourly Energy Requirments REs.\"\"\"\n        load_e = self.time_stamp\n        load_e['Load[kWh]'] = self.EL*self.area_e*self.x_e\n        load_e['PV[kWh]'] = (self.pv_data*self.peak_power *\n                             (self.area_e_pv/self.module_area))/self.norm\n        load_e.to_csv(os.path.join(self.output_destination, 'e_load.csv'))\n        logging.info(\n            \"Calculate electricty demand and supply for educational buildings\")\n        print('Info: Eductaional building load and pv supply siml.')\n\n    def industrial_energy_req(self):\n        \"\"\"Simulate Ind. quarter hourly Energy Requirments REs.\"\"\"\n        load_i = self.time_stamp\n        load_i['Load[kWh]'] = self.IL*self.area_i*self.x_i\n        load_i['PV[kWh]'] = (self.pv_data*self.peak_power *\n                             (self.area_i_pv/self.module_area))/self.norm\n        load_i.to_csv(os.path.join(self.output_destination, 'i_load.csv'))\n        logging.info(\n            \"Calculate electricty demand and supply for industrial buildings\")\n        print('Info: Industrial building load and pv supply siml.')\n\n    def residential_energy_req(self):\n        \"\"\"Simulate Res. quarter hourly Energy Requirments REs.\"\"\"\n        load_r = self.time_stamp\n        load_r['Load[kWh]'] = self.RL*self.area_r*self.x_r\n        load_r['PV[kWh]'] = (self.pv_data*self.peak_power *\n                             (self.area_r_pv/self.module_area))/self.norm\n        load_r.to_csv(os.path.join(self.output_destination, 'r_load.csv'))\n        logging.info(\n            \"Calculate electricty demand and supply for residential buildings\")\n        print('Info: Residential building load and pv supply siml.')\n\n    def highway_energy_req(self):\n        \"\"\"Simulate Urban Streetlightning. quarter hourly.\"\"\"\n        street_data = gpd.read_file(os.path.join(\n            self.input_destination_2, 'highway/highway.shp'))\n        area_sl = street_data['area'].sum()\n        self.no_building = len(street_data)\n        load_sl = self.time_stamp\n        load_sl['Load[kWh]'] = self.SL*area_sl*self.x_sl\n        load_sl.to_csv(os.path.join(self.output_destination, 'sl_load.csv'))\n        logging.info(\n            \"Calculate electricty demand for street lights\")\n        print('Info: Streetlightning load siml.')\n\n    def aggregate_demand_supply(self):\n        \"\"\"Aggrgate all simulated PV power generation.\"\"\"\n        print('Info: Aggregate simulated PV power generation and electricity demand.')\n\n        demand_supply_agri = pd.read_csv(\n            os.path.join(self.output_destination, 'a_load.csv'))\n        demand_supply_comm = pd.read_csv(\n            os.path.join(self.output_destination, 'c_load.csv'))\n        demand_supply_educ = pd.read_csv(\n            os.path.join(self.output_destination, 'e_load.csv'))\n        demand_supply_indu = pd.read_csv(\n            os.path.join(self.output_destination, 'i_load.csv'))\n        demand_supply_resi = pd.read_csv(\n            os.path.join(self.output_destination, 'r_load.csv'))\n        demand_street_light = pd.read_csv(\n            os.path.join(self.output_destination, 'sl_load.csv'))\n\n        # aggregate all pv supply for the different building types\n        agg_pv = (demand_supply_agri['PV[kWh]'] + demand_supply_comm['PV[kWh]'] +\n                  demand_supply_educ['PV[kWh]'] + demand_supply_indu['PV[kWh]'] +\n                  demand_supply_resi['PV[kWh]'])/self.norm  # to MWh\n        agg_pv = np.array(agg_pv)\n        agg_pv = pd.DataFrame(agg_pv, columns=[\"PV[MWh]\"])\n\n        # aggregate all electricity demand for the different building types (MWh)\n        agg_load = (demand_supply_agri['Load[kWh]'] + demand_supply_comm['Load[kWh]'] +\n                    demand_supply_educ['Load[kWh]'] + demand_supply_indu['Load[kWh]'] +\n                    demand_supply_resi['Load[kWh]'] + demand_street_light['Load[kWh]'])/self.norm\n\n        # prepare demand and supply data for optimization\n        agg_load = np.array(agg_load)\n        agg_load = pd.DataFrame(agg_load, columns=[\"Load[MWh]\"])\n        agg_load['PV[MWh]'] = agg_pv[\"PV[MWh]\"]\n        agg_load['demand_el'] = agg_load[\"Load[MWh]\"].values * \\\n            1000  # Kilo-watts hour\n        agg_load['wind'] = self.wind_power_data  # normalized wind feedin data\n        agg_load['pv'] = self.pv_data  # normalized pv feedin data\n        agg_load['time'] = self.time_stamp['time']\n        agg_load = agg_load.set_index('time')\n\n        agg_load.loc[:, [\"Load[MWh]\", 'PV[MWh]']].to_csv(os.path.join(\n            self.output_destination, 'aggregated-demand-supply.csv'))\n        agg_load.loc[:, [\"demand_el\", 'wind', 'pv']].to_csv(\n            os.path.join(self.output_destination, 'optimization-commodities.csv'))\n        logging.info(\n            \"Calculate aggregated electricty demand and supplies\")\n\n    def plot_quarter_load_energy(self):\n        \"\"\"Simulate quarter load and plot Urban Energy Requirments REs.\"\"\"\n        print('Info: Plot Urban Energy Requirments.')\n        fig_size = (14, 8)\n        sim_df = pd.read_csv(os.path.join(\n            self.output_destination, 'aggregated-demand-supply.csv'))\n        sim_df['PV[MWh]'].plot(style='r', figsize=fig_size, grid=True)\n        sim_df['Load[MWh]'].plot(style='g', figsize=fig_size, grid=True)\n        plt.xlabel('Time')\n        plt.ylabel('MW')\n        plt.title('Aggregated Energy Requirments in Oldenburg')\n        plt.legend(['Simulated PV', 'Simulated load'], loc='upper left')\n        plt.savefig(self.output_destination2+\"Energy_Requirments.png\", dpi=300)\n        plt.show()\n        logging.info(\"Generate demand and supply plot\")\n\n    def flexigis_urban_simulation(self):\n        \"\"\"Simulate urban Energy requirements for target location.\"\"\"\n        self.feedin_data()\n        self.standard_load_profiles()\n        self.electricity_usage_index()\n        self.roofTop_pv_capacity()\n        self.agricultural_load()\n        self.commercial_energy_req()\n        self.eductaional_energy_req()\n        self.industrial_energy_req()\n        self.residential_energy_req()\n        self.highway_energy_req()\n        self.aggregate_demand_supply()\n        self.plot_quarter_load_energy()\n        logging.info(\"Electricity Demand and Supply simulation Done!\")\n\n\nif __name__ == \"__main__\":\n    flexigis_energy = UrbanEnergyRequirement()\n    flexigis_energy.flexigis_urban_simulation()\n", "meta": {"hexsha": "063063fb9fa200890b6a9acee6564857e99b8169", "size": 12421, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/flexigis_simulate.py", "max_stars_repo_name": "FlexiGIS/FlexiGIS", "max_stars_repo_head_hexsha": "fc0bef64fa229141bb195f3ea2d208f4c80e2aff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-02-10T09:08:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T03:36:06.000Z", "max_issues_repo_path": "code/flexigis_simulate.py", "max_issues_repo_name": "FlexiGIS/FlexiGIS", "max_issues_repo_head_hexsha": "fc0bef64fa229141bb195f3ea2d208f4c80e2aff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/flexigis_simulate.py", "max_forks_repo_name": "FlexiGIS/FlexiGIS", "max_forks_repo_head_hexsha": "fc0bef64fa229141bb195f3ea2d208f4c80e2aff", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-03-13T19:08:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T03:36:15.000Z", "avg_line_length": 48.1434108527, "max_line_length": 97, "alphanum_fraction": 0.646566299, "include": true, "reason": "import numpy", "num_tokens": 2895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.1761267430288662}}
{"text": "#! /usr/bin/env python\n\n########################################################################\n#                                                                      #\n# Resums the non-global logarithms, needs ngl_resum.py                 #\n#                                                                      #\n# If using ngl_resum, please cite                                      #\n#               doi:10.1007/JHEP09(2020)029                            #\n#               https://inspirehep.net/literature/1798660              #\n#                                                                      #\n########################################################################\n\n__author__ = 'Marcel Balsiger'\n__email__ = 'marcel.balsiger@hotmail.com'\n__date__ = 'October 19, 2020'\n\nimport time\nimport numpy as np\nimport argparse\nimport pylhe\nimport ngl_resum as ngl\n\nparser = argparse.ArgumentParser(description='This code shows how to '\\\n        'use ngl_resum in combination with LHE-files, considering '\\\n        'top-pair production. First, each event gets tested whether '\\\n        'it fulfills the conditions of Table 1 from the ATLAS paper '\\\n        'arXiv:1203.5015 [hep-ex] and then showers the dipoles with '\\\n        'the outside region defined by the symmetric rapidity gap '\\\n        'from -y to y with areas around the bottom quarks cut away. '\\\n        'Similar code was used to resum the non-global logarithms in '\\\n        'Section 5 of arXiv:2006.00014')\nparser.add_argument('-f','--file', help='lhe event file to shower',\\\n        default=None,required=True)\nparser.add_argument('-y','--ymax', help='ymax of outside region', \\\n        default=0.8, type=float)\nparser.add_argument('-n','--nsh', help='number of showers per dipole', \\\n        default=100, type=int)\nparser.add_argument('-t','--tmax', help='maximal shower time tmax', \\\n        default=0.1, type=float)\nparser.add_argument('-m','--nbins', help='number of bins in hists', \\\n        default=100, type=int)\nparser.add_argument('-c','--cutoff', help='cutoff of shower', \\\n        default=5, type=float)\nparser.add_argument('-s','--seed', help='random seed', \\\n        default=None, type=int)\nparser.add_argument('-b','--break', help='stop after so many events', \\\n        default=100000, type=int)\nargs = vars(parser.parse_args())\neventFile=args['file']\n\nif not(args['seed'] is None) : np.random.seed(args['seed'])\n\n\nshowerCutoff=float(args['cutoff'])\nnbins=int(args['nbins'])\ntmax=float(args['tmax'])\nnsh=int(args['nsh'])\n\n\ndef _outside(self,v):\n    jetaxis1=self.event.outgoingBottom[0]/self.event.outgoingBottom[0].e\n    jetaxis2=self.event.outgoingBottom[1]/self.event.outgoingBottom[1].e\n    jetRadius=0.4\n    rapRangeMax=float(args['ymax'])\n    rapRangeMin=0.0\n    return (v.R2(jetaxis1)>jetRadius**2) and \\\n           (v.R2(jetaxis2)>jetRadius**2) and \\\n           (abs(v.rap)<rapRangeMax) and (abs(v.rap)>=rapRangeMin)\n\ndef validEvent(ev): # ev is the ngl.Event we want to test\n    \n    # check whether we have the necessary particles\n    if ev.intermediateTop == None : return False\n    if ev.outgoingBottom == None : return False\n    if (ev.outgoingElectron == None) and (ev.outgoingMuon == None): \\\n            return False\n    if len(ev.intermediateTop) != 2 :  return False\n    if len(ev.outgoingBottom) != 2 : return False\n\n    momentaLeptonsOut=[]\n    momentaNeutrinoOut=[]\n    \n    electronmuonevent=True\n    if not ev.outgoingElectron==None:\n        for i in ev.outgoingElectron:\n            momentaLeptonsOut.append(i)\n            # checks on electron(s)\n            if i.eT< 25: return False\n            if abs(i.rap)>2.47: return False\n        for i in ev.outgoingENeutrino:\n            momentaNeutrinoOut.append(i)\n    else:\n        electronmuonevent=False\n            \n\n    if not ev.outgoingMuon==None:\n        for i in ev.outgoingMuon:\n            momentaLeptonsOut.append(i)\n            # checks on muon(s)\n            if i.pT< 20: return False\n            if abs(i.rap)>2.5: return False\n        for i in ev.outgoingMNeutrino:\n            momentaNeutrinoOut.append(i)\n    else:\n        electronmuonevent=False\n    \n    # check number of leptons ans neutrinos\n    if len(momentaLeptonsOut) != 2 : return False\n    if len(momentaNeutrinoOut) != 2 : return False\n    \n    dileptonmass=np.sqrt((momentaLeptonsOut[0]+momentaLeptonsOut[1])*\\\n                            (momentaLeptonsOut[0]+momentaLeptonsOut[1]))\n    missingMomentum=(momentaNeutrinoOut[0]+momentaNeutrinoOut[1])\n        \n    if not electronmuonevent:\n        # checks on \"missing momenta\" (neutrinos) and dilepton mass\n        if missingMomentum.eT<40 : return False\n        if (dileptonmass<15 or abs(dileptonmass-91)<10) : return False\n    else:\n        # check on visible transverse momentum\n        if (momentaLeptonsOut[0].pT+momentaLeptonsOut[1].pT+\\\n            ev.outgoingBottom[0].pT+ev.outgoingBottom[1].pT)<130:\n                return False\n\n    # checks on bottom quarks\n    for i in ev.outgoingBottom:\n        if i.pT<25: return False\n        if abs(i.rap)>2.4: return False\n        for j in momentaLeptonsOut:\n                    if i.R2(j)<0.4**2: return False\n\n    return True # only gets reached, if no check failed.\n    \n\n\nevtFile = pylhe.readLHE(eventFile)\n\n\nfullResultLL=ngl.Hist(nbins,tmax,errorHistCalc=True)\nfullNGL1Loop=0.\nfullNGL1LoopSq=0.\nfullNGL2Loop=0.\nfullNGL2LoopSq=0.\n\neventWeight=0.\n\nnumberEvents=0\nnumberValidEvents=0\n\ntimeStart = time.time()\n\nfor event in evtFile:\n    numberEvents+=1\n    \n    \n    ev=ngl.Event(eventFromFile=event,productionDipoles='intermediate',\\\n                    decayDipoles=False)\n    \n    if not eventWeight > 0:\n        eventWeight=ev.weight\n    if not eventWeight==ev.weight:\n        print(\"Warning: events not of equal weight!\")\n\n    if validEvent(ev):\n        numberValidEvents+=1\n        \n        outsideRegion=ngl.OutsideRegion(ev)\n        outsideRegion.outside = _outside.__get__(outsideRegion,\\\n            ngl.OutsideRegion)\n        shower=ngl.Shower(ev,outsideRegion,nsh,nbins,tmax,showerCutoff)\n        shower.shower()\n        fullResultLL+=shower.resLL\n        fullNGL1Loop+=shower.ngl1Loop\n        fullNGL1LoopSq+=shower.ngl1LoopSq\n        fullNGL2Loop+=shower.ngl2Loop\n        fullNGL2LoopSq+=shower.ngl2LoopSq\n            \n    if numberEvents >= int(args['break']):break\n    \nprint('runtime=', time.time()-timeStart,' sec')    \nprint(\"of \", numberEvents,\" events, \", numberValidEvents,\" were valid.\")\nprint(\"Weight of each event:\", eventWeight)\nprint('\\n\\n'  )\n\nprint('*************************************')\nprint('*  t       LL(t)          dS(t)     * ')\nprint('*************************************\\n')\nprint('*** Binned Result ***\\n\\n')\n\n\nfor i in range(0,fullResultLL.nbins):    \n    print( round(fullResultLL.centerBinValue[i],4),' ', \\\n                fullResultLL.entries[i]/numberValidEvents,' ', \\\n                np.sqrt(fullResultLL.squaredError[i])/numberValidEvents)\n\nprint('\\n'  )  \nsnlo=fullNGL1Loop/numberValidEvents\nsnloError=np.sqrt((fullNGL1LoopSq/numberValidEvents-\\\n                        (fullNGL1Loop/numberValidEvents)**2)\\\n                        /(nsh*numberValidEvents))\nprint('snlo=',snlo)\nprint('snloError=',snloError)\n\nprint('\\n')\n\nsnnlo=fullNGL2Loop/numberValidEvents+0.5*snlo**2\n#Error(snnlo)=|d(snnlo)/d(fullNGL2Loop)*Error(fullNGL2Loop)|\n#               + |d(snnlo)/d(snlo)*Error(snlo)|\nsnnloError=abs(np.sqrt((fullNGL2LoopSq/numberValidEvents-\\\n                (fullNGL2Loop/numberValidEvents)**2)/\\\n                (nsh*numberValidEvents)))\\\n                +abs(snlo*snloError)\nprint('snnlo=',snnlo)\nprint('snnloError=',snnloError)\nprint('\\n')\n", "meta": {"hexsha": "9b9969ed658e48e822e3c4b7dbe4c4230c6399c8", "size": 7632, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/resummator_LHE.py", "max_stars_repo_name": "MarcelBalsiger/ngl_resum", "max_stars_repo_head_hexsha": "982139b18d1d6a3d0dff5c803761de067ea1c5a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/resummator_LHE.py", "max_issues_repo_name": "MarcelBalsiger/ngl_resum", "max_issues_repo_head_hexsha": "982139b18d1d6a3d0dff5c803761de067ea1c5a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/resummator_LHE.py", "max_forks_repo_name": "MarcelBalsiger/ngl_resum", "max_forks_repo_head_hexsha": "982139b18d1d6a3d0dff5c803761de067ea1c5a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-17T17:46:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-17T17:46:25.000Z", "avg_line_length": 35.3333333333, "max_line_length": 72, "alphanum_fraction": 0.5989255765, "include": true, "reason": "import numpy", "num_tokens": 2057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.17612673957284206}}
{"text": "import tensorflow as tf\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.layers import Layer\nfrom tensorflow.keras import Sequential\nimport tensorflow.keras.layers as nn\nfrom tensorflow import einsum\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\n\nfrom einops import rearrange, repeat\nfrom einops.layers.tensorflow import Rearrange\n\nimport numpy as np\n\ndef exists(val):\n    return val is not None\n\ndef pair(t):\n    return t if isinstance(t, tuple) else (t, t)\n\n# adaptive token sampling functions and classes\n\ndef log(t, eps = 1e-6):\n    return tf.math.log(t + eps)\n\ndef sample_gumbel(shape, dtype, eps = 1e-6):\n    u = tf.random.uniform(shape, dtype=dtype)\n    return -log(-log(u, eps), eps)\n\ndef torch_gather(x, indices, gather_axis):\n    # if pytorch gather indices are\n    # [[[0, 10, 20], [0, 10, 20], [0, 10, 20]],\n    #  [[0, 10, 20], [0, 10, 20], [0, 10, 20]]]\n    # tf nd_gather needs to be\n    # [[0,0,0], [0,0,10], [0,0,20], [0,1,0], [0,1,10], [0,1,20], [0,2,0], [0,2,10], [0,2,20],\n    #  [1,0,0], [1,0,10], [1,0,20], [1,1,0], [1,1,10], [1,1,20], [1,2,0], [1,2,10], [1,2,20]]\n\n    indices = tf.cast(indices, tf.int64)\n    # create a tensor containing indices of each element\n    all_indices = tf.where(tf.fill(indices.shape, True))\n    gather_locations = tf.reshape(indices, [indices.shape.num_elements()])\n\n    # splice in our pytorch style index at the correct axis\n    gather_indices = []\n    for axis in range(len(indices.shape)):\n        if axis == gather_axis:\n            gather_indices.append(gather_locations)\n        else:\n            gather_indices.append(all_indices[:, axis])\n\n    gather_indices = tf.stack(gather_indices, axis=-1)\n    gathered = tf.gather_nd(x, gather_indices)\n    reshaped = tf.reshape(gathered, indices.shape)\n    return reshaped\n\ndef batched_index_select(values, indices, dim = 1):\n    value_dims = values.shape[(dim + 1):]\n    values_shape, indices_shape = map(lambda t: list(t.shape), (values, indices))\n    indices = indices[(..., *((None,) * len(value_dims)))]\n    indices = tf.tile(indices, multiples=[1] * len(indices_shape) + [*value_dims])\n    value_expand_len = len(indices_shape) - (dim + 1)\n    values = values[(*((slice(None),) * dim), *((None,) * value_expand_len), ...)]\n\n    value_expand_shape = [-1] * len(values.shape)\n    expand_slice = slice(dim, (dim + value_expand_len))\n    value_expand_shape[expand_slice] = indices.shape[expand_slice]\n    dim += value_expand_len\n\n    values = torch_gather(values, indices, dim)\n    return values\n\nclass AdaptiveTokenSampling(Layer):\n    def __init__(self, output_num_tokens, eps=1e-6):\n        super(AdaptiveTokenSampling, self).__init__()\n        self.eps = eps\n        self.output_num_tokens = output_num_tokens\n\n    def call(self, attn, value=None, mask=None, training=True):\n        heads, output_num_tokens, eps, dtype = attn.shape[1], self.output_num_tokens, self.eps, attn.dtype\n\n        # first get the attention values for CLS token to all other tokens\n        cls_attn = attn[..., 0, 1:]\n\n        # calculate the norms of the values, for weighting the scores, as described in the paper\n        value_norms = tf.norm(value[..., 1:, :], axis=-1)\n\n        # weigh the attention scores by the norm of the values, sum across all heads\n        cls_attn = einsum('b h n, b h n -> b n', cls_attn, value_norms)\n\n        # normalize to 1\n        normed_cls_attn = cls_attn / (tf.reduce_sum(cls_attn, axis=-1, keepdims=True) + eps)\n\n        # instead of using inverse transform sampling, going to invert the softmax and use gumbel-max sampling instead\n        pseudo_logits = log(normed_cls_attn)\n\n        # mask out pseudo logits for gumbel-max sampling\n        mask_without_cls = mask[:, 1:]\n        mask_value = -np.finfo(attn.dtype.as_numpy_dtype).max / 2\n        pseudo_logits = tf.where(~mask_without_cls, mask_value, pseudo_logits)\n\n        # expand k times, k being the adaptive sampling number\n        pseudo_logits = repeat(pseudo_logits, 'b n -> b k n', k=output_num_tokens)\n        pseudo_logits = pseudo_logits + sample_gumbel(pseudo_logits.shape, dtype=dtype)\n\n        # gumble-max and add one to reserve 0 for padding / mask\n        sampled_token_ids = tf.argmax(pseudo_logits, axis=-1) + 1\n\n        # calculate unique using torch.unique and then pad the sequence from the right\n        unique_sampled_token_ids_list = []\n        for t in tf.unstack(sampled_token_ids):\n            t = tf.cast(t, tf.int32)\n            t, _ = tf.unique(t)\n            x = tf.sort(t)\n            unique_sampled_token_ids_list.append(x)\n\n\n        unique_sampled_token_ids = pad_sequences(unique_sampled_token_ids_list)\n\n        # calculate the new mask, based on the padding\n        new_mask = unique_sampled_token_ids != 0\n\n        # CLS token never gets masked out (gets a value of True)\n        new_mask = tf.pad(new_mask, paddings=[[0, 0], [1, 0]], constant_values=True)\n\n        # prepend a 0 token id to keep the CLS attention scores\n        unique_sampled_token_ids = tf.pad(unique_sampled_token_ids, paddings=[[0, 0], [1, 0]])\n        expanded_unique_sampled_token_ids = repeat(unique_sampled_token_ids, 'b n -> b h n', h=heads)\n\n        # gather the new attention scores\n        new_attn = batched_index_select(attn, expanded_unique_sampled_token_ids, dim=2)\n\n        # return the sampled attention scores, new mask (denoting padding), as well as the sampled token indices (for the residual)\n        return new_attn, new_mask, unique_sampled_token_ids\n\ndef gelu(x, approximate=False):\n    if approximate:\n        coeff = tf.cast(0.044715, x.dtype)\n        return 0.5 * x * (1.0 + tf.tanh(0.7978845608028654 * (x + coeff * tf.pow(x, 3))))\n    else:\n        return 0.5 * x * (1.0 + tf.math.erf(x / tf.cast(1.4142135623730951, x.dtype)))\n\nclass GELU(Layer):\n    def __init__(self, approximate=False):\n        super(GELU, self).__init__()\n        self.approximate = approximate\n\n    def call(self, x, training=True):\n        return gelu(x, self.approximate)\n\nclass PreNorm(Layer):\n    def __init__(self, fn):\n        super(PreNorm, self).__init__()\n\n        self.norm = nn.LayerNormalization()\n        self.fn = fn\n\n    def call(self, x, **kwargs):\n        return self.fn(self.norm(x), **kwargs)\n\nclass MLP(Layer):\n    def __init__(self, dim, hidden_dim, dropout=0.0):\n        super(MLP, self).__init__()\n        self.net = Sequential([\n            nn.Dense(units=hidden_dim),\n            GELU(),\n            nn.Dropout(rate=dropout),\n            nn.Dense(units=dim),\n            nn.Dropout(rate=dropout)\n        ])\n\n    def call(self, x, training=True):\n        return self.net(x, training=training)\n\nclass Attention(Layer):\n    def __init__(self, dim, heads=8, dim_head=64, dropout=0.0, output_num_tokens=None):\n        super(Attention, self).__init__()\n        inner_dim = dim_head * heads\n        self.heads = heads\n        self.scale = dim_head ** -0.5\n\n        self.attend = nn.Softmax()\n        self.to_qkv = nn.Dense(units=inner_dim * 3, use_bias=False)\n\n        self.output_num_tokens = output_num_tokens\n        self.ats = AdaptiveTokenSampling(output_num_tokens) if exists(output_num_tokens) else None\n\n        self.to_out = Sequential([\n            nn.Dense(units=dim),\n            nn.Dropout(rate=dropout)\n        ])\n\n    def call(self, x, mask=None, training=True):\n        num_tokens = x.shape[1]\n\n        qkv = self.to_qkv(x)\n        qkv = tf.split(qkv, num_or_size_splits=3, axis=-1)\n        q, k, v = map(lambda t: rearrange(t, 'b n (h d)-> b h n d', h=self.heads), qkv)\n\n        dots = tf.matmul(q, tf.transpose(k, perm=[0, 1, 3, 2])) * self.scale\n\n        if exists(mask):\n            mask_f = tf.cast(mask, tf.float32)\n            dots_mask = rearrange(mask_f, 'b i -> b 1 i 1') * rearrange(mask_f, 'b j -> b 1 1 j')\n            dots_mask = tf.cast(dots_mask, tf.bool)\n            mask_value = -np.finfo(dots.dtype.as_numpy_dtype).max\n            dots = tf.where(~dots_mask, mask_value, dots)\n\n        attn = self.attend(dots)\n\n        sampled_token_ids = None\n\n        # if adaptive token sampling is enabled\n        # and number of tokens is greater than the number of output tokens\n        if exists(self.output_num_tokens) and (num_tokens - 1) > self.output_num_tokens:\n            attn, mask, sampled_token_ids = self.ats(attn, v, mask=mask)\n\n        out = tf.matmul(attn, v)\n        out = rearrange(out, 'b h n d -> b n (h d)')\n        out = self.to_out(out, training=training)\n\n        return out, mask, sampled_token_ids\n\nclass Transformer(Layer):\n    def __init__(self, dim, depth, max_tokens_per_depth, heads, dim_head, mlp_dim, dropout=0.0):\n        super(Transformer, self).__init__()\n        assert len(max_tokens_per_depth) == depth, 'max_tokens_per_depth must be a tuple of length that is equal to the depth of the transformer'\n        assert sorted(max_tokens_per_depth, reverse=True) == list(max_tokens_per_depth), 'max_tokens_per_depth must be in decreasing order'\n        assert min(max_tokens_per_depth) > 0, 'max_tokens_per_depth must have at least 1 token at any layer'\n\n        self.layers = []\n        for _, output_num_tokens in zip(range(depth), max_tokens_per_depth):\n            self.layers.append([\n                PreNorm(Attention(dim, output_num_tokens=output_num_tokens, heads=heads, dim_head=dim_head, dropout=dropout)),\n                PreNorm(MLP(dim, mlp_dim, dropout=dropout))\n            ])\n\n    def call(self, x, training=True):\n        b, n = x.shape[:2]\n\n        # use mask to keep track of the paddings when sampling tokens\n        # as the duplicates (when sampling) are just removed, as mentioned in the paper\n        mask = tf.ones([b, n], dtype=tf.bool)\n\n        token_ids = tf.range(n)\n        token_ids = repeat(token_ids, 'n -> b n', b = b)\n\n        for attn, ff in self.layers:\n            attn_out, mask, sampled_token_ids = attn(x, mask=mask, training=training)\n\n            # when token sampling, one needs to then gather the residual tokens with the sampled token ids\n            if exists(sampled_token_ids):\n                x = batched_index_select(x, sampled_token_ids, dim=1)\n                token_ids = batched_index_select(token_ids, sampled_token_ids, dim=1)\n\n            x = x + attn_out\n\n            x = ff(x, training=training) + x\n\n        return x, token_ids\n\nclass ViT(Model):\n    def __init__(self,\n                 image_size, \n                 patch_size, \n                 num_classes, \n                 dim, \n                 depth, \n                 max_tokens_per_depth, \n                 heads, \n                 mlp_dim,\n                 dim_head=64, \n                 dropout=0.0, \n                 emb_dropout=0.0\n                 ):\n        super(ViT, self).__init__()\n\n        image_height, image_width = pair(image_size)\n        patch_height, patch_width = pair(patch_size)\n\n        assert image_height % patch_height == 0 and image_width % patch_width == 0, 'Image dimensions must be divisible by the patch size.'\n\n        num_patches = (image_height // patch_height) * (image_width // patch_width)\n\n        self.patch_embedding = Sequential([\n            Rearrange('b (h p1) (w p2) c -> b (h w) (p1 p2 c)', p1=patch_height, p2=patch_width),\n            nn.Dense(units=dim)\n        ])\n\n        self.pos_embedding = tf.Variable(initial_value=tf.random.normal([1, num_patches + 1, dim]))\n        self.cls_token = tf.Variable(initial_value=tf.random.normal([1, 1, dim]))\n        self.dropout = nn.Dropout(rate=emb_dropout)\n\n        self.transformer = Transformer(dim, depth, max_tokens_per_depth, heads, dim_head, mlp_dim, dropout)\n\n        self.mlp_head = Sequential([\n            nn.LayerNormalization(),\n            nn.Dense(units=num_classes)\n        ])\n\n\n    def call(self, img, return_sampled_token_ids=False, training=True, **kwargs):\n        x = self.patch_embedding(img)\n        b, n, _ = x.shape\n\n        cls_tokens = repeat(self.cls_token, '() n d -> b n d', b=b)\n        x = tf.concat([cls_tokens, x], axis=1)\n        x += self.pos_embedding[:, :(n + 1)]\n        x = self.dropout(x, training=training)\n\n        x, token_ids = self.transformer(x, training=training)\n\n        logits = self.mlp_head(x[:, 0])\n\n        if return_sampled_token_ids:\n            # remove CLS token and decrement by 1 to make -1 the padding\n            token_ids = token_ids[:, 1:] - 1\n            return logits, token_ids\n\n        return logits\n\nv = ViT(\n    image_size = 256,\n    patch_size = 16,\n    num_classes = 1000,\n    dim = 1024,\n    depth = 6,\n    max_tokens_per_depth = (256, 128, 64, 32, 16, 8), # a tuple that denotes the maximum number of tokens that any given layer should have. if the layer has greater than this amount, it will undergo adaptive token sampling\n    heads = 16,\n    mlp_dim = 2048,\n    dropout = 0.1,\n    emb_dropout = 0.1\n)\n\nimg = tf.random.normal(shape=[4, 256, 256, 3])\npreds = v(img) # (1, 1000)\nprint(preds.shape)", "meta": {"hexsha": "e6f03e987da37554085e24e0a6848186ccd5ff97", "size": 12869, "ext": "py", "lang": "Python", "max_stars_repo_path": "vit_tensorflow/ats_vit.py", "max_stars_repo_name": "taki0112/vit-tensorflow", "max_stars_repo_head_hexsha": "f16972989d9df478d7ee3ab1c45332d412801646", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2022-03-25T08:57:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T22:30:41.000Z", "max_issues_repo_path": "vit_tensorflow/ats_vit.py", "max_issues_repo_name": "170928/vit-tensorflow", "max_issues_repo_head_hexsha": "f16972989d9df478d7ee3ab1c45332d412801646", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-28T07:28:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:51:26.000Z", "max_forks_repo_path": "vit_tensorflow/ats_vit.py", "max_forks_repo_name": "170928/vit-tensorflow", "max_forks_repo_head_hexsha": "f16972989d9df478d7ee3ab1c45332d412801646", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2022-03-28T05:24:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T03:18:42.000Z", "avg_line_length": 38.4149253731, "max_line_length": 222, "alphanum_fraction": 0.6312844821, "include": true, "reason": "import numpy", "num_tokens": 3358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.17612673957284206}}
{"text": "\"\"\"\nkaldo\nAnharmonic Lattice Dynamics\n\"\"\"\nimport numpy as np\nfrom sparse import COO\nimport pandas as pd\nimport ase.units as units\nfrom kaldo.helpers.tools import count_rows\nfrom ase import Atoms\nimport re\nfrom kaldo.helpers.logger import get_logger\nlogging = get_logger()\n\n\ndef import_from_files(replicated_atoms, dynmat_file=None, third_file=None, supercell=(1, 1, 1),\n                      third_energy_threshold=0.):\n    # TODO: split this method into two pieces\n    n_replicas = np.prod(supercell)\n    n_total_atoms = replicated_atoms.positions.shape[0]\n    n_unit_atoms = int(n_total_atoms / n_replicas)\n    unit_symbols = []\n    unit_positions = []\n    for i in range(n_unit_atoms):\n        unit_symbols.append(replicated_atoms.get_chemical_symbols()[i])\n        unit_positions.append(replicated_atoms.positions[i])\n    unit_cell = replicated_atoms.cell / supercell\n\n    atoms = Atoms(unit_symbols,\n                  positions=unit_positions,\n                  cell=unit_cell,\n                  pbc=[1, 1, 1])\n\n    second_order = None\n    third_order = None\n\n    if dynmat_file:\n        logging.info('Reading dynamical matrix')\n        second_dl = import_second(atoms, replicas=supercell, filename=dynmat_file)\n        second_order = second_dl\n\n    if third_file:\n        try:\n            logging.info('Reading sparse third order')\n            third_dl = import_sparse_third(atoms=atoms,\n                                              supercell=supercell,\n                                              filename=third_file,\n                                              third_energy_threshold=third_energy_threshold)\n\n        except UnicodeDecodeError:\n            if third_energy_threshold != 0:\n                raise ValueError('Third threshold not supported for dense third')\n            logging.info('Reading dense third order')\n            third_dl = import_dense_third(atoms, supercell=supercell, filename=third_file)\n            logging.info('Third order matrix stored.')\n        third_dl = third_dl[:n_unit_atoms]\n        third_shape = (\n            n_unit_atoms * 3, n_replicas * n_unit_atoms * 3, n_replicas * n_unit_atoms * 3)\n        third_dl = third_dl.reshape(third_shape)\n        third_order = third_dl\n\n    return second_order, third_order\n\n\n\ndef import_second(atoms, replicas=(1, 1, 1), filename='Dyn.form'):\n    replicas = np.array(replicas)\n    n_unit_cell = atoms.positions.shape[0]\n    dyn_mat = import_dynamical_matrix(n_unit_cell, replicas, filename)\n    mass = np.sqrt (atoms.get_masses ())\n    dyn_mat = dyn_mat * mass[np.newaxis, :, np.newaxis, np.newaxis, np.newaxis, np.newaxis]\n    dyn_mat = dyn_mat * mass[np.newaxis, np.newaxis, np.newaxis, np.newaxis, :, np.newaxis]\n    return dyn_mat\n\n\ndef import_dynamical_matrix(n_atoms, supercell=(1, 1, 1), filename='Dyn.form'):\n    supercell = np.array(supercell)\n    dynamical_matrix_frame = pd.read_csv(filename, header=None, delim_whitespace=True)\n    dynamical_matrix = dynamical_matrix_frame.values\n    n_replicas = np.prod(supercell)\n    if dynamical_matrix.size == n_replicas * (n_atoms * 3) ** 2:\n        dynamical_matrix = dynamical_matrix.reshape((n_atoms, 3, n_replicas, n_atoms, 3))\n    elif dynamical_matrix.size == (n_replicas * n_atoms * 3) ** 2:\n        dynamical_matrix = dynamical_matrix.reshape((n_replicas, n_atoms, 3, n_replicas, n_atoms, 3))[0]\n    elif dynamical_matrix.size == (n_atoms * 3) ** 2:\n        dynamical_matrix = dynamical_matrix.reshape((n_atoms, 3, 1, n_atoms, 3))\n    else:\n        logging.error('Impossible to read calculate_dynmat with size ' + str(dynamical_matrix.size))\n    tenjovermoltoev = 10 * units.J / units.mol\n    return dynamical_matrix * tenjovermoltoev\n\n\ndef import_sparse_third(atoms, supercell=(1, 1, 1), filename='THIRD', third_energy_threshold=0.):\n    supercell = np.array(supercell)\n    n_replicas = np.prod(supercell)\n    n_atoms = atoms.get_positions().shape[0]\n    n_replicated_atoms = n_atoms * n_replicas\n    n_rows = count_rows(filename)\n    array_size = min(n_rows * 3, n_atoms * 3 * (n_replicated_atoms * 3) ** 2)\n    coords = np.zeros((array_size, 6), dtype=np.int16)\n    values = np.zeros((array_size))\n    index_in_unit_cell = 0\n    tenjovermoltoev = 10 * units.J / units.mol\n    with open(filename) as f:\n        for i, line in enumerate(f):\n            l_split = re.split('\\s+', line.strip())\n            coords_to_write = np.array(l_split[0:-3], dtype=int) - 1\n            values_to_write = np.array(l_split[-3:], dtype=np.float)\n            #TODO: add 'if' third_energy_threshold before calculating the mask\n            mask_to_write = np.abs(values_to_write) > third_energy_threshold\n\n            if mask_to_write.any() and coords_to_write[0] < n_atoms:\n                for alpha in np.arange(3)[mask_to_write]:\n                    coords[index_in_unit_cell, :-1] = coords_to_write[np.newaxis, :]\n                    coords[index_in_unit_cell, -1] = alpha\n                    values[index_in_unit_cell] = values_to_write[alpha] * tenjovermoltoev\n                    index_in_unit_cell = index_in_unit_cell + 1\n            if i % 1000000 == 0:\n                logging.info('reading third order: ' + str(np.round(i / n_rows, 2) * 100) + '%')\n    logging.info('read ' + str(3 * i) + ' interactions')\n    coords = coords[:index_in_unit_cell].T\n    values = values[:index_in_unit_cell]\n    sparse_third = COO (coords, values, shape=(n_atoms, 3, n_replicated_atoms, 3, n_replicated_atoms, 3))\n    return sparse_third\n\n\ndef import_dense_third(atoms, supercell, filename, is_reduced=True):\n    supercell = np.array(supercell)\n    n_replicas = np.prod(supercell)\n    n_atoms = atoms.get_positions().shape[0]\n    if is_reduced:\n        total_rows = (n_atoms *  3) * (n_atoms * n_replicas * 3) ** 2\n        third = np.fromfile(filename, dtype=np.float, count=total_rows)\n        third = third.reshape((n_atoms, 3, n_atoms * n_replicas, 3, n_atoms * n_replicas, 3))\n    else:\n        total_rows = (n_atoms * n_replicas * 3) ** 3\n        third = np.fromfile(filename, dtype=np.float, count=total_rows)\n        third = third.reshape((n_atoms * n_replicas, 3, n_atoms * n_replicas, 3, n_atoms * n_replicas, 3))\n    return third\n", "meta": {"hexsha": "4e106b90ce3112855fab76cd1b8852b16b6e42d3", "size": 6164, "ext": "py", "lang": "Python", "max_stars_repo_path": "kaldo/interface/eskm_io.py", "max_stars_repo_name": "kcbhamu/kaldo", "max_stars_repo_head_hexsha": "5926ac03f796f82841012ba1dd4ead8eee03a6c7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 49, "max_stars_repo_stars_event_min_datetime": "2020-07-04T21:50:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T21:05:12.000Z", "max_issues_repo_path": "kaldo/interface/eskm_io.py", "max_issues_repo_name": "kaituohuo/kaldo", "max_issues_repo_head_hexsha": "537bceea2c3206711a8899d68e1dbd23fb0c38b6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2020-07-24T06:22:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T02:17:50.000Z", "max_forks_repo_path": "kaldo/interface/eskm_io.py", "max_forks_repo_name": "kaituohuo/kaldo", "max_forks_repo_head_hexsha": "537bceea2c3206711a8899d68e1dbd23fb0c38b6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2020-08-20T15:07:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-07T19:18:59.000Z", "avg_line_length": 44.0285714286, "max_line_length": 106, "alphanum_fraction": 0.6570408825, "include": true, "reason": "import numpy", "num_tokens": 1581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.1761267326607938}}
{"text": "# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n'''System information'''\nimport numpy as np\n\n\nclass periodic_box_condition_information:\n    \"\"\"periodic_box_condition_information\"\"\"\n\n    def __init__(self, controller, box_length):\n        CONSTANT_UINT_MAX_FLOAT = 4294967296.0\n        self.crd_to_uint_crd_cof = np.array([CONSTANT_UINT_MAX_FLOAT / box_length[0],\n                                             CONSTANT_UINT_MAX_FLOAT / box_length[1],\n                                             CONSTANT_UINT_MAX_FLOAT / box_length[2]])\n        self.quarter_crd_to_uint_crd_cof = 0.25 * self.crd_to_uint_crd_cof\n        self.uint_dr_to_dr_cof = 1.0 / self.crd_to_uint_crd_cof\n\n\nclass system_information:\n    \"\"\"system_information\"\"\"\n\n    def __init__(self, controller, md_info):\n        CONSTANT_PRES_CONVERTION_INVERSE = 0.00001439506089041446\n        self.md_info = md_info\n        self.box_length = self.md_info.box_length\n        self.steps = 0\n        self.step_limit = 1000 if \"step_limit\" not in controller.Command_Set else int(\n            controller.Command_Set[\"step_limit\"])\n        self.target_temperature = 300.0 if \"target_temperature\" not in controller.Command_Set else float(\n            controller.Command_Set[\"target_temperature\"])\n        if md_info.mode == 2 and \"target_pressure\" in controller.Command_Set:\n            self.target_pressure = float(controller.Command_Set[\"target_pressure\"])\n        else:\n            self.target_pressure = 1\n        self.target_pressure *= CONSTANT_PRES_CONVERTION_INVERSE\n        self.d_virial = 0\n        self.d_pressure = 0\n        self.d_temperature = 0\n        self.d_potential = 0\n        self.d_sum_of_atom_ek = 0\n        self.freedom = 3 * md_info.atom_numbers\n\n\nclass non_bond_information:\n    \"\"\"system_information\"\"\"\n\n    def __init__(self, controller, md_info):\n        self.md_info = md_info\n        self.skin = 2.0 if \"skin\" not in controller.Command_Set else float(controller.Command_Set[\"skin\"])\n        print(\"    skin set to %.2f Angstram\" % (self.skin))\n        self.cutoff = 10.0 if \"cutoff\" not in controller.Command_Set else float(controller.Command_Set[\"cutoff\"])\n        self.atom_numbers = self.md_info.atom_numbers\n        self.excluded_atom_numbers = 0\n        self.h_excluded_list_start = []\n        self.h_excluded_numbers = []\n        self.h_excluded_list = []\n        if controller.amber_parm is not None:\n            file_path = controller.amber_parm\n            self.read_information_from_amberfile(file_path)\n        else:\n            self.read_exclude_file(controller)\n\n    def read_exclude_file(self, controller):\n        \"\"\"read_exclude_file\"\"\"\n        if \"exclude_in_file\" in controller.Command_Set:\n            print(\"    Start reading excluded list:\")\n            path = controller.Command_Set[\"exclude_in_file\"]\n            file = open(path, 'r')\n            context = file.readlines()\n            atom_numbers, self.excluded_atom_numbers = list(map(int, context[0].strip().split()))\n            if self.md_info.atom_numbers > 0 and (atom_numbers != self.md_info.atom_numbers):\n                print(\"        Error: atom_numbers is not equal: \", atom_numbers, self.md_info.atom_numbers)\n                exit(1)\n            else:\n                self.md_info.atom_numbers = atom_numbers\n            count = 0\n            for idx, val in enumerate(context):\n                if idx > 0:\n                    el = list(map(int, val.strip().split()))\n                    if el[0] == 1 and -1 in el:\n                        self.h_excluded_numbers.append(0)\n                    else:\n                        self.h_excluded_numbers.append(el[0])\n                    self.h_excluded_list_start.append(count)\n                    if el:\n                        self.h_excluded_list.extend(el[1:])\n                        count += el[0]\n            print(\"    End reading excluded list\")\n            file.close()\n        else:\n            print(\"    Set all atom exclude no atoms as default\")\n            count = 0\n            for i in range(self.md_info.atom_numbers):\n                self.h_excluded_numbers[i] = 0\n                self.h_excluded_list_start[i] = count\n                for _ in range(self.h_excluded_numbers[i]):\n                    self.h_excluded_list[count] = 0\n                    count += 1\n            print(\"    End reading charge\")\n\n    def read_information_from_amberfile(self, file_path):\n        '''read amber file'''\n        file = open(file_path, 'r')\n        context = file.readlines()\n        file.close()\n        self.h_excluded_list_start = [0] * self.atom_numbers\n        self.h_excluded_numbers = [0] * self.atom_numbers\n\n        for idx, val in enumerate(context):\n            if idx < len(context) - 1:\n                if \"%FLAG POINTERS\" in val + context[idx + 1] and \"%FORMAT(10I8)\" in val + context[idx + 1]:\n                    start_idx = idx + 2\n                    count = 0\n                    value = list(map(int, context[start_idx].strip().split()))\n                    information = []\n                    information.extend(value)\n                    while count < 11:\n                        start_idx += 1\n                        value = list(map(int, context[start_idx].strip().split()))\n                        information.extend(value)\n                        count += len(value)\n                    self.excluded_atom_numbers = information[10]\n                    print(\"excluded atom numbers \", self.excluded_atom_numbers)\n                    break\n        for idx, val in enumerate(context):\n            if \"%FLAG NUMBER_EXCLUDED_ATOMS\" in val:\n                count = 0\n                start_idx = idx\n                information = []\n                while count < self.atom_numbers:\n                    start_idx += 1\n                    if \"%FORMAT\" in context[start_idx]:\n                        continue\n                    else:\n                        value = list(map(int, context[start_idx].strip().split()))\n                        information.extend(value)\n                        count += len(value)\n                count = 0\n                for i in range(self.atom_numbers):\n                    self.h_excluded_numbers[i] = information[i]\n                    self.h_excluded_list_start[i] = count\n                    count += information[i]\n                break\n\n        total_count = sum(self.h_excluded_numbers)\n        self.h_excluded_list = []\n        for idx, val in enumerate(context):\n            if \"%FLAG EXCLUDED_ATOMS_LIST\" in val:\n                count = 0\n                start_idx = idx\n                information = []\n                while count < total_count:\n                    start_idx += 1\n                    if \"%FORMAT\" in context[start_idx]:\n                        continue\n                    else:\n                        value = list(map(int, context[start_idx].strip().split()))\n                        information.extend(value)\n                        count += len(value)\n\n                count = 0\n                for i in range(self.atom_numbers):\n                    tmp_list = []\n                    if self.h_excluded_numbers[i] == 1:\n                        tmp_list.append(information[count] - 1)\n                        if information[count] == 0:\n                            self.h_excluded_numbers[i] = 0\n                        count += 1\n                    else:\n                        for _ in range(self.h_excluded_numbers[i]):\n                            tmp_list.append(information[count] - 1)\n\n                            count += 1\n                        tmp_list = sorted(tmp_list)\n                    self.h_excluded_list.extend(tmp_list)\n                break\n\n\nclass NVE_iteration:\n    \"\"\"NVE_iteration\"\"\"\n\n    def __init__(self, controller, md_info):\n        self.max_velocity = -1 if \"nve_velocity_max\" not in controller.Command_Set else float(\n            controller.Command_Set[\"nve_velocity_max\"])\n\n\nclass residue_information:\n    \"\"\"residue_information\"\"\"\n\n    def __init__(self, controller, md_info):\n        self.md_info = md_info\n        self.residue_numbers = 0\n        self.h_mass = []\n        self.h_mass_inverse = []\n        self.h_res_start = []\n        self.h_res_end = []\n        self.momentum = []\n        self.center_of_mass = []\n        self.sigma_of_res_ek = 0\n        self.res_ek_energy = 0\n        self.sigma_of_res_ek = 0\n        self.is_initialized = 0\n        print(\"    Start reading residue list:\")\n        if \"residue_in_file\" in controller.Command_Set:\n            self.read_residule_file(controller)\n        elif \"amber_parm7\" in controller.Command_Set:\n            self.residue_numbers = self.md_info.residue_numbers\n            self.h_res_start = md_info.h_res_start\n            self.h_res_end = md_info.h_res_end\n            self.is_initialized = 1\n            self.read_res_mass()\n        else:\n            self.residue_numbers = md_info.atom_numbers\n            self.h_res_start = list(range(self.residue_numbers))\n            self.h_res_end = list(range(1, self.residue_numbers + 1))\n            self.is_initialized = 1\n        print(\"    End reading residue list\")\n\n    def read_res_mass(self):\n        \"\"\" Read_AMBER_Parm7 \"\"\"\n        if self.md_info.h_mass:\n            for i in range(self.residue_numbers):\n                temp_mass = 0\n                for j in range(self.h_res_start[i], self.h_res_end[i]):\n                    temp_mass += self.md_info.h_mass[j]\n                self.h_mass.append(temp_mass)\n                if temp_mass == 0:\n                    self.h_mass_inverse.append(0)\n                else:\n                    self.h_mass_inverse.append(1.0 / temp_mass)\n        else:\n            print(\"    Error: atom mass should be initialized before residue mass\")\n            exit(1)\n\n    def read_residule_file(self, controller):\n        \"\"\"read_residule_file\"\"\"\n        if \"residue_in_file\" in controller.Command_Set:\n            path = controller.Command_Set[\"residue_in_file\"]\n            file = open(path, 'r')\n            context = file.readlines()\n            atom_numbers, self.residue_numbers = list(map(int, context[0].strip().split()))\n            print(\"        residue_numbers is \", self.residue_numbers)\n            # self.md_info.residue_numbers = self.residue_numbers\n            if self.md_info.atom_numbers > 0 and (atom_numbers != self.md_info.atom_numbers):\n                print(\"        Error: atom_numbers is not equal: \", atom_numbers, self.md_info.atom_numbers)\n                exit(1)\n            else:\n                self.md_info.atom_numbers = atom_numbers\n            print(\"        residue_numbers is \", self.residue_numbers)\n\n            count = 0\n            for idx, val in enumerate(context):\n                if idx > 0:\n                    self.h_res_start.append(count)\n                    temp = int(val.strip())\n                    count += temp\n                    self.h_res_end.append(count)\n            print(\"    End reading excluded list\")\n            file.close()\n            self.is_initialized = 1\n            if self.is_initialized:\n                self.read_res_mass()\n\n\nclass trajectory_output:\n    \"\"\"trajectory_output\"\"\"\n\n    def __init__(self, controller, md_info):\n        self.current_crd_synchronized_step = 0\n        self.is_molecule_map_output = 0\n        if \"molecule_map_output\" in controller.Command_Set:\n            self.is_molecule_map_output = int(controller.Command_Set[\"molecule_map_output\"])\n        self.amber_irest = -1\n        self.write_trajectory_interval = 1000 if \"write_information_interval\" not in controller.Command_Set else int(\n            controller.Command_Set[\"write_information_interval\"])\n        self.write_restart_file_interval = self.write_trajectory_interval if \"write_restart_file_interval\" not in \\\n                                                                             controller.Command_Set else \\\n            int(controller.Command_Set[\"write_restart_file_interval\"])\n", "meta": {"hexsha": "ad99526c824a3e65155d88eedabd88e5d4e3a24d", "size": 12559, "ext": "py", "lang": "Python", "max_stars_repo_path": "model_zoo/research/hpc/sponge/src/system_information.py", "max_stars_repo_name": "LottieWang/mindspore", "max_stars_repo_head_hexsha": "1331c7e432fb691d1cfa625ab7cc7451dcfc7ce0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "model_zoo/research/hpc/sponge/src/system_information.py", "max_issues_repo_name": "LottieWang/mindspore", "max_issues_repo_head_hexsha": "1331c7e432fb691d1cfa625ab7cc7451dcfc7ce0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model_zoo/research/hpc/sponge/src/system_information.py", "max_forks_repo_name": "LottieWang/mindspore", "max_forks_repo_head_hexsha": "1331c7e432fb691d1cfa625ab7cc7451dcfc7ce0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.1580756014, "max_line_length": 117, "alphanum_fraction": 0.5623855403, "include": true, "reason": "import numpy", "num_tokens": 2566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.17601548487073151}}
{"text": "\"\"\"\nSpectral data representation.\n\n\"\"\"\n\nfrom __future__ import (absolute_import, division, print_function,\n                        unicode_literals)\n\nfrom .core import Data\nfrom .atomic import get_atomdat\n\nfrom astropy.units import (erg, km, cm, s, angstrom, spectral,\n                           spectral_density, Quantity, UnitsError)\nfrom astropy.constants import m_e, c, e\nfrom astropy.table import Table, Column\n\nfrom math import pi, sqrt, exp, log10\nfrom warnings import warn\n\nimport numpy as np\n\n__all__ = ['Spectrum2D', 'Spectrum1D', 'Absorber', 'EmissionLine']\n\ne2_me_c = (e.esu ** 2 / (m_e.cgs * c.cgs)).to(cm ** 2 / s)\nc_kms = c.to(km / s)\n\natomdat = None\n\n\ndef find_bin_edges(bin_centres):\n    \"\"\"\n    Find the bin edges given the bin centres.\n\n    Parameters\n    ----------\n    bin_centres : array, shape (N,)\n        The bin centres.\n\n    Returns\n    -------\n    bins : array, shape (N + 1,)\n        The bin edges.\n\n    \"\"\"\n\n    if not isinstance(bin_centres, np.ndarray):\n        bin_centres = np.asarray(bin_centres)\n\n    edges = bin_centres[:-1] + 0.5 * (bin_centres[1:] - bin_centres[:-1])\n    bins = np.concatenate(([2 * bin_centres[0] - edges[0]], edges,\n                           [2 * bin_centres[-1] - edges[-1]]))\n\n    return bins\n\n\nclass Spectrum2D(object):\n    \"\"\"\n    A 2D spectrum.\n\n    Parameters\n    ----------\n    dispersion : `astropy.units.Quantity` or array, shape (N,)\n        Spectral dispersion axis.\n\n    data : array, shape (N, M)\n        The spectral data.\n\n    unit : `astropy.units.UnitBase` or str, optional\n        Unit for the dispersion axis.\n\n    \"\"\"\n\n    def __init__(self, dispersion, data, unit=None):\n\n        self.dispersion = Quantity(dispersion, unit=unit)\n\n        if unit is not None:\n            self.wavelength = self.dispersion.to(angstrom)\n\n        else:\n            self.wavelength = self.dispersion\n\n        self.data = data\n\n\nclass Spectrum1D(object):\n    \"\"\"\n    A 1D spectrum. Assumes wavelength units unless otherwise specified.\n\n    Parameters\n    ----------\n    dispersion : `astropy.units.Quantity` or array\n        Spectral dispersion axis.\n\n    flux : `igmtools.data.Data`, `astropy.units.Quantity` or array\n        Spectral flux. Should have the same length as `dispersion`.\n\n    error : `astropy.units.Quantity` or array, optional\n        Error on each flux value.\n\n    continuum : `astropy.units.Quantity` or array, optional\n        An estimate of the continuum flux.\n\n    mask : array, optional\n        Mask for the spectrum. The values must be False where valid and True\n        where not.\n\n    unit : `astropy.units.UnitBase` or str, optional\n        Spectral unit.\n\n    dispersion_unit : `astropy.units.UnitBase` or str, optional\n        Unit for the dispersion axis.\n\n    meta : dict, optional\n        Meta data for the spectrum.\n\n    \"\"\"\n\n    def __init__(self, dispersion, flux, error=None, continuum=None,\n                 mask=None, unit=None, dispersion_unit=None, meta=None):\n\n        _unit = flux.unit if unit is None and hasattr(flux, 'unit') else unit\n\n        if isinstance(error, (Quantity, Data)):\n            if error.unit != _unit:\n                raise UnitsError('The error unit must be the same as the '\n                                 'flux unit.')\n            error = error.value\n\n        elif isinstance(error, Column):\n            if error.unit != _unit:\n                raise UnitsError('The error unit must be the same as the '\n                                 'flux unit.')\n            error = error.data\n\n        # Set zero error elements to NaN:\n        if error is not None:\n            zero = error == 0\n            error[zero] = np.nan\n\n            # Mask these elements:\n            if mask is not None:\n                self.mask = mask | np.isnan(error)\n\n            else:\n                self.mask = np.isnan(error)\n\n        # If dispersion is a `Quantity`, `Data`, or `Column` instance with the\n        # unit attribute set, that unit is preserved if `dispersion_unit` is\n        # None, but overriden otherwise\n        self.dispersion = Quantity(dispersion, unit=dispersion_unit)\n\n        if dispersion_unit is not None:\n            self.wavelength = self.dispersion.to(angstrom)\n\n        else:\n            # Assume wavelength units:\n            self.wavelength = self.dispersion\n\n        self.flux = Data(flux, error, unit)\n\n        if continuum is not None:\n            self.continuum = Quantity(continuum, unit=unit)\n\n        else:\n            self.continuum = None\n\n        self.meta = meta\n\n    @classmethod\n    def from_table(cls, table, dispersion_column, flux_column,\n                   error_column=None, continuum_column=None, unit=None,\n                   dispersion_unit=None):\n        \"\"\"\n        Initialises a `Spectrum1D` object from an `astropy.table.Table`\n        instance.\n\n        Parameters\n        ----------\n        table : `astropy.table.Table`\n            Contains information used to construct the spectrum. Must have\n            columns for the dispersion axis and the spectral flux.\n\n        dispersion_column : str\n            Name for the dispersion column.\n\n        flux_column : str\n            Name for the flux column.\n\n        error_column : str, optional\n            Name for the error column.\n\n        continuum_column : str, optional\n            Name for the continuum column.\n\n        unit : `astropy.units.UnitBase` or str, optional\n            Spectral unit.\n\n        dispersion_unit : `astropy.units.UnitBase` or str, optional\n            Unit for the dispersion axis.\n\n        \"\"\"\n\n        dispersion = Quantity(table[dispersion_column])\n        flux = Quantity(table[flux_column])\n\n        if error_column is not None:\n            error = Quantity(table[error_column])\n        else:\n            error = None\n\n        if continuum_column is not None:\n            continuum = Quantity(table[continuum_column])\n        else:\n            continuum = None\n\n        meta = table.meta\n        mask = table.mask\n\n        return cls(dispersion, flux, error, continuum, mask, unit,\n                   dispersion_unit, meta)\n\n    def write(self, *args, **kwargs):\n        \"\"\"\n        Write the spectrum to a file. Accepts the same arguments as\n        `astropy.table.Table.write`\n\n        \"\"\"\n\n        if self.dispersion.unit is None:\n            label_string = 'WAVELENGTH'\n\n        else:\n            if self.dispersion.unit.physical_type == 'length':\n                label_string = 'WAVELENGTH'\n\n            elif self.dispersion.unit.physical_type == 'frequency':\n                label_string = 'FREQUENCY'\n\n            elif self.dispersion.unit.physical_type == 'energy':\n                label_string = 'ENERGY'\n\n            else:\n                raise ValueError('unrecognised unit type')\n\n        t = Table([self.dispersion, self.flux, self.flux.uncertainty.value],\n                  names=[label_string, 'FLUX', 'ERROR'])\n        t['ERROR'].unit = t['FLUX'].unit\n\n        if self.continuum is not None:\n            t['CONTINUUM'] = self.continuum\n\n        t.write(*args, **kwargs)\n\n    def plot(self, **kwargs):\n        \"\"\"\n        Plot the spectrum. Accepts the same arguments as\n        `igmtools.plot.Plot`.\n\n        \"\"\"\n\n        from ..plot import Plot\n\n        p = Plot(1, 1, 1, **kwargs)\n\n        p.axes[0].plot(self.dispersion.value, self.flux.value,\n                       drawstyle='steps-mid')\n\n        if self.flux.uncertainty is not None:\n            p.axes[0].plot(self.dispersion.value, self.flux.uncertainty.value,\n                           drawstyle='steps-mid')\n\n        p.tidy()\n        p.display()\n\n    def normalise_to_magnitude(self, magnitude, band):\n        \"\"\"\n        Normalises the spectrum to match the flux equivalent to the\n        given AB magnitude in the given passband.\n\n        Parameters\n        ----------\n        magnitude : float\n            AB magnitude.\n\n        band : `igmtools.photometry.Passband`\n            The passband.\n\n        \"\"\"\n\n        from ..photometry import mag2flux\n\n        mag_flux = mag2flux(magnitude, band)\n        spec_flux = self.calculate_flux(band)\n        norm = mag_flux / spec_flux\n        self.flux *= norm\n\n    def calculate_flux(self, band):\n        \"\"\"\n        Calculate the mean flux for a passband, weighted by the response\n        and wavelength in the given passband.\n\n        Parameters\n        ----------\n        band : `igmtools.photometry.Passband`\n            The passband.\n\n        Returns\n        -------\n        flux : `astropy.units.Quantity`\n            The mean flux in erg / s / cm^2 / Angstrom.\n\n        Notes\n        -----\n        This function does not calculate an uncertainty.\n\n        \"\"\"\n\n        if (self.wavelength[0] > band.wavelength[0] or\n                self.wavelength[-1] < band.wavelength[-1]):\n\n            warn('Spectrum does not cover the whole bandpass, '\n                 'extrapolating...')\n            dw = np.median(np.diff(self.wavelength.value))\n            spec_wavelength = np.arange(\n                band.wavelength.value[0],\n                band.wavelength.value[-1] + dw, dw) * angstrom\n            spec_flux = np.interp(spec_wavelength, self.wavelength,\n                                  self.flux.value)\n\n        else:\n            spec_wavelength = self.wavelength\n            spec_flux = self.flux.value\n\n        i, j = spec_wavelength.searchsorted(\n            Quantity([band.wavelength[0], band.wavelength[-1]]))\n        wavelength = spec_wavelength[i:j]\n        flux = spec_flux[i:j]\n\n        dw_band = np.median(np.diff(band.wavelength))\n        dw_spec = np.median(np.diff(wavelength))\n\n        if dw_spec.value > dw_band.value > 20:\n\n            warn('Spectrum wavelength sampling interval {0:.2f}, but bandpass'\n                 'sampling interval {1:.2f}'.format(dw_spec, dw_band))\n\n            # Interpolate the spectrum to the passband wavelengths:\n            flux = np.interp(band.wavelength, wavelength, flux)\n            band_transmission = band.transmission\n            wavelength = band.wavelength\n\n        else:\n            # Interpolate the band transmission to the spectrum wavelengths:\n            band_transmission = np.interp(\n                wavelength, band.wavelength, band.transmission)\n\n        # Weight by the response and wavelength, appropriate when we're\n        # counting the number of photons within the band:\n        flux = (np.trapz(band_transmission * flux * wavelength, wavelength) /\n                np.trapz(band_transmission * wavelength, wavelength))\n        flux *= erg / s / cm ** 2 / angstrom\n\n        return flux\n\n    def calculate_magnitude(self, band, system='AB'):\n        \"\"\"\n        Calculates the magnitude in a given passband.\n\n        band : `igmtools.photometry.Passband`\n            The passband.\n\n        system : {`AB`, `Vega`}\n            Magnitude system.\n\n        Returns\n        -------\n        magnitude : float\n            Magnitude in the given system.\n\n        \"\"\"\n\n        if system not in ('AB', 'Vega'):\n            raise ValueError('`system` must be one of `AB` or `Vega`')\n\n        f1 = self.calculate_flux(band)\n\n        if f1 > 0:\n            magnitude = -2.5 * log10(f1 / band.flux[system])\n\n            if system == 'Vega':\n                # Add 0.026 because Vega has V = 0.026:\n                magnitude += 0.026\n\n        else:\n            magnitude = np.inf\n\n        return magnitude\n\n    def apply_extinction(self, EBmV):\n        \"\"\"\n        Apply Milky Way extinction.\n\n        Parameters\n        ----------\n        EBmV : float\n            Colour excess.\n\n        \"\"\"\n\n        from astro.extinction import MWCardelli89\n\n        tau = MWCardelli89(self.wavelength, EBmV=EBmV).tau\n        self.flux *= np.exp(-tau)\n\n        if self.continuum is not None:\n            self.continuum *= np.exp(-tau)\n\n    def rebin(self, dispersion):\n        \"\"\"\n        Rebin the spectrum onto a new dispersion axis.\n\n        Parameters\n        ----------\n        dispersion : float, `astropy.units.Quantity` or array\n            The dispersion for the rebinned spectrum. If a float, assumes a\n            linear scale with that bin size.\n\n        \"\"\"\n\n        if isinstance(dispersion, float):\n            dispersion = np.arange(\n                self.dispersion.value[0], self.dispersion.value[-1],\n                dispersion)\n\n        old_bins = find_bin_edges(self.dispersion.value)\n        new_bins = find_bin_edges(dispersion)\n\n        widths = np.diff(old_bins)\n\n        old_length = len(self.dispersion)\n        new_length = len(dispersion)\n\n        i = 0  # index of old array\n        j = 0  # index of new array\n\n        # Variables used for rebinning:\n        df = 0.0\n        de2 = 0.0\n        nbins = 0.0\n\n        flux = np.zeros_like(dispersion)\n        error = np.zeros_like(dispersion)\n\n        # Sanity check:\n        if old_bins[-1] < new_bins[0] or new_bins[-1] < old_bins[0]:\n            raise ValueError('Dispersion scales do not overlap!')\n\n        # Find the first contributing old pixel to the rebinned spectrum:\n        if old_bins[i + 1] < new_bins[0]:\n\n            # Old dispersion scale extends lower than the new one. Find the\n            # first old bin that overlaps with the new scale:\n            while old_bins[i + 1] < new_bins[0]:\n                i += 1\n\n            i -= 1\n\n        elif old_bins[0] > new_bins[j + 1]:\n\n            # New dispersion scale extends lower than the old one. Find the\n            # first new bin that overlaps with the old scale:\n            while old_bins[0] > new_bins[j + 1]:\n                flux = np.nan\n                error = np.nan\n                j += 1\n\n            j -= 1\n\n        l0 = old_bins[i]  # lower edge of contributing old bin\n\n        while True:\n\n            h0 = old_bins[i + 1]  # upper edge of contributing old bin\n            h1 = new_bins[j + 1]  # upper edge of jth new bin\n\n            if h0 < h1:\n                # Count up the decimal number of old bins that contribute to\n                # the new one and start adding up fractional flux values:\n                if self.flux.uncertainty.value[i] > 0:\n                    bin_fraction = (h0 - l0) / widths[i]\n                    nbins += bin_fraction\n\n                    # We don't let `Data` handle the error propagation here\n                    # because a sum of squares will not give us what we\n                    # want, i.e. 0.25**2 + 0.75**2 != 0.5**2 + 0.5**2 != 1**2\n                    df += self.flux.value[i] * bin_fraction\n                    de2 += self.flux.uncertainty.value[i] ** 2 * bin_fraction\n\n                l0 = h0\n                i += 1\n\n                if i == old_length:\n                    break\n\n            else:\n                # We have all but one of the old bins that contribute to the\n                # new one, so now just add the remaining fraction of the new\n                # bin to the decimal bin count and add the remaining\n                # fractional flux value to the sum:\n                if self.flux.uncertainty.value[i] > 0:\n                    bin_fraction = (h1 - l0) / widths[i]\n                    nbins += bin_fraction\n                    df += self.flux.value[i] * bin_fraction\n                    de2 += self.flux.uncertainty.value[i] ** 2 * bin_fraction\n\n                if nbins > 0:\n                    # Divide by the decimal bin count to conserve flux density:\n                    flux[j] = df / nbins\n                    error[j] = sqrt(de2) / nbins\n\n                else:\n                    flux[j] = 0.0\n                    error[j] = 0.0\n\n                df = 0.0\n                de2 = 0.0\n                nbins = 0.0\n\n                l0 = h1\n                j += 1\n\n                if j == new_length:\n                    break\n\n        if hasattr(self.dispersion, 'unit'):\n            dispersion = Quantity(dispersion, self.dispersion.unit)\n\n        if hasattr(self.flux, 'unit'):\n            flux = Data(flux, error, self.flux.unit)\n\n        # Linearly interpolate the continuum onto the new dispersion scale:\n        if self.continuum is not None:\n            continuum = np.interp(dispersion, self.dispersion, self.continuum)\n        else:\n            continuum = None\n\n        return self.__class__(dispersion, flux, continuum=continuum)\n\n\nclass Absorber(object):\n    \"\"\"\n    Class representation of an absorber.\n\n    Parameters\n    ----------\n    identifier : str\n        Name of the ion, molecule or isotope, e.g. `HI`.\n\n    redshift : float, optional\n        Redshift of the absorber.\n\n    logn : float, optional\n        Log10 column density (cm^-2).\n\n    b : float, optional\n        Doppler broadening parameter (km/s).\n\n    covering_fraction : float, optional\n        Covering fraction.\n\n    atom : `igmtools.data.AtomDat`, optional\n        Atomic data.\n\n    \"\"\"\n\n    def __init__(self, identifier, redshift=None, logn=None, b=None,\n                 covering_fraction=1, atom=None):\n\n        if atom is None:\n            atom = get_atomdat()\n\n        self.identifier = identifier\n        self.transitions = atom[identifier]\n        self.redshift = redshift\n        self.logn = logn\n        self.b = b\n        self.covering_fraction = covering_fraction\n\n    def __repr__(self):\n\n        return 'Absorber({0}, z={1:.2f}, logN={2:.2f}, b={3})'.format(\n            self.identifier, self.redshift, self.logn, int(self.b))\n\n    @classmethod\n    def from_tau_peak(cls, transition, tau, b):\n        \"\"\"\n        Initialise an absorber from the optical depth at line centre and\n        Doppler broadining parameter of a given transition.\n\n        Parameters\n        ----------\n        transition : str\n            Name of the transition, e.g. `HI 1215'\n\n        tau : float\n            Optical depth at the line centre.\n\n        b : float\n            Doppler broadening parameter (km/s).\n\n        \"\"\"\n\n        atom = get_atomdat()\n        transition = atom.get_transition(transition)\n\n        if isinstance(b, Quantity):\n            b = b.to(cm / s)\n        else:\n            b = (b * km / s).to(cm / s)\n\n        wavelength = transition.wavelength.to(cm)\n        osc = transition.osc\n\n        column = tau * b / (sqrt(pi) * e2_me_c * osc * wavelength)\n        logn = log10(column.value)\n\n        return cls(identifier=transition.parent, logn=logn, b=b)\n\n    def optical_depth(self, dispersion):\n        \"\"\"\n        Calculates the optical depth profile for a given spectral\n        dispersion array.\n\n        Parameters\n        ----------\n        dispersion : array\n            Spectral dispersion.\n\n        Returns\n        -------\n        tau : array\n            The optical depth profile.\n\n        \"\"\"\n\n        from ..calculations import optical_depth, tau_peak\n\n        if isinstance(dispersion, Quantity):\n            dispersion = dispersion.to(angstrom)\n\n        elif hasattr(dispersion, 'unit'):\n            if dispersion.unit is not None:\n                dispersion = dispersion.to(angstrom)\n\n        else:\n            dispersion = Quantity(dispersion, unit=angstrom)\n\n        velocity_range = ([-20000, 20000] * km / s if self.logn > 18\n                          else [-1000, 1000] * km / s)\n\n        # Select only transitions with redshifted central wavelengths inside\n        # `dispersion` +/- 500 km/s:\n        rest_wavelengths = Quantity([t.wavelength for t in self.transitions])\n        observed_wavelengths = rest_wavelengths * (1 + self.redshift)\n\n        wmin = dispersion[0] * (1 - 500 * km / s / c_kms)\n        wmax = dispersion[-1] * (1 - 500 * km / s / c_kms)\n\n        in_range = ((observed_wavelengths >= wmin) &\n                    (observed_wavelengths <= wmax))\n        transitions = np.array(self.transitions)[in_range]\n\n        tau = np.zeros_like(dispersion.value)\n\n        for i, transition in enumerate(transitions):\n\n            tau_max = tau_peak(transition, self.logn, self.b)\n\n            if 1 - exp(-tau_max) < 1e-3:\n                continue\n\n            observed_wavelength = transition.wavelength * (1 + self.redshift)\n            dv = ((dispersion - observed_wavelength) /\n                  observed_wavelength * c_kms)\n\n            i0, i1 = dv.searchsorted(velocity_range)\n            tau0 = optical_depth(dv[i0:i1], transition, self.logn, self.b)\n            tau[i0:i1] += tau0\n\n        return tau\n\n\nclass EmissionLine(object):\n    \"\"\"\n    Class representation of an emission line and its properties.\n\n    Parameters\n    ----------\n    wavelength : float\n        Rest frame wavelength of the line in Angstrom.\n\n    redshift : float\n        Redshift of the emission line.\n\n    flux : `igmtools.data.Data`, optional\n        Integrated line flux.\n\n    cont : `igmtools.data.Data`, optional\n        Continuum flux at the line centre.\n\n    eqw : `igmtools.data.Data`, optional\n        Equivalent width of the line.\n\n    \"\"\"\n\n    def __init__(self, wavelength, redshift, flux=None, cont=None, eqw=None):\n\n        from ..calculations import comoving_distance\n\n        if flux and not isinstance(flux, Data):\n            raise ValueError('flux must be an instance of a Data object')\n\n        if cont and not isinstance(cont, Data):\n            raise ValueError('cont must be an instance of a Data object')\n\n        if eqw and not isinstance(eqw, Data):\n            raise ValueError('eqw must be an instance of a Data object')\n\n        if isinstance(wavelength, Quantity):\n            self.wavelength = wavelength.to(angstrom)\n\n        else:\n            self.wavelength = wavelength * angstrom\n\n        self.redshift = redshift\n        self.wavelength_observed = self.wavelength * (1 + self.redshift)\n\n        if flux:\n\n            self._flux = flux.to(erg / cm ** 2 / s, equivalencies=spectral())\n            self.rflux = self._flux * (1 + redshift) ** 2\n\n            distance = comoving_distance(self.redshift).cgs\n            self.luminosity = 4 * pi * distance ** 2 * self._flux\n\n            if cont and eqw:\n\n                self._cont = cont.to(\n                    erg / cm ** 2 / s / angstrom,\n                    equivalencies=spectral_density(self.wavelength_observed))\n                self.rcont = self._cont * (1 + redshift) ** 3\n\n                self._eqw = eqw.to(angstrom)\n                self.reqw = self._eqw / (1 + redshift)\n\n            elif cont and not eqw:\n\n                self._cont = cont.to(\n                    erg / cm ** 2 / s / angstrom,\n                    equivalencies=spectral_density(self.wavelength_observed))\n                self.rcont = self._cont * (1 + redshift) ** 3\n\n                self._eqw = self._flux / self._cont\n                self.reqw = self._eqw / (1 + redshift)\n\n            elif eqw and not cont:\n\n                self._eqw = eqw.to(angstrom)\n                self.reqw = self._eqw / (1 + redshift)\n\n                self._cont = self._flux / self._eqw\n                self.rcont = self._cont * (1 + redshift) ** 3\n\n            else:\n\n                self._eqw = eqw\n                self.reqw = None\n                self._cont = cont\n                self.rcont = None\n\n        elif cont:\n\n            self._cont = cont.to(\n                erg / cm ** 2 / s / angstrom,\n                equivalencies=spectral_density(self.wavelength_observed))\n            self.rcont = self._cont * (1 + redshift) ** 3\n\n            if eqw:\n\n                self._eqw = eqw.to(angstrom)\n                self.reqw = self._eqw / (1 + redshift)\n\n                self._flux = self._cont * self._eqw\n                self.rflux = self._flux * (1 + redshift) ** 2\n\n                distance = comoving_distance(self.redshift).cgs\n                self.luminosity = 4 * pi * distance ** 2 * self._flux\n\n            else:\n\n                self._eqw = eqw\n                self.reqw = None\n                self._flux = flux\n                self.rflux = None\n                self.luminosity = None\n\n        elif eqw:\n\n            self._eqw = eqw.to(angstrom)\n            self.reqw = self._eqw / (1 + redshift)\n\n            self._flux = flux\n            self.rflux = None\n            self._cont = cont\n            self.rcont = None\n            self.luminosity = None\n\n        else:\n\n            self._flux = flux\n            self.rflux = None\n            self._cont = cont\n            self.rcont = None\n            self._eqw = eqw\n            self.reqw = None\n            self.luminosity = None\n\n    @property\n    def flux(self):\n        return self._flux\n\n    @flux.setter\n    def flux(self, value):\n\n        from ..calculations import comoving_distance\n\n        if not isinstance(value, Data):\n            raise ValueError('flux must be an instance of a Data object')\n\n        self._flux = value.to(erg / cm ** 2 / s, equivalencies=spectral())\n        self.rflux = self._flux * (1 + self.redshift) ** 2\n\n        distance = comoving_distance(self.redshift).cgs\n        self.luminosity = 4 * pi * distance ** 2 * self._flux\n\n    @property\n    def cont(self):\n        return self._cont\n\n    @cont.setter\n    def cont(self, value):\n\n        if not isinstance(value, Data):\n            raise ValueError('cont must be an instance of a Data object')\n\n        self._cont = value.to(\n            erg / cm ** 2 / s / angstrom,\n            equivalencies=spectral_density(self.wavelength_observed))\n        self.rcont = self._cont * (1 + self.redshift) ** 3\n\n    @property\n    def eqw(self):\n        return self._eqw\n\n    @eqw.setter\n    def eqw(self, value):\n\n        if not isinstance(value, Data):\n            raise ValueError('eqw must be an instance of a Data object')\n\n        self._eqw = value.to(angstrom)\n        self.reqw = self._eqw / (1 + self.redshift)\n", "meta": {"hexsha": "e17f94c938f9e18ac86976194de970d65e2753e1", "size": 25454, "ext": "py", "lang": "Python", "max_stars_repo_path": "igmtools/data/spectral.py", "max_stars_repo_name": "cwfinn/igmtools", "max_stars_repo_head_hexsha": "6e14973fd1e69d5e7bd7c40f93ffe11e2cd41990", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "igmtools/data/spectral.py", "max_issues_repo_name": "cwfinn/igmtools", "max_issues_repo_head_hexsha": "6e14973fd1e69d5e7bd7c40f93ffe11e2cd41990", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "igmtools/data/spectral.py", "max_forks_repo_name": "cwfinn/igmtools", "max_forks_repo_head_hexsha": "6e14973fd1e69d5e7bd7c40f93ffe11e2cd41990", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-19T04:45:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-19T04:45:38.000Z", "avg_line_length": 29.1235697941, "max_line_length": 79, "alphanum_fraction": 0.5524475524, "include": true, "reason": "import numpy,from astropy", "num_tokens": 5898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032313, "lm_q2_score": 0.3007455852086006, "lm_q1q2_score": 0.17596658902707846}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\n\nimport argparse\n\nimport multiprocessing\nimport numpy as np\n\nimport torch\nfrom torch import nn, Tensor\nimport torch.nn.functional as F\n\nfrom torch_geometric.data import Data as GeometricData, Batch\n\nfrom ctp.util import make_batches\nfrom ctp.clutrr import Data, Instance\n\nfrom ctp.geometric import GraphAttentionNetwork\nfrom ctp.geometric import GraphConvolutionalNetwork\n\nfrom ctp.geometric import VecBaselineNetworkV1\nfrom ctp.geometric import VecBaselineNetworkV2\nfrom ctp.geometric import Seq2VecEncoderFactory\n\nfrom typing import Dict, List, Tuple, Optional\n\nimport logging\n\nlogger = logging.getLogger(os.path.basename(sys.argv[0]))\nnp.set_printoptions(linewidth=256, precision=4, suppress=True, threshold=sys.maxsize)\n\ntorch.set_num_threads(multiprocessing.cpu_count())\n\n# PYTHONPATH=. python3 ./bin/geometric-cli.py\n#  --train data/clutrr-emnlp/data_089907f8/*train*\n#  --test data/clutrr-emnlp/data_089907f8/*test*\n\n\ndef to_data(instance: Instance,\n            relation_to_idx: Dict[str, int],\n            test_relation_to_idx: Dict[str, int],\n            nb_entities: int,\n\n            is_predicate: bool,\n            predicate_to_idx: Dict[str, int],\n            relation_to_predicate: Dict[str, str],\n            test_predicate_to_idx: Dict[str, int],\n\n            device: Optional[torch.device] = None) -> Tuple[GeometricData, Tuple[int, int]]:\n    entity_lst = sorted({x for t in instance.story for x in {t[0], t[2]}})\n    entity_to_idx = {e: i for i, e in enumerate(entity_lst)}\n\n    x = torch.arange(nb_entities, device=device).view(-1, 1)\n\n    edge_list = [(entity_to_idx[s], entity_to_idx[o]) for (s, _, o) in instance.story]\n    edge_index = torch.tensor(list(zip(*edge_list)), dtype=torch.long, device=device)\n\n    if is_predicate is True:\n        edge_types = [predicate_to_idx[relation_to_predicate[p]] for (_, p, _) in instance.story]\n        y = torch.tensor([test_predicate_to_idx[relation_to_predicate[instance.target[1]]]], device=device)\n    else:\n        edge_types = [relation_to_idx[p] for (_, p, _) in instance.story]\n        y = torch.tensor([test_relation_to_idx[instance.target[1]]], device=device)\n\n    edge_attr = torch.tensor(edge_types, dtype=torch.long, device=device).view(-1, 1)\n\n    res = GeometricData(x=x, edge_index=edge_index, edge_attr=edge_attr, y=y)\n\n    target_pair = (entity_to_idx[instance.target[0]], entity_to_idx[instance.target[2]])\n    return res, target_pair\n\n\ndef to_batches(instances: List[Instance],\n               batch_size: int,\n               relation_to_idx: Dict[str, int],\n               test_relation_to_idx: Dict[str, int],\n\n               is_predicate: bool,\n               predicate_to_idx: Dict[str, int],\n               relation_to_predicate: Dict[str, str],\n               test_predicate_to_idx: Dict[str, int],\n\n               device: Optional[torch.device] = None) -> List[Tuple[Batch, List[int], Tensor, List[Instance]]]:\n    nb_instances, res = len(instances), []\n    batches = make_batches(nb_instances, batch_size)\n\n    for batch_start, batch_end in batches:\n        batch_instances = instances[batch_start:batch_end]\n        max_nb_entities = max(i.nb_nodes for i in batch_instances)\n        this_batch_size = len(batch_instances)\n\n        batch_pairs = [\n            to_data(i, relation_to_idx, test_relation_to_idx, max_nb_entities,\n                    is_predicate, predicate_to_idx, relation_to_predicate, test_predicate_to_idx, device=device)\n            for i in batch_instances\n        ]\n\n        batch_data: List[GeometricData] = [d for d, _ in batch_pairs]\n        batch_targets: List[List[int]] = [[p[0], p[1]] for _, p in batch_pairs]\n\n        max_node = max(i + 1 for b in batch_data for i in b.x[:, 0].cpu().numpy())\n\n        batch = Batch.from_data_list(batch_data)\n        slices = [max_node for _ in batch_data]\n\n        targets = torch.tensor(batch_targets, dtype=torch.long, device=device).view(this_batch_size, 1, 2)\n\n        res += [(batch, slices, targets, batch_instances)]\n    return res\n\n\ndef main(argv):\n    argparser = argparse.ArgumentParser('Geometric CLUTRR', formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n    train_path = \"data/clutrr-emnlp/data_test/64.csv\"\n\n    argparser.add_argument('--train', action='store', type=str, default=train_path)\n    argparser.add_argument('--test', nargs='+', type=str, default=[])\n\n    argparser.add_argument('--model', '-m', action='store', type=str, default='gat')\n\n    # training params\n    argparser.add_argument('--epochs', '-e', action='store', type=int, default=100)\n    argparser.add_argument('--learning-rate', '-l', action='store', type=float, default=0.001)\n    argparser.add_argument('--batch-size', '-b', action='store', type=int, default=100)\n\n    argparser.add_argument('--embedding-size', '-k', action='store', type=int, default=100)\n    argparser.add_argument('--edge-embedding-size', '-K', action='store', type=int, default=20)\n    argparser.add_argument('--hidden-size', action='store', type=int, default=100)\n    argparser.add_argument('--nb-filters', action='store', type=int, default=100)\n    argparser.add_argument('--nb-heads', action='store', type=int, default=3)\n    argparser.add_argument('--nb-rounds', action='store', type=int, default=3)\n    argparser.add_argument('--nb-highway', action='store', type=int, default=2)\n\n    argparser.add_argument('--seed', action='store', type=int, default=0)\n\n    argparser.add_argument('--evaluate-every', '-V', action='store', type=int, default=1)\n\n    argparser.add_argument('--v2', action='store_true', default=False)\n    argparser.add_argument('--predicate', action='store_true', default=False)\n\n    args = argparser.parse_args(argv)\n\n    train_path = args.train\n    test_paths = args.test\n\n    model_name = args.model\n\n    nb_epochs = args.epochs\n    learning_rate = args.learning_rate\n    batch_size = args.batch_size\n\n    embedding_size = args.embedding_size\n    edge_embedding_size = args.edge_embedding_size\n    hidden_size = args.hidden_size\n    nb_filters = args.nb_filters\n    nb_heads = args.nb_heads\n    nb_rounds = args.nb_rounds\n    nb_highway = args.nb_highway\n\n    seed = args.seed\n\n    evaluate_every = args.evaluate_every\n\n    is_v2 = args.v2\n    is_predicate = args.predicate\n\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n\n    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n    logger.info(f'Device: {device}')\n\n    if torch.cuda.is_available():\n        torch.set_default_tensor_type(torch.cuda.FloatTensor)\n\n    data = Data(train_path=train_path, test_paths=test_paths)\n\n    entity_lst, _, relation_lst = data.entity_lst, data.predicate_lst, data.relation_lst\n    predicate_lst = data.predicate_lst\n\n    relation_to_predicate = data.relation_to_predicate\n\n    test_relation_lst = [\"aunt\", \"brother\", \"daughter\", \"daughter-in-law\", \"father\", \"father-in-law\", \"granddaughter\",\n                         \"grandfather\", \"grandmother\", \"grandson\", \"mother\", \"mother-in-law\", \"nephew\", \"niece\",\n                         \"sister\", \"son\", \"son-in-law\", \"uncle\"]\n\n    test_predicate_lst = sorted({relation_to_predicate[r] for r in test_relation_lst})\n\n    relation_to_idx = {r: i for i, r in enumerate(relation_lst)}\n    test_relation_to_idx = {r: i for i, r in enumerate(test_relation_lst)}\n\n    predicate_to_idx = {p: i for i, p in enumerate(predicate_lst)}\n    test_predicate_to_idx = {p: i for i, p in enumerate(test_predicate_lst)}\n\n    nb_nodes = len(entity_lst)\n    nb_edge_types = len(relation_lst)\n    nb_targets = len(test_relation_lst)\n\n    if is_predicate is True:\n        nb_edge_types = len(predicate_lst)\n        nb_targets = len(test_predicate_lst)\n\n    nb_instances = len(data.train)\n    batches = to_batches(data.train, batch_size=batch_size,\n                         relation_to_idx=relation_to_idx,\n                         test_relation_to_idx=test_relation_to_idx,\n\n                         is_predicate=is_predicate,\n                         predicate_to_idx=predicate_to_idx,\n                         relation_to_predicate=relation_to_predicate,\n                         test_predicate_to_idx=test_predicate_to_idx,\n\n                         device=device)\n\n    if model_name in {'gat'}:\n        model = GraphAttentionNetwork(nb_nodes=nb_nodes, nb_edge_types=nb_edge_types, target_size=nb_targets,\n                                      nb_heads=nb_heads, embedding_size=embedding_size,\n                                      edge_embedding_size=edge_embedding_size, nb_rounds=nb_rounds)\n    elif model_name in {'gcn'}:\n        model = GraphConvolutionalNetwork(nb_nodes=nb_nodes, nb_edge_types=nb_edge_types, target_size=nb_targets,\n                                          embedding_size=embedding_size, edge_embedding_size=edge_embedding_size,\n                                          nb_rounds=nb_rounds)\n    else:\n        encoder_factory = Seq2VecEncoderFactory()\n        encoder = encoder_factory.build(name=model_name, embedding_dim=embedding_size, hidden_size=hidden_size,\n                                        num_filters=nb_filters, num_heads=nb_heads, num_highway=nb_highway)\n\n        if is_v2 is False:\n            model = VecBaselineNetworkV1(nb_nodes=nb_nodes, nb_edge_types=nb_targets, relation_lst=relation_lst,\n                                         encoder=encoder, embedding_size=embedding_size)\n        else:\n            model = VecBaselineNetworkV2(nb_nodes=nb_nodes, nb_edge_types=nb_targets, relation_lst=relation_lst,\n                                         encoder=encoder, embedding_size=embedding_size)\n\n    model = model.to(device)\n\n    params_lst = nn.ParameterList([p for p in model.parameters()])\n    optimizer = torch.optim.Adam(params_lst, lr=learning_rate)\n\n    def test(test_set) -> float:\n        correct = 0\n        model.eval()\n\n        test_batches = to_batches(test_set, batch_size=batch_size, relation_to_idx=relation_to_idx,\n                                  test_relation_to_idx=test_relation_to_idx,\n\n                                  is_predicate=is_predicate,\n                                  predicate_to_idx=predicate_to_idx,\n                                  relation_to_predicate=relation_to_predicate,\n                                  test_predicate_to_idx=test_predicate_to_idx,\n\n                                  device=device)\n\n        for test_batch, test_slices, test_targets, test_instances in test_batches:\n            test_logits = model(test_batch, test_slices, test_targets, test_instances)\n            test_predictions = test_logits.max(dim=1)[1]\n            correct += test_predictions.eq(test_batch.y).sum().item()\n        return correct / len(test_set)\n\n    for epoch in range(1, nb_epochs + 1):\n        loss_total = 0.0\n        model.train()\n\n        for batch, slices, targets, instances in batches:\n            logits = model(batch, slices, targets, instances)\n\n            assert logits.shape[1] == len(test_relation_lst if not is_predicate else test_predicate_lst)\n\n            loss = F.cross_entropy(logits, batch.y, reduction='sum')\n            loss_total += loss.item()\n\n            loss.backward()\n            optimizer.step()\n            optimizer.zero_grad()\n\n        # train_accuracy = test(data.train)\n        print(f'Epoch: {epoch:03d}, Train Loss: {loss_total / nb_instances:.7f}')\n\n        if epoch % evaluate_every == 0:\n            for name in data.test:\n                test_accuracy = test(data.test[name])\n                print(f'Epoch: {epoch:03d}, Test Set: {name}, Accuracy: {test_accuracy:.7f}')\n\n    logger.info(\"Training finished\")\n\n\nif __name__ == '__main__':\n    logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n    print(' '.join(sys.argv))\n    main(sys.argv[1:])\n", "meta": {"hexsha": "2639194a62c984c994943474276d6dd78924f4f5", "size": 11734, "ext": "py", "lang": "Python", "max_stars_repo_path": "bin/geometric-cli.py", "max_stars_repo_name": "Vikicsizmadia/ctp", "max_stars_repo_head_hexsha": "d88fdfecf4b90ee42e6137a9767226c0d35b19a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2020-07-14T15:44:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T10:33:07.000Z", "max_issues_repo_path": "bin/geometric-cli.py", "max_issues_repo_name": "Vikicsizmadia/ctp", "max_issues_repo_head_hexsha": "d88fdfecf4b90ee42e6137a9767226c0d35b19a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-12-28T05:57:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T01:05:06.000Z", "max_forks_repo_path": "bin/geometric-cli.py", "max_forks_repo_name": "Vikicsizmadia/ctp", "max_forks_repo_head_hexsha": "d88fdfecf4b90ee42e6137a9767226c0d35b19a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-07-14T22:56:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T02:40:10.000Z", "avg_line_length": 39.7762711864, "max_line_length": 118, "alphanum_fraction": 0.6608147264, "include": true, "reason": "import numpy", "num_tokens": 2651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.33111975283019596, "lm_q1q2_score": 0.17589391641260146}}
{"text": "from pathlib import Path\n\nimport math\nimport os\nimport numpy as np\nimport torch\nfrom tqdm import tqdm\nfrom PIL import Image\n\nfrom vp_suite.base.base_dataset import VPDataset, VPData\nimport vp_suite.constants as constants\n\nclass MovingMNISTDataset(VPDataset):\n    r\"\"\"\n    Dataset class for the dataset \"Moving MNIST\", as firstly encountered in\n    \"Unsupervised Learning of Video Representations using LSTMs\" by Srivastava et al.\n    (https://arxiv.org/pdf/1502.04681v3.pdf).\n\n    Each sequence depicts two digits from the MNIST dataset moving linearly in front of a black background,\n    occasionally bouncing off the wall and overlapping each other.\n\n    For downloading and preparing the dataset, scripts have been developed by Tencia Lee,\n    ported to python 3 by Praateek Mahajan (https://gist.github.com/praateekmahajan/b42ef0d295f528c986e2b3a0b31ec1fe)\n    and further modified here.\n    \"\"\"\n\n    NAME = \"Moving MNIST\"\n    DEFAULT_DATA_DIR = constants.DATA_PATH / \"moving_mnist\"\n    MIN_SEQ_LEN = 20\n    ACTION_SIZE = 0\n    DATASET_FRAME_SHAPE = (64, 64, 3)\n\n    train_to_val_ratio = 0.96\n\n    def __init__(self, split, **dataset_kwargs):\n        super(MovingMNISTDataset, self).__init__(split, **dataset_kwargs)\n        self.NON_CONFIG_VARS.extend([\"data_ids\", \"data_fps\"])\n\n        self.data_dir = str((Path(self.data_dir) / split).resolve())\n        self.data_ids = sorted(os.listdir(self.data_dir))\n        self.data_fps = [os.path.join(self.data_dir, image_id) for image_id in self.data_ids]\n\n    def __len__(self):\n        return len(self.data_fps)\n\n    def __getitem__(self, i) -> VPData:\n        if not self.ready_for_usage:\n            raise RuntimeError(\"Dataset is not yet ready for usage (maybe you forgot to call set_seq_len()).\")\n\n        rgb_raw = np.load(self.data_fps[i])  # [t', h, w]\n        rgb_raw = np.expand_dims(rgb_raw, axis=-1).repeat(3, axis=-1) # [t', h, w, c]\n        rgb_raw = rgb_raw[:self.seq_len:self.seq_step]  # [t, h, w, c]\n        rgb = self.preprocess(rgb_raw)\n\n        actions = torch.zeros((self.total_frames, 1))  # [t, a], actions should be disregarded in training logic\n\n        data = { \"frames\": rgb, \"actions\": actions }\n        return data\n\n    def download_and_prepare_dataset(self):\n        frame_size = (64, 64)\n        num_frames = 20  # length of each sequence\n        digit_size = 28  # size of mnist digit within frame\n        digits_per_image = 2  # number of digits in each frame\n        d_path = self.DEFAULT_DATA_DIR\n        d_path.mkdir(parents=True)\n\n        # training sequences\n        train_seqs = 60000\n        print(\"generating training set...\")\n        train_data = generate_moving_mnist(d_path, training=True, shape=frame_size, num_frames=num_frames,\n                                           num_images=train_seqs, original_size=digit_size,\n                                           nums_per_image=digits_per_image)\n        print(\"saving training set...\")\n        save_generated_mmnist(train_data, train_seqs, frame_size, d_path / \"train\")\n\n        # testing sequences\n        test_seqs = 10000\n        print(\"generating test set...\")\n        test_data = generate_moving_mnist(d_path, training=False, shape=frame_size, num_frames=num_frames,\n                                          num_images=test_seqs, original_size=digit_size,\n                                          nums_per_image=digits_per_image)\n        print(\"saving test set...\")\n        save_generated_mmnist(test_data, test_seqs, frame_size, d_path / \"test\")\n\n# === MMNIST data preparation tools ============================================\n\ndef save_generated_mmnist(data: np.ndarray, seqs: int, frame_size: (int, int), out_path: Path):\n    r\"\"\"\n    Save generated data per-sequence to specified out path.\n\n    Args:\n        data (np.ndarray): The generated data to save.\n        seqs (int): The number of generated sequences.\n        frame_size ((int, int)): The frame size.\n        out_path (Path): The path where the data should be saved.\n    \"\"\"\n    out_path.mkdir()\n    num_frames = data.shape[0] // seqs\n    data = data.reshape(seqs, num_frames, *frame_size)\n    for i in tqdm(range(data.shape[0])):\n        cur_out_fp = out_path / f\"seq_{i:05d}.npy\"\n        np.save(str(cur_out_fp), data[i])\n\n# helper functions\ndef arr_from_img(im, mean: float = 0, std: float = 1):\n    r\"\"\"\n    Convert image to array.\n\n    Args:\n        im(): Image.\n        mean(float): Mean to subtract.\n        std(float): Standard Deviation to subtract.\n\n    Returns:\n        Image in np.float32 format, in width height channel format. With values in range 0,1\n        Shift means subtract by certain value. Could be used for mean subtraction.\n\n    \"\"\"\n    width, height = im.size\n    arr = im.getdata()\n    c = int(np.product(arr.size) / (width * height))\n\n    return (np.asarray(arr, dtype=np.float32).reshape((height, width, c)).transpose(2, 1, 0) / 255. - mean) / std\n\ndef img_from_arr(X: np.ndarray, index: int, mean: float = 0, std: float = 1):\n    r\"\"\"\n    Convert array to image.\n\n    Args:\n        X(np.ndarray): Dataset of shape N x C x W x H.\n        index(int): Index of image we want to fetch.\n        mean(float): Mean to add.\n        std(float): Standard Deviation to add.\n\n    Returns:\n        Image with dimensions H x W x C or H x W if it's a single channel image.\n    \"\"\"\n    ch, w, h = X.shape[1], X.shape[2], X.shape[3]\n    ret = (((X[index] + mean) * 255.) * std).reshape(ch, w, h).transpose(2, 1, 0).clip(0, 255).astype(np.uint8)\n    if ch == 1:\n        ret = ret.reshape(h, w)\n    return ret\n\ndef load_dataset(d_path: Path, training: bool):\n    r\"\"\"\n    Loads MNIST from the web on demand.\n\n    Args:\n        d_path (Path): The path where the downloaded digits should be stored.\n        training (bool): Whether to use the training images (True) or the test images (False).\n\n    Returns: The loaded MNIST images.\n\n    \"\"\"\n    from vp_suite.utils.utils import download_from_url\n    import gzip\n\n    def load_mnist_images(filename):\n        if not os.path.exists(filename):\n            mnist_source = 'http://yann.lecun.com/exdb/mnist/'\n            fname_ = filename.split(\"/\")[-1]\n            download_from_url(mnist_source + fname_, filename)\n        with gzip.open(filename, 'rb') as f:\n            data = np.frombuffer(f.read(), np.uint8, offset=16)\n        data = data.reshape(-1, 1, 28, 28).transpose(0, 1, 3, 2)\n        return data / np.float32(255)\n\n    if training:\n        return load_mnist_images(str(d_path / 'train-images-idx3-ubyte.gz'))\n    return load_mnist_images(str(d_path / 't10k-images-idx3-ubyte.gz'))\n\ndef generate_moving_mnist(d_path: Path, training: bool = False, shape: (int, int) = (64, 64),\n                          num_frames: int = 30, num_images: int = 100, original_size: int = 28,\n                          nums_per_image: int = 2):\n    r\"\"\"\n    Generate sequences of moving MNIST digits by moving them around between frames.\n\n    Args:\n        training (bool): Used to decide if downloading/generating training set or test set.\n        shape ((int, int)): Shape we want for our moving images (new_width and new_height).\n        num_frames (int): Number of frames in a particular movement/animation/gif.\n        num_images (int): Number of movement/animations/gif to generate.\n        original_size (int): Real size of the images (eg: MNIST is 28x28).\n        nums_per_image (int): Digits per movement/animation/gif.\n\n    Returns:\n        Dataset of np.uint8 type with dimensions num_frames * num_images x 1 x new_width x new_height\n\n    \"\"\"\n    mnist = load_dataset(d_path, training)\n    width, height = shape\n\n    # Get how many pixels can we move around a single image\n    lims = (x_lim, y_lim) = width - original_size, height - original_size\n\n    # Create a dataset of shape of num_frames * num_images x 1 x new_width x new_height\n    # Eg : 3000000 x 1 x 64 x 64\n    dataset = np.empty((num_frames * num_images, 1, width, height), dtype=np.uint8)\n\n    for img_idx in tqdm(range(num_images)):\n        # Randomly generate direction, speed and velocity for both images\n        direcs = np.pi * (np.random.rand(nums_per_image) * 2 - 1)\n        speeds = np.random.randint(5, size=nums_per_image) + 2\n        veloc = np.asarray([(speed * math.cos(direc), speed * math.sin(direc)) for direc, speed in zip(direcs, speeds)])\n        # Get a list containing two PIL images randomly sampled from the database\n        mnist_images = [Image.fromarray(img_from_arr(mnist, r, mean=0)).resize((original_size, original_size),\n                                                                               Image.ANTIALIAS) \\\n                        for r in np.random.randint(0, mnist.shape[0], nums_per_image)]\n        # Generate tuples of (x,y) i.e initial positions for nums_per_image (default : 2)\n        positions = np.asarray([(np.random.rand() * x_lim, np.random.rand() * y_lim) for _ in range(nums_per_image)])\n\n        # Generate new frames for the entire num_framesgth\n        for frame_idx in range(num_frames):\n\n            canvases = [Image.new('L', (width, height)) for _ in range(nums_per_image)]\n            canvas = np.zeros((1, width, height), dtype=np.float32)\n\n            # In canv (i.e Image object) place the image at the respective positions\n            # Super impose both images on the canvas (i.e empty np array)\n            for i, canv in enumerate(canvases):\n                canv.paste(mnist_images[i], tuple(positions[i].astype(int)))\n                canvas += arr_from_img(canv, mean=0)\n\n            # Get the next position by adding velocity\n            next_pos = positions + veloc\n\n            # Iterate over velocity and see if we hit the wall\n            # If we do then change the  (change direction)\n            for i, pos in enumerate(next_pos):\n                for j, coord in enumerate(pos):\n                    if coord < -2 or coord > lims[j] + 2:\n                        veloc[i] = list(list(veloc[i][:j]) + [-1 * veloc[i][j]] + list(veloc[i][j + 1:]))\n\n            # Make the permanent change to position by adding updated velocity\n            positions = positions + veloc\n\n            # Add the canvas to the dataset array\n            dataset[img_idx * num_frames + frame_idx] = (canvas * 255).clip(0, 255).astype(np.uint8)\n\n    return dataset\n", "meta": {"hexsha": "9797f5c7d7546955fbb390e53d509cb010d35c37", "size": 10259, "ext": "py", "lang": "Python", "max_stars_repo_path": "vp_suite/datasets/mmnist.py", "max_stars_repo_name": "dfuchss/vp-suite", "max_stars_repo_head_hexsha": "6c7e85a94652b7c0b08ab8316885993772ec09b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vp_suite/datasets/mmnist.py", "max_issues_repo_name": "dfuchss/vp-suite", "max_issues_repo_head_hexsha": "6c7e85a94652b7c0b08ab8316885993772ec09b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vp_suite/datasets/mmnist.py", "max_forks_repo_name": "dfuchss/vp-suite", "max_forks_repo_head_hexsha": "6c7e85a94652b7c0b08ab8316885993772ec09b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.3925619835, "max_line_length": 120, "alphanum_fraction": 0.6313480846, "include": true, "reason": "import numpy", "num_tokens": 2545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.17589390799145455}}
{"text": "'''\n\nAuthors: Renke Huang, Qiuhua Huang\nContact: qiuhua.huang@pnnl.gov\n\n'''\n\nimport sys, os, time, parser, math\nimport numpy as np\nimport gym, ray\nimport logz, optimizers, utils\nfrom obserfilter import RunningStat\nfrom policy_LSTM import *\nimport socket\nfrom shared_noise import *\nfrom GridPackPowerDynSimEnvDef_v2 import GridPackPowerDynSimEnv\nfrom statistics import *\n\nfolder_dir = os.path.abspath(os.path.join(os.getcwd(), \"..\"))\nprint('-----------------root path of the rlgc:', folder_dir)\n\nFAULT_BUS_CANDIDATES = [0, 1, 2, 3, 4, 5, 6, 7, 8]\nFAULT_START_TIME = 1.0\nFTD_CANDIDATES = [0.00, 0.05, 0.1]\nFAULT_CASES = [(FAULT_BUS_CANDIDATES[i], FAULT_START_TIME, FTD_CANDIDATES[j]) for i in range(len(FAULT_BUS_CANDIDATES))\n               for j in range(len(FTD_CANDIDATES))]\n\nGKE = True # whether the training is running on GKE\nEIOC = True # set this to be true if running on GKE\n\nb_debug_timing = True\nNUM_CORES = 18\n\nOB_DIM = 301\nAC_DIM = 81\n\nif GKE:\n    simu_input_file = folder_dir + '/testData/tamu2000/input_tamu2000_step005_rmgensmall30_withob_2acloads_v33_nocsv_superlu.xml'\nelse:\n    simu_input_file = folder_dir + '/testData/tamu2000/input_tamu2000_step005_rmgensmall30_withob_2acloads_v33_nocsv_eioc.xml'\n\t\nrl_config_file = folder_dir + '/testData/tamu2000/json/RLGC_RL_tamu2000_loadShedding_zone3_gp.json'\n\n\n# ======================================================================\n\n@ray.remote\nclass SingleRolloutWorker(object):\n    '''\n    responsible for doing one single rollout in the env\n    '''\n\n    def __init__(self, rollout_length, policy_params):\n\n        print('\\n\\n\\n -----------------------Set Env=GridPackPowerDynSimEnv------------------------\\n\\n\\n')\n        self.env = GridPackPowerDynSimEnv(simu_input_file, rl_config_file, force_symmetric_continuous_action=True)\n        print('\\n\\n\\n ----------------------------Set Env Done-----------------------------\\n\\n\\n')\n        self.rollout_length = rollout_length\n        self.policy_type = policy_params['type']\n        if policy_params['type'] == 'linear':\n            self.policy = LinearPolicy(policy_params)\n        elif policy_params['type'] == 'nonlinear':\n            self.policy = FullyConnectedNeuralNetworkPolicy(policy_params)\n        elif policy_params['type'] == 'LSTM':\n            self.policy = LSTMPolicy(policy_params)\n        else:\n            raise NotImplementedError\n        time.sleep(5)\n\n    def single_rollout(self, fault_tuple, weights, ob_mean, ob_std):\n        # one SingleRolloutWorker is only doing one fault case in an iter\n        # fault_tuple = FAULT_CASES[fault_case_id]\n        total_reward = 0.\n        steps = 0\n        self.policy.update_weights(weights)\n\n        # us RS for collection of observation states; restart every rollout\n        self.RS = RunningStat(shape=(OB_DIM,))\n\n        t1 = time.time()\n        ob = self.env.validate(case_Idx=0, fault_bus_idx=fault_tuple[0],\n                               fault_start_time=fault_tuple[1], fault_duration_time=fault_tuple[2])\n        t_validate = time.time() - t1\n\n        if self.policy_type == 'LSTM':\n            self.policy.reset()\n\n        t_act = 0\n        t_step = 0\n        for _ in range(self.rollout_length):\n            ob = np.asarray(ob, dtype=np.float64)\n            self.RS.push(ob)\n            normal_ob = (ob - ob_mean) / (ob_std + 1e-8)\n            t3 = time.time()\n            action_org = self.policy.act(normal_ob)\n            t4 = time.time()\n            ob, reward, done, _ = self.env.step(action_org)\n            t5 = time.time()\n            t_act += t4 - t3\n            t_step += t5 - t4\n            total_reward += reward\n            steps += 1\n            if done:\n                break\n        t2 = time.time()\n\n        if b_debug_timing:\n            return {'reward': total_reward, 'step': steps, 'time': [{'Total Time': t2 - t1},\n                                                                    {'Reset Time': t_validate},\n                                                                    {'Action Time': t_act},\n                                                                    {'Step Time': t_step} ]}\n        else:\n            return {'reward': total_reward, 'step': steps, 'time': [t2 - t1, t_validate, t_act, t_step]}\n\n    def return_RS(self):\n        return self.RS\n\n    def close_env(self):\n        self.env.close_env()\n        return\n\ndef run_ars_test(params):\n\n    # set policy parameters.\n    if params['policy_file'] != \"\":\n        nonlin_policy_org = np.load(params['policy_file'], allow_pickle=True)\n        nonlin_policy = nonlin_policy_org['arr_0']\n\n        w_M = nonlin_policy[0].copy()\n        w_mean = nonlin_policy[1].copy()\n        w_std = nonlin_policy[2].copy()\n\n        policy_params = {'type': params['policy_type'],\n                         'policy_network_size': params['policy_network_size'],\n                         'ob_dim': OB_DIM,\n                         'ac_dim': AC_DIM,\n                         'weights': w_M,\n                         'w_mean': w_mean,\n                         'w_std': w_std,\n                         }\n    else:\n        # set policy parameters.\n        policy_params = {'type': params['policy_type'],\n                         'policy_network_size': params['policy_network_size'],\n                         'ob_dim': OB_DIM,\n                         'ac_dim': AC_DIM}\n\n    single_rollout_workers = []\n    nsingleworks = min( len(FAULT_CASES), params['onedirection_numofcasestorun'])\n\n\n    #-----------just test one single worker----------------------------------------\n\n    for i in range(nsingleworks):\n        single_rollout_workers.append(SingleRolloutWorker.remote(rollout_length=150,\n                                                                      policy_params=policy_params))\n        time.sleep(2)\n\n    weights_id = ray.put(w_M)\n    ob_mean = ray.put(w_mean)\n    ob_std = ray.put(w_std)\n\n    # -----------just test one single worker----------------------------------------\n    icase = 1\n    tmp_id = single_rollout_workers[icase].single_rollout.remote(\n                fault_tuple=FAULT_CASES[icase], weights=weights_id, ob_mean=ob_mean,\n                ob_std=ob_std)\n    tmp_result = ray.get(tmp_id)\n\n    print ('-----------testing just one single roll out for fault tuple: ', FAULT_CASES[icase])\n    print (tmp_result)\n    print('----------- finished testing for just one single roll out for fault tuple: ', FAULT_CASES[icase])\n    print ('\\n')\n\n    for itr in range (5):\n\n        results_ids = []\n\n        # -----------just test different number of works for rolling out fully distributed for each itration-----------------\n        nworkers = nsingleworks//(itr+1)\n\n        print ('---------start multiple single roll outs, itr: ', itr, ', n-workers: ', nworkers)\n        print('\\n')\n        for i in range(nworkers):\n            results_ids.append(single_rollout_workers[i].single_rollout.remote(\n                fault_tuple=FAULT_CASES[i], weights=weights_id, ob_mean=ob_mean,\n                ob_std=ob_std))\n\n        results = ray.get(results_ids)\n        reward_list = []\n        step_list = []\n        time_list = []\n        for result in results:\n            reward_list.append(result['reward'])\n            step_list.append(result['step'])\n            time_list.append(result['time'])\n        reward_ave = mean(reward_list)\n\n        print ('--------------n-works: ', nworkers, ', average reward: ', reward_ave)\n        for itmp in range(len(reward_list)):\n            print('Reward: ', reward_list[itmp], ', Steps: ', step_list[itmp], ', Timing: ', time_list[itmp])\n        # ----- delete the weight in the global table in ray before return\n\n        print('\\n')\n\t\n    print ('-------------------finished all testing!!!!!!!!!!!!!--------------')\n    del weights_id\n    del ob_mean\n    del ob_std\n\n    return\n\n# Setting\nif __name__ == '__main__':\n    import argparse\n\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--n_iter', '-n', type=int, default=500)  # Number of iterations\n    if EIOC:  # EIOC test\n        parser.add_argument('--n_directions', '-nd', type=int, default=1)\n    else:  # Constance training\n        parser.add_argument('--n_directions', '-nd', type=int, default=128)\n    if EIOC:  # EIOC test\n        parser.add_argument('--deltas_used', '-du', type=int, default=2)\n    else:  # Constance training\n        parser.add_argument('--deltas_used', '-du', type=int, default=64)\n    parser.add_argument('--step_size', '-s', type=float, default=1)  # default=0.02\n    parser.add_argument('--delta_std', '-std', type=float, default=2)  # default=.03\n    parser.add_argument('--decay', type=float, default=0.995)  # decay of step_size and delta_std\n    parser.add_argument('--rollout_length', '-r', type=int, default=150)\n    parser.add_argument('--seed', type=int, default=589)  # Seed Number for randomization\n    parser.add_argument('--policy_type', type=str, default='LSTM')\n    parser.add_argument('--dir_path', type=str,\n                        default='ars_tamu2000_testrayandgridpack')  # Folder Name for outputs\n    if EIOC:  # EIOC test\n        parser.add_argument('--save_per_iter', type=int, default=1)  # save the .npz file per x iterations\n    else:  # Constance training\n        parser.add_argument('--save_per_iter', type=int, default=10)  # save the .npz file per x iterations\n    parser.add_argument('--policy_network_size', type=list, default=[64, 64])\n\n    parser.add_argument('--onedirection_numofcasestorun', type=int,\n                        default=18)  # len(FAULT_CASES))  # For each direction, how many cases to run, default is to run all the fault\n    # please set onedirection_numofcasestorun to be the multiplie of 3, such as 6,9,12,15,18, etc\n\n    # please specify number of cores here; it is to help determine the number of workers\n    if EIOC:  # EIOC test\n        parser.add_argument('--cores', type=int, default=NUM_CORES)  # how many cores available as of hardware, EIOC test\n    else:  # Constance training\n        parser.add_argument('--cores', type=int, default=NUM_CORES)  # how many cores available as of hardware\n    parser.add_argument('--policy_file', type=str, default=\"training_results/1_3faultcases/nonlinear_policy_plus490.npz\")\n\n    # the parameters controlling iterations for convergence\n    # n_iter is maximum number of iterations\n    # tol_p is tolerance for the percentage of average reward change between iterations\n    # tol_steps is the total iterations for maintaining tol_p\n    parser.add_argument('--tol_p', type=float, default=0.001)\n    parser.add_argument('--tol_steps', type=int, default=100)\n    local_ip = socket.gethostbyname(socket.gethostname())\n\n    # Init Ray in Cluster, use log_to_driver=True for printing messages from remote nodes\n    ##!!#####################################################################################################\n    # !! if you are using EIOC, use this line of code below\n    if EIOC:  # EIOC test\n        ray.init(address=\"localhost:6379\", log_to_driver=False)\n    else:\n        # !! if you are using Constance, use this line of code below\n        ray.init(temp_dir=os.environ[\"tmpfolder\"], redis_address=os.environ[\"ip_head\"], log_to_driver=False)\n    ##!!######################################################################################################\n\n    args = parser.parse_args()\n    params = vars(args)\n    t1 = time.time()\n    run_ars_test(params)\n    t2 = time.time()\n    print('Total Time run_ars:', t2 - t1)\n", "meta": {"hexsha": "627009cfd63e30d70e22e0325765f2ef7ed47ccd", "size": 11436, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/test_one_level_ray_rollout.py", "max_stars_repo_name": "pnnl/HADREC", "max_stars_repo_head_hexsha": "9341cdb601a8158ca9607d08ed42d5acdda6ffef", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test_one_level_ray_rollout.py", "max_issues_repo_name": "pnnl/HADREC", "max_issues_repo_head_hexsha": "9341cdb601a8158ca9607d08ed42d5acdda6ffef", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test_one_level_ray_rollout.py", "max_forks_repo_name": "pnnl/HADREC", "max_forks_repo_head_hexsha": "9341cdb601a8158ca9607d08ed42d5acdda6ffef", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4347826087, "max_line_length": 134, "alphanum_fraction": 0.5909408884, "include": true, "reason": "import numpy", "num_tokens": 2719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.17589390589369616}}
{"text": "# -*- coding: utf-8 -*-\nimport numpy as np\nfrom scipy import interpolate\nfrom .BaseDataProtocol.SABProtocol import dtype_sab\nfrom .util import _prepare_for_read, _unpack_from_buf, julian2date, \\\n    get_radar_info, make_time_unit_str, get_radar_sitename\nfrom netCDF4 import date2num\nfrom ..core.NRadar import PRD\nfrom ..configure.pyart_config import get_metadata, get_fillvalue\nfrom ..configure.default_config import CINRAD_field_mapping, _LIGHT_SPEED\nfrom ..core.PyartRadar import Radar\n\n\nclass SABBaseData(object):\n    \"\"\"\n    解码SA/SB/CB/SC2.0的雷达数据，仅仅对数据（dBZ, V, W）做了转换\n    \"\"\"\n\n    def __init__(self, filename, station_lon=None, station_lat=None, station_alt=None):\n        \"\"\"\n        :param filename:  radar basedata filename\n        :param station_lon:  radar station longitude //units: degree east\n        :param station_lat:  radar station latitude //units:degree north\n        :param station_alt:  radar station altitude //units: meters\n        \"\"\"\n        super(SABBaseData, self).__init__()\n        self.filename = filename\n        self.station_lon = station_lon\n        self.station_lat = station_lat\n        self.station_alt = station_alt\n        self.fid = _prepare_for_read(self.filename)\n        self.RadialNum, self.nrays = self._RadialNum_SAB_CB()  ##检查文件有无问题\n        self.radial = self._parse_radial()\n        status = np.array([istatus['RadialStatus'] for istatus in self.radial[:]])\n        self.sweep_start_ray_index = np.where((status == 0) | (status == 3))[0]\n        self.sweep_end_ray_index = np.where((status == 2) | (status == 4))[0]\n        self.nsweeps = len(self.sweep_start_ray_index)\n        self.fid.close()\n\n    def _RadialNum_SAB_CB(self):\n        \"\"\"f: a file-like object was provided, 确定雷达数据的径向字节长度\"\"\"\n        assert self.fid.read(28)[14:16] == b'\\x01\\x00', 'file in not a valid SA/SB/CB file!'\n        self.fid.seek(0, 0)  ##移动到开头\n        data_len = len(self.fid.read())\n        assert (data_len % 2432 == 0) | (data_len % 4132 == 0) | (data_len % 3132 == 0), \"file size has problems!\"\n        ###判断雷达数据类型SA/SB 或者 CB\n        if data_len % 2432 == 0:\n            RadialNum = 2432\n            self.Type = \"SAB\"\n        elif data_len % 4132 == 0:\n            RadialNum = 4132\n            self.Type = 'CB'\n        else:\n            RadialNum = 3132\n            self.Type = 'SC'\n        self.fid.seek(0, 0)  ##移动到开头\n        return RadialNum, int(data_len / RadialNum)\n\n    def _parse_radial(self):\n        \"\"\"\n        循环读取所有径向数据\n        :param fid:\n        :return:\n        \"\"\"\n        radial = []\n        for _ in range(self.nrays):\n            radial.append(self._parse_radial_single(self.fid.read(self.RadialNum)))\n        return radial\n\n    def _parse_radial_single(self, radial_buf):\n        Radial = {}\n        RadialHeader, size_tmp = _unpack_from_buf(radial_buf, 0, dtype_sab.RadialHeader())\n        Radial.update(RadialHeader)\n        dBZ = np.frombuffer(radial_buf[RadialHeader['PtrOfReflectivity'] + dtype_sab.InfSize:\\\n                                                     RadialHeader['PtrOfReflectivity'] + dtype_sab.InfSize +\\\n                                                     RadialHeader['GatesNumberOfReflectivity']],\\\n                                                    dtype=\"u1\")\n        V = np.frombuffer(radial_buf[RadialHeader['PtrOfVelocity'] + dtype_sab.InfSize: \\\n                                                     RadialHeader['PtrOfVelocity'] + dtype_sab.InfSize + \\\n                                                     RadialHeader['GatesNumberOfDoppler']], \\\n                                                    dtype=\"u1\")\n        W = np.frombuffer(radial_buf[RadialHeader['PtrOfSpectrumWidth'] + dtype_sab.InfSize: \\\n                                                   RadialHeader['PtrOfSpectrumWidth']  + dtype_sab.InfSize+ \\\n                                                   RadialHeader['GatesNumberOfDoppler']], \\\n                                                    dtype=\"u1\")\n        Radial['fields'] = {}\n        Radial['fields']['dBZ'] = np.where(dBZ > 1, (dBZ.astype(int) - 2) / 2. - 32, np.nan).astype(np.float32)\n        Radial['fields']['V'] = np.where(V > 1, (V.astype(int) - 2) / 2. - 63.5, np.nan).astype(np.float32)\n        Radial['fields']['W'] = np.where(W > 1, (W.astype(int) - 2) / 2. - 63.5, np.nan).astype(np.float32)\n        return Radial\n\n    def get_nyquist_velocity(self):\n        \"\"\"get nyquist vel per ray\n        获取每根径向的不模糊速度\n        :return:(nRays)\n        \"\"\"\n        return np.array([iradial['Nyquist'] / 100. for iradial in self.radial])\n\n    def get_unambiguous_range(self):\n        \"\"\"\n        获取每根径向的不模糊距离 units:km\n        :return:(nRays)\n        \"\"\"\n        return np.array([iradial['URange'] / 10. for iradial in self.radial])\n\n    def get_scan_time(self):\n        \"\"\"\n        获取每根径向的扫描时间\n        :return:(nRays)\n        \"\"\"\n        return np.array([julian2date(iradial['JulianDate'], iradial['mSends']) for iradial in self.radial])\n\n    def get_sweep_end_ray_index(self):\n        \"\"\"\n        获取每个sweep的结束的index，包含在内\n        :return:(nsweep)\n        \"\"\"\n        return self.sweep_end_ray_index\n\n    def get_sweep_start_ray_index(self):\n        \"\"\"\n        获取每个sweep的开始的index\n        :return:(nsweep)\n        \"\"\"\n        return self.sweep_start_ray_index\n\n    def get_rays_per_sweep(self):\n        \"\"\"\n        获取每个sweep的径向数\n        :return:(nsweep)\n        \"\"\"\n        return self.sweep_end_ray_index - self.sweep_start_ray_index + 1\n\n    def get_azimuth(self):\n        \"\"\"\n        获取每根径向的方位角\n        :return:(nRays)\n        \"\"\"\n        return np.array([iradial['AZ'] / 8. * 180. / 4096. for iradial in self.radial])\n\n    def get_elevation(self):\n        \"\"\"\n        获取每根径向的仰角\n        :return: (nRays)\n        \"\"\"\n        return np.array([iradial['El'] / 8. * 180. / 4096. for iradial in self.radial])\n\n    def get_latitude_longitude_altitude_frequency(self):\n        \"\"\"\n        获取经纬度高度，雷达频率\n        :return:lat, lon, alt, frequency\n        \"\"\"\n        lat, lon, alt, frequency = get_radar_info(self.filename)\n        if self.station_lon is not None:\n            lon = self.station_lon\n        if self.station_lat is not None:\n            lat = self.station_lat\n        if self.station_alt is not None:\n            alt = self.station_alt\n        return lat, lon, alt, frequency\n\n    def get_scan_type(self):\n        \"\"\"\n        获取扫描的类型\n        :return:\n        \"\"\"\n        return \"ppi\"\n\n    def get_sitename(self):\n        return get_radar_sitename(self.filename)\n\n\nclass SAB2NRadar(object):\n    \"\"\"到NusitRadar object 的桥梁\"\"\"\n\n    def __init__(self, SAB):\n        self.SAB = SAB\n        self.v_index_alone = self.get_v_idx()\n        self.dBZ_index_alone = self.get_dbz_idx()\n        self.dBZ_Res = self.SAB.radial[0][\"GateSizeOfReflectivity\"] ##反射率因子的分辨率\n        for index_with_dbz, index_with_v in zip(self.dBZ_index_alone, self.v_index_alone):\n            assert abs(self.SAB.get_elevation()[index_with_v] - \\\n                       self.SAB.get_elevation()[index_with_dbz]) < 0.5, \"warning! maybe it is a problem.\"\n            self.interp_dBZ(index_with_dbz, index_with_v)\n        ind_remove = self.get_reomve_radial_num()\n        self.radial = [iray for ind, iray in enumerate(self.SAB.radial) if ind not in ind_remove]\n        self.nrays = len(self.radial)\n        self.nsweeps = self.SAB.nsweeps - self.dBZ_index_alone.size\n        status = np.array([istatus['RadialStatus'] for istatus in self.radial[:]])\n        self.sweep_start_ray_index = np.where((status == 0) | (status == 3))[0]\n        self.sweep_end_ray_index = np.where((status == 2) | (status == 4))[0]\n        self.scan_type = self.SAB.get_scan_type()\n        self.latitude, self.longitude, self.altitude, self.frequency = \\\n            self.SAB.get_latitude_longitude_altitude_frequency()\n        self.bins_per_sweep = self.get_nbins_per_sweep()\n        self.max_bins = self.bins_per_sweep.max()\n        self.range = self.get_range_per_radial(self.max_bins)  ##所有的数据向多普勒数据对齐\n        self.azimuth = self.get_azimuth()\n        self.elevation = self.get_elevation()\n        self.fields = self._get_fields()\n        self.sitename = self.SAB.get_sitename()\n\n    def get_reomve_radial_num(self):\n        \"\"\"获得需要remove的radial的index\"\"\"\n        \"\"\"获得需要remove的radial的index\"\"\"\n        dBZ_alone = self.get_dbz_idx()\n        index_romove = []\n        for isweep in dBZ_alone:\n            index_romove.extend(range(self.SAB.sweep_start_ray_index[isweep], \\\n                                      self.SAB.sweep_end_ray_index[isweep] + 1))\n        return index_romove\n\n    def get_v_idx(self):\n        \"\"\"获取需要插值的sweep, 插值到有径向速度仰角\"\"\"\n        flag = np.array([((self.SAB.radial[idx]['fields'][\"V\"].size != 0) and\n                          (self.SAB.radial[idx]['fields'][\"dBZ\"].size == 0)) \\\n                         for idx in self.SAB.sweep_start_ray_index])\n        return np.where(flag == 1)[0]\n\n    def get_dbz_idx(self):\n        \"\"\"获取含有dbz的sweep\"\"\"\n        flag = np.array([((self.SAB.radial[idx]['fields'][\"V\"].size == 0) and\n                          (self.SAB.radial[idx]['fields'][\"dBZ\"].size != 0)) \\\n                         for idx in self.SAB.sweep_start_ray_index])\n        return np.where(flag == 1)[0]\n\n    def interp_dBZ(self, field_with_dBZ_num, field_without_dBZ_num):\n        \"\"\"\n        将dBZ插值到不含dBZ的仰角\n        :param field_with_dBZ_num: 要插值的sweep num, （从0开始）\n        :param field_without_dBZ_num: 要插值到的sweep num, (从0开始)  which to evaluate the interpolated values\n        :return:\n        \"\"\"\n        azimuth = self.SAB.get_azimuth()  ##\n        assert (field_with_dBZ_num + 1) == field_without_dBZ_num, \"check interp sweep!\"\n        dbz_az = azimuth[self.SAB.sweep_start_ray_index[field_with_dBZ_num]: \\\n                         self.SAB.sweep_end_ray_index[field_with_dBZ_num] + 1]\n        v_az = azimuth[self.SAB.sweep_start_ray_index[field_without_dBZ_num]: \\\n                       self.SAB.sweep_end_ray_index[field_without_dBZ_num] + 1]\n        dbz_idx = np.argmin(np.abs(dbz_az.reshape(-1, 1) - v_az.reshape(1, -1)), axis=0) + \\\n                  self.SAB.sweep_start_ray_index[field_with_dBZ_num]\n        v_idx = np.arange(self.SAB.sweep_start_ray_index[field_without_dBZ_num], \\\n                          self.SAB.sweep_end_ray_index[field_without_dBZ_num] + 1)\n        for ind_dbz, ind_v in zip(dbz_idx, v_idx):\n            self.SAB.radial[ind_v][\"fields\"]['dBZ'] = self.SAB.radial[ind_dbz][\"fields\"]['dBZ']\n\n    def get_azimuth(self):\n        \"\"\"\n        获取每根径向的方位角\n        :return:(nRays)\n        \"\"\"\n        return np.array([iradial['AZ'] / 8. * 180. / 4096. for iradial in self.radial])\n\n    def get_elevation(self):\n        \"\"\"\n        获取每根径向的仰角\n        :return: (nRays)\n        \"\"\"\n        return np.array([iradial['El'] / 8. * 180. / 4096. for iradial in self.radial])\n\n    def get_rays_per_sweep(self):\n        \"\"\"\n        获取每个sweep的径向数\n        :return:(nsweep)\n        \"\"\"\n        return self.sweep_end_ray_index - self.sweep_start_ray_index + 1\n\n    def get_scan_time(self):\n        \"\"\"\n        获取每根径向的扫描时间\n        :return:(nRays)\n        \"\"\"\n        return np.array([julian2date(iradial['JulianDate'], iradial['mSends']) for iradial in self.radial])\n\n    def get_nyquist_velocity(self):\n        \"\"\"get nyquist vel per ray\n        获取每根径向的不模糊速度\n        :return:(nRays)\n        \"\"\"\n        return np.array([iradial['Nyquist'] / 100. for iradial in self.radial])\n\n    def get_unambiguous_range(self):\n        \"\"\"\n        获取每根径向的不模糊距离\n        :return:(nRays)\n        \"\"\"\n        return np.array([iradial['URange'] / 10. for iradial in self.radial])\n\n    def get_sweep_end_ray_index(self):\n        \"\"\"\n        获取每个sweep的结束的index，包含在内\n        :return:(nsweep)\n        \"\"\"\n        return self.sweep_end_ray_index\n\n    def get_sweep_start_ray_index(self):\n        \"\"\"\n        获取每个sweep的开始的index\n        :return:(nsweep)\n        \"\"\"\n        return self.sweep_start_ray_index\n\n    def get_nbins_per_sweep(self):\n        \"\"\"\n        确定每个sweep V探测的库数\n        :return:\n        \"\"\"\n        return np.array([self.radial[idx]['fields']['V'].size for idx in self.sweep_start_ray_index])\n\n    def get_range_per_radial(self, length):\n        \"\"\"\n        确定径向每个库的距离\n        :param length:\n        :return:\n        \"\"\"\n        Resolution = self.radial[0][\"GateSizeOfDoppler\"]\n        return np.linspace(Resolution, Resolution * length, length)\n\n    def get_dbz_range_per_radial(self, length):\n        \"\"\"\n        确定径向每个库的距离\n        :param length:\n        :return:\n        \"\"\"\n        Resolution = self.dBZ_Res\n        start_range = self.radial[0][\"GateSizeOfDoppler\"]\n        return np.linspace(start_range, start_range + Resolution * (length - 1), length)\n\n    def _get_fields(self):\n        \"\"\"将所有的field的数据提取出来\"\"\"\n        fields = {}\n        field_keys = self.radial[0]['fields'].keys()\n        for ikey in field_keys:\n            fields[ikey] = np.array([self._add_or_del_field(iray['fields'], ikey) for iray in self.radial])\n        return fields\n\n    def _add_or_del_field(self, dat_fields, key):\n        \"\"\"\n        根据fields的key提取数据, 将dbz的数据和dop的数据分辨率统一\n        :param dat_fields: fields的数据\n        :param key: key words\n        :return:\n        \"\"\"\n        length = self.max_bins\n        if key == \"dBZ\":\n            dbz_range = self.get_dbz_range_per_radial(dat_fields[key].size)\n            dop_range = self.range\n            match_data = interpolate.interp1d(dbz_range, dat_fields[key], kind=\"nearest\",\n                                              bounds_error=False, fill_value=np.nan)\n            dat_ray = match_data(dop_range)\n            #print(dop_range, dbz_range)\n            #print(dat_ray)\n            return dat_ray.ravel()\n        else:\n            dat_ray = dat_fields[key]\n        if dat_ray.size >= length:\n            return (dat_ray[:length]).ravel()\n        else:\n            out = np.full((length,), np.nan)\n            out[:dat_ray.size] = dat_ray\n            return out.ravel()\n\n    def get_NRadar_nyquist_speed(self):\n        \"\"\"array shape (nsweeps)\"\"\"\n        return np.array([self.radial[idx]['Nyquist'] / 100. for idx in self.sweep_start_ray_index])\n\n    def get_NRadar_unambiguous_range(self):\n        \"\"\"array shape (nsweeps)\"\"\"\n        return np.array([self.radial[idx]['URange'] / 10. for idx in self.sweep_start_ray_index])\n\n    def get_fixed_angle(self):\n        if self.nsweeps == 9:\n            fixed_angle = np.array([0.50, 1.45, 2.40, 3.35, 4.30, 6.00, 9.00, 14.6, 19.5])\n        elif self.nsweeps == 14:\n            fixed_angle = np.array([0.50, 1.45, 2.40, 3.35, 4.30, 5.25, 6.2, 7.5, 8.7, 10, 12, 14, 16.7, 19.5])\n        elif self.nsweeps == 6:\n            fixed_angle = np.array([0.50, 1.50, 2.50, 2.50, 3.50, 4.50])\n        elif self.nsweeps == 4:\n            fixed_angle = np.array([0.50, 2.50, 3.50, 4.50])\n        else:\n            fixed_angle = np.array([self.radial[idx]['El'] / 8. * 180. / 4096. for idx in self.sweep_start_ray_index])\n        return fixed_angle\n\n    def ToPRD(self):\n        \"\"\"将WSR98D数据转为PRD的数据格式\"\"\"\n        return PRD(fields=self.fields, scan_type=self.scan_type, time=self.get_scan_time(), \\\n                          range=self.range, azimuth=self.azimuth, elevation=self.elevation, latitude=self.latitude, \\\n                          longitude=self.longitude, altitude=self.altitude,\n                          sweep_start_ray_index=self.sweep_start_ray_index, \\\n                          sweep_end_ray_index=self.sweep_end_ray_index, fixed_angle=self.get_fixed_angle(), \\\n                          bins_per_sweep=self.bins_per_sweep, nyquist_velocity=self.get_NRadar_nyquist_speed(), \\\n                          frequency=self.frequency, unambiguous_range=self.get_NRadar_unambiguous_range(), \\\n                          nrays=self.nrays, nsweeps=self.nsweeps, sitename = self.sitename, pyart_radar=self.ToPyartRadar())\n\n    def ToPyartRadar(self):\n        \"\"\"转化为Pyart Radar的对象\"\"\"\n        dts = self.get_scan_time()\n        units = make_time_unit_str(min(dts))\n        time = get_metadata('time')\n        time['units'] = units\n        time['data'] = date2num(dts, units).astype('float32')\n\n        # range\n        _range = get_metadata('range')\n        # assume that the number of gates and spacing from the first ray is\n        # representative of the entire volume\n        _range['data'] = self.range\n        _range['meters_to_center_of_first_gate'] = self.radial[0][\"GateSizeOfDoppler\"]\n        _range['meters_between_gates'] = self.radial[0][\"GateSizeOfDoppler\"]\n\n        latitude = get_metadata('latitude')\n        longitude = get_metadata('longitude')\n        altitude = get_metadata('altitude')\n        latitude['data'] = np.array([self.latitude], dtype='float64')\n        longitude['data'] = np.array([self.longitude], dtype='float64')\n        altitude['data'] = np.array([self.altitude], dtype='float64')\n\n        metadata = get_metadata('metadata')\n        metadata['original_container'] = 'CINRAD/SAB'\n        metadata['site_name'] = self.sitename\n        metadata['radar_name'] = \"CINRAD/SA/SB/CB/SC\"\n\n        sweep_start_ray_index = get_metadata('sweep_start_ray_index')\n        sweep_end_ray_index = get_metadata('sweep_end_ray_index')\n        sweep_start_ray_index['data'] = self.sweep_start_ray_index\n        sweep_end_ray_index['data'] = self.sweep_end_ray_index\n\n        sweep_number = get_metadata('sweep_number')\n        sweep_number['data'] = np.arange(self.nsweeps, dtype='int32')\n\n        scan_type = self.scan_type\n\n        sweep_mode = get_metadata('sweep_mode')\n        sweep_mode['data'] = np.array(self.nsweeps * ['azimuth_surveillance'], dtype='S')\n\n        # elevation\n        elevation = get_metadata('elevation')\n        elevation['data'] = self.elevation\n\n        # azimuth\n        azimuth = get_metadata('azimuth')\n        azimuth['data'] = self.azimuth\n\n        # fixed_angle\n        fixed_angle = get_metadata('fixed_angle')\n        fixed_angle['data'] = self.get_fixed_angle()\n\n        # instrument_parameters\n        instrument_parameters = self._get_instrument_parameters()\n\n        # fields\n        fields = {}\n        for field_name_abbr in self.fields.keys():\n            field_name = CINRAD_field_mapping[field_name_abbr]\n            if field_name is None:\n                continue\n            field_dic = get_metadata(field_name)\n            field_dic['data'] = np.ma.masked_array(self.fields[field_name_abbr],\\\n                                mask=np.isnan(self.fields[field_name_abbr]), fill_value=get_fillvalue())\n            field_dic['_FillValue'] = get_fillvalue()\n            fields[field_name] = field_dic\n\n        return Radar(time, _range, fields, metadata, scan_type,\n                     latitude, longitude, altitude,\n                     sweep_number, sweep_mode, fixed_angle, sweep_start_ray_index,\n                     sweep_end_ray_index,\n                     azimuth, elevation,\n                     instrument_parameters=instrument_parameters)\n\n    def _get_instrument_parameters(self):\n        \"\"\" Return a dictionary containing instrument parameters. \"\"\"\n\n        # pulse width\n        pulse_width = get_metadata('pulse_width')\n        pulse_width['data'] = np.array([self.radial[0][\"GateSizeOfDoppler\"] / _LIGHT_SPEED,], dtype='float32')  # m->sec\n\n        # assume that the parameters in the first ray represent the beam widths,\n        # bandwidth and frequency in the entire volume\n\n        wavelength_hz = self.frequency * 10 ** 9\n\n        # radar_beam_width_h\n        radar_beam_width_h = get_metadata('radar_beam_width_h')\n        radar_beam_width_h['data'] = np.array([1, ], dtype='float32')\n\n        # radar_beam_width_v\n        radar_beam_width_v = get_metadata('radar_beam_width_v')\n        radar_beam_width_v['data'] = np.array([1, ], dtype='float32')\n\n        # frequency\n        frequency = get_metadata('frequency')\n        frequency['data'] = np.array([wavelength_hz], dtype='float32')\n\n        instrument_parameters = {\n            'pulse_width': pulse_width,\n            'radar_beam_width_h': radar_beam_width_h,\n            'radar_beam_width_v': radar_beam_width_v,\n            'frequency': frequency, }\n\n        # nyquist velocity if defined\n        nyquist_velocity = get_metadata('nyquist_velocity')\n        nyquist_velocity['data'] = self.get_nyquist_velocity()\n        instrument_parameters['nyquist_velocity'] = nyquist_velocity\n        return instrument_parameters\n", "meta": {"hexsha": "5368c682cbac2bc90577ad57966b1fc5f7f4db28", "size": 20321, "ext": "py", "lang": "Python", "max_stars_repo_path": "pycwr/io/SABFile.py", "max_stars_repo_name": "1271756664/study", "max_stars_repo_head_hexsha": "8013dd6c597618949c5fcbf86e38502525a8136d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 144, "max_stars_repo_stars_event_min_datetime": "2019-11-27T14:36:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T08:21:17.000Z", "max_issues_repo_path": "pycwr/io/SABFile.py", "max_issues_repo_name": "flashlxy/pycwr", "max_issues_repo_head_hexsha": "98b3a19736b085205da8b6d632308e3c00ac5b7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32, "max_issues_repo_issues_event_min_datetime": "2019-11-29T10:11:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T07:46:44.000Z", "max_forks_repo_path": "pycwr/io/SABFile.py", "max_forks_repo_name": "flashlxy/pycwr", "max_forks_repo_head_hexsha": "98b3a19736b085205da8b6d632308e3c00ac5b7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 57, "max_forks_repo_forks_event_min_datetime": "2019-11-27T12:51:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T14:50:05.000Z", "avg_line_length": 40.2396039604, "max_line_length": 124, "alphanum_fraction": 0.5951478766, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.17589390589369616}}
{"text": "import os\nimport sqlite3 as db\nimport datetime\nimport socket\nimport numpy as np\nimport healpy as hp\nimport pandas as pd\nimport matplotlib.path as mplPath\nfrom rubin_sim.utils import _hpid2RaDec, xyz_angular_radius, _buildTree, _xyz_from_ra_dec\nfrom rubin_sim.site_models import FieldsDatabase\nimport rubin_sim\n\n\ndef smallest_signed_angle(a1, a2):\n    \"\"\"\n    via https://stackoverflow.com/questions/1878907/the-smallest-difference-between-2-angles\"\"\"\n    TwoPi = 2.*np.pi\n    x = a1 % TwoPi\n    y = a2 % TwoPi\n    a = (x - y) % TwoPi\n    b = (y - x) % TwoPi\n    result = b+0\n    alb = np.where(a < b)[0]\n    result[alb] = -1.*a[alb]\n    return result\n\nclass int_rounded(object):\n    \"\"\"\n    Class to help force comparisons be made on scaled up integers,\n    preventing machine precision issues cross-platforms\n\n    Parameters\n    ----------\n    inval : number-like thing\n        Some number that we want to compare\n    scale : float (1e5)\n        How much to scale inval before rounding and converting to an int.\n    \"\"\"\n    def __init__(self, inval, scale=1e5):\n        self.initial = inval\n        self.value = np.round(inval * scale).astype(int)\n        self.scale = scale\n\n    def __eq__(self, other):\n        return self.value == other.value\n\n    def __ne__(self, other):\n        return self.value != other.value\n\n    def __lt__(self, other):\n        return self.value < other.value\n\n    def __le__(self, other):\n        return self.value <= other.value\n\n    def __gt__(self, other):\n        return self.value > other.value\n\n    def __ge__(self, other):\n        return self.value >= other.value\n\n    def __repr__(self):\n        return str(self.initial)\n\n    def __add__(self, other):\n        out_scale = np.min([self.scale, other.scale])\n        result = int_rounded(self.initial + other.initial, scale=out_scale)\n        return result\n\n    def __sub__(self, other):\n        out_scale = np.min([self.scale, other.scale])\n        result = int_rounded(self.initial - other.initial, scale=out_scale)\n        return result\n\n    def __mul__(self, other):\n        out_scale = np.min([self.scale, other.scale])\n        result = int_rounded(self.initial * other.initial, scale=out_scale)\n        return result\n\n    def __div__(self, other):\n        out_scale = np.min([self.scale, other.scale])\n        result = int_rounded(self.initial / other.initial, scale=out_scale)\n        return result\n\n\ndef set_default_nside(nside=None):\n    \"\"\"\n    Utility function to set a default nside value across the scheduler.\n\n    XXX-there might be a better way to do this.\n\n    Parameters\n    ----------\n    nside : int (None)\n        A valid healpixel nside.\n    \"\"\"\n    if not hasattr(set_default_nside, 'nside'):\n        if nside is None:\n            nside = 32\n        set_default_nside.nside = nside\n    if nside is not None:\n        set_default_nside.nside = nside\n    return set_default_nside.nside\n\n\ndef restore_scheduler(observationId, scheduler, observatory, filename, filter_sched=None):\n    \"\"\"Put the scheduler and observatory in the state they were in. Handy for checking reward fucnction\n\n    Parameters\n    ----------\n    observationId : int\n        The ID of the last observation that should be completed\n    scheduler : rubin_sim.scheduler.scheduler object\n        Scheduler object.\n    observatory : rubin_sim.schedler.observatory.Model_observatory\n        The observaotry object\n    filename : str\n        The output sqlite dayabase to use\n    filter_sched : rubin_sim.scheduler.scheduler object\n        The filter scheduler. Note that we don't look up the official end of the previous night,\n        so there is potential for the loaded filters to not match.\n    \"\"\"\n    sc = schema_converter()\n    # load up the observations\n    observations = sc.opsim2obs(filename)\n    good_obs = np.where(observations['ID'] <= observationId)[0]\n    observations = observations[good_obs]\n\n    # replay the observations back into the scheduler\n    for obs in observations:\n        scheduler.add_observation(obs)\n        if filter_sched is not None:\n            filter_sched.add_observation(obs)\n\n    if filter_sched is not None:\n        # Make sure we have mounted the right filters for the night\n        # XXX--note, this might not be exact, but should work most of the time.\n        mjd_start_night = np.min(observations['mjd'][np.where(observations['night'] == obs['night'])])\n        observatory.mjd = mjd_start_night\n        conditions = observatory.return_conditions()\n        filters_needed = filter_sched(conditions)\n    else:\n        filters_needed = ['u', 'g', 'r', 'i', 'y']\n\n    # update the observatory\n    observatory.mjd = obs['mjd'] + observatory.observatory.visit_time(obs)/3600./24.\n    observatory.observatory.parked = False\n    observatory.observatory.current_RA_rad = obs['RA']\n    observatory.observatory.current_dec_rad = obs['dec']\n    observatory.observatory.current_rotSkyPos_rad = obs['rotSkyPos']\n    observatory.observatory.cumulative_azimuth_rad = obs['cummTelAz']\n    observatory.observatory.mounted_filters = filters_needed\n    # Note that we haven't updated last_az_rad, etc, but those values should be ignored.\n\n    return scheduler, observatory\n\n\ndef int_binned_stat(ids, values, statistic=np.mean):\n    \"\"\"\n    Like scipy.binned_statistic, but for unique int ids\n    \"\"\"\n\n    uids = np.unique(ids)\n    order = np.argsort(ids)\n\n    ordered_ids = ids[order]\n    ordered_values = values[order]\n\n    left = np.searchsorted(ordered_ids, uids, side='left')\n    right = np.searchsorted(ordered_ids, uids, side='right')\n\n    stat_results = []\n    for le, ri in zip(left, right):\n        stat_results.append(statistic(ordered_values[le:ri]))\n\n    return uids, np.array(stat_results)\n\n\ndef gnomonic_project_toxy(RA1, Dec1, RAcen, Deccen):\n    \"\"\"Calculate x/y projection of RA1/Dec1 in system with center at RAcen, Deccen.\n    Input radians. Grabbed from sims_selfcal\"\"\"\n    # also used in Global Telescope Network website\n    cosc = np.sin(Deccen) * np.sin(Dec1) + np.cos(Deccen) * np.cos(Dec1) * np.cos(RA1-RAcen)\n    x = np.cos(Dec1) * np.sin(RA1-RAcen) / cosc\n    y = (np.cos(Deccen)*np.sin(Dec1) - np.sin(Deccen)*np.cos(Dec1)*np.cos(RA1-RAcen)) / cosc\n    return x, y\n\n\ndef gnomonic_project_tosky(x, y, RAcen, Deccen):\n    \"\"\"Calculate RA/Dec on sky of object with x/y and RA/Cen of field of view.\n    Returns Ra/Dec in radians.\"\"\"\n    denom = np.cos(Deccen) - y * np.sin(Deccen)\n    RA = RAcen + np.arctan2(x, denom)\n    Dec = np.arctan2(np.sin(Deccen) + y * np.cos(Deccen), np.sqrt(x*x + denom*denom))\n    return RA, Dec\n\n\ndef match_hp_resolution(in_map, nside_out, UNSEEN2nan=True):\n    \"\"\"Utility to convert healpix map resolution if needed and change hp.UNSEEN values to\n    np.nan.\n\n    Parameters\n    ----------\n    in_map : np.array\n        A valie healpix map\n    nside_out : int\n        The desired resolution to convert in_map to\n    UNSEEN2nan : bool (True)\n        If True, convert any hp.UNSEEN values to np.nan\n    \"\"\"\n    current_nside = hp.npix2nside(np.size(in_map))\n    if current_nside != nside_out:\n        out_map = hp.ud_grade(in_map, nside_out=nside_out)\n    else:\n        out_map = in_map\n    if UNSEEN2nan:\n        out_map[np.where(out_map == hp.UNSEEN)] = np.nan\n    return out_map\n\n\ndef raster_sort(x0, order=['x', 'y'], xbin=1.):\n    \"\"\"XXXX--depriciated, use tsp instead.\n\n    Do a sort to scan a grid up and down. Simple starting guess to traveling salesman.\n\n    Parameters\n    ----------\n    x0 : array\n    order : list\n        Keys for the order x0 should be sorted in.\n    xbin : float (1.)\n        The binsize to round off the first coordinate into\n\n    returns\n    -------\n    array sorted so that it rasters up and down.\n    \"\"\"\n    coords = x0.copy()\n    bins = np.arange(coords[order[0]].min()-xbin/2., coords[order[0]].max()+3.*xbin/2., xbin)\n    # digitize my bins\n    coords[order[0]] = np.digitize(coords[order[0]], bins)\n    order1 = np.argsort(coords, order=order)\n    coords = coords[order1]\n    places_to_invert = np.where(np.diff(coords[order[-1]]) < 0)[0]\n    if np.size(places_to_invert) > 0:\n        places_to_invert += 1\n        indx = np.arange(coords.size)\n        index_sorted = np.zeros(indx.size, dtype=int)\n        index_sorted[0:places_to_invert[0]] = indx[0:places_to_invert[0]]\n\n        for i, inv_pt in enumerate(places_to_invert[:-1]):\n            if i % 2 == 0:\n                index_sorted[inv_pt:places_to_invert[i+1]] = indx[inv_pt:places_to_invert[i+1]][::-1]\n            else:\n                index_sorted[inv_pt:places_to_invert[i+1]] = indx[inv_pt:places_to_invert[i+1]]\n\n        if np.size(places_to_invert) % 2 != 0:\n            index_sorted[places_to_invert[-1]:] = indx[places_to_invert[-1]:][::-1]\n        else:\n            index_sorted[places_to_invert[-1]:] = indx[places_to_invert[-1]:]\n        return order1[index_sorted]\n    else:\n        return order1\n\n\nclass schema_converter(object):\n    \"\"\"\n    Record how to convert an observation array to the standard opsim schema\n    \"\"\"\n    def __init__(self):\n        # Conversion dictionary, keys are opsim schema, values are observation dtype names\n        self.convert_dict = {'observationId': 'ID', 'night': 'night',\n                             'observationStartMJD': 'mjd',\n                             'observationStartLST': 'lmst', 'numExposures': 'nexp',\n                             'visitTime': 'visittime', 'visitExposureTime': 'exptime',\n                             'proposalId': 'survey_id', 'fieldId': 'field_id',\n                             'fieldRA': 'RA', 'fieldDec': 'dec', 'altitude': 'alt', 'azimuth': 'az',\n                             'filter': 'filter', 'airmass': 'airmass', 'skyBrightness': 'skybrightness',\n                             'cloud': 'clouds', 'seeingFwhm500': 'FWHM_500',\n                             'seeingFwhmGeom': 'FWHM_geometric', 'seeingFwhmEff': 'FWHMeff',\n                             'fiveSigmaDepth': 'fivesigmadepth', 'slewTime': 'slewtime',\n                             'slewDistance': 'slewdist', 'paraAngle': 'pa', 'rotTelPos': 'rotTelPos',\n                             'rotSkyPos': 'rotSkyPos', 'moonRA': 'moonRA',\n                             'moonDec': 'moonDec', 'moonAlt': 'moonAlt', 'moonAz': 'moonAz',\n                             'moonDistance': 'moonDist', 'moonPhase': 'moonPhase',\n                             'sunAlt': 'sunAlt', 'sunAz': 'sunAz', 'solarElong': 'solarElong', 'note':'note'}\n        # Column(s) not bothering to remap:  'observationStartTime': None,\n        self.inv_map = {v: k for k, v in self.convert_dict.items()}\n        # angles to converts\n        self.angles_rad2deg = ['fieldRA', 'fieldDec', 'altitude', 'azimuth', 'slewDistance',\n                               'paraAngle', 'rotTelPos', 'rotSkyPos', 'moonRA', 'moonDec',\n                               'moonAlt', 'moonAz', 'moonDistance', 'sunAlt', 'sunAz', 'solarElong',\n                               'cummTelAz']\n        # Put LMST into degrees too\n        self.angles_hours2deg = ['observationStartLST']\n\n    def obs2opsim(self, obs_array, filename=None, info=None, delete_past=False):\n        \"\"\"convert an array of observations into a pandas dataframe with Opsim schema\n        \"\"\"\n        if delete_past:\n            try:\n                os.remove(filename)\n            except OSError:\n                pass\n\n        df = pd.DataFrame(obs_array)\n        df = df.rename(index=str, columns=self.inv_map)\n        for colname in self.angles_rad2deg:\n            df[colname] = np.degrees(df[colname])\n        for colname in self.angles_hours2deg:\n            df[colname] = df[colname] * 360./24.\n\n        if filename is not None:\n            con = db.connect(filename)\n            df.to_sql('observations', con, index=False)\n            if info is not None:\n                df = pd.DataFrame(info)\n                df.to_sql('info', con)\n\n    def opsim2obs(self, filename):\n        \"\"\"convert an opsim schema dataframe into an observation array.\n        \"\"\"\n\n        con = db.connect(filename)\n        df = pd.read_sql('select * from observations;', con)\n        for key in self.angles_rad2deg:\n            df[key] = np.radians(df[key])\n        for key in self.angles_hours2deg:\n            df[key] = df[key] * 24./360.\n\n        df = df.rename(index=str, columns=self.convert_dict)\n\n        blank = empty_observation()\n        final_result = np.empty(df.shape[0], dtype=blank.dtype)\n        # XXX-ugh, there has to be a better way.\n        for i, key in enumerate(df.columns):\n            if key in self.inv_map.keys():\n                final_result[key] = df[key].values\n\n        return final_result\n\n\ndef empty_observation():\n    \"\"\"Return a numpy array that could be a handy observation record\n\n    XXX:  Should this really be \"empty visit\"? Should we have \"visits\" made\n    up of multple \"observations\" to support multi-exposure time visits?\n\n    XXX-Could add a bool flag for \"observed\". Then easy to track all proposed\n    observations. Could also add an mjd_min, mjd_max for when an observation should be observed.\n    That way we could drop things into the queue for DD fields.\n\n    XXX--might be nice to add a generic \"sched_note\" str field, to record any metadata that\n    would be useful to the scheduler once it's observed. and/or observationID.\n\n    Returns\n    -------\n    numpy array\n\n\n    The numpy fields have the following structure\n    RA : float\n       The Right Acension of the observation (center of the field) (Radians)\n    dec : float\n       Declination of the observation (Radians)\n    mjd : float\n       Modified Julian Date at the start of the observation (time shutter opens)\n    exptime : float\n       Total exposure time of the visit (seconds)\n    filter : str\n        The filter used. Should be one of u, g, r, i, z, y.\n    rotSkyPos : float\n        The rotation angle of the camera relative to the sky E of N (Radians)\n    nexp : int\n        Number of exposures in the visit.\n    airmass : float\n        Airmass at the center of the field\n    FWHMeff : float\n        The effective seeing FWHM at the center of the field. (arcsec)\n    skybrightness : float\n        The surface brightness of the sky background at the center of the\n        field. (mag/sq arcsec)\n    night : int\n        The night number of the observation (days)\n    flush_by_mjd : float\n        If we hit this MJD, we should flush the queue and refill it.\n    cummTelAz : float\n        The cummulative telescope rotation in azimuth\n    \"\"\"\n\n    names = ['ID', 'RA', 'dec', 'mjd', 'flush_by_mjd', 'exptime', 'filter', 'rotSkyPos', 'nexp',\n             'airmass', 'FWHM_500', 'FWHMeff', 'FWHM_geometric', 'skybrightness', 'night',\n             'slewtime', 'visittime', 'slewdist', 'fivesigmadepth',\n             'alt', 'az', 'pa', 'clouds', 'moonAlt', 'sunAlt', 'note',\n             'field_id', 'survey_id', 'block_id',\n             'lmst', 'rotTelPos', 'moonAz', 'sunAz', 'sunRA', 'sunDec', 'moonRA', 'moonDec',\n             'moonDist', 'solarElong', 'moonPhase', 'cummTelAz']\n\n    types = [int, float, float, float, float, float, 'U1', float, int,\n             float, float, float, float, float, int,\n             float, float, float, float,\n             float, float, float, float, float, float, 'U40',\n             int, int, int,\n             float, float, float, float, float, float, float, float,\n             float, float, float, float]\n    result = np.zeros(1, dtype=list(zip(names, types)))\n    return result\n\n\ndef scheduled_observation():\n    \"\"\"Make an array for pre-scheduling observations\n\n    mjd_tol : float\n        The tolerance on how early an observation can execute (days).\n\n    \"\"\"\n\n    # Standard things from the usual observations\n    names = ['ID', 'RA', 'dec', 'mjd', 'flush_by_mjd', 'exptime', 'filter', 'rotSkyPos', 'nexp',\n             'note']\n    types = [int, float, float, float, float, float, 'U1', float, float, 'U40']\n    names += ['mjd_tol', 'dist_tol', 'alt_min', 'alt_max', 'HA_max', 'HA_min', 'observed']\n    types += [float, float, float, float, float, float, bool]\n    result = np.zeros(1, dtype=list(zip(names, types)))\n    return result\n\n\ndef read_fields():\n    \"\"\"Read in the Field coordinates\n\n    Returns\n    -------\n    fields : `numpy.array`\n        With RA and dec in radians.\n    \"\"\"\n    query = 'select fieldId, fieldRA, fieldDEC from Field;'\n    fd = FieldsDatabase()\n    fields = np.array(list(fd.get_field_set(query)))\n    # order by field ID\n    fields = fields[fields[:,0].argsort()]\n\n    names = ['RA', 'dec']\n    types = [float, float]\n    result = np.zeros(np.size(fields[:, 1]), dtype=list(zip(names, types)))\n    result['RA'] = np.radians(fields[:, 1])\n    result['dec'] = np.radians(fields[:, 2])\n\n    return result\n\n\ndef hp_kd_tree(nside=None, leafsize=100, scale=1e5):\n    \"\"\"\n    Generate a KD-tree of healpixel locations\n\n    Parameters\n    ----------\n    nside : int\n        A valid healpix nside\n    leafsize : int (100)\n        Leafsize of the kdtree\n\n    Returns\n    -------\n    tree : scipy kdtree\n    \"\"\"\n    if nside is None:\n        nside = set_default_nside()\n\n    hpid = np.arange(hp.nside2npix(nside))\n    ra, dec = _hpid2RaDec(nside, hpid)\n    return _buildTree(ra, dec, leafsize, scale=scale)\n\n\nclass hp_in_lsst_fov(object):\n    \"\"\"\n    Return the healpixels within a pointing. A very simple LSST camera model with\n    no chip/raft gaps.\n    \"\"\"\n    def __init__(self, nside=None, fov_radius=1.75, scale=1e5):\n        \"\"\"\n        Parameters\n        ----------\n        fov_radius : float (1.75)\n            Radius of the filed of view in degrees\n        \"\"\"\n        if nside is None:\n            nside = set_default_nside()\n\n        self.tree = hp_kd_tree(nside=nside, scale=scale)\n        self.radius = np.round(xyz_angular_radius(fov_radius)*scale).astype(int)\n        self.scale = scale\n\n    def __call__(self, ra, dec, **kwargs):\n        \"\"\"\n        Parameters\n        ----------\n        ra : float\n            RA in radians\n        dec : float\n            Dec in radians\n\n        Returns\n        -------\n        indx : numpy array\n            The healpixels that are within the FoV\n        \"\"\"\n\n        x, y, z = _xyz_from_ra_dec(np.max(ra), np.max(dec))\n        x = np.round(x * self.scale).astype(int)\n        y = np.round(y * self.scale).astype(int)\n        z = np.round(z * self.scale).astype(int)\n\n        indices = self.tree.query_ball_point((x, y, z), self.radius)\n        return np.array(indices)\n\n\nclass hp_in_comcam_fov(object):\n    \"\"\"\n    Return the healpixels within a ComCam pointing. Simple camera model\n    with no chip gaps.\n    \"\"\"\n    def __init__(self, nside=None, side_length=0.7):\n        \"\"\"\n        Parameters\n        ----------\n        side_length : float (0.7)\n            The length of one side of the square field of view (degrees).\n        \"\"\"\n        if nside is None:\n            nside = set_default_nside()\n        self.nside = nside\n        self.tree = hp_kd_tree(nside=nside)\n        self.side_length = np.radians(side_length)\n        self.inner_radius = xyz_angular_radius(side_length/2.)\n        self.outter_radius = xyz_angular_radius(side_length/2.*np.sqrt(2.))\n        # The positions of the raft corners, unrotated\n        self.corners_x = np.array([-self.side_length/2., -self.side_length/2., self.side_length/2.,\n                                  self.side_length/2.])\n        self.corners_y = np.array([self.side_length/2., -self.side_length/2., -self.side_length/2.,\n                                  self.side_length/2.])\n\n    def __call__(self, ra, dec, rotSkyPos=0.):\n        \"\"\"\n        Parameters\n        ----------\n        ra : float\n            RA in radians\n        dec : float\n            Dec in radians\n        rotSkyPos : float\n            The rotation angle of the camera in radians\n        Returns\n        -------\n        indx : numpy array\n            The healpixels that are within the FoV\n        \"\"\"\n        x, y, z = _xyz_from_ra_dec(np.max(ra), np.max(dec))\n        # Healpixels within the inner circle\n        indices = self.tree.query_ball_point((x, y, z), self.inner_radius)\n        # Healpixels withing the outer circle\n        indices_all = np.array(self.tree.query_ball_point((x, y, z), self.outter_radius))\n        indices_to_check = indices_all[np.in1d(indices_all, indices, invert=True)]\n\n        cos_rot = np.cos(rotSkyPos)\n        sin_rot = np.sin(rotSkyPos)\n        x_rotated = self.corners_x*cos_rot - self.corners_y*sin_rot\n        y_rotated = self.corners_x*sin_rot + self.corners_y*cos_rot\n\n        # Draw the square that we want to check if points are in.\n        bbPath = mplPath.Path(np.array([[x_rotated[0], y_rotated[0]],\n                                       [x_rotated[1], y_rotated[1]],\n                                       [x_rotated[2], y_rotated[2]],\n                                       [x_rotated[3], y_rotated[3]],\n                                       [x_rotated[0], y_rotated[0]]]))\n\n        ra_to_check, dec_to_check = _hpid2RaDec(self.nside, indices_to_check)\n\n        # Project the indices to check to the tangent plane, see if they fall inside the polygon\n        x, y = gnomonic_project_toxy(ra_to_check, dec_to_check, ra, dec)\n        for i, xcheck in enumerate(x):\n            # I wonder if I can do this all at once rather than a loop?\n            if bbPath.contains_point((x[i], y[i])):\n                indices.append(indices_to_check[i])\n\n        return np.array(indices)\n\n\ndef run_info_table(observatory, extra_info=None):\n    \"\"\"\n    Make a little table for recording the information about a run\n    \"\"\"\n\n    observatory_info = observatory.get_info()\n    if extra_info is not None:\n        for key in extra_info:\n            observatory_info.append([key, extra_info[key]])\n    observatory_info = np.array(observatory_info)\n\n    n_feature_entries = 3\n\n    names = ['Parameter', 'Value']\n    dtypes = ['|U200', '|U200']\n    result = np.zeros(observatory_info[:, 0].size + n_feature_entries,\n                      dtype=list(zip(names, dtypes)))\n\n    # Fill in info about the run\n    result[0]['Parameter'] = 'Date, ymd'\n    now = datetime.datetime.now()\n    result[0]['Value'] = '%i, %i, %i' % (now.year, now.month, now.day)\n\n    result[1]['Parameter'] = 'hostname'\n    result[1]['Value'] = socket.gethostname()\n\n    result[2]['Parameter'] = 'rubin_sim.__version__'\n    result[2]['Value'] = rubin_sim.__version__\n\n    result[3:]['Parameter'] = observatory_info[:, 0]\n    result[3:]['Value'] = observatory_info[:, 1]\n\n    return result\n\n\ndef inrange(inval, minimum=-1., maximum=1.):\n    \"\"\"\n    Make sure values are within min/max\n    \"\"\"\n    inval = np.array(inval)\n    below = np.where(inval < minimum)\n    inval[below] = minimum\n    above = np.where(inval > maximum)\n    inval[above] = maximum\n    return inval\n\n\ndef warm_start(scheduler, observations, mjd_key='mjd'):\n    \"\"\"Replay a list of observations into the scheduler\n\n    Parameters\n    ----------\n    scheduler : scheduler object\n    observations : np.array\n        An array of observation (e.g., from sqlite2observations)\n    \"\"\"\n\n    # Check that observations are in order\n    observations.sort(order=mjd_key)\n    for observation in observations:\n        scheduler.add_observation(observation)\n\n    return scheduler\n\n\ndef season_calc(night, offset=0, modulo=None, max_season=None, season_length=365.25, floor=True):\n    \"\"\"\n    Compute what season a night is in with possible offset and modulo\n    using convention that night -365 to 0 is season -1.\n\n    Parameters\n    ----------\n    night : int or array\n        The night we want to convert to a season\n    offset : float or array (0)\n        Offset to be applied to night (days)\n    modulo : int (None)\n        If the season should be modulated (i.e., so we can get all even years)\n        (seasons, years w/default season_length)\n    max_season : int (None)\n        For any season above this value (before modulo), set to -1\n    season_length : float (365.25)\n        How long to consider one season (nights)\n    floor : bool (True)\n        If true, take the floor of the season. Otherwise, returns season as a float\n    \"\"\"\n    if np.size(night) == 1:\n        night = np.ravel(np.array([night]))\n    result = night + offset\n    result = result/season_length\n    if floor:\n        result = np.floor(result)\n    if max_season is not None:\n        over_indx = np.where(int_rounded(result) >= int_rounded(max_season))\n\n    if modulo is not None:\n        neg = np.where(int_rounded(result) < int_rounded(0))\n        result = result % modulo\n        result[neg] = -1\n    if max_season is not None:\n        result[over_indx] = -1\n    if floor:\n        result = result.astype(int)\n    return result\n\n\ndef create_season_offset(nside, sun_RA_rad):\n    \"\"\"\n    Make an offset map so seasons roll properly\n    \"\"\"\n    hpindx = np.arange(hp.nside2npix(nside))\n    ra, dec = _hpid2RaDec(nside, hpindx)\n    offset = ra - sun_RA_rad + 2.*np.pi\n    offset = offset % (np.pi*2)\n    offset = offset * 365.25/(np.pi*2)\n    offset = -offset - 365.25\n    return offset\n\n\nclass TargetoO(object):\n    \"\"\"Class to hold information about a target of opportunity object\n\n    Parameters\n    ----------\n    tooid : int\n        Unique ID for the ToO.\n    footprints : np.array\n        np.array healpix maps. 1 for areas to observe, 0 for no observe.\n    mjd_start : float\n        The MJD the ToO starts\n    duration : float\n       Duration of the ToO (days).\n    \"\"\"\n    def __init__(self, tooid, footprint, mjd_start, duration):\n        self.footprint = footprint\n        self.duration = duration\n        self.id = tooid\n        self.mjd_start = mjd_start\n\n\nclass Sim_targetoO_server(object):\n    \"\"\"Wrapper to deliver a targetoO object at the right time\n    \"\"\"\n\n    def __init__(self, targetoO_list):\n        self.targetoO_list = targetoO_list\n        self.mjd_starts = np.array([too.mjd_start for too in self.targetoO_list])\n        durations = np.array([too.duration for too in self.targetoO_list])\n        self.mjd_ends = self.mjd_starts + durations\n\n    def __call__(self, mjd):\n        in_range = np.where((mjd > self.mjd_starts) & (mjd < self.mjd_ends))[0]\n        result = None\n        if in_range.size > 0:\n            result = [self.targetoO_list[i] for i in in_range]\n        return result\n", "meta": {"hexsha": "502a02bca3dec648e2c7a6e4c238bafae75e6c87", "size": 26166, "ext": "py", "lang": "Python", "max_stars_repo_path": "rubin_sim/scheduler/utils/utils.py", "max_stars_repo_name": "RileyWClarke/flarubin", "max_stars_repo_head_hexsha": "eb7b1ee21c828523f8a5374fe4510fe6e5ec2a2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rubin_sim/scheduler/utils/utils.py", "max_issues_repo_name": "RileyWClarke/flarubin", "max_issues_repo_head_hexsha": "eb7b1ee21c828523f8a5374fe4510fe6e5ec2a2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rubin_sim/scheduler/utils/utils.py", "max_forks_repo_name": "RileyWClarke/flarubin", "max_forks_repo_head_hexsha": "eb7b1ee21c828523f8a5374fe4510fe6e5ec2a2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1693548387, "max_line_length": 109, "alphanum_fraction": 0.61453795, "include": true, "reason": "import numpy", "num_tokens": 6738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.17589390589369616}}
{"text": "# Noel C. F. Codella\n# Example Triplet Loss Code for Keras / TensorFlow\n\n# Implementing Improved Triplet Loss from:\n# Zhang et al. \"Tracking Persons-of-Interest via Adaptive Discriminative Features\" ECCV 2016\n\n# Got help from multiple web sources, including:\n# 1) https://stackoverflow.com/questions/47727679/triplet-model-for-image-retrieval-from-the-keras-pretrained-network\n# 2) https://ksaluja15.github.io/Learning-Rate-Multipliers-in-Keras/\n# 3) https://keras.io/preprocessing/image/\n# 4) https://github.com/keras-team/keras/issues/3386\n# 5) https://github.com/keras-team/keras/issues/8130\n\n\n# GLOBAL DEFINES\nT_G_WIDTH = 224\nT_G_HEIGHT = 224\nT_G_NUMCHANNELS = 3\nT_G_SEED = 1337\n\n# Misc. Necessities\nimport sys\nimport ssl # these two lines solved issues loading pretrained model\nssl._create_default_https_context = ssl._create_unverified_context\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\nfrom scipy.misc import imresize\nnp.random.seed(T_G_SEED)\n\n# TensorFlow Includes\nimport tensorflow as tf\n#from tensorflow.contrib.losses import metric_learning\ntf.set_random_seed(T_G_SEED)\n\n# Keras Imports & Defines \nimport keras\nimport keras.applications\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras import optimizers\nimport keras.layers as kl\n\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# Generator object for data augmentation.\n# Can change values here to affect augmentation style.\ndatagen = ImageDataGenerator(  rotation_range=90,\n                                width_shift_range=0.05,\n                                height_shift_range=0.05,\n                                zoom_range=0.1,\n                                horizontal_flip=True,\n                                vertical_flip=True,\n                                )\n\n# Local Imports\nfrom LR_SGD import LR_SGD\n\n# generator function for data augmentation\ndef createDataGen(X1, X2, X3, Y, b):\n\n    local_seed = T_G_SEED\n    genX1 = datagen.flow(X1,Y, batch_size=b, seed=local_seed, shuffle=False)\n    genX2 = datagen.flow(X2,Y, batch_size=b, seed=local_seed, shuffle=False)\n    genX3 = datagen.flow(X3,Y, batch_size=b, seed=local_seed, shuffle=False)\n    while True:\n            X1i = genX1.next()\n            X2i = genX2.next()\n            X3i = genX3.next()\n\n            yield [X1i[0], X2i[0], X3i[0]], X1i[1]\n\n\ndef createModel(emb_size):\n\n    # Initialize a ResNet50_ImageNet Model\n    resnet_input = kl.Input(shape=(T_G_WIDTH,T_G_HEIGHT,T_G_NUMCHANNELS))\n    resnet_model = keras.applications.resnet50.ResNet50(weights='imagenet', include_top = False, input_tensor=resnet_input)\n\n    # New Layers over ResNet50\n    net = resnet_model.output\n    #net = kl.Flatten(name='flatten')(net)\n    net = kl.GlobalAveragePooling2D(name='gap')(net)\n    #net = kl.Dropout(0.5)(net)\n    net = kl.Dense(emb_size,activation='relu',name='t_emb_1')(net)\n    net = kl.Lambda(lambda  x: K.l2_normalize(x,axis=1), name='t_emb_1_l2norm')(net)\n\n    # model creation\n    base_model = Model(resnet_model.input, net, name=\"base_model\")\n\n    # triplet framework, shared weights\n    input_shape=(T_G_WIDTH,T_G_HEIGHT,T_G_NUMCHANNELS)\n    input_anchor = kl.Input(shape=input_shape, name='input_anchor')\n    input_positive = kl.Input(shape=input_shape, name='input_pos')\n    input_negative = kl.Input(shape=input_shape, name='input_neg')\n\n    net_anchor = base_model(input_anchor)\n    net_positive = base_model(input_positive)\n    net_negative = base_model(input_negative)\n\n    # The Lamda layer produces output using given function. Here its Euclidean distance.\n    positive_dist = kl.Lambda(euclidean_distance, name='pos_dist')([net_anchor, net_positive])\n    negative_dist = kl.Lambda(euclidean_distance, name='neg_dist')([net_anchor, net_negative])\n    tertiary_dist = kl.Lambda(euclidean_distance, name='ter_dist')([net_positive, net_negative])\n\n    # This lambda layer simply stacks outputs so both distances are available to the objective\n    stacked_dists = kl.Lambda(lambda vects: K.stack(vects, axis=1), name='stacked_dists')([positive_dist, negative_dist, tertiary_dist])\n\n    model = Model([input_anchor, input_positive, input_negative], stacked_dists, name='triple_siamese')\n\n    # Setting up optimizer designed for variable learning rate\n\n    # Variable Learning Rate per Layers\n    lr_mult_dict = {}\n    last_layer = ''\n    for layer in resnet_model.layers:\n        # comment this out to refine earlier layers\n        # layer.trainable = False  \n        # print layer.name\n        lr_mult_dict[layer.name] = 1\n        # last_layer = layer.name\n    lr_mult_dict['t_emb_1'] = 100\n\n    base_lr = 0.0001\n    momentum = 0.9\n    v_optimizer = LR_SGD(lr=base_lr, momentum=momentum, decay=0.0, nesterov=False, multipliers = lr_mult_dict)\n\n    model.compile(optimizer=v_optimizer, loss=triplet_loss, metrics=[accuracy])\n\n    return model\n\n\ndef triplet_loss(y_true, y_pred):\n    margin = K.constant(1)\n    return K.mean(K.maximum(K.constant(0), K.square(y_pred[:,0,0]) - 0.5*(K.square(y_pred[:,1,0])+K.square(y_pred[:,2,0])) + margin))\n\ndef accuracy(y_true, y_pred):\n    return K.mean(y_pred[:,0,0] < y_pred[:,1,0])\n\ndef l2Norm(x):\n    return  K.l2_normalize(x, axis=-1)\n\ndef euclidean_distance(vects):\n    x, y = vects\n    return K.sqrt(K.maximum(K.sum(K.square(x - y), axis=1, keepdims=True), K.epsilon()))\n\n\n# loads an image and preprocesses\ndef t_read_image(loc):\n    t_image = cv2.imread(loc)\n    t_image = cv2.resize(t_image, (T_G_HEIGHT,T_G_WIDTH))\n    t_image = t_image.astype(\"float32\")\n    t_image = keras.applications.resnet50.preprocess_input(t_image, data_format='channels_last')\n\n    return t_image\n\n# loads a set of images from a text index file   \ndef t_read_image_list(flist, start, length):\n\n    with open(flist) as f:\n        content = f.readlines() \n    content = [x.strip().split()[0] for x in content] \n\n    datalen = length\n    if (datalen < 0):\n        datalen = len(content)\n\n    if (start + datalen > len(content)):\n        datalen = len(content) - start\n \n    imgset = np.zeros((datalen, T_G_HEIGHT, T_G_WIDTH, T_G_NUMCHANNELS))\n\n    for i in range(start, start+datalen):\n        if ((i-start) < len(content)):\n            imgset[i-start] = t_read_image(content[i])\n\n    return imgset\n\n\ndef file_numlines(fn):\n    with open(fn) as f:\n        return sum(1 for _ in f)\n\n\ndef main(argv):\n\n    if len(argv) < 2:\n        print 'Usage: \\n\\t -learn <Train Anchors (TXT)> <Train Positives (TXT)> <Train Negatives (TXT)> <Val Anchors (TXT)> <Val Positives (TXT)> <Val Negatives (TXT)> <embedding size> <batch size> <num epochs> <output model prefix> \\n\\t -extract <Model Prefix> <Input Image List (TXT)> <Output File (TXT)> \\n\\t\\tBuilds and scores a triplet-loss model '\n        return\n\n    if 'learn' in argv[0]:\n        learn(argv[1:])\n    elif 'extract' in argv[0]:\n        extract(argv[1:])    \n\n    return\n\n\ndef extract(argv):\n\n    if len(argv) < 3:\n        print 'Usage: \\n\\t <Model Prefix> <Input Image List (TXT)> <Output File (TXT)> \\n\\t\\tExtracts triplet-loss model'\n        return\n\n    modelpref = argv[0]\n    imglist = argv[1]\n    outfile = argv[2]\n\n    with open(modelpref + '.json', \"r\") as json_file:\n        model_json = json_file.read()\n\n    loaded_model = keras.models.model_from_json(model_json)\n    loaded_model.load_weights(modelpref + '.h5')\n\n    base_model = loaded_model.get_layer('base_model')\n\n    # create a new single input\n    input_shape=(T_G_WIDTH,T_G_HEIGHT,T_G_NUMCHANNELS)\n    input_single = kl.Input(shape=input_shape, name='input_single')\n    \n    # create a new model without the triple loss\n    net_single = base_model(input_single)\n    model = Model(input_single, net_single, name='embedding_net')\n\n    chunksize = 1000\n    total_img = file_numlines(imglist)\n    total_img_ch = int(np.ceil(total_img / float(chunksize)))\n\n    with open(outfile, 'w') as f_handle:\n\n        for i in range(0, total_img_ch):\n            imgs = t_read_image_list(imglist, i*chunksize, chunksize)\n\n            vals = model.predict(imgs)\n    \n            np.savetxt(f_handle, vals)\n\n\n    return\n\n\n\ndef learn(argv):\n    \n    if len(argv) < 10:\n        print 'Usage: \\n\\t <Train Anchors (TXT)> <Train Positives (TXT)> <Train Negatives (TXT)> <Val Anchors (TXT)> <Val Positives (TXT)> <Val Negatives (TXT)> <embedding size> <batch size> <num epochs> <output model> \\n\\t\\tLearns triplet-loss model'\n        return\n\n    in_t_a = argv[0]\n    in_t_b = argv[1]\n    in_t_c = argv[2]\n\n    in_v_a = argv[3]\n    in_v_b = argv[4]\n    in_v_c = argv[5]\n\n    emb_size = int(argv[6])\n    batch = int(argv[7])\n    numepochs = int(argv[8])\n    outpath = argv[9] \n\n    # chunksize is the number of images we load from disk at a time\n    chunksize = batch*100\n    total_t = file_numlines(in_t_a)\n    total_v = file_numlines(in_v_b)\n    total_t_ch = int(np.ceil(total_t / float(chunksize)))\n    total_v_ch = int(np.ceil(total_v / float(chunksize)))\n\n    print 'Dataset has ' + str(total_t) + ' training triplets, and ' + str(total_v) + ' validation triplets.'\n\n    print 'Creating a model ...'\n    model = createModel(emb_size)\n\n    print 'Training loop ...'\n    \n    # manual loop over epochs to support very large sets of triplets\n    for e in range(0, numepochs):\n\n        for t in range(0, total_t_ch):\n\n            print 'Epoch ' + str(e) + ': train chunk ' + str(t+1) + '/ ' + str(total_t_ch) + ' ...'\n\n            print 'Reading image lists ...'\n            anchors_t = t_read_image_list(in_t_a, t*chunksize, chunksize)\n            positives_t = t_read_image_list(in_t_b, t*chunksize, chunksize)\n            negatives_t = t_read_image_list(in_t_c, t*chunksize, chunksize)\n            Y_train = np.random.randint(2, size=(1,2,anchors_t.shape[0])).T\n\n            print 'Starting to fit ...'\n            # This method does NOT use data augmentation\n            # model.fit([anchors_t, positives_t, negatives_t], Y_train, epochs=numepochs,  batch_size=batch)\n\n            # This method uses data augmentation\n            model.fit_generator(generator=createDataGen(anchors_t,positives_t,negatives_t,Y_train,batch), steps_per_epoch=len(Y_train) / batch, epochs=1, shuffle=False, use_multiprocessing=True)\n        \n        # In case the validation images don't fit in memory, we load chunks from disk again. \n        val_res = [0.0, 0.0]\n        total_w = 0.0\n        for v in range(0, total_v_ch):\n\n            print 'Loading validation image lists ...'\n            print 'Epoch ' + str(e) + ': val chunk ' + str(v+1) + '/ ' + str(total_v_ch) + ' ...'\n            anchors_v = t_read_image_list(in_v_a, v*chunksize, chunksize)\n            positives_v = t_read_image_list(in_v_b, v*chunksize, chunksize)\n            negatives_v = t_read_image_list(in_v_c, v*chunksize, chunksize)\n            Y_val = np.random.randint(2, size=(1,2,anchors_v.shape[0])).T\n\n            # Weight of current validation measurement. \n            # if loaded expected number of items, this will be 1.0, otherwise < 1.0, and > 0.0.\n            w = float(anchors_v.shape[0]) / float(chunksize)\n            total_w = total_w + w\n\n            curval = model.evaluate([anchors_v, positives_v, negatives_v], Y_val, batch_size=batch)\n            val_res[0] = val_res[0] + w*curval[0]\n            val_res[1] = val_res[1] + w*curval[1]\n\n        val_res = [x / total_w for x in val_res]\n\n        print 'Validation Results: ' + str(val_res)\n\n    print 'Saving model ...'\n\n    # Save the model and weights\n    model.save(outpath + '.h5')\n\n    # Due to some remaining Keras bugs around loading custom optimizers\n    # and objectives, we save the model architecture as well\n    model_json = model.to_json()\n    with open(outpath + '.json', \"w\") as json_file:\n        json_file.write(model_json)\n\n    return\n\n\n# Main Driver\nif __name__ == \"__main__\":\n    main(sys.argv[1:])\n", "meta": {"hexsha": "07cbb9ec0e21d2d34a0ff8fd2bb210ac856eee22", "size": 11749, "ext": "py", "lang": "Python", "max_stars_repo_path": "tripletloss.py", "max_stars_repo_name": "seriousran/tripletloss-keras-tensorflow", "max_stars_repo_head_hexsha": "8554a39add87488fb70a6a4b83bc049e11fe9cc7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54, "max_stars_repo_stars_event_min_datetime": "2018-07-09T15:45:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T08:35:15.000Z", "max_issues_repo_path": "tripletloss.py", "max_issues_repo_name": "seriousran/tripletloss-keras-tensorflow", "max_issues_repo_head_hexsha": "8554a39add87488fb70a6a4b83bc049e11fe9cc7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-03-17T10:20:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-17T03:16:15.000Z", "max_forks_repo_path": "tripletloss.py", "max_forks_repo_name": "seriousran/tripletloss-keras-tensorflow", "max_forks_repo_head_hexsha": "8554a39add87488fb70a6a4b83bc049e11fe9cc7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2018-08-30T05:55:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-31T01:59:28.000Z", "avg_line_length": 34.7603550296, "max_line_length": 353, "alphanum_fraction": 0.6655885607, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.3106943704494217, "lm_q1q2_score": 0.17585876790646301}}
{"text": "\nfrom itertools import chain, product\nimport os, sys, re, copy, ase\nimport ase.data as ad\nfrom openeye.oechem import *\nimport numpy as np\nimport networkx as nx\nimport networkx.algorithms.isomorphism  as iso\nimport aqml.cheminfo.oechem.OEChem as oe\nfrom rdkit import Chem\nimport scipy.spatial.distance as ssd\nimport aqml.cheminfo.openbabel.obabel as cib\nimport multiprocessing\nimport aqml.cheminfo.math as cim\nimport cml.sd as dd\nimport itertools as itl\nimport tempfile as tpf\n#tsdf = tpf.NamedTemporaryFile(dir=tdir)\nimport aqml.cheminfo.fortran.famoneib as fa\n\nglobal dsHX\ndsHX = {5:1.20, 6:1.10, 7:1.00, 8:0.98, 9:0.92, 14:1.48, 15:1.42, 16:1.34, 17:1.27}\n\n\nclass ParentMol(object):\n\n    def __init__(self, string, isort=False, iat=None, wg=True, k=7, \\\n                 k2=7, opr='.le.', fixGeom=False, keepHalogen=False, \\\n                 ivdw=False, dminVDW=1.2, inmr=False, \\\n                 covPLmin=5, debug=False):\n\n        self.covPLmin = covPLmin\n\n        self.k = k\n        self.k2 = k2\n        self.fixGeom = fixGeom\n        self.iat = iat\n        self.keepHalogen = keepHalogen\n        self.debug = debug\n        self.vsa = {'.le.': [-1,0], '.eq.': [0, ]}[opr] # valences accepted\n        self.wg = wg\n        self.ivdw = ivdw\n        self.dminVDW = dminVDW\n        self.s2cnr = {'H':1, 'B':3, 'C':4, 'N':3, 'O':2, 'F':1, \\\n                'Si':4, 'P':3, 'S':2, 'Cl':1, 'Br':1, 'I':1}\n        self.z2cnr = {1:1, 5:3, 6:4, 7:3, 8:2, 9:1, 14:4, 15:3, 16:2, 17:1, 35:1, 53:1}\n\n        # subg must be a subm (i.e., hybs are all retained)\n        # and rings cannot be broken!\n        self.FORCE_RING_CLOSED = True\n\n        # ready the molecule\n        M = oe.StringM(string, debug=debug)\n\n        # the block below is not necessary. It's only useful\n        # for test purpose to check if some fragments are missing.\n        # Plus, OEChem has some limitation on num_atoms for\n        # subgraph match when the subgraph is actually the whole mol\n#       if not isort:\n#           # protein is too huge, the program complains that\n#           # the default number of matches limit reached in\n#           # substructure search if you do `M.sort_atoms()\n#           M.sort_atoms()\n\n        self.M = M\n        m = M.oem\n        self.oem = m\n        self.na = M.na\n        self.g0 = ( M.bom > 0 ).astype(np.int)\n        np.fill_diagonal(self.g0, 0)\n        self.bom0 = M.bom\n\n        smi = M.can\n        zs0 = np.array(M.zs)\n        self.zs0 = zs0\n        self.coords = M.coords\n\n        # get CNs of all heavy atoms\n        cns0 = self.g0.sum(axis=0)\n        self.cns0 = cns0\n        cnrs0 = np.array( [ self.z2cnr[zi] for zi in zs0 ] )\n\n        # reference net charge of each atom\n        self.charges = M.charges\n\n        # reference total valences\n        self.tvs0 = self.bom0.sum(axis=0) + np.abs( self.charges )\n\n        # get reference aromaticity of atoms\n        # to be genuinely aromatic, the atom has to be unsaturated\n        # Note that the so-called `genuinely aromatic means that the\n        # corresponding molecular fragment cannot be described by a\n        # unique SMILES string.\n        ars0_1 = ( self.tvs0 - cns0 == 1 ); #print ' -- ars0_1 = ', ars0_1\n        ars0_2 = [ ai.IsAromatic() for ai in m.GetAtoms() ]\n        self.ars0 = np.logical_and(ars0_1, ars0_2) # ars0_1 #\n        #print ' iPause, smi = ', smi\n        # get envs that corresponds to multiple SMILES\n        self.envs = self.get_elusive_envs()\n        # get envs like 'C=C=C', 'C=C=N', 'C=N#N', etc\n        self.envsC = self.get_envsC()\n\n        if not inmr:\n            ncbs = []\n            if self.wg and self.ivdw:\n                ncbs = M.perceive_non_covalent_bonds(dminVDW=self.dminVDW, \\\n                                  covPLmin=self.covPLmin)\n            self.ncbs = ncbs\n\n\n    def get_nodes_bridge(self, zsi, mf_i, bom_i, dsi, mapping_i_reverse, nodes_i):\n        \"\"\"\n        get nodes connecting two or more standalone parts in a molecule/fragment\n        \"\"\"\n        na_i = len(zsi)\n        ias_i = np.arange(na_i)\n        iasH = ias_i[ zsi == 1 ]\n        nH = len(iasH)\n        # get all pairs of H's that are not connected to the same heavy atom\n        nodes_new = []\n        for jh in range(nH):\n            for kh in range(jh+1,nH):\n                jh_u = iasH[jh]; kh_u = iasH[kh]\n                h_j = mf_i.GetAtom( OEHasAtomIdx(jh_u) )\n                h_k = mf_i.GetAtom( OEHasAtomIdx(kh_u) )\n                nbr_jh = ias_i[ bom_i[jh_u] == 1 ][0]\n                nbr_kh = ias_i[ bom_i[kh_u] == 1 ][0]\n                if nbr_jh != nbr_kh:\n                    dHH = dsi[kh_u,jh_u]\n                    if dHH > 0 and dHH <= 1.6: # a thresh of 1.6 \\AA --> ~2 heavy atoms in the shortest path will be added\n                        nbr_jh_old = mapping_i_reverse[nbr_jh]\n                        nbr_kh_old = mapping_i_reverse[nbr_kh]\n                        a1 = self.m.GetAtom( OEHasAtomIdx(nbr_jh_old) )\n                        a2 = self.m.GetAtom( OEHasAtomIdx(nbr_kh_old) )\n                        #print ' nbr_jh_old, nbr_kh_old = ', nbr_jh_old, nbr_kh_old\n                        for a3 in OEShortestPath(a1,a2):\n                            ia3 = a3.GetIdx()\n                            if ia3 not in nodes_i:\n                                nodes_new.append( ia3 )\n        return nodes_new\n\n    def extend_heavy_nodes(self, jas_hvy, sg):\n\n        degrees = self.degrees\n        sets = self.sets\n        ds = self.ds\n\n        set_i = set()\n        # get neighbors of those heavy atoms\n        for j,ja in enumerate(jas_hvy):\n            degree0_j = degrees[ja]\n            degree_j = sg[j,:].sum()\n            #if ja == 1339: print 'Yeah', degree_j, degree0_j\n            if degree_j < degree0_j:\n                if ja in self.flexible_nodes: # saturated node\n                    set_i.update( [ja,] )\n                else:\n                    #if ja == 36: print ' Gotha 3 !'\n                    for nodes_i in self.rigid_nodes:\n                        if ja in nodes_i:\n                            set_i.update( nodes_i ); #print ' -- ja, nodes_i = ', ja, nodes_i\n            else:\n                set_i.update( [ja, ] )\n\n        jas_u = list(set_i) # nodes_of_heavy_atoms\n        sets.append( set_i )\n        self.sets = sets\n        self.jas_u = jas_u\n        #return istop\n\n\n    def build_m(self, nodes_to_add):\n        \"\"\"\n        nodes_to_add -- atomic indices to be added to build `mf\n        \"\"\"\n        atoms = self.atoms # parent molecule\n\n        mf = OEGraphMol()\n        mapping = {}\n        atoms_sg = [];\n\n        # step 1, add heavy atoms to `mf\n        icnt = 0\n        for ja in nodes_to_add:\n            aj = atoms[ja]; zj = self.zs0[ja]\n            aj2 = mf.NewAtom( zj )\n            atoms_sg.append( aj2 ); mapping[ja] = icnt; icnt += 1\n            aj2.SetHyb( OEGetHybridization(aj) )\n            mf.SetCoords(aj2, self.coords[ja])\n        # step 2, add H's and XH bond\n        bonds = []\n        #print ' -- nodes_to_add = ', nodes_to_add\n        for j,ja in enumerate(nodes_to_add):\n            aj = atoms[ja]\n            zj = self.zs0[ja]\n            aj2 = atoms_sg[j]\n            for ak in aj.GetAtoms():\n                ka = ak.GetIdx()\n                zk = ak.GetAtomicNum()\n                if zk == 1:\n                    ak2 = mf.NewAtom( 1 )\n                    b2 = mf.NewBond( aj2, ak2, 1)\n                    mf.SetCoords(ak2, self.coords[ka]); #print ' - ka, ', self.coords[ka]\n                    bonds.append( [icnt,j,1] ); icnt += 1\n                else:\n                    # __don't__ add atom `ak to `mf as `ak may be added to `mf later\n                    # in the for loop ``for ja in nodes_to_add`` later!!\n                    if ka not in nodes_to_add:\n                        # add H\n                        v1 = self.coords[ka] - self.coords[ja]\n                        dHX = dsHX[zj];\n                        coords_k = self.coords[ja] + dHX*v1/np.linalg.norm(v1)\n                        ak2 = mf.NewAtom( 1 )\n                        mf.SetCoords(ak2, coords_k); #print ' --- ka, ', coords_k\n                        b2 = mf.NewBond( aj2, ak2, 1)\n                        bonds.append( [icnt,j,1] ); icnt += 1\n\n        nadd = len(nodes_to_add)\n        #print ' __ nodes_to_add = ', nodes_to_add\n        for j in range(nadd):\n            for k in range(j+1,nadd):\n                #print ' j,k = ', j,k\n                ja = nodes_to_add[j]; ka = nodes_to_add[k]\n                ja2 = mapping[ja]; ka2 = mapping[ka]\n                bo = self.bom0[ja,ka]\n                if bo > 0:\n                    aj2 = atoms_sg[ja2]; ak2 = atoms_sg[ka2]\n                    bonds.append( [j,k,bo] )\n                    b2 = mf.NewBond( aj2, ak2, bo )\n                    #print ' (ja,ka,bo) = (%d,%d,%d), '%(ja, ka, bo), '(ja2,ka2,bo) = (%d,%d,%d)'%(ja2,ka2,bo)\n        assert mf.NumAtoms() == icnt\n        bom_u = np.zeros((icnt,icnt), np.int)\n        for bond_i in bonds:\n            bgn,end,bo_i = bond_i\n            bom_u[bgn,end] = bom_u[end,bgn] = bo_i\n\n        return bom_u, mapping, mf\n\n\n    def get_rigid_and_flexible_nodes(self):\n        \"\"\"\n        NMR only\n\n        (1) rigid nodes\n            extended smallest set of small unbreakable fragments,\n            including aromatic rings, 3- and 4-membered rings\n            (accompanied with high strain, not easy to cover these\n            interactions in amons) and -C(=O)N- fragments\n\n            These nodes is output as a list of lists, with each\n            containing the atom indices for a unbreakable ring\n            with size ranging from 3 to 9, or -C(=O)N-\n        (2) flexible nodes\n            a list of saturated atom indices\n        \"\"\"\n\n        def update_sets(set_i, sets):\n            if np.any([ set_i <= set_j for set_j in sets ]):\n                return sets\n            intersected = [ set_i.intersection(set_j) for set_j in sets ]\n            istats = np.array([ si != set() for si in intersected ])\n            nset = len(sets); idxs = np.arange( nset )\n            if np.any( istats ):\n                #assert istats.astype(np.int).sum() == 1\n                for iset in idxs:\n                    if istats[iset]:\n                        sets[iset] = set_i.union( sets[iset] )\n            else:\n                sets.append( set_i )\n            return sets\n\n        m = self.oem\n        nodes_hvy = list( np.arange(self.na)[ self.zs0 > 1 ] )\n\n        # first search for rings\n        namin = 3\n        namax = 10\n        sets = []\n        for i in range(namin, namax+1):\n            if i in [3,4,]:\n                pat_i = '*~1' + '~*'*(i-2) + '~*1'\n            else:\n                pat_i = '*:1' + ':*'*(i-2) + ':*1'\n            ss = OESubSearch(pat_i)\n            iok = OEPrepareSearch(m, ss)\n            for match in ss.Match(m):\n                set_i = set()\n                for ma in match.GetAtoms():\n                    set_i.update( [ma.target.GetIdx()] )\n                if set_i not in sets: sets.append( set_i )\n        # now remove those rings that are union of smaller rings\n        n = len(sets)\n        sets_remove = []\n        ijs = itl.combinations( range(n), 2 )\n        sets_u = []\n        for i,j in ijs:\n            set_ij = sets[i].union( sets[j] )\n            if set_ij in sets and (set_ij not in sets_remove):\n                sets_remove.append( set_ij )\n        sets_u = cim.get_compl(sets, sets_remove)\n        sets = sets_u\n\n        # then find atoms with hyb .le. 2, e.g., -C(=O)N-, -C(=O)O-,\n        # -[N+](=O)[O-], -C#N, etc\n        iasc = []\n        for ai in m.GetAtoms():\n            hyb = OEGetHybridization(ai)\n            if hyb < 3 and hyb > 0:\n                iasc.append( ai.GetIdx() )\n        sg = self.g0[iasc,:][:,iasc]\n        na_sg = len(iasc)\n        dic_sg = dict(zip(range(na_sg), iasc))\n        for sgi in oe.find_cliques( sg ):\n            set_i = set([ dic_sg[ii] for ii in sgi ])\n            sets = update_sets(set_i, sets)\n\n        for pat_i in ['[CX3](=O)[O,N]', '[#7,#8,#9;!a][a]', ]:\n            ss = OESubSearch(pat_i)\n            iok = OEPrepareSearch(m, ss)\n            for match in ss.Match(m):\n                set_i = set()\n                for ma in match.GetAtoms():\n                    set_i.update( [ma.target.GetIdx()] )\n                sets = update_sets(set_i, sets)\n        rigid_nodes = [ list(si) for si in sets ]\n        rigid_nodes_ravel = []\n        for nodes_i in rigid_nodes: rigid_nodes_ravel += nodes_i\n        self.rigid_nodes = rigid_nodes\n\n        # now find flexible nodes, i.e., saturated nodes with breakable connected bonds\n        flexible_nodes = list( set(nodes_hvy)^set(rigid_nodes_ravel) )\n\n        obsolete = \"\"\"\n        flexible_nodes = set()\n        for pat_i in ['[CX4,SiX4,PX3,F,Cl,Br,I]', ]:\n            ss = OESubSearch(pat_i)\n            iok = OEPrepareSearch(m, ss)\n            for match in ss.Match(m):\n                for ma in match.GetAtoms():\n                    flexible_nodes.update( [ma.target.GetIdx()] )\n\n        for pat_i in [ '[NX3;!a]', '[OX2;!a]', '[SX2;!a]', ]:\n            ss = OESubSearch(pat_i)\n            iok = OEPrepareSearch(m, ss)\n            for match in ss.Match(m):\n                for ma in match.GetAtoms():\n                    ia = ma.target.GetIdx()\n                    if ia not in rigid_nodes_ravel:\n                        flexible_nodes.update( [ia] )\"\"\"\n\n        self.flexible_nodes = list(flexible_nodes)\n\n    def get_elusive_envs(self):\n        \"\"\"\n        check if the bond linking two atoms in `ias is eligbile\n        for breaking by inspecting if these two atoms are in a\n        elusive environment, i.e., a genuinely aromatic env\n        e.g., Cc1c(C)cccc1 (two SMILES exist!); exceptions:\n        o1cccc1, since it has only one possible SMILES string\n        \"\"\"\n        filt = np.array( self.ars0 ) #.astype(np.int32)\n        if filt.astype(np.int).sum() == 0: return set([])\n        ias0 = np.arange( len(self.ars0) )\n        ias1 = ias0[filt]\n        g2 = self.bom0[filt, :][:, filt]\n        iok = False\n        envs = set([])\n        for cliques_i in oe.find_cliques(g2):\n            if len(cliques_i) > 2:\n                gci = g2[cliques_i, :][:, cliques_i]\n\n                # set `irad to False to ensure that no atom is unsaturated in valence\n                ess, nrss = oe.edges_standalone_updated(gci, irad=False)\n                #print ' __ ess = ', ess\n                #print ' __ nrss = ', nrss\n\n                # note that for genuinely aromatic env, `nrss should contain\n                # no more than 1 unique list\n                nes = len(ess)\n                if nes > 0:\n                    n1 = len(ess[0])\n                    nrs1 = set( nrss[0] )\n                    for nrs in nrss[1:]:\n                        if set(nrs) != nrs1:\n                            raise '#ERROR: more than 2 different sets in nodes_residual??'\n                #    # get the common list in `ess, then remove it\n                #    # e.g., a C=C attached to a benzene ring is an\n                #    # explicit env, inly the benzene ring is an implicite\n                #    # env as there are more than 1 corresponding SMIELS string\n                #    comms = []\n                #    for i in range(n1):\n                #        comm = ess[0][i]\n                #        if np.all( [ comm in ess[j] for j in range(1,nes) ] ):\n                #            comms.append( comm )\n                #\n                #    envs.update( set( oe.comba( cim.get_compl_u(ess[0],comms) ) ) )\n                    envs.update( set( oe.comba( ess[0]) ) )\n        envs_u = set( [ ias1[k] for k in list(envs) ] )\n        return envs_u\n\n    def get_envsC(self):\n        \"\"\"\n        get conjugated environments containing adjacent double bonds,\n        e.g., C=C=C, C=N#N\n        \"\"\"\n        qs = ['[*]=[*]#[*]', '[*]=[*]=[*]']\n        ts = []\n        for q in qs:\n            ots = oe.is_subg(self.oem, q, iop = 1)\n            if ots[0]:\n                for tsi in ots[1]:\n                    tsi_u = set(tsi)\n                    if len(ts) == 0:\n                        ts.append( tsi_u )\n                    else:\n                        iexist = False\n                        for j, tsj in enumerate(ts):\n                            if tsi_u.intersection(tsj):\n                                iexist = True\n                                tsj.update( tsi_u )\n                                ts[j] = tsj\n                                break\n                        if not iexist: ts.append( tsi_u )\n        return ts\n\n\n    def get_cutout(self, ias0, cutoff=8.0):\n        \"\"\"\n        retrieve the union of local structure within a radius\n        of `cutoff of atom in `ias0\n        \"\"\"\n        m = self.oem\n        self.m = m\n\n        ias = np.arange(self.na)\n        ias_hvy = ias[ self.zs0 > 1]\n\n        self.ias_hvy = ias_hvy\n        #ds = self.ds\n        ds = ssd.squareform( ssd.pdist(self.coords) )\n        self.ds = ds\n\n        atoms = [ ai for ai in m.GetAtoms() ]\n        self.atoms = atoms\n\n        # get degree of heavy atom\n        degrees = []\n        for i in range(self.na):\n            csi = self.bom0[i,:]\n            degree_i = np.sum( np.logical_and( csi > 0, self.zs0 > 1 ) )\n            degrees.append( degree_i )\n        self.degrees = degrees\n\n        self.get_rigid_and_flexible_nodes()\n\n        msf = []\n        self.sets = []\n        boms = []\n        mappings = []\n\n        jas_u = set()\n        icnt = 0\n        for ia in ias0:\n            filt = ( ds[ia] <= cutoff )\n            jas = list( ias[filt] )\n\n            # get heavy atoms\n            jas_hvy = []\n            for j,ja in enumerate(jas):\n                zja = self.zs0[ja]\n                if zja == 1:\n                    nbr = ias[self.g0[ja,:] == 1][0]\n                    #if self.zs0[nbr] in [7,8,9,15,16,17]:\n                        # these electronegative atoms will induce electrostatic effects (long-ranged)\n                    jas_hvy.append( nbr )\n                else:\n                    jas_hvy.append( ja )\n            #print ' -- jas_hvy = ', jas_hvy\n            # get neighbors of those heavy atoms\n            sg = self.g0[jas_hvy,:][:,jas_hvy]\n            #istop = self.extend_heavy_nodes(jas_hvy, sg)\n            self.extend_heavy_nodes(jas_hvy, sg)\n#           if 1339 in self.jas_u:\n#               if icnt == 0: print self.jas_u\n#               icnt += 1\n            jas_u.update( self.jas_u )\n\n        bom_u, mapping, mf = self.build_m( list(jas_u) )\n\n        # the extracted molecular fragments (i.e., `mf) may contain\n        # several disconnected components, now add some atoms\n        #  re-connecting these standalone entities\n        mf_i = mf\n        bom_i = bom_u\n        mapping_i = mapping\n\n        mapping_i_reverse = {}\n        nodes_i = [] # heavy nodes of `mf\n        for keyi in mapping_i.keys():\n            val_i = mapping_i[keyi]; nodes_i.append( keyi )\n            mapping_i_reverse[val_i] = keyi\n        if self.debug: print ' --         nodes = ', nodes_i\n        dic_i = mf_i.GetCoords()\n        coords_i = []\n        for j in range(mf_i.NumAtoms()): coords_i.append( dic_i[j] )\n        zsi = np.array([ aj.GetAtomicNum() for aj in mf_i.GetAtoms() ])\n        dsi = ssd.squareform( ssd.pdist(coords_i) )\n\n        nodes_new = self.get_nodes_bridge(zsi, mf_i, bom_i, dsi, mapping_i_reverse, nodes_i)\n\n        if self.debug: print ' --     new nodes = ', nodes_new\n        jas_hvy = list( set(nodes_i + nodes_new) )\n        sg = self.g0[jas_hvy,:][:,jas_hvy]\n        #istop = self.extend_heavy_nodes(jas_hvy, sg)\n        #if 1339 in jas_hvy:\n        #    idx = jas_hvy.index(1339)\n        #    iasU = np.arange(sg.shape[0])\n        #    print iasU[ sg[idx,:] > 0 ]\n\n        self.extend_heavy_nodes(jas_hvy, sg)\n        jas_u = self.jas_u\n\n        if self.debug: print ' -- jas_u = ', jas_u, ' [updated]'\n        mf_u = self.build_m( list(set(jas_u)) )[-1]\n        return mf_u\n\n\n    def get_atoms_within_cutoff(self, qa=None, za=None, cutoff=3.6):\n        \"\"\"\n        For now, for prediction of NMR only\n\n        retrieve atoms around atom `ia-th H atom within a radius of\n        `cutoff.\n\n        This function will be used when dealing with large molecules\n        like proteins where long-range interactions are significant.\n        The related properties include NMR shifts.\n        \"\"\"\n\n        m = self.oem\n        self.m = m\n\n        ias = np.arange(self.na)\n        ias_hvy = ias[ self.zs0 > 1]\n        if za is None:\n            ias_za = ias\n        else:\n            ias_za = ias[ self.zs0 == za ]\n        self.ias_za = ias_za\n\n        self.ias_hvy = ias_hvy\n        #ds = self.ds\n        ds = ssd.squareform( ssd.pdist(self.coords) )\n        self.ds = ds\n\n        atoms = [ ai for ai in m.GetAtoms() ]\n        self.atoms = atoms\n\n        # get degree of heavy atom\n        degrees = []\n        for i in range(self.na):\n            csi = self.bom0[i]\n            degree_i = np.sum( np.logical_and( csi > 0, self.zs0 > 1 ) )\n            degrees.append( degree_i )\n        self.degrees = degrees\n\n        if qa is None:\n            qsa = ias_za\n        else:\n            qsa = [ias_za[qa], ]\n        self.get_rigid_and_flexible_nodes()\n\n        msf = []\n        self.sets = []\n        boms = []\n        mappings = []\n        for ia in qsa:\n            filt = ( ds[ia] <= cutoff )\n            jas = list( ias[filt] )\n\n            # get heavy atoms\n            jas_hvy = []\n            for j,ja in enumerate(jas):\n                zja = self.zs0[ja]\n                if zja == 1:\n                    nbr = ias[self.g0[ja] == 1][0]\n                    #if self.zs0[nbr] in [7,8,9,15,16,17]:\n                        # these electronegative atoms will induce electrostatic effects (long-ranged)\n                    jas_hvy.append( nbr )\n                else:\n                    jas_hvy.append( ja )\n            #print ' -- jas_hvy = ', jas_hvy\n            # get neighbors of those heavy atoms\n            sg = self.g0[jas_hvy,:][:,jas_hvy]\n            #istop = self.extend_heavy_nodes(jas_hvy, sg)\n            self.extend_heavy_nodes(jas_hvy, sg)\n\n            jas_u = self.jas_u\n            #print ' -- jas_u = ', jas_u\n            bom_u, mapping, mf = self.build_m(jas_u)\n            boms.append(bom_u)\n            mappings.append( mapping )\n            msf.append(mf)\n\n        # the extracted molecular fragments (i.e., `mf) may contain\n        # several disconnected components, now add some atoms\n        #  re-connecting these standalone entities\n        msf_u = []\n        self.sets = [] # update !! Vital!!\n        for i in range(len(msf)):\n            mf_i = msf[i]\n            bom_i = boms[i]\n            mapping_i = mappings[i]\n            mapping_i_reverse = {}\n            nodes_i = [] # heavy nodes of `mf\n            for keyi in mapping_i.keys():\n                val_i = mapping_i[keyi]; nodes_i.append( keyi )\n                mapping_i_reverse[val_i] = keyi\n            if self.debug: print ' --         nodes = ', nodes_i\n            dic_i = mf_i.GetCoords()\n            coords_i = []\n            for j in range(mf_i.NumAtoms()): coords_i.append( dic_i[j] )\n            zsi = np.array([ aj.GetAtomicNum() for aj in mf_i.GetAtoms() ])\n            dsi = ssd.squareform( ssd.pdist(coords_i) )\n\n            nodes_new = self.get_nodes_bridge(zsi, mf_i, bom_i, dsi, mapping_i_reverse, nodes_i)\n            if self.debug: print ' --     new nodes = ', nodes_new\n            jas_hvy = nodes_i + nodes_new\n            sg = self.g0[jas_hvy,:][:,jas_hvy]\n            #istop = self.extend_heavy_nodes(jas_hvy, sg)\n            self.extend_heavy_nodes(jas_hvy, sg)\n            jas_u = self.jas_u\n            if self.debug: print ' -- jas_u = ', jas_u, ' [updated]'\n            mf_u = self.build_m( jas_u )[-1]\n            msf_u.append( mf_u )\n        msf = msf_u\n\n        # Finally remove any fragment that are part of some larger fragment\n        sets = self.sets\n        nmf = len(msf)\n        nas = np.array( [ len(set_i) for set_i in sets ] )\n        seq = np.argsort( nas )[::-1]\n        #print ' -- nas = ', nas\n        #print ' --seq = ', seq\n        sets1 = []\n        msf1 = []\n        qsa1 = []\n        for i in seq:\n            sets1.append( sets[i ] )\n            msf1.append( msf[i ] )\n            qsa1.append( qsa[i ] )\n\n        sets_u = [sets1[0], ]\n        msf_u = [msf1[0], ]\n        qsa_u = [ qsa1[0], ]\n        for i in range( 1, nmf ):\n            #print ' -- sets_u = ', sets_u\n            ioks2 = [ sets1[i] <= set_j for set_j in sets_u ]\n            if not np.any(ioks2): # now remove the `set_j in `sets\n                sets_u.append( sets1[i] )\n                msf_u.append( msf1[i] )\n                qsa_u.append( qsa1[i] )\n\n        self.sets = sets_u\n        self.qsa = qsa_u\n        self.msf = msf_u\n\n\nclass ParentMols(object):\n\n    def __init__(self, strings, fixGeom, iat=None, wg=True, k=7,\\\n                 nmaxcomb=3,icc=None, substring=None, rc=6.4, \\\n                 isort=False, k2=7, opr='.le.', wsmi=True, irc=True, \\\n                 iters=[30,90], dminVDW= 1.2, \\\n                 idiff=0, thresh=0.2, \\\n                 keepHalogen=False, debug=False, ncore=1, \\\n                 forcefield='mmff94', do_ob_ff=True, do_rk_ff=False, \\\n                 ivdw=False, covPLmin=5, prefix=''):\n#                 do_pm7=False, relaxHHV=False, \\\n        \"\"\"\n        prefix -- a string added to the beginning of the name of a\n                  folder, where all sdf files will be written to.\n                  It should be ended with '_' if it's not empty\n        irc    -- T/F: relax w/wo dihedral constraints\n\n        substring -- SMILES of a ligand.\n                  Typically in a protein-ligand complex, we need\n                  to identify the ligand first and then retrieve\n                  all the local atoms that bind to the ligand via\n                  vdW interaction as amons for training in ML. The\n                  thus obtained fragment is dubbed `centre.\n\n                  If `substring is assigned a string,\n                  we will generated only amons that are\n                  a) molecular complex; b) any atom in the centre\n                  must be involved.\n        rc     -- cutoff radius centered on each atom of the central\n                  component. It's used when `icc is not None.\n        \"\"\"\n\n        def check_ncbs(a, b, c):\n            iok = False\n            for si in itl.product(a,b):\n                if set(si) in c:\n                    iok = True; break\n            return iok\n\n        param = Parameters(wg, fixGeom, k, k2, ivdw, dminVDW, \\\n                           forcefield, thresh, do_ob_ff, \\\n                           do_rk_ff, idiff, iters)\n\n        # at most 1 True can be set\n        ioks = [ do_ob_ff, do_rk_ff, ]\n        assert np.array(ioks).astype(np.int).sum() <= 1\n\n        ncpu = multiprocessing.cpu_count()\n        if ncore > ncpu:\n            ncore = ncpu\n\n        # temparary folder\n        tdirs = ['/scratch', '/tmp']\n        for tdir in tdirs:\n            if os.path.exists(tdir):\n                break\n\n        # num_molecule_total\n        assert type(strings) is list, '#ERROR: `strings must be a list'\n        nmt = len(strings)\n        if iat != None:\n            assert nmt == 1, '#ERROR: if u wanna specify the atomic idx, 1 input molecule at most is allowed'\n\n        cans = []; nhas = []; es = []; maps = []\n        ms = []; ms0 = []\n\n        # initialize `Sets\n        seta = Sets(param)\n        for ir in range(nmt):\n            print ' -- Mid %d'%(ir+1)\n            string = strings[ir]\n            obj = ParentMol(string, isort=isort, iat=iat, wg=wg, k=k, k2=k2, \\\n                            opr=opr, fixGeom=fixGeom, covPLmin=covPLmin, \\\n                            ivdw=ivdw, dminVDW=dminVDW, \\\n                            keepHalogen=keepHalogen, debug=debug)\n            ncbs = obj.ncbs\n            Mlis, iass, cans = [], [], []\n            # we needs all fragments in the first place; later we'll\n            # remove redundencies when merging molecules to obtain\n            # valid vdw complexes\n            nas = []; nasv = []; pss = []\n            iass = []; iassU = []\n            for Mli, ias, can in obj.generate_amons():\n                iasU = ias + [-1,]*(k-len(ias)); nasv.append( len(ias) )\n                Mlis.append( Mli ); iass.append( ias ); cans.append( can )\n                iassU.append( iasU ); pss += list(Mli[1])\n                nas.append( len(Mli[0]) )\n            nmi = len(cans)\n            print ' -- nmi = ', nmi\n\n            nas = np.array(nas, np.int)\n            nasv = np.array(nasv, np.int)\n            pss = np.array(pss)\n            iassU = np.array(iassU, np.int)\n            ncbsU = np.array(ncbs, np.int)\n\n            # now combine amons to get amons complex to account for\n            # long-ranged interaction\n            if wg and ivdw:\n                if substring != None:\n                    cliques_c = set( oe.is_subg(obj.oem, substring, iop=1)[1][0] )\n                    #print ' -- cliques_c = ', cliques_c\n                    cliques = oe.find_cliques(obj.g0)\n                    Mlis_centre = []; iass_centre = []; cans_centre = []\n                    Mlis_others = []; iass_others = []; cans_others = []\n                    for i in range(nmi):\n                        #print ' %d/%d done'%(i+1, nmi)\n                        if set(iass[i]) <= cliques_c:\n                            Mlis_centre.append( Mlis[i] )\n                            iass_centre.append( iass[i] )\n                            cans_centre.append( cans[i] )\n                        else:\n                            Mlis_others.append( Mlis[i] )\n                            iass_others.append( iass[i] )\n                            cans_others.append( cans[i] )\n                    nmi_c = len(Mlis_centre)\n                    nmi_o = nmi - nmi_c\n                    print ' -- nmi_centre, nmi_others = ', nmi_c, nmi_o\n                    Mlis_U = []; cans_U = []\n                    for i0 in range(nmi_c):\n                        ias1 = iass_centre[i0]\n                        t1 = Mlis_centre[i0]; nha1 = (np.array(t1[0]) > 1).sum()\n                        for j0 in range(nmi_o):\n                            ias2 = iass_others[j0]\n                            t2 = Mlis_others[j0]; nha2 = np.array((t2[0]) > 1).sum()\n                            if nha1 + nha2 <= k2 and check_ncbs(ias1, ias2, ncbs):\n                                dmin = ssd.cdist(t1[1], t2[1]).min()\n                                if dmin >= dminVDW:\n                                    cansij = [cans_centre[i0], cans_others[j0]]\n                                    cansij.sort()\n                                    cans_U.append( '.'.join(cansij) )\n                                    Mlis_U.append( merge(t1, t2) )\n                    Mlis = Mlis_U; cans = cans_U\n                    print ' -- nmi_U = ', len(Mlis)\n                else:\n                    obsolete = \"\"\"\n                    for i0 in range(nmi-1):\n                        ias1 =  iass[i0]\n                        t1 = Mlis[i0]; nha1 = (np.array(t1[0]) > 1).sum()\n                        for j0 in range(i0+1,nmi):\n                            ias2 = iass[j0]\n                            t2 = Mlis[j0]; nha2 = np.array((t2[0]) > 1).sum()\n                            if nha1 + nha2 <= k2 and check_ncbs(ias1, ias2, obj.ncbs):\n                                dmin = ssd.cdist(t1[1], t2[1]).min()\n                                if dmin >= dminVDW:\n                                    cansij = [cans[i0], cans[j0]]\n                                    cansij.sort()\n                                    cans.append( '.'.join(cansij) )\n                                    Mlis.append( merge(t1, t2) )\"\"\"\n                    obsolete = \"\"\"print 'nas.shape = ', nas.shape\n                    print 'nasv.shape = ', nasv.shape\n                    print 'iassU.shape = ', iassU.shape\n                    print 'pss.shape = ', pss.shape\n                    print 'ncbsU.shape = ', ncbsU.shape\"\"\"\n                    print 'dminVDW = ', dminVDW\n                    gv,gc = fa.get_amon_adjacency(k2,nas,nasv,iassU.T,pss.T,ncbsU.T,dminVDW)\n                    print 'amon connectivity done'\n                    #print 'gv=',gv # 'np.any(gv > 0) = ', np.any(gv > 0)\n                    ims = np.arange(nmi)\n                    combs = []\n                    for im in range(nmi):\n                        nv1 = nasv[im]\n                        jms = ims[ gv[im] > 0 ]\n                        nj = len(jms)\n                        if nj == 1:\n                            # in this case, nmaxcomb = 2\n                            jm = jms[0]\n                            if nmaxcomb == 2:\n                                # setting `nmaxcomb = 2 means to include\n                                # all possible combinations consisting of\n                                # two standalone molecules\n                                comb = [im,jms[0]]; comb.sort()\n                                if comb not in combs:\n                                    combs += [comb]\n                            else:\n                                # if we are not imposed with `nmaxcomb = 2,\n                                # we remove any complex corresponding to 2) below\n                                #\n                                # 1)    1 --- 2  (no other frag is connected to `1 or `2)\n                                #\n                                # 2)    1 --- 2\n                                #              \\\n                                #               \\\n                                #                3\n                                if len(gv[jm]) == 1:\n                                    comb = [im,jm]; comb.sort()\n                                    if comb not in combs:\n                                        combs += [comb]\n                        else:\n                            if nmaxcomb == 2:\n                                for jm in jms:\n                                    comb = [im,jm]; comb.sort()\n                                    if comb not in combs:\n                                        combs += [comb]\n                            elif nmaxcomb == 3:\n                                #for jm in jms:\n                                #    comb = [im,jm]; comb.sort()\n                                #    if comb not in combs:\n                                #        combs += [comb]\n\n                                # this is the default choice and is more reasonable\n                                # as only the most relevant local frags are included.\n                                # Here we don't consider frags like [im,p],[im,q] as\n                                # 1) the local envs are covered by [im,p,q]; 2) it's less\n                                # relevant to [im,p,q]\n                                for (p,q) in itl.combinations(jms,2):\n                                    nv2 = nasv[p]; nv3 = nasv[q]\n                                    if nv1+nv2+nv3 <= k2 and gc[p,q] == 0:\n                                        comb = [im,p,q]; comb.sort()\n                                        if comb not in combs:\n                                            combs += [comb]\n                    print 'atom indices of all amons done'\n                    for comb in combs:\n                        #print comb\n                        cans_i = [ cans[ic] for ic in comb ]; cans_i.sort()\n                        cans.append('.'.join(cans_i))\n                        ts_i = [ Mlis[ic] for ic in comb ]\n                        Mlis.append( merge(ts_i) )\n                    print 'amons now ready for filtering'\n            #else:\n            #    #\n\n\n            ncan = len(cans)\n            # now remove redundancy\n            if wg:\n                #print ' cans = ', cans\n                for i in range(ncan):\n                    #print '** ', cans[i], (np.array(Mlis[i][0]) > 1).sum(),\\\n                    #                       len(Mlis[i][0]), Mlis[i][0]\n                    seta.update(ir, cans[i], Mlis[i])\n                seta._sort()\n            else:\n                for i in range(ncan):\n                    #print ' ++ i, cans[i] = ', i,cans[i]\n                    seta.update2(ir, cans[i], Mlis[i])\n                seta._sort2()\n            print 'amons are sorted and regrouped'\n\n        cans = seta.cans; ncs = seta.ncs; nhas = seta.nhas\n\n        ncan = len(cans)\n        self.cans = cans\n        if not wsmi: return\n        nd = len(str(ncan))\n\n        s1 = 'EQ' if opr == '.eq.' else ''\n        svdw = '_vdw%d'%k2 if ivdw else ''\n        scomb = '_comb2' if nmaxcomb == 2 else ''\n        sthresh = '_dE%.2f'%thresh if thresh > 0 else ''\n        if prefix == '':\n            fdn = 'g%s%d%s%s_covL%d%s'%(s1,k,svdw,sthresh,covPLmin,scomb)\n        else:\n            fdn = prefix\n\n        if not os.path.exists(fdn): os.system('mkdir -p %s'%fdn)\n        self.fd = fdn\n\n        if iat is not None:\n            fdn += '_iat%d'%iat # absolute idx\n        if wg and (not os.path.exists(fdn+'/raw')): os.system('mkdir -p %s/raw'%fdn)\n        with open(fdn + '/' + fdn+'.smi', 'w') as fid:\n            fid.write('\\n'.join( [ '%s %d'%(cans[i],ncs[i]) for i in range(ncan) ] ) )\n        dd.io.save('%s/maps.pkl'%fdn, {'maps': maps} )\n\n        if wg:\n            ms = seta.ms; ms0 = seta.ms0;\n            for i in range(ncan):\n                ms_i = ms[i]; ms0_i = ms0[i]\n                nci = ncs[i]\n                labi = '0'*(nd - len(str(i+1))) + str(i+1)\n                print ' ++ %d %06d/%06d %60s %3d'%(nhas[i], i+1, ncan, cans[i], nci)\n                for j in range(nci):\n                    f_j = fdn + '/frag_%s_c%05d'%(labi, j+1) + '.sdf'\n                    f0_j = fdn + '/raw/frag_%s_c%05d_raw'%(labi, j+1) + '.sdf'\n                    m_j = ms_i[j]; m0_j = ms0_i[j]\n                    Chem.MolToMolFile(m_j, f_j)\n                    Chem.MolToMolFile(m0_j, f0_j)\n            print ' -- nmi_u = ', sum(ncs)\n            print ' -- ncan = ', len(np.unique(cans))\n        else:\n            if wsmi:\n                with open(fdn + '/' + fdn+'.smi', 'w') as fid:\n                    fid.write('\\n'.join( [ '%s'%(cans[i]) for i in range(ncan) ] ) )\n\n", "meta": {"hexsha": "90387043bf2e5bb25984f41a2db29717ee5f1a10", "size": 38187, "ext": "py", "lang": "Python", "max_stars_repo_path": "cheminfo/openbabel/amon_cutout.py", "max_stars_repo_name": "binghuang2018/aqml", "max_stars_repo_head_hexsha": "4901f3bd85db968fb3fc7ab97fd443421909d89d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2020-02-17T11:15:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T18:03:15.000Z", "max_issues_repo_path": "cheminfo/openbabel/amon_cutout.py", "max_issues_repo_name": "binghuang2018/aqml", "max_issues_repo_head_hexsha": "4901f3bd85db968fb3fc7ab97fd443421909d89d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-11T06:49:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-21T07:30:53.000Z", "max_forks_repo_path": "cheminfo/openbabel/amon_cutout.py", "max_forks_repo_name": "binghuang2018/aqml", "max_forks_repo_head_hexsha": "4901f3bd85db968fb3fc7ab97fd443421909d89d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-09T01:37:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-19T13:13:34.000Z", "avg_line_length": 40.0283018868, "max_line_length": 122, "alphanum_fraction": 0.4619373085, "include": true, "reason": "import numpy,import scipy,import networkx", "num_tokens": 10170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.1756382864198116}}
{"text": "#!/usr/bin/env python\n\n'''\ndescription:    create sea surface temperatures and sea ice concentrations\n                input files for Blue Action experiments 1 and 2\nlicense:        APACHE 2.0\nauthor:         Ronald van Haren, NLeSC (r.vanharen@esciencecenter.nl)\n'''\n\nfrom netCDF4 import Dataset\nfrom netCDF4 import date2num as nc_date2num\nfrom netCDF4 import num2date as nc_num2date\nimport numpy as np\nimport os\nimport time\nimport sys\nimport subprocess\nimport argparse\n\n\ndef main(startyear, endyear, overwrite):\n    '''\n    Main function, call experiment 1 and experiment 2 functions\n\n    Args:\n        startyear (int):        First year to use in calculations\n        endyear (int):          Stop calculations in the beginning of this year\n        overwrite (bool):       Force overwriting exsisting files if True\n    '''\n    exp1(startyear, endyear, overwrite)\n    exp2(startyear, endyear, overwrite)\n    exp3_4(startyear, endyear, 3, overwrite)\n    exp3_4(startyear, endyear, 4, overwrite)\n\n\ndef create_dimensions_netcdf(ncfile, dtobj, lat, lon):\n    '''\n    Define dimensions in netCDF file\n\n    Args:\n        ncfile:     netCDF file handle\n        dtobj:      python datetime object\n        lat:        latitude [degrees]\n        lon:        longitude [degrees]\n\n    Returns:\n        ncfile:     netCDF file handle\n    '''\n    # description of the file\n    ncfile.description = 'Blue Action'\n    ncfile.history = 'Created ' + time.ctime(time.time())\n    # create time dimension\n    timevar = ncfile.createDimension('time', None)\n    # netcdf time variable UTC\n    timevar = ncfile.createVariable('time', 'float32', ('time',),\n                                    zlib=True)\n    timevar.units = 'days since 1850-01-01 00:00:00'\n    timevar.calendar = 'gregorian'\n    timevar.standard_name = 'time'\n    timevar.long_name = 'Time'\n    timevar.axis = 'T'\n    # convert dtobj to num\n    timevar[:] = nc_date2num(dtobj,\n                             units=ncfile['time'].units,\n                             calendar=ncfile['time'].calendar)\n    # write lon/lat variables\n    lonvar = ncfile.createDimension('longitude', len(lon))\n    lonvar = ncfile.createVariable('longitude', 'float32', ('longitude',))\n    lonvar.units = 'degrees_east'\n    lonvar.axis = 'X'\n    lonvar.standard_name = 'longitude'\n    lonvar.long_name = 'Longitude'\n    lonvar[:] = lon\n    latvar = ncfile.createDimension('latitude', len(lat))\n    latvar = ncfile.createVariable('latitude', 'float32', ('latitude',))\n    latvar.units = 'degrees_north'\n    latvar.axis = 'Y'\n    latvar.standard_name = 'latitude'\n    latvar.long_name = 'Latitude'\n    latvar[:] = lat\n    return ncfile\n\n\ndef create_variable_sic(ncfile, sic):\n    '''\n    Add sea ice concentraction[time, lat, lon] to netCDF file\n\n    Args:\n        ncfile:     netCDF file handle\n        sic:        sea ice concentration in [frac]\n\n    Returns:\n        ncfile:     netCDF file handle\n    '''\n    sicvar = ncfile.createVariable('sic', 'float32',\n                                   ('time', 'latitude', 'longitude',),\n                                   zlib=True, fill_value=-1e30)\n    sicvar.standar_name = 'sea_ice_area_fration'\n    sicvar.long_name = 'SIC'\n    sicvar.units = '1'\n    sicvar.cell_methods = 'time: lat: lon: mean'\n    sicvar[:] = sic\n    return ncfile\n\n\ndef create_variable_sst(ncfile, sst):\n    '''\n    Add sea surface temperatures[time, lat, lon] to netCDF file\n\n    Args:\n        ncfile:     netCDF file handle\n        sst:        sea surface temperatures in [K]\n\n    Returns:\n        ncfile:     netCDF file handle\n    '''\n    sstvar = ncfile.createVariable('sst', 'float32',\n                                   ('time', 'latitude', 'longitude',),\n                                   fill_value=-1e30, zlib=True)\n    sstvar.standar_name = 'sea_surface_temperature'\n    sstvar.long_name = 'SST'\n    sstvar.units = 'K'\n    sstvar.cell_methods = 'time: lat: lon: mean'\n    sstvar[:] = sst\n    return ncfile\n\n\ndef sst_sic_adjustment(sst, siconc, units_sst='K', units_sic='frac'):\n    '''\n    Perform SST and SIC adjustments as per instructions:\n        1. Set minimum SST to -1.8 degC\n        2. Set SST to -1.8 degC if SIC>0.9\n        3. If SST>5 degC, set SIC to 0\n        4. If SIC<0.9, we calculate SSTmax, where\n           SSTmax=9.328(*0.729-SIC^3)-1.8. If SST>SSTmax,\n           reduce SIC so that SST=SSTmax.\n\n    Args:\n        sst:        sea surface temperatures in [degC] of [K]\n        siconc:     sea ice concentration in [frac] of [perc]\n        units_sst:  units of sst input, [degC] or [K]\n        units_sic:  units of siconc input [frac] of [perc]\n\n    Returns:\n        sst:        adjusted sea surface temperatures in [K]\n        siconc:     adjusted sea ice concentration in [frac]\n    '''\n    # get sst mask\n    sst_mask = np.ma.getmask(sst)\n    # convert units for calculation\n    if (units_sst == 'K'):\n        # convert to degC for calculations\n        sst = sst - 273.15\n    elif (units_sst == 'C'):\n        pass\n    else:\n        print('Unknown units for SST: ' + str(units_sst))\n        sys.exit()\n    if (units_sic == 'perc'):\n        # convert to fraction\n        siconc = siconc/100.\n    elif (units_sic == 'frac'):\n        pass\n    else:\n        print('Unknown units for SIC: ' + str(units_sic))\n        sys.exit()\n    # set minimum SST to -1.8 degC\n    np.ma.MaskedArray.clip(sst, -1.8, None, out=sst)\n    # set maximum SIC to 0.999478 (IFS segfaults when SIC=1)\n    np.ma.MaskedArray.clip(siconc, None, 0.999478, out=siconc)\n    # unshare mask\n    sst.unshare_mask()\n    siconc.unshare_mask()\n    # set SST to -1.8degC if sic>0.9\n    sst[siconc > 0.9] = -1.8\n    # If SST>5 degC, set SIC to 0\n    siconc[sst > 5] = 0\n    # If SIC<90%, we calculate SSTmax (SSTmax=9.328*(0.729-SIC^3)-1.8)\n    sstmax = np.zeros(np.shape(siconc))\n    idx_sic = (siconc < 0.9) & (siconc > 0)\n    sstmax[idx_sic] = (9.328 * (0.729-(siconc[idx_sic])**3)-1.8)\n    # If SST > SSTmax,reduce the SIC, so that SST=SSTmax\n    idx = (sst > sstmax) & (siconc < 0.9) & (siconc > 0)\n    siconc[idx] = (0.729 - ((sst[idx] + 1.8)/9.328))**(1/3)\n    # set maximum SIC to 0.999478 (IFS segfaults when SIC=1)\n    np.ma.MaskedArray.clip(siconc, None, 0.999478, out=siconc)\n    # convert SST to K\n    sst = sst + 273.15\n    # reapply original sst mask\n    sst = np.ma.masked_where(sst_mask, sst)\n    return sst, siconc\n\n\ndef exp1(startyear, endyear, overwrite=False):\n    '''\n    create input files for Blue Action experiment 1\n\n    Args:\n        startyear (int):      First year to use in calculations\n        endyear (int):        Stop calculations in the beginning of this year\n        overwrite (bool):     Force overwriting existing files\n    '''\n    # basestring input files\n    siconc_bs = (\"siconc_input4MIPs_SSTsAndSeaIce_HighResMIP_MOHC-\" +\n                 \"HadISST-2-2-0-0-0_gn_\")\n    tos_bs = (\"tos_input4MIPs_SSTsAndSeaIce_HighResMIP_MOHC-\" +\n              \"HadISST-2-2-0-0-0_gn_\")\n    # basestring output files\n    tos_bsout = 'HadISST2_prelim_0to360_alldays_sst_'\n    siconc_bsout = 'HadISST2_prelim_0to360_alldays_sic_'\n    # create output directory if needed\n    if not os.path.exists('exp1'):\n        os.makedirs('exp1')\n    # loop over all years\n    for yr in range(int(startyear), int(endyear)):\n        # input filenames\n        timestr = str(yr) + '0101-' + str(yr) + '1231'\n        filename_sic_in = os.path.join('siconc', siconc_bs + timestr + '.nc')\n        filename_tos_in = os.path.join('tos', tos_bs + timestr + '.nc')\n        # output filenames\n        filename_sic_out = os.path.join('exp1', siconc_bsout + str(yr) + '.nc')\n        filename_tos_out = os.path.join('exp1', tos_bsout + str(yr) + '.nc')\n        # check if existing file can be used\n        if (all(os.path.isfile(fl) for fl in\n                [filename_sic_out, filename_tos_out]) and not overwrite):\n            print('Keeping existing files: ' + filename_sic_out + ' and ' +\n                  filename_tos_out)\n            continue\n        # open output netCDF files\n        ncfile_tos_in = Dataset(filename_tos_in, 'r')\n        ncfile_sic_in = Dataset(filename_sic_in, 'r')\n        # open output netCDF files\n        ncfile_tos = Dataset(filename_tos_out, 'w')\n        ncfile_sic = Dataset(filename_sic_out, 'w')\n        # convert time to datetimeobject\n        dtobj = nc_num2date(ncfile_tos_in['time'][:],\n                            units=ncfile_tos_in['time'].units,\n                            calendar=ncfile_tos_in['time'].calendar)\n        sst = ncfile_tos_in.variables['tos'][:]\n        siconc = ncfile_sic_in.variables['siconc'][:]\n        lat = ncfile_tos_in.variables['latitude'][:]\n        lon = ncfile_tos_in.variables['longitude'][:]\n        # adjust sst and sic per instructions\n        sst, siconc = sst_sic_adjustment(sst, siconc,\n                                         units_sst='C', units_sic='perc')\n        # write sst\n        ncfile_tos = create_dimensions_netcdf(ncfile_tos, dtobj, lat, lon)\n        ncfile_tos = create_variable_sst(ncfile_tos, sst)\n        # write sic\n        ncfile_sic = create_dimensions_netcdf(ncfile_sic, dtobj, lat, lon)\n        ncfile_sic = create_variable_sic(ncfile_sic, siconc)\n        # close netCDF files\n        ncfile_tos.close()\n        ncfile_sic.close()\n        ncfile_tos_in.close()\n        ncfile_sic_in.close()\n\ndef exp3_4(startyear, endyear, expno, overwrite=False):\n    '''\n    create input files for Blue Action experiment 3 and/or 4\n\n    Args:\n        startyear (int):      First year to use in calculations\n        endyear (int):        Stop calculations in the beginning of this year\n        expno (int):          Experiment number (3 or 4)\n        overwrite (bool):     Force overwriting existing files\n    '''\n    if expno not in [3, 4]:\n        print('experiment number should be 3 or 4, returning...')\n        return\n    # basestring input files\n    siconc_bs = (\"siconc_input4MIPs_SSTsAndSeaIce_HighResMIP_MOHC-\" +\n                 \"HadISST-2-2-0-0-0_gn_\")\n    tos_bs = (\"tos_EXP\" + str(expno) + \"-HadISST-2-2-0-0-0_gn_\")\n    # basestring output files\n    tos_bsout = 'HadISST2_prelim_0to360_alldays_sst_'\n    siconc_bsout = 'HadISST2_prelim_0to360_alldays_sic_'\n    # create output directory if needed\n    if not os.path.exists('exp' + str(expno)):\n        os.makedirs('exp' + str(expno))\n    # loop over all years\n    for yr in range(int(startyear), int(endyear)):\n        # input filenames\n        timestr = str(yr) + '0101-' + str(yr) + '1231'\n        filename_sic_in = os.path.join('siconc', siconc_bs + timestr + '.nc')\n        filename_tos_in = os.path.join('input', 'EXP' + str(expno), tos_bs + timestr + '.nc')\n        # output filenames\n        filename_sic_out = os.path.join('exp' + str(expno), siconc_bsout + str(yr) + '.nc')\n        filename_tos_out = os.path.join('exp' + str(expno), tos_bsout + str(yr) + '.nc')\n        # check if existing file can be used\n        if (all(os.path.isfile(fl) for fl in\n                [filename_sic_out, filename_tos_out]) and not overwrite):\n            print('Keeping existing files: ' + filename_sic_out + ' and ' +\n                  filename_tos_out)\n            continue\n        # open output netCDF files\n        ncfile_tos_in = Dataset(filename_tos_in, 'r')\n        ncfile_sic_in = Dataset(filename_sic_in, 'r')\n        # open output netCDF files\n        ncfile_tos = Dataset(filename_tos_out, 'w')\n        ncfile_sic = Dataset(filename_sic_out, 'w')\n        # convert time to datetimeobject\n        dtobj = nc_num2date(ncfile_tos_in['time'][:],\n                            units=ncfile_tos_in['time'].units,\n                            calendar=ncfile_tos_in['time'].calendar)\n        sst = ncfile_tos_in.variables['tos'][:]\n        siconc = ncfile_sic_in.variables['siconc'][:]\n        lat = ncfile_tos_in.variables['latitude'][:]\n        lon = ncfile_tos_in.variables['longitude'][:]\n        # adjust sst and sic per instructions\n        sst, siconc = sst_sic_adjustment(sst, siconc,\n                                         units_sst='C', units_sic='perc')\n        # write sst\n        ncfile_tos = create_dimensions_netcdf(ncfile_tos, dtobj, lat, lon)\n        ncfile_tos = create_variable_sst(ncfile_tos, sst)\n        # write sic\n        ncfile_sic = create_dimensions_netcdf(ncfile_sic, dtobj, lat, lon)\n        ncfile_sic = create_variable_sic(ncfile_sic, siconc)\n        # close netCDF files\n        ncfile_tos.close()\n        ncfile_sic.close()\n        ncfile_tos_in.close()\n        ncfile_sic_in.close()\n\n\ndef exp2_climate(startyear, endyear, filename_sic_climate,\n                 filename_sst_climate):\n    '''\n    Calculate daily climate for SST/SIC for Blue Action experiment 2\n\n    Args:\n        startyear (int):        First year to use in calculations\n        endyear (int):          Stop calculations in the beginning of this year\n        filename_sic_climate:   Path sea ice concentration climate netCDF file\n        filename_sst_climate:   Path sea surface temperatures climate netCDF\n                                file\n    '''\n    # basestring files\n    sst_bs = 'HadISST2_prelim_0to360_alldays_sst_'\n    siconc_bs = 'HadISST2_prelim_0to360_alldays_sic_'\n    # calculate sea ice daily climate\n    fn_sic = [os.path.join('exp1', siconc_bs + str(yr) + '.nc') for yr in\n              range(int(startyear), int(endyear))]\n    fn_sic_str = ' '.join(map(str, fn_sic))\n    tmpfile = os.path.join('exp2', 'tmpfile.nc')\n    command = 'cdo cat ' + fn_sic_str + ' ' + tmpfile\n    subprocess.check_call(command, shell=True)\n    command = 'cdo ydaymean ' + tmpfile + ' ' + filename_sic_climate\n    subprocess.check_call(command, shell=True)\n    os.remove(tmpfile)\n    # calculate sst daily climate\n    fn_sst = [os.path.join('exp1', sst_bs + str(yr) + '.nc') for yr in\n              range(int(startyear), int(endyear))]\n    fn_sst_str = ' '.join(map(str, fn_sst))\n    command = 'cdo cat ' + fn_sst_str + ' ' + tmpfile\n    subprocess.check_call(command, shell=True)\n    command = 'cdo ydaymean ' + tmpfile + ' ' + filename_sst_climate\n    subprocess.check_call(command, shell=True)\n    os.remove(tmpfile)\n\n\ndef exp2(startyear, endyear, overwrite=False):\n    '''\n    Create input files for Blue Action experiment 2\n\n    Args:\n        startyear (int):      First year to use in calculations\n        endyear (int):        Stop calculations in the beginning of this year\n        overwrite (bool):     Force overwriting existing files\n    '''\n    # basestring files\n    sst_bs = 'HadISST2_prelim_0to360_alldays_sst_'\n    siconc_bs = 'HadISST2_prelim_0to360_alldays_sic_'\n    # input filenames climate\n    filename_sic_climate = os.path.join('exp2',\n                                        'sic_climate_' + str(startyear) +\n                                        '_' + str(endyear) + '.nc')\n    filename_sst_climate = os.path.join('exp2',\n                                        'sst_climate_' + str(startyear) +\n                                        '_' + str(endyear) + '.nc')\n    # create output directory if needed\n    if not os.path.exists('exp2'):\n        os.makedirs('exp2')\n    # check if existing file can be used\n    if (all(os.path.isfile(fl) for fl in\n            [filename_sic_climate, filename_sst_climate]) and not overwrite):\n        print('Keeping existing files: ' + filename_sic_climate +\n              ' and ' + filename_sst_climate)\n    else:\n        exp2_climate(startyear, endyear,\n                     filename_sic_climate, filename_sst_climate)\n    # open sst and sic daily climate netCDF files (r)\n    ncfile_sic_climate = Dataset(filename_sic_climate, 'r')\n    ncfile_sst_climate = Dataset(filename_sst_climate, 'r')\n    sst_clim = ncfile_sst_climate.variables['sst'][:]\n    sic_clim = ncfile_sic_climate.variables['sic'][:]\n    # loop over all years of exp 1 files\n    for idx, yr in enumerate(range(int(startyear), int(endyear))):\n        # input filenames\n        filename_sic_in = os.path.join('exp1', siconc_bs + str(yr) + '.nc')\n        filename_sst_in = os.path.join('exp1', sst_bs + str(yr) + '.nc')\n        # output filenames\n        filename_sic_out = os.path.join('exp2', siconc_bs + str(yr) + '.nc')\n        filename_sst_out = os.path.join('exp2', sst_bs + str(yr) + '.nc')\n        # check if existing file can be used\n        if ((os.path.isfile(filename_sic_out) and\n             (os.path.isfile(filename_sst_out)) and\n             not overwrite)):\n            print('Keeping existing files: ' + filename_sic_out +\n                  ' and ' + filename_sst_out)\n            continue\n        # open input files (r)\n        ncfile_sic_in = Dataset(filename_sic_in, 'r')\n        ncfile_sst_in = Dataset(filename_sst_in, 'r')\n        # open output files (rw)\n        ncfile_sic_out = Dataset(filename_sic_out, 'w')\n        ncfile_sst_out = Dataset(filename_sst_out, 'w')\n        # convert time to datetimeobject\n        dtobj = nc_num2date(ncfile_sst_in['time'][:],\n                            units=ncfile_sst_in['time'].units,\n                            calendar=ncfile_sst_in['time'].calendar)\n        sst = ncfile_sst_in.variables['sst'][:]\n        lat = ncfile_sst_in.variables['latitude'][:]\n        lon = ncfile_sst_in.variables['longitude'][:]\n        # get sst mask\n        sst_mask = np.ma.getmask(sst)\n        # use sic_clim for sic and sst_clim where sic>0\n        sst = np.where(sic_clim[0:np.shape(sst)[0], :] > 0,\n                       sst_clim[0:np.shape(sst)[0], :], sst)\n        # reapply original sst mask\n        sst = np.ma.masked_where(sst_mask, sst)\n        sic = sic_clim[0:np.shape(sst)[0], :]  # make sure ndays are equal\n        # redo the sst and sic adjustments as per instruction\n        sst, sic = sst_sic_adjustment(sst, sic,\n                                      units_sst='K', units_sic='frac')\n        # write sst\n        ncfile_sst_out = create_dimensions_netcdf(ncfile_sst_out, dtobj,\n                                                  lat, lon)\n        ncfile_sst_out = create_variable_sst(ncfile_sst_out, sst)\n        # write sic\n        ncfile_sic_out = create_dimensions_netcdf(ncfile_sic_out, dtobj,\n                                                  lat, lon)\n        ncfile_sic_out = create_variable_sic(ncfile_sic_out, sic)\n        # close netCDF files\n        ncfile_sic_out.close()\n        ncfile_sst_out.close()\n        ncfile_sic_in.close()\n        ncfile_sst_in.close()\n    # close daily climate netCDF files\n    ncfile_sic_climate.close()\n    ncfile_sst_climate.close()\n\n\nif __name__ == \"__main__\":\n    # define command line arguments\n    parser = argparse.ArgumentParser()\n    parser.add_argument('-s', '--startyear', type=int, default=1979,\n                        help=\"startyear to use for processing files [default 1979]\")\n    parser.add_argument('-e', '--endyear', type=int, default=2016,\n                        help=\"stop processing in the beginning of endyear [default 2016]\")\n    parser.add_argument('-f', '--force', action='store_true',\n                        help=\"force overwriting existing files\")\n    # get arguments\n    args = parser.parse_args()\n    # call main()\n    main(args.startyear, args.endyear, args.force)\n", "meta": {"hexsha": "a268bfcceb4f54a9b842a36468241de8a5fc90ab", "size": 19094, "ext": "py", "lang": "Python", "max_stars_repo_path": "blctn-input.py", "max_stars_repo_name": "blue-action/blctn-input", "max_stars_repo_head_hexsha": "921905ad828a2fe36aea0e869b14d53bd13dee0c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-02-26T14:59:59.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-26T14:59:59.000Z", "max_issues_repo_path": "blctn-input.py", "max_issues_repo_name": "blue-action/blctn-input", "max_issues_repo_head_hexsha": "921905ad828a2fe36aea0e869b14d53bd13dee0c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "blctn-input.py", "max_forks_repo_name": "blue-action/blctn-input", "max_forks_repo_head_hexsha": "921905ad828a2fe36aea0e869b14d53bd13dee0c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-03-14T13:47:13.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-14T13:47:13.000Z", "avg_line_length": 40.886509636, "max_line_length": 93, "alphanum_fraction": 0.6075206871, "include": true, "reason": "import numpy", "num_tokens": 5343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.1756382744601729}}
{"text": "import random\nfrom pathlib import Path\nimport math\nimport logging\nimport os\n\nfrom collections import defaultdict\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport gym\nfrom gym import spaces\nfrom gym.spaces.box import Box\nfrom gym.spaces.discrete import Discrete\n\nimport numpy as np\n\nfrom deep_rl import Task, Config, Logger, BaseNormalizer\nfrom deep_rl.component.envs import DummyVecEnv, SubprocVecEnv, OriginalReturnWrapper\nfrom deep_rl.network import GaussianActorCriticNet, DeterministicActorCriticNet, NoisyLinear, layer_init\n\nfrom py_diff_pd.core.py_diff_pd_core import HexMesh3d, HexDeformable, StdRealVector, StdIntVector, QuadMesh2d\nfrom py_diff_pd.common.common import create_folder, ndarray, print_info\nfrom py_diff_pd.common.hex_mesh import generate_hex_mesh, get_boundary_face\nfrom py_diff_pd.common.display import export_gif, Arrow3D\n\nfrom baselines.common.running_mean_std import RunningMeanStd\n\n\nclass MeanStdNormalizer(BaseNormalizer):\n    def __init__(self, read_only=False, clip=10.0, epsilon=1e-8):\n        BaseNormalizer.__init__(self, read_only)\n        self.read_only = read_only\n        self.rms = None\n        self.clip = clip\n        self.epsilon = epsilon\n\n    def __call__(self, x):\n        x = np.asarray(x)\n        if self.rms and self.read_only:\n            return np.clip(x, -self.clip, self.clip)\n        if self.rms is None:\n            self.rms = RunningMeanStd(shape=(1,) + x.shape[1:])\n        if not self.read_only:\n            self.rms.update(x)\n        return np.clip((x - self.rms.mean) / np.sqrt(self.rms.var + self.epsilon),\n                       -self.clip, self.clip)\n\n    def state_dict(self):\n        return {'mean': self.rms.mean,\n                'var': self.rms.var}\n\n    def load_state_dict(self, saved):\n        self.rms.mean = saved['mean']\n        self.rms.var = saved['var']\n\n\ndef tensor(x):\n    if isinstance(x, torch.Tensor):\n        return x\n    x = np.asarray(x, dtype=np.float64)\n    x = torch.from_numpy(x).to(Config.DEVICE)\n    return x\n\n\nclass LayerNormFCBody(nn.Module):\n    def __init__(self, state_dim, hidden_units=(64, 64), gate=F.relu, noisy_linear=False):\n        super(LayerNormFCBody, self).__init__()\n        dims = (state_dim,) + hidden_units\n        if noisy_linear:\n            self.layers = nn.ModuleList(\n                [NoisyLinear(dim_in, dim_out) for dim_in, dim_out in zip(dims[:-1], dims[1:])])\n        else:\n            self.layers = nn.ModuleList(\n                [nn.Sequential(*[\n                    nn.Linear(dim_in, dim_out, bias=False),\n                    nn.LayerNorm(dim_out, elementwise_affine=True)\n                    ]) for dim_in, dim_out in zip(dims[:-1], dims[1:])])\n\n        self.gate = gate\n        self.feature_dim = dims[-1]\n        self.noisy_linear = noisy_linear\n\n    def reset_noise(self):\n        if self.noisy_linear:\n            for layer in self.layers:\n                layer.reset_noise()\n\n    def forward(self, x):\n        for layer in self.layers:\n            x = self.gate(layer(x))\n        return x\n\n\nclass MyDeterministicActorCriticNet(DeterministicActorCriticNet):\n    def feature(self, obs):\n        obs = tensor(obs)\n        return self.phi_body(obs)\n\n    def save(self, path):\n        torch.save({\n            'checkpoints': self.network.state_dict(),\n            'normalizer': self.config.state_normalizer.state_dict(),\n        }, path)\n\n    def load(self, path):\n        state_dict = torch.load(path, map_location='cpu')\n        self.network.load_state_dict(state_dict['checkpoints'])\n        self.config.state_normalizer.load_state_dict(state_dict['normalizer'])\n\n\nclass MyGaussianActorCriticNet(GaussianActorCriticNet):\n    def forward(self, obs, action=None):\n        obs = tensor(obs)\n        phi = self.phi_body(obs)\n        phi_a = self.actor_body(phi)\n        phi_v = self.critic_body(phi)\n        mean = torch.tanh(self.fc_action(phi_a))\n        v = self.fc_critic(phi_v)\n        dist = torch.distributions.Normal(mean, F.softplus(self.std))\n        if action is None:\n            action = dist.sample()\n        log_prob = dist.log_prob(action).sum(-1).unsqueeze(-1)\n        entropy = dist.entropy().sum(-1).unsqueeze(-1)\n        return {'action': action,\n                'log_pi_a': log_prob,\n                'entropy': entropy,\n                'mean': mean,\n                'v': v}\n\n    def save(self, path):\n        torch.save({\n            'checkpoints': self.network.state_dict(),\n            'normalizer': self.config.state_normalizer.state_dict(),\n        }, path)\n\n    def load(self, path):\n        state_dict = torch.load(path, map_location='cpu')\n        self.network.load_state_dict(state_dict['checkpoints'])\n        self.config.state_normalizer.load_state_dict(state_dict['normalizer'])\n\n\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s: %(message)s')\n\ndef get_logger(path, log_level=0):\n    logger = logging.getLogger()\n    logger.setLevel(logging.INFO)\n    return Logger(logger, str(path), log_level)\n\n\nclass DiffPDTask(Task):\n    def __init__(\n            self,\n            env_fn,\n            sim_class,\n            seed,\n            num_envs=1,\n            single_process=True,\n            episode_life=True,\n        ):\n\n        envs = [make_env(env_fn, sim_class, seed, i, episode_life) for i in range(num_envs)]\n        if num_envs == 1 or single_process:\n            Wrapper = DummyVecEnv\n        else:\n            Wrapper = SubprocVecEnv\n        self.env = Wrapper(envs)\n        self.name = 'diffpd'\n        self.observation_space = self.env.observation_space\n        self.state_dim = int(np.prod(self.env.observation_space.shape))\n\n        self.action_space = self.env.action_space\n        if isinstance(self.action_space, Discrete):\n            self.action_dim = self.action_space.n\n        elif isinstance(self.action_space, Box):\n            self.action_dim = self.action_space.shape[0]\n        else:\n            assert 'unknown action space'\n\n    def reset(self):\n        return self.env.reset()\n\n    def step(self, actions):\n        if isinstance(self.action_space, Box):\n            actions = np.clip(actions, self.action_space.low, self.action_space.high)\n        return self.env.step(actions)\n\n\ndef make_env(env_fn, *args, **kwargs):\n    def _thunk():\n        env = env_fn(*args, **kwargs)\n        env = OriginalReturnWrapper(env)\n\n        return env\n    return _thunk\n\n\ndef make_water_snake_3d(sim_class, seed, rank, *args, **kwargs):\n\n    os.system(\"taskset -p 0xff %d\" % os.getpid())\n\n    seed = seed + rank\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.set_default_dtype(torch.float64)\n\n    folder = Path('water_snake').resolve()\n    folder.mkdir(parents=True, exist_ok=True)\n\n    # Mesh parameters.\n    cell_nums = [20, 2, 2]\n    node_nums = [c + 1 for c in cell_nums]\n    dx = 0.1\n    origin = np.zeros((3,))\n    bin_file_name = str(folder / 'water_snake.bin')\n    voxels = np.ones(cell_nums)\n\n    voxel_indices, vertex_indices = generate_hex_mesh(voxels, dx, origin, bin_file_name, write=False)\n    mesh = HexMesh3d()\n    mesh.Initialize(bin_file_name)\n\n    # FEM parameters.\n    youngs_modulus = 1e6\n    poissons_ratio = 0.45\n    density = 1e3\n    method = 'pd_eigen'\n    opt = {\n        'max_pd_iter': 1000, 'max_ls_iter': 10, 'abs_tol': 1e-4, 'rel_tol': 1e-3, 'verbose': 0,\n        'thread_ct': 1, 'use_bfgs': 1, 'bfgs_history_size': 10\n    }\n\n    deformable = HexDeformable()\n    deformable.Initialize(bin_file_name, density, 'none', youngs_modulus, poissons_ratio)\n    # Elasticity.\n    deformable.AddPdEnergy('corotated', [youngs_modulus / (1 + poissons_ratio),], [])\n    # Hydrodynamics parameters.\n    rho = 1e3\n    v_water = [0, 0, 0]   # Velocity of the water.\n    # # Cd_points = (angle, coeff) pairs where angle is normalized to [0, 1].\n    Cd_points = ndarray([[0.0, 0.05], [0.4, 0.05], [0.7, 1.85], [1.0, 2.05]])\n    # # Ct_points = (angle, coeff) pairs where angle is normalized to [-1, 1].\n    Ct_points = ndarray([[-1, -0.8], [-0.3, -0.5], [0.3, 0.1], [1, 2.5]])\n    # The current Cd and Ct are similar to Figure 2 in SoftCon.\n    # surface_faces is a list of (v0, v1) where v0 and v1 are the vertex indices of the two endpoints of a boundary edge.\n    # The order of (v0, v1) is determined so that following all v0 -> v1 forms a ccw contour of the deformable body.\n    surface_faces = get_boundary_face(mesh)\n    deformable.AddStateForce(\n        'hydrodynamics', np.concatenate(\n            [[rho,], v_water, Cd_points.ravel(), Ct_points.ravel(), ndarray(surface_faces).ravel()]))\n\n    # Add actuation.\n    # ******************** <- muscle\n    # |                  | <- body\n    # |                  | <- body\n    # ******************** <- muscle\n\n    all_muscles = []\n    shared_muscles = []\n    for i in [0, cell_nums[2] - 1]:\n        muscle_pair = []\n        for j in [0, cell_nums[1] - 1]:\n            indices = voxel_indices[:, j, i].tolist()\n            deformable.AddActuation(1e5, [1.0, 0.0, 0.0], indices)\n            muscle_pair.append(indices)\n        shared_muscles.append(muscle_pair)\n    all_muscles.append(shared_muscles)\n    deformable.all_muscles = all_muscles\n\n    # Implement the forward and backward simulation.\n    dt = 3.33e-2\n    num_frames = 200\n    dofs = deformable.dofs()\n    act_dofs = deformable.act_dofs()\n    arrow_target_data = np.array([-1, 0, 0], dtype=np.float64)\n\n    w_sideward = 10.0\n    w_face = 0.0\n\n    mid_x = math.floor(node_nums[0] / 2)\n    mid_y = math.floor(node_nums[1] / 2)\n    mid_z = math.floor(node_nums[2] / 2)\n    mid_line = vertex_indices[:, mid_y, mid_z]\n    center = vertex_indices[mid_x, mid_y, mid_z]\n\n    face_head = vertex_indices[0, mid_y, mid_z]\n    face_tail = vertex_indices[2, mid_y, mid_z]\n\n    def get_state_(sim, q_, v_, a_=None, f_ext_=None):\n        q_center = q_.reshape((-1, 3))[center]\n        v_center = v_.reshape((-1, 3))[center]\n\n        q_mid_line_rel = q_.reshape((-1, 3))[mid_line] - q_center\n        v_mid_line = v_.reshape((-1, 3))[mid_line]\n        state = [\n            v_center,\n            q_mid_line_rel.ravel(),\n            v_mid_line.ravel(),\n        ]\n        return np.concatenate(state).copy()\n\n    def get_reward_(sim, q_, v_, a_=None, f_ext_=None):\n\n        v_center = np.mean(v_.reshape((-1, 3))[mid_line], axis=0)\n        face_dir = q_.reshape((-1, 3))[face_head] - q_.reshape((-1, 3))[face_tail]\n        face_dir = face_dir / np.linalg.norm(face_dir)\n\n        # forward loss\n        forward_reward = np.dot(v_center, arrow_target_data)\n\n        # sideward loss\n        cross = np.cross(v_center, arrow_target_data)\n        sideward_reward = -np.dot(cross, cross)\n\n        # face loss\n        face_reward = np.dot(face_dir, arrow_target_data)\n\n        return forward_reward + w_sideward * sideward_reward + w_face * face_reward\n\n    def get_done_(sim, q_, v_, a_, f_ext_):\n        if sim.frame >= sim.num_frames:\n            return True\n        return False\n\n    setattr(sim_class, 'get_state_', get_state_)\n    setattr(sim_class, 'get_reward_', get_reward_)\n    setattr(sim_class, 'get_done_', get_done_)\n\n    sim = sim_class(\n        deformable, mesh, center, dofs, act_dofs, method, dt, opt, num_frames)\n\n    if sim_class is AdaSim:\n        action_shape = (len(all_muscles),)\n    elif sim_class is IndSim:\n        muscle_dofs = 0\n        for shared_muscles in all_muscles:\n            muscle_dofs += len(shared_muscles[0][0])\n        action_shape = (muscle_dofs,)\n    else:\n        raise ValueError('invalid simulation class')\n\n    sim.set_action_space(action_shape)\n\n    sim.observation_space.seed(seed + rank)\n    sim.action_space.seed(seed + rank)\n\n    return sim\n\n\n\ndef make_starfish_3d(sim_class, seed, rank, *args, **kwargs):\n\n    os.system(\"taskset -p 0xff %d\" % os.getpid())\n\n    seed = seed + rank\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.set_default_dtype(torch.float64)\n\n    folder = Path('starfish').resolve()\n    folder.mkdir(parents=True, exist_ok=True)\n\n    # Mesh parameters\n    limb_width = 2\n    limb_length = 10\n    limb_depth = 2\n\n    cell_nums = [limb_length * 2 + limb_width, limb_length * 2 + limb_width, limb_depth]\n    node_nums = [c + 1 for c in cell_nums]\n    dx = 0.1\n    origin = np.zeros((3,))\n    bin_file_name = str(folder / 'starfish.bin')\n\n    voxels = np.ones(cell_nums)\n    voxels[:limb_length, :limb_length] = 0\n    voxels[:limb_length, -limb_length:] = 0\n    voxels[-limb_length:, :limb_length] = 0\n    voxels[-limb_length:, -limb_length:] = 0\n\n    voxel_indices, vertex_indices = generate_hex_mesh(\n        voxels, dx, origin, bin_file_name, write=False)\n    mesh = HexMesh3d()\n    mesh.Initialize(bin_file_name)\n\n    # FEM parameters.\n    youngs_modulus = 1e6\n    poissons_ratio = 0.45\n    density = 1e3\n    method = 'pd_eigen'\n    opt = {\n        'max_pd_iter': 1000, 'max_ls_iter': 10, 'abs_tol': 1e-4, 'rel_tol': 1e-3, 'verbose': 0,\n        'thread_ct': 1, 'use_bfgs': 1, 'bfgs_history_size': 10\n    }\n\n    deformable = HexDeformable()\n    deformable.Initialize(bin_file_name, density, 'none', youngs_modulus, poissons_ratio)\n    # Elasticity.\n    deformable.AddPdEnergy('corotated', [youngs_modulus / (1 + poissons_ratio),], [])\n    # Hydrodynamics parameters.\n    rho = 1e3\n    v_water = [0, 0, 0]   # Velocity of the water.\n    # # Cd_points = (angle, coeff) pairs where angle is normalized to [0, 1].\n    Cd_points = ndarray([[0.0, 0.05], [0.4, 0.05], [0.7, 1.85], [1.0, 2.05]])\n    # # Ct_points = (angle, coeff) pairs where angle is normalized to [-1, 1].\n    Ct_points = ndarray([[-1, -0.8], [-0.3, -0.5], [0.3, 0.1], [1, 2.5]])\n    # The current Cd and Ct are similar to Figure 2 in SoftCon.\n    # surface_faces is a list of (v0, v1) where v0 and v1 are the vertex indices of the two endpoints of a boundary edge.\n    # The order of (v0, v1) is determined so that following all v0 -> v1 forms a ccw contour of the deformable body.\n    surface_faces = get_boundary_face(mesh)\n    deformable.AddStateForce(\n        'hydrodynamics', np.concatenate(\n            [[rho,], v_water, Cd_points.ravel(), Ct_points.ravel(), ndarray(surface_faces).ravel()]))\n\n    # Add actuation.\n    all_muscles = []\n    muscle_pairs = []\n\n    muscle_stiffness = 1e5\n\n    for move in [range(limb_length - 1, -1, -1), range(-limb_length, 0)]:\n        for fix in [limb_length, limb_length + limb_width - 1]:\n\n            muscle_pair = []\n            for depth in [0, limb_depth - 1]:\n                indices = [int(voxel_indices[fix, m, depth]) for m in move]\n                deformable.AddActuation(muscle_stiffness, [0.0, 1.0, 0.0], indices)\n                muscle_pair.append(indices)\n            muscle_pairs.append(muscle_pair)\n\n            muscle_pair = []\n            for depth in [0, limb_depth - 1]:\n                indices = [int(voxel_indices[m, fix, depth]) for m in move]\n                deformable.AddActuation(muscle_stiffness, [1.0, 0.0, 0.0], indices)\n                muscle_pair.append(indices)\n            muscle_pairs.append(muscle_pair)\n\n    all_muscles = [\n        [muscle_pairs[0], muscle_pairs[2]],\n        [muscle_pairs[1], muscle_pairs[3]],\n        [muscle_pairs[4], muscle_pairs[6]],\n        [muscle_pairs[5], muscle_pairs[7]],\n    ]\n    deformable.all_muscles = all_muscles\n\n    # Implement the forward and backward simulation.\n    dt = 3.33e-2\n    num_frames = 200\n    dofs = deformable.dofs()\n    act_dofs = deformable.act_dofs()\n    arrow_target_data = np.array([0, 0, 1], dtype=np.float64)\n\n    w_sideward = 1.0\n    w_face = 0.0\n\n    mid_x = math.floor(node_nums[0] / 2)\n    mid_y = math.floor(node_nums[1] / 2)\n    mid_z = math.floor(node_nums[2] / 2)\n    center = vertex_indices[mid_x, mid_y, mid_z]\n\n    face_head = vertex_indices[mid_x, mid_y, -1]\n    face_tail = vertex_indices[mid_x, mid_y, 0]\n\n    mid_plane = np.array([\n        vertex_indices[mid_x, :limb_length, mid_z],\n        vertex_indices[mid_x, -limb_length:, mid_z],\n        vertex_indices[:limb_length, mid_y, mid_z],\n        vertex_indices[-limb_length:, mid_y, mid_z],\n    ]).ravel()\n\n    def get_state_(sim, q_, v_, a_=None, f_ext_=None):\n        q_center = q_.reshape((-1, 3))[center]\n        v_center = v_.reshape((-1, 3))[center]\n\n        q_mid_line_rel = q_.reshape((-1, 3))[mid_plane] - q_center\n        v_mid_line = v_.reshape((-1, 3))[mid_plane]\n        state = [\n            v_center,\n            q_mid_line_rel.ravel(),\n            v_mid_line.ravel(),\n        ]\n        return np.concatenate(state).copy()\n\n    def get_reward_(sim, q_, v_, a_=None, f_ext_=None):\n\n        v_center = v_.reshape((-1, 3))[center]\n        face_dir = q_.reshape((-1, 3))[face_head] - q_.reshape((-1, 3))[face_tail]\n        face_dir = face_dir / np.linalg.norm(face_dir)\n\n        # forward loss\n        forward_reward = np.dot(v_center, arrow_target_data)\n\n        # sideward loss\n        cross = np.cross(v_center, arrow_target_data)\n        sideward_reward = -np.dot(cross, cross)\n\n        # face loss\n        face_reward = np.dot(face_dir, arrow_target_data)\n\n        return forward_reward + w_sideward * sideward_reward + w_face * face_reward\n\n    def get_done_(sim, q_, v_, a_, f_ext_):\n        if sim.frame >= sim.num_frames:\n            return True\n        return False\n\n    setattr(sim_class, 'get_state_', get_state_)\n    setattr(sim_class, 'get_reward_', get_reward_)\n    setattr(sim_class, 'get_done_', get_done_)\n\n    sim = sim_class(\n        deformable, mesh, center, dofs, act_dofs, method, dt, opt, num_frames)\n\n    if sim_class is AdaSim:\n        action_shape = (len(all_muscles),)\n    elif sim_class is IndSim:\n        muscle_dofs = 0\n        for shared_muscles in all_muscles:\n            muscle_dofs += len(shared_muscles[0][0])\n        action_shape = (muscle_dofs,)\n    else:\n        raise ValueError('invalid simulation class')\n\n    sim.set_action_space(action_shape)\n\n    sim.observation_space.seed(seed + rank)\n    sim.action_space.seed(seed + rank)\n\n    return sim\n\n\nclass AdaSim(gym.Env):\n\n    \"\"\"Custom Environment that follows gym interface\"\"\"\n    metadata = {'render.modes': ['human']}\n\n    def __init__(\n            self, deformable, mesh, center,\n            dofs, act_dofs, method, dt, option, num_frames\n        ):\n\n        super(AdaSim, self).__init__()\n        self.deformable = deformable\n        self.mesh = mesh\n        self.center = center\n        self.dofs = dofs\n        self.act_dofs = act_dofs\n        self.method = method\n        self.dt = dt\n        self.option = option\n        self.num_frames = num_frames\n\n        self.a_init = np.zeros(self.act_dofs)\n        self.prev_a = None\n\n        self.frame = 0\n\n        self.q = None\n        self.v = None\n\n        if isinstance(mesh, Mesh2d):\n            dim = 2\n        elif isinstance(mesh, HexMesh3d):\n            dim = 3\n        else:\n            raise ValueError(f'invlaid mesh type: {type(mesh)}')\n\n        q0 = ndarray(self.mesh.py_vertices())\n        q0_center = q0.reshape((-1, dim))[center]\n        self.q0 = (q0.reshape((-1, dim)) - q0_center).ravel()\n        self.v0 = np.zeros_like(q0, dtype=np.float64)\n        self.f_ext = np.zeros_like(q0, dtype=np.float64)\n\n        self.observation_space = spaces.Box(\n            low=-10.0, high=10.0, shape=self.get_state_(self.q0, self.v0).shape, dtype=np.float64) # pylint: disable=no-member\n        self.action_space = None\n        self.reset()\n\n    def set_action_space(self, action_shape):\n        self.action_space = spaces.Box(low=-1.0, high=1.0, shape=action_shape, dtype=np.float64)\n\n    def get_action(self, action):\n\n        if self.prev_a is None:\n            prev_a = self.a_init.copy()\n        else:\n            prev_a = self.prev_a\n\n        a = []\n        pointer = 0\n\n        for w, shared_muscles in zip(action, self.deformable.all_muscles):\n            mu_pair = [0.5 * (np.abs(w) - w), 0.5 * (np.abs(w) + w)]\n            for muscle_pair in shared_muscles:\n                if len(muscle_pair) != 2:\n                    raise ValueError('adaptive controller require paired muscles')\n                for mu, muscle in zip(mu_pair, muscle_pair):\n                    prev_a_cord = prev_a[pointer:pointer + len(muscle)]\n                    pointer += len(muscle)\n                    a_cord = np.concatenate([mu.reshape((1,)), prev_a_cord[:-1]])\n                    a.append(a_cord)\n\n        a = np.array(a).ravel()\n        self.prev_a = a.copy()\n        return 1 - a\n\n    def step(self, a):\n\n        self.frame += 1\n\n        a = self.get_action(a)\n\n        q_array = StdRealVector(self.q)\n        v_array = StdRealVector(self.v)\n        a_array = StdRealVector(a)\n        f_ext_array = StdRealVector(self.f_ext)\n        q_next_array = StdRealVector(self.dofs)\n        v_next_array = StdRealVector(self.dofs)\n\n        self.deformable.PyForward(\n            self.method, q_array, v_array, a_array, f_ext_array,\n            self.dt, self.option, q_next_array, v_next_array, StdIntVector(0))\n\n        q = ndarray(q_next_array)\n        v = ndarray(v_next_array)\n\n        self.q, self.v = q.copy(), v.copy()\n\n        state = self.get_state_(q, v, a, self.f_ext) # pylint: disable=no-member\n        reward = self.get_reward_(q, v, a, self.f_ext) # pylint: disable=no-member\n        done = self.get_done_(q, v, a, self.f_ext) # pylint: disable=no-member\n\n        if done:\n            self.reset()\n\n        return state, reward, done, dict()\n\n    def reset(self):\n        self.frame = 0\n        self.q = self.q0.copy()\n        self.v = self.v0.copy()\n        self.prev_a = None\n\n        return self.get_state_(self.q, self.v) # pylint: disable=no-member\n\n\nclass IndSim(AdaSim):\n    def get_action(self, action):\n\n        a_shared_muscles = []\n        a = []\n\n        pointer = 0\n        for shared_muscles in self.deformable.all_muscles:\n            a_shared_muscles.append(action[pointer:pointer + len(shared_muscles[0][0])])\n\n        for w, shared_muscles in zip(a_shared_muscles, self.deformable.all_muscles):\n            mu_pair = [0.5 * (np.abs(w) - w), 0.5 * (np.abs(w) + w)]\n            for muscle_pair in shared_muscles:\n                if len(muscle_pair) != 2:\n                    raise ValueError('adaptive controller require paired muscles')\n                for mu, muscle in zip(mu_pair, muscle_pair):\n                    a.append(mu)\n\n        a = np.array(a).ravel()\n        return 1 - a\n", "meta": {"hexsha": "540115c0c77d411adb1726f5440acd6e930f5c0d", "size": 22296, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/py_diff_pd/common/rl_sim.py", "max_stars_repo_name": "brokencuph/diff_pd", "max_stars_repo_head_hexsha": "2c30ecfa39762c5fc78dea9c7a226000e9fc5c15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-02-10T02:28:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T07:28:35.000Z", "max_issues_repo_path": "python/py_diff_pd/common/rl_sim.py", "max_issues_repo_name": "srl-ethz/diffPD_sim2real", "max_issues_repo_head_hexsha": "e491668995a163b8ff7542d99f0b4e0c0f4ed2df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/py_diff_pd/common/rl_sim.py", "max_forks_repo_name": "srl-ethz/diffPD_sim2real", "max_forks_repo_head_hexsha": "e491668995a163b8ff7542d99f0b4e0c0f4ed2df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-03-11T20:13:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T03:38:46.000Z", "avg_line_length": 33.2776119403, "max_line_length": 126, "alphanum_fraction": 0.6137872264, "include": true, "reason": "import numpy", "num_tokens": 6013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3380771174808128, "lm_q1q2_score": 0.17563827099538493}}
{"text": "#!/usr/bin/env python3\n\"\"\"\nSWC: Manipulate graph data in SWC format.\n\nIncludes read/write to disk.\n\"\"\"\nfrom typing import Dict, List, Tuple, Union\nimport math\n\nimport networkx as nx\nimport numpy as np\n\n\nclass NodeTypes:\n    \"\"\"\n    Enum of types for nodes in SWC.\n\n    range(8)\n    \"\"\"\n\n    UNDEFINED = 0\n    SOMA = 1\n    AXON = 2\n    DENDRITE = 3\n    APICAL_DENDRITE = 4\n    FORK_POINT = 5\n    END_POINT = 6\n    CUSTOM = 7\n\n    @staticmethod\n    def is_valid(cls, t: int) -> bool:\n        \"\"\"\n        Determine if a node type is a valid SWC-spec type.\n\n        Arguments:\n            t (int): Type\n\n        Returns:\n            bool: True if valid\n\n        \"\"\"\n        return t in [0, 1, 2, 3, 4, 5, 6, 7]\n\n\nclass NeuronMorphology:\n    \"\"\"\n    A wrapper class for neuron morphologies.\n\n    Contains a graph representation of the morphology in nx.DiGraph format.\n    \"\"\"\n\n    def __init__(self, **kwargs):\n        \"\"\"\n        Create a new NeuronMorphology.\n\n        Arguments:\n            source (NeuronMorphology): Optional. Source to copy from\n\n        \"\"\"\n        if \"source\" in kwargs:\n            if isinstance(kwargs[\"source\"], NeuronMorphology):\n                self._skeleton = kwargs[\"source\"].get_graph()\n            elif isinstance(kwargs[\"source\"], nx.Graph):\n                self._skeleton = kwargs[\"source\"]\n            else:\n                raise ValueError(\n                    \"The `source` argument passed to the NeuronMorphology \"\n                    + \"constructor must be a graph or a NeuronMorphology.\"\n                    + \"Type was {}.\".format(type(kwargs[\"source\"]))\n                )\n        else:\n            self._skeleton = nx.DiGraph()\n\n    def __len__(self):\n        return len(self._skeleton)\n\n    def get_graph(self, copy: bool = True) -> nx.DiGraph:\n        \"\"\"\n        Return the underlying graph data structure.\n\n        By default, this returns a copy, so that modifications to this graph do\n        not affect the parent NeuronMorphology (which is expected behavior).\n        However, by explicitly passing `copy=False`, you can request a pointer\n        to the same graph.\n\n        Arguments:\n            copy (bool : True): If a copy should be returned instead of a\n                pointer to the original\n\n        Returns:\n            networkx.Graph: The graph data structure that backs the morphology\n\n        \"\"\"\n        if copy:\n            return self._skeleton.copy()\n        else:\n            return self._skeleton\n\n    def add_node(\n        self, id: int, t: int = None, xyz: Tuple[int, int, int] = None, r: float = None\n    ) -> None:\n        \"\"\"\n        Add a new node to the skeleton.\n\n        Arguments:\n            id (int): The ID of the node (0 is invalid)\n            t (int): The type of node. Validate with `NodeTypes.is_valid(t)`\n            xyz (int[3]): The xyz position of the node\n            r (float): The radius of the neuron at this node\n\n        Returns:\n            None\n        \"\"\"\n        return self._skeleton.add_node(id, t=t, xyz=xyz, r=r)\n\n    def add_edge(self, start: int, end: int) -> None:\n        \"\"\"\n        Add a new edge to the skeleton.\n\n        Arguments:\n            start (int): The origin of the edge (ID)\n            stop (int): The end of the edge (ID)\n\n        Returns:\n            None\n\n        \"\"\"\n        return self._skeleton.add_edge(start, end)\n\n    def get_branch_points(self) -> List[int]:\n        \"\"\"\n        Returns a list of all node IDs where degree > 2.\n\n        Arguments:\n            None\n\n        Returns:\n            int[]: Node IDs where degree > 2\n        \"\"\"\n        results: List[int] = []\n        for start, stops in self._skeleton.pred.items():\n            if len(stops.keys()) >= 2:\n                results.append(start)\n        return results\n\n    def get_branch_angles(self) -> Dict[int, float]:\n        \"\"\"Get the branch angles between all connected nodes.\"\"\"\n\n        angles = {}\n        for node in self._skeleton.nodes():\n            neighbors = [i for i in nx.all_neighbors(self._skeleton, node)]\n            if (len(neighbors)) == 2:\n                # This is not a branch point, so we can compute:\n                angles[node] = self.get_branch_angle((neighbors[0], node, neighbors[1]))\n        return angles\n\n    def get_branch_angle(self, abc: Tuple[int, int, int]):\n        \"\"\"\n        Returns the minimum branch angle between edges AB and BC.\n        \"\"\"\n        a, b, c = abc\n        apos = np.array(self._skeleton.nodes[a][\"xyz\"])\n        bpos = np.array(self._skeleton.nodes[b][\"xyz\"])\n        cpos = np.array(self._skeleton.nodes[c][\"xyz\"])\n\n        ba_unit_vector = apos - bpos\n        ba_unit_vector /= np.linalg.norm(ba_unit_vector)\n        bc_unit_vector = cpos - bpos\n        bc_unit_vector /= np.linalg.norm(bc_unit_vector)\n        dot_product = np.dot(ba_unit_vector, bc_unit_vector)\n        return np.arccos(dot_product)\n\n    def get_distance_between_nodes(self, a: int, b: int) -> float:\n        \"\"\"\n        Returns the distance between two nodes.\n\n        Arguments:\n            a (int): The first node ID\n            b (int): The second node ID\n\n        Returns:\n            float: The distance between the two nodes\n        \"\"\"\n        return np.linalg.norm(\n            np.array(self._skeleton.nodes[a][\"xyz\"])\n            - np.array(self._skeleton.nodes[b][\"xyz\"])\n        )\n\n    def get_path_length(self, start: int, end: int) -> float:\n        \"\"\"\n        Get the path length between two nodes.\n\n        Arguments:\n            start (int): The origin of the path (ID)\n            stop (int): The end of the path (ID)\n\n        Returns:\n            float: The length of the path\n\n        \"\"\"\n        # Get the shortest path IDs:\n        path = nx.shortest_path(self._skeleton, start, end)\n        # Compute the path length. The length is the sum of x1y1z1 - x0y0z0:\n        length = 0\n        for i in range(len(path) - 1):\n            length += self.get_distance_between_nodes(path[i], path[i + 1])\n        return length\n\n    def get_total_length(self) -> float:\n        \"\"\"\n        Returns the total length of the neuron's segments.\n        \"\"\"\n        # Iterate over all edges and add the length of each edge:\n        total_length = 0\n        for start, end in self._skeleton.edges():\n            total_length += self.get_distance_between_nodes(start, end)\n        return total_length\n\n    def smoothed(self) -> nx.DiGraph:\n        \"\"\"\n        Returns a _copy_ of this morphology as a smoothed graph.\n        # TODO: This is very inefficient.\n\n        \"\"\"\n        gcopy = self.get_graph()\n        gcopy_old = self.get_graph()\n        new_count = 0\n        old_count = len(self._skeleton.adj)\n        while new_count != old_count:\n            gcopy_old = gcopy\n            old_count = len(gcopy_old.adj)\n            for node, connections in gcopy_old.adj.items():\n                if len(connections) == 2:\n                    start, stop = connections.keys()\n                    gcopy.add_edge(start, stop)\n                    gcopy.remove_node(node)\n                    break\n            new_count = len(gcopy.adj)\n        return gcopy\n\n    @staticmethod\n    def from_file(filename: str):\n        return load_swc(filename)\n\n    @staticmethod\n    def from_string(swc: str):\n        return read_swc(swc)\n\n    def translate(self, translation: Tuple[int, int, int], inplace=False):\n        \"\"\"\n        Translate the target neuron morphology (affine translation) in XYZ.\n\n        Arguments:\n            translation (Tuple[int, int, int]): The translation to perform\n            inplace (bool: False): Whether to perform the translation on this\n                morphology (True) or on a copy (False).\n\n        Returns:\n            The morphology upon which the translation was performed\n\n        \"\"\"\n        if inplace:\n            target = self\n        else:\n            target = NeuronMorphology(source=self)\n        for node in target._skeleton.nodes():\n            current = target._skeleton.nodes[node][\"xyz\"]\n            target._skeleton.nodes[node][\"xyz\"] = [\n                current[0] + translation[0],\n                current[1] + translation[1],\n                current[2] + translation[2],\n            ]\n        return target\n\n    def scale(self, scale: Union[float, Tuple[float, float, float]], inplace=False):\n        \"\"\"\n        Scale the target neuron morphology.\n\n        Arguments:\n            scale (Union[float, Tuple[float, float, float]]): The scale to\n                perform. If a tuple, [X,Y,Z]. If a scalar, perform an isometric\n                scale on all three axes.\n            inplace (bool: False): Whether to perform the translation on this\n                morphology (True) or on a copy (False).\n\n        Returns:\n            The morphology upon which the scaling was performed\n\n        \"\"\"\n        if inplace:\n            target = self\n        else:\n            target = NeuronMorphology(source=self)\n\n        if isinstance(scale, (float, int)):\n            scale = (scale, scale, scale)\n\n        for node in target._skeleton.nodes():\n            current = target._skeleton.nodes[node][\"xyz\"]\n            target._skeleton.nodes[node][\"xyz\"] = [\n                current[0] * scale[0],\n                current[1] * scale[1],\n                current[2] * scale[2],\n            ]\n        return target\n\n    def rotate(\n        self, rotation: Tuple[int, int, int], inplace: bool = False, _p: int = 10\n    ):\n        \"\"\"\n        Perform a rotation on the neuron morphology.\n\n        If inplace is True, will perform the rotation on the current object.\n\n        Arguments:\n            rotation (Tuple[int, int, int]): The rotation to perform, in\n                pitch-roll-yaw order. Units are in radians.\n            inplace (bool: False): Whether to perform the rotation on this\n                morphology (True) or on a copy (False).\n            _p (int: 10): Digits of precision. Because SWC files are text-\n                files, higher precision here costs more in terms of file\n                storage. Values of 5 or greater should be fine for most\n                purposes, unless coordinates are small to begin with.\n\n        Returns:\n            The morphology upon which the translation was performed\n\n        \"\"\"\n\n        # Formula adapted from https://stackoverflow.com/a/34060479/979255\n        pitch, roll, yaw = rotation\n        cosa = math.cos(yaw)\n        sina = math.sin(yaw)\n\n        cosb = math.cos(pitch)\n        sinb = math.sin(pitch)\n\n        cosc = math.cos(roll)\n        sinc = math.sin(roll)\n\n        Axx = cosa * cosb\n        Axy = cosa * sinb * sinc - sina * cosc\n        Axz = cosa * sinb * cosc + sina * sinc\n\n        Ayx = sina * cosb\n        Ayy = sina * sinb * sinc + cosa * cosc\n        Ayz = sina * sinb * cosc - cosa * sinc\n\n        Azx = -sinb\n        Azy = cosb * sinc\n        Azz = cosb * cosc\n\n        if inplace:\n            target = self\n        else:\n            target = NeuronMorphology(source=self)\n\n        for node in target._skeleton.nodes():\n            current = target._skeleton.nodes[node][\"xyz\"]\n            target._skeleton.nodes[node][\"xyz\"] = [\n                round(Axx * current[0] + Axy * current[1] + Axz * current[2], _p),\n                round(Ayx * current[0] + Ayy * current[1] + Ayz * current[2], _p),\n                round(Azx * current[0] + Azy * current[1] + Azz * current[2], _p),\n            ]\n        return target\n\n    def draw(self, node_radius_multiplier: int = 10):\n        k = self._skeleton\n        pos = {n: a[\"xyz\"][:2] for n, a in k.nodes(data=True)}\n        nx.draw(\n            nx.Graph(k),\n            pos=pos,\n            width=5,\n            node_size=[n[\"r\"] * node_radius_multiplier for _, n in k.nodes(data=True)],\n            arrowsize=1,\n        )\n\n\ndef read_swc(swc_str: str) -> NeuronMorphology:\n    \"\"\"\n    Construct a NeuronMorphology from a SWC string.\n\n    For file imports, see also `load_swc`.\n\n    Returns:\n        NeuronMorphology\n    \"\"\"\n    lines = swc_str.split(\"\\n\")\n    neuron = NeuronMorphology()\n    last_index = None\n    for line in lines:\n        line = line.strip()\n        if (not line) or (line[0] == \"#\"):\n            continue\n        else:\n            attrs = [float(i) for i in line.split()]\n            neuron.add_node(int(attrs[0]), t=int(attrs[1]), xyz=attrs[2:5], r=attrs[5])\n            last_index = attrs[-1]\n            if last_index >= 0:\n                neuron.add_edge(int(attrs[0]), int(attrs[-1]))\n    return neuron\n\n\ndef load_swc(filename: str) -> NeuronMorphology:\n    \"\"\"\n    Loads a SWC from disk, into a NeuronMorphology object.\n\n    For str imports, see also `read_swc`.\n\n    Arguments:\n        filename (str)\n\n    Returns:\n        NeuronMorphology\n\n    \"\"\"\n    try:\n        with open(filename, \"r\") as fh:\n            contents = fh.read()\n            return read_swc(contents)\n    except Exception as ex:\n        raise ValueError(\"Invalid file {}\".format(filename))\n\n\ndef save_swc(filename: str, nmorpho: NeuronMorphology) -> str:\n    \"\"\"\n    Saves a morphology to disk in the form of a SWC file.\n\n    Arguments:\n        filename (str): The file to which to save the SWC\n        nmorpho (NeuronMorphology): The morphology to save\n\n    Returns:\n        str: File path on disk to which the SWC was saved\n\n    \"\"\"\n    lines = []\n    g = nmorpho.get_graph()\n    _edges = g.edges()\n    # Loop through the nodes. Pass `True` to include metadata:\n    for node in g.nodes(data=True):\n        parent = [i for i in g.succ[node[0]]]\n        if parent == []:\n            parent = -1\n        else:\n            parent = parent[0]\n\n        #             n  T xyz R  P\n        lines.append(\n            \"{} {} {} {} {}\".format(\n                str(node[0]),\n                str(node[1][\"t\"]),\n                \" \".join([str(i) for i in node[1][\"xyz\"]]),\n                str(node[1][\"r\"]),\n                str(parent),\n            )\n        )\n    with open(filename, \"w\") as swc_output:\n        swc_output.write(\"\\n\".join(lines))\n        swc_output.write(\"\\n\")\n    return filename\n", "meta": {"hexsha": "4cf9f5bca8a8749584babbf2ccf3f0508b458d2c", "size": 13973, "ext": "py", "lang": "Python", "max_stars_repo_path": "neuromorpholib/swc/__init__.py", "max_stars_repo_name": "j6k4m8/neuromorpholib", "max_stars_repo_head_hexsha": "816eac0ae1214ba56dc378b47ab7af154efff0bf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-08-27T17:50:02.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-18T11:47:30.000Z", "max_issues_repo_path": "neuromorpholib/swc/__init__.py", "max_issues_repo_name": "j6k4m8/neuromorpholib", "max_issues_repo_head_hexsha": "816eac0ae1214ba56dc378b47ab7af154efff0bf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "neuromorpholib/swc/__init__.py", "max_forks_repo_name": "j6k4m8/neuromorpholib", "max_forks_repo_head_hexsha": "816eac0ae1214ba56dc378b47ab7af154efff0bf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2445887446, "max_line_length": 88, "alphanum_fraction": 0.5475560009, "include": true, "reason": "import numpy,import networkx", "num_tokens": 3311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.175638267530597}}
{"text": "##\n## function to return the AGN spectrum\n##   given nu (in Hz), and log(L_bol/L_sun), returns \n##   log(nuL_nu/L_sun)\n##\n##\tkeywords to shortcut for various bands:\n##\t  BB = B-band, IR = mid-IR (15 microns), \n##    SX = soft X-rays (0.5-2 keV), \n##    HX = hard X-rays (2-10 keV)\n##\n##  keywords for different spectra:\n##    MARCONI = Marconi et al. 2004-ish spectrum -- it's not *really* \n##      the same (updated w. more recent estimates of the X-ray \n##      input parameters, i.e. Gamma & reflection angle, from Tozzi et al. 2006 \n##\t\tas well as the more recent Steffen et al. 2006 calibration of the \n##      alpha_ox relation (specifically their l_uv-l_2keV bisector measurement, \n##      which is a subtle difference but is very important for the bolometric \n##      corrections of the most luminous X-ray sources\n##    HRH = Hopkins, Richards, & Hernquist 2006 template spectrum\n##\t    compiled from a number of observations therein. It's a little closer to \n##      a typical observed spectrum, with a more detailed modeling of a number of \n##      parts of the spectrum (i.e. more continuum shape). the major difference is \n##      that it includes a hot dust component, which is important to account for \n##      since much of the energy comes out there. however, if you want to model \n##      that generation self-consistently, you should use the \"input\" marconi et al. \n##      spectrum. still, the galaxy-scale obscuration doesn't necessarily produce this \n##      and the alpha-ox calibrations are for objects with this feature, so it is \n##      generally more representative\n##    RICHARDS = Richards et al. 2006 all-quasar mean SED: if you want a \n##      non-luminosity-dependent spectrum for whatever reason, this is an improved \n##      version of Elvis et al. 1994 (which is too X-ray bright)\n##\n##    SDSS can be added as a keyword with any of the model spectra, and it will \n##      overlay the vanden Berk et al. 2001 median SDSS SED over the relevant \n##      portion of the spectrum :: basically does so with a sliding continuum determination\n##      that then overlays this spectrum, such that the integrated luminosity in the \n##      entire bandpass and the continuum spectrum are conserved (i.e. you can put this \n##      over an arbitrary continuum\n##\n##\tunless you're using the Richards et al. 2006 spectra, if you want a reference for this, \n##    it should be Hopkins, Richards, & Hernquist 2006. Even the \"MARCONI\" key spectrum \n##    is substantially modified as described. If you want the additional relevant \n##    observational compilations on which it's all based, the list is : \n##    Richards et al. 2006, Steffen et al. 2006, Hatziminaoglou et al. 2005, \n##    Tozzi et al. 2006, Strateva et al. 2005, Telfer et al. 2002, Vanden Berk et al. 2001, \n##    George et al. 1998, Elvis et al. 1994, Marconi et al. 2004 (not really an observational \n##    paper but the methodology does follow them), with the X-ray reflection component \n##    following Ueda et al. 2003 in the PEXRAV code, Magdziarz & Zdziarski 1995\n##\n##\n##\ndef agn_spectrum( nu_in_Hz, log_l_bol, \\\n\tBB=0, IR=0, SX=0, HX=0, \\\n\tHRH=0, MARCONI=0, RICHARDS=0, \\\n\tSDSS=0 ):\n\n    import utilities as util\n    import numpy as np\n    import math\n    import ctypes\n\n    ## location of shared library\n    exec_call=util.return_python_routines_homedir()+'/agn_spectrum/agn_spectrum_py.so'\n    lib=ctypes.cdll[exec_call];\n\n    if (1 == BB) : nu_in_Hz = -1.0\n    if (1 == IR) : nu_in_Hz = -2.0\n    if (1 == SX) : nu_in_Hz = -3.0\n    if (1 == HX) : nu_in_Hz = -4.0\t\n    spectrum_key = 0\n    if (1 == HRH) \t\t: spectrum_key = 0\n    if (1 == MARCONI) \t: spectrum_key = 1\n    if (1 == RICHARDS) \t: spectrum_key = 2\t\n    sloan_key    = 0\n    if (1 == SDSS)\t\t: sloan_key = 1\n\n    nu_in_Hz=np.array(nu_in_Hz,ndmin=1,dtype='d');\n    log_l_bol=np.array(log_l_bol,ndmin=1,dtype='d');\n    \n    N_nu = nu_in_Hz.shape[0]\n    N_lum = log_l_bol.shape[0]\n    l_band_all = np.zeros((N_nu,N_lum),dtype='d')\n\n    out_cast = ctypes.c_double*N_nu\n    for i in range(N_lum):\n        #l_band_vec = np.zeros(N_nu,dtype='d')\n        l_band_vec = out_cast()\n        log_l_bol_pass = log_l_bol[i]\n\n        lib.main( ctypes.c_int(N_nu),\\\n            nu_in_Hz.ctypes.data_as(ctypes.POINTER(ctypes.c_double)),\\\n            ctypes.c_double(log_l_bol_pass),\\\n            ctypes.c_int(spectrum_key),\\\n            ctypes.c_int(sloan_key),\\\n            ctypes.byref(l_band_vec) );\n            #l_band_vec.ctypes.data_as(ctypes.POINTER(ctypes.c_double)));\n        ## now put the output arrays into a useful format \n        l_band_vec = np.copy(np.ctypeslib.as_array(l_band_vec));\n        l_band_all[:,i] = l_band_vec\n\n    return l_band_all\n\n", "meta": {"hexsha": "a194a0e3255be19122068aa6d264cc00d78d21f8", "size": 4700, "ext": "py", "lang": "Python", "max_stars_repo_path": "paul_analysis/Python/agn_spectrum/agn_spectrum_wrapper.py", "max_stars_repo_name": "lzkelley/arepo-mbh-sims_analysis", "max_stars_repo_head_hexsha": "f14519552cedd39a040b53e6d7cc538b5b8f38a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paul_analysis/Python/agn_spectrum/agn_spectrum_wrapper.py", "max_issues_repo_name": "lzkelley/arepo-mbh-sims_analysis", "max_issues_repo_head_hexsha": "f14519552cedd39a040b53e6d7cc538b5b8f38a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paul_analysis/Python/agn_spectrum/agn_spectrum_wrapper.py", "max_forks_repo_name": "lzkelley/arepo-mbh-sims_analysis", "max_forks_repo_head_hexsha": "f14519552cedd39a040b53e6d7cc538b5b8f38a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.6310679612, "max_line_length": 94, "alphanum_fraction": 0.6670212766, "include": true, "reason": "import numpy", "num_tokens": 1383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.17547956099530745}}
{"text": "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Mixture of Experts routing mechanisms.\"\"\"\n\nfrom typing import Any, Callable, Iterable, Tuple\n\nimport flax\nfrom flax import linen as nn\nimport jax\nimport jax.numpy as jnp\n\n# Type Stubs\nPRNGKey = Any\nRouterOutput = Any\nShape = Iterable[int]\n\n# Switch Transformer (https://arxiv.org/abs/2101.03961) suggests using\n# nn.initializers.variance_scaling(0.1, \"fan_in\", \"truncated_normal\")\n# scaling throughout MoE models, but we find slightly better results adopting\n# typical normally-distributed scaling for the router specifically.\ndefault_kernel_init = nn.initializers.normal(stddev=2e-2)\ndefault_bias_init = nn.initializers.zeros\n\n\n@flax.struct.dataclass\nclass RouterIndices:\n  \"\"\"Dispatch indices and combine weights for scatter/gather-based routing.\n\n  Attributes:\n    dispatch_indices: <int32>[NUM_GROUPS, TOKENS_PER_GROUP,\n      NUM_SELECTED_EXPERTS, 2] dispatch indices indicating, for each token, its\n      preferred expert and its priority in that expert's buffer.\n    combine_weights: <float>[NUM_GROUPS, TOKENS_PER_GROUP, NUM_SELECTED_EXPERTS]\n      combine weights used for scaling expert outputs with the router's dispatch\n      probability/confidence.\n    auxiliary_loss: Load balancing loss for router.\n    router_z_loss: Router z-loss. Encourages router logits to remain small in an\n      effort to improve stability.\n  \"\"\"\n  dispatch_indices: jnp.ndarray\n  combine_weights: jnp.ndarray\n  auxiliary_loss: float\n  router_z_loss: float = 0.\n\n\n@flax.struct.dataclass\nclass RouterMask:\n  \"\"\"Dispatch and combine arrays for expert routing with masked matmuls.\n\n  Attributes:\n    dispatch_mask: <bool>[NUM_GROUPS, TOKENS_PER_GROUP, NUM_EXPERTS,\n      EXPERT_CAPACITY] dispatch array that is 1 if the token gets routed to the\n      corresponding expert, and 0 otherwise.\n    combine_array: <float>[NUM_GROUPS, TOKENS_PER_GROUP, NUM_EXPERTS,\n      EXPERT_CAPACITY] combine array used for combining expert outputs and\n      scaling with router probability.\n    auxiliary_loss: Load balancing loss for router.\n    router_z_loss: Router z-loss. Encourages router logits to remain small in an\n      effort to improve stability.\n  \"\"\"\n  dispatch_mask: jnp.ndarray\n  combine_array: jnp.ndarray\n  auxiliary_loss: float\n  router_z_loss: float = 0.\n\n\ndef _favor_one_hot_slices():\n  \"\"\"Returns true iff running on TPUs.\"\"\"\n  return jax.default_backend() == \"tpu\" or jax.devices()[0].platform == \"tpu\"\n\n\ndef _take_along_axis(array, indices,\n                     axis):\n  \"\"\"Takes values from the input array by matching 1D index and data slices.\n\n  This function serves the same purpose as jax.numpy.take_along_axis, except\n  that it uses one-hot matrix multiplications under the hood on TPUs:\n  (1) On TPUs, we use one-hot matrix multiplications to select elements from the\n      array.\n  (2) Otherwise, we fall back to jax.numpy.take_along_axis.\n\n  Notes:\n    - To simplify matters in case (1), we only support slices along the second\n      or last dimensions.\n    - We may wish to revisit (1) for very large arrays.\n\n  Args:\n    array: Source array.\n    indices: Indices to take along each 1D slice of array.\n    axis: Axis along which to take 1D slices.\n\n  Returns:\n    The indexed result.\n  \"\"\"\n  if array.ndim != indices.ndim:\n    raise ValueError(\n        \"indices and array must have the same number of dimensions; \"\n        f\"{indices.ndim} vs. {array.ndim}.\")\n\n  if (axis != -1 and axis != array.ndim - 1 and  # Not last dimension\n      axis != 1 and axis != -array.ndim + 1):  # Not second dimension\n    raise ValueError(\n        \"Only slices along the second or last dimension are supported; \"\n        f\"array.ndim = {array.ndim}, while axis = {axis}.\")\n\n  if _favor_one_hot_slices():\n    one_hot_length = array.shape[axis]\n    one_hot_indices = jax.nn.one_hot(indices, one_hot_length, axis=axis)\n\n    if axis == -1 or array.ndim == 1:\n      # Take i elements from last dimension (s).\n      # We must use HIGHEST precision to accurately reproduce indexing\n      # operations with matrix multiplications.\n      result = jnp.einsum(\n          \"...s,...is->...i\",\n          array,\n          one_hot_indices,\n          precision=jax.lax.Precision.HIGHEST)\n    else:\n      # Take i elements from second dimension (s). We assume here that we always\n      # want to slice along the second dimension.\n      # We must use HIGHEST precision to accurately reproduce indexing\n      # operations with matrix multiplications.\n      result = jnp.einsum(\n          \"ns...,nis...->ni...\",\n          array,\n          one_hot_indices,\n          precision=jax.lax.Precision.HIGHEST)\n    return jax.lax.convert_element_type(result, array.dtype)\n  else:\n    return jnp.take_along_axis(array, indices, axis=axis)\n\n\ndef _top_k(array, k):\n  \"\"\"Returns top k values and their indices along the last axis of the array.\n\n  This function serves the same purpose as jax.lax.top_k, but in a more XLA\n  friendly manner for TPUs:\n  (1) On TPUs, we use one-hot matrix multiplications to select the top k values.\n      This convoluted way of obtaining the top k values is generally faster on\n      TPUs.\n  (2) Otherwise, we fall back to jax.lax.top_k (and its underlying scatter op).\n\n  Args:\n    array: Source array.\n    k: Number of top values to select.\n\n  Returns:\n    - Top k values\n    - Associated top k indices.\n  \"\"\"\n  if _favor_one_hot_slices():\n    top_k_indices = jax.lax.top_k(array, k)[-1]\n    top_k_values = _take_along_axis(array, top_k_indices, axis=-1)\n    return top_k_values, top_k_indices\n  else:\n    return jax.lax.top_k(array, k)\n\n\nclass RouterWeights(nn.Module):\n  \"\"\"Router module converting token inputs to router logits.\n\n  Attributes:\n    use_bias: Whether or not to use the bias term in computing the logits.\n    dtype: Numerical float type for router logit computation.\n    kernel_init: Initialization scheme for kernel.\n    bias_init: Initialization scheme for bias.\n    precision: XLA precision for array computations.\n  \"\"\"\n  use_bias: bool = True\n  dtype: jnp.dtype = jnp.bfloat16\n  kernel_init: Callable[[PRNGKey, Shape, jnp.dtype],\n                        jnp.ndarray] = default_kernel_init\n  bias_init: Callable[[PRNGKey, Shape, jnp.dtype],\n                      jnp.ndarray] = default_bias_init\n  precision: jax.lax.Precision = jax.lax.Precision.DEFAULT\n\n  @nn.compact\n  def __call__(self, token_inputs,\n               num_experts):\n    \"\"\"Applies RouterWeights module.\n\n    Args:\n      token_inputs: Flattened batch of tokens with shape <float>[NUM_GROUPS,\n        TOKENS_PER_GROUP, HIDDEN_DIM].\n      num_experts: Number of experts.\n\n    Returns:\n      Router logits with shape <float>[NUM_GROUPS, TOKENS_PER_GROUP,\n      NUM_EXPERTS].\n    \"\"\"\n    return nn.DenseGeneral(\n        num_experts,\n        use_bias=self.use_bias,\n        dtype=self.dtype,\n        kernel_init=self.kernel_init,\n        bias_init=self.bias_init,\n        precision=self.precision)(\n            token_inputs)\n\n\nclass Router(nn.Module):\n  \"\"\"Abstract base router class, defining router API and inner workings.\n\n  Attributes:\n    router_weights: Configurable module used to compute router logits from token\n      inputs.\n    jitter_noise: Amplitude of jitter noise applied to router logits.\n    dtype: Numeric float type for returned combine array. All actual\n      computations are performed in float32 of the input for stability.\n  \"\"\"\n  router_weights: RouterWeights\n  jitter_noise: float\n  dtype: jnp.dtype\n\n  def __call__(self,\n               token_inputs,\n               num_experts,\n               expert_capacity,\n               apply_jitter = True):\n    \"\"\"Computes dispatch and combine arrays for routing to experts.\n\n    Args:\n      token_inputs: <float>[NUM_GROUPS, TOKENS_PER_GROUP, HIDDEN_DIM] inputs to\n        send to experts.\n      num_experts: Number of experts.\n      expert_capacity: Each group will send this many tokens to each expert.\n      apply_jitter: If true, apply jitter noise during routing.\n\n    Returns:\n      Router indices or mask arrays (depending on router type).\n    \"\"\"\n    router_probs, router_logits = self._compute_router_probabilities(\n        token_inputs, num_experts, apply_jitter)\n    instructions = self._compute_routing_instructions(router_probs,\n                                                      expert_capacity)\n    return instructions.replace(router_z_loss=_router_z_loss(router_logits))\n\n  def _compute_router_probabilities(\n      self, token_inputs, num_experts,\n      apply_jitter):\n    \"\"\"Computes router probabilities from input tokens.\n\n    Args:\n      token_inputs: <float>[NUM_GROUPS, TOKENS_PER_GROUP, HIDDEN_DIM] from which\n        router probabilities are computed.\n      num_experts: Number of experts.\n      apply_jitter: If true, apply jitter noise.\n\n    Returns:\n      - <float32>[NUM_GROUPS, TOKENS_PER_GROUP, NUM_EXPERTS] probabilities for\n        each token and expert. Used for routing tokens to experts.\n      - <float>[NUM_GROUPS, TOKENS_PER_GROUP, NUM_EXPERTS] raw router logits.\n        Used for computing router z-loss.\n    \"\"\"\n    # For remainder of routing computation we use float32 to ensure stability.\n    # See the discussion of \"selective precision\" in\n    # https://arxiv.org/abs/2101.03961.\n    token_inputs = jax.lax.convert_element_type(token_inputs, jnp.float32)\n\n    if apply_jitter and self.jitter_noise > 0:\n      token_inputs *= jax.random.uniform(\n          self.make_rng(\"jitter\"),\n          token_inputs.shape,\n          token_inputs.dtype,\n          minval=1.0 - self.jitter_noise,\n          maxval=1.0 + self.jitter_noise)\n\n    # Shape: [NUM_GROUPS, TOKENS_PER_GROUP, NUM_EXPERTS]\n    router_logits = self.router_weights(token_inputs, num_experts)\n\n    router_probabilities = jax.nn.softmax(router_logits, axis=-1)\n\n    return router_probabilities, router_logits\n\n  def _compute_routing_instructions(self, router_probs,\n                                    expert_capacity):\n    \"\"\"Computes instructions for routing inputs to experts.\"\"\"\n    raise NotImplementedError(\n        \"Router is an abstract class that should be subclassed.\")\n\n\nclass ScatterRouter(Router):\n  \"\"\"Abstract base router class for scatter dispatch routers.\n\n  ScatterRouter(s) return RouterIndices containing dispatch indices and combine\n  weights for sending token inputs (via scatter) and receiving outputs (via\n  gather) to and from experts.\n\n  Scatter-based routing is generally faster than masked matmul routing on CPUs\n  and GPUs.\n  \"\"\"\n\n  def _compute_routing_instructions(self, router_probs,\n                                    expert_capacity):\n    \"\"\"Computes instructions for routing inputs to experts.\n\n    Args:\n      router_probs: <float32>[NUM_GROUPS, TOKENS_PER_GROUP, NUM_EXPERTS]\n        probabilities used to determine the routing of tokens to the experts.\n      expert_capacity: Each group will send this many tokens to each expert.\n\n    Returns:\n      Router indices containing dispatch indices and combine weights.\n    \"\"\"\n    raise NotImplementedError(\n        \"ScatterRouter is an abstract class that should be subclassed.\")\n\n\nclass MaskedRouter(Router):\n  \"\"\"Abstract base router class for masked matmul dispatch routers.\n\n  MaskedRouter(s) return RouterMask(s) containing a dispatch mask and combine\n  array for sending and receiving (via masked matmuls) inputs and outputs to and\n  from experts.\n\n  Routing using masked matmuls is generally faster than scatter-based routing on\n  CPUs and GPUs.\n  \"\"\"\n\n  def _compute_routing_instructions(self, router_probs,\n                                    expert_capacity):\n    \"\"\"Computes masks for the top-k experts per token.\n\n    Args:\n      router_probs: <float32>[NUM_GROUPS, TOKENS_PER_GROUP, NUM_EXPERTS]\n        probabilities used to determine the routing of tokens to the experts.\n      expert_capacity: Each group will send this many tokens to each expert.\n\n    Returns:\n      Router mask arrays.\n    \"\"\"\n    raise NotImplementedError(\n        \"MaskedRouter is an abstract class that should be subclassed.\")\n\n\nclass TokensChooseScatterRouter(ScatterRouter):\n  \"\"\"Scatter router using tokens choose top-k experts assignment.\n\n  This router uses the same mechanism as in Switch Transformer\n  (https://arxiv.org/abs/2101.03961): tokens choose their top experts. Items are\n  sorted by router_probs and then routed to their choice of expert until the\n  expert's expert_capacity is reached. There is no guarantee that each token is\n  processed by an expert, or that each expert receives at least one token.\n\n  Attributes:\n    num_selected_experts: Maximum number of experts to which each token is\n      routed. Tokens may be routed to fewer experts if particular experts are\n      oversubscribed / reach capacity.\n    batch_prioritized_routing: Whether or not to use Batch Prioritized Routing\n      (BPR), originally introduced in V-MoE (https://arxiv.org/abs/2106.05974).\n        With BPR, we prioritize routing those top-k tokens with the highest\n        router probability, rather than simply using each tokens left-to-right\n        ordering in the batch. This prioritization is important because the\n        experts have limited capacity.\n  \"\"\"\n  num_selected_experts: int\n  batch_prioritized_routing: bool\n\n  def _compute_routing_instructions(self, router_probs,\n                                    expert_capacity):\n    \"\"\"Computes dispatch indices and combine weights for the top-k experts.\n\n    Args:\n      router_probs: <float32>[NUM_GROUPS, TOKENS_PER_GROUP, NUM_EXPERTS]\n        probabilities used to determine the routing of tokens to the experts.\n      expert_capacity: Each group will send this many tokens to each expert.\n\n    Returns:\n      Dispatch indices and combine weights for scatter/gather-based routing.\n    \"\"\"\n    num_groups, tokens_per_group, num_experts = router_probs.shape\n\n    # Top-k router probability and corresponding expert indices for each token.\n    # Shape: [NUM_GROUPS, TOKENS_PER_GROUP, NUM_SELECTED_EXPERTS].\n    combine_weights, expert_indices = _top_k(\n        router_probs, k=self.num_selected_experts)\n\n    auxiliary_loss = _load_balancing_loss(router_probs, expert_indices)\n\n    if self.batch_prioritized_routing:\n      # Sort tokens according to their routing probability per token group, so\n      # that the highest probability tokens are routed first.\n      token_ordering = jnp.argsort(-combine_weights[Ellipsis, 0], axis=-1)\n      expert_indices = _take_along_axis(\n          expert_indices, jnp.expand_dims(token_ordering, axis=-1), axis=-2)\n\n    # Identify each token's preferred expert.\n    # Make NUM_SELECTED_EXPERTS the leading axis to ensure that top-1 choices\n    # have priority over top-2 choices, which have priority over top-3\n    # choices...\n    preferred_experts = jnp.swapaxes(expert_indices, 1, 2)\n    # Shape: [NUM_GROUPS, NUM_SELECTED_EXPERTS * TOKENS_PER_GROUP]\n    preferred_experts = preferred_experts.reshape(num_groups, -1)\n\n    # Shape: [NUM_GROUPS, TOKENS_PER_GROUP * NUM_SELECTED_EXPERTS, NUM_EXPERTS].\n    expert_mask = jax.nn.one_hot(\n        preferred_experts, num_experts, dtype=jnp.int32)\n\n    # Experts have a fixed capacity that we cannot exceed. A token's priority\n    # within the expert's buffer is given by the masked, cumulative capacity of\n    # its target expert.\n    # Shape: [NUM_GROUPS, TOKENS_PER_GROUP * NUM_SELECTED_EXPERTS, NUM_EXPERTS].\n    token_priority = jnp.cumsum(expert_mask, axis=1) * expert_mask - 1.0\n    # Shape: [NUM_GROUPS, NUM_SELECTED_EXPERTS, TOKENS_PER_GROUP, NUM_EXPERTS].\n    token_priority = token_priority.reshape(\n        (num_groups, self.num_selected_experts, -1, num_experts))\n    # Shape: [NUM_GROUPS, TOKENS_PER_GROUP, NUM_SELECTED_EXPERTS, NUM_EXPERTS].\n    token_priority = jnp.swapaxes(token_priority, 1, 2)\n    # For each token, across all experts, select the only non-negative\n    # (unmasked) priority.\n    # Shape: [NUM_GROUPS, TOKENS_PER_GROUP, NUM_SELECTED_EXPERTS].\n    token_priority = jnp.max(token_priority, axis=-1)\n\n    # Return to original index shape.\n    preferred_experts = preferred_experts.reshape(num_groups,\n                                                  self.num_selected_experts,\n                                                  tokens_per_group)\n    # Shape: [NUM_GROUPS, TOKENS_PER_GROUP, NUM_SELECTED_EXPERTS]\n    preferred_experts = jnp.swapaxes(preferred_experts, 1, 2)\n\n    if self.batch_prioritized_routing:\n      # Place tokens in their original ordering.\n      inverse_token_ordering = jnp.argsort(token_ordering, axis=-1)\n      preferred_experts = _take_along_axis(\n          preferred_experts,\n          jnp.expand_dims(inverse_token_ordering, axis=-1),\n          axis=-2)\n      token_priority = _take_along_axis(\n          token_priority,\n          jnp.expand_dims(inverse_token_ordering, axis=-1),\n          axis=-2)\n\n    # Mask out tokens that overflow the maximum expert capacities.\n    # Shape: [NUM_GROUPS, TOKENS_PER_GROUP, NUM_SELECTED_EXPERTS].\n    combine_weights *= token_priority < expert_capacity\n\n    # Expert index and priority within the expert capacity buffer.\n    # Shape: [NUM_GROUPS, TOKENS_PER_GROUP, NUM_SELECTED_EXPERTS, 2].\n    dispatch_indices = jnp.stack([preferred_experts, token_priority], axis=-1)\n\n    # Return to default dtype now that router computation is complete.\n    combine_weights = jax.lax.convert_element_type(combine_weights, self.dtype)\n    dispatch_indices = jax.lax.convert_element_type(dispatch_indices, jnp.int32)\n\n    return RouterIndices(dispatch_indices, combine_weights, auxiliary_loss)\n\n\nclass TokensChooseMaskedRouter(MaskedRouter):\n  \"\"\"Masked matmul router using tokens choose top-k experts assignment.\n\n  This router uses the same mechanism as in Switch Transformer\n  (https://arxiv.org/abs/2101.03961): tokens choose their top experts. Items are\n  sorted by router_probs and then routed to their choice of expert until the\n  expert's expert_capacity is reached. There is no guarantee that each token is\n  processed by an expert, or that each expert receives at least one token.\n\n  Attributes:\n    num_selected_experts: Maximum number of experts to which each token is\n      routed. Tokens may be routed to fewer experts if particular experts are\n      oversubscribed / reach capacity.\n    batch_prioritized_routing: Whether or not to use Batch Prioritized Routing\n      (BPR), originally introduced in V-MoE (https://arxiv.org/abs/2106.05974).\n        With BPR, we prioritize routing those top-k tokens with the highest\n        router probability, rather than simply using each tokens left-to-right\n        ordering in the batch. This prioritization is important because the\n        expert's have limited capacity.\n  \"\"\"\n  num_selected_experts: int\n  batch_prioritized_routing: bool\n\n  def _compute_routing_instructions(self, router_probs,\n                                    expert_capacity):\n    \"\"\"Computes masks for the top-k experts per token.\n\n    Args:\n      router_probs: <float32>[NUM_GROUPS, TOKENS_PER_GROUP, NUM_EXPERTS]\n        probabilities used to determine the routing of tokens to the experts.\n      expert_capacity: Each group will send this many tokens to each expert.\n\n    Returns:\n      Dispatch and combine arrays for routing with masked matmuls.\n    \"\"\"\n    num_groups, _, num_experts = router_probs.shape\n\n    # Top-k router probability and corresponding expert indices for each token.\n    # Shape: [NUM_GROUPS, TOKENS_PER_GROUP, NUM_SELECTED_EXPERTS].\n    expert_gate, expert_index = _top_k(\n        router_probs, k=self.num_selected_experts)\n\n    auxiliary_loss = _load_balancing_loss(router_probs, expert_index)\n\n    if self.batch_prioritized_routing:\n      # Sort tokens according to their routing probability per group, so that\n      # the highest probability tokens are routed first.\n      permutation = jnp.argsort(-expert_gate[Ellipsis, 0], axis=-1)\n      # Shape: [NUM_GROUPS, TOKENS_PER_GROUP, NUM_SELECTED_EXPERTS]\n      expert_index = _take_along_axis(\n          expert_index, jnp.expand_dims(permutation, axis=-1), axis=-2)\n\n    # Make NUM_SELECTED_EXPERTS the leading axis to ensure that top-1 choices\n    # have priority over top-2 choices, which have priority over top-3 choices,\n    # etc.\n    expert_index = jnp.swapaxes(expert_index, 1, 2)\n    # Shape: [NUM_GROUPS, NUM_SELECTED_EXPERTS * TOKENS_PER_GROUP]\n    expert_index = expert_index.reshape(num_groups, -1)\n\n    # Create mask out of indices.\n    # Shape: [NUM_GROUPS, TOKENS_PER_GROUP * NUM_SELECTED_EXPERTS, NUM_EXPERTS].\n    expert_mask = jax.nn.one_hot(expert_index, num_experts, dtype=jnp.int32)\n\n    # Experts have a fixed capacity that we cannot exceed. A token's priority\n    # within the expert's buffer is given by the masked, cumulative capacity of\n    # its target expert.\n    # Shape: [NUM_GROUPS, TOKENS_PER_GROUP * NUM_SELECTED_EXPERTS, NUM_EXPERTS].\n    token_priority = jnp.cumsum(expert_mask, axis=1) * expert_mask - 1.0\n    # Shape: [NUM_GROUPS, NUM_SELECTED_EXPERTS, TOKENS_PER_GROUP, NUM_EXPERTS].\n    token_priority = token_priority.reshape(\n        (num_groups, self.num_selected_experts, -1, num_experts))\n    # Shape: [NUM_GROUPS, TOKENS_PER_GROUP, NUM_SELECTED_EXPERTS, NUM_EXPERTS].\n    token_priority = jnp.swapaxes(token_priority, 1, 2)\n    # For each token, across all selected experts, select the only non-negative\n    # (unmasked) priority. Now, for group G routing to expert E, token T has\n    # non-negative priority (i.e. token_priority[G,T,E] >= 0) if and only if E\n    # is its targeted expert.\n    # Shape: [NUM_GROUPS, TOKENS_PER_GROUP, NUM_EXPERTS].\n    token_priority = jnp.max(token_priority, axis=2)\n\n    if self.batch_prioritized_routing:\n      # Place token priorities in original ordering of tokens.\n      inv_permutation = jnp.argsort(permutation, axis=-1)\n      token_priority = _take_along_axis(\n          token_priority, jnp.expand_dims(inv_permutation, axis=-1), axis=-2)\n\n    # Token T can only be routed to expert E if its priority is positive and\n    # less than the expert capacity. One-hot matrix will ignore indices outside\n    # the range [0, EXPERT_CAPACITY).\n    # Shape: [NUM_GROUPS, TOKENS_PER_GROUP, NUM_EXPERTS, EXPERT_CAPACITY].\n    dispatch_mask = jax.nn.one_hot(\n        token_priority, expert_capacity, dtype=jnp.bool_)\n\n    # The combine array will be used for combining expert outputs, scaled by the\n    # router probabilities. Shape: [NUM_GROUPS, TOKENS_PER_GROUP, NUM_EXPERTS,\n    # EXPERT_CAPACITY].\n    combine_array = jnp.einsum(\n        \"...te,...tec->...tec\",\n        router_probs,\n        dispatch_mask,\n        precision=jax.lax.Precision.DEFAULT)\n\n    # Return to default dtype now that router computation is complete.\n    combine_array = jax.lax.convert_element_type(combine_array, self.dtype)\n\n    return RouterMask(dispatch_mask, combine_array, auxiliary_loss)\n\n\nclass ExpertsChooseMaskedRouter(MaskedRouter):\n  \"\"\"Masked matmul router using experts choose tokens assignment.\n\n  This router uses the same mechanism as in Mixture-of-Experts with Expert\n  Choice (https://arxiv.org/abs/2202.09368): each expert selects its top\n  expert_capacity tokens. An individual token may be processed by multiple\n  experts or none at all.\n  \"\"\"\n\n  def _compute_routing_instructions(self, router_probs,\n                                    expert_capacity):\n    \"\"\"Computes masks for the highest probability token per expert.\n\n    Args:\n      router_probs: <float32>[NUM_GROUPS, TOKENS_PER_GROUP, NUM_EXPERTS]\n        probabilities used to determine the routing of tokens to the experts.\n      expert_capacity: Each group will send this many tokens to each expert.\n\n    Returns:\n      Dispatch and combine arrays for routing with masked matmuls.\n    \"\"\"\n    tokens_per_group = router_probs.shape[1]\n\n    # vmap over group dimension.\n    router_probs_t = jax.vmap(lambda m: m.transpose())(router_probs)\n\n    # Top expert_capacity router probability and corresponding token indices for\n    # each expert. Shapes: [NUM_GROUPS, NUM_EXPERTS, EXPERT_CAPACITY].\n    expert_gate, expert_index = _top_k(router_probs_t, k=expert_capacity)\n\n    # Convert to one-hot mask of expert indices for each token in each group.\n    # Shape: [NUM_GROUPS, NUM_EXPERTS, EXPERT_CAPACITY, TOKENS_PER_GROUP].\n    dispatch_mask = jax.nn.one_hot(\n        expert_index, tokens_per_group, dtype=jnp.int32)\n\n    # Move axes to conform with shape expected by MoeLayer API.\n    # Shape: [NUM_GROUPS, TOKENS_PER_GROUP, NUM_EXPERTS, EXPERT_CAPACITY]\n    dispatch_mask = jnp.moveaxis(dispatch_mask, 3, 1)\n\n    # The combine array will be used for combining expert outputs, scaled by the\n    # router probabilities. Shape: [NUM_GROUPS, NUM_EXPERTS, TOKENS_PER_GROUP,\n    # EXPERT_CAPACITY].\n    combine_array = jnp.einsum(\n        \"...ec,...tec->...tec\",\n        expert_gate,\n        dispatch_mask,\n        precision=jax.lax.Precision.DEFAULT)\n\n    # Return to default dtype now that router computation is complete.\n    combine_array = jax.lax.convert_element_type(combine_array, self.dtype)\n\n    # Each expert is choosing tokens until it reaches full capacity, so we don't\n    # need an auxiliary loading balancing loss for expert choice routing.\n    auxiliary_loss = 0.0\n\n    return RouterMask(dispatch_mask, combine_array, auxiliary_loss)\n\n\ndef _load_balancing_loss(router_probs,\n                         expert_indices):\n  \"\"\"Computes auxiliary load balancing loss as in Switch Transformer.\n\n  See Switch Transformer (https://arxiv.org/abs/2101.03961). This function\n  implements the loss function presented in equations (4) - (6). It aims to\n  penalize those cases where the routing between experts is unbalanced.\n\n  Args:\n    router_probs: Probability assigned to each expert per token. Shape:\n      <float32>[NUM_GROUPS, TOKENS_PER_GROUP, NUM_EXPERTS].\n    expert_indices: <int>[NUM_GROUPS, TOKENS_PER_GROUP, NUM_SELECTED_EXPERTS]\n      indices identifying the top NUM_SELECTED_EXPERTS for a given token.\n\n  Returns:\n    The auxiliary loss.\n  \"\"\"\n  num_experts = router_probs.shape[-1]\n\n  # Shape: [NUM_GROUPS, TOKENS_PER_GROUP, NUM_SELECTED_EXPERTS, NUM_EXPERTS].\n  expert_mask = jax.nn.one_hot(expert_indices, num_experts, dtype=jnp.int32)\n  # For a given token, determine if it was routed to a given expert.\n  # Shape: [NUM_GROUPS, TOKENS_PER_GROUP, NUM_EXPERTS]\n  expert_mask = jnp.max(expert_mask, axis=-2)\n\n  tokens_per_group_and_expert = jnp.mean(\n      expert_mask, dtype=jnp.float32, axis=-2)\n  router_prob_per_group_and_expert = jnp.mean(\n      router_probs, dtype=jnp.float32, axis=-2)\n  return jnp.mean(\n      tokens_per_group_and_expert * router_prob_per_group_and_expert,\n      dtype=jnp.float32) * num_experts**2\n\n\ndef _router_z_loss(router_logits):\n  \"\"\"Compute router z-loss.\n\n   The router z-loss was introduced in Designing Effective Sparse Expert Models\n   (https://arxiv.org/abs/2202.08906). It encourages router logits to remain\n   small in an effort to improve stability.\n\n  Args:\n    router_logits: <float>[NUM_GROUPS, TOKENS_PER_GROUP, NUM_EXPERTS] router\n      logits.\n\n  Returns:\n    Scalar router z-loss.\n  \"\"\"\n  num_groups, tokens_per_group, _ = router_logits.shape\n  log_z = jax.nn.logsumexp(router_logits, axis=-1)\n  z_loss = log_z**2\n  return jnp.sum(z_loss, dtype=jnp.float32) / (num_groups * tokens_per_group)\n", "meta": {"hexsha": "043682cbb23a5b01dcfa739324176959f725db50", "size": 27736, "ext": "py", "lang": "Python", "max_stars_repo_path": "sparse_mixers/routing.py", "max_stars_repo_name": "dumpmemory/google-research", "max_stars_repo_head_hexsha": "bc87d010ab9086b6e92c3f075410fa6e1f27251b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sparse_mixers/routing.py", "max_issues_repo_name": "dumpmemory/google-research", "max_issues_repo_head_hexsha": "bc87d010ab9086b6e92c3f075410fa6e1f27251b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sparse_mixers/routing.py", "max_forks_repo_name": "dumpmemory/google-research", "max_forks_repo_head_hexsha": "bc87d010ab9086b6e92c3f075410fa6e1f27251b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.7882352941, "max_line_length": 80, "alphanum_fraction": 0.7193899625, "include": true, "reason": "import jax", "num_tokens": 6451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.1754052486805411}}
{"text": "import numpy as np\nimport time\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Function\nfrom torch.cuda.amp import custom_bwd, custom_fwd\n\ntry:\n    import _raymarching as _backend\nexcept ImportError:\n    from .backend import _backend\n\n\n# ----------------------------------------\n# utils\n# ----------------------------------------\n\nclass _near_far_from_aabb(Function):\n    @staticmethod\n    @custom_fwd(cast_inputs=torch.float32)\n    def forward(ctx, rays_o, rays_d, aabb, min_near=0.2):\n        ''' near_far_from_aabb, CUDA implementation\n        Calculate rays' intersection time (near and far) with aabb\n        Args:\n            rays_o: float, [N, 3]\n            rays_d: float, [N, 3]\n            aabb: float, [6], (xmin, ymin, zmin, xmax, ymax, zmax)\n            min_near: float, scalar\n        Returns:\n            nears: float, [N]\n            fars: float, [N]\n        '''\n        if not rays_o.is_cuda: rays_o = rays_o.cuda()\n        if not rays_d.is_cuda: rays_d = rays_d.cuda()\n\n        rays_o = rays_o.contiguous().view(-1, 3)\n        rays_d = rays_d.contiguous().view(-1, 3)\n\n        N = rays_o.shape[0] # num rays\n\n        nears = torch.empty(N, dtype=rays_o.dtype, device=rays_o.device)\n        fars = torch.empty(N, dtype=rays_o.dtype, device=rays_o.device)\n\n        _backend.near_far_from_aabb(rays_o, rays_d, aabb, N, min_near, nears, fars)\n\n        return nears, fars\n\nnear_far_from_aabb = _near_far_from_aabb.apply\n\n# ----------------------------------------\n# train functions\n# ----------------------------------------\n\nclass _march_rays_train(Function):\n    @staticmethod\n    @custom_fwd(cast_inputs=torch.float32)\n    def forward(ctx, rays_o, rays_d, bound, density_grid, mean_density, nears, fars, step_counter=None, mean_count=-1, perturb=False, align=-1, force_all_rays=False, dt_gamma=0, max_steps=1024):\n        ''' march rays to generate points (forward only)\n        Args:\n            rays_o/d: float, [N, 3]\n            bound: float, scalar\n            density_grid: float, [C, H, H, H]\n            mean_density: float, scalar\n            nears/fars: float, [N]\n            step_counter: int32, (2), used to count the actual number of generated points.\n            mean_count: int32, estimated mean steps to accelerate training. (but will randomly drop rays if the actual point count exceeded this threshold.)\n            perturb: bool\n            align: int, pad output so its size is dividable by align, set to -1 to disable.\n            force_all_rays: bool, ignore step_counter and mean_count, always calculate all rays. Useful if rendering the whole image, instead of some rays.\n            dt_gamma: float, called cone_angle in instant-ngp, exponentially accelerate ray marching if > 0. (very significant effect, but generally lead to worse performance)\n            max_steps: int, max number of sampled points along each ray, also affect min_stepsize.\n        Returns:\n            xyzs: float, [M, 3], all generated points' coords. (all rays concated, need to use `rays` to extract points belonging to each ray)\n            dirs: float, [M, 3], all generated points' view dirs.\n            deltas: float, [M, 2], all generated points' deltas. (first for RGB, second for Depth)\n            rays: int32, [N, 3], all rays' (index, point_offset, point_count), e.g., xyzs[rays[i, 1]:rays[i, 2]] --> points belonging to rays[i, 0]\n        '''\n\n        if not rays_o.is_cuda: rays_o = rays_o.cuda()\n        if not rays_d.is_cuda: rays_d = rays_d.cuda()\n        if not density_grid.is_cuda: density_grid = density_grid.cuda()\n        \n        rays_o = rays_o.contiguous().view(-1, 3)\n        rays_d = rays_d.contiguous().view(-1, 3)\n        density_grid = density_grid.contiguous()\n\n        N = rays_o.shape[0] # num rays\n\n        C = density_grid.shape[0] # grid cascade\n        H = density_grid.shape[1] # grid resolution\n\n        M = N * max_steps # init max points number in total\n\n        # running average based on previous epoch (mimic `measured_batch_size_before_compaction` in instant-ngp)\n        # It estimate the max points number to enable faster training, but will lead to random ignored rays if underestimated.\n        if not force_all_rays and mean_count > 0:\n            if align > 0:\n                mean_count += align - mean_count % align\n            M = mean_count\n        \n        xyzs = torch.zeros(M, 3, dtype=rays_o.dtype, device=rays_o.device)\n        dirs = torch.zeros(M, 3, dtype=rays_o.dtype, device=rays_o.device)\n        deltas = torch.zeros(M, 2, dtype=rays_o.dtype, device=rays_o.device)\n        rays = torch.empty(N, 3, dtype=torch.int32, device=rays_o.device) # id, offset, num_steps\n\n        if step_counter is None:\n            step_counter = torch.zeros(2, dtype=torch.int32, device=rays_o.device) # point counter, ray counter\n        \n        _backend.march_rays_train(rays_o, rays_d, density_grid, mean_density, bound, dt_gamma, max_steps, N, C, H, M, nears, fars, xyzs, dirs, deltas, rays, step_counter, perturb) # m is the actually used points number\n\n        #print(step_counter, M)\n\n        # only used at the first (few) epochs.\n        if force_all_rays or mean_count <= 0:\n            m = step_counter[0].item() # D2H copy\n            if align > 0:\n                m += align - m % align\n            xyzs = xyzs[:m]\n            dirs = dirs[:m]\n            deltas = deltas[:m]\n\n            torch.cuda.empty_cache()\n\n        return xyzs, dirs, deltas, rays\n\nmarch_rays_train = _march_rays_train.apply\n\n\nclass _composite_rays_train(Function):\n    @staticmethod\n    @custom_fwd(cast_inputs=torch.float32)\n    def forward(ctx, sigmas, rgbs, deltas, rays):\n        ''' composite rays' rgbs, according to the ray marching formula.\n        Args:\n            rgbs: float, [M, 3]\n            sigmas: float, [M,]\n            deltas: float, [M, 2]\n            rays: int32, [N, 3]\n        Returns:\n            weights_sum: float, [N,], the alpha channel\n            depth: float, [N, ], the Depth\n            image: float, [N, 3], the RGB channel (after multiplying alpha!)\n        '''\n        \n        sigmas = sigmas.contiguous()\n        rgbs = rgbs.contiguous()\n\n        M = sigmas.shape[0]\n        N = rays.shape[0]\n\n        weights_sum = torch.empty(N, dtype=sigmas.dtype, device=sigmas.device)\n        depth = torch.empty(N, dtype=sigmas.dtype, device=sigmas.device)\n        image = torch.empty(N, 3, dtype=sigmas.dtype, device=sigmas.device)\n\n        _backend.composite_rays_train_forward(sigmas, rgbs, deltas, rays, M, N, weights_sum, depth, image)\n\n        ctx.save_for_backward(sigmas, rgbs, deltas, rays, weights_sum, depth, image)\n        ctx.dims = [M, N]\n\n        return weights_sum, depth, image\n    \n    @staticmethod\n    @custom_bwd\n    def backward(ctx, grad_weights_sum, grad_depth, grad_image):\n\n        # NOTE: grad_depth is not used now! It won't be propagated to sigmas.\n\n        grad_weights_sum = grad_weights_sum.contiguous()\n        grad_image = grad_image.contiguous()\n\n        sigmas, rgbs, deltas, rays, weights_sum, depth, image = ctx.saved_tensors\n        M, N = ctx.dims\n   \n        grad_sigmas = torch.zeros_like(sigmas)\n        grad_rgbs = torch.zeros_like(rgbs)\n\n        _backend.composite_rays_train_backward(grad_weights_sum, grad_image, sigmas, rgbs, deltas, rays, weights_sum, image, M, N, grad_sigmas, grad_rgbs)\n\n        return grad_sigmas, grad_rgbs, None, None\n\n\ncomposite_rays_train = _composite_rays_train.apply\n\n# ----------------------------------------\n# infer functions\n# ----------------------------------------\n\nclass _march_rays(Function):\n    @staticmethod\n    @custom_fwd(cast_inputs=torch.float32)\n    def forward(ctx, n_alive, n_step, rays_alive, rays_t, rays_o, rays_d, bound, density_grid, mean_density, near, far, align=-1, perturb=False, dt_gamma=0, max_steps=1024):\n        ''' march rays to generate points (forward only, for inference)\n        Args:\n            n_alive: int, number of alive rays\n            n_step: int, how many steps we march\n            rays_alive: int, [N], the alive rays' IDs in N (N >= n_alive, but we only use first n_alive)\n            rays_t: float, [N], the alive rays' time, we only use the first n_alive.\n            rays_o/d: float, [N, 3]\n            bound: float, scalar\n            density_grid: float, [C, H, H, H]\n            mean_density: float, scalar\n            nears/fars: float, [N]\n            align: int, pad output so its size is dividable by align, set to -1 to disable.\n            perturb: bool/int, int > 0 is used as the random seed.\n            dt_gamma: float, called cone_angle in instant-ngp, exponentially accelerate ray marching if > 0. (very significant effect, but generally lead to worse performance)\n            max_steps: int, max number of sampled points along each ray, also affect min_stepsize.\n        Returns:\n            xyzs: float, [n_alive * n_step, 3], all generated points' coords\n            dirs: float, [n_alive * n_step, 3], all generated points' view dirs.\n            deltas: float, [n_alive * n_step, 2], all generated points' deltas (here we record two deltas, the first is for RGB, the second for depth).\n        '''\n        \n        if not rays_o.is_cuda: rays_o = rays_o.cuda()\n        if not rays_d.is_cuda: rays_d = rays_d.cuda()\n        \n        rays_o = rays_o.contiguous().view(-1, 3)\n        rays_d = rays_d.contiguous().view(-1, 3)\n\n        C = density_grid.shape[0] # grid cascade\n        H = density_grid.shape[1] # grid resolution\n        M = n_alive * n_step\n\n        if align > 0:\n            M += align - (M % align)\n        \n        xyzs = torch.zeros(M, 3, dtype=rays_o.dtype, device=rays_o.device)\n        dirs = torch.zeros(M, 3, dtype=rays_o.dtype, device=rays_o.device)\n        deltas = torch.zeros(M, 2, dtype=rays_o.dtype, device=rays_o.device) # 2 vals, one for rgb, one for depth\n\n        _backend.march_rays(n_alive, n_step, rays_alive, rays_t, rays_o, rays_d, bound, dt_gamma, max_steps, C, H, density_grid, mean_density, near, far, xyzs, dirs, deltas, perturb)\n\n        return xyzs, dirs, deltas\n\nmarch_rays = _march_rays.apply\n\n\nclass _composite_rays(Function):\n    @staticmethod\n    @custom_fwd(cast_inputs=torch.float32) # need to cast sigmas & rgbs to float\n    def forward(ctx, n_alive, n_step, rays_alive, rays_t, sigmas, rgbs, deltas, weights_sum, depth, image):\n        ''' composite rays' rgbs, according to the ray marching formula. (for inference)\n        Args:\n            n_alive: int, number of alive rays\n            n_step: int, how many steps we march\n            rays_alive: int, [N], the alive rays' IDs in N (N >= n_alive, but we only use first n_alive)\n            rays_t: float, [N], the alive rays' time, we only use the first n_alive.\n            sigmas: float, [n_alive * n_step,]\n            rgbs: float, [n_alive * n_step, 3]\n            deltas: float, [n_alive * n_step, 2], all generated points' deltas (here we record two deltas, the first is for RGB, the second for depth).\n        In-place Outputs:\n            weights_sum: float, [N,], the alpha channel\n            depth: float, [N,], the depth value\n            image: float, [N, 3], the RGB channel (after multiplying alpha!)\n        '''\n        _backend.composite_rays(n_alive, n_step, rays_alive, rays_t, sigmas, rgbs, deltas, weights_sum, depth, image)\n        return tuple()\n\n\ncomposite_rays = _composite_rays.apply\n\n\nclass _compact_rays(Function):\n    @staticmethod\n    @custom_fwd(cast_inputs=torch.float32)\n    def forward(ctx, n_alive, rays_alive, rays_alive_old, rays_t, rays_t_old, alive_counter):\n        ''' compact rays, remove dead rays and reallocate alive rays, to accelerate next ray marching.\n        Args:\n            n_alive: int, number of alive rays\n            rays_alive_old: int, [N]\n            rays_t_old: float, [N], dead rays are marked by rays_t < 0\n            alive_counter: int, [1], used to count remained alive rays.\n        In-place Outputs:\n            rays_alive: int, [N]\n            rays_t: float, [N]\n        '''    \n        _backend.compact_rays(n_alive, rays_alive, rays_alive_old, rays_t, rays_t_old, alive_counter)\n        return tuple()\n\ncompact_rays = _compact_rays.apply", "meta": {"hexsha": "71c7da99206403fd8354fa5d70b34b7c2b316f41", "size": 12156, "ext": "py", "lang": "Python", "max_stars_repo_path": "raymarching/raymarching.py", "max_stars_repo_name": "ashawkey/torch-ngp", "max_stars_repo_head_hexsha": "8f81bf90715776666dfb9c568b9e84abd9a5414c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 262, "max_stars_repo_stars_event_min_datetime": "2022-01-23T06:38:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:44:42.000Z", "max_issues_repo_path": "raymarching/raymarching.py", "max_issues_repo_name": "ashawkey/torch-ngp", "max_issues_repo_head_hexsha": "8f81bf90715776666dfb9c568b9e84abd9a5414c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 39, "max_issues_repo_issues_event_min_datetime": "2022-01-26T07:31:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T09:13:34.000Z", "max_forks_repo_path": "raymarching/raymarching.py", "max_forks_repo_name": "ashawkey/torch-ngp", "max_forks_repo_head_hexsha": "8f81bf90715776666dfb9c568b9e84abd9a5414c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2022-01-29T00:57:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T02:27:05.000Z", "avg_line_length": 43.4142857143, "max_line_length": 218, "alphanum_fraction": 0.6237249095, "include": true, "reason": "import numpy", "num_tokens": 3126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.17540524868054105}}
{"text": "import cv2\nimport numpy as np\n\n# Create a black image.\nimg = np.zeros((800, 800, 3), np.uint8)\n\n# Initialize the Kalman filter.\nkalman = cv2.KalmanFilter(4, 2)\nkalman.measurementMatrix = np.array(\n    [[1, 0, 0, 0],\n     [0, 1, 0, 0]], np.float32)\nkalman.transitionMatrix = np.array(\n    [[1, 0, 1, 0],\n     [0, 1, 0, 1],\n     [0, 0, 1, 0],\n     [0, 0, 0, 1]], np.float32)\nkalman.processNoiseCov = np.array(\n    [[1, 0, 0, 0],\n     [0, 1, 0, 0],\n     [0, 0, 1, 0],\n     [0, 0, 0, 1]], np.float32) * 0.03\n\nlast_measurement = None\nlast_prediction = None\n\ndef on_mouse_moved(event, x, y, flags, param):\n    global img, kalman, last_measurement, last_prediction\n\n    measurement = np.array([[x], [y]], np.float32)\n    if last_measurement is None:\n        # This is the first measurement.\n        # Update the Kalman filter's state to match the measurement.\n        kalman.statePre = np.array(\n            [[x], [y], [0], [0]], np.float32)\n        kalman.statePost = np.array(\n            [[x], [y], [0], [0]], np.float32)\n        prediction = measurement\n    else:\n        kalman.correct(measurement)\n        prediction = kalman.predict()  # Gets a reference, not a copy\n\n        # Trace the path of the measurement in green.\n        cv2.line(img, (last_measurement[0], last_measurement[1]),\n                 (measurement[0], measurement[1]), (0, 255, 0))\n\n        # Trace the path of the prediction in red.\n        cv2.line(img, (last_prediction[0], last_prediction[1]),\n                 (prediction[0], prediction[1]), (0, 0, 255))\n\n    last_prediction = prediction.copy()\n    last_measurement = measurement\n\ncv2.namedWindow('kalman_tracker')\ncv2.setMouseCallback('kalman_tracker', on_mouse_moved)\n\nwhile True:\n    cv2.imshow('kalman_tracker', img)\n    k = cv2.waitKey(1)\n    if k == 27:  # Escape\n        cv2.imwrite('kalman.png', img)\n        break\n", "meta": {"hexsha": "8171ad1175c2ef31f1dd49b14265b655f190eb8d", "size": 1849, "ext": "py", "lang": "Python", "max_stars_repo_path": "chapter08/kalman.py", "max_stars_repo_name": "ankona/Learning-OpenCV-4-Computer-Vision-with-Python-Third-Edition", "max_stars_repo_head_hexsha": "caa9326e310253fba1aab624b46ea899ce16a21f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 286, "max_stars_repo_stars_event_min_datetime": "2019-06-29T11:47:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T08:41:28.000Z", "max_issues_repo_path": "chapter08/kalman.py", "max_issues_repo_name": "chihhao428/Learning-OpenCV-4-Computer-Vision-with-Python-Third-Edition", "max_issues_repo_head_hexsha": "ee29cfefb4f21ba5acf6222aa69ef1c05c8fc05d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-10-01T17:48:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T04:27:06.000Z", "max_forks_repo_path": "chapter08/kalman.py", "max_forks_repo_name": "chihhao428/Learning-OpenCV-4-Computer-Vision-with-Python-Third-Edition", "max_forks_repo_head_hexsha": "ee29cfefb4f21ba5acf6222aa69ef1c05c8fc05d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 153, "max_forks_repo_forks_event_min_datetime": "2019-07-01T02:53:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T08:43:44.000Z", "avg_line_length": 29.8225806452, "max_line_length": 69, "alphanum_fraction": 0.5965386696, "include": true, "reason": "import numpy", "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.32082128783705344, "lm_q1q2_score": 0.1754052380293545}}
{"text": "#!/usr/bin/env python\n\n\"\"\"\nThis module provides classes to create phase diagrams.\n\"\"\"\n\nfrom __future__ import division\n\n__author__ = \"Shyue Ping Ong\"\n__copyright__ = \"Copyright 2011, The Materials Project\"\n__version__ = \"2.0\"\n__maintainer__ = \"Shyue Ping Ong\"\n__email__ = \"shyue@mit.edu\"\n__status__ = \"Production\"\n__date__ = \"Nov 25, 2012\"\n\nimport collections\nimport numpy as np\n\nfrom pyhull.convex_hull import ConvexHull\n\nfrom pymatgen.core.composition import Composition\nfrom pymatgen.phasediagram.entries import GrandPotPDEntry, TransformedPDEntry\n\nfrom pymatgen.core.periodic_table import DummySpecie\nfrom pymatgen.analysis.reaction_calculator import Reaction, ReactionError\n\n\nclass PhaseDiagram (object):\n    \"\"\"\n    Simple phase diagram class taking in elements and entries as inputs.\n    The algorithm is based on the work in the following papers:\n\n    1. S. P. Ong, L. Wang, B. Kang, and G. Ceder, Li-Fe-P-O2 Phase Diagram from\n       First Principles Calculations. Chem. Mater., 2008, 20(5), 1798-1807.\n       doi:10.1021/cm702327g\n\n    2. S. P. Ong, A. Jain, G. Hautier, B. Kang, G. Ceder, Thermal stabilities\n       of delithiated olivine MPO4 (M=Fe, Mn) cathodes investigated using first\n       principles calculations. Electrochem. Comm., 2010, 12(3), 427-430.\n       doi:10.1016/j.elecom.2010.01.010\n\n    .. attribute: elements:\n\n        Elements in the phase diagram.\n\n    ..attribute: all_entries\n\n        All entries provided for Phase Diagram construction. Note that this\n        does not mean that all these entries are actually used in the phase\n        diagram. For example, this includes the positive formation energy\n        entries that are filtered out before Phase Diagram construction.\n\n    .. attribute: qhull_data\n\n        Data used in the convex hull operation. This is essentially a matrix of\n        composition data and energy per atom values created from qhull_entries.\n\n    .. attribute: dim\n\n        The dimensionality of the phase diagram.\n\n    .. attribute: facets\n\n        Facets of the phase diagram in the form of  [[1,2,3],[4,5,6]...]\n\n    .. attribute: el_refs:\n\n        List of elemental references for the phase diagrams. These are\n        entries corresponding to the lowest energy element entries for simple\n        compositional phase diagrams.\n\n    .. attribute: qhull_entries:\n\n        Actual entries used in convex hull. Excludes all positive formation\n        energy entries.\n    \"\"\"\n\n    # Tolerance for determining if formation energy is positive.\n    formation_energy_tol = 1e-11\n\n    def __init__(self, entries, elements=None):\n        \"\"\"\n        Standard constructor for phase diagram.\n\n        Args:\n            entries:\n                A list of PDEntry-like objects having an energy,\n                energy_per_atom and composition.\n            elements:\n                Optional list of elements in the phase diagram. If set to None,\n                the elements are determined from the the entries themselves.\n        \"\"\"\n        if elements is None:\n            elements = set()\n            map(elements.update, [entry.composition.elements\n                                  for entry in entries])\n        elements = list(elements)\n        # Qhull seems to be sensitive to choice of independent composition\n        # components due to numerical issues in higher dimensions. The\n        # code permutes the element sequence until one that works is found.\n        dim = len(elements)\n        el_refs = {}\n        for el in elements:\n            el_entries = filter(lambda e: e.composition.is_element and\n                                e.composition.elements[0] == el, entries)\n            if len(el_entries) == 0:\n                raise PhaseDiagramError(\n                    \"There are no entries associated with terminal {}.\"\n                    .format(el))\n            el_refs[el] = min(el_entries, key=lambda e: e.energy_per_atom)\n\n        data = []\n        for entry in entries:\n            comp = entry.composition\n            row = map(comp.get_atomic_fraction, elements)\n            row.append(entry.energy_per_atom)\n            data.append(row)\n\n        data = np.array(data)\n        self.all_entries_hulldata = data[:, 1:]\n\n        # Calculate formation energies and remove positive formation energy\n        # entries\n        vec = [el_refs[el].energy_per_atom for el in elements] + [-1]\n        form_e = -np.dot(data, vec)\n        ind = np.where(form_e <= -self.formation_energy_tol)[0].tolist()\n        ind.extend(map(entries.index, el_refs.values()))\n        qhull_entries = [entries[i] for i in ind]\n        qhull_data = data[ind][:, 1:]\n\n        if len(qhull_data) == dim:\n            self.facets = [range(dim)]\n        else:\n            facets = ConvexHull(qhull_data, joggle=True).vertices\n            finalfacets = []\n            for facet in facets:\n                is_non_element_facet = any(\n                    (len(qhull_entries[i].composition) > 1 for i in facet))\n                if is_non_element_facet:\n                    m = qhull_data[facet]\n                    m[:, -1] = 1\n                    if abs(np.linalg.det(m)) > 1e-8:\n                        finalfacets.append(facet)\n            self.facets = finalfacets\n\n        self.all_entries = entries\n        self.qhull_data = qhull_data\n        self.dim = dim\n        self.el_refs = el_refs\n        self.elements = elements\n        self.qhull_entries = qhull_entries\n\n    @property\n    def unstable_entries(self):\n        \"\"\"\n        Entries that are unstable in the phase diagram. Includes positive\n        formation energy entries.\n        \"\"\"\n        return [e for e in self.all_entries if e not in self.stable_entries]\n\n    @property\n    def stable_entries(self):\n        \"\"\"\n        Returns the stable entries in the phase diagram.\n        \"\"\"\n        stable_entries = set()\n        for facet in self.facets:\n            for vertex in facet:\n                stable_entries.add(self.qhull_entries[vertex])\n        return stable_entries\n\n    def get_form_energy(self, entry):\n        \"\"\"\n        Returns the formation energy for an entry (NOT normalized) from the\n        elemental references.\n\n        Args:\n            entry:\n                A PDEntry-like object.\n\n        Returns:\n            Formation energy from the elemental references.\n        \"\"\"\n        comp = entry.composition\n        energy = entry.energy - sum([comp[el] *\n                                     self.el_refs[el].energy_per_atom\n                                     for el in comp.elements])\n        return energy\n\n    def get_form_energy_per_atom(self, entry):\n        \"\"\"\n        Returns the formation energy per atom for an entry from the\n        elemental references.\n\n        Args:\n            entry:\n                An PDEntry-like object\n\n        Returns:\n            Formation energy **per atom** from the elemental references.\n        \"\"\"\n        comp = entry.composition\n        return self.get_form_energy(entry) / comp.num_atoms\n\n    def __repr__(self):\n        return self.__str__()\n\n    def __str__(self):\n        symbols = [el.symbol for el in self.elements]\n        output = [\"{} phase diagram\".format(\"-\".join(symbols)),\n                  \"{} stable phases: \".format(len(self.stable_entries)),\n                  \", \".join([entry.name\n                             for entry in self.stable_entries])]\n        return \"\\n\".join(output)\n\n\nclass GrandPotentialPhaseDiagram(PhaseDiagram):\n    \"\"\"\n    A class representing a Grand potential phase diagram. Grand potential phase\n    diagrams are essentially phase diagrams that are open to one or more\n    components. To construct such phase diagrams, the relevant free energy is\n    the grand potential, which can be written as the Legendre transform of the\n    Gibbs free energy as follows\n\n    Grand potential = G - u\\ :sub:`X` N\\ :sub:`X`\\\n\n    The algorithm is based on the work in the following papers:\n\n    1. S. P. Ong, L. Wang, B. Kang, and G. Ceder, Li-Fe-P-O2 Phase Diagram from\n       First Principles Calculations. Chem. Mater., 2008, 20(5), 1798-1807.\n       doi:10.1021/cm702327g\n\n    2. S. P. Ong, A. Jain, G. Hautier, B. Kang, G. Ceder, Thermal stabilities\n       of delithiated olivine MPO4 (M=Fe, Mn) cathodes investigated using first\n       principles calculations. Electrochem. Comm., 2010, 12(3), 427-430.\n       doi:10.1016/j.elecom.2010.01.010\n    \"\"\"\n\n    def __init__(self, entries, chempots, elements=None):\n        \"\"\"\n        Standard constructor for grand potential phase diagram.\n\n        Args:\n            entries:\n                A list of PDEntry-like objects having an energy,\n                energy_per_atom and composition.\n            chempots:\n                A dict of {element: float} to specify the chemical potentials\n                of the open elements.\n            elements:\n                Optional list of elements in the phase diagram. If set to None,\n                the elements are determined from the entries themselves.\n        \"\"\"\n        if elements is None:\n            elements = set()\n            map(elements.update, [entry.composition.elements\n                                  for entry in entries])\n\n        elements = set(elements).difference(chempots.keys())\n        all_entries = [GrandPotPDEntry(e, chempots)\n                       for e in entries\n                       if (not e.is_element) or\n                       e.composition.elements[0] in elements]\n        self.chempots = chempots\n\n        super(GrandPotentialPhaseDiagram, self).__init__(all_entries, elements)\n\n    def __str__(self):\n        output = []\n        chemsys = \"-\".join([el.symbol for el in self.elements])\n        output.append(\"{} grand potential phase diagram with \".format(chemsys))\n        output[-1] += \", \".join([\"u{}={}\".format(el, v)\n                                 for el, v in self.chempots.items()])\n        output.append(\"{} stable phases: \".format(len(self.stable_entries)))\n        output.append(\", \".join([entry.name\n                                 for entry in self.stable_entries]))\n        return \"\\n\".join(output)\n\n\nclass CompoundPhaseDiagram(PhaseDiagram):\n    \"\"\"\n    Generates phase diagrams from compounds as terminations instead of\n    elements.\n    \"\"\"\n\n    # Tolerance for determining if amount of a composition is positive.\n    amount_tol = 1e-5\n\n    def __init__(self, entries, terminal_compositions,\n                 normalize_terminal_compositions=True):\n        \"\"\"\n        Args:\n            entries:\n                Sequence of input entries. For example, if you want a Li2O-P2O5\n                phase diagram, you might have all Li-P-O entries as an input.\n            terminal_compositions:\n                Terminal compositions of phase space. In the Li2O-P2O5 example,\n                these will be the Li2O and P2O5 compositions.\n            normalize_terminal_compositions:\n                Whether to normalize the terminal compositions to a per atom\n                basis. If normalized, the energy above hulls will be consistent\n                for comparison across systems. Non-normalized terminals are\n                more intuitive in terms of compositional breakdowns.\n        \"\"\"\n        self.original_entries = entries\n        self.terminal_compositions = terminal_compositions\n        self.normalize_terminals = normalize_terminal_compositions\n        (pentries, species_mapping) = \\\n            self.transform_entries(entries, terminal_compositions)\n        self.species_mapping = species_mapping\n        PhaseDiagram.__init__(self, pentries,\n                              elements=species_mapping.values())\n\n    def transform_entries(self, entries, terminal_compositions):\n        \"\"\"\n        Method to transform all entries to the composition coordinate in the\n        terminal compositions. If the entry does not fall within the space\n        defined by the terminal compositions, they are excluded. For example,\n        Li3PO4 is mapped into a Li2O:1.5, P2O5:0.5 composition. The terminal\n        compositions are represented by DummySpecies.\n\n        Args:\n            entries:\n                Sequence of all input entries\n            terminal_compositions:\n                Terminal compositions of phase space.\n\n        Returns:\n            Sequence of TransformedPDEntries falling within the phase space.\n        \"\"\"\n        new_entries = []\n        if self.normalize_terminals:\n            fractional_comp = [c.get_fractional_composition()\n                               for c in terminal_compositions]\n        else:\n            fractional_comp = terminal_compositions\n\n        #Map terminal compositions to unique dummy species.\n        sp_mapping = collections.OrderedDict()\n        for i, comp in enumerate(fractional_comp):\n            sp_mapping[comp] = DummySpecie(\"X\" + chr(102 + i))\n\n        for entry in entries:\n            try:\n                rxn = Reaction(fractional_comp, [entry.composition])\n                rxn.normalize_to(entry.composition)\n                #We only allow reactions that have positive amounts of\n                #reactants.\n                if all([rxn.get_coeff(comp) <= CompoundPhaseDiagram.amount_tol\n                        for comp in fractional_comp]):\n                    newcomp = {sp_mapping[comp]: -rxn.get_coeff(comp)\n                               for comp in fractional_comp}\n                    newcomp = {k: v for k, v in newcomp.items()\n                               if v > CompoundPhaseDiagram.amount_tol}\n                    transformed_entry = \\\n                        TransformedPDEntry(Composition(newcomp), entry)\n                    new_entries.append(transformed_entry)\n            except ReactionError:\n                #If the reaction can't be balanced, the entry does not fall\n                #into the phase space. We ignore them.\n                pass\n        return new_entries, sp_mapping\n\n\nclass PhaseDiagramError(Exception):\n    \"\"\"\n    An exception class for Phase Diagram generation.\n    \"\"\"\n    pass\n", "meta": {"hexsha": "685282af3f05d11acefcef04801d907e8381fdce", "size": 13957, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymatgen/phasediagram/pdmaker.py", "max_stars_repo_name": "miaoliu/pymatgen", "max_stars_repo_head_hexsha": "fe3c48ce3334924e6693f857aebc64b9714d1af2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pymatgen/phasediagram/pdmaker.py", "max_issues_repo_name": "miaoliu/pymatgen", "max_issues_repo_head_hexsha": "fe3c48ce3334924e6693f857aebc64b9714d1af2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pymatgen/phasediagram/pdmaker.py", "max_forks_repo_name": "miaoliu/pymatgen", "max_forks_repo_head_hexsha": "fe3c48ce3334924e6693f857aebc64b9714d1af2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6199460916, "max_line_length": 79, "alphanum_fraction": 0.6086551551, "include": true, "reason": "import numpy", "num_tokens": 2993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.17534290043917716}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nClass definitions for RRTMG objects in RCE model. Implements bridge between\npyRRTMG API and the RCE model solver requirements.\n\nCreated on Tue Nov 15 18:43:23 2016\n\n@author: maxwell\n\"\"\"\n\n\nfrom radiation.radiation import RadModel,Flux\nimport radiation.pyrrtmg as rr\nimport numpy as np\n\n\nclass RRTMGModel(RadModel):\n    \"\"\"\n    Class construct for pyrrtmg\n    \"\"\"\n\n    def __init__(self,cpdair=None,**kwargs):\n\n        print('ititializing rrtmg object')\n        if cpdair is None:\n            print(\n                \"WARNING: cpdair not provided to RRTMGModel. \" ,\n                \"Using pyRRTMG default.\"\n                 )\n            rr.lw.init()\n            rr.sw.init()\n        else:\n            rr.lw.init(cpdair)\n            rr.sw.init(cpdair)\n    def radiation(self,atms,cparm,lwparm, swparm):\n        \"\"\"\n        Calculates RRTMG radiation.\n\n        Expects an Atmosphere object with the following variables (size):\n            play (n)\n            plev (n+1)\n            tlay (n)\n            tlev (n+1)\n            qlay (n)\n            o3lay (n)\n        Expects a ChemParm object with the following scalars:\n            co2\n            ch4\n            n2o\n            o2\n            cfc11\n            cfc12\n            cfc22\n            ccl4\n        Expects a LWParm object with the following scalars:\n            emis\n        Expects a SWParm object with the following scalars:\n            albedo\n            fday\n            coszen\n            scon\n\n        Returns a Flux object with short and longwave fluxes\n        \"\"\"\n        fuir = np.empty(len(atms.plev))\n        fdir = np.empty(len(atms.plev))\n        fusw = np.empty(len(atms.plev))\n        fdsw = np.empty(len(atms.plev))\n\n        # flip indices, since rrtm expects pressure to decrease with index,\n        # while the Atmosphere class expects pressure to increase with index.\n        (fuir[::-1], fdir[::-1]) = rr.lw.rad(atms.play[::-1], atms.plev[::-1],\n                                 atms.tlay[::-1], atms.tlev[::-1],\n                                 atms.tsfc,\n                                 atms.qlay[::-1], atms.o3lay[::-1],\n                                 **cparm, **lwparm)\n        (fusw[::-1], fdsw[::-1]) = rr.sw.rad(atms.play[::-1], atms.plev[::-1],\n                                 atms.tlay[::-1], atms.tlev[::-1],\n                                 atms.tsfc,\n                                 atms.qlay[::-1], atms.o3lay[::-1],\n                                 **cparm, **swparm)\n\n        return Flux(fuir,fdir,fusw,fdsw)\n\n", "meta": {"hexsha": "c90b7d11b0e2789068533a9c2e2d6f9f2d1077c3", "size": 2562, "ext": "py", "lang": "Python", "max_stars_repo_path": "radiation/rrtmg.py", "max_stars_repo_name": "msmithsm/rce", "max_stars_repo_head_hexsha": "91e6fd2ee93b64a471aa7e0ca62bb4649c1b3b19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "radiation/rrtmg.py", "max_issues_repo_name": "msmithsm/rce", "max_issues_repo_head_hexsha": "91e6fd2ee93b64a471aa7e0ca62bb4649c1b3b19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "radiation/rrtmg.py", "max_forks_repo_name": "msmithsm/rce", "max_forks_repo_head_hexsha": "91e6fd2ee93b64a471aa7e0ca62bb4649c1b3b19", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7906976744, "max_line_length": 78, "alphanum_fraction": 0.493754879, "include": true, "reason": "import numpy", "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.17534289327014715}}
{"text": "import numpy as np\nimport xmltodict\nimport os\nimport cv2\nimport matplotlib.pyplot as plt\nfrom glob import glob\nfrom concurrent.futures import ThreadPoolExecutor\n\nimport tensorflow as tf\n\nanchor_scale = 16\n#\nIOU_NEGATIVE = 0.3\nIOU_POSITIVE = 0.7\nIOU_SELECT = 0.7\n\nRPN_POSITIVE_NUM = 150\nRPN_TOTAL_NUM = 300\n\n# bgr  can find from  here https://github.com/fchollet/deep-learning-models/blob/master/imagenet_utils.py\nIMAGE_MEAN = [123.68, 116.779, 103.939]\n\nDEBUG = True\n\n\ndef readxml(path):\n    gtboxes = []\n    with open(path, 'rb') as f:\n        xml = xmltodict.parse(f)\n        bboxes = xml['annotation']['object']\n        if (type(bboxes) != list):\n            x1 = bboxes['bndbox']['xmin']\n            y1 = bboxes['bndbox']['ymin']\n            x2 = bboxes['bndbox']['xmax']\n            y2 = bboxes['bndbox']['ymax']\n            gtboxes.append((int(x1), int(y1), int(x2), int(y2)))\n        else:\n            with ThreadPoolExecutor() as executor:\n                for x1, y1, x2, y2 in executor.map(lambda bbox: (bbox['bndbox']['xmin'], bbox['bndbox']['ymin'],\n                                                                 bbox['bndbox']['xmax'], bbox['bndbox']['ymax']),\n                                                   bboxes):\n                    gtboxes.append((int(x1), int(y1), int(x2), int(y2)))\n\n        imgfile = xml['annotation']['filename']\n    return np.array(gtboxes), imgfile\n\n\ndef gen_anchor(featuresize, scale):\n    \"\"\"\n    gen base anchor from feature map [HXW][10][4]\n    reshape  [HXW][10][4] to [HXWX10][4]\n    生成的锚框是相对于原图的，即原图中每16像素就有10个锚框\n    \"\"\"\n\n    heights = [11, 16, 23, 33, 48, 68, 97, 139, 198, 283]\n    widths = [16, 16, 16, 16, 16, 16, 16, 16, 16, 16]\n\n    # gen k=9 anchor size (h,w)\n    heights = np.array(heights).reshape(len(heights), 1)\n    widths = np.array(widths).reshape(len(widths), 1)\n\n    # 锚框大小为16像素\n    base_anchor = np.array([0, 0, 15, 15])\n    # center x,y\n    xt = (base_anchor[0] + base_anchor[2]) * 0.5\n    yt = (base_anchor[1] + base_anchor[3]) * 0.5\n\n    # x1 y1 x2 y2 \n    x1 = xt - widths * 0.5\n    y1 = yt - heights * 0.5\n    x2 = xt + widths * 0.5\n    y2 = yt + heights * 0.5\n\n    # 一组十个锚框\n    base_anchor = np.hstack((x1, y1, x2, y2))\n\n    h, w = featuresize\n    shift_x = np.arange(0, w) * scale\n    shift_y = np.arange(0, h) * scale\n    # apply shift\n    anchor = []\n    for i in shift_y:\n        for j in shift_x:\n            anchor.append(base_anchor + [j, i, j, i])\n    return np.array(anchor).reshape((-1, 4))\n\n\ndef cal_iou(box1, box1_area, boxes2, boxes2_area):\n    \"\"\"\n    box1 [x1,y1,x2,y2]\n    boxes2 [Msample,x1,y1,x2,y2]\n    \"\"\"\n    x1 = np.maximum(box1[0], boxes2[:, 0])\n    x2 = np.minimum(box1[2], boxes2[:, 2])\n    y1 = np.maximum(box1[1], boxes2[:, 1])\n    y2 = np.minimum(box1[3], boxes2[:, 3])\n\n    intersection = np.maximum(x2 - x1, 0) * np.maximum(y2 - y1, 0)\n    iou = intersection / (box1_area + boxes2_area[:] - intersection[:])\n    return iou\n\n\ndef cal_overlaps(boxes1, boxes2):\n    \"\"\"\n    boxes1 [Nsample,x1,y1,x2,y2]  anchor\n    boxes2 [Msample,x1,y1,x2,y2]  grouth-box\n    \n    \"\"\"\n    area1 = (boxes1[:, 0] - boxes1[:, 2]) * (boxes1[:, 1] - boxes1[:, 3])  # (Nsample, 1)\n    area2 = (boxes2[:, 0] - boxes2[:, 2]) * (boxes2[:, 1] - boxes2[:, 3])  # (Msample, 1)\n\n    overlaps = np.zeros((boxes1.shape[0], boxes2.shape[0]))  # (Nsample, Msample)\n\n    # calculate the intersection of  boxes1(anchor) and boxes2(GT box)\n    for i in range(boxes1.shape[0]):\n        overlaps[i][:] = cal_iou(boxes1[i], area1[i], boxes2, area2)\n\n    return overlaps\n\n\ndef bbox_transfrom(anchors, gtboxes):\n    \"\"\"\n    anchors: (Nsample, 4)\n    gtboxes: (Nsample, 4)\n     compute relative predicted vertical coordinates Vc ,Vh\n        with respect to the bounding box location of an anchor \n    \"\"\"\n    Cy = (gtboxes[:, 1] + gtboxes[:, 3]) * 0.5  # (Nsample, )\n    Cya = (anchors[:, 1] + anchors[:, 3]) * 0.5  # (Nsample, )\n    h = gtboxes[:, 3] - gtboxes[:, 1] + 1.0  # (Nsample, )\n    ha = anchors[:, 3] - anchors[:, 1] + 1.0  # (Nsample, )\n\n    Vc = (Cy - Cya) / ha  # (Nsample, )\n    Vh = np.log(h / ha)  # (Nsample, )\n\n    ret = np.vstack((Vc, Vh))\n\n    return ret.transpose()  # (Nsample, 2)\n\n\ndef bbox_transfor_inv(anchor, regr):\n    \"\"\"\n    anchor: (NSample, 4)\n    regr: (NSample, 2)\n\n    根据锚框和偏移量反向得到GTBox\n    \"\"\"\n\n    Cya = (anchor[:, 1] + anchor[:, 3]) * 0.5  # 锚框y中心点\n    ha = anchor[:, 3] - anchor[:, 1] + 1\n\n    Vcx = regr[..., 0]  # y中心点偏移\n    Vhx = regr[..., 1]  # 高度偏移\n\n    Cyx = Vcx * ha + Cya  # GTBox y中心点\n    hx = np.exp(Vhx) * ha  # GTBox 高\n    xt = (anchor[:, 0] + anchor[:, 2]) * 0.5  # 锚框x中心点\n\n    x1 = xt - 16 * 0.5\n    y1 = Cyx - hx * 0.5\n    x2 = xt + 16 * 0.5\n    y2 = Cyx + hx * 0.5\n    bbox = np.vstack((x1, y1, x2, y2)).transpose()\n\n    return bbox\n\n\ndef clip_box(bbox, im_shape):\n    # x1 >= 0\n    bbox[:, 0] = np.maximum(np.minimum(bbox[:, 0], im_shape[1] - 1), 0)\n    # y1 >= 0\n    bbox[:, 1] = np.maximum(np.minimum(bbox[:, 1], im_shape[0] - 1), 0)\n    # x2 < im_shape[1]\n    bbox[:, 2] = np.maximum(np.minimum(bbox[:, 2], im_shape[1] - 1), 0)\n    # y2 < im_shape[0]\n    bbox[:, 3] = np.maximum(np.minimum(bbox[:, 3], im_shape[0] - 1), 0)\n\n    return bbox\n\n\ndef filter_bbox(bbox, minsize):\n    ws = bbox[:, 2] - bbox[:, 0] + 1\n    hs = bbox[:, 3] - bbox[:, 1] + 1\n    keep = np.where((ws >= minsize) & (hs >= minsize))[0]\n    return keep\n\n\ndef cal_rpn(imgsize, featuresize, scale, gtboxes):\n    \"\"\"\n    gtboxes: (Msample, 4)\n    \"\"\"\n    imgh, imgw = imgsize\n\n    # gen base anchor\n    base_anchor = gen_anchor(featuresize, scale)  # (Nsample, 4)\n\n    # calculate iou\n    overlaps = cal_overlaps(base_anchor, gtboxes)  # (Nsample, Msample)\n\n    # init labels -1 don't care  0 is negative  1 is positive\n    labels = np.empty(base_anchor.shape[0])\n    labels.fill(-1)  # (Nsample,)\n\n    # for each GT box corresponds to an anchor which has highest IOU\n    gt_argmax_overlaps = overlaps.argmax(axis=0)  # (Msample, )\n\n    # the anchor with the highest IOU overlap with a GT box\n    anchor_argmax_overlaps = overlaps.argmax(axis=1)  # (Nsample, )\n    anchor_max_overlaps = overlaps[range(overlaps.shape[0]), anchor_argmax_overlaps]  # (Nsample, )\n\n    # IOU > IOU_POSITIVE\n    labels[anchor_max_overlaps > IOU_POSITIVE] = 1\n    # IOU <IOU_NEGATIVE\n    labels[anchor_max_overlaps < IOU_NEGATIVE] = 0\n    # ensure that every GT box has at least one positive RPN region\n    labels[gt_argmax_overlaps] = 1\n\n    # only keep anchors inside the image\n    outside_anchor = np.where(\n        (base_anchor[:, 0] < 0) |\n        (base_anchor[:, 1] < 0) |\n        (base_anchor[:, 2] >= imgw) |\n        (base_anchor[:, 3] >= imgh)\n    )[0]\n    labels[outside_anchor] = -1\n\n    # 剔除掉多余的正负样例\n    # subsample positive labels ,if greater than RPN_POSITIVE_NUM(default 128)\n    fg_index = np.where(labels == 1)[0]\n    if (len(fg_index) > RPN_POSITIVE_NUM):\n        labels[np.random.choice(fg_index, len(fg_index) - RPN_POSITIVE_NUM, replace=False)] = -1\n\n    # subsample negative labels\n    bg_index = np.where(labels == 0)[0]\n    num_bg = RPN_TOTAL_NUM - np.sum(labels == 1)\n    if (len(bg_index) > num_bg):\n        # print('bgindex:',len(bg_index),'num_bg',num_bg)\n        labels[np.random.choice(bg_index, len(bg_index) - num_bg, replace=False)] = -1\n\n    # calculate bbox targets\n    # debug here \n    bbox_targets = bbox_transfrom(base_anchor, gtboxes[anchor_argmax_overlaps, :])\n    # bbox_targets=[]\n\n    return [labels, bbox_targets], base_anchor\n\n\ndef get_session(gpu_fraction=0.6):\n    '''''Assume that you have 6GB of GPU memory and want to allocate ~2GB'''\n\n    num_threads = os.environ.get('OMP_NUM_THREADS')\n    gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_fraction)\n\n    if num_threads:\n        return tf.Session(config=tf.ConfigProto(\n            gpu_options=gpu_options, intra_op_parallelism_threads=num_threads, allow_soft_placement=True))\n    else:\n        return tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, allow_soft_placement=True))\n\n\nclass random_uniform_num():\n    \"\"\"\n    uniform random\n    \"\"\"\n\n    def __init__(self, total, start=0):\n        self.total = total\n        self.range = [i for i in range(total)]\n        np.random.shuffle(self.range)\n        self.index = start\n\n    def get(self, batch_size):\n        ret = []\n        if self.index + batch_size > self.total:\n            piece1 = self.range[self.index:]\n            np.random.shuffle(self.range)\n            self.index = (self.index + batch_size) - self.total\n            piece2 = self.range[0:self.index]\n            ret.extend(piece1)\n            ret.extend(piece2)\n        else:\n            ret = self.range[self.index:self.index + batch_size]\n            self.index = self.index + batch_size\n        return ret\n\n\ndef nms(dets, thresh):\n    x1 = dets[:, 0]\n    y1 = dets[:, 1]\n    x2 = dets[:, 2]\n    y2 = dets[:, 3]\n    scores = dets[:, 4]\n\n    areas = (x2 - x1 + 1) * (y2 - y1 + 1)\n    order = scores.argsort()[::-1]  # Sort from high to low\n\n    keep = []\n    while order.size > 0:\n        i = order[0]\n        keep.append(i)\n        xx1 = np.maximum(x1[i], x1[order[1:]])\n        yy1 = np.maximum(y1[i], y1[order[1:]])\n        xx2 = np.minimum(x2[i], x2[order[1:]])\n        yy2 = np.minimum(y2[i], y2[order[1:]])\n\n        w = np.maximum(0.0, xx2 - xx1 + 1)\n        h = np.maximum(0.0, yy2 - yy1 + 1)\n        inter = w * h\n        ovr = inter / (areas[i] + areas[order[1:]] - inter)\n\n        inds = np.where(ovr <= thresh)[0]\n        order = order[inds + 1]\n    return keep\n\n\ndef gen_sample(xmlpath, imgpath, batchsize=1):\n    \"\"\"\n    由于图像大小不定，批处理大小只能为1\n    \"\"\"\n\n    # list xml \n    xmlfiles = glob(xmlpath + '/*.xml')\n    rd = random_uniform_num(len(xmlfiles))\n    xmlfiles = np.array(xmlfiles)\n\n    while True:\n        shuf = xmlfiles[rd.get(1)]\n        gtbox, imgfile = readxml(shuf[0])\n        img = cv2.imread(imgpath + \"\\\\\" + imgfile)\n        h, w, c = img.shape\n\n        # clip image\n        if np.random.randint(0, 100) > 50:\n            img = img[:, ::-1, :]\n            newx1 = w - gtbox[:, 2] - 1\n            newx2 = w - gtbox[:, 0] - 1\n            gtbox[:, 0] = newx1\n            gtbox[:, 2] = newx2\n\n        [cls, regr], _ = cal_rpn((h, w), (int(h / 16), int(w / 16)), 16, gtbox)\n        # zero-center by mean pixel\n        m_img = img - IMAGE_MEAN\n        m_img = np.expand_dims(m_img, axis=0)\n\n        regr = np.hstack([cls.reshape(cls.shape[0], 1), regr])\n\n        #\n        cls = np.expand_dims(cls, axis=0)\n        cls = np.expand_dims(cls, axis=1)\n        # regr = np.expand_dims(regr,axis=1)\n        regr = np.expand_dims(regr, axis=0)\n\n        yield m_img, {'rpn_class_reshape': cls, 'rpn_regress_reshape': regr}\n\n\ndef rpn_test():\n    xmlpath = 'G:\\data\\VOCdevkit\\VOC2007\\Annotations\\img_4375.xml'\n    imgpath = 'G:\\data\\VOCdevkit\\VOC2007\\JPEGImages\\img_4375.jpg'\n    gtbox, _ = readxml(xmlpath)\n    img = cv2.imread(imgpath)\n    h, w, c = img.shape\n    [cls, regr], base_anchor = cal_rpn((h, w), (int(h / 16), int(w / 16)), 16, gtbox)\n    print(cls.shape)\n    print(regr.shape)\n\n    regr = np.expand_dims(regr, axis=0)\n    inv_anchor = bbox_transfor_inv(base_anchor, regr)\n    anchors = inv_anchor[cls == 1]\n    anchors = anchors.astype(int)\n    for i in anchors:\n        cv2.rectangle(img, (i[0], i[1]), (i[2], i[3]), (255, 0, 0), 3)\n    plt.imshow(img)\n\n# rpn_test()\n# plt.show()\n\n# xmlpath = 'E:\\data\\VOCdevkit\\VOC2007\\Annotations'\n# imgpath = 'E:\\data\\VOCdevkit\\VOC2007\\JPEGImages'\n# gen1 = gen_sample(xmlpath, imgpath, 3)\n# _, ret = next(gen1)\n# print(ret.get('rpn_class_reshape').shape)\n# print(ret.get('rpn_regress_reshape').shape)\n", "meta": {"hexsha": "b17301fef3429e2253910910d35db1ca2de9c5fa", "size": 11570, "ext": "py", "lang": "Python", "max_stars_repo_path": "dlocr/ctpn/lib/utils.py", "max_stars_repo_name": "GlassyWing/text-detection-ocr", "max_stars_repo_head_hexsha": "9bb9efd4a0a7af7d1a9a6784450d1843ffe15d8a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 277, "max_stars_repo_stars_event_min_datetime": "2018-11-14T06:15:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T15:20:40.000Z", "max_issues_repo_path": "dlocr/ctpn/lib/utils.py", "max_issues_repo_name": "dun933/text-detection-ocr", "max_issues_repo_head_hexsha": "9bb9efd4a0a7af7d1a9a6784450d1843ffe15d8a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 31, "max_issues_repo_issues_event_min_datetime": "2018-11-19T09:47:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-18T16:36:42.000Z", "max_forks_repo_path": "dlocr/ctpn/lib/utils.py", "max_forks_repo_name": "dun933/text-detection-ocr", "max_forks_repo_head_hexsha": "9bb9efd4a0a7af7d1a9a6784450d1843ffe15d8a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 116, "max_forks_repo_forks_event_min_datetime": "2018-11-14T06:15:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T09:09:42.000Z", "avg_line_length": 30.2088772846, "max_line_length": 113, "alphanum_fraction": 0.5762316335, "include": true, "reason": "import numpy", "num_tokens": 3877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3140505321516081, "lm_q1q2_score": 0.17534288968563225}}
{"text": "\nimport numpy as np\nimport glob\nfrom losses import jacobian_determinant1\nimport torch\nimport torch.nn.functional as nnf\nimport os\nimport argparse\nfrom model import Net\n\nparser = argparse.ArgumentParser(description='param')\nparser.add_argument(\"--gpu\", type=str, help=\"gpu id\",dest=\"gpu\", default='0')\nparser.add_argument('--atlas_file', default=\"/home/songlei/OASdata/OAS_new/atlases/\", type=str)#UM_379\nparser.add_argument('--checkpoint_path',\n                    default=\"/home/newdisk/songlei/train/version_ResT_new/ResT1/checkpoint&log4/BN_False/lsMSElr0.0001/s0.02/0.7426435049957362_model_best.pth.tar\",\n                    type=str)\nparser.add_argument('--test_file', default=\"/home/songlei/OASdata/OAS_new/valsets/\", type=str)\nargs = parser.parse_args()\ndef test():\n    device = torch.device('cuda:{}'.format(args.gpu) if torch.cuda.is_available() else 'cpu')\n    print(args.checkpoint_path)\n    model = Net((1, 1, 96, 112, 96), 3)\n    check_point = torch.load(args.checkpoint_path, map_location='cpu')\n    model.load_state_dict(check_point['state_dict'])\n    model = model.to(device)\n    model.eval()\n\n    labels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n              20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]\n\n    val_acc = 0.0\n    atlas_paths = glob.glob(os.path.join(args.atlas_file + '*_MR1.npy'))\n    val_paths = glob.glob(os.path.join(args.test_file + '*_MR1.npy'))\n    JAC = []\n    Dice = []\n    Time = []\n    for atlas_path in atlas_paths:\n       atlas_name = os.path.split(atlas_path)[1][:-4]\n       atlas = np.load(atlas_path)\n       atlas_label = np.load(args.atlas_file+atlas_name+\"_label.npy\")\n       atlas = torch.Tensor(atlas).cuda(device=device).unsqueeze(0).unsqueeze(0)\n       for val_path in val_paths:\n                val_name = os.path.split(val_path)[1][:-4]\n                val = np.load(val_path)\n                val_label = np.load(args.test_file + val_name + \"_label.npy\")\n\n                val=torch.Tensor(val).cuda(device=device).unsqueeze(0).unsqueeze(0)\n                val_label=torch.Tensor(val_label).cuda(device=device).unsqueeze(0).unsqueeze(0)\n\n                import time\n                time1 = time.time()\n                pred,flow=model(val,atlas)\n                pred_img = STN(val.shape[2:], val, flow, mode=\"bilinear\")\n                time = time.time()-time1\n                print(time)\n                Time.append(time)\n                flow_per = flow.permute(0, 2, 3, 4, 1)\n                flow_per = flow_per.squeeze(0).detach().cpu()\n                #np.save(\"/home/songlei/flow.npy\",flow_per)\n\n                jac = jacobian_determinant1(flow_per)\n                jac = jac.squeeze()\n                jac_neg_per = np.sum([i <= 0 for i in jac])\n                JAC.append(jac_neg_per)\n\n\n                pred_label=STN(val_label.shape[2:],val_label,flow)\n                pred_label=pred_label.squeeze(0).squeeze(0).detach().cpu().numpy()\n                acc=dice(atlas_label,pred_label,labels)\n                Dice.append(acc)\n\n                print(\"dice: \", acc)\n                print(\"Jac:\", jac_neg_per,\"\\n\")\n    print(\"DICE:\", np.mean(Dice), \"std:\", np.std(Dice))\n    print(\"JAC:\", np.mean(JAC), \"std:\", np.std(JAC))\n    print(\"Time:\", np.mean(Time), \"std:\", np.std(Time))\n\n\n\ndef STN(size, src, flow, mode='nearest'):\n    device = torch.device('cuda:{}'.format(args.gpu) if torch.cuda.is_available() else 'cpu')\n    vectors = [torch.arange(0, s) for s in size]\n    grids = torch.meshgrid(vectors)\n    grid = torch.stack(grids)  # y, x, z\n    grid = torch.unsqueeze(grid, 0)  # add batch\n    grid = grid.type(torch.FloatTensor).to(device)\n\n    # print(size)\n\n    new_locs = grid + flow\n    # print(new_locs.shape)\n    # print(\"new_locs.mean : {}\".format(new_locs.mean()))\n    # print(\"new_locs.shape: {}\".format(new_locs.shape))\n    shape = flow.shape[2:]\n\n    for i in range(len(shape)):\n        new_locs[:, i, ...] = 2 * ((new_locs[:, i, ...] / (shape[i] - 1) - 0.5))\n\n    if len(shape) == 2:\n        new_locs = new_locs.permute(0, 2, 3, 1)\n        new_locs = new_locs[..., [1, 0]]  # 最里边这一维的第一列和第0列的数据\n    elif len(shape) == 3:\n        new_locs = new_locs.permute(0, 2, 3, 4, 1)\n        # print(\"new_locs_origin.shape : {}\".format(new_locs.shape))\n        new_locs = new_locs[..., [2, 1, 0]]\n        # print(\"new_locs.shape : {}\".format(new_locs.shape))\n        new_locs_construct = new_locs\n    #     print(\"new_locs_construct max : {}  min: {}  mean : {}\".format(new_locs_construct.max(),new_locs_construct.min(),new_locs_construct.mean()))\n    # print(\"new_locs' mean: {} ,min: {},max: {}\".format(new_locs_construct.mean(),new_locs_construct.min(),new_locs_construct.max()))\n    return nnf.grid_sample(src, new_locs_construct, align_corners=True, mode=mode)\n\ndef dice(array1, array2, labels):\n    \"\"\"\n    Computes the dice overlap between two arrays for a given set of integer labels.\n    \"\"\"\n    dicem = np.zeros(len(labels))\n    for idx, label in enumerate(labels):\n        top = 2 * np.sum(np.logical_and(array1 == label, array2 == label))\n        bottom = np.sum(array1 == label) + np.sum(array2 == label)\n        bottom = np.maximum(bottom, np.finfo(float).eps)  # add epsilon\n        dicem[idx] = top / bottom\n    return np.mean(dicem)\nimport pystrum.pynd.ndutils as nd\ndef jacobian_determinant1(disp):\n    \"\"\"\n    jacobian determinant of a displacement field.\n    NB: to compute the spatial gradients, we use np.gradient.\n\n    Parameters:\n        disp: 2D or 3D displacement field of size [*vol_shape, nb_dims],\n              where vol_shape is of len nb_dims\n\n    Returns:\n        jacobian determinant (scalar)\n    \"\"\"\n\n    # check inputs\n    volshape = disp.shape[:-1]\n    nb_dims = len(volshape)\n    assert len(volshape) in (2, 3), 'flow has to be 2D or 3D'\n\n    # compute grid\n    grid_lst = nd.volsize2ndgrid(volshape)\n    grid = np.stack(grid_lst, len(volshape))\n\n    # compute gradients\n    J = np.gradient(disp + grid)\n\n    # 3D glow\n    if nb_dims == 3:\n        dx = J[0]\n        dy = J[1]\n        dz = J[2]\n\n        # compute jacobian components\n        Jdet0 = dx[..., 0] * (dy[..., 1] * dz[..., 2] - dy[..., 2] * dz[..., 1])\n        Jdet1 = dx[..., 1] * (dy[..., 0] * dz[..., 2] - dy[..., 2] * dz[..., 0])\n        Jdet2 = dx[..., 2] * (dy[..., 0] * dz[..., 1] - dy[..., 1] * dz[..., 0])\n\n        return Jdet0 - Jdet1 + Jdet2\n\n    else: # must be 2\n\n        dfdx = J[0]\n        dfdy = J[1]\n\n        return dfdx[..., 0] * dfdy[..., 1] - dfdy[..., 0] * dfdx[..., 1]\nif __name__ == \"__main__\":\n    test()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "9df1f5766ffea6a5e9d1e2411d8fb0e6a311926c", "size": 6568, "ext": "py", "lang": "Python", "max_stars_repo_path": "test.py", "max_stars_repo_name": "SLKaMiHi/ResT-UNet-unsupervised-medical-image-registration-network-based-on-Transformer-and-CNN", "max_stars_repo_head_hexsha": "728624f978f345a1e713046a7dde12d6f84fd3dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-11T06:46:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T06:46:43.000Z", "max_issues_repo_path": "test.py", "max_issues_repo_name": "SLKaMiHi/ResT-UNet-unsupervised-medical-image-registration-network-based-on-Transformer-and-CNN", "max_issues_repo_head_hexsha": "728624f978f345a1e713046a7dde12d6f84fd3dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test.py", "max_forks_repo_name": "SLKaMiHi/ResT-UNet-unsupervised-medical-image-registration-network-based-on-Transformer-and-CNN", "max_forks_repo_head_hexsha": "728624f978f345a1e713046a7dde12d6f84fd3dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6766169154, "max_line_length": 164, "alphanum_fraction": 0.5857186358, "include": true, "reason": "import numpy", "num_tokens": 1877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3140505321516081, "lm_q1q2_score": 0.1753428896856322}}
{"text": "import numpy as np\nimport pandas as pd\nfrom datetime import datetime\n\n\ndef string_date(mnthDay, year):\n    \"\"\"Return a string date as 'mm/dd/yyyy'.\n\n       Argument format:\n       'mm/dd' string\n       'yyyy'\"\"\"\n    return(mnthDay + '/' + str(year))\n\n\nclass TouRate(object):\n    \"\"\"Object for Utility Time Of Use Tariff.\n\n    Class for a utilty time of use tariff structure.  TouRate provides\n    methods to slice a dataframe with an year long hourly datetime axis (8760)\n    by the time periods defined by a time of use (TOU) utility rate.\n\n    Instance Variables:\n    year - integer year for the anlaysis; the year effects holidays\n    cal - an instance of pandas holiday calendar\n    deliveryPrice - float price for the base elec. price ($/kWh)\n    periods - dictionary defining the time of use periods\n\n    Periods dict format days dict can be empty\n    SCE_TOU_GS_2 = {'holWkndsWinter': {'dates': ('10/01', '5/31'),\n                                    'times': ('00:00', '23:00'),\n                                    'days': {'dropHol': True, 'dropWknd': True, 'inverse': True},\n                                    'price': 0.04064}\n                   }\n\n    Methods:\n    spans_year - returns bool indicating if tou period spans calendar year\n    filter_days - Returns dataframe without holidays or weekends or inverse\n    get_period - Returns dataframe with only hours and days from the give tou period\n    get_all_periods - Returns dataframe with a column for each tou period.\n    get_rates - Returns dataframe with TOU period rates from TouRate object.\n\n    \"\"\"\n    def __init__(self,\n                 year,\n                 cal,\n                 deliveryPrice,\n                 periods={}):\n\n        self.year = year\n        self.cal = cal\n        self.deliveryPrice = deliveryPrice\n        self.periods = periods\n\n    def spans_year(self, key):\n        \"\"\"Returns bool indicating spanning calendar year end.\n\n        Arguments:\n        dict key (string) for the TOU period to check\n        \"\"\"\n        startDate = string_date(self.periods[key]['dates'][0], self.year)\n        endDate = string_date(self.periods[key]['dates'][1], self.year)\n        startDay = pd.date_range(startDate, periods=1).dayofyear\n        endDay = pd.date_range(endDate, periods=1).dayofyear\n        return(endDay[0] - startDay[0] < 0)\n\n    def filter_days(self, df, dropWknd=True, dropHol=True, inverse=False):\n        \"\"\"Returns dataframe without holidays or weekends or inverse.\n\n        Arguments:\n        df - dataframe of energy production (hourly)\n\n        Keyword arguments:\n        dropWknd=bool  default is True\n        dropHol=bool, default is True\n        inverse=bool, default is False\n        \"\"\"\n        # create function to check this and return error?\n        # if df.index.date[0].year == self.year:\n        df_int = pd.DataFrame()\n        if df_int.empty:\n            if dropWknd & dropHol:\n                df_int = df.loc[~np.in1d(df.index.date, df.index[df.index.weekday > 4].date)]\n                holExcp = self.cal.holidays(datetime(self.year, 1, 1), datetime(self.year, 12, 31), return_name=False)\n                df_int = df_int.loc[~np.in1d(df_int.index.date, holExcp.date)]\n            elif dropWknd:\n                df_int = df.loc[~np.in1d(df.index.date, df.index[df.index.weekday > 4].date)]\n            elif dropHol:\n                holExcp = self.cal.holidays(datetime(self.year, 1, 1), datetime(self.year, 12, 31), return_name=False)\n                df_int = df.loc[~np.in1d(df.index.date, holExcp.date)]\n            else:\n                df_int = df\n\n        if inverse:\n            return(df.loc[~np.in1d(df.index.date, df_int.index.date)])\n        else:\n            return(df_int)\n\n    def get_period(self, df, key):\n        \"\"\"Returns dataframe with only hours and days from the give tou period.\n\n        Arguments:\n        df - dataframe of hourly energy production data\n        key - dict key of TOU period defined in the\n        \"\"\"\n        daysFiltered = self.filter_days(df, **self.periods[key]['days'])\n        perStart = string_date(self.periods[key]['dates'][0], df.index[0].date().year)\n        perEnd = string_date(self.periods[key]['dates'][1], df.index[0].date().year)\n        if self.spans_year(key):\n            # slice period for beginning of the year\n            fall = daysFiltered.ix[perStart:string_date('12/31', df.index[0].date().year)]\n            fall = fall.between_time(self.periods[key]['times'][0], self.periods[key]['times'][1])\n            fall = fall.sort_index()\n            # slice period for end of the year\n            spring = fall.append(daysFiltered.ix[string_date('1/1', df.index[0].date().year):perEnd])\n            spring = spring.between_time(self.periods[key]['times'][0], self.periods[key]['times'][1])\n            spring = spring.sort_index()\n            return(spring.rename_axis({'data': key}, axis=1))\n        else:\n            df_temp = daysFiltered.ix[perStart:perEnd]\n            df_temp = df_temp.between_time(self.periods[key]['times'][0], self.periods[key]['times'][1])\n            return(df_temp.rename_axis({'data': key}, axis=1))\n\n    def get_all_periods(self, df):\n        \"\"\"Returns dataframe with a column for each tou period.\n\n        Arguments:\n        df - dataframe of hourly energy production data\n        \"\"\"\n        df_append = pd.DataFrame()\n        for index, element in enumerate(self.periods):\n            df_temp = self.get_period(df, element)\n            df_append = df_append.append(df_temp)\n        return(df_append.sort_index())\n\n    def get_rates(self):\n        \"\"\"Returns dataframe with TOU period rates from TouRate object.\"\"\"\n        rates = np.empty(len(self.periods))\n        for index, element in enumerate(self.periods):\n            rates[index] = self.periods[element]['price']\n        return(pd.Series(rates, self.periods.keys()))\n\n    def get_summary(self, df):\n        \"\"\"Returns datafame with summary TOU data of input dataframe.\n\n        Arguments:\n        df - dataframe of hourly energy production data\n        \"\"\"\n        results_df = pd.DataFrame({'Energy kWh': self.get_all_periods(df).sum()})\n        results_df['Prices $/kWh'] = self.deliveryPrice + self.get_rates()\n        results_df['Value $'] = results_df['Energy kWh'] * results_df['Prices $/kWh']\n        return(results_df)\n\n\"\"\"\n    def check_times(self):\n        \"\"Returns df with TOU period rates from TouRate object.\n        No arguments required\n        \"\"\n        for index, element in enumerate(self.periods):\n            if index == 0:\n                season = self.periods[element]['date']\n            elif season = self.periods[element]['date']\n                start_times = pd.Series(index=np.arange(len(self.periods)))\n                end_times = pd.Series(index=np.arange(len(self.periods)))\n                for index, element in enumerate(self.periods):\n                    start_times[index] = int(self.periods[element]['times'][0][0:2])\n                    end_times[index] = int(self.periods[element]['times'][1][0:2])\n\n        return(start_times, end_times)\n        #return(pd.Series(rates, self.periods.keys()))\n\"\"\"\n", "meta": {"hexsha": "d11e588108faf03145b0a1b97a7f1c47b5cd5353", "size": 7108, "ext": "py", "lang": "Python", "max_stars_repo_path": "tou.py", "max_stars_repo_name": "bt-/tou", "max_stars_repo_head_hexsha": "b53e88367afeaa44a2da98d9188fc886683c096a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tou.py", "max_issues_repo_name": "bt-/tou", "max_issues_repo_head_hexsha": "b53e88367afeaa44a2da98d9188fc886683c096a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tou.py", "max_forks_repo_name": "bt-/tou", "max_forks_repo_head_hexsha": "b53e88367afeaa44a2da98d9188fc886683c096a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.567251462, "max_line_length": 118, "alphanum_fraction": 0.6036859876, "include": true, "reason": "import numpy", "num_tokens": 1629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.32766830082071396, "lm_q1q2_score": 0.17533479287991588}}
{"text": "def create_rois(image, size_thresh, method_thresh, closing, scale_factor):\n    '''\n    Main entry-point function for generating ROIs automatically. \n    Does thresholding, clever merging of intersecting ROIs and ordering left-right-top-bottom.\n\n            Parameters:\n                    image (np.array): 3-dimensional (2d + RGB) numpy array with pixel data for retrieved jpeg from OMERO\n                    size_thresh (num): Minimum size (in full-resolution pixels) for an ROI to be considered an ROI\n                    method_thresh (str): Thresholding method. Current options are 'otsu', 'triangle', 'yen' and 'li'.\n                    closing (int): radius for the diamond-shaped structuring element used for closing operation.\n                    scale_factor (int): scaling that was used to generate the downsampled image. Used to re-scale minimum size threshold.\n\n            Returns:\n                    regions (list): list of pruned, ordered tuples of the form (y1,x1,y2,x2) representing the ROIs to be saved back to OMERO.\n    '''\n    from skimage.color import rgb2gray\n    from skimage.filters import threshold_otsu, threshold_triangle, threshold_yen, threshold_li\n    from skimage.util import invert\n    from skimage.morphology import diamond, binary_closing\n    from skimage.measure import regionprops, label\n    import numpy as np\n\n\n    # we're assuming the image is RGB and dark features on light background\n    im = rgb2gray(image)\n    im = invert(im)\n    \n    # ugly thresholding choice here - I'm assuming the inputs to be well-behaved\n    if method_thresh == 'otsu':\n        im_thresh = im > threshold_otsu(im)\n    elif method_thresh == 'triangle':\n        im_thresh = im > threshold_triangle(im)\n    elif method_thresh == 'yen':\n        im_thresh = im > threshold_yen(im)\n    elif method_thresh == 'li':\n        im_thresh = im > threshold_li(im)\n\n    # do a bit of closing to already merge regions that are almost touching\n    # how much? up to you, it's an input parameter\n    im_thresh = binary_closing(im_thresh, diamond(closing))\n    im_lab = label(im_thresh)\n\n    # get rid of ROIs smaller than required size threshold\n    for i in range(1, im_lab.max()+1):\n        coords = np.where(im_lab == i)\n        if len(coords[0]) < (size_thresh / (scale_factor ** 2)):\n            im_lab[coords] = 0\n      \n    regionproperties = regionprops(im_lab)\n    regions = []\n\n    # at least for now we only care about the bounding boxes for ROIs\n    for r in regionproperties:\n        regions.append(r.bbox)\n    regions = prune_regions(regions)\n    regions = order_regions(regions)\n    #return []\n    return regions\n\ndef distance(p1, p2):\n    '''\n    Basic L2 distance. I will not bother writing a detailed docstring for this.\n    '''\n\n    import numpy as np\n    d = np.sqrt(((p2[0] - p1[0]) ** 2) + ((p2[1] - p1[1]) ** 2))\n    return d\n\ndef weighted_distance(p1, p2, weight):\n    '''\n    Weighted L2 distance where Y difference is multiplied by a weight. \n    We want discrepancies in Y to be magnified to be able to detect lines.\n    '''\n    import numpy as np\n    d = np.sqrt(((p2[0] - p1[0]) ** 2) + ((weight * (p2[1] - p1[1])) ** 2))\n    return d\n\ndef generate_centroids(regions):\n    '''\n    Generate centroids of the region bounding boxes. \n\n    Parameters:\n                    regions (list): tuples of the form (y1,x1,y2,x2) representing the ROI bounding boxes\n                    \n            Returns:\n                    centroids (list): list of tuples of the form (X, Y) with centroids (because I hate the original tuple coordinate ordering)\n                                    \n    '''\n   \n    centroids = []\n    if regions != []:\n        for region in regions:\n            centroids.append(((region[1]+ region[3])/2, (region[0]+ region[2])/2))\n    return centroids\n\ndef order_regions(regions):\n    '''\n    This function is an absolute nightmare that will require a lot of in-line commenting to make any sense of. But basically it gets\n    a list of region bounding boxes and returns the same list, but ordered left-right and top-bottom (i.e. writing order). \n\n    Parameters:\n                    regions (list): tuples of the form (y1,x1,y2,x2) representing the ROI bounding boxes\n                    \n            Returns:\n                    a mess (list): also tuples of the form (y1,x1,y2,x2) representing the ROI bounding boxes, but ordered\n                                    \n    '''\n\n\n    import numpy as np\n    if regions != []:\n        \n        #while regions != []:\n        centroids = generate_centroids(regions)\n\n        # detecting top-left ROI: lowest sum of coordinates\n        sums = [c[0]+c[1] for c in centroids]\n        topleft = sums.index(min(sums))\n        # I won't need to order that one (it's the first), so I get rid of it\n        c_topleft = centroids[topleft]\n        r_topleft = regions[topleft]\n        regions.remove(r_topleft)\n        centroids.remove(c_topleft)\n\n        # calculate weighted distances to the top left ROI, where Y distances are weighted at\n        # 20 (!!!) times the X distances - this sucks and I still can't figure out a better way to \n        # make sure I'm getting lines correctly!\n        dists = [weighted_distance(x,c_topleft,20) for x in centroids]\n        \n        # basically I sort everything based on the weighted distances\n        # If I did things right, the first elements are on the top line, then there's a big\n        # jump in weighted distances, then second line, big jump, third line, and so on\n        centroids = [x for _,x in sorted(zip(dists,centroids))]\n        regions = [x for _,x in sorted(zip(dists,regions))]\n        dists = [x for x in sorted(dists)]\n\n        # detecting \"big jumps\" as anything bigger than 1.5 times the st dev of differences\n        differences = [dists[i+1]-dists[i] for i in range(len(dists)-1)]\n        line_dividers = differences > 1.5*np.std(differences)\n        line_dividers = np.insert(line_dividers,0,False)\n\n\n        # create list of lists where each element is a list containing a line of ROIs\n        lines = []\n        lines.append([r_topleft])\n        for i in range(len(regions)):\n            if line_dividers[i]:\n                lines.append([])\n            lines[-1].append(regions[i])\n            \n        results = []\n\n        # sort each line left-to-right by comparing x values\n        for line in lines:\n            line_centr = generate_centroids(line)\n            xvals = [x[0] for x in line_centr]  \n            results.append([x for _,x in sorted(zip(xvals,line))])  \n\n        # return statement is just unraveling the list of lists as a single list\n        return [item for sublist in results for item in sublist]\n    else:\n        return []\n\ndef prune_regions(regions):\n    '''\n    Get rid of any regions with aspect ratios bigger than 4. Why 4? Good question.\n    '''\n    restart = True\n    while restart:\n        restart = False\n        for region in regions:   \n            if check_aspect_ratio(region, 4):\n                regions.remove(region)\n                restart = True\n                break\n            \n    regions = cluster_regions(regions)\n    \n  \n    return(regions)\n\n\ndef cluster_regions(regions):\n\n    '''\n    This function does some clever graph stuff to merge ROIs hierarchically based on intersection areas. By defining merge \n    priorities a priori instead of iteratively, we get really good quality ROIs that can even overlap without becoming a single\n    huge bounding box.\n\n    Parameters:\n                    regions (list): tuples of the form (y1,x1,y2,x2) representing the ROI bounding boxes\n                    \n            Returns:\n                    results (list): also tuples of the form (y1,x1,y2,x2) (but fewer of them) representing the ROI bounding boxes, but merged\n                                    \n    '''\n    import networkx as nx\n    willmerge = []\n    mergee = []\n    results = []\n\n    # we do a pass through all regions and generate two new lists: a boolean saying whether that region needs merging\n    # (i.e. it intersects with another one) and an integer one with the index of the region that should be merged with\n    # that one\n    for region in regions:\n        intersection = check_intersections(region,regions)\n        if intersection != -1:\n            willmerge.append(True)\n            mergee.append(intersection)\n            \n    # if a region doesn't have intersections, go ahead and add it to the results list        \n        else:\n            willmerge.append(False)\n            mergee.append(intersection)\n            results.append(region)\n    \n    # create a graph and add an edge for each combination of regions that need to be merged.\n    G = nx.Graph()\n    edges = []\n    count = 0\n    for roi in range(len(mergee)):\n        if willmerge[count] == True:\n            edges.append((count,mergee[count]))\n        count = count + 1\n    G.add_edges_from(edges)\n\n\n    # the resulting graph will have one connected component per final ROI, and the final ROI is the bounding box\n    # around all ROIs in this connected component\n    for a in nx.connected_components(G):\n        roi = merge_cluster(list(a), regions)\n        results.append(roi)\n    \n    return results\n\n\ndef merge_cluster(indices, regions):\n    '''\n    Generate a bounding box around all ROIs with given indices on the list of regions (also given)\n    '''\n    region = regions[indices[0]]\n    for i in range(1,len(indices)):\n        region = merge_regions(region, regions[indices[i]])\n    return region\n\ndef check_aspect_ratio(region, threshold):\n    '''\n    Simple binary check to see whether a bounding box exceeds a threshold aspect ratio. True means ROI is very elongated.\n    '''\n    bbox = region\n    ratio = (bbox[2]-bbox[0])/(bbox[3]-bbox[1])\n    if ratio > threshold or ratio < (1/threshold):\n        return True\n\ndef check_intersections(region, regions):\n    '''\n    Calculates intersection areas between a region and all other regions and returns the index of the maximum intersection area.\n\n    Parameters:\n                    regions (list): tuples of the form (y1,x1,y2,x2) representing the ROI bounding boxes\n                    region (tuple): tuple of the form (y1,x1,y2,x2) representing the ROI to be checked against all others\n                    \n            Returns:\n                    index (int): index of the maximum intersection area ROI on the regions list\n                                    \n    '''\n    int_areas = []\n    bbox = region\n    for r in regions:\n        r_bbox = r\n        \n        # the current region being checked is always on the regions list, so we ignore it\n        if (r_bbox == bbox):\n            int_areas.append(0)\n\n            continue\n        if bbox[0] >= r_bbox[2] or r_bbox[0] >= bbox[2]:\n            int_areas.append(0) \n            continue\n        if bbox[1] >= r_bbox[3] or r_bbox[1] >= bbox[3]:\n            int_areas.append(0) \n            continue\n\n        # magical code that gives us coordinates for the intersection bounding box\n        y1 = max(min(bbox[0],r_bbox[2]), min(r_bbox[0],bbox[2]))\n        x1 = max(min(bbox[1],r_bbox[3]), min(r_bbox[1],bbox[3]))\n        y2 = min(max(bbox[0],r_bbox[2]), max(r_bbox[0],bbox[2]))\n        x2 = min(max(bbox[1],r_bbox[3]), max(r_bbox[1],bbox[3]))\n\n        # we add the area of intersection to the int_areas list\n        if (x2 > x1) and (y2 > y1):\n            int_areas.append((x2-x1)*(y2-y1))\n        else:\n            int_areas.append(0)\n\n    # return -1 if there is no intersection (returning 0 is a bad idea because 0 is a valid index)\n    if max(int_areas) == 0:\n        return -1\n    else:\n    # otherwise, return index of maximum intersection area\n        return int_areas.index(max(int_areas)) \n\n\ndef merge_regions(region,other):\n    '''\n    Simple magic code that generates a bounding box that is the union of two bounding boxes.\n    '''\n    y1 = min(region[0],other[0])\n    x1 = min(region[1], other[1])\n    y2 = max(region[2], other[2])\n    x2 = max(region[3], other[3])\n    \n    return (y1,x1,y2,x2) \n\n\n\n# just some sample code if you want to run the whole workflow standalone\n\nif __name__ == \"__main__\":\n    import os\n    import argparse\n    import sys\n\n    from create_session import create_json_session, create_blitz_session\n    from retrieve_image import retrieve_image, get_image\n    from save_rois import save_rois\n    \n    parser = argparse.ArgumentParser()\n    parser.add_argument('--rerun',\n                        dest='rerun',\n                        action='store_true',\n                        help='Set this flag if it is a rerun (WILL delete ALL existing ROIs)')\n    args = parser.parse_args(sys.argv[1:])\n\n    WEB_HOSTNAME = os.environ['OMERO_WEB_HOSTNAME']\n    HOSTNAME = os.environ['OMERO_HOSTNAME']\n    USERNAME = os.environ['OMERO_ADMIN_USER']\n    PASSWORD = os.environ['OMERO_ADMIN_PASSWORD']\n    img_id = 4\n    scale_factor = 64\n    login_rsp, session, base_url = create_json_session(WEB_HOSTNAME, USERNAME, PASSWORD, verify=False)\n    img = retrieve_image(session, base_url, img_id, scale_factor)\n    regions = create_rois(img, 200, 'triangle', 5, scale_factor)\n    conn = create_blitz_session(HOSTNAME, USERNAME, PASSWORD)\n    image = get_image(conn, img_id)\n    save_rois(image, regions, scale_factor, args.rerun)\n    conn.close()", "meta": {"hexsha": "2393c76419675829aa3b681b91be0d3c5403b6d5", "size": 13264, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/create_rois.py", "max_stars_repo_name": "TheJacksonLaboratory/detect_rois_omero", "max_stars_repo_head_hexsha": "6add7770b0d1cabac8c3d234e036fadefb5ede3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/create_rois.py", "max_issues_repo_name": "TheJacksonLaboratory/detect_rois_omero", "max_issues_repo_head_hexsha": "6add7770b0d1cabac8c3d234e036fadefb5ede3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/create_rois.py", "max_forks_repo_name": "TheJacksonLaboratory/detect_rois_omero", "max_forks_repo_head_hexsha": "6add7770b0d1cabac8c3d234e036fadefb5ede3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2247838617, "max_line_length": 142, "alphanum_fraction": 0.6224366707, "include": true, "reason": "import numpy,import networkx", "num_tokens": 3099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.17533479287991585}}
{"text": "# Copyright 2018 The Cirq Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"A protocol for implementing high performance unitary left-multiplies.\"\"\"\n\n\nfrom typing import Any, Union, Sequence, TypeVar\n\nimport numpy as np\nfrom typing_extensions import Protocol\n\nfrom cirq import linalg\nfrom cirq.protocols.unitary import unitary\nfrom cirq.type_workarounds import NotImplementedType\n\n\n# This is a special indicator value used by the apply_unitary_to_tensor method\n# to determine whether or not the caller provided a 'default' argument. It must\n# be of type np.ndarray to ensure the method has the correct type signature in\n# that case. It is checked for using `is`, so it won't have a false positive if\n# the user provides a different np.array([]) value.\n\nRaiseTypeErrorIfNotProvided = np.array([])  # type: np.ndarray\n\nTDefault = TypeVar('TDefault')\n\n\nclass SupportsApplyUnitaryToTensor(Protocol):\n    \"\"\"An object that can be efficiently left-multiplied into tensors.\"\"\"\n\n    def _apply_unitary_to_tensor_(self,\n                                  target_tensor: np.ndarray,\n                                  available_buffer: np.ndarray,\n                                  axes: Sequence[int],\n                                  ) -> Union[np.ndarray, NotImplementedType]:\n        \"\"\"Left-multiplies a unitary effect onto a tensor with good performance.\n\n        This method is given both the target tensor and workspace of the same\n        shape and dtype. The method then either performs inline modifications of\n        the target tensor and returns it, or writes its output into the\n        workspace tensor and returns that. This signature makes it possible to\n        write specialized simulation methods that run without performing large\n        allocations, significantly increasing simulation performance.\n\n        The target may represent a wavefunction, a unitary matrix, or some other\n        tensor. Implementations will work in all of these cases as long as they\n        correctly focus on only operating on the given axes.\n\n        Args:\n            target_tensor: The input tensor that needs to be left-multiplied by\n                the unitary effect of the receiving object. The tensor will\n                have the shape (2, 2, 2, ..., 2). It usually corresponds to\n                a multi-qubit superposition, but it could also be a multi-qubit\n                unitary transformation or some other concept.\n            available_buffer: Pre-allocated workspace with the same shape and\n                dtype as the target tensor.\n            axes: Which axes the unitary effect is being applied to (e.g. the\n                qubits that the gate is operating on).\n\n        Returns:\n            If the receiving object is not able to apply its unitary effect,\n            NotImplemented should be returned.\n\n            If the receiving object is able to work inline, it should directly\n            mutate target_tensor and then return target_tensor. The caller will\n            understand this to mean that the result is in target_tensor.\n\n            If the receiving object is unable to work inline, it can write its\n            output over available_buffer and then return available_buffer. The\n            caller will understand this to mean that the result is in\n            available_buffer (and so what was available_buffer will become\n            target_tensor in the next call, and vice versa).\n\n            The receiving object is also permitted to allocate a new\n            numpy.ndarray and return that as its result.\n        \"\"\"\n\n\ndef apply_unitary_to_tensor(val: Any,\n                            target_tensor: np.ndarray,\n                            available_buffer: np.ndarray,\n                            axes: Sequence[int],\n                            default: TDefault = RaiseTypeErrorIfNotProvided\n                            ) -> Union[np.ndarray, TDefault]:\n    \"\"\"High performance left-multiplication of a unitary effect onto a tensor.\n\n    If `val` defines an _apply_unitary_to_tensor_ method, that method will be\n    used to apply `val`'s unitary effect to the target tensor. Otherwise, if\n    `val` defines a _unitary_ method, its unitary matrix will be retrieved and\n    applied using a generic method. Otherwise the application fails, and either\n    an exception is raised or the specified default value is returned.\n\n        The target may represent a wavefunction, a unitary matrix, or some other\n        tensor. Implementations will work in all of these cases as long as they\n        correctly focus on only operating on the given axes. See also:\n        `cirq.slice_for_qubits_equal_to(axes, int)`, which does the correct\n        thing in all these cases.\n\n    Args:\n        val: The value with a unitary effect to apply to the target tensor.\n        target_tensor: The input tensor that needs to be left-multiplied by\n            the unitary effect of `val`. Note that this value may be mutated\n            inline into the output. The tensor will have the shape\n            (2, 2, 2, ..., 2). target_tensor may correspond to a multi-qubit\n            superposition (with each axis being a qubit), a multi-qubit unitary\n            transformation (with some axes being qubit inputs and others being\n            qubit outputs), or some other concept.\n        available_buffer: Pre-allocated workspace with the same shape and\n            dtype as the target tensor. Note that the output may be written\n            into this buffer.\n        axes: Which axes the unitary effect is being applied to (e.g. the\n            qubits that the gate is operating on). For example, a CNOT being\n            applied to qubits #4 and #2 of a circuit would result in\n            axes=(4, 2).\n        default: What should be returned if `val` doesn't have a unitary effect.\n            If not specified, a TypeError is raised instead of returning\n            a default value.\n\n    Returns:\n        If the receiving object is not able to apply its unitary effect,\n        the specified default value is returned (or a TypeError is raised).\n\n        If the receiving object was able to work inline, directly\n        mutating target_tensor it will return target_tensor. The caller is\n        responsible for checking if the result is target_tensor.\n\n        If the receiving object wrote its output over available_buffer, the\n        result will be available_buffer. The caller is responsible for\n        checking if the result is available_buffer (and e.g. swapping\n        the buffer for the target tensor before the next call).\n\n        The receiving object may also write its output over a new buffer\n        that it created, in which case that new array is returned.\n\n    Raises:\n        TypeError: `val` doesn't have a unitary effect and `default` wasn't\n            specified.\n    \"\"\"\n\n    # Check if the specialized method is present.\n    getter = getattr(val, '_apply_unitary_to_tensor_', None)\n    if getter is not None:\n        result = getter(target_tensor, available_buffer, axes)\n        if result is not NotImplemented:\n            return result\n\n    # Fallback to using the object's _unitary_ matrix.\n    matrix = unitary(val, None)\n    if matrix is not None:\n        # Special case for single-qubit operations.\n        if matrix.shape == (2, 2):\n            zero = linalg.slice_for_qubits_equal_to(axes, 0)\n            one = linalg.slice_for_qubits_equal_to(axes, 1)\n            return linalg.apply_matrix_to_slices(target_tensor,\n                                                 matrix,\n                                                 [zero, one],\n                                                 out=available_buffer)\n\n        # Fallback to np.einsum for the general case.\n        return linalg.targeted_left_multiply(\n            matrix.astype(target_tensor.dtype).reshape((2,) * (2 * len(axes))),\n            target_tensor,\n            axes,\n            out=available_buffer)\n\n    # Don't know how to apply. Fallback to specified default behavior.\n    if default is not RaiseTypeErrorIfNotProvided:\n        return default\n    raise TypeError(\"object of type '{}' \"\n                    \"has no _apply_unitary_to_tensor_ \"\n                    \"or _unitary_ methods \"\n                    \"(or they returned NotImplemented).\".format(type(val)))\n", "meta": {"hexsha": "b752a7792da07114a21cf3ce9242be6263df5ac1", "size": 8802, "ext": "py", "lang": "Python", "max_stars_repo_path": "cirq/protocols/apply_unitary_to_tensor.py", "max_stars_repo_name": "sleichen/Cirq", "max_stars_repo_head_hexsha": "02f715203406d1f2af2d86e7561af09a2cdd4d45", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-20T00:08:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-20T00:08:33.000Z", "max_issues_repo_path": "cirq/protocols/apply_unitary_to_tensor.py", "max_issues_repo_name": "sleichen/Cirq", "max_issues_repo_head_hexsha": "02f715203406d1f2af2d86e7561af09a2cdd4d45", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cirq/protocols/apply_unitary_to_tensor.py", "max_forks_repo_name": "sleichen/Cirq", "max_forks_repo_head_hexsha": "02f715203406d1f2af2d86e7561af09a2cdd4d45", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.8369565217, "max_line_length": 80, "alphanum_fraction": 0.6616678028, "include": true, "reason": "import numpy", "num_tokens": 1783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.32766829425520916, "lm_q1q2_score": 0.17533478936672459}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 23 12:11:15 2020\n\nModified from the cornstover biorefinery constructed in Cortes-Peña et al., 2020,\nwith modification of fermentation system for 2,3-Butanediol instead of the original ethanol\n\n[1] Cortes-Peña et al., BioSTEAM: A Fast and Flexible Platform for the Design, \n    Simulation, and Techno-Economic Analysis of Biorefineries under Uncertainty. \n    ACS Sustainable Chem. Eng. 2020, 8 (8), 3302–3310. \n    https://doi.org/10.1021/acssuschemeng.9b07040.\n\nAll units are explicitly defined here for transparency and easy reference\n\n@author: sarangbhagwat\n\"\"\"\n\n\n# %% \n\n# =============================================================================\n# Setup\n# =============================================================================\n\nimport numpy as np\nimport biosteam as bst\nfrom chaospy import distributions as shape\nfrom biosteam import main_flowsheet as find\nfrom biosteam.evaluation import Model, Metric\nfrom biosteam.evaluation.evaluation_tools.parameter import Setter\nfrom biorefineries.HP.system_light_lle_vacuum_distillation import process_groups_dict, HP_tea, HP_no_BT_tea,\\\nflowsheet, get_GWP, get_FEC, CFs, spec, process_groups, process_groups_dict,\\\nget_material_cost_breakdown, get_GWP_by_ID, get_FEC_by_ID, get_ng_GWP, get_ng_FEC,\\\nget_FGHTP_GWP, get_feedstock_FEC, get_electricity_demand_non_cooling_GWP, get_electricity_demand_non_cooling_FEC,\\\nget_direct_emissions_GWP, get_net_electricity_GWP, get_net_electricity_FEC,\\\nget_heating_demand_GWP, get_heating_demand_FEC,\\\nget_cooling_demand_GWP, get_cooling_demand_FEC, get_heating_demand_VOC, get_cooling_demand_VOC, get_electricity_demand_non_cooling_VOC, get_VOC\nfrom warnings import warn\n\nfind.set_flowsheet(flowsheet)\nget_annual_factor = lambda: 1.\n_kg_per_ton = 907.18474\n_feedstock_factor = _kg_per_ton / 0.8\n\nHP_sys = find.system.HP_sys\nBT_sys = find.system.BT_sys\nHXN = find.unit.HXN\n\nsystem_feeds = [i for i in HP_sys.feeds if i.price] + \\\n    [i for i in BT_sys.feeds if i.price]\nsystem_products = [i for i in HP_sys.products if i.price] + \\\n    [i for i in BT_sys.products if i.price]\n    \ngypsum = find.stream.gypsum\nsystem_products.append(gypsum)\n\n\n\nlock_yield = False\nlock_titer = False\nlock_productivity = False\n\n# %% \n\n# =============================================================================\n# Overall biorefinery metrics\n# =============================================================================\n\n# Minimum selling price of AA stream\ndef get_MSP():\n    # for i in range(3):\n        # aa_price = \n    return HP_tea.solve_price(AA)\n\n# Mass flow rate of HP stream\nAA = find.unit.T606_P-0\nfeedstock = find.stream.feedstock\nget_yield = lambda: AA.F_mass*get_annual_factor()/1e6\n# Purity (%) of HP in the final product\nget_purity = lambda: AA.imass['AA']/AA.F_mass\n# Adjust for purity\nget_adjusted_MSP = lambda: get_MSP() / get_purity()\nget_adjusted_yield = lambda: get_yield() * get_purity()\n# Recovery (%) = recovered/amount in fermentation broth\nR301 = find.unit.R301\nget_recovery = lambda: AA.imol['HP'] \\\n    /(R302.outs[0].imol['HP']+2*R302.outs[0].imol['CalciumLactate'])\nget_overall_TCI = lambda: HP_tea.TCI/1e6\n# Annual operating cost, note that AOC excludes electricity credit\nget_overall_AOC = lambda: HP_tea.AOC/1e6\nget_material_cost = lambda: HP_tea.material_cost/1e6\n# Annual sale revenue from products, note that electricity credit is not included,\n# but negative sales from waste disposal are included\n# (i.e., wastes are products of negative selling price)\nget_annual_sale = lambda: HP_tea.sales/1e6\n# System power usage, individual unit power usage should be positive\nBT = find.unit.BT\n# excess_power = lambda: BT.electricity_generated\nexcess_power = lambda: BT.power_utility.production\nelectricity_price = bst.PowerUtility.price\n# Electricity credit is positive if getting revenue from excess electricity\nget_electricity_credit = lambda: (excess_power()*electricity_price*get_annual_factor())/1e6\n\n\n#%% \nclass Metrics(list):\n    def __init__(self, metrics):\n        self.extend(metrics)\n        \n    def append(self, metric):\n        # self_copy = copy.deepcopy(self)\n        repeated = False\n        for i in self:\n            if i.index == metric.index:\n                repeated = True\n                break\n        if repeated:\n            warn(\"Metric {metric.index} already exists in Metrics object. Second instance has been deleted.\")\n        else:\n            super().append(metric)\n        \n    def extend(self,metrics):\n        for i in metrics:\n            self.append(i)\n#%%\n\nmetrics = Metrics([Metric('Minimum selling price', get_MSP, '$/kg'),\n           Metric('Product yield', get_yield, '10^6 kg/yr'),\n           Metric('Product purity', get_purity, '%'),\n            Metric('Adjusted minimum selling price', get_adjusted_MSP, '$/kg'),\n           Metric('Adjusted product yield', get_adjusted_yield, '10^6 kg/yr'),\n           Metric('Product recovery', get_recovery, '%'),\n           Metric('Total capital investment', get_overall_TCI, '10^6 $'),\n           Metric('Annual operating cost', get_overall_AOC, '10^6 $/yr'),\n           Metric('Annual material cost', get_material_cost, '10^6 $/yr'),\n           Metric('Annual product sale', get_annual_sale, '10^6 $/yr'),\n           Metric('Annual electricity credit', get_electricity_credit, '10^6 $/yr')\n           ])\n\n# %% Breakdowns by process groups\ndef get_group_heating_demand(group):\n    return sum([sum([hu.duty for hu in unit.heat_utilities if hu.duty*hu.flow>0.]) for unit in group.units])\n\ndef get_group_cooling_demand(group):\n    return sum([sum([hu.duty for hu in unit.heat_utilities if hu.duty*hu.flow<0.]) for unit in group.units])\n\n# Heating duty\n\nmetrics.extend((Metric('feedstock_group - heating demand',\n                       lambda: 0.001*sum([sum([hu.duty for hu in unit.heat_utilities \\\n                                               if hu.duty*hu.flow>0.]) for unit in \\\n                                          process_groups_dict['feedstock_group'].units])/AA.F_mass,\n                       'MJ/kg'),))\n\nmetrics.extend((Metric('pretreatment_group - heating demand',\n                       lambda: 0.001*sum([sum([hu.duty for hu in unit.heat_utilities \\\n                                               if hu.duty*hu.flow>0.]) for unit in \\\n                                          process_groups_dict['pretreatment_group'].units])/AA.F_mass,\n                       'MJ/kg'),))\n\nmetrics.extend((Metric('conversion_group - heating demand',\n                       lambda: 0.001*sum([sum([hu.duty for hu in unit.heat_utilities \\\n                                               if hu.duty*hu.flow>0.]) for unit in \\\n                                          process_groups_dict['conversion_group'].units])/AA.F_mass,\n                       'MJ/kg'),))\n\nmetrics.extend((Metric('separation_group - heating demand',\n                       lambda: 0.001*sum([sum([hu.duty for hu in unit.heat_utilities \\\n                                               if hu.duty*hu.flow>0.]) for unit in \\\n                                          process_groups_dict['separation_group'].units])/AA.F_mass,\n                       'MJ/kg'),))\n\nmetrics.extend((Metric('WWT_group - heating demand',\n                       lambda: 0.001*sum([sum([hu.duty for hu in unit.heat_utilities \\\n                                               if hu.duty*hu.flow>0.]) for unit in \\\n                                          process_groups_dict['WWT_group'].units])/AA.F_mass,\n                       'MJ/kg'),))\n\nmetrics.extend((Metric('HXN_group - heating demand',\n                       lambda: 0.001*sum([sum([hu.duty for hu in unit.heat_utilities \\\n                                               if hu.duty*hu.flow>0.]) for unit in \\\n                                          process_groups_dict['HXN_group'].units])/AA.F_mass,\n                       'MJ/kg'),))\n\nmetrics.extend((Metric('BT_group - heating demand',\n                       lambda: 0.001*sum([sum([hu.duty for hu in unit.heat_utilities \\\n                                               if hu.duty*hu.flow>0.]) for unit in \\\n                                          process_groups_dict['BT_group'].units])/AA.F_mass,\n                       'MJ/kg'),))\n\nmetrics.extend((Metric('CT_group - heating demand',\n                       lambda: 0.001*sum([sum([hu.duty for hu in unit.heat_utilities \\\n                                               if hu.duty*hu.flow>0.]) for unit in \\\n                                          process_groups_dict['CT_group'].units])/AA.F_mass,\n                       'MJ/kg'),))\n\nmetrics.extend((Metric('facilities_no_hu_group - heating demand',\n                       lambda: 0.001*sum([sum([hu.duty for hu in unit.heat_utilities \\\n                                               if hu.duty*hu.flow>0.]) for unit in \\\n                                          process_groups_dict['facilities_no_hu_group'].units])/AA.F_mass,\n                       'MJ/kg'),))\n\n# Cooling duty\n\nmetrics.extend((Metric('feedstock_group - cooling demand',\n                       lambda: 0.001*sum([sum([hu.duty for hu in unit.heat_utilities \\\n                                               if hu.duty*hu.flow<0.]) for unit in \\\n                                          process_groups_dict['feedstock_group'].units])/AA.F_mass,\n                       'MJ/kg'),))\n\nmetrics.extend((Metric('pretreatment_group - cooling demand',\n                       lambda: 0.001*sum([sum([hu.duty for hu in unit.heat_utilities \\\n                                               if hu.duty*hu.flow<0.]) for unit in \\\n                                          process_groups_dict['pretreatment_group'].units])/AA.F_mass,\n                       'MJ/kg'),))\n\nmetrics.extend((Metric('conversion_group - cooling demand',\n                       lambda: 0.001*sum([sum([hu.duty for hu in unit.heat_utilities \\\n                                               if hu.duty*hu.flow<0.]) for unit in \\\n                                          process_groups_dict['conversion_group'].units])/AA.F_mass,\n                       'MJ/kg'),))\n\nmetrics.extend((Metric('separation_group - cooling demand',\n                       lambda: 0.001*sum([sum([hu.duty for hu in unit.heat_utilities \\\n                                               if hu.duty*hu.flow<0.]) for unit in \\\n                                          process_groups_dict['separation_group'].units])/AA.F_mass,\n                       'MJ/kg'),))\n\nmetrics.extend((Metric('WWT_group - cooling demand',\n                       lambda: 0.001*sum([sum([hu.duty for hu in unit.heat_utilities \\\n                                               if hu.duty*hu.flow<0.]) for unit in \\\n                                          process_groups_dict['WWT_group'].units])/AA.F_mass,\n                       'MJ/kg'),))\n\nmetrics.extend((Metric('HXN_group - cooling demand',\n                       lambda: 0.001*sum([sum([hu.duty for hu in unit.heat_utilities \\\n                                               if hu.duty*hu.flow<0.]) for unit in \\\n                                          process_groups_dict['HXN_group'].units])/AA.F_mass,\n                       'MJ/kg'),))\n\nmetrics.extend((Metric('BT_group - cooling demand',\n                       lambda: 0.001*sum([sum([hu.duty for hu in unit.heat_utilities \\\n                                               if hu.duty*hu.flow<0.]) for unit in \\\n                                          process_groups_dict['BT_group'].units])/AA.F_mass,\n                       'MJ/kg'),))\n\nmetrics.extend((Metric('CT_group - cooling demand',\n                       lambda: 0.001*sum([sum([hu.duty for hu in unit.heat_utilities \\\n                                               if hu.duty*hu.flow<0.]) for unit in \\\n                                          process_groups_dict['CT_group'].units])/AA.F_mass,\n                       'MJ/kg'),))\n\nmetrics.extend((Metric('facilities_no_hu_group - cooling demand',\n                       lambda: 0.001*sum([sum([hu.duty for hu in unit.heat_utilities \\\n                                               if hu.duty*hu.flow<0.]) for unit in \\\n                                          process_groups_dict['facilities_no_hu_group'].units])/AA.F_mass,\n                       'MJ/kg'),))  \n\n\n# Installed equipment cost\n\nmetrics.extend((Metric('feedstock_group - installed equipment cost',\n                       lambda:process_groups_dict['feedstock_group'].get_installed_cost(),\n                       '10^6 $'),))\n\nmetrics.extend((Metric('pretreatment_group - installed equipment cost',\n                       lambda:process_groups_dict['pretreatment_group'].get_installed_cost(),\n                       '10^6 $'),))\n\nmetrics.extend((Metric('conversion_group - installed equipment cost',\n                       lambda:process_groups_dict['conversion_group'].get_installed_cost(),\n                       '10^6 $'),))\n\nmetrics.extend((Metric('separation_group - installed equipment cost',\n                       lambda:process_groups_dict['separation_group'].get_installed_cost(),\n                       '10^6 $'),))\n\nmetrics.extend((Metric('WWT_group - installed equipment cost',\n                       lambda:process_groups_dict['WWT_group'].get_installed_cost(),\n                       '10^6 $'),))\n\nmetrics.extend((Metric('HXN_group - installed equipment cost',\n                       lambda:process_groups_dict['HXN_group'].get_installed_cost(),\n                       '10^6 $'),))\n\nmetrics.extend((Metric('BT_group - installed equipment cost',\n                       lambda:process_groups_dict['BT_group'].get_installed_cost(),\n                       '10^6 $'),))\n\nmetrics.extend((Metric('CT_group - installed equipment cost',\n                       lambda:process_groups_dict['CT_group'].get_installed_cost(),\n                       '10^6 $'),))\n\nmetrics.extend((Metric('facilities_no_hu_group - installed equipment cost',\n                       lambda:process_groups_dict['facilities_no_hu_group'].get_installed_cost(),\n                       '10^6 $'),))  \n\n# Power utility demand\n\nmetrics.extend((Metric('feedstock_group - power utility demand',\n                       lambda:process_groups_dict['feedstock_group'].get_electricity_consumption()/AA.F_mass,\n                       'MW/kg'),))\n\nmetrics.extend((Metric('pretreatment_group - power utility demand',\n                       lambda:process_groups_dict['pretreatment_group'].get_electricity_consumption()/AA.F_mass,\n                       'MW/kg'),))\n\nmetrics.extend((Metric('conversion_group - power utility demand',\n                       lambda:process_groups_dict['conversion_group'].get_electricity_consumption()/AA.F_mass,\n                       'MW/kg'),))\n\nmetrics.extend((Metric('separation_group - power utility demand',\n                       lambda:process_groups_dict['separation_group'].get_electricity_consumption()/AA.F_mass,\n                       'MW/kg'),))\n\nmetrics.extend((Metric('WWT_group - power utility demand',\n                       lambda:process_groups_dict['WWT_group'].get_electricity_consumption()/AA.F_mass,\n                       'MW/kg'),))\n\nmetrics.extend((Metric('HXN_group - power utility demand',\n                       lambda:process_groups_dict['HXN_group'].get_electricity_consumption()/AA.F_mass,\n                       'MW/kg'),))\n\nmetrics.extend((Metric('BT_group - power utility demand',\n                       lambda:process_groups_dict['BT_group'].get_electricity_consumption()/AA.F_mass,\n                       'MW/kg'),))\n\nmetrics.extend((Metric('CT_group - power utility demand',\n                       lambda:process_groups_dict['CT_group'].get_electricity_consumption()/AA.F_mass,\n                       'MW/kg'),))\n\nmetrics.extend((Metric('facilities_no_hu_group - power utility demand',\n                       lambda:process_groups_dict['facilities_no_hu_group'].get_electricity_consumption()/AA.F_mass,\n                       'MW/kg'),))  \n\n# Material cost\n\nmetrics.extend((Metric('feedstock_group - material cost',\n                       lambda:get_material_cost_breakdown()['feedstock_group'],\n                       '$/kg'),))\n\nmetrics.extend((Metric('pretreatment_group - material cost',\n                       lambda:get_material_cost_breakdown()['pretreatment_group'],\n                       '$/kg'),))\n\nmetrics.extend((Metric('conversion_group - material cost',\n                       lambda:get_material_cost_breakdown()['conversion_group'],\n                       '$/kg'),))\n\nmetrics.extend((Metric('separation_group - material cost',\n                       lambda:get_material_cost_breakdown()['separation_group'],\n                       '$/kg'),))\n\nmetrics.extend((Metric('WWT_group - material cost',\n                       lambda:get_material_cost_breakdown()['WWT_group'],\n                       '$/kg'),))\n\nmetrics.extend((Metric('HXN_group - material cost',\n                       lambda:get_material_cost_breakdown()['HXN_group'],\n                       '$/kg'),))\n\nmetrics.extend((Metric('BT_group - material cost',\n                       lambda:get_material_cost_breakdown()['BT_group'],\n                       '$/kg'),))\n\nmetrics.extend((Metric('CT_group - material cost',\n                       lambda:get_material_cost_breakdown()['CT_group'],\n                       '$/kg'),))\n\nmetrics.extend((Metric('facilities_no_hu_group - material cost',\n                       lambda:get_material_cost_breakdown()['facilities_no_hu_group'],\n                       '$/kg'),))\n\n# =============================================================================\n# Material cost breakdown\n# =============================================================================\n\ndef get_material_cost(feed):\n    return lambda: feed.price*feed.F_mass*get_annual_factor()/1e6\nfor feed in system_feeds:\n    metrics.extend((Metric(feed.ID, get_material_cost(feed), '10^6 $/yr', 'Material cost'),))\nfermentation_lime = find.stream.fermentation_lime\nFGD_lime = find.stream.FGD_lime\n\ncheck_material_cost = lambda: sum(get_material_cost(feed)()\n                                  for feed in system_feeds) - HP_tea.material_cost/1e6\n\ndef get_product_sale(stream):\n    return lambda: stream.price*stream.F_mass*get_annual_factor()/1e6\nfor product in system_products:\n    metrics.extend((Metric(product.ID, get_product_sale(product), '10^6 $/yr', 'Product sale'),))\ncheck_product_sale= \\\n    lambda: sum(get_product_sale(product)() for product in system_products) \\\n        - HP_tea.sales/1e6\nmetrics.extend((Metric('Check', check_product_sale, '10^6 $/yr', 'Product sale'),))\n\n\n\n# To see if TEA converges well for each simulation\nget_NPV = lambda: HP_tea.NPV\nmetrics.extend((Metric('Net present value', get_NPV, '$', 'TEA'), ))\n\n# To check HXN energy balance error\n# metrics.append(Metric('HXN energy balance error', lambda: HXN.energy_balance_percent_error))\n\nmetrics.extend((Metric('HXN energy balance error', lambda: HXN.energy_balance_percent_error, '%', 'TEA'), ))\n\n##### LCA #####\nmetrics.extend((\n    Metric('Total GWP', get_GWP, 'kg CO2-eq/kg', 'LCA'),\n    Metric('Total FEC', get_FEC, 'MJ/kg', 'LCA')\n    ))\n\n# Material GWP\nmetrics.extend((Metric('GWP - H2SO4',\n                       lambda:get_GWP_by_ID('H2SO4'),\n                       'kg CO2/kg', 'LCA'),))\nmetrics.extend((Metric('GWP - NaOH',\n                       lambda:get_GWP_by_ID('NaOH'),\n                       'kg CO2/kg', 'LCA'),))\nmetrics.extend((Metric('GWP - AmmoniumHydroxide',\n                       lambda:get_GWP_by_ID('AmmoniumHydroxide'),\n                       'kg CO2/kg', 'LCA'),))\nmetrics.extend((Metric('GWP - CalciumDihydroxide',\n                       lambda:get_GWP_by_ID('CalciumDihydroxide'),\n                       'kg CO2/kg', 'LCA'),))\nmetrics.extend((Metric('GWP - Hexanol',\n                       lambda:get_GWP_by_ID('Hexanol'),\n                       'kg CO2/kg', 'LCA'),))\nmetrics.extend((Metric('GWP - Enzyme',\n                       lambda:get_GWP_by_ID('Enzyme'),\n                       'kg CO2/kg', 'LCA'),))\nmetrics.extend((Metric('GWP - TiO2',\n                       lambda:get_GWP_by_ID('TiO2'),\n                       'kg CO2/kg', 'LCA'),))\nmetrics.extend((Metric('GWP - CSL',\n                       lambda:get_GWP_by_ID('CSL'),\n                       'kg CO2/kg', 'LCA'),))\n\n# Material FEC\nmetrics.extend((Metric('FEC - H2SO4',\n                       lambda:get_FEC_by_ID('H2SO4'),\n                       'kg CO2/kg', 'LCA'),))\nmetrics.extend((Metric('FEC - NaOH',\n                       lambda:get_FEC_by_ID('NaOH'),\n                       'kg CO2/kg', 'LCA'),))\nmetrics.extend((Metric('FEC - AmmoniumHydroxide',\n                       lambda:get_FEC_by_ID('AmmoniumHydroxide'),\n                       'kg CO2/kg', 'LCA'),))\nmetrics.extend((Metric('FEC - CalciumDihydroxide',\n                       lambda:get_FEC_by_ID('CalciumDihydroxide'),\n                       'kg CO2/kg', 'LCA'),))\nmetrics.extend((Metric('FEC - Hexanol',\n                       lambda:get_FEC_by_ID('Hexanol'),\n                       'kg CO2/kg', 'LCA'),))\nmetrics.extend((Metric('FEC - Enzyme',\n                       lambda:get_FEC_by_ID('Enzyme'),\n                       'kg CO2/kg', 'LCA'),))\nmetrics.extend((Metric('FEC - TiO2',\n                       lambda:get_FEC_by_ID('TiO2'),\n                       'kg CO2/kg', 'LCA'),))\nmetrics.extend((Metric('FEC - CSL',\n                       lambda:get_FEC_by_ID('CSL'),\n                       'kg CO2/kg', 'LCA'),))\n# Natural gas\nmetrics.extend((Metric('GWP - natural gas',\n                       lambda:get_ng_GWP(),\n                       'kg CO2/kg', 'LCA'),))\nmetrics.extend((Metric('FEC - natural gas',\n                       lambda:get_ng_FEC(),\n                       'MJ/kg', 'LCA'),))\n\n# Natural gas\nmetrics.extend((Metric('GWP - natural gas',\n                       lambda:get_ng_GWP(),\n                       'kg CO2/kg', 'LCA'),))\nmetrics.extend((Metric('FEC - natural gas',\n                       lambda:get_ng_FEC(),\n                       'MJ/kg', 'LCA'),))\n\n# Electricity\nmetrics.extend((Metric('GWP - electricity, net',\n                       lambda:get_net_electricity_GWP(),\n                       'kg CO2/kg', 'LCA'),))\nmetrics.extend((Metric('FEC - electricity, net',\n                       lambda:get_net_electricity_FEC(),\n                       'MJ/kg', 'LCA'),))\n\n# Feedstock growth, harvesting, transportation, and preprocessing\nmetrics.extend((Metric('GWP - Feedstock GHTP',\n                       lambda:get_FGHTP_GWP(),\n                       'kg CO2/kg', 'LCA'),))\nmetrics.extend((Metric('FEC - Feedstock GHTP',\n                       lambda:get_feedstock_FEC(),\n                       'MJ/kg', 'LCA'),))\n\n# Direct non-biogenic emissions GWP\nmetrics.extend((Metric('GWP - Other direct non-bio emmissions',\n                       lambda:get_direct_emissions_GWP(),\n                       'kg CO2/kg', 'LCA'),))\n\nmetrics.extend((Metric('GWP - Other direct non-bio emmissions',\n                       lambda:get_direct_emissions_GWP(),\n                       'kg CO2/kg', 'LCA'),))\n\n# Demand LCA contributions\nmetrics.extend((Metric('cGWP - System heating demand',\n                       lambda:get_heating_demand_GWP()/get_GWP(),\n                       'frac', 'LCA'),))\n\nmetrics.extend((Metric('cGWP - System cooling demand',\n                       lambda:get_cooling_demand_GWP()/get_GWP(),\n                       'frac', 'LCA'),))\n\nmetrics.extend((Metric('cGWP - System non-cooling electricity demand',\n                       lambda:get_electricity_demand_non_cooling_GWP()/get_GWP(),\n                       'frac', 'LCA'),))\n\nmetrics.extend((Metric('cFEC - System heating demand',\n                       lambda:get_heating_demand_FEC()/get_FEC(),\n                       'frac', 'LCA'),))\n\nmetrics.extend((Metric('cFEC - System cooling demand',\n                       lambda:get_cooling_demand_FEC()/get_FEC(),\n                       'frac', 'LCA'),))\n\nmetrics.extend((Metric('cFEC - System non-cooling electricity demand',\n                       lambda:get_electricity_demand_non_cooling_FEC()/get_FEC(),\n                       'frac', 'LCA'),))\n\n# Demand TEA contributions\nmetrics.extend((Metric('cVOC - System heating demand',\n                       lambda:get_heating_demand_VOC()/get_VOC(),\n                       'frac', 'LCA'),))\n\nmetrics.extend((Metric('cVOC - System cooling demand',\n                       lambda:get_cooling_demand_VOC()/get_VOC(),\n                       'frac', 'LCA'),))\n\nmetrics.extend((Metric('cVOC - System non-cooling electricity demand',\n                       lambda:get_electricity_demand_non_cooling_VOC()/get_VOC(),\n                       'frac', 'LCA'),))\n\nmetrics.extend((Metric('Turbogenerator - installed equipment cost',\n                       lambda:BT.installed_costs['Turbogenerator']/1e6,\n                       '10^6 $', 'LCA'),))\n# %% \n\n# =============================================================================\n# Construction base model\n# =============================================================================\n\nHP_model = Model(HP_sys, metrics)\nparam = HP_model.parameter\n\ndef baseline_uniform(baseline, ratio):\n    lb, ub = baseline*(1-ratio), baseline*(1+ratio)\n    if lb > ub: ub, lb = lb, ub\n    return shape.Uniform(lb, ub)\n\ndef baseline_triangle(baseline, ratio):\n    lb, mid, ub = baseline*(1-ratio), baseline, baseline*(1+ratio)\n    if lb > ub: ub, lb = lb, ub\n    return shape.Triangle(lb, mid, ub)\n\n\nD = baseline_uniform(1, 0.1)\n@param(name='Blank parameter', element=feedstock, kind='coupled', units='',\n       baseline=1, distribution=D)\ndef set_blank_parameter(anything):\n    # This does nothing\n    feedstock.T = feedstock.T\n    \n# =============================================================================\n# TEA parameters\n# =============================================================================\n\nD = shape.Triangle(0.84, 0.9, 0.96)\n@param(name='Plant uptime', element='TEA', kind='isolated', units='%',\n       baseline=0.9, distribution=D)\ndef set_operating_days(uptime):\n    HP_tea.operating_days = 365. * uptime\n\n\nfeedstock = find('feedstock')\nD = shape.Triangle(60, 71.3, 83.7)\n@param(name='Feedstock unit price', element='TEA', kind='isolated', units='$/dry-ton',\n       baseline=71.3, distribution=D)\ndef set_feedstock_price(price):\n    feedstock.price = price / _feedstock_factor\n\n\n# Impactful parameters are set to triangular distribution based on literature,\n# less important ones are set to ±10% of baseline value\nspecial_price = {\n#     stream           distribution     min  mid   max\n    'lime_fresh':       ('Triangle',   (0.160, 0.262, 0.288)),\n    'gypsum':           ('Uniform',   (-0.0288,   0.00776))\n    }\n\n# Prices for boiler_chems, baghouse_bag, and cooling_tower_chems are not included\n# as they are tied to BT/CT duties\ndefault_price_streams = ('sulfuric_acid_fresh',\n                         'makeup_TiO2_catalyst', 'ammonia_fresh', 'enzyme', \n                         'system_makeup_water', 'aerobic_caustic', 'ash', 'hexanol_fresh')\n\ndef add_stream_price_param(stream, D):\n    param(setter=Setter(stream, 'price'),\n          name=f'{stream.ID} price', element='TEA', kind='isolated', units='$/kg',\n          baseline=stream.price, distribution=D)\n\nfor stream_ID in special_price.keys():\n    stream = getattr(find.stream, stream_ID)\n    lower = special_price[stream_ID][1][0]\n    mid = stream.price\n    upper = special_price[stream_ID][1][-1]\n    if special_price[stream_ID][0] == 'Triangle':\n        D = shape.Triangle(lower, mid, upper)\n    elif special_price[stream.ID][0] == 'Uniform':\n        D = shape.Uniform(lower, upper)\n    add_stream_price_param(stream, D)\n\nfor stream_ID in default_price_streams:\n    stream = getattr(find.stream, stream_ID)\n    baseline = stream.price\n    D = baseline_triangle(baseline, 0.1)\n    add_stream_price_param(stream, D)\n\nD = shape.Triangle(0.067, 0.070, 0.073)\n@param(name='Electricity price', element='TEA', kind='isolated', units='$/kWh',\n       baseline=0.070, distribution=D)\ndef set_electricity_price(price): \n    bst.PowerUtility.price = price\n\nBT = flowsheet('BT')\nnatural_gas_price = BT.natural_gas_price\nD = shape.Triangle(natural_gas_price*0.9, natural_gas_price, natural_gas_price*1.1)\n@param(name='Natural gas price', element='TEA', kind='isolated', units='$/kWh',\n       baseline=natural_gas_price, distribution=D)\ndef set_natural_gas_price(price): \n    BT.natural_gas_price = price\n    \n\nD = baseline_triangle(1., 0.25)\n@param(name='TCI ratio', element='TEA', kind='isolated', units='% of baseline',\n        baseline=1., distribution=D)\ndef set_TCI_ratio(ratio): \n    for unit in HP_sys.units:\n        if hasattr(unit, 'cost_items'):\n            for item in unit.cost_items:\n                unit.cost_items[item].cost *= ratio/HP_no_BT_tea._TCI_ratio_cached\n                HP_no_BT_tea._TCI_ratio_cached = ratio\n\n# =============================================================================\n# LCA parameters\n# =============================================================================\n\nD = shape.Uniform(0.09646, 0.12894) # see Feedstock_impacts_YL\n@param(name='Feedstock GHTP GWP100 CF', element='LCA', kind='isolated', units='kg-CO2eq. / dry-kg',\n       baseline=0.10945, distribution=D)\ndef set_feedstock_GWP_CF(CF):\n    CFs['GWP_CFs']['FGHTP Corn stover'] = CF\n    \nD = shape.Uniform(1.32576, 1.75741) # see Feedstock_impacts_YL\n@param(name='Feedstock GHTP FEC CF', element='LCA', kind='isolated', units='MJeq. / dry-kg',\n       baseline=1.68, distribution=D)\ndef set_feedstock_FEC_CF(CF):\n    CFs['FEC_CFs']['FGHTP Corn stover'] = CF\n    \n# =============================================================================\n# Pretreatment parameters\n# =============================================================================\n\nM202 = find.unit.M202\nD = shape.Triangle(0.25, 0.3, 0.4)\n@param(name='Pretreatment solid loading', element=M202, kind='coupled', units='%', \n       baseline=0.3, distribution=D)\ndef set_pretreatment_solid_loading(loading): \n    M202.solid_loading = loading\n\n\n# baseline imass discrepancy\npretreatment_sulfuric_acid = find.stream.pretreatment_sulfuric_acid\nD = shape.Triangle(10, 22.1, 35)\n@param(name='Pretreatment sulfuric acid loading', element=pretreatment_sulfuric_acid,\n       kind='coupled', units='mg/g-dry feedstock', baseline=22.1, distribution=D)\ndef set_pretreatment_sulfuric_acid_loading(loading): \n    feedstock_dry_mass = feedstock.F_mass - feedstock.imass['H2O']\n    pretreatment_sulfuric_acid.imass['H2SO4'] = feedstock_dry_mass*loading/1000*0.93\n    pretreatment_sulfuric_acid.imass['H2O'] = feedstock_dry_mass*loading/1000*0.07\n\nR201 = find.unit.R201\nD = shape.Triangle(0.06, 0.099, 0.12)\n@param(name='Pretreatment glucan-to-glucose', element=R201, kind='coupled', units='%',\n       baseline=0.099, distribution=D)\ndef set_R201_glucan_conversion(X): R201.pretreatment_rxns[0].X = X    \n\nD = shape.Triangle(0.8, 0.9, 0.92)\n@param(name='Pretreatment xylan-to-xylose', element=R201, kind='coupled', units='%',\n       baseline=0.9, distribution=D)\ndef set_R201_xylan_conversion(X): R201.pretreatment_rxns[4].X = X        \n\n\n# =============================================================================\n# Conversion parameters\n# =============================================================================\n\nM301 = find.unit.M301\nR302 = find.unit.R302\nR303 = find.unit.R303\n\nD = shape.Triangle(0.175, 0.2, 0.25)\n@param(name='Enzymatic hydrolysis solid loading', element=M301, kind='coupled', units='%',\n       baseline=0.2, distribution=D)\ndef set_R301_hydrolysis_solid_loading(loading): M301.solid_loading = loading\n\nD = shape.Triangle(10, 20, 30)\n@param(name='Enzyme loading', element=M301, kind='coupled', units='mg/g glucan',\n       baseline=20, distribution=D)\ndef set_R301_enzyme_loading(loading): M301.enzyme_loading = loading\n\n# Enzymatic hydrolysis\nD = shape.Triangle(0., 24., 56.)\n@param(name='Enzymatic hydrolysis time', element=R301, kind='coupled', units='hr',\n       baseline=24, distribution=D)\ndef set_R301_hydrolysis_time(tau): R301.tau_saccharification = tau\n\nD = shape.Triangle(0.75, 0.9, 0.948-1e-6)\n@param(name='Enzymatic hydrolysis glucan-to-glucose', element=R301, kind='coupled', units='%',\n       baseline=0.9, distribution=D)\ndef set_R301_glucan_conversion(X): R301.saccharification_rxns[2].X = X\n\n\nD = shape.Triangle(0.684, 0.76, 0.8360000000000001)\n@param(name='Productivity', element=R302, kind='coupled', units='g/L/hr',\n       baseline=0.76, distribution=D)\ndef set_HP_productivity(productivity):\n    if not lock_productivity:\n        spec.spec_3 = productivity\n    \nD = shape.Triangle(5., 10., 15.)\n@param(name='CSL loading', element=R301, kind='coupled', units='g/L',\n       baseline=10., distribution=D)\ndef set_CSL_loading(loading): R302.CSL_loading = loading\n\n\n\nD = shape.Triangle(0.49*0.8, 0.49, 0.49*1.2) # +/- 20% of baseline\n@param(name='3-Hydroxypropionic acid yield', element=R302, kind='coupled', units='% theoretical',\n        baseline=0.49, distribution=D)\ndef set_R302_HP_yield(X):\n    if not lock_yield:\n        spec.spec_1 = X\n\nD = shape.Triangle(54.8*0.8, 54.8, 54.8*1.2) # +/- 20% of baseline\n@param(name='3-Hydroxypropionic acid titer', element=R302, kind='coupled', units='g/L',\n        baseline=54.8, distribution=D)\ndef set_R302_HP_titer(X):\n    if not lock_titer:\n        spec.spec_2 = X\n    \n##############################################################################################\n\nD = shape.Triangle(0.032, 0.040, 0.048)\n@param(name='Acetic acid and glycerol yield', element=R303, kind='coupled', units='% theoretical',\n        baseline=0.040, distribution=D)\ndef set_R301_acetic_acid_yield(X): \n    # 1e-6 is to avoid generating tiny negative flow (e.g., 1e-14) in R301\n    # R302_X = R302.cofermentation_rxns.X\n    ferm_ratio = R303.ferm_ratio\n    \n    X1 = min(X, 1-1e-6-R302.glucose_to_HP_rxn.X-R302.glucose_to_biomass_rxn.X)\n    X2 = min(X, 1-1e-6-R302.xylose_to_HP_rxn.X-R302.xylose_to_biomass_rxn.X)\n    \n    R302.glucose_to_acetic_acid_rxn.X = X1\n    R303.glucose_to_acetic_acid_rxn.X = X1 * ferm_ratio\n    \n    R302.xylose_to_acetic_acid_rxn.X = X2\n    R303.xylose_to_acetic_acid_rxn.X = X2 * ferm_ratio\n    \n    X1_glycerol = X1 if X1==X else 0.\n    X2_glycerol = X2 if X2==X else 0.  \n    \n    R302.glucose_to_glycerol_rxn.X = X1_glycerol\n    R303.glucose_to_glycerol_rxn.X = X1_glycerol * ferm_ratio\n    \n    R302.xylose_to_glycerol_rxn.X = X2_glycerol\n    R303.xylose_to_glycerol_rxn.X = X2_glycerol * ferm_ratio\n    \n    \n   \nS302 = find.unit.S302\nD = shape.Triangle(0.05, 0.07, 0.1)\n@param(name='Inoculum ratio', element=S302, kind='coupled', units='%',\n        baseline=0.07, distribution=D)\ndef set_inoculum_ratio(ratio): S302.split = ratio*np.ones(len(S302.split))\n\n\n\n# =============================================================================\n# Separation parameters\n# =============================================================================\n\nS402 = find.unit.S402\nD = shape.Triangle(0.95, 0.995, 1.)\n@param(name='Gypsum split', element=S402, kind='coupled', units='',\n       baseline=0.995, distribution=D)\ndef set_S402_gypsum_split(split):\n    gypsum_index = S402.chemicals.index('Gypsum')\n    S402.split[gypsum_index] = split\n\nR401 = find.unit.R401\nD = baseline_triangle(1., 0.1)\n@param(name='Acidulation time', element=R401, kind='coupled', units='hr',\n       baseline=1., distribution=D)\ndef set_R401_tau(tau):\n    R401.tau = tau\n\nM402 = find.unit.M402\nD = shape.Triangle(0.27, 0.3, 0.35)\n@param(name='Dehydration feed HP weight fraction', element=M402, kind='coupled', units='w/w',\n       baseline=0.3, distribution=D)\ndef set_M402_HP_wt_frac(wt_frac):\n    M402.HP_wt_frac = wt_frac\n\nR402 = find.unit.R402\n# D = baseline_triangle(0.95, 0.05)\nD = shape.Triangle(0.72, 0.8, 0.88)\n@param(name='Dehydration conversion', element=R402, kind='coupled', units='',\n       baseline=0.8, distribution=D)\ndef set_R402_conversion(X):\n    R402.dehydration_reactions[0].X = X\n\nD = baseline_triangle(38.22666667, 0.1)\n@param(name='Dehydration time', element=R402, kind='coupled', units='h',\n       baseline=38.22666667, distribution=D)\ndef set_R402_conversion(R402_tau):\n    R402.tau = R402_tau\n    \n\n# =============================================================================\n# Facilities parameters\n# =============================================================================\n\n# Facilities are currently not in unit path. thus not set the element here\nD = baseline_uniform(0.8, 0.1)\n@param(name='BT combustion efficiency', element=BT, kind='coupled', units='%',\n       baseline=0.8, distribution=D)\ndef set_BT_combustion_efficiency(efficiency):\n    BT.boiler_efficiency = efficiency\n\n# All parameters\nparameters = HP_model.get_parameters()\n\nindex_TEA = len(metrics)\n\n\n# %%\n\n# =============================================================================\n# Model to evalute system across internal rate of return\n# =============================================================================\n\ndef create_IRR_metrics(IRR):\n    def get_IRR_based_MSP():\n        HP_tea.IRR = IRR\n        return get_MSP()\n    return [Metric('Minimum selling price', get_IRR_based_MSP, '$/kg', f'IRR={IRR:.0%}'),\n            Metric('Net present value', get_NPV, '$', f'IRR={IRR:.0%}')]\n\nIRRs = np.linspace(0, 0.4, 41)\nIRR_metrics = sum([create_IRR_metrics(IRR) for IRR in IRRs],[])\n\nHP_model_IRR = Model(HP_sys, IRR_metrics)\nHP_model_IRR.set_parameters(parameters)\n\n\n# %% \n\n# =============================================================================\n# Model to evalute system across 3-Hydroxypropionic acid yield\n# =============================================================================\n\nHP_model_LA_yield = Model(HP_sys, metrics)\n\ndef set_LA_yield(LA_yield):\n    R301_X = R301.cofermentation_rxns.X\n    R301_X[0] = R301_X[3] = LA_yield\n    R301_X[1] = R301_X[4] = min(1-1e-6-R301_X[0]-R301_X[2], R301_X[1])\n    R302_X = R302.cofermentation_rxns.X\n    R302_X[0] = R302_X[3] = R301_X[0] * R302.ferm_ratio\n    R302_X[1] = R302_X[4] = R301_X[1] * R302.ferm_ratio\n\nLA_yield_parameters = tuple([i for i in parameters if not i.name=='3-Hydroxypropionic acid yield'])\nHP_model_LA_yield.set_parameters(LA_yield_parameters)\n\n\n# %%\n\n# =============================================================================\n# Model to evalute system across feedstock price and carbohydate content\n# =============================================================================\n\ndef create_feedstock_price_metris(price):\n    def get_price_based_MSP():\n        price_per_kg = price / _kg_per_ton * 0.8\n        feedstock.price = price_per_kg\n        return get_MSP()\n    return [Metric('Minimum selling price', get_price_based_MSP, '$/kg', f'Price={price:.0f} [$/dry-ton]'),\n            Metric('Net present value', get_NPV, '$', f'Price={price:.0f} [$/dry-ton]')]\n\nprices = np.linspace(50, 300, 26)\nprices = np.concatenate((prices, np.array([71.26])))\nfeedstock_price_metrics = sum([create_feedstock_price_metris(price) \n                                for price in prices],[])\n\ndef set_feedstock_carbs(carbs_content):\n    carbs = ('Glucan', 'Xylan', 'Arabinan', 'Galactan', 'Mannan')\n    dry_mass = feedstock.F_mass.copy() - feedstock.imass[('H2O',)].copy()\n    old_carbs_mass_total = feedstock.imass[carbs].sum().copy()\n    ratio = feedstock.get_normalized_mass(carbs)\n    new_carbs_mass = dry_mass * carbs_content * ratio\n    feedstock.set_flow(new_carbs_mass, 'kg/hr', carbs)\n    mass_diff = new_carbs_mass.sum() - old_carbs_mass_total\n    feedstock.imass['Extract'] -= mass_diff\n    if any(feedstock.mass < 0):\n        raise ValueError(f'Carbohydrate content of {carbs_content*100:.0f}% dry weight is infeasible')\n\nHP_model_feedstock = Model(HP_sys, feedstock_price_metrics)\n\nparam = HP_model_feedstock.parameter\n\n# Set a fake parameter to enable evaluation across internal rate of return\nfeedstock = find.stream.feedstock\nD = shape.Uniform(0.9, 1.1)\n@param(name='Fake parameter', element=feedstock, kind='coupled', units='',\n       baseline=1, distribution=D)\ndef set_fake_parameter(anything): pass\n\nindex_IRR = len(metrics)\n# %%\n\n# =============================================================================\n# Model to evalute system across feedstock succinic acid content\n# =============================================================================\n\ndef set_feedstock_succinic_acid_content(SA_content):\n    dry_mass = feedstock.F_mass - feedstock.imass['H2O']\n    feedstock.imass['SuccinicAcid'] = SA_content * dry_mass\n    # Use Extract to close mass balance\n    feedstock.imass['Extract'] -= (feedstock.F_mass-feedstock.imass['H2O']) - dry_mass\n    if any(feedstock.mass<0):\n        raise ValueError(f'Succinic acid content of {SA_content*100:.0f}% dry weight is infeasible')\n\nHP_model_SA_content = Model(HP_sys, metrics)\nHP_model_SA_content.set_parameters(parameters)\n\n\n# %% \n\n# =============================================================================\n# Model to evalute system across HXN minimum approach temperature\n# =============================================================================\nget_HXN_util_cost = lambda: HXN.utility_cost\nget_HXN_util_savings = lambda: - 100*(HXN.utility_cost*350*24) / (HP_sys.utility_cost - HXN.utility_cost*350*24)\ndef create_HXN_T_min_app_metrics(T_min_app):\n    return [Metric('HXN utility savings', get_HXN_util_savings, '%', f'T_min_app={T_min_app:.0f} [K]')]\n\nT_min_apps = np.linspace(1, 20, 21)\nHXN_T_min_app_metrics = sum([create_HXN_T_min_app_metrics(T_min_app) for T_min_app in T_min_apps],[])\n\n\nHP_model_HXN_T_min_app = Model(HP_sys, metrics)\n\ndef set_HXN_T_min_app(T_min_app):\n    HXN.T_min_app = T_min_app\n\nHP_model_HXN_T_min_app.set_parameters(parameters)\n\n\n\n# %% Evaluate\n# N_samples = 100\n# rule = 'L' # For Latin-Hypercube sampling\n# model=HP_model\n# samples = model.sample(N_samples, rule)\n# model.load_samples(samples)\n# model.evaluate()\n# model.table # All evaluations are stored as a pandas DataFrame\n\n\n", "meta": {"hexsha": "48bc224c5b504ffd188a24846d17346ea56cdd83", "size": 41925, "ext": "py", "lang": "Python", "max_stars_repo_path": "BioSTEAM 2.x.x/biorefineries/HP/analyses/models.py", "max_stars_repo_name": "yoelcortes/Bioindustrial-Complex", "max_stars_repo_head_hexsha": "d39edfec88e443ef7a62218ca0215e3b105f4b96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2020-05-12T21:46:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T00:35:35.000Z", "max_issues_repo_path": "BioSTEAM 2.x.x/biorefineries/HP/analyses/models.py", "max_issues_repo_name": "yalinli2/Bioindustrial-Park", "max_issues_repo_head_hexsha": "196e2d60ec9bf0466ef804d036c995b89bc72f72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2020-03-05T14:39:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T22:24:50.000Z", "max_forks_repo_path": "BioSTEAM 2.x.x/biorefineries/HP/analyses/models.py", "max_forks_repo_name": "yalinli2/Bioindustrial-Park", "max_forks_repo_head_hexsha": "196e2d60ec9bf0466ef804d036c995b89bc72f72", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2020-05-14T13:02:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T19:41:07.000Z", "avg_line_length": 42.2205438066, "max_line_length": 143, "alphanum_fraction": 0.5847823494, "include": true, "reason": "import numpy", "num_tokens": 10183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.17533478802133737}}
{"text": "\"\"\"\nCustom implementation of the Levenberg-Marquardt Algorithm\n\"\"\"\n#***************************************************************************************************\n# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).\n# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights\n# in this software.\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n# in compliance with the License.  You may obtain a copy of the License at\n# http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory.\n#***************************************************************************************************\n\nimport signal as _signal\nimport time as _time\n\nimport numpy as _np\nimport scipy as _scipy\n\nfrom pygsti.optimize import arraysinterface as _ari\nfrom pygsti.optimize.customsolve import custom_solve as _custom_solve\nfrom pygsti.baseobjs.verbosityprinter import VerbosityPrinter as _VerbosityPrinter\nfrom pygsti.baseobjs.resourceallocation import ResourceAllocation as _ResourceAllocation\nfrom pygsti.baseobjs.nicelyserializable import NicelySerializable as _NicelySerializable\n\n# from scipy.optimize import OptimizeResult as _optResult\n\n#Make sure SIGINT will generate a KeyboardInterrupt (even if we're launched in the background)\n_signal.signal(_signal.SIGINT, _signal.default_int_handler)\n\n#constants\n_MACH_PRECISION = 1e-12\n#MU_TOL1 = 1e10 # ??\n#MU_TOL2 = 1e3  # ??\n\n\nclass OptimizerResult(object):\n    \"\"\"\n    The result from an optimization.\n\n    Parameters\n    ----------\n    objective_func : ObjectiveFunction\n        The objective function that was optimized.\n\n    opt_x : numpy.ndarray\n        The optimal argument (x) value.  Often a vector of parameters.\n\n    opt_f : numpy.ndarray\n        the optimal objective function (f) value.  Often this is the least-squares\n        vector of objective function values.\n\n    opt_jtj : numpy.ndarray, optional\n        the optimial `dot(transpose(J),J)` value, where `J`\n        is the Jacobian matrix.  This may be useful for computing\n        approximate error bars.\n\n    opt_unpenalized_f : numpy.ndarray, optional\n        the optimal objective function (f) value with any\n        penalty terms removed.\n\n    chi2_k_distributed_qty : float, optional\n        a value that is supposed to be chi2_k distributed.\n\n    optimizer_specific_qtys : dict, optional\n        a dictionary of additional optimization parameters.\n    \"\"\"\n    def __init__(self, objective_func, opt_x, opt_f=None, opt_jtj=None,\n                 opt_unpenalized_f=None, chi2_k_distributed_qty=None,\n                 optimizer_specific_qtys=None):\n        self.objective_func = objective_func\n        self.x = opt_x\n        self.f = opt_f\n        self.jtj = opt_jtj  # jacobian.T * jacobian\n        self.f_no_penalties = opt_unpenalized_f\n        self.optimizer_specific_qtys = optimizer_specific_qtys\n        self.chi2_k_distributed_qty = chi2_k_distributed_qty\n\n\nclass Optimizer(_NicelySerializable):\n    \"\"\"\n    An optimizer.  Optimizes an objective function.\n    \"\"\"\n\n    @classmethod\n    def cast(cls, obj):\n        \"\"\"\n        Cast `obj` to a :class:`Optimizer`.\n\n        If `obj` is already an `Optimizer` it is just returned,\n        otherwise this function tries to create a new object\n        using `obj` as a dictionary of constructor arguments.\n\n        Parameters\n        ----------\n        obj : Optimizer or dict\n            The object to cast.\n\n        Returns\n        -------\n        Optimizer\n        \"\"\"\n        if isinstance(obj, cls):\n            return obj\n        else:\n            return cls(**obj) if obj else cls()\n\n\nclass CustomLMOptimizer(Optimizer):\n    \"\"\"\n    A Levenberg-Marquardt optimizer customized for GST-like problems.\n\n    Parameters\n    ----------\n    maxiter : int, optional\n        The maximum number of (outer) interations.\n\n    maxfev : int, optional\n        The maximum function evaluations.\n\n    tol : float or dict, optional\n        The tolerance, specified as a single float or as a dict\n        with keys `{'relx', 'relf', 'jac', 'maxdx'}`.  A single\n        float sets the `'relf'` and `'jac'` elemments and leaves\n        the others at their default values.\n\n    fditer : int optional\n        Internally compute the Jacobian using a finite-difference method\n        for the first `fditer` iterations.  This is useful when the initial\n        point lies at a special or singular point where the analytic Jacobian\n        is misleading.\n\n    first_fditer : int, optional\n        Number of finite-difference iterations applied to the first\n        stage of the optimization (only).  Unused.\n\n    damping_mode : {'identity', 'JTJ', 'invJTJ', 'adaptive'}\n        How damping is applied.  `'identity'` means that the damping parameter mu\n        multiplies the identity matrix.  `'JTJ'` means that mu multiplies the\n        diagonal or singular values (depending on `scaling_mode`) of the JTJ\n        (Fischer information and approx. hessaian) matrix, whereas `'invJTJ'`\n        means mu multiplies the reciprocals of these values instead.  The\n        `'adaptive'` mode adaptively chooses a damping strategy.\n\n    damping_basis : {'diagonal_values', 'singular_values'}\n        Whether the the diagonal or singular values of the JTJ matrix are used\n        during damping.  If `'singular_values'` is selected, then a SVD of the\n        Jacobian (J) matrix is performed and damping is performed in the basis\n        of (right) singular vectors.  If `'diagonal_values'` is selected, the\n        diagonal values of relevant matrices are used as a proxy for the the\n        singular values (saving the cost of performing a SVD).\n\n    damping_clip : tuple, optional\n        A 2-tuple giving upper and lower bounds for the values that mu multiplies.\n        If `damping_mode == \"identity\"` then this argument is ignored, as mu always\n        multiplies a 1.0 on the diagonal if the identity matrix.  If None, then no\n        clipping is applied.\n\n    use_acceleration : bool, optional\n        Whether to include a geodesic acceleration term as suggested in\n        arXiv:1201.5885.  This is supposed to increase the rate of\n        convergence with very little overhead.  In practice we've seen\n        mixed results.\n\n    uphill_step_threshold : float, optional\n        Allows uphill steps when taking two consecutive steps in nearly\n        the same direction.  The condition for accepting an uphill step\n        is that `(uphill_step_threshold-beta)*new_objective < old_objective`,\n        where `beta` is the cosine of the angle between successive steps.\n        If `uphill_step_threshold == 0` then no uphill steps are allowed,\n        otherwise it should take a value between 1.0 and 2.0, with 1.0 being\n        the most permissive to uphill steps.\n\n    init_munu : tuple, optional\n        If not None, a (mu, nu) tuple of 2 floats giving the initial values\n        for mu and nu.\n\n    oob_check_interval : int, optional\n        Every `oob_check_interval` outer iterations, the objective function\n        (`obj_fn`) is called with a second argument 'oob_check', set to True.\n        In this case, `obj_fn` can raise a ValueError exception to indicate\n        that it is Out Of Bounds.  If `oob_check_interval` is 0 then this\n        check is never performed; if 1 then it is always performed.\n\n    oob_action : {\"reject\",\"stop\"}\n        What to do when the objective function indicates (by raising a ValueError\n        as described above).  `\"reject\"` means the step is rejected but the\n        optimization proceeds; `\"stop\"` means the optimization stops and returns\n        as converged at the last known-in-bounds point.\n\n    oob_check_mode : int, optional\n        An advanced option, expert use only.  If 0 then the optimization is\n        halted as soon as an *attempt* is made to evaluate the function out of bounds.\n        If 1 then the optimization is halted only when a would-be *accepted* step\n        is out of bounds.\n\n    serial_solve_proc_threshold : int optional\n        When there are fewer than this many processors, the optimizer will solve linear\n        systems serially, using SciPy on a single processor, rather than using a parallelized\n        Gaussian Elimination (with partial pivoting) algorithm coded in Python. Since SciPy's\n        implementation is more efficient, it's not worth using the parallel version until there\n        are many processors to spread the work among.\n    \"\"\"\n    def __init__(self, maxiter=100, maxfev=100, tol=1e-6, fditer=0, first_fditer=0, damping_mode=\"identity\",\n                 damping_basis=\"diagonal_values\", damping_clip=None, use_acceleration=False,\n                 uphill_step_threshold=0.0, init_munu=\"auto\", oob_check_interval=0,\n                 oob_action=\"reject\", oob_check_mode=0, serial_solve_proc_threshold=100):\n\n        if isinstance(tol, float): tol = {'relx': 1e-8, 'relf': tol, 'f': 1.0, 'jac': tol, 'maxdx': 1.0}\n        self.maxiter = maxiter\n        self.maxfev = maxfev\n        self.tol = tol\n        self.fditer = fditer\n        self.first_fditer = first_fditer\n        self.damping_mode = damping_mode\n        self.damping_basis = damping_basis\n        self.damping_clip = damping_clip\n        self.use_acceleration = use_acceleration\n        self.uphill_step_threshold = uphill_step_threshold\n        self.init_munu = init_munu\n        self.oob_check_interval = oob_check_interval\n        self.oob_action = oob_action\n        self.oob_check_mode = oob_check_mode\n        self.array_types = 3 * ('p',) + ('e', 'ep')  # see custom_leastsq fn \"-type\"s  -need to add 'jtj' type\n        self.called_objective_methods = ('lsvec', 'dlsvec')  # the objective function methods we use (for mem estimate)\n        self.serial_solve_proc_threshold = serial_solve_proc_threshold\n\n    def _to_nice_serialization(self):\n        state = super()._to_nice_serialization()\n        state.update({\n            'maximum_iterations': self.maxiter,\n            'maximum_function_evaluations': self.maxfev,\n            'tolerance': self.tol,\n            'number_of_finite_difference_iterations': self.fditer,\n            'number_of_first_stage_finite_difference_iterations': self.first_fditer,\n            'damping_mode': self.damping_mode,\n            'damping_basis': self.damping_basis,\n            'damping_clip': self.damping_clip,\n            'use_acceleration': self.use_acceleration,\n            'uphill_step_threshold': self.uphill_step_threshold,\n            'initial_mu_and_nu': self.init_munu,\n            'out_of_bounds_check_interval': self.oob_check_interval,\n            'out_of_bounds_action': self.oob_action,\n            'out_of_bounds_check_mode': self.oob_check_mode,\n            'array_types': self.array_types,\n            'called_objective_function_methods': self.called_objective_methods,\n            'serial_solve_number_of_processors_threshold': self.serial_solve_proc_threshold\n        })\n        return state\n\n    @classmethod\n    def _from_nice_serialization(cls, state):\n        return cls(maxiter=state['maximum_iterations'],\n                   maxfev=state['maximum_function_evaluations'],\n                   tol=state['tolerance'],\n                   fditer=state['number_of_finite_difference_iterations'],\n                   first_fditer=state['number_of_first_stage_finite_difference_iterations'],\n                   damping_mode=state['damping_mode'],\n                   damping_basis=state['damping_basis'],\n                   damping_clip=state['damping_clip'],\n                   use_acceleration=state['use_acceleration'],\n                   uphill_step_threshold=state['uphill_step_threshold'],\n                   init_munu=state['initial_mu_and_nu'],\n                   oob_check_interval=state['out_of_bounds_check_interval'],\n                   oob_action=state['out_of_bounds_action'],\n                   oob_check_mode=state['out_of_bounds_check_mode'],\n                   serial_solve_proc_threshold=state['serial_solve_number_of_processors_threshold'])\n\n    def run(self, objective, profiler, printer):\n\n        \"\"\"\n        Perform the optimization.\n\n        Parameters\n        ----------\n        objective : ObjectiveFunction\n            The objective function to optimize.\n\n        profiler : Profiler\n            A profiler to track resource usage.\n\n        printer : VerbosityPrinter\n            printer to use for sending output to stdout.\n        \"\"\"\n        objective_func = objective.lsvec\n        jacobian = objective.dlsvec\n        x0 = objective.model.to_vector()\n        x_limits = objective.model.parameter_bounds\n        # x_limits should be a (num_params, 2)-shaped array, holding on each row the (min, max) values for the\n        #  corresponding parameter (element of the \"x\" vector) or `None`.  If `None`, then no limits are imposed.\n\n        # Check memory limit can handle what custom_leastsq will \"allocate\"\n        nExtra = objective.ex  # number of additional \"extra\" elements\n        nEls = objective.layout.num_elements + nExtra; nP = len(x0)  # 'e' and 'p' for array types\n        objective.resource_alloc.check_can_allocate_memory(3 * nP + nEls + nEls * nP + nP * nP)  # see array_types above\n\n        from ..layouts.distlayout import DistributableCOPALayout as _DL\n        ari = _ari.DistributedArraysInterface(objective.layout, nExtra) \\\n            if isinstance(objective.layout, _DL) else _ari.UndistributedArraysInterface(nEls, nP)\n\n        opt_x, converged, msg, mu, nu, norm_f, f, opt_jtj = custom_leastsq(\n            objective_func, jacobian, x0,\n            max_iter=self.maxiter,\n            num_fd_iters=self.fditer,\n            f_norm2_tol=self.tol.get('f', 1.0),\n            jac_norm_tol=self.tol.get('jac', 1e-6),\n            rel_ftol=self.tol.get('relf', 1e-6),\n            rel_xtol=self.tol.get('relx', 1e-8),\n            max_dx_scale=self.tol.get('maxdx', 1.0),\n            damping_mode=self.damping_mode,\n            damping_basis=self.damping_basis,\n            damping_clip=self.damping_clip,\n            use_acceleration=self.use_acceleration,\n            uphill_step_threshold=self.uphill_step_threshold,\n            init_munu=self.init_munu,\n            oob_check_interval=self.oob_check_interval,\n            oob_action=self.oob_action,\n            oob_check_mode=self.oob_check_mode,\n            resource_alloc=objective.resource_alloc,\n            arrays_interface=ari,\n            serial_solve_proc_threshold=self.serial_solve_proc_threshold,\n            x_limits=x_limits,\n            verbosity=printer - 1, profiler=profiler)\n\n        printer.log(\"Least squares message = %s\" % msg, 2)\n        assert(converged), \"Failed to converge: %s\" % msg\n        current_v = objective.model.to_vector()\n        if not _np.allclose(current_v, opt_x):  # ensure the last model evaluation was at opt_x\n            objective_func(opt_x)\n            #objective.model.from_vector(opt_x)  # performed within line above\n\n        #DEBUG CHECK SYNC between procs (especially for shared mem) - could REMOVE\n        # if objective.resource_alloc.comm is not None:\n        #     comm = objective.resource_alloc.comm\n        #     v_cmp = comm.bcast(objective.model.to_vector() if (comm.Get_rank() == 0) else None, root=0)\n        #     v_matches_x = _np.allclose(objective.model.to_vector(), opt_x)\n        #     same_as_root = _np.isclose(_np.linalg.norm(objective.model.to_vector() - v_cmp), 0.0)\n        #     if not (v_matches_x and same_as_root):\n        #         raise ValueError(\"Rank %d CUSTOMLM ERROR: END model vector-matches-x=%s and vector-is-same-as-root=%s\"\n        #                          % (comm.rank, str(v_matches_x), str(same_as_root)))\n        #     comm.barrier()  # if we get past here, then *all* processors are OK\n        #     if comm.rank == 0:\n        #         print(\"OK - model vector == best_x and all vectors agree w/root proc's\")\n\n        unpenalized_f = f[0:-objective.ex] if (objective.ex > 0) else f\n        unpenalized_normf = sum(unpenalized_f**2)  # objective function without penalty factors\n        chi2k_qty = objective.chi2k_distributed_qty(norm_f)\n\n        return OptimizerResult(objective, opt_x, norm_f, opt_jtj, unpenalized_normf, chi2k_qty,\n                               {'msg': msg, 'mu': mu, 'nu': nu, 'fvec': f})\n\n#Scipy version...\n#            opt_x, _, _, msg, flag = \\\n#                _spo.leastsq(objective_func, x0, xtol=tol['relx'], ftol=tol['relf'], gtol=tol['jac'],\n#                             maxfev=maxfev * (len(x0) + 1), full_output=True, Dfun=jacobian)  # pragma: no cover\n#            printer.log(\"Least squares message = %s; flag =%s\" % (msg, flag), 2)            # pragma: no cover\n#            opt_state = (msg,)\n\n\ndef custom_leastsq(obj_fn, jac_fn, x0, f_norm2_tol=1e-6, jac_norm_tol=1e-6,\n                   rel_ftol=1e-6, rel_xtol=1e-6, max_iter=100, num_fd_iters=0,\n                   max_dx_scale=1.0, damping_mode=\"identity\", damping_basis=\"diagonal_values\",\n                   damping_clip=None, use_acceleration=False, uphill_step_threshold=0.0,\n                   init_munu=\"auto\", oob_check_interval=0, oob_action=\"reject\", oob_check_mode=0,\n                   resource_alloc=None, arrays_interface=None, serial_solve_proc_threshold=100,\n                   x_limits=None, verbosity=0, profiler=None):\n    \"\"\"\n    An implementation of the Levenberg-Marquardt least-squares optimization algorithm customized for use within pyGSTi.\n\n    This general purpose routine mimic to a large extent the interface used by\n    `scipy.optimize.leastsq`, though it implements a newer (and more robust) version\n    of the algorithm.\n\n    Parameters\n    ----------\n    obj_fn : function\n        The objective function.  Must accept and return 1D numpy ndarrays of\n        length N and M respectively.  Same form as scipy.optimize.leastsq.\n\n    jac_fn : function\n        The jacobian function (not optional!).  Accepts a 1D array of length N\n        and returns an array of shape (M,N).\n\n    x0 : numpy.ndarray\n        Initial evaluation point.\n\n    f_norm2_tol : float, optional\n        Tolerace for `F^2` where `F = `norm( sum(obj_fn(x)**2) )` is the\n        least-squares residual.  If `F**2 < f_norm2_tol`, then mark converged.\n\n    jac_norm_tol : float, optional\n        Tolerance for jacobian norm, namely if `infn(dot(J.T,f)) < jac_norm_tol`\n        then mark converged, where `infn` is the infinity-norm and\n        `f = obj_fn(x)`.\n\n    rel_ftol : float, optional\n        Tolerance on the relative reduction in `F^2`, that is, if\n        `d(F^2)/F^2 < rel_ftol` then mark converged.\n\n    rel_xtol : float, optional\n        Tolerance on the relative value of `|x|`, so that if\n        `d(|x|)/|x| < rel_xtol` then mark converged.\n\n    max_iter : int, optional\n        The maximum number of (outer) interations.\n\n    num_fd_iters : int optional\n        Internally compute the Jacobian using a finite-difference method\n        for the first `num_fd_iters` iterations.  This is useful when `x0`\n        lies at a special or singular point where the analytic Jacobian is\n        misleading.\n\n    max_dx_scale : float, optional\n        If not None, impose a limit on the magnitude of the step, so that\n        `|dx|^2 < max_dx_scale^2 * len(dx)` (so elements of `dx` should be,\n        roughly, less than `max_dx_scale`).\n\n    damping_mode : {'identity', 'JTJ', 'invJTJ', 'adaptive'}\n        How damping is applied.  `'identity'` means that the damping parameter mu\n        multiplies the identity matrix.  `'JTJ'` means that mu multiplies the\n        diagonal or singular values (depending on `scaling_mode`) of the JTJ\n        (Fischer information and approx. hessaian) matrix, whereas `'invJTJ'`\n        means mu multiplies the reciprocals of these values instead.  The\n        `'adaptive'` mode adaptively chooses a damping strategy.\n\n    damping_basis : {'diagonal_values', 'singular_values'}\n        Whether the the diagonal or singular values of the JTJ matrix are used\n        during damping.  If `'singular_values'` is selected, then a SVD of the\n        Jacobian (J) matrix is performed and damping is performed in the basis\n        of (right) singular vectors.  If `'diagonal_values'` is selected, the\n        diagonal values of relevant matrices are used as a proxy for the the\n        singular values (saving the cost of performing a SVD).\n\n    damping_clip : tuple, optional\n        A 2-tuple giving upper and lower bounds for the values that mu multiplies.\n        If `damping_mode == \"identity\"` then this argument is ignored, as mu always\n        multiplies a 1.0 on the diagonal if the identity matrix.  If None, then no\n        clipping is applied.\n\n    use_acceleration : bool, optional\n        Whether to include a geodesic acceleration term as suggested in\n        arXiv:1201.5885.  This is supposed to increase the rate of\n        convergence with very little overhead.  In practice we've seen\n        mixed results.\n\n    uphill_step_threshold : float, optional\n        Allows uphill steps when taking two consecutive steps in nearly\n        the same direction.  The condition for accepting an uphill step\n        is that `(uphill_step_threshold-beta)*new_objective < old_objective`,\n        where `beta` is the cosine of the angle between successive steps.\n        If `uphill_step_threshold == 0` then no uphill steps are allowed,\n        otherwise it should take a value between 1.0 and 2.0, with 1.0 being\n        the most permissive to uphill steps.\n\n    init_munu : tuple, optional\n        If not None, a (mu, nu) tuple of 2 floats giving the initial values\n        for mu and nu.\n\n    oob_check_interval : int, optional\n        Every `oob_check_interval` outer iterations, the objective function\n        (`obj_fn`) is called with a second argument 'oob_check', set to True.\n        In this case, `obj_fn` can raise a ValueError exception to indicate\n        that it is Out Of Bounds.  If `oob_check_interval` is 0 then this\n        check is never performed; if 1 then it is always performed.\n\n    oob_action : {\"reject\",\"stop\"}\n        What to do when the objective function indicates (by raising a ValueError\n        as described above).  `\"reject\"` means the step is rejected but the\n        optimization proceeds; `\"stop\"` means the optimization stops and returns\n        as converged at the last known-in-bounds point.\n\n    oob_check_mode : int, optional\n        An advanced option, expert use only.  If 0 then the optimization is\n        halted as soon as an *attempt* is made to evaluate the function out of bounds.\n        If 1 then the optimization is halted only when a would-be *accepted* step\n        is out of bounds.\n\n    resource_alloc : ResourceAllocation, optional\n        When not None, an resource allocation object used for distributing the computation\n        across multiple processors.\n\n    arrays_interface : ArraysInterface\n        An object that provides an interface for creating and manipulating data arrays.\n\n    serial_solve_proc_threshold : int optional\n        When there are fewer than this many processors, the optimizer will solve linear\n        systems serially, using SciPy on a single processor, rather than using a parallelized\n        Gaussian Elimination (with partial pivoting) algorithm coded in Python. Since SciPy's\n        implementation is more efficient, it's not worth using the parallel version until there\n        are many processors to spread the work among.\n\n    x_limits : numpy.ndarray, optional\n        A (num_params, 2)-shaped array, holding on each row the (min, max) values for the corresponding\n        parameter (element of the \"x\" vector).  If `None`, then no limits are imposed.\n\n    verbosity : int, optional\n        Amount of detail to print to stdout.\n\n    profiler : Profiler, optional\n        A profiler object used for to track timing and memory usage.\n\n    Returns\n    -------\n    x : numpy.ndarray\n        The optimal solution.\n    converged : bool\n        Whether the solution converged.\n    msg : str\n        A message indicating why the solution converged (or didn't).\n    \"\"\"\n    resource_alloc = _ResourceAllocation.cast(resource_alloc)\n    comm = resource_alloc.comm\n    printer = _VerbosityPrinter.create_printer(verbosity, comm)\n    ari = arrays_interface  # shorthand\n\n    # MEM from ..baseobjs.profiler import Profiler\n    # MEM debug_prof = Profiler(comm, True)\n    # MEM profiler = debug_prof\n\n    msg = \"\"\n    converged = False\n    global_x = x0.copy()\n    f = obj_fn(global_x)  # 'E'-type array\n    norm_f = ari.norm2_f(f)  # _np.linalg.norm(f)**2\n    half_max_nu = 2**62  # what should this be??\n    tau = 1e-3\n    alpha = 0.5  # for acceleration\n    nu = 2\n    mu = 1  # just a guess - initialized on 1st iter and only used if rejected\n\n    #Allocate potentially shared memory used in loop\n    JTJ = ari.allocate_jtj()\n    JTf = ari.allocate_jtf()\n    x = ari.allocate_jtf()\n    #x_for_jac = ari.allocate_x_for_jac()\n    if num_fd_iters > 0:\n        fdJac = ari.allocate_jac()\n\n    ari.allscatter_x(global_x, x)\n\n    if x_limits is not None:\n        x_lower_limits = ari.allocate_jtf()\n        x_upper_limits = ari.allocate_jtf()\n        ari.allscatter_x(x_limits[:, 0], x_lower_limits)\n        ari.allscatter_x(x_limits[:, 1], x_upper_limits)\n\n    if damping_basis == \"singular_values\":\n        Jac_V = ari.allocate_jtj()\n\n    if damping_mode == 'adaptive':\n        dx_lst = [ari.allocate_jtf(), ari.allocate_jtf(), ari.allocate_jtf()]\n        new_x_lst = [ari.allocate_jtf(), ari.allocate_jtf(), ari.allocate_jtf()]\n        global_new_x_lst = [global_x.copy() for i in range(3)]\n    else:\n        dx = ari.allocate_jtf()\n        new_x = ari.allocate_jtf()\n        global_new_x = global_x.copy()\n        if use_acceleration:\n            dx1 = ari.allocate_jtf()\n            dx2 = ari.allocate_jtf()\n            df2_x = ari.allocate_jtf()\n            JTdf2 = ari.allocate_jtf()\n            global_accel_x = global_x.copy()\n\n    # don't let any component change by more than ~max_dx_scale\n    if max_dx_scale:\n        max_norm_dx = (max_dx_scale**2) * len(global_x)\n    else: max_norm_dx = None\n\n    if not _np.isfinite(norm_f):\n        msg = \"Infinite norm of objective function at initial point!\"\n\n    if len(global_x) == 0:  # a model with 0 parameters - nothing to optimize\n        msg = \"No parameters to optimize\"; converged = True\n\n    # DB: from ..tools import matrixtools as _mt\n    # DB: print(\"DB F0 (%s)=\" % str(f.shape)); _mt.print_mx(f,prec=0,width=4)\n    #num_fd_iters = 1000000 # DEBUG: use finite difference iterations instead\n    # print(\"DEBUG: setting num_fd_iters == 0!\");  num_fd_iters = 0 # DEBUG\n    last_accepted_dx = None\n    min_norm_f = 1e100  # sentinel\n    best_x = ari.allocate_jtf()\n    best_x[:] = x[:]  # like x.copy() -the x-value corresponding to min_norm_f ('P'-type)\n\n    spow = 0.0  # for damping_mode == 'adaptive'\n    if damping_clip is not None:\n        def dclip(ar): return _np.clip(ar, damping_clip[0], damping_clip[1])\n    else:\n        def dclip(ar): return ar\n\n    if init_munu != \"auto\":\n        mu, nu = init_munu\n    best_x_state = (mu, nu, norm_f, f.copy(), spow, None)  # need f.copy() b/c f is objfn mem\n    rawJTJ_scratch = None\n    jtj_buf = ari.allocate_jtj_shared_mem_buf()\n\n    try:\n\n        for k in range(max_iter):  # outer loop\n            # assume global_x, x, f, fnorm hold valid values\n\n            if len(msg) > 0:\n                break  # exit outer loop if an exit-message has been set\n\n            if norm_f < f_norm2_tol:\n                if oob_check_interval <= 1:\n                    msg = \"Sum of squares is at most %g\" % f_norm2_tol\n                    converged = True; break\n                else:\n                    printer.log((\"** Converged with out-of-bounds with check interval=%d, reverting to last \"\n                                 \"know in-bounds point and setting interval=1 **\") % oob_check_interval, 2)\n                    oob_check_interval = 1\n                    x[:] = best_x[:]\n                    mu, nu, norm_f, f[:], spow, _ = best_x_state\n                    continue  # can't make use of saved JTJ yet - recompute on nxt iter\n\n            #printer.log(\"--- Outer Iter %d: norm_f = %g, mu=%g\" % (k,norm_f,mu))\n\n            if profiler: profiler.memory_check(\"custom_leastsq: begin outer iter *before de-alloc*\")\n            Jac = None\n\n            if profiler: profiler.memory_check(\"custom_leastsq: begin outer iter\")\n\n            # unnecessary b/c global_x is already valid: ari.allgather_x(x, global_x)\n            if k >= num_fd_iters:\n                Jac = jac_fn(global_x)  # 'EP'-type, but doesn't actually allocate any more mem (!)\n            else:\n                # Note: x holds only number of \"fine\"-division params - need to use global_x, and\n                # Jac only holds a subset of the derivative and element columns and rows, respectively.\n                f_fixed = f.copy()  # a static part of the distributed `f` resturned by obj_fn - MUST copy this.\n\n                pslice = ari.jac_param_slice(only_if_leader=True)\n                eps = 1e-7\n                #Don't do this: for ii, i in enumerate(range(pslice.start, pslice.stop)): (must keep procs in sync)\n                for i in range(len(global_x)):\n                    x_plus_dx = global_x.copy()\n                    x_plus_dx[i] += eps\n                    fd = (obj_fn(x_plus_dx) - f_fixed) / eps\n                    if pslice.start <= i < pslice.stop:\n                        fdJac[:, i - pslice.start] = fd\n                    #if comm is not None: comm.barrier()  # overkill for shared memory leader host barrier\n                Jac = fdJac\n\n            #DEBUG: compare with analytic jacobian (need to uncomment num_fd_iters DEBUG line above too)\n            #Jac_analytic = jac_fn(x)\n            #if _np.linalg.norm(Jac_analytic-Jac) > 1e-6:\n            #    print(\"JACDIFF = \",_np.linalg.norm(Jac_analytic-Jac),\" per el=\",\n            #          _np.linalg.norm(Jac_analytic-Jac)/Jac.size,\" sz=\",Jac.size)\n\n            # DB: from ..tools import matrixtools as _mt\n            # DB: print(\"DB JAC (%s)=\" % str(Jac.shape)); _mt.print_mx(Jac,prec=0,width=4); assert(False)\n            if profiler: profiler.memory_check(\"custom_leastsq: after jacobian:\"\n                                               + \"shape=%s, GB=%.2f\" % (str(Jac.shape),\n                                                                        Jac.nbytes / (1024.0**3)))\n            Jnorm = _np.sqrt(ari.norm2_jac(Jac))\n            xnorm = _np.sqrt(ari.norm2_x(x))\n            printer.log(\"--- Outer Iter %d: norm_f = %g, mu=%g, |x|=%g, |J|=%g\" % (k, norm_f, mu, xnorm, Jnorm))\n\n            #assert(_np.isfinite(Jac).all()), \"Non-finite Jacobian!\" # NaNs tracking\n            #assert(_np.isfinite(_np.linalg.norm(Jac))), \"Finite Jacobian has inf norm!\" # NaNs tracking\n\n            tm = _time.time()\n\n            #OLD MPI-enabled JTJ computation\n            ##if my_mpidot_qtys is None:\n            ##    my_mpidot_qtys = _mpit.distribute_for_dot(Jac.T.shape, Jac.shape, resource_alloc)\n            #JTJ, JTJ_shm = _mpit.mpidot(Jac.T, Jac, my_mpidot_qtys[0], my_mpidot_qtys[1],\n            #                            my_mpidot_qtys[2], resource_alloc, JTJ, JTJ_shm)  # _np.dot(Jac.T,Jac) 'PP'\n\n            ari.fill_jtj(Jac, JTJ, jtj_buf)\n            ari.fill_jtf(Jac, f, JTf)  # 'P'-type\n\n            if profiler: profiler.add_time(\"custom_leastsq: dotprods\", tm)\n            #assert(not _np.isnan(JTJ).any()), \"NaN in JTJ!\" # NaNs tracking\n            #assert(not _np.isinf(JTJ).any()), \"inf in JTJ! norm Jac = %g\" % _np.linalg.norm(Jac) # NaNs tracking\n            #assert(_np.isfinite(JTJ).all()), \"Non-finite JTJ!\" # NaNs tracking\n            #assert(_np.isfinite(JTf).all()), \"Non-finite JTf!\" # NaNs tracking\n\n            idiag = ari.jtj_diag_indices(JTJ)\n            norm_JTf = ari.infnorm_x(JTf)\n            norm_x = ari.norm2_x(x)  # _np.linalg.norm(x)**2\n            undamped_JTJ_diag = JTJ[idiag].copy()  # 'P'-type\n            #max_JTJ_diag = JTJ.diagonal().copy()\n\n            JTf *= -1.0; minus_JTf = JTf  # use the same memory for -JTf below (shouldn't use JTf anymore)\n            #Maybe just have a minus_JTf variable?\n\n            # FUTURE TODO: keep tallying allocated memory, i.e. array_types (stopped here)\n\n            if damping_basis == \"singular_values\":\n                # Jac = U * s * Vh; J.T * J = conj(V) * s * U.T * U * s * Vh = conj(V) * s^2 * Vh\n                # Jac_U, Jac_s, Jac_Vh = _np.linalg.svd(Jac, full_matrices=False)\n                # Jac_V = _np.conjugate(Jac_Vh.T)\n\n                global_JTJ = ari.gather_jtj(JTJ)\n                if comm is None or comm.rank == 0:\n                    global_Jac_s2, global_Jac_V = _np.linalg.eigh(global_JTJ)\n                    ari.scatter_jtj(global_Jac_V, Jac_V)\n                    comm.bcast(global_Jac_s2, root=0)\n                else:\n                    ari.scatter_jtj(None, Jac_V)\n                    global_Jac_s2 = comm.bcast(None, root=0)\n\n                #print(\"Rank %d: min s2 = %g\" % (comm.rank, min(global_Jac_s2)))\n                #if min(global_Jac_s2) < -1e-4 and (comm is None or comm.rank == 0):\n                #    print(\"WARNING: min Jac s^2 = %g (max = %g)\" % (min(global_Jac_s2), max(global_Jac_s2)))\n                assert(min(global_Jac_s2) / abs(max(global_Jac_s2)) > -1e-6), \"JTJ should be positive!\"\n                global_Jac_s = _np.sqrt(_np.clip(global_Jac_s2, 1e-12, None))  # eigvals of JTJ must be >= 0\n                global_Jac_VT_mJTf = ari.global_svd_dot(Jac_V, minus_JTf)  # = dot(Jac_V.T, minus_JTf)\n\n                #DEBUG\n                #num_large_svals = _np.count_nonzero(Jac_s > _np.max(Jac_s) / 1e2)\n                #Jac_Uproj = Jac_U[:,0:num_large_svals]\n                #JTJ_evals, JTJ_U = _np.linalg.eig(JTJ)\n                #printer.log(\"JTJ (dim=%d) eval min/max=%g, %g; %d large svals (of %d)\" % (\n                #    JTJ.shape[0], _np.min(_np.abs(JTJ_evals)), _np.max(_np.abs(JTJ_evals)),\n                #                          num_large_svals, len(Jac_s)))\n\n            if norm_JTf < jac_norm_tol:\n                if oob_check_interval <= 1:\n                    msg = \"norm(jacobian) is at most %g\" % jac_norm_tol\n                    converged = True; break\n                else:\n                    printer.log((\"** Converged with out-of-bounds with check interval=%d, reverting to last \"\n                                 \"know in-bounds point and setting interval=1 **\") % oob_check_interval, 2)\n                    oob_check_interval = 1\n                    x[:] = best_x[:]\n                    mu, nu, norm_f, f[:], spow, _ = best_x_state\n                    continue  # can't make use of saved JTJ yet - recompute on nxt iter\n\n            if k == 0:\n                if init_munu == \"auto\":\n                    if damping_mode == 'identity':\n                        mu = tau * ari.max_x(undamped_JTJ_diag)  # initial damping element\n                        #mu = min(mu, MU_TOL1)\n                    else:\n                        # initial multiplicative damping element\n                        #mu = tau # initial damping element - but this seem to low, at least for termgap...\n                        mu = min(1.0e5, ari.max_x(undamped_JTJ_diag) / norm_JTf)  # Erik's heuristic\n                        #tries to avoid making mu so large that dx is tiny and we declare victory prematurely\n                else:\n                    mu, nu = init_munu\n                rawJTJ_scratch = JTJ.copy()  # allocates the memory for a copy of JTJ so only update mem elsewhere\n                best_x_state = mu, nu, norm_f, f.copy(), spow, rawJTJ_scratch  # update mu,nu,JTJ of initial best state\n            else:\n                #on all other iterations, update JTJ of best_x_state if best_x == x, i.e. if we've just evaluated\n                # a previously accepted step that was deemed the best we've seen so far\n                if _np.allclose(x, best_x):\n                    rawJTJ_scratch[:, :] = JTJ[:, :]  # use pre-allocated memory\n                    rawJTJ_scratch[idiag] = undamped_JTJ_diag  # no damping; the \"raw\" JTJ\n                    best_x_state = best_x_state[0:5] + (rawJTJ_scratch,)  # update mu,nu,JTJ of initial \"best state\"\n\n            #determing increment using adaptive damping\n            while True:  # inner loop\n\n                if profiler: profiler.memory_check(\"custom_leastsq: begin inner iter\")\n                #print(\"DB: Pre-damping JTJ diag = [\",_np.min(_np.abs(JTJ[idiag])),_np.max(_np.abs(JTJ[idiag])),\"]\")\n\n                if damping_mode == 'identity':\n                    assert(damping_clip is None), \"damping_clip cannot be used with damping_mode == 'identity'\"\n                    if damping_basis == \"singular_values\":\n                        reg_Jac_s = global_Jac_s + mu\n\n                        #Notes:\n                        #Previously we computed inv_JTJ here and below computed dx:\n                        #inv_JTJ = _np.dot(Jac_V, _np.dot(_np.diag(1 / reg_Jac_s**2), Jac_V.T))\n                        # dx = _np.dot(Jac_V, _np.diag(1 / reg_Jac_s**2), global_Jac_VT_mJTf\n                        #But now we just compute reg_Jac_s here, and so the rest below.\n                    else:\n                        # ok if assume fine-param-proc.size == 1 (otherwise need to sync setting local JTJ)\n                        JTJ[idiag] = undamped_JTJ_diag + mu  # augment normal equations\n\n                elif damping_mode == 'JTJ':\n                    if damping_basis == \"singular_values\":\n                        reg_Jac_s = global_Jac_s + mu * dclip(global_Jac_s)\n                    else:\n                        add_to_diag = mu * dclip(undamped_JTJ_diag)\n                        JTJ[idiag] = undamped_JTJ_diag + add_to_diag  # ok if assume fine-param-proc.size == 1\n\n                elif damping_mode == 'invJTJ':\n                    if damping_basis == \"singular_values\":\n                        reg_Jac_s = global_Jac_s + mu * dclip(1.0 / global_Jac_s)\n                    else:\n                        add_to_diag = mu * dclip(1.0 / undamped_JTJ_diag)\n                        JTJ[idiag] = undamped_JTJ_diag + add_to_diag  # ok if assume fine-param-proc.size == 1\n\n                elif damping_mode == 'adaptive':\n                    if damping_basis == \"singular_values\":\n                        reg_Jac_s_lst = [global_Jac_s + mu * dclip(global_Jac_s**(spow + 0.1)),\n                                         global_Jac_s + mu * dclip(global_Jac_s**spow),\n                                         global_Jac_s + mu * dclip(global_Jac_s**(spow - 0.1))]\n                    else:\n                        add_to_diag_lst = [mu * dclip(undamped_JTJ_diag**(spow + 0.1)),\n                                           mu * dclip(undamped_JTJ_diag**spow),\n                                           mu * dclip(undamped_JTJ_diag**(spow - 0.1))]\n                else:\n                    raise ValueError(\"Invalid damping mode: %s\" % damping_mode)\n\n                #assert(_np.isfinite(JTJ).all()), \"Non-finite JTJ (inner)!\" # NaNs tracking\n                #assert(_np.isfinite(JTf).all()), \"Non-finite JTf (inner)!\" # NaNs tracking\n\n                try:\n                    if profiler: profiler.memory_check(\"custom_leastsq: before linsolve\")\n                    tm = _time.time()\n                    success = True\n\n                    if damping_basis == 'diagonal_values':\n                        if damping_mode == 'adaptive':\n                            for ii, add_to_diag in enumerate(add_to_diag_lst):\n                                JTJ[idiag] = undamped_JTJ_diag + add_to_diag  # ok if assume fine-param-proc.size == 1\n                                #dx_lst.append(_scipy.linalg.solve(JTJ, -JTf, sym_pos=True))\n                                #dx_lst.append(custom_solve(JTJ, -JTf, resource_alloc))\n                                _custom_solve(JTJ, minus_JTf, dx_lst[ii], ari, resource_alloc,\n                                              serial_solve_proc_threshold)\n                        else:\n                            #dx = _scipy.linalg.solve(JTJ, -JTf, sym_pos=True)\n                            _custom_solve(JTJ, minus_JTf, dx, ari, resource_alloc, serial_solve_proc_threshold)\n\n                    elif damping_basis == 'singular_values':\n                        #Note: above solves JTJ*x = -JTf => x = inv_JTJ * (-JTf)\n                        # but: J = U*s*Vh => JTJ = (VhT*s*UT)(U*s*Vh) = VhT*s^2*Vh, and inv_Vh = V b/c V is unitary\n                        # so inv_JTJ = inv_Vh * 1/s^2 * inv_VhT = V * 1/s^2 * VT  = (N,K)*(K,K)*(K,N) if use psuedoinv\n\n                        if damping_mode == 'adaptive':\n                            #dx_lst = [_np.dot(ijtj, minus_JTf) for ijtj in inv_JTJ_lst]  # special case\n                            for ii, s in enumerate(reg_Jac_s_lst):\n                                ari.fill_dx_svd(Jac_V, (1 / s**2) * global_Jac_VT_mJTf, dx_lst[ii])\n                        else:\n                            # dx = _np.dot(inv_JTJ, minus_JTf)\n                            ari.fill_dx_svd(Jac_V, (1 / reg_Jac_s**2) * global_Jac_VT_mJTf, dx)\n                    else:\n                        raise ValueError(\"Invalid damping_basis = '%s'\" % damping_basis)\n\n                    if profiler: profiler.add_time(\"custom_leastsq: linsolve\", tm)\n                #except _np.linalg.LinAlgError:\n                except _scipy.linalg.LinAlgError:  # DIST TODO - a different kind of exception caught?\n                    success = False\n\n                if success and use_acceleration:  # Find acceleration term:\n                    assert(damping_mode != 'adaptive'), \"Cannot use acceleration in adaptive mode (yet)\"\n                    assert(damping_basis != 'singular_values'), \"Cannot use acceleration w/singular-value basis (yet)\"\n                    df2_eps = 1.0\n                    try:\n                        #df2 = (obj_fn(x + df2_dx) + obj_fn(x - df2_dx) - 2 * f) / \\\n                        #    df2_eps**2  # 2nd deriv of f along dx direction\n                        # Above line expanded to reuse shared memory\n                        df2 = -2 * f\n                        df2_x[:] = x + df2_eps * dx\n                        ari.allgather_x(df2_x, global_accel_x)\n                        df2 += obj_fn(global_accel_x)\n                        df2_x[:] = x - df2_eps * dx\n                        ari.allgather_x(df2_x, global_accel_x)\n                        df2 += obj_fn(global_accel_x)\n                        df2 /= df2_eps**2\n                        f[:] = df2; df2 = f  # use `f` as an appropriate shared-mem object for fill_jtf below\n\n                        ari.fill_jtf(Jac, df2, JTdf2)\n                        JTdf2 *= -0.5  # keep using JTdf2 memory in solve call below\n                        #dx2 = _scipy.linalg.solve(JTJ, -0.5 * JTdf2, sym_pos=True)  # Note: JTJ not init w/'adaptive'\n                        _custom_solve(JTJ, JTdf2, dx2, ari, resource_alloc, serial_solve_proc_threshold)\n                        dx1[:] = dx[:]\n                        dx += dx2  # add acceleration term to dx\n                    except _scipy.linalg.LinAlgError:\n                        print(\"WARNING - linear solve failed for acceleration term!\")\n                        # but ok to continue - just stick with first order term\n                    except ValueError:\n                        print(\"WARNING - value error during computation of acceleration term!\")\n\n                reject_msg = \"\"\n                if profiler: profiler.memory_check(\"custom_leastsq: after linsolve\")\n                if success:  # linear solve succeeded\n                    #dx = _hack_dx(obj_fn, x, dx, Jac, JTJ, JTf, f, norm_f)\n\n                    if damping_mode != 'adaptive':\n                        new_x[:] = x + dx\n                        norm_dx = ari.norm2_x(dx)  # _np.linalg.norm(dx)**2\n\n                        #ensure dx isn't too large - don't let any component change by more than ~max_dx_scale\n                        if max_norm_dx and norm_dx > max_norm_dx:\n                            dx *= _np.sqrt(max_norm_dx / norm_dx)\n                            new_x[:] = x + dx\n                            norm_dx = ari.norm2_x(dx)  # _np.linalg.norm(dx)**2\n\n                        #apply x limits (bounds)\n                        if x_limits is not None:\n                            # Approach 1: project x into valid space by simply clipping out-of-bounds values\n                            for i, (x_el, lower, upper) in enumerate(zip(x, x_lower_limits, x_upper_limits)):\n                                if new_x[i] < lower:\n                                    new_x[i] = lower\n                                    dx[i] = lower - x_el\n                                elif new_x[i] > upper:\n                                    new_x[i] = upper\n                                    dx[i] = upper - x_el\n                            norm_dx = ari.norm2_x(dx)  # _np.linalg.norm(dx)**2\n\n                            # Approach 2: by scaling back dx (seems less good, but here in case we want it later)\n                            # # minimally reduce dx s.t. new_x = x + dx so that x_lower_limits <= x+dx <= x_upper_limits\n                            # # x_lower_limits - x <= dx <= x_upper_limits - x.  Note: use potentially updated dx from\n                            # # max_norm_dx block above.  For 0 <= scale <= 1,\n                            # # 1) require x + scale*dx - x_upper_limits <= 0 => scale <= (x_upper_limits - x) / dx\n                            # #    [Note: above assumes dx > 0 b/c if not it moves x away from bound and scale < 0]\n                            # #    so if scale >= 0, then scale = min((x_upper_limits - x) / dx, 1.0)\n                            # scale = None\n                            # new_x[:] = (x_upper_limits - x) / dx\n                            # new_x_min = ari.min_x(new_x)\n                            # if 0 <= new_x_min < 1.0:\n                            #     scale = new_x_min\n                            #\n                            # # 2) require x + scale*dx - x_lower_limits <= 0 => scale <= (x - x_lower_limits) / (-dx)\n                            # new_x[:] = (x_lower_limits - x) / dx\n                            # new_x_min = ari.min_x(new_x)\n                            # if 0 <= new_x_min < 1.0:\n                            #     scale = new_x_min if (scale is None) else min(new_x_min, scale)\n                            #\n                            # if scale is not None:\n                            #     dx *= scale\n                            # new_x[:] = x + dx\n                            # norm_dx = ari.norm2_x(dx)  # _np.linalg.norm(dx)**2\n\n                    else:\n                        for dx, new_x in zip(dx_lst, new_x_lst):\n                            new_x[:] = x + dx\n                        norm_dx_lst = [ari.norm2_x(dx) for dx in dx_lst]\n\n                        #ensure dx isn't too large - don't let any component change by more than ~max_dx_scale\n                        if max_norm_dx:\n                            for i, norm_dx in enumerate(norm_dx_lst):\n                                if norm_dx > max_norm_dx:\n                                    dx_lst[i] *= _np.sqrt(max_norm_dx / norm_dx)\n                                    new_x_lst[i][:] = x + dx_lst[i]\n                                    norm_dx_lst[i] = ari.norm2_x(dx_lst[i])\n\n                        #apply x limits (bounds)\n                        if x_limits is not None:\n                            for i, (dx, new_x) in enumerate(zip(dx_lst, new_x_lst)):\n                                # Do same thing as above for each possible dx in dx_lst\n                                # Approach 1:\n                                for ii, (x_el, lower, upper) in enumerate(zip(x, x_lower_limits, x_upper_limits)):\n                                    if new_x[ii] < lower:\n                                        new_x[ii] = lower\n                                        dx[ii] = lower - x_el\n                                    elif new_x[ii] > upper:\n                                        new_x[ii] = upper\n                                        dx[ii] = upper - x_el\n                                norm_dx_lst[i] = ari.norm2_x(dx)  # _np.linalg.norm(dx)**2\n\n                                # Approach 2:\n                                # scale = None\n                                # new_x[:] = (x_upper_limits - x) / dx\n                                # new_x_min = ari.min_x(new_x)\n                                # if 0 <= new_x_min < 1.0:\n                                #     scale = new_x_min\n                                #\n                                # new_x[:] = (x_lower_limits - x) / dx\n                                # new_x_min = ari.min_x(new_x)\n                                # if 0 <= new_x_min < 1.0:\n                                #     scale = new_x_min if (scale is None) else min(new_x_min, scale)\n                                #\n                                # if scale is not None:\n                                #     dx *= scale\n                                # new_x[:] = x + dx\n                                # norm_dx_lst[i] = ari.norm2_x(dx)\n\n                        norm_dx = norm_dx_lst[1]  # just use center value for printing & checks below\n\n                    printer.log(\"  - Inner Loop: mu=%g, norm_dx=%g\" % (mu, norm_dx), 2)\n                    #MEM if profiler: profiler.memory_check(\"custom_leastsq: mid inner loop\")\n                    #print(\"DB: new_x = \", new_x)\n\n                    if norm_dx < (rel_xtol**2) * norm_x:  # and mu < MU_TOL2:\n                        if oob_check_interval <= 1:\n                            msg = \"Relative change, |dx|/|x|, is at most %g\" % rel_xtol\n                            converged = True; break\n                        else:\n                            printer.log((\"** Converged with out-of-bounds with check interval=%d, reverting to last \"\n                                         \"know in-bounds point and setting interval=1 **\") % oob_check_interval, 2)\n                            oob_check_interval = 1\n                            x[:] = best_x[:]\n                            mu, nu, norm_f, f[:], spow, _ = best_x_state\n                            break\n\n                    if norm_dx > (norm_x + rel_xtol) / (_MACH_PRECISION**2):\n                        msg = \"(near-)singular linear system\"; break\n\n                    if oob_check_interval > 0 and oob_check_mode == 0:\n                        if k % oob_check_interval == 0:\n                            #Check to see if objective function is out of bounds\n\n                            in_bounds = []\n                            if damping_mode == 'adaptive':\n                                new_f_lst = []\n                                for new_x, global_new_x in zip(new_x_lst, global_new_x_lst):\n                                    ari.allgather_x(new_x, global_new_x)\n                                    try:\n                                        new_f = obj_fn(global_new_x, oob_check=True)\n                                    except ValueError:  # Use this to mean - \"not allowed, but don't stop\"\n                                        in_bounds.append(False)\n                                        new_f_lst.append(None)  # marks OOB attempts that shouldn't be considered\n                                    else:  # no exception raised\n                                        in_bounds.append(True)\n                                        new_f_lst.append(new_f.copy())\n                            else:\n                                #print(\"DB: Trying |x| = \", _np.linalg.norm(new_x), \" |x|^2=\", _np.dot(new_x,new_x))\n                                # MEM if profiler: profiler.memory_check(\"custom_leastsq: before oob_check obj_fn\")\n                                ari.allgather_x(new_x, global_new_x)\n                                try:\n                                    new_f = obj_fn(global_new_x, oob_check=True)\n                                except ValueError:  # Use this to mean - \"not allowed, but don't stop\"\n                                    in_bounds.append(False)\n                                else:\n                                    in_bounds.append(True)\n\n                            if any(in_bounds):  # In adaptive mode, proceed if *any* cases are in-bounds\n                                new_x_is_allowed = True\n                                new_x_is_known_inbounds = True\n                            else:\n                                MIN_STOP_ITER = 1  # the minimum iteration where an OOB objective stops the optimization\n                                if oob_action == \"reject\" or k < MIN_STOP_ITER:\n                                    new_x_is_allowed = False  # (and also not in bounds)\n                                elif oob_action == \"stop\":\n                                    if oob_check_interval == 1:\n                                        msg = \"Objective function out-of-bounds! STOP\"\n                                        converged = True; break\n                                    else:  # reset to last know in-bounds point and not do oob check every step\n                                        printer.log(\n                                            (\"** Hit out-of-bounds with check interval=%d, reverting to last \"\n                                             \"know in-bounds point and setting interval=1 **\") % oob_check_interval, 2)\n                                        oob_check_interval = 1\n                                        x[:] = best_x[:]\n                                        mu, nu, norm_f, f[:], spow, _ = best_x_state  # can't make use of saved JTJ yet\n                                        break  # restart next outer loop\n                                else:\n                                    raise ValueError(\"Invalid `oob_action`: '%s'\" % oob_action)\n                        else:  # don't check this time\n\n                            if damping_mode == 'adaptive':\n                                new_f_lst = []\n                                for new_x, global_new_x in zip(new_x_lst, global_new_x_lst):\n                                    ari.allgather_x(new_x, global_new_x)\n                                    new_f_lst.append(obj_fn(global_new_x).copy())\n                            else:\n                                ari.allgather_x(new_x, global_new_x)\n                                new_f = obj_fn(global_new_x, oob_check=False)\n\n                            new_x_is_allowed = True\n                            new_x_is_known_inbounds = False\n                    else:\n                        #Just evaluate objective function normally; never check for in-bounds condition\n                        if damping_mode == 'adaptive':\n                            new_f_lst = []\n                            for new_x, global_new_x in zip(new_x_lst, global_new_x_lst):\n                                ari.allgather_x(new_x, global_new_x)\n                                new_f_lst.append(obj_fn(global_new_x).copy())\n                        else:\n                            ari.allgather_x(new_x, global_new_x)\n                            new_f = obj_fn(global_new_x)\n\n                        new_x_is_allowed = True\n                        new_x_is_known_inbounds = bool(oob_check_interval == 0)  # consider \"in bounds\" if not checking\n\n                    if new_x_is_allowed:\n\n                        # MEM if profiler: profiler.memory_check(\"custom_leastsq: after obj_fn\")\n                        if damping_mode == 'adaptive':\n                            norm_new_f_lst = [ari.norm2_f(new_f) if (new_f is not None) else 1e100\n                                              for new_f in new_f_lst]  # 1e100 so we don't choose OOB adaptive cases\n                            if any([not _np.isfinite(norm_new_f) for norm_new_f in norm_new_f_lst]):  # avoid inf loop\n                                msg = \"Infinite norm of objective function!\"; break\n\n                            #iMin = _np.argmin(norm_new_f_lst)  # pick lowest (best) objective\n                            gain_ratio_lst = [(norm_f - nnf) / ari.dot_x(dx, mu * dx + minus_JTf)\n                                              for (nnf, dx) in zip(norm_new_f_lst, dx_lst)]\n                            iMin = _np.argmax(gain_ratio_lst)  # pick highest (best) gain ratio\n                            # but expected decrease is |f|^2 = grad(fTf) * dx = (grad(fT)*f + fT*grad(f)) * dx\n                            #                                                 = (JT*f + fT*J) * dx\n                            # <<more explanation>>\n                            norm_new_f = norm_new_f_lst[iMin]\n                            new_f = new_f_lst[iMin]\n                            new_x = new_x_lst[iMin]\n                            global_new_x = global_new_x_lst[iMin]\n                            dx = dx_lst[iMin]\n                            if iMin == 0: spow = min(1.0, spow + 0.1)\n                            elif iMin == 2: spow = max(-1.0, spow - 0.1)\n                            printer.log(\"ADAPTIVE damping => i=%d b/c fs=[%s] gains=[%s] => spow=%g\" % (\n                                iMin, \", \".join([\"%.3g\" % v for v in norm_new_f_lst]),\n                                \", \".join([\"%.3g\" % v for v in gain_ratio_lst]), spow))\n\n                        else:\n                            norm_new_f = ari.norm2_f(new_f)  # _np.linalg.norm(new_f)**2\n                            if not _np.isfinite(norm_new_f):  # avoid infinite loop...\n                                msg = \"Infinite norm of objective function!\"; break\n\n                        # dL = expected decrease in ||F||^2 from linear model\n                        dL = ari.dot_x(dx, mu * dx + minus_JTf)\n                        dF = norm_f - norm_new_f      # actual decrease in ||F||^2\n\n                        #DEBUG - see if cos_phi < 0.001, say, might work as a convergence criterion\n                        #if damping_basis == 'singular_values':\n                        #    # projection of new_f onto solution tangent plane\n                        #    new_f_proj = _np.dot(Jac_Uproj, _np.dot(Jac_Uproj.T, new_f))\n                        #    # angle between residual vec and tangent plane\n                        #    cos_phi = _np.sqrt(_np.dot(new_f_proj, new_f_proj) / norm_new_f)\n                        #    #grad_f_norm = _np.linalg.norm(mu * dx - JTf)\n                        #else:\n                        #    cos_phi = 0\n\n                        if dF <= 0 and uphill_step_threshold > 0:\n                            beta = 0 if last_accepted_dx is None else \\\n                                (ari.dot_x(dx, last_accepted_dx)\n                                    / _np.sqrt(ari.norm2_x(dx) * ari.norm2_x(last_accepted_dx)))\n                            uphill_ok = (uphill_step_threshold - beta) * norm_new_f < min(min_norm_f, norm_f)\n                        else:\n                            uphill_ok = False\n\n                        if use_acceleration:\n                            accel_ratio = 2 * _np.sqrt(ari.norm2_x(dx2) / ari.norm2_x(dx1))\n                            printer.log(\"      (cont): norm_new_f=%g, dL=%g, dF=%g, reldL=%g, reldF=%g aC=%g\" %\n                                        (norm_new_f, dL, dF, dL / norm_f, dF / norm_f, accel_ratio), 2)\n\n                        else:\n                            printer.log(\"      (cont): norm_new_f=%g, dL=%g, dF=%g, reldL=%g, reldF=%g\" %\n                                        (norm_new_f, dL, dF, dL / norm_f, dF / norm_f), 2)\n                            accel_ratio = 0.0\n\n                        if dL / norm_f < rel_ftol and dF >= 0 and dF / norm_f < rel_ftol \\\n                           and dF / dL < 2.0 and accel_ratio <= alpha:\n                            if oob_check_interval <= 1:  # (if 0 then no oob checking is done)\n                                msg = \"Both actual and predicted relative reductions in the\" + \\\n                                    \" sum of squares are at most %g\" % rel_ftol\n                                converged = True; break\n                            else:\n                                printer.log((\"** Converged with out-of-bounds with check interval=%d, \"\n                                             \"reverting to last know in-bounds point and setting \"\n                                             \"interval=1 **\") % oob_check_interval, 2)\n                                oob_check_interval = 1\n                                x[:] = best_x[:]\n                                mu, nu, norm_f, f[:], spow, _ = best_x_state  # can't make use of saved JTJ yet\n                                break\n\n                        # MEM if profiler: profiler.memory_check(\"custom_leastsq: before success\")\n\n                        if (dL > 0 and dF > 0 and accel_ratio <= alpha) or uphill_ok:\n                            #Check whether an otherwise acceptable solution is in-bounds\n                            if oob_check_mode == 1 and oob_check_interval > 0 and k % oob_check_interval == 0:\n                                #Check to see if objective function is out of bounds\n                                try:\n                                    #print(\"DB: Trying |x| = \", _np.linalg.norm(new_x), \" |x|^2=\", _np.dot(new_x,new_x))\n                                    # MEM if profiler:\n                                    # MEM    profiler.memory_check(\"custom_leastsq: before oob_check obj_fn mode 1\")\n                                    obj_fn(global_new_x, oob_check=True)  # don't actually need return val (== new_f)\n                                    new_f_is_allowed = True\n                                    new_x_is_known_inbounds = True\n                                except ValueError:  # Use this to mean - \"not allowed, but don't stop\"\n                                    MIN_STOP_ITER = 1  # the minimum iteration where an OOB objective can stops the opt.\n                                    if oob_action == \"reject\" or k < MIN_STOP_ITER:\n                                        new_f_is_allowed = False  # (and also not in bounds)\n                                    elif oob_action == \"stop\":\n                                        if oob_check_interval == 1:\n                                            msg = \"Objective function out-of-bounds! STOP\"\n                                            converged = True; break\n                                        else:  # reset to last know in-bounds point and not do oob check every step\n                                            printer.log(\n                                                (\"** Hit out-of-bounds with check interval=%d, reverting to last \"\n                                                 \"know in-bounds point and setting interval=1 **\") % oob_check_interval,\n                                                2)\n                                            oob_check_interval = 1\n                                            x[:] = best_x[:]\n                                            mu, nu, norm_f, f[:], spow, _ = best_x_state  # can't use of saved JTJ yet\n                                            break  # restart next outer loop\n                                    else:\n                                        raise ValueError(\"Invalid `oob_action`: '%s'\" % oob_action)\n                            else:\n                                new_f_is_allowed = True\n\n                            if new_f_is_allowed:\n                                # reduction in error: increment accepted!\n                                t = 1.0 - (2 * dF / dL - 1.0)**3  # dF/dL == gain ratio\n                                # always reduce mu for accepted step when |dx| is small\n                                mu_factor = max(t, 1.0 / 3.0) if norm_dx > 1e-8 else 0.3\n                                mu *= mu_factor\n                                nu = 2\n                                x[:] = new_x[:]; f[:] = new_f[:]; norm_f = norm_new_f\n                                global_x[:] = global_new_x[:]\n                                printer.log(\"      Accepted%s! gain ratio=%g  mu * %g => %g\"\n                                            % (\" UPHILL\" if uphill_ok else \"\", dF / dL, mu_factor, mu), 2)\n                                last_accepted_dx = dx.copy()\n                                if new_x_is_known_inbounds and norm_f < min_norm_f:\n                                    min_norm_f = norm_f\n                                    best_x[:] = x[:]\n                                    best_x_state = (mu, nu, norm_f, f.copy(), spow, None)\n                                    #Note: we use rawJTJ=None above because the current `JTJ` was evaluated\n                                    # at the *last* x-value -- we need to wait for the next outer loop\n                                    # to compute the JTJ for this best_x_state\n\n                                #assert(_np.isfinite(x).all()), \"Non-finite x!\" # NaNs tracking\n                                #assert(_np.isfinite(f).all()), \"Non-finite f!\" # NaNs tracking\n\n                                ##Check to see if we *would* switch to Q-N method in a hybrid algorithm\n                                #new_Jac = jac_fn(new_x)\n                                #new_JTf = _np.dot(new_Jac.T,new_f)\n                                #print(\" CHECK: %g < %g ?\" % (_np.linalg.norm(new_JTf,\n                                #    ord=_np.inf),0.02 * _np.linalg.norm(new_f)))\n\n                                break  # exit inner loop normally\n                            else:\n                                reject_msg = \" (out-of-bounds)\"\n                    else:\n                        reject_msg = \" (out-of-bounds)\"\n\n                else:\n                    reject_msg = \" (LinSolve Failure)\"\n\n                # if this point is reached, either the linear solve failed\n                # or the error did not reduce.  In either case, reject increment.\n\n                #Increase damping (mu), then increase damping factor to\n                # accelerate further damping increases.\n                mu *= nu\n                if nu > half_max_nu:  # watch for nu getting too large (&overflow)\n                    msg = \"Stopping after nu overflow!\"; break\n                nu = 2 * nu\n                printer.log(\"      Rejected%s!  mu => mu*nu = %g, nu => 2*nu = %g\"\n                            % (reject_msg, mu, nu), 2)\n            #end of inner loop\n\n        #end of outer loop\n        else:\n            #if no break stmt hit, then we've exceeded max_iter\n            msg = \"Maximum iterations (%d) exceeded\" % max_iter\n            converged = True  # call result \"converged\" even in this case, but issue warning:\n            printer.warning(\"Treating result as *converged* after maximum iterations (%d) were exceeded.\" % max_iter)\n\n    except KeyboardInterrupt:\n        if comm is not None:\n            # ensure all procs agree on what best_x is (in case the interrupt occurred around x being updated)\n            comm.Bcast(best_x, root=0)\n            printer.log(\"Rank %d caught keyboard interrupt!  Returning the current solution as being *converged*.\"\n                        % comm.Get_rank())\n        else:\n            printer.log(\"Caught keyboard interrupt!  Returning the current solution as being *converged*.\")\n        msg = \"Keyboard interrupt!\"\n        converged = True\n\n    if comm is not None:\n        comm.barrier()  # Just to be safe, so procs stay synchronized and we don't free anything too soon\n\n    ari.deallocate_jtj(JTJ)\n    ari.deallocate_jtf(JTf)\n    ari.deallocate_jtf(x)\n    ari.deallocate_jtj_shared_mem_buf(jtj_buf)\n    #ari.deallocate_x_for_jac(x_for_jac)\n\n    if x_limits is not None:\n        ari.deallocate_jtf(x_lower_limits)\n        ari.deallocate_jtf(x_upper_limits)\n\n    if damping_basis == \"singular_values\":\n        ari.deallocate_jtj(Jac_V)\n\n    if damping_mode == 'adaptive':\n        for xx in dx_lst: ari.deallocate_jtf(xx)\n        for xx in new_x_lst: ari.deallocate_jtf(xx)\n    else:\n        ari.deallocate_jtf(dx)\n        ari.deallocate_jtf(new_x)\n        if use_acceleration:\n            ari.deallocate_jtf(dx1)\n            ari.deallocate_jtf(dx2)\n            ari.deallocate_jtf(df2_x)\n            ari.deallocate_jtf(JTdf2)\n\n    if num_fd_iters > 0:\n        ari.deallocate_jac(fdJac)\n\n    ari.allgather_x(best_x, global_x)\n    ari.deallocate_jtf(best_x)\n\n    #JTJ[idiag] = undampled_JTJ_diag #restore diagonal\n    mu, nu, norm_f, f[:], spow, rawJTJ = best_x_state\n\n    global_f = _np.empty(ari.global_num_elements(), 'd')\n    ari.allgather_f(f, global_f)\n\n    return global_x, converged, msg, mu, nu, norm_f, global_f, rawJTJ\n    #solution = _optResult()\n    #solution.x = x; solution.fun = f\n    #solution.success = converged\n    #solution.message = msg\n    #return solution\n\n\ndef _hack_dx(obj_fn, x, dx, jac, jtj, jtf, f, norm_f):\n    #HACK1\n    #if nRejects >= 2:\n    #    dx = -(10.0**(1-nRejects))*x\n    #    print(\"HACK - setting dx = -%gx!\" % 10.0**(1-nRejects))\n    #    return dx\n\n    #HACK2\n    if True:\n        print(\"HACK2 - trying to find a good dx by iteratively stepping in each direction...\")\n\n        test_f = obj_fn(x + dx); cmp_normf = _np.dot(test_f, test_f)\n        print(\"Compare with suggested step => \", cmp_normf)\n        STEP = 0.0001\n\n        #import bpdb; bpdb.set_trace()\n        #gradient = -jtf\n        test_dx = _np.zeros(len(dx), 'd')\n        last_normf = norm_f\n        for ii in range(len(dx)):\n\n            #Try adding\n            while True:\n                test_dx[ii] += STEP\n                test_f = obj_fn(x + test_dx); test_normf = _np.dot(test_f, test_f)\n                if test_normf < last_normf:\n                    last_normf = test_normf\n                else:\n                    test_dx[ii] -= STEP\n                    break\n\n            if test_dx[ii] == 0:  # then try subtracting\n                while True:\n                    test_dx[ii] -= STEP\n                    test_f = obj_fn(x + test_dx); test_normf = _np.dot(test_f, test_f)\n                    if test_normf < last_normf:\n                        last_normf = test_normf\n                    else:\n                        test_dx[ii] += STEP\n                        break\n\n            if abs(test_dx[ii]) > 1e-6:\n                test_prediction = norm_f + _np.dot(-2 * jtf, test_dx)\n                tp2_f = f + _np.dot(jac, test_dx)\n                test_prediction2 = _np.dot(tp2_f, tp2_f)\n                cmp_dx = dx  # -jtf\n                print(\" -> Adjusting index \", ii, \":\", x[ii], \"+\", test_dx[ii], \" => \", last_normf, \"(cmp w/dx: \",\n                      cmp_dx[ii], test_prediction, test_prediction2, \") \",\n                      \"YES\" if test_dx[ii] * cmp_dx[ii] > 0 else \"NO\")\n\n        if _np.linalg.norm(test_dx) > 0 and last_normf < cmp_normf:\n            print(\"FOUND HACK dx w/norm = \", _np.linalg.norm(test_dx))\n            return test_dx\n        else:\n            print(\"KEEPING ORIGINAL dx\")\n\n    #HACK3\n    if False:\n        print(\"HACK3 - checking if there's a simple dx that is better...\")\n        test_f = obj_fn(x + dx); cmp_normf = _np.dot(test_f, test_f)\n        orig_prediction = norm_f + _np.dot(2 * jtf, dx)\n        Jdx = _np.dot(jac, dx)\n        op2_f = f + Jdx\n        orig_prediction2 = _np.dot(op2_f, op2_f)\n        # main objective = fT*f = norm_f\n        # at new x => (f+J*dx)T * (f+J*dx) = norm_f + JdxT*f + fT*Jdx\n        #                                  = norm_f + 2*(fT*J)dx (b/c transpose of real# does nothing)\n        #                                  = norm_f + 2*dxT*(JT*f)\n        # prediction 2 also includes (J*dx)T * (J*dx) term = dxT * (jtj) * dx\n        orig_prediction3 = orig_prediction + _np.dot(Jdx, Jdx)\n        norm_dx = _np.linalg.norm(dx)\n        print(\"Compare with suggested |dx| = \", norm_dx, \" => \", cmp_normf,\n              \"(predicted: \", orig_prediction, orig_prediction2, orig_prediction3)\n        STEP = norm_dx  # 0.0001\n\n        #import bpdb; bpdb.set_trace()\n        test_dx = _np.zeros(len(dx), 'd')\n        best_ii = -1; best_normf = norm_f; best_dx = 0\n        for ii in range(len(dx)):\n\n            #Try adding a small amount\n            test_dx[ii] = STEP\n            test_f = obj_fn(x + test_dx); test_normf = _np.dot(test_f, test_f)\n            if test_normf < best_normf:\n                best_normf = test_normf\n                best_dx = STEP\n                best_ii = ii\n            else:\n                test_dx[ii] = -STEP\n                test_f = obj_fn(x + test_dx); test_normf = _np.dot(test_f, test_f)\n                if test_normf < best_normf:\n                    best_normf = test_normf\n                    best_dx = -STEP\n                    best_ii = ii\n            test_dx[ii] = 0\n\n        test_dx[best_ii] = best_dx\n        test_prediction = norm_f + _np.dot(2 * jtf, test_dx)\n        tp2_f = f + _np.dot(jac, test_dx)\n        test_prediction2 = _np.dot(tp2_f, tp2_f)\n\n        jj = _np.argmax(_np.abs(dx))\n        print(\"Best decrease = index\", best_ii, \":\", x[best_ii], '+', best_dx, \"==>\",\n              best_normf, \" (predictions: \", test_prediction, test_prediction2, \")\")\n        print(\" compare with original dx[\", best_ii, \"]=\", dx[best_ii],\n              \"YES\" if test_dx[best_ii] * dx[best_ii] > 0 else \"NO\")\n        print(\" max of abs(dx) is index \", jj, \":\", dx[jj], \"yes\" if jj == best_ii else \"no\")\n\n        if _np.linalg.norm(test_dx) > 0 and best_normf < cmp_normf:\n            print(\"FOUND HACK dx w/norm = \", _np.linalg.norm(test_dx))\n            return test_dx\n        else:\n            print(\"KEEPING ORIGINAL dx\")\n    return dx\n\n\n#Wikipedia-version of LM algorithm, testing mu and mu/nu damping params and taking\n# mu/nu => new_mu if acceptable...  This didn't seem to perform well, but maybe just\n# needs some tweaking, so leaving it commented here for reference\n#def custom_leastsq_wikip(obj_fn, jac_fn, x0, f_norm_tol=1e-6, jac_norm_tol=1e-6,\n#                   rel_tol=1e-6, max_iter=100, comm=None, verbosity=0, profiler=None):\n#    msg = \"\"\n#    converged = False\n#    x = x0\n#    f = obj_fn(x)\n#    norm_f = _np.linalg.norm(f)\n#    tau = 1e-3 #initial mu\n#    nu = 1.3\n#    my_cols_slice = None\n#\n#\n#    if not _np.isfinite(norm_f):\n#        msg = \"Infinite norm of objective function at initial point!\"\n#\n#    for k in range(max_iter): #outer loop\n#        # assume x, f, fnorm hold valid values\n#\n#        if len(msg) > 0:\n#            break #exit outer loop if an exit-message has been set\n#\n#        if norm_f < f_norm_tol:\n#            msg = \"norm(objectivefn) is small\"\n#            converged = True; break\n#\n#        if verbosity > 0:\n#            print(\"--- Outer Iter %d: norm_f = %g\" % (k,norm_f))\n#\n#        if profiler: profiler.mem_check(\"custom_leastsq: begin outer iter *before de-alloc*\")\n#        jac = None; jtj = None; jtf = None\n#\n#        if profiler: profiler.mem_check(\"custom_leastsq: begin outer iter\")\n#        jac = jac_fn(x)\n#        if profiler: profiler.mem_check(\"custom_leastsq: after jacobian:\"\n#                                        + \"shape=%s, GB=%.2f\" % (str(jac.shape),\n#                                                        jac.nbytes/(1024.0**3)) )\n#\n#        tm = _time.time()\n#        if my_cols_slice is None:\n#            my_cols_slice = _mpit.distribute_for_dot(jac.shape[0], comm)\n#        jtj = _mpit.mpidot(jac.T,jac,my_cols_slice,comm)   #_np.dot(jac.T,jac)\n#        jtf = _np.dot(jac.T,f)\n#        if profiler: profiler.add_time(\"custom_leastsq: dotprods\",tm)\n#\n#        idiag = _np.diag_indices_from(jtj)\n#        norm_JTf = _np.linalg.norm(jtf) #, ord='inf')\n#        norm_x = _np.linalg.norm(x)\n#        undampled_JTJ_diag = jtj.diagonal().copy()\n#\n#        if norm_JTf < jac_norm_tol:\n#            msg = \"norm(jacobian) is small\"\n#            converged = True; break\n#\n#        if k == 0:\n#            mu = tau #* _np.max(undampled_JTJ_diag) # initial damping element\n#        #mu = tau #* _np.max(undampled_JTJ_diag) # initial damping element\n#\n#        #determing increment using adaptive damping\n#        while True:  #inner loop\n#\n#            ### Evaluate with mu' = mu / nu\n#            mu = mu / nu\n#            if profiler: profiler.mem_check(\"custom_leastsq: begin inner iter\")\n#            jtj[idiag] *= (1.0 + mu) # augment normal equations\n#            #jtj[idiag] += mu # augment normal equations\n#\n#            try:\n#                if profiler: profiler.mem_check(\"custom_leastsq: before linsolve\")\n#                tm = _time.time()\n#                success = True\n#                dx = _np.linalg.solve(jtj, -jtf)\n#                if profiler: profiler.add_time(\"custom_leastsq: linsolve\",tm)\n#            except _np.linalg.LinAlgError:\n#                success = False\n#\n#            if profiler: profiler.mem_check(\"custom_leastsq: after linsolve\")\n#            if success: #linear solve succeeded\n#                new_x = x + dx\n#                norm_dx = _np.linalg.norm(dx)\n#\n#                #if verbosity > 1:\n#                #    print(\"--- Inner Loop: mu=%g, norm_dx=%g\" % (mu,norm_dx))\n#\n#                if norm_dx < rel_tol*norm_x: #use squared qtys instead (speed)?\n#                    msg = \"relative change in x is small\"\n#                    converged = True; break\n#\n#                if norm_dx > (norm_x+rel_tol)/_MACH_PRECISION:\n#                    msg = \"(near-)singular linear system\"; break\n#\n#                new_f = obj_fn(new_x)\n#                if profiler: profiler.mem_check(\"custom_leastsq: after obj_fn\")\n#                norm_new_f = _np.linalg.norm(new_f)\n#                if not _np.isfinite(norm_new_f): # avoid infinite loop...\n#                    msg = \"Infinite norm of objective function!\"; break\n#\n#                dF = norm_f - norm_new_f\n#                if dF > 0: #accept step\n#                    #print(\"      Accepted!\")\n#                    x,f, norm_f = new_x, new_f, norm_new_f\n#                    nu = 1.3\n#                    break # exit inner loop normally\n#                else:\n#                    mu *= nu #increase mu\n#            else:\n#                #Linear solve failed:\n#                mu *= nu #increase mu\n#                nu = 2*nu\n#\n#            jtj[idiag] = undampled_JTJ_diag #restore diagonal for next inner loop iter\n#        #end of inner loop\n#    #end of outer loop\n#    else:\n#        #if no break stmt hit, then we've exceeded max_iter\n#        msg = \"Maximum iterations (%d) exceeded\" % max_iter\n#\n#    return x, converged, msg\n", "meta": {"hexsha": "3fdd893dc0ccb10a747f92dac984a59be5de9f37", "size": 78612, "ext": "py", "lang": "Python", "max_stars_repo_path": "pygsti/optimize/customlm.py", "max_stars_repo_name": "maij/pyGSTi", "max_stars_repo_head_hexsha": "70e83e05fa689f53550feb3914c4fac40ca4a943", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2016-01-28T05:02:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T07:46:33.000Z", "max_issues_repo_path": "pygsti/optimize/customlm.py", "max_issues_repo_name": "00mjk/pyGSTi", "max_issues_repo_head_hexsha": "4f8bf5337b01b7afcb7b0580b717b5d1fe281be4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 113, "max_issues_repo_issues_event_min_datetime": "2016-02-25T15:32:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:18:13.000Z", "max_forks_repo_path": "pygsti/optimize/customlm.py", "max_forks_repo_name": "00mjk/pyGSTi", "max_forks_repo_head_hexsha": "4f8bf5337b01b7afcb7b0580b717b5d1fe281be4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2016-03-15T19:32:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T10:22:05.000Z", "avg_line_length": 51.4813359528, "max_line_length": 120, "alphanum_fraction": 0.5379585814, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 18583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.17533478450814616}}
{"text": "\"\"\"\n  Calculate emissions from Fire Radiative Flux (FRP/Area).\n\"\"\"\n\n__VERSION__ = 2.5\n__CVSTAG__  = '@CVSTAG'\n\nimport warnings\nwarnings.simplefilter('ignore',DeprecationWarning)\n\nimport os\nfrom datetime import date, timedelta\n\nfrom numpy    import array, zeros, zeros_like, linspace, sum, exp,    any, all, logical_or\n\nfrom gfio     import GFIO\n\nfrom qfed.mxd14_l3 import __VERSION__ as L3A_VERSION\nfrom qfed.mxd14_l3 import __CVSTAG__  as L3A_CVSTAG\n\n\n#                  -------------------\n#                  Internal Parameters\n#                  -------------------\n\n# Fire emission flux density [kg/s/m^2]\n#\n#     f_s = S_f(sat) * (FRP/A) * Alpha * B_f(s)\n#\n\n# Biome-dependent Emission Factors\n# (From Andreae & Merlet 2001)\n# Units: g(species) / kg(dry mater)\n# --------------------------------\nB_f  = {}   \neB_f = {} # errors\n\n#                Tropical  Extratrop.    \n#                 Forests     Forests   Savanna  Grasslands\n#                --------  ----------   -------  ----------\nB_f['CO2']  = (  1580.00,    1569.00,  1613.00,     1613.00  )\nB_f['CO']   = (   104.00,     107.00,    65.00,       65.00  )\nB_f['SO2']  = (     0.57,       1.00,     0.35,        0.35  )\nB_f['OC']   = (     5.20,       9.14,     3.40,        3.40  )\nB_f['BC']   = (     0.66,       0.56,     0.48,        0.48  )\nB_f['NH3']  = (     1.30,       1.40,     1.05,        1.05  )\nB_f['PM25'] = (     9.10,      13.00,     5.40,        5.40  )\nB_f['TPM']  = (     8.50,      17.60,     8.30,        8.30  ) # note that TPM < PM2.5 for Tropical Forests\nB_f['NO']   = (     1.60,       3.00,     3.90,        3.90  ) # NOx as NO\nB_f['MEK']  = (     0.43,       0.45,     0.26,        0.26  ) # Methyl Ethyl Ketone\nB_f['C3H6'] = (     0.55,       0.59,     0.26,        0.26  ) # Propene/Propylene\nB_f['C2H6'] = (     1.20,       0.60,     0.32,        0.32  ) # Ethane\nB_f['C3H8'] = (     0.15,       0.25,     0.09,        0.09  ) # Propane\nB_f['ALK4'] = (     0.056,      0.091,    0.025,       0.025 ) # C4,5 alkanes (C4H10): n-butane + i-butane\nB_f['ALD2'] = (     0.65,       0.50,     0.50,        0.50  ) # Acetaldehyde (C2H4O)\nB_f['CH2O'] = (     1.40,       2.20,     0.26,        0.26  ) # Formaldehyde (HCHO)\nB_f['ACET'] = (     0.62,       0.56,     0.43,        0.43  ) # Acetone (C3H6O)\nB_f['CH4']  = (     6.80,       4.70,     2.30,        2.30  ) # Methene (CH4)\n\n\n#                Tropical  Extratrop.    \n#                 Forests     Forests   Savanna  Grasslands\n#                --------  ----------   -------  ----------\neB_f['CO2']  = (   90.00,     131.00,    95.00,       95.00  )\neB_f['CO']   = (   20.00,      37.00,    20.00,       20.00  )\neB_f['SO2']  = (    0.23,       0.23,     0.16,        0.16  )\neB_f['OC']   = (    1.50,       0.55,     1.40,        1.40  )\neB_f['BC']   = (    0.31,       0.19,     0.18,        0.18  )\neB_f['NH3']  = (    0.80,       0.80,     0.45,        0.45  )\neB_f['PM25'] = (    1.50,       7.00,     1.50,        1.50  )\neB_f['TPM']  = (    2.00,       6.40,     3.20,        3.20  )\neB_f['NO']   = (    0.70,       1.40,     2.40,        2.40  )\neB_f['MEK']  = (    0.22,       0.28,     0.13,        0.13  )\neB_f['C3H6'] = (    0.25,       0.16,     0.14,        0.14  )\neB_f['C2H6'] = (    0.70,       0.15,     0.16,        0.16  )\neB_f['C3H8'] = (    0.10,       0.11,     0.03,        0.03  )\neB_f['ALK4'] = (    0.03,       0.05,     0.09,        0.09  )\neB_f['ALD2'] = (    0.32,       0.02,     0.39,        0.39  )\neB_f['CH2O'] = (    0.70,       0.50,     0.44,        0.44  )\neB_f['ACET'] = (    0.31,       0.04,     0.18,        0.18  )\neB_f['CH4']  = (    2.00,       1.90,     0.90,        0.90  )\n\n# Scaling of C6 based on C5 (based on OC tuning)\n# ----------------------------------------------\nalpha = array([0.96450253,1.09728882,1.12014982,1.22951496,1.21702972])\nfor s in B_f.keys():\n    B_f[s] = list(array(B_f[s]) * alpha[1:])\n    \n# Combustion rate constant\n# (ECMWF Tech Memo 596)\n# It could be biome-dependent in case we want to tinker\n# with the A-M emission factors\n# -----------------------------------------------------\nAlpha = 1.37e-6 # kg(dry mater)/J\nA_f = {}\n#                           Tropical  Extratrop.    \n#                           Forests     Forests    Savanna  Grasslands\n#                           --------  ----------   -------  ----------\nA_f['CO2']  = Alpha * array(( 1.000,     1.000,     1.000,       1.000 ))\nA_f['CO']   = Alpha * array(( 1.000,     1.000,     1.000,       1.000 ))\nA_f['SO2']  = Alpha * array(( 2.500,     4.500,     1.800,       1.800 ))\nA_f['OC']   = Alpha * array(( 2.500,     4.500,     1.800,       1.800 ))\nA_f['BC']   = Alpha * array(( 2.500,     4.500,     1.800,       1.800 ))\nA_f['NH3']  = Alpha * array(( 2.500,     4.500,     1.800,       1.800 ))\nA_f['PM25'] = Alpha * array(( 2.500,     4.500,     1.800,       1.800 ))\nA_f['TPM']  = Alpha * array(( 2.500,     4.500,     1.800,       1.800 ))\nA_f['NO']   = Alpha * array(( 1.000,     1.000,     1.000,       1.000 ))\nA_f['MEK']  = Alpha * array(( 1.000,     1.000,     1.000,       1.000 ))\nA_f['C3H6'] = Alpha * array(( 1.000,     1.000,     1.000,       1.000 ))\nA_f['C2H6'] = Alpha * array(( 1.000,     1.000,     1.000,       1.000 ))\nA_f['C3H8'] = Alpha * array(( 1.000,     1.000,     1.000,       1.000 ))\nA_f['ALK4'] = Alpha * array(( 1.000,     1.000,     1.000,       1.000 ))\nA_f['ALD2'] = Alpha * array(( 1.000,     1.000,     1.000,       1.000 ))\nA_f['CH2O'] = Alpha * array(( 1.000,     1.000,     1.000,       1.000 ))\nA_f['ACET'] = Alpha * array(( 1.000,     1.000,     1.000,       1.000 ))\nA_f['CH4']  = Alpha * array(( 1.000,     1.000,     1.000,       1.000 ))\n\n\n# Satellite Fudge Factor\n# ----------------------\nS_f = {}\nS_f['MODIS_TERRA'] = 1.385 * alpha[0] # C6 scaling based on C5 above\nS_f['MODIS_AQUA' ] = 0.473\n\n#                     Tropical  Extratrop.    \n#                      Forests     Forests   Savanna  Grasslands\n#                     --------  ----------   -------  ----------\n#\n#S_f['MODIS_TERRA'] = ( 1.000,      1.000,    1.000,       1.000 )\n#S_f['MODIS_AQUA' ] = ( 1.000,      1.000,    1.000,       1.000 )\n\n\n\nclass Emissions(object):\n    \"\"\"\n    Class for computing emissions from pre-gridded FRP\n    estimates.\n    \"\"\"\n\n#---\n    def __init__(self, date, FRP, F, Land, Water, Cloud, biomes='default', Verb=0):\n        \"\"\"\n        Initializes an Emission object. On input,\n\n          date  ---   date object\n\n          FRP   ---   Dictionary keyed by satellite name\n                      with each element containing a\n                      tuple with gridded Fire Radiative Power\n                      (MW); each tuple element corresponds to a\n                      different biome type, e.g.,\n                      \n                      FRP['MODIS_TERRA'] = (frp_tf,frp_xf,frp_sv,frp_gl)\n\n          F     ---   Dictionary keyed by satellite name\n                      with each element containing a\n                      tuple with gridded forecast of FRP density \n                      (MW km-2); each tuple element corresponds to a\n                      different biome type, e.g.,\n                      \n                      F['MODIS_TERRA'] = (f_tf,f_xf,f_sv,f_gl)\n        \n          Land  ---   Dictionary keyed by satellite name\n                      with each element containing a\n                      observed clear-land area [km2] for each gridbox\n          \n          Water ---   Dictionary keyed by satellite name\n                      with each element containing a\n                      water area [km2] for each gridbox\n\n          Cloud ---   Dictionary keyed by satellite name\n                      with each element containing a\n                      cloud area [km2] for each gridbox            \n        \"\"\"\n\n#       Save relevant information\n#       -------------------------\n        self.Land  = Land\n        self.Water = Water\n        self.Cloud = Cloud\n        self.FRP   = FRP\n        self.F     = F\n        self.Sat   = Land.keys()\n        self.date  = date\n        self.verb  = Verb\n\n\n#       Filter missing data\n#       -------------------\n        eps = 1.0e-2\n        FillValue=1.0e20\n        \n        missing = []\n        for sat in self.Sat:\n            m = Land[sat][:,:]  > (1 - eps)*FillValue\n            m = logical_or(m, Water[sat][:,:] > (1 - eps)*FillValue)\n            m = logical_or(m, Cloud[sat][:,:] > (1 - eps)*FillValue)\n\n            n_biomes = len(FRP[sat])\n            for b in range(n_biomes):\n                m = logical_or(m, FRP[sat][b][:,:] > (1 - eps)*FillValue)\n\n            if any(m): \n                print '[w] Detected missing area or FRP values in %s QFED/L3A file on %s' % (sat, self.date)\n           \n            Land[sat][m]  = 0.0\n            Water[sat][m] = 0.0 \n            Cloud[sat][m] = 0.0\n            for b in range(n_biomes):\n                FRP[sat][b][m] = 0.0\n\n            if all(m):\n                missing.append(True)\n            else:\n                missing.append(False)\n\n        assert not all(missing), '[x] No valid L3A input data. Please persist emissions from the last known good date.'\n                \n\n#       Biomes\n#       -----------\n        if biomes == 'default':\n            self.biomes = ('Tropical Forest', 'Extratropical Forests', 'Savanna', 'Grassland')\n        else:\n            self.biomes = biomes[:]\n\n\n#       Record grid\n#       -----------\n        self.im, self.jm = Land[self.Sat[0]].shape\n        if (5*self.im - 8*(self.jm - 1)) == 0:\n            self.lon  = linspace(-180.,180.,self.im,endpoint=False)\n            self.lat  = linspace(-90.,90.,self.jm)\n        elif (self.im*6 == self.jm):\n            self.lon = linspace(1,self.im,self.im)\n            self.lat = linspace(1,self.jm,self.jm)\n        else:\n            d_lon = 360.0 / self.im\n            d_lat = 180.0 / self.jm\n            self.lon = linspace(-180+d_lon/2, 180-d_lon/2, self.im)\n            self.lat = linspace( -90+d_lat/2,  90-d_lat/2, self.jm)\n\n#---\n    def calculate(self, Species='all', method='default'):\n    \n        \"\"\"\n        Calculate emissions for each species using built-in\n        emission coefficients and fudge factors.\n\n        The default list of species is: \n        Species = ('CO', 'CO2','SO2','OC','BC','NH3','PM25','NO','MEK', \n                   'C3H6','C2H6','C3H8','ALK4','ALD2','CH2O','ACET','CH4')\n\n        The default method for computing the emissions is:\n            method = 'sequential-zero' \n        \"\"\"\n\n\n        if (Species == 'all') or (Species == 'default'):\n            species = ('CO'  , 'CO2' , 'SO2' , 'OC'  , 'BC'  , 'NH3' , \n                       'PM25', 'NO'  , 'MEK' , 'C3H6', 'C2H6', 'C3H8', \n                       'ALK4', 'ALD2', 'CH2O', 'ACET', 'CH4')\n        else:\n            species = Species[:]\n\n\n        # factor needed to convert B_f from [g/kg] to [kg/kg]\n        units_factor = 1e-3\n\n        n_biomes = len(self.biomes)\n\n        A_l = zeros((self.im, self.jm))\n        A_w = zeros((self.im, self.jm))\n        A_c = zeros((self.im, self.jm))\n\n        for sat in self.Sat:\n            A_l += self.Land[sat]\n            A_w += self.Water[sat]\n            A_c += self.Cloud[sat]\n\n        A_o = A_l + A_w\n\n        i = (A_l > 0)\n        j = ((A_l + A_c) > 0)\n\n        E = {}\n        E_= {}\n        for s in species:\n            E[s]  = zeros((n_biomes, self.im, self.jm))\n            E_[s] = zeros((n_biomes, self.im, self.jm))\n\n            for sat in self.Sat:\n                FRP = self.FRP[sat]\n                F   = self.F[sat]\n                A_  = self.Cloud[sat]\n                \n                for b in range(n_biomes):\n                    E[s][b,:,:]  += units_factor * A_f[s][b] * S_f[sat] * B_f[s][b] * FRP[b]\n                    E_[s][b,:,:] += units_factor * A_f[s][b] * S_f[sat] * B_f[s][b] * F[b] * A_\n           \n            for b in range(n_biomes):\n                E_b  = E[s][b,:,:]\n                E_b_ = E_[s][b,:,:]\n\n                if (method == 'default') or (method == 'sequential'):\n                    E_b[j] = ( (E_b[j]  / (A_o[j] + A_c[j])) * (1 + A_c[j] / (A_l[j] + A_c[j])) +\n                               (E_b_[j] / (A_o[j] + A_c[j])) * (    A_c[j] / (A_l[j] + A_c[j])) )\n\n                if method == 'sequential-zero':\n                    E_b[i] = E_b[i] / (A_o[i] + A_c[i]) * (1.0 + A_c[i] / (A_l[i] + A_c[i]))\n\n                if method == 'nofires':\n                    E_b[i] = E_b[i] / (A_o[i] + A_c[i])\n\n                if method == 'similarity':\n                    E_b[i] = E_b[i] / A_l[i] * ((A_l[i] + A_c[i]) / (A_o[i] + A_c[i]))\n\n                if method == 'similarity_qfed-2.2':\n                    E_b[i] = E_b[i] / A_o[i]\n                   \n\n#       Save Forecast dictionary\n#       ------------------------\n        dt  = 1.0    # days\n        tau = 3.0    # days\n\n        for sat in self.Sat:\n            for b in range(n_biomes):\n                s = species[0]\n\n                self.F[sat][b][:,:] = (E[s][b,:,:] / (units_factor * A_f[s][b] * S_f[sat] * B_f[s][b])) * exp(-dt/tau)\n                self.F[sat][b][j] = self.F[sat][b][j] * ((A_o[j] + A_c[j]) / (A_l[j] + A_c[j]))\n\n#       Save Emission dictionary\n#       ------------------------\n        self.Species = species\n        self.Emissions = E\n\n\n#---\n    def total(self, specie):\n        \"\"\"\n        Calculates the emissions from all biomes.\n        \"\"\"\n\n        return sum(self.Emissions[specie][:,:,:], axis=0)\n\n\n#---\n    def _write_ana(self, filename=None, dir='.', expid='qfed2', col='sfc', tag=None):\n       \"\"\"\n       Writes gridded emissions. You must call method\n       calculate() first. Optional input parameters:\n\n       filename  ---  file name; if not specified each\n                      species will be written to a separate\n                      file, e.g.,\n                         qfed2.emis_co.sfc.20030205.nc4\n       dir       ---  optional directory name, only used\n                      when *filename* is omitted\n       expid     ---  optional experiment id, only used\n                      when *filename* is omitted\n       col       ---  collection\n       tag       ---  tag name, by default it will be set to\n                      the QFED CVS tag name as part of the \n                      installation procedure\n       \n       \"\"\"\n       \n       title = 'QFED Level3b v%3.1f (%s) Gridded Emission Estimates' % (__VERSION__, _getTagName(tag))\n       source = 'NASA/GSFC/GMAO GEOS Aerosol Group'\n       contact = ('%s; %s') % ('arlindo.dasilva@nasa.gov', 'anton.darmenov@nasa.gov')\n\n\n#      Create directory for output file\n#      --------------------------------\n       dir = os.path.join(dir, 'Y%04d'%self.date.year, 'M%02d'%self.date.month)\n       rc = os.system(\"/bin/mkdir -p %s\"%dir)\n       if rc:\n           raise IOError, 'cannot create output directory'\n\n\n       nymd = 10000*self.date.year + 100*self.date.month + self.date.day\n       nhms = 120000\n\n#      Loop over species\n#      -----------------\n       vname_ = ( 'biomass', 'biomass_tf', 'biomass_xf', 'biomass_sv', 'biomass_gl' )\n\n       filename_ = filename\n       self.filename = {}\n       for s in self.Species:\n\n           if filename_ is None:\n               filename = dir+'/%s.emis_%s.%s.%d.nc4'\\\n                          %(expid,s.lower(),col,nymd)\n               vname = vname_ \n           else:\n               vname = [ '%s_%s' % (s.lower(), name) for name in vname_]\n\n           vtitle = [ '%s Biomass Emissions' % s, \n                      '%s Biomass Emissions from Tropical Forests' % s, \n                      '%s Biomass Emissions from Extratropical Forests' % s,\n                      '%s Biomass Emissions from Savanna' % s,\n                      '%s Biomass Emissions from Grasslands' % s ]\n                      \n           vunits = [ 'kg s-1 m-2', 'kg s-1 m-2', 'kg s-1 m-2', 'kg s-1 m-2', 'kg s-1 m-2' ]\n\n           self.filename[s] = filename\n\n#          Open file if it exists, otherwise create it\n#          -------------------------------------------\n           if os.path.exists(filename):\n               f = GFIO(filename,'w')\n           else:\n               f = GFIO()\n               f.create(filename, vname, nymd, nhms,\n                        lon=self.lon, lat=self.lat,\n                        vtitle=vtitle, vunits=vunits, timinc=240000,\n                        title=title, source=source, contact=contact)\n\n           f.write(vname[0], nymd, nhms, self.total(s))\n\n           for b in range(len(self.biomes)):\n               name = vname[b + 1]\n               f.write(name, nymd, nhms, self.Emissions[s][b,:,:])\n\n           try:\n               f.close()\n           except:\n               pass\n\n           if self.verb >=1:\n               print \"[w] Wrote file \"+filename\n\n\n#---\n    def _write_fcs(self, forecast, FillValue=1.0e20):\n       \"\"\"\n       Writes gridded emissions. You must call method\n       calculate() first. Input parameter(s):\n\n       forecast        ---  L3a file names\n       forecast_fields ---  Variable names of FRP density forecast\n       \"\"\"\n      \n       vname  = ('land', 'water', 'cloud', \n                 'frp_tf', 'frp_xf', 'frp_sv', 'frp_gl', \n                 'fb_tf', 'fb_xf', 'fb_sv', 'fb_gl')\n       vtitle = ('Observed Clear Land Area',\n                 'Water Area',\n                 'Obscured by Clouds Area',\n                 'Fire Radiative Power (Tropical Forests)',\n                 'Fire Radiative Power (Extra-tropical Forests)',\n                 'Fire Radiative Power (Savanna)',\n                 'Fire Radiative Power (Grasslands)',\n                 'Background FRP Density (Tropical Forests)',\n                 'Background FRP Density (Extra-tropical Forests)',\n                 'Background FRP Density (Savanna)',\n                 'Background FRP Density (Grasslands)')\n       vunits  = ('km2', 'km2', 'km2', 'MW', 'MW', 'MW', 'MW', \n                  'MW km-2', 'MW km-2', 'MW km-2', 'MW km-2')\n       title   = 'QFED Level3a v%3.1f (%s) Gridded FRP Estimates'%(L3A_VERSION, _getTagName(L3A_CVSTAG))\n       source  = 'NASA/GSFC/GMAO GEOS Aerosol Group'\n       contact = ('%s; %s') % ('arlindo.dasilva@nasa.gov', 'anton.darmenov@nasa.gov')\n\n       d = self.date + timedelta(days=1)\n       nymd = 10000*d.year + 100*d.month + d.day\n       nhms = 120000\n\n       for sat in self.Sat:\n           f = GFIO()\n           \n           f.create(forecast[sat], vname, nymd, nhms, lon=self.lon, lat=self.lat,\n                    vtitle=vtitle, vunits=vunits, title=title, source=source, contact=contact)\n          \n           missing = zeros_like(self.F[sat][0])\n           missing[:,:] = FillValue\n\n           f.write('land',   nymd, nhms, missing)\n           f.write('water',  nymd, nhms, missing)\n           f.write('cloud',  nymd, nhms, missing)\n           f.write('frp_tf', nymd, nhms, missing)\n           f.write('frp_xf', nymd, nhms, missing)\n           f.write('frp_sv', nymd, nhms, missing)\n           f.write('frp_gl', nymd, nhms, missing)\n         \n           f.write('fb_tf', nymd, nhms, self.F[sat][0])\n           f.write('fb_xf', nymd, nhms, self.F[sat][1])\n           f.write('fb_sv', nymd, nhms, self.F[sat][2])\n           f.write('fb_gl', nymd, nhms, self.F[sat][3])\n\n           try:\n               f.close()\n           except:\n               pass\n\n#---\n    def write(self, filename=None, dir='.', forecast=None, expid='qfed2', col='sfc', \n                    tag=None, ndays=1, uncompressed=False):\n       \"\"\"\n       Writes gridded emissions that can persist for a number of days. You must \n       call method calculate() first. Optional input parameters:\n\n       filename      ---  file name; if not specified each\n                          species will be written to a separate\n                          file, e.g.,\n                          qfed2.emis_co.sfc.20030205.nc4\n       dir           ---  optional directory name, only used\n                          when *filename* is omitted\n       expid         ---  optional experiment id, only used\n                          when *filename* is omitted\n       col           ---  collection\n       tag           ---  tag name, by default it will be set to\n                          the QFED CVS tag name as part of the \n                          installation procedure\n       ndays         ---  persist emissions for a number of days\n       uncompressed  ---  use n4zip to compress gridded output file\n       \n       \"\"\"\n\n#      Write out the emission files\n#      ----------------------------\n       self._write_fcs(forecast)\n\n       for n in range(ndays):\n\n#          Write out the emission files\n#          ----------------------------\n           self._write_ana(filename=filename,dir=dir,expid=expid,col=col,tag=tag)\n\n#          Compress the files by default\n#          -----------------------------\n           if not uncompressed:\n               for s in self.filename.keys():\n                   rc = os.system(\"n4zip %s\"%self.filename[s])\n                   if rc:\n                       warnings.warn('cannot compress output file <%s>'%self.filename[s])\n\n#          Increment date by one day\n#          ---------------------------------\n           self.date = self.date + timedelta(days=1)\n\n#..............................................................\n\ndef _getTagName(tag):\n    if tag != None:\n        tag_name = tag\n    else:    \n        if __CVSTAG__ not in (None, ''):\n            tag_name = __CVSTAG__\n        else:\n            tag_name = 'CVSTAG_UNKNOWN'\n\n    return tag_name\n\n", "meta": {"hexsha": "6025ef950124f51e80660931cc37639ffb48c20c", "size": 21404, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Components/qfed/qfed/emissions.py", "max_stars_repo_name": "GEOS-ESM/AeroApps", "max_stars_repo_head_hexsha": "874dad6f34420c014d98eccbe81a061bdc0110cf", "max_stars_repo_licenses": ["NASA-1.3", "ECL-2.0", "Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-02T14:23:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T15:39:30.000Z", "max_issues_repo_path": "src/Components/qfed/qfed/emissions.py", "max_issues_repo_name": "GEOS-ESM/AeroApps", "max_issues_repo_head_hexsha": "874dad6f34420c014d98eccbe81a061bdc0110cf", "max_issues_repo_licenses": ["NASA-1.3", "ECL-2.0", "Apache-2.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-04-15T16:22:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T13:59:25.000Z", "max_forks_repo_path": "src/Components/qfed/qfed/emissions.py", "max_forks_repo_name": "GEOS-ESM/AeroApps", "max_forks_repo_head_hexsha": "874dad6f34420c014d98eccbe81a061bdc0110cf", "max_forks_repo_licenses": ["NASA-1.3", "ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4272890485, "max_line_length": 119, "alphanum_fraction": 0.45117735, "include": true, "reason": "from numpy", "num_tokens": 6619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3451052776934245, "lm_q1q2_score": 0.17524855443809043}}
{"text": "from __future__ import division\nfrom __future__ import print_function\n\nimport sys\nimport os\nsys.path.append( '%s/gcn' % os.path.dirname(os.path.realpath(__file__)) )\n# add the libary path for graph reduction and local search\n# sys.path.append( '%s/kernel' % os.path.dirname(os.path.realpath(__file__)) )\n\nimport time\nimport scipy.io as sio\nimport numpy as np\nimport scipy.sparse as sp\nimport queue\nfrom copy import deepcopy\n\n# import the libary for graph reduction and local search\n# from reduce_lib import reducelib\n\nimport tensorflow as tf\nfrom utils import *\nfrom models import GCN_DEEP_DIVER\n\nN_bd = 32\n\n# Settings\nflags = tf.app.flags\nFLAGS = flags.FLAGS\nflags.DEFINE_string('model', 'gcn_cheby', 'Model string.')  # 'gcn', 'gcn_cheby', 'dense'\nflags.DEFINE_float('learning_rate', 0.001, 'Initial learning rate.')\nflags.DEFINE_integer('epochs', 201, 'Number of epochs to train.')\nflags.DEFINE_integer('hidden1', 32, 'Number of units in hidden layer 1.')\nflags.DEFINE_integer('diver_num', 32, 'Number of outputs.')\nflags.DEFINE_float('dropout', 0, 'Dropout rate (1 - keep probaNUmbility).')\nflags.DEFINE_float('weight_decay', 5e-4, 'Weight for L2 loss on embedding matrix.')\nflags.DEFINE_integer('early_stopping', 1000, 'Tolerance for early stopping (# of epochs).')\nflags.DEFINE_integer('max_degree', 1, 'Maximum Chebyshev polynomial degree.')\nflags.DEFINE_integer('num_layer', 20, 'number of layers.')\n\n# test data path\ndata_path = \"./data\"\nval_mat_names = os.listdir(data_path)\n\n# Some preprocessing\n\nnum_supports = 1 + FLAGS.max_degree\nmodel_func = GCN_DEEP_DIVER\n\n# Define placeholders\nplaceholders = {\n    'support': [tf.sparse_placeholder(tf.float32) for _ in range(num_supports)],\n    'features': tf.sparse_placeholder(tf.float32, shape=(None, N_bd)), # featureless: #points\n    'labels': tf.placeholder(tf.float32, shape=(None, 2)), # 0: not linked, 1:linked\n    'labels_mask': tf.placeholder(tf.int32),\n    'dropout': tf.placeholder_with_default(0., shape=()),\n    'num_features_nonzero': tf.placeholder(tf.int32)  # helper variable for sparse dropout\n}\n\n# Create model\nmodel = model_func(placeholders, input_dim=N_bd, logging=True)\n\n# use gpu 0\nos.environ['CUDA_VISIBLE_DEVICES']=str(0)\n\n# Initialize session\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nsess = tf.Session(config=config)\n\n# Define model evaluation function\ndef evaluate(features, support, placeholders):\n    t_test = time.time()\n    feed_dict_val = construct_feed_dict4pred(features, support, placeholders)\n    outs_val = sess.run([model.outputs_softmax], feed_dict=feed_dict_val)\n    return (time.time() - t_test), outs_val[0]\n\ndef findNodeEdges(adj):\n    nn = adj.shape[0]\n    edges = []\n    for i in range(nn):\n        edges.append(adj.indices[adj.indptr[i]:adj.indptr[i+1]])\n    return edges\n\ndef isis_v2(edges, nIS_vec_local, cn):\n    return np.sum(nIS_vec_local[edges[cn]] == 1) > 0\n\ndef isis(edges, nIS_vec_local):\n    tmp = (nIS_vec_local==1)\n    return np.sum(tmp[edges[0]]*tmp[edges[1]]) > 0\n\ndef add_rnd_q(cns, nIS_vec_local):\n    global adj_0\n\n    nIS_vec_local[cns] = 1\n    tmp = sp.find(adj_0[cns, :] == 1)\n    nIS_vec_local[tmp[1]] = 0\n    remain_vec_tmp = (nIS_vec_local == -1)\n    adj = adj_0\n    adj = adj[remain_vec_tmp, :]\n    adj = adj[:, remain_vec_tmp]\n    if reduce_graph(adj, nIS_vec_local):\n        return True\n    return False\n\ndef fake_reduce_graph(adj):\n    reduced_node = -np.ones(adj.shape[0])\n    reduced_adj = adj\n    mapping = np.arange(adj.shape[0])\n    reverse_mapping = np.arange(adj.shape[0])\n    crt_is_size = 0\n    return reduced_node, reduced_adj, mapping, reverse_mapping, crt_is_size\n\ndef fake_local_search(adj, nIS_vec):\n    return nIS_vec.astype(int)\n\ndef reduce_graph(adj, nIS_vec_local):\n    global best_IS_num\n    global best_IS_vec\n    global bsf_q\n    global adj_0\n    global q_ct\n    global id\n    global out_id\n    global res_ct\n\n    remain_vec = (nIS_vec_local == -1)\n\n    # reduce graph\n    # reduced_node, reduced_adj, mapping, reverse_mapping, crt_is_size = api.reduce_graph(adj)\n    reduced_node, reduced_adj, mapping, reverse_mapping, crt_is_size = fake_reduce_graph(adj)\n    nIS_vec_sub = reduced_node.copy()\n    nIS_vec_sub_tmp = reduced_node.copy()\n    nIS_vec_sub[nIS_vec_sub_tmp == 0] = 1\n    nIS_vec_sub[nIS_vec_sub_tmp == 1] = 0\n    reduced_nn = reduced_adj.shape[0]\n\n    # update MIS after reduction\n    tmp = sp.find(adj[nIS_vec_sub == 1, :] == 1)\n    nIS_vec_sub[tmp[1]] = 0\n    nIS_vec_local[remain_vec] = nIS_vec_sub\n    nIS_vec_local[nIS_vec_local == 2] = -1\n\n    # if the whole graph is reduced, we find a candidate\n    if reduced_nn == 0:\n        remain_vec_tmp = (nIS_vec_local == -1)\n        if np.sum(remain_vec_tmp) == 0:\n            # get a solution\n            res_ct += 1\n            # nIS_vec_local = api.local_search(adj_0, nIS_vec_local)\n            nIS_vec_local = fake_local_search(adj_0, nIS_vec_local)\n            if np.sum(nIS_vec_local) > best_IS_num:\n                best_IS_num = np.sum(nIS_vec_local)\n                best_IS_vec = deepcopy(nIS_vec_local)\n                sio.savemat('./res_%04d/%s' % (\n                    time_limit, val_mat_names[id]), {'er_graph': adj_0, 'nIS_vec': best_IS_vec})\n            print(\"ID: %03d\" % id, \"QItem: %03d\" % q_ct, \"Res#: %03d\" % res_ct,\n                  \"Current: %d\" % (np.sum(nIS_vec_local)), \"Best: %d\" % best_IS_num, \"Reduction\")\n            return True\n        adj = adj_0\n        adj = adj[remain_vec_tmp, :]\n        adj = adj[:, remain_vec_tmp]\n        bsf_q.append([adj, nIS_vec_local.copy(), remain_vec.copy(), reduced_adj, reverse_mapping.copy()])\n    else:\n        bsf_q.append([adj, nIS_vec_local.copy(), remain_vec.copy(), reduced_adj, reverse_mapping.copy()])\n\n    return False\n\n# Init variables\nsaver=tf.train.Saver(max_to_keep=1000)\nsess.run(tf.global_variables_initializer())\n\nckpt=tf.train.get_checkpoint_state(\"./model\")\nprint('loaded '+ckpt.model_checkpoint_path)\nsaver.restore(sess,ckpt.model_checkpoint_path)\n\nnoout = FLAGS.diver_num # number of outputs\ntime_limit = 600  # time limit for searching\n\nif not os.path.isdir(\"./res_%04d\"%time_limit):\n    os.makedirs(\"./res_%04d\"%time_limit)\n\n# for graph reduction and local search\n# api = reducelib()\n\nfor id in range(len(val_mat_names)):\n    best_IS_num = -1\n    mat_contents = sio.loadmat(data_path + '/' + val_mat_names[id])\n    adj_0 = mat_contents['adj']\n    # yy = mat_contents['indset_label']\n    # opt_num = np.sum(yy[:,0])\n    # edges_0 = sp.find(adj_0) # for isis version 1\n    edges_0 = findNodeEdges(adj_0)\n    nn = adj_0.shape[0]\n    bsf_q = []\n    q_ct = 0\n    res_ct = 0\n    out_id = -1\n\n    start_time = time.time()\n    while time.time()-start_time < time_limit:\n\n        # if best_IS_num == opt_num:\n        #     break\n\n        if len(bsf_q) == 0:\n            if reduce_graph(adj_0, -np.ones(nn)):\n                break\n\n        q_item = bsf_q.pop(np.random.randint(0,len(bsf_q)))\n        q_ct += 1\n\n        adj = q_item[0]\n        remain_vec = deepcopy(q_item[2])\n        reduced_adj = q_item[3]\n        reverse_mapping = deepcopy(q_item[4])\n        remain_nn = adj.shape[0]\n        reduced_nn = reduced_adj.shape[0]\n\n        if reduced_nn != 0:\n            # GCN\n            features = np.ones([reduced_nn, N_bd])\n            features = sp.lil_matrix(features)\n            features = preprocess_features(features)\n            support = simple_polynomials(reduced_adj, FLAGS.max_degree)\n\n            _, z_out = evaluate(features, support, placeholders)\n\n            for out_id in range(noout):\n                # if best_IS_num == opt_num:\n                #     break\n\n                nIS_vec = deepcopy(q_item[1])\n                nIS_Prob_sub_t = z_out[:, 2 * out_id + 1]\n                nIS_Prob_sub = np.zeros(remain_nn)\n                nIS_Prob_sub[reverse_mapping] = nIS_Prob_sub_t\n                nIS_Prob = np.zeros(nn)\n                nIS_Prob[remain_vec] = nIS_Prob_sub\n\n                # chosen nodes\n                cns_sorted = np.argsort(1 - nIS_Prob)\n\n                # tt = time.time()\n                nIS_vec_tmp = deepcopy(nIS_vec)\n                for cid in range(nn):\n                    cn = cns_sorted[cid]\n                    # check graph\n                    if isis_v2(edges_0, nIS_vec_tmp, cn):\n                        break\n                    nIS_vec_tmp[cn] = 1\n                    if np.random.random_sample() > 0.7:\n                        add_rnd_q(cns_sorted[:(cid+1)], deepcopy(nIS_vec))\n\n                # print(\"time=\", \"{:.5f}\".format((time.time() - tt)))\n\n                cns = cns_sorted[:cid]\n                nIS_vec[cns] = 1\n                tmp = sp.find(adj_0[cns, :] == 1)\n                nIS_vec[tmp[1]] = 0\n                remain_vec_tmp = (nIS_vec == -1)\n                if np.sum(remain_vec_tmp) == 0:\n                    # get a solution\n                    res_ct += 1\n                    # nIS_vec = api.local_search(adj_0, nIS_vec)\n                    nIS_vec = fake_local_search(adj_0, nIS_vec)\n                    if np.sum(nIS_vec) > best_IS_num:\n                        best_IS_num = np.sum(nIS_vec)\n                        best_IS_vec = deepcopy(nIS_vec)\n                        sio.savemat('./res_%04d/%s' % (\n                        time_limit, val_mat_names[id]), {'er_graph': adj_0, 'nIS_vec': best_IS_vec})\n                    print(\"ID: %03d\" % id, \"QItem: %03d\" % q_ct, \"Res#: %03d\" % res_ct,\n                          \"Current: %d\" % (np.sum(nIS_vec)), \"Best: %d\" % best_IS_num, \"Network\")\n                    continue\n                adj = adj_0\n                adj = adj[remain_vec_tmp, :]\n                adj = adj[:, remain_vec_tmp]\n\n                if reduce_graph(adj, nIS_vec):\n                    continue\n        else:\n            nIS_vec = deepcopy(q_item[1])\n            if reduce_graph(adj, nIS_vec):\n                continue\n\n    sio.savemat('./res_%04d/%s' % (time_limit, val_mat_names[id]), {'er_graph': adj_0, 'nIS_vec': best_IS_vec})\n", "meta": {"hexsha": "76c09709953e1e83976528bf28f56ac42369040a", "size": 9938, "ext": "py", "lang": "Python", "max_stars_repo_path": "demo.py", "max_stars_repo_name": "knshnb/NPHard", "max_stars_repo_head_hexsha": "18dc6254553fc9a61e3f37fccfcb8cde0c8a688d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demo.py", "max_issues_repo_name": "knshnb/NPHard", "max_issues_repo_head_hexsha": "18dc6254553fc9a61e3f37fccfcb8cde0c8a688d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demo.py", "max_forks_repo_name": "knshnb/NPHard", "max_forks_repo_head_hexsha": "18dc6254553fc9a61e3f37fccfcb8cde0c8a688d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8701754386, "max_line_length": 111, "alphanum_fraction": 0.6184342926, "include": true, "reason": "import numpy,import scipy", "num_tokens": 2671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.1752485510176972}}
{"text": "from abc import ABC, abstractmethod\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import backend as K\n\nfrom ..base.errors import MissingModelError\nfrom ..base.mixins import RandomStateMixin, NumActionsMixin, LoggerMixin\nfrom ..policies.base import BasePolicy\nfrom ..caching import NStepCache\nfrom ..losses import SoftmaxPolicyLossWithLogits, ClippedSurrogateLoss\nfrom ..utils import (\n    project_onto_actions_np, softmax, argmax, check_numpy_array)\n\n\n__all__ = (\n    'BaseV',\n    'BaseQTypeI',\n    'BaseQTypeII',\n    'BaseSoftmaxPolicy',\n)\n\n\nclass BaseFunctionApproximator(ABC, LoggerMixin):\n    @abstractmethod\n    def __call__(self, *args, **kwargs):\n        pass\n\n    @abstractmethod\n    def update(self, *args, **kwargs):\n        pass\n\n    @abstractmethod\n    def batch_eval(self, *args, **kwargs):\n        pass\n\n    @abstractmethod\n    def batch_update(self, *args, **kwargs):\n        pass\n\n    def _check_attrs(self):\n        required_attrs = [\n            'env', 'gamma', 'bootstrap_n', 'train_model', 'predict_model',\n            'target_model', '_cache']\n\n        if isinstance(self, BaseSoftmaxPolicy):\n            required_attrs.remove('bootstrap_n')\n            required_attrs.remove('gamma')\n            required_attrs.remove('_cache')\n\n        missing_attrs = \", \".join(\n            attr for attr in required_attrs if not hasattr(self, attr))\n\n        if missing_attrs:\n            raise AttributeError(\n                \"missing attributes: {}\".format(missing_attrs))\n\n    def _train_on_batch(self, inputs, outputs):\n        \"\"\"\n        Run self.train_model.train_on_batch(inputs, outputs) and return the\n        losses as a dict of type: {loss_name <str>: loss_value <float>}.\n\n        \"\"\"\n        losses = self.train_model.train_on_batch(inputs, outputs)\n\n        # add metric names\n        if len(self.train_model.metrics_names) > 1:\n            assert len(self.train_model.metrics_names) == len(losses)\n            losses = dict(zip(self.train_model.metrics_names, losses))\n        else:\n            assert isinstance(losses, (float, np.float32, np.float64))\n            assert len(self.train_model.metrics_names) == 1\n            losses = {self.train_model.metrics_names[0]: losses}\n\n        if hasattr(self.env, 'record_losses'):\n            self.env.record_losses(losses)\n\n        return losses\n\n    def sync_target_model(self, tau=1.0):\n        \"\"\"\n        Synchronize the target model with the primary model.\n\n        Parameters\n        ----------\n        tau : float between 0 and 1, optional\n\n            The amount of exponential smoothing to apply in the target update:\n\n            .. math::\n\n                w_\\\\text{target}\\\\ \\\\leftarrow\\\\ (1 - \\\\tau)\\\\,w_\\\\text{target}\n                + \\\\tau\\\\,w_\\\\text{primary}\n\n        \"\"\"\n        if tf.__version__ >= '2.0':\n            target_weights = self.target_model.trainable_variables\n            primary_weights = self.predict_model.trainable_variables\n            tf.group(*(\n                K.update(wt, wt + tau * (wp - wt))\n                for wt, wp in zip(target_weights, primary_weights)))\n            self.logger.debug(\n                \"updated target_mode with tau = {:.3g}\".format(tau))\n\n        else:\n            if not hasattr(self, '_target_model_sync_op'):\n                target_weights = tf.get_collection(\n                    tf.GraphKeys.GLOBAL_VARIABLES, scope='target')  # list\n                primary_weights = tf.get_collection(\n                    tf.GraphKeys.GLOBAL_VARIABLES, scope='primary')  # list\n\n                if not target_weights:\n                    raise MissingModelError(\n                        \"no model weights found in variable scope: 'target'\")\n                if not primary_weights:\n                    raise MissingModelError(\n                        \"no model weights found in variable scope: 'primary'\")\n                assert len(primary_weights) == len(target_weights)\n\n                self._target_model_sync_tau = tf.placeholder(\n                    tf.float32, shape=())\n                self._target_model_sync_op = tf.group(*(\n                    K.update(wt, wt + self._target_model_sync_tau * (wp - wt))\n                    for wt, wp in zip(target_weights, primary_weights)))\n\n            K.get_session().run(\n                self._target_model_sync_op,\n                feed_dict={self._target_model_sync_tau: tau})\n            self.logger.debug(\n                \"updated target_mode with tau = {:.3g}\".format(tau))\n\n\nclass BaseV(BaseFunctionApproximator):\n    \"\"\"\n    Base class for modeling a :term:`state value function`.\n\n    A :term:`state value function` is implemented by mapping :math:`s\\\\mapsto\n    v(s)`.\n\n    Parameters\n    ----------\n    env : gym environment\n\n        A gym environment.\n\n    train_model : keras.Model(:term:`S`, :term:`V`)\n\n        Used for training.\n\n    predict_model : keras.Model(:term:`S`, :term:`V`)\n\n        Used for predicting. For a :term:`state value function` the\n        :term:`target_model` and :term:`predict_model` are the same.\n\n    target_model : keras.Model(:term:`S`, :term:`V`)\n\n        A :term:`target_model` is used to make predictions on a bootstrapping\n        scenario. It can be advantageous to use a point-in-time copy of the\n        :term:`predict_model` to construct a bootstrapped target.\n\n    gamma : float, optional\n\n        The discount factor for discounting future rewards.\n\n    bootstrap_n : positive int, optional\n\n        The number of steps in n-step bootstrapping. It specifies the number of\n        steps over which we're willing to delay bootstrapping. Large :math:`n`\n        corresponds to Monte Carlo updates and :math:`n=1` corresponds to\n        TD(0).\n\n    bootstrap_with_target_model : bool, optional\n\n        Whether to use the :term:`target_model` when constructing a\n        bootstrapped target. If False (default), the primary\n        :term:`predict_model` is used.\n\n    \"\"\"\n    def __init__(\n            self, env, train_model, predict_model, target_model,\n            gamma=0.9,\n            bootstrap_n=1,\n            bootstrap_with_target_model=False):\n\n        self.env = env\n        self.train_model = train_model\n        self.predict_model = predict_model\n        self.target_model = target_model\n        self.gamma = float(gamma)\n        self.bootstrap_n = int(bootstrap_n)\n        self.bootstrap_with_target_model = bool(bootstrap_with_target_model)\n\n        self._cache = NStepCache(self.env, self.bootstrap_n, self.gamma)\n\n    def __call__(self, s, use_target_model=False):\n        \"\"\"\n        Evaluate the Q-function.\n\n        Parameters\n        ----------\n        s : state observation\n\n            A single state observation.\n\n        use_target_model : bool, optional\n\n            Whether to use the :term:`target_model` internally. If False\n            (default), the :term:`predict_model` is used.\n\n        Returns\n        -------\n        V : float or array of floats\n\n            The estimated value of the state :math:`v(s)`.\n\n        \"\"\"\n        assert self.env.observation_space.contains(s)\n        S = np.expand_dims(s, axis=0)\n        V = self.batch_eval(S, use_target_model=use_target_model)\n        check_numpy_array(V, shape=(1,))\n        V = np.asscalar(V)\n        return V\n\n    def update(self, s, r, done):\n        \"\"\"\n        Update the Q-function.\n\n        Parameters\n        ----------\n        s : state observation\n\n            A single state observation..\n\n        r : float\n\n            A single observed reward.\n\n        done : bool\n\n            Whether the episode has finished.\n\n        \"\"\"\n        assert self.env.observation_space.contains(s)\n        self._cache.add(s, 0, r, done)\n\n        # eager updates\n        while self._cache:\n            S, _, Rn, In, S_next, _ = self._cache.pop()\n            self.batch_update(S, Rn, In, S_next)\n\n    def batch_update(self, S, Rn, In, S_next):\n        \"\"\"\n        Update the value function on a batch of transitions.\n\n        Parameters\n        ----------\n        S : nd array, shape: [batch_size, ...]\n\n            A batch of state observations.\n\n        Rn : 1d array, dtype: float, shape: [batch_size]\n\n            A batch of partial returns. For example, in n-step bootstrapping\n            this is given by:\n\n            .. math::\n\n                R^{(n)}_t\\\\ =\\\\ R_t + \\\\gamma\\\\,R_{t+1} + \\\\dots\n                    \\\\gamma^{n-1}\\\\,R_{t+n-1}\n\n            In other words, it's the non-bootstrapped part of the n-step\n            return.\n\n        In : 1d array, dtype: float, shape: [batch_size]\n\n            A batch bootstrapping factor. For instance, in n-step bootstrapping\n            this is given by :math:`I^{(n)}_t=\\\\gamma^n` if the episode is\n            ongoing and :math:`I^{(n)}_t=0` otherwise. This allows us to write\n            the bootstrapped target as:\n\n            .. math::\n\n                G^{(n)}_t=R^{(n)}_t+I^{(n)}_tQ(S_{t+n}, A_{t+n})\n\n\n        S_next : nd array, shape: [batch_size, ...]\n\n            A batch of next-state observations.\n\n        Returns\n        -------\n        losses : dict\n\n            A dict of losses/metrics, of type ``{name <str>: value <float>}``.\n\n        \"\"\"\n        V_next = self.batch_eval(\n            S_next, use_target_model=self.bootstrap_with_target_model)\n        Gn = Rn + In * V_next\n        losses = self._train_on_batch(S, Gn)\n        return losses\n\n    def batch_eval(self, S, use_target_model=False):\n        \"\"\"\n        Evaluate the state value function on a batch of state observations.\n\n        Parameters\n        ----------\n        S : nd array, shape: [batch_size, ...]\n\n            A batch of state observations.\n\n        use_target_model : bool, optional\n\n            Whether to use the :term:`target_model` internally. If False\n            (default), the :term:`predict_model` is used.\n\n        Returns\n        -------\n        V : 1d array, dtype: float, shape: [batch_size]\n\n            The predicted state values.\n\n        \"\"\"\n        model = self.target_model if use_target_model else self.predict_model\n\n        V = model.predict_on_batch(S)\n        check_numpy_array(V, ndim=2, axis_size=1, axis=1)\n        V = np.squeeze(V, axis=1)  # shape: [batch_size]\n        return V\n\n\nclass BaseGenericQ(BaseFunctionApproximator, NumActionsMixin):\n    UPDATE_STRATEGIES = ('sarsa', 'q_learning', 'double_q_learning')\n\n    def __init__(\n            self, env, train_model, predict_model, target_model,\n            gamma=0.9,\n            bootstrap_n=1,\n            bootstrap_with_target_model=False,\n            update_strategy='sarsa'):\n\n        self.env = env\n        self.train_model = train_model\n        self.predict_model = predict_model\n        self.target_model = target_model\n        self.gamma = float(gamma)\n        self.bootstrap_n = int(bootstrap_n)\n        self.bootstrap_with_target_model = bool(bootstrap_with_target_model)\n        self.update_strategy = update_strategy\n\n        self._cache = NStepCache(self.env, self.bootstrap_n, self.gamma)\n\n    def __call__(self, s, a=None, use_target_model=False):\n        \"\"\"\n        Evaluate the Q-function.\n\n        Parameters\n        ----------\n        s : state observation\n\n            A single state observation.\n\n        a : action, optional\n\n            A single action.\n\n        use_target_model : bool, optional\n\n            Whether to use the :term:`target_model` internally. If False\n            (default), the :term:`predict_model` is used.\n\n        Returns\n        -------\n        Q : float or array of floats\n\n            If action ``a`` is provided, a single float representing\n            :math:`q(s,a)` is returned. If, on the other hand, ``a`` is left\n            unspecified, a vector representing :math:`q(s,.)` is returned\n            instead. The shape of the latter return value is ``[num_actions]``,\n            which is only well-defined for discrete action spaces.\n\n        \"\"\"\n        assert self.env.observation_space.contains(s)\n        S = np.expand_dims(s, axis=0)\n        if a is not None:\n            assert self.env.action_space.contains(a)\n            A = np.expand_dims(a, axis=0)\n            Q = self.batch_eval(S, A, use_target_model=use_target_model)\n            check_numpy_array(Q, shape=(1,))\n            Q = np.asscalar(Q)\n        else:\n            Q = self.batch_eval(S, use_target_model=use_target_model)\n            check_numpy_array(Q, shape=(1, self.num_actions))\n            Q = np.squeeze(Q, axis=0)\n        return Q\n\n    def update(self, s, pi, r, done):\n        \"\"\"\n        Update the Q-function.\n\n        Parameters\n        ----------\n        s : state observation\n\n            A single state observation.\n\n        pi : int or 1d array, shape: [num_actions]\n\n            Vector of action propensities under the behavior policy. This may\n            be just an indicator if the action propensities are inferred\n            through sampling. For instance, let's say our action space is\n            :class:`Discrete(4)`, then passing ``pi = 2`` is equivalent to\n            passing ``pi = [0, 0, 1, 0]``. Both would indicate that the action\n            :math:`a=2` was drawn from the behavior policy.\n\n        r : float\n\n            A single observed reward.\n\n        done : bool\n\n            Whether the episode has finished.\n\n        \"\"\"\n        assert self.env.observation_space.contains(s)\n        pi = self.check_pi(pi)\n        self._cache.add(s, pi, r, done)\n\n        # eager updates\n        while self._cache:\n            self.batch_update(*self._cache.pop())  # pop with batch_size=1\n\n    def batch_update(self, S, P, Rn, In, S_next, P_next=None):\n        \"\"\"\n        Update the value function on a batch of transitions.\n\n        Parameters\n        ----------\n        S : nd array, shape: [batch_size, ...]\n\n            A batch of state observations.\n\n        P : 2d Tensor, dtype: int, shape: [batch_size]\n\n            A batch of action propensities. :term:`P` is typically just an\n            indicator for which action was chosen by the behavior policy. In\n            this sense, :term:`P` acts as a projector more than a prediction\n            target. That is, :term:`P` is used to project our predicted values\n            down to those for which we actually received the feedback signal.\n\n        Rn : 1d array, dtype: float, shape: [batch_size]\n\n            A batch of partial returns. For example, in n-step bootstrapping\n            this is given by:\n\n            .. math::\n\n                R^{(n)}_t\\\\ =\\\\ R_t + \\\\gamma\\\\,R_{t+1} + \\\\dots\n                    \\\\gamma^{n-1}\\\\,R_{t+n-1}\n\n            In other words, it's the non-bootstrapped part of the n-step\n            return.\n\n        In : 1d array, dtype: float, shape: [batch_size]\n\n            A batch bootstrapping factor. For instance, in n-step bootstrapping\n            this is given by :math:`I^{(n)}_t=\\\\gamma^n` if the episode is\n            ongoing and :math:`I^{(n)}_t=0` otherwise. This allows us to write\n            the bootstrapped target as:\n\n            .. math::\n\n                G^{(n)}_t=R^{(n)}_t+I^{(n)}_tQ(S_{t+n}, A_{t+n})\n\n\n        S_next : nd array, shape: [batch_size, ...]\n\n            A batch of next-state observations.\n\n        P_next : 2d Tensor, dtype: int, shape: [batch_size, num_actions]\n\n            Action propensities :term:`P_next` for the (potential) next action.\n            This argument is only used if ``update_strategy='sarsa'``.\n\n        Returns\n        -------\n        losses : dict\n\n            A dict of losses/metrics, of type ``{name <str>: value <float>}``.\n\n        \"\"\"\n        G = self.bootstrap_target(Rn, In, S_next, P_next)\n        losses = self._train_on_batch([S, G], P)\n        return losses\n\n    def bootstrap_target(self, Rn, In, S_next, P_next=None):\n        \"\"\"\n        Get the bootstrapped target\n        :math:`G^{(n)}_t=R^{(n)}_t+\\\\gamma^nQ(S_{t+n}, A_{t+n})`.\n\n        Parameters\n        ----------\n        Rn : 1d array, dtype: float, shape: [batch_size]\n\n            A batch of partial returns. For example, in n-step bootstrapping\n            this is given by:\n\n            .. math::\n\n                R^{(n)}_t\\\\ =\\\\ R_t + \\\\gamma\\\\,R_{t+1} + \\\\dots\n                    \\\\gamma^{n-1}\\\\,R_{t+n-1}\n\n            In other words, it's the non-bootstrapped part of the n-step\n            return.\n\n        In : 1d array, dtype: float, shape: [batch_size]\n\n            A batch bootstrapping factor. For instance, in n-step bootstrapping\n            this is given by :math:`I^{(n)}_t=\\\\gamma^n` if the episode is\n            ongoing and :math:`I^{(n)}_t=0` otherwise. This allows us to write\n            the bootstrapped target as:\n\n            .. math::\n\n                G^{(n)}_t=R^{(n)}_t+I^{(n)}_tQ(S_{t+n},A_{t+n})\n\n\n        S_next : nd array, shape: [batch_size, ...]\n\n            A batch of next-state observations.\n\n        P_next : 2d Tensor, dtype: int, shape: [batch_size, num_actions]\n\n            Action propensities :term:`P_next` for the (potential) next action.\n            This argument is only used if ``update_strategy='sarsa'``.\n\n        Returns\n        -------\n        Gn : 1d array, dtype: int, shape: [batch_size]\n\n            A batch of bootstrap-estimated returns\n            :math:`G^{(n)}_t=R^{(n)}_t+I^{(n)}_tQ(S_{t+n},A_{t+n})` computed\n            according to given ``update_strategy``.\n\n        \"\"\"\n        if self.update_strategy == 'sarsa':\n            assert P_next is not None\n            Q_next = self.batch_eval(\n                S_next, use_target_model=self.bootstrap_with_target_model)\n            Q_next = np.einsum('ij,ij->i', Q_next, P_next)\n        elif self.update_strategy == 'q_learning':\n            Q_next = np.max(\n                self.batch_eval(\n                    S_next, use_target_model=self.bootstrap_with_target_model),\n                axis=1)\n        elif self.update_strategy == 'double_q_learning':\n            if not self.bootstrap_with_target_model:\n                raise ValueError(\n                    \"incompatible settings: \"\n                    \"update_strategy='double_q_learning' requires that \"\n                    \"bootstrap_with_target_model=True\")\n            A_next = np.argmax(\n                self.batch_eval(S_next, use_target_model=False), axis=1)\n            Q_next = self.batch_eval(S_next, use_target_model=True)\n            Q_next = project_onto_actions_np(Q_next, A_next)\n        else:\n            raise ValueError(\"unknown update_strategy\")\n\n        Gn = Rn + In * Q_next\n        return Gn\n\n    @abstractmethod\n    def batch_eval(self, S, A=None, use_target_model=False):\n        \"\"\"\n        Evaluate the Q-function on a batch of state (or state-action)\n        observations.\n\n        Parameters\n        ----------\n        S : nd array, shape: [batch_size, ...]\n\n            A batch of state observations.\n\n        A : 1d array, dtype: int, shape: [batch_size], optional\n\n            A batch of actions that were taken.\n\n        use_target_model : bool, optional\n\n            Whether to use the :term:`target_model` internally. If False\n            (default), the :term:`predict_model` is used.\n\n        Returns\n        -------\n        Q : 1d or 2d array of floats\n\n            If action ``A`` is provided, a 1d array representing a batch of\n            :math:`q(s,a)` is returned. If, on the other hand, ``A`` is left\n            unspecified, a vector representing a batch of :math:`q(s,.)` is\n            returned instead. The shape of the latter return value is\n            ``[batch_size, num_actions]``, which is only well-defined for\n            discrete action\n            spaces.\n\n        \"\"\"\n        pass\n\n\nclass BaseQTypeI(BaseGenericQ):\n    \"\"\"\n    Base class for modeling :term:`type-I <type-I state-action value function>`\n    Q-function.\n\n    A :term:`type-I <type-I state-action value function>` Q-function is\n    implemented by mapping :math:`(s, a)\\\\mapsto q(s,a)`.\n\n    Parameters\n    ----------\n    env : gym environment\n\n        A gym environment.\n\n    train_model : keras.Model([:term:`S`, :term:`A`], :term:`Q_sa`)\n\n        Used for training.\n\n    predict_model : keras.Model([:term:`S`, :term:`A`], :term:`Q_sa`)\n\n        Used for predicting. For :term:`type-I <type-I state-action value\n        function>` Q-functions, the :term:`target_model` and\n        :term:`predict_model` are the same.\n\n    target_model : keras.Model(:term:`S`, :term:`Q_sa`)\n\n        A :term:`target_model` is used to make predictions on a bootstrapping\n        scenario. It can be advantageous to use a point-in-time copy of the\n        :term:`predict_model` to construct a bootstrapped target.\n\n    gamma : float, optional\n\n        The discount factor for discounting future rewards.\n\n    bootstrap_n : positive int, optional\n\n        The number of steps in n-step bootstrapping. It specifies the number of\n        steps over which we're willing to delay bootstrapping. Large :math:`n`\n        corresponds to Monte Carlo updates and :math:`n=1` corresponds to\n        TD(0).\n\n    bootstrap_with_target_model : bool, optional\n\n        Whether to use the :term:`target_model` when constructing a\n        bootstrapped target. If False (default), the primary\n        :term:`predict_model` is used.\n\n    update_strategy : str, optional\n\n        The update strategy that we use to select the (would-be) next-action\n        :math:`A_{t+n}` in the bootstrapped target:\n\n        .. math::\n\n            G^{(n)}_t\\\\ =\\\\ R^{(n)}_t + \\\\gamma^n Q(S_{t+n}, A_{t+n})\n\n        Options are:\n\n            'sarsa'\n                Sample the next action, i.e. use the action that was actually\n                taken.\n\n            'q_learning'\n                Take the action with highest Q-value under the current\n                estimate, i.e. :math:`A_{t+n} = \\\\arg\\\\max_aQ(S_{t+n}, a)`.\n                This is an off-policy method.\n\n            'double_q_learning'\n                Same as 'q_learning', :math:`A_{t+n} = \\\\arg\\\\max_aQ(S_{t+n},\n                a)`, except that the value itself is computed using the\n                :term:`target_model` rather than the primary model, i.e.\n\n                .. math::\n\n                    A_{t+n}\\\\ &=\\\\\n                        \\\\arg\\\\max_aQ_\\\\text{primary}(S_{t+n}, a)\\\\\\\\\n                    G^{(n)}_t\\\\ &=\\\\ R^{(n)}_t\n                        + \\\\gamma^n Q_\\\\text{target}(S_{t+n}, A_{t+n})\n\n    \"\"\"\n    def batch_eval(self, S, A=None, use_target_model=False):\n        model = self.target_model if use_target_model else self.predict_model\n\n        if A is not None:\n            Q = model.predict_on_batch([S, A])\n            check_numpy_array(Q, ndim=2, axis_size=1, axis=1)\n            Q = np.squeeze(Q, axis=1)\n            return Q  # shape: [batch_size]\n        else:\n            Q = []\n            for a in range(self.num_actions):\n                A = a * np.ones(len(S), dtype='int')\n                Q.append(self.batch_eval(S, A))\n            Q = np.stack(Q, axis=1)\n            check_numpy_array(Q, ndim=2, axis_size=self.num_actions, axis=1)\n            return Q  # shape: [batch_size, num_actions]\n\n\nclass BaseQTypeII(BaseGenericQ):\n    \"\"\"\n    Base class for modeling :term:`type-II <type-II state-action value\n    function>` Q-function.\n\n    A :term:`type-II <type-II state-action value function>` Q-function is\n    implemented by mapping :math:`s\\\\mapsto q(s,.)`.\n\n    Parameters\n    ----------\n    env : gym environment\n\n        A gym environment.\n\n    train_model : keras.Model([:term:`S`, :term:`G`], :term:`Q_s`)\n\n        Used for training.\n\n    predict_model : keras.Model(:term:`S`, :term:`Q_s`)\n\n        Used for predicting.\n\n    target_model : keras.Model(:term:`S`, :term:`Q_s`)\n\n        A :term:`target_model` is used to make predictions on a bootstrapping\n        scenario. It can be advantageous to use a point-in-time copy of the\n        :term:`predict_model` to construct a bootstrapped target.\n\n    gamma : float, optional\n\n        The discount factor for discounting future rewards.\n\n    bootstrap_n : positive int, optional\n\n        The number of steps in n-step bootstrapping. It specifies the number of\n        steps over which we're willing to delay bootstrapping. Large :math:`n`\n        corresponds to Monte Carlo updates and :math:`n=1` corresponds to\n        TD(0).\n\n    bootstrap_with_target_model : bool, optional\n\n        Whether to use the :term:`target_model` when constructing a\n        bootstrapped target. If False (default), the primary\n        :term:`predict_model` is used.\n\n    update_strategy : str, optional\n\n        The update strategy that we use to select the (would-be) next-action\n        :math:`A_{t+n}` in the bootsrapped target:\n\n        .. math::\n\n            G^{(n)}_t\\\\ =\\\\ R^{(n)}_t + \\\\gamma^n Q(S_{t+n}, A_{t+n})\n\n        Options are:\n\n            'sarsa'\n                Sample the next action, i.e. use the action that was actually\n                taken.\n\n            'q_learning'\n                Take the action with highest Q-value under the current\n                estimate, i.e. :math:`A_{t+n} = \\\\arg\\\\max_aQ(S_{t+n}, a)`.\n                This is an off-policy method.\n\n            'double_q_learning'\n                Same as 'q_learning', :math:`A_{t+n} = \\\\arg\\\\max_aQ(S_{t+n},\n                a)`, except that the value itself is computed using the\n                :term:`target_model` rather than the primary model, i.e.\n\n                .. math::\n\n                    A_{t+n}\\\\ &=\\\\\n                        \\\\arg\\\\max_aQ_\\\\text{primary}(S_{t+n}, a)\\\\\\\\\n                    G^{(n)}_t\\\\ &=\\\\ R^{(n)}_t\n                        + \\\\gamma^n Q_\\\\text{target}(S_{t+n}, A_{t+n})\n\n    \"\"\"\n    def batch_eval(self, S, A=None, use_target_model=False):\n        model = self.target_model if use_target_model else self.predict_model\n\n        if A is not None:\n            Q = model.predict_on_batch(S)  # shape: [batch_size, num_actions]\n            check_numpy_array(Q, ndim=2, axis_size=self.num_actions, axis=1)\n            check_numpy_array(\n                A, ndim=1, dtype='int', axis_size=Q.shape[0], axis=0)\n            Q = project_onto_actions_np(Q, A)\n            return Q  # shape: [batch_size]\n        else:\n            Q = model.predict_on_batch(S)\n            check_numpy_array(Q, ndim=2, axis_size=self.num_actions, axis=1)\n            return Q  # shape: [batch_size, num_actions]\n\n\nclass BaseSoftmaxPolicy(BasePolicy, BaseFunctionApproximator, NumActionsMixin, RandomStateMixin):  # noqa: E501\n    \"\"\"\n    Base class for modeling :term:`updateable policies <updateable policy>` for\n    discrete action spaces.\n\n    Parameters\n    ----------\n    env : gym environment\n\n        A gym environment.\n\n    train_model : keras.Model([:term:`S`, :term:`Adv`], :term:`Z`)\n\n        Used for training.\n\n    predict_model : keras.Model(:term:`S`, :term:`Z`)\n\n        Used for predicting.\n\n    target_model : keras.Model(:term:`S`, :term:`Z`)\n\n        A :term:`target_model` is used to make predictions on a bootstrapping\n        scenario. It can be advantageous to use a point-in-time copy of the\n        :term:`predict_model` to construct a bootstrapped target.\n\n    update_strategy : str, optional\n\n        The strategy for updating our policy. This typically determines the\n        loss function that we use for our policy function approximator.\n\n        Options are:\n\n            'vanilla'\n                Plain vanilla policy gradient. The corresponding (surrogate)\n                loss function that we use is:\n\n                .. math::\n\n                    J(\\\\theta)\\\\ =\\\\ -\\\\mathcal{A}(s,a)\\\\,\\\\ln\\\\pi(a|s,\\\\theta)\n\n            'ppo'\n                `Proximal policy optimization\n                <https://arxiv.org/abs/1707.06347>`_ uses a clipped proximal\n                loss:\n\n                .. math::\n\n                    J(\\\\theta)\\\\ =\\\\ \\\\min\\\\Big(\n                        r(\\\\theta)\\\\,\\\\mathcal{A}(s,a)\\\\,,\\\\\n                        \\\\text{clip}\\\\big(\n                            r(\\\\theta), 1-\\\\epsilon, 1+\\\\epsilon\\\\big)\n                                \\\\,\\\\mathcal{A}(s,a)\\\\Big)\n\n                where :math:`r(\\\\theta)` is the probability ratio:\n\n                .. math::\n\n                    r(\\\\theta)\\\\ =\\\\ \\\\frac\n                        {\\\\pi(a|s,\\\\theta)}\n                        {\\\\pi(a|s,\\\\theta_\\\\text{old})}\n\n            'cross_entropy'\n                Straightforward categorical cross-entropy (from logits). This\n                loss function does *not* make use of the advantages\n                :term:`Adv`. Instead, it minimizes the cross entropy between\n                the behavior policy :math:`\\\\pi_b(a|s)` and the learned policy\n                :math:`\\\\pi_\\\\theta(a|s)`:\n\n                .. math::\n\n                    J(\\\\theta)\\\\ =\\\\ \\\\hat{\\\\mathbb{E}}_t\\\\left\\\\{\n                        -\\\\sum_a \\\\pi_b(a|S_t)\\\\, \\\\log \\\\pi_\\\\theta(a|S_t)\n                    \\\\right\\\\}\n\n    ppo_clipping : float, optional\n\n        The clipping parameter :math:`\\\\epsilon` in the PPO clipped surrogate\n        loss. This option is only applicable if ``update_strategy='ppo'``.\n\n    entropy_bonus : float, optional\n\n        The coefficient of the entropy bonus term in the policy objective.\n\n    random_seed : int, optional\n\n        Sets the random state to get reproducible results.\n\n    \"\"\"\n    UPDATE_STRATEGIES = ('vanilla', 'ppo', 'cross_entropy')\n\n    def __init__(\n            self, env, train_model, predict_model, target_model,\n            update_strategy='vanilla',\n            ppo_clipping=0.2,\n            entropy_bonus=0.01,\n            random_seed=None):\n\n        self.env = env\n        self.train_model = train_model\n        self.predict_model = predict_model\n        self.target_model = target_model\n        self.update_strategy = update_strategy\n        self.ppo_clipping = float(ppo_clipping)\n        self.entropy_bonus = float(entropy_bonus)\n        self.random_seed = random_seed  # sets self.random in RandomStateMixin\n\n        # TODO: allow for non-discrete action spaces\n        self._actions = np.arange(self.num_actions)\n\n    def __call__(self, s, use_target_model=False):\n        \"\"\"\n        Draw an action from the current policy :math:`\\\\pi(a|s)`.\n\n        Parameters\n        ----------\n        s : state observation\n\n            A single state observation.\n\n        use_target_model : bool, optional\n\n            Whether to use the :term:`target_model` internally. If False\n            (default), the :term:`predict_model` is used.\n\n        Returns\n        -------\n        a : action\n\n            A single action proposed under the current policy.\n\n        \"\"\"\n        proba = self.proba(s, use_target_model=use_target_model)\n        a = self.random.choice(self._actions, p=proba)\n        return a\n\n    def proba(self, s, use_target_model=False):\n        \"\"\"\n        Get the probabilities over all actions :math:`\\\\pi(a|s)`.\n\n        Parameters\n        ----------\n        s : state observation\n\n            A single state observation.\n\n        use_target_model : bool, optional\n\n            Whether to use the :term:`target_model` internally. If False\n            (default), the :term:`predict_model` is used.\n\n        Returns\n        -------\n        pi : 1d array, shape: [num_actions]\n\n            Probabilities over all actions.\n\n            **Note.** This hasn't yet been implemented for non-discrete action\n            spaces.\n\n        \"\"\"\n        assert self.env.observation_space.contains(s)\n        S = np.expand_dims(s, axis=0)\n        P = self.batch_eval(S, use_target_model=use_target_model)\n        check_numpy_array(P, shape=(1, self.num_actions))\n        pi = np.squeeze(P, axis=0)\n        return pi\n\n    def greedy(self, s, use_target_model=False):\n        \"\"\"\n        Draw the greedy action, i.e. :math:`\\\\arg\\\\max_a\\\\pi(a|s)`.\n\n        Parameters\n        ----------\n        s : state observation\n\n            A single state observation.\n\n        use_target_model : bool, optional\n\n            Whether to use the :term:`target_model` internally. If False\n            (default), the :term:`predict_model` is used.\n\n        Returns\n        -------\n        a : action\n\n            A single action proposed under the current policy.\n\n        \"\"\"\n        a = argmax(self.proba(s, use_target_model=use_target_model))\n        return a\n\n    def update(self, s, pi, advantage):\n        \"\"\"\n        Update the policy.\n\n        Parameters\n        ----------\n        s : state observation\n\n            A single state observation.\n\n        pi : 1d array, shape: [num_actions]\n\n            Vector of action propensities under the behavior policy. This may\n            be just an indicator if the action propensities are inferred\n            through sampling, e.g. if we have four possible actions ``pi = [0,\n            0, 1, 0]`` would indicate that the action :math:`a=2` was drawn\n            from the behavior policy.\n\n        advantage : float\n\n            A value for the advantage :math:`\\\\mathcal{A}(s,a) = q(s,a) -\n            v(s)`. This might be sampled and/or estimated version of the true\n            advantage.\n\n        \"\"\"\n        assert self.env.observation_space.contains(s)\n        check_numpy_array(pi, ndim=1, axis_size=self.num_actions, axis=0)\n\n        S = np.expand_dims(s, axis=0)\n        P = np.expand_dims(pi, axis=0)\n        Adv = np.expand_dims(advantage, axis=0)\n        self.batch_update(S, P, Adv)\n\n    def batch_eval(self, S, use_target_model=False):\n        \"\"\"\n        Evaluate the policy on a batch of state observations.\n\n        Parameters\n        ----------\n        S : nd array, shape: [batch_size, ...]\n\n            A batch of state observations.\n\n        use_target_model : bool, optional\n\n            Whether to use the :term:`target_model` internally. If False\n            (default), the :term:`predict_model` is used.\n\n        Returns\n        -------\n        P : 2d array, shape: [batch_size, num_actions]\n\n            A batch of predicted action probabilities :math:`\\\\pi(a|s)`.\n\n        \"\"\"\n        model = self.target_model if use_target_model else self.predict_model\n\n        Z = model.predict_on_batch(S)\n        check_numpy_array(Z, ndim=2, axis_size=self.num_actions, axis=1)\n        P = softmax(Z, axis=1)\n        return P  # shape: [batch_size, num_actions]\n\n    def batch_update(self, S, P, Adv):\n        \"\"\"\n        Update the policy on a batch of transitions.\n\n        Parameters\n        ----------\n        S : nd array, shape: [batch_size, ...]\n\n            A batch of state observations.\n\n        P : 2d Tensor, dtype: int, shape: [batch_size]\n\n            A batch of action propensities. :term:`P` is typically just an\n            indicator for which action was chosen by the behavior policy. In\n            this sense, :term:`P` acts as a projector more than a prediction\n            target. That is, :term:`P` is used to project our predicted values\n            down to those for which we actually received the feedback signal:\n            :term:`Adv`.\n\n        Adv : 1d array, dtype: float, shape: [batch_size]\n\n            A value for the :term:`advantage <Adv>` :math:`\\\\mathcal{A}(s,a) = q(s,a) -\n            v(s)`. This might be sampled and/or estimated version of the true\n            advantage.\n\n        Returns\n        -------\n        losses : dict\n\n            A dict of losses/metrics, of type ``{name <str>: value <float>}``.\n\n        \"\"\"\n        check_numpy_array(P, ndim=2, axis_size=self.num_actions, axis=1)\n        losses = self._train_on_batch([S, Adv], P)\n        return losses\n\n    def _policy_loss(self, Adv, Z_target=None):\n        if self.update_strategy == 'vanilla':\n            return SoftmaxPolicyLossWithLogits(\n                Adv, entropy_bonus=self.entropy_bonus)\n\n        if self.update_strategy == 'ppo':\n            assert Z_target is not None\n            return ClippedSurrogateLoss(\n                Adv, Z_target, entropy_bonus=self.entropy_bonus,\n                epsilon=self.ppo_clipping)\n\n        if self.update_strategy == 'cross_entropy':\n            return keras.losses.CategoricalCrossentropy(from_logits=True)\n\n        raise ValueError(\n            \"unknown update_strategy '{}'\".format(self.update_strategy))\n", "meta": {"hexsha": "a5dfa8777dc2c8aebcc0a0209d13d56b1d965218", "size": 36018, "ext": "py", "lang": "Python", "max_stars_repo_path": "keras_gym/function_approximators/base.py", "max_stars_repo_name": "axb2035/keras-gym", "max_stars_repo_head_hexsha": "076ebbca022f4dbdcae2a14967f824652fe473c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "keras_gym/function_approximators/base.py", "max_issues_repo_name": "axb2035/keras-gym", "max_issues_repo_head_hexsha": "076ebbca022f4dbdcae2a14967f824652fe473c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "keras_gym/function_approximators/base.py", "max_forks_repo_name": "axb2035/keras-gym", "max_forks_repo_head_hexsha": "076ebbca022f4dbdcae2a14967f824652fe473c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4779080252, "max_line_length": 111, "alphanum_fraction": 0.5731023377, "include": true, "reason": "import numpy", "num_tokens": 8493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.17524855101769718}}
{"text": "import numpy as np\nimport cv2\n\ndef py_cpu_nms_in_numpy(dets, thresh):\n    \"\"\"Pure Python NMS baseline.\"\"\"\n    # 所有图片的坐标信息，字典形式储存\n    x1 = dets[:, 0]\n    y1 = dets[:, 1]\n    x2 = dets[:, 2]\n    y2 = dets[:, 3]\n    scores = dets[:, 4]##bbox打分\n    # 计算出所有图片的面积\n    areas = (x2 - x1 + 1) * (y2 - y1 + 1)\n    # 打分从大到小排列，取index\n    order = scores.argsort()[::-1]\n\n    keep = [] # 用来存放最后保留的图片的相应评分\n    while order.size > 0:\n        # order[0]是当前分数最大的窗口，肯定保留\n        i = order[0]\n        keep.append(i)# 保留改图片的值\n        # 计算窗口i与其他所有窗口的交叠部分的面积\n        xx1 = np.maximum(x1[i], x1[order[1:]])\n        yy1 = np.maximum(y1[i], y1[order[1:]])\n        xx2 = np.minimum(x2[i], x2[order[1:]])\n        yy2 = np.minimum(y2[i], y2[order[1:]])\n        # 计算出各个相交矩形的面积\n        w = np.maximum(0.0, xx2 - xx1 + 1)\n        h = np.maximum(0.0, yy2 - yy1 + 1)\n        inter = w * h\n        # 交/并得到iou值\n        ovr = inter / (areas[i] + areas[order[1:]] - inter)\n        # inds为所有与窗口i的iou值小于threshold值的窗口的index，其他窗口此次都被窗口i吸收\n        inds = np.where(ovr <= thresh)[0]\n        # order里面只保留与窗口i交叠面积小于threshold的那些窗口，由于ovr长度比order长度少1(不包含i)，所以inds+1对应到保留的窗口\n        order = order[inds + 1]\n\n    return keep\n\ndef point_form(boxes):\n    \"\"\" Convert prior_boxes to (xmin, ymin, xmax, ymax)\n    representation for comparison to point form ground truth data.\n    Args:\n        boxes: (tensor) center-size default boxes from priorbox layers.\n    Return:\n        boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.\n    \"\"\"\n    \"\"\"\n    将以前的方框转换为（xmin、ymin、xmax、ymax）\n\t用于与点格式地面真实数据进行比较的表示。\n\t参数：\n\tbox:（tensor）中心大小priorbox层的默认框。\n\t返回：\n\t盒子：（张量）转换成盒子的xmin，ymin，xmax，ymax形式。\n    \"\"\"\n    return np.concatenate((boxes[:, :2] - boxes[:, 2:]/2,     # xmin, ymin\n                     boxes[:, :2] + boxes[:, 2:]/2), 1)  # xmax, ymax\n\ndef center_size(boxes):\n    \"\"\" Convert prior_boxes to (cx, cy, w, h)\n    representation for comparison to center-size form ground truth data.\n    Args:\n        boxes: (tensor) point_form boxes\n    Return:\n        boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.\n    \"\"\"\n    return np.concatenate(((boxes[:, 2:] + boxes[:, :2])/2, boxes[:, 2:] - boxes[:, :2]), 1) # cx, cy # w, h\n\ndef intersect(box_a, box_b):\n    \"\"\" We resize both tensors to [A,B,2] without new malloc:\n    [A,2] -> [A,1,2] -> [A,B,2]\n    [B,2] -> [1,B,2] -> [A,B,2]\n    Then we compute the area of intersect between box_a and box_b.\n    Args:\n      box_a: (tensor) bounding boxes, Shape: [A,4].\n      box_b: (tensor) bounding boxes, Shape: [B,4].\n    Return:\n      (tensor) intersection area, Shape: [A,B].\n      将以前的方框转换为（cx，cy，w，h）\n\t用于与地面真值数据中心大小进行比较的表示。\n\t参数：\n\t方块：（张量）点式方块\n\t返回：\n\tbox:（张量）转换成xmin，ymin，xmax，ymax形式的box\n    \"\"\"\n    box_a = box_a.cpu()\n    box_b = box_b.cpu()\n    A = box_a.size(0)\n    B = box_b.size(0)\n    max_xy = np.min(box_a[:, 2:].unsqueeze(1).expand(A, B, 2),\n                       box_b[:, 2:].unsqueeze(0).expand(A, B, 2))\n    min_xy = np.max(box_a[:, :2].unsqueeze(1).expand(A, B, 2),\n                       box_b[:, :2].unsqueeze(0).expand(A, B, 2))\n    inter = np.clip((max_xy - min_xy), min=0)\n    return inter[:, :, 0] * inter[:, :, 1]\n\ndef jaccard(box_a, box_b):\n    \"\"\"Compute the jaccard overlap of two sets of boxes.  The jaccard overlap\n    is simply the intersection over union of two boxes.  Here we operate on\n    ground truth boxes and default boxes.\n    E.g.:\n        A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B)\n    Args:\n        box_a: (tensor) Ground truth bounding boxes, Shape: [num_objects,4]\n        box_b: (tensor) Prior boxes from priorbox layers, Shape: [num_priors,4]\n    Return:\n        jaccard overlap: (tensor) Shape: [box_a.size(0), box_b.size(0)]\n \t计算两组盒子的重叠相似系数。\n\n重叠相似只是两个框的并集上的交集。\n\n在这里，我们操作地面真相框和默认框。\n\n例如。：\n\nA∩B/A∪B=A∩B/（面积（A）+面积（B）-A∩B）\n\n参数：\n\nbox_a:（张量）地面真值边界框，形状：[num_aobjects，4]\n\nbox_b:（张量）来自priorbox层的先前盒，形状：[num_priors，4]\n\n返回：\n\n重叠相似：（张量）形状：[框a.尺寸（0），框b.尺寸（0）]\n    \"\"\"\n    inter = intersect(box_a, box_b)\n    area_a = ((box_a[:, 2]-box_a[:, 0]) *\n              (box_a[:, 3]-box_a[:, 1])).unsqueeze(1).expand_as(inter)  # [A,B]\n    area_b = ((box_b[:, 2]-box_b[:, 0]) *\n              (box_b[:, 3]-box_b[:, 1])).unsqueeze(0).expand_as(inter)  # [A,B]\n    union = area_a + area_b - inter\n    return inter / union  # [A,B]\n\ndef matrix_iou(a, b):\n    \"\"\"\n    return iou of a and b, numpy version for data augenmentation\n    返回a和b的iou，numpy版本进行数据补充\n    \"\"\"\n    lt = np.maximum(a[:, np.newaxis, :2], b[:, :2])\n    rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:])\n\n    area_i = (np.prod(rb - lt, axis=2) * (lt < rb)).all(axis=2)\n    area_a = np.prod(a[:, 2:] - a[:, :2], axis=1)\n    area_b = np.prod(b[:, 2:] - b[:, :2], axis=1)\n    return area_i / (area_a[:, np.newaxis] + area_b - area_i)\n\ndef matrix_iof(a, b):\n    \"\"\"\n    matrix_iof 的意思是裁剪后的roi除以boxes,有全覆盖的则留下。\n    return iof of a and b, numpy version for data augenmentation\n    返回a和b的iof，numpy版本进行数据补充\n    \"\"\"\n    lt = np.maximum(a[:, np.newaxis, :2], b[:, :2])#x1 y1 最大值\n    rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:])# x2 y2 最小值\n\n    area_i = (np.prod(rb - lt, axis=2) * (lt < rb)).all(axis=2)#连乘 即面积\n    area_a = np.prod(a[:, 2:] - a[:, :2], axis=1)\n    return area_i / np.maximum(area_a[:, np.newaxis], 1)\n\ndef match(threshold, truths, priors, variances, labels, landms, loc_t, conf_t, landm_t, idx):\n    \"\"\"Match each prior box with the ground truth box of the highest jaccard\n    overlap, encode the bounding boxes, then return the matched indices\n    corresponding to both confidence and location preds.\n    Args:\n        threshold: (float) The overlap threshold used when mathing boxes.\n        truths: (tensor) Ground truth boxes, Shape: [num_obj, 4].\n        priors: (tensor) Prior boxes from priorbox layers, Shape: [n_priors,4].\n        variances: (tensor) Variances corresponding to each prior coord,\n            Shape: [num_priors, 4].\n        labels: (tensor) All the class labels for the image, Shape: [num_obj].\n        landms: (tensor) Ground truth landms, Shape [num_obj, 10].\n        loc_t: (tensor) Tensor to be filled w/ endcoded location targets.\n        conf_t: (tensor) Tensor to be filled w/ matched indices for conf preds.\n        landm_t: (tensor) Tensor to be filled w/ endcoded landm targets.\n        idx: (int) current batch index\n    Return:\n        The matched indices corresponding to 1)location 2)confidence 3)landm preds.\n    \"\"\"\n    # jaccard index\n    # # 第1步,计算IOU\n    overlaps = jaccard(\n        truths,\n        point_form(priors)\n    )\n    # (Bipartite Matching)\n    # [1,num_objects] best prior for each ground truth\n    # 第2步,为每个真实框匹配一个IOU最大的锚点框,GT框->锚点框\n    # best_prior_overlap为每个真实框的最大IOU值,shape[num_objects,1]\n    # best_prior_idx为对应的最大IOU的先验锚点框的Index,其元素值的范围为[0,num_priors]\n    best_prior_overlap, best_prior_idx = overlaps.max(1, keepdim=True)\n\n    # ignore hard gt\n    valid_gt_idx = best_prior_overlap[:, 0] >= 0.2\n    best_prior_idx_filter = best_prior_idx[valid_gt_idx, :]\n    if best_prior_idx_filter.shape[0] <= 0:\n        loc_t[idx] = 0\n        conf_t[idx] = 0\n        return\n\n    # [1,num_priors] best ground truth for each prior\n    # 第3步,若先验锚点框与GT框的IOU>阈值,也将这些锚点框匹配上,锚点框->GT框\n    # best_truth_overlap为每个先验锚点框对应其中一个真实框的最大IOU,shape[1,num_priors]\n    # best_truth_idx为每个先验锚点框对应的真实框的index,其元素值的范围为[0,num_objects]\n\n    best_truth_overlap, best_truth_idx = overlaps.max(0, keepdim=True)\n    best_truth_idx.squeeze_(0)\n    best_truth_overlap.squeeze_(0)\n    best_prior_idx.squeeze_(1)\n    best_prior_idx_filter.squeeze_(1)\n    best_prior_overlap.squeeze_(1)\n    # 第4步\n    # index_fill_(self, dim: _int, index: Tensor, value: Number)对第dim行的index使用value进行填充\n    # best_truth_overlap为第一步匹配的结果,需要使用到,使用best_prior_idx是第二步的结果,也是需要使用上的\n    # 所以在best_truth_overlap上进行填充,表明选出来的正例\n    # 使用2进行填充,是因为,IOU值的范围是[0,1],只要使用大于1的值填充,就表明肯定能被选出来\n    best_truth_overlap.index_fill_(0, best_prior_idx_filter, 2)  # ensure best prior\n    # TODO refactor: index  best_prior_idx with long tensor\n    # ensure every gt matches with its prior of max overlap\n    # 确保每个GT框都能匹配上最大IOU的先验锚点框\n    # 得到每个先验锚点框都能有一个匹配上的数字\n    # best_prior_idx的元素值的范围是[0,num_priors],长度为num_objects\n    for j in range(best_prior_idx.size(0)):     # 判别此anchor是预测哪一个boxes\n        best_truth_idx[best_prior_idx[j]] = j\n    #box\n    matches = truths[best_truth_idx]            # 取出最佳匹配的GT框,Shape: [num_priors,4]\n    conf = labels[best_truth_idx]                # Shape: [num_priors],0为背景,\n    conf[best_truth_overlap < threshold] = 0     # 置信度小于阈值的label设置为0\n    loc = encode(matches, priors, variances)    # 进行位置编码\n\n    #landm\n    matches_landm = landms[best_truth_idx]      # 取出最佳匹配的landm\n    landm = encode_landm(matches_landm, priors, variances)# 进行位置编码\n    loc_t[idx] = loc    # [num_priors,4] encoded offsets to learn应该学习的编码偏差\n    conf_t[idx] = conf  # [num_priors] top class label for each prior每个锚点框的label\n    landm_t[idx] = landm #应该学习的编码偏差\n\ndef encode(matched, priors, variances):\n    \"\"\"Encode the variances from the priorbox layers into the ground truth boxes\n    we have matched (based on jaccard overlap) with the prior boxes.\n    Args:\n        matched: (tensor) Coords of ground truth for each prior in point-form\n            Shape: [num_priors, 4].\n        priors: (tensor) Prior boxes in center-offset form\n            Shape: [num_priors,4].\n        variances: (list[float]) Variances of priorboxes\n    Return:\n        encoded boxes (tensor), Shape: [num_priors, 4]\n        对坐标进行编码\n        利用GT框和先验锚点框,计算偏差,用于回归\n    \"\"\"\n\n    # dist b/t match center and prior's center\n    g_cxcy = (matched[:, :2] + matched[:, 2:])/2 - priors[:, :2] # 计算GT框与锚点框中心点的距离\n    # encode variance\n    g_cxcy /= (variances[0] * priors[:, 2:])\n    # match wh / prior wh\n    g_wh = (matched[:, 2:] - matched[:, :2]) / priors[:, 2:]\n    g_wh = np.log(g_wh) / variances[1]\n    # return target for smooth_l1_loss\n    return np.concatenate([g_cxcy, g_wh], 1)  # [num_priors,4]\n\ndef encode_landm(matched, priors, variances):\n\n    \"\"\"Encode the variances from the priorbox layers into the ground truth boxes\n    we have matched (based on jaccard overlap) with the prior boxes.\n    Args:\n        matched: (tensor) Coords of ground truth for each prior in point-form\n            Shape: [num_priors, 10].\n        priors: (tensor) Prior boxes in center-offset form\n            Shape: [num_priors,4].\n        variances: (list[float]) Variances of priorboxes\n    Return:\n        encoded landm (tensor), Shape: [num_priors, 10]\n    对landm坐标进行编码\n    \"\"\"\n\n    # dist b/t match center and prior's center\n    matched = np.reshape(matched, (matched.size(0), 5, 2))\n    priors_cx = priors[:, 0].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2)\n    priors_cy = priors[:, 1].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2)\n    priors_w = priors[:, 2].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2)\n    priors_h = priors[:, 3].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2)\n    priors = np.concatenate([priors_cx, priors_cy, priors_w, priors_h], 2)\n    g_cxcy = matched[:, :, :2] - priors[:, :, :2]\n    # encode variance\n    g_cxcy /= (variances[0] * priors[:, :, 2:])\n    # g_cxcy /= priors[:, :, 2:]\n    g_cxcy = g_cxcy.reshape(g_cxcy.size(0), -1)\n    # return target for smooth_l1_loss\n    return g_cxcy\n\n# Adapted from https://github.com/Hakuyume/chainer-ssd\ndef decode_in_numpy(loc, priors, variances):\n    \"\"\"Decode locations from predictions using priors to undo\n    the encoding we did for offset regression at train time.\n    Args:\n        loc (tensor): location predictions for loc layers,\n            Shape: [num_priors,4]网络预测的锚点框偏差信息\n        priors (tensor): Prior boxes in center-offset form.\n            Shape: [num_priors,4].先验锚点框\n        variances: (list[float]) Variances of priorboxes预测框的坐标\n    Return:\n        decoded bounding box predictions\n    对编码的坐标进行解码,返回预测框的坐标\n    \"\"\"\n    # [中心点x,中心点y,宽,高]\n    boxes = np.concatenate((\n        priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:],\n        priors[:, 2:] * np.exp(loc[:, 2:] * variances[1])), 1)\n\n    boxes[:, :2] -= boxes[:, 2:] / 2 # xmin,ymin\n    boxes[:, 2:] += boxes[:, :2] # xmax,ymax\n    return boxes\n\ndef decode_landm_in_numpy(pre, priors, variances):\n    \"\"\"Decode landm from predictions using priors to undo\n    the encoding we did for offset regression at train time.\n    Args:\n        pre (tensor): landm predictions for loc layers,\n            Shape: [num_priors,10]\n        priors (tensor): Prior boxes in center-offset form.\n            Shape: [num_priors,4].\n        variances: (list[float]) Variances of priorboxes\n    Return:\n        decoded landm predictions\n    \"\"\"\n    landms = np.concatenate((priors[:, :2] + pre[:, :2] * variances[0] * priors[:, 2:],\n                        priors[:, :2] + pre[:, 2:4] * variances[0] * priors[:, 2:],\n                        priors[:, :2] + pre[:, 4:6] * variances[0] * priors[:, 2:],\n                        priors[:, :2] + pre[:, 6:8] * variances[0] * priors[:, 2:],\n                        priors[:, :2] + pre[:, 8:10] * variances[0] * priors[:, 2:],\n                        ), axis=1)#五个特征点\n    return landms\ndef log_sum_exp(x):\n    \"\"\"Utility function for computing log_sum_exp while determining\n    This will be used to determine unaveraged confidence loss across\n    all examples in a batch.\n    Args:\n        x (Variable(tensor)): conf_preds from conf layers\n    确定时用于计算的实用函数（log_sum_exp）\n\n这将用于确定批处理中所有示例的不可用信心损失。\n\n参数：\n\nx（变量（张量）：来自conf层的conf preds\n    \"\"\"\n    x_max = x.data.max()\n    return np.log(np.sum(np.exp(x-x_max), 1, keepdims=True)) + x_max\n\n\ndef shift_img(img,dx,dy,fill_with =0):\n    '''\n    平移图片\n    :param img: 需要操作的图片\n    :param dx: 向右平移多少\n    :param dy: 向下平移多少\n    :param fill_with: 多的部分用什么填充\n    :return:img 操作之后的图片\n    '''\n    M = np.array([[1,0,dx],[0,1,dy]])\n    shifted = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))\n    return shifted\n\ndef rotate_img(img,angle,circle):\n    '''\n    旋转图片\n    :param img:需要操作的图片\n    :param angle: 旋转角度\n    :param circle: 旋转圆心\n    :return: 操作之后的图片\n    '''\n    M = cv2.getRotationMatrix2D((circle[0], circle[1]), angle, 1)\n    rotate = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))\n    return rotate", "meta": {"hexsha": "83651e877a8e4e94bea4346987da0938ec845589", "size": 14088, "ext": "py", "lang": "Python", "max_stars_repo_path": "knn/utils/retinaface_tool_in_numpy.py", "max_stars_repo_name": "Starman-SWA/Face-recognition-trolley-based-on-AX7010-FPGA-board", "max_stars_repo_head_hexsha": "d518158c20da4b3f2536867cfda30848911d08c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-05T03:17:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-05T03:17:43.000Z", "max_issues_repo_path": "knn/utils/retinaface_tool_in_numpy.py", "max_issues_repo_name": "Starman-SWA/Face-recognition-trolley-based-on-AX7010-FPGA-board", "max_issues_repo_head_hexsha": "d518158c20da4b3f2536867cfda30848911d08c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "knn/utils/retinaface_tool_in_numpy.py", "max_forks_repo_name": "Starman-SWA/Face-recognition-trolley-based-on-AX7010-FPGA-board", "max_forks_repo_head_hexsha": "d518158c20da4b3f2536867cfda30848911d08c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-20T12:36:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-05T03:37:30.000Z", "avg_line_length": 37.3687002653, "max_line_length": 108, "alphanum_fraction": 0.6210959682, "include": true, "reason": "import numpy", "num_tokens": 5193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.17524855101769718}}
{"text": "# Copyright 2021 Calico LLC\n# Copyright 2021 DeepMind Technologies Limited\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport time\nimport os\nimport glob\nimport json\nimport functools\nimport inspect\nfrom pathlib import Path\n\nimport tensorflow as tf\nfrom tqdm import tqdm\nimport numpy as np\nimport pandas as pd\nfrom typing import Any, Callable, Dict, Optional, Text, Union, Iterable, List, Sequence\n\nimport sonnet as snt\nfrom sonnet.src import base, once, types, utils\nfrom sonnet.src.optimizers import optimizer_utils\n\nimport tensorflow as tf\nimport wandb\n\n# attribute\n\n# Enformer tensorflow code was directly taken and modified for distributed training\n# https://github.com/deepmind/deepmind-research/tree/master/enformer\n\n# Genetic augmentation code was taken from\n# https://github.com/calico/basenji/blob/84c681a4b02f592a3de90799cee7f17d96f81ef8/basenji/archive/augmentation.py\n\n# constants\n\nNUM_CORES_ENFORCE = 64  # using v3-64\n\nSEQUENCE_LENGTH = 196_608\nTARGET_LENGTH = 896\nBIN_SIZE = 128\n\n# assert TPUs\n\ntpu = tf.distribute.cluster_resolver.TPUClusterResolver(tpu = 'enformer')\ntf.config.experimental_connect_to_cluster(tpu)\ntf.tpu.experimental.initialize_tpu_system(tpu)\ntpu_strategy = snt.distribute.TpuReplicator(tpu)\n\nnum_cores =  tpu_strategy.num_replicas_in_sync\nassert num_cores == NUM_CORES_ENFORCE, f'must betraining on {num_cores} cores'\n\n# optimizer\n\ndef adam_update(g, alpha, beta_1, beta_2, epsilon, t, m, v):\n  \"\"\"Implements 'Algorithm 1' from :cite:`kingma2014adam`.\"\"\"\n  m = beta_1 * m + (1. - beta_1) * g      # Biased first moment estimate.\n  v = beta_2 * v + (1. - beta_2) * g * g  # Biased second raw moment estimate.\n  m_hat = m / (1. - tf.pow(beta_1, t))    # Bias corrected 1st moment estimate.\n  v_hat = v / (1. - tf.pow(beta_2, t))    # Bias corrected 2nd moment estimate.\n  update = alpha * m_hat / (tf.sqrt(v_hat) + epsilon)\n  return update, m, v\n\n# https://github.com/deepmind/sonnet/blob/v2/sonnet/src/optimizers/adam.py\n# modified for Adam with decoupled weight decay\n\nclass Adam(base.Optimizer):\n  def __init__(self,\n               learning_rate: Union[types.FloatLike, tf.Variable] = 0.001,\n               beta1: Union[types.FloatLike, tf.Variable] = 0.9,\n               beta2: Union[types.FloatLike, tf.Variable] = 0.999,\n               epsilon: Union[types.FloatLike, tf.Variable] = 1e-8,\n               weight_decay: Union[types.FloatLike, tf.Variable] = 1e-4,\n               name: Optional[str] = None):\n    super().__init__(name=name)\n    self.learning_rate = learning_rate\n    self.beta1 = beta1\n    self.beta2 = beta2\n    self.epsilon = epsilon\n    self.weight_decay = weight_decay\n    # TODO(petebu): Consider allowing the user to pass in a step.\n    self.step = tf.Variable(0, trainable=False, name=\"t\", dtype=tf.int64)\n    self.m = []\n    self.v = []\n\n  @once.once\n  def _initialize(self, parameters: Sequence[tf.Variable]):\n    \"\"\"First and second order moments are initialized to zero.\"\"\"\n    zero_var = lambda p: utils.variable_like(p, trainable=False)\n    with tf.name_scope(\"m\"):\n      self.m.extend(zero_var(p) for p in parameters)\n    with tf.name_scope(\"v\"):\n      self.v.extend(zero_var(p) for p in parameters)\n\n  def apply(self, updates: Sequence[types.ParameterUpdate],\n            parameters: Sequence[tf.Variable]):\n    optimizer_utils.check_distribution_strategy()\n    optimizer_utils.check_updates_parameters(updates, parameters)\n    self._initialize(parameters)\n    self.step.assign_add(1)\n    for update, param, m_var, v_var in zip(updates, parameters, self.m, self.v):\n      if update is None:\n        continue\n\n      optimizer_utils.check_same_dtype(update, param)\n      learning_rate = tf.cast(self.learning_rate, update.dtype)\n      beta_1 = tf.cast(self.beta1, update.dtype)\n      beta_2 = tf.cast(self.beta2, update.dtype)\n      epsilon = tf.cast(self.epsilon, update.dtype)\n      step = tf.cast(self.step, update.dtype)\n\n      update, m, v = adam_update(\n        g=update, alpha=learning_rate, beta_1=beta_1, beta_2=beta_2,\n        epsilon=epsilon, t=step, m=m_var, v=v_var)\n\n      # decoupled weight decay\n      # hack for now to exclude biases\n      weight_decay_update = (param * self.weight_decay * learning_rate) if 'w:0' in param.name else tf.zeros_like(param)\n\n      param.assign_sub(update)\n      param.assign_sub(weight_decay_update)\n\n      m_var.assign(m)\n      v_var.assign(v)\n\n# classes\n\nclass MultiheadAttention(snt.Module):\n  \"\"\"Multi-head attention.\"\"\"\n\n  def __init__(self,\n               value_size: int,\n               key_size: int,\n               num_heads: int,\n               scaling: bool = True,\n               attention_dropout_rate: float = 0.1,\n               relative_positions: bool = False,\n               relative_position_symmetric: bool = False,\n               relative_position_functions: Optional[List[str]] = None,\n               num_relative_position_features: Optional[int] = None,\n               positional_dropout_rate: float = 0.1,\n               zero_initialize: bool = True,\n               initializer: Optional[snt.initializers.Initializer] = None,\n               name: str = None):\n    \"\"\"Creates a MultiheadAttention module.\n\n    Args:.prefetch(2)\n      value_size: The size of each value embedding per head.\n      key_size: The size of each key and query embedding per head.\n      num_heads: The number of independent queries per timestep.\n      scaling: Whether to scale the attention logits.\n      attention_dropout_rate: Dropout rate for attention logits.\n      relative_positions: Whether to use TransformerXL style relative attention.\n      relative_position_symmetric: If True, the symmetric version of basis\n        functions will be used. If False, a symmetric and asymmetric versions\n        will be use.\n      relative_position_functions: List of function names used for relative\n        positional biases.\n      num_relative_position_features: Number of relative positional features\n        to compute. If None, `value_size * num_heads` is used.\n      positional_dropout_rate: Dropout rate for the positional encodings if\n        relative positions are used.\n      zero_initialize: if True, the final linear layer will be 0 initialized.\n      initializer: Initializer for the projection layers. If unspecified,\n        VarianceScaling is used with scale = 2.0.\n      name: Name of module.\n    \"\"\"\n    super().__init__(name=name)\n    self._value_size = value_size\n    self._key_size = key_size\n    self._num_heads = num_heads\n    self._attention_dropout_rate = attention_dropout_rate\n    self._scaling = scaling\n    self._relative_positions = relative_positions\n    self._relative_position_symmetric = relative_position_symmetric\n    self._relative_position_functions = relative_position_functions\n    if num_relative_position_features is None:\n      # num_relative_position_features needs to be divisible by the number of\n      # relative positional functions *2 (for symmetric & asymmetric version).\n      divisible_by = 2 * len(self._relative_position_functions)\n      self._num_relative_position_features = (\n          (self._value_size // divisible_by) * divisible_by)\n    else:\n      self._num_relative_position_features = num_relative_position_features\n    self._positional_dropout_rate = positional_dropout_rate\n\n    self._initializer = initializer\n    if self._initializer is None:\n      self._initializer = snt.initializers.VarianceScaling(scale=2.0)\n\n    key_proj_size = self._key_size * self._num_heads\n    embedding_size = self._value_size * self._num_heads\n\n    self._q_layer = snt.Linear(\n        key_proj_size,\n        name='q_layer',\n        with_bias=False,\n        w_init=self._initializer)\n    self._k_layer = snt.Linear(\n        key_proj_size,\n        name='k_layer',\n        with_bias=False,\n        w_init=self._initializer)\n    self._v_layer = snt.Linear(\n        embedding_size,\n        name='v_layer',\n        with_bias=False,\n        w_init=self._initializer)\n    w_init = snt.initializers.Constant(1e-8) if zero_initialize else self._initializer\n    self._embedding_layer = snt.Linear(\n        embedding_size,\n        name='embedding_layer',\n        w_init=w_init,\n        b_init= snt.initializers.Constant(1e-8))\n\n    # Create additional layers if using relative positions.\n    if self._relative_positions:\n      self._r_k_layer = snt.Linear(\n          key_proj_size,\n          name='r_k_layer',\n          with_bias=False,\n          w_init=self._initializer)\n      self._r_w_bias = tf.Variable(\n          self._initializer([1, self._num_heads, 1, self._key_size],\n                            dtype=tf.float32),\n          name='r_w_bias')\n      self._r_r_bias = tf.Variable(\n          self._initializer([1, self._num_heads, 1, self._key_size],\n                            dtype=tf.float32),\n          name='r_r_bias')\n\n  def _multihead_output(self, linear, inputs):\n    \"\"\"Applies a standard linear to inputs and returns multihead output.\"\"\"\n\n    output = snt.BatchApply(linear)(inputs)  # [B, T, H * KV]\n    num_kv_channels = output.shape[-1] // self._num_heads\n    # Split H * Channels into separate axes.\n    output = snt.reshape(output,\n                         output_shape=[-1, self._num_heads, num_kv_channels])\n    # [B, T, H, KV] -> [B, H, T, KV]\n    return tf.transpose(output, [0, 2, 1, 3])\n\n  def __call__(self,\n               inputs,\n               is_training=False):\n    # Initialise the projection layers.\n    embedding_size = self._value_size * self._num_heads\n    seq_len = inputs.shape[1]\n\n    # Compute q, k and v as multi-headed projections of the inputs.\n    q = self._multihead_output(self._q_layer, inputs)  # [B, H, T, K]\n    k = self._multihead_output(self._k_layer, inputs)  # [B, H, T, K]\n    v = self._multihead_output(self._v_layer, inputs)  # [B, H, T, V]\n\n    # Scale the query by the square-root of key size.\n    if self._scaling:\n      q *= self._key_size**-0.5\n\n    if self._relative_positions:\n      # For relative positions, we project positions to form relative keys.\n      distances = tf.range(-seq_len + 1, seq_len, dtype=tf.float32)[tf.newaxis]\n      positional_encodings = positional_features_all(\n          positions=distances,\n          feature_size=self._num_relative_position_features,\n          seq_length=seq_len,\n          feature_functions=self._relative_position_functions,\n          symmetric=self._relative_position_symmetric)\n      # [1, 2T-1, Cr]\n\n      if is_training:\n        positional_encodings = tf.nn.dropout(\n            positional_encodings, rate=self._positional_dropout_rate)\n\n      # [1, H, 2T-1, K]\n      r_k = self._multihead_output(self._r_k_layer, positional_encodings)\n\n      # Add shifted relative logits to content logits.\n      # [B, H, T', T]\n      content_logits = tf.matmul(q + self._r_w_bias, k, transpose_b=True)\n      # [B, H, T', 2T-1]\n      relative_logits = tf.matmul(\n          q + self._r_r_bias, r_k, transpose_b=True)\n      #  [B, H, T', T]\n      relative_logits = relative_shift(relative_logits)\n      logits = content_logits + relative_logits\n    else:\n      # [B, H, T', T]\n      logits = tf.matmul(q, k, transpose_b=True)\n\n    weights = tf.nn.softmax(logits)\n\n    # Dropout on the attention weights.\n    if is_training:\n      weights = tf.nn.dropout(weights, rate=self._attention_dropout_rate)\n\n    # Transpose and reshape the output.\n    output = tf.matmul(weights, v)  # [B, H, T', V]\n    output_transpose = tf.transpose(output, [0, 2, 1, 3])  # [B, T', H, V]\n\n    # Final linear layer.\n    attended_inputs = snt.reshape(\n        output_transpose, output_shape=[embedding_size], preserve_dims=2)\n    output = self._embedding_layer(attended_inputs)\n\n    return output\n\ndef relative_shift(x):\n  \"\"\"Shift the relative logits like in TransformerXL.\"\"\"\n  # We prepend zeros on the final timescale dimension.\n  to_pad = tf.zeros_like(x[..., :1])\n  x = tf.concat([to_pad, x], -1)\n  _, num_heads, t1, t2 = x.shape\n  x = tf.reshape(x, [-1, num_heads, t2, t1])\n  x = tf.slice(x, [0, 0, 1, 0], [-1, -1, -1, -1])\n  x = tf.reshape(x, [-1, num_heads, t1, t2 - 1])\n  x = tf.slice(x, [0, 0, 0, 0], [-1, -1, -1, (t2 + 1) // 2])\n  return x\n\n# Available feature functions:\ndef get_positional_feature_function(name):\n  \"\"\"Returns positional feature functions.\"\"\"\n  available = {\n      'positional_features_exponential': positional_features_exponential,\n      'positional_features_central_mask': positional_features_central_mask,\n      'positional_features_gamma': positional_features_gamma\n  }\n  if name not in available:\n    raise ValueError(f'Function {name} not available in {available.keys()}')\n  return available[name]\n\n\ndef positional_features_all(positions: tf.Tensor,\n                            feature_size: int,\n                            seq_length: Optional[int] = None,\n                            bin_size: Optional[int] = None,\n                            feature_functions: Optional[List[str]] = None,\n                            symmetric=False):\n  \"\"\"Compute relative positional encodings/features.\n\n  Each positional feature function will compute/provide the same fraction of\n  features, making up the total of feature_size.\n\n  Args:\n    positions: Tensor of relative positions of arbitrary shape.\n    feature_size: Total number of basis functions.\n    seq_length: Sequence length denoting the characteristic length that\n      the individual positional features can use. This is required since the\n      parametrization of the input features should be independent of `positions`\n      while it could still require to use the total number of features.\n    bin_size: Bin sized used to partition the sequence. This can be used to\n      compute features on the absolute scale relative to the genome.\n    feature_functions: List of different feature functions to use. Each function\n      will take as argument: positions, sequence length and number of features\n      to compute.\n    symmetric: If True, the resulting features will be symmetric across the\n      relative position of 0 (i.e. only absolute value of positions will\n      matter). If false, then both the symmetric and asymmetric version\n      (symmetric multiplied by sign(positions)) of the features will be used.\n\n  Returns:\n    Tensor of shape: `positions.shape + (feature_size,)`.\n  \"\"\"\n  if feature_functions is None:\n    feature_functions = ['positional_features_exponential',\n                         'positional_features_central_mask',\n                         'positional_features_gamma']\n  num_components = len(feature_functions)  # 1 per each basis function\n  if not symmetric:\n    num_components = 2 * num_components\n\n  # For now, we do not allow odd sized embeddings.\n  if feature_size % num_components != 0:\n    raise ValueError(\n        f'feature_size has to be divisible by {num_components}')\n\n  feature_functions = [get_positional_feature_function(f)\n                       for f in feature_functions]\n  num_basis_per_class = feature_size // num_components\n  embeddings = tf.concat([f(tf.abs(positions), num_basis_per_class,\n                            seq_length, bin_size)\n                          for f in feature_functions],\n                         axis=-1)\n  if not symmetric:\n    embeddings = tf.concat([embeddings,\n                            tf.sign(positions)[..., tf.newaxis] * embeddings],\n                           axis=-1)\n  tf.TensorShape(embeddings.shape).assert_is_compatible_with(\n      positions.shape + [feature_size])\n  return embeddings\n\n\ndef _prepend_dims(x, num_dims):\n  return tf.reshape(x, shape=[1] * num_dims + x.shape)\n\n\ndef positional_features_exponential(positions: tf.Tensor,\n                                    feature_size: int,\n                                    seq_length: Optional[int] = None,\n                                    bin_size: Optional[int] = None,\n                                    min_half_life: Optional[float] = 3.0):\n  \"\"\"Create exponentially decaying positional weights.\n\n  Args:\n    positions: Position tensor (arbitrary shape).\n    feature_size: Number of basis functions to use.\n    seq_length: Sequence length.\n    bin_size: (unused). See `positional_features_all`.\n    min_half_life: Smallest exponential half life in the grid of half lives.\n\n  Returns:\n    A Tensor with shape [2 * seq_length - 1, feature_size].\n  \"\"\"\n  del bin_size  # Unused.\n  if seq_length is None:\n    seq_length = tf.reduce_max(tf.abs(positions)) + 1\n  # Grid of half lifes from [3, seq_length / 2] with feature_size\n  # distributed on the log scale.\n  seq_length = tf.cast(seq_length, dtype=tf.float32)\n  max_range = tf.math.log(seq_length) / tf.math.log(2.0)\n  half_life = tf.pow(2.0, tf.linspace(min_half_life, max_range, feature_size))\n  half_life = _prepend_dims(half_life, positions.shape.rank)\n  positions = tf.abs(positions)\n  outputs = tf.exp(-tf.math.log(2.0) / half_life * positions[..., tf.newaxis])\n  tf.TensorShape(outputs.shape).assert_is_compatible_with(\n      positions.shape + [feature_size])\n  return outputs\n\n\ndef positional_features_central_mask(positions: tf.Tensor,\n                                     feature_size: int,\n                                     seq_length: Optional[int] = None,\n                                     bin_size: Optional[int] = None):\n  \"\"\"Positional features using a central mask (allow only central features).\"\"\"\n  del seq_length  # Unused.\n  del bin_size  # Unused.\n  center_widths = tf.pow(2.0, tf.range(1, feature_size + 1, dtype=tf.float32))\n  center_widths = center_widths - 1\n  center_widths = _prepend_dims(center_widths, positions.shape.rank)\n  outputs = tf.cast(center_widths > tf.abs(positions)[..., tf.newaxis],\n                    tf.float32)\n  tf.TensorShape(outputs.shape).assert_is_compatible_with(\n      positions.shape + [feature_size])\n  return outputs\n\n\ndef gamma_pdf(x, concentration, rate):\n  \"\"\"Gamma probability distribution function: p(x|concentration, rate).\"\"\"\n  log_unnormalized_prob = tf.math.xlogy(concentration - 1., x) - rate * x\n  log_normalization = (tf.math.lgamma(concentration) -\n                       concentration * tf.math.log(rate))\n  return tf.exp(log_unnormalized_prob - log_normalization)\n\n\ndef positional_features_gamma(positions: tf.Tensor,\n                              feature_size: int,\n                              seq_length: Optional[int] = None,\n                              bin_size: Optional[int] = None,\n                              stddev=None,\n                              start_mean=None):\n  \"\"\"Positional features computed using the gamma distributions.\"\"\"\n  del bin_size  # Unused.\n  if seq_length is None:\n    seq_length = tf.reduce_max(tf.abs(positions)) + 1\n  if stddev is None:\n    stddev = seq_length / (2 * feature_size)\n  if start_mean is None:\n    start_mean = seq_length / feature_size\n  mean = tf.linspace(start_mean, seq_length, num=feature_size)\n  mean = _prepend_dims(mean, positions.shape.rank)\n  concentration = (mean / stddev)**2\n  rate = mean / stddev**2\n  probabilities = gamma_pdf(\n      tf.abs(tf.cast(positions, dtype=tf.float32))[..., tf.newaxis],\n      concentration, rate)\n  probabilities += 1e-8  # To ensure numerical stability.\n  outputs = probabilities / tf.reduce_max(probabilities)\n  tf.TensorShape(outputs.shape).assert_is_compatible_with(\n      positions.shape + [feature_size])\n  return outputs\n\nclass Enformer(snt.Module):\n  \"\"\"Main model.\"\"\"\n\n  def __init__(self,\n               channels: int = 1536,\n               num_transformer_layers: int = 11,\n               num_heads: int = 8,\n               pooling_type: str = 'attention',\n               use_convnext: bool = False,\n               name: str = 'enformer'):\n    \"\"\"Enformer model.\n\n    Args:\n      channels: Number of convolutional filters and the overall 'width' of the\n        model.\n      num_transformer_layers: Number of transformer layers.\n      num_heads: Number of attention heads.\n      pooling_type: Which pooling function to use. Options: 'attention' or max'.\n      name: Name of sonnet module.\n    \"\"\"\n    super().__init__(name=name)\n    # pylint: disable=g-complex-comprehension,g-long-lambda,cell-var-from-loop\n    heads_channels = {'human': 5313, 'mouse': 1643}\n    dropout_rate = 0.4\n    assert channels % num_heads == 0, ('channels needs to be divisible '\n                                       f'by {num_heads}')\n    whole_attention_kwargs = {\n        'attention_dropout_rate': 0.05,\n        'initializer': None,\n        'key_size': 64,\n        'num_heads': num_heads,\n        'num_relative_position_features': channels // num_heads,\n        'positional_dropout_rate': 0.01,\n        'relative_position_functions': [\n            'positional_features_exponential',\n            'positional_features_central_mask',\n            'positional_features_gamma'\n        ],\n        'relative_positions': True,\n        'scaling': True,\n        'value_size': channels // num_heads,\n        'zero_initialize': True\n    }\n\n    trunk_name_scope = tf.name_scope('trunk')\n    trunk_name_scope.__enter__()\n    from sonnet.src import moving_averages\n\n    # lambda is used in Sequential to construct the module under tf.name_scope.\n    def conv_block(filters, width=1, w_init=None, name='conv_block', **kwargs):\n      with tf.name_scope(name or \"batch_norm\"):\n        moving_mean = moving_averages.ExponentialMovingAverage(\n            0.9, name=\"moving_mean\")\n        moving_variance = moving_averages.ExponentialMovingAverage(\n            0.9, name=\"moving_variance\")\n      return Sequential(lambda: [\n          snt.distribute.CrossReplicaBatchNorm(create_scale=True,\n                        create_offset=True,\n                        moving_mean = moving_mean,\n                        moving_variance = moving_variance,\n                        scale_init=snt.initializers.Ones()),\n          gelu,\n          snt.Conv1D(filters, width, w_init=w_init, **kwargs)\n      ], name=name)\n\n    def convnext_block(filters, width=1, mult = 4, ds_conv_kernel_size = 7, w_init=None, name='convnext_block', **kwargs):\n      return Sequential(lambda: [\n          ExpandDims(2),\n          snt.DepthwiseConv2D((ds_conv_kernel_size, 1), name ='convnext_ds_conv'),\n          Squeeze(2),\n          snt.LayerNorm(axis=-1, create_scale=True, create_offset=True),\n          snt.Linear(filters * mult, name='convnext_project_in'),\n          tf.nn.relu,\n          snt.Linear(filters, name='convnext_project_out')\n      ], name=name)\n\n    conv_block_fn = convnext_block if use_convnext else conv_block\n\n    stem = Sequential(lambda: [\n        snt.Conv1D(channels // 2, 15),\n        Residual(conv_block(channels // 2, 1, name='pointwise_conv_block')),\n        pooling_module(pooling_type, pool_size=2),\n    ], name='stem')\n\n    filter_list = exponential_linspace_int(start=channels // 2, end=channels,\n                                           num=6, divisible_by=128)\n    conv_tower = Sequential(lambda: [\n        Sequential(lambda: [\n            conv_block(num_filters, 5),\n            Residual(conv_block(num_filters, 1, name='pointwise_conv_block')),\n            pooling_module(pooling_type, pool_size=2),\n            ],\n                   name=f'conv_tower_block_{i}')\n        for i, num_filters in enumerate(filter_list)], name='conv_tower')\n\n    # Transformer.\n    def transformer_mlp():\n      return Sequential(lambda: [\n          snt.LayerNorm(axis=-1, create_scale=True, create_offset=True),\n          snt.Linear(channels * 2, name = 'project_in'),\n          snt.Dropout(dropout_rate),\n          tf.nn.relu,\n          snt.Linear(channels, name = 'project_out'),\n          snt.Dropout(dropout_rate)], name='mlp')\n\n    transformer = Sequential(lambda: [\n        Sequential(lambda: [\n            Residual(Sequential(lambda: [\n                snt.LayerNorm(axis=-1,\n                              create_scale=True, create_offset=True,\n                              scale_init=snt.initializers.Ones()),\n                MultiheadAttention(**whole_attention_kwargs,\n                                                    name=f'attention_{i}'),\n                snt.Dropout(dropout_rate),\n            ], name='mha')),\n            Residual(transformer_mlp())], name=f'transformer_block_{i}')\n        for i in range(num_transformer_layers)], name='transformer')\n\n    crop_final = TargetLengthCrop1D(TARGET_LENGTH, name='target_input')\n\n    final_pointwise = Sequential(lambda: [\n        conv_block(channels * 2, 1),\n        snt.Dropout(dropout_rate / 8),\n        gelu], name='final_pointwise')\n\n    self._trunk = Sequential([stem,\n                              conv_tower,\n                              transformer,\n                              crop_final,\n                              final_pointwise],\n                             name='trunk')\n    trunk_name_scope.__exit__(None, None, None)\n\n    with tf.name_scope('heads'):\n      self._heads = {\n          head: Sequential(\n              lambda: [snt.Linear(num_channels), tf.nn.softplus],\n              name=f'head_{head}')\n          for head, num_channels in heads_channels.items()\n      }\n    # pylint: enable=g-complex-comprehension,g-long-lambda,cell-var-from-loop\n\n  @property\n  def trunk(self):\n    return self._trunk\n\n  @property\n  def heads(self):\n    return self._heads\n\n  def __call__(self, inputs: tf.Tensor,\n               is_training: bool) -> Dict[str, tf.Tensor]:\n    trunk_embedding = self.trunk(inputs, is_training=is_training)\n    return {\n        head: head_module(trunk_embedding, is_training=is_training)\n        for head, head_module in self.heads.items()\n    }\n\n  @tf.function(input_signature=[\n      tf.TensorSpec([None, SEQUENCE_LENGTH, 4], tf.float32)])\n  def predict_on_batch(self, x):\n    \"\"\"Method for SavedModel.\"\"\"\n    return self(x, is_training=False)\n\n\nclass TargetLengthCrop1D(snt.Module):\n  \"\"\"Crop sequence to match the desired target length.\"\"\"\n\n  def __init__(self, target_length: int, name='target_length_crop'):\n    super().__init__(name=name)\n    self._target_length = target_length\n\n  def __call__(self, inputs):\n    trim = (inputs.shape[-2] - self._target_length) // 2\n    if trim < 0:\n      raise ValueError('inputs longer than target length')\n\n    return inputs[..., trim:-trim, :]\n\nclass ExpandDims(snt.Module):\n\n  def __init__(self, dim: int, name='expand_dims'):\n    super().__init__(name=name)\n    self._dim = dim\n\n  def __call__(self, inputs):\n    return tf.expand_dims(inputs, self._dim)\n\nclass Squeeze(snt.Module):\n\n  def __init__(self, dim: int, name='squeeze'):\n    super().__init__(name=name)\n    self._dim = dim\n\n  def __call__(self, inputs):\n    return tf.squeeze(inputs, self._dim)\n\nclass Sequential(snt.Module):\n  \"\"\"snt.Sequential automatically passing is_training where it exists.\"\"\"\n\n  def __init__(self,\n               layers: Optional[Union[Callable[[], Iterable[snt.Module]],\n                                      Iterable[Callable[..., Any]]]] = None,\n               name: Optional[Text] = None):\n    super().__init__(name=name)\n    if layers is None:\n      self._layers = []\n    else:\n      # layers wrapped in a lambda function to have a common namespace.\n      if hasattr(layers, '__call__'):\n        with tf.name_scope(name):\n          layers = layers()\n      self._layers = [layer for layer in layers if layer is not None]\n\n  def __call__(self, inputs: tf.Tensor, is_training: bool, **kwargs):\n    outputs = inputs\n    for _, mod in enumerate(self._layers):\n      if accepts_is_training(mod):\n        outputs = mod(outputs, is_training=is_training, **kwargs)\n      else:\n        outputs = mod(outputs, **kwargs)\n    return outputs\n\n\ndef pooling_module(kind, pool_size):\n  \"\"\"Pooling module wrapper.\"\"\"\n  if kind == 'attention':\n    return SoftmaxPooling1D(pool_size=pool_size, per_channel=True,\n                            w_init_scale=2.0)\n  elif kind == 'max':\n    return tf.keras.layers.MaxPool1D(pool_size=pool_size, padding='same')\n  else:\n    raise ValueError(f'Invalid pooling kind: {kind}.')\n\n\nclass SoftmaxPooling1D(snt.Module):\n  \"\"\"Pooling operation with optional weights.\"\"\"\n\n  def __init__(self,\n               pool_size: int = 2,\n               per_channel: bool = False,\n               w_init_scale: float = 0.0,\n               name: str = 'softmax_pooling'):\n    \"\"\"Softmax pooling.\n\n    Args:\n      pool_size: Pooling size, same as in Max/AvgPooling.\n      per_channel: If True, the logits/softmax weights will be computed for\n        each channel separately. If False, same weights will be used across all\n        channels.\n      w_init_scale: When 0.0 is equivalent to avg pooling, and when\n        ~2.0 and `per_channel=False` it's equivalent to max pooling.\n      name: Module name.\n    \"\"\"\n    super().__init__(name=name)\n    self._pool_size = pool_size\n    self._per_channel = per_channel\n    self._w_init_scale = w_init_scale\n    self._logit_linear = None\n\n  @snt.once\n  def _initialize(self, num_features):\n    self._logit_linear = snt.Linear(\n        output_size=num_features if self._per_channel else 1,\n        with_bias=False,  # Softmax is agnostic to shifts.\n        w_init=snt.initializers.Identity(self._w_init_scale))\n\n  def __call__(self, inputs):\n    _, length, num_features = inputs.shape\n    self._initialize(num_features)\n    inputs = tf.reshape(\n        inputs,\n        (-1, length // self._pool_size, self._pool_size, num_features))\n    return tf.reduce_sum(\n        inputs * tf.nn.softmax(self._logit_linear(inputs), axis=-2),\n        axis=-2)\n\n\nclass Residual(snt.Module):\n  \"\"\"Residual block.\"\"\"\n\n  def __init__(self, module: snt.Module, name='residual'):\n    super().__init__(name=name)\n    self._module = module\n\n  def __call__(self, inputs: tf.Tensor, is_training: bool, *args,\n               **kwargs) -> tf.Tensor:\n    return inputs + self._module(inputs, is_training, *args, **kwargs)\n\n\ndef gelu(x: tf.Tensor) -> tf.Tensor:\n  \"\"\"Applies the Gaussian error linear unit (GELU) activation function.\n\n  Using approximiation in section 2 of the original paper:\n  https://arxiv.org/abs/1606.08415\n\n  Args:\n    x: Input tensor to apply gelu activation.\n  Returns:\n    Tensor with gelu activation applied to it.\n  \"\"\"\n  return tf.nn.sigmoid(1.702 * x) * x\n\n\ndef one_hot_encode(sequence: str,\n                   alphabet: str = 'ACGT',\n                   neutral_alphabet: str = 'N',\n                   neutral_value: Any = 0,\n                   dtype=np.float32) -> np.ndarray:\n  \"\"\"One-hot encode sequence.\"\"\"\n  def to_uint8(string):\n    return np.frombuffer(string.encode('ascii'), dtype=np.uint8)\n  hash_table = np.zeros((np.iinfo(np.uint8).max, len(alphabet)), dtype=dtype)\n  hash_table[to_uint8(alphabet)] = np.eye(len(alphabet), dtype=dtype)\n  hash_table[to_uint8(neutral_alphabet)] = neutral_value\n  hash_table = hash_table.astype(dtype)\n  return hash_table[to_uint8(sequence)]\n\n\ndef exponential_linspace_int(start, end, num, divisible_by=1):\n  \"\"\"Exponentially increasing values of integers.\"\"\"\n  def _round(x):\n    return int(np.round(x / divisible_by) * divisible_by)\n\n  base = np.exp(np.log(end / start) / (num - 1))\n  return [_round(start * base**i) for i in range(num)]\n\n\ndef accepts_is_training(module):\n  return 'is_training' in list(inspect.signature(module.__call__).parameters)\n\n# data related functions\n\n# @title `get_targets(organism)`\ndef get_targets(organism):\n  targets_txt = f'https://raw.githubusercontent.com/calico/basenji/master/manuscripts/cross2020/targets_{organism}.txt'\n  return pd.read_csv(targets_txt, sep='\\t')\n\n# @title `get_dataset(organism, subset, num_threads=8)`\n\ndef reverse_complement_transform(seq):\n  \"\"\"Reverse complement of batched onehot seq and corresponding label and na.\"\"\"\n\n  # reverse complement sequence\n  seq_rc = tf.gather(seq, [3, 2, 1, 0], axis=-1)\n  seq_rc = tf.reverse(seq_rc, axis=[0])\n  return seq_rc\n\n\ndef shift_sequence(seq, shift_amount, pad_value=0.25):\n  \"\"\"Shift a sequence left or right by shift_amount.\n  Args:\n    seq: a [batch_size, sequence_length, sequence_depth] sequence to shift\n    shift_amount: the signed amount to shift (tf.int32 or int)\n    pad_value: value to fill the padding (primitive or scalar tf.Tensor)\n  \"\"\"\n  input_shape = seq.shape\n\n  pad = pad_value * tf.ones_like(seq[0:tf.abs(shift_amount), :])\n\n  def _shift_right(_seq):\n    sliced_seq = _seq[:-shift_amount:, :]\n    return tf.concat([pad, sliced_seq], axis=0)\n\n  def _shift_left(_seq):\n    sliced_seq = _seq[-shift_amount:, :]\n    return tf.concat([sliced_seq, pad], axis=0)\n\n  output = tf.cond(\n      tf.greater(shift_amount, 0), lambda: _shift_right(seq),\n      lambda: _shift_left(seq))\n\n  output.set_shape(input_shape)\n  return output\n\ndef augment_stochastic_shifts(seq, augment_shifts):\n  \"\"\"Apply a stochastic shift augmentation.\n  Args:\n    seq: input sequence of size [batch_size, length, depth]\n    augment_shifts: list of int offsets to sample from\n  Returns:\n    shifted and padded sequence of size [batch_size, length, depth]\n  \"\"\"\n  shift_index = tf.random.uniform(shape=[], minval=0,\n      maxval=len(augment_shifts), dtype=tf.int64)\n  shift_value = tf.gather(tf.constant(augment_shifts), shift_index)\n\n  seq = tf.cond(tf.not_equal(shift_value, 0),\n                lambda: shift_sequence(seq, shift_value),\n                lambda: seq)\n\n  return seq\n\ndef augment_stochastic_shifts_map_fn(datum):\n  augment_shifts = [-2, -1, 0, 1, 2]\n  return dict(\n    sequence = augment_stochastic_shifts(datum['sequence'], augment_shifts),\n    target = datum['target']\n  )\n\ndef augment_stochastic_rc_map_fn(datum):\n  sequence, target = (datum['sequence'], datum['target'])\n  augment = tf.random.uniform(shape=[]) > 0.5\n  sequence, target = tf.cond(augment, lambda: (sequence[::-1, ::-1], target[::-1, :]),\n                              lambda: (sequence, target))\n  return dict(sequence = sequence, target = target)\n\n\ndef organism_path(organism):\n    return os.path.join(f'gs://basenji_barnyard/data', organism)\n\n\ndef get_dataset(organism, subset, num_threads=8, shuffle=True, rotate = 0, augment = False):\n  metadata = get_metadata(organism)\n  files = tfrecord_files(organism, subset) \n  files = files[rotate:] + files[:rotate]\n  dataset = tf.data.TFRecordDataset(files,\n                                    compression_type='ZLIB',\n                                    num_parallel_reads=num_threads)\n  if shuffle:\n    dataset = dataset.repeat()\n    dataset = dataset.shuffle(5000, seed = 42)\n\n  dataset = dataset.map(functools.partial(deserialize, metadata=metadata),\n                        num_parallel_calls=num_threads)\n  if augment:\n    dataset = dataset.map(augment_stochastic_shifts_map_fn, num_parallel_calls=num_threads)\n    dataset = dataset.map(augment_stochastic_rc_map_fn, num_parallel_calls=num_threads)\n\n  return dataset\n\n\ndef get_metadata(organism):\n  # Keys:\n  # num_targets, train_seqs, valid_seqs, test_seqs, seq_length,\n  # pool_width, crop_bp, target_length\n  path = os.path.join(organism_path(organism), 'statistics.json')\n  with tf.io.gfile.GFile(path, 'r') as f:\n    return json.load(f)\n\n\ndef tfrecord_files(organism, subset):\n  # Sort the values by int(*).\n  return sorted(tf.io.gfile.glob(os.path.join(\n      organism_path(organism), 'tfrecords', f'{subset}-*.tfr'\n  )), key=lambda x: int(x.split('-')[-1].split('.')[0]))\n\n\ndef deserialize(serialized_example, metadata):\n  \"\"\"Deserialize bytes stored in TFRecordFile.\"\"\"\n  feature_map = {\n      'sequence': tf.io.FixedLenFeature([], tf.string),\n      'target': tf.io.FixedLenFeature([], tf.string),\n  }\n  example = tf.io.parse_example(serialized_example, feature_map)\n  sequence = tf.io.decode_raw(example['sequence'], tf.bool)\n  sequence = tf.reshape(sequence, (metadata['seq_length'], 4))\n  sequence = tf.cast(sequence, tf.float32)\n\n  target = tf.io.decode_raw(example['target'], tf.float16)\n  target = tf.reshape(target,\n                      (metadata['target_length'], metadata['num_targets']))\n  target = tf.cast(target, tf.float32)\n\n  return {'sequence': sequence,\n          'target': target}\n\n# new get_dataset, for sequences that are actually 196_608\n\nNEW_TFRECORD_LOCATIONS = dict(\n  human = dict(\n    train = 'gs://enformer-human-train/',\n    valid = 'gs://enformer-human-valid/'\n  ),\n  mouse = dict(\n    train = 'gs://enformer-mouse-train/',\n    valid = 'gs://enformer-mouse-valid/'\n  )\n)\n\nNUM_TRACKS_CONFIG = dict(human = 5313, mouse = 1643)\n\ndef new_dataset_map_seq_target(\n  element,\n  seq_len,\n  species,  # 'human' or 'mouse'\n  target_length = 896,\n  shifts = None,\n  augment_rc = False\n):\n  assert species in NUM_TRACKS_CONFIG, f'{species} not found in config'\n  num_tracks = NUM_TRACKS_CONFIG[species]\n\n  num_shifts = 0 if shifts is None else len(list(range(shifts[0], shifts[1] + 1)))\n\n  data = {\n    'seq': tf.io.FixedLenFeature([(seq_len + num_shifts) * 4], tf.float32),\n    'target': tf.io.FixedLenFeature([target_length * num_tracks], tf.float32),\n  }\n\n  content = tf.io.parse_single_example(element, data)\n\n  content['sequence'] = content.pop('seq')\n  content['sequence'] = tf.reshape(content['sequence'], (-1, 4))\n  content['target'] = tf.reshape(content['target'], (target_length, -1))\n\n  # take care of shift augmentation\n\n  shifts = tf.pad(tf.random.uniform(shape = [1], minval = 0, maxval = num_shifts, dtype = tf.int64), [[0, 1]])\n  content['sequence'] = tf.slice(content['sequence'], shifts, (seq_len, -1))\n\n  if augment_rc:\n    content = augment_stochastic_rc_map_fn(content)\n\n  content['sequence'].set_shape(tf.TensorShape([seq_len, 4]))\n  content['target'].set_shape(tf.TensorShape([target_length, num_tracks]))\n\n  return content\n\ndef get_dataset_new(\n  organism,\n  datatype,\n  shifts = (-2, 2),\n  augment_rc = False,\n  num_threads = 8\n):\n  gcs_path = NEW_TFRECORD_LOCATIONS[organism][datatype]\n  files = sorted(tf.io.gfile.glob(f'{gcs_path}*.tfrecord'))\n\n  dataset = tf.data.TFRecordDataset(files, compression_type = 'ZLIB', num_parallel_reads = num_threads)\n  map_element_fn = partial(new_dataset_map_seq_target, seq_len = SEQUENCE_LENGTH, species = organism, shifts = shifts, augment_rc = augment_rc)\n  dataset = dataset.map(map_element_fn)\n  return dataset\n\n# training related functions\n\ndef corr_coef(x, y, eps = 0):\n  x2 = tf.math.square(x)\n  y2 = tf.math.square(y)\n  xy = x * y\n  ex = tf.reduce_mean(x, axis = 1)\n  ey = tf.reduce_mean(y, axis = 1)\n  exy = tf.reduce_mean(xy, axis = 1)\n  ex2 = tf.reduce_mean(x2, axis = 1)\n  ey2 = tf.reduce_mean(y2, axis = 1)\n  r = (exy - ex * ey) / ((tf.math.sqrt(ex2 - tf.math.square(ex) + eps) * tf.math.sqrt(ey2 - tf.math.square(ey) + eps)) + eps)\n  return tf.reduce_mean(r, axis = -1)\n\ndef create_eval_step(model, head):\n  @tf.function\n  def predict(seq, target):\n    pred = model(seq, is_training=False)[head]\n    return corr_coef(pred, target)\n  return predict\n\ndef create_step_function(model, optimizer, head, clip_grad_norm = 1.0, weight_decay = 0.0001):\n\n  @tf.function\n  def train_step(batch_seq, batch_target):\n    with tf.GradientTape() as tape:\n      with snt.mixed_precision.scope(tf.float16):\n        outputs = model(batch_seq, is_training=True)[head]\n\n      corr_coef_loss = 1 - corr_coef(outputs, batch_target, eps = 1e-8)\n      poisson = tf.reduce_mean(\n          tf.keras.losses.poisson(batch_target, outputs))\n      loss = poisson\n\n    gradients = tape.gradient(loss, model.trainable_variables, unconnected_gradients=tf.UnconnectedGradients.ZERO)\n    gradients = [tf.clip_by_norm(grad, clip_grad_norm) for grad in gradients]\n    ctx = tf.distribute.get_replica_context()\n    gradients = ctx.all_reduce(\"mean\", gradients)\n    optimizer.apply(gradients, model.trainable_variables)\n    return loss\n\n  return train_step\n\n# instantiate model and training / eval functions\n\nwith tpu_strategy.scope():\n  model = Enformer(channels=1536,\n                   num_heads=8,\n                   num_transformer_layers=11)\n\n  learning_rate = tf.Variable(0., trainable=False, name='learning_rate')\n  optimizer = snt.optimizers.Adam(learning_rate=learning_rate)\n\n  train_step_human = create_step_function(model, optimizer, 'human')\n  train_step_mouse = create_step_function(model, optimizer, 'mouse')\n\n  eval_step_human = create_eval_step(model, 'human')\n  eval_step_mouse = create_eval_step(model, 'mouse')\n\n# experiment tracker\n\nwandb.init(project='enformer')\nwandb.run.save()\n\n# Train the model\n\nnum_steps = int(2e6)\nnum_warmup_steps = 5000\ntarget_learning_rate = 5e-4\n\ncheckpoint_every = 2500\nmax_eval_steps = 25\neval_every = 500\n\n# Step variables\n\nglobal_step = tf.Variable(0, name='global_step', trainable=False)\n\n# checkpointing\n\ncheckpoint_root = \"gs://enformer/\"\ncheckpoint_name = \"enformer\"\n\nsave_prefix = os.path.join(checkpoint_root, checkpoint_name)\n\ncheckpoint = tf.train.Checkpoint(module = model,  step = global_step, optimizer = optimizer)\n\n# load latest checkpoint if possible\n\nlatest = tf.train.latest_checkpoint(checkpoint_root)\nif latest is not None:\n  checkpoint.restore(latest)\n\n@tf.function\ndef step():\n  global_step.assign(global_step + 1)\n\n  batch_human, batch_mouse = next(data_it)\n  loss_human = tpu_strategy.run(train_step_human, args = (batch_human['sequence'], batch_human['target']))\n  loss_mouse = tpu_strategy.run(train_step_mouse, args = (batch_mouse['sequence'], batch_mouse['target']))\n\n  loss_human = tpu_strategy.reduce('mean', loss_human, axis = None)\n  loss_mouse = tpu_strategy.reduce('mean', loss_mouse, axis = None)\n\n  learning_rate_frac = tf.math.minimum(1.0, tf.cast(global_step, tf.float32) / tf.math.maximum(1.0, float(num_warmup_steps)))      \n  learning_rate.assign(target_learning_rate * learning_rate_frac)\n\n  return loss_human, loss_mouse\n\n@tf.function\ndef eval_step():\n  batch_human = next(valid_human_data_it)\n  batch_mouse = next(valid_mouse_data_it)\n  human_r = tpu_strategy.run(eval_step_human, args = (batch_human['sequence'], batch_human['target']))\n  mouse_r = tpu_strategy.run(eval_step_mouse, args = (batch_mouse['sequence'], batch_mouse['target']))\n\n  human_r = tpu_strategy.reduce('mean', human_r, axis = 0)\n  mouse_r = tpu_strategy.reduce('mean', mouse_r, axis = 0)\n  return human_r, mouse_r\n\ni = global_step.numpy()\n\ntotal_mice = 114 * 256 + 111\ntotal_human = 132 * 256 + 229\nbucket_size = 256\nnum_seen = i * num_cores\nhuman_file_skip = (num_seen % total_human) // bucket_size\nmouse_file_skip = (num_seen % total_mice) // bucket_size\n\nhuman_dataset = get_dataset('human', 'train', rotate = human_file_skip).batch(num_cores, drop_remainder = True)\nmouse_dataset = get_dataset('mouse', 'train', rotate = mouse_file_skip).batch(num_cores, drop_remainder = True)\nhuman_mouse_dataset = tf.data.Dataset.zip((human_dataset, mouse_dataset)).prefetch(2)\n\nhuman_valid_dataset = get_dataset('human', 'valid', shuffle = False).repeat().batch(num_cores)\nmouse_valid_dataset = get_dataset('mouse', 'valid', shuffle = False).repeat().batch(num_cores)\n\ndata_it = iter(tpu_strategy.experimental_distribute_dataset(human_mouse_dataset))\nvalid_human_data_it = iter(tpu_strategy.experimental_distribute_dataset(human_valid_dataset))\nvalid_mouse_data_it = iter(tpu_strategy.experimental_distribute_dataset(mouse_valid_dataset))\n\nprint(f'starting from {i}')\n\nwhile i < num_steps:\n  print(f'processing step {i}')\n  loss_human, loss_mouse = step()\n  loss_human = loss_human.numpy()\n  loss_mouse = loss_mouse.numpy()\n  learning_rate_numpy = learning_rate.numpy()\n  print(f'completed step {i}')\n  log = {\n    'loss_human': loss_human,\n    'loss_mouse': loss_mouse,\n    'learning_rate': learning_rate_numpy\n  }\n\n  if i and not i % eval_every:\n    print('evaluating')\n\n    human_pearson_r, mouse_pearson_r = eval_step()\n    human_pearson_r = human_pearson_r.numpy()\n    mouse_pearson_r = mouse_pearson_r.numpy()\n\n    log = {\n      **log,\n      'human_pearson_r': human_pearson_r,\n      'mouse_pearson_r': mouse_pearson_r\n    }\n\n  wandb.log(log, step = i)\n\n  if not i % checkpoint_every:\n    print('checkpointing')\n    checkpoint.save(save_prefix)\n\n  i += 1\n", "meta": {"hexsha": "5f8c53adbbdffa079e957f01b2b1e1b974673097", "size": 44119, "ext": "py", "lang": "Python", "max_stars_repo_path": "train.py", "max_stars_repo_name": "lucidrains/enformer-tensorflow-sonnet-training-script", "max_stars_repo_head_hexsha": "6de9af047ecc1d8158afb8f12d128c6d504c5511", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-06T01:27:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T12:11:13.000Z", "max_issues_repo_path": "train.py", "max_issues_repo_name": "lucidrains/enformer-tensorflow-sonnet-training-script", "max_issues_repo_head_hexsha": "6de9af047ecc1d8158afb8f12d128c6d504c5511", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "train.py", "max_forks_repo_name": "lucidrains/enformer-tensorflow-sonnet-training-script", "max_forks_repo_head_hexsha": "6de9af047ecc1d8158afb8f12d128c6d504c5511", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-01-06T01:59:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T07:31:47.000Z", "avg_line_length": 36.7658333333, "max_line_length": 143, "alphanum_fraction": 0.6710714205, "include": true, "reason": "import numpy", "num_tokens": 10695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.1752485441769108}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n为了适应中国雷达在不同仰角的探测距离不同以及前几层仰角 dop和ref分开扫描的问题\n提出NuistRadar Object，以方便后续的算法及绘图\n\"\"\"\nimport numpy as np\nimport xarray as xr\nfrom ..configure.default_config import DEFAULT_METADATA, FILL_VALUE, CINRAD_field_mapping\nfrom ..core.transforms import antenna_vectors_to_cartesian\nfrom scipy import spatial\nfrom ..interp.RadarInterp import radar_interp2d_var, radar_interp2d\n\nclass PRD(object):\n    \"\"\"\n    Polarimetry Radar Data (PRD)\n    A class for storing antenna coordinate radar data.\n    Attributes\n    ----------\n    fields : dict\n        Moment fields. with different variables\n    scan_type : str\n        Type of scan, one of 'ppi', 'rhi', 'sector' or 'other'. If the scan\n        volume contains multiple sweep modes this should be 'other'.\n    time : datetime object\n        Time at the center of each ray.\n    range : numpy array //m\n        Range to the center of each gate (bin).\n    latitude : scalar//units:degree\n        Latitude of the instrument.\n    longitude: scalar//units:degree\n        Longitude of the instrument.\n    altitude : scalar//units:m\n        Altitude of the instrument, above sea level.\n    fixed_angle : (nsweeps) units:degree\n        Target angle for thr sweep. Azimuth angle in RHI modes, elevation\n        angle in all other modes.\n    azimuth : (nrays) units :degree\n        Azimuth of antenna, relative to true North. Azimuth angles are\n        recommended to be expressed in the range of [0, 360], but other\n        representations are not forbidden.\n    elevation : (nrays) units :degree\n        Elevation of antenna, relative to the horizontal plane. Elevation\n        angles are recommended to be expressed in the range of [-180, 180],\n        but other representations are not forbidden.\n    sweep_start_ray_index : numpy array(nsweeps)\n        Index of the first ray in each sweep relative to the start of the\n        volume, 0-based.\n    sweep_end_ray_index : numpy array(nsweeps)\n        Index of the last ray in each sweep relative to the start of the\n        volume, 0-based.\n    rays_per_sweep : numpy array (nsweeps)\n        Number of rays in each sweep. The data key of this attribute is\n        create upon first access from the data in the sweep_start_ray_index and\n        sweep_end_ray_index attributes. If the sweep locations needs to be\n        modified, do this prior to accessing this attribute or use\n        :py:func:`init_rays_per_sweep` to reset the attribute.\n    bins_per_sweep : numpy array (nsweeps)    !!!##added\n        Number of bins in each sweep. The data key of this attribute is\n        create upon first access from the data in the sweep_start_ray_index and\n        sweep_end_ray_index attributes. If the sweep locations needs to be\n        modified, do this prior to accessing this attribute or use\n        :py:func:`init_rays_per_sweep` to reset the attribute.\n    nyquist_velocity: numpy array (nsweeps) (m/s)\n    unambiguous_range:numpy array (nsweeps) (m/s)\n    frequency: constant (GHZ)\n    nrays : int\n        Number of rays in the volume.\n    nsweeps : int\n        Number of sweep in the volume.\n\n    \"\"\"\n\n    def __init__(self, fields,  scan_type, time, range, azimuth, elevation,latitude,\n                 longitude, altitude, sweep_start_ray_index, sweep_end_ray_index,\n                 fixed_angle, bins_per_sweep, nyquist_velocity, frequency, unambiguous_range,\n                 nrays, nsweeps, sitename):\n\n        super(PRD, self).__init__()\n        keys = fields.keys()\n        self.fields = []\n        for idx, (istart, iend) in enumerate(zip(sweep_start_ray_index, sweep_end_ray_index)):\n            isweep_data = xr.Dataset(coords={'azimuth': (['time', ], azimuth[istart:iend+1]),\n                                            'elevation': (['time',], elevation[istart:iend+1]),\n                                            'range': range[:bins_per_sweep[idx]], 'time': time[istart:iend+1]})\n            isweep_data.azimuth.attrs = DEFAULT_METADATA['azimuth']\n            isweep_data.elevation.attrs = DEFAULT_METADATA['elevation']\n            isweep_data.range.attrs = DEFAULT_METADATA['range']\n            isweep_data.time.attrs = DEFAULT_METADATA['time']\n            for ikey in keys:\n                isweep_data[ikey] = (['time','range'], fields[ikey][istart:iend+1, :bins_per_sweep[idx]])\n                isweep_data[ikey].attrs = DEFAULT_METADATA[CINRAD_field_mapping[ikey]]\n            self.fields.append(isweep_data)\n        self.scan_info = xr.Dataset(data_vars={\"latitude\":latitude,\"longitude\":longitude,\n                        \"altitude\":altitude,\"scan_type\":scan_type,  \"frequency\":frequency,\n                         \"nyquist_velocity\":(['sweep',], nyquist_velocity),\n                        \"unambiguous_range\":(['sweep',], unambiguous_range),\n                        \"rays_per_sweep\": (['sweep',], sweep_end_ray_index-sweep_start_ray_index+1),\n                        \"fixed_angle\": ([\"sweep\",], fixed_angle)},\n                        coords={\"sweep\": np.arange(nsweeps, dtype=int)})\n\n        self.scan_info['latitude'].attrs = DEFAULT_METADATA['latitude']\n        self.scan_info['longitude'].attrs = DEFAULT_METADATA['longitude']\n        self.scan_info['altitude'].attrs = DEFAULT_METADATA['altitude']\n        self.scan_info['scan_type'].attrs = DEFAULT_METADATA['scan_type']\n        self.scan_info['frequency'].attrs = DEFAULT_METADATA['frequency']\n        self.scan_info['nyquist_velocity'].attrs = DEFAULT_METADATA['nyquist_velocity']\n        self.scan_info['unambiguous_range'].attrs = DEFAULT_METADATA['unambiguous_range']\n        self.scan_info['rays_per_sweep'].attrs = DEFAULT_METADATA['rays_per_sweep']\n        self.scan_info['fixed_angle'].attrs = DEFAULT_METADATA['fixed_angle']\n        self.nsweeps = nsweeps\n        self.nrays = nrays\n        self.sitename = sitename\n\n    def get_vertical_section(self, start_point, end_point, field_name):\n        \"\"\"\n        :param start_point: units:m\n        :param end_point:  units:m\n        :return:\n        \"\"\"\n        start_x, start_y = start_point\n        end_x, end_y = end_point\n        bins_res = (self.fields[0].range[1] - self.fields[0].range[0]).values\n        start_end_dis = np.sqrt((start_x-end_x)**2 + (start_y-end_y)**2)\n        npoints = int(start_end_dis/(bins_res/2.) + 1)\n        x_line = np.linspace(start_x, end_x, npoints)\n        y_line = np.linspace(start_y, end_y, npoints)\n        target = np.c_[x_line, y_line]\n        xy_line_1d = np.linspace(0, start_end_dis, npoints)\n        z_values = []\n        field_values = []\n        #先对剖线取最邻近点\n        for ifield in self.fields:\n            _x, _y, _z = antenna_vectors_to_cartesian(ifield.range.values, \\\n                                ifield.azimuth.values, ifield.elevation.values)\n            kdtree = spatial.cKDTree(np.c_[_x.ravel(), _y.ravel()])\n            _distance, _idx = kdtree.query(target, k=1, n_jobs=-1)\n            _z_value = np.where(_distance > bins_res*2, np.nan, _z.ravel()[_idx])\n            _field_value = np.where(_distance > bins_res*2, np.nan, ifield[field_name].values.ravel()[_idx])\n            z_values.append(_z_value)\n            field_values.append(_field_value)\n        z_values = np.asarray(z_values)\n        field_values = np.asarray(field_values)\n        xy_line_values = np.stack([xy_line_1d,]*len(self.fields), axis=0)\n        mask_flag = (np.isnan(z_values.ravel()) | np.isnan(field_values.ravel()))\n        z_values_ravel = z_values.ravel()[~mask_flag]\n        xy_line_values_ravel = xy_line_values.ravel()[~mask_flag]\n        field_values_ravel = field_values.ravel()[~mask_flag]\n        mesh_xy, mesh_z = np.mgrid[0:start_end_dis:npoints*1j, 0:np.nanmax(z_values):bins_res/2.] #生成剖面的网格\n        grid_field = radar_interp2d_var(np.c_[xy_line_values_ravel, z_values_ravel], field_values_ravel,\\\n                              (mesh_xy, mesh_z), bandwidth=360/self.fields[0].azimuth.size)\n        return mesh_xy, mesh_z, grid_field\n", "meta": {"hexsha": "e38e24c657e436f293e853fa1fc7f2c43a8d3806", "size": 7920, "ext": "py", "lang": "Python", "max_stars_repo_path": "pycwr/core/NRadar.py", "max_stars_repo_name": "zhaopingsun/pycwr", "max_stars_repo_head_hexsha": "7459371588e6d0d6d0737e249afa3921fe073151", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-12-24T06:07:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-13T02:24:18.000Z", "max_issues_repo_path": "pycwr/core/NRadar.py", "max_issues_repo_name": "zhaopingsun/pycwr", "max_issues_repo_head_hexsha": "7459371588e6d0d6d0737e249afa3921fe073151", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pycwr/core/NRadar.py", "max_forks_repo_name": "zhaopingsun/pycwr", "max_forks_repo_head_hexsha": "7459371588e6d0d6d0737e249afa3921fe073151", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.1052631579, "max_line_length": 111, "alphanum_fraction": 0.6516414141, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.17524854417691077}}
{"text": "import numpy as np\nfrom astropy.io import fits\nimport matplotlib.pyplot as plt\nimport lightweaver.constants as Const\nfrom lightweaver.rh_atoms import H_6_atom, H_6_CRD_atom, H_3_atom, C_atom, O_atom, OI_ord_atom, Si_atom, Al_atom, CaII_atom, Fe_atom, FeI_atom, He_9_atom, He_atom, He_large_atom, MgII_atom, N_atom, Na_atom, S_atom\nfrom lightweaver.atmosphere import Atmosphere, ScaleType\nfrom lightweaver.atomic_set import RadiativeSet\nfrom lightweaver.atomic_table import get_global_atomic_table\nfrom lightweaver.molecule import MolecularTable\nfrom lightweaver.LwCompiled import LwContext\nfrom lightweaver.utils import InitialSolution\nfrom concurrent.futures import ProcessPoolExecutor, wait, as_completed\nfrom tqdm import tqdm\nfrom contextlib import redirect_stdout\nimport os\nimport pickle\n\ndef prep_atmos(data, xIdx, yIdx):\n    height = data[xIdx, yIdx, :, 0].astype('<f8') / 1e2\n    temp = data[xIdx, yIdx, :, 1].astype('<f8')\n    vlos = data[xIdx, yIdx, :, 3].astype('<f8') / 1e2\n    # pgasTop = data[xIdx, yIdx, 0, 2].astype('<f8') / (Const.CM_TO_M**2 / Const.G_TO_KG)\n    pgas = data[xIdx, yIdx, :, 2].astype('<f8') / (Const.CM_TO_M**2 / Const.G_TO_KG)\n\n    return {'height': height, 'temp': temp, 'vlos': vlos, 'pgas': pgas}\n\ndef iterate_ctx(ctx, prd=True, Nscatter=3, NmaxIter=1000):\n    for i in range(NmaxIter):\n        dJ = ctx.formal_sol_gamma_matrices()\n        if i < Nscatter:\n            continue\n        delta = ctx.stat_equil()\n        if prd:\n            dRho = ctx.prd_redistribute(maxIter=5)\n\n        if ctx.crswDone and dJ < 3e-3 and delta < 1e-3:\n            print(i)\n            print('----------')\n            return\n\nwave = np.linspace(853.9444, 854.9444, 1001)\n\ndata = fits.getdata('better_eb_310400.fits')\n# atmosData = prep_atmos(data, 10,10)\n\ndef crsw_factory(initVal=1e3):\n    val = initVal\n    def callback():\n        nonlocal val\n        val = max(1.0, val * 0.1**(1/val))\n        return val\n    return callback\n\ndef cmo_synth(atmosData, crsw=None):\n    with open(os.devnull, 'w') as f:\n        with redirect_stdout(f):\n            if crsw is not None:\n                crsw = crsw()\n            atmos = Atmosphere(ScaleType.Geometric, depthScale=atmosData['height'], temperature=atmosData['temp'], vlos=atmosData['vlos'], vturb=4000*np.ones_like(atmosData['height']))\n\n            aSet = RadiativeSet([H_3_atom(), C_atom(), O_atom(), Si_atom(), Al_atom(), CaII_atom(), Fe_atom(), He_atom(), MgII_atom(), N_atom(), Na_atom(), S_atom()])\n            aSet.set_active('H', 'Ca')\n\n            spect = aSet.compute_wavelength_grid()\n\n            atmos.convert_scales(Pgas=atmosData['pgas'])\n            atmos.quadrature(5)\n\n            mols = MolecularTable()\n            eqPops = aSet.iterate_lte_ne_eq_pops(mols, atmos)\n            ctx = LwContext(atmos, spect, eqPops, conserveCharge=True, initSol=InitialSolution.Lte, crswCallback=crsw)\n            iterate_ctx(ctx, prd=False)\n            eqPops.update_lte_atoms_Hmin_pops(atmos)\n            Iwave = ctx.compute_rays(wave, [1.0])\n            return Iwave\n\ndef cmo_synth_lte(atmosData):\n    with open(os.devnull, 'w') as f:\n        with redirect_stdout(f):\n            atmos = Atmosphere(ScaleType.Geometric, depthScale=atmosData['height'], temperature=atmosData['temp'], vlos=atmosData['vlos'], vturb=4000*np.ones_like(atmosData['height']))\n\n            aSet = RadiativeSet([H_3_atom(), C_atom(), O_atom(), Si_atom(), Al_atom(), CaII_atom(), Fe_atom(), He_atom(), MgII_atom(), N_atom(), Na_atom(), S_atom()])\n            aSet.set_active('Ca')\n\n            spect = aSet.compute_wavelength_grid()\n\n            atmos.convert_scales(Pgas=atmosData['pgas'])\n            atmos.quadrature(5)\n\n            mols = MolecularTable()\n            eqPops = aSet.iterate_lte_ne_eq_pops(mols, atmos)\n            ctx = LwContext(atmos, spect, eqPops, conserveCharge=False)\n            iterate_ctx(ctx, prd=False)\n            eqPops.update_lte_atoms_Hmin_pops(atmos)\n            Iwave = ctx.compute_rays(wave, [1.0])\n            return Iwave\n\natmosData = []\nwith open('BrokenPixels.pickle', 'rb') as pkl:\n    brokenPixels = pickle.load(pkl)\n\nfor x, y in brokenPixels:\n    atmosData.append(prep_atmos(data, x, y))\n\nwith ProcessPoolExecutor() as executor:\n    futures = [executor.submit(cmo_synth, d, crsw_factory) for d in atmosData]\n    for f in tqdm(as_completed(futures), total=len(futures)):\n        pass\n\nspectra = []\nfor f in futures:\n    try:\n        spectra.append(f.result())\n    except:\n        spectra.append(None)\n\nname = 'NlteRedo.pickle'\nwith open(name, 'wb') as f:\n    pickle.dump(spectra, f)\n\n\n\n# atmosHse = Atmosphere(ScaleType.Geometric, depthScale=atmosData['height'], temperature=atmosData['temp'], vlos=atmosData['vlos'], vturb=4000*np.ones_like(atmosData['height']))\n\n\n# atmosHse.convert_scales(Ptop=atmosData['pgas'][0])\n# atmosHse.quadrature(5)\n\n# aSet = RadiativeSet([H_3_atom(), C_atom(), O_atom(), Si_atom(), Al_atom(), CaII_atom(), Fe_atom(), He_atom(), MgII_atom(), N_atom(), Na_atom(), S_atom()])\n# aSet.set_active('Ca')\n# spectHse = aSet.compute_wavelength_grid()\n# eqPopsHse = aSet.iterate_lte_ne_eq_pops(mols, atmosHse)\n# ctxHse = LwContext(atmosHse, spectHse, eqPopsHse, conserveCharge=False, initSol=InitialSolution.Lte)\n# iterate_ctx(ctxHse, prd=False)\n# eqPopsHse.update_lte_atoms_Hmin_pops(atmosHse)\n# IwaveHse = ctxHse.compute_rays(wave, [1.0])\n\n# plt.ion()\n# plt.plot(wave, Iwave)\n# plt.plot(wave, IwaveHse)\n# plt.show()", "meta": {"hexsha": "62210cf5dc197ab6173f420698ff564dc37cda4a", "size": 5423, "ext": "py", "lang": "Python", "max_stars_repo_path": "SanjaCubeStokesIRedo.py", "max_stars_repo_name": "Goobley/LightweaverSamples", "max_stars_repo_head_hexsha": "85bf26744f7c0c01b8345ba3307bb2fefd1685a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SanjaCubeStokesIRedo.py", "max_issues_repo_name": "Goobley/LightweaverSamples", "max_issues_repo_head_hexsha": "85bf26744f7c0c01b8345ba3307bb2fefd1685a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-06-05T18:58:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-05T20:00:46.000Z", "max_forks_repo_path": "SanjaCubeStokesIRedo.py", "max_forks_repo_name": "Goobley/LightweaverSamples", "max_forks_repo_head_hexsha": "85bf26744f7c0c01b8345ba3307bb2fefd1685a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4609929078, "max_line_length": 213, "alphanum_fraction": 0.6671583994, "include": true, "reason": "import numpy,from astropy", "num_tokens": 1607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.2782568056728001, "lm_q1q2_score": 0.17523907055019383}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Sky background related\"\"\"\n\nimport os\nimport warnings\n\nimport numpy as np\n\nfrom astropy.table import Table\n\nfrom scipy.stats import sigmaclip\nfrom scipy.stats import binned_statistic_2d\n\nfrom . import utils\nfrom . import plotting\n\n__all__ = ['SkyObjs', 'AperPhot', 'S18A_APER']\n\n\nclass AperPhot():\n    \"\"\"\n    Class for aperture photometry in HSC.\n    \"\"\"\n    PIX = 0.168 # arcsec/pixe\n\n    def __init__(self, name, rad, rerun='s18a'):\n        \"\"\"Start a aperture photometry object.\"\"\"\n        self.aper_id = name\n        self.name = \"aper{0}\".format(self.aper_id)\n        self.r_pix = rad\n        self.area_pix = np.pi * (rad ** 2.0)\n        self.r_arcsec = rad * self.PIX\n        self.area_arcsec = np.pi * (self.r_arcsec ** 2.0)\n        self.rerun = rerun\n\n        # Name of the columns for flux and flux error\n        self.flux_col = self.flux(rerun=self.rerun)\n        self.err_col = self.err(rerun=self.rerun)\n\n    def flux(self, band=None, rerun='s18a'):\n        \"\"\"Aperture flux column name in S18A.\"\"\"\n        if rerun == 's18a':\n            if band is not None:\n                return \"{0}_apertureflux_{1}_flux\".format(band.strip(), self.aper_id)\n            return \"apertureflux_{0}_flux\".format(self.aper_id)\n        else:\n            raise NotImplementedError(\"# Only S18A data are available.\")\n\n    def err(self, band=None, rerun='s18a'):\n        \"\"\"Aperture flux error column name in S18A.\"\"\"\n        if rerun == 's18a':\n            if band is not None:\n                return \"{0}_{1}sigma\".format(band.strip(), self.flux(rerun=rerun))\n            return \"{0}sigma\".format(self.flux(rerun=rerun))\n        else:\n            raise NotImplementedError(\"# Only S18A data are available.\")\n\n# Aperture flux in S18A\nS18A_APER_ID = ['10', '15', '20', '30', '40', '57', '84',\n                '118', '168', '235']\nS18A_APER_RAD = [3.0, 4.5, 6.0, 9.0, 12.0, 17.0, 25.0, 35.0, 50.0, 70.0]\nS18A_APER = {}\nfor ii, rr in zip(S18A_APER_ID, S18A_APER_RAD):\n    S18A_APER['aper{0}'.format(ii)] = AperPhot(ii, rr)\n\nclass SkyObjs():\n    \"\"\"\n    Class for HSC sky objects.\n    \"\"\"\n    # Convert the flux from erg/s/cm^2/Hz to HSC image value\n    CGS_TO_IMG = 1.7378E30\n    # Convert the flux from erg/s/cm^2/Hz to muJy\n    CGS_TO_MUJY = 1.0E29\n    # Convert the from from muJy to HSC image unit\n    MUJY_TO_IMG = CGS_TO_IMG / CGS_TO_MUJY\n\n    # List of filters\n    FILTER_LIST = ['HSC-G', 'HSC-R', 'HSC-I', 'HSC-Z', 'HSC-Y']\n\n    # Nicknames of filters\n    FILTER_SHORT = ['g', 'r', 'i', 'z', 'y']\n\n    def __init__(self, skyobjs, meas=False, nobj_min=5):\n        \"\"\"\n        Initialize an object for HSC sky object catalog.\n        \"\"\"\n        # Whether it is a forced photometry or a measurement catalog\n        if meas:\n            self.ra_col = 'i_ra'\n            self.dec_col = 'i_dec'\n            self.type = 'meas'\n            self.meas = True\n        else:\n            self.ra_col = 'ra'\n            self.dec_col = 'dec'\n            self.type = 'force'\n            self.meas = False\n\n        # If skyobjs is a file name, read in the catalog\n        if isinstance(skyobjs, str):\n            _, file_ext = os.path.splitext(skyobjs)\n            if file_ext == '.npy':\n                self.skyobjs = np.load(skyobjs)\n            elif file_ext == '.fits':\n                self.skyobjs = Table.read(skyobjs).as_array().data\n            else:\n                raise TypeError(\"# Wrong file type: npy or fits!\")\n        elif isinstance(skyobjs, Table):\n            try:\n                self.skyobjs = skyobjs.as_array()\n            except Exception:\n                self.skyobjs = skyobjs.as_array()\n        elif isinstance(skyobjs, np.ndarray) or isinstance(skyobjs, np.recarray):\n            self.skyobjs = skyobjs\n\n        # Minimum number of sky objects\n        self.n_min = nobj_min\n\n        # List of Tracts\n        self.tract_list = list(np.unique(self.skyobjs['tract']))\n        self.n_tract = len(self.tract_list)\n\n        # List of Patches and Tracts\n        self.tract_patch = np.unique(\n            [\"{0}_{1:03d}\".format(t, p) for t, p in\n             zip(self.skyobjs['tract'], self.skyobjs['patch'])])\n        self.n_tract_patch = len(self.tract_patch)\n\n    def select_tract(self, tract, patch=None, n_min=10, verbose=True) -> 'SkyObjs':\n        \"\"\"Select sky objects on one Tract (and Patch) from the catalog \"\"\"\n        tract_mask = self.skyobjs['tract'] == tract\n        if tract_mask.sum() == 0:\n            if verbose:\n                warnings.warn(\"# Tract {0} is not available!\".format(tract))\n            return SkyObjs(self.skyobjs[self.skyobjs['tract'] < 0])\n\n        if patch is not None:\n            tract_mask = tract_mask & (self.skyobjs['patch'] == patch)\n            if tract_mask.sum() == 0:\n                if verbose:\n                    warnings.warn(\n                        \"# Tract {0}-Patch {1} is not available!\".format(tract, patch))\n                return SkyObjs(self.skyobjs[self.skyobjs['tract'] < 0])\n\n        # Number of sky objects available\n        n_skyobj = tract_mask.sum()\n        if n_skyobj <= n_min:\n            if patch is None:\n                if verbose:\n                    warnings.warn(\"# Tract {0} has less than {1} skyobjs: {2}\".format(\n                        tract, n_min, n_skyobj))\n            else:\n                if verbose:\n                    warnings.warn(\"# Tract {0}-Patch {1} has < {2} skyobjs: {3}\".format(\n                        tract, patch, n_min, n_skyobj))\n            return SkyObjs(self.skyobjs[self.skyobjs['tract'] < 0])\n\n        return SkyObjs(self.skyobjs[tract_mask])\n\n    def select_box(self, ra1, ra2, dec1, dec2, n_min=5, verbose=True) -> 'SkyObjs':\n        \"\"\"Select sky objects in a box region.\"\"\"\n        # Order of the coordinates\n        if ra1 >= ra2:\n            ra1, ra2 = ra2, ra1\n        if dec1 >= dec2:\n            dec1, dec2 = dec2, dec1\n\n        # Select sky objects in that region\n        box_mask = ((self.skyobjs[self.ra_col] >= ra1) &\n                    (self.skyobjs[self.ra_col] <= ra2) &\n                    (self.skyobjs[self.dec_col] >= dec1) &\n                    (self.skyobjs[self.dec_col] <= dec2))\n\n        if box_mask.sum() == 0:\n            if verbose:\n                warnings.warn(\n                    \"# No sky object in this region: {0}:{1}-{2}:{3}\".format(\n                        ra1, ra2, dec1, dec2))\n            return SkyObjs(self.skyobjs[self.skyobjs['tract'] < 0])\n\n        if box_mask.sum() <= n_min:\n            if verbose:\n                warnings.warn(\"# Only find {0} sky object(s)\".format(box_mask.sum()))\n\n        return SkyObjs(self.skyobjs[box_mask])\n\n    def select_circle(self, ra, dec, radius, n_min=5, verbose=True):\n        \"\"\"Select sky objects within a circle. Radius is in astropy.units.\"\"\"\n        from astropy.coordinates import SkyCoord\n        import astropy.units as u\n        if str(radius).replace('.', '', 1).isdigit():\n            radius = radius * u.arcsec\n\n        c = SkyCoord(ra, dec, frame='icrs', unit='deg')\n        catalog = SkyCoord(self.skyobjs[self.ra_col], \n                           self.skyobjs[self.dec_col], unit='deg', frame='icrs')\n        circle_mask = (catalog.separation(c) < radius)\n        \n        if circle_mask.sum() == 0:\n            if verbose:\n                warnings.warn(\n                    \"# No sky object in this region: RA = {0}, DEC = {1}, r = {2} arcsec\".format(\n                        ra, dec, radius))\n            return SkyObjs(self.skyobjs[self.skyobjs['tract'] < 0])\n\n        if circle_mask.sum() <= n_min:\n            if verbose:\n                warnings.warn(\"# Only find {0} sky object(s)\".format(circle_mask.sum()))\n\n        return SkyObjs(self.skyobjs[circle_mask])\n\n    def flux_stats(self, aper, band, rerun='s18a', sigma=3.5,\n                   kde=False, bw=None, to_mujy=True, prefix=None):\n        \"\"\"Basic statistics of the flux.\"\"\"\n        u_factor = self.CGS_TO_MUJY if to_mujy else 1.0\n        assert band in self.FILTER_SHORT, \"# Wrong filter name: {}\".format(band)\n\n        flux_col = aper.flux(rerun=rerun, band=band)\n\n        try:\n            flux = self.skyobjs[flux_col] * u_factor\n        except ValueError:\n            raise Exception(\"# Wrong flux column name: {0}\".format(flux_col))\n\n        return utils.stats_summary(flux, sigma=sigma, n_min=self.n_min,\n                                   kde=kde, bw=bw, prefix=prefix)\n\n    def snr_stats(self, aper, band, rerun='s18a', sigma=3.5,\n                  kde=False, bw=None, prefix=None):\n        \"\"\"Basic statistics of the S/N.\"\"\"\n        assert band in self.FILTER_SHORT, \"# Wrong filter name: {}\".format(band)\n\n        flux_col = aper.flux(rerun=rerun, band=band)\n        err_col = aper.err(rerun=rerun, band=band)\n\n        try:\n            snr = self.skyobjs[flux_col] / self.skyobjs[err_col]\n        except ValueError:\n            raise Exception(\"# Wrong column names: {0}/{1}\".format(flux_col, err_col))\n\n        return utils.stats_summary(snr, sigma=sigma, n_min=self.n_min,\n                                   kde=kde, bw=bw, prefix=prefix)\n\n    def mu_stats(self, aper, band, to_mujy=True, rerun='s18a', sigma=3.5,\n                 kde=False, bw=None, prefix=None):\n        \"\"\"Basic statistics of the aperture flux density.\"\"\"\n        u_factor = self.CGS_TO_MUJY if to_mujy else 1.0\n        assert band in self.FILTER_SHORT, \"# Wrong filter name: {}\".format(band)\n\n        flux_col = aper.flux(rerun=rerun, band=band)\n\n        try:\n            mu = self.skyobjs[flux_col] * u_factor / aper.area_arcsec\n        except ValueError:\n            raise Exception(\"# Wrong flux column name: {0}\".format(flux_col))\n\n        return utils.stats_summary(mu, sigma=sigma, n_min=self.n_min,\n                                   kde=kde, bw=bw, prefix=prefix)\n\n    def sum_all_filters(self, aper, **kwargs):\n        \"\"\"Provide a summary of sky objects in all five bands.\"\"\"\n        aper_sum = {}\n        for band in self.FILTER_SHORT:\n            # Sky flux\n            flux_pre = \"{0}_{1}_flux\".format(aper.name, band)\n            flux_stats = self.flux_stats(aper, band, prefix=flux_pre, **kwargs)\n            # S/N of sky flux\n            snr_pre = \"{0}_{1}_snr\".format(aper.name, band)\n            snr_stats = self.flux_stats(aper, band, prefix=snr_pre, **kwargs)\n            # Surface flux density\n            mu_pre = \"{0}_{1}_mu\".format(aper.name, band)\n            mu_stats = self.flux_stats(aper, band, prefix=mu_pre, **kwargs)\n            aper_sum = {**aper_sum, **flux_stats, **snr_stats, **mu_stats}\n\n        return aper_sum\n\n    def sum_aper_list(self, aper_list, **kwargs):\n        \"\"\"Summary of sky objects in all five bands for a list of apertures.\"\"\"\n        if isinstance(aper_list, list):\n            return {key: value for stats in [\n                self.sum_all_filters(aper, **kwargs) for aper in aper_list]\n                    for key, value in stats.items()}\n        else:\n            raise TypeError(\"# Need a list of AperPhot objects!\")\n\n    def sum_all_tracts(self, aper_list, patch=False, verbose=True, **kwargs):\n        \"\"\"Provide summary for all the Tracts-(Patches) in the catalog.\"\"\"\n        result = []\n        if not patch:\n            for t in self.tract_list:\n                if isinstance(aper_list, list):\n                    t_sum = self.select_tract(t, verbose=verbose).sum_aper_list(\n                        aper_list, **kwargs)\n                    t_sum['tract'] = t\n                    result.append(t_sum)\n                elif isinstance(aper_list, AperPhot):\n                    t_sum = self.select_tract(t, verbose=verbose).sum_all_filters(\n                        aper_list, **kwargs)\n                    t_sum['tract'] = t\n                    result.append(t_sum)\n        else:\n            for t, p in [(int(tp.split('_')[0]), int(tp.split('_')[1]))\n                         for tp in self.tract_patch]:\n                if isinstance(aper_list, list):\n                    t_sum = self.select_tract(t, patch=p, verbose=verbose).sum_aper_list(\n                        aper_list, **kwargs)\n                    t_sum['tract'] = t\n                    t_sum['patch'] = p\n                    result.append(t_sum)\n                elif isinstance(aper_list, AperPhot):\n                    t_sum = self.select_tract(t, patch=p, verbose=verbose).sum_all_filters(\n                        aper_list, **kwargs)\n                    t_sum['tract'] = t\n                    t_sum['tract'] = p\n                    result.append(t_sum)\n\n        return result\n\n    def get_summary(self, aper, band, prop, tract=None, patch=None,\n                    rerun='s18a', kde=False, bw=0.2, sigma=3.0, to_mujy=True,\n                    plot=False):\n        \"\"\"Show histogram of the properties of sky objects.\"\"\"\n        assert band in self.FILTER_SHORT, \"# Wrong filter name: {}\".format(band)\n        u_factor = self.CGS_TO_MUJY if to_mujy else 1.0\n\n        if tract is None:\n            sky = self.skyobjs\n        else:\n            sky = self.select_tract(tract, patch=patch).skyobjs\n\n        # Column names\n        flux_col = aper.flux(rerun=rerun, band=band)\n        err_col = aper.err(rerun=rerun, band=band)\n\n        try:\n            if prop == 'flux':\n                values = sky[flux_col] * u_factor\n            elif prop == 'snr':\n                values = sky[flux_col] / sky[err_col]\n            elif prop == 'mu':\n                values = (sky[flux_col] * u_factor) / aper.area_arcsec\n            else:\n                raise Exception(\"# Wrong type of properties: flux/snr/mu\")\n        except ValueError:\n            raise Exception(\"# Wrong flux column name: {0}\".format(flux_col))\n\n        clipped, summary = utils.stats_summary(\n            values, sigma=sigma, n_min=self.n_min, kde=kde, bw=bw,\n            return_clipped=True)\n\n        if plot:\n            if tract is None:\n                region = None\n            if tract is not None and patch is None:\n                region = r'$\\mathrm{Tract\\ }%5d$' % tract\n            elif tract is not None and patch is not None:\n                region = r'${0}:{1}$'.format(tract, patch)\n\n            aper_str = r\"$\\rm {0}$\".format(aper.name[0].upper() + aper.name[1:])\n\n            hist = plotting.plot_skyobj_hist(\n                clipped, summary, band, prop, region=region, aper=aper_str, fontsize=20)\n\n            return clipped, summary, hist\n\n        return clipped, summary\n\n    def plot_map(self, aper, band, prop, tract=None, patch=None, boxsize=0.19,\n                 rerun='s18a', sigma=3.0, to_mujy=True, region=None, y_size=4,\n                 margin=0.2, fontsize=30):\n        \"\"\"Show histogram of the properties of sky objects.\"\"\"\n        assert band in self.FILTER_SHORT, \"# Wrong filter name: {}\".format(band)\n        u_factor = self.CGS_TO_MUJY if to_mujy else 1.0\n\n        if tract is None:\n            sky = self.skyobjs\n        else:\n            sky = self.select_tract(tract, patch=patch).skyobjs\n\n        # Column names\n        flux_col = aper.flux(rerun=rerun, band=band)\n        err_col = aper.err(rerun=rerun, band=band)\n\n        try:\n            if prop == 'flux':\n                values = sky[flux_col] * u_factor\n            elif prop == 'snr':\n                values = sky[flux_col] / sky[err_col]\n            elif prop == 'mu':\n                values = (sky[flux_col] * u_factor) / aper.area_arcsec\n            else:\n                raise Exception(\"# Wrong type of properties: flux/snr/mu\")\n        except ValueError:\n            raise Exception(\"# Wrong flux column name: {0}\".format(flux_col))\n\n        flag = np.isfinite(values)\n        values = values[flag]\n\n        # RA, Dec\n        ra, dec = sky['ra'][flag], sky['dec'][flag]\n\n        # Number of bins\n        x_bins = np.floor((np.max(ra) - np.min(ra)) / boxsize)\n        y_bins = np.floor((np.max(dec) - np.min(dec)) / boxsize)\n\n        _, low, upp = sigmaclip(values, low=sigma, high=sigma)\n        mask = (values >= low) & (values <= upp)\n\n        n_sky, x_edges, y_edges, _ = binned_statistic_2d(\n            ra[mask], dec[mask], values[mask], 'count', bins=[x_bins, y_bins])\n\n        mean_sky, _, _, _ = binned_statistic_2d(\n            ra[mask], dec[mask], values[mask], 'mean', bins=[x_bins, y_bins])\n\n        _, low_mean, upp_mean = sigmaclip(\n            mean_sky[np.isfinite(mean_sky)].flatten(), low=sigma, high=sigma)\n\n        v_edge = np.min(np.abs([low_mean, upp_mean]))\n\n        if region is not None:\n            region_str = r'$\\rm {0}$'.format(region)\n        else:\n            region_str = ''\n\n        band_str = r'$\\ \\ \\ \\rm {0}-band$'.format(band)\n        aper_str = r\"$\\ \\ \\ \\rm {0}$\".format(aper.name[0].upper() + aper.name[1:])\n\n        skyobj_map = plotting.map_skyobjs(\n            x_edges, y_edges, n_sky, mean_sky,\n            label=region_str + band_str + aper_str, n_min=10,\n            vmin=-v_edge, vmax=v_edge, y_size=y_size, margin=margin, fontsize=fontsize)\n\n        return x_edges, y_edges, n_sky, mean_sky, skyobj_map\n", "meta": {"hexsha": "1ed9d0b337cf384637ac3aecefa729f7ab228e44", "size": 16941, "ext": "py", "lang": "Python", "max_stars_repo_path": "unagi/sky.py", "max_stars_repo_name": "Christopher-Bradshaw/unagi", "max_stars_repo_head_hexsha": "29bb2df0c8674438f24c3932e0b1b65a83dec4ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2019-06-04T02:21:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T01:59:18.000Z", "max_issues_repo_path": "unagi/sky.py", "max_issues_repo_name": "minaskar/unagi", "max_issues_repo_head_hexsha": "821858aa3912bd5bc7bc347a54e3b70afceeb101", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2018-08-19T07:09:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-08T08:45:28.000Z", "max_forks_repo_path": "unagi/sky.py", "max_forks_repo_name": "minaskar/unagi", "max_forks_repo_head_hexsha": "821858aa3912bd5bc7bc347a54e3b70afceeb101", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-08-04T22:30:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-08T09:10:10.000Z", "avg_line_length": 38.9448275862, "max_line_length": 97, "alphanum_fraction": 0.5504397615, "include": true, "reason": "import numpy,from scipy,import astropy,from astropy", "num_tokens": 4439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.29746994883293104, "lm_q1q2_score": 0.17517682389032954}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport logging\nfrom pathlib import Path\nimport numpy as np\nfrom astropy import units as u\nfrom astropy.io import fits\nfrom astropy.table import Table\nfrom gammapy.data import GTI\nfrom gammapy.irf import EDispKernel, EDispKernelMap\nfrom gammapy.maps import RegionNDMap\nfrom gammapy.stats import WStatCountsStatistic, cash, get_wstat_mu_bkg, wstat\nfrom gammapy.utils.random import get_random_state\nfrom gammapy.utils.scripts import make_name, make_path\nfrom .map import MapDataset\nfrom .utils import get_axes, get_figure\n\n__all__ = [\"SpectrumDatasetOnOff\", \"SpectrumDataset\"]\n\nlog = logging.getLogger(__name__)\n\n\nclass SpectrumDataset(MapDataset):\n    \"\"\"Spectrum dataset for likelihood fitting.\n\n    The spectrum dataset bundles reduced counts data, with a spectral model,\n    background model and instrument response function to compute the fit-statistic\n    given the current model and data.\n\n    Parameters\n    ----------\n    models : `~gammapy.modeling.models.Models`\n        Fit model\n    counts : `~gammapy.maps.RegionNDMap`\n        Counts spectrum\n    exposure : `~gammapy.maps.RegionNDMap`\n        Effective area\n    edisp : `~gammapy.irf.EDispKernelMap`\n        Energy dispersion kernel.\n    mask_safe : `~gammapy.maps.RegionNDMap`\n        Mask defining the safe data range.\n    mask_fit : `~gammapy.maps.RegionNDMap`\n        Mask to apply to the likelihood for fitting.\n    name : str\n        Dataset name.\n    gti : `~gammapy.data.GTI`\n        GTI of the observation or union of GTI if it is a stacked observation\n    meta_table : `~astropy.table.Table`\n        Table listing informations on observations used to create the dataset.\n        One line per observation for stacked datasets.\n\n    See Also\n    --------\n    SpectrumDatasetOnOff, FluxPointsDataset, MapDataset\n    \"\"\"\n\n    stat_type = \"cash\"\n    tag = \"SpectrumDataset\"\n\n    def __init__(\n        self,\n        models=None,\n        counts=None,\n        exposure=None,\n        background=None,\n        edisp=None,\n        mask_safe=None,\n        mask_fit=None,\n        name=None,\n        gti=None,\n        meta_table=None,\n    ):\n\n        self._name = make_name(name)\n        self._evaluators = {}\n\n        if mask_fit is not None and mask_fit.dtype != np.dtype(\"bool\"):\n            raise ValueError(\"mask data must have dtype bool\")\n\n        self.counts = counts\n        self.mask_fit = mask_fit\n        self.exposure = exposure\n        self.edisp = edisp\n        self.background = background\n        self.mask_safe = mask_safe\n        self.gti = gti\n        self.meta_table = meta_table\n        self.models = models\n\n    @property\n    def psf(self):\n        return None\n\n    @property\n    def mask_safe(self):\n        if self._mask_safe is None:\n            data = np.ones(self._geom.data_shape, dtype=bool)\n            self._mask_safe = RegionNDMap.from_geom(self._geom, data=data)\n\n        return self._mask_safe\n\n    @mask_safe.setter\n    def mask_safe(self, mask):\n        if mask is None or isinstance(mask, RegionNDMap):\n            self._mask_safe = mask\n        else:\n            raise ValueError(f\"Must be `RegionNDMap` and not {type(mask)}\")\n\n    def stat_array(self):\n        \"\"\"Likelihood per bin given the current model parameters\"\"\"\n        return cash(n_on=self.counts.data, mu_on=self.npred().data)\n\n    def stat_sum(self):\n        \"\"\"Total statistic given the current model parameters.\"\"\"\n        stat = self.stat_array()\n\n        if self.mask is not None:\n            stat = stat[self.mask.data]\n\n        return np.sum(stat, dtype=np.float64)\n\n    def write(self):\n        raise NotImplementedError\n\n    def read(self):\n        raise NotImplementedError\n\n    def to_hdulist(self):\n        raise NotImplementedError\n\n    def from_hdulist(self):\n        raise NotImplementedError\n\n    def from_dict(self):\n        raise NotImplementedError\n\n    # TODO: decide what to about these \"useless\" methods\n    def to_spectrum_dataset(self, *args, **kwargs):\n        \"\"\"Returns self\"\"\"\n        return self\n\n    def cutout(self, *args, **kwargs):\n        \"\"\"Returns self\"\"\"\n        return self\n\n    def pad(self, *args, **kwargs):\n        \"\"\"Returns self\"\"\"\n        return self\n\n    @property\n    # TODO: make this a method to support different methods?\n    def energy_range(self):\n        \"\"\"Energy range defined by the safe mask\"\"\"\n        energy = self._geom.axes[\"energy\"].edges\n        energy_min, energy_max = energy[:-1], energy[1:]\n\n        if self.mask_safe is not None:\n            if self.mask_safe.data.any():\n                energy_min = energy_min[self.mask_safe.data[:, 0, 0]]\n                energy_max = energy_max[self.mask_safe.data[:, 0, 0]]\n            else:\n                return None, None\n\n        return u.Quantity([energy_min.min(), energy_max.max()])\n\n    def plot_fit(\n        self,\n        ax_spectrum=None,\n        ax_residuals=None,\n        kwargs_spectrum=None,\n        kwargs_residuals=None,\n    ):\n        \"\"\"Plot spectrum and residuals in two panels.\n\n        Calls `~SpectrumDataset.plot_excess` and `~SpectrumDataset.plot_residuals`.\n\n        Parameters\n        ----------\n        ax_spectrum : `~matplotlib.axes.Axes`\n            Axes to plot spectrum on.\n        ax_residuals : `~matplotlib.axes.Axes`\n            Axes to plot residuals on.\n        kwargs_spectrum : dict\n            Keyword arguments passed to `~SpectrumDataset.plot_excess`.\n        kwargs_residuals : dict\n            Keyword arguments passed to `~SpectrumDataset.plot_residuals`.\n\n        Returns\n        -------\n        ax_spectrum, ax_residuals : `~matplotlib.axes.Axes`\n            Spectrum and residuals plots.\n        \"\"\"\n        from matplotlib.gridspec import GridSpec\n\n        gs = GridSpec(7, 1)\n        ax_spectrum, ax_residuals = get_axes(\n            ax_spectrum,\n            ax_residuals,\n            8,\n            7,\n            [gs[:5, :]],\n            [gs[5:, :]],\n            kwargs2={\"sharex\": ax_spectrum},\n        )\n        kwargs_spectrum = kwargs_spectrum or {}\n        kwargs_residuals = kwargs_residuals or {}\n\n        self.plot_excess(ax_spectrum, **kwargs_spectrum)\n        ax_spectrum.label_outer()\n\n        self.plot_residuals(ax_residuals, **kwargs_residuals)\n        method = kwargs_residuals.get(\"method\", \"diff\")\n        label = self._residuals_labels[method]\n        ax_residuals.set_ylabel(f\"Residuals\\n{label}\")\n\n        return ax_spectrum, ax_residuals\n\n    @property\n    def _energy_unit(self):\n        return self._geom.axes[0].unit\n\n    def _plot_energy_range(self, ax):\n        energy_min, energy_max = self.energy_range\n        kwargs = {\"color\": \"black\", \"linestyle\": \"dashed\"}\n        ax.axvline(energy_min.to_value(self._energy_unit), label=\"fit range\", **kwargs)\n        ax.axvline(energy_max.to_value(self._energy_unit), **kwargs)\n\n    def plot_counts(\n        self, ax=None, kwargs_counts=None, kwargs_background=None, **kwargs\n    ):\n        \"\"\"Plot counts and background.\n\n        Parameters\n        ----------\n        ax : `~matplotlib.axes.Axes`\n            Axes to plot on.\n        kwargs_counts: dict\n            Keyword arguments passed to `~matplotlib.axes.Axes.hist` for the counts.\n        kwargs_background: dict\n            Keyword arguments passed to `~matplotlib.axes.Axes.hist` for the background.\n        **kwargs: dict\n            Keyword arguments passed to both `~matplotlib.axes.Axes.hist`.\n\n        Returns\n        -------\n        ax : `~matplotlib.axes.Axes`\n            Axes object.\n        \"\"\"\n        kwargs_counts = kwargs_counts or {}\n        kwargs_background = kwargs_background or {}\n\n        plot_kwargs = kwargs.copy()\n        plot_kwargs.update(kwargs_counts)\n        plot_kwargs.setdefault(\"label\", \"Counts\")\n        ax = self.counts.plot_hist(ax, **plot_kwargs)\n\n        plot_kwargs = kwargs.copy()\n        plot_kwargs.update(kwargs_background)\n\n        plot_kwargs.setdefault(\"label\", \"Background\")\n        self.background.plot_hist(ax, **plot_kwargs)\n\n        self._plot_energy_range(ax)\n        energy_min, energy_max = self.energy_range\n        ax.set_xlim(0.7 * energy_min.value, 1.3 * energy_max.value)\n\n        ax.legend(numpoints=1)\n        return ax\n\n    def plot_excess(\n        self, ax=None, kwargs_excess=None, kwargs_npred_signal=None, **kwargs\n    ):\n        \"\"\"Plot excess and predicted signal.\n\n        Parameters\n        ----------\n        ax : `~matplotlib.axes.Axes`\n            Axes to plot on.\n        kwargs_excess: dict\n            Keyword arguments passed to `~matplotlib.axes.Axes.errorbar` for\n            the excess.\n        kwargs_npred_signal : dict\n            Keyword arguments passed to `~matplotlib.axes.Axes.hist` for the\n            predicted signal.\n        **kwargs: dict\n            Keyword arguments passed to both plot methods.\n\n        Returns\n        -------\n        ax : `~matplotlib.axes.Axes`\n            Axes object.\n        \"\"\"\n        kwargs_excess = kwargs_excess or {}\n        kwargs_npred_signal = kwargs_npred_signal or {}\n\n        plot_kwargs = kwargs.copy()\n        plot_kwargs.update(kwargs_excess)\n        plot_kwargs.setdefault(\"label\", \"Excess counts\")\n        ax = self.excess.plot(\n            ax, yerr=np.sqrt(np.abs(self.excess.data.flatten())), **plot_kwargs\n        )\n\n        plot_kwargs = kwargs.copy()\n        plot_kwargs.update(kwargs_npred_signal)\n        plot_kwargs.setdefault(\"label\", \"Predicted signal counts\")\n        self.npred_signal().plot_hist(ax, **plot_kwargs)\n\n        self._plot_energy_range(ax)\n        ax.legend(numpoints=1)\n        return ax\n\n    def residuals(self, method=\"diff\"):\n        \"\"\"Compute the spectral residuals.\n\n        Parameters\n        ----------\n        method : {\"diff\", \"diff/model\", \"diff/sqrt(model)\"}\n            Method used to compute the residuals. Available options are:\n                - ``diff`` (default): data - model\n                - ``diff/model``: (data - model) / model\n                - ``diff/sqrt(model)``: (data - model) / sqrt(model)\n\n        Returns\n        -------\n        residuals : `RegionNDMap`\n            Residual spectrum\n        \"\"\"\n        residuals = self._compute_residuals(self.counts, self.npred(), method)\n        return residuals\n\n    def plot_residuals(self, ax=None, method=\"diff\", **kwargs):\n        \"\"\"Plot spectrum residuals.\n\n        Parameters\n        ----------\n        ax : `~matplotlib.axes.Axes`\n            Axes to plot on.\n        method : {\"diff\", \"diff/model\", \"diff/sqrt(model)\"}\n            Normalization used to compute the residuals, see `SpectrumDataset.residuals`.\n        **kwargs : dict\n            Keyword arguments passed to `~matplotlib.axes.Axes.errorbar`.\n\n        Returns\n        -------\n        ax : `~matplotlib.axes.Axes`\n            Axes object.\n        \"\"\"\n        # TODO: remove code duplication with `MapDataset.plot_residuals_spectral()`\n        residuals = self.residuals(method)\n        if method == \"diff\":\n            yerr = np.sqrt((self.counts.data + self.npred().data).flatten())\n        else:\n            yerr = np.ones_like(residuals.data.flatten())\n\n        kwargs.setdefault(\"color\", kwargs.pop(\"c\", \"black\"))\n        ax = residuals.plot(ax, yerr=yerr, **kwargs)\n        ax.axhline(0, color=kwargs[\"color\"], lw=0.5)\n\n        label = self._residuals_labels[method]\n        ax.set_ylabel(f\"Residuals ({label})\")\n        ax.set_yscale(\"linear\")\n        ymin = 1.05 * np.nanmin(residuals.data - yerr)\n        ymax = 1.05 * np.nanmax(residuals.data + yerr)\n        ax.set_ylim(ymin, ymax)\n        return ax\n\n    @classmethod\n    def create(\n        cls,\n        e_reco,\n        e_true=None,\n        region=None,\n        reference_time=\"2000-01-01\",\n        name=None,\n        meta_table=None,\n    ):\n        \"\"\"Creates empty spectrum dataset.\n\n        Empty containers are created with the correct geometry.\n        counts, background and aeff are zero and edisp is diagonal.\n\n        The safe_mask is set to False in every bin.\n\n        Parameters\n        ----------\n        e_reco : `~gammapy.maps.MapAxis`\n            counts energy axis. Its name must be \"energy\".\n        e_true : `~gammapy.maps.MapAxis`\n            effective area table energy axis. Its name must be \"energy-true\".\n            If not set use reco energy values. Default : None\n        region : `~regions.SkyRegion`\n            Region to define the dataset for.\n        reference_time : `~astropy.time.Time`\n            reference time of the dataset, Default is \"2000-01-01\"\n        meta_table : `~astropy.table.Table`\n            Table listing informations on observations used to create the dataset.\n            One line per observation for stacked datasets.\n        \"\"\"\n        if e_true is None:\n            e_true = e_reco.copy(name=\"energy_true\")\n\n        if region is None:\n            region = \"icrs;circle(0, 0, 1)\"\n\n        name = make_name(name)\n        counts = RegionNDMap.create(region=region, axes=[e_reco])\n        background = RegionNDMap.create(region=region, axes=[e_reco])\n        exposure = RegionNDMap.create(\n            region=region, axes=[e_true], unit=\"cm2 s\", meta={\"livetime\": 0 * u.s}\n        )\n        edisp = EDispKernelMap.from_diagonal_response(e_reco, e_true, geom=counts.geom)\n        mask_safe = RegionNDMap.from_geom(counts.geom, dtype=\"bool\")\n        gti = GTI.create(u.Quantity([], \"s\"), u.Quantity([], \"s\"), reference_time)\n\n        return SpectrumDataset(\n            counts=counts,\n            exposure=exposure,\n            background=background,\n            edisp=edisp,\n            mask_safe=mask_safe,\n            gti=gti,\n            name=name,\n        )\n\n    def peek(self, fig=None):\n        \"\"\"Quick-look summary plots.\n\n        Parameters\n        ----------\n        fig : `~matplotlib.figure.Figure`\n            Figure to add AxesSubplot on.\n\n        Returns\n        -------\n        ax1, ax2, ax3 : `~matplotlib.axes.AxesSubplot`\n            Counts, effective area and energy dispersion subplots.\n        \"\"\"\n        fig = get_figure(fig, 16, 4)\n        ax1, ax2, ax3 = fig.subplots(1, 3)\n\n        ax1.set_title(\"Counts\")\n        self.plot_counts(ax1)\n\n        ax2.set_title(\"Exposure\")\n        self.exposure.plot(ax2)\n        self._plot_energy_range(ax2)\n        energy_min, energy_max = self.energy_range\n        ax2.set_xlim(0.7 * energy_min.value, 1.3 * energy_max.value)\n\n        ax3.set_title(\"Energy Dispersion\")\n        if self.edisp is not None:\n            kernel = self.edisp.get_edisp_kernel()\n            kernel.plot_matrix(ax3, vmin=0, vmax=1)\n\n        # TODO: optimize layout\n        fig.subplots_adjust(wspace=0.3)\n        return ax1, ax2, ax3\n\n\nclass SpectrumDatasetOnOff(SpectrumDataset):\n    \"\"\"Spectrum dataset for on-off likelihood fitting.\n\n    The on-off spectrum dataset bundles reduced counts data, off counts data,\n    with a spectral model, relative background efficiency and instrument\n    response functions to compute the fit-statistic given the current model\n    and data.\n\n    Parameters\n    ----------\n    models : `~gammapy.modeling.models.Models`\n        Fit model\n    counts : `~gammapy.maps.RegionNDMap`\n        ON Counts spectrum\n    counts_off : `~gammapy.maps.RegionNDMap`\n        OFF Counts spectrum\n    exposure : `~gammapy.maps.RegionNDMap`\n        Exposure\n    edisp : `~gammapy.irf.EDispKernelMap`\n        Energy dispersion kernel\n    mask_safe : `~gammapy.maps.RegionNDMap`\n        Mask defining the safe data range.\n    mask_fit : `~gammapy.maps.RegionNDMap`\n        Mask to apply to the likelihood for fitting.\n    acceptance : `~gammapy.maps.RegionNDMap` or float\n        Relative background efficiency in the on region.\n    acceptance_off : `~gammapy.maps.RegionNDMap` or float\n        Relative background efficiency in the off region.\n    name : str\n        Name of the dataset.\n    gti : `~gammapy.data.GTI`\n        GTI of the observation or union of GTI if it is a stacked observation\n    meta_table : `~astropy.table.Table`\n        Table listing informations on observations used to create the dataset.\n        One line per observation for stacked datasets.\n\n    See Also\n    --------\n    SpectrumDataset, FluxPointsDataset, MapDataset\n    \"\"\"\n\n    stat_type = \"wstat\"\n    tag = \"SpectrumDatasetOnOff\"\n\n    def __init__(\n        self,\n        models=None,\n        counts=None,\n        counts_off=None,\n        exposure=None,\n        edisp=None,\n        mask_safe=None,\n        mask_fit=None,\n        acceptance=None,\n        acceptance_off=None,\n        name=None,\n        gti=None,\n        meta_table=None,\n    ):\n\n        self._name = make_name(name)\n        self._evaluators = {}\n\n        self.counts = counts\n        self.counts_off = counts_off\n\n        self.mask_fit = mask_fit\n        self.exposure = exposure\n        self.edisp = edisp\n        self.mask_safe = mask_safe\n        self.meta_table = meta_table\n\n        if np.isscalar(acceptance):\n            data = np.ones(self._geom.data_shape) * acceptance\n            acceptance = RegionNDMap.from_geom(self._geom, data=data)\n\n        self.acceptance = acceptance\n\n        if np.isscalar(acceptance_off):\n            data = np.ones(self._geom.data_shape) * acceptance_off\n            acceptance_off = RegionNDMap.from_geom(self._geom, data=data)\n\n        self.acceptance_off = acceptance_off\n\n        self.gti = gti\n        self.models = models\n\n    def __str__(self):\n        str_ = super().__str__()\n\n        str_list = str_.split(\"\\n\")\n\n        if getattr(self, \"counts_off\", None) is not None:\n            counts_off = np.sum(self.counts_off.data)\n            str_cts = \"\\t{:32}: {:.2f}\".format(\"Total off counts\", counts_off)\n\n        str_list.insert(6, str_cts)\n\n        acceptance = np.nan\n        if self.acceptance is not None:\n            acceptance = np.mean(self.acceptance.data)\n\n        str_acc = \"\\n\\t{:32}: {:.3f}\\n\".format(\"Acceptance mean\", acceptance)\n\n        acceptance_off = np.nan\n        if self.acceptance_off is not None:\n            acceptance_off = np.sum(self.acceptance_off.data)\n        str_acc += \"\\t{:32}: {:.3f}\".format(\"Acceptance off\", acceptance_off)\n\n        str_list.insert(16, str_acc)\n        str_ = \"\\n\".join(str_list)\n\n        return str_.expandtabs(tabsize=2)\n\n    def npred_background(self):\n        \"\"\"Background counts estimated from the marginalized likelihood estimate.\n         See :ref:`wstat`\n         \"\"\"\n        mu_bkg = self.alpha.data * get_wstat_mu_bkg(\n            n_on=self.counts.data,\n            n_off=self.counts_off.data,\n            alpha=self.alpha.data,\n            mu_sig=self.npred_signal().data,\n        )\n        return RegionNDMap.from_geom(geom=self._geom, data=mu_bkg)\n\n    def npred_off(self):\n        \"\"\"Predicted counts in the off region\n\n        Returns\n        -------\n        npred_off : `Map`\n            Predicted off counts\n        \"\"\"\n        return self.npred_background() / self.alpha\n\n    @property\n    def background(self):\n        \"\"\" alpha * noff\"\"\"\n        return self.alpha * self.counts_off\n\n    @property\n    def alpha(self):\n        \"\"\"Exposure ratio between signal and background regions\"\"\"\n        alpha = self.acceptance / self.acceptance_off\n        np.nan_to_num(alpha.data, copy=False)\n        return alpha\n\n    @property\n    def _geom(self):\n        \"\"\"Main analysis geometry\"\"\"\n        if self.counts is not None:\n            return self.counts.geom\n        elif self.counts_off is not None:\n            return self.counts_off.geom\n        elif self.acceptance is not None:\n            return self.acceptance.geom\n        elif self.acceptance_off is not None:\n            return self.acceptance_off.geom\n        else:\n            raise ValueError(\n                \"Either 'counts', 'counts_off', 'acceptance' or 'acceptance_of' must be defined.\"\n            )\n\n    def stat_array(self):\n        \"\"\"Likelihood per bin given the current model parameters\"\"\"\n        mu_sig = self.npred_signal().data\n        on_stat_ = wstat(\n            n_on=self.counts.data,\n            n_off=self.counts_off.data,\n            alpha=self.alpha.data,\n            mu_sig=mu_sig,\n        )\n        return np.nan_to_num(on_stat_)\n\n    def fake(self, npred_background, random_state=\"random-seed\"):\n        \"\"\"Simulate fake counts for the current model and reduced irfs.\n\n        This method overwrites the counts and off counts defined on the dataset object.\n\n        Parameters\n        ----------\n        npred_background : `~gammapy.maps.RegionNDMap`\n            Predicted background to be used in the on region.\n        random_state : {int, 'random-seed', 'global-rng', `~numpy.random.RandomState`}\n            Defines random number generator initialisation.\n            Passed to `~gammapy.utils.random.get_random_state`.\n        \"\"\"\n        random_state = get_random_state(random_state)\n\n        npred = self.npred_signal()\n        npred.data = random_state.poisson(npred.data)\n        npred_bkg = random_state.poisson(npred_background.data)\n        self.counts = npred + npred_bkg\n\n        npred_off = npred_background / self.alpha\n        npred_off.data = random_state.poisson(npred_off.data)\n        self.counts_off = npred_off\n\n    @classmethod\n    def create(\n        cls,\n        e_reco,\n        e_true=None,\n        region=None,\n        reference_time=\"2000-01-01\",\n        name=None,\n        meta_table=None,\n    ):\n        \"\"\"Create empty SpectrumDatasetOnOff.\n\n        Empty containers are created with the correct geometry.\n        counts, counts_off and aeff are zero and edisp is diagonal.\n\n        The safe_mask is set to False in every bin.\n\n        Parameters\n        ----------\n        e_reco : `~gammapy.maps.MapAxis`\n            counts energy axis. Its name must be \"energy\".\n        e_true : `~gammapy.maps.MapAxis`\n            effective area table energy axis. Its name must be \"energy-true\".\n            If not set use reco energy values. Default : None\n        region : `~regions.SkyRegion`\n            Region to define the dataset for.\n        reference_time : `~astropy.time.Time`\n            reference time of the dataset, Default is \"2000-01-01\"\n        meta_table : `~astropy.table.Table`\n            Table listing informations on observations used to create the dataset.\n            One line per observation for stacked datasets.\n        \"\"\"\n        dataset = super().create(\n            e_reco=e_reco,\n            e_true=e_true,\n            region=region,\n            reference_time=reference_time,\n            name=name,\n        )\n\n        counts_off = dataset.counts.copy()\n        acceptance = RegionNDMap.from_geom(counts_off.geom, dtype=int)\n        acceptance.data += 1\n\n        acceptance_off = RegionNDMap.from_geom(counts_off.geom, dtype=int)\n        acceptance_off.data += 1\n\n        return cls.from_spectrum_dataset(\n            dataset=dataset,\n            acceptance=acceptance,\n            acceptance_off=acceptance_off,\n            counts_off=counts_off,\n        )\n\n    @classmethod\n    def read(cls, filename):\n        \"\"\"Read from file\n\n        For now, filename is assumed to the name of a PHA file where BKG file, ARF, and RMF names\n        must be set in the PHA header and be present in the same folder\n\n        Parameters\n        ----------\n        filename : str\n            OGIP PHA file to read\n        \"\"\"\n        raise NotImplementedError(\n            \"To read from an OGIP fits file use SpectrumDatasetOnOff.from_ogip_files.\"\n        )\n\n    def _is_stackable(self):\n        \"\"\"Check if the Dataset contains enough information to be stacked\"\"\"\n        if (\n            self.acceptance_off is None\n            or self.acceptance is None\n            or self.counts_off is None\n        ):\n            return False\n        else:\n            return True\n\n    def stack(self, other):\n        r\"\"\"Stack this dataset with another one.\n\n        Safe mask is applied to compute the stacked counts vector.\n        Counts outside each dataset safe mask are lost.\n\n        Stacking is performed in-place.\n\n        The stacking of 2 datasets is implemented as follows.\n        Here, :math:`k`  denotes a bin in reconstructed energy and :math:`j = {1,2}` is the dataset number\n\n        The ``mask_safe`` of each dataset is defined as:\n\n        .. math::\n\n            \\epsilon_{jk} =\\left\\{\\begin{array}{cl} 1, &\n            \\mbox{if k is inside the energy thresholds}\\\\ 0, &\n            \\mbox{otherwise} \\end{array}\\right.\n\n        Then the total ``counts`` and ``counts_off`` are computed according to:\n\n        .. math::\n\n            \\overline{\\mathrm{n_{on}}}_k =  \\mathrm{n_{on}}_{1k} \\cdot \\epsilon_{1k} +\n            \\mathrm{n_{on}}_{2k} \\cdot \\epsilon_{2k}\n\n            \\overline{\\mathrm{n_{off}}}_k = \\mathrm{n_{off}}_{1k} \\cdot \\epsilon_{1k} +\n            \\mathrm{n_{off}}_{2k} \\cdot \\epsilon_{2k}\n\n        The stacked ``safe_mask`` is then:\n\n        .. math::\n\n            \\overline{\\epsilon_k} = \\epsilon_{1k} OR \\epsilon_{2k}\n\n        In each energy bin :math:`k`, the count excess is computed taking into account the ON ``acceptance``,\n        :math:`a_{on}_k` and the OFF one: ``acceptance_off``, :math:`a_{off}_k`. They define\n        the :math:`\\alpha_k=a_{on}_k/a_{off}_k` factors such that :math:`n_{ex}_k = n_{on}_k - \\alpha_k n_{off}_k`.\n        We define the stacked value of :math:`\\overline{{a}_{on}}_k = 1` so that:\n\n        .. math::\n\n            \\overline{{a}_{off}}_k = \\frac{\\overline{\\mathrm {n_{off}}}}{\\alpha_{1k} \\cdot\n            \\mathrm{n_{off}}_{1k} \\cdot \\epsilon_{1k} + \\alpha_{2k} \\cdot \\mathrm{n_{off}}_{2k} \\cdot \\epsilon_{2k}}\n\n\n        The stacking of :math:`j` elements is implemented as follows.  :math:`k`\n        and :math:`l` denote a bin in reconstructed and true energy, respectively.\n\n        .. math::\n\n            \\epsilon_{jk} =\\left\\{\\begin{array}{cl} 1, & \\mbox{if\n                bin k is inside the energy thresholds}\\\\ 0, & \\mbox{otherwise} \\end{array}\\right.\n\n            \\overline{t} = \\sum_{j} t_i\n\n            \\overline{\\mathrm{aeff}}_l = \\frac{\\sum_{j}\\mathrm{aeff}_{jl}\n                \\cdot t_j}{\\overline{t}}\n\n            \\overline{\\mathrm{edisp}}_{kl} = \\frac{\\sum_{j} \\mathrm{edisp}_{jkl}\n                \\cdot \\mathrm{aeff}_{jl} \\cdot t_j \\cdot \\epsilon_{jk}}{\\sum_{j} \\mathrm{aeff}_{jl}\n                \\cdot t_j}\n\n\n        Parameters\n        ----------\n        other : `~gammapy.datasets.SpectrumDatasetOnOff`\n            the dataset to stack to the current one\n\n        Examples\n        --------\n        >>> from gammapy.datasets import SpectrumDatasetOnOff\n        >>> obs_ids = [23523, 23526, 23559, 23592]\n        >>> datasets = []\n        >>> for obs in obs_ids:\n        >>>     filename = \"$GAMMAPY_DATA/joint-crab/spectra/hess/pha_obs{}.fits\"\n        >>>     ds = SpectrumDatasetOnOff.from_ogip_files(filename.format(obs))\n        >>>     datasets.append(ds)\n        >>> stacked = datasets[0]\n        >>> for ds in datasets[1:]:\n        >>>     stacked.stack(ds)\n        >>> print(stacked)\n        \"\"\"\n        if not isinstance(other, SpectrumDatasetOnOff):\n            raise TypeError(\"Incompatible types for SpectrumDatasetOnOff stacking\")\n\n        # We assume here that counts_off, acceptance and acceptance_off are well defined.\n        if not self._is_stackable() or not other._is_stackable():\n            raise ValueError(\"Cannot stack incomplete SpectrumDatsetOnOff.\")\n\n        geom = self.counts.geom\n        total_off = RegionNDMap.from_geom(geom)\n        total_alpha = RegionNDMap.from_geom(geom)\n\n        total_off.stack(self.counts_off, weights=self.mask_safe)\n        total_off.stack(other.counts_off, weights=other.mask_safe)\n\n        total_alpha.stack(self.alpha * self.counts_off, weights=self.mask_safe)\n        total_alpha.stack(other.alpha * other.counts_off, weights=other.mask_safe)\n\n        with np.errstate(divide=\"ignore\", invalid=\"ignore\"):\n            acceptance_off = total_off / total_alpha\n            average_alpha = total_alpha.data.sum() / total_off.data.sum()\n\n        # For the bins where the stacked OFF counts equal 0, the alpha value is performed by weighting on the total\n        # OFF counts of each run\n        is_zero = total_off.data == 0\n        acceptance_off.data[is_zero] = 1 / average_alpha\n\n        self.acceptance = RegionNDMap.from_geom(geom)\n        self.acceptance.data += 1\n        self.acceptance_off = acceptance_off\n\n        if self.counts_off is not None:\n            self.counts_off *= self.mask_safe\n            self.counts_off.stack(other.counts_off, weights=other.mask_safe)\n\n        super().stack(other)\n\n    def to_ogip_files(self, outdir=None, use_sherpa=False, overwrite=False):\n        \"\"\"Write OGIP files.\n\n        If you want to use the written files with Sherpa you have to set the\n        ``use_sherpa`` flag. Then all files will be written in units 'keV' and\n        'cm2'.\n\n        The naming scheme is fixed, with {name} the dataset name:\n\n        * PHA file is named pha_obs{name}.fits\n        * BKG file is named bkg_obs{name}.fits\n        * ARF file is named arf_obs{name}.fits\n        * RMF file is named rmf_obs{name}.fits\n\n        Parameters\n        ----------\n        outdir : `pathlib.Path`\n            output directory, default: pwd\n        use_sherpa : bool, optional\n            Write Sherpa compliant files, default: False\n        overwrite : bool\n            Overwrite existing files?\n        \"\"\"\n        # TODO: refactor and reduce amount of code duplication\n        outdir = Path.cwd() if outdir is None else make_path(outdir)\n        outdir.mkdir(exist_ok=True, parents=True)\n\n        phafile = f\"pha_obs{self.name}.fits\"\n\n        bkgfile = phafile.replace(\"pha\", \"bkg\")\n        arffile = phafile.replace(\"pha\", \"arf\")\n        rmffile = phafile.replace(\"pha\", \"rmf\")\n\n        counts_table = self.counts.to_table()\n        counts_table[\"QUALITY\"] = np.logical_not(self.mask_safe.data[:, 0, 0])\n        counts_table[\"BACKSCAL\"] = self.acceptance.data[:, 0, 0]\n        counts_table[\"AREASCAL\"] = np.ones(self.acceptance.data.size)\n        meta = self._ogip_meta()\n\n        meta[\"respfile\"] = rmffile\n        meta[\"backfile\"] = bkgfile\n        meta[\"ancrfile\"] = arffile\n        meta[\"hduclas2\"] = \"TOTAL\"\n        counts_table.meta = meta\n\n        name = counts_table.meta[\"name\"]\n        hdu = fits.BinTableHDU(counts_table, name=name)\n\n        energy_axis = self.counts.geom.axes[0]\n\n        hdu_format = \"ogip-sherpa\" if use_sherpa else \"ogip\"\n\n        hdulist = fits.HDUList(\n            [fits.PrimaryHDU(), hdu, energy_axis.to_table_hdu(format=hdu_format)]\n        )\n\n        if self.gti is not None:\n            hdu = fits.BinTableHDU(self.gti.table, name=\"GTI\")\n            hdulist.append(hdu)\n\n        if self.counts.geom._region is not None and self.counts.geom.wcs is not None:\n            region_table = self.counts.geom._to_region_table()\n            region_hdu = fits.BinTableHDU(region_table, name=\"REGION\")\n            hdulist.append(region_hdu)\n\n        hdulist.writeto(str(outdir / phafile), overwrite=overwrite)\n\n        aeff = self.exposure / self.exposure.meta[\"livetime\"]\n\n        aeff.write(\n            outdir / arffile,\n            overwrite=overwrite,\n            format=hdu_format,\n            ogip_column=\"SPECRESP\",\n        )\n\n        if self.counts_off is not None:\n            counts_off_table = self.counts_off.to_table()\n            counts_off_table[\"QUALITY\"] = np.logical_not(self.mask_safe.data[:, 0, 0])\n            counts_off_table[\"BACKSCAL\"] = self.acceptance_off.data[:, 0, 0]\n            counts_off_table[\"AREASCAL\"] = np.ones(self.acceptance.data.size)\n            meta = self._ogip_meta()\n            meta[\"hduclas2\"] = \"BKG\"\n\n            counts_off_table.meta = meta\n            name = counts_off_table.meta[\"name\"]\n            hdu = fits.BinTableHDU(counts_off_table, name=name)\n            hdulist = fits.HDUList(\n                [fits.PrimaryHDU(), hdu, energy_axis.to_table_hdu(format=hdu_format)]\n            )\n            if (\n                self.counts_off.geom._region is not None\n                and self.counts_off.geom.wcs is not None\n            ):\n                region_table = self.counts_off.geom._to_region_table()\n                region_hdu = fits.BinTableHDU(region_table, name=\"REGION\")\n                hdulist.append(region_hdu)\n\n            hdulist.writeto(str(outdir / bkgfile), overwrite=overwrite)\n\n        if self.edisp is not None:\n            kernel = self.edisp.get_edisp_kernel()\n            kernel.write(outdir / rmffile, overwrite=overwrite, use_sherpa=use_sherpa)\n\n    def _ogip_meta(self):\n        \"\"\"Meta info for the OGIP data format\"\"\"\n        try:\n            livetime = self.exposure.meta[\"livetime\"]\n        except KeyError:\n            raise ValueError(\n                \"Storing in ogip format require the livetime \"\n                \"to be defined in the exposure meta data\"\n            )\n        return {\n            \"name\": \"SPECTRUM\",\n            \"hduclass\": \"OGIP\",\n            \"hduclas1\": \"SPECTRUM\",\n            \"corrscal\": \"\",\n            \"chantype\": \"PHA\",\n            \"detchans\": self.counts.geom.axes[0].nbin,\n            \"filter\": \"None\",\n            \"corrfile\": \"\",\n            \"poisserr\": True,\n            \"hduclas3\": \"COUNT\",\n            \"hduclas4\": \"TYPE:1\",\n            \"lo_thres\": self.energy_range[0].to_value(\"TeV\"),\n            \"hi_thres\": self.energy_range[1].to_value(\"TeV\"),\n            \"exposure\": livetime.to_value(\"s\"),\n            \"obs_id\": self.name,\n        }\n\n    @classmethod\n    def from_ogip_files(cls, filename):\n        \"\"\"Read `~gammapy.datasets.SpectrumDatasetOnOff` from OGIP files.\n\n        BKG file, ARF, and RMF must be set in the PHA header and be present in\n        the same folder.\n\n        The naming scheme is fixed to the following scheme:\n\n        * PHA file is named ``pha_obs{name}.fits``\n        * BKG file is named ``bkg_obs{name}.fits``\n        * ARF file is named ``arf_obs{name}.fits``\n        * RMF file is named ``rmf_obs{name}.fits``\n          with ``{name}`` the dataset name.\n\n        Parameters\n        ----------\n        filename : str\n            OGIP PHA file to read\n        \"\"\"\n        filename = make_path(filename)\n        dirname = filename.parent\n\n        with fits.open(str(filename), memmap=False) as hdulist:\n            counts = RegionNDMap.from_hdulist(hdulist, format=\"ogip\")\n            acceptance = RegionNDMap.from_hdulist(\n                hdulist, format=\"ogip\", ogip_column=\"BACKSCAL\"\n            )\n            livetime = counts.meta[\"EXPOSURE\"] * u.s\n\n            if \"GTI\" in hdulist:\n                gti = GTI(Table.read(hdulist[\"GTI\"]))\n            else:\n                gti = None\n\n            mask_safe = RegionNDMap.from_hdulist(\n                hdulist, format=\"ogip\", ogip_column=\"QUALITY\"\n            )\n            mask_safe.data = np.logical_not(mask_safe.data)\n\n        phafile = filename.name\n\n        try:\n            rmffile = phafile.replace(\"pha\", \"rmf\")\n            kernel = EDispKernel.read(dirname / rmffile)\n            edisp = EDispKernelMap.from_edisp_kernel(kernel, geom=counts.geom)\n\n        except OSError:\n            # TODO : Add logger and echo warning\n            edisp = None\n\n        try:\n            bkgfile = phafile.replace(\"pha\", \"bkg\")\n            with fits.open(str(dirname / bkgfile), memmap=False) as hdulist:\n                counts_off = RegionNDMap.from_hdulist(hdulist, format=\"ogip\")\n                acceptance_off = RegionNDMap.from_hdulist(\n                    hdulist, ogip_column=\"BACKSCAL\"\n                )\n        except OSError:\n            # TODO : Add logger and echo warning\n            counts_off, acceptance_off = None, None\n\n        arffile = phafile.replace(\"pha\", \"arf\")\n        aeff = RegionNDMap.read(dirname / arffile, format=\"ogip-arf\")\n        exposure = aeff * livetime\n        exposure.meta[\"livetime\"] = livetime\n\n        if edisp is not None:\n            edisp.exposure_map.data = exposure.data[:, :, np.newaxis, :]\n\n        return cls(\n            counts=counts,\n            exposure=exposure,\n            counts_off=counts_off,\n            edisp=edisp,\n            mask_safe=mask_safe,\n            acceptance=acceptance,\n            acceptance_off=acceptance_off,\n            name=str(counts.meta[\"OBS_ID\"]),\n            gti=gti,\n        )\n\n    def info_dict(self, in_safe_data_range=True):\n        \"\"\"Info dict with summary statistics, summed over energy\n\n        Parameters\n        ----------\n        in_safe_data_range : bool\n            Whether to sum only in the safe energy range\n\n        Returns\n        -------\n        info_dict : dict\n            Dictionary with summary info.\n        \"\"\"\n        info = super().info_dict(in_safe_data_range)\n\n        if self.mask_safe and in_safe_data_range:\n            mask = self.mask_safe.data.astype(bool)\n        else:\n            mask = slice(None)\n\n        counts_off = np.nan\n        if self.counts_off is not None:\n            counts_off = self.counts_off.data[mask].sum()\n\n        info[\"counts_off\"] = counts_off\n\n        acceptance = 1\n        if self.acceptance:\n            # TODO: handle energy dependent a_on / a_off\n            acceptance = self.acceptance.data[mask].sum()\n\n        info[\"acceptance\"] = acceptance\n\n        acceptance_off = np.nan\n        if self.acceptance_off:\n            acceptance_off = acceptance * counts_off / info[\"background\"]\n\n        info[\"acceptance_off\"] = acceptance_off\n\n        alpha = np.nan\n        if self.acceptance_off and self.acceptance:\n            alpha = np.mean(self.alpha.data[mask])\n\n        info[\"alpha\"] = alpha\n\n        info[\"sqrt_ts\"] = WStatCountsStatistic(\n            info[\"counts\"], info[\"counts_off\"], acceptance / acceptance_off,\n        ).sqrt_ts\n        info[\"stat_sum\"] = self.stat_sum()\n        return info\n\n    def to_dict(self, filename, *args, **kwargs):\n        \"\"\"Convert to dict for YAML serialization.\"\"\"\n        outdir = Path(filename).parent\n        filename = str(outdir / f\"pha_obs{self.name}.fits\")\n\n        return {\"name\": self.name, \"type\": self.tag, \"filename\": filename}\n\n    def write(self, filename, overwrite):\n        \"\"\"Write spectrum dataset on off to file.\n\n        Currently only the OGIP format is supported\n\n        Parameters\n        ----------\n        filename : str\n            Filename to write to.\n        overwrite : bool\n            Overwrite existing file.\n        \"\"\"\n        outdir = Path(filename).parent\n        self.to_ogip_files(outdir=outdir, overwrite=overwrite)\n\n    @classmethod\n    def from_dict(cls, data, **kwargs):\n        \"\"\"Create flux point dataset from dict.\n\n        Parameters\n        ----------\n        data : dict\n            Dict containing data to create dataset from.\n\n        Returns\n        -------\n        dataset : `SpectrumDatasetOnOff`\n            Spectrum dataset on off.\n\n        \"\"\"\n\n        filename = make_path(data[\"filename\"])\n        dataset = cls.from_ogip_files(filename=filename)\n        dataset.mask_fit = None\n        return dataset\n\n    @classmethod\n    def from_spectrum_dataset(\n        cls, dataset, acceptance, acceptance_off, counts_off=None\n    ):\n        \"\"\"Create spectrum dataseton off from another dataset.\n\n        Parameters\n        ----------\n        dataset : `SpectrumDataset`\n            Spectrum dataset defining counts, edisp, exposure etc.\n        acceptance : `~numpy.array` or float\n            Relative background efficiency in the on region.\n        acceptance_off : `~numpy.array` or float\n            Relative background efficiency in the off region.\n        counts_off : `~gammapy.maps.RegionNDMap`\n            Off counts spectrum . If the dataset provides a background model,\n            and no off counts are defined. The off counts are deferred from\n            counts_off / alpha.\n\n        Returns\n        -------\n        dataset : `SpectrumDatasetOnOff`\n            Spectrum dataset on off.\n\n        \"\"\"\n        if counts_off is None and dataset.background is not None:\n            alpha = acceptance / acceptance_off\n            counts_off = dataset.npred_background() / alpha\n\n        return cls(\n            models=dataset.models,\n            counts=dataset.counts,\n            exposure=dataset.exposure,\n            counts_off=counts_off,\n            edisp=dataset.edisp,\n            mask_safe=dataset.mask_safe,\n            mask_fit=dataset.mask_fit,\n            acceptance=acceptance,\n            acceptance_off=acceptance_off,\n            gti=dataset.gti,\n            name=dataset.name,\n            meta_table=dataset.meta_table,\n        )\n\n    def to_spectrum_dataset(self, name=None):\n        \"\"\" Convert a SpectrumDatasetOnOff to a SpectrumDataset\n        The background model template is taken as alpha*counts_off\n\n        Parameters\n        ----------\n        name: str\n            Name of the new dataset\n\n        Returns\n        -------\n        dataset: `SpectrumDataset`\n            SpectrumDatset with cash statistics\n        \"\"\"\n\n        name = make_name(name)\n        return SpectrumDataset(\n            counts=self.counts,\n            exposure=self.exposure,\n            edisp=self.edisp,\n            name=name,\n            gti=self.gti,\n            mask_fit=self.mask_fit,\n            mask_safe=self.mask_safe,\n            meta_table=self.meta_table,\n            background=self.background,\n        )\n\n    def slice_by_idx(self, slices, name=None):\n        \"\"\"Slice sub dataset.\n\n        The slicing only applies to the maps that define the corresponding axes.\n\n        Parameters\n        ----------\n        slices : dict\n            Dict of axes names and integers or `slice` object pairs. Contains one\n            element for each non-spatial dimension. For integer indexing the\n            corresponding axes is dropped from the map. Axes not specified in the\n            dict are kept unchanged.\n        name : str\n            Name of the sliced dataset.\n\n        Returns\n        -------\n        map_out : `Map`\n            Sliced map object.\n        \"\"\"\n        name = make_name(name)\n        kwargs = {\"gti\": self.gti, \"name\": name}\n\n        if self.counts is not None:\n            kwargs[\"counts\"] = self.counts.slice_by_idx(slices=slices)\n\n        if self.exposure is not None:\n            kwargs[\"exposure\"] = self.exposure.slice_by_idx(slices=slices)\n\n        if self.edisp is not None:\n            kwargs[\"edisp\"] = self.edisp.slice_by_idx(slices=slices)\n\n        if self.mask_safe is not None:\n            kwargs[\"mask_safe\"] = self.mask_safe.slice_by_idx(slices=slices)\n\n        if self.mask_fit is not None:\n            kwargs[\"mask_fit\"] = self.mask_fit.slice_by_idx(slices=slices)\n\n        kwargs[\"acceptance\"] = self.acceptance.slice_by_idx(slices=slices)\n        kwargs[\"acceptance_off\"] = self.acceptance_off.slice_by_idx(slices=slices)\n        kwargs[\"counts_off\"] = self.counts_off.slice_by_idx(slices=slices)\n        return self.__class__(**kwargs)\n\n    def resample_energy_axis(self, energy_axis, name=None):\n        \"\"\"Resample SpectrumDatasetOnOff over new reconstructed energy axis.\n\n        Counts are summed taking into account safe mask.\n\n        Parameters\n        ----------\n        energy_axis : `~gammapy.maps.MapAxis`\n            New reconstructed energy axis\n        name: str\n            Name of the new dataset.\n\n        Returns\n        -------\n        dataset: `SpectrumDataset`\n            Resampled spectrum dataset .\n        \"\"\"\n        dataset = super().resample_energy_axis(energy_axis=energy_axis, name=name)\n\n        axis = dataset.counts.geom.axes[\"energy\"]\n\n        counts_off = None\n        if self.counts_off is not None:\n            counts_off = self.counts_off\n            counts_off = counts_off.resample_axis(axis=axis, weights=self.mask_safe)\n\n        acceptance = 1\n        acceptance_off = None\n        if self.acceptance is not None:\n            acceptance = self.acceptance\n            acceptance = acceptance.resample_axis(axis=axis, weights=self.mask_safe)\n\n            background = self.alpha * self.counts_off\n            background = background.resample_axis(axis=axis, weights=self.mask_safe)\n\n            acceptance_off = acceptance * counts_off / background\n\n        return self.__class__.from_spectrum_dataset(\n            dataset,\n            acceptance=acceptance,\n            acceptance_off=acceptance_off,\n            counts_off=counts_off,\n        )\n", "meta": {"hexsha": "196502e6f2a71efae3ddb85dc35c1f152f1eaba3", "size": 44162, "ext": "py", "lang": "Python", "max_stars_repo_path": "gammapy/datasets/spectrum.py", "max_stars_repo_name": "facero/gammapy", "max_stars_repo_head_hexsha": "80ddd9b8390fac37e380d9915adc559cad767b8d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gammapy/datasets/spectrum.py", "max_issues_repo_name": "facero/gammapy", "max_issues_repo_head_hexsha": "80ddd9b8390fac37e380d9915adc559cad767b8d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-02-22T23:12:30.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-22T23:12:30.000Z", "max_forks_repo_path": "gammapy/datasets/spectrum.py", "max_forks_repo_name": "facero/gammapy", "max_forks_repo_head_hexsha": "80ddd9b8390fac37e380d9915adc559cad767b8d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3801965231, "max_line_length": 116, "alphanum_fraction": 0.5966215298, "include": true, "reason": "import numpy,from astropy", "num_tokens": 10153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.2974699426047947, "lm_q1q2_score": 0.17517681593009443}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n.. py:currentmodule:: xray.mac.models.casino\n.. moduleauthor:: Hendrix Demers <hendrix.demers@mail.mcgill.ca>\n\nCompute mass absorption coefficient like in CASINO v2.\n\"\"\"\n\n###############################################################################\n# Copyright 2021 Hendrix Demers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n###############################################################################\n\n# Standard library modules.\nimport math\nimport logging\n\n# Third party modules.\nimport numpy as np\n\n# Local modules.\n\n# Project modules.\nfrom xray.mac import get_current_module_path\n\n# Globals and constants variables.\n# Define used to related element name and atomic number.\nHYDROGEN = 1\nBERYLLIUM = 4\nCARBON = 6\nOXYGEN = 8\nALUMINUM = 13\nSILICON = 14\nGOLD = 79\n\n# Define used to related element symbol and mass density.\nMASS_DENSITY_H_g_cm3 = 1.0\nMASS_DENSITY_BE_g_cm3 = 1.848\nMASS_DENSITY_C_g_cm3 = 2.34\nMASS_DENSITY_O_g_cm3 = 1.0\nMASS_DENSITY_AL_g_cm3 = 2.7\nMASS_DENSITY_SI_g_cm3 = 2.34\nMASS_DENSITY_AU_g_cm3 = 19.3\nMASS_DENSITY_H2O_g_cm3 = 1.0\n\n# Define used to related element symbol and mass fraction.\n# Mass fraction of H in parylene C6H6.\nCH_C6H6 = 0.08\n# Mass fraction of C in parylene C6H6.\nCC = 0.92\nCH_H2O = 0.1111\nCO = 0.8889\n\nNOISE_FWHM = 53.0\nDETECTOR_FWHM = 1.61\nHDV = 0.01\n\nnoz = 0\n\n# Inner-shell ionisation energy (critical excitation energy) in keV.\ntransitions = [\n    [0.013598, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],\n    [0.024586, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],\n    [0.054748, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],\n    [0.110996, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],\n    [0.187994, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],\n    [0.283790, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],\n    [0.401586, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],\n    [0.531982, 0.023699, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],\n    [0.685377, 0.030999, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],\n    [0.866871, 0.044998, 0.018299, 0.018299, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],\n    [1.072064, 0.063298, 0.031099, 0.031099, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],\n    [1.304956, 0.089397, 0.051398, 0.051398, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],\n    [1.559547, 0.117696, 0.073098, 0.073098, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],\n    [1.838838, 0.148695, 0.099197, 0.099197, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],\n    [2.145427, 0.189294, 0.132196, 0.132196, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],\n    [2.471916, 0.229192, 0.164794, 0.132196, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],\n    [2.822304, 0.270191, 0.201593, 0.199993, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],\n    [3.202791, 0.319989, 0.247292, 0.245192, 0.025299, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],\n    [3.607278, 0.377087, 0.296290, 0.293590, 0.033899, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],\n    [4.037963, 0.437785, 0.349988, 0.346388, 0.043699, 0.025399, 0.000000, 0.000000, 0.000000, 0.000000],\n    [4.492648, 0.500383, 0.406686, 0.402186, 0.053798, 0.032299, 0.032299, 0.000000, 0.000000, 0.000000],\n    [4.966231, 0.563681, 0.461484, 0.455485, 0.060298, 0.034599, 0.034599, 0.000000, 0.000000, 0.000000],\n    [5.464915, 0.628179, 0.520482, 0.512883, 0.066498, 0.037799, 0.037799, 0.000000, 0.000000, 0.000000],\n    [5.988997, 0.694576, 0.583680, 0.574481, 0.074097, 0.042499, 0.042499, 0.000000, 0.000000, 0.000000],\n    [6.538778, 0.768974, 0.651378, 0.640278, 0.083897, 0.048598, 0.048598, 0.000000, 0.000000, 0.000000],\n    [7.111759, 0.846071, 0.721076, 0.708076, 0.092897, 0.053998, 0.053998, 0.000000, 0.000000, 0.000000],\n    [7.708639, 0.925569, 0.793573, 0.778574, 0.100697, 0.059498, 0.059498, 0.000000, 0.000000, 0.000000],\n    [8.332519, 1.008066, 0.871870, 0.854671, 0.111796, 0.068098, 0.068098, 0.000000, 0.000000, 0.000000],\n    [8.978596, 1.096063, 0.950968, 0.931068, 0.119796, 0.073598, 0.073598, 0.000000, 0.000000, 0.000000],\n    [9.658273, 1.193560, 1.042765, 1.019665, 0.135895, 0.086597, 0.086597, 0.000000, 0.000000, 0.000000],\n    [10.366749, 1.297656, 1.142261, 1.115362, 0.158095, 0.106796, 0.102897, 0.000000, 0.000000, 0.000000],\n    [11.102724, 1.414252, 1.247758, 1.216659, 0.179994, 0.127896, 0.120796, 0.000000, 0.000000, 0.000000],\n    [11.866297, 1.526448, 1.358554, 1.323055, 0.203493, 0.146395, 0.140495, 0.041199, 0.041199, 0.000000],\n    [12.657371, 1.653844, 1.476150, 1.435751, 0.231492, 0.168194, 0.161895, 0.056698, 0.056698, 0.000000],\n    [13.473244, 1.781940, 1.595946, 1.549847, 0.256491, 0.189294, 0.181494, 0.070098, 0.068998, 0.027299],\n    [14.325114, 1.920935, 1.727141, 1.674843, 0.256491, 0.222692, 0.213793, 0.088897, 0.088897, 0.023999],\n    [15.199184, 2.065030, 1.863837, 1.804339, 0.322089, 0.247392, 0.238492, 0.111796, 0.110296, 0.029299],\n    [16.104053, 2.216225, 2.006732, 1.939534, 0.357488, 0.279791, 0.269091, 0.134995, 0.133095, 0.037699],\n    [17.037823, 2.372420, 2.155427, 2.079930, 0.393587, 0.312389, 0.300290, 0.159595, 0.157395, 0.045498],\n    [17.996990, 2.531514, 2.306622, 2.222225, 0.430285, 0.344188, 0.330489, 0.182394, 0.179994, 0.051298],\n    [18.984957, 2.697608, 2.464617, 2.370420, 0.468384, 0.378387, 0.362988, 0.207393, 0.204593, 0.058098],\n    [19.998823, 2.865403, 2.625011, 2.520115, 0.504583, 0.409686, 0.392287, 0.230292, 0.226992, 0.061798],\n    [21.043287, 3.042397, 2.793105, 2.676809, 0.504583, 0.444885, 0.424986, 0.256391, 0.252891, 0.061798],\n    [22.116451, 3.223891, 2.966799, 2.837804, 0.584980, 0.482784, 0.460584, 0.283590, 0.279391, 0.074897],\n    [23.219114, 3.411784, 3.145993, 3.003698, 0.627079, 0.520982, 0.496183, 0.311689, 0.306990, 0.080997],\n    [24.349474, 3.604178, 3.330187, 3.173193, 0.669877, 0.559081, 0.531482, 0.339988, 0.334689, 0.086397],\n    [25.513136, 3.805671, 3.523581, 3.350986, 0.717476, 0.602380, 0.571381, 0.372787, 0.366688, 0.095197],\n    [26.710295, 4.017864, 3.726874, 3.537380, 0.770174, 0.650678, 0.616479, 0.410486, 0.403686, 0.107596],\n    [27.938953, 4.237356, 3.937867, 3.729974, 0.825572, 0.702176, 0.664277, 0.450785, 0.443085, 0.121896],\n    [29.199110, 4.464549, 4.155960, 3.928667, 0.883770, 0.756374, 0.714376, 0.493283, 0.484784, 0.136495],\n    [30.490168, 4.698141, 4.380251, 4.132060, 0.943668, 0.811872, 0.765574, 0.536882, 0.527482, 0.151995],\n    [31.812721, 4.939033, 4.611844, 4.341253, 1.005966, 0.869671, 0.818672, 0.582480, 0.572081, 0.168294],\n    [33.168274, 5.187924, 4.851935, 4.556945, 1.072064, 0.930468, 0.874570, 0.631279, 0.619379, 0.186394],\n    [34.560230, 5.452615, 5.103527, 4.782038, 1.072064, 0.998966, 0.936968, 0.631279, 0.672277, 0.186394],\n    [35.983379, 5.714106, 5.359218, 5.011730, 1.217059, 1.064964, 0.997566, 0.739475, 0.725475, 0.230792],\n    [37.439331, 5.988597, 5.623410, 5.246822, 1.292756, 1.136662, 1.062164, 0.796073, 0.780674, 0.252991],\n    [38.923279, 6.266088, 5.890400, 5.482514, 1.361254, 1.204359, 1.123362, 0.848471, 0.831672, 0.270391],\n    [40.441631, 6.548578, 6.163991, 5.723206, 1.434551, 1.272757, 1.185360, 0.901269, 0.883270, 0.289590],\n    [41.989178, 6.834569, 6.440182, 5.964098, 1.510949, 1.337355, 1.242158, 0.951068, 0.930968, 0.304490],\n    [43.567421, 7.125758, 6.721272, 6.207690, 1.575247, 1.402753, 1.297356, 0.999866, 0.977667, 0.315189],\n    [45.182468, 7.427649, 7.012562, 6.459081, 1.575247, 1.471350, 1.356854, 1.051464, 1.026865, 0.315189],\n    [46.832615, 7.736538, 7.311552, 6.715972, 1.722742, 1.540648, 1.419752, 1.105963, 1.080163, 0.345688],\n    [48.517357, 8.051727, 7.616842, 6.976664, 1.799939, 1.613845, 1.480550, 1.160561, 1.130862, 0.360188],\n    [50.237400, 8.375317, 7.930032, 7.242555, 1.880736, 1.688243, 1.543948, 1.217159, 1.185160, 0.375787],\n    [51.993935, 8.707705, 8.251320, 7.513745, 1.967433, 1.767640, 1.611245, 1.274957, 1.241158, 0.397887],\n    [53.786678, 9.045494, 8.580309, 7.789836, 2.046731, 1.841738, 1.675543, 1.332455, 1.294856, 0.416286],\n    [55.615818, 9.393883, 8.917499, 8.070827, 2.128228, 1.922735, 1.741141, 1.391453, 1.351354, 0.435685],\n    [57.483555, 9.750969, 9.263987, 8.357616, 2.206425, 2.005732, 1.811739, 1.453251, 1.409252, 0.449085],\n    [59.387592, 10.115356, 9.616574, 8.647707, 2.306722, 2.089729, 1.884436, 1.514549, 1.467650, 0.471684],\n    [61.330223, 10.486046, 9.977862, 8.943297, 2.398019, 2.172926, 1.949734, 1.576247, 1.527748, 0.487183],\n    [63.311657, 10.870031, 10.348249, 9.243787, 2.491116, 2.263423, 2.023531, 1.639344, 1.588446, 0.506183],\n    [65.348587, 11.270318, 10.739036, 9.560376, 2.600812, 2.365320, 2.107529, 1.716342, 1.661644, 0.538082],\n    [67.414116, 11.681105, 11.135722, 9.880765, 2.707908, 2.468616, 2.193926, 1.793139, 1.735041, 0.565481],\n    [69.522644, 12.099390, 11.543609, 10.206453, 2.819504, 2.574813, 2.280923, 1.871537, 1.809139, 0.594980],\n    [71.673973, 12.526276, 11.958294, 10.534943, 2.931601, 2.681509, 2.367220, 1.948834, 1.882836, 0.624979],\n    [73.868294, 12.967561, 12.384581, 10.870532, 3.048397, 2.792105, 2.457117, 2.030731, 1.960034, 0.654278],\n    [76.108421, 13.418045, 12.823666, 11.214820, 3.173592, 2.908601, 2.550614, 2.116028, 2.040331, 0.690077],\n    [78.392143, 13.879430, 13.272150, 11.563309, 3.295888, 3.026397, 2.645310, 2.201825, 2.121528, 0.721976],\n    [80.722168, 14.352314, 13.733134, 11.918296, 3.424784, 3.147693, 2.742907, 2.291022, 2.205625, 0.758774],\n    [83.099487, 14.838798, 14.208219, 12.283484, 3.561479, 3.278389, 2.847003, 2.384819, 2.294822, 0.800273],\n    [85.527504, 15.346180, 14.697402, 12.657071, 3.703974, 3.415584, 2.956500, 2.485016, 2.389219, 0.845471],\n    [88.001518, 15.860263, 15.199485, 13.034759, 3.850570, 3.554080, 3.066296, 2.585512, 2.483916, 0.893570],\n    [90.522842, 16.386944, 15.710567, 13.418145, 3.998965, 3.696175, 3.176792, 2.687509, 2.579513, 0.938168],\n    [93.101845, 16.938726, 16.243750, 13.813332, 4.149260, 3.853969, 3.301788, 2.797905, 2.682909, 0.995266],\n    [95.726654, 17.492407, 16.784130, 14.213018, 4.316854, 4.007864, 3.425884, 2.908601, 2.786606, 1.041965],\n    [98.400665, 18.048389, 17.336514, 14.618905, 4.481848, 4.158859, 3.537880, 3.021398, 2.892302, 1.096963],\n    [101.133575, 18.638369, 17.905893, 15.030691, 4.651842, 4.326853, 3.662876, 3.136094, 2.999798, 1.152961],\n    [103.918381, 19.236048, 18.483675, 15.443876, 4.821836, 4.489348, 3.791671, 3.248290, 3.104795, 1.208359],\n    [106.751686, 19.839329, 19.082554, 15.870462, 5.001831, 4.655842, 3.908868, 3.370086, 3.218891, 1.268957],\n    [109.647186, 20.471407, 19.692532, 16.299747, 5.182125, 4.830236, 4.045963, 3.490682, 3.331887, 1.329455],\n    [112.597588, 21.103884, 20.313011, 16.732533, 5.366718, 5.000731, 4.173659, 3.611078, 3.441684, 1.387053],\n    [115.602188, 21.756662, 20.946892, 17.165720, 5.547812, 5.182024, 4.303254, 3.727474, 3.551579, 1.440751],\n    [118.673981, 22.426041, 21.599770, 17.609404, 5.723006, 5.366018, 4.434550, 3.850170, 3.665676, 1.500649],\n    [121.813866, 23.096418, 22.265446, 18.056187, 5.932699, 5.541013, 4.556446, 3.972466, 3.777972, 1.558547],\n    [125.022758, 23.772097, 22.943224, 18.503473, 6.120292, 5.710007, 4.666842, 4.091961, 3.886768, 1.617045],\n    [128.215652, 24.459169, 23.778194, 18.929359, 6.287787, 5.894800, 4.796837, 4.226857, 3.970866, 1.642944],\n    [128.215652, 24.459169, 23.778194, 18.929359, 6.287787, 5.894800, 4.796837, 4.226857, 3.970866, 1.642944],\n    [128.215652, 24.459169, 23.778194, 18.929359, 6.287787, 5.894800, 4.796837, 4.226857, 3.970866, 1.642944],\n    [128.215652, 24.459169, 23.778194, 18.929359, 6.287787, 5.894800, 4.796837, 4.226857, 3.970866, 1.642944]]\n\n# Atomic weight in g/mol.\nA = [0, 1.008, 4.003, 6.941, 9.012, 10.81, 12.01, 14.01, 16.00, 19.00, 20.18,\n     22.99, 24.31, 26.98, 28.09, 30.97, 32.06, 35.45, 39.95, 39.10, 40.08, 44.96, 47.90, 50.94,\n     52.00, 54.94, 55.85, 58.93, 58.71, 63.55, 65.37, 69.72, 72.59, 74.92, 78.96, 79.90, 83.80,\n     85.47, 87.62, 88.91, 91.22, 92.91, 95.94, 98.91, 101.1, 102.9, 106.4, 107.9, 112.4, 114.8,\n     118.7, 121.8, 127.6, 126.9, 131.3, 132.9, 137.3, 138.9, 140.1, 140.9, 144.2, 145, 150.4,\n     152.0, 157.3, 158.9, 160.5, 164.9, 167.3, 168.9, 173.0, 175.5, 180.9, 183.9, 186.2, 190.2,\n     192.2, 195.1, 197.0, 200.6, 204.4, 209.0, 210, 210, 222, 223, 226.0, 227, 232, 231, 238, 237,\n     244, 243, 247, 247, 251, 254, 257, 257, 254, 257]\n\n\ndef square(a):\n    return a * a\n\n\ndef mac_zaluzec_cm2_g(wavelength_A, atomic_number_absorber):  # noqa\n    \"\"\"\n    Compute mass absorption coefficient from Zaluzec model.\n\n    Le domaine de validite a ete etendue pour 0<e<185 (meme parametre que e>=185).\n\n    @todo Find the unit of the returned mass absorption coefficient.\n\n    @param wavelength_A electron wavelength in Angstrom.\n    @param atomic_number_absorber atomic number of the absorber element.\n    @return mass absorption coefficient in ??.\n    @retval -1.0 if the inputs are out of range of the model.\n    \"\"\"\n    l_A = wavelength_A  # noqa\n    absorber = atomic_number_absorber\n\n    energy_eV = 12398.1 / l_A  # noqa\n    c = 0.\n    n = 0.\n    c_abs = 0.0\n\n    # Ne fonct. pas puisque pas de raie de plus faible energie que .183\n    if energy_eV < 185 and absorber != 1:\n        # .. todo:: Bug in CASINO: wavelength passed to macs_total.\n        c_abs = macs_total(energy_eV * 1.0e-3, absorber)\n        # c_abs = macs_total(l, absorber)\n        return c_abs\n\n    if energy_eV > 1487 and absorber != 1:\n        # .. todo:: Bug in CASINO: wavelngth passed to macs_total.\n        c_abs = macs_total(energy_eV * 1.0e-3, absorber)\n        # c_abs = macs_total(l, absorber)\n        return c_abs\n    else:\n        if absorber == HYDROGEN:\n            if energy_eV > 1487:\n                c_abs = special_equations(energy_eV / 1000.0, absorber)\n                return c_abs\n\n            if 679 < energy_eV <= 1487:\n                c = 0.001472\n                n = 3.359\n            if 395 < energy_eV <= 679:\n                c = 0.001816\n                n = 3.285\n            if energy_eV <= 395:\n                c = 0.002138\n                n = 3.231\n\n            if c == 0.0:\n                logging.error(\"Erreur dans la fonction COEFF_ABS H\")\n                raise ValueError\n            else:\n                c_abs = c * math.pow((12398.1 / energy_eV), n)\n\n            if c_abs < 0.0:\n                c_abs = 0.0\n\n            return c_abs\n\n        if absorber == BERYLLIUM:\n            if 679 < energy_eV <= 1487:\n                c = 0.3102\n                n = 3.001\n            if 285 < energy_eV <= 679:\n                c = 0.5060\n                n = 2.831\n            if energy_eV <= 285:\n                c = 2.2480\n                n = 2.419\n\n            if c == 0.0:\n                logging.error(\"\\n\\nerreur dans la fonction COEFF_ABS Be\")\n                raise ValueError\n            else:\n                c_abs = c * math.pow((12398.1 / energy_eV), n)\n\n            return c_abs\n\n        if absorber == CARBON:\n            if 705 < energy_eV <= 1487:\n                c = 1.966\n                n = 2.788\n            if 285 < energy_eV <= 705:\n                c = 4.1290\n                n = 2.529\n            if energy_eV <= 285:\n                c = 0.2572\n                n = 2.404\n\n            if c == 0.0:\n                logging.error(\"\\n\\nerreur dans la fonction COEFF_ABS C\")\n                raise ValueError\n            else:\n                c_abs = c * math.pow((12398.1 / energy_eV), n)\n\n            return c_abs\n\n        if absorber == OXYGEN:\n            if 532 < energy_eV <= 1487:\n                c = 6.9980\n                n = 2.573\n            if energy_eV <= 532:\n                c = .4810\n                n = 2.479\n\n            if c == 0.0:\n                logging.error(\"\\n\\nerreur dans la fonction COEFF_ABS O\")\n                raise ValueError\n            else:\n                c_abs = c * math.pow((12398.1 / energy_eV), n)\n\n            return c_abs\n\n        if absorber == ALUMINUM:\n            if 556 < energy_eV <= 1487:\n                c = 1.2860\n                n = 2.712\n                c_abs = c * math.pow((12398.1 / energy_eV), n)\n\n                return c_abs\n            if energy_eV <= 556:\n                c_abs = -7.059e-4 * math.pow(l_A, 4) - \\\n                        4.815e-2 * math.pow(l_A, 3) + \\\n                        25.79 * square(l_A) - 3.644e2 * l_A + 1801.\n\n                if c_abs < 0.0:\n                    c_abs = 0.0\n\n                return c_abs\n\n            if c_abs == 0.0:\n                logging.error(\"\\n\\nerreur dans la fonction COEFF_ABS Al\")\n                raise ValueError\n\n        if absorber == SILICON:\n            if 637 < energy_eV <= 1487:\n                c = 1.759\n                n = 2.706\n                c_abs = c * math.pow((12398.1 / energy_eV), n)\n\n                return c_abs\n\n            if energy_eV <= 637:\n                c_abs = -0.2407 * math.pow(l_A, 3) + 39.83 * square(l_A) - 527. * l_A + 2278.\n                if c_abs < 0.0:\n                    c_abs = 0.0\n\n                return c_abs\n\n            if c_abs == 0.0:\n                logging.error(\"\\n\\nerreur dans la fonction COEFF_ABS Si\")\n                raise ValueError\n\n        if absorber == GOLD:\n            if 776 < energy_eV <= 1487:\n                c = 41.17\n                n = 1.906\n                c_abs = c * math.pow((12398.1 / energy_eV), n)\n\n                return c_abs\n\n            if energy_eV <= 776:\n                c_abs = -4.411e-4 * math.pow(l_A, 5) + \\\n                        9.878e-2 * math.pow(l_A, 4) - \\\n                        8.218 * math.pow(l_A, 3) + \\\n                        302. * square(l_A) - 4.466e3 * l_A + 29660.\n                if c_abs < 0.0:\n                    c_abs = 0.0\n\n                return c_abs\n\n            if c_abs == 0.0:\n                logging.error(\"\\n\\nerreur dans la fonction COEFF_ABS Au\")\n                raise ValueError\n\n    return -1.0\n\n\ndef special_equations(energy_keV, atomic_number):  # noqa\n    \"\"\"\n    Equations used in mac_zaluzec_cm2_g.\n\n    @param energy_keV\n    @param atomic_number\n    @return macs\n    \"\"\"\n    z = atomic_number\n\n    l_A = 12.3981 / energy_keV  # noqa\n    if z == 1:\n        if 2.0 >= energy_keV >= 1:\n            macs = 3.0353 * math.pow(l_A, 0.01460)\n            return macs\n\n        if 3.5 >= energy_keV >= 1:\n            macs = 3.5 * math.pow(l_A, 0.05890)\n            return macs\n\n        if 4.0 >= energy_keV >= 1:\n            macs = 3.5 * math.pow(l_A, 0.07434)\n            return macs\n\n        if 6.0 >= energy_keV >= 1:\n            macs = 2.937 * math.pow(l_A, 0.27795)\n            return macs\n\n        if 9.2 >= energy_keV >= 1:\n            macs = 0.627 * math.pow(l_A, .4231)\n            return macs\n\n        if 40.0 >= energy_keV >= 1:\n            macs = 0.089 * math.pow(l_A, .44767)\n            return macs\n\n    if z == 2:\n        if 3.7 <= energy_keV <= 6.0:\n            macs = 3.7 * math.pow(l_A, .10107)\n            return macs\n\n        if energy_keV <= 9.5:\n            macs = 2.44950 * math.pow(l_A, .19040)\n            return macs\n\n        if energy_keV <= 18.:\n            macs = 1.1265 * math.pow(l_A, .21026)\n            return macs\n\n        if energy_keV <= 40.:\n            macs = 0.08672 * math.pow(l_A, .18714)\n            return macs\n\n    if z == 3:\n        if 5.90 <= energy_keV <= 8.80:\n            macs = 5.9 * math.pow(l_A, .18233)\n            return macs\n\n        if energy_keV <= 12.50:\n            macs = 4.17123 * math.pow(l_A, 0.26263)\n            return macs\n\n        if energy_keV <= 19.20:\n            macs = 1.97884 * math.pow(l_A, .26156)\n            return macs\n\n        if energy_keV <= 40.:\n            macs = .2920 * math.pow(l_A, .22601)\n            return macs\n\n    if z == 4:\n        if 8.0 <= energy_keV <= 12.50:\n            macs = 8. * math.pow(l_A, .38680)\n            return macs\n\n        if energy_keV <= 19.80:\n            macs = 5.53694 * math.pow(l_A, .38371)\n            return macs\n\n        if energy_keV <= 40.:\n            macs = 0.63152 * math.pow(l_A, .29211)\n            return macs\n\n    if z == 5:\n        if 10.2 <= energy_keV <= 15.:\n            macs = 10.2 * math.pow(l_A, .62897)\n            return macs\n\n        if energy_keV <= 21.:\n            macs = 6.84584 * math.pow(l_A, .49970)\n            return macs\n\n        if energy_keV <= 31.:\n            macs = 3.83941 * math.pow(l_A, .40524)\n            return macs\n\n        if energy_keV >= 40.:\n            macs = .63152 * math.pow(l_A, .29211)\n            return macs\n\n    if z == 6:\n        if 13. <= energy_keV <= 21.:\n            macs = 13. * math.pow(l_A, 1.10987)\n            return macs\n\n        if energy_keV <= 27.5:\n            macs = 9.94906 * math.pow(l_A, .74709)\n            return macs\n\n        if energy_keV <= 40.:\n            macs = 2.588 * math.pow(l_A, .40943)\n            return macs\n\n    if z == 7:\n        if 15. <= energy_keV < 21.:\n            macs = 15. * math.pow(l_A, 1.4640)\n            return macs\n\n        if energy_keV <= 30.:\n            macs = 12.96310 * math.pow(l_A, 1.06418)\n            return macs\n\n        if energy_keV <= 40.:\n            macs = 6.26451 * math.pow(l_A, .60023)\n            return macs\n\n    if z == 8:\n        if 17.2 <= energy_keV <= 25.:\n            macs = 17.2 * math.pow(l_A, 1.83450)\n            return macs\n\n        if energy_keV <= 40.:\n            macs = 13.21194 * math.pow(l_A, 1.07154)\n            return macs\n\n    if z == 9:\n        if 20. <= energy_keV <= 28.5:\n            macs = 20.0 * math.pow(l_A, 2.41791)\n            return macs\n\n        if energy_keV <= 40.:\n            macs = 14.85851 * math.pow(l_A, 1.19931)\n            return macs\n\n    if z == 10:\n        if 23. <= energy_keV <= 30.:\n            macs = 23. * math.pow(l_A, 3.28063)\n            return macs\n\n        if energy_keV <= 40.:\n            macs = 19.86943 * math.pow(l_A, 1.79454)\n            return macs\n\n    if z == 11:\n        if energy_keV <= 25. and energy_keV <= 30.:\n            macs = 25. * math.pow(l_A, 3.51621)\n            return macs\n\n        if energy_keV <= 40.:\n            macs = 22.51741 * math.pow(l_A, 2.05417)\n            return macs\n\n    if z == 12:\n        if 27.3 <= energy_keV <= 30.:\n            macs = 27.3 * math.pow(l_A, 3.19488)\n            return macs\n\n    if z == 13:\n        if 29.5 <= energy_keV < 40.:\n            macs = 29.5 * math.pow(l_A, 3.40890)\n            return macs\n\n    if z == 14:\n        if 32.5 <= energy_keV <= 40.:\n            macs = 32.5 * math.pow(l_A, 4.90164)\n            return macs\n\n    if z == 15:\n        if energy_keV <= 35. and energy_keV <= 40.:\n            macs = 35. * math.pow(l_A, 5.66476)\n            return macs\n\n    if z == 16:\n        if 37.5 <= energy_keV <= 40.:\n            macs = 37.5 * math.pow(l_A, 6.09135)\n            return macs\n\n    return 0.0\n\n\ndef macs_henke_ebisu(energy_keV, atomic_number):  # noqa\n    \"\"\"\n    Compute mass absorption coefficient from Henke and Ebisu (1974) model.\n\n    Parameterization from tables in files KCOEFF.PRN and LCOEFF.PRN.\n\n    @todo Find the unit of the returned mass absorption coefficient.\n\n    @note Use Zaluzec model for hydrogen absorber.\n\n    @param energy_keV energy in keV\n    @param atomic_number atomic number of the absorber.\n    @return mass absorption coefficient in ??.\n    @retval -1.0 if energy is greater than 1.6 keV.\n    @retval -1.0 if absorber is less than 3 or greater than 94.\n    \"\"\"\n    if energy_keV <= 0.0:\n        raise ValueError\n\n    z = atomic_number\n\n    if z == 1:\n        absp = mac_zaluzec_cm2_g(12.3981 / energy_keV, z)\n        return absp\n\n    if energy_keV > 1.6:\n        return -1\n\n    zmin = 3\n    zmax = 94\n    if (z < zmin) or (z > zmax):\n        return -1\n\n    i = 0\n    emin = i\n    emax = i + 1\n    # ffitfener = 0\n    nener = 14\n\n    # Energy and there corresponding columns value in the kcoeff.prn (0) and lcoeff.prn (1) files.\n    # position is a pair of (fileIndex, columnIndex).\n    # Updated value to have the same energy for x-ray line and in the files.\n    energies_keV = [0.183, 0.277, 0.392, 0.452, 0.525, 0.573, 0.637, 0.677, 0.705, 0.776, 0.848, 0.852, 0.930, 1.012]  # noqa\n    # Original values\n    # energie[14] ={0.185, 0.281, 0.392, 0.452, 0.525, 0.573, 0.637, 0.677, 0.705, 0.776, 0.849, 0.852, 0.930, 1.012}\n    position = [[0, 1], [0, 2], [0, 3], [1, 1], [0, 4], [1, 3], [1, 4], [0, 5], [1, 5], [1, 6], [0, 6], [1, 7], [1, 8],\n                [1, 9]]\n\n    if 0.183 <= energy_keV <= 1.012:\n        # Recherche de position dans les fichiers.\n        condition = True\n        while condition:\n            emin = i\n            emax = i + 1\n            i += 1\n\n            condition = ((energies_keV[emax] < energy_keV) and (i < nener))\n\n        ffitfener = 0\n    else:\n        if energy_keV < 0.183:\n            emin = 1\n            emax = 2\n            ffitfener = 1\n        else:\n            # Position par defaut si extrapolation au-dela de 1.01.\n            emin = 12\n            emax = 13\n            ffitfener = 0\n\n    posfmin = position[emin][0]\n    posfmax = position[emax][0]\n    poscmin = position[emin][1]\n    poscmax = position[emax][1]\n    posl = z - 2\n\n    # kcol = 6\n    # lcol = 9\n    #\n    # absmin = 0.0\n    # absmax = 0.0\n\n    # for INI File\n    file_path_K = get_current_module_path(__file__, \"../../../data/casino/KCOEFF.PRN\")  # noqa\n    file_path_L = get_current_module_path(__file__, \"../../../data/casino/LCOEFF.PRN\")  # noqa\n\n    if posfmin == 0:\n        with open(file_path_K, 'r') as kcoeff:\n            lines = kcoeff.readlines()\n\n            items = lines[posl - 1].split()\n            absmin = float(items[poscmin - 1])\n    else:\n        with open(file_path_L, 'r') as lcoeff:\n            lines = lcoeff.readlines()\n\n            items = lines[posl - 1].split()\n            absmin = float(items[poscmin - 1])\n\n    if posfmax == 0:\n        with open(file_path_K, 'r') as kcoeff:\n            lines = kcoeff.readlines()\n\n            items = lines[posl - 1].split()\n            absmax = float(items[poscmax - 1])\n    else:\n        with open(file_path_L, 'r') as lcoeff:\n            lines = lcoeff.readlines()\n\n            items = lines[posl - 1].split()\n            absmax = float(items[poscmax - 1])\n\n    # absp = 0.0\n    if ffitfener == 0:\n        absp = ((absmax - absmin) / (energies_keV[emax] - energies_keV[emin])) * (energy_keV - energies_keV[emin]) + \\\n               absmin\n    else:\n        # Fit exponentiel a faible energie.\n        absp = math.exp(\n            ((math.log(absmax) - math.log(absmin)) / (math.log(energies_keV[emax]) - math.log(energies_keV[emin]))) * (\n                        math.log(energy_keV) - math.log(energies_keV[emin])) + math.log(absmin))\n\n    return absp\n\n\ndef macs_total(energy_keV, atomic_number):  # noqa\n    \"\"\"\n    Compute mass absorption coefficient by combining Leroux and Henke-Ebisu models.\n\n    @note For energy less or equal than 1.01 keV it use Henke-Ebisu model.\n    @note For energy greater than 1.01 keV it use Heinrich model.\n\n    @todo Find the unit of the returned mass absorption coefficient.\n\n    @param energy_keV electron energy in keV.\n    @param atomic_number atomic number of the absorber\n    @return mass absorption coefficient in ??.\n    \"\"\"\n\n    if energy_keV <= 1.01:\n        abst = macs_henke_ebisu(energy_keV, atomic_number)\n    else:\n        abst = macs_heinrich(12.3981 / energy_keV, atomic_number)\n\n    return abst\n\n\ndef macs_heinrich(wavelength_A, atomic_number_absorber):  # noqa\n    \"\"\"\n    Compute mass absorption coefficient from Heinrich model.\n\n    @todo Find the unit of the returned mass absorption coefficient.\n\n    @param wavelength_A electron wavelength in Angstrom.\n    @param atomic_number_absorber\n    @return mass absorption coefficient in ??.\n    \"\"\"\n    l_A = wavelength_A  # noqa\n\n    z = atomic_number_absorber\n    atomic_number = atomic_number_absorber\n\n    # c_total = 0\n\n    ntot = 0\n\n    atot = 0\n\n    btot = 0\n    bmult = 1\n    cmult = 1\n\n    energy_c_keV = np.zeros(10)  # noqa\n    n = np.zeros(4)\n    a = np.zeros(5)\n    b = np.zeros(5)\n    c_tot = np.zeros(6)\n    C = np.zeros((6, 7))  # noqa\n\n    for i in range(10):\n        energy_c_keV[i] = transitions[atomic_number - 1][i]\n\n    energy_keV = 12.3981 / l_A  # noqa\n\n    if energy_keV > energy_c_keV[0]:\n        if atomic_number < 6:\n            C[0][0] = -2.87536e-4\n            C[0][1] = 1.808599e-3\n            C[0][2] = 0\n            C[0][3] = 0\n            C[0][4] = 0\n            C[0][5] = 0\n\n            n[0] = 3.34745\n            n[1] = 0.02652873\n            n[2] = -0.01273815\n            n[3] = 0\n\n            a[0] = 24.4545\n            a[1] = 155.6055\n            a[2] = -14.15422\n            a[3] = 0\n            a[4] = 0\n\n            b[0] = -103.0\n            b[1] = -18.2\n            b[2] = 0\n            b[3] = 0\n            b[4] = 0\n\n        if atomic_number > 5:\n            C[0][0] = 5.253e-3\n            C[0][1] = 1.33257e-3\n            C[0][2] = -7.5937e-5\n            C[0][3] = 1.69357e-6\n            C[0][4] = -1.3975e-8\n            C[0][5] = 0\n\n            n[0] = 3.112\n            n[1] = -0.0121\n            n[2] = 0\n            n[3] = 0\n\n            a[0] = 0\n            a[1] = 47.0\n            a[2] = 6.52\n            a[3] = -0.152624\n            a[4] = 0\n\n            b[0] = 0\n            b[1] = 0\n            b[2] = 0\n            b[3] = 0\n            b[4] = 0\n\n    if energy_c_keV[0] > energy_keV > energy_c_keV[3]:\n        C[0][0] = -9.24e-5\n        C[0][1] = 1.41478e-4\n        C[0][2] = -5.24999e-6\n        C[0][3] = 9.85296e-8\n        C[0][4] = -9.07306e-10\n        C[0][5] = 3.19254e-12\n\n        n[0] = 2.7575\n        n[1] = 1.889e-3\n        n[2] = -4.982e-5\n        n[3] = 0\n\n        a[0] = 0\n        a[1] = 17.8096\n        a[2] = 0.067429\n        a[3] = 0.01253775\n        a[4] = -1.16286e-4\n\n        b[0] = 0\n        b[1] = 0\n        b[2] = 0\n        b[3] = 0\n        b[4] = 0\n\n        if energy_c_keV[0] > energy_keV > energy_c_keV[1]:\n            cmult = 1\n        if energy_c_keV[1] > energy_keV > energy_c_keV[2]:\n            cmult = 0.858\n        if energy_c_keV[2] > energy_keV > energy_c_keV[3]:\n            cmult = (0.8933 - z * 8.29e-3 + math.pow(z, 2) * 6.38e-5)\n\n    if energy_c_keV[3] > energy_keV > energy_c_keV[4]:\n        if atomic_number < 30:\n            C[0][0] = 1.889757e-2\n            C[0][1] = -1.8517159e-3\n            C[0][2] = 6.9602789e-5\n            C[0][3] = -1.1641145e-6\n            C[0][4] = 7.2773258e-9\n            C[0][5] = 0\n\n        if atomic_number > 29:\n            C[0][0] = 3.0039e-3\n            C[0][1] = -1.73663566e-4\n            C[0][2] = 4.0424792e-6\n            C[0][3] = -4.0585911e-8\n            C[0][4] = 1.497763e-10\n            C[0][5] = 0\n\n        n[0] = 0.5385\n        n[1] = 0.084597\n        n[2] = -1.08246e-3\n        n[3] = 4.4509e-6\n\n        a[0] = 0\n        a[1] = 10.2575657\n        a[2] = -0.822863477\n        a[3] = 2.63199611e-2\n        a[4] = -1.8641019e-4\n\n        if atomic_number < 61:\n            b[0] = 0\n            b[1] = 5.654\n            b[2] = -0.536839169\n            b[3] = 0.018972278\n            b[4] = -1.683474e-4\n\n        if atomic_number > 60:\n            b[0] = 0\n            b[1] = -1232.4022\n            b[2] = 51.114164\n            b[3] = -0.699473097\n            b[4] = 3.1779619e-3\n\n    if energy_c_keV[4] > energy_keV > energy_c_keV[8]:\n        C[0][0] = 7.7708e-5\n        C[0][1] = -7.83544e-6\n        C[0][2] = 2.209365e-7\n        C[0][3] = -1.29086e-9\n        C[0][4] = 0\n        C[0][5] = 0\n\n        C[1][0] = 1.406\n        C[1][1] = 0.0162\n        C[1][2] = -6.561e-4\n        C[1][3] = 4.865e-6\n        C[1][4] = 0\n        C[1][5] = 0\n\n        C[2][0] = 0.584\n        C[2][1] = 0.01955\n        C[2][2] = -1.285e-4\n        C[2][3] = 0\n        C[2][4] = 0\n        C[2][5] = 0\n\n        C[3][0] = 1.082\n        C[3][1] = 1.366e-3\n        C[3][2] = 0\n        C[3][3] = 0\n        C[3][4] = 0\n        C[3][5] = 0\n\n        C[4][0] = 1.6442\n        C[4][1] = -0.0480\n        C[4][2] = 4.0664e-4\n        C[4][3] = 0\n        C[4][4] = 0\n        C[4][5] = 0\n\n        n[0] = 3.0\n        n[1] = -0.004\n        n[2] = 0\n        n[3] = 0\n\n        a[0] = 0\n        a[1] = 4.62\n        a[2] = -0.04\n        a[3] = 0\n        a[4] = 0\n\n        b[0] = 2.51\n        b[1] = -0.052\n        b[2] = 3.78e-4\n        b[3] = 0\n        b[4] = 0\n\n        bmult = energy_c_keV[7]\n\n    if energy_c_keV[8] > energy_keV > energy_c_keV[9]:\n        C[0][0] = 4.3156e-3\n        C[0][1] = -1.4653e-4\n        C[0][2] = 1.707073e-6\n        C[0][3] = -6.69827e-9\n        C[0][4] = 0\n        C[0][5] = 0\n\n        cmult = 1.08\n\n        n[0] = 0.3736\n        n[1] = 0.02401\n        n[2] = 0\n        n[3] = 0\n\n        a[0] = 0\n        a[1] = 19.64\n        a[2] = -0.61239\n        a[3] = 5.39309e-3\n        a[4] = 0\n\n        b[0] = -113.0\n        b[1] = 4.5\n        b[2] = 0\n        b[3] = 0\n        b[4] = 0\n\n    if energy_keV < energy_c_keV[9]:\n        cutoff = (0.252 * z - 31.1812) * z + 1042\n\n        C[0][0] = 4.3156e-3\n        C[0][1] = -1.4653e-4\n        C[0][2] = 1.707073e-6\n        C[0][3] = -6.69827e-9\n        C[0][4] = 0\n        C[0][5] = 0\n\n        cmult = 1.08\n\n        a[0] = 0\n        a[1] = 19.64\n        a[2] = -0.61239\n        a[3] = 5.39309e-3\n        a[4] = 0\n\n    for i in range(5):\n        for j in range(6):\n            c_tot[i] += cmult * C[i][j] * math.pow(z, j)\n    for i in range(4):\n        ntot += n[i] * math.pow(z, i)\n    for i in range(5):\n        atot += a[i] * math.pow(z, i)\n    for i in range(5):\n        btot += bmult * b[i] * math.pow(z, i)\n\n    if energy_c_keV[4] > energy_keV > energy_c_keV[5]:\n        c_total = c_tot[0] * c_tot[1] * c_tot[2]\n    elif energy_c_keV[5] > energy_keV > energy_c_keV[6]:\n        c_total = c_tot[0] * c_tot[1] * c_tot[3]\n    elif energy_c_keV[6] > energy_keV > energy_c_keV[7]:\n        c_total = 0.95 * c_tot[0] * c_tot[1]\n    elif energy_c_keV[7] > energy_keV > energy_c_keV[8]:\n        c_total = c_tot[0] * c_tot[1] * c_tot[4]\n    else:\n        c_total = c_tot[0]\n\n    macsh = c_total * math.pow(z, 4) / A[atomic_number] * math.pow((12.397 / energy_keV), ntot) * (\n                1 - math.exp((-energy_keV * 1000 + btot) / atot))\n\n    if energy_keV < energy_c_keV[9]:\n        macsh = 1.02 * c_total * math.pow((12.397 / energy_keV), ntot) * c_total * math.pow(z, 4) / A[atomic_number] * (\n                    (energy_keV * 1000 - cutoff) / (energy_c_keV[9] - cutoff))\n\n    return macsh\n\n\ndef efficiency(energy_keV):  # noqa\n    \"\"\"\n    Compute x-ray detector collection efficiency.\n\n    If energy is less than 7 keV, include absorption from:\n    - Al layer\n    - Formvar layer\n    - Au layer\n    - Si dead layer\n    - Be window\n    - Carbon contamination layer\n    - Ice contamination layer\n\n    If energy is greater than 15 keV, include the effect of Si thickness.\n\n    If energy is between 7 and 15 keV, efficiency is one.\n\n    If energy is less than 0.03 keV, the efficiency is zero.\n\n    @param energy_keV x-ray energy in keV.\n    @return fraction of detected x-ray.\n    \"\"\"\n\n    # detector parameters.\n    parameters = {}\n    # Aluminium.\n    parameters[1] = 120e-7\n    # Parylene.\n    parameters[2] = 130e-7\n    # Au.\n    parameters[3] = 0.0\n    # Couche morte de Si.\n    parameters[4] = 50e-7\n    # Berrylium.\n    parameters[5] = 0.0\n    # Carbone.\n    parameters[6] = 0.0\n    # Glace H2O.\n    parameters[7] = 0.0\n    # Cristal.\n    parameters[8] = 0.3\n\n    l_A = 12.3981 / energy_keV  # noqa\n\n    if energy_keV < 7.0:\n        if energy_keV > 0.03:\n            if parameters[1] != 0.0:\n                a_al = mac_zaluzec_cm2_g(l_A, 13) * MASS_DENSITY_AL_g_cm3 * parameters[1]\n            else:\n                a_al = 0\n\n            # APA=(CH_C6H6*mac_zaluzec_cm2_g(l,1)+CC*mac_zaluzec_cm2_g(l,6))*D_C*a[2]\n\n            if parameters[2] != 0.0:\n                a_formvar = (0.0707 * mac_zaluzec_cm2_g(l_A, 1) +\n                             0.6063 * mac_zaluzec_cm2_g(l_A, 6) +\n                             0.3231 * mac_zaluzec_cm2_g(l_A, 8)) * MASS_DENSITY_C_g_cm3 * parameters[2]\n            else:\n                a_formvar = 0\n\n            if parameters[3] != 0.0:\n                a_au = mac_zaluzec_cm2_g(l_A, 79) * MASS_DENSITY_AU_g_cm3 * parameters[3]\n            else:\n                a_au = 0\n\n            if parameters[4] != 0.0:\n                a_si_dl = mac_zaluzec_cm2_g(l_A, 14) * MASS_DENSITY_SI_g_cm3 * parameters[4]\n            else:\n                a_si_dl = 0\n\n            if parameters[5] != 0.0:\n                a_be = mac_zaluzec_cm2_g(l_A, 4) * MASS_DENSITY_BE_g_cm3 * parameters[5]\n            else:\n                a_be = 0\n\n            if parameters[6] != 0.0:\n                a_c = mac_zaluzec_cm2_g(l_A, 6) * MASS_DENSITY_C_g_cm3 * parameters[6]\n            else:\n                a_c = 0\n\n            if parameters[7] != 0.0:\n                a_h2o = (CH_H2O * mac_zaluzec_cm2_g(l_A, 1) + CO * mac_zaluzec_cm2_g(l_A, 8)) * \\\n                        MASS_DENSITY_H2O_g_cm3 * parameters[7]\n            else:\n                a_h2o = 0\n\n            eff = math.exp(-a_h2o - a_al - a_formvar - a_au - a_si_dl - a_be - a_c)\n            return eff\n        else:\n            return 0.0\n\n    if energy_keV > 15.0:\n        tsi = parameters[8]\n        asi = macs_total(12.3981 / l_A, 14) * MASS_DENSITY_SI_g_cm3 * tsi\n        eff = (1.0 - math.exp(-asi))\n\n        return eff\n\n    if 7.0 < energy_keV < 10.0:\n        return 1.0\n\n    return 1.0\n", "meta": {"hexsha": "dd04394b7bafb3706e2c87774f8ab3f64ff1e8ca", "size": 38284, "ext": "py", "lang": "Python", "max_stars_repo_path": "xray/mac/models/casino.py", "max_stars_repo_name": "drix00/pyxraymac", "max_stars_repo_head_hexsha": "f9e2c4e073ff1f5d9fbfaa58b3b66c041433896a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "xray/mac/models/casino.py", "max_issues_repo_name": "drix00/pyxraymac", "max_issues_repo_head_hexsha": "f9e2c4e073ff1f5d9fbfaa58b3b66c041433896a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xray/mac/models/casino.py", "max_forks_repo_name": "drix00/pyxraymac", "max_forks_repo_head_hexsha": "f9e2c4e073ff1f5d9fbfaa58b3b66c041433896a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7720254314, "max_line_length": 125, "alphanum_fraction": 0.5389718943, "include": true, "reason": "import numpy", "num_tokens": 15893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.3073580168652638, "lm_q1q2_score": 0.17514877635346673}}
{"text": "# -*- coding: utf-8 -*-\r\n  \r\n# Cage deformer for Maya based on Mean value coordinates\r\n# \r\n#  @author      Shizuo KAJI\r\n#  @date        2013/5/13\r\n\r\n# usage:\r\n#   Load the plugin from \"Plugin Manager\"\r\n#   Select a target mesh and type the following from the script editor:\r\n#        import maya.cmds as cmds\r\n#        deformer = cmds.deformer(type='cageDeformerMVC')[0]\r\n#   Then, select a cage mesh and type the following:\r\n#        shape=pm.selected( type=\"transform\" )[0].getShapes()[0]\r\n#        cmds.connectAttr(shape+\".outMesh\", deformer+\".cageMesh\")\r\n#   Wait for a moment, and edit the cage mesh\r\n\r\nimport maya.OpenMayaMPx as OpenMayaMPx\r\nimport maya.OpenMaya as OpenMaya\r\nimport numpy as np\r\n\r\nOFF = 10\r\nON = 0\r\n\r\nclass CageDeformerNode(OpenMayaMPx.MPxDeformerNode):\r\n    kPluginNodeId = OpenMaya.MTypeId(0x000000020)\r\n    kPluginNodeName = 'cageDeformerMVC'\r\n     \r\n    aCageMesh = OpenMaya.MObject()\r\n\r\n    w=[]   # weights\r\n    p=[]   # vertices of the cage\r\n    \r\n    def __init__(self):\r\n        OpenMayaMPx.MPxDeformerNode.__init__(self)\r\n \r\n    def deform(self, data, itGeo, localToWorldMatrix, mIndex):\r\n        blendMode = data.inputValue( CageDeformerNode.aBlendMode ).asShort()\r\n        if blendMode == OFF:\r\n            self._resetPosition(itGeo)\r\n            return\r\n        CageMesh = data.inputValue(CageDeformerNode.aCageMesh).asMesh()\r\n        if CageMesh.isNull():\r\n            return\r\n        cageMesh = OpenMaya.MFnMesh(CageMesh)\r\n        q=self._getPoints(cageMesh)\r\n        if len(self.p)!= len(q):\r\n            # initialisation\r\n            self.p=q\r\n            tri=self._getTri(cageMesh)\r\n            self.w=[]\r\n            while not itGeo.isDone():\r\n                mu=np.zeros(len(q))\r\n                pt = itGeo.position()\r\n                v = np.array([pt.x, pt.y, pt.z])\r\n                for tr in tri:\r\n                    e=[v-q[tr[i]] for i in range(3)]\r\n                    en=[e[i]/np.linalg.norm(e[i]) for i in range(3)] \r\n                    b=[np.arccos(np.dot(en[(i+1)%3],en[(i+2)%3])) for i in range(3)]\r\n                    n=[np.cross(en[(i+1)%3],en[(i+2)%3]) for i in range(3)]\r\n                    nu=[n[i]/np.linalg.norm(n[i]) for i in range(3)] \r\n                    a=[np.dot(nu[(i+1)%3],nu[(i+2)%3]) for i in range(3)]\r\n                    for i in range(3):\r\n                        mu[tr[i]]-=(b[i]+b[(i+2)%3]*a[(i+1)%3]+b[(i+1)%3]*a[(i+2)%3])/(2.0*np.dot(en[i],nu[i]))\r\n                mu /= np.array([np.linalg.norm(v-q[j]) for j in range(len(q))])\r\n                smu=sum(mu)\r\n                self.w.append(np.array([mu[j]/smu for j in range(len(q))]))\r\n                itGeo.next() \r\n            return\r\n            \r\n        # run-time\r\n        pts = OpenMaya.MPointArray()\r\n        itGeo.allPositions(pts)   \r\n        for i in range(pts.length()):\r\n            pos = sum([self.w[i][j]*q[j] for j in range(len(q))])\r\n            pts[i].x, pts[i].y, pts[i].z=[pos[0],pos[1],pos[2]]\r\n        itGeo.setAllPositions(pts)\r\n        return\r\n    \r\n\r\n    def _resetPosition(self,itGeo):\r\n        while not itGeo.isDone():\r\n            pt = itGeo.position()\r\n            itGeo.setPosition(pt)\r\n            itGeo.next() \r\n        return\r\n    \r\n    def _getPoints(self, mesh):\r\n        qs = OpenMaya.MPointArray()\r\n        mesh.getPoints(qs)\r\n        q=[np.array( [ qs[i].x, qs[i].y, qs[i].z ]) for i in range(qs.length())]\r\n        return q\r\n        \r\n    def _getTri(self, mesh):\r\n        count = OpenMaya.MIntArray()\r\n        tl = OpenMaya.MIntArray( )\r\n        mesh.getTriangles(count, tl)\r\n        num=len(tl)/3\r\n        tri = [ (tl[3*i], tl[3*i+1], tl[3*i+2]) for i in range(num)]\r\n        return tri\r\n\r\n    \r\ndef creator():\r\n    return OpenMayaMPx.asMPxPtr(CageDeformerNode())\r\n \r\ndef initialize():\r\n    outputGeom = OpenMayaMPx.cvar.MPxDeformerNode_outputGeom\r\n\r\n    tAttr = OpenMaya.MFnTypedAttribute()\r\n    CageDeformerNode.aCageMesh = tAttr.create('cageMesh', 'cm', OpenMaya.MFnData.kMesh)\r\n    tAttr.setStorable(False)\r\n    CageDeformerNode.addAttribute( CageDeformerNode.aCageMesh )\r\n    CageDeformerNode.attributeAffects(CageDeformerNode.aCageMesh, outputGeom)\r\n      \r\n    # interpolation mode \r\n    eAttr = OpenMaya.MFnEnumAttribute()\r\n    CageDeformerNode.aBlendMode = eAttr.create( \"blendMode\", \"bm\", 0 )\r\n    eAttr.addField( \"MVC\", ON )\r\n    eAttr.addField( \"off\", OFF )\r\n    eAttr.setStorable( True )\r\n    CageDeformerNode.addAttribute( CageDeformerNode.aBlendMode)    \r\n    CageDeformerNode.attributeAffects(CageDeformerNode.aBlendMode, outputGeom)  \r\n\r\ndef initializePlugin(obj):\r\n    plugin = OpenMayaMPx.MFnPlugin(obj, 'Shizuo KAJI', '1.0', 'Any')\r\n    try:\r\n        plugin.registerNode(CageDeformerNode.kPluginNodeName, CageDeformerNode.kPluginNodeId, creator, initialize, OpenMayaMPx.MPxNode.kDeformerNode)\r\n    except:\r\n        raise RuntimeError, 'Failed to register node'\r\n \r\ndef uninitializePlugin(obj):\r\n    plugin = OpenMayaMPx.MFnPlugin(obj)\r\n    try:\r\n        plugin.deregisterNode(CageDeformerNode.kPluginNodeId)\r\n    except:\r\n        raise RuntimeError, 'Failed to deregister node'", "meta": {"hexsha": "bd81cf5934b9e73ceb7b175b6f480a819a609802", "size": 5071, "ext": "py", "lang": "Python", "max_stars_repo_path": "cageDeformerMVC.py", "max_stars_repo_name": "shizuo-kaji/CageMVC", "max_stars_repo_head_hexsha": "3f25faa5ef6b5da9bc0617b90bab9a6290054dd7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2016-04-08T18:12:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-07T15:56:30.000Z", "max_issues_repo_path": "cageDeformerMVC.py", "max_issues_repo_name": "shizuo-kaji/CageMVC", "max_issues_repo_head_hexsha": "3f25faa5ef6b5da9bc0617b90bab9a6290054dd7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cageDeformerMVC.py", "max_forks_repo_name": "shizuo-kaji/CageMVC", "max_forks_repo_head_hexsha": "3f25faa5ef6b5da9bc0617b90bab9a6290054dd7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-10-26T02:34:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T15:17:15.000Z", "avg_line_length": 37.2867647059, "max_line_length": 150, "alphanum_fraction": 0.5748373102, "include": true, "reason": "import numpy", "num_tokens": 1409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.17513091861816954}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"Base pyro model class\"\"\"\n\nimport os\nfrom collections import defaultdict, Iterable\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pyro import poutine\nfrom tqdm.auto import tqdm\n\nimport pyro\nimport torch\nfrom pyro.infer import SVI, JitTrace_ELBO\nfrom pyro.infer import Predictive\nfrom pyro.infer.autoguide import AutoDelta, AutoGuideList\nfrom cell2location.distributions.AutoNormal import AutoNormal\nfrom pyro.infer.autoguide import init_to_mean\nimport pyro.optim as optim\nfrom sklearn.model_selection import train_test_split\n\nfrom torch.utils.data import Dataset, DataLoader\n\nfrom cell2location.models.base.base_model import BaseModel\n\n\ndef flatten_iterable(iterable):\n    flattened_list = []\n    for i in iterable:\n        if isinstance(i, Iterable):\n            flattened_list += flatten_iterable(i)\n        else:\n            flattened_list.append(i)\n    return flattened_list\n\n\nclass MiniBatchDataset(Dataset):\n\n    def __init__(self, x_data, extra_data, return_idx=False):\n        self.x_data = x_data\n        self.extra_data = extra_data\n        self.return_idx = return_idx\n\n    def __len__(self):\n        return len(self.x_data)\n\n    def __getitem__(self, idx):\n        if self.return_idx:\n            return self.x_data[idx], {**{'idx': idx}, **{k: v[idx] for k, v in self.extra_data.items()}}\n        return self.x_data[idx], {k: v[idx] for k, v in self.extra_data.items()}\n\n\n# base model class - defining shared methods but not the model itself\nclass PyroModel(BaseModel):\n    r\"\"\"Base class for pyro models.\n    :param n_fact: number of factors\n    :param X_data: Numpy array of gene expression (cols) in spatial locations (rows)\n    :param learning_rate: ADAM learning rate for optimising Variational inference objective\n    :param n_iter: number of training iterations\n    :param total_grad_norm_constraint: gradient constraints in optimisation\n    \"\"\"\n\n    def __init__(\n            self,\n            X_data: np.ndarray,\n            n_fact: int = 10,\n            data_type: str = 'float32',\n            n_iter: int = 200000,\n            learning_rate=0.001,\n            total_grad_norm_constraint=200,\n            use_cuda=True,\n            verbose=True,\n            var_names=None, var_names_read=None,\n            obs_names=None, fact_names=None, sample_id=None,\n            minibatch_size=None,\n            minibatch_seed=42,\n            point_estim=[],\n            custom_guides={}\n    ):\n\n        ############# Initialise parameters ################\n        super().__init__(X_data, n_fact,\n                         data_type, n_iter,\n                         learning_rate, total_grad_norm_constraint,\n                         verbose, var_names, var_names_read,\n                         obs_names, fact_names, sample_id)\n\n        self.extra_data = {}\n        self.init_vals = {}\n        self.minibatch_size = minibatch_size\n        self.minibatch_seed = minibatch_seed\n        self.MiniBatchDataset = MiniBatchDataset\n        self.use_cuda = use_cuda\n        self.device = 'cuda' if self.use_cuda else 'cpu'\n        self.point_estim = point_estim\n        self.custom_guides = custom_guides\n        self.guide_type = 'AutoNormal'\n\n        if self.use_cuda:\n            if data_type == 'float32':\n                torch.set_default_tensor_type(torch.cuda.FloatTensor)\n            elif data_type == 'float16':\n                torch.set_default_tensor_type(torch.cuda.HalfTensor)\n            elif data_type == 'float64':\n                torch.set_default_tensor_type(torch.cuda.DoubleTensor)\n            else:\n                raise ValueError('Only 32, 16 and 64-bit tensors can be used (data_type)')\n        else:\n            if data_type == 'float32':\n                torch.set_default_tensor_type(torch.FloatTensor)\n            elif data_type == 'float16':\n                torch.set_default_tensor_type(torch.HalfTensor)\n            elif data_type == 'float64':\n                torch.set_default_tensor_type(torch.DoubleTensor)\n            else:\n                raise ValueError('Only 32, 16 and 64-bit tensors can be used (data_type)')\n\n    def sample_prior(self):\n        r\"\"\" Take one sample from the prior \n        :return: self.prior_trace dictionary with an element for each parameter of the model. \n        \"\"\"\n        print(\".sample_prior() not implemented yet\")\n\n    def fit_advi_iterative_simple(self, n: int = 3, method='advi', n_type='restart',\n                                  n_iter=None, learning_rate=None, progressbar=True, ):\n        r\"\"\" Find posterior using ADVI (deprecated)\n        (maximising likehood of the data and minimising KL-divergence of posterior to prior)\n        :param n: number of independent initialisations\n        :param method: which approximation of the posterior (guide) to use?.\n            * ``'advi'`` - Univariate normal approximation (pyro.infer.autoguide.AutoDiagonalNormal)\n            * ``'custom'`` - Custom guide using conjugate posteriors\n        :return: self.svi dictionary with svi pyro objects for each n, and sefl.elbo dictionary storing training history. \n        \"\"\"\n\n        # Pass data to pyro / pytorch\n        self.x_data = torch.tensor(self.X_data.astype(self.data_type))  # .double()\n\n        # initialise parameter store\n        self.svi = {}\n        self.hist = {}\n        self.guide_i = {}\n        self.samples = {}\n        self.node_samples = {}\n\n        self.n_type = n_type\n\n        if n_iter is None:\n            n_iter = self.n_iter\n\n        if learning_rate is None:\n            learning_rate = self.learning_rate\n\n        if np.isin(n_type, ['bootstrap']):\n            if self.X_data_sample is None:\n                self.bootstrap_data(n=n)\n        elif np.isin(n_type, ['cv']):\n            self.generate_cv_data()  # cv data added to self.X_data_sample\n\n        init_names = ['init_' + str(i + 1) for i in np.arange(n)]\n\n        for i, name in enumerate(init_names):\n\n            # initialise Variational distributiion = guide\n            try:\n                create_plates = getattr(self, 'create_plates')\n            except Exception as e:\n                create_plates = None\n            \n            if method is 'advi':\n                self.guide_i[name] = AutoGuideList(self.model)\n                self.guide_i[name].append(\n                    AutoNormal(poutine.block(self.model, expose_all=True, hide_all=False, hide=self.point_estim),\n                               init_loc_fn=init_to_mean, create_plates=create_plates))\n                self.guide_i[name].append(\n                    AutoDelta(poutine.block(self.model, hide_all=True, expose=self.point_estim,\n                                            create_plates=create_plates)))\n            elif method is 'custom':\n                self.guide_i[name] = self.guide\n\n            # pick dataset depending on the training mode and move to GPU\n            if np.isin(n_type, ['cv', 'bootstrap']):\n                self.x_data = torch.tensor(self.X_data_sample[i].astype(self.data_type))\n            else:\n                self.x_data = torch.tensor(self.X_data.astype(self.data_type))\n\n            if self.use_cuda:\n                # move tensors and modules to CUDA\n                self.x_data = self.x_data.cuda()\n\n            pyro.clear_param_store()\n\n            self.guide_i[name](self.x_data)\n\n            # initialise SVI inference method\n            self.svi[name] = SVI(self.model, self.guide_i[name],\n                                 optim.ClippedAdam({'lr': learning_rate,\n                                                    # limit the gradient step from becoming too large\n                                                    'clip_norm': self.total_grad_norm_constraint}),\n                                 loss=JitTrace_ELBO())\n\n            # record ELBO Loss history here\n            self.hist[name] = []\n\n            # train for n_iter\n            it_iterator = tqdm(range(n_iter))\n            for it in it_iterator:\n\n                hist = self.svi[name].step(self.x_data)\n                it_iterator.set_description('ELBO Loss: ' + str(np.round(hist, 3)))\n                self.hist[name].append(hist)\n\n                # if it % 50 == 0 & self.verbose:\n                # logging.info(\"Elbo loss: {}\".format(hist))\n                if it % 500 == 0:\n                    torch.cuda.empty_cache()\n\n    def set_initial_values(self):\n        r\"\"\"Method for setting initial values on covariate effect (gene_factors parameter)\n        :return: nothing\n        \"\"\"\n        if self.guide_type == 'AutoGuideList':\n            def prefix(i):\n                return f'AutoGuideList.{i}.'\n        elif self.guide_type == 'AutoNormal':\n            def prefix(i):\n                return f'AutoNormal.'\n\n        for k in list(self.init_vals.keys()):\n\n            if k in self.point_estim:\n                pyro.param(f'{prefix(1)}{k}',\n                           torch.Tensor(self.init_vals[k][1](self.init_vals[k][0])))\n            else:\n                pyro.param(f'{prefix(0)}locs.{k}',\n                           torch.Tensor(self.init_vals[k][1](self.init_vals[k][0])))\n\n    def fit_advi_iterative(self, n=3, method='advi', n_type='restart',\n                           n_iter=None, learning_rate=None,\n                           progressbar=True, num_workers=2,\n                           train_proportion=None, stratify_cv=None,\n                           l2_weight=False, sample_scaling_weight=0.5,\n                           checkpoints=None,\n                           checkpoint_dir='./checkpoints',\n                           tracking=False):\n\n        r\"\"\" Train posterior using ADVI method.\n        (maximising likehood of the data and minimising KL-divergence of posterior to prior)\n        :param n: number of independent initialisations\n        :param method: to allow for potential use of SVGD or MCMC (currently only ADVI implemented).\n        :param n_type: type of repeated initialisation:\n                                  'restart' to pick different initial value,\n                                  'cv' for molecular cross-validation - splits counts into n datasets,\n                                         for now, only n=2 is implemented\n                                  'bootstrap' for fitting the model to multiple downsampled datasets.\n                                         Run `mod.bootstrap_data()` to generate variants of data\n        :param n_iter: number of iterations, supersedes self.n_iter\n        :param train_proportion: if not None, which proportion of cells to use for training and which for validation.\n        :param checkpoints: int, list of int's or None, number of checkpoints to save while model training or list of\n            iterations to save checkpoints on\n        :param checkpoint_dir: str, directory to save checkpoints in\n        :param tracking: bool, track all latent variables during training - if True makes training 2 times slower\n        :return: None\n        \"\"\"\n\n        # initialise parameter store\n        self.svi = {}\n        self.hist = {}\n        self.guide_i = {}\n        self.trace_elbo_i = {}\n        self.samples = {}\n        self.node_samples = {}\n\n        if tracking:\n            self.logp_hist = {}\n\n        if n_iter is None:\n            n_iter = self.n_iter\n\n        if type(checkpoints) is int:\n            if n_iter < checkpoints:\n                checkpoints = n_iter\n            checkpoints = np.linspace(0, n_iter, checkpoints + 1, dtype=int)[1:]\n            self.checkpoints = list(checkpoints)\n        else:\n            self.checkpoints = checkpoints\n\n        self.checkpoint_dir = checkpoint_dir\n\n        self.n_type = n_type\n        self.l2_weight = l2_weight\n        self.sample_scaling_weight = sample_scaling_weight\n        self.train_proportion = train_proportion\n\n        if stratify_cv is not None:\n            self.stratify_cv = stratify_cv\n\n        if train_proportion is not None:\n            self.validation_hist = {}\n            self.training_hist = {}\n            if tracking:\n                self.logp_hist_val = {}\n                self.logp_hist_train = {}\n\n        if learning_rate is None:\n            learning_rate = self.learning_rate\n\n        if np.isin(n_type, ['bootstrap']):\n            if self.X_data_sample is None:\n                self.bootstrap_data(n=n)\n        elif np.isin(n_type, ['cv']):\n            self.generate_cv_data()  # cv data added to self.X_data_sample\n\n        init_names = ['init_' + str(i + 1) for i in np.arange(n)]\n\n        for i, name in enumerate(init_names):\n            ################### Initialise parameters & optimiser ###################\n            # initialise Variational distribution = guide\n            try:\n                create_plates = getattr(self, 'create_plates')\n            except Exception as e:\n                create_plates = None\n            \n            if method is 'advi':\n                if len(self.point_estim + flatten_iterable(self.custom_guides.keys())) > 0:\n                    self.guide_i[name] = AutoGuideList(self.model)\n                    normal_guide_block = poutine.block(self.model, expose_all=True, hide_all=False,\n                                                       hide=self.point_estim + flatten_iterable(\n                                                           self.custom_guides.keys()))\n                    self.guide_i[name].append(AutoNormal(normal_guide_block, init_loc_fn=init_to_mean,\n                                                         create_plates=create_plates))\n                    self.guide_i[name].append(\n                        AutoDelta(poutine.block(self.model, hide_all=True, expose=self.point_estim, \n                                                create_plates=create_plates)))\n                    for k, v in self.custom_guides.items():\n                        self.guide_i[name].append(v)\n                else:\n                    self.guide_i[name] = AutoNormal(self.model, init_loc_fn=init_to_mean, \n                                                    create_plates=create_plates)\n\n                self.guide_type = type(self.guide_i[name]).__name__\n\n            elif method is 'custom':\n                self.guide_i[name] = self.guide\n\n            def initialise_svi(x_data, extra_data):\n\n                pyro.clear_param_store()\n\n                self.set_initial_values()\n\n                self.init_guide(name, x_data, extra_data)\n\n                self.trace_elbo_i[name] = JitTrace_ELBO()  # JitTrace_ELBO()\n\n                # initialise SVI inference method\n                self.svi[name] = SVI(self.model, self.guide_i[name],\n                                     optim.ClippedAdam({'lr': learning_rate,\n                                                        # limit the gradient step from becoming too large\n                                                        'clip_norm': self.total_grad_norm_constraint}),\n                                     loss=self.trace_elbo_i[name])\n\n            # record ELBO Loss history here\n            self.hist[name] = []\n            if tracking:\n                self.logp_hist[name] = defaultdict(list)\n\n            if train_proportion is not None:\n                self.validation_hist[name] = []\n                if tracking:\n                    self.logp_hist_val[name] = defaultdict(list)\n\n            ################### Select data for this iteration ###################\n            if np.isin(n_type, ['cv', 'bootstrap']):\n                X_data = self.X_data_sample[i].astype(self.data_type)\n            else:\n                X_data = self.X_data.astype(self.data_type)\n\n            ################### Training / validation split ###################\n            # split into training and validation\n            if train_proportion is not None:\n                idx = np.arange(len(X_data))\n                train_idx, val_idx = train_test_split(idx, train_size=train_proportion,\n                                                      shuffle=True, stratify=self.stratify_cv)\n\n                extra_data_val = {k: torch.FloatTensor(v[val_idx]).to(self.device) for k, v in self.extra_data.items()}\n                extra_data_train = {k: torch.FloatTensor(v[train_idx]) for k, v in self.extra_data.items()}\n\n                x_data_val = torch.FloatTensor(X_data[val_idx]).to(self.device)\n                x_data = torch.FloatTensor(X_data[train_idx])\n            else:\n                # just convert data to CPU tensors\n                x_data = torch.FloatTensor(X_data)\n                extra_data_train = {k: torch.FloatTensor(v) for k, v in self.extra_data.items()}\n\n            ################### Move data to cuda - FULL data ###################\n            # if not minibatch do this:\n            if self.minibatch_size is None:\n                # move tensors to CUDA\n                x_data = x_data.to(self.device)\n                for k in extra_data_train.keys():\n                    extra_data_train[k] = extra_data_train[k].to(self.device)\n                # extra_data_train = {k: v.to(self.device) for k, v in extra_data_train.items()}\n\n            ################### MINIBATCH data ###################\n            else:\n                # create minibatches\n                dataset = MiniBatchDataset(x_data, extra_data_train, return_idx=True)\n                loader = DataLoader(dataset, batch_size=self.minibatch_size,\n                                    num_workers=0, shuffle=True, drop_last=True) \n\n            ################### Training the model ###################\n            if self.minibatch_size is None:\n                initialise_svi(x_data, extra_data_train)\n            else:\n                i = 0\n                for batch in loader:\n                    i = i + 1\n                    if i == 1:\n                        x_data_batch, extra_data_batch = batch\n                        x_data_batch = x_data_batch.to(self.device)\n                        extra_data_batch = {k: v.to(self.device) for k, v in extra_data_batch.items()}\n\n                initialise_svi(x_data, extra_data_batch)\n\n            # start training in epochs\n            epochs_iterator = tqdm(range(n_iter))\n            for epoch in epochs_iterator:\n\n                if self.minibatch_size is None:\n                    ################### Training FULL data ###################\n                    iter_loss = self.step_train(name, x_data, extra_data_train)\n\n                    self.hist[name].append(iter_loss)\n                    # save data for posterior sampling\n                    self.x_data = x_data\n                    self.extra_data_train = extra_data_train\n\n                    if tracking:\n                        guide_tr, model_tr = self.step_trace(name, x_data, extra_data_train)\n                        self.logp_hist[name]['guide'].append(guide_tr.log_prob_sum().item())\n                        self.logp_hist[name]['model'].append(model_tr.log_prob_sum().item())\n\n                        for k, v in model_tr.nodes.items():\n                            if \"log_prob_sum\" in v:\n                                self.logp_hist[name][k].append(v[\"log_prob_sum\"].item())\n\n                else:\n                    ################### Training MINIBATCH data ###################\n                    aver_loss = []\n                    if tracking:\n                        aver_logp_guide = []\n                        aver_logp_model = []\n                        aver_logp = defaultdict(list)\n\n                    for batch in loader:\n\n                        x_data_batch, extra_data_batch = batch\n                        x_data_batch = x_data_batch.to(self.device)\n                        extra_data_batch = {k: v.to(self.device) for k, v in extra_data_batch.items()}\n\n                        loss = self.step_train(name, x_data_batch, extra_data_batch)\n\n                        if tracking:\n                            guide_tr, model_tr = self.step_trace(name, x_data_batch, extra_data_batch)\n                            aver_logp_guide.append(guide_tr.log_prob_sum().item())\n                            aver_logp_model.append(model_tr.log_prob_sum().item())\n\n                            for k, v in model_tr.nodes.items():\n                                if \"log_prob_sum\" in v:\n                                    aver_logp[k].append(v[\"log_prob_sum\"].item())\n\n                        aver_loss.append(loss)\n\n                    iter_loss = np.sum(aver_loss)\n\n                    # save data for posterior sampling\n                    self.x_data = x_data_batch\n                    self.extra_data_train = extra_data_batch\n\n                    self.hist[name].append(iter_loss)\n\n                    if tracking:\n                        iter_logp_guide = np.sum(aver_logp_guide)\n                        iter_logp_model = np.sum(aver_logp_model)\n                        self.logp_hist[name]['guide'].append(iter_logp_guide)\n                        self.logp_hist[name]['model'].append(iter_logp_model)\n\n                        for k, v in aver_logp.items():\n                            self.logp_hist[name][k].append(np.sum(v))\n\n                if self.checkpoints is not None:\n                    if (epoch + 1) in self.checkpoints:\n                        self.save_checkpoint(epoch + 1, prefix=name)\n\n                ################### Evaluating cross-validation loss ###################\n                if train_proportion is not None:\n\n                    iter_loss_val = self.step_eval_loss(name, x_data_val, extra_data_val)\n\n                    if tracking:\n                        guide_tr, model_tr = self.step_trace(name, x_data_val, extra_data_val)\n                        self.logp_hist_val[name]['guide'].append(guide_tr.log_prob_sum().item())\n                        self.logp_hist_val[name]['model'].append(model_tr.log_prob_sum().item())\n\n                        for k, v in model_tr.nodes.items():\n                            if \"log_prob_sum\" in v:\n                                self.logp_hist_val[name][k].append(v[\"log_prob_sum\"].item())\n\n                    self.validation_hist[name].append(iter_loss_val)\n                    epochs_iterator.set_description(f'ELBO Loss: ' + '{:.4e}'.format(iter_loss) \\\n                                                    + ': Val loss: ' + '{:.4e}'.format(iter_loss_val))\n                else:\n                    epochs_iterator.set_description('ELBO Loss: ' + '{:.4e}'.format(iter_loss))\n\n                if epoch % 20 == 0:\n                    torch.cuda.empty_cache()\n\n            if train_proportion is not None:\n                # rescale loss\n                self.validation_hist[name] = [i / (1 - train_proportion)\n                                              for i in self.validation_hist[name]]\n                self.hist[name] = [i / train_proportion for i in self.hist[name]]\n\n                # reassing the main loss to be displayed\n                self.training_hist[name] = self.hist[name]\n                self.hist[name] = self.validation_hist[name]\n\n                if tracking:\n                    for k, v in self.logp_hist[name].items():\n                        self.logp_hist[name][k] = [i / train_proportion for i in self.logp_hist[name][k]]\n                        self.logp_hist_val[name][k] = [i / (1 - train_proportion) for i in self.logp_hist_val[name][k]]\n\n                    self.logp_hist_train[name] = self.logp_hist[name]\n                    self.logp_hist[name] = self.logp_hist_val[name]\n\n            if self.verbose:\n                print(plt.plot(np.log10(self.hist[name][0:])));\n\n    def init_guide(self, name, x_data, extra_data):\n\n        self.guide_i[name](x_data)\n\n    def step_train(self, name, x_data, extra_data):\n\n        return self.svi[name].step(x_data)\n\n    def step_eval_loss(self, name, x_data, extra_data):\n\n        return self.svi[name].evaluate_loss(x_data)\n\n    def step_predictive(self, predictive, x_data, extra_data):\n\n        return predictive(x_data)\n\n    def step_trace(self, name, x_data, extra_data):\n\n        guide_tr = poutine.trace(self.guide_i[name]).get_trace(x_data)\n        model_tr = poutine.trace(poutine.replay(self.model,\n                                                trace=guide_tr)).get_trace(x_data)\n        return guide_tr, model_tr\n\n    def fit_nuts(self, n_samples: int = 1000, warmup_steps: int = 1000, save_samples=False):\n\n        self.samples = {}\n        self.n_samples = n_samples\n\n        # create sampler and run MCMC\n        self.nuts_kernel = NUTS(self.model, jit_compile=True)\n        self.mcmc = MCMC(self.nuts_kernel, num_samples=n_samples,\n                         warmup_steps=warmup_steps)\n        self.mcmc.run(self.x_data)\n\n        post_samples = {k: v.detach().cpu().numpy() for k, v in self.mcmc.get_samples().items()}\n\n        # summarise samples\n        self.samples['post_sample_means'] = {v: post_samples[v].mean(axis=0) for v in post_samples.varnames}\n        self.samples['post_sample_q05'] = {v: np.quantile(post_samples[v], 0.05, axis=0) for v in post_samples.varnames}\n        self.samples['post_sample_q95'] = {v: np.quantile(post_samples[v], 0.95, axis=0) for v in post_samples.varnames}\n        self.samples['post_sample_sds'] = {v: post_samples[v].std(axis=0) for v in post_samples.varnames}\n\n        if (save_samples):\n            self.samples['post_samples'] = post_samples\n\n    def plot_history_old(self, iter_start: int = 15000, iter_end=-1):\n        r\"\"\" Plot training history\n        :param iter_start: omit initial iterations from the plot\n        :param iter_end: omit last iterations from the plot\n        \"\"\"\n        for i in self.hist.keys():\n            print(plt.plot(np.log10(np.array(self.hist[i])[iter_start:iter_end])));\n\n    def plot_history_1(self, iter_start=0, iter_end=-1,\n                       mean_field_slot=None, log_y=True, ax=None):\n        r\"\"\" Plot training history\n\n        :param iter_start: omit initial iterations from the plot\n        :param iter_end: omit last iterations from the plot\n        \"\"\"\n\n        if ax is None:\n            ax = plt\n            ax.set_xlabel = plt.xlabel\n            ax.set_ylabel = plt.ylabel\n\n        if mean_field_slot is None:\n            mean_field_slot = self.hist.keys()\n\n        for i in mean_field_slot:\n\n            if iter_end == -1:\n                iter_end = np.array(self.hist[i]).flatten().shape[0]\n\n            y = np.array(self.hist[i]).flatten()[iter_start:iter_end]\n            if log_y:\n                y = np.log10(y)\n            ax.plot(np.arange(iter_start, iter_end), y, label='train')\n            ax.set_xlabel('Training epochs')\n            ax.set_ylabel('Reconstruction accuracy (ELBO loss)')\n            ax.legend()\n            plt.tight_layout()\n\n    def sample_node1(self, node, init, batch_size: int = 10):\n\n        predictive = Predictive(self.model, guide=self.guide_i[init],\n                                num_samples=batch_size)\n\n        post_samples = {k: v.detach().cpu().numpy()\n                        for k, v in self.step_predictive(predictive, self.x_data, self.extra_data_train).items()\n                        if k == node}\n\n        return (post_samples[node])\n\n    def sample_node(self, node, init, n_sampl_iter,\n                    batch_size: int = 10, suff=''):\n\n        # sample first batch\n        self.samples[node + suff][init] = self.sample_node1(node, init, batch_size=batch_size)\n\n        for it in tqdm(range(n_sampl_iter - 1)):\n            # sample remaining batches\n            post_node = self.sample_node1(node, init, batch_size=batch_size)\n\n            # concatenate batches\n            self.samples[node + suff][init] = np.concatenate((self.samples[node + suff][init], post_node), axis=0)\n\n        # compute mean across samples\n        self.samples[node + suff][init] = self.samples[node + suff][init].mean(0)\n\n    def sample_all1(self, init='init_1', batch_size: int = 10):\n\n        predictive = Predictive(self.model, guide=self.guide_i[init],\n                                num_samples=batch_size)\n\n        post_samples = {k: v.detach().cpu().numpy()\n                        for k, v in self.step_predictive(predictive, self.x_data, self.extra_data_train).items()\n                        if k != \"data_target\"}\n\n        return (post_samples)\n\n    def sample_all(self, n_sampl_iter, init='init_1', batch_size: int = 10):\n\n        # sample first batch\n        self.samples['post_samples'] = self.sample_all1(init, batch_size=batch_size)\n\n        for it in tqdm(range(n_sampl_iter - 1)):\n            # sample remaining batches\n            post_samples = self.sample_all1(init, batch_size=batch_size)\n\n            # concatenate batches\n            self.samples['post_samples'] = {k: np.concatenate((self.samples['post_samples'][k],\n                                                               post_samples[k]), axis=0)\n                                            for k in post_samples.keys()}\n\n    def b_evaluate_stability(self, node, n_samples: int = 1000, batch_size: int = 10,\n                             align=True, transpose=True):\n        r\"\"\" Evaluate stability of posterior samples between training initialisations\n        (takes samples and correlates the values of factors between training initialisations)\n        :param node: which pymc3 node to sample? Factors should be in columns.\n        :param n_samples: the number of samples.\n        :param batch_size: generate samples in batches of size `batch_size`. Necessary for the computation to fit in the GPU memory \n        :return: self.samples[node_name+_stab] dictionary with an element for each training initialisation. \n        \"\"\"\n\n        self.n_samples = n_samples\n        self.n_sampl_iter = int(np.ceil(n_samples / batch_size))\n        self.n_sampl_batch = batch_size\n\n        self.samples[node + '_stab'] = {}\n\n        for i in self.guide_i.keys():\n            self.sample_node(node, i, self.n_sampl_iter,\n                             batch_size=self.n_sampl_batch, suff='_stab')\n\n        # plot correlations of posterior mean between training initialisations\n        for i in range(len(self.samples[node + '_stab'].keys()) - 1):\n            x = self.samples[node + '_stab']['init_' + str(1)]\n            y = self.samples[node + '_stab']['init_' + str(i + 2)]\n            if transpose:\n                x = x.T\n                y = y.T\n            print(self.align_plot_stability(x, y,\n                                            str(1), str(i + 2), align=align))\n\n    def sample_posterior(self, node='all',\n                         n_samples: int = 1000, batch_size: int = 10,\n                         save_samples=False,\n                         mean_field_slot='init_1'):\n        r\"\"\" Sample posterior distribution of parameters - either all or single parameter\n        :param node: pyro parameter to sample (e.g. default \"all\", self.spot_factors)\n        :param n_samples: number of posterior samples to generate (1000 is recommended, reduce if you get GPU memory error)\n        :param save_samples: save samples in addition to sample mean, 5% quantile, SD.\n        :param return_samples: return summarised samples in addition to saving them in `self.samples`\n        :param mean_field_slot: string, which mean_field slot to sample? 'init_1' by default\n        :return: dictionary of dictionaries (mean, 5% quantile, SD, optionally all samples) with numpy arrays for each parameter.\n        Optional dictionary of all samples contains parameters as numpy arrays of shape ``(n_samples, ...)``\n        \"\"\"\n\n        self.n_samples = n_samples\n        self.n_sampl_iter = int(np.ceil(n_samples / batch_size))\n        self.n_sampl_batch = batch_size\n\n        if (node == 'all'):\n            # Sample all parameters - might use a lot of GPU memory\n\n            self.sample_all(self.n_sampl_iter, init=mean_field_slot, batch_size=self.n_sampl_batch)\n\n            self.param_names = list(self.samples['post_samples'].keys())\n\n            self.samples['post_sample_means'] = {v: self.samples['post_samples'][v].mean(axis=0)\n                                                 for v in self.param_names}\n            self.samples['post_sample_q05'] = {v: np.quantile(self.samples['post_samples'][v], 0.05, axis=0)\n                                               for v in self.param_names}\n            self.samples['post_sample_q95'] = {v: np.quantile(self.samples['post_samples'][v], 0.95, axis=0)\n                                               for v in self.param_names}\n            self.samples['post_sample_sds'] = {v: self.samples['post_samples'][v].std(axis=0)\n                                               for v in self.param_names}\n\n            if not save_samples:\n                self.samples['post_samples'] = None\n\n        else:\n            self.sample_node(node, mean_field_slot, self.n_sampl_iter,\n                             batch_size=self.n_sampl_batch, suff='')\n\n        return (self.samples)\n\n    def save_checkpoint(self, n, prefix=''):\n        r\"\"\" Save pyro parameter store (current status of Variational parameters) to disk\n        :param n: epoch number\n        :param prefix: filename prefix (e.g. init number)\n        \"\"\"\n\n        if not os.path.exists(self.checkpoint_dir):\n            os.makedirs(self.checkpoint_dir)\n\n        filename = f'{self.checkpoint_dir}/{prefix}_{n}.ckp'\n        pyro.get_param_store().save(filename)\n\n    def load_checkpoint(self, filename):\n        r\"\"\" Load pyro parameter store (current status of Variational parameters) from disk\n        :param filename: checkpoint filename\n        \"\"\"\n\n        if filename in os.listdir(self.checkpoint_dir):\n            pyro.get_param_store().load(filename)\n        else:\n            checkpoints = os.listdir(self.checkpoint_dir)\n            checkpoints = '\\n'.join(checkpoints)\n            checkpoint_dir_abspath = os.path.abspath(self.checkpoint_dir)\n            raise ValueError(f'No such filename in {checkpoint_dir_abspath}, available filenames : \\n'\n                             f'{checkpoints}')\n", "meta": {"hexsha": "bc70a7d308194c86987971f90ce7e2366c03b00c", "size": 33839, "ext": "py", "lang": "Python", "max_stars_repo_path": "cell2location/models/pyro/pyro_model.py", "max_stars_repo_name": "bio-ruxandra-tesloianu/cell2location", "max_stars_repo_head_hexsha": "7d9a187b88cf67d6d134b452749f325826d67a57", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cell2location/models/pyro/pyro_model.py", "max_issues_repo_name": "bio-ruxandra-tesloianu/cell2location", "max_issues_repo_head_hexsha": "7d9a187b88cf67d6d134b452749f325826d67a57", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cell2location/models/pyro/pyro_model.py", "max_forks_repo_name": "bio-ruxandra-tesloianu/cell2location", "max_forks_repo_head_hexsha": "7d9a187b88cf67d6d134b452749f325826d67a57", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.8329015544, "max_line_length": 132, "alphanum_fraction": 0.5582316262, "include": true, "reason": "import numpy", "num_tokens": 6954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.17513091861816954}}
{"text": "# -*- coding: utf-8 -*-\n# =============================================================================\n# Copyright (c) 2012, Lawrence Livermore National Security, LLC.\n# Produced at the Lawrence Livermore National Laboratory.\n# Written by Joel Bernier <bernier2@llnl.gov> and others.\n# LLNL-CODE-529294.\n# All rights reserved.\n#\n# This file is part of HEXRD. For details on dowloading the source,\n# see the file COPYING.\n#\n# Please also see the file LICENSE.\n#\n# This program is free software; you can redistribute it and/or modify it under\n# the terms of the GNU Lesser General Public License (as published by the Free\n# Software Foundation) version 2.1 dated February 1999.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTABILITY\n# or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this program (see file LICENSE); if not, write to\n# the Free Software Foundation, Inc., 59 Temple Place, Suite 330,\n# Boston, MA 02111-1307 USA or visit <http://www.gnu.org/licenses/>.\n# =============================================================================\n\"\"\"\nModule for XRD material class\n\nUse the Material class directly for new materials.  Known\nmaterials are defined by name in materialDict.\n\"\"\"\nfrom configparser import SafeConfigParser as Parser\nimport numpy\n\nfrom hexrd.crystallography import PlaneData as PData\nfrom hexrd.valunits import valWUnit\nfrom hexrd import unitcell\nfrom hexrd.constants import ptable\nimport copy\n\nfrom os import path\nfrom pathlib import Path\nfrom CifFile import ReadCif\nimport  h5py\nfrom warnings import warn\nfrom hexrd.mksupport import Write2H5File\nfrom hexrd.symbols import xtal_sys_dict\nfrom hexrd.symbols import Hall_to_sgnum, HM_to_sgnum\n\n__all__ = ['Material', 'loadMaterialList']\n\n\n#\n# ================================================== Module Data\n#\n\n\ndef _angstroms(x):\n    return valWUnit('lp', 'length',  x, 'angstrom')\n\n\ndef _degrees(x):\n    return valWUnit('lp', 'angle',   x, 'degrees')\n\n\ndef _key(x):\n    return x.name\n\n\n#\n# ---------------------------------------------------CLASS:  Material\n#\n\n\nclass Material(object):\n    \"\"\"Simple class for holding lattice parameters, accessible by name.\n\n    The class references materials by name and contains lattice and\n    space group data.\n    default data is for nickel, but name is material\n    \"\"\"\n    DFLT_NAME = 'material.xtal'\n    DFLT_XTAL = 'Ni'\n    DFLT_SGNUM = 225\n\n    DFLT_LPARMS = [_angstroms(3.61), _angstroms(3.61), _angstroms(3.61),\n                   _degrees(90.0), _degrees(90.0), _degrees(90.0)]\n    DFLT_SSMAX = 100\n\n    DFLT_KEV = valWUnit('wavelength', 'energy', 80.725e0, 'keV')\n    DFLT_STR = 0.0025\n    DFLT_TTH = numpy.radians(0.25)\n    DFLT_TTHMAX = numpy.radians(160.0)\n    \"\"\"\n    ATOMINFO    Fractional Atom Position of an atom in the unit cell followed by the\n    site occupany and debye waller (U) factor in A^(-2)\n    B is related to U by B = 8 pi^2 U\n\n    ATOMTYPE    atomic number of all the different species in the unitcell\n    \"\"\"\n    DFLT_ATOMINFO = numpy.array([[0., 0., 0., 1.]])\n    DFLT_U = numpy.array([4.18e-7])\n    DFLT_ATOMTYPE = numpy.array([28])\n\n    '''\n    the dmin parameter is used to figure out the maximum sampling for g-vectors\n    this parameter is in angstroms\n    '''\n    DFLT_DMIN = _angstroms(1.0)\n\n    '''\n    some materials have more than one space group setting. for ex\n    the diamond cubic system has two settings with the origin either\n    at (0,0,0) or at (1/4,1/4,1/4) etc. this handle takes care of these\n    cases. but the defaiult is always 0\n\n    default space group setting\n    '''\n    DFLT_SGSETTING = 0\n\n    def __init__(self, name=None, material_file=None, dmin=DFLT_DMIN, kev=DFLT_KEV, sgsetting=DFLT_SGSETTING):\n        \"\"\"Constructor for Material\n\n        name -- (str) name of crystal\n        material_file -- (str) name of the material file\n        which contains the crystal. this could be either cif\n        or hdf5\n        \"\"\"\n        self.name = name\n        self.description = ''\n\n        self._dmin = dmin\n\n        self._beamEnergy = kev\n\n        self.sgsetting = sgsetting\n\n        if material_file:\n            # Get values from configuration\n            # self._readCfg(material_file)\n            # >> @ date 08/20/2020 SS removing dependence on hklmax\n            #self._hklMax = Material.DFLT_SSMAX\n            # self._beamEnergy = Material.DFLT_KEV\n            form = Path(material_file).suffix[1:]\n\n            if(form == 'cif'):\n                self._readCif(material_file)\n            elif(form in ['h5', 'hdf5', 'xtal']):\n                self._readHDFxtal(fhdf=material_file, xtal=name)\n        else:\n            # Use default values\n            self._lparms = Material.DFLT_LPARMS\n            # self._hklMax = Material.DFLT_SSMAX\n            #\n            self.description = ''\n            #\n            self.sgnum = Material.DFLT_SGNUM\n            self._sgsetting = Material.DFLT_SGSETTING\n            #\n            self._atominfo = Material.DFLT_ATOMINFO\n            #\n            self._U = Material.DFLT_U\n            #\n            self._atomtype = Material.DFLT_ATOMTYPE\n            #\n\n        self.unitcell = unitcell.unitcell(\n            self._lparms, self.sgnum, self._atomtype, self._atominfo, self._U,\n            self._dmin.getVal('nm'), self._beamEnergy.value,\n            self._sgsetting)\n\n        self._newPdata()\n        self.update_structure_factor()\n\n    def __str__(self):\n        \"\"\"String representation\"\"\"\n        s = 'Material:  %s\\n' % self.name\n        if self.description:\n            s += '   description:  %s\\n' % self.description\n            pass\n        s += '   plane Data:  %s' % str(self.planeData)\n        return s\n\n    def _newPdata(self):\n        \"\"\"Create a new plane data instance\"\"\"\n        # spaceGroup module calulates forbidden reflections\n        '''\n        >> @date 08/20/2020 SS removing dependence of planeData\n        initialization on the spaceGroup module. everything is\n        initialized using the unitcell module now\n        '''\n        hkls = self.unitcell.getHKLs(self._dmin.getVal('nm')).T\n        lprm = [self._lparms[i] for i in unitcell._rqpDict[self.unitcell.latticeType][0]]\n        laue = self.unitcell._laueGroup\n        self._pData = PData(hkls, lprm, laue,\n                            self._beamEnergy, Material.DFLT_STR,\n                            tThWidth=Material.DFLT_TTH,\n                            tThMax=Material.DFLT_TTHMAX)\n        '''\n          Set default exclusions\n          all reflections with two-theta smaller than 90 degrees\n        '''\n        tth = numpy.array([hkldata['tTheta'] for hkldata in self._pData.hklDataList])\n\n        dflt_excl = numpy.ones(tth.shape,dtype=numpy.bool)\n        dflt_excl[~numpy.isnan(tth)] = ~( (tth[~numpy.isnan(tth)] >= 0.0) & \\\n                                     (tth[~numpy.isnan(tth)] <= numpy.pi/2.0) )\n        dflt_excl[0] = False\n        self._pData.exclusions = dflt_excl\n\n        return\n\n    def update_structure_factor(self):\n        hkls = self.planeData.getHKLs(allHKLs=True)\n        sf = numpy.zeros([hkls.shape[0],])\n        for i,g in enumerate(hkls):\n            sf[i] = self.unitcell.CalcXRSF(g)\n\n        self.planeData.set_structFact(sf[~self.planeData.exclusions])\n\n    def _readCif(self, fcif=DFLT_NAME+'.cif'):\n        \"\"\"\n        >> @AUTHOR:     Saransh Singh, Lawrence Livermore National Lab, saransh1@llnl.gov\n        >> @DATE:       10/16/2019 SS 1.0 original\n        >> @DETAILS:    hexrd3 will have real structure factors and will require the overhaul\n                        of the crystallography. In this effort, we will have a cif reader and\n                        also the HDF5 format reader in the material class. We will be using\n                        pycifrw for i/o\n        \"\"\"\n\n        # make sure file exists etc.\n        if(fcif == Material.DFLT_NAME+'.cif'):\n            try:\n                cif = ReadCif(fcif)\n            except(OSError):\n                raise RuntimeError('OS Error: No file name supplied and default file name not found.')\n        else:\n            try:\n                cif = ReadCif(fcif)\n            except(OSError):\n                raise RuntimeError('OS Error: File not found')\n\n        # read the file\n        for k in cif.keys():\n            if('_cell_length_a' in cif[k]):\n                m = k\n                break\n        cifdata = cif[m]\n        # cifdata = cif[cif.keys()[0]]\n\n        # make sure the space group is present in the cif file, either as\n        # international table number, hermann-maguain or hall symbol\n        sgkey = ['_space_group_IT_number', \n                 '_symmetry_space_group_name_h-m', \n                 '_symmetry_space_group_name_hall',\n                 '_symmetry_Int_Tables_number']\n\n        sgdata = False\n        for key in sgkey:\n            sgdata = sgdata or (key in cifdata)\n            if(sgdata):\n                skey = key\n                break\n\n        if(not(sgdata)):\n            raise RuntimeError(' No space group information in CIF file! ')\n\n        sgnum = 0\n        if skey is sgkey[0]:\n            sgnum = int(cifdata[sgkey[0]])\n        elif (skey is sgkey[1]):\n            HM = cifdata[sgkey[1]]\n            HM = HM.replace(\" \", \"\")\n            sgnum = HM_to_sgnum[HM]\n        elif (skey is sgkey[2]):\n            hall = cifdata[sgkey[2]]\n            hall = hall.replace(\" \", \"\")\n            sgnum = Hall_to_sgnum[HM]\n        elif(skey is sgkey[3]):\n            sgnum = int(cifdata[sgkey[3]])\n\n        # lattice parameters\n        lparms = []\n        lpkey = ['_cell_length_a', '_cell_length_b', \\\n                 '_cell_length_c', '_cell_angle_alpha', \\\n                 '_cell_angle_beta', '_cell_angle_gamma']\n\n        for key in lpkey:\n            n = cifdata[key].find('(')\n            if(n != -1):\n                lparms.append(float(cifdata[key][:n]))\n            else:\n                lparms.append(float(cifdata[key]))\n\n        for i in range(6):\n                if(i < 3):\n                    lparms[i] = _angstroms(lparms[i])\n                else:\n                    lparms[i] = _degrees(lparms[i])\n\n        self._lparms = lparms\n        self.sgnum   = sgnum\n\n        # fractional atomic site, occ and vibration amplitude\n        fracsitekey = ['_atom_site_fract_x', '_atom_site_fract_y',\\\n                        '_atom_site_fract_z',]\n\n        occ_U       = ['_atom_site_occupancy',\\\n                        '_atom_site_u_iso_or_equiv','_atom_site_U_iso_or_equiv']\n\n        sitedata = True\n        for key in fracsitekey:\n            sitedata = sitedata and (key in cifdata)\n\n        if(not(sitedata)):\n            raise RuntimeError(' fractional site position is not present or incomplete in the CIF file! ')\n\n        atompos = []\n        for key in fracsitekey:\n            slist = cifdata[key]\n            pos = []\n\n            for p in slist:\n                n = p.find('(')\n\n                if(n != -1):\n                    pos.append(p[:n])\n                else:\n                    pos.append(p)\n\n            '''\n            sometimes cif files have negative values so need to\n            bring them back to fractional coordinates between 0-1\n            '''\n            pos = numpy.asarray(pos).astype(numpy.float64)\n            pos,_ = numpy.modf(pos+100.0)\n            atompos.append(pos)\n\n        \"\"\"note that the vibration amplitude, U is just the amplitude (in A)\n            to convert to the typical B which occurs in the debye-waller factor,\n            we will use the following formula\n            B = 8 * pi ^2 * < U_av^2 >\n            this will be done here so we dont have to worry about it later\n        \"\"\"\n\n        pocc = (occ_U[0] in cifdata.keys())\n        pU   = (occ_U[1] in cifdata.keys()) or (occ_U[2] in cifdata.keys())\n\n        if(not pocc):\n            warn('occupation fraction not present. setting it to 1')\n            occ = numpy.ones(atompos[0].shape)\n            atompos.append(occ)\n        else:\n            slist = cifdata[occ_U[0]]\n            occ = []\n            for p in slist:\n                n = p.find('(')\n\n                if(n != -1):\n                    occ.append(p[:n])\n                else:\n                    occ.append(p)\n\n            atompos.append(numpy.asarray(occ).astype(numpy.float64))\n\n        if(not pU):\n            warn('Debye-Waller factors not present. setting to same values for all atoms.')\n            U = 1.0/numpy.pi/2./numpy.sqrt(2.) * numpy.ones(atompos[0].shape)\n            self._U = U\n        else:\n            if(occ_U[1] in cifdata.keys()):\n                k = occ_U[1]\n            else:\n                k = occ_U[2]\n\n            slist = cifdata[k]\n            U = []\n            for p in slist:\n                n = p.find('(')\n\n                if(n != -1):\n                    U.append(p[:n])\n                else:\n                    U.append(p)\n\n            self._U = numpy.asarray(U).astype(numpy.float64)\n        '''\n        format everything in the right shape etc.\n        '''\n        self._atominfo = numpy.asarray(atompos).T\n\n        '''\n        get atome types here i.e. the atomic number of atoms at each site\n        '''\n        atype = '_atom_site_type_symbol'\n        patype = (atype in cifdata)\n        if(not patype):\n            raise RuntimeError('atom types not defined in cif file.')\n\n        satype = cifdata[atype]\n        atomtype = []\n\n        for s in satype:\n            atomtype.append(ptable[s])\n\n        self._atomtype  = numpy.asarray(atomtype).astype(numpy.int32)\n        self._sgsetting = 0\n\n    def _readHDFxtal(self, fhdf=DFLT_NAME, xtal=DFLT_NAME):\n        \"\"\"\n        >> @AUTHOR:     Saransh Singh, Lawrence Livermore National Lab, saransh1@llnl.gov\n        >> @DATE:       10/17/2019 SS 1.0 original\n        >> @DETAILS:    hexrd3 will have real structure factors and will require the overhaul\n                        of the crystallography. In this effort, we will have a HDF file reader.\n                        the file will be the same as the EMsoft xtal file. h5py will be used for\n                        i/o\n        \"\"\"\n\n        fexist = path.exists(fhdf)\n        if(fexist):\n            fid = h5py.File(fhdf, 'r')\n            xtal = \"/\"+xtal\n            if xtal not in fid:\n                raise IOError('crystal doesn''t exist in material file.')\n        else:\n            raise IOError('material file does not exist.')\n\n        gid         = fid.get(xtal)\n\n        sgnum       = numpy.asscalar(numpy.array(gid.get('SpaceGroupNumber'), \\\n                                    dtype = numpy.int32))\n        \"\"\"\n            IMPORTANT NOTE:\n            note that the latice parameters is nm by default\n            hexrd on the other hand uses A as the default units, so we\n            need to be careful and convert it right here, so there is no\n            confusion later on\n        \"\"\"\n        lparms      = list(gid.get('LatticeParameters'))\n\n        for i in range(6):\n            if(i < 3):\n                lparms[i] = _angstroms(lparms[i]*10.0)\n            else:\n                lparms[i] = _degrees(lparms[i])\n\n        self._lparms    = lparms\n        #self._lparms    = self._toSixLP(sgnum, lparms)\n        # fill space group and lattice parameters\n        self.sgnum      = sgnum\n\n        # the U factors are related to B by the relation B = 8pi^2 U\n        self._atominfo  = numpy.transpose(numpy.array(gid.get('AtomData'), dtype = numpy.float64))\n        self._U         = numpy.transpose(numpy.array(gid.get('U'), dtype = numpy.float64))\n\n        # read atom types (by atomic number, Z)\n        self._atomtype = numpy.array(gid.get('Atomtypes'), dtype = numpy.int32)\n        self._atom_ntype = self._atomtype.shape[0]\n\n        self._sgsetting = numpy.asscalar(numpy.array(gid.get('SpaceGroupSetting'), \\\n                                        dtype = numpy.int32))\n\n        fid.close()\n\n    def dump_material(self, filename):\n        '''\n        get the atominfo dictionaary aand the lattice parameters\n        '''\n        AtomInfo = {}\n\n        AtomInfo['file'] = filename\n        AtomInfo['xtalname'] = self.name\n        AtomInfo['xtal_sys'] = xtal_sys_dict[self.unitcell.latticeType.lower()]\n        AtomInfo['Z'] = self.unitcell.atom_type\n        AtomInfo['SG'] = self.unitcell.sgnum\n        AtomInfo['SGsetting'] = self.unitcell.sgsetting\n        AtomInfo['APOS'] = self.unitcell.atom_pos\n        AtomInfo['U'] = self.unitcell.U\n\n        '''\n        lattice parameters\n        '''\n        lat_param = {'a': self.unitcell.a,\n                     'b': self.unitcell.b,\n                     'c': self.unitcell.c,\n                     'alpha': self.unitcell.alpha,\n                     'beta': self.unitcell.beta,\n                     'gamma': self.unitcell.gamma}\n\n        Write2H5File(AtomInfo, lat_param)\n\n    # ============================== API\n    #\n    #  ========== Properties\n    #\n\n    # property:  spaceGroup\n\n    @property\n    def spaceGroup(self):\n        \"\"\"(read only) Space group\"\"\"\n        return self._spaceGroup\n\n    @property\n    def vol(self):\n        return self.unitcell.vol\n\n\n    # property:  sgnum\n\n    def _get_sgnum(self):\n        \"\"\"Get method for sgnum\"\"\"\n        return self._sgnum\n\n    def _set_sgnum(self, v):\n        \"\"\"Set method for sgnum\n        >> @date 08/20/2020 SS removed planedata initialization\n            everytime sgnum is updated singe everything is initialized\n            using unitcell now\n        \"\"\"\n        self._sgnum = v\n\n        # Update the unit cell if there is one\n        if hasattr(self, 'unitcell'):\n            self.unitcell.sgnum = v\n\n    sgnum = property(_get_sgnum, _set_sgnum, None,\n                     \"Space group number\")\n    # property:  beamEnergy\n\n    def _get_beamEnergy(self):\n        \"\"\"Get method for beamEnergy\"\"\"\n        return self._beamEnergy\n\n    def _set_beamEnergy(self, keV):\n        \"\"\"\n        Set method for beamEnergy\n\n        * note that units are assumed to be keV for\n          float arguments.  Also can take a valWUnit\n          instance\n        \"\"\"\n        self._beamEnergy = keV\n        self.planeData.wavelength = keV\n\n        return\n\n    beamEnergy = property(_get_beamEnergy, _set_beamEnergy, None,\n                          \"Beam energy in keV\")\n\n    #>> @date 08/20/2020 removing dependence on hklmax\n    # property:  hklMax\n\n    # def _get_hklMax(self):\n    #     \"\"\"Get method for hklMax\"\"\"\n    #     return self._hklMax\n\n    # def _set_hklMax(self, v):\n    #     \"\"\"Set method for hklMax\"\"\"\n    #     self._hklMax = v\n    #     self._newPdata()  # update planeData\n    #     return\n\n    # hklMax = property(_get_hklMax, _set_hklMax, None,\n    #                   \"Max sum of squares for HKLs\")\n    # property:  planeData\n\n    @property\n    def planeData(self):\n        \"\"\"(read only) Return the planeData attribute (lattice parameters)\"\"\"\n        return self._pData\n\n    # property:  latticeParameters\n\n    def _get_latticeParameters(self):\n        \"\"\"Get method for latticeParameters\"\"\"\n        return self._lparms\n\n    def _set_latticeParameters(self, v):\n        \"\"\"Set method for latticeParameters\"\"\"\n        if(len(v) != 6):\n            v = unitcell._rqpDict[self.unitcell.latticeType][1](v)\n        lp = [_angstroms(v[i]) for i in range(3)]\n        for i in range(3,6):\n            lp.append(_degrees(v[i]))\n        self._lparms = lp\n\n        rq_lp = unitcell._rqpDict[self.unitcell.latticeType][0]\n        for i,vv in enumerate(lp):\n            if(vv.isLength()):\n                val = vv.value / 10.0\n            else:\n                val = vv.value\n            setattr(self.unitcell, unitcell._lpname[i], val)\n        v2 = [lp[x].value for x in rq_lp]\n        self.planeData.lparms = v2\n\n        return\n\n    lpdoc = r\"\"\"Lattice parameters\n\nOn output, all six paramters are returned.\n\nOn input, either all six or a minimal set is accepted.\n\nThe values have units attached, i.e. they are valWunit instances.\n\"\"\"\n    latticeParameters = property(\n            _get_latticeParameters, _set_latticeParameters,\n            None, lpdoc)\n\n    # property:  \"name\"\n\n    def _get_name(self):\n        \"\"\"Set method for name\"\"\"\n        return self._name\n\n    def _set_name(self, v):\n        \"\"\"Set method for name\"\"\"\n        self._name = v\n\n        return\n\n    name = property(_get_name, _set_name, None,\n                    \"Name of material\")\n\n    @property\n    def dmin(self):\n        return self._dmin\n\n    @dmin.setter\n    def dmin(self, v):\n        if self._dmin == v:\n            return\n\n        self._dmin = v\n\n        # Update the unit cell\n        self.unitcell.dmin = v.getVal('nm')\n\n        self._newPdata()\n        self.update_structure_factor()\n\n    # property: \"atominfo\"\n    def _get_atominfo(self):\n        \"\"\"Set method for name\"\"\"\n        return self._atominfo\n\n    def _set_atominfo(self, v):\n        \"\"\"Set method for name\"\"\"\n        if v.shape[1] == 4:\n            self._atominfo = v\n        else:\n            print(\"Improper syntax, array must be n x 4\")\n\n        return\n\n    atominfo = property(\n        _get_atominfo, _set_atominfo, None,\n        \"Information about atomic positions and electron number\")\n\n    #\n    #  ========== Methods\n    #\n    #\n    pass  # end class\n\n\n#\n#  -----------------------------------------------END CLASS:  Material\n#\n#  Utility Functions\n#\n\n\ndef loadMaterialList(cfgFile):\n    \"\"\"Load a list of materials from a file\n\n    The file uses the config file format.  See ConfigParser module.\n\"\"\"\n    p = Parser()\n    p.read(cfgFile)\n    #\n    #  Each section defines a material\n    #\n    names = p.sections()\n    matList = [Material(n, p) for n in names]\n    # Sort the list\n    matList = sorted(matList, key=_key)\n\n    return matList\n\n\ndef load_materials_hdf5(f, dmin=Material.DFLT_DMIN, kev=Material.DFLT_KEV,\n                        sgsetting=Material.DFLT_SGSETTING):\n    \"\"\"Load materials from an HDF5 file\n\n    The file uses the HDF5 file format.\n    \"\"\"\n    with h5py.File(f, 'r') as rf:\n        names = list(rf)\n\n    return {\n        name: Material(name, f, dmin=dmin, kev=kev, sgsetting=sgsetting)\n        for name in names\n    }\n\n\ndef save_materials_hdf5(f, materials):\n    \"\"\"Save a dict of materials into an HDF5 file\"\"\"\n    for material in materials.values():\n        material.dump_material(f)\n\n#\n#  ============================== Executable section for testing\n#\n\n\nif __name__ == '__main__':\n    #\n    #  For testing\n    #\n    import sys\n\n    if len(sys.argv) == 1:\n        print(\"need argument:  materials.cfg\")\n        sys.exit()\n        pass\n\n    ml = loadMaterialList(sys.argv[1])\n\n    print('MATERIAL LIST\\n')\n    print(('   from file:  ', sys.argv[1]))\n    for m in ml:\n        print(m)\n        pass\n    pass\n", "meta": {"hexsha": "7dc0291cb947990ec93dc8d73c8bd3ca7855897d", "size": 22817, "ext": "py", "lang": "Python", "max_stars_repo_path": "hexrd/material.py", "max_stars_repo_name": "rachelelim/hexrd-1", "max_stars_repo_head_hexsha": "2fbd5a8804e7443c60e17efef0a7350e53487885", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hexrd/material.py", "max_issues_repo_name": "rachelelim/hexrd-1", "max_issues_repo_head_hexsha": "2fbd5a8804e7443c60e17efef0a7350e53487885", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hexrd/material.py", "max_forks_repo_name": "rachelelim/hexrd-1", "max_forks_repo_head_hexsha": "2fbd5a8804e7443c60e17efef0a7350e53487885", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8337837838, "max_line_length": 110, "alphanum_fraction": 0.5596265942, "include": true, "reason": "import numpy", "num_tokens": 5675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.33458942798284697, "lm_q1q2_score": 0.17513091514518683}}
{"text": "# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\nimport numpy as np\nimport autograd.numpy as anp\nfrom autograd import grad\nfrom typing import Tuple, Dict, List, Optional\nfrom numpy.random import RandomState\nimport logging\n\nfrom syne_tune.optimizer.schedulers.searchers.bayesopt.gpautograd.kernel \\\n    import KernelFunction\nfrom syne_tune.optimizer.schedulers.searchers.bayesopt.gpautograd.mean \\\n    import MeanFunction\nfrom syne_tune.optimizer.schedulers.searchers.bayesopt.gpautograd.learncurve.issm \\\n    import issm_likelihood_slow_computations, posterior_computations, \\\n    sample_posterior_marginals, _inner_product, issm_likelihood_computations, \\\n    issm_likelihood_precomputations, decode_features, _rowvec, \\\n    update_posterior_state, update_posterior_pvec, _flatvec, _colvec\nfrom syne_tune.optimizer.schedulers.searchers.bayesopt.gpautograd.learncurve.issm \\\n    import sample_posterior_joint as sample_posterior_joint_issm, \\\n    predict_posterior_marginals_extended as predict_posterior_marginals_issm\nfrom syne_tune.optimizer.schedulers.searchers.bayesopt.gpautograd.learncurve.freeze_thaw \\\n    import sample_posterior_joint as sample_posterior_joint_expdecay, \\\n    predict_posterior_marginals_extended as predict_posterior_marginals_expdecay\nfrom syne_tune.optimizer.schedulers.searchers.bayesopt.gpautograd.learncurve.model_params \\\n    import ISSModelParameters\nfrom syne_tune.optimizer.schedulers.searchers.bayesopt.gpautograd.learncurve.freeze_thaw \\\n    import resource_kernel_likelihood_slow_computations, \\\n    ExponentialDecayBaseKernelFunction, logdet_cholfact_cov_resource, \\\n    resource_kernel_likelihood_computations, \\\n    resource_kernel_likelihood_precomputations\nfrom syne_tune.optimizer.schedulers.searchers.bayesopt.datatypes.common \\\n    import Configuration\n\nlogger = logging.getLogger(__name__)\n\n__all__ = ['GaussProcAdditivePosteriorState',\n           'IncrementalUpdateGPAdditivePosteriorState',\n           'GaussProcISSMPosteriorState',\n           'GaussProcExpDecayPosteriorState']\n\n\nclass GaussProcAdditivePosteriorState(object):\n    \"\"\"\n    Represent posterior state for joint Gaussian model of learning curves over\n    a number of configurations. The (additive) model is the sum of a Gaussian\n    process model for function values at r_max and independent Gaussian models\n    over r only.\n\n    Importantly, inference scales cubically only in the number of\n    configurations, not in the number of observations.\n\n    \"\"\"\n\n    def __init__(\n            self, data: Optional[Dict], mean: MeanFunction,\n            kernel: KernelFunction, noise_variance, **kwargs):\n        \"\"\"\n        `data` contains input points and targets, as obtained from\n        `issm.prepare_data`. `iss_model` maintains the ISSM parameters.\n\n        :param data: Input points and targets\n        :param mean: Mean function m(X)\n        :param kernel: Kernel function k(X, X')\n        :param noise_variance: Noise variance\n        \"\"\"\n        self.mean = mean\n        self.kernel = kernel\n        self.noise_variance = noise_variance\n        self.poster_state = None\n        if data is not None:\n            self.r_min = data['r_min']\n            self.r_max = data['r_max']\n            # Compute posterior state\n            self._compute_posterior_state(data, noise_variance, **kwargs)\n        else:\n            # Copy constructor, used by `IncrementalUpdateGPISSMPosteriorState`\n            # subclass\n            self.poster_state = kwargs['poster_state']\n            self.r_min = kwargs['r_min']\n            self.r_max = kwargs['r_max']\n\n    def _compute_posterior_state(\n            self, data: Dict, noise_variance, **kwargs):\n        raise NotImplementedError()\n\n    def neg_log_likelihood(self):\n        assert 'criterion' in self.poster_state, \\\n            \"neg_log_likelihood not defined for fantasizing posterior state\"\n        return self.poster_state['criterion']\n\n    def predict(\n            self, test_features: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n        \"\"\"\n        We compute marginals over f(x, r), where `test_features` are extended\n        features.\n        Note: The test configs must not overlap with any in the training set.\n        Otherwise, at least if `r != r_max`, the predictive distributions\n        computed here may be wrong.\n\n        :param test_features: Extended features for test configs\n        :return: posterior_means, posterior_variances\n        \"\"\"\n        raise NotImplementedError()\n\n    def sample_marginals(\n            self, test_features: np.ndarray, num_samples: int = 1,\n            random_state: Optional[RandomState] = None) -> np.ndarray:\n        \"\"\"\n        See comments of `predict`.\n\n        :param test_features: Input points for test configs\n        :param num_samples: Number of samples\n        :param random_state: PRNG\n        :return: Marginal samples, (num_test, num_samples)\n        \"\"\"\n        if random_state is None:\n            random_state = np.random\n        return sample_posterior_marginals(\n            self.poster_state, self.mean, self.kernel, test_features,\n            random_state=random_state, num_samples=num_samples)\n\n    def backward_gradient(\n            self, input: np.ndarray,\n            head_gradients: Dict[str, np.ndarray],\n            mean_data: float, std_data: float) -> np.ndarray:\n        \"\"\"\n        Implements SurrogateModel.backward_gradient, see comments there.\n        This is for a single posterior state. If the SurrogateModel uses\n        MCMC, have to call this for every sample.\n\n        :param input: Single input point x, shape (d,)\n        :param head_gradients: See SurrogateModel.backward_gradient\n        :param mean_data: Mean used to normalize targets\n        :param std_data: Stddev used to normalize targets\n        :return:\n        \"\"\"\n        test_feature = np.reshape(input, (1, -1))\n\n        def diff_test_feature(test_feature_array):\n            norm_mean, norm_variance = self.predict(test_feature_array)\n            # De-normalize, and variance -> stddev\n            pred_mean = norm_mean * std_data + mean_data\n            pred_std = anp.sqrt(norm_variance) * std_data\n            head_gradients_mean = anp.reshape(head_gradients['mean'], pred_mean.shape)\n            head_gradients_std = anp.reshape(head_gradients['std'], pred_std.shape)\n            # Added to mimic mxnet.autograd.backward\n            pred_mean_sum = _inner_product(pred_mean, head_gradients_mean)\n            pred_std_sum = _inner_product(pred_std, head_gradients_std)\n            return pred_mean_sum + pred_std_sum\n\n        test_feature_gradient = grad(diff_test_feature)\n        return np.reshape(test_feature_gradient(test_feature), input.shape)\n\n    def _sample_curves_internal(\n            self, data: Dict, poster_state: Dict, num_samples: int = 1,\n            random_state: Optional[RandomState] = None) -> List[Dict]:\n        raise NotImplementedError()\n\n    def sample_curves(\n            self, data: Dict, num_samples: int = 1,\n            random_state: Optional[RandomState] = None) -> List[Dict]:\n        \"\"\"\n        Given data from one or more configurations (as returned by\n        `issm.prepare_data`), for each config, sample a curve from the\n        joint posterior (predictive) distribution over latent targets.\n        The curve for each config in `data` may be partly observed, but\n        must not be fully observed. Samples for the different configs are\n        independent. None of the configs in `data` must appear in the dataset\n        used to compute the posterior state.\n\n        The result is a list of Dict, one for each config. If for a config,\n        targets in `data` are given for resource values range(r_min, r_obs),\n        the dict entry `y` is a joint sample [y_r], r in range(r_obs, r_max+1).\n        For some subclasses (e.g., ISSM), there is also an entry `f` with a\n        joint sample [f_r], r in range(r_obs-1, r_max+1), the latent function\n        values before noise. These entries are matrices with `num_samples`\n        columns, which are independent (the joint dependence is along the rows).\n\n        :param data: Data for configs to predict at\n        :param num_samples: Number of samples to draw from each curve\n        :param random_state: PRNG state to be used for sampling\n        :return: See above\n        \"\"\"\n        return self._sample_curves_internal(\n            data=data, poster_state=self.poster_state, num_samples=num_samples,\n            random_state=random_state)\n\n    def has_precomputations(self, data: Dict) -> bool:\n        raise NotImplementedError()\n\n\nclass IncrementalUpdateGPAdditivePosteriorState(GaussProcAdditivePosteriorState):\n    \"\"\"\n    Extension of :class:`GaussProcAdditivePosteriorState` which allows for\n    incremental updating (single config added to the dataset).\n    This is required for simulation-based scoring, and for support of\n    fantasizing.\n\n    \"\"\"\n    def __init__(\n            self, data: Optional[Dict], mean: MeanFunction,\n            kernel: KernelFunction, noise_variance, **kwargs):\n        super().__init__(\n            data, mean, kernel, noise_variance, **kwargs)\n\n    def _prepare_update(\n            self, feature: np.ndarray, targets: np.ndarray) \\\n            -> Tuple[float, float, float]:\n        \"\"\"\n        Helper method for `update`. Returns new entries for d, s, r2 vectors.\n\n        :param feature: See `update`\n        :param targets: See `update`\n        :return: (d_new, s_new, r2_new)\n        \"\"\"\n        raise NotImplementedError()\n\n    def _update_internal(\n            self, feature: np.ndarray, targets: np.ndarray) -> Dict:\n        \"\"\"\n        Update posterior state, given a single new datapoint. `feature`,\n        `targets` are like one entry of `data`. The method returns a new\n        object with the updated state.\n\n        :param feature: See above\n        :param targets: See above\n        :return: Arguments to create new posterior state\n        \"\"\"\n        # Update posterior state\n        feature = _rowvec(feature, _np=np)\n        d_new, s_new, r2_new = self._prepare_update(feature, targets)\n        new_poster_state = update_posterior_state(\n            self.poster_state, self.kernel, feature, d_new, s_new, r2_new)\n        # Return args to create new object by way of \"copy constructor\"\n        return dict(\n            data=None,\n            mean=self.mean,\n            kernel=self.kernel,\n            noise_variance=self.noise_variance,\n            poster_state=new_poster_state,\n            r_min=self.r_min, r_max=self.r_max)\n\n    def update(\n            self, feature: np.ndarray, targets: np.ndarray) \\\n            -> 'IncrementalUpdateGPAdditivePosteriorState':\n        raise NotImplementedError()\n\n    def update_pvec(\n            self, feature: np.ndarray, targets: np.ndarray) -> np.ndarray:\n        \"\"\"\n        Part of `update`: Only update prediction vector p. This cannot be used\n        to update p for several new datapoints.\n\n        :param feature:\n        :param targets:\n        :return: New p vector\n        \"\"\"\n        feature = _rowvec(feature, _np=np)\n        d_new, s_new, r2_new = self._prepare_update(feature, targets)\n        return update_posterior_pvec(\n            self.poster_state, self.kernel, feature, d_new, s_new, r2_new)\n\n    def _sample_posterior_joint_for_config(\n            self, poster_state: Dict, config: Configuration, feature: np.ndarray,\n            targets: np.ndarray, random_state: RandomState) -> np.ndarray:\n        data = {'features': [feature],\n                'targets': [targets],\n                'configs': [config]}\n        results = self._sample_curves_internal(\n            data, poster_state, num_samples=1, random_state=random_state)\n        return results[0]['y']\n\n    def sample_and_update_for_pending(\n            self, data_pending: Dict, sample_all_nonobserved: bool = False,\n            random_state: Optional[RandomState] = None) \\\n            -> (List[np.ndarray], 'IncrementalUpdateGPAdditivePosteriorState'):\n        \"\"\"\n        This function is needed for sampling fantasy targets, and also to\n        support simulation-based scoring.\n\n        `issm.prepare_data_with_pending` creates two data dicts `data_nopending`,\n        `data_pending`, the first for configs with observed data, but no\n        pending evals, the second for configs with pending evals.\n        You create the state with `data_nopending`, then call this method with\n        `data_pending`.\n\n        This method is iterating over configs (or trials) in `data_pending`.\n        For each config, it draws a joint sample from some non-observed\n        targets, then updates the state conditioned on observed and sampled\n        targets (by calling `update`). If `sample_all_nonobserved` is False,\n        the number of targets sampled is the entry in\n        `data_pending['num_pending']`. Otherwise, targets are sampled for all\n        non-observed positions.\n\n        The method returns the list of sampled target vectors, and the state\n        at the end (like `update` does as well).\n\n        :param data_pending: See above\n        :param sample_all_nonobserved: See above\n        :param random_state: PRNG\n        :return: pending_targets, final_state\n        \"\"\"\n        if random_state is None:\n            random_state = np.random\n        curr_poster_state = self.poster_state\n        targets_lst = []\n        final_state = self\n        for config, feature, targets, num_pending in zip(\n                data_pending['configs'], data_pending['features'],\n                data_pending['targets'], data_pending['num_pending']):\n            # Draw joint sample\n            fantasies = _flatvec(self._sample_posterior_joint_for_config(\n                curr_poster_state, config, feature, targets, random_state),\n                _np=np)\n            if not sample_all_nonobserved:\n                fantasies = fantasies[:num_pending]\n            fantasies = _colvec(fantasies, _np=np)\n            targets_lst.append(fantasies)\n            # Update state\n            full_targets = np.vstack((targets, fantasies))\n            final_state = self.update(feature, full_targets)\n            curr_poster_state = final_state.poster_state\n        return targets_lst, final_state\n\n\nclass GaussProcISSMPosteriorState(IncrementalUpdateGPAdditivePosteriorState):\n    \"\"\"\n    Represent posterior state for joint Gaussian model of learning curves over\n    a number of configurations. The model is the sum of a Gaussian process\n    model for function values at r_max and independent Gaussian linear\n    innovation state space models (ISSMs) of a particular power law decay\n    form.\n\n    \"\"\"\n    def __init__(\n            self, data: Optional[Dict], mean: MeanFunction,\n            kernel: KernelFunction, iss_model: ISSModelParameters,\n            noise_variance, **kwargs):\n        \"\"\"\n        `data` contains input points and targets, as obtained from\n        `issm.prepare_data`. `iss_model` maintains the ISSM parameters.\n\n        :param data: Input points and targets\n        :param mean: Mean function m(X)\n        :param kernel: Kernel function k(X, X')\n        :param iss_model: ISS model\n        :param noise_variance: Innovation and noise variance\n        \"\"\"\n        self.iss_model = iss_model\n        super().__init__(\n            data, mean, kernel, noise_variance=noise_variance, **kwargs)\n\n    def has_precomputations(self, data: Dict) -> bool:\n        return all(k in data for k in ('ydims', 'num_configs', 'deltay', 'logr'))\n\n    def _compute_posterior_state(\n            self, data: Dict, noise_variance, **kwargs):\n        profiler = kwargs.get('profiler')\n        # Compute posterior state\n        issm_params = self.iss_model.get_issm_params(data['features'])\n        if self.has_precomputations(data):\n            issm_likelihood = issm_likelihood_computations(\n                precomputed=data,\n                issm_params=issm_params,\n                r_min=self.r_min, r_max=self.r_max,\n                profiler=profiler)\n        else:\n            issm_likelihood = issm_likelihood_slow_computations(\n                targets=data['targets'],\n                issm_params=issm_params,\n                r_min=self.r_min, r_max=self.r_max,\n                profiler=profiler)\n        if profiler is not None:\n            profiler.start('poster_comp')\n        self.poster_state = posterior_computations(\n            features=data['features'],\n            mean=self.mean, kernel=self.kernel,\n            issm_likelihood=issm_likelihood,\n            noise_variance=noise_variance)\n        if profiler is not None:\n            profiler.stop('poster_comp')\n\n    def predict(\n            self, test_features: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n        resource_attr_range = (self.r_min, self.r_max)\n        features, resources = decode_features(\n            test_features, resource_attr_range=resource_attr_range)\n        issm_params = self.iss_model.get_issm_params(features)\n        return predict_posterior_marginals_issm(\n            poster_state=self.poster_state,\n            mean=self.mean,\n            kernel=self.kernel,\n            test_features=features,\n            resources=resources,\n            issm_params=issm_params,\n            r_min=self.r_min, r_max=self.r_max)\n\n    @staticmethod\n    def data_precomputations(data: Dict):\n        logger.info(\"Enhancing data dictionary by precomputed variables\")\n        data.update(issm_likelihood_precomputations(\n            targets=data['targets'], r_min=data['r_min']))\n\n    def _sample_curves_internal(\n            self, data: Dict, poster_state: Dict, num_samples: int = 1,\n            random_state: Optional[RandomState] = None) -> List[Dict]:\n        if random_state is None:\n            random_state = np.random\n        results = []\n        for feature, targets, config in zip(\n                data['features'], data['targets'], data['configs']):\n            issm_params = self.iss_model.get_issm_params(\n                feature.reshape((1, -1)))\n            results.append(sample_posterior_joint_issm(\n                poster_state=poster_state,\n                mean=self.mean,\n                kernel=self.kernel,\n                feature=feature,\n                targets=targets,\n                issm_params=issm_params,\n                r_min=self.r_min, r_max=self.r_max,\n                random_state=random_state,\n                num_samples=num_samples))\n        return results\n\n    def _prepare_update(\n            self, feature: np.ndarray, targets: np.ndarray) \\\n            -> Tuple[float, float, float]:\n        issm_params = self.iss_model.get_issm_params(feature.reshape((1, -1)))\n        issm_likelihood = issm_likelihood_slow_computations(\n            targets=[_colvec(targets, _np=np)],\n            issm_params=issm_params,\n            r_min=self.r_min, r_max=self.r_max)\n        d_new = issm_likelihood['d'].item()\n        vtv = issm_likelihood['vtv'].item()\n        wtv = issm_likelihood['wtv'].item()\n        s_sq = vtv / self.noise_variance\n        s_new = np.sqrt(s_sq)\n        muhat = _flatvec(self.mean(feature)).item() - issm_likelihood['c'].item()\n        r2_new = wtv / self.noise_variance - s_sq * muhat\n        return d_new, s_new, r2_new\n\n    def update(\n            self, feature: np.ndarray, targets: np.ndarray) \\\n            -> 'IncrementalUpdateGPAdditivePosteriorState':\n        create_kwargs = self._update_internal(feature, targets)\n        return GaussProcISSMPosteriorState(\n            **create_kwargs, iss_model=self.iss_model)\n\n\nclass GaussProcExpDecayPosteriorState(IncrementalUpdateGPAdditivePosteriorState):\n    \"\"\"\n    Represent posterior state for joint Gaussian model of learning curves over\n    a number of configurations. The model is the sum of a Gaussian process\n    model for function values at r_max and independent Gaussian processes over\n    r, using an exponential decay covariance function. The latter is shared\n    between all configs.\n\n    This is essentially the model from the Freeze Thaw paper (see also\n    :class:`ExponentialDecayResourcesKernelFunction`).\n\n    \"\"\"\n    def __init__(\n            self, data: Optional[Dict],\n            mean: MeanFunction,\n            kernel: KernelFunction,\n            res_kernel: ExponentialDecayBaseKernelFunction,\n            noise_variance, **kwargs):\n        \"\"\"\n        `data` contains input points and targets, as obtained from\n        `issm.prepare_data`.\n\n        :param data: Input points and targets\n        :param mean: Mean function m(X)\n        :param kernel: Kernel function k(X, X')\n        :param res_kernel: Kernel function k_r(r, r'), of exponential decay\n            type\n        :param noise_variance: Innovation and noise variance\n        \"\"\"\n        self.res_kernel = res_kernel\n        super().__init__(\n            data, mean, kernel, noise_variance=noise_variance, **kwargs)\n        assert self.r_min == res_kernel.r_min and self.r_max == res_kernel.r_max, \\\n            ((self.r_min, self.r_max), (res_kernel.r_min, res_kernel.r_max))\n\n    def has_precomputations(self, data: Dict) -> bool:\n        return all(k in data for k in ('ydims', 'num_configs', 'yflat'))\n\n    def _compute_posterior_state(\n            self, data: Dict, noise_variance, **kwargs):\n        profiler = kwargs.get('profiler')\n        # Compute posterior state\n        if profiler is not None:\n            profiler.start('likelihood')\n        if self.has_precomputations(data):\n            issm_likelihood = resource_kernel_likelihood_computations(\n                precomputed=data,\n                res_kernel=self.res_kernel,\n                noise_variance=noise_variance)\n        else:\n            issm_likelihood = resource_kernel_likelihood_slow_computations(\n                targets=data['targets'],\n                res_kernel=self.res_kernel,\n                noise_variance=noise_variance)\n        if profiler is not None:\n            profiler.stop('likelihood')\n            profiler.start('poster_comp')\n        self.poster_state = posterior_computations(\n            features=data['features'],\n            mean=self.mean, kernel=self.kernel,\n            issm_likelihood=issm_likelihood,\n            noise_variance=noise_variance)\n        if profiler is not None:\n            profiler.stop('poster_comp')\n        # Add missing term to criterion value\n        if 'criterion' in self.poster_state:\n            part3 = logdet_cholfact_cov_resource(issm_likelihood)\n            self.poster_state['criterion'] += part3\n        # Extra terms required in `sample_curves`\n        self.poster_state['lfact_all'] = issm_likelihood['lfact_all']\n        self.poster_state['means_all'] = issm_likelihood['means_all']\n        self.poster_state['noise_variance'] = noise_variance\n\n    def predict(\n            self, test_features: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n        resource_attr_range = (self.r_min, self.r_max)\n        features, resources = decode_features(\n            test_features, resource_attr_range=resource_attr_range)\n        return predict_posterior_marginals_expdecay(\n            poster_state=self.poster_state,\n            mean=self.mean,\n            kernel=self.kernel,\n            test_features=features,\n            resources=resources,\n            res_kernel=self.res_kernel)\n\n    @staticmethod\n    def data_precomputations(data: Dict):\n        data.update(resource_kernel_likelihood_precomputations(\n            targets=data['targets']))\n\n    def _sample_curves_internal(\n            self, data: Dict, poster_state: Dict, num_samples: int = 1,\n            random_state: Optional[RandomState] = None) -> List[Dict]:\n        assert 'lfact_all' in poster_state\n        if random_state is None:\n            random_state = np.random\n        lfact_all = poster_state['lfact_all']\n        means_all = poster_state['means_all']\n        noise_variance = poster_state['noise_variance']\n        results = []\n        for feature, targets in zip(data['features'], data['targets']):\n            results.append(sample_posterior_joint_expdecay(\n                poster_state=poster_state,\n                mean=self.mean,\n                kernel=self.kernel,\n                feature=feature,\n                targets=targets,\n                res_kernel=self.res_kernel,\n                noise_variance=noise_variance,\n                lfact_all=lfact_all,\n                means_all=means_all,\n                random_state=random_state,\n                num_samples=num_samples))\n        return results\n\n    def _prepare_update(\n            self, feature: np.ndarray, targets: np.ndarray) \\\n            -> Tuple[float, float, float]:\n        issm_likelihood = resource_kernel_likelihood_slow_computations(\n            targets=[_colvec(targets, _np=np)],\n            res_kernel=self.res_kernel,\n            noise_variance=self.noise_variance)\n        vtv = issm_likelihood['vtv'].item()\n        wtv = issm_likelihood['wtv'].item()\n        s_sq = vtv / self.noise_variance\n        s_new = np.sqrt(s_sq)\n        muhat = _flatvec(self.mean(feature)).item()\n        r2_new = wtv / self.noise_variance - s_sq * muhat\n        return 0.0, s_new, r2_new\n\n    def update(\n            self, feature: np.ndarray, targets: np.ndarray) \\\n            -> 'IncrementalUpdateGPAdditivePosteriorState':\n        create_kwargs = self._update_internal(feature, targets)\n        # Extra terms required in `sample_curves`\n        new_poster_state = create_kwargs['poster_state']\n        for k in ('lfact_all', 'means_all', 'noise_variance'):\n            new_poster_state[k] = self.poster_state[k]\n        return GaussProcExpDecayPosteriorState(\n            **create_kwargs, res_kernel=self.res_kernel)\n", "meta": {"hexsha": "6a89215a8203d754661c6b5ab154d9dfba9e0ec2", "size": 26096, "ext": "py", "lang": "Python", "max_stars_repo_path": "syne_tune/optimizer/schedulers/searchers/bayesopt/gpautograd/learncurve/posterior_state.py", "max_stars_repo_name": "hfurkanbozkurt/syne-tune", "max_stars_repo_head_hexsha": "05ee2668f0155b40c3ee3b61e4b3d58f3f9f3c4f", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "syne_tune/optimizer/schedulers/searchers/bayesopt/gpautograd/learncurve/posterior_state.py", "max_issues_repo_name": "hfurkanbozkurt/syne-tune", "max_issues_repo_head_hexsha": "05ee2668f0155b40c3ee3b61e4b3d58f3f9f3c4f", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-25T15:56:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T17:53:10.000Z", "max_forks_repo_path": "syne_tune/optimizer/schedulers/searchers/bayesopt/gpautograd/learncurve/posterior_state.py", "max_forks_repo_name": "hfurkanbozkurt/syne-tune", "max_forks_repo_head_hexsha": "05ee2668f0155b40c3ee3b61e4b3d58f3f9f3c4f", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.2769485904, "max_line_length": 91, "alphanum_fraction": 0.6549279583, "include": true, "reason": "import numpy,from numpy", "num_tokens": 5660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.17513091017035481}}
{"text": "from collections import namedtuple\nimport numpy as np\n\"\"\"\nTemplates for amino acidic residues\n\"\"\"\n\nAA_info = namedtuple('AA_info', 'coords atom_names bonds bb sc offset')\n\nA_info = AA_info(coords=np.array([[-0.75, -1.26, -0.51],\n                                  [-0.04,  0.03, -0.48],\n                                  [1.47, -0.14, -0.46],\n                                  [2.04, -1.21, -0.48],\n                                  [-0.5,  0.86,  0.73],\n                                  [-0.07, -2.02, -0.5],\n                                  [-0.27,  0.58, -1.4],\n                                  [-1.59,  1.01,  0.69],\n                                  [-0.26,  0.35,  1.66],\n                                  [-0.02,  1.84,  0.74]]),\n                 atom_names=['N', 'CA', 'C', 'O', 'CB',\n                             'H', 'HA', 'HB1', 'HB2', 'HB3'],\n                 bb=[0, 1, 2, 3, 5, 6],\n                 sc=[4, 7, 8, 9],\n                 bonds=[(0, 1), (0, 5), (1, 2), (1, 4), (1, 6),\n                        (2, 3), (4, 7), (4, 8), (4, 9)],\n                 offset=10)\n\nR_info = AA_info(coords=np.array([[-0.07, -3.66,  2.53],\n                                  [0.51, -2.96,  1.34],\n                                  [2.04, -2.96,  1.38],\n                                  [2.67, -3.46,  2.27],\n                                  [-0.07, -1.52,  1.29],\n                                  [0.2, -0.77, -0.05],\n                                  [-0.38,  0.65, -0.],\n                                  [-0.14,  1.37, -1.3],\n                                  [-0.49,  2.57, -1.61],\n                                  [-1.11,  3.37, -0.79],\n                                  [-0.21,  3.05, -2.81],\n                                  [0.61, -4.02,  3.2],\n                                  [0.22, -3.52,  0.45],\n                                  [0.34, -0.95,  2.13],\n                                  [-1.15, -1.57,  1.45],\n                                  [-0.25, -1.33, -0.88],\n                                  [1.27, -0.71, -0.25],\n                                  [0.08,  1.22,  0.81],\n                                  [-1.45,  0.62,  0.2],\n                                  [0.34,  0.81, -2.],\n                                  [-1.35,  3.05,  0.16],\n                                  [-1.39,  4.32, -1.01],\n                                  [0.28,  2.45, -3.46],\n                                  [-0.48,  4.01, -3.04]]),\n                 atom_names=['N', 'CA', 'C', 'O', 'CB', 'CG', 'CD', 'NE', 'CZ', 'NH1', 'NH2', 'H', 'HA',\n                             'HB2', 'HB3', 'HG2', 'HG3', 'HD2', 'HD3', 'HE', 'HH11', 'HH12', 'HH21', 'HH22'],\n                 bb=[0, 1, 2, 3, 11, 12],\n                 sc=[4, 5, 6, 7, 8, 9, 10, 13, 14, 15,\n                     16, 17, 18, 19, 20, 21, 22, 23],\n                 bonds=[(0, 1), (0, 11), (1, 2), (1, 4), (1, 12), (2, 3), (4, 5), (4, 13), (4, 14), (5, 6), (5, 15), (5, 16),\n                        (6, 7), (6, 17), (6, 18), (7, 8), (7, 19), (8, 9), (8, 10), (9, 20), (9, 21), (10, 22), (10, 23)],\n                 offset=24)\n\nN_info = AA_info(coords=np.array([[0.15, -1.78, -0.63],\n                                  [0.76, -0.44, -0.59],\n                                  [2.28, -0.5, -0.63],\n                                  [2.93, -1.53, -0.6],\n                                  [0.3,  0.37,  0.64],\n                                  [-1.21,  0.48,  0.76],\n                                  [-1.84,  1.38, -0.01],\n                                  [-1.85, -0.21,  1.53],\n                                  [0.87, -2.5, -0.61],\n                                  [0.47,  0.1, -1.5],\n                                  [0.73,  1.37,  0.61],\n                                  [0.68, -0.11,  1.55],\n                                  [-2.85,  1.45,  0.04],\n                                  [-1.33,  1.96, -0.66]]),\n                 atom_names=['N', 'CA', 'C', 'O', 'CB', 'CG', 'ND2',\n                             'OD1', 'H', 'HA', 'HB2', 'HB3', 'HD21', 'HD22'],\n                 bb=[0, 1, 2, 3, 8, 9],\n                 sc=[4, 5, 6, 7, 10, 11, 12, 13],\n                 bonds=[(0, 1), (0, 8), (1, 2), (1, 4), (1, 9), (2, 3), (4, 5),\n                        (4, 10), (4, 11), (5, 6), (5, 7), (6, 12), (6, 13)],\n                 offset=14)\n\nD_info = AA_info(coords=np.array([[-0.67, -1.84, -0.63],\n                                  [-0.06, -0.49, -0.62],\n                                  [1.46, -0.53, -0.62],\n                                  [2.11, -1.56, -0.64],\n                                  [-0.58,  0.33,  0.59],\n                                  [-0.08,  1.77,  0.62],\n                                  [-0.,  2.38, -0.43],\n                                  [0.17,  2.25,  1.71],\n                                  [0.06, -2.55, -0.64],\n                                  [-0.34,  0.03, -1.54],\n                                  [-0.29, -0.16,  1.51],\n                                  [-1.67,  0.36,  0.56]]),\n                 atom_names=['N', 'CA', 'C', 'O', 'CB', 'CG',\n                             'OD1', 'OD2', 'H', 'HA', 'HB2', 'HB3'],\n                 bb=[0, 1, 2, 3, 8, 9],\n                 sc=[4, 5, 6, 7, 10, 11],\n                 bonds=[(0, 1), (0, 8), (1, 2), (1, 4), (1, 9), (2, 3),\n                        (4, 5), (4, 10), (4, 11), (5, 6), (5, 7)],\n                 offset=12)\n\nC_info = AA_info(coords=np.array([[-0.72, -1.62, -0.64],\n                                  [-0.12, -0.27, -0.64],\n                                  [1.39, -0.31, -0.63],\n                                  [2.05, -1.33, -0.62],\n                                  [-0.67,  0.53,  0.56],\n                                  [-0.17,  2.29,  0.55],\n                                  [0.01, -2.32, -0.65],\n                                  [-0.41,  0.24, -1.56],\n                                  [-0.32,  0.08,  1.5],\n                                  [-1.76,  0.5,  0.54],\n                                  [0.79,  2.19,  1.49]]),\n                 atom_names=['N', 'CA', 'C', 'O', 'CB',\n                             'SG', 'H', 'HA', 'HB2', 'HB3', 'HG'],\n                 bb=[0, 1, 2, 3, 6, 7],\n                 sc=[4, 5, 8, 9, 10],\n                 bonds=[(0, 1), (0, 6), (1, 2), (1, 4), (1, 7),\n                        (2, 3), (4, 5), (4, 8), (4, 9), (5, 10)],\n                 offset=11)\n\nE_info = AA_info(coords=np.array([[-0.55, -2.38, -1.05],\n                                  [0.04, -1.01, -1.02],\n                                  [1.56, -1.05, -1.05],\n                                  [2.19, -2.09, -1.05],\n                                  [-0.48, -0.21,  0.21],\n                                  [0.01,  1.27,  0.29],\n                                  [-0.41,  2.11,  1.49],\n                                  [-1.17,  1.52,  2.39],\n                                  [-0.01,  3.23,  1.6],\n                                  [0.12, -3.15, -1.04],\n                                  [-0.26, -0.48, -1.95],\n                                  [-0.18, -0.74,  1.12],\n                                  [-1.58, -0.22,  0.2],\n                                  [-0.31,  1.83, -0.58],\n                                  [1.1,  1.31,  0.31]]),\n                 atom_names=['N', 'CA', 'C', 'O', 'CB', 'CG', 'CD',\n                             'OE1', 'OE2', 'H', 'HA', 'HB2', 'HB3', 'HG2', 'HG3'],\n                 bb=[0, 1, 2, 3, 9, 10],\n                 sc=[4, 5, 6, 7, 8, 11, 12, 13, 14],\n                 bonds=[(0, 1), (0, 9), (1, 2), (1, 4), (1, 10), (2, 3), (4, 5),\n                        (4, 11), (4, 12), (5, 6), (5, 13), (5, 14), (6, 7), (6, 8)],\n                 offset=15)\n\nQ_info = AA_info(coords=np.array([[-0.39, -2.48, -1.42],\n                                  [0.22, -1.13, -1.37],\n                                  [1.74, -1.19, -1.41],\n                                  [2.39, -2.22, -1.38],\n                                  [-0.29, -0.37, -0.12],\n                                  [0.19,  1.11, -0.04],\n                                  [-0.26,  1.91,  1.18],\n                                  [-1.02,  1.3,  2.12],\n                                  [0.09,  3.06,  1.34],\n                                  [0.33, -3.2, -1.4],\n                                  [-0.07, -0.6, -2.28],\n                                  [0.02, -0.91,  0.77],\n                                  [-1.39, -0.38, -0.15],\n                                  [-0.14,  1.65, -0.93],\n                                  [1.28,  1.13, -0.04],\n                                  [-1.28,  1.82,  2.94],\n                                  [-1.3,  0.34,  2.01]]),\n                 atom_names=['N', 'CA', 'C', 'O', 'CB', 'CG', 'CD', 'NE2',\n                             'OE1', 'H', 'HA', 'HB2', 'HB3', 'HG2', 'HG3', 'HE21', 'HE22'],\n                 bb=[0, 1, 2, 3, 9, 10],\n                 sc=[4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16],\n                 bonds=[(0, 1), (0, 9), (1, 2), (1, 4), (1, 10), (2, 3), (4, 5), (4, 11),\n                        (4, 12), (5, 6), (5, 13), (5, 14), (6, 7), (6, 8), (7, 15), (7, 16)],\n                 offset=17)\n\nG_info = AA_info(coords=np.array([[-1.25,  0.2, -0.25],\n                                  [0.2,  0.29, -0.51],\n                                  [1.04, -0.41,  0.54],\n                                  [0.6, -0.99,  1.5],\n                                  [-1.42, -0.33,  0.61],\n                                  [0.43, -0.17, -1.47],\n                                  [0.51,  1.34, -0.52]]),\n                 atom_names=['N', 'CA', 'C', 'O', 'H', 'HA2', 'HA3'],\n                 bb=[0, 1, 2, 3, 4, 5, 6],\n                 sc=[],\n                 bonds=[(0, 1), (0, 4), (1, 2), (1, 5), (1, 6), (2, 3)],\n                 offset=7)\n\nH_info = AA_info(coords=np.array([[0.48, -2.42, -1.17],\n                                  [1.07, -1.1, -0.85],\n                                  [2.58, -1.1, -0.89],\n                                  [3.22, -2.11, -1.12],\n                                  [0.58, -0.67,  0.57],\n                                  [-0.26,  0.58,  0.55],\n                                  [-1.64,  0.55,  0.39],\n                                  [0.19,  1.83,  0.69],\n                                  [-0.95,  2.55,  0.61],\n                                  [-2.06,  1.81,  0.42],\n                                  [1.15, -3.17, -1.33],\n                                  [0.75, -0.38, -1.62],\n                                  [1.41, -0.53,  1.25],\n                                  [-0.03, -1.48,  1.],\n                                  [-2.26, -0.33,  0.25],\n                                  [-0.89,  3.63,  0.69],\n                                  [-3.07,  2.19,  0.33]]),\n                 atom_names=['N', 'CA', 'C', 'O', 'CB', 'CG', 'CD2', 'ND1',\n                             'CE1', 'NE2', 'H', 'HA', 'HB2', 'HB3', 'HD2', 'HE1', 'HE2'],\n                 bb=[0, 1, 2, 3, 10, 11],\n                 sc=[4, 5, 6, 7, 8, 9, 12, 13, 14, 15, 16],\n                 bonds=[(0, 1), (0, 10), (1, 2), (1, 4), (1, 11), (2, 3), (4, 5), (4, 12),\n                        (4, 13), (5, 6), (5, 7), (6, 9), (6, 14), (7, 8), (8, 9), (8, 15), (9, 16)],\n                 offset=17)\n\nI_info = AA_info(coords=np.array([[0.35, -2.2, -1.14],\n                                  [0.87, -0.81, -1.13],\n                                  [2.39, -0.8, -1.14],\n                                  [3.1, -1.79, -1.14],\n                                  [0.3,  0.03,  0.06],\n                                  [-1.26, -0.04,  0.14],\n                                  [0.75,  1.51,  0.02],\n                                  [-1.85,  0.5,  1.47],\n                                  [1.11, -2.88, -1.16],\n                                  [0.58, -0.33, -2.07],\n                                  [0.7, -0.42,  0.98],\n                                  [-1.6, -1.07,  0.05],\n                                  [-1.7,  0.51, -0.69],\n                                  [1.84,  1.61,  0.05],\n                                  [0.39,  2.02, -0.88],\n                                  [0.38,  2.06,  0.89],\n                                  [-1.43, -0.04,  2.33],\n                                  [-1.66,  1.57,  1.61],\n                                  [-2.93,  0.36,  1.49]]),\n                 atom_names=['N', 'CA', 'C', 'O', 'CB', 'CG1', 'CG2', 'CD1', 'H', 'HA',\n                             'HB', 'HG12', 'HG13', 'HG21', 'HG22', 'HG23', 'HD11', 'HD12', 'HD13'],\n                 bb=[0, 1, 2, 3, 8, 9],\n                 sc=[4, 5, 6, 7, 10, 11, 12, 13, 14, 15, 16, 17, 18],\n                 bonds=[(0, 1), (0, 8), (1, 2), (1, 4), (1, 9), (2, 3), (4, 5), (4, 6), (4, 10),\n                        (5, 7), (5, 11), (5, 12), (6, 13), (6, 14), (6, 15), (7, 16), (7, 17), (7, 18)],\n                 offset=19)\n\nL_info = AA_info(coords=np.array([[0.63, -2.16, -0.9],\n                                  [1.25, -0.81, -0.9],\n                                  [2.77, -0.86, -0.91],\n                                  [3.41, -1.9, -0.9],\n                                  [0.75,  0.03,  0.31],\n                                  [-0.79,  0.2,  0.44],\n                                  [-1.11,  1.13,  1.64],\n                                  [-1.45,  0.77, -0.84],\n                                  [1.33, -2.9, -0.91],\n                                  [0.98, -0.29, -1.82],\n                                  [1.21,  1.02,  0.27],\n                                  [1.12, -0.44,  1.23],\n                                  [-1.24, -0.77,  0.65],\n                                  [-0.69,  0.73,  2.57],\n                                  [-0.7,  2.13,  1.49],\n                                  [-2.19,  1.23,  1.79],\n                                  [-1.,  1.72, -1.13],\n                                  [-1.35,  0.06, -1.67],\n                                  [-2.52,  0.93, -0.68]]),\n                 atom_names=['N', 'CA', 'C', 'O', 'CB', 'CG', 'CD1', 'CD2', 'H', 'HA',\n                             'HB2', 'HB3', 'HG', 'HD11', 'HD12', 'HD13', 'HD21', 'HD22', 'HD23'],\n                 bb=[0, 1, 2, 3, 8, 9],\n                 sc=[4, 5, 6, 7, 10, 11, 12, 13, 14, 15, 16, 17, 18],\n                 bonds=[(0, 1), (0, 8), (1, 2), (1, 4), (1, 9), (2, 3), (4, 5), (4, 10), (4, 11),\n                        (5, 6), (5, 7), (5, 12), (6, 13), (6, 14), (6, 15), (7, 16), (7, 17), (7, 18)],\n                 offset=19)\n\nK_info = AA_info(coords=np.array([[-4.94e-01,  -3.60e+00,  -1.67e+00],\n                                  [1.09e-01,  -2.26e+00,  -1.68e+00],\n                                  [1.62e+00,  -2.32e+00,  -1.73e+00],\n                                  [2.28e+00,  -3.33e+00,  -1.62e+00],\n                                  [-3.98e-01,  -1.46e+00,  -4.42e-01],\n                                  [1.06e-01,  -1.00e-03,  -4.40e-01],\n                                  [-3.72e-01,   7.71e-01,   8.00e-01],\n                                  [2.11e-01,   2.19e+00,   8.10e-01],\n                                  [-3.47e-01,   3.07e+00,   1.89e+00],\n                                  [2.46e-01,  -4.30e+00,  -1.69e+00],\n                                  [-2.06e-01,  -1.74e+00,  -2.59e+00],\n                                  [-7.70e-02,  -1.97e+00,   4.71e-01],\n                                  [-1.49e+00,  -1.46e+00,  -4.51e-01],\n                                  [-2.38e-01,   5.00e-01,  -1.35e+00],\n                                  [1.20e+00,   8.00e-03,  -4.58e-01],\n                                  [-6.10e-02,   2.36e-01,   1.71e+00],\n                                  [-1.47e+00,   8.16e-01,   8.01e-01],\n                                  [-1.10e-02,   2.70e+00,  -1.29e-01],\n                                  [1.30e+00,   2.13e+00,   9.27e-01],\n                                  [-4.74e-01,   2.51e+00,   2.76e+00],\n                                  [2.81e-01,   3.86e+00,   2.10e+00],\n                                  [-1.27e+00,   3.44e+00,   1.62e+00]]),\n                 atom_names=['N', 'CA', 'C', 'O', 'CB', 'CG', 'CD', 'CE', 'NZ', 'H', 'HA',\n                             'HB2', 'HB3', 'HG2', 'HG3', 'HD2', 'HD3', 'HE2', 'HE3', 'HZ1', 'HZ2', 'HZ3'],\n                 bb=[0, 1, 2, 3, 9, 10],\n                 sc=[4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],\n                 bonds=[(0, 1), (0, 9), (1, 2), (1, 4), (1, 10), (2, 3), (4, 5), (4, 11), (4, 12), (5, 6), (5, 13),\n                        (5, 14), (6, 7), (6, 15), (6, 16), (7, 8), (7, 17), (7, 18), (8, 19), (8, 20), (8, 21)],\n                 offset=22)\n\nM_info = AA_info(coords=np.array([[1., -1.99, -1.18],\n                                  [1.53, -0.61, -1.18],\n                                  [3.04, -0.58, -1.22],\n                                  [3.76, -1.56, -1.15],\n                                  [1.02,  0.18,  0.05],\n                                  [-0.52,  0.32,  0.08],\n                                  [-1.04,  1.47,  1.4],\n                                  [-2.82,  1.13,  1.44],\n                                  [1.78, -2.65, -1.19],\n                                  [1.2, -0.1, -2.1],\n                                  [1.46,  1.18,  0.03],\n                                  [1.35, -0.31,  0.96],\n                                  [-0.97, -0.65,  0.26],\n                                  [-0.88,  0.71, -0.88],\n                                  [-3.25,  1.3,  0.45],\n                                  [-2.98,  0.1,  1.75],\n                                  [-3.3,  1.81,  2.16]]),\n                 atom_names=['N', 'CA', 'C', 'O', 'CB', 'CG', 'SD', 'CE', 'H',\n                             'HA', 'HB2', 'HB3', 'HG2', 'HG3', 'HE1', 'HE2', 'HE3'],\n                 bb=[0, 1, 2, 3, 8, 9],\n                 sc=[4, 5, 6, 7, 10, 11, 12, 13, 14, 15, 16],\n                 bonds=[(0, 1), (0, 8), (1, 2), (1, 4), (1, 9), (2, 3), (4, 5), (4, 10),\n                        (4, 11), (5, 6), (5, 12), (5, 13), (6, 7), (7, 14), (7, 15), (7, 16)],\n                 offset=17)\n\nF_info = AA_info(coords=np.array([[1.34, -1.84, -1.06],\n                                  [1.9, -0.47, -1.04],\n                                  [3.41, -0.47, -1.1],\n                                  [4.11, -1.47, -1.04],\n                                  [1.42,  0.32,  0.21],\n                                  [-0.1,  0.39,  0.34],\n                                  [-0.79, -0.61,  1.03],\n                                  [-0.82,  1.46, -0.2],\n                                  [-2.18, -0.57,  1.14],\n                                  [-2.21,  1.5, -0.09],\n                                  [-2.89,  0.49,  0.58],\n                                  [2.09, -2.53, -1.06],\n                                  [1.57,  0.06, -1.93],\n                                  [1.82,  1.33,  0.17],\n                                  [1.83, -0.14,  1.11],\n                                  [-0.25, -1.44,  1.47],\n                                  [-0.31,  2.26, -0.74],\n                                  [-2.71, -1.37,  1.66],\n                                  [-2.77,  2.33, -0.52],\n                                  [-3.98,  0.51,  0.66]]),\n                 atom_names=['N', 'CA', 'C', 'O', 'CB', 'CG', 'CD1', 'CD2', 'CE1', 'CE2',\n                             'CZ', 'H', 'HA', 'HB2', 'HB3', 'HD1', 'HD2', 'HE1', 'HE2', 'HZ'],\n                 bb=[0, 1, 2, 3, 11, 12],\n                 sc=[4, 5, 6, 7, 8, 9, 10, 13, 14, 15, 16, 17, 18, 19],\n                 bonds=[(0, 1), (0, 11), (1, 2), (1, 4), (1, 12), (2, 3), (4, 5), (4, 13), (4, 14), (5, 6),\n                        (5, 7), (6, 8), (6, 15), (7, 9), (7, 16), (8, 10), (8, 17), (9, 10), (9, 18), (10, 19)],\n                 offset=20)\n\nP_info = AA_info(coords=np.array([[0.73, -0.63,  1.11],\n                                  [1.17,  0.41,  0.14],\n                                  [1.07,  1.82,  0.72],\n                                  [0.6,  2.1,  1.8],\n                                  [0.27,  0.24, -1.09],\n                                  [-1.04, -0.26, -0.49],\n                                  [-0.57, -1.17,  0.65],\n                                  [2.22,  0.26, -0.14],\n                                  [0.69, -0.53, -1.75],\n                                  [0.14,  1.16, -1.66],\n                                  [-1.65, -0.8, -1.22],\n                                  [-1.62,  0.58, -0.09],\n                                  [-0.42, -2.18,  0.28],\n                                  [-1.29, -1.18,  1.47]]),\n                 atom_names=['N', 'CA', 'C', 'O', 'CB', 'CG', 'CD',\n                             'HA', 'HB2', 'HB3', 'HG2', 'HG3', 'HD2', 'HD3'],\n                 bb=[0, 1, 2, 3, 7],\n                 sc=[4, 5, 6, 8, 9, 10, 11, 12, 13],\n                 bonds=[(0, 1), (0, 6), (1, 2), (1, 4), (1, 7), (2, 3), (4, 5),\n                        (4, 8), (4, 9), (5, 6), (5, 10), (5, 11), (6, 12), (6, 13)],\n                 offset=14)\n\nS_info = AA_info(coords=np.array([[-0.66, -1.27, -0.65],\n                                  [0.01,  0.04, -0.69],\n                                  [1.52, -0.08, -0.71],\n                                  [2.12, -1.14, -0.71],\n                                  [-0.47,  0.93,  0.48],\n                                  [-0.02,  0.42,  1.73],\n                                  [0.04, -2.01, -0.72],\n                                  [-0.25,  0.54, -1.63],\n                                  [-1.56,  0.96,  0.47],\n                                  [-0.09,  1.94,  0.34],\n                                  [-0.38, -0.48,  1.86]]),\n                 atom_names=['N', 'CA', 'C', 'O', 'CB',\n                             'OG', 'H', 'HA', 'HB2', 'HB3', 'HG'],\n                 bb=[0, 1, 2, 3, 6, 7],\n                 sc=[4, 5, 8, 9, 10],\n                 bonds=[(0, 1), (0, 6), (1, 2), (1, 4), (1, 7),\n                        (2, 3), (4, 5), (4, 8), (4, 9), (5, 10)],\n                 offset=11)\n\nT_info = AA_info(coords=np.array([[-0.55, -2.02, -0.81],\n                                  [0.11, -0.69, -0.81],\n                                  [1.63, -0.81, -0.83],\n                                  [2.23, -1.87, -0.79],\n                                  [-0.38,  0.14,  0.42],\n                                  [0.23,  1.56,  0.53],\n                                  [-1.79,  0.31,  0.35],\n                                  [0.13, -2.78, -0.82],\n                                  [-0.16, -0.17, -1.72],\n                                  [-0.13, -0.41,  1.33],\n                                  [-2.07,  0.79,  1.15],\n                                  [-0.19,  2.08,  1.4],\n                                  [1.32,  1.53,  0.67],\n                                  [0.,  2.16, -0.36]]),\n                 atom_names=['N', 'CA', 'C', 'O', 'CB', 'CG2', 'OG1',\n                             'H', 'HA', 'HB', 'HG1', 'HG21', 'HG22', 'HG23'],\n                 bb=[0, 1, 2, 3, 7, 8],\n                 sc=[4, 5, 6, 9, 10, 11, 12, 13],\n                 bonds=[(0, 1), (0, 7), (1, 2), (1, 4), (1, 8), (2, 3), (4, 5),\n                        (4, 6), (4, 9), (5, 11), (5, 12), (5, 13), (6, 10)],\n                 offset=14)\n\nW_info = AA_info(coords=np.array([[1.58, -2.74, -0.43],\n                                  [2.2, -1.39, -0.43],\n                                  [3.71, -1.44, -0.46],\n                                  [4.36, -2.47, -0.42],\n                                  [1.71, -0.57,  0.79],\n                                  [0.2, -0.32,  0.78],\n                                  [-0.75, -1.07,  1.46],\n                                  [-0.5,  0.65,  0.1],\n                                  [-1.84,  0.48,  0.37],\n                                  [-0.05,  1.67, -0.75],\n                                  [-2., -0.58,  1.2],\n                                  [-2.8,  1.31, -0.21],\n                                  [-1.01,  2.51, -1.33],\n                                  [-2.38,  2.33, -1.06],\n                                  [2.29, -3.47, -0.41],\n                                  [1.91, -0.87, -1.35],\n                                  [2.23,  0.38,  0.84],\n                                  [1.98, -1.11,  1.7],\n                                  [-0.59, -1.94,  2.09],\n                                  [-2.96, -0.99,  1.56],\n                                  [1.,  1.81, -0.96],\n                                  [-3.87,  1.16, -0.01],\n                                  [-0.7,  3.3, -2.],\n                                  [-3.1,  2.99, -1.53]]),\n                 atom_names=['N', 'CA', 'C', 'O', 'CB', 'CG', 'CD1', 'CD2', 'CE2', 'CE3', 'NE1', 'CZ2',\n                             'CZ3', 'CH2', 'H', 'HA', 'HB2', 'HB3', 'HD1', 'HE1', 'HE3', 'HZ2', 'HZ3', 'HH2'],\n                 bb=[0, 1, 2, 3, 14, 15],\n                 sc=[4, 5, 6, 7, 8, 9, 10, 11, 12, 13,\n                     16, 17, 18, 19, 20, 21, 22, 23],\n                 bonds=[(0, 1), (0, 14), (1, 2), (1, 4), (1, 15), (2, 3), (4, 5), (4, 16), (4, 17), (5, 6), (5, 7), (6, 10), (6, 18),\n                        (7, 8), (7, 9), (8, 10), (8, 11), (9, 12), (9, 20), (10, 19), (11, 13), (11, 21), (12, 13), (12, 22), (13, 23)],\n                 offset=24)\n\nY_info = AA_info(coords=np.array([[-0.84, -2.19,  1.38],\n                                  [0.62, -2.08,  1.12],\n                                  [1.44, -2.84,  2.14],\n                                  [0.98, -3.39,  3.12],\n                                  [1.08, -0.6,  1.08],\n                                  [0.41,  0.26,  0.02],\n                                  [0.83,  0.23, -1.31],\n                                  [-0.63,  1.14,  0.38],\n                                  [0.21,  1.03, -2.27],\n                                  [-1.24,  1.94, -0.57],\n                                  [-0.82,  1.89, -1.9],\n                                  [-1.42,  2.68, -2.84],\n                                  [-1.05, -2.73,  2.23],\n                                  [0.85, -2.55,  0.16],\n                                  [2.16, -0.56,  0.92],\n                                  [0.92, -0.16,  2.07],\n                                  [1.64, -0.43, -1.61],\n                                  [-0.96,  1.19,  1.42],\n                                  [0.54,  1., -3.31],\n                                  [-2.04,  2.61, -0.27],\n                                  [-2.12,  3.21, -2.41]]),\n                 atom_names=['N', 'CA', 'C', 'O', 'CB', 'CG', 'CD1', 'CD2', 'CE1', 'CE2',\n                             'CZ', 'OH', 'H', 'HA', 'HB2', 'HB3', 'HD1', 'HD2', 'HE1', 'HE2', 'HH'],\n                 bb=[0, 1, 2, 3, 12, 13],\n                 sc=[4, 5, 6, 7, 8, 9, 10, 11, 14, 15, 16, 17, 18, 19, 20],\n                 bonds=[(0, 1), (0, 12), (1, 2), (1, 4), (1, 13), (2, 3), (4, 5), (4, 14), (4, 15), (5, 6), (5, 7),\n                        (6, 8), (6, 16), (7, 9), (7, 17), (8, 10), (8, 18), (9, 10), (9, 19), (10, 11), (11, 20)],\n                 offset=21)\n\nV_info = AA_info(coords=np.array([[-0.13, -2.06, -0.86],\n                                  [0.43, -0.69, -0.82],\n                                  [1.95, -0.72, -0.85],\n                                  [2.63, -1.73, -0.84],\n                                  [-0.12,  0.08,  0.42],\n                                  [0.53,  1.48,  0.61],\n                                  [-1.65,  0.27,  0.34],\n                                  [0.63, -2.74, -0.87],\n                                  [0.13, -0.17, -1.73],\n                                  [0.11, -0.51,  1.31],\n                                  [0.35,  2.13, -0.25],\n                                  [0.09,  1.97,  1.49],\n                                  [1.6,  1.41,  0.79],\n                                  [-2.17, -0.68,  0.23],\n                                  [-2.02,  0.74,  1.26],\n                                  [-1.93,  0.92, -0.49]]),\n                 atom_names=['N', 'CA', 'C', 'O', 'CB', 'CG1', 'CG2', 'H', 'HA',\n                             'HB', 'HG11', 'HG12', 'HG13', 'HG21', 'HG22', 'HG23'],\n                 bb=[0, 1, 2, 3, 7, 8],\n                 sc=[4, 5, 6, 9, 10, 11, 12, 13, 14, 15],\n                 bonds=[(0, 1), (0, 7), (1, 2), (1, 4), (1, 8), (2, 3), (4, 5), (4, 6),\n                        (4, 9), (5, 10), (5, 11), (5, 12), (6, 13), (6, 14), (6, 15)],\n                 offset=16)\n\n\n\n\nB_info = AA_info(coords=np.array([[ 1.12,  0.22, -0.24],\n                                  [ 1.74, -0.73, -0.65],\n                                  [-0.34,  0.14,  0.17],\n                                  [-0.47, -0.57,  0.98],\n                                  [-0.68,  1.12,  0.5 ],\n                                  [-0.95, -0.17, -0.69]]),\n             atom_names = ['C', 'O', 'CH3', 'HH31', 'HH32', 'HH33'],\n             bb = [0, 2],\n             sc = [1, 3, 4, 5],\n             bonds = [(0, 1), (0, 2), (2, 3), (2, 4), (2, 5)],\n             offset = 6)\n\n\nZ_info = AA_info(coords=np.array([[ 2.23,  0.97, -0.68],\n                                  [ 3.68,  0.81, -0.52],\n                                  [ 1.91,  1.81, -0.21],\n                                  [ 3.93,  0.74,  0.55],\n                                  [ 4.02, -0.09, -1.03],\n                                  [ 4.2 ,  1.68, -0.94]]),\n                  atom_names = ['N', 'CH3', 'H', 'HH31', 'HH32', 'HH33'],\n                  bb = [0, 2],\n                  sc = [1, 3, 4, 5],\n                  bonds = [(0, 1), (0, 2), (1, 3), (1, 4), (1, 5)],\n                  offset = 6)\n\n\n\ntemplates_aa = {'A': A_info, 'C': C_info, 'D': D_info, 'E': E_info,\n                'F': F_info, 'G': G_info, 'H': H_info, 'I': I_info,\n                'K': K_info, 'L': L_info, 'M': M_info, 'N': N_info,\n                'P': P_info, 'Q': Q_info, 'R': R_info, 'S': S_info,\n                'T': T_info, 'V': V_info, 'W': W_info, 'Y': Y_info,\n                'B': B_info, 'Z': Z_info}\n\none_to_three_aa = {'A': 'ALA', 'C': 'CYS', 'D': 'ASP', 'E': 'GLU', 'F': 'PHE',\n                'G': 'GLY', 'H': 'HIS', 'I': 'ILE', 'K': 'LYS', 'L': 'LEU',\n                'M': 'MET', 'N': 'ASN', 'P': 'PRO', 'Q': 'GLN', 'R': 'ARG',\n                'S': 'SER', 'T': 'THR', 'V': 'VAL', 'W': 'TRP', 'Y': 'TYR',\n                'B': 'ACE', 'Z': 'NME'}\n\nthree_to_one_aa = {val: key for key, val in one_to_three_aa.items()}\n", "meta": {"hexsha": "ec9ba515d95b0ef468db1373cb533ea15e3c2857", "size": 30061, "ext": "py", "lang": "Python", "max_stars_repo_path": "bomeba0/templates/aminoacids.py", "max_stars_repo_name": "aloctavodia/bomeba0", "max_stars_repo_head_hexsha": "e212986d8ee60be1da91d63a7a889db14ec851c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bomeba0/templates/aminoacids.py", "max_issues_repo_name": "aloctavodia/bomeba0", "max_issues_repo_head_hexsha": "e212986d8ee60be1da91d63a7a889db14ec851c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2017-06-01T15:46:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T18:28:36.000Z", "max_forks_repo_path": "bomeba0/templates/aminoacids.py", "max_forks_repo_name": "aloctavodia/bomeba0", "max_forks_repo_head_hexsha": "e212986d8ee60be1da91d63a7a889db14ec851c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-09-30T13:26:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:01:18.000Z", "avg_line_length": 55.9795158287, "max_line_length": 136, "alphanum_fraction": 0.2251422108, "include": true, "reason": "import numpy", "num_tokens": 10932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584174871563662, "lm_q2_score": 0.2658804847339313, "lm_q1q2_score": 0.1750603606424316}}
{"text": "\"\"\"\nCoordinate Transformation Functions\n\nThis module contains the functions for converting one\n`sunpy.coordinates.frames` object to another.\n\n.. warning::\n\n  The functions in this submodule should never be called directly, transforming\n  between coordinate frames should be done using the ``.transform_to`` methods\n  on `~astropy.coordinates.BaseCoordinateFrame` or\n  `~astropy.coordinates.SkyCoord` instances.\n\n\"\"\"\nimport logging\nfrom copy import deepcopy\nfrom functools import wraps\nfrom contextlib import contextmanager\n\nimport numpy as np\n\nimport astropy.units as u\nfrom astropy.constants import c as speed_of_light\nfrom astropy.coordinates import (\n    HCRS,\n    ICRS,\n    BaseCoordinateFrame,\n    ConvertError,\n    HeliocentricMeanEcliptic,\n    get_body_barycentric,\n)\nfrom astropy.coordinates.baseframe import frame_transform_graph\nfrom astropy.coordinates.builtin_frames import make_transform_graph_docs\nfrom astropy.coordinates.builtin_frames.utils import get_jd12\nfrom astropy.coordinates.matrix_utilities import matrix_product, matrix_transpose, rotation_matrix\nfrom astropy.coordinates.representation import (\n    CartesianRepresentation,\n    SphericalRepresentation,\n    UnitSphericalRepresentation,\n)\n# Import erfa via astropy to make sure we are using the same ERFA library as Astropy\nfrom astropy.coordinates.sky_coordinate import erfa\nfrom astropy.coordinates.transformations import FunctionTransform, FunctionTransformWithFiniteDifference\nfrom astropy.time import Time\n\nfrom sunpy import log\nfrom sunpy.sun import constants\nfrom .frames import (\n    _J2000,\n    GeocentricEarthEquatorial,\n    GeocentricSolarEcliptic,\n    Heliocentric,\n    HeliocentricEarthEcliptic,\n    HeliocentricInertial,\n    HeliographicCarrington,\n    HeliographicStonyhurst,\n    Helioprojective,\n)\n\nRSUN_METERS = constants.get('radius').si.to(u.m)\n\n__all__ = ['transform_with_sun_center',\n           'propagate_with_solar_surface',\n           'hgs_to_hgc', 'hgc_to_hgs', 'hcc_to_hpc',\n           'hpc_to_hcc', 'hcc_to_hgs', 'hgs_to_hcc',\n           'hpc_to_hpc',\n           'hcrs_to_hgs', 'hgs_to_hcrs',\n           'hgs_to_hgs', 'hgc_to_hgc', 'hcc_to_hcc',\n           'hme_to_hee', 'hee_to_hme', 'hee_to_hee',\n           'hee_to_gse', 'gse_to_hee', 'gse_to_gse',\n           'hgs_to_hci', 'hci_to_hgs', 'hci_to_hci',\n           'hme_to_gei', 'gei_to_hme', 'gei_to_gei']\n\n\n# Boolean flag for whether to ignore the motion of the center of the Sun in inertial space\n_ignore_sun_motion = False\n\n\n# If not None, the name of the differential-rotation model to use for any obstime change\n_autoapply_diffrot = None\n\n\n@contextmanager\ndef transform_with_sun_center():\n    \"\"\"\n    Context manager for coordinate transformations to ignore the motion of the center of the Sun.\n\n    Normally, coordinates refer to a point in inertial space (relative to the barycenter of the\n    solar system).  Transforming to a different observation time does not move the point at all,\n    but rather only updates the coordinate representation as needed for the origin and axis\n    orientations at the new observation time.  However, the center of the Sun moves over time.\n    Thus, for example, a coordinate that lies on the surface of the Sun at one observation time\n    will not continue to lie on the surface of the Sun at other observation times.\n\n    Under this context manager, transformations will instead move the coordinate over time to\n    \"follow\" the translational motion of the center of Sun, thus maintaining the position of the\n    coordinate relative to the center of the Sun.\n\n    Notes\n    -----\n    This context manager accounts only for the motion of the center of the Sun, i.e.,\n    translational motion.  The motion of solar features due to any rotation of the Sun about its\n    rotational axis is not accounted for.\n\n    Due to the implementation approach, this context manager modifies transformations between only\n    these five coordinate frames:\n    `~sunpy.coordinates.frames.HeliographicStonyhurst`,\n    `~sunpy.coordinates.frames.HeliographicCarrington`,\n    `~sunpy.coordinates.frames.HeliocentricInertial`,\n    `~sunpy.coordinates.frames.Heliocentric`, and\n    `~sunpy.coordinates.frames.Helioprojective`.\n\n    Examples\n    --------\n    >>> from astropy.coordinates import SkyCoord\n    >>> from sunpy.coordinates import HeliographicStonyhurst, transform_with_sun_center\n    >>> import astropy.units as u\n    >>> start_frame = HeliographicStonyhurst(obstime=\"2001-01-01\")\n    >>> end_frame = HeliographicStonyhurst(obstime=\"2001-02-01\")\n    >>> sun_center = SkyCoord(0*u.deg, 0*u.deg, 0*u.AU, frame=start_frame)\n    >>> sun_center\n    <SkyCoord (HeliographicStonyhurst: obstime=2001-01-01T00:00:00.000, rsun=695700.0 km): (lon, lat, radius) in (deg, deg, AU)\n        (0., 0., 0.)>\n    >>> sun_center.transform_to(end_frame)  # transformations do not normally follow Sun center\n    <SkyCoord (HeliographicStonyhurst: obstime=2001-02-01T00:00:00.000, rsun=695700.0 km): (lon, lat, radius) in (deg, deg, AU)\n        (23.33174233, -5.96399877, 0.00027959)>\n    >>> with transform_with_sun_center():\n    ...     sun_center.transform_to(end_frame)  # now following Sun center\n    <SkyCoord (HeliographicStonyhurst: obstime=2001-02-01T00:00:00.000, rsun=695700.0 km): (lon, lat, radius) in (deg, deg, AU)\n        (0., 0., 0.)>\n    \"\"\"\n    try:\n        global _ignore_sun_motion\n\n        old_ignore_sun_motion = _ignore_sun_motion  # nominally False\n\n        if not old_ignore_sun_motion:\n            log.debug(\"Ignoring the motion of the center of the Sun for transformations\")\n        _ignore_sun_motion = True\n        yield\n    finally:\n        if not old_ignore_sun_motion:\n            log.debug(\"Stop ignoring the motion of the center of the Sun for transformations\")\n        _ignore_sun_motion = old_ignore_sun_motion\n\n\n@contextmanager\ndef propagate_with_solar_surface(rotation_model='howard'):\n    \"\"\"\n    Context manager for coordinate transformations to automatically apply solar\n    differential rotation for any change in observation time.\n\n    Normally, coordinates refer to a point in inertial space (relative to the\n    barycenter of the solar system).  Transforming to a different observation time\n    does not move the point at all, but rather only updates the coordinate\n    representation as needed for the origin and axis orientations at the new\n    observation time.\n\n    Under this context manager, transformations will instead treat the coordinate\n    as if it were referring to a point on the solar surface instead of a point in\n    inertial space.  If a transformation has a change in observation time, the\n    heliographic longitude of the point will be updated according to the specified\n    rotation model.\n\n    Parameters\n    ----------\n    rotation_model : `str`\n        Accepted model names are ``'howard'`` (default), ``'snodgrass'``,\n        ``'allen'``, and ``'rigid'``.  See the documentation for\n        :func:`~sunpy.physics.differential_rotation.diff_rot` for the differences\n        between these models.\n\n    Notes\n    -----\n    This context manager also ignores the motion of the center of the Sun (see\n    :func:`~sunpy.coordinates.transformations.transform_with_sun_center`).\n\n    Due to the implementation approach, this context manager modifies\n    transformations between only these five coordinate frames:\n    `~sunpy.coordinates.frames.HeliographicStonyhurst`,\n    `~sunpy.coordinates.frames.HeliographicCarrington`,\n    `~sunpy.coordinates.frames.HeliocentricInertial`,\n    `~sunpy.coordinates.frames.Heliocentric`, and\n    `~sunpy.coordinates.frames.Helioprojective`.\n\n    Examples\n    --------\n    .. minigallery:: sunpy.coordinates.propagate_with_solar_surface\n\n    >>> import astropy.units as u\n    >>> from astropy.coordinates import SkyCoord\n    >>> from sunpy.coordinates import HeliocentricInertial, propagate_with_solar_surface\n    >>> meridian = SkyCoord(0*u.deg, [-60, -30, 0, 30, 60]*u.deg, 1*u.AU,\n    ...                     frame=HeliocentricInertial, obstime='2021-09-15')\n    >>> out_frame = HeliocentricInertial(obstime='2021-09-21')\n    >>> with propagate_with_solar_surface():\n    ...     print(meridian.transform_to(out_frame))\n    <SkyCoord (HeliocentricInertial: obstime=2021-09-21T00:00:00.000): (lon, lat, distance) in (deg, deg, AU)\n        [(70.24182965, -60., 1.),\n         (82.09298036, -30., 1.),\n         (85.9579703 ,   0., 1.),\n         (82.09298036,  30., 1.),\n         (70.24182965,  60., 1.)]>\n    >>> with propagate_with_solar_surface(rotation_model='rigid'):\n    ...     print(meridian.transform_to(out_frame))\n    <SkyCoord (HeliocentricInertial: obstime=2021-09-21T00:00:00.000): (lon, lat, distance) in (deg, deg, AU)\n        [(85.1064, -60., 1.), (85.1064, -30., 1.),\n         (85.1064,   0., 1.), (85.1064,  30., 1.),\n         (85.1064,  60., 1.)]>\n    \"\"\"\n    with transform_with_sun_center():\n        try:\n            global _autoapply_diffrot\n\n            old_autoapply_diffrot = _autoapply_diffrot  # nominally False\n\n            log.debug(\"Enabling automatic solar differential rotation \"\n                      f\"('{rotation_model}') for any changes in obstime\")\n            _autoapply_diffrot = rotation_model\n            yield\n        finally:\n            if not old_autoapply_diffrot:\n                log.debug(\"Disabling automatic solar differential rotation \"\n                          \"for any changes in obstime\")\n            _autoapply_diffrot = old_autoapply_diffrot\n\n\n# Global counter to keep track of the layer of transformation\n_layer_level = 0\n\n\ndef _transformation_debug(description):\n    \"\"\"\n    Decorator to produce debugging output for a transformation function: its description, inputs,\n    and output.  Unicode box-drawing characters are used.\n    \"\"\"\n    def decorator(func):\n        @wraps(func)\n        def wrapped_func(*args, **kwargs):\n            global _layer_level\n\n            # Check if the logging level is at least DEBUG (for performance reasons)\n            debug_output = log.getEffectiveLevel() <= logging.DEBUG\n\n            if debug_output:\n                # Indention for transformation layer\n                indention = u\"\\u2502   \" * _layer_level\n\n                # For the input arguments, add indention to any lines after the first line\n                from_str = str(args[0]).replace(\"\\n\", f\"\\n       {indention}\\u2502       \")\n                to_str = str(args[1]).replace(\"\\n\", f\"\\n       {indention}\\u2502       \")\n\n                # Log the description and the input arguments\n                log.debug(f\"{indention}{description}\")\n                log.debug(f\"{indention}\\u251c\\u2500From: {from_str}\")\n                log.debug(f\"{indention}\\u251c\\u2500To  : {to_str}\")\n\n                # Increment the layer level to increase the indention for nested transformations\n                _layer_level += 1\n\n            result = func(*args, **kwargs)\n\n            if debug_output:\n                # Decrement the layer level\n                _layer_level -= 1\n\n                # For the output, add intention to any lines after the first line\n                out_str = str(result).replace(\"\\n\", f\"\\n       {indention}        \")\n\n                # Log the output\n                log.debug(f\"{indention}\\u2514\\u2500Out : {out_str}\")\n\n            return result\n        return wrapped_func\n    return decorator\n\n\ndef _observers_are_equal(obs_1, obs_2):\n    # Note that this also lets pass the situation where both observers are None\n    if obs_1 is obs_2:\n        return True\n\n    # obs_1 != obs_2\n    if obs_1 is None:\n        raise ConvertError(\"The source observer is set to None, but the transformation requires \"\n                           \"the source observer to be specified, as the destination observer \"\n                           f\"is set to {obs_2}.\")\n    if obs_2 is None:\n        raise ConvertError(\"The destination observer is set to None, but the transformation \"\n                           \"requires the destination observer to be specified, as the \"\n                           f\"source observer is set to {obs_1}.\")\n    if isinstance(obs_1, str):\n        if obs_1 == \"self\":\n            return False\n        raise ConvertError(\"The source observer needs to have `obstime` set because the \"\n                           \"destination observer is different.\")\n    if isinstance(obs_2, str):\n        if obs_2 == \"self\":\n            return False\n        raise ConvertError(\"The destination observer needs to have `obstime` set because the \"\n                           \"source observer is different.\")\n\n    return np.atleast_1d((u.allclose(obs_1.lat, obs_2.lat) and\n                          u.allclose(obs_1.lon, obs_2.lon) and\n                          u.allclose(obs_1.radius, obs_2.radius) and\n                          _times_are_equal(obs_1.obstime, obs_2.obstime))).all()\n\n\ndef _check_observer_defined(frame):\n    if frame.observer is None:\n        raise ConvertError(\"This transformation cannot be performed because the \"\n                           f\"{frame.__class__.__name__} frame has observer=None.\")\n    elif isinstance(frame.observer, str):\n        if frame.observer != \"self\":\n            raise ConvertError(\"This transformation cannot be performed because the \"\n                               f\"{frame.__class__.__name__} frame needs a specified obstime \"\n                               f\"to fully resolve observer='{frame.observer}'.\")\n        elif not isinstance(frame, HeliographicCarrington):\n            raise ConvertError(f\"The {frame.__class__.__name__} frame has observer='self' \"\n                               \"but this is valid for only HeliographicCarrington frames.\")\n\n\ndef _times_are_equal(time_1, time_2):\n    # Checks whether times are equal\n    if isinstance(time_1, Time) and isinstance(time_2, Time):\n        # We explicitly perform the check in TAI to avoid possible numerical precision differences\n        # between a time in UTC and the same time after a UTC->TAI->UTC conversion\n        return np.all(time_1.tai == time_2.tai)\n\n    # We also deem the times equal if they are both None\n    return time_1 is None and time_2 is None\n\n\n# =============================================================================\n# ------------------------- Transformation Framework --------------------------\n# =============================================================================\n\n\ndef _transform_obstime(frame, obstime):\n    \"\"\"\n    Transform a frame to a new obstime using the appropriate loopback transformation.\n    If the new obstime is None, no transformation is performed.\n    If the frame's obstime is None, the frame is copied with the new obstime.\n    \"\"\"\n    # If obstime is None or the obstime matches, nothing needs to be done\n    if obstime is None or _times_are_equal(frame.obstime, obstime):\n        return frame\n\n    # Transform to the new obstime using the appropriate loopback transformation\n    new_frame = frame.replicate(obstime=obstime)\n    if frame.obstime is not None:\n        return frame.transform_to(new_frame)\n    else:\n        return new_frame\n\n\ndef _rotation_matrix_hgs_to_hgc(obstime, observer_distance_from_sun):\n    \"\"\"\n    Return the rotation matrix from HGS to HGC at the same observation time\n    \"\"\"\n    if obstime is None:\n        raise ConvertError(\"To perform this transformation, the coordinate\"\n                           \" frame needs a specified `obstime`.\")\n\n    # Import here to avoid a circular import\n    from .sun import L0, earth_distance\n\n    # Calculate the difference in light travel time if the observer is at a different distance from\n    # the Sun than the Earth is\n    delta_time = (observer_distance_from_sun - earth_distance(obstime)) / speed_of_light\n\n    # Calculate the corresponding difference in apparent longitude\n    delta_lon = delta_time * constants.sidereal_rotation_rate\n\n    # Rotation is only in longitude, so only around the Z axis\n    return rotation_matrix(-(L0(obstime) + delta_lon), 'z')\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 HeliographicStonyhurst, HeliographicCarrington)\n@_transformation_debug(\"HGS->HGC\")\ndef hgs_to_hgc(hgscoord, hgcframe):\n    \"\"\"\n    Convert from Heliographic Stonyhurst to Heliographic Carrington.\n    \"\"\"\n    _check_observer_defined(hgcframe)\n    if isinstance(hgcframe.observer, str) and hgcframe.observer == \"self\":\n        observer_radius = hgscoord.radius\n    else:\n        observer_radius = hgcframe.observer.radius\n\n    # First transform the HGS coord to the HGC obstime\n    int_coord = _transform_obstime(hgscoord, hgcframe.obstime)\n\n    # Rotate from HGS to HGC\n    total_matrix = _rotation_matrix_hgs_to_hgc(int_coord.obstime, observer_radius)\n    newrepr = int_coord.cartesian.transform(total_matrix)\n\n    return hgcframe._replicate(newrepr, obstime=int_coord.obstime)\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 HeliographicCarrington, HeliographicStonyhurst)\n@_transformation_debug(\"HGC->HGS\")\ndef hgc_to_hgs(hgccoord, hgsframe):\n    \"\"\"\n    Convert from Heliographic Carrington to Heliographic Stonyhurst.\n    \"\"\"\n    _check_observer_defined(hgccoord)\n\n    hgccoord = hgccoord.make_3d()\n\n    if isinstance(hgccoord.observer, str) and hgccoord.observer == \"self\":\n        observer_radius = hgccoord.radius\n    else:\n        observer_radius = hgccoord.observer.radius\n\n    # First transform the HGC coord to the HGS obstime\n    int_coord = _transform_obstime(hgccoord, hgsframe.obstime)\n\n    # Rotate from HGC to HGS\n    total_matrix = matrix_transpose(_rotation_matrix_hgs_to_hgc(int_coord.obstime,\n                                                                observer_radius))\n    newrepr = int_coord.cartesian.transform(total_matrix)\n\n    return hgsframe._replicate(newrepr, obstime=int_coord.obstime)\n\n\ndef _matrix_hcc_to_hpc():\n    # Returns the transformation matrix that permutes/swaps axes from HCC to HPC\n\n    # HPC spherical coordinates are a left-handed frame with these equivalent Cartesian axes:\n    #   HPC_X = -HCC_Z\n    #   HPC_Y = HCC_X\n    #   HPC_Z = HCC_Y\n    # (HPC_X and HPC_Y are not to be confused with HPC_Tx and HPC_Ty)\n    return np.array([[0, 0, -1],\n                     [1, 0, 0],\n                     [0, 1, 0]])\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 Heliocentric, Helioprojective)\n@_transformation_debug(\"HCC->HPC\")\ndef hcc_to_hpc(helioccoord, heliopframe):\n    \"\"\"\n    Convert from Heliocentric Cartesian to Helioprojective Cartesian.\n    \"\"\"\n    _check_observer_defined(helioccoord)\n    _check_observer_defined(heliopframe)\n\n    # Transform the HPC observer (in HGS) to the HPC obstime in case it's different\n    observer = _transform_obstime(heliopframe.observer, heliopframe.obstime)\n\n    # Loopback transform HCC coord to obstime and observer of HPC frame\n    int_frame = Heliocentric(obstime=observer.obstime, observer=observer)\n    int_coord = helioccoord.transform_to(int_frame)\n\n    # Shift the origin from the Sun to the observer\n    distance = int_coord.observer.radius\n    newrepr = int_coord.cartesian - CartesianRepresentation(0*u.m, 0*u.m, distance)\n\n    # Permute/swap axes from HCC to HPC equivalent Cartesian\n    newrepr = newrepr.transform(_matrix_hcc_to_hpc())\n\n    # Explicitly represent as spherical because external code (e.g., wcsaxes) expects it\n    return heliopframe.realize_frame(newrepr.represent_as(SphericalRepresentation))\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 Helioprojective, Heliocentric)\n@_transformation_debug(\"HPC->HCC\")\ndef hpc_to_hcc(heliopcoord, heliocframe):\n    \"\"\"\n    Convert from Helioprojective Cartesian to Heliocentric Cartesian.\n    \"\"\"\n    _check_observer_defined(heliopcoord)\n    _check_observer_defined(heliocframe)\n\n    heliopcoord = heliopcoord.make_3d()\n\n    # Permute/swap axes from HPC equivalent Cartesian to HCC\n    newrepr = heliopcoord.cartesian.transform(matrix_transpose(_matrix_hcc_to_hpc()))\n\n    # Transform the HPC observer (in HGS) to the HPC obstime in case it's different\n    observer = _transform_obstime(heliopcoord.observer, heliopcoord.obstime)\n\n    # Shift the origin from the observer to the Sun\n    distance = observer.radius\n    newrepr += CartesianRepresentation(0*u.m, 0*u.m, distance)\n\n    # Complete the conversion of HPC to HCC at the obstime and observer of the HPC coord\n    int_coord = Heliocentric(newrepr, obstime=observer.obstime, observer=observer)\n\n    # Loopback transform HCC as needed\n    return int_coord.transform_to(heliocframe)\n\n\ndef _rotation_matrix_hcc_to_hgs(longitude, latitude):\n    # Returns the rotation matrix from HCC to HGS based on the observer longitude and latitude\n\n    # Permute the axes of HCC to match HGS Cartesian equivalent\n    #   HGS_X = HCC_Z\n    #   HGS_Y = HCC_X\n    #   HGS_Z = HCC_Y\n    axes_matrix = np.array([[0, 0, 1],\n                            [1, 0, 0],\n                            [0, 1, 0]])\n\n    # Rotate in latitude and longitude (sign difference because of direction difference)\n    lat_matrix = rotation_matrix(latitude, 'y')\n    lon_matrix = rotation_matrix(-longitude, 'z')\n\n    return lon_matrix @ lat_matrix @ axes_matrix\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 Heliocentric, HeliographicStonyhurst)\n@_transformation_debug(\"HCC->HGS\")\ndef hcc_to_hgs(helioccoord, heliogframe):\n    \"\"\"\n    Convert from Heliocentric Cartesian to Heliographic Stonyhurst.\n    \"\"\"\n    _check_observer_defined(helioccoord)\n\n    # Transform the HCC observer (in HGS) to the HCC obstime in case it's different\n    hcc_observer_at_hcc_obstime = _transform_obstime(helioccoord.observer, helioccoord.obstime)\n\n    total_matrix = _rotation_matrix_hcc_to_hgs(hcc_observer_at_hcc_obstime.lon,\n                                               hcc_observer_at_hcc_obstime.lat)\n\n    # Transform from HCC to HGS at the HCC obstime\n    newrepr = helioccoord.cartesian.transform(total_matrix)\n    int_coord = HeliographicStonyhurst(newrepr, obstime=hcc_observer_at_hcc_obstime.obstime)\n\n    # For historical reasons, we support HCC with no obstime transforming to HGS with an obstime\n    if int_coord.obstime is None and heliogframe.obstime is not None:\n        int_coord = int_coord.replicate(obstime=heliogframe.obstime)\n\n    # Loopback transform HGS as needed\n    return int_coord.transform_to(heliogframe)\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 HeliographicStonyhurst, Heliocentric)\n@_transformation_debug(\"HGS->HCC\")\ndef hgs_to_hcc(heliogcoord, heliocframe):\n    \"\"\"\n    Convert from Heliographic Stonyhurst to Heliocentric Cartesian.\n    \"\"\"\n    _check_observer_defined(heliocframe)\n\n    heliogcoord = heliogcoord.make_3d()\n\n    # Loopback transform HGS if there is a change in obstime\n    int_coord = _transform_obstime(heliogcoord, heliocframe.obstime)\n\n    # Transform the HCC observer (in HGS) to the HCC obstime in case it's different\n    hcc_observer_at_hcc_obstime = _transform_obstime(heliocframe.observer, int_coord.obstime)\n\n    total_matrix = matrix_transpose(_rotation_matrix_hcc_to_hgs(hcc_observer_at_hcc_obstime.lon,\n                                                                hcc_observer_at_hcc_obstime.lat))\n\n    # Transform from HGS to HCC at the same obstime\n    newrepr = int_coord.cartesian.transform(total_matrix)\n    return heliocframe.realize_frame(newrepr)\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 Helioprojective, Helioprojective)\n@_transformation_debug(\"HPC->HPC\")\ndef hpc_to_hpc(from_coo, to_frame):\n    \"\"\"\n    This converts from HPC to HPC, with different observer location parameters.\n    It does this by transforming through HGS.\n    \"\"\"\n    if _observers_are_equal(from_coo.observer, to_frame.observer) and \\\n       _times_are_equal(from_coo.obstime, to_frame.obstime):\n        return to_frame.realize_frame(from_coo.data)\n\n    _check_observer_defined(from_coo)\n    _check_observer_defined(to_frame)\n\n    hgs = from_coo.transform_to(HeliographicStonyhurst(obstime=to_frame.obstime))\n    hpc = hgs.transform_to(to_frame)\n\n    return hpc\n\n\ndef _rotation_matrix_reprs_to_reprs(start_representation, end_representation):\n    \"\"\"\n    Return the matrix for the direct rotation from one representation to a second representation.\n    The representations need not be normalized first, and can be arrays of representations.\n    \"\"\"\n    A = start_representation.to_cartesian()\n    B = end_representation.to_cartesian()\n    rotation_axis = A.cross(B)\n    rotation_angle = -np.arccos(A.dot(B) / (A.norm() * B.norm()))  # negation is required\n\n    if rotation_angle.isscalar:\n        # This line works around some input/output quirks of Astropy's rotation_matrix()\n        matrix = np.array(rotation_matrix(rotation_angle, rotation_axis.xyz.value.tolist()))\n    else:\n        matrix_list = [np.array(rotation_matrix(angle, axis.xyz.value.tolist()))\n                       for angle, axis in zip(rotation_angle, rotation_axis)]\n        matrix = np.stack(matrix_list)\n\n    return matrix\n\n\ndef _rotation_matrix_reprs_to_xz_about_z(representations):\n    \"\"\"\n    Return one or more matrices for rotating one or more representations around the Z axis into the\n    XZ plane.\n    \"\"\"\n    A = representations.to_cartesian()\n\n    # Zero out the Z components\n    # (The additional transpose operations are to handle both scalar and array inputs)\n    A_no_z = CartesianRepresentation((A.xyz.T * [1, 1, 0]).T)\n\n    # Rotate the resulting vector to the X axis\n    x_axis = CartesianRepresentation(1, 0, 0)\n    matrix = _rotation_matrix_reprs_to_reprs(A_no_z, x_axis)\n\n    return matrix\n\n\ndef _sun_earth_icrf(time):\n    \"\"\"\n    Return the Sun-Earth vector for ICRF-based frames.\n    \"\"\"\n    sun_pos_icrs = get_body_barycentric('sun', time)\n    earth_pos_icrs = get_body_barycentric('earth', time)\n    return earth_pos_icrs - sun_pos_icrs\n\n\n# The Sun's north pole is oriented RA=286.13 deg, dec=63.87 deg in ICRS, and thus HCRS as well\n# (See Archinal et al. 2011,\n#   \"Report of the IAU Working Group on Cartographic Coordinates and Rotational Elements: 2009\")\n# The orientation of the north pole in ICRS/HCRS is assumed to be constant in time\n_SOLAR_NORTH_POLE_HCRS = UnitSphericalRepresentation(lon=constants.get('alpha_0'),\n                                                     lat=constants.get('delta_0'))\n\n\n# Calculate the rotation matrix to de-tilt the Sun's rotation axis to be parallel to the Z axis\n_SUN_DETILT_MATRIX = _rotation_matrix_reprs_to_reprs(_SOLAR_NORTH_POLE_HCRS,\n                                                     CartesianRepresentation(0, 0, 1))\n\n\ndef _affine_params_hcrs_to_hgs(hcrs_time, hgs_time):\n    \"\"\"\n    Return the affine parameters (matrix and offset) from HCRS to HGS\n\n    HGS shares the same origin (the Sun) as HCRS, but has its Z axis aligned with the Sun's\n    rotation axis and its X axis aligned with the projection of the Sun-Earth vector onto the Sun's\n    equatorial plane (i.e., the component of the Sun-Earth vector perpendicular to the Z axis).\n    Thus, the transformation matrix is the product of the matrix to align the Z axis (by de-tilting\n    the Sun's rotation axis) and the matrix to align the X axis.  The first matrix is independent\n    of time and is pre-computed, while the second matrix depends on the time-varying Sun-Earth\n    vector.\n    \"\"\"\n    # Determine the Sun-Earth vector in ICRS\n    # Since HCRS is ICRS with an origin shift, this is also the Sun-Earth vector in HCRS\n    sun_pos_icrs = get_body_barycentric('sun', hgs_time)\n    earth_pos_icrs = get_body_barycentric('earth', hgs_time)\n    sun_earth = earth_pos_icrs - sun_pos_icrs\n\n    # De-tilt the Sun-Earth vector to the frame with the Sun's rotation axis parallel to the Z axis\n    sun_earth_detilt = sun_earth.transform(_SUN_DETILT_MATRIX)\n\n    # Rotate the Sun-Earth vector about the Z axis so that it lies in the XZ plane\n    rot_matrix = _rotation_matrix_reprs_to_xz_about_z(sun_earth_detilt)\n\n    total_matrix = rot_matrix @ _SUN_DETILT_MATRIX\n\n    # All of the above is calculated for the HGS observation time\n    # If the HCRS observation time is different, calculate the translation in origin\n    if not _ignore_sun_motion and np.any(hcrs_time != hgs_time):\n        sun_pos_old_icrs = get_body_barycentric('sun', hcrs_time)\n        offset_icrf = sun_pos_old_icrs - sun_pos_icrs\n    else:\n        offset_icrf = sun_pos_icrs * 0  # preserves obstime shape\n\n    offset = offset_icrf.transform(total_matrix)\n    return total_matrix, offset\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 HCRS, HeliographicStonyhurst)\n@_transformation_debug(\"HCRS->HGS\")\ndef hcrs_to_hgs(hcrscoord, hgsframe):\n    \"\"\"\n    Convert from HCRS to Heliographic Stonyhurst (HGS).\n\n    Even though we calculate the parameters for the affine transform, we use\n    ``FunctionTransformWithFiniteDifference`` because otherwise there is no way to account for the\n    induced angular velocity when transforming a coordinate with velocity information.\n    \"\"\"\n    if hgsframe.obstime is None:\n        raise ConvertError(\"To perform this transformation, the HeliographicStonyhurst\"\n                           \" frame needs a specified `obstime`.\")\n\n    rot_matrix, offset = _affine_params_hcrs_to_hgs(hcrscoord.obstime, hgsframe.obstime)\n\n    return hgsframe.realize_frame(hcrscoord.cartesian.transform(rot_matrix) + offset)\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 HeliographicStonyhurst, HCRS)\n@_transformation_debug(\"HGS->HCRS\")\ndef hgs_to_hcrs(hgscoord, hcrsframe):\n    \"\"\"\n    Convert from Heliographic Stonyhurst to HCRS.\n\n    Even though we calculate the parameters for the affine transform, we use\n    ``FunctionTransformWithFiniteDifference`` because otherwise there is no way to account for the\n    induced angular velocity when transforming a coordinate with velocity information.\n    \"\"\"\n    if hgscoord.obstime is None:\n        raise ConvertError(\"To perform this transformation, the HeliographicStonyhurst\"\n                           \" frame needs a specified `obstime`.\")\n\n    hgscoord = hgscoord.make_3d()\n\n    # Calculate the matrix and offset in the HCRS->HGS direction\n    forward_matrix, forward_offset = _affine_params_hcrs_to_hgs(hcrsframe.obstime, hgscoord.obstime)\n\n    # Invert the transformation to get the HGS->HCRS transformation\n    reverse_matrix = matrix_transpose(forward_matrix)\n    reverse_offset = (-forward_offset).transform(reverse_matrix)\n\n    return hcrsframe.realize_frame(hgscoord.cartesian.transform(reverse_matrix) + reverse_offset)\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 HeliographicStonyhurst, HeliographicStonyhurst)\n@_transformation_debug(\"HGS->HGS\")\ndef hgs_to_hgs(from_coo, to_frame):\n    \"\"\"\n    Convert between two Heliographic Stonyhurst frames.\n    \"\"\"\n    if to_frame.obstime is None:\n        return from_coo.replicate()\n    elif _times_are_equal(from_coo.obstime, to_frame.obstime):\n        return to_frame.realize_frame(from_coo.data)\n    else:\n        if _autoapply_diffrot:\n            from_coo = from_coo._apply_diffrot((to_frame.obstime - from_coo.obstime).to('day'),\n                                               _autoapply_diffrot)\n        return from_coo.transform_to(HCRS(obstime=to_frame.obstime)).transform_to(to_frame)\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 HeliographicCarrington, HeliographicCarrington)\n@_transformation_debug(\"HGC->HGC\")\ndef hgc_to_hgc(from_coo, to_frame):\n    \"\"\"\n    Convert between two Heliographic Carrington frames.\n    \"\"\"\n    if _observers_are_equal(from_coo.observer, to_frame.observer) and \\\n       _times_are_equal(from_coo.obstime, to_frame.obstime):\n        return to_frame.realize_frame(from_coo.data)\n\n    _check_observer_defined(from_coo)\n    _check_observer_defined(to_frame)\n\n    # Convert through HGS\n    hgscoord = from_coo.transform_to(HeliographicStonyhurst(obstime=from_coo.obstime))\n\n    return hgscoord.transform_to(to_frame)\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 Heliocentric, Heliocentric)\n@_transformation_debug(\"HCC->HCC\")\ndef hcc_to_hcc(from_coo, to_frame):\n    \"\"\"\n    Convert between two Heliocentric frames.\n    \"\"\"\n    if _observers_are_equal(from_coo.observer, to_frame.observer) and \\\n       _times_are_equal(from_coo.obstime, to_frame.obstime):\n        return to_frame.realize_frame(from_coo.data)\n\n    _check_observer_defined(from_coo)\n    _check_observer_defined(to_frame)\n\n    # Convert through HGS\n    hgscoord = from_coo.transform_to(HeliographicStonyhurst(obstime=to_frame.obstime))\n\n    return hgscoord.transform_to(to_frame)\n\n\ndef _rotation_matrix_hme_to_hee(hmeframe):\n    \"\"\"\n    Return the rotation matrix from HME to HEE at the same observation time\n    \"\"\"\n    # Get the Sun-Earth vector\n    sun_earth = HCRS(_sun_earth_icrf(hmeframe.obstime), obstime=hmeframe.obstime)\n    sun_earth_hme = sun_earth.transform_to(hmeframe).cartesian\n\n    # Rotate the Sun-Earth vector about the Z axis so that it lies in the XZ plane\n    rot_matrix = _rotation_matrix_reprs_to_xz_about_z(sun_earth_hme)\n\n    # Tilt the rotated Sun-Earth vector so that it is aligned with the X axis\n    tilt_matrix = _rotation_matrix_reprs_to_reprs(sun_earth_hme.transform(rot_matrix),\n                                                  CartesianRepresentation(1, 0, 0))\n\n    return matrix_product(tilt_matrix, rot_matrix)\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 HeliocentricMeanEcliptic, HeliocentricEarthEcliptic)\n@_transformation_debug(\"HME->HEE\")\ndef hme_to_hee(hmecoord, heeframe):\n    \"\"\"\n    Convert from Heliocentric Mean Ecliptic to Heliocentric Earth Ecliptic\n    \"\"\"\n    if heeframe.obstime is None:\n        raise ConvertError(\"To perform this transformation, the coordinate\"\n                           \" frame needs a specified `obstime`.\")\n\n    # Convert to the HME frame with mean equinox of date at the HEE obstime, through HCRS\n    int_frame = HeliocentricMeanEcliptic(obstime=heeframe.obstime, equinox=heeframe.obstime)\n    int_coord = hmecoord.transform_to(HCRS(obstime=hmecoord.obstime)).transform_to(int_frame)\n\n    # Rotate the intermediate coord to the HEE frame\n    total_matrix = _rotation_matrix_hme_to_hee(int_frame)\n    newrepr = int_coord.cartesian.transform(total_matrix)\n\n    return heeframe.realize_frame(newrepr)\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 HeliocentricEarthEcliptic, HeliocentricMeanEcliptic)\n@_transformation_debug(\"HEE->HME\")\ndef hee_to_hme(heecoord, hmeframe):\n    \"\"\"\n    Convert from Heliocentric Earth Ecliptic to Heliocentric Mean Ecliptic\n    \"\"\"\n    if heecoord.obstime is None:\n        raise ConvertError(\"To perform this transformation, the coordinate\"\n                           \" frame needs a specified `obstime`.\")\n\n    int_frame = HeliocentricMeanEcliptic(obstime=heecoord.obstime, equinox=heecoord.obstime)\n\n    # Rotate the HEE coord to the intermediate frame\n    total_matrix = matrix_transpose(_rotation_matrix_hme_to_hee(int_frame))\n    int_repr = heecoord.cartesian.transform(total_matrix)\n    int_coord = int_frame.realize_frame(int_repr)\n\n    # Convert to the HME frame through HCRS\n    return int_coord.transform_to(HCRS(obstime=int_coord.obstime)).transform_to(hmeframe)\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 HeliocentricEarthEcliptic, HeliocentricEarthEcliptic)\n@_transformation_debug(\"HEE->HEE\")\ndef hee_to_hee(from_coo, to_frame):\n    \"\"\"\n    Convert between two Heliocentric Earth Ecliptic frames.\n    \"\"\"\n    if _times_are_equal(from_coo.obstime, to_frame.obstime):\n        return to_frame.realize_frame(from_coo.data)\n    elif to_frame.obstime is None:\n        return from_coo\n    else:\n        return from_coo.transform_to(HCRS(obstime=from_coo.obstime)).transform_to(to_frame)\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 HeliocentricEarthEcliptic, GeocentricSolarEcliptic)\n@_transformation_debug(\"HEE->GSE\")\ndef hee_to_gse(heecoord, gseframe):\n    \"\"\"\n    Convert from Heliocentric Earth Ecliptic to Geocentric Solar Ecliptic\n    \"\"\"\n    # First transform the HEE coord to the GSE obstime\n    int_coord = _transform_obstime(heecoord, gseframe.obstime)\n\n    if int_coord.obstime is None:\n        raise ConvertError(\"To perform this transformation, the coordinate\"\n                           \" frame needs a specified `obstime`.\")\n\n    # Import here to avoid a circular import\n    from .sun import earth_distance\n\n    # Find the Earth-object vector in the intermediate frame\n    sun_earth_int = earth_distance(int_coord.obstime) * CartesianRepresentation(1, 0, 0)\n    earth_object_int = int_coord.cartesian - sun_earth_int\n\n    # Flip the vector in X and Y, but leave Z untouched\n    # (The additional transpose operations are to handle both scalar and array inputs)\n    newrepr = CartesianRepresentation((earth_object_int.xyz.T * [-1, -1, 1]).T)\n\n    return gseframe._replicate(newrepr, obstime=int_coord.obstime)\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 GeocentricSolarEcliptic, HeliocentricEarthEcliptic)\n@_transformation_debug(\"GSE->HEE\")\ndef gse_to_hee(gsecoord, heeframe):\n    \"\"\"\n    Convert from Geocentric Solar Ecliptic to Heliocentric Earth Ecliptic\n    \"\"\"\n    # First transform the GSE coord to the HEE obstime\n    int_coord = _transform_obstime(gsecoord, heeframe.obstime)\n\n    if int_coord.obstime is None:\n        raise ConvertError(\"To perform this transformation, the coordinate\"\n                           \" frame needs a specified `obstime`.\")\n\n    # Import here to avoid a circular import\n    from .sun import earth_distance\n\n    # Find the Sun-object vector in the intermediate frame\n    earth_sun_int = earth_distance(int_coord.obstime) * CartesianRepresentation(1, 0, 0)\n    sun_object_int = int_coord.cartesian - earth_sun_int\n\n    # Flip the vector in X and Y, but leave Z untouched\n    # (The additional transpose operations are to handle both scalar and array inputs)\n    newrepr = CartesianRepresentation((sun_object_int.xyz.T * [-1, -1, 1]).T)\n\n    return heeframe._replicate(newrepr, obstime=int_coord.obstime)\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 GeocentricSolarEcliptic, GeocentricSolarEcliptic)\n@_transformation_debug(\"GSE->GSE\")\ndef gse_to_gse(from_coo, to_frame):\n    \"\"\"\n    Convert between two Geocentric Solar Ecliptic frames.\n    \"\"\"\n    if _times_are_equal(from_coo.obstime, to_frame.obstime):\n        return to_frame.realize_frame(from_coo.data)\n    else:\n        heecoord = from_coo.transform_to(HeliocentricEarthEcliptic(obstime=from_coo.obstime))\n        return heecoord.transform_to(to_frame)\n\n\ndef _rotation_matrix_hgs_to_hci(obstime):\n    \"\"\"\n    Return the rotation matrix from HGS to HCI at the same observation time\n    \"\"\"\n    z_axis = CartesianRepresentation(0, 0, 1)*u.m\n    if not obstime.isscalar:\n        z_axis = z_axis._apply('repeat', obstime.size)\n\n    # Get the ecliptic pole in HGS\n    ecliptic_pole = HeliocentricMeanEcliptic(z_axis, obstime=obstime, equinox=_J2000)\n    ecliptic_pole_hgs = ecliptic_pole.transform_to(HeliographicStonyhurst(obstime=obstime))\n\n    # Rotate the ecliptic pole to the -YZ plane, which aligns the solar ascending node with the X\n    # axis\n    rot_matrix = _rotation_matrix_reprs_to_xz_about_z(ecliptic_pole_hgs.cartesian)\n    xz_to_yz_matrix = rotation_matrix(-90*u.deg, 'z')\n\n    return xz_to_yz_matrix @ rot_matrix\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 HeliographicStonyhurst, HeliocentricInertial)\n@_transformation_debug(\"HGS->HCI\")\ndef hgs_to_hci(hgscoord, hciframe):\n    \"\"\"\n    Convert from Heliographic Stonyhurst to Heliocentric Inertial\n    \"\"\"\n\n    hgscoord = hgscoord.make_3d()\n\n    # First transform the HGS coord to the HCI obstime\n    int_coord = _transform_obstime(hgscoord, hciframe.obstime)\n\n    if int_coord.obstime is None:\n        raise ConvertError(\"To perform this transformation, the coordinate\"\n                           \" frame needs a specified `obstime`.\")\n\n    # Rotate from HGS to HCI\n    total_matrix = _rotation_matrix_hgs_to_hci(int_coord.obstime)\n    newrepr = int_coord.cartesian.transform(total_matrix)\n\n    return hciframe._replicate(newrepr, obstime=int_coord.obstime)\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 HeliocentricInertial, HeliographicStonyhurst)\n@_transformation_debug(\"HCI->HGS\")\ndef hci_to_hgs(hcicoord, hgsframe):\n    \"\"\"\n    Convert from Heliocentric Inertial to Heliographic Stonyhurst\n    \"\"\"\n    # First transform the HCI coord to the HGS obstime\n    int_coord = _transform_obstime(hcicoord, hgsframe.obstime)\n\n    if int_coord.obstime is None:\n        raise ConvertError(\"To perform this transformation, the coordinate\"\n                           \" frame needs a specified `obstime`.\")\n\n    # Rotate from HCI to HGS\n    total_matrix = matrix_transpose(_rotation_matrix_hgs_to_hci(int_coord.obstime))\n    newrepr = int_coord.cartesian.transform(total_matrix)\n\n    return hgsframe._replicate(newrepr, obstime=int_coord.obstime)\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 HeliocentricInertial, HeliocentricInertial)\n@_transformation_debug(\"HCI->HCI\")\ndef hci_to_hci(from_coo, to_frame):\n    \"\"\"\n    Convert between two Heliocentric Inertial frames.\n    \"\"\"\n    if _times_are_equal(from_coo.obstime, to_frame.obstime):\n        return to_frame.realize_frame(from_coo.data)\n    else:\n        return from_coo.transform_to(HeliographicStonyhurst(obstime=from_coo.obstime)).\\\n            transform_to(to_frame)\n\n\ndef _rotation_matrix_obliquity(time):\n    \"\"\"\n    Return the rotation matrix from Earth equatorial to ecliptic coordinates\n    \"\"\"\n    return rotation_matrix(erfa.obl06(*get_jd12(time, 'tt'))*u.radian, 'x')\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 HeliocentricMeanEcliptic, GeocentricEarthEquatorial)\n@_transformation_debug(\"HME->GEI\")\ndef hme_to_gei(hmecoord, geiframe):\n    \"\"\"\n    Convert from Heliocentric Mean Ecliptic to Geocentric Earth Equatorial\n    \"\"\"\n    if geiframe.obstime is None:\n        raise ConvertError(\"To perform this transformation, the coordinate\"\n                           \" frame needs a specified `obstime`.\")\n\n    # Use an intermediate frame of HME at the GEI observation time, through HCRS\n    int_frame = HeliocentricMeanEcliptic(obstime=geiframe.obstime, equinox=geiframe.equinox)\n    int_coord = hmecoord.transform_to(HCRS(obstime=int_frame.obstime)).transform_to(int_frame)\n\n    # Get the Sun-Earth vector in the intermediate frame\n    sun_earth = HCRS(_sun_earth_icrf(int_frame.obstime), obstime=int_frame.obstime)\n    sun_earth_int = sun_earth.transform_to(int_frame).cartesian\n\n    # Find the Earth-object vector in the intermediate frame\n    earth_object_int = int_coord.cartesian - sun_earth_int\n\n    # Rotate from ecliptic to Earth equatorial\n    rot_matrix = matrix_transpose(_rotation_matrix_obliquity(int_frame.equinox))\n    newrepr = earth_object_int.transform(rot_matrix)\n\n    return geiframe.realize_frame(newrepr)\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 GeocentricEarthEquatorial, HeliocentricMeanEcliptic)\n@_transformation_debug(\"GEI->HME\")\ndef gei_to_hme(geicoord, hmeframe):\n    \"\"\"\n    Convert from Geocentric Earth Equatorial to Heliocentric Mean Ecliptic\n    \"\"\"\n    if geicoord.obstime is None:\n        raise ConvertError(\"To perform this transformation, the coordinate\"\n                           \" frame needs a specified `obstime`.\")\n\n    # Use an intermediate frame of HME at the GEI observation time\n    int_frame = HeliocentricMeanEcliptic(obstime=geicoord.obstime, equinox=geicoord.equinox)\n\n    # Get the Sun-Earth vector in the intermediate frame\n    sun_earth = HCRS(_sun_earth_icrf(int_frame.obstime), obstime=int_frame.obstime)\n    sun_earth_int = sun_earth.transform_to(int_frame).cartesian\n\n    # Rotate from Earth equatorial to ecliptic\n    rot_matrix = _rotation_matrix_obliquity(int_frame.equinox)\n    earth_object_int = geicoord.cartesian.transform(rot_matrix)\n\n    # Find the Sun-object vector in the intermediate frame\n    sun_object_int = sun_earth_int + earth_object_int\n    int_coord = int_frame.realize_frame(sun_object_int)\n\n    # Convert to the final frame through HCRS\n    return int_coord.transform_to(HCRS(obstime=int_coord.obstime)).transform_to(hmeframe)\n\n\n@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,\n                                 GeocentricEarthEquatorial, GeocentricEarthEquatorial)\n@_transformation_debug(\"GEI->GEI\")\ndef gei_to_gei(from_coo, to_frame):\n    \"\"\"\n    Convert between two Geocentric Earth Equatorial frames.\n    \"\"\"\n    if _times_are_equal(from_coo.equinox, to_frame.equinox) and \\\n       _times_are_equal(from_coo.obstime, to_frame.obstime):\n        return to_frame.realize_frame(from_coo.data)\n    else:\n        return from_coo.transform_to(HCRS(obstime=from_coo.obstime)).transform_to(to_frame)\n\n\ndef _make_sunpy_graph():\n    \"\"\"\n    Culls down the full transformation graph for SunPy purposes and returns the string version\n    \"\"\"\n    # Frames to keep in the transformation graph\n    keep_list = ['icrs', 'hcrs', 'heliocentrictrueecliptic', 'heliocentricmeanecliptic',\n                 'heliographic_stonyhurst', 'heliographic_carrington',\n                 'heliocentric', 'helioprojective',\n                 'heliocentricearthecliptic', 'geocentricsolarecliptic',\n                 'heliocentricinertial', 'geocentricearthequatorial',\n                 'gcrs', 'precessedgeocentric', 'geocentrictrueecliptic', 'geocentricmeanecliptic',\n                 'cirs', 'altaz', 'itrs']\n\n    small_graph = deepcopy(frame_transform_graph)\n    cull_list = [name for name in small_graph.get_names() if name not in keep_list]\n    cull_frames = [small_graph.lookup_name(name) for name in cull_list]\n\n    for frame in cull_frames:\n        # Remove the part of the graph where the unwanted frame is the source frame\n        if frame in small_graph._graph:\n            del small_graph._graph[frame]\n\n        # Remove all instances of the unwanted frame as the destination frame\n        for entry in small_graph._graph:\n            if frame in small_graph._graph[entry]:\n                del (small_graph._graph[entry])[frame]\n\n    # Clean up the node list\n    for name in cull_list:\n        small_graph._cached_names.pop(name)\n\n    _add_astropy_node(small_graph)\n\n    docstr = make_transform_graph_docs(small_graph)\n\n    # Make adjustments to the graph\n    docstr = _tweak_graph(docstr)\n\n    return docstr\n\n\ndef _add_astropy_node(graph):\n    \"\"\"\n    Add an 'Astropy' node that links to an ICRS node in the graph\n    \"\"\"\n    class Astropy(BaseCoordinateFrame):\n        name = \"REPLACE\"\n\n    @graph.transform(FunctionTransform, Astropy, ICRS)\n    def fake_transform1():\n        pass\n\n    @graph.transform(FunctionTransform, ICRS, Astropy)\n    def fake_transform2():\n        pass\n\n\ndef _tweak_graph(docstr):\n    # Remove Astropy's diagram description\n    output = docstr[docstr.find('.. Wrap the graph'):]\n\n    # Change the Astropy node\n    output = output.replace('Astropy [shape=oval label=\"Astropy\\\\n`REPLACE`\"]',\n                            'Astropy [shape=box3d style=filled fillcolor=lightcyan '\n                            'label=\"Other frames\\\\nin Astropy\"]')\n\n    # Change the Astropy<->ICRS links to black\n    output = output.replace('ICRS -> Astropy[  color = \"#783001\" ]',\n                            'ICRS -> Astropy[  color = \"#000000\" ]')\n    output = output.replace('Astropy -> ICRS[  color = \"#783001\" ]',\n                            'Astropy -> ICRS[  color = \"#000000\" ]')\n\n    # Set the nodes to be filled and cyan by default\n    output = output.replace('AstropyCoordinateTransformGraph {',\n                            'AstropyCoordinateTransformGraph {\\n'\n                            '        node [style=filled fillcolor=lightcyan]')\n\n    # Set the nodes for SunPy frames to be white\n    sunpy_frames = ['HeliographicStonyhurst', 'HeliographicCarrington',\n                    'Heliocentric', 'Helioprojective',\n                    'HeliocentricEarthEcliptic', 'GeocentricSolarEcliptic',\n                    'HeliocentricInertial', 'GeocentricEarthEquatorial']\n    for frame in sunpy_frames:\n        output = output.replace(frame + ' [', frame + ' [fillcolor=white ')\n\n    # Set the rank direction to be left->right (as opposed to top->bottom)\n    # Force nodes for ICRS, HCRS, and \"Other frames in Astropy\" to be at the same rank\n    output = output.replace('        overlap=false',\n                            '        overlap=false\\n'\n                            '        rankdir=LR\\n'\n                            '        {rank=same; ICRS; HCRS; Astropy}')\n\n    output = output.replace('<ul>\\n\\n',\n                            '<ul>\\n\\n' +\n                            _add_legend_row('SunPy frames', 'white') +\n                            _add_legend_row('Astropy frames', 'lightcyan'))\n\n    return output\n\n\ndef _add_legend_row(label, color):\n    row = '        <li style=\"list-style: none;\">\\n'\\\n          '            <p style=\"font-size: 12px;line-height: 24px;font-weight: normal;'\\\n          'color: #848484;padding: 0;margin: 0;\">\\n'\\\n          '                <b>' + label + ':</b>\\n'\\\n          '                    <span class=\"dot\" style=\"height: 20px;width: 40px;'\\\n          'background-color: ' + color + ';border-radius: 50%;border: 1px solid black;'\\\n          'display: inline-block;\"></span>\\n'\\\n          '            </p>\\n'\\\n          '        </li>\\n\\n\\n'\n    return row\n", "meta": {"hexsha": "6ae8f34342d15d0235eccb58aca5af671dad23ff", "size": 50328, "ext": "py", "lang": "Python", "max_stars_repo_path": "sunpy/coordinates/transformations.py", "max_stars_repo_name": "Octaves0911/sunpy", "max_stars_repo_head_hexsha": "d3dff03fe6cc404e40f22da90200ffbb3d38c1a7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sunpy/coordinates/transformations.py", "max_issues_repo_name": "Octaves0911/sunpy", "max_issues_repo_head_hexsha": "d3dff03fe6cc404e40f22da90200ffbb3d38c1a7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sunpy/coordinates/transformations.py", "max_forks_repo_name": "Octaves0911/sunpy", "max_forks_repo_head_hexsha": "d3dff03fe6cc404e40f22da90200ffbb3d38c1a7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.559042114, "max_line_length": 127, "alphanum_fraction": 0.6952591003, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 12307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.2538610069692489, "lm_q1q2_score": 0.1749878179867125}}
{"text": "# ============================================================================\n# 付録 I 電気ヒートポンプ・ガス瞬間式併用型給湯温水暖房機\n#    （給湯熱源：電気ヒートポンプ・ガス瞬間式併用、暖房熱源：電気ヒートポンプ・ガス瞬間式併用）\n# ============================================================================\n\n\nimport numpy as np\n\n\n# ============================================================================\n# I.2 消費電力量\n# ============================================================================\n\n\ndef calc_E_E_hs_d_t(L_HWH, hybrid_category, theta_ex_d_Ave_d, L_dashdash_k_d_t, L_dashdash_s_d_t, L_dashdash_w_d_t,\n                    L_dashdash_b2_d_t,\n                    L_dashdash_ba2_d_t):\n    \"\"\"# 1時間当たりの給湯機の消費電力量 (1)\n\n    Args:\n      L_HWH(ndarray): 1日当たりの温水暖房の熱負荷 (MJ/d)\n      hybrid_category(str): 電気ヒートポンプ・ガス瞬間式併用型給湯温水暖房機の区分\n      theta_ex_d_Ave_d(ndarray): 日平均外気温度 (℃)\n      L_dashdash_k_d_t(ndarray): 1時間当たりの台所水栓における太陽熱補正給湯熱負荷 (MJ/h)\n      L_dashdash_s_d_t(ndarray): 1時間当たりの浴室シャワー水栓における太陽熱補正給湯熱負荷 (MJ/h)\n      L_dashdash_w_d_t(ndarray): 1時間当たりの洗面水栓における太陽熱補正給湯熱負荷 (MJ/h)\n      L_dashdash_b2_d_t(ndarray): 1時間当たりの浴槽追焚時における太陽熱補正給湯熱負荷 (MJ/h)\n      L_dashdash_ba2_d_t(ndarray): 1時間当たりの浴槽追焚時における太陽熱補正給湯熱負荷 (MJ/h)\n\n    Returns:\n      ndarray: 1時間当たりの給湯機の消費電力量 (kWh/h)\n\n    \"\"\"\n    # 1日当たりの太陽熱補正給湯熱負荷\n    L_dashdash_k_d = get_L_dashdash_k_d(L_dashdash_k_d_t)\n    L_dashdash_s_d = get_L_dashdash_s_d(L_dashdash_s_d_t)\n    L_dashdash_w_d = get_L_dashdash_w_d(L_dashdash_w_d_t)\n    L_dashdash_b2_d = get_L_dashdash_b2_d(L_dashdash_b2_d_t)\n    L_dashdash_ba2_d = get_L_dashdash_ba2_d(L_dashdash_ba2_d_t)\n\n    E_E_hs_d = calc_E_E_hs_d(L_HWH, hybrid_category, theta_ex_d_Ave_d, L_dashdash_k_d, L_dashdash_s_d, L_dashdash_w_d,\n                             L_dashdash_b2_d, L_dashdash_ba2_d)\n\n    # 1日当たりの太陽熱補正給湯熱負荷、給湯機の消費電力量の配列要素を1時間ごとに引き延ばす(合計値は24倍になることに注意)\n    E_E_hs_d = np.repeat(E_E_hs_d, 24)\n    L_dashdash_k_d = np.repeat(L_dashdash_k_d, 24)\n    L_dashdash_s_d = np.repeat(L_dashdash_s_d, 24)\n    L_dashdash_w_d = np.repeat(L_dashdash_w_d, 24)\n    L_dashdash_b2_d = np.repeat(L_dashdash_b2_d, 24)\n    L_dashdash_ba2_d = np.repeat(L_dashdash_ba2_d, 24)\n\n    E_E_hs_d_t = np.zeros(24 * 365)\n\n    # (1-1) 太陽熱補正給湯熱負荷が発生しない日 => 24時間で単純分割\n    f1 = (L_dashdash_k_d + L_dashdash_s_d + L_dashdash_w_d + L_dashdash_b2_d + L_dashdash_ba2_d == 0)\n    E_E_hs_d_t[f1] = E_E_hs_d[f1] / 24\n\n    # (1-2) 太陽熱補正給湯熱負荷が発生する日 => 負荷で按分\n    f2 = (L_dashdash_k_d + L_dashdash_s_d + L_dashdash_w_d + L_dashdash_b2_d + L_dashdash_ba2_d > 0)\n    E_E_hs_d_t[f2] = E_E_hs_d[f2] * (\n            L_dashdash_k_d_t[f2] + L_dashdash_s_d_t[f2] + L_dashdash_w_d_t[f2] + L_dashdash_b2_d_t[f2] +\n            L_dashdash_ba2_d_t[f2]) / (\n                             L_dashdash_k_d[f2] + L_dashdash_s_d[f2] + L_dashdash_w_d[f2] + L_dashdash_b2_d[f2] +\n                             L_dashdash_ba2_d[f2])\n\n    return E_E_hs_d_t\n\n\ndef calc_E_E_hs_d(L_HWH, hybrid_category, theta_ex_d_Ave_d, L_dashdash_k_d, L_dashdash_s_d, L_dashdash_w_d,\n                  L_dashdash_b2_d,\n                  L_dashdash_ba2_d):\n    \"\"\"# 1日当たりの給湯機の消費電力量 (2)\n\n    Args:\n      L_HWH(ndarray): 1日当たりの温水暖房の熱負荷 (MJ/d)\n      hybrid_category(str): 電気ヒートポンプ・ガス瞬間式併用型給湯温水暖房機の区分\n      theta_ex_d_Ave_d(ndarray): 日平均外気温度 (℃)\n      L_dashdash_k_d(ndarray): 1日当たりの台所水栓における太陽熱補正給湯熱負荷 (MJ/d)\n      L_dashdash_s_d(ndarray): 1日当たりの浴室シャワー水栓における太陽熱補正給湯熱負荷 (MJ/d)\n      L_dashdash_w_d(ndarray): 1日当たりの洗面水栓における太陽熱補正給湯熱負荷 (MJ/d)\n      L_dashdash_b2_d(ndarray): 1日当たりの浴槽追焚時における太陽熱補正給湯熱負荷 (MJ/d)\n      L_dashdash_ba2_d(ndarray): 1日当たりの浴槽追焚時における太陽熱補正給湯熱負荷 (MJ/d)\n\n    Returns:\n      ndarray: 1日当たりの給湯機の消費電力量 (kWh/d)\n\n    \"\"\"\n    # 係数\n    a_1, a_2, a_3, a_4 = get_coeff_a(L_HWH, hybrid_category)\n\n    # デフロスト係数\n    C_E_def_d = get_C_E_def_d(theta_ex_d_Ave_d)\n\n    E_E_hs_d = ((a_1 * theta_ex_d_Ave_d + a_2 * (\n            L_dashdash_k_d + L_dashdash_s_d + L_dashdash_w_d + L_dashdash_b2_d) + a_3 * L_HWH + a_4) * C_E_def_d\n                + (0.01723 * L_dashdash_ba2_d + 0.06099)) * 10 ** 3 / 3600\n\n    return E_E_hs_d\n\n\ndef get_coeff_a(L_HWH, hybrid_category):\n    \"\"\"# 係数a_1, a_2, a_3, a_4\n\n    Args:\n      L_HWH(ndarray): 1日当たりの温水暖房の熱負荷 (MJ/d)\n      hybrid_category(str): 電気ヒートポンプ・ガス瞬間式併用型給湯温水暖房機の区分\n\n    Returns:\n      tuple: 係数a_1, a_2, a_3, a_4\n\n    \"\"\"\n\n    a_1 = np.zeros(365)\n    a_2 = np.zeros(365)\n    a_3 = np.zeros(365)\n    a_4 = np.zeros(365)\n    if hybrid_category == '区分1':\n        a_1[L_HWH > 0] = get_table_i_3()[0][0]\n        a_1[L_HWH == 0] = get_table_i_3()[0][2]\n        a_2[L_HWH > 0] = get_table_i_3()[1][0]\n        a_2[L_HWH == 0] = get_table_i_3()[1][2]\n        a_3[L_HWH > 0] = get_table_i_3()[2][0]\n        a_3[L_HWH == 0] = get_table_i_3()[2][2]\n        a_4[L_HWH > 0] = get_table_i_3()[3][0]\n        a_4[L_HWH == 0] = get_table_i_3()[3][2]\n    elif hybrid_category == '区分2':\n        a_1[L_HWH > 0] = get_table_i_3()[0][1]\n        a_1[L_HWH == 0] = get_table_i_3()[0][3]\n        a_2[L_HWH > 0] = get_table_i_3()[1][1]\n        a_2[L_HWH == 0] = get_table_i_3()[1][3]\n        a_3[L_HWH > 0] = get_table_i_3()[2][1]\n        a_3[L_HWH == 0] = get_table_i_3()[2][3]\n        a_4[L_HWH > 0] = get_table_i_3()[3][1]\n        a_4[L_HWH == 0] = get_table_i_3()[3][3]\n    else:\n        raise ValueError(hybrid_category)\n    return a_1, a_2, a_3, a_4\n\ndef get_table_i_3():\n    \"\"\"表I.3 式(1)における係数\n\n    Args:\n\n    Returns:\n      list: 表I.3 式(1)における係数\n\n    \"\"\"\n    # 表I.3 式(1)における係数\n    table_i_3 = [\n        (-0.51375, -0.57722, -0.18114, -0.30429),\n        (-0.01782, 0.03865, 0.10483, 0.08497),\n        (0.27640, 0.18173, 0.0, 0.0),\n        (9.40671, 15.30711, 5.85285, 10.66158)\n    ]\n    return table_i_3\n\ndef get_C_E_def_d(theta_ex_d_Ave_d):\n    \"\"\"1日当たりのデフロスト運転による消費電力量の補正係数 (3)\n\n    Args:\n      theta_ex_d_Ave_d: 日平均外気温度 (℃)\n\n    Returns:\n      ndarray: 1日当たりのデフロスト運転による消費電力量の補正係数 (3)\n\n    \"\"\"\n    C_E_def_d = np.ones(365)\n\n    f = theta_ex_d_Ave_d < 7\n    C_E_def_d[f] = 1 + (7 - theta_ex_d_Ave_d[f]) * 0.0091\n\n    return C_E_def_d\n\n\n# ============================================================================\n# I.3 ガス消費量\n# ============================================================================\n\n\ndef calc_E_G_hs_d_t(L_HWH, hybrid_category, Theta_ex_Ave, L_dashdash_k_d_t, L_dashdash_s_d_t, L_dashdash_w_d_t, L_dashdash_b2_d_t,\n                   L_dashdash_ba2_d_t):\n    \"\"\"# 1時間当たりの給湯機のガス消費量 (4)\n\n    Args:\n      L_HWH(ndarray): 1日当たりの温水暖房の熱負荷 (MJ/d)\n      hybrid_category(str): 電気ヒートポンプ・ガス瞬間式併用型給湯温水暖房機の区分\n      Theta_ex_Nave: 夜間平均外気温 (℃)\n      L_dashdash_k_d_t(ndarray): 1時間当たりの台所水栓における節湯補正給湯熱負荷 (MJ/hd)\n      L_dashdash_s_d_t(ndarray): 1時間当たりの浴室シャワー水栓における節湯補正給湯熱負荷 (MJ/hd)\n      L_dashdash_w_d_t(ndarray): 1時間当たりの洗面水栓における節湯補正給湯熱負荷 (MJ/h)\n      L_dashdash_b2_d_t(ndarray): 1時間当たりの浴槽追焚時における節湯補正給湯熱負荷 (MJ/h)\n      L_dashdash_ba2_d_t(ndarray): 1時間当たりの浴槽追焚時における節湯補正給湯熱負荷 (MJ/h)\n      Theta_ex_Ave: returns: 1時間当たりの給湯機のガス消費量  (MJ/h)\n\n    Returns:\n      ndarray: 1時間当たりの給湯機のガス消費量  (MJ/h)\n\n    \"\"\"\n\n    # 1日当たりの太陽熱補正給湯熱負荷\n    L_dashdash_k_d = get_L_dashdash_k_d(L_dashdash_k_d_t)\n    L_dashdash_s_d = get_L_dashdash_s_d(L_dashdash_s_d_t)\n    L_dashdash_w_d = get_L_dashdash_w_d(L_dashdash_w_d_t)\n    L_dashdash_b2_d = get_L_dashdash_b2_d(L_dashdash_b2_d_t)\n    L_dashdash_ba2_d = get_L_dashdash_ba2_d(L_dashdash_ba2_d_t)\n\n    # 1日当たりの給湯機のガス消費量 (5)\n    E_G_hs_d = calc_E_G_hs_d(L_HWH, hybrid_category, Theta_ex_Ave, L_dashdash_k_d, L_dashdash_s_d, L_dashdash_w_d, L_dashdash_b2_d,\n               L_dashdash_ba2_d)\n\n    # 1日当たりの太陽熱補正給湯熱負荷、給湯機のガス消費量の配列要素を1時間ごとに引き延ばす(合計値は24倍になることに注意)\n    E_G_hs_d = np.repeat(E_G_hs_d, 24)\n    L_dashdash_k_d = np.repeat(L_dashdash_k_d, 24)\n    L_dashdash_s_d = np.repeat(L_dashdash_s_d, 24)\n    L_dashdash_w_d = np.repeat(L_dashdash_w_d, 24)\n    L_dashdash_b2_d = np.repeat(L_dashdash_b2_d, 24)\n    L_dashdash_ba2_d = np.repeat(L_dashdash_ba2_d, 24)\n\n    E_G_hs_d_t = np.zeros(24 * 365)\n\n    # (4-1) 太陽熱補正給湯熱負荷が発生しない日 => 24時間で単純分割\n    f1 = (L_dashdash_k_d + L_dashdash_s_d + L_dashdash_w_d + L_dashdash_b2_d + L_dashdash_ba2_d == 0)\n    E_G_hs_d_t[f1] = E_G_hs_d[f1] / 24\n\n    # (4-2) 太陽熱補正給湯熱負荷が発生する日 => 負荷で按分\n    f2 = (L_dashdash_k_d + L_dashdash_s_d + L_dashdash_w_d + L_dashdash_b2_d + L_dashdash_ba2_d > 0)\n    E_G_hs_d_t[f2] = E_G_hs_d[f2] * (\n            L_dashdash_k_d_t[f2] + L_dashdash_s_d_t[f2] + L_dashdash_w_d_t[f2] + L_dashdash_b2_d_t[f2] +\n            L_dashdash_ba2_d_t[f2]) / (\n                             L_dashdash_k_d[f2] + L_dashdash_s_d[f2] + L_dashdash_w_d[f2] + L_dashdash_b2_d[f2] +\n                             L_dashdash_ba2_d[f2])\n\n    return E_G_hs_d_t\n\ndef calc_E_G_hs_d(L_HWH, hybrid_category, Theta_ex_Ave, L_dashdash_k_d, L_dashdash_s_d, L_dashdash_w_d, L_dashdash_b2_d,\n               L_dashdash_ba2_d):\n    \"\"\"# 1日当たりの給湯機のガス消費量 (5)\n\n    Args:\n      L_HWH(ndarray): 1日当たりの温水暖房の熱負荷 (MJ/d)\n      hybrid_category(str): 電気ヒートポンプ・ガス瞬間式併用型給湯温水暖房機の区分\n      Theta_ex_Ave(ndarray): 夜間平均外気温 (℃)\n      L_dashdash_k_d(ndarray): 1日当たりの台所水栓における節湯補正給湯熱負荷 (MJ/d)\n      L_dashdash_s_d(ndarray): 1日当たりの浴室シャワー水栓における節湯補正給湯熱負荷 (MJ/d)\n      L_dashdash_w_d(ndarray): 1日当たりの洗面水栓における節湯補正給湯熱負荷 (MJ/d)\n      L_dashdash_b2_d(ndarray): 1日当たりの浴槽追焚時における節湯補正給湯熱負荷 (MJ/d)\n      L_dashdash_ba2_d(ndarray): 1日当たりの浴槽追焚時における節湯補正給湯熱負荷 (MJ/d)\n\n    Returns:\n      ndarray: 1日当たりの給湯機のガス消費量  (MJ/d)\n\n    \"\"\"\n    # 係数\n    b_1, b_2, b_3, b_4 = get_coeff_b(L_HWH, hybrid_category)\n\n    # デフロスト係数\n    C_G_def_d = get_C_G_def_d(Theta_ex_Ave)\n\n    # 浴槽追焚時における日平均給湯機効率\n    e_ba2 = get_e_ba2_d(Theta_ex_Ave, L_dashdash_ba2_d)\n\n    return ((b_1 * Theta_ex_Ave + b_2 * (\n            L_dashdash_k_d + L_dashdash_s_d + L_dashdash_w_d + L_dashdash_b2_d) + b_3 * L_HWH + b_4) * C_G_def_d + (\n                    L_dashdash_ba2_d / e_ba2))\n\n\ndef get_coeff_b(L_HWH, hybrid_category):\n    \"\"\"# 係数b_1, b_2, b_3, b_4\n\n    Args:\n      L_HWH(ndarray): 1日当たりの温水暖房の熱負荷 (MJ/d)\n      hybrid_category(str): 電気ヒートポンプ・ガス瞬間式併用型給湯温水暖房機の区分\n\n    Returns:\n      tuple: 係数b_1, b_2, b_3, b_4\n\n    \"\"\"\n\n    b_1 = np.zeros(365)\n    b_2 = np.zeros(365)\n    b_3 = np.zeros(365)\n    b_4 = np.zeros(365)\n    if hybrid_category == '区分1':\n        b_1[L_HWH > 0] = get_table_i_4()[0][0]\n        b_1[L_HWH == 0] = get_table_i_4()[0][2]\n        b_2[L_HWH > 0] = get_table_i_4()[1][0]\n        b_2[L_HWH == 0] = get_table_i_4()[1][2]\n        b_3[L_HWH > 0] = get_table_i_4()[2][0]\n        b_3[L_HWH == 0] = get_table_i_4()[2][2]\n        b_4[L_HWH > 0] = get_table_i_4()[3][0]\n        b_4[L_HWH == 0] = get_table_i_4()[3][2]\n    elif hybrid_category == '区分2':\n        b_1[L_HWH > 0] = get_table_i_4()[0][1]\n        b_1[L_HWH == 0] = get_table_i_4()[0][3]\n        b_2[L_HWH > 0] = get_table_i_4()[1][1]\n        b_2[L_HWH == 0] = get_table_i_4()[1][3]\n        b_3[L_HWH > 0] = get_table_i_4()[2][1]\n        b_3[L_HWH == 0] = get_table_i_4()[2][3]\n        b_4[L_HWH > 0] = get_table_i_4()[3][1]\n        b_4[L_HWH == 0] = get_table_i_4()[3][3]\n    else:\n        raise ValueError(hybrid_category)\n    return b_1, b_2, b_3, b_4\n\ndef get_table_i_4():\n    \"\"\"表I.4 係数\n\n    Args:\n\n    Returns:\n      list: 表I.4 係数\n\n    \"\"\"\n    # 表I.4 係数\n    table_i_4 = [\n        (-0.19841, -0.5782, -0.05770, 0.14061),\n        (1.10632, 0.75066, 0.47525, 0.3227),\n        (0.19307, 0.46244, 0.0, 0.0),\n        (-10.36669, -12.55999, -6.34593, -13.43567)\n    ]\n    return table_i_4\n\ndef get_e_ba2_d(theta_ex_d_Ave_d, L_dashdash_ba2_d):\n    \"\"\"# 浴槽追焚時における日平均給湯機効率 (6)\n\n    Args:\n      theta_ex_d_Ave_d(ndarray): 日平均外気温度 (℃)\n      L_dashdash_ba2_d(ndarray): 1日当たりの浴槽追焚時における太陽熱補正給湯負荷 (MJ/d)\n\n    Returns:\n      ndarray: 浴槽追焚時における日平均給湯機効率 (6)\n\n    \"\"\"\n    # 係数\n    c_1, c_2, c_3 = get_coeff_c()\n\n    e_ba2_d = c_1 * theta_ex_d_Ave_d + c_2 * L_dashdash_ba2_d + c_3\n\n    # 効率が1.0を超えない範囲で\n    e_ba2_d = np.clip(e_ba2_d, None, 1)\n\n    return e_ba2_d\n\n\ndef get_coeff_c():\n    \"\"\"表I.5 係数\n\n    Args:\n\n    Returns:\n      tuple: 表I.5 係数\n\n    \"\"\"\n    # 表I.5 係数\n    table_i_5 = (0.0048, 0.0060, 0.7544)\n    return table_i_5\n\n\ndef get_C_G_def_d(theta_ex_d_Ave_d):\n    \"\"\"# 1日当たりのデフロスト運転によるガス消費量の補正係数 (7)\n\n    Args:\n      theta_ex_d_Ave_d(ndarray): 日平均外気温度 (℃)\n\n    Returns:\n      ndarray: 1日当たりのデフロスト運転によるガス消費量の補正係数 (7)\n\n    \"\"\"\n    C_G_def = np.ones(365)\n\n    f = theta_ex_d_Ave_d < 7\n    C_G_def[f] = 1 + (7 - theta_ex_d_Ave_d[f]) * 0.0205\n\n    return C_G_def\n\n\n# ============================================================================\n# I.4 灯油消費量\n# ============================================================================\n\n\ndef get_E_K_hs_d_t():\n    \"\"\"# 1時間当たりの給湯機の灯油消費量\n\n    Args:\n\n    Returns:\n      ndarray: 1時間当たりの給湯機の灯油消費量\n\n    \"\"\"\n    # 1日当たりの給湯機の灯油消費量は0とする\n    return np.zeros(24*365)\n\n\n# ============================================================================\n# I.5 温水暖房における熱源機の往き温水温度の候補\n# ============================================================================\n\n\ndef get_hotwater_temp_list():\n    \"\"\"# 温水暖房における熱源機の往き温水温度の候補\n\n    Args:\n\n    Returns:\n      温水暖房における熱源機の往き温水温度の候補\n\n    \"\"\"\n    return [60, 40]\n\n\ndef get_L_dashdash_k_d(L_dashdash_k_d_t):\n    \"\"\"# 1日当たりの台所水栓における太陽熱補正給湯熱負荷 (MJ/d)\n\n    Args:\n      L_dashdash_k_d_t(ndarray): 1時間当たりの台所水栓における太陽熱補正給湯熱負荷 (MJ/h)\n\n    Returns:\n      ndarray: 1日当たりの台所水栓における太陽熱補正給湯熱負荷 (MJ/d)\n\n    \"\"\"\n    return np.sum(L_dashdash_k_d_t.reshape((365, 24)), axis=1)\n\n\ndef get_L_dashdash_s_d(L_dashdash_s_d_t):\n    \"\"\"# 1日当たりの浴室シャワー水栓における太陽熱補正給湯負荷 (MJ/d)\n\n    Args:\n      L_dashdash_s_d_t(ndarray): 1時間当たりの浴室シャワー水栓における太陽熱補正給湯負荷 (MJ/h)\n\n    Returns:\n      ndarray: 1日当たりの浴室シャワー水栓における太陽熱補正給湯負荷 (MJ/d)\n\n    \"\"\"\n    return np.sum(L_dashdash_s_d_t.reshape((365, 24)), axis=1)\n\n\ndef get_L_dashdash_w_d(L_dashdash_w_d_t):\n    \"\"\"# 1日当たりの洗面水栓における太陽熱補正給湯負荷 (MJ/d)\n\n    Args:\n      L_dashdash_w_d_t(ndarray): 1時間当たりの洗面水栓における太陽熱補正給湯負荷 (MJ/h)\n\n    Returns:\n      ndarray: 1日当たりの洗面水栓における太陽熱補正給湯負荷 (MJ/d)\n\n    \"\"\"\n    return np.sum(L_dashdash_w_d_t.reshape((365, 24)), axis=1)\n\n\ndef get_L_dashdash_b1_d(L_dashdash_b1_d_t):\n    \"\"\"# 1日当たりの浴槽水栓湯はり時における太陽熱補正給湯負荷 (MJ/d)\n\n    Args:\n      L_dashdash_b1_d_t: 1時間当たりの浴槽水栓湯はり時における太陽熱補正給湯負荷 (MJ/h)\n\n    Returns:\n      ndarray: 1日当たりの浴槽水栓湯はり時における太陽熱補正給湯負荷 (MJ/d)\n\n    \"\"\"\n    return np.sum(L_dashdash_b1_d_t.reshape((365, 24)), axis=1)\n\n\ndef get_L_dashdash_b2_d(L_dashdash_b2_d_t):\n    \"\"\"# 1日当たりの浴槽自動湯はり時における太陽熱補正給湯負荷 (MJ/d)\n\n    Args:\n      L_dashdash_b2_d_t(ndarray): 1時間当たりの浴槽自動湯はり時における太陽熱補正給湯負荷 (MJ/h)\n\n    Returns:\n      ndarray: 1日当たりの浴槽自動湯はり時における太陽熱補正給湯負荷 (MJ/d)\n\n    \"\"\"\n    return np.sum(L_dashdash_b2_d_t.reshape((365, 24)), axis=1)\n\n\ndef get_L_dashdash_ba1_d(L_dashdash_ba1_d_t):\n    \"\"\"# 1日当たりの浴槽水栓さし湯時における太陽熱補正給湯負荷 (MJ/d)\n\n    Args:\n      L_dashdash_ba1_d_t(ndarray): 1時間当たりの浴槽水栓さし湯時における太陽熱補正給湯負荷 (MJ/h)\n\n    Returns:\n      ndarray: 1日当たりの浴槽水栓さし湯時における太陽熱補正給湯負荷 (MJ/d)\n\n    \"\"\"\n    return np.sum(L_dashdash_ba1_d_t.reshape((365, 24)), axis=1)\n\n\ndef get_L_dashdash_ba2_d(L_dashdash_ba2_d_t):\n    \"\"\"# 1日当たりの浴槽追焚時における太陽熱補正給湯負荷 (MJ/d)\n\n    Args:\n      L_dashdash_ba2_d_t(ndarray): 1時間当たりの浴槽追焚時における太陽熱補正給湯負荷 (MJ/h)\n\n    Returns:\n      ndarray: 1日当たりの浴槽追焚時における太陽熱補正給湯負荷 (MJ/d)\n\n    \"\"\"\n    return np.sum(L_dashdash_ba2_d_t.reshape((365, 24)), axis=1)\n", "meta": {"hexsha": "38e2547341a3ce4d37d6affbd4c27aacb1ad9f66", "size": 14965, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/pyhees/section7_1_i.py", "max_stars_repo_name": "jjj-design/pyhees", "max_stars_repo_head_hexsha": "d63e7cd84abfc2f509bc1cd1256598a10aac1825", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pyhees/section7_1_i.py", "max_issues_repo_name": "jjj-design/pyhees", "max_issues_repo_head_hexsha": "d63e7cd84abfc2f509bc1cd1256598a10aac1825", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-01-04T07:29:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T08:02:51.000Z", "max_forks_repo_path": "src/pyhees/section7_1_i.py", "max_forks_repo_name": "jjj-design/pyhees", "max_forks_repo_head_hexsha": "d63e7cd84abfc2f509bc1cd1256598a10aac1825", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-01-19T07:57:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T00:25:54.000Z", "avg_line_length": 29.870259481, "max_line_length": 131, "alphanum_fraction": 0.6206481791, "include": true, "reason": "import numpy", "num_tokens": 7846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.28776782186926264, "lm_q1q2_score": 0.17486590681298303}}
{"text": "# Encoding: UTF-8\n# Copyright (c) Marnik Bercx, University of Antwerp\n# Distributed under the terms of the MIT License\n\nimport itertools\nimport math\nimport json\nimport os\nimport pdb\n\nimport numpy as np\n\nfrom monty.io import zopen\nfrom monty.json import jsanitize, MSONable\nfrom pymatgen.core import Structure, Composition, Molecule, Site, Element\nfrom pymatgen.analysis.chemenv.coordination_environments.voronoi \\\n    import DetailedVoronoiContainer\nfrom pymatgen.io.vasp.outputs import Outcar\nfrom pymatgen.symmetry.analyzer import SpacegroupAnalyzer\nfrom pymatgen.analysis.transition_state import NEBAnalysis\nfrom pymatgen.util.plotting import pretty_plot\n\nscipy_old_piecewisepolynomial = True\ntry:\n    from scipy.interpolate import PiecewisePolynomial\nexcept ImportError:\n    from scipy.interpolate import CubicSpline\n\n    scipy_old_piecewisepolynomial = False\n\n\"\"\"\nModule that contains tools to represent and calculate the properties of\nbattery cathodes.\n\n\"\"\"\n\n__author__ = \"Marnik Bercx\"\n__copyright__ = \"Copyright 2018, Marnik Bercx, University of Antwerp\"\n__version__ = \"0.1\"\n__maintainer__ = \"Marnik Bercx\"\n__email__ = \"marnik.bercx@uantwerpen.be\"\n__date__ = \"May 2018\"\n\n# TODO Currently, the dimers are defined by their indices.\n# This is a consequence of the fact that the DetailedVoronoiContainer\n# expects indices for its neighbor method. Frankly, I would prefer sites as\n# the basis of the dimer definition as well as it's environment.\n\n# Values for determining the neighbors of a site in a voronoi decomposition\nVORONOI_DIST_FACTOR = 1.4\nVORONOI_ANG_FACTOR = 0.6\n\n# Tuple of possible cations. This idea should work fine, considering the\n# fact that these cation elements rarely serve another purpose than being\n# a cation.\nCATIONS = (\"Li\", \"Na\", \"Mg\")\n\n# Tolerance for determining whether two oxygens are on opposite sides of an\n# octahedron. If the angle between the two vectors connecting the site and\n# the corresponding oxygens is larger than this value, the oxygens are\n# considered to be opposites.\nOXYGEN_ANGLE_TOL = math.pi * 9 / 10\n\n# Tolerance for the representation determination. This can be pretty big, since\n# the dimer environment structure is known.\nREPRESENTATION_DIST_TOL = 5e-1\nREPRESENTATION_ANGLE_TOL = 2e-1\n\n# Dimer representation symmetry permutations\nSYMMETRY_PERMUTATIONS = [[1, 2, 4, 3, 6, 5, 8, 7, 9, 10, 11, 12],\n                         [2, 1, 3, 4, 7, 8, 5, 6, 11, 12, 9, 10],\n                         [1, 2, 3, 4, 5, 6, 7, 8, 10, 9, 12, 11],\n                         [2, 1, 4, 3, 8, 7, 6, 5, 11, 12, 9, 10],\n                         [1, 2, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11],\n                         [2, 1, 4, 3, 8, 7, 6, 5, 12, 11, 10, 9],\n                         [2, 1, 3, 4, 7, 8, 5, 6, 12, 11, 10, 9],\n                         [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]\n\n\nclass Cathode(Structure):\n    \"\"\"\n    A class representing a cathode material in a battery.\n\n    The main idea of this class is to keep track of the original sites by\n    using sites with empty Compositions. This is important to make sure that\n    the voronoi decomposition is successful, and hence interesting if we\n    want to look at coordinations and neighbors. Another advantage is that\n    we can consider the empty cation sites for final positions of transition\n    metal migrations.\n\n    \"\"\"\n\n    def __init__(self, lattice, species, coords, charge=None,\n                 validate_proximity=False,\n                 to_unit_cell=False, coords_are_cartesian=False,\n                 site_properties=None):\n\n        super(Cathode, self).__init__(\n            lattice=lattice, species=species, coords=coords,\n            validate_proximity=validate_proximity, to_unit_cell=to_unit_cell,\n            coords_are_cartesian=coords_are_cartesian,\n            site_properties=site_properties\n        )\n\n        self._voronoi = None\n\n    @property\n    def cation_configuration(self):\n        \"\"\"\n        A list of all sites which correspond to cations in the Cathode.\n\n        Returns:\n\n        \"\"\"\n        return [site for site in self.sites if site.species_string in CATIONS]\n\n    @cation_configuration.setter\n    def cation_configuration(self, configuration):\n\n        # TODO Add checks\n\n        # Remove all cations\n        for cation in [cat for cat in CATIONS if Element[cat] in set(\n                self.composition.keys())]:\n            self.replace_species({cation: {cation: 0}})\n\n        # Add the cation sites\n        if isinstance(configuration, dict):\n            for cation in configuration.keys():\n                for index in configuration[cation]:\n                    self.replace(index, cation, properties={\"magmom\": 0})\n\n        elif all([isinstance(item, Site) for item in configuration]):\n            for catsite in configuration:\n                for i, site in enumerate(self):\n                    if np.linalg.norm(site.distance(catsite)) < 0.05:\n                        self.replace(i, catsite.specie,\n                                     properties={\"magmom\": 0})\n\n        else:\n            raise TypeError(\"Cation configurations should be a dictionary \"\n                            \"mapping cations to site indices or a list of \"\n                            \"sites.\")\n\n    def __str__(self):\n        \"\"\"\n        Overwritten string representation, in order to provide information\n        about the cation configuration, as well as the VESTA index, which\n        is useful when defining structural changes.\n\n        \"\"\"\n        outs = [\"Full Formula ({s})\".format(s=self.composition.formula),\n                \"Reduced Formula: {}\".format(self.composition.reduced_formula)]\n        to_s = lambda x: \"%0.6f\" % x\n        outs.append(\"abc   : \" + \" \".join([to_s(i).rjust(10)\n                                           for i in self.lattice.abc]))\n        outs.append(\"angles: \" + \" \".join([to_s(i).rjust(10)\n                                           for i in self.lattice.angles]))\n        if self._charge:\n            if self._charge >= 0:\n                outs.append(\"Overall Charge: +{}\".format(self._charge))\n            else:\n                outs.append(\"Overall Charge: -{}\".format(self._charge))\n        outs.append(\"Sites ({i})\".format(i=len(self)))\n        data = []\n        props = self.site_properties\n        keys = sorted(props.keys())\n        vesta_index = 1\n        for i, site in enumerate(self):\n            if site.species_and_occu.num_atoms == 0:\n                row = [str(i), \"-\", \"Vac\"]\n\n            else:\n                row = [str(i), vesta_index, site.species_string]\n                vesta_index += 1\n\n            row.extend([to_s(j) for j in site.frac_coords])\n            for k in keys:\n                row.append(props[k][i])\n            data.append(row)\n\n        from tabulate import tabulate\n        outs.append(\n            tabulate(data,\n                     headers=[\"#\", \"#VESTA\", \"SP\", \"a\", \"b\", \"c\"] + keys,\n                     ))\n        return \"\\n\".join(outs)\n\n    @property\n    def voronoi(self):\n        \"\"\"\n        ChemEnv voronoi decomposition of the cathode structure.\n\n        Returns:\n            pymatgen.analysis.chemenv.coordination_environments.voronoi.\\\n            DetailedVoronoiContainer\n\n        \"\"\"\n        if self._voronoi is None:\n            self._voronoi = DetailedVoronoiContainer(self)\n\n        return self._voronoi\n\n    @voronoi.setter\n    def voronoi(self, voronoi_container):\n        self._voronoi = voronoi_container\n\n    def add_cations(self, sites=None):\n        \"\"\"\n        Args:\n            sites:\n\n        Returns:\n\n        \"\"\"\n\n        # Add the cation sites\n        if isinstance(sites, dict):\n            for cation in sites.keys():\n                for index in sites[cation]:\n                    self.replace(index, cation, properties={\"magmom\": 0})\n\n        elif all([isinstance(item, Site) for item in sites]):\n            for catsite in sites:\n                for i, site in enumerate(self):\n                    if np.linalg.norm(site.distance(catsite)) < 0.05:\n                        self.replace(i, catsite.specie,\n                                     properties={\"magmom\": 0})\n\n        else:\n            raise TypeError(\"Cation configurations should be a dictionary \"\n                            \"mapping cations to site indices or a list of \"\n                            \"sites.\")\n\n    def remove_cations(self, sites=None):\n        \"\"\"\n        Remove the cations from the cathode, i.e. delithiate the structure in\n        case Li is the cation of the cathode.\n\n        Note that this does not remove the sites from the pymatgen Structure.\n        The occupancy is simply adjusted to an empty Composition object.\n\n        Args:\n            sites: List of indices\n            List of pymatgen.core.Sites which are to be removed.\n\n        \"\"\"\n\n        # TODO add checks\n\n        # If no sites are given\n        if sites is None:\n            # Remove all the cations\n            self.cation_configuration = []\n\n        # If a List of integers is given\n        elif all([isinstance(item, int) for item in sites]):\n            for index in sites:\n                self.replace(index, Composition(), properties={\"magmom\": 0})\n\n        # If a List of sites is given\n        elif all([isinstance(item, Site) for item in sites]):\n            for site in sites:\n                # Check if the provided site corresponds to a cation site\n                if site in self.cation_configuration:\n                    cat_conf = self.cation_configuration.copy()\n                    cat_conf.remove(site)\n                    self.cation_configuration = cat_conf\n                else:\n                    raise Warning(\"Requested site not found in cation \"\n                                  \"configuration.\")\n        else:\n            raise IOError(\"Incorrect site input.\")\n\n    def change_site_distance(self, site_indices, distance):\n        \"\"\"\n        Change the coordinates of two sites in a structure in order to adjust\n        their distance.\n\n        Args:\n            site_indices:\n            distance:\n        \"\"\"\n\n        # TODO Add possibility of site_indices simply being the sites\n\n        site_a = self.sites[site_indices[0]]\n        site_b = self.sites[site_indices[1]]\n\n        # Find the distance between the sites, as well as the image of site B\n        # closest to site A\n        (original_distance, closest_image_b) = site_a.distance_and_image(\n            site_b)\n\n        image_cart_coords = self.lattice.get_cartesian_coords(\n            site_b.frac_coords + closest_image_b\n        )\n\n        # Calculate the vector that connects site A with site B\n        connection_vector = image_cart_coords - site_a.coords\n\n        # Make it a unit vector\n        connection_vector /= np.linalg.norm(connection_vector)\n\n        # Calculate the distance the sites need to be moved.\n        site_move_distance = (original_distance - distance) / 2\n\n        # Calculate the new cartesian coordinates of the sites\n        new_site_a_coords = site_a.coords \\\n                            + site_move_distance * connection_vector\n        new_site_b_coords = site_b.coords \\\n                            - site_move_distance * connection_vector\n\n        # Change the sites in the structure\n        self.replace(i=site_indices[0], species=site_a.species_string,\n                     coords=new_site_a_coords,\n                     coords_are_cartesian=True,\n                     properties=site_a.properties)\n\n        self.replace(i=site_indices[1], species=site_b.species_string,\n                     coords=new_site_b_coords,\n                     coords_are_cartesian=True,\n                     properties=site_b.properties)\n\n    def update_sites(self, directory, ignore_magmom=False):\n        \"\"\"\n        Based on the CONTCAR and OUTCAR of a geometry optimization, update the\n        site coordinates and magnetic moments that were optimized. Note that\n        this method relies on the cation configuration of the cathode not\n        having changed.\n\n        Args:\n            directory (str): Directory in which the geometry optimization\n                output files (i.e. CONTCAR and OUTCAR) are stores.\n            ignore_magmom (bool): Flag that indicates that the final magnetic\n                moments of the optimized structure should be ignored. This means\n                that the magnetic moments of the Cathode structure will\n                remain the same.\n        \"\"\"\n\n        new_cathode = Cathode.from_file(os.path.join(directory, \"CONTCAR\"))\n\n        out = Outcar(os.path.join(directory, \"OUTCAR\"))\n\n        if ignore_magmom:\n            magmom = [site.properties[\"magmom\"] for site in self.sites\n                      if site.species_and_occu != Composition()]\n            new_cathode.add_site_property(\"magmom\", magmom)\n        else:\n            magmom = [site[\"tot\"] for site in out.magnetization]\n            new_cathode.add_site_property(\"magmom\", magmom)\n\n        # Update the lattice\n        self.modify_lattice(new_cathode.lattice)\n\n        # Update the coordinates of the occupied sites.\n        new_index = 0\n        for i, site in enumerate(self):\n\n            # If the site is not empty\n            if site.species_and_occu != Composition():\n                new_site = new_cathode.sites[new_index]\n                # Update the site coordinates\n                self.replace(i, species=new_site.species_and_occu,\n                             coords=new_site.frac_coords,\n                             properties=new_site.properties)\n                new_index += 1\n\n    def find_noneq_cations(self):\n        \"\"\"\n        Find a list of the site indices of all non-equivalent cations.\n\n        Returns:\n            List of site indices\n\n        \"\"\"\n        symmops = SpacegroupAnalyzer(self).get_space_group_operations()\n\n        cation_indices = [\n            index for index in range(len(self.sites))\n            if not self.sites[index].species_string == \"O\"\n        ]\n\n        # Start with adding the first cation\n        inequiv_cations = [cation_indices[0], ]\n\n        for index in cation_indices[1:]:\n\n            s1 = [self.sites[index], ]\n\n            # Check if the site is equivalent with one of the sites in the\n            # inequivalent list.\n            inequivalent = True\n\n            for inequive_index in inequiv_cations:\n\n                s2 = [self.sites[inequive_index], ]\n\n                if symmops.are_symmetrically_equivalent(s1, s2):\n                    inequivalent = False\n\n            if inequivalent:\n                inequiv_cations.append(index)\n\n        return inequiv_cations\n\n    def find_cation_configurations(self):\n        \"\"\"\n        Plan is to find all non-equivalent cation configurations. Is probably\n        already implemented elsewhere.\n\n        Returns:\n\n        \"\"\"\n        raise NotImplementedError\n\n    def set_to_high_spin(self):\n        \"\"\"\n\n        :return:\n        \"\"\"\n        raise NotImplementedError\n\n    def set_to_low_spin(self):\n        \"\"\"\n\n        :return:\n        \"\"\"\n        raise NotImplementedError\n\n    def as_ordered_structure(self):\n        \"\"\"\n        Return the structure as a pymatgen.core.Structure, removing the\n        unoccupied sites. This is because many of the IO methods of pymatgen\n        run into issues when empty occupancies are present.\n\n        Returns:\n            pymatgen.core.Structure\n\n        \"\"\"\n\n        return Structure.from_sites(\n            [site for site in self.sites\n             if site.species_and_occu != Composition()]\n        )\n\n    def to(self, fmt=None, filename=None, **kwargs):\n        \"\"\"\n        Structure method override to solve issue with writing the Cathode to a\n        POSCAR file\n\n        # TODO Figure out what exactly was the problem here again... Should\n        have written this down immediately! I think it had something to do\n        with the order of the Sites changing...\n\n        Args:\n            fmt:\n            filename:\n            **kwargs:\n\n        Returns:\n\n        \"\"\"\n\n        if fmt == \"poscar\":\n            structure = self.as_ordered_structure()\n            return structure.to(fmt, filename, **kwargs)\n\n        else:\n            return super(Cathode, self).to(fmt, filename, **kwargs)\n\n    @classmethod\n    def from_structure(cls, structure):\n        \"\"\"\n        Initializes a Cathode from a pymatgen.core.Structure.\n\n        Args:\n            structure (pymatgen.core.Structure): Structure from which to\n            initialize the Cathode.\n\n        Returns:\n            pybat.core.Structure\n\n        \"\"\"\n\n        return cls.from_sites(structure.sites)\n\n\nclass LiRichCathode(Cathode):\n    \"\"\"\n    A class representing a Li-rich cathode material.\n\n    \"\"\"\n\n    def __init__(self, lattice, species, coords, charge=None,\n                 validate_proximity=False,\n                 to_unit_cell=False, coords_are_cartesian=False,\n                 site_properties=None):\n\n        super(LiRichCathode, self).__init__(\n            lattice=lattice, species=species, coords=coords,\n            validate_proximity=validate_proximity, to_unit_cell=to_unit_cell,\n            coords_are_cartesian=coords_are_cartesian,\n            site_properties=site_properties\n        )\n\n    def find_oxygen_dimers(self, site_index=None,\n                           oxygen_angle_tol=OXYGEN_ANGLE_TOL):\n        \"\"\"\n        Returns a list of index pairs corresponding to the oxygen dimers that\n        can be formed around the site provided by the user, i.e. with oxygens\n        that are neighbours of the provided site.\n\n        Args:\n            site_index:\n\n        Returns:\n\n        \"\"\"\n\n        if site_index is None:\n\n            # TODO This is a lazy way of dealing with this...\n            # Just using the method for single indices and then filtering\n            # duplicates is probably not the fastest implementation. But it\n            # sure is the fastest to implement :P\n\n            oxygen_dimers = set()\n\n            cation_indices = [\n                index for index in range(len(self.sites))\n                if not self.sites[index].species_string == \"O\"\n            ]\n\n            for index in cation_indices:\n                for dimer in self.find_oxygen_dimers(index):\n                    oxygen_dimers.add(dimer)\n\n            return list(oxygen_dimers)\n\n        else:\n\n            # Determine the oxygen neighbors for the provided site\n            oxygen_neighbors_indices = [\n                neighbor[\"index\"] for neighbor\n                in self.voronoi.neighbors(site_index, VORONOI_DIST_FACTOR,\n                                          VORONOI_ANG_FACTOR)\n                if self.sites[neighbor[\"index\"]].species_string == \"O\"\n            ]\n\n            # pdb.set_trace()\n\n            if len(oxygen_neighbors_indices) <= 1:\n                raise ValueError(\"Provided site does not have two oxygen \"\n                                 \"neighbours.\\n\")\n\n            # Find all oxygen neighbour combinations that can form dimers. This\n            # means they are not opposites on the site's octahedron environment.\n            oxygen_dimers = []\n            oxygen_combinations = itertools.combinations(\n                oxygen_neighbors_indices, 2\n            )\n\n            for oxygen_pair in oxygen_combinations:\n\n                site = self.sites[site_index]\n                oxygen_site_A = self.sites[oxygen_pair[0]]\n                oxygen_site_B = self.sites[oxygen_pair[1]]\n\n                oxygen_image_A = site.distance_and_image(oxygen_site_A)[1]\n                oxygen_image_B = site.distance_and_image(oxygen_site_B)[1]\n\n                image_A_cart_coords = oxygen_site_A.coords \\\n                                      + np.dot(oxygen_image_A,\n                                               self.lattice.matrix)\n                image_B_cart_coords = oxygen_site_B.coords \\\n                                      + np.dot(oxygen_image_B,\n                                               self.lattice.matrix)\n\n                oxygen_vector_A = image_A_cart_coords - site.coords\n                oxygen_vector_B = image_B_cart_coords - site.coords\n\n                if angle_between(oxygen_vector_A, oxygen_vector_B) < \\\n                        oxygen_angle_tol:\n                    oxygen_dimers.append(oxygen_pair)\n\n            if len(oxygen_dimers) > 12:\n                raise Warning(\n                    \"Found more than 12 oxygen pairs around a single \"\n                    \"site. This can be caused by the use of a small \"\n                    \"unit cell. Results may not be useful.\")\n\n            return oxygen_dimers\n\n    def remove_dimer_cations(self, dimer_indices):\n        \"\"\"\n\n        Args:\n            dimer_indices:\n\n        Returns:\n\n        \"\"\"\n\n        # Find the sites of the dimer environment\n        dimer_environment = Dimer(self, dimer_indices).sites\n\n        remove_sites = [site for site in dimer_environment\n                        if site.species_string in CATIONS]\n\n        self.remove_cations(remove_sites)\n\n    def find_noneq_dimers(self, site_index=None, method=\"symmops\"):\n        \"\"\"\n        A script that distills the non-equivalent oxygen dimers around a site\n        index.\n\n        In case no site index is provided, the method will loop over all sites\n        which do not correspond to an oxygen.\n\n        Args:\n            site_index (int): Index of the site around which the dimers\n            should be considered.\n            method (str): Method for determining equivalency:\n\n            \"symmops\" - Two dimers are considered when they are\n            symmetrically equivalent, using the symmetry operations of the\n            cathode unit cell.\n\n            \"representation\" - Two dimers are equivalent if their\n            environments are the same, i.e. when they have the same\n            representation.\n\n        Returns:\n            List of Tuples with the dimer indices\n\n        \"\"\"\n\n        ineq_dimers = []\n\n        if method == \"symmops\":\n\n            symmops = SpacegroupAnalyzer(self).get_space_group_operations()\n\n            # If no site is provided, consider all inequivalent cation sites\n            if site_index is None:\n\n                ineq_cations = self.find_noneq_cations()\n\n                for index in ineq_cations:\n\n                    site_dimers = self.find_oxygen_dimers(index)\n\n                    for dimer in site_dimers:\n\n                        d1 = [self.sites[dimer[0]], self.sites[dimer[1]]]\n\n                        inequivalent = True\n\n                        for ineq_dimer in ineq_dimers:\n\n                            d2 = [self.sites[ineq_dimer[0]],\n                                  self.sites[ineq_dimer[1]]]\n\n                            if symmops.are_symmetrically_equivalent(d1, d2):\n                                inequivalent = False\n\n                        if inequivalent:\n                            ineq_dimers.append(dimer)\n\n            # Else only consider the site provided\n            else:\n                site_dimers = self.find_oxygen_dimers(site_index)\n\n                for dimer in site_dimers:\n\n                    d1 = [self.sites[dimer[0]], self.sites[dimer[1]]]\n\n                    inequivalent = True\n\n                    for ineq_dimer in ineq_dimers:\n\n                        d2 = [self.sites[ineq_dimer[0]],\n                              self.sites[ineq_dimer[1]]]\n\n                        if symmops.are_symmetrically_equivalent(d1, d2):\n                            inequivalent = False\n\n                    if inequivalent:\n                        ineq_dimers.append(dimer)\n\n            return ineq_dimers\n\n        elif method == \"representation\":\n            # TODO update this method\n\n            raise NotImplementedError()\n\n            # if site_index is None:\n            #\n            #     ignore = set(CATIONS).union((\"O\",))\n            #\n            #     transition_metal_indices = [index for index in\n            #                                 range(len(self.sites))\n            #                                 if self.sites[index].species_string\n            #                                 not in ignore]\n            #\n            #     for index in transition_metal_indices:\n            #\n            #         dimers = [Dimer(self, dimer_indices) for dimer_indices\n            #                   in self.find_oxygen_dimers(index)]\n            #\n            #         for dimer in dimers:\n            #             if dimer not in noneq_dimers:\n            #                 noneq_dimers.append(dimer)\n            #\n            # else:\n            #\n            #     dimers = [Dimer(self, dimer_indices) for dimer_indices\n            #               in self.find_oxygen_dimers(site_index)]\n            #\n            #     for dimer in dimers:\n            #         if dimer not in noneq_dimers:\n            #             noneq_dimers.append(dimer)\n            #\n            # return noneq_dimers\n\n        else:\n            raise IOError(\"Method for finding non-equivalent dimers is not \"\n                          \"recognized.\")\n\n    def list_noneq_dimers(self):\n        \"\"\"\n        Create a list of lists of equivalent dimers of the various\n        non-equivalent dimers, i.e. group all dimers in the structure in\n        lists of dimers that are equivalent to each other.\n\n        Returns:\n\n        \"\"\"\n\n        symmops = SpacegroupAnalyzer(self).get_space_group_operations()\n\n        dimers = self.find_oxygen_dimers()\n\n        noneq_dimer_lists = [[dimer, ] for dimer in self.find_noneq_dimers()]\n\n        for dimer in dimers:\n\n            d1 = [self.sites[dimer[0]], self.sites[dimer[1]]]\n\n            for noneq_dimer_list in noneq_dimer_lists:\n\n                d2 = [self.sites[noneq_dimer_list[0][0]],\n                      self.sites[noneq_dimer_list[0][1]]]\n\n                if symmops.are_symmetrically_equivalent(d1, d2):\n                    noneq_dimer_list.append(dimer)\n\n        return noneq_dimer_lists\n\n\n# TODO Currently the whole dimer representation only works for the O-O\n# dimers in the O3 stacking. Allowing for different oxygen frameworks will\n# require some more possible representations. One way is to figure out the\n# structure of the molecule and set up the representation for each\n# structure, but I think it would pay off to think if there isn't some\n# better way of checking the equivalency of dimer environments. Moreover,\n# we should probably first test to see if considering only the immediate\n# environment is sufficient.\n\nclass Dimer(MSONable):\n    \"\"\"\n    Class definition of an oxygen dimer in a Li-rich cathode structure.\n\n    \"\"\"\n\n    # TODO Give the definition of this class a good hard thinking over.\n\n    def __init__(self, cathode, dimer_indices):\n        \"\"\"\n        Initialize\n\n        Args:\n            cathode\n            dimer_indices\n\n        Returns:\n            pybat.core.Dimer\n\n        \"\"\"\n        self._cathode = cathode\n        self._indices = tuple(dimer_indices)\n        self._sites = list\n        self._center = None\n        self._representation = list\n\n    def __eq__(self, other):\n        \"\"\"\n        Checks if the dimer environments of two dimers are the same.\n\n\n        Args:\n            other:\n\n        Returns:\n\n        \"\"\"\n        is_equal = False\n\n        for permutation in SYMMETRY_PERMUTATIONS:\n\n            if [self.representation[index] for index in range(1, 13)] == \\\n                    [other.representation[key] for key in permutation]:\n                is_equal = True\n\n        return is_equal\n\n    @property\n    def cathode(self):\n        return self._cathode\n\n    @property\n    def indices(self):\n        return self._indices\n\n    @property\n    def sites(self):\n\n        if self._sites is list:\n            # Find the oxygen neighbours\n            oxygen_a_neighbors = [\n                neighbor[\"index\"] for neighbor\n                in self.cathode.voronoi.neighbors(self.indices[0],\n                                                  VORONOI_DIST_FACTOR,\n                                                  VORONOI_ANG_FACTOR)\n            ]\n            oxygen_b_neighbors = [\n                neighbor[\"index\"] for neighbor\n                in self.cathode.voronoi.neighbors(self.indices[1],\n                                                  VORONOI_DIST_FACTOR,\n                                                  VORONOI_ANG_FACTOR)\n            ]\n\n            # Determine the indices of the oxygen environment. The indices are\n            # sorted in such a way that the oxygen indices come first,\n            # followed by the indices of the shared neighbors.\n            # TODO This can be done better. Really.\n            # TODO Fix issue for small unit cells\n            # The issue for small unit cells is that the oxygen atoms have\n            # more shared neighbors than two according to the voronoi\n            # decomposition, which messes up the assignment of the\n            # environment atoms in the representation. This needs to be fixed.\n            shared_neighbors = tuple(\n                set(oxygen_a_neighbors).intersection(oxygen_b_neighbors)\n            )\n            other_neighbors = set(oxygen_a_neighbors).union(oxygen_b_neighbors)\n            other_neighbors.remove(shared_neighbors[0])\n            other_neighbors.remove(shared_neighbors[1])\n            other_neighbors = tuple(other_neighbors)\n\n            dimer_environment_indices = self._indices + shared_neighbors \\\n                                        + other_neighbors\n\n            # Recover the corresponding sites\n            self._sites = [self.cathode.sites[index] for index\n                           in dimer_environment_indices]\n\n        return self._sites\n\n    @property\n    def center(self):\n\n        if self._center is None:\n\n            # Find the center of the oxygen sites\n            oxygen_sites = []\n            for site in self.sites:\n                if site.species_string == \"O\":\n                    oxygen_sites.append(site)\n\n            (distance, oxygen_image) = oxygen_sites[0].distance_and_image(\n                oxygen_sites[1])\n\n            image_cart_coords = oxygen_sites[1].coords \\\n                                + np.dot(oxygen_image,\n                                         self.cathode.lattice.matrix)\n\n            self._center = (oxygen_sites[0].coords + image_cart_coords) / 2\n\n        return self._center\n\n    @property\n    def representation(self):\n        if self._representation is list:\n\n            # A representation # TODO Add definition\n\n            # The representation idea seems like the fastest way of being able\n            # to compare two dimers. By reducing them to a representation, we\n            # are able compare dimers by applying permutations that represent\n            # symmetry transformations. This is not a very general approach,\n            # clearly.\n\n            # Note that the sites property is built in such a way that the\n            # first two sites correspond to the oxygen atoms and the next two\n            # correspond to the shared neighbours. This convention is made to\n            # save us some work here.\n\n            dimer_molecule = self.get_dimer_molecule()\n\n            oxy_1 = dimer_molecule.sites[0]\n            oxy_2 = dimer_molecule.sites[1]\n\n            shared_neighbor_3 = dimer_molecule.sites[2]\n            shared_neighbor_4 = dimer_molecule.sites[3]\n\n            # The representation is defined as a dictionary between site\n            # numbers and dimer environment sites\n            representation = {1: oxy_1.species_and_occu,\n                              2: oxy_2.species_and_occu,\n                              3: shared_neighbor_3.species_and_occu,\n                              4: shared_neighbor_4.species_and_occu}\n\n            # TODO Find a cleaner way of assigning representation positions\n\n            # Loop over the remaining sites to find their representation\n            # positions\n            for site in dimer_molecule.sites[4:]:\n\n                # Find the sites which are in the plane of the oxygens and\n                # their shared neighbors.\n                if np.linalg.norm(oxy_1.coords\n                                  - (\n                                          shared_neighbor_4.coords - oxy_1.coords)\n                                  - site.coords) < REPRESENTATION_DIST_TOL:\n                    representation[5] = site.species_and_occu\n\n                if np.linalg.norm(oxy_1.coords\n                                  - (\n                                          shared_neighbor_3.coords - oxy_1.coords)\n                                  - site.coords) < REPRESENTATION_DIST_TOL:\n                    representation[6] = site.species_and_occu\n\n                if np.linalg.norm(oxy_2.coords\n                                  - (\n                                          shared_neighbor_4.coords - oxy_2.coords)\n                                  - site.coords) < REPRESENTATION_DIST_TOL:\n                    representation[7] = site.species_and_occu\n\n                if np.linalg.norm(oxy_2.coords\n                                  - (\n                                          shared_neighbor_3.coords - oxy_2.coords) \\\n                                  - site.coords) < REPRESENTATION_DIST_TOL:\n                    representation[8] = site.species_and_occu\n\n                # Find the sites which are out of plane\n                oxy_1_oop = np.cross(\n                    shared_neighbor_4.coords - oxy_1.coords,\n                    shared_neighbor_3.coords - oxy_1.coords\n                )\n                oxy_2_oop = np.cross(\n                    shared_neighbor_3.coords - oxy_2.coords,\n                    shared_neighbor_4.coords - oxy_2.coords\n                )\n\n                if angle_between(oxy_1_oop, site.coords - oxy_1.coords) \\\n                        < REPRESENTATION_ANGLE_TOL:\n                    representation[9] = site.species_and_occu\n\n                if angle_between(oxy_1_oop, site.coords - oxy_1.coords) \\\n                        > math.pi - REPRESENTATION_ANGLE_TOL:\n                    representation[10] = site.species_and_occu\n\n                if angle_between(oxy_2_oop, site.coords - oxy_2.coords) \\\n                        < REPRESENTATION_ANGLE_TOL:\n                    representation[11] = site.species_and_occu\n\n                if angle_between(oxy_2_oop, site.coords - oxy_2.coords) \\\n                        > math.pi - REPRESENTATION_ANGLE_TOL:\n                    representation[12] = site.species_and_occu\n\n            self._representation = representation\n\n            if len(representation) != len(self.sites):\n                raise ValueError(\"Failed to create dimer representation.\")\n\n        return self._representation\n\n    def get_dimer_molecule(self):\n\n        molecule_sites = []\n\n        for site in self.sites:\n            (distance, jimage) = site.distance_and_image_from_frac_coords(\n                self.cathode.lattice.get_fractional_coords(self.center))\n\n            image_cart_coords = \\\n                site.coords - np.dot(jimage, self.cathode.lattice.matrix)\n\n            molecule_sites.append(Site(site.species_and_occu,\n                                       image_cart_coords))\n\n        return Molecule.from_sites(molecule_sites)\n\n    def visualize_dimer_environment(self, filename=None):\n        \"\"\"\n        Creates a .xyz file of the oxygen dimer environment in order to\n        visualize it in e.g. VESTA.\n\n        Returns:\n\n        \"\"\"\n\n        # Turn the structure into a molecule, ignoring the sites with zero\n        # occupancy\n        dimer_environment_molecule = Molecule.from_sites(\n            [site for site in self.get_dimer_molecule().sites\n             if not site.species_and_occu == Composition({\"\": 0})]\n        )\n\n        if filename is None:\n            filename = str(self.cathode.composition.reduced_composition\n                           ).replace(\" \", \"\") + \"_\" \\\n                       + str(self.indices[0]) + \"_\" + str(self.indices[1]) \\\n                       + \".xyz\"\n\n        dimer_environment_molecule.to(\"xyz\", filename)\n\n    # TODO Check if MSONable methods need to be implemented\n\n    def to(self, fmt=\"json\", filename=None):\n\n        if fmt == \"json\":\n            if filename:\n                with zopen(filename, \"wt\", encoding='utf8') as file:\n                    return json.dump(self.as_dict(), file)\n            else:\n                return json.dumps(self.as_dict())\n        else:\n            raise NotImplementedError(\"Currently only json format is \"\n                                      \"supported.\")\n\n    @classmethod\n    def from_str(cls, input_string, fmt=\"json\"):\n        \"\"\"\n        Initialize a Facet from a string.\n\n        Currently only supports 'json' formats.\n\n        Args:\n            input_string (str): String from which the Facet is initialized.\n            fmt (str): Format of the string representation.\n\n        Returns:\n            (*cage.Facet*)\n        \"\"\"\n        if fmt == \"json\":\n            d = json.loads(input_string)\n            return cls.from_dict(d)\n        else:\n            raise NotImplementedError('Only json format has been '\n                                      'implemented.')\n\n    @classmethod\n    def from_file(cls, filename):\n\n        with zopen(filename) as file:\n            contents = file.read()\n\n        return cls.from_str(contents)\n\n    def as_dict(self):\n\n        d = {\"cathode\": self.cathode.as_dict(),\n             \"dimer_indices\": self.indices}\n\n        return d\n\n    @classmethod\n    def from_dict(cls, d):\n\n        return cls(cathode=LiRichCathode.from_dict(d[\"cathode\"]),\n                   dimer_indices=d[\"dimer_indices\"])\n\n\nclass DimerNEBAnalysis(NEBAnalysis):\n    \"\"\"\n    Subclass of the NEBAnalysis class in order to change the plotting of the\n    barriers, as well as allowing for saving the NEB analysis to a json file.\n    \"\"\"\n\n    def __init__(self, r, energies, forces, structures, spline_options=None,\n                 dimer_indices=None):\n        super().__init__(\n            r, energies, forces, structures, spline_options\n        )\n        self._dimer_indices = tuple(dimer_indices)\n\n    @property\n    def dimer_indices(self):\n        return self._dimer_indices\n\n    @dimer_indices.setter\n    def dimer_indices(self, indices):\n        self._dimer_indices = indices\n\n    @property\n    def dimer_distances(self):\n        return np.array([s.distance_matrix[self.dimer_indices]\n                         for s in self.structures])\n\n    def as_dict(self):\n        \"\"\"\n        Dict representation of NEBAnalysis.\n\n        Returns:\n            JSON serializable dict representation.\n        \"\"\"\n        return {\"@module\": self.__class__.__module__,\n                \"@class\": self.__class__.__name__,\n                'r': jsanitize(self.r),\n                'energies': jsanitize(self.energies),\n                'forces': jsanitize(self.forces),\n                'structures': [s.as_dict() for s in self.structures],\n                \"dimer_indices\": self.dimer_indices}\n\n    def to(self, fmt=\"json\", filename=None):\n\n        if fmt == \"json\":\n            if filename:\n                with zopen(filename, \"wt\", encoding='utf8') as file:\n                    return json.dump(self.as_dict(), file)\n            else:\n                return json.dumps(self.as_dict())\n        else:\n            raise NotImplementedError(\"Currently only json format is \"\n                                      \"supported.\")\n\n    @classmethod\n    def from_dir(cls, root_dir, relaxation_dirs=None, **kwargs):\n        \"\"\"\n\n        Args:\n            root_dir:\n            relaxation_dirs:\n            **kwargs:\n\n        Returns:\n\n        \"\"\"\n        if relaxation_dirs is not None:\n            raise NotImplementedError\n\n        indices = tuple(\n            [int(el) for el in\n             os.path.abspath(root_dir).split('/')[-1].split('_')\n             if all([is_number(c) for c in el])]\n        )\n\n        neb = super().from_dir(root_dir, relaxation_dirs, **kwargs)\n\n        # Because the dimer indices are based on the internal indices of the\n        # Cathode object, we need to load the cathode json files to\n        # determine the distance between the dimers properly.\n        image_dirs = [file for file in os.listdir(root_dir)\n                      if len(file) == 2 and os.path.isdir(file)]\n\n        structures = [\n            Cathode.from_file(os.path.join(image_dir, \"final_cathode.json\"))\n            for image_dir in image_dirs\n        ]\n\n        # Sort the data according to the directory numbers\n        structure_data = sorted(\n            zip(image_dirs, structures),\n            key=lambda z: int(z[0])\n        )\n\n        dimer_neb = DimerNEBAnalysis(\n            r=neb.r,\n            energies=neb.energies,\n            forces=neb.forces,\n            structures=[el[1] for el in structure_data],\n            spline_options=neb.spline_options,\n            dimer_indices=indices,\n        )\n\n        return dimer_neb\n\n    @classmethod\n    def from_str(cls, input_string, fmt=\"json\"):\n        \"\"\"\n        Initialize a DimerNEBAnalysis from a string.\n\n        Currently only supports 'json' formats.\n\n        Args:\n            input_string (str): String from which the object is initialized.\n            fmt (str): Format of the string representation.\n\n        Returns:\n            (*pybat.core.DimerNEBAnalysis*)\n        \"\"\"\n        if fmt == \"json\":\n            d = json.loads(input_string)\n            return cls.from_dict(d)\n        else:\n            raise NotImplementedError('Only json format has been '\n                                      'implemented.')\n\n    @classmethod\n    def from_file(cls, filename):\n\n        with zopen(filename) as file:\n            contents = file.read()\n\n        return cls.from_str(contents)\n\n    @classmethod\n    def from_dict(cls, d):\n\n        return cls(r=d['r'], energies=d[\"energies\"], forces=d[\"forces\"],\n                   structures=[LiRichCathode.from_dict(structure) for\n                               structure in d[\"structures\"]],\n                   dimer_indices=d[\"dimer_indices\"])\n\n    def get_plot(self, normalize_rnx_coodinate=True, label_barrier=True):\n        \"\"\"\n        Returns the NEB plot. Uses Henkelman's approach of spline fitting\n        each section of the reaction path based on tangent force and energies.\n\n        Args:\n            label_barrier (bool): Whether to label the maximum barrier.\n\n        Returns:\n            matplotlib.pyplot object.\n        \"\"\"\n        plt = pretty_plot(12, 8)\n\n        spline_x = np.arange(0, np.max(self.r), 0.01)\n        spline_y = self.spline(spline_x) * 1000\n\n        relative_energies = self.energies - self.energies[0]\n\n        plt.plot(spline_x, spline_y, 'k--',\n                 self.r, relative_energies * 1000, 'ro',\n                 linewidth=2,\n                 markersize=10)\n\n        plt.xlabel(\"O-O Distance ($\\mathrm{\\AA}$)\")\n        plt.xticks(self.r[::2], [str(round(d, 2)) for d in\n                                 self.dimer_distances[::2]])\n        plt.ylabel(\"Energy (meV)\")\n        plt.ylim((np.min(spline_y) - 10, np.max(spline_y) * 1.02 + 20))\n\n        if label_barrier:\n            data = zip(spline_x, spline_y)\n            barrier = max(data, key=lambda d: d[1])\n            plt.plot([0, barrier[0]], [barrier[1], barrier[1]], 'k--')\n            plt.annotate('%.0f meV' % (np.max(spline_y) - np.min(spline_y)),\n                         xy=(barrier[0] / 2, barrier[1] * 1.02),\n                         xytext=(barrier[0] / 2, barrier[1] * 1.02),\n                         horizontalalignment='center')\n\n        plt.tight_layout()\n        return plt\n\n\n# SO Plagiarism\ndef unit_vector(vector):\n    \"\"\" Returns the unit vector of the vector.  \"\"\"\n    return vector / np.linalg.norm(vector)\n\n\ndef angle_between(v1, v2):\n    \"\"\"\n    Returns the angle in radians between vectors 'v1' and 'v2'::\n    \"\"\"\n    v1_u = unit_vector(v1)\n    v2_u = unit_vector(v2)\n    return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))\n\n\n# def rotation_matrix(axis, theta):\n#     \"\"\"\n#     Return the rotation matrix associated with clockwise rotation about\n#     the given axis by theta radians.\n#     \"\"\"\n#     axis = np.asarray(axis)\n#     axis = axis/math.sqrt(np.dot(axis, axis))\n#     a = math.cos(theta/2.0)\n#     b, c, d = axis*math.sin(theta/2.0)\n#     aa, bb, cc, dd = a*a, b*b, c*c, d*d\n#     bc, ad, ac, ab, bd, cd = b*c, a*d, a*c, a*b, b*d, c*d\n#     return np.array([[aa+bb-cc-dd, 2*(bc+ad), 2*(bd-ac)],\n#                      [2*(bc-ad), aa+cc-bb-dd, 2*(cd+ab)],\n#                      [2*(bd+ac), 2*(cd-ab), aa+dd-bb-cc]])\n\n\ndef permute(iterable, permutation):\n    if len(iterable) != len(permutation):\n        raise ValueError(\"Length of list does not match permutation length!\")\n\n    permutation_numbers = set([i for i in range(1, len(iterable) + 1)])\n\n    if len(permutation_numbers.intersection(permutation)) != len(permutation):\n        raise ValueError(\"Permutation is ill-defined.\")\n\n    return [iterable[index - 1] for index in permutation]\n\n\ndef is_number(s):\n    try:\n        float(s)\n        return True\n    except ValueError:\n        return False\n\ndef new_function(arg1, arg2):\n    \"\"\"\n    This describes the function.\n\n    Args:\n        arg1 (list):\n        arg2:\n\n    Returns:\n\n    \"\"\"", "meta": {"hexsha": "467f5e76dd6fdc4c5ac6388aaec14856589af279", "size": 45084, "ext": "py", "lang": "Python", "max_stars_repo_path": "pybat/core.py", "max_stars_repo_name": "lslap/pybat", "max_stars_repo_head_hexsha": "72fcc703c095ab9841e8b13845c1bea780f02904", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pybat/core.py", "max_issues_repo_name": "lslap/pybat", "max_issues_repo_head_hexsha": "72fcc703c095ab9841e8b13845c1bea780f02904", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pybat/core.py", "max_forks_repo_name": "lslap/pybat", "max_forks_repo_head_hexsha": "72fcc703c095ab9841e8b13845c1bea780f02904", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8977443609, "max_line_length": 84, "alphanum_fraction": 0.5661210185, "include": true, "reason": "import numpy,from scipy", "num_tokens": 9677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3415824860330003, "lm_q1q2_score": 0.1747934299792149}}
{"text": "#!/usr/bin/env python\nimport time\nimport pandas as pd\nimport collections\nfrom collections import defaultdict\nimport re\nimport numpy as np\nfrom Bio.SeqRecord import SeqRecord\nfrom Bio.Seq import Seq\nimport numpy as np\nimport re\n\ndef peptide_mass(peptide, fixed_modifications=[\"Carbamidomethylation of C\"], variable_modifications=[], nterm=True, cterm=True):\n    if 'X' in peptide:\n        return [np.inf]\n    if 'Z' in peptide:\n        return [np.inf]\n    if 'B' in peptide:\n        return [np.inf]\n\n    \n    masses = []\n\n    mass_h20=18.01056\n    nterm_mass =    1.007825035\n    cterm_mass =    1.007825035 + 15.99491463\n\n\n    monoisotopic = {'A':   71.037114,\n                    'C':   103.009185,\n                    'D':   115.026943,\n                    'E':   129.042593,\n                    'F':   147.068414,\n                    'G':   57.021464,\n                    'H':   137.058912,\n                    'U':   150.95363,\n                    'O':   237.147735,\n                    'I':   113.084064,\n                    'K':   128.09496,\n                    'L':   113.084064, \n                    'J':   113.084064,\n                    'M':   131.04049,\n                    'N':   114.042927,\n                    'P':   97.05276,\n                    'Q':   128.05858,\n                    'R':   156.101111,\n                    'S':   87.03203,\n                    'T':   101.04768,\n                    'V':   99.06841,\n                    'W':   186.07931,\n                    'Y':   163.06333  }\n    ##############\n    # Fixed mods #\n    ##############\n    options = [\"Carbamidomethylation of C\"]\n    for i in fixed_modifications:\n        assert i in options\n    if \"Carbamidomethylation of C\" in fixed_modifications:\n        monoisotopic['C'] = monoisotopic['C'] + 57.021464\n    \n    for aa in peptide:\n        masses.append(monoisotopic[aa])\n\n    # < insert directed graph here > #\n    masslist = [sum(masses)]\n    # < insert directed graph here > #\n    \n    if nterm == True:\n        masslist = [i + nterm_mass for i in masslist]\n    if cterm == True:\n        masslist = [i + cterm_mass for i in masslist]\n\n    return masslist\n\ndef mz2mw(mz, charge):\n    proton_mass=1.007276\n    mw = (mz * charge) - (proton_mass * charge) \n    return np.round(mw, 4)\n\nclass TagMatch:\n    def __init__(self, query, tag_mass_list, target, fixed_modifications=['Carbamidomethylation of C'], variable_modifications=[], enzymes=['Trypsin'], specificity='specific', prec_tol=0.02, gap_tol=0.5, max_missed_cleavages=3):\n        self.possible_enzymes = ['Trypsin', 'Trypsin, no P rule','Whole protein']\n        self.enzymes = enzymes\n        self.max_missed_cleavages = max_missed_cleavages\n        for enzyme in self.enzymes:\n            assert enzyme in self.possible_enzymes\n\n        self.possible_specificity = ['specific', 'semi-specific', 'unspecific']\n        self.specificity = specificity\n        assert self.specificity in self.possible_specificity\n        \n        self.target = target\n        self.target_length = len(target)\n\n        self.tag_mass_list = tag_mass_list\n        \n        self.gap_mass_dict = defaultdict(set)\n\n        if not ((self.specificity=='specific') and (self.enzymes==['Trypsin'])):\n            self.gaps = self.gaps()\n            self.max_gaps = (max(self.gaps[0]), max(self.gaps[1]))\n            self.maxngap = self.max_gaps[0]\n            self.maxcgap = self.max_gaps[1]\n\n        self.query=query\n        self.query_length = len(query)\n        self.fixed_modifications=fixed_modifications\n        self.variable_modifications=variable_modifications\n        self.query_positions = self.query_positions()\n        self.prec_tol = prec_tol\n        self.gap_tol  = gap_tol\n\n        self.validated=False\n        self.specificity = specificity\n\n        self.positions = self.match()\n        self.peptides  = self.peptides()\n        self.masses = self.masses()\n        \n        self.amino_gaps = self.amino_gaps()\n        self.validate_masses(self.masses)\n            \n    def query_positions(self):\n        positions = [(m.start(), m.start()+self.query_length ) for m in re.finditer('(?={})'.format(self.query), self.target)]\n        return positions\n    \n    def validate_masses(self, mass_dict):\n        validated_precursor = []\n        precursor_peptides = defaultdict(list)\n        validated_peptides = set()\n        \n        for position_key in mass_dict:\n            target_masses = mass_dict[position_key]\n            target_peptide = self.peptides[position_key]\n            \n            for target_mass in target_masses:\n                for tag_mass_set in self.tag_mass_list:\n                    assert len(tag_mass_set) == 3\n                    query_mass = tag_mass_set[1]\n                    diff = abs(target_mass - query_mass)\n                    if diff < self.prec_tol:\n                        nterm_mass_gap = tag_mass_set[0]\n                        cterm_mass_gap = tag_mass_set[2]\n                        for amino_gaps in self.amino_gaps[target_peptide]:\n                            nterm_gap_match=False\n                            cterm_gap_match=False\n                            if not amino_gaps[0] in self.gap_mass_dict:\n                                nterm_amino_gaps = peptide_mass(amino_gaps[0], nterm=False, cterm=False, fixed_modifications=self.fixed_modifications, variable_modifications = self.variable_modifications)\n                            else:\n                                nterm_amino_gaps = self.gap_mass_dict[amino_gaps[0]]\n                            for nterm_amino_gap in nterm_amino_gaps:\n                                if abs(nterm_amino_gap - nterm_mass_gap) < self.gap_tol:\n                                    nterm_gap_match=True\n                            if not amino_gaps[1] in self.gap_mass_dict:\n                                cterm_amino_gaps = peptide_mass(amino_gaps[1], nterm=False, cterm=False, fixed_modifications = self.fixed_modifications, variable_modifications=self.variable_modifications)\n                            else:\n                                cterm_amino_gaps = self.gap_mass_dict[amino_gaps[1]]\n                            for cterm_amino_gap in cterm_amino_gaps:\n                                if abs(cterm_amino_gap - cterm_mass_gap) < self.gap_tol:\n                                    cterm_gap_match=True\n                            \n                            if (cterm_gap_match==True) and (nterm_gap_match==True):\n                                validated_precursor.append(tag_mass_set)\n                                precursor_peptides[tag_mass_set].append(self.peptides[position_key])\n                                validated_peptides.add(self.peptides[position_key])\n        self.validated_precursor = validated_precursor\n        self.precursor_peptides  = precursor_peptides\n        self.validated_peptides = list(validated_peptides)\n        if len(validated_precursor) > 0:\n            self.validated = True\n\n    def masses(self):\n        masses = {}\n        for key in self.peptides:\n            peptide = self.peptides[key]\n            masslist = peptide_mass(peptide, fixed_modifications=self.fixed_modifications, variable_modifications=self.variable_modifications, nterm=True, cterm=True)\n            masses[key] = masslist\n        return masses\n\n    def peptides(self):\n        peptides = {}\n        for coord in self.positions:\n            p = self.target[coord[0]:coord[1]]\n            key='{}:{}'.format(str(coord[0]), str(coord[1]))\n            peptides[key] = p\n        return peptides\n\n    def match(self):\n        coords = []\n        for coord in self.query_positions:\n            nterms = self.nterms(coord[0])\n            cterms = self.cterms(coord[1]-1)\n\n            for nterm in nterms:\n                for cterm in cterms:\n                    amino_acid_before = self.target[nterm -1: nterm]\n                    first_amino_acid  = self.target[nterm]\n                    last_amino_acid   = self.target[cterm -1]\n                    amino_acid_after   = self.target[cterm : cterm + 1]\n                    valid = valid_cleavage( amino_acid_before, first_amino_acid, last_amino_acid, amino_acid_after, self.enzymes, self.specificity)\n                    if valid == True:\n                        mc = missed_cleavages(self.target[nterm:cterm], self.enzymes)\n                        if (mc <= self.max_missed_cleavages):\n                            coords.append((nterm, cterm))\n        return coords\n\n\n    def nterms(self, pos):\n        nterm = pos\n        nterms=[]\n        \n        if ((self.specificity=='specific') and (self.enzymes==['Trypsin'])):\n            valid_gaps=True\n            missed=0\n            while valid_gaps==True:\n                if nterm == 0:\n                    nterms.append(nterm)\n                    return nterms\n                else: \n                    current_amino = self.target[nterm]\n                    previous_amino = self.target[nterm-1]\n                    if (current_amino != 'P') and (previous_amino in {'R', 'K'}):\n                        nterms.append(nterm)\n                        missed += 1\n                        if missed > self.max_missed_cleavages:\n                            return nterms\n                    nterm -= 1\n                    assert nterm >= 0\n        else:\n            valid_gaps=True\n            limit = self.maxngap + self.gap_tol\n            while valid_gaps==True:\n                amino_gap = self.target[nterm:pos]\n                validated=False\n                gaps = peptide_mass(amino_gap, fixed_modifications=self.fixed_modifications, variable_modifications=self.variable_modifications, nterm=False, cterm=False)\n                self.gap_mass_dict[amino_gap].update(gaps)\n                for gap in gaps:\n                    diff_gaps = set([(abs(i-gap) < self.gap_tol) for i in self.gaps[0]])\n                    if True in diff_gaps:\n                        validated=True\n\n                if nterm == 0:\n                    if validated == True:\n                        nterms.append(nterm)\n                    return nterms\n                else: \n                    if validated == True:\n                        nterms.append(nterm)\n                    nterm -= 1\n                    assert nterm >= 0\n                if min(gaps) > limit:\n                    return nterms\n\n    def cterms(self, pos):\n        cterm = pos\n        cterms=[]\n        \n        if ((self.specificity=='specific') and (self.enzymes==['Trypsin'])):\n            valid_gaps =True\n            missed=0\n            while valid_gaps ==True:\n                amino_gap = self.target[pos +1:cterm+1]\n\n                if cterm == self.target_length-1:\n                    cterms.append(cterm + 1)\n                    return cterms\n                else: \n                    current_amino = self.target[cterm]\n                    next_amino = self.target[cterm +1]\n                    if (next_amino != 'P') and (current_amino in {'R', 'K'}):\n                        cterms.append(cterm + 1)\n                        missed += 1\n                        if missed > self.max_missed_cleavages:\n                            return cterms\n                    cterm += 1\n                    assert cterm <= self.target_length -1\n\n        else:\n            valid_gaps =True\n            limit = self.maxcgap + self.gap_tol\n            while valid_gaps ==True:\n                amino_gap = self.target[pos +1:cterm+1]\n                gaps = peptide_mass(amino_gap, fixed_modifications=self.fixed_modifications, variable_modifications=self.variable_modifications, nterm=False, cterm=False)\n                self.gap_mass_dict[amino_gap].update(gaps)\n                validated=False\n                \n                for gap in gaps:\n                    diff_gaps = set([(abs(i-gap) < self.gap_tol) for i in self.gaps[1]])\n                    if True in diff_gaps:\n                        validated=True\n\n                if cterm == self.target_length-1:\n                    if validated == True:\n                        cterms.append(cterm + 1)\n                    return cterms\n                else: \n                    if validated == True:\n                        cterms.append(cterm + 1)\n                    cterm += 1\n                    assert cterm <= self.target_length -1\n                if min(gaps) > limit:\n                    return cterms\n\n    def gaps(self):\n        ngaps = []\n        cgaps = []\n        for tag in self.tag_mass_list:\n            n = tag[0]\n            c = tag[2]\n            ngaps.append(n)\n            cgaps.append(c)\n        return (list(set(ngaps)), list(set(cgaps)))\n\n    def amino_gaps(self):\n        amino_gap_dict = defaultdict(list)\n        for key in self.peptides:\n            peptide = self.peptides[key]\n            positions = [(m.start(), m.start()+self.query_length ) for m in re.finditer('(?={})'.format(self.query), peptide)]\n            for coord in positions:\n                tag_start = coord[0]\n                tag_end = tag_start + self.query_length\n                nterm_gap = peptide[:tag_start]\n                cterm_gap = peptide[tag_end:]\n                amino_gap_dict[peptide].append( (nterm_gap, cterm_gap) )\n        return amino_gap_dict\n\ndef valid_cleavage(amino_acid_before, first_amino_acid, last_amino_acid, amino_acid_after, enzymes, specificity):\n    valid = False\n    nterm_valid=False\n    cterm_valid=False\n    for enzyme in enzymes:\n        if enzyme=='Trypsin, no P rule':\n            cleavage_aminos=['K','R']\n            if amino_acid_before == '':\n                nterm_valid=True\n            elif amino_acid_before in cleavage_aminos:\n                nterm_valid=True\n            if amino_acid_after =='':\n                cterm_valid=True\n            elif last_amino_acid in cleavage_aminos:\n                cterm_valid=True\n\n        elif enzyme == 'Trypsin':\n            cleavage_aminos=['K','R']\n            \n            if amino_acid_before == '':\n                nterm_valid=True\n            elif (amino_acid_before in cleavage_aminos) and (first_amino_acid != 'P'):\n                nterm_valid=True\n            \n            if amino_acid_after =='':\n                cterm_valid=True\n            elif last_amino_acid in cleavage_aminos:\n                cterm_valid=True\n        \n        elif enzyme == 'Whole protein':\n            \n            if amino_acid_before == '':\n                nterm_valid=True\n            \n            if amino_acid_after =='':\n                cterm_valid=True\n    if ((nterm_valid and cterm_valid) == True) and (specificity == 'specific'):\n        valid = True\n    elif ((nterm_valid or cterm_valid) == True) and (specificity == 'semi-specific'):\n        valid = True\n    elif specificity == 'unspecific':\n        valid=True\n    return valid\n\ndef missed_cleavages(peptide, enzymes):\n    new_peptides = [peptide]\n    for enzyme in enzymes:\n        holder=[]\n        for datum in new_peptides:\n            if enzyme=='Trypsin, no P rule':\n                peptides = re.sub(r'(?<=[RK])','\\n', datum).split('\\n')\n                holder += peptides\n            elif enzyme == 'Trypsin':\n                peptides = re.sub(r'(?<=[RK])(?=[^P])','\\n', datum).split('\\n')\n                holder += peptides\n            elif enzyme == 'Whole protein':\n                peptides = [datum]\n                holder += peptides\n        new_peptides = holder\n    return len(new_peptides) - 1\n\ndef character_strip(sequence, character):\n    started=False\n    start_pos=0\n    while (started==False) and (start_pos < len(sequence)):\n        if sequence[start_pos]==character:\n            start_pos += 1\n        else:\n            started = True\n\n    end_pos=len(sequence)-1\n    ended=False\n    while (ended==False) and (end_pos > 0):\n        if sequence[end_pos]==character:\n            end_pos -= 1\n        else:\n            ended = True\n    return sequence[start_pos: end_pos + 1]\n\nclass gap_sequence:\n    def __init__(self, gap, fixed_modifications=['Carbamidomethylation of C'], variable_modifications=[], prec_tol=0.02, gap_tol=0.5):\n        self.gap = gap\n        self.prec_tol = prec_tol\n        self.gap_tol  = gap_tol\n        self.fixed_modifications = fixed_modifications\n        self.variable_modifications = variable_modifications\n        self.gap_sequences=[]\n        \n        self.possible = set([0])\n        self.valid = False\n\n        self.aminos     =           ['A', \n                                     'C', \n                                     'D', \n                                     'E', \n                                     'F' ,\n                                     'G', \n                                     'H', \n                                     'U', \n                                     'O', \n                                     'I', \n                                     'K', \n                                     'L', \n                                     'J',\n                                     'M', \n                                     'N', \n                                     'P' , \n                                     'Q', \n                                     'R', \n                                     'S', \n                                     'T' , \n                                     'V' , \n                                     'W', \n                                     'Y']\n\n    def sequences(self, mass=0, sequence=''):\n        diff = np.absolute(mass - self.gap)\n\n        if diff < self.prec_tol:\n            self.gap_sequences.append(sequence)\n        \n        elif (mass < self.gap):\n            for amino in self.aminos:\n                masses=peptide_mass(amino, variable_modifications = self.variable_modifications, fixed_modifications=self.fixed_modifications, nterm=False, cterm=False)\n                for m in masses:\n                    newmass=mass + m\n                    newsequence = sequence + amino\n                    self.sequences(newmass, newsequence)\n    \n    def validate(self):\n        newpossible=set()\n        for mass in self.possible:\n            diff = np.absolute(mass - self.gap)\n\n            if diff < self.prec_tol:\n                self.valid = True\n        \n            elif (mass < self.gap) and (self.valid==False):\n                for amino in self.aminos:\n                    masses=peptide_mass(amino, variable_modifications = self.variable_modifications, fixed_modifications=self.fixed_modifications, nterm=False, cterm=False)\n                    for m in masses:\n                        newmass = mass + m\n                        newpossible.add(np.round(newmass,4))\n        if (len(newpossible) > 0) and (self.valid ==False):\n            self.possible=newpossible\n            self.validate()\n\nclass blast_tags:\n    def __init__(self, subject, tags, fixed_modifications=['Carbamidomethylation of C'], variable_modifications=[], prec_tol=0.02, gap_tol=0.5, min_identities = 4, IL_equivalence=True):\n\n        self.subject=subject\n        self.tags=tags \n        self.fixed_modifications = fixed_modifications\n        self.variable_modifications = variable_modifications\n        self.prec_tol  = prec_tol\n        self.gap_tol = gap_tol\n\n        self.min_identities = min_identities\n        self.IL_equivalence = IL_equivalence\n\n        self.mweights = set()\n        self.nmasses  = set()\n        self.cmasses  = set()\n        \n        self.samples  = set()\n        self.scans    = set()\n\n        record_holder = set()\n        self.newrecords = []\n\n\n        for qtag in self.tags:\n            qseq = str(qtag.seq)\n            qsubstrings = self.substrings(qseq, self.subject)\n            \n            modified_tags = self.segment_matching(qseq, self.subject, min_identities=self.min_identities, IL_equivalence=self.IL_equivalence)\n            idlist = qtag.id.split(';')\n            file = idlist[0]\n            scan = idlist[1]\n            mw = float(idlist[2].split('mw=')[1])\n            ngap = float(idlist[3].split('ngap=')[1])\n            cgap = float(idlist[4].split('cgap=')[1])\n\n            for i in modified_tags:\n                newseq=i[0]\n                newngap = np.round(ngap + i[1],6)\n                newcgap = np.round(cgap + i[2],6)\n                newseq, newngap, newcgap = self.fix_negative_gaps(newseq, newngap, newcgap)\n                valid_tag=True\n                if newngap <= -(self.gap_tol):\n                    valid_tag=False\n                elif newcgap <= -(self.gap_tol):\n                    valid_tag=False\n                if valid_tag == True:\n                    newid ='{};{};mw={};ngap={};cgap={}'.format(file, scan, mw, newngap, newcgap)\n                    newrec=SeqRecord(seq=Seq(newseq),id=newid,description='Segment correction of {}-{}-{}'.format(ngap,qseq,cgap))\n                    temp = newrec.format('fasta')\n                    if not temp in record_holder:\n                        record_holder.add(temp)\n                        self.newrecords.append(newrec)\n\n    def valid_tag(self, tag):\n        sequence_masses = peptide_mass(tag[0], fixed_modifications=self.fixed_modifications, variable_modifications = self.variable_modifications, cterm=True, nterm=True)\n        for mass in sequence_masses:\n            total = mass + tag[2] + tag[3]\n            diff = np.absolute(total - tag[1])\n            if diff < self.prec_tol:\n                return True\n\n    def substrings(self, reference, match_sequence):\n        substrings=[]\n        for charpos in range(len(match_sequence)):\n            mismatch=False\n            pos= charpos\n            while (mismatch == False) & (pos < len(match_sequence)):\n                if match_sequence[charpos:pos +1]  in reference:\n                    pos += 1\n                else:\n                    mismatch=True\n                subs = match_sequence[charpos:pos ]\n            if subs != '':\n                substrings.append(subs)\n        return substrings\n\n    def longest_substring(self, substrings):    \n        maxlen = len(max(substrings, key=len))\n        maxes = [i for i in substrings if len(i) == maxlen]\n        return maxes\n    \n    def substring_coordinates(self, reference, substr):\n        coordinates=[(m.start(), m.start() + len(substr)) for m in re.finditer('(?={})'.format(substr), reference)]\n        return coordinates\n\n    def cmass_gap(self, reference, coordinates):\n        mass_gaps=[]\n        for coordinate in coordinates:\n            amino_gap = reference[coordinate[1]:]\n            amino_masses = peptide_mass(amino_gap, fixed_modifications = self.fixed_modifications, variable_modifications = self.variable_modifications, nterm=False, cterm=False)\n            mass_gaps += amino_masses\n        return mass_gaps\n\n    def nmass_gap(self, reference, coordinates):\n        mass_gaps=[]\n        for coordinate in coordinates:\n            amino_gap = reference[:coordinate[0]]\n            amino_masses = peptide_mass(amino_gap, fixed_modifications = self.fixed_modifications, variable_modifications = self.variable_modifications, nterm=False, cterm=False)\n            mass_gaps += amino_masses\n        return mass_gaps\n    \n    def new_records(self):\n        newrecords = []\n        test = []\n        for newtag in self.newtags:\n            rec = SeqRecord(seq=Seq(newtag[0]), id = '{};{};mw={};ngap={};cgap={}'.format(list(self.samples)[0], list(self.scans)[0], str(newtag[1]), str(newtag[2]), str(newtag[3])))\n            trec = rec.format('fasta')\n            if not trec in test:\n                test.append(trec)\n                newrecords.append(rec)\n        return newrecords\n    \n    def match_segments(self, tagsequence, blastsequence, substrings, min_identities, matchsequence='', matchngap=None, matchcgap=None, identities=[], matches = set()):\n        if (len(substrings) == 0):\n            if len(identities) > 0:\n                if (len(''.join(identities)) >= min_identities):\n                    for cg in peptide_mass(blastsequence, cterm=False, nterm=False, fixed_modifications = self.fixed_modifications, variable_modifications = self.variable_modifications):\n                        for cg2 in peptide_mass(tagsequence, cterm=False, nterm=False, fixed_modifications = self.fixed_modifications, variable_modifications = self.variable_modifications ) :\n                            matches.add((matchsequence + blastsequence, matchngap, cg2-cg, '-'.join(identities)))\n            return matches\n\n        subst = substrings[0]\n        newsubstrings = substrings[1:]\n        refpos = [(m.start(), m.start()+len(subst)) for m in re.finditer('(?={})'.format(subst), blastsequence)]\n        tagpos = [(m.start(), m.start()+len(subst)) for m in re.finditer('(?={})'.format(subst), tagsequence)]\n        \n        newtags = self.match_segments(tagsequence, blastsequence, newsubstrings, min_identities, matchsequence=matchsequence, matchngap=matchngap, matchcgap=matchcgap, identities=identities, matches=matches)\n        matches.update(newtags)\n        \n        for r in refpos:\n            for t in tagpos:\n                refgap = blastsequence[:r[0]]\n                matchgap = tagsequence[:t[0]]\n                newblastsequence = blastsequence[r[1] :]\n                newtagsequence = tagsequence[t[1] :]\n\n                refgapmasses=peptide_mass(refgap, nterm=False, cterm=False, fixed_modifications=self.fixed_modifications, variable_modifications=self.variable_modifications)\n                matchgapmasses = peptide_mass(matchgap, nterm=False, cterm=False, fixed_modifications=self.fixed_modifications, variable_modifications = self.variable_modifications)\n\n                for rm in refgapmasses:\n                    for tm in matchgapmasses:\n                        if matchngap==None:\n                            newmatchngap = tm - rm\n                            newmatchngap = np.round(newmatchngap, 6)\n                            newmatchsequence = refgap + subst\n                            newtags = self.match_segments(newtagsequence, newblastsequence, newsubstrings, min_identities, matchsequence=newmatchsequence, matchngap=newmatchngap, matchcgap = matchcgap, identities=identities + [subst] , matches=matches)\n                            matches.update(newtags)\n                        elif rm==tm==0:\n                            return matches\n                        else:\n                            diff = abs(rm - tm)\n                            if diff < self.gap_tol:\n                                newmatchsequence = matchsequence + refgap + subst\n                                newtags = self.match_segments(newtagsequence, newblastsequence, newsubstrings, min_identities, matchsequence=newmatchsequence, matchngap=matchngap, matchcgap=matchcgap, identities=identities + [subst], matches=matches)\n                                matches.update(newtags)\n        return matches\n\n    def segment_matching(self, tagsequence, blastsequence, min_identities=4, IL_equivalence=True):\n        if IL_equivalence==True:\n            newtagsequence = 'L'.join(tagsequence.split('I'))\n            newblastsequence = 'L'.join(blastsequence.split('I'))\n        else:\n            newtagsequence = tagsequence\n            newblastsequence = blastsequence\n\n        substrings = self.substrings(newblastsequence, newtagsequence)\n        newtags = self.match_segments(newtagsequence, newblastsequence, substrings, min_identities=min_identities, matchsequence='', matchngap=None, matchcgap=None, identities=[], matches=set())\n        besttags=[]\n        bestlen=0\n        \n        for tag in newtags:\n            identities = ''.join(tag[3].split('-'))\n            if len(identities) > bestlen:\n                bestlen = len(identities)\n        \n        for tag in newtags:\n            identities = ''.join(tag[3].split('-'))\n            if len(identities) == bestlen:\n                assert tag[0] == newblastsequence\n                tag = (blastsequence, tag[1], tag[2], tag[3])\n                besttags.append(tag)\n        return set(besttags)\n        \n    def fix_negative_gaps(self, sequence, ngap, cgap):\n        \n        if ngap < 0:\n            ngap_fixed=False\n            for position in range(1, len(sequence)):\n                newsequence = sequence[position:]\n                newgapsequence = sequence[:position]\n                ng = peptide_mass(newgapsequence, nterm=False, cterm=False,  fixed_modifications=self.fixed_modifications, variable_modifications= self.variable_modifications)\n                mng = min(ng)\n                \n                if mng + ngap >= self.gap_tol:\n                    break    \n                \n                for _ in ng:\n                    newg = ngap + _\n                    if np.absolute(newg) < self.gap_tol:\n                        ngap = newg\n                        sequence = newsequence\n                        ngap_fixed=True\n                        break\n                if ngap_fixed==True:\n                    break\n\n        if cgap < 0:\n            cgap_fixed=False\n            for position in range(1, len(sequence)):\n                newsequence = sequence[:-position]\n                newgapsequence = sequence[-position:]\n                cg = peptide_mass(newgapsequence, nterm=False, cterm=False,  fixed_modifications=self.fixed_modifications, variable_modifications= self.variable_modifications)\n                \n                mcg = min(cg)\n                \n                if mcg + cgap >= self.gap_tol:\n                    break    \n    #            \n                for _ in cg:\n                    newg = cgap + _\n                    if np.absolute(newg) < self.gap_tol:\n                        cgap = newg\n                        sequence = newsequence\n                        cgap_fixed=True\n                        break\n                if cgap_fixed==True:\n                    break\n\n        return sequence, np.round(ngap,4), np.round(cgap,4)\n\n    \n", "meta": {"hexsha": "c6535cdbe003270f1aaf496e20cfd5a14a2ac222", "size": 29739, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/tagmatch.py", "max_stars_repo_name": "reid-wagner/proteomics-pipelines", "max_stars_repo_head_hexsha": "2214c2ad4c14fabcb50a3c0800e9d383ce73df3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-09-06T14:05:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T10:09:06.000Z", "max_issues_repo_path": "lib/tagmatch.py", "max_issues_repo_name": "reid-wagner/proteomics-pipelines", "max_issues_repo_head_hexsha": "2214c2ad4c14fabcb50a3c0800e9d383ce73df3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2018-09-30T00:49:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-27T07:55:26.000Z", "max_forks_repo_path": "lib/tagmatch.py", "max_forks_repo_name": "reid-wagner/proteomics-pipelines", "max_forks_repo_head_hexsha": "2214c2ad4c14fabcb50a3c0800e9d383ce73df3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-29T12:20:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-06T14:38:43.000Z", "avg_line_length": 42.1232294618, "max_line_length": 252, "alphanum_fraction": 0.5290695719, "include": true, "reason": "import numpy", "num_tokens": 6598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3174262785020255, "lm_q1q2_score": 0.17477724695765576}}
{"text": "\"\"\"Implementation of HSD-scripted.\n\nHigh-level Q-functions Q(s,\\zbf) are trained either with QMIX (with decentralized execution)\nor Q-learning (centralized execution) using the global reward\nLow-level Q-functions Q(o^n,z^n,a^n) are trained with independent Q-learning using local rewards\n\"\"\"\n\nimport tensorflow as tf\nimport numpy as np\nimport sys\nimport networks\n\n\nclass Alg(object):\n\n    def __init__(self, alg_name, config_alg, n_agents, l_state, l_obs, l_action, N_roles, nn):\n        \"\"\"\n        Args:\n            alg_name: currently supports 'hsd-scripted' for QMIX at high level or 'mara-c' for Q-learning at high level. Low level is always independent Q-learning\n            config_alg: dictionary of general RL params\n            n_agents: number of agents on the team controlled by this alg\n            l_state, l_obs, l_action, N_roles: int\n            nn: dictionary with neural net sizes\n        \"\"\"\n        self.alg_name = alg_name\n\n        self.l_state = l_state\n        self.l_obs = l_obs\n        self.l_action = l_action\n        self.N_roles = N_roles\n        self.nn = nn\n\n        self.n_agents = n_agents\n        self.tau = config_alg['tau']\n        self.lr_Q = config_alg['lr_Q']\n        self.gamma = config_alg['gamma']\n\n        self.agent_labels = np.eye(self.n_agents)\n\n        if self.alg_name == 'mara-c':\n            # Combinatorial action space, but we don't allow duplicate roles\n            assert(self.N_roles >= self.n_agents)\n            self.dim_role_space = int(np.math.factorial(self.N_roles) / np.math.factorial(self.N_roles - self.n_agents))\n            self.list_list_indices = []\n            self.populate_list_list_roles(0, [])\n\n        # Initialize computational graph\n        self.create_networks()\n        self.list_initialize_target_ops, self.list_update_target_ops, self.list_update_target_ops_low = self.get_assign_target_ops()\n        self.create_train_op()\n        self.create_train_op_IQL()\n\n        # TF summaries\n        self.create_summary()\n\n    def populate_list_list_roles(self, agent_idx, list_indices):\n        \n        if len(list_indices) == self.n_agents:\n            self.list_list_indices.append(list_indices)\n        else:\n            for idx_role in range(self.N_roles):\n                if idx_role in list_indices:\n                    # Skip over duplicate roles\n                    continue\n                else:\n                    l = list(list_indices)\n                    l.append(idx_role)\n                    self.populate_list_list_roles(agent_idx+1, l)\n\n    def create_networks(self):\n\n        # Placeholders\n        self.state = tf.placeholder(tf.float32, [None, self.l_state], 'state')\n        self.obs = tf.placeholder(tf.float32, [None, self.l_obs], 'obs')\n        self.role = tf.placeholder(tf.float32, [None, self.N_roles], 'role')\n        \n        # Low-level Q-functions\n        with tf.variable_scope(\"Qlow_main\"):\n            self.Q_low = networks.Q_low(self.obs, self.role, self.nn['n_h1_low'], self.nn['n_h2_low'], self.l_action)\n        with tf.variable_scope(\"Qlow_target\"):\n            self.Q_low_target = networks.Q_low(self.obs, self.role, self.nn['n_h1_low'], self.nn['n_h2_low'], self.l_action)\n\n        self.argmax_Q_low = tf.argmax(self.Q_low, axis=1)\n        self.argmax_Q_low_target = tf.argmax(self.Q_low_target, axis=1)\n\n        # Low level action\n        self.actions_low_1hot = tf.placeholder(tf.float32, [None, self.l_action], 'actions_low_1hot')\n\n        # High-level Q-functions\n        if self.alg_name == 'hsd-scripted':\n            # Individual agent networks\n            # output dimension is [time * n_agents, q-values]\n            with tf.variable_scope(\"Agent_main\"):\n                self.agent_qs = networks.Qmix_single(self.obs, self.nn['n_h1'], self.nn['n_h2'], self.N_roles)\n            with tf.variable_scope(\"Agent_target\"):\n                self.agent_qs_target = networks.Qmix_single(self.obs, self.nn['n_h1'], self.nn['n_h2'], self.N_roles)\n            \n            self.argmax_Q = tf.argmax(self.agent_qs, axis=1)\n            self.argmax_Q_target = tf.argmax(self.agent_qs_target, axis=1)\n            \n            # To extract Q-value from agent_qs and agent_qs_target\n            # [batch*n_agents, N_roles]\n            self.actions_1hot = tf.placeholder(tf.float32, [None, self.N_roles], 'actions_1hot')\n            # [batch*n_agents, 1]\n            self.q_selected = tf.reduce_sum(tf.multiply(self.agent_qs, self.actions_1hot), axis=1)\n            # [batch, n_agents]\n            self.mixer_q_input = tf.reshape( self.q_selected, [-1, self.n_agents] )\n            \n            self.q_target_selected = tf.reduce_sum(tf.multiply(self.agent_qs_target, self.actions_1hot), axis=1)\n            self.mixer_target_q_input = tf.reshape( self.q_target_selected, [-1, self.n_agents] )\n            \n            # Mixing network\n            with tf.variable_scope(\"Mixer_main\"):\n                self.mixer = networks.Qmix_mixer(self.mixer_q_input, self.state, self.l_state, self.n_agents, self.nn['n_h_mixer'])\n            with tf.variable_scope(\"Mixer_target\"):\n                self.mixer_target = networks.Qmix_mixer(self.mixer_target_q_input, self.state, self.l_state, self.n_agents, self.nn['n_h_mixer'])\n        elif self.alg_name == 'mara-c':\n            # Standard Q-learning for role assignment\n            with tf.variable_scope(\"Qhigh_main\"):\n                self.Q_high = networks.Q_high(self.state, self.nn['n_h1'], self.nn['n_h2'], self.dim_role_space)\n            with tf.variable_scope(\"Qhigh_target\"):\n                self.Q_high_target = networks.Q_high(self.state, self.nn['n_h1'], self.nn['n_h2'], self.dim_role_space)\n            self.argmax_Q_high = tf.argmax(self.Q_high, axis=1)\n            self.argmax_Q_high_target = tf.argmax(self.Q_high_target, axis=1)\n            self.actions_high_1hot = tf.placeholder(tf.float32, [None, self.dim_role_space], 'actions_high_1hot')\n                \n    def get_assign_target_ops(self):\n\n        # ops for equating main and target\n        list_initial_ops = []\n        # ops for slow update of target toward main\n        list_update_ops = []\n        # ops for slow update of low-level target toward low-level main\n        list_update_ops_low = []\n\n        if self.alg_name == 'hsd-scripted':\n            list_Agent_main = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Agent_main')\n            map_name_Agent_main = {v.name.split('main')[1] : v for v in list_Agent_main}\n            list_Agent_target = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Agent_target')\n            map_name_Agent_target = {v.name.split('target')[1] : v for v in list_Agent_target}\n            \n            if len(list_Agent_main) != len(list_Agent_target):\n                raise ValueError(\"get_initialize_target_ops : lengths of Agent_main and Agent_target do not match\")\n            \n            for name, var in map_name_Agent_main.items():\n                # create op that assigns value of main variable to\n                # target variable of the same name\n                list_initial_ops.append( map_name_Agent_target[name].assign(var) )\n            \n            for name, var in map_name_Agent_main.items():\n                # incremental update of target towards main\n                list_update_ops.append( map_name_Agent_target[name].assign( self.tau*var + (1-self.tau)*map_name_Agent_target[name] ) )\n            \n            list_Mixer_main = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Mixer_main')\n            map_name_Mixer_main = {v.name.split('main')[1] : v for v in list_Mixer_main}\n            list_Mixer_target = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Mixer_target')\n            map_name_Mixer_target = {v.name.split('target')[1] : v for v in list_Mixer_target}\n            \n            if len(list_Mixer_main) != len(list_Mixer_target):\n                raise ValueError(\"get_initialize_target_ops : lengths of Mixer_main and Mixer_target do not match\")\n            \n            # ops for equating main and target\n            for name, var in map_name_Mixer_main.items():\n                # create op that assigns value of main variable to\n                # target variable of the same name\n                list_initial_ops.append( map_name_Mixer_target[name].assign(var) )\n            \n            # ops for slow update of target toward main\n            for name, var in map_name_Mixer_main.items():\n                # incremental update of target towards main\n                list_update_ops.append( map_name_Mixer_target[name].assign( self.tau*var + (1-self.tau)*map_name_Mixer_target[name] ) )\n        elif self.alg_name == 'mara-c':\n            list_Qhigh_main = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Qhigh_main')\n            map_name_Qhigh_main = {v.name.split('main')[1] : v for v in list_Qhigh_main}\n            list_Qhigh_target = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Qhigh_target')\n            map_name_Qhigh_target = {v.name.split('target')[1] : v for v in list_Qhigh_target}\n            \n            if len(list_Qhigh_main) != len(list_Qhigh_target):\n                raise ValueError(\"get_initialize_target_ops : lengths of Qhigh_main and Qhigh_target do not match\")\n            \n            for name, var in map_name_Qhigh_main.items():\n                # create op that assigns value of main variable to\n                # target variable of the same name\n                list_initial_ops.append( map_name_Qhigh_target[name].assign(var) )\n            \n            for name, var in map_name_Qhigh_main.items():\n                # incremental update of target towards main\n                list_update_ops.append( map_name_Qhigh_target[name].assign( self.tau*var + (1-self.tau)*map_name_Qhigh_target[name] ) )\n        \n        list_Qlow_main = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Qlow_main')\n        map_name_Qlow_main = {v.name.split('main')[1] : v for v in list_Qlow_main}\n        list_Qlow_target = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Qlow_target')\n        map_name_Qlow_target = {v.name.split('target')[1] : v for v in list_Qlow_target}\n        \n        if len(list_Qlow_main) != len(list_Qlow_target):\n            raise ValueError(\"get_initialize_target_ops : lengths of Qlow_main and Qlow_target do not match\")\n        \n        for name, var in map_name_Qlow_main.items():\n            # create op that assigns value of main variable to\n            # target variable of the same name\n            list_initial_ops.append( map_name_Qlow_target[name].assign(var) )\n        \n        for name, var in map_name_Qlow_main.items():\n            # incremental update of target towards main\n            list_update_ops_low.append( map_name_Qlow_target[name].assign( self.tau*var + (1-self.tau)*map_name_Qlow_target[name] ) )\n\n        return list_initial_ops, list_update_ops, list_update_ops_low\n\n    def run_actor(self, list_obs, roles, epsilon, sess):\n        \"\"\"Get low-level actions for all agents as a batch.\n\n        Args:\n            list_obs: list of vectors, one per agent\n            roles: np.array where each row is a 1-hot vector\n            epsilon: exploration parameter\n            sess: TF session\n\n        Returns: np.array of action integers\n        \"\"\"\n        # convert to batch\n        obs = np.array(list_obs)\n        feed = {self.obs : obs, self.role : roles}\n        actions_argmax = sess.run(self.argmax_Q_low, feed_dict=feed)\n\n        actions = np.zeros(self.n_agents, dtype=int)\n        for idx in range(self.n_agents):\n            if np.random.rand() < epsilon:\n                actions[idx] = np.random.randint(0, self.l_action)\n            else:\n                actions[idx] = actions_argmax[idx]\n\n        return actions\n\n    def assign_roles(self, list_obs, epsilon, sess):\n        \"\"\"Get high-level role assignment actions for all agents.\n        \n        Args:\n            list_obs: list of vectors, one per agent\n            epsilon: exploration parameter\n            sess: TF session\n\n        Returns: np.array of role indices\n        \"\"\"\n        obs = np.array(list_obs)\n        feed = {self.obs : obs}\n        roles_argmax = sess.run(self.argmax_Q, feed_dict=feed)\n\n        roles = np.zeros(self.n_agents, dtype=int)\n        for idx in range(self.n_agents):\n            if np.random.rand() < epsilon:\n                roles[idx] = np.random.randint(0, self.N_roles)\n            else:\n                roles[idx] = roles_argmax[idx]\n\n        return roles\n\n    def assign_roles_centralized(self, state, epsilon, sess):\n        \"\"\"Centralized skill selection for all agents.\n        \n        Directly samples one single action index from high-level Q function\n        Maps action index to roles for all agents\n\n        Returns np.array of role indices\n        \"\"\"\n        if np.random.rand() < epsilon:\n            idx = np.random.randint(0, self.dim_role_space)\n        else:\n            feed = {self.state : np.array([state])}\n            idx = sess.run(self.argmax_Q_high, feed_dict=feed)\n        roles = np.array( self.list_list_indices[int(idx)] )\n\n        return roles, np.squeeze(idx)\n\n    def create_train_op(self):\n\n        self.td_target = tf.placeholder(tf.float32, [None], 'td_target')\n        if self.alg_name == 'hsd-scripted':\n            # TD target calculated in train_step() using Mixer_target\n            self.loss_Q_high = tf.reduce_mean(tf.square(self.td_target - tf.squeeze(self.mixer)))\n        elif self.alg_name == 'mara-c':\n            # Treat the role assignment as single-agent Q-learning\n            self.td_error_Q = self.td_target - tf.reduce_sum(tf.multiply(self.Q_high, self.actions_high_1hot), axis=1)\n            self.loss_Q_high = tf.reduce_mean(tf.square(self.td_error_Q))\n            \n        self.Q_opt = tf.train.AdamOptimizer(self.lr_Q)\n        self.Q_op = self.Q_opt.minimize(self.loss_Q_high)\n\n    def create_train_op_IQL(self):\n        self.td_target_IQL = tf.placeholder(tf.float32, [None], 'td_target_IQL')\n        self.td_error = self.td_target_IQL - tf.reduce_sum(tf.multiply(self.Q_low, self.actions_low_1hot), axis=1)\n        self.loss_IQL = tf.reduce_mean(tf.square(self.td_error))\n\n        self.IQL_opt = tf.train.AdamOptimizer(self.lr_Q)\n        self.IQL_op = self.IQL_opt.minimize(self.loss_IQL)\n\n    def create_summary(self):\n        \n        if self.alg_name == 'hsd-scripted':\n            summaries = [tf.summary.scalar('loss_Q_high', self.loss_Q_high)]\n            mixer_main_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Mixer_main')\n            for v in mixer_main_variables:\n                summaries.append(tf.summary.histogram(v.op.name, v))\n            grads = self.Q_opt.compute_gradients(self.loss_Q_high, mixer_main_variables)\n            for grad, var in grads:\n                if grad is not None:\n                    summaries.append( tf.summary.histogram(var.op.name+'/gradient', grad) )\n            \n            agent_main_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Agent_main')\n            for v in agent_main_variables:\n                summaries.append(tf.summary.histogram(v.op.name, v))\n            grads = self.Q_opt.compute_gradients(self.loss_Q_high, agent_main_variables)\n            for grad, var in grads:\n                if grad is not None:\n                    summaries.append( tf.summary.histogram(var.op.name+'/gradient', grad) )\n        elif self.alg_name == 'mara-c':\n            summaries = [tf.summary.scalar('loss_Q_high', self.loss_Q_high)]\n            Q_main_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Qhigh_main')\n            for v in Q_main_variables:\n                summaries.append(tf.summary.histogram(v.op.name, v))\n            grads = self.Q_opt.compute_gradients(self.loss_Q_high, Q_main_variables)\n            for grad, var in grads:\n                if grad is not None:\n                    summaries.append( tf.summary.histogram(var.op.name+'/gradient', grad) )\n\n        self.summary_op = tf.summary.merge(summaries)\n\n        summaries_low = [tf.summary.scalar('loss_IQL', self.loss_IQL)]\n        Qlow_main_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Qlow_main')\n        for v in Qlow_main_variables:\n            summaries_low.append(tf.summary.histogram(v.op.name, v))\n        grads = self.IQL_opt.compute_gradients(self.loss_IQL, Qlow_main_variables)\n        for grad, var in grads:\n            if grad is not None:\n                summaries_low.append( tf.summary.histogram(var.op.name+'/gradient', grad) )\n\n        self.summary_op_low = tf.summary.merge(summaries_low)\n\n    def process_actions(self, n_steps, actions, n_actions):\n        \"\"\"\n        Args:\n            n_steps: number of steps in trajectory\n            actions: must have shape [time, n_agents], and values are action indices\n            n_actions: dimension of action space\n\n        Returns: 1-hot representation of actions\n        \"\"\"\n        # Each row of actions is one time step,\n        # row contains action indices for all agents\n        # Convert to [time, agents, N_roles]\n        # so each agent gets its own 1-hot row vector\n        actions_1hot = np.zeros([n_steps, self.n_agents, n_actions], dtype=int)\n        grid = np.indices((n_steps, self.n_agents))\n        actions_1hot[grid[0], grid[1], actions] = 1\n\n        # In-place reshape of actions to [time*n_agents, N_roles]\n        actions_1hot.shape = (n_steps*self.n_agents, n_actions)\n\n        return actions_1hot\n\n    def process_batch(self, batch):\n        \"\"\"Used for high-level buffer\n        \n        Extract quantities of the same type from batch.\n        Format batch so that each agent at each time step is one batch entry.\n        \"\"\"\n        # shapes are [time, ...original dims...]\n        if self.alg_name == 'hsd-scripted':\n            state = np.stack(batch[:,0]) # [time, l_state]\n            obs = np.stack(batch[:,1]) # [time, agents, l_obs]\n            actions = np.stack(batch[:,2]) # [time, agents]\n            reward = np.stack(batch[:,3]) # [time]\n            state_next = np.stack(batch[:,4]) # [time, l_state]\n            obs_next = np.stack(batch[:,5]) # [time, agents, l_obs]\n            done = np.stack(batch[:,6]) # [time]\n        elif self.alg_name == 'mara-c':\n            state = np.stack(batch[:,0]) # [time, l_state]\n            actions = np.stack(batch[:,1]) # [time]\n            reward = np.stack(batch[:,2]) # [time]\n            state_next = np.stack(batch[:,3]) # [time, l_state]\n            done = np.stack(batch[:,4]) # [time]\n\n        # Try to free memory\n        batch = None\n    \n        n_steps = state.shape[0]\n\n        if self.alg_name == 'hsd-scripted':\n            # In-place reshape for obs, so that one time step\n            # for one agent is considered one batch entry\n            obs.shape = (n_steps * self.n_agents, self.l_obs)\n            obs_next.shape = (n_steps * self.n_agents, self.l_obs)\n            actions_1hot = self.process_actions(n_steps, actions, self.N_roles)\n            return n_steps, state, obs, actions_1hot, reward, state_next, obs_next, done\n        elif self.alg_name == 'mara-c':\n            actions_1hot = np.zeros([n_steps, self.dim_role_space])\n            actions_1hot[np.arange(n_steps), actions] = 1\n            return n_steps, state, actions_1hot, reward, state_next, done\n\n\n    def process_batch_low(self, batch):\n        \"\"\"\n        Extract quantities of the same type from batch.\n        Format batch so that each agent at each time step is one batch entry.\n        \"\"\"\n        # shapes are [time, ...original dims...]\n        # state = np.stack(batch[:,0]) # [time, l_state]\n        obs = np.stack(batch[:,0]) # [time, agents, l_obs]\n        actions = np.stack(batch[:,1]) # [time, agents]\n        rewards = np.stack(batch[:,2]) # [time, agents]\n        # state_next = np.stack(batch[:,4]) # [time, l_state]\n        obs_next = np.stack(batch[:,3]) # [time, agents, l_obs]\n        # done = np.stack(batch[:,6]) # [time]\n        roles = np.stack(batch[:,4]) # [time, agents, N_roles]\n\n        # Try to free memory\n        batch = None\n    \n        n_steps = obs.shape[0]\n\n        # In-place reshape for obs, so that one time step\n        # for one agent is considered one batch entry\n        obs.shape = (n_steps * self.n_agents, self.l_obs)\n        obs_next.shape = (n_steps * self.n_agents, self.l_obs)\n        rewards.shape = (n_steps * self.n_agents)\n        roles.shape = (n_steps * self.n_agents, self.N_roles)\n\n        actions_1hot = self.process_actions(n_steps, actions, self.l_action)\n            \n        return n_steps, obs, actions_1hot, rewards, obs_next, roles\n\n    def train_step(self, sess, batch, step_train=0, summarize=False, writer=None):\n        \"\"\"Training step for role assignment policy via QMIX or Q-learning.\"\"\"\n        if self.alg_name == 'hsd-scripted':\n            # Each agent for each time step is now a batch entry\n            n_steps, state, obs, actions_1hot, reward, state_next, obs_next, done = self.process_batch(batch)\n\n            # Get argmax actions from target networks\n            feed = {self.obs : obs_next}\n            argmax_actions = sess.run(self.argmax_Q_target, feed_dict=feed) # [batch*n_agents]\n            # Convert to 1-hot\n            actions_target_1hot = np.zeros([n_steps * self.n_agents, self.N_roles], dtype=int)\n            actions_target_1hot[np.arange(n_steps*self.n_agents), argmax_actions] = 1\n            \n            # Get Q_tot target value\n            feed = {self.state : state_next,\n                    self.actions_1hot : actions_target_1hot,\n                    self.obs : obs_next}\n            Q_tot_target = sess.run(self.mixer_target, feed_dict=feed)\n\n            done_multiplier = -(done - 1)\n            target = reward + self.gamma * np.squeeze(Q_tot_target) * done_multiplier\n        elif self.alg_name == 'mara-c':\n            n_steps, state, actions_1hot, reward, state_next, done = self.process_batch(batch)\n\n            feed = {self.state : state_next}\n            Q_target = sess.run(self.Q_high_target, feed_dict=feed)\n            target = reward + self.gamma * np.max(Q_target, axis=1)\n\n        feed = {self.state : state, self.td_target : target}\n        if self.alg_name == 'hsd-scripted':\n            feed[self.obs] = obs\n            feed[self.actions_1hot] = actions_1hot\n        elif self.alg_name == 'mara-c':\n            feed[self.actions_high_1hot] = actions_1hot\n\n        if summarize:\n            summary, _ = sess.run([self.summary_op, self.Q_op], feed_dict=feed)\n            writer.add_summary(summary, step_train)\n        else:\n            _ = sess.run(self.Q_op, feed_dict=feed)\n\n        sess.run(self.list_update_target_ops)\n\n    def train_step_low(self, sess, batch, step_train=0, summarize=False, writer=None):\n        \"\"\"Training step for low-level action policy.\n        \n        Runs independent Q-learning on each agent's experiences using local rewards\n        \"\"\"\n        n_steps, obs, actions_1hot, rewards, obs_next, roles = self.process_batch_low(batch)\n\n        # Get target values\n        feed = {self.obs : obs_next, self.role : roles}\n        Q_target = sess.run(self.Q_low_target, feed_dict=feed)\n        target = rewards + self.gamma * np.max(Q_target, axis=1)\n\n        feed = {self.obs : obs,\n                self.actions_low_1hot : actions_1hot,\n                self.role : roles,\n                self.td_target_IQL : target}\n        if summarize:\n            summary, _ = sess.run([self.summary_op_low, self.IQL_op], feed_dict=feed)\n            writer.add_summary(summary, step_train)\n        else:\n            _ = sess.run(self.IQL_op, feed_dict=feed)\n\n        sess.run(self.list_update_target_ops_low)\n", "meta": {"hexsha": "056aa116d947c19390eac75f71e80fd20e84a519", "size": 23644, "ext": "py", "lang": "Python", "max_stars_repo_path": "alg/alg_hsd_scripted.py", "max_stars_repo_name": "wwxFromTju/hierarchical-marl", "max_stars_repo_head_hexsha": "30f1e214759078b3f60ea715bac4d888cdd2cf5d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 42, "max_stars_repo_stars_event_min_datetime": "2020-03-14T08:28:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T18:17:42.000Z", "max_issues_repo_path": "alg/alg_hsd_scripted.py", "max_issues_repo_name": "011235813/hierarchical-marl", "max_issues_repo_head_hexsha": "cc6b08f00feb949387096990eb37e7071da7ecf6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "alg/alg_hsd_scripted.py", "max_forks_repo_name": "011235813/hierarchical-marl", "max_forks_repo_head_hexsha": "cc6b08f00feb949387096990eb37e7071da7ecf6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2020-03-18T07:00:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T02:57:38.000Z", "avg_line_length": 47.5734406439, "max_line_length": 163, "alphanum_fraction": 0.6212569785, "include": true, "reason": "import numpy", "num_tokens": 5432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.17477723273618384}}
{"text": "\"\"\" Code for fetching data for API.\n\"\"\"\n\nimport logging\nfrom typing import List\nimport datetime\nfrom datetime import timezone\nfrom scipy.interpolate import griddata, interp1d\nfrom geoalchemy2.shape import to_shape\nfrom shapely.geometry import Point, Polygon\nimport app.db.database\nfrom app.schemas import (WeatherStation, WeatherModelPrediction,\n                         WeatherModelPredictionValues, WeatherModelRun)\nfrom app.db.models import ModelRunGridSubsetPrediction\nimport app.db.crud\nfrom app.wildfire_one import get_stations_by_codes\nfrom app import config\nfrom app.models import ModelEnum\nfrom app.models.fetch import extract_stations_in_polygon\n\nlogger = logging.getLogger(__name__)\n\n\nclass MatchingStationNotFoundException(Exception):\n    \"\"\" Exception raised when station cannot be found. \"\"\"\n\n\nclass NoonInterpolator:\n    \"\"\" Interpolates a noon value using a value before noon, and after noon. \"\"\"\n\n    def __init__(self):\n        \"\"\" Init object. \"\"\"\n        # Keep track of previous values, in order to calculate missing noon value.\n        self.prev_values = {}\n        self.prev_timestamp = None\n        self.current_values = {}\n        self.current_timestamp = None\n        # Noon time for all our stations, in utc, is 12PST or 20h00UTC\n        self.utc_noon = datetime.time(hour=20)\n\n    def update(self, key, value, timestamp: datetime.datetime):\n        \"\"\" Update interpolater with latest value. \"\"\"\n        # before anything, lets translate the timestamp to utc\n        utc_timestamp = timestamp.astimezone(timezone.utc)\n        if self.current_timestamp != utc_timestamp:\n            # Swap out current with previous\n            self.prev_timestamp = self.current_timestamp\n            self.prev_values = self.current_values\n            # Reset current\n            self.current_values = {}\n            self.current_timestamp = utc_timestamp\n\n        self.current_values[key] = value\n\n    def is_before_noon(self, timestamp: datetime.datetime):\n        \"\"\" Return true if given time is before utc noon \"\"\"\n        return timestamp.time() < self.utc_noon\n\n    def is_after_noon(self, timestamp: datetime.datetime):\n        \"\"\" Retrun true if given time is after uct noon \"\"\"\n        return timestamp.time() > self.utc_noon\n\n    def calculate_noon_value(self) -> WeatherModelPredictionValues:\n        \"\"\" Calcualte the interpolated noon value (if possible) \"\"\"\n        # If the previous timestamp was before noon, and the current timestamp is after noon,\n        # it means there is no noon value, and we can interpolate one.\n        result = None\n        if (self.prev_timestamp and\n                self.is_before_noon(self.prev_timestamp) and\n                self.is_after_noon(self.current_timestamp)):\n            noon = datetime.datetime(year=self.prev_timestamp.year, month=self.prev_timestamp.month,\n                                     day=self.prev_timestamp.day, hour=self.utc_noon.hour,\n                                     minute=self.utc_noon.minute, tzinfo=timezone.utc)\n            result = WeatherModelPredictionValues(datetime=noon)\n            # x-axis is the timestamp\n            x_axis = (self.prev_timestamp.timestamp(),\n                      self.current_timestamp.timestamp())\n            # for each key value, we have a y-axis\n            y_axis = {}\n            for key, value in self.prev_values.items():\n                y_axis[key] = [value, self.current_values[key]]\n            for key, value in y_axis.items():\n                function = interp1d(x_axis, value, kind='linear')\n                interpolated_value = function(noon.timestamp())\n                # the interpolated value is in the form of an array, we just want the 1st element.\n                setattr(result, key, interpolated_value.item(0))\n        return result\n\n\ndef _add_model_prediction_record_to_prediction_schema(prediction_schema: WeatherModelPrediction,\n                                                      prediction_record: ModelRunGridSubsetPrediction,\n                                                      points: List[float],\n                                                      noon_interpolator: NoonInterpolator):\n    \"\"\" Add the model prediction for a particular timestamp to the prediction schema. \"\"\"\n    prediction_values = WeatherModelPredictionValues(\n        datetime=prediction_record.prediction_timestamp)\n    target_coordinate = [(prediction_schema.station.long,\n                          prediction_schema.station.lat)]\n    key_map = {\n        'tmp_tgl_2': 'temperature',\n        'rh_tgl_2': 'relative_humidity'\n    }\n\n    # Iterate through each of the mappings.\n    for key, target in key_map.items():\n        # Get the values.\n        values = getattr(prediction_record, key)\n        if values:\n            # If there are values, calculate the interpolated value, and set.\n            interpolated_value = griddata(\n                points, values, target_coordinate, method='linear')[0]\n            setattr(prediction_values, target, interpolated_value)\n            noon_interpolator.update(\n                target, interpolated_value, prediction_record.prediction_timestamp)\n\n    noon_value = noon_interpolator.calculate_noon_value()\n    if noon_value:\n        prediction_schema.values.append(noon_value)\n    prediction_schema.values.append(prediction_values)\n\n\ndef _fetch_model_predictions_by_stations(\n        session,\n        model: ModelEnum,\n        stations: List[WeatherStation]) -> List[WeatherModelPrediction]:\n    \"\"\" Fetch predictions for stations. \"\"\"\n    # pylint: disable=too-many-locals\n    # Get the most recent model run:\n    most_recent_run = app.db.crud.get_most_recent_model_run(\n        session, model, app.db.crud.LATLON_15X_15)\n    # Get the predictions:\n    query = app.db.crud.get_model_run_predictions(\n        session, most_recent_run, map(lambda station: [station.long, station.lat], stations))\n\n    # Construct response object:\n    model_run = WeatherModelRun(\n        datetime=most_recent_run.prediction_run_timestamp,\n        name=most_recent_run.prediction_model.name,\n        abbreviation=most_recent_run.prediction_model.abbreviation,\n        projection=most_recent_run.prediction_model.projection)\n\n    predictions = []\n    tmp_station_list = stations.copy()\n    prev_grid = None\n    points = None\n    stations_in_polygon = None\n    predictions_in_grid = {}\n\n    for grid, prediction_record in query:\n        if grid != prev_grid:\n            prev_grid = grid\n            predictions_in_grid = {}\n            # Get the bounding points (ignore the last point of the polygon)\n            poly = to_shape(grid.geom)\n            points = list(poly.exterior.coords)[:-1]\n            stations_in_polygon = extract_stations_in_polygon(\n                tmp_station_list, poly)\n            # Initialize predictions for all the stations in this grid.\n            for station in stations_in_polygon:\n                prediction = WeatherModelPrediction(\n                    station=station, model_run=model_run, values=[])\n                predictions.append(prediction)\n                predictions_in_grid[station.code] = prediction, NoonInterpolator(\n                )\n                logger.info(type(predictions_in_grid[station.code]))\n                # pop the station off the list\n                tmp_station_list.remove(station)\n\n        # It could conceivably happen that we have N where N>1 stations in a\n        # grid, in which case we need to iterate over the grid predictions N times.\n        for prediction, noon_interpolator in predictions_in_grid.values():\n            _add_model_prediction_record_to_prediction_schema(\n                prediction, prediction_record, points, noon_interpolator)\n        # NOTE: The code would be much simpler if we only did the interpolation afterwards.\n\n    return predictions\n\n\nasync def _fetch_model_predictions_by_station_codes(model: ModelEnum, station_codes: List[int]):\n    \"\"\" Fetch predictions from database.\n    \"\"\"\n    # Using the list of station codes, fetch the stations:\n    stations = await get_stations_by_codes(station_codes)\n    session = app.db.database.get_session()\n    # Fetch the all the predictions.\n    predictions = _fetch_model_predictions_by_stations(\n        session, model, stations)\n\n    return predictions\n\n\nasync def fetch_model_predictions(model: ModelEnum, station_codes: List[int]):\n    \"\"\" Fetch 10 day global model weather predictions for a given station.\"\"\"\n    # Fetch predictions from the database.\n    return await _fetch_model_predictions_by_station_codes(model, station_codes)\n", "meta": {"hexsha": "44642458de7b2536018736980c1e0a700869ff67", "size": 8541, "ext": "py", "lang": "Python", "max_stars_repo_path": "app/models/fetch/predictions.py", "max_stars_repo_name": "bcgov/wps-api", "max_stars_repo_head_hexsha": "1392ae87434428b10854bf67dd8b7517da6b3a02", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-12T02:59:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-12T02:59:08.000Z", "max_issues_repo_path": "app/models/fetch/predictions.py", "max_issues_repo_name": "bcgov/wps-api", "max_issues_repo_head_hexsha": "1392ae87434428b10854bf67dd8b7517da6b3a02", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 96, "max_issues_repo_issues_event_min_datetime": "2020-02-18T21:03:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-13T02:14:06.000Z", "max_forks_repo_path": "app/models/fetch/predictions.py", "max_forks_repo_name": "bcgov/wps-api", "max_forks_repo_head_hexsha": "1392ae87434428b10854bf67dd8b7517da6b3a02", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-03-06T18:49:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T22:41:23.000Z", "avg_line_length": 43.5765306122, "max_line_length": 102, "alphanum_fraction": 0.6669008313, "include": true, "reason": "from scipy", "num_tokens": 1650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.17475743960370999}}
{"text": "# Copyright (C) 2011 by Michele Silva (michele.silva@gmail.com)\n# This code is part of the Biopython distribution and governed by its\n# license. Please see the LICENSE file that should have been included\n# as part of this package.\n\nimport numpy\nimport math\nimport os\nimport warnings\nfrom time import time\n\nfrom mocapy.framework import EMEngine, mocapy_seed, eMISMASK\nfrom mocapy.inference import GibbsRandom, LikelihoodInfEngineHMM\n\nfrom Bio.PDB.TorusDBN import TorusDBNModel\nfrom Bio.PDB.TorusDBN.TorusDBNExceptions import TorusDBNBuildPolypeptideException, \\\n    TorusDBNChainBreakException, TorusDBNException, TorusDBNWarning\nfrom Bio.PDB.TorusDBN._io import read_missing_residues, create_sequence_from_file\n\n\n\nclass TorusDBNTrainer(object):\n    \"\"\" Allow training a TorusDBN model with a given training set. \"\"\"\n    \n\n    def __init__(self, seed=int(time()), show_info=False, show_warnings=True):\n        \"\"\"\n        @param seed: Seed for the random number generator.\n        @type seed: int\n        \n        @param show_info: Output information during the training.\n        @type show_info: bool\n        \n        @param show_warnings: Output warnings.\n        @type show_warnings: bool\n        \n        \"\"\"\n        # Mocapy config\n        mocapy_seed(seed)\n        \n        # Print information and warnings to the standard output\n        self.show_info = show_info\n        self.show_warnings = show_warnings\n                            \n        # Inference engine parameters\n        self.em_steps = 100\n        self.burnin_steps = 20\n        self.mcmc_steps = 1\n        \n        # Convergence check for the optimal node size search\n        self.check_convergence = False\n        self.convergence_window = 80\n        self.convergence_threshold = 55\n\n        # Default Model\n        self.model = TorusDBNModel(seed)\n        \n        # Training sequences and mismasks \n        self.seq_list = []\n        self.mismask_list = []\n        self.__missing_residues = {}\n                            \n        \n    def train(self, training_set, missing_residues=None, use_aic=False):\n        \"\"\" Train the model with a given training set.\n        \n        @param training_set: The files to be used in the training.\n        @type training_set: list(str)\n        \n        @param missing_residues: The file describing the missing residues in\n            the training set.\n        @type missing_residues: str\n        \n        @param use_aic: Use the Akaike information criterion to measure the \n            model fitness.\n        @type use_aic: bool\n        \n        \"\"\"\n        if not self.show_warnings:\n            warning_list = warnings.filters[:]\n            warnings.filterwarnings('ignore', category=TorusDBNWarning)\n            \n        if missing_residues is not None:\n            missing_residues = read_missing_residues(missing_residues)\n            \n        self.seq_list, self.mismask_list = self._create_sequence_and_mismask(\n            training_set, missing_residues)      \n        self.info('Training started...')\n        ic = self._train(use_aic)\n        self.info('Training finished.\\n')\n        \n        if not self.show_warnings:\n            warnings.filters = warning_list\n            \n        return ic        \n        \n        \n    def _train(self, use_aic):    \n        \"\"\" Train the model.\n        \n        @param use_aic: Use the Akaike information criterion to measure the \n            model fitness.\n        @type use_aic: bool\n        \n        \"\"\"    \n        dbn = self.model.dbn\n        \n        self.hmm_ll_calculator = LikelihoodInfEngineHMM(\n            dbn=dbn, hidden_node_index=0, check_dbn=False)\n                    \n        mcmc = GibbsRandom(dbn)\n        em = EMEngine(dbn, mcmc, self.seq_list, self.mismask_list, [])\n        \n        # EM loop\n        ll_list = []\n        for i in xrange(self.em_steps):\n            if i == 0:\n\t\t       em.do_E_step(1, self.burnin_steps)\n            else:\n\t\t       em.do_E_step(self.mcmc_steps, 0)\n            \n            ll_list.append(em.get_loglik())\n            em.do_M_step()\n            \n            if self.check_convergence:\n                if i > self.convergence_window:\n                     if self._get_hairiness(ll_list):\n                        break\n                        \n        if (use_aic):\n            return self.calculate_AIC()\n        else:\n            return self.calculate_BIC()\n\n    \n    def calculate_AIC(self):\n        \"\"\" The Akaike information criterion (AIC) is a measure of the relative \n        goodness of fit of a statistical model.\n        \n        Akaike, Hirotugu (1974). \"A new look at the statistical model \n        identification\". IEEE Transactions on Automatic Control 19 (6): \n        716-723. doi:10.1109/TAC.1974.1100705. MR0423716.\n        \"\"\"            \n        hmm_ll_calculator = LikelihoodInfEngineHMM(\n            dbn=self.model.dbn, hidden_node_index=0, check_dbn=False)\n        ll_full = hmm_ll_calculator.calc_ll(self.seq_list, self.mismask_list)\n        return 2 * ll_full - 2 * self._get_parameter_count()\n        \n                \n    def calculate_BIC(self):\n        \"\"\" The Bayesian information criterion (BIC) is a criterion for model \n        selection among a finite set of models.\n        \n        Schwarz, Gideon E. (1978). \"Estimating the dimension of a model\". Annals\n        of Statistics 6 (2): 461-464. doi:10.1214/aos/1176344136. MR468014.\n        \"\"\"            \n        hmm_ll_calculator = LikelihoodInfEngineHMM(\n            dbn=self.model.dbn, hidden_node_index=0, check_dbn=False)\n        ll_full = hmm_ll_calculator.calc_ll(self.seq_list, self.mismask_list)     \n        return 2 * ll_full - self._get_parameter_count() * math.log(\n            self._get_observation_count())\n\n    \n    def __get_hairiness(self, ll_list):\n        \"\"\" Check whether likelihood is oscilating during the training.\n        \n        @param ll_list: Likelihood list.\n        @type ll_list: list(float)\n        \n        \"\"\"\n        for j in xrange(self.convergence_window, len(ll_list)):\n\t\n            match=0\n            for i in xrange(self.convergence_window):               \n                # Test if likelihood is oscillating\n                if (ll_list[j-i] > ll_list[j-i+1] and ll_list[j-i] > ll_list[j-i-1]) \\\n                    or (ll_list[j-i] < ll_list[j-i-1] and ll_list[j-i] < ll_list[j-i+1]) :                \n                    match += 1                \n            \n            if match >= self.convergence_threshold:\n                return True\t\n        return False\t\n                \n                \n    def _create_sequence_and_mismask(self, training_set, missing_residues):\n        \"\"\" Create sequence and mismask (mask that identifies values as\n            hidden, observed or missing) from a training set.\n            \n        @param training_set: The files to be used in the training.\n        @type training_set: list(str)\n        \n        @param missing_residues: The file describing the missing residues in\n            the training set.\n        @type missing_residues: str\n        \n        \"\"\"\n        seq_list = []\n        mismask_list = []\n        \n        if not self.show_warnings:\n            warning_list = warnings.filters[:]\n            warnings.filterwarnings('ignore', category=TorusDBNWarning)\n            \n        training_set_count = len(training_set)\n        for filename in training_set:\n            self.info('Reading data from training file %s...' % (filename))\n            try:\n                sequences, mismasks = create_sequence_from_file(\n                    filename, missing_residues, not self.show_warnings)\n                seq_list += sequences\n                mismask_list += mismasks\n            except TorusDBNException as error:\n                warnings.warn(\n                    \"%s The file was not included in the training set.\" % error,\n                    TorusDBNWarning\n                )\n                training_set_count -= 1\n        self.info('\\n%d files included in the training set.' % (training_set_count))\n        if not self.show_warnings:\n            warnings.filters = warning_list\n        \n        return seq_list, mismask_list        \n            \n            \n    def find_optimal_model(\n        self, training_set, use_aic=False, min_node=10, \n        max_node=90, start_size=20, end_size=5, node_samples=4, \n        check_decreasing_ll=False, missing_residues=None):\n        \"\"\"\n        Optimization method to find the best size for the hidden node \n        according to a training set.\n        \n        @param training_set: The files to be used in the training.\n        @type training_set: list(str)\n        \n        @param min_node: Minimum size of the hidden node\n        @type min_node: int\n        \n        @param max_node: Maximum size of the hidden node\n        @type max_node: int\n        \n        @param start_size: Start size of the hidden node\n        @type start: int\n        \n        @param end_size: Final size of the hidden node\n        @type end: int\n        \n        @param use_aic: Use the Akaike information criterion to measure the \n            model fitness.\n        @type use_aic: bool        \n        \n        @param check_decreasing_ll: Check whether the loglikelihood is decreasing.\n        @type check_decreasing_ll: bool\n        \n        @param missing_residues: The file describing the missing residues in\n            the training set.\n        @type missing_residues: str\n        \n        \n        \"\"\"            \n        if not self.show_warnings:\n            warning_list = warnings.filters[:]\n            warnings.filterwarnings('ignore', category=TorusDBNWarning)\n            \n        if missing_residues is not None:\n            missing_residues = read_missing_residues(missing_residues)\n            \n        self.seq_list, self.mismask_list = self._create_sequence_and_mismask(\n            training_set, missing_residues)             \n            \n        max_position = 0\n        start_res = start_size\n        avg_full_LL = []\n        \n        IC_array = [[]*n for n in xrange(node_samples + 2)]\n        \n        # Decrease size resolution until threshold (end_size)\n        while start_size >= end_size:\n            # Loop over node sizes\n            for i in xrange(min_node, max_node + 1, start_size):\n                \n                # Continues if at the maximum node size from the previous resolution \n                if (len(IC_array[0]) > 0 and i == IC_array[0][max_position]) or i <= 0:\n                    continue\n\n                # Add node-size value to header\n                IC_array[0].append(i)\n                IC_cum = 0\n                \n                if start_res == start_size:\n                    avg_full_LL.append(0)\n                    \n                for j in xrange(1, node_samples + 1):\n                    self.info(\"Training with node size = %d (sample %d)\" % (i, j))\n                    self.model.create_dbn(hidden_node_size=i)\n                    IC = self._train(use_aic)\n                    IC_array[j].append(IC)\n                    IC_cum += IC\n                    \n                    if (check_decreasing_ll):\n                        # Save forward likelihoods in order to infer if it is decreasing\n                        hmm_ll_calculator = LikelihoodInfEngineHMM(\n                            dbn=self.model.dbn, hidden_node_index=0, check_dbn=False)\n                        ll_full = hmm_ll_calculator.calc_ll(self.seq_list, self.mismask_list)\n                        avg_full_LL[-1] = avg_full_LL[-1] + ll_full/self._get_observation_count()\n                    \n                # Calculate mean IC for each node-size and add to array\n                IC_array[node_samples + 1].append(IC_cum / node_samples)\n                \n                # Check if log-likelihood is decreasing \n                if (len(avg_full_LL) > 1) and (avg_full_LL[-1] < avg_full_LL[-2]) and \\\n                    (start_res == start_size) and check_decreasing_ll:\n                    self.info(\"Log-likelihood is decreasing. There is no reason to test higher node sizes.\")\n                    break\n                                     \n            # Column number for maximum IC value\n            max_position = IC_array[node_samples + 1].index(max(IC_array[node_samples + 1])) \n            self.info(\"Optimal node size: %s\\n\" % (IC_array[0][max_position]))\n          \n            # Update resolution\n            start_size = start_size / 2\n            \n            # Update node limits\n            min_node = IC_array[0][max_position] - start_size\n            max_node = IC_array[0][max_position] + start_size\n     \n        IC_max_node = IC_array[0][max_position]\n        \n        # Final train to the optimal model\n        dbn_list = []\n        IC_list = []\n        \n        for j in xrange(node_samples):\n            self.model.create_dbn(hidden_node_size=IC_max_node)\n            IC = self._train(use_aic)\n            IC_list.append(IC)\n            dbn_list.append(self.model.dbn)\n            \n        IC_max = max(IC_list)\n        self.model.dbn = dbn_list[IC_list.index(IC_max)]\n        \n        self.info(\"Optimal Model:\\nHidden node size = %s\\nIC = %s\\n\" % (IC_max_node, IC_max)) \n        \n        if not self.show_warnings:\n            warnings.filters = warning_list       \n        return IC_max_node, IC_max\n        \n\n    def info(self, message):\n        \"\"\" Print a message to the standard output, in case show_info is enabled.\n        \n        @param message: The message to be printed.\n        @type message: str\n        \n        \"\"\"\n        if self.show_info:\n            print(message)\n            \n    \n    def get_model(self):\n        \"\"\" Get the current TorusDBN model. \n        \n        @rtype: TorusDBNModel\n        @return: The model.\n                \n        \"\"\"\n        return self.model\n        \n    \n    def _get_observation_count(self):\n        \"\"\" The total number of observations.\n        \n        @rtype: int\n        @return: Number of observations.\n        \n        \"\"\"\n        observation_count = 0\n        for sequence in self.seq_list:\n            observation_count += sequence.shape[0]     \n            \n        return observation_count\n        \n                \n    def _get_parameter_count(self):\n        \"\"\" The number of parameters.\n        \n        @rtype: int\n        @return: Number of parameters.\n        \n        \"\"\"\n        parameters_d = 5;\n        size_h = self.model.size_h\n        return (size_h - 1) + size_h * (\n            (size_h - 1) + parameters_d + (self.model.size_aa - 1) + \n            (self.model.size_ss - 1) + (self.model.size_cis - 1)\n        )     \n", "meta": {"hexsha": "ce64c457a009f07b7c83577381039cf7cced1e70", "size": 14575, "ext": "py", "lang": "Python", "max_stars_repo_path": "Bio/PDB/TorusDBN/TorusDBNTrainer.py", "max_stars_repo_name": "mchelem/biopython", "max_stars_repo_head_hexsha": "2daa5fee06077bbada8b89fe6032c3f123318fc2", "max_stars_repo_licenses": ["PostgreSQL"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-29T17:32:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-29T17:32:16.000Z", "max_issues_repo_path": "Bio/PDB/TorusDBN/TorusDBNTrainer.py", "max_issues_repo_name": "mchelem/biopython", "max_issues_repo_head_hexsha": "2daa5fee06077bbada8b89fe6032c3f123318fc2", "max_issues_repo_licenses": ["PostgreSQL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Bio/PDB/TorusDBN/TorusDBNTrainer.py", "max_forks_repo_name": "mchelem/biopython", "max_forks_repo_head_hexsha": "2daa5fee06077bbada8b89fe6032c3f123318fc2", "max_forks_repo_licenses": ["PostgreSQL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7128463476, "max_line_length": 108, "alphanum_fraction": 0.5606174957, "include": true, "reason": "import numpy", "num_tokens": 3166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.174757436084208}}
{"text": "import struct\nimport math\nimport numpy as np\nimport warnings\nimport cv2\nfrom scipy import ndimage\nimport datetime\nimport os\nimport json\n\n# to convert action names to the corresponding ID number and vice-versa\nACTION_TO_ID = {'push': 0, 'grasp': 1, 'place': 2}\nID_TO_ACTION = {0: 'push', 1: 'grasp', 2: 'place'}\n\n\ndef mkdir_p(path):\n    \"\"\"Create the specified path on the filesystem like the `mkdir -p` command\n    Creates one or more filesystem directory levels as needed,\n    and does not return an error if the directory already exists.\n    \"\"\"\n    # http://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python\n    try:\n        os.makedirs(path)\n    except OSError as exc:  # Python >2.5\n        if exc.errno == errno.EEXIST and os.path.isdir(path):\n            pass\n        else:\n            raise\n\n\ndef timeStamped(fname, fmt='%Y-%m-%d-%H-%M-%S_{fname}'):\n    \"\"\" Apply a timestamp to the front of a filename description.\n    see: http://stackoverflow.com/a/5215012/99379\n    \"\"\"\n    return datetime.datetime.now().strftime(fmt).format(fname=fname)\n\n\nclass NumpyEncoder(json.JSONEncoder):\n    \"\"\" json encoder for numpy types\n    source: https://stackoverflow.com/a/49677241/99379\n    \"\"\"\n    def default(self, obj):\n        if isinstance(obj,\n            (np.int_, np.intc, np.intp, np.int8,\n             np.int16, np.int32, np.int64, np.uint8,\n             np.uint16, np.uint32, np.uint64)):\n            return int(obj)\n        elif isinstance(obj,\n           (np.float_, np.float16, np.float32,\n            np.float64)):\n            return float(obj)\n        elif isinstance(obj, (np.ndarray,)):\n            return obj.tolist()\n        return json.JSONEncoder.default(self, obj)\n\n\ndef clearance_log_to_trial_count(clearance_log):\n    \"\"\" Convert clearance log list of end indices to a list of the current trial number at each iteration.\n\n    # Returns\n\n    List of lists of the current trial index.\n    ex: [[0], [0], [0], [1], [1]]\n    \"\"\"\n    if not len(clearance_log):\n        return []\n    clearance_log = np.squeeze(clearance_log).astype(np.int)\n    # Make a list of the right length containing all zeros\n    trial_count = []\n    prev_trial_end_index = 0\n    for trial_num, trial_end_index in enumerate(clearance_log):\n        trial_count += [[trial_num]] * int(trial_end_index - prev_trial_end_index)\n        prev_trial_end_index = trial_end_index\n    return trial_count\n\n\ndef get_pointcloud(color_img, depth_img, camera_intrinsics):\n\n    # Get depth image size\n    im_h = depth_img.shape[0]\n    im_w = depth_img.shape[1]\n\n    # Project depth into 3D point cloud in camera coordinates\n    pix_x,pix_y = np.meshgrid(np.linspace(0,im_w-1,im_w), np.linspace(0,im_h-1,im_h))\n    cam_pts_x = np.multiply(pix_x-camera_intrinsics[0][2],depth_img/camera_intrinsics[0][0])\n    cam_pts_y = np.multiply(pix_y-camera_intrinsics[1][2],depth_img/camera_intrinsics[1][1])\n    cam_pts_z = depth_img.copy()\n    cam_pts_x.shape = (im_h*im_w,1)\n    cam_pts_y.shape = (im_h*im_w,1)\n    cam_pts_z.shape = (im_h*im_w,1)\n\n    # Reshape image into colors for 3D point cloud\n    rgb_pts_r = color_img[:,:,0]\n    rgb_pts_g = color_img[:,:,1]\n    rgb_pts_b = color_img[:,:,2]\n    rgb_pts_r.shape = (im_h*im_w,1)\n    rgb_pts_g.shape = (im_h*im_w,1)\n    rgb_pts_b.shape = (im_h*im_w,1)\n\n    cam_pts = np.concatenate((cam_pts_x, cam_pts_y, cam_pts_z), axis=1)\n    rgb_pts = np.concatenate((rgb_pts_r, rgb_pts_g, rgb_pts_b), axis=1)\n\n    return cam_pts, rgb_pts\n\n\ndef get_heightmap(color_img, depth_img, cam_intrinsics, cam_pose, workspace_limits, heightmap_resolution, background_heightmap=None, median_filter_pixels=5):\n\n    if median_filter_pixels > 0:\n        depth_img = ndimage.median_filter(depth_img, size=median_filter_pixels)\n\n    # Compute heightmap size\n    heightmap_size = np.round(((workspace_limits[1][1] - workspace_limits[1][0])/heightmap_resolution, (workspace_limits[0][1] - workspace_limits[0][0])/heightmap_resolution)).astype(int)\n    depth_heightmap = np.zeros(heightmap_size)\n\n    # Get 3D point cloud from RGB-D images\n    surface_pts, color_pts = get_pointcloud(color_img, depth_img, cam_intrinsics)\n\n    # Transform 3D point cloud from camera coordinates to robot coordinates\n    surface_pts = np.transpose(np.dot(cam_pose[0:3,0:3],np.transpose(surface_pts)) + np.tile(cam_pose[0:3,3:],(1,surface_pts.shape[0])))\n\n    # Sort surface points by z value\n    sort_z_ind = np.argsort(surface_pts[:,2])\n    surface_pts = surface_pts[sort_z_ind]\n    color_pts = color_pts[sort_z_ind]\n\n    # Filter out surface points outside heightmap boundaries\n    heightmap_valid_ind = np.logical_and(np.logical_and(np.logical_and(np.logical_and(surface_pts[:,0] >= workspace_limits[0][0], surface_pts[:,0] < workspace_limits[0][1]), surface_pts[:,1] >= workspace_limits[1][0]), surface_pts[:,1] < workspace_limits[1][1]), surface_pts[:,2] < workspace_limits[2][1])\n    surface_pts = surface_pts[heightmap_valid_ind]\n    color_pts = color_pts[heightmap_valid_ind]\n\n    # Create orthographic top-down-view RGB-D depth heightmap\n    heightmap_pix_x = np.floor((surface_pts[:,0] - workspace_limits[0][0])/heightmap_resolution).astype(int)\n    heightmap_pix_y = np.floor((surface_pts[:,1] - workspace_limits[1][0])/heightmap_resolution).astype(int)\n    depth_heightmap[heightmap_pix_y,heightmap_pix_x] = surface_pts[:,2]\n    z_bottom = workspace_limits[2][0]\n    depth_heightmap = depth_heightmap - z_bottom\n    depth_heightmap[depth_heightmap < 0] = 0\n    if median_filter_pixels > 0:\n        depth_heightmap = ndimage.median_filter(depth_heightmap, size=median_filter_pixels)\n    depth_heightmap[depth_heightmap == -z_bottom] = np.nan\n    # subtract out the scene background heights, if available\n    if background_heightmap is not None:\n        depth_heightmap -= background_heightmap\n        min_z = np.nanmin(depth_heightmap)\n        if min_z < 0:\n            depth_heightmap = np.clip(depth_heightmap, 0, None)\n            if min_z < -0.005:\n                print('WARNING: get_heightmap() depth_heightmap contains negative heights with min ' + str(min_z) + ', '\n                    'saved depth heightmap png files may be invalid! '\n                    'See README.md for instructions to collect the depth heightmap again. '\n                    'Clipping the minimum to 0 for now.')\n\n    # Create orthographic top-down-view RGB-D color heightmaps\n    color_heightmap_r = np.zeros((heightmap_size[0], heightmap_size[1], 1), dtype=np.uint8)\n    color_heightmap_g = np.zeros((heightmap_size[0], heightmap_size[1], 1), dtype=np.uint8)\n    color_heightmap_b = np.zeros((heightmap_size[0], heightmap_size[1], 1), dtype=np.uint8)\n    color_heightmap_r[heightmap_pix_y,heightmap_pix_x] = color_pts[:,[0]]\n    color_heightmap_g[heightmap_pix_y,heightmap_pix_x] = color_pts[:,[1]]\n    color_heightmap_b[heightmap_pix_y,heightmap_pix_x] = color_pts[:,[2]]\n    if median_filter_pixels > 0:\n        color_heightmap_r = ndimage.median_filter(color_heightmap_r, size=median_filter_pixels)\n        color_heightmap_b = ndimage.median_filter(color_heightmap_b, size=median_filter_pixels)\n        color_heightmap_g = ndimage.median_filter(color_heightmap_g, size=median_filter_pixels)\n    color_heightmap = np.concatenate((color_heightmap_r, color_heightmap_g, color_heightmap_b), axis=2)\n\n\n    return color_heightmap, depth_heightmap\n\ndef common_sense_action_failure_heuristic(heightmap, heightmap_resolution=0.002, gripper_width=0.06, min_contact_height=0.02, push_length=0.0, z_buffer=0.01):\n    \"\"\" Get heuristic scores for the grasp Q value at various pixels. 0 means our model confidently indicates no progress will be made, 1 means progress may be possible.\n    \"\"\"\n    pixels_to_dilate = int(np.ceil((gripper_width + push_length)/heightmap_resolution))\n    kernel = np.ones((pixels_to_dilate, pixels_to_dilate), np.uint8)\n    object_pixels = (heightmap > min_contact_height).astype(np.uint8)\n    contactable_regions = cv2.dilate(object_pixels, kernel, iterations=1)\n\n    if push_length > 0.0:\n        # For push, skip regions where the gripper would be too high\n        reigonal_maximums = ndimage.maximum_filter(heightmap, (pixels_to_dilate, pixels_to_dilate))\n        block_pixels = (heightmap > (reigonal_maximums - z_buffer)).astype(np.uint8)\n        # set all the pixels where the push would be too high to zero,\n        # meaning it is not an action which would contact any object\n        # the blocks and the gripper width around them are set to zero.\n        gripper_width_pixels_to_dilate = int(np.ceil((gripper_width)/heightmap_resolution))\n        kernel = np.ones((gripper_width_pixels_to_dilate, gripper_width_pixels_to_dilate), np.uint8)\n        push_too_high_pixels = cv2.dilate(block_pixels, kernel, iterations=1)\n        contactable_regions[np.nonzero(push_too_high_pixels)] = 0\n\n    return contactable_regions\n\ndef common_sense_action_space_mask(depth_heightmap, push_predictions=None, grasp_predictions=None, place_predictions=None, place_dilation=None, show_heightmap=False, color_heightmap=None):\n    \"\"\" Convert predictions to a masked array indicating if tasks may make progress in this region, based on depth_heightmap.\n\n    The masked arrays will indicate 0 where progress may be possible (no mask applied), and 1 where our model confidently indicates no progress will be made.\n    Note the mask values here are the opposite of the common_sense_failure_heuristic() function, so where that function has a mask value of 0, this function has a value of 1. \n    In other words the mask values returned here are equivalent to 1-common_sense_action_failure_heuristic(). \n    This is because in the numpy MaksedArray a True value inticates the data at the corresponding location is INVALID.\n\n    # Returns\n\n    Numpy MaskedArrays push_predictions, grasp_predictions, place_predictions\n    \"\"\"\n    # TODO(ahundt) \"common sense\" dynamic action space parameters should be accessible from the command line\n    # \"common sense\" dynamic action space, mask pixels we know cannot lead to progress\n    if push_predictions is not None:\n        push_contactable_regions = common_sense_action_failure_heuristic(depth_heightmap, gripper_width=0.04, push_length=0.1)\n        # \"1 - push_contactable_regions\" switches the values to mark masked regions we should not visit with the value 1\n        push_predictions = np.ma.masked_array(push_predictions, np.broadcast_to(1 - push_contactable_regions, push_predictions.shape, subok=True))\n    if grasp_predictions is not None:\n        grasp_contact_regions = common_sense_action_failure_heuristic(depth_heightmap, gripper_width=0.00)\n        grasp_predictions = np.ma.masked_array(grasp_predictions, np.broadcast_to(1 - grasp_contact_regions, push_predictions.shape, subok=True))\n    if place_predictions is not None:\n        place_contact_regions = common_sense_action_failure_heuristic(depth_heightmap, gripper_width=place_dilation)\n        place_predictions = np.ma.masked_array(place_predictions, np.broadcast_to(1 - place_contact_regions, push_predictions.shape, subok=True))\n    if show_heightmap:\n        # visualize the common sense function results\n        # show the heightmap\n        f = plt.figure()\n        # f.suptitle(str(trainer.iteration))\n        f.add_subplot(1,4, 1)\n        if grasp_predictions is not None:\n            plt.imshow(grasp_contact_regions)\n        f.add_subplot(1,4, 2)\n        if push_predictions is not None:\n            plt.imshow(push_contactable_regions)\n        f.add_subplot(1,4, 3)\n        plt.imshow(depth_heightmap)\n        f.add_subplot(1,4, 4)\n        if color_heightmap is not None:\n            plt.imshow(color_heightmap)\n        plt.show(block=True)\n    return push_predictions, grasp_predictions, place_predictions\n\n# Save a 3D point cloud to a binary .ply file\ndef pcwrite(xyz_pts, filename, rgb_pts=None):\n    assert xyz_pts.shape[1] == 3, 'input XYZ points should be an Nx3 matrix'\n    if rgb_pts is None:\n        rgb_pts = np.ones(xyz_pts.shape).astype(np.uint8)*255\n    assert xyz_pts.shape == rgb_pts.shape, 'input RGB colors should be Nx3 matrix and same size as input XYZ points'\n\n    # Write header for .ply file\n    pc_file = open(filename, 'wb')\n    pc_file.write('ply\\n')\n    pc_file.write('format binary_little_endian 1.0\\n')\n    pc_file.write('element vertex %d\\n' % xyz_pts.shape[0])\n    pc_file.write('property float x\\n')\n    pc_file.write('property float y\\n')\n    pc_file.write('property float z\\n')\n    pc_file.write('property uchar red\\n')\n    pc_file.write('property uchar green\\n')\n    pc_file.write('property uchar blue\\n')\n    pc_file.write('end_header\\n')\n\n    # Write 3D points to .ply file\n    for i in range(xyz_pts.shape[0]):\n        pc_file.write(bytearray(struct.pack(\"fffccc\",xyz_pts[i][0],xyz_pts[i][1],xyz_pts[i][2],rgb_pts[i][0].tostring(),rgb_pts[i][1].tostring(),rgb_pts[i][2].tostring())))\n    pc_file.close()\n\n\ndef get_affordance_vis(grasp_affordances, input_images, num_rotations, best_pix_ind):\n    vis = None\n    for vis_row in range(num_rotations/4):\n        tmp_row_vis = None\n        for vis_col in range(4):\n            rotate_idx = vis_row*4+vis_col\n            affordance_vis = grasp_affordances[rotate_idx,:,:]\n            affordance_vis[affordance_vis < 0] = 0 # assume probability\n            # affordance_vis = np.divide(affordance_vis, np.max(affordance_vis))\n            affordance_vis[affordance_vis > 1] = 1 # assume probability\n            affordance_vis.shape = (grasp_affordances.shape[1], grasp_affordances.shape[2])\n            affordance_vis = cv2.applyColorMap((affordance_vis*255).astype(np.uint8), cv2.COLORMAP_JET)\n            input_image_vis = (input_images[rotate_idx,:,:,:]*255).astype(np.uint8)\n            input_image_vis = cv2.resize(input_image_vis, (0,0), fx=0.5, fy=0.5, interpolation=cv2.INTER_NEAREST)\n            affordance_vis = (0.5*cv2.cvtColor(input_image_vis, cv2.COLOR_RGB2BGR) + 0.5*affordance_vis).astype(np.uint8)\n            if rotate_idx == best_pix_ind[0]:\n                affordance_vis = cv2.circle(affordance_vis, (int(best_pix_ind[2]), int(best_pix_ind[1])), 7, (0,0,255), 2)\n            if tmp_row_vis is None:\n                tmp_row_vis = affordance_vis\n            else:\n                tmp_row_vis = np.concatenate((tmp_row_vis,affordance_vis), axis=1)\n        if vis is None:\n            vis = tmp_row_vis\n        else:\n            vis = np.concatenate((vis,tmp_row_vis), axis=0)\n\n    return vis\n\n\ndef get_difference(color_heightmap, color_space, bg_color_heightmap):\n\n    color_space = np.concatenate((color_space, np.asarray([[0.0, 0.0, 0.0]])), axis=0)\n    color_space.shape = (color_space.shape[0], 1, 1, color_space.shape[1])\n    color_space = np.tile(color_space, (1, color_heightmap.shape[0], color_heightmap.shape[1], 1))\n\n    # Normalize color heightmaps\n    color_heightmap = color_heightmap.astype(float)/255.0\n    color_heightmap.shape = (1, color_heightmap.shape[0], color_heightmap.shape[1], color_heightmap.shape[2])\n    color_heightmap = np.tile(color_heightmap, (color_space.shape[0], 1, 1, 1))\n\n    bg_color_heightmap = bg_color_heightmap.astype(float)/255.0\n    bg_color_heightmap.shape = (1, bg_color_heightmap.shape[0], bg_color_heightmap.shape[1], bg_color_heightmap.shape[2])\n    bg_color_heightmap = np.tile(bg_color_heightmap, (color_space.shape[0], 1, 1, 1))\n\n    # Compute nearest neighbor distances to key colors\n    key_color_dist = np.sqrt(np.sum(np.power(color_heightmap - color_space,2), axis=3))\n    # key_color_dist_prob = F.softmax(Variable(torch.from_numpy(key_color_dist), volatile=True), dim=0).data.numpy()\n\n    bg_key_color_dist = np.sqrt(np.sum(np.power(bg_color_heightmap - color_space,2), axis=3))\n    # bg_key_color_dist_prob = F.softmax(Variable(torch.from_numpy(bg_key_color_dist), volatile=True), dim=0).data.numpy()\n\n    key_color_match = np.argmin(key_color_dist, axis=0)\n    bg_key_color_match = np.argmin(bg_key_color_dist, axis=0)\n    key_color_match[key_color_match == color_space.shape[0] - 1] = color_space.shape[0] + 1\n    bg_key_color_match[bg_key_color_match == color_space.shape[0] - 1] = color_space.shape[0] + 2\n\n    return np.sum(key_color_match == bg_key_color_match).astype(float)/np.sum(bg_key_color_match < color_space.shape[0]).astype(float)\n\n\n# Get rotation matrix from euler angles\ndef euler2rotm(theta):\n    R_x = np.array([[1,         0,                  0                   ],\n                    [0,         math.cos(theta[0]), -math.sin(theta[0]) ],\n                    [0,         math.sin(theta[0]), math.cos(theta[0])  ]\n                    ])\n    R_y = np.array([[math.cos(theta[1]),    0,      math.sin(theta[1])  ],\n                    [0,                     1,      0                   ],\n                    [-math.sin(theta[1]),   0,      math.cos(theta[1])  ]\n                    ])\n    R_z = np.array([[math.cos(theta[2]),    -math.sin(theta[2]),    0],\n                    [math.sin(theta[2]),    math.cos(theta[2]),     0],\n                    [0,                     0,                      1]\n                    ])\n    R = np.dot(R_z, np.dot( R_y, R_x ))\n    return R\n\n\n# Checks if a matrix is a valid rotation matrix.\ndef isRotm(R) :\n    Rt = np.transpose(R)\n    shouldBeIdentity = np.dot(Rt, R)\n    I = np.identity(3, dtype = R.dtype)\n    n = np.linalg.norm(I - shouldBeIdentity)\n    return n < 1e-6\n\n\n# Calculates rotation matrix to euler angles\ndef rotm2euler(R) :\n\n    assert(isRotm(R))\n\n    sy = math.sqrt(R[0,0] * R[0,0] +  R[1,0] * R[1,0])\n    singular = sy < 1e-6\n\n    if  not singular :\n        x = math.atan2(R[2,1] , R[2,2])\n        y = math.atan2(-R[2,0], sy)\n        z = math.atan2(R[1,0], R[0,0])\n    else :\n        x = math.atan2(-R[1,2], R[1,1])\n        y = math.atan2(-R[2,0], sy)\n        z = 0\n\n    return np.array([x, y, z])\n\n\ndef angle2rotm(angle, axis, point=None):\n    # Copyright (c) 2006-2018, Christoph Gohlke\n\n    sina = math.sin(angle)\n    cosa = math.cos(angle)\n    axis_magnitude = np.linalg.norm(axis)\n    axis = np.divide(axis, axis_magnitude, out=np.zeros_like(axis), where=axis_magnitude!=0)\n\n    # Rotation matrix around unit vector\n    R = np.diag([cosa, cosa, cosa])\n    R += np.array(np.outer(axis, axis) * (1.0 - cosa))\n    axis *= sina\n    RA = np.array([[ 0.0,     -axis[2],  axis[1]],\n                      [ axis[2], 0.0,      -axis[0]],\n                      [-axis[1], axis[0],  0.0]])\n    R = RA + np.array(R)\n    M = np.identity(4)\n    M[:3, :3] = R\n    if point is not None:\n\n        # Rotation not around origin\n        point = np.array(point[:3], dtype=np.float64, copy=False)\n        M[:3, 3] = point - np.dot(R, point)\n    return M\n\n\ndef rotm2angle(R):\n    # From: euclideanspace.com\n\n    epsilon = 0.01 # Margin to allow for rounding errors\n    epsilon2 = 0.1 # Margin to distinguish between 0 and 180 degrees\n\n    assert(isRotm(R))\n\n    if ((abs(R[0][1]-R[1][0])< epsilon) and (abs(R[0][2]-R[2][0])< epsilon) and (abs(R[1][2]-R[2][1])< epsilon)):\n        # Singularity found\n        # First check for identity matrix which must have +1 for all terms in leading diagonaland zero in other terms\n        if ((abs(R[0][1]+R[1][0]) < epsilon2) and (abs(R[0][2]+R[2][0]) < epsilon2) and (abs(R[1][2]+R[2][1]) < epsilon2) and (abs(R[0][0]+R[1][1]+R[2][2]-3) < epsilon2)):\n            # this singularity is identity matrix so angle = 0\n            return [0,1,0,0] # zero angle, arbitrary axis\n\n        # Otherwise this singularity is angle = 180\n        angle = np.pi\n        xx = (R[0][0]+1)/2\n        yy = (R[1][1]+1)/2\n        zz = (R[2][2]+1)/2\n        xy = (R[0][1]+R[1][0])/4\n        xz = (R[0][2]+R[2][0])/4\n        yz = (R[1][2]+R[2][1])/4\n        if ((xx > yy) and (xx > zz)): # R[0][0] is the largest diagonal term\n            if (xx< epsilon):\n                x = 0\n                y = 0.7071\n                z = 0.7071\n            else:\n                x = np.sqrt(xx)\n                y = xy/x\n                z = xz/x\n        elif (yy > zz): # R[1][1] is the largest diagonal term\n            if (yy< epsilon):\n                x = 0.7071\n                y = 0\n                z = 0.7071\n            else:\n                y = np.sqrt(yy)\n                x = xy/y\n                z = yz/y\n        else: # R[2][2] is the largest diagonal term so base result on this\n            if (zz< epsilon):\n                x = 0.7071\n                y = 0.7071\n                z = 0\n            else:\n                z = np.sqrt(zz)\n                x = xz/z\n                y = yz/z\n        return [angle,x,y,z] # Return 180 deg rotation\n\n    # As we have reached here there are no singularities so we can handle normally\n    s = np.sqrt((R[2][1] - R[1][2])*(R[2][1] - R[1][2]) + (R[0][2] - R[2][0])*(R[0][2] - R[2][0]) + (R[1][0] - R[0][1])*(R[1][0] - R[0][1])) # used to normalise\n    if (abs(s) < 0.001):\n        s = 1\n\n    # Prevent divide by zero, should not happen if matrix is orthogonal and should be\n    # Caught by singularity test above, but I've left it in just in case\n    angle = np.arccos(( R[0][0] + R[1][1] + R[2][2] - 1)/2)\n    x = (R[2][1] - R[1][2])/s\n    y = (R[0][2] - R[2][0])/s\n    z = (R[1][0] - R[0][1])/s\n    return [angle,x,y,z]\n\n\ndef quat2rotm(quat):\n    \"\"\"\n    Quaternion to rotation matrix.\n\n    Args:\n    - quat (4, numpy array): quaternion w, x, y, z\n    Returns:\n    - rotm: (3x3 numpy array): rotation matrix\n    \"\"\"\n    w = quat[0]\n    x = quat[1]\n    y = quat[2]\n    z = quat[3]\n\n    s = w*w + x*x + y*y + z*z\n\n    rotm = np.array([[1-2*(y*y+z*z)/s, 2*(x*y-z*w)/s,   2*(x*z+y*w)/s  ],\n                     [2*(x*y+z*w)/s,   1-2*(x*x+z*z)/s, 2*(y*z-x*w)/s  ],\n                     [2*(x*z-y*w)/s,   2*(y*z+x*w)/s,   1-2*(x*x+y*y)/s]\n    ])\n\n    return rotm\n\n\ndef make_rigid_transformation(pos, orn):\n    \"\"\"\n    Rigid transformation from position and orientation.\n    Args:\n    - pos (3, numpy array): translation\n    - orn (4, numpy array): orientation in quaternion\n    Returns:\n    - homo_mat (4x4 numpy array): homogenenous transformation matrix\n    \"\"\"\n    rotm = quat2rotm(orn)\n    homo_mat = np.c_[rotm, np.reshape(pos, (3, 1))]\n    homo_mat = np.r_[homo_mat, [[0, 0, 0, 1]]]\n\n    return homo_mat\n\n\ndef axis_angle_and_translation_to_rigid_transformation(tool_position, tool_orientation):\n    tool_orientation_angle = np.linalg.norm(tool_orientation)\n    tool_orientation_axis = tool_orientation/tool_orientation_angle\n    # Note that this following rotm is the base frame in tool frame\n    tool_orientation_rotm = angle2rotm(tool_orientation_angle, tool_orientation_axis, point=None)[:3,:3]\n    # Tool rigid body transformation\n    tool_transformation = np.zeros((4, 4))\n    tool_transformation[:3, :3] = tool_orientation_rotm\n    tool_transformation[:3, 3] = tool_position\n    tool_transformation[3, 3] = 1\n    return tool_transformation\n\n\ndef axxb(robotPose, markerPose, baseToCamera=True):\n    \"\"\"\n    Copyright (c) 2019, Hongtao Wu\n    AX=XB solver for eye-on base\n    Using the Park and Martin Method: https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=326576\n\n    Args:\n    - robotPose (list of 4x4 numpy array): poses (homogenous transformation) of the robot end-effector in the robot base frame.\n    - markerPose (list of 4x4 numpy array): poses (homogenous transformation) of the marker in the camera frame.\n    - baseToCamera (boolean): If true it will compute the base to camera transform, if false it will compute the robot tip to fiducial transform.\n\n    Return:\n    - cam2base (4x4 numpy array): poses of the camera in robot base frame.\n    \"\"\"\n\n    assert len(robotPose) == len(markerPose), 'robot poses and marker poses are not of the same length!'\n\n    n = len(robotPose)\n    print(\"Total number of poses: %i\" % n)\n    A = np.zeros((4, 4, n-1))\n    B = np.zeros((4, 4, n-1))\n    alpha = np.zeros((3, n-1))\n    beta = np.zeros((3, n-1))\n\n    M = np.zeros((3, 3))\n\n    nan_num = 0\n\n    sequence = np.arange(n)\n    np.random.shuffle(sequence)\n\n    for i in range(n-1):\n        if baseToCamera:\n            # compute the robot base to the robot camera\n            A[:, :, i] = np.matmul(robotPose[sequence[i+1]], pose_inv(robotPose[sequence[i]]))\n            B[:, :, i] = np.matmul(markerPose[sequence[i+1]], pose_inv(markerPose[sequence[i]]))\n        else:\n            # compute the robot tool tip to the robot fiducial marker seen by the camera\n            A[:, :, i] = np.matmul(pose_inv(robotPose[sequence[i+1]]), robotPose[sequence[i]])\n            B[:, :, i] = np.matmul(pose_inv(markerPose[sequence[i+1]]), markerPose[sequence[i]])\n\n        alpha[:, i] = get_mat_log(A[:3, :3, i])\n        beta[:, i] = get_mat_log(B[:3, :3, i])\n\n        # Bad pair of transformation are very close in the orientation.\n        # They will give nan result\n        if np.sum(np.isnan(alpha[:, i])) + np.sum(np.isnan(beta[:, i])) > 0:\n            nan_num += 1\n            continue\n        else:\n            M += np.outer(beta[:, i], alpha[:, i])\n\n    print(\"Invalid poses number: {}\".format(nan_num))\n\n    # Get the rotation matrix\n    mtm = np.matmul(M.T, M)\n    u_mtm, s_mtm, vh_mtm = np.linalg.svd(mtm)\n\n    R = np.matmul(np.matmul(np.matmul(u_mtm, np.diag(np.power(s_mtm, -0.5))), vh_mtm), M.T)\n\n    # Get the tranlation vector\n    I_Ra_Left = np.zeros((3*(n-1), 3))\n    ta_Rtb_Right = np.zeros((3 * (n-1), 1))\n    for i in range(n-1):\n        I_Ra_Left[(3*i):(3*(i+1)), :] = np.eye(3) - A[:3, :3, i]\n        ta_Rtb_Right[(3*i):(3*(i+1)), :] = np.reshape(A[:3, 3, i] - np.dot(R, B[:3, 3, i]), (3, 1))\n    t = np.linalg.lstsq(I_Ra_Left, ta_Rtb_Right, rcond=None)[0]\n\n    cam2base = np.c_[R, t]\n    cam2base = np.r_[cam2base, [[0, 0, 0, 1]]]\n\n    return cam2base\n\n\ndef pose_inv(pose):\n    \"\"\"\n    Inverse of a homogenenous transformation.\n    Args:\n    - pose (4x4 numpy array)\n    Return:\n    - inv_pose (4x4 numpy array)\n    \"\"\"\n    R = pose[:3, :3]\n    t = pose[:3, 3]\n\n    inv_R = R.T\n    inv_t = - np.dot(inv_R, t)\n\n    inv_pose = np.c_[inv_R, np.transpose(inv_t)]\n    inv_pose = np.r_[inv_pose, [[0, 0, 0, 1]]]\n\n    return inv_pose\n\n\ndef get_mat_log(R):\n    \"\"\"\n    Get the log(R) of the rotation matrix R.\n\n    Args:\n    - R (3x3 numpy array): rotation matrix\n    Returns:\n    - w (3, numpy array): log(R)\n    \"\"\"\n    theta = np.arccos((np.trace(R) - 1) / 2)\n    w_hat = (R - R.T) * theta / (2 * np.sin(theta))  # Skew symmetric matrix\n    w = np.array([w_hat[2, 1], w_hat[0, 2], w_hat[1, 0]])  # [w1, w2, w3]\n\n    return w\n\n\ndef calib_grid_cartesian(workspace_limits, calib_grid_step):\n    \"\"\"\n    Construct 3D calibration grid across workspace\n\n    # Arguments\n\n        workspace_limits: list of [min,max] coordinates for the list [x, y, z] in meters.\n        calib_grid_step: the step size of points in a 3d grid to be created in meters.\n\n    # Returns\n\n        num_calib_grid_pts, calib_grid_pts\n    \"\"\"\n    gridspace_x = np.linspace(workspace_limits[0][0], workspace_limits[0][1], (workspace_limits[0][1] - workspace_limits[0][0])/calib_grid_step)\n    gridspace_y = np.linspace(workspace_limits[1][0], workspace_limits[1][1], (workspace_limits[1][1] - workspace_limits[1][0])/calib_grid_step)\n    gridspace_z = np.linspace(workspace_limits[2][0], workspace_limits[2][1], (workspace_limits[2][1] - workspace_limits[2][0])/calib_grid_step)\n    calib_grid_x, calib_grid_y, calib_grid_z = np.meshgrid(gridspace_x, gridspace_y, gridspace_z)\n    num_calib_grid_pts = calib_grid_x.shape[0]*calib_grid_x.shape[1]*calib_grid_x.shape[2]\n    calib_grid_x.shape = (num_calib_grid_pts,1)\n    calib_grid_y.shape = (num_calib_grid_pts,1)\n    calib_grid_z.shape = (num_calib_grid_pts,1)\n    calib_grid_pts = np.concatenate((calib_grid_x, calib_grid_y, calib_grid_z), axis=1)\n    return num_calib_grid_pts, calib_grid_pts\n\n\ndef check_separation(values, distance_threshold):\n    \"\"\"Checks that the separation among the values is close enough about distance_threshold.\n\n    :param values: array of values to check, assumed to be sorted from low to high\n    :param distance_threshold: threshold\n    :returns: success\n    :rtype: bool\n\n    \"\"\"\n    for i in range(len(values) - 1):\n        x = values[i]\n        y = values[i + 1]\n        assert x < y, '`values` assumed to be sorted'\n        if y < x + distance_threshold / 2.:\n            # print('check_separation(): not long enough for idx: {}'.format(i))\n            return False\n        if y - x > distance_threshold:\n            # print('check_separation(): too far apart')\n            return False\n    return True\n\n\ndef polyfit(*args, **kwargs):\n    with warnings.catch_warnings():\n        # suppress the RankWarning, which just means the best fit line was bad.\n        warnings.simplefilter('ignore', np.RankWarning)\n        out = np.polyfit(*args, **kwargs)\n    return out\n\ndef is_jsonable(x):\n    try:\n        json.dumps(x)\n        return True\n    except (TypeError, OverflowError):\n        return False\n\n# killeen: this is defining the goal\nclass StackSequence(object):\n    def __init__(self, num_obj, is_goal_conditioned_task=True, trial=0, total_steps=1):\n        \"\"\" Oracle to choose a sequence of specific color objects to interact with.\n\n        Generates one hot encodings for a list of objects of the specified length.\n        Can be used for stacking or simply grasping specific objects.\n\n        # Member Variables\n\n        num_obj: the number of objects to manage. Each object is assumed to be in a list indexed from 0 to num_obj.\n        is_goal_conditioned_task: do we care about which specific object we are using\n        object_color_sequence: to get the full order of the current stack goal.\n\n        \"\"\"\n        self.num_obj = num_obj\n        self.is_goal_conditioned_task = is_goal_conditioned_task\n        self.trial = trial\n        self.reset_sequence()\n        self.total_steps = total_steps\n\n    def reset_sequence(self):\n        \"\"\" Generate a new sequence of specific objects to interact with.\n        \"\"\"\n        if self.is_goal_conditioned_task:\n            # 3 is currently the red block\n            # object_color_index = 3\n            self.object_color_index = 0\n\n            # Choose a random sequence to stack\n            self.object_color_sequence = np.random.permutation(self.num_obj)\n            # TODO(ahundt) This might eventually need to be the size of robot.stored_action_labels, but making it color-only for now.\n            self.object_color_one_hot_encodings = []\n            for color in self.object_color_sequence:\n                object_color_one_hot_encoding = np.zeros((self.num_obj))\n                object_color_one_hot_encoding[color] = 1.0\n                self.object_color_one_hot_encodings.append(object_color_one_hot_encoding)\n        else:\n            self.object_color_index = None\n            self.object_color_one_hot_encodings = None\n            self.object_color_sequence = None\n        self.trial += 1\n\n    def current_one_hot(self):\n        \"\"\" Return the one hot encoding for the current specific object.\n        \"\"\"\n        return self.object_color_one_hot_encodings[self.object_color_index]\n\n    def sequence_one_hot(self):\n        \"\"\" Return the one hot encoding for the entire stack sequence.\n        \"\"\"\n        return np.concatenate(self.object_color_one_hot_encodings)\n\n    def current_sequence_progress(self):\n        \"\"\" How much of the current stacking sequence we have completed.\n\n        For example, if the sequence should be [0, 1, 3, 2].\n        At initialization this will return [0].\n        After one next() calls it will return [0, 1].\n        After two next() calls it will return [0, 1, 3].\n        After three next() calls it will return [0, 1, 3, 2].\n        After four next() calls a new sequence will be generated and it will return one element again.\n        \"\"\"\n        if self.is_goal_conditioned_task:\n            return self.object_color_sequence[:self.object_color_index+1]\n        else:\n            return None\n\n    def next(self): \n        self.total_steps += 1\n        if self.is_goal_conditioned_task:\n            self.object_color_index += 1\n            if not self.object_color_index < self.num_obj:\n                self.reset_sequence()\n\n\ndef check_row_success(depth_heightmap, block_height_threshold=0.02, row_boundary_length=75, row_boundary_width=18, block_pixel_size=550, prev_z_height=None):\n    \"\"\" Return if the current arrangement of blocks in the heightmap is a valid row \n    \"\"\"\n    heightmap_trans = np.copy(depth_heightmap)\n    heightmap_trans = np.transpose(heightmap_trans)\n\n    heightmaps = (depth_heightmap, heightmap_trans)\n    counts = []\n\n    for heightmap in heightmaps:\n        # threshold pixels which contain a block\n        block_pixels = heightmap > block_height_threshold\n\n        # get positions of all those pixels  \n        coords = np.nonzero(block_pixels)\n        x = coords[1]\n        y = coords[0]\n        if x.size == 0 or y.size == 0:\n            return False, 0\n\n        # get best fit line y=mx+b\n        m, b = np.polyfit(x, y, 1)\n\n        # pick 2 random points on the line and find the unit vector\n        x1 = 0\n        y1 = int(m*x1 + b)\n        x2 = 224\n        y2 = int(m*x2 + b)\n\n        l = np.sqrt((x2-x1)**2 + (y2-y1)**2)\n        x_unit = (x2-x1)/l\n        y_unit = (y2-y1)/l\n\n        # centroid of block_pixels\n        centroid = (int(np.mean(x)), int(np.mean(y)))\n        \n        # get row_boundary_rectangle points\n        x1_r = int(centroid[0] - x_unit * row_boundary_length - y_unit * row_boundary_width)\n        y1_r = int(centroid[1] - y_unit * row_boundary_length + x_unit * row_boundary_width)\n        x2_r = int(centroid[0] + x_unit * row_boundary_length - y_unit * row_boundary_width)\n        y2_r = int(centroid[1] + y_unit * row_boundary_length + x_unit * row_boundary_width)\n        x3_r = int(centroid[0] + x_unit * row_boundary_length + y_unit * row_boundary_width)\n        y3_r = int(centroid[1] + y_unit * row_boundary_length - x_unit * row_boundary_width)\n        x4_r = int(centroid[0] - x_unit * row_boundary_length + y_unit * row_boundary_width)\n        y4_r = int(centroid[1] - y_unit * row_boundary_length - x_unit * row_boundary_width)\n\n        # create row_boundary_mask\n        mask = np.zeros((224,224))\n        pts = np.array([[x1_r,y1_r],[x2_r,y2_r],[x3_r,y3_r],[x4_r,y4_r]], np.int32)\n        pts = pts.reshape((-1,1,2))\n        cv2.fillPoly(mask, [pts], (255,255,255))\n        mask = mask > 0  # convert to bool\n\n        # get all block_pixels inside of row_boundary_rectangle and count them \n        block_pixels_in_row = np.logical_and(mask, block_pixels)\n        count = np.count_nonzero(block_pixels_in_row)\n\n        counts.append(count)\n\n    true_count = max(counts[0], counts[1])\n    row_size = true_count / block_pixel_size\n\n    if prev_z_height is not None:\n        success = row_size > prev_z_height\n    else:\n        success = True\n\n    print(\"ROW CHECK PIXEL COUNT: \", true_count, \", success: \", success, \", row size: \", row_size)\n\n    return success, row_size", "meta": {"hexsha": "4b4fab5121868341a4ce5e083184ab06280d7510", "size": 34786, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils.py", "max_stars_repo_name": "Psyche-mia/good_robot", "max_stars_repo_head_hexsha": "56b9f92c3152a860f774322306a2b77c73753adb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 69, "max_stars_repo_stars_event_min_datetime": "2019-09-30T13:42:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:37:51.000Z", "max_issues_repo_path": "utils.py", "max_issues_repo_name": "Psyche-mia/good_robot", "max_issues_repo_head_hexsha": "56b9f92c3152a860f774322306a2b77c73753adb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-10-23T20:03:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-10T09:43:50.000Z", "max_forks_repo_path": "utils.py", "max_forks_repo_name": "Psyche-mia/good_robot", "max_forks_repo_head_hexsha": "56b9f92c3152a860f774322306a2b77c73753adb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2019-11-17T20:57:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T10:46:25.000Z", "avg_line_length": 42.0628778718, "max_line_length": 305, "alphanum_fraction": 0.6470419134, "include": true, "reason": "import numpy,from scipy", "num_tokens": 9510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.32423539245106087, "lm_q1q2_score": 0.17475743608420796}}
{"text": "\"\"\"\nLosses for training neural networks.\n\nAuthors\n * Mirco Ravanelli 2020\n * Samuele Cornell 2020\n * Hwidong Na 2020\n * Yan Gao 2020\n * Titouan Parcollet 2020\n\"\"\"\n\nimport math\nimport torch\nimport logging\nimport functools\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom itertools import permutations\nfrom speechbrain.dataio.dataio import length_to_mask\nfrom speechbrain.decoders.ctc import filter_ctc_output\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef transducer_loss(\n    log_probs, targets, input_lens, target_lens, blank_index, reduction=\"mean\"\n):\n    \"\"\"Transducer loss, see `speechbrain/nnet/loss/transducer_loss.py`.\n\n    Arguments\n    ---------\n    predictions : torch.Tensor\n        Predicted tensor, of shape [batch, maxT, maxU, num_labels].\n    targets : torch.Tensor\n        Target tensor, without any blanks, of shape [batch, target_len].\n    input_lens : torch.Tensor\n        Length of each utterance.\n    target_lens : torch.Tensor\n        Length of each target sequence.\n    blank_index : int\n        The location of the blank symbol among the label indices.\n    reduction : str\n        Specifies the reduction to apply to the output: 'mean' | 'batchmean' | 'sum'.\n    \"\"\"\n    from speechbrain.nnet.loss.transducer_loss import Transducer\n\n    input_lens = (input_lens * log_probs.shape[1]).int()\n    target_lens = (target_lens * targets.shape[1]).int()\n    return Transducer.apply(\n        log_probs, targets, input_lens, target_lens, blank_index, reduction\n    )\n\n\nclass PitWrapper(nn.Module):\n    \"\"\"\n    Permutation Invariant Wrapper to allow Permutation Invariant Training\n    (PIT) with existing losses.\n\n    Permutation invariance is calculated over the sources/classes axis which is\n    assumed to be the rightmost dimension: predictions and targets tensors are\n    assumed to have shape [batch, ..., channels, sources].\n\n    Arguments\n    ---------\n    base_loss : function\n        Base loss function, e.g. torch.nn.MSELoss. It is assumed that it takes\n        two arguments:\n        predictions and targets and no reduction is performed.\n        (if a pytorch loss is used, the user must specify reduction=\"none\").\n\n    Returns\n    ---------\n    pit_loss : torch.nn.Module\n        Torch module supporting forward method for PIT.\n\n    Example\n    -------\n    >>> pit_mse = PitWrapper(nn.MSELoss(reduction=\"none\"))\n    >>> targets = torch.rand((2, 32, 4))\n    >>> p = (3, 0, 2, 1)\n    >>> predictions = targets[..., p]\n    >>> loss, opt_p = pit_mse(predictions, targets)\n    >>> loss\n    tensor([0., 0.])\n    \"\"\"\n\n    def __init__(self, base_loss):\n        super(PitWrapper, self).__init__()\n        self.base_loss = base_loss\n\n    def _fast_pit(self, loss_mat):\n        \"\"\"\n        Arguments\n        ----------\n        loss_mat : torch.Tensor\n            Tensor of shape [sources, source] containing loss values for each\n            possible permutation of predictions.\n\n        Returns\n        -------\n        loss : torch.Tensor\n            Permutation invariant loss for the current batch, tensor of shape [1]\n\n        assigned_perm : tuple\n            Indexes for optimal permutation of the input over sources which\n            minimizes the loss.\n        \"\"\"\n\n        loss = None\n        assigned_perm = None\n        for p in permutations(range(loss_mat.shape[0])):\n            c_loss = loss_mat[range(loss_mat.shape[0]), p].mean()\n            if loss is None or loss > c_loss:\n                loss = c_loss\n                assigned_perm = p\n        return loss, assigned_perm\n\n    def _opt_perm_loss(self, pred, target):\n        \"\"\"\n        Arguments\n        ---------\n        pred : torch.Tensor\n            Network prediction for the current example, tensor of\n            shape [..., sources].\n        target : torch.Tensor\n            Target for the current example, tensor of shape [..., sources].\n\n        Returns\n        -------\n        loss : torch.Tensor\n            Permutation invariant loss forthe  current example, tensor of shape [1]\n\n        assigned_perm : tuple\n            Indexes for optimal permutation of the input over sources which\n            minimizes the loss.\n\n        \"\"\"\n\n        n_sources = pred.size(-1)\n\n        pred = pred.unsqueeze(-2).repeat(\n            *[1 for x in range(len(pred.shape) - 1)], n_sources, 1\n        )\n        target = target.unsqueeze(-1).repeat(\n            1, *[1 for x in range(len(target.shape) - 1)], n_sources\n        )\n\n        loss_mat = self.base_loss(pred, target)\n        assert (\n            len(loss_mat.shape) >= 2\n        ), \"Base loss should not perform any reduction operation\"\n        mean_over = [x for x in range(len(loss_mat.shape))]\n        loss_mat = loss_mat.mean(dim=mean_over[:-2])\n\n        return self._fast_pit(loss_mat)\n\n    def reorder_tensor(self, tensor, p):\n        \"\"\"\n        Arguments\n        ---------\n        tensor : torch.Tensor\n            Tensor to reorder given the optimal permutation, of shape\n            [batch, ..., sources].\n        p : list of tuples\n            List of optimal permutations, e.g. for batch=2 and n_sources=3\n            [(0, 1, 2), (0, 2, 1].\n\n        Returns\n        -------\n        reordered : torch.Tensor\n            Reordered tensor given permutation p.\n        \"\"\"\n\n        reordered = torch.zeros_like(tensor, device=tensor.device)\n        for b in range(tensor.shape[0]):\n            reordered[b] = tensor[b][..., p[b]].clone()\n        return reordered\n\n    def forward(self, preds, targets):\n        \"\"\"\n            Arguments\n            ---------\n            preds : torch.Tensor\n                Network predictions tensor, of shape\n                [batch, channels, ..., sources].\n            targets : torch.Tensor\n                Target tensor, of shape [batch, channels, ..., sources].\n\n            Returns\n            -------\n            loss : torch.Tensor\n                Permutation invariant loss for current examples, tensor of\n                shape [batch]\n\n            perms : list\n                List of indexes for optimal permutation of the inputs over\n                sources.\n                e.g., [(0, 1, 2), (2, 1, 0)] for three sources and 2 examples\n                per batch.\n        \"\"\"\n        losses = []\n        perms = []\n        for pred, label in zip(preds, targets):\n            loss, p = self._opt_perm_loss(pred, label)\n            perms.append(p)\n            losses.append(loss)\n        loss = torch.stack(losses)\n        return loss, perms\n\n\ndef ctc_loss(\n    log_probs, targets, input_lens, target_lens, blank_index, reduction=\"mean\"\n):\n    \"\"\"CTC loss.\n\n    Arguments\n    ---------\n    predictions : torch.Tensor\n        Predicted tensor, of shape [batch, time, chars].\n    targets : torch.Tensor\n        Target tensor, without any blanks, of shape [batch, target_len]\n    input_lens : torch.Tensor\n        Length of each utterance.\n    target_lens : torch.Tensor\n        Length of each target sequence.\n    blank_index : int\n        The location of the blank symbol among the character indexes.\n    reduction : str\n        What reduction to apply to the output. 'mean', 'sum', 'batch',\n        'batchmean', 'none'.\n        See pytorch for 'mean', 'sum', 'none'. The 'batch' option returns\n        one loss per item in the batch, 'batchmean' returns sum / batch size.\n    \"\"\"\n    input_lens = (input_lens * log_probs.shape[1]).int()\n    target_lens = (target_lens * targets.shape[1]).int()\n    log_probs = log_probs.transpose(0, 1)\n\n    if reduction == \"batchmean\":\n        reduction_loss = \"sum\"\n    elif reduction == \"batch\":\n        reduction_loss = \"none\"\n    else:\n        reduction_loss = reduction\n    loss = torch.nn.functional.ctc_loss(\n        log_probs,\n        targets,\n        input_lens,\n        target_lens,\n        blank_index,\n        zero_infinity=True,\n        reduction=reduction_loss,\n    )\n\n    if reduction == \"batchmean\":\n        return loss / targets.shape[0]\n    elif reduction == \"batch\":\n        N = loss.size(0)\n        return loss.view(N, -1).sum(1) / target_lens.view(N, -1).sum(1)\n    else:\n        return loss\n\n\ndef l1_loss(\n    predictions, targets, length=None, allowed_len_diff=3, reduction=\"mean\"\n):\n    \"\"\"Compute the true l1 loss, accounting for length differences.\n\n    Arguments\n    ---------\n    predictions : torch.Tensor\n        Predicted tensor, of shape ``[batch, time, *]``.\n    targets : torch.Tensor\n        Target tensor with the same size as predicted tensor.\n    length : torch.Tensor\n        Length of each utterance for computing true error with a mask.\n    allowed_len_diff : int\n        Length difference that will be tolerated before raising an exception.\n    reduction : str\n        Options are 'mean', 'batch', 'batchmean', 'sum'.\n        See pytorch for 'mean', 'sum'. The 'batch' option returns\n        one loss per item in the batch, 'batchmean' returns sum / batch size.\n\n    Example\n    -------\n    >>> probs = torch.tensor([[0.9, 0.1, 0.1, 0.9]])\n    >>> l1_loss(probs, torch.tensor([[1., 0., 0., 1.]]))\n    tensor(0.1000)\n    \"\"\"\n    predictions, targets = truncate(predictions, targets, allowed_len_diff)\n    loss = functools.partial(torch.nn.functional.l1_loss, reduction=\"none\")\n    return compute_masked_loss(\n        loss, predictions, targets, length, reduction=reduction\n    )\n\n\ndef mse_loss(\n    predictions, targets, length=None, allowed_len_diff=3, reduction=\"mean\"\n):\n    \"\"\"Compute the true mean squared error, accounting for length differences.\n\n    Arguments\n    ---------\n    predictions : torch.Tensor\n        Predicted tensor, of shape ``[batch, time, *]``.\n    targets : torch.Tensor\n        Target tensor with the same size as predicted tensor.\n    length : torch.Tensor\n        Length of each utterance for computing true error with a mask.\n    allowed_len_diff : int\n        Length difference that will be tolerated before raising an exception.\n    reduction : str\n        Options are 'mean', 'batch', 'batchmean', 'sum'.\n        See pytorch for 'mean', 'sum'. The 'batch' option returns\n        one loss per item in the batch, 'batchmean' returns sum / batch size.\n\n    Example\n    -------\n    >>> probs = torch.tensor([[0.9, 0.1, 0.1, 0.9]])\n    >>> mse_loss(probs, torch.tensor([[1., 0., 0., 1.]]))\n    tensor(0.0100)\n    \"\"\"\n    predictions, targets = truncate(predictions, targets, allowed_len_diff)\n    loss = functools.partial(torch.nn.functional.mse_loss, reduction=\"none\")\n    return compute_masked_loss(\n        loss, predictions, targets, length, reduction=reduction\n    )\n\n\ndef classification_error(\n    probabilities, targets, length=None, allowed_len_diff=3, reduction=\"mean\"\n):\n    \"\"\"Computes the classification error at frame or batch level.\n\n    Arguments\n    ---------\n    probabilities : torch.Tensor\n        The posterior probabilities of shape\n        [batch, prob] or [batch, frames, prob]\n    targets : torch.Tensor\n        The targets, of shape [batch] or [batch, frames]\n    length : torch.Tensor\n        Length of each utterance, if frame-level loss is desired.\n    allowed_len_diff : int\n        Length difference that will be tolerated before raising an exception.\n    reduction : str\n        Options are 'mean', 'batch', 'batchmean', 'sum'.\n        See pytorch for 'mean', 'sum'. The 'batch' option returns\n        one loss per item in the batch, 'batchmean' returns sum / batch size.\n\n    Example\n    -------\n    >>> probs = torch.tensor([[[0.9, 0.1], [0.1, 0.9]]])\n    >>> classification_error(probs, torch.tensor([1, 1]))\n    tensor(0.5000)\n    \"\"\"\n    if len(probabilities.shape) == 3 and len(targets.shape) == 2:\n        probabilities, targets = truncate(\n            probabilities, targets, allowed_len_diff\n        )\n\n    def error(predictions, targets):\n        predictions = torch.argmax(probabilities, dim=-1)\n        return (predictions != targets).float()\n\n    return compute_masked_loss(\n        error, probabilities, targets.long(), length, reduction=reduction\n    )\n\n\ndef nll_loss(\n    log_probabilities,\n    targets,\n    length=None,\n    label_smoothing=0.0,\n    allowed_len_diff=3,\n    reduction=\"mean\",\n):\n    \"\"\"Computes negative log likelihood loss.\n\n    Arguments\n    ---------\n    log_probabilities : torch.Tensor\n        The probabilities after log has been applied.\n        Format is [batch, log_p] or [batch, frames, log_p].\n    targets : torch.Tensor\n        The targets, of shape [batch] or [batch, frames].\n    length : torch.Tensor\n        Length of each utterance, if frame-level loss is desired.\n    allowed_len_diff : int\n        Length difference that will be tolerated before raising an exception.\n    reduction : str\n        Options are 'mean', 'batch', 'batchmean', 'sum'.\n        See pytorch for 'mean', 'sum'. The 'batch' option returns\n        one loss per item in the batch, 'batchmean' returns sum / batch size.\n\n    Example\n    -------\n    >>> probs = torch.tensor([[0.9, 0.1], [0.1, 0.9]])\n    >>> nll_loss(torch.log(probs), torch.tensor([1, 1]))\n    tensor(1.2040)\n    \"\"\"\n    if len(log_probabilities.shape) == 3:\n        log_probabilities, targets = truncate(\n            log_probabilities, targets, allowed_len_diff\n        )\n        log_probabilities = log_probabilities.transpose(1, -1)\n\n    # Pass the loss function but apply reduction=\"none\" first\n    loss = functools.partial(torch.nn.functional.nll_loss, reduction=\"none\")\n    return compute_masked_loss(\n        loss,\n        log_probabilities,\n        targets.long(),\n        length,\n        label_smoothing=label_smoothing,\n        reduction=reduction,\n    )\n\n\ndef bce_loss(\n    inputs,\n    targets,\n    length=None,\n    weight=None,\n    pos_weight=None,\n    reduction=\"mean\",\n    allowed_len_diff=3,\n    label_smoothing=0.0,\n):\n    \"\"\"Computes binary cross-entropy (BCE) loss. It also applies the sigmoid\n    function directly (this improves the numerical stability).\n\n    Arguments\n    ---------\n    inputs : torch.Tensor\n        The output before applying the final softmax\n        Format is [batch[, 1]?] or [batch, frames[, 1]?].\n        (Works with or without a singleton dimension at the end).\n    targets : torch.Tensor\n        The targets, of shape [batch] or [batch, frames].\n    length : torch.Tensor\n        Length of each utterance, if frame-level loss is desired.\n    weight : torch.Tensor\n        A manual rescaling weight if provided it’s repeated to match input\n        tensor shape.\n    pos_weight : torch.Tensor\n        A weight of positive examples. Must be a vector with length equal to\n        the number of classes.\n    allowed_len_diff : int\n        Length difference that will be tolerated before raising an exception.\n    reduction: str\n        Options are 'mean', 'batch', 'batchmean', 'sum'.\n        See pytorch for 'mean', 'sum'. The 'batch' option returns\n        one loss per item in the batch, 'batchmean' returns sum / batch size.\n\n    Example\n    -------\n    >>> inputs = torch.tensor([10.0, -6.0])\n    >>> targets = torch.tensor([1, 0])\n    >>> bce_loss(inputs, targets)\n    tensor(0.0013)\n    \"\"\"\n    # Squeeze singleton dimension so inputs + targets match\n    if len(inputs.shape) == len(targets.shape) + 1:\n        inputs = inputs.squeeze(-1)\n\n    # Make sure tensor lengths match\n    if len(inputs.shape) >= 2:\n        inputs, targets = truncate(inputs, targets, allowed_len_diff)\n    elif length is not None:\n        raise ValueError(\"length can be passed only for >= 2D inputs.\")\n\n    # Pass the loss function but apply reduction=\"none\" first\n    loss = functools.partial(\n        torch.nn.functional.binary_cross_entropy_with_logits,\n        weight=weight,\n        pos_weight=pos_weight,\n        reduction=\"none\",\n    )\n    return compute_masked_loss(\n        loss,\n        inputs,\n        targets.float(),\n        length,\n        label_smoothing=label_smoothing,\n        reduction=reduction,\n    )\n\n\ndef kldiv_loss(\n    log_probabilities,\n    targets,\n    length=None,\n    label_smoothing=0.0,\n    allowed_len_diff=3,\n    pad_idx=0,\n    reduction=\"mean\",\n):\n    \"\"\"Computes the KL-divergence error at the batch level.\n    This loss applies label smoothing directly to the targets\n\n    Arguments\n    ---------\n    probabilities : torch.Tensor\n        The posterior probabilities of shape\n        [batch, prob] or [batch, frames, prob].\n    targets : torch.Tensor\n        The targets, of shape [batch] or [batch, frames].\n    length : torch.Tensor\n        Length of each utterance, if frame-level loss is desired.\n    allowed_len_diff : int\n        Length difference that will be tolerated before raising an exception.\n    reduction : str\n        Options are 'mean', 'batch', 'batchmean', 'sum'.\n        See pytorch for 'mean', 'sum'. The 'batch' option returns\n        one loss per item in the batch, 'batchmean' returns sum / batch size.\n\n    Example\n    -------\n    >>> probs = torch.tensor([[0.9, 0.1], [0.1, 0.9]])\n    >>> kldiv_loss(torch.log(probs), torch.tensor([1, 1]))\n    tensor(1.2040)\n    \"\"\"\n    if label_smoothing > 0:\n        if log_probabilities.dim() == 2:\n            log_probabilities = log_probabilities.unsqueeze(1)\n\n        bz, time, n_class = log_probabilities.shape\n        targets = targets.long().detach()\n\n        confidence = 1 - label_smoothing\n\n        log_probabilities = log_probabilities.view(-1, n_class)\n        targets = targets.view(-1)\n        with torch.no_grad():\n            true_distribution = log_probabilities.clone()\n            true_distribution.fill_(label_smoothing / (n_class - 1))\n            ignore = targets == pad_idx\n            targets = targets.masked_fill(ignore, 0)\n            true_distribution.scatter_(1, targets.unsqueeze(1), confidence)\n\n        loss = torch.nn.functional.kl_div(\n            log_probabilities, true_distribution, reduction=\"none\"\n        )\n        loss = loss.masked_fill(ignore.unsqueeze(1), 0)\n\n        # return loss according to reduction specified\n        if reduction == \"mean\":\n            return loss.sum().mean()\n        elif reduction == \"batchmean\":\n            return loss.sum() / bz\n        elif reduction == \"batch\":\n            return loss.view(bz, -1).sum(1) / length\n        elif reduction == \"sum\":\n            return loss.sum()\n        else:\n            return loss\n    else:\n        return nll_loss(log_probabilities, targets, length, reduction=reduction)\n\n\ndef truncate(predictions, targets, allowed_len_diff=3):\n    \"\"\"Ensure that predictions and targets are the same length.\n\n    Arguments\n    ---------\n    predictions : torch.Tensor\n        First tensor for checking length.\n    targets : torch.Tensor\n        Second tensor for checking length.\n    allowed_len_diff : int\n        Length difference that will be tolerated before raising an exception.\n    \"\"\"\n    len_diff = predictions.shape[1] - targets.shape[1]\n    if len_diff == 0:\n        return predictions, targets\n    elif abs(len_diff) > allowed_len_diff:\n        raise ValueError(\n            \"Predictions and targets should be same length, but got %s and \"\n            \"%s respectively.\" % (predictions.shape[1], targets.shape[1])\n        )\n    elif len_diff < 0:\n        return predictions, targets[:, : predictions.shape[1]]\n    else:\n        return predictions[:, : targets.shape[1]], targets\n\n\ndef compute_masked_loss(\n    loss_fn,\n    predictions,\n    targets,\n    length=None,\n    label_smoothing=0.0,\n    reduction=\"mean\",\n):\n    \"\"\"Compute the true average loss of a set of waveforms of unequal length.\n\n    Arguments\n    ---------\n    loss_fn : function\n        A function for computing the loss taking just predictions and targets.\n        Should return all the losses, not a reduction (e.g. reduction=\"none\").\n    predictions : torch.Tensor\n        First argument to loss function.\n    targets : torch.Tensor\n        Second argument to loss function.\n    length : torch.Tensor\n        Length of each utterance to compute mask. If None, global average is\n        computed and returned.\n    label_smoothing: float\n        The proportion of label smoothing. Should only be used for NLL loss.\n        Ref: Regularizing Neural Networks by Penalizing Confident Output\n        Distributions. https://arxiv.org/abs/1701.06548\n    reduction : str\n        One of 'mean', 'batch', 'batchmean', 'none' where 'mean' returns a\n        single value and 'batch' returns one per item in the batch and\n        'batchmean' is sum / batch_size and 'none' returns all.\n    \"\"\"\n    mask = torch.ones_like(targets)\n    if length is not None:\n        length_mask = length_to_mask(\n            length * targets.shape[1], max_len=targets.shape[1],\n        )\n\n        # Handle any dimensionality of input\n        while len(length_mask.shape) < len(mask.shape):\n            length_mask = length_mask.unsqueeze(-1)\n        length_mask = length_mask.type(mask.dtype)\n        mask *= length_mask\n\n    # Compute, then reduce loss\n    loss = loss_fn(predictions, targets) * mask\n    N = loss.size(0)\n    if reduction == \"mean\":\n        loss = loss.sum() / torch.sum(mask)\n    elif reduction == \"batchmean\":\n        loss = loss.sum() / N\n    elif reduction == \"batch\":\n        loss = loss.reshape(N, -1).sum(1) / mask.reshape(N, -1).sum(1)\n\n    if label_smoothing == 0:\n        return loss\n    else:\n        loss_reg = torch.mean(predictions, dim=1) * mask\n        if reduction == \"mean\":\n            loss_reg = torch.sum(loss_reg) / torch.sum(mask)\n        elif reduction == \"batchmean\":\n            loss_reg = torch.sum(loss_reg) / targets.shape[0]\n        elif reduction == \"batch\":\n            loss_reg = loss_reg.sum(1) / mask.sum(1)\n\n        return -label_smoothing * loss_reg + (1 - label_smoothing) * loss\n\n\ndef get_si_snr_with_pitwrapper(source, estimate_source):\n    \"\"\"This function wraps si_snr calculation with the speechbrain pit-wrapper.\n\n    Arguments:\n    ---------\n    source: [B, T, C],\n        Where B is the batch size, T is the length of the sources, C is\n        the number of sources the ordering is made so that this loss is\n        compatible with the class PitWrapper.\n\n    estimate_source: [B, T, C]\n        The estimated source.\n\n    Example:\n    ---------\n    >>> x = torch.arange(600).reshape(3, 100, 2)\n    >>> xhat = x[:, :, (1, 0)]\n    >>> si_snr = -get_si_snr_with_pitwrapper(x, xhat)\n    >>> print(si_snr)\n    tensor([135.2284, 135.2284, 135.2284])\n    \"\"\"\n\n    pit_si_snr = PitWrapper(cal_si_snr)\n    loss, perms = pit_si_snr(source, estimate_source)\n\n    return loss\n\n\ndef cal_si_snr(source, estimate_source):\n    \"\"\"Calculate SI-SNR.\n\n    Arguments:\n    ---------\n    source: [T, B, C],\n        Where B is batch size, T is the length of the sources, C is the number of sources\n        the ordering is made so that this loss is compatible with the class PitWrapper.\n\n    estimate_source: [T, B, C]\n        The estimated source.\n\n    Example:\n    ---------\n    >>> import numpy as np\n    >>> x = torch.Tensor([[1, 0], [123, 45], [34, 5], [2312, 421]])\n    >>> xhat = x[:, (1, 0)]\n    >>> x = x.unsqueeze(-1).repeat(1, 1, 2)\n    >>> xhat = xhat.unsqueeze(1).repeat(1, 2, 1)\n    >>> si_snr = -cal_si_snr(x, xhat)\n    >>> print(si_snr)\n    tensor([[[ 25.2142, 144.1789],\n             [130.9283,  25.2142]]])\n    \"\"\"\n    EPS = 1e-8\n    assert source.size() == estimate_source.size()\n    device = estimate_source.device.type\n\n    source_lengths = torch.tensor(\n        [estimate_source.shape[0]] * estimate_source.shape[1], device=device\n    )\n    mask = get_mask(source, source_lengths)\n    estimate_source *= mask\n\n    num_samples = (\n        source_lengths.contiguous().reshape(1, -1, 1).float()\n    )  # [1, B, 1]\n    mean_target = torch.sum(source, dim=0, keepdim=True) / num_samples\n    mean_estimate = (\n        torch.sum(estimate_source, dim=0, keepdim=True) / num_samples\n    )\n    zero_mean_target = source - mean_target\n    zero_mean_estimate = estimate_source - mean_estimate\n    # mask padding position along T\n    zero_mean_target *= mask\n    zero_mean_estimate *= mask\n\n    # Step 2. SI-SNR with PIT\n    # reshape to use broadcast\n    s_target = zero_mean_target  # [T, B, C]\n    s_estimate = zero_mean_estimate  # [T, B, C]\n    # s_target = <s', s>s / ||s||^2\n    dot = torch.sum(s_estimate * s_target, dim=0, keepdim=True)  # [1, B, C]\n    s_target_energy = (\n        torch.sum(s_target ** 2, dim=0, keepdim=True) + EPS\n    )  # [1, B, C]\n    proj = dot * s_target / s_target_energy  # [T, B, C]\n    # e_noise = s' - s_target\n    e_noise = s_estimate - proj  # [T, B, C]\n    # SI-SNR = 10 * log_10(||s_target||^2 / ||e_noise||^2)\n    si_snr_beforelog = torch.sum(proj ** 2, dim=0) / (\n        torch.sum(e_noise ** 2, dim=0) + EPS\n    )\n    si_snr = 10 * torch.log10(si_snr_beforelog + EPS)  # [B, C]\n\n    return -si_snr.unsqueeze(0)\n\n\ndef get_mask(source, source_lengths):\n    \"\"\"\n    Arguments\n    ---------\n    source : [T, B, C]\n    source_lengths : [B]\n\n    Returns\n    -------\n    mask : [T, B, 1]\n\n    Example:\n    ---------\n    >>> source = torch.randn(4, 3, 2)\n    >>> source_lengths = torch.Tensor([2, 1, 4]).int()\n    >>> mask = get_mask(source, source_lengths)\n    >>> print(mask)\n    tensor([[[1.],\n             [1.],\n             [1.]],\n    <BLANKLINE>\n            [[1.],\n             [0.],\n             [1.]],\n    <BLANKLINE>\n            [[0.],\n             [0.],\n             [1.]],\n    <BLANKLINE>\n            [[0.],\n             [0.],\n             [1.]]])\n    \"\"\"\n    T, B, _ = source.size()\n    mask = source.new_ones((T, B, 1))\n    for i in range(B):\n        mask[source_lengths[i] :, i, :] = 0\n    return mask\n\n\nclass AngularMargin(nn.Module):\n    \"\"\"\n    An implementation of Angular Margin (AM) proposed in the following\n    paper: '''Margin Matters: Towards More Discriminative Deep Neural Network\n    Embeddings for Speaker Recognition''' (https://arxiv.org/abs/1906.07317)\n\n    Arguments\n    ---------\n    margin : float\n        The margin for cosine similiarity\n    scale : float\n        The scale for cosine similiarity\n\n    Return\n    ---------\n    predictions : torch.Tensor\n\n    Example\n    -------\n    >>> pred = AngularMargin()\n    >>> outputs = torch.tensor([ [1., -1.], [-1., 1.], [0.9, 0.1], [0.1, 0.9] ])\n    >>> targets = torch.tensor([ [1., 0.], [0., 1.], [ 1., 0.], [0.,  1.] ])\n    >>> predictions = pred(outputs, targets)\n    >>> predictions[:,0] > predictions[:,1]\n    tensor([ True, False,  True, False])\n    \"\"\"\n\n    def __init__(self, margin=0.0, scale=1.0):\n        super(AngularMargin, self).__init__()\n        self.margin = margin\n        self.scale = scale\n\n    def forward(self, outputs, targets):\n        \"\"\"Compute AM between two tensors\n\n        Arguments\n        ---------\n        outputs : torch.Tensor\n            The outputs of shape [N, C], cosine simiarity is required.\n        targets : torch.Tensor\n            The targets of shape [N, C], where the margin is applied for.\n\n        Return\n        ---------\n        predictions : torch.Tensor\n        \"\"\"\n        outputs = outputs - self.margin * targets\n        return self.scale * outputs\n\n\nclass AdditiveAngularMargin(AngularMargin):\n    \"\"\"\n    An implementation of Additive Angular Margin (AAM) proposed\n    in the following paper: '''Margin Matters: Towards More Discriminative Deep\n    Neural Network Embeddings for Speaker Recognition'''\n    (https://arxiv.org/abs/1906.07317)\n\n    Arguments\n    ---------\n    margin : float\n        The margin for cosine similiarity.\n    scale: float\n        The scale for cosine similiarity.\n\n    Returns\n    -------\n    predictions : torch.Tensor\n        Tensor.\n    Example\n    -------\n    >>> outputs = torch.tensor([ [1., -1.], [-1., 1.], [0.9, 0.1], [0.1, 0.9] ])\n    >>> targets = torch.tensor([ [1., 0.], [0., 1.], [ 1., 0.], [0.,  1.] ])\n    >>> pred = AdditiveAngularMargin()\n    >>> predictions = pred(outputs, targets)\n    >>> predictions[:,0] > predictions[:,1]\n    tensor([ True, False,  True, False])\n    \"\"\"\n\n    def __init__(self, margin=0.0, scale=1.0, easy_margin=False):\n        super(AdditiveAngularMargin, self).__init__(margin, scale)\n        self.easy_margin = easy_margin\n\n        self.cos_m = math.cos(self.margin)\n        self.sin_m = math.sin(self.margin)\n        self.th = math.cos(math.pi - self.margin)\n        self.mm = math.sin(math.pi - self.margin) * self.margin\n\n    def forward(self, outputs, targets):\n        \"\"\"\n        Compute AAM between two tensors\n\n        Arguments\n        ---------\n        outputs : torch.Tensor\n            The outputs of shape [N, C], cosine simiarity is required.\n        targets : torch.Tensor\n            The targets of shape [N, C], where the margin is applied for.\n\n        Return\n        ---------\n        predictions : torch.Tensor\n        \"\"\"\n        cosine = outputs.float()\n        sine = torch.sqrt(1.0 - torch.pow(cosine, 2))\n        phi = cosine * self.cos_m - sine * self.sin_m  # cos(theta + m)\n        if self.easy_margin:\n            phi = torch.where(cosine > 0, phi, cosine)\n        else:\n            phi = torch.where(cosine > self.th, phi, cosine - self.mm)\n        outputs = (targets * phi) + ((1.0 - targets) * cosine)\n        return self.scale * outputs\n\n\nclass LogSoftmaxWrapper(nn.Module):\n    \"\"\"\n    Arguments\n    ---------\n    Returns\n    ---------\n    loss : torch.Tensor\n        Learning loss\n    predictions : torch.Tensor\n        Log probabilities\n    Example\n    -------\n    >>> outputs = torch.tensor([ [1., -1.], [-1., 1.], [0.9, 0.1], [0.1, 0.9] ])\n    >>> outputs = outputs.unsqueeze(1)\n    >>> targets = torch.tensor([ [0], [1], [0], [1] ])\n    >>> log_prob = LogSoftmaxWrapper(nn.Identity())\n    >>> loss = log_prob(outputs, targets)\n    >>> 0 <= loss < 1\n    tensor(True)\n    >>> log_prob = LogSoftmaxWrapper(AngularMargin(margin=0.2, scale=32))\n    >>> loss = log_prob(outputs, targets)\n    >>> 0 <= loss < 1\n    tensor(True)\n    >>> outputs = torch.tensor([ [1., -1.], [-1., 1.], [0.9, 0.1], [0.1, 0.9] ])\n    >>> log_prob = LogSoftmaxWrapper(AdditiveAngularMargin(margin=0.3, scale=32))\n    >>> loss = log_prob(outputs, targets)\n    >>> 0 <= loss < 1\n    tensor(True)\n    \"\"\"\n\n    def __init__(self, loss_fn):\n        super(LogSoftmaxWrapper, self).__init__()\n        self.loss_fn = loss_fn\n        self.criterion = torch.nn.KLDivLoss(reduction=\"sum\")\n\n    def forward(self, outputs, targets, length=None):\n        \"\"\"\n        Arguments\n        ---------\n        outputs : torch.Tensor\n            Network output tensor, of shape\n            [batch, 1, outdim].\n        targets : torch.Tensor\n            Target tensor, of shape [batch, 1].\n\n        Returns\n        -------\n        loss: torch.Tensor\n            Loss for current examples.\n        \"\"\"\n        outputs = outputs.squeeze(1)\n        targets = targets.squeeze(1)\n        targets = F.one_hot(targets.long(), outputs.shape[1]).float()\n        try:\n            predictions = self.loss_fn(outputs, targets)\n        except TypeError:\n            predictions = self.loss_fn(outputs)\n\n        predictions = F.log_softmax(predictions, dim=1)\n        loss = self.criterion(predictions, targets) / targets.sum()\n        return loss\n\n\ndef ctc_loss_kd(log_probs, targets, input_lens, blank_index, device):\n    \"\"\"Knowledge distillation for CTC loss.\n\n    Reference\n    ---------\n    Distilling Knowledge from Ensembles of Acoustic Models for Joint CTC-Attention End-to-End Speech Recognition.\n    https://arxiv.org/abs/2005.09310\n\n    Arguments\n    ---------\n    log_probs : torch.Tensor\n        Predicted tensor from student model, of shape [batch, time, chars].\n    targets : torch.Tensor\n        Predicted tensor from single teacher model, of shape [batch, time, chars].\n    input_lens : torch.Tensor\n        Length of each utterance.\n    blank_index : int\n        The location of the blank symbol among the character indexes.\n    device : str\n        Device for computing.\n    \"\"\"\n    scores, predictions = torch.max(targets, dim=-1)\n\n    pred_list = []\n    pred_len_list = []\n    for j in range(predictions.shape[0]):\n        # Getting current predictions\n        current_pred = predictions[j]\n\n        actual_size = (input_lens[j] * log_probs.shape[1]).int()\n        current_pred = current_pred[0:actual_size]\n        current_pred = filter_ctc_output(\n            list(current_pred.cpu().numpy()), blank_id=blank_index\n        )\n        current_pred_len = len(current_pred)\n        pred_list.append(current_pred)\n        pred_len_list.append(current_pred_len)\n\n    max_pred_len = max(pred_len_list)\n    for j in range(predictions.shape[0]):\n        diff = max_pred_len - pred_len_list[j]\n        for n in range(diff):\n            pred_list[j].append(0)\n\n    # generate soft label of teacher model\n    fake_lab = torch.from_numpy(np.array(pred_list))\n    fake_lab.to(device)\n    fake_lab = fake_lab.int()\n    fake_lab_lengths = torch.from_numpy(np.array(pred_len_list)).int()\n    fake_lab_lengths.to(device)\n\n    input_lens = (input_lens * log_probs.shape[1]).int()\n    log_probs = log_probs.transpose(0, 1)\n    return torch.nn.functional.ctc_loss(\n        log_probs,\n        fake_lab,\n        input_lens,\n        fake_lab_lengths,\n        blank_index,\n        zero_infinity=True,\n    )\n\n\ndef ce_kd(inp, target):\n    \"\"\"Simple version of distillation for cross-entropy loss.\n\n    Arguments\n    ---------\n    inp : torch.Tensor\n        The probabilities from student model, of shape [batch_size * length, feature]\n    target : torch.Tensor\n        The probabilities from teacher model, of shape [batch_size * length, feature]\n    \"\"\"\n    return (-target * inp).sum(1)\n\n\ndef nll_loss_kd(\n    probabilities, targets, rel_lab_lengths,\n):\n    \"\"\"Knowledge distillation for negative log-likelihood loss.\n\n    Reference\n    ---------\n    Distilling Knowledge from Ensembles of Acoustic Models for Joint CTC-Attention End-to-End Speech Recognition.\n    https://arxiv.org/abs/2005.09310\n\n    Arguments\n    ---------\n    probabilities : torch.Tensor\n        The predicted probabilities from the student model.\n        Format is [batch, frames, p]\n    targets : torch.Tensor\n        The target probabilities from the teacher model.\n        Format is [batch, frames, p]\n    rel_lab_lengths : torch.Tensor\n        Length of each utterance, if the frame-level loss is desired.\n\n    Example\n    -------\n    >>> probabilities = torch.tensor([[[0.8, 0.2], [0.2, 0.8]]])\n    >>> targets = torch.tensor([[[0.9, 0.1], [0.1, 0.9]]])\n    >>> rel_lab_lengths = torch.tensor([1.])\n    >>> nll_loss_kd(probabilities, targets, rel_lab_lengths)\n    tensor(-0.7400)\n    \"\"\"\n    # Getting the number of sentences in the minibatch\n    N_snt = probabilities.shape[0]\n\n    # Getting the maximum length of label sequence\n    max_len = probabilities.shape[1]\n\n    # Getting the label lengths\n    lab_lengths = torch.round(rel_lab_lengths * targets.shape[1]).int()\n\n    # Reshape to [batch_size * length, feature]\n    prob_curr = probabilities.reshape(N_snt * max_len, probabilities.shape[-1])\n\n    # Generating mask\n    mask = length_to_mask(\n        lab_lengths, max_len=max_len, dtype=torch.float, device=prob_curr.device\n    )\n\n    # Reshape to [batch_size * length, feature]\n    lab_curr = targets.reshape(N_snt * max_len, targets.shape[-1])\n\n    loss = ce_kd(prob_curr, lab_curr)\n    # Loss averaging\n    loss = torch.sum(loss.reshape(N_snt, max_len) * mask) / torch.sum(mask)\n    return loss\n", "meta": {"hexsha": "8a13d81f736eb4cd7f85d7cf1773462aad0338ef", "size": 35166, "ext": "py", "lang": "Python", "max_stars_repo_path": "speechbrain/nnet/losses.py", "max_stars_repo_name": "davewhipps/speechbrain", "max_stars_repo_head_hexsha": "3ea4d4878be74465bfbfc8c5e560bbc6417e8812", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-28T10:51:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T10:51:52.000Z", "max_issues_repo_path": "speechbrain/nnet/losses.py", "max_issues_repo_name": "davewhipps/speechbrain", "max_issues_repo_head_hexsha": "3ea4d4878be74465bfbfc8c5e560bbc6417e8812", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "speechbrain/nnet/losses.py", "max_forks_repo_name": "davewhipps/speechbrain", "max_forks_repo_head_hexsha": "3ea4d4878be74465bfbfc8c5e560bbc6417e8812", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0273224044, "max_line_length": 113, "alphanum_fraction": 0.6066370926, "include": true, "reason": "import numpy", "num_tokens": 8605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.31069438959712026, "lm_q1q2_score": 0.17466508478855797}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Authors: James D. McClain\n#          Timothy Berkelbach <tim.berkelbach@gmail.com>\n#\n\nimport time\nimport numpy\nfrom functools import reduce\n\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf.pbc import scf\nfrom pyscf.cc import gccsd\nfrom pyscf.pbc.mp.kmp2 import get_frozen_mask, get_nmo, get_nocc\nfrom pyscf.pbc.cc import kintermediates as imdk\nfrom pyscf.lib.parameters import LOOSE_ZERO_TOL, LARGE_DENOM\nfrom pyscf.pbc.lib import kpts_helper\n\nDEBUG = False\n\n#\n# FIXME: When linear dependence is found in KHF and handled by function\n# pyscf.scf.addons.remove_linear_dep_, different k-point may have different\n# number of orbitals.\n#\n\n#einsum = numpy.einsum\neinsum = lib.einsum\n\n\ndef kernel(cc, eris, t1=None, t2=None, max_cycle=50, tol=1e-8, tolnormt=1e-6,\n           max_memory=2000, verbose=logger.INFO):\n    \"\"\"Exactly the same as pyscf.cc.ccsd.kernel, which calls a\n    *local* energy() function.\"\"\"\n    if isinstance(verbose, logger.Logger):\n        log = verbose\n    else:\n        log = logger.Logger(cc.stdout, verbose)\n\n    assert (isinstance(eris, gccsd._PhysicistsERIs))\n    if t1 is None and t2 is None:\n        t1, t2 = cc.init_amps(eris)[1:]\n    elif t1 is None:\n        nocc = cc.nocc\n        nvir = cc.nmo - nocc\n        nkpts = cc.nkpts\n        t1 = numpy.zeros((nkpts, nocc, nvir), numpy.complex128)\n    elif t2 is None:\n        t2 = cc.init_amps(eris)[2]\n\n    cput1 = cput0 = (time.clock(), time.time())\n    nkpts, nocc, nvir = t1.shape\n    eold = 0\n    eccsd = 0\n\n    if isinstance(cc.diis, lib.diis.DIIS):\n        adiis = cc.diis\n    elif cc.diis:\n        adiis = lib.diis.DIIS(cc, cc.diis_file)\n        adiis.space = cc.diis_space\n    else:\n        adiis = None\n\n    conv = False\n    for istep in range(max_cycle):\n        t1new, t2new = cc.update_amps(t1, t2, eris, max_memory)\n        normt = numpy.linalg.norm(t1new - t1) + numpy.linalg.norm(t2new - t2)\n        if cc.iterative_damping < 1.0:\n            alpha = cc.iterative_damping\n            t1, t2 = (1-alpha)*t1 + alpha*t1new, (1-alpha)*t2 + alpha*t2new\n        else:\n            t1, t2 = t1new, t2new\n        t1new = t2new = None\n\n        t1, t2 = cc.run_diis(t1, t2, istep, normt, eccsd - eold, adiis)\n        eold, eccsd = eccsd, energy(cc, t1, t2, eris)\n        log.info('istep = %d  E(CCSD) = %.15g  dE = %.9g  norm(t1,t2) = %.6g', istep, eccsd, eccsd - eold, normt)\n        cput1 = log.timer('CCSD iter', *cput1)\n        if abs(eccsd - eold) < tol and normt < tolnormt:\n            conv = True\n            break\n    log.timer('CCSD', *cput0)\n    return conv, eccsd, t1, t2\n\n\ndef energy(cc, t1, t2, eris):\n    nkpts, nocc, nvir = t1.shape\n    fock = eris.fock\n    eris_oovv = eris.oovv.copy()\n    e = 0.0 + 0j\n    for ki in range(nkpts):\n        e += einsum('ia,ia', fock[ki, :nocc, nocc:], t1[ki, :, :])\n    t1t1 = numpy.zeros(shape=t2.shape, dtype=t2.dtype)\n    for ki in range(nkpts):\n        ka = ki\n        for kj in range(nkpts):\n            #kb = kj\n            t1t1[ki, kj, ka, :, :, :, :] = einsum('ia,jb->ijab', t1[ki, :, :], t1[kj, :, :])\n    tau = t2 + 2 * t1t1\n    e += 0.25 * numpy.dot(tau.flatten(), eris_oovv.flatten())\n    e /= nkpts\n    if abs(e.imag) > 1e-4:\n        logger.warn(cc, 'Non-zero imaginary part found in KCCSD energy %s', e)\n    return e.real\n\n\ndef update_amps(cc, t1, t2, eris, max_memory=2000):\n    time0 = time.clock(), time.time()\n    log = logger.Logger(cc.stdout, cc.verbose)\n    nkpts, nocc, nvir = t1.shape\n    fock = eris.fock\n\n    fov = fock[:, :nocc, nocc:].copy()\n    foo = fock[:, :nocc, :nocc].copy()\n    fvv = fock[:, nocc:, nocc:].copy()\n\n    tau = imdk.make_tau(cc, t2, t1, t1)\n\n    Fvv = imdk.cc_Fvv(cc, t1, t2, eris)\n    Foo = imdk.cc_Foo(cc, t1, t2, eris)\n    Fov = imdk.cc_Fov(cc, t1, t2, eris)\n    Woooo = imdk.cc_Woooo(cc, t1, t2, eris)\n    Wvvvv = imdk.cc_Wvvvv(cc, t1, t2, eris)\n    Wovvo = imdk.cc_Wovvo(cc, t1, t2, eris)\n\n    # Move energy terms to the other side\n    for k in range(nkpts):\n        Fvv[k] -= numpy.diag(numpy.diag(fvv[k]))\n        Foo[k] -= numpy.diag(numpy.diag(foo[k]))\n\n    # Get the momentum conservation array\n    # Note: chemist's notation for momentum conserving t2(ki,kj,ka,kb), even though\n    # integrals are in physics notation\n    kconserv = kpts_helper.get_kconserv(cc._scf.cell, cc.kpts)\n\n    eris_ovvo = numpy.zeros(shape=(nkpts, nkpts, nkpts, nocc, nvir, nvir, nocc), dtype=t2.dtype)\n    eris_oovo = numpy.zeros(shape=(nkpts, nkpts, nkpts, nocc, nocc, nvir, nocc), dtype=t2.dtype)\n    eris_vvvo = numpy.zeros(shape=(nkpts, nkpts, nkpts, nvir, nvir, nvir, nocc), dtype=t2.dtype)\n    for km, kb, ke in kpts_helper.loop_kkk(nkpts):\n        kj = kconserv[km, ke, kb]\n        # <mb||je> -> -<mb||ej>\n        eris_ovvo[km, kb, ke] = -eris.ovov[km, kb, kj].transpose(0, 1, 3, 2)\n        # <mn||je> -> -<mn||ej>\n        # let kb = kn as a dummy variable\n        eris_oovo[km, kb, ke] = -eris.ooov[km, kb, kj].transpose(0, 1, 3, 2)\n        # <ma||be> -> - <be||am>*\n        # let kj = ka as a dummy variable\n        kj = kconserv[km, ke, kb]\n        eris_vvvo[ke, kj, kb] = -eris.ovvv[km, kb, ke].transpose(2, 3, 1, 0).conj()\n\n    # T1 equation\n    t1new = numpy.zeros(shape=t1.shape, dtype=t1.dtype)\n    for ka in range(nkpts):\n        ki = ka\n        t1new[ka] += numpy.array(fov[ka, :, :]).conj()\n        t1new[ka] += einsum('ie,ae->ia', t1[ka], Fvv[ka])\n        t1new[ka] += -einsum('ma,mi->ia', t1[ka], Foo[ka])\n        for km in range(nkpts):\n            t1new[ka] += einsum('imae,me->ia', t2[ka, km, ka], Fov[km])\n            t1new[ka] += -einsum('nf,naif->ia', t1[km], eris.ovov[km, ka, ki])\n            for kn in range(nkpts):\n                ke = kconserv[km, ki, kn]\n                t1new[ka] += -0.5 * einsum('imef,maef->ia', t2[ki, km, ke], eris.ovvv[km, ka, ke])\n                t1new[ka] += -0.5 * einsum('mnae,nmei->ia', t2[km, kn, ka], eris_oovo[kn, km, ke])\n\n    # T2 equation\n    t2new = numpy.array(eris.oovv).conj()\n    for ki, kj, ka in kpts_helper.loop_kkk(nkpts):\n        # Chemist's notation for momentum conserving t2(ki,kj,ka,kb)\n        kb = kconserv[ki, ka, kj]\n\n        Ftmp = Fvv[kb] - 0.5 * einsum('mb,me->be', t1[kb], Fov[kb])\n        tmp = einsum('ijae,be->ijab', t2[ki, kj, ka], Ftmp)\n        t2new[ki, kj, ka] += tmp\n\n        #t2new[ki,kj,kb] -= tmp.transpose(0,1,3,2)\n        Ftmp = Fvv[ka] - 0.5 * einsum('ma,me->ae', t1[ka], Fov[ka])\n        tmp = einsum('ijbe,ae->ijab', t2[ki, kj, kb], Ftmp)\n        t2new[ki, kj, ka] -= tmp\n\n        Ftmp = Foo[kj] + 0.5 * einsum('je,me->mj', t1[kj], Fov[kj])\n        tmp = einsum('imab,mj->ijab', t2[ki, kj, ka], Ftmp)\n        t2new[ki, kj, ka] -= tmp\n\n        #t2new[kj,ki,ka] += tmp.transpose(1,0,2,3)\n        Ftmp = Foo[ki] + 0.5 * einsum('ie,me->mi', t1[ki], Fov[ki])\n        tmp = einsum('jmab,mi->ijab', t2[kj, ki, ka], Ftmp)\n        t2new[ki, kj, ka] += tmp\n\n        for km in range(nkpts):\n            # Wminj\n            #   - km - kn + ka + kb = 0\n            # =>  kn = ka - km + kb\n            kn = kconserv[ka, km, kb]\n            t2new[ki, kj, ka] += 0.5 * einsum('mnab,mnij->ijab', tau[km, kn, ka], Woooo[km, kn, ki])\n            ke = km\n            t2new[ki, kj, ka] += 0.5 * einsum('ijef,abef->ijab', tau[ki, kj, ke], Wvvvv[ka, kb, ke])\n\n            # Wmbej\n            #     - km - kb + ke + kj = 0\n            #  => ke = km - kj + kb\n            ke = kconserv[km, kj, kb]\n            tmp = einsum('imae,mbej->ijab', t2[ki, km, ka], Wovvo[km, kb, ke])\n            #     - km - kb + ke + kj = 0\n            # =>  ke = km - kj + kb\n            #\n            # t[i,e] => ki = ke\n            # t[m,a] => km = ka\n            if km == ka and ke == ki:\n                tmp -= einsum('ie,ma,mbej->ijab', t1[ki], t1[km], eris_ovvo[km, kb, ke])\n            t2new[ki, kj, ka] += tmp\n            t2new[ki, kj, kb] -= tmp.transpose(0, 1, 3, 2)\n            t2new[kj, ki, ka] -= tmp.transpose(1, 0, 2, 3)\n            t2new[kj, ki, kb] += tmp.transpose(1, 0, 3, 2)\n\n        ke = ki\n        tmp = einsum('ie,abej->ijab', t1[ki], eris_vvvo[ka, kb, ke])\n        t2new[ki, kj, ka] += tmp\n        # P(ij) term\n        ke = kj\n        tmp = einsum('je,abei->ijab', t1[kj], eris_vvvo[ka, kb, ke])\n        t2new[ki, kj, ka] -= tmp\n\n        km = ka\n        tmp = einsum('ma,mbij->ijab', t1[ka], eris.ovoo[km, kb, ki])\n        t2new[ki, kj, ka] -= tmp\n        # P(ab) term\n        km = kb\n        tmp = einsum('mb,maij->ijab', t1[kb], eris.ovoo[km, ka, ki])\n        t2new[ki, kj, ka] += tmp\n\n    eia = numpy.zeros(shape=(nocc, nvir), dtype=t1new.dtype)\n    for ki in range(nkpts):\n        eia = foo[ki].diagonal()[:, None] - fvv[ki].diagonal()[None, :]\n        # When padding the occupied/virtual arrays, some fock elements will be zero\n        idx = numpy.where(abs(eia) < LOOSE_ZERO_TOL)[0]\n        eia[idx] = LARGE_DENOM\n\n        t1new[ki] /= eia\n\n    eijab = numpy.zeros(shape=(nocc, nocc, nvir, nvir), dtype=t2new.dtype)\n    kconserv = kpts_helper.get_kconserv(cc._scf.cell, cc.kpts)\n    for ki, kj, ka in kpts_helper.loop_kkk(nkpts):\n        kb = kconserv[ki, ka, kj]\n        eijab = (foo[ki].diagonal()[:, None, None, None] + foo[kj].diagonal()[None, :, None, None] -\n                 fvv[ka].diagonal()[None, None, :, None] - fvv[kb].diagonal()[None, None, None, :])\n        # Due to padding; see above discussion concerning t1new in update_amps()\n        idx = numpy.where(abs(eijab) < LOOSE_ZERO_TOL)[0]\n        eijab[idx] = LARGE_DENOM\n\n        t2new[ki, kj, ka] /= eijab\n\n    time0 = log.timer_debug1('update t1 t2', *time0)\n\n    return t1new, t2new\n\n\nclass GCCSD(gccsd.GCCSD):\n    def __init__(self, mf, frozen=0, mo_coeff=None, mo_occ=None):\n        assert (isinstance(mf, scf.khf.KSCF))\n        if not isinstance(mf, scf.kghf.KGHF):\n            mf = scf.addons.convert_to_ghf(mf)\n        self.kpts = mf.kpts\n        gccsd.GCCSD.__init__(self, mf, frozen, mo_coeff, mo_occ)\n\n    @property\n    def nkpts(self):\n        return len(self.kpts)\n\n    get_nocc = get_nocc\n    get_nmo = get_nmo\n    get_frozen_mask = get_frozen_mask\n\n    def dump_flags(self):\n        logger.info(self, '\\n')\n        logger.info(self, '******** PBC CC flags ********')\n        gccsd.GCCSD.dump_flags(self)\n        return self\n\n    def init_amps(self, eris):\n        time0 = time.clock(), time.time()\n        nocc = self.nocc\n        nvir = self.nmo - nocc\n        nkpts = self.nkpts\n        t1 = numpy.zeros((nkpts, nocc, nvir), dtype=numpy.complex128)\n        t2 = numpy.zeros((nkpts, nkpts, nkpts, nocc, nocc, nvir, nvir), dtype=numpy.complex128)\n        self.emp2 = 0\n        foo = eris.fock[:, :nocc, :nocc].copy()\n        fvv = eris.fock[:, nocc:, nocc:].copy()\n        fov = eris.fock[:, :nocc, nocc:].copy()\n        eris_oovv = eris.oovv.copy()\n        eia = numpy.zeros((nocc, nvir))\n        eijab = numpy.zeros((nocc, nocc, nvir, nvir))\n\n        kconserv = kpts_helper.get_kconserv(self._scf.cell, self.kpts)\n        for ki, kj, ka in kpts_helper.loop_kkk(nkpts):\n            kb = kconserv[ki, ka, kj]\n            eijab = (foo[ki].diagonal()[:, None, None, None] + foo[kj].diagonal()[None, :, None, None] -\n                     fvv[ka].diagonal()[None, None, :, None] - fvv[kb].diagonal()[None, None, None, :])\n            # Due to padding; see above discussion concerning t1new in update_amps()\n            idx = numpy.where(abs(eijab) < LOOSE_ZERO_TOL)[0]\n            eijab[idx] = LARGE_DENOM\n\n            t2[ki, kj, ka] = eris_oovv[ki, kj, ka] / eijab\n\n        t2 = numpy.conj(t2)\n        self.emp2 = 0.25 * numpy.einsum('pqrijab,pqrijab', t2, eris_oovv).real\n        self.emp2 /= nkpts\n\n        logger.info(self, 'Init t2, MP2 energy = %.15g', self.emp2.real)\n        logger.timer(self, 'init mp2', *time0)\n        return self.emp2, t1, t2\n\n    def ccsd(self, t1=None, t2=None, eris=None, **kwargs):\n        if eris is None: eris = self.ao2mo(self.mo_coeff)\n        self.eris = eris\n        self.converged, self.e_corr, self.t1, self.t2 = \\\n                kernel(self, eris, t1, t2, max_cycle=self.max_cycle,\n                       tol=self.conv_tol,\n                       tolnormt=self.conv_tol_normt,\n                       max_memory=self.max_memory, verbose=self.verbose)\n        if self.converged:\n            logger.info(self, 'CCSD converged')\n        else:\n            logger.info(self, 'CCSD not converge')\n        if self._scf.e_tot == 0:\n            logger.info(self, 'E_corr = %.16g', self.e_corr)\n        else:\n            logger.info(self, 'E(CCSD) = %.16g  E_corr = %.16g', self.e_corr + self._scf.e_tot, self.e_corr)\n        return self.e_corr, self.t1, self.t2\n\n    def ao2mo(self, mo_coeff=None):\n        nkpts = self.nkpts\n        nmo = self.nmo\n        mem_incore = nkpts**3 * nmo**4 * 8 / 1e6\n        mem_now = lib.current_memory()[0]\n\n        if (mem_incore + mem_now < self.max_memory) or self.mol.incore_anyway:\n            return _make_eris_incore(self, mo_coeff)\n        else:\n            raise NotImplementedError\n\n    def update_amps(self, t1, t2, eris, max_memory=2000):\n        return update_amps(self, t1, t2, eris, max_memory)\n\n    def amplitudes_to_vector(self, t1, t2):\n        return numpy.hstack((t1.ravel(), t2.ravel()))\n\n    def vector_to_amplitudes(self, vec, nmo=None, nocc=None):\n        if nocc is None: nocc = self.nocc\n        if nmo is None: nmo = self.nmo\n        nvir = nmo - nocc\n        nkpts = self.nkpts\n        nov = nkpts * nocc * nvir\n        t1 = vec[:nov].reshape(nkpts, nocc, nvir)\n        t2 = vec[nov:].reshape(nkpts, nkpts, nkpts, nocc, nocc, nvir, nvir)\n        return t1, t2\n\n\nCCSD = GCCSD\n\n\ndef _make_eris_incore(cc, mo_coeff=None):\n    log = logger.Logger(cc.stdout, cc.verbose)\n    cput0 = (time.clock(), time.time())\n    eris = gccsd._PhysicistsERIs()\n    kpts = cc.kpts\n    nkpts = cc.nkpts\n    nocc = cc.nocc\n    nmo = cc.nmo\n    nvir = nmo - nocc\n    eris.nocc = nocc\n\n    #if any(nocc != numpy.count_nonzero(cc._scf.mo_occ[k] > 0) for k in range(nkpts)):\n    #    raise NotImplementedError('Different occupancies found for different k-points')\n\n    if mo_coeff is None:\n        # If mo_coeff is not canonical orbital\n        # TODO does this work for k-points? changed to conjugate.\n        raise NotImplementedError\n        mo_coeff = cc.mo_coeff\n    nao = mo_coeff[0].shape[0]\n    dtype = mo_coeff[0].dtype\n\n    moidx = get_frozen_mask(cc)\n    nocc_per_kpt = numpy.asarray(get_nocc(cc, per_kpoint=True))\n    nmo_per_kpt  = numpy.asarray(get_nmo(cc, per_kpoint=True))\n\n    padded_moidx = []\n    for k in range(nkpts):\n        kpt_nocc = nocc_per_kpt[k]\n        kpt_nvir = nmo_per_kpt[k] - kpt_nocc\n        kpt_padded_moidx = numpy.concatenate((numpy.ones(kpt_nocc, dtype=numpy.bool),\n                                              numpy.zeros(nmo - kpt_nocc - kpt_nvir, dtype=numpy.bool),\n                                              numpy.ones(kpt_nvir, dtype=numpy.bool)))\n        padded_moidx.append(kpt_padded_moidx)\n\n    eris.mo_coeff = []\n    eris.orbspin = []\n    # Generate the molecular orbital coefficients with the frozen orbitals masked.\n    # Each MO is tagged with orbspin, a list of 0's and 1's that give the overall\n    # spin of each MO.\n    #\n    # Here we will work with two index arrays; one is for our original (small) moidx\n    # array while the next is for our new (large) padded array.\n    for k in range(nkpts):\n        kpt_moidx = moidx[k]\n        kpt_padded_moidx = padded_moidx[k]\n\n        mo = numpy.zeros((nao, nmo), dtype=dtype)\n        mo[:, kpt_padded_moidx] = mo_coeff[k][:, kpt_moidx]\n        if hasattr(mo_coeff[k], 'orbspin'):\n            orbspin_dtype = mo_coeff[k].orbspin[kpt_moidx].dtype\n            orbspin = numpy.zeros(nmo, dtype=orbspin_dtype)\n            orbspin[kpt_padded_moidx] = mo_coeff[k].orbspin[kpt_moidx]\n            mo = lib.tag_array(mo, orbspin=orbspin)\n            eris.orbspin.append(orbspin)\n        # FIXME: What if the user freezes all up spin orbitals in\n        # an RHF calculation?  The number of electrons will still be\n        # even.\n        else:  # guess orbital spin - assumes an RHF calculation\n            assert (numpy.count_nonzero(kpt_moidx) % 2 == 0)\n            orbspin = numpy.zeros(mo.shape[1], dtype=int)\n            orbspin[1::2] = 1\n            mo = lib.tag_array(mo, orbspin=orbspin)\n            eris.orbspin.append(orbspin)\n        eris.mo_coeff.append(mo)\n\n    # Re-make our fock MO matrix elements from density and fock AO\n    dm = cc._scf.make_rdm1(cc.mo_coeff, cc.mo_occ)\n    fockao = cc._scf.get_hcore() + cc._scf.get_veff(cc._scf.cell, dm)\n    eris.fock = numpy.asarray([reduce(numpy.dot, (mo.T.conj(), fockao[k], mo)) for k, mo in enumerate(eris.mo_coeff)])\n\n    kconserv = kpts_helper.get_kconserv(cc._scf.cell, cc.kpts)\n    # The bottom nao//2 coefficients are down (up) spin while the top are up (down).\n    # These are 'spin-less' quantities; spin-conservation will be added manually.\n    so_coeff = [mo[:nao // 2] + mo[nao // 2:] for mo in eris.mo_coeff]\n\n    eri = numpy.empty((nkpts, nkpts, nkpts, nmo, nmo, nmo, nmo), dtype=numpy.complex128)\n    fao2mo = cc._scf.with_df.ao2mo\n    for kp, kq, kr in kpts_helper.loop_kkk(nkpts):\n        ks = kconserv[kp, kq, kr]\n        eri_kpt = fao2mo(\n            (so_coeff[kp], so_coeff[kq], so_coeff[kr], so_coeff[ks]), (kpts[kp], kpts[kq], kpts[kr], kpts[ks]),\n            compact=False)\n        eri_kpt[(eris.orbspin[kp][:, None] != eris.orbspin[kq]).ravel()] = 0\n        eri_kpt[:, (eris.orbspin[kr][:, None] != eris.orbspin[ks]).ravel()] = 0\n        eri_kpt = eri_kpt.reshape(nmo, nmo, nmo, nmo)\n        eri[kp, kq, kr] = eri_kpt\n\n    # Check some antisymmetrized properties of the integrals\n    if DEBUG:\n        check_antisymm_3412(cc, cc.kpts, eri)\n\n    # Antisymmetrizing (pq|rs)-(ps|rq), where the latter integral is equal to\n    # (rq|ps); done since we aren't tracking the kpoint of orbital 's'\n    eri = eri - eri.transpose(2, 1, 0, 5, 4, 3, 6)\n    # Chemist -> physics notation\n    eri = eri.transpose(0, 2, 1, 3, 5, 4, 6)\n\n    # Set the various integrals\n    eris.dtype = eri.dtype\n    eris.oooo = eri[:, :, :, :nocc, :nocc, :nocc, :nocc].copy() / nkpts\n    eris.ooov = eri[:, :, :, :nocc, :nocc, :nocc, nocc:].copy() / nkpts\n    eris.ovoo = eri[:, :, :, :nocc, nocc:, :nocc, :nocc].copy() / nkpts\n    eris.oovv = eri[:, :, :, :nocc, :nocc, nocc:, nocc:].copy() / nkpts\n    eris.ovov = eri[:, :, :, :nocc, nocc:, :nocc, nocc:].copy() / nkpts\n    eris.ovvv = eri[:, :, :, :nocc, nocc:, nocc:, nocc:].copy() / nkpts\n    eris.vvvv = eri[:, :, :, nocc:, nocc:, nocc:, nocc:].copy() / nkpts\n\n    log.timer('CCSD integral transformation', *cput0)\n    return eris\n\n\ndef check_antisymm_3412(cc, kpts, integrals):\n    kconserv = kpts_helper.get_kconserv(cc._scf.cell, cc.kpts)\n    nkpts = len(kpts)\n    diff = 0.0\n    for kp, kq, kr in kpts_helper.loop_kkk(nkpts):\n        ks = kconserv[kp, kr, kq]\n        for p in range(integrals.shape[3]):\n            for q in range(integrals.shape[4]):\n                for r in range(integrals.shape[5]):\n                    for s in range(integrals.shape[6]):\n                        pqrs = integrals[kp, kq, kr, p, q, r, s]\n                        rspq = integrals[kq, kp, kr, q, p, r, s]\n                        cdiff = numpy.linalg.norm(pqrs - rspq).real\n                        if diff > 1e-5:\n                            print(\"AS diff = %.15g\" % cdiff, pqrs, rspq, kp, kq, kr, ks, p, q, r, s)\n                        diff = max(diff, cdiff)\n    print(\"antisymmetrization : max diff = %.15g\" % diff)\n    if diff > 1e-5:\n        print(\"Energy cutoff (or cell.mesh) is not enough to converge AO integrals.\")\n    return diff\n\n\ndef check_antisymm_12(cc, kpts, integrals):\n    kconserv = kpts_helper.get_kconserv(cc._scf.cell, cc.kpts)\n    nkpts = len(kpts)\n    diff = 0.0\n    for kp, kq, kr in kpts_helper.loop_kkk(nkpts):\n        ks = kconserv[kp, kr, kq]\n        for p in range(integrals.shape[3]):\n            for q in range(integrals.shape[4]):\n                for r in range(integrals.shape[5]):\n                    for s in range(integrals.shape[6]):\n                        pqrs = integrals[kp, kq, kr, p, q, r, s]\n                        qprs = integrals[kq, kp, kr, q, p, r, s]\n                        cdiff = numpy.linalg.norm(pqrs + qprs).real\n                        if diff > 1e-5:\n                            print(\"AS diff = %.15g\" % cdiff, pqrs, qprs, kp, kq, kr, ks, p, q, r, s)\n                        diff = max(diff, cdiff)\n    print(\"antisymmetrization : max diff = %.15g\" % diff)\n    if diff > 1e-5:\n        print(\"Energy cutoff (or cell.mesh) is not enough to converge AO integrals.\")\n\n\ndef check_antisymm_34(cc, kpts, integrals):\n    kconserv = kpts_helper.get_kconserv(cc._scf.cell, cc.kpts)\n    nkpts = len(kpts)\n    diff = 0.0\n    for kp, kq, kr in kpts_helper.loop_kkk(nkpts):\n        ks = kconserv[kp, kr, kq]\n        for p in range(integrals.shape[3]):\n            for q in range(integrals.shape[4]):\n                for r in range(integrals.shape[5]):\n                    for s in range(integrals.shape[6]):\n                        pqrs = integrals[kp, kq, kr, p, q, r, s]\n                        pqsr = integrals[kp, kq, ks, p, q, s, r]\n                        cdiff = numpy.linalg.norm(pqrs + pqsr).real\n                        if diff > 1e-5:\n                            print(\"AS diff = %.15g\" % cdiff, pqrs, pqsr, kp, kq, kr, ks, p, q, r, s)\n                        diff = max(diff, cdiff)\n    print(\"antisymmetrization : max diff = %.15g\" % diff)\n    if diff > 1e-5:\n        print(\"Energy cutoff (or cell.mesh) is not enough to converge AO integrals.\")\n", "meta": {"hexsha": "6007c7de3db3877f923c2591446069b2f0a3aefe", "size": 22137, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/pbc/cc/kccsd.py", "max_stars_repo_name": "y-yao/pyscf_arrow", "max_stars_repo_head_hexsha": "079088a5d92af1570167004f411207deb104a1bb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-01T12:39:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-01T12:39:45.000Z", "max_issues_repo_path": "pyscf/pbc/cc/kccsd.py", "max_issues_repo_name": "y-yao/pyscf_arrow", "max_issues_repo_head_hexsha": "079088a5d92af1570167004f411207deb104a1bb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscf/pbc/cc/kccsd.py", "max_forks_repo_name": "y-yao/pyscf_arrow", "max_forks_repo_head_hexsha": "079088a5d92af1570167004f411207deb104a1bb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1760435572, "max_line_length": 118, "alphanum_fraction": 0.570673533, "include": true, "reason": "import numpy", "num_tokens": 7476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.17466508478855794}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCIE 2017 Colour Fidelity Index\n==============================\n\nDefines the *CIE 2017 Colour Fidelity Index* (CFI) computation objects:\n\n- :class:`colour.quality.ColourRendering_Specification_CIE2017`\n- :func:`colour.quality.colour_fidelity_index_CIE2017`\n\nReferences\n----------\n-   :cite:`CIETC1-902017` : CIE TC 1-90. (2017). CIE 2017 colour fidelity index\n    for accurate scientific use. CIE Central Bureau. ISBN:978-3-902842-61-9\n\"\"\"\n\nimport numpy as np\nimport os\nfrom collections import namedtuple\n\nfrom colour.algebra import Extrapolator, euclidean_distance, linstep_function\nfrom colour.appearance import XYZ_to_CIECAM02, VIEWING_CONDITIONS_CIECAM02\nfrom colour.colorimetry import (\n    MSDS_CMFS_STANDARD_OBSERVER, MultiSpectralDistributions, SpectralShape,\n    SpectralDistribution, sd_to_XYZ, sd_blackbody, reshape_msds, sd_ones,\n    sd_CIE_illuminant_D_series)\nfrom colour.models import XYZ_to_UCS, UCS_to_uv, JMh_CIECAM02_to_CAM02UCS\nfrom colour.temperature import uv_to_CCT_Ohno2013, CCT_to_xy_CIE_D\nfrom colour.utilities import CACHE_REGISTRY, as_int, usage_warning\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2021 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-developers@colour-science.org'\n__status__ = 'Production'\n\n__all__ = [\n    'SPECTRAL_SHAPE_CIE2017', 'RESOURCES_DIRECTORY_CIE2017',\n    'TCS_ColorimetryData_CIE2017', 'ColourRendering_Specification_CIE2017',\n    'colour_fidelity_index_CIE2017', 'load_TCS_CIE2017',\n    'CCT_reference_illuminant', 'sd_reference_illuminant',\n    'tcs_colorimetry_data', 'delta_E_to_R_f'\n]\n\nSPECTRAL_SHAPE_CIE2017 = SpectralShape(380, 780, 1)\n\"\"\"\nSpectral shape for *CIE 2017 Colour Fidelity Index* (CFI)\nstandard.\n\nSPECTRAL_SHAPE_CIE2017 : SpectralShape\n\"\"\"\n\nRESOURCES_DIRECTORY_CIE2017 = os.path.join(\n    os.path.dirname(__file__), 'datasets')\n\"\"\"\n*CIE 2017 Colour Fidelity Index* resources directory.\n\nRESOURCES_DIRECTORY_CIE2017 : unicode\n\"\"\"\n\n_CACHE_TCS_CIE2017 = CACHE_REGISTRY.register_cache(\n    '{0}._CACHE_TCS_CIE2017'.format(__name__))\n\n\nclass TCS_ColorimetryData_CIE2017(\n        namedtuple('TCS_ColorimetryData_CIE2017',\n                   ('name', 'XYZ', 'CAM', 'JMh', 'Jpapbp'))):\n    \"\"\"\n    Defines the the class storing *test colour samples* colorimetry data.\n    \"\"\"\n\n\nclass ColourRendering_Specification_CIE2017(\n        namedtuple('ColourRendering_Specification_CIE2017',\n                   ('name', 'sd_reference', 'R_f', 'R_s', 'CCT', 'D_uv',\n                    'colorimetry_data', 'delta_E_s'))):\n    \"\"\"\n    Defines the *CIE 2017 Colour Fidelity Index* (CFI) colour quality\n    specification.\n\n    Parameters\n    ----------\n    name : unicode\n        Name of the test spectral distribution.\n    sd_reference : SpectralDistribution\n        Spectral distribution of the reference illuminant.\n    R_f : numeric\n        *CIE 2017 Colour Fidelity Index* (CFI) :math:`R_f`.\n    R_s : array_like\n        Individual *colour fidelity indexes* data for each sample.\n    CCT : numeric\n        Correlated colour temperature :math:`T_{cp}`.\n    D_uv : numeric\n        Distance from the Planckian locus :math:`\\\\Delta_{uv}`.\n    colorimetry_data : tuple\n        Colorimetry data for the test and reference computations.\n    delta_E_s : ndarray, (16,)\n        Colour shifts of samples.\n    \"\"\"\n\n\ndef colour_fidelity_index_CIE2017(sd_test, additional_data=False):\n    \"\"\"\n    Returns the *CIE 2017 Colour Fidelity Index* (CFI) :math:`R_f` of given\n    spectral distribution.\n\n    Parameters\n    ----------\n    sd_test : SpectralDistribution\n        Test spectral distribution.\n    additional_data : bool, optional\n        Whether to output additional data.\n\n    Returns\n    -------\n    numeric or ColourRendering_Specification_CIE2017\n        *CIE 2017 Colour Fidelity Index* (CFI) :math:`R_f`.\n\n    References\n    ----------\n    :cite:`CIETC1-902017`\n\n    Examples\n    --------\n    >>> from colour.colorimetry import SDS_ILLUMINANTS\n    >>> sd = SDS_ILLUMINANTS['FL2']\n    >>> colour_fidelity_index_CIE2017(sd)  # doctest: +ELLIPSIS\n    70.1208254...\n    \"\"\"\n\n    if sd_test.shape.start > 380 or sd_test.shape.end < 780:\n        usage_warning('Test spectral distribution shape does not span the'\n                      'recommended 380-780nm range, missing values will be'\n                      'filled with zeros!')\n\n        # NOTE: \"CIE 2017 Colour Fidelity Index\" standard recommends filling\n        # missing values with zeros.\n        sd_test = sd_test.copy()\n        sd_test.extrapolator = Extrapolator\n        sd_test.extrapolator_kwargs = {\n            'method': 'constant',\n            'left': 0,\n            'right': 0\n        }\n\n    if sd_test.shape.interval > 5:\n        raise ValueError('Test spectral distribution interval is greater than'\n                         '5nm which is the maximum recommended value '\n                         'for computing the \"CIE 2017 Colour Fidelity Index\"!')\n\n    shape = SpectralShape(SPECTRAL_SHAPE_CIE2017.start,\n                          SPECTRAL_SHAPE_CIE2017.end, sd_test.shape.interval)\n\n    CCT, D_uv = CCT_reference_illuminant(sd_test)\n    sd_reference = sd_reference_illuminant(CCT, shape)\n\n    # NOTE: All computations except CCT calculation use the\n    # \"CIE 1964 10 Degree Standard Observer\".\n    # pylint: disable=E1102\n    cmfs_10 = reshape_msds(\n        MSDS_CMFS_STANDARD_OBSERVER['CIE 1964 10 Degree Standard Observer'],\n        shape)\n\n    # pylint: disable=E1102\n    sds_tcs = reshape_msds(load_TCS_CIE2017(shape), shape)\n\n    test_tcs_colorimetry_data = tcs_colorimetry_data(sd_test, sds_tcs, cmfs_10)\n    reference_tcs_colorimetry_data = tcs_colorimetry_data(\n        sd_reference, sds_tcs, cmfs_10)\n\n    delta_E_s = np.empty(len(sds_tcs.labels))\n    for i, _delta_E in enumerate(delta_E_s):\n        delta_E_s[i] = euclidean_distance(\n            test_tcs_colorimetry_data[i].Jpapbp,\n            reference_tcs_colorimetry_data[i].Jpapbp)\n\n    R_s = delta_E_to_R_f(delta_E_s)\n    R_f = delta_E_to_R_f(np.average(delta_E_s))\n\n    if additional_data:\n        return ColourRendering_Specification_CIE2017(\n            sd_test.name, sd_reference, R_f, R_s, CCT, D_uv,\n            (test_tcs_colorimetry_data, reference_tcs_colorimetry_data),\n            delta_E_s)\n    else:\n        return R_f\n\n\ndef load_TCS_CIE2017(shape):\n    \"\"\"\n    Loads the *CIE 2017 Test Colour Samples* dataset appropriate for the given\n    spectral shape.\n\n    The datasets are cached and won't be loaded again on subsequent calls to\n    this definition.\n\n    Parameters\n    ----------\n    shape : SpectralShape\n        Spectral shape of the tested illuminant.\n\n    Returns\n    -------\n    MultiSpectralDistributions\n        *CIE 2017 Test Colour Samples* dataset.\n\n    Examples\n    --------\n    >>> sds_tcs = load_TCS_CIE2017(SpectralShape(interval=5))\n    >>> len(sds_tcs.labels)\n    99\n    \"\"\"\n\n    global _CACHE_TCS_CIE2017\n\n    interval = shape.interval\n\n    assert interval in (1, 5), (\n        'Spectral shape interval must be either 1nm or 5nm!')\n\n    filename = 'tcs_cfi2017_{0}_nm.csv.gz'.format(as_int(interval))\n\n    if filename in _CACHE_TCS_CIE2017:\n        return _CACHE_TCS_CIE2017[filename]\n\n    data = np.genfromtxt(\n        str(os.path.join(RESOURCES_DIRECTORY_CIE2017, filename)),\n        delimiter=',')\n    labels = ['TCS{0} (CIE 2017)'.format(i) for i in range(99)]\n\n    tcs = MultiSpectralDistributions(data[:, 1:], data[:, 0], labels)\n\n    _CACHE_TCS_CIE2017[filename] = tcs\n\n    return tcs\n\n\ndef CCT_reference_illuminant(sd):\n    \"\"\"\n    Computes the reference illuminant correlated colour temperature\n    :math:`T_{cp}` and :math:`\\\\Delta_{uv}` for given test spectral\n    distribution using *Ohno (2013)* method.\n\n    Parameters\n    ----------\n    sd : SpectralDistribution\n        Test spectral distribution.\n\n    Returns\n    -------\n    ndarray\n        Correlated colour temperature :math:`T_{cp}`, :math:`\\\\Delta_{uv}`.\n\n    Examples\n    --------\n    >>> from colour import SDS_ILLUMINANTS\n    >>> sd = SDS_ILLUMINANTS['FL2']\n    >>> CCT_reference_illuminant(sd)  # doctest: +ELLIPSIS\n    (4224.4697052..., 0.0017871...)\n    \"\"\"\n\n    XYZ = sd_to_XYZ(sd)\n\n    CCT, D_uv = uv_to_CCT_Ohno2013(UCS_to_uv(XYZ_to_UCS(XYZ)))\n\n    return CCT, D_uv\n\n\ndef sd_reference_illuminant(CCT, shape):\n    \"\"\"\n    Computes the reference illuminant for a given correlated colour temperature\n    :math:`T_{cp}` for use in *CIE 2017 Colour Fidelity Index* (CFI)\n    computation.\n\n    Parameters\n    ----------\n    CCT : numeric\n        Correlated colour temperature :math:`T_{cp}`.\n    shape : SpectralShape\n        Desired shape of the returned spectral distribution.\n\n    Returns\n    -------\n    SpectralDistribution\n        Reference illuminant for *CIE 2017 Colour Fidelity Index* (CFI)\n        computation.\n\n    Examples\n    --------\n    >>> from colour.utilities import numpy_print_options\n    >>> with numpy_print_options(suppress=True):\n    ...     sd_reference_illuminant(  # doctest: +ELLIPSIS\n    ...         4224.469705295263300, SpectralShape(380, 780, 20))\n    SpectralDistribution([[ 380.        ,    0.0034089...],\n                          [ 400.        ,    0.0044208...],\n                          [ 420.        ,    0.0053260...],\n                          [ 440.        ,    0.0062857...],\n                          [ 460.        ,    0.0072767...],\n                          [ 480.        ,    0.0080207...],\n                          [ 500.        ,    0.0086590...],\n                          [ 520.        ,    0.0092242...],\n                          [ 540.        ,    0.0097686...],\n                          [ 560.        ,    0.0101444...],\n                          [ 580.        ,    0.0104475...],\n                          [ 600.        ,    0.0107642...],\n                          [ 620.        ,    0.0110439...],\n                          [ 640.        ,    0.0112535...],\n                          [ 660.        ,    0.0113922...],\n                          [ 680.        ,    0.0115185...],\n                          [ 700.        ,    0.0113155...],\n                          [ 720.        ,    0.0108192...],\n                          [ 740.        ,    0.0111582...],\n                          [ 760.        ,    0.0101299...],\n                          [ 780.        ,    0.0105638...]],\n                         interpolator=SpragueInterpolator,\n                         interpolator_kwargs={},\n                         extrapolator=Extrapolator,\n                         extrapolator_kwargs={...})\n    \"\"\"\n\n    if CCT <= 5000:\n        sd_planckian = sd_blackbody(CCT, shape)\n\n    if CCT >= 4000:\n        xy = CCT_to_xy_CIE_D(CCT)\n        sd_daylight = sd_CIE_illuminant_D_series(xy).align(shape)\n\n    if CCT < 4000:\n        sd_reference = sd_planckian\n    elif 4000 <= CCT <= 5000:\n        # Planckian and daylight illuminant must be normalised so that the\n        # mixture isn't biased.\n        sd_planckian /= sd_to_XYZ(sd_planckian)[1]\n        sd_daylight /= sd_to_XYZ(sd_daylight)[1]\n\n        # Mixture: 4200K should be 80% Planckian, 20% CIE Illuminant D Series.\n        m = (CCT - 4000) / 1000\n        values = linstep_function(m, sd_planckian.values, sd_daylight.values)\n        name = ('{0}K Blackbody & CIE Illuminant D Series Mixture - {1:.1f}%'\n                .format(as_int(CCT), 100 * m))\n        sd_reference = SpectralDistribution(values, shape.range(), name=name)\n    elif CCT > 5000:\n        sd_reference = sd_daylight\n\n    return sd_reference\n\n\ndef tcs_colorimetry_data(sd_irradiance, sds_tcs, cmfs):\n    \"\"\"\n    Returns the *test colour samples* colorimetry data under given test light\n    source or reference illuminant spectral distribution for the\n    *CIE 2017 Colour Fidelity Index* (CFI) computations.\n\n    Parameters\n    ----------\n    sd_irradiance : SpectralDistribution\n        Test light source or reference illuminant spectral distribution, i.e.\n        the irradiance emitter.\n    sds_tcs : MultiSpectralDistributions\n        *Test colour samples* spectral distributions.\n    cmfs : XYZ_ColourMatchingFunctions\n        Standard observer colour matching functions.\n\n    Returns\n    -------\n    list\n        *Test colour samples* colorimetry data under the given test light\n        source or reference illuminant spectral distribution.\n\n    Examples\n    --------\n    >>> delta_E_to_R_f(4.4410383190)  # doctest: +ELLIPSIS\n    70.1208254...\n    \"\"\"\n\n    XYZ_w = sd_to_XYZ(sd_ones(), cmfs, sd_irradiance)\n    Y_b = 20\n    L_A = 100\n    surround = VIEWING_CONDITIONS_CIECAM02['Average']\n\n    tcs_data = []\n    for sd_tcs in sds_tcs.to_sds():\n        XYZ = sd_to_XYZ(sd_tcs, cmfs, sd_irradiance)\n        CAM = XYZ_to_CIECAM02(XYZ, XYZ_w, L_A, Y_b, surround, True)\n        JMh = CAM.J, CAM.M, CAM.h\n        Jpapbp = JMh_CIECAM02_to_CAM02UCS(JMh)\n\n        tcs_data.append(\n            TCS_ColorimetryData_CIE2017(sd_tcs.name, XYZ, CAM, JMh, Jpapbp))\n\n    return tcs_data\n\n\ndef delta_E_to_R_f(delta_E):\n    \"\"\"\n    Converts from colour-appearance difference to\n    *CIE 2017 Colour Fidelity Index* (CFI) :math:`R_f` value.\n\n    Parameters\n    ----------\n    delta_E : numeric\n        Euclidean distance between two colours in *CAM02-UCS* colourspace.\n\n    Returns\n    -------\n    float\n        Corresponding *CIE 2017 Colour Fidelity Index* (CFI) :math:`R_f` value.\n    \"\"\"\n\n    c_f = 6.73\n\n    return 10 * np.log(np.exp((100 - c_f * delta_E) / 10) + 1)\n", "meta": {"hexsha": "fc243341d33c4e1f37dbaa56b54665eb621909ee", "size": 13503, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/quality/cfi2017.py", "max_stars_repo_name": "villirion/colour", "max_stars_repo_head_hexsha": "27a3e6ad2900988dd91505f0b18c318301f0a6c6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "colour/quality/cfi2017.py", "max_issues_repo_name": "villirion/colour", "max_issues_repo_head_hexsha": "27a3e6ad2900988dd91505f0b18c318301f0a6c6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/quality/cfi2017.py", "max_forks_repo_name": "villirion/colour", "max_forks_repo_head_hexsha": "27a3e6ad2900988dd91505f0b18c318301f0a6c6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.615942029, "max_line_length": 79, "alphanum_fraction": 0.6211212323, "include": true, "reason": "import numpy", "num_tokens": 3656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.31069438959712015, "lm_q1q2_score": 0.1746650847885579}}
{"text": "from __future__ import division\nimport numpy as np\nfrom scipy.linalg import solve\nimport sys\nimport time\nfrom properties import *\nfrom parse_file import *\n\nclass RealTime(object):\n    \"\"\"A RealTime object contains important parsed data from a Gaussian RealTime\n    log file.\n\n    Attributes:\n        name:            A string containing primary filename\n        logfile:         A string representing the Gaussian realtime log file \n        electricDipole:  Object containing x, y, z electric dipole moments (au)\n        magneticDipole:  Object containing x, y, z magnetic dipole moments (au)\n        electricField:   Object containing x, y, z electric field strengths (au)\n        magneticField:   Object containing x, y, z magnetic field strengths (au)\n        iops:            Dict containing IOps for 512 \n        envelope:        Dict containing field parameters printed in logfile\n        time:            Array containing time (au)\n        energy:          Array containing energy (au)\n        frequency:       Array containing frequencies from *time* (au)\n        fourier:         Array containing fourier transformed signal (au)\n        propertyarrays:  List containing names of properties stored as arrays.\n        truncate:        Method to truncate propertyarrays to a given length\n        mmut_restart:    Integer containing how often MMUT restarts\n        au2fs:           Scalar constant to convert au to femtoseconds \n    \"\"\"\n\n    def __init__(self, name, prog=\"GAUSSIAN\"):\n        \"\"\"Return a RealTime object whose logfile is *logfile*.\"\"\" \n        # Initialize data\n        self.name           = name\n        self.prog           = prog\n\n        if prog == \"GAUSSIAN\":\n          self.logfile        = name+'.log'\n          self.iops           = {'132':['0'],\n                                 '134':['0'], \n                                 '177':['0'], \n                                 '136':['0'], \n                                 '137':['0'], \n                                 '138':['0'], \n                                 '139':['0'], \n                                 '140':['0'], \n                                 '141':['0'], \n                                 '142':['0'], \n                                 '143':['0'], \n                                 '144':['0']}\n        elif prog == \"CQ\":\n          self.fieldFile    = name + \"_RealTime_AppliedField.csv\"\n          self.dipoleFile   = name + \"_RealTime_Dipole.csv\"\n          self.mullikenFile = name + \"_RealTime_Mulliken.csv\"\n          self.occAFile     = name + \"_RealTime_OrbOcc_Alpha.csv\"\n          self.occBFile     = name + \"_RealTime_OrbOcc_Beta.csv\"\n\n        else:\n          pass # Should throw an error here\n\n        self.envelope       = {}\n        self.electricDipole = ElectricDipole()\n        self.magneticDipole = MagneticDipole()\n        self.electricField  = ElectricField()\n        self.magneticField  = MagneticField()\n        self.orthonorm      = None\n        self.step_size      = None\n        self.total_steps    = None\n        self.time           = None\n        self.energy         = None\n        self.frequency      = None \n        self.fourier        = None\n        self.au2fs          = 0.0241888425\n        # TODO May want to look at a better way of defining which attributes are\n        # arrays instead of just hard-coding them in.\n        self.propertyarrays = ['electricDipole',\n                               'magneticDipole',\n                               'electricField',\n                               'magneticField',\n                               'time',\n                               #FIXME valid for H2+ Rabi ONLY\n                               'HOMO',\n                               'LUMO',\n                               'energy']\n        self.truncate       = truncate\n        self.min_length     = None\n        self.mmut_restart   = 10000000000 # e.g. never restart\n        #FIXME: ONLY FOR H2+ RABI\n        self.HOMO           = None\n        self.LUMO           = None\n\n        # Call parser \n        parse_file(self)\n\n        if prog == \"GAUSSIAN\":\n          decode_iops(self)\n\n          # Make all arrays consistent length\n          clean_data(self)\n\n    def pade_tx(self,dipole_direction='x',spectra='abs',damp_const=5500,\n        num_pts=10000):\n        # num_pts: number of points to sample for pade transformation\n\n        if (spectra.lower() == 'abs') or (spectra.lower() == 'power'):  \n            if dipole_direction.lower() == 'x':\n                dipole = self.electricDipole.x\n#                kick_strength = self.electricField.x[0]\n            elif dipole_direction.lower() == 'y':\n                dipole = self.electricDipole.y\n#                kick_strength = self.electricField.y[0]\n            elif dipole_direction.lower() == 'z':\n                dipole = self.electricDipole.z\n#                kick_strength = self.electricField.z[0]\n            else:\n                print \"Not a valid direction for the dipole! Try: x,y,z \"\n        elif spectra.lower() == 'ecd':\n            if dipole_direction.lower() == 'x':\n                dipole = self.magneticDipole.x\n                kick_strength = self.electricField.x[0]\n            elif dipole_direction.lower() == 'y':\n                dipole = self.magneticDipole.y\n                kick_strength = self.electricField.y[0]\n            elif dipole_direction.lower() == 'z':\n                dipole = self.magneticDipole.z\n                kick_strength = self.electricField.z[0]\n            else:\n                print \"Not a valid direction for the dipole! Try: x,y,z \"\n        else: \n            print \"Not a valid spectra choice\"\n\n#        if np.isclose(kick_strength,0.0):\n#            if dipole_direction.lower() == 'x':\n#                kick_strength = max(self.electricField.x)\n#            elif dipole_direction.lower() == 'y':\n#                kick_strength = max(self.electricField.y)\n#            elif dipole_direction.lower() == 'z':\n#                kick_strength = max(self.electricField.z)\n#            if np.isclose(kick_strength,0.0):\n#                print \"Kick strength = 0. Make sure you FFT'd the correct direction\"\n#                sys.exit(0)\n#            print \"It looks like you are not perturbing the field at time = 0\"\n#            print \"so we are taking the maximum of the electric field instead\"\n#            print \"This may not be the functionality you want.\"\n \n\n        # skip is integer to skip every n-th value\n        # skip = 1 would not skip any values, but skip = 10 would only\n        # consider every tenth value\n        skip = 1 \n        dipole = dipole - dipole[0]\n        dipole = dipole[::skip]\n        damp = np.exp(-(self.time-self.time[0])/float(damp_const))\n        damp = damp[::skip]\n        dipole = dipole * damp\n\n        timestep = skip*(self.time[2] - self.time[1])\n        M = len(dipole)\n        N = int(np.floor(M / 2))\n\n        print \"N = \", N\n        if N > num_pts:\n            N = num_pts\n        print \"Trimmed points to: \", N\n\n        # G and d are (N-1) x (N-1)\n        # d[k] = -dipole[N+k] for k in range(1,N)\n        d = -dipole[N+1:2*N] \n\n        # Old code, which works with regular Ax=b linear solver. \n        # G[k,m] = dipole[N - m + k] for m,k in range(1,N)\n        #G = dipole[N + np.arange(1,N)[:,None] - np.arange(1,N)]\n        #b = solve(G,d,check_finite=False)\n\n        # Toeplitz linear solver using Levinson recursion\n        # Should be O(n^2), and seems to work well, but if you get strange\n        # results you may want to switch to regular linear solver which is much\n        # more stable.\n        try:\n            from scipy.linalg import toeplitz, solve_toeplitz\n        except ImportError:\n            print \"You'll need SciPy version >= 0.17.0\"\n            \n        # Instead, form G = (c,r) as toeplitz\n        #c = dipole[N:2*N-1]\n        #r = np.hstack((dipole[1],dipole[N-1:1:-1]))\n        b = solve_toeplitz((dipole[N:2*N-1],\\\n            np.hstack((dipole[1],dipole[N-1:1:-1]))),d,check_finite=False)\n      \n        # Now make b Nx1 where b0 = 1 \n        b = np.hstack((1,b)) \n\n        # b[m]*dipole[k-m] for k in range(0,N), for m in range(k) \n        a = np.dot(np.tril(toeplitz(dipole[0:N])),b)\n\n        p = np.poly1d(a)\n        q = np.poly1d(b)\n\n        # If you want energies greater than 2*27.2114 eV, you'll need to change\n        # the default frequency range to something greater.\n        self.frequency = np.arange(0,2,0.000025)\n        W = np.exp(-1j*self.frequency*timestep)\n\n        fw_re = np.real(p(W)/q(W))\n        fw_im = np.imag(p(W)/q(W))\n\n        if np.any(np.isinf(self.frequency)) or np.any(np.isnan(self.frequency)):\n            print \"Check your dT: frequency contains NaNs and/or Infs!\"\n            sys.exit(0)\n\n        if spectra.lower() == 'abs':\n#            self.fourier = \\\n#                np.abs(self.frequency**2/(2.0*np.pi)*fw_im*fw_re)\n            self.fourier = \\\n                np.abs(1.e0/(2.0*np.pi)*np.abs(p(W)/q(W))**2)\n            np.savetxt('fftdata_cm-1_pade.txt', np.transpose([self.frequency/4.55633E-6,self.fourier]))  \n        elif spectra.lower() == 'ecd':\n            self.fourier = \\\n                (17.32*fw_re)/(np.pi*kick_strength)\n        elif spectra.lower() == 'power':\n            self.fourier = \\\n                (self.frequency*(fw_re**2 + fw_im**2))/(np.pi*kick_strength)\n\n    def fourier_tx(self,dipole_direction='x',spectra='abs',damp_const=150,\n                    zero_pad=None,auto=False):\n        \"\"\"Return a set of frequencies and fourier transforms of a time\n        dependent signal, e.g. return fourier transform of the x component of\n        the time varying electric dipole\"\"\"\n        from scipy.fftpack import fft, fftfreq \n        # Choose which signal to FFT\n        if spectra.lower() == 'abs':  \n            if dipole_direction.lower() == 'x':\n                dipole = self.electricDipole.x\n#                kick_strength = self.electricField.x[0]\n            elif dipole_direction.lower() == 'y':\n                dipole = self.electricDipole.y\n#                kick_strength = self.electricField.y[0]\n            elif dipole_direction.lower() == 'z':\n                dipole = self.electricDipole.z\n#                kick_strength = self.electricField.z[0]\n            else:\n                print \"Not a valid direction for the dipole! Try: x,y,z \"\n        elif spectra.lower() == 'ecd':\n            if dipole_direction.lower() == 'x':\n                dipole = self.magneticDipole.x\n                kick_strength = self.electricField.x[0]\n            elif dipole_direction.lower() == 'y':\n                dipole = self.magneticDipole.y\n                kick_strength = self.electricField.y[0]\n            elif dipole_direction.lower() == 'z':\n                dipole = self.magneticDipole.z\n                kick_strength = self.electricField.z[0]\n            else:\n                print \"Not a valid direction for the dipole! Try: x,y,z \"\n        else: \n            print \"Not a valid spectra choice\"\n\n#        if np.isclose(kick_strength,0.0):\n#            if dipole_direction.lower() == 'x':\n#                kick_strength = max(self.electricField.x)\n#            elif dipole_direction.lower() == 'y':\n#                kick_strength = max(self.electricField.y)\n#            elif dipole_direction.lower() == 'z':\n#                kick_strength = max(self.electricField.z)\n#            if np.isclose(kick_strength,0.0):\n#                print \"Kick strength = 0. Make sure you FFT'd the correct direction\"\n#                sys.exit(0)\n#            print \"It looks like you are not perturbing the field at time = 0\"\n#            print \"so we are taking the maximum of the electric field instead\"\n\n        if auto:\n            dt = self.time[2] - self.time[1]\n            damp_const = self.time[-1]/10.0\n            line_width = (2.0/damp_const)*27.2114\n            #print \"Damp const = \", damp_const\n            if line_width > 2.0:\n                print \"Large line width: \", \"{0:.3f}\".format(line_width),\" eV\"\n                print \"Spectra not meaningful. Exiting...\"\n                sys.exit(0)\n            else:\n                print \"Line width (eV) = \", \"{0:.3f}\".format(line_width)\n             \n            dipole = dipole - dipole[0]\n            damp = np.exp(-(self.time-self.time[0])/float(damp_const))\n            dipole = dipole * damp\n\n            resolution = 0.025 #eV\n            zero_pad   = int(np.floor((2.0*np.pi*27.2114)/(resolution*dt))\\\n                - len(self.time))\n            if(zero_pad < 0.0):\n                zero_pad = 0.0\n            print \"Number zeros = \", zero_pad\n\n            zero = np.linspace(0,0,zero_pad)\n            dipole = np.hstack((dipole,zero))\n\n        else:\n            dipole = dipole - dipole[0]\n            damp = np.exp(-(self.time-self.time[0])/float(damp_const))\n            dipole = dipole * damp\n\n            if zero_pad:\n                zero = np.linspace(0,0,zero_pad)\n                dipole = np.hstack((dipole,zero))\n    \n        fw = fft(dipole)\n        fw_re = np.real(fw)\n        fw_im = np.imag(fw)\n       \n        n = len(fw_re)\n        m = int(n / 2)\n        timestep = self.time[2] - self.time[1]\n        self.frequency = fftfreq(n,d=timestep)*2.0*np.pi\n        if np.any(np.isinf(self.frequency)) or np.any(np.isnan(self.frequency)):\n            print \"Check your dT: frequency contains NaNs and/or Infs!\"\n            sys.exit(0)\n\n        if spectra.lower() == 'abs':\n            self.fourier = \\\n                np.abs(self.frequency**2/(2.0*np.pi)*np.abs(fw)**2)\n            np.savetxt('fftdata_cm-1_fourier.txt', np.transpose([self.frequency/4.55633E-6,self.fourier]))  \n\n\n        elif spectra.lower() == 'ecd':\n            self.fourier = \\\n                (17.32*fw_re)/(np.pi*kick_strength)\n\n        # Grab positive values only\n        self.frequency = self.frequency[1:m]\n        self.fourier   = self.fourier[1:m]\n\n    def test(self):\n        self.check_energy()\n        self.check_iops()\n        pass\n\n    def check_energy(self):\n        dE = abs(max(self.energy) - min(self.energy)) \n        t_maxE = self.time[np.argmax(self.energy)]\n        t_minE = self.time[np.argmin(self.energy)]\n        print \"Energy conserved to: \", \"{0:.2e}\".format(dE), \" au\"\n        print \"Max energy at time:  \", t_maxE, \" au\"\n        print \"Min energy at time:  \", t_minE, \" au\"\n\n    def check_field(self,tol=1e-6):\n        if self.envelope['Field']:\n            print \"External field:      \", self.envelope['Envelope']\n            print \"Ex field matches:    \", np.allclose(self.electricField.x,\n                self.expected_field('Ex'),atol=tol)\n            print \"Ey field matches:    \", np.allclose(self.electricField.y,\n                self.expected_field('Ey'),atol=tol)\n            print \"Ez field matches:    \", np.allclose(self.electricField.z,\n                self.expected_field('Ez'),atol=tol)\n           # print \"Bx field matches: \", np.allclose(self.magneticField.x,\n           #     self.expected_field('Bx'),atol=tol)\n           # print \"By field matches: \", np.allclose(self.magneticField.y,\n           #     self.expected_field('By'),atol=tol)\n           # print \"Bz field matches: \", np.allclose(self.magneticField.z,\n           #     self.expected_field('Bz'),atol=tol)\n        else:\n            print \"No external field applied\"\n\n    def check_iops(self):\n        \"\"\" Check internal consistency of some set iops and values printed out\n        to the logfile, as well as some derived quantities\"\"\"\n        # Check the step size\n        if self.step_size == (self.time[2] - self.time[1]):\n            if ((self.step_size == 0.05) \\\n                and (int(self.iops['134'][0]) == 0)) or\\\n               (self.step_size == float(self.iops['134'][0])*0.00001):\n                print \"Time step             [OK]: \", self.step_size, \" au\"\n        else:\n            print \"Inconsistent time step: \"\n            print \"  IOps:                  \", self.iops['134'][1]\n            print \"  logfile header showing \", self.step_size\n            print \"  logfile showing        \", self.time[2] - self.time[1]\n        # Check the total propagation steps\n        if ((self.total_steps == 15) \\\n           and (int(self.iops['132'][0]) == 0)) or\\\n            (self.total_steps == abs(int(self.iops['132'][0]))):\n                print \"Number MMUT steps     [OK]: \", self.total_steps, \" steps\"\n        else:\n            print \"Inconsistent propagation time: \"\n            print \"  IOps:                  \", self.iops['132'][1]\n            print \"  logfile header showing \", self.total_steps\n        # Check if external field is indeed On or OFF\n        if ((self.envelope['Field'] == False) and\\\n           (int(self.iops['138'][0]) == 0)):\n            print \"Field off:            [OK]\"\n        elif (self.envelope and int(self.iops['138'][0]) != 0):\n            print \"Field on:             [OK]\"\n            self.check_field()\n        else:\n            print \"Inconsistency in field:\"\n            print \"IOps:                     \", self.iops['138'] \n        \n        # Check Orthonormalization\n        if ((self.orthonorm == self.iops['136'][1])):\n            print \"Orthonormality        [OK]:\", self.orthonorm\n        else:\n            print \"Inconsistency in orthonormality\"\n            print \"IOps:                      \", self.iops['136'][1]\n            print \"logfile showing:           \", self.iops['136'][1]\n\n    def expected_field(self,component):\n        Time  = self.time\n        TOn   = self.envelope['TOn']\n        TOff  = self.envelope['TOff']\n        try:\n            Omega = self.envelope['Frequency']\n        except KeyError:\n            Omega = 0.0 \n        try:\n            Phase = self.envelope['Phase']\n        except KeyError:\n            Phase = 0.0\n        OmegT = Omega*(Time - TOn) + Phase\n        field = np.zeros_like(self.time)\n        if self.envelope['Envelope'] == 'Constant':\n            # Step function, depending on how TOn and TOff are defined\n            idx = np.where((Time >= TOn) & (Time < TOff))\n            # in GDV OmegT begins at TOn as well\n            field[idx] = self.envelope[component]*np.cos(OmegT[idx])\n        elif self.envelope['Envelope'] == 'Linear':\n            TMax = (2.0*np.pi)/Omega\n            # Linearly ramp off to zero \n            idx = np.where((Time >= TOn) & (Time <= TOff) & \\\n                (Time > TOff-TMax))\n            field[idx] = self.envelope[component]*\\\n                         ((TOff-Time[idx])/TMax)*np.cos(OmegT[idx])\n            # Constant envelope \n            idx = np.where((Time >= TOn) & (Time <= TOff) & \\\n                (Time > TOn+TMax) & (Time <= TOff-TMax))\n            field[idx] = self.envelope[component]*np.cos(OmegT[idx])\n            # Linearly ramp up to maximum in first cycle\n            idx = np.where((Time >= TOn) & (Time <= TOff) & \\\n                (Time <= TOn+TMax))\n            field[idx] = self.envelope[component]*\\\n                         ((Time[idx]-TOn)/TMax)*np.cos(OmegT[idx])\n        elif self.envelope['Envelope'] == 'Gaussian':\n            idx = np.where((Time >= TOn) & (Time < TOff))\n            #FIXME: Sigma is hard-coded for testing...need to print it in the \n            # output and then search for it during parsing.\n            Sigma = 0.01\n            TCntr = np.sqrt(np.log(1000.0))/Sigma\n            field[idx] = self.envelope[component]*\\\n                         np.cos(OmegT[idx])*\\\n                         np.exp(-(Sigma*(Time[idx]-TCntr))**2)\n        else:\n            print \"Not a valid field!\"\n            sys.exit(0) \n        return field\n\n \nif __name__ == '__main__':\n    a = RealTime('test')\n    import matplotlib.pyplot as plt \n    plt.plot(a.time,a.electricDipole.z)\n    plt.savefig('dipole.pdf')\n    #plt.show()\n    \n            \n\n", "meta": {"hexsha": "5e3e2591fa683b7f13d76fa63c959282be87de87", "size": 19719, "ext": "py", "lang": "Python", "max_stars_repo_path": "realtime.py", "max_stars_repo_name": "dblinger/BOMD_vibspec", "max_stars_repo_head_hexsha": "3bf10946c4a3f3eba0ca7696b4c7201a3b9e0ed1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "realtime.py", "max_issues_repo_name": "dblinger/BOMD_vibspec", "max_issues_repo_head_hexsha": "3bf10946c4a3f3eba0ca7696b4c7201a3b9e0ed1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "realtime.py", "max_forks_repo_name": "dblinger/BOMD_vibspec", "max_forks_repo_head_hexsha": "3bf10946c4a3f3eba0ca7696b4c7201a3b9e0ed1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4064516129, "max_line_length": 108, "alphanum_fraction": 0.5219838734, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3311197396289915, "lm_q1q2_score": 0.17460490992350727}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCommon Colour Models Utilities\n==============================\n\nDefines various colour models common utilities.\n\nSee Also\n--------\n`RGB Colourspaces IPython Notebook\n<http://nbviewer.ipython.org/github/colour-science/colour-ipython/blob/master/notebooks/models/rgb.ipynb>`_  # noqa\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\n\nfrom colour.models import RGB_COLOURSPACES, XYZ_to_RGB\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013 - 2014 - Colour Developers'\n__license__ = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-science@googlegroups.com'\n__status__ = 'Production'\n\n__all__ = ['XYZ_to_sRGB']\n\n\ndef XYZ_to_sRGB(XYZ,\n                illuminant=RGB_COLOURSPACES.get('sRGB').whitepoint,\n                chromatic_adaptation_method='CAT02',\n                transfer_function=True):\n    \"\"\"\n    Converts from *CIE XYZ* colourspace to *sRGB* colourspace.\n\n    Parameters\n    ----------\n    XYZ : array_like, (3,)\n        *CIE XYZ* colourspace matrix.\n    illuminant : array_like, optional\n        Source illuminant chromaticity coordinates.\n    chromatic_adaptation_method : unicode, optional\n        ('XYZ Scaling', 'Bradford', 'Von Kries', 'Fairchild', 'CAT02')\n        *Chromatic adaptation* method.\n    transfer_function : bool, optional\n        Apply *sRGB* *transfer function*.\n\n    Returns\n    -------\n    ndarray, (3,)\n        *sRGB* colour matrix.\n\n    Notes\n    -----\n    -   Input *CIE XYZ* colourspace matrix is in domain [0, 1].\n\n    Examples\n    --------\n    >>> XYZ = np.array([0.1180583421, 0.1034, 0.0515089229])\n    >>> XYZ_to_sRGB(XYZ)  # doctest: +ELLIPSIS\n    array([ 0.4822488...,  0.3165197...,  0.2207051...])\n    \"\"\"\n\n    sRGB = RGB_COLOURSPACES.get('sRGB')\n    return XYZ_to_RGB(XYZ,\n                      illuminant,\n                      sRGB.whitepoint,\n                      sRGB.to_RGB,\n                      chromatic_adaptation_method,\n                      sRGB.transfer_function if transfer_function else None)\n", "meta": {"hexsha": "2f5dc1f23ba5ebf1e3e1aad4d8f914c455b0270d", "size": 2122, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/models/common.py", "max_stars_repo_name": "canavandl/colour", "max_stars_repo_head_hexsha": "a453cd37b6135a9092d5ea5b2aafb8d19134bdff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-27T11:32:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-27T11:32:48.000Z", "max_issues_repo_path": "colour/models/common.py", "max_issues_repo_name": "canavandl/colour", "max_issues_repo_head_hexsha": "a453cd37b6135a9092d5ea5b2aafb8d19134bdff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/models/common.py", "max_forks_repo_name": "canavandl/colour", "max_forks_repo_head_hexsha": "a453cd37b6135a9092d5ea5b2aafb8d19134bdff", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6756756757, "max_line_length": 115, "alphanum_fraction": 0.6286522149, "include": true, "reason": "import numpy", "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.30404168757891037, "lm_q1q2_score": 0.1744221511294428}}
{"text": "\"\"\"\nAndrin Jenal, 2017\nETH Zurich\n\"\"\"\n\n\nimport tensorflow as tf\nimport numpy as np\n\nimport nn_ops\nfrom vgg import vgg\n\n\nclass VAE_DCGAN:\n\n    def __init__(self, image_size, channels, z_size=256, learning_rate_enc=5e-4, learning_rate_dis=5e-4, learning_rate_dec=5e-4):\n        # summaries\n        self.merged_summary_op = None\n        self.summary_writer = None\n\n        self.image_size = image_size\n        self.image_channels = channels\n        self.z_size = z_size\n\n        self.d_real = 0.0\n        self.d_fake = 0.0\n\n        self.learning_rate_enc = learning_rate_enc\n        self.learning_rate_gen = learning_rate_dec\n        self.learning_rate_dis = learning_rate_dis\n\n        self.eps = 1e-8\n\n        self.lr_discriminator = tf.placeholder(tf.float32, shape=[])\n        self.lr_generator = tf.placeholder(tf.float32, shape=[])\n        self.lr_encoder = tf.placeholder(tf.float32, shape=[])\n\n        self.x = tf.placeholder(tf.float32, shape=(None, self.image_size, self.image_size, self.image_channels))\n        self.batch_size = tf.shape(self.x)[0]\n\n        self.z_p = tf.random_normal((self.batch_size, self.z_size), mean=0, stddev=1)\n        self.eps = tf.random_normal((self.batch_size, self.z_size), mean=0, stddev=1)\n\n        # preload vgg network for loss backpropagation\n        self.vgg_weights, self.vgg_mean_pixel = vgg.load_net(\"datasets/imagenet-vgg-verydeep-19.mat\")\n\n        with tf.variable_scope(\"vae_dcgan_model\"):\n            tf.summary.histogram(\"x_values\", self.x)\n\n            with tf.variable_scope(\"encoder\"):\n                self.z_x_mean, self.z_x_log_sigma = self._encoder(self.x)\n\n            with tf.variable_scope(\"generator\"):\n                self.z_x = tf.add(self.z_x_mean, tf.multiply(tf.exp(self.z_x_log_sigma), self.eps))\n                tf.summary.histogram(\"z\", self.z_x)\n                tf.summary.histogram(\"z_mu\", self.z_x_mean)\n                tf.summary.histogram(\"z_sigma\", tf.exp(self.z_x_log_sigma))\n\n                self.x_tilde = self._generator(self.z_x)\n                tf.summary.histogram(\"x_tilde_values\", self.x_tilde)\n\n            with tf.variable_scope(\"discriminator\"):\n                self.dis_x_tilde_p, self.l_x_tilde = self._discriminator(self.x_tilde)\n                tf.summary.histogram(\"predicted_x_tilde_values\", self.dis_x_tilde_p)\n\n            with tf.variable_scope(\"generator\", reuse=True):\n                self.x_p = self._generator(self.z_p)\n                tf.summary.histogram(\"x_p_values\", self.x_tilde)\n\n            with tf.variable_scope(\"discriminator\", reuse=True):\n                self.dis_x, self.l_x = self._discriminator(self.x)\n                tf.summary.histogram(\"predicted_x_values\", self.dis_x)\n\n            with tf.variable_scope(\"discriminator\", reuse=True):\n                self.dis_x_p, _ = self._discriminator(self.x_p)\n                tf.summary.histogram(\"predicted_x_p_values\", self.dis_x_p)\n\n            with tf.variable_scope(\"losses\"):\n                self.prior = self._kl_divergence()\n\n                self.discriminator_loss = self._wasserstein_gradient_penalty_discriminator_loss()\n                self.generator_loss = self._wasserstein_gradient_penalty_generator_loss()\n                self.lth_layer_loss = self._lth_layer_loss()\n                self.mse_loss = self._pixel_loss()\n                #self.feature_loss = self._vgg_feature_loss()\n\n                self.dissimilarity_loss = 0.5 * self.lth_layer_loss + 0.5 * self.mse_loss\n\n                self.loss_encoder = self.prior + self.dissimilarity_loss\n                self.loss_generator = self.dissimilarity_loss + self.generator_loss\n                self.loss_discriminator = self.discriminator_loss\n\n                train_variables = tf.trainable_variables()\n                self.encoder_vars = [var for var in train_variables if \"encoder\" in var.name]\n                self.discriminator_vars = [var for var in train_variables if \"discriminator\" in var.name]\n                self.generator_vars = [var for var in train_variables if \"generator\" in var.name]\n\n                with tf.name_scope(\"encoder_optimizer\"):\n                    self.e_optim = self._adam_optimizer(self.loss_encoder, self.encoder_vars, self.lr_encoder)\n\n                with tf.name_scope(\"discriminator_optimizer\"):\n                    self.d_optim = self._rms_prop_optimizer(self.loss_discriminator, self.discriminator_vars, self.lr_discriminator)\n\n                with tf.name_scope(\"generator_optimizer\"):\n                    self.g_optim = self._rms_prop_optimizer(self.loss_generator, self.generator_vars, self.lr_generator)\n\n        # initialize saver\n        self.saver = tf.train.Saver([v for v in tf.global_variables() if \"vae_dcgan_model\" in v.name])\n\n        self._check_tensors()\n\n    def _adam_optimizer(self, loss, loss_params, learning_rate, beta1=0.5):\n        optimizer = tf.train.AdamOptimizer(learning_rate, beta1=beta1)\n        grads = optimizer.compute_gradients(loss, var_list=loss_params)\n        grads = nn_ops.clip_gradient_norms(grads, 50)\n        train_optimizer = optimizer.apply_gradients(grads)\n        grad_norms = self._l2_norms(grads)\n        tf.summary.histogram(\"gradient_l2_norms\", grad_norms)\n        return train_optimizer\n\n    def _rms_prop_optimizer(self, loss, loss_params, learning_rate):\n        optimizer = tf.train.RMSPropOptimizer(learning_rate)\n        grads = optimizer.compute_gradients(loss, var_list=loss_params)\n        grads = nn_ops.clip_gradient_norms(grads, 50)\n        train_optimizer = optimizer.apply_gradients(grads)\n        grad_norms = self._l2_norms(grads)\n        tf.summary.histogram(\"gradient_l2_norms\", grad_norms)\n        return train_optimizer\n\n    def _l2_norms(self, gradients):\n        return [tf.nn.l2_loss(g) for g, v in gradients if g is not None]\n\n    def _encoder2(self, x):\n        x = tf.reshape(x, [self.batch_size, self.image_size * self.image_size * self.image_channels])\n        z_mean = nn_ops.linear_contrib(x, self.z_size, activation_fn=None, scope=\"fully_connected\")\n        z_log_sigma_sq = nn_ops.linear_contrib(x, self.z_size, activation_fn=None, scope=\"fully_connected\")\n        return z_mean, z_log_sigma_sq\n\n    def _encoder(self, x):\n        x = tf.reshape(x, [self.batch_size, self.image_size, self.image_size, self.image_channels])\n        conv1 = nn_ops.conv2d_contrib(x, 64, kernel=5, stride=2, activation_fn=nn_ops.relu_batch_norm, scope=\"conv1\")\n        conv2 = nn_ops.conv2d_contrib(conv1, 128, kernel=3, stride=2, activation_fn=nn_ops.relu_batch_norm, scope=\"conv2\")\n        conv3 = nn_ops.conv2d_contrib(conv2, 256, kernel=3, stride=2, padding=\"VALID\", activation_fn=nn_ops.relu_batch_norm, scope=\"conv3\")\n        flatten = nn_ops.flatten_contrib(conv3)\n        z_mean = nn_ops.linear_contrib(flatten, self.z_size, activation_fn=nn_ops.relu_batch_norm, scope=\"fully_connected\")\n        z_log_sigma = nn_ops.linear_contrib(flatten, self.z_size, activation_fn=nn_ops.relu_batch_norm, scope=\"fully_connected\")\n        return z_mean, z_log_sigma\n\n    def _discriminator(self, x):\n        x = tf.reshape(x, [self.batch_size, self.image_size, self.image_size, self.image_channels])\n        conv1 = nn_ops.conv2d_contrib(x, 64, kernel=5, stride=2, activation_fn=nn_ops.leaky_relu_batch_norm, scope=\"conv1\")\n        conv2 = nn_ops.conv2d_contrib(conv1, 128, kernel=3, stride=2, activation_fn=nn_ops.leaky_relu_batch_norm, scope=\"conv2\")\n        conv3 = nn_ops.conv2d_contrib(conv2, 256, kernel=3, stride=2, activation_fn=nn_ops.leaky_relu_batch_norm, scope=\"conv3\")\n        conv4 = nn_ops.conv2d_contrib(conv3, 256, kernel=3, stride=2, padding=\"VALID\", activation_fn=nn_ops.leaky_relu_batch_norm, scope=\"conv4\")\n        conv4 = nn_ops.flatten_contrib(conv4)\n        fc = nn_ops.linear_contrib(conv4, 512, activation_fn=nn_ops.leaky_relu_batch_norm, scope=\"fully_connected\")\n        predicted = nn_ops.linear_contrib(fc, 1, activation_fn=tf.nn.sigmoid, scope=\"prediction\")\n        net = {\"conv1\": conv1, \"conv2\": conv2, \"conv3\": conv3, \"conv4\": conv4, \"fc\": fc}\n        return predicted, [net[\"conv1\"], net[\"conv2\"], net[\"fc\"]]\n\n    def _generator(self, z):\n        fc = nn_ops.linear_contrib(z, 4 * 4 * 512, activation_fn=None)\n        z = tf.reshape(fc, shape=(tf.shape(z)[0], 4, 4, 512))\n        deconv1 = nn_ops.conv2d_transpose_contrib(z, 512, kernel=4, stride=2, activation_fn=nn_ops.relu_batch_norm, scope=\"upconv1\")\n        deconv2 = nn_ops.conv2d_transpose_contrib(deconv1, 256, kernel=5, stride=2, activation_fn=nn_ops.relu_batch_norm, scope=\"upconv2\")\n        deconv3 = nn_ops.conv2d_transpose_contrib(deconv2, 128, kernel=5, stride=2, activation_fn=nn_ops.relu_batch_norm, scope=\"upconv3\")\n        deconv4 = nn_ops.conv2d_transpose_contrib(deconv3, self.image_channels, kernel=5, stride=2, activation_fn=None, scope=\"upconv4\")\n        return tf.nn.tanh(deconv4)\n\n    def _discriminator_loss(self, eps=1e-8):\n        with tf.name_scope(\"logits_discriminator_loss\"):\n            dis_loss = tf.reduce_mean(-1.0 * tf.log(tf.clip_by_value(self.dis_x, eps, 1.0)) -\n                                      tf.log(tf.clip_by_value(1.0 - self.dis_x_p, eps, 1.0)) -\n                                      tf.log(tf.clip_by_value(1.0 - self.dis_x_tilde_p, eps, 1.0)))\n            tf.summary.scalar(\"discriminator_loss_mean\", dis_loss)\n            return dis_loss\n\n    def _generator_loss(self, eps=1e-8):\n        with tf.name_scope(\"logits_generator_loss\"):\n            gen_loss = tf.reduce_mean(-1.0 * tf.log(tf.clip_by_value(self.dis_x_p, eps, 1.0)) -\n                                      tf.log(tf.clip_by_value(self.dis_x_tilde_p, eps, 1.0)))\n            tf.summary.scalar(\"generator_loss_mean\", gen_loss)\n            return gen_loss\n\n    def _kl_divergence(self):\n        with tf.name_scope(\"kl_divergence_loss\"):\n            KL = tf.reduce_sum((-self.z_x_log_sigma + 0.5 * (tf.exp(2.0 * self.z_x_log_sigma) + tf.square(self.z_x_mean)) - 0.5), axis=-1)\n            KL_mean = tf.reduce_mean(KL)\n            tf.summary.histogram(\"KL_divergence\", KL)\n            tf.summary.scalar(\"kl_divergence_mean\", KL_mean)\n            return KL_mean\n\n    def _pixel_loss(self):\n        with tf.name_scope(\"pixel_loss\"):\n            pixel_loss = tf.reduce_mean(tf.nn.l2_loss(self.x - self.x_tilde) / np.prod(self.x.get_shape().as_list()[1:]))\n            pixel_loss_weighted = 1.0 * pixel_loss\n            tf.summary.scalar(\"pixel_loss_mean\", pixel_loss_weighted)\n            return pixel_loss_weighted\n\n    def _lth_layer_loss(self):\n        with tf.name_scope(\"lth_layer_loss\"):\n            lth_layer_loss = 0\n            for l1, l2 in zip(self.l_x, self.l_x_tilde):\n                lth_layer_loss += tf.nn.l2_loss((l1 - l2)) / (self.image_size * self.image_size * self.image_channels)\n            lth_layer_loss *= 1.0 / len(self.l_x)\n            tf.summary.scalar(\"lth_layer_loss_mean\", lth_layer_loss)\n            return lth_layer_loss\n\n    def _discriminator_binary_cross_entropy_loss(self):\n        with tf.name_scope(\"cross_entropy_discriminator_loss\"):\n            d_loss_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.dis_x, labels=tf.ones_like(self.dis_x)))\n            d_loss_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.dis_x_p, labels=tf.zeros_like(self.dis_x_p)))\n            dis_loss = d_loss_real + d_loss_fake\n            tf.summary.scalar(\"discriminator_loss_mean\", dis_loss)\n            return dis_loss\n\n    def _generator_binary_cross_entropy_loss(self):\n        with tf.name_scope(\"cross_entropy_generator_loss\"):\n            gen_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.dis_x_p, labels=tf.ones_like(self.dis_x_p)))\n            tf.summary.scalar(\"generator_loss_mean\", gen_loss)\n            return gen_loss\n\n    def _wasserstein_discriminator_loss(self):\n        \"\"\" https://github.com/igul222/improved_wgan_training/blob/master/gan_mnist.py \"\"\"\n        with tf.name_scope(\"wasserstein_discriminator_loss\"):\n            dis_loss = -tf.reduce_mean(self.dis_x) + tf.reduce_mean(self.dis_x_p) + tf.reduce_mean(self.dis_x_tilde_p)\n            tf.summary.scalar(\"discriminator_loss_mean\", dis_loss)\n            return dis_loss\n\n    def _wasserstein_generator_loss(self):\n        \"\"\" https://github.com/igul222/improved_wgan_training/blob/master/gan_mnist.py \"\"\"\n        with tf.name_scope(\"wasserstein_generator_loss\"):\n            gen_loss = -tf.reduce_mean(self.dis_x_p) - tf.reduce_mean(self.dis_x_tilde_p)\n            tf.summary.scalar(\"generator_loss_mean\", gen_loss)\n            return gen_loss\n\n    def _wasserstein_gradient_penalty_discriminator_loss(self):\n        \"\"\" https://github.com/igul222/improved_wgan_training/blob/master/gan_mnist.py \"\"\"\n        with tf.name_scope(\"wasserstein_gradient_penalty_discriminator_loss\"):\n            dis_loss = -tf.reduce_mean(self.dis_x) + tf.reduce_mean(self.dis_x_p) + tf.reduce_mean(self.dis_x_tilde_p)\n            x_p = tf.reshape(self.x_p, [self.batch_size, -1])\n            x = tf.reshape(self.x, [self.batch_size, -1])\n            differences = x_p - x\n            interpolates = x + (tf.random_uniform([self.batch_size, 1], minval=0, maxval=1) * differences)\n            dis_interpolates, _ = self._discriminator(interpolates)\n            gradients = tf.gradients(dis_interpolates, [interpolates])[0]\n            slopes = tf.sqrt(tf.reduce_sum(tf.square(gradients), reduction_indices=[1]))\n            gradient_penalty = tf.reduce_mean((slopes - 1.) ** 2)\n            dis_loss += 10 * gradient_penalty\n            tf.summary.scalar(\"discriminator_loss_mean\", dis_loss)\n            return dis_loss\n\n    def _wasserstein_gradient_penalty_generator_loss(self):\n        \"\"\" https://github.com/igul222/improved_wgan_training/blob/master/gan_mnist.py \"\"\"\n        with tf.name_scope(\"wasserstein_gradient_penalty_generator_loss\"):\n            gen_loss = -tf.reduce_mean(self.dis_x_p) - tf.reduce_mean(self.dis_x_tilde_p)\n            tf.summary.scalar(\"generator_loss_mean\", gen_loss)\n            return gen_loss\n\n    def _vgg_feature_loss(self):\n        with tf.name_scope(\"feature_loss_vgg\"):\n            feature_layers = [\"relu3_3\"]\n            # [0.22591736, 0.77408264]\n            # [0.09079630, 0.33333333, 0.57587037]\n            # [0.04912966, 0.16162175, 0.33837825, 0.45087034]\n            # [0.03139669, 0.09036695, 0.20000000, 0.30963305, 0.36860331]\n            # [0.02222448, 0.05677295, 0.12367752, 0.20965582, 0.27656038, 0.31110886]\n            # [0.01683352, 0.03891270, 0.08120526, 0.14285714, 0.20450902, 0.24680159, 0.26888077]\n            # [0.01336953, 0.02844961, 0.05647934, 0.09969787, 0.15030213, 0.19352066, 0.22155039, 0.23663047]\n            feature_weights = [1.0]\n            feature_losses = []\n            for ith, layer in enumerate(feature_layers):\n                x_weights, _ = self._vgg_layer_weights(self.x, layer, self.batch_size, self.image_size, self.image_size, self.vgg_weights, self.vgg_mean_pixel)\n                x_tilde_weights, x_tilde_size = self._vgg_layer_weights(self.x_tilde, layer, self.batch_size, self.image_size, self.image_size, self.vgg_weights, self.vgg_mean_pixel)\n                feature_losses.append(feature_weights[ith] * (tf.nn.l2_loss(x_weights - x_tilde_weights) / x_tilde_size))\n            feature_loss = tf.reduce_mean(tf.convert_to_tensor(feature_losses))\n            feature_loss_weighted = feature_loss\n            tf.summary.scalar(\"feature_loss_mean\", feature_loss_weighted)\n            return feature_loss_weighted\n\n    def _vgg_layer_weights(self, input_images, layer_name, batch_size, image_height, image_width, vgg_weights, vgg_mean_pixel, pooling=\"avg\"):\n        if self.image_channels == 3:\n            input_images = tf.reshape(input_images, shape=[batch_size, image_height, image_width, self.image_channels])\n        else:\n            input_images = tf.reshape(input_images, shape=[batch_size, image_height, image_width])\n            input_images = tf.stack([input_images, input_images, input_images], axis=-1)\n        input_images_mean = vgg.preprocess(input_images, vgg_mean_pixel)\n        net_forward_images = vgg.net_preloaded(vgg_weights, input_images_mean, pooling)\n        weights_size = np.prod(net_forward_images[layer_name].get_shape().as_list()[1:])\n        return net_forward_images[layer_name], weights_size\n\n    def _check_tensors(self):\n        if tf.trainable_variables():\n            for v in tf.trainable_variables():\n                print(\"%s : %s\" % (v.name, v.get_shape()))\n\n    def _sigmoid(self, x, shift, mult):\n        \"\"\"\n        Using this sigmoid to discourage one network overpowering the other\n        \"\"\"\n        return 1 / (1 + np.exp(-(x + shift) * mult))\n\n    def update_params(self, sess, input_tensor):\n        e_current_lr = self.learning_rate_enc# * self._sigmoid(np.mean(self.d_real), -.5, 15)\n        g_current_lr = self.learning_rate_gen# * self._sigmoid(np.mean(self.d_real), -.5, 15)\n        d_current_lr = self.learning_rate_dis# * self._sigmoid(np.mean(self.d_fake), -.5, 15)\n\n        _, _, _ = sess.run([self.d_optim, self.e_optim, self.g_optim], feed_dict={self.x: input_tensor,\n                                                                                  self.lr_encoder: e_current_lr,\n                                                                                  self.lr_generator: g_current_lr,\n                                                                                  self.lr_discriminator: d_current_lr})\n\n        kl, d_loss, g_loss, lth_layer, d_real, d_fake = sess.run([self.prior, self.discriminator_loss, self.generator_loss, self.dissimilarity_loss, self.dis_x, self.dis_x_p], feed_dict={self.x: input_tensor})\n\n        self.d_real = d_real\n        self.d_fake = d_fake\n\n        return kl, d_loss, g_loss, lth_layer, e_current_lr, g_current_lr, d_current_lr\n\n    def generate_samples(self, sess, num_samples):\n        z = np.random.normal(size=(num_samples, self.z_size))\n        samples = sess.run(self.x_p, feed_dict={self.z_p: z})\n        return np.array(samples)\n\n    def initialize_summaries(self, sess, summary_directory):\n        self.merged_summary_op = tf.summary.merge_all()\n        self.summary_writer = tf.summary.FileWriter(summary_directory, sess.graph)\n\n    def update_summaries(self, sess, x, epoch):\n        if self.merged_summary_op is not None:\n            summary = sess.run(self.merged_summary_op, feed_dict={self.x: x})\n            self.summary_writer.add_summary(summary, global_step=epoch)\n            print(\"updated summaries...\")\n\n    def restore_model(self, sess, checkpoint_file):\n        self.saver.restore(sess, checkpoint_file)\n        print(\"model restored from:\", checkpoint_file)\n", "meta": {"hexsha": "e72bd8a8cd9cdc8a4f30636cd64c5e095d4f708d", "size": 18659, "ext": "py", "lang": "Python", "max_stars_repo_path": "vae_dcgan.py", "max_stars_repo_name": "TheRiddance/dcgan", "max_stars_repo_head_hexsha": "c414696a38a48c3ff471e6ef56f04f9aef52e5c5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vae_dcgan.py", "max_issues_repo_name": "TheRiddance/dcgan", "max_issues_repo_head_hexsha": "c414696a38a48c3ff471e6ef56f04f9aef52e5c5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vae_dcgan.py", "max_forks_repo_name": "TheRiddance/dcgan", "max_forks_repo_head_hexsha": "c414696a38a48c3ff471e6ef56f04f9aef52e5c5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.2041420118, "max_line_length": 209, "alphanum_fraction": 0.6642370974, "include": true, "reason": "import numpy", "num_tokens": 4588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.17437139087515333}}
{"text": "import numpy as np\nfrom scipy import optimize\nfrom .phase_correlation import get_ambient_flow\nfrom .objects import get_obj_extent\n\nLARGE_NUM = 1000\n\n\ndef euclidean_dist(vec1, vec2):\n    \"\"\" Computes euclidean distance. \"\"\"\n    vec1 = np.array(vec1)\n    vec2 = np.array(vec2)\n    dist = np.sqrt(sum((vec1-vec2)**2))\n    return dist\n\n\ndef get_sizeChange(size1, size2):\n    \"\"\" Returns change in size of an echo as the ratio of the larger size to\n    the smaller, minus 1. \"\"\"\n    if (size1 < 5) and (size2 < 5):\n        return 0\n    elif size1 >= size2:\n        return size1/size2 - 1\n    else:\n        return size2/size1 - 1\n\n\ndef find_objects(search_box, image2):\n    \"\"\" Identifies objects found in the search region. \"\"\"\n    if not search_box['valid']:\n        obj_found = np.array(-1)\n    else:\n        search_area = image2[search_box['x1']:search_box['x2'],\n                             search_box['y1']:search_box['y2']]\n        obj_found = np.unique(search_area)\n    return obj_found\n\n\ndef shifts_disagree(shift1, shift2, record, thresh):\n    \"\"\" Returns True if shift disparity greater than MAX_SHIFT_DISP\n    parameter. \"\"\"\n    shift1 = shift1*record.grid_size[1:]\n    shift2 = shift2*record.grid_size[1:]\n    shift_disparity = euclidean_dist(shift1, shift2)\n    return shift_disparity/record.interval.seconds > thresh\n\n\ndef clip_shift(shift, record, params):\n    \"\"\" Clips shift according to MAX_FLOW_MAG paramter. \"\"\"\n    shift_meters = shift * record.grid_size[1:]\n    shift_mag = np.linalg.norm(shift_meters)\n    velocity = shift_mag / record.interval.seconds\n    if velocity > params['MAX_FLOW_MAG'] and shift_mag != 0:\n        unit = shift_meters / shift_mag\n        clipped = unit * params['MAX_FLOW_MAG'] * record.interval.seconds\n        clipped_pix = clipped/record.grid_size[1:]\n        return clipped_pix\n    else:\n        return shift\n\n\ndef correct_shift(\n        local_shift, current_objects, obj_id1, global_shift, record,\n        params):\n    \"\"\" Takes in flow vector based on local phase correlation (see\n    get_std_flow) and compares it to the last headings of the object and\n    the global_shift vector for that timestep. Corrects accordingly.\n    Note: At the time of this function call, current_objects has not yet been\n    updated for the current frame and frame_new, so the id2s in current_objects\n    correspond to the objects in the current frame. \"\"\"\n    global_shift = clip_shift(global_shift, record, params)\n\n    # Note last_heads is defined using object centers! These jump around a lot\n    # when tracking large objects and should therefore probably not be used\n    # when tracking MCS systems!\n\n    if current_objects is None:\n        last_heads = None\n    else:\n        obj_index = current_objects['id2'] == obj_id1\n        last_heads = current_objects['last_heads'][obj_index].flatten()\n        last_heads = np.round(last_heads * record.interval_ratio, 2)\n        if len(last_heads) == 0:\n            last_heads = None\n\n    if last_heads is None:\n        if shifts_disagree(\n                local_shift, global_shift, record, params['MAX_SHIFT_DISP']):\n            case = 0\n            corrected_shift = global_shift\n        else:\n            case = 1\n            corrected_shift = (local_shift + global_shift)/2\n\n    elif shifts_disagree(\n            local_shift, last_heads, record, params['MAX_SHIFT_DISP']):\n        if shifts_disagree(\n                local_shift, global_shift, record, params['MAX_SHIFT_DISP']):\n            case = 2\n            corrected_shift = last_heads\n        else:\n            case = 3\n            corrected_shift = local_shift\n\n    else:\n        case = 4\n        # corrected_shift = (local_shift + last_heads)/2\n        if shifts_disagree(\n                local_shift, global_shift,\n                record, params['MAX_SHIFT_DISP_ALT']):\n            corrected_shift = global_shift\n        else:\n            corrected_shift = local_shift\n\n    corrected_shift = np.round(corrected_shift, 2)\n\n    record.count_case(case)\n    record.record_shift(corrected_shift, global_shift,\n                        last_heads, local_shift, case)\n    return corrected_shift\n\n\ndef predict_search_extent(obj1_extent, shift, params, grid_size):\n    \"\"\" Predicts search extent/region for the object in image2 given\n    the image shift. \"\"\"\n    shifted_center = obj1_extent['obj_center'] + shift\n    search_radius_r = params['SEARCH_MARGIN'] / grid_size[1]\n    search_radius_c = params['SEARCH_MARGIN'] / grid_size[2]\n    x1 = shifted_center[0] - search_radius_r\n    x2 = shifted_center[0] + search_radius_r + 1\n    y1 = shifted_center[1] - search_radius_c\n    y2 = shifted_center[1] + search_radius_c + 1\n    x1 = np.int32(x1)\n    x2 = np.int32(x2)\n    y1 = np.int32(y1)\n    y2 = np.int32(y2)\n    return {'x1': x1, 'x2': x2, 'y1': y1, 'y2': y2,\n            'center_pred': shifted_center, 'valid': True}\n\n\ndef check_search_box(search_box, img_dims):\n    \"\"\" Checks if search_box is within the boundaries of the frame. Clips to\n    edges of frame if out of bounds. Marks as invalid if too small. \"\"\"\n    if search_box['x1'] < 0:\n        search_box['x1'] = 0\n    if search_box['y1'] < 0:\n        search_box['y1'] = 0\n    if search_box['x2'] > img_dims[0]:\n        search_box['x2'] = img_dims[0]\n    if search_box['y2'] > img_dims[1]:\n        search_box['y2'] = img_dims[1]\n    if (\n            (search_box['x2'] - search_box['x1'] < 5)\n            or (search_box['y2'] - search_box['y1'] < 5)):\n        search_box['valid'] = False\n    return search_box\n\n\ndef get_disparity(obj_found, image2, search_box, obj1_extent):\n    \"\"\" Computes disparities for objects in obj_found. \"\"\"\n    dist_pred = np.empty(0)\n    change = np.empty(0)\n    for target_obj in obj_found:\n        target_extent = get_obj_extent(image2, target_obj)\n        euc_dist = euclidean_dist(target_extent['obj_center'],\n                                  search_box['center_pred'])\n        dist_pred = np.append(dist_pred, euc_dist)\n        size_changed = get_sizeChange(target_extent['obj_area'],\n                                      obj1_extent['obj_area'])\n        change = np.append(change, size_changed)\n    # Note that merger of systems may create a sudden size change\n    # that exaggerates cost function.\n    disparity = dist_pred + change\n    return disparity\n\n\ndef get_disparity_all(obj_found, image2, search_box, obj1_extent):\n    \"\"\" Returns disparities of all objects found within the search box. \"\"\"\n    if np.max(obj_found) <= 0:\n        disparity = np.array([LARGE_NUM])\n    else:\n        obj_found = obj_found[obj_found > 0]\n        disparity = get_disparity(obj_found, image2,\n                                  search_box, obj1_extent)\n    return disparity\n\n\ndef save_obj_match(obj_id1, obj_found, disparity, obj_match, params):\n    \"\"\" Saves disparity values in obj_match matrix. If disparity is greater\n    than MAX_DISPARITY, saves a large number. \"\"\"\n    disparity[disparity > params['MAX_DISPARITY']] = LARGE_NUM\n    if np.max(obj_found) > 0:\n        obj_found = obj_found[obj_found > 0]\n        obj_found = obj_found - 1\n        obj_id1 = obj_id1 - 1\n        obj_match[obj_id1, obj_found] = disparity\n    return obj_match\n\n\ndef locate_all_objects(\n        data_dic, global_shift, current_objects, record, params):\n    \"\"\" Matches all the objects in image1 to objects in image2. This is the\n    main function called on a pair of images. \"\"\"\n    nobj1 = np.max(data_dic['frame'])\n    nobj2 = np.max(data_dic['frame_new'])\n\n    if (nobj2 == 0) or (nobj1 == 0):\n        print('No echoes to track!')\n        return\n\n    obj_match = np.full(\n        (nobj1, np.max((nobj1, nobj2))), LARGE_NUM, dtype='f')\n    u_shift = []\n    v_shift = []\n\n    for obj_id1 in np.arange(nobj1) + 1:\n        obj1_extent = get_obj_extent(data_dic['frame'], obj_id1)\n\n        shift = get_ambient_flow(\n            obj1_extent, data_dic['refl'], data_dic['refl_new'], params,\n            record.grid_size)\n\n        if shift is None:\n            record.count_case(5)\n            shift = global_shift\n\n        shift = correct_shift(\n            shift, current_objects, obj_id1, global_shift, record, params)\n\n        shift_meters = shift * record.grid_size[1:]\n        [v, u] = shift_meters/record.interval.seconds\n        u_shift.append(u)\n        v_shift.append(v)\n\n        search_box = predict_search_extent(\n            obj1_extent, shift, params, record.grid_size)\n        search_box = check_search_box(search_box, data_dic['frame_new'].shape)\n        objs_found = find_objects(search_box, data_dic['frame_new'])\n        disparity = get_disparity_all(\n            objs_found, data_dic['frame_new'], search_box, obj1_extent)\n        obj_match = save_obj_match(\n            obj_id1, objs_found, disparity, obj_match, params)\n\n    return obj_match, u_shift, v_shift\n\n\ndef match_pairs(obj_match, params):\n    \"\"\" Matches objects into pairs given a disparity matrix and removes\n    bad matches. Bad matches have a disparity greater than the maximum\n    threshold. \"\"\"\n\n    # Create a list of sets, where the i-th set will store the objects\n    # from image1 that have merged with objects in image2\n    # Maybe faster to use a 2D array?\n    obj_merge = np.zeros(obj_match.shape, dtype=bool)\n\n    # Determine optimal pairs\n    pairs = optimize.linear_sum_assignment(obj_match)\n\n    for id1 in pairs[0]:\n        if obj_match[id1, pairs[1][id1]] > params['MAX_DISPARITY']:\n            # Set to -1 if object has died (or merged)\n            pairs[1][id1] = -1\n            # Find the closest object in image2 to object with id1\n            id2 = np.argmin(obj_match[id1])\n            # If this object was in the search radius of object id1,\n            # add object id1 to obj_merge[id2].\n            if obj_match[id1, id2] < LARGE_NUM:\n                obj_merge[id1, id2] = True\n\n    pairs = pairs[1] + 1  # ids in current_objects are 1-indexed\n    return pairs, obj_merge\n\n\ndef get_pairs(data_dic, global_shift, current_objects, record, params):\n    \"\"\" Given two images, this function identifies the matching objects and\n    pairs them appropriately. See disparity function. \"\"\"\n    nobj1 = np.max(data_dic['frame'])\n    nobj2 = np.max(data_dic['frame_new'])\n\n    if nobj1 == 0:\n        print('No echoes found in the first scan.')\n        return\n    elif nobj2 == 0:\n        zero_pairs = np.zeros(nobj1)\n        zero_obj_merge = np.zeros(\n            (nobj1, np.max((nobj1, nobj2))), dtype=bool)\n        return zero_pairs, zero_obj_merge, [np.nan] * nobj1, [np.nan] * nobj1\n\n    obj_match, u_shift, v_shift = locate_all_objects(\n        data_dic, global_shift, current_objects, record, params)\n\n    pairs, obj_merge = match_pairs(obj_match, params)\n\n    return pairs, obj_merge, u_shift, v_shift\n", "meta": {"hexsha": "998c080665263bc70706966e9ba09750d240ef5c", "size": 10699, "ext": "py", "lang": "Python", "max_stars_repo_path": "tint/matching.py", "max_stars_repo_name": "eshort0401/TINT", "max_stars_repo_head_hexsha": "8342a59daeaee839365b08ab2fe362c8f2a84002", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tint/matching.py", "max_issues_repo_name": "eshort0401/TINT", "max_issues_repo_head_hexsha": "8342a59daeaee839365b08ab2fe362c8f2a84002", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tint/matching.py", "max_forks_repo_name": "eshort0401/TINT", "max_forks_repo_head_hexsha": "8342a59daeaee839365b08ab2fe362c8f2a84002", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1452702703, "max_line_length": 79, "alphanum_fraction": 0.6453874194, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.2942149721629888, "lm_q1q2_score": 0.17437138720741982}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nModule for the data classes:\n    Maps are made of X,Y and associated DataMap(s), while\n    Profiles are made of R and associated DataProfile(s)\n\"\"\"\n\n# External modules\nimport numpy as np\nfrom numpy import deg2rad\n\n# Units\nimport astropy.units as u\n\n# various modules from local lib\nfrom .maps_grammar import (analyse_maps_kwargs, analyse_data_kwargs,\n                           default_data_separator, list_Data_attr,\n                           get_dmap_info_from_dtype, _add_density_suffix,\n                           _is_flag_density, remap_suffix, _add_density_prefix)\n\nfrom .misc_io import (add_suffix, add_prefix, default_float, add_err_prefix,\n                      AttrDict, remove_suffix, guess_stepxy, get_extent,\n                      cover_linspace)\n\nfrom . import check, transform\n\ndefault_data_names = [\"data\", \"edata\"]\ndict_units = {\"XY\": u.arcsec, \"R\": u.arcsec}\n\nclass DataMap(object):\n    \"\"\"Data class representing a specific map\n\n    Attributes\n    ----------\n    data\n    edata\n    order\n    dname\n    dunit\n    flag\n    \"\"\"\n    def __init__(self, **kwargs):\n        \"\"\"\n        Args:\n            data: numpy array\n                Input datas values.\n            edata: numpy array [None]\n                Uncertainties for the data.\n            order: int [0]\n                order of the velocity moment. Can be -1 for 'others' (grid)\n            dname: str [None]\n                Name of the datamap\n            flag: str [None]\n            dtype: str [\"\"]\n            dunit: astropy unit [None]\n        \"\"\"\n        # Using the key list in list_Data_attr to set the attributes\n        for keyword in list_Data_attr:\n            setattr(self, keyword, kwargs.pop(keyword, None))\n\n    def add_transformed_data(self, data, edata=None, suffix=\"\"):\n        \"\"\"Add a transformed map - e.g, deprojected - using a suffix\n\n        Args:\n            data:\n            edata:\n            suffix:\n\n        Returns:\n\n        \"\"\"\n        if suffix == \"\" or suffix is None:\n            print(\"[add_transformed_data] Failed to add data, suffix is empty\")\n            return\n        new_data_attr = add_suffix(\"data\", suffix)\n        setattr(self, new_data_attr, data)\n        new_edata_attr = add_err_prefix(new_data_attr)\n        setattr(self, new_edata_attr, edata)\n\n    def _reshape_datamap(self, shape):\n        \"\"\"reshape the data\n        Args:\n            shape:\n\n        \"\"\"\n        self.data = self.data.reshape(shape)\n        if self.edata is not None:\n            self.edata = self.edata.reshape(shape)\n\n    def deproject_velocities(self, inclin=90.0):\n        \"\"\"Deproject Velocity map and add it\n        \"\"\"\n\n        if self.order != 1:\n            print(\"ERROR: data are not of order 1 [velocities] -- Aborting\")\n            return\n        Vdep, eVdep = transform.deproject_velocities(self.data,\n                                                     self.edata,\n                                                     inclin)\n        self.add_transformed_data(Vdep, eVdep, \"dep\")\n\nclass DataProfile(DataMap):\n    def __init__(self, **kwargs):\n        \"\"\"Create a profile class with some data and errors.\n\n        Args:\n            data:\n            edata:\n            **kwargs: (see DataMap)\n                order: int\n                mname: str\n                flag: str\n                dtype: \"\"\n        \"\"\"\n        # Using DataMap class attributes\n        super().__init__(**kwargs)\n\n        # Now 1D in case the input is 2D\n        if self.data is not None:\n            self.data = self.data.ravel()\n        if self.edata is not None:\n            self.edata = self.edata.ravel()\n\nclass Map(object):\n    \"\"\"A Map is a set of DataMaps associated with a location grid (X, Y)\n    It is used to describe a set of e.g., velocity fields, flux maps, etc\n    A grid is associated natively to these DataMaps as well as an orientation\n    on the sky.\n    If no grid is provided, the grid is set to integer numbers (pixels).\n\n    Attributes\n    ----------\n    NE_direct: bool [True]\n        If True, direct sense for NE meaning East is counter-clockwise\n        from North in the map.\n    alpha_North: float [0.]\n        Angle of the North w.r.t. top. Positive means counter-clockwise.\n    X, Y: numpy arrays [None, None]\n        Input location grid\n    data: numpy array [None]\n        Input values\n    edata: numpy array [None]\n        Uncertainties\n    order: int [0]\n        Order of the velocity moment. -1 for 'others' (e.g., X, Y)\n    \"\"\"\n    def __init__(self, X=None, Y=None, mname=None, mtype=\"\", comment=\"\", **kwargs):\n        \"\"\"\n        Args:\n            X: numpy array [None]\n                Input X axis location array\n            Y: numpy array [None]\n                Input Y axis location array\n            Xcen, Ycen: float, float\n                Centre for the X and Y axes. Default is the centre of the image.\n            mname: str [None]\n                Name of the dataset\n            comment: str [\"\"]\n                Comment attached to the Map\n\n            **kwargs:\n                Any of these attributes can be provided with\n                a suffix. E.g., \"dataCO\" will be understood\n                as data and with a flag=CO.\n                data: array\n                edata: array [None]\n                    Uncertainty map\n                mname: str\n                    Name of the map\n                mtype: str\n                    Type of the map\n                flag: str\n                    Flag for the map\n                order: int\n                    Order for the datamap\n        \"\"\"\n        # Empty dictionary for the moments\n        self.dmaps = AttrDict()\n\n        # ----------- First the default attributes ----------------\n        # We assume that by default the units are the default arcsec\n        self.XYunit = kwargs.pop(\"XYunit\", dict_units['XY'])\n\n        # Filling value\n        self._fill_value = kwargs.pop(\"fill_value\", 'nan')\n        # Method\n        self._method = kwargs.pop(\"method\", \"linear\")\n\n        # Comment, mname and map type\n        self.comment = comment\n        self.mname = mname\n        self.mtype = mtype\n        self.overwrite = kwargs.pop(\"overwrite\", False)\n        self._force_dtype = kwargs.pop(\"force_dtype\", False)\n\n        # ----------------- End of default attributes -------------\n\n        # ----------- Analyse the kwargs ----------------------\n        dict_dmaps, map_kwargs = analyse_data_kwargs(**kwargs)\n\n        # ------------ X and Y for the map ---------------\n        # First getting the shape of the data\n        # Using X first\n        if X is not None:\n            self.shape = X.shape\n        # If no X, try with the data\n        else:\n            # Look for the first data which exists\n            data = None\n            for name_dmap in dict_dmaps.keys():\n                if \"data\" in dict_dmaps[name_dmap]:\n                    data = dict_dmaps[name_dmap]['data']\n                    break\n\n            if check._check_ifarrays([data]):\n                    self.shape = data.shape\n            else:\n                raise ValueError(\"No reference shape is provided \"\n                      \"for map '{}'(via X, data) - Ignoring this map\".format(\n                       mname))\n                return\n\n        # Initialise the X, Y coordinates\n        self.Xcen = kwargs.pop(\"Xcen\", 0.)\n        self.Ycen = kwargs.pop(\"Ycen\", 0.)\n        # Pixel scale for the X, Y coordinates\n        self.pixel_scale = kwargs.pop(\"pixel_scale\", 1.)\n        if not self._init_XY(X, Y):\n            raise ValueError(\"ERROR: X and Y are not compatible\")\n            return\n\n        # Boolean to say whether E is direct from N (counter-clockwise)\n        self.NE_direct = kwargs.pop(\"NE_direct\", True)\n        # Angle (degrees) between North and top\n        self.alpha_North = kwargs.pop(\"alpha_north\", 0.)\n        # Get the matrix for the alignment with North-up\n        self.align_xy_NorthEast()\n\n        # --- Attaching each data map in turn -----------\n        # Add each datamap one by one\n        for dmap_name, dmap_kwargs in dict_dmaps.items():\n            if 'dname' not in dmap_kwargs:\n                dmap_kwargs['dname'] = dmap_name\n\n            # Test if we need to force dtype\n            self.add_datamap(**dmap_kwargs)\n\n    def __getattr__(self, mname):\n        for suffix in default_data_names:\n            if mname.startswith(suffix):\n                for mapname in self.dmaps.keys():\n                    if mapname in mname:\n                        basename = remove_suffix(mname, mapname,\n                                                 separator=default_data_separator)\n                        return getattr(self.dmaps[mapname], basename)\n        raise AttributeError(\"'Map' object has no attribute {}\".format(mname))\n\n    def __dir__(self):\n        return  super().__dir__() + [add_suffix(attr, map) for item in ['data', 'edata']\n                for map in self.dmaps.keys() for attr in self.dmaps[map].__dir__()\n                if attr.startswith(item)]\n\n    @property\n    def ndatamaps(self):\n        return len(self.dmaps)\n\n    def _init_XY(self, X, Y):\n        \"\"\"Initialise X and Y\n\n        Args:\n            X: numpy array\n            Y: numpy array\n                Input X, Y grid.\n        \"\"\"\n        # Define the grid in case X, Y not yet defined\n        # If it is the case, using the reference Map\n        if X is None or Y is None:\n            # We get the grid in pixel\n            print(\"WARNING: X or Y not provided. Using Pixel XY grid.\")\n            ref_ind = np.indices(self.shape, dtype=default_float)\n            self.X = ref_ind[1] - self.Xcen\n            self.Y = ref_ind[0] - self.Ycen\n            # And now convert to default unit\n            self._convert_to_xyunit()\n        else:\n            # if X, Y pre-defined, unit is pre-defined too\n            if not check._check_consistency_sizes([X, Y]):\n                print(\"ERROR: errors on sizes of X and Y\")\n                return False\n            # Just removing the centre to get 0,0\n            self.X = X - self.Xcen\n            self.Y = Y - self.Ycen\n\n        # Making sure the shapes agree\n        self.X = self.X.reshape(self.shape)\n        self.Y = self.Y.reshape(self.shape)\n        return True\n\n    def add_datamap(self, **kwargs):\n        \"\"\"Add a new DataMap to the present Map. Will check if\n        grid is compatible.\n\n        Args:\n            data: 2d array\n            order: int\n            edata: 2d array\n            dname: str\n            dtype: str\n            flag: str\n            dunit: astropy unit\n        \"\"\"\n        # Input dname to define the data. If none, define using the counter\n        dname = kwargs.pop(\"dname\", None)\n        if dname is None or dname==\"\":\n            dname = \"{0}{1:02d}\".format(self.mname, self.ndatamaps+1)\n\n        data = kwargs.pop(\"data\", None)\n        if data is None:\n            print(\"WARNING[attach_data/Map]: cannot attach data: \"\n                  \"it is 'None' (dname is {}) - Ignoring\".format(dname))\n            return\n\n        if not check._check_ifarrays([data]):\n            print(\"WARNING[attach_data/Map]: these date are not an array\"\n                  \"(dname is {}) - Ignoring\".format(dname))\n            return\n\n        overwrite = kwargs.pop(\"overwrite\", self.overwrite)\n\n        if self._has_datamap(dname) and not overwrite:\n            print(\"WARNING[attach_data]: data map {} already exists \"\n                  \"- Aborting\".format(dname))\n            print(\"WARNING[attach_data]: use overwrite option to force.\")\n            return\n\n        # Check if we wish to force the dtype / dunit\n        force_dtype = kwargs.pop(\"force_dtype\", self._force_dtype)\n        if force_dtype:\n            dtype = kwargs.get(\"dtype\", None)\n            dmap_info = get_dmap_info_from_dtype(dtype, dname)\n            # Transfer\n            for key, value in dmap_info.items():\n                kwargs[key] = value\n\n        self.attach_datamap(DataMap(data=data, dname=dname, **kwargs))\n\n    @property\n    def eq_pscale(self):\n        return u.pixel_scale(self.pixel_scale * self.XYunit / u.pixel)\n\n    @property\n    def _get_pixel_scale(self):\n        return (1. * u.pixel).to(self.XYunit, equivalencies=self.eq_pscale).value\n\n    def _convert_to_xyunit(self):\n        \"\"\"Convert XYunit into the default one\n        a priori arcseconds.\n        \"\"\"\n        self.X *= self.xyunit_per_pixel * self.pixel_scale\n        self.Y *= self.xyunit_per_pixel * self.pixel_scale\n        # Update the unit\n        self.pixel_scale = 1.0\n        self.XYunit = dict_units['XY']\n\n    @property\n    def xyunit_per_pixel(self):\n        return (1. * self.XYunit).to(dict_units['XY'],\n                                 self.eq_pscale).value\n\n    def _get_datamap(self, dname=None, order=None):\n        \"\"\"Get the datamap if it exists, and\n        check the order\n\n        Args:\n            dname:\n            order:\n\n        Returns:\n\n        \"\"\"\n        if dname is None:\n            if order is None:\n                # then just get the first map\n                dname = list(self.dmaps.keys())[0]\n            else:\n                # Then get the first map of right order\n                for key in self.dmaps.keys():\n                    if self.dmaps[key].order == order:\n                        dname = key\n                        break\n\n        if self._has_datamap(dname):\n            return self.dmaps[dname]\n        else:\n            print(\"No such datamap {} in this Map\".format(dname))\n            return None\n\n    def _fullname(self, dname):\n        return add_suffix(self.mname, dname, separator=default_data_separator)\n\n    def _has_datamap(self, dname):\n        return dname in self.dmaps.keys()\n\n    def _regrid_xydatamaps(self):\n        if not check._check_ifnD([self.X], ndim=2):\n            print(\"WARNING: regridding X, Y and datamaps into 2D arrays\")\n            newextent, newX, newY = transform.regrid_XY(self.X, self.Y)\n            for dname in self.dmaps.keys():\n                self.dmaps[dname].data = transform.regrid_Z(self.X, self.Y,\n                                                           self.dmaps[dname].data,\n                                                           newX, newY,\n                                                           fill_value=self._fill_value,\n                                                           method=self._method)\n                self.dmaps[dname].edata = transform.regrid_Z(self.X, self.Y,\n                                                            self.dmaps[dname].edata,\n                                                            newX, newY,\n                                                            fill_value=self._fill_value,\n                                                            method=self._method)\n            # Finally getting the new X and Y\n            self.X, self.Y = newX, newY\n            self.shape = self.X.shape\n\n    def _reshape_datamaps(self):\n        \"\"\"Reshape all datamaps following X,Y shape\n        \"\"\"\n        for dname in self.dmap.keys():\n            self.dmaps[dname].reshape(self.shape)\n\n    def attach_datamap(self, datamap):\n        \"\"\"Attach a DataMap to this Map\n\n        Args:\n            datamap: a DataMap\n        \"\"\"\n        if self._check_datamap(datamap):\n            datamap._reshape_datamap(self.shape)\n            self.dmaps[datamap.dname] = datamap\n            print(\"INFO: Attaching datamap {0} of type {1} (unit = {2})\".format(\n                      datamap.dname, datamap.flag, datamap.dunit))\n        else:\n            print(\"WARNING[attach_datamap]: could not attach datamap\")\n\n    def _check_datamap(self, datamap):\n        \"\"\"Check consistency of data\n        \"\"\"\n        # Main loop on the names of the dmaps\n        arrays_to_check = [datamap.data.ravel()]\n        if datamap.edata is not None:\n            arrays_to_check.append(datamap.edata.ravel())\n\n        # First checking that the data are arrays\n        if not check._check_ifarrays(arrays_to_check):\n            print(\"ERROR[check_datamap]: input maps not all arrays\")\n            return False\n\n        # Then checking that they are consistent with X, Y\n        arrays_to_check.insert(0, self.X.ravel())\n        if not check._check_consistency_sizes(arrays_to_check):\n            print(\"ERROR[check_datamap]: input datamap does not \"\n                  \"have the same size than input grid (X, Y)\")\n            return False\n\n        return True\n\n    def align_axes(self, galaxy):\n        \"\"\"Align all axes using X and Y as input\n        \"\"\"\n        self.align_xy_lineofnodes(galaxy)\n        self.align_xy_bar(galaxy)\n        self.align_xy_deproj_bar(galaxy)\n\n    @property\n    def XY_extent(self):\n        return [np.min(self.X), np.max(self.X),\n                np.min(self.Y), np.max(self.Y)]\n\n    @property\n    def _R(self):\n        return np.sqrt(self.X**2 + self.Y**2)\n\n    # Setting up NE direct or not\n    @property\n    def NE_direct(self) :\n        return self.__NE_direct\n\n    @NE_direct.setter\n    def NE_direct(self, NE_direct) :\n        self.__NE_direct = NE_direct\n        self._mat_direct = np.where(NE_direct,\n                                    transform.set_stretchmatrix(),\n                                    transform.set_reverseXmatrix())\n    # Setting up North-East to the top\n    @property\n    def alpha_North(self) :\n        return self.__alpha_North\n\n    @alpha_North.setter\n    def alpha_North(self, alpha_North) :\n        \"\"\"Initialise the parameters in the disc structure for alpha_North angles\n        in degrees and radian, as well as the associated transformation matrix\n\n        Input\n        -----\n        alpha_North: angle in degrees for the PA of the North direction\n        \"\"\"\n        self.__alpha_North = alpha_North\n        self.__alpha_North_rad = deg2rad(alpha_North)\n        self._mat_NE = self._mat_direct @ transform.set_rotmatrix(self.__alpha_North_rad)\n\n    def _get_angle_from_PA(self, PA):\n        \"\"\"Provide a way to get the angle within the original\n        frame of a certain axis with a given PA\n        Args:\n            PA: float\n                PA of axis with respect to North\n\n        Returns:\n            The angle in the original frame\n        \"\"\"\n        return PA + self.alpha_North * np.where(self.NE_direct, 1., -1.)\n\n    def align_xy_NorthEast(self) :\n        \"\"\"Get North to the top and East on the left\n        \"\"\"\n        self.X_NE, self.Y_NE = self.rotate(matrix=self._mat_NE)\n\n    def align_xy_lineofnodes(self, galaxy) :\n        \"\"\"Set the Line of Nodes (defined by its Position Angle, angle from the North\n        going counter-clockwise) as the positive X axis\n        \"\"\"\n        self._mat_lon_NE = galaxy._mat_lon.dot(self._mat_NE)\n        self.X_lon, self.Y_lon = self.rotate(matrix=self._mat_lon_NE)\n\n    def deproject(self, galaxy):\n        \"\"\"Deproject X,Y around the line of nodes using the inclination\n        \"\"\"\n        self.X_londep, self.Y_londep = self.rotate(matrix=galaxy._mat_inc,\n                                             X=self.X_lon, Y=self.Y_lon)\n\n    def align_xy_bar(self, galaxy) :\n        \"\"\"Set the bar (defined by its Position Angle, angle from the North\n        going counter-clockwise) as the positive X axis\n        \"\"\"\n        self.X_bar, self.Y_bar = self.rotate(matrix=galaxy._mat_bar @ self._mat_NE)\n\n    def align_xy_deproj_bar(self, galaxy) :\n        \"\"\"Set the bar (defined by its Position Angle, angle from the North\n        going counter-clockwise) as the positive X axis after deprojection\n        \"\"\"\n        self._mat_deproj_bar = galaxy._mat_bardep @ galaxy._mat_inc @ galaxy._mat_lon @ self._mat_NE\n        self.X_bardep, self.Y_bardep = self.rotate(matrix=self._mat_deproj_bar)\n\n        ## Mirroring the coordinates\n        self.X_mirror, self.Y_mirror = self.rotate(matrix=np.linalg.inv(self._mat_deproj_bar),\n                                                   X=self.X_bardep, Y=-self.Y_bardep)\n\n    def rotate(self, **kwargs):\n        \"\"\"Uses the rotate function from transform.py with a default\n        X,Y set of arrays using self.X and self.Y\n\n        Parameters\n        ----------\n        **kwargs: set of arguments, see transform.rotate\n            Includes X, Y, matrix\n\n        Returns:\n        The rotated arrays Xrot, Yrot\n        \"\"\"\n        X = kwargs.pop(\"X\", self.X)\n        Y = kwargs.pop(\"Y\", self.Y)\n        return transform.rotate_vectors(X, Y, **kwargs)\n\n    def intmap_to_densitymap(self, dname, galaxy):\n        \"\"\"Change intensity into density quantity\n        by dividing by the XYunit**2\n\n        Args:\n            dname (str): name of the datamap\n            galaxy (Galaxy):\n\n        Does:\n            attach a new map with the normalisation\n\n        \"\"\"\n        if not self._has_datamap(dname):\n            return\n\n        dmap = self.dmaps[dname]\n        # Test if the map is a density one using the type\n        if not _is_flag_density(dmap.flag):\n            scalepc2 = galaxy.pc_per_xyunit(self.XYunit) ** 2\n            newdata = dmap.data / scalepc2\n            if dmap.edata is not None:\n                newedata = dmap.edata / scalepc2\n            else:\n                newedata = None\n            newdtype = _add_density_suffix(dmap.dtype)\n            newdunit = dmap.dunit / self.XYunit**2\n            newflag = _add_density_prefix(dmap.flag)\n            newdname = _add_density_prefix(dmap.dname)\n            self.add_datamap(dname=newdname, data=newdata, edata=newedata,\n                             dunit=newdunit, dtype=newdtype,\n                             flag=newflag, order=dmap.order,\n                             comment=\"Renormalised density\")\n            return newdname\n        else:\n            return dname\n\n\n    def deproject_velocities(self, dname, inclin=90.0):\n        \"\"\"Deproject Velocity map if it exists\n\n        Parameters\n        ----------\n        dname: str\n            Name of the datamap to deproject\n        inclin: float [90]\n            Inclination in degrees\n        \"\"\"\n\n        if dname in self.dmaps:\n            self.dmaps[dname].deproject_velocities(inclin=inclin)\n        else:\n            print(\"ERROR: no such data name in this Map\")\n\nclass Profile(object):\n    \"\"\"A Profile is a set of DataProfiles associated via the same R profile.\n    It is used to describe radial dprofiles e.g., rotation curves.\n\n    Attributes\n    ----------\n    R: numpy array [None]\n        Input location radii\n    data: numpy array [None]\n        Input values\n    edata: numpy array [None]\n        Uncertainties\n    order: int [0]\n        Order of the velocity moment. -1 for 'others' (e.g., X, Y)\n    \"\"\"\n    def __init__(self, R=None, ref_size=None,\n                 pname=None, ptype=\"\", **kwargs):\n        \"\"\"\n        Args:\n            R (numpy array): radii\n            pname (str): name of the profile [None]\n            ptype (str): type of the profile\n\n            **kwargs:\n                data (array): input data\n                edata (array): uncertainties\n                dname (str): name of the data\n                ptype (str): type of the dataprofile\n                flag (str): flag for the dataprofile\n                order (int): order\n                comment (str): comment to be attached [\"\"]\n        \"\"\"\n        # Empty dictionary for the moments\n        self.dprofiles = AttrDict()\n\n        # See if a dataprofile is provided\n        self.Runit = kwargs.pop(\"Runit\", dict_units['R'])\n        self.pixel_scale = kwargs.pop(\"pixel_scale\", 1.)\n\n        # Get the list of suffixes which will be used to attach datasets\n        dict_dprofs, prof_kwargs = analyse_data_kwargs(**kwargs)\n\n        # First getting the shape of the data\n        if ref_size is not None:\n            self.size = ref_size\n        elif R is not None:\n            self.size = R.size\n        else:\n            # Look for the first data which exists\n            data = None\n            for dname in dict_dprofs.keys():\n                if \"data\" in dict_dprofs[dname]:\n                    data = dict_dprofs[dname]['data']\n                    break\n            if check._check_ifarrays([data]):\n                self.size = data.size\n            else:\n                print(\"ERROR: no reference shape is provided \"\n                      \"(via R, data or ref_size) - Aborting\")\n                return\n\n        # New step in R when provided\n        Rfinestep = kwargs.pop(\"Rfinestep\", 0)\n        self._init_R(R)\n\n        # Filling value\n        self._fill_value = kwargs.pop(\"fill_value\", 'nan')\n        # Method\n        self._method = kwargs.pop(\"method\", \"linear\")\n\n        # Comment for Profile\n        self.comment = kwargs.pop(\"comment\", \"\")\n        # Name of Profile\n        self.pname = pname\n        self.ptype = ptype\n        self.overwrite = kwargs.pop(\"overwrite\", False)\n        self._force_dtype = kwargs.pop(\"force_dtype\", False)\n\n        # Add each datamap one by one\n        for dname, dprof_kwargs in dict_dprofs.items():\n            if 'dname' not in dprof_kwargs:\n                dprof_kwargs['dname'] = dname\n            self.add_dataprofile(**dprof_kwargs)\n\n        if Rfinestep > 0:\n            self.interpolate(newstep=Rfinestep)\n\n    @property\n    def _get_pixel_scale(self):\n        return (1. * u.pixel).to(self.Runit, equivalencies=self.eq_pscale).value\n\n    def _convert_to_runit(self):\n        \"\"\"Convert XYunit into the default one\n        a priori arcseconds.\n        \"\"\"\n        self.R *= self.Runit_per_pixel\n        # Update the unit\n        self.Runit = dict_units['R']\n\n    @property\n    def Runit_per_pixel(self):\n        return (1. * self.Runit).to(dict_units['R'],\n                                 self.eq_pscale).value\n    @property\n    def eq_pscale(self):\n        return u.pixel_scale(self.pixel_scale * self.Runit / u.pixel)\n\n    def _init_R(self, R):\n        \"\"\"Initialise Rin\n\n        Args:\n            R: numpy array\n        \"\"\"\n        # Define the grid in case Rin\n        # If it is the case, using the reference profile\n        if R is None:\n            self.R = np.arange(self.size, dtype=default_float)\n        else:\n            self.R = R.ravel()\n        self._convert_to_runit()\n\n    @property\n    def ndataprofs(self):\n        return len(self.dprofiles)\n\n    def _fullname(self, dname):\n        return add_suffix(self.pname, dname, separator=default_data_separator)\n\n    def _has_dataprofile(self, dname):\n        return dname in self.dprofiles.keys()\n\n    def _get_dataprofile(self, dname=None, order=None):\n        \"\"\"Get the dataprofile if it exists, and\n        check the order\n\n        Args:\n            dname:\n            order:\n\n        Returns:\n\n        \"\"\"\n        if dname is None:\n            if order is None:\n                # then just get the first profile\n                dname = list(self.dprofiles.keys())[0]\n            else:\n                # Then get the first profile of right order\n                for key in self.dprofiles.keys():\n                    if self.dprofiles[key].order == order:\n                        dname = key\n                        break\n\n        if self._has_dataprofile(dname):\n            return self.dprofiles[dname]\n        else:\n            print(\"No such dataprofile {} in this Map\".format(dname))\n            return None\n\n    def attach_dataprofile(self, dataprofile):\n        \"\"\"Attach a DataProfile to this Profile\n\n        Args:\n            dataprofile: DataProfile to attach\n        \"\"\"\n        if self._check_dprofiles(dataprofile):\n            self.dprofiles[dataprofile.dname] = dataprofile\n\n    def add_dataprofile(self, **kwargs):\n        \"\"\"Attach a new Profile to the present Set.\n\n        Args:\n            data: 1d array\n            order: int\n            edata: 1d array\n            dname: str\n            dtype: str\n            flag: str\n            dunit: astropy unit\n\n        \"\"\"\n        data = kwargs.pop(\"data\", None)\n        if data is None:\n            print(\"ERROR[add_dataprofile]: data is None - Aborting\")\n            return\n\n        # Input dname to define the data. If none, define using the counter\n        dname = kwargs.pop(\"dname\", None)\n        if dname is None or dname==\"\":\n            dname = \"{0}{1:02d}\".format(self.pname, self.ndataprofs+1)\n        if dname[0] == default_data_separator:\n            dname = dname[1:]\n\n        if self._has_dataprofile(dname) and not overwrite:\n            print(\"WARNING[add_dataprofile]: data profile {} already exists \"\n                  \"- Aborting\".format(dname))\n            print(\"WARNING[add_dataprofile]: use overwrite option to force.\")\n            return\n\n        # Check if we wish to force the dtype / dunit\n        force_dtype = kwargs.pop(\"force_dtype\", self._force_dtype)\n        if force_dtype:\n            dtype = kwargs.get(\"dtype\", None)\n            dmap_info = get_dmap_info_from_dtype(dtype, dname)\n            # Transfer\n            for key, value in dmap_info.items():\n                kwargs[key] = value\n\n        self.attach_dataprofile(DataProfile(data=data, dname=dname, **kwargs))\n\n    def __getattr__(self, dname):\n        for suffix in default_data_names:\n            if dname.startswith(suffix):\n                for profname in self.dprofiles.keys():\n                    if profname in dname:\n                        basename = remove_suffix(dname, profname)\n                        return getattr(self.dprofiles[profname], basename)\n        raise AttributeError(\"'Profile' object has no attribute {}\".format(dname))\n\n    def __dir__(self, list_names=default_data_names):\n        return  super().__dir__() + [add_suffix(attr, prof) for item in list_names\n                for prof in self.dprofiles.keys() for attr in self.dprofiles[prof].__dir__()\n                if attr.startswith(item)]\n\n    def _check_dprofiles(self, dataprofile):\n        \"\"\"Check consistency of dataprofile\n        by comparing with self.Rin\n\n        Args\n            dataprofile: DataProfile\n        \"\"\"\n        # Putting everything in 1D\n        ref_array = self.R\n\n        data = dataprofile.data\n        edata = dataprofile.edata\n        arrays_to_check = [data.ravel()]\n        if edata is not None:\n            arrays_to_check.append(edata.ravel())\n\n        # Checking if the data are 1D arrays\n        if not check._check_ifarrays(arrays_to_check):\n            print(\"ERROR: input profile not all arrays\")\n            return False\n\n        # Check that they all have the same size\n        arrays_to_check.insert(0, ref_array)\n        if not check._check_consistency_sizes(arrays_to_check):\n            print(\"ERROR: input profile does not the same size \"\n                  \"than input radial grid (R)\")\n            return False\n\n        return True\n\n    def interpolate(self, dname, step=1.0, suffix=\"fine\", overwrite=False):\n        \"\"\"Provide interpolated profile\n\n        Args:\n            stepR: float [1.0]\n            suffix: str [\"\"]\n            overwrite: bool [False]\n\n        Returns:\n\n        \"\"\"\n        if step <= 0:\n            print(\"ERROR[interpolate]: new step is <= 0 - Aborting\")\n            return\n\n        # Getting the data\n        if not self._has_dataprofile(dname):\n            print(\"ERROR[interpolate]: no such dataprofile \"\n                  \"with name {}\".format(dname))\n            return\n\n        if hasattr(self.dprofiles[dname], add_suffix(\"R\", suffix)):\n            if overwrite:\n                print(\"WARNING: overwriting existing interpolated profile\")\n            else:\n                print(\"ERROR[interpolate]: interpolated profile exists. \"\n                      \"Use 'overwrite' to update.\")\n                return\n\n        Rfine, dfine, edfine = transform.interpolate_profile(self.R,\n                                                             self.dprofiles[dname].data,\n                                                             self.dprofiles[dname].edata,\n                                                             step=step)\n        setattr(self.dprofiles[dname], add_suffix(\"R\", suffix), Rfine)\n        setattr(self.dprofiles[dname], add_suffix(\"data\", suffix), dfine)\n        setattr(self.dprofiles[dname], add_suffix(\"edata\", suffix), edfine)\n\nclass Slicing(object):\n    \"\"\"Provides a way to slice a 2D field. This class just\n    computes the slits positions for further usage.\n    \"\"\"\n    def __init__(self, yextent=[-10.,10.], yin=None, slit_width=1.0, nslits=None):\n        \"\"\"Initialise the Slice by computing the number of slits and\n        their positions (defined by the axis 'y').\n\n        Args:\n            yextent: list of 2 floats\n                [ymin, ymax]\n            yin: numpy array\n                input y position\n            slit_width: float\n                Width of the slit\n            nslits: int\n                Number of slits. This is optional if a range or input yin\n                is provided.\n        \"\"\"\n\n        # First deriving the range. Priority is on yin\n        if yin is not None:\n            yextent = [np.min(yin), np.max(yin)]\n        # First deriving the number of slits prioritising nslits\n\n        Dy = np.abs(yextent[1] - yextent[0])\n        if nslits is None:\n            self.nslits = np.int(Dy / slit_width + 1.0)\n            ye2 = (Dy - self.nslits * slit_width) / 2.\n            # Adding left-over on both sides equally\n            yextent = [yextent[0] - ye2, yextent[1] + ye2]\n        else:\n            self.nslits = nslits\n            slit_width = Dy / self.nslits\n\n        self.width = slit_width\n        sw2 = slit_width / 2.\n        self.ycentres = np.linspace(yextent[0] + sw2, yextent[1] - sw2, self.nslits)\n        self.yedges = np.linspace(yextent[0], yextent[1], self.nslits+1)\n        self.yiter = np.arange(self.nslits)\n\n        @property\n        def yextent(self):\n            return [self.yedges[0], self.yedges[-1]]\n\n        @property\n        def slice_width(self):\n            return np.abs(self.yedges[-1] - self.yedges[0])\n\n\ndef match_datamaps(map1, map2=None, dname1=None, dname2=None,\n                   odname1=None, odname2=None, PAnodes=0.):\n    \"\"\"Aligning two datamaps\n\n    Args:\n        map1 (Map): input Map\n        map2 (Map): second input Map. If None, use the first one.\n        dmap1_name (str): name of input datamap 1\n        dmap2_name (str): name of input datamap 2\n        omap1_name (str): name of output datamap 1\n        omap2_name (str): name of output datamap 2\n\n    Returns:\n        New Map with matched datamaps\n    \"\"\"\n    if map2 is None:\n        map2 = map1\n\n    # Get the datamaps\n    dmap1 = map1._get_datamap(dname1)\n    dmap2 = map2._get_datamap(dname2)\n    if dmap1 is None or dmap2 is None:\n        return None\n\n    # Determine the new grid\n    XYextent = get_extent(map1.X_lon, map1.Y_lon)\n    newstep = guess_stepxy(map1.X_lon, map1.Y_lon)\n    Xn, Yn = np.meshgrid(cover_linspace(XYextent[0], XYextent[1], newstep),\n                         cover_linspace(XYextent[2], XYextent[3], newstep))\n\n    # Regrid\n    new_data1 = transform.regrid_Z(map1.X_lon, map1.Y_lon, dmap1.data, Xn, Yn)\n    new_edata1 = transform.regrid_Z(map1.X_lon, map1.Y_lon, dmap1.edata, Xn, Yn)\n    new_data2 = transform.regrid_Z(map2.X_lon, map2.Y_lon, dmap2.data, Xn, Yn)\n    new_edata2 = transform.regrid_Z(map2.X_lon, map2.Y_lon, dmap2.edata, Xn, Yn)\n\n    # And re-attach to a regrided mass map\n    omname1 = add_suffix(map1.mname, remap_suffix, separator=\"\")\n    if odname1 is None:\n        odname1 = add_suffix(dmap1.dname, remap_suffix, separator=\"\")\n    if odname2 is None:\n        odname2 = add_suffix(dmap2.dname, remap_suffix, separator=\"\")\n    mtype1 = add_prefix(map1.mtype, remap_suffix, separator=\"\")\n    dtype1 = dmap1.dtype.lower()\n    dtype2 = dmap2.dtype.lower()\n\n    # Creating the new Map\n    print(\"INFO[match_datamaps]: Creating the first map {0} and \"\n          \"attaching first datamap {1}\".format(omname1, dname1))\n    newMap = Map(mname=omname1, data=new_data1, edata=new_edata1, order=0,\n                 mtype=mtype1, X=Xn, Y=Yn, dtype=dtype1, flag=dmap1.flag,\n                 dunit=dmap1.dunit, dname=odname1, alpha_north=-90.0-PAnodes)\n\n    # Adding the second datamap\n    print(\"INFO[match_datamaps]: attaching the datamap {0} to map {1}\".format(\n           dname2, omname1))\n    newMap.add_datamap(data=new_data2, order=dmap2.order, edata=new_edata2,\n                    dname=odname2, flag=dmap2.flag, dtype=dtype2,\n                    dunit=dmap2.dunit)\n\n    return newMap\n", "meta": {"hexsha": "cd09bc46f49afc26af2ab2a140447aed1c1d4cf8", "size": 36248, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/pydisc/disc_data.py", "max_stars_repo_name": "emsellem/pydisc", "max_stars_repo_head_hexsha": "a8737b6c84d150774612f50e6607fd0dcfe6e677", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pydisc/disc_data.py", "max_issues_repo_name": "emsellem/pydisc", "max_issues_repo_head_hexsha": "a8737b6c84d150774612f50e6607fd0dcfe6e677", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pydisc/disc_data.py", "max_forks_repo_name": "emsellem/pydisc", "max_forks_repo_head_hexsha": "a8737b6c84d150774612f50e6607fd0dcfe6e677", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2607003891, "max_line_length": 100, "alphanum_fraction": 0.5566100199, "include": true, "reason": "import numpy,from numpy,import astropy", "num_tokens": 8511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.1743193017008742}}
{"text": "import os\nimport sys\nimport csv\nimport numpy as np\nimport logging\nimport yaml\nimport pytz\nfrom pathlib import Path\nfrom datetime import datetime, timedelta\nfrom matplotlib import pyplot as plt\nimport mne\n\n# How wide of a buffer around the crop do we want?\n# 1 second is enough with .5s epochs\nBUFFER_SECONDS = 1\n\nHIGHPASS_ARTIFACT = 0.5\nHIGHPASS_MMN = 1\nLOWPASS_MMN = 35\nHIGHPASS_ABR = 100\nLOWPASS_ABR = 3000\n\n# Event IDs\nUNKNOWN = 1\nSTANDARD = 2\nDEVIANT = 3\nEVENT_COLORS = {\n    UNKNOWN: \"blue\",\n    STANDARD: \"green\",\n    DEVIANT: \"red\"\n}\n\nclass BDFWithMetadata():\n    def __init__(self, path, kind, force=False, is_2013I=False, no_reference=False, reference_o1=False, reference_o2=False, no_notch=False, no_crop=False):\n        self.script_dir = sys.path[0]\n        self.kind = kind\n        self.is_2013I = is_2013I\n        self.no_reference = no_reference\n        # Both is the default, so set them to false\n        if reference_o1 and reference_o2:\n            reference_o1 = False\n            reference_o2 = False\n        self.reference_o1 = reference_o1\n        self.reference_o2 = reference_o2\n        self.no_notch = no_notch\n        self.no_crop = no_crop\n\n        # Determine if source path is in the standard /study/thukdam/raw-data/subjects location or not\n        p = Path(path).resolve()\n        self.source_path = str(p)\n        parts = p.parts\n        if \"raw-data\" in parts and \"subjects\" in parts:\n            # If \"raw-data\", \"subjects\" is in path, replace \"raw-data\" with \"analyses\", \"eeg\"\n            dest = list(parts)\n            raw_index = dest.index('raw-data')\n            dest[raw_index] = \"analyses\"\n            dest.insert(raw_index+1, \"eeg_artifacts\")\n\n            # Kind is MMN or ABR, but now we want to allow for O1/O2 only referencing\n            subfolder = kind\n            if self.reference_o1:\n                subfolder += \"-o1\"\n            if self.reference_o2:\n                subfolder += \"-o2\"\n            dest[raw_index+2] = subfolder\n            dest.remove(\"biosemi\")\n            dest[-1] = dest[-1].replace(\".bdf\", \"\")\n\n            artifact_path = Path(os.path.join(*dest))\n            dest[raw_index+1] = \"eeg_plots\"\n            plot_path = Path(os.path.join(*dest))\n\n            dest[raw_index+1] = \"eeg_statistics\"\n            statistics_path = Path(os.path.join(*dest))\n        else:\n            artifact_path = p\n            plot_path = p\n            statistics_path = p\n            if not force:\n                # DIE unless they forced to save in current dir with a flag\n                logging.critical(\"Data file not stored in expected raw-data/subjects directory, please run with --force to save masks and plots and stuff to current directory\")\n                sys.exit(1)\n\n        output_dir = p.parent\n        self.artifact_path = str(artifact_path)\n        self.plot_path = str(plot_path)\n        self.statistics_path = str(statistics_path)\n\n        logging.info(f\"Saving artifacts to {self.artifact_path}\")\n        logging.info(f\"Saving plots to {self.plot_path}\")\n        logging.info(f\"Saving statistics to {self.statistics_path}\")\n\n        # Create directories if they don't exist\n        artifact_path.parent.mkdir(parents=True, exist_ok=True)\n        plot_path.parent.mkdir(parents=True, exist_ok=True)\n        statistics_path.parent.mkdir(parents=True, exist_ok=True)\n\n        self.highpass_artifact = HIGHPASS_ARTIFACT\n\n        if self.is_mmn():\n            self.highpass = HIGHPASS_MMN\n            self.lowpass = LOWPASS_MMN\n            self.event_id = {\n                \"Unknown\": UNKNOWN,\n                \"Standard\": STANDARD,\n                \"Deviant\": DEVIANT\n            }\n        else:\n            self.highpass = HIGHPASS_ABR\n            self.lowpass = LOWPASS_ABR\n            self.event_id = {\n                \"Unknown\": UNKNOWN,\n            }\n\n    def is_standard_frequencies(self):\n        if self.is_mmn():\n            return self.highpass == HIGHPASS_MMN and self.lowpass == LOWPASS_MMN\n        else:\n            return self.highpass == HIGHPASS_ABR and self.lowpass == LOWPASS_ABR\n        \n\n    def is_mmn(self):\n        return self.kind == \"mmn\"\n\n    def load(self):\n        # Do we have existing metadata?\n        self.load_existing_metadata()\n        self.load_existing_events()\n\n        self.load_file(self.source_path)\n\n    def strip_reference_electrode(self, path):\n        return path.replace(\"-o1\", \"\").replace(\"-o2\", \"\")\n\n    def load_existing_metadata(self):\n        metadata = self.artifact_metadata_file()\n\n        # If we can't find the file at the default path, try stripping out -o1 or -o2\n        # to get the \"previous\" mask with both reference electrodes\n        if not os.path.exists(metadata):\n            metadata = self.strip_reference_electrode(metadata)\n\n        if os.path.exists(metadata):\n            with open(metadata) as file:\n                data = yaml.load(file, Loader=yaml.FullLoader)\n                self.tstart_seconds = data['tstart_seconds']\n                self.tstop_seconds = data['tstop_seconds']\n                if 'highpass' in data:\n                    self.highpass = data['highpass']\n                if 'lowpass' in data:\n                    self.lowpass = data['lowpass']\n                logging.info(f\"Loaded existing start {self.tstart_seconds} and end {self.tstop_seconds} from {metadata}, frequencies are {self.highpass}Hz to {self.lowpass}Hz\")\n        else:\n            self.tstart_seconds = None\n            self.tstop_seconds = None\n\n    def load_existing_events(self):\n        e = self.events_file()\n\n        # If we can't find the file at the default path, try stripping out -o1 or -o2\n        # to get the \"previous\" events file from the artifact rejection with both reference electrodes\n        if not os.path.exists(e):\n            e = self.strip_reference_electrode(e)\n\n        if os.path.exists(e):\n            self.events = np.load(e)\n            logging.info(f\"Loaded {len(self.events)} from events numpy file {e}\")\n        else:\n            self.events = []\n\n    def locate_events(self, expected_events, expected_duration, kind):\n        \"\"\"\n        Locate event chunks in file that match the given duration.\n\n        expected_events: Integer number of events we want to find\n        expected_duration: Duration in seconds that we want to find them in\n        kind: User-visible sort of events we're looking for\n        \"\"\"\n        sfreq = self.raw.info['sfreq']\n        raw_events = mne.find_events(self.raw)\n\n        skipped_events = 0\n        looking = True\n\n        logging.info(f\"Found {len(raw_events)} total events in file.\")\n        if len(raw_events) < expected_events:\n            logging.fatal(f\"Not enough events to find {expected_events}, exiting!\")\n            sys.exit(1)\n        while looking and len(raw_events) - skipped_events >= expected_events:\n            tstart = (raw_events[skipped_events,0] - (sfreq * BUFFER_SECONDS))\n            self.tstart_seconds = tstart / sfreq\n            tstop = (raw_events[skipped_events+expected_events-1,0] + (sfreq * BUFFER_SECONDS))\n            self.tstop_seconds = tstop / sfreq\n            duration_seconds = self.tstop_seconds - self.tstart_seconds\n\n            if duration_seconds > expected_duration - BUFFER_SECONDS*2 and \\\n                duration_seconds < expected_duration + BUFFER_SECONDS*2:\n                logging.info(f\"Found events at {tstart} with duration {duration_seconds} after skipping {skipped_events}\")\n                looking = False\n            else:\n                logging.debug(f\"Skipped {skipped_events}, at {tstart} with {duration_seconds} (looking for {expected_events})\")\n                skipped_events += 1\n\n        if looking:\n            # Sorry if this sucks in actual use, bit of a rush to get this all working\n            logging.warning(f\"Could not find {expected_events} {kind} events automatically, skipped {skipped_events} while trying.\")\n            logging.warning(f\"Please scroll and find start and stop time in seconds manually!\")\n            # Temporarily set our events to the full list for plotting\n            self.events = raw_events.copy()\n            self.plot(False)\n            self.tstart_seconds = float(input(f\"Enter {kind} start time (in seconds): \"))\n            self.tstop_seconds = float(input(f\"Enter {kind} stop time (in seconds): \"))\n\n        # Crop to those seconds\n        self.raw.crop(tmin=self.tstart_seconds, tmax=self.tstop_seconds)\n        self.tstart = self.tstart_seconds * sfreq\n        self.tstop = self.tstop_seconds * sfreq\n\n        # Truncate the events list to the ones we wanted,\n        # keeping in mind we have to start at the index after the start\n        index = np.searchsorted(raw_events[:,0], self.tstart)\n        self.events = raw_events[index:index+expected_events].copy()\n\n    def load_file(self, raw_file):\n        self.raw = mne.io.read_raw_bdf(raw_file)\n\n        # TODO: Original script does weird event deletion, with this comment:\n        \"\"\"\n        On the South computer, it appears that there are many short (2 or 3\n        sample duration) events that are probably due to a problem in the MMN\n        .WAV files or noise / dropouts / flakiness in the cables connecting the\n        field laptop audio-out jack to the input on the BioSemi system. Whatever\n        the cause, they're bogus and they screw up analysis. So we'll just delete\n        them.\n        \"\"\"\n\n        first_run = True\n        \n        if self.tstart_seconds and len(self.events) > 0:\n            # If we already have information, use that\n            self.raw.crop(tmin=self.tstart_seconds, tmax=self.tstop_seconds)\n            first_run = False\n        elif not self.no_crop:\n            if self.is_mmn():\n                # Crop to the MMN section of the file\n                self.locate_events(2000, 1000, self.kind)\n            else:\n                # Crop to the ABR section of the file\n                self.locate_events(4000, 200, self.kind)\n\n        self.raw.load_data()\n        # Rename channels in raw based on actual electrode names\n        # This is based on FMed_Chanlocs_6channels.ced\n        # EXG2 used to be called mr and EXG3 was ml,\n        # they are renamed to O1 and O2\n        # so that when we load the electrode montage below it matches\n\n        if self.raw.info['nchan'] == 17:\n            # Unclear why, but in the original files, the 6 channels are duplicated\n            # MNE appends a number to differentiate the dupes\n            self.raw.rename_channels({'EXG1-0': 'Cz', 'EXG2-0': 'O1', 'EXG3-0': 'O2', 'EXG4-0': 'Fz', 'EXG5-0': 'Pz', 'EXG6-0': 'T8'})\n        else:\n            self.raw.rename_channels({'EXG1': 'Cz', 'EXG2': 'O1', 'EXG3': 'O2', 'EXG4': 'Fz', 'EXG5': 'Pz', 'EXG6': 'T8'})\n\n        # Reference electrodes on mastoids\n        if self.no_reference:\n            logging.warning(\"Not referencing mastoids, raw view\")\n        else:\n            if self.reference_o1:\n                logging.warning(\"Referencing only O1\")\n                self.raw.set_eeg_reference(['O1'])\n            elif self.reference_o2:\n                logging.warning(\"Referencing only O2\")\n                self.raw.set_eeg_reference(['O2'])\n            else:\n                self.raw.set_eeg_reference(['O1', 'O2'])\n\n        # Try to hack in some electrode location information into the raw.info\n        montage = mne.channels.make_standard_montage('biosemi16')\n        self.raw.set_montage(montage, raise_if_subset=False)\n\n        # Notch out the India power frequency unless told not to\n        if self.no_notch:\n            logging.info(\"Not notch filtering at 50Hz\")\n        else:\n            logging.info(\"Notch filtering at 50Hz\")\n            self.raw.notch_filter(np.arange(50, 251, 50))\n        \n        if self.no_crop:\n            logging.warning(\"Not cropping, so not doing any artifact or event loading\")\n            return\n        elif first_run:\n            if self.is_mmn():\n                # Figure out if tones are same or deviant\n                self.load_event_tones_for_mmn()\n            # We don't need to do any hacking of events for ABR\n        \n            # Now we automatically save out the cropping and events metadata\n            self.save_metadata()\n            self.save_events()\n\n        # If previous annotations exist, read them\n        self.load_annotations()\n\n\n    def save_metadata(self):\n        data = {\n            'tstart_seconds': int(self.tstart_seconds),\n            'tstop_seconds': int(self.tstop_seconds),\n            'source_path': self.source_path,\n            'highpass_artifact': self.highpass_artifact,\n            'highpass': self.highpass,\n            'lowpass': self.lowpass,\n        }\n        with open(self.artifact_metadata_file(), 'w') as file:\n            yaml.dump(data, file)\n\n    def save_events(self):\n        np.save(self.events_file(), self.events)\n\n    def load_annotations(self):\n        mask_path = self.artifact_mask_file()\n\n        # If we can't find the file at the default path, try stripping out -o1 or -o2\n        # to get the \"previous\" mask file from the previous artifact rejection process\n        if not os.path.exists(mask_path):\n            mask_path = self.strip_reference_electrode(mask_path)\n\n        if os.path.exists(mask_path):\n            logging.info(f\"Loading existing artifact annotations from {mask_path}\")\n            a = mne.read_annotations(mask_path)\n            self.raw.set_annotations(a)\n\n\n    def load_event_tones_for_mmn(self):\n        logging.info(f\"Determining MMN event types\")\n        # Now we need to load the right event tones and paste them into the event array\n        mmnToneDir = os.path.join(self.script_dir, 'MMN_tone_sequences')\n        is2013Initial = self.is_2013I\n\n        if is2013Initial:\n            # 2 seconds to account for user accepting MMN .WAV file to be played\n            # 303 seconds to play \"silence\" .WAV file.\n            # 1 second to avoid interference between file playback routines\n            # 12 seconds from start of MMN .WAV file to first tone being played\n            secondsFromScriptStartToFirstTone = 2 + 303 + 1 + 12\n            mmnToneFileStart = os.path.join(mmnToneDir, 'south', 'MMN_roving_with_trigger_dpdb02_seed_10')\n            mmnToneFileEnd = '_31-May-2014_tone_sequence.txt'\n        else:\n            # 2 seconds to account for user accepting MMN .WAV file to be played\n            # 300 seconds for 300 second \"silence\" pause\n            # 10 seconds from start of MMN .WAV file to first tone being played\n            secondsFromScriptStartToFirstTone = 2 + 300 + 10;\n            mmnToneFileStart = os.path.join(mmnToneDir, 'north', 'MMN_roving_with_trigger_dpdb01_seed_10')\n            mmnToneFileEnd = '_21-Dec-2012_tone_sequence.txt'\n\n        # NOTE: This code matches what the original Matlab script does,\n        # but note that we're assuming UTC which feels... strange.\n        meas_date = self.raw.info['meas_date'][0]\n        logging.info(f'Measured date string in BDF file is {meas_date}')\n        recordedDate = datetime.fromtimestamp(meas_date, pytz.timezone(\"UTC\"))\n\n        logging.info(f'Recorded date is {recordedDate}')\n        actualStart = recordedDate + timedelta(seconds=self.tstart_seconds - secondsFromScriptStartToFirstTone)\n        doy = actualStart.timetuple().tm_yday\n\n        logging.info(f'Script start day of year = {doy}')\n        noon = actualStart.replace(hour=12, minute=0, second=0)\n        if abs(noon - actualStart).seconds < 600:\n            logging.warning(f\"WARNING: start time {actualStart} is close to noon, so the event tone discovery may be wrong\")\n\n        # We can now guess which tone sequence .TXT file to use for assigning\n        # tone IDs to events in the .BDF file.\n        logging.info(f'Script actual start is {actualStart}')\n\n        # This determination is based on day of the year and time of day:\n        if (actualStart.hour >= 12):\n            daySegment = 1\n        else:\n            daySegment = 0\n        dayEven = doy % 2\n        whichSeq = 2 * dayEven + daySegment\n        mmnToneFileName = f\"{mmnToneFileStart}{whichSeq}{mmnToneFileEnd}\"\n        logging.info(f\"Loading tones from {mmnToneFileName}\")\n\n        with open(mmnToneFileName) as csvfile:\n            reader = csv.reader(csvfile)\n            tones = next(reader)\n            # NOTE: there are way more than 2000 entries because of... legacy reasons. IGNORE\n\n        # Finally, we know enough to repair the events in the raw data\n        # and mark them same or deviant\n        numSameEvents = 0\n        numDeviantEvents = 0\n        for i in range(1, len(self.events)):\n            if (tones[i] == tones[i - 1]):\n                self.events[i,2] = STANDARD\n                numSameEvents += 1\n            else:\n                self.events[i,2] = DEVIANT\n                numDeviantEvents += 1\n        logging.info(f\"Determined {numSameEvents} same events and {numDeviantEvents} deviant events\")\n\n    def artifact_mask_file(self):\n        return self.artifact_path + f\".{self.kind}_artifact_mask.csv\"\n\n    def artifact_metadata_file(self):\n        return self.artifact_path + f\".{self.kind}_artifact_metadata.yaml\"\n    \n    def events_file(self):\n        return self.artifact_path + f\".{self.kind}_events.npy\"\n\n    def plot_output_path(self, name):\n        return self.plot_path + f\".{self.kind}_{name}.png\"\n\n    def plot(self, block=True, display_huge=False, no_events=False):\n        if display_huge:\n            if self.is_mmn:\n                duration = 1000.0\n            else:\n                duration = 200.0\n            scalings = dict(eeg=150e-6)\n            events = None\n        else:\n            duration = 5.0\n            scalings = dict(eeg=50e-6)\n            events = self.events\n\n        if no_events:\n            events = None\n\n        order = [1, 2, 3, 0, 4, 5]\n        n_channels = 7\n\n        self.raw.plot(\n            block=block,\n            n_channels=n_channels,\n            remove_dc=True,\n            events=events,\n            event_color=EVENT_COLORS,\n            highpass=self.highpass_artifact,\n            duration=duration,\n            order=order,\n            scalings=scalings)\n\n    def artifact_rejection(self, display_huge=False, no_events=False):\n        logging.info(\"View loaded. Ready for artifact rejection! Press 'a' to start, add a label, and then drag on the graph. Close the view window to continue.\")\n        self.plot(display_huge=display_huge, no_events=no_events)\n\n        mask_path = self.artifact_mask_file()\n\n        # Save the annotations\n        if len(self.raw.annotations) > 0:\n            self.raw.annotations.save(mask_path)\n\n    def build_epochs(self):\n        # Actually do the real final filtering (happens in-place)\n        self.raw.filter(l_freq=self.highpass, h_freq=self.lowpass, fir_design='firwin')\n\n        # Epoching...\n        picks = ['Cz', 'Fz', 'Pz', 'T8']\n        if self.is_mmn():\n            tmin, tmax = -0.1, 0.4\n        else:\n            tmin, tmax = -0.002, 0.010\n\n        epochs_params = dict(events=self.events, event_id=self.event_id,\n                            tmin=tmin, tmax=tmax,\n                            picks=picks, reject=None, flat=None)\n\n        self.epochs = mne.Epochs(self.raw, **epochs_params)\n        return self.epochs\n\n\n    def save_figure(self, fig, name, force_name=False):\n        if self.is_standard_frequencies() or force_name:\n            filename = self.plot_output_path(name)\n        else:\n            filename = self.plot_output_path(f\"{name}_{self.highpass}Hz_to_{self.lowpass}Hz\")\n        fig.savefig(filename, dpi=300)\n        logging.info(f\"Saved {name} plot to {filename}\")\n\n    \n    def epoch_images(self):\n        logging.warning(\"Plotting epoch image, VERY SLOW\")\n        fig = self.epochs.plot_image(cmap=\"YlGnBu_r\", group_by=None,\n                picks=['Cz', 'Fz', 'T8', 'Pz'], show=False)\n        self.save_figure(fig, \"epochs\")\n\n\n    def average_output_path(self, name):\n        return self.statistics_path + f\".{self.kind}-{name}-ave.fif\"\n\n    def save_average(self):\n        if self.is_mmn():\n            deviant = self.epochs[\"Deviant\"].average()\n            dfile = self.average_output_path(\"deviant\")\n            logging.info(f\"Saved evoked averages of deviant events to {dfile}\")\n            mne.write_evokeds(dfile, deviant)\n\n            standard = self.epochs[\"Standard\"].average()\n            sfile = self.average_output_path(\"standard\")\n            mne.write_evokeds(sfile, standard)\n            logging.info(f\"Saved evoked averages of standard events to {sfile}\")\n\n        average = self.epochs.average()\n        afile = self.average_output_path(\"all\")\n        mne.write_evokeds(afile, average)\n        logging.info(f\"Saved evoked averages to {afile}\")\n\n    def epoch_view(self):\n        logging.info(\"Loading epoch viewer...\")\n        epochs.plot(block=True)\n\n    def psd(self, high_freq):\n        # Spectral density is go!\n        # https://mne.tools/stable/generated/mne.io.Raw.html#mne.io.Raw.plot_psd\n        #fig = self.raw.plot_psd(0, high_freq, average=False, show=False, estimate='power')\n        fig = self.raw.plot_psd(0, high_freq, area_mode='std', show=False, n_fft=60000)\n        title = f\"Power spectral density for {self.kind}\"\n        self.save_figure(fig, f\"psd_to_{high_freq}\", True)\n\n    def topo(self):\n        epochs = self.epochs\n\n        joint_kwargs = dict(ts_args=dict(time_unit='s'),\n                        topomap_args=dict(time_unit='s'),\n                        show=False)\n        if self.is_mmn():\n            deviant = epochs[\"Deviant\"].average()\n            standard = epochs[\"Standard\"].average()\n            fig1 = deviant.plot_joint(**joint_kwargs)\n            self.save_figure(fig1, \"deviant_average\")\n            fig2 = standard.plot_joint(**joint_kwargs)\n            self.save_figure(fig2, \"standard_average\")\n        else:\n            average = epochs.average()\n            fig = average.plot_joint(**joint_kwargs)\n            self.save_figure(fig, \"epoch_average\")\n", "meta": {"hexsha": "13a2848c308cabd704d59df076b6d7e0cfde42f7", "size": 21919, "ext": "py", "lang": "Python", "max_stars_repo_path": "eeg_shared.py", "max_stars_repo_name": "uwmadison-chm/paper-fin-lott-2020", "max_stars_repo_head_hexsha": "81e30126981e73883dfd630c4e3915445dfbf97b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eeg_shared.py", "max_issues_repo_name": "uwmadison-chm/paper-fin-lott-2020", "max_issues_repo_head_hexsha": "81e30126981e73883dfd630c4e3915445dfbf97b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eeg_shared.py", "max_forks_repo_name": "uwmadison-chm/paper-fin-lott-2020", "max_forks_repo_head_hexsha": "81e30126981e73883dfd630c4e3915445dfbf97b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5907407407, "max_line_length": 176, "alphanum_fraction": 0.6127104339, "include": true, "reason": "import numpy", "num_tokens": 5201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096343, "lm_q2_score": 0.3380771174808128, "lm_q1q2_score": 0.17431929985616187}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nimport math, copy, csv, sys\nfrom numpy import mat, multiply\n\nclass landmarks(object):\n    \"\"\"\n    The landmarks class can be used to read, write and manipulate landmarks.  For example...\n        lmk = landmarks()                                       # Construct\n        lmk = landmarks([ ['label1',1.5,2], ['label2',2.4,5]] ) # Construct from landmarks list\n        lmk = landmarks(\"/path/to/landmarks.lmk\")               # Construct from landmarks file\n        lmk.Read(path)           # Read landmarks from given path\n        labels = lmk.GetLabels() # Get the labels of the landmarks\n        lmk.SetLabels(labels)    # Set the labels of the landmarks\n        lmk.Write(path)           # Write landmarks to given path\n    \"\"\"\n\n    def __init__(self, inputLandmarks=[['0',0,0,0]], spacing=[1.0,1.0,1.0]):\n        self.spacing = spacing\n        if type(inputLandmarks) is str:\n            self.Read(inputLandmarks, spacing)\n        elif type(inputLandmarks) is list:\n            self.SetLandmarks(inputLandmarks)\n        else:\n            raise Exception(\"Landmarks must be constructed with either a landmaks list or landmarks file path\")\n\n    def SetLandmarks(self,landmarkList):\n        \"\"\"\n        Sets the landmarks using given landmark list.\n        Format of landmarkList must be...\n            [[label1,x1,y1,...],...,[labelN,xN,yN,...]]\n        ... where x1,y1,...,xN,yN... must be numeric.\n        \"\"\"\n        # Make sure that landmarkList is a list\n        if not(type(landmarkList) is list): raise Exception(\"landmarkList must be of type list\")\n        \n        if len(landmarkList) != 0:\n            # Make sure that each landmark in landmarkList is a list\n            for landmark in landmarkList:\n                if not(type(landmark) is list): raise Exception(\"Each landmark in landmarkList must be a list.\")\n            \n            # Make sure dimension of 1st landmark in landmarkList > 0\n            dimension = len(landmarkList[0]) - 1\n            if dimension < 1: raise Exception(\"Each landmark in landmarkList must have 1 or more dinemsions\")\n\n            for landmark in landmarkList:\n                # Make sure each landmark in landmarkList has same dimension\n                if len(landmark)-1 != dimension: raise Exception(\"Each landmark in landmarkList must have same dimension.\")\n\n                # Make sure each landmark in landmarkList has numeric cordinates\n                for value in landmark[1:]:\n                    try:\n                        value + 0\n                    except TypeError:\n                        raise Exception(\"Coordinates of landmarks must be numeric.\")\n\n        self.landmarkList = landmarkList\n\n    def GetLandmarks(self,labelList=[]):\n        \"\"\"\n        Returns list of lanmarks in the format\n            [[label1,x1,y1,...],...,[labelN,xN,yN,...]]\n        \"\"\"\n        if labelList==[]:\n            return self.landmarkList[:]\n        else:\n            outLandmarkList = []\n            for label in labelList:\n                for landmark in self.landmarkList:\n                    if landmark[0] == label: outLandmarkList.append(landmark)\n            return outLandmarkList\n\n    def GetPoints(self, labelList=[]):\n        \"\"\"\n        Returns list of lanmarks in the format\n            [[x1,y1,...],...,[xN,yN,...]]\n        \"\"\"\n        if labelList==[]: labelList = self.GetLabels()\n        outPointList = []\n        for label in labelList:\n            for landmark in self.landmarkList:\n                if landmark[0] == label: outPointList.append(landmark[1:])\n        return outPointList\n\n    \n    def SetLabels(self,labelList):\n        \"\"\"\n        Sets the labels of the landmarks where labelList must have format...\n             [label1,...,labelN]\n        It is necessary that len(labelList) == landmarks.GetNumberOfLandmarks()\n        \"\"\"\n        if not(type(labelList) is list): raise Exception(\"labelList must be of type list\")\n        if len(labelList) != self.GetNumberOfLandmarks(): raise Exception(\"Label list must contain same number of labels as this landmarks object.\")\n        for i in range(0,self.GetNumberOfLandmarks()): self.landmarkList[i][0] = labelList[i]\n\n    def GetLabels(self):\n        \"\"\"\n        Returns list of landmark labels in the format...\n            [label1,...,labelN]\n        \"\"\"\n        labelList = []\n        for landmark in self.landmarkList: labelList.append(landmark[0])\n        return labelList\n\n    \n    def GetDimensionOfLandmarks(self):\n        \"\"\"\n        Returns the dimension of landmarks.\n        \"\"\"\n        return len(self.landmarkList[0]) - 1\n\n    def GetNumberOfLandmarks(self):\n        \"\"\"\n        Returns the number of landmarks.\n        \"\"\"\n        return len(self.landmarkList)\n\n    def GetNumberOfPoints(self):\n        \"\"\"\n        Returns the number of points\n        \"\"\"\n        return self.GetNumberOfLandmarks()\n    \n    def GetSize(self):\n        \"\"\"\n        Returns size of bounding box at origin which contains all landmarks\n        \"\"\"\n        dimension = self.GetDimensionOfLandmarks() \n        size = [0]*dimension\n        for lmk in self.landmarkList:\n            for i in range(dimension):\n                if lmk[i+1] > size[i]: size[i] = lmk[i+1]\n        return(size)\n\n    def GetMin(self):\n        \"\"\"\n        Returns minimum index of bounding box containing all landmarks\n        \"\"\"\n        dimension = self.GetDimensionOfLandmarks() \n        minValue = [float('inf')]*dimension\n        for lmk in self.landmarkList:\n            for i in range(dimension):\n                if lmk[i+1] < minValue[i]: minValue[i] = lmk[i+1]\n        return minValue\n\n    def GetMax(self):\n        \"\"\"\n        Returns maximum index of bounding box containing all landmarks\n        \"\"\"\n        dimension = self.GetDimensionOfLandmarks() \n        maxValue = [float('-inf')]*dimension\n        for lmk in self.landmarkList:\n            for i in range(dimension):\n                if lmk[i+1] > maxValue[i]: maxValue[i] = lmk[i+1]\n        return maxValue\n\n\n    def Read(self,path,spacing=[1.0,1.0,1.0]):\n        \"\"\"\n        Reads landmarks from given path.\n        It accepts landmarks files in the following formats\n        1. CIS format which usually has extension .lmk\n            Landmarks...\n            N\n            label1\n            x1 y1 z1 1 1\n            ...\n            labelN\n            xN yN zN 1 1\n        2. DiffeoMap format which usually has extension .txt\n            Landmarks...\n            N\n            label1 x1 y1 z1 ...\n            ...\n            labelN xN yN zN ...\n        \"\"\"\n        self.spacing = spacing\n\n        # Read lines from landmark file into list while triming whitespace and skiping blank line\n        landmarkFile = open(path,\"r\")\n        lineList = []\n        for line in landmarkFile.readlines():\n            if line.strip() != \"\": lineList.append(line.strip())\n        landmarkFile.close()\n\n        # Make sure this is a valid landmarks file by checking that the 1st line begins with \"Landmarks\"\n        if lineList.pop(0)[0:9] != \"Landmarks\":\n            raise Exception(path + \" is not a valid landmarks file.\")\n\n        # Get number of landmarks from 2nd line of file\n        numberOfLandmarks = int(lineList.pop(0))\n\n        # Split all lines in line list into words\n        #def StringSplit(string): return string.split()\n        lineList = map(str.split,lineList)\n\n        # Read landmarks from line list  \n        landmarkList = []\n        i = 0\n        while i < len(lineList):\n            if len(lineList[i]) == 1: # For CIS format landmarks\n                label = lineList[i][0]\n                index = map(float,lineList[i+1][0:3])\n                i += 2\n            else:                     # For DiffeoMap format landmarks\n                label = lineList[i][0]\n                index = map(float,lineList[i][1:4])\n                i += 1\n\n            point = [a*b for (a,b) in zip(index, spacing)]\n            landmark = [label] + point\n            landmarkList.append(landmark)\n            if len(landmarkList) >= numberOfLandmarks: break\n\n        self.SetLandmarks(landmarkList)\n\n    def Write(self,path):\n        \"\"\"\n        Writes landmarks to given path using CIS format.\n        \"\"\"\n        # Write header\n        landmarkFile = open(path,\"w\")\n        print(\"Landmarks-1.0\",file=landmarkFile)              # 1st line should always be \"Landmarks-1.0\"\n        print(self.GetNumberOfLandmarks(), file=landmarkFile) # 2nd line is always the number of landmarks\n\n        # Write landmarks\n        for landmark in self.landmarkList:\n            label = landmark[0]\n            point = landmark[1:]\n            index = [str(a/b) for (a,b) in zip(point, self.spacing)]\n            print(label,file=landmarkFile)\n            print(\" \".join(index + [\"1\",\"1\"]), file=landmarkFile)\n\n        # Write tail\n        # tail = '0\\n0\\n0\\n0,1,0\\n0\\n\"NeuroData\"\\n0.1,0.9\\n\"Voxel\"\\n0,0,0\\n' + \",\".join(map(str,self.spacing))\n        # print(tail, file=landmarkFile)\n        landmarkFile.close()\n\n    def WriteCsv(self, path):\n        csvFile = open(path, 'w')\n        csvWriter = csv.writer(csvFile)\n        header = ['label','x','y','z']\n        csvWriter.writerows([header] + self.landmarkList)\n        csvFile.close()\n\n    def GetDistances(self,otherLandmarks,spacing=[1,1,1]):\n        \"\"\"\n        Returns a list of distances between corresponding landmarks of this landmarks object and another landmarks objects.\n        \"\"\"\n        if self.GetNumberOfLandmarks() != otherLandmarks.GetNumberOfLandmarks(): raise Exception(\"Other landmarks must have same number of landmarks as this landmarks object.\")\n\n        otherLandmarkList = otherLandmarks.GetLandmarks()\n        distanceList = []\n        for i in range(0,self.GetNumberOfLandmarks()):\n            sumOfSquaredDifferences = 0\n            for j in range(0,self.GetDimensionOfLandmarks()):\n                sumOfSquaredDifferences += ((self.landmarkList[i][j+1] - otherLandmarkList[i][j+1])*spacing[j])**2\n\n            distanceList.append(math.sqrt(sumOfSquaredDifferences))\n\n        return distanceList\n\n    def Affine(self, affine):\n        print(type(self))\n        ### TODO generalize to other dimensions\n        if (not(type(affine)) is list) or (len(affine) != 12): raise Exception(\"affine must be a list of length 12.\")\n        lmkList = []\n        labelList = self.GetLabels()\n        for i in range(self.GetNumberOfLandmarks()):\n            x0 = mat(self.landmarkList[i][1:]).reshape(3,1)\n            A = mat(affine[:9]).reshape(3,3)\n            b = mat(affine[9:]).reshape(3,1)\n            #x1 = A.I*(x0 - b)\n            x1 = A*x0 + b\n            lmk = [labelList[i]] +  x1.flatten().tolist()[0]\n            lmkList.append(lmk)\n        return landmarks(lmkList, spacing=self.spacing)\n\n    def Flip(self, size):\n        \"\"\"\n        Returns flipped landmarks.\n        Useful for converting BrainWorks Landmarks to MRIStudio Landmarks or vice versa.\n        \"\"\"\n        if (not(type(size)) is list) or (len(size) != 3): raise Exception(\"size must be a list of length 3.\")\n        lmkList = []\n        labelList = self.GetLabels()\n        s = mat(size)\n        for i in range(self.GetNumberOfLandmarks()):\n            x0 = mat(self.landmarkList[i][1:])\n            x1 = s - 1 - x0\n            lmk  = [labelList[i]] + x1.tolist()[0]\n            lmkList.append(lmk)\n        return landmarks(lmkList, self.spacing)\n    \n    \"\"\"\n    def Resample(self, inSpacing, outSpacing):\n        outLandmarkList = []\n        for inLandmark in self.landmarkList:\n            inLabel = inLandmark[0]\n            inIndex = mat(inLandmark[1:])\n            x = multiply(inIndex, inSpacing)\n            outIndex = x / outSpacing\n            outLandmark = [inLabel] + outIndex.tolist()[0]\n            outLandmarkList.append(outLandmark)\n\n        return landmarks(outLandmarkList)\n    \"\"\"\n\n    def Crop(self, size):\n        if (not(type(size)) is list) or (len(size) != 3): raise Exception(\"size must be a list of length 3.\")\n        outLandmarkList = []\n        for inLandmark in self.landmarkList:\n            inLabel = inLandmark[0]\n            inCoordinate = mat(inLandmark[1:])\n            outCoordinate = inCoordinate - mat(size)\n            outLandmark = [inLabel] + outCoordinate.tolist()[0]\n            outLandmarkList.append(outLandmark)\n\n        return landmarks(outLandmarkList, self.spacing)\n\n\n\n\nclass surface(landmarks):\n    def __init__(self, inputPoints=[[0,0,0]], spacing=[1.0,1.0,1.0], inputConnections=None):\n        self.numSurfaces = 1\n        self.numPoints = 1\n        self.numPolygons = 0\n        self.numConnections = 0\n        self.connectionList = []\n        if type(inputPoints) is list:\n            inputLandmarks = [] \n            for (i,point) in enumerate(inputPoints):\n                landmark = [str(i)] + point\n                inputLandmarks+=[landmark]\n            landmarks.__init__(self, inputLandmarks)\n        elif type(inputPoints) is str:\n            self.Read(inputPoints, spacing)\n\n\n    def Write(self, path):\n        \"\"\"\n        Writes surface to given path using BYU format\n        \"\"\"\n        # Write metadata\n        surfaceFile = open(path,\"w\")\n        print(\"{0} {1} {2} {3}\".format(self.numSurfaces, self.GetNumberOfPoints(), self.numPolygons, self.GetNumberOfConnections()), file=surfaceFile)\n\n        for i in range(self.numSurfaces):\n            print(\"{0} {1}\".format(self.surfaceConnectionsStart[i], self.surfaceConnectionsEnd[i]),file=surfaceFile)\n\n        # Write points\n        pointList = self.GetPoints()\n        for point in pointList:\n            print(\" \".join(map(str,point)),file=surfaceFile)\n        \n        # Write connections\n        for connection in self.connectionList[:]:\n            print(\" \".join(map(str,connection[:-1]))+\" -\"+str(connection[-1]), file=surfaceFile)\n\n        surfaceFile.close()\n\n    def Read(self, path, spacing=[1.0,1.0,1.0]):\n        \"\"\"\n        Reads surface from given path\n        It accepts surfaces in the following format\n        1. BYU format which has extension .byu\n\n           <numSurfaces> <numPoints> <numPolygons> <numConnections>\n           1 <numPointsInSurface1>\n           2 <numPointsInSurface2>\n           ...\n           <numSurfaces> <numPointsInSurface<numSurfaces>>\n           x1 y1 z1\n           x2 y2 z2\n           ...\n           x<numPoints> y<numPoints> z<numPoints>\n        \"\"\"\n        dimension = 3\n        self.spacing = spacing\n        surfaceFile = open(path, \"r\")\n        lineList = []\n        for line in surfaceFile.readlines():\n            if line.strip() != \"\": lineList.append(line.strip())\n        surfaceFile.close()\n\n        # Read Metadata\n        line1 = lineList.pop(0).split()\n        [self.numSurfaces, self.numPoints, self.numPolygons, self.numConnections] = map(int, line1[0:4])\n\n        self.surfaceConnectionsStart = []\n        self.surfaceConnectionsEnd = []\n        for i in range(self.numSurfaces): \n            [start, end] = lineList.pop(0).split()\n            self.surfaceConnectionsStart.append(int(start))\n            self.surfaceConnectionsEnd.append(int(end))\n\n        # Read Points\n        pointData = []\n        while len(pointData) < self.numPoints*dimension:\n            line = lineList.pop(0)\n            pointData+=map(float,line.split())\n                    \n        landmarkList = []\n        for i in range(self.numPoints):\n            point = pointData[i*dimension:(i+1)*dimension]\n            label = str(i)\n            landmark = [label] + point\n            landmarkList.append(landmark)\n\n        self.SetLandmarks(landmarkList)\n\n        # Read Connections\n        connectionData = []\n        for line in lineList: connectionData += map(int,line.split())\n\n        self.connectionList = []\n        connection = []\n        for value in connectionData:\n            if value > 0:\n                connection.append(value)\n            else:\n                connection.append(-value)\n                self.connectionList.append(connection)\n                connection=[]\n\n        \n    def GetNumberOfConnections(self):\n        return len(self.connectionList)\n\n    def Affine(self, affine):\n        print(type(self))\n        ### TODO generalize to other dimensions\n        if (not(type(affine)) is list) or (len(affine) != 12): raise Exception(\"affine must be a list of length 12.\")\n        pointList = []\n        for i in range(self.GetNumberOfPoints()):\n            x0 = mat(self.landmarkList[i][1:]).reshape(3,1)\n            A = mat(affine[:9]).reshape(3,3)\n            b = mat(affine[9:]).reshape(3,1)\n            #x1 = A.I*(x0 - b)\n            x1 = A*x0 + b\n            point = x1.flatten().tolist()[0]\n            pointList.append(point)\n        return surface(pointList, spacing=self.spacing)\n", "meta": {"hexsha": "288614a3b4bc31f3723200c3a0dd554ff3692d4d", "size": 16740, "ext": "py", "lang": "Python", "max_stars_repo_path": "ndreg/landmarks.py", "max_stars_repo_name": "kkutten1/ndregOld", "max_stars_repo_head_hexsha": "7a3f5426c5a592e46cb3ed14765ed1f4f302f4a6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ndreg/landmarks.py", "max_issues_repo_name": "kkutten1/ndregOld", "max_issues_repo_head_hexsha": "7a3f5426c5a592e46cb3ed14765ed1f4f302f4a6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ndreg/landmarks.py", "max_forks_repo_name": "kkutten1/ndregOld", "max_forks_repo_head_hexsha": "7a3f5426c5a592e46cb3ed14765ed1f4f302f4a6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.533632287, "max_line_length": 176, "alphanum_fraction": 0.5714456392, "include": true, "reason": "from numpy", "num_tokens": 3931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.17431929826210552}}
{"text": "#!/usr/bin/python\n\"\"\"\nThis script is for processing the ADV data files in the ADV/ directory.\n\"\"\"\nimport dolfyn.adv.api as avm\nfrom dolfyn.tools import within\nfrom dolfyn.data.time import num2date\nimport numpy as np\nfrom os.path import isfile\nfrom main import FILEINFO\n\n# # The file names:\n# FNAMES = {ky: val.basename for ky, val in FILEINFO.iteritems()}\n\n# Some variables for calculating dissipation rate (\\epsilon)\neps_freqs = np.array([[.3, 1],\n                      [.3, 1],\n                      [.3, 3], ])\nspec_noise = [1.5e-4,\n              1.5e-4,\n              1.5e-5, ]\npii = 2 * np.pi\n\nmc = avm.motion.CorrectMotion()\n\n\ndef run(finfo=FILEINFO.values(), readvec=None, savecsv=False):\n    \"\"\"\n    Process the ADV data.\n\n    Parameters\n    ----------\n    fnames : iterable\n         A list of data file names that you want to process (default: all of\n         them).\n    readvec : {True, None, False}\n         Whether to read the raw ``.vec`` file, or load the ``.h5``\n         file. Default: read .h5, if it is available.\n    savecsv : bool\n         Save the ``_average5min.csv`` files?\n    \"\"\"\n    for finf in finfo:\n        print(\"File: {}\".format(finf.fname))\n        if readvec is True or \\\n           readvec is None and not isfile(finf.abs_fname + '.h5'):\n            dr = _read_raw(finf)\n        else:\n            dr = avm.load(finf.abs_fname + '.h5')\n\n        drm = correct_motion(dr, finf)\n\n        print('  Saving matlab file...')\n        drm.add_data('datenum', drm.mpltime + 366, 'main')\n        drm.save_mat(finf.abs_fname + '_earth.mat', groups=['orient', 'main'])\n        drm.pop_data('datenum')\n\n        bdat = average(drm)\n\n        print(\"  Saving binned data to hdf5...\")\n        bdat.save(finf.abs_fname + '_earth_b5m.h5')\n\n        if savecsv:\n            _save_csv(bdat, finf)\n\n        print(\"  Rotating to Principal frame...\")\n        avm.rotate.earth2principal(drm)\n        print(\"  Binning and saving...\")\n        bdat2 = average(drm)\n\n        bdat2.save(finf.abs_fname + '_pax_b5m.h5')\n\n        print(\"Done.\")\n\n\ndef _read_raw(finf):\n    # Read the raw vector file\n    if not isfile(finf.abs_source_fname):\n        print(\"File not found.\")\n        if finf in FILEINFO.values():\n            print(\"... Try running the main.pull function?\")\n    dr = avm.read_nortek(finf.abs_source_fname)\n\n    dr.noise[0] = 0\n    dr.noise[1] = 0\n    dr.noise[2] = 0\n\n    # Crop the data when the instrument was on the seafloor\n    dr = dr.subset(within(dr.mpltime, dr.props['time_range']))\n\n    ##########\n    print('  Cleaning the data...')\n    dr.u[~within(dr.u, [-2.5, 0.5])] = np.NaN\n    avm.clean.fillpoly(dr.u, 3, 12)\n    dr.v[~within(dr.v, [-1, 1])] = np.NaN\n    avm.clean.fillpoly(dr.v, 3, 12)\n    dr.v[~within(dr.w, [-1, 1])] = np.NaN\n    avm.clean.fillpoly(dr.w, 3, 12)\n    avm.clean.GN2002(dr.u)\n    avm.clean.GN2002(dr.v)\n    avm.clean.GN2002(dr.w)\n    for nm, d in dr.iter():\n        if isinstance(d, np.ndarray) and \\\n           d.dtype == np.float64 and nm not in ['mpltime']:\n            dr[nm] = d.astype(np.float32)\n    if dr.has_imu:\n        (dr.pitch,\n         dr.roll,\n         dr.heading) = avm.rotate.orient2euler(dr.orientmat)\n    print('  Saving...')\n    dr.save(finf.abs_fname + '.h5',\n            units={\n                'vel': 'm/s', 'velrot': 'm/s',\n                'velacc': 'm/s', 'AngRt': 'rad/s',\n                'Accel': 'm/s^2', 'AccelStable': 'm/s^2',\n                'pitch': 'deg', 'roll': 'deg', 'heading': 'deg true',\n                'mpltime': 'MatPlotLib Time format',\n                'time': 'ISO8601 time strings.', },\n            description={\n                'vel': 'Velocity array 0:True East, 1: True North, 2: Up',\n                'velrot': 'The rotation-rate velocity.',\n                'velacc': 'The tranlational (acceleration) velocity.',\n                'AccelStable': 'The low-frequency acceleration '\n                'that is ignored in calculating velacc.',\n                'pitch': 'The pitch of the ADV body',\n                'roll': 'The roll of the ADV body',\n                'heading': 'The heading (True) of the ADV body',\n                'orientmat': \"The orientation matrix of the\"\n                \" ADV body in the Earth's reference frame\", })\n    return dr\n\n\ndef _save_csv(bdat, finf):\n\n        ti = bdat.sigma_Uh / bdat.U_mag\n        ti[bdat.U_mag < 0.7] = np.NaN\n\n        print(\"  Saving average csv file...\")\n        np.savetxt(finf.abs_fname + '_Average5min.csv',\n                   np.vstack((num2date(bdat.mpltime), bdat.u,\n                              bdat.v, bdat.w, ti)).T,\n                   fmt=['%s'] + ['%0.3f'] * 4,\n                   header='Date+Time (US/Pacific), u (true east m/s), '\n                          'v (true north m/s), w (up m/s), '\n                          'Turbulence Intensity',\n                   delimiter=', ')\n\n\ndef correct_motion(dr, finf):\n\n    print('  Motion correcting...')\n    drm = dr.copy()\n    mc(drm)\n    (drm.pitch[:],\n     drm.roll[:],\n     drm.heading[:]) = avm.rotate.orient2euler(drm.orientmat)\n    print('  Saving...')\n    drm.save(finf.abs_fname + '_earth.h5',\n             units={\n                 'vel': 'm/s', 'velrot': 'm/s',\n                 'velacc': 'm/s', 'AngRt': 'rad/s',\n                 'Accel': 'm/s^2', 'AccelStable': 'm/s^2',\n                 'pitch': 'deg', 'roll': 'deg', 'heading': 'deg true',\n                 'mpltime': 'MatPlotLib Time format',\n                 'time': 'ISO8601 time strings.', },\n             description={\n                 'vel': 'Velocity array 0:True East, 1: True North, 2: Up',\n                 'velrot': 'The rotation-rate velocity.',\n                 'velacc': 'The tranlational (acceleration) velocity.',\n                 'AccelStable': 'The low-frequency acceleration that'\n                 ' is ignored in calculating velacc.',\n                 'pitch': 'The pitch of the ADV body',\n                 'roll': 'The roll of the ADV body',\n                 'heading': 'The heading (True) of the ADV body',\n                 'orientmat': \"The orientation matrix of the ADV \"\n                 \"body in the Earth's reference frame\", })\n    return drm\n\n\ndef average(dat):\n    print(\"  Averaging...\")\n    bnr = avm.TurbBinner(n_bin=5 * 60 * dat.fs, fs=dat.fs)\n\n    # This is just a shortcut\n    velmot = dat.velacc + dat.velrot\n\n    bdat = bnr(dat)\n\n    # Calculate spectra ####\n    bdat.add_data('Spec_velrot',\n                  bnr.calc_vel_psd(dat.velrot, ),\n                  'spec')\n    bdat.add_data('Spec_velacc',\n                  bnr.calc_vel_psd(dat.velacc, ),\n                  'spec')\n    bdat.add_data('Spec_velmot',\n                  bnr.calc_vel_psd(velmot, ),\n                  'spec')\n    bdat.add_data('Spec_velraw',\n                  bnr.calc_vel_psd(dat.velraw, ),\n                  'spec')\n\n    # Calculate cross-spectra ('point cross-spectra') ####\n    bdat.props['Cspec_comp'] = ['uv', 'uw', 'vw']\n    bdat.add_data('Cspec_vel',\n                  bnr.calc_vel_cpsd(dat.vel).astype(np.complex64),\n                  'spec')\n    bdat.add_data('Cspec_velmot',\n                  bnr.calc_vel_cpsd(velmot).astype(np.complex64),\n                  'spec')\n    bdat.add_data('Cspec_velraw',\n                  bnr.calc_vel_cpsd(dat.velraw).astype(np.complex64),\n                  'spec')\n\n    # Calculate triple products ####\n    # setup\n    bdat.props['tripprod_comp'] = [['uuu', 'uuv', 'uuw', ],\n                                   ['vvu', 'vvv', 'vvw', ],\n                                   ['wwu', 'wwv', 'www', ]]\n    bdat.add_data('tripprod',\n                  np.empty((3, 3, len(bdat.u)),\n                           dtype=np.float32),\n                  'turb')\n    # Calculate\n    turb = bnr.demean(dat.vel)\n    for i0 in range(3):\n        for i1 in range(3):\n            bdat.tripprod[i0, i1] = (turb[i0] ** 2 * turb[i1]).mean(-1)\n\n    # Calculate the dissipation rate ####\n    epstmp = np.zeros_like(bdat.u)\n    Ntmp = 0\n    for idx, frq_rng in enumerate(eps_freqs):\n        if frq_rng is None:\n            continue\n        om_rng = frq_rng * pii\n        N = ((om_rng[0] < bdat.omega) & (bdat.omega < om_rng[1])).sum()\n        sptmp = bdat.Spec[idx] - spec_noise[idx] / pii\n        sptmp[sptmp < 0] = 0\n        tmp = bnr.calc_epsilon_LT83(sptmp,\n                                    bdat.omega,\n                                    np.abs(bdat.U),\n                                    om_rng)\n        epstmp += tmp * N\n        Ntmp += N\n    epstmp /= Ntmp\n    # epstmp[np.abs(dat.U) < 0.2] = np.NaN\n    bdat.add_data('epsilon', epstmp, 'main')\n    return bdat\n\nif __name__ == '__main__':\n\n    import argparse\n\n    parser = argparse.ArgumentParser(\n        description=\"Process ADV data files.\")\n    parser.add_argument(\n        'fnames', nargs='*',\n        help='The base file names (<basename>, i.e., without '\n        'file extensions) of the files to process. If no files '\n        'are specified, all files specified in the scrip will be processed.')\n    parser.add_argument(\n        '--readvec',\n        help=\"Force reading of the binary vector file. By default, \"\n        \"the script will only read `<basename>.vec` files if there \"\n        \"is no <basename>.h5\",\n        action='store_true')\n    parser.add_argument(\n        '--savecsv',\n        help=\"Save simplified CSV files during processing?\",\n        action='store_true')\n    args = parser.parse_args()\n    if not args.readvec:\n        args.readvec = None\n    if len(args.fnames) == 0:\n        args.fnames = FNAMES.values()\n\n    run(args.fnames, readvec=args.readvec, savecsv=args.savecsv)\n", "meta": {"hexsha": "a51406ba19214f70b05dcc83a38890055a4d3fd6", "size": 9549, "ext": "py", "lang": "Python", "max_stars_repo_path": "process_adv.py", "max_stars_repo_name": "lkilcher/TTMdata_June2014", "max_stars_repo_head_hexsha": "a9b26daf24525633cf61f4aa4de7102bde825bee", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "process_adv.py", "max_issues_repo_name": "lkilcher/TTMdata_June2014", "max_issues_repo_head_hexsha": "a9b26daf24525633cf61f4aa4de7102bde825bee", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "process_adv.py", "max_forks_repo_name": "lkilcher/TTMdata_June2014", "max_forks_repo_head_hexsha": "a9b26daf24525633cf61f4aa4de7102bde825bee", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3489208633, "max_line_length": 78, "alphanum_fraction": 0.5241386533, "include": true, "reason": "import numpy", "num_tokens": 2582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.1743192982621055}}
{"text": "# this file has the transformer model\n\nimport os\nimport math\nimport json\nimport torch\nimport numpy as np\nfrom torch import nn\nfrom PIL import Image\nfrom tqdm import trange\nfrom textwrap import wrap\nimport matplotlib.pyplot as plt\nfrom tokenizers import Tokenizer\nfrom types import SimpleNamespace\nfrom argparse import ArgumentParser\nfrom torch.nn import functional as F\nfrom torch.utils.data import DataLoader\n\nfrom generation import GenerationMixin\nfrom discrete_vae import VQVAE_v3, transforms, set_seed\n\nfrom transformers import GPT2Config\nfrom transformers.models.gpt2.modeling_gpt2 import Block, MLP\n\n\nWANDB = os.getenv(\"WANDB\")\nif WANDB:\n  import wandb\n\nplt.rcParams.update({\n  'font.family': 'barlow',\n  'font.size': 10\n})\n\n# ------ helper functions\n\ndef configure_optimizers(model, lr, weight_decay = 0.1, betas=(0.9, 0.999)):\n    \"\"\"\n    from karpathy/minGPT\n    This long function is unfortunately doing something very simple and is being very defensive:\n    We are separating out all parameters of the model into two buckets: those that will experience\n    weight decay for regularization and those that won't (biases, and layernorm/embedding weights).\n    We are then returning the PyTorch optimizer object.\n    \"\"\"\n    # separate out all parameters to those that will and won't experience regularizing weight decay\n    decay = set()\n    no_decay = set()\n    whitelist_weight_modules = (torch.nn.Linear, MLP, Block)\n    blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding) # add denorm here\n    for mn, m in model.named_modules():\n        for pn, p in m.named_parameters():\n            fpn = '%s.%s' % (mn, pn) if mn else pn # full param name\n            if \"vae\" in fpn:\n              continue\n\n            pn_type = pn.split(\".\")[-1]\n            if pn_type == 'bias':\n                # all biases will not be decayed\n                no_decay.add(fpn)\n            elif (\n                (pn_type == 'weight' and isinstance(m, blacklist_weight_modules)) or\n                \"ln\" in fpn or\n                \"positional_encoding\" in fpn\n            ):\n                # weights of blacklist modules will NOT be weight decayed\n                no_decay.add(fpn)\n            elif pn_type == 'weight' and isinstance(m, whitelist_weight_modules):\n                # weights of whitelist modules will be weight decayed\n                decay.add(fpn)\n\n    # validate that we considered every parameter\n    param_dict = {pn: p for pn, p in model.named_parameters() if \"vae\" not in pn}\n    inter_params = decay & no_decay\n    union_params = decay | no_decay\n\n    assert len(inter_params) == 0, \"parameters %s made it into both decay/no_decay sets!\" % (str(inter_params), )\n    assert len(param_dict.keys() - union_params) == 0, \"parameters %s were not separated into either decay/no_decay set!\" \\\n                                                % (str(param_dict.keys() - union_params), )\n\n    # create the pytorch optimizer object\n    optim_groups = [\n        {\"params\": [param_dict[pn] for pn in sorted(list(decay))], \"weight_decay\": weight_decay},\n        {\"params\": [param_dict[pn] for pn in sorted(list(no_decay))], \"weight_decay\": 0.0},\n    ]\n    optimizer = torch.optim.AdamW(optim_groups, lr=lr, betas=betas)\n    return optimizer\n\n\ndef init_weights(dalle, v=False):\n  # function to initiliase the parameters, .apply() has some problems like\n  # you cannot find the exact name and so there might be a \"Linear\" in part\n  # of network you do not want to modify. This looped approach gives a much\n  # better control over what happens\n  for n, p in dalle.named_parameters():\n    if \"vae\" in n:\n      # we do not want to reinit VAE\n      continue\n\n    m0 = f\"{p.mean().item():.3f}, {p.std().item():.3f}\"\n    if \"weight\" in n and \"ln_\" not in n:\n      # this is linear weight\n      p.data.normal_(mean=0.0, std=0.2)\n\n    # layer norm\n    elif \"ln_\" in n:\n      if \"bias\" in n:\n        p.data.zero_()\n      else:\n        p.data.fill_(1.0)\n\n    elif \"positional_encoding\" in n:\n      # this is the positional encoding that was giving nightmares\n      # if you do not initialise it the network passes the `torch.empty()`\n      # through the network without giving a warning and keeps returning\n      # nan.\n      p.data.normal_(mean=0.0, std=0.2)\n\n    elif \"bias\" in n:\n      p.data.zero_()\n\n    m1 = f\"{p.mean().item():.3f}, {p.std().item():.3f}\"\n    if v: print(n, \"\\t\", m0, \"\\t\", m1)\n\n# ------ model classes\n\nclass Vqvae:\n  \"\"\"\n  Wrapper for model in discrete_vae, automatically infers the architecture from model path\n  \"\"\"\n  def __init__(self, model_path):\n    # model_path looks like this path/to/vqvae3_128_325_3025_0_64\n    args = self.infer_details_from_name(model_path)\n    for k,v in vars(args).items():\n      setattr(self, k, v)\n\n  @staticmethod\n  def infer_details_from_name(model_path):\n    attrs=model_path.split(\"/\")[-1].split(\"_\")\n    in_channels=3                    # number of channels in the image (def=3)\n    input_res=int(attrs[1])          # input resolution of the image\n    embedding_dim=int(attrs[2])*3    # embedding dimension for the latent space\n    num_embeddings=int(attrs[3])     # number of embeddings in the codebook\n    add_residual=bool(int(attrs[4])) # to use the model with residual connection or not\n    dim = int(attrs[2])\n    hidden_dims=[dim, int(1.5 * dim), dim * 2] # hidden dimensions for different layers\n    args = SimpleNamespace(\n      model_path=model_path,\n      in_channels=in_channels,\n      input_res=input_res,\n      embedding_dim=embedding_dim,\n      num_embeddings=num_embeddings,\n      add_residual=add_residual,\n      hidden_dims=hidden_dims,\n    )\n    return args\n\n  def get_model(self):\n    model = VQVAE_v3(\n        in_channels=self.in_channels,\n        embedding_dim=self.embedding_dim,\n        num_embeddings=self.num_embeddings,\n        hidden_dims=self.hidden_dims,\n        add_residual=self.add_residual,\n    )\n    map_location = \"cpu\" if not torch.cuda.is_available() else \"cuda\"\n    model.load_state_dict(torch.load(self.model_path, map_location=map_location))\n    model.eval()\n    return model\n\n\nclass TransformerConfig():\n  def __init__(\n    self,\n    text_context_len=256,\n    image_context_len=256,\n    text_vocab_size=16000,\n    image_vocab_size=3025,\n    n_embd=512,\n    n_layers=12,\n    n_heads=64,\n  ):\n    self.text_context_len=text_context_len\n    self.image_context_len=image_context_len\n    self.text_vocab_size=text_vocab_size\n    self.image_vocab_size=image_vocab_size\n    self.n_embd=n_embd\n    self.n_layers=n_layers\n    self.n_heads=n_heads\n    self.total_context_len = text_context_len + image_context_len\n\n\nclass Transformer(nn.Module):\n  def __init__(self, total_context_len:int,  n_embd: int, n_layers: int, n_heads: int, attn_mask: torch.Tensor = None):\n    super().__init__()\n    self.n_embd = n_embd\n    self.n_layers = n_layers\n    self.transconfig = GPT2Config(\n      n_positions=total_context_len,\n      n_ctx=total_context_len,\n      n_embd=n_embd,\n      n_head=n_heads,\n      n_layer=n_layers\n    )\n    self.attn_mask = attn_mask\n\n    # using the ResidualAttentionBlock from OpenAI was causing problems\n    # so using the huggingface GPT2 Block instead\n    self.h = nn.ModuleList([\n      Block(self.transconfig.n_ctx, self.transconfig, scale=True)\n      for _ in range(n_layers)\n    ])\n\n  def forward(self, x: torch.Tensor, attn_mask = None, output_attentions = False):\n    hidden_states = x\n    for blk in self.h:\n      output = blk(\n        hidden_states,\n        attention_mask=self.attn_mask if attn_mask is None else attn_mask,\n        output_attentions=output_attentions,\n      )\n      hidden_states = output[-1]\n    return [hidden_states]\n\n\nclass DallETransformer(nn.Module, GenerationMixin):\n  def __init__(self, vae, transformer_config):\n    super().__init__()\n    self.vae = vae\n    self.vae.requires_grad_ = False\n\n    # transformer\n    tconf = transformer_config\n    self.config = tconf\n    self.context_length=tconf.text_context_len + tconf.image_context_len\n    total_vocab_size = tconf.text_vocab_size + tconf.image_vocab_size\n\n    # this does not need to be a nn.Embedding because the full length will always be used\n    self.positional_encoding = nn.Parameter(torch.empty(self.context_length, tconf.n_embd))\n    self.token_embedding = nn.Embedding(total_vocab_size, tconf.n_embd)\n    self.transformer = Transformer(\n      total_context_len=self.context_length,\n      n_embd=tconf.n_embd,\n      n_layers=tconf.n_layers,\n      n_heads=tconf.n_heads,\n      attn_mask=None\n    )\n    self.image_head = nn.Sequential(\n      nn.LayerNorm(tconf.n_embd),\n      nn.Linear(tconf.n_embd, tconf.image_vocab_size)\n    )\n\n  def build_attention_mask(self, _len = None):\n    _len = self.context_length if _len is None else _len\n    # lazily create causal attention mask, with full attention between the vision tokens\n    # pytorch uses additive attention mask; fill with -inf\n    mask = torch.ones(_len, _len) * -1e6\n    # mask.fill_(-1e6) # nan happens with float(\"-inf\")\n    mask.triu_(1)      # zero out the lower diagonal\n    return mask.unsqueeze(0).unsqueeze(0)\n\n  def forward(self, text_tokens, images = None, image_tokens=None, attn_mask = None, recons = False, loss = False, **kwargs):\n    \"\"\"this model automanages the text tokens by incrementing to the correct vocab\"\"\"\n    config = self.config\n    no_image = True\n    if image_tokens is None and images is not None:\n      with torch.no_grad():\n        image_tokens = self.vae._encode_image(images) # [B,i]\n        no_image = False\n    elif image_tokens is not None:\n      no_image = False\n\n    # increment because the image tokens occupy the first segement\n    text_tokens = text_tokens + config.image_vocab_size\n\n    if no_image:\n      tokens = text_tokens\n    else:\n      tokens = torch.cat([text_tokens, image_tokens], dim = -1) # [B,t] + [B,i] = [B,M]\n\n    total_gen = tokens.shape[1]\n    embed = self.token_embedding(tokens) + self.positional_encoding[:total_gen, :] # [B,M,e]\n \n    if attn_mask is not None:\n      attn_mask = attn_mask.view(embed.size(0), -1)\n      attn_mask = attn_mask[:, None, None, :]\n      attn_mask = (1.0 - attn_mask) * -10000.0\n    else:\n      attn_mask = self.build_attention_mask(tokens.size(1)).to(embed.device)\n\n    # transformer blocks return tuple [hidden_states, present, (attentions, cross_attentions)]\n    out = self.transformer(x = embed, attn_mask = attn_mask)[0] # [B,M,e]\n    out = self.image_head(out) # [B,M,vi]\n    output = [out]\n\n    if loss:\n      # note that we do not need to calculate loss for the entire sequence but only for the image tokens\n      # so the labels are -100 for text_tokens and image_tokens concatenated\n      labels = torch.cat([\n        torch.ones_like(text_tokens).long() * -100,\n        image_tokens\n      ], dim = -1)[:, 1:].contiguous().view(-1)\n      logits = out[:, :-1].contiguous().view(-1, config.image_vocab_size)\n      loss = F.cross_entropy(logits, labels, ignore_index=-100)\n      output = [out, loss]\n\n    if recons:\n      # caller wants to see the constructed image\n      softmax = out[:, len(text_tokens[0]):].softmax(dim = -1) # [B, HW, E]\n      image_dim = np.sqrt(softmax.shape[1]).astype(int)\n      softmax = softmax.view(-1, image_dim, image_dim, softmax.size(-1))\n      softmax = softmax.permute((0, 3, 1, 2)) # [B,H,W,E] -> [B,E,H,W]\n      image_gen_tokens = F.one_hot(\n        torch.argmax(softmax, dim = 1),\n        num_classes = softmax.size(1)\n      ).permute((0, 3, 1, 2)).float()\n      recons = self.vae._decode_ids(image_gen_tokens)\n      output = output + [recons]\n\n    return output\n\n\nclass Dalle():\n  def __init__(self, model_args, vae, tokenizer):\n    self.model = DallETransformer(vae, model_args)\n    self.device = \"cpu\"\n    self.model.load_state_dict(torch.load(\n      model_args.model_path,\n      map_location=self.device\n    ))\n    self.model.eval()\n\n    self.model_args = model_args\n    self.tokenizer = tokenizer\n    self.text_end_id = self.tokenizer.get_vocab()[\"<|endoftext|>\"]\n    self.image_end_id = self.tokenizer.get_vocab()[\"<|endofimage|>\"]\n\n  \n  @staticmethod\n  def parse_name(model_path, image_vocab_size, text_vocab_size):\n    # folder_path = f\"./dalle_{vqvae_arch.input_res}_{args.n_embd}_\"\n    #   \"{args.n_layers}_{args.n_heads}_{args.batch_size}_{args.text_context_len}/dalle_{gs}.pt\"\n    gs = int(model_path.split(\"_\")[-1].split(\".\")[0])\n    arch = model_path.split(\"/\")[-1]\n    res = int(arch.split(\"_\")[1])\n    text_context_len = int(arch.split(\"_\")[6])\n    return SimpleNamespace(\n      model_path=model_path,\n      _gs = gs,\n      input_res=res,\n      n_embd=int(arch.split(\"_\")[2]),\n      n_layers=int(arch.split(\"_\")[3]),\n      n_heads=int(arch.split(\"_\")[4]),\n      batch_size=int(arch.split(\"_\")[5]),\n      text_context_len=text_context_len,\n      image_vocab_size=image_vocab_size,\n      image_context_len=int((res / 8) ** 2),\n      text_vocab_size=text_vocab_size,\n      total_context_len= text_context_len + int((res / 8) ** 2)\n    )\n\n  # most of the code for generation comes from hugginface\n  # https://github.com/huggingface/transformers/src/transformers/generation_utils.py\n  @staticmethod\n  def top_k_top_p_filtering(\n    logits,\n    top_k: int = 0,\n    top_p: float = 1.0,\n    filter_value: float = -float(\"Inf\"),\n    min_tokens_to_keep: int = 1,\n  ):\n    if top_k > 0:\n      top_k = min(max(top_k, min_tokens_to_keep), logits.size(-1))  # Safety check\n      # Remove all tokens with a probability less than the last token of the top-k\n      indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]\n      logits[indices_to_remove] = filter_value\n\n    if top_p < 1.0:\n      sorted_logits, sorted_indices = torch.sort(logits, descending=True)\n      cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)\n\n      # Remove tokens with cumulative probability above the threshold (token with 0 are kept)\n      sorted_indices_to_remove = cumulative_probs > top_p\n      if min_tokens_to_keep > 1:\n        # Keep at least min_tokens_to_keep (set to min_tokens_to_keep-1 because we add the first one below)\n        sorted_indices_to_remove[..., :min_tokens_to_keep] = 0\n      # Shift the indices to the right to keep also the first token above the threshold\n      sorted_indices_to_remove[...,1:] = sorted_indices_to_remove[..., :-1].clone()\n      sorted_indices_to_remove[..., 0] = 0\n\n      # scatter sorted tensors to original indexing\n      indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)\n      logits[indices_to_remove] = filter_value\n    return logits\n\n\n  def complete_image(self, text_tokens, batch_size, num_beams, image_tokens=None, top_k = 50, top_p = 0.95):\n    config = self.model_args\n    if image_tokens is None:\n        num_steps = config.total_context_len - text_tokens.shape[1]\n    else:\n        num_steps = config.total_context_len - text_tokens.shape[1] - image_tokens.shape[1]\n    for i in trange(num_steps):\n      total_gen = config.text_context_len\n      if image_tokens is not None:\n        image_tokens = image_tokens.view(batch_size*num_beams, -1)\n        total_gen += image_tokens.shape[1]\n\n      with torch.no_grad():\n        logits = self.model.forward(\n            text_tokens=text_tokens.view(batch_size*num_beams, -1),\n            image_tokens=image_tokens,\n            attn_mask = torch.ones(text_tokens.size(0), total_gen)\n        )[0].cpu() # [batch_size * num_beams, total_gen, image_vocab_size]\n      scores = F.log_softmax(logits[:, -1], dim=-1) # [batch_size * num_beams, image_vocab_size]\n      top_scores = self.top_k_top_p_filtering(\n        logits=scores,\n        top_k = top_k,\n        top_p=top_p,\n        filter_value = -1e6\n      )  # [batch_size * num_beams, image_vocab_size]\n      # _scores = top_scores.contiguous().view(batch_size, num_beams * top_scores.size(-1)) # (batch_size, num_beams * vocab_size)\n      \n      # Sample 2 next tokens for each beam (so we have some spare tokens and match output of greedy beam search)\n      probs = F.softmax(top_scores, dim=-1)\n      next_tokens = torch.multinomial(probs, num_samples=num_beams) # (batch_size, num_beams)\n    \n      next_scores = torch.gather(top_scores, -1, next_tokens) # (batch_size, num_beams)\n      \n      next_scores, next_scores_indices = torch.sort(next_scores, descending=True, dim=1)\n        \n      # gather those with high score for each batch\n      next_tokens = torch.gather(next_tokens, -1, next_scores_indices)[:, 0].unsqueeze(1)  # (batch_size, 1)\n\n      if image_tokens is not None:\n        image_tokens = torch.cat([image_tokens, next_tokens], dim = -1)\n      else:\n        image_tokens = next_tokens\n    return image_tokens\n\n\n  def generate(self, texts, num_beams = 1, images=None, image_context_len=100, top_k=50, top_p=0.95):\n    # text_tokens = self.tok.encode(cap).ids[:self.textlen - 1] + [self.text_end_id]\n    config = self.model_args\n    tokens = [self.tokenizer.encode(x * 100).ids[:config.text_context_len - 1] for x in texts]\n    tokens = torch.Tensor([[x for _ in range(num_beams)] for x in tokens]).long()\n    tokens = tokens.view(num_beams * len(texts), -1)\n    eot_tokens = torch.ones(len(tokens), 1) * self.text_end_id\n    text_tokens = torch.cat([tokens, eot_tokens], dim=-1).long().to(self.device)\n    batch_size = len(texts)\n\n    with torch.no_grad():\n      image_tokens = None\n      if images is not None and image_context_len > 0:\n        image_tokens = self.model.vae._encode_image(images.to(self.device))\n        image_tokens = image_tokens[:, :image_context_len]\n\n      complete_image_tokens = self.complete_image(\n        text_tokens=text_tokens,\n        image_tokens=image_tokens,\n        batch_size=batch_size,\n        num_beams=num_beams,\n        top_k = top_k,\n        top_p = top_p\n      )\n\n      # now that the tokens are generated we need to pass this to the vae\n      gen_image = self.model.vae._decode_ids(image_tokens=complete_image_tokens).permute((0, 2, 3, 1))\n    gen_image = (gen_image.numpy() * 255).astype(np.uint8)\n    return gen_image\n\n\n# ---------- model ends\n\n\nclass DallECaptions():\n  def __init__(\n      self,\n      captions_file,\n      tokenizer_path,\n      keys,\n      res = 128,\n      text_context_len=64\n    ):\n\n    with open(captions_file, \"r\") as f:\n      self.data = json.load(f)\n    self.image_keys = list(self.data.keys())\n    self.indices = keys\n\n    # image related\n    self.t = transforms.Compose([\n      transforms.Resize((res, res)),\n      transforms.ToTensor()\n    ])\n\n    # text related\n    self.textlen = text_context_len\n    self.tok = Tokenizer.from_file(tokenizer_path)\n    self.text_end_id = self.tok.get_vocab()[\"<|endoftext|>\"]\n    self.image_end_id = self.tok.get_vocab()[\"<|endofimage|>\"]\n\n    print(\"Tokenizer loaded with vocab size:\", self.tok.get_vocab_size())\n\n  @staticmethod\n  def get_split(captions_file, train_split=0.95):\n    # we need to get the split index to ensure correct split\n    with open(captions_file, \"r\") as f:\n      data = json.load(f)\n    image_keys = list(data.keys())\n    np.random.shuffle(image_keys)\n    train_idx = int(train_split*len(image_keys))\n    return image_keys[:train_idx], image_keys[train_idx:]\n\n  def __len__(self):\n    return len(self.indices)\n\n  def decode(self, x):\n    return [self.tok.decode(y, skip_special_tokens=True) for y in x.tolist()]\n\n  def __getitem__(self, i):\n    key = self.indices[i]\n    x = self.data[key]\n    img = self.t(Image.open(x[\"path\"]).convert('RGB'))\n    \n    # just force this to be very large, repeat is fine OpenAI DallE does this as well\n    cap = x[\"caption\"].lower() * 100\n    text_tokens = self.tok.encode(cap).ids[:self.textlen - 1] + [self.text_end_id]\n    return {\n      \"images\": img,\n      \"text_tokens\": torch.Tensor(text_tokens).long()\n    }\n\n\nclass DallETrainer():\n  def __init__(self, train, test, model):\n    self.model = model\n    self.model_config = model.config\n    self.train_dataset=train\n    self.test_dataset=test\n    self.device=\"cpu\"\n    if torch.cuda.is_available():\n      self.device=torch.cuda.current_device()\n      self.model=torch.nn.DataParallel(self.model).to(self.device)\n      print(\"Model is now CUDA!\")\n\n  def save_checkpoint(self, ckpt_path=None):\n    raw_model=self.model.module if hasattr(self.model, \"module\") else self.model\n    ckpt_path=ckpt_path if ckpt_path is not None else self.config.ckpt_path\n    print(f\"Saving Model at {ckpt_path}\")\n    torch.save(raw_model.state_dict(), ckpt_path)\n\n  def norm_img(self, img):\n    img -= img.min()\n    img /= img.max()\n    return img\n\n  def train(\n    self,\n    batch_size,\n    n_epochs,\n    lr,\n    folder_path,\n    skip_steps,\n    weight_decay = 1e-3,\n    warmup_perc=0.05,\n    test_every=1000,\n    test_batch_size=None,\n    patience=5,\n    gradient_accumulation_steps: int=1,\n  ):\n    model = self.model\n    model_config = self.model_config\n    train_data = self.train_dataset\n    test_data = self.test_dataset\n    epoch_step = len(train_data) // batch_size + int(len(train_data) % batch_size != 0)\n\n\n    gs = 0                 # global step counter\n    train_losses = [-1]    # list with values of training losses at each step\n    do_skip = True         # flag for one time skipping steps during training\n    min_test_loss = 10000  # any large value for the minimum test loss yer achieved\n    patience_counter = 0   # counter for matching the patience\n    break_training = False # flag is set when we run out of patience and want to break\n                           # training for outer loop as well\n    model.train()          # set model to training mode\n    _lr = 0                # set rolling _lr for logging dict\n    \n    # number of steps and warmup for LR scheduling\n    total_steps = int(epoch_step * n_epochs)\n    warmup_steps = int(warmup_perc * total_steps)\n    \n    print(f\"Warmup/Total: [{warmup_steps}/{total_steps}] | Perc: {warmup_steps/total_steps:.3f} ({warmup_perc})\")\n\n    # VAE is not to be optimised, named_parameters() gives more control\n    # optim = torch.optim.Adam(\n    #   (p for n, p in dalle.named_parameters() if \"vae\" not in n),\n    #   lr=lr\n    # )\n    optim = configure_optimizers(model, 1., weight_decay, betas = (0.9, 0.99))\n\n    # NOAM scheme from \"Attention is all you need\"\n    lr_lambda_fn = lambda gs: (model_config.n_embd ** -0.5) * min ((gs + 1) ** -0.5, (gs + 1) * (warmup_steps ** -1.5))\n    lr_scheduler = torch.optim.lr_scheduler.LambdaLR(optim, lr_lambda_fn, last_epoch=-1, verbose=False)\n    \n    if gradient_accumulation_steps > 1:\n      eff_batch_size = gradient_accumulation_steps * batch_size\n      print(\":: Due to presence of gradient_accumulation_steps effective size:\", eff_batch_size)\n\n    for epoch in range(n_epochs):\n      # ----- train for one complete epoch\n      dl = DataLoader(\n          dataset=train_data,\n          batch_size=batch_size,\n          pin_memory=True,    # for CUDA\n          shuffle=True,       # of course, my stupid ass didn't do it for first 74 runs\n          num_workers=8       # number of workers for parallel loading\n      )\n      pbar = trange(epoch_step)\n      model.zero_grad()\n\n      for d, loop_idx in zip(dl, pbar):\n        # don't train if we need to skip some steps but we do not want\n        # it to skip for all the future epochs and so we add `do_skip` flag\n        if skip_steps and loop_idx < skip_steps and do_skip:\n          lr_scheduler.step() # lr also needs to be correct\n          continue\n        do_skip = False\n\n        # train the model\n        d = {k: v.to(self.device) for k,v in d.items()}\n        pbar.set_description(f\"[TRAIN - {epoch}] GS: {gs}, Loss: {round(train_losses[-1], 5)}\")\n        _, loss = model(**d, loss = True)\n        loss = loss.mean()  # gather from multiple GPUs\n        log_dict = {\"loss\": loss.item()}\n\n        # backprop gradient acc. code:\n        # https://gist.github.com/thomwolf/ac7a7da6b1888c2eeac8ac8b9b05d3d3\n        loss = loss / gradient_accumulation_steps\n        loss.backward()\n        if gs and gs % gradient_accumulation_steps == 0:\n          torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n          optim.step()\n\n          # this needs to be done before each back prop so that gradients are pointing\n          # in the intended minimum. because this needs to be done before each loss.backward() pass\n          # I do it at the end of each step because in loop id would behave the same\n          # https://stackoverflow.com/questions/48001598/why-do-we-need-to-call-zero-grad-in-pytorch\n          model.zero_grad()\n          # ------ update ends\n\n        # # decay based on our progress of training, picked from\n        # # https://github.com/karpathy/minGPT/blob/master/mingpt/trainer.py\n        # # since we are processing a fixed number of tokens in each step unlike LM-GPT\n        # # we can let go of counting the processed tokens and instead just focus on the\n        # # global steps processed\n        # if gs < warmup_steps:\n        #   # linear warmup\n        #   lr_mult = gs / max(1, warmup_steps)\n        # else:\n        #   # cosine decay\n        #   progress = (gs - warmup_steps) / max(1, total_steps - warmup_steps)\n        #   lr_mult = max(0.1, 0.5 * (1.0 + math.cos(math.pi * progress)))\n\n        # _lr = lr * lr_mult\n        # for param_group in optim.param_groups:\n        #   param_group['lr'] = _lr\n\n        lr_scheduler.step()\n        _lr = lr_scheduler.get_last_lr()[0]\n\n        gs += 1\n        train_losses.append(loss.item() * gradient_accumulation_steps)\n        log_dict.update({\"lr\": _lr})\n\n        # ----- test loop\n        if test_data != None and gs and gs % test_every == 0:\n          print(\":: Entering Testing Mode\")\n          if test_batch_size is None:\n            test_batch_size = batch_size * 4\n          dl=DataLoader(\n            dataset=test_data,\n            batch_size=test_batch_size, # testing can run larger batches\n            pin_memory=True,            # for CUDA\n            shuffle=False,              # to ensure we can see the progress being made\n            num_workers=8               # number of workers for parallel loading\n          )\n          model.zero_grad() # remove any gradients from the model\n          model.eval()      # convert model to testing mode\n\n          epoch_step_test=len(test_data) // test_batch_size + int(len(test_data) % test_batch_size != 0)\n          pbar_test=trange(epoch_step_test)\n          test_loss=[]\n          for d, e in zip(dl, pbar_test):\n            d = {k: v.to(self.device) for k, v in d.items()}\n            pbar_test.set_description(f\"[TEST - {epoch}]\")\n            with torch.no_grad():\n              _, loss, gen_images = model(**d, loss=True, recons = True)\n            loss=loss.mean() # gather from multiple GPUs\n            test_loss.append(loss.item())\n\n          # now create samples of the images and\n          fig=plt.figure(figsize=(20, 7))\n          captions_text = test_data.decode(d[\"text_tokens\"][:10])\n          for _i, (i, o, c) in enumerate(zip(d[\"images\"][:10], gen_images[:10], captions_text)):\n            i=self.norm_img(i.permute(1, 2, 0).cpu().numpy())\n            o=self.norm_img(o.permute(1, 2, 0).cpu().numpy())\n            plt.subplot(2, 10, _i + 1)\n            plt.imshow(i)\n            plt.subplot(2, 10, _i + 10 + 1)\n            plt.imshow(o)\n            plt.title(\"\\n\".join(wrap(c, 20))[:100]) # should be at last\n          plt.tight_layout()\n          plt.savefig(f\"{folder_path}/sample_{gs}.png\")\n          del fig # delete and save the warning\n\n          test_loss = np.mean(test_loss)\n          log_dict.update({\"test_loss\": test_loss})\n          print(\":::: Loss:\", test_loss)\n\n          if min_test_loss > test_loss:\n            print(\":: Previous loss was larger, updating value\")\n            min_test_loss = test_loss\n            patience_counter = 0\n            self.save_checkpoint(ckpt_path=f\"{folder_path}/dalle_{gs}.pt\")\n\n          else:\n            print(\":: Previous loss was smaller, updating value\")\n            patience_counter += 1\n\n          if patience_counter == patience:\n            print(\":: Ran out of patience, stopping training\")\n            break_training = True\n            break\n          model.train()  # convert model back to training mode\n\n        # ------ testing `if` ends\n        if WANDB:\n          wandb.log(log_dict)\n        else:\n          print(log_dict)\n\n        if break_training: break\n      # ------ epoch loop ends\n    \n      if break_training: break\n    # ------ training loop ends\n\n\nif __name__ == \"__main__\":\n  args = ArgumentParser(description= \"train DallE transformer model\")\n  args.add_argument(\"--vqvae\", type=str, default=\"./vqvae3_128_325_3025_0_ckpt_30600.pt\", help=\"path to the VQVAE_v3 model file\")\n  args.add_argument(\"--tokenizer\", type=str, default=\"../tokenizer.json\", help=\"path to the tokenizer\")\n  args.add_argument(\"--model_path\", type=str, default=\"./dalle2_128_576_36_12_6/dalle_48000.pt\", help=\"path to pretrained model\")\n  args.add_argument(\"--captions\", type=str, default=\"../captions_train.json\", help=\"path to captions file\")\n  args.add_argument(\"--text_context_len\", type=int, default=128, help=\"number of tokens in the text\")\n  args.add_argument(\"--n_embd\", type=int, default=576, help=\"embedding dimension of the model\")\n  args.add_argument(\"--n_layers\", type=int, default=36, help=\"number of attention layers\")\n  args.add_argument(\"--n_heads\", type=int, default=12, help=\"number of heads in MHA\")\n  args.add_argument(\"--batch_size\", type=int, default=6, help=\"minibatch size\")\n  args.add_argument(\"--n_epochs\", type=int, default=2, help=\"number of epochs to train for\")\n  args.add_argument(\"--lr\", type=int, default=1e-4, help=\"learning rate\")\n  args.add_argument(\"--gas\", type=int, default=30, help=\"gradient accumulation steps\")\n  args.add_argument(\"--seed\", type=int, default=3, help=\"seed value\")  # 3 = my misha\n  args.add_argument(\"--test_every\", type=int, default=4000, help=\"test every this steps\")\n  args.add_argument(\"--patience\", type=int, default=2, help=\"stop training if no improvement in this steps\")\n  args = args.parse_args()\n\n  # set seed to ensure everything is properly split\n  vqvae_arch = Vqvae.infer_details_from_name(args.vqvae)\n  set_seed(args.seed)\n  folder_path = f\"./dalle2_{vqvae_arch.input_res}_{args.n_embd}_\" +\\\n      f\"{args.n_layers}_{args.n_heads}_{args.batch_size}\"\n  print(f\":: Will Save data in {folder_path}\")\n  os.makedirs(folder_path, exist_ok=True)\n\n  train_split = 0.995\n  train_keys, test_keys = DallECaptions.get_split(\n      captions_file=args.captions, train_split=train_split)\n  dallecaptions_train = DallECaptions(\n    captions_file=args.captions,\n    tokenizer_path=args.tokenizer,\n    res=vqvae_arch.input_res,\n    keys=train_keys,\n    text_context_len=args.text_context_len,\n  )\n  dallecaptions_test = DallECaptions(\n    captions_file=args.captions,\n    tokenizer_path=args.tokenizer,\n    res=vqvae_arch.input_res,\n    keys=test_keys,\n    text_context_len=args.text_context_len,\n  )\n  print(\"Train Size:\", len(dallecaptions_train), \"; Test Size:\", len(dallecaptions_test))\n\n  # mapping for <res>: <encoded_res>\n  resmap = {\n    128: 16\n  }\n\n  # define the model\n  model = Vqvae(args.vqvae)\n  transformer_config = TransformerConfig(\n    text_context_len=args.text_context_len,\n    image_context_len=int(resmap[vqvae_arch.input_res]**2),\n    text_vocab_size=dallecaptions_train.tok.get_vocab_size(),\n    image_vocab_size=model.num_embeddings,\n    n_embd=args.n_embd,\n    n_layers=args.n_layers,\n    n_heads=args.n_heads\n  )\n  dalle = DallETransformer(model.get_model(), transformer_config)\n  init_weights(dalle) # init weights manually\n  print(\":: Number of params:\", sum(p.numel() for p in dalle.parameters()))\n\n  if args.model_path is not None:\n    dalle.load_state_dict(torch.load(args.model_path))\n\n  if WANDB:\n    wandb.init(project=\"dall-e\", resume = True)\n    wandb.watch(dalle) # watch the model metrics\n\n  # define the trainer\n  trainer = DallETrainer(dallecaptions_train, dallecaptions_test, dalle)\n  trainer.train(\n    batch_size=args.batch_size,\n    n_epochs=args.n_epochs,\n    lr=args.lr,\n    skip_steps=48000,\n    test_every=args.test_every,\n    patience=args.patience,\n    gradient_accumulation_steps=args.gas,\n    folder_path=folder_path,\n    weight_decay=0.01,\n    warmup_perc=0.01,\n  )\n", "meta": {"hexsha": "b31a160c52bc91c56abbf427974d86f4db7de732", "size": 32182, "ext": "py", "lang": "Python", "max_stars_repo_path": "dalle.py", "max_stars_repo_name": "yashbonde/dall-e-baby", "max_stars_repo_head_hexsha": "92f53be31ece8450d7ec31bfcf69e93ad536e7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2021-03-03T09:58:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T12:50:33.000Z", "max_issues_repo_path": "dalle.py", "max_issues_repo_name": "yashbonde/dall-e-baby", "max_issues_repo_head_hexsha": "92f53be31ece8450d7ec31bfcf69e93ad536e7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-02-14T22:09:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-29T14:21:03.000Z", "max_forks_repo_path": "dalle.py", "max_forks_repo_name": "yashbonde/dall-e-baby", "max_forks_repo_head_hexsha": "92f53be31ece8450d7ec31bfcf69e93ad536e7dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-17T17:18:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-12T08:43:50.000Z", "avg_line_length": 38.495215311, "max_line_length": 130, "alphanum_fraction": 0.660089491, "include": true, "reason": "import numpy", "num_tokens": 8209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.515619900836397, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.17431929322928028}}
{"text": "# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2020, the cclib development team\n#\n# This file is part of cclib (http://cclib.github.io) and is distributed under\n# the terms of the BSD 3-Clause License.\n\n\"\"\"Stockholder partitioning based on cclib data.\"\"\"\nimport copy\nimport random\nimport numpy\nimport logging\nimport math\nimport os\nimport sys\n\nfrom cclib.method.calculationmethod import Method\nfrom cclib.method.volume import electrondensity_spin\nfrom cclib.parser.utils import convertor\nfrom cclib.parser.utils import find_package\n\nfrom typing import List\n\n\nclass MissingInputError(Exception):\n    pass\n\n\nclass Stockholder(Method):\n    \"\"\"An abstract base class for stockholder-type methods.\"\"\"\n\n    # All of these are required for stockholder-type charges.\n    required_attrs = (\"homos\", \"mocoeffs\", \"nbasis\", \"gbasis\")\n\n    def __init__(\n        self,\n        data,\n        volume,\n        proatom_path=None,\n        progress=None,\n        loglevel=logging.INFO,\n        logname=\"Log\",\n    ):\n        \"\"\" Initialize Stockholder-type method object.\n            Inputs are:\n                data -- ccData object that describe target molecule.\n                volume -- Volume object that describe target Cartesian grid.\n                proatom_path -- path to proatom densities\n                (directory containing atoms.h5 in horton or c2_001_001_000_400_075.txt in chargemol)\n        \"\"\"\n        super(Stockholder, self).__init__(data, progress, loglevel, logname)\n\n        self.volume = volume\n        self.proatom_path = proatom_path\n\n        # Check whether proatom_path is a valid directory or not.\n        assert os.path.isdir(\n            proatom_path\n        ), \"Directory that contains proatom densities should be added as an input.\"\n\n        # Read in reference charges.\n        self.proatom_density = []\n        self.radial_grid_r = []\n        for atom_number in self.data.atomnos:\n            density, r = self._read_proatom(self.proatom_path, atom_number, 0)\n            self.proatom_density.append(density)\n            self.radial_grid_r.append(r)\n\n    def __str__(self):\n        \"\"\"Return a string representation of the object.\"\"\"\n        return \"Stockholder\"\n\n    def __repr__(self):\n        \"\"\"Return a representation of the object.\"\"\"\n        return \"Stockholder\"\n\n    def _check_required_attributes(self):\n        super(Stockholder, self)._check_required_attributes()\n\n    def _read_proatom(\n        self, directory, atom_num, charge  # type = str  # type = int  # type = float\n    ):\n        # type: (...) -> numpy.ndarray, numpy.ndarray\n        \"\"\"Return a list containing proatom reference densities.\"\"\"\n        # TODO: Treat calculations with psuedopotentials\n        # TODO: Modify so that proatom densities are read only once for horton\n        #       [https://github.com/cclib/cclib/pull/914#discussion_r464039991]\n        # File name format:\n        #   ** Chargemol **\n        #       c2_[atom number]_[nuclear charge]_[electron count]_[cutoff radius]_[# shells]\n        #   ** Horton **\n        #       atoms.h5\n        # File format:\n        #   Starting from line 13, each line contains the charge densities for each shell\n        # If `charge` is not an integer, proatom densities have to be linearly interpolated between\n        # the densities of the ion/atom with floor(charge) and ceiling(charge)\n        charge_floor = int(math.floor(charge))\n        charge_ceil = int(math.ceil(charge))\n\n        chargemol_path_floor = os.path.join(\n            directory,\n            \"c2_{:03d}_{:03d}_{:03d}_500_100.txt\".format(\n                atom_num, atom_num, atom_num - charge_floor\n            ),\n        )\n        chargemol_path_ceil = os.path.join(\n            directory,\n            \"c2_{:03d}_{:03d}_{:03d}_500_100.txt\".format(\n                atom_num, atom_num, atom_num - charge_ceil\n            ),\n        )\n        horton_path = os.path.join(directory, \"atoms.h5\")\n\n        if os.path.isfile(chargemol_path_floor) or os.path.isfile(chargemol_path_ceil):\n            # Use chargemol proatom densities\n            # Each shell is .05 angstroms apart (uniform).\n            # *scalefactor* = 10.58354497764173 bohrs in module_global_parameter.f08\n            if atom_num <= charge_floor:\n                density_floor = numpy.array([0])\n            else:\n                density_floor = numpy.loadtxt(chargemol_path_floor, skiprows=12, dtype=float)\n            if atom_num >= charge_ceil:\n                density_ceil = numpy.array([0])\n            else:\n                density_ceil = numpy.loadtxt(chargemol_path_ceil, skiprows=12, dtype=float)\n\n            density = (charge_ceil - charge) * density_floor + (\n                charge - charge_floor\n            ) * density_ceil\n            radiusgrid = numpy.arange(1, len(density) + 1) * 0.05\n\n        elif os.path.isfile(horton_path):\n            # Use horton proatom densities\n            assert find_package(\"h5py\"), \"h5py is needed to read in proatom densities from horton.\"\n\n            import h5py\n\n            with h5py.File(horton_path, \"r\") as proatomdb:\n                if atom_num <= charge_floor:\n                    density_floor = numpy.array([0])\n                    radiusgrid = numpy.array([0])\n                else:\n                    keystring_floor = \"Z={}_Q={:+d}\".format(atom_num, charge_floor)\n                    density_floor = numpy.asanyarray(list(proatomdb[keystring_floor][\"rho\"]))\n\n                    # gridspec is specification of integration grid for proatom densities in horton.\n                    # Example -- ['PowerRTransform', '1.1774580743206259e-07', '20.140888089596444', '41']\n                    #   is constructed using PowerRTransform grid\n                    #   with rmin = 1.1774580743206259e-07\n                    #        rmax = 20.140888089596444\n                    #   and  ngrid = 41\n                    # PowerRTransform is default in horton-atomdb.py.\n                    gridtype, gridmin, gridmax, gridn = (\n                        proatomdb[keystring_floor].attrs[\"rtransform\"].split()\n                    )\n                    gridmin = convertor(float(gridmin), \"bohr\", \"Angstrom\")\n                    gridmax = convertor(float(gridmax), \"bohr\", \"Angstrom\")\n                    gridn = int(gridn)\n                    # Convert byte to string in Python3\n                    if sys.version[0] == \"3\":\n                        gridtype = gridtype.decode(\"UTF-8\")\n\n                    # First verify that it is one of recognized grids\n                    assert gridtype in [\n                        \"LinearRTransform\",\n                        \"ExpRTransform\",\n                        \"PowerRTransform\",\n                    ], \"Grid type not recognized.\"\n\n                    if gridtype == \"LinearRTransform\":\n                        # Linear transformation. r(t) = rmin + t*(rmax - rmin)/(npoint - 1)\n                        gridcoeff = (gridmax - gridmin) / (gridn - 1)\n                        radiusgrid = gridmin + numpy.arange(1, gridn + 1) * gridcoeff\n                    elif gridtype == \"ExpRTransform\":\n                        # Exponential transformation. r(t) = rmin*exp(t*log(rmax/rmin)/(npoint - 1))\n                        gridcoeff = math.log(gridmax / gridmin) / (gridn - 1)\n                        radiusgrid = gridmin * numpy.exp(numpy.arange(1, gridn + 1) * gridcoeff)\n                    elif gridtype == \"PowerRTransform\":\n                        # Power transformation. r(t) = rmin*t^power\n                        # with  power = log(rmax/rmin)/log(npoint)\n                        gridcoeff = math.log(gridmax / gridmin) / math.log(gridn)\n                        radiusgrid = gridmin * numpy.power(numpy.arange(1, gridn + 1), gridcoeff)\n\n                if atom_num <= charge_ceil:\n                    density_ceil = numpy.array([0])\n                else:\n                    keystring_ceil = \"Z={}_Q={:+d}\".format(atom_num, charge_ceil)\n                    density_ceil = numpy.asanyarray(list(proatomdb[keystring_ceil][\"rho\"]))\n\n                density = (charge_ceil - charge) * density_floor + (\n                    charge - charge_floor\n                ) * density_ceil\n\n                del h5py\n\n        else:\n            raise MissingInputError(\"Pro-atom densities were not found in the specified path.\")\n\n        if charge == charge_floor:\n            density = density_floor\n\n        return density, radiusgrid\n\n    def calculate(self, indices=None, fupdate=0.05):\n        \"\"\" Charge density on a Cartesian grid is a common routine required for Stockholder-type\n            and related methods. This abstract class prepares the grid if input Volume object\n            is empty.\n        \"\"\"\n        # Obtain charge densities on the grid if it does not contain one.\n        if not numpy.any(self.volume.data):\n            self.logger.info(\"Calculating charge densities on the provided empty grid.\")\n            if len(self.data.mocoeffs) == 1:\n                self.charge_density = electrondensity_spin(\n                    self.data, self.volume, [self.data.mocoeffs[0][: self.data.homos[0] + 1]]\n                )\n                self.charge_density.data *= 2\n            else:\n                self.charge_density = electrondensity_spin(\n                    self.data,\n                    self.volume,\n                    [\n                        self.data.mocoeffs[0][: self.data.homos[0] + 1],\n                        self.data.mocoeffs[1][: self.data.homos[1] + 1],\n                    ],\n                )\n        # If charge densities are provided beforehand, log this information\n        # `Volume` object does not contain (nor rely on) information about the constituent atoms.\n        else:\n            self.logger.info(\"Using charge densities from the provided Volume object.\")\n            self.charge_density = self.volume\n", "meta": {"hexsha": "5da30feef79cb009a5b7545e4e728eaf975ff606", "size": 9811, "ext": "py", "lang": "Python", "max_stars_repo_path": "cclib/method/stockholder.py", "max_stars_repo_name": "eimrek/cclib", "max_stars_repo_head_hexsha": "6e8eab4226fd976dfb105d71ae11a8bd01ca12d0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-12T09:08:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-12T09:08:49.000Z", "max_issues_repo_path": "cclib/method/stockholder.py", "max_issues_repo_name": "eimrek/cclib", "max_issues_repo_head_hexsha": "6e8eab4226fd976dfb105d71ae11a8bd01ca12d0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cclib/method/stockholder.py", "max_forks_repo_name": "eimrek/cclib", "max_forks_repo_head_hexsha": "6e8eab4226fd976dfb105d71ae11a8bd01ca12d0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4718614719, "max_line_length": 106, "alphanum_fraction": 0.5706859647, "include": true, "reason": "import numpy", "num_tokens": 2198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.33807711081162, "lm_q1q2_score": 0.17431929138456814}}
{"text": "\"\"\"\nTo be able to use this script you need to either:\n* Run `python setup.py build_ext --inplace` or\n* install via `pip install -e .`\n\nOriginal Source: https://github.com/fizyr/keras-retinanet\n\"\"\"\n\nimport numpy as np\nimport keras\n\n#from .anchor import bbox_transform\nfrom ..utils.compute_overlap import compute_overlap\n\ndef bbox_transform(anchors, gt_boxes, mean=None, std=None):\n    \"\"\"Compute bounding-box regression targets for an image.\"\"\"\n\n    if mean is None:\n        mean = np.array([0, 0, 0, 0])\n    if std is None:\n        std = np.array([0.2, 0.2, 0.2, 0.2])\n\n    if isinstance(mean, (list, tuple)):\n        mean = np.array(mean)\n    elif not isinstance(mean, np.ndarray):\n        raise ValueError('Expected mean to be a np.ndarray, list or tuple. Received: {}'.format(type(mean)))\n\n    if isinstance(std, (list, tuple)):\n        std = np.array(std)\n    elif not isinstance(std, np.ndarray):\n        raise ValueError('Expected std to be a np.ndarray, list or tuple. Received: {}'.format(type(std)))\n\n    anchor_widths  = anchors[:, 2] - anchors[:, 0]\n    anchor_heights = anchors[:, 3] - anchors[:, 1]\n\n    targets_dx1 = (gt_boxes[:, 0] - anchors[:, 0]) / anchor_widths\n    targets_dy1 = (gt_boxes[:, 1] - anchors[:, 1]) / anchor_heights\n    targets_dx2 = (gt_boxes[:, 2] - anchors[:, 2]) / anchor_widths\n    targets_dy2 = (gt_boxes[:, 3] - anchors[:, 3]) / anchor_heights\n\n    targets = np.stack((targets_dx1, targets_dy1, targets_dx2, targets_dy2))\n    targets = targets.T\n\n    targets = (targets - mean) / std\n\n    return targets\n\ndef anchor_targets_bbox(\n    anchors,\n    image_group,\n    annotations_group,\n    num_classes,\n    negative_overlap=0.4,\n    positive_overlap=0.5,\n    distance=False,\n    distance_scaling=100\n):\n    \"\"\" Generate anchor targets for bbox detection.\n\n    Args\n        anchors: np.array of annotations of shape (N, 4) for (x1, y1, x2, y2).\n        image_group: List of BGR images.\n        annotations_group: List of annotations (np.array of shape (N, 5) for (x1, y1, x2, y2, label)).\n        num_classes: Number of classes to predict.\n        mask_shape: If the image is padded with zeros, mask_shape can be used to mark the relevant part of the image.\n        negative_overlap: IoU overlap for negative anchors (all anchors with overlap < negative_overlap are negative).\n        positive_overlap: IoU overlap or positive anchors (all anchors with overlap > positive_overlap are positive).\n\n    Returns\n        labels_batch: batch that contains labels & anchor states (np.array of shape (batch_size, N, num_classes + 1),\n                      where N is the number of anchors for an image and the last column defines the anchor state (-1 for ignore, 0 for bg, 1 for fg).\n        regression_batch: batch that contains bounding-box regression targets for an image & anchor states (np.array of shape (batch_size, N, 4 + 1),\n                      where N is the number of anchors for an image, the first 4 columns define regression targets for (x1, y1, x2, y2) and the\n                      last column defines anchor states (-1 for ignore, 0 for bg, 1 for fg).\n    \"\"\"\n\n    assert(len(image_group) == len(annotations_group)), \"The length of the images and annotations need to be equal.\"\n    assert(len(annotations_group) > 0), \"No data received to compute anchor targets for.\"\n    for annotations in annotations_group:\n        assert('bboxes' in annotations), \"Annotations should contain bboxes.\"\n        assert('labels' in annotations), \"Annotations should contain labels.\"\n\n    batch_size = len(image_group)\n\n    regression_batch  = np.zeros((batch_size, anchors.shape[0], 4 + 1), dtype=keras.backend.floatx())\n    labels_batch      = np.zeros((batch_size, anchors.shape[0], num_classes + 1), dtype=keras.backend.floatx())\n    distance_batch      = np.zeros((batch_size, anchors.shape[0], 1 + 1), dtype=keras.backend.floatx())\n\n    # compute labels and regression targets\n    for index, (image, annotations) in enumerate(zip(image_group, annotations_group)):\n        if annotations['bboxes'].shape[0]:\n            # obtain indices of gt annotations with the greatest overlap\n            positive_indices, ignore_indices, argmax_overlaps_inds = compute_gt_annotations(anchors, annotations['bboxes'], negative_overlap, positive_overlap)\n\n            labels_batch[index, ignore_indices, -1]       = -1\n            labels_batch[index, positive_indices, -1]     = 1\n\n            regression_batch[index, ignore_indices, -1]   = -1\n            regression_batch[index, positive_indices, -1] = 1\n\n            distance_batch[index, ignore_indices, -1]   = -1\n            distance_batch[index, positive_indices, -1] = 1\n\n            # compute target class labels\n            pos_overlap_inds = [argmax_overlaps_inds[positive_indices]]\n            label_indices = annotations['labels'][tuple(pos_overlap_inds)].astype(int)\n            \n            labels_batch[index, positive_indices, label_indices] = 1\n\n            regression_batch[index, :, :-1] = bbox_transform(anchors, annotations['bboxes'][argmax_overlaps_inds, :])\n\n\n            if distance:\n                distance_batch[index, positive_indices, 0] = annotations['distances'][pos_overlap_inds[0][:]]/distance_scaling\n            \n    \n        # ignore annotations outside of image\n        if image.shape:\n            anchors_centers = np.vstack([(anchors[:, 0] + anchors[:, 2]) / 2, (anchors[:, 1] + anchors[:, 3]) / 2]).T\n            indices = np.logical_or(anchors_centers[:, 0] >= image.shape[1], anchors_centers[:, 1] >= image.shape[0])\n\n            labels_batch[index, indices, -1]     = -1\n            regression_batch[index, indices, -1] = -1\n            distance_batch[index, indices, -1]   = -1\n    if distance:\n        return regression_batch, labels_batch, distance_batch\n    else:\n        return regression_batch, labels_batch\n\n\ndef compute_gt_annotations(\n    anchors,\n    annotations,\n    negative_overlap=0.4,\n    positive_overlap=0.5\n    ):\n    \"\"\" Obtain indices of gt annotations with the greatest overlap.\n\n    Args\n        anchors: np.array of annotations of shape (N, 4) for (x1, y1, x2, y2).\n        annotations: np.array of shape (N, 5) for (x1, y1, x2, y2, label).\n        negative_overlap: IoU overlap for negative anchors (all anchors with overlap < negative_overlap are negative).\n        positive_overlap: IoU overlap or positive anchors (all anchors with overlap > positive_overlap are positive).\n\n    Returns\n        positive_indices: indices of positive anchors\n        ignore_indices: indices of ignored anchors\n        argmax_overlaps_inds: ordered overlaps indices\n    \"\"\"\n\n    overlaps = compute_overlap(anchors.astype(np.float64), annotations.astype(np.float64))\n    argmax_overlaps_inds = np.argmax(overlaps, axis=1)\n    max_overlaps = overlaps[np.arange(overlaps.shape[0]), argmax_overlaps_inds]\n\n    # assign \"dont care\" labels\n    positive_indices = max_overlaps >= positive_overlap\n    ignore_indices = (max_overlaps > negative_overlap) & ~positive_indices\n\n    return positive_indices, ignore_indices, argmax_overlaps_inds\n\n\n", "meta": {"hexsha": "97c7302b123564c0b86d44b88019d6c4388a5be6", "size": 7055, "ext": "py", "lang": "Python", "max_stars_repo_path": "crfnet/utils/anchor_calc.py", "max_stars_repo_name": "XiaoJake/CameraRadarFusionNet", "max_stars_repo_head_hexsha": "5506700c21ecda8de7cbbfa0cff25413fbcb2a96", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 256, "max_stars_repo_stars_event_min_datetime": "2020-01-20T08:45:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:13:16.000Z", "max_issues_repo_path": "crfnet/utils/anchor_calc.py", "max_issues_repo_name": "XiaoJake/CameraRadarFusionNet", "max_issues_repo_head_hexsha": "5506700c21ecda8de7cbbfa0cff25413fbcb2a96", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 31, "max_issues_repo_issues_event_min_datetime": "2020-02-01T00:23:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T18:08:25.000Z", "max_forks_repo_path": "crfnet/utils/anchor_calc.py", "max_forks_repo_name": "XiaoJake/CameraRadarFusionNet", "max_forks_repo_head_hexsha": "5506700c21ecda8de7cbbfa0cff25413fbcb2a96", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 102, "max_forks_repo_forks_event_min_datetime": "2020-01-20T12:44:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T06:36:24.000Z", "avg_line_length": 43.549382716, "max_line_length": 159, "alphanum_fraction": 0.6687455705, "include": true, "reason": "import numpy", "num_tokens": 1702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283033, "lm_q2_score": 0.278256793702402, "lm_q1q2_score": 0.1742233060151022}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n@ PyCAMP  Python Causal Modeling of Pathways, a python implmentation for modeling\ncausal relationship bewtween cellular signaling proteins, particularly phosphorylated\nproteins based on reverse phase protein array (RPPA) data.  This model is designed\nto model the signal transduction through series of protein phosphorylation cascade,\nin which phosphorylation of a protein often activate the protein, which in turn\nlead to phosphorylation of other proteins.  This model represent\nthe phosphorylation state(s) and activation state of a protein separately such that the model\nis capable of capture the fact that, at certain time, phosphorylation of a protein\ncan be decoupled by drug and inhibitors. \n\n\nCreated on Wed Aug 14 19:16:25 2013\n\n@author: Xinghua  Lu\n\"\"\"\n\nimport networkx as nx\nimport numpy as np\nfrom numpy import matlib\nfrom rpy2 import robjects \nimport  math, cPickle, re\nfrom SigNetNode import SigNetNode\nfrom StringIO import StringIO\nfrom NamedMatrix import NamedMatrix\nfrom SteinerTree import *\n\nimport rpy2.robjects.numpy2ri\nrpy2.robjects.numpy2ri.activate()   # enable directly pass numpy arrary or matrix as arguments to rpy object\nR = robjects.r                      # load R instance\nR.library(\"glmnet\")\nglmnet = R('glmnet')                # make glmnet from R a callable python object\n\nR.library(\"mixtools\")\nnormalmixEM = R('normalmixEM')\n\n\n\nclass PyGibbCAMP:  \n    ## Constructor\n    #  @param nodeFile  A string of pathname of file containing nodes.  The \n    #                   name, type, measured\n    #  @param edgeFile  A list of tuples, each containing a source and sink node \n    #                   of an edge\n    #  @param dataMatrixFile  A string to data\n    def __init__(self, nodeFile , dataMatrixFile , perturbMatrix = None, missingDataMatrix=None):\n        self.network = None\n        self.obsData = None\n        self.missingDataMatrix = None\n        perturbInstances = None\n        self.nChains = 1\n        \n        self.dictPerturbEffect = {'AKT1' : [('GSK690693',\t0), \\\n        ('GSK690693_GSK1120212', 0)], 'MAP2K1' : [('GSK690693_GSK1120212', 0)],\\\n        'EGFR': [('EGF' , 1), ('FGF1', 1)]}\n#        self.stimuli = ['EGF',\t'FGF1',\t'HGF',\t'IGF1', 'Insulin',\t'NRG1',\t'PBS',\t'Serum']\n\n        # parse data mastrix by calling NamedMatrix class\n        if not dataMatrixFile:\n            raise Exception(\"Cannot create PyCAMP obj without 'dataMatrixFile'\")\n            return\n        self.obsData = NamedMatrix(dataMatrixFile)\n        nCases, nAntibodies = np.shape(self.obsData.data)\n        self.obsData.colnames = map(lambda s: s+'F', self.obsData.colnames)\n        self.obsDataFileName = dataMatrixFile\n        \n        if perturbMatrix:        \n            self.perturbData = NamedMatrix(perturbMatrix)\n            perturbInstances = self.perturbData.getColnames()\n            self.perturbInstances = perturbInstances\n                    \n        if missingDataMatrix:\n            self.missingDataMatrix = NamedMatrix(missingDataMatrix)\n            allMissing = np.sum(self.missingDataMatrix, 0) ==  nCases\n            if np.any(allMissing):\n                raise Exception (\"Data matrix contain data-less columns\")\n            self.missingDataMatrix.colnames = map(lambda s: s+'F', self.missingDataMatrix.colnames)\n\n        if not nodeFile:\n            raise Exception(\"Calling 'intiNetwork' with empty nodeFile name\")\n            return\n\n        try:\n            nf = open(nodeFile, \"r\")\n            nodeLines = nf.readlines()\n            if len(nodeLines) == 1:  # Mac files end a line with \\r instead of \\n\n                nodeLines = nodeLines[0].split(\"\\r\")\n            nf.close()\n        except IOError:\n            raise Exception( \"Failed to open the file containing nodes\")\n            return\n            \n        print \"Creating network\"          \n        self.network = nx.DiGraph()\n\n        self.dictProteinToAntibody = dict()\n        self.dictAntibodyToProtein = dict()\n        # parse nodes\n        for line in nodeLines:\n            #print line\n            protein, antibody = line.rstrip().split(',')\n            \n            if protein not in self.dictProteinToAntibody:\n                self.dictProteinToAntibody[protein] = []\n            self.dictProteinToAntibody[protein].append(antibody)\n            self.dictAntibodyToProtein[antibody] = protein\n            \n            fluo = antibody + 'F'\n            if protein not in self.network:\n                self.network.add_node(protein, nodeObj = SigNetNode(protein, 'ACTIVATIONSTATE', False))\n            self.network.add_node(antibody, nodeObj= SigNetNode(antibody, 'PHOSPHORYLATIONSTATE', False))\n            self.network.add_node(fluo, nodeObj = SigNetNode(fluo, 'FLUORESCENCE', True))\n            self.network.add_edge(antibody, protein)\n            self.network.add_edge(antibody, fluo)\n        \n        for perturb in perturbInstances:\n            self.network.add_node(perturb, nodeObj = SigNetNode(perturb, 'PERTURBATION', True))                \n            \n        # Add edges between PERTURBATION, protein activity,and  phosphorylation layers \n        for pro in self.dictProteinToAntibody:\n            for phos in self.dictAntibodyToProtein:\n                if self.dictAntibodyToProtein[phos] == pro:\n                    continue\n                self.network.add_edge(pro, phos)\n            for perturb in perturbInstances:\n                self.network.add_edge(perturb, pro)\n            \n        \n    ## Init parameters of the model\n    #  In Bayesian network setting, the joint probability is calculated\n    #  through the product of a series conditional probability.  The parameters\n    #  of the PyCAMP model defines p(x | Pa(X)).  For observed fluorescent node\n    #  the conditional probability is a mixture of two Gaussian distribution.  \n    #  therefore, the parameters are two pairs of mu and sigma.  For\n    #  the hidden variables representing phosphorylation states and activation\n    #  states of proteins, the conditional probability is defined by a logistic\n    #  regression. Therefore, the parameters associated with such a node is a \n    #  vector of real numbers.\n    # \n    def _initParams(self):\n        print \"Initialize parameters associated with each node in each MCMC chain\"\n        for nodeId in self.network: \n            self._initNodeParams(nodeId)\n            \n    def _initNodeParams(self, nodeId):\n        nodeObj = self.network.node[nodeId]['nodeObj']\n        if nodeObj.type == 'FLUORESCENCE':                \n            # Estimate mean and sd of fluo signal using mixture model\n            if self.missingDataMatrix and nodeId in self.missingDataMatrix.getColnames():\n                nodeData = self.obsData.getValuesByCol( nodeId)\n                nodeData = nodeData[self.missingDataMatrix.getValuesByCol(nodeId) == 0]\n            else:\n                nodeData = self.obsData.getValuesByCol(nodeId)\n            nodeObj.mus = np.zeros((self.nChains, 2))\n            nodeObj.sigmas = np.zeros((self.nChains, 2))\n            for c in range(self.nChains):   \n                mixGaussians = normalmixEM(robjects.FloatVector(nodeData), k = 2 )\n                # mus and sigmas are represented as nChain x 2 matrices\n                nodeObj.mus[c,:] = np.array(mixGaussians[2])\n                nodeObj.sigmas[c,:] = np.array(mixGaussians[3])            \n        else:\n            preds = self.network.predecessors(nodeId)\n            if len(preds) > 0:\n                nodeObj.paramNames = preds\n                nodeObj.params = np.random.randn(self.nChains, len(preds) + 1)\n            else:\n                nodeObj.params  = None\n                \n    \n    ## Initialize latent variables\n    #    \n    #\n    def _initHiddenStates(self):\n        hiddenNodes = [n for n in self.network if not self.network.node[n]['nodeObj'].bMeasured]\n        phosNodes = [n for n in self.network if self.network.node[n]['nodeObj'].type == 'PHOSPHORYLATIONSTATE']\n        #print str(phosNodes)\n        nCases, nAntibody = self.obsData.shape()\n        caseNames = self.obsData.getRownames()\n        \n        self.nodeStates = list()\n        for c in range(self.nChains):\n            tmp = np.zeros((nCases, len(hiddenNodes)))\n            tmp[np.random.rand(nCases, len(hiddenNodes)) < 0.3] = 1\n            tmp = np.column_stack((tmp, self.perturbData.data))\n            colnames = hiddenNodes + self.perturbData.colnames\n            self.nodeStates.append(NamedMatrix(npMatrix = tmp, colnames = colnames, rownames = caseNames))\n            \n            #initialize phos state based on the observed fluo \n            for node in phosNodes:\n                fluoNode = node + 'F'\n                #print \"phosNode:\" + node + \"; fluoNode: \" + fluoNode\n                fluoNodeObj = self.network.node[fluoNode]['nodeObj']\n                fluoData = self.obsData.getValuesByCol(fluoNode)\n                tmp = np.zeros(nCases)\n                phosProbOne = - np.log(fluoNodeObj.sigmas[c, 1])\\\n                - 0.5 * np.square(fluoData - fluoNodeObj.mus[c, 1]) / np.square(fluoNodeObj.sigmas[c, 1])                    \n                phosProbZero = - np.log(fluoNodeObj.sigmas[c, 0])\\\n                - 0.5 * np.square(fluoData - fluoNodeObj.mus[c, 0]) / np.square(fluoNodeObj.sigmas[c, 0])\n                tmp[phosProbOne > phosProbZero] = 1\n                nodeIndx = self.nodeStates[c].findColIndices(node)\n                self.nodeStates[c].data[:,nodeIndx] = tmp\n                \n                # take care of missing values by random sampling\n                if self.missingDataMatrix:\n                    if node in self.missingDataMatrix.getColnames(): \n                        #print \"processing node with missing values: \" + nodeId\n                        missingCases = self.missingDataMatrix.getValuesByCol(node) == 1\n                        tmp = np.zeros(sum(missingCases))\n                        tmp[np.random.rand(len(tmp)) <= 0.3] = 1\n                        self.nodeStates[c].data[missingCases, nodeIndx] = tmp\n                    \n        \n        \n    ## Calculate the marginal probability of observing the measured data by\n    #  integrating out all possible setting of latent variable states and \n    #  model parameters.            \n    def calcEvidenceLikelihood(self):\n        phosNodes = [n for n in self.network if self.network.node[n]['nodeObj'].type == 'PHOSPHORYLATIONSTATE']\n        loglikelihood = 0\n        nCases, nAntibodies = np.shape(self.obsData.data) \n        for nodeId in phosNodes:\n            nodeObj = self.network.node[nodeId]['nodeObj']\n            nodeIndx = self.nodeStates[0].findColIndices(nodeId)\n            preds = self.network.predecessors(nodeId)\n            for c in range(self.nChains):\n                nodeData = self.nodeStates[c].data[:, nodeIndx]\n                predStates = np.column_stack((np.ones(nCases), self.nodeStates[c].getValuesByCol(preds)))\n                pOneCondOnParents = 1 / (1 + np.exp( - np.dot(predStates, nodeObj.params[c,:])))\n                pOneCondOnParents[pOneCondOnParents == 1.] -= np.finfo(np.float).eps\n                \n                loglikelihood += np.sum(nodeData * np.log(pOneCondOnParents) \\\n                + (1 - nodeData) * np.log(1 - pOneCondOnParents))\n                \n            loglikelihood /= self.nChains\n            return loglikelihood\n        \n    ## Perform graph search\n    def trainGibbsEM(self, nChains = 10, alpha = 0.1, nParents = 4, nSamples = 5, pickleDumpFile = None, maxIter = 1000):\n        self.nChains = nChains\n        self.alpha = alpha  \n        self.likelihood = list()\n        self.nSamples = nSamples\n        self.nParents = nParents\n        \n        if pickleDumpFile:\n            self.pickleDumpFile = pickleDumpFile\n        else:\n            self.pickleDumpFile = self.obsDataFileName + \"alpha\" + str(self.alpha) +  \".pickle\"  \n        \n        # check if the network and data agrees\n        nodeToDelete = list()\n        for nodeId in self.network:\n            if self.network.node[nodeId]['nodeObj'].type == 'FLUORESCENCE' and nodeId not in self.obsData.getColnames():\n                print \"Node \" + nodeId + \" don't has associated data\"\n                nodeToDelete.append(nodeId)\n                nodeToDelete.append(self.network.predecessors(nodeId)[0])\n        for nodeId in nodeToDelete:\n            if self.network.has_node(nodeId):\n                print \"removing node \" + nodeId\n                self.network.remove_node(nodeId)\n\n        # Starting EM set up Markov chains  to train a model purely based on prior knowledge        \n        self._initParams()\n        self._initHiddenStates()\n\n        # perform update of latent variables in a layer-wise manner\n        self.likelihood = list()        \n        \n        self.expectedStates = list()\n        nCases, nAntibodies = np.shape(self.obsData.data)\n        for c in range(self.nChains):                  \n            # each chain collect expected statistics of nodes from samples along the chain\n            self.expectedStates.append(np.zeros(np.shape(self.nodeStates[c].data)))\n\n        print \"Starting EM: alpha = \" + str(self.alpha) + \"; nChains = \" + str(self.nChains) + \"; nSamples = \" + str (self.nSamples) + \"; nParents = \" + str(self.nParents)\n        optLikelihood = float(\"-inf\")\n        bConverged = False\n        sampleCount = 0\n        \n        likelihood = self.calcEvidenceLikelihood()\n        print \"nIter: 0\"  + \"; log likelihood of evidence: \" + str(likelihood)\n        self.likelihood.append(likelihood)\n        for nIter in range(maxIter): \n                \n            # E-step of EM\n            self._updateActivationStates()            \n            if  (nIter+1) % 2 == 0: # we collect sample every other iteration\n                sampleCount += 1\n                for c in range(self.nChains):\n                    self.expectedStates[c] +=  self.nodeStates[c].data                \n                \n            # M-step of EM.  We only update parameters after a collecting a certain number of samples\n            if sampleCount >= self.nSamples:                    \n                sampleCount = 0\n                 # take expectation of sample states\n                self.expectedStates = map(lambda x: x / self.nSamples, self.expectedStates)\n                self._updteParams(self.alpha, nparents = self.nParents)\n                \n                likelihood = self.calcEvidenceLikelihood()\n                self.likelihood.append(likelihood)   \n                print \"nIter: \" + str(nIter + 1) + \"; log likelihood of evidence: \" + str(likelihood)                    \n\n                # collect the current best fit models\n                if likelihood > optLikelihood:\n                    optLikelihood = likelihood\n                    try:\n                        cPickle.dump(self, open(self.pickleDumpFile, 'wb'))\n                    except: \n                        raise Exception(\"Cannot create pickle dumpfile \" + self.pickleDumpFile)\n\n                bConverged = self._checkConvergence()\n                if bConverged:\n                    print \"EM converged!\"\n                    break\n                \n                for c in range(self.nChains):  # clear expectedStates\n                    self.expectedStates[c] = np.zeros(np.shape(self.nodeStates[c].data))\n                \n        # now try to delete edges that does contribute to evidence\n        #self.trimEdgeByConsensus(.9)\n        return self  \n            \n    def _checkConvergence(self):\n        # To do, add convergence checking code\n        if len(self.likelihood) < 20:\n            return False\n            \n        ml = np.mean(self.likelihood[-5:-1])\n        ratio = abs(self.likelihood[-1] - ml ) / abs(ml)        \n        return ratio <= 0.001\n\n    def _updateActivationStates(self):\n        nCases, antibody = np.shape(self.obsData.data)\n        nCases, nHiddenNodes = np.shape(self.nodeStates[0].data)\n\n        # interate through all nodes. \n        activationNode = [n for n in self.network if self.network.node[n]['nodeObj'].type == 'ACTIVATIONSTATE']\n                    \n        for nodeId in activationNode: \n            for c in range(self.nChains):\n                curNodeMarginal = self.calcNodeCondProb(nodeId, c)\n                \n                # sample states of current node based on the prob, and update \n                sampleState = np.zeros(nCases)\n                sampleState[curNodeMarginal >= np.random.rand(nCases)] = 1.\n                curNodeIndx = self.nodeStates[c].findColIndices(nodeId)\n                self.nodeStates[c].data[:, curNodeIndx] = sampleState\n                \n                # clamp the activationState of perturbed nodes to a fix value\n                if nodeId in self.dictPerturbEffect:\n                    # the diction keeps a list conditins under which the node is perurbed and the state to be clamped to\n                    for condition, state in self.dictPerturbEffect[nodeId]:\n                        perturbState = self.nodeStates[c].getValuesByCol(condition)\n                        indx = self.nodeStates[c].findColIndices(nodeId)\n                        self.nodeStates[c].data[perturbState==1, indx] = state\n                        \n            \n    def calcNodeCondProb(self, nodeId, c):\n        \"\"\"\n        Calculate the marginal probability of a node's state set to \"1\" conditioning \n        on all evidence.\n        \n        args:\n             nodeId   A string id of the node of interest\n             c        An integer indicate the chain from which the parameter \n                         vector to be used  \n        \"\"\"\n        nodeObj = self.network.node[nodeId]['nodeObj']\n        if nodeObj.bMeasured:\n            raise Exception(\"Call _caclNodeMarginalProb on an observed variable \" + nodeId)\n\n        nCases, nAntibody = np.shape(self.obsData.data)        \n\n        # collect the state of the predecessors of the node\n        preds = self.network.predecessors(nodeId)        \n        logProbOneCondOnParents = 0\n        logProbZeroCondOnParents = 0\n        if len(preds) > 0:  # if the node has parents  \n            # calculate p(curNode = 1 | parents);                 \n            nodeParams = nodeObj.params[c,:] \n            predStates =  np.column_stack((np.ones(nCases), self.nodeStates[c].getValuesByCol(preds))) \n            pOneCondOnParents = 1 / (1 + np.exp( - np.dot(predStates, nodeParams)))\n            pOneCondOnParents[pOneCondOnParents == 1] -= np.finfo(np.float).eps\n            pOneCondOnParents[pOneCondOnParents == 0] += np.finfo(np.float).eps\n            logProbOneCondOnParents  = np.log(pOneCondOnParents)\n            logProbZeroCondOnParents = np.log(1 - pOneCondOnParents)\n\n        # collect  evidence from  children \n        logProbChildCondOne = 0  # the prob of child conditioning on current node == 1\n        logProdOfChildCondZeros = 0\n        \n        children = self.network.successors(nodeId)\n        if len(children) > 0:\n            for child in children:  \n                childNodeObj = self.network.node[child]['nodeObj']\n                curChildStates = self.nodeStates[c].getValuesByCol(child)                    \n                \n                # Collect states of the predecessors of the child\n                childPreds = self.network.predecessors(child)\n                childNodeParams = childNodeObj.params[c,:]\n                childPredStates = self.nodeStates[c].getValuesByCol(childPreds)\n                childPredStates = np.column_stack((np.ones(nCases), childPredStates)) # padding data with a column ones as bias\n\n                # Set the state of current node to ones \n                curNodePosInPredList = childPreds.index(nodeId) + 1 # offset by 1 because padding \n                if childNodeParams[curNodePosInPredList] == 0:  # not an real edge \n                    continue\n                childPredStates[:, curNodePosInPredList] = np.ones(nCases)                \n                pChildCondCurNodeOnes = 1 / (1 + np.exp(-np.dot(childPredStates, childNodeParams)))\n                pChildCondCurNodeOnes[pChildCondCurNodeOnes==1] -= np.finfo(np.float).eps\n                pChildCondCurNodeOnes[pChildCondCurNodeOnes==0] += np.finfo(np.float).eps\n                logProbChildCondOne += np.log (curChildStates * pChildCondCurNodeOnes + (1 - curChildStates) * (1 - pChildCondCurNodeOnes))\n                    \n                # set the state of the current node (nodeId) to zeros \n                childPredStates [:, curNodePosInPredList] = np.zeros(nCases)\n                pChildCondCurNodeZeros = 1 / (1 + np.exp(- np.dot(childPredStates, childNodeParams))) \n                pChildCondCurNodeZeros[pChildCondCurNodeZeros==1]  -= np.finfo(np.float).eps\n                pChildCondCurNodeZeros[pChildCondCurNodeZeros==0]  += np.finfo(np.float).eps\n                logProdOfChildCondZeros += np.log(curChildStates * pChildCondCurNodeZeros + (1 - curChildStates) * (1 - pChildCondCurNodeZeros))\n\n        # now we can calculate the marginal probability of current node \n        curNodeMarginal = 1 / (1 + np.exp(logProbZeroCondOnParents + logProdOfChildCondZeros - logProbOneCondOnParents - logProbChildCondOne))\n        return curNodeMarginal\n    \n\n    def parseGlmnetCoef(self, glmnet_res):        \n        \"\"\" Parse the 'beta' matrix returned by calling glmnet through RPy2.\n            Return the first column of 'beta' matrix of the glmnet object \n            with 3 or more non-zero values \n            \"\"\"\n        # read in intercept; a vector of length of nLambda\n        a0 = np.array(glmnet_res.rx('a0'))[0]\n        \n        # Read in lines of beta matrix txt, which is a nVariables * nLambda.\n        # Since we call glmnet by padding x with a column of 1s, we only work\n        # with the 'beta' matrix returned by fit\n        betaLines = StringIO(str(glmnet_res.rx('beta'))).readlines()\n        dimStr = re.search(\"\\d+\\s+x\\s+\\d+\", betaLines[1]).group(0)\n        if not dimStr:\n            raise Exception(\"'parse_glmnet_res' could not determine the dims of beta\")\n        nVariables , nLambda = map(int, dimStr.split(' x ')) \n        betaMatrix = np.zeros( (nVariables, nLambda), dtype=np.float)\n        \n        # glmnet print beta matrix in mulitple blocks with \n        # nVariable * blockSize\n        blockSize = len(betaLines[4].split()) - 1\n        curBlockColStart = - blockSize\n        for line in betaLines:  #read in blocks\n            m = re.search('^V\\d+', line)\n            if not m:  # only find the lines begins with 'V\\d'\n                continue\n            else:\n                rowIndx = int(m.group(0)[1:len(m.group(0))]) \n            if rowIndx == 1:\n                curBlockColStart += blockSize\n                \n            # set 'rowIndx' as start from 0\n            rowIndx -= 1\n\n            fields = line.rstrip().split()\n            fields.pop(0)\n            if len(fields) != blockSize:\n                blockSize = len(fields)\n            for j in range(blockSize):\n                if fields[j] == '.':\n                    continue\n                else:\n                    betaMatrix[rowIndx, curBlockColStart + j] = float(fields[j])                 \n                            \n        return a0, betaMatrix       \n      \n        \n    def _updteParams(self, alpha = 0.1, nparents=None):\n        # Update the parameter associated with each node, p(n | Pa(n)) using logistic regression,\n        # using expected states of precessors as X and current node states acrss samples as y\n        nCases, nVariables = np.shape(self.obsData.data)\n        if not nparents:\n            nparents = self.nParents\n        \n        for nodeId in self.network:     \n            nodeObj = self.network.node[nodeId]['nodeObj'] \n            if nodeObj.type == 'FLUORESCENCE' or nodeObj.type == 'PERTURBATION':\n                continue\n            nodeObj.fitRes = list()\n            preds = self.network.predecessors(nodeId)\n            predIndices = self.nodeStates[0].findColIndices(preds)\n                       \n            for c in range(self.nChains): \n                expectedPredState = self.expectedStates[c][:, predIndices]\n                #x = np.column_stack((np.ones(nCases), expectedPredState))                    \n                x =  np.column_stack((np.ones(nCases), expectedPredState))\n                y = self.nodeStates[c].getValuesByCol(nodeId) \n                    \n                #check if all x and y are of same value, which will lead to problem for glmnet\n                rIndx = map(lambda z: int(math.floor(z)), np.random.rand(50) * nCases)\n                if sum(y) == nCases:  # if every y == 1                      \n                    y[rIndx] = 0                        \n                elif sum( map(lambda x: 1 - x, y)) == nCases:\n                    y[rIndx] = 1        \n                y = robjects.vectors.IntVector(y)\n                \n                allRwoSumOnes = np.where(np.sum(x, 0) == nCases)[0]\n                for col in allRwoSumOnes:\n                    rIndx = map(lambda z: int(math.floor(z)), np.random.rand(3) * nCases)\n                    x[rIndx, col] = 0 \n                allZeros = np.where(np.sum(np.ones(np.shape(x)) - x, 0) == nCases) \n                for col in allZeros[0]:\n                    rIndx = map(lambda z: int(math.floor(z)), np.random.rand(3) * nCases)\n                    x[rIndx, col] = 1\n                    \n                # call logistic regression using glmnet from Rpy\n                fit = glmnet (x, y, alpha = alpha, family = \"binomial\", intercept = 0)\n                nodeObj.fitRes.append(fit)\n                    \n                # extract coefficients glmnet, keep the first set beta with nParent non-zeros values\n                a0, betaMatrix = self.parseGlmnetCoef(fit) \n                for j in range(np.shape(betaMatrix)[1]):\n                    if sum(betaMatrix[:, j] != 0.) >= nparents:\n                        break\n                if j >= len(a0):\n                    j = len(a0) - 1\n                    \n                myparams = betaMatrix[:, j]\n                if sum( myparams != 0.) > nparents:\n                    sortedParams = sorted(np.abs(myparams))                    \n                    myparams[np.abs(myparams) < sortedParams[-self.nParents]] = 0.  \n                    \n                nodeObj.params[c,:] =  myparams\n                        \n                        \n    def getStimuliSpecificNet(self, stimulus):  \n        self.stimuli = ['EGF',\t'FGF1',\t'HGF',\t'IGF1',\t 'Insulin',\t'NRG1',\t 'PBS',\t 'Serum']\n        #self.stimuli = ['loLIG1',\t'hiLIG1',\t'loLIG2',\t'hiLIG2']\n        # trim unused edges\n        if not stimulus in self.nodeStates[0].getColnames():\n            raise Exception(\"Input stimulus '\" + stimulus + \"' is not in the experiment data\")\n\n        #self.trimEdgeByConsensus(0.9)\n        stimulusCases = self.perturbData.getValuesByCol(stimulus) == 1\n        controlCases = np.sum(self.perturbData.getValuesByCol(self.stimuli), 1) == 0\n        \n        # identify the nodes to keep by determine if a node responds to a stimuli\n        activeNodes = set()\n        activeNodes.add(stimulus)\n        for nodeId in self.network:            \n            if self.network.node[nodeId]['nodeObj'].type == 'FLUORESCENCE' \\\n            or self.network.node[nodeId]['nodeObj'].type == 'fluorescence':\n                nodeControlValues = self.obsData.getValuesByCol(nodeId)[controlCases]\n                nodeStimulValues = self.obsData.getValuesByCol(nodeId)[stimulusCases]\n                ttestRes = R('t.test')(robjects.FloatVector(nodeControlValues), robjects.FloatVector(nodeStimulValues))\n                pvalue = np.array(ttestRes.rx('p.value')[0])[0]\n                if pvalue < 0.05:\n                    activeNodes.add(self.network.predecessors(nodeId)[0])\n\n        # copy network to a tmp, redirect edges from activation state nodes \n        # Edge indicates the impact \n        tmpNet = nx.DiGraph()\n        for u,  v in self.network.edges():\n            # we are only interested in the edge from protein point to antibody\n            if (self.network.node[u]['nodeObj'].type == 'ACTIVATIONSTATE'\\\n            or self.network.node[u]['nodeObj'].type == 'activeState')\\\n            and (self.network.node[v]['nodeObj'].type == 'PHOSPHORYLATIONSTATE'\\\n            or self.network.node[v]['nodeObj'].type == 'phosState'):\n                # extract parameters associated with u and v\n                vPreds = self.network.predecessors(v)\n                uIndx = vPreds.index(u)\n                vParams = np.sum(self.network.node[v]['nodeObj'].params, 0) \n                if len(vParams) != (len(vPreds) + 1):\n                    raise Exception (\"Bug in retrieving parameters of node v \" + u)\n                paramZeros = np.sum(self.network.node[v]['nodeObj'].params == 0, 0)\n                if np.float(paramZeros[uIndx+1]) / float(self.nChains) > .9:\n                    continue  # don't add edge with beta == 0\n                    \n                for ab in self.dictProteinToAntibody[u]: \n                    if ab not in self.network:\n                        continue\n                    # find the impact of phosphorylation on activation state\n                    uPreds = self.network.predecessors(u)\n                    uParams = np.mean(self.network.node[u]['nodeObj'].params, 0) \n                    if len(uParams) != (len(uPreds) + 1):\n                        raise Exception (\"Bug in retrieving parameters of node v \" + u)\n                    #uAntibodyParam = uParams[uPreds.index(ab) + 1]\n                    \n#                    if vParams[uIndx+1] > 0. and (vParams[uIndx+1] * uAntibodyParam) > 0:\n#                        tmpNet.add_edge(ab, v, effect = \"+\", betaValue = vParams[uIndx+1])\n#                    elif (vParams[uIndx+1] * uAntibodyParam) < 0.:\n#                        tmpNet.add_edge(ab, v, effect = \"-\", betaValue = vParams[uIndx+1])          \n                    if vParams[uIndx+1] > 0. :\n                        tmpNet.add_edge(ab, v, effect = \"+\", betaValue = vParams[uIndx+1])\n                    elif vParams[uIndx+1]  < 0.:\n                        tmpNet.add_edge(ab, v, effect = \"-\", betaValue = vParams[uIndx+1])          \n            \n        # remove leave nodes that is not in activeNodes list\n        while True:\n            leafNodes = []\n            for nodeId in tmpNet:                     \n                if (nodeId not in activeNodes and len(tmpNet.successors(nodeId)) == 0)\\\n                or (nodeId not in activeNodes and len(tmpNet.predecessors(nodeId)) == 0):\n                    leafNodes.append(nodeId)\n                    \n            if len(leafNodes) == 0:\n                break\n            \n            for leaf in leafNodes:\n                tmpNet.remove_node(leaf)\n        \n        # now try to remove cycles and make the tmpNet a DAG\n        return tmpNet\n            \n                         \n                        \n    def toGraphML(self, filename):\n        tmpNet = nx.DiGraph()\n        for edge in self.network.edges():\n            tmpNet.add_edge(edge)\n            \n        nx.write_graphml(tmpNet, filename, encoding='utf-8', prettyprint=True)\n        \n#    # this funciton implement \n#    def K2LikeGreedySearch (self, tmpNet):\n#        for node in tmpNet:\n#            ancestors = tmpNet.predecessors(node)\n#            preds = []\n#            while True:\n#                \n                \n                \n                \n            \n        \n\n", "meta": {"hexsha": "9cc854f2bbed575128efd9399ae0b8c95cd41e7c", "size": 31384, "ext": "py", "lang": "Python", "max_stars_repo_path": "PyGibbCAMP.py", "max_stars_repo_name": "xlu29466/PyGibbCAMP", "max_stars_repo_head_hexsha": "2ca7e9ecae69d8f8eb058204f99e322ae1b37670", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-01-05T17:15:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-26T22:18:30.000Z", "max_issues_repo_path": "PyGibbCAMP.py", "max_issues_repo_name": "xlu29466/PyGibbCAMP", "max_issues_repo_head_hexsha": "2ca7e9ecae69d8f8eb058204f99e322ae1b37670", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PyGibbCAMP.py", "max_forks_repo_name": "xlu29466/PyGibbCAMP", "max_forks_repo_head_hexsha": "2ca7e9ecae69d8f8eb058204f99e322ae1b37670", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2015-01-08T16:38:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T13:09:09.000Z", "avg_line_length": 49.579778831, "max_line_length": 171, "alphanum_fraction": 0.5672954372, "include": true, "reason": "import numpy,from numpy,import networkx", "num_tokens": 7364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.32082131381216084, "lm_q1q2_score": 0.17416211647326343}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\n\n\"\"\"\n    Graph metric learning\n\"\"\"\n\n# Python modules\nimport torch\nfrom torch.optim.lr_scheduler import StepLR\nimport glob\nimport numpy as np\nimport time\nimport os\nimport sys\n\n# Own modules\nfrom options import Options\nfrom Logger import LogMetric\nfrom utils import save_checkpoint, load_checkpoint\nfrom models import models, distance\nfrom test_iam import test\nfrom data.load_data import load_data\nfrom loss.contrastive import ContrastiveLoss, TripletLoss\n\n__author__ = \"Pau Riba\"\n__email__ = \"priba@cvc.uab.cat\"\n\n\ndef train(data_loader, nets, optimizer, cuda, criterion, epoch):\n    batch_time = LogMetric.AverageMeter()\n    batch_load_time = LogMetric.AverageMeter()\n    losses = LogMetric.AverageMeter()\n\n    net, distNet = nets\n    # switch to train mode\n    net.train()\n    distNet.train()\n\n    end = time.time()\n    for i, (g1, g2, g3, target) in enumerate(data_loader):\n        # Prepare input data\n        if cuda:\n            g1.to(torch.device('cuda'))\n            g2.to(torch.device('cuda'))\n            g1.gdata['std'], g2.gdata['std'] = g1.gdata['std'].cuda(), g2.gdata['std'].cuda()\n            if args.triplet:\n                g3.to(torch.device('cuda'))\n                g3.gdata['std'] = g3.gdata['std'].cuda()\n            else:\n                target = target.cuda()\n\n        batch_load_time.update(time.time() - end)\n        optimizer.zero_grad()\n\n        # Output\n        g1 = net(g1)\n        g2 = net(g2)\n\n        if args.triplet:\n            g3 = net(g3)\n            loss = criterion(g1, g2, g3, distNet)\n        else:\n            loss = criterion(g1, g2, target, distNet)\n\n        # Gradiensts and update\n        loss.backward()\n        optimizer.step()\n\n        # Save values\n        losses.update(loss.item(), g1.batch_size)\n        batch_time.update(time.time() - end)\n        end = time.time()\n\n        if i > 0 and i%args.log_interval == 0:\n            print('Epoch: [{0}]({1}/{2}) Average Loss {loss.avg:.3f}; Avg Time x Batch {b_time.avg:.3f} Avg Load Time x Batch {b_load_time.avg:.3f}'\n                    .format(epoch, i, len(data_loader), loss=losses, b_time=batch_time, b_load_time=batch_load_time))\n    print('Epoch: [{0}] Average Loss {loss.avg:.3f}; Avg Time x Batch {b_time.avg:.3f} Avg Time x Batch {b_load_time.avg:.3f}'\n            .format(epoch, loss=losses, b_time=batch_time, b_load_time=batch_load_time))\n    return losses\n\n\ndef main():\n    print('Loss & Optimizer')\n    if args.loss=='triplet':\n        args.triplet=True\n        criterion = TripletLoss(margin=args.margin, swap=args.swap)\n    elif args.loss=='triplet_distance':\n        args.triplet=True\n        criterion = TripletLoss(margin=args.margin, swap=args.swap, dist=True)\n    else:\n        args.triplet=False\n        criterion = ContrastiveLoss(margin=args.margin)\n\n    print('Prepare data')\n    train_loader, valid_loader, test_pair_loader, test_triplet_loader, in_size = load_data(args.dataset, args.data_path, triplet=args.triplet, batch_size=args.batch_size, prefetch=args.prefetch, set_partition=args.set_partition)\n\n    print('Create model')\n    net = models.GNN(in_size, args.hidden, args.out_size, dropout=args.dropout)\n    distNet = distance.SoftHd(args.out_size)\n\n    optimizer = torch.optim.Adam(list(net.parameters())+list(distNet.parameters()), args.learning_rate, weight_decay=args.decay)\n    scheduler = StepLR(optimizer, 5, gamma = args.gamma)\n\n    print('Check CUDA')\n    if args.cuda and args.ngpu > 1:\n        print('\\t* Data Parallel **NOT TESTED**')\n        net = torch.nn.DataParallel(net, device_ids=list(range(args.ngpu)))\n\n    if args.cuda:\n        print('\\t* CUDA')\n        net, distNet = net.cuda(), distNet.cuda()\n        criterion = criterion.cuda()\n\n    start_epoch = 0\n    best_perf = 0\n    early_stop_counter = 0\n    if args.load is not None:\n        print('Loading model')\n        checkpoint = load_checkpoint(args.load)\n        net.load_state_dict(checkpoint['state_dict'])\n        distNet.load_state_dict(checkpoint['state_dict_dist'])\n        start_epoch = checkpoint['epoch']\n        best_perf = checkpoint['best_perf']\n\n    if not args.test:\n        print('***Train***')\n\n        for epoch in range(start_epoch, args.epochs):\n\n            loss_train = train(train_loader, [net, distNet], optimizer, args.cuda, criterion, epoch)\n            acc_valid, auc_valid = test(valid_loader, [net, distNet], args.cuda)\n\n            # Early-Stop + Save model\n            if acc_valid.avg > best_perf:\n                best_perf = acc_valid.avg\n                early_stop_counter = 0\n                if args.save is not None:\n                    save_checkpoint({'epoch': epoch + 1, 'state_dict': net.state_dict(), 'state_dict_dist': distNet.state_dict(), 'best_perf': best_perf}, directory=args.save, file_name='checkpoint')\n            else:\n                if early_stop_counter >= args.early_stop:\n                    print('Early Stop epoch {}'.format(epoch))\n                    break\n                early_stop_counter += 1\n\n            # Logger\n            if args.log:\n                # Scalars\n                logger.add_scalar('loss_train', loss_train.avg)\n                logger.add_scalar('acc_valid', acc_valid.avg.item())\n                logger.add_scalar('learning_rate', scheduler.get_lr()[0])\n                logger.step()\n\n            scheduler.step()\n        # Load Best model in case of save it\n        if args.save is not None:\n            print('Loading best  model')\n            best_model_file = os.path.join(args.save, 'checkpoint.pth')\n            checkpoint = load_checkpoint(best_model_file)\n            net.load_state_dict(checkpoint['state_dict'])\n            distNet.load_state_dict(checkpoint['state_dict_dist'])\n            print('Best model at epoch {epoch} and acc {acc}%'.format(epoch=checkpoint['epoch'],acc=checkpoint['best_perf']))\n\n    print('***Valid***')\n    test(valid_loader, [net, distNet], args.cuda)\n    print('***Test***')\n    test(test_triplet_loader, [net, distNet], args.cuda, data_pair_loader=test_pair_loader)\n    sys.exit()\n\nif __name__ == '__main__':\n    torch.autograd.set_detect_anomaly(True)\n    # Parse options\n    args = Options().parse()\n    print('Parameters:\\t' + str(args))\n\n    # Check cuda & Set random seed\n    args.cuda = args.ngpu > 0 and torch.cuda.is_available()\n\n    if args.seed > 1:\n        np.random.seed(args.seed)\n        torch.manual_seed(args.seed)\n        if args.cuda:\n            torch.cuda.manual_seed(args.seed)\n\n    # Check Test and Load\n    if args.test and args.load is None:\n        raise Exception('Cannot test without loading a model.')\n\n    if not args.test and args.log is not None:\n        print('Initialize logger')\n        ind = len(glob.glob(args.log + '*_run-batchSize_{}'.format(args.batch_size)))\n        log_dir = args.log + '{}_run-batchSize_{}/' \\\n                .format(ind, args.batch_size)\n        args.save = args.save + '{}_run-batchSize_{}/' \\\n                .format(ind, args.batch_size)\n        # Create logger\n        print('Log dir:\\t' + log_dir)\n        logger = LogMetric.Logger(log_dir, force=True)\n\n    main()\n    sys.exit()\n\n", "meta": {"hexsha": "a136c43325c1b8b52d1164333179e9560fa6d49b", "size": 7171, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/train_iam.py", "max_stars_repo_name": "priba/graph_metric.pytorch", "max_stars_repo_head_hexsha": "68930d7bbc6b2b3ff12e39d7e9260f7bbe6a2e80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-11-17T10:28:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T09:32:42.000Z", "max_issues_repo_path": "src/train_iam.py", "max_issues_repo_name": "priba/graph_metric.pytorch", "max_issues_repo_head_hexsha": "68930d7bbc6b2b3ff12e39d7e9260f7bbe6a2e80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-06-22T17:29:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-18T10:27:22.000Z", "max_forks_repo_path": "src/train_iam.py", "max_forks_repo_name": "priba/graph_metric.pytorch", "max_forks_repo_head_hexsha": "68930d7bbc6b2b3ff12e39d7e9260f7bbe6a2e80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1519607843, "max_line_length": 228, "alphanum_fraction": 0.6208339144, "include": true, "reason": "import numpy", "num_tokens": 1702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.542863297964157, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.174162105897564}}
{"text": "\"\"\"\nUtilities for coordinate-based meta-analysis estimators\n\"\"\"\nimport os\nimport math\nimport logging\nimport requests\nfrom io import BytesIO\nfrom tarfile import TarFile\n\nimport numpy as np\nimport numpy.linalg as npl\nimport nibabel as nb\nfrom scipy import ndimage\nfrom lzma import LZMAFile\nfrom tqdm.auto import tqdm\n\nfrom .peaks2maps import model_fn\nfrom ...due import due\nfrom ... import references\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nLGR = logging.getLogger(__name__)\n\n\ndef _get_resize_arg(target_shape):\n    mni_shape_mm = np.array([148.0, 184.0, 156.0])\n    target_resolution_mm = np.ceil(\n        mni_shape_mm / np.array(target_shape)).astype(\n        np.int32)\n    target_affine = np.array([[4., 0., 0., -75.],\n                              [0., 4., 0., -105.],\n                              [0., 0., 4., -70.],\n                              [0., 0., 0., 1.]])\n    target_affine[0, 0] = target_resolution_mm[0]\n    target_affine[1, 1] = target_resolution_mm[1]\n    target_affine[2, 2] = target_resolution_mm[2]\n    return target_affine, list(target_shape)\n\n\ndef _get_generator(contrasts_coordinates, target_shape, affine,\n                   skip_out_of_bounds=False):\n    def generator():\n        for contrast in contrasts_coordinates:\n            encoded_coords = np.zeros(list(target_shape))\n            for real_pt in contrast:\n                vox_pt = np.rint(nb.affines.apply_affine(\n                    npl.inv(affine), real_pt)).astype(int)\n                if skip_out_of_bounds and (vox_pt[0] >= 32 or\n                                           vox_pt[1] >= 32 or vox_pt[2] >= 32):\n                    continue\n                encoded_coords[vox_pt[0], vox_pt[1], vox_pt[2]] = 1\n            yield (encoded_coords, encoded_coords)\n\n    return generator\n\n\ndef _get_checkpoint_dir():\n    from appdirs import AppDirs\n    dirs = AppDirs(appname=\"nimare\", appauthor=\"neurostuff\", version=\"1.0\")\n    checkpoint_dir = os.path.join(dirs.user_data_dir, \"ohbm2018_model\")\n    if not os.path.exists(checkpoint_dir):\n        LGR.info('Downloading the model (this is a one-off operation)...')\n        url = \"https://zenodo.org/record/1257721/files/ohbm2018_model.tar.xz?download=1\"\n        # Streaming, so we can iterate over the response.\n        r = requests.get(url, stream=True)\n        f = BytesIO()\n\n        # Total size in bytes.\n        total_size = int(r.headers.get('content-length', 0))\n        block_size = 1024 * 1024\n        wrote = 0\n        for data in tqdm(r.iter_content(block_size), total=math.ceil(total_size // block_size),\n                         unit='MB', unit_scale=True):\n            wrote = wrote + len(data)\n            f.write(data)\n        if total_size != 0 and wrote != total_size:\n            raise Exception(\"Download interrupted\")\n\n        f.seek(0)\n        LGR.info('Uncompressing the model to %s...'.format(checkpoint_dir))\n        tarfile = TarFile(fileobj=LZMAFile(f), mode=\"r\")\n        tarfile.extractall(dirs.user_data_dir)\n    return checkpoint_dir\n\n\n@due.dcite(references.PEAKS2MAPS,\n           description='Transforms coordinates of peaks to unthresholded maps using a deep '\n                       'convolutional neural net.')\ndef peaks2maps(contrasts_coordinates, skip_out_of_bounds=True,\n               tf_verbosity_level=None):\n    \"\"\"\n    Generate modeled activation (MA) maps using depp ConvNet model peaks2maps\n\n    Parameters\n    ----------\n    contrasts_coordinates : list of lists that are len == 3\n        List of contrasts and their coordinates\n    skip_out_of_bounds : aboolean, optional\n        Remove coordinates outside of the bounding box of the peaks2maps model\n    tf_verbosity_level : int\n        Tensorflow verbosity logging level\n\n    Returns\n    -------\n    ma_values : array-like\n        1d array of modeled activation values.\n    \"\"\"\n    try:\n        import tensorflow as tf\n    except ImportError as e:\n        if \"No module named 'tensorflow'\" in str(e):\n            raise Exception(\"tensorflow not installed - see https://www.tensorflow.org/install/ \"\n                            \"for instructions\")\n        else:\n            raise\n\n    if tf_verbosity_level is None:\n        tf_verbosity_level = tf.logging.FATAL\n    target_shape = (32, 32, 32)\n    affine, _ = _get_resize_arg(target_shape)\n    tf.logging.set_verbosity(tf_verbosity_level)\n\n    def generate_input_fn():\n        dataset = tf.data.Dataset.from_generator(_get_generator(contrasts_coordinates,\n                                                                target_shape, affine,\n                                                                skip_out_of_bounds=skip_out_of_bounds),\n                                                 (tf.float32, tf.float32),\n                                                 (tf.TensorShape(target_shape), tf.TensorShape(target_shape)))\n        dataset = dataset.batch(1)\n        iterator = dataset.make_one_shot_iterator()\n        return iterator.get_next()\n\n    model_dir = _get_checkpoint_dir()\n    model = tf.estimator.Estimator(model_fn, model_dir=model_dir)\n\n    results = model.predict(generate_input_fn)\n    results = [result for result in results]\n    assert len(results) == len(contrasts_coordinates), \"returned %d\" % len(results)\n\n    niis = [nb.Nifti1Image(np.squeeze(result), affine) for result in results]\n    return niis\n\n\ndef compute_ma(shape, ijk, kernel):\n    \"\"\"\n    Generate modeled activation (MA) maps.\n    Replaces the values around each focus in ijk with the contrast-specific\n    kernel. Takes the element-wise maximum when looping through foci, which\n    accounts for foci which are near to one another and may have overlapping\n    kernels.\n\n    Parameters\n    ----------\n    shape : tuple\n        Shape of brain image + buffer. Typically (91, 109, 91) + (30, 30, 30).\n    ijk : array-like\n        Indices of foci. Each row is a coordinate, with the three columns\n        corresponding to index in each of three dimensions.\n    kernel : array-like\n        3D array of smoothing kernel. Typically of shape (30, 30, 30).\n\n    Returns\n    -------\n    ma_values : array-like\n        1d array of modeled activation values.\n    \"\"\"\n    ma_values = np.zeros(shape)\n    mid = int(np.floor(kernel.shape[0] / 2.))\n    mid1 = mid + 1\n    for j_peak in range(ijk.shape[0]):\n        i, j, k = ijk[j_peak, :]\n        xl = max(i - mid, 0)\n        xh = min(i + mid1, ma_values.shape[0])\n        yl = max(j - mid, 0)\n        yh = min(j + mid1, ma_values.shape[1])\n        zl = max(k - mid, 0)\n        zh = min(k + mid1, ma_values.shape[2])\n        xlk = mid - (i - xl)\n        xhk = mid - (i - xh)\n        ylk = mid - (j - yl)\n        yhk = mid - (j - yh)\n        zlk = mid - (k - zl)\n        zhk = mid - (k - zh)\n\n        if ((xl >= 0) & (xh >= 0) & (yl >= 0) & (yh >= 0) & (zl >= 0) &\n                (zh >= 0) & (xlk >= 0) & (xhk >= 0) & (ylk >= 0) & (yhk >= 0) &\n                (zlk >= 0) & (zhk >= 0)):\n            ma_values[xl:xh, yl:yh, zl:zh] = np.maximum(\n                ma_values[xl:xh, yl:yh, zl:zh],\n                kernel[xlk:xhk, ylk:yhk, zlk:zhk])\n    return ma_values\n\n\n@due.dcite(references.ALE_KERNEL,\n           description='Introduces sample size-dependent kernels to ALE.')\ndef get_ale_kernel(img, n=None, fwhm=None):\n    \"\"\"\n    Estimate 3D Gaussian and sigma (in voxels) for ALE kernel given\n    sample size (n) or fwhm (in mm).\n    \"\"\"\n    if n is not None and fwhm is not None:\n        raise ValueError('Only one of n and fwhm may be specified')\n    elif n is None and fwhm is None:\n        raise ValueError('Either n or fwhm must be provided')\n    elif n is not None:\n        uncertain_templates = (5.7 / (2. * np.sqrt(2. / np.pi)) *\n                               np.sqrt(8. * np.log(2.)))  # pylint: disable=no-member\n        # Assuming 11.6 mm ED between matching points\n        uncertain_subjects = (11.6 / (2 * np.sqrt(2 / np.pi)) *\n                              np.sqrt(8 * np.log(2))) / np.sqrt(n)  # pylint: disable=no-member\n        fwhm = np.sqrt(uncertain_subjects ** 2 + uncertain_templates ** 2)\n\n    fwhm_vox = fwhm / np.sqrt(np.prod(img.header.get_zooms()))\n    sigma_vox = fwhm_vox * np.sqrt(2.) / (np.sqrt(2. * np.log(2.)) * 2.)  # pylint: disable=no-member\n\n    data = np.zeros((31, 31, 31))\n    mid = int(np.floor(data.shape[0] / 2.))\n    data[mid, mid, mid] = 1.\n    kernel = ndimage.filters.gaussian_filter(data, sigma_vox, mode='constant')\n\n    # Crop kernel to drop surrounding zeros\n    mn = np.min(np.where(kernel > np.spacing(1))[0])\n    mx = np.max(np.where(kernel > np.spacing(1))[0])\n    kernel = kernel[mn:mx + 1, mn:mx + 1, mn:mx + 1]\n    mid = int(np.floor(data.shape[0] / 2.))\n    return sigma_vox, kernel\n", "meta": {"hexsha": "a171584c7907ab275fcb8b2f3d98aaabb1287c6f", "size": 8651, "ext": "py", "lang": "Python", "max_stars_repo_path": "nimare/meta/cbma/utils.py", "max_stars_repo_name": "Julio-Yanes/NiMARE", "max_stars_repo_head_hexsha": "36bb05034041998519814b55fe402489147fdd63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nimare/meta/cbma/utils.py", "max_issues_repo_name": "Julio-Yanes/NiMARE", "max_issues_repo_head_hexsha": "36bb05034041998519814b55fe402489147fdd63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nimare/meta/cbma/utils.py", "max_forks_repo_name": "Julio-Yanes/NiMARE", "max_forks_repo_head_hexsha": "36bb05034041998519814b55fe402489147fdd63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9429824561, "max_line_length": 110, "alphanum_fraction": 0.5942665588, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.32082128783705344, "lm_q1q2_score": 0.1741620976268541}}
{"text": "# Adversarial learning for event-based music generation with SeqGAN\n# Reference:\n# \"SeqGAN: Sequence Generative Adversarial Nets with Policy Gradient.\"\n# (Yu, Lantao, et al.).\n# ... Honestly, it's too hard to train ;(\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.distributions import Categorical\n\nimport numpy as np\nimport os, sys, time, argparse\nfrom progress.bar import Bar\n\nimport config, utils\nfrom config import device\nfrom data import Dataset\nfrom model import PerformanceRNN\nfrom sequence import EventSeq, ControlSeq\n\n# pylint: disable=E1101\n\n\n#========================================================================\n# Discriminator\n#========================================================================\n\ndiscriminator_config = {\n    'event_dim': EventSeq.dim(),\n    'hidden_dim': 512,\n    'gru_layers': 3,\n    'gru_dropout': 0.3\n}\n\nclass EventSequenceEncoder(nn.Module):\n    def __init__(self, event_dim=EventSeq.dim(), hidden_dim=512,\n                 gru_layers=3, gru_dropout=0.3):\n        super().__init__()\n        self.event_embedding = nn.Embedding(event_dim, hidden_dim)\n        self.gru = nn.GRU(hidden_dim, hidden_dim,\n                          num_layers=gru_layers, dropout=gru_dropout)\n        self.attn = nn.Parameter(torch.randn(hidden_dim), requires_grad=True)\n        self.output_fc = nn.Linear(hidden_dim, 1)\n        self.output_fc_activation = nn.Sigmoid()\n\n    def forward(self, events, hidden=None, output_logits=False):\n        # events: [steps, batch_size]\n        events = self.event_embedding(events)\n        outputs, _ = self.gru(events, hidden) # [t, b, h]\n        weights = (outputs * self.attn).sum(-1, keepdim=True)\n        output = (outputs * weights).mean(0) # [b, h]\n        output = self.output_fc(output).squeeze(-1) # [b]\n        if output_logits:\n            return output\n        output = self.output_fc_activation(output)\n        return output\n\n\n#========================================================================\n# Pretrain Discriminator\n#========================================================================\n\ndef pretrain_discriminator(model_sess_path,         # load\n                           discriminator_sess_path, # load + save\n                           batch_data_generator,    # Dataset(...).batches(...)\n                           discriminator_config_overwrite={},\n                           gradient_clipping=False,\n                           control_ratio=1.0,\n                           num_iter=-1,\n                           save_interval=60.0,\n                           discriminator_lr=0.001,\n                           enable_logging=False,\n                           auto_sample_factor=False,\n                           sample_factor=1.0):\n\n    print('-' * 70)\n    print('model_sess_path:', model_sess_path)\n    print('discriminator_sess_path:', discriminator_sess_path)\n    print('discriminator_config_overwrite:', discriminator_config_overwrite)\n    print('sample_factor:', sample_factor)\n    print('auto_sample_factor:', auto_sample_factor)\n    print('discriminator_lr:', discriminator_lr)\n    print('gradient_clipping:', gradient_clipping)\n    print('control_ratio:', control_ratio)\n    print('num_iter:', num_iter)\n    print('save_interval:', save_interval)\n    print('enable_logging:', enable_logging)\n    print('-' * 70)\n    \n    # Load generator\n    model_sess = torch.load(model_sess_path)\n    model_config = model_sess['model_config']\n    model = PerformanceRNN(**model_config).to(device)\n    model.load_state_dict(model_sess['model_state'])\n\n    print(f'Generator from \"{model_sess_path}\"')\n    print(model)\n    print('-' * 70)\n\n    # Load discriminator and optimizer\n    global discriminator_config\n    try:\n        discriminator_sess = torch.load(discriminator_sess_path)\n        discriminator_config = discriminator_sess['discriminator_config']\n        discriminator_state = discriminator_sess['discriminator_state']\n        discriminator_optimizer_state = discriminator_sess['discriminator_optimizer_state']\n        print(f'Discriminator from \"{discriminator_sess_path}\"')\n        discriminator_loaded = True\n    except:\n        print(f'New discriminator session at \"{discriminator_sess_path}\"')\n        discriminator_config.update(discriminator_config_overwrite)\n        discriminator_loaded = False\n\n    discriminator = EventSequenceEncoder(**discriminator_config).to(device)\n    optimizer = optim.Adam(discriminator.parameters(), lr=discriminator_lr)\n    if discriminator_loaded:\n        discriminator.load_state_dict(discriminator_state)\n        optimizer.load_state_dict(discriminator_optimizer_state)\n\n    print(discriminator)\n    print(optimizer)\n    print('-' * 70)\n\n    def save_discriminator():\n        print(f'Saving to \"{discriminator_sess_path}\"')\n        torch.save({\n            'discriminator_config': discriminator_config,\n            'discriminator_state': discriminator.state_dict(),\n            'discriminator_optimizer_state': optimizer.state_dict()\n        }, discriminator_sess_path)\n        print('Done saving')\n\n    # Disable gradient for generator\n    for parameter in model.parameters():\n        parameter.requires_grad_(False)\n\n    model.eval()\n    discriminator.train()\n\n    loss_func = nn.BCEWithLogitsLoss()\n    last_save_time = time.time()\n\n    if enable_logging:\n        from tensorboardX import SummaryWriter\n        writer = SummaryWriter()\n\n    try:\n        for i, (events, controls) in enumerate(batch_data_generator):\n            if i == num_iter:\n                break\n            \n            steps, batch_size = events.shape\n\n            # Prepare inputs\n            events = torch.LongTensor(events).to(device)\n            if np.random.random() <= control_ratio:\n                controls = torch.FloatTensor(controls).to(device)\n            else:\n                controls = None\n\n            init = torch.randn(batch_size, model.init_dim).to(device)\n\n            # Predict for real event sequence\n            real_events = events\n            real_logit = discriminator(real_events, output_logits=True)\n            real_target = torch.ones_like(real_logit).to(device)\n\n            if auto_sample_factor:\n                sample_factor = np.random.choice([\n                    0.1, 0.4, 0.6, 0.7, 0.8, 0.9, 1.0,\n                    1.1, 1.2, 1.4, 1.6, 2.0, 4.0, 10.0])\n\n            # Predict for fake event sequence from the generator\n            fake_events = model.generate(init, steps, None, controls,\n                                         greedy=0, output_type='index',\n                                         temperature=sample_factor)\n            fake_logit = discriminator(fake_events, output_logits=True)\n            fake_target = torch.zeros_like(fake_logit).to(device)\n\n            # Compute loss\n            loss = (loss_func(real_logit, real_target) +\n                    loss_func(fake_logit, fake_target)) / 2\n            \n            # Backprop\n            discriminator.zero_grad()\n            loss.backward()\n\n            # Gradient clipping\n            norm = utils.compute_gradient_norm(discriminator.parameters())\n            if gradient_clipping:\n                nn.utils.clip_grad_norm_(discriminator.parameters(), gradient_clipping)\n\n            optimizer.step()\n\n            # Logging\n            loss = loss.item()\n            norm = norm.item()\n            print(f'{i} loss: {loss}, norm: {norm}, sf: {sample_factor}')\n            if enable_logging:\n                writer.add_scalar(f'pretrain/D/loss/all', loss, i)\n                writer.add_scalar(f'pretrain/D/loss/{sample_factor}', loss, i)\n                writer.add_scalar(f'pretrain/D/norm/{sample_factor}', norm, i)\n\n            if last_save_time + save_interval < time.time():\n                last_save_time = time.time()\n                save_discriminator()\n\n    except KeyboardInterrupt:\n        save_discriminator()\n\n\n#========================================================================\n# Adversarial Learning\n#========================================================================\n\n\ndef train_adversarial(sess_path, batch_data_generator,\n                      model_load_path, model_optimizer_class,\n                      model_gradient_clipping, discriminator_gradient_clipping,\n                      model_learning_rate, reset_model_optimizer,\n                      discriminator_load_path, discriminator_optimizer_class,\n                      discriminator_learning_rate, reset_discriminator_optimizer,\n                      g_max_q_mean, g_min_q_mean, d_min_loss, g_max_steps, d_max_steps,\n                      mc_sample_size, mc_sample_factor, first_to_train,\n                      save_interval, control_ratio, enable_logging):\n    \n    if enable_logging:\n        from tensorboardX import SummaryWriter\n        writer = SummaryWriter()\n\n    if os.path.isfile(sess_path):\n        adv_state = torch.load(sess_path)\n        model_config = adv_state['model_config']\n        model_state = adv_state['model_state']\n        model_optimizer_state = adv_state['model_optimizer_state']\n        discriminator_config = adv_state['discriminator_config']\n        discriminator_state = adv_state['discriminator_state']\n        discriminator_optimizer_state = adv_state['discriminator_optimizer_state']\n        print('-' * 70)\n        print('Session is loaded from', sess_path)\n        loaded_from_session = True\n\n    else:\n        model_sess = torch.load(model_load_path)\n        model_config = model_sess['model_config']\n        model_state = model_sess['model_state']\n        discriminator_sess = torch.load(discriminator_load_path)\n        discriminator_config = discriminator_sess['discriminator_config']\n        discriminator_state = discriminator_sess['discriminator_state']\n        loaded_from_session = False\n\n    model = PerformanceRNN(**model_config)\n    model.load_state_dict(model_state)\n    model.to(device).train()\n    model_optimizer = model_optimizer_class(model.parameters(), lr=model_learning_rate)\n\n    discriminator = EventSequenceEncoder(**discriminator_config)\n    discriminator.load_state_dict(discriminator_state)\n    discriminator.to(device).train()\n    discriminator_optimizer = discriminator_optimizer_class(discriminator.parameters(),\n                                                            lr=discriminator_learning_rate)\n\n    if loaded_from_session:\n        if not reset_model_optimizer:\n            model_optimizer.load_state_dict(model_optimizer_state)\n        if not reset_discriminator_optimizer:\n            discriminator_optimizer.load_state_dict(discriminator_optimizer_state)\n\n    g_loss_func = nn.CrossEntropyLoss()\n    d_loss_func = nn.BCEWithLogitsLoss(reduce=False)\n    \n\n    print('-' * 70)\n    print('Options')\n    print('sess_path:', sess_path)\n    print('save_interval:', save_interval)\n    print('batch_data_generator:', batch_data_generator)\n    print('control_ratio:', control_ratio)\n    print('g_max_q_mean:', g_max_q_mean)\n    print('g_min_q_mean:', g_min_q_mean)\n    print('d_min_loss:', d_min_loss)\n    print('mc_sample_size:', mc_sample_size)\n    print('mc_sample_factor:', mc_sample_factor)\n    print('enable_logging:', enable_logging)\n    print('model_load_path:', model_load_path)\n    print('model_loss:', g_loss_func)\n    print('model_optimizer_class:', model_optimizer_class)\n    print('model_gradient_clipping:', model_gradient_clipping)\n    print('model_learning_rate:', model_learning_rate)\n    print('reset_model_optimizer:', reset_model_optimizer)\n    print('discriminator_load_path:', discriminator_load_path)\n    print('discriminator_loss:', d_loss_func)\n    print('discriminator_optimizer_class:', discriminator_optimizer_class)\n    print('discriminator_gradient_clipping:', discriminator_gradient_clipping)\n    print('discriminator_learning_rate:', discriminator_learning_rate)\n    print('reset_discriminator_optimizer:', reset_discriminator_optimizer)\n    print('first_to_train:', first_to_train)\n    print('-' * 70)\n    print(f'Generator from \"{sess_path if loaded_from_session else model_load_path}\"')\n    print(model)\n    print(model_optimizer)\n    print('-' * 70)\n    print(f'Discriminator from \"{sess_path if loaded_from_session else discriminator_load_path}\"')\n    print(discriminator)\n    print(discriminator_optimizer)\n    print('-' * 70)\n    \n    \n    def save():\n        print(f'Saving to \"{sess_path}\"')\n        torch.save({\n            'model_config': model_config,\n            'model_state': model.state_dict(),\n            'model_optimizer_state': model_optimizer.state_dict(),\n            'discriminator_config': discriminator_config,\n            'discriminator_state': discriminator.state_dict(),\n            'discriminator_optimizer_state': discriminator_optimizer.state_dict()\n        }, sess_path)\n        print('Done saving')\n    \n    def mc_rollout(generated, hidden, total_steps, controls=None):\n        # generated: [t, batch_size]\n        # hidden: [n_layers, batch_size, hidden_dim]\n        # controls: [total_steps - t, batch_size, control_dim]\n        generated = torch.cat(generated, 0)\n        generated_steps, batch_size = generated.shape # t, b\n        steps = total_steps - generated_steps # s\n\n        generated = generated.unsqueeze(1) # [t, 1, b]\n        generated = generated.repeat(1, mc_sample_size, 1) # [t, mcs, b]\n        generated = generated.view(generated_steps, -1) # [t, mcs * b]\n\n        hidden = hidden.unsqueeze(1).repeat(1, mc_sample_size, 1, 1)\n        hidden = hidden.view(model.gru_layers, -1, model.hidden_dim)\n\n        if controls is not None:\n            assert controls.shape == (steps, batch_size, model.control_dim)\n            controls = controls.unsqueeze(1) # [s, 1, b, c]\n            controls = controls.repeat(1, mc_sample_size, 1, 1) # [s, mcs, b, c]\n            controls = controls.view(steps, -1, model.control_dim) # [s, mcs * b, c]\n\n        event = generated[-1].unsqueeze(0) # [1, mcs * b]\n        control = None # default when controls is None\n        outputs = []\n\n        for i in range(steps):\n            if controls is not None:\n                control = controls[i].unsqueeze(0) # [1, mcs * b, c]\n\n            output, hidden = model.forward(event, control=control, hidden=hidden)\n            probs = model.output_fc_activation(output / mc_sample_factor)\n            event = Categorical(probs).sample() # [1, mcs * b]\n            outputs.append(event)\n\n        sequences = torch.cat([generated, *outputs], 0)\n        assert sequences.shape == (total_steps, mc_sample_size * batch_size)\n        return sequences\n\n\n    def train_generator(batch_size, init, events, controls):\n        # Generator step\n        hidden = model.init_to_hidden(init)\n        event = model.get_primary_event(batch_size)\n        outputs = []\n        generated = []\n        q_values = []\n\n        for step in Bar('MC Rollout').iter(range(steps)):\n            control = controls[step].unsqueeze(0) if use_control else None\n            output, hidden = model.forward(event, control=control, hidden=hidden)\n            outputs.append(output)\n            probs = model.output_fc_activation(output / mc_sample_factor)\n            generated.append(Categorical(probs).sample())\n\n            with torch.no_grad():\n                if step < steps - 1:\n                    sequences = mc_rollout(generated, hidden, steps, controls[step+1:])\n                    mc_score = discriminator(sequences) # [mcs * b]\n                    mc_score = mc_score.view(mc_sample_size, batch_size) # [mcs, b]\n                    q_value = mc_score.mean(0, keepdim=True) # [1, batch_size]\n                \n                else:\n                    q_value = discriminator(torch.cat(generated, 0))\n                    q_value = q_value.unsqueeze(0) # [1, batch_size]\n            \n                q_values.append(q_value)\n        \n        # Compute loss\n        q_values = torch.cat(q_values, 0) # [steps, batch_size]\n        q_mean = q_values.mean().detach()\n        q_values = q_values - q_mean\n        generated = torch.cat(generated, 0) # [steps, batch_size]\n        outputs = torch.cat(outputs, 0) # [steps, batch_size, event_dim]\n        loss = F.cross_entropy(outputs.view(-1, model.event_dim),\n                               generated.view(-1),\n                               reduce=False)\n        loss = (loss * q_values.view(-1)).mean()\n\n        # Backprop\n        model.zero_grad()\n        loss.backward()\n\n        # Gradient clipping\n        norm = utils.compute_gradient_norm(model.parameters())\n        if model_gradient_clipping:\n            nn.utils.clip_grad_norm_(model.parameters(), model_gradient_clipping)\n\n        model_optimizer.step()\n\n        q_mean = q_mean.item()\n        norm = norm.item()\n        return q_mean, norm\n\n    def train_discriminator(batch_size, init, events, controls):\n        # Discriminator step\n        with torch.no_grad():\n            generated = model.generate(init, steps, None, controls,\n                                        greedy=0, temperature=mc_sample_factor)\n            \n        fake_logit = discriminator(generated, output_logits=True)\n        real_logit = discriminator(events, output_logits=True)\n        fake_target = torch.zeros_like(fake_logit)\n        real_target = torch.ones_like(real_logit)\n\n        # Compute loss\n        fake_loss = F.binary_cross_entropy_with_logits(fake_logit, fake_target)\n        real_loss = F.binary_cross_entropy_with_logits(real_logit, real_target)\n        loss = (real_loss + fake_loss) / 2\n\n        # Backprop\n        discriminator.zero_grad()\n        loss.backward()\n\n        # Gradient clipping\n        norm = utils.compute_gradient_norm(discriminator.parameters())\n        if discriminator_gradient_clipping:\n            nn.utils.clip_grad_norm_(discriminator.parameters(), discriminator_gradient_clipping)\n\n        discriminator_optimizer.step()\n\n        real_loss = real_loss.item()\n        fake_loss = fake_loss.item()\n        loss = loss.item()\n        norm = norm.item()\n        return loss, real_loss, fake_loss, norm\n\n    try:\n        last_save_time = time.time()\n        step_for = first_to_train\n        g_steps = 0\n        d_steps = 0\n        \n        for i, (events, controls) in enumerate(batch_data_generator):\n            steps, batch_size = events.shape\n            init = torch.randn(batch_size, model.init_dim).to(device)\n            events = torch.LongTensor(events).to(device)\n\n            use_control = np.random.random() <= control_ratio\n            controls = torch.FloatTensor(controls).to(device) if use_control else None\n\n            if step_for == 'G':\n                q_mean, norm = train_generator(batch_size, init, events, controls)\n                g_steps += 1\n\n                print(f'{i} (G-step) Q_mean: {q_mean}, norm: {norm}')\n                if enable_logging:\n                    writer.add_scalar('adversarial/G/Q_mean', q_mean, i)\n                    writer.add_scalar('adversarial/G/norm', norm, i)\n\n                if q_mean < g_min_q_mean:\n                    print(f'Q is too small: {q_mean}, exiting')\n                    raise KeyboardInterrupt\n\n                if q_mean > g_max_q_mean or (g_max_steps and g_steps >= g_max_steps):\n                    step_for = 'D'\n                    d_steps = 0\n\n            if step_for == 'D':\n                loss, real_loss, fake_loss, norm = train_discriminator(batch_size, init, events, controls)\n                d_steps += 1\n\n                print(f'{i} (D-step) loss: {loss} (real: {real_loss}, fake: {fake_loss}), norm: {norm}')\n                if enable_logging:\n                    writer.add_scalar('adversarial/D/loss', loss, i)\n                    writer.add_scalar('adversarial/D/norm', norm, i)\n\n                if fake_loss <= real_loss < d_min_loss or (d_max_steps and d_steps >= d_max_steps):\n                    step_for = 'G'\n                    g_steps = 0\n\n            if last_save_time + save_interval < time.time():\n                last_save_time = time.time()\n                save()\n\n    except KeyboardInterrupt:\n        save()\n\n\n\n#========================================================================\n# Script Arguments\n#========================================================================\n\ndef batch_generator(args):\n    print('-' * 70)\n    dataset = Dataset(args.dataset_path, verbose=True)\n    print(dataset)\n    return dataset.batches(args.batch_size, args.window_size, args.stride_size)\n\ndef pretrain(args):\n    pretrain_discriminator(model_sess_path=args.generator_session_path,\n                           discriminator_sess_path=args.discriminator_session_path,\n                           discriminator_config_overwrite=utils.params2dict(args.discriminator_parameters),\n                           batch_data_generator=args.batch_generator(args),\n                           gradient_clipping=args.gradient_clipping,\n                           sample_factor=args.sample_factor,\n                           auto_sample_factor=args.auto_sample_factor,\n                           control_ratio=args.control_ratio,\n                           num_iter=args.stop_iteration,\n                           save_interval=args.save_interval,\n                           discriminator_lr=args.discriminator_learning_rate,\n                           enable_logging=args.enable_logging)\n\ndef adversarial(args):\n    train_adversarial(sess_path=args.session_path,\n                      batch_data_generator=args.batch_generator(args),\n                      model_load_path=args.generator_load_path,\n                      discriminator_load_path=args.discriminator_load_path,\n                      model_optimizer_class=getattr(optim, args.generator_optimizer),\n                      discriminator_optimizer_class=getattr(optim, args.discriminator_optimizer),\n                      model_gradient_clipping=args.generator_gradient_clipping,\n                      discriminator_gradient_clipping=args.discriminator_gradient_clipping,\n                      model_learning_rate=args.generator_learning_rate,\n                      discriminator_learning_rate=args.discriminator_learning_rate,\n                      reset_model_optimizer=args.reset_generator_optimizer,\n                      reset_discriminator_optimizer=args.reset_discriminator_optimizer,\n                      g_max_q_mean=args.g_max_q_mean,\n                      g_min_q_mean=args.g_min_q_mean,\n                      d_min_loss=args.d_min_loss,\n                      g_max_steps=args.g_max_steps,\n                      d_max_steps=args.d_max_steps,\n                      mc_sample_size=args.monte_carlo_sample_size,\n                      mc_sample_factor=args.monte_carlo_sample_factor,\n                      first_to_train=args.first_to_train,\n                      control_ratio=args.control_ratio,\n                      save_interval=args.save_interval,\n                      enable_logging=args.enable_logging)\n\ndef get_args():\n    parser = argparse.ArgumentParser()\n    subparsers = parser.add_subparsers()\n    parser.add_argument('-d', '--dataset-path', type=str, required=True)\n    parser.add_argument('-b', '--batch-size', type=int, default=64)\n    parser.add_argument('-w', '--window-size', type=int, default=200)\n    parser.add_argument('-s', '--stride-size', type=int, default=10)\n    parser.set_defaults(batch_generator=batch_generator)\n    pre_parser = subparsers.add_parser('pretrain', aliases=['p', 'pre'])\n    pre_parser.add_argument('-G', '--generator-session-path', type=str, default=True)\n    pre_parser.add_argument('-D', '--discriminator-session-path', type=str, required=True)\n    pre_parser.add_argument('-p', '--discriminator-parameters', type=str, default='')\n    pre_parser.add_argument('-l', '--discriminator-learning-rate', type=float, default=0.001)\n    pre_parser.add_argument('-g', '--gradient-clipping', type=float, default=False)\n    pre_parser.add_argument('-f', '--sample-factor', type=float, default=1.0)\n    pre_parser.add_argument('-af', '--auto-sample-factor', action='store_true', default=False)\n    pre_parser.add_argument('-c', '--control-ratio', type=float, default=1.0)\n    pre_parser.add_argument('-n', '--stop-iteration', type=int, default=-1)\n    pre_parser.add_argument('-i', '--save-interval', type=float, default=60.0)\n    pre_parser.add_argument('-L', '--enable-logging', action='store_true', default=False)\n    pre_parser.set_defaults(main=pretrain)\n    adv_parser = subparsers.add_parser('adversarial', aliases=['a', 'adv'])\n    adv_parser.add_argument('-S', '--session-path', type=str, required=True)\n    adv_parser.add_argument('-Gp', '--generator-load-path', type=str)\n    adv_parser.add_argument('-Dp', '--discriminator-load-path', type=str)\n    adv_parser.add_argument('-Go', '--generator-optimizer', type=str, default='Adam')\n    adv_parser.add_argument('-Do', '--discriminator-optimizer', type=str, default='RMSprop')\n    adv_parser.add_argument('-Gg', '--generator-gradient-clipping', type=float, default=False)\n    adv_parser.add_argument('-Dg', '--discriminator-gradient-clipping', type=float, default=False)\n    adv_parser.add_argument('-Gl', '--generator-learning-rate', type=float, default=0.001)\n    adv_parser.add_argument('-Dl', '--discriminator-learning-rate', type=float, default=0.001)\n    adv_parser.add_argument('-Gr', '--reset-generator-optimizer', action='store_true', default=False)\n    adv_parser.add_argument('-Dr', '--reset-discriminator-optimizer', action='store_true', default=False)\n    adv_parser.add_argument('-Gq', '--g-max-q-mean', type=float, default=0.5)\n    adv_parser.add_argument('-Gm', '--g-min-q-mean', type=float, default=0.0)\n    adv_parser.add_argument('-Dm', '--d-min-loss', type=float, default=0.5)\n    adv_parser.add_argument('-Gs', '--g-max-steps', type=int, default=0)\n    adv_parser.add_argument('-Ds', '--d-max-steps', type=int, default=0)\n    adv_parser.add_argument('-f', '--first-to-train', type=str, default='G', choices=['G', 'D'])\n    adv_parser.add_argument('-ms', '--monte-carlo-sample-size', type=int, default=8)\n    adv_parser.add_argument('-mf', '--monte-carlo-sample-factor', type=float, default=1.0)\n    adv_parser.add_argument('-c', '--control-ratio', type=float, default=1.0)\n    adv_parser.add_argument('-i', '--save-interval', type=float, default=60.0)\n    adv_parser.add_argument('-L', '--enable-logging', action='store_true', default=False)\n    adv_parser.set_defaults(main=adversarial)\n    return parser.parse_args()\n\n\nif __name__ == '__main__':\n    args = get_args()\n    args.main(args)\n", "meta": {"hexsha": "94d556d4382fbee2b170d34074b8fcbf26cb8046", "size": 26464, "ext": "py", "lang": "Python", "max_stars_repo_path": "adversarial.py", "max_stars_repo_name": "hircumg/Performance-RNN-PyTorch", "max_stars_repo_head_hexsha": "db07a73e399d0fcdc080e8fbe4adb30bbb702e7e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 119, "max_stars_repo_stars_event_min_datetime": "2018-05-23T19:17:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T07:48:11.000Z", "max_issues_repo_path": "adversarial.py", "max_issues_repo_name": "jakeypaulyguyy/Performance-RNN-PyTorch", "max_issues_repo_head_hexsha": "83ca93a2186ab5655fb2ca6e4ea9ce177e9d6111", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-05-25T05:47:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-24T13:00:42.000Z", "max_forks_repo_path": "adversarial.py", "max_forks_repo_name": "jakeypaulyguyy/Performance-RNN-PyTorch", "max_forks_repo_head_hexsha": "83ca93a2186ab5655fb2ca6e4ea9ce177e9d6111", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34, "max_forks_repo_forks_event_min_datetime": "2018-06-07T18:17:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-19T22:54:47.000Z", "avg_line_length": 43.9601328904, "max_line_length": 107, "alphanum_fraction": 0.6222415357, "include": true, "reason": "import numpy", "num_tokens": 5435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3140505578320071, "lm_q1q2_score": 0.17413175882219453}}
{"text": "\"\"\" Proof of concept for n-way matching using footprint detection\n\nSome terminology:\n\ncell    :   A small area, used to find matches,  The size\n    should be about the same as the maximum match radius.\n\nsource   :  As per DM, per-catalog detection\n\nmatchWcs :  The WCS used to define the cells\n\nsubRegion : A square sub-region of the skymap defined by the matchWcs\n\nsourceCountsMap :  A map of the number of source per cell, made per\n   subRegion\n\nCluster:  A set of sources found by running a footprint finding algorithm\n   on a sourceCountsMap\n\n\"\"\"\n\nimport sys\nimport os\nimport glob\n\nfrom collections import OrderedDict\n\nimport time\nimport numpy as np\nfrom astropy import wcs\nfrom astropy.table import Table\nfrom astropy.table import vstack\nfrom astropy.io import fits\n\ntry:\n    import pyarrow.parquet as pq  # noqa\nexcept ImportError:\n    print(\"nway requires pyarrrow\")\n\ntry:\n    import lsst.afw.detection as afwDetect\n    import lsst.afw.image as afwImage\nexcept ImportError:\n    print(\"nway requires lsst.afw\")    \n    \nRECURSE_MAX = 200\nCOLUMNS = ['ra', 'decl', 'visit', 'ccd', 'sky_source', 'sourceId', 'PsFlux', 'PsFluxErr', 'Centroid_flag', 'detect_isPrimary']\n\ndef createGlobalWcs(refDir, cellSize, nCell):\n    \"\"\" Helper function to create the WCS used to project the\n    sources in a skymap \"\"\"\n    w = wcs.WCS(naxis=2)\n    w.wcs.cdelt = [-cellSize, cellSize]\n    w.wcs.crpix = [nCell[0]/2, nCell[1]/2]\n    w.wcs.crval = [refDir[0], refDir[1]]\n    return w\n\ndef clusterStats(clusterDict):\n    \"\"\" Helper function to get stats about the clusters\n\n    'Orphan'   means single source clusters (i.e., single detections)\n    'Mixed`    means there is more that one source from at least one\n               input catalog\n    'Confused' means there are more than four cases of duplication\n    \"\"\"\n    nOrphan = 0\n    nMixed = 0\n    nConfused = 0\n    for val in clusterDict.values():\n        if val.nSrc == 1:\n            nOrphan += 1\n        if val.nSrc != val.nUnique:\n            nMixed += 1\n            if val.nSrc > val.nUnique + 3:\n                nConfused += 1\n    return np.array([len(clusterDict), nOrphan, nMixed, nConfused])\n\n\nclass ClusterData:\n    \"\"\" Class to store data about clusters\n\n    Parameters\n    ----------\n    iCluster : `int`\n        Cluster ID\n    origCluster : `int`\n        Id of the original cluster this cluster was made from\n    nSrc : `int`\n        Number of sources in this cluster\n    nUnique : `int`\n        Number of catalogs contributing sources to this cluster\n    catIndices : `np.array`, [`int`]\n        Indices of the catalogs of sources associated to this cluster\n    sourcdIds : `np.array`, [`int`]\n        Sources IDs of the sources associated to this cluster\n    sourcdIdxs : `np.array`, [`int`]\n        Indices of the sources with their respective catalogs\n    xCent : `float`\n        X-pixel value of cluster centroid (in WCS used to do matching)\n    yCent : `float`\n        Y-pixel value of cluster centroid (in WCS used to do matching)\n    \"\"\"\n    def __init__(self, iCluster, footprint, sources, origCluster=None):\n        self._iCluster = iCluster\n        self._footprint = footprint\n        if origCluster is None:\n            self._origCluster = self._iCluster\n        else:\n            self._origCluster = origCluster\n        self._catIndices = sources[0]\n        self._sourceIds = sources[1]\n        self._sourceIdxs = sources[2]\n        self._nSrc =  self._catIndices.size\n        self._nUnique = len(np.unique(self._catIndices))\n        self._objects = []\n        self._xCent = None\n        self._yCent = None\n        self._dist2 = None\n        self._rmsDist = None\n        self.xCell = None\n        self.yCell = None\n        self.snr = None\n\n    def extract(self, subRegionData):\n        \"\"\" Extract the xCell, yCell and snr data from\n        the sources in this cluster\n        \"\"\"\n        self.xCell = np.zeros((self._nSrc), np.float32)\n        self.yCell = np.zeros((self._nSrc), np.float32)\n        self.snr = np.zeros((self._nSrc), np.float32)\n        for i, (iCat, srcIdx) in enumerate(zip(self._catIndices, self._sourceIdxs)):\n            self.xCell[i] = subRegionData.data[iCat]['xcell'].values[srcIdx]\n            self.yCell[i] = subRegionData.data[iCat]['ycell'].values[srcIdx]\n            self.snr[i] = subRegionData.data[iCat]['SNR'].values[srcIdx]\n\n    def clearTempData(self):\n        \"\"\" Remove temporary data only used when making objects \"\"\"\n        self.xCell = None\n        self.yCell = None\n        self.snr = None\n\n    @property\n    def iCluster(self):\n        \"\"\" Return the cluster ID \"\"\"\n        return self._iCluster\n\n    @property\n    def nSrc(self):\n        \"\"\" Return the number of sources associated to the cluster \"\"\"\n        return self._nSrc\n\n    @property\n    def nUnique(self):\n        \"\"\" Return the number of catalogs contributing sources to the cluster \"\"\"\n        return self._nUnique\n\n    @property\n    def sourceIds(self):\n        \"\"\" Return the source IDs associated to this cluster \"\"\"\n        return self._sourceIds\n\n    @property\n    def dist2(self):\n        \"\"\" Return an array with the distance squared (in cells)\n        between each source and the cluster centroid \"\"\"\n        return self._dist2\n\n    @property\n    def objects(self):\n        \"\"\" Return the objects associated with this cluster \"\"\"\n        return self._objects\n\n    def processCluster(self, subRegionData, pixelR2Cut):\n        \"\"\" Function that is called recursively to\n        split clusters until they:\n\n        1.  Consist only of sources with the match radius of the cluster\n        centroid.\n\n        2.  Have at most one source per input catalog\n        \"\"\"\n        self._nSrc =  self._catIndices.size\n        self._nUnique = len(np.unique(self._catIndices))\n        if self._nSrc == 0:\n            print(\"Empty cluster\", self._nSrc, self._nUnique)\n            return self._objects\n        self.extract(subRegionData)\n        if self._nSrc == 1:\n            self._xCent = self.xCell[0]\n            self._yCent = self.yCell[0]\n            self._dist2 = np.zeros((1))\n            self._rmsDist = 0.\n            initialObject = self.addObject(subRegionData)\n            initialObject.processObject(subRegionData, pixelR2Cut)\n            self.clearTempData()\n            return self._objects\n\n        sumSnr = np.sum(self.snr)\n        self._xCent = np.sum(self.xCell*self.snr) / sumSnr\n        self._yCent = np.sum(self.yCell*self.snr) / sumSnr\n        self._dist2 = (self._xCent - self.xCell)**2 + (self._yCent - self.yCell)**2\n        self._rmsDist = np.sqrt(np.mean(self._dist2))\n        \n        initialObject = self.addObject(subRegionData)\n        initialObject.processObject(subRegionData, pixelR2Cut)\n        self.clearTempData()\n        return self._objects\n\n    def addObject(self, subRegionData, mask=None):\n        \"\"\" Add a new object to this cluster \"\"\"\n        newObject = subRegionData.addObject(self, mask)\n        self._objects.append(newObject)\n        return newObject\n\n\nclass ObjectData:\n    \"\"\" Small class to define 'Objects', i.e., sets of associated sources \"\"\"\n\n    def __init__(self, cluster, objectId, mask):\n        \"\"\" Build from `ClusterData`, an objectId and mask specifying with sources\n        in the cluster are part of the object \"\"\"\n        self._parentCluster = cluster\n        self._objectId = objectId\n        if mask is None:\n            self._mask = np.ones((self._parentCluster.nSrc), dtype=bool)\n        else:\n            self._mask = mask\n        self._catIndices = self._parentCluster._catIndices[self._mask]\n        self._nSrc = self._catIndices.size\n        self._nUnique = np.unique(self._catIndices).size\n        self._xCent = None\n        self._yCent = None\n        self._dist2 = None\n        self._rmsDist = None\n\n    @property\n    def nSrc(self):\n        \"\"\" Return the number of sources associated to the cluster \"\"\"\n        return self._nSrc\n\n    @property\n    def nUnique(self):\n        \"\"\" Return the number of catalogs contributing sources to the cluster \"\"\"\n        return self._nUnique\n\n    @property\n    def dist2(self):\n        \"\"\" Return an array with the distance squared (in cells)\n        between each source and the cluster centroid \"\"\"\n        return self._dist2\n\n    def updateCatIndices(self):\n        self._catIndices = self._parentCluster._catIndices[self._mask]\n        self._nSrc = self._catIndices.size\n        self._nUnique = np.unique(self._catIndices).size\n\n    def sourceIds(self):\n        return self._parentCluster.sourceIds[self._mask]\n        \n    def processObject(self, subRegionData, pixelR2Cut, recurse=0):\n        \"\"\" Recursively process an object and make sub-objects \"\"\"\n        if recurse > RECURSE_MAX:\n            print(\"Recursion limit: \", self._nSrc, self._nUnique)\n            return\n        if self._nSrc == 0:\n            print(\"Empty object\", self._nSrc, self._nUnique, recurse)\n            return\n\n        xCell = self._parentCluster.xCell[self._mask]\n        yCell = self._parentCluster.yCell[self._mask]\n        snr = self._parentCluster.snr[self._mask]\n\n        if self._mask.sum() == 1:\n            self._xCent = xCell[0]\n            self._yCent = yCell[0]\n            self._dist2 = np.zeros((1), float)\n            self._rmsDist = 0.\n            return\n\n        sumSnr = np.sum(snr)\n        self._xCent = np.sum(xCell*snr) / sumSnr\n        self._yCent = np.sum(yCell*snr) / sumSnr\n        self._dist2 = np.array((self._xCent - xCell)**2 + (self._yCent - yCell)**2)\n        self._rmsDist = np.sqrt(np.mean(self._dist2))\n        subMask = self._dist2 < pixelR2Cut\n        if subMask.all():\n            if self._nSrc != self._nUnique:\n                self.splitObject(subRegionData, pixelR2Cut, recurse=recurse+1)\n            return\n\n        if not subMask.any():\n            idx = np.argmax(snr)\n            self._xCent = xCell[idx]\n            self._yCent = yCell[idx]\n            self._dist2 = np.array((self._xCent - xCell)**2 + (self._yCent - yCell)**2)\n            self._rmsDist = np.sqrt(np.mean(self._dist2))\n            subMask = self._dist2 < pixelR2Cut\n\n        newObjMask = self._mask.copy()\n        newObjMask[newObjMask] *= subMask\n\n        newObject = self._parentCluster.addObject(subRegionData, newObjMask)\n        newObject.processObject(subRegionData, pixelR2Cut)\n\n        self._mask[self._mask] *= ~subMask\n        self.updateCatIndices()\n        self.processObject(subRegionData, pixelR2Cut, recurse=recurse+1)\n\n\n    def splitObject(self, subRegionData, pixelR2Cut, recurse=0):\n        \"\"\" Split up a cluster keeping only one source per input\n        catalog, choosing the one closest to the cluster center \"\"\"\n        sortIdx = np.argsort(self._dist2)\n        mask = np.ones((self._nSrc), dtype=bool)\n        usedCats = {}\n        for iSrc, catIdx in zip(sortIdx, self._catIndices[sortIdx]):\n            if catIdx not in usedCats:\n                usedCats[catIdx] = 1\n                continue\n            else:\n                usedCats[catIdx] += 1\n            mask[iSrc] = False\n\n        newObjMask = self._mask.copy()\n        newObjMask[newObjMask] *= mask\n\n        newObject = self._parentCluster.addObject(subRegionData, newObjMask)\n        newObject.processObject(subRegionData, pixelR2Cut)\n\n        self._mask[self._mask] *= ~mask\n        self.updateCatIndices()        \n        self.processObject(subRegionData, pixelR2Cut, recurse=recurse+1)\n\n\nclass SubregionData:\n    \"\"\" Class to analyze data for a SubRegion\n\n    Include sub-region boundries, reduced data tables\n    and clustering results\n\n    Does not store sky maps\n\n    Subregions are square sub-regions of the Skymap\n    constructed with the WCS\n\n    The subregion covers corner:corner+size\n\n    The sources are projected into an array that extends `buf` cells\n    beyond the region.\n\n    Parameters\n    ----------\n    _data : `list`, [`Dataframe`]\n        Reduced dataframes with only sources for this sub-region\n\n    _clusterIds : `list`, [`np.array`]\n        Matched arrays with the index of the cluster associated to each\n        source.  I.e., these could added to the Dataframes as\n        additional columns\n\n    _clusterDict : `dict`, [`int` : `ClusterData`]\n        Dictionary with cluster membership data\n\n    TODO:  Add code to filter out clusters centered in the buffer\n    \"\"\"\n    def __init__(self, matcher, idOffset, corner, size, buf=10):\n        self._matcher = matcher\n        self._idOffset = idOffset # Offset used for the Object and Cluster IDs for this region\n        self._corner = corner # cellX, cellY for corner of region\n        self._size = size # size of region\n        self._buf = buf\n        self._minCell = corner - buf\n        self._maxCell = corner + size + buf\n        self._nCells = self._maxCell - self._minCell\n        self._data = None\n        self._nSrc = None\n        self._footprintIds = None\n        self._clusterDict = OrderedDict()\n        self._objectDict = OrderedDict()\n\n    def reduceData(self, data):\n        \"\"\" Pull out only the data needed for this sub-region \"\"\"\n        self._data = [self.reduceDataframe(val) for val in data]\n        self._nSrc = sum([len(df) for df in self._data])\n        \n    @property\n    def nClusters(self):\n        \"\"\" Return the number of clusters in this region \"\"\"\n        return len(self._clusterDict)\n\n    @property\n    def nObjects(self):\n        \"\"\" Return the number of objects in this region \"\"\"\n        return len(self._objectDict)\n\n    @property\n    def data(self):\n        \"\"\" Return the data associated to this region \"\"\"\n        return self._data\n\n    @property\n    def clusterDist(self):\n        \"\"\" Return a dictionary mapping clusters Ids to clusters \"\"\"\n        return self._clusterDict\n\n    def reduceDataframe(self, dataframe):\n        \"\"\" Filters dataframe to keep only source in the subregion \"\"\"\n        xLocal = dataframe['xcell'] - self._minCell[0]\n        yLocal = dataframe['ycell'] - self._minCell[1]\n        filtered = (xLocal >= 0) & (xLocal < self._nCells[0]) & (yLocal >= 0) & (yLocal < self._nCells[1])\n        red = dataframe[filtered].copy(deep=True)\n        red['xlocal'] = xLocal[filtered]\n        red['ylocal'] = yLocal[filtered]\n        return red\n\n    def countsMap(self, weightName=None):\n        \"\"\" Fill a map that counts the number of source per cell \"\"\"\n        toFill = np.zeros((self._nCells))\n        for df in self._data:\n            toFill += self.fillSubRegionFromDf(df, weightName=weightName)\n        return toFill\n\n    def associateSourcesToFootprints(self, clusterKey):\n        \"\"\" Loop through data and associate sources to clusters \"\"\"\n        self._footprintIds = [self.findClusterIds(df, clusterKey) for df in self._data]\n\n    def buildClusterData(self, fpSet, pixelR2Cut=4.):\n        \"\"\" Loop through cluster ids and collect sources into\n        the ClusterData objects \"\"\"\n        footprints = fpSet.getFootprints()\n        footprintDict = {}\n        nMissing = 0\n        nFound = 0\n        for iCat, (df, footprintIds) in enumerate(zip(self._data, self._footprintIds)):\n            for srcIdx, (srcId, footprintId) in enumerate(zip(df['sourceId'], footprintIds)):\n                if footprintId < 0:\n                    nMissing += 1\n                    continue\n                if footprintId not in footprintDict:\n                    footprintDict[footprintId] = [(iCat, srcId, srcIdx)]\n                else:\n                    footprintDict[footprintId].append((iCat, srcId, srcIdx))\n                nFound += 1\n        for footprintId, sources in footprintDict.items():\n            footprint = footprints[footprintId]\n            iCluster = footprintId+self._idOffset\n            cluster = ClusterData(iCluster, footprint, np.array(sources).T)\n            self._clusterDict[iCluster] = cluster\n            cluster.processCluster(self, pixelR2Cut)\n\n    def analyze(self, weightName=None, pixelR2Cut=4.):\n        \"\"\" Analyze this sub-region\n\n        Note that this returns the counts maps and clustering info,\n        which can be helpful for debugging.\n        \"\"\"\n        if self._nSrc == 0:\n            return None\n        countsMap = self.countsMap(weightName)\n        oDict = self.getFootprints(countsMap)\n        oDict['countsMap'] = countsMap\n        self.associateSourcesToFootprints(oDict['footprintKey'])\n        self.buildClusterData(oDict['footprints'], pixelR2Cut)\n        return oDict\n\n    @staticmethod\n    def findClusterIds(df, clusterKey):\n        \"\"\" Associate sources to clusters using `clusterkey`\n        which is a map where any pixel associated to a cluster\n        has the cluster index as its value \"\"\"\n        return np.array([clusterKey[yLocal,xLocal] for xLocal, yLocal in zip(df['xlocal'], df['ylocal'])]).astype(np.int32)\n\n    def fillSubRegionFromDf(self, df, weightName=None):\n        \"\"\" Fill a source counts map from a reduced dataframe for one input\n        catalog \"\"\"\n        if weightName is None:\n            weights = None\n        else:\n            weights = df[weightName].values\n        hist = np.histogram2d(df['xlocal'], df['ylocal'], bins=self._nCells,\n                              range=((0, self._nCells[0]),\n                                     (0, self._nCells[1])),\n                              weights=weights)\n        return hist[0]\n\n    @staticmethod\n    def filterFootprints(fpSet, buf):\n        \"\"\" Remove footprints within `buf` cells of the region edge \"\"\"\n        region = fpSet.getRegion()\n        width, height = region.getWidth(), region.getHeight()\n        outList = []\n        maxX = width - buf\n        maxY = height - buf\n        for fp in fpSet.getFootprints():\n            cent = fp.getCentroid()\n            xC = cent.getX()\n            yC = cent.getY()\n            if xC < buf or xC > maxX or yC < buf or yC > maxY:\n                continue\n            outList.append(fp)\n        fpSetOut = afwDetect.FootprintSet(fpSet.getRegion())\n        fpSetOut.setFootprints(outList)\n        return fpSetOut\n\n    def getFootprints(self, countsMap):\n        \"\"\" Take a source counts map and do clustering using Footprint detection\n        \"\"\"\n        image = afwImage.ImageF(countsMap.astype(np.float32))\n        footprintsOrig = afwDetect.FootprintSet(image, afwDetect.Threshold(0.5))\n        footprints = self.filterFootprints(footprintsOrig, self._buf)\n        footprintKey = afwImage.ImageI(np.full(countsMap.shape, -1, dtype=np.int32))\n        for i, footprint in enumerate(footprints.getFootprints()):\n            footprint.spans.setImage(footprintKey, i, doClip=True)\n        return dict(image=image, footprints=footprints, footprintKey=footprintKey)\n\n    def getClusterAssociations(self):\n        \"\"\" Convert the clusters to a set of associations \"\"\"\n        clusterIds = []\n        sourceIds = []\n        distances = []\n        for cluster in self._clusterDict.values():\n            clusterIds.append(np.full((cluster.nSrc), cluster.iCluster, dtype=int))\n            sourceIds.append(cluster.sourceIds)\n            distances.append(cluster.dist2)\n        if not distances:\n            return Table(dict(distance=[], id=np.array([], int), object=np.array([], int)))\n        distances = np.hstack(distances)\n        distances = self._matcher.cellToArcsec() * np.sqrt(distances)\n        data = dict(object=np.hstack(clusterIds),\n                    id=np.hstack(sourceIds),\n                    distance=distances)\n        return Table(data)\n\n    def getObjectAssociations(self):\n        clusterIds = []\n        objectIds = []\n        sourceIds = []\n        distances = []\n        for obj in self._objectDict.values():\n            clusterIds.append(np.full((obj._nSrc), obj._parentCluster.iCluster, dtype=int))\n            objectIds.append(np.full((obj._nSrc), obj._objectId, dtype=int))\n            sourceIds.append(obj.sourceIds())\n            distances.append(obj.dist2)\n        if not distances:\n            return Table(dict(object=np.array([], int),\n                              parent=np.array([], int),\n                              id=np.array([], int),\n                              distance=[]))\n        distances = np.hstack(distances)\n        distances = self._matcher.cellToArcsec() * np.sqrt(distances)            \n        data = dict(object=np.hstack(objectIds),\n                    parent=np.hstack(clusterIds),\n                    id=np.hstack(sourceIds),\n                    distance=distances)\n        return Table(data)\n\n    def getClusterStats(self):\n        \"\"\" Convert the clusters to a set of associations \"\"\"\n        nClust = self.nClusters\n        clusterIds = np.zeros((nClust), dtype=int)\n        nSrcs = np.zeros((nClust), dtype=int)\n        nObjects = np.zeros((nClust), dtype=int)\n        nUniques = np.zeros((nClust), dtype=int)\n        distRms = np.zeros((nClust), dtype=float)\n        xCents = np.zeros((nClust), dtype=float)\n        yCents = np.zeros((nClust), dtype=float)\n        for idx, cluster in enumerate(self._clusterDict.values()):\n            clusterIds[idx] = cluster._iCluster\n            nSrcs[idx] = cluster.nSrc\n            nObjects[idx] = len(cluster._objects)\n            nUniques[idx] = cluster.nUnique\n            distRms[idx] = cluster._rmsDist\n            xCents[idx] = cluster._xCent\n            yCents[idx] = cluster._yCent\n        ra, decl = self._matcher.cellToWorld(xCents, yCents)\n        distRms *= self._matcher.cellToArcsec()\n\n        data = dict(clusterIds=clusterIds,\n                    nSrcs=nSrcs,\n                    nObject=nObjects,\n                    nUnique=nUniques,\n                    distRms=distRms,\n                    ra=ra,\n                    decl=decl)\n\n        return Table(data)\n\n    def getObjectStats(self):\n        \"\"\" Convert the clusters to a set of associations \"\"\"\n        nObj = self.nObjects\n        clusterIds = np.zeros((nObj), dtype=int)\n        objectIds = np.zeros((nObj), dtype=int)\n        nSrcs = np.zeros((nObj), dtype=int)\n        distRms = np.zeros((nObj), dtype=float)\n        xCents = np.zeros((nObj), dtype=float)\n        yCents = np.zeros((nObj), dtype=float)\n        for idx, obj in enumerate(self._objectDict.values()):\n            clusterIds[idx] = obj._parentCluster._iCluster\n            objectIds[idx] = obj._objectId\n            nSrcs[idx] = obj.nSrc\n            distRms[idx] = obj._rmsDist\n            xCents[idx] = obj._xCent\n            yCents[idx] = obj._yCent\n\n        ra, decl = self._matcher.cellToWorld(xCents, yCents)\n        distRms *= self._matcher.cellToArcsec()\n        \n        data = dict(clusterIds=clusterIds,\n                    objectIds=objectIds,\n                    nSrcs=nSrcs,\n                    distRms=distRms,\n                    ra=ra,\n                    decl=decl)\n\n        return Table(data)\n\n    def addObject(self, cluster, mask=None):\n        \"\"\" Add an object to this sub-region \"\"\"\n        objectId = self.nObjects + self._idOffset\n        newObject = ObjectData(cluster, objectId, mask)\n        self._objectDict[objectId] = newObject\n        return newObject\n\n\nclass NWayMatch:\n    \"\"\" Class to do N-way matching\n\n    Uses a provided WCS to define a Skymap that covers the full region\n    begin matched.\n\n    Uses that WCS to assign cell locations to all sources in the input catalogs\n\n    Iterates over sub-regions and does source clustering in each sub-region\n    using Footprint detection on a Skymap of source counts per cell.\n\n    Assigns each input source to a cluster.\n\n    At that stage the clusters are not the final product as they can include\n    more than one soruce from a given catalog.\n\n    Loops over clusters and processes each cluster to:\n\n       1. Remove outliers outside the match radius w.r.t. the cluster centroid.\n       2. Resolve cases of confusion, where multiple sources from a single\n       catalog contribute to a cluster.\n\n    Parameters\n    ----------\n    _redData : `list`, [`Dataframe`]\n        Reduced dataframes with only the columns needed for matching\n\n    _clusters : `OrderedDict`, [`tuple`, `SubregionData`]\n        Dictionary providing access to subregion data\n    \"\"\"\n\n    def __init__(self, matchWcs, **kwargs):\n        self._wcs = matchWcs\n        self._cellSize = self._wcs.wcs.cdelt[1]\n        self._nCellSide = np.ceil(2*np.array(self._wcs.wcs.crpix)).astype(int)\n        self._subRegionSize = kwargs.get('subRegionSize', 3000)\n        self._subRegionBuffer = kwargs.get('subRegionBuffer', 10)\n        self._subregionMaxObject = kwargs.get('subregionMaxObject', 100000)\n        self._pixelR2Cut = kwargs.get('pixelR2Cut', 1.0)\n        self._nSubRegion = np.ceil(self._nCellSide/self._subRegionSize)\n        self._redData = OrderedDict()\n        self._clusters = None\n\n    def cellToArcsec(self):\n        return 3600. * self._cellSize\n\n    def cellToWorld(self, xCell, yCell):\n        return self._wcs.wcs_pix2world(xCell, yCell, 0)\n    \n    @classmethod\n    def create(cls, refDir, regionSize, cellSize, **kwargs):\n        \"\"\" Make an `NWayMatch` object from inputs \"\"\"\n        nCell = (np.array(regionSize)/cellSize).astype(int)\n        matchWcs = createGlobalWcs(refDir, cellSize, nCell)\n        return cls(matchWcs, **kwargs)\n\n    @property\n    def redData(self):\n        \"\"\" Return the dictionary of reduced data, i.e., just the columns\n        need for matching \"\"\"\n        return self._redData\n\n    @property\n    def nSubRegion(self):\n        \"\"\" Return the number of sub-regions in X,Y \"\"\"\n        return self._nSubRegion\n\n    def reduceData(self, inputFiles, visitIds):\n        \"\"\" Read input files and filter out only the columns we need \"\"\"\n        for fName, vid in zip(inputFiles, visitIds):\n            self._redData[vid] = self.reduceDataFrame(fName)\n\n    def reduceDataFrame(self, fName):\n        \"\"\" Read and reduce a single input file \"\"\"\n        parq = pq.read_pandas(fName, columns=COLUMNS)\n        df = parq.to_pandas()\n        df['SNR'] = df['PsFlux']/df['PsFluxErr']\n        # select sources that have SNR > 5.\n        # You may start with 10 or even 50 if you want to start with just the brightest objects\n        # AND\n        # Centroid_flag is True if there was a problem fitting the position (centroid)\n        # AND\n        # sky_source is True if it is a measurement of blank sky.\n        # sky_sources should have SNR < 5 or the Centroid_flag set,\n        # but explicitly filter just to make sure.\n        # AND\n        # detect_isPrimary = True to remove duplicate rows from deblending:\n        # If a source has been deblended, the parent is marked detect_isPrimary=False and its children True.\n        df_clean = df[(df.SNR > 5) & ~df.Centroid_flag & ~df.sky_source & df.detect_isPrimary]\n        xcell, ycell = self._wcs.wcs_world2pix(df_clean['ra'].values, df_clean['decl'].values, 0)\n        df_red = df_clean[[\"ra\", \"decl\", \"SNR\", \"sourceId\"]].copy(deep=True)\n        df_red['xcell'] = xcell\n        df_red['ycell'] = ycell\n        return df_red[[\"ra\", \"decl\", \"SNR\", \"sourceId\", \"xcell\", \"ycell\"]]\n\n    def reduceCatalog(self, catalog):\n        \"\"\" Reduce a catalog \"\"\"\n        raise NotImplementedError()\n\n    def add(self, catalog, vid):\n        \"\"\" Add a catalog to the data set being matched \"\"\"\n        self._redData[vid] = self.reduceCatalog(catalog)\n\n    def getIdOffset(self, ix, iy):\n        \"\"\" Get the ID offset to use for a given sub-region \"\"\"\n        subRegionIdx = self._nSubRegion[1]*ix + iy\n        return int(self._subregionMaxObject * subRegionIdx)\n\n    def analyzeSubregion(self, ix, iy, fullData=False):\n        \"\"\" Analyze a single subregion\n\n        Returns an OrderedDict\n\n        'srd' : `SubregionData`\n            The analysis data for the sub-region\n\n        if fullData is True the return dict will include\n\n        'image' : `afwImage.ImageI`\n            Image of subregion source counts map\n        'countsMap' : `np.array`\n            Numpy array with same\n        'clusters' : `afwDetect.FootprintSet`\n            Clusters as dectected by finding FootprintSet on source counts map\n        'clusterKey' : `afwImage.ImageI`\n            Map of subregion with pixels filled with index of\n            associated Footprints\n        \"\"\"\n        iSubRegion = np.array([ix, iy])\n        corner = iSubRegion * self._subRegionSize\n        idOffset = self.getIdOffset(ix, iy)\n        srd = SubregionData(self, idOffset, corner, self._subRegionSize, self._subRegionBuffer)\n        srd.reduceData(self._redData.values())\n        oDict = srd.analyze(pixelR2Cut=self._pixelR2Cut)\n        if oDict is None:\n            return None\n        if fullData:\n            oDict['srd'] = srd\n            return oDict\n        if srd.nObjects >= self._subregionMaxObject:\n            print(\"Too many object in a subregion\", srd.nObjects, elf._subregionMaxObject)\n        return dict(srd=srd)\n\n    def finish(self):\n        \"\"\" Does clusering for all subregions\n\n        Does not store source counts maps for the counts regions\n        \"\"\"\n        self._clusters = OrderedDict()\n        nAssoc = 0\n        clusterAssocTables = []\n        objectAssocTables = []\n        clusterStatsTables = []\n        objectStatsTables = []\n\n        for ix in range(int(self._nSubRegion[0])):\n            sys.stdout.write(\"%2i \" % ix)\n            sys.stdout.flush()\n            for iy in range(int(self._nSubRegion[1])):\n                sys.stdout.write('.')\n                sys.stdout.flush()\n                iSubRegion = (ix, iy)\n                odict = self.analyzeSubregion(ix, iy)\n                if odict is None:\n                    continue\n                subregionData = odict['srd']\n                self._clusters[iSubRegion] = subregionData\n                clusterAssocTables.append(subregionData.getClusterAssociations())\n                objectAssocTables.append(subregionData.getObjectAssociations())\n                clusterStatsTables.append(subregionData.getClusterStats())\n                objectStatsTables.append(subregionData.getObjectStats())\n                \n            sys.stdout.write('!\\n')\n\n        sys.stdout.write(\"Making association vectors\\n\")\n        hduList = fits.HDUList([fits.PrimaryHDU(),\n                                fits.table_to_hdu(vstack(clusterAssocTables)),\n                                fits.table_to_hdu(vstack(objectAssocTables)),\n                                fits.table_to_hdu(vstack(clusterStatsTables)),\n                                fits.table_to_hdu(vstack(objectStatsTables))])\n        return hduList\n\n    def allStats(self):\n        \"\"\" Helper function to print info about clusters \"\"\"\n        stats = np.zeros((4), int)\n        for key, srd in self._clusters.items():\n            subRegionStats = clusterStats(srd._clusterDict)\n            print(\"%3i, %3i: %8i %8i %8i %8i\" % (key[0], key[1], subRegionStats[0], subRegionStats[1], subRegionStats[2], subRegionStats[3]))\n            stats += subRegionStats\n        return stats\n\ndef main():\n    \"\"\" Example usage \"\"\"\n\n    DATADIR = \".\"\n    SOURCE_TABLEFILES = glob.glob(os.path.join(DATADIR, \"sourceTable-*.parq\"))\n    VISIT_IDS = np.arange(len(SOURCE_TABLEFILES))\n\n    REF_DIR = (150., 2.)  # RA, DEC in deg\n    REGION_SIZE = (3., 3.)  # in Deg\n    #CELL_SIZE = 5.0e-5    # in Deg\n    CELL_SIZE = 1. / (3600*2) # in Deg\n    #SUBREGION_SIZE = 2700 # in Pixels\n    SUBREGION_SIZE = 1350 # in Pixels\n    PIXEL_R2CUT = 1.\n    \n    t0 = time.time()\n    nWay = NWayMatch.create(REF_DIR, REGION_SIZE, CELL_SIZE, pixelR2Cut=PIXEL_R2CUT, subRegionSize=SUBREGION_SIZE)\n    print(\"Building clusters in %ix%i sub-regions\" % (nWay.nSubRegion[0], nWay.nSubRegion[1]))\n    nWay.reduceData(SOURCE_TABLEFILES, VISIT_IDS)\n    outTables = nWay.finish()\n    t1 = time.time()\n    print(\"Reading and clustering took %s s\" % (t1-t0))\n\n    print(\"Cluster Summaries for sub-regions\")\n    print(\"Region  :  nCluster nOrphan  nMixed   nConf\")\n    stats = nWay.allStats()\n    print(\"Total:   %8i %8i %8i %8i\" % (stats[0], stats[1], stats[2], stats[3]))\n\n    outTables.writeto(\"out.fits\", overwrite=True)\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "08c99cd57305bd3b2a297706979bcdcb33dddbcc", "size": 31841, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/nway/nway.py", "max_stars_repo_name": "KIPAC/NWayMatch", "max_stars_repo_head_hexsha": "3cc4dfd8816dfb373a3f1174801549a05a2baf52", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-29T19:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-29T19:58:42.000Z", "max_issues_repo_path": "python/nway/nway.py", "max_issues_repo_name": "KIPAC/NWayMatch", "max_issues_repo_head_hexsha": "3cc4dfd8816dfb373a3f1174801549a05a2baf52", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/nway/nway.py", "max_forks_repo_name": "KIPAC/NWayMatch", "max_forks_repo_head_hexsha": "3cc4dfd8816dfb373a3f1174801549a05a2baf52", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5483490566, "max_line_length": 141, "alphanum_fraction": 0.6128262303, "include": true, "reason": "import numpy,from astropy", "num_tokens": 7804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3140505578320071, "lm_q1q2_score": 0.17413175882219453}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nSpectroscope - Analysis\n=======================\n\nDefines the objects for the homemade spectroscope spectrum images analysis.\n\nReferences\n----------\n.. [1]  http://thomasmansencal.blogspot.fr/2014/07/a-homemade-spectroscope.html\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\nimport scipy.ndimage\n\nfrom colour import (Extrapolator, LinearInterpolator, RGB_COLOURSPACES,\n                    RGB_luminance, SpectralDistribution,\n                    MultiSpectralDistributions)\nfrom colour.utilities import tstack\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2021 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-developers@colour-science.org'\n__status__ = 'Production'\n\n__all__ = [\n    'RGB_Spectrum', 'image_profile', 'calibrate_RGB_spectrum_profile',\n    'calibrated_RGB_spectrum', 'luminance_sd'\n]\n\n\nclass RGB_Spectrum(MultiSpectralDistributions):\n    \"\"\"\n    Defines an *RGB* spectrum object implementation.\n\n    Parameters\n    ----------\n    data : Series or Dataframe or Signal or MultiSignals or \\\nMultiSpectralDistributions or array_like or dict_like, optional\n        Data to be stored in the multi-spectral distributions.\n    domain : array_like, optional\n        Values to initialise the multiple :class:`colour.SpectralDistribution`\n        class instances :attr:`colour.continuous.Signal.wavelengths` attribute\n        with. If both ``data`` and ``domain`` arguments are defined, the latter\n        will be used to initialise the\n        :attr:`colour.continuous.Signal.wavelengths` attribute.\n    labels : array_like, optional\n        Names to use for the :class:`colour.SpectralDistribution` class\n        instances.\n\n    Other Parameters\n    ----------------\n    name : unicode, optional\n       Multi-spectral distribution name.\n    interpolator : object, optional\n        Interpolator class type to use as interpolating function for the\n        :class:`colour.SpectralDistribution` class instances.\n    interpolator_args : dict_like, optional\n        Arguments to use when instantiating the interpolating function\n        of the :class:`colour.SpectralDistribution` class instances.\n    extrapolator : object, optional\n        Extrapolator class type to use as extrapolating function for the\n        :class:`colour.SpectralDistribution` class instances.\n    extrapolator_args : dict_like, optional\n        Arguments to use when instantiating the extrapolating function\n        of the :class:`colour.SpectralDistribution` class instances.\n    strict_labels : array_like, optional\n        Multi-spectral distribution labels for figures, default to\n        :attr:`colour.characterisation.RGB_SpectralSensitivities.labels`\n        attribute value.\n    \"\"\"\n\n    def __init__(self, data=None, domain=None, labels=None, **kwargs):\n        super(RGB_Spectrum, self).__init__(\n            data, domain, labels=('R', 'G', 'B'), **kwargs)\n\n\ndef image_profile(image, line, samples=None):\n    \"\"\"\n    Returns the image profile using given line coordinates and given samples\n    count.\n\n    Parameters\n    ----------\n    image : ndarray\n        Image to retrieve the profile.\n    line : tuple or list or ndarray, (x0, y0, x1, y1)\n        Coordinates as image array indexes to measure the profile.\n    samples : int, optional\n        Samples count to retrieve along the line, default to image width.\n\n    Returns\n    -------\n    ndarray\n        Profile.\n\n    References\n    ----------\n    .. [2]  http://stackoverflow.com/a/7880726/931625\n            (Last accessed 8 August 2014)\n    \"\"\"\n\n    height, width, channels = image.shape\n    samples = samples if samples else width\n    x0, y0, x1, y1 = line\n\n    profile = []\n    for i in range(channels):\n        x, y = np.linspace(x0, x1, samples), np.linspace(y0, y1, samples)\n        z = image[:, :, i]\n\n        profile.append(\n            scipy.ndimage.map_coordinates(np.transpose(z), np.vstack([x, y])))\n\n    return np.dstack(profile)\n\n\ndef calibrate_RGB_spectrum_profile(profile, reference, measured, samples=None):\n    \"\"\"\n    Calibrates given spectrum profile using given theoretical reference\n    wavelength lines in nanometers and measured lines in horizontal axis pixels\n    values. If more than 2 lines are provided the profile data will be warped\n    to fit the theoretical reference wavelength lines.\n\n    Parameters\n    ----------\n    profile : ndarray\n        Image profile to calibrate.\n    reference : dict\n        Theoretical reference wavelength lines.\n    measured : dict\n        Measured lines in horizontal axis pixels values.\n    samples : int, optional\n        Profile samples count.\n\n    Returns\n    -------\n    RGB_Spectrum\n        Calibrated RGB spectrum.\n    \"\"\"\n\n    samples = samples if samples else profile.shape[1]\n    measured_lines = [\n        line for line, value in sorted(measured.items(), key=lambda x: x[1])\n    ]\n\n    # Reference samples.\n    r = np.array([reference.get(sample) for sample in measured_lines])\n    # Measured samples.\n    m = np.array([measured.get(sample) for sample in measured_lines])\n\n    # Reference range array.\n    rr = np.linspace(min(r), max(r))\n    # Measured range array.\n    mm = np.linspace(min(m), max(m))\n\n    # Interpolator from reference to measured.\n    r_to_m_interpolator = Extrapolator(LinearInterpolator(r, m))\n\n    # Interpolator from measured range to reference range.\n    mm_to_rr_interpolator = Extrapolator(LinearInterpolator(mm, rr))\n\n    # Colors interpolator.\n    R_interpolator = Extrapolator(\n        LinearInterpolator(np.arange(0, profile.shape[1]), profile[0, :, 0]))\n    G_interpolator = Extrapolator(\n        LinearInterpolator(np.arange(0, profile.shape[1]), profile[0, :, 1]))\n    B_interpolator = Extrapolator(\n        LinearInterpolator(np.arange(0, profile.shape[1]), profile[0, :, 2]))\n\n    wavelengths = np.linspace(\n        mm_to_rr_interpolator([0]), mm_to_rr_interpolator([profile.shape[1]]),\n        samples)\n\n    return RGB_Spectrum(\n        dict(\n            zip(wavelengths,\n                tstack([\n                    R_interpolator(r_to_m_interpolator(wavelengths)),\n                    G_interpolator(r_to_m_interpolator(wavelengths)),\n                    B_interpolator(r_to_m_interpolator(wavelengths))\n                ]))),\n        name='RGB Spectrum')\n\n\ndef calibrated_RGB_spectrum(image, reference, measured, samples=None):\n    \"\"\"\n    Returns the RGB spectrum of given image.\n\n    Parameters\n    ----------\n    image : ndarray\n        Image to retrieve the RGB spectrum, assuming the spectrum is already\n        properly oriented.\n    reference : dict\n        Theoretical reference wavelength lines.\n    measured : dict\n        Measured lines in horizontal axis pixels values.\n    samples : int, optional\n        Spectrum samples count.\n\n    Returns\n    -------\n    RGB_Spectrum\n        RGB spectrum.\n    \"\"\"\n\n    samples = samples if samples else image.shape[1]\n    profile = image_profile(\n        image, line=[0, 0, image.shape[1] - 1, 0], samples=samples)\n\n    return calibrate_RGB_spectrum_profile(\n        profile=profile,\n        reference=reference,\n        measured=measured,\n        samples=samples)\n\n\ndef luminance_sd(spectrum, colourspace=RGB_COLOURSPACES['sRGB']):\n    \"\"\"\n    Returns the luminance spectral distribution of given RGB spectrum.\n\n    Parameters\n    ----------\n    spectrum : RGB_Spectrum\n        RGB spectrum to retrieve the luminance from.\n    colourspace : RGB_Colourspace\n        *RGB* Colourspace.\n\n    Returns\n    -------\n    SpectralDistribution\n        RGB spectrum luminance spectral distribution, units are arbitrary\n        and normalised to [0, 100] domain.\n    \"\"\"\n\n    spectrum = spectrum.copy().normalise(100)\n    luminance = lambda x: RGB_luminance(x, colourspace.primaries, colourspace.\n                                        whitepoint)\n\n    return SpectralDistribution(\n        dict(zip(spectrum.wavelengths, luminance(spectrum.values))),\n        name='calibrated_RGB_spectrum')\n", "meta": {"hexsha": "19272f5b1b7b14c5f3fa483f84d64a88f84df00b", "size": 8078, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour_spectroscope/fraunhofer/analysis.py", "max_stars_repo_name": "colour-science/colour-spectroscope", "max_stars_repo_head_hexsha": "73ad5920355b509b00939adccd4ec42a2075e698", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-04-15T09:29:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-11T20:26:41.000Z", "max_issues_repo_path": "colour_spectroscope/fraunhofer/analysis.py", "max_issues_repo_name": "colour-science/colour-spectroscope", "max_issues_repo_head_hexsha": "73ad5920355b509b00939adccd4ec42a2075e698", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour_spectroscope/fraunhofer/analysis.py", "max_forks_repo_name": "colour-science/colour-spectroscope", "max_forks_repo_head_hexsha": "73ad5920355b509b00939adccd4ec42a2075e698", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-01-18T17:31:33.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-24T17:35:23.000Z", "avg_line_length": 32.5725806452, "max_line_length": 79, "alphanum_fraction": 0.6678633325, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.1741317481429274}}
{"text": "\"\"\"\nClasses for specific source models\n\"\"\"\nimport numpy as np\nfrom yt.funcs import ensure_numpy_array\nfrom tqdm.auto import tqdm\nfrom pyxsim.utils import mylog\nfrom yt.units.yt_array import YTQuantity\nfrom yt.utilities.physical_constants import clight\nfrom pyxsim.spectral_models import thermal_models\nfrom pyxsim.utils import parse_value, isunitful\nfrom soxs.utils import parse_prng\nfrom soxs.constants import elem_names, atomic_weights, metal_elem\nfrom yt.utilities.exceptions import YTFieldNotFound\nfrom yt.utilities.parallel_tools.parallel_analysis_interface import \\\n    parallel_objects, communication_system, parallel_capable\nfrom numbers import Number\n\ncomm = communication_system.communicators[-1]\n\nsolar_H_abund = 0.74\n\nsqrt_two = np.sqrt(2.)\n\n\nclass ParallelProgressBar:\n    def __init__(self, title):\n        self.title = title\n        mylog.info(f\"Starting '{title}'\")\n\n    def update(self, *args, **kwargs):\n        return\n\n    def close(self):\n        mylog.info(f\"Finishing '{self.title}'\")\n\n\nclass SourceModel:\n    def __init__(self, prng=None):\n        self.spectral_norm = None\n        self.redshift = None\n        self.prng = parse_prng(prng)\n\n    def __call__(self, chunk):\n        pass\n\n    def setup_model(self, data_source, redshift, spectral_norm):\n        self.spectral_norm = spectral_norm\n        self.redshift = redshift\n\n    def cleanup_model(self):\n        pass\n\n\nmetal_abund = {\"angr\": 0.0189,\n               \"aspl\": 0.0134,\n               \"wilm\": 0.0134,\n               \"lodd\": 0.0133}\n\n\nclass ThermalSourceModel(SourceModel):\n    r\"\"\"\n    Initialize a source model from a thermal spectrum.\n\n    Parameters\n    ----------\n    spectral_model : string\n        The thermal model spectrum type to use. Known options are \"apec\".\n    emin : float\n        The minimum energy for the spectrum in keV.\n    emax : float\n        The maximum energy for the spectrum in keV.\n    nchan : integer\n        The number of channels in the spectrum.\n    Zmet : float, string, or tuple of strings\n        The metallicity. If a float, assumes a constant metallicity throughout\n        in solar units. If a string or tuple of strings, is taken to be the \n        name of the metallicity field.\n    temperature_field : string or (ftype, fname) tuple, optional\n        The yt temperature field to use for the thermal modeling. Must have\n        units of Kelvin. If not specified, the default temperature field for\n        the dataset will be used.\n    emission_measure_field : string or (ftype, fname) tuple, optional\n        The yt emission measure field to use for the thermal modeling. Must\n        have units of cm^-3. If not specified, the default emission measure\n        field for the dataset will be used or derived.\n    kT_min : float, optional\n        The default minimum temperature in keV to compute emission for.\n        Default: 0.025\n    kT_max : float, optional\n        The default maximum temperature in keV to compute emission for.\n        Default: 64.0\n    n_kT : integer, optional\n        The number of temperature bins to use when computing emission.\n        Default: 10000\n    kT_scale : string, optional\n        The scaling of the bins to use when computing emission, \n        \"linear\" or \"log\". Default: \"linear\"\n    max_density : float, (value, unit) tuple, :class:`~yt.units.yt_array.YTQuantity`, or :class:`~astropy.units.Quantity`\n        The maximum density of the cells or particles to use when generating \n        photons. If a float, the units are assumed to be g/cm**3. \n        Default: 5e-25 g/cm**3.\n    var_elem : dictionary, optional\n        Elements that should be allowed to vary freely from the single abundance\n        parameter. Each dictionary value, specified by the abundance symbol, \n        corresponds to the abundance of that symbol. If a float, it is understood\n        to be constant and in solar units. If a string or tuple of strings, it is\n        assumed to be a spatially varying field. Default: None\n    method : string, optional\n        The method used to generate the photon energies from the spectrum:\n        \"invert_cdf\": Invert the cumulative distribution function of the spectrum.\n        \"accept_reject\": Acceptance-rejection method using the spectrum. \n        The first method should be sufficient for most cases.\n    thermal_broad : boolean, optional\n        Whether or not the spectral lines should be thermally\n        broadened. Default: True\n    model_root : string, optional\n        The directory root where the model files are stored. If not provided,\n        a default location known to pyXSIM is used. \n    model_vers : string, optional\n        The version identifier string for the model files, e.g.\n        \"2.0.2\". Default depends on the model used.\n    nei : boolean, optional\n        If True, use the non-equilibrium ionization tables. These are\n        not supplied with pyXSIM/SOXS but must be downloaded separately, in\n        which case the *apec_root* parameter must also be set to their\n        location. Default: False\n    nolines : boolean, optional\n        Turn off lines entirely for generating emission.\n        Default: False\n    abund_table : string or array_like, optional\n        The abundance table to be used for solar abundances. \n        Either a string corresponding to a built-in table or an array\n        of 30 floats corresponding to the abundances of each element\n        relative to the abundance of H. Default is \"angr\".\n        Built-in options are:\n        \"angr\" : from Anders E. & Grevesse N. (1989, Geochimica et \n        Cosmochimica Acta 53, 197)\n        \"aspl\" : from Asplund M., Grevesse N., Sauval A.J. & Scott \n        P. (2009, ARAA, 47, 481)\n        \"wilm\" : from Wilms, Allen & McCray (2000, ApJ 542, 914 \n        except for elements not listed which are given zero abundance)\n        \"lodd\" : from Lodders, K (2003, ApJ 591, 1220)\n    prng : integer or :class:`~numpy.random.RandomState` object \n        A pseudo-random number generator. Typically will only be specified\n        if you have a reason to generate the same set of random numbers, \n        such as for a test. Default is to use the :mod:`numpy.random` module.\n\n    Examples\n    --------\n    >>> source_model = ThermalSourceModel(\"apec\", 0.1, 10.0, 10000, \n    ...                                   (\"gas\", \"metallicity\"))\n    \"\"\"\n    def __init__(self, spectral_model, emin, emax, nchan, Zmet,\n                 temperature_field=None, emission_measure_field=None,\n                 kT_min=0.025, kT_max=64.0, n_kT=10000, kT_scale=\"linear\", \n                 max_density=5.0e-25, var_elem=None, method=\"invert_cdf\", \n                 thermal_broad=True, model_root=None, model_vers=None, \n                 nei=False, nolines=False, abund_table=\"angr\",\n                 prng=None):\n        if isinstance(spectral_model, str):\n            if spectral_model not in thermal_models:\n                raise KeyError(f\"{spectral_model} is not a known thermal \"\n                               f\"spectral model!\")\n            spectral_model = thermal_models[spectral_model]\n        self.temperature_field = temperature_field\n        self.Zmet = Zmet\n        self.nei = nei\n        self.ftype = None\n        if var_elem is None:\n            var_elem = {}\n            var_elem_keys = None\n            self.num_var_elem = 0\n        else:\n            var_elem_keys = list(var_elem.keys())\n            self.num_var_elem = len(var_elem_keys)\n        self.var_elem = var_elem\n        self.spectral_model = spectral_model(emin, emax, nchan,\n                                             var_elem=var_elem_keys,\n                                             thermal_broad=thermal_broad,\n                                             model_root=model_root,\n                                             model_vers=model_vers,\n                                             nolines=nolines, nei=nei,\n                                             abund_table=abund_table)\n        self.var_elem_keys = self.spectral_model.var_elem_names\n        self.var_ion_keys = self.spectral_model.var_ion_names\n        self.method = method\n        self.prng = parse_prng(prng)\n        self.kT_min = kT_min\n        self.kT_max = kT_max\n        self.kT_scale = kT_scale\n        self.n_kT = n_kT\n        self.spectral_norm = None\n        self.redshift = None\n        self.pbar = None\n        self.kT_bins = None\n        self.dkT = None\n        self.emission_measure_field = emission_measure_field\n        self.Zconvert = 1.0\n        self.abund_table = abund_table\n        self.atable = self.spectral_model.atable\n        self.mconvert = {}\n        if max_density is not None:\n            if not isinstance(max_density, YTQuantity):\n                if isinstance(max_density, tuple):\n                    max_density = YTQuantity(max_density[0], max_density[1])\n                else:\n                    max_density = YTQuantity(max_density, \"g/cm**3\")\n        self.max_density = max_density\n        self.density_field = None  # Will be determined later\n        self.tot_num_cells = 0  # Will be determined later\n        self.ftype = \"gas\"\n\n    def setup_model(self, data_source, redshift, spectral_norm):\n        if self.emission_measure_field is None:\n            self.emission_measure_field = \\\n                (self.ftype, 'emission_measure')\n        try:\n            ftype = data_source.ds._get_field_info(\n                self.emission_measure_field).name[0]\n        except YTFieldNotFound:\n            raise RuntimeError(f\"The {self.emission_measure_field} field is not \"\n                               \"found. If you do not have species fields in \"\n                               \"your dataset, you may need to set \"\n                               \"default_species_fields='ionized' in the call \"\n                               \"to yt.load().\")\n        self.ftype = ftype\n        self.redshift = redshift\n        if not self.nei and not isinstance(self.Zmet, float):\n            Z_units = str(data_source.ds._get_field_info(self.Zmet).units)\n            if Z_units in [\"dimensionless\", \"\", \"code_metallicity\"]:\n                Zsum = (self.atable*atomic_weights)[metal_elem].sum()\n                self.Zconvert = atomic_weights[1]/(Zsum*solar_H_abund)\n            elif Z_units == \"Zsun\":\n                self.Zconvert = 1.0\n            else:\n                raise RuntimeError(f\"I don't understand metallicity \"\n                                   f\"units of {Z_units}!\")\n        if self.num_var_elem > 0:\n            for key, value in self.var_elem.items():\n                if not isinstance(value, float):\n                    if \"^\" in key:\n                        elem = key.split(\"^\")[0]\n                    else:\n                        elem = key\n                    n_elem = elem_names.index(elem)\n                    m_units = str(data_source.ds._get_field_info(value).units)\n                    if m_units in [\"dimensionless\", \"\", \"code_metallicity\"]:\n                        m = self.atable[n_elem]*atomic_weights[n_elem]\n                        self.mconvert[key] = atomic_weights[1]/(m*solar_H_abund)\n                    elif m_units == \"Zsun\":\n                        self.mconvert[key] = 1.0\n                    else:\n                        raise RuntimeError(f\"I don't understand units of \"\n                                           f\"{m_units} for element {key}!\")\n        self.density_field = (ftype, \"density\")\n        mylog.info(f\"Using emission measure field \"\n                   f\"'{self.emission_measure_field}'.\")\n        if self.temperature_field is None:\n            self.temperature_field = (ftype, 'temperature')\n        mylog.info(f\"Using temperature field \"\n                   f\"'{self.temperature_field}'.\")\n        self.spectral_model.prepare_spectrum(redshift, self.kT_min,\n                                             self.kT_max)\n        self.spectral_norm = spectral_norm\n        if self.kT_scale == \"linear\":\n            self.kT_bins = np.linspace(self.kT_min, self.kT_max, \n                                       num=self.n_kT+1)\n        elif self.kT_scale == \"log\":\n            self.kT_bins = np.logspace(np.log10(self.kT_min),\n                                       np.log10(self.kT_max),\n                                       num=self.n_kT+1)\n        self.dkT = np.diff(self.kT_bins)\n        citer = data_source.chunks([], \"io\")\n        num_cells = 0\n        for chunk in parallel_objects(citer):\n            num_cells += chunk[self.temperature_field].size\n        self.tot_num_cells = comm.mpi_allreduce(num_cells)\n        if parallel_capable:\n            self.pbar = ParallelProgressBar(\"Processing cells/particles \")\n        else:\n            self.pbar = tqdm(leave=True, total=self.tot_num_cells,\n                             desc=\"Processing cells/particles \")\n\n    def cleanup_model(self):\n        self.emission_measure_field = None\n        self.temperature_field = None\n        self.pbar.close()\n\n    def __call__(self, chunk):\n\n        num_photons_max = 10000000\n        emid = self.spectral_model.emid\n        ebins = self.spectral_model.ebins\n        nchan = len(emid)\n\n        orig_ncells = chunk[self.temperature_field].size\n        if orig_ncells == 0:\n            return\n        if self.max_density is None:\n            dens_cut = np.ones(orig_ncells, dtype=\"bool\")\n        else:\n            dens_cut = chunk[self.density_field] < self.max_density\n        kT = np.atleast_1d(\n            chunk[self.temperature_field].to_value(\"keV\", \"thermal\"))\n        EM = np.atleast_1d(chunk[self.emission_measure_field].d*dens_cut)\n\n        idxs = np.argsort(kT)\n\n        kT_sorted = kT[idxs]\n        idx_min = np.searchsorted(kT_sorted, self.kT_min)\n        idx_max = np.searchsorted(kT_sorted, self.kT_max)\n        idxs = idxs[idx_min:idx_max]\n        num_cells = len(idxs)\n\n        if num_cells == 0:\n            self.pbar.update(orig_ncells)\n            return\n        else:\n            self.pbar.update(orig_ncells-num_cells)\n\n        kT_idxs = np.digitize(kT[idxs], self.kT_bins)-1\n        bcounts = np.bincount(kT_idxs).astype(\"int\")\n        bcounts = bcounts[bcounts > 0]\n        n = int(0)\n        bcell = []\n        ecell = []\n        for bcount in bcounts:\n            bcell.append(n)\n            ecell.append(n+bcount)\n            n += bcount\n        kT_idxs = np.unique(kT_idxs)\n\n        cell_em = EM[idxs]*self.spectral_norm\n\n        if self.nei:\n            metalZ = np.zeros(num_cells)\n            elem_keys = self.var_ion_keys\n        else:\n            elem_keys = self.var_elem_keys\n            if isinstance(self.Zmet, float):\n                metalZ = self.Zmet*np.ones(num_cells)\n            else:\n                metalZ = np.atleast_1d(chunk[self.Zmet].d[idxs]*\n                                       self.Zconvert)\n\n        elemZ = None\n        if self.num_var_elem > 0:\n            elemZ = np.zeros((self.num_var_elem, num_cells))\n            for j, key in enumerate(elem_keys):\n                value = self.var_elem[key]\n                if isinstance(value, float):\n                    elemZ[j, :] = value\n                else:\n                    elemZ[j, :] = np.atleast_1d(chunk[value].d[idxs]*\n                                                self.mconvert[key])\n\n        number_of_photons = np.zeros(num_cells, dtype=\"int64\")\n        energies = np.zeros(num_photons_max)\n\n        start_e = 0\n        end_e = 0\n\n        for ibegin, iend, bcount, ikT in zip(bcell, ecell, bcounts, kT_idxs):\n\n            self.pbar.update(bcount)\n\n            kT = self.kT_bins[ikT] + 0.5*self.dkT[ikT]\n\n            cem = cell_em[ibegin:iend]\n\n            cspec, mspec, vspec = self.spectral_model.get_spectrum(kT)\n\n            tot_ph_c = cspec.d.sum()\n            tot_ph_m = mspec.d.sum()\n\n            cell_norm_c = tot_ph_c*cem\n            cell_norm_m = tot_ph_m*metalZ[ibegin:iend]*cem\n            cell_norm = cell_norm_c + cell_norm_m\n\n            if vspec is not None:\n                cell_norm_v = np.zeros(cem.size)\n                for j in range(self.num_var_elem):\n                    tot_ph_v = vspec.d[j, :].sum()\n                    cell_norm_v += tot_ph_v*elemZ[j, ibegin:iend]*cem\n                cell_norm += cell_norm_v\n\n            cell_n = ensure_numpy_array(self.prng.poisson(lam=cell_norm))\n\n            number_of_photons[ibegin:iend] = cell_n\n\n            end_e += int(cell_n.sum())\n\n            if self.method == \"invert_cdf\":\n                cumspec_c = np.insert(np.cumsum(cspec.d), 0, 0.0)\n                cumspec_m = np.insert(np.cumsum(mspec.d), 0, 0.0)\n                if vspec is None:\n                    cumspec_v = None\n                else:\n                    cumspec_v = np.zeros((self.num_var_elem, nchan+1))\n                    for j in range(self.num_var_elem):\n                        cumspec_v[j, 1:] = np.cumsum(vspec.d[j, :])\n\n            ei = start_e\n            for icell in range(ibegin, iend):\n                cn = number_of_photons[icell]\n                if cn == 0:\n                    continue\n                # The rather verbose form of the few next statements is a\n                # result of code optimization and shouldn't be changed\n                # without checking for perfomance degradation. See\n                # https://bitbucket.org/yt_analysis/yt/pull-requests/1766\n                # for details.\n                if self.method == \"invert_cdf\":\n                    cumspec = cumspec_c\n                    cumspec += metalZ[icell] * cumspec_m\n                    if cumspec_v is not None:\n                        for j in range(self.num_var_elem):\n                            cumspec += elemZ[j, icell]*cumspec_v[j, :]\n                    norm_factor = 1.0 / cumspec[-1]\n                    cumspec *= norm_factor\n                    randvec = self.prng.uniform(size=cn)\n                    randvec.sort()\n                    cell_e = np.interp(randvec, cumspec, ebins)\n                elif self.method == \"accept_reject\":\n                    tot_spec = cspec.d\n                    tot_spec += metalZ[icell] * mspec.d\n                    if vspec is not None:\n                        for j in range(self.num_var_elem):\n                            tot_spec += elemZ[j, icell]*vspec.d[j, :]\n                    norm_factor = 1.0 / tot_spec.sum()\n                    tot_spec *= norm_factor\n                    eidxs = self.prng.choice(nchan, size=cn, p=tot_spec)\n                    cell_e = emid[eidxs]\n                while ei+cn > num_photons_max:\n                    num_photons_max *= 2\n                if num_photons_max > energies.size:\n                    energies.resize(num_photons_max, refcheck=False)\n                energies[ei:ei+cn] = cell_e\n                ei += cn\n\n            start_e = end_e\n\n        active_cells = number_of_photons > 0\n        idxs = idxs[active_cells]\n        ncells = idxs.size\n\n        return ncells, number_of_photons[active_cells], idxs, energies[:end_e].copy()\n\n    def cleanup_model(self):\n        self.pbar.close()\n\n\nclass PowerLawSourceModel(SourceModel):\n    r\"\"\"\n    Initialize a source model from a power-law spectrum.\n\n    Parameters\n    ----------\n    e0 : float, (value, unit) tuple, :class:`~yt.units.yt_array.YTQuantity`, or :class:`~astropy.units.Quantity`\n        The reference energy of the power law, in the rest frame of the source.\n        If units are not given, they are assumed to be in keV.\n    emin : float, (value, unit) tuple, :class:`~yt.units.yt_array.YTQuantity`, or :class:`~astropy.units.Quantity`\n        The minimum energy of the photons to be generated, in the rest frame of\n        the source. If units are not given, they are assumed to be in keV.\n    emax : float, (value, unit) tuple, :class:`~yt.units.yt_array.YTQuantity`, or :class:`~astropy.units.Quantity`\n        The maximum energy of the photons to be generated, in the rest frame of\n        the source. If units are not given, they are assumed to be in keV.\n    emission_field : string or (ftype, fname) tuple\n        The field corresponding to the specific photon count rate per cell or\n        particle, in the rest frame of the source, which serves as the\n        normalization for the power law. Must be in counts/s/keV.\n    index : float, string, or (ftype, fname) tuple\n        The power-law index of the spectrum. Either a float for a single power law or\n        the name of a field that corresponds to the power law.\n    prng : integer or :class:`~numpy.random.RandomState` object \n        A pseudo-random number generator. Typically will only be specified\n        if you have a reason to generate the same set of random numbers, such as for a\n        test. Default is to use the :mod:`numpy.random` module.\n\n    Examples\n    --------\n    >>> e0 = (1.0, \"keV\")\n    >>> emin = (0.01, \"keV\")\n    >>> emax = (100., \"keV\")\n    >>> plaw_model = PowerLawSourceModel(e0, emin, emax, (\"gas\", \"norm\"), (\"gas\", \"index\"))\n    \"\"\"\n    def __init__(self, e0, emin, emax, emission_field, alpha, prng=None):\n        self.e0 = parse_value(e0, \"keV\")\n        self.emin = parse_value(emin, \"keV\")\n        self.emax = parse_value(emax, \"keV\")\n        self.emission_field = emission_field\n        self.alpha = alpha\n        self.prng = parse_prng(prng)\n        self.spectral_norm = None\n        self.redshift = None\n        self.ftype = None\n\n    def setup_model(self, data_source, redshift, spectral_norm):\n        self.spectral_norm = spectral_norm\n        self.redshift = redshift\n        self.scale_factor = 1.0 / (1.0 + self.redshift)\n        self.ftype = data_source.ds._get_field_info(self.emission_field).name[0]\n\n    def __call__(self, chunk):\n\n        num_cells = len(chunk[self.emission_field])\n\n        if isinstance(self.alpha, float):\n            alpha = self.alpha*np.ones(num_cells)\n        else:\n            alpha = chunk[self.alpha].v\n\n        norm_fac = (self.emax.v**(1.-alpha)-self.emin.v**(1.-alpha))\n        norm_fac[alpha == 1] = np.log(self.emax.v/self.emin.v)\n        norm = norm_fac*chunk[self.emission_field].v*self.e0.v**alpha\n        norm[alpha != 1] /= (1.-alpha[alpha != 1])\n        norm *= self.spectral_norm*self.scale_factor\n\n        number_of_photons = self.prng.poisson(lam=norm)\n\n        energies = np.zeros(number_of_photons.sum())\n\n        start_e = 0\n        end_e = 0\n        for i in range(num_cells):\n            if number_of_photons[i] > 0:\n                end_e = start_e+number_of_photons[i]\n                u = self.prng.uniform(size=number_of_photons[i])\n                if alpha[i] == 1:\n                    e = self.emin.v*(self.emax.v/self.emin.v)**u\n                else:\n                    e = self.emin.v**(1.-alpha[i]) + u*norm_fac[i]\n                    e **= 1./(1.-alpha[i])\n                energies[start_e:end_e] = e * self.scale_factor\n                start_e = end_e\n\n        active_cells = number_of_photons > 0\n        ncells = active_cells.sum()\n\n        return ncells, number_of_photons[active_cells], active_cells, energies[:end_e].copy()\n\n\nclass LineSourceModel(SourceModel):\n    r\"\"\"\n    Initialize a source model from a single line.\n\n    Parameters\n    ----------\n    e0 : float, (value, unit) tuple, :class:`~yt.units.yt_array.YTQuantity`, or :class:`~astropy.units.Quantity`\n        The location of the emission line in energy in the rest frame of the\n        source. If units are not given, they are assumed to be in keV.\n    emission_field : string or (ftype, fname) tuple\n        The field corresponding to the photon count rate per cell or particle,\n        in the rest frame of the source, which serves as the normalization for\n        the line. Must be in counts/s.\n    sigma : float, (value, unit) tuple, :class:`~yt.units.yt_array.YTQuantity`, or :class:`~astropy.units.Quantity`\n        The standard intrinsic deviation of the emission line (not from Doppler\n        broadening, which is handled in the projection step). Units of\n        velocity or energy are accepted. If units are not given, they\n        are assumed to be in keV. If set to a field name, the line broadening\n        is assumed to be based on this field (in units of velocity or energy).\n        If set to None (the default), it is assumed that the line is unbroadened.\n    prng : integer or :class:`~numpy.random.RandomState` object \n        A pseudo-random number generator. Typically will only be specified\n        if you have a reason to generate the same set of random numbers, such as for a\n        test. Default is to use the :mod:`numpy.random` module.\n\n    Examples\n    --------\n    >>> location = (3.5, \"keV\")\n    >>> sigma = (1000., \"km/s\")\n    >>> line_model = LineEmissionSourceModel(location, \"dark_matter_density_squared\", sigma=sigma)\n    \"\"\"\n    def __init__(self, e0, emission_field, sigma=None, prng=None):\n        from unyt.exceptions import UnitConversionError\n        self.e0 = parse_value(e0, \"keV\")\n        if isinstance(sigma, Number):\n            self.sigma = parse_value(sigma, \"keV\")\n        elif isunitful(sigma):\n            # The broadening is constant\n            try:\n                self.sigma = parse_value(sigma, \"km/s\")\n                self.sigma *= self.e0/clight\n                self.sigma.convert_to_units(\"keV\")\n            except UnitConversionError:\n                self.sigma = parse_value(sigma, \"keV\")\n        else:\n            # Either no broadening or a field name\n            self.sigma = sigma\n        self.emission_field = emission_field\n        self.prng = parse_prng(prng)\n        self.spectral_norm = None\n        self.redshift = None\n        self.ftype = None\n\n    def setup_model(self, data_source, redshift, spectral_norm):\n        self.spectral_norm = spectral_norm\n        self.redshift = redshift\n        self.scale_factor = 1.0 / (1.0 + self.redshift)\n        self.ftype = data_source.ds._get_field_info(self.emission_field).name[0]\n\n    def __call__(self, chunk):\n        num_cells = len(chunk[self.emission_field])\n        F = chunk[self.emission_field]*self.spectral_norm*self.scale_factor\n        number_of_photons = self.prng.poisson(lam=F.in_cgs().v)\n\n        energies = self.e0*np.ones(number_of_photons.sum())\n\n        if isinstance(self.sigma, YTQuantity):\n            dE = self.prng.normal(loc=0.0, scale=float(self.sigma),\n                                  size=number_of_photons.sum())*self.e0.uq\n            energies += dE\n        elif self.sigma is not None:\n            sigma = (chunk[self.sigma]*self.e0/clight).in_units(\"keV\")\n            start_e = 0\n            for i in range(num_cells):\n                if number_of_photons[i] > 0:\n                    end_e = start_e+number_of_photons[i]\n                    dE = self.prng.normal(loc=0.0, scale=float(sigma[i]),\n                                          size=number_of_photons[i])*self.e0.uq\n                    energies[start_e:end_e] += dE\n                    start_e = end_e\n\n        energies = energies * self.scale_factor\n\n        active_cells = number_of_photons > 0\n        ncells = active_cells.sum()\n\n        return ncells, number_of_photons[active_cells], active_cells, energies\n\n", "meta": {"hexsha": "05be2da6890adfd8902f435e6f27cbb8c82ad0ff", "size": 26964, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyxsim/source_models.py", "max_stars_repo_name": "Joeybraspenning/pyxsim", "max_stars_repo_head_hexsha": "6e06bd87c721580fa7fea2d363a2cc4c6b35ca70", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2016-08-08T17:09:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T20:47:13.000Z", "max_issues_repo_path": "pyxsim/source_models.py", "max_issues_repo_name": "Joeybraspenning/pyxsim", "max_issues_repo_head_hexsha": "6e06bd87c721580fa7fea2d363a2cc4c6b35ca70", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 38, "max_issues_repo_issues_event_min_datetime": "2016-08-08T19:54:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-19T09:03:01.000Z", "max_forks_repo_path": "pyxsim/source_models.py", "max_forks_repo_name": "Joeybraspenning/pyxsim", "max_forks_repo_head_hexsha": "6e06bd87c721580fa7fea2d363a2cc4c6b35ca70", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-04-04T10:07:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T11:44:11.000Z", "avg_line_length": 42.664556962, "max_line_length": 121, "alphanum_fraction": 0.5893042575, "include": true, "reason": "import numpy", "num_tokens": 6384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.2658804730998169, "lm_q1q2_score": 0.17412372038829727}}
{"text": "# ======================================================================================\n# Copyright and other protections apply. Please see the accompanying LICENSE file for\n# rights and restrictions governing use of this software. All rights not expressly\n# waived or licensed are reserved. If that file is missing or appears to be modified\n# from its original, then please contact the author before viewing or using this\n# software in any capacity.\n# ======================================================================================\n\nfrom __future__ import annotations\n\nimport os\nfrom collections import Counter as counter\nfrom collections.abc import Iterable as IterableC\nfrom collections.abc import Mapping as MappingC\nfrom fractions import Fraction\nfrom itertools import chain, product, repeat\nfrom math import sqrt\nfrom operator import (\n    __abs__,\n    __add__,\n    __and__,\n    __eq__,\n    __floordiv__,\n    __ge__,\n    __getitem__,\n    __gt__,\n    __invert__,\n    __le__,\n    __lt__,\n    __mod__,\n    __mul__,\n    __ne__,\n    __neg__,\n    __or__,\n    __pos__,\n    __pow__,\n    __sub__,\n    __truediv__,\n    __xor__,\n)\nfrom typing import (\n    Callable,\n    Counter,\n    Dict,\n    ItemsView,\n    Iterable,\n    Iterator,\n    KeysView,\n    List,\n    Mapping,\n    Optional,\n    Tuple,\n    TypeVar,\n    Union,\n    ValuesView,\n    cast,\n    overload,\n)\n\nfrom . import rng\nfrom .bt import beartype\nfrom .lifecycle import experimental\nfrom .symmetries import comb, gcd\nfrom .types import (\n    CachingProtocolMeta,\n    IntT,\n    OutcomeT,\n    Protocol,\n    _BinaryOperatorT,\n    _IntCs,\n    _OutcomeCs,\n    _RationalInitializerT,\n    _UnaryOperatorT,\n    as_int,\n    is_even,\n    is_odd,\n    runtime_checkable,\n    sorted_outcomes,\n)\n\n__all__ = (\"H\",)\n\n\n# ---- Types ---------------------------------------------------------------------------\n\n\n_T = TypeVar(\"_T\")\n_T_co = TypeVar(\"_T_co\", covariant=True)\n_MappingT = Mapping[OutcomeT, int]\n_SourceT = Union[\n    IntT,\n    Iterable[OutcomeT],\n    Iterable[Tuple[OutcomeT, IntT]],\n    _MappingT,\n    \"HableT\",\n]\n_OperandT = Union[OutcomeT, \"H\", \"HableT\"]\n_ExpandT = Callable[[\"H\", OutcomeT], Union[OutcomeT, \"H\"]]\n_CoalesceT = Callable[[\"H\", OutcomeT], \"H\"]\n\n\n# ---- Data ----------------------------------------------------------------------------\n\n\ntry:\n    _ROW_WIDTH = os.get_terminal_size().columns\nexcept OSError:\n    try:\n        _ROW_WIDTH = int(os.environ[\"COLUMNS\"])\n    except (KeyError, ValueError):\n        _ROW_WIDTH = 88\n\n\n# ---- Functions -----------------------------------------------------------------------\n\n\ndef coalesce_replace(h: H, outcome: OutcomeT) -> H:\n    r\"\"\"\n    Default behavior for [``H.substitute``][dyce.h.H.substitute]. Returns *h* unmodified\n    (*outcome* is ignored).\n    \"\"\"\n    return h\n\n\n# ---- Classes -------------------------------------------------------------------------\n\n\nclass H(_MappingT):\n    r\"\"\"\n    An immutable mapping for use as a histogram which supports arithmetic operations.\n    This is useful for modeling discrete outcomes, like individual dice. ``#!python H``\n    objects encode finite discrete probability distributions as integer counts without\n    any denominator.\n\n    !!! info\n\n        The lack of an explicit denominator is intentional and has two benefits. First,\n        a denominator is redundant. Without it, one never has to worry about\n        probabilities summing to one (e.g., via miscalculation, floating point error,\n        etc.). Second (and perhaps more importantly), sometimes one wants to have an\n        insight into non-reduced counts, not just probabilities. If needed,\n        probabilities can always be derived, as shown below.\n\n    The [initializer][dyce.h.H.__init__] takes a single parameter, *items*. In its most\n    explicit form, *items* maps outcome values to counts.\n\n    Modeling a single six-sided die (``1d6``) can be expressed as:\n\n    ``` python\n    >>> from dyce import H\n    >>> d6 = H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})\n\n    ```\n\n    An iterable of pairs can also be used (similar to ``#!python dict``).\n\n    ``` python\n    >>> d6 == H(((1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1)))\n    True\n\n    ```\n\n    Two shorthands are provided. If *items* is an iterable of numbers, counts of 1 are\n    assumed.\n\n    ``` python\n    >>> d6 == H((1, 2, 3, 4, 5, 6))\n    True\n\n    ```\n\n    Repeated items are accumulated, as one would expect.\n\n    ``` python\n    >>> H((2, 3, 3, 4, 4, 5))\n    H({2: 1, 3: 2, 4: 2, 5: 1})\n\n    ```\n\n    If *items* is an integer, it is shorthand for creating a sequential range $[{1} ..\n    {items}]$ (or $[{items} .. {-1}]$ if *items* is negative).\n\n    ``` python\n    >>> d6 == H(6)\n    True\n\n    ```\n\n    Histograms are maps, so we can test equivalence against other maps.\n\n    ``` python\n    >>> H(6) == {1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}\n    True\n\n    ```\n\n    Simple indexes can be used to look up an outcome’s count.\n\n    ``` python\n    >>> H((2, 3, 3, 4, 4, 5))[3]\n    2\n\n    ```\n\n    Most arithmetic operators are supported and do what one would expect. If the operand\n    is a number, the operator applies to the outcomes.\n\n    ``` python\n    >>> d6 + 4\n    H({5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1})\n\n    ```\n\n    ``` python\n    >>> d6 * -1\n    H({-6: 1, -5: 1, -4: 1, -3: 1, -2: 1, -1: 1})\n    >>> d6 * -1 == -d6\n    True\n    >>> d6 * -1 == H(-6)\n    True\n\n    ```\n\n    If the operand is another histogram, combinations are computed. Modeling the sum of\n    two six-sided dice (``2d6``) can be expressed as:\n\n    ``` python\n    >>> d6 + d6\n    H({2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 5, 9: 4, 10: 3, 11: 2, 12: 1})\n    >>> print((d6 + d6).format(width=65))\n    avg |    7.00\n    std |    2.42\n    var |    5.83\n      2 |   2.78% |#\n      3 |   5.56% |##\n      4 |   8.33% |####\n      5 |  11.11% |#####\n      6 |  13.89% |######\n      7 |  16.67% |########\n      8 |  13.89% |######\n      9 |  11.11% |#####\n     10 |   8.33% |####\n     11 |   5.56% |##\n     12 |   2.78% |#\n\n    ```\n\n    To sum ${n}$ identical histograms, the matrix multiplication operator (``@``)\n    provides a shorthand.\n\n    ``` python\n    >>> 3@d6 == d6 + d6 + d6\n    True\n\n    ```\n\n    The ``#!python len`` built-in function can be used to show the number of distinct\n    outcomes.\n\n    ``` python\n    >>> len(2@d6)\n    11\n\n    ```\n\n    The [``total`` property][dyce.h.H.total] can be used to compute the total number of\n    combinations and each outcome’s probability.\n\n    ``` python\n    >>> from fractions import Fraction\n    >>> (2@d6).total\n    36\n    >>> [(outcome, Fraction(count, (2@d6).total)) for outcome, count in (2@d6).items()]\n    [(2, Fraction(1, 36)), (3, Fraction(1, 18)), (4, Fraction(1, 12)), (5, Fraction(1, 9)), (6, Fraction(5, 36)), (7, Fraction(1, 6)), ..., (12, Fraction(1, 36))]\n\n    ```\n\n    Histograms provide common comparators (e.g., [``eq``][dyce.h.H.eq]\n    [``ne``][dyce.h.H.ne], etc.). One way to count how often a first six-sided die\n    shows a different face than a second is:\n\n    ``` python\n    >>> d6.ne(d6)\n    H({False: 6, True: 30})\n    >>> print(d6.ne(d6).format(width=65))\n    avg |    0.83\n    std |    0.37\n    var |    0.14\n      0 |  16.67% |########\n      1 |  83.33% |#########################################\n\n    ```\n\n    Or, how often a first six-sided die shows a face less than a second is:\n\n    ``` python\n    >>> d6.lt(d6)\n    H({False: 21, True: 15})\n    >>> print(d6.lt(d6).format(width=65))\n    avg |    0.42\n    std |    0.49\n    var |    0.24\n      0 |  58.33% |#############################\n      1 |  41.67% |####################\n\n    ```\n\n    Or how often at least one ``#!python 2`` will show when rolling four six-sided dice:\n\n    ``` python\n    >>> d6_eq2 = d6.eq(2) ; d6_eq2  # how often a 2 shows on a single six-sided die\n    H({False: 5, True: 1})\n    >>> 4@d6_eq2  # count of 2s showing on 4d6\n    H({0: 625, 1: 500, 2: 150, 3: 20, 4: 1})\n    >>> (4@d6_eq2).ge(1)  # how often that count is at least one\n    H({False: 625, True: 671})\n    >>> print((4@d6_eq2).ge(1).format(width=65))\n    avg |    0.52\n    std |    0.50\n    var |    0.25\n      0 |  48.23% |########################\n      1 |  51.77% |#########################\n\n    ```\n\n    !!! bug \"Mind your parentheses\"\n\n        Parentheses are often necessary to enforce the desired order of operations. This\n        is most often an issue with the ``#!python @`` operator, because it behaves\n        differently than the ``d`` operator in most dedicated grammars. More\n        specifically, in Python, ``#!python @`` has a [lower\n        precedence](https://docs.python.org/3/reference/expressions.html#operator-precedence)\n        than ``#!python .`` and ``#!python […]``.\n\n        ``` python\n        >>> 2@d6[7]  # type: ignore\n        Traceback (most recent call last):\n          ...\n        KeyError: 7\n        >>> 2@d6.le(7)  # probably not what was intended\n        H({2: 36})\n        >>> 2@d6.le(7) == 2@(d6.le(7))\n        True\n\n        ```\n\n        ``` python\n        >>> (2@d6)[7]\n        6\n        >>> (2@d6).le(7)\n        H({False: 15, True: 21})\n        >>> 2@d6.le(7) == (2@d6).le(7)\n        False\n\n        ```\n\n    Counts are generally accumulated without reduction. To reduce, call the\n    [``lowest_terms`` method][dyce.h.H.lowest_terms].\n\n    ``` python\n    >>> d6.ge(4)\n    H({False: 3, True: 3})\n    >>> d6.ge(4).lowest_terms()\n    H({False: 1, True: 1})\n\n    ```\n\n    Testing equivalence implicitly performs reductions of operands.\n\n    ``` python\n    >>> d6.ge(4) == d6.ge(4).lowest_terms()\n    True\n\n    ```\n    \"\"\"\n    __slots__: Tuple[str, ...] = (\"_h\", \"_simple_init\")\n\n    # ---- Initializer -----------------------------------------------------------------\n\n    @beartype\n    def __init__(self, items: _SourceT) -> None:\n        r\"Initializer.\"\n        super().__init__()\n        self._simple_init: Optional[int] = None\n        tmp: Counter[OutcomeT] = counter()\n\n        if isinstance(items, MappingC):\n            items = items.items()\n\n        if isinstance(items, _IntCs):\n            if items != 0:\n                self._simple_init = as_int(items)\n                outcome_range = range(\n                    self._simple_init,\n                    0,\n                    1 if self._simple_init < 0 else -1,  # count toward zero\n                )\n\n                if isinstance(items, _OutcomeCs):\n                    outcome_type = type(items)\n                    tmp.update({outcome_type(i): 1 for i in outcome_range})\n                else:\n                    tmp.update({i: 1 for i in outcome_range})\n        elif isinstance(items, HableT):\n            tmp.update(items.h())\n        elif isinstance(items, IterableC):\n            # Items is either an Iterable[OutcomeT] or an Iterable[Tuple[OutcomeT,\n            # IntT]] (although this technically supports Iterable[Union[OutcomeT,\n            # Tuple[OutcomeT, IntT]]])\n            for item in items:\n                if isinstance(item, tuple):\n                    outcome, count = item\n                    tmp[outcome] += as_int(count)\n                else:\n                    tmp[item] += 1\n        else:\n            raise ValueError(f\"unrecognized initializer {items}\")\n\n        # Sort and omit zero counts. As of Python 3.7, insertion order of keys is\n        # preserved.\n        self._h: _MappingT = {\n            outcome: tmp[outcome]\n            for outcome in sorted_outcomes(tmp)\n            if tmp[outcome] != 0\n        }\n\n    # ---- Overrides -------------------------------------------------------------------\n\n    @beartype\n    def __repr__(self) -> str:\n        if self._simple_init is not None:\n            arg = str(self._simple_init)\n        else:\n            arg = dict.__repr__(self._h)\n\n        return f\"{type(self).__name__}({arg})\"\n\n    @beartype\n    def __eq__(self, other) -> bool:\n        if isinstance(other, HableT):\n            return __eq__(self, other.h())\n        elif isinstance(other, H):\n            return __eq__(self.lowest_terms()._h, other.lowest_terms()._h)\n        else:\n            return super().__eq__(other)\n\n    @beartype\n    def __ne__(self, other) -> bool:\n        if isinstance(other, HableT):\n            return __ne__(self, other.h())\n        elif isinstance(other, H):\n            return not __eq__(self, other)\n        else:\n            return super().__ne__(other)\n\n    @beartype\n    def __hash__(self) -> int:\n        return hash(frozenset(self._lowest_terms()))\n\n    @beartype\n    def __len__(self) -> int:\n        return len(self._h)\n\n    @beartype\n    def __getitem__(self, key: OutcomeT) -> int:\n        return __getitem__(self._h, key)\n\n    @beartype\n    def __iter__(self) -> Iterator[OutcomeT]:\n        return iter(self._h)\n\n    @beartype\n    def __add__(self, other: _OperandT) -> H:\n        try:\n            return self.map(__add__, other)\n        except NotImplementedError:\n            return NotImplemented\n\n    @beartype\n    def __radd__(self, other: OutcomeT) -> H:\n        try:\n            return self.rmap(other, __add__)\n        except NotImplementedError:\n            return NotImplemented\n\n    @beartype\n    def __sub__(self, other: _OperandT) -> H:\n        try:\n            return self.map(__sub__, other)\n        except NotImplementedError:\n            return NotImplemented\n\n    @beartype\n    def __rsub__(self, other: OutcomeT) -> H:\n        try:\n            return self.rmap(other, __sub__)\n        except NotImplementedError:\n            return NotImplemented\n\n    @beartype\n    def __mul__(self, other: _OperandT) -> H:\n        try:\n            return self.map(__mul__, other)\n        except NotImplementedError:\n            return NotImplemented\n\n    @beartype\n    def __rmul__(self, other: OutcomeT) -> H:\n        try:\n            return self.rmap(other, __mul__)\n        except NotImplementedError:\n            return NotImplemented\n\n    @beartype\n    def __matmul__(self, other: IntT) -> H:\n        try:\n            other = as_int(other)\n        except TypeError:\n            return NotImplemented\n\n        if other < 0:\n            raise ValueError(\"argument cannot be negative\")\n        else:\n            return sum_h(repeat(self, other))\n\n    @beartype\n    def __rmatmul__(self, other: IntT) -> H:\n        return self.__matmul__(other)\n\n    @beartype\n    def __truediv__(self, other: _OperandT) -> H:\n        try:\n            return self.map(__truediv__, other)\n        except NotImplementedError:\n            return NotImplemented\n\n    @beartype\n    def __rtruediv__(self, other: OutcomeT) -> H:\n        try:\n            return self.rmap(other, __truediv__)\n        except NotImplementedError:\n            return NotImplemented\n\n    @beartype\n    def __floordiv__(self, other: _OperandT) -> H:\n        try:\n            return self.map(__floordiv__, other)\n        except NotImplementedError:\n            return NotImplemented\n\n    @beartype\n    def __rfloordiv__(self, other: OutcomeT) -> H:\n        try:\n            return self.rmap(other, __floordiv__)\n        except NotImplementedError:\n            return NotImplemented\n\n    @beartype\n    def __mod__(self, other: _OperandT) -> H:\n        try:\n            return self.map(__mod__, other)\n        except NotImplementedError:\n            return NotImplemented\n\n    @beartype\n    def __rmod__(self, other: OutcomeT) -> H:\n        try:\n            return self.rmap(other, __mod__)\n        except NotImplementedError:\n            return NotImplemented\n\n    @beartype\n    def __pow__(self, other: _OperandT) -> H:\n        try:\n            return self.map(__pow__, other)\n        except NotImplementedError:\n            return NotImplemented\n\n    @beartype\n    def __rpow__(self, other: OutcomeT) -> H:\n        try:\n            return self.rmap(other, __pow__)\n        except NotImplementedError:\n            return NotImplemented\n\n    @beartype\n    def __and__(self, other: Union[IntT, \"H\", \"HableT\"]) -> H:\n        try:\n            if isinstance(other, _IntCs):\n                other = as_int(other)\n\n            return self.map(__and__, other)\n        except (NotImplementedError, TypeError):\n            return NotImplemented\n\n    @beartype\n    def __rand__(self, other: IntT) -> H:\n        try:\n            return self.rmap(as_int(other), __and__)\n        except (NotImplementedError, TypeError):\n            return NotImplemented\n\n    @beartype\n    def __xor__(self, other: Union[IntT, \"H\", \"HableT\"]) -> H:\n        try:\n            if isinstance(other, _IntCs):\n                other = as_int(other)\n\n            return self.map(__xor__, other)\n        except NotImplementedError:\n            return NotImplemented\n\n    @beartype\n    def __rxor__(self, other: IntT) -> H:\n        try:\n            return self.rmap(as_int(other), __xor__)\n        except (NotImplementedError, TypeError):\n            return NotImplemented\n\n    @beartype\n    def __or__(self, other: Union[IntT, \"H\", \"HableT\"]) -> H:\n        try:\n            if isinstance(other, _IntCs):\n                other = as_int(other)\n\n            return self.map(__or__, other)\n        except (NotImplementedError, TypeError):\n            return NotImplemented\n\n    @beartype\n    def __ror__(self, other: IntT) -> H:\n        try:\n            return self.rmap(as_int(other), __or__)\n        except (NotImplementedError, TypeError):\n            return NotImplemented\n\n    @beartype\n    def __neg__(self) -> H:\n        return self.umap(__neg__)\n\n    @beartype\n    def __pos__(self) -> H:\n        return self.umap(__pos__)\n\n    @beartype\n    def __abs__(self) -> H:\n        return self.umap(__abs__)\n\n    @beartype\n    def __invert__(self) -> H:\n        return self.umap(__invert__)\n\n    @beartype\n    def counts(self) -> ValuesView[int]:\n        r\"\"\"\n        More descriptive synonym for the [``values`` method][dyce.h.H.values].\n        \"\"\"\n        return self._h.values()\n\n    @beartype\n    def items(self) -> ItemsView[OutcomeT, int]:\n        # TODO(posita): See <https://github.com/python/typeshed/issues/5808>\n        return self._h.items()  # type: ignore\n\n    @beartype\n    def keys(self) -> KeysView[OutcomeT]:\n        return self.outcomes()\n\n    @beartype\n    def outcomes(self) -> KeysView[OutcomeT]:\n        r\"\"\"\n        More descriptive synonym for the [``keys`` method][dyce.h.H.keys].\n        \"\"\"\n        # TODO(posita): See <https://github.com/python/typeshed/issues/5808>\n        return self._h.keys()  # type: ignore\n\n    @beartype\n    def values(self) -> ValuesView[int]:\n        return self.counts()\n\n    # ---- Properties ------------------------------------------------------------------\n\n    @property\n    def total(self) -> int:\n        r\"\"\"\n        !!! warning \"Experimental\"\n\n            This propertyshould be considered experimental and may change or disappear\n            in future versions.\n\n        Equivalent to ``#!python sum(self.counts())``.\n        \"\"\"\n\n        @experimental\n        def _total() -> int:\n            return sum(self.counts())\n\n        return _total()\n\n    # ---- Methods ---------------------------------------------------------------------\n\n    @beartype\n    def map(\n        self,\n        bin_op: _BinaryOperatorT,\n        right_operand: _OperandT,\n    ) -> H:\n        r\"\"\"\n        Applies *bin_op* to each outcome of the histogram as the left operand and\n        *right_operand* as the right. Shorthands exist for many arithmetic operators and\n        comparators.\n\n        ``` python\n        >>> import operator\n        >>> d6 = H(6)\n        >>> d6.map(operator.__add__, d6)\n        H({2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 5, 9: 4, 10: 3, 11: 2, 12: 1})\n        >>> d6.map(operator.__add__, d6) == d6 + d6\n        True\n\n        ```\n\n        ``` python\n        >>> d6.map(operator.__pow__, 2)\n        H({1: 1, 4: 1, 9: 1, 16: 1, 25: 1, 36: 1})\n        >>> d6.map(operator.__pow__, 2) == d6 ** 2\n        True\n\n        ```\n\n        ``` python\n        >>> d6.map(operator.__gt__, 3)\n        H({False: 3, True: 3})\n        >>> d6.map(operator.__gt__, 3) == d6.gt(3)\n        True\n\n        ```\n        \"\"\"\n        if isinstance(right_operand, HableT):\n            right_operand = right_operand.h()\n\n        if isinstance(right_operand, H):\n            return type(self)(\n                (bin_op(s, o), self[s] * right_operand[o])\n                for s, o in product(self, right_operand)\n            )\n        else:\n            return type(self)(\n                (bin_op(outcome, right_operand), count)\n                for outcome, count in self.items()\n            )\n\n    @beartype\n    def rmap(\n        self,\n        left_operand: OutcomeT,\n        bin_op: _BinaryOperatorT,\n    ) -> H:\n        r\"\"\"\n        Analogous to the [``map`` method][dyce.h.H.map], but where the caller supplies\n        *left_operand*.\n\n        ``` python\n        >>> import operator\n        >>> d6 = H(6)\n        >>> d6.rmap(2, operator.__pow__)\n        H({2: 1, 4: 1, 8: 1, 16: 1, 32: 1, 64: 1})\n        >>> d6.rmap(2, operator.__pow__) == 2 ** d6\n        True\n\n        ```\n\n        !!! note\n\n            The positions of *left_operand* and *bin_op* are different from\n            [``map`` method][dyce.h.H.map]. This is intentional and serves as a reminder\n            of operand ordering.\n        \"\"\"\n        return type(self)(\n            (bin_op(left_operand, outcome), count) for outcome, count in self.items()\n        )\n\n    @beartype\n    def umap(\n        self,\n        un_op: _UnaryOperatorT,\n    ) -> H:\n        r\"\"\"\n        Applies *un_op* to each outcome of the histogram.\n\n        ``` python\n        >>> import operator\n        >>> H(6).umap(operator.__neg__)\n        H(-6)\n\n        ```\n\n        ``` python\n        >>> H(4).umap(lambda outcome: (-outcome) ** outcome)\n        H({-27: 1, -1: 1, 4: 1, 256: 1})\n\n        ```\n        \"\"\"\n        h = type(self)((un_op(outcome), count) for outcome, count in self.items())\n\n        if self._simple_init is not None:\n            simple_init = un_op(self._simple_init)\n\n            if isinstance(simple_init, _IntCs):\n                h_simple = type(self)(simple_init)\n\n                if h_simple == h:\n                    return h_simple\n\n        return h\n\n    @beartype\n    def lt(\n        self,\n        other: _OperandT,\n    ) -> H:\n        r\"\"\"\n        Shorthand for ``#!python self.map(operator.__lt__, other).umap(bool)``.\n\n        ``` python\n        >>> H(6).lt(3)\n        H({False: 4, True: 2})\n\n        ```\n\n        See the [``map``][dyce.h.H.map] and [``umap``][dyce.h.H.umap] methods.\n        \"\"\"\n        return self.map(__lt__, other).umap(bool)\n\n    @beartype\n    def le(\n        self,\n        other: _OperandT,\n    ) -> H:\n        r\"\"\"\n        Shorthand for ``#!python self.map(operator.__le__, other).umap(bool)``.\n\n        ``` python\n        >>> H(6).le(3)\n        H({False: 3, True: 3})\n\n        ```\n\n        See the [``map``][dyce.h.H.map] and [``umap``][dyce.h.H.umap] methods.\n        \"\"\"\n        return self.map(__le__, other).umap(bool)\n\n    @beartype\n    def eq(\n        self,\n        other: _OperandT,\n    ) -> H:\n        r\"\"\"\n        Shorthand for ``#!python self.map(operator.__eq__, other).umap(bool)``.\n\n        ``` python\n        >>> H(6).eq(3)\n        H({False: 5, True: 1})\n\n        ```\n\n        See the [``map``][dyce.h.H.map] and [``umap``][dyce.h.H.umap] methods.\n        \"\"\"\n        return self.map(__eq__, other).umap(bool)\n\n    @beartype\n    def ne(\n        self,\n        other: _OperandT,\n    ) -> H:\n        r\"\"\"\n        Shorthand for ``#!python self.map(operator.__ne__, other).umap(bool)``.\n\n        ``` python\n        >>> H(6).ne(3)\n        H({False: 1, True: 5})\n\n        ```\n\n        See the [``map``][dyce.h.H.map] and [``umap``][dyce.h.H.umap] methods.\n        \"\"\"\n        return self.map(__ne__, other).umap(bool)\n\n    @beartype\n    def gt(\n        self,\n        other: _OperandT,\n    ) -> H:\n        r\"\"\"\n        Shorthand for ``#!python self.map(operator.__gt__, other).umap(bool)``.\n\n        ``` python\n        >>> H(6).gt(3)\n        H({False: 3, True: 3})\n\n        ```\n\n        See the [``map``][dyce.h.H.map] and [``umap``][dyce.h.H.umap] methods.\n        \"\"\"\n        return self.map(__gt__, other).umap(bool)\n\n    @beartype\n    def ge(\n        self,\n        other: _OperandT,\n    ) -> H:\n        r\"\"\"\n        Shorthand for ``#!python self.map(operator.__ge__, other).umap(bool)``.\n\n        ``` python\n        >>> H(6).ge(3)\n        H({False: 2, True: 4})\n\n        ```\n\n        See the [``map``][dyce.h.H.map] and [``umap``][dyce.h.H.umap] methods.\n        \"\"\"\n        return self.map(__ge__, other).umap(bool)\n\n    @beartype\n    def is_even(self) -> H:\n        r\"\"\"\n        Equivalent to ``#!python self.umap(dyce.types.is_even)``.\n\n        ``` python\n        >>> H((-4, -2, 0, 1, 2, 3)).is_even()\n        H({False: 2, True: 4})\n\n        ```\n\n        See the [``umap`` method][dyce.h.H.umap].\n        \"\"\"\n        return self.umap(is_even)\n\n    @beartype\n    def is_odd(self) -> H:\n        r\"\"\"\n        Equivalent to ``#!python self.umap(dyce.types.is_odd)``.\n\n        ``` python\n        >>> H((-4, -2, 0, 1, 2, 3)).is_odd()\n        H({False: 4, True: 2})\n\n        ```\n\n        See the [``umap`` method][dyce.h.H.umap].\n        \"\"\"\n        return self.umap(is_odd)\n\n    @beartype\n    def accumulate(self, other: _SourceT) -> H:\n        r\"\"\"\n        Accumulates counts.\n\n        ``` python\n        >>> H(4).accumulate(H(6))\n        H({1: 2, 2: 2, 3: 2, 4: 2, 5: 1, 6: 1})\n\n        ```\n        \"\"\"\n        if isinstance(other, MappingC):\n            other = other.items()\n        elif not isinstance(other, IterableC):\n            other = cast(Iterable[OutcomeT], (other,))\n\n        return type(self)(chain(self.items(), cast(Iterable, other)))\n\n    @experimental\n    @beartype\n    def exactly_k_times_in_n(\n        self,\n        outcome: OutcomeT,\n        n: IntT,\n        k: IntT,\n    ) -> int:\n        r\"\"\"\n        !!! warning \"Experimental\"\n\n            This method should be considered experimental and may change or disappear in\n            future versions.\n\n        Computes and returns the probability distribution where *outcome* appears\n        exactly *k* times among ``#!python n@self``.\n\n        ``` python\n        >>> H(6).exactly_k_times_in_n(outcome=5, n=4, k=2)\n        150\n        >>> H((2, 3, 3, 4, 4, 5)).exactly_k_times_in_n(outcome=2, n=3, k=3)\n        1\n        >>> H((2, 3, 3, 4, 4, 5)).exactly_k_times_in_n(outcome=4, n=3, k=3)\n        8\n\n        ```\n        \"\"\"\n        n = as_int(n)\n        k = as_int(k)\n        assert k <= n\n        c_outcome = self.get(outcome, 0)\n\n        return comb(n, k) * c_outcome ** k * (self.total - c_outcome) ** (n - k)\n\n    @beartype\n    def explode(self, max_depth: IntT = 1) -> H:\n        r\"\"\"\n        Shorthand for ``#!python self.substitute(lambda h, outcome: h if outcome == max(h)\n        else outcome, operator.__add__, max_depth)``.\n\n        ``` python\n        >>> H(6).explode(max_depth=2)\n        H({1: 36, 2: 36, 3: 36, 4: 36, 5: 36, 7: 6, 8: 6, 9: 6, 10: 6, 11: 6, 13: 1, 14: 1, 15: 1, 16: 1, 17: 1, 18: 1})\n\n        ```\n\n        See the [``substitute`` method][dyce.h.H.substitute].\n        \"\"\"\n        return self.substitute(\n            lambda h, outcome: h if outcome == max(h) else outcome,\n            __add__,\n            max_depth,\n        )\n\n    @beartype\n    def lowest_terms(self) -> H:\n        r\"\"\"\n        Computes and returns a histogram whose counts share a greatest common divisor of 1.\n\n        ``` python\n        >>> df = H((-1, -1, 0, 0, 1, 1)) ; df\n        H({-1: 2, 0: 2, 1: 2})\n        >>> df.lowest_terms()\n        H({-1: 1, 0: 1, 1: 1})\n\n        ```\n\n        ``` python\n        >>> d6avg = H((2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5)) ; d6avg\n        H({2: 2, 3: 4, 4: 4, 5: 2})\n        >>> d6avg.lowest_terms()\n        H({2: 1, 3: 2, 4: 2, 5: 1})\n\n        ```\n        \"\"\"\n        return type(self)(self._lowest_terms())\n\n    @experimental\n    @beartype\n    def order_stat_for_n_at_pos(self, n: IntT, pos: IntT) -> H:\n        r\"\"\"\n        !!! warning \"Experimental\"\n\n            This method should be considered experimental and may change or disappear in\n            future versions.\n\n        Shorthand for ``#!python self.order_stat_func_for_n(n)(pos)``.\n        \"\"\"\n        return self.order_stat_func_for_n(n)(pos)\n\n    @experimental\n    @beartype\n    def order_stat_func_for_n(self, n: IntT) -> Callable[[IntT], \"H\"]:\n        r\"\"\"\n        !!! warning \"Experimental\"\n\n            This method should be considered experimental and may change or disappear in\n            future versions.\n\n        Returns a function that takes a single argument (*pos*) and computes the\n        probability distribution for each outcome appearing in that position among\n        ``#!python n@self``.\n\n        ``` python\n        >>> d6avg = H((2, 3, 3, 4, 4, 5))\n        >>> order_stat_for_5d6avg = d6avg.order_stat_func_for_n(5)\n        >>> order_stat_for_5d6avg(3)  # counts where outcome appears at index 3\n        H({2: 26, 3: 1432, 4: 4792, 5: 1526})\n\n        ```\n\n        The results show that, when rolling five six-sided “averaging” dice and sorting\n        each roll, there are 26 ways where ``#!python 2`` appears at the fourth (index\n        ``#!python 3``) position, 1432 ways where ``#!python 3`` appears at the fourth\n        position, etc. This can be verified independently using the computationally\n        expensive method of enumerating rolls and counting those that meet the criteria.\n\n        ``` python\n        >>> from dyce import P\n        >>> p_5d6avg = 5@P(d6avg)\n        >>> sum(count for roll, count in p_5d6avg.rolls_with_counts() if roll[3] == 5)\n        1526\n\n        ```\n\n        This method exists in addition to the\n        [``H.order_stat_for_n_at_pos`` method][dyce.h.H.order_stat_for_n_at_pos] because\n        computing the betas for each outcome in *n* is unnecessary for each *pos*. Where\n        different *pos* values are needed for the same *n* (e.g., in a loop) and where\n        *n* is large, that overhead can be significant. The returned function caches\n        those betas for *n* such that repeated querying or results at *pos* can be\n        computed much faster.\n\n        ``` python\n        In [2]: %timeit [H(6).order_stat_for_n_at_pos(100, i) for i in range(10)]\n        1.61 s ± 31.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\n        In [3]: %%timeit\n           ...: order_stat_for_100d6_at_pos = H(6).order_stat_func_for_n(100)\n           ...: [order_stat_for_100d6_at_pos(i) for i in range(10)]\n        170 ms ± 3.41 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n        ```\n        \"\"\"\n        betas_by_outcome: Dict[OutcomeT, Tuple[H, H]] = {}\n\n        for outcome in self.outcomes():\n            betas_by_outcome[outcome] = (\n                n @ self.le(outcome),\n                n @ self.lt(outcome),\n            )\n\n        def _gen_h_items_at_pos(pos: int) -> Iterator[Tuple[OutcomeT, int]]:\n            for outcome, (h_le, h_lt) in betas_by_outcome.items():\n                yield (\n                    outcome,\n                    h_le.gt(pos).get(True, 0) - h_lt.gt(pos).get(True, 0),\n                )\n\n        @beartype\n        def order_stat_for_n_at_pos(pos: IntT) -> H:\n            return type(self)(_gen_h_items_at_pos(as_int(pos)))\n\n        return order_stat_for_n_at_pos\n\n    @beartype\n    def substitute(\n        self,\n        expand: _ExpandT,\n        coalesce: _CoalesceT = coalesce_replace,\n        max_depth: IntT = 1,\n    ) -> H:\n        r\"\"\"\n        Calls *expand* on each outcome, recursively up to *max_depth* times. If *expand*\n        returns a number, it replaces the outcome. If it returns an\n        [``H`` object][dyce.h.H], *coalesce* is called on the outcome and the expanded\n        histogram, and the returned histogram is folded into result. The default\n        behavior for *coalesce* is to replace the outcome with the expanded histogram.\n        Returned histograms are always reduced to their lowest terms.\n\n        See [``coalesce_replace``][dyce.h.coalesce_replace] and the\n        [``lowest_terms`` method][dyce.h.H.lowest_terms].\n\n        This method can be used to model complex rules. The following models re-rolling\n        a face of 1 on the first roll:\n\n        ``` python\n        >>> def reroll_one(h: H, outcome):\n        ...   return h if outcome == 1 else outcome\n\n        >>> H(6).substitute(reroll_one)\n        H({1: 1, 2: 7, 3: 7, 4: 7, 5: 7, 6: 7})\n\n        ```\n\n        See the [``explode`` method][dyce.h.H.explode] for a common shorthand for\n        “exploding” dice (i.e., where, if the greatest face come up, the die is\n        re-rolled and the result is added to a running sum).\n\n        In nearly all cases, when a histogram is substituted for an outcome, it takes on\n        the substituted outcome’s “scale”. In other words, the sum of the counts of the\n        replacement retains the same proportion as the replaced outcome in relation to\n        other outcomes. This becomes clearer when there is no overlap between the\n        original histogram and the substitution.\n\n        ``` python\n        >>> orig = H({1: 1, 2: 2, 3: 3, 4: 4})\n        >>> sub = orig.substitute(lambda h, outcome: -h if outcome == 4 else outcome) ; sub\n        H({-4: 8, -3: 6, -2: 4, -1: 2, 1: 5, 2: 10, 3: 15})\n        >>> sum(count for outcome, count in orig.items() if outcome == 4) / orig.total\n        0.4\n        >>> sum(count for outcome, count in sub.items() if outcome < 0) / sub.total\n        0.4\n\n        ```\n\n        !!! note \"An important exception\"\n\n            If *coalesce* returns the empty histogram (``H({})``), the corresponding\n            outcome and its counts are omitted from the result without substitution or\n            scaling. A silly example is modeling a d5 by indefinitely re-rolling a d6\n            until something other than a 6 comes up.\n\n            ``` python\n            >>> H(6).substitute(lambda h, outcome: H({}) if outcome == 6 else outcome)\n            H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1})\n\n            ```\n\n            This technique is more useful when modeling re-rolling certain derived\n            outcomes, like ties in a contest.\n\n            ``` python\n            >>> d6_3, d8_2 = 3@H(6), 2@H(8)\n            >>> d6_3.vs(d8_2)\n            H({-1: 4553, 0: 1153, 1: 8118})\n            >>> d6_3.vs(d8_2).substitute(lambda h, outcome: H({}) if outcome == 0 else outcome)\n            H({-1: 4553, 1: 8118})\n\n            ```\n\n        Because it delegates to a callback for refereeing substitution decisions,\n        ``#!python substitute`` is quite flexible and well suited to modeling (or at\n        least approximating) logical progressions. Consider the following rules:\n\n          1. Start with a total of zero.\n          2. Roll a six-sided die. Add the face to the total. If the face was a six, go\n             to step 3. Otherwise stop.\n          3. Roll a four-sided die. Add the face to the total. If the face was a four,\n             go to step 2. Otherwise stop.\n\n        What is the likelihood of an even final tally? This can be approximated by:\n\n        ``` python\n        >>> d4, d6 = H(4), H(6)\n\n        >>> def reroll_greatest_on_d4_d6(h: H, outcome):\n        ...   if outcome == max(h):\n        ...     if h == d6: return d4\n        ...     if h == d4: return d6\n        ...   return outcome\n\n        >>> import operator\n        >>> h = d6.substitute(reroll_greatest_on_d4_d6, operator.__add__, max_depth=6)\n        >>> h_even = h.is_even()\n        >>> print(f\"{h_even[1] / h_even.total:.3%}\")\n        39.131%\n\n        ```\n\n        Surprised? Because both six and four are even numbers, the only way we keep\n        rolling is if the total is even. You might think this would lead to evens being\n        *more* likely. However, we only care about the final tally and the rules direct\n        us to re-roll certain evens (nudging us toward an odd number more often than\n        not).\n\n        We can also use this method to model expected damage from a single attack in\n        d20-like role playing games.\n\n        ``` python\n        >>> bonus = 1\n        >>> dmg_dice = H(8)\n        >>> dmg = dmg_dice + bonus\n        >>> crit = dmg + dmg_dice\n        >>> target = 15 - bonus\n        >>> d20 = H(20)\n\n        >>> def dmg_from_attack_roll(h: H, outcome):\n        ...   if outcome == 20:\n        ...     return crit\n        ...   elif outcome >= target:\n        ...     return dmg\n        ...   else:\n        ...     return 0\n\n        >>> h = d20.substitute(dmg_from_attack_roll)\n        >>> print(h.format(width=65, scaled=True))\n        avg |    2.15\n        std |    3.40\n        var |   11.55\n          0 |  65.00% |##################################################\n          2 |   3.75% |##\n          3 |   3.83% |##\n          4 |   3.91% |###\n          5 |   3.98% |###\n          6 |   4.06% |###\n          7 |   4.14% |###\n          8 |   4.22% |###\n          9 |   4.30% |###\n         10 |   0.62% |\n         11 |   0.55% |\n         12 |   0.47% |\n         13 |   0.39% |\n         14 |   0.31% |\n         15 |   0.23% |\n         16 |   0.16% |\n         17 |   0.08% |\n\n        ```\n        \"\"\"\n        max_depth = as_int(max_depth)\n\n        if max_depth < 0:\n            raise ValueError(\"max_depth cannot be negative\")\n\n        def _substitute(h: H, depth: int = 0) -> H:\n            assert coalesce is not None\n\n            if depth == max_depth:\n                return h\n\n            total_scalar = 1\n            items_for_reassembly: List[Tuple[OutcomeT, int, int]] = []\n\n            for outcome, count in h.items():\n                expanded = expand(h, outcome)\n\n                if isinstance(expanded, H):\n                    # Keep expanding deeper, if we can\n                    expanded = _substitute(expanded, depth + 1)\n                    # Coalesce the result\n                    expanded = coalesce(expanded, outcome)\n                    # Account for the impact of expansion on peers\n                    expanded_scalar = expanded.total\n\n                    if expanded_scalar:\n                        total_scalar *= expanded_scalar\n                        # Account for the impact of the original count on the result, but\n                        # keep track of the impact on peers so we can factor it out for\n                        # these items later\n                        items_for_reassembly.extend(\n                            (exp_f, exp_c * count, expanded_scalar)\n                            for exp_f, exp_c in expanded.items()\n                        )\n                else:\n                    items_for_reassembly.append((expanded, count, 1))\n\n            return type(self)(\n                (\n                    # Apply the total_scalar, but factor out this item's contribution\n                    (outcome, count * total_scalar // s)\n                    for outcome, count, s in items_for_reassembly\n                )\n            ).lowest_terms()\n\n        return _substitute(self)\n\n    @beartype\n    def vs(self, other: _OperandT) -> H:\n        r\"\"\"\n        Compares the histogram with *other*. -1 represents where *other* is greater. 0\n        represents where they are equal. 1 represents where *other* is less.\n\n        Shorthand for ``#!python self.within(0, 0, other)``.\n\n        ``` python\n        >>> H(6).vs(H(4))\n        H({-1: 6, 0: 4, 1: 14})\n        >>> H(6).vs(H(4)) == H(6).within(0, 0, H(4))\n        True\n\n        ```\n\n        See the [``within`` method][dyce.h.H.within].\n        \"\"\"\n        return self.within(0, 0, other)\n\n    @beartype\n    def within(self, lo: OutcomeT, hi: OutcomeT, other: _OperandT = 0) -> H:\n        r\"\"\"\n        Computes the difference between the histogram and *other*. -1 represents where that\n        difference is less than *lo*. 0 represents where that difference between *lo*\n        and *hi* (inclusive). 1 represents where that difference is greater than *hi*.\n\n        ``` python\n        >>> d6_2 = 2@H(6)\n        >>> d6_2.within(7, 9)\n        H({-1: 15, 0: 15, 1: 6})\n        >>> print(d6_2.within(7, 9).format(width=65))\n        avg |   -0.25\n        std |    0.72\n        var |    0.52\n         -1 |  41.67% |####################\n          0 |  41.67% |####################\n          1 |  16.67% |########\n\n        ```\n\n        ``` python\n        >>> d6_3, d8_2 = 3@H(6), 2@H(8)\n        >>> d6_3.within(-1, 1, d8_2)  # 3d6 w/in 1 of 2d8\n        H({-1: 3500, 0: 3412, 1: 6912})\n        >>> print(d6_3.within(-1, 1, d8_2).format(width=65))\n        avg |    0.25\n        std |    0.83\n        var |    0.69\n         -1 |  25.32% |############\n          0 |  24.68% |############\n          1 |  50.00% |#########################\n\n        ```\n        \"\"\"\n        return self.map(_within(lo, hi), other)\n\n    @overload\n    def distribution(\n        self,\n        fill_items: Optional[_MappingT] = None,\n    ) -> Iterator[Tuple[OutcomeT, Fraction]]:\n        ...\n\n    @overload\n    def distribution(\n        self,\n        fill_items: _MappingT,\n        rational_t: _RationalInitializerT[_T],\n    ) -> Iterator[Tuple[OutcomeT, _T]]:\n        ...\n\n    @overload\n    def distribution(\n        self,\n        *,\n        rational_t: _RationalInitializerT[_T],\n    ) -> Iterator[Tuple[OutcomeT, _T]]:\n        ...\n\n    @experimental\n    @beartype\n    def distribution(\n        self,\n        fill_items: Optional[_MappingT] = None,\n        # TODO(posita): See <https://github.com/python/mypy/issues/10854> for context on\n        # all the @overload work-around nonsense above and remove those once that issue\n        # is addressed.\n        rational_t: _RationalInitializerT[_T] = Fraction,\n    ) -> Iterator[Tuple[OutcomeT, _T]]:\n        r\"\"\"\n        Presentation helper function returning an iterator for each outcome/count or\n        outcome/probability pair.\n\n        ``` python\n        >>> h = H((1, 2, 3, 3, 4, 4, 5, 6))\n        >>> list(h.distribution())\n        [(1, Fraction(1, 8)), (2, Fraction(1, 8)), (3, Fraction(1, 4)), (4, Fraction(1, 4)), (5, Fraction(1, 8)), (6, Fraction(1, 8))]\n        >>> list(h.ge(3).distribution())\n        [(False, Fraction(1, 4)), (True, Fraction(3, 4))]\n\n        ```\n\n        If provided, *fill_items* supplies defaults for any “missing” outcomes.\n\n        ``` python\n        >>> list(h.distribution())\n        [(1, Fraction(1, 8)), (2, Fraction(1, 8)), (3, Fraction(1, 4)), (4, Fraction(1, 4)), (5, Fraction(1, 8)), (6, Fraction(1, 8))]\n        >>> list(h.distribution(fill_items={0: 0, 7: 0}))\n        [(0, Fraction(0, 1)), (1, Fraction(1, 8)), (2, Fraction(1, 8)), (3, Fraction(1, 4)), (4, Fraction(1, 4)), (5, Fraction(1, 8)), (6, Fraction(1, 8)), (7, Fraction(0, 1))]\n\n        ```\n\n        !!! warning \"Experimental\"\n\n            The *rational_t* argument to this method should be considered experimental\n            and may change or disappear in future versions.\n\n        If provided, *rational_t* must be a callable that takes two ``#!python int``s (a\n        numerator and denominator) and returns an instance of a desired (but otherwise\n        arbitrary) type.\n\n        ``` python\n        >>> list(h.distribution(rational_t=lambda n, d: f\"{n}/{d}\"))\n        [(1, '1/8'), (2, '1/8'), (3, '2/8'), (4, '2/8'), (5, '1/8'), (6, '1/8')]\n\n        ```\n\n        ``` python\n        >>> import sympy\n        >>> list(h.distribution(rational_t=sympy.Rational))\n        [(1, 1/8), (2, 1/8), (3, 1/4), (4, 1/4), (5, 1/8), (6, 1/8)]\n\n        ```\n\n        ``` python\n        >>> import sage.rings.rational  # doctest: +SKIP\n        >>> list(h.distribution(rational_t=lambda n, d: sage.rings.rational.Rational((n, d))))  # doctest: +SKIP\n        [(1, 1/8), (2, 1/8), (3, 1/4), (4, 1/4), (5, 1/8), (6, 1/8)]\n\n        ```\n\n        !!! note\n\n            The arguments passed to *rational_t* are not reduced to the lowest terms.\n\n        The *rational_t* argument is a convenience. Iteration or comprehension can be\n        used to accomplish something similar.\n\n        ``` python\n        >>> [(outcome, f\"{probability.numerator}/{probability.denominator}\") for outcome, probability in (h).distribution()]\n        [(1, '1/8'), (2, '1/8'), (3, '1/4'), (4, '1/4'), (5, '1/8'), (6, '1/8')]\n\n        ```\n\n        Many number implementations can convert directly from ``#!python\n        fractions.Fraction``s.\n\n        ``` python\n        >>> import sympy.abc\n        >>> [(outcome, sympy.Rational(probability)) for outcome, probability in (h + sympy.abc.x).distribution()]\n        [(x + 1, 1/8), (x + 2, 1/8), (x + 3, 1/4), (x + 4, 1/4), (x + 5, 1/8), (x + 6, 1/8)]\n\n        ```\n\n        ``` python\n        >>> import sage.rings.rational  # doctest: +SKIP\n        >>> [(outcome, sage.rings.rational.Rational(probability)) for outcome, probability in h.distribution()]  # doctest: +SKIP\n        [(1, 1/6), (2, 1/6), (3, 1/3), (4, 1/3), (5, 1/6), (6, 1/6)]\n\n        ```\n        \"\"\"\n        if fill_items is None:\n            fill_items = {}\n\n        combined = dict(chain(fill_items.items(), self.items()))\n        total = sum(combined.values()) or 1\n\n        return (\n            (outcome, rational_t(combined[outcome], total))\n            for outcome in sorted_outcomes(combined)\n        )\n\n    @beartype\n    def distribution_xy(\n        self,\n        fill_items: Optional[_MappingT] = None,\n    ) -> Tuple[Tuple[OutcomeT, ...], Tuple[float, ...]]:\n        r\"\"\"\n        Presentation helper function returning an iterator for a “zipped” arrangement of the\n        output from the [``distribution`` method][dyce.h.H.distribution] and ensures the\n        values are ``#!python float``s.\n\n        ``` python\n        >>> list(H(6).distribution())\n        [(1, Fraction(1, 6)), (2, Fraction(1, 6)), (3, Fraction(1, 6)), (4, Fraction(1, 6)), (5, Fraction(1, 6)), (6, Fraction(1, 6))]\n        >>> H(6).distribution_xy()\n        ((1, 2, 3, 4, 5, 6), (0.16666666, 0.16666666, 0.16666666, 0.16666666, 0.16666666, 0.16666666))\n\n        ```\n        \"\"\"\n        # TODO(posita): See <https://github.com/python/typing/issues/193>\n        return tuple(  # type: ignore\n            zip(\n                *(\n                    (outcome, float(probability))\n                    for outcome, probability in self.distribution(fill_items)\n                )\n            )\n        )\n\n    @beartype\n    def format(\n        self,\n        fill_items: Optional[_MappingT] = None,\n        width: IntT = _ROW_WIDTH,\n        scaled: bool = False,\n        tick: str = \"#\",\n        sep: str = os.linesep,\n    ) -> str:\n        r\"\"\"\n        Returns a formatted string representation of the histogram. If provided,\n        *fill_items* supplies defaults for any missing outcomes. If *width* is greater\n        than zero, a horizontal bar ASCII graph is printed using *tick* and *sep* (which\n        are otherwise ignored if *width* is zero or less).\n\n        ``` python\n        >>> print(H(6).format(width=0))\n        {avg: 3.50, 1: 16.67%, 2: 16.67%, 3: 16.67%, 4: 16.67%, 5: 16.67%, 6: 16.67%}\n\n        ```\n\n        ``` python\n        >>> print((2@H(6)).format(fill_items={i: 0 for i in range(1, 21)}, width=65, tick=\"@\"))\n        avg |    7.00\n        std |    2.42\n        var |    5.83\n          1 |   0.00% |\n          2 |   2.78% |@\n          3 |   5.56% |@@\n          4 |   8.33% |@@@@\n          5 |  11.11% |@@@@@\n          6 |  13.89% |@@@@@@\n          7 |  16.67% |@@@@@@@@\n          8 |  13.89% |@@@@@@\n          9 |  11.11% |@@@@@\n         10 |   8.33% |@@@@\n         11 |   5.56% |@@\n         12 |   2.78% |@\n         13 |   0.00% |\n         14 |   0.00% |\n         15 |   0.00% |\n         16 |   0.00% |\n         17 |   0.00% |\n         18 |   0.00% |\n         19 |   0.00% |\n         20 |   0.00% |\n\n        ```\n\n        If *scaled* is ``#!python True``, horizontal bars are scaled to *width*.\n\n        ``` python\n        >>> h = (2@H(6)).ge(7)\n        >>> print(f\"{' 65 chars wide -->|':->65}\")\n        ---------------------------------------------- 65 chars wide -->|\n        >>> print(h.format(width=65, scaled=False))\n        avg |    0.58\n        std |    0.49\n        var |    0.24\n          0 |  41.67% |####################\n          1 |  58.33% |#############################\n        >>> print(h.format(width=65, scaled=True))\n        avg |    0.58\n        std |    0.49\n        var |    0.24\n          0 |  41.67% |###################################\n          1 |  58.33% |##################################################\n\n        ```\n        \"\"\"\n        width = as_int(width)\n\n        # We convert various values herein to native ints and floats because number\n        # tower implementations sometimes neglect to implement __format__ properly (or\n        # at all). (I'm looking at you, sage.rings.…!)\n        try:\n            mu: OutcomeT = float(self.mean())\n        except TypeError:\n            mu = self.mean()\n\n        if width <= 0:\n\n            def _parts() -> Iterator[str]:\n                yield f\"avg: {mu:.2f}\"\n\n                for (\n                    outcome,\n                    probability,\n                ) in self.distribution(fill_items):\n                    probability_f = float(probability)\n                    yield f\"{outcome}:{probability_f:7.2%}\"\n\n            return \"{\" + \", \".join(_parts()) + \"}\"\n        else:\n            w = width - 15\n\n            @beartype\n            def lines() -> Iterator[str]:\n                yield f\"avg | {mu:7.2f}\"\n\n                try:\n                    std = float(self.stdev(mu))\n                    var = float(self.variance(mu))\n                    yield f\"std | {std:7.2f}\"\n                    yield f\"var | {var:7.2f}\"\n                except TypeError:\n                    pass\n\n                if self:\n                    outcomes, probabilities = self.distribution_xy(fill_items)\n                    tick_scale = max(probabilities) if scaled else 1.0\n\n                    for outcome, probability in zip(outcomes, probabilities):\n                        try:\n                            outcome_str = f\"{outcome: 3}\"\n                        except (TypeError, ValueError):\n                            outcome_str = str(outcome)\n                            outcome_str = f\"{outcome_str: >3}\"\n\n                        ticks = tick * int(w * probability / tick_scale)\n                        probability_f = float(probability)\n                        yield f\"{outcome_str} | {probability_f:7.2%} |{ticks}\"\n\n            return sep.join(lines())\n\n    @beartype\n    def mean(self) -> OutcomeT:\n        r\"\"\"\n        Returns the mean of the weighted outcomes (or 0.0 if there are no outcomes).\n        \"\"\"\n        numerator: float\n        denominator: float\n        numerator = denominator = 0\n\n        for outcome, count in self.items():\n            numerator += outcome * count\n            denominator += count\n\n        return numerator / (denominator or 1)\n\n    @beartype\n    def stdev(self, mu: Optional[OutcomeT] = None) -> OutcomeT:\n        r\"\"\"\n        Shorthand for ``#!python math.sqrt(self.variance(mu))``.\n        \"\"\"\n        return sqrt(self.variance(mu))\n\n    @beartype\n    def variance(self, mu: Optional[OutcomeT] = None) -> OutcomeT:\n        r\"\"\"\n        Returns the variance of the weighted outcomes. If provided, *mu* is used as the mean\n        (to avoid duplicate computation).\n        \"\"\"\n        mu = mu if mu else self.mean()\n        numerator: float\n        denominator: float\n        numerator = denominator = 0\n\n        for outcome, count in self.items():\n            numerator += (outcome - mu) ** 2 * count\n            denominator += count\n\n        return numerator / (denominator or 1)\n\n    @beartype\n    def roll(self) -> OutcomeT:\n        r\"\"\"\n        Returns a (weighted) random outcome, sorted.\n        \"\"\"\n        return (\n            rng.RNG.choices(\n                population=tuple(self.outcomes()),\n                weights=tuple(self.counts()),\n                k=1,\n            )[0]\n            if self\n            else 0\n        )\n\n    def _lowest_terms(self) -> Iterable[Tuple[OutcomeT, int]]:\n        counts_gcd = gcd(*self.counts())\n\n        return ((k, v // counts_gcd) for k, v in self.items())\n\n\n@runtime_checkable\nclass HableT(\n    Protocol,\n    metaclass=CachingProtocolMeta,\n):\n    r\"\"\"\n    A protocol whose implementer can be expressed as (or reduced to) an\n    [``H`` object][dyce.h.H] by calling its [``h`` method][dyce.h.HableT.h]. Currently,\n    only the [``P`` class][dyce.p.P] implements this protocol, but this affords an\n    integration point for ``#!python dyce`` users.\n\n    !!! info\n\n        The intended pronunciation of ``Hable`` is *AYCH-uh-bul*[^1] (i.e.,\n        [``H``][dyce.h.H]-able). Yes, that is a clumsy attempt at\n        [verbing](https://www.gocomics.com/calvinandhobbes/1993/01/25). (You could\n        *totally* [``H``][dyce.h.H] that, dude!) However, if you prefer something else\n        (e.g. *HAY-bul* or *AYCH-AY-bul*), no one is going to judge you. (Well, they\n        *might*, but they *shouldn’t*.) We all know what you mean.\n\n    [^1]:\n\n        World Book Online (WBO) style [pronunciation\n        respelling](https://en.wikipedia.org/wiki/Pronunciation_respelling_for_English#Traditional_respelling_systems).\n    \"\"\"\n    __slots__: Tuple[str, ...] = ()\n\n    def h(self) -> H:\n        r\"\"\"\n        Express its implementer as an [``H`` object][dyce.h.H].\n        \"\"\"\n        ...\n\n\nclass HableOpsMixin:\n    r\"\"\"\n    A “mix-in” class providing arithmetic operations for implementers of the\n    [``HableT`` protocol][dyce.h.HableT]. The [``P`` class][dyce.p.P] derives from this\n    class.\n\n    !!! info\n\n        See [``HableT``][dyce.h.HableT] for notes on pronunciation.\n    \"\"\"\n    __slots__: Tuple[str, ...] = ()\n\n    @beartype\n    def __add__(self: HableT, other: _OperandT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__add__(self.h(), other)``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __add__(self.h(), other)\n\n    @beartype\n    def __radd__(self: HableT, other: OutcomeT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__add__(other, self.h())``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __add__(other, self.h())\n\n    @beartype\n    def __sub__(self: HableT, other: _OperandT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__sub__(self.h(), other)``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __sub__(self.h(), other)\n\n    @beartype\n    def __rsub__(self: HableT, other: OutcomeT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__sub__(other, self.h())``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __sub__(other, self.h())\n\n    @beartype\n    def __mul__(self: HableT, other: _OperandT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__mul__(self.h(), other)``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __mul__(self.h(), other)\n\n    @beartype\n    def __rmul__(self: HableT, other: OutcomeT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__mul__(other, self.h())``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __mul__(other, self.h())\n\n    @beartype\n    def __truediv__(self: HableT, other: _OperandT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__truediv__(self.h(), other)``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __truediv__(self.h(), other)\n\n    @beartype\n    def __rtruediv__(self: HableT, other: OutcomeT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__truediv__(other, self.h())``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __truediv__(other, self.h())\n\n    @beartype\n    def __floordiv__(self: HableT, other: _OperandT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__floordiv__(self.h(), other)``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __floordiv__(self.h(), other)\n\n    @beartype\n    def __rfloordiv__(self: HableT, other: OutcomeT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__floordiv__(other, self.h())``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __floordiv__(other, self.h())\n\n    @beartype\n    def __mod__(self: HableT, other: _OperandT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__mod__(self.h(), other)``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __mod__(self.h(), other)\n\n    @beartype\n    def __rmod__(self: HableT, other: OutcomeT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__mod__(other, self.h())``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __mod__(other, self.h())\n\n    @beartype\n    def __pow__(self: HableT, other: _OperandT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__pow__(self.h(), other)``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __pow__(self.h(), other)\n\n    @beartype\n    def __rpow__(self: HableT, other: OutcomeT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__pow__(other, self.h())``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __pow__(other, self.h())\n\n    @beartype\n    def __and__(self: HableT, other: Union[IntT, H, HableT]) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__and__(self.h(), other)``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __and__(self.h(), other)\n\n    @beartype\n    def __rand__(self: HableT, other: IntT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__and__(other, self.h())``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __and__(other, self.h())\n\n    @beartype\n    def __xor__(self: HableT, other: Union[IntT, H, HableT]) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__xor__(self.h(), other)``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __xor__(self.h(), other)\n\n    @beartype\n    def __rxor__(self: HableT, other: IntT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__xor__(other, self.h())``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __xor__(other, self.h())\n\n    @beartype\n    def __or__(self: HableT, other: Union[IntT, H, HableT]) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__or__(self.h(), other)``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __or__(self.h(), other)\n\n    @beartype\n    def __ror__(self: HableT, other: IntT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__or__(other, self.h())``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __or__(other, self.h())\n\n    @beartype\n    def __neg__(self: HableT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__neg__(self.h())``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __neg__(self.h())\n\n    @beartype\n    def __pos__(self: HableT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__pos__(self.h())``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __pos__(self.h())\n\n    @beartype\n    def __abs__(self: HableT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__abs__(self.h())``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __abs__(self.h())\n\n    @beartype\n    def __invert__(self: HableT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python operator.__invert__(self.h())``. See the\n        [``h`` method][dyce.h.HableT.h].\n        \"\"\"\n        return __invert__(self.h())\n\n    @beartype\n    def lt(self: HableT, other: _OperandT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python self.h().lt(other)``. See the\n        [``h`` method][dyce.h.HableT.h] and [``H.lt``][dyce.h.H.lt].\n        \"\"\"\n        return self.h().lt(other)\n\n    @beartype\n    def le(self: HableT, other: _OperandT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python self.h().le(other)``. See the\n        [``h`` method][dyce.h.HableT.h] and [``H.le``][dyce.h.H.le].\n        \"\"\"\n        return self.h().le(other)\n\n    @beartype\n    def eq(self: HableT, other: _OperandT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python self.h().eq(other)``. See the\n        [``h`` method][dyce.h.HableT.h] and [``H.eq``][dyce.h.H.eq].\n        \"\"\"\n        return self.h().eq(other)\n\n    @beartype\n    def ne(self: HableT, other: _OperandT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python self.h().ne(other)``. See the\n        [``h`` method][dyce.h.HableT.h] and [``H.ne``][dyce.h.H.ne].\n        \"\"\"\n        return self.h().ne(other)\n\n    @beartype\n    def gt(self: HableT, other: _OperandT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python self.h().gt(other)``. See the\n        [``h`` method][dyce.h.HableT.h] and [``H.gt``][dyce.h.H.gt].\n        \"\"\"\n        return self.h().gt(other)\n\n    @beartype\n    def ge(self: HableT, other: _OperandT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python self.h().ge(other)``. See the\n        [``h`` method][dyce.h.HableT.h] and [``H.ge``][dyce.h.H.ge].\n        \"\"\"\n        return self.h().ge(other)\n\n    @beartype\n    def is_even(self: HableT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python self.h().is_even()``. See the\n        [``h`` method][dyce.h.HableT.h] and [``H.is_even``][dyce.h.H.is_even].\n        \"\"\"\n        return self.h().is_even()\n\n    @beartype\n    def is_odd(self: HableT) -> H:\n        r\"\"\"\n        Shorthand for ``#!python self.h().is_odd()``. See the\n        [``h`` method][dyce.h.HableT.h] and [``H.is_odd``][dyce.h.H.is_odd].\n        \"\"\"\n        return self.h().is_odd()\n\n    @beartype\n    def explode(self: HableT, max_depth: IntT = 1) -> H:\n        r\"\"\"\n        Shorthand for ``#!python self.h().explode(max_depth)``. See the\n        [``h`` method][dyce.h.HableT.h] and [``H.explode``][dyce.h.H.explode].\n        \"\"\"\n        return self.h().explode(max_depth)\n\n    @beartype\n    def substitute(\n        self: HableT,\n        expand: _ExpandT,\n        coalesce: _CoalesceT = coalesce_replace,\n        max_depth: IntT = 1,\n    ) -> H:\n        r\"\"\"\n        Shorthand for ``#!python self.h().substitute(expand, coalesce, max_depth)``. See the\n        [``h`` method][dyce.h.HableT.h] and [``H.substitute``][dyce.h.H.substitute].\n        \"\"\"\n        return self.h().substitute(expand, coalesce, max_depth)\n\n    @beartype\n    def within(self: HableT, lo: OutcomeT, hi: OutcomeT, other: _OperandT = 0) -> H:\n        r\"\"\"\n        Shorthand for ``#!python self.h().within(lo, hi, other)``. See the\n        [``h`` method][dyce.h.HableT.h] and [``H.within``][dyce.h.H.within].\n        \"\"\"\n        return self.h().within(lo, hi, other)\n\n\n# ---- Functions -----------------------------------------------------------------------\n\n\n@beartype\ndef sum_h(hs: Iterable[H]):\n    \"\"\"\n    Shorthand for ``#!python H({}) if h_sum == 0 else sum(hs)``.\n\n    This is to ensure that summing zero or more histograms always returns a histograms.\n    \"\"\"\n    h_sum = sum(hs)\n\n    return H({}) if h_sum == 0 else h_sum\n\n\n@beartype\ndef _within(lo: OutcomeT, hi: OutcomeT) -> _BinaryOperatorT:\n    if lo > hi:\n        raise ValueError(f\"lower bound ({lo}) is greater than upper bound ({hi})\")\n\n    def _cmp(a: OutcomeT, b: OutcomeT) -> int:\n        # This approach will probably not work with most symbolic outcomes\n        diff = a - b\n\n        return bool(diff > hi) - bool(diff < lo)\n\n    setattr(_cmp, \"lo\", lo)\n    setattr(_cmp, \"hi\", hi)\n\n    return _cmp\n", "meta": {"hexsha": "94297df39139b5ae0cfcc409e9abe891ffbbbdd5", "size": 63354, "ext": "py", "lang": "Python", "max_stars_repo_path": "dyce/h.py", "max_stars_repo_name": "posita/dyce", "max_stars_repo_head_hexsha": "aa0180cc1e3607e552e45f9d03af7de667838aea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2021-07-08T07:04:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:42:50.000Z", "max_issues_repo_path": "dyce/h.py", "max_issues_repo_name": "posita/dyce", "max_issues_repo_head_hexsha": "aa0180cc1e3607e552e45f9d03af7de667838aea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-07-21T23:40:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-08T14:50:53.000Z", "max_forks_repo_path": "dyce/h.py", "max_forks_repo_name": "posita/dyce", "max_forks_repo_head_hexsha": "aa0180cc1e3607e552e45f9d03af7de667838aea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2117310443, "max_line_length": 176, "alphanum_fraction": 0.517788932, "include": true, "reason": "import sympy,import sage", "num_tokens": 17959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.32766831395172374, "lm_q1q2_score": 0.17406047972873043}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2020 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#\n\nimport time\nimport numpy\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf import ao2mo\nfrom pyscf.cc import ccsd\n\n#\n# JCP, 95, 2623\n# JCP, 95, 2639\n#\n\ndef _gamma1_intermediates(mycc, t1, t2, l1, l2):\n    nocc, nvir = t1.shape\n    doo =-numpy.einsum('ja,ia->ij', t1, l1)\n    dvv = numpy.einsum('ia,ib->ab', t1, l1)\n    xtv = numpy.einsum('ie,me->im', t1, l1)\n    dvo = t1.T - numpy.einsum('im,ma->ai', xtv, t1)\n    theta = t2 * 2 - t2.transpose(0,1,3,2)\n    doo -= lib.einsum('jkab,ikab->ij', theta, l2)\n    dvv += lib.einsum('jica,jicb->ab', theta, l2)\n    xt1  = lib.einsum('mnef,inef->mi', l2, theta)\n    xt2  = lib.einsum('mnaf,mnef->ea', l2, theta)\n    dvo += numpy.einsum('imae,me->ai', theta, l1)\n    dvo -= numpy.einsum('mi,ma->ai', xt1, t1)\n    dvo -= numpy.einsum('ie,ae->ai', t1, xt2)\n    dov = l1\n    return doo, dov, dvo, dvv\n\n# gamma2 intermediates in Chemist's notation\ndef _gamma2_intermediates(mycc, t1, t2, l1, l2, compress_vvvv=False):\n    f = lib.H5TmpFile()\n    _gamma2_outcore(mycc, t1, t2, l1, l2, f, compress_vvvv)\n    d2 = (f['dovov'].value, f['dvvvv'].value, f['doooo'].value, f['doovv'].value,\n          f['dovvo'].value, None,             f['dovvv'].value, f['dooov'].value)\n    return d2\n\ndef _gamma2_outcore(mycc, t1, t2, l1, l2, h5fobj, compress_vvvv=False):\n    log = logger.Logger(mycc.stdout, mycc.verbose)\n    nocc, nvir = t1.shape\n    nov = nocc * nvir\n    nvir_pair = nvir * (nvir+1) //2\n    dtype = numpy.result_type(t1, t2, l1, l2).char\n    if compress_vvvv:\n        dvvvv = h5fobj.create_dataset('dvvvv', (nvir_pair,nvir_pair), dtype)\n    else:\n        dvvvv = h5fobj.create_dataset('dvvvv', (nvir,nvir,nvir,nvir), dtype)\n    dovvo = h5fobj.create_dataset('dovvo', (nocc,nvir,nvir,nocc), dtype,\n                                  chunks=(nocc,1,nvir,nocc))\n    fswap = lib.H5TmpFile()\n\n    time1 = time.clock(), time.time()\n    pvOOv = lib.einsum('ikca,jkcb->aijb', l2, t2)\n    moo = numpy.einsum('dljd->jl', pvOOv) * 2\n    mvv = numpy.einsum('blld->db', pvOOv) * 2\n    gooov = lib.einsum('kc,cija->jkia', t1, pvOOv)\n    fswap['mvOOv'] = pvOOv\n    pvOOv = None\n\n    pvoOV = -lib.einsum('ikca,jkbc->aijb', l2, t2)\n    theta = t2 * 2 - t2.transpose(0,1,3,2)\n    pvoOV += lib.einsum('ikac,jkbc->aijb', l2, theta)\n    moo += numpy.einsum('dljd->jl', pvoOV)\n    mvv += numpy.einsum('blld->db', pvoOV)\n    gooov -= lib.einsum('jc,cika->jkia', t1, pvoOV)\n    fswap['mvoOV'] = pvoOV\n    pvoOV = None\n\n    mia =(numpy.einsum('kc,ikac->ia', l1, t2) * 2\n        - numpy.einsum('kc,ikca->ia', l1, t2))\n    mab = numpy.einsum('kc,kb->cb', l1, t1)\n    mij = numpy.einsum('kc,jc->jk', l1, t1) + moo*.5\n\n    tau = numpy.einsum('ia,jb->ijab', t1, t1)\n    tau += t2\n    goooo = lib.einsum('ijab,klab->ijkl', tau, l2)*.5\n    h5fobj['doooo'] = (goooo.transpose(0,2,1,3)*2 -\n                       goooo.transpose(0,3,1,2)).conj()\n\n    gooov += numpy.einsum('ji,ka->jkia', -.5*moo, t1)\n    gooov += lib.einsum('la,jkil->jkia', 2*t1, goooo)\n    gooov -= lib.einsum('ib,jkba->jkia', l1, tau)\n    gooov = gooov.conj()\n    gooov -= lib.einsum('jkba,ib->jkia', l2, t1)\n    h5fobj['dooov'] = gooov.transpose(0,2,1,3)*2 - gooov.transpose(1,2,0,3)\n    tau = goovo = None\n    time1 = log.timer_debug1('rdm intermediates pass1', *time1)\n\n    goovv = numpy.einsum('ia,jb->ijab', mia.conj(), t1.conj())\n    max_memory = max(0, mycc.max_memory - lib.current_memory()[0])\n    unit = nocc**2*nvir*6\n    blksize = min(nocc, nvir, max(ccsd.BLKMIN, int(max_memory*.95e6/8/unit)))\n    doovv = h5fobj.create_dataset('doovv', (nocc,nocc,nvir,nvir), dtype,\n                                  chunks=(nocc,nocc,1,nvir))\n\n    log.debug1('rdm intermediates pass 2: block size = %d, nvir = %d in %d blocks',\n               blksize, nvir, int((nvir+blksize-1)/blksize))\n    for p0, p1 in lib.prange(0, nvir, blksize):\n        tau = numpy.einsum('ia,jb->ijab', t1[:,p0:p1], t1)\n        tau += t2[:,:,p0:p1]\n        tmpoovv  = lib.einsum('ijkl,klab->ijab', goooo, tau)\n        tmpoovv -= lib.einsum('jk,ikab->ijab', mij, tau)\n        tmpoovv -= lib.einsum('cb,ijac->ijab', mab, t2[:,:,p0:p1])\n        tmpoovv -= lib.einsum('bd,ijad->ijab', mvv*.5, tau)\n        tmpoovv += .5 * tau\n        tmpoovv = tmpoovv.conj()\n        tmpoovv += .5 * l2[:,:,p0:p1]\n        goovv[:,:,p0:p1] += tmpoovv\n\n        pvOOv = fswap['mvOOv'][p0:p1]\n        pvoOV = fswap['mvoOV'][p0:p1]\n        gOvvO = lib.einsum('kiac,jc,kb->iabj', l2[:,:,p0:p1], t1, t1)\n        gOvvO += numpy.einsum('aijb->iabj', pvOOv)\n        govVO = numpy.einsum('ia,jb->iabj', l1[:,p0:p1], t1)\n        govVO -= lib.einsum('ikac,jc,kb->iabj', l2[:,:,p0:p1], t1, t1)\n        govVO += numpy.einsum('aijb->iabj', pvoOV)\n        dovvo[:,p0:p1] = 2*govVO + gOvvO\n        doovv[:,:,p0:p1] = (-2*gOvvO - govVO).transpose(3,0,1,2).conj()\n        gOvvO = govVO = None\n\n        tau -= t2[:,:,p0:p1] * .5\n        for q0, q1 in lib.prange(0, nvir, blksize):\n            goovv[:,:,q0:q1,:] += lib.einsum('dlib,jlda->ijab', pvOOv, tau[:,:,:,q0:q1]).conj()\n            goovv[:,:,:,q0:q1] -= lib.einsum('dlia,jldb->ijab', pvoOV, tau[:,:,:,q0:q1]).conj()\n            tmp = pvoOV[:,:,:,q0:q1] + pvOOv[:,:,:,q0:q1]*.5\n            goovv[:,:,q0:q1,:] += lib.einsum('dlia,jlbd->ijab', tmp, t2[:,:,:,p0:p1]).conj()\n        pvOOv = pvoOV = tau = None\n        time1 = log.timer_debug1('rdm intermediates pass2 [%d:%d]'%(p0, p1), *time1)\n    h5fobj['dovov'] = goovv.transpose(0,2,1,3) * 2 - goovv.transpose(1,2,0,3)\n    goovv = goooo = None\n\n    max_memory = max(0, mycc.max_memory - lib.current_memory()[0])\n    unit = max(nocc**2*nvir*2+nocc*nvir**2*3,\n               nvir**3*2+nocc*nvir**2*2+nocc**2*nvir*2)\n    blksize = min(nvir, max(ccsd.BLKMIN, int(max_memory*.9e6/8/unit)))\n    iobuflen = int(256e6/8/blksize)\n    log.debug1('rdm intermediates pass 3: block size = %d, nvir = %d in %d blocks',\n               blksize, nocc, int((nvir+blksize-1)/blksize))\n    dovvv = h5fobj.create_dataset('dovvv', (nocc,nvir,nvir,nvir), dtype,\n                                  chunks=(nocc,min(nocc,nvir),1,nvir))\n    time1 = time.clock(), time.time()\n    for istep, (p0, p1) in enumerate(lib.prange(0, nvir, blksize)):\n        l2tmp = l2[:,:,p0:p1]\n        gvvvv = lib.einsum('ijab,ijcd->abcd', l2tmp, t2)\n        jabc = lib.einsum('ijab,ic->jabc', l2tmp, t1)\n        gvvvv += lib.einsum('jabc,jd->abcd', jabc, t1)\n        l2tmp = jabc = None\n\n        if compress_vvvv:\n# symmetrize dvvvv because it does not affect the results of ccsd_grad\n# dvvvv = gvvvv.transpose(0,2,1,3)-gvvvv.transpose(0,3,1,2)*.5\n# dvvvv = (dvvvv+dvvvv.transpose(0,1,3,2)) * .5\n# dvvvv = (dvvvv+dvvvv.transpose(1,0,2,3)) * .5\n# now dvvvv == dvvvv.transpose(0,1,3,2) == dvvvv.transpose(1,0,3,2)\n            tmp = numpy.empty((nvir,nvir,nvir))\n            tmpvvvv = numpy.empty((p1-p0,nvir,nvir_pair))\n            for i in range(p1-p0):\n                vvv = gvvvv[i].conj().transpose(1,0,2)\n                tmp[:] = vvv - vvv.transpose(2,1,0)*.5\n                lib.pack_tril(tmp+tmp.transpose(0,2,1), out=tmpvvvv[i])\n            # tril of (dvvvv[p0:p1,p0:p1]+dvvvv[p0:p1,p0:p1].T)\n            for i in range(p0, p1):\n                for j in range(p0, i):\n                    tmpvvvv[i-p0,j] += tmpvvvv[j-p0,i]\n                tmpvvvv[i-p0,i] *= 2\n            for i in range(p1, nvir):\n                off = i * (i+1) // 2\n                dvvvv[off+p0:off+p1] = tmpvvvv[:,i]\n            for i in range(p0, p1):\n                off = i * (i+1) // 2\n                if p0 > 0:\n                    tmpvvvv[i-p0,:p0] += dvvvv[off:off+p0]\n                dvvvv[off:off+i+1] = tmpvvvv[i-p0,:i+1] * .25\n            tmp = tmpvvvv = None\n        else:\n            for i in range(p0, p1):\n                vvv = gvvvv[i-p0].conj().transpose(1,0,2)\n                dvvvv[i] = vvv - vvv.transpose(2,1,0)*.5\n\n        gvovv = lib.einsum('adbc,id->aibc', gvvvv, -t1)\n        gvvvv = None\n\n        gvovv += lib.einsum('akic,kb->aibc', fswap['mvoOV'][p0:p1], t1)\n        gvovv -= lib.einsum('akib,kc->aibc', fswap['mvOOv'][p0:p1], t1)\n\n        gvovv += lib.einsum('ja,jibc->aibc', l1[:,p0:p1], t2)\n        gvovv += lib.einsum('ja,jb,ic->aibc', l1[:,p0:p1], t1, t1)\n        gvovv += numpy.einsum('ba,ic->aibc', mvv[:,p0:p1]*.5, t1)\n        gvovv = gvovv.conj()\n        gvovv += lib.einsum('ja,jibc->aibc', t1[:,p0:p1], l2)\n\n        dovvv[:,:,p0:p1] = gvovv.transpose(1,3,0,2)*2 - gvovv.transpose(1,2,0,3)\n        gvvov = None\n        time1 = log.timer_debug1('rdm intermediates pass3 [%d:%d]'%(p0, p1), *time1)\n\n    fswap = None\n    dvvov = None\n    return (h5fobj['dovov'], h5fobj['dvvvv'], h5fobj['doooo'], h5fobj['doovv'],\n            h5fobj['dovvo'], dvvov          , h5fobj['dovvv'], h5fobj['dooov'])\n\ndef make_rdm1(mycc, t1, t2, l1, l2, ao_repr=False):\n    r'''\n    Spin-traced one-particle density matrix in MO basis (the occupied-virtual\n    blocks from the orbital response contribution are not included).\n\n    dm1[p,q] = <q_alpha^\\dagger p_alpha> + <q_beta^\\dagger p_beta>\n\n    The convention of 1-pdm is based on McWeeney's book, Eq (5.4.20).\n    The contraction between 1-particle Hamiltonian and rdm1 is\n    E = einsum('pq,qp', h1, rdm1)\n    '''\n    d1 = _gamma1_intermediates(mycc, t1, t2, l1, l2)\n    return _make_rdm1(mycc, d1, with_frozen=True, ao_repr=ao_repr)\n\ndef make_rdm2(mycc, t1, t2, l1, l2, ao_repr=False):\n    r'''\n    Spin-traced two-particle density matrix in MO basis\n\n    dm2[p,q,r,s] = \\sum_{sigma,tau} <p_sigma^\\dagger r_tau^\\dagger s_tau q_sigma>\n\n    Note the contraction between ERIs (in Chemist's notation) and rdm2 is\n    E = einsum('pqrs,pqrs', eri, rdm2)\n    '''\n    d1 = _gamma1_intermediates(mycc, t1, t2, l1, l2)\n    f = lib.H5TmpFile()\n    d2 = _gamma2_outcore(mycc, t1, t2, l1, l2, f, False)\n    return _make_rdm2(mycc, d1, d2, with_dm1=True, with_frozen=True,\n                      ao_repr=ao_repr)\n\ndef _make_rdm1(mycc, d1, with_frozen=True, ao_repr=False):\n    r'''dm1[p,q] = <q_alpha^\\dagger p_alpha> + <q_beta^\\dagger p_beta>\n\n    The convention of 1-pdm is based on McWeeney's book, Eq (5.4.20).\n    The contraction between 1-particle Hamiltonian and rdm1 is\n    E = einsum('pq,qp', h1, rdm1)\n    '''\n    doo, dov, dvo, dvv = d1\n    nocc, nvir = dov.shape\n    nmo = nocc + nvir\n    dm1 = numpy.empty((nmo,nmo), dtype=doo.dtype)\n    dm1[:nocc,:nocc] = doo + doo.conj().T\n    dm1[:nocc,nocc:] = dov + dvo.conj().T\n    dm1[nocc:,:nocc] = dm1[:nocc,nocc:].conj().T\n    dm1[nocc:,nocc:] = dvv + dvv.conj().T\n    dm1[numpy.diag_indices(nocc)] += 2\n\n    if with_frozen and mycc.frozen is not None:\n        nmo = mycc.mo_occ.size\n        nocc = numpy.count_nonzero(mycc.mo_occ > 0)\n        rdm1 = numpy.zeros((nmo,nmo), dtype=dm1.dtype)\n        rdm1[numpy.diag_indices(nocc)] = 2\n        moidx = numpy.where(mycc.get_frozen_mask())[0]\n        rdm1[moidx[:,None],moidx] = dm1\n        dm1 = rdm1\n\n    if ao_repr:\n        mo = mycc.mo_coeff\n        dm1 = lib.einsum('pi,ij,qj->pq', mo, dm1, mo.conj())\n    return dm1\n\n# Note vvvv part of 2pdm have been symmetrized.  It does not correspond to\n# vvvv part of CI 2pdm\ndef _make_rdm2(mycc, d1, d2, with_dm1=True, with_frozen=True, ao_repr=False):\n    r'''\n    dm2[p,q,r,s] = \\sum_{sigma,tau} <p_sigma^\\dagger r_tau^\\dagger s_tau q_sigma>\n\n    Note the contraction between ERIs (in Chemist's notation) and rdm2 is\n    E = einsum('pqrs,pqrs', eri, rdm2)\n    '''\n    dovov, dvvvv, doooo, doovv, dovvo, dvvov, dovvv, dooov = d2\n    nocc, nvir = dovov.shape[:2]\n    nmo = nocc + nvir\n\n    dm2 = numpy.empty((nmo,nmo,nmo,nmo), dtype=doovv.dtype)\n\n    dovov = numpy.asarray(dovov)\n    dm2[:nocc,nocc:,:nocc,nocc:] = dovov\n    dm2[:nocc,nocc:,:nocc,nocc:]+= dovov.transpose(2,3,0,1)\n    dm2[nocc:,:nocc,nocc:,:nocc] = dm2[:nocc,nocc:,:nocc,nocc:].transpose(1,0,3,2).conj()\n    dovov = None\n\n    doovv = numpy.asarray(doovv)\n    dm2[:nocc,:nocc,nocc:,nocc:] = doovv\n    dm2[:nocc,:nocc,nocc:,nocc:]+= doovv.transpose(1,0,3,2).conj()\n    dm2[nocc:,nocc:,:nocc,:nocc] = dm2[:nocc,:nocc,nocc:,nocc:].transpose(2,3,0,1)\n    doovv = None\n\n    dovvo = numpy.asarray(dovvo)\n    dm2[:nocc,nocc:,nocc:,:nocc] = dovvo\n    dm2[:nocc,nocc:,nocc:,:nocc]+= dovvo.transpose(3,2,1,0).conj()\n    dm2[nocc:,:nocc,:nocc,nocc:] = dm2[:nocc,nocc:,nocc:,:nocc].transpose(1,0,3,2).conj()\n    dovvo = None\n\n    if len(dvvvv.shape) == 2:\n# To handle the case of compressed vvvv, which is used in nuclear gradients\n        dvvvv = ao2mo.restore(1, dvvvv, nvir)\n        dm2[nocc:,nocc:,nocc:,nocc:] = dvvvv\n        dm2[nocc:,nocc:,nocc:,nocc:]*= 4\n    else:\n        dvvvv = numpy.asarray(dvvvv)\n        dm2[nocc:,nocc:,nocc:,nocc:] = dvvvv\n        dm2[nocc:,nocc:,nocc:,nocc:]+= dvvvv.transpose(1,0,3,2).conj()\n        dm2[nocc:,nocc:,nocc:,nocc:]*= 2\n    dvvvv = None\n\n    doooo = numpy.asarray(doooo)\n    dm2[:nocc,:nocc,:nocc,:nocc] = doooo\n    dm2[:nocc,:nocc,:nocc,:nocc]+= doooo.transpose(1,0,3,2).conj()\n    dm2[:nocc,:nocc,:nocc,:nocc]*= 2\n    doooo = None\n\n    dovvv = numpy.asarray(dovvv)\n    dm2[:nocc,nocc:,nocc:,nocc:] = dovvv\n    dm2[nocc:,nocc:,:nocc,nocc:] = dovvv.transpose(2,3,0,1)\n    dm2[nocc:,nocc:,nocc:,:nocc] = dovvv.transpose(3,2,1,0).conj()\n    dm2[nocc:,:nocc,nocc:,nocc:] = dovvv.transpose(1,0,3,2).conj()\n    dovvv = None\n\n    dooov = numpy.asarray(dooov)\n    dm2[:nocc,:nocc,:nocc,nocc:] = dooov\n    dm2[:nocc,nocc:,:nocc,:nocc] = dooov.transpose(2,3,0,1)\n    dm2[:nocc,:nocc,nocc:,:nocc] = dooov.transpose(1,0,3,2).conj()\n    dm2[nocc:,:nocc,:nocc,:nocc] = dooov.transpose(3,2,1,0).conj()\n\n    if with_frozen and mycc.frozen is not None:\n        nmo, nmo0 = mycc.mo_occ.size, nmo\n        nocc = numpy.count_nonzero(mycc.mo_occ > 0)\n        rdm2 = numpy.zeros((nmo,nmo,nmo,nmo), dtype=dm2.dtype)\n        moidx = numpy.where(mycc.get_frozen_mask())[0]\n        idx = (moidx.reshape(-1,1) * nmo + moidx).ravel()\n        lib.takebak_2d(rdm2.reshape(nmo**2,nmo**2),\n                       dm2.reshape(nmo0**2,nmo0**2), idx, idx)\n        dm2 = rdm2\n\n    if with_dm1:\n        dm1 = _make_rdm1(mycc, d1, with_frozen)\n        dm1[numpy.diag_indices(nocc)] -= 2\n\n        for i in range(nocc):\n            dm2[i,i,:,:] += dm1 * 2\n            dm2[:,:,i,i] += dm1 * 2\n            dm2[:,i,i,:] -= dm1\n            dm2[i,:,:,i] -= dm1.T\n\n        for i in range(nocc):\n            for j in range(nocc):\n                dm2[i,i,j,j] += 4\n                dm2[i,j,j,i] -= 2\n\n    # dm2 was computed as dm2[p,q,r,s] = < p^\\dagger r^\\dagger s q > in the\n    # above. Transposing it so that it be contracted with ERIs (in Chemist's\n    # notation):\n    #   E = einsum('pqrs,pqrs', eri, rdm2)\n    dm2 = dm2.transpose(1,0,3,2)\n\n    if ao_repr:\n        dm2 = _rdm2_mo2ao(dm2.transpose(1,0,3,2), mycc.mo_coeff)\n    return dm2\n\n\ndef _rdm2_mo2ao(dm2, mo):\n    mo_C = mo.conj()\n    return lib.einsum('ijkl,pi,qj,rk,sl->pqrs', dm2, mo, mo_C, mo, mo_C)\n\n\nif __name__ == '__main__':\n    from functools import reduce\n    from pyscf import gto\n    from pyscf import scf\n    from pyscf.cc import ccsd\n    from pyscf import ao2mo\n\n    mol = gto.M()\n    mf = scf.RHF(mol)\n    mcc = ccsd.CCSD(mf)\n\n    numpy.random.seed(2)\n    nocc = 5\n    nmo = 12\n    nvir = nmo - nocc\n    eri0 = numpy.random.random((nmo,nmo,nmo,nmo))\n    eri0 = ao2mo.restore(1, ao2mo.restore(8, eri0, nmo), nmo)\n    fock0 = numpy.random.random((nmo,nmo))\n    fock0 = fock0 + fock0.T + numpy.diag(range(nmo))*2\n    t1 = numpy.random.random((nocc,nvir))\n    t2 = numpy.random.random((nocc,nocc,nvir,nvir))\n    t2 = t2 + t2.transpose(1,0,3,2)\n    l1 = numpy.random.random((nocc,nvir))\n    l2 = numpy.random.random((nocc,nocc,nvir,nvir))\n    l2 = l2 + l2.transpose(1,0,3,2)\n    h1 = fock0 - (numpy.einsum('kkpq->pq', eri0[:nocc,:nocc])*2\n                - numpy.einsum('pkkq->pq', eri0[:,:nocc,:nocc]))\n\n    eris = lambda:None\n    eris.oooo = eri0[:nocc,:nocc,:nocc,:nocc].copy()\n    eris.ooov = eri0[:nocc,:nocc,:nocc,nocc:].copy()\n    eris.ovoo = eri0[:nocc,nocc:,:nocc,:nocc].copy()\n    eris.oovv = eri0[:nocc,:nocc,nocc:,nocc:].copy()\n    eris.ovov = eri0[:nocc,nocc:,:nocc,nocc:].copy()\n    eris.ovvo = eri0[:nocc,nocc:,nocc:,:nocc].copy()\n    eris.ovvv = eri0[:nocc,nocc:,nocc:,nocc:].copy()\n    eris.vvvv = eri0[nocc:,nocc:,nocc:,nocc:].copy()\n    eris.fock = fock0\n\n    doo, dov, dvo, dvv = _gamma1_intermediates(mcc, t1, t2, l1, l2)\n    print((numpy.einsum('ij,ij', doo, fock0[:nocc,:nocc]))*2+20166.329861034799)\n    print((numpy.einsum('ab,ab', dvv, fock0[nocc:,nocc:]))*2-58078.964019246778)\n    print((numpy.einsum('ai,ia', dvo, fock0[:nocc,nocc:]))*2+74994.356886784764)\n    print((numpy.einsum('ia,ai', dov, fock0[nocc:,:nocc]))*2-34.010188025702391)\n\n    fdm2 = lib.H5TmpFile()\n    dovov, dvvvv, doooo, doovv, dovvo, dvvov, dovvv, dooov = \\\n            _gamma2_outcore(mcc, t1, t2, l1, l2, fdm2, True)\n    print('dovov', lib.finger(numpy.array(dovov)) - -14384.907042073517)\n    print('dvvvv', lib.finger(numpy.array(dvvvv)) - -25.374007033024839)\n    print('doooo', lib.finger(numpy.array(doooo)) -  60.114594698129963)\n    print('doovv', lib.finger(numpy.array(doovv)) - -79.176348067958401)\n    print('dovvo', lib.finger(numpy.array(dovvo)) -   9.864134457251815)\n    print('dovvv', lib.finger(numpy.array(dovvv)) - -421.90333700061342)\n    print('dooov', lib.finger(numpy.array(dooov)) - -592.66863759586136)\n    fdm2 = None\n\n    dovov, dvvvv, doooo, doovv, dovvo, dvvov, dovvv, dooov = \\\n            _gamma2_intermediates(mcc, t1, t2, l1, l2)\n    print('dovov', lib.finger(numpy.array(dovov)) - -14384.907042073517)\n    print('dvvvv', lib.finger(numpy.array(dvvvv)) -  45.872344902116758)\n    print('doooo', lib.finger(numpy.array(doooo)) -  60.114594698129963)\n    print('doovv', lib.finger(numpy.array(doovv)) - -79.176348067958401)\n    print('dovvo', lib.finger(numpy.array(dovvo)) -   9.864134457251815)\n    print('dovvv', lib.finger(numpy.array(dovvv)) - -421.90333700061342)\n    print('dooov', lib.finger(numpy.array(dooov)) - -592.66863759586136)\n\n    print('doooo',numpy.einsum('kilj,kilj', doooo, eris.oooo)*2-15939.9007625418)\n    print('dvvvv',numpy.einsum('acbd,acbd', dvvvv, eris.vvvv)*2-37581.823919588 )\n    print('dooov',numpy.einsum('jkia,jkia', dooov, eris.ooov)*2-128470.009687716)\n    print('dovvv',numpy.einsum('icba,icba', dovvv, eris.ovvv)*2+166794.225195056)\n    print('dovov',numpy.einsum('iajb,iajb', dovov, eris.ovov)*2+719279.812916893)\n    print('dovvo',numpy.einsum('jbai,jbia', dovvo, eris.ovov)*2\n                 +numpy.einsum('jiab,jiba', doovv, eris.oovv)*2+53634.0012286654)\n\n    dm1 = make_rdm1(mcc, t1, t2, l1, l2)\n    dm2 = make_rdm2(mcc, t1, t2, l1, l2)\n    e2 =(numpy.einsum('ijkl,ijkl', doooo, eris.oooo)*2\n        +numpy.einsum('acbd,acbd', dvvvv, eris.vvvv)*2\n        +numpy.einsum('jkia,jkia', dooov, eris.ooov)*2\n        +numpy.einsum('icba,icba', dovvv, eris.ovvv)*2\n        +numpy.einsum('iajb,iajb', dovov, eris.ovov)*2\n        +numpy.einsum('jbai,jbia', dovvo, eris.ovov)*2\n        +numpy.einsum('ijab,ijab', doovv, eris.oovv)*2\n        +numpy.einsum('ij,ij', doo, fock0[:nocc,:nocc])*2\n        +numpy.einsum('ia,ia', dov, fock0[:nocc,nocc:])*2\n        +numpy.einsum('ai,ai', dvo, fock0[nocc:,:nocc])*2\n        +numpy.einsum('ab,ab', dvv, fock0[nocc:,nocc:])*2\n        +fock0[:nocc].trace()*2\n        -numpy.einsum('kkpq->pq', eri0[:nocc,:nocc,:nocc,:nocc]).trace()*2\n        +numpy.einsum('pkkq->pq', eri0[:nocc,:nocc,:nocc,:nocc]).trace())\n    print(e2+794721.197459942)\n    print(numpy.einsum('pqrs,pqrs', dm2, eri0)*.5 +\n          numpy.einsum('pq,qp', dm1, h1) - e2)\n\n    print(numpy.allclose(dm2, dm2.transpose(1,0,3,2)))\n    print(numpy.allclose(dm2, dm2.transpose(2,3,0,1)))\n\n    d1 = numpy.einsum('kkpq->qp', dm2) / 9\n    print(numpy.allclose(d1, dm1))\n\n    mol = gto.Mole()\n    mol.atom = [\n        [8 , (0. , 0.     , 0.)],\n        [1 , (0. , -0.757 , 0.587)],\n        [1 , (0. , 0.757  , 0.587)]]\n    mol.basis = '631g'\n    mol.build()\n    mf = scf.RHF(mol).run()\n\n    mycc = ccsd.CCSD(mf)\n    mycc.frozen = 2\n    ecc, t1, t2 = mycc.kernel()\n    l1, l2 = mycc.solve_lambda()\n    dm1 = make_rdm1(mycc, t1, t2, l1, l2)\n    dm2 = make_rdm2(mycc, t1, t2, l1, l2)\n    nmo = mf.mo_coeff.shape[1]\n    eri = ao2mo.kernel(mf._eri, mf.mo_coeff, compact=False).reshape([nmo]*4)\n    hcore = mf.get_hcore()\n    h1 = reduce(numpy.dot, (mf.mo_coeff.T, hcore, mf.mo_coeff))\n    e1 = numpy.einsum('ij,ji', h1, dm1)\n    e1+= numpy.einsum('ijkl,ijkl', eri, dm2) * .5\n    e1+= mol.energy_nuc()\n    print(e1 - mycc.e_tot)\n", "meta": {"hexsha": "5d34acef6e08e3399ebe1575c7253c95edf9c487", "size": 21048, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/cc/ccsd_rdm.py", "max_stars_repo_name": "r-peng/pyscf", "max_stars_repo_head_hexsha": "9a14f9bcc63bc75f5939cb4d00eb47861d8d8989", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-30T22:33:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-22T18:02:36.000Z", "max_issues_repo_path": "pyscf/cc/ccsd_rdm.py", "max_issues_repo_name": "r-peng/pyscf", "max_issues_repo_head_hexsha": "9a14f9bcc63bc75f5939cb4d00eb47861d8d8989", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscf/cc/ccsd_rdm.py", "max_forks_repo_name": "r-peng/pyscf", "max_forks_repo_head_hexsha": "9a14f9bcc63bc75f5939cb4d00eb47861d8d8989", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4330708661, "max_line_length": 95, "alphanum_fraction": 0.5906024325, "include": true, "reason": "import numpy", "num_tokens": 8344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.2974699363766585, "lm_q1q2_score": 0.17404999881050573}}
{"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 28 15:19:30 2018\n\n@author:\nDr. Maximilian N. Günther\nEuropean Space Agency (ESA)\nEuropean Space Research and Technology Centre (ESTEC)\nKeplerlaan 1, 2201 AZ Noordwijk, The Netherlands\nEmail: maximilian.guenther@esa.int\nGitHub: mnguenther\nTwitter: m_n_guenther\nWeb: www.mnguenther.com\n\"\"\"\n\nfrom __future__ import print_function, division, absolute_import\n\n#::: plotting settings\nimport seaborn as sns\nsns.set(context='paper', style='ticks', palette='deep', font='sans-serif', font_scale=1.5, color_codes=True)\nsns.set_style({\"xtick.direction\": \"in\",\"ytick.direction\": \"in\"})\nsns.set_context(rc={'lines.markeredgewidth': 1})\n\n#::: modules\nimport os\n#import collections\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import ScalarFormatter\nimport pickle\nfrom corner import corner\nfrom tqdm import tqdm \nfrom astropy.constants import M_earth, M_jup, M_sun, R_earth, R_jup, R_sun, au\nimport copy\nfrom multiprocessing import Pool\nfrom contextlib import closing\n\n#::: allesfitter modules\nfrom . import config\nfrom .utils.latex_printer import round_tex\nfrom .general_output import logprint\nfrom .priors.simulate_PDF import simulate_PDF\nfrom .limb_darkening import LDC3\nfrom .computer import update_params, calculate_model, flux_fct, flux_subfct_ellc, flux_subfct_sinusoidal_phase_curves\nfrom .exoworlds_rdx.lightcurves.index_transits import index_transits\nfrom .lightcurves import get_epoch_occ\n\n\n\n\n###############################################################################\n#::: constants (replaced with astropy.constants)\n###############################################################################\n#M_earth = 5.9742e+24 \t#kg \tEarth mass\n#M_jup   = 1.8987e+27 \t#kg \tJupiter mass\n#M_sun   = 1.9891e+30 \t#kg \tSolar mass\n#R_earth = 6378136      #m \tEarth equatorial radius\n#R_jup   = 71492000 \t#m \tJupiter equatorial radius\n#R_sun   = 695508000 \t#m \tSolar radius\n\n\n\n###############################################################################\n#::: globals\n#::: sorry for that... it's multiprocessing, not me, I swear!\n###############################################################################\n# companion = None\n# inst = None\n# samples2 = None\n# derived_samples = None\n\n\n###############################################################################\n#::: calculate values from model curves\n###############################################################################\ndef calculate_values_from_model_curves(p, inst, companion):\n    '''\n    Parameters\n    ----------\n    p : dict\n        parameters corresponding to one single sample\n    inst : str\n        instrument name\n    companion : str\n        companion name\n\n    Returns\n    -------\n    list\n        list containing the transit depth, occultation depth, and nightside flux\n    '''\n    \n    #==========================================================================\n    #::: init\n    #==========================================================================\n    depth_tr = np.nan\n    depth_occ = np.nan\n    nightside_flux = np.nan\n    epoch_occ = get_epoch_occ(p[companion+'_epoch'], p[companion+'_period'], p[companion+'_f_s'], p[companion+'_f_c'])\n\n\n    #==========================================================================\n    #:: calculating\n    #==========================================================================\n    \n    #::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n    #::: without phase curve\n    #::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n    if (config.BASEMENT.settings['phase_curve'] is False):\n        #::: compute transit / primary eclipse depth\n        depth_tr = 1. - flux_subfct_ellc(p, inst, companion, xx=[p[companion+'_epoch']])[0]\n        \n        #::: compute occultation / secondary eclipse depth (if wished)\n        if (config.BASEMENT.settings['secondary_eclipse'] is True): \n            depth_occ = 1. - flux_subfct_ellc(p, inst, companion, xx=[epoch_occ])[0]\n\n\n    #::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n    #::: with phase curve sine_series or sine_physical\n    #::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n    elif (config.BASEMENT.settings['phase_curve'] is True) and (config.BASEMENT.settings['phase_curve_style'] in ['sine_series','sine_physical']):\n        \n        #::: 0: epoch, 1: epoch_occ\n        xx0 = [p[companion+'_epoch'], epoch_occ]\n        \n        #::: for debugging\n        # xx0 = np.linspace(p[companion+'_epoch']-0.25*p[companion+'_period'], p[companion+'_epoch']+0.75*p[companion+'_period'], 1001)\n        \n        #::: the full model flux with phase curve and dips\n        phase_curve_dips = flux_fct(p, inst, companion, xx=xx0)\n\n        #::: the phase curve without any dips\n        ellc_flux, ellc_flux1, ellc_flux2 = flux_subfct_ellc(p, inst, companion, xx=xx0, return_fluxes=True)\n        phase_curve_no_dips = flux_subfct_sinusoidal_phase_curves(p, inst, companion, np.ones_like(xx0), xx=xx0)\n        \n        #::: the phase curve with atmopsheric dips, but without nightside flux (sbratio=1e-12)\n        p2 = copy.deepcopy(p)\n        p2[companion+'_sbratio_'+inst] = 1e-12\n        ellc_flux, ellc_flux1, ellc_flux2 = flux_subfct_ellc(p2, inst, companion, xx=xx0, return_fluxes=True)\n        phase_curve_atmo_dips = flux_subfct_sinusoidal_phase_curves(p2, inst, companion, ellc_flux2, xx=xx0)\n\n        #::: for debugging\n        # fig = plt.figure()\n        # plt.plot(xx0, phase_curve_dips, label='phase_curve_dips')\n        # plt.plot(xx0, phase_curve_no_dips, label='phase_curve_no_dips')\n        # plt.plot(xx0, phase_curve_atmo_dips, label='phase_curve_atmo_dips')\n        # plt.legend()\n        # plt.ylim([0.999,1.001])\n        # plt.axhline(1,c='grey',ls='--')\n        # fig.savefig(os.path.join(config.BASEMENT.outdir,'phase_curve_depths.pdf'), bbox_inches='tight')\n\n        #::: compute transit / primary eclipse depth\n        depth_tr = 1e3 * (phase_curve_no_dips[0] - phase_curve_dips[0]) #in ppt; 0: epoch\n        \n        #::: compute\n        if (config.BASEMENT.settings['secondary_eclipse'] is True): \n            \n            #::: compute occultation / secondary eclipse depth\n            depth_occ = 1e3 * (phase_curve_no_dips[1] - phase_curve_dips[1]) #in ppt; 1: epoch_occ\n                \n            #::: compute nightside flux\n            nightside_flux = 1e3 * (phase_curve_atmo_dips[1] - phase_curve_dips[1]) #in ppt; 1: epoch_occ\n            \n\n    #::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n    #::: with phase curve ellc_physical\n    #::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n    elif (config.BASEMENT.settings['phase_curve'] is True) and (config.BASEMENT.settings['phase_curve_style'] in ['ellc_physical']):\n        pass #TODO: not yet implemented\n        \n    \n    #==========================================================================\n    #::: return\n    #==========================================================================\n    return [depth_tr, depth_occ, nightside_flux]\n\n\n\n\n###############################################################################\n#::: the main derive function\n###############################################################################\ndef derive(samples, mode):\n    '''\n    Derives parameter of the system using Winn 2010\n    \n    Input:\n    ------\n    samples : array\n        samples from the mcmc or nested sampling\n    mode : str\n        'mcmc' or 'ns'\n        \n    Returns:\n    --------\n    derived_samples : dict \n        with keys 'i', 'R1a', 'R2a', 'k', 'depth_undiluted', 'b_tra', 'b_occ', 'Ttot', 'Tfull'\n        each key contains all the samples derived from the MCMC samples \n        (not mean values, but pure samples!)\n        i = inclination \n        R1a = R1/a, radius companion over semiamplitude\n        R2a = R2/a, radius star over semiamplitude\n        Ttot = T_{1-4}, total transit width \n        Tfull = T_{2-3}, full-transit width\n        \n    Output:\n    -------\n    latex table of results\n    corner plot of derived values posteriors\n    '''\n    \n    #::: using a global keyword \n    #::: sorry for that... it's multiprocessing, not me, I swear!\n    global companion\n    global inst\n    global samples2\n    global derived_samples\n    \n    samples2 = samples #global variable\n    N_samples = samples.shape[0]\n    \n\n    #==========================================================================\n    #::: stellar 'posteriors'\n    #==========================================================================\n    if os.path.exists( os.path.join(config.BASEMENT.datadir,'params_star.csv') ):\n        buf = np.genfromtxt( os.path.join(config.BASEMENT.datadir,'params_star.csv'), delimiter=',', names=True, dtype=None, encoding='utf-8', comments='#' )\n        star = {}\n        star['R_star'] = simulate_PDF(buf['R_star'], buf['R_star_lerr'], buf['R_star_uerr'], size=N_samples, plot=False)\n        star['M_star'] = simulate_PDF(buf['M_star'], buf['M_star_lerr'], buf['M_star_uerr'], size=N_samples, plot=False)\n        star['Teff_star'] = simulate_PDF(buf['Teff_star'], buf['Teff_star_lerr'], buf['Teff_star_uerr'], size=N_samples, plot=False)\n    else:\n        star = {'R_star':np.nan, 'M_star':np.nan, 'Teff_star':np.nan}\n    \n    \n    #==========================================================================\n    #::: derive all the params\n    #==========================================================================\n    companions = config.BASEMENT.settings['companions_all']\n    \n    def get_params(key):\n        ind = np.where(config.BASEMENT.fitkeys==key)[0]\n        if len(ind)==1: \n            return samples[:,ind].flatten() #if it was fitted for\n        else: \n            try:\n                if config.BASEMENT.params[key] is None:\n                    return np.nan #if None, retun nan instead\n                else:\n                    return config.BASEMENT.params[key] #else take the input value\n            except KeyError:\n                return np.nan #if all fails, return nan\n        \n    def sin_d(alpha): return np.sin(np.deg2rad(alpha))\n    def cos_d(alpha): return np.cos(np.deg2rad(alpha))\n    def arcsin_d(x): return np.rad2deg(np.arcsin(x))\n    def arccos_d(x): return np.rad2deg(np.arccos(x))\n\n    derived_samples = {}\n    for cc in companions:\n        companion = cc\n        \n        #----------------------------------------------------------------------\n        #::: radii\n        #----------------------------------------------------------------------\n        derived_samples[companion+'_R_star/a'] = get_params(companion+'_rsuma') / (1. + get_params(companion+'_rr'))\n        derived_samples[companion+'_a/R_star'] = (1. + get_params(companion+'_rr')) / get_params(companion+'_rsuma')\n        derived_samples[companion+'_R_companion/a'] = get_params(companion+'_rsuma') * get_params(companion+'_rr') / (1. + get_params(companion+'_rr'))\n        derived_samples[companion+'_R_companion_(R_earth)'] = star['R_star'] * get_params(companion+'_rr') * R_sun.value / R_earth.value #in R_earth\n        derived_samples[companion+'_R_companion_(R_jup)'] = star['R_star'] * get_params(companion+'_rr') * R_sun.value / R_jup.value #in R_jup\n\n    \n        #----------------------------------------------------------------------\n        #::: orbit\n        #----------------------------------------------------------------------\n        derived_samples[companion+'_a_(R_sun)'] = star['R_star'] / derived_samples[companion+'_R_star/a']   \n        derived_samples[companion+'_a_(AU)'] = derived_samples[companion+'_a_(R_sun)'] * R_sun.value/au.value\n        derived_samples[companion+'_i'] = arccos_d(get_params(companion+'_cosi')) #in deg\n        derived_samples[companion+'_e'] = get_params(companion+'_f_s')**2 + get_params(companion+'_f_c')**2\n        derived_samples[companion+'_e_sinw'] = get_params(companion+'_f_s') * np.sqrt(derived_samples[companion+'_e'])\n        derived_samples[companion+'_e_cosw'] = get_params(companion+'_f_c') * np.sqrt(derived_samples[companion+'_e'])\n        derived_samples[companion+'_w'] = np.rad2deg(np.mod( np.arctan2(get_params(companion+'_f_s'), get_params(companion+'_f_c')), 2*np.pi) ) #in deg, from 0 to 360\n        if np.isnan(derived_samples[companion+'_w']).all():\n            derived_samples[companion+'_w'] = 0.\n        \n        \n        #----------------------------------------------------------------------\n        #::: masses\n        #----------------------------------------------------------------------\n        #::: for detached binaries, where K and q were fitted:\n        if (companion+'_K' in config.BASEMENT.params) and len(config.BASEMENT.settings['inst_rv2'])>0:\n            derived_samples[companion+'_M_companion_(M_earth)'] = get_params(companion+'_q') * star['M_star'] * M_sun.value / M_earth.value #in M_earth\n            derived_samples[companion+'_M_companion_(M_jup)'] = get_params(companion+'_q') * star['M_star'] * M_sun.value / M_jup.value #in M_jup\n            derived_samples[companion+'_M_companion_(M_sun)'] = get_params(companion+'_q') * star['M_star'] #in M_sun\n\n        #::: for exoplanets or single-lined binaries, where only K was fitted, approximate/best-guess q form K:\n        elif companion+'_K' in config.BASEMENT.params:\n            a_1 = 0.019771142 * get_params(companion+'_K') * get_params(companion+'_period') * np.sqrt(1. - derived_samples[companion+'_e']**2)/sin_d(derived_samples[companion+'_i'])\n    #        derived_samples[companion+'_a_rv'] = (1.+1./ellc_params[companion+'_q'])*a_1\n            derived_samples[companion+'_q'] = 1./(( derived_samples[companion+'_a_(R_sun)'] / a_1 ) - 1.)\n            derived_samples[companion+'_M_companion_(M_earth)'] = derived_samples[companion+'_q'] * star['M_star'] * M_sun.value / M_earth.value #in M_earth\n            derived_samples[companion+'_M_companion_(M_jup)'] = derived_samples[companion+'_q'] * star['M_star'] * M_sun.value / M_jup.value #in M_jup\n            derived_samples[companion+'_M_companion_(M_sun)'] = derived_samples[companion+'_q'] * star['M_star'] #in M_sun\n\n            \n        #----------------------------------------------------------------------\n        #::: time of secondary eclipse   \n        #---------------------------------------------------------------------- \n        if config.BASEMENT.settings['secondary_eclipse'] is True:\n            derived_samples[companion+'_epoch_occ'] = get_params(companion+'_epoch') + get_params(companion+'_period')/2. * (1. + 4./np.pi * derived_samples[companion+'_e'] * cos_d(derived_samples[companion+'_w'])  ) #approximation from Winn2010\n        \n        \n        #----------------------------------------------------------------------\n        #::: impact params of primary eclipse with eccentricity corrections (from Winn 2010) \n        #----------------------------------------------------------------------\n        eccentricity_correction_b_tra = ( (1. - derived_samples[companion+'_e']**2) / ( 1. + derived_samples[companion+'_e']*sin_d(derived_samples[companion+'_w']) ) )\n        \n        derived_samples[companion+'_b_tra'] = (1./derived_samples[companion+'_R_star/a']) * get_params(companion+'_cosi') * eccentricity_correction_b_tra\n        \n        \n        #----------------------------------------------------------------------\n        #::: impact params of secondary eclipse with eccentricity corrections (from Winn 2010) \n        #----------------------------------------------------------------------        \n        eccentricity_correction_b_occ = ( (1. - derived_samples[companion+'_e']**2) / ( 1. - derived_samples[companion+'_e']*sin_d(derived_samples[companion+'_w']) ) )\n        \n        if config.BASEMENT.settings['secondary_eclipse'] is True:\n            derived_samples[companion+'_b_occ'] = (1./derived_samples[companion+'_R_star/a']) * get_params(companion+'_cosi') * eccentricity_correction_b_occ\n        \n        \n        #----------------------------------------------------------------------\n        #::: transit duration (in hours) with eccentricity corrections (from Winn 2010) \n        #----------------------------------------------------------------------\n        eccentricity_correction_T_tra = ( np.sqrt(1. - derived_samples[companion+'_e']**2) / ( 1. + derived_samples[companion+'_e']*sin_d(derived_samples[companion+'_w']) ) )\n        \n        derived_samples[companion+'_T_tra_tot'] = get_params(companion+'_period')/np.pi *24.  \\\n                                                  * np.arcsin( derived_samples[companion+'_R_star/a'] \\\n                                                               * np.sqrt( (1. + get_params(companion+'_rr'))**2 - derived_samples[companion+'_b_tra']**2 ) \\\n                                                               / sin_d(derived_samples[companion+'_i']) ) \\\n                                                  * eccentricity_correction_T_tra    #in h\n        derived_samples[companion+'_T_tra_full'] = get_params(companion+'_period')/np.pi *24.  \\\n                                                   * np.arcsin( derived_samples[companion+'_R_star/a'] \\\n                                                                * np.sqrt( (1. - get_params(companion+'_rr'))**2 - derived_samples[companion+'_b_tra']**2  )\\\n                                                                / sin_d(derived_samples[companion+'_i']) ) \\\n                                                   * eccentricity_correction_T_tra    #in h\n                                  \n        \n        #----------------------------------------------------------------------\n        #::: primary and secondary eclipse depths (per inst) \n        #::: / transit and occultation depths (per inst)\n        #----------------------------------------------------------------------\n        for ii in config.BASEMENT.settings['inst_phot']:\n            \n            \n            #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n            #::: setup\n            #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n            inst = ii\n            N_less_samples = 1000\n            derived_samples[companion+'_depth_tr_dil_'+inst] = np.nan*np.empty(N_less_samples)\n            derived_samples[companion+'_depth_occ_dil_'+inst] = np.nan*np.empty(N_less_samples)\n            derived_samples[companion+'_nightside_flux_dil_'+inst] = np.nan*np.empty(N_less_samples)\n\n            \n            #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n            #::: iterate through all samples, draw different models and measure the depths\n            #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n            print('Deriving eclipse depths (and more) from the model curves for companion', companion, 'and instrument', inst+'...')\n            for i in range(N_less_samples):\n                s = samples[ np.random.randint(low=0,high=samples2.shape[0]) , : ]\n                p = update_params(s)\n                r = calculate_values_from_model_curves(p, inst, companion)\n                derived_samples[companion+'_depth_tr_dil_'+inst][i] = r[0]\n                derived_samples[companion+'_depth_occ_dil_'+inst][i] = r[1]\n                derived_samples[companion+'_nightside_flux_dil_'+inst][i] = r[2]\n                \n            \n            #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n            #resize the arrays to match the true N_samples (by redrawing the 1000 values)\n            #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n            derived_samples[companion+'_depth_tr_dil_'+inst] = np.resize(derived_samples[companion+'_depth_tr_dil_'+inst], N_samples)\n            derived_samples[companion+'_depth_occ_dil_'+inst] = np.resize(derived_samples[companion+'_depth_occ_dil_'+inst], N_samples)\n            derived_samples[companion+'_nightside_flux_dil_'+inst] = np.resize(derived_samples[companion+'_nightside_flux_dil_'+inst], N_samples)\n        \n    \n        #----------------------------------------------------------------------\n        #::: undiluted (per companion; per inst)\n        #----------------------------------------------------------------------\n        for inst in config.BASEMENT.settings['inst_phot']:\n            dil = get_params('dil_'+inst)\n            if all(np.atleast_1d(np.isnan(dil))): dil = 0\n            derived_samples[companion+'_depth_tr_undil_'+inst] = derived_samples[companion+'_depth_tr_dil_'+inst] / (1. - dil) #in ppt\n            derived_samples[companion+'_depth_occ_undil_'+inst] = derived_samples[companion+'_depth_occ_dil_'+inst] / (1. - dil) #in ppt\n            derived_samples[companion+'_nightside_flux_undil_'+inst] = derived_samples[companion+'_nightside_flux_dil_'+inst] / (1. - dil) #in ppt\n        \n        \n        #----------------------------------------------------------------------\n        #::: equilibirum temperature\n        #::: currently assumes Albedo of 0.3 and Emissivity of 1\n        #----------------------------------------------------------------------\n        albedo = 0.3\n        emissivity = 1.\n        derived_samples[companion+'_Teq'] = star['Teff_star']  * ( (1.-albedo)/emissivity )**0.25 * np.sqrt(derived_samples[companion+'_R_star/a'] / 2.)\n        \n        \n        #----------------------------------------------------------------------\n        #::: stellar density from orbit\n        #----------------------------------------------------------------------\n        if companion in config.BASEMENT.settings['companions_phot']:\n            if all(np.atleast_1d(get_params(companion+'_rr'))<0.215443469): #see computer.py; get_params could return np.nan (float) or array; all(np.atleast_1d(...)) takes care of that\n                derived_samples[companion+'_host_density'] = 3. * np.pi * (1./derived_samples[companion+'_R_star/a'])**3. / (get_params(companion+'_period')*86400.)**2 / 6.67408e-8 #in cgs\n  \n    \n        #----------------------------------------------------------------------\n        #::: companion densities\n        #----------------------------------------------------------------------\n        derived_samples[companion+'_density'] = ( (derived_samples[companion+'_M_companion_(M_earth)'] * M_earth) / (4./3. * np.pi * (derived_samples[companion+'_R_companion_(R_earth)'] * R_earth)**3 ) ).cgs.value #in cgs\n        \n        \n        #----------------------------------------------------------------------\n        #::: the companion's surface gravity (individual posterior distribution for each companion; via Southworth+ 2007)\n        #----------------------------------------------------------------------\n        try:\n            derived_samples[companion+'_surface_gravity'] = 2. * np.pi / (get_params(companion+'_period')*86400.) * np.sqrt((1.-derived_samples[companion+'_e']**2)) * (get_params(companion+'_K')*1e5) / (derived_samples[companion+'_R_companion/a'])**2 / sin_d(derived_samples[companion+'_i'])\n        except:\n            pass\n        \n        \n        #----------------------------------------------------------------------\n        #::: period ratios (for ressonance studies)\n        #----------------------------------------------------------------------\n        if len(companions)>1:\n            for other_companion in companions:\n                if other_companion is not companion:\n                    derived_samples[companion+'_period/'+other_companion+'_period'] = get_params(companion+'_period') / get_params(other_companion+'_period')\n                        \n                    \n        #----------------------------------------------------------------------\n        #::: limb darkening\n        #----------------------------------------------------------------------\n        for inst in config.BASEMENT.settings['inst_all']:\n            \n            #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n            #::: host\n            #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n            if config.BASEMENT.settings['host_ld_law_'+inst] is None:\n                pass\n                \n            elif config.BASEMENT.settings['host_ld_law_'+inst] == 'lin':\n                derived_samples['host_ldc_u1_'+inst] = get_params('host_ldc_q1_'+inst)\n                \n            elif config.BASEMENT.settings['host_ld_law_'+inst] == 'quad':\n                derived_samples['host_ldc_u1_'+inst] = 2 * np.sqrt(get_params('host_ldc_q1_'+inst)) * get_params('host_ldc_q2_'+inst)\n                derived_samples['host_ldc_u2_'+inst] = np.sqrt(get_params('host_ldc_q1_'+inst)) * (1. - 2. * get_params('host_ldc_q2_'+inst))\n                \n            elif config.BASEMENT.settings['host_ld_law_'+inst] == 'sing':\n                derived_samples['host_ldc_u1_'+inst] = np.nan*np.empty(N_samples)\n                derived_samples['host_ldc_u2_'+inst] = np.nan*np.empty(N_samples)\n                derived_samples['host_ldc_u3_'+inst] = np.nan*np.empty(N_samples)\n                for i in range(N_samples):\n                    u1, u2, u3 = LDC3.forward([get_params('host_ldc_q1_'+inst)[i], get_params('host_ldc_q2_'+inst)[i], get_params('host_ldc_q3_'+inst)[i]])\n                    derived_samples['host_ldc_u1_'+inst][i] = u1\n                    derived_samples['host_ldc_u2_'+inst][i] = u2\n                    derived_samples['host_ldc_u3_'+inst][i] = u3\n                \n            else:\n                raise ValueError(\"Currently only 'none', 'lin', 'quad' and 'sing' limb darkening are supported.\")\n            \n        \n    #==========================================================================\n    #::: median stellar density\n    #==========================================================================\n    derived_samples['combined_host_density'] = []\n    for companion in config.BASEMENT.settings['companions_phot']:\n        try: derived_samples['combined_host_density'] = np.append(derived_samples['combined_host_density'], derived_samples[companion+'_host_density'])\n        except: pass\n    \n\n    \n    ###############################################################################\n    #::: write keys for output\n    ###############################################################################\n    names = []\n    labels = []\n    for companion in companions:\n            \n        names.append( companion+'_R_star/a' )\n        labels.append( 'Host radius over semi-major axis '+companion+'; $R_\\star/a_\\mathrm{'+companion+'}$' )\n        \n        names.append( companion+'_a/R_star' )\n        labels.append( 'Semi-major axis '+companion+' over host radius; $a_\\mathrm{'+companion+'}/R_\\star$' )\n        \n        names.append( companion+'_R_companion/a'  )\n        labels.append( 'Companion radius '+companion+' over semi-major axis '+companion+'; $R_\\mathrm{'+companion+'}/a_\\mathrm{'+companion+'}$' )\n        \n        names.append( companion+'_R_companion_(R_earth)' )\n        labels.append( 'Companion radius '+companion+'; $R_\\mathrm{'+companion+'}$ ($\\mathrm{R_{\\oplus}}$)' )\n        \n        names.append( companion+'_R_companion_(R_jup)' )\n        labels.append( 'Companion radius '+companion+'; $R_\\mathrm{'+companion+'}$ ($\\mathrm{R_{jup}}$)' )\n        \n        names.append( companion+'_a_(R_sun)' )\n        labels.append( 'Semi-major axis '+companion+'; $a_\\mathrm{'+companion+'}$ ($\\mathrm{R_{\\odot}}$)' )\n        \n        names.append( companion+'_a_(AU)' )\n        labels.append( 'Semi-major axis '+companion+'; $a_\\mathrm{'+companion+'}$ (AU)' )\n        \n        names.append( companion+'_i' )\n        labels.append( 'Inclination '+companion+'; $i_\\mathrm{'+companion+'}$ (deg)' )\n        \n        names.append( companion+'_e' )\n        labels.append( 'Eccentricity '+companion+'; $e_\\mathrm{'+companion+'}$' )\n        \n        names.append( companion+'_w' )\n        labels.append( 'Argument of periastron '+companion+'; $w_\\mathrm{'+companion+'}$ (deg)' )\n        \n        names.append( companion+'_q' )\n        labels.append( 'Mass ratio '+companion+'; $q_\\mathrm{'+companion+'}$' )\n        \n        names.append( companion+'_M_companion_(M_earth)' )\n        labels.append( 'Companion mass '+companion+'; $M_\\mathrm{'+companion+'}$ ($\\mathrm{M_{\\oplus}}$)' )\n        \n        names.append( companion+'_M_companion_(M_jup)' )\n        labels.append( 'Companion mass '+companion+'; $M_\\mathrm{'+companion+'}$ ($\\mathrm{M_{jup}}$)' )\n        \n        names.append( companion+'_M_companion_(M_sun)' )\n        labels.append( 'Companion mass '+companion+'; $M_\\mathrm{'+companion+'}$ ($\\mathrm{M_{\\odot}}$)' )\n        \n        names.append( companion+'_b_tra' )\n        labels.append( 'Impact parameter '+companion+'; $b_\\mathrm{tra;'+companion+'}$' )\n        \n        names.append( companion+'_T_tra_tot'  )\n        labels.append( 'Total transit duration '+companion+'; $T_\\mathrm{tot;'+companion+'}$ (h)' )\n        \n        names.append( companion+'_T_tra_full' )\n        labels.append( 'Full-transit duration '+companion+'; $T_\\mathrm{full;'+companion+'}$ (h)' )\n        \n        names.append( companion+'_epoch_occ'  )\n        labels.append( 'Epoch occultation '+companion+'; $T_\\mathrm{0;occ;'+companion+'}$' )\n        \n        names.append( companion+'_b_occ'  )\n        labels.append( 'Impact parameter occultation '+companion+'; $b_\\mathrm{occ;'+companion+'}$' )\n        \n        names.append( companion+'_host_density' )\n        labels.append( 'Host density from orbit '+companion+'; $\\\\rho_\\mathrm{\\star;'+companion+'}$ (cgs)' )\n    \n        names.append( companion+'_density' )\n        labels.append( 'Companion density '+companion+'; $\\\\rho_\\mathrm{'+companion+'}$ (cgs)' )\n        \n        names.append( companion+'_surface_gravity')\n        labels.append( 'Companion surface gravity '+companion+'; $g_\\mathrm{'+companion+'}$ (cgs)' )\n        \n        names.append( companion+'_Teq' )\n        labels.append( 'Equilibrium temperature '+companion+'; $T_\\mathrm{eq;'+companion+'}$ (K)' )\n        \n        for inst in config.BASEMENT.settings['inst_phot']:\n            \n            names.append( companion+'_depth_tr_undil_'+inst )\n            labels.append( 'Transit depth (undil.) '+companion+'; $\\delta_\\mathrm{tr; undil; '+companion+'; '+inst+'}$ (ppt)' )\n            \n            names.append( companion+'_depth_tr_dil_'+inst )\n            labels.append( 'Transit depth (dil.) '+companion+'; $\\delta_\\mathrm{tr; dil; '+companion+'; '+inst+'}$ (ppt)' )\n        \n            names.append( companion+'_depth_occ_undil_'+inst )\n            labels.append( 'Occultation depth (undil.) '+companion+'; $\\delta_\\mathrm{occ; undil; '+companion+'; '+inst+'}$ (ppt)' )\n            \n            names.append( companion+'_depth_occ_dil_'+inst )\n            labels.append( 'Occultation depth (dil.) '+companion+'; $\\delta_\\mathrm{occ; dil; '+companion+'; '+inst+'}$ (ppt)' )\n            \n            names.append( companion+'_nightside_flux_undil_'+inst )\n            labels.append( 'Nightside flux (undil.)'+companion+'; $F_\\mathrm{nightside; undil; '+companion+'; '+inst+'}$ (ppt)' )\n            \n            names.append( companion+'_nightside_flux_dil_'+inst )\n            labels.append( 'Nightside flux (dil.)'+companion+'; $F_\\mathrm{nightside; dil; '+companion+'; '+inst+'}$ (ppt)' )\n            \n            \n            \n        #::: period ratios (for ressonance studies)\n        if len(companions)>1:\n            for other_companion in companions:\n                if other_companion is not companion:\n                    names.append( companion+'_period/'+other_companion+'_period' )\n                    labels.append( 'Period ratio; $P_\\mathrm{'+companion+'} / P_\\mathrm{'+other_companion+'}$' )\n           \n            \n    #::: host\n    for inst in config.BASEMENT.settings['inst_all']:    \n        if config.BASEMENT.settings['host_ld_law_'+inst] is None:\n            pass\n            \n        elif config.BASEMENT.settings['host_ld_law_'+inst] == 'lin':\n            names.append( 'host_ldc_u1_'+inst )\n            labels.append( 'Limb darkening; $u_\\mathrm{1; '+inst+'}$' )\n            \n        elif config.BASEMENT.settings['host_ld_law_'+inst] == 'quad':\n            names.append( 'host_ldc_u1_'+inst )\n            labels.append( 'Limb darkening; $u_\\mathrm{1; '+inst+'}$' )\n            names.append( 'host_ldc_u2_'+inst )\n            labels.append( 'Limb darkening; $u_\\mathrm{2; '+inst+'}$' )\n            \n        elif config.BASEMENT.settings['host_ld_law_'+inst] == 'sing':\n            names.append( 'host_ldc_u1_'+inst )\n            labels.append( 'Limb darkening; $u_\\mathrm{1; '+inst+'}$' )\n            names.append( 'host_ldc_u2_'+inst )\n            labels.append( 'Limb darkening; $u_\\mathrm{2; '+inst+'}$' )\n            names.append( 'host_ldc_u3_'+inst )\n            labels.append( 'Limb darkening; $u_\\mathrm{3; '+inst+'}$' )\n            \n        else:\n            raise ValueError(\"Currently only 'none', 'lin', 'quad' and 'sing' limb darkening are supported.\")\n                \n        \n    names.append( 'combined_host_density' )\n    labels.append( 'Combined host density from all orbits; $rho_\\mathrm{\\star; combined}$ (cgs)' )\n        \n            \n    ###############################################################################\n    #::: delete pointless values\n    ###############################################################################\n    ind_good = []\n    for i,name in enumerate(names):\n        if (name in derived_samples) and isinstance(derived_samples[name], np.ndarray) and not all(np.isnan(derived_samples[name])) and not all(np.array(derived_samples[name])==0):\n            ind_good.append(i)\n            \n    names = [ names[i] for i in ind_good ]\n    labels = [ labels[i] for i in ind_good ]\n    \n    \n    ###############################################################################\n    #::: if any meaningful values are left, go output them\n    ###############################################################################\n    if len(names)>0:\n            \n        #=====================================================================\n        #::: save all in pickle\n        #=====================================================================\n        pickle.dump(derived_samples, open(os.path.join(config.BASEMENT.outdir,mode+'_derived_samples.pickle'),'wb'))\n        \n        \n        #=====================================================================\n        #::: save txt & latex table & latex commands\n        #=====================================================================\n        with open(os.path.join(config.BASEMENT.outdir,mode+'_derived_table.csv'),'w') as outfile,\\\n             open(os.path.join(config.BASEMENT.outdir,mode+'_derived_latex_table.txt'),'w') as f,\\\n             open(os.path.join(config.BASEMENT.outdir,mode+'_derived_latex_cmd.txt'),'w') as f_cmd:\n                 \n            outfile.write('#property,value,lower_error,upper_error,source\\n')\n            \n            f.write('Parameter & Value & Source \\\\\\\\ \\n')\n            f.write('\\\\hline \\n')\n            f.write('\\\\multicolumn{3}{c}{\\\\textit{Derived parameters}} \\\\\\\\ \\n')\n            f.write('\\\\hline \\n')\n            \n            for name,label in zip(names, labels):\n                ll, median, ul = np.nanpercentile(derived_samples[name], [15.865, 50., 84.135])\n                outfile.write( str(label)+','+str(median)+','+str(median-ll)+','+str(ul-median)+',derived\\n' )\n                \n                value = round_tex(median, median-ll, ul-median)\n                f.write( label + ' & $' + value + '$ & derived \\\\\\\\ \\n' )\n                \n                simplename = name.replace(\"_\", \"\").replace(\"/\", \"over\").replace(\"(\", \"\").replace(\")\", \"\").replace(\"1\", \"one\").replace(\"2\", \"two\")\n                f_cmd.write('\\\\newcommand{\\\\'+simplename+'}{$'+value+'$} %'+label+' = $'+value+'$\\n')\n                \n        logprint('\\nSaved '+mode+'_derived_results.csv, '+mode+'_derived_latex_table.txt, and '+mode+'_derived_latex_cmd.txt')\n        \n            \n        #=====================================================================\n        #::: plot corner\n        #=====================================================================\n        if 'combined_host_density' in names: names.remove('combined_host_density') #has (N_companions x N_dims) dimensions, thus does not match the rest\n        \n        #::: clean up any isolated NaN's before calling corner\n        for name in names:\n            median = np.nanmedian(derived_samples[name])\n            ind = np.where(np.isnan(derived_samples[name]))\n            derived_samples[name][ind] = median\n\n        #::: prep the matrix for corner\n        x = np.column_stack([ derived_samples[name] for name in names ])\n        fontsize = np.min(( 24. + 0.5*(len(names)), 40 ))\n        \n        fig = corner(x,\n                     range = [0.999]*len(names),\n                     labels = names,\n                     quantiles=[0.15865, 0.5, 0.84135],\n                     show_titles=True, \n                     label_kwargs={\"fontsize\":fontsize, \"rotation\":45, \"horizontalalignment\":'right'},\n                     max_n_ticks=3)\n        caxes = np.reshape(np.array(fig.axes), (len(names),len(names)))\n        \n        #::: set allesfitter titles\n        for i, name in enumerate(names): \n            \n            ll, median, ul = np.nanpercentile(derived_samples[name], [15.865, 50., 84.135])\n            value = round_tex(median, median-ll, ul-median)\n            ctitle = r'' + labels[i] + '\\n' + r'$=' + value + '$'\n            if len(names)>1:\n                # caxes[i,i].set_title(ctitle)\n                caxes[i,i].set_title(ctitle, fontsize=fontsize, rotation=45, horizontalalignment='left')\n                for i in range(caxes.shape[0]):\n                    for j in range(caxes.shape[1]):\n                        caxes[i,j].xaxis.set_label_coords(0.5, -0.5)\n                        caxes[i,j].yaxis.set_label_coords(-0.5, 0.5)\n            \n                        if i==(caxes.shape[0]-1): \n                            fmt = ScalarFormatter(useOffset=False)\n                            caxes[i,j].xaxis.set_major_formatter(fmt)\n                        if (i>0) and (j==0):\n                            fmt = ScalarFormatter(useOffset=False)\n                            caxes[i,j].yaxis.set_major_formatter(fmt)\n                            \n                        for tick in caxes[i,j].xaxis.get_major_ticks(): tick.label.set_fontsize(24) \n                        for tick in caxes[i,j].yaxis.get_major_ticks(): tick.label.set_fontsize(24)    \n            else:\n                caxes.set_title(ctitle)\n                caxes.xaxis.set_label_coords(0.5, -0.5)\n                caxes.yaxis.set_label_coords(-0.5, 0.5)\n        \n        dpi = np.max(( 100. - len(names), 50 ))\n        try: #some matplitlib versions cannot handle jpg\n            fig.savefig( os.path.join(config.BASEMENT.outdir,mode+'_derived_corner.jpg'), dpi=dpi, bbox_inches='tight' )\n        except:\n            fig.savefig( os.path.join(config.BASEMENT.outdir,mode+'_derived_corner.png'), bbox_inches='tight' )\n        plt.close(fig)\n        \n        \n        #=====================================================================\n        #::: finish\n        #=====================================================================\n        logprint('\\nSaved '+mode+'_derived_corner.pdf')\n        \n        \n    else:\n        logprint('\\nNo values available to be derived.')\n        \n        ", "meta": {"hexsha": "24a497b3bf8cf6d3f153220a4d0216c706574902", "size": 39488, "ext": "py", "lang": "Python", "max_stars_repo_path": "allesfitter/deriver.py", "max_stars_repo_name": "pierfra-ro/allesfitter", "max_stars_repo_head_hexsha": "a6a885aaeb3253fec0d924ef3b45e8b7c473b181", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "allesfitter/deriver.py", "max_issues_repo_name": "pierfra-ro/allesfitter", "max_issues_repo_head_hexsha": "a6a885aaeb3253fec0d924ef3b45e8b7c473b181", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "allesfitter/deriver.py", "max_forks_repo_name": "pierfra-ro/allesfitter", "max_forks_repo_head_hexsha": "a6a885aaeb3253fec0d924ef3b45e8b7c473b181", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.652173913, "max_line_length": 291, "alphanum_fraction": 0.5058245543, "include": true, "reason": "import numpy,from astropy", "num_tokens": 9181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.17398464304014738}}
{"text": "#   Copyright 2020 The PyMC Developers\n#\n#   Licensed under the Apache License, Version 2.0 (the \"License\");\n#   you may not use this file except in compliance with the License.\n#   You may obtain a copy of the License at\n#\n#       http://www.apache.org/licenses/LICENSE-2.0\n#\n#   Unless required by applicable law or agreed to in writing, software\n#   distributed under the License is distributed on an \"AS IS\" BASIS,\n#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#   See the License for the specific language governing permissions and\n#   limitations under the License.\n\nimport warnings\n\nfrom collections import OrderedDict\n\nimport theano\nimport theano.tensor as tt\n\nfrom pymc3.model import inputvars, modelcontext\nfrom pymc3.step_methods.arraystep import ArrayStepShared\nfrom pymc3.theanof import make_shared_replacements, tt_rng\n\n__all__ = []\n\nEXPERIMENTAL_WARNING = (\n    \"Warning: Stochastic Gradient based sampling methods are experimental step methods and not yet\"\n    \" recommended for use in PyMC3!\"\n)\n\n\ndef _value_error(cond, str):\n    \"\"\"Throws ValueError if cond is False\"\"\"\n    if not cond:\n        raise ValueError(str)\n\n\ndef _check_minibatches(minibatch_tensors, minibatches):\n    _value_error(isinstance(minibatch_tensors, list), \"minibatch_tensors must be a list.\")\n\n    _value_error(hasattr(minibatches, \"__iter__\"), \"minibatches must be an iterator.\")\n\n\ndef prior_dlogp(vars, model, flat_view):\n    \"\"\"Returns the gradient of the prior on the parameters as a vector of size D x 1\"\"\"\n    terms = tt.concatenate([theano.grad(var.logpt, var).flatten() for var in vars], axis=0)\n    dlogp = theano.clone(terms, flat_view.replacements, strict=False)\n\n    return dlogp\n\n\ndef elemwise_dlogL(vars, model, flat_view):\n    \"\"\"\n    Returns Jacobian of the log likelihood for each training datum wrt vars\n    as a matrix of size N x D\n    \"\"\"\n    # select one observed random variable\n    obs_var = model.observed_RVs[0]\n    # tensor of shape (batch_size,)\n    logL = obs_var.logp_elemwiset.sum(axis=tuple(range(1, obs_var.logp_elemwiset.ndim)))\n    # calculate fisher information\n    terms = []\n    for var in vars:\n        output, _ = theano.scan(\n            lambda i, logX=logL, v=var: theano.grad(logX[i], v).flatten(),\n            sequences=[tt.arange(logL.shape[0])],\n        )\n        terms.append(output)\n    dlogL = theano.clone(tt.concatenate(terms, axis=1), flat_view.replacements, strict=False)\n    return dlogL\n\n\nclass BaseStochasticGradient(ArrayStepShared):\n    R\"\"\"\n    BaseStochasticGradient Object\n\n    For working with BaseStochasticGradient Object\n    we need to supply the probabilistic model\n    (:code:`model`) with the data supplied to observed\n    variables of type `GeneratorOp`\n\n    Parameters\n    ----------\n    vars: list\n        List of variables for sampler\n    batch_size`: int\n        Batch Size for each step\n    total_size: int\n        Total size of the training data\n    step_size: float\n        Step size for the parameter update\n    model: PyMC Model\n        Optional model for sampling step. Defaults to None (taken from context)\n    random_seed: int\n        The seed to initialize the Random Stream\n    minibatches: iterator\n        If the ObservedRV.observed is not a GeneratorOp then this parameter must not be None\n    minibatch_tensor: list of tensors\n        If the ObservedRV.observed is not a GeneratorOp then this parameter must not be None\n        The length of this tensor should be the same as the next(minibatches)\n\n    Notes\n    -----\n    Defining a BaseStochasticGradient needs\n    custom implementation of the following methods:\n        - :code: `.mk_training_fn()`\n            Returns a theano function which is called for each sampling step\n        - :code: `._initialize_values()`\n            Returns None it creates class variables which are required for the training fn\n    \"\"\"\n\n    def __init__(\n        self,\n        vars=None,\n        batch_size=None,\n        total_size=None,\n        step_size=1.0,\n        model=None,\n        random_seed=None,\n        minibatches=None,\n        minibatch_tensors=None,\n        **kwargs\n    ):\n        warnings.warn(EXPERIMENTAL_WARNING)\n\n        model = modelcontext(model)\n\n        if vars is None:\n            vars = model.vars\n\n        vars = inputvars(vars)\n\n        self.model = model\n        self.vars = vars\n        self.batch_size = batch_size\n        self.total_size = total_size\n        _value_error(\n            total_size != None or batch_size != None,\n            \"total_size and batch_size of training data have to be specified\",\n        )\n        self.expected_iter = int(total_size / batch_size)\n\n        # set random stream\n        self.random = None\n        if random_seed is None:\n            self.random = tt_rng()\n        else:\n            self.random = tt_rng(random_seed)\n\n        self.step_size = step_size\n\n        shared = make_shared_replacements(vars, model)\n\n        self.updates = OrderedDict()\n        self.q_size = int(sum(v.dsize for v in self.vars))\n\n        flat_view = model.flatten(vars)\n        self.inarray = [flat_view.input]\n\n        self.dlog_prior = prior_dlogp(vars, model, flat_view)\n        self.dlogp_elemwise = elemwise_dlogL(vars, model, flat_view)\n        self.q_size = int(sum(v.dsize for v in self.vars))\n\n        if minibatch_tensors != None:\n            _check_minibatches(minibatch_tensors, minibatches)\n            self.minibatches = minibatches\n\n            # Replace input shared variables with tensors\n            def is_shared(t):\n                return isinstance(t, theano.compile.sharedvalue.SharedVariable)\n\n            tensors = [(t.type() if is_shared(t) else t) for t in minibatch_tensors]\n            updates = OrderedDict(\n                {t: t_ for t, t_ in zip(minibatch_tensors, tensors) if is_shared(t)}\n            )\n            self.minibatch_tensors = tensors\n            self.inarray += self.minibatch_tensors\n            self.updates.update(updates)\n\n        self._initialize_values()\n        super().__init__(vars, shared)\n\n    def _initialize_values(self):\n        \"\"\"Initializes the parameters for the stochastic gradient minibatch\n        algorithm\"\"\"\n        raise NotImplementedError\n\n    def mk_training_fn(self):\n        raise NotImplementedError\n\n    def training_complete(self):\n        \"\"\"Returns boolean if astep has been called expected iter number of times\"\"\"\n        return self.expected_iter == self.t\n\n    def astep(self, q0):\n        \"\"\"Perform a single update in the stochastic gradient method.\n\n        Returns new shared values and values sampled\n        The size and ordering of q0 and q must be the same\n        Parameters\n        -------\n        q0: list\n            List of shared values and values sampled from last estimate\n\n        Returns\n        -------\n        q\n        \"\"\"\n        if hasattr(self, \"minibatch_tensors\"):\n            return q0 + self.training_fn(q0, *next(self.minibatches))\n        else:\n            return q0 + self.training_fn(q0)\n", "meta": {"hexsha": "1620f21b0e89df539f27110dc8600df7d4de8cff", "size": 6998, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymc3/step_methods/sgmcmc.py", "max_stars_repo_name": "mcnoat/pymc3", "max_stars_repo_head_hexsha": "8b1f64cce32db3357301b88bbe9f7108733ac70a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-26T10:13:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-21T15:45:20.000Z", "max_issues_repo_path": "pymc3/step_methods/sgmcmc.py", "max_issues_repo_name": "mcnoat/pymc3", "max_issues_repo_head_hexsha": "8b1f64cce32db3357301b88bbe9f7108733ac70a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-11-27T00:11:53.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-27T00:42:36.000Z", "max_forks_repo_path": "pymc3/step_methods/sgmcmc.py", "max_forks_repo_name": "mcnoat/pymc3", "max_forks_repo_head_hexsha": "8b1f64cce32db3357301b88bbe9f7108733ac70a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-11-03T01:15:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T12:26:45.000Z", "avg_line_length": 32.5488372093, "max_line_length": 99, "alphanum_fraction": 0.6591883395, "include": true, "reason": "import theano,from pymc3", "num_tokens": 1569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.17398463901006478}}
{"text": "#This software is Copyright 2012 The Regents of the University of California. All Rights Reserved.\n#Permission to use, copy, modify, and distribute this software and its documentation for educational, research and non-profit purposes for non-profit institutions, without fee, and without a written agreement is hereby granted, provided that the above copyright notice, this paragraph and the following three paragraphs appear in all copies.\n#Permission to make commercial use of this software may be obtained by contacting:\n#Technology Transfer Office\n#9500 Gilman Drive, Mail Code 0910\n#University of California\n#La Jolla, CA 92093-0910\n#(858) 534-5815\n#invent@ucsd.edu\n#This software program and documentation are copyrighted by The Regents of the University of California. The software program and documentation are supplied \"as is\", without any accompanying services from The Regents. The Regents does not warrant that the operation of the program will be uninterrupted or error-free. The end-user understands that the program was developed for research purposes and is advised not to rely exclusively on the program for any reason.\n#IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO\n#ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR\n#CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING\n#OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,\n#EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF\n#THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF\n#CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,\n#INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n#MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n#THE SOFTWARE PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO\n#PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR\n#MODIFICATIONS.\n\n# Functions for comparing contours\n\nfrom numpy import *\nfrom geometry import *\nfrom point_set import *\n\n\ndef biggestGap(contour1, contour2):\n    \"\"\"See Hausdorff distance.\"\"\"\n\n    biggestGapValue = 0\n\n    locations1 = contour1.locations()\n    locations2 = contour2.locations()\n\n    for index1 in range(len(locations1)):\n        point1 = array(locations1[index1])\n\n        # the minimum distance represents the gap from point1 to point2\n\n        # initialize gap\n        gap = distance(point1, array(locations2[0]))\n\n        # find the minimum\n        #print \"find the minimum\"\n        for coordList2 in locations2:\n            point2 = array(coordList2)\n            dist = distance(point1, point2)\n            #print dist\n            if dist < gap:\n                gap = dist\n\n        # if the gap is the largest found so far, keep it\n        if gap > biggestGapValue:\n            biggestGapValue = gap\n\n    return biggestGapValue\n\n\ndef overlap_old(contour1, contour2):\n    \"\"\"Deprecated\"\"\"\n\n    temp1 = zeros((1000, 1000), dtype=int8)\n    temp2 = zeros((1000, 1000), dtype=int8)\n\n    binaryImage1 = contour1.binaryImage\n    binaryImage2 = contour2.binaryImage\n\n    boundingBox1 = contour1.get2DBoundingBox()\n    boundingBox2 = contour2.get2DBoundingBox()\n\n    temp1[boundingBox1[0][0]:boundingBox1[1][0]+1,\n          boundingBox1[0][1]:boundingBox1[1][1]+1] = binaryImage1\n\n    temp2[boundingBox2[0][0]:boundingBox2[1][0]+1,\n          boundingBox2[0][1]:boundingBox2[1][1]+1] = binaryImage2\n\n    andImage = logical_and(temp1, temp2) * 1\n    orImage = logical_or(temp1, temp2) * 1\n    fraction = float(sum(andImage)) / float(sum(orImage))\n\n    return fraction\n\n\ndef overlap(contour1, contour2):\n    \"\"\"Contour overlap\"\"\"\n\n    #temp1 = zeros((1000, 1000), dtype=int8)\n    #temp2 = zeros((1000, 1000), dtype=int8)\n\n    binaryImage1 = contour1.binaryImage\n    binaryImage2 = contour2.binaryImage\n\n    boundingBox1 = contour1.get2DBoundingBox()\n    boundingBox2 = contour2.get2DBoundingBox()\n\n    minX = min(boundingBox1[0][0], boundingBox2[0][0])\n    minY = min(boundingBox1[0][1], boundingBox2[0][1])\n    maxX = max(boundingBox1[1][0], boundingBox2[1][0])\n    maxY = max(boundingBox1[1][1], boundingBox2[1][1])\n\n    temp1 = zeros((maxX-minX+1, maxY-minY+1))\n    temp2 = zeros((maxX-minX+1, maxY-minY+1))\n\n    temp1[boundingBox1[0][0]-minX:boundingBox1[1][0]-minX+1,\n          boundingBox1[0][1]-minY:boundingBox1[1][1]-minY+1] = binaryImage1\n\n    temp2[boundingBox2[0][0]-minX:boundingBox2[1][0]-minX+1,\n          boundingBox2[0][1]-minY:boundingBox2[1][1]-minY+1] = binaryImage2\n\n    andImage = logical_and(temp1, temp2) * 1\n    orImage = logical_or(temp1, temp2) * 1\n    fraction = float(sum(andImage)) / float(sum(orImage))\n\n    return fraction\n\n", "meta": {"hexsha": "1878a2f37a446dcf00ff094d3e8e657c1ec62cb0", "size": 4573, "ext": "py", "lang": "Python", "max_stars_repo_path": "cytoseg/contour_comparison.py", "max_stars_repo_name": "slash-segmentation/DP2", "max_stars_repo_head_hexsha": "6f768e4b8a75a3ab2bf1359ae94704332426a4d6", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cytoseg/contour_comparison.py", "max_issues_repo_name": "slash-segmentation/DP2", "max_issues_repo_head_hexsha": "6f768e4b8a75a3ab2bf1359ae94704332426a4d6", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cytoseg/contour_comparison.py", "max_forks_repo_name": "slash-segmentation/DP2", "max_forks_repo_head_hexsha": "6f768e4b8a75a3ab2bf1359ae94704332426a4d6", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1083333333, "max_line_length": 465, "alphanum_fraction": 0.714848021, "include": true, "reason": "from numpy", "num_tokens": 1223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.17390068230595473}}
{"text": "# Copyright (c) Anand Patil, 2007\n\n__docformat__ = 'reStructuredText'\n\nimport pymc as pm\nfrom . import linalg_utils\nimport copy\nimport types\nimport numpy as np\nfrom .gp_submodel import *\nimport warnings\n\nfrom pymc import six\nfrom pymc.six import print_\nxrange = six.moves.xrange\n\nfrom .Realization import Realization\nfrom .Mean import Mean\nfrom .Covariance import Covariance\nfrom .GPutils import observe, regularize_array\n\n__all__ = [\n    'wrap_metropolis_for_gp_parents',\n    'GPEvaluationGibbs',\n    'GPParentAdaptiveMetropolis',\n    'GPStepMethod',\n    'GPEvaluationMetropolis',\n    'MeshlessGPMetropolis']\n\n\nclass GPStepMethod(pm.NoStepper):\n\n    @staticmethod\n    def competence(stochastic):\n        if isinstance(stochastic, GaussianProcess):\n            return 1\n        else:\n            return 0\n\n    def tune(self, verbose=0):\n        return False\n\ndef wrap_metropolis_for_gp_parents(metro_class):\n    \"\"\"\n    Wraps Metropolis step methods so they can handle extended parents of\n    Gaussian processes.\n    \"\"\"\n    class wrapper(metro_class):\n        __doc__ = \"\"\"A modified version of class %s that handles parents of Gaussian processes.\nDocstring of class %s: \\n\\n%s\"\"\" % (metro_class.__name__, metro_class.__name__, metro_class.__doc__)\n\n        def __init__(self, stochastic, *args, **kwds):\n\n            self.metro_class.__init__(self, stochastic, *args, **kwds)\n\n            mb = set(self.markov_blanket)\n            for c in list(self.children):\n                if isinstance(c, GaussianProcess):\n                    self.children |= c.extended_children\n                    mb |= c.extended_children\n            self.markov_blanket = list(mb)\n\n            # Remove f from the set that will be used to compute\n            # logp_plus_loglike.\n            self.markov_blanket_no_f = set(\n                filter(\n                    lambda x: not isinstance(\n                        x,\n                        GaussianProcess),\n                    self.markov_blanket))\n            self.fs = filter(\n                lambda x: isinstance(\n                    x,\n                    GaussianProcess),\n                self.markov_blanket)\n            self.fr_checks = [f.submodel.fr_check for f in self.fs]\n\n        def get_logp_plus_loglike(self):\n            return pm.logp_of_set(self.markov_blanket_no_f)\n        logp_plus_loglike = property(get_logp_plus_loglike)\n\n        def propose(self):\n            self.metro_class.propose(self)\n            try:\n                # First make sure none of the stochastics handled by\n                # metro_method forbid their current values.\n                for s in self.stochastics:\n                    s.logp\n                # Then make sure the covariances are all still full-rank on the\n                # observation locations.\n                for frc in self.fr_checks:\n                    frc.logp\n                for f in self.fs:\n                    f.rand()\n                self.f_proposed = True\n            except pm.ZeroProbability:\n                self.f_proposed = False\n\n        def reject(self):\n            self.metro_class.reject(self)\n            if self.f_proposed:\n                for f in self.fs:\n                    f.revert()\n\n        @staticmethod\n        def competence(stochastic, metro_class=metro_class):\n            if any([isinstance(child, GaussianProcess)\n                    for child in stochastic.extended_children]):\n                return metro_class.competence(stochastic) + .01\n            else:\n                return 0\n\n    wrapper.__name__ = 'GPParent%s' % metro_class.__name__\n    wrapper.metro_class = metro_class\n\n    return wrapper\n\n\n# Wrap all registered Metropolis step methods to use GP parents.\nnew_sm_dict = {}\nfiltered_registry = [\n    sm for sm in pm.StepMethodRegistry if issubclass(\n        sm,\n        pm.Metropolis)]\nfor sm in filtered_registry:\n    wrapped_method = wrap_metropolis_for_gp_parents(sm)\n    new_sm_dict[wrapped_method.__name__] = wrapped_method\nGPParentAdaptiveMetropolis = wrap_metropolis_for_gp_parents(\n    pm.AdaptiveMetropolis)\n__all__ += new_sm_dict.keys()\nlocals().update(new_sm_dict)\n\n\nclass MeshlessGPMetropolis(pm.Metropolis):\n\n    def __init__(self, gp):\n        pm.Metropolis.__init__(\n            self,\n            gp,\n            proposal_distribution='Prior',\n            check_before_accepting=False)\n\n    def propose(self):\n        self.stochastic.rand()\n\n    @staticmethod\n    def competence(stochastic):\n        if isinstance(stochastic, GaussianProcess):\n            if len(stochastic.submodel.mesh) == 0:\n                return 3\n            else:\n                return 0\n        else:\n            return 0\n\n\nclass _GPEvaluationMetropolis(pm.Metropolis):\n\n    \"\"\"\n    Updates a GP evaluation, the 'f_eval' attribute of a GP submodel.\n    The stationary distribution of the assymetric proposal is equal\n    to the prior distribution, an attempt to minimize jumps to values\n    forbidden by the prior.\n    \"\"\"\n\n    def __init__(self, stochastic, proposal_sd=1, **kwds):\n        pm.Metropolis.__init__(\n            self,\n            stochastic,\n            proposal_sd=proposal_sd,\n            **kwds)\n\n    def propose(self):\n        sig = pm.utils.value(self.stochastic.parents['sig'])\n        mu = pm.utils.value(self.stochastic.parents['mu'])\n\n        delta = pm.rmv_normal_chol(0 * mu, sig)\n\n        beta = np.minimum(1, self.proposal_sd * self.adaptive_scale_factor)\n        bsig = beta * sig\n        sb2 = np.sqrt(1 - beta ** 2)\n        self.stochastic.value = (\n            self.stochastic.value - mu) * sb2 + beta * delta + mu\n        xp, x = self.stochastic.value, self.stochastic.last_value\n        self._hastings_factor = pm.mv_normal_chol_like(\n            x,\n            (xp - mu) * sb2 + mu,\n            bsig) - pm.mv_normal_chol_like(xp,\n                                           (x - mu) * sb2 + mu,\n                                           bsig)\n\n        # self.stochastic.value = self.stochastic.value + self.adaptive_scale_factor*self.proposal_sd*delta\n        # self._hastings_factor = 0\n\n    def hastings_factor(self):\n        return self._hastings_factor\n\n    @staticmethod\n    def competence(stochastic):\n        if isinstance(stochastic, GPEvaluation):\n            return 3\n        else:\n            return 0\n\nGPEvaluationMetropolis = wrap_metropolis_for_gp_parents(\n    _GPEvaluationMetropolis)\n\n\nclass GPEvaluationGibbs(pm.Metropolis):\n\n    \"\"\"\n    Updates a GP evaluation f_eval. Assumes the only children of f_eval\n    are as distributed follows:\n\n    eps_p_f ~ Normal(f_eval[ti], 1./V)\n\n    or\n\n    eps_p_f ~ Normal(f_eval, 1./V)\n\n    if ti is None.\n    \"\"\"\n\n    def __init__(self, submod, V, eps_p_f, ti=None, tally=True, verbose=0):\n\n        self.f_eval = submod.f_eval\n        self.f = submod.f\n        pm.StepMethod.__init__(self, [self.f, self.f_eval], tally=tally)\n\n        self.children_no_data = copy.copy(self.children)\n        if isinstance(eps_p_f, pm.Variable):\n            self.children_no_data.remove(eps_p_f)\n            self.eps_p_f = eps_p_f\n        else:\n            for epf in eps_p_f:\n                self.children_no_data.remove(epf)\n            self.eps_p_f = pm.Lambda(\n                'eps_p_f',\n                lambda e=eps_p_f: np.hstack(\n                    e),\n                trace=False)\n\n        self.V = pm.Lambda(\n            '%s_vect' % V.__name__,\n            lambda V=V: np.resize(V,\n                                  len(submod.mesh)))\n        self.C_eval = submod.C_eval\n        self.M_eval = submod.M_eval\n        self.S_eval = submod.S_eval\n\n        M_eval_shape = pm.utils.value(self.M_eval).shape\n        C_eval_shape = pm.utils.value(self.C_eval).shape\n        self.ti = ti or np.arange(M_eval_shape[0])\n\n        # Work arrays\n        self.scratch1 = np.asmatrix(np.empty(C_eval_shape, order='F'))\n        self.scratch2 = np.asmatrix(np.empty(C_eval_shape, order='F'))\n        self.scratch3 = np.empty(M_eval_shape)\n\n        # Initialize hidden attributes\n        self.accepted = 0.\n        self.rejected = 0.\n        self._state = ['rejected', 'accepted', 'proposal_distribution']\n        self._tuning_info = []\n        self.proposal_distribution = None\n\n        self.verbose = verbose\n\n    def get_logp(self):\n        return 0.\n    logp = property(get_logp)\n\n    def get_loglike(self):\n        return pm.utils.logp_of_set(self.children_no_data)\n    loglike = property(get_loglike)\n\n    def get_logp_plus_loglike(self):\n        return self.get_loglike()\n    logp_plus_loglike = property(get_logp_plus_loglike)\n\n    def reject(self):\n        self.rejected += 1\n        if self.verbose:\n            print_(self._id + ' rejecting')\n        # Revert the field evaluation and the rest of the field.\n        self.f_eval.revert()\n        self.f.revert()\n\n    def tune(self, verbose=0):\n        return False\n\n    def propose(self):\n\n        if self.verbose:\n            print_(self._id + ' proposing')\n\n        fc = pm.gp.fast_matrix_copy\n\n        eps_p_f = pm.utils.value(self.eps_p_f)\n        f = pm.utils.value(self.f_eval)\n        for i in xrange(len(self.scratch3)):\n            self.scratch3[i] = np.sum(eps_p_f[self.ti[i]] - f[i])\n\n        # Compute Cholesky factor of covariance of eps_p_f, C(x,x) + V\n        C_eval_value = pm.utils.value(self.C_eval)\n        C_eval_shape = C_eval_value.shape\n\n        # Get the Cholesky factor of C_eval, plus the nugget.\n        # I don't think you can use S_eval for speed, unfortunately.\n        in_chol = fc(C_eval_value, self.scratch1)\n\n        v_val = pm.utils.value(self.V)\n        for i in xrange(pm.utils.value(C_eval_shape)[0]):\n            in_chol[i, i] += v_val[i] / np.alen(self.ti[i])\n\n        info = pm.gp.linalg_utils.dpotrf_wrap(in_chol)\n        if info > 0:\n            raise np.linalg.LinAlgError\n\n        # Compute covariance of f conditional on eps_p_f.\n        offdiag = fc(C_eval_value, self.scratch2)\n        offdiag = pm.gp.trisolve(\n            in_chol,\n            offdiag,\n            uplo='U',\n            transa='T',\n            inplace=True)\n\n        C_step = offdiag.T * offdiag\n        C_step *= -1\n        C_step += C_eval_value\n\n        # Compute mean of f conditional on eps_p_f.\n        for i in xrange(len(self.scratch3)):\n            self.scratch3[i] = np.mean(eps_p_f[self.ti[i]])\n        m_step = pm.utils.value(\n            self.M_eval) + np.dot(offdiag.T,\n                                  pm.gp.trisolve(in_chol,\n                                                 (self.scratch3 -\n                                                  self.M_eval.value),\n                                                 uplo='U',\n                                                 transa='T')).view(np.ndarray).ravel()\n\n        sig_step = C_step\n        info = pm.gp.linalg_utils.dpotrf_wrap(C_step.T)\n        if info > 0:\n            warnings.warn(\n                'Full conditional covariance was not positive definite.')\n            return\n\n        # Update value of f.\n        self.f_eval.value = m_step + np.dot(\n            sig_step,\n            np.random.normal(\n                size=sig_step.shape[\n                    1])).view(\n                        np.ndarray).ravel(\n        )\n        # Propose the rest of the field from its conditional prior.\n        self.f.rand()\n", "meta": {"hexsha": "4878d9ae1a2b97630f122e2fd640c59bef40f3aa", "size": 11262, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymc/gp/step_methods.py", "max_stars_repo_name": "fabianrost84/pymc", "max_stars_repo_head_hexsha": "f514a8a42475ca12f2b0c2c9592c8c2f890d9f02", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pymc/gp/step_methods.py", "max_issues_repo_name": "fabianrost84/pymc", "max_issues_repo_head_hexsha": "f514a8a42475ca12f2b0c2c9592c8c2f890d9f02", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pymc/gp/step_methods.py", "max_forks_repo_name": "fabianrost84/pymc", "max_forks_repo_head_hexsha": "f514a8a42475ca12f2b0c2c9592c8c2f890d9f02", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-07-05T04:56:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T03:17:05.000Z", "avg_line_length": 31.1966759003, "max_line_length": 107, "alphanum_fraction": 0.5795595809, "include": true, "reason": "import numpy", "num_tokens": 2595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.17390067551778224}}
{"text": "import numpy as np\nimport os\nimport copy\n\nfrom Replicates import *\nfrom utils import *\n\nimport matplotlib as mat\nimport matplotlib.pyplot as plt\n\ntry:\n    from mpi4py import MPI      # Import MPI if available\nexcept:\n    pass\n    \n    \ndef ReachSteadyStateAndRescale(kmc_template, scale_parent_fldr, n_runs = 16, n_batches = 1000, \n                                acf_cut = 0.05, include_stiff_reduc = True, max_events = int(1e3), \n                                max_iterations = 30, ss_inc = 1.0, n_samples = 100, parallel_mode = 'Squidward',\n                                ACF_tol = 0.08, rate_tol = 0.05):\n\n    '''\n    Handles rate rescaling and continuation of KMC runs\n    \n    :param kmc_template:            kmc_traj object with information about the physical system\n    \n    :param scale_parent_fldr:       Working directory\n    \n    :param n_runs:                  Number of trajectories to run, also the number of processors\n    \n    :param include_stiff_reduc:     True to allow for scaledown, False to turn this feature off\n    \n    :param max_events:              Maximum number of events for the first iteration\n    \n    :param max_iterations:          Maximum number of iterations to use\n    \n    :param ss_inc:                  Factor to scale the final time by if you have not yet reached steady state\n    \n    :param n_samples:               Number of time points to sample for each trajectory\n    \n    :param parallel_mode:           MPI, Squidward, or Farber\n    '''\n    \n    if parallel_mode == 'MPI':\n        try:\n            COMM = MPI.COMM_WORLD\n            COMM.Barrier()\n        except:\n            raise NameError('mpi4py dependency has not been imported.')\n    \n    prev_batch = Replicates()       # Set this if the starting iteration is not 1\n    initial_states = None\n    \n    # Placeholder variables\n    if not os.path.exists(scale_parent_fldr):\n        os.makedirs(scale_parent_fldr)\n    ClearFolderContents(scale_parent_fldr)\n    SDF_vec = None        # scaledown factors for each iteration\n    \n    # Convergence variables\n    is_steady_state = False\n    iteration = 1              \n    \n    scale_final_time = ss_inc\n\n    while not is_steady_state and iteration <= max_iterations:\n        \n        # Make folder for iteration\n        iter_fldr = os.path.join(scale_parent_fldr, 'Iteration_' + str(iteration))\n        if not os.path.exists(iter_fldr):\n            os.makedirs(iter_fldr)\n            \n        # Create object for batch\n        cur_batch = Replicates()\n        cur_batch.ParentFolder = iter_fldr\n        cur_batch.n_trajectories = n_runs\n        cur_batch.N_batches = n_batches\n        cur_batch.Set_kmc_template(kmc_template)        # Set template KMC trajectory\n        \n        if iteration == 1:              # Sample on events, because we do not know the time scales\n        \n            # Set sampling parameters\n            cur_batch.runtemplate.simin.MaxStep = max_events\n            cur_batch.runtemplate.simin.SimTime_Max = 'inf'\n            cur_batch.runtemplate.simin.WallTime_Max = 'inf'\n            cur_batch.runtemplate.simin.restart = False\n            \n            cur_batch.runtemplate.simin.procstat = ['event', np.max( [max_events / n_samples, 1] ) ]\n            cur_batch.runtemplate.simin.specnum = ['event', np.max( [max_events / n_samples, 1] ) ]\n            cur_batch.runtemplate.simin.hist = ['event', np.max( [max_events * (n_samples-1) / n_samples, 1] )]       # only record the initial and final states\n\n            SDF_vec = np.ones( cur_batch.runtemplate.mechin.get_num_rxns() )         # Initialize scaledown factors\n        \n        elif iteration > 1:             # Time sampling\n\n            # Change sampling\n            cur_batch.runtemplate.simin.MaxStep = 'inf'\n            cur_batch.runtemplate.simin.WallTime_Max = 'inf'\n            cur_batch.runtemplate.simin.restart = False\n            cur_batch.runtemplate.simin.SimTime_Max = prev_batch.t_vec[-1] * scale_final_time\n            cur_batch.runtemplate.simin.SimTime_Max = float('{0:.3E} \\t'.format( cur_batch.runtemplate.simin.SimTime_Max ))     # round to 4 significant figures\n            cur_batch.runtemplate.simin.procstat = ['time', cur_batch.runtemplate.simin.SimTime_Max / n_samples]\n            cur_batch.runtemplate.simin.specnum = ['time', cur_batch.runtemplate.simin.SimTime_Max / n_samples]\n            cur_batch.runtemplate.simin.hist = ['time', cur_batch.runtemplate.simin.SimTime_Max ]\n            \n            # Adjust pre-exponential factors based on the stiffness assessment of the previous iteration\n            if include_stiff_reduc:\n                cur_batch.runtemplate.AdjustPreExponentials(SDF_vec)\n            \n            # Use continuation\n            initial_states = prev_batch.History_final_snaps\n        \n        # Run jobs and read output\n        if parallel_mode == 'MPI':\n            if COMM.rank == 0:\n                cur_batch.BuildJobFiles(init_states = initial_states)\n                \n            # Collect whatever has to be done in a list. Here we'll just collect a list of\n            # numbers. Only the first rank has to do this.\n            if COMM.rank == 0:\n                jobs = cur_batch.run_dirs\n                jobs = [jobs[_i::COMM.size] for _i in range(COMM.size)]             # Split into however many cores are available.\n            else:\n                jobs = None\n            \n            jobs = COMM.scatter(jobs, root=0)           # Scatter jobs across cores.\n            \n            # Now each rank just does its jobs and collects everything in a results list.\n            # Make sure to not use super big objects in there as they will be pickled to be\n            # exchanged over MPI.\n            for job in jobs:\n                cur_batch.runtemplate.Path = job\n                cur_batch.runtemplate.Run_sim()  \n                \n        else:\n            cur_batch.BuildJobFiles(init_states = initial_states)\n            cur_batch.RunAllTrajectories_JobArray(server = parallel_mode, job_name = 'Iteration_' + str(iteration) )\n            \n        cur_batch.ReadMultipleRuns()\n        \n        if iteration == 1:\n            cum_batch = copy.deepcopy(cur_batch)\n        else:\n            cum_batch = append_replicates(prev_batch, cur_batch)         # combine with previous data\n        \n        # Test steady-state\n        cum_batch.AverageRuns()\n        acf_data = cum_batch.Compute_rate()\n        \n        print '\\nIteration ' + str(iteration)\n        print 'Batches per trajectory: ' + str(cum_batch.Nbpt)\n        print 'Batch length (s): ' + str(cum_batch.batch_length)\n        print 'Rate: ' + str(cum_batch.rate)\n        print 'Rate confidence interval: ' + str(cum_batch.rate_CI)\n        print 'Autocorrelation: ' + str(cum_batch.ACF)\n        print 'Autocorrelation confidence: ' + str(cum_batch.ACF_CI)\n        \n        # Test if autocorrelation function has converged\n        \n        if cum_batch.ACF is None:\n            decorrelated = False\n        else:\n            decorrelated = ( cum_batch.ACF + cum_batch.ACF_CI < ACF_tol)\n        \n        # Test if rate is computed with sufficient accuracy\n        if cum_batch.rate == 0:\n            rate_accurate = False\n        else:\n            rate_accurate = (cum_batch.rate_CI / cum_batch.rate < rate_tol)\n        \n        print 'Decorrelated? ' + str(decorrelated)\n        print 'Rate accurate? ' + str(rate_accurate)\n        print '\\n'\n        \n        is_steady_state = decorrelated and rate_accurate\n        \n        # Record information about the iteration\n        cum_batch.runAvg.PlotGasSpecVsTime()\n        cum_batch.runAvg.PlotSurfSpecVsTime()\n        \n        cur_batch.AverageRuns()\n        cur_batch.runAvg.PlotElemStepFreqs()\n        scaledown_data = ProcessStepFreqs(cur_batch.runAvg)         # compute change in scaledown factors based on simulation result\n        delta_sdf = scaledown_data['delta_sdf']\n        \n        # Update scaledown factors\n        for ind in range(len(SDF_vec)):\n            SDF_vec[ind] = SDF_vec[ind] * delta_sdf[ind]\n            \n        scale_final_time = np.max( [1.0/np.min(delta_sdf), ss_inc] )\n        \n        prev_batch = copy.deepcopy(cum_batch)\n        iteration += 1\n\n    return cum_batch\n    \n\ndef ProcessStepFreqs(run, stiff_cut = 100.0, delta = 0.05, equilib_cut = 0.1):        # Change to allow for irreversible reactions\n    \n    '''\n    Takes an average KMC trajectory and assesses the reaction frequencies to identify fast reactions\n    Process KMC output and determine how to further scale down reactions\n    Uses algorithm from A. Chatterjee, A.F. Voter, Accurate acceleration of kinetic Monte Carlo simulations through the modification of rate constants, J. Chem. Phys. 132 (2010) 194101.\n    '''\n    \n    delta_sdf = np.ones( run.mechin.get_num_rxns() )    # initialize the marginal scaledown factors\n    rxn_speeds = []\n    \n    # data analysis\n    freqs = run.procstatout.events[-1,:]\n    fwd_freqs = freqs[0::2]\n    bwd_freqs = freqs[1::2]\n    net_freqs = fwd_freqs - bwd_freqs\n    tot_freqs = fwd_freqs + bwd_freqs\n    \n    fast_rxns = []\n    slow_rxns = []        \n    for i in range(len(tot_freqs)):\n        if tot_freqs[i] == 0:\n            slow_rxns.append(i)\n            rxn_speeds.append('slow')\n        else:\n            PE = float(net_freqs[i]) / tot_freqs[i]\n            if np.abs(PE) < equilib_cut:\n                fast_rxns.append(i)\n                rxn_speeds.append('fast')\n            else:\n                slow_rxns.append(i)\n                rxn_speeds.append('slow')\n    \n    # Find slow scale rate\n    slow_freqs = [1.0]      # put an extra 1 in case no slow reactions occur\n    for i in slow_rxns:\n        slow_freqs.append(tot_freqs[i])\n    slow_scale = np.max(slow_freqs)\n    \n    # Adjust fast reactions closer to the slow scale\n    for i in fast_rxns:\n        N_f = tot_freqs[i] / float(slow_scale)              # number of fast events per rare event\n        #alpha_UB = N_f * delta / np.log(1 / delta) + 1             # Chatterjee formula\n        \n        #delta_sdf[i] = np.min([1.0, np.max([stiff_cut / N_f, 1. / alpha_UB ]) ])\n        delta_sdf[i] = np.min([1.0, stiff_cut / N_f ])\n        \n    return {'delta_sdf': delta_sdf, 'rxn_speeds': rxn_speeds, 'tot': tot_freqs, 'net': net_freqs}\n    \n    \ndef ReadScaledown(RunPath, fldrs_cut = None, product = None, n_batches = 1000):\n    \n    '''\n    Read a scaledown that has already been run\n    '''\n\n    # Prepare data to graph\n    batch_lengths = []\n    rates_vec = []\n    rates_vec_ci = []\n    acf_vec = []\n    acf_vec_ci = []\n    \n    \n    # Count the iterations\n    n_folders = len(os.listdir(RunPath))\n    if not fldrs_cut is None:\n       \n        n_folders = fldrs_cut\n\n    print str(n_folders) + ' iterations found'\n\n    cum_batch = None\n    for ind in range(1,n_folders+1):\n        \n        x = Replicates()\n        x.ParentFolder = os.path.join(RunPath, 'Iteration_' + str(ind))\n        x.ReadMultipleRuns()\n\n        if ind == 1:\n            cum_batch = x\n        else:\n            cum_batch = append_replicates(cum_batch, x)\n            \n        cum_batch.N_batches = n_batches\n        cum_batch.gas_product = product\n        acf_data = cum_batch.Compute_rate()\n        print 'Iteration ' + str(ind)\n        print 'Batches per trajectory: ' + str(cum_batch.Nbpt)\n        print 'Batch length (s): ' + str(cum_batch.batch_length)\n        print 'Rate: ' + str(cum_batch.rate)\n        print 'Rate confidence interval: ' + str(cum_batch.rate_CI)\n        print 'Autocorrelation: ' + str(cum_batch.ACF)\n        print 'Autocorrelation confidence: ' + str(cum_batch.ACF_CI)\n\n        print '\\n'\n        \n        batch_lengths.append(cum_batch.batch_length)\n        rates_vec.append(cum_batch.rate)\n        rates_vec_ci.append(cum_batch.rate_CI)\n        acf_vec.append(cum_batch.ACF)\n        acf_vec_ci.append(cum_batch.ACF_CI)\n            \n    print batch_lengths\n    print rates_vec\n    print rates_vec_ci\n    print acf_vec\n    print acf_vec_ci\n        \n            \n    return cum_batch\n\n    ", "meta": {"hexsha": "07eb9a22af7596e57de8da2fe112bab7805cafa3", "size": 12008, "ext": "py", "lang": "Python", "max_stars_repo_path": "zacros_wrapper/RateRescaling.py", "max_stars_repo_name": "WayneYann/Zacros-Wrapper", "max_stars_repo_head_hexsha": "992f239530600ecf84f07f9ab7c4152b9bb64c25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-03T20:35:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T20:35:05.000Z", "max_issues_repo_path": "zacros_wrapper/RateRescaling.py", "max_issues_repo_name": "WayneYann/Zacros-Wrapper", "max_issues_repo_head_hexsha": "992f239530600ecf84f07f9ab7c4152b9bb64c25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "zacros_wrapper/RateRescaling.py", "max_forks_repo_name": "WayneYann/Zacros-Wrapper", "max_forks_repo_head_hexsha": "992f239530600ecf84f07f9ab7c4152b9bb64c25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.735483871, "max_line_length": 185, "alphanum_fraction": 0.6054297135, "include": true, "reason": "import numpy", "num_tokens": 2857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.1739006755177822}}
{"text": "# coding: utf-8\n\nimport os\nimport shutil\nimport subprocess\nfrom pathlib import Path\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom matplotlib.patches import Wedge\nfrom scipy.integrate import trapz\nfrom scipy.interpolate import NearestNDInterpolator, griddata, interp1d\nfrom scipy.optimize import minimize\n\nTESLAMAX_PACKAGE_DIR = Path(os.path.dirname(__file__))\n\nTESLAMAX_JAVA_DIR = TESLAMAX_PACKAGE_DIR.parent / 'java'\n\nTESLAMAX_CLASS_FILE = TESLAMAX_JAVA_DIR / 'TeslaMax.class'\n\nTESLAMAX_CMD = ['comsolbatch', '-inputfile', str(TESLAMAX_CLASS_FILE)]\n\nB_HIGH_FILENAME = \"B_high.txt\"\nB_LOW_FILENAME = \"B_low.txt\"\n\nB_III_FILENAME = \"B_III.txt\"\n\nH_IV_FILENAME = \"H_IV_1Q.txt\"\n\nMAIN_RESULTS_FILENAME = \"COMSOL Main Results.txt\"\n\nMAGNETIC_PROFILE_FILENAME = \"COMSOL Magnetic Profile.txt\"\n\nPARAMETER_FILENAME = \"params.txt\"\n\nN_PROFILE_POINTS = 181  # keep at this level to have in increments of 1 degree\nN_R_POINTS = 20\n\nN_POINTS_PER_AXIS = 400\n\nFIGSIZE_CM = 20\nFIGSIZE_INCHES = FIGSIZE_CM / 2.54\n\nFONTSIZE = 20\n\nB_HIGH_LEVEL = 1.0\nB_LOW_LEVEL = 0.0\n\nDEBUG = False\n\n\ndef get_comsol_parameters_series(filename=PARAMETER_FILENAME):\n    \"\"\"Parse a COMSOL parameters file 'filename' and\n    return a pandas Series from it.\n\n    \"\"\"\n    param_comsol_file = Path(filename)\n\n    param_comsol_series = pd.read_csv(str(param_comsol_file),\n                                        squeeze=True,\n                                        sep=\" \",\n                                        index_col=0,\n                                        header=None)\n\n    param_comsol_series.name = \"COMSOL Parameters\"\n    param_comsol_series.index.name = None\n\n    # append the units to the parameters names\n    names_with_units = {}\n    for name in param_comsol_series.keys():\n        if name.startswith(\"h_\") or name.startswith(\"R_\"):\n            names_with_units[name] = name + \"[m]\"\n        if name.startswith(\"alpha\") or name.startswith(\n                \"phi\") or name.startswith(\"delta_phi\"):\n            names_with_units[name] = name + \"[deg]\"\n        if name.startswith(\"B_\"):\n            names_with_units[name] = name + \"[T]\"\n        if name.startswith(\"H_c\"):\n            names_with_units[name] = name + \"[A/m]\"\n\n    param_comsol_series = param_comsol_series.rename(names_with_units)\n    return param_comsol_series\n\n\ndef read_comsol_data_file(filename):\n    \"\"\"Read and parse 'filename' as exported by COMSOL.\n    Export the numerical data as a numpy array containing only the numerical\n    data; the first two columns are x and y values. All values are in SI.\n\n    Keyword Arguments:\n    filename -- str\n    \"\"\"\n\n    return np.loadtxt(filename, skiprows=9)\n\n\ndef read_comsol_profile_data(filename):\n    \"\"\"\n    Read 'filename' as exported by TeslaMax and return an array of the\n    magnetic profile data, where the first column is the angle\n    in degrees [0,360] and the second is the average magnetic\n    flux density in tesla\n    \"\"\"\n\n    profile_data = np.loadtxt(filename,\n                              skiprows=1)\n\n    return profile_data.T\n\n\ndef process_main_results_file():\n    \"\"\"Take the file \"COMSOL Main Results.txt\" as exported by COMSOL and\n    clean the header data.\n\n    \"\"\"\n\n    p = Path('.') / MAIN_RESULTS_FILENAME\n\n    results = pd.read_csv(MAIN_RESULTS_FILENAME,\n                            sep=\"\\s+\",\n                            skiprows=5,\n                            index_col=None,\n                            header=None,\n                            names=[\"B_high[T]\",\n                                   \"B_low[T]\",\n                                   \"A_gap[m2]\",\n                                   \"A_magnet[m2]\",\n                                   \"-H_Brem_II_max[A/m]\",\n                                   \"-H_Brem_IV_max[A/m]\",\n                                   \"A_demag[m2]\"])\n\n    results_series = results.ix[0]\n\n    results_series.to_csv(str(p),\n                          float_format=\"%.6f\",\n                          sep=\" \",\n                          header=False,\n                          index=True)\n\n\ndef read_main_results_file():\n    \"\"\"Return a Series where each row is one of the COMSOL Main results\"\"\"\n\n    results_filepath = Path(MAIN_RESULTS_FILENAME)\n\n    results_series = pd.read_table(results_filepath,\n                                   sep=\" \",\n                                   squeeze=True,\n                                   index_col=0,\n                                   header=None)\n    results_series.index.name = None\n    results_series.name = \"COMSOL Main Results\"\n    return results_series\n\n\n# noinspection PyPep8Naming\ndef calculate_magnitude(components_grid):\n    \"\"\"\n    Return an array [x, y, norm(V)] from [x, y, Vx, Vy]\n    \"\"\"\n\n    # noinspection PyPep8Naming\n    x, y, Vx, Vy = components_grid.T\n\n    V = np.sqrt(Vx * Vx + Vy * Vy)\n    return np.array((x, y, V)).T #sem erro aqui mas sai um zero\n\n\ndef calculate_magnetic_profile(B_data, params):\n    \"\"\"\n    Return the magnetic profile array [phi, B] based on data for the\n    magnetic flux density [x, y, B] and a dictionary of parameters.\n\n    The magnetic profile is defined as the magnetic flux density along the\n    circumference in the middle of the air gap.\n\n    The grid for 'B_data' is supposed to span the interval 0 <= phi <= 90\n    (the first quadrant); this function mirrors this interval and return phi\n    in the interval [0, 360].\n    \"\"\"\n\n    params = expand_parameter_dictionary(params)\n\n    R_g = params['R_g']\n    R_o = params['R_o']\n\n    # create ranges for phi and r\n    phi_min = 0.0\n    phi_max = np.pi / 2\n\n    phi_vector_1q = np.linspace(phi_min, phi_max, N_PROFILE_POINTS)\n\n    r_central = (R_o + R_g) / 2\n\n    # calcualte the points (x,y) distributed along\n    # radial lines\n    x_grid = r_central * np.cos(phi_vector_1q)\n    y_grid = r_central * np.sin(phi_vector_1q)\n\n    B_profile_1q = griddata(B_data[:, 0:2],\n                            B_data[:, 2],\n                            np.array([x_grid, y_grid]).T)\n    #ERRO AQUI. PRIMEIRO DIGITO DO B_profile_1q A PARTIR DE CERTO MOMENTO VEM NAN\n    b=np.isnan(B_profile_1q)\n    for i in range(0,len(b)):\n        if b[i]==True:\n            B_profile_1q[i]=B_profile_1q[i+1]\n        else: continue\n\n    # extrapolate data to the full circle\n    phi_vector = np.concatenate((phi_vector_1q,\n                                 phi_vector_1q + np.pi / 2,\n                                 phi_vector_1q + np.pi,\n                                 phi_vector_1q + (3 / 2) * np.pi))\n\n    B_profile = np.concatenate((B_profile_1q,\n                                B_profile_1q[::-1],\n                                B_profile_1q,\n                                B_profile_1q[::-1]))\n\n    profile_data = np.array((np.rad2deg(phi_vector), B_profile)).T\n    return profile_data\n\n\ndef write_magnetic_profile_file():\n    \"\"\"Create a file \"COMSOL Magnetic Profile.txt\" in the current directory,\n    assuming the teslamax command was already ran, and write the magnetic\n    profile data (magentic flux density at the air gap central circumference).\n    \"\"\"\n\n    p = Path('.') / MAGNETIC_PROFILE_FILENAME\n    column_names = [\"phi[deg]\", \"B[T]\"]\n    column_header = \" \".join(column_names)\n\n    # load data from the B_III filename\n    B_III_data = read_comsol_data_file(B_III_FILENAME)\n    # get the columns corresponding to [x, y, B_x, B_y] and calculate [x, y, B]\n    B_1q = calculate_magnitude(B_III_data[:, :4])\n\n    case_series = get_comsol_parameters_series()\n\n\n    profile_data = calculate_magnetic_profile(B_1q, case_series)\n\n    np.savetxt(str(p),\n               profile_data,\n               fmt=(\"%.2f\", \"%.5f\"),\n               delimiter=\" \",\n               header=column_header,\n               comments='')\n\n\ndef calculate_average_high_field(profile_data):\n    \"\"\"\n        Return the average magnetic profile through the high field region,\n        based on profile data [theta, B_profile]\n        \"\"\"\n\n    # in the present model, the high field region (equivalent to the cold\n    # blow in an AMR device) goes from -45° to +45°, and from 135° to 225°\n\n    theta_min = 135.0\n    theta_max = 225.0\n\n    theta_vector = profile_data[:, 0]\n    B_profile_vector = profile_data[:, 1]\n\n    # select values only where theta_vector falls in the high field region\n    # this will return an array with True only at those positions\n    region_filter = np.logical_and(theta_vector > theta_min,\n                                   theta_vector < theta_max)\n\n    # select the region of the magnetic profile that satisfy this condition\n    theta_high_field = theta_vector[region_filter]\n    B_profile_high_field = B_profile_vector[region_filter]\n\n    # return the integral of these samples, divided by the range\n    B_integrated = trapz(B_profile_high_field, theta_high_field)\n    theta_range = theta_max - theta_min\n\n    B_high_avg = B_integrated / theta_range\n    return B_high_avg\n\n\ndef write_magnetic_profile_central_file():\n    \"\"\"Create a file \"COMSOL Magnetic Profile.txt\" in the current directory,\n    assuming the teslamax command was already ran, and write the magnetic\n    profile data (magnetic induction at central radial position).\n\n    \"\"\"\n\n    p = Path('.') / MAGNETIC_PROFILE_FILENAME\n    column_names = [\"phi[deg]\", \"B[T]\"]\n    column_header = \" \".join(column_names)\n\n    # load data from the high and low field regions\n    B_h = read_comsol_data_file(B_HIGH_FILENAME)\n    B_l = read_comsol_data_file(B_LOW_FILENAME)\n\n    B_1q = np.concatenate((B_h, B_l), axis=0)\n\n    # calcualte vector of angles for the first quadrant\n    case_series = get_comsol_parameters_series()\n\n    n_phi_points = 100\n\n    R_g = case_series['R_g[m]']\n    R_o = case_series['R_o[m]']\n\n    # create ranges for phi and r\n    phi_min = 0.0\n    phi_max = np.pi / 2\n\n    phi_vector_1q = np.linspace(phi_min, phi_max, N_PROFILE_POINTS)\n\n    r_min = R_o\n    r_max = R_g\n\n    r_central = (R_o + R_g)/2\n\n    # calcualte the points (x,y) distributed along\n    # radial lines\n    x_grid = r_central * np.cos(phi_vector_1q)\n    y_grid = r_central * np.sin(phi_vector_1q)\n\n    B_profile_1q = griddata(B_1q[:, 0:2], B_1q[:, 2],\n                            np.array([x_grid, y_grid]).T)\n\n    # extrapolate data to the full circle\n    phi_vector = np.concatenate((phi_vector_1q,\n                                 phi_vector_1q + np.pi / 2,\n                                 phi_vector_1q + np.pi,\n                                 phi_vector_1q + (3 / 2) * np.pi))\n\n    B_profile = np.concatenate((B_profile_1q,\n                                B_profile_1q[::-1],\n                                B_profile_1q,\n                                B_profile_1q[::-1]))\n\n    profile_data = np.array((np.rad2deg(phi_vector), B_profile)).T\n\n    np.savetxt(str(p),\n               profile_data,\n               fmt=(\"%.2f\", \"%.5f\"),\n               delimiter=\" \",\n               header=column_header,\n               comments='')\n\n\ndef run_teslamax(verbose=False):\n    \"\"\"\n    Run the teslamax process in the current directory, clean the results file\n    and create a magnetic profile file.\n\n    Assumes the parameters file is present in the current directory.\"\"\"\n    comsol_process = subprocess.run(TESLAMAX_CMD,\n                                    shell=True,\n                                    stdout=subprocess.PIPE,\n                                    stderr=subprocess.STDOUT,\n                                    universal_newlines=True)\n    if verbose:\n        print(comsol_process.stdout)\n    process_main_results_file()\n    write_magnetic_profile_file()\n\n\ndef remove_units_from_dict_keys(dictionary):\n    \"\"\"Remove a string '[<anything>]' from every key of 'dictionary'\"\"\"\n\n    new_dictionary = {}\n\n    for key in dictionary.keys():\n        new_key = key.split('[')[0]\n        new_dictionary[new_key] = dictionary[key]\n\n    return new_dictionary\n\n\ndef expand_parameter_dictionary(param_simple):\n    \"\"\"\n    Return a new dictionary, calculating derivative parameters from\n    'param_simple', which is usually passed to COMSOL.\n\n    If the input dictionary contain units, they are removed. The returned\n    dict does not contain units\n    \"\"\"\n    param_dict = remove_units_from_dict_keys(param_simple)\n\n    # cast the number of segments to int, if necessary\n    param_dict[\"n_IV\"] = int(param_dict[\"n_IV\"])\n\n    # remove some keys that are not necessary (and which may cause errors)\n    try:\n        del param_dict[\"-H_Brem_IV_max\"]\n    except:\n        pass\n\n    # calculate magnet geometry\n    param_dict[\"R_g\"] = param_dict[\"R_o\"] + param_dict[\"h_gap\"]\n    param_dict[\"R_c\"] = param_dict[\"R_s\"] + param_dict[\"h_fc\"]\n    if param_dict[\"n_II\"] > 0:\n        param_dict[\"delta_phi_S_II\"] = ((param_dict[\"phi_S_II\"] -\n                                         param_dict[\"phi_C_II\"]) /\n                                        param_dict[\"n_II\"])\n    if param_dict[\"n_IV\"] > 0:\n        param_dict[\"delta_phi_S_IV\"] = (param_dict[\"phi_S_IV\"] /\n                                        param_dict[\"n_IV\"])\n\n    return param_dict\n\n\ndef write_parameter_file_from_dict(param_dict):\n    \"\"\"From a basic 'param_dict', calculate the necessary other parameters\n    (e.g. magnet segment size from total size and number of segments) and write\n    the correct parameters file.\n\n    If 'param_dict' contains units in the names, they are removed.\n    \"\"\"\n\n    param_dict = expand_parameter_dictionary(param_dict)\n\n    # write the dictionary file in the appropriate format that COMSOL can parse\n    parameters_file_path = Path(\".\") / PARAMETER_FILENAME\n\n    param_text = \"\"\n\n    for (key, value) in param_dict.items():\n        param_text = param_text + \"%s %s\\n\" % (key, value)\n\n    parameters_file_path.write_text(param_text)\n\n\ndef run_teslamax_from_params(params, verbose=False):\n    \"\"\"Write the 'params' dictionary in the apropriate format to the current\n    directory (removing units if necessary) and run the teslamax process\"\"\"\n    write_parameter_file_from_dict(params)\n    run_teslamax(verbose)\n\n\n\ndef normalize_vector(v):\n    \"\"\"\n    Return the normalized (dimensionless) form of vector\n    (or list of vectors) v\"\"\"\n\n    # v could be a single vector or a list of vectors,\n    # so we handle different cases\n    if v.ndim == 1:\n        return v / np.linalg.norm(v)\n    else:\n        v_norm = np.linalg.norm(v, axis=1)\n        v_norm_inv = np.reciprocal(v_norm).reshape(len(v), 1)\n        return np.multiply(v, v_norm_inv)\n\n\ndef create_quater_circle_figure_template(r_lim, params):\n    \"\"\"\n    Return (fig,axes) correspondent to a figure of the first quadrant,\n    limited by r_lim.\n    Both magnets are also drawn.\n\n    The size of the figure is controlled by FIGSIZE_INCHES\"\"\"\n\n    fig = plt.figure(figsize=(FIGSIZE_INCHES, FIGSIZE_INCHES))\n    axes = fig.add_subplot(111, aspect='equal')\n\n    axes.set_ylim(0, 1e3 * r_lim)\n    axes.set_xlim(0, 1e3 * r_lim)\n\n    axes.set_ylabel(r'$y\\ [\\si{\\mm}$]')\n    axes.set_xlabel(r'$x\\ [\\si{\\mm}$]')\n\n    R_o = params['R_o']\n    R_i = params['R_i']\n    R_s = params['R_s']\n    R_g = params.get('R_g', params['R_o'] + params['h_gap'])\n\n    magnet_II_outer = plt.Circle((0, 0), 1000 * R_o, color='k', fill=False)\n    magnet_II_inner = plt.Circle((0, 0), 1e3 * R_i, color='k', fill=False)\n    axes.add_artist(magnet_II_outer)\n    axes.add_artist(magnet_II_inner)\n\n    magnet_IV_outer = plt.Circle((0, 0), 1e3 * R_s, color='k', fill=False)\n    magnet_IV_inner = plt.Circle((0, 0), 1000 * R_g, color='k', fill=False)\n    axes.add_artist(magnet_IV_outer)\n    axes.add_artist(magnet_IV_inner)\n\n    return fig, axes\n\n\ndef generate_sector_mesh_points(R1, R2, phi1, phi2):\n    \"\"\"\n    Return a list of points [X,Y] uniformily distributed in a circle between\n    radii R1 and R2 and angular positions phi1 and phi2\n\n    The number of points is controlled by N_POINTS_PER_AXIS.\n    \"\"\"\n\n    phi_min = phi1\n    phi_max = phi2\n\n    phi_vector = np.linspace(phi_min, phi_max, N_POINTS_PER_AXIS)\n\n    r_vector = np.linspace(R1, R2, N_POINTS_PER_AXIS)\n\n    phi_grid, r_grid = np.meshgrid(phi_vector, r_vector)\n\n    X_vector = (r_grid * np.cos(phi_grid)).flatten()\n    Y_vector = (r_grid * np.sin(phi_grid)).flatten()\n    return np.array([X_vector, Y_vector]).T\n\n\n\ndef create_magnet_IV_figure_template(params):\n    \"\"\"\n    Return (fig,axes) correspondent to a figure of the\n    first quadrant of magnet IV.\n\n    The size of the figure is controlled by FIGSIZE_INCHES\"\"\"\n\n    fig = plt.figure(figsize=(FIGSIZE_INCHES, FIGSIZE_INCHES))\n    axes = fig.add_subplot(111, aspect='equal')\n\n    R_o = params['R_o']\n    R_i = params['R_i']\n    R_s = params['R_s']\n    R_g = params.get('R_g', params['R_o'] + params['h_gap'])\n    R_c = params.get('R_c', params['R_s'] + params['h_fc'])\n    r_lim = R_c\n\n    axes.set_ylim(0, 1e3 * r_lim)\n    axes.set_xlim(0, 1e3 * r_lim)\n\n    axes.set_ylabel(r'$y\\ [\\si{\\mm}$]')\n    axes.set_xlabel(r'$x\\ [\\si{\\mm}$]')\n\n    width_IV = R_s - R_g\n    n_IV = int(params['n_IV'])\n    delta_phi_S_IV = params['delta_phi_S_IV']\n    for i in range(0, n_IV):\n        theta_0 = i * delta_phi_S_IV\n        theta_1 = (i + 1) * delta_phi_S_IV\n        magnet_segment = Wedge((0, 0),\n                               1e3 * R_s,\n                               theta_0,\n                               theta_1,\n                               1e3 * width_IV,\n                               color='k',\n                               fill=False)\n        axes.add_artist(magnet_segment)\n\n    return fig, axes\n\n\ndef create_magnets_figure_template(params):\n    \"\"\"\n    Return (fig,axes) correspondent to a figure of the\n    first quadrant of both magnets.\n\n    The size of the figure is controlled by FIGSIZE_INCHES\"\"\"\n\n    fig = plt.figure(figsize=(FIGSIZE_INCHES, FIGSIZE_INCHES))\n    axes = fig.add_subplot(111, aspect='equal')\n\n    R_o = params['R_o']\n    R_i = params['R_i']\n    R_s = params['R_s']\n    R_g = params.get('R_g', params['R_o'] + params['h_gap'])\n    R_c = params.get('R_c', params['R_s'] + params['h_fc'])\n    r_lim = R_c\n\n    axes.set_ylim(0, 1e3 * r_lim)\n    axes.set_xlim(0, 1e3 * r_lim)\n\n    axes.set_ylabel(r'$y\\ [\\si{\\mm}$]')\n    axes.set_xlabel(r'$x\\ [\\si{\\mm}$]')\n\n    width_II = R_o - R_i\n    n_II = int(params['n_II'])\n    delta_phi_S_II = params['delta_phi_S_II']\n    for i in range(0, n_II):\n        theta_0 = i * delta_phi_S_II\n        theta_1 = (i + 1) * delta_phi_S_II\n        magnet_segment = Wedge((0, 0),\n                               1e3 * R_o,\n                               theta_0,\n                               theta_1,\n                               1e3 * width_II,\n                               color='k',\n                               fill=False)\n        axes.add_artist(magnet_segment)\n\n    width_IV = R_s - R_g\n    n_IV = int(params['n_IV'])\n    delta_phi_S_IV = params['delta_phi_S_IV']\n    for j in range(0, n_IV):\n        theta_0 = j * delta_phi_S_IV\n        theta_1 = (j + 1) * delta_phi_S_IV\n        magnet_segment = Wedge((0, 0),\n                               1e3 * R_s,\n                               theta_0,\n                               theta_1,\n                               1e3 * width_IV,\n                               color='k',\n                               fill=False)\n        axes.add_artist(magnet_segment)\n\n    return fig, axes\n\n\nclass TeslaMaxGeometry:\n    \"\"\"\n    Class representing the physical geometry of the TeslaMax system,\n    with all radii and angles.\n\n    To instantiante, pass a dictionary (or similar object) with all geometric\n    parameters in SI units (except for the angles, which must be provided in\n    degrees). The names for the keys follow the standard convention, without\n    the units in the names. E.g.\n\n    >>> params = {'R_i': 0.015, 'phi_C_II': 15, ...} # provide other parameters\n    >>> tmg = TeslaMaxGeometry(params)\n\n    The parameters 'R_o', 'h_gap' and 'R_g' are not independent. If two are\n    provided, the class automatically calculates the other one. If you provide\n    all three, it's your responsibility to provide three consistent values.\n\n    Currently, the only possible calculations are volume-related.\n    \"\"\"\n\n    def __init__(self, params):\n        \"\"\"\n        Keyword Arguments:\n        params -- dict-like\n        \"\"\"\n\n        self.geometric_parameters = params.copy()\n        self._complete_geometric_parameters()\n\n    def _complete_geometric_parameters(self):\n        \"\"\"\n        For two of the parameters 'R_o', 'R_g', 'h_gap', calculate the\n        third one and populate the 'geometric_parameters' field.\n\n        If all three parameters are provided, nothing happens\n        \"\"\"\n\n        gp = self.geometric_parameters\n\n        if ('R_o' in gp) and ('R_g' in gp) and ('h_gap' in gp):\n            pass\n        else:\n            if ('R_o' in gp) and ('R_g' in gp):\n\n                gp['h_gap'] = gp['R_g'] - gp['R_o']\n\n            elif ('R_o' in gp) and ('h_gap' in gp):\n\n                gp['R_g'] = gp['R_o'] + gp['h_gap']\n\n            elif ('R_g' in gp) and ('h_gap' in gp):\n\n                gp['R_o'] = gp['R_g'] - gp['h_gap']\n\n    def calculate_magnet_volume(self, L):\n        \"\"\"\n        Return the volume (m3) of the permanent regions,\n        for a length of 'L' (m)\n        \"\"\"\n\n        params = self.geometric_parameters\n\n        phi_S_II = np.deg2rad(params[\"phi_S_II\"])\n        phi_S_IV = np.deg2rad(params[\"phi_S_IV\"])\n        phi_C_II = np.deg2rad(params[\"phi_C_II\"])\n\n        R_i = params[\"R_i\"]\n        R_o = params[\"R_o\"]\n        R_s = params[\"R_s\"]\n        R_g = params[\"R_g\"]\n\n        # the factor of 2 already accounts for 4 quadrants\n        A_II = 2 * (phi_S_II - phi_C_II) * (R_o ** 2 - R_i ** 2)\n        A_IV = 2 * phi_S_IV * (R_s ** 2 - R_g ** 2)\n        V = (A_II + A_IV) * L\n\n        return V\n\n\ndef expand_parameters_from_remanence_array(magnet_parameters, params, prefix):\n    \"\"\"\n    Return a new parameters dict with the magnet parameters in the form\n    '<prefix>_<magnet>_<segment>', with the values from 'magnet_parameters'\n    and other parameters from 'params'.\n\n    The length of the array 'magnet_parameters' must be equal to the sum of\n    the number of segments in both cylinders.\n\n    The first n_II elements refer to the inner magnet,\n    and the remaining elements to the outer magnet.\n    \"\"\"\n\n    params_expanded = params.copy()\n\n    n_II = params[\"n_II\"]\n    for i in range(0, n_II):\n        params_expanded[\"%s_II_%d\" % (prefix, i + 1,)] = magnet_parameters[i]\n\n    n_IV = params[\"n_IV\"]\n    for j in range(0, n_IV):\n        k = j + n_II  # the first n_II elements refer to magnet II\n        params_expanded[\"%s_IV_%d\" % (prefix, j + 1,)] = magnet_parameters[k]\n\n    return params_expanded\n\n\ndef calculate_instantaneous_profile(phi, B_high, B_low, *args):\n    \"\"\"\n    Calculate the value of the two-pole instantaneous magnetic profile at\n    angular position 'phi' (in degrees), where the profile oscillates from\n    'B_low' to 'B_high'\n\n    \"\"\"\n\n    high_region = (phi <= 45)\n    high_region = np.logical_or(high_region,\n                                np.logical_and((phi >= 135),\n                                               (phi <= 225)))\n    high_region = np.logical_or(high_region, (phi >= 315))\n    return np.where(high_region, B_high, B_low)\n\n\ndef calculate_ramp_profile(phi, B_high, B_low, high_field_fraction, *args):\n    \"\"\"\n    Calculate the value of the two-pole instantaneous magnetic profile at\n    angular position 'phi' (in degrees), where the profile oscillates from\n    'B_low' to 'B_high' in a trapezoidal wave, with each plateau occupying\n    'high_field_fraction' of the cycle.\n\n    \"\"\"\n\n    # for the edge case of a field fraction of 50%,\n    # the ramp profile is equivalent to the instantaneous profile\n    if np.isclose(high_field_fraction,0.5):\n        return calculate_instantaneous_profile(phi,B_high,B_low,args)\n\n    # for two poles, we can replicate the results from 0 to 180\n    phi = np.mod(phi,180)\n\n    # the fraction of the cycle where the field is constant is the fraction\n    # where the field is at the high level, plus the fration where the field is\n    # at the low level, hence the factor of 2\n    field_fraction = 2 * high_field_fraction\n    angle_change = field_fraction * 45\n\n    high_region = (phi < angle_change)\n    high_region = np.logical_or(high_region, (phi > (180 - angle_change)))\n\n    descent_region = np.logical_and((phi >= angle_change),\n                                    (phi <= 90 - angle_change))\n\n    ascent_region = np.logical_and((phi >= 90 + angle_change),\n                                   (phi <= 180 - angle_change))\n\n    return np.where(high_region,\n                    B_high,\n                    np.where(descent_region,\n                             B_high + (B_low - B_high) * (\n                                     phi - angle_change) / (\n                                         (1 - field_fraction) * 90),\n                             np.where(ascent_region,\n                                      B_low + (B_high - B_low) * (\n                                              phi - (90 + angle_change)) / (\n                                              (1 - field_fraction) * 90),\n                                      B_low)))\n\n\nclass TeslaMaxPreDesign:\n    \"\"\"\n    Class representing a fixed-geometry pre-design of the TeslaMax system,\n    with all geometric and material parameters, but without the direction of\n    magnetization for the magnet segments.\n\n    To instantiate, you have to pass a dictionary with the parameters:\n    >>> tmpd = TeslaMaxPreDesign({'R_i': 0.015, 'mu_r_II': 1.05, ...})\n\n    This dictionary should at least contain all geometric parameters,\n    with which a TeslaMaxGeometry object will be created. The material\n    properties can be added  directly in the constructor;\n    the remanences magnitudes for each segment in this case are specified\n    as a vector:\n\n    >>> geom_params = {'R_i': 0.015, 'n_II': 2, ...}\n    >>> tmpd = TeslaMaxPreDesign(geom_params,\n                                 mu_r_II=1.05,\n                                 mu_r_IV=1.10,\n                                 mu_r_iron=5e5,\n                                 linear_iron=1,\n                                 B_rem_vector=np.array([1.4,1.4,1.2,1.2])\n\n    The parameters dictionary may contain some of the material properties;\n    if you provide a parameter in the dictionary and via the constructor,\n    it is the latter value that will be used to build the object. In the\n    dictionary, the remanences must be provided in the usual form\n    (e.g. 'B_rem_II_1')\n    \"\"\"\n\n    def __init__(self,\n                 params,\n                 mu_r_II=None,\n                 mu_r_IV=None,\n                 B_rem_vector=None,\n                 mu_r_iron=None,\n                 linear_iron=None):\n\n        self.geometry = TeslaMaxGeometry(params)\n        self.geometry_material_parameters = self.geometry.geometric_parameters\n\n        if mu_r_II is not None:\n            self.geometry_material_parameters['mu_r_II'] = mu_r_II\n\n        if mu_r_IV is not None:\n            self.geometry_material_parameters['mu_r_IV'] = mu_r_IV\n\n        if mu_r_iron is not None:\n            self.geometry_material_parameters['mu_r_iron'] = mu_r_iron\n\n        if linear_iron is not None:\n            self.geometry_material_parameters['linear_iron'] = linear_iron\n\n        if B_rem_vector is not None:\n            self.geometry_material_parameters = expand_parameters_from_remanence_array(\n                B_rem_vector,\n                self.geometry_material_parameters,\n                'B_rem')\n\n        self.points_F_operators = None\n        self.F_operators = None\n\n        self.alpha_B_rem_optimal = None\n        self.optimization_results = None\n\n    def calculate_B_III_from_single_block(self,\n                                          point,\n                                          segment,\n                                          magnet,\n                                          magnitude,\n                                          angle):\n        \"\"\"\n        Return B_III(point) when 'segment' (1, 2, 3, ...)  of 'magnet'\n        (either 'II' or 'IV') has a remanence of 'magnitude' and 'angle',\n        and all other segments have null remanence.\n\n        \"\"\"\n\n        n_II = self.geometry_material_parameters[\"n_II\"]\n        n_IV = self.geometry_material_parameters[\"n_IV\"]\n        n_total = n_II + n_IV\n\n        B_rem_vector = np.zeros(n_total)\n        alpha_B_rem_vector = np.zeros(n_total)\n\n        if magnet == \"II\":\n            element = segment - 1\n\n        else:\n            element = n_II + (segment - 1)\n\n        B_rem_vector[element] = magnitude\n        alpha_B_rem_vector[element] = angle\n\n        tmpd = TeslaMaxPreDesign(self.geometry_material_parameters,\n                                 B_rem_vector=B_rem_vector)\n\n        # the results of these intermediate calculations are stored in this dir\n        auxdir = Path('.') / 'teslamax-optimization'\n        auxdir.mkdir(exist_ok=True)\n        tmm = TeslaMaxModel(tmpd, alpha_B_rem_vector, str(auxdir))\n        tmm.run(verbose=DEBUG)\n        result = tmm.calculate_B_III_from_position(point)\n        return result\n\n    def calculate_F_operators(self):\n        \"\"\"\n        Return (F_II_x, F_II_y, F_IV_x, F_IV_y), where each element is a list\n        of the F-operators vector fields calculated at a uniform mesh\n        in the air gap.\n\n        For instance, F_II_x[0] is an array of (B_x, B_y), calculated when\n        only the first segment of magnet II is magnetized in the x-direction,\n        with unit remanence\n        \"\"\"\n\n        n_II = self.geometry_material_parameters['n_II']\n        n_IV = self.geometry_material_parameters['n_IV']\n\n        R_o = self.geometry_material_parameters[\"R_o\"]\n        R_g = self.geometry_material_parameters[\"R_g\"]\n        points = generate_sector_mesh_points(1.001 * R_o,\n                                             0.999 * R_g,\n                                             0.0,\n                                             np.pi / 2)\n        self.points_F_operators = points\n\n        F_II_x = []\n        F_II_y = []\n\n        F_IV_x = []\n        F_IV_y = []\n\n        for k in range(0, n_II):\n            F_II_x.append(self.calculate_B_III_from_single_block(point=points,\n                                                                 segment=k + 1,\n                                                                 magnet='II',\n                                                                 magnitude=1.0,\n                                                                 angle=0.0))\n\n            F_II_y.append(self.calculate_B_III_from_single_block(point=points,\n                                                                 segment=k + 1,\n                                                                 magnet='II',\n                                                                 magnitude=1.0,\n                                                                 angle=90.0))\n\n        for j in range(0, n_IV):\n            F_IV_x.append(self.calculate_B_III_from_single_block(point=points,\n                                                                 segment=j + 1,\n                                                                 magnet='IV',\n                                                                 magnitude=1.0,\n                                                                 angle=0.0))\n\n            F_IV_y.append(self.calculate_B_III_from_single_block(point=points,\n                                                                 segment=j + 1,\n                                                                 magnet='IV',\n                                                                 magnitude=1.0,\n                                                                 angle=90.0))\n\n        self.F_operators = (F_II_x, F_II_y, F_IV_x, F_IV_y)\n    def get_points_F_operators(self):\n        if self.points_F_operators is None:\n            self.calculate_F_operators()\n        return self.points_F_operators\n\n    def get_F_operators(self):\n\n        if self.F_operators is None:\n            self.calculate_F_operators()\n        return self.F_operators\n\n    def superposition_B_III(self, alpha_B_rem):\n        \"\"\"\n        Return (x, y, B_x, B_y) based on a  vector of remanence angles.\n\n        - 'alpha_B_rem' is a vector of (n_II + n_IV) remanences, where the\n        first n_II elements represent magnet II and the remaining elements\n        represent magnet IV\n\n        \"\"\"\n\n        B_III = 0.0\n\n        points = self.get_points_F_operators()\n        F_II_x, F_II_y, F_IV_x, F_IV_y = self.get_F_operators() #nao eh aqui\n\n        params = self.geometry_material_parameters\n\n        n_II = params[\"n_II\"]\n        for k in range(0, n_II):\n            B_rem = params[\"B_rem_II_%d\" % (k + 1)]\n            alpha = np.deg2rad(alpha_B_rem[k])\n            B = B_rem * (np.cos(alpha) * F_II_x[k] + np.sin(alpha) * F_II_y[k])\n            B_III = B_III + B\n        n_IV = params[\"n_IV\"]\n        for j in range(0, n_IV):\n            B_rem = params[\"B_rem_IV_%d\" % (j + 1)]\n            alpha = np.deg2rad(alpha_B_rem[n_II + j])\n            B = B_rem * (np.cos(alpha) * F_IV_x[j] + np.sin(alpha) * F_IV_y[j])\n\n            B_III = B_III + B\n        B_III_grid = np.concatenate((points, B_III), axis=1)\n\n        return B_III_grid\n\n    def calculate_functional_average(self, alpha_B_rem):\n        \"\"\"\n        Return the objective functional based on  a vector of remanence angles.\n        The objective functional is defined as the reciprocal of the\n        average high field, to be minimized.\n\n        - 'alpha_B_rem' is a vector of (n_II + n_IV) remanences, where the\n        first n_II elements represent magnet II and the remaining elements\n        represent magnet IV\n        \"\"\"\n\n        B_III_data = self.superposition_B_III(alpha_B_rem)\n\n        # the above statement will return [x,y,B_x,B_y]. We have to calculate the magnitude to pass it\n        # to the magnetic profile data\n        B_III_data = calculate_magnitude(B_III_data)\n\n        B_profile_data = calculate_magnetic_profile(B_III_data,\n                                                    self.geometry_material_parameters).T\n\n        S = -calculate_average_high_field(B_profile_data)\n        return S\n\n    def calculate_functional_target(self,\n                                    alpha_B_rem,\n                                    target_profile_function,\n                                    target_profile_args):\n        \"\"\"\n        Return the objective functional based on  a vector of remanence angles.\n        The objective functional is defined as the difference between the\n        resulting profile and a target profile function,\n        and is to be minimized.\n\n        - 'alpha_B_rem' is a vector of (n_II + n_IV) remanences, where the\n        first n_II elements represent magnet II and the remaining elements\n        represent magnet IV\n        - 'target_profile_function' is a function with signature\n        'f(phi_vector, *args)' (the first argument is the vector of angular\n        positions where the profile is to be calculated, followed by\n        all other arguments)\n        - 'target_profile_args' is a tuple with other arguments to pass to\n        'target_profile_function' (see above). The first two elements\n        are some measure of the maximum and minimum field\n        \"\"\"\n\n        B_III_data = self.superposition_B_III(alpha_B_rem)\n\n        # the above statement will return [x,y,B_x,B_y]. We have to calculate\n        # the magnitude to pass it to the magnetic profile data\n        B_III_data = calculate_magnitude(B_III_data)\n\n        phi_vector, B_profile = calculate_magnetic_profile(B_III_data,\n                                                           self.geometry_material_parameters).T\n\n        B_target_profile = target_profile_function(phi_vector,\n                                                   *target_profile_args)\n\n        phi_vector = np.deg2rad(phi_vector)\n\n        # use a \"least squares\" approach\n        B_lsq = np.square((B_profile - B_target_profile))\n        B_max = target_profile_args[0]\n        B_min = target_profile_args[1]\n\n        S = np.trapz(B_lsq, phi_vector) / (2 * np.pi * (B_max - B_min) ** 2)\n\n        return S\n\n    def calculate_functional(self,\n                             alpha_B_rem,\n                             functional_args=(calculate_instantaneous_profile,\n                                              (B_HIGH_LEVEL,B_LOW_LEVEL))):\n        \"\"\"\n        Return the objective functional based on  a vector of remanence angles.\n        The objective functional is defined as the difference between the\n        resulting profile and a target profile function,\n        and is to be minimized.\n\n        - 'alpha_B_rem' is a vector of (n_II + n_IV) remanences, where the\n        first n_II elements represent magnet II and the remaining elements\n        represent magnet IV\n        - `functional_args' is a tuple in the form\n        (target_profile_function, target_profile_args), where:\n            - 'target_profile_function' is a function with signature\n        'f(phi_vector, *args)' (the first argument is the vector of angular\n        positions where the profile is to be calculated, followed by\n        all other arguments)\n            - 'target_profile_args' is a tuple with other arguments to pass to\n        'target_profile_function' (see above)\n        \"\"\"\n\n        return self.calculate_functional_target(alpha_B_rem,\n                                                functional_args[0],\n                                                functional_args[1])\n\n    def calculate_functional_derivative(self,\n                                        alpha_B_rem,\n                                        i,\n                                        functional_args):\n        \"\"\"\n        Return the derivative of the functional in respect to the i-th element\n        of the remanence angles vector.\n\n        - 'alpha_B_rem' is a vector of (n_II + n_IV) remanences, where the\n        first n_II elements represent magnet II and the remaining elements\n        represent magnet IV\n        - 'i' is the element (0-based) in respect to which the derivative\n        is being evaluated\n        - 'functional_args' is a tuple with other arguments that are passed to\n        the functional method\n        \"\"\"\n\n        S = self.calculate_functional(alpha_B_rem,\n                                      functional_args)\n\n        alpha_B_rem_plus = alpha_B_rem.copy()\n        delta = 1e-6\n        alpha_B_rem_plus[i] = alpha_B_rem_plus[i] + delta\n\n        S_plus = self.calculate_functional(alpha_B_rem_plus,\n                                           functional_args)\n\n        dS = (S_plus - S) / delta\n        return dS\n\n    def calculate_funcional_derivative_second_order(self,\n                                                    alpha_B_rem,\n                                                    i,\n                                                    j,\n                                                    functional_args):\n        \"\"\"\n        Return the second-order derivative of the functional in respect\n        to the (i,j) elements (e.g. d/dalpha_i (dfunctional/dalpha_j))\n        \"\"\"\n\n        dS_j = self.calculate_functional_derivative(alpha_B_rem,\n                                                    j,\n                                                    functional_args)\n\n        alpha_B_rem_plus = alpha_B_rem.copy()\n        delta = 1e-6\n        alpha_B_rem_plus[i] = alpha_B_rem_plus[i] + delta\n\n        dS_j_plus = self.calculate_functional_derivative(alpha_B_rem_plus,\n                                                         j,\n                                                         functional_args)\n\n        ddS = (dS_j_plus - dS_j) / delta\n        return ddS\n\n    def calculate_functional_gradient(self,\n                                      alpha_B_rem,\n                                      functional_args=(\n                                              calculate_instantaneous_profile,\n                                              (B_HIGH_LEVEL,))):\n        \"\"\"\n        Return the gradient of the functional evaluated at point 'alpha_B_rem'.\n\n        Arguments:\n        - alpha_B_rem is a vector of (n_II + n_IV) remanences, where the\n        gradient is to be evaluated\n        - 'functional_args' is a tuple with other arguments that are passed to\n        the functional method\n        \"\"\"\n\n        n = len(alpha_B_rem)\n\n        grad = np.array([self.calculate_functional_derivative(alpha_B_rem,\n                                                              i,\n                                                              functional_args)\n                         for i in range(0, n)])\n        return grad\n\n    def calculate_functional_hessian(self,\n                                     alpha_B_rem,\n                                     functional_args=(\n                                             calculate_instantaneous_profile,\n                                             (B_HIGH_LEVEL,))):\n        \"\"\"\n        Return the Hessian matrix of the functional evaluated at\n        point 'alpha_B_rem'.\n\n        Arguments:\n        - alpha_B_rem is a vector of (n_II + n_IV) remanences, where the\n        gradient is to be evaluated\n        - 'functional_args' is a tuple with other arguments that are passed to\n        the functional method\n        \"\"\"\n\n        n = len(alpha_B_rem)\n\n        hess = np.array([\n            [self.calculate_funcional_derivative_second_order(alpha_B_rem,\n                                                              i,\n                                                              j,\n                                                              functional_args)\n             for j in range(0, n)]\n            for i in range(0, n)])\n        return hess\n\n    def _calculate_optimal_remanence_angles(self,\n                                            target_profile_function=calculate_instantaneous_profile,\n                                            target_profile_args=(\n                                                    B_HIGH_LEVEL,)):\n\n        \"\"\"\n        Calculate the optimal remanence angles that minimize the deviation\n        between the resulting profile and 'target_profile_function'.\n\n        Arguments:\n        ----------\n\n        - 'target_profile_function' is a function with signature\n        'f(phi_vector, *args)' (the first argument is the vector of angular\n        positions where the profile is to be calculated, followed by\n        all other arguments)\n        - 'target_profile_args' is a tuple with other arguments to pass to\n        'target_profile_function' (see above)\n\n\n        --\n        \"\"\"\n\n        n_II = self.geometry_material_parameters[\"n_II\"]\n        n_IV = self.geometry_material_parameters[\"n_IV\"]\n\n        n = n_II + n_IV\n\n        alpha_B_rem_0 = np.zeros(n)\n\n        # this function, to be used by the minimize function, has signature\n        # f(alpha_B_rem,args); i.e. it takes a candidate vector of\n        # remanence angles and a tuple of other arguments\n        objective_function = self.calculate_functional\n\n        # in the case of our functional formulation, the above function\n        # takes the name of the target profile and other parameters that are\n        # passed along\n        functional_args = (target_profile_function, target_profile_args)\n\n        bounds = [(0.0, 360.0) for i in range(0, n)]\n        \n        optres_g = minimize(objective_function,\n                            alpha_B_rem_0,\n                            args=(functional_args,),\n                            bounds=bounds,\n                            options={'disp': False})\n\n        self.optimization_results = optres_g\n        self.alpha_B_rem_optimal = optres_g.x\n\n    def get_optimal_remanence_angles(self,\n                                     target_profile_function=calculate_instantaneous_profile,\n                                     target_profile_args=(B_HIGH_LEVEL,)):\n\n        \"\"\"\n        Return the optimal remanence angles that minimize the deviation\n        between the resulting profile and 'target_profile_function'.\n\n        Arguments:\n        ----------\n\n        - 'target_profile_function' is a function with signature\n        'f(phi_vector, *args)' (the first argument is the vector of angular\n        positions where the profile is to be calculated, followed by\n        all other arguments)\n        - 'target_profile_args' is a tuple with other arguments to pass to\n        'target_profile_function' (see above)\n\n        \"\"\"\n\n        if self.alpha_B_rem_optimal is None:\n            self._calculate_optimal_remanence_angles(target_profile_function,\n                                                     target_profile_args)\n\n        return self.alpha_B_rem_optimal\n\n\nclass TeslaMaxModel:\n    \"\"\"\n    Class representing the full TeslaMax model.\n\n    To create an instance of the class, first you have to create a\n    TeslaMaxPreDesign object and an array of remanence angles,\n    and then pass these parameters along with  a path where to store the\n    generated text files:\n\n    >>> tmpd = TeslaMaxPreDesign({...})\n    >>> alpha_B_rem = [...]\n    >>> tmm = TeslaMaxModel(tmpd, alpha_B_rem, \"teslamax-results\")\n\n    If the path already exists, it will be cleaned up to avoid confusion\n    between different simulations.\n\n    If you want to preserve the data in 'path', set the argument 'clean'\n    to False in the constructor\n\n    \"\"\"\n\n    def __init__(self, teslamax_predesign, alpha_vector, path, clean=True):\n        self.pre_design = teslamax_predesign\n\n        self.params = expand_parameters_from_remanence_array(alpha_vector,\n                                                             self.pre_design.geometry_material_parameters,\n                                                             \"alpha_rem\")\n\n        self.path = Path(path)\n        if (self.path.exists()) and (self.path.is_dir()) and clean:\n            shutil.rmtree(str(self.path))\n\n        self.path.mkdir(exist_ok=True)\n\n        self.profile_data = np.empty(2)\n        self.calculate_B_profile = None\n        self.B_III_data = None\n        self.calculate_B_III_from_position = None\n        self.demagnetized_volume_fraction = None\n\n    def run(self, verbose=False):\n        \"\"\"\n        Change the current directory temporarily to the object's path\n        and run the TeslaMax program in it.\n\n        Also populates the appropriate fields with results from TeslaMax\n        \"\"\"\n\n        cwd = os.getcwd()\n        os.chdir(str(self.path))\n        run_teslamax_from_params(self.params, verbose)\n        os.chdir(cwd)\n\n        self.profile_data = self.get_profile_data()\n        self.calculate_B_profile = interp1d(self.profile_data[:, 0],\n                                            self.profile_data[:, 1],\n                                            kind='linear')\n\n        self.B_III_data = self.get_B_III_data()\n        self.calculate_B_III_from_position = NearestNDInterpolator(\n            self.B_III_data[:, :2],\n            self.B_III_data[:, 2:4])\n\n        self.demagnetized_volume_fraction = self.get_results_series()[\"Demagnetized fraction[%]\"]\n\n    def get_B_III_data(self):\n        \"\"\"\n        Return an array [x, y, Bx, By] for the air gap region\n        \"\"\"\n\n        B_III_file_path = self.path / B_III_FILENAME\n        B_III_full_data = read_comsol_data_file(str(B_III_file_path))\n\n        B_III_data = B_III_full_data[:, :4]\n        return B_III_data\n\n    def get_profile_data(self):\n        \"\"\"\n        Return an array of the magnetic profile data, where the first column\n        is the angle in degrees [0,360] and the second is the average magnetic\n        flux density in tesla\n        \"\"\"\n\n        profile_file_path = self.path / MAGNETIC_PROFILE_FILENAME\n        profile_data = read_comsol_profile_data(str(profile_file_path))\n\n        return profile_data\n    \n    def get_results_series(self):\n        \"\"\"\n        Return a Series with the main simulation results\n        \"\"\"\n        \n        results_filepath = self.path / MAIN_RESULTS_FILENAME\n\n        results_series = pd.read_csv(results_filepath,\n                                       sep=\" \",\n                                       squeeze=True,\n                                       index_col=0,\n                                       header=None)\n        results_series.index.name = None\n        results_series.name = \"COMSOL Main Results\"\n        \n        # add demagnetization fraction\n        results_series[\"Demagnetized fraction[%]\"] = results_series[\"A_demag[m2]\"] / results_series[\"A_magnet[m2]\"] * 100\n        return results_series", "meta": {"hexsha": "4ab498818691d73b1c551df7c097220165292c87", "size": 48440, "ext": "py", "lang": "Python", "max_stars_repo_path": "teslamax/__init__.py", "max_stars_repo_name": "GabrielNandi/Gabriel-Garcia-Nandi", "max_stars_repo_head_hexsha": "22a9c36d3186739cae6a50f1cc4cb55fdb7f34ee", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "teslamax/__init__.py", "max_issues_repo_name": "GabrielNandi/Gabriel-Garcia-Nandi", "max_issues_repo_head_hexsha": "22a9c36d3186739cae6a50f1cc4cb55fdb7f34ee", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "teslamax/__init__.py", "max_forks_repo_name": "GabrielNandi/Gabriel-Garcia-Nandi", "max_forks_repo_head_hexsha": "22a9c36d3186739cae6a50f1cc4cb55fdb7f34ee", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4352596928, "max_line_length": 121, "alphanum_fraction": 0.5731626755, "include": true, "reason": "import numpy,from scipy", "num_tokens": 10866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.17390067551778218}}
{"text": "# This module includes the functions that perform the \"pre-processing\": In short, they prepare the data structure\n# that is then processed by the \"Energy analysis\" and \"Exergy analysis\" functions, all in one go.\n#\n# The module is made of :\n# - One function that simply reads in the data that is already available from the original dataset\n\nimport numpy as np\nimport pandas as pd\n\n\n\ndef mainEngineProcessing(raw, processed, CONSTANTS, status, hd):\n    # This script summarizes all the functions that calculate the required data for the Main Engines different flows\n    # Reading existing values\n    processed = readMainEnginesExistingValues(raw, processed, CONSTANTS, hd)\n    # Calculating the main engines fuel flows\n    processed = mainEngineFuelFlowCalculation(raw, processed, CONSTANTS, hd)\n    # Calculating the main engines power output\n    processed = mainEnginePowerCalculation(processed, CONSTANTS)\n    # Calculating engine load, that is used many times later on\n    status = engineStatusCalculation(\"MainEngines\", raw, processed, CONSTANTS, status, hd)\n    # Calculating air and exhaust gas flows in the main engines\n    processed = mainEngineAirFlowCalculation(raw, processed, status, CONSTANTS)\n    # Calculating cooling flows\n    processed = engineCoolingSystemsCalculation(processed, CONSTANTS, status, \"MainEngines\")\n    return (processed, status)\n\n\ndef auxEngineProcessing(raw, processed, CONSTANTS, status, hd):\n    # This script summarizes all the functions that calculate the required data for the Main Engines different flows\n    # Reading existing values\n    processed = readAuxEnginesExistingValues(raw, processed, CONSTANTS, hd)\n    # Calculating the power, including the generator efficiency\n    processed = auxEnginePowerCalculation(processed, CONSTANTS)\n    # Calculating engine load, that is used many times later on\n    status = engineStatusCalculation(\"AuxEngines\", raw, processed, CONSTANTS, status, hd)\n    # Calculating the auxiliary engines fuel flows\n    processed = auxEngineFuelFlowCalculation(raw, processed, CONSTANTS, status)\n    # Calculate air and exhaust gas flows in the main engines\n    processed = auxEngineAirFlowCalculation(raw, processed, CONSTANTS)\n    # Calculating cooling flows\n    processed = engineCoolingSystemsCalculation(processed, CONSTANTS, status, \"AuxEngines\", )\n    return (processed, status)\n\n\n\ndef assumptions(raw, processed, CONSTANTS, hd):\n    # This function includes generic assumed values in the main structure\n    for name in CONSTANTS[\"General\"][\"NAMES\"][\"MainEngines\"]:\n        # The pressure at the turbocharger inlet is equal to the atmospheric pressure\n        processed[name][\"TC\"][\"Air_in\"][\"p\"] = CONSTANTS[\"General\"][\"P_ATM\"]\n    for name in CONSTANTS[\"General\"][\"NAMES\"][\"AuxEngines\"]:\n        # The pressure at the turbocharger inlet is equal to the atmospheric pressure\n        processed[name][\"TC\"][\"Air_in\"][\"p\"] = CONSTANTS[\"General\"][\"P_ATM\"]\n    processed[\"T_0\"] = raw[hd[\"ER13_SW_T_IN\"]] + 273.15\n    return processed\n\n\n\ndef readMainEnginesExistingValues(raw, processed, CONSTANTS, hd):\n    # This function only reads existing series. It does not do any pre-processing action.\n    for name in CONSTANTS[\"General\"][\"NAMES\"][\"MainEngines\"]:\n        # Reading main engines exhaust gas temperature, TC inlet and outlet\n        processed[name][\"Cyl\"][\"EG_out\"][\"T\"] = raw[hd[name + \"-TC_EG_T_IN\"]] + 273.15  # Measured before mixer with flow form bypass\n        processed[name][\"TC\"][\"EG_out\"][\"T\"] = raw[hd[name + \"-TC_EG_T_OUT\"]] + 273.15  # Measured after mixer with waste gate\n        # Reading main engines exhaust gas temperature, after HRSG. Only two of the four main engines have the HRSG\n        if name==\"ME2\" or name==\"ME3\":\n            processed[name][\"HRSG\"][\"EG_out\"][\"T\"] = raw[hd[name + \"-EGB_EG_T_OUT\"]] + 273.15\n            processed[name][\"HRSG\"][\"EG_in\"][\"T\"] = raw[hd[name + \"-TC_EG_T_OUT\"]] + 273.15\n        # Temperature in the engine room, i.e. inlet to the compressor of the TC\n        processed[name][\"TC\"][\"Air_in\"][\"T\"] = raw[hd[\"ER-FWD_AIR_T_\"]] + 273.15\n        processed[name][\"Comp\"][\"Air_in\"][\"T\"] = processed[name][\"TC\"][\"Air_in\"][\"T\"]\n        # Pressure of the charge air, at the compressor outlet (and, hence, at the cylinder inlet)\n        processed[name][\"TC\"][\"Air_out\"][\"p\"] = raw[hd[name+\"-CAC_AIR_P_OUT\"]] + 1\n        processed[name][\"Cyl\"][\"Air_in\"][\"p\"] = processed[name][\"TC\"][\"Air_out\"][\"p\"]\n        processed[name][\"BPvalve\"][\"Air_in\"][\"p\"] = processed[name][\"TC\"][\"Air_out\"][\"p\"]\n        # Reading the HT temperature before and after the main engine\n        # processed[name][\"CAC_HT\"][\"Water_out\"][\"T\"] = raw[name + \"_HT_water_T_out\"] # Note: this might be inconsistent\n        processed[name][\"JWC\"][\"HTWater_in\"][\"T\"] = raw[hd[name + \"-HT_FW_T_IN\"]] + 273.15\n        # Reading the LT temperature before the main engine\n        processed[name][\"CAC_LT\"][\"LTWater_in\"][\"T\"] = raw[hd[name + \"-LT_FW_T_IN\"]] + 273.15\n        # Reading the Lubricating oil temperature before and after the Lubricating Oil Cooler (hence, In is higher)\n        processed[name][\"LOC\"][\"LubOil_out\"][\"T\"] = raw[hd[name + \"-LOC_OIL_T_OUT\"]] + 273.15\n        #                           processed[name][\"LOC\"][\"LubOil_out\"][\"T\"] = raw[hd[name + \"_TC_OIL_T_OUT\"]]\n        # Reading fuel oil temperature before injection\n        processed[name][\"Cyl\"][\"FuelPh_in\"][\"T\"] = raw[hd[name + \"-CYL_FUEL_T_IN\"]] + 273.15\n        # Reading charge air temperature, after the charge air cooler (or at cylinder inlet)\n        processed[name][\"CAC_LT\"][\"Air_out\"][\"T\"] = raw[hd[name + \"-CAC_AIR_T_OUT\"]] + 273.15\n        processed[name][\"Cyl\"][\"Air_in\"][\"T\"] = processed[name][\"CAC_LT\"][\"Air_out\"][\"T\"]\n        # Reading Engine rpm\n        processed[name][\"Cyl\"][\"Power_out\"][\"omega\"] = raw[hd[name + \"__RPM_\"]]\n    return processed\n\n\n\n\n\n\n\ndef mainEngineFuelFlowCalculation(raw, processed, CONSTANTS, hd):\n    # This function calculates the engine\n    for name in CONSTANTS[\"General\"][\"NAMES\"][\"MainEngines\"]:\n        # This function calculates the fuel flow of the main engines\n        # In the case of the main engines, the fuel flow of an engine is calculated given its fuel\n        # rack position and its rotating speed.\n        fuel_rack_position = CONSTANTS[\"MainEngines\"][\"FRP_2_MFR\"][\"FRP_MIN\"][name] + (CONSTANTS[\"MainEngines\"][\"FRP_2_MFR\"][\"FRP_MAX\"][name]-CONSTANTS[\"MainEngines\"][\"FRP_2_MFR\"][\"FRP_MIN\"][name]) * raw[hd[name+\"__FRP_\"]]/100\n        # Temporarily, only the ISO fuel flow is calculated\n        processed[name][\"Cyl\"][\"FuelPh_in\"][\"mdot\"] = CONSTANTS[\"MainEngines\"][\"MFR_FUEL_DES_ISO\"] * (\n            (CONSTANTS[\"MainEngines\"][\"FRP_2_MFR\"][\"POLY\"][name][0] + CONSTANTS[\"MainEngines\"][\"FRP_2_MFR\"][\"POLY\"][name][1] * fuel_rack_position) /\n            (CONSTANTS[\"MainEngines\"][\"FRP_2_MFR\"][\"POLY\"][name][0] + CONSTANTS[\"MainEngines\"][\"FRP_2_MFR\"][\"POLY\"][name][1] * CONSTANTS[\"MainEngines\"][\"FRP_DES\"][name])) * (\n            processed[name][\"Cyl\"][\"Power_out\"][\"omega\"] / CONSTANTS[\"MainEngines\"][\"RPM_DES\"])\n        aaa = 0\n    return processed\n\n\ndef mainEnginePowerCalculation(processed, CONSTANTS):\n    # This function calculates the Power of the engine starting from the efficiency of the engine,\n    # which is calcualted starting from other available data\n    for name in CONSTANTS[\"General\"][\"NAMES\"][\"MainEngines\"]:\n        # Calculate fuel flow-based engine load\n        fuel_based_load = processed[name][\"Cyl\"][\"FuelPh_in\"][\"mdot\"] / CONSTANTS[\"MainEngines\"][\"MFR_FUEL_DES_ISO\"]\n        # Calculate ISO bsfc (break specific fuel consumption)\n        bsfc_iso = fuel_based_load.apply(polyvalHelperFunction, args=(CONSTANTS[\"MainEngines\"][                                                                  \"POLY_FUEL_LOAD_2_BSFC_ISO\"],))\n        # Corrects the bsfc from ISO conditions to \"real\" conditions\n        (bsfc,LHV) = bsfcISOCorrection(bsfc_iso,processed[name][\"Cyl\"][\"Air_in\"][\"T\"],processed[name][\"CAC_LT\"][\"LTWater_in\"][\"T\"],processed[name][\"Cyl\"][\"FuelPh_in\"][\"T\"],CONSTANTS)\n        # Calculates the real fuel flow using the ISO conversion\n        processed[name][\"Cyl\"][\"FuelPh_in\"][\"mdot\"] = processed[name][\"Cyl\"][\"FuelPh_in\"][\"mdot\"] * bsfc / bsfc_iso\n        # Calculates the power of the engine as mfr/bsfc, with unit conversion to get the output in kW\n        # Shaft energy out\n        processed[name][\"Cyl\"][\"Power_out\"][\"Wdot\"] = processed[name][\"Cyl\"][\"FuelPh_in\"][\"mdot\"] / bsfc * 1000 * 3600\n        # Chemical energy in the fuel\n        processed[name][\"Cyl\"][\"FuelCh_in\"][\"Wdot\"] = processed[name][\"Cyl\"][\"FuelPh_in\"][\"mdot\"] * LHV\n    return processed\n\n\n\n\n\ndef mainEngineAirFlowCalculation(raw, processed, status, CONSTANTS):\n    # This function calculates the different air and exhaust gas flows in the main engines, taking into account the\n    # presence of air bypass and exhaust wastegate valves\n    for name in CONSTANTS[\"General\"][\"NAMES\"][\"MainEngines\"]:\n        # Reading the pressure of the charge air after the compressor from the raw database\n        # Calculating the compressor isentropic efficiency\n        comp_isentropic_efficiency = processed[name][\"Cyl\"][\"Air_in\"][\"p\"].apply(polyvalHelperFunction,args=(CONSTANTS[\"MainEngines\"][\n                                                                                   \"POLY_PIN_2_ETA_IS\"],))\n        # Calculating the compressor's compression ratio\n        beta_comp = processed[name][\"TC\"][\"Air_out\"][\"p\"] / processed[name][\"TC\"][\"Air_in\"][\"p\"]\n        # Calculating the temperature after the compressor, based on ideal gas assumption\n        processed[name][\"TC\"][\"Air_out\"][\"T\"] = processed[name][\"TC\"][\"Air_in\"][\"T\"] * beta_comp**((\n            CONSTANTS[\"General\"][\"K_AIR\"]-1)/CONSTANTS[\"General\"][\"K_AIR\"]) / comp_isentropic_efficiency\n        # The state of the air at the outlet of the compressor, outlet of the TC block, and inlet of the bypass valve\n        #  are the same\n        processed[name][\"Comp\"][\"Air_out\"][\"T\"] = processed[name][\"TC\"][\"Air_out\"][\"T\"]\n        processed[name][\"BPvalve\"][\"Air_in\"][\"T\"] = processed[name][\"TC\"][\"Air_out\"][\"T\"]\n        # The same temperature is the inlet to the charge air cooler\n        processed[name][\"CAC_HT\"][\"Air_in\"][\"T\"] = processed[name][\"TC\"][\"Air_out\"][\"T\"]\n        # Calculating the air inflow aspired by the cylinder: calculated as inlet air density times the maximum volume,\n        # times the engine speed\n        processed[name][\"Cyl\"][\"Air_in\"][\"mdot\"] = CONSTANTS[\"MainEngines\"][\"V_SW\"] * (\n            processed[name][\"Cyl\"][\"Air_in\"][\"p\"] * 1e5) / (\n            CONSTANTS[\"General\"][\"R_AIR\"] * processed[name][\"Cyl\"][\"Air_in\"][\"T\"]) * (\n            processed[name][\"Cyl\"][\"Power_out\"][\"omega\"] / 60 / 2 * CONSTANTS[\"General\"][\"ETA_VOL\"]) * (\n            CONSTANTS[\"MainEngines\"][\"N_CYL\"])\n        processed[name][\"Cyl\"][\"EG_out\"][\"mdot\"] = processed[name][\"Cyl\"][\"Air_in\"][\"mdot\"] + processed[name][\"Cyl\"][\n            \"FuelPh_in\"][\"mdot\"]\n        # Here we calculate the bypass mass flow. THIS NEEDS TO BE CHECKED FOR CONSISTENCY (i.e. the bypass mass flow\n        #  should always be kind of low, and anyway only be seen at low to medium load).\n        # The equation is the result of a mass and energy balance over the whole engine\n        #dh_comp_on_eta = (CONSTANTS[\"General\"][\"CP_AIR\"] / CONSTANTS[\"MainEngines\"][\"ETA_MECH_TC\"] *\n        #    processed[name][\"Cyl\"][\"Air_in\"][\"mdot\"] * (\n        #    processed[name][\"Comp\"][\"Air_out\"][\"T\"] - processed[name][\"Comp\"][\"Air_in\"][\"T\"]))\n        #processed[name][\"BPvalve\"][\"Air_in\"][\"mdot\"] = (\n        #    processed[name][\"Cyl\"][\"EG_out\"][\"mdot\"] * CONSTANTS[\"General\"][\"CP_EG\"] * (\n        #       processed[name][\"Cyl\"][\"EG_out\"][\"T\"] - processed[name][\"TC\"][\"EG_out\"][\"T\"]) - dh_comp_on_eta) / (\n        #  CONSTANTS[\"General\"][\"CP_EG\"] * (\n        #   processed[name][\"TC\"][\"EG_out\"][\"T\"] - processed[name][\"Comp\"][\"Air_out\"][\"T\"]) -\n        #   dh_comp_on_eta)\n        #processed[name][\"BPvalve\"][\"Air_in\"][\"mdot\"] = (\n        #    CONSTANTS[\"General\"][\"CP_AIR\"] * processed[name][\"Cyl\"][\"Air_in\"][\"mdot\"] * (processed[name][\"Comp\"][\"Air_out\"][\"T\"] - processed[name][\"Comp\"][\"Air_in\"][\"T\"]) +\n        #    CONSTANTS[\"General\"][\"CP_EG\"] * CONSTANTS[\"MainEngines\"][\"ETA_MECH_TC\"] * (processed[name][\"Cyl\"][\"Air_in\"][\"mdot\"] - processed[name][\"Cyl\"][\"FuelPh_in\"][\"mdot\"]) *\n        #    (processed[name][\"Cyl\"][\"EG_out\"][\"T\"] - processed[name][\"TC\"][\"EG_out\"][\"T\"])) / (\n        #    CONSTANTS[\"General\"][\"CP_AIR\"] * (\n        #        processed[name][\"Comp\"][\"Air_in\"][\"T\"]+ CONSTANTS[\"MainEngines\"][\"ETA_MECH_TC\"] * processed[name][\"TC\"][\"EG_out\"][\"T\"] -\n        #        (1 + CONSTANTS[\"MainEngines\"][\"ETA_MECH_TC\"]) * processed[name][\"Comp\"][\"Air_out\"][\"T\"]))\n        # The new approximation is that the valve is only open for engine load below 50%, and when it is open it increases the flow by a fixed amount\n        processed[name][\"BPvalve\"][\"Air_in\"][\"mdot\"][:] = 0\n        processed[name][\"BPvalve\"][\"Air_in\"][\"mdot\"][(status[name][\"Load\"]<0.5) | ((status[name][\"Load\"]<0.6) & (processed[name][\"TC\"][\"EG_out\"][\"T\"]<620))] = CONSTANTS[\"MainEngines\"][\"BYPASS_FLOW\"]\n        processed[name][\"BPvalve\"][\"Air_out\"][\"mdot\"] = processed[name][\"BPvalve\"][\"Air_in\"][\"mdot\"]\n        # Calculating the temperature of the mixture after the merge between bypass and exhaust gas from the cylinders\n        processed[name][\"TC\"][\"EG_in\"][\"T\"] = (\n            processed[name][\"BPvalve\"][\"Air_in\"][\"mdot\"] * CONSTANTS[\"General\"][\"CP_AIR\"] * processed[name][\"Comp\"][\"Air_out\"][\"T\"] +\n            processed[name][\"Cyl\"][\"Air_in\"][\"mdot\"] * CONSTANTS[\"General\"][\"CP_EG\"] * processed[name][\"Cyl\"][\"EG_out\"][\"T\"]) / (\n            processed[name][\"Cyl\"][\"EG_out\"][\"mdot\"] * CONSTANTS[\"General\"][\"CP_EG\"] +\n            processed[name][\"BPvalve\"][\"Air_in\"][\"mdot\"] * CONSTANTS[\"General\"][\"CP_AIR\"])\n        # The air mass flow going through the compressor is equal to the sum of the air flow through the bypass valve and\n        # to the cylinders\n        processed[name][\"TC\"][\"Air_in\"][\"mdot\"] = processed[name][\"BPvalve\"][\"Air_in\"][\"mdot\"] + processed[name][\"Cyl\"][\"Air_in\"][\"mdot\"]\n        # Inlet and outlet flows to the compressor are equal\n        processed[name][\"TC\"][\"Air_out\"][\"mdot\"] = processed[name][\"TC\"][\"Air_in\"][\"mdot\"]\n        # The flow through the turbine is equal to the sum of the bypass flow and the exhaust coming from the cylinders\n        processed[name][\"TC\"][\"EG_in\"][\"mdot\"] = processed[name][\"BPvalve\"][\"Air_in\"][\"mdot\"] + processed[name][\"Cyl\"][\"EG_out\"][\"mdot\"]\n        processed[name][\"TC\"][\"EG_out\"][\"mdot\"] = processed[name][\"TC\"][\"EG_in\"][\"mdot\"]\n    return processed\n\n\n\n\n\n\ndef readAuxEnginesExistingValues(raw, processed,CONSTANTS,hd):\n    for name in CONSTANTS[\"General\"][\"NAMES\"][\"AuxEngines\"]:\n        # Reading main engines exhaust gas temperature, TC inlet and outlet\n        processed[name][\"TC\"][\"EG_in\"][\"T\"] = raw[hd[name + \"-TC_EG_T_IN1\"]] + 273.15\n        processed[name][\"TC\"][\"EG_out\"][\"T\"] = raw[hd[name + \"-TC_EG_T_OUT\"]] + 273.15\n        # Reading main engines exhaust gas temperature, after HRSG\n        processed[name][\"HRSG\"][\"EG_out\"][\"T\"] = raw[hd[name + \"-EGB_EG_T_OUT\"]] + 273.15\n        processed[name][\"HRSG\"][\"EG_in\"][\"T\"] = processed[name][\"TC\"][\"EG_out\"][\"T\"] + 273.15\n        # Temperature in the engine room, i.e. inlet to the compressor of the TC\n        processed[name][\"TC\"][\"Air_in\"][\"T\"] = raw[hd[\"ER_AIR_T_\"]] + 273.15\n        # Reading the HT temperature before and after the main engine\n        processed[name][\"JWC\"][\"HTWater_in\"][\"T\"] = raw[hd[name + \"-HT_FW_T_IN\"]] + 273.15\n        # Reading the LT temperature before the main engine\n        processed[name][\"CAC_LT\"][\"LTWater_in\"][\"T\"] = raw[hd[name + \"-LT-CAC_FW_T_IN\"]] + 273.15\n        # Reading the Lubricating oil temperature before and after the Lubricating oil cooler\n        processed[name][\"LOC\"][\"LubOil_out\"][\"T\"] = raw[hd[name + \"-LOC_OIL_T_OUT\"]] + 273.15\n        # Reading fuel oil temperature before injection\n        processed[name][\"Cyl\"][\"FuelPh_in\"][\"T\"] = raw[hd[name + \"-CYL_FUEL_T_IN\"]] + 273.15\n        # Reading charge air temperature.\n        processed[name][\"CAC_LT\"][\"Air_out\"][\"T\"] = raw[hd[name + \"-CAC_AIR_T_OUT\"]] + 273.15\n        processed[name][\"CAC_LT\"][\"Air_out\"][\"p\"] = raw[hd[name + \"-CAC_AIR_P_OUT\"]] + 1\n        processed[name][\"AG\"][\"Power_out\"][\"Wdot\"] = raw[hd[name + \"_POWER_Wdot_OUT\"]]\n        processed[name][\"Cyl\"][\"Air_in\"][\"T\"] = processed[name][\"CAC_LT\"][\"Air_out\"][\"T\"]\n        processed[name][\"Cyl\"][\"Air_in\"][\"p\"] = processed[name][\"CAC_LT\"][\"Air_out\"][\"p\"]\n    return processed\n\n\ndef auxEnginePowerCalculation(processed, CONSTANTS):\n    # Calculating the power of the auxiliary engines\n    for name in CONSTANTS[\"General\"][\"NAMES\"][\"AuxEngines\"]:\n        load = processed[name][\"AG\"][\"Power_out\"][\"Wdot\"] / CONSTANTS[\"AuxiliaryEngines\"][\"MCR\"]\n        eta_AG =  CONSTANTS[\"AuxiliaryEngines\"][\"AG\"][\"ETA_DES\"] - CONSTANTS[\"AuxiliaryEngines\"][\"AG\"][\"A\"] * np.exp(\n            -CONSTANTS[\"AuxiliaryEngines\"][\"AG\"][\"k\"] * (load))\n        processed[name][\"AG\"][\"Power_in\"][\"Wdot\"] = processed[name][\"AG\"][\"Power_out\"][\"Wdot\"] / eta_AG\n        processed[name][\"AG\"][\"Losses\"][\"Wdot\"] = processed[name][\"AG\"][\"Power_in\"][\"Wdot\"] - processed[name][\"AG\"][\"Power_out\"][\"Wdot\"]\n        processed[name][\"Cyl\"][\"Power_out\"][\"Wdot\"] = processed[name][\"AG\"][\"Power_in\"][\"Wdot\"]\n\ndef auxEngineFuelFlowCalculation(raw, processed, CONSTANTS, status):\n    # Proceeding with the auxiliary engines\n    for name in CONSTANTS[\"General\"][\"NAMES\"][\"AuxEngines\"]:\n        # First we calculate the ISO break specific fuel consumption (BSFC)\n        bsfc_iso = status[name][\"Load\"].apply(polyvalHelperFunction, args=(CONSTANTS[\"AuxEngines\"][\n                                                                          \"POLY_LOAD_2_ISO_BSFC\"],))\n        (bsfc, LHV) = bsfcISOCorrection(bsfc_iso, processed[name][\"Cyl\"][\"Air_in\"][\"T\"], processed[name][\"CAC_LT\"][\n                \"LTWater_in\"][\"T\"], processed[name][\"Cyl\"][\"FuelPh_in\"][\"T\"], CONSTANTS)\n        processed[name][\"Cyl\"][\"FuelPh_in\"][\"mdot\"] = bsfc * processed[name][\"Cyl\"][\"Power_out\"][\"Wdot\"] / 3600 / 1000\n        processed[name][\"Cyl\"][\"FuelCh_in\"][\"Wdot\"] = processed[name][\"Cyl\"][\"FuelPh_in\"][\"mdot\"] * LHV\n    return processed\n\n\ndef auxEngineAirFlowCalculation(raw, processed, CONSTANTS):\n    # This function calculates the different air and exhaust gas flows in the main engines, taking into account the\n    # presence of air bypass and exhaust wastegate valves\n    for name in CONSTANTS[\"General\"][\"NAMES\"][\"AuxEngines\"]:\n        # Reading the pressure of the charge air after the compressor from the raw database\n        # Calculating the compressor isentropic efficiency\n        comp_isentropic_efficiency = processed[name][\"Cyl\"][\"Air_in\"][\"p\"].apply(polyvalHelperFunction,args=(CONSTANTS[\"AuxEngines\"][\n                                                                                   \"POLY_PIN_2_ETA_IS\"],))\n        # Calculating the compressor's compression ratio\n        beta_comp = processed[name][\"TC\"][\"Air_out\"][\"p\"] / processed[name][\"TC\"][\"Air_in\"][\"p\"]\n        # Calculating the temperature after the compressor, based on ideal gas assumption\n        processed[name][\"TC\"][\"Air_out\"][\"T\"] = processed[name][\"TC\"][\"Air_in\"][\"T\"] * (1 + beta_comp**((\n            CONSTANTS[\"General\"][\"K_AIR\"]-1)/CONSTANTS[\"General\"][\"K_AIR\"])) / comp_isentropic_efficiency\n        # The state of the air at the outlet of the compressor, outlet of the TC block, and inlet of the bypass valve\n        #  are the same\n        processed[name][\"Comp\"][\"Air_out\"][\"T\"] = processed[name][\"TC\"][\"Air_out\"][\"T\"]\n        processed[name][\"BPvalve\"][\"Air_in\"][\"T\"] = processed[name][\"TC\"][\"Air_out\"][\"T\"]\n        # The same temperature is the inlet to the charge air cooler\n        processed[name][\"CAC_HT\"][\"Air_in\"][\"T\"] = processed[name][\"TC\"][\"Air_out\"][\"T\"]\n        # Calculating the air inflow aspired by the cylinder: calculated as inlet air density times the maximum volume,\n        # times the engine speed\n        processed[name][\"Cyl\"][\"Air_in\"][\"mdot\"] = CONSTANTS[\"MainEngines\"][\"V_MAX\"] * (\n            processed[name][\"Cyl\"][\"Air_in\"][\"p\"] * 1e5) / (\n            CONSTANTS[\"General\"][\"R_AIR\"] / processed[name][\"Cyl\"][\"Air_in\"][\"T\"]) * (\n            processed[name][\"Cyl\"][\"Power_out\"][\"omega\"] / 60 / 2 * CONSTANTS[\"General\"][\"ETA_VOL\"]) * (\n            CONSTANTS[\"AuxEngines\"][\"N_CYL\"])\n        processed[name][\"Cyl\"][\"EG_out\"][\"mdot\"] = processed[name][\"Cyl\"][\"Air_in\"][\"mdot\"] + processed[name][\"Cyl\"][\n            \"FuelPh_in\"][\"mdot\"]\n        # Here we calculate the bypass mass flow. THIS NEEDS TO BE CHECKED FOR CONSISTENCY (i.e. the bypass mass flow\n        #  should always be kind of low, and anyway only be seen at low to medium load).\n        # The equation is the result of a mass and energy balance over the whole engine\n        processed[name][\"BPvalve\"][\"Air_in\"][\"mdot\"] = (\n            processed[name][\"Cyl\"][\"EG_out\"][\"mdot\"] * CONSTANTS[\"General\"][\"CP_EG\"] * (\n                processed[name][\"TC\"][\"EG_in\"][\"T\"] - processed[name][\"TC\"][\"EG_out\"][\"T\"]) * CONSTANTS[\"MainEngines\"][\"ETA_MECH_TC\"] -\n            CONSTANTS[\"General\"][\"CP_AIR\"] * processed[name][\"Cyl\"][\"Air_in\"][\"mdot\"] * (\n                processed[name][\"Comp\"][\"Air_out\"][\"T\"] - processed[name][\"Comp\"][\"Air_in\"][\"T\"])) / (\n            CONSTANTS[\"General\"][\"CP_AIR\"] * (processed[name][\"Comp\"][\"Air_out\"][\"T\"] - processed[name][\"Comp\"][\"Air_in\"][\"T\"]) -\n            CONSTANTS[\"General\"][\"CP_EG\"] * CONSTANTS[\"MainEngines\"][\"ETA_MECH_TC\"] * (\n                processed[name][\"TC\"][\"EG_in\"][\"T\"] - processed[name][\"TC\"][\"EG_out\"][\"T\"]))\n        processed[name][\"BPvalve\"][\"Air_out\"][\"mdot\"] = processed[name][\"BPvalve\"][\"Air_in\"][\"mdot\"]\n        # The air mass flow going through the compressor is equal to the sum of the air flow through the bypass valve and\n        # to the cylinders\n        processed[name][\"TC\"][\"Air_in\"][\"mdot\"] = processed[name][\"BPvalve\"][\"Air_in\"][\"mdot\"] + processed[name][\"Cyl\"][\"Air_in\"][\"mdot\"]\n        # Inlet and outlet flows to the compressor are equal\n        processed[name][\"TC\"][\"Air_out\"][\"mdot\"] = processed[name][\"TC\"][\"Air_in\"][\"mdot\"]\n        # The flow through the turbine is equal to the sum of the bypass flow and the exhaust coming from the cylinders\n        processed[name][\"TC\"][\"EG_in\"][\"mdot\"] = processed[name][\"BPvalve\"][\"Air_in\"][\"mdot\"] + processed[name][\"Cyl\"][\"EG_out\"][\"mdot\"]\n        # Calculating the temperature of the mixture after the merge between bypass and exhaust gas from the cylinders\n        processed[name][\"Cyl\"][\"EG_out\"][\"T\"] = 298 + (\n            processed[name][\"TC\"][\"EG_in\"][\"mdot\"] * CONSTANTS[\"General\"][\"CP_EG\"] * (processed[name][\"TC\"][\"EG_in\"][\"T\"] - 298) -\n            processed[name][\"BPvalve\"][\"Air_in\"][\"mdot\"] * CONSTANTS[\"General\"][\"CP_AIR\"] * (processed[name][\"TC\"][\"Air_out\"][\"T\"] - 298)) / (\n            processed[name][\"Cyl\"][\"EG_out\"][\"mdot\"] * CONSTANTS[\"General\"][\"CP_EG\"])\n    return processed\n\n\ndef readOtherExistingValues(raw, processed):\n    # Other components\n    processed[\"Other\"][\"SWC13\"][\"SeaWater\"][\"T_out\"] = raw[\"SWC13_SeaWater_Tout\"]  # CHECK IF IT IS IN OR OUT\n    processed[\"Other\"][\"SWC24\"][\"SeaWater\"][\"T_out\"] = raw[\"SWC24_SeaWater_Tout\"]  # CHECK IF IT IS IN OR OUT\n    processed[\"Other\"][\"SWC24\"][\"SeaWater\"][\"T_in\"] = raw[\"SeaWater_T\"]\n    processed[\"Other\"][\"SWC24\"][\"SeaWater\"][\"T_in\"] = raw[\"SeaWater_T\"]\n    return processed\n\ndef engineStatusCalculation(type, raw, processed, CONSTANTS, status, hd):\n    for name in CONSTANTS[\"General\"][\"NAMES\"][type]:\n        status[name][\"Load\"] = processed[name][\"Cyl\"][\"Power_out\"][\"Wdot\"] / CONSTANTS[type][\"MCR\"]\n        # We consider that the engines are on if the RPM of the turbocharger is higher than 5000 RPM\n        #status[name][\"OnOff\"] = (status[name][\"Load\"] > 0.05) & (processed[name][\"Cyl\"][\"Power_out\"][\"omega\"] > CONSTANTS[\"MainEngines\"][\"RPM_DES\"] * 0.1)\n        status[name][\"OnOff\"] = raw[hd[name+\"-TC__RPM_\"]] > 5000\n    return status\n\n\ndef engineCoolingSystemsCalculation(processed, CONSTANTS, status, engine_type):\n    # This function calculates the different flows related to the cooling systems of the main engines.\n    for name in CONSTANTS[\"General\"][\"NAMES\"][engine_type]:\n        # Calculating the total energy flow going to the cooling systems, based on the energy balance on the engine\n        energy_2_cooling = (processed[name][\"Cyl\"][\"FuelCh_in\"][\"Wdot\"] -\n            processed[name][\"Cyl\"][\"Power_out\"][\"Wdot\"] +\n            CONSTANTS[\"General\"][\"CP_HFO\"] * processed[name][\"Cyl\"][\"FuelPh_in\"][\"mdot\"] *\n                (processed[name][\"Cyl\"][\"FuelPh_in\"][\"T\"] - processed[\"T_0\"]) -\n            CONSTANTS[\"General\"][\"CP_EG\"] * processed[name][\"TC\"][\"EG_out\"][\"mdot\"] *\n                (processed[name][\"TC\"][\"EG_out\"][\"T\"] - processed[\"T_0\"]) +\n            CONSTANTS[\"General\"][\"CP_AIR\"] * processed[name][\"TC\"][\"Air_in\"][\"mdot\"] *\n                (processed[name][\"TC\"][\"Air_in\"][\"T\"] - processed[\"T_0\"]))\n        # Calculating the energy going to the charge air cooler, based on the estimated temperatures on the air line\n        energy_2_cac = CONSTANTS[\"General\"][\"CP_AIR\"] * processed[name][\"Cyl\"][\"Air_in\"][\"mdot\"] * (processed[name][\"TC\"][\"Air_out\"][\"T\"] - processed[name][\"Cyl\"][\"Air_in\"][\"T\"])\n        # Calculating the energy going to the HT cooling systems, based on interpolation from the project guide\n        energy_2_ht_theoric = status[name][\"Load\"].apply(piecewisePolyvalHelperFunction,args=(CONSTANTS[engine_type][\"POLY_LOAD_2_QDOT_HT\"],)) * CONSTANTS[engine_type][\"QDOT_HT_DES\"]\n        energy_2_lt_theoric = status[name][\"Load\"].apply(piecewisePolyvalHelperFunction,args=(CONSTANTS[engine_type][\"POLY_LOAD_2_QDOT_LT\"],)) * CONSTANTS[engine_type][\"QDOT_LT_DES\"]\n        # The values calculated based on the project guide are reconciled based on the energy balance\n        energy_2_ht = energy_2_cooling * energy_2_ht_theoric / (energy_2_ht_theoric + energy_2_lt_theoric)\n        energy_2_lt = energy_2_cooling - energy_2_ht\n        # The energy going to the CAC, HT stage is calculated assuming a 85% effectiveness of the heat exchanger\n        energy_2_cac_ht = CONSTANTS[engine_type][\"EPS_CAC_HTSTAGE\"] * processed[name][\"TC\"][\"Air_in\"][\"mdot\"] * CONSTANTS[\"General\"][\"CP_AIR\"] * (\n            processed[name][\"TC\"][\"Air_out\"][\"T\"] - processed[name][\"CAC_HT\"][\"HTWater_in\"][\"T\"])\n        # The energy going to the CAC, LT stage results as a consequence by thermal balance over the CAC\n        energy_2_cac_lt = energy_2_cac - energy_2_cac_ht\n        # The energy to the JWC results as a balance over the HT cooling systems\n        energy_2_jwc = energy_2_ht - energy_2_cac_ht\n        # The energy to the LOC results as a balance over the LT cooling systems\n        energy_2_loc = energy_2_lt - energy_2_cac_lt\n        # For all pumps, it is here assumed that the flow scales only with the speed of the engine (biiiiig assumption)\n        processed[name][\"LOC\"][\"LTWater_in\"][\"mdot\"] = CONSTANTS[engine_type][\"MFR_LT\"] * processed[name][\"Cyl\"][\"Power_out\"][\"omega\"] / CONSTANTS[engine_type][\"RPM_DES\"]\n        processed[name][\"JWC\"][\"HTWater_in\"][\"mdot\"] = CONSTANTS[engine_type][\"MFR_HT\"] * processed[name][\"Cyl\"][\"Power_out\"][\"omega\"] / CONSTANTS[engine_type][\"RPM_DES\"]\n        # Asssigning values based on mass balances\n        processed[name][\"LOC\"][\"LTWater_out\"][\"mdot\"] = processed[name][\"LOC\"][\"LTWater_in\"][\"mdot\"]\n        processed[name][\"CAC_LT\"][\"LTWater_out\"][\"mdot\"] = processed[name][\"LOC\"][\"LTWater_in\"][\"mdot\"]\n        processed[name][\"CAC_LT\"][\"LTWater_out\"][\"mdot\"] = processed[name][\"LOC\"][\"LTWater_in\"][\"mdot\"]\n        processed[name][\"JWC\"][\"HTWater_out\"][\"mdot\"] = processed[name][\"JWC\"][\"HTWater_in\"][\"mdot\"]\n        processed[name][\"CAC_HT\"][\"HTWater_in\"][\"mdot\"] = processed[name][\"JWC\"][\"HTWater_in\"][\"mdot\"]\n        processed[name][\"CAC_HT\"][\"HTWater_out\"][\"mdot\"] = processed[name][\"JWC\"][\"HTWater_in\"][\"mdot\"]\n        # Finally, the temperatures in the flows are calculated based on the calculated energy and mass flow values\n        # For LT, first we have the CAC, then the LOC\n        processed[name][\"CAC_LT\"][\"LTWater_out\"][\"T\"] = processed[name][\"CAC_LT\"][\"LTWater_in\"][\"T\"] + energy_2_cac_lt / processed[name][\"CAC_LT\"][\"LTWater_out\"][\"mdot\"] / CONSTANTS[\"General\"][\"CP_WATER\"]\n        processed[name][\"LOC\"][\"LTWater_in\"][\"T\"] = processed[name][\"CAC_LT\"][\"LTWater_out\"][\"T\"]\n        processed[name][\"LOC\"][\"LTWater_out\"][\"T\"] = processed[name][\"LOC\"][\"LTWater_in\"][\"T\"] + energy_2_loc / processed[name][\"LOC\"][\"LTWater_out\"][\"mdot\"] / CONSTANTS[\"General\"][\"CP_WATER\"]\n        # For HT, first we have the JWC, then the CAC, HT\n        processed[name][\"JWC\"][\"HTWater_out\"][\"T\"] = processed[name][\"JWC\"][\"HTWater_in\"][\"T\"] + energy_2_jwc / processed[name][\"JWC\"][\"HTWater_out\"][\"mdot\"] / CONSTANTS[\"General\"][\"CP_WATER\"]\n        processed[name][\"CAC_HT\"][\"HTWater_in\"][\"T\"] = processed[name][\"JWC\"][\"HTWater_out\"][\"T\"]\n        processed[name][\"CAC_HT\"][\"HTWater_out\"][\"T\"] = processed[name][\"CAC_HT\"][\"HTWater_in\"][\"T\"] + energy_2_cac_ht / processed[name][\"CAC_HT\"][\"HTWater_out\"][\"mdot\"] / CONSTANTS[\"General\"][\"CP_WATER\"]\n        # For the LOC, we know the outlet (lower) temperature, we calculate the inlet temperature\n        processed[name][\"LOC\"][\"LubOil_out\"][\"mdot\"][:] = CONSTANTS[engine_type][\"MFR_LO\"]\n        processed[name][\"LOC\"][\"LubOil_in\"][\"mdot\"][:] = CONSTANTS[engine_type][\"MFR_LO\"]\n        processed[name][\"LOC\"][\"LubOil_in\"][\"T\"] = processed[name][\"LOC\"][\"LubOil_out\"][\"T\"] + energy_2_loc / processed[name][\"LOC\"][\"LubOil_out\"][\"mdot\"] / CONSTANTS[\"General\"][\"CP_LO\"]\n    return processed\n\n\n\ndef bsfcISOCorrection(bsfc_ISO, charge_air_temp, charge_air_cooling_temp, fuel_temp, CONSTANTS):\n    # This function calculates the \"real\" BSFC starting from the ISO corrected one and from measurements of\n    # - Charge air temperature [K]\n    # - Charge air coolant temperature [K]\n    # - Fuel LHV [MJ/kg]\n    # - Mechanical efficiency (often assumed at 0.8)\n\n    # Assigning the value of the LHV depending on the fuel temperature\n    LHV = pd.Series(0,index=charge_air_temp.index)\n    LHV[fuel_temp < 70] = CONSTANTS[\"General\"][\"LHV_MDO\"] # If T_fuel<70, it is Diesel\n    LHV[fuel_temp >= 70] = CONSTANTS[\"General\"][\"LHV_HFO\"] # If T_fuel>70, it is HFO\n    # Converting existing data (expected in the form of dataSeries\n    if isinstance(charge_air_temp,pd.Series):\n        T_ca = charge_air_temp.values\n    else:\n        print(\"Error: Expecting a pandas data series as data type\")\n    if isinstance(charge_air_cooling_temp,pd.Series):\n        T_lt = charge_air_cooling_temp.values\n    else:\n        print(\"Error: Expecting a pandas data series as data type\")\n    # Providing reference values for the variables\n    k = (CONSTANTS[\"General\"][\"ISO\"][\"T_CA\"] / T_ca)**1.2 * (CONSTANTS[\"General\"][\"ISO\"][\"T_LT\"] / T_lt)\n    alpha = k - 0.7 * (1 - k) * (1/CONSTANTS[\"General\"][\"ISO\"][\"ETA_MECH\"] - 1)\n    beta = k / alpha\n    # Final calculation of the BSFC\n    bsfc = bsfc_ISO * CONSTANTS[\"General\"][\"ISO\"][\"LHV\"] / LHV * beta\n    return (bsfc, LHV)\n\n\ndef polyvalHelperFunction(x,p):\n    # The problem with applying \"polyval\" to data series is that the \"x\" is the second argument of the function\n    # instead of being the first. So we use this function to invert the two, waiting to find a better way\n    output = np.polyval(p,x)\n    return output\n\ndef piecewisePolyvalHelperFunction(x,p):\n    # The problem with applying \"polyval\" to data series is that the \"x\" is the second argument of the function\n    # instead of being the first. So we use this function to invert the two, waiting to find a better way\n    output = np.piecewise(x, [x < 0.5 , x >= 0.5], [np.polyval(p[1],x) , np.polyval(p[0],x)])\n    return output\n", "meta": {"hexsha": "3be97d297b999f8d25eca05e2cacfb3991ad3c2a", "size": 31825, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python files/preprocessing_old.py", "max_stars_repo_name": "francescobaldi86/Ecos2015PaperExtension", "max_stars_repo_head_hexsha": "486cbb770c5394938f08af3d880d1300d71dc753", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-09-05T10:58:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-21T07:28:36.000Z", "max_issues_repo_path": "Python files/preprocessing_old.py", "max_issues_repo_name": "francescobaldi86/Ecos2015PaperExtension", "max_issues_repo_head_hexsha": "486cbb770c5394938f08af3d880d1300d71dc753", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python files/preprocessing_old.py", "max_forks_repo_name": "francescobaldi86/Ecos2015PaperExtension", "max_forks_repo_head_hexsha": "486cbb770c5394938f08af3d880d1300d71dc753", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-03-14T19:30:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-10T10:07:43.000Z", "avg_line_length": 74.1841491841, "max_line_length": 226, "alphanum_fraction": 0.6407541241, "include": true, "reason": "import numpy", "num_tokens": 8165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.33458944788835565, "lm_q1q2_score": 0.17382635227817947}}
{"text": "# paper: \n# \tyolo1: https://arxiv.org/abs/1506.02640\n# \tyolo2: https://arxiv.org/abs/1612.08242\n# \tyolo3: https://pjreddie.com/media/files/papers/YOLOv3.pdf\n# Author: Charles\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport sys\nsys.path.append('../')\nfrom utils.cfg_utils import *\nfrom utils.standard_utils import *\nfrom loss_module.region_loss import RegionLoss\nfrom layers.yolo_layer import YoloLayer\nfrom cfg import *\n\n\n# pad:\n# \tpre-Tensor <Right and Bottom> expand 1 dim.\n# \t(the same as pre-final <Right and Bottom>)\n# maxpool2d:\n# \tstride: 1\n# \tk_size: (2, 2)\n# Input:\n# \t(batch_size, in_channels, w, h)\n# Output:\n# \tthe same as Input.\nclass MaxPoolStride1(nn.Module):\n\tdef __init__(self):\n\t\tsuper(MaxPoolStride1, self).__init__()\n\tdef forward(self, x):\n\t\tx_pad = F.pad(x, (0, 1, 0, 1), mode='replicate')\n\t\tx = F.max_pool2d(x_pad, 2, stride=1)\n\t\treturn x\n\n\n# Function:\n# \texpand H, W using their own elements\n# Example(stride=2):\n# \t(0, 0, ., .):\n# \t\torigin:\n# \t\t\t1 2\n# \t\t\t3 4\n# \t\tchanged:\n# \t\t\t1 1 2 2\n# \t\t\t1 1 2 2\n# \t\t\t3 3 4 4\n# \t\t\t3 3 4 4\n# Input:\n# \t(batch_size, in_channels, h, w)\n# Output:\n# \t(batch_size, in_channels, h*stride, w*stride)\nclass Upsample(nn.Module):\n\tdef __init__(self, stride=2):\n\t\tsuper(Upsample, self).__init__()\n\t\tself.stride = stride\n\tdef forward(self, x):\n\t\tassert(x.data.dim() == 4)\n\t\tB = x.data.size(0)\n\t\tC = x.data.size(1)\n\t\tH = x.data.size(2)\n\t\tW = x.data.size(3)\n\t\tx = x.view(B, C, H, 1, W, 1).expand(B, C, H, self.stride, W, self.stride).contiguous().view(B, C, H*self.stride, W*self.stride)\n\t\treturn x\n\n\n# Function:\n# \t(B, C, H, W) -> (B, hs*ws*C, H//hs, W//ws)\n# \tGet each C using stride that feels like skipping\n# Input:\n# \t(batch_size, in_channels, h, w)\n# Output:\n# \t(batch_size, ws*hs*C, H//hs, W//ws)\nclass Reorg(nn.Module):\n\tdef __init__(self, stride=2):\n\t\tsuper(Reorg, self).__init__()\n\t\tself.stride = stride\n\tdef forward(self, x):\n\t\tassert(x.data.dim() == 4)\n\t\tB = x.data.size(0)\n\t\tC = x.data.size(1)\n\t\tH = x.data.size(2)\n\t\tW = x.data.size(3)\n\t\tassert(H % self.stride == 0)\n\t\tassert(W % self.stride == 0)\n\t\tw_stride = self.stride\n\t\th_stride = self.stride\n\t\t# (B, C, H, W) -> (B, C, H//hs, W//ws, hs, ws)\n\t\tx = x.view(B, C, H//h_stride, h_stride, W//w_stride, w_stride).transpose(3, 4).contiguous()\n\t\t# (B, C, H//hs, W//ws, hs, ws) -> (B, C, hs*ws, -1)\n\t\tx = x.view(B, C, (H//h_stride)*(W//w_stride), h_stride*w_stride).transpose(2, 3).contiguous()\n\t\t# (B, C, hs*ws, -1) -> (B, hs*ws, C, H//hs, W//ws)\n\t\tx = x.view(B, C, h_stride*w_stride, H//h_stride, W//w_stride).transpose(1, 2).contiguous()\n\t\t# (B, hs*ws, C, H//hs, W//ws) -> (B, hs*ws*C, H//hs, W//ws)\n\t\tx = x.view(B, h_stride*w_stride*C, H//h_stride, W//w_stride)\n\t\treturn x\n\n\n# Function:\n# \tcompute all elements' average each (H, W)\n# Input:\n# \t(N, C, H, W)\n# Output:\n# \t(N, C)\nclass GlobalAvgPool2d(nn.Module):\n\tdef __init__(self):\n\t\tsuper(GlobalAvgPool2d, self).__init__()\n\tdef forward(self, x):\n\t\tN = x.data.size(0)\n\t\tC = x.data.size(1)\n\t\tH = x.data.size(2)\n\t\tW = x.data.size(3)\n\t\tx = F.avg_pool2d(x, (H, W))\n\t\tx = x.view(N, C)\n\t\treturn x\n\n\n# Function:\n# \tfor route and shortcut\nclass EmptyModule(nn.Module):\n\tdef __init__(self):\n\t\tsuper(EmptyModule, self).__init__()\n\tdef forward(self, x):\n\t\treturn x\n\n\n# Darknet\n# Support route shortcut and reorg\nclass Darknet(nn.Module):\n\tdef __init__(self, cfgfile):\n\t\tsuper(Darknet, self).__init__()\n\t\tself.is_yolo3 = False\n\t\tself.blocks = parse_cfg(cfgfile)\n\t\tself.losses = []\n\t\tself.models = self.create_network(self.blocks)\n\t\t# Because of all yolo layers' anchors, num_anchors, anchor_step and num_classes is the same.\n\t\tself.loss = self.models[len(self.models)-1]\n\t\tself.width = int(self.blocks[0]['width'])\n\t\tself.height = int(self.blocks[0]['height'])\n\t\tif self.blocks[(len(self.blocks)-1)]['type'] == 'region' or 'yolo':\n\t\t\tself.anchors = self.loss.anchors\n\t\t\tself.num_anchors = self.loss.num_anchors\n\t\t\tself.anchor_step = self.loss.anchor_step\n\t\t\tself.num_classes = self.loss.num_classes\n\t\tself.header = torch.IntTensor([0, 0, 0, 0, 0])\n\t\tself.seen = 0\n\t\t# self.multiGPU = False\n\tdef forward(self, x):\n\t\tind = -2\n\t\tis_yolo3 = self.is_yolo3\n\t\tyolo_outs = []\n\t\toutputs = dict()\n\t\t# out_boxes = []\n\t\tfor block in self.blocks:\n\t\t\tind += 1\n\t\t\tif block['type'] == 'net':\n\t\t\t\tcontinue\n\t\t\telif block['type'] in ['convolutional', 'maxpool', 'reorg', 'upsample', 'avgpool', 'softmax', 'connected']:\n\t\t\t\tx = self.models[ind](x)\n\t\t\t\toutputs[ind] = x\n\t\t\telif block['type'] == 'route':\n\t\t\t\tlayers = block['layers'].split(',')\n\t\t\t\tlayers = [int(i) if int(i) > 0 else int(i)+ind for i in layers]\n\t\t\t\tif len(layers) == 1:\n\t\t\t\t\tx = outputs[layers[0]]\n\t\t\t\t\toutputs[ind] = x\n\t\t\t\telif len(layers) == 2:\n\t\t\t\t\tx1 = outputs[layers[0]]\n\t\t\t\t\tx2 = outputs[layers[1]]\n\t\t\t\t\tx = torch.cat((x1, x2), 1)\n\t\t\t\t\toutputs[ind] = x\n\t\t\telif block['type'] == 'shortcut':\n\t\t\t\tfrom_layer = int(block['from'])\n\t\t\t\tactivation = block['activation']\n\t\t\t\tfrom_layer = from_layer if from_layer > 0 else from_layer + ind\n\t\t\t\tx1 = outputs[from_layer]\n\t\t\t\tx2 = outputs[ind-1]\n\t\t\t\tx  = x1 + x2\n\t\t\t\tif activation == 'leaky':\n\t\t\t\t\tx = F.leaky_relu(x, 0.1, inplace=True)\n\t\t\t\telif activation == 'relu':\n\t\t\t\t\tx = F.relu(x, inplace=True)\n\t\t\t\toutputs[ind] = x\n\t\t\telif block['type'] == 'region':\n\t\t\t\tcontinue\n\t\t\t\t# if self.training:\n\t\t\t\t# \tyolo_outs.append(x)\n\t\t\t\t# \toutputs[ind] = None\n\t\t\t\t# else:\n\t\t\t\t# \tboxes = self.models[ind](x)\n\t\t\t\t# \tout_boxes.append(boxes)\n\t\t\telif block['type'] == 'yolo':\n\t\t\t\t# continue\n\t\t\t\tis_yolo3 = True\n\t\t\t\tyolo_outs.append(x)\n\t\t\t\t# if self.training:\n\t\t\t\t# \tyolo_outs.append(x)\n\t\t\t\t# \toutputs[ind] = None\n\t\t\t\t# else:\n\t\t\t\t# \tboxes = self.models[ind](x)\n\t\t\t\t# \tout_boxes.append(boxes)\n\t\t\telif block['type'] == 'cost':\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tprint('[Error]:unkown type %s' % (block['type'])) \n\t\t# if self.training:\n\t\t# \t# return self.loss\n\t\t# \tif is_yolo3:\n\t\t# \t\t# print('[INFO]:This yolov3 darknet-train...')\n\t\t# \t\treturn yolo_outs\n\t\t# \telse:\n\t\t# \t\treturn x\n\t\t# else:\n\t\t# \tif is_yolo3:\n\t\t# \t\t# print('[INFO]:This yolov3 darknet-test...')\n\t\t# \t\treturn out_boxes\n\t\t# \telse:\n\t\t# \t\treturn x\n\t\t# return x\n\t\tif is_yolo3:\n\t\t\treturn yolo_outs\n\t\telse:\n\t\t\treturn x\n\t# merge conv, bn, leaky, etc.\n\tdef create_network(self, blocks):\n\t\tmodels = nn.ModuleList()\n\t\tprev_filters = 3\n\t\tout_filters =[]\n\t\tprev_stride = 1\n\t\tout_strides = []\n\t\tconv_id = 0\n\t\t# all conv stride = 1\n\t\t# So out_strides record sizes reduce in scale\n\t\tfor block in blocks:\n\t\t\tif block['type'] == 'net':\n\t\t\t\tprev_filters = int(block['channels'])\n\t\t\t\tcontinue\n\t\t\telif block['type'] == 'convolutional':\n\t\t\t\tconv_id = conv_id + 1\n\t\t\t\tbatch_normalize = int(block['batch_normalize'])\n\t\t\t\tfilters = int(block['filters'])\n\t\t\t\tkernel_size = int(block['size'])\n\t\t\t\tstride = int(block['stride'])\n\t\t\t\tis_pad = int(block['pad'])\n\t\t\t\t# Problem:\n\t\t\t\t# \tkernel_size when odd better?\n\t\t\t\tpad = (kernel_size-1)//2 if is_pad else 0\n\t\t\t\tactivation = block['activation']\n\t\t\t\tmodel = nn.Sequential()\n\t\t\t\tif batch_normalize:\n\t\t\t\t\tmodel.add_module('conv{}'.format(conv_id), nn.Conv2d(prev_filters, filters, kernel_size, stride, pad, bias=False))\n\t\t\t\t\tmodel.add_module('bn{}'.format(conv_id), nn.BatchNorm2d(filters))\n\t\t\t\telse:\n\t\t\t\t\tmodel.add_module('conv{}'.format(conv_id), nn.Conv2d(prev_filters, filters, kernel_size, stride, pad))\n\t\t\t\tif activation == 'leaky':\n\t\t\t\t\tmodel.add_module('leaky{}'.format(conv_id), nn.LeakyReLU(0.1, inplace=True))\n\t\t\t\telif activation == 'relu':\n\t\t\t\t\tmodel.add_module('relu{}'.format(conv_id), nn.ReLU(inplace=True))\n\t\t\t\tprev_filters = filters\n\t\t\t\tout_filters.append(prev_filters)\n\t\t\t\tprev_stride = stride * prev_stride\n\t\t\t\tout_strides.append(prev_stride)\n\t\t\t\tmodels.append(model)\n\t\t\telif block['type'] == 'maxpool':\n\t\t\t\tpool_size = int(block['size'])\n\t\t\t\tstride = int(block['stride'])\n\t\t\t\tif stride > 1:\n\t\t\t\t\tmodel = nn.MaxPool2d(pool_size, stride)\n\t\t\t\telse:\n\t\t\t\t\tmodel = MaxPoolStride1()\n\t\t\t\tout_filters.append(prev_filters)\n\t\t\t\tprev_stride = stride * prev_stride\n\t\t\t\tout_strides.append(prev_stride)\n\t\t\t\tmodels.append(model)\n\t\t\t# at end in general\n\t\t\telif block['type'] == 'avgpool':\n\t\t\t\tmodel = GlobalAvgPool2d()\n\t\t\t\tout_filters.append(prev_filters)\n\t\t\t\tmodels.append(model)\n\t\t\telif block['type'] == 'softmax':\n\t\t\t\tmodel = nn.Softmax()\n\t\t\t\tout_strides.append(prev_stride)\n\t\t\t\tout_filters.append(prev_filters)\n\t\t\t\tmodels.append(model)\n\t\t\t# the losses are averaged over observations for each minibatch. \n\t\t\telif block['type'] == 'cost':\n\t\t\t\tif block['_type'] == 'sse':\n\t\t\t\t\tmodel = nn.MSELoss(size_average=True)\n\t\t\t\telif block['_type'] == 'L1':\n\t\t\t\t\tmodel = nn.L1Loss(size_average=True)\n\t\t\t\telif block['_type'] == 'smooth':\n\t\t\t\t\tmodel = nn.SmoothL1Loss(size_average=True)\n\t\t\t\tout_filters.append(1)\n\t\t\t\tout_strides.append(prev_stride)\n\t\t\t\tmodels.append(model)\n\t\t\telif block['type'] == 'reorg':\n\t\t\t\tstride = int(block['stride'])\n\t\t\t\tprev_filters = stride * stride * prev_filters\n\t\t\t\tout_filters.append(prev_filters)\n\t\t\t\tprev_stride = prev_stride * stride\n\t\t\t\tout_strides.append(prev_stride)\n\t\t\t\tmodels.append(Reorg(stride))\n\t\t\telif block['type'] == 'upsample':\n\t\t\t\tstride = int(block['stride'])\n\t\t\t\tout_filters.append(prev_filters)\n\t\t\t\tprev_stride = prev_stride // stride\n\t\t\t\tout_strides.append(prev_stride)\n\t\t\t\tmodels.append(Upsample(stride))\n\t\t\telif block['type'] == 'route':\n\t\t\t\tlayers = block['layers'].split(',')\n\t\t\t\tind = len(models)\n\t\t\t\tlayers = [int(i) if int(i) > 0 else int(i)+ind for i in layers]\n\t\t\t\tif len(layers) == 1:\n\t\t\t\t\tprev_filters = out_filters[layers[0]]\n\t\t\t\t\tprev_stride = out_strides[layers[0]]\n\t\t\t\telif len(layers) == 2:\n\t\t\t\t\tassert(layers[0] == ind - 1)\n\t\t\t\t\tprev_filters = out_filters[layers[0]] + out_filters[layers[1]]\n\t\t\t\t\tprev_stride = out_strides[layers[0]]\n\t\t\t\tout_filters.append(prev_filters)\n\t\t\t\tout_strides.append(prev_stride)\n\t\t\t\tmodels.append(EmptyModule())\n\t\t\t# other params used in forward function\n\t\t\telif block['type'] == 'shortcut':\n\t\t\t\tind = len(models)\n\t\t\t\tprev_filters = out_filters[ind-1]\n\t\t\t\tout_filters.append(prev_filters)\n\t\t\t\tprev_stride = out_strides[ind-1]\n\t\t\t\tout_strides.append(prev_stride)\n\t\t\t\tmodels.append(EmptyModule())\n\t\t\telif block['type'] == 'connected':\n\t\t\t\tfilters = int(block['output'])\n\t\t\t\tif block['activation'] == 'linear':\n\t\t\t\t\tmodel = nn.Linear(prev_filters, filters)\n\t\t\t\telif block['activation'] == 'leaky':\n\t\t\t\t\tmodel = nn.Sequential(\n\t\t\t\t\t\t\t\tnn.Linear(prev_filters, filters),\n\t\t\t\t\t\t\t\tnn.LeakyReLU(0.1, inplace=True))\n\t\t\t\telif block['activation'] == 'relu':\n\t\t\t\t\tmodel = nn.Sequential(\n\t\t\t\t\t\t\t\tnn.Linear(prev_filters, filters),\n\t\t\t\t\t\t\t\tnn.ReLU(inplace=True))\n\t\t\t\tprev_filters = filters\n\t\t\t\tout_filters.append(prev_filters)\n\t\t\t\tout_strides.append(prev_stride)\n\t\t\t\tmodels.append(model)\n\t\t\t# Note:\n\t\t\t# \tsome values aren't assigned to class\n\t\t\t# \t(RegionLoss and YoloLayer())\n\t\t\telif block['type'] == 'region':\n\t\t\t\tloss = RegionLoss()\n\t\t\t\tanchors = block['anchors'].split(',')\n\t\t\t\tloss.anchors = [float(i) for i in anchors]\n\t\t\t\tloss.num_classes = int(block['classes'])\n\t\t\t\tloss.num_anchors = int(block['num'])\n\t\t\t\tloss.anchor_step = len(loss.anchors) // loss.num_anchors\n\t\t\t\tloss.object_scale = float(block['object_scale'])\n\t\t\t\tloss.noobject_scale = float(block['noobject_scale'])\n\t\t\t\tloss.class_scale = float(block['class_scale'])\n\t\t\t\tloss.coord_scale = float(block['coord_scale'])\n\t\t\t\tloss.stride = prev_stride\n\t\t\t\tout_filters.append(prev_filters)\n\t\t\t\tout_strides.append(prev_stride)\n\t\t\t\tmodels.append(loss)\n\t\t\t\tself.losses.append(loss)\n\t\t\telif block['type'] == 'yolo':\n\t\t\t\tself.is_yolo3 = True\n\t\t\t\tyolo_layer = YoloLayer()\n\t\t\t\tanchors = block['anchors'].split(',')\n\t\t\t\tanchor_mask = block['mask'].split(',')\n\t\t\t\tyolo_layer.anchor_mask = [int(i) for i in anchor_mask]\n\t\t\t\tyolo_layer.anchors = [float(i) for i in anchors]\n\t\t\t\tyolo_layer.num_classes = int(block['classes'])\n\t\t\t\tyolo_layer.num_anchors = int(block['num'])\n\t\t\t\tyolo_layer.anchor_step = len(yolo_layer.anchors) // yolo_layer.num_anchors\n\t\t\t\tyolo_layer.stride = prev_stride\n\t\t\t\t# yolo_layer.object_scale = float(block['object_scale'])\n\t\t\t\t# yolo_layer.noobject_scale = float(block['noobject_scale'])\n\t\t\t\t# yolo_layer.class_scale = float(block['class_scale'])\n\t\t\t\t# yolo_layer.coord_scale = float(block['coord_scale'])\n\t\t\t\tout_filters.append(prev_filters)\n\t\t\t\tout_strides.append(prev_stride)\n\t\t\t\tmodels.append(yolo_layer)\n\t\t\t\tself.losses.append(yolo_layer)\n\t\t\telse:\n\t\t\t\tprint('[Error]:unkown type %s' % (block['type']))\n\t\treturn models\n\tdef print_network(self):\n\t\tprint_cfg(self.blocks)\n\tdef load_weights(self, weightfile):\n\t\tfp = open(weightfile, 'rb')\n\t\theader = np.fromfile(fp, count=5, dtype=np.int32)\n\t\t# header = np.fromfile(fp, count=4, dtype=np.int32)\n\t\tself.header = torch.from_numpy(header)\n\t\tself.seen = self.header[3]\n\t\t# print(self.header)\n\t\t# print(self.seen)\n\t\tbuf = np.fromfile(fp, dtype=np.float32)\n\t\t# print(len(buf))\n\t\tfp.close()\n\t\tstart = 0\n\t\tind = -2\n\t\tfor block in self.blocks:\n\t\t\tif start >= buf.size:\n\t\t\t\tbreak\n\t\t\tind = ind + 1\n\t\t\tif block['type'] == 'net':\n\t\t\t\tcontinue\n\t\t\telif block['type'] == 'convolutional':\n\t\t\t\tmodel = self.models[ind]\n\t\t\t\tbatch_normalize = int(block['batch_normalize'])\n\t\t\t\tif batch_normalize:\n\t\t\t\t\tstart = load_conv_bn(buf, start, model[0], model[1])\n\t\t\t\telse:\n\t\t\t\t\tstart = load_conv(buf, start, model[0])\n\t\t\telif block['type'] == 'connected':\n\t\t\t\tmodel = self.models[ind]\n\t\t\t\tif block['activation'] != 'linear':\n\t\t\t\t\tstart = load_fc(buf, start, model[0])\n\t\t\t\telse:\n\t\t\t\t\tstart = load_fc(buf, start, model)\n\t\t\t# Easier to develop\n\t\t\telif block['type'] == 'maxpool':\n\t\t\t\tcontinue\n\t\t\telif block['type'] == 'reorg':\n\t\t\t\tcontinue\n\t\t\telif block['type'] == 'upsample':\n\t\t\t\tcontinue\n\t\t\telif block['type'] == 'route':\n\t\t\t\tcontinue\n\t\t\telif block['type'] == 'shortcut':\n\t\t\t\tcontinue\n\t\t\telif block['type'] == 'region':\n\t\t\t\tcontinue\n\t\t\telif block['type'] == 'yolo':\n\t\t\t\tcontinue\n\t\t\telif block['type'] == 'avgpool':\n\t\t\t\tcontinue\n\t\t\telif block['type'] == 'softmax':\n\t\t\t\tcontinue\n\t\t\telif block['type'] == 'cost':\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tprint('[Error]:unkown type %s' % (block['type']))\n\t# cutoff:\n\t# \twhether delete end block or not\n\tdef save_weights(self, outfile, cutoff=0):\n\t\tif cutoff <= 0:\n\t\t\tcutoff = len(self.blocks) - 1\n\t\tfp = open(outfile, 'wb')\n\t\tself.header[3] = self.seen\n\t\theader = self.header\n\t\theader.numpy().tofile(fp)\n\t\tind = -1\n\t\tfor blockId in range(1, cutoff+1):\n\t\t\tind = ind + 1\n\t\t\tblock = self.blocks[blockId]\n\t\t\tif block['type'] == 'convolutional':\n\t\t\t\tmodel = self.models[ind]\n\t\t\t\tbatch_normalize = int(block['batch_normalize'])\n\t\t\t\tif batch_normalize:\n\t\t\t\t\tsave_conv_bn(fp, model[0], model[1])\n\t\t\t\telse:\n\t\t\t\t\tsave_conv(fp, model[0])\n\t\t\t# activation fun(like ReLU) params don't need be saved.\n\t\t\telif block['type'] == 'connected':\n\t\t\t\tmodel = self.models[ind]\n\t\t\t\tif block['activation'] != 'linear':\n\t\t\t\t\tsave_fc(fc, model[0])\n\t\t\t\telse:\n\t\t\t\t\tsave_fc(fc, model)\n\t\t\t# Easier to develop\n\t\t\telif block['type'] == 'maxpool':\n\t\t\t\tcontinue\n\t\t\telif block['type'] == 'reorg':\n\t\t\t\tcontinue\n\t\t\telif block['type'] == 'upsample':\n\t\t\t\tcontinue\n\t\t\telif block['type'] == 'route':\n\t\t\t\tcontinue\n\t\t\telif block['type'] == 'shortcut':\n\t\t\t\tcontinue\n\t\t\telif block['type'] == 'region':\n\t\t\t\tcontinue\n\t\t\telif block['type'] == 'yolo':\n\t\t\t\tcontinue\n\t\t\telif block['type'] == 'avgpool':\n\t\t\t\tcontinue\n\t\t\telif block['type'] == 'softmax':\n\t\t\t\tcontinue\n\t\t\telif block['type'] == 'cost':\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tprint('[Error]:unkown type %s' % (block['type']))\n\t\tfp.close()\n\n\nif __name__ == '__main__':\n\t# x = torch.Tensor(2, 2, 4, 4).fill_(1)\n\t# x = nn.Parameter(x)\n\t# print(x)\n\t# print(GlobalAvgPool2d()(x))\n\td = Darknet('../cfg/me/darknet19_wfc_face.cfg')\n\t# d = Darknet('../cfg/me/darknet19_wfc_face.cfg')\n\td.print_network()\n\td.load_weights('../weights/darknet19_wfc.weights')\n\t# d.load_weights(r'E:\\GraduationProject\\experiment_record\\detection\\yolov3_CelebA\\train\\weights\\000042.weights')\n\t# d.load_weights('../weights/000050.weights')", "meta": {"hexsha": "a0b8be0d0133c3f5b6c7d91614024298b94c8e21", "size": 15734, "ext": "py", "lang": "Python", "max_stars_repo_path": "FaceDetect/nets/darknet.py", "max_stars_repo_name": "CharlesPikachu/CharlesFace", "max_stars_repo_head_hexsha": "90bfe38c58068228d0069dce43b55b2570acaa16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2018-05-23T07:07:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-28T07:37:30.000Z", "max_issues_repo_path": "FaceDetect/nets/darknet.py", "max_issues_repo_name": "CharlesPikachu/CharlesFace", "max_issues_repo_head_hexsha": "90bfe38c58068228d0069dce43b55b2570acaa16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FaceDetect/nets/darknet.py", "max_forks_repo_name": "CharlesPikachu/CharlesFace", "max_forks_repo_head_hexsha": "90bfe38c58068228d0069dce43b55b2570acaa16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9115913556, "max_line_length": 129, "alphanum_fraction": 0.6384898945, "include": true, "reason": "import numpy", "num_tokens": 4810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3345894478883556, "lm_q1q2_score": 0.17382635227817944}}
{"text": "# coding: utf-8\n# Copyright (c) Tingzheng Hou.\n# Distributed under the terms of the MIT License.\n\n\"\"\"\nThis module implements functions for coordination analysis.\n\"\"\"\n\nfrom typing import Dict, List, Tuple, Union, Callable, Optional\n\nimport numpy as np\nfrom tqdm.notebook import tqdm\nfrom MDAnalysis import Universe, AtomGroup\nfrom MDAnalysis.core.groups import Atom\nfrom MDAnalysis.analysis.distances import distance_array\nfrom scipy.signal import savgol_filter\nfrom mdgo.util import atom_vec, angle\n\n\n__author__ = \"Tingzheng Hou\"\n__version__ = \"1.0\"\n__maintainer__ = \"Tingzheng Hou\"\n__email__ = \"tingzheng_hou@berkeley.edu\"\n__date__ = \"Feb 9, 2021\"\n\n\ndef neighbor_distance(\n    nvt_run: Universe,\n    center_atom: Atom,\n    run_start: int,\n    run_end: int,\n    species: str,\n    select_dict: Dict[str, str],\n    distance: float,\n) -> Dict[str, np.ndarray]:\n    \"\"\"\n    Calculates a dictionary of distances between the ``center_atom`` and neighbor atoms.\n\n    Args:\n        nvt_run: An MDAnalysis ``Universe`` containing wrapped trajectory.\n        center_atom: The center atom object.\n        run_start: Start frame of analysis.\n        run_end: End frame of analysis.\n        species: The neighbor species in the select_dict.\n        select_dict: A dictionary of atom species selection, where each atom species name is a key\n            and the corresponding values are the selection language.\n        distance: The neighbor cutoff distance.\n\n    Returns:\n        A dictionary of distance of neighbor atoms to the ``center_atom``. The keys are atom indexes in string type .\n    \"\"\"\n    dist_dict = {}\n    time_count = 0\n    trj_analysis = nvt_run.trajectory[run_start:run_end:]\n    species_selection = select_dict.get(species)\n    if species_selection is None:\n        raise ValueError(\"Invalid species selection\")\n    for ts in trj_analysis:\n        selection = (\n            \"(\" + species_selection + \") and (around \" + str(distance) + \" index \" + str(center_atom.index) + \")\"\n        )\n        shell = nvt_run.select_atoms(selection, periodic=True)\n        for atom in shell.atoms:\n            if str(atom.index) not in dist_dict:\n                dist_dict[str(atom.index)] = np.full(run_end - run_start, 100.0)\n        time_count += 1\n    time_count = 0\n    for ts in trj_analysis:\n        for atom_index, val in dist_dict.items():\n            dist = distance_array(ts[center_atom.index], ts[int(atom_index)], ts.dimensions)\n            val[time_count] = dist\n        time_count += 1\n    return dist_dict\n\n\ndef find_nearest(\n    trj: Dict[str, np.ndarray],\n    time_step: float,\n    binding_cutoff: float,\n    hopping_cutoff: float,\n    smooth: int = 51,\n) -> Tuple[List[int], Union[float, np.floating], List[int]]:\n    \"\"\"Using the dictionary of neighbor distance ``trj``, finds the nearest neighbor ``sites`` that the center atom\n    binds to, and calculates the ``frequency`` of hopping between each neighbor, and ``steps`` when each binding site\n    exhibits the closest distance to the center atom.\n\n    Args:\n        trj: A dictionary of distances between center atom and neighbor atoms.\n        time_step: The time step of the simulation in ps.\n        binding_cutoff: Binding cutoff distance.\n        hopping_cutoff: Detaching cutoff distance.\n        smooth: The length of the smooth filter window. Default to 51.\n\n    Returns:\n        Returns an array of nearest neighbor ``sites`` (unique on each frame),\n        the ``frequency`` of hopping between sites, and ``steps`` when each binding site\n        exhibits the closest distance to the center atom.\n    \"\"\"\n    time_span = len(list(trj.values())[0])\n    if smooth > 0:\n        for kw in list(trj):\n            trj[kw] = savgol_filter(trj.get(kw), smooth, 2)\n    site_distance = [100 for _ in range(time_span)]\n    sites: List[Union[int, np.integer]] = [0 for _ in range(time_span)]\n    start_site = min(trj, key=lambda k: trj[k][0])\n    kw_start = trj.get(start_site)\n    assert kw_start is not None\n    if kw_start[0] < binding_cutoff:\n        sites[0] = int(start_site)\n        site_distance[0] = kw_start[0]\n    else:\n        pass\n    for time in range(1, time_span):\n        if sites[time - 1] == 0:\n            old_site_distance = 100\n        else:\n            old_trj = trj.get(str(sites[time - 1]))\n            assert old_trj is not None\n            old_site_distance = old_trj[time]\n        if old_site_distance > hopping_cutoff:\n            new_site = min(trj, key=lambda k: trj[k][time])\n            new_trj = trj.get(new_site)\n            assert new_trj is not None\n            new_site_distance = new_trj[time]\n            if new_site_distance > binding_cutoff:\n                site_distance[time] = 100\n            else:\n                sites[time] = int(new_site)\n                site_distance[time] = new_site_distance\n        else:\n            sites[time] = sites[time - 1]\n            site_distance[time] = old_site_distance\n    sites = [int(i) for i in sites]\n    sites_and_distance_array = np.array([[sites[i], site_distance[i]] for i in range(len(sites))])\n    steps = []\n    closest_step: Optional[int] = 0\n    previous_site = sites_and_distance_array[0][0]\n    if previous_site == 0:\n        closest_step = None\n    for i, step in enumerate(sites_and_distance_array):\n        site = step[0]\n        distance = step[1]\n        if site == 0:\n            pass\n        else:\n            if site == previous_site:\n                if distance < sites_and_distance_array[closest_step][1]:\n                    closest_step = i\n                else:\n                    pass\n            else:\n                if closest_step is not None:\n                    steps.append(closest_step)\n                closest_step = i\n                previous_site = site\n    if closest_step is not None:\n        steps.append(closest_step)\n    change = (np.diff([i for i in sites if i != 0]) != 0).sum()\n    assert change == len(steps) - 1 or change == len(steps) == 0\n    frequency = change / (time_span * time_step)\n    return sites, frequency, steps\n\n\ndef find_nearest_free_only(\n    trj: Dict[str, np.ndarray],\n    time_step: float,\n    binding_cutoff: float,\n    hopping_cutoff: float,\n    smooth: int = 51,\n) -> Tuple[List[int], Union[float, np.floating], List[int]]:\n    \"\"\"Using the dictionary of neighbor distance ``trj``, finds the nearest neighbor ``sites`` that the ``center_atom``\n    binds to, and calculates the ``frequency`` of hopping between each neighbor, and ``steps`` when each binding site\n    exhibits the closest distance to the center atom.\n    * Only hopping events with intermediate free state (no binded nearest neighbor) are counted.\n\n    Args:\n        trj: A dictionary of distances between center atom and neighbor atoms.\n        time_step: The time step of the simulation in ps.\n        binding_cutoff: Binding cutoff distance.\n        hopping_cutoff: Detaching cutoff distance.\n        smooth: The length of the smooth filter window. Default to 51.\n\n    Returns:\n        Returns an array of nearest neighbor ``sites`` (unique on each frame),\n        the ``frequency`` of hopping between sites, and ``steps`` when each binding site\n        exhibits the closest distance to the center atom.\n    \"\"\"\n    time_span = len(list(trj.values())[0])\n    if smooth > 0:\n        for kw in list(trj):\n            trj[kw] = savgol_filter(trj.get(kw), smooth, 2)\n    site_distance = [100 for _ in range(time_span)]\n    sites: List[Union[int, np.integer]] = [0 for _ in range(time_span)]\n    start_site = min(trj, key=lambda k: trj[k][0])\n    kw_start = trj.get(start_site)\n    assert kw_start is not None\n    if kw_start[0] < binding_cutoff:\n        sites[0] = int(start_site)\n        site_distance[0] = kw_start[0]\n    else:\n        pass\n    for time in range(1, time_span):\n        if sites[time - 1] == 0:\n            old_site_distance = 100\n        else:\n            old_trj = trj.get(str(sites[time - 1]))\n            assert old_trj is not None\n            old_site_distance = old_trj[time]\n        if old_site_distance > hopping_cutoff:\n            new_site = min(trj, key=lambda k: trj[k][time])\n            new_trj = trj.get(new_site)\n            assert new_trj is not None\n            new_site_distance = new_trj[time]\n            if new_site_distance > binding_cutoff:\n                site_distance[time] = 100\n            else:\n                sites[time] = int(new_site)\n                site_distance[time] = new_site_distance\n        else:\n            sites[time] = sites[time - 1]\n            site_distance[time] = old_site_distance\n    sites = [int(i) for i in sites]\n    sites_and_distance_array = np.array([[sites[i], site_distance[i]] for i in range(len(sites))])\n    steps = []\n    closest_step: Optional[int] = 0\n    previous_site = sites_and_distance_array[0][0]\n    previous_zero = False\n    if previous_site == 0:\n        closest_step = None\n        previous_zero = True\n    for i, step in enumerate(sites_and_distance_array):\n        site = step[0]\n        distance = step[1]\n        if site == 0:\n            previous_zero = True\n        else:\n            if site == previous_site:\n                if distance < sites_and_distance_array[closest_step][1]:\n                    closest_step = i\n                else:\n                    pass\n            elif not previous_zero:\n                previous_site = site\n                if distance < sites_and_distance_array[closest_step][1]:\n                    closest_step = i\n                else:\n                    pass\n            else:\n                if closest_step is not None:\n                    steps.append(closest_step)\n                closest_step = i\n                previous_site = site\n    if closest_step is not None:\n        steps.append(closest_step)\n    frequency = (len(steps) - 1) / (time_span * time_step)\n    return sites, frequency, steps\n\n\ndef find_in_n_out(\n    trj: Dict[str, np.ndarray], binding_cutoff: float, hopping_cutoff: float, smooth: int = 51, cool: int = 20\n) -> Tuple[List[int], List[int]]:\n    \"\"\"Finds the frames when the center atom binds with the neighbor (binding) or hopping out (hopping)\n    according to the dictionary of neighbor distance.\n\n    Args:\n        trj: A dictionary of distances between center atom and neighbor atoms.\n        binding_cutoff: Binding cutoff distance.\n        hopping_cutoff: Hopping out cutoff distance.\n        smooth: The length of the smooth filter window. Default to 51.\n        cool: The cool down frames between hopping in and hopping out. Default to 20.\n\n    Returns:\n        Two arrays of numberings of frames with hopping in and hopping out event, respectively.\n    \"\"\"\n    time_span = len(list(trj.values())[0])\n    if smooth > 0:\n        for kw in list(trj):\n            trj[kw] = savgol_filter(trj.get(kw), smooth, 2)\n    site_distance = [100 for _ in range(time_span)]\n    sites = [0 for _ in range(time_span)]\n    start_site = min(trj, key=lambda k: trj[k][0])\n    kw_start = trj.get(start_site)\n    assert kw_start is not None\n    if kw_start[0] < binding_cutoff:\n        sites[0] = int(start_site)\n        site_distance[0] = kw_start[0]\n    else:\n        pass\n    for time in range(1, time_span):\n        if sites[time - 1] == 0:\n            old_site_distance = 100\n        else:\n            old_trj = trj.get(str(sites[time - 1]))\n            assert old_trj is not None\n            old_site_distance = old_trj[time]\n        if old_site_distance > hopping_cutoff:\n            new_site = min(trj, key=lambda k: trj[k][time])\n            new_trj = trj.get(new_site)\n            assert new_trj is not None\n            new_site_distance = new_trj[time]\n            if new_site_distance > binding_cutoff:\n                site_distance[time] = 100\n            else:\n                sites[time] = int(new_site)\n                site_distance[time] = new_site_distance\n        else:\n            sites[time] = sites[time - 1]\n            site_distance[time] = old_site_distance\n    sites = [int(i) for i in sites]\n\n    last = sites[0]\n    steps_in: List[int] = []\n    steps_out: List[int] = []\n    in_cool = cool\n    out_cool = cool\n    for i, s in enumerate(sites):\n        if last == s:\n            pass\n        elif last == 0:\n            in_cool = 0\n            steps_in.append(i)\n            if out_cool < cool:\n                steps_out.pop()\n        elif s == 0:\n            out_cool = 0\n            steps_out.append(i)\n            if in_cool < cool:\n                steps_in.pop()\n        else:\n            if cool == 0:\n                steps_out.append(i - 1)\n                steps_in.append(i)\n        last = s\n        in_cool += 1\n        out_cool += 1\n    return steps_in, steps_out\n\n\ndef check_contiguous_steps(\n    nvt_run: Universe,\n    center_atom: Atom,\n    distance_dict: Dict[str, float],\n    select_dict: Dict[str, str],\n    run_start: int,\n    run_end: int,\n    checkpoints: np.ndarray,\n    lag: int = 20,\n) -> Dict[str, np.ndarray]:\n    \"\"\"Calculates the distance between the center atom and the neighbor atom\n    in the checkpoint +/- lag time range.\n\n    Args:\n        nvt_run: An MDAnalysis ``Universe`` containing wrapped trajectory.\n        center_atom: The center atom object.\n        distance_dict: A dictionary of Cutoff distance of neighbor for each species.\n        select_dict: A dictionary of atom species selection, where each atom species name is a key\n            and the corresponding values are the selection language.\n        run_start: Start frame of analysis.\n        run_end: End frame of analysis.\n        checkpoints: The frame numberings of interest to check for contiguous steps.\n        lag: The range (+/- lag) of the contiguous steps. Default to 20.\n\n    Returns:\n        An array of distance between the center atom and the neighbor atoms\n        in the checkpoint +/- lag time range.\n    \"\"\"\n    coord_num: Dict[str, Union[List[List[int]], np.ndarray]] = {\n        x: [[] for _ in range(lag * 2 + 1)] for x in distance_dict\n    }\n    trj_analysis = nvt_run.trajectory[run_start:run_end:]\n    has = False\n    for i, ts in enumerate(trj_analysis):\n        log = False\n        checkpoint = -1\n        for j in checkpoints:\n            if abs(i - j) <= lag:\n                log = True\n                has = True\n                checkpoint = j\n        if log:\n            for kw in distance_dict:\n                selection = select_shell(select_dict, distance_dict, center_atom, kw)\n                shell = nvt_run.select_atoms(selection, periodic=True)\n                coord_num[kw][i - checkpoint + lag].append(len(shell))\n    one_atom_ave = {}\n    if has:\n        for kw in coord_num:\n            np_arrays = np.array([np.array(time).mean() for time in coord_num[kw]])\n            one_atom_ave[kw] = np_arrays\n    return one_atom_ave\n\n\ndef heat_map(\n    nvt_run: Universe,\n    floating_atom: Atom,\n    cluster_center_sites: List[int],\n    cluster_terminal: Union[str, List[str]],\n    cartesian_by_ref: np.ndarray,\n    run_start: int,\n    run_end: int,\n    dim: str = \"xyz\",\n) -> np.ndarray:\n    \"\"\"\n    Calculates the heat map of the floating atom around the cluster. The coordinates are normalized to\n    a cartesian coordinate system where the cluster_center_sites atom is the origin.\n\n    Args:\n        nvt_run: An MDAnalysis ``Universe`` containing wrapped trajectory.\n        floating_atom: Floating atom species.\n        cluster_center_sites: A list of nearest cluster center sites (atom index).\n        cluster_terminal: The selection string for terminal atom species of the cluster\n            (typically the binding site for the floating ion). The argument can be a str if\n            all the terminal atoms have the same selection string and are equivalent, or a list\n            if the terminal atoms are distinct and have different selection strings.\n        cartesian_by_ref: Transformation matrix between cartesian and reference coordinate systems.\n        run_start: Start frame of analysis.\n        run_end: End frame of analysis.\n        dim: Desired dimensions to calculate heat map. TODO: 2d support or dimension selection.\n\n    Returns:\n        The coordinates of the floating ion around clusters normalized to the desired cartesian coordinate system.\n    \"\"\"\n    dimension = len(dim)\n    if isinstance(cluster_terminal, list):\n        mode = \"ordered\"\n        if len(cluster_terminal) != dimension:\n            term_order = \", \".join(c for c in dim)\n            raise ValueError(f\"Please specify the cluster_terminal in the order of {term_order}.\")\n    else:\n        mode = \"unordered\"\n    trj_analysis = nvt_run.trajectory[run_start:run_end:]\n    coordinates = []\n    for i, ts in enumerate(trj_analysis):\n        if cluster_center_sites[i] == 0:\n            pass\n        else:\n            center_atom = nvt_run.select_atoms(\"index \" + str(cluster_center_sites[i]))[0]\n            if mode == \"ordered\":\n                selections = [\n                    \"(\" + species + \") and (same resid as index \" + str(center_atom.index) + \")\"\n                    for species in cluster_terminal\n                ]\n                bind_atoms_xyz = [nvt_run.select_atoms(sel, periodic=True) for sel in selections]\n                vertex_atoms: List[Atom] = []\n                for atoms in bind_atoms_xyz:\n                    if len(atoms) == 1:\n                        vertex_atoms.append(atoms[0])\n                    elif len(atoms) > 1:\n                        distances = distance_array(ts[floating_atom.index], atoms.positions, ts.dimensions)\n                        idx = np.argpartition(distances[0], 1)\n                        vertex_atoms.append(atoms[idx[0]])\n                    else:\n                        raise ValueError(\n                            f\"There should be at least 1 cluster_terminal atom in the {str(dim[i])} dimension.\"\n                            f\"Try broadening the selection at index {str(i + 1)} of the cluster_terminal \"\n                        )\n            else:\n                assert isinstance(cluster_terminal, str)\n                selection = \"(\" + cluster_terminal + \") and (same resid as index \" + str(center_atom.index) + \")\"\n                bind_atoms = nvt_run.select_atoms(selection, periodic=True)\n                if len(bind_atoms) == dimension:\n                    vertex_atoms = bind_atoms\n                elif len(bind_atoms) > dimension:\n                    distances = distance_array(ts[floating_atom.index], bind_atoms.positions, ts.dimensions)\n                    idx = np.argpartition(distances[0], 3)\n                    vertex_atoms = bind_atoms[idx[:3]]\n                else:\n                    raise ValueError(\n                        f\"There should be at least {dimension} cluster_terminal atoms in order to position \"\n                        \"the floating ion. Try broadening the cluster_terminal selection\"\n                    )\n            vector_a = atom_vec(vertex_atoms[0], center_atom, ts.dimensions)\n            vector_b = atom_vec(vertex_atoms[1], center_atom, ts.dimensions)\n            vector_c = atom_vec(vertex_atoms[2], center_atom, ts.dimensions)\n            vector_atom = atom_vec(floating_atom, center_atom, ts.dimensions)\n            basis_abc = np.transpose([vector_a, vector_b, vector_c])\n            abc_atom = np.linalg.solve(basis_abc, vector_atom)\n            unit_x = np.linalg.norm(\n                cartesian_by_ref[0, 0] * vector_a\n                + cartesian_by_ref[0, 1] * vector_b\n                + cartesian_by_ref[0, 2] * vector_c\n            )\n            unit_y = np.linalg.norm(\n                cartesian_by_ref[1, 0] * vector_a\n                + cartesian_by_ref[1, 1] * vector_b\n                + cartesian_by_ref[1, 2] * vector_c\n            )\n            unit_z = np.linalg.norm(\n                cartesian_by_ref[2, 0] * vector_a\n                + cartesian_by_ref[2, 1] * vector_b\n                + cartesian_by_ref[2, 2] * vector_c\n            )\n            vector_x = cartesian_by_ref[0] / unit_x\n            vector_y = cartesian_by_ref[1] / unit_y\n            vector_z = cartesian_by_ref[2] / unit_z\n            basis_xyz = np.transpose([vector_x, vector_y, vector_z])\n            xyz_atom = np.linalg.solve(basis_xyz, abc_atom)\n            coordinates.append(xyz_atom)\n    return np.array(coordinates)\n\n\ndef process_evol(\n    nvt_run: Universe,\n    select_dict: Dict[str, str],\n    in_list: Dict[str, List[np.ndarray]],\n    out_list: Dict[str, List[np.ndarray]],\n    distance_dict: Dict[str, float],\n    run_start: int,\n    run_end: int,\n    lag: int,\n    binding_cutoff: float,\n    hopping_cutoff: float,\n    smooth: int,\n    cool: int,\n    binding_site: str,\n    center_atom: str,\n):\n    \"\"\"Calculates the coordination number evolution of species around ``center_atom`` as a function of time,\n    the coordination numbers are averaged over all frames around events when the center_atom\n    hopping to and hopping out from the ``binding_site``.\n\n    Args:\n        nvt_run: An MDAnalysis ``Universe`` containing wrapped trajectory.\n        select_dict: A dictionary of atom species selection, where each atom species name is a key\n            and the corresponding values are the selection language.\n        in_list: A list to store the distances for hopping in events.\n        out_list: A list to store the distances for hopping out events.\n        distance_dict: A dict of coordination cutoff distance of the neighbor species.\n        run_start: Start frame of analysis.\n        run_end: End frame of analysis.\n        lag: The frame range (+/- lag) for check evolution.\n        binding_cutoff: Binding cutoff distance.\n        hopping_cutoff: Hopping out cutoff distance.\n        smooth: The length of the smooth filter window. Default to 51.\n        cool: The cool down frames between binding and hopping out.\n        binding_site: The binding site of binding and hopping out events.\n        center_atom: The solvation shell center atom.\n    \"\"\"\n    center_atoms = nvt_run.select_atoms(select_dict.get(center_atom))\n    for atom in tqdm(center_atoms[::]):\n        neighbor_trj = neighbor_distance(\n            nvt_run, atom, run_start + lag, run_end - lag, binding_site, select_dict, binding_cutoff\n        )\n        hopping_in, hopping_out = find_in_n_out(neighbor_trj, binding_cutoff, hopping_cutoff, smooth=smooth, cool=cool)\n        if len(hopping_in) > 0:\n            in_one = check_contiguous_steps(\n                nvt_run,\n                atom,\n                distance_dict,\n                select_dict,\n                run_start,\n                run_end,\n                np.array(hopping_in) + lag,\n                lag=lag,\n            )\n            for kw, value in in_one.items():\n                in_list[kw].append(value)\n        if len(hopping_out) > 0:\n            out_one = check_contiguous_steps(\n                nvt_run,\n                atom,\n                distance_dict,\n                select_dict,\n                run_start,\n                run_end,\n                np.array(hopping_out) + lag,\n                lag=lag,\n            )\n            for kw, value in out_one.items():\n                out_list[kw].append(value)\n\n\ndef get_full_coords(\n    coords: np.ndarray,\n    reflection: Optional[List[np.ndarray]] = None,\n    rotation: Optional[List[np.ndarray]] = None,\n    inversion: Optional[List[np.ndarray]] = None,\n    sample: Optional[int] = None,\n    dim: str = \"xyz\",\n) -> np.ndarray:\n    \"\"\"\n    A helper function for calculating the heatmap. It applies the ``reflection``, ``rotation`` and ``inversion``\n    symmetry operations to ``coords`` and take ``sample`` number of samples.\n\n    Args:\n        coords: An array of coordinates.\n        reflection: A list of reflection symmetry operation matrix.\n        rotation: A list of rotation symmetry operation matrix.\n        inversion: A list of inversion symmetry operation matrix.\n        sample: Number of samples to take from ``coords``.\n        dim: The dimensions of the coordinates. Default to \"xyz\".\n\n    Returns:\n        An array with ``sample`` number of coordinates.\n    \"\"\"\n    dimension = len(dim)\n    coords_full = coords\n    if reflection:\n        coords_copy = coords_full\n        for mat in reflection:\n            if mat.shape == (3,) and dimension == 3 or mat.shape == (2,) and dimension == 2:\n                coords_ref = coords_copy * mat\n                coords_full = np.concatenate((coords_full, coords_ref), axis=0)\n            elif mat.shape == (3, 3) and dimension == 3 or mat.shape == (2, 2) and dimension == 2:\n                coords_ref = np.dot(coords_copy, mat)\n                coords_full = np.concatenate((coords_full, coords_ref), axis=0)\n            else:\n                raise ValueError(\n                    f\"Invalid reflection matrix. For {dimension}-D system, the matrix should be\"\n                    f\" {dimension}x{dimension} or a vector of length {dimension}\"\n                )\n    if rotation:\n        coords_copy = coords_full\n        for mat in rotation:\n            if mat.shape == (3, 3) and dimension == 3 or mat.shape == (2, 2) and dimension == 2:\n                coords_rot = np.dot(coords_copy, mat)\n                coords_full = np.concatenate((coords_full, coords_rot), axis=0)\n            else:\n                raise ValueError(\n                    f\"Invalid rotation matrix. For {dimension}-D system, the matrix should be {dimension}x{dimension}.\"\n                )\n    if inversion:\n        coords_copy = coords_full\n        for mat in inversion:\n            if mat.shape == (3, 3) and dimension == 3 or mat.shape == (2, 2) and dimension == 2:\n                coords_inv = np.dot(coords_copy, mat)\n                coords_full = np.concatenate((coords_full, coords_inv), axis=0)\n            else:\n                raise ValueError(\n                    f\"Invalid inversion matrix. For {dimension}-D system, the matrix should be {dimension}x{dimension}.\"\n                )\n    if sample:\n        if coords_full.shape[0] > sample:\n            index = np.random.choice(coords_full.shape[0], sample, replace=False)\n            coords_full = coords_full[index]\n        else:\n            print(f\"Warning: the number of coordinates < {sample}, will not perform sampling.\")\n    return coords_full\n\n\ndef cluster_coordinates(  # TODO: rewrite the method\n    nvt_run: Universe,\n    select_dict: Dict[str, str],\n    run_start: int,\n    run_end: int,\n    species: List[str],\n    distance: float,\n    basis_vectors: Optional[Union[List[np.ndarray], np.ndarray]] = None,\n    cluster_center: str = \"center\",\n) -> np.ndarray:\n    \"\"\"Calculates the average position of a cluster.\n\n    Args:\n        nvt_run: An MDAnalysis ``Universe`` containing wrapped trajectory.\n        select_dict: A dictionary of atom species selection, where each atom species name is a key\n            and the corresponding values are the selection language.\n        run_start: Start frame of analysis.\n        run_end: End frame of analysis.\n        species: A list of species in the cluster.\n        distance: The coordination cutoff distance.\n        basis_vectors: The basis vector for normalizing the coordinates of the cluster atoms.\n        cluster_center: Cluster center atom species.\n\n    Returns:\n        An array of coordinates of the cluster atoms.\n    \"\"\"\n    trj_analysis = nvt_run.trajectory[run_start:run_end:]\n    cluster_center_atom = nvt_run.select_atoms(select_dict.get(cluster_center), periodic=True)[0]\n    selection = (\n        \"(\"\n        + \" or \".join(s for s in species)\n        + \") and (around \"\n        + str(distance)\n        + \" index \"\n        + str(cluster_center_atom.index)\n        + \")\"\n    )\n    shell = nvt_run.select_atoms(selection, periodic=True)\n    cluster = []\n    for atom in shell:\n        coord_list = []\n        for ts in trj_analysis:\n            coord_list.append(atom.position)\n        cluster.append(np.mean(np.array(coord_list), axis=0))\n    cluster_array = np.array(cluster)\n    if basis_vectors:\n        if len(basis_vectors) == 2:\n            vec1 = basis_vectors[0]\n            vec2 = basis_vectors[1]\n            vec3 = np.cross(vec1, vec2)\n            vec2 = np.cross(vec1, vec3)\n        elif len(basis_vectors) == 3:\n            vec1 = basis_vectors[0]\n            vec2 = basis_vectors[1]\n            vec3 = basis_vectors[2]\n        else:\n            raise ValueError(\"incorrect vector format\")\n        vec1 = vec1 / np.linalg.norm(vec1)\n        vec2 = vec2 / np.linalg.norm(vec2)\n        vec3 = vec3 / np.linalg.norm(vec3)\n        basis_xyz = np.transpose([vec1, vec2, vec3])\n        cluster_norm = np.linalg.solve(basis_xyz, cluster_array.T).T\n        cluster_norm = cluster_norm - np.mean(cluster_norm, axis=0)\n        return cluster_norm\n    return cluster_array\n\n\ndef num_of_neighbor(\n    nvt_run: Universe,\n    center_atom: Atom,\n    distance_dict: Dict[str, float],\n    select_dict: Dict[str, str],\n    run_start,\n    run_end,\n    write=False,\n    structure_code=None,\n    write_freq=0,\n    write_path=None,\n) -> Dict[str, np.ndarray]:\n    \"\"\"Calculates the coordination number of each specified neighbor species and the total coordination number\n    in the specified frame range.\n\n    Args:\n        nvt_run: An MDAnalysis ``Universe`` containing wrapped trajectory.\n        center_atom: The solvation shell center atom.\n        distance_dict: A dict of coordination cutoff distance of the neighbor species.\n        select_dict: A dictionary of atom species selection, where each atom species name is a key\n            and the corresponding values are the selection language.\n        run_start: Start frame of analysis.\n        run_end: End frame of analysis.\n        write: Whether to writes out a series of desired solvation structures as ``*.xyz`` files.\n        structure_code: An integer code representing the solvation structure to write out.\n            For example, 221 is two species A, two species B and one species C.\n        write_freq: Probability to write out files.\n        write_path: Path to write out files.\n\n    Returns:\n        A diction containing the coordination number sequence of each specified neighbor species\n        and the total coordination number sequence in the specified frame range .\n    \"\"\"\n    time_count = 0\n    trj_analysis = nvt_run.trajectory[run_start:run_end:]\n    cn_values = {}\n    species = list(distance_dict.keys())\n    for kw in species:\n        cn_values[kw] = np.zeros(int(len(trj_analysis)))\n    cn_values[\"total\"] = np.zeros(int(len(trj_analysis)))\n    for ts in trj_analysis:\n        digit_of_species = len(species) - 1\n        for kw in species:\n            selection = select_shell(select_dict, distance_dict, center_atom, kw)\n            shell = nvt_run.select_atoms(selection, periodic=True)\n            # for each atom in shell, create/add to dictionary\n            # (key = atom id, value = list of values for step function)\n            for _ in shell.atoms:\n                cn_values[kw][time_count] += 1\n                cn_values[\"total\"][time_count] += 10 ** digit_of_species\n            digit_of_species = digit_of_species - 1\n        if write and cn_values[\"total\"][time_count] == structure_code:\n            a = np.random.random()\n            if a > 1 - write_freq:\n                print(\"writing\")\n                selection_write = \" or \".join(\n                    \"(same resid as \" + select_shell(select_dict, distance_dict, center_atom, kw) + \")\"\n                    for kw in species\n                )\n                center_selection = \"same type as index \" + str(center_atom.index)\n                selection_write = \"((\" + selection_write + \") and not \" + center_selection + \")\"\n                structure = nvt_run.select_atoms(selection_write, periodic=True)\n                center_pos = ts[center_atom.index]\n                center_name = center_atom.name\n                path = write_path + str(center_atom.id) + \"_\" + str(int(ts.time)) + \"_\" + str(structure_code) + \".xyz\"\n                write_out(center_pos, center_name, structure, path)\n        time_count += 1\n    return cn_values\n\n\ndef num_of_neighbor_simple(\n    nvt_run: Universe,\n    center_atom: Atom,\n    distance_dict: Dict[str, float],\n    select_dict: Dict[str, str],\n    run_start: int,\n    run_end: int,\n) -> Dict[str, np.ndarray]:\n    \"\"\"Calculates solvation structure type (1 for SSIP, 2 for CIP and 3 for AGG) with respect to the ``enter_atom``\n    in the specified frame range.\n\n    Args:\n        nvt_run: An MDAnalysis ``Universe`` containing wrapped trajectory.\n        center_atom: The solvation shell center atom.\n        distance_dict: A dict of coordination cutoff distance of the neighbor species.\n        select_dict: A dictionary of atom species selection, where each atom species name is a key\n            and the corresponding values are the selection language.\n        run_start: Start frame of analysis.\n        run_end: End frame of analysis.\n\n    Returns:\n        A dict with \"total\" as the key and an array of the solvation structure type in the specified frame range\n        as the value.\n    \"\"\"\n\n    time_count = 0\n    trj_analysis = nvt_run.trajectory[run_start:run_end:]\n    center_selection = \"same type as index \" + str(center_atom.index)\n    assert len(distance_dict) == 1, \"Please only specify the counter-ion species in the distance_dict\"\n    species = list(distance_dict.keys())[0]\n    cn_values = np.zeros(int(len(trj_analysis)))\n    for ts in trj_analysis:\n        selection = select_shell(select_dict, distance_dict, center_atom, species)\n        shell = nvt_run.select_atoms(selection, periodic=True)\n        shell_len = len(shell)\n        if shell_len == 0:\n            cn_values[time_count] = 1\n        elif shell_len == 1:\n            selection_species = select_shell(center_selection, distance_dict, shell.atoms[0], species)\n            shell_species = nvt_run.select_atoms(selection_species, periodic=True)\n            shell_species_len = len(shell_species) - 1\n            if shell_species_len == 0:\n                cn_values[time_count] = 2\n            else:\n                cn_values[time_count] = 3\n        else:\n            cn_values[time_count] = 3\n        time_count += 1\n    cn_values = {\"total\": cn_values}\n    return cn_values\n\n\ndef angular_dist_of_neighbor(\n    nvt_run: Universe,\n    center_atom: Atom,\n    distance_dict: Dict[str, float],\n    select_dict: Dict[str, str],\n    run_start: int,\n    run_end: int,\n    cip: bool = True,\n) -> Dict[str, np.ndarray]:\n    \"\"\"\n    Calculates the angle of a-c-b of center atom c in the specified frames.\n\n    Args:\n        nvt_run: An MDAnalysis ``Universe`` containing wrapped trajectory.\n        center_atom: The center atom object.\n        select_dict: A dictionary of atom species selection, where each atom species name is a key\n            and the corresponding values are the selection language.\n        distance_dict: A dict of coordination cutoff distance of the neighbor species. The key must be\n            in the order of a, b, c, where a is the neighbor species used for determining coordination type,\n            b is the other neighbor species, and c is the center species.\n        run_start: Start frame of analysis.\n        run_end: End frame of analysis.\n        cip: Only includes contact ion pair structures with only one `a` and one `c` atoms.\n            Default to True.\n\n    Returns:\n        An array of angles of a-c-b occurrence in the specified frames.\n    \"\"\"\n    names = list(distance_dict.keys())\n    assert len(names) == 3, \"Invalid number of keys in distance_dict, should be 3.\"\n    neighbor_a, neighbor_b, center_c = tuple(names)\n    acb_angle = []\n    trj_analysis = nvt_run.trajectory[run_start:run_end:]\n    for ts in trj_analysis:\n        a_selection = select_shell(select_dict, distance_dict, center_atom, neighbor_a)\n        a_group = nvt_run.select_atoms(a_selection, periodic=True)\n        a_num = len(a_group)\n        if a_num == 0:\n            continue\n        if a_num == 1:\n            c_selection = select_shell(select_dict, distance_dict, a_group.atoms[0], center_c)\n            c_atoms = nvt_run.select_atoms(c_selection, periodic=True)\n            shell_species_len = len(c_atoms) - 1\n            if shell_species_len == 0:\n                shell_type = \"cip\"\n            else:\n                shell_type = \"agg\"\n        else:\n            shell_type = \"agg\"\n        if shell_type == \"agg\" and cip:\n            continue\n        c_pos = center_atom.position\n        for a_atom in a_group.atoms:\n            a_pos = a_atom.position\n            b_selection = select_shell(select_dict, distance_dict, center_atom, neighbor_b)\n            b_group = nvt_run.select_atoms(b_selection, periodic=True)\n            for b_atom in b_group.atoms:\n                b_pos = b_atom.position\n                theta = angle(a_pos, c_pos, b_pos)\n                acb_angle.append(theta)\n    return {\"total\": np.array(acb_angle)}\n\n\ndef num_of_neighbor_specific(\n    nvt_run: Universe,\n    center_atom: Atom,\n    distance_dict: Dict[str, float],\n    select_dict: Dict[str, str],\n    run_start: int,\n    run_end: int,\n    counter_atom: str = \"anion\",\n) -> Dict[str, np.ndarray]:\n    \"\"\"\n    Calculates the coordination number of each specific solvation structure type (SSIP, CIP, AGG).\n\n    Args:\n        nvt_run: An MDAnalysis ``Universe`` containing wrapped trajectory.\n        center_atom: The center atom object.\n        distance_dict: A dict of coordination cutoff distance of the neighbor species.\n        select_dict: A dictionary of atom species selection, where each atom species name is a key\n            and the corresponding values are the selection language.\n        run_start: Start frame of analysis.\n        run_end: End frame of analysis.\n        counter_atom: The neighbor counter ion species. Default to \"anion\".\n\n    Returns:\n        A tuple containing three dictionary of the coordination number of each neighbor species\n        and total coordination number for the three solvation structure type, respectively.\n    \"\"\"\n    time_count = 0\n    trj_analysis = nvt_run.trajectory[run_start:run_end:]\n    cip_step = []\n    ssip_step = []\n    agg_step = []\n    cn_values = {}\n    for kw in distance_dict:\n        cn_values[kw] = np.zeros(int(len(trj_analysis)))\n    cn_values[\"total\"] = np.zeros(int(len(trj_analysis)))\n    for ts in trj_analysis:\n        for kw in distance_dict:\n            kw_selection = select_shell(select_dict, distance_dict, center_atom, kw)\n            kw_shell = nvt_run.select_atoms(kw_selection, periodic=True)\n            cn_values[kw][time_count] += len(kw_shell)\n            cn_values[\"total\"][time_count] += len(kw_shell)\n\n        selection = select_shell(select_dict, distance_dict, center_atom, counter_atom)\n        shell = nvt_run.select_atoms(selection, periodic=True)\n        shell_len = len(shell)\n        center_selection = \"same type as index \" + str(center_atom.index)\n        if shell_len == 0:\n            ssip_step.append(time_count)\n        elif shell_len == 1:\n            selection_species = select_shell(center_selection, distance_dict, shell.atoms[0], counter_atom)\n            shell_species = nvt_run.select_atoms(selection_species, periodic=True)\n            shell_species_len = len(shell_species) - 1\n            if shell_species_len == 0:\n                cip_step.append(time_count)\n            else:\n                agg_step.append(time_count)\n        else:\n            agg_step.append(time_count)\n        time_count += 1\n    cn_dict = {}\n    for kw in distance_dict:\n        cn_dict[\"ssip_\" + kw] = cn_values[kw][ssip_step]\n        cn_dict[\"cip_\" + kw] = cn_values[kw][cip_step]\n        cn_dict[\"agg_\" + kw] = cn_values[kw][agg_step]\n    return cn_dict\n\n\ndef full_solvation_structure(  # TODO: rewrite the method\n    nvt_run: Universe,\n    center_atom: Atom,\n    center_species: str,\n    counter_species: str,\n    select_dict: Dict[str, str],\n    distance: float,\n    run_start: int,\n    run_end: int,\n    depth: int = 4,\n) -> np.ndarray:\n    \"\"\"\n    Obtain the solvation structure of a full connected ion network with depth-first traversal.\n\n    Args:\n        nvt_run: An MDAnalysis ``Universe`` containing wrapped trajectory.\n        center_atom: The center atom object.\n        center_species: The center ion species. It should be the atom directly connect to the counter ion.\n        counter_species: The neighbor counter ion species. It should be the atom directly connect to the center ion.\n        select_dict: A dictionary of atom species selection, where each atom species name is a key\n            and the corresponding values are the selection language.\n        distance: The coordination cutoff distance.\n        run_start: Start frame of analysis.\n        run_end: End frame of analysis.\n        depth: The depth of the traversal. Default to 4\n\n    Returns:\n        Return an array of full solvation structure of the specified frames. Each solvation structure is represented by\n        an array of the number of ions from the first to the n-th solvation shell with n=``depth``.\n    \"\"\"\n    center_selection = select_dict.get(center_species)\n    counter_selection = select_dict.get(counter_species)\n    assert (center_selection is not None) and (counter_selection is not None)\n\n    def select_counter_ion(selection, dist, atom):\n        return \"(\" + selection + \" and around \" + str(dist) + \" same fragment as index \" + str(atom.index) + \")\"\n\n    def center_shell(this_shell, this_layer, frame):\n        for counter in this_shell.atoms:\n            if counter.id not in counter_ion_list:\n                counter_ion_list.append(counter.id)\n                cn_values[frame][this_layer] += 1\n                if this_layer + 1 < depth:\n                    next_shell = nvt_run.select_atoms(\n                        select_counter_ion(center_selection, distance, counter),\n                        periodic=True,\n                    )\n                    counter_shell(next_shell, this_layer + 1, frame)\n\n    def counter_shell(this_shell, this_layer, frame):\n        for center in this_shell.atoms:\n            if center.id not in center_ion_list:\n                center_ion_list.append(center.id)\n                cn_values[frame][this_layer] += 1\n                if this_layer + 1 < depth:\n                    next_shell = nvt_run.select_atoms(\n                        select_counter_ion(counter_selection, distance, center),\n                        periodic=True,\n                    )\n                    center_shell(next_shell, this_layer + 1, frame)\n\n    time_count = 0\n    trj_analysis = nvt_run.trajectory[run_start:run_end:]\n    cn_values = np.zeros((int(len(trj_analysis)), depth))\n    for ts in trj_analysis:\n        center_ion_list: List[np.int_] = [center_atom.id]\n        counter_ion_list: List[np.int_] = []\n        first_shell = nvt_run.select_atoms(\n            select_counter_ion(counter_selection, distance, center_atom),\n            periodic=True,\n        )\n        center_shell(first_shell, 0, time_count)\n    return cn_values\n\n\ndef concat_coord_array(\n    nvt_run: Universe,\n    func: Callable,\n    center_atoms: AtomGroup,\n    distance_dict: Dict[str, float],\n    select_dict: Dict[str, str],\n    run_start: int,\n    run_end: int,\n    **kwargs: Union[bool, str],\n) -> Dict[str, np.ndarray]:\n    \"\"\"\n    A helper function to analyze the coordination number/structure of every atoms in an ``AtomGroup`` using the\n    specified function.\n\n    Args:\n        nvt_run: An MDAnalysis ``Universe`` containing wrapped trajectory.\n        func: One of the neighbor statistical method (num_of_neighbor, num_of_neighbor_simple)\n        center_atoms: Atom group of the center atoms.\n        distance_dict: A dictionary of coordination cutoff distance of the neighbor species.\n        select_dict: A dictionary of atom species selection, where each atom species name is a key\n            and the corresponding values are the selection language.\n        run_start: Start frame of analysis.\n        run_end: End frame of analysis.\n\n    Returns:\n        A diction containing the coordination number sequence of each specified neighbor species\n        and the total coordination number sequence in the specified frame range.\n    \"\"\"\n    num_array = func(nvt_run, center_atoms[0], distance_dict, select_dict, run_start, run_end, **kwargs)\n    for atom in tqdm(center_atoms[1::]):\n        this_atom = func(nvt_run, atom, distance_dict, select_dict, run_start, run_end, **kwargs)\n        for kw in num_array:\n            num_array[kw] = np.concatenate((num_array.get(kw), this_atom.get(kw)), axis=0)\n    return num_array\n\n\ndef write_out(center_pos: np.ndarray, center_name: str, neighbors: AtomGroup, path: str):\n    \"\"\"\n    Helper function for solvation structure coordinates write out.\n\n    Args:\n        center_pos: The coordinates of the center atom in the frame.\n        center_name: The element name of the center atom in the frame.\n        neighbors: The neighbor AtomGroup.\n        path: The path to write out ``*.xyz`` file.\n    \"\"\"\n    lines = []\n    lines.append(str(len(neighbors) + 1))\n    lines.append(\"\")\n    lines.append(f\"{center_name} 0.0000000 0.0000000 0.0000000\")\n    box = neighbors.dimensions\n    half_box = np.array([box[0], box[1], box[2]]) / 2\n    for atom in neighbors:\n        locs = []\n        for i in range(3):\n            loc = atom.position[i] - center_pos[i]\n            if loc > half_box[i]:\n                loc = loc - box[i]\n            elif loc < -half_box[i]:\n                loc = loc + box[i]\n            else:\n                pass\n            locs.append(loc)\n        element_name = atom.name\n        assert element_name is not None\n        line = element_name + \" \" + \" \".join(str(loc) for loc in locs)\n        lines.append(line)\n    with open(path, \"w\") as xyz_file:\n        xyz_file.write(\"\\n\".join(lines))\n\n\ndef select_shell(\n    select: Union[Dict[str, str], str], distance: Union[Dict[str, float], str], center_atom: Atom, kw: str\n) -> str:\n    \"\"\"\n    Select a group of atoms that is within a distance of an ``center_atom``.\n\n    Args:\n        select: A selection string of neighbors or a dictionary of atom species selection, where each atom\n            species name is a key and the corresponding values are the selection string.\n        distance: A neighbor cutoff distance or a dict of cutoff distances of neighbor species.\n        center_atom: The solvation shell center ``Atom`` object\n        kw: The key for the select and/or distance dictionary if applicable.\n\n    Returns:\n        A selection string specifying the neighbor species within a distance of the ``center_atom``.\n    \"\"\"\n    if isinstance(select, dict):\n        species_selection = select[kw]\n        if species_selection is None:\n            raise ValueError(\"Species specified does not match entries in the select dict.\")\n    else:\n        species_selection = select\n    if isinstance(distance, dict):\n        distance_value = distance[kw]\n        if distance_value is None:\n            raise ValueError(\"Species specified does not match entries in the distance dict.\")\n        distance_str = str(distance_value)\n    else:\n        distance_str = distance\n    selection = \"(\" + species_selection + \") and (around \" + distance_str + \" index \" + str(center_atom.index) + \")\"\n    return selection\n", "meta": {"hexsha": "fbbc4174050c9eeb6a56d991cd7a83e532558bda", "size": 47123, "ext": "py", "lang": "Python", "max_stars_repo_path": "mdgo/coordination.py", "max_stars_repo_name": "HT-MD/mdgo", "max_stars_repo_head_hexsha": "bd06b226c6015fb083c099508bc81f521a4329c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-15T01:18:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T01:18:13.000Z", "max_issues_repo_path": "mdgo/coordination.py", "max_issues_repo_name": "HT-MD/mdgo", "max_issues_repo_head_hexsha": "bd06b226c6015fb083c099508bc81f521a4329c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-11-12T20:48:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T23:41:47.000Z", "max_forks_repo_path": "mdgo/coordination.py", "max_forks_repo_name": "HT-MD/mdgo", "max_forks_repo_head_hexsha": "bd06b226c6015fb083c099508bc81f521a4329c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-11-12T21:10:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T19:30:57.000Z", "avg_line_length": 41.4450307828, "max_line_length": 120, "alphanum_fraction": 0.621925599, "include": true, "reason": "import numpy,from scipy", "num_tokens": 10620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3345894478883556, "lm_q1q2_score": 0.17382635227817939}}
{"text": "import logging\nimport string\nimport sys\nfrom collections import deque\n\nimport numpy as np\nfrom scipy.special import logsumexp\nfrom sklearn.base import BaseEstimator\nfrom sklearn.utils import check_array, check_random_state\nimport scipy.optimize\nfrom . import _hmmc, _utils\nfrom .utils import normalize, log_normalize, iter_from_X_lengths, log_mask_zero\n\n\n_log = logging.getLogger(__name__)\n#: Supported decoder algorithms.\nDECODER_ALGORITHMS = frozenset((\"viterbi\", \"map\"))\n\n\nclass ConvergenceMonitor:\n    \"\"\"Monitors and reports convergence to :data:`sys.stderr`.\n\n    Parameters\n    ----------\n    tol : double\n        Convergence threshold. EM has converged either if the maximum\n        number of iterations is reached or the log probability\n        improvement between the two consecutive iterations is less\n        than threshold.\n\n    n_iter : int\n        Maximum number of iterations to perform.\n\n    verbose : bool\n        If ``True`` then per-iteration convergence reports are printed,\n        otherwise the monitor is mute.\n\n    Attributes\n    ----------\n    history : deque\n        The log probability of the data for the last two training\n        iterations. If the values are not strictly increasing, the\n        model did not converge.\n\n    iter : int\n        Number of iterations performed while training the model.\n\n    Examples\n    --------\n    Use custom convergence criteria by subclassing ``ConvergenceMonitor``\n    and redefining the ``converged`` method. The resulting subclass can\n    be used by creating an instance and pointing a model's ``monitor_``\n    attribute to it prior to fitting.\n\n    >>> from hmmlearn.base import ConvergenceMonitor\n    >>> from hmmlearn import hmm\n    >>>\n    >>> class ThresholdMonitor(ConvergenceMonitor):\n    ...     @property\n    ...     def converged(self):\n    ...         return (self.iter == self.n_iter or\n    ...                 self.history[-1] >= self.tol)\n    >>>\n    >>> model = hmm.GaussianHMM(n_components=2, tol=5, verbose=True)\n    >>> model.monitor_ = ThresholdMonitor(model.monitor_.tol,\n    ...                                   model.monitor_.n_iter,\n    ...                                   model.monitor_.verbose)\n    \"\"\"\n    _template = \"{iter:>10d} {logprob:>16.4f} {delta:>+16.4f}\"\n\n    def __init__(self, tol, n_iter, verbose):\n        self.tol = tol\n        self.n_iter = n_iter\n        self.verbose = verbose\n        self.history = deque(maxlen=2)\n        self.iter = 0\n\n    def __repr__(self):\n        class_name = self.__class__.__name__\n        params = sorted(dict(vars(self), history=list(self.history)).items())\n        return (\"{}(\\n\".format(class_name)\n                + \"\".join(map(\"    {}={},\\n\".format, *zip(*params)))\n                + \")\")\n\n    def _reset(self):\n        \"\"\"Reset the monitor's state.\"\"\"\n        self.iter = 0\n        self.history.clear()\n\n    def report(self, logprob):\n        \"\"\"Reports convergence to :data:`sys.stderr`.\n\n        The output consists of three columns: iteration number, log\n        probability of the data at the current iteration and convergence\n        rate.  At the first iteration convergence rate is unknown and\n        is thus denoted by NaN.\n\n        Parameters\n        ----------\n        logprob : float\n            The log probability of the data as computed by EM algorithm\n            in the current iteration.\n        \"\"\"\n        if self.verbose:\n            delta = logprob - self.history[-1] if self.history else np.nan\n            message = self._template.format(\n                iter=self.iter + 1, logprob=logprob, delta=delta)\n            print(message, file=sys.stderr)\n\n        self.history.append(logprob)\n        self.iter += 1\n\n    @property\n    def converged(self):\n        \"\"\"``True`` if the EM algorithm converged and ``False`` otherwise.\"\"\"\n        # XXX we might want to check that ``logprob`` is non-decreasing.\n        return (self.iter == self.n_iter or\n                (len(self.history) == 2 and\n                 self.history[1] - self.history[0] < self.tol))\n\n\nclass _BaseHMM(BaseEstimator):\n    r\"\"\"Base class for Hidden Markov Models.\n\n    This class allows for easy evaluation of, sampling from, and\n    maximum a posteriori estimation of the parameters of a HMM.\n\n    See the instance documentation for details specific to a\n    particular object.\n\n    Parameters\n    ----------\n    n_components : int\n        Number of states in the model.\n\n    startprob_prior : array, shape (n_components, ), optional\n        Parameters of the Dirichlet prior distribution for\n        :attr:`startprob_`.\n\n    transmat_prior : array, shape (n_components, n_components), optional\n        Parameters of the Dirichlet prior distribution for each row\n        of the transition probabilities :attr:`transmat_`.\n\n    algorithm : string, optional\n        Decoder algorithm. Must be one of \"viterbi\" or \"map\".\n        Defaults to \"viterbi\".\n\n    random_state: RandomState or an int seed, optional\n        A random number generator instance.\n\n    n_iter : int, optional\n        Maximum number of iterations to perform.\n\n    tol : float, optional\n        Convergence threshold. EM will stop if the gain in log-likelihood\n        is below this value.\n\n    verbose : bool, optional\n        When ``True`` per-iteration convergence reports are printed\n        to :data:`sys.stderr`. You can diagnose convergence via the\n        :attr:`monitor_` attribute.\n\n    params : string, optional\n        Controls which parameters are updated in the training\n        process.  Can contain any combination of 's' for startprob,\n        't' for transmat, and other characters for subclass-specific\n        emission parameters. Defaults to all parameters.\n\n    init_params : string, optional\n        Controls which parameters are initialized prior to\n        training.  Can contain any combination of 's' for\n        startprob, 't' for transmat, and other characters for\n        subclass-specific emission parameters. Defaults to all\n        parameters.\n\n    Attributes\n    ----------\n    monitor\\_ : ConvergenceMonitor\n        Monitor object used to check the convergence of EM.\n\n    startprob\\_ : array, shape (n_components, )\n        Initial state occupation distribution.\n\n    transmat\\_ : array, shape (n_components, n_components)\n        Matrix of transition probabilities between states.\n    \"\"\"\n    def __init__(self, n_components=1,\n                 startprob_prior=1.0, transmat_prior=1.0,\n                 algorithm=\"viterbi\", random_state=None,\n                 n_iter=10, tol=1e-2, verbose=False,\n                 params=string.ascii_letters,\n                 init_params=string.ascii_letters,\n                 A1 = None,\n                 a = 0,\n                 b = 1,\n                 grad_iter = 100,\n                 grad_conv = 10**-2,\n                 grad_lr = 10**-2,\n                 t0 = 0,\n                 transmat_ = None,\n                 startprob_ = None):\n        self.n_components = n_components\n        self.params = params\n        self.init_params = init_params\n        self.startprob_prior = startprob_prior\n        self.transmat_prior = transmat_prior\n        self.algorithm = algorithm\n        self.random_state = random_state\n        self.n_iter = n_iter\n        self.tol = tol\n        self.verbose = verbose\n        self.monitor_ = ConvergenceMonitor(self.tol, self.n_iter, self.verbose)\n        # added samuelbray32\n        self.A1 = A1 #time dependent transition matrix\n        self.a = a #parameters of sigmoid function\n        self.b = b\n        self.grad_iter = grad_iter #stop criteria for _grad_descent\n        self.grad_conv = grad_conv\n        self.grad_lr = grad_lr\n        self.t0 = t0\n        self.transmat_ = transmat_\n        self.startprob_ = startprob_\n        self.track_params = []\n        self.grad_method = 'newtons_linesearch'\n\n    def get_stationary_distribution(self):\n        \"\"\"Compute the stationary distribution of states.\n        \"\"\"\n        # The stationary distribution is proportional to the left-eigenvector\n        # associated with the largest eigenvalue (i.e., 1) of the transition\n        # matrix.\n        _utils.check_is_fitted(self, \"transmat_\")\n        eigvals, eigvecs = np.linalg.eig(self.transmat_.T)\n        eigvec = np.real_if_close(eigvecs[:, np.argmax(eigvals)])\n        return eigvec / eigvec.sum()\n\n    def score_samples(self, X, lengths=None):\n        \"\"\"Compute the log probability under the model and compute posteriors.\n\n        Parameters\n        ----------\n        X : array-like, shape (n_samples, n_features)\n            Feature matrix of individual samples.\n\n        lengths : array-like of integers, shape (n_sequences, ), optional\n            Lengths of the individual sequences in ``X``. The sum of\n            these should be ``n_samples``.\n\n        Returns\n        -------\n        logprob : float\n            Log likelihood of ``X``.\n\n        posteriors : array, shape (n_samples, n_components)\n            State-membership probabilities for each sample in ``X``.\n\n        See Also\n        --------\n        score : Compute the log probability under the model.\n        decode : Find most likely state sequence corresponding to ``X``.\n        \"\"\"\n        _utils.check_is_fitted(self, \"startprob_\")\n        self._check()\n\n        X = check_array(X)\n        n_samples = X.shape[0]\n        logprob = 0\n        posteriors = np.zeros((n_samples, self.n_components))\n        for i, j in iter_from_X_lengths(X, lengths):\n            framelogprob = self._compute_log_likelihood(X[i:j])\n            logprobij, fwdlattice = self._do_forward_pass(framelogprob)\n            logprob += logprobij\n\n            bwdlattice = self._do_backward_pass(framelogprob)\n            posteriors[i:j] = self._compute_posteriors(fwdlattice, bwdlattice)\n        return logprob, posteriors\n\n    def score(self, X, lengths=None):\n        \"\"\"Compute the log probability under the model.\n\n        Parameters\n        ----------\n        X : array-like, shape (n_samples, n_features)\n            Feature matrix of individual samples.\n\n        lengths : array-like of integers, shape (n_sequences, ), optional\n            Lengths of the individual sequences in ``X``. The sum of\n            these should be ``n_samples``.\n\n        Returns\n        -------\n        logprob : float\n            Log likelihood of ``X``.\n\n        See Also\n        --------\n        score_samples : Compute the log probability under the model and\n            posteriors.\n        decode : Find most likely state sequence corresponding to ``X``.\n        \"\"\"\n        _utils.check_is_fitted(self, \"startprob_\")\n        self._check()\n\n        X = check_array(X)\n        # XXX we can unroll forward pass for speed and memory efficiency.\n        logprob = 0\n        for i, j in iter_from_X_lengths(X, lengths):\n            framelogprob = self._compute_log_likelihood(X[i:j])\n            logprobij, _fwdlattice = self._do_forward_pass(framelogprob)\n            logprob += logprobij\n        return logprob\n\n    def _decode_viterbi(self, X):\n        framelogprob = self._compute_log_likelihood(X)\n        return self._do_viterbi_pass(framelogprob)\n\n    def _decode_map(self, X):\n        _, posteriors = self.score_samples(X)\n        logprob = np.max(posteriors, axis=1).sum()\n        state_sequence = np.argmax(posteriors, axis=1)\n        return logprob, state_sequence\n\n    def decode(self, X, lengths=None, algorithm=None):\n        \"\"\"Find most likely state sequence corresponding to ``X``.\n\n        Parameters\n        ----------\n        X : array-like, shape (n_samples, n_features)\n            Feature matrix of individual samples.\n\n        lengths : array-like of integers, shape (n_sequences, ), optional\n            Lengths of the individual sequences in ``X``. The sum of\n            these should be ``n_samples``.\n\n        algorithm : string\n            Decoder algorithm. Must be one of \"viterbi\" or \"map\".\n            If not given, :attr:`decoder` is used.\n\n        Returns\n        -------\n        logprob : float\n            Log probability of the produced state sequence.\n\n        state_sequence : array, shape (n_samples, )\n            Labels for each sample from ``X`` obtained via a given\n            decoder ``algorithm``.\n\n        See Also\n        --------\n        score_samples : Compute the log probability under the model and\n            posteriors.\n        score : Compute the log probability under the model.\n        \"\"\"\n        _utils.check_is_fitted(self, \"startprob_\")\n        self._check()\n\n        algorithm = algorithm or self.algorithm\n        if algorithm not in DECODER_ALGORITHMS:\n            raise ValueError(\"Unknown decoder {!r}\".format(algorithm))\n\n        decoder = {\n            \"viterbi\": self._decode_viterbi,\n            \"map\": self._decode_map\n        }[algorithm]\n\n        X = check_array(X)\n        n_samples = X.shape[0]\n        logprob = 0\n        state_sequence = np.empty(n_samples, dtype=int)\n        for i, j in iter_from_X_lengths(X, lengths):\n            # XXX decoder works on a single sample at a time!\n            logprobij, state_sequenceij = decoder(X[i:j])\n            logprob += logprobij\n            state_sequence[i:j] = state_sequenceij\n\n        return logprob, state_sequence\n\n    def predict(self, X, lengths=None):\n        \"\"\"Find most likely state sequence corresponding to ``X``.\n\n        Parameters\n        ----------\n        X : array-like, shape (n_samples, n_features)\n            Feature matrix of individual samples.\n\n        lengths : array-like of integers, shape (n_sequences, ), optional\n            Lengths of the individual sequences in ``X``. The sum of\n            these should be ``n_samples``.\n\n        Returns\n        -------\n        state_sequence : array, shape (n_samples, )\n            Labels for each sample from ``X``.\n        \"\"\"\n        _, state_sequence = self.decode(X, lengths)\n        return state_sequence\n\n    def predict_proba(self, X, lengths=None):\n        \"\"\"Compute the posterior probability for each state in the model.\n\n        X : array-like, shape (n_samples, n_features)\n            Feature matrix of individual samples.\n\n        lengths : array-like of integers, shape (n_sequences, ), optional\n            Lengths of the individual sequences in ``X``. The sum of\n            these should be ``n_samples``.\n\n        Returns\n        -------\n        posteriors : array, shape (n_samples, n_components)\n            State-membership probabilities for each sample from ``X``.\n        \"\"\"\n        _, posteriors = self.score_samples(X, lengths)\n        return posteriors\n\n    def sample(self, n_samples=1, random_state=None):\n        \"\"\"Generate random samples from the model.\n\n        Parameters\n        ----------\n        n_samples : int\n            Number of samples to generate.\n\n        random_state : RandomState or an int seed\n            A random number generator instance. If ``None``, the object's\n            ``random_state`` is used.\n\n        Returns\n        -------\n        X : array, shape (n_samples, n_features)\n            Feature matrix.\n\n        state_sequence : array, shape (n_samples, )\n            State sequence produced by the model.\n        \"\"\"\n        _utils.check_is_fitted(self, \"startprob_\")\n        self._check()\n\n        if random_state is None:\n            random_state = self.random_state\n        random_state = check_random_state(random_state)\n\n        startprob_cdf = np.cumsum(self.startprob_)\n        transmat_cdf = np.cumsum(self.transmat_, axis=1)\n\n        currstate = (startprob_cdf > random_state.rand()).argmax()\n        state_sequence = [currstate]\n        X = [self._generate_sample_from_state(\n            currstate, random_state=random_state)]\n\n        for t in range(n_samples - 1):\n            currstate = (transmat_cdf[currstate] > random_state.rand()) \\\n                .argmax()\n            state_sequence.append(currstate)\n            X.append(self._generate_sample_from_state(\n                currstate, random_state=random_state))\n\n        return np.atleast_2d(X), np.array(state_sequence, dtype=int)\n\n    def fit(self, X, lengths=None):\n        \"\"\"Estimate model parameters.\n\n        An initialization step is performed before entering the\n        EM algorithm. If you want to avoid this step for a subset of\n        the parameters, pass proper ``init_params`` keyword argument\n        to estimator's constructor.\n\n        Parameters\n        ----------\n        X : array-like, shape (n_samples, n_features)\n            Feature matrix of individual samples.\n\n        lengths : array-like of integers, shape (n_sequences, )\n            Lengths of the individual sequences in ``X``. The sum of\n            these should be ``n_samples``.\n\n        Returns\n        -------\n        self : object\n            Returns self.\n        \"\"\"\n        X = check_array(X)\n        self._init(X, lengths=lengths)\n        self._check()\n\n        self.monitor_._reset()\n        for iter in range(self.n_iter):\n            print('E iteration: ', iter)\n            stats = self._initialize_sufficient_statistics()\n            curr_logprob = 0\n            for i, j in iter_from_X_lengths(X, lengths):\n                framelogprob = self._compute_log_likelihood(X[i:j])\n                logprob, fwdlattice = self._do_forward_pass(framelogprob)\n                curr_logprob += logprob\n                bwdlattice = self._do_backward_pass(framelogprob)\n                posteriors = self._compute_posteriors(fwdlattice, bwdlattice)\n                self._accumulate_sufficient_statistics(\n                    stats, X[i:j], framelogprob, posteriors, fwdlattice,\n                    bwdlattice)\n                print('fwd: ', fwdlattice[10])\n                print('bwd: ', bwdlattice[10])\n            # XXX must be before convergence check, because otherwise\n            #     there won't be any updates for the case ``n_iter=1``.\n            del fwdlattice\n            del bwdlattice\n            del framelogprob\n            self._do_mstep(stats, posteriors)\n\n            self.monitor_.report(curr_logprob)\n            if self.monitor_.converged:\n                break\n\n        if (self.transmat_.sum(axis=1) == 0).any():\n            _log.warning(\"Some rows of transmat_ have zero sum because no \"\n                         \"transition from the state was ever observed.\")\n\n        return self\n\n    def _do_viterbi_pass(self, framelogprob):\n        n_samples, n_components = framelogprob.shape\n        state_sequence, logprob = _hmmc._viterbi(\n            n_samples, n_components, log_mask_zero(self.startprob_),\n            log_mask_zero(self.transmat_), framelogprob)\n        return logprob, state_sequence\n\n    def _do_forward_pass(self, framelogprob):\n        n_samples, n_components = framelogprob.shape\n        fwdlattice = np.zeros((n_samples, n_components))\n        # _hmmc._forward(n_samples, n_components,\n        #                log_mask_zero(self.startprob_),\n        #                self.transmat_,\n        #                framelogprob, fwdlattice,\n        #                self.A1,\n        #                self.U(np.arange(n_samples)+self.t0))\n        t = np.arange(n_samples)+self.t0\n        log_trans = self.transmat_ + np.transpose(self.A1[:,:,None]*self.U(t),[2,0,1])\n        log_trans[log_trans<0] = 10**-20\n        print('trans: ', np.min(log_trans))\n        log_trans = log_mask_zero(log_trans)\n        print('log_trans: ', np.max(log_trans))\n        _hmmc._forward(n_samples, n_components,\n                       log_mask_zero(self.startprob_),\n                       log_trans,\n                       framelogprob, fwdlattice,)\n\n        with np.errstate(under=\"ignore\"):\n            return logsumexp(fwdlattice[-1]), fwdlattice\n\n    def _do_backward_pass(self, framelogprob):\n        n_samples, n_components = framelogprob.shape\n        bwdlattice = np.zeros((n_samples, n_components))\n        # _hmmc._backward(n_samples, n_components,\n        #                 log_mask_zero(self.startprob_),\n        #                 self.transmat_,\n        #                 framelogprob, bwdlattice,\n        #                 self.A1,\n        #                 self.U(np.arange(n_samples)+self.t0))\n        t = np.arange(n_samples)+self.t0\n        log_trans = self.transmat_ + np.transpose(self.A1[:,:,None]*self.U(t),[2,0,1])\n        log_trans[log_trans<0] = 10**-20\n        print('trans: ', np.min(log_trans))\n        log_trans = log_mask_zero(log_trans)\n        print('log_trans: ', np.max(log_trans))\n        _hmmc._backward(n_samples, n_components,\n                       log_mask_zero(self.startprob_),\n                       log_trans,\n                       framelogprob, bwdlattice,)\n        return bwdlattice\n\n    def _compute_posteriors(self, fwdlattice, bwdlattice):\n        # gamma is guaranteed to be correctly normalized by logprob at\n        # all frames, unless we do approximate inference using pruning.\n        # So, we will normalize each frame explicitly in case we\n        # pruned too aggressively.\n        log_gamma = fwdlattice + bwdlattice\n        log_normalize(log_gamma, axis=1)\n        with np.errstate(under=\"ignore\"):\n            return np.exp(log_gamma)\n\n    def _init(self, X, lengths):\n        \"\"\"Initializes model parameters prior to fitting.\n\n        Parameters\n        ----------\n        X : array-like, shape (n_samples, n_features)\n            Feature matrix of individual samples.\n\n        lengths : array-like of integers, shape (n_sequences, )\n            Lengths of the individual sequences in ``X``. The sum of\n            these should be ``n_samples``.\n        \"\"\"\n        init = 1. / self.n_components\n        if 's' in self.init_params or not hasattr(self, \"startprob_\"):\n            self.startprob_ = np.full(self.n_components, init)\n        if 't' in self.init_params or not hasattr(self, \"transmat_\"):\n            self.transmat_ = np.full((self.n_components, self.n_components),\n                                     init)\n        n_fit_scalars_per_param = self._get_n_fit_scalars_per_param()\n        n_fit_scalars = sum(n_fit_scalars_per_param[p] for p in self.params)\n        if X.size < n_fit_scalars:\n            _log.warning(\"Fitting a model with {} free scalar parameters with \"\n                         \"only {} data points will result in a degenerate \"\n                         \"solution.\".format(n_fit_scalars, X.size))\n\n    def _check(self):\n        \"\"\"Validates model parameters prior to fitting.\n\n        Raises\n        ------\n\n        ValueError\n            If any of the parameters are invalid, e.g. if :attr:`startprob_`\n            don't sum to 1.\n        \"\"\"\n        self.startprob_ = np.asarray(self.startprob_)\n        if len(self.startprob_) != self.n_components:\n            raise ValueError(\"startprob_ must have length n_components\")\n        if not np.allclose(self.startprob_.sum(), 1.0):\n            raise ValueError(\"startprob_ must sum to 1.0 (got {:.4f})\"\n                             .format(self.startprob_.sum()))\n\n        self.transmat_ = np.asarray(self.transmat_)\n        if self.transmat_.shape != (self.n_components, self.n_components):\n            raise ValueError(\n                \"transmat_ must have shape (n_components, n_components)\")\n        if not np.allclose(self.transmat_.sum(axis=1), 1.0):\n            raise ValueError(\"rows of transmat_ must sum to 1.0 (got {})\"\n                             .format(self.transmat_.sum(axis=1)))\n\n    def _compute_log_likelihood(self, X):\n        \"\"\"Computes per-component log probability under the model.\n\n        Parameters\n        ----------\n        X : array-like, shape (n_samples, n_features)\n            Feature matrix of individual samples.\n\n        Returns\n        -------\n        logprob : array, shape (n_samples, n_components)\n            Log probability of each sample in ``X`` for each of the\n            model states.\n        \"\"\"\n\n    def _generate_sample_from_state(self, state, random_state=None):\n        \"\"\"Generates a random sample from a given component.\n\n        Parameters\n        ----------\n        state : int\n            Index of the component to condition on.\n\n        random_state: RandomState or an int seed\n            A random number generator instance. If ``None``, the object's\n            ``random_state`` is used.\n\n        Returns\n        -------\n        X : array, shape (n_features, )\n            A random sample from the emission distribution corresponding\n            to a given component.\n        \"\"\"\n\n    # Methods used by self.fit()\n\n    def _initialize_sufficient_statistics(self):\n        \"\"\"Initializes sufficient statistics required for M-step.\n\n        The method is *pure*, meaning that it doesn't change the state of\n        the instance.  For extensibility computed statistics are stored\n        in a dictionary.\n\n        Returns\n        -------\n        nobs : int\n            Number of samples in the data.\n\n        start : array, shape (n_components, )\n            An array where the i-th element corresponds to the posterior\n            probability of the first sample being generated by the i-th\n            state.\n\n        trans : array, shape (n_components, n_components)\n            An array where the (i, j)-th element corresponds to the\n            posterior probability of transitioning between the i-th to j-th\n            states.\n        \"\"\"\n        stats = {'nobs': 0,\n                 'start': np.zeros(self.n_components),\n                 'trans': np.zeros((self.n_components, self.n_components))}\n        return stats\n\n    def _accumulate_sufficient_statistics(self, stats, X, framelogprob,\n                                          posteriors, fwdlattice, bwdlattice):\n        \"\"\"Updates sufficient statistics from a given sample.\n\n        Parameters\n        ----------\n        stats : dict\n            Sufficient statistics as returned by\n            :meth:`~base._BaseHMM._initialize_sufficient_statistics`.\n\n        X : array, shape (n_samples, n_features)\n            Sample sequence.\n\n        framelogprob : array, shape (n_samples, n_components)\n            Log-probabilities of each sample under each of the model states.\n\n        posteriors : array, shape (n_samples, n_components)\n            Posterior probabilities of each sample being generated by each\n            of the model states.\n\n        fwdlattice, bwdlattice : array, shape (n_samples, n_components)\n            Log-forward and log-backward probabilities.\n        \"\"\"\n        stats['nobs'] += 1\n        if 's' in self.params:\n            stats['start'] += posteriors[0]\n        if 't' in self.params:\n            n_samples, n_components = framelogprob.shape\n            # when the sample is of length 1, it contains no transitions\n            # so there is no reason to update our trans. matrix estimate\n            if n_samples <= 1:\n                return\n\n            log_xi_sum = np.full((n_components, n_components), -np.inf)\n            _hmmc._compute_log_xi_sum(n_samples, n_components, fwdlattice,\n                                      log_mask_zero(self.transmat_),\n                                      bwdlattice, framelogprob,\n                                      log_xi_sum)\n            with np.errstate(under=\"ignore\"):\n                stats['trans'] += np.exp(log_xi_sum)\n\n    def _do_mstep(self, stats, posteriors):\n        \"\"\"Performs the M-step of EM algorithm.\n\n        Parameters\n        ----------\n        stats : dict\n            Sufficient statistics updated from all available samples.\n        \"\"\"\n        # If a prior is < 1, `prior - 1 + starts['start']` can be negative.  In\n        # that case maximization of (n1+e1) log p1 + ... + (ns+es) log ps under\n        # the conditions sum(p) = 1 and all(p >= 0) show that the negative\n        # terms can just be set to zero.\n        # The ``np.where`` calls guard against updating forbidden states\n        # or transitions in e.g. a left-right HMM.\n        if 's' in self.params:\n            startprob_ = np.maximum(self.startprob_prior - 1 + stats['start'],\n                                    0)\n            self.startprob_ = np.where(self.startprob_ == 0, 0, startprob_)\n            normalize(self.startprob_)\n        if 't' in self.params:\n            transmat_ = np.maximum(self.transmat_prior - 1 + stats['trans'], 0)\n            self.transmat_ = np.where(self.transmat_ == 0, 0, transmat_)\n            normalize(self.transmat_, axis=1)\n        if not self.a == None:\n            # self._grad_ascent(self._transition_posterior(posteriors))\n            log_P_tij = log_mask_zero(np.zeros((posteriors.shape[0],self.n_components,self.n_components)))\n            _hmmc._transition_posterior(log_P_tij.shape[0], self.n_components, log_P_tij, log_mask_zero(posteriors))\n            if self.grad_method == 'newtons_linesearch':\n                self._newtons_linesearch(np.exp(log_P_tij[1:]))\n            elif self.grad_method == 'newtons':\n                self._newtons(np.exp(log_P_tij[1:]))\n            elif self.grad_method == 'grad_ascent':\n                self._grad_ascent(np.exp(log_P_tij[1:]))\n            elif self.grad_method == 'grad_ascent_linesearch':\n                self._grad_ascent_linesearch(np.exp(log_P_tij[1:]))\n            elif self.grad_method == 'scipy':\n                self._scipy(np.exp(log_P_tij[1:]))\n            else:\n                print (self.grad_method, ' is not a defined method')\n\n    def _transition_posterior_external(self, log_P_tij, posteriors):\n        _hmmc._transition_posterior(log_P_tij.shape[0], self.n_components, log_P_tij, log_mask_zero(posteriors))\n\n    def U(self, t):\n        return 1-self.sigma(t)\n\n    def dU(self, t):\n        return -self.sigma(t)*(1-self.sigma(t))\n\n    # NEW VERSION: x = t/a - b\n    def sigma(self, t):\n        # print('new sigma')\n        t = t/24/60/120\n        return (1+np.exp(-(t-self.b)/self.a))**-1\n\n    def _grad_ascent(self, P_tij):\n        print('transition posteriors:', P_tij.shape)\n        print('max: ', np.max(P_tij))\n        print('sumcheck: ', np.sum(P_tij[1,:,:]), np.sum(P_tij[-1,:,:]) )\n        if np.array(self.grad_lr).size == 1:\n            self.grad_lr = [self.grad_lr, self.grad_lr]\n        t = np.arange(P_tij.shape[0]) + self.t0\n        for iter in range(self.grad_iter):\n            mu = self._mu(t) * P_tij\n            db = -mu.sum()/self.a *self.grad_lr[1]\n            da = -(((t/24/60/120-self.b)[:,None,None]/self.a**2)*mu).sum()*self.grad_lr[0]\n\n            print('mu: ', self._mu(t)[10].sum())\n            print('gradients: ', da, db)\n            if (np.abs(da) <= self.grad_conv * np.abs(self.a)) and (np.abs(db) <= self.grad_conv * np.abs(self.b)):\n                print('converged: ', iter)\n                print('a: ', self.a)\n                print('b: ', self.b)\n                return;\n            self.a = self.a + da\n            self.b = self.b + db\n            print('a: ', self.a)\n            print('b: ', self.b)\n        print(self.grad_iter)\n\n    def _grad_ascent_linesearch(self, P_tij):\n        t = np.arange(P_tij.shape[0])\n        L = lambda : (P_tij*np.log(self.transmat_ + np.transpose(self.A1[:,:,None]*self.U(t),[2,0,1]))).sum()\n        # grad_ascent update w/ linesearch\n        L_prev = L()\n        for iter in range(self.grad_iter):\n            # define direction\n            mu = self._mu(t) * P_tij\n            db = -mu.sum()/self.a\n            da = -(((t/24/60/120-self.b)[:,None,None]/self.a**2)*mu).sum()\n            delta = np.array([da,db])\n            delta =delta/np.linalg.norm(delta, ord=2)\n            print('grad: ', da, db)\n            # determine step size\n            prev_a = self.a\n            prev_b = self.b\n            updated = False\n            for s in self.grad_lr:\n                self.a = self.a + s*delta[0]\n                self.b = self.b + s*delta[1]\n                L_new = L()\n                # check if sufficient improvement, if so quit\n                #note: log likelihood (L) will always be <0\n                #therefore WANT L_new/L_prev < 1\n                if L_new/L_prev < self.grad_conv:\n                    L_prev = L_new\n                    updated = True\n                    break;\n                else:\n                    self.a = prev_a\n                    self.b = prev_b\n\n            # check convergence\n            # if (np.abs(delta[0]/self.a) < self.grad_conv) and (np.abs(delta[1]/self.b) < self.grad_conv): #TODO: put in convergence criteria\n            #     break\n            if not updated:\n                self.a = prev_a\n                self.b = prev_b\n                print('not updated')\n                break\n            self.track_params.append([self.a,self.b, delta[0], delta[1], L_new])\n            print('a: ',self.a)\n            print('b: ', self.b)\n\n\n    def _newtons(self,P_tij):\n        for i in range(self.grad_iter):\n            print(i)\n            J, g = self._jacobian_grad(P_tij)\n            delta =  - np.matmul(np.linalg.inv(J), g)\n            print('Jac: ', J)\n            print('grad: ', g)\n            print('Diff: ', delta)\n            if (np.abs(delta[0]/self.a) < self.grad_conv) and (np.abs(delta[1]/self.b) < self.grad_conv): #TODO: put in convergence criteria\n                break\n            self.a = self.a + self.grad_lr[0] * delta[0]\n            self.b = self.b + self.grad_lr[1] * delta[1]\n            self.track_params.append([self.a,self.b, delta[0], delta[1]])\n            print('a: ',self.a)\n            print('b: ', self.b)\n        return\n\n    def _newtons_linesearch(self,P_tij):\n        t = np.arange(P_tij.shape[0])\n        L = lambda : (P_tij*np.log(self.transmat_ + np.transpose(self.A1[:,:,None]*self.U(t),[2,0,1]))).sum()\n        #newton update w/ linesearch\n        L_prev = L()\n        for i in range(self.grad_iter):\n            # get step direction\n            print(i)\n            J, g = self._jacobian_grad(P_tij)\n            delta =  - np.matmul(np.linalg.inv(J), g)\n            if np.linalg.norm(delta, ord=2)>1: #sets a maximum to the step size\n                delta =delta/np.linalg.norm(delta, ord=2)\n            print('Jac: ', J)\n            print('grad: ', g)\n            print('Diff: ', delta)\n            # determine step size\n            prev_a = self.a\n            prev_b = self.b\n            updated = False\n            for s in self.grad_lr:\n                self.a = self.a + s*delta[0]\n                self.b = self.b + s*delta[1]\n                L_new = L()\n                # check if sufficient improvement, if so quit\n                #note: log likelihood (L) will always be <0\n                #therefore WANT L_new/L_prev < 1\n                print('L',L_new,L_prev)\n                if L_new/L_prev < self.grad_conv:\n                    L_prev = L_new\n                    updated = True\n                    break;\n                else:\n                    self.a = prev_a\n                    self.b = prev_b\n\n            # check convergence\n            # if (np.abs(delta[0]/self.a) < self.grad_conv) and (np.abs(delta[1]/self.b) < self.grad_conv): #TODO: put in convergence criteria\n            #     break\n            if not updated:\n                self.a = prev_a\n                self.b = prev_b\n                print('not updated')\n                break\n            self.track_params.append([self.a,self.b, delta[0], delta[1], L_new])\n            print('a: ',self.a)\n            print('b: ', self.b)\n\n        return\n\n    def _scipy(self, P_tij):\n        t = np.arange(P_tij.shape[0])\n        def nL(x):\n            a = x[0]\n            b = x[1]\n            u_loc = lambda t: 1-(1+np.exp(-(t/120/60/24-b)/a))**-1\n            t = np.arange(P_tij.shape[0])\n            return -(P_tij*np.log(self.transmat_ + np.transpose(self.A1[:,:,None]*u_loc(t),[2,0,1]))).sum()\n        def jac(x):\n            a = x[0]\n            b = x[1]\n            sigma_loc = lambda t: 1-(1+np.exp(-(t/120/60/24-b)/a))**-1\n            u_loc = lambda t: 1-sigma_loc(t)\n            du_loc = lambda t: -sigma_loc(t)*(1-sigma_loc(t))\n            mu_loc =lambda t: np.transpose(self.A1[:,:,None]*u_loc(t),[2,0,1])/self.transmat_ + np.transpose(self.A1[:,:,None]*u_loc(t),[2,0,1])\n            t = np.arange(P_tij.shape[0])\n            mu = mu_loc(t) * P_tij\n            dxda = -((t/24/60/120-b)[:,None,None]/a**2)\n            dxdb = -1/a\n            db = mu*dxdb\n            da = mu*dxda\n            return -np.array([np.sum(da), np.sum(db)])\n        def hess(x):\n            a = x[0]\n            b = x[1]\n            sigma_loc = lambda t: 1-(1+np.exp(-(t/120/60/24-b)/a))**-1\n            u_loc = lambda t: 1-sigma_loc(t)\n            du_loc = lambda t: -sigma_loc(t)*(1-sigma_loc(t))\n            mu_loc =lambda t: np.transpose(self.A1[:,:,None]*u_loc(t),[2,0,1])/self.transmat_ + np.transpose(self.A1[:,:,None]*u_loc(t),[2,0,1])\n            t = np.arange(P_tij.shape[0])\n            mu = mu_loc(t) * P_tij\n            dxda = -((t/24/60/120-b)[:,None,None]/a**2)\n            dxdb = -1/a\n            db = -mu*dxdb\n            da = -mu*dxda\n            dL2_dada = (da*(-mu_loc(t)*dxda+(2*u_loc(t)-1)[:,None,None]*dxda-2/a)).sum()\n            dL2_dbdb = (db*(-mu_loc(t)*dxdb+(2*u_loc(t)-1)[:,None,None]*dxdb)).sum()\n            dL2_dadb = (db*(-mu_loc(t)*dxda+(2*u_loc(t)-1)[:,None,None]*dxda+dxdb)).sum()\n            dL2_dbda = dL2_dadb#(db*(-self._mu(t)*dxda+(2*self.U(t)-1)[:,None,None]*dxda+dxdb)\n            return np.array([[dL2_dada, dL2_dadb],[dL2_dbda, dL2_dbdb]])\n\n        #result = scipy.optimize.minimize(nL,[self.a,self.b],method='Newton-CG', jac=jac, hess=hess, tol=self.grad_conv,)\n        result = scipy.optimize.minimize(nL,[self.a,self.b])\n        self.a = result.x[0]\n        self.b = result.x[1]\n        self.track_params.append([self.a,self.b,result.fun])\n        self._grad_ascent_linesearch(P_tij)\n\n\n\n    def _jacobian_grad(self,P_tij):\n        t = np.arange(P_tij.shape[0])\n        mu = self._mu(t) * P_tij\n        dxda = -((t/24/60/120-self.b)[:,None,None]/self.a**2)\n        dxdb = -1/self.a\n        db = mu*dxdb\n        da = mu*dxda\n\n        G = np.array([np.sum(da), np.sum(db)])\n\n        dL2_dada = (da*(-self._mu(t)*dxda+(2*self.U(t)-1)[:,None,None]*dxda-2/self.a)).sum()\n        dL2_dbdb = (db*(-self._mu(t)*dxdb+(2*self.U(t)-1)[:,None,None]*dxdb)).sum()\n        dL2_dadb = (db*(-self._mu(t)*dxda+(2*self.U(t)-1)[:,None,None]*dxda+dxdb)).sum()\n        dL2_dbda = dL2_dadb#(db*(-self._mu(t)*dxda+(2*self.U(t)-1)[:,None,None]*dxda+dxdb)\n        J = np.array([[dL2_dada, dL2_dadb],[dL2_dbda, dL2_dbdb]])\n        return J, G\n\n    # # OLD VERSION: x = a*(t-b)\n    # def sigma(self, t):\n    #     return (1+np.exp(-self.a*(t-self.b)))**-1\n    #\n    # def _grad_ascent(self, P_tij):\n    #     print('transition posteriors:', P_tij.shape)\n    #     print('max: ', np.max(P_tij))\n    #     print('sumcheck: ', np.sum(P_tij[1,:,:]), np.sum(P_tij[-1,:,:]) )\n    #     t = np.arange(P_tij.shape[0]) + self.t0\n    #     for iter in range(self.grad_iter):\n    #         mu = self._mu(t) * P_tij\n    #         db = -mu.sum()#*self.a*-1\n    #         da = ((t[:,None,None]-self.b)*mu).sum()\n    #\n    #         print('mu: ', self._mu(t)[10].sum())\n    #         print('gradients: ', da, db)\n    #         if (self.grad_lr * np.abs(da) <= self.grad_conv * np.abs(self.a)) and (self.grad_lr * np.abs(db) <= self.grad_conv * np.abs(self.b)):\n    #             print('converged: ', iter)\n    #             return;\n    #         #self.a = self.a + self.grad_lr * da\n    #         self.b = self.b + self.grad_lr * db\n    #     print(self.grad_iter)\n\n\n    def _transition_posterior(self, posteriors):\n        print('posterior shape: ',posteriors.shape)\n        print('max: ', np.max(posteriors))\n        print('sumcheck: ', np.sum(posteriors[1,:]), np.sum(posteriors[-1,:]) )\n        P_tij = np.zeros((posteriors.shape[0],self.n_components,self.n_components))\n        for t in range(1, P_tij.shape[0]):\n            for i in range(self.n_components):\n                for j in range(self.n_components):\n                    P_tij[t,i,j] = posteriors[t-1,i]*posteriors[t,j]\n        return P_tij\n\n    def _mu(self,t):\n        num = np.transpose(self.A1[:,:,None]*self.dU(t),[2,0,1])\n        denom = self.transmat_ + np.transpose(self.A1[:,:,None]*self.U(t),[2,0,1])\n        # print('mu num: ', num[10,:,:].sum())\n        # print('mu denom: ', denom[10].sum())\n        return num/denom\n\n    def _set_transmat(self, transmat_):\n        self.transmat_ = (transmat_)\n\n    def _set_startprob(self,startprob):\n        self.startprob_ = startprob\n", "meta": {"hexsha": "8103700e50db572a2de6d0355fd93f81644e33fd", "size": 40313, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/sb_hmmlearn/base.py", "max_stars_repo_name": "samuelbray32/variable_hmm", "max_stars_repo_head_hexsha": "5d985bd9a353749f6a7302c8101749f1f3235ac8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/sb_hmmlearn/base.py", "max_issues_repo_name": "samuelbray32/variable_hmm", "max_issues_repo_head_hexsha": "5d985bd9a353749f6a7302c8101749f1f3235ac8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/sb_hmmlearn/base.py", "max_forks_repo_name": "samuelbray32/variable_hmm", "max_forks_repo_head_hexsha": "5d985bd9a353749f6a7302c8101749f1f3235ac8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7998075072, "max_line_length": 147, "alphanum_fraction": 0.569890606, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 9713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.17382634883106735}}
{"text": "import numpy as np\n\nfrom ._cython import build_sumtree_from_array\nfrom ._cython import get_prefix_sum_idx\nfrom ._cython import strided_sum\nfrom ._cython import update_sumtree\n\n\ndef _temporarily_enable_update(func):\n    def wrapper(self, *args, **kwargs):\n        self._enable_writes(True)\n        try:\n            output = func(self, *args, **kwargs)\n        finally:\n            self._enable_writes(False)\n        return output\n\n    return wrapper\n\n\nclass SumTreeArray(np.ndarray):\n    \"\"\"\n    A subclass of an ``numpy.ndarray`` that maintains an internal sumtree\n    for fast Categorical distribution sampling and fast sum operations,\n    at the expense of slower write operations. Because ``SumTreeArray``\n    is a subclass of ``numpy.ndarray``, it can be used just like a\n    ``numpy.ndarray``. It also comes with three new methods: ``sample``,\n    ``get_prefix_sum_id``, and ``sumtree``.\n\n    All elements of ``SumTreeArray`` must be non-negative (explanation below).\n\n    Parameters\n    ----------\n    shape_or_array : int, tuple of ints, array-like\n        When an int or tuple of ints is provided, a ``SumTreeArray`` is created\n        from an array of zeros of the given shape. When array-like, a\n        ``SumTreeArray`` is created from the given array.\n    dtype : data-type, optional\n        When provided creates a ``SumTreeArray`` of the specified dtype. If not\n        provided, and ``shape_or_array`` is a shape, then an array of zeros with\n        dtype ``float`` is created.  Defaults to ``None``. All integer and floating\n        point dtypes are supported. Because of the non-negativity requirement,\n        complex dtypes are not supported.\n\n    Notes\n    -----\n    Because the elements of a ``SumTreeArray`` represent an unnormalized\n    Categorical probability distribution, we require that all elements of a\n    ``SumTreeArray`` be non-negative.\n\n    For the sake of the integrity of the sumtree, the memory of the array is\n    carefully guarded. Elements of ``SumTreeArray`` should only be updated through\n    the ``SumTreeArray`` API.  This ensures that the underlying sumtree correctly\n    models the underlying array. For example, when creating a ``SumTreeArray``\n    from ``another_array``, the new ``SumTreeArray`` uses a copy of ``another_array``.\n    Thus, changes to ``another_array`` do not affect the ``SumTreeArray``. As another\n    example, using ``SumTreeArray.view(np.ndarray)`` will return an object\n    with read-only access to the underlying array ``SumTreeArray``.\n\n    Similarly, when retrieving elements of a ``SumTreeArray`` through indexing,\n    the returned object is always an ``np.ndarray`` that is a copy or read-only\n    view of the underlying array in ``SumTreeArray``, and thus the integrity of the\n    sumtree is protected. Another reason for doing this is that we always assume\n    that we do not want to re-compute a new sumtree on top of the returned object,\n    which could be unnecessarily expensive.\n\n    References\n    ----------\n    [1] NumPy https://numpy.org\n\n    Examples\n    --------\n    >>> SumTreeArray(4,dtype='int32')\n    SumTreeArray([0, 0, 0, 0], dtype=int32)\n    >>> SumTreeArray((2,2),dtype='int32')\n    SumTreeArray([[0, 0],\n                  [0, 0]], dtype=int32)\n    >>> sum_tree = SumTreeArray(np.array([1,2,3,4],dtype='float32'))\n    >>> sum_tree\n    SumTreeArray([1., 2., 3., 4.], dtype=float32)\n    >>> # set and get just like an ndarray\n    >>> sum_tree[:2] = [2,1]\n    >>> sum_tree\n    SumTreeArray([2., 1., 3., 4.], dtype=float32)\n    \"\"\"\n\n    def __new__(self, shape_or_array, dtype=None):\n\n        if isinstance(shape_or_array, SumTreeArray):\n            if dtype is None:\n                return shape_or_array\n            else:\n                return SumTreeArray(shape_or_array.view(np.ndarray), dtype)\n\n        elif isinstance(shape_or_array, np.ndarray):\n            if shape_or_array.size <= 1:\n                raise ValueError(\n                    \"input to SumTreeArray must have shape with at least 2 elements\"\n                )\n            assert shape_or_array.size > 1\n            dtype = shape_or_array.dtype if dtype is None else dtype\n            array = shape_or_array.astype(dtype, copy=True)  # strictly copies\n            return array.view(SumTreeArray)\n\n        else:\n            dtype = float if dtype is None else dtype\n            array = np.zeros(shape_or_array, dtype=dtype)\n            if array.size <= 1:\n                raise ValueError(\n                    \"input to SumTreeArray must have shape with at least 2 elements\"\n                )\n            return array.view(SumTreeArray)\n\n    @_temporarily_enable_update\n    def __array_finalize__(self, array):\n\n        if not np.shares_memory(array, self):\n            # note that we would have ended up here without overriding copy(...)\n            raise NotImplementedError(\"input array and self must share memory\")\n\n        if isinstance(self.base, SumTreeArray) and self.base.dtype == self.dtype:\n            # inherit the same base and sum tree\n            if array.size != self.size:\n                # we should never end up here\n                raise NotImplementedError(\n                    \"input array and base SumTreeArray must have same number of elements\"\n                )\n            self._flat_base = self.base._flat_base\n            self._indices = self.base._indices.reshape(self.shape)\n            self._sumtree = self.base._sumtree\n        else:\n            # initialize\n            self._flat_base = array.view(np.ndarray).ravel()\n            self._indices = np.arange(array.size, dtype=np.intp).reshape(array.shape)\n            self._sumtree = np.zeros_like(self._flat_base)\n            # sumtree needs to be initialize\n            self._rebuild_sumtree()\n\n    # When a transformation is applied to a SumTreeArray object, it is assumed that\n    # we do not want a new SumTreeArray object (which could result in a large\n    # number of unwanted prefix sum tree updates)...and thus the transformation\n    # is applied to the underlying array object, and an NDArray is returned.\n    # The exception to this rule is in-place operators, such as +=\n    def __array_prepare__(self, out_arr, context=None):\n        return out_arr.view(np.ndarray)\n\n    def __array_wrap__(self, out_arr, context=None):\n        return out_arr.view(np.ndarray)\n\n    @_temporarily_enable_update\n    def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):\n        inputs = list(inputs)\n        for i, x in enumerate(inputs):\n            if isinstance(x, SumTreeArray):\n                inputs[i] = x.view(np.ndarray)\n        inputs = tuple(inputs)\n        if \"out\" in kwargs and kwargs[\"out\"] is not None:\n            out = kwargs[\"out\"]\n            if len(out) == 1 and out[0] is self:\n                # this is an in-place update on self\n                # proceed with update and then rebuild sumtree\n                kwargs[\"out\"] = (self.view(np.ndarray),)\n                _ = super(SumTreeArray, self).__array_ufunc__(\n                    ufunc, method, *inputs, **kwargs\n                )\n                self._rebuild_sumtree()\n                return self\n            else:\n                raise NotImplementedError\n        else:\n            return super(SumTreeArray, self).__array_ufunc__(\n                ufunc, method, *inputs, **kwargs\n            )\n\n    def _enable_writes(self, val):\n        self.setflags(write=val)\n\n    def __setitem__(self, idx, val):\n        self.put(idx, val)\n\n    def __getitem__(self, idx):\n        return self.view(np.ndarray)[idx]\n\n    def _rebuild_sumtree(self):\n        build_sumtree_from_array(self._flat_base, self._sumtree)\n\n    def astype(self, *args, **kwargs):\n        return self.view(np.ndarray).astype(*args, **kwargs)\n\n    def choose(self, *args, **kwargs):\n        return self.view(np.ndarray).choose(*args, **kwargs)\n\n    def copy(self, *args, **kwargs):\n        return SumTreeArray(self.view(np.ndarray))\n\n    def diagonal(self, *args, **kwargs):\n        return self.view(np.ndarray).diagonal(*args, **kwargs)\n\n    def dot(self, *args, **kwargs):\n        return self.view(np.ndarray).dot(*args, **kwargs)\n\n    @_temporarily_enable_update\n    def fill(self, *args, **kwargs):\n        super(SumTreeArray, self).fill(*args, **kwargs)\n        self._rebuild_sumtree()\n\n    def flatten(self, *args, **kwargs):\n        return self.view(np.ndarray).flatten(*args, **kwargs)\n\n    @property\n    def imag(self):\n        return self.view(np.ndarray).imag\n\n    def mean(self, *args, **kwargs):\n        output = self.sum(*args, **kwargs)\n        m = np.array(output).size\n        n = self.size\n        assert n % m == 0\n        return output / float(n / m)\n\n    def newbyteorder(self, *args, **kwargs):\n        return self.view(np.ndarray).newbyteorder(*args, **kwargs)\n\n    @_temporarily_enable_update\n    def partition(self, *args, **kwargs):\n        super(SumTreeArray, self).partition(*args, **kwargs)\n        self._rebuild_sumtree()\n\n    def put(self, indices, values):\n        # TODO: there's probably a better way of building an index iterator\n        indices = np.ascontiguousarray(self._indices[indices]).ravel()\n        values = np.ascontiguousarray(values, dtype=self._flat_base.dtype).ravel()\n        update_sumtree(indices, values, self._flat_base, self._sumtree)\n\n    @property\n    def real(self):\n        return self.view(np.ndarray).real\n\n    def repeat(self, *args, **kwargs):\n        return self.view(np.ndarray).repeat(*args, **kwargs)\n\n    def round(self, *args, **kwargs):\n        return self.view(np.ndarray).round(*args, **kwargs)\n\n    @_temporarily_enable_update\n    def sort(self, *args, **kwargs):\n        super(SumTreeArray, self).sort(*args, **kwargs)\n        self._rebuild_sumtree()\n\n    def squeeze(self):\n        return self.reshape(self.view(np.ndarray).squeeze().shape)\n\n    def sumtree(self):\n        \"\"\"\n        Returns a copy of the sumtree.\n\n        Returns\n        -------\n        sumtree : ndarray\n            A copy of the (flat) sumtree object maintained by ``SumTreeArray``.\n\n        Examples\n        --------\n        >>> sum_tree = SumTreeArray(np.array([1,2,3,4],dtype='float32'))\n        >>> sum_tree\n        SumTreeArray([1., 2., 3., 4.], dtype=float32)\n        >>> sum_tree.sumtree()\n        array([ 0., 10.,  3.,  7.], dtype=float32)\n        >>> sum_tree_from_2d_array = SumTreeArray(np.array([[1,2],[3,4]],dtype='int32'))\n        >>> sum_tree_from_2d_array\n        SumTreeArray([[1., 2.],\n                      [3., 4.]], dtype=float32)\n        >>> sum_tree_from_2d_array.sumtree()\n        array([ 0., 10.,  3.,  7.], dtype=float32)\n        \"\"\"\n        return np.copy(self._sumtree)\n\n    def swapaxes(self, *args, **kwargs):\n        return self.view(np.ndarray).swapaxes(*args, **kwargs)\n\n    @property\n    def T(self):\n        return self.view(np.ndarray).T\n\n    def take(self, *args, **kwargs):\n        return self.view(np.ndarray).take(*args, **kwargs)\n\n    def trace(self, *args, **kwargs):\n        return self.view(np.ndarray).trace(*args, **kwargs)\n\n    def transpose(self, *args, **kwargs):\n        return self.view(np.ndarray).transpose(*args, **kwargs)\n\n    def get_prefix_sum_id(self, prefix_sum, flatten_indices=False):\n        \"\"\"\n        Returns an array of indices of the same shape is the input array\n        ``prefix_sum`` where each element ``i`` in the output is ``j``\n        such that ``self.ravel()[:j+1] < prefix_sum[i]``.  In other words,\n        the output array returns the index of the largest prefix sum of\n        self that is less than the provided input.\n\n        Parameters\n        ----------\n        prefix_sum : array-like\n            An n-dimensional array of prefix sums.  Does not need to be\n            of the same shape as ``self``.\n        flatten_indices : bool, optional\n            Defaults to ``False``.  When ``True``, returns the indices\n            as if ``self`` is a 1d array (i.e. ``self.ravel()``)\n\n        Returns\n        -------\n        prefix_sum_indices : ndarray, tuple(ndarray)\n            A new array holding the result is returned containing the\n            indices of the supplied prefix sums. The returned array\n            has the same shape as the input array. When supplied with\n            ``flatten_indices=False`` and ``self`` is an n-d array\n            where ``n>1``, then a tuple of ``n`` arrays is returned\n            where each element of the tuple corresponds to each dimension\n            of the ``SumTreeArray``.\n\n        Notes\n        -----\n        Arithmetic is modular when using integer types, and no error is\n        raised on overflow.\n\n        Examples\n        --------\n        >>> sum_tree = SumTreeArray(np.array([1,2,3,4],dtype='float32'))\n        >>> sum_tree\n        SumTreeArray([1., 2., 3., 4.], dtype=float32)\n        >>> sum_tree.get_prefix_sum_id(np.arange(10))\n        array([0, 1, 1, 2, 2, 2, 3, 3, 3, 3], dtype=int32)\n        >>> sum_tree.get_prefix_sum_id(np.arange(10).reshape(2,5))\n        array([[0, 1, 1, 2, 2],\n               [2, 3, 3, 3, 3]], dtype=int32)\n        >>> sum_tree_from_2d_array = SumTreeArray(np.array([[1,2],[3,4]],dtype='int32'))\n        >>> sum_tree_from_2d_array\n        SumTreeArray([[1., 2.],\n                       [3., 4.]], dtype=float32)\n        >>> # output is \"flattened\" and thus will be the same as ``sum_tree.get_prefix_sum_id`` above\n        >>> sum_tree_from_2d_array.get_prefix_sum_id(np.arange(10))\n        array([0, 1, 1, 2, 2, 2, 3, 3, 3, 3], dtype=int32)\n        >>> sum_tree_from_2d_array.get_prefix_sum_id(np.arange(10).reshape(2,5))\n        array([[0, 1, 1, 2, 2],\n               [2, 3, 3, 3, 3]], dtype=int32)\n        \"\"\"\n        # ensure prefix sum is the correct type and is contiguous\n        prefix_sum = np.ascontiguousarray(prefix_sum, dtype=self.dtype)\n        prefix_sum_flat = prefix_sum.ravel()\n        # init return array\n        flat_idx = np.zeros(prefix_sum.size, dtype=np.intp)\n        # get ids\n        get_prefix_sum_idx(flat_idx, prefix_sum_flat, self._flat_base, self._sumtree)\n        # output shape should be same as prefix_sum shape\n        if prefix_sum.ndim > 1:\n            output = flat_idx.reshape(prefix_sum.shape)\n        else:\n            output = flat_idx\n        if self.ndim <= 1 or flatten_indices:\n            return output\n        else:\n            return np.unravel_index(output, self.shape)\n\n    def sample(self, nsamples=1, flatten_indices=False):\n        \"\"\"\n        Return a sample of indices, where the probability an index being\n        sampled is equal to the value at that index divided by the\n        sum of the array, i.e. ``probs = self/self.sum()``.\n\n        Parameters\n        ----------\n        nsamples : int\n            Number of samples to return\n        flatten_indices : bool, optional\n            Defaults to ``False``.  When ``True``, returns the indices\n            as if ``self`` is a 1d array (i.e. ``self.ravel()``)\n\n        Returns\n        -------\n        sample_of_indices : ndarray, tuple(ndarray)\n            A new array holding the result is returned containing the\n            sampled indices.  If the underlying ``SumTreeArray`` array\n            is n-dimensional, where n>1, and ``flatten_indices=False``,\n            then a tuple of ``n`` arrays is returned where each element of\n            the tuple corresponds to each dimension of the ``SumTreeArray``\n            array.\n\n        Notes\n        -----\n        Arithmetic is modular when using integer types, and no error is\n        raised on overflow.\n\n        Examples\n        --------\n        >>> sum_tree = SumTreeArray(np.array([1,2,3,4],dtype='float32'))\n        >>> sum_tree\n        SumTreeArray([1., 2., 3., 4.], dtype=float32)\n        >>> sum_tree.sample(10)\n        array([2, 3, 3, 3, 3, 1, 2, 2, 2, 0], dtype=int32)\n        >>> # probability of being sampled\n        >>> sum_tree / sum_tree.sum()\n        array([0.1, 0.2, 0.3, 0.4], dtype=float32)\n        >>> # sampled proportions\n        >>> (sum_tree.sample(1000)[None] == np.arange(4)[:,None]).mean(axis=1)\n        array([0.10057, 0.19919, 0.29983, 0.40041])\n        >>> # sampling from a 2-d array\n        >>> sum_tree_from_2d_array = SumTreeArray(np.array([[1,2,3],[4,5,6]],dtype='int32'))\n        >>> sum_tree_from_2d_array\n        SumTreeArray([[1, 2, 3],\n                      [4, 5, 6]], dtype=int32)\n        >>> sum_tree_from_2d_array.sample(4)\n        (array([1, 1, 1, 0]), array([1, 1, 2, 2]))\n        >>> sum_tree_from_2d_array.sample(4,flatten_indices=True)\n        array([4, 4, 5, 2], dtype=int32)\n        \"\"\"\n        if self.sum() == 0:\n            raise ValueError(\"array must have at least 1 positive value\")\n        # sample priority values in the cumulative sum\n        vals = (self.sum() * np.random.rand(nsamples)).astype(self.dtype)\n        return self.get_prefix_sum_id(vals, flatten_indices)\n\n    def _parse_axis_arg(self, axis):\n        if axis is None:\n            return None\n        else:\n            axes = np.array(axis).reshape(-1)\n            if len(set(axes)) < len(axes):\n                raise IndexError(\n                    \"invalid axis argument: %s contains duplicates\" % str(axis)\n                )\n            return np.arange(self.ndim)[axes]\n\n    def sum(self, axis=None, keepdims=False):\n        \"\"\"\n        Functions the same as ``numpy.sum(...)`` except that some ``sum``\n        operations can be significantly faster for large arrays\n        when the sum operation is performed over C-contiguous\n        ranges of indices.  For example, for a 2d array, supplying\n        ``axis=1`` to the ``sum`` function would be a sum operation over\n        C-contiguous ranges of indices, and thus benefit from sum-tree\n        speedups.  However, ``axis=0`` is not C-contiguous sum operation,\n        and would thus revert to the standard ``numpy.sum`` method.\n\n        Parameters\n        ----------\n        axis : None or int or tuple of ints, optional\n            Axis or axes along which a sum is performed. The default,\n            ``axis=None``, will sum all of the elements of the input array.\n            If axis is negative it counts from the last to the first axis.\n            If axis is a tuple of ints, a sum is performed on all of the\n            axes specified in the tuple instead of a single axis or all the\n            axes as before.\n        keepdims : bool, optional\n            If this is set to True, the axes which are reduced are left in\n            the result as dimensions with size one. With this option, the\n            result will broadcast correctly against the input array. Defaults\n            to ``False``.\n\n        Returns\n        -------\n        sum_along_axis : ndarray\n            An array with the same shape as self, with the specified axis\n            or axes removed, unless ``keepdims=True`` in which case the\n            specified axis or axes are not removed, but will have size ``1``.\n            If axis is None, a scalar is returned.\n\n        Notes\n        -----\n        Arithmetic is modular when using integer types, and no error is raised on overflow.\n        SumTreeArray does not use the improved precision techniques that NumPy uses when\n        summing along the fast axis (C-contiguous), instead relying on the standard floating\n        point precision arithmetic provided by Python.\n\n        References\n        ----------\n        [1] NumPy.  For more information on ``numpy.sum``, please see\n        https://numpy.org/doc/stable/reference/generated/numpy.sum.html\n\n        Examples\n        --------\n        >>> x = SumTreeArray(np.ones((1000,1000)))\n        >>> # lightning fast\n        >>> x.sum()\n        1000000.0\n        >>> # very fast\n        >>> x.sum(axis=1)\n        array([1000., ..., 1000.], dtype='float64')\n        >>> # slightly slower than NumPy\n        >>> x.sum(axis=0)\n        array([1000., ..., 1000.], dtype='float64')\n        >>> # maintain dims with keepdims=True\n        >>> x.sum(axis=1,keepdims=True).shape\n        (1000, 1)\n        >>> x.sum(axis=1).shape\n        (1000,)\n        \"\"\"\n        axes = self._parse_axis_arg(axis)\n        if axes is None:\n            if keepdims:\n                return self._sumtree[1:2].reshape([1] * self.ndim)\n            else:\n                return self._sumtree[1]\n        else:\n            if axes.min() == self.ndim - len(axes):\n                # strides are contiguous along leaves of sumtree\n                stride = int(np.prod(np.array(self.shape)[axes]))\n                output = strided_sum(self._flat_base, self._sumtree, stride)\n                if keepdims:\n                    return output.reshape(list(output.shape) + [1] * len(axes))\n                else:\n                    return output\n            else:\n                return super(SumTreeArray, self).sum(axis=axis, keepdims=keepdims)\n", "meta": {"hexsha": "b0cb919217985859ad2838df61ea115b29e7a952", "size": 20730, "ext": "py", "lang": "Python", "max_stars_repo_path": "starr/sumtree_array.py", "max_stars_repo_name": "justinmaojones/starr", "max_stars_repo_head_hexsha": "59b13a79a1a8c440b04af61e765bb2001e7828a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "starr/sumtree_array.py", "max_issues_repo_name": "justinmaojones/starr", "max_issues_repo_head_hexsha": "59b13a79a1a8c440b04af61e765bb2001e7828a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "starr/sumtree_array.py", "max_forks_repo_name": "justinmaojones/starr", "max_forks_repo_head_hexsha": "59b13a79a1a8c440b04af61e765bb2001e7828a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2524271845, "max_line_length": 101, "alphanum_fraction": 0.5972021225, "include": true, "reason": "import numpy", "num_tokens": 5013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.17382634883106732}}
{"text": "'''\n    @Author: fxm\n    @Date: Dec 27, 2020.\n    @Title: Learn class.\n'''\n\nimport logging\nimport os\nimport numpy as np\nfrom collections import deque\nfrom random import shuffle\n\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom Framework.Mcts import MCTS\nfrom Framework.Net import dotdict\nfrom SelfPlay import SelfPlay\n\nlog = logging.getLogger(__name__)\n\nargs = dotdict({\n    'numIters': 100,  # 神经网络训练迭代次数\n    'numEps': 100,  # 自学习过程每次比赛场数\n    'tempThreshold': 15,  # 搜索树的阈值\n    'updateThreshold': 0.5,  # 如果新模型赢了超过updateThreshold比例的比赛，就接受新模型\n    'maxlenOfQueue': 200000,  # 训练数据上限\n    'numMCTSSims': 25,  # 搜索树采样数量\n    'arenaCompare': 2,  # 新旧模型对比需要的比赛次数\n    'cpuct': 1,  # 搜索树参数\n    'checkpoint': './Model/',  # 模型保存路径\n    'load_model': False,  # 是否加载模型\n    'numItersFortable': 20,\n})\n\n\nclass Learn():\n    '''\n        初始化\n        参数设置:\n        game：游戏对象\n        net：网络对象\n        pnet：竞争对手的网络对象\n        mcts：蒙特卡洛树对象\n        args：其他参数\n        table：保存的训练数据，每次训练都使用这里面的数据\n    '''\n\n    def __init__(self, game, net, args):\n        self.game = game\n        self.net = net\n        self.pnet = self.net.__class__(self.game)\n        self.args = args\n        self.mcts = MCTS(self.game, self.net, self.args)\n        self.table = []\n        self.firstrain = True\n\n    '''\n        process过程算法\n        将蒙特卡洛树搜索得到的\n        棋盘(即状态)、得到的action概率向量、值\n        传入神经网络进行学习\n    '''\n\n    def process(self):\n        # 结果保存表\n        table = []\n        board = self.game.initBoard()\n        # 由于是学习过程，谁先手无所谓\n        self.curcolor = 1\n        step = 0\n\n        # 只要比赛不结束就一直进行\n        while True:\n            step += 1\n            # 当前玩家所使用棋盘对象\n            canonicalBoard = self.game.getCanonicalForm(board, self.curcolor)\n            # 如果step大于阈值，则不再计算准确的概率向量，而是将概率最大的设为1，其他为0\n            temp = int(step < self.args.tempThreshold)\n\n            # 获得当前的概率向量\n            prob = self.mcts.getActionProb(canonicalBoard, temp=temp)\n            sym = self.game.getSymmetries(canonicalBoard, prob)\n            for b, p in sym:\n                table.append([b, self.curcolor, p, None])\n\n            # 执行动作后获得下一状态，并交换掌棋权，然后继续执行上述过程\n            action = np.random.choice(len(prob), p=prob)\n            board, self.curcolor = self.game.getNextState(board, self.curcolor, action)\n            ended = self.game.getGameEnded(board, self.curcolor)\n\n            # 如果结束就返回结果，是一个三元组\n            # 最终的结果包括了搜索轨迹中所有的状态对应的\n            # 状态本身，动作action概率向量，以及最有希望得到的值\n            if ended != -2:\n                return [(x[0], x[2], ended * ((-1) ** (x[1] != self.curcolor))) for x in table]\n\n    '''\n        学习过程\n        AC模块采用神经网络学习\n        process模块采用蒙特卡洛树搜索过程\n    '''\n\n    def learn(self):\n        for i in range(1, self.args.numIters + 1):\n            log.info(f'Starting Iter #{i} ...')\n            deq = deque([], maxlen=self.args.maxlenOfQueue)\n\n            # 在自学习过程中，执行process算法过程\n            for _ in tqdm(range(self.args.numEps), desc=\"Self Play\"):\n                self.mcts = MCTS(self.game, self.net, self.args)\n                deq += self.process()\n\n            # 将训练结果保存到table中\n            self.table.append(deq)\n\n            if len(self.table) > self.args.numItersFortable:\n                log.warning(f\"Removing the oldest entry in data. len(table) = {len(self.table)}\")\n                self.table.pop(0)\n\n            # 训练前需要将数据打乱\n            data = []\n            for e in self.table:\n                data.extend(e)\n            shuffle(data)\n\n            # 训练新的网络前需要保存旧的网络\n            self.net.saveCheckpoint(folder=self.args.checkpoint, filename='temp.pth.tar')\n            self.pnet.loadCheckpoint(folder=self.args.checkpoint, filename='temp.pth.tar')\n            pmcts = MCTS(self.game, self.pnet, self.args)\n\n            self.net.train(data)\n            mcts = MCTS(self.game, self.net, self.args)\n\n            # 如果是第一次训练，那么不需要比较网络\n            if self.firstrain == True:\n                self.net.saveCheckpoint(folder=self.args.checkpoint, filename='temp.pth.tar')\n                self.net.saveCheckpoint(folder=self.args.checkpoint, filename='best.pth.tar')\n                self.firstrain = False\n                continue\n\n            log.info('与旧的网络对比中：')\n            arena = SelfPlay(lambda x: np.argmax(pmcts.getActionProb(x, temp=0)),\n                             lambda x: np.argmax(mcts.getActionProb(x, temp=0)), self.game)\n            pwins, wins, draws = arena.playGames(self.args.arenaCompare)\n\n            log.info('胜/负 : %d / %d ; 平局 : %d' % (wins, pwins, draws))\n            if pwins + wins == 0 or float(wins) / (pwins + wins) <= self.args.updateThreshold:\n                log.info('不接受新的模型')\n                self.net.loadCheckpoint(folder=self.args.checkpoint, filename='temp.pth.tar')\n            else:\n                log.info('接受新的模型')\n                self.net.saveCheckpoint(folder=self.args.checkpoint, filename='best.pth.tar')\n", "meta": {"hexsha": "f98ac0dde088e9ae667ddb4782b4deb7ec930506", "size": 4821, "ext": "py", "lang": "Python", "max_stars_repo_path": "AlphaGoZero/code/Learn.py", "max_stars_repo_name": "OoSnowfxm/AlphaZero_Othello", "max_stars_repo_head_hexsha": "3e94ac29dbac413502eb85628a0f8eb6d402d5e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AlphaGoZero/code/Learn.py", "max_issues_repo_name": "OoSnowfxm/AlphaZero_Othello", "max_issues_repo_head_hexsha": "3e94ac29dbac413502eb85628a0f8eb6d402d5e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AlphaGoZero/code/Learn.py", "max_forks_repo_name": "OoSnowfxm/AlphaZero_Othello", "max_forks_repo_head_hexsha": "3e94ac29dbac413502eb85628a0f8eb6d402d5e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3051948052, "max_line_length": 97, "alphanum_fraction": 0.5637834474, "include": true, "reason": "import numpy", "num_tokens": 1584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.17382634883106732}}
{"text": "\"\"\"Methods for decorrelating simulation results.\"\"\"\n\nimport copy\nimport math\n\nimport numpy as np\nfrom pymbar import timeseries\n\nfrom origamipy import datatypes\nfrom origamipy import utility\n\n\nNUM_STAPLES_TAG = 'numstaples'\n\n\nclass DecorrelatedOutputs:\n    _datatypes = ['enes', 'ops', 'staples', 'staplestates']\n    _trjtypes = ['trj', 'vcf', 'ores', 'states']\n#    _trjtypes = ['trj', 'vcf', 'states']\n\n    def __init__(self, sim_collections, all_conditions):\n        self.all_conditions = all_conditions\n        self._sim_collections = sim_collections\n        self._decor_masks = []\n        self._num_decorrelated_steps = 0\n        self._datatype_to_decors = {}\n        self._trjtype_to_decors = {}\n\n    def get_concatenated_datatype(self, tag):\n        concat = []\n        for data in self._datatype_to_decors[tag]:\n            concat.append(datatypes.OutputData.concatenate(data))\n\n        return datatypes.OutputData.concatenate(concat)\n\n    def get_num_steps_per_condition(self):\n        steps = []\n        for rep_to_data in self._datatype_to_decors['enes']:\n            steps.append(sum([s.steps for s in rep_to_data]))\n\n        return steps\n\n    def get_concatenated_series(self, tag):\n        for reps_data in self._datatype_to_decors.values():\n            if tag in reps_data[0][0].tags:\n                concat = []\n                for data in reps_data:\n                    reps = []\n                    for series in data:\n                        reps.append(series[tag])\n\n                    concat.append(np.concatenate(reps))\n\n                return np.concatenate(concat)\n\n        else:\n            raise Exception\n\n    @property\n    def all_series_tags(self):\n        tags = []\n        for decors in self._datatype_to_decors.values():\n            datatype = decors[0][0]\n            for tag in datatype.tags:\n                if tag == 'step':\n                    continue\n\n                tags.append(tag)\n\n        return tags\n\n    def perform_decorrelation(self, skip):\n        print('Performing decorrelations')\n        print('State,   configs, t0, g,   Neff')\n        for sim_collection in self._sim_collections:\n            self._decor_masks.append([])\n            for rep in sim_collection._reps:\n                mask = self._construct_decorrelation_mask(sim_collection, rep,\n                        skip)\n                self._decor_masks[-1].append(mask)\n\n    def _construct_decorrelation_mask(self, sim_collection, rep, skip):\n        enes = sim_collection.reps_energies[rep]\n        ops = sim_collection.reps_order_params[rep]\n        num_staples = sim_collection.reps_staples[rep]\n        steps = enes.steps\n        rpots = utility.calc_reduced_potentials(enes, ops, num_staples,\n                                                sim_collection.conditions)\n        start_i, g, Neff = timeseries.detectEquilibration(rpots, nskip=skip)\n        template = '{:<8} {:<8} {:<3} {:<4.1f} {:<.1f}'\n        print(template.format(sim_collection.conditions.fileformat, steps,\n                start_i, g, Neff))\n        indices = (timeseries.subsampleCorrelatedData(rpots[start_i:], g=skip*g))\n        return [i + start_i for i in indices]\n\n    def read_decors_from_files(self, data_only=False):\n        for datatype in self._datatypes:\n            self._datatype_to_decors[datatype] = []\n            for sim_collection in self._sim_collections:\n                reps_series = sim_collection.get_decor_reps_data(datatype)\n                self._datatype_to_decors[datatype].append(reps_series)\n\n        if not data_only:\n            for trjtype in self._trjtypes:\n                self._trjtype_to_decors[trjtype] = []\n                for sim_collection in self._sim_collections:\n                    reps_series = sim_collection.get_decor_reps_trj(trjtype)\n                    self._trjtype_to_decors[trjtype].append(reps_series)\n\n    def apply_masks(self):\n        # The mask numbering is different than the rep number\n        for datatype in self._datatypes:\n            self._datatype_to_decors[datatype] = []\n            for i, sim_collection in enumerate(self._sim_collections):\n                self._datatype_to_decors[datatype].append([])\n                reps_to_data = sim_collection.get_reps_data(datatype)\n                for j, rep in enumerate(sim_collection._reps):\n                    data = reps_to_data[rep]\n                    data.apply_mask(self._decor_masks[i][j])\n                    self._datatype_to_decors[datatype][i].append(data)\n\n        for trjtype in self._trjtypes:\n            self._trjtype_to_decors[trjtype] = []\n            for i, sim_collection in enumerate(self._sim_collections):\n                self._trjtype_to_decors[trjtype].append([])\n                reps_to_trjs = sim_collection.get_reps_trj(trjtype)\n                for j, rep in enumerate(sim_collection._reps):\n                    trjs = reps_to_trjs[rep]\n                    filebase = sim_collection.decor_filebase_template.format(\n                            sim_collection.filebase, rep,\n                            sim_collection.conditions.fileformat)\n                    filename = '{}.{}'.format(filebase, trjtype)\n                    decor_trj = self._apply_mask_to_trjs(self._decor_masks[i][j],\n                            trjs, filename)\n                    self._trjtype_to_decors[trjtype][i].append(decor_trj)\n\n    def _apply_mask_to_trjs(self, mask, trjs, filename):\n        out_file = open(filename, 'w')\n        step_i = 0\n        mask_i = 0\n        for trj in trjs:\n            for step in trj:\n                step_included = step_i == mask[mask_i]\n                if step_included:\n                    out_file.write(step)\n                    mask_i += 1\n                    if mask_i == len(mask):\n                        return\n\n                step_i += 1\n            trj.close()\n\n        out_file.close()\n\n    def write_decors_to_files(self):\n        for datatype in self._datatypes:\n            for i, sim_collection in enumerate(self._sim_collections):\n                for j, rep in enumerate(sim_collection._reps):\n                    filebase = sim_collection.decor_filebase_template.format(\n                            sim_collection.filebase, rep,\n                            sim_collection.conditions.fileformat)\n                    if datatype == 'enes':\n                        self._datatype_to_decors[datatype][i][j].to_file(filebase,\n                                float(sim_collection.conditions.temp))\n                    else:\n                        self._datatype_to_decors[datatype][i][j].to_file(filebase)\n\n    def filter_collections(self, filter_tag, value):\n        filtered_count = 0\n        for i, sim_collection in enumerate(self._sim_collections):\n            for j, rep in enumerate(sim_collection._reps):\n\n                # Create mask\n                selected_op = self._datatype_to_decors['ops'][i][j][filter_tag]\n                mask = selected_op == value\n                filtered_count += mask.sum()\n\n                # Apply mask\n                for datatype in self._datatypes:\n                    data = self._datatype_to_decors[datatype][i][j]._data\n                    reduced_data = []\n                    for series in data:\n                        reduced_data.append(series[mask])\n\n                    reduced_data = np.array(reduced_data)\n                    self._datatype_to_decors[datatype][i][j]._data = reduced_data\n\n        return filtered_count\n\n\nclass SimpleDecorrelatedOutputs:\n    _datatypes = ['enes', 'ops', 'staples', 'staplestates']\n    _trjtypes = ['trj', 'vcf', 'ores', 'states']\n\n    def __init__(self, sim_collections, all_conditions):\n        self.all_conditions = all_conditions\n        self._sim_collections = sim_collections\n        self._decor_masks = []\n        self._num_decorrelated_steps = 0\n        self._datatype_to_decors = {}\n        self._trjtype_to_decors = {}\n\n    def get_concatenated_datatype(self, tag):\n        return datatypes.OutputData.concatenate(self._datatype_to_decors[tag])\n\n    def get_num_steps_per_condition(self):\n        steps = []\n        for data in self._datatype_to_decors['enes']:\n            steps.append(data.steps)\n\n        return steps\n\n    def get_concatenated_series(self, tag):\n        for data in self._datatype_to_decors.values():\n            if tag in data[0].tags:\n                concat = []\n                for series in data:\n                    concat.append(series[tag])\n\n                return np.concatenate(concat)\n\n        else:\n            raise Exception\n\n    @property\n    def all_series_tags(self):\n        tags = []\n        for decors in self._datatype_to_decors.values():\n            datatype = decors[0]\n            for tag in datatype.tags:\n                if tag == 'step':\n                    continue\n\n                tags.append(tag)\n\n        return tags\n\n    def perform_decorrelation(self, skip):\n        print('Performing decorrelations')\n        print('State,   configs, t0, g,   Neff')\n        for sim_collection in self._sim_collections:\n            mask = self._construct_decorrelation_mask(sim_collection, skip)\n            self._decor_masks.append(mask)\n\n    def _construct_decorrelation_mask(self, sim_collection, skip):\n        enes = sim_collection.get_data('enes')\n        ops = sim_collection.get_data('ops')\n        num_staples = sim_collection.get_data('staples')\n        steps = enes.steps\n        rpots = utility.calc_reduced_potentials(enes, ops, num_staples,\n                                                sim_collection.conditions)\n        start_i, g, Neff = timeseries.detectEquilibration(rpots, nskip=skip)\n        template = '{:<8} {:<8} {:<3} {:<4.1f} {:<.1f}'\n        print(template.format(sim_collection.conditions.fileformat, steps,\n                start_i, g, Neff))\n        indices = (timeseries.subsampleCorrelatedData(rpots[start_i:], g=skip*g))\n        return [i + start_i for i in indices]\n\n    def read_decors_from_files(self, data_only=False):\n        for datatype in self._datatypes:\n            self._datatype_to_decors[datatype] = []\n            for sim_collection in self._sim_collections:\n                series = sim_collection.get_data(datatype)\n                self._datatype_to_decors[datatype].append(series)\n\n        if not data_only:\n            for trjtype in self._trjtypes:\n                self._trjtype_to_decors[trjtype] = []\n                for sim_collection in self._sim_collections:\n                    series = sim_collection.get_trj(trjtype)\n                    self._trjtype_to_decors[trjtype].append(series)\n\n    def apply_masks(self):\n        # The mask numbering is different than the rep number\n        for datatype in self._datatypes:\n            self._datatype_to_decors[datatype] = []\n            for i, sim_collection in enumerate(self._sim_collections):\n                data = sim_collection.get_data(datatype)\n                data.apply_mask(self._decor_masks[i])\n                self._datatype_to_decors[datatype].append(data)\n\n        for trjtype in self._trjtypes:\n            self._trjtype_to_decors[trjtype] = []\n            for i, sim_collection in enumerate(self._sim_collections):\n                trj = sim_collection.get_trj(trjtype)\n                filebase = '{}_decor'.format(sim_collection.filebase)\n                filename = '{}.{}'.format(filebase, trjtype)\n                decor_trj = self._apply_mask_to_trj(self._decor_masks[i],\n                        trj, filename)\n                self._trjtype_to_decors[trjtype].append(decor_trj)\n\n    def _apply_mask_to_trj(self, mask, trj, filename):\n        out_file = open(filename, 'w')\n        step_i = 0\n        mask_i = 0\n        for step in trj:\n            step_included = step_i == mask[mask_i]\n            if step_included:\n                out_file.write(step)\n                mask_i += 1\n                if mask_i == len(mask):\n                    return\n\n            step_i += 1\n        trj.close()\n\n        out_file.close()\n\n    def write_decors_to_files(self):\n        for datatype in self._datatypes:\n            for i, sim_collection in enumerate(self._sim_collections):\n                filebase = '{}_decor'.format(sim_collection.filebase)\n                if datatype == 'enes':\n                    self._datatype_to_decors[datatype][i].to_file(filebase,\n                            float(sim_collection.conditions.temp))\n                else:\n                    self._datatype_to_decors[datatype][i].to_file(filebase)\n\n    def filter_collections(self, filter_tag, value):\n        filtered_count = 0\n        for i, sim_collection in enumerate(self._sim_collections):\n\n            # Create mask\n            selected_op = self._datatype_to_decors['ops'][i][filter_tag]\n            mask = selected_op == value\n            filtered_count += mask.sum()\n\n            # Apply mask\n            for datatype in self._datatypes:\n                data = self._datatype_to_decors[datatype][i]._data\n                reduced_data = []\n                for series in data:\n                    reduced_data.append(series[mask])\n\n                reduced_data = np.array(reduced_data)\n                self._datatype_to_decors[datatype][i]._data = reduced_data\n\n        return filtered_count\n", "meta": {"hexsha": "bc2da129fd7d7cb59861810097cf95ee60549703", "size": 13180, "ext": "py", "lang": "Python", "max_stars_repo_path": "origamipy/decorrelate.py", "max_stars_repo_name": "jakublala/LatticeDNAOrigamiJakub", "max_stars_repo_head_hexsha": "efd1147deea534f1c9cd0ab22bc3c5dec89c3c52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-12T13:18:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-12T13:18:53.000Z", "max_issues_repo_path": "origamipy/decorrelate.py", "max_issues_repo_name": "jakublala/LatticeDNAOrigamiJakub", "max_issues_repo_head_hexsha": "efd1147deea534f1c9cd0ab22bc3c5dec89c3c52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "origamipy/decorrelate.py", "max_forks_repo_name": "jakublala/LatticeDNAOrigamiJakub", "max_forks_repo_head_hexsha": "efd1147deea534f1c9cd0ab22bc3c5dec89c3c52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8790560472, "max_line_length": 82, "alphanum_fraction": 0.5848254932, "include": true, "reason": "import numpy", "num_tokens": 2847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.17382634538395528}}
{"text": "\"\"\"\n\nWritten by JT Fuchs in July 2015\nBased off pySALT redution routine specsens.py by S. Crawford\nAnd reading the darned IRAF documentation\n\nflux_calibration.py performs flux calibration on a 1D and wavelength-calibrated spectrum\n\nTo run file:\npython flux_calibration.py spec_list --flux_list listflux.txt --stan_list liststandards.txt --extinct False\npython flux_calibration.py GD1212.ms.fits --usemaster True\n\n\n:INPUTS:\n    spec_list: either single *.fits file or text file containing list of files to flux calibrate.\n\n:OPTIONS:\n    --flux_list: string, file containing standard star fluxes. These are typically m*.dat.\n\n    --stan_list: string, file with list of 1D standard star spectra\n\n    --usemaster: boolean, Option to use master response function instead of single star observation. Default: False\n\n    --extinct: boolean, Option to extinction correct spectra. Default: True\n\n:OUTPUTS: \n        flux calibrated files (_flux is added to the filename). User will be prompted if file will overwrite existing file.\n\n        sensitivity_params.txt:  File is updated everytime spec_sens.py is run. Contains information used in the flux calibration. Columns are: input observed spectrum, date/time program was run, observed standard spectrum used for calibration, flux calibration file (m*dat), pixel regions excluded in fit, order of polynomial to flux standard, width in Angstroms used for rebinning, output spectrum filename\n\n        sens_fits_DATE.txt: File for diagnostics. Columns are: wavelength, observed flux, polynomial fit, and residuals for each standard listed above. There are extra zeros at the bottom of some columns. \n\n\n\nEach list should have the names of the stars, with blue and red exposures next to each other.\nThe ordering of the standard star flux files should match the order of the standard star list.\nExample:\n\nliststandard:\nwtfb.LTT3218_930_blue.ms.fits\nwtfb.LTT3218_930_red.ms.fits\nwnb.GD50_930_blue.ms.fits\nwnb.GD50_930_red.ms.fits\n\nlistflux:\nmltt3218.dat\nmgd50.dat\n\nspec_list:\nwnb.WD0122p0030_930_blue.ms.fits\nwnb.WD0122p0030_930_red.ms.fits\nwnb.WD0235p069_930_blue.ms.fits\nwnb.WD0235p069_930_red.ms.fits\n\n#####\n\nCounting variables are fruits and vegetables.\n\n\n\"\"\"\n\nimport os\nimport sys\nimport numpy as np\n#import pyfits as fits\nimport astropy.io.fits as fits\nimport spectools as st\nimport datetime\nfrom glob import glob\nimport matplotlib.pyplot as plt\nfrom scipy.interpolate import UnivariateSpline\nimport argparse\n\n#=============================================\n#To help with command line interpretation\ndef str2bool(v):\n    if v.lower() in ('yes','true','t','y','1'):\n        return True\n    if v.lower() in ('no','false','f','n','0'):\n        return False\n    else:\n        raise argparse.ArgumentTypeError('Boolean value expected.')\n\n\n#=============================================\n#These functions are to help with excluding regions from the sensitivity function\ndef find_nearest(array,value):\n    idx = (np.abs(array-value)).argmin()\n    return array[idx]\n\ndef onclick(event):\n    global ix,iy\n    ix, iy = event.xdata,event.ydata\n    global coords\n    ax.axvline(x=ix,color='k',linewidth='3')\n    fig.canvas.draw()\n    coords.append((ix,iy))\n\n\n#=============================================\n\n\ndef flux_calibrate_now(stdlist,fluxlist,speclist,extinct_correct=False,masterresp=False):\n    if extinct_correct:\n        extinctflag = 0\n    else:\n        extinctflag = -1\n    if masterresp: #Use the master response function\n        #Read in master response function and use that.\n        cwd = os.getcwd()\n        os.chdir('/afs/cas.unc.edu/depts/physics_astronomy/clemens/students/group/standards/response_curves/')\n        standards = sorted(glob('*resp*.npy'))\n\n        master_response_blue_in = np.load(standards[0])\n        master_response_blue_in_pol = np.poly1d(master_response_blue_in)\n        master_response_blue_out = np.load(standards[1])\n        master_response_blue_out_pol = np.poly1d(master_response_blue_out)\n        master_response_red_in = np.load(standards[2])\n        master_response_red_in_pol = np.poly1d(master_response_red_in)\n        master_response_red_out = np.load(standards[3])\n        master_response_red_out_pol = np.poly1d(master_response_red_out)\n\n        os.chdir(cwd)\n\n        airstd = np.ones([4])\n        #airstd[0] = 1.1\n\n        #For saving files correctly\n        stdflux = np.array(['mmaster.dat'])\n        #standards = np.array([masterlist])\n        allexcluded = [[None] for i in range(len(standards))]\n        orderused = np.zeros([len(standards)])\n        size = 0.\n\n        #Find shift for each night\n        #For blue setup: use mean of 4530-4590\n        #for red setup: use mean of 6090-6190\n        try:\n            flux_tonight_list = np.genfromtxt('response_curves.txt',dtype=str)\n            print 'Found response_curves.txt file.'\n            print flux_tonight_list\n            if flux_tonight_list.size == 1:\n                flux_tonight_list = np.array([flux_tonight_list])\n            for x in flux_tonight_list:\n                #print x\n                if 'blue' in x.lower():\n                    wave_tonight, sens_tonight = np.genfromtxt(x,unpack=True)\n                    blue_low_index = np.min(np.where(wave_tonight > 4530.))\n                    blue_high_index = np.min(np.where(wave_tonight > 4590.))\n                    blue_mean_tonight = np.mean(sens_tonight[blue_low_index:blue_high_index])\n                elif 'red' in x.lower():\n                    wave_tonight, sens_tonight = np.genfromtxt(x,unpack=True)\n                    red_low_index = np.min(np.where(wave_tonight > 6090.))\n                    red_high_index = np.min(np.where(wave_tonight > 6190.))\n                    red_mean_tonight = np.mean(sens_tonight[red_low_index:red_high_index])\n        except:\n            print 'No response_curves.txt file found.'\n            blue_mean_tonight = None\n            red_mean_tonight = None\n            flux_tonight_list = ['None','None']\n        \n    else: #Use the standard star fluxes in the typical manner\n        #Read in each standard star spectrum \n        standards = np.genfromtxt(stdlist,dtype=str)\n        if standards.size ==1:\n            standards = np.array([standards])\n        stdflux = np.genfromtxt(fluxlist,dtype=str)\n        if stdflux.size == 1:\n            stdflux = np.array([stdflux]) #save stdflux explicitly as an array so you can index if only 1 element\n        #Check that the files are set up correctly to avoid mixing standards.\n        #This checks that the files in liststandard have similar characters to those in listflux and the correct order. But might break if flux file doesn't match. E.G. mcd32d9927.dat is often called CD-32_9927 in our system. \n        '''\n        onion = 0\n        for stanspec in standards:\n            quickcheck = stdflux[onion//2].lower()[1:-4] in stanspec.lower()\n            if not quickcheck:\n                print 'Check your standard star and flux files. They are mixed up.'\n                sys.exit()\n            onion += 1\n        '''\n        orderused = np.zeros([len(standards)])\n        senspolys = []\n        airstd = np.zeros([len(standards)])\n        allexcluded = [[None] for i in range(len(standards))]\n        \n        #Calculating the sensitivity function of each standard star\n        cucumber = 0\n        for stdspecfile in standards:\n            print stdspecfile\n            #Read in the observed spectrum of the standard star\n            obs_spectra,airmass,exptime,dispersion = st.readspectrum(stdspecfile) #obs_spectra is an object containing opfarr,farr,sky,sigma,warr\n            airstd[cucumber] = airmass\n            #plt.clf()\n            #plt.plot(obs_spectra.warr,obs_spectra.opfarr)\n            #plt.show()\n        \n            #Do the extinction correction\n            if extinct_correct:\n                print 'Extinction correcting spectra.'\n                plt.clf()\n                plt.plot(obs_spectra.warr,obs_spectra.opfarr)\n                obs_spectra.opfarr = st.extinction_correction(obs_spectra.warr,obs_spectra.opfarr,airmass)\n                plt.plot(obs_spectra.warr,obs_spectra.opfarr)\n                #plt.show()\n\n            #Change to the standard star directory\n            cwd = os.getcwd()\n            os.chdir('/afs/cas.unc.edu/depts/physics_astronomy/clemens/students/group/standards')\n\n            #read in the standard file\n            placeholder = cucumber // 2\n            stdfile = stdflux[placeholder]\n            std_spectra = st.readstandard(stdfile)\n            os.chdir(cwd)\n            #plt.clf()\n            #plt.plot(std_spectra.warr,std_spectra.magarr,'.')\n            #plt.show()\n            #Only keep the part of the standard file that overlaps with observation.\n            lowwv = np.where(std_spectra.warr >= np.min(obs_spectra.warr))\n            lowwv = np.asarray(lowwv)\n            highwv = np.where(std_spectra.warr <= np.max(obs_spectra.warr))\n            highwv = np.asarray(highwv)\n            index = np.intersect1d(lowwv,highwv)\n        \n            std_spectra.warr = std_spectra.warr[index]\n            std_spectra.magarr = std_spectra.magarr[index]\n            std_spectra.wbin = std_spectra.wbin[index]\n        \n            #Convert from AB mag to fnu, then to fwave (ergs/s/cm2/A)\n            stdzp = 3.68e-20 #The absolute flux per unit frequency at an AB mag of zero\n            std_spectra.magarr = st.magtoflux(std_spectra.magarr,stdzp)\n            std_spectra.magarr = st.fnutofwave(std_spectra.warr, std_spectra.magarr)\n\n            #plt.clf()\n            #plt.plot(std_spectra.warr,std_spectra.magarr,'.')\n            #plt.show()\n            #np.savetxt('hz4_stan.txt',np.transpose([std_spectra.warr,std_spectra.magarr]))\n            #exit()\n        \n            #We want to rebin the observed spectrum to match with the bins in the standard file. This makes summing up counts significantly easier.\n            #Set the new binning here.\n            print 'Starting to rebin: ',stdspecfile \n            low = np.rint(np.min(obs_spectra.warr)) #Rounds to nearest integer\n            high = np.rint(np.max(obs_spectra.warr))\n            size = 0.05 #size in Angstroms you want each bin\n        \n            num = (high - low) / size + 1. #number of bins. Must add one to get correct number.\n            wavenew = np.linspace(low,high,num=num) #wavelength of each new bin\n\n            #Now do the rebinning using Ian Crossfield's rebinning package\n            binflux = st.resamplespec(wavenew,obs_spectra.warr,obs_spectra.opfarr,200.) #200 is the oversampling factor\n            print 'Done rebinning. Now summing the spectrum into new bins to match', stdfile\n            #plt.clf()\n            #plt.plot(obs_spectra.warr,obs_spectra.opfarr)\n            #plt.plot(wavenew,binflux)\n            #plt.show()\n        \n            #Now sum the rebinned spectra into the same bins as the standard star file\n            counts = st.sum_std(std_spectra.warr,std_spectra.wbin,wavenew,binflux)\n            #plt.clf()\n            #plt.plot(std_spectra.warr,std_spectra.magarr)\n            #plt.plot(obs_spectra.warr,obs_spectra.opfarr,'b')\n            #plt.plot(std_spectra.warr,counts,'g+')\n            #plt.show()\n            \n            #Calculate the sensitivity function\n            sens_function = st.sensfunc(counts,std_spectra.magarr,exptime,std_spectra.wbin,airmass)\n            #plt.clf()\n            #plt.plot(std_spectra.warr,sens_function)\n            #plt.show()\n            #sys.exit()\n            #Fit a low order polynomial to this function so that it is smooth.\n            #The sensitivity function is in units of 2.5 * log10[counts/sec/Ang / ergs/cm2/sec/Ang]\n            #Choose regions to not include in fit, first by checking if a mask file exists, and if not the prompt for user interaction.\n            if 'blue' in stdspecfile.lower():\n                std_mask = stdfile[0:-4] + '_blue_maskasdf.dat'\n            if 'red' in stdspecfile.lower():\n                std_mask = stdfile[0:-4] + '_red_maskasdf.dat'\n            std_mask2 = glob(std_mask)\n            if len(std_mask2) == 1.:\n                print 'Found mask file.\\n'\n                mask = np.ones(len(std_spectra.warr))\n                excluded_wave = np.genfromtxt(std_mask) #Read in wavelengths to exclude\n                #print excluded_wave\n                #print type(excluded_wave)\n                #Find index of each wavelength\n                excluded = []\n                for x in excluded_wave:\n                    #print x\n                    #print np.where(std_spectra.warr == find_nearest(std_spectra.warr,x))\n                    pix_val = np.where(std_spectra.warr == find_nearest(std_spectra.warr,x))\n                    excluded.append(pix_val[0][0])\n                #print excluded\n                lettuce = 0\n                while lettuce < len(excluded):\n                    mask[excluded[lettuce]:excluded[lettuce+1]+1] = 0\n                    lettuce += 2\n                excluded =  np.array(excluded).tolist()\n                allexcluded[cucumber] = excluded\n                indices = np.where(mask !=0.)\n                lambdasfit = std_spectra.warr[indices]\n                fluxesfit = sens_function[indices]\n            else:\n                print 'No mask found. User interaction required.\\n'\n                \n                global ax, fig, coords\n                coords = []\n                plt.clf()\n                fig = plt.figure(1)\n                ax = fig.add_subplot(111)\n                ax.plot(std_spectra.warr,sens_function)\n                cid = fig.canvas.mpl_connect('button_press_event',onclick)\n                print 'Please click on both sides of regions you want to exclude. Then close the plot.'\n                plt.title('Click both sides of regions you want to exclude. Then close the plot.')\n                plt.show(1)\n        \n        \n                #Mask our the regions you don't want to fit\n                #We need make sure left to right clicking and right to left clicking both work.\n                mask = np.ones(len(std_spectra.warr))\n                excluded = np.zeros(len(coords))\n                lettuce = 0\n                if len(coords) > 0:\n                    while lettuce < len(coords):\n                        x1 = np.where(std_spectra.warr == (find_nearest(std_spectra.warr,coords[lettuce][0])))\n                        excluded[lettuce] = np.asarray(x1)\n                        lettuce += 1\n                        x2 = np.where(std_spectra.warr == (find_nearest(std_spectra.warr,coords[lettuce][0])))\n                        if x2 < x1:\n                            x1,x2 = x2,x1\n                        mask[x1[0][0]:x2[0][0]+1] = 0 #have to add 1 here to the second index so that we exclude through that index. Most important for when we need to exclude the last point of the array.\n                        excluded[lettuce-1] = np.asarray(x1)\n                        excluded[lettuce] = np.asarray(x2)\n                        lettuce += 1\n\n                excluded =  np.array(excluded).tolist()\n                allexcluded[cucumber] = excluded\n                indices = np.where(mask !=0.)\n                lambdasfit = std_spectra.warr[indices]\n                fluxesfit = sens_function[indices]\n        \n                #Save masked wavelengths\n                lambdasnotfit = std_spectra.warr[excluded]\n                #print lambdasnotfit\n                #print stdfile\n                if 'blue' in stdspecfile.lower():\n                    std_mask_name = stdfile[0:-4] + '_blue_mask.dat'\n                if 'red' in stdspecfile.lower():\n                    std_mask_name = stdfile[0:-4] + '_red_mask.dat'\n                np.savetxt(std_mask_name,np.transpose(np.array(lambdasnotfit)))\n                #exit()\n\n            ##Move back to directory with observed spectra\n            #os.chdir(cwd) \n        \n        \n            #Make sure they are finite\n            ind1 = np.isfinite(lambdasfit) & np.isfinite(fluxesfit)\n            lambdasfit = lambdasfit[ind1]\n            fluxesfit = fluxesfit[ind1]\n\n            print 'Fitting the sensitivity funtion now.'\n            order = 4\n            repeat = 'yes'\n            while repeat == 'yes':\n                p = np.polyfit(lambdasfit,fluxesfit,order)\n                f = np.poly1d(p)\n                smooth_sens = f(lambdasfit)\n                residual = fluxesfit - smooth_sens\n                plt.close()\n                plt.ion()\n                g, (ax1,ax2) = plt.subplots(2,sharex=True)\n                ax1.plot(lambdasfit,fluxesfit,'b+')\n                ax1.plot(lambdasfit,smooth_sens,'r',linewidth=2.0)\n                ax1.set_ylabel('Sensitivity Function')\n                ax2.plot(lambdasfit,residual,'k+')\n                ax2.set_ylabel('Residuals')\n                ax1.set_title('Current polynomial order: %s' % order)\n                g.subplots_adjust(hspace=0)\n                plt.setp([a.get_xticklabels() for a in g.axes[:-1]],visible=False)\n                plt.show()\n                plt.ioff()\n                #Save this sensitivity curve\n                '''\n                try:\n                    temp_file = fits.open(stdspecfile)\n                    ADCstat = temp_file[0].header['ADCSTAT']\n                except:\n                    ADCstat = 'none'\n                    pass\n                if 'blue' in stdspecfile.lower():\n                    resp_name = 'senscurve_' + stdfile[1:-4] + '_' + str(np.round(airstd[cucumber],decimals=3))  + '_' + ADCstat  + '_' + cwd[60:70] + '_blue.txt'\n                elif 'red' in stdspecfile.lower():\n                    resp_name = 'senscurve_' + stdfile[1:-4] + '_' + str(np.round(airstd[cucumber],decimals=3))  + '_' + ADCstat  + '_' + cwd[60:70] + '_red.txt'\n                print resp_name\n                #exit()\n                np.savetxt(resp_name,np.transpose([lambdasfit,fluxesfit]))\n                '''\n                repeat = raw_input('Do you want to try again (yes/no)? ')\n                if repeat == 'yes':\n                    order = raw_input('New order for polynomial: ')\n\n            orderused[cucumber] = order\n            senspolys.append(f)\n\n            #Save arrays for diagnostic plots\n            if cucumber == 0:\n                bigarray = np.zeros([len(lambdasfit),4.*len(standards)])\n                artichoke = 0\n            bigarray[0:len(lambdasfit),artichoke] = lambdasfit\n            bigarray[0:len(fluxesfit),artichoke+1] = fluxesfit\n            bigarray[0:len(smooth_sens),artichoke+2] = smooth_sens\n            bigarray[0:len(residual),artichoke+3] = residual\n            artichoke += 4\n                   \n            cucumber += 1\n\n        #Save fit and residuals into text file for diagnostic plotting later.\n        #Need to save lambdasfit,fluxesfit,smooth_sens,residual for each standard\n        #List of standards is found as standards\n        now = datetime.datetime.now().strftime(\"%Y-%m-%dT%H:%M\")\n        with open('sens_fits_' + now + '.txt','a') as handle:\n            header = str(standards) + '\\n Set of four columns correspond to wavelength, observed flux, polynomial fit, \\n and residuals for each standard listed above. \\n You will probably need to strip zeros from the bottoms of some columns.'\n            np.savetxt(handle,bigarray,fmt='%f',header = header)    \n\n    #Outline for next steps:\n    #Read in both red and blue files\n    #compute airmass and compare to airstd\n    #choose best standard and flux calibrate both blue and red\n    #save files and write to sensitivity_params.txt\n    \n    if speclist[-4:] == 'fits':\n        specfile = np.array([speclist])\n    else:\n        specfile = np.genfromtxt(speclist,dtype=str)\n        if specfile.size ==1:\n            specfile = np.array([specfile])\n    \n    length = len(specfile)\n    airwd = np.zeros([length])\n    bean = 0\n    #if length == 1:\n    #    redfile = False\n    #else:\n    #    redfile = True\n\n    avocado = 0\n    while avocado < length:\n        #Read in the blue and red spectra we want to flux calibrate. Save the airmass\n        WD_spectra1,airmass1,exptime1,dispersion1 = st.readspectrum(specfile[avocado])\n        if (len(specfile) >= 1) and (avocado+1 < length):\n            if 'red' in specfile[avocado+1]:\n                redfile = True\n            else:\n                redfile = False\n        else:\n            redfile = False\n        if redfile:\n            WD_spectra2,airmass2,exptime2,dispersion2 = st.readspectrum(specfile[avocado+1])\n                \n        #Extinction correct WD\n        if extinct_correct:\n            print 'Extinction correcting spectra.'\n            #plt.clf()\n            #plt.plot(WD_spectra1.warr,WD_spectra1.opfarr)\n            WD_spectra1.opfarr = st.extinction_correction(WD_spectra1.warr,WD_spectra1.opfarr,airmass1)\n            WD_spectra1.farr = st.extinction_correction(WD_spectra1.warr,WD_spectra1.farr,airmass1)\n            WD_spectra1.sky = st.extinction_correction(WD_spectra1.warr,WD_spectra1.sky,airmass1)\n            WD_spectra1.sigma = st.extinction_correction(WD_spectra1.warr,WD_spectra1.sigma,airmass1)\n            #plt.plot(WD_spectra1.warr,WD_spectra1.opfarr)\n            #plt.show()\n\n            if redfile:\n                #plt.clf()\n                #plt.plot(WD_spectra2.warr,WD_spectra2.opfarr)\n                WD_spectra2.opfarr = st.extinction_correction(WD_spectra2.warr,WD_spectra2.opfarr,airmass2)\n                WD_spectra2.farr = st.extinction_correction(WD_spectra2.warr,WD_spectra2.farr,airmass2)\n                WD_spectra2.sky = st.extinction_correction(WD_spectra2.warr,WD_spectra2.sky,airmass2)\n                WD_spectra2.sigma = st.extinction_correction(WD_spectra2.warr,WD_spectra2.sigma,airmass2)\n\n\n                #zaplt.plot(WD_spectra2.warr,WD_spectra2.opfarr)\n                #plt.show()\n        airwd[avocado] = airmass1\n        if redfile:\n            airwd[avocado+1] = airmass2\n        #Compare the airmasses to determine the best standard star\n        tomato = 0\n        while tomato < len(airstd):\n            if redfile:\n                diff = np.absolute(np.mean([airwd[avocado],airwd[avocado+1]]) - np.mean([airstd[tomato],airstd[tomato+1]]))\n            else:\n                diff = np.absolute(airwd[avocado] - airstd[tomato])\n            if tomato == 0:\n                difference = diff\n                choice = tomato\n            if diff < difference:\n                difference = diff\n                choice = tomato\n            tomato += 2\n    \n        #To get the flux calibration, perform the following\n        #Flux = counts / (Exptime * dispersion * 10**(sens/2.5))\n        #Get the sensitivity function at the correct wavelength spacing\n        if masterresp:\n            header_temp = st.readheader(specfile[avocado])\n            ADCstatus = header_temp['ADCSTAT']\n            if ADCstatus == 'IN':\n                sens_wave1_unscale = master_response_blue_in_pol(WD_spectra1.warr)\n                blue_low_index = np.min(np.where(WD_spectra1.warr > 4530.))\n                blue_high_index = np.min(np.where(WD_spectra1.warr > 4590.))\n                blue_mean_stan = np.mean(sens_wave1_unscale[blue_low_index:blue_high_index])\n                if blue_mean_tonight == None:\n                    sens_wave1 = sens_wave1_unscale\n                else:\n                    sens_wave1 = sens_wave1_unscale + (blue_mean_tonight - blue_mean_stan)\n                choice = 0\n            else:\n                sens_wave1_unscale = master_response_blue_out_pol(WD_spectra1.warr)\n                blue_low_index = np.min(np.where(WD_spectra1.warr > 4530.))\n                blue_high_index = np.min(np.where(WD_spectra1.warr > 4590.))\n                blue_mean_stan = np.mean(sens_wave1_unscale[blue_low_index:blue_high_index])\n                if blue_mean_tonight == None:\n                    sens_wave1 = sens_wave1_unscale\n                else:\n                    sens_wave1 = sens_wave1_unscale + (blue_mean_tonight - blue_mean_stan)\n                choice = 1\n            if redfile:\n                header_temp = st.readheader(specfile[avocado+1])\n                ADCstatus = header_temp['ADCSTAT']\n                if ADCstatus == 'IN':\n                    sens_wave2_unscale = master_response_red_in_pol(WD_spectra2.warr)\n                    red_low_index = np.min(np.where(WD_spectra2.warr > 6090.))\n                    red_high_index = np.min(np.where(WD_spectra2.warr > 6190.))\n                    red_mean_stan = np.mean(sens_wave2_unscale[red_low_index:red_high_index])\n                    if red_mean_tonight == None:\n                        sens_wave2 = sens_wave2_unscale\n                    else:\n                        sens_wave2 = sens_wave2_unscale + (red_mean_tonight - red_mean_stan)\n                    choice2 = 2\n                else:\n                    sens_wave2_unscale = master_response_red_out_pol(WD_spectra2.warr)\n                    red_low_index = np.min(np.where(WD_spectra2.warr > 6090.))\n                    red_high_index = np.min(np.where(WD_spectra2.warr > 6190.))\n                    red_mean_stan = np.mean(sens_wave2_unscale[red_low_index:red_high_index])\n                    if red_mean_tonight == None:\n                        sens_wave2 = sens_wave2_unscale\n                    else:\n                        sens_wave2 = sens_wave2_unscale + (red_mean_tonight - red_mean_stan)\n                    choice2 = 3\n        else:\n            sens_wave1 = senspolys[choice](WD_spectra1.warr)\n            if redfile:\n                sens_wave2 = senspolys[choice+1](WD_spectra2.warr)\n\n        #Perform the flux calibration. We do this on the optimal extraction, non-variance weighted aperture, the sky spectrum, and the sigma spectrum.\n        print 'Doing the final flux calibration.'\n        #np.savetxt('response_g60-54_extinction_2016-03-17.txt',np.transpose([WD_spectra1.warr,(exptime1 * dispersion1 * 10.**(sens_wave1/2.5))]))#,WD_spectra2.warr,(exptime2 * dispersion2 * 10.**(sens_wave2/2.5))]))\n        #exit()\n        star_opflux1 = st.cal_spec(WD_spectra1.opfarr,sens_wave1,exptime1,dispersion1)\n        star_flux1 = st.cal_spec(WD_spectra1.farr,sens_wave1,exptime1,dispersion1)\n        sky_flux1 = st.cal_spec(WD_spectra1.sky,sens_wave1,exptime1,dispersion1)\n        sigma_flux1 = st.cal_spec(WD_spectra1.sigma,sens_wave1,exptime1,dispersion1)\n\n        if redfile:\n            star_opflux2 = st.cal_spec(WD_spectra2.opfarr,sens_wave2,exptime2,dispersion2)\n            star_flux2 = st.cal_spec(WD_spectra2.farr,sens_wave2,exptime2,dispersion2)\n            sky_flux2 = st.cal_spec(WD_spectra2.sky,sens_wave2,exptime2,dispersion2)\n            sigma_flux2 = st.cal_spec(WD_spectra2.sigma,sens_wave2,exptime2,dispersion2)\n        \n        #plt.clf()\n        #plt.plot(WD_spectra.warr,star_opflux)\n        #plt.show()\n\n        #Save final spectra if using master response\n        if masterresp:\n            if avocado == 0:\n                diagnostic_array = np.zeros([len(WD_spectra1.warr),2*length])\n            diagnostic_array[0:len(WD_spectra1.warr),bean] = WD_spectra1.warr\n            bean += 1\n            diagnostic_array[0:len(star_opflux1),bean] = star_opflux1\n            bean += 1\n            if redfile:\n                diagnostic_array[0:len(WD_spectra2.warr),bean] = WD_spectra2.warr\n                bean += 1\n                diagnostic_array[0:len(star_opflux2),bean] = star_opflux2\n                bean += 1\n        #if avocado == (length -1 ) or (redfile == True and avocado == (length-2)):\n        #    print 'Saveing diagnostic file.'\n        #    now = datetime.datetime.now().strftime(\"%Y-%m-%dT%H:%M\")\n        #    with open('flux_fits_' + now + '.txt','a') as handle:\n        #        header = str(specfile) + '\\n Each star is formatted as wavelength, flux'\n        #        np.savetxt(handle,diagnostic_array,fmt='%.10e',header=header)\n\n\n        print 'Saving the final spectrum.'\n        \n        #Save the flux-calibrated spectrum and update the header\n        header1 = st.readheader(specfile[avocado])\n        header1.set('EX-FLAG',extinctflag) #Extiction correction? 0=yes, -1=no\n        header1.set('CA-FLAG',0) #Calibrated to flux scale? 0=yes, -1=no\n        header1.set('BUNIT','erg/cm2/s/A') #physical units of the array value\n        header1.set('STANDARD',str(standards[choice]),'Flux standard used') #flux standard used for flux-calibration\n        if masterresp:\n            header1.set('STDOFF',str(flux_tonight_list[0]),'Night offset used')\n        \n        if redfile:\n            header2 = st.readheader(specfile[avocado+1])\n            header2.set('EX-FLAG',extinctflag) #Extiction correction? 0=yes, -1=no\n            header2.set('CA-FLAG',0) #Calibrated to flux scale? 0=yes, -1=no\n            header2.set('BUNIT','erg/cm2/s/A') #physical units of the array value\n            if masterresp:\n                header2.set('STANDARD',str(standards[choice2]),'Flux standard used') #flux standard used for flux-calibration\n                header1.set('STDOFF',str(flux_tonight_list[1]),'Night offset used')\n            else:\n                header2.set('STANDARD',str(standards[choice+1]),'Flux standard used') #flux standard used for flux-calibration\n\n        #Set up size of new fits image\n        Ni = 4. #Number of extensions\n        Nx1 = len(star_flux1)\n        if redfile:\n            Nx2 = len(star_flux2)\n        Ny = 1. #All 1D spectra\n\n        data1 = np.empty(shape = (Ni,Ny,Nx1))\n        data1[0,:,:] = star_opflux1\n        data1[1,:,:] = star_flux1\n        data1[2,:,:] = sky_flux1\n        data1[3,:,:] = sigma_flux1\n    \n        if redfile:\n            data2 = np.empty(shape = (Ni,Ny,Nx2))\n            data2[0,:,:] = star_opflux2\n            data2[1,:,:] = star_flux2\n            data2[2,:,:] = sky_flux2\n            data2[3,:,:] = sigma_flux2\n\n        #Add '_flux' to the end of the filename\n        loc1 = specfile[avocado].find('.ms.fits')\n        if masterresp:\n            newname1 = specfile[avocado][0:loc1] + '_flux_' + stdflux[0][1:-4]  + '.ms.fits'\n        else:\n            newname1 = specfile[avocado][0:loc1] + '_flux_' + stdflux[choice//2][1:-4]  + '.ms.fits'\n        clob = False\n        mylist = [True for f in os.listdir('.') if f == newname1]\n        exists = bool(mylist)\n\n        if exists:\n            print 'File %s already exists.' % newname1\n            nextstep = raw_input('Do you want to overwrite or designate a new name (overwrite/new)? ')\n            if nextstep == 'overwrite':\n                clob = True\n                exists = False\n            elif nextstep == 'new':\n                newname1 = raw_input('New file name: ')\n                exists = False\n            else:\n                exists = False\n        print 'Saving: ', newname1\n        newim1 = fits.PrimaryHDU(data=data1,header=header1)\n        newim1.writeto(newname1,clobber=clob)\n\n        if redfile:\n            loc2 = specfile[avocado+1].find('.ms.fits')\n            if masterresp:\n                newname2 = specfile[avocado+1][0:loc2] + '_flux_' + stdflux[0][1:-4] + '.ms.fits'\n            else:\n                newname2 = specfile[avocado+1][0:loc2] + '_flux_' + stdflux[choice//2][1:-4] + '.ms.fits'\n            clob = False\n            mylist = [True for f in os.listdir('.') if f == newname2]\n            exists = bool(mylist)\n\n            if exists:\n                print 'File %s already exists.' % newname2\n                nextstep = raw_input('Do you want to overwrite or designate a new name (overwrite/new)? ')\n                if nextstep == 'overwrite':\n                    clob = True\n                    exists = False\n                elif nextstep == 'new':\n                    newname2 = raw_input('New file name: ')\n                    exists = False\n                else:\n                    exists = False\n\n            newim2 = fits.PrimaryHDU(data=data2,header=header2)\n            newim2.writeto(newname2,clobber=clob)\n            print 'Saving: ', newname2\n\n        #Finally, save all the used parameters into a file for future reference.\n        # specfile,current date, stdspecfile,stdfile,order,size,newname\n        f = open('sensitivity_params.txt','a')\n        now = datetime.datetime.now().strftime(\"%Y-%m-%dT%H:%M\")\n        if masterresp:\n            newinfo1 = specfile[avocado] + '\\t' + now + '\\t' + standards[choice] + '\\t' + stdflux[0] + '\\t' + str(allexcluded[choice]) + '\\t' + str(orderused[choice]) + '\\t' + str(size) + '\\t' + newname1\n        else:\n            newinfo1 = specfile[avocado] + '\\t' + now + '\\t' + standards[choice] + '\\t' + stdflux[choice//2] + '\\t' + str(allexcluded[choice]) + '\\t' + str(orderused[choice]) + '\\t' + str(size) + '\\t' + newname1\n        if redfile:\n            if masterresp:\n                newinfo2 = specfile[avocado+1] + '\\t' + now + '\\t' + standards[choice2] + '\\t' + stdflux[0] + '\\t' + str(allexcluded[choice+1]) + '\\t' + str(orderused[choice+1]) + '\\t' + str(size) + '\\t' + newname2\n            else:\n                newinfo2 = specfile[avocado+1] + '\\t' + now + '\\t' + standards[choice+1] + '\\t' + stdflux[choice//2] + '\\t' + str(allexcluded[choice+1]) + '\\t' + str(orderused[choice+1]) + '\\t' + str(size) + '\\t' + newname2\n            f.write(newinfo1 + \"\\n\" + newinfo2 + \"\\n\")\n        else:\n            f.write(newinfo1 + \"\\n\")\n        f.close()\n\n        if redfile:\n            avocado += 2\n        else:\n            avocado += 1\n\n    print 'Done flux calibrating the spectra.'\n\n\n\n\n\n#Run from command line\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('spec_list')\n    parser.add_argument('--flux_list',default=None)\n    parser.add_argument('--stan_list',default=None)\n    parser.add_argument('--usemaster',type=str2bool,nargs='?',const=False,default=False,help='Activate nice mode.')\n    parser.add_argument('--extinct',type=str2bool,nargs='?',const=True,default=True,help='Activate nice mode.')\n    args = parser.parse_args()\n    #print args.stand_list\n    flux_calibrate_now(args.stan_list,args.flux_list,args.spec_list,extinct_correct=args.extinct,masterresp=args.usemaster)\n", "meta": {"hexsha": "1b2387edc27971ba736c91c0554ba11698b7dcb0", "size": 33980, "ext": "py", "lang": "Python", "max_stars_repo_path": "flux_calibration.py", "max_stars_repo_name": "joshfuchs/ZZCeti_pipeline", "max_stars_repo_head_hexsha": "f3803817e4894d25c1e39ae9fb07b6896d9ce9c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "flux_calibration.py", "max_issues_repo_name": "joshfuchs/ZZCeti_pipeline", "max_issues_repo_head_hexsha": "f3803817e4894d25c1e39ae9fb07b6896d9ce9c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "flux_calibration.py", "max_forks_repo_name": "joshfuchs/ZZCeti_pipeline", "max_forks_repo_head_hexsha": "f3803817e4894d25c1e39ae9fb07b6896d9ce9c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-06-28T17:52:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-09T21:27:44.000Z", "avg_line_length": 46.6117969822, "max_line_length": 408, "alphanum_fraction": 0.5895821071, "include": true, "reason": "import numpy,from scipy,import astropy", "num_tokens": 8666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3174262655876759, "lm_q1q2_score": 0.17354904983878314}}
{"text": "import re\n# import sys\nimport os\nimport pandas as pd\nimport numpy as np\nfrom scipy import signal\nfrom scipy import ndimage\nfrom sklearn import decomposition\nimport matplotlib.pyplot as plt\nplt.rcParams[\"font.family\"] = \"IPAexGothic\"\n\n\nclass EMG:\n    \"\"\"\n    筋電位を扱うクラス\n\n    Attributes\n    ----------\n    data : pandas.DataFrame\n        筋電位データ\n\n    fs : float\n        サンプリング周波数\n\n    H : pandas.DataFrame\n        筋シナジーの重み\n\n    W : pandas.DataFrame\n        筋シナジーの時間変化\n\n    muscle_colors : str | list = 'tab:blue'\n        筋肉に対応する色\n\n    begin_time : float\n        対象範囲の開始時間\n\n    end_time : float\n        対象範囲の終了時間\n\n    Examples\n    --------\n    >>> from measurexp.EMG import EMG\n    >>> emg = EMG()\n    >>> emg.read('EMG.csv')\n    >>> emg.set_time(0, 30)\n    >>> emg.prep()\n    >>> emg.calc_synergy()\n    >>> emg.plot_synergy()\n    >>> emg.set_colors('../muscle_colors.csv')\n    >>> emg.plot_synergy_weights()\n    \"\"\"\n\n    def __init__(self):\n        # 筋電位データ\n        self.data: pd.DataFrame = None\n        # フィルター後のデータ\n        self.rms: pd.DataFrame = None\n        # 正規化後のデータ\n        self.norm: pd.DataFrame = None\n        # サンプリング周波数\n        self.fs: float = None\n        self.H: pd.DataFrame = None\n        self.W: pd.DataFrame = None\n        self.begin_time: float = None\n        self.end_time: float = None\n        self.muscles_color: str | list = 'tab:blue'\n        self.taskname: str = 'Unnamed'\n\n    def set_colors(self, colors) -> 'EMG':\n        \"\"\"筋肉に対応する色を設定します。\n\n        Parameters\n        ----------\n        colors : str | list\n            筋肉に対応する色のリストまたは文字列\n\n        Returns\n        -------\n        self : EMG\n        \"\"\"\n        if type(colors) in (str, list):\n            if os.path.isfile(colors):\n                self.muscles_color = pd.read_csv(\n                    colors, header=None).values.reshape(-1).tolist()\n                return self\n            self.muscles_color = colors\n        else:\n            print('筋肉に対応する色を指定してください。')\n        return self\n\n    def _col2muscles_name(self, col_muscle: str):\n        match = re.match(r'^(.+):', col_muscle)\n        if match is not None:\n            muscles_name = match.group(1)\n        return muscles_name\n\n    def read(self, filename: str) -> 'EMG':\n        \"\"\"データファイル (*.csv) を読み込みます。\n\n        Parameters\n        ----------\n        filename : str\n            データファイル (*.csv)\n\n        Returns\n        -------\n        self : EMG\n        \"\"\"\n        try:\n            # self.data = pd.read_csv(filename,\n            # encoding='Shift-JIS', header=116)\n            self.data = pd.read_csv(filename)\n        except UnicodeDecodeError as err:\n            print(err)\n            print('デコードできません。正しい文字コードを指定してください。')\n        except FileNotFoundError as err:\n            print(err)\n            print('筋電位データのファイルを指定してください。')\n\n        # インデックスの設定\n        self.data.set_index(['Time [s]'], inplace=True)\n        self.begin_time, self.end_time = \\\n            self.data.index[0], self.data.index[-1]\n        self.fs = self.data.shape[0] / (self.end_time - self.begin_time)\n        return self\n\n    def name(self, taskname: str) -> 'EMG':\n        \"\"\"タスク名を設定します。\n\n        Parameters\n        ----------\n        taskname : str\n            タスク名\n\n        Return\n        ------\n        self : EMG\n        \"\"\"\n        self.taskname = taskname\n        return self\n\n    def prep(self, period: float = 0.2, n: int = 5, Fc: np.ndarray = np.array([5, 500])) -> 'EMG':\n        \"\"\"データの下処理を行います。\n\n        Parameters\n        ----------\n        period : float = 0.1\n            RMS するウィンドウの範囲 (秒)\n\n        n : int = 5\n            ローパスフィルターの次数\n\n        Fc : int = 50\n            ローパスフィルターの遮断周波数\n\n        Returns\n        -------\n        self : EMG\n        \"\"\"\n        # b, a = signal.butter(n, Fc / self.fs * 2, 'band', analog=True)\n        x = self.data.loc[self.begin_time:self.end_time, :].copy()\n        # for m in range(x.shape[1]):\n            # x.iloc[:, m] = signal.filtfilt(b, a, x.iloc[:, m])\n\n        x[:] = np.power(x - x.mean(), 2)\n        for _ in x:\n            x[_][:] = ndimage.gaussian_filter1d(x[_], self.fs * period)\n        self.rms = np.sqrt(x)\n        return self\n\n    def resample(self, fs: int) -> 'EMG':\n        df = self.rms.copy()\n        self.rms = pd.DataFrame(\n            signal.resample(df.to_numpy(), self.end_time * fs),\n            index=(np.arange(self.end_time * fs) / fs),\n            columns=df.columns\n        )\n        df = self.data.copy()\n        self.data = pd.DataFrame(\n            signal.resample(df.to_numpy(), self.end_time * fs),\n            index=(np.arange(self.end_time * fs) / fs),\n            columns=df.columns\n        )\n        self.fs = fs\n\n        return self\n\n    def set_muscles(self, muscles) -> 'EMG':\n        self.rms = self.rms.loc[:, muscles]\n        self.data = self.data.loc[:, muscles]\n        return self\n\n    def _vaf(self, X: np.ndarray, W: np.ndarray, H: np.ndarray):\n        VAF = 1 - np.power(X - W.dot(H), 2).sum() / np.power(X, 2).sum()\n        return VAF\n\n    def _calc_synergy(self, X: np.ndarray, max_vaf: float):\n        VAFs = []\n        for n_components in range(1, X.shape[1]):\n            model = decomposition.NMF(\n                n_components=n_components,\n                init='nndsvda',\n                random_state=0,\n                tol=1e-1\n            )\n            W = model.fit_transform(X)\n            H = model.components_\n            VAFs.append(self._vaf(X, W, H))\n            if VAFs[-1] > max_vaf:\n                break\n\n        return (VAFs, W, H)\n\n    def set_time(self, begin_time: float, end_time: float) -> 'EMG':\n        \"\"\"処理対象時間を設定します。\n\n        Parameters\n        ----------\n        begin_time : float\n            処理範囲の開始時間\n\n        end_time : float\n            処理範囲の終了時間\n\n        Returns\n        -------\n        self : EMG\n        \"\"\"\n        self.begin_time, self.end_time = begin_time, end_time\n        return self\n\n    def calc_synergy(self, max_vaf: float = 0.9, norm: bool = True) -> 'EMG':\n        \"\"\"筋シナジーを計算します。\n\n        Parameters\n        ----------\n        max_vaf : float = 0.9\n            最大 VAF\n\n        norm : bool = True\n            正規化した筋シナジーで計算する\n\n        Returns\n        -------\n        self : EMG\n        \"\"\"\n        if self.norm is None:\n            print('正規化されたデータが存在しません。正規化する必要があります。')\n            return EMG\n\n        X = self.norm.values if norm else self.rms.values\n\n        self.VAFs, W, H = self._calc_synergy(X, max_vaf)\n        self.W = pd.DataFrame(\n            W,\n            columns=[f'筋シナジー {_+1}' for _ in range(W.shape[1])],\n            index=self.rms.index\n        )\n        self.H = pd.DataFrame(\n            H,\n            columns=self.rms.columns,\n            index=[f'筋シナジー {_+1}' for _ in range(W.shape[1])]\n        )\n        self.n_synergy = self.H.shape[0]\n        return self\n\n    def plot_synergy(self, **kwargs) -> 'EMG':\n        \"\"\"筋シナジーの時間変化を表示します。\n\n        Parameters\n        ----------\n        kwargs : Any\n\n\n        Returns\n        -------\n        self : EMG\n        \"\"\"\n        fig, ax = plt.subplots()\n\n        plt_kwargs = {'ax': ax}\n        if kwargs is not None:\n            plt_kwargs.update(kwargs)\n        self.W.plot(**plt_kwargs)\n        ax.set_xlim(self.begin_time, self.end_time)\n        ax.yaxis.set_major_formatter(plt.ScalarFormatter(useMathText=True))\n        ax.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))\n        plt.show()\n        return self\n\n    def plot_synergy_weights(self) -> 'EMG':\n        \"\"\"筋シナジーを表示します。\n\n        Returns\n        -------\n        self : EMG\n        \"\"\"\n\n        fig, ax = plt.subplots(\n            self.n_synergy, figsize=(6.4, 1.6 * self.n_synergy))\n        if self.n_synergy == 1:\n            ax = [ax]\n        for _ in range(self.n_synergy):\n            self.H.iloc[_, :].plot.bar(ax=ax[_], color=self.muscles_color)\n            if _ == self.n_synergy - 1:\n                break\n            ax[_].axes.xaxis.set_visible(False)\n        fig.tight_layout()\n        plt.show()\n        return self\n", "meta": {"hexsha": "5445e0bdd7a933e449798e8ac3c5f01050e3046e", "size": 7949, "ext": "py", "lang": "Python", "max_stars_repo_path": "measurexp/EMG.py", "max_stars_repo_name": "bcl-group/measurexp", "max_stars_repo_head_hexsha": "66ab471dad2534ec48d13d0546ee3a4f0eb46a91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "measurexp/EMG.py", "max_issues_repo_name": "bcl-group/measurexp", "max_issues_repo_head_hexsha": "66ab471dad2534ec48d13d0546ee3a4f0eb46a91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "measurexp/EMG.py", "max_forks_repo_name": "bcl-group/measurexp", "max_forks_repo_head_hexsha": "66ab471dad2534ec48d13d0546ee3a4f0eb46a91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5594855305, "max_line_length": 98, "alphanum_fraction": 0.5038369606, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.17354904630839937}}
{"text": "\"\"\"\nThis file is part of the OpenProtein project.\n\nFor license information, please see the LICENSE file in the root directory.\n\"\"\"\n\nimport math\nimport os\nfrom datetime import datetime\nimport torch\nimport torch.utils.data\nimport h5py\nimport PeptideBuilder\nimport Bio.PDB\nimport numpy as np\nimport pnerf.pnerf as pnerf\n\nAA_ID_DICT = {'A': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'K': 9,\n              'L': 10, 'M': 11, 'N': 12, 'P': 13, 'Q': 14, 'R': 15, 'S': 16, 'T': 17,\n              'V': 18, 'W': 19, 'Y': 20}\n\n\ndef contruct_dataloader_from_disk(filename, minibatch_size):\n    return torch.utils.data.DataLoader(H5PytorchDataset(filename),\n                                       batch_size=minibatch_size,\n                                       shuffle=True,\n                                       collate_fn=merge_samples_to_minibatch)\n\n\nclass H5PytorchDataset(torch.utils.data.Dataset):\n    def __init__(self, filename):\n        super(H5PytorchDataset, self).__init__()\n\n        self.h5pyfile = h5py.File(filename, 'r')\n        self.num_proteins, self.max_sequence_len = self.h5pyfile['primary'].shape\n\n    def __getitem__(self, index):\n        mask = torch.Tensor(self.h5pyfile['mask'][index, :]).type(dtype=torch.bool)\n        prim = torch.masked_select(\n            torch.Tensor(self.h5pyfile['primary'][index, :]).type(dtype=torch.long),\n            mask)\n        tertiary = torch.Tensor(self.h5pyfile['tertiary'][index][:int(mask.sum())])# max length x 9\n        return prim, tertiary, mask\n\n    def __len__(self):\n        return self.num_proteins\n\n\ndef merge_samples_to_minibatch(samples):\n    samples_list = []\n    for sample in samples:\n        samples_list.append(sample)\n    # sort according to length of aa sequence\n    samples_list.sort(key=lambda x: len(x[0]), reverse=True)\n    return zip(*samples_list)\n\ndef set_experiment_id(data_set_identifier, learning_rate, minibatch_size):\n    output_string = datetime.now().strftime('%Y-%m-%d_%H_%M_%S')\n    output_string += \"-\" + str(os.getpid())\n    output_string += \"-\" + data_set_identifier\n    output_string += \"-LR\" + str(learning_rate).replace(\".\", \"_\")\n    output_string += \"-MB\" + str(minibatch_size)\n    globals().__setitem__(\"experiment_id\", output_string)\n\n\ndef get_experiment_id():\n    return globals().get(\"experiment_id\")\n\n\ndef write_out(*args, end='\\n'):\n    output_string = datetime.now().strftime('%Y-%m-%d %H:%M:%S') \\\n                    + \": \" + str.join(\" \", [str(a) for a in args]) + end\n    if globals().get(\"experiment_id\") is not None:\n        with open(\"output/\" + globals().get(\"experiment_id\") + \".txt\", \"a+\") as output_file:\n            output_file.write(output_string)\n            output_file.flush()\n    print(output_string, end=\"\")\n\n\ndef write_model_to_disk(model):\n    path = \"output/models/\" + globals().get(\"experiment_id\") + \".model\"\n    torch.save(model, path)\n    return path\n\n\ndef write_prediction_data_to_disk(prediction_data):\n    filepath = \"output/predictions/\" + globals().get(\"experiment_id\") + \".txt\"\n    output_file = open(filepath, 'w')\n    output_file.write(prediction_data)\n    output_file.close()\n\n\ndef draw_plot(fig, plt, validation_dataset_size, sample_num, train_loss_values,\n              validation_loss_values):\n    def draw_with_vars():\n        ax = fig.gca()\n        ax2 = ax.twinx()\n        plt.grid(True)\n        plt.title(\"Training progress (\" + str(validation_dataset_size)\n                  + \" samples in validation set)\")\n        train_loss_plot, = ax.plot(sample_num, train_loss_values)\n        ax.set_ylabel('Train Negative log likelihood')\n        ax.yaxis.labelpad = 0\n        validation_loss_plot, = ax2.plot(sample_num, validation_loss_values, color='black')\n        ax2.set_ylabel('Validation loss')\n        ax2.set_ylim(bottom=0)\n        plt.legend([train_loss_plot, validation_loss_plot],\n                   ['Train loss on last batch', 'Validation loss'])\n        ax.set_xlabel('Minibatches processed (=network updates)', color='black')\n\n    return draw_with_vars\n\n\ndef draw_ramachandran_plot(fig, plt, phi, psi):\n    def draw_with_vars():\n        ax = fig.gca()\n        plt.grid(True)\n        plt.title(\"Ramachandran plot\")\n        train_loss_plot, = ax.plot(phi, psi)\n        ax.set_ylabel('Psi')\n        ax.yaxis.labelpad = 0\n        plt.legend([train_loss_plot],\n                   ['Phi psi'])\n        ax.set_xlabel('Phi', color='black')\n\n    return draw_with_vars\n\n\ndef write_result_summary(accuracy):\n    output_string = globals().get(\"experiment_id\") + \": \" + str(accuracy) + \"\\n\"\n    with open(\"output/result_summary.txt\", \"a+\") as output_file:\n        output_file.write(output_string)\n        output_file.flush()\n    print(output_string, end=\"\")\n\n\ndef calculate_dihedral_angles_over_minibatch(atomic_coords_padded, batch_sizes, use_gpu):\n    angles = []\n    atomic_coords = atomic_coords_padded.transpose(0, 1)\n    for idx, _ in enumerate(batch_sizes):\n        angles.append(calculate_dihedral_angles(atomic_coords[idx][:batch_sizes[idx]], use_gpu))\n    return torch.nn.utils.rnn.pad_packed_sequence(\n        torch.nn.utils.rnn.pack_sequence(angles))\n\n\ndef protein_id_to_str(protein_id_list):\n    _aa_dict_inverse = {v: k for k, v in AA_ID_DICT.items()}\n    aa_list = []\n    for protein_id in protein_id_list:\n        aa_symbol = _aa_dict_inverse[int(protein_id)]\n        aa_list.append(aa_symbol)\n    return aa_list\n\n\ndef calculate_dihedral_angles(atomic_coords, use_gpu):\n    assert int(atomic_coords.shape[1]) == 9\n    atomic_coords = atomic_coords.contiguous().view(-1, 3)\n\n    zero_tensor = torch.tensor(0.0)\n    if use_gpu:\n        zero_tensor = zero_tensor.cuda()\n\n    dihedral_list = [zero_tensor, zero_tensor]\n    dihedral_list.extend(compute_dihedral_list(atomic_coords))\n    dihedral_list.append(zero_tensor)\n    angles = torch.tensor(dihedral_list).view(-1, 3)\n    return angles\n\n\ndef compute_dihedral_list(atomic_coords):\n    # atomic_coords is -1 x 3\n    ba = atomic_coords[1:] - atomic_coords[:-1]\n    ba /= ba.norm(dim=1).unsqueeze(1)\n    ba_neg = -1 * ba\n\n    n1_vec = torch.cross(ba[:-2], ba_neg[1:-1], dim=1)\n    n2_vec = torch.cross(ba_neg[1:-1], ba[2:], dim=1)\n    n1_vec /= n1_vec.norm(dim=1).unsqueeze(1)\n    n2_vec /= n2_vec.norm(dim=1).unsqueeze(1)\n\n    m1_vec = torch.cross(n1_vec, ba_neg[1:-1], dim=1)\n\n    x_value = torch.sum(n1_vec * n2_vec, dim=1)\n    y_value = torch.sum(m1_vec * n2_vec, dim=1)\n\n    return torch.atan2(y_value, x_value)\n\n\ndef get_structure_from_angles(aa_list_encoded, angles):\n    aa_list = protein_id_to_str(aa_list_encoded)\n    omega_list = angles[1:, 0]\n    phi_list = angles[1:, 1]\n    psi_list = angles[:-1, 2]\n    assert len(aa_list) == len(phi_list) + 1 == len(psi_list) + 1 == len(omega_list) + 1\n    structure = PeptideBuilder.make_structure(aa_list,\n                                              list(map(lambda x: math.degrees(x), phi_list)),\n                                              list(map(lambda x: math.degrees(x), psi_list)),\n                                              list(map(lambda x: math.degrees(x), omega_list)))\n    return structure\n\n\ndef write_to_pdb(structure, prot_id):\n    out = Bio.PDB.PDBIO()\n    out.set_structure(structure)\n    out.save(\"output/protein_\" + str(prot_id) + \".pdb\")\n\n\ndef calc_pairwise_distances(chain_a, chain_b, use_gpu):\n    distance_matrix = torch.Tensor(chain_a.size()[0], chain_b.size()[0]).type(torch.float)\n    # add small epsilon to avoid boundary issues\n    epsilon = 10 ** (-4) * torch.ones(chain_a.size(0), chain_b.size(0))\n    if use_gpu:\n        distance_matrix = distance_matrix.cuda()\n        epsilon = epsilon.cuda()\n\n    for idx, row in enumerate(chain_a.split(1)):\n        distance_matrix[idx] = torch.sum((row.expand_as(chain_b) - chain_b) ** 2, 1).view(1, -1)\n\n    return torch.sqrt(distance_matrix + epsilon)\n\n\ndef calc_drmsd(chain_a, chain_b, use_gpu=False):\n    assert len(chain_a) == len(chain_b)\n    distance_matrix_a = calc_pairwise_distances(chain_a, chain_a, use_gpu)\n    distance_matrix_b = calc_pairwise_distances(chain_b, chain_b, use_gpu)\n    return torch.norm(distance_matrix_a - distance_matrix_b, 2) \\\n           / math.sqrt((len(chain_a) * (len(chain_a) - 1)))\n\n\n# method for translating a point cloud to its center of mass\ndef transpose_atoms_to_center_of_mass(atoms_matrix):\n    # calculate com by summing x, y and z respectively\n    # and dividing by the number of points\n    center_of_mass = np.matrix([[atoms_matrix[0, :].sum() / atoms_matrix.shape[1]],\n                                [atoms_matrix[1, :].sum() / atoms_matrix.shape[1]],\n                                [atoms_matrix[2, :].sum() / atoms_matrix.shape[1]]])\n    # translate points to com and return\n    return atoms_matrix - center_of_mass\n\n\ndef calc_rmsd(chain_a, chain_b):\n    # move to center of mass\n    chain_a_value = chain_a.cpu().numpy().transpose()\n    chain_b_value = chain_b.cpu().numpy().transpose()\n    X = transpose_atoms_to_center_of_mass(chain_a_value)\n    Y = transpose_atoms_to_center_of_mass(chain_b_value)\n\n    R = Y * X.transpose()\n    # extract the singular values\n    _, S, _ = np.linalg.svd(R)\n    # compute RMSD using the formular\n    E0 = sum(list(np.linalg.norm(x) ** 2 for x in X.transpose())\n             + list(np.linalg.norm(x) ** 2 for x in Y.transpose()))\n    TraceS = sum(S)\n    RMSD = np.sqrt((1 / len(X.transpose())) * (E0 - 2 * TraceS))\n    return RMSD\n\n\ndef calc_angular_difference(values_1, values_2):\n    values_1 = values_1.transpose(0, 1).contiguous()\n    values_2 = values_2.transpose(0, 1).contiguous()\n    acc = 0\n    for idx, _ in enumerate(values_1):\n        assert values_1[idx].shape[1] == 3\n        assert values_2[idx].shape[1] == 3\n        a1_element = values_1[idx].view(-1, 1)\n        a2_element = values_2[idx].view(-1, 1)\n        acc += torch.sqrt(torch.mean(\n            torch.min(torch.abs(a2_element - a1_element),\n                      2 * math.pi - torch.abs(a2_element - a1_element)\n                      ) ** 2))\n    return acc / values_1.shape[0]\n\n\ndef structures_to_backbone_atoms_padded(structures):\n    backbone_atoms_list = []\n    for structure in structures:\n        backbone_atoms_list.append(structure_to_backbone_atoms(structure))\n    backbone_atoms_padded, batch_sizes_backbone = torch.nn.utils.rnn.pad_packed_sequence(\n        torch.nn.utils.rnn.pack_sequence(backbone_atoms_list))\n    return backbone_atoms_padded, batch_sizes_backbone\n\n\ndef structure_to_backbone_atoms(structure):\n    predicted_coords = []\n    for res in structure.get_residues():\n        predicted_coords.append(torch.Tensor(res[\"N\"].get_coord()))\n        predicted_coords.append(torch.Tensor(res[\"CA\"].get_coord()))\n        predicted_coords.append(torch.Tensor(res[\"C\"].get_coord()))\n    return torch.stack(predicted_coords).view(-1, 9)\n\n\ndef get_backbone_positions_from_angular_prediction(angular_emissions, batch_sizes, use_gpu):\n    # angular_emissions -1 x minibatch size x 3 (omega, phi, psi)\n    points = pnerf.dihedral_to_point(angular_emissions, use_gpu)\n    coordinates = pnerf.point_to_coordinate(points, use_gpu) / 100  # devide by 100 to angstrom unit\n    return coordinates.transpose(0, 1).contiguous()\\\n               .view(len(batch_sizes), -1, 9).transpose(0, 1), batch_sizes\n\n\ndef calc_avg_drmsd_over_minibatch(backbone_atoms_padded, actual_coords_padded, batch_sizes):\n    backbone_atoms_list = list(\n        [backbone_atoms_padded[:batch_sizes[i], i] for i in range(int(backbone_atoms_padded\n                                                                      .size(1)))])\n    actual_coords_list = list(\n        [actual_coords_padded[:batch_sizes[i], i] for i in range(int(actual_coords_padded\n                                                                     .size(1)))])\n    drmsd_avg = 0\n    for idx, backbone_atoms in enumerate(backbone_atoms_list):\n        actual_coords = actual_coords_list[idx].transpose(0, 1).contiguous().view(-1, 3)\n        drmsd_avg += calc_drmsd(backbone_atoms.transpose(0, 1).contiguous().view(-1, 3),\n                                actual_coords)\n    return drmsd_avg / len(backbone_atoms_list)\n\n\ndef encode_primary_string(primary):\n    return list([AA_ID_DICT[aa] for aa in primary])\n\n\ndef initial_pos_from_aa_string(batch_aa_string):\n    structures = []\n    for aa_string in batch_aa_string:\n        structure = get_structure_from_angles(aa_string,\n                                              np.repeat([-120], len(aa_string) - 1),\n                                              np.repeat([140], len(aa_string) - 1),\n                                              np.repeat([-370], len(aa_string) - 1))\n        structures.append(structure)\n    return structures\n\n\ndef pass_messages(aa_features, message_transformation, use_gpu):\n    # aa_features (#aa, #features) - each row represents the amino acid type\n    # (embedding) and the positions of the backbone atoms\n    # message_transformation: (-1 * 2 * feature_size) -> (-1 * output message size)\n    feature_size = aa_features.size(1)\n    aa_count = aa_features.size(0)\n    eye = torch.eye(aa_count, dtype=torch.uint8).view(-1).expand(2, feature_size, -1)\\\n        .transpose(1, 2).transpose(0, 1)\n    eye_inverted = torch.ones(eye.size(), dtype=torch.uint8) - eye\n    if use_gpu:\n        eye_inverted = eye_inverted.cuda()\n    features_repeated = aa_features.repeat((aa_count, 1)).view((aa_count, aa_count, feature_size))\n    # (aa_count^2 - aa_count) x 2 x aa_features     (all pairs except for reflexive connections)\n    aa_messages = torch.stack((features_repeated.transpose(0, 1), features_repeated))\\\n        .transpose(0, 1).transpose(1, 2).view(-1, 2, feature_size)\n    aa_msg_pairs = torch.masked_select(aa_messages, eye_inverted).view(-1, 2, feature_size)\n    transformed = message_transformation(aa_msg_pairs).view(aa_count, aa_count - 1, -1)\n    transformed_sum = transformed.sum(dim=1)  # aa_count x output message size\n    return transformed_sum\n\n\ndef load_model_from_disk(path, force_cpu=True):\n    if force_cpu:\n        # load model with map_location set to storage (main mem)\n        model = torch.load(path, map_location=lambda storage, loc: storage)\n        # flattern parameters in memory\n        model.flatten_parameters()\n        # update internal state accordingly\n        model.use_gpu = False\n    else:\n        # load model using default map_location\n        model = torch.load(path)\n        model.flatten_parameters()\n    return model\n", "meta": {"hexsha": "fb727f41d80699fb5591a42587fc6689bd8e10cb", "size": 14391, "ext": "py", "lang": "Python", "max_stars_repo_path": "util.py", "max_stars_repo_name": "biokvantz/openprotein", "max_stars_repo_head_hexsha": "d88d9c43ba8e382a518929da6f3d1e9281a11f75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "util.py", "max_issues_repo_name": "biokvantz/openprotein", "max_issues_repo_head_hexsha": "d88d9c43ba8e382a518929da6f3d1e9281a11f75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util.py", "max_forks_repo_name": "biokvantz/openprotein", "max_forks_repo_head_hexsha": "d88d9c43ba8e382a518929da6f3d1e9281a11f75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4273972603, "max_line_length": 100, "alphanum_fraction": 0.6507539434, "include": true, "reason": "import numpy", "num_tokens": 3616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.1735490427780156}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nPython wrapper around the C extension for the theoretical 3-D\nreal-space correlation function, :math:`\\\\xi(r)`. Corresponding\nC routines are in ``theory/xi/``, python interface is\n:py:mod:`Corrfunc.theory.xi`.\n\"\"\"\n\nfrom __future__ import (division, print_function, absolute_import,\n                        unicode_literals)\n\n__author__ = ('Manodeep Sinha')\n__all__ = ('xi',)\n\n\ndef xi(boxsize, nthreads, binfile, X, Y, Z,\n       weights=None, weight_type=None, verbose=False, output_ravg=False,\n       xbin_refine_factor=2, ybin_refine_factor=2,\n       zbin_refine_factor=1, max_cells_per_dim=100,\n       copy_particles=True, enable_min_sep_opt=True,\n       c_api_timer=False, isa='fastest', bin_type='custom', attrs_pair_weights=None):\n    \"\"\"\n    Function to compute the projected correlation function in a\n    periodic cosmological box. Pairs which are separated by less\n    than the ``r`` bins (specified in ``binfile``) in 3-D real space.\n\n    If ``weights`` are provided, the resulting correlation function\n    is weighted.  The weighting scheme depends on ``weight_type``.\n\n\n    .. note:: Pairs are double-counted. And if ``rmin`` is set to\n        0.0, then all the self-pairs (i'th particle with itself) are\n        added to the first bin => minimum number of pairs in the first bin\n        is the total number of particles.\n\n\n    Parameters\n    ----------\n    boxsize : double\n        A double-precision value for the boxsize of the simulation\n        in same units as the particle positions and the ``r`` bins.\n\n    nthreads : integer\n        Number of threads to use.\n\n    binfile : string or an list/array of floats\n        For string input: filename specifying the ``r`` bins for\n        ``xi``. The file should contain white-space separated values\n        of (rmin, rmax)  for each ``r`` wanted. The bins need to be\n        contiguous and sorted in increasing order (smallest bins come first).\n\n        For array-like input: A sequence of ``r`` values that provides the\n        bin-edges. For example,\n        ``np.logspace(np.log10(0.1), np.log10(10.0), 15)`` is a valid\n        input specifying **14** (logarithmic) bins between 0.1 and 10.0. This\n        array does not need to be sorted.\n\n    X/Y/Z : arraytype, real (float/double)\n        Particle positions in the 3 axes. Must be within [0, boxsize]\n        and specified in the same units as ``rp_bins`` and boxsize. All\n        3 arrays must be of the same floating-point type.\n\n        Calculations will be done in the same precision as these arrays,\n        i.e., calculations will be in floating point if XYZ are single\n        precision arrays (C float type); or in double-precision if XYZ\n        are double precision arrays (C double type).\n\n    weights : array_like, real (float/double), optional\n        A scalar, or an array of weights of shape (n_weights, n_positions) or\n        (n_positions,). ``weight_type`` specifies how these weights are used;\n        results are returned in the ``weightavg`` field.\n\n    verbose : boolean (default false)\n        Boolean flag to control output of informational messages\n\n    output_ravg : boolean (default false)\n        Boolean flag to output the average ``r`` for each bin. Code will\n        run slower if you set this flag.\n\n        Note: If you are calculating in single-precision, ``rpavg`` will\n        suffer from numerical loss of precision and can not be trusted. If\n        you need accurate ``rpavg`` values, then pass in double precision\n        arrays for the particle positions.\n\n    (xyz)bin_refine_factor : integer, default is (2,2,1); typically within [1-3]\n        Controls the refinement on the cell sizes. Can have up to a 20% impact\n        on runtime.\n\n    max_cells_per_dim : integer, default is 100, typical values in [50-300]\n        Controls the maximum number of cells per dimension. Total number of\n        cells can be up to (max_cells_per_dim)^3. Only increase if ``rmax`` is\n        too small relative to the boxsize (and increasing helps the runtime).\n\n    copy_particles : boolean (default True)\n        Boolean flag to make a copy of the particle positions\n        If set to False, the particles will be re-ordered in-place\n\n        .. versionadded:: 2.3.0\n\n    enable_min_sep_opt : boolean (default true)\n        Boolean flag to allow optimizations based on min. separation between\n        pairs of cells. Here to allow for comparison studies.\n\n        .. versionadded:: 2.3.0\n\n    c_api_timer : boolean (default false)\n        Boolean flag to measure actual time spent in the C libraries. Here\n        to allow for benchmarking and scaling studies.\n\n    isa : string (default ``fastest``)\n        Controls the runtime dispatch for the instruction set to use. Options\n        are: [``fastest``, ``avx512f``, ``avx``, ``sse42``, ``fallback``]\n\n        Setting isa to ``fastest`` will pick the fastest available instruction\n        set on the current computer. However, if you set ``isa`` to, say,\n        ``avx`` and ``avx`` is not available on the computer, then the code\n        will revert to using ``fallback`` (even though ``sse42`` might be\n        available).  Unless you are benchmarking the different instruction\n        sets, you should always leave ``isa`` to the default value. And if\n        you *are* benchmarking, then the string supplied here gets translated\n        into an ``enum`` for the instruction set defined in ``utils/defs.h``.\n\n    weight_type : string, optional, Default: None.\n        The type of weighting to apply. One of [\"pair_product\", None].\n\n    bin_type : string, case-insensitive (default ``custom``)\n        Set to ``lin`` for speed-up in case of linearly-spaced bins.\n        In this case, the bin number for a pair separated by ``r`` is given by\n        ``(r - binfile[0])/(binfile[-1] - binfile[0])*(len(binfile) - 1)``,\n        i.e. only the first and last bins of input ``binfile`` are considered.\n        Then setting ``output_ravg`` is virtually costless.\n        For non-linear binning, set to ``custom``.\n        In the vast majority of cases, bin_type='linear' will yield identical\n        results to custom linear binning but with higher performance.\n        In a few rare cases where a pair falls on a bin boundary,\n        'linear' and custom linear may disagree on which bin the pair falls into\n        due to finite floating point precision.\n        ``auto`` will choose linear binning if input ``binfile`` is within\n        ``rtol = 1e-05`` *and* ``atol = 1e-08`` (relative and absolute tolerance)\n        of ``np.linspace(binfile[0], binfile[-1], len(binfile))``.\n\n    pair_weights : array-like, optional. Default: None.\n        Array of pair weights.\n\n    sep_pair_weights : array-like, optional. Default: None.\n        Array of separations corresponding to ``pair_weights``.\n\n    attrs_pair_weights : tuple. Default: None.\n        Attributes for pair weights; in case ``weight_type`` is \"inverse_bitwise\",\n        the tuple of (offset to be added to the bitwise counts,\n        default weight value if denominator is zero).\n\n    Returns\n    -------\n    results : Numpy structured array\n        A numpy structured array containing [rmin, rmax, ravg, xi, npairs,\n        weightavg] for each radial specified in the ``binfile``. If\n        ``output_ravg`` is not set then ``ravg`` will be set to 0.0 for all\n        bins; similarly for ``weightavg``. ``xi`` contains the correlation\n        function while ``npairs`` contains the number of pairs in that bin.\n        If using weights, ``xi`` will be weighted while ``npairs`` will not be.\n\n    api_time : float, optional\n        Only returned if ``c_api_timer`` is set.  ``api_time`` measures only\n        the time spent within the C library and ignores all python overhead.\n\n    Example\n    -------\n    >>> from __future__ import print_function\n    >>> import numpy as np\n    >>> from os.path import dirname, abspath, join as pjoin\n    >>> import Corrfunc\n    >>> from Corrfunc.theory.xi import xi\n    >>> binfile = pjoin(dirname(abspath(Corrfunc.__file__)),\n    ...                 \"../theory/tests/\", \"bins\")\n    >>> N = 100000\n    >>> boxsize = 420.0\n    >>> nthreads = 4\n    >>> seed = 42\n    >>> np.random.seed(seed)\n    >>> X = np.random.uniform(0, boxsize, N)\n    >>> Y = np.random.uniform(0, boxsize, N)\n    >>> Z = np.random.uniform(0, boxsize, N)\n    >>> weights = np.ones_like(X)\n    >>> results = xi(boxsize, nthreads, binfile, X, Y, Z, weights=weights, weight_type='pair_product', output_ravg=True)\n    >>> for r in results: print(\"{0:10.6f} {1:10.6f} {2:10.6f} {3:10.6f} {4:10d} {5:10.6f}\"\n    ...                         .format(r['rmin'], r['rmax'],\n    ...                         r['ravg'], r['xi'], r['npairs'], r['weightavg']))\n    ...                   # doctest: +NORMALIZE_WHITESPACE\n      0.167536   0.238755   0.226592  -0.205733          4   1.000000\n      0.238755   0.340251   0.289277  -0.176729         12   1.000000\n      0.340251   0.484892   0.426819  -0.051829         40   1.000000\n      0.484892   0.691021   0.596187  -0.131853        106   1.000000\n      0.691021   0.984777   0.850100  -0.049207        336   1.000000\n      0.984777   1.403410   1.225112   0.028543       1052   1.000000\n      1.403410   2.000000   1.737153   0.011403       2994   1.000000\n      2.000000   2.850200   2.474588   0.005405       8614   1.000000\n      2.850200   4.061840   3.532018  -0.014098      24448   1.000000\n      4.061840   5.788530   5.022241  -0.010784      70996   1.000000\n      5.788530   8.249250   7.160648  -0.001588     207392   1.000000\n      8.249250  11.756000  10.207213  -0.000323     601002   1.000000\n     11.756000  16.753600  14.541171   0.000007    1740084   1.000000\n     16.753600  23.875500  20.728773  -0.001595    5028058   1.000000\n\n    \"\"\"\n\n    try:\n        from Corrfunc._countpairs import countpairs_xi as xi_extn\n    except ImportError:\n        msg = \"Could not import the C extension for the projected \"\\\n              \"correlation function.\"\n        raise ImportError(msg)\n\n    import numpy as np\n    from future.utils import bytes_to_native_str\n    from Corrfunc.utils import translate_isa_string_to_enum, translate_bin_type_string_to_enum,\\\n        get_edges, convert_to_native_endian,\\\n        sys_pipes, process_weights\n\n    weights, _ = process_weights(weights, None, X, None, weight_type, autocorr=True)\n\n    # Ensure all input arrays are native endian\n    X, Y, Z = [convert_to_native_endian(arr, warn=False)\n                        for arr in [X, Y, Z]]\n\n    if weights is not None:\n        weights = [convert_to_native_endian(arr, warn=False) for arr in weights]\n\n    # Passing None parameters breaks the parsing code, so avoid this\n    kwargs = {}\n    for k in ['weights', 'weight_type', 'attrs_pair_weights']:\n        v = locals()[k]\n        if v is not None:\n            kwargs[k] = v\n\n    integer_isa = translate_isa_string_to_enum(isa)\n    integer_bin_type = translate_bin_type_string_to_enum(bin_type)\n    rbinfile = get_edges(binfile)\n    with sys_pipes():\n      extn_results = xi_extn(boxsize, nthreads, rbinfile,\n                             X, Y, Z,\n                             verbose=verbose,\n                             output_ravg=output_ravg,\n                             xbin_refine_factor=xbin_refine_factor,\n                             ybin_refine_factor=ybin_refine_factor,\n                             zbin_refine_factor=zbin_refine_factor,\n                             max_cells_per_dim=max_cells_per_dim,\n                             copy_particles=copy_particles,\n                             enable_min_sep_opt=enable_min_sep_opt,\n                             c_api_timer=c_api_timer,\n                             isa=integer_isa,\n                             bin_type=integer_bin_type, **kwargs)\n    if extn_results is None:\n        msg = \"RuntimeError occurred\"\n        raise RuntimeError(msg)\n    else:\n        extn_results, api_time = extn_results\n\n    results_dtype = np.dtype([(bytes_to_native_str(b'rmin'), np.float64),\n                              (bytes_to_native_str(b'rmax'), np.float64),\n                              (bytes_to_native_str(b'ravg'), np.float64),\n                              (bytes_to_native_str(b'xi'), np.float64),\n                              (bytes_to_native_str(b'npairs'), np.uint64),\n                              (bytes_to_native_str(b'weightavg'), np.float64)])\n    results = np.array(extn_results, dtype=results_dtype)\n\n    if not c_api_timer:\n        return results\n    else:\n        return results, api_time\n\n\nif __name__ == '__main__':\n    import doctest\n    doctest.testmod()\n", "meta": {"hexsha": "be16bdcbc9ae4d01b6dbe9627f7fdbbd20bacd73", "size": 12631, "ext": "py", "lang": "Python", "max_stars_repo_path": "Corrfunc/theory/xi.py", "max_stars_repo_name": "adematti/Corrfunc", "max_stars_repo_head_hexsha": "5402d2e63b3e1f56d9c61fdf799d1d19f1fca1a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Corrfunc/theory/xi.py", "max_issues_repo_name": "adematti/Corrfunc", "max_issues_repo_head_hexsha": "5402d2e63b3e1f56d9c61fdf799d1d19f1fca1a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-29T03:02:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-08T02:33:25.000Z", "max_forks_repo_path": "Corrfunc/theory/xi.py", "max_forks_repo_name": "adematti/Corrfunc", "max_forks_repo_head_hexsha": "5402d2e63b3e1f56d9c61fdf799d1d19f1fca1a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.4352517986, "max_line_length": 120, "alphanum_fraction": 0.6301955506, "include": true, "reason": "import numpy", "num_tokens": 3273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.3242353989809524, "lm_q1q2_score": 0.1734978573075064}}
{"text": "# Copyright (c) 2015, Andrew Delong and Babak Alipanahi All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without modification,\n# are permitted provided that the following conditions are met:\n# \n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n# \n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation and/or\n# other materials provided with the distribution.\n# \n# 3. Neither the name of the copyright holder nor the names of its contributors\n# may be used to endorse or promote products derived from this software without\n# specific prior written permission.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# \n# Author's note: \n#     This file was distributed as part of the Nature Biotechnology \n#     supplementary software release for DeepBind. Users of DeepBind\n#     are encouraged to instead use the latest source code and binaries \n#     for scoring sequences at\n#        http://tools.genes.toronto.edu/deepbind/\n# \nimport sys, os\nimport numpy as np\nimport argparse\nfrom smat import *\n\n#os.environ[\"PYTHONUNBUFFERED\"] = \"1\"  # Disable output buffering\nsys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)\n\nparser = argparse.ArgumentParser(description=\"Train a convolutional neural net on MNIST and print out the error rates.\")\nparser.add_argument(\"--device\",type=int,default=None,help=\"Device # to use (which GPU). Default is 0.\")\nparser.add_argument(\"--show_filters\",action=\"store_true\",default=False,help=\"Plot the filters after each update, showing in a popup window.\")\nparser.add_argument(\"--f64\",action=\"store_true\",default=False,help=\"Use float64, if supported by the GPU. Default is float32.\")\nargs = parser.parse_args()\n\nif args.device is not None:\n    set_backend_options(device=args.device)\n\ndt = float64 if args.f64 else float32\nset_default_dtype(dt)\n\nprint \"Using device\", get_backend_info().device\nprint \"Checking cuDNN ...\",\ntry:    cudnn_dll()\nexcept: quit(\"Failed to load cuDNN shared library. Quitting.\");\nprint \"OK.\"\n\n##############################################################################\n#  Functions for loading DATA\n##############################################################################\n\n# Load a data as of pairs (X,Y) where:\n#    X is a (batchsize x inputsize) matrix of inputs\n#    Y is a (batchsize x outputsize) matrix of corresponding targets\n#  MNIST has 60000 training examples total.\nwith np.load(\"data/mnist/mnist_train.npz\") as mnist_file:\n    inputs_train  = asarray(mnist_file['X'], dtype=dt)/255   # Load 60000 x 784 matrix of training inputs, scaled to range [0,1]\n    targets_train = asarray(mnist_file['Y'], dtype=dt)       # Load 60000 x 10 matrix of training targets\n\nwith np.load(\"data/mnist/mnist_test.npz\") as mnist_file:\n    inputs_test  = asarray(mnist_file['X'], dtype=dt)/255    # Load 10000 x 784 matrix of testing inputs, scaled to range [0,1]\n    targets_test = asarray(mnist_file['Y'], dtype=dt)        # Load 10000 x 10 matrix of testing targets\n\n# Generate minibatches out of the full dataset.\ntrainsize = len(inputs_train)\ntestsize  = len(inputs_test)\nbatchsize = 100            ; assert trainsize % batchsize == 0 # Make sure we use all training examples\nbatches_train = [(inputs_train[i:i+batchsize], targets_train[i:i+batchsize]) for i in range(0, trainsize, batchsize)]\nbatches_test  = [(inputs_test [i:i+batchsize], targets_test [i:i+batchsize]) for i in range(0, testsize,  batchsize)]\n\n##############################################################################\n#  CONVNET CONFIGURATION\n##############################################################################\n\n# Configuration of neural net layers (number of filters, hidden units, etc)\ninput_w = 28          # Width  of MNIST image\ninput_h = 28          # Height of MNIST image\ninput_c = 1           # Number of input channels for MNIST\n\n# Layer 1 is convolution, so call it C1\nC1_filter_c = 32  # Number of filters in C1\nC1_filter_w = 5   # Width  of filters in C1\nC1_filter_h = 5   # Height of filters in C1\nC1_stride   = 1   # Stride of C1\nC1_w = (input_w-C1_filter_w)//C1_stride + 1  # Width  of C1 output featuremap\nC1_h = (input_h-C1_filter_h)//C1_stride + 1  # Height of C1 output featuremap\n\n# Layer 2 is pooling, so call it P1\nP1_mode = \"max\"   # Pooling type (\"max\" or \"avg\")\nP1_window_w = 3   # Width  of pooling windows in P1\nP1_window_h = 3   # Height of pooling windows in P1\nP1_stride   = 2   # Stride of P1\nP1_w = (C1_w-P1_window_w)//P1_stride + 1  # Width  of P1 output featuremap\nP1_h = (C1_h-P1_window_h)//P1_stride + 1  # Height of P1 output featuremap\n\n# Layer 3 is fully connected, so call it F1\nF1_size = 1000         # Number of neurons in F1\nF1_dropout_rate = 0.5  # Dropout rate for F1\n\n# Layer 4 is fully connected softmax, so call it F2\nF2_size = 10      # 10 classes representing digits 0..9\n\n##############################################################################\n#  CONVNET PARAMETER ALLOCATION and INITIALIZATION\n##############################################################################\n\n# Count how many parameters there are in total for each later,\n# so that we can allocate one big vector P for all parameters\nnum_params = { 'C1_weights' : C1_filter_c*C1_filter_w*C1_filter_h * (input_c),\n               'C1_bias'    : C1_filter_c,\n               'F1_weights' : F1_size * (C1_filter_c*P1_w*P1_h),\n               'F1_bias'    : F1_size,\n               'F2_weights' : F2_size * (F1_size),\n               'F2_bias'    : F2_size }\nnum_params_total = sum(num_params.values())\nP = zeros(num_params_total, dt)\nP_grad = zeros_like(P)\n\n# Slice the param vector P into parameters for each layer.\n_ = 0  # temp counter\nC1_weights = P[_:_+num_params['C1_weights']].reshape((C1_filter_c,  input_c*C1_filter_h*C1_filter_w)); _ += C1_weights.size;\nC1_bias    = P[_:_+num_params['C1_bias'   ]];                                                          _ += C1_bias.size;\nF1_weights = P[_:_+num_params['F1_weights']].reshape((C1_filter_c*P1_w*P1_h, F1_size));                _ += F1_weights.size;\nF1_bias    = P[_:_+num_params['F1_bias'   ]].reshape((1,         F1_size));                            _ += F1_bias.size;\nF2_weights = P[_:_+num_params['F2_weights']].reshape((F1_size,   F2_size));                            _ += F2_weights.size;\nF2_bias    = P[_:_+num_params['F2_bias'   ]].reshape((1,         F2_size));                            _ += F2_bias.size;\nassert _ == num_params_total\n\n# Slice the gradient vector P_grad into parameters for each layer.\n_ = 0\nC1_weights_grad = P_grad[_:_+num_params['C1_weights']].reshape((C1_filter_c,  input_c*C1_filter_h*C1_filter_w)); _ += C1_weights_grad.size;\nC1_bias_grad    = P_grad[_:_+num_params['C1_bias'   ]];                                                          _ += C1_bias_grad.size;\nF1_weights_grad = P_grad[_:_+num_params['F1_weights']].reshape((C1_filter_c*P1_w*P1_h, F1_size));                _ += F1_weights_grad.size;\nF1_bias_grad    = P_grad[_:_+num_params['F1_bias'   ]].reshape((1,         F1_size));                            _ += F1_bias_grad.size;\nF2_weights_grad = P_grad[_:_+num_params['F2_weights']].reshape((F1_size,   F2_size));                            _ += F2_weights_grad.size;\nF2_bias_grad    = P_grad[_:_+num_params['F2_bias'   ]].reshape((1,         F2_size));                            _ += F2_bias_grad.size;\nassert _ == num_params_total\n\n# Initialize parameters in P for each layer with a different random scale.\ndef set_rand(target, scale):\n    target.ravel()[:] = randn(target.size) * scale\nset_rand(C1_weights, 0.01);    C1_bias += 0.0001;    # Initialize biases as small positive values\nset_rand(F1_weights, 0.01);    F1_bias += 0.0001;\nset_rand(F2_weights, 0.01);\n\n##############################################################################\n#  CONVNET FORWARDPROP / BACKPROP\n##############################################################################\n\n# Send input mini-batch through our convnet.\n# Returns final outputs and, if targets are given, returns gradients as well.\ndef eval_convnet(inputs, targets=None):\n\n    # Network parameters stored in global variables, for simplicity of this demo\n    global C1_weights, C1_bias\n    global F1_weights, F1_bias\n    global F2_weights, F2_bias\n\n    # Gradients of parameters also stored in global variables, for simplicity\n    global C1_weights_grad, C1_bias_grad\n    global F1_weights_grad, F1_bias_grad\n    global F2_weights_grad, F2_bias_grad\n    \n    # Forward propagate C1\n    C1_hidden = relu(conv2(inputs, input_w, input_h, C1_weights, C1_filter_w, C1_filter_h, bias=C1_bias, stride=C1_stride))\n\n    # Forward propagate P1\n    P1_hidden = pool2(P1_mode, C1_hidden, C1_w, C1_h, P1_window_w, P1_window_h, stride=P1_stride)\n\n    # Forward propagate F1\n    F1_hidden = relu(dot(P1_hidden, F1_weights) + F1_bias)\n    F1_hidden, F1_mask = dropout(F1_hidden, F1_dropout_rate, test_mode=(targets is None))\n\n    # Forward propagate F2\n    F2_hidden = softmax(dot(F1_hidden, F2_weights) + F2_bias)\n\n    # If no targets provided (no gradient requested), just return the predictions of final layer\n    if targets is None:\n        return F2_hidden\n\n    # Compute residuals\n    F2_delta = F2_hidden - targets\n\n    # Backward propagate F2_delta\n    F2_bias_grad[:] = sum(F2_delta, axis=0)\n    F2_weights_grad[:] = dot_tn(F1_hidden, F2_delta)\n    F1_delta = dot_nt(F2_delta, F2_weights)\n\n    # Backward propagate F1_delta\n    F1_delta = dropout_grad(F1_delta, F1_mask)  # Backprop through dropout after F1 layer\n    F1_delta *= relu_grad(F1_hidden)            # Backprop through relu after F1 layer\n    F1_bias_grad[:] = sum(F1_delta, axis=0)\n    F1_weights_grad[:] = dot_tn(P1_hidden, F1_delta)\n    P1_delta = dot_nt(F1_delta, F1_weights)\n\n    # Backward propagate P1_delta\n    C1_delta = pool2_grad(P1_mode, C1_hidden, C1_w, C1_h, P1_window_w, P1_window_h, P1_hidden, P1_delta, stride=P1_stride)\n\n    # Backward propagate C1_delta\n    C1_delta *= relu_grad(C1_hidden)  # Backprop through relu after C1 layer\n    conv2_biasgrad(C1_bias, C1_delta, C1_bias_grad)\n    conv2_filtersgrad(inputs, input_w, input_h, C1_filter_w, C1_filter_h, C1_delta, C1_weights_grad, stride=C1_stride)\n\n##############################################################################\n#  Functions for PRINTING\n##############################################################################\n\ndef make_filter_grid(filter_weights, filter_w, filter_h, max_cols=8):\n    \n    # Determine the range [-vmin, vmax] to map to [0, 255]\n    vmin = float(filter_weights.min())\n    vmax = float(filter_weights.max())\n    vmax, vmin = max(vmax, -vmin), min(-vmax, vmin)\n\n    # Scale all filters to range [0, 255] and reshape to a single (n, width, height) array\n    images = ((filter_weights.asnumpy() - vmin) / (vmax - vmin) * 255).astype(np.uint8).reshape((-1, filter_h, filter_w))\n    n = len(images)\n\n    # Create a big image to store the filters, then copy each filter into its slot in the grid\n    num_cols = min(n, max_cols)\n    num_rows = (n + num_cols - 1) // num_cols\n    grid = np.zeros((num_rows*(filter_h+1)+1, num_cols*(filter_w+1)+1), np.uint8)\n    for col in range(num_cols):\n        for row in range(num_rows):\n            i = row*num_cols + col\n            if i < len(images):\n                grid[1+row*(filter_h+1):(row+1)*(filter_h+1),\n                     1+col*(filter_w+1):(col+1)*(filter_w+1)] = images[i]\n\n    return grid\n\n\ndef error_rate(batches):\n    predictions = np.vstack([eval_convnet(inputs).asnumpy() for inputs, targets in batches])\n    targets     = np.vstack([targets.asnumpy()              for inputs, targets in batches])\n    num_errors  = np.sum( predictions[np.where(targets==1)] != predictions.max(axis=1) )\n    return 100.*num_errors/len(predictions)\n\n\nfilter_plot_img = None   # Global variable to hold reference to the filter image currently being plotted in a pyplot window\ndef plot_filter_grid():\n    global filter_plot_img\n    import matplotlib.pyplot as plt\n    import matplotlib.cm as cm\n\n    filter_grid = make_filter_grid(C1_weights, C1_filter_w, C1_filter_h)\n    if filter_plot_img is None:\n        # The first time we plot the filters, use imshow and pop up a new window\n        filter_plot_img = plt.imshow(filter_grid, cmap=cm.Greys_r, interpolation=\"NEAREST\")\n        plt.show(block=False)\n    else:\n        # When we want to just update the filters, replace the data and give pyplot event loop a chance to draw\n        filter_plot_img.set_data(filter_grid)\n        plt.pause(0.001)\n\n\ndef print_status(epoch=None):\n    update_interval = 5\n    if epoch is not None:\n        print \".\",\n    if epoch is None or (epoch+1) % update_interval == 0:  # Only print status every 5 epochs.\n        time_per_epoch = toc() / update_interval\n        train_error = error_rate(batches_train)\n        test_error  = error_rate(batches_test)\n        status_msg = \"start\" if epoch is None else (\"epoch[%d]\"% (epoch+1))\n        time_msg   = \"(%.2fs/epoch)\" % time_per_epoch if epoch is not None else \"\"\n        print \"\\n%s: %.2f%% train err, %.2f%% test err %s \" % (status_msg, train_error, test_error, time_msg),\n        if args.show_filters:\n            plot_filter_grid()\n        tic()\n\ntic()\nprint_status()\n\n##############################################################################\n#  SGD TRAINING LOOP\n##############################################################################\n\n# Parameters of SGD training\nnum_epoch  = 50\nlearn_rate = 0.02\nmomentum   = 0.90\n\n# Allocate array to store momentum of every parameter; updated during training\nP_momentum = zeros_like(P)\n\ntic(\"training time\")\n\n# Start training!\nfor epoch in range(num_epoch):\n\n    for inputs, targets in batches_train:\n\n        # Generate compute per-layer gradient based on targets\n        eval_convnet(inputs, targets)\n\n        # Gradient step with very basic momentum\n        P_grad *= -learn_rate/batchsize\n        P_momentum *= momentum\n        P_momentum += P_grad\n        P += P_momentum\n\n    # Print current classification error on training data\n    print_status(epoch)\n    \nprint \"\\nTotal training time = %.1fs\" % toc(\"training time\")\n", "meta": {"hexsha": "fe1d17b38ac2c1abd4357070a82cbf5cfdd21eac", "size": 14979, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/libs/smat/py/demo_convnet.py", "max_stars_repo_name": "gifford-lab/deepbind-docker", "max_stars_repo_head_hexsha": "9a6e48d3ee550cc8c7bf06173a78442a6ba10ac8", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2016-03-07T04:05:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-04T17:04:14.000Z", "max_issues_repo_path": "code/libs/smat/py/demo_convnet.py", "max_issues_repo_name": "gifford-lab/deepbind-docker", "max_issues_repo_head_hexsha": "9a6e48d3ee550cc8c7bf06173a78442a6ba10ac8", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-07-04T15:53:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-06T03:01:47.000Z", "max_forks_repo_path": "code/libs/smat/py/demo_convnet.py", "max_forks_repo_name": "gifford-lab/deepbind-docker", "max_forks_repo_head_hexsha": "9a6e48d3ee550cc8c7bf06173a78442a6ba10ac8", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-06-18T18:51:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-06T19:33:29.000Z", "avg_line_length": 46.809375, "max_line_length": 141, "alphanum_fraction": 0.6498431137, "include": true, "reason": "import numpy", "num_tokens": 3816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.1734978559939649}}
{"text": "# Copyright 2022 The TEMPO Collaboration\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nModule for the process tensor time evolving matrix product operator algorithm\n(PT-TEMPO). This module is based on [Strathearn2018], [Pollock2018],\n[Jorgensen2019], and [Fux2021].\n\n**[Strathearn2018]**\nA. Strathearn, P. Kirton, D. Kilda, J. Keeling and\nB. W. Lovett,  *Efficient non-Markovian quantum dynamics using\ntime-evolving matrix product operators*, Nat. Commun. 9, 3322 (2018).\n\n**[Pollock2018]**\nF.  A.  Pollock,  C.  Rodriguez-Rosario,  T.  Frauenheim,\nM. Paternostro, and K. Modi, *Non-Markovian quantumprocesses: Complete\nframework and efficient characterization*, Phys. Rev. A 97, 012127 (2018).\n\n**[Jorgensen2019]**\nM. R. Jørgensen and F. A. Pollock, *Exploiting the causal tensor network\nstructure of quantum processes to efficiently simulate non-markovian path\nintegrals*, Phys. Rev. Lett. 123, 240602 (2019)\n\n**[Fux2021]**\nG. E. Fux, E. Butler, P. R. Eastham, B. W. Lovett, and\nJ. Keeling, *Efficient exploration of Hamiltonian parameter space for\noptimal control of non-Markovian open quantum systems*, Phys. Rev. Lett. 126,\n200401 (2021).\n\"\"\"\n\nfrom typing import Dict, Optional, Text, Union\nfrom copy import copy\n\nimport numpy as np\n\nfrom oqupy.base_api import BaseAPIClass\nfrom oqupy.bath import Bath\nfrom oqupy.config import PT_DEFAULT_TOLERANCE\nfrom oqupy.config import PT_TEMPO_BACKEND_CONFIG\nfrom oqupy.process_tensor import BaseProcessTensor\nfrom oqupy.process_tensor import SimpleProcessTensor\nfrom oqupy.process_tensor import FileProcessTensor\nfrom oqupy.tempo.backends.pt_tempo_backend import PtTempoBackend\nfrom oqupy.tempo.tempo import TempoParameters\nfrom oqupy.tempo.tempo import guess_tempo_parameters\nfrom oqupy.tempo.tempo import influence_matrix\nfrom oqupy.operators import commutator, acommutator\nfrom oqupy.operators import left_right_super\nfrom oqupy.util import get_progress\n\n\nPT_CLASS = {\"simple\": SimpleProcessTensor}\n\n\n\nclass PtTempo(BaseAPIClass):\n    \"\"\"\n    Class to facilitate a PT-TEMPO computation.\n\n    Parameters\n    ----------\n    bath: Bath\n        The Bath (includes the coupling operator to the system).\n    parameters: TempoParameters\n        The parameters for the PT-TEMPO computation.\n    start_time: float\n        The start time.\n    backend_config: dict (default = None)\n        The configuration of the backend. If `backend_config` is\n        ``None`` then the default backend configuration is used.\n    name: str (default = None)\n        An optional name for the tempo object.\n    description: str (default = None)\n        An optional description of the tempo object.\n    \"\"\"\n    def __init__(\n            self,\n            bath: Bath,\n            start_time: float,\n            end_time: float,\n            parameters: TempoParameters,\n            process_tensor_file: Optional[Union[Text, bool]] = None,\n            overwrite: Optional[bool] = False,\n            backend_config: Optional[Dict] = None,\n            name: Optional[Text] = None,\n            description: Optional[Text] = None) -> None:\n        \"\"\"Create a PtTempo object. \"\"\"\n        assert isinstance(bath, Bath), \\\n            \"Argument 'bath' must be an instance of Bath.\"\n        self._bath = bath\n        self._dimension = self._bath.dimension\n        self._correlations = self._bath.correlations\n\n        try:\n            tmp_start_time = float(start_time)\n        except Exception as e:\n            raise AssertionError(\"Start time must be a float.\") from e\n        self._start_time = tmp_start_time\n\n        try:\n            tmp_end_time = float(end_time)\n        except Exception as e:\n            raise AssertionError(\"End time must be a float.\") from e\n        self._end_time = tmp_end_time\n\n        assert isinstance(parameters, TempoParameters), \\\n            \"Argument 'parameters' must be an instance of TempoParameters.\"\n        self._parameters = parameters\n\n        self._process_tensor = None\n        if process_tensor_file or isinstance(process_tensor_file, Text):\n            if isinstance(process_tensor_file, Text):\n                filename = process_tensor_file\n            else:\n                filename = None\n            self._init_file_process_tensor(filename, overwrite)\n        else:\n            self._init_simple_process_tensor()\n\n        if backend_config is None:\n            self._backend_config = PT_TEMPO_BACKEND_CONFIG\n        else:\n            self._backend_config = backend_config\n\n        super().__init__(name, description)\n\n        tmp_coupling_comm = commutator(self._bath._coupling_operator)\n        tmp_coupling_acomm = acommutator(self._bath._coupling_operator)\n        self._coupling_comm = tmp_coupling_comm.diagonal()\n        self._coupling_acomm = tmp_coupling_acomm.diagonal()\n\n        tmp_num_steps = int((end_time - self._start_time)/self._parameters.dt)\n        assert tmp_num_steps >= 2, \\\n            \"Parameter `end_time` must be more than two times steps \" \\\n            + \"larger than the parameter `start_time`!\"\n        self._num_steps = tmp_num_steps\n\n        self._backend_instance = None\n        self._init_pt_tempo_backend()\n\n    def _init_simple_process_tensor(self):\n        \"\"\"ToDo. \"\"\"\n        unitary = self._bath.unitary_transform\n        if not np.allclose(unitary, np.identity(self._dimension)):\n            transform_in = left_right_super(unitary.conjugate().T,\n                                            unitary).T\n            transform_out = left_right_super(unitary,\n                                             unitary.conjugate().T).T\n        else:\n            transform_in = None\n            transform_out = None\n        self._process_tensor = SimpleProcessTensor(\n            hilbert_space_dimension=self._dimension,\n            dt=self._parameters.dt,\n            transform_in=transform_in,\n            transform_out=transform_out)\n\n    def _init_file_process_tensor(self, filename, overwrite):\n        \"\"\"ToDo. \"\"\"\n        unitary = self._bath.unitary_transform\n        if not np.allclose(unitary, np.identity(self._dimension)):\n            transform_in = left_right_super(unitary.conjugate().T,\n                                            unitary).T\n            transform_out = left_right_super(unitary,\n                                             unitary.conjugate().T).T\n        else:\n            transform_in = None\n            transform_out = None\n\n        if overwrite:\n            mode = \"overwrite\"\n        else:\n            mode = \"write\"\n        self._process_tensor = FileProcessTensor(\n            mode=mode,\n            filename=filename,\n            hilbert_space_dimension=self._dimension,\n            dt=self._parameters.dt,\n            transform_in=transform_in,\n            transform_out=transform_out)\n\n    def _init_pt_tempo_backend(self):\n        \"\"\"Create and initialize the pt-tempo backend. \"\"\"\n        sum_north = np.array([1.0]*(self._dimension**2))\n        sum_west = np.array([1.0]*(self._dimension**2))\n        dkmax = self._parameters.dkmax\n        if dkmax is None:\n            dkmax = self._num_steps\n        self._backend_instance = PtTempoBackend(\n                dimension=self._dimension,\n                influence=self._influence,\n                process_tensor=self._process_tensor,\n                sum_north=sum_north,\n                sum_west=sum_west,\n                num_steps=self._num_steps,\n                dkmax=dkmax,\n                epsrel=self._parameters.epsrel,\n                config=self._backend_config)\n\n    def _influence(self, dk: int):\n        \"\"\"Create the influence functional matrix for a time step distance\n        of dk. \"\"\"\n        return influence_matrix(\n            dk,\n            parameters=self._parameters,\n            correlations=self._correlations,\n            coupling_acomm=self._coupling_acomm,\n            coupling_comm=self._coupling_comm)\n\n    @property\n    def dimension(self) -> np.ndarray:\n        \"\"\"Hilbert space dimension. \"\"\"\n        return copy(self._dimension)\n\n    def compute(self, progress_type: Optional[Text] = None) -> None:\n        \"\"\"\n        Propagate (or continue to propagate) the TEMPO tensor network to\n        time `end_time`.\n\n        Parameters\n        ----------\n        progress_type: str (default = None)\n            The progress report type during the computation. Types are:\n            {``silent``, ``simple``, ``bar``}. If `None` then\n            the default progress type is used.\n        \"\"\"\n        if self._backend_instance.step is None:\n            self._backend_instance.initialize()\n\n        progress = get_progress(progress_type)\n        with progress(self._backend_instance.num_steps) as prog_bar:\n            while self._backend_instance.compute_step():\n                prog_bar.update(self._backend_instance.step)\n            prog_bar.update(self._backend_instance.step)\n\n    def get_process_tensor(\n            self,\n            progress_type: Optional[Text] = None) -> BaseProcessTensor:\n        \"\"\"\n        Returns a the computed process tensor. It performs the computation if\n        it hasn't been already done.\n\n        Parameters\n        ----------\n        progress_type: str (default = None)\n            The progress report type during the computation. Types are:\n            {``silent``, ``simple``, ``bar``}. If `None` then\n            the default progress type is used.\n\n        Returns\n        -------\n        process_tensor: SimpleProcessTensor\n            The computed process tensor.\n        \"\"\"\n        if self._backend_instance.step is None or \\\n            self._backend_instance.step < self._backend_instance.num_steps:\n            self.compute(progress_type=progress_type)\n\n        if len(self._process_tensor) < self._backend_instance.num_steps:\n            self._backend_instance.update_process_tensor()\n\n        return self._process_tensor\n\n\ndef pt_tempo_compute(\n        bath: Bath,\n        start_time: float,\n        end_time: float,\n        parameters: Optional[TempoParameters] = None,\n        tolerance: Optional[float] = PT_DEFAULT_TOLERANCE,\n        process_tensor_file: Optional[Union[Text, bool]] = None,\n        overwrite: Optional[bool] = False,\n        backend_config: Optional[Dict] = None,\n        progress_type: Optional[Text] = None,\n        name: Optional[Text] = None,\n        description: Optional[Text] = None) -> BaseProcessTensor:\n    \"\"\"\n    Shortcut for creating a process tensor by performing a PT-TEMPO\n    computation.\n\n    Parameters\n    ----------\n    bath: Bath\n        The Bath (includes the coupling operator to the system).\n    start_time: float\n        The start time.\n    end_time: float\n        The time to which the PT-TEMPO should be computed.\n    parameters: TempoParameters\n        The parameters for the PT-TEMPO computation.\n    tolerance: float\n        Tolerance for the parameter estimation (only applicable if\n        `parameters` is None).\n    backend_config: dict (default = None)\n        The configuration of the backend. If `backend_config` is\n        ``None`` then the default backend configuration is used.\n    progress_type: str (default = None)\n        The progress report type during the computation. Types are:\n        {``'silent'``, ``'simple'``, ``'bar'``}.  If `None` then\n        the default progress type is used.\n    name: str (default = None)\n        An optional name for the tempo object.\n    description: str (default = None)\n        An optional description of the tempo object.\n    \"\"\"\n    if parameters is None:\n        assert tolerance is not None, \\\n            \"If 'parameters' is 'None' then 'tolerance' must be \" \\\n            + \"a positive float.\"\n        parameters = guess_tempo_parameters(bath=bath,\n                                            start_time=start_time,\n                                            end_time=end_time,\n                                            tolerance=tolerance)\n    ptt = PtTempo(bath,\n                  start_time,\n                  end_time,\n                  parameters,\n                  process_tensor_file,\n                  overwrite,\n                  backend_config,\n                  name,\n                  description)\n    ptt.compute(progress_type=progress_type)\n    return ptt.get_process_tensor()\n", "meta": {"hexsha": "8bc55d14b91449cca73188f153a7623a82dd87e9", "size": 12671, "ext": "py", "lang": "Python", "max_stars_repo_path": "oqupy/tempo/pt_tempo.py", "max_stars_repo_name": "gefux/OQuPy", "max_stars_repo_head_hexsha": "764528fb6181ea62f8829a9e0a9e3faa2af71e1f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "oqupy/tempo/pt_tempo.py", "max_issues_repo_name": "gefux/OQuPy", "max_issues_repo_head_hexsha": "764528fb6181ea62f8829a9e0a9e3faa2af71e1f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "oqupy/tempo/pt_tempo.py", "max_forks_repo_name": "gefux/OQuPy", "max_forks_repo_head_hexsha": "764528fb6181ea62f8829a9e0a9e3faa2af71e1f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.823880597, "max_line_length": 78, "alphanum_fraction": 0.6319943177, "include": true, "reason": "import numpy", "num_tokens": 2772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.3242353989809524, "lm_q1q2_score": 0.1734978476921537}}
{"text": "\"\"\"PriNCe configuration module.\"\"\"\n\nimport os.path as path\nimport platform\nimport sys\nimport warnings\n\nimport numpy as np\n\nbase_path = path.dirname(path.abspath(__file__))\n\n#: Debug flag for verbose printing, 0 silences PriNCe entirely\ndebug_level = 1\n#: Printout debug info only for functions in this list (just give the name,\n#: \"get_solution\" for instance) Warning, this option slows down initialization\n#: by a lot. Use only when needed.\noverride_debug_fcn = []\n#: Override debug printout for debug levels < value for the functions above\noverride_max_level = 10\n#: Print module name in debug output\nprint_module = False\n\n# =================================================================\n# Paths and library locations\n# =================================================================\n\n#: Directory where the data files for the calculation are stored\ndata_dir = path.join(base_path, 'data')\n\n#: PrinceDB file name\ndb_fname = 'prince_db_05.h5'\n\n#: Model file for redistribution functions (from SOPHIA or similar)\nredist_fname = 'sophia_redistribution_logbins.npy'\n\n\n#=========================================================================\n# Physics configuration\n#=========================================================================\n\n#: Cosmological parameters\n\n#: Hubble constant\nH_0 = 70.5  #km s^-1 Mpc^-1\nH_0s = 2.28475e-18  #s^-1\n\n#: Omega_m\nOmega_m = 0.27\n\n#: Omega_Lambda\nOmega_Lambda = 0.73\n\n#: CMB energy kB*T0 [GeV]\nE_CMB = 2.34823e-13  \n\n#===========================================================================\n# Grids\n#===========================================================================\n\n#: Cosmic ray energy grid (defines system size for solver)\n#: Number of bins in multiples of 4 recommended for maximal vectorization\n#: efficiency for 256 bit AVX or similar\n#: Format (log10(E_min), log10(E_max), nbins/decade of energy)\ncosmic_ray_grid = (3, 14, 8)\n#: Photon grid of target field, only for calculation of rates\nphoton_grid = (-15, -6, 8)\n\n#: Scale of the energy grid\n#:'E': logarithmic in energy E_i = E_min * (Delta)^i\n#:'logE': linear grid in x = log_10(E): x_i = x_min + i * Delta\ngrid_scale ='E'\n\n#: Order of semi-lagrangian for energy derivative \nsemi_lagr_method ='5th_order'\n\n#===========================================================================\n# Model options\n#===========================================================================\n\n#: Threshold lifetime value for explicit transport of particles of this type. It\n#: means that if a particle is unstable with lifetime smaller than this threshold,\n#: it will be decayed until all final state particles of this chain are stable.\n#: In other words: short intermediate states will be integrated out\ntau_dec_threshold = np.inf # All unstable particles decay\n# tau_dec_threshold = 0.  # None unstable particles decay\n# tau_dec_threshold = 850. # This value is for stable neutrons\n\n#: Particle ID for which redistribution functions are needed to be taken into\n#: account. The default value is 101 (proton). All particles with smaller\n#: IDs, i.e. neutrinos, pions, muons etc., will have energy redistributions.\n#: For larger IDs (nuclei) the boost conservation is employed.\nredist_threshold_ID = 101\n\n#: Cut on energy redistribution functions\n#: Resitribution below this x value are set to 0.\n#: \"x_cut\" : 0.,\n#: \"x_cut_proton\" : 0.,\nx_cut = 1e-4\nx_cut_proton = 1e-1\n\n#: cut on photon energy, cross section above y = E_cr e_ph / m_cr does not contribute\ny_cut = np.inf\n\n# Build equation system up to a maximal nuclear mass of\nmax_mass = np.inf\n\n# Include secondaries like photons and neutrinos\nsecondaries = True\n# List of specific particles to ignore\nignore_particles = [20,21] # (we ignore photons and electrons, as their physics is not fully implemented)\n\n#===========================================================================\n# Parameters of numerical integration\n#===========================================================================\n\n# Update rates at not more frequently than this value in z\nupdate_rates_z_threshold = 0.01\n\n# #Number of MKL threads (for sparse matrix multiplication the performance\n# #advantage from using more than a few threads is limited by memory bandwidth)\nMKL_threads = 4\n\n# Sparse matrix-vector product from \"CUPY\"|\"MKL\"|\"scipy\"\nlinear_algebra_backend = \"MKL\"\n\n\n# Check for CUPY library for GPU support\ntry:\n    import cupy\n    has_cupy = True\n    mempool = cupy.get_default_memory_pool()\n    mempool.free_all_blocks()\nexcept ModuleNotFoundError:\n    print('CUPY not found for GPU support. Degrading to MKL.')\n    if linear_algebra_backend == 'cupy':\n        linear_algebra_backend = 'MKL'\n    has_cupy = False\n\n#: determine shared library extension and MKL path\npf = platform.platform()\n\nif 'Linux' in pf:\n    mkl_path = path.join(sys.prefix, 'lib', 'libmkl_rt.so')\nelif 'Darwin' in pf:\n    mkl_path = path.join(sys.prefix, 'lib', 'libmkl_rt.dylib')\nelse:\n    # Windows case\n    mkl_path = path.join(sys.prefix, 'Library', 'bin', 'mkl_rt.dll')\n\n# mkl library handler\nmkl = None\n\n# Check if MKL library found\nif path.isfile(mkl_path):\n    has_mkl = True\nelse:\n    has_mkl = False\n\ndef set_mkl_threads(nthreads):\n    global mkl, MKL_threads\n    from ctypes import cdll, byref, c_int\n    mkl = cdll.LoadLibrary(mkl_path)\n    # Set number of threads\n    MKL_threads = nthreads\n    mkl.mkl_set_num_threads(byref(c_int(nthreads)))\n    if debug_level >= 5:\n        print('MKL threads limited to {0}'.format(nthreads))\n\nif has_mkl:\n    set_mkl_threads(MKL_threads)\n\nif not has_mkl and linear_algebra_backend.lower() == 'mkl':\n    print('MKL runtime not found. Degrading to scipy.')\n    linear_algebra_backend = 'scipy'\n\ndef _download_file(url, outfile):\n    \"\"\"Downloads the PriNCe database from github release binaries.\"\"\"\n\n    from tqdm import tqdm\n    import requests\n    import math\n\n    # Streaming, so we can iterate over the response.\n    r = requests.get(url, stream=True)\n\n    # Total size in bytes.\n    total_size = int(r.headers.get('content-length', 0))\n    block_size = 1024 * 1024\n    wrote = 0\n    with open(outfile, 'wb') as f:\n        for data in tqdm(r.iter_content(block_size), total=math.ceil(total_size // block_size),\n                         unit='MB', unit_scale=True):\n            wrote = wrote + len(data)\n            f.write(data)\n    if total_size != 0 and wrote != total_size:\n        raise Exception(\"ERROR, something went wrong\")\n\n# Download database file from github\nbase_url = 'https://github.com/joheinze/PriNCe/releases/download/'\nrelease_tag = 'v0.5_alpha_release/'\nurl = base_url + release_tag + db_fname\nif not path.isfile(path.join(data_dir, db_fname)):\n    print('Downloading for PriNCe database file {0}.'.format(db_fname))\n    if debug_level >= 2:\n        print(url)\n    _download_file(url, path.join(data_dir, db_fname))\nelse:\n    import h5py\n    try:\n        with h5py.File(path.join(data_dir, db_fname), 'r') as prince_db:\n            db_version = (prince_db.attrs['version'])\n    except:\n        print(f'Database file {db_fname} corrupted. Retrying download.')\n        _download_file(url, path.join(data_dir, db_fname))\n    finally:\n        with h5py.File(path.join(data_dir, db_fname), 'r') as prince_db:\n            db_version = (prince_db.attrs['version'])\n        if debug_level >= 2:\n            print(f'Using database file version {db_version}.')\n\n# if path.isfile(path.join(data_dir, '...previous db name...')):\n#     import os\n#     print('Removing previous database {0}.'.format('...previous db name...'))\n#     os.unlink(path.join(data_dir, '...previous db name...'))\n", "meta": {"hexsha": "705d0152a500fbebb6f9b9ed034dcf533990be87", "size": 7566, "ext": "py", "lang": "Python", "max_stars_repo_path": "prince_cr/config.py", "max_stars_repo_name": "afedynitch/PriNCe", "max_stars_repo_head_hexsha": "372f037f6c114528c52c6d5ca3624897b72a8605", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-05-01T12:21:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-26T16:18:39.000Z", "max_issues_repo_path": "prince_cr/config.py", "max_issues_repo_name": "afedynitch/PriNCe", "max_issues_repo_head_hexsha": "372f037f6c114528c52c6d5ca3624897b72a8605", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-05-03T11:37:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-15T12:37:40.000Z", "max_forks_repo_path": "prince_cr/config.py", "max_forks_repo_name": "afedynitch/PriNCe", "max_forks_repo_head_hexsha": "372f037f6c114528c52c6d5ca3624897b72a8605", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-16T01:35:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T13:08:11.000Z", "avg_line_length": 33.6266666667, "max_line_length": 105, "alphanum_fraction": 0.6418186624, "include": true, "reason": "import numpy,import cupy", "num_tokens": 1818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.173469068264183}}
{"text": "# ----------------------------------------------------------------------------\n# Copyright (c) 2016-2017, UniFrac development team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file LICENSE, distributed with this software.\n# ----------------------------------------------------------------------------\nfrom warnings import warn\nfrom functools import reduce\nfrom operator import or_\n\nimport numpy as np\nimport skbio\n\nimport unifrac as qsu\nfrom unifrac._meta import CONSOLIDATIONS\n\n\ndef is_biom_v210(f):\n    import h5py\n    if not h5py.is_hdf5(f):\n        return False\n    with h5py.File(f, 'r') as fp:\n        if 'format-version' not in fp.attrs:\n            return False\n\n        version = fp.attrs.get('format-version', None)\n\n        if version is None:\n            return False\n\n        if tuple(version) != (2, 1):\n            return False\n\n    return True\n\n\ndef is_newick(f):\n    sniffer = skbio.io.format.newick.newick.sniffer_function\n    return sniffer(f)[0]\n\n\ndef _validate(table, phylogeny):\n    if not is_biom_v210(table):\n        raise ValueError(\"Table does not appear to be a BIOM-Format v2.1\")\n    if not is_newick(phylogeny):\n        raise ValueError(\"The phylogeny does not appear to be newick\")\n\n\ndef _validate_meta(tables, phylogenies):\n    for idx, (table, phylogeny) in enumerate(zip(tables, phylogenies)):\n        if not is_biom_v210(table):\n            raise ValueError(f\"Table at position {idx} does not appear to be a\"\n                             \" BIOM-Format v2.1\")\n        if not is_newick(phylogeny):\n            raise ValueError(f\"The phylogeny at position {idx} does not appear\"\n                             \" to be newick\")\n\n\ndef unweighted(table: str,\n               phylogeny: str,\n               threads: int = 1,\n               variance_adjusted: bool = False,\n               bypass_tips: bool = False) -> skbio.DistanceMatrix:\n    \"\"\"Compute Unweighted UniFrac\n\n    Parameters\n    ----------\n    table : str\n        A filepath to a BIOM-Format 2.1 file.\n    phylogeny : str\n        A filepath to a Newick formatted tree.\n    threads : int, optional\n        The number of threads to use. Default of 1.\n    variance_adjusted : bool, optional\n        Adjust for varianace or not. Default is False.\n    bypass_tips : bool\n        Bypass the tips of the tree in the computation. This reduces compute\n        by about 50%, but is an approximation.\n\n    Returns\n    -------\n    skbio.DistanceMatrix\n        The resulting distance matrix.\n\n    Raises\n    ------\n    IOError\n        If the tree file is not found\n        If the table is not found\n    ValueError\n        If the table does not appear to be BIOM-Format v2.1.\n        If the phylogeny does not appear to be in Newick format.\n\n    Notes\n    -----\n    Unweighted UniFrac was originally described in [1]_. Variance Adjusted\n    UniFrac was originally described in [2]_, and while its application to\n    Unweighted UniFrac was not described, factoring in the variance adjustment\n    is still feasible and so it is exposed.\n\n    References\n    ----------\n    .. [1] Lozupone, C. & Knight, R. UniFrac: a new phylogenetic method for\n       comparing microbial communities. Appl. Environ. Microbiol. 71, 8228-8235\n       (2005).\n    .. [2] Chang, Q., Luan, Y. & Sun, F. Variance adjusted weighted UniFrac: a\n       powerful beta diversity measure for comparing communities based on\n       phylogeny. BMC Bioinformatics 12:118 (2011).\n    \"\"\"\n    _validate(table, phylogeny)\n    return qsu.ssu(table, phylogeny, 'unweighted',\n                   variance_adjusted, 1.0, bypass_tips, threads)\n\n\ndef unweighted_fp32(table: str,\n                    phylogeny: str,\n                    threads: int = 1,\n                    variance_adjusted: bool = False,\n                    bypass_tips: bool = False) -> skbio.DistanceMatrix:\n    \"\"\"Compute Unweighted UniFrac using fp32 math\n\n    Parameters\n    ----------\n    table : str\n        A filepath to a BIOM-Format 2.1 file.\n    phylogeny : str\n        A filepath to a Newick formatted tree.\n    threads : int, optional\n        The number of threads to use. Default of 1.\n    variance_adjusted : bool, optional\n        Adjust for varianace or not. Default is False.\n    bypass_tips : bool\n        Bypass the tips of the tree in the computation. This reduces compute\n        by about 50%, but is an approximation.\n\n    Returns\n    -------\n    skbio.DistanceMatrix\n        The resulting distance matrix.\n\n    Raises\n    ------\n    IOError\n        If the tree file is not found\n        If the table is not found\n    ValueError\n        If the table does not appear to be BIOM-Format v2.1.\n        If the phylogeny does not appear to be in Newick format.\n\n    Notes\n    -----\n    Unweighted UniFrac was originally described in [1]_. Variance Adjusted\n    UniFrac was originally described in [2]_, and while its application to\n    Unweighted UniFrac was not described, factoring in the variance adjustment\n    is still feasible and so it is exposed.\n\n    References\n    ----------\n    .. [1] Lozupone, C. & Knight, R. UniFrac: a new phylogenetic method for\n       comparing microbial communities. Appl. Environ. Microbiol. 71, 8228-8235\n       (2005).\n    .. [2] Chang, Q., Luan, Y. & Sun, F. Variance adjusted weighted UniFrac: a\n       powerful beta diversity measure for comparing communities based on\n       phylogeny. BMC Bioinformatics 12:118 (2011).\n    \"\"\"\n    _validate(table, phylogeny)\n    return qsu.ssu(table, phylogeny, 'unweighted_fp32',\n                   variance_adjusted, 1.0, bypass_tips, threads)\n\n\ndef weighted_normalized(table: str,\n                        phylogeny: str,\n                        threads: int = 1,\n                        variance_adjusted: bool = False,\n                        bypass_tips: bool = False) -> skbio.DistanceMatrix:\n    \"\"\"Compute weighted normalized UniFrac\n\n    Parameters\n    ----------\n    table : str\n        A filepath to a BIOM-Format 2.1 file.\n    phylogeny : str\n        A filepath to a Newick formatted tree.\n    threads : int, optional\n        The number of threads to use. Default of 1.\n    variance_adjusted : bool, optional\n        Adjust for varianace or not. Default is False.\n    bypass_tips : bool\n        Bypass the tips of the tree in the computation. This reduces compute\n        by about 50%, but is an approximation.\n\n    Returns\n    -------\n    skbio.DistanceMatrix\n        The resulting distance matrix.\n\n    Raises\n    ------\n    IOError\n        If the tree file is not found\n        If the table is not found\n    ValueError\n        If the table does not appear to be BIOM-Format v2.1.\n        If the phylogeny does not appear to be in Newick format.\n\n    Notes\n    -----\n    Weighted UniFrac was originally described in [1]_. Variance Adjusted\n    Weighted UniFrac was originally described in [2]_.\n\n    References\n    ----------\n    .. [1] Lozupone, C. A., Hamady, M., Kelley, S. T. & Knight, R. Quantitative\n       and qualitative beta diversity measures lead to different insights into\n       factors that structure microbial communities. Appl. Environ. Microbiol.\n       73, 1576-1585 (2007).\n    .. [2] Chang, Q., Luan, Y. & Sun, F. Variance adjusted weighted UniFrac: a\n       powerful beta diversity measure for comparing communities based on\n       phylogeny. BMC Bioinformatics 12:118 (2011).\n    \"\"\"\n    _validate(table, phylogeny)\n    return qsu.ssu(str(table), str(phylogeny), 'weighted_normalized',\n                   variance_adjusted, 1.0, bypass_tips, threads)\n\n\ndef weighted_normalized_fp32(table: str,\n                             phylogeny: str,\n                             threads: int = 1,\n                             variance_adjusted: bool = False,\n                             bypass_tips: bool = False\n                             ) -> skbio.DistanceMatrix:\n    \"\"\"Compute weighted normalized UniFrac using fp32 math\n\n    Parameters\n    ----------\n    table : str\n        A filepath to a BIOM-Format 2.1 file.\n    phylogeny : str\n        A filepath to a Newick formatted tree.\n    threads : int, optional\n        The number of threads to use. Default of 1.\n    variance_adjusted : bool, optional\n        Adjust for varianace or not. Default is False.\n    bypass_tips : bool\n        Bypass the tips of the tree in the computation. This reduces compute\n        by about 50%, but is an approximation.\n\n    Returns\n    -------\n    skbio.DistanceMatrix\n        The resulting distance matrix.\n\n    Raises\n    ------\n    IOError\n        If the tree file is not found\n        If the table is not found\n    ValueError\n        If the table does not appear to be BIOM-Format v2.1.\n        If the phylogeny does not appear to be in Newick format.\n\n    Notes\n    -----\n    Weighted UniFrac was originally described in [1]_. Variance Adjusted\n    Weighted UniFrac was originally described in [2]_.\n\n    References\n    ----------\n    .. [1] Lozupone, C. A., Hamady, M., Kelley, S. T. & Knight, R. Quantitative\n       and qualitative beta diversity measures lead to different insights into\n       factors that structure microbial communities. Appl. Environ. Microbiol.\n       73, 1576-1585 (2007).\n    .. [2] Chang, Q., Luan, Y. & Sun, F. Variance adjusted weighted UniFrac: a\n       powerful beta diversity measure for comparing communities based on\n       phylogeny. BMC Bioinformatics 12:118 (2011).\n    \"\"\"\n    _validate(table, phylogeny)\n    return qsu.ssu(str(table), str(phylogeny), 'weighted_normalized_fp32',\n                   variance_adjusted, 1.0, bypass_tips, threads)\n\n\ndef weighted_unnormalized(table: str,\n                          phylogeny: str,\n                          threads: int = 1,\n                          variance_adjusted: bool = False,\n                          bypass_tips: bool = False) -> skbio.DistanceMatrix:\n    # noqa\n    \"\"\"Compute weighted unnormalized UniFrac\n\n    Parameters\n    ----------\n    table : str\n        A filepath to a BIOM-Format 2.1 file.\n    phylogeny : str\n        A filepath to a Newick formatted tree.\n    threads : int, optional\n        The number of threads to use. Default is 1.\n    variance_adjusted : bool, optional\n        Adjust for varianace or not. Default is False.\n    bypass_tips : bool\n        Bypass the tips of the tree in the computation. This reduces compute\n        by about 50%, but is an approximation.\n\n    Returns\n    -------\n    skbio.DistanceMatrix\n        The resulting distance matrix.\n\n    Raises\n    ------\n    IOError\n        If the tree file is not found\n        If the table is not found\n    ValueError\n        If the table does not appear to be BIOM-Format v2.1.\n        If the phylogeny does not appear to be in Newick format.\n\n    Notes\n    -----\n    Weighted UniFrac was originally described in [1]_. Variance Adjusted\n    Weighted UniFrac was originally described in [2]_.\n\n    References\n    ----------\n    .. [1] Lozupone, C. A., Hamady, M., Kelley, S. T. & Knight, R. Quantitative\n       and qualitative beta diversity measures lead to different insights into\n       factors that structure microbial communities. Appl. Environ. Microbiol.\n       73, 1576-1585 (2007).\n    .. [2] Chang, Q., Luan, Y. & Sun, F. Variance adjusted weighted UniFrac: a\n       powerful beta diversity measure for comparing communities based on\n       phylogeny. BMC Bioinformatics 12:118 (2011).\n    \"\"\"\n    _validate(table, phylogeny)\n    return qsu.ssu(str(table), str(phylogeny), 'weighted_unnormalized',\n                   variance_adjusted, 1.0, bypass_tips, threads)\n\n\ndef weighted_unnormalized_fp32(table: str,\n                               phylogeny: str,\n                               threads: int = 1,\n                               variance_adjusted: bool = False,\n                               bypass_tips: bool = False\n                               ) -> skbio.DistanceMatrix:\n    # noqa\n    \"\"\"Compute weighted unnormalized UniFrac using fp32 math\n\n    Parameters\n    ----------\n    table : str\n        A filepath to a BIOM-Format 2.1 file.\n    phylogeny : str\n        A filepath to a Newick formatted tree.\n    threads : int, optional\n        The number of threads to use. Default is 1.\n    variance_adjusted : bool, optional\n        Adjust for varianace or not. Default is False.\n    bypass_tips : bool\n        Bypass the tips of the tree in the computation. This reduces compute\n        by about 50%, but is an approximation.\n\n    Returns\n    -------\n    skbio.DistanceMatrix\n        The resulting distance matrix.\n\n    Raises\n    ------\n    IOError\n        If the tree file is not found\n        If the table is not found\n    ValueError\n        If the table does not appear to be BIOM-Format v2.1.\n        If the phylogeny does not appear to be in Newick format.\n\n    Notes\n    -----\n    Weighted UniFrac was originally described in [1]_. Variance Adjusted\n    Weighted UniFrac was originally described in [2]_.\n\n    References\n    ----------\n    .. [1] Lozupone, C. A., Hamady, M., Kelley, S. T. & Knight, R. Quantitative\n       and qualitative beta diversity measures lead to different insights into\n       factors that structure microbial communities. Appl. Environ. Microbiol.\n       73, 1576-1585 (2007).\n    .. [2] Chang, Q., Luan, Y. & Sun, F. Variance adjusted weighted UniFrac: a\n       powerful beta diversity measure for comparing communities based on\n       phylogeny. BMC Bioinformatics 12:118 (2011).\n    \"\"\"\n    _validate(table, phylogeny)\n    return qsu.ssu(str(table), str(phylogeny), 'weighted_unnormalized_fp32',\n                   variance_adjusted, 1.0, bypass_tips, threads)\n\n\ndef generalized(table: str,\n                phylogeny: str,\n                threads: int = 1,\n                alpha: float = 1.0,\n                variance_adjusted: bool = False,\n                bypass_tips: bool = False) -> skbio.DistanceMatrix:\n    \"\"\"Compute Generalized UniFrac\n\n    Parameters\n    ----------\n    table : str\n        A filepath to a BIOM-Format 2.1 file.\n    phylogeny : str\n        A filepath to a Newick formatted tree.\n    threads : int, optional\n        The number of threads to use. Default is 1\n    alpha : float, optional\n        The level of contribution of high abundance branches. Higher alpha\n        increases the contribution of from high abundance branches while lower\n        alpha reduces the contribution. Alpha was originally defined over the\n        range [0, 1]. Default is 1.0.\n    variance_adjusted : bool, optional\n        Adjust for varianace or not. Default is False.\n    bypass_tips : bool\n        Bypass the tips of the tree in the computation. This reduces compute\n        by about 50%, but is an approximation.\n\n    Returns\n    -------\n    skbio.DistanceMatrix\n        The resulting distance matrix.\n\n    Raises\n    ------\n    IOError\n        If the tree file is not found\n        If the table is not found\n    ValueError\n        If the table does not appear to be BIOM-Format v2.1.\n        If the phylogeny does not appear to be in Newick format.\n\n    Notes\n    -----\n    Generalized UniFrac was originally described in [1]_. Variance Adjusted\n    UniFrac was originally described in [2]_, but was not described in as\n    applied to Generalized UniFrac. It is feasible to do, so it is exposed\n    here.\n\n    An alpha of 1.0 is Weighted normalized UniFrac. An alpha of 0.0 is\n    approximately Unweighted UniFrac, and is if the proportions are\n    dichotomized.\n\n    References\n    ----------\n    .. [1] Chen, J., Bittinger, K., Charlson, E. S., Hoffmann C., Lewis, J.,\n       Wu, G. D., Collman R. G., Bushman, F. D. & Hongzhe L. Associating\n       microbiome composition with environmental covariates using generalized\n       UniFrac distances. Bioinformatics 28(16), 2106–2113 (2012).\n    .. [2] Chang, Q., Luan, Y. & Sun, F. Variance adjusted weighted UniFrac: a\n       powerful beta diversity measure for comparing communities based on\n       phylogeny. BMC Bioinformatics 12:118 (2011).\n    \"\"\"\n    _validate(table, phylogeny)\n    if alpha == 1.0:\n        warn(\"alpha of 1.0 is weighted-normalized UniFrac. \"\n             \"Weighted-normalized is being used instead as it is more \"\n             \"optimized.\",\n             Warning)\n        return weighted_normalized(table, phylogeny, threads,\n                                   variance_adjusted)\n    else:\n        return qsu.ssu(str(table), str(phylogeny), 'generalized',\n                       variance_adjusted, alpha, bypass_tips, threads)\n\n\ndef generalized_fp32(table: str,\n                     phylogeny: str,\n                     threads: int = 1,\n                     alpha: float = 1.0,\n                     variance_adjusted: bool = False,\n                     bypass_tips: bool = False) -> skbio.DistanceMatrix:\n    \"\"\"Compute Generalized UniFrac using fp32 math\n\n    Parameters\n    ----------\n    table : str\n        A filepath to a BIOM-Format 2.1 file.\n    phylogeny : str\n        A filepath to a Newick formatted tree.\n    threads : int, optional\n        The number of threads to use. Default is 1\n    alpha : float, optional\n        The level of contribution of high abundance branches. Higher alpha\n        increases the contribution of from high abundance branches while lower\n        alpha reduces the contribution. Alpha was originally defined over the\n        range [0, 1]. Default is 1.0.\n    variance_adjusted : bool, optional\n        Adjust for varianace or not. Default is False.\n    bypass_tips : bool\n        Bypass the tips of the tree in the computation. This reduces compute\n        by about 50%, but is an approximation.\n\n    Returns\n    -------\n    skbio.DistanceMatrix\n        The resulting distance matrix.\n\n    Raises\n    ------\n    IOError\n        If the tree file is not found\n        If the table is not found\n    ValueError\n        If the table does not appear to be BIOM-Format v2.1.\n        If the phylogeny does not appear to be in Newick format.\n\n    Notes\n    -----\n    Generalized UniFrac was originally described in [1]_. Variance Adjusted\n    UniFrac was originally described in [2]_, but was not described in as\n    applied to Generalized UniFrac. It is feasible to do, so it is exposed\n    here.\n\n    An alpha of 1.0 is Weighted normalized UniFrac. An alpha of 0.0 is\n    approximately Unweighted UniFrac, and is if the proportions are\n    dichotomized.\n\n    References\n    ----------\n    .. [1] Chen, J., Bittinger, K., Charlson, E. S., Hoffmann C., Lewis, J.,\n       Wu, G. D., Collman R. G., Bushman, F. D. & Hongzhe L. Associating\n       microbiome composition with environmental covariates using generalized\n       UniFrac distances. Bioinformatics 28(16), 2106–2113 (2012).\n    .. [2] Chang, Q., Luan, Y. & Sun, F. Variance adjusted weighted UniFrac: a\n       powerful beta diversity measure for comparing communities based on\n       phylogeny. BMC Bioinformatics 12:118 (2011).\n    \"\"\"\n    _validate(table, phylogeny)\n    if alpha == 1.0:\n        warn(\"alpha of 1.0 is weighted-normalized UniFrac. \"\n             \"Weighted-normalized is being used instead as it is more \"\n             \"optimized.\",\n             Warning)\n        return weighted_normalized_fp32(table, phylogeny, threads,\n                                        variance_adjusted)\n    else:\n        return qsu.ssu(str(table), str(phylogeny), 'generalized_fp32',\n                       variance_adjusted, alpha, bypass_tips, threads)\n\n\nMETHODS = {'unweighted': unweighted,\n           'weighted_normalized': weighted_normalized,\n           'weighted_unnormalized': weighted_unnormalized,\n           'generalized': generalized,\n           'unweighted_fp32': unweighted_fp32,\n           'weighted_normalized_fp32': weighted_normalized_fp32,\n           'weighted_unnormalized_fp32': weighted_unnormalized_fp32,\n           'generalized_fp32': generalized_fp32}\n\n\ndef meta(tables: tuple, phylogenies: tuple, weights: tuple = None,\n         consolidation: str = None, method: str = None,\n         threads: int = 1, variance_adjusted: bool = False,\n         alpha: float = None, bypass_tips: bool = False) -> \\\n         skbio.DistanceMatrix:\n    \"\"\"Compute meta UniFrac\n\n    Parameters\n    ----------\n    tables : tuple of str\n        Filepaths to BIOM-Format 2.1 files. This tuple is expected to be in\n        index order with phylogenies.\n    phylogenies : tuple of str\n        Filepaths to Newick formatted trees. This tuple is expected to be in\n        index order with tables.\n    weights : tuple of float, optional\n        The weight applied to each tree/table pair. This tuple is expected to\n        be in index order with tables and phylogenies. Default is to weight\n        each tree/table pair evenly.\n    consolidation : str, optional\n        The matrix consolidation method. The available choices are:\n        'skipping_missing_matrices', 'missing_zero', 'missing_one',\n        'skipping_missing_values'. The default is 'skipping_missing_values'.\n    method : str\n        The UniFrac method to use. The available choices are:\n        'unweighted', 'weighted_unnormalized', 'weighted_normalized', and\n        'generalized'.\n    threads : int, optional\n        The number of threads to use. Default is 1\n    bypass_tips : bool\n        Bypass the tips of the tree in the computation. This reduces compute\n        by about 50%, but is an approximation.\n    alpha : float, optional\n        The level of contribution of high abundance branches. Higher alpha\n        increases the contribution of from high abundance branches while lower\n        alpha reduces the contribution. Alpha was originally defined over the\n        range [0, 1]. Default is 1.0\n    variance_adjusted : bool, optional\n        Adjust for varianace or not. Default is False.\n\n    Returns\n    -------\n    skbio.DistanceMatrix\n        The resulting distance matrix.\n\n    Raises\n    ------\n    IOError\n        If the tree file is not found\n        If the table is not found\n    ValueError\n        If the table does not appear to be BIOM-Format v2.1.\n        If the phylogeny does not appear to be in Newick format.\n\n    Notes\n    -----\n    UniFrac can be adapted to account for multiple genes, as originally\n    done in [1]_.\n\n    Generalized UniFrac was originally described in [2]_. Variance Adjusted\n    UniFrac was originally described in [3]_, but was not described in as\n    applied to Generalized UniFrac. It is feasible to do, so it is exposed\n    here.\n\n    References\n    ----------\n    .. [1] Lozupone C. A., Hamady M., Cantarel B. L., Coutinho P. M.,\n       Henrissat B., Gordon J. I. & Knight R. The convergence of carbohydrate\n       active gene repertoires in human gut microbes. PNAS 105(39):15076-81\n       (2008).\n    .. [2] Chen, J., Bittinger, K., Charlson, E. S., Hoffmann C., Lewis, J.,\n       Wu, G. D., Collman R. G., Bushman, F. D. & Hongzhe L. Associating\n       microbiome composition with environmental covariates using generalized\n       UniFrac distances. Bioinformatics 28(16), 2106–2113 (2012).\n    .. [3] Chang, Q., Luan, Y. & Sun, F. Variance adjusted weighted UniFrac: a\n       powerful beta diversity measure for comparing communities based on\n       phylogeny. BMC Bioinformatics 12:118 (2011).\n    \"\"\"\n    if not len(tables):\n        raise ValueError(\"No tables specified.\")\n\n    if not len(phylogenies):\n        raise ValueError(\"No trees specified.\")\n\n    if len(tables) != len(phylogenies):\n        raise ValueError(\"Number of trees and tables must be the same.\")\n\n    if weights is None:\n        weights = tuple(1 for _ in phylogenies)\n    else:\n        if len(weights) != len(phylogenies):\n            raise ValueError(\"Number of weights does not match number of \"\n                             \"trees and tables.\")\n\n    if method is None:\n        raise ValueError(\"No method specified.\")\n    method_ = METHODS.get(method.replace('-', '_'))\n    if method_ is None:\n        raise ValueError(\"Method (%s) unrecognized. Available methods are: %s\"\n                         % (method, ', '.join(METHODS.keys())))\n\n    if consolidation is None:\n        consolidation = 'skipping_missing_values'\n    consolidation_ = CONSOLIDATIONS.get(consolidation.replace('-', '_'))\n    if consolidation_ is None:\n        raise ValueError(\"Consolidation (%s) unrecognized. Available \"\n                         \"consolidations are: %s\"\n                         % (consolidation, ', '.join(CONSOLIDATIONS.keys())))\n\n    if alpha is not None and method is not generalized:\n        raise ValueError(\"The alpha parameter can only be set when the method \"\n                         \"is set as 'generalized', the selected method is \"\n                         \"'%s'.\" % method)\n\n    _validate_meta(tables, phylogenies)\n\n    kwargs = {'threads': threads,\n              'bypass_tips': bypass_tips,\n              'variance_adjusted': variance_adjusted}\n    if alpha is not None:\n        kwargs['alpha'] = alpha\n\n    weights = np.array(weights, float)/sum(weights)\n    dms = [method_(table, tree, **kwargs) for table, tree in zip(tables,\n                                                                 phylogenies)]\n    all_ids = sorted(reduce(or_, [set(dm.ids) for dm in dms]))\n    dm = consolidation_(dms, [dm.ids for dm in dms], weights, all_ids)\n\n    return skbio.DistanceMatrix(dm, ids=all_ids)\n", "meta": {"hexsha": "0464dd71288184293d63f2c77f2bd82e41e3d6ad", "size": 25154, "ext": "py", "lang": "Python", "max_stars_repo_path": "unifrac/_methods.py", "max_stars_repo_name": "ChrisKeefe/unifrac", "max_stars_repo_head_hexsha": "77a0692c1fc265214f7bee9349b20527d332e239", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unifrac/_methods.py", "max_issues_repo_name": "ChrisKeefe/unifrac", "max_issues_repo_head_hexsha": "77a0692c1fc265214f7bee9349b20527d332e239", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unifrac/_methods.py", "max_forks_repo_name": "ChrisKeefe/unifrac", "max_forks_repo_head_hexsha": "77a0692c1fc265214f7bee9349b20527d332e239", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7211678832, "max_line_length": 79, "alphanum_fraction": 0.6235191222, "include": true, "reason": "import numpy", "num_tokens": 6084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.310694383214554, "lm_q1q2_score": 0.17346906113706492}}
{"text": "#!/usr/bin/env pyth\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 18 15:45:32 2021\n\n@author: michael\n\"\"\"\nfrom datetime import datetime\nimport torch\nimport xitorch\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport argparse\nimport os\nfrom torch import nn, optim\nfrom LoadData import LoadData\nimport shutil\nfrom _utils import EarlyStopping\nfrom torch.utils.tensorboard import SummaryWriter\nfrom typing import Callable, Union, Mapping, Any, Sequence, Optional\nfrom xitorch._utils.assertfuncs import assert_fcn_params, assert_runtime\nfrom xitorch._core.pure_function import get_pure_function, make_sibling\nfrom xitorch._impls.integrate.ivp.explicit_rk import rk4_ivp, rk38_ivp\nfrom xitorch._impls.integrate.ivp.adaptive_rk import rk23_adaptive, rk45_adaptive\nfrom xitorch._utils.misc import set_default_option, TensorNonTensorSeparator, TensorPacker\nfrom xitorch._utils.tensor import convert_none_grads_to_zeros\nfrom xitorch._docstr.api_docstr import get_methods_docstr\nfrom xitorch.debug.modes import is_debug_enabled\n\n__all__ = [\"solve_ivp\"]\n\n\ndef solve_ivp(fcn: Union[Callable[..., torch.Tensor], Callable[..., Sequence[torch.Tensor]]],\n              ts: torch.Tensor,\n              y0: torch.Tensor,\n              params: Sequence[Any] = [],\n              bck_options: Mapping[str, Any] = {},\n              method: Optional[str] = None,\n              **fwd_options) -> Union[torch.Tensor, Sequence[torch.Tensor]]:\n    r\"\"\"\n    Solve the initial value problem (IVP) or also commonly known as ordinary\n    differential equations (ODE), where given the initial value :math:`\\mathbf{y_0}`,\n    it then solves\n\n    .. math::\n\n        \\mathbf{y}(t) = \\mathbf{y_0} + \\int_{t_0}^{t} \\mathbf{f}(t', \\mathbf{y}, \\theta)\\ \\mathrm{d}t'\n\n    Arguments\n    ---------\n    fcn: callable\n        The function that represents dy/dt. The function takes an input of a\n        single time ``t`` and tensor ``y`` with shape ``(*ny)`` and\n        produce :math:`\\mathrm{d}\\mathbf{y}/\\mathrm{d}t` with shape ``(*ny)``.pip3 insta;;\n        The output of the function must be a tensor with shape ``(*ny)`` or\n        a list of tensors.\n    ts: torch.tensor\n        The time points where the value of `y` will be returned.\n        It must be monotonically increasing or decreasing.\n        It is a tensor with shape ``(nt,)``.\n    y0: torch.tensor\n        The initial value of ``y``, i.e. ``y(t[0]) == y0``.\n        It is a tensor with shape ``(*ny)`` or a list of tensors.\n    params: list\n        Sequence of other parameters required in the function.\n    bck_options: dict\n        Options for the backward solve_ivp method. If not specified, it will\n        take the same options as fwd_options.\n    method: str or None\n        Initial value problem solver. If None, it will choose ``\"rk45\"``.\n    **fwd_options\n        Method-specific option (see method section below).\n\n    Returns\n    -------\n    torch.tensor or a list of tensors\n        The values of ``y`` for each time step in ``ts``.\n        It is a tensor with shape ``(nt,*ny)`` or a list of tensors\n    \"\"\"\n    if is_debug_enabled():\n        assert_fcn_params(fcn, (ts[0], y0, *params))\n    assert_runtime(len(ts.shape) == 1, \"Argument ts must be a 1D tensor\")\n\n    if method is None:  # set the default method\n        method = \"rk45\"\n    fwd_options[\"method\"] = method\n\n    # run once to see if the outputs is a tuple or a single tensor\n    is_y0_list = isinstance(y0, list) or isinstance(y0, tuple)\n    dydt = fcn(ts[0], y0, *params)\n    is_dydt_list = isinstance(dydt, list) or isinstance(dydt, tuple)\n    if is_y0_list != is_dydt_list:\n        raise RuntimeError(\"The y0 and output of fcn must both be tuple or a tensor\")\n\n    pfcn = get_pure_function(fcn)\n    if is_y0_list:\n        nt = len(ts)\n        roller = TensorPacker(y0)\n\n        @make_sibling(pfcn)\n        def pfcn2(t, ytensor, *params):\n            ylist = roller.pack(ytensor)\n            res_list = pfcn(t, ylist, *params)\n            res = roller.flatten(res_list)\n            return res\n\n        y0 = roller.flatten(y0)\n        res = _SolveIVP.apply(pfcn2, ts, fwd_options, bck_options, len(params), y0, *params, *pfcn.objparams())\n        return roller.pack(res)\n    else:\n        return _SolveIVP.apply(pfcn, ts, fwd_options, bck_options, len(params), y0, *params, *pfcn.objparams())\n\n\nclass _SolveIVP(torch.autograd.Function):\n    @staticmethod\n    def forward(ctx, pfcn, ts, fwd_options, bck_options, nparams, y0, *allparams):\n        config = fwd_options\n        ctx.bck_config = set_default_option(config, bck_options)\n\n        params = allparams[:nparams]\n        objparams = allparams[nparams:]\n\n        orig_method = config.pop(\"method\")\n        method = orig_method.lower()\n        try:\n            solver = {\n                \"rk4\": rk4_ivp,\n                \"rk38\": rk38_ivp,\n                \"rk23\": rk23_adaptive,\n                \"rk45\": rk45_adaptive,\n            }[method]\n        except KeyError:\n            raise RuntimeError(\"Unknown solve_ivp method: %s\" % config[\"method\"])\n        yt = solver(pfcn, ts, y0, params, **config)\n        # print(yt)\n\n        #########################\n        #####multiprocessing#####\n        #########################\n\n        # save the parameters for backward\n        ctx.param_sep = TensorNonTensorSeparator(allparams, varonly=True)\n        tensor_params = ctx.param_sep.get_tensor_params()\n        ctx.save_for_backward(ts, y0, *tensor_params)\n        ctx.pfcn = pfcn\n        ctx.nparams = nparams\n        ctx.yt = yt\n        ctx.ts_requires_grad = ts.requires_grad\n\n        return yt\n\n    @staticmethod\n    def backward(ctx, grad_yt):\n        # grad_yt: (nt, *ny)\n        nparams = ctx.nparams\n        pfcn = ctx.pfcn\n        param_sep = ctx.param_sep\n        yt = ctx.yt\n        ts_requires_grad = ctx.ts_requires_grad\n\n        # restore the parameters\n        saved_tensors = ctx.saved_tensors\n        ts = saved_tensors[0]\n        y0 = saved_tensors[1]\n        tensor_params = list(saved_tensors[2:])\n        allparams = param_sep.reconstruct_params(tensor_params)  # maybe change the device\n        ntensor_params = len(tensor_params)\n        params = allparams[:nparams]\n        objparams = allparams[nparams:]\n\n        grad_enabled = torch.is_grad_enabled()\n\n        # custom function to evaluate the input `pfcn` based on whether we want\n        # to connect the graph or not\n        def pfunc2(t, y, tensor_params):\n            if not grad_enabled:\n                # if graph is not constructed, then use the default tensor_params\n                ycopy = y.detach().requires_grad_()  # [yi.detach().requires_grad_() for yi in y]\n                tcopy = t.detach().requires_grad_(False)\n                f = pfcn(tcopy, ycopy, *params)\n                return f, ycopy, tensor_params\n            else:\n                # if graph is constructed, then use the clone of the tensor params\n                # so that infinite loop of backward can be avoided\n                tensor_params_copy = [p.clone().requires_grad_() for p in tensor_params]\n                ycopy = y.clone().requires_grad_()\n                tcopy = t.clone().requires_grad_(False)\n                allparams_copy = param_sep.reconstruct_params(tensor_params_copy)\n                params_copy = allparams_copy[:nparams]\n                objparams_copy = allparams_copy[nparams:]\n                with pfcn.useobjparams(objparams_copy):\n                    f = pfcn(tcopy, ycopy, *params_copy)\n                return f, ycopy, tensor_params_copy\n\n        # slices and indices definitions on the augmented states\n        y_index = 0\n        dLdy_index = 1\n        # dLdt_index = 2\n        # dLdt_slice = slice(dLdt_index, dLdt_index+1, None) # [2:3]\n        dLdp_slice = slice(-ntensor_params, None, None) if ntensor_params > 0 else slice(0, 0,\n                                                                                         None)  # [-ntensor_params:]\n        state_size = 2 + ntensor_params  # 3 + ntensor_params\n        states = [None for _ in range(state_size)]  # .to(ts.device())\n\n        def new_pfunc(t, states, *tensor_params):\n            # t: single-element\n            y = states[y_index]\n            dLdy = -states[dLdy_index]\n            with torch.enable_grad():\n                f, y2, tensor_params2 = pfunc2(t, y, tensor_params)\n            allgradinputs = ([y2] + list(tensor_params2))\n            # allgradinputs = list(tensor_params2)\n            allgrads = torch.autograd.grad(f,\n                                           inputs=allgradinputs,\n                                           grad_outputs=dLdy,\n                                           retain_graph=True,\n                                           allow_unused=True,\n                                           create_graph=torch.is_grad_enabled())  # list of (*ny)\n            allgrads = convert_none_grads_to_zeros(allgrads, allgradinputs)\n            outs = (\n                f,  # dydt\n                *allgrads,\n            )\n            return outs\n\n        ts_flip = ts.flip(0)\n        t_flip_idx = -1\n        states[y_index] = yt[t_flip_idx]\n        states[dLdy_index] = grad_yt[t_flip_idx]\n        # states[dLdt_index] = torch.zeros_like(ts[0])\n        states[dLdp_slice] = [torch.zeros_like(tp) for tp in tensor_params]\n        grad_ts = [None for _ in range(len(ts))] if ts_requires_grad else None\n\n        for i in range(len(ts_flip) - 1):\n            # sprint(i)\n            # print(states[-1])\n            t_flip_idx -= 1\n            # ctx.bck_config[\"methods\"] = 'rk4'\n            outs = solve_ivp(new_pfunc, ts_flip[i:i + 2], states, tensor_params,\n                             fwd_options=ctx.bck_config, bck_options=ctx.bck_config, method=\"rk4\")\n            # only take the output for the earliest time\n            states = [out[-1] for out in outs]\n            states[y_index] = yt[t_flip_idx]\n            # gyt is the contribution from the input grad_y\n            # gy0 is the propagated gradients from the later time step\n            states[dLdy_index] = grad_yt[t_flip_idx] + states[dLdy_index]\n        for ii in range(len(states)):\n            states[ii] = states[ii].to(ts.device)\n\n        # if ts_requires_grad:\n        #     grad_ts[0] = states[dLdt_index].reshape(-1)\n\n        grad_y0 = states[dLdy_index]  # dL/dy0, (*ny)\n        if ts_requires_grad:\n            grad_ts = torch.cat(grad_ts).reshape(*ts.shape)\n        grad_tensor_params = states[dLdp_slice]\n        grad_ntensor_params = [None for _ in range(len(allparams) - ntensor_params)]\n        grad_params = param_sep.reconstruct_params(grad_tensor_params, grad_ntensor_params)\n        return (None, grad_ts, None, None, None, grad_y0, *grad_params)\n\n\n# docstring completion\nivp_methods = {\n    \"rk45\": rk45_adaptive,\n    \"rk23\": rk23_adaptive,\n    \"rk4\": rk4_ivp,\n}\nsolve_ivp.__doc__ = get_methods_docstr(solve_ivp, ivp_methods)\n\n\n###################################################\n################### GLV model #####################\n###################################################\n\nclass CancerODEGlv_CPU(xitorch.EditableModule):\n\n    def __init__(self, patientNo, **params):\n        # self.r = params[\"r\"]\n        self.A = params[\"A\"]\n        self.K = params[\"K\"]\n        self.pars = params[\"pars\"]\n        self.data = LoadData()._Patient_data(patientNo)\n        if patientNo == \"patient002\":\n            self.data = self.data[:84]\n        if patientNo == \"patient046\":\n            self.data[43:46, 1] -= 10\n        if patientNo == \"patient056\":\n            self.data[46, 1] = (self.data[44, 1] + self.data[48, 1]) / 2\n        if patientNo == \"patient086\":\n            self.data[1, 1] = (self.data[1, 1] + self.data[8, 1]) / 2\n        if patientNo == \"patient104\":\n            self.data = self.data[:(-3)]\n        # normalization of drug\n        self.CPA = torch.from_numpy(self.data[:, 2]).float()\n        self.LEU = torch.from_numpy(self.data[:, 3]).float()\n        self.Days = torch.from_numpy(self.data[:, 6] - self.data[0, 6]).float()\n        self.OnOff = self.data[:, 5];\n        # self.pre_leu()\n        self.Response = self.drug_response(\n            torch.linspace(start=self.Days[0], end=self.Days[-1], steps=int(self.Days[-1] - self.Days[0]) + 1))\n        self.cell_size = 5.236e-10  # 4. / 3. * 3.1415926 * (5e-4cm) ** 3   # cm^3\n\n    def drug_response(self, t):\n        drug = torch.zeros((t.shape[0], 2), dtype=torch.float)\n        slice0 = torch.bucketize(t, self.Days, right=True) - 1\n        slice_75 = torch.where(self.LEU == 7.5)[0]\n        dose75_date = self.Days[slice_75]\n        slice_225 = torch.where(self.LEU == 22.5)[0]\n        dose225_date = self.Days[slice_225]\n        slice_30 = torch.where(self.LEU == 30)[0]\n        dose30_date = self.Days[slice_30]\n        slice_45 = torch.where(self.LEU == 45)[0]\n        dose45_date = self.Days[slice_45]\n\n        I0_CPA_dose = self.CPA[slice0]\n        I0_LEU_dose = self.LEU[slice0] # LEu dose has 7.5/22.5/30/45, 4 different dosages, for 4/12/16/24 weeks, and we can see that no matter\n        dose75 = dose225 = dose30 = dose45 = 1\n        _date = -100\n        for date in dose75_date.int():\n            if abs(date - _date) < 7 or abs(date - _date) == 7:\n                dose75 += 1\n            else:\n                dose75 = 1\n            if dose75 == 1:\n                temp = torch.zeros(28, dtype = torch.float)  # last 12 weeks\n                temp[0:7 * 1] = - 3.75 / 6 * torch.arange(0, 7, 1)\n                temp[(7 * 1):(7 * 3)] = (7.5 + 3.75) / (20 - 6) * torch.arange(7, 21, 1) + (\n                            7.5 - (7.5 + 3.75) / (20 - 6) * 20)\n                temp[(7 * 3):] = 7.5\n                I0_LEU_dose[date: (date + 7 * 4)] = temp[0:I0_LEU_dose[date: (date + 7 * 4)].size(0)]\n            else:\n                I0_LEU_dose[_date: (date + 7 * 4)] = 7.5\n            _date = date + 7 * 4\n        _date = -100\n        for date in dose225_date.int():\n            if abs(date - _date) <  7 or abs(date - _date) == 7:\n                dose225 += 1\n            else:\n                dose225 = 1\n            if dose225 == 1:\n                temp = torch.zeros(7*12, dtype = torch.float) # last 12 weeks\n                temp[0:7*1] = - 3.75/6 * torch.arange(0,7,1)\n                temp[(7*1):(7*3)] = (7.5 + 3.75)/(20-6) *torch.arange(7, 21, 1) +(7.5 -  (7.5 + 3.75)/(20-6)*20)\n                temp[(7*3):] = 7.5\n                I0_LEU_dose[date: (date + 7 * 12)] = temp[0:I0_LEU_dose[date: (date + 7 * 12)].size(0)]\n            else:\n                I0_LEU_dose[_date: (date + 7 * 12)] = 7.5\n            _date = date + 7 * 12\n\n        _date = -100\n        for date in dose30_date.int():\n            if abs(date - _date) <  7 or abs(date - _date) == 7:\n                dose30 += 1\n            else:\n                dose30 = 1\n            if dose30 == 1:\n                temp = torch.zeros(7*16, dtype = torch.float)  # last 12 weeks\n                temp[0:7 * 1] = - 3.75 / 6 * torch.arange(0, 7, 1)\n                temp[(7 * 1):(7 * 3)] = (7.5 + 3.75) / (20 - 6) * torch.arange(7, 21, 1) + (\n                            7.5 - (7.5 + 3.75) / (20 - 6) * 20)\n                temp[(7 * 3):] = 7.5\n                I0_LEU_dose[date: (date + 7 * 16)] = temp[0:I0_LEU_dose[date: (date + 7 * 16)].size(0)]\n            else:\n                I0_LEU_dose[_date: (date + 7 * 16)] = 7.5\n            _date = date + 7 * 16\n        _date = -100\n        for date in dose45_date.int():\n            if abs(date - _date) <  7 or abs(date - _date) == 7:\n                dose45 += 1\n            else:\n                dose45 = 1\n            if dose45 == 1:\n                temp = torch.zeros(7 * 24, dtype = torch.float)  # last 12 weeks\n                temp[0:7 * 1] = - 3.75 / 6 * torch.arange(0, 7, 1)\n                temp[(7 * 1):(7 * 3)] = (7.5 + 3.75) / (20 - 6) * torch.arange(7, 21, 1) + (\n                            7.5 - (7.5 + 3.75) / (20 - 6) * 20)\n                temp[(7 * 3):] = 7.5\n                I0_LEU_dose[date: (date + 7 * 24)] = temp[0:I0_LEU_dose[date: (date + 7 * 24)].size(0)]\n            else:\n                I0_LEU_dose[_date: (date + 7 * 24)] = 7.5\n            _date = date + 7 * 24\n\n        I0_LEU_dose[torch.cat((torch.where(I0_LEU_dose == 22.5)[0],torch.where(I0_LEU_dose == 30)[0],torch.where(I0_LEU_dose == 45)[0]))] = 7.5\n        I0_LEU_dose = I0_LEU_dose / 7.5\n        I0_CPA_dose = I0_CPA_dose / 200\n        for ii in range(1, I0_LEU_dose.shape[0] - 1):\n            if  I0_LEU_dose[ii+1] < 0 and I0_LEU_dose[ii-1] == 1.:\n                I0_LEU_dose[ii : (ii + 7 * 3)] = 1.\n        drug[:, 0] = I0_CPA_dose\n        drug[:, 1] = I0_LEU_dose\n        return drug\n\n    def forward(self, t, y):\n        r = self.pars[0:2]\n        beta = self.pars[2:4]\n        Beta = torch.zeros((2, 2), dtype=torch.float)\n        Beta[:, 0] = beta\n        phi = self.pars[-4]\n        betac = self.pars[(-2):]\n        A = torch.tensor([1., .5, .5, 1.]).view(2, 2)\n        A[0,1] = 1/(1 + torch.exp(-self.pars[-3] * torch.tensor([t /28/12]))) #+= self.pars[-3] * t /28/12 #\n        # A[0, 1] = a1; A[1, 0] = a2\n        gamma = 0.25  # the half life time for psa is 2.5 days, so each day psa decrease by  25%\n        # drug = torch.zeros((t.shape[0], 2), dtype = torch.float)\n        # slice0 = torch.bucketize(t, self.Days, right = True) - 1\n        # I_CPA_dose = self.CPA[slice0];I_LEU_dose = self.LEU[slice0]\n        index = int(t) if len(t.shape) == 0 else t.int().cpu().numpy()\n        x = y[0:2]  # cell count\n        p = y[-1]  # psa level\n        # comp = torch.tensor([x[0]*2 + x[1]*a, x[0]*a + x[1]*1])\n        dxdt = torch.multiply(\n            r * x, (1 - (x @ A / self.K) ** phi - self.Response[index] @ Beta))  # -\n        # self.Response[index, 0] * self.Response[index, 1] * Mu))\n        dpdt = betac @ x * self.cell_size - gamma * p  # /(abs(sum(dxdt)) + gamma) /(abs(sum(dxdt)*1000/self.K) + gamma)\n        df = torch.zeros(3, dtype=torch.float)\n        df[0:2], df[-1] = dxdt, dpdt\n        return df\n\n    def getparamnames(self, methodname, prefix=\"\"):\n        if methodname == \"forward\":\n            return [prefix + \"A\",  prefix + \"K\", prefix + \"pars\"]  # , prefix+\"beta\", prefix+\"gamma\", prefix+\"alpha\"]\n        else:\n            raise KeyError()\n\ndef MSEloss_weight(inputs, targets, weight):\n    return torch.sum(weight * (inputs - targets) ** 2)\n\n\ndef clip_grad(grad, max_norm: float, norm_type: float = 2.0) -> torch.Tensor:\n\n    max_norm = float(max_norm)\n    norm_type = float(norm_type)\n    if len(grad) == 0:\n        return torch.tensor(0.)\n    device = grad.device\n    total_norm = torch.norm(grad.detach(), norm_type).to(device)\n    clip_coef = max_norm / (total_norm + 1e-6)\n    if clip_coef < 1:\n        grad.detach().mul_(clip_coef.to(grad.device))\n    return total_norm\n\n# As for the determination of the initial value, we define if psa =10, the cell count for AD is 1e8\n\nfrom collections import deque\n\ndef train_glv(args, alldata):\n\n    i = args.number\n    fail_deque =  deque(maxlen = 10)\n    alpha = 0.25 #Alpha[i]\n    # under_i = [4, 13, 19, 54, 60, 83, 87, 95, 96, 100, 101, 105]\n    # if i in under_i:\n    #     alpha = 0.5\n    cell_size = 5.236e-10\n    fail_flag = False\n    if len(str(i)) == 1:\n        patientNo = \"patient00\" + str(i)\n    elif len(str(i)) == 2:\n        patientNo = \"patient0\" + str(i)\n    else:\n        patientNo = \"patient\" + str(i)\n    print(patientNo)\n\n    # PARS = np.array(pd.read_csv(\"PARS.csv\"), dtype=np.float).reshape(-1)\n    # if patientNo in [\"patient012\",\"patient015\" ,\"patient006\"]:\n    #     continue\n    data = alldata[patientNo]\n    if patientNo == \"patient002\":\n        data = data[:84]\n    if patientNo == \"patient046\":\n        data[43:46, 1] -= 10\n    if patientNo == \"patient056\":\n        data[46, 1] = (data[44,1] + data[48,1])/2\n    if patientNo == \"patient086\":\n        data[1,1] = (data[1,1]+data[8,1])/2\n    if patientNo == \"patient104\":\n        data = data[:(-3)]\n    Days = data[:, 6] - data[0, 6]\n    OnOff = data[:, 5]\n    Cycle = data[:,-3]\n    PSA = data[:, 1]\n    index = np.where(np.isnan(PSA))[0]\n    PSA = torch.from_numpy(np.delete(PSA, index)).float()\n    DAYS = np.delete(Days, index)\n    treatInt = [0.]\n    validate_set = deque(maxlen=int(Cycle[-1]))\n    for ii in range(1, OnOff.shape[0] - 1):\n        if OnOff[ii - 1] == 1 and OnOff[ii] == 0:\n            treatInt.append(Days[ii])\n        if OnOff[ii - 1] == 0 and OnOff[ii] == 1:\n            treatInt.append(Days[ii])\n    treatInt.append(Days[-1])\n    slicing = np.digitize(treatInt, DAYS, right=True)\n    for kk in np.arange(slicing.shape[0]-1, step = 2):\n        if kk + 2 < slicing.shape[0]:\n            loo = np.random.choice(DAYS[slicing[kk] + 1:slicing[kk + 2]])\n        elif kk + 2 >= slicing.shape[0] and DAYS[slicing[kk]+1:].size != 0:\n            loo = np.random.choice(DAYS[slicing[kk]+1:])\n        else:\n            break\n        validate_set.append(loo)\n    validate_days = np.array(validate_set, dtype=np.int32)\n    validate_psa = PSA[np.isin(DAYS, validate_set)].detach().numpy()\n    train_days = DAYS[~np.isin(DAYS, validate_set)]\n    train_slice = np.digitize(treatInt, train_days, right=True)\n    train_psa = PSA[~np.isin(DAYS, validate_set)]\n    # 5e+8 5cm^3 = 5000mm^3\n    mean_v = 5\n    mean_psa = 22.1\n    K1 = 1.1 * mean_v * (max(PSA)/mean_psa)/cell_size  # 2e+11\n    K2 = alpha * K1\n    K = torch.tensor([K1, K2]) #1.1 * mean_v * (max(PSA)/mean_psa)/cell_size #\n    # r = torch.tensor([1.2, 1.5], dtype = torch.float) # AD is 2 times more responsive compared to AI cell\n    # e = torch.tensor([[0.8], [0.9]], dtype = torch.float) # AD is 5 times more competitive effects exert than AI cells\n    A = torch.tensor([1., .5, 0.5, 1.], dtype=torch.float).view(2, 2)\n    inputs = torch.linspace(start=Days[0], end=Days[-1], steps=int(Days[-1] - Days[0]) + 1, dtype=torch.float)\n    # criterion = nn.MSELoss()\n    # learning_rate = torch.tensor([.00001, .00001, .001, .001, .0001, .00001, .001, .001])\n    # momentum = 0.98\n    # velocity = 0.\n    # pars = torch.tensor([0.05, 0.05, 2, 1, 1., -0.01, 1., 1.]).float().requires_grad_()\n    parsdir = \"./retrain-sigmoid/model_pars\"\n    parslist = os.listdir(parsdir)\n    PARS = torch.zeros(8, dtype = torch.float)\n    # reading the ode parameters and the initial/terminal states\n    for file in parslist:\n        pars_df = pd.read_csv(parsdir + '/' + file)\n        pars = torch.from_numpy(np.array(pars_df.loc[4, ~np.isnan(pars_df.loc[4, :])])).float()\n        PARS += pars\n\n    pars = PARS/len(parslist)\n    pars[-3] = 0\n    # if patientNo in [\"patient063\", \"patient075\", \"patient083\", \"patient050\", \"patient036\", \"patient088\", \"patient105\", \"patient087\", \"patient095\", \"patient101\",\n    #                  \"patient001\", \"patient003\", \"patient004\", \"patient011\", \"patient013\", \"patient046\", \"patient063\", \"patient036\", \"patient062\", \"patient046\",\n    #                  \"patient013\", \"patient016\", \"patient017\", \"patient056\", \"patient071\", \"patient078\", \"patient079\", \"patient091\", \"patient104\", \"patient105\",\n    #                  \"patient032\", \"patient083\", \"patient092\"]:\n    #     pars_df = pd.read_csv(\"./retrain-sigmoid/model_pars\" + '/Args_' + patientNo + \".csv\")\n    #     pars = torch.from_numpy(np.array(pars_df.loc[4, ~np.isnan(pars_df.loc[4, :])])).float()\n    pars = pars.requires_grad_()\n    inits_pars = pars.detach().numpy()\n    loss_deque = deque(maxlen=10)\n    loss = torch.tensor([10000], dtype=torch.float)\n    Epoch = 10000\n    best_loss = 10000\n    best_pars = pars.detach().numpy()\n    cancerode = CancerODEGlv_CPU(patientNo, A=A, K=K, pars=pars)\n    optimizer = torch.optim.Adam([cancerode.pars], lr = .001)\n    scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size =1000, gamma=0.8)\n    # initialize the early_stopping object\n    early_stopping = EarlyStopping(patience=15)\n    if not os.path.exists(\"./analysis-sigmoid\"):\n        os.mkdir(\"./analysis-sigmoid\")\n    if not os.path.exists(\"./analysis-sigmoid/model_infos/\" + patientNo):\n        os.makedirs(\"./analysis-sigmoid/model_infos/\" + patientNo)\n    if not os.path.exists(\"./analysis-sigmoid/model_plots/\" + patientNo):\n        # shutil.rmtree(\"./retrain-sigmoid/model_plots/\" + patientNo)\n        os.makedirs(\"./analysis-sigmoid/model_plots/\" + patientNo)\n    if not os.path.exists(\"./analysis-sigmoid/model_pars/\" + patientNo):\n        os.makedirs(\"./analysis-sigmoid/model_pars/\" + patientNo)\n    if not os.path.exists(\"./analysis-sigmoid/model_validate\"):\n        os.makedirs(\"./analysis-sigmoid/model_validate\")\n    log = []\n    t = datetime.now().strftime(\"%Y%m%d-%H%M\")\n    summary_dir = \"./analysis-sigmoid/model_infos\" + '/' + str(patientNo) + '/' + str(t) + \"/\" + str(args.t)\n    writer = SummaryWriter(log_dir=summary_dir)\n    for epoch in range(Epoch):\n        Init = torch.tensor([mean_v/mean_psa * PSA[0]/cell_size, 1e-4 * K2, PSA[0]], dtype=torch.float)\n        _loss = loss.detach().numpy()\n        _pars = pars.detach().numpy()\n        loss = torch.zeros(1, dtype=torch.float)\n\n        res = Init.detach().numpy().reshape(1, -1)\n        optimizer.zero_grad()\n        for ii in range(len(treatInt) - 1):\n            if ii == len(treatInt) - 2:\n                INPUTS = inputs[int(treatInt[ii]):]\n            else:\n                INPUTS = inputs[int(treatInt[ii]):int(treatInt[ii + 1])]\n            ts = INPUTS.requires_grad_(False)\n            OUT = solve_ivp(cancerode.forward, ts=ts, y0=Init, params=(), atol=1e-08, rtol=1e-05)\n            res = np.append(res, OUT.detach().numpy(), axis=0)\n            d = train_days[train_slice[ii]:train_slice[ii + 1]]\n            slicing1 = np.digitize(d, INPUTS, right=True)\n            EST_PSA = OUT[slicing1, -1]\n            EST_PSA[torch.isnan(EST_PSA)] = 1000\n            psa = train_psa[train_slice[ii]: train_slice[ii + 1]]\n            if ii == 0:\n                psa[0] = Init[-1]\n            Init = OUT[-1]\n            weights = 1.\n            n_psa = psa.shape[0]\n            if ii % 2 == 0:\n                weights = torch.linspace(start=1, end=n_psa, steps=n_psa)\n            if ii % 2 == 1:\n                weights = torch.linspace(start=n_psa, end=1, steps=n_psa)\n            weights = weights/sum(weights)\n            loss = MSEloss_weight(EST_PSA, psa, weights) #+ loss\n            loss.backward(retain_graph=True if ii != len(treatInt) - 2 else False)\n\n        # pars_grad = torch.autograd.grad(loss, (cancerode.pars,))[0]\n        # clip_grad(pars_grad, max_norm=10);\n        # velocity = momentum * velocity - learning_rate * pars_grad # pars_grad\n        # pars = pars.add(velocity)  # .detach().requires_grad_()\n        # optimizer.zero_grad()\n        # loss.backward()\n        torch.nn.utils.clip_grad_norm_(pars, max_norm = 100 * (1.001 - epoch/Epoch))\n        optimizer.step()\n        with torch.no_grad():\n            pars[:2].clamp_( min = 5e-3, max = 1e-1)\n            pars[2:4].clamp_( min=0)\n            pars[-2:].clamp_( min=1e-3)\n        scheduler.step()\n        # cancerode.pars = pars\n        pars_grad = pars.grad\n        flag_pars = pars_grad.detach().numpy()[-3]\n        # avoiding over-fitted\n        loss_deque.append(_loss)\n        print(pars.detach().numpy())\n        loss_array = np.array(loss_deque, dtype=np.float).reshape(-1)\n        if epoch > 10:\n            loss_decay_mask = sum((loss_array[1:] - loss_array[:-1]) / loss_array[:-1] > 0)\n\n        if loss.detach().numpy().item() < best_loss:\n            best_loss = loss.detach().numpy().item()\n            best_pars = pars.detach().numpy()\n\n        with torch.no_grad():\n            res = res[1:]\n            ad = res[:, 0]\n            ai = res[:, 1]\n            p = res[:, 2]\n            val_psa = p[validate_days]\n            validate_loss = np.mean((val_psa - validate_psa) ** 2)\n            # log.append([epoch, loss.detach().numpy().item(), validate_loss])\n            writer.add_scalar('Loss', loss.detach().numpy().item(), epoch)\n            writer.add_scalar('V-Loss', validate_loss, epoch)\n            # if epoch % 50 == 0:\n            #     file_writing_obj = open('./analysis-sigmoid/model_infos/infos-' + patientNo + \"-\" + str(args.t) + '.txt', 'w')\n            #     file_writing_obj.write(str(log))\n            #     file_writing_obj.close()\n                #print('Epoch: {} \\t Loss: {:.2f} \\t Val_Loss: {:.2f}'.format(epoch, loss.detach().numpy().item(), validate_loss))\n            if epoch % 100 == 0:\n                # x = inputs.detach().numpy()\n                # plt.scatter(DAYS, PSA, color=\"black\", marker=\"*\", alpha=0.6)\n                # plt.plot(x, p, color=\"black\", linestyle=\"-\", linewidth=1)\n                # plt.xlabel(\"Time (Days)\" )\n                # plt.ylabel(\"PSA level (ug/ml)\")\n                # plt.savefig(\"./analysis-sigmoid/model_plots/\"+patientNo+\"/PSA_\" + str(args.t) + \"-\" + patientNo + \"_\" + str(epoch) + \".png\", dpi=100)\n                # # plt.show()\n                # plt.close()\n                # plt.plot(x, ad, color=\"black\", linestyle=\"--\", linewidth=1, label=\"AD\")\n                # plt.plot(x, ai, color=\"black\", linestyle=\"-.\", linewidth=1, label=\"AI\")\n                # plt.xlabel(\"Time (Days)\")\n                # plt.ylabel(\"Cell counts\")\n                # plt.legend(loc='upper right')\n                # plt.savefig(\"./analysis-sigmoid/model_plots/\"+patientNo+\"/Cell_All_\" + str(args.t) + \"-\" + patientNo + \"_\" + str(epoch) + \".png\", dpi=100)\n                # # plt.show()\n                # plt.close()\n                # plt.plot(x, ai, color=\"black\", linestyle=\"-.\", linewidth=1, label=\"AI\")\n                # plt.xlabel(\"Time (Days)\")\n                # plt.ylabel(\"Cell counts\")\n                # plt.savefig(\"./analysis-sigmoid/model_plots/\"+patientNo+\"/Cell_AI_\" + str(args.t) + \"-\" + patientNo + \"_\" + str(epoch) + \".png\", dpi=100)\n                # # plt.show()\n                # plt.close()\n                A1 = A.detach().numpy().reshape(-1)\n                K1 = K.detach().numpy()\n                terminate = res[-1]\n                init = Init.detach().numpy()\n                states1 = np.append(init, terminate)\n                pars_detach = pars.detach().numpy()\n                plist = [A1, K1, states1, pars_detach, best_pars]\n                plist_df = pd.DataFrame(plist)\n                plist_df.to_csv(\"./analysis-sigmoid/model_pars/\"+patientNo+\"/Args_\" + str(args.t) + \"-\" + patientNo + \".csv\",\n                                index=False)\n        if epoch > 2000:\n            early_stopping(validate_loss, pars)\n        if early_stopping.early_stop:\n            print(\"Early stopping\")\n            break\n\n    Init = torch.tensor([mean_v/mean_psa * PSA[0]/cell_size, 1e-4 * K2, PSA[0]], dtype=torch.float)\n    cancerode = CancerODEGlv_CPU(patientNo, A=A, K=K, pars=pars)\n    out = solve_ivp(cancerode.forward, ts=inputs, y0=Init, params=(), atol=1e-08, rtol=1e-05)\n    ad = out[:, 0].detach().numpy()\n    ai = out[:, 1].detach().numpy()\n    psa = out[:, -1].detach().numpy()\n    pred_validate_psa = psa[validate_days]\n    validate_loss = np.array([sum((pred_validate_psa - validate_psa)**2)], dtype = np.float)\n    validate_list = [validate_psa, pred_validate_psa, validate_loss]\n    validate_df = pd.DataFrame(validate_list, index = [\"true\", 'predict', 'loss'])\n    validate_df.to_csv(\"./analysis-sigmoid/model_validate/\" + patientNo + \"/validate_\" + str(args.t) + \"-\" + patientNo + \".csv\", index=True)\n    print(validate_loss)\n    x = inputs.numpy()\n    plt.scatter(DAYS, PSA, color=\"black\", marker=\"*\", alpha=0.6)\n\n    plt.plot(x, psa, color=\"black\", linestyle=\"-\", linewidth=1)\n    plt.xlabel(\"Time (Days)\")\n    plt.ylabel(\"PSA level (ug/ml)\")\n    plt.savefig(\"./analysis-sigmoid/model_plots/\"+patientNo+\"/Final_PSA_\" + str(args.t) + \"-\" + patientNo + \".png\", dpi=300)\n    plt.close()\n\n    plt.plot(x, ad, color=\"black\", linestyle=\"--\", linewidth=1, label=\"AD\")\n    plt.plot(x, ai, color=\"black\", linestyle=\"-.\", linewidth=1, label=\"AI\")\n    plt.xlabel(\"Time (Days)\")\n    plt.ylabel(\"Cell counts\")\n    plt.legend(loc='upper right')\n    plt.savefig(\"./analysis-sigmoid/model_plots/\"+patientNo+\"/Final_Cell_\" + str(args.t) + \"-\" + patientNo + \".png\", dpi=300)\n    plt.close()\n\n    # competition strength\n    c = (out[:, :2] @ A[:, 1] / K[1]) ** pars[-3]\n    cc = c.detach().numpy()\n    plt.plot(x, cc, color=\"b\", linestyle=\"-\", linewidth=1, label=\"Competition for AI\")\n    plt.savefig(\"./analysis-sigmoid/model_plots/\"+patientNo+\"/Final_Competition_\" + str(args.t) + \"-\" + patientNo + \".png\", dpi=300)\n    plt.close()\n\n    A = A.detach().numpy().reshape(-1)\n    K = K.detach().numpy()\n    terminate = out[-1].detach().numpy()\n    init = Init.detach().numpy()\n    states = np.append(init, terminate)\n    pars_detach = pars.detach().numpy()\n    plist = [A, K, states, pars_detach, best_pars]\n    plist_df = pd.DataFrame(plist)\n    plist_df.to_csv(\"./analysis-sigmoid/model_pars/\"+patientNo+\"/Args_\" + str(args.t) + \"-\" + patientNo + \".csv\", index=False)\n\n\nparser = argparse.ArgumentParser(description='Patient arguments')\nparser.add_argument('--number', '-n', help='Patient No., int type, requested', default=13, type = int)\nparser.add_argument('--t',  default=0, type = int)\nargs = parser.parse_args()\n\nif __name__ == \"__main__\":\n    alldata =  LoadData().Double_Drug()\n    train_glv(args, alldata)\n\n", "meta": {"hexsha": "d70fda04bd952efb63b611fa198f650710d1c1a8", "size": 33165, "ext": "py", "lang": "Python", "max_stars_repo_path": "GLV/ode_model_test.py", "max_stars_repo_name": "Michaelrising/PPO-PyTorch", "max_stars_repo_head_hexsha": "171256881f11a7bf18e51baa843004abebc18267", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GLV/ode_model_test.py", "max_issues_repo_name": "Michaelrising/PPO-PyTorch", "max_issues_repo_head_hexsha": "171256881f11a7bf18e51baa843004abebc18267", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GLV/ode_model_test.py", "max_forks_repo_name": "Michaelrising/PPO-PyTorch", "max_forks_repo_head_hexsha": "171256881f11a7bf18e51baa843004abebc18267", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.9390243902, "max_line_length": 162, "alphanum_fraction": 0.5632142319, "include": true, "reason": "import numpy", "num_tokens": 9466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.17345965265230104}}
{"text": "from collections  import namedtuple\r\nfrom itertools    import count\r\nfrom glob         import glob\r\nfrom time         import time, sleep\r\n\r\nfrom .synthesis    import Synthesis\r\nfrom .utils        import Fold\r\nfrom .kmerSetDB    import kmerSetDB\r\nfrom .kmerSetArray import kmerSetArray\r\n\r\nimport sys\r\nimport numpy\r\nimport uuid\r\nimport math\r\nimport textwrap\r\n\r\nfrom . import utils\r\nfrom . import makerchecks\r\nfrom . import projector\r\nfrom . import berno\r\nfrom . import finder\r\n\r\nfrom Bio.SeqUtils import MeltingTemp\r\n\r\n\r\nclass NRPMaker(object):\r\n\r\n    def __init__(self, part_type='RNA', seed=None):\r\n\r\n        # Instance variables\r\n        self.part_type  = part_type\r\n        self.synthesis  = Synthesis()\r\n        self.fold       = Fold(part_type=part_type)\r\n        self.proj_id    = str(uuid.uuid4())\r\n        self.kmer_db    = None\r\n        self.background = None\r\n\r\n        # Seed the RNG\r\n        if not seed is None and isinstance(seed, int):\r\n            self.rng = numpy.random.default_rng(seed=seed)\r\n        else:\r\n            self.rng = numpy.random.default_rng()\r\n\r\n        # Lookup tables\r\n        if self.part_type == 'RNA':\r\n            self.iupac_space = {\r\n                'A': {'A'},\r\n                'C': {'C'},\r\n                'G': {'G'},\r\n                'U': {'U'},\r\n                'R': {'A', 'G'},\r\n                'Y': {'C', 'U'},\r\n                'S': {'G', 'C'},\r\n                'W': {'A', 'U'},\r\n                'K': {'G', 'U'},\r\n                'M': {'A', 'C'},\r\n                'B': {'C', 'G', 'U'},\r\n                'V': {'A', 'C', 'G'},\r\n                'D': {'A', 'G', 'U'},\r\n                'H': {'A', 'C', 'U'},\r\n                'N': {'A', 'U', 'G', 'C'}\r\n            }\r\n            self.iupac_compl = {\r\n                'A': 'U', # A - U\r\n                'C': 'G', # C - G\r\n                'G': 'Y', # G - C U - Y\r\n                'U': 'R', # U - A G - R\r\n                'R': 'Y', # R - A G - U C - Y\r\n                'Y': 'R', # Y - C U - G A G - R\r\n                'S': 'B', # S - G C - C G U - B\r\n                'W': 'D', # W - A U - U A G - D\r\n                'K': 'N', # K - G U - C U G A\r\n                'M': 'K', # M - A C - U G - K\r\n                'B': 'N', # B - C G U - G C U A - N\r\n                'V': 'D', # V - A C G - U G A - D\r\n                'D': 'N', # D - A G U - U C A G - N\r\n                'H': 'N', # H - A C U - U G A G - N\r\n                'N': 'N'\r\n            }\r\n            self.base_compl = {\r\n                'A': ['U'],\r\n                'G': ['C', 'U'],\r\n                'C': ['G'],\r\n                'U': ['A', 'G']\r\n            }\r\n        else:\r\n            self.iupac_space = {\r\n                'A': {'A'},\r\n                'C': {'C'},\r\n                'G': {'G'},\r\n                'T': {'T'},\r\n                'R': {'A', 'G'},\r\n                'Y': {'C', 'T'},\r\n                'S': {'G', 'C'},\r\n                'W': {'A', 'T'},\r\n                'K': {'G', 'T'},\r\n                'M': {'A', 'C'},\r\n                'B': {'C', 'G', 'T'},\r\n                'V': {'A', 'C', 'G'},\r\n                'D': {'A', 'G', 'T'},\r\n                'H': {'A', 'C', 'T'},\r\n                'N': {'A', 'T', 'G', 'C'}\r\n            }\r\n            self.iupac_compl = {\r\n                'A': 'T', # A - T\r\n                'C': 'G', # C - G\r\n                'G': 'C', # G - C\r\n                'T': 'A', # T - A\r\n                'R': 'Y', # R - A G - T C - Y\r\n                'Y': 'R', # Y - C T - G A - R\r\n                'S': 'S', # S - G C - C G - S\r\n                'W': 'W', # W - A T - T A - W\r\n                'K': 'M', # K - G T - C A - M\r\n                'M': 'K', # M - A C - T G - K\r\n                'B': 'V', # B - C G T - G C A - V\r\n                'V': 'B', # V - A C G - T G C - B\r\n                'D': 'H', # D - A G T - T C A - H\r\n                'H': 'D', # H - A C T - T G A - D\r\n                'N': 'N'\r\n            }\r\n            self.base_compl = {\r\n                'A': ['T'],\r\n                'G': ['C'],\r\n                'C': ['G'],\r\n                'T': ['A']\r\n            }\r\n\r\n    def _get_adjusted_struct(self, struct, seq):\r\n        if struct is None:\r\n            return '.'*len(seq)\r\n        elif len(seq) < len(struct):\r\n            return struct[:len(seq)]\r\n        elif len(seq) > len(struct):\r\n            return ''.join([struct, '.'*(len(seq) - len(struct))])\r\n        return struct\r\n\r\n    def _get_meta_struct(self, struct):\r\n        struct_spec   = namedtuple(\r\n            'struct_spec', 'struct paired_dict rev_paired_dict unpaired_set folding inversefolding')\r\n        pairing_stack = []\r\n        meta_struct   = struct_spec(\r\n            struct=struct.replace('x', '.'),\r\n            paired_dict={},\r\n            rev_paired_dict={},\r\n            unpaired_set=set(),\r\n            folding={},\r\n            inversefolding={})\r\n\r\n        for index, nt in enumerate(struct):\r\n\r\n            if nt == '(':\r\n                pairing_stack.append(index)\r\n\r\n            elif nt == ')':\r\n\r\n                try:\r\n                    closure = pairing_stack.pop()\r\n                except:\r\n                    raise ValueError(\r\n                        ' [X] Unbalanced parentheses in structure constraint')\r\n\r\n                meta_struct.paired_dict[closure]   = index\r\n                meta_struct.rev_paired_dict[index] = closure\r\n\r\n            elif nt == 'x':\r\n                meta_struct.unpaired_set.add(index)\r\n\r\n        if pairing_stack:\r\n            raise ValueError(\r\n                ' [X] Unbalanced parentheses in structure constraint')\r\n\r\n        if meta_struct.paired_dict:\r\n            meta_struct.folding['status'] = True\r\n            meta_struct.inversefolding['status'] = True\r\n        elif meta_struct.unpaired_set:\r\n            meta_struct.folding['status'] = True\r\n            meta_struct.inversefolding['status'] = False\r\n        else:\r\n            meta_struct.folding['status'] = False\r\n            meta_struct.inversefolding['status'] = False\r\n\r\n        return meta_struct\r\n\r\n    def _get_meta_seq(self, seq, meta_struct):\r\n        seq = list(seq)\r\n        meta_seq = [None] * len(seq)\r\n\r\n        # Normalize Meta Sequence\r\n        for i in range(len(seq)):\r\n            try:\r\n                if i in meta_struct.paired_dict:\r\n                    j = meta_struct.paired_dict[i]\r\n                    if len(self.iupac_space[seq[j]]) < len(self.iupac_space[seq[i]]):\r\n                        seq[i] = self.iupac_compl[seq[j]]\r\n                    elif len(self.iupac_space[seq[i]]) < len(self.iupac_space[seq[j]]):\r\n                        seq[j] = self.iupac_compl[seq[i]]\r\n                meta_seq[i] = set(self.iupac_space[seq[i]])\r\n            except:\r\n                raise ValueError(\r\n                    ' [X] Invalid IUPAC code at index {} in sequence constraint'.format(i))\r\n\r\n        return tuple(meta_seq)\r\n\r\n    def _reset_candidate_kmer_set(\r\n        self,\r\n        candidate,\r\n        kmer_set,\r\n        i):\r\n        candidate[i] = '-'\r\n        kmer_set[i]  = ' '\r\n\r\n    def _clear_path(\r\n        self,\r\n        candidate,\r\n        tried_set,\r\n        kmer_set,\r\n        i,\r\n        k):\r\n        j = i\r\n        while j > k:\r\n            self._reset_candidate_kmer_set(\r\n                candidate,\r\n                kmer_set,\r\n                j)\r\n            tried_set[j] = set()\r\n            # tried_set[j] = set(candidate[j])\r\n            j -= 1\r\n        else:\r\n            self._reset_candidate_kmer_set(\r\n                candidate,\r\n                kmer_set,\r\n                j)\r\n        i = j\r\n        return i\r\n\r\n    def _get_rollback_index(\r\n        self,\r\n        meta_seq,\r\n        meta_struct,\r\n        i,\r\n        homology,\r\n        candidate,\r\n        tried_set):\r\n        roll_back_index = None\r\n        # See if any position in last homology places has potential for change\r\n        j = i\r\n        while (j >= i - homology + 1) and (j >= 0):\r\n            # Case ( or . with potential for change\r\n            if not (j in meta_struct.rev_paired_dict):\r\n                if len(meta_seq[j]) > len(tried_set[j]):\r\n                    roll_back_index = j\r\n                    break\r\n            # Case ) for RNA Parts with potential for change\r\n            else:\r\n                l = meta_struct.rev_paired_dict[j]\r\n                pnt = meta_seq[j]\r\n                pnt = pnt.intersection(\r\n                    self.base_compl[candidate[l]])\r\n                if len(tried_set[j]) < len(pnt):\r\n                    roll_back_index = j\r\n                    break\r\n            j -= 1\r\n        # Else go to the ( for the first ) in the last homology places\r\n        if not roll_back_index:\r\n            j = max(0, i - homology + 1)\r\n            k = None\r\n            while j <= i:\r\n                if j in meta_struct.rev_paired_dict:\r\n                    k = j\r\n                    break\r\n                j += 1\r\n            roll_back_index = meta_struct.rev_paired_dict[k]\r\n        return roll_back_index\r\n\r\n    def _roll_back(\r\n        self,\r\n        meta_seq,\r\n        meta_struct,\r\n        i,\r\n        homology,\r\n        candidate,\r\n        tried_set,\r\n        kmer_set,\r\n        rbi=None):\r\n        # Default Case: Explicit roll back\r\n        if not rbi is None:\r\n\r\n            # traceback to ( if corresponding ) given\r\n            if rbi in meta_struct.rev_paired_dict:\r\n                j = meta_struct.rev_paired_dict[rbi]\r\n                pnt = meta_seq[rbi]\r\n                pnt = pnt.intersection(\r\n                    self.base_compl[candidate[j]])\r\n                # No potential for change\r\n                if len(pnt) == len(tried_set[i]):\r\n                    rbi = j\r\n\r\n            self._clear_path(\r\n                candidate, tried_set, kmer_set, i, k=rbi)\r\n            return rbi\r\n\r\n        # Case 1: i is not paired upstream\r\n        if not i in meta_struct.rev_paired_dict:\r\n            self._reset_candidate_kmer_set(\r\n                candidate, kmer_set, i)\r\n\r\n        # Case 2: i is paired upstream\r\n        else:\r\n            roll_back_index = self._get_rollback_index(\r\n                meta_seq, meta_struct, i, homology, candidate, tried_set)\r\n            i = self._clear_path(\r\n                candidate, tried_set, kmer_set, i, k=roll_back_index)\r\n\r\n        return i\r\n\r\n    def _get_local_roll_back_index(\r\n        self,\r\n        candidate,\r\n        i,\r\n        local_model_fn,\r\n        verbose):\r\n        # Prep candidate\r\n        candidate_str = ''.join(candidate)\r\n        candidate_str = candidate_str[:i+1]\r\n\r\n        # Try to evaluate the local_model_fn on candidate_str\r\n        outcome = True\r\n        try:\r\n            outcome = local_model_fn(candidate_str)\r\n            if outcome in [True, False]:\r\n                state, index = outcome, i\r\n            else:\r\n                state, index = outcome\r\n        except Exception as e:\r\n            print(' Local Model fn. failed to evaluate partial path: {}\\n'.format(\r\n                candidate_str))\r\n            raise e # No intelligence, halt everything!\r\n\r\n        # State satisfactory?\r\n        try:\r\n            assert state in [True, False]\r\n        except Exception as e:\r\n            print(' Local Model fn. failed to evaluate partial path: {}'.format(\r\n                candidate_str))\r\n            print(' Local Model fn. returned a non-boolean evaluation: {}\\n'.format(\r\n                state))\r\n            raise e\r\n\r\n        # Index satisfactory?\r\n        try:\r\n            if state == False:\r\n                index = int(index)\r\n                assert 0 <= index <= i\r\n        except Exception as e:\r\n            print(' Local Model fn. failed to evaluate partial path: {}'.format(\r\n                candidate_str))\r\n            print(' Local Model fn. returned a non-integer or invalid traceback index: {}\\n'.format(\r\n                index))\r\n            raise e\r\n\r\n        # No conflict found!\r\n        if state:\r\n            return None\r\n        # Conflict Found!\r\n        else:\r\n            return index\r\n\r\n    def _get_non_coding_candidate(\r\n        self,\r\n        meta_seq,\r\n        meta_struct,\r\n        homology,\r\n        local_model_fn,\r\n        verbose,\r\n        jump=False,\r\n        start_seq=None,\r\n        allow_internal_repeat=False):\r\n\r\n        # Setup the data structures\r\n        candidate = ['-'] * len(meta_seq) if not start_seq else list(start_seq)\r\n        tried_set = [set() for _ in range(len(meta_seq))]\r\n        kmer_set  = kmerSetArray(size=len(meta_seq))\r\n\r\n        # Setup indexing\r\n        i               = 0\r\n        roll_back_count = 0\r\n\r\n        # Main backtracking code\r\n        while -1 < i < len(meta_seq):\r\n\r\n            # Jumping out of iteration\r\n            if jump and roll_back_count == homology:\r\n                candidate = None\r\n                break\r\n\r\n            # Try to build a candidate\r\n            if candidate[i] == '-':\r\n\r\n                # Phase determination\r\n                forward = False\r\n                # Case )\r\n                if i in meta_struct.rev_paired_dict:\r\n                    j = meta_struct.rev_paired_dict[i]\r\n                    pnt = meta_seq[i]\r\n                    pnt = pnt.intersection(\r\n                        self.base_compl[candidate[j]])\r\n                    if len(pnt) > len(tried_set[i]):\r\n                        forward = True\r\n                # Case ( and .\r\n                else:\r\n                    if len(tried_set[i]) < len(meta_seq[i]):\r\n                        forward = True\r\n\r\n                # Forward phase - A nucleotide may be chosen\r\n                if forward:\r\n                    # Reset roll_back_count\r\n                    roll_back_count = 0\r\n\r\n                    # Case ( and .\r\n                    if not i in meta_struct.rev_paired_dict:\r\n                        candidate[i] = self.rng.choice(\r\n                            sorted(meta_seq[i]-tried_set[i]))\r\n                        tried_set[i].add(candidate[i])\r\n                        # Case (\r\n                        if i in meta_struct.paired_dict:\r\n                            j = meta_struct.paired_dict[i]\r\n                            # DNA Parts\r\n                            if self.part_type == 'DNA':\r\n                                pnt = self.base_compl[candidate[i]][0]\r\n                                candidate[j] = pnt\r\n                            # RNA Parts\r\n                            else:\r\n                                pnt = meta_seq[j]\r\n                                pnt = pnt.intersection(\r\n                                    self.base_compl[candidate[i]])\r\n                                candidate[j] = self.rng.choice(sorted(pnt))\r\n                            tried_set[j] = set(candidate[j])\r\n                    # Case )\r\n                    else:\r\n                        j = meta_struct.rev_paired_dict[i]\r\n                        # DNA Parts\r\n                        if self.part_type == 'DNA':\r\n                            pnt = self.base_compl[candidate[j]][0]\r\n                            candidate[i] = pnt\r\n                        # RNA Parts\r\n                        else:\r\n                            pnt = pnt - tried_set[i]\r\n                            candidate[i] = self.rng.choice(sorted(pnt))\r\n                        tried_set[i].add(candidate[i])\r\n\r\n                # Backward phase - Nucleotide choices exhausted, so traceback\r\n                else:\r\n                    # Update roll_back_count\r\n                    roll_back_count += 1\r\n\r\n                    # Reset and roll back\r\n                    tried_set[i] = set()\r\n                    kmer_set[i]  = ' '\r\n                    if i > 0:\r\n                        # Clear stuff at current index\r\n                        self._reset_candidate_kmer_set(\r\n                            candidate,\r\n                            kmer_set,\r\n                            i)\r\n                        # Traceback to previous index\r\n                        # since current index done\r\n                        i = self._roll_back(\r\n                            meta_seq,\r\n                            meta_struct,\r\n                            i-1,\r\n                            homology,\r\n                            candidate,\r\n                            tried_set,\r\n                            kmer_set) + 1\r\n                    i -= 1\r\n                    continue\r\n\r\n            # See if built candidate[i] is valid\r\n            # Case ( and .\r\n            elif not i in meta_struct.rev_paired_dict:\r\n                # Wrong nucleotide selected\r\n                if not candidate[i] in meta_seq[i]:\r\n                    self._reset_candidate_kmer_set(\r\n                        candidate=candidate,\r\n                        kmer_set=kmer_set,\r\n                        i=i)\r\n                    tried_set[i] = set()\r\n                    continue\r\n            # Case )\r\n            elif i in meta_struct.rev_paired_dict:\r\n                j = meta_struct.rev_paired_dict[i]\r\n                # Paired bases are not complementary\r\n                # or, Wrong nucleotide selected\r\n                if (not candidate[j] in self.base_compl[candidate[i]]) or \\\r\n                   (not candidate[i] in meta_seq[i]):\r\n                    self._reset_candidate_kmer_set(\r\n                        candidate=candidate,\r\n                        kmer_set=kmer_set,\r\n                        i=i)\r\n                    tried_set[i] = set()\r\n                    continue\r\n\r\n            # See if the local model function is violated\r\n            if local_model_fn:\r\n                rbi = self._get_local_roll_back_index(\r\n                    candidate, i, local_model_fn, verbose)\r\n                # Model function violated, and\r\n                # a traceback location was determined\r\n                if not rbi is None:\r\n                    roll_back_count = 0 if rbi < i else roll_back_count\r\n                    i = self._roll_back(\r\n                        meta_seq,\r\n                        meta_struct,\r\n                        i,\r\n                        homology,\r\n                        candidate,\r\n                        tried_set,\r\n                        kmer_set,\r\n                        rbi)\r\n                    continue\r\n\r\n            # Are either of these mers seen previously?\r\n            mmer_seen = False\r\n            kmer = None\r\n\r\n            # Handle equal internal and shared repeats\r\n            if i >= homology-1:\r\n                # Get the kmer/rmer\r\n                kmer = ''.join(candidate[i-homology+1:i+1])\r\n                rmer = utils.get_revcomp(kmer)\r\n                mmer = min(kmer, rmer)\r\n\r\n                # Case: kmer/rkmer is an internal\r\n                #       repeat to current part\r\n                if not allow_internal_repeat:\r\n                    # Direct repeat\r\n                    if kmer in kmer_set:\r\n                        mmer_seen = True\r\n                    # Inverted repeat\r\n                    elif rmer in kmer_set:\r\n                        mmer_seen = True\r\n                    # Palindrome repeat\r\n                    elif kmer == rmer:\r\n                        mmer_seen = True\r\n\r\n                # Case: mmer is a shared repeat with\r\n                #       a previous part\r\n                if not mmer_seen:\r\n                    if mmer in self.kmer_db:\r\n                        mmer_seen = True\r\n\r\n                # Case: mmer is a shared repeat with\r\n                #       background\r\n                if not mmer_seen:\r\n                    if not self.background is None:\r\n                        if self.background.K == homology:\r\n                            if mmer in self.background:\r\n                                mmer_seen = True\r\n\r\n            # Handle background repeats\r\n            if not mmer_seen and \\\r\n               not self.background is None and \\\r\n               homology != self.background.K:\r\n\r\n                # Determine background K\r\n                K = self.background.K\r\n\r\n                # Check is warranted\r\n                if i >= K-1:\r\n\r\n                    # Get the kmer/rmer\r\n                    kmer = ''.join(candidate[i-K+1:i+1])\r\n                    rmer = utils.get_revcomp(kmer)\r\n                    mmer = min(kmer, rmer)\r\n\r\n                    # Actual check\r\n                    if mmer in self.background:\r\n                        mmer_seen = True\r\n\r\n            # Traceback to eliminate repeat\r\n            if mmer_seen:\r\n                i = self._roll_back(\r\n                    meta_seq,\r\n                    meta_struct,\r\n                    i,\r\n                    homology,\r\n                    candidate,\r\n                    tried_set,\r\n                    kmer_set)\r\n                continue\r\n\r\n            # Everything OK .. insert kmer\r\n            if i >= homology-1:\r\n                kmer_set[i] = kmer\r\n\r\n            # Roll forward\r\n            i += 1\r\n\r\n        # Prepare to return candidate\r\n        del kmer_set\r\n        if candidate is None or '-' in candidate:\r\n            return None\r\n        else:\r\n            return ''.join(candidate)\r\n\r\n    def _get_opt_pass_count(self, meta_struct, synth_opt, global_model_fn):\r\n        opt_criteria_count = 1 # Since candidate must at least be non-repetitive\r\n        if meta_struct.folding['status']:\r\n            opt_criteria_count += 1\r\n        if synth_opt:\r\n            opt_criteria_count += 1\r\n        if global_model_fn:\r\n            opt_criteria_count += 1\r\n        return opt_criteria_count\r\n\r\n    # Diagnostic function -- Shouldn't trigger on experimental changes\r\n    def _is_non_coding_construction_verified(self, meta_seq, meta_struct, candidate):\r\n        i = 0\r\n        while i < len(candidate):\r\n            if not candidate[i] in meta_seq[i]:\r\n                return False,1,i\r\n            if i in meta_struct.paired_dict:\r\n                j = meta_struct.paired_dict[i]\r\n                if not candidate[j] in self.base_compl[candidate[i]]:\r\n                    return False,2,i\r\n            i += 1\r\n        return True,0,0\r\n\r\n    def _is_synthesis_verified(self, candidate):\r\n        return self.synthesis.evaluate(candidate)\r\n\r\n    def _is_structure_verified(self, meta_struct, struct_type, candidate):\r\n        struct_satisfied = 0\r\n\r\n        # Decide which structure criteria to fulfill\r\n        if struct_type == 'centroid':\r\n            candidate_structs = [self.fold.evaluate_centroid(\r\n                candidate)]\r\n        elif struct_type == 'both':\r\n            candidate_structs = [self.fold.evaluate_mfe(\r\n                candidate)]\r\n            candidate_structs.append(self.fold.evaluate_centroid(\r\n                candidate))\r\n        else:\r\n            candidate_structs = [self.fold.evaluate_mfe(\r\n                candidate)]\r\n\r\n        for candidate_struct in candidate_structs:\r\n            vienna_meta_struct = self._get_meta_struct(\r\n                candidate_struct)\r\n            # Ensure all forbidden base indices unpaired\r\n            for bp_closed in meta_struct.unpaired_set:\r\n                if not vienna_meta_struct.struct[bp_closed] == '.':\r\n                    return False\r\n            # Ensure all paired base indices paired as desired\r\n            for bp_open in meta_struct.paired_dict:\r\n                if not bp_open in vienna_meta_struct.paired_dict:\r\n                    break\r\n                else:\r\n                    if meta_struct.paired_dict[bp_open] != vienna_meta_struct.paired_dict[bp_open]:\r\n                        break\r\n            else:\r\n                struct_satisfied += 1\r\n\r\n        # All structure criteria satisfied\r\n        if struct_satisfied == len(candidate_structs):\r\n            return True\r\n        else:\r\n            return False\r\n\r\n    def _get_inverse_fold_candidate(self, start_seq, meta_seq, meta_struct):\r\n        inverse_fold_seq = ''.join(char.lower() if len(meta_seq[i]) == 1 else char for i,char in enumerate(start_seq))\r\n        return self.fold.design(\r\n            seq=inverse_fold_seq, struct=meta_struct.struct).upper()\r\n\r\n    def _get_verified_non_coding_candidate(self,\r\n        homology,\r\n        meta_seq,\r\n        meta_struct,\r\n        struct_type,\r\n        synth_opt,\r\n        local_model_fn,\r\n        global_model_fn,\r\n        jump_count,\r\n        fail_count,\r\n        verbose,\r\n        abortion,\r\n        allow_internal_repeat=False):\r\n\r\n        # Setup counts and variables\r\n        current_jump_count = 0\r\n        current_fail_count = 0\r\n        struct_fail_count  = 0\r\n        synth_fail_count   = 0\r\n        model_fail_count   = 0\r\n        seed_seq           = None\r\n        verified_candidate = None\r\n        opt_pass_count     = self._get_opt_pass_count(\r\n            meta_struct,\r\n            synth_opt,\r\n            global_model_fn)\r\n\r\n\r\n        while not verified_candidate:\r\n\r\n            # Try to get a non-repetitive candidate\r\n            start_seq = self._get_non_coding_candidate(\r\n                meta_seq=meta_seq,\r\n                meta_struct=meta_struct,\r\n                homology=homology,\r\n                local_model_fn=local_model_fn,\r\n                verbose=verbose,\r\n                jump=current_jump_count < jump_count,\r\n                start_seq=seed_seq,\r\n                allow_internal_repeat=allow_internal_repeat)\r\n            candidate = start_seq\r\n            if start_seq:\r\n                # If structure unmatched but constraint has base pairings, go for inverse-repair strategy\r\n                if meta_struct.inversefolding['status'] and not self._is_structure_verified(\r\n                    meta_struct, struct_type, start_seq):\r\n                    inverse_fold_seq = self._get_inverse_fold_candidate(\r\n                        start_seq,\r\n                        meta_seq,\r\n                        meta_struct)\r\n                    candidate = self._get_non_coding_candidate(\r\n                        meta_seq=meta_seq,\r\n                        meta_struct=meta_struct,\r\n                        homology=homology,\r\n                        local_model_fn=local_model_fn,\r\n                        verbose=verbose,\r\n                        jump=current_jump_count < jump_count,\r\n                        start_seq=inverse_fold_seq,\r\n                        allow_internal_repeat=allow_internal_repeat)\r\n\r\n            opt_count = 0\r\n\r\n            # If valid candidate then process\r\n            if candidate:\r\n                current_jump_count = 0\r\n                opt_count += 1\r\n\r\n                # Diagnostic block -- Shouldn't trigger on experimental changes\r\n                construction = self._is_non_coding_construction_verified(\r\n                    meta_seq,\r\n                    meta_struct,\r\n                    candidate)\r\n                construction_state = construction[0]\r\n                error_digest = construction[1:]\r\n                if not construction_state:\r\n                    current_fail_count += 1\r\n                    raise Exception(\r\n                        'Maker built a rogue candidate: {}\\nError Digest: {}\\nPlease report issue to authors.'.format(\r\n                            candidate,\r\n                            error_digest))\r\n                else:\r\n                    pass\r\n\r\n                # Synthesis optimization\r\n                if synth_opt:\r\n                    if self._is_synthesis_verified(candidate):\r\n                        opt_count += 1\r\n                    else:\r\n                        synth_fail_count += 1\r\n\r\n                # Global model optimization\r\n                if global_model_fn:\r\n\r\n                    # Try to evaluate the global_model_fn on candidate_str\r\n                    outcome = True\r\n                    try:\r\n                        outcome = global_model_fn(candidate)\r\n                    except Exception as e:\r\n                        print(' Global Model fn. failed to evaluate complete path: {}\\n'.format(\r\n                            candidate))\r\n                        raise e\r\n\r\n                    # Outcome satisfactory?\r\n                    try:\r\n                        assert outcome in [True, False]\r\n                    except Exception as e:\r\n                        print(' Global Model fn. returned a non-boolean state: {}\\n'.format(\r\n                            outcome))\r\n                        raise e\r\n\r\n                    # Process outcome\r\n                    if outcome: # True\r\n                        opt_count += 1\r\n                    else:       # False\r\n                        model_fail_count += 1\r\n\r\n                # Structural optimization\r\n                if meta_struct.folding['status']:\r\n                    if self._is_structure_verified(\r\n                        meta_struct,\r\n                        struct_type,\r\n                        candidate):\r\n                        opt_count += 1\r\n                    else:\r\n                        struct_fail_count += 1\r\n\r\n                # Did everything get optimized?\r\n                if opt_count == opt_pass_count:\r\n                    verified_candidate = candidate\r\n                else:\r\n                    current_fail_count += 1\r\n\r\n                # Failure count exceeded, terminate\r\n                if current_fail_count == fail_count:\r\n                    break\r\n\r\n            # No candidate produced\r\n            else:\r\n                # No jumps made yet no non-repetitive candidate found\r\n                if current_jump_count >= jump_count:\r\n                    break\r\n                # Increase current_jump_count\r\n                else:\r\n                    current_jump_count += 1\r\n                # Abortion limit reached?\r\n                if abortion and current_jump_count >= jump_count:\r\n                    break\r\n\r\n        if int(verbose) > 1:\r\n            print('\\n  [seq fails] {}, [struct fails] {}, [synth fails] {}, [global fails] {}, [opt fails] {}'.format(\r\n                current_jump_count,\r\n                struct_fail_count,\r\n                synth_fail_count,\r\n                model_fail_count,\r\n                current_fail_count))\r\n\r\n        return verified_candidate, current_jump_count+1, current_fail_count+1\r\n\r\n    def _get_non_coding_nrps(\r\n        self,\r\n        homology,\r\n        seq,\r\n        struct,\r\n        struct_type,\r\n        target,\r\n        synth_opt,\r\n        local_model_fn,\r\n        global_model_fn,\r\n        jump_count,\r\n        fail_count,\r\n        verbose,\r\n        abortion,\r\n        allow_internal_repeat=False):\r\n\r\n        # Setup structures\r\n        seq = seq.upper()\r\n        meta_struct = self._get_meta_struct(\r\n            struct=self._get_adjusted_struct(struct, seq))\r\n        meta_seq = self._get_meta_seq(\r\n            seq=seq,\r\n            meta_struct=meta_struct)\r\n\r\n        seq_count  = 0\r\n        iter_count = 0\r\n        time_sum   = 0.0\r\n        begin_time = time()\r\n        break_flag = False\r\n\r\n        # Setup Bernoulli Success model\r\n        total_jump_trials    = jump_count\r\n        total_jump_successes = 1\r\n        curr_jump_prob       = berno.get_prob(\r\n            trials=total_jump_trials,\r\n            success=total_jump_successes)\r\n        curr_jump_trial      = jump_count\r\n        total_fail_trials    = fail_count\r\n        total_fail_successes = 1\r\n        curr_fail_prob       = berno.get_prob(\r\n            trials=total_fail_trials,\r\n            success=total_fail_successes)\r\n        curr_fail_trial      = fail_count\r\n\r\n        # Stream parts until completion\r\n        while True:\r\n\r\n            t0 = time()\r\n\r\n            candidate, curr_jump_trial, curr_fail_trial = self._get_verified_non_coding_candidate(\r\n                homology,\r\n                meta_seq,\r\n                meta_struct,\r\n                struct_type,\r\n                synth_opt,\r\n                local_model_fn,\r\n                global_model_fn,\r\n                curr_jump_trial,\r\n                curr_fail_trial,\r\n                verbose,\r\n                abortion,\r\n                allow_internal_repeat)\r\n\r\n            if candidate is None:\r\n                break_flag = True\r\n\r\n            # Got a canidate -- will try again\r\n            if not break_flag:\r\n                final_candidate = candidate\r\n                update_status   = True\r\n                try:\r\n                    for kmer in utils.stream_min_kmers(\r\n                        seq=candidate,\r\n                        k=homology):\r\n                        self.kmer_db.add(kmer)\r\n                except Exception as E:\r\n                    update_status = False\r\n\r\n                if not update_status: # Memory full\r\n                    if verbose:\r\n                        print('[ERROR] Memory Full ... Breaking Loop')\r\n                        yield update_status\r\n\r\n                seq_count  += 1\r\n                time_sum   += time()-t0\r\n                iter_count += 1\r\n\r\n                if verbose:\r\n                    print(' [part] {}, [{}-mers] {}, [iter time] {:.2f}s, [avg time] {:.2f}s, [total time] {:.2f}h'.format(\r\n                        seq_count,\r\n                        homology,\r\n                        len(self.kmer_db),\r\n                        time()-t0, time_sum / iter_count,\r\n                        (time() - begin_time) / 3600.0))\r\n\r\n                yield final_candidate\r\n\r\n                # No more parts required\r\n                if seq_count == target:\r\n                    break\r\n            # No more candidates to build\r\n            else:\r\n                yield candidate\r\n                break\r\n\r\n            # Update failure limits based on Bernoulli Success model\r\n            total_jump_trials    += curr_jump_trial\r\n            total_jump_successes += 1\r\n            curr_jump_prob       =  berno.get_prob(trials=total_jump_trials, success=total_jump_successes)\r\n            curr_jump_trial      =  berno.get_trials(prob=curr_jump_prob)\r\n            total_fail_trials    += curr_fail_trial\r\n            total_fail_successes += 1\r\n            curr_fail_prob       =  berno.get_prob(trials=total_fail_trials, success=total_fail_successes)\r\n            curr_fail_trial      =  berno.get_trials(prob=curr_fail_prob)\r\n\r\n    def _check_maker_constraints(\r\n        self,\r\n        seq,\r\n        struct,\r\n        part_type,\r\n        allow_internal_repeat,\r\n        target,\r\n        homology):\r\n        # Sequence Legality 1\r\n        if not isinstance(seq, str):\r\n            print('\\n [ERROR]    Sequence Constraint must be a string, not {}'.format(type(seq)))\r\n            print(' [SOLUTION] Try correcting Sequence Constraint\\n')\r\n            return False\r\n        # Sequence Legality 2\r\n        if len(seq) < 5:\r\n            print('\\n [ERROR]    Sequence Constraint must be longer than 4 bases, not {}'.format(len(seq)))\r\n            print(' [SOLUTION] Try using a longer Sequence Constraint\\n')\r\n            return False\r\n        # Structure Legality 1\r\n        if not isinstance(struct, str):\r\n            print('\\n [ERROR]    Structure Constraint must be a string, not {}'.format(type(struct)))\r\n            print(' [SOLUTION] Try correcting Structure Constraint\\n')\r\n            return False\r\n        # Structure Legality 2\r\n        if len(struct) != len(seq):\r\n            print('\\n [ERROR]    Structure Constraint must be same length as Sequence Constraint ({}), not {}'.format(\r\n                len(seq),\r\n                len(struct)))\r\n            print(' [SOLUTION] Try correcting length of Structure Constraint\\n')\r\n            return False\r\n        # Part Type Legality 1\r\n        if not isinstance(part_type, str):\r\n            print('\\n [ERROR]    Part Type must be a string, not \\'{}\\''.format(type(part_type)))\r\n            print(' [SOLUTION] Try correcting Part Type\\n')\r\n            return False\r\n        # Part Type Legality 2\r\n        if not part_type in ['DNA', 'RNA']:\r\n            print('\\n [ERROR]    Part Type must be \\'RNA\\' or \\'DNA\\', not \\'{}\\''.format(part_type))\r\n            print(' [SOLUTION] Try correcting Part Type\\n')\r\n            return False\r\n        # Sequence Legality 3\r\n        seq_legal, seq_illegal_chars = makerchecks.is_seq_constr_legal(seq, part_type)\r\n        if not seq_legal:\r\n            print('\\n [ERROR]    {} Sequence Constraint is not legal due to chars: {}'.format(part_type, seq_illegal_chars))\r\n            print(' [SOLUTION] Try correcting Sequence Constraint or Part Type\\n')\r\n            return False\r\n        # Structure Legality 3\r\n        struct_legal, unclosed, unopened, invalid = makerchecks.is_structure_valid(struct)\r\n        if not struct_legal:\r\n            print('\\n [ERROR]    Structure Constraint is illegal or unbalanced')\r\n            if unclosed:\r\n                print(' [ERROR]    >> Unclosed bases at locations: {}'.format(unclosed))\r\n            if unopened:\r\n                print(' [ERROR]    >> Unopened bases at locations: {}'.format(unopened))\r\n            if invalid:\r\n                print(' [ERROR]    >> Invalid characters at locations: {}'.format(invalid))\r\n            print(' [SOLUTION] Try correcting Structure Constraint\\n')\r\n            return False\r\n        # Sequence + Structure + Part Type Base Pairing Combination Legality\r\n        combo_state, incompat_locs, reduced_locs = makerchecks.is_pairing_compatible(seq, struct, part_type)\r\n        if not combo_state:\r\n            if incompat_locs:\r\n                print('\\n [ERROR]    Incompatible Base Pairing for {} Parts at locations: {}'.format(part_type, incompat_locs))\r\n                print(' [SOLUTION] Try correcting Sequence Constraint or Part Type\\n')\r\n                return False\r\n            if reduced_locs: # -- soft check\r\n                print('\\n [WARNING]  Reducible Paired Bases at locations: {}'.format(reduced_locs))\r\n                print(' [WARNING]  Fewer Parts may be Generated')\r\n        # Lmax Legality 1\r\n        if not isinstance(homology, int):\r\n            print('\\n [ERROR]    Lmax must be an integer, not {}'.format(type(homology)))\r\n            print(' [SOLUTION] Try correcting Lmax\\n')\r\n            return False\r\n        # Lmax Legality 2\r\n        if homology-1 < 5:\r\n            print('\\n [ERROR]    Lmax must be greater than 4, not {}'.format(homology-1))\r\n            print(' [SOLUTION] Try correcting Lmax\\n')\r\n            return False\r\n        # Lmax Legality 3\r\n        if homology-1 >= len(seq):\r\n            print('\\n [ERROR]    Lmax must be less than length of Sequence Constraint ({}), not {}'.format(len(seq), homology-1))\r\n            print(' [SOLUTION] Try correcting Lmax\\n')\r\n            return False\r\n        # Target Size Legality 1\r\n        if not isinstance(target, int):\r\n            print('\\n [ERROR]    Target Size must be an integer, not {}'.format(type(target)))\r\n            print(' [SOLUTION] Try correcting Target Size\\n')\r\n            return False\r\n        # Target Size Legality 2\r\n        if target < 1:\r\n            print('\\n [ERROR]    Target Size must be greater than 0, not {}'.format(target))\r\n            print(' [SOLUTION] Try correcting Target Size\\n')\r\n            return False\r\n        # Sequence Sufficiency -- soft check\r\n        seq_sufficient, constrained_motif_locs = makerchecks.is_seq_constr_sufficient(seq, struct, homology, target)\r\n        if not seq_sufficient:\r\n            print('\\n [WARNING]  Target Size of {} may be unreachable from given Sequence/Structure Constraint and Lmax of {}'.format(target, homology-1))\r\n            print(' [WARNING]  >> Lmax limiting windows between locations: {}'.format(constrained_motif_locs))\r\n            print(' [WARNING]  Fewer Parts may be Generated')\r\n        # Internal Repeats Legality\r\n        if not allow_internal_repeat in [True, False]:\r\n            print('\\n [ERROR]    Internal Repeat must be boolean, not {}'.format(type(allow_internal_repeat)))\r\n            print(' [SOLUTION] Try correcting Internal Repeat\\n')\r\n            return False\r\n        # Structure Sufficiency\r\n        if not allow_internal_repeat:\r\n            struct_sufficient, long_hairpins = makerchecks.is_structure_not_conflict(struct, homology)\r\n            if not struct_sufficient:\r\n                print('\\n [ERROR] Structure Constraint is insufficient based on given Lmax')\r\n                for long_hairpin in long_hairpins:\r\n                    print(' [ERROR] >> Long hairpin at locations: {}'.format(long_hairpin))\r\n                    print(' [SOLUTION] Try relaxing Structure Constraint or setting internal_repeats=True')\r\n                print()\r\n                return False\r\n        return True\r\n\r\n    def _check_maker_inputs(\r\n        self,\r\n        struct_type,\r\n        synth_opt,\r\n        jump_count,\r\n        fail_count,\r\n        output_file,\r\n        verbose):\r\n        # Struct Type Legality\r\n        if not struct_type in ['mfe', 'centroid', 'both']:\r\n            print('\\n [ERROR]    Struct Type must be \\'mfe\\', \\'centroid\\' or \\'both\\', not \\'{}\\''.format(struct_type))\r\n            print(' [SOLUTION] Try correcting Part Type\\n')\r\n            return False\r\n        # Synth Optimization Legality\r\n        if not synth_opt in [True, False]:\r\n            print('\\n [ERROR]    Synth Opt must be True or False, not {}'.format(synth_opt))\r\n            print(' [SOLUTION] Try correcting Synth Opt\\n')\r\n            return False\r\n        # Jump Count Legality 1\r\n        if not isinstance(jump_count, int):\r\n            print('\\n [ERROR]    Jump Count must be an integer, not {}'.format(type(jump_count)))\r\n            print(' [SOLUTION] Try correcting Jump Count\\n')\r\n            return False\r\n        # Jump Count Legality 2\r\n        if jump_count < 0:\r\n            print('\\n [ERROR]    Jump Count must be greater than 0, not {}'.format(jump_count))\r\n            print(' [SOLUTION] Try correcting Jump Count\\n')\r\n            return False\r\n        # Fail Count Legality 1\r\n        if not isinstance(fail_count, int):\r\n            print('\\n [ERROR]    Fail Count must be an integer, not {}'.format(type(fail_count)))\r\n            print(' [SOLUTION] Try correcting Fail Count\\n')\r\n            return False\r\n        # Fail Count Legality 2\r\n        if fail_count < 0:\r\n            print('\\n [ERROR]    Fail Count must be greater than 0, not {}'.format(fail_count))\r\n            print(' [SOLUTION] Try correcting Fail Count\\n')\r\n            return False\r\n        # Output File Legality\r\n        if not output_file is None:\r\n            if not isinstance(output_file, str):\r\n                print('\\n [ERROR]    Output File must be a string or None, not {}'.format(type(output_file)))\r\n                print(' [SOLUTION] Try correcting Output File\\n')\r\n                return False\r\n        # Everything OK\r\n        return True\r\n\r\n    def nrp_maker(self,\r\n        homology,\r\n        seq_constr,\r\n        struct_constr,\r\n        target_size,\r\n        background=None,\r\n        struct_type=None,\r\n        synth_opt=True,\r\n        local_model_fn=None,\r\n        global_model_fn=None,\r\n        jump_count=10,\r\n        fail_count=1000,\r\n        output_file=None,\r\n        verbose=True,\r\n        abortion=True,\r\n        allow_internal_repeat=False,\r\n        check_constraints=True):\r\n\r\n        if verbose:\r\n            print('\\n[Non-Repetitive Parts Calculator - Maker Mode]')\r\n        build_parts = True\r\n\r\n        # Check Maker Constraints\r\n        if check_constraints:\r\n            if verbose:\r\n                print('\\n[Checking Constraints]')\r\n                print('  Sequence Constraint: {}'.format(seq_constr))\r\n                print(' Structure Constraint: {}'.format(struct_constr))\r\n                print('      Part Type      : {}'.format(self.part_type))\r\n                print('           Lmax      : {} bp'.format(homology-1))\r\n                print('    Target Size      : {} parts'.format(target_size))\r\n                print('  Internal Repeats   : {}'.format(allow_internal_repeat))\r\n            check_status = self._check_maker_constraints(\r\n                seq_constr,\r\n                struct_constr,\r\n                self.part_type,\r\n                allow_internal_repeat,\r\n                target_size,\r\n                homology)\r\n\r\n            if check_status == False:\r\n                if verbose:\r\n                    print(' Check Status: FAIL\\n')\r\n                build_parts = False\r\n            else:\r\n                if verbose:\r\n                    print('\\n Check Status: PASS')\r\n\r\n            # Background Check\r\n            if build_parts:\r\n                if not background is None:\r\n                    if verbose:\r\n                        print('\\n[Checking Background]\\n Background: {}'.format(background))\r\n                    if isinstance(background, kmerSetDB):\r\n                        if background.K > len(seq_constr):\r\n                            build_parts = False\r\n                            print('\\n [ERROR]    Background Lmax of {} is greater than desired part length ({}-bp)'.format(\r\n                                background.K-1,\r\n                                len(seq_constr)))\r\n                            print(' [SOLUTION] Try using a background with Lmax less than or equal to part length\\n')\r\n                            if verbose:\r\n                                print(' Check Status: FAIL\\n')\r\n                        if build_parts and not background.ALIVE:\r\n                            build_parts = False\r\n                            print('\\n [ERROR]    Background is closed or dropped')\r\n                            print(' [SOLUTION] Try using an open Background\\n')\r\n                            if verbose:\r\n                                print(' Check Status: FAIL\\n')\r\n                        if build_parts:\r\n                            if verbose:\r\n                                print('\\n Check Status: PASS')\r\n\r\n                    else:\r\n                        build_parts = False\r\n                        print('\\n [ERROR]    Background Object is INVALID')\r\n                        print(' [SOLUTION] Try instantiating background via nrpcalc.background(...)\\n')\r\n                        if verbose:\r\n                            print(' Check Status : FAIL\\n')\r\n\r\n            # Arguments Check\r\n            if build_parts:\r\n                if verbose:\r\n                    print('\\n[Checking Arguments]')\r\n                    print(' Struct Type : {}'.format(struct_type))\r\n                    print('  Synth Opt  : {}'.format(synth_opt))\r\n                    print('   Jump Count: {}'.format(jump_count))\r\n                    print('   Fail Count: {}'.format(fail_count))\r\n                    print(' Output File : {}'.format(output_file))\r\n                check_status = self._check_maker_inputs(\r\n                    struct_type,\r\n                    synth_opt,\r\n                    jump_count,\r\n                    fail_count,\r\n                    output_file,\r\n                    verbose)\r\n\r\n                if check_status == False:\r\n                    if verbose:\r\n                        print(' Check Status: FAIL\\n')\r\n                    build_parts = False\r\n                else:\r\n                    if verbose:\r\n                        print('\\n Check Status: PASS')\r\n\r\n            if not build_parts:\r\n                # Cleanups\r\n                self.background = None\r\n                self.kmer_db = None\r\n                raise RuntimeError('Invalid Constraints, Background or Arguments')\r\n\r\n        # Separate Checks from Build Logs\r\n        if verbose:\r\n            print()\r\n\r\n        # kmer_db and background Setup\r\n        projector.setup_proj_dir(self.proj_id)\r\n        self.kmer_db = set()\r\n        self.background = background\r\n        # self.kmer_db = kmerSetDB(\r\n        #     path='./{}/kmerDB'.format(self.proj_id),\r\n        #     homology=homology,\r\n        #     verbose=verbose)\r\n\r\n        # Project Setup\r\n        if output_file is None:\r\n            projector.setup_proj_dir(self.proj_id)\r\n            output_file = './{}/seq_list.fa'.format(self.proj_id)\r\n\r\n        # Execute Maker\r\n        with open(output_file, 'w') as out_file:\r\n            seq_constr    = seq_constr.upper()\r\n            struct_constr = self._get_adjusted_struct(\r\n                struct_constr,\r\n                seq_constr)\r\n            current_nrp_count = 0\r\n            memory_exhausted  = False\r\n\r\n            if verbose:\r\n                print('Constructing Toolbox:\\n')\r\n\r\n            for non_coding_nrp in self._get_non_coding_nrps(\r\n                homology,\r\n                seq_constr,\r\n                struct_constr,\r\n                struct_type,\r\n                target_size,\r\n                synth_opt,\r\n                local_model_fn,\r\n                global_model_fn,\r\n                jump_count,\r\n                fail_count,\r\n                verbose,\r\n                abortion,\r\n                allow_internal_repeat):\r\n\r\n                # Write out genetic part\r\n                if non_coding_nrp:\r\n                    out_file.write(\r\n                        '>non-repetitive part {}\\n'.format(\r\n                            current_nrp_count+1))\r\n                    non_coding_nrp = '\\n'.join(\r\n                        textwrap.wrap(\r\n                            non_coding_nrp, 80))\r\n                    out_file.write('{}\\n'.format(\r\n                        non_coding_nrp))\r\n                    current_nrp_count += 1\r\n                else:\r\n                    if non_coding_nrp is None:\r\n                        if verbose:\r\n                            print('Failure Limits Exceeded or k-mers Exhausted. Cannot Build More Parts.')\r\n                    else:\r\n                        if verbose:\r\n                            print('Memory Capacity at Full. Cannot Build More Parts.')\r\n                        memory_exhausted = True\r\n\r\n                # Memory no longer available ... stop\r\n                if memory_exhausted:\r\n                    break\r\n            if verbose:\r\n                print('\\nConstruction Complete.\\n')\r\n\r\n        # Detach Background\r\n        self.background = None\r\n\r\n        # Remove kmerSetDB\r\n        # self.kmer_db.drop()\r\n        self.kmer_db = None\r\n\r\n        # Pack output in dictionary\r\n        parts_dict = {}\r\n        for i,line in enumerate(utils.stream_fasta_seq_list(output_file)):\r\n            line = line.strip()\r\n            parts_dict[i] = line\r\n\r\n        # Cleanups and Return\r\n        projector.remove_proj_dir()\r\n        if verbose:\r\n            print('Non-Repetitive Toolbox Size: {}'.format(current_nrp_count))\r\n        return parts_dict\r\n\r\ndef main():\r\n    homology = 16\r\n    sm_obj = NRPMaker(seed=7)\r\n\r\n    # Hammerhead Nielsen Paper\r\n    seq         = 'NNNN AGNNNU CANNNNN UGUGCUU NNNNNU CUGAUGA NNNN GUGA NNNN GAAA NNNC CUCU NNNNN UAAU NNNNN UUAA NNNN' # Nielsen Like\r\n    struct      = 'xxxx x((((( x(((((( xxxxxxx )))))) xxxxxxx (((( xxxx )))) xxx) )))) xxxx ((((( xxxx ))))) xxxx xxxx'\r\n    seq         = ''.join(seq.split(' '))\r\n    struct      = ''.join(struct.split(' '))\r\n    output_file = None #'riboz.fa'\r\n    background  = None #utils.get_fasta_seq_list(fasta_filename='input.fa.bk104')\r\n\r\n    # Final Result Store\r\n    final_toolbox = {}\r\n\r\n    # Initialize Background\r\n    background = kmerSetDB(\r\n        path='./testDB',\r\n        homology=homology,\r\n        verbose=True)\r\n    # background.multiadd(\r\n    #     utils.get_fasta_seq_list(\r\n    #         fasta_filename='input.fa.bk104'))\r\n\r\n    # Background Based Single Part Design Works\r\n    t0 = time()\r\n    tt = 0\r\n    toolbox1 = sm_obj.nrp_maker(homology, [seq], [struct], [10],\r\n        struct_type='mfe',\r\n        background=background,\r\n        jump_count=100,\r\n        fail_count=1000,\r\n        synth_opt=False,\r\n        verbose=True,\r\n        abortion=True,\r\n        allow_internal_repeat=True,\r\n        output_file=output_file)\r\n    tt += time() - t0\r\n    final_toolbox.update(\r\n        zip(range(len(final_toolbox), len(final_toolbox)+len(toolbox1)),\r\n            toolbox1.values()))\r\n\r\n    # Adding More Background Post Design Works\r\n    background.multiadd(toolbox1.values())\r\n\r\n    # Serial Designs from Multiple Constraints Works\r\n    t0 = time()\r\n    toolbox2 = sm_obj.nrp_maker(homology, [seq]*2, [struct]*2, [20]*2,\r\n        struct_type='mfe',\r\n        background=background,\r\n        jump_count=100,\r\n        fail_count=1000,\r\n        synth_opt=False,\r\n        verbose=True,\r\n        abortion=True,\r\n        allow_internal_repeat=False,\r\n        output_file=output_file)\r\n    tt += time() - t0\r\n    final_toolbox.update(\r\n        zip(range(len(final_toolbox), len(final_toolbox)+len(toolbox2)),\r\n            toolbox2.values()))\r\n\r\n    # Assert All Parts Unique and Non-Repetitive\r\n    assert len(set(final_toolbox.values())) == len(\r\n        finder.nrp_finder(final_toolbox.values(), homology, None, verbose=False))\r\n\r\n    # Drop Background\r\n    background.drop()\r\n\r\n    # Report Time Elapsed\r\n    print('\\nWall Time {} sec'.format(tt))\r\n\r\nif __name__ == '__main__':\r\n    main()\r\n", "meta": {"hexsha": "0314c6806fc6058ebbb6cbe79a78fd1cac328f7f", "size": 52558, "ext": "py", "lang": "Python", "max_stars_repo_path": "nrpcalc/base/maker.py", "max_stars_repo_name": "TimothyStiles/nrpcalc", "max_stars_repo_head_hexsha": "42ab25e929d472c2e808dd3bec6430bc80b42a06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-07-27T17:59:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T03:33:17.000Z", "max_issues_repo_path": "nrpcalc/base/maker.py", "max_issues_repo_name": "TimothyStiles/nrpcalc", "max_issues_repo_head_hexsha": "42ab25e929d472c2e808dd3bec6430bc80b42a06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-07-17T23:10:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-10T05:19:47.000Z", "max_forks_repo_path": "nrpcalc/base/maker.py", "max_forks_repo_name": "TimothyStiles/nrpcalc", "max_forks_repo_head_hexsha": "42ab25e929d472c2e808dd3bec6430bc80b42a06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-07-27T17:59:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-08T15:47:28.000Z", "avg_line_length": 37.9480144404, "max_line_length": 155, "alphanum_fraction": 0.4736481601, "include": true, "reason": "import numpy", "num_tokens": 10578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.17345964584492204}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Meeko hydrate molecule\n#\n\nimport numpy as np\n\nfrom .utils import geomutils\nfrom .utils import obutils\n\n\nclass HydrateMoleculeLegacy:\n    def __init__(self, distance=3.0, charge=0, atom_type=\"W\"):\n        \"\"\"Initialize the legacy hydrate typer for AutoDock 4.2.x\n\n        Args:\n            distance (float): distance between water molecules and ligand heavy atoms. (default: 3.0)\n            charge (float): partial charge of the water molecule. Not use for the hydrated docking. (default: 0)\n            atom_type (str): atom type of the water molecule. (default: W)\n\n        \"\"\"\n        self._distance = distance\n        self._charge = charge\n        self._atom_type = atom_type\n        self._bond_type = 1\n        self._rotatable = False\n        self._hb_config = {'HD': {1: (1, 1)},    # neigh: 1, wat: 1, sp1\n                           'OA': {\n                                      1: (2, 2), # neigh: 1, wat: 2, sp2\n                                      2: (2, 3)  # neigh: 2, wat: 2, sp3\n                                  },\n                           'SA': {\n                                      1: (2, 2), # neigh: 1, wat: 2, sp2\n                                      2: (2, 3)  # neigh: 2, wat: 2, sp3\n                                  },\n                           'NA': {\n                                      1: (1, 1), # neigh: 1, wat: 3, sp1\n                                      2: (1, 2), # neigh: 2, wat: 1, sp2\n                                      3: (1, 3)  # neigh: 3, wat: 1, sp3\n                                  }\n                           }\n\n    def _place_sp1_one_water(self, anchor_xyz, neighbor_xyz, hb_length=3.0):\n        position = anchor_xyz + geomutils.vector(neighbor_xyz, anchor_xyz)\n        position = geomutils.resize_vector(position, hb_length, anchor_xyz)\n        positions = np.array([position])\n\n        return positions\n\n    def _place_sp2_one_water(self, anchor_xyz, neighbor1_xyz, neighbor2_xyz, hb_length=3.0):\n        position = geomutils.atom_to_move(anchor_xyz, [neighbor1_xyz, neighbor2_xyz])\n        position = geomutils.resize_vector(position, hb_length, anchor_xyz)\n        positions = np.array([position])\n\n        return positions\n\n    def _place_sp2_two_waters(self, anchor_xyz, neighbor1_xyz, neighbor2_xyz, hb_lengths, angles):\n        if len(hb_lengths) != 2:\n            raise ValueError()\n        if len(angles) != 2:\n            raise ValueError()\n\n        positions = []\n\n        r = geomutils.rotation_axis(neighbor1_xyz, anchor_xyz, neighbor2_xyz, origin=anchor_xyz)\n        p = neighbor1_xyz\n\n        # We rotate p to get each vectors if necessary\n        for hb_length, angle in zip(hb_lengths, angles):\n            vector = p\n            if angle != 0.:\n                position = geomutils.rotate_point(vector, anchor_xyz, r, angle)\n            position = geomutils.resize_vector(position, hb_length, anchor_xyz)\n            positions.append(position)\n\n        positions = np.array(positions)\n\n        return positions\n\n    def _place_sp3_one_water(self, anchor_xyz, neighbor1_xyz, neighbor2_xyz, neighbor3_xyz, hb_length):\n        # We have to normalize bonds, otherwise the water molecule is not well placed\n        v1 = anchor_xyz + geomutils.normalize(geomutils.vector(anchor_xyz, neighbor1_xyz))\n        v2 = anchor_xyz + geomutils.normalize(geomutils.vector(anchor_xyz, neighbor2_xyz))\n        v3 = anchor_xyz + geomutils.normalize(geomutils.vector(anchor_xyz, neighbor3_xyz))\n\n        position = geomutils.atom_to_move(anchor_xyz, [v1, v2, v3])\n        position = geomutils.resize_vector(position, hb_length, anchor_xyz)\n        positions = np.array([position])\n\n        return positions\n\n    def _place_sp3_two_waters(self, anchor_xyz, neighbor1_xyz, neighbor2_xyz, hb_lengths, angles):\n        if len(hb_lengths) != 2:\n            raise ValueError()\n        if len(angles) != 2:\n            raise ValueError()\n\n        positions = []\n\n        v1 = anchor_xyz + geomutils.normalize(geomutils.vector(anchor_xyz, neighbor1_xyz))\n        v2 = anchor_xyz + geomutils.normalize(geomutils.vector(anchor_xyz, neighbor2_xyz))\n\n        r = anchor_xyz + geomutils.normalize(geomutils.vector(v1, v2))\n        p = geomutils.atom_to_move(anchor_xyz, [v1, v2])\n\n        # We rotate p to get each vectors if necessary\n        for hb_length, angle in zip(hb_lengths, angles):\n            vector = p\n            if angle != 0.:\n                position = geomutils.rotate_point(vector, anchor_xyz, r, angle)\n            position = geomutils.resize_vector(position, hb_length, anchor_xyz)\n            positions.append(position)\n\n        positions = np.array(positions)\n\n        return positions\n\n    def hydrate(self, mol):\n        \"\"\"Add water molecules to the ligand\n        \n        Args:\n            mol (OBMol): input OBMol molecule object\n\n        \"\"\"\n        setup = mol.setup\n        water_anchors = []\n        water_positions = []\n        # It will be the same distance for all of the water molecules\n        hb_length = self._distance\n\n        for a, neighbors in setup.graph.items():\n            atom_type = setup.get_atom_type(a)\n            anchor_xyz = setup.get_coord(a)\n            neighbor1_xyz = setup.get_coord(neighbors[0])\n            positions = np.array([])\n            n_wat = None\n            hyb = None\n\n            if atom_type in self._hb_config:\n                try:\n                    n_wat, hyb = self._hb_config[atom_type][len(neighbors)]\n                except KeyError:\n                    raise RuntimeError('Cannot place water molecules on atom %d of type %s with %d neighbors.' % (a, atom_type, len(neighbors)))\n\n                water_anchors.append(a)\n\n            if hyb == 1:\n                if n_wat == 1:\n                    # Example: X-HD\n                    positions = self._place_sp1_one_water(anchor_xyz,\n                                                          neighbor1_xyz,\n                                                          hb_length - 1.0)\n            elif hyb == 2:\n                if n_wat == 1:\n                    # Example: X-Nitrogen-X\n                    neighbor2_xyz = setup.get_coord(neighbors[1])\n                    positions = self._place_sp2_one_water(anchor_xyz,\n                                                          neighbor1_xyz, neighbor2_xyz,\n                                                          hb_length)\n                elif n_wat == 2:\n                    # Example: C=0 (backbone oxygen)\n                    tmp_neighbors = [x for x in setup.get_neigh(neighbors[0]) if not x == a]\n                    neighbor2_xyz =  setup.get_coord(tmp_neighbors[0])\n                    positions = self._place_sp2_two_waters(anchor_xyz,\n                                                           neighbor1_xyz, neighbor2_xyz,\n                                                           [hb_length, hb_length],\n                                                           [-np.radians(120), np.radians(120)])\n                elif n_wat == 3:\n                    hyb = 3\n            elif hyb == 3:\n                if n_wat == 1:\n                    # Example: Ammonia\n                    neighbor2_xyz = setup.get_coord(neighbors[1])\n                    neighbor3_xyz = setup.get_coord(neighbors[2])\n                    positions = self._place_sp3_one_water(anchor_xyz, \n                                                          neighbor1_xyz, neighbor2_xyz, neighbor3_xyz,\n                                                          hb_length)\n                elif n_wat == 2:\n                    # Example: O-HD (Oxygen in hydroxyl group)\n                    neighbor2_xyz = setup.get_coord(neighbors[1])\n                    positions = self._place_sp3_two_waters(anchor_xyz,\n                                                           neighbor1_xyz, neighbor2_xyz,\n                                                           [hb_length, hb_length],\n                                                           [-np.radians(60), np.radians(60)])\n                elif n_wat == 3:\n                    positions = np.array([])\n\n            if positions.size:\n                water_positions.append(positions)\n\n        for water_anchor, waters_on_anchor in zip(water_anchors, water_positions):\n            for water_on_anchor in waters_on_anchor:\n                tmp = setup.pdbinfo[water_anchor]\n                pdbinfo = obutils.PDBAtomInfo('WAT', tmp.resName, tmp.resNum, tmp.chain)\n                setup.add_pseudo(water_on_anchor, self._charge, [water_anchor], self._atom_type,\n                                     self._bond_type, self._rotatable, pdbinfo)\n", "meta": {"hexsha": "5e36ca695d69bed46692ba88217e419ac2f44888", "size": 8641, "ext": "py", "lang": "Python", "max_stars_repo_path": "meeko/hydrate.py", "max_stars_repo_name": "romanchemist/Meeko", "max_stars_repo_head_hexsha": "17c88a824276321fa57292fd619321b2b632802b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-16T02:19:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T02:19:16.000Z", "max_issues_repo_path": "meeko/hydrate.py", "max_issues_repo_name": "romanchemist/Meeko", "max_issues_repo_head_hexsha": "17c88a824276321fa57292fd619321b2b632802b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "meeko/hydrate.py", "max_forks_repo_name": "romanchemist/Meeko", "max_forks_repo_head_hexsha": "17c88a824276321fa57292fd619321b2b632802b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.6414141414, "max_line_length": 144, "alphanum_fraction": 0.5199629672, "include": true, "reason": "import numpy", "num_tokens": 1871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.17345964244123263}}
{"text": "#############MEASURING FACIAL SIMILARITY USING SIAMESE NETWORK##########\r\n#############Created & Modified by: MUHAMMAD UMER#######################\r\n#############DATE: 11/5/2020############################################\r\n\r\n\r\nimport torchvision\r\nimport torchvision.datasets as dset\r\nimport torchvision.transforms as transforms\r\nfrom torch.utils.data import DataLoader,Dataset\r\nimport matplotlib.pyplot as plt\r\nimport torchvision.utils\r\nimport numpy as np\r\nimport random\r\nfrom PIL import Image\r\nimport torch\r\nfrom torch.autograd import Variable\r\nimport PIL.ImageOps\r\nimport torch.nn as nn\r\nfrom torch import optim\r\nimport torch.nn.functional as F\r\nfrom Dataset import Config, SiameseNetworkDataset\r\nfrom Model import  SiameseNetwork, ContrastiveLoss\r\n\r\n\r\ndef imshow(img,text=None,should_save=False):\r\n    npimg = img.numpy()\r\n    plt.axis(\"off\")\r\n    if text:\r\n        plt.text(75, 8, text, style='italic',fontweight='bold',\r\n            bbox={'facecolor':'white', 'alpha':0.8, 'pad':10})\r\n    plt.imshow(np.transpose(npimg, (1, 2, 0)))\r\n    plt.show()\r\n\r\ndef show_plot(iteration,loss):\r\n    plt.plot(iteration,loss)\r\n    plt.show()\r\n\r\n\r\n\r\n################JUST PLOTTING RANDOM FACES TO SEE###############################\r\nfolder_dataset = dset.ImageFolder(root=Config.training_dir)\r\nsiamese_dataset = SiameseNetworkDataset(imageFolderDataset=folder_dataset,\r\n                                        transform=transforms.Compose([transforms.Resize((100,100)),\r\n                                                                      transforms.ToTensor()\r\n                                                                      ])\r\n                                       ,should_invert=False)\r\n\r\nvis_dataloader = DataLoader(siamese_dataset,\r\n                        shuffle=True,\r\n                        num_workers=8,\r\n                        batch_size=8)\r\ndataiter = iter(vis_dataloader)\r\n\r\n\r\nexample_batch = next(dataiter)\r\nconcatenated = torch.cat((example_batch[0],example_batch[1]),0)\r\nimshow(torchvision.utils.make_grid(concatenated))\r\nprint(example_batch[2].numpy())\r\n\r\n\r\n\r\n#####################################TRAINING PHASE##########################################\r\n\r\ntrain_dataloader = DataLoader(siamese_dataset,\r\n                        shuffle=True,\r\n                        num_workers=8,\r\n                        batch_size=Config.train_batch_size)\r\n\r\nnet = SiameseNetwork().cuda()\r\ncriterion = ContrastiveLoss()\r\noptimizer = optim.Adam(net.parameters(), lr=0.0005)\r\ncounter = []\r\nloss_history = []\r\niteration_number = 0\r\n\r\nfor epoch in range(0,Config.train_number_epochs):\r\n    for i, data in enumerate(train_dataloader, 0):\r\n        img0, img1, label = data\r\n        img0, img1, label = img0.cuda(), img1.cuda(), label.cuda()\r\n        optimizer.zero_grad()\r\n        output1, output2 = net(img0, img1)\r\n        loss_contrastive = criterion(output1,output2,label)\r\n        loss_contrastive.backward()\r\n        optimizer.step()\r\n        if i %10 == 0 :\r\n            print(\"Epoch number {}\\n Current loss {}\\n\".format(epoch,loss_contrastive.item()))\r\n            iteration_number +=10\r\n            counter.append(iteration_number)\r\n            loss_history.append(loss_contrastive.item())\r\nshow_plot(counter,loss_history)\r\n\r\n\r\n#####################################TESTING PHASE##########################################\r\n\r\nfolder_dataset_test = dset.ImageFolder(root=Config.testing_dir)\r\nsiamese_dataset = SiameseNetworkDataset(imageFolderDataset=folder_dataset_test,\r\n                                        transform=transforms.Compose([transforms.Resize((100, 100)),\r\n                                                                      transforms.ToTensor()\r\n                                                                      ])\r\n                                        , should_invert=False)\r\n\r\ntest_dataloader = DataLoader(siamese_dataset, num_workers=6, batch_size=1, shuffle=True)\r\ndataiter = iter(test_dataloader)\r\nx0, _, _ = next(dataiter)\r\n\r\nfor i in range(10):\r\n    _, x1, label2 = next(dataiter)\r\n    concatenated = torch.cat((x0, x1), 0)\r\n\r\n    output1, output2 = net(Variable(x0).cuda(), Variable(x1).cuda())\r\n    euclidean_distance = F.pairwise_distance(output1, output2)\r\n    imshow(torchvision.utils.make_grid(concatenated), 'Dissimilarity: {:.2f}'.format(euclidean_distance.item()))", "meta": {"hexsha": "a3dd58c019c76e7d4f15980e1565cb5c3a5b2067", "size": 4316, "ext": "py", "lang": "Python", "max_stars_repo_path": "Main_facial_similarity.py", "max_stars_repo_name": "umerm5/Siamese_Network", "max_stars_repo_head_hexsha": "3fd9f120e60d1e59e12ea8bdb97ac5571734bf95", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Main_facial_similarity.py", "max_issues_repo_name": "umerm5/Siamese_Network", "max_issues_repo_head_hexsha": "3fd9f120e60d1e59e12ea8bdb97ac5571734bf95", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Main_facial_similarity.py", "max_forks_repo_name": "umerm5/Siamese_Network", "max_forks_repo_head_hexsha": "3fd9f120e60d1e59e12ea8bdb97ac5571734bf95", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5357142857, "max_line_length": 112, "alphanum_fraction": 0.5681186284, "include": true, "reason": "import numpy", "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.17345964244123263}}
{"text": "import uproot\nfrom itertools import chain, product\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom tqdm import tqdm as tqdm \nimport src.mip_eff.tb_data_handling as dh\nimport src.mip_eff.simulation_analysis as mc\nimport argparse\nfrom datetime import datetime\nimport os\nimport warnings\nimport csv\n\ndef eff(mode, Nchb=8, qc=False):\n    \"\"\" Estimates the MIP detection efficiency for CaloEvents data.\n    Parameters:\n    -----------\n        mode    :   'dt' or 'calo' for trigger-time correlated hits or CaloEvents, respectively.\n        Nchb    :   the number of chambers in the setup. Default: 8.\n    \n    Returns:\n    --------\n\n        eff_tot :    a dictionary of the efficiency value of the different\n                    chambers. The chamber numbers serves as keys.  \n        pool_tot :   a dictionary of the number of MIP tracks used as reference\n                    for the efficiency estimation. The chamber numbers serves as keys.\n    \"\"\"\n\n    if mode == 'calo':\n        print('Running efficiency estimation for hits in CaloEvents.')\n        dataId = 'caloId'\n        df_MIPs = pd.DataFrame(columns = ['eventId', 'chbid', 'xpos', 'ypos', 'dt', 'digit', 'chipid', 'hardid',\n        'nhits', 'caloId', 'zx0', 'zx1', 'zy0', 'zy1'])\n    else:\n        print('Running efficiency estimation for hits which are time-correlated with the trigger.')\n        dataId = 'eventId'\n        df_MIPs = pd.DataFrame(columns = ['eventId', 'chbid', 'xpos', 'ypos', 'dt', 'digit', 'chipid', 'hardid',\n        'nhits', 'zx0', 'zx1', 'zy0', 'zy1'])\n\n    if Nchb == 7:\n        runList = pd.read_csv('data/eScan8Layers.csv')\n    else:\n        runList = pd.read_csv('data/eScan{}Layers.csv'.format(Nchb))\n    \n    l = runList.shape[0]\n\n    # for selection quality control purpose\n    if qc:\n        eff_runs = {'run': [], 'eff': [], 'pool': []}\n\n    # Define list of excluded runs\n    if Nchb == 8 or Nchb == 7:\n        excluded_runs = ['0036', '0650', '0712']\n    elif Nchb == 11:\n        excluded_runs = ['0018', '0726']\n    else:\n        excluded_runs = []\n\n    for i in tqdm(range(l)):\n        \n        # # debug\n\n        # if i > 0:\n        #     print('DEBUG MODE!!! ONLY 1 RUNS!!!')\n        #     break\n\n        run = runList.iloc[i]\n\n        if format(run[\"time\"], '04d') not in excluded_runs:\n            runId = '{:08d}-{:04d}-{}'.format(run[\"day\"], run[\"time\"], run[\"index\"])\n            print(runId)\n            df = dh.read_nov18run(run, Nchb=Nchb)\n            df = df[df.chbid <= Nchb]\n\n            if mode == 'calo':\n                time_wins = dh.calo_time_wins(df)\n            else:\n                time_wins = [15]\n\n            df_batch, nEvents = dh.cleaning(df, mode, time_wins)\n\n            if nEvents == 0:\n                print('Zero nEvents after cleaning!')\n                continue\n                \n            # eff_events = df_batch.groupby(dataId)['chbid'].agg(lambda x: len(x) > Nchb-2)\n            # eff_events = eff_events[eff_events].index.tolist()\n            \n            # Keep only effective events with more than Nchb-2 layers\n            eff_events = df_batch.groupby(dataId).agg(lambda x: len(set(x))) \n            eff_events = eff_events[eff_events['chbid'] > Nchb-2].index.tolist()\n            df_batch_eff = df_batch[df_batch[dataId].isin(eff_events)]\n            \n            # for selection quality control purpose\n            if qc:\n                hresx_tot = [0 for i in range(10)]\n                hresy_tot = [0 for i in range(10)]\n            \n            if df_batch_eff.shape[0] > 0:\n                (effective_MIPs, hresx, hresy, edge) = dh.isMIP(df_batch_eff, mode, Nchb=Nchb, res=2)\n\n                print ('{:.2%} of events are valid MIPs'.format(len(effective_MIPs)/nEvents))\n                df_batch_eff = df_batch_eff[df_batch_eff[dataId].isin(effective_MIPs)]\n                \n                # df_batch_eff[dataId] = df_batch_eff[dataId].agg(lambda x: '{}_{}'.format(runId, x))\n                df_MIPs = pd.concat([df_MIPs,df_batch_eff], axis=0)\n\n                # for selection quality control purpose\n                if qc:\n                    hresx_tot += hresx\n                    hresy_tot += hresy\n                    eff_run, pool_run, mult_run = dh.efficiency_estimation(df_batch)\n                    eff_runs['run'].append(runId)\n                    eff_runs['eff'].append(eff_run)\n                    eff_runs['pool'].append(pool_run)\n\n    eff_tot, pool_tot, mult_tot = dh.efficiency_estimation(df_MIPs, mode, Nchb)\n\n    dh.exporter(eff_tot, pool_tot, mult_tot, mode, Nchb)\n\n    return eff_tot, pool_tot, mult_tot\n\n\ndef eff_MC(energy, mipeff, sig, particle='pions', Nchb=8):\n    \"\"\" Estimates the MIP detection efficiency for CaloEvents data.\n    Parameters:\n    -----------\n        energy  :   beam energy in GeV (2-6).\n        mipeff  :   simulation mip threshold.\n        particle:   beam's type of particle: 'pions' or 'electrons'. Default: 'pions'.\n        mode    :   'dt' or 'calo' for trigger-time correlated hits or CaloEvents, respectively.\n        Nchb    :   the number of chambers in the setup. Default: 8.\n    \n    Returns:\n    --------\n\n        eff_tot :    a dictionary of the efficiency value of the different\n                    chambers. The chamber numbers serves as keys.  \n        pool_tot :   a dictionary of the number of MIP tracks used as reference\n                    for the efficiency estimation. The chamber numbers serves as keys.\n    \"\"\"\n\n    # filename, digit = mc.MAX_FILES[particle][energy][mipeff]\n    MC_HOME = '/Users/dansh/Projects/g4_mpgd_sdhcal/uMSDHCAL/rootfiles/10chb_high_statistics/digitized/'\n    prefix = 'digitized_MeasuredEff_0sig_8chbs_uMSDHCAL_ArCO2_2cm'\n    suffix = '0T_10k_FTFP_BERT.root'\n\n    filename = prefix + '_pi_{}_'.format(energy) + suffix\n    dataId = 'eventId'\n    filename = 'digitized_MeasuredEff_20200923_0.01sig_8chbs_high_statistics_100k_10chbs_5GeV_pi_QGSP_BERT.root'\n    # filename = 'digitized_noMult_lowMMHighRP_{}sig_8chbs_high_statistics_1M_10chbs_{}_pi.root'.format(sig, energy)\n    print(\"efficiency estimation for: \" + filename)\n    # read file to dataframe\n    file = uproot.open(MC_HOME + filename)\n    tree = file['tvec']\n    df= (pd.DataFrame(list(chain(*[list(product([x],[y])) \\\n                        for x, y in zip(tree.array(\"eventId\"),\n                                        tree.array(\"layer\"))])),\n                                        columns= ['eventId',\"chbid\"]))\n    df['xpos'] = tree.array('xpos').flatten()\n    df['ypos'] = tree.array('ypos').flatten()\n    # df['Thr'] = tree.array('Thr').flatten()\n    df['digit'] = tree.array('digit').flatten()\n    df['pad'] = df[['chbid', 'xpos', 'ypos']].agg(tuple, axis=1)\n\n    df_batch, nEvents = dh.cleaning(df, 'MC')\n    print('{} clean events'.format(len(df_batch[dataId].unique())))\n    if nEvents == 0:\n        raise ValueError('nEvent is zero!')\n        return\n        \n    eff_events = df_batch.groupby(dataId)['chbid'].agg(lambda x: len(set(x)) > Nchb-2)\n    eff_events = eff_events[eff_events].index.tolist()\n    df_batch_eff = df_batch[df_batch[dataId].isin(eff_events)]\n    \n    if df_batch_eff.shape[0] > 0:\n        (effective_MIPs, hresx, hresy, edge) = dh.isMIP(df_batch_eff, mode, Nchb=Nchb, res=2)\n\n\n        print ('{:.2%} of events are valid MIPs'.format(len(effective_MIPs)/len(df_batch[dataId].unique().tolist())))\n        df_batch_eff = df_batch_eff[df_batch_eff[dataId].isin(effective_MIPs)]\n        df_MIPs = df_batch_eff\n\n    \n    eff_tot, pool_tot, mult_tot = dh.efficiency_estimation(df_MIPs, 'MC', Nchb)\n    df_MIPs.to_pickle(MC_HOME + 'df_MIPs_'+ filename[:-5] + '.pkl')\n    return eff_tot, pool_tot, mult_tot\n\n\ndef plot_eff(eff_tot, pool_tot, mode, Nchb=8):\n    \"\"\"Generates plots for efficiency estimation and save them.\n    Parameters:\n    -----------\n        eff_tot :    a dictionary of the efficiency value of the different\n                    chambers. The chamber numbers serve as keys.  \n        pool_tot :   a dictionary of the number of MIP tracks used as reference\n                    for the efficiency estimation. The chamber numbers serve as keys.\n        mode     :  'dt', 'calo', or 'MC' for trigger-time correlated hits, CaloEvents, or simulation, respectively.\n        Nchb :      the number of chambers in the setup. Default: 8.\n    \n    Return:\n    -------\n        None\n    \n    \"\"\"\n    fig = plt.figure(figsize=(15, 20), constrained_layout=False)\n    gs = fig.add_gridspec(nrows=3, ncols=1, left=0.05, right=0.48, wspace=0.05)\n    ax1 = fig.add_subplot(gs[1, :])\n    ax2 = fig.add_subplot(gs[-1, :])\n    \n    # 16x16 cm^2 uM chambers\n    yerr_sm = [1/np.sqrt(pool_tot[i]) for i in range(2, 4)]\n    ax1.errorbar(range(2, 4), [eff_tot[i] for i in range(2, 4)], yerr=yerr_sm, fmt='o',\n                label='Small MM')\n    \n    # 48x48 cm^2 uM chambers\n    yerr_lm = [1/np.sqrt(pool_tot[i]) for i in range(4, 7)]\n    ax1.errorbar(range(4, 7), [eff_tot[i] for i in range(4, 7)], yerr=yerr_lm, fmt='s',\n                label='large MM')\n    yerr = [1/np.sqrt(pool_tot[i]) for i in range(7, Nchb+1)]\n    \n    # 48x48 cm^2 RPWELL chambers\n    if Nchb == 11:\n        dict_RPWELL = {7: 'ASU 61', 8: 'ASU 60', 9: 'ASU 51', 10: 'ASU 57', 11: 'ASU 52'}\n    elif Nchb in [7,8]:\n        dict_RPWELL = {7: 'ASU 61', 8: 'ASU 51'}\n    \n    # saving dato to csv\n    if not os.path.isdir('./results'):\n        os.mkdir(\"./results\")\n\n    ax1.errorbar(range(7, Nchb+1), [eff_tot[i] for i in range(7, Nchb+1)], yerr=yerr, fmt='^',\n                label='RPWELL')\n    \n    ax1.set_xlabel('layer number')\n    ax1.set_ylim(0.4,1)\n    ax1.legend()\n    ax1.set_ylabel('MIP detection efficiency')\n\n    # Add a table at the bottom of the axes\n    # ax2.axis('tight')\n    rowlabels = ['Small MM 2',\n                 'Small MM 3',\n                 'Large MM 1',\n                 'Large MM 2',\n                 'Large MM 3']\n    ax2.axis('off')\n    cell_text = []\n    for i in range(7, Nchb+1):\n        rowlabels.append('RPWELL {}'.format(dict_RPWELL[i]))\n\n    cell_text.append(['{:.2}'.format(eff_tot[i] * 100) for i in range(2, Nchb+1)])\n    cell_text.append(['{:.2}'.format(1/np.sqrt(pool_tot[i]) * 100) for i in range(2, Nchb+1)])\n    cell_text.append([pool_tot[i] for i in range(2, Nchb+1)])\n    table = ax2.table(cellText=np.array(cell_text).T,\n                        colLabels=('efficiency[%]', 'error[%]', 'tested tracks'),\n                        rowLabels= rowlabels,\n                        loc='center')\n    table.set_fontsize(18)\n    table.auto_set_column_width([0, 1, 2])\n    table.scale(10, 3)\n\n    # saving figure\n    if not os.path.isdir('./figures'):\n        os.mkdir(\"./figures\")\n    \n    fig.savefig('figures/mip_eff_{}layers_{}_{}.png'.format(Nchb, mode, datetime.now().strftime('%Y%m%d_%H%M')))\n\n    # plt.show()\n    del(fig)\n    print('| ASU | Effieicny [%] | number of tested tracks|')\n    print('|------|----------------|-----------------------|')\n    for i in range(2, 4):\n        print(\"|layer {} | {:.2}+\\-{:.2} \\t| {} |\".format(i,\n                                                  eff_tot[i]*100,\n                                                  yerr_sm[i-2]*100,\n                                                  pool_tot[i]))\n    for i in range(4, 7):\n        print(\"|layer {} | {:.2}+\\-{:.2} \\t| {} |\".format(i,\n                                                  eff_tot[i]*100,\n                                                  yerr_lm[i-4]*100,\n                                                  pool_tot[i]))\n    for i in range(7,Nchb+1):\n        print(\"|{} | {:.2}+\\-{:.2} \\t| {} |\".format(dict_RPWELL[i],\n                                                  eff_tot[i]*100,\n                                                  yerr[i-7]*100,\n                                                  pool_tot[i]))\n\n\ndef plot_mult(mult_tot, mode, Nchb=8):\n    \"\"\"Generates plots for efficiency estimation and save them.\n    Parameters:\n    -----------\n        mult_tot :  a dictionary of the pad multiplicity value of the different\n                    chambers. The chamber numbers serve as keys.  \n        mode     :  'dt', 'calo', or 'MC' for trigger-time correlated hits, CaloEvents, or simulation, respectively.\n        Nchb :      the number of chambers in the setup. Default: 8.\n    \n    Return:\n    -------\n        None\n    \n    \"\"\"\n\n    fig = plt.figure(figsize=(10, 7))\n    # 16x16 cm^2 uM chambers\n    plt.scatter(range(2, 4), [mult_tot[i] for i in range(2, 4)], \n                label='Small MM')\n    \n    # 48x48 cm^2 uM chambers\n    plt.scatter(range(4, 7), [mult_tot[i] for i in range(4, 7)],\n                label='large MM')\n    \n    # 48x48 cm^2 RPWELL chambers\n    if Nchb == 11:\n        dict_RPWELL = {7: 'ASU 61', 8: 'ASU 60', 9: 'ASU 51', 10: 'ASU 57', 11: 'ASU 52'}\n    elif Nchb == 8:\n        dict_RPWELL = {7: 'ASU 61', 8: 'ASU 51'}\n\n    plt.scatter(range(7, Nchb+1), [mult_tot[i] for i in range(7, Nchb+1)],\n                label='RPWELL')\n    \n    plt.xlabel('layer number')\n    plt.ylim(0.4,1)\n    plt.legend()\n    plt.ylabel('MIP detection efficiency')\n\n    # saving figure\n    if not os.path.isdir('./figures'):\n        os.mkdir(\"./figures\")\n    \n    fig.savefig('figures/mip_mult_{}layers_{}_{}.png'.format(Nchb, mode, datetime.now().strftime('%Y%m%d_%H%M')))\n\n    # plt.show()\n    del(fig)\n    print('| \\# of Chamber | Multiplicity |')\n    print('|------|----------------|-----------------------|')\n    for i in range(7,Nchb+1):\n        print(\"|{} | {:.2} \\t|\".format(i, mult_tot[i]))\n\nif __name__ == \"__main__\":\n\n    parser = argparse.ArgumentParser()\n\n    parser.add_argument('-m', '--mode', help='analysis mode (dt, calo or MC)',\n                        default='dt', choices=['dt', 'calo', 'MC'])\n    parser.add_argument('-n', '--Nchb', help='number of layers in the setup',\n                        default='8', choices=['8', '11', '7'])\n    parser.add_argument('-e', '--energy', type=int, help='beam energy in GeV.',\n                        choices=range(2,7))\n    parser.add_argument('-s', '--sigma', type=float, help=\"width of the residual's fluctuation.\",\n                        default=1.)\n    parser.add_argument('--mipeff', help='mip efficiency')\n    parser.add_argument('-p', '--particle', help=\"The type of the beam's particle.\",\n                        default='pions', choices=('pions', 'electrons'))\n    \n    args = parser.parse_args()\n    mode = args.mode\n    if mode == 'MC':\n        energy = '{}GeV'.format(args.energy)\n        particle = args.particle\n        mipeff = args.mipeff\n        # if mipeff not in list(mc.MAX_FILES[particle][energy].keys()):\n        #     raise ValueError('Out of range for specific energy: mipeff.')\n    Nchb = int(args.Nchb)\n\n    warnings.simplefilter('ignore', np.RankWarning)\n    \n\n    if mode not in ['calo', 'dt', 'MC']:\n        raise ValueError('Not a valid type of analysis mode.')\n\n    if mode == 'MC':\n        eff_tot, pool_tot, mult_tot = eff_MC(energy, mipeff, args.sigma, particle=particle, Nchb=Nchb)\n        plot_eff(eff_tot, pool_tot, 'MC', Nchb)\n        plot_mult(mult_tot, 'MC', Nchb)\n    else:\n        eff_tot, pool_tot, mult_tot = eff(mode, Nchb=Nchb)\n        plot_eff(eff_tot, pool_tot, mode, Nchb)\n        plot_mult(mult_tot, mode, Nchb)", "meta": {"hexsha": "0f4c2f08a1b73974514831a1e733fadf63b9828a", "size": 15215, "ext": "py", "lang": "Python", "max_stars_repo_path": "efficiency_estimation.py", "max_stars_repo_name": "dansichi/RPWELL_SDHCAL_analysis", "max_stars_repo_head_hexsha": "3e0b84e134267f8e2f907163fb72314d5e8ee6dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "efficiency_estimation.py", "max_issues_repo_name": "dansichi/RPWELL_SDHCAL_analysis", "max_issues_repo_head_hexsha": "3e0b84e134267f8e2f907163fb72314d5e8ee6dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "efficiency_estimation.py", "max_forks_repo_name": "dansichi/RPWELL_SDHCAL_analysis", "max_forks_repo_head_hexsha": "3e0b84e134267f8e2f907163fb72314d5e8ee6dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.725848564, "max_line_length": 117, "alphanum_fraction": 0.5566217548, "include": true, "reason": "import numpy", "num_tokens": 4229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3415824860330003, "lm_q1q2_score": 0.1734596390375432}}
{"text": "\"\"\"Defines the Instrument class\"\"\"\n#***************************************************************************************************\n# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).\n# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights\n# in this software.\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n# in compliance with the License.  You may obtain a copy of the License at\n# http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory.\n#***************************************************************************************************\nimport collections as _collections\nimport numpy as _np\nimport warnings as _warnings\n\nfrom ..tools import matrixtools as _mt\nfrom .label import Label as _Label\n\n#from . import labeldicts as _ld\nfrom . import modelmember as _gm\nfrom . import operation as _op\nfrom . import spamvec as _sv\n\n\ndef convert(instrument, toType, basis, extra=None):\n    \"\"\"\n    Convert intrument to a new type of parameterization, potentially\n    creating a new object.  Raises ValueError for invalid conversions.\n\n    Parameters\n    ----------\n    instrument : Instrument\n        Instrument to convert\n\n    toType : {\"full\",\"TP\",\"static\",\"static unitary\"}\n        The type of parameterizaton to convert to.  See\n        :method:`Model.set_all_parameterizations` for more details.\n\n    basis : {'std', 'gm', 'pp', 'qt'} or Basis object\n        The basis for `povm`.  Allowed values are Matrix-unit (std),\n        Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt)\n        (or a custom basis object).\n\n    extra : object, optional\n        Additional information for conversion.\n\n    Returns\n    -------\n    Instrument\n       The converted instrument, usually a distinct\n       object from the object passed as input.\n    \"\"\"\n\n    if toType == \"TP\":\n        if isinstance(instrument, TPInstrument):\n            return instrument\n        else:\n            return TPInstrument(list(instrument.items()))\n    elif toType in (\"full\", \"static\", \"static unitary\"):\n        gate_list = [(k, _op.convert(g, toType, basis)) for k, g in instrument.items()]\n        return Instrument(gate_list)\n    else:\n        raise ValueError(\"Cannot convert an instrument to type %s\" % toType)\n\n\nclass Instrument(_gm.ModelMember, _collections.OrderedDict):\n    \"\"\"\n    Meant to correspond to a quantum instrument in theory, this class\n    generalizes that notion slightly to include a collection of gates that may\n    or may not have all of the properties associated by a mathematical quantum\n    instrument.\n    \"\"\"\n\n    def __init__(self, op_matrices, items=[]):\n        \"\"\"\n        Creates a new Instrument object.\n\n        Parameters\n        ----------\n        op_matrices : dict of LinearOperator objects\n            A dict (or list of key,value pairs) of the gates.\n        \"\"\"\n        self._readonly = False  # until init is done\n        if len(items) > 0:\n            assert(op_matrices is None), \"`items` was given when op_matrices != None\"\n\n        dim = None\n        evotype = None\n\n        if op_matrices is not None:\n            if isinstance(op_matrices, dict):\n                matrix_list = [(k, v) for k, v in op_matrices.items()]  # gives definite ordering\n            elif isinstance(op_matrices, list):\n                matrix_list = op_matrices  # assume it's is already an ordered (key,value) list\n            else:\n                raise ValueError(\"Invalid `op_matrices` arg of type %s\" % type(op_matrices))\n\n            items = []\n            for k, v in matrix_list:\n                gate = v if isinstance(v, _op.LinearOperator) else \\\n                    _op.FullDenseOp(v)\n\n                if evotype is None: evotype = gate._evotype\n                else: assert(evotype == gate._evotype), \\\n                    \"All instrument gates must have the same evolution type\"\n\n                if dim is None: dim = gate.dim\n                assert(dim == gate.dim), \"All instrument gates must have the same dimension!\"\n                items.append((k, gate))\n\n        if evotype is None:\n            evotype = \"densitymx\"  # default (if no instrument gates)\n\n        _collections.OrderedDict.__init__(self, items)\n        _gm.ModelMember.__init__(self, dim, evotype)\n        self._paramvec = self._build_paramvec()\n        self._readonly = True\n\n    #No good way to update Instrument on the fly yet...\n    #def _update_paramvec(self, modified_obj=None):\n    #    \"\"\"Updates self._paramvec after a member of this Model is modified\"\"\"\n    #    for obj in self.values():\n    #        assert(obj.gpindices is self), \"Cannot add/adjust parameter vector!\"\n    #\n    #    #update parameters changed by modified_obj\n    #    self._paramvec[modified_obj.gpindices] = modified_obj.to_vector()\n    #\n    #    #re-initialze any members that also depend on the updated parameters\n    #    modified_indices = set(modified_obj.gpindices_as_array())\n    #    for obj in self.values()\n    #        if obj is modified_obj: continue\n    #        if modified_indices.intersection(obj.gpindices_as_array()):\n    #            obj.from_vector(self._paramvec[obj.gpindices])\n\n    def _build_paramvec(self):\n        \"\"\" Resizes self._paramvec and updates gpindices & parent members as needed,\n            and will initialize new elements of _paramvec, but does NOT change\n            existing elements of _paramvec (use _update_paramvec for this)\"\"\"\n        v = _np.empty(0, 'd'); off = 0\n\n        # Step 2: add parameters that don't exist yet\n        for obj in self.values():\n            if obj.gpindices is None or obj.parent is not self:\n                #Assume all parameters of obj are new independent parameters\n                v = _np.insert(v, off, obj.to_vector())\n                num_new_params = obj.allocate_gpindices(off, self)\n                off += num_new_params\n            else:\n                inds = obj.gpindices_as_array()\n                M = max(inds) if len(inds) > 0 else -1; L = len(v)\n                if M >= L:\n                    #Some indices specified by obj are absent, and must be created.\n                    w = obj.to_vector()\n                    v = _np.concatenate((v, _np.empty(M + 1 - L, 'd')), axis=0)  # [v.resize(M+1) doesn't work]\n                    for ii, i in enumerate(inds):\n                        if i >= L: v[i] = w[ii]\n                off = M + 1\n        return v\n\n    def __setitem__(self, key, value):\n        if self._readonly: raise ValueError(\"Cannot alter Instrument elements\")\n        else: return _collections.OrderedDict.__setitem__(self, key, value)\n\n    def __reduce__(self):\n        \"\"\" Needed for OrderedDict-derived classes (to set dict items) \"\"\"\n        #need to *not* pickle parent, as __reduce__ bypasses ModelMember.__getstate__\n        dict_to_pickle = self.__dict__.copy()\n        dict_to_pickle['_parent'] = None\n\n        #Note: must *copy* elements for pickling/copying\n        return (Instrument, (None, [(key, gate.copy()) for key, gate in self.items()]), dict_to_pickle)\n\n    def __pygsti_reduce__(self):\n        return self.__reduce__()\n\n    def simplify_operations(self, prefix=\"\"):\n        \"\"\"\n        Returns a dictionary of gates that belong to the Instrument's parent\n        `Model` - that is, whose `gpindices` are set to all or a subset of\n        this instruments's gpindices.  These are used internally within\n        computations involving the parent `Model`.\n\n        Parameters\n        ----------\n        prefix : str\n            A string, usually identitying this instrument, which may be used\n            to prefix the simplified gate keys.\n\n        Returns\n        -------\n        OrderedDict of Gates\n        \"\"\"\n        #Create a \"simplified\" (Model-referencing) set of element gates\n        simplified = _collections.OrderedDict()\n        if isinstance(prefix, _Label):  # Deal with case when prefix isn't just a string\n            for k, g in self.items():\n                comp = g.copy()\n                comp.set_gpindices(_gm._compose_gpindices(self.gpindices,\n                                                          g.gpindices), self.parent)\n                simplified[_Label(prefix.name + \"_\" + k, prefix.sslbls)] = comp\n        else:\n            if prefix: prefix += \"_\"\n            for k, g in self.items():\n                comp = g.copy()\n                comp.set_gpindices(_gm._compose_gpindices(self.gpindices,\n                                                          g.gpindices), self.parent)\n                simplified[prefix + k] = comp\n        return simplified\n\n    def num_elements(self):\n        \"\"\"\n        Return the number of total gate elements in this instrument.\n        This is in general different from the number of *parameters*,\n        which are the number of free variables used to generate all of\n        the matrix *elements*.\n\n        Returns\n        -------\n        int\n        \"\"\"\n        return sum([g.size for g in self.values()])\n\n    def num_params(self):\n        \"\"\"\n        Get the number of independent parameters which specify this Instrument.\n\n        Returns\n        -------\n        int\n           the number of independent parameters.\n        \"\"\"\n        return len(self._paramvec)\n\n    def to_vector(self):\n        \"\"\"\n        Extract a vector of the underlying gate parameters from this Instrument.\n\n        Returns\n        -------\n        numpy array\n            a 1D numpy array with length == num_params().\n        \"\"\"\n        return self._paramvec\n\n    def from_vector(self, v, close=False, nodirty=False):\n        \"\"\"\n        Initialize the Instrument using a vector of its parameters.\n\n        Parameters\n        ----------\n        v : numpy array\n            The 1D vector of gate parameters.  Length\n            must == num_params().\n\n        Returns\n        -------\n        None\n        \"\"\"\n        assert(len(v) == self.num_params())\n        for gate in self.values():\n            gate.from_vector(v[gate.gpindices], close, nodirty)\n        self._paramvec = v\n\n    def transform(self, S):\n        \"\"\"\n        Update Instrument element matrix G with inv(S) * G * S.\n\n        Parameters\n        ----------\n        S : GaugeGroupElement\n            A gauge group element which specifies the \"S\" matrix\n            (and it's inverse) used in the above similarity transform.\n        \"\"\"\n        #Note: since each Mi is a linear function of MT and the Di, we can just\n        # transform the MT and Di (self.param_ops) and re-init the elements.\n        for gate in self.values():\n            gate.transform(S)\n            self._paramvec[gate.gpindices] = gate.to_vector()\n        self.dirty = True\n\n    def depolarize(self, amount):\n        \"\"\"\n        Depolarize this Instrument by the given `amount`.\n\n        Parameters\n        ----------\n        amount : float or tuple\n            The amount to depolarize by.  If a tuple, it must have length\n            equal to one less than the dimension of the gate. All but the\n            first element of each spam vector (often corresponding to the\n            identity element) are multiplied by `amount` (if a float) or\n            the corresponding `amount[i]` (if a tuple).\n\n        Returns\n        -------\n        None\n        \"\"\"\n        #Note: since each Mi is a linear function of MT and the Di, we can just\n        # depolarize the MT and Di (self.param_ops) and re-init the elements.\n        for gate in self.values():\n            gate.depolarize(amount)\n            self._paramvec[gate.gpindices] = gate.to_vector()\n        self.dirty = True\n\n    def rotate(self, amount, mxBasis='gm'):\n        \"\"\"\n        Rotate this instrument by the given `amount`.\n\n        Parameters\n        ----------\n        amount : tuple of floats, optional\n            Specifies the rotation \"coefficients\" along each of the non-identity\n            Pauli-product axes.  The gate's matrix `G` is composed with a\n            rotation operation `R`  (so `G` -> `dot(R, G)` ) where `R` is the\n            unitary superoperator corresponding to the unitary operator\n            `U = exp( sum_k( i * rotate[k] / 2.0 * Pauli_k ) )`.  Here `Pauli_k`\n            ranges over all of the non-identity un-normalized Pauli operators.\n\n        mxBasis : {'std', 'gm', 'pp', 'qt'} or Basis object\n            The source and destination basis, respectively.  Allowed\n            values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp),\n            and Qutrit (qt) (or a custom basis object).\n\n        Returns\n        -------\n        None\n        \"\"\"\n        #Note: since each Mi is a linear function of MT and the Di, we can just\n        # rotate the MT and Di (self.param_ops) and re-init the elements.\n        for gate in self.values():\n            gate.rotate(amount, mxBasis)\n            self._paramvec[gate.gpindices] = gate.to_vector()\n        self.dirty = True\n\n    def acton(self, state):\n        \"\"\"\n        Act with this instrument upon `state`\n\n        Parameters\n        ----------\n        state : SPAMVec\n            The state to act on\n\n        Returns\n        -------\n        OrderedDict\n            A dictionary whose keys are the outcome labels (strings)\n            and whose values are `(prob, normalized_state)` tuples\n            giving the probability of seeing the given outcome and\n            the resulting state that would be obtained if and when\n            that outcome is observed.\n        \"\"\"\n        # Note: no 'stabilizer' or 'statevec' support yet (how renormalize sframe or how does state vec work?)\n        assert(self._evotype in ('densitymx',)), \\\n            \"acton(...) cannot be used with the %s evolution type!\" % self._evotype\n        assert(state._evotype == self._evotype), \"Evolution type mismatch: %s != %s\" % (self._evotype, state._evotype)\n\n        staterep = state._rep\n        outcome_probs_and_states = _collections.OrderedDict()\n        for lbl, element in self.items():\n            output_rep = element._rep.acton(staterep)\n            output_unnormalized_state = output_rep.todense()\n            prob = output_unnormalized_state[0] * state.dim**0.25\n            output_normalized_state = output_unnormalized_state / prob  # so [0]th == 1/state_dim**0.25\n            outcome_probs_and_states[lbl] = (prob, _sv.StaticSPAMVec(output_normalized_state, self._evotype, 'prep'))\n\n        return outcome_probs_and_states\n\n    def __str__(self):\n        s = \"Instrument with elements:\\n\"\n        for lbl, element in self.items():\n            s += \"%s:\\n%s\\n\" % (lbl, _mt.mx_to_string(element.base, width=4, prec=2))\n        return s\n\n\nclass TPInstrument(_gm.ModelMember, _collections.OrderedDict):\n    \"\"\"\n    A trace-preservng quantum instrument which is a collection of gates whose\n    sum is a trace-preserving map.  The instrument's elements may or may not\n    have all of the properties associated by a mathematical quantum instrument.\n\n    If M1,M2,...Mn are the elements of the instrument, then we parameterize\n    1. MT = (M1+M2+...Mn) as a TPParmeterizedGate\n    2. Di = Mi - MT for i = 1..(n-1) as FullyParameterizedGates\n\n    So to recover M1...Mn we compute:\n    Mi = Di + MT for i = 1...(n-1)\n       = -(n-2)*MT-sum(Di) = -(n-2)*MT-[(MT-Mi)-n*MT] for i == (n-1)\n    \"\"\"\n    #Scratch:\n    #    Scratch\n    # M1+M2+M3+M4  MT\n    #   -M2-M3-M4  M1-MT\n    #-M1   -M3-M4  M2-MT\n    #-M1-M2   -M4  M3-MT\n    #\n    #(M1-MT) + (M2-MT) + (M3-MT) = (MT-M4) - 3*MT = -2*MT-M4\n    # M4 = -(sum(Di)+(4-2=2)*MT) = -(sum(all)+(4-3=1)*MT)\n    #n=2 case: (M1-MT) = (MT-M2)-MT = -M2, so M2 = -sum(Di)\n\n    def __init__(self, op_matrices, items=[]):\n        \"\"\"\n        Creates a new Instrument object.\n\n        Parameters\n        ----------\n        gates : dict of numpy arrays\n            A dict (or list of key,value pairs) of the operation matrices whose sum\n            must be a trace-preserving (TP) map.\n        \"\"\"\n        self._readonly = False  # until init is done\n        if len(items) > 0:\n            assert(op_matrices is None), \"`items` was given when op_matrices != None\"\n\n        dim = None\n        self.param_ops = []  # first element is TP sum (MT), following\n        #elements are fully-param'd (Mi-Mt) for i=0...n-2\n\n        #Note: when un-pickling using items arg, these members will\n        # remain the above values, but *will* be set when state dict is copied\n        # in (so unpickling works as desired)\n\n        if op_matrices is not None:\n            if isinstance(op_matrices, dict):\n                matrix_list = [(k, v) for k, v in op_matrices.items()]  # gives definite ordering\n            elif isinstance(op_matrices, list):\n                matrix_list = op_matrices  # assume it's is already an ordered (key,value) list\n            else:\n                raise ValueError(\"Invalid `op_matrices` arg of type %s\" % type(op_matrices))\n\n            # Create gate objects that are used to parameterize this instrument\n            MT = _op.TPDenseOp(sum([v for k, v in matrix_list]))\n            MT.set_gpindices(slice(0, MT.num_params()), self)\n            self.param_ops.append(MT)\n\n            dim = MT.dim; off = MT.num_params()\n            for k, v in matrix_list[:-1]:\n                Di = _op.FullDenseOp(v - MT)\n                Di.set_gpindices(slice(off, off + Di.num_params()), self)\n                assert(Di.dim == dim)\n                self.param_ops.append(Di); off += Di.num_params()\n\n            #Create a TPInstrumentOp for each operation matrix\n            # Note: TPInstrumentOp sets it's own parent and gpindices\n            items = [(k, _op.TPInstrumentOp(self.param_ops, i))\n                     for i, (k, v) in enumerate(matrix_list)]\n\n            #DEBUG\n            #print(\"POST INIT PARAM GATES:\")\n            #for i,v in enumerate(self.param_ops):\n            #    print(i,\":\\n\",v)\n            #\n            #print(\"POST INIT ITEMS:\")\n            #for k,v in items:\n            #    print(k,\":\\n\",v)\n\n        _collections.OrderedDict.__init__(self, items)\n        _gm.ModelMember.__init__(self, dim, \"densitymx\")\n        self._readonly = True\n\n    def __setitem__(self, key, value):\n        if self._readonly: raise ValueError(\"Cannot alter POVM elements\")\n        else: return _collections.OrderedDict.__setitem__(self, key, value)\n\n    def __reduce__(self):\n        \"\"\" Needed for OrderedDict-derived classes (to set dict items) \"\"\"\n        #Don't pickle TPInstrumentGates b/c they'll each pickle the same\n        # param_ops and I don't this will unpickle correctly.  Instead, just\n        # strip the numpy array from each element and call __init__ again when\n        # unpickling:\n        op_matrices = [(lbl, _np.asarray(val)) for lbl, val in self.items()]\n        return (TPInstrument, (op_matrices, []), {'_gpindices': self._gpindices})\n\n    def __pygsti_reduce__(self):\n        return self.__reduce__()\n\n    def simplify_operations(self, prefix=\"\"):\n        \"\"\"\n        Returns a dictionary of gates that belong to the Instrument's parent\n        `Model` - that is, whose `gpindices` are set to all or a subset of\n        this instruments's gpindices.  These are used internally within\n        computations involving the parent `Model`.\n\n        Parameters\n        ----------\n        prefix : str\n            A string, usually identitying this instrument, which may be used\n            to prefix the simplified gate keys.\n\n        Returns\n        -------\n        OrderedDict of Gates\n        \"\"\"\n        #Create a \"simplified\" (Model-referencing) set of param gates\n        param_simplified = []\n        for g in self.param_ops:\n            comp = g.copy()\n            comp.set_gpindices(_gm._compose_gpindices(self.gpindices,\n                                                      g.gpindices), self.parent)\n            param_simplified.append(comp)\n\n        # Create \"simplified\" elements, which infer their parent and\n        # gpindices from the set of \"param-gates\" they're constructed with.\n        if isinstance(prefix, _Label):  # Deal with case when prefix isn't just a string\n            simplified = _collections.OrderedDict(\n                [(_Label(prefix.name + \"_\" + k, prefix.sslbls), _op.TPInstrumentOp(param_simplified, i))\n                 for i, k in enumerate(self.keys())])\n        else:\n            if prefix: prefix += \"_\"\n            simplified = _collections.OrderedDict(\n                [(prefix + k, _op.TPInstrumentOp(param_simplified, i))\n                 for i, k in enumerate(self.keys())])\n        return simplified\n\n    def num_elements(self):\n        \"\"\"\n        Return the number of total gate elements in this instrument.\n        This is in general different from the number of *parameters*,\n        which are the number of free variables used to generate all of\n        the matrix *elements*.\n\n        Returns\n        -------\n        int\n        \"\"\"\n        return sum([g.size for g in self.values()])\n\n    def num_params(self):\n        \"\"\"\n        Get the number of independent parameters which specify this Instrument.\n\n        Returns\n        -------\n        int\n           the number of independent parameters.\n        \"\"\"\n        return sum([g.num_params() for g in self.param_ops])\n\n    def to_vector(self):\n        \"\"\"\n        Extract a vector of the underlying gate parameters from this Instrument.\n\n        Returns\n        -------\n        numpy array\n            a 1D numpy array with length == num_params().\n        \"\"\"\n        v = _np.empty(self.num_params(), 'd')\n        for gate in self.param_ops:\n            v[gate.gpindices] = gate.to_vector()\n        return v\n\n    def from_vector(self, v, close=False, nodirty=False):\n        \"\"\"\n        Initialize the Instrument using a vector of its parameters.\n\n        Parameters\n        ----------\n        v : numpy array\n            The 1D vector of gate parameters.  Length\n            must == num_params().\n\n        Returns\n        -------\n        None\n        \"\"\"\n        for gate in self.param_ops:\n            gate.from_vector(v[gate.gpindices], close, nodirty)\n        for instGate in self.values():\n            instGate._construct_matrix()\n\n    def transform(self, S):\n        \"\"\"\n        Update Instrument element matrix G with inv(S) * G * S.\n\n        Parameters\n        ----------\n        S : GaugeGroupElement\n            A gauge group element which specifies the \"S\" matrix\n            (and it's inverse) used in the above similarity transform.\n        \"\"\"\n        #Note: since each Mi is a linear function of MT and the Di, we can just\n        # transform the MT and Di (self.param_ops) and re-init the elements.\n        for gate in self.param_ops:\n            gate.transform(S)\n\n        for element in self.values():\n            element._construct_matrix()  # construct from param gates\n        self.dirty = True\n\n    def depolarize(self, amount):\n        \"\"\"\n        Depolarize this Instrument by the given `amount`.\n\n        Parameters\n        ----------\n        amount : float or tuple\n            The amount to depolarize by.  If a tuple, it must have length\n            equal to one less than the dimension of the gate. All but the\n            first element of each spam vector (often corresponding to the\n            identity element) are multiplied by `amount` (if a float) or\n            the corresponding `amount[i]` (if a tuple).\n\n        Returns\n        -------\n        None\n        \"\"\"\n        #Note: since each Mi is a linear function of MT and the Di, we can just\n        # depolarize the MT and Di (self.param_ops) and re-init the elements.\n        for gate in self.param_ops:\n            gate.depolarize(amount)\n\n        for element in self.values():\n            element._construct_matrix()  # construct from param gates\n        self.dirty = True\n\n    def rotate(self, amount, mxBasis='gm'):\n        \"\"\"\n        Rotate this instrument by the given `amount`.\n\n        Parameters\n        ----------\n        amount : tuple of floats, optional\n            Specifies the rotation \"coefficients\" along each of the non-identity\n            Pauli-product axes.  The gate's matrix `G` is composed with a\n            rotation operation `R`  (so `G` -> `dot(R, G)` ) where `R` is the\n            unitary superoperator corresponding to the unitary operator\n            `U = exp( sum_k( i * rotate[k] / 2.0 * Pauli_k ) )`.  Here `Pauli_k`\n            ranges over all of the non-identity un-normalized Pauli operators.\n\n        mxBasis : {'std', 'gm', 'pp', 'qt'} or Basis object\n            The source and destination basis, respectively.  Allowed\n            values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp),\n            and Qutrit (qt) (or a custom basis object).\n\n        Returns\n        -------\n        None\n        \"\"\"\n        #Note: since each Mi is a linear function of MT and the Di, we can just\n        # rotate the MT and Di (self.param_ops) and re-init the elements.\n        for gate in self.param_ops:\n            gate.rotate(amount, mxBasis)\n\n        for element in self.values():\n            element._construct_matrix()  # construct from param gates\n        self.dirty = True\n\n    def __str__(self):\n        s = \"TPInstrument with elements:\\n\"\n        for lbl, element in self.items():\n            s += \"%s:\\n%s\\n\" % (lbl, _mt.mx_to_string(element.base, width=4, prec=2))\n        return s\n", "meta": {"hexsha": "c157b22abfbb5e3a2baf8d0154c57e6277458993", "size": 25283, "ext": "py", "lang": "Python", "max_stars_repo_path": "pygsti/objects/instrument.py", "max_stars_repo_name": "drewrisinger/pyGSTi", "max_stars_repo_head_hexsha": "dd4ad669931c7f75e026456470cf33ac5b682d0d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-19T15:11:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T15:11:09.000Z", "max_issues_repo_path": "pygsti/objects/instrument.py", "max_issues_repo_name": "drewrisinger/pyGSTi", "max_issues_repo_head_hexsha": "dd4ad669931c7f75e026456470cf33ac5b682d0d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pygsti/objects/instrument.py", "max_forks_repo_name": "drewrisinger/pyGSTi", "max_forks_repo_head_hexsha": "dd4ad669931c7f75e026456470cf33ac5b682d0d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.777607362, "max_line_length": 118, "alphanum_fraction": 0.5828817783, "include": true, "reason": "import numpy", "num_tokens": 5796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3415824860330003, "lm_q1q2_score": 0.1734596390375432}}
{"text": "#!/usr/bin/env python3\nimport copy\nimport logging\nimport os\nimport sys\nimport tempfile\n\nimport numpy as np\nimport offsb.op.geometry\nimport simtk.unit\nimport simtk.unit as unit\nimport offsb.treedi\nimport offsb.treedi.tree\nfrom rdkit import Chem\nfrom simtk import openmm\n\nimport openforcefield as oFF\nfrom openforcefield.topology import Molecule\nfrom openforcefield.typing.engines.smirnoff.parameters import \\\n    UnassignedProperTorsionParameterException\n\nfrom .. import qcarchive as qca\nfrom .. import rdutil\nfrom ..tools import const\n\nlogger = logging.getLogger(__name__)\noFFlogger = logging.getLogger(\"openforcefield\")\noFFlogger.setLevel(logging.ERROR)\n\n\ndef load_geometric_opt_trj_xyz(fnm, dims=3):\n    N = 0\n    xyz = []\n    with open(fnm, \"r\") as fd:\n        N = int(fd.readline().split()[0])\n        total_N = 1\n        for line in fd:\n            total_N += 1\n        n_frames = total_N // (N + 2)\n    ene_in_au = []\n    sym = list([\"\"] * N)\n    with open(fnm, \"r\") as fd:\n        xyz = np.empty((n_frames, N, dims))\n        for j in range(n_frames):\n            N = int(fd.readline().split()[0])\n            energy = float(fd.readline().split()[-1])\n            ene_in_au.append(energy)\n            for i in range(N):\n                line = fd.readline().split()\n                pos = line[1:]\n                sym[i] = line[0]\n                xyz[j][i][:] = list(map(float, pos))\n\n    # xyz in angstrom\n    return sym, xyz, np.array(ene_in_au)\n\n\nclass OpenMMEnergy(offsb.treedi.tree.PartitionTree):\n    \"\"\"Creates an openMM system of each entry\n    Stores the total energy of molecules\n    \"\"\"\n\n    def __init__(self, filename, source_tree, name):\n        super().__init__(source_tree, name)\n        import logging\n\n        logger = logging.getLogger()\n        level = logger.getEffectiveLevel()\n        logger.setLevel(level=logging.ERROR)\n        from pkg_resources import iter_entry_points\n\n        self.filename = filename\n\n        self._select = \"Molecule\"\n        self.minimize = False\n        self.constrain = False\n        self.geometric = True\n\n        # Seems to bottleneck at 4, so mask here to avoid memory waste\n        self.processes = 4\n        search_pth = list(\n            iter_entry_points(group=\"openforcefield.smirnoff_forcefield_directory\")\n        )\n        abspth = os.path.join(\".\", filename)\n        print(\"Searching\", \".\")\n        found = False\n        if os.path.exists(abspth):\n            self.abs_path = abspth\n            print(\"Found\")\n            found = True\n        if not found:\n            for entry_point in search_pth:\n                pth = entry_point.load()()[0]\n                abspth = os.path.join(pth, filename)\n                abspth = abspth if abspth.endswith(\"offxml\") else abspth + \".offxml\"\n                print(\"Searching\", abspth)\n                if os.path.exists(abspth):\n                    self.abs_path = abspth\n                    print(\"Found\")\n                    break\n                raise Exception(\"Forcefield could not be found\")\n        self.forcefield = oFF.typing.engines.smirnoff.ForceField(\n            self.abs_path, disable_version_check=True, allow_cosmetic_attributes=True\n        )\n        logger.setLevel(level=level)\n        print(\"My db is\", self.db)\n\n    def to_pickle(self, db=True, name=None):\n        super().to_pickle(db=db, name=name)\n\n    def _apply_initialize(self, targets):\n        pass\n\n    def _apply_finalize(self, targets):\n        pass\n\n    def _unpack_result(self, ret):\n        self.db.update(ret)\n\n    def _generate_apply_kwargs(self, i, target, kwargs=None):\n\n        # labels = self.source.db[target.payload][\"data\"]\n        entry = self.source.source.db[target.payload][\"data\"]\n\n        out_str = \"\"\n\n        if kwargs is None:\n            kwargs = {}\n\n        mol = kwargs.get(\"mol\")\n\n        if mol is None:\n            smi = entry.attributes[\"canonical_isomeric_explicit_hydrogen_mapped_smiles\"]\n            if \"initial_molecule\" in entry.dict():\n                qcid = entry.dict()[\"initial_molecule\"]\n            elif \"initial_molecules\" in entry.dict():\n                qcid = entry.dict()[\"initial_molecules\"]\n            else:\n                out_str += \"{:d} initial mol was empty: {:s}\".format(i, str(qcid))\n                return {\"error\": out_str}\n\n            if isinstance(qcid, set):\n                qcid = list(qcid)\n            if isinstance(qcid, list):\n                qcid = str(qcid[0])\n\n            qcmolid = \"QCM-\" + qcid\n\n            if qcmolid not in self.source.source.db:\n                out_str += \"{:d} initial mol was empty: {:s}\".format(i, str(qcmolid))\n                return {\"error\": out_str}\n\n            if \"data\" in self.source.source.db.get(qcmolid):\n                qcmol = self.source.source.db.get(qcmolid).get(\"data\")\n            else:\n                out_str += \"{:d} initial mol was empty: {:s}\".format(i, str(qcmolid))\n                return {\"error\": out_str}\n\n            mol = offsb.rdutil.mol.rdmol_from_smiles_and_qcmol(smi, qcmol)\n            kwargs[\"mol\"] = mol\n            kwargs[\"qcmolid\"] = qcmolid\n\n    def apply_single(self, i, target, **kwargs):\n        def unmap(xyz, map_idx):\n            inv = [(map_idx[i] - 1) for i in range(len(xyz))]\n            return xyz[inv]\n\n        def remap(xyz, map_idx):\n            remap_idx = {v - 1: k for k, v in map_idx.items()}\n            inv = [remap_idx[i] for i in range(len(xyz))]\n            return xyz[inv]\n\n        # mol = kwargs[\"mol\"]\n        # qcmolid = kwargs[\"qcmolid\"]\n\n        ret_str = []\n        # if n < 192:\n        #    continue\n        entry_node = next(self.source.node_iter_to_root(target, select=\"Entry\"))\n        attrs = self.source.db[entry_node.payload][\"data\"].dict()[\"attributes\"]\n        # attrs = self.source.db[target.payload]['data'].dict()['attributes']\n\n        # Since we now have spec nodes, need one under the spec\n        # Just grab the first.. only need metadata (e.g. mapping)\n        try:\n            mol_node = next(\n                self.source.node_iter_depth_first(entry_node, select=\"Molecule\")\n            )\n        except Exception:\n            ret_str.append(\n                \"ERROR: This job has no molecules: {} {}\\n\".format(\"\", target.payload)\n            )\n            return {target: ret_str}\n            # Likely StopIteration (no molecules; all failed)\n\n        qcmol = self.source.db[mol_node.payload][\"data\"]\n\n        #         if isinstance(qcmolid, list):\n        #             qcmolid = qcmolid[0]\n        #         qcmolid = \"QCM-\" + str(qcmolid)\n        #         breakpoint()\n        #         if qcmolid in self.source.db:\n        #             qcmol = self.source.db.get(qcmolid).get(\"data\")\n        #         else:\n        #             ret_str.append(\n        #                 \"ERROR: Molcule ID {:s} not in the local database\\n\".format(qcmolid)\n        #             )\n        #             return {target: ret_str}\n\n        smiles_pattern = attrs.get(\"canonical_isomeric_explicit_hydrogen_mapped_smiles\")\n\n        mol = rdutil.mol.build_from_smiles(smiles_pattern)\n        map_idx = rdutil.mol.atom_map(mol)\n        ret = rdutil.mol.embed_qcmol_3d(mol, qcmol)\n        if ret < 0:\n            ret_str.append(\n                \"ERROR: Could not generate a conformation in RDKit. {} {}\\n\".format(\n                    \"\", target.payload\n                )\n            )\n            qca.qcmol_to_xyz(\n                qcmol,\n                fnm=\"mol.\" + \"\" + \".\" + target.index + \".rdconfgenfail.xyz\",\n                comment=\"\" + \" rdconfgen fail \" + target.payload,\n            )\n            return {target: ret_str}\n        # conf = mol.GetConformer()\n        # ids = AllChem.EmbedMultipleConfs( mol, numConfs=1)\n        # try:\n        #    conf = mol.GetConformer(ids[0])\n        # except IndexError:\n        #    print(\"ERROR: Could not generate a conformation in RDKit.\", qcmolid, target.payload)\n        #    qca.qcmol_to_xyz( qcmol,\n        #        fnm=\"mol.\"+qcmolid+\".\"+target.payload+\".rdconfgenfail.xyz\", comment=qcmolid + \" rdconfgen fail \" + target.payload)\n        #    continue\n        # conf = mol.GetConformer(ids[0])\n\n        use_min_mol_for_charge = True\n        if use_min_mol_for_charge:\n            minidx = None\n            minene = None\n            minmol = None\n            try:\n                for opt in self.source.node_iter_depth_first(\n                    target, select=\"Optimization\"\n                ):\n                    opt_rec = self.source.db[opt.payload][\"data\"]\n                    status = opt_rec.status[:]\n                    if status != \"COMPLETE\":\n                        ret_str.append(\"This opt is not complete.. skipping..\\n\")\n                        continue\n                    allene = opt_rec.energies\n                    if allene is None:\n                        ret_str.append(\n                            \"ERROR: No energies. {} {}\\n\".format(\"\", target.payload)\n                        )\n                        # ret_str.append(str(e) + \"\\n\")\n                        qca.qcmol_to_xyz(\n                            qcmol,\n                            fnm=\"mol.\" + \"\" + \".\" + target.index + \".noenefail.xyz\",\n                            comment=\"\" + \" noene fail \" + target.payload,\n                        )\n                        return {target: ret_str}\n                    ene = allene[-1]\n                    if minene is None:\n                        minene = ene\n                        minidx = opt.children[-1]\n                    elif ene < minene:\n                        minene = ene\n                        minidx = opt.children[-1]\n            except (TypeError, IndexError) as e:\n                # ene is not a list above if TypeError\n                # IndexError it is []\n                ret_str.append(\"ERROR: No energies. {} {}\\n\".format(\"\", target.payload))\n                ret_str.append(str(e) + \"\\n\")\n                qca.qcmol_to_xyz(\n                    qcmol,\n                    fnm=\"mol.\" + \"\" + \".\" + target.index + \".noenefail.xyz\",\n                    comment=\"\" + \" noene fail \" + target.payload,\n                )\n                return {target: ret_str}\n\n            if minidx == None:\n                ret_str.append(\"EMPTY. SKIPPING\\n\")\n                return {target: ret_str}\n            grad_node = self.source.node_index[minidx]\n            mol_node = self.source.node_index[grad_node.children[0]]\n            qcmol = self.source.db[mol_node.payload][\"data\"]\n\n            ret_str.append(\"min mol is {} ene is {} au\\n\".format(mol_node, minene))\n\n        xyz = qcmol.geometry\n        sym = qcmol.symbols\n        # for i, a in enumerate(mol.GetAtoms()):\n        #    conf.SetAtomPosition(i, xyz[ map_idx[ i] - 1] * const.bohr2angstrom)\n\n        # Chem.rdmolops.AssignStereochemistryFrom3D( mol, ids[0], replaceExistingTags=True)\n        # Chem.rdmolops.AssignStereochemistryFrom3D( mol, ids[0], replaceExistingTags=True)\n        Chem.rdmolops.AssignAtomChiralTagsFromStructure(\n            mol, -1, replaceExistingTags=True\n        )\n\n        with tempfile.TemporaryDirectory() as tmpdir:\n            cwd = os.getcwd()\n            os.chdir(tmpdir)\n            mmol = oFF.topology.Molecule.from_rdkit(mol, allow_undefined_stereo=True)\n            try:\n                top = oFF.topology.Topology().from_molecules(mmol)\n            except AssertionError:\n                ret_str.append(\n                    \"ERROR: Could not setup molecule in oFF. {} {}\\n\".format(\n                        \"\", target.payload\n                    )\n                )\n                qca.qcmol_to_xyz(\n                    qcmol,\n                    fnm=\"mol.\" + \"\" + \".\" + target.index + \".offmolfail.xyz\",\n                    comment=\"\" + \" oFF fail \" + target.payload,\n                )\n                # pdb.set_trace()\n                return {target: ret_str}\n            try:\n                mmol.compute_partial_charges_am1bcc()\n\n            except Exception as e:\n                os.chdir(cwd)\n                ret_str.append(\n                    \"ERROR: Could not compute partial charge. {} {}\\n\".format(\n                        \"\", target.payload\n                    )\n                )\n                ret_str.append(str(e.__traceback__.__repr__()) + \"\\n\")\n                ret_str.append(str(e) + \"\\n\")\n                qca.qcmol_to_xyz(\n                    qcmol,\n                    fnm=\"mol.\" + \"\" + \".\" + target.index + \".chrgfail.xyz\",\n                    comment=\"\" + \" charge fail \" + target.payload,\n                )\n                # pdb.set_trace()\n                return {target: ret_str}\n            os.chdir(cwd)\n\n        gen_MM_charge = [mmol.partial_charges]\n\n        fail = True\n        nodes = list(self.source.node_iter_depth_first(target, select=\"Molecule\"))\n        order = np.arange(len(nodes))\n        vals = []\n        for mol_node in nodes:\n            val = tuple(\n                [\n                    c.payload[2]\n                    for c in self.source.node_iter_to_root(\n                        mol_node, select=\"Constraint\"\n                    )\n                ]\n            )\n            if len(val) > 0:\n                vals.append(val)\n        if len(vals) > 0:\n            vals = np.array(vals)\n            order = np.lexsort(vals.T)\n            nodes_in_order = [nodes[i] for i in order]\n        else:\n            nodes_in_order = nodes\n\n        ret_obj = {}\n\n        for mol_node in nodes_in_order:\n            fail = True\n            qcmol = self.source.db[mol_node.payload][\"data\"]\n            xyz = qcmol.geometry\n            xyz = xyz * const.bohr2angstrom\n\n            # this will take the xyz from qcmol and put them in the order of\n            # the cmiles, based on the mapped indices (1-index)\n            # sends qcmol to mmmol\n            xyz = unmap(xyz, map_idx)\n\n            constraints = None\n            if self.constrain:\n                # constraints = [ [c.payload[1], c.payload[2]] for c in \\\n                # self.source.node_iter_to_root( mol_node, select=\"Constraint\")]\n                # print(\"constraints are\", constraints)\n                swap_map = {v - 1: k for k, v in map_idx.items()}\n                constraints = [\n                    [[swap_map[i] for i in c.payload[1]], c.payload[2]]\n                    for c in self.source.node_iter_to_root(\n                        mol_node, select=\"Constraint\"\n                    )\n                ]\n                # qca.qcmol_to_xyz( {\"symbols\": unmap(qcmol['symbols'],  map_idx), \"geometry\":xyz*const.angstrom2bohr},\n                #     fnm=\"mol.\"+qcmolid+\".\"+target.index+\".map.xyz\", comment=qcmolid + \" map fail \" + str(constraints))\n                # constraints = [ [unmap(np.array(c.payload[1]), map_idx), c.payload[2]] for c in \\\n                # self.source.node_iter_to_root( mol_node, select=\"Constraint\")]\n\n                # print(\"angle before OpenMM is \", self.calculate_dihedral(xyz, *constraints[0][0])/unit.degrees)\n                # print(\"constraints are\", constraints)\n            try:\n                total_ene, pos = self.calc_mm_energy(\n                    top, xyz, charge=gen_MM_charge, constraints=constraints\n                )\n                fail = False\n            except UnassignedProperTorsionParameterException as e:\n                ret_str.append(\n                    \"ERROR: oFF could not assign torsion for {} {}\\n\".format(\n                        qcmolid, target.payload\n                    )\n                )\n                ret_str.append(str(e) + \"\\n\")\n                break\n            except Exception as e:\n                ret_str.append(\n                    \"ERROR: oFF exception for {} {}\\n\".format(qcmolid, target.payload)\n                )\n                ret_str.append(str(e.__traceback__.__repr__()) + \"\\n\")\n                ret_str.append(str(e) + \"\\n\")\n                fail = True\n                break\n\n            constraints = [\n                c.payload\n                for c in self.source.node_iter_to_root(mol_node, select=\"Constraint\")\n            ]\n            # print(\"    {} {} {}\\n\".format( mol_node, constraints, total_ene), end=\"\")\n            ret_str.append(\"    {} {} {}\\n\".format(mol_node, constraints, total_ene))\n\n            pl = {}\n            if self.minimize and pos is not None:\n                pl = qcmol.copy()\n                pl.geometry = remap(np.array(pos) * const.angstrom2bohr, map_idx)\n\n            pl[\"energy\"] = total_ene\n\n            ret_obj.update({mol_node.payload: {\"data\": pl}})\n            # self.db.__setitem__( )\n\n        if fail:\n            qca.qcmol_to_xyz(\n                qcmol,\n                fnm=\"mol.\" + qcmolid + \".\" + target.index + \".labelfail.xyz\",\n                comment=qcmolid + \" label fail \" + target.payload,\n            )\n        return {target: ret_str, \"return\": ret_obj}\n\n    def apply(self, targets=None):\n        if targets is None:\n            targets = list(self.source.iter_entry())\n        elif not hasattr(targets, \"__iter__\"):\n            targets = [targets]\n\n        # expand if a generator\n        targets = list(targets)\n\n        n_targets = len(targets)\n\n        if self.processes is None or self.processes > 1:\n            import concurrent.futures\n\n            exe = concurrent.futures.ProcessPoolExecutor(max_workers=self.processes)\n\n            work = [\n                exe.submit(OpenMMEnergy.apply_single, self, n, target)\n                for n, target in enumerate(targets, 1)\n            ]\n            for n, future in enumerate(concurrent.futures.as_completed(work), 1):\n                if future.done:\n                    try:\n                        val = future.result()\n                    except RuntimeError:\n                        print(\"RUNTIME ERROR; race condition??\")\n                if val is None:\n                    print(\"data is None?!?\")\n                    continue\n                for tgt, ret in val.items():\n                    if tgt == \"return\":\n                        self.db.update(ret)\n                    else:\n                        print(n, \"/\", n_targets, tgt)\n                        for line in ret:\n                            print(line, end=\"\")\n\n            exe.shutdown()\n\n        # # This version seems to be more stable, but all of the results must\n        # # finish before iterating\n\n        # exe = Pool(processes=self.processes)\n        # work = [ exe.apply_async( OpenMMEnergy.apply_single, ( self, n, target) ) for n, target in enumerate(targets, 1) ]\n        # out = [result.get() for result in work if result is not None]\n        # for n, val in enumerate(out, 1):\n        #     for tgt, ret in val.items():\n        #         if tgt == \"return\":\n        #             self.db.update(ret)\n        #         else:\n        #             print( n,\"/\", n_targets, tgt)\n        #             for line in ret:\n        #                 print(line, end=\"\")\n        # exe.close()\n\n        # for i, val in enumerate( out):\n        #     for tgt, ret in val.items():\n        #         print( n,\"/\", n_targets, tgt)\n        #         print( ret)\n\n        # single process mode; does not launch any new processes\n        if self.processes == 1:\n            for n, target in enumerate(targets, 1):\n                val = self.apply_single(n, target)\n                for tgt, ret in val.items():\n                    if tgt == \"return\":\n                        self.db.update(ret)\n                    else:\n                        print(n, \"/\", n_targets, tgt)\n                        for line in ret:\n                            print(line, end=\"\")\n        ########################################\n\n    def calculate_dihedral(self, coords, idx1, idx2, idx3, idx4):\n        # from:\n        # https://math.stackexchange.com/questions/47059/how-do-i-calculate-a-dihedral-angle-given-cartesian-coordinates\n        # https://stackoverflow.com/questions/20305272/dihedral-torsion-angle-from-four-points-in-cartesian-coordinates-in-python\n        b1 = coords[idx1] - coords[idx2]\n        b1 /= np.sqrt(np.dot(b1, b1))\n        b2 = coords[idx2] - coords[idx3]\n        b2 /= np.sqrt(np.dot(b2, b2))\n        b3 = coords[idx3] - coords[idx4]\n        b3 /= np.sqrt(np.dot(b3, b3))\n        # print (b1, b2, b3)\n        n1 = np.cross(b1, b2)\n        n2 = np.cross(b2, b3)\n        m1 = np.cross(n1, b2)\n        # print ( n1,n2,m1 )\n        x = np.dot(n2, n1)\n        y = np.dot(n2, m1)\n        theta = np.arctan2(y, x) * unit.radian\n        # print ( theta, np.degrees ( theta ) * unit.degree )\n        return theta\n\n    def add_harmonic_dihedral_restraints(\n        self, system, coords, k, hw, indices_to_restrain, debug=False\n    ):\n        print(\"Adding harmonic dihedral restraints: \")\n        if len(indices_to_restrain) != 4:\n            print(\n                \"WARNING: Must be exactly 4 atoms specified for a dihedral restraint.  Skipping ...\"\n            )\n            return system\n        theta0 = self.calculate_dihedral(coords, *indices_to_restrain)  # in radians\n        print(theta0)\n        expr = \"0.5*k*max(0,( min(d_theta,2*pi-d_theta) - hw ))^2;\"\n        expr += \"d_theta = abs(theta - theta0);\"\n        expr += f\"pi = {np.pi:.10f}\"\n        force = openmm.CustomTorsionForce(expr)\n        force.addGlobalParameter(\"k\", k)\n        force.addGlobalParameter(\"hw\", hw)\n        force.addPerTorsionParameter(\"theta0\")\n        force.addTorsion(*indices_to_restrain, [theta0])\n        system.addForce(force)\n        return system\n\n    def mm_potential(\n        self, forcefield, top, xyz, charge=False, constraints=None, use_geometric=False\n    ):\n\n        if isinstance(charge, bool):\n            if charge:\n                system = forcefield.create_openmm_system(top)\n            else:\n                mols = [\n                    Molecule(mol.reference_molecule) for mol in top.topology_molecules\n                ]\n                for i, _ in enumerate(mols):\n                    mols[i].partial_charges = simtk.unit.Quantity(\n                        np.zeros(mols[i].n_atoms), simtk.unit.elementary_charge\n                    )\n                system = forcefield.create_openmm_system(\n                    top, charge_from_molecules=mols\n                )\n        else:\n            mols = [Molecule(mol.reference_molecule) for mol in top.topology_molecules]\n            for i, _ in enumerate(mols):\n                mols[i].partial_charges = charge[i]\n            system = forcefield.create_openmm_system(top, charge_from_molecules=mols)\n\n        integrator = openmm.VerletIntegrator(0.1 * simtk.unit.femtoseconds)\n        sim = openmm.app.simulation.Simulation(top, system, integrator)\n        sim.context.setPositions(xyz * const.angstrom2nm)\n\n        # params = forcefield.label_molecules(top)[0]\n        # for p in params:\n        #     print(p)\n        #     print(dict(params[p]))\n\n        getPositions = self.minimize\n        # system = sim.context.getSystem()\n        # forces = system.getForces()\n        use_geometric = self.geometric\n        if True and use_geometric and self.minimize:\n\n            import geometric.optimize as geoopt\n\n            with tempfile.TemporaryDirectory() as tmpdir:\n                cwd = os.getcwd()\n                os.chdir(tmpdir)\n                system = forcefield.create_openmm_system(\n                    top, charge_from_molecules=mols\n                )\n                xml = openmm.XmlSerializer.serialize(system)\n                open(\"system.xml\", \"w\").write(xml)\n                with open(\"mol.pdb\", \"w\") as fid:\n                    openmm.app.pdbfile.PDBFile.writeFile(top.to_openmm(), xyz, fid)\n\n                args = {\n                    \"input\": \"system.xml\",\n                    \"pdb\": \"mol.pdb\",\n                    \"openmm\": True,\n                    \"maxiter\": 2000,\n                }\n                if constraints is not None:\n\n                    with open(\"constraints\", \"w\") as fid:\n                        fid.write(\"$set\\n\")\n                        for constr in constraints:\n                            ids = [x + 1 for x in constr[0]]\n                            val = constr[1]\n                            out_str = \"dihedral {:d} {:d} {:d} {:d} {:12.5f}\\n\".format(\n                                *ids, val\n                            )\n                            # out_str = \"dihedral {:d} {:d} {:d} {:d}\\n\".format(*ids)\n                            fid.write(out_str)\n                            # print(out_str, end=\"\")\n                    args[\"constraints\"] = \"constraints\"\n\n                success = False\n                with tempfile.TemporaryFile(\"w\") as null:\n                    sys.stderr = null\n                    try:\n                        geoopt.run_optimizer(**args)\n                        success = True\n                    except Exception as e:\n                        print(\"This optimization failed!\")\n                        print(e)\n                    sys.stderr = sys.__stderr__\n                    if success:\n                        _, traj, ene = load_geometric_opt_trj_xyz(\"system_optim.xyz\")\n                os.chdir(cwd)\n\n            if not success:\n                return None, None\n\n            return ene[-1] * const.hartree2kcalmol, traj[-1]\n\n        elif True and self.minimize and constraints is not None:\n            # print(\"Using frozen torsion...\")\n            for constr in constraints:\n                # assume torsion...\n                # print(\"Searching torsion\", constr)\n                for idx in constr[0]:\n                    system.setParticleMass(idx, 0.0)\n            if self.minimize:\n                sim.minimizeEnergy()\n            state = sim.context.getState(getEnergy=True, getPositions=getPositions)\n            energy = state.getPotentialEnergy().in_units_of(\n                simtk.unit.kilocalories_per_mole\n            )\n            pos = None\n            if self.minimize:\n                pos = state.getPositions(asNumpy=True) / simtk.unit.angstroms\n\n        elif False and self.minimize and constraints is not None:\n            print(\"Using custom torsion force...\")\n            cforce = openmm.CustomTorsionForce(\n                \"0.5*k*max(0.0,min(dtheta, 2*pi-dtheta))^2; dtheta = abs(theta-theta0); pi = 3.1415926535\"\n            )\n            cforce.addPerTorsionParameter(\"k\")\n            cforce.addPerTorsionParameter(\"theta0\")\n            for constr in constraints:\n                # assume torsion...\n                # print(\"Searching torsion\", constr)\n                if len(constr[0]) == 4:\n                    print(\"adding torsion\", constr[0])\n                    cforce.addTorsion(*constr[0], [300.0, constr[1] * np.pi / 180])\n\n            # print(\"adding force...\")\n            iforce = system.addForce(cforce)\n\n            integrator = openmm.VerletIntegrator(0.1 * simtk.unit.femtoseconds)\n            sim = openmm.app.simulation.Simulation(top, system, integrator)\n            sim.context.setPositions(xyz * const.angstrom2nm)\n            getPositions = self.minimize\n            # system = sim.context.getSystem()\n            # forces = system.getForces()\n            state = sim.context.getState(getEnergy=True, getPositions=getPositions)\n            energy = state.getPotentialEnergy().in_units_of(\n                simtk.unit.kilocalories_per_mole\n            )\n            print(\"energy is\", energy)\n            if self.minimize:\n                sim.minimizeEnergy()\n            state = sim.context.getState(getEnergy=True, getPositions=getPositions)\n            energy = state.getPotentialEnergy().in_units_of(\n                simtk.unit.kilocalories_per_mole\n            )\n            pos = state.getPositions(asNumpy=True) / simtk.unit.nanometers\n            print(\"energy is\", energy)\n\n            system2 = forcefield.create_openmm_system(top, charge_from_molecules=mols)\n            integrator = openmm.VerletIntegrator(0.1 * simtk.unit.femtoseconds)\n            sim = openmm.app.simulation.Simulation(top, system2, integrator)\n            sim.context.setPositions(pos)\n            state = sim.context.getState(getEnergy=True, getPositions=getPositions)\n            energy = state.getPotentialEnergy().in_units_of(\n                simtk.unit.kilocalories_per_mole\n            )\n            print(\"energy is\\n\", energy)\n            pos = None\n            if self.minimize:\n                pos = state.getPositions(asNumpy=True) / simtk.unit.angstroms\n            return energy, pos\n\n        elif self.minimize and constraints is not None:\n            forces = system.getForces()\n            print(\"Using iterative torsion force...\")\n            state = sim.context.getState(getEnergy=True, getPositions=getPositions)\n            pos = state.getPositions(asNumpy=True) / simtk.unit.angstroms\n            print(\n                \"angle before OpenMM opt is \",\n                self.calculate_dihedral(pos, *constraints[0][0]) / unit.degrees,\n            )\n            dx = list([np.inf] * len(constraints))\n            dk = 1.0 * simtk.unit.kilojoules_per_mole\n            dE = 0.0\n            energy = 0.0\n            eps = 0.001\n            maxsteps = 100000\n            nstep = 0\n            pha = None\n            k = None\n            per = 0\n            ref_k = None\n            ref_pha = None\n            while nstep < maxsteps and all([abs(dxi) > eps for dxi in dx]):\n                for constr in constraints:\n                    # assume torsion...\n                    # print(\"Searching torsion\", constr)\n                    if len(constr[0]) == 4:\n\n                        torsions = [\n                            f for f in forces if type(f) == openmm.PeriodicTorsionForce\n                        ][0]\n                        N = torsions.getNumTorsions()\n                        found = False\n                        # print(\"Found N existing torsions:\", N)\n\n                        if pha is None:\n                            pha = constr[1] * np.pi / 180\n                        for idx in range(N):\n                            (\n                                p1,\n                                p2,\n                                p3,\n                                p4,\n                                per,\n                                phai,\n                                ki,\n                            ) = torsions.getTorsionParameters(idx)\n                            if k is None:\n                                k = ki\n                                ref_k = ki\n                                ref_pha = phai\n                            target = tuple(constr[0])\n                            if target[-1] < target[0]:\n                                target = tuple(target[::-1])\n                            # print(\"Retreived\", p1,p2,p3,p4,per,pha,ki, target)\n                            if tuple([p1, p2, p3, p4]) == target:\n                                # print(\"retreived\", idx, p1,p2,p3,p4,per,phai,ki)\n                                # print(\"Found torsion\", target, constr[1])\n                                # print(\"mass: \", [system.getParticleMass(x) for x in constr[0]])\n                                k += dk\n                                # per = 1\n                                # print(\"setting\", idx, p1,p2,p3,p4,per,pha,k)\n                                torsions.setTorsionParameters(\n                                    idx, p1, p2, p3, p4, per, pha, k\n                                )\n                                found = True\n                                # print(\"Set to\", idx, p1, p2, p3, p4, per, pha, k)\n                        if not found:\n                            raise Exception(\"The constrained torsion was not found!\")\n                            # p1,p2,p3,p4 = constr[0]\n                            # pha = constr[1]*np.pi/180.\n                            # k = 9999999.0\n                            # per = 1\n                            # constr[1],  torsions.addTorsion(p1,p2,p3,p4,per,pha,k)\n                        torsions.updateParametersInContext(sim.context)\n                sim.minimizeEnergy(tolerance=1e-5, maxIterations=1)\n                state = sim.context.getState(getEnergy=True, getPositions=getPositions)\n                energy2 = state.getPotentialEnergy() / simtk.unit.kilocalories_per_mole\n                pos = state.getPositions(asNumpy=True) / simtk.unit.angstroms\n\n                # now check to see if the constraints moved\n                for i, constr in enumerate(constraints):\n                    # assume torsion...\n                    # print(\"Calculating torsion\", constr)\n                    if len(constr[0]) == 4:\n                        angle = offsb.op.geometry.TorsionOperation.measure_praxeolitic_single(\n                            {\"geometry\": pos}, list(target)\n                        )\n                        dx[i] = abs(angle - constr[1])\n                        dE = energy2 - energy\n                        energy = energy2\n                        # print(\"Dx\", i, \"is \", dx[i], \"k=\", k, target, constr[1], angle,\"dE=\",dE, \"pha=\", pha * 180/np.pi)\n                        angle2 = (\n                            self.calculate_dihedral(pos, *list(target)) / unit.degrees\n                        )\n                        if (\n                            nstep == 0\n                            or nstep == maxsteps\n                            or all([abs(dxi) < eps for dxi in dx])\n                        ):\n                            print(\n                                \"C {:d} dt= {:14.8e} k= {:12.3f} {:s} t_0= {:6.2f} t= {:6.2f} t2= {:6.2f} dE= {:16.8e} pha= {:14.8e}\".format(\n                                    i,\n                                    dx[i],\n                                    k / unit.kilojoules_per_mole,\n                                    str(target),\n                                    constr[1],\n                                    angle,\n                                    angle2,\n                                    dE,\n                                    pha * 180 / np.pi,\n                                )\n                            )\n\n                        # angle = constr[1] *np.pi/180\n                        # if angle < constr[1] and angle < 0:\n                        #     pha *= 1. - (.01 / np.log10(nstep+2)\n                        #     # print(\"decrease1\")\n                        # elif angle < constr[1] and angle > 0:\n                        #     pha *= 1. + (.1 /np.log10(nstep+2))\n                        #     # print(\"increase1\")\n                        # elif angle > constr[1] and angle > 0:\n                        #     pha *= 1. - (.1 / np.log10(nstep+2)\n                        #     # print(\"decrease2\")\n                        # elif angle > constr[1] and angle < 0:\n                        #     pha *= 1. + (.1 /np.log10(nstep+2))\n                        #     # print(\"increase2\")\n                        pha -= (0.75) * ((angle - constr[1]) * np.pi / 180)\n                        if pha < -2 * np.pi:\n                            pha += 2 * np.pi\n                        elif pha > 2 * np.pi:\n                            pha -= 2 * np.pi\n\n                nstep += 1\n\n            for constr in constraints:\n                # assume torsion...\n                # print(\"Searching torsion\", constr)\n                if len(constr[0]) == 4:\n\n                    torsions = [\n                        f for f in forces if type(f) == openmm.PeriodicTorsionForce\n                    ][0]\n                    N = torsions.getNumTorsions()\n                    found = False\n                    # print(\"Found N existing torsions:\", N)\n\n                    for idx in range(N):\n                        p1, p2, p3, p4, per, phai, ki = torsions.getTorsionParameters(\n                            idx\n                        )\n                        target = tuple(constr[0])\n                        if target[-1] < target[0]:\n                            target = tuple(target[::-1])\n                        if tuple([p1, p2, p3, p4]) == target:\n                            # print(\"Found torsion\", target, constr[1])\n                            # per = 1\n                            torsions.setTorsionParameters(\n                                idx, p1, p2, p3, p4, per, ref_pha, ref_k\n                            )\n\n            state = sim.context.getState(getEnergy=True, getPositions=getPositions)\n            energy = state.getPotentialEnergy().in_units_of(\n                simtk.unit.kilocalories_per_mole\n            )\n            # print(\"energy (remove)\", energy)\n            torsions.updateParametersInContext(sim.context)\n            state = sim.context.getState(getEnergy=True, getPositions=getPositions)\n            energy = state.getPotentialEnergy().in_units_of(\n                simtk.unit.kilocalories_per_mole\n            )\n            # print(\"energy (remove)\", energy)\n            pos = None\n            if self.minimize:\n                pos = state.getPositions(asNumpy=True) / simtk.unit.angstroms\n\n        else:\n            if self.minimize:\n                sim.minimizeEnergy()\n            state = sim.context.getState(getEnergy=True, getPositions=getPositions)\n            energy = state.getPotentialEnergy().in_units_of(\n                simtk.unit.kilocalories_per_mole\n            )\n            pos = None\n            if self.minimize:\n                pos = state.getPositions(asNumpy=True) / simtk.unit.angstroms\n        return energy, pos\n\n    def calc_mm_energy(self, top, xyz, component=None, charge=False, constraints=None):\n        forcefield = self.forcefield\n        if component is None:\n            ene, pos = self.mm_potential(\n                forcefield, top, xyz, charge=charge, constraints=constraints\n            )\n            return ene, pos\n\n        modff = copy.deepcopy(forcefield)\n\n        force = modff.get_parameter_handler(component)\n        for term in force.parameters:\n            if component == \"vdW\":\n                term.epsilon *= 0.0\n            if component in [\"Bonds\", \"Angles\"]:\n                term.k *= 0.0\n            if component in [\"ProperTorsions\", \"ImproperTorsions\"]:\n                for i, _ in enumerate(term.k):\n                    term.k[i] *= 0.0\n\n        ene, pos = self.mm_potential(\n            modff, top, xyz, charge=charge, constraints=constraints\n        )\n        return ene, pos\n\n\n#    def calc_vdw_direct(xyz, labels):\n#        \"\"\" doesn't work yet\"\"\"\n#        na = len(xyz)\n#        atoms = range(na)\n#        ene = 0.0\n#        r = distance.cdist(xyz,xyz)\n#        for i in atoms:\n#            ii = (i,)\n#            for j in atoms:\n#                if(j >= i):\n#                    break\n#                jj = (j,)\n#                eps = np.sqrt(labels[ii].epsilon * labels[jj].epsilon) / labels[jj].epsilon.unit\n#                rmin = (labels[ii].rmin_half + labels[jj].rmin_half)/2.0\n#                rmin = rmin / rmin.unit\n#                rij = r[i,j]\n#                a = rmin/rij\n#                a = a**6\n#                ene += eps * (a**2 - 2*a)\n#                #print(i,j,\"r\", rij, \"ene\", ene, \"rmin\", rmin, \"eps\", eps, \"a\", a)\n#        return ene * simtk.unit.kilocalorie_per_mole\n\n#    def apply( self, targets=None):\n#        gen_MM_charge = True\n#        try:\n#            total_ene = self.calc_mm_energy(forcefield, top, xyz, charge=gen_MM_charge)\n#        except Exception as e:\n#            log.write(str(e) + '\\n')\n#            success = False\n#            break\n# log.write(\"  Conformation energy {:4d}/{:4d}\\n\".format(qcmol_i+1,n_qcmol))\n# log.flush()\n# if(get_qm_energy):\n#    ene_str = \"{:13.8f} a.u.\".format(ene[qcmol_i])\n#    log.write(\"    QM {:18s}= {:s} \\n\".format(\"Energy\", ene_str))\n#    log.flush()\n\n# ene_name_str = \"Energy\" if gen_MM_charge else \"EnergyNoElec\"\n# log.write(\"    MM {:18s}= {:10.5f} {:s}\\n\".format(ene_name_str,\n#    (total_ene/total_ene.unit ),\n#    str(total_ene.unit)))\n# log.flush()\n\n# sim.context.setPositions(xyz * angstrom2nm)\n# state = sim.context.getState(getEnergy = True, getPositions=True)\n# sim_ene = state.getPotentialEnergy()\n# reporter.report(sim, state)\n# log.write(\"    MM {:18s}= {:9.4f} {:s}\\n\\n\".format(\"App Energy\",\n#    (sim_ene.value_in_unit(simtk.unit.kilocalorie_per_mole)),\n#    str(simtk.unit.kilocalorie_per_mole)))\n# log.flush()\n# sim.minimizeEnergy()\n# state = sim.context.getState(getEnergy = True, getPositions=True)\n# sim_min_ene = state.getPotentialEnergy()\n# reporter.report(sim, state)\n# log.write(\"    MM {:18s}= {:9.4f} {:s}\\n\\n\".format(\"App Min Energy\",\n#    (sim_min_ene.value_in_unit(simtk.unit.kilocalorie_per_mole)),\n#    str(simtk.unit.kilocalorie_per_mole)))\n\n\n# log.flush()\n#        ene_sum = total_ene\n# if('direct_vdw' not in mol_data['energy']['oFF']):\n#    mol_data['energy']['oFF']['direct_vdw'] = []\n# mol_data['energy']['oFF']['direct_vdw'].append(calc_vdw_direct(xyz, labels['vdW']))\n# print(mol_data['energy']['oFF']['direct_vdw'])\n\n#        if('epot' not in mol_data['energy']['oFF']):\n#            mol_data['energy']['oFF']['epot'] = []\n#        mol_data[\"energy\"]['oFF']['epot'].append(total_ene)\n#        for component in ['vdW' ] + valence_params:\n#            energy_sans_component = calc_mm_energy(forcefield, top, xyz, component=component, charge=gen_MM_charge)\n#            energy_component = total_ene - energy_sans_component\n#\n#            if(component not in mol_data[\"energy\"]['oFF']):\n#                mol_data[\"energy\"]['oFF'][component] = []\n#            mol_data[\"energy\"]['oFF'][component].append(energy_component)\n#            ene_sum -= energy_component\n#            log.write(\"    MM {:18s}= {:10.5f} {:s}\\n\".format(component,\n#                (energy_component/energy_component.unit ),\n#                str(energy_component.unit)))\n#            log.flush()\n#        if(gen_MM_charge):\n#            if('Electrostatics' not in mol_data['energy']['oFF']):\n#                mol_data['energy']['oFF']['Electrostatics'] = []\n#            mol_data['energy']['oFF']['Electrostatics'].append(ene_sum)\n#            log.write(\"    MM {:18s}= {:10.5f} {:s}\\n\\n\".format(\"Electrostatics\",\n#                (ene_sum/ene_sum.unit ),\n#                str(ene_sum.unit)))\n#\n#        #log.write(\"    MM {:18s}= {:10.5f} {:s}\\n\\n\".format(\"Direct vdW\",\n#        #    (mol_data['energy']['oFF']['direct_vdw'][qcmol_i] / mol_data['energy']['oFF']['direct_vdw'][qcmol_i].unit ),\n#        #    str(mol_data['energy']['oFF']['direct_vdw'][qcmol_i].unit)))\n#        log.flush()\n\n#    if(success == False):\n#        continue\n#    log.write(\"\\n  Conformation energy summary\\n\")\n#    if(len(ene) > 1):\n#        if(get_qm_energy):\n#            ene_str = \"{:13.8f} +- {:13.8f} a.u.\".format(np.mean(ene), np.std(ene))\n#            log.write(\"    QM {:18s}= {:s} \\n\".format(\"Energy\", ene_str))\n#\n#        log.write(\"    MM {:18s}= {:10.5f} +- {:10.5f} {:s}\\n\\n\".format(ene_name_str,\n#            np.mean([i/i.unit for i in mol_data[\"energy\"]['oFF']['epot']]),\n#            np.std([i/i.unit for i in mol_data[\"energy\"]['oFF']['epot']]),\n#            str(mol_data[\"energy\"]['oFF']['epot'][0].unit)))\n#        components_to_print = ['vdW' ] + valence_params\n#        if(gen_MM_charge):\n#            components_to_print += ['Electrostatics']\n#        for component in components_to_print:\n#            log.write(\"    MM {:18s}= {:10.5f} +- {:10.5f} {:s}\\n\".format(component,\n#                np.mean([i/i.unit for i in mol_data[\"energy\"]['oFF'][component]]),\n#                np.std([i/i.unit for i in mol_data[\"energy\"]['oFF'][component]]),\n#                str(mol_data[\"energy\"]['oFF'][component][0].unit)))\n", "meta": {"hexsha": "7e2fc5e8f9669c4cd8a1574a0dd03aefc801aeb0", "size": 43375, "ext": "py", "lang": "Python", "max_stars_repo_path": "offsb/op/openmm.py", "max_stars_repo_name": "MobleyLab/openff-spellbook", "max_stars_repo_head_hexsha": "66a9f2add895034da7949701069b11cf0ab3f817", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-09-20T13:53:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-25T20:42:12.000Z", "max_issues_repo_path": "offsb/op/openmm.py", "max_issues_repo_name": "MobleyLab/openff-spellbook", "max_issues_repo_head_hexsha": "66a9f2add895034da7949701069b11cf0ab3f817", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-10-12T07:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-22T10:22:17.000Z", "max_forks_repo_path": "offsb/op/openmm.py", "max_forks_repo_name": "MobleyLab/openff-spellbook", "max_forks_repo_head_hexsha": "66a9f2add895034da7949701069b11cf0ab3f817", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-12T00:31:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-30T21:36:10.000Z", "avg_line_length": 41.3095238095, "max_line_length": 141, "alphanum_fraction": 0.4905360231, "include": true, "reason": "import numpy", "num_tokens": 10037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.1734596390375432}}
{"text": "import os\nimport random\nimport sys\nimport torch\nfrom skimage.morphology import remove_small_objects,binary_opening\nimport numpy as np\n\ndef average(list):\n    s = 0\n    for item in list:\n        s += item\n    return s/len(list)\n\ndef sum(list):\n    s = 0\n    for item in list:\n        s += item\n    return s\n\ndef analysis(x,y):\n    '''\n    对输入的两个四维张量[B,1,H,W]进行逐图的DSC、PPV、Sensitivity计算\n    其中x表示网络输出的预测值\n    y表示实际的预想结果mask\n    返回为一个batch中DSC、PPV、Sen的平均值及batch大小\n    '''\n    \n    x = torch.from_numpy(x.astype(np.uint8)).cuda()\n    # y = torch.from_numpy(y.astype(np.uint8))\n    x=x.type(dtype=torch.uint8)\n    y=y.type(dtype=torch.uint8)#保证类型为uint8\n    DSC=[]\n    PPV=[]\n    Sen=[]\n    if x.shape==y.shape:\n        batch=x.shape[0]\n        for i in range(batch):#按第一个维度分开\n            \n            tmp = torch.eq(x[i],y[i])\n            \n            tp=int(torch.sum(torch.mul(x[i]==1,tmp==1))) #真阳性\n            fp=int(torch.sum(torch.mul(x[i]==1,tmp==0))) #假阳性\n            fn=int(torch.sum(torch.mul(x[i]==0,tmp==0))) #假阴性\n        \n        \n            try:\n                DSC.append(2*tp/(fp+2*tp+fn))\n            except:\n                DSC.append(0)\n            try:\n                PPV.append(tp/(tp+fp))\n            except:\n                PPV.append(0)\n            try:\n                Sen.append(tp/(tp+fn))\n            except:\n                Sen.append(0)\n            \n                \n    else:\n        sys.stderr.write('Analysis input dimension error')\n        \n\n    DSC = sum(DSC)/batch\n    PPV = sum(PPV)/batch\n    Sen = sum(Sen)/batch\n    return DSC, PPV, Sen, batch\n\n\ndef post_process(img,min_size=100):\n    '''\n    图像后处理过程\n    包括开运算和去除过小体素\n    返回uint16格式numpy二值数组\n    '''\n    img = img.cpu()\n    img = img.numpy().astype(np.bool)\n    b,c,w,h = img.shape\n    if c==1:\n        for i in range(b):\n            img_tmp = img[i,0,:,:]\n            img_tmp = binary_opening(img_tmp)\n            remove_small_objects(img_tmp, min_size=min_size, in_place=True)\n            img_tmp = ~remove_small_objects(~img_tmp, min_size=min_size)\n            img[i,0,:,:] = img_tmp\n        \n    return img.astype(np.uint16)", "meta": {"hexsha": "9d0e11654ee2dc73e05c82d00617fca2287902d8", "size": 2114, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/eval_Unet.py", "max_stars_repo_name": "abc008/MT-Brain-Network", "max_stars_repo_head_hexsha": "a823722d4d3211c955bc1370bd8399d27c6640f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/eval_Unet.py", "max_issues_repo_name": "abc008/MT-Brain-Network", "max_issues_repo_head_hexsha": "a823722d4d3211c955bc1370bd8399d27c6640f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/eval_Unet.py", "max_forks_repo_name": "abc008/MT-Brain-Network", "max_forks_repo_head_hexsha": "a823722d4d3211c955bc1370bd8399d27c6640f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2988505747, "max_line_length": 75, "alphanum_fraction": 0.5264900662, "include": true, "reason": "import numpy", "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.17331481311120098}}
{"text": "\"\"\"\nFunctions are modified on top of GFLA.\nGFLA's license: https://github.com/RenYurui/Global-Flow-Local-Attention/blob/master/LICENSE.md\n\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torchvision.models as models\nimport torch.nn.functional as F\nimport os\nimport torchvision.transforms as transforms\nimport numpy as np\n\nclass GANLoss(nn.Module):\n    \"\"\"Define different GAN objectives.\n    The GANLoss class abstracts away the need to create the target label tensor\n    that has the same size as the input.\n    \"\"\"\n\n    def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):\n        \"\"\" Initialize the GANLoss class.\n        Parameters:\n            gan_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp.\n            target_real_label (bool) - - label for a real image\n            target_fake_label (bool) - - label of a fake image\n        Note: Do not use sigmoid as the last layer of Discriminator.\n        LSGAN needs no sigmoid. vanilla GANs will handle it with BCEWithLogitsLoss.\n        \"\"\"\n        super(GANLoss, self).__init__()\n        self.register_buffer('real_label', torch.tensor(target_real_label))\n        self.register_buffer('fake_label', torch.tensor(target_fake_label))\n        self.gan_mode = gan_mode\n        if gan_mode == 'lsgan':\n            self.loss = nn.MSELoss()\n        elif gan_mode == 'vanilla':\n            self.loss = nn.BCEWithLogitsLoss()\n        elif gan_mode in ['wgangp']:\n            self.loss = None\n        else:\n            raise NotImplementedError('gan mode %s not implemented' % gan_mode)\n\n    def get_target_tensor(self, prediction, target_is_real):\n        \"\"\"Create label tensors with the same size as the input.\n        Parameters:\n            prediction (tensor) - - tpyically the prediction from a discriminator\n            target_is_real (bool) - - if the ground truth label is for real images or fake images\n        Returns:\n            A label tensor filled with ground truth label, and with the size of the input\n        \"\"\"\n\n        if target_is_real:\n            target_tensor = self.real_label\n        else:\n            target_tensor = self.fake_label\n        return target_tensor.expand_as(prediction)\n\n    def __call__(self, prediction, target_is_real):\n        \"\"\"Calculate loss given Discriminator's output and grount truth labels.\n        Parameters:\n            prediction (tensor) - - tpyically the prediction output from a discriminator\n            target_is_real (bool) - - if the ground truth label is for real images or fake images\n        Returns:\n            the calculated loss.\n        \"\"\"\n        if self.gan_mode in ['lsgan', 'vanilla']:\n            target_tensor = self.get_target_tensor(prediction, target_is_real)\n            loss = self.loss(prediction, target_tensor)\n        elif self.gan_mode == 'wgangp':\n            if target_is_real:\n                loss = -prediction.mean()\n            else:\n                loss = prediction.mean()\n        return loss\n\n\n\n\ndef cal_gradient_penalty(netD, real_data, fake_data, device, type='mixed', constant=1.0, lambda_gp=10.0):\n    \"\"\"Calculate the gradient penalty loss, used in WGAN-GP paper https://arxiv.org/abs/1704.00028\n    Arguments:\n        netD (network)              -- discriminator network\n        real_data (tensor array)    -- real images\n        fake_data (tensor array)    -- generated images from the generator\n        device (str)                -- GPU / CPU: from torch.device('cuda:{}'.format(self.gpu_ids[0])) if self.gpu_ids else torch.device('cpu')\n        type (str)                  -- if we mix real and fake data or not [real | fake | mixed].\n        constant (float)            -- the constant used in formula ( | |gradient||_2 - constant)^2\n        lambda_gp (float)           -- weight for this loss\n    Returns the gradient penalty loss\n    \"\"\"\n    if lambda_gp > 0.0:\n        if type == 'real':   # either use real images, fake images, or a linear interpolation of two.\n            interpolatesv = real_data\n        elif type == 'fake':\n            interpolatesv = fake_data\n        elif type == 'mixed':\n            alpha = torch.rand(real_data.shape[0], 1, device=device)\n            alpha = alpha.expand(real_data.shape[0], real_data.nelement() // real_data.shape[0]).contiguous().view(*real_data.shape)\n            interpolatesv = alpha * real_data + ((1 - alpha) * fake_data)\n        else:\n            raise NotImplementedError('{} not implemented'.format(type))\n        interpolatesv.requires_grad_(True)\n        disc_interpolates = netD(interpolatesv)\n        gradients = torch.autograd.grad(outputs=disc_interpolates, inputs=interpolatesv,\n                                        grad_outputs=torch.ones(disc_interpolates.size()).to(device),\n                                        create_graph=True, retain_graph=True, only_inputs=True)\n        gradients = gradients[0].view(real_data.size(0), -1)  # flat the data\n        gradient_penalty = (((gradients + 1e-16).norm(2, dim=1) - constant) ** 2).mean() * lambda_gp        # added eps\n        return gradient_penalty, gradients\n    else:\n        return 0.0, None\n\n    \n\nclass MultiAffineRegularizationLoss(nn.Module):\n    def __init__(self, kz_dic):\n        super(MultiAffineRegularizationLoss, self).__init__()\n        self.kz_dic=kz_dic\n        self.method_dic={}\n        for key in kz_dic:\n            instance = AffineRegularizationLoss(kz_dic[key])\n            self.method_dic[key] = instance\n        self.layers = sorted(kz_dic, reverse=True) \n \n    def __call__(self, flow_fields):\n        loss=0\n        for i in range(len(flow_fields)):\n            method = self.method_dic[self.layers[i]]\n            loss += method(flow_fields[i])\n        return loss\n\nclass AffineRegularizationLoss(nn.Module):\n    \"\"\"docstring for AffineRegularizationLoss\"\"\"\n    # kernel_size: kz\n    def __init__(self, kz):\n        super(AffineRegularizationLoss, self).__init__()\n        self.kz = kz\n        self.criterion = torch.nn.L1Loss()\n        from models.networks.block_extractor.block_extractor   import BlockExtractor\n        from models.networks.local_attn_reshape.local_attn_reshape   import LocalAttnReshape\n    \n        self.extractor = BlockExtractor(kernel_size=kz)\n        self.reshape = LocalAttnReshape()\n\n        temp = np.arange(kz)\n        A = np.ones([kz*kz, 3])\n        A[:, 0] = temp.repeat(kz)\n        A[:, 1] = temp.repeat(kz).reshape((kz,kz)).transpose().reshape(kz**2)\n        AH = A.transpose()\n        k = np.dot(A, np.dot(np.linalg.inv(np.dot(AH, A)), AH)) - np.identity(kz**2) #K = (A((AH A)^-1)AH - I)\n        self.kernel = np.dot(k.transpose(), k)\n        self.kernel = torch.from_numpy(self.kernel).unsqueeze(1).view(kz**2, kz, kz).unsqueeze(1)\n\n    def __call__(self, flow_fields):\n        grid = self.flow2grid(flow_fields)\n\n        grid_x = grid[:,0,:,:].unsqueeze(1)\n        grid_y = grid[:,1,:,:].unsqueeze(1)\n        weights = self.kernel.type_as(flow_fields)\n        #import pdb; pdb.set_trace()\n        loss_x = self.calculate_loss(grid_x, weights)\n        loss_y = self.calculate_loss(grid_y, weights)\n        return loss_x+loss_y\n\n\n    def calculate_loss(self, grid, weights):\n        results = nn.functional.conv2d(grid, weights)   # KH K B [b, kz*kz, w, h]\n        b, c, h, w = results.size()\n        kernels_new = self.reshape(results, self.kz)\n        f = torch.zeros(b, 2, h, w).type_as(kernels_new) + float(int(self.kz/2))\n        grid_H = self.extractor(grid, f)\n        result = torch.nn.functional.avg_pool2d(grid_H*kernels_new, self.kz, self.kz)\n        loss = torch.mean(result)*self.kz**2\n        return loss\n\n    def flow2grid(self, flow_field):\n        b,c,h,w = flow_field.size()\n        x = torch.arange(w).view(1, -1).expand(h, -1).type_as(flow_field).float() \n        y = torch.arange(h).view(-1, 1).expand(-1, w).type_as(flow_field).float()\n        grid = torch.stack([x,y], dim=0)\n        grid = grid.unsqueeze(0).expand(b, -1, -1, -1)\n        return flow_field+grid\n\nclass VGGLoss(nn.Module):\n    r\"\"\"\n    Perceptual loss, VGG-based\n    https://arxiv.org/abs/1603.08155\n    https://github.com/dxyang/StyleTransfer/blob/master/utils.py\n    \"\"\"\n\n    def __init__(self, weights=[1.0, 1.0, 1.0, 1.0, 1.0]):\n        super(VGGLoss, self).__init__()\n        self.add_module('vgg', VGG19())\n        self.criterion = torch.nn.L1Loss()\n        self.weights = weights\n\n    def compute_gram(self, x):\n        b, ch, h, w = x.size()\n        f = x.view(b, ch, w * h)\n        f_T = f.transpose(1, 2)\n        G = f.bmm(f_T) / (h * w * ch)\n        return G\n        \n    def __call__(self, x, y, last_only=False, content_only=False):\n        # Compute features\n        x_vgg, y_vgg = self.vgg(x), self.vgg(y)\n        if not last_only:\n            content_loss = 0.0\n            content_loss += self.weights[0] * self.criterion(x_vgg['relu1_1'], y_vgg['relu1_1'])\n            content_loss += self.weights[1] * self.criterion(x_vgg['relu2_1'], y_vgg['relu2_1'])\n            content_loss += self.weights[2] * self.criterion(x_vgg['relu3_1'], y_vgg['relu3_1'])\n            content_loss += self.weights[3] * self.criterion(x_vgg['relu4_1'], y_vgg['relu4_1'])\n            content_loss += self.weights[4] * self.criterion(x_vgg['relu5_1'], y_vgg['relu5_1'])\n            if content_only:\n                return content_loss\n\n            # Compute loss\n            style_loss = 0.0\n            style_loss += self.criterion(self.compute_gram(x_vgg['relu2_2']), self.compute_gram(y_vgg['relu2_2']))\n            style_loss += self.criterion(self.compute_gram(x_vgg['relu3_4']), self.compute_gram(y_vgg['relu3_4']))\n            style_loss += self.criterion(self.compute_gram(x_vgg['relu4_4']), self.compute_gram(y_vgg['relu4_4']))\n            style_loss += self.criterion(self.compute_gram(x_vgg['relu5_2']), self.compute_gram(y_vgg['relu5_2']))\n        else:\n            content_loss = self.criterion(x_vgg['relu5_1'], y_vgg['relu5_1'])\n            if content_only:\n                return content_loss\n            style_loss = self.criterion(self.compute_gram(x_vgg['relu5_2']), self.compute_gram(y_vgg['relu5_2']))\n\n        return content_loss, style_loss\n\nclass PerceptualCorrectness(nn.Module):\n    r\"\"\"\n\n    \"\"\"\n\n    def __init__(self, layer=['rel1_1','relu2_1','relu3_1','relu4_1']):\n        super(PerceptualCorrectness, self).__init__()\n        self.add_module('vgg', VGG19())\n        self.layer = layer  \n        self.eps=1e-8 \n        from models.networks.resample2d_package.resample2d import Resample2d\n        self.resample = Resample2d(4, 1, sigma=2)\n\n    def __call__(self, target, source, flow_list, used_layers, mask=None, use_bilinear_sampling=False):\n        used_layers=sorted(used_layers, reverse=True)\n        # self.target=target\n        # self.source=source\n        self.target_vgg, self.source_vgg = self.vgg(target), self.vgg(source)\n        loss = 0\n        for i in range(len(flow_list)):\n            loss += self.calculate_loss(flow_list[i], self.layer[used_layers[i]], mask, use_bilinear_sampling)\n\n\n\n        return loss\n\n    def calculate_loss(self, flow, layer, mask=None, use_bilinear_sampling=False):\n        target_vgg = self.target_vgg[layer]\n        source_vgg = self.source_vgg[layer]\n        [b, c, h, w] = target_vgg.shape\n        # maps = F.interpolate(maps, [h,w]).view(b,-1)\n        flow = F.interpolate(flow, [h,w])\n\n        target_all = target_vgg.view(b, c, -1)                      #[b C N2]\n        source_all = source_vgg.view(b, c, -1).transpose(1,2)       #[b N2 C]\n\n\n        source_norm = source_all/(source_all.norm(dim=2, keepdim=True)+self.eps)\n        target_norm = target_all/(target_all.norm(dim=1, keepdim=True)+self.eps)\n        \n        correction = torch.bmm(source_norm, target_norm) #[b N2 N2]\n        (correction_max,max_indices) = torch.max(correction, dim=1)\n\n        # interple with bilinear sampling\n        if use_bilinear_sampling:\n            input_sample = self.bilinear_warp(source_vgg, flow).view(b, c, -1)\n        else:\n            input_sample = self.resample(source_vgg, flow).view(b, c, -1)\n\n        correction_sample = F.cosine_similarity(input_sample, target_all)    #[b 1 N2]\n        loss_map = torch.exp(-correction_sample/(correction_max+self.eps))\n        if mask is None:\n            loss = torch.mean(loss_map) - torch.exp(torch.tensor(-1).type_as(loss_map))\n        else:\n            mask=F.interpolate(mask, size=(target_vgg.size(2), target_vgg.size(3)))\n            mask=mask.view(-1, target_vgg.size(2)*target_vgg.size(3))\n            loss_map = loss_map - torch.exp(torch.tensor(-1).type_as(loss_map))\n            loss = torch.sum(mask * loss_map)/(torch.sum(mask)+self.eps)\n\n        # print(correction_sample[0,2076:2082])\n        # print(correction_max[0,2076:2082])\n        # coor_x = [32,32]\n        # coor = max_indices[0,32+32*64]\n        # coor_y = [int(coor%64), int(coor/64)]\n        # source = F.interpolate(self.source, [64,64])\n        # target = F.interpolate(self.target, [64,64])\n        # source_i = source[0]\n        # target_i = target[0]\n\n        # source_i = source_i.view(3, -1)\n        # source_i[:,coor]=-1\n        # source_i[0,coor]=1\n        # source_i = source_i.view(3,64,64)\n        # target_i[:,32,32]=-1\n        # target_i[0,32,32]=1\n        # lists = str(int(torch.rand(1)*100))\n        # img_numpy = util.tensor2im(source_i.data)\n        # util.save_image(img_numpy, 'source'+lists+'.png')\n        # img_numpy = util.tensor2im(target_i.data)\n        # util.save_image(img_numpy, 'target'+lists+'.png')\n        return loss\n\n    def bilinear_warp(self, source, flow):\n        [b, c, h, w] = source.shape\n        x = torch.arange(w).view(1, -1).expand(h, -1).type_as(source).float() / (w-1)\n        y = torch.arange(h).view(-1, 1).expand(-1, w).type_as(source).float() / (h-1)\n        grid = torch.stack([x,y], dim=0)\n        grid = grid.unsqueeze(0).expand(b, -1, -1, -1)\n        grid = 2*grid - 1\n        flow = 2*flow/torch.tensor([w, h]).view(1, 2, 1, 1).expand(b, -1, h, w).type_as(flow)\n        grid = (grid+flow).permute(0, 2, 3, 1)\n        input_sample = F.grid_sample(source, grid).view(b, c, -1)\n        return input_sample\n\nclass VGG19(torch.nn.Module):\n    def __init__(self):\n        super(VGG19, self).__init__()\n        features = models.vgg19(pretrained=True).features\n        self.relu1_1 = torch.nn.Sequential()\n        self.relu1_2 = torch.nn.Sequential()\n\n        self.relu2_1 = torch.nn.Sequential()\n        self.relu2_2 = torch.nn.Sequential()\n\n        self.relu3_1 = torch.nn.Sequential()\n        self.relu3_2 = torch.nn.Sequential()\n        self.relu3_3 = torch.nn.Sequential()\n        self.relu3_4 = torch.nn.Sequential()\n\n        self.relu4_1 = torch.nn.Sequential()\n        self.relu4_2 = torch.nn.Sequential()\n        self.relu4_3 = torch.nn.Sequential()\n        self.relu4_4 = torch.nn.Sequential()\n\n        self.relu5_1 = torch.nn.Sequential()\n        self.relu5_2 = torch.nn.Sequential()\n        self.relu5_3 = torch.nn.Sequential()\n        self.relu5_4 = torch.nn.Sequential()\n\n        for x in range(2):\n            self.relu1_1.add_module(str(x), features[x])\n\n        for x in range(2, 4):\n            self.relu1_2.add_module(str(x), features[x])\n\n        for x in range(4, 7):\n            self.relu2_1.add_module(str(x), features[x])\n\n        for x in range(7, 9):\n            self.relu2_2.add_module(str(x), features[x])\n\n        for x in range(9, 12):\n            self.relu3_1.add_module(str(x), features[x])\n\n        for x in range(12, 14):\n            self.relu3_2.add_module(str(x), features[x])\n\n        for x in range(14, 16):\n            self.relu3_2.add_module(str(x), features[x])\n\n        for x in range(16, 18):\n            self.relu3_4.add_module(str(x), features[x])\n\n        for x in range(18, 21):\n            self.relu4_1.add_module(str(x), features[x])\n\n        for x in range(21, 23):\n            self.relu4_2.add_module(str(x), features[x])\n\n        for x in range(23, 25):\n            self.relu4_3.add_module(str(x), features[x])\n\n        for x in range(25, 27):\n            self.relu4_4.add_module(str(x), features[x])\n\n        for x in range(27, 30):\n            self.relu5_1.add_module(str(x), features[x])\n\n        for x in range(30, 32):\n            self.relu5_2.add_module(str(x), features[x])\n\n        for x in range(32, 34):\n            self.relu5_3.add_module(str(x), features[x])\n\n        for x in range(34, 36):\n            self.relu5_4.add_module(str(x), features[x])\n\n        # don't need the gradients, just want the features\n        for param in self.parameters():\n            param.requires_grad = False\n\n    def forward(self, x):\n        relu1_1 = self.relu1_1(x)\n        relu1_2 = self.relu1_2(relu1_1)\n\n        relu2_1 = self.relu2_1(relu1_2)\n        relu2_2 = self.relu2_2(relu2_1)\n\n        relu3_1 = self.relu3_1(relu2_2)\n        relu3_2 = self.relu3_2(relu3_1)\n        relu3_3 = self.relu3_3(relu3_2)\n        relu3_4 = self.relu3_4(relu3_3)\n\n        relu4_1 = self.relu4_1(relu3_4)\n        relu4_2 = self.relu4_2(relu4_1)\n        relu4_3 = self.relu4_3(relu4_2)\n        relu4_4 = self.relu4_4(relu4_3)\n\n        relu5_1 = self.relu5_1(relu4_4)\n        relu5_2 = self.relu5_2(relu5_1)\n        relu5_3 = self.relu5_3(relu5_2)\n        relu5_4 = self.relu5_4(relu5_3)\n\n        out = {\n            'relu1_1': relu1_1,\n            'relu1_2': relu1_2,\n\n            'relu2_1': relu2_1,\n            'relu2_2': relu2_2,\n\n            'relu3_1': relu3_1,\n            'relu3_2': relu3_2,\n            'relu3_3': relu3_3,\n            'relu3_4': relu3_4,\n\n            'relu4_1': relu4_1,\n            'relu4_2': relu4_2,\n            'relu4_3': relu4_3,\n            'relu4_4': relu4_4,\n\n            'relu5_1': relu5_1,\n            'relu5_2': relu5_2,\n            'relu5_3': relu5_3,\n            'relu5_4': relu5_4,\n        }\n        return out\n", "meta": {"hexsha": "7952cffea3bdbe7a056dbe492ad7a909cd23fe13", "size": 17818, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/external_functions.py", "max_stars_repo_name": "fyviezhao/dressing-in-order", "max_stars_repo_head_hexsha": "63790663ad0420d9d2dabed22d5c56dd40422313", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/external_functions.py", "max_issues_repo_name": "fyviezhao/dressing-in-order", "max_issues_repo_head_hexsha": "63790663ad0420d9d2dabed22d5c56dd40422313", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/external_functions.py", "max_forks_repo_name": "fyviezhao/dressing-in-order", "max_forks_repo_head_hexsha": "63790663ad0420d9d2dabed22d5c56dd40422313", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8612975391, "max_line_length": 143, "alphanum_fraction": 0.6029857448, "include": true, "reason": "import numpy", "num_tokens": 4844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.17331480965631146}}
{"text": "\"\"\"\nVersion 8.0\n***********\nThis version is object oriented and uses 5 methods via\nSEIQRDPSolver to solve the SEIQRDP model.\nIt supports multiprocessing (with experiment module or any other method\n                             by 'adding' experiments together: exp1 + exp2).\nThis version is not optimized.\n\nIn this version (8.0.alpha):\n    - The dataset is now handled properly. No more global variable LOCATIONS.\n    - Only the data for the population/region in question is loaded.\n    - Dataset is downloaded with user's permission if no data file is found.\n    - Corrected the fitness function (nRMSE as described in the paper).\n    - The fitness function has been re-written to be readable.\n    - Got rid of Comparator class. Fitness is handled in the GA class.\n    - Got rid of Simulator class. SEIQRDPSolver does the same job.\n    - *MAJOR* Dictionaries are now the data structure for the model's\n        parameters. This will allow easily integration of other models.\n    - Got rid of Configurator class and other parameter's handling functions.\n        The parameters are accessed by their names in the new dictionary\n        structure.\n    - The model's search space is no longer hardcoded in this file. It was\n        moved to the model's file.\n    - Corrected the 95% confidence interval computation. (was off by 1%)\n    - GeneticFit no longer fits at initialization. Requires a call to run().\n    - Data is loaded more properly and much faster.\n    - Renamed a lot of stuff (name conventions were not respected before)\n    - Some code refactoring. It runs significantly faster.\n\"\"\"\n__version__ = '8.0.a'\n\n# Math\nimport numpy as np\nimport scipy.stats as st\nfrom math import sqrt\nfrom random import random\nfrom random import choice as rand_choice\nfrom itertools import combinations\n# Results\nimport matplotlib.pyplot as plt\nfrom datetime import timedelta\n# Data\nimport pandas as pd\nfrom os.path import isfile, isdir\nfrom os import mkdir\n# Utils\nfrom copy import deepcopy  # Is needed to create hard copies\n# Internal\nfrom seiqrdp_model.region_data import Region\nimport seiqrdp_model.seiqrdp_solver as slv\n\n\n# ###############    DATA    ################\ndef update_data():\n    \"\"\"\n    Downloads data from\n    https://raw.githubusercontent.com/datasets/\n    \"\"\"\n    dataset = pd.read_csv('https://raw.githubusercontent.com/datasets/'\n                          'covid-19/master/data/'\n                          'time-series-19-covid-combined.csv')\n    if not isdir('Data/'):\n        mkdir('Data/')\n    dataset.to_csv(r'Data/time-series-19-covid-combined.csv',\n                   index=False)\n\n\ndef load_data(region_name, pop_size):\n    \"\"\"\n        Loading data from csv file.\n        Returns the Region object.\n    \"\"\"\n    print(\"Dataset is loading...\")\n\n    # If data is missing, prompt for data download.\n    if not isfile('Data/time-series-19-covid-combined.csv'):\n        print(\"Dataset not found.\")\n        usr_input = input('Download data from github repo? (y/any) :\\n')\n        if usr_input == 'y' or usr_input == 'Y':\n            print(\"Dataset is being updated...\")\n            update_data()\n    # Load data from file.\n    dataframe = pd.read_csv('Data/time-series-19-covid-combined.csv')\n\n    region = Region.from_dataframe(dataframe, region_name, pop_size)\n    return region\n# ###############    DATA    ################\n\n\nclass GeneticFit:\n    \"\"\"\n        This class implements an evolutionary genetic algorithm that\n        finds the best fitting SEIR parameters for a 'region' (pop + cases).\n        At each generation we keep the best 'elite_size' parameters and breed\n        them with a 'mutation_rate'.\n        We stop at 'max_gen' generations.\n        The best result (parameters) is 'self.elite'.\n        Set 'verbose' = True to see the progress.\n    \"\"\"\n\n    def __init__(self, region, elite_size, max_gen, mutation_rate=0.4,\n                 search_space=slv.search_space, method='LSODA', verbose=False):\n        self.region = region\n        self.elite_size = elite_size\n        self.max_gen = max_gen\n        self.mutation_rate = mutation_rate\n        self.search_space = search_space\n\n        # I0 and E0 first guesses.\n        self.search_space['I0'] = [region.rcQ[0], region.rcQ[0]*5]\n        self.search_space['E0'] = [region.rcQ[0], region.rcQ[0]*5]\n\n        self.method = method\n        self.verbose = verbose\n\n        (self.lembda, self.kappa) = self.compute_lambda_kappa()\n\n        self.result = []\n        self.elite = []\n\n    def run(self):\n        self.result = self.evolve()\n        self.elite = self.result[0]\n\n    def compute_lambda_kappa(self):\n        \"\"\"\n            Determine Lambda and Kappa from real data.\n            Note: 'lembda' is used instead of the Python reserved name lambda.\n        \"\"\"\n        lembda = []\n        kappa = []\n        cQ = np.array(self.region.rcQ)\n        R = np.array(self.region.rR)\n        D = np.array(self.region.rD)\n        Q = cQ - R - D\n\n        for n in range(len(Q)-1):\n            if (R[n] == 0) and (D[n] == 0):  # v007.4\n                continue\n            lembda.append((R[n+1]-R[n])/Q[n])\n            kappa.append((D[n+1]-D[n])/Q[n])\n\n        Lembda = np.mean(np.array(lembda))\n        Kappa = np.mean(np.array(kappa))\n        return (Lembda, Kappa)\n\n    def evolve(self):\n        \"\"\"\n        Evolves the initial population of parameters over a number of\n        generations to fit the epidemic model.\n\n        Returns:\n        (parameters, fitness)\n            A tuple of the best parameters set and its fitness value.\n\n        \"\"\"\n        # Computing the total population size from the elite size.\n        pop_size = self.elite_size*(self.elite_size-1)\n\n        # Computing the search space's widths (in which params can vary)\n        width = {}\n        for param in self.search_space:\n            width[param] = self.search_space[param][1]\\\n                - self.search_space[param][0]\n\n        population = []\n        elite = []\n\n        # Generating the initial population\n        for i in range(pop_size):\n            parameters = {'lambda': self.lembda, 'kappa': self.kappa}\n            for param in self.search_space:\n                parameters[param] = random()*width[param]\\\n                    + self.search_space[param][0]\n\n            # Adding the set of parameters to the population along with\n            # its fitness.\n            population.append([parameters, self.fitness(parameters)])\n\n        # Selecting the elite\n        elite = self.generate_elite(population, self.elite_size)\n\n        # Main loop: iterates up to max_gen generations.\n        for g in range(self.max_gen):\n            # Passing the elite into the next population\n            new_population = self.generate_next_population(elite, width)\n            # Generate the next elite.\n            elite = self.generate_elite(new_population, self.elite_size)\n\n            if self.verbose:\n                print(f'Generation {g+1} of {self.max_gen}.'\n                      f'Best: {elite[0][1]}\\n')\n        # Return a tuple (params, fitness) of the best elite.\n        return ([elite[0][0], elite[0][1]])\n\n    def generate_next_population(self, elite, width):\n        \"\"\"\n        Generates the next generation's population from the previous ones'\n        elite.\n\n        Parameters:\n            elite :\n                The elite parameters which survive and breed.\n            width :\n                List of widths of the search space; by how much the parameters\n                can mutate.\n\n        Returns:\n            new_population : list\n                The population of the next generation.\n        \"\"\"\n        # Passing the elite directly into the next population\n        new_population = deepcopy(elite)\n\n        # Breed and mutate, and add to the new population\n        for par1, par2 in combinations(elite, 2):\n            offspring = self.cross(par1[0], par2[0],\n                                   width, self.search_space)\n            # Add the offspring to the new population along with\n            # its fitness.\n            new_population.append([offspring, self.fitness(offspring)])\n\n        return new_population\n\n    def sort_population(self, pop):\n        \"\"\"\n            Sorts the population of the genetic pool by\n            their fitting score (2nd element in population list)\n            Note: get rid of lambda and replace it with a externally\n                    declared function (performance issue)\n        \"\"\"\n        # reverse = None (Sorts in Ascending order)\n        pop.sort(key=lambda x: x[1])\n        return pop\n\n    def cross(self, par1, par2, width, search_space):\n        \"\"\"\n            Generates an offspring by breeding 2 parents, with\n            a 'mutation_chance' = 0-1.\n        \"\"\"\n        offspring = {'lambda': self.lembda, 'kappa': self.kappa}\n        for param in search_space:\n            if random() < self.mutation_rate:\n                #   Mutation: the gene is random\n                offspring[param] = random()*width[param]+search_space[param][0]\n            else:\n                #   Breeding: the gene is from a single random parent\n                offspring[param] = rand_choice([par1[param], par2[param]])\n        return offspring\n\n    def generate_elite(self, population, elite_size):\n        \"\"\"\n            Sorts the population by their scores and\n            returns 'elite_size' best elements.\n        \"\"\"\n        # Selecting the elite\n        self.sort_population(population)\n        return population[:elite_size]\n\n    def fitness(self, genome):\n        \"\"\" Computes the fitness of a genome.\n            genome = [6 values], no kappa/lambda.\n        \"\"\"\n        simulation = slv.SEIQRDPSolver(genome, self.region, mode='fit')\n\n        simulation.solve_model(0, len(self.region.rcQ), 1, self.method)\n\n        sqr_sum = 0\n        for a, b in zip(self.region.rcQ, simulation.cQ):\n            sqr_sum += (a-b)**2\n        n_rmse = sqrt(np.mean(sqr_sum))/np.mean(self.region.rcQ)\n        return n_rmse\n\n\nclass Analyzer:\n    \"\"\"\n        This class measures BRN, peak_time, Peak values for a given 'Region'\n        and a set of SEIR parameters.\n        It gives also the data of simulation for n_sim_days period after\n        the first day.\n    \"\"\"\n\n    def __init__(self, region, parameters, n_sim_days):\n        self.region = region\n        self.parameters = parameters\n        self.n_sim_days = n_sim_days\n\n        simulation = slv.SEIQRDPSolver(parameters, region)\n        simulation.solve_model(0, self.n_sim_days)\n\n        active_cases = simulation.Q\n\n        peak_active_infections = max(simulation.Q)\n        peak_day = simulation.Q.index(peak_active_infections)\n        self.peak_is_outofrange = False\n        if peak_day == len(simulation.Q)-1:\n            self.peak_is_outofrange = True\n\n        self.peak = active_cases[peak_day-1]\n        self.peak_time = peak_day\n        self.brn = parameters['beta']/parameters['delta']\n        self.fit = simulation\n\n    def get_epidemic_startdate(self):\n        \"\"\"\n        This can be used to seek the probable first day when the\n        first exposition occured.\n        \"\"\"\n\n        solver = slv.SEIQRDPSolver(self.parameters, self.region)\n\n        step = -30\n        solver.solve_model(0, step, 1, 'LSODA')\n        E = solver.E\n\n        while E[0] > 1:\n            step += -30\n            # Simulates the previous 30 days\n            solver.solve_model(step+30, step, 1, 'LSODA')\n            E = solver.E\n        starting_point = 0\n\n        while E[starting_point] < 0:\n            starting_point += 1\n\n        starting_point += step\n        starting_date = self.region.first_day\\\n            + timedelta(days=starting_point)\n        return(starting_date)\n\n\nclass BaseExperiment:\n    \"\"\"\n        A BaseExperiment perfoms a genetic fitting + simulation\n        and computes the model variables.\n        It is suited for parallel computing since 2 instences of\n        BaseExeriment can be added together to form a 3rd one:\n            exp3 = exp1 + exp2\n        Example:\n            >> import Algeria_SEIR_COVID2019_Object as SEIR\n            >> SEIR.load_data()\n            >> ita_exp = SEIR.BaseExperiment(region=SEIR.LOCATIONS['Italy'],\n                                             n_sim_days=100, n_experiments=4)\n            >> ita_exp.run()\n            >> ita_exp.compute_results()\n            >> ita_exp.show_results('all')\n    \"\"\"\n\n    def __init__(self, region, n_sim_days, n_experiments,\n                 elite_size=10, max_gen=50, mutation_rate=0.4,\n                 search_space=slv.search_space, method='LSODA', verbose=False):\n\n        self.region = region\n        self.n_sim_days = n_sim_days\n        self.n_experiments = n_experiments\n        self.elite_size = elite_size\n        self.max_gen = max_gen\n        self.mutation_rate = mutation_rate\n        self.search_space = search_space\n        self.method = method\n        self.verbose = verbose\n\n    def init_states(self):\n\n        # typical values\n        self.typical_brn = 0\n        self.typical_experiment_index = 0\n        self.typical_parameters = {}\n        self.typical_peak = 0\n        self.typical_peak_time = 0\n        self.typical_peak_found = True\n\n        # observables mean values\n        self.brn = 0\n        self.peak = 0\n        self.peak_time = 0\n        self.peak_found = True\n\n        # observables covariances\n        self.err_brn = 0\n        self.err_peak = 0\n        self.err_peak_time = 0\n\n        # Elite parameters\n        self.elites = []\n\n        # All exps. data.\n        self.raw_brn, self.raw_Rn, self.raw_peak, self.raw_peak_time,\\\n            self.raw_S, self.raw_E, self.raw_I, self.raw_Q, self.raw_cQ,\\\n            self.raw_R, self.raw_D, self.raw_P\\\n            = [], [], [], [], [], [], [], [], [], [], [], []\n\n        # mean compartmental variables\n        self.S, self.E, self.I, self.Q, self.cQ, self.R, self.D,\\\n            self.P, self.Rn\\\n            = [], [], [], [], [], [], [], [], []\n\n        # compartmental variables covariances\n        self.err_S, self.err_E, self.err_I, self.err_Q, self.err_cQ,\\\n            self.err_R, self.err_D, self.err_P, self.err_Rn\\\n            = [], [], [], [], [], [], [], [], []\n\n        # days list of simulation\n        self.days = []\n\n    def run(self):\n        \"\"\"\n            Runs the simulations WITHOUT computing the final results.\n        \"\"\"\n        # Here we perform n_experiments of experiments\n        # (fitting + calculating observables)\n        self.init_states()\n\n        for n in range(self.n_experiments):\n            # Fit real data and obtaining the n'th elite parameter\n            if self.verbose:\n                print(\"Fitting data: \", n+1, \" out of \",\n                      self.n_experiments, ' experiments.')\n            fit = GeneticFit(self.region, self.elite_size, self.max_gen,\n                             self.mutation_rate, self.search_space,\n                             self.method, self.verbose)\n            fit.run()\n\n            # Calculate observables of n'th elite parameter\n            if self.verbose:\n                print(\"Calculating epidemic data.\")\n            observables = Analyzer(self.region, fit.elite, self.n_sim_days)\n            # Assign what you have obtained to lists\n            self.elites.append(fit.elite)\n            self.raw_brn.append(observables.brn)\n            self.raw_peak.append(observables.peak)\n            self.raw_peak_time.append(observables.peak_time)\n            self.raw_S.append(observables.fit.S)\n            self.raw_E.append(observables.fit.E)\n            self.raw_I.append(observables.fit.I)\n            self.raw_Q.append(observables.fit.Q)\n            self.raw_cQ.append(observables.fit.cQ)\n            self.raw_R.append(observables.fit.R)\n            self.raw_D.append(observables.fit.D)\n            self.raw_P.append(observables.fit.P)\n            # R(t) = brn * S/N  v007.4\n            self.raw_Rn.append([observables.brn * s/self.region.N\n                                for s in self.raw_S[n]])\n            if observables.peak_is_outofrange:\n                self.peak_found = False\n\n    def compute_results(self):\n        \"\"\"\n            Computes the final results of the simulations.\n        \"\"\"\n        # Calculate the {mean values} and {typical values}\n        # of observables from n_experiments of experiments\n        if self.verbose:\n            print(\"I am calculating expected values\")\n\n        self.brn = np.mean(np.array(self.raw_brn))\n\n        self.typical_brn = self.raw_brn[0]\n        for n in range(1, self.n_experiments):\n            if (self.raw_brn[n]-self.brn)**2 < (self.typical_brn-self.brn)**2:\n                self.typical_brn = self.raw_brn[n]\n                self.typical_experiment_index = n\n            else:\n                continue\n\n        self.typical_parameters = self.elites[self.typical_experiment_index]\n\n        self.peak = np.mean(np.array(self.raw_peak))\n        self.typical_peak = self.raw_peak[self.typical_experiment_index]\n\n        self.peak_time = np.mean(np.array(self.raw_peak_time))\n        self.typical_peak_time\\\n            = self.raw_peak_time[self.typical_experiment_index]\n\n        # Calculate the mean values of compartmental variables\n        for i in range(self.n_sim_days):\n            self.S.append(np.mean(np.array(self.raw_S)[:, i]))\n            self.E.append(np.mean(np.array(self.raw_E)[:, i]))\n            self.I.append(np.mean(np.array(self.raw_I)[:, i]))\n            self.Q.append(np.mean(np.array(self.raw_Q)[:, i]))\n            self.cQ.append(np.mean(np.array(self.raw_cQ)[:, i]))\n            self.R.append(np.mean(np.array(self.raw_R)[:, i]))\n            self.D.append(np.mean(np.array(self.raw_D)[:, i]))\n            self.P.append(np.mean(np.array(self.raw_P)[:, i]))\n            self.Rn.append(np.mean(np.array(self.raw_Rn)[:, i]))\n\n        # Calculate the error of observables\n        # Critical value for 95% confidence interval.\n        crit_value = st.t.ppf((1 + 0.95) / 2, self.n_sim_days - 1)\n        if self.verbose:\n            print(\"Calculating errors\")\n        self.err_brn = st.sem(np.array(self.raw_brn)) * crit_value\n        self.err_peak = st.sem(np.array(self.raw_peak)) * crit_value\n        self.err_peak_time = st.sem(np.array(self.raw_peak_time)) * crit_value\n\n        # Calculate the std error on comartmental variables  v007.4\n        #  * crit_value means sigma2 : 95% confidence\n        for i in range(self.n_sim_days):\n            self.days.append(i)\n            self.err_S.append(st.sem(np.array(self.raw_S)[:, i]) * crit_value)\n            self.err_E.append(st.sem(np.array(self.raw_E)[:, i]) * crit_value)\n            self.err_I.append(st.sem(np.array(self.raw_I)[:, i]) * crit_value)\n            self.err_Q.append(st.sem(np.array(self.raw_Q)[:, i]) * crit_value)\n            self.err_cQ.append(st.sem(np.array(self.raw_cQ)[:, i])*crit_value)\n            self.err_R.append(st.sem(np.array(self.raw_R)[:, i]) * crit_value)\n            self.err_D.append(st.sem(np.array(self.raw_D)[:, i]) * crit_value)\n            self.err_P.append(st.sem(np.array(self.raw_P)[:, i]) * crit_value)\n            self.err_Rn.append(st.sem(np.array(self.raw_Rn)[:, i])*crit_value)\n\n    def show_results(self, *curves):\n        \"\"\"\n            Shows the curves and prints the results of\n            n_experiments experiments.\n        \"\"\"\n        print('___________________ Plots ___________________')\n        self.show_curves(*curves)\n\n        self.show_result_values()\n        return\n\n    def show_curves(self, *curves):\n        \"\"\"\n            Shows the curves only.\n            Available curves:\n                cq: Cumulative quarantined.\n                q: active quarantined.\n                rn: Rn(t)\n            Choosing 'all' or no arguments shows all the curves.\n        \"\"\"\n        # Errors handling\n        args = ['cq', 'q', 'rn', 'all']\n        n_plots = 0\n        for arg in curves:\n            if arg not in args:\n                print(f'Warning: \\'{arg}\\' is not a valid curve.')\n            else:\n                n_plots += 1\n\n        draw_all = (len(curves) == 0) or ('all' in curves)\n        if draw_all:\n            n_plots = 3\n\n        # Plot cQ and Q with error bars\n        fig, plots = plt.subplots(nrows=n_plots, ncols=1, sharex=False,\n                                  figsize=[8, (13/3)*n_plots])\n\n        if n_plots == 1:\n            plots = (plots,)\n\n        last_plot = -1\n        if 'cq' in curves or draw_all:\n            last_plot += 1\n            cq = plots[last_plot]\n            cq.set_title('Cumulative Number of cases')\n            cq.plot(self.region.rcQ, color='red', marker=\"o\",\n                    label='Real data (fitting)')\n            cq.errorbar(self.days, self.cQ, yerr=self.err_cQ, errorevery=6,\n                        ecolor='black', label='Model')\n            cq.legend(loc=\"lower right\")\n            cq.set_xlabel(f'Days since {self.region.first_day}')\n            cq.set_ylabel('cQ(t)')\n            cq.grid(True)\n\n        if 'q' in curves or draw_all:\n            last_plot += 1\n            q = plots[last_plot]\n            q.set_title('Number of active cases')\n            q.errorbar(self.days, self.Q, yerr=self.err_Q, errorevery=6,\n                       ecolor='black')\n            q.set_xlabel(f'Days since {self.region.first_day}')\n            q.set_ylabel('Q(t)')\n            q.grid(True)\n\n        if 'rn' in curves or draw_all:\n            last_plot += 1\n            rn = plots[last_plot]\n            rn.set_title('Reproduction Number')\n            rn.errorbar(self.days, self.Rn, yerr=self.err_Rn, errorevery=6,\n                        ecolor='black', label='R(t)')\n            # Drawing Rn = 1\n            rn.plot(self.days, [1]*len(self.Rn), label='R=1', color='red',\n                    linestyle='dashed')\n            rn.legend(loc=\"upper right\")\n            rn.set_xlabel(f'Days since {self.region.first_day}')\n            rn.set_ylabel('R(t)')\n            rn.grid(True)\n\n        fig.tight_layout()\n        plt.show()\n\n    def show_result_values(self):\n        \"\"\"\n            Shows the numerical values of the experiment.\n        \"\"\"\n        # Showing mean values\n        print('_______________________ Mean Values _______________________')\n        print('BRN: ', round(self.brn, 3), \"\\u00B1\", round(self.err_brn, 3))\n\n        if self.peak_found:\n            print('peak_time: ',\n                  self.region.first_day + timedelta(round(self.peak_time)),\n                  ' (', round(self.peak_time, 2), \") \\u00B1\",\n                  round(self.err_peak_time, 2))\n            print('Peak:', int(self.peak), \"\\u00B1\", int(self.err_peak))\n        else:\n            print(\"A peak could not be found in the chosen time period.\")\n        # Totals (mean)\n        print('')\n        print(f'Total infected (t={self.n_sim_days}):',\n              int(self.cQ[-1]), \"\\u00B1\", int(self.err_cQ[-1]))\n        print(f'Total recovered (t={self.n_sim_days}):',\n              int(self.R[-1]), \"\\u00B1\", int(self.err_R[-1]))\n        print(f'Total deaths (t={self.n_sim_days}):',\n              int(self.D[-1]), \"\\u00B1\", int(self.err_D[-1]))\n\n        # Showing typical values\n        print('_______________________ Typical Values _______________________')\n\n        print('Typical values are chosen to give the closest BRN '\n              'to the mean BRN.\\n')\n\n        print('BRN: ', round(self.typical_brn, 3))\n        if self.peak_found:\n            print('peak_time: ', self.region.first_day\n                  + timedelta(round(self.typical_peak_time)),\n                  ' (', round(self.typical_peak_time, 2), ')')\n            print('Peak:', int(self.typical_peak))\n        else:\n            print(\"A peak could not be found in the chosen time period.\")\n\n        # Totals (typical)\n        print('')\n        print(f'Total infected (t={self.n_sim_days}):',\n              int(self.raw_cQ[self.typical_experiment_index][-1]))\n        print(f'Total recovered (t={self.n_sim_days}):',\n              int(self.raw_R[self.typical_experiment_index][-1]))\n        print(f'Total deaths (t={self.n_sim_days}):',\n              int(self.raw_D[self.typical_experiment_index][-1]))\n\n        print('')\n        print('Protection rate: ',\n              round(self.typical_parameters['alpha'], 3))\n        print('Transmission rate: ',\n              round(self.typical_parameters['beta'], 3))\n        print('Latent period: ',\n              round(1/self.typical_parameters['gamma'], 3))\n        print('Infectious period: ',\n              round(1/self.typical_parameters['delta'], 3))\n        print('Recovery rate: ',\n              round(self.typical_parameters['lambda'], 3))\n        print('Fatality rate: ',\n              round(self.typical_parameters['kappa'], 3))\n        print('Number of exposed people in (', self.region.first_day, ') = ',\n              round(self.typical_parameters['E0']))\n        print('Number of infectious people in (', self.region.first_day,\n              ') = ', round(self.typical_parameters['I0']))\n\n    def __add__(self, other):\n        \"\"\"\n            Defines the + operator for BaseExperiment.\n            NOTE : This is just a hack for now!\n            To Do: Make this more robust\n        \"\"\"\n        newExp = deepcopy(self)\n        newExp.elites += other.elites\n        newExp.raw_brn += other.raw_brn\n        newExp.raw_peak += other.raw_peak\n        newExp.raw_peak_time += other.raw_peak_time\n        newExp.raw_S += other.raw_S\n        newExp.raw_E += other.raw_E\n        newExp.raw_I += other.raw_I\n        newExp.raw_Q += other.raw_Q\n        newExp.raw_cQ += other.raw_cQ\n        newExp.raw_R += other.raw_R\n        newExp.raw_D += other.raw_D\n        newExp.raw_P += other.raw_P\n        newExp.raw_Rn += other.raw_Rn\n        newExp.n_experiments += other.n_experiments\n\n        # observables mean values\n        newExp.brn = 0\n        newExp.peak = 0\n        newExp.peak_time = 0\n        newExp.peak_found = newExp.peak_found and other.peak_found\n\n        # observables covariances\n        newExp.err_brn = 0\n        newExp.err_peak = 0\n        newExp.err_peak_time = 0\n\n        # mean compartmental variables\n        newExp.S, newExp.E, newExp.I, newExp.Q, newExp.cQ, newExp.R,\\\n            newExp.D, newExp.P, newExp.Rn = [], [], [], [], [], [], [], [], []\n\n        # compartmental variables covariances\n        newExp.err_S, newExp.err_E, newExp.err_I, newExp.err_Q, newExp.err_cQ,\\\n            newExp.err_R, newExp.err_D, newExp.err_P, newExp.err_Rn = [], [],\\\n            [], [], [], [], [], [], []\n\n        newExp.days = []\n\n        return newExp\n", "meta": {"hexsha": "4e6aaebd559ce6cd1da2ec15885362592bfa7d71", "size": 26431, "ext": "py", "lang": "Python", "max_stars_repo_path": "seiqrdp_model/seiqrdp_suite.py", "max_stars_repo_name": "Taha-Rouabah/COVID-19", "max_stars_repo_head_hexsha": "e83790b09830bec74fc8ee5759d624f0e4251e77", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-05-30T13:52:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T08:48:14.000Z", "max_issues_repo_path": "seiqrdp_model/seiqrdp_suite.py", "max_issues_repo_name": "Taha-Rouabah/COVID-19", "max_issues_repo_head_hexsha": "e83790b09830bec74fc8ee5759d624f0e4251e77", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-06-18T11:41:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-23T18:41:57.000Z", "max_forks_repo_path": "seiqrdp_model/seiqrdp_suite.py", "max_forks_repo_name": "Taha-Rouabah/COVID-19", "max_forks_repo_head_hexsha": "e83790b09830bec74fc8ee5759d624f0e4251e77", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-06-23T17:44:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-03T14:54:05.000Z", "avg_line_length": 37.5440340909, "max_line_length": 79, "alphanum_fraction": 0.5802277629, "include": true, "reason": "import numpy,import scipy", "num_tokens": 6163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.173314806201422}}
{"text": "#!/usr/bin/env python3.7\n\n##################################################################################################\n# This script is used for setting the velocity-dependent transfer fucntion (TF) to 1e-8 for TF   #\n# file generated by CAMB(planck_2018_transfer_out.dat) and axsionCAMB(planck_2018_axion_transfer #\n# _out.dat). Be sure to prepare the input transfer function files and specify their name!! The   #\n# output file planck_2018_transfer_out_no_vel.dat/planck_2018_axion_transfer_out.dat will be     #\n# produced accordingly(corresponding to CAMB/axionCAMB input).                                   #\n##################################################################################################\n\nimport sys\nimport numpy as np\nimport pandas as pd\n\nif len(sys.argv) != 2:\n    raise RuntimeError(\"Input Error: Please select do axion or not (T/F)!\")\n\nif sys.argv[1] == \"F\":\n    # no axion\n    df_trans = pd.read_csv('planck_2018_transfer_out.dat', delimiter='\\s+', index_col=False)\n    col = list(df_trans.columns[1:])\n    col.append(\"None\")\n    df_trans.columns = col\n    df_trans = df_trans.iloc[:,:-1]\n    df_trans['v_CDM'] = 1e-8*np.ones(df_trans['v_CDM'].shape)\n    df_trans['v_b'] = 1e-8*np.ones(df_trans['v_b'].shape)\n    df_trans['v_b-v_c'] = 1e-8*np.ones(df_trans['v_b-v_c'].shape)\n    \n    df_trans.to_csv('planck_2018_transfer_out_no_vel.dat',header=None, sep='\\t', float_format = \"%.6e\", index=None)\n####################################################################################################################\nelif sys.argv[1] == \"T\":\n    # with axion\n    df_trans_axion = pd.read_csv('planck_2018_axion_transfer_out.dat', delimiter='\\s+', index_col=False, header=None)\n    \n    # switch the CDM column with axion column\n    temp = df_trans_axion.iloc[:,1].copy()\n    df_trans_axion.iloc[:,1] = df_trans_axion.iloc[:,6].copy()\n    df_trans_axion.iloc[:,6] = temp.copy()\n    \n    # switch the CDM column with total matter column\n    temp = df_trans_axion.iloc[:,6].copy()\n    df_trans_axion.iloc[:,6] = df_trans_axion.iloc[:,-1].copy()\n    df_trans_axion.iloc[:,-1] = temp.copy()\n    \n    # subtitute the data with negative TF by its absolute value\n    df_trans_axion = abs(df_trans_axion)\n\n    # subtitute the data with negative TF by 1e-8\n#    cri = df_trans_axion<0.0\n#    print(\"Total %.2f%% of tranfer function is negative term!\"%(100*cri.sum().sum()/cri.shape[0]/cri.shape[1]))\n#    df_trans_axion[cri] = 1e-8\n    \n    for i in range(9,13):\n        df_trans_axion[i] = 1e-8*np.ones(len(df_trans_axion.iloc[:,0]))\n        \n    df_trans_axion.iloc[:,:100].to_csv('planck_2018_axion_transfer_out_no_vel.dat', \\\n                                        header=None, sep='\\t', float_format = \"%.6e\", index=None)\n    #with open('planck_2018_axion_transfer_out_no_vel.dat','w') as f:\n    #    np.savetxt(f, df_trans_axion.iloc[:,:],delimiter=' ', fmt = '%.6e')\n####################################################################################################################\nelse:\n    raise RuntimeError(\"Input Error: Please select do axion or not (T/F)!\")\n", "meta": {"hexsha": "878747d6d72d604c7cf64e23822d8edbce4b9044", "size": 3096, "ext": "py", "lang": "Python", "max_stars_repo_path": "tool/inits/GEN_UM_IC_WITH_PHASE_WITH_TRANSFER_FUNC/set_velocities_zero.py", "max_stars_repo_name": "CliffLinTw/gamer_non-uniform_AMR", "max_stars_repo_head_hexsha": "f21c3d89ce870da3a1833641576bf054b604b648", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tool/inits/GEN_UM_IC_WITH_PHASE_WITH_TRANSFER_FUNC/set_velocities_zero.py", "max_issues_repo_name": "CliffLinTw/gamer_non-uniform_AMR", "max_issues_repo_head_hexsha": "f21c3d89ce870da3a1833641576bf054b604b648", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tool/inits/GEN_UM_IC_WITH_PHASE_WITH_TRANSFER_FUNC/set_velocities_zero.py", "max_forks_repo_name": "CliffLinTw/gamer_non-uniform_AMR", "max_forks_repo_head_hexsha": "f21c3d89ce870da3a1833641576bf054b604b648", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.1428571429, "max_line_length": 117, "alphanum_fraction": 0.5726744186, "include": true, "reason": "import numpy", "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.17331480274653255}}
{"text": "from __future__ import division\nimport sys,os\n\nif sys.version_info.major>=3:\n\tfrom io import StringIO\nelse:\n\tfrom StringIO import StringIO\n\nfrom .nbody import NbodySnapshot\nfrom .. import extern as ext\nfrom .settings import LTSettings\n\nimport numpy as np\nimport astropy.units as u\nfrom astropy.cosmology import w0waCDM,LambdaCDM\n\n############################################################\n################Gadget2Settings class#######################\n############################################################\n\nclass Gadget2Settings(LTSettings):\n\n\t\"\"\"\n\tClass handler of the tunable settings in a Gadget2 run\n\n\t\"\"\"\n\n\tfile_names = [\"InitCondFile\",\"OutputDir\",\"EnergyFile\",\"InfoFile\",\"TimingsFile\",\"CpuFile\",\"RestartFile\",\"SnapshotFileBase\",\"OutputListFilename\"]\n\tcpu_timings = [\"TimeLimitCPU\",\"ResubmitOn\",\"ResubmitCommand\"]\n\tcode_options = [\"ICFormat\",\"SnapFormat\",\"ComovingIntegrationOn\",\"TypeOfTimestepCriterion\",\"OutputListOn\",\"PeriodicBoundariesOn\"]\n\tcharacteristics_of_run = [\"TimeMax\"]\n\toutput_frequency = [\"TimeBetSnapshot\",\"TimeOfFirstSnapshot\",\"CpuTimeBetRestartFile\",\"TimeBetStatistics\",\"NumFilesPerSnapshot\",\"NumFilesWrittenInParallel\"]\n\taccuracy_time_integration = [\"ErrTolIntAccuracy\",\"MaxRMSDisplacementFac\",\"CourantFac\",\"MaxSizeTimestep\",\"MinSizeTimestep\"]\n\ttree_algorithm = [\"ErrTolTheta\",\"TypeOfOpeningCriterion\",\"ErrTolForceAcc\",\"TreeDomainUpdateFrequency\"]\n\tsph = [\"DesNumNgb\",\"MaxNumNgbDeviation\",\"ArtBulkViscConst\",\"InitGasTemp\",\"MinGasTemp\"]\n\tmemory_allocation = [\"PartAllocFactor\",\"TreeAllocFactor\",\"BufferSize\"]\n\tsystem_of_units = [\"UnitLength_in_cm\",\"UnitMass_in_g\",\"UnitVelocity_in_cm_per_s\",\"GravityConstantInternal\"]\n\tsoftening = [\"MinGasHsmlFractional\",\"SofteningGas\",\"SofteningHalo\",\"SofteningDisk\",\"SofteningBulge\",\"SofteningStars\",\"SofteningBndry\",\"SofteningGasMaxPhys\",\"SofteningHaloMaxPhys\",\"SofteningDiskMaxPhys\",\"SofteningBulgeMaxPhys\",\"SofteningStarsMaxPhys\",\"SofteningBndryMaxPhys\"]\n\n\tdef __init__(self,**kwargs):\n\n\t\t#Default outputs\n\t\tself.OutputScaleFactor = np.array([0.2463687286034,0.25331915596808,0.2603792960781,0.26755062217624,0.27483471475984,0.282233268286,0.28974809827109,0.29738114881152,0.30513450055509,0.31301037915502,0.32101116424033,0.32913939894726,0.3373978000372,0.34578926866836,0.35431690185511,0.36298400467612,0.37179410329025,0.38075095882651,0.38985858222059,0.39912125007794,0.40854352165158,0.4181302570317,0.42788663665433,0.43781818224776,0.4479307793476,0.45823070152614,0.46872463649679,0.47941971427274,0.49032353757851,0.50144421473605,0.51279039527177,0.52437130852031,0.53619680553253,0.54827740463258,0.56062434101017,0.57324962078195,0.58616608000982,0.59938744922579,0.61292842408364,0.62680474283878,0.64103327145057,0.65563209720868,0.67062063190864,0.68601972574487,0.70185179325524,0.71814095284413,0.73491318163551,0.75219648767026,0.77002110176951,0.78841969174729,0.80742760208188,0.82708312265889,0.84742779079644,0.86850673147378,0.89036904153293,0.91306822464037,0.9366626850185,0.96121628943351,0.98679900871668,1.0])\n\n\t\t#File names\n\t\tself.InitCondFile = \"gadget_ic\"\n\t\tself.OutputDir = \"snapshots\"\n\t\tself.EnergyFile = \"energy.txt\"\n\t\tself.InfoFile = \"info.txt\"\n\t\tself.TimingsFile = \"timings.txt\"\n\t\tself.CpuFile = \"cpu.txt\"\n\t\tself.RestartFile = \"restart\"\n\t\tself.SnapshotFileBase = \"snapshot\"\n\t\tself.OutputListFilename = \"outputs.txt\"\n\n\t\t#CPU Timings\n\t\tself.TimeLimitCPU = 1.0*u.day\n\t\tself.ResubmitOn = 0\n\t\tself.ResubmitCommand = \"my-scriptfile\"\n\n\t\t#Code options\n\t\tself.ICFormat  = 1\n\t\tself.SnapFormat = 1\n\t\tself.ComovingIntegrationOn = 1\n\t\tself.TypeOfTimestepCriterion = 0\n\t\tself.OutputListOn = 1\n\t\tself.PeriodicBoundariesOn = 1\n\n\t\t#Caracteristics of run  \n\t\tself.TimeMax = 1.0\n\n\t\t#Output frequency\n\t\tself.TimeBetSnapshot = 0.5\n\t\tself.TimeOfFirstSnapshot = 0\n\t\tself.CpuTimeBetRestartFile = 12.5*u.hour \n\t\tself.TimeBetStatistics = 0.05\n\t\tself.NumFilesPerSnapshot = 16\n\t\tself.NumFilesWrittenInParallel = 8\n\n\t\t#Accuracy of time integration\n\t\tself.ErrTolIntAccuracy = 0.025 \n\t\tself.MaxRMSDisplacementFac = 0.2\n\t\tself.CourantFac = 0.15     \n\t\tself.MaxSizeTimestep = 0.02\n\t\tself.MinSizeTimestep = 0.0\n\n\n\t\t#Tree algorithm, force accuracy, domain update frequency\n\t\tself.ErrTolTheta = 0.45\n\t\tself.TypeOfOpeningCriterion = 1\n\t\tself.ErrTolForceAcc = 0.005\n\t\tself.TreeDomainUpdateFrequency = 0.025\n\n\t\t\n\t\t#Further parameters of SPH\n\t\tself.DesNumNgb = 33\n\t\tself.MaxNumNgbDeviation = 2\n\t\tself.ArtBulkViscConst = 0.8\n\t\tself.InitGasTemp = 1000.0    \n\t\tself.MinGasTemp = 50.0    \n\n\t\t#Memory allocation\n\t\tself.PartAllocFactor = 1.3    \n\t\tself.TreeAllocFactor = 0.7\n\t\tself.BufferSize = 20*u.Mbyte \n\n\n\t\t#System of units\n\t\tself.UnitLength_in_cm = 3.085678e21       # ;  1.0 kpc \n\t\tself.UnitMass_in_g = 1.989e43    #;  1.0e10 solar masses \n\t\tself.UnitVelocity_in_cm_per_s = 1.0e5  # ;  1 km/sec \n\t\tself.GravityConstantInternal = 0\n\n\n\t\t#Softening lengths\n\t\tself.MinGasHsmlFractional = 0.25\n\t\tself.SofteningGas = 0\n\t\tself.SofteningHalo = 9.000000\n\t\tself.SofteningDisk = 0\n\t\tself.SofteningBulge = 0\n\t\tself.SofteningStars = 0\n\t\tself.SofteningBndry = 0\n\n\t\tself.SofteningGasMaxPhys = 0\n\t\tself.SofteningHaloMaxPhys = 9.000000\n\t\tself.SofteningDiskMaxPhys = 0\n\t\tself.SofteningBulgeMaxPhys = 0\n\t\tself.SofteningStarsMaxPhys = 0\n\t\tself.SofteningBndryMaxPhys = 0\n\n\t\t#Allow for kwargs override\n\t\tfor key in kwargs.keys():\n\t\t\tsetattr(self,key,kwargs[key])\n\n\tdef sections(self):\n\n\t\treturn [ \"file_names\",\"cpu_timings\",\"code_options\",\"characteristics_of_run\",\"output_frequency\",\"accuracy_time_integration\",\"tree_algorithm\",\"sph\",\"memory_allocation\",\"system_of_units\",\"softening\" ]\n\n\tdef showSection(self,section):\n\n\t\tif section not in self.sections():\n\t\t\traise ValueError(\"Parameter file does not admit a section named {0}\".format(section))\n\n\t\tfor option in getattr(self,section):\n\t\t\tprint(\"{0} = {1}\".format(option,getattr(self,option)))\n\n\tdef show(self):\n\n\t\tfor section in self.sections():\n\t\t\tprint(section+\":\\n\")\n\t\t\tself.showSection(section)\n\t\t\tprint(\"\\n\")\t\n\n\tdef writeSection(self,section):\n\n\t\t\"\"\"\n\t\tWrites the corresponding section of the Gadget2 parameter file\n\n\t\t\"\"\"\n\n\t\toutput = StringIO()\n\n\t\t#Write preamble\n\t\toutput.write(\"% {0}\\n\\n\".format(section))\n\n\t\t#Cycle through options\n\t\tfor option in getattr(self,section):\n\n\t\t\t#Read the corresponding value\n\t\t\tvalue = getattr(self,option)\n\n\t\t\t#Convert units as necessary\n\t\t\tif type(value)==u.quantity.Quantity:\n\t\t\t\t\n\t\t\t\tif value.unit.physical_type==\"time\":\n\t\t\t\t\tvalue = value.to(u.s).value\n\t\t\t\telif value.unit.physical_type==\"speed\":\n\t\t\t\t\tvalue = value.to(u.cm/u.s).value\n\t\t\t\telif \"byte\" in value.unit.to_string():\n\t\t\t\t\tvalue = value.to(u.Mbyte).value\n\n\t\t\t#Write the line\n\t\t\toutput.write(\"{0}\t\t{1}\\n\".format(option,value))\n\n\t\t#Finish\n\t\toutput.write(\"\\n\\n\")\n\t\toutput.seek(0)\n\n\t\treturn output.read()\n\t\t\n\n\t@classmethod\n\tdef default(cls):\n\n\t\t\"\"\"\n\t\tGenerate default settings\n\t\t\"\"\"\n\n\t\treturn cls()\n\n############################################################\n################Gadget2Header class#########################\n############################################################\n\nclass Gadget2Header(dict):\n\n\t\"\"\"\n\tClass handler of a Gadget2 snapshot header\n\n\t\"\"\"\n\n\tdef __init__(self,HeaderDict=dict()):\n\n\t\tsuper(Gadget2Header,self).__init__()\n\t\tfor key in HeaderDict.keys():\n\t\t\tself[key] = HeaderDict[key]\n\n\tdef __repr__(self):\n\n\t\tkeys = self.keys()\n\t\tkeys.sort()\n\t\t\n\t\treturn \"\\n\".join([ \"{0} : {1}\".format(key,self[key]) for key in keys ]) \n\n\tdef __add__(self,rhs):\n\n\t\tassert isinstance(rhs,Gadget2Header),\"addition not defined if rhs is not a Gadget2Header!\"\n\n\t\t#Check that it makes sense to add the snapshots (cosmological parameters, box size, time and redshift must agree)\n\t\tfields_to_match = [\"Ode0\",\"Om0\",\"h\",\"w0\",\"wa\",\"box_size\",\"endianness\",\"flag_cooling\",\"flag_feedback\",\"flag_sfr\",\"num_files\"]\n\t\tfields_to_match += [\"num_particles_total\",\"num_particles_total_gas\",\"num_particles_total_side\",\"num_particles_total_with_mass\",\"redshift\",\"scale_factor\"]\n\n\t\tfor field in fields_to_match:\n\t\t\tassert self[field] == rhs[field],\"{0} fields do not match!\".format(field)\n\n\t\tassert np.all(self[\"masses\"]==rhs[\"masses\"])\n\t\tassert np.all(self[\"num_particles_total_of_type\"]==rhs[\"num_particles_total_of_type\"])\n\n\t\t#Construct the header of the merged snapshot\n\t\tmerged_header = self.copy()\n\t\tmerged_header[\"files\"] += rhs[\"files\"]\n\t\tmerged_header[\"num_particles_file\"] += rhs[\"num_particles_file\"]\n\t\tmerged_header[\"num_particles_file_gas\"] += rhs[\"num_particles_file_gas\"]\n\t\tmerged_header[\"num_particles_file_of_type\"] += rhs[\"num_particles_file_of_type\"]\n\t\tmerged_header[\"num_particles_file_with_mass\"] += rhs[\"num_particles_file_with_mass\"]\n\n\t\treturn merged_header\n\n##############################################################\n#################Gadget2Snapshot class######################\n##############################################################\n\nclass Gadget2Snapshot(NbodySnapshot):\n\n\t\"\"\"\n\tA class that handles Gadget2 snapshots, mainly I/O from the binary format and spatial information statistics.Inherits from the abstract NbodySnapshot\n\n\t\"\"\"\n\n\t###############################################################################################\n\t#########################Abstract methods implementation#######################################\n\t###############################################################################################\n\n\t@classmethod\n\tdef buildFilename(cls,root,pool,**kwargs):\n\t\t\n\t\tif pool is not None:\n\t\t\treturn root+\".{0}\".format(pool.rank)\n\t\telse:\n\t\t\treturn root\n\n\t@classmethod\n\tdef int2root(cls,name,n):\n\t\treturn name + \"_{0:03d}\".format(n)\n\n\t############################################################################################\n\n\tdef getHeader(self):\n\t\t\n\t\theader = Gadget2Header(ext._gadget2.getHeader(self.fp))\n\t\theader[\"files\"] = [self.fp.name]\n\n\t\theader[\"w0\"] = -1.0\n\t\theader[\"wa\"] = 0.0\n\t\theader[\"comoving_distance\"] = LambdaCDM(H0=header[\"h\"]*100,Om0=header[\"Om0\"],Ode0=header[\"Ode0\"]).comoving_distance(header[\"redshift\"]).to(u.kpc).value * header[\"h\"]\n\n\t\treturn header \n\n\t############################################################################################\n\n\tdef setLimits(self):\n\t\tself._first = None\n\t\tself._last = None\n\n\t############################################################################################\n\n\tdef getPositions(self,first=None,last=None,save=True):\n\n\t\t\"\"\"\n\t\tReads in the particles positions (read in of a subset is allowed): when first and last are specified, the numpy array convention is followed (i.e. getPositions(first=a,last=b)=getPositions()[a:b])\n\n\t\t:param first: first particle in the file to be read, if None 0 is assumed\n\t\t:type first: int. or None\n\n\t\t:param last: last particle in the file to be read, if None the total number of particles is assumed\n\t\t:type last: int. or None\n\n\t\t:param save: if True saves the particles positions as attribute\n\t\t:type save: bool.\n\n\t\t:returns: numpy array with the particle positions\n\n\t\t\"\"\"\n\n\t\t#The file must not be closed\n\t\tassert not self.fp.closed\n\n\t\t#Particles do not have structure\n\t\tself.weights = None\n\t\tself.virial_radius = None\n\t\tself.concentration = None\n\n\t\tnumPart = self._header[\"num_particles_file\"]\n\n\t\t#Calculate the offset from the beginning of the file: 4 bytes (endianness) + 256 bytes (header) + 8 bytes (void)\n\t\toffset = 4 + 256 + 8\n\n\t\t#If first is specified, offset the file pointer by that amount\n\t\tif first is not None:\n\t\t\t\n\t\t\tassert first>=0\n\t\t\toffset += 4 * 3 * first\n\t\t\tnumPart -= first\n\n\t\tif last is not None:\n\n\t\t\tif first is not None:\n\t\t\t\t\n\t\t\t\tassert last>=first and last<=self._header[\"num_particles_file\"]\n\t\t\t\tnumPart = last - first\n\n\t\t\telse:\n\n\t\t\t\tassert last<=self._header[\"num_particles_file\"]\n\t\t\t\tnumPart = last\n\n\n\t\t#Read in the particles positions and return the corresponding array\n\t\ttry:\n\t\t\tpositions = (ext._gadget2.getPosVel(self.fp,offset,numPart) * self.kpc_over_h).to(self.Mpc_over_h)\n\t\texcept AttributeError:\n\t\t\tpositions = ext._gadget2.getPosVel(self.fp,offset,numPart) * u.kpc\n\n\t\tif save:\n\t\t\tself.positions = positions\n\t\t\treturn self.positions\n\t\t\n\t\t#Return\n\t\treturn positions\n\n\t############################################################################################\n\n\tdef getVelocities(self,first=None,last=None,save=True):\n\n\t\t\"\"\"\n\t\tReads in the particles velocities (read in of a subset is allowed): when first and last are specified, the numpy array convention is followed (i.e. getVelocities(first=a,last=b)=getVelocities()[a:b])\n\n\t\t:param first: first particle in the file to be read, if None 0 is assumed\n\t\t:type first: int. or None\n\n\t\t:param last: last particle in the file to be read, if None the total number of particles is assumed\n\t\t:type last: int. or None\n\n\t\t:param save: if True saves the particles velocities as attrubute\n\t\t:type save: bool.\n\n\t\t:returns: numpy array with the particle velocities\n\n\t\t\"\"\"\n\n\t\tassert not self.fp.closed\n\n\t\tnumPart = self._header[\"num_particles_file\"]\n\n\t\t#Calculate the offset from the beginning of the file: 4 bytes (endianness) + 256 bytes (header) + 8 bytes (void)\n\t\toffset = 4 + 256 + 8\n\n\t\t#Skip all the particle positions\n\t\toffset += 4 * 3 * numPart\n\n\t\t#Skip other 8 void bytes\n\t\toffset += 8\n\n\t\t#If first is specified, offset the file pointer by that amount\n\t\tif first is not None:\n\t\t\t\n\t\t\tassert first>=0\n\t\t\toffset += 4 * 3 * first\n\t\t\tnumPart -= first\n\n\t\tif last is not None:\n\n\t\t\tif first is not None:\n\t\t\t\t\n\t\t\t\tassert last>=first and last<=self._header[\"num_particles_file\"]\n\t\t\t\tnumPart = last - first\n\n\t\t\telse:\n\n\t\t\t\tassert last<=self._header[\"num_particles_file\"]\n\t\t\t\tnumPart = last\n\n\n\t\t#Read in the particles positions and return the corresponding array\n\t\tvelocities = ext._gadget2.getPosVel(self.fp,offset,numPart)\n\n\t\t#Scale units\n\t\tvelocities *= self._velocity_unit\n\t\tvelocities *= u.cm / u.s\n\n\t\tif save:\n\t\t\tself.velocities = velocities\n\t\t\treturn self.velocities\n\t\t\n\t\t#Return\n\t\treturn velocities\n\n\t############################################################################################\n\n\tdef getID(self,first=None,last=None,save=True):\n\n\t\t\"\"\"\n\t\tReads in the particles IDs, 4 byte ints, (read in of a subset is allowed): when first and last are specified, the numpy array convention is followed (i.e. getID(first=a,last=b)=getID()[a:b])\n\n\t\t:param first: first particle in the file to be read, if None 0 is assumed\n\t\t:type first: int. or None\n\n\t\t:param last: last particle in the file to be read, if None the total number of particles is assumed\n\t\t:type last: int. or None\n\n\t\t:param save: if True saves the particles IDs as attribute\n\t\t:type save: bool.\n\n\t\t:returns: numpy array with the particle IDs\n\n\t\t\"\"\"\n\n\t\tassert not self.fp.closed\n\n\t\tnumPart = self._header[\"num_particles_file\"]\n\n\t\t#Calculate the offset from the beginning of the file: 4 bytes (endianness) + 256 bytes (header) + 8 bytes (void)\n\t\toffset = 4 + 256 + 8\n\n\t\t#Skip all the particle positions\n\t\toffset += 4 * 3 * numPart\n\n\t\t#Skip other 8 void bytes\n\t\toffset += 8\n\n\t\t#Skip all the particle velocities\n\t\toffset += 4 * 3 * numPart\n\n\t\t#Skip other 8 void bytes\n\t\toffset += 8\n\n\t\t#If first is specified, offset the file pointer by that amount\n\t\tif first is not None:\n\t\t\t\n\t\t\tassert first>=0\n\t\t\toffset += 4 * first\n\t\t\tnumPart -= first\n\n\t\tif last is not None:\n\n\t\t\tif first is not None:\n\t\t\t\t\n\t\t\t\tassert last>=first and last<=self._header[\"num_particles_file\"]\n\t\t\t\tnumPart = last - first\n\n\t\t\telse:\n\n\t\t\t\tassert last<=self._header[\"num_particles_file\"]\n\t\t\t\tnumPart = last\n\n\n\t\t#Read in the particles positions and return the corresponding array\n\t\tids = ext._gadget2.getID(self.fp,offset,numPart)\n\t\tif save:\n\t\t\tself.id = ids\n\t\t\treturn self.id\n\t\t\n\t\t#Return\n\t\treturn ids\n\n\t############################################################################################\n\n\tdef write(self,filename,files=1):\n\n\t\t\"\"\"\n\t\tWrites particles information (positions, velocities, etc...) to a properly formatter Gadget snapshot\n\n\t\t:param filename: name of the file to which to write the snapshot\n\t\t:type filename: str.\n\n\t\t:param files: number of files on which to split the writing of the snapshot (useful if the number of particles is large); if > 1 the extension \".n\" is appended to the filename\n\t\t:type files: int.\n\n\t\t\"\"\"\n\n\t\t#Sanity checks\n\t\tassert hasattr(self,\"positions\"),\"Positions must be specified!!\"\n\t\tassert self.positions.shape[1]==3\n\n\t\tif not hasattr(self,\"_header\"):\n\t\t\tself.setHeaderInfo()\t\n\n\t\t#Build a bare header based on the available info (need to convert units back to the Gadget ones)\n\t\t_header_bare = self._header.copy()\n\t\t_header_bare[\"box_size\"] = _header_bare[\"box_size\"].to(self.kpc_over_h).value\n\t\t_header_bare[\"masses\"] = _header_bare[\"masses\"].to(u.g).value * _header_bare[\"h\"] / self._mass_unit\n\t\t_header_bare[\"num_particles_file_of_type\"] = _header_bare[\"num_particles_file_of_type\"].astype(np.int32)\n\t\t_header_bare[\"num_particles_total_of_type\"] = _header_bare[\"num_particles_total_of_type\"].astype(np.int32)\n\t\t_header_bare[\"comoving_distance\"] = _header_bare[\"comoving_distance\"].to(self.Mpc_over_h).value * 1.0e3\n\n\n\t\t#Convert units for positions and velocities\n\t\t_positions_converted = self.positions.to(self.kpc_over_h).value.astype(np.float32)\n\n\t\tif hasattr(self,\"velocities\"):\n\t\t\tassert self.positions.shape==self.velocities.shape\n\t\t\t_velocities_converted = (self.velocities.to(u.cm/u.s).value / self._velocity_unit).astype(np.float32)\n\t\t\twriteVel = 1\n\t\telse:\n\t\t\t_velocities_converted = np.zeros((1,3),dtype=np.float32)\n\t\t\twriteVel = 0\n\n\t\t#Check if we want to split on multiple files (only DM particles supported so far for this feature)\n\t\tif files>1:\n\n\t\t\t#Number of files the snapshot is split into\n\t\t\t_header_bare[\"num_files\"] = files\n\n\t\t\t#Update the header with the file names\n\t\t\tself.header[\"files\"] = [ \"{0}.{1}\".format(filename,n) for n in range(files) ]\n\n\t\t\t#Distribute particles among files\n\t\t\tparticles_per_file = _header_bare[\"num_particles_total\"] // files\n\n\t\t\t#Write each file\n\t\t\tfor n in range(files - 1):\n\t\t\t\t\n\t\t\t\t#Update header\n\t\t\t\t_header_bare[\"num_particles_file\"] = particles_per_file\n\t\t\t\t#TODO all particles are DM, fix distribution in the future\n\t\t\t\t_header_bare[\"num_particles_file_of_type\"] = np.array([0,particles_per_file,0,0,0,0],dtype=np.int32)\n\n\t\t\t\t#Write it!\n\t\t\t\tfilename_with_extension = \"{0}.{1}\".format(filename,n)\n\t\t\t\text._gadget2.write(_header_bare,_positions_converted[n*particles_per_file:(n+1)*particles_per_file],_velocities_converted[n*particles_per_file:(n+1)*particles_per_file],n*particles_per_file+1,filename_with_extension,writeVel)\n\n\t\t\t\n\t\t\t#The last file might have a different number of particles\n\t\t\tparticles_last_file = len(_positions_converted[particles_per_file*(files-1):])\n\n\t\t\t#Update header\n\t\t\t_header_bare[\"num_particles_file\"] = particles_last_file\n\t\t\t#TODO all particles are DM, fix distribution in the future\n\t\t\t_header_bare[\"num_particles_file_of_type\"] = np.array([0,particles_last_file,0,0,0,0],dtype=np.int32)\n\n\t\t\t#Write it!\n\t\t\tfilename_with_extension = \"{0}.{1}\".format(filename,files-1)\n\t\t\text._gadget2.write(_header_bare,_positions_converted[particles_per_file*(files-1):],_velocities_converted[particles_per_file*(files-1):],(files-1)*particles_per_file+1,filename_with_extension,writeVel)\n\n\t\telse:\n\n\t\t\t#Update the num_files key only if not present already\n\t\t\tif \"num_files\" not in _header_bare.keys():\n\t\t\t\t_header_bare[\"num_files\"] = 1\n\n\t\t\t#Update the header with the file names\n\t\t\tself.header[\"files\"] = [ filename ]\n\t\t\t\n\t\t\t#Write it!!\n\t\t\text._gadget2.write(_header_bare,_positions_converted,_velocities_converted,1,filename,writeVel)\n\n\t############################################################################################\n\t###########################Extra methods####################################################\n\t############################################################################################\n\n\tdef setHeaderInfo(self,Om0=0.26,Ode0=0.74,w0=-1.0,wa=0.0,h=0.72,redshift=100.0,box_size=15.0*u.Mpc/0.72,flag_cooling=0,flag_sfr=0,flag_feedback=0,flag_stellarage=0,flag_metals=0,flag_entropy_instead_u=0,masses=np.array([0,1.03e10,0,0,0,0])*u.Msun,num_particles_file_of_type=None,npartTotalHighWord=np.zeros(6,dtype=np.uint32)):\n\n\t\t\"\"\"\n\t\tSets the header info in the snapshot to write\n\n\t\t\"\"\"\n\n\t\tif num_particles_file_of_type is None:\n\t\t\tnum_particles_file_of_type = np.array([0,1,0,0,0,0],dtype=np.int32) * self.positions.shape[0]\n\n\t\tassert num_particles_file_of_type.sum()==self.positions.shape[0],\"The total number of particles must match!!\"\n\t\tassert box_size.unit.physical_type==\"length\"\n\t\tassert masses.unit.physical_type==\"mass\"\n\n\t\t#Create the header\n\t\tself._header = Gadget2Header()\n\t\t\n\t\t#Fill in\n\t\tself._header[\"Om0\"] = Om0\n\t\tself._header[\"Ode0\"] = Ode0\n\t\tself._header[\"w0\"] = w0\n\t\tself._header[\"wa\"] = wa\n\t\tself._header[\"h\"] = h\n\t\tself._header[\"H0\"] = 100.0*h*u.km/(u.s*u.Mpc)\n\t\tself._header[\"redshift\"] = redshift\n\t\tself._header[\"scale_factor\"] = 1.0 / (1.0 + redshift)\n\t\tself._header[\"box_size\"] = box_size\n\t\tself._header[\"flag_cooling\"] = flag_cooling\n\t\tself._header[\"flag_sfr\"] = flag_sfr\n\t\tself._header[\"flag_feedback\"] = flag_feedback\n\t\tself._header[\"flag_stellarage\"] = flag_stellarage\n\t\tself._header[\"flag_metals\"] = flag_metals\n\t\tself._header[\"flag_entropy_instead_u\"] = flag_entropy_instead_u\n\t\tself._header[\"masses\"] = masses\n\t\tself._header[\"num_particles_file_of_type\"] = num_particles_file_of_type\n\t\tself._header[\"num_particles_file\"] = num_particles_file_of_type.sum()\n\t\tself._header[\"num_particles_total_of_type\"] = num_particles_file_of_type\n\t\tself._header[\"num_particles_total\"] = num_particles_file_of_type.sum()\n\t\tself._header[\"npartTotalHighWord\"] = npartTotalHighWord\n\n\t\t#Define the kpc/h and Mpc/h units for convenience\n\t\tself.kpc_over_h = u.def_unit(\"kpc/h\",u.kpc/self._header[\"h\"])\n\t\tself.Mpc_over_h = u.def_unit(\"Mpc/h\",u.Mpc/self._header[\"h\"])\n\n\t\t#Compute the comoving distance according to the model\n\t\tcosmo = w0waCDM(H0=100.0*h,Om0=Om0,Ode0=Ode0,w0=w0,wa=wa)\n\t\tself._header[\"comoving_distance\"] = cosmo.comoving_distance(redshift).to(self.Mpc_over_h)\n\n\n\tdef writeParameterFile(self,filename,settings):\n\n\t\t\"\"\"\n\t\tWrites a Gadget2 parameter file to evolve the current snapshot using Gadget2\n\n\t\t:param filename: name of the file to which to write the parameters\n\t\t:type filename: str.\n\n\t\t:param settings: tunable settings of Gadget2 (see Gadget2 manual)\n\t\t:type settings: Gadget2Settings\n\n\t\t\"\"\"\n\n\t\t#Create output directory if not existent already\n\t\toutputdir = settings.OutputDir\n\t\tif not(os.path.isdir(outputdir)):\n\t\t\tos.mkdir(outputdir)\n\n\t\t#Update the settings according to the physical units of the current snapshot\n\t\tsettings.UnitLength_in_cm = self._length_unit\n\t\tsettings.UnitMass_in_g = self._mass_unit\n\t\tsettings.UnitVelocity_in_cm_per_s = self._velocity_unit\n\n\t\t#Set the appropriate name for the initial condition file\n\t\tif \"files\" in self.header.keys():\n\t\t\tsuffix = self.header[\"files\"][0].split(\".\")[-1]\n\t\t\tsettings.InitCondFile = os.path.abspath(self.header[\"files\"][0].rstrip(\".{0}\".format(suffix)))\n\n\t\t#Write the options\n\t\twith open(filename,\"w\") as paramfile:\n\n\t\t\t#Filenames section\n\t\t\tparamfile.write(settings.writeSection(\"file_names\"))\n\t\t\t\n\t\t\t#CPU time limit section\n\t\t\tparamfile.write(settings.writeSection(\"cpu_timings\"))\n\n\t\t\t#Code options section\n\t\t\tparamfile.write(settings.writeSection(\"code_options\"))\n\n\t\t\t#Initial scale factor time\n\t\t\tparamfile.write(\"{0}\t\t\t{1}\\n\".format(\"TimeBegin\",self.header[\"scale_factor\"]))\n\n\t\t\t#Characteristics of run section\n\t\t\tparamfile.write(settings.writeSection(\"characteristics_of_run\"))\n\t\t\t\n\t\t\t#Cosmological parameters\n\t\t\tparamfile.write(\"{0}\t\t\t{1}\\n\".format(\"Omega0\",self.header[\"Om0\"]))\n\t\t\tparamfile.write(\"{0}\t\t\t{1}\\n\".format(\"OmegaLambda\",self.header[\"Ode0\"]))\n\t\t\tparamfile.write(\"{0}\t\t\t{1}\\n\".format(\"OmegaBaryon\",0.046))\n\t\t\tparamfile.write(\"{0}\t\t\t{1}\\n\".format(\"HubbleParam\",self.header[\"h\"]))\n\t\t\tparamfile.write(\"{0}\t\t\t{1}\\n\".format(\"BoxSize\",self.header[\"box_size\"].to(self.kpc_over_h).value))\n\t\t\tparamfile.write(\"{0}\t\t\t{1}\\n\".format(\"w0\",self.header[\"w0\"]))\n\t\t\tparamfile.write(\"{0}\t\t\t{1}\\n\\n\".format(\"wa\",self.header[\"wa\"]))\n\n\t\t\t#Output frequency section\n\t\t\tparamfile.write(settings.writeSection(\"output_frequency\"))\n\n\t\t\t#Accuracy of time integration section\n\t\t\tparamfile.write(settings.writeSection(\"accuracy_time_integration\"))\n\n\t\t\t#Tree algorithm section\n\t\t\tparamfile.write(settings.writeSection(\"tree_algorithm\"))\n\n\t\t\t#SPH section\n\t\t\tparamfile.write(settings.writeSection(\"sph\"))\n\n\t\t\t#Memory allocation section\n\t\t\tparamfile.write(settings.writeSection(\"memory_allocation\"))\n\n\t\t\t#System of units section\n\t\t\tparamfile.write(settings.writeSection(\"system_of_units\"))\n\n\t\t\t#Softening lengths section\n\t\t\tparamfile.write(settings.writeSection(\"softening\"))\n\n\n##############################################################\n#################Gadget2SnapshotDE class######################\n##############################################################\n\nclass Gadget2SnapshotDE(Gadget2Snapshot):\n\n\t\"\"\"\n\tA class that handles Gadget2 snapshots, mainly I/O from the binary format and spatial information statistics.Inherits from Gadget2Snapshot; assumes that the header includes Dark Energy information\n\n\t\"\"\"\n\n\tdef getHeader(self):\n\t\theader = Gadget2Header(ext._gadget2.getHeader(self.fp))\n\t\theader[\"files\"] = [self.fp.name]\n\n\t\treturn header\n\n##############################################################\n#################Gadget2SnapshotNu class######################\n##############################################################\n\nclass Gadget2SnapshotNu(Gadget2Snapshot):\n\n\t\"\"\"\n\tA class that handles Gadget2 snapshots with neutrino effects\n\n\t\"\"\"\n\n\tdef getHeader(self):\n\t\t\n\t\theader = Gadget2Header(ext._gadget2.getHeader(self.fp))\n\t\theader[\"files\"] = [self.fp.name]\n\n\t\tdel header[\"comoving_distance\"]\n\t\theader[\"w0\"] = -1.\n\t\theader[\"wa\"] = 0.\n\n\t\treturn header\n\n##################################################################\n#################Gadget2SnapshotPipe class########################\n##################################################################\n\nclass Gadget2SnapshotPipe(Gadget2SnapshotDE):\n\n\t\"\"\"\n\tRead in the particle positions when calling the constructor, without calling fseek\n\n\t\"\"\"\n\n\tdef __init__(self,*args,**kwargs):\n\n\t\t#Call parent constructor\n\t\tsuper(Gadget2SnapshotPipe,self).__init__(*args,**kwargs)\n\n\t\t#Read in the positions \n\t\tnpart = self.header[\"num_particles_file\"]\n\t\tself.fp.read(8)\n\t\t\n\t\ttry:\n\t\t\tself.positions = (np.fromstring(self.fp.read(4*3*npart),dtype=np.float32).reshape(npart,3) * self.kpc_over_h).to(self.Mpc_over_h)\n\t\texcept AttributeError:\n\t\t\tpass\n\n\t\t#Read the rest\n\t\tself.fp.read()\n\n\t\t#Particles do not have structure\n\t\tself.weights = None\n\t\tself.virial_radius = None\n\t\tself.concentration = None\n\n\n", "meta": {"hexsha": "87be625fc8c775a1e4ba52d78f508a65bfa49847", "size": 26414, "ext": "py", "lang": "Python", "max_stars_repo_path": "lenstools/simulations/gadget2.py", "max_stars_repo_name": "asabyr/LensTools", "max_stars_repo_head_hexsha": "e155d6d39361e550906cec00dbbc57686a4bca5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-27T02:03:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T02:03:11.000Z", "max_issues_repo_path": "lenstools/simulations/gadget2.py", "max_issues_repo_name": "asabyr/LensTools", "max_issues_repo_head_hexsha": "e155d6d39361e550906cec00dbbc57686a4bca5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lenstools/simulations/gadget2.py", "max_forks_repo_name": "asabyr/LensTools", "max_forks_repo_head_hexsha": "e155d6d39361e550906cec00dbbc57686a4bca5c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.435443038, "max_line_length": 1037, "alphanum_fraction": 0.6770651927, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 7163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.30404168127272885, "lm_q1q2_score": 0.1732589626558309}}
{"text": "\"\"\"The main container for waveform objects with mode weights\"\"\"\n\nimport re\nimport numpy as np\nimport quaternionic\nimport spherical\nfrom .. import TimeSeries\nfrom . import WaveformMixin\nfrom .mode_utilities import _expectation_value_LL, _expectation_value_Ldt\n\nNRAR_mode_regex = re.compile(r\"\"\"Y_l(?P<L>[0-9]+)_m(?P<M>[-+0-9]+)\\.dat\"\"\")\n\n\nclass WaveformModes(WaveformMixin, TimeSeries):\n    \"\"\"Array-like object representing time-series data of SWSH modes\n\n    We generally assume that the data represent mode weights in expansions of\n    functions in terms of spin-weighted spherical harmonics (where the standard\n    spherical harmonics just happen to have spin weight 0).\n\n    This object is based on the TimeSeries object, but has many additional methods\n    for manipulating modes.\n\n    Parameters\n    ----------\n    input_array : (..., N, ..., M, ...) array_like\n        Input data representing the dependent variable, in any form that can be\n        converted to a numpy array.  This includes scalars, lists, lists of tuples,\n        tuples, tuples of tuples, tuples of lists, and numpy ndarrays.  It can have\n        an arbitrary number of dimensions, but the length `N` along `time_axis`\n        must match the length of `time`, and the length `M` along `modes_axis` (see\n        below) must be consistent with `ell_min` and `ell_max`.  Values must be\n        finite.\n    time : (N,) array_like\n        1-D array containing values of the independent variable.  Values must be\n        real, finite, and in strictly increasing order.\n    time_axis : int, optional\n        Axis along which `input_array` is assumed to be varying in time, meaning\n        that for `time[i]` the corresponding values are `np.take(input_array, i,\n        axis=time_axis)`.  If this is not given, the first axis of `input_array`\n        that has the same length as `time` is chosen as the time axis — which may\n        be prone to errors.\n    modes_axis : int\n        Axis of the array along which the modes are stored.  See Notes below.\n    ell_min : int\n        Smallest value of ℓ stored in the data\n    ell_max : int\n        Largest value of ℓ stored in the data\n\n    Notes\n    -----\n    We assume that the modes at a given time, say, are stored in a flat array, in\n    order of increasing `m` and `ell`, with `m` varying most rapidly — something\n    like the following:\n\n        [f(ell, m) for ell in range(ell_min, ell_max+1) for m in range(-ell,ell+1)]\n\n    The total size is implicitly `ell_max * (ell_max + 2) - ell_min ** 2 + 1`.\n\n    For backwards compatibility, it is possible to retrieve individual modes in the\n    same way as the old NRAR-format HDF5 files would be read, as in\n\n        h_22 = waveform[\"Y_l2_m2.dat\"]\n\n    Note that \"History.txt\" may not contain anything but an empty string, because\n    history is not retained in more recent data formats.  Also note that — while\n    not strictly a part of this class — the loaders that open waveform files will\n    return a dict-like object when the extrapolation order is not specified.  That\n    object can also be accessed in a backwards-compatible way much like the root\n    directory of the NRAR-format HDF5 files.  For example:\n\n        with sxs.loadcontext(\"rhOverM_Asymptotic_GeometricUnits_CoM.h5\") as f:\n            h_22 = f[\"Extrapolated_N2.dir/Y_l2_m2.dat\"]\n\n    This code is identical to the equivalent code using `h5py` except that the call\n    to `h5py.File` is replaced with the call to `sxs.loadcontext`.  The `.dat`\n    datasets are reconstructed on the fly, but should be bitwise-identical to the\n    output from the HDF5 file whenever the underlying format is NRAR.\n\n    \"\"\"\n    import functools\n\n    def __new__(cls, input_array, *args, **kwargs):\n        for requirement in [\"modes_axis\", \"ell_min\", \"ell_max\"]:\n            if requirement not in kwargs and requirement not in getattr(input_array, \"_metadata\", {}):\n                raise ValueError(f\"{cls} could not find required argument '{requirement}'\")\n        self = super().__new__(cls, input_array, *args, **kwargs)\n        return self\n\n    def __getitem__(self, key):\n        if isinstance(key, str):\n            if key == \"History.txt\":\n                return self._metadata.get(\"history\", \"\")\n            # Assume we're asking for Y_l2_m2.dat or something\n            if self.ndarray.shape != (self.n_times, self.n_modes):\n                raise ValueError(f\"Data has shape {self.ndarray.shape}, which is incompatible with NRAR format\")\n            match = NRAR_mode_regex.match(key)\n            if not match:\n                raise ValueError(f\"Key '{key}' did not match mode format\")\n            ell, m = int(match[\"L\"]), int(match[\"M\"])\n            if ell < self.ell_min or ell > self.ell_max:\n                raise ValueError(f\"Key '{key}' requested ell={ell} value not found in this data\")\n            if abs(m) > ell:\n                raise ValueError(f\"Key '{key}' requested (ell, m)=({ell}, {m}) value does not make sense\")\n            index = self.index(ell, m)\n            data = np.take(self.ndarray, index, axis=self.modes_axis).view(float).reshape((-1, 2))\n            return np.hstack((self.time[:, np.newaxis], data))\n        obj, time_key = self._slice(key)\n        if time_key is None:\n            raise ValueError(f\"Fancy indexing (with {key}) is not supported\")\n        obj = obj.view(type(self))\n        if \"frame\" in obj._metadata and obj.frame.shape == (self.n_times, 4):\n            obj._metadata[\"frame\"] = obj.frame[time_key, :]\n        return obj\n\n    @property\n    def modes_axis(self):\n        \"\"\"Axis of the array storing the various modes\n\n        See the documentation of this class for an explanation of what this means.\n\n        See Also\n        --------\n        time_axis : Axis of the array along which time varies\n\n        \"\"\"\n        return self._metadata[\"modes_axis\"]\n\n    @property\n    def ell_min(self):\n        \"\"\"Smallest value of ℓ stored in the data\"\"\"\n        return self._metadata[\"ell_min\"]\n\n    @property\n    def ell_max(self):\n        \"\"\"Largest value of ℓ stored in the data\"\"\"\n        return self._metadata[\"ell_max\"]\n\n    @property\n    def n_modes(self):\n        \"\"\"Total number of mode weights stored in the data\"\"\"\n        return self.shape[self.modes_axis]\n\n    @property\n    def LM(self):\n        \"\"\"Array of (ell, m) values in the data\n\n        This array is just a flat array of `[ell, m]` pairs.  It is automatically\n        recomputed each time `ell_min` or `ell_max` is changed.  Specifically, it is\n\n            np.array([\n                [ell, m]\n                for ell in range(self.ell_min, self.ell_max+1)\n                for m in range(-ell, ell+1)\n            ])\n\n        \"\"\"\n        return np.array([[ell, m] for ell in range(self.ell_min, self.ell_max+1) for m in range(-ell, ell+1)])\n\n    def index(self, ell, m):\n        \"\"\"Mode index of given (ell,m) mode in the data\n\n        Parameters\n        ----------\n        ell : int\n        m : int\n\n        Returns\n        -------\n        idx : int\n            Index such that self.LM[idx] == [ell, m]\n\n        \"\"\"\n        return spherical.Yindex(ell, m, self.ell_min)\n\n    @property\n    def abs(self):\n        \"\"\"Absolute value of the data\n\n        Returns\n        -------\n        absolute : TimeSeries\n            Because the absolute values make no sense as mode weights, this is just a\n            plain TimeSeries object.\n\n        See Also\n        --------\n        arg\n\n        \"\"\"\n        return np.abs(self.view(TimeSeries))\n\n    @property\n    def arg(self):\n        \"\"\"Complex phase angle of the data\n\n        Note that the result is not \"unwrapped\", meaning that there may be\n        discontinuities as the phase approaches ±π.\n\n        Returns\n        -------\n        phase : TimeSeries\n            Values are in the interval (-π, π].\n\n        See Also\n        --------\n        numpy.angle\n        arg_unwrapped\n\n        \"\"\"\n        return np.angle(self.view(TimeSeries))\n\n    @property\n    def arg_unwrapped(self):\n        \"\"\"Complex phase angle of the data, unwrapped along the time axis\n\n        The result is \"unwrapped\", meaning that discontinuities as the phase approaches\n        ±π are removed by adding an appropriate amount to all following data points.\n\n        Returns\n        -------\n        phase : TimeSeries\n            Values at the initial time are in the interval (-π, π], but may evolve to\n            arbitrary real values.\n\n        See Also\n        --------\n        numpy.angle\n        numpy.unwrap\n        arg\n\n        \"\"\"\n        return TimeSeries(np.unwrap(self.arg, axis=self.time_axis), self.time)\n\n    @property\n    def norm(self):\n        \"\"\"Compute the L² norm of the waveform\n\n        Returns\n        -------\n        n : TimeSeries\n\n        See Also\n        --------\n        numpy.linalg.norm\n        numpy.take\n        norm2 : squared version of this\n\n        Notes\n        -----\n        The integral of the (squared) magnitude of the data equals the sum of the\n        (squared) magnitude of the modes for orthonormal basis functions, meaning that\n        the L² norm of the function equals the basic Euclidean norm of the modes.  We\n        assume that these modes are expanded in a band-limited but otherwise complete\n        orthonormal basis.\n\n        \"\"\"\n        return TimeSeries(np.linalg.norm(self, axis=self.modes_axis), self.time)\n\n    @property\n    def bar(self):\n        \"\"\"Return waveform modes of function representing conjugate of this function\n\n        N.B.: This property is different from the `.conjugate` method; see below.\n\n        See Also\n        --------\n        re : Return modes of function representing the real part of this function\n        im : Return modes of function representing the imaginary part of this function\n\n        Notes\n        -----\n        This property is different from the `.conjugate` (or `.conj`) method, in that\n        `.conjugate` returns the conjugate of the mode weights of the function, whereas\n        this property returns the mode weights of the conjugate of the function.  That\n        is, `.conjugate` treats the data as a generic numpy array, and simply returns\n        the complex conjugate of the raw data without considering what the data\n        actually represents.  This property treats the data as a function represented\n        by its mode weights.\n\n        The resulting function has the negative spin weight of the input function.\n\n        We have\n\n            conjugate(f){s, l, m} = (-1)**(s+m) * conjugate(f{-s, l, -m})\n\n        \"\"\"\n        return spherical.modes.algebra.bar(self)\n\n    @property\n    def re(self):\n        \"\"\"Return waveform modes of function representing real part of this function\n\n        N.B.: This property is different from the `.real` method; see below.\n\n        See Also\n        --------\n        im : Equivalent method for the imaginary part\n        bar : Return modes of function representing the conjugate of this function\n\n        Notes\n        -----\n        This property is different from the `.real` method, in that `.real` returns the\n        real part of the mode weights of the function, whereas this property returns\n        the mode weights of the real part of the function.  That is, `.real` treats the\n        data as a generic numpy array, and simply returns the real part of the raw data\n        without considering what the data actually represents.  This property treats\n        the data as a function represented by its mode weights.\n\n        Note that this only makes sense for functions of spin weight zero; taking the\n        real part of functions with nonzero spin weight will depend too sensitively on\n        the orientation of the coordinate system to make sense.  Therefore, this\n        property raises a ValueError for other spins.\n\n        The condition that a function `f` be real is that its modes satisfy\n\n            f{l, m} = conjugate(f){l, m} = (-1)**(m) * conjugate(f{l, -m})\n\n        [Note that conjugate(f){l, m} != conjugate(f{l, m}).]  As usual, we enforce\n        that condition by essentially averaging the two modes:\n\n            f{l, m} = (f{l, m} + (-1)**m * conjugate(f{l, -m})) / 2\n\n        \"\"\"\n        return spherical.modes.algebra._real_func(self, False)\n\n    @property\n    def im(self):\n        \"\"\"Return waveform modes of function representing imaginary part of this function\n\n        N.B.: This property is different from the `.imag` method; see below.\n\n        See Also\n        --------\n        re : Equivalent method for the real part\n        bar : Return modes of function representing the conjugate of this function\n\n        Notes\n        -----\n        This property is different from the `.imag` method, in that `.imag` returns the\n        imaginary part of the mode weights of the function, whereas this property\n        returns the mode weights of the imaginary part of the function.  That is,\n        `.imag` treats the data as a generic numpy array, and simply returns the\n        imaginary part of the raw data without considering what the data actually\n        represents.  This property treats the data as a function represented by its\n        mode weights.\n\n        Note that this only makes sense for functions of spin weight zero; taking the\n        imaginary part of functions with nonzero spin weight will depend too\n        sensitively on the orientation of the coordinate system to make sense.\n        Therefore, this property raises a ValueError for other spins.\n\n        The condition that a function `f` be imaginary is that its modes satisfy\n\n            f{l, m} = -conjugate(f){l, m} = (-1)**(m+1) * conjugate(f{l, -m})\n\n        [Note that conjugate(f){l, m} != conjugate(f{l, m}).]  As usual, we enforce\n        that condition by essentially averaging the two modes:\n\n            f{l, m} = (f{l, m} + (-1)**(m+1) * conjugate(f{l, -m})) / 2\n\n        \"\"\"\n        return spherical.modes.algebra._imag_func(self, False)\n\n    from spherical.modes.derivatives import (\n        Lsquared, Lz, Lplus, Lminus,\n        Rsquared, Rz, Rplus, Rminus,\n        eth, ethbar\n    )\n\n    @property\n    def eth_GHP(self):\n        \"\"\"Spin-raising derivative operator defined by Geroch-Held-Penrose\n\n        The operator ð is defined in https://dx.doi.org/10.1063/1.1666410\n\n        See Also\n        --------\n        eth : Related operator in the Newman-Penrose convention\n        ethbar : Similar operator in the Newman-Penrose convention\n        ethbar_GHP : Conjugate of this operator\n\n        Notes\n        -----\n        We assume that the Ricci rotation coefficients satisfy β=β'=0, meaning that\n        this operator equals the Newman-Penrose operator ð multiplied by 1/√2.\n\n        \"\"\"\n        return self.eth / np.sqrt(2)\n\n    @property\n    def ethbar_GHP(self):\n        \"\"\"Spin-lowering derivative operator defined by Geroch-Held-Penrose\n\n        The operator ð̄ is defined in https://dx.doi.org/10.1063/1.1666410\n\n        See Also\n        --------\n        eth : Related operator in the Newman-Penrose convention\n        ethbar : Similar operator in the Newman-Penrose convention\n        eth_GHP : Conjugate of this operator\n\n        Notes\n        -----\n        We assume that the Ricci rotation coefficients satisfy β=β'=0, meaning that\n        this operator equals the Newman-Penrose operator ð̄ multiplied by 1/√2.\n\n        \"\"\"\n        return self.ethbar / np.sqrt(2)\n\n    def max_norm_index(self, skip_fraction_of_data=4):\n        \"\"\"Index of time step with largest norm\n\n        The optional argument skips a fraction of the data.  The default is 4, which\n        means that it skips the first 1/4 of the data, and only searches the last 3/4\n        of the data for the max.  This must be strictly greater than 1, or the entire\n        data is searched for the maximum of the norm.\n\n        \"\"\"\n        if skip_fraction_of_data <= 1:\n            return np.argmax(self.norm)\n        else:\n            i = int(self.n_times // skip_fraction_of_data)\n            return np.argmax(self[i:].norm) + i\n\n    def max_norm_time(self, skip_fraction_of_data=4):\n        \"\"\"Return time at which largest norm occurs in data\n\n        See `help(max_norm_index)` for explanation of the optional argument.\n\n        \"\"\"\n        return self.t[self.max_norm_index(skip_fraction_of_data=skip_fraction_of_data)]\n\n    def interpolate(self, new_time, derivative_order=0, out=None):\n        \"\"\"Interpolate this object to a new set of times\n\n        Note that if this object has \"frame\" data and the derivative order is nonzero,\n        it is not entirely clear what is desired.  In those cases, the frame is just\n        interpolated to the new times, but no derivative or antiderivative is taken.\n\n        Parameters\n        ----------\n        new_time : array_like\n            Points to evaluate the interpolant at\n        derivative_order : int, optional\n            Order of derivative to evaluate.  If negative, the antiderivative is\n            returned.  Default value of 0 returns the interpolated data without\n            derivatives or antiderivatives.  Must be between -3 and 3, inclusive.\n\n        See Also\n        --------\n        scipy.interpolate.CubicSpline :\n            The function that this function is based on.\n        antiderivative :\n            Calls this funtion with `new_time=self.time` and\n            `derivative_order=-antiderivative_order` (defaulting to a single\n            antiderivative).\n        derivative :\n            Calls this function `new_time=self.time` and\n            `derivative_order=derivative_order` (defaulting to a single derivative).\n        dot :\n            Property calling `self.derivative(1)`.\n        ddot :\n            Property calling `self.derivative(2)`.\n        int :\n            Property calling `self.antiderivative(1)`.\n        iint :\n            Property calling `self.antiderivative(2)`.\n\n        \"\"\"\n        result = TimeSeries.interpolate(self, new_time, derivative_order=derivative_order, out=out)\n        if self.frame.shape == (self.n_times, 4) and not np.array_equal(self.time, result.time):\n            self._metadata[\"frame\"] = quaternionic.squad(self.frame, self.time, result.time)\n        return result\n\n    def truncate(self, tol=1e-10):\n        \"\"\"Truncate the precision of this object's data in place\n\n        This function sets bits in the data to 0 when they have lower significance than\n        will alter the norm of the Waveform by a fraction `tol` at that instant in\n        time.\n\n        \"\"\"\n        if tol != 0.0:\n            tol_per_mode = tol / np.sqrt(self.n_modes)\n            abs_tolerance = np.linalg.norm(self.ndarray, axis=self.modes_axis, keepdims=True) * tol_per_mode\n            super().truncate(abs_tolerance)\n\n    def convert_to_conjugate_pairs(self):\n        \"\"\"Convert modes to conjugate-pair format in place\n\n        This function alters this object's modes to store the sum and difference of\n        pairs with opposite `m` values.  If we denote the modes `f[l, m]`, then we\n        define\n\n            s[l, m] = (f[l, m] + f̄[l, -m]) / √2\n            d[l, m] = (f[l, m] - f̄[l, -m]) / √2\n\n        For m<0 we replace the mode data with `d[l, -m]`, for m=0 we do nothing, and\n        for m>0 we replace the mode data with `s[l, m]`.  That is, the mode data on\n        output look like this:\n\n            [d[2, 2], d[2, 1], f[2, 0], s[2, 1], s[2, 2], d[3, 3], d[3, 2], ...]\n\n        The factor of √2 is chosen so that the norm (sum of the magnitudes squared) at\n        each time for this data is the same as it is for the original data.\n\n        \"\"\"\n        mode_plus = np.empty_like(self.ndarray[..., 0])\n        mode_minus = np.empty_like(mode_plus)\n        for ell in range(self.ell_min, self.ell_max + 1):\n            for m in range(1, ell + 1):\n                i_plus = self.index(ell, m)\n                i_minus = self.index(ell, -m)\n                mode_plus[:] = self.ndarray[..., i_plus]\n                mode_minus[:] = self.ndarray[..., i_minus]\n                self.ndarray[..., i_plus] = (mode_plus + np.conjugate(mode_minus)) / np.sqrt(2)\n                self.ndarray[..., i_minus] = (mode_plus - np.conjugate(mode_minus)) / np.sqrt(2)\n\n    def convert_from_conjugate_pairs(self):\n        \"\"\"Convert modes from conjugate-pair format in place\n\n        This function reverses the effects of `convert_to_conjugate_pairs`.  See that\n        function's docstring for details.\n\n        \"\"\"\n        mode_plus = np.empty_like(self.ndarray[..., 0])\n        mode_minus = np.empty_like(mode_plus)\n        for ell in range(self.ell_min, self.ell_max + 1):\n            for m in range(1, ell + 1):\n                i_plus = self.index(ell, m)\n                i_minus = self.index(ell, -m)\n                mode_plus[:] = self.ndarray[..., i_plus]\n                mode_minus[:] = self.ndarray[..., i_minus]\n                self.ndarray[..., i_plus] = (mode_plus + mode_minus) / np.sqrt(2)\n                self.ndarray[..., i_minus] = np.conjugate(mode_plus - mode_minus) / np.sqrt(2)\n\n    def evaluate(self, *directions):\n        \"\"\"Evaluate waveform in a particular direction or set of directions\n\n        Parameters\n        ----------\n        directions : array_like\n            Directions of the observer relative to the source may be specified using\n            the usual spherical coordinates, and an optional polarization angle (see\n            Notes below).  These can be expressed as 2 or 3 floats (where the third is\n            the polarization angle), or as an array with final dimension of size 2 or\n            3.  Alternatively, the input may be a `quaternionic.array` (see Notes and\n            arxiv.org/abs/1604.08140).  Input arrays can have multiple leading\n            dimensions; the final dimension is always considered to hold the\n            directions, and the other dimensions are retained in the output.\n\n        Returns\n        -------\n        signal : array_like\n            Note that this is complex-valued, meaning that it represents both\n            polarizations.  To get the signal measured by a single detector, just take\n            the real part.\n\n        Notes\n        -----\n        To evaluate mode weights and obtain values, we need to evaluate spin-weighted\n        spherical harmonics (SWSHs).  Though usually treated as functions of just the\n        angles (θ, ϕ), a mathematically correct treatment (arxiv.org/abs/1604.08140)\n        defines SWSHs as functions of the rotation needed to rotate the basis (x̂, ŷ, ẑ)\n        onto the usual spherical-coordinate basis (θ̂, ϕ̂, n̂).  This function can take\n        quaternionic arrays representing such a rotation directly, or the (θ, ϕ)\n        coordinates themselves, and optionally the polarization angle ψ, which are\n        automatically converted to quaternionic arrays.\n\n        We define the spherical coordinates (θ, ϕ) such that θ is the polar angle\n        (angle between the z axis and the point) and ϕ is the azimuthal angle (angle\n        between x axis and orthogonal projection of the point into the x-y plane).\n        This gives rise to the standard unit tangent vectors (θ̂, ϕ̂).\n\n        We also define the polarization angle ψ as the angle through which we must\n        rotate the vector θ̂ in a positive sense about n̂ to line up with the vector\n        defining the legs of the detector.  If not given, this angle is treated as 0.\n\n        Examples\n        --------\n        We can evaluate the signal in a single direction:\n\n        >>> θ, ϕ, ψ = 0.1, 0.2, 0.3\n        >>> w.evaluate(θ, ϕ)  # Default polarization angle\n        >>> w.evaluate(θ, ϕ, ψ)  # Specified polarization angle\n\n        Or we can evaluate in a set of directions:\n\n        >>> w.evaluate([[θ, ϕ], [θ+0.4, ϕ], [θ+0.8, ϕ]])\n\n        We can also evaluate on a more extensive set of directions.  Here, we construct\n        an equi-angular grid to evaluate the waveform on (though irregular grids are\n        also acceptable as long as you can pack them into a numpy array).\n\n        >>> n_theta = n_phi = 2 * w.ell_max + 1\n        >>> equiangular = np.array([\n            [\n                [theta, phi]\n                for phi in np.linspace(0.0, 2*np.pi, num=n_phi, endpoint=False)\n            ]\n            for theta in np.linspace(0.0, np.pi, num=n_theta, endpoint=True)\n        ])\n        >>> w.evaluate(equiangular)\n\n        \"\"\"\n        if len(directions) == 1:\n            directions = directions[0]\n        if isinstance(directions, quaternionic.array):\n            R = directions\n        else:\n            directions = np.asarray(directions, dtype=float)\n            if directions.shape[-1] == 2:\n                R = quaternionic.array.from_spherical_coordinates(directions)\n            elif directions.shape[-1] == 3:\n                R = quaternionic.array.from_euler_angles(directions[..., 1], directions[..., 0], directions[..., 2])\n            else:\n                raise ValueError(\n                    f\"Input `directions` array must be quaternionic, or \"\n                    f\"final dimension of must have size 2 or 3, not {directions.shape[-1]}\"\n                )\n\n        # Compute the shape of the output\n        modes_axis = self.modes_axis\n        out_shape = (\n            self.shape[:modes_axis]\n            + R.shape[:-1]\n            + tuple() if (modes_axis % self.ndim) == (-1 % self.ndim) else self.shape[modes_axis+1:]\n        )\n\n        # For now, we'll keep the new dimensions flat\n        Rflat = R.ndarray.reshape(-1, 4)\n        signal_shape = list(self.shape)\n        signal_shape[modes_axis] = Rflat.shape[0]\n        signal = np.zeros(tuple(signal_shape), dtype=complex)\n\n        # Now, loop through, evaluating for each input R value\n        wigner = spherical.Wigner(self.ell_max, ell_min=self.ell_min, mp_max=abs(self.spin_weight))\n        sYlm = np.empty(wigner.Ysize, dtype=complex)\n        slices = [slice(None) for _ in range(signal.ndim)]\n        if np.array_equal(self.frame, np.atleast_2d(quaternionic.one)):  # frame is time-independent\n            for i_R in range(Rflat.shape[0]):\n                slices[modes_axis] = i_R\n                wigner.sYlm(self.spin_weight, Rflat[i_R], out=sYlm)\n                signal[tuple(slices)] = np.dot(self.ndarray, sYlm)\n        else:  # Need to account for time-dependent frame\n            data_slices = [slice(None) for _ in range(self.ndarray.ndim)]\n            time_axis = self.time_axis\n            for i_t in range(self.n_times):\n                slices[time_axis] = i_t\n                data_slices[time_axis] = i_t\n                R_t = self.frame[i_t].inverse * Rflat\n                for i_R, R_i in enumerate(Rflat):\n                    slices[modes_axis] = i_R\n                    wigner.sYlm(self.spin_weight, R_i, out=sYlm)\n                    signal[tuple(slices)] = np.dot(self.ndarray[tuple(data_slices)], sYlm)\n\n        return TimeSeries(signal.reshape(out_shape), self.time)\n\n    # TODO:\n    # expectation_value_L\n    # # Don't bother with inner_product_LL, as it doesn't appear to be used; maybe a more general version?\n    # inner_product\n    # mode_frame : Minimally rotating O'Shaughnessy et al. frame\n    # to_mode_frame\n    # corotating_frame\n\n    @property\n    def expectation_value_LL(self):\n        \"\"\"Compute the matrix expectation value ⟨w|LᵃLᵇ|w⟩\n\n        Here, Lᵃ is the usual angular-momentum operator familiar from quantum physics,\n        and\n\n            ⟨w|LᵃLᵇ|w⟩ = ℜ{Σₗₘₙ w̄ˡᵐ ⟨l,m|LᵃLᵇ|l,n⟩ wˡⁿ}\n\n        This quantity is important for computing the angular velocity of a waveform.\n\n        See Also\n        --------\n        expectation_value_Ldt\n        angular_velocity\n\n        \"\"\"\n        mode_weights = np.moveaxis(self.ndarray, self.modes_axis, -1)\n        output_shape = mode_weights.shape[:-1] + (3, 3)\n        mode_weights = mode_weights.reshape(-1, mode_weights.shape[-1])\n        LL = np.zeros((mode_weights.shape[0], 3, 3), dtype=float)\n        _expectation_value_LL(mode_weights, self.LM, LL)\n        return LL.reshape(output_shape)\n\n    @property\n    def expectation_value_Ldt(self):\n        \"\"\"Compute the matrix expectation value ⟨w|Lᵃ∂ₜ|w⟩\n\n        Here, Lᵃ is the usual angular-momentum operator familiar from quantum physics,\n        ∂ₜ is the partial derivative with respect to time, and\n\n            ⟨w|Lᵃ∂ₜ|w⟩ = ℑ{Σₗₘₙ w̄ˡᵐ ⟨l,m|Lᵃ|l,n⟩ ∂ₜwˡⁿ}\n\n        This quantity is important for computing the angular velocity of a waveform.\n\n        See Also\n        --------\n        expectation_value_LL\n        angular_velocity\n\n        \"\"\"\n        mode_weights = np.moveaxis(self.ndarray, self.modes_axis, -1)\n        output_shape = mode_weights.shape[:-1] + (3,)\n        mode_weights = mode_weights.reshape(-1, mode_weights.shape[-1])\n        mode_weights_dot = np.moveaxis(self.dot.ndarray, self.modes_axis, -1)\n        mode_weights_dot = mode_weights_dot.reshape(-1, mode_weights_dot.shape[-1])\n        Ldt = np.zeros((mode_weights.shape[0], 3), dtype=float)\n        _expectation_value_Ldt(mode_weights, mode_weights_dot, self.LM, Ldt)\n        return Ldt.reshape(output_shape)\n\n    @property\n    def angular_velocity(self):\n        \"\"\"Angular velocity of waveform\n\n        This function calculates the angular velocity of a WaveformModes object from\n        its modes — essentially, the angular velocity of the rotating frame in which\n        the time dependence of the modes is minimized.  This was introduced in Sec. II\n        of \"Angular velocity of gravitational radiation and the corotating frame\"\n        <http://arxiv.org/abs/1302.2919>.\n\n        It can be calculated in terms of the expectation values ⟨w|Lᵃ∂ₜ|w⟩ and\n        ⟨w|LᵃLᵇ|w⟩ according to the relation\n\n            ⟨w|LᵇLᵃ|w⟩ ωₐ = -⟨w|Lᵇ∂ₜ|w⟩\n\n        For each set of modes (e.g., at each instant of time), this is a simple linear\n        equation in 3 dimensions to be solved for ω.\n\n        See Also\n        --------\n        expectation_value_LL\n        expectation_value_Ldt\n\n        \"\"\"\n        # Calculate the <L∂ₜ> vector and <LL> matrix at each instant\n        ldt = self.expectation_value_Ldt\n        ll = self.expectation_value_LL\n\n        # Solve ⟨w|LᵇLᵃ|w⟩ ωₐ = -⟨w|Lᵇ∂ₜ|w⟩ for ω\n        ω = -np.linalg.solve(ll, ldt)\n\n        return ω\n\n    def boost(self, v⃗, ell_max):\n        \"\"\"Find modes of waveform boosted by velocity v⃗\n\n        Implements Equation (21) of arxiv.org/abs/1509.00862\n\n        Parameters\n        ----------\n        v⃗ : array_like\n            Three-vector representing the velocity of the boosted frame relative to the\n            inertial frame, in units where the speed of light is 1\n        ell_max : int\n            Maximum value of `ell` to use while computing the transformation, and to\n            provide in the returned object.  See Notes, below.\n\n        Returns\n        -------\n        wprime : WaveformModes\n            Modes of waveform measured in boosted frame or of modes from boosted source\n            measured in original frame.  This should have the same properties as the\n            input waveform, except with (1) different time data [see Notes, below], (2)\n            a minimum `ell` value of 0 even for spin weight other than 0, and (3) a\n            maximum `ell` value of `ell_max`.\n\n        Notes\n        -----\n        Due to the nature of the transformation, some of the information in the input\n        waveform must be discarded, because it corresponds to slices of the output\n        waveform that are not completely represented in the input.  Thus, the times of\n        the output waveform will not just be the Lorentz-transformed times of the input\n        waveform.\n\n        Depending on the magnitude β=|v⃗|, a very large value of `ell_max` may be\n        needed.  The dominant factor is the translation that builds up over time:\n        `β*T`, where `T` is the largest time found in the waveform.  For example, if\n        β*T ≈ 1000M, we might need `ell_max=64` to maintain a comparable accuracy as in\n        the input data.\n\n        Because of the `β*T` effects, it is usually best to set t=0 at the merger time\n        — best approximated as `self.max_norm_time()`.  The largest translation is then\n        found early in the waveform, when the waveform is changing slowly.\n\n        \"\"\"\n        from .transformations import boost\n        return boost(self, v⃗, ell_max)\n\n    def rotate(self, quat):\n        \"\"\"Rotate decomposition basis of modes represented by this waveform\n\n        This returns a new waveform object, with missing \"frame\" data.\n\n        Parameters\n        ----------\n        quat : quaternionic.array\n            This must have one quaternion or the same number of quaternions as the\n            number of times in the waveform.\n\n        \"\"\"\n        from spherical.wigner import _rotate\n\n        R = quaternionic.array(quat)\n        wigner = spherical.Wigner(self.ell_max, ell_min=self.ell_min)  #, mp_max=abs(self.spin_weight))\n        D = np.zeros(wigner.Dsize, dtype=complex)\n        mode_weights = self.ndarray\n        rotated_mode_weights = np.zeros_like(mode_weights)\n        mode_weights = np.moveaxis(mode_weights, self.modes_axis, -1)\n        rotated_mode_weights = np.moveaxis(rotated_mode_weights, self.modes_axis, -1)\n        shape = rotated_mode_weights.shape\n        if quat.shape == (4,) or quat.shape == (1, 4):\n            wigner.D(R, out=D)\n            mode_weights = mode_weights.reshape(-1, mode_weights.shape[-1])\n            rotated_mode_weights = rotated_mode_weights.reshape(-1, mode_weights.shape[-1])\n            _rotate(\n                mode_weights, rotated_mode_weights,\n                wigner.ell_min, wigner.ell_max, wigner.mp_max,\n                self.ell_min, self.ell_max, self.spin_weight,\n                D\n            )\n        elif quat.shape == (self.n_times, 4):\n            slices = [slice(None) for _ in range(self.ndim)]\n            time_axis = self.time_axis if self.time_axis < self.modes_axis else self.time_axis - 1\n            for i_t in range(self.n_times):\n                wigner.D(R[i_t], out=D)\n                slices[time_axis] = i_t\n                s = tuple(slices)\n                m = mode_weights[s]\n                r = rotated_mode_weights[s]\n                m = m.reshape(-1, m.shape[-1])\n                r = r.reshape(-1, r.shape[-1])\n                _rotate(\n                    m, r,\n                    wigner.ell_min, wigner.ell_max, wigner.mp_max,\n                    self.ell_min, self.ell_max, self.spin_weight,\n                    D\n                )\n        else:\n            raise ValueError(\n                f\"Quaternionic array shape {R.shape} not understood; expected {(4,)}, {(1, 4)}, or {(self.n_times, 4)}\"\n            )\n        rotated_mode_weights = rotated_mode_weights.reshape(shape)\n        rotated_mode_weights = np.moveaxis(rotated_mode_weights, -1, self.modes_axis)\n        new_metadata = self._metadata.copy()\n        new_metadata.pop(\"frame\", None)\n        return type(self)(rotated_mode_weights, **new_metadata)\n\n    def to_inertial_frame(self):\n        \"\"\"Return a copy of this waveform in the inertial frame\"\"\"\n        if \"frame\" not in self._metadata:\n            raise ValueError(\"This waveform has no frame information\")\n        if self.frame.shape[0] == 1:\n            raise ValueError(\"This waveform appears to already be in an inertial frame\")\n        if self.frame.shape != (self.n_times, 4):\n            raise ValueError(f\"Frame shape {frame.shape} not understood; expected {(self.n_times, 4)}\")\n        w = self.rotate(~self.frame)\n        w._metadata[\"frame_type\"] = \"inertial\"\n        return w\n\n    def to_corotating_frame(\n        self, R0=None, tolerance=1e-12, z_alignment_region=None, return_omega=False, truncate_log_frame=False\n    ):\n        \"\"\"Return a copy of this waveform in the corotating frame\n\n        The corotating frame is defined to be a rotating frame for which the (L² norm\n        of the) time-dependence of the modes expressed in that frame is minimized.\n        This leaves the frame determined only up to an overall rotation.  In this \n\n        Parameters\n        ----------\n        R0 : quaternionic, optional\n            Initial value of frame when integrating angular velocity.  Defaults to the\n            identity.\n        tolerance : float, optional\n            Absolute tolerance used in integration of angular velocity\n        z_alignment_region : {None, 2-tuple of floats}, optional\n            If not None, the dominant eigenvector of the <LL> matrix is aligned with\n            the z axis, averaging over this portion of the data.  The first and second\n            elements of the input are considered fractions of the inspiral at which to\n            begin and end the average.  For example, (0.1, 0.9) would lead to starting\n            10% of the time from the first time step to the max norm time, and ending\n            at 90% of that time.\n        return_omega : bool, optional\n            If True, return a 2-tuple consisting of the waveform in the corotating\n            frame (the usual returned object) and the angular-velocity data.  That is\n            frequently also needed, so this is just a more efficient way of getting the\n            data.\n        truncate_log_frame : bool, optional\n            If True, set bits of log(frame) with lower significance than `tolerance` to\n            zero, and use exp(truncated(log(frame))) to rotate the waveform.  Also\n            returns `log_frame` along with the waveform (and optionally `omega`)\n\n        \"\"\"\n        raise NotImplementedError()\n        frame, omega = corotating_frame(\n            self, R0=R0, tolerance=tolerance, z_alignment_region=z_alignment_region, return_omega=True\n        )\n        if truncate_log_frame:\n            log_frame = np.log(frame).ndarray\n            power_of_2 = 2 ** int(-np.floor(np.log2(2 * tolerance)))\n            log_frame = np.round(log_frame * power_of_2) / power_of_2\n            frame = np.exp(quaternionic.array(log_frame))\n        w = self.rotate_decomposition_basis(frame)\n        w._metadata[\"frame_type\"] = \"corotating\"\n        w._metadata[\"frame\"] = frame\n        if return_omega:\n            if truncate_log_frame:\n                return (w, omega, log_frame)\n            else:\n                return (w, omega)\n        else:\n            if truncate_log_frame:\n                return (w, log_frame)\n            else:\n                return w\n", "meta": {"hexsha": "54bda109fadfe741ba0978ede774e8ff40b774da", "size": 38212, "ext": "py", "lang": "Python", "max_stars_repo_path": "sxs/waveforms/waveform_modes.py", "max_stars_repo_name": "dongzesun/sxs", "max_stars_repo_head_hexsha": "74ac9576032ddc232ff48510ba20f0a9e7116861", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-12-08T20:56:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T09:01:39.000Z", "max_issues_repo_path": "sxs/waveforms/waveform_modes.py", "max_issues_repo_name": "duetosymmetry/sxs", "max_issues_repo_head_hexsha": "1617bf9d1eb06b1aa063db2b310d4e7c3d02e5e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33, "max_issues_repo_issues_event_min_datetime": "2019-12-06T17:40:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T16:53:02.000Z", "max_forks_repo_path": "sxs/waveforms/waveform_modes.py", "max_forks_repo_name": "duetosymmetry/sxs", "max_forks_repo_head_hexsha": "1617bf9d1eb06b1aa063db2b310d4e7c3d02e5e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2019-12-04T17:37:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T07:22:43.000Z", "avg_line_length": 41.3997833153, "max_line_length": 119, "alphanum_fraction": 0.6195959384, "include": true, "reason": "import numpy", "num_tokens": 9078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3040416812727289, "lm_q1q2_score": 0.17325895821368265}}
{"text": "\"\"\"\nRadiate.py\n\nAuthor: Jordan Mirocha\nAffiliation: University of Colorado at Boulder\nCreated on 2010-10-18.\n\nDescription: Just keeping this routine around to look at the finite c \nimplementation - need to transfer it to RadiationField class\n     \n\"\"\"\n\nimport copy, math\nimport numpy as np\n\n#try:\n#    from mpi4py import MPI\n#    rank = MPI.COMM_WORLD.rank\n#    size = MPI.COMM_WORLD.size\n#except ImportError:\n#    print \"Module mpi4py not found.  No worries, we'll just run in serial.\"\nrank = 0\nsize = 1\n\nE_th = [13.6, 24.6, 54.4]\n\nneglible_tau = 1e-12\nneglible_column = 10\n\nclass Radiate:\n    def __init__(self, grid, source, **kwargs):\n        self.pf = parse_kwargs(**kwargs)\n        self.grid = grid\n        self.src = source\n        \n        # Classes\n        #self.cosm = Cosmology(pf)\n        #self.control = ControlSimulation(pf)\n        self.coeff = RateCoefficients(pf, rs, g)\n        #self.Ts = SpinTemperature(pf)\n        #self.HI = Hydrogen(pf)\n                \n        # Grid/units/etc\n        self.GridDimensions = int(pf[\"GridDimensions\"])\n        self.grid = np.arange(self.GridDimensions)\n        self.StopTime = pf['StopTime'] * self.pf['TimeUnits']\n        self.StartCell = pf['StartRadius'] * self.GridDimensions\n        self.R0 = pf['StartRadius'] * pf['LengthUnits']\n                \n        # Deal with log-grid, compute dx\n        #if pf['LogarithmicGrid']:\n        #    self.r = np.logspace(np.log10(self.R0), \\\n        #        np.log10(pf['LengthUnits']), self.GridDimensions + 1)\n        #else:\n        #    self.r = np.linspace(self.R0, pf['LengthUnits'], self.GridDimensions + 1)\n        \n        #self.dx = np.diff(self.r)   \n        #self.r = self.r[0:-1] \n        #self.CellCrossingTime = self.dx / c\n                \n        # For convenience \n        self.zeros_tmp = np.zeros(4)\n        \n    def EvolvePhotonsAtInfiniteSpeed(self, newdata, t, dt, h):\n        \"\"\"\n        Solver for InfiniteSpeedOfLight = 1.\n        \"\"\"        \n                \n        # Could change with time for accreting black holes (or not yet implemented sources)\n        Lbol = []\n        for rs in self.rs.all_sources:\n            Lbol.append(rs.BolometricLuminosity(t))\n                                                \n        # Loop over cells radially, solve rate equations, update values in data -> newdata\n        for cell in self.grid:   \n                        \n            # If this cell belongs to another processor, continue\n            if self.pf['ParallelizationMethod'] == 1 and size > 1:\n                if cell not in self.solve_arr: \n                    continue\n                    \n            # Update progressbar        \n            if rank == 0 and self.ProgressBar: \n                self.pbar.update(cell * size)\n                                                            \n            # Read in densities for this cell\n            n_e = self.data[\"ElectronDensity\"][cell]\n            n_HI = self.data[\"HIDensity\"][cell]\n            n_HII = self.data[\"HIIDensity\"][cell]\n            n_HeI = self.data[\"HeIDensity\"][cell]\n            n_HeII = self.data[\"HeIIDensity\"][cell]\n            n_HeIII = self.data[\"HeIIIDensity\"][cell]\n                    \n            # Read in ionized fractions for this cell\n            x_HI = self.x_HI_arr[cell]\n            x_HII = self.x_HII_arr[cell]\n            x_HeI = self.x_HeI_arr[cell]\n            x_HeII = self.x_HeII_arr[cell]\n            x_HeIII = self.x_HeIII_arr[cell]\n                                    \n            # Convenience arrays for column, absorber, and ion densities plus a few others\n            ncol = self.ncol_all[cell]   # actually log10(ncol)\n            nabs = self.nabs_all[cell]\n            nion = self.nion_all[cell]\n            n_H = n_HI + n_HII\n            n_He = n_HeI + n_HeII + n_HeIII                \n            n_B = n_H + n_He + n_e\n                                                                                            \n            # Read in temperature and internal energy for this cell\n            T = self.data[\"Temperature\"][cell]\n                                                                                          \n            # Read radius\n            r = self.r[cell]\n                            \n            # Retrieve indices used for 3D interpolation\n            indices = self.indices_all[cell]\n            \n            # Retrieve optical depth to this cell\n            tau = self.tau_all[cell]\n                            \n            # Retrieve path length through this cell\n            dx = self.dx[cell]     \n                                                                         \n            # Retrieve coefficients and what not.\n            args = [nabs, nion, n_H, n_He, n_e]\n            args.extend(self.coeff.ConstructArgs(args, indices, Lbol, r, ncol, T, dx, t, self.z, cell))\n            \n            # Unpack so we have everything by name\n            nabs, nion, n_H, n_He, n_e, Gamma, gamma, Beta, alpha, \\\n                k_H, zeta, eta, psi, xi, omega, hubble, compton, Jc, Ji = args     \n                \n            # Sum ionization + heating over all sources (last axis)            \n            args[5] = np.sum(Gamma, axis = -1) \n            args[6] = np.sum(gamma, axis = -1)      \n            args[9] = np.sum(k_H, axis = -1)\n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \n            ######################################\n            ######## Solve Rate Equations ########\n            ###################################### \n                                                                                                                                    \n            self.solver.set_initial_value(self.q_all[cell], t).set_f_params(args).set_jac_params(args)\n            self.solver.integrate(t + dt)\n            newxHII, newxHeII, newxHeIII, newE = self.solver.y \n            newxHII, newxHeII, newxHeIII, newE = self.ConserveParticleNumber(newxHII, newxHeII, newxHeIII, newE) \n                                            \n            # Convert from internal energy back to temperature\n            if self.pf['Isothermal']:\n                newT = T\n            else:\n                newT = newE * 2. / 3. / k_B / n_B                                \n                                            \n            if self.pf['CosmologicalExpansion']:\n                n_H = self.cosm.nH0 * (1. + (self.z - self.dz))**3\n                n_He = self.cosm.nHe0 * (1. + (self.z - self.dz))**3  \n                n_e = newxHII * n_H + newxHeII * n_He + 2.0 * newxHeIII * n_He\n                n_B = n_H + n_He + n_e\n                 \n            # Calculate neutral fractions\n            newHI = n_H * (1. - newxHII)\n            newHII = n_H * newxHII\n            newHeI = n_He * (1. - newxHeII - newxHeIII)\n            newHeII = n_He * newxHeII\n            newHeIII = n_He * newxHeIII\n            \n            # Derive Ts, dTb\n            delta = 0\n            Ts = self.Ts.Ts(self.z, n_H, n_e, newT, newxHII, np.sum(Jc), np.sum(Ji))\n            dTb = self.HI.BrightnessTemperature(self.z, newxHII, delta, Ts)\n                                                                        \n            # Store data\n            newdata = self.StoreData(newdata, cell, newHI, newHII, newHeI, newHeII, newHeIII, newT,\n                tau, Gamma, k_H, Beta, alpha, zeta, eta, psi, gamma, xi, omega, hubble, compton, \n                Jc, Ji, Ts, dTb)\n                                                                                                            \n            ######################################\n            ################ DONE ################\n            ######################################\n                \n            # Adjust timestep based on maximum allowed neutral fraction change     \n            if self.AdaptiveGlobalStep:\n                dtphot[cell] = self.control.ComputePhotonTimestep(tau, \n                    [newHI, newHeI, newHeII], [newHII, newHeII, newHeIII], \n                    ncol, n_H, n_He, n_e, n_B, Gamma, gamma, Beta, alpha, k_H, \n                    zeta, eta, psi, xi, omega, hubble, compton, newT, self.z, dt) \n        \n        return newdata, dtphot\n        \n    def EvolvePhotonsAtFiniteSpeed(self, newdata, t, dt, h):\n        \"\"\"\n        Solver for InfiniteSpeedOfLight = 0.\n        \n        PhotonPackage guide: \n            pack = [EmissionTime, EmissionTimeInterval, ncolHI, ncolHeI, ncolHeII, Energy]\n        \"\"\" \n        \n        # Set up timestep array for use on next cycle\n        if self.AdaptiveGlobalStep:\n            dtphot = 1.e50 * np.ones_like(self.grid)\n        else:\n            dtphot = dt\n            \n        Lbol = self.rs.BolometricLuminosity(t)    \n            \n        # Photon packages going from oldest to youngest - will have to create it on first timestep\n        if t == 0: \n            packs = []\n        else: \n            packs = list(self.data['PhotonPackages']) \n        \n        # Add one for this timestep\n        packs.append(np.array([t, dt, neglible_column, neglible_column, neglible_column, Lbol * dt]))\n            \n        # Loop over photon packages, updating values in cells: data -> newdata\n        for j, pack in enumerate(packs):\n            t_birth = pack[0]\n            r_pack = (t - t_birth) * c        # Position of package before evolving photons\n            r_max = r_pack + dt * c           # Furthest this package will get this timestep\n                                                                             \n            # Cells we need to know about - not necessarily integer\n            cell_pack = (r_pack - self.R0) * self.GridDimensions / self.pf['LengthUnits']\n            cell_pack_max = (r_max - self.R0) * self.GridDimensions / self.pf['LengthUnits'] - 1\n            cell_t = t  \n                      \n            Lbol = pack[-1] / pack[1]          \n                                            \n            # Advance this photon package as far as it will go on this global timestep  \n            while cell_pack < cell_pack_max:\n                                                        \n                # What cell are we in\n                if cell_pack < 0:\n                    cell = -1\n                else:    \n                    cell = int(cell_pack)\n                \n                if cell >= self.GridDimensions: \n                    break\n                \n                # Compute dc (like dx but in fractional cell units)\n                # Really how far this photon can go in this step\n                if cell_pack % 1 == 0: \n                    dc = min(cell_pack_max - cell_pack, 1)\n                else: \n                    dc = min(math.ceil(cell_pack) - cell_pack, cell_pack_max - cell_pack)        \n                                                                                          \n                # We really need to evolve this cell until the next photon package arrives, which\n                # is probably longer than a cell crossing time unless the global dt is vv small.\n                if (len(packs) > 1) and ((j + 1) < len(packs)): \n                    subdt = min(dt, packs[j + 1][0] - pack[0])\n                else: \n                    subdt = dt\n                   \n                # If photons haven't hit first cell interface yet, evolve in time                \n                if cell < 0:\n                    cell_pack += dc\n                    cell_t += subdt\n                    continue        \n                    \n                # Current radius in code units                                                                                                                                                                                                                                                                                                                          \n                r = cell_pack * self.pf['LengthUnits'] / self.pf['GridDimensions']\n                \n                # These quantities will be different (in general) for each step\n                # of the while loop\n                n_e = newdata[\"ElectronDensity\"][cell]\n                n_HI = newdata[\"HIDensity\"][cell]\n                n_HII = newdata[\"HIIDensity\"][cell]\n                n_HeI = newdata[\"HeIDensity\"][cell]\n                n_HeII = newdata[\"HeIIDensity\"][cell]\n                n_HeIII = newdata[\"HeIIIDensity\"][cell] \n                n_H = n_HI + n_HII\n                n_He = n_HeI + n_HeII + n_HeIII\n                \n                # Read in ionized fractions for this cell\n                x_HI = n_HI / n_H\n                x_HII = n_HII / n_H\n                x_HeI = n_HeI / n_He\n                x_HeII = n_HeII = n_He\n                x_HeIII = n_HeIII = n_He\n                \n                # Compute mean molecular weight for this cell\n                mu = 1. / (self.cosm.X * (1. + x_HII) + self.cosm.Y * (1. + x_HeII + x_HeIII) / 4.)\n                \n                # Retrieve path length through this cell\n                dx = self.dx[cell]     \n                                        \n                # Crossing time\n                dct = self.CellCrossingTime[cell]                        \n                                        \n                # For convenience     \n                nabs = np.array([n_HI, n_HeI, n_HeII])\n                nion = np.array([n_HII, n_HeII, n_HeIII])\n                n_H = n_HI + n_HII\n                n_He = n_HeI + n_HeII + n_HeIII\n                n_B = n_H + n_He + n_e\n                \n                # Compute internal energy for this cell\n                T = newdata[\"Temperature\"][cell]\n                E = 3. * k_B * T * n_B / mu / 2.\n                \n                q_cell = [n_HII, n_HeII, n_HeIII, E]\n                                \n                # Add columns of this cell\n                packs[j][2] += newdata['HIDensity'][cell] * dc * dx\n                packs[j][3] += newdata['HeIDensity'][cell] * dc * dx \n                packs[j][4] += newdata['HeIIDensity'][cell] * dc * dx\n                ncol = np.log10(packs[j][2:5])\n                \n                ######################################\n                ######## Solve Rate Equations ########\n                ######################################\n                \n                # Retrieve indices used for interpolation\n                indices = self.coeff.Interpolate.GetIndices(ncol)\n                \n                # Retrieve coefficients and what not.\n                args = [nabs, nion, n_H, n_He, n_e]                \n                args.extend(self.coeff.ConstructArgs(args, indices, Lbol, r, ncol, T, dx * dc, t, self.z, cell))\n           \n                # Unpack so we have everything by name\n                nabs, nion, n_H, n_He, n_e, Gamma, gamma, Beta, alpha, \\\n                    k_H, zeta, eta, psi, xi, omega, hubble, compton = args        \n                                                                                                         \n                ######################################\n                ######## Solve Rate Equations ########\n                ######################################                          \n                                \n                tarr, qnew, h, odeitr, rootitr = self.solver.integrate(self.RateEquations, \n                    q_cell, cell_t, cell_t + subdt, self.z, self.z - self.dz, None, h, *args)                 \n                                    \n                # Unpack results of coupled equations - Remember: these are lists and we only need the last entry \n                newHII, newHeII, newHeIII, newE = qnew    \n                \n                # Weight by volume if less than a cell traversed\n                if dc < 1:\n                    dnHII = newHII - newdata['HIIDensity'][cell]\n                    dnHeII = newHeII - newdata['HeIIDensity'][cell]\n                    dnHeIII = newHeIII - newdata['HeIIIDensity'][cell]\n                    dV = self.coeff.ShellVolume(r, dx * dc) / self.coeff.ShellVolume(self.r[cell], dx)\n                    newHII = newdata['HIIDensity'][cell] + dnHII * dV \n                    newHeII = newdata['HeIIDensity'][cell] + dnHeII * dV\n                    newHeIII = newdata['HeIIIDensity'][cell] + dnHeIII * dV\n                                \n                # Calculate neutral fractions\n                newHI = n_H - newHII\n                newHeI = n_He - newHeII - newHeIII               \n                \n                # Convert from internal energy back to temperature\n                newT = newE * 2. * mu / 3. / k_B / n_B     \n                                 \n                # Store data\n                newdata = self.StoreData(newdata, cell, newHI, newHII, newHeI, newHeII, newHeIII, newT,\n                    self.tau_all[cell], odeitr, h, rootitr, Gamma, k_H, Beta, alpha, zeta, eta, psi, gamma, xi, \n                    omega, hubble, compton)                    \n                                                         \n                cell_pack += dc\n                cell_t += subdt\n                                                \n                ######################################\n                ################ DONE ################     \n                ######################################  \n                \n        # Adjust timestep for next cycle\n        if self.AdaptiveGlobalStep:\n            n_HI = newdata['HIDensity']\n            n_HII = newdata['HIIDensity']\n            n_H_all = n_HI + n_HII\n            n_HeI = newdata['HeIDensity']\n            n_HeII = newdata['HeIIDensity']\n            n_HeIII = newdata['HeIIIDensity']\n            n_He_all = n_HeI + n_HeII + n_HeIII\n            n_e_all = n_HII + n_HeII + 2 * n_HeIII\n            T = newdata['Temperature']\n            n_B_all = n_H_all + n_He_all + n_e_all\n            \n            ncol_HI = np.roll(np.cumsum(n_HI * self.dx), 1)\n            ncol_HeI = np.roll(np.cumsum(n_HeI * self.dx), 1)\n            ncol_HeII = np.roll(np.cumsum(n_HeII * self.dx), 1)\n            ncol_HI[0] = ncol_HeI[0] = ncol_HeII[0] = neglible_column\n            ncol = np.transpose(np.log10([ncol_HI, ncol_HeI, ncol_HeII]))   \n            \n            tau = self.ComputeOpticalDepths([ncol_HI, ncol_HeI, ncol_HeII])\n            \n            for cell in self.grid:\n                r = self.r[cell]\n                dx = self.dx[cell]\n                nabs = np.array([n_HI[cell], n_HeI[cell], n_HeII[cell]])\n                nion = np.array([n_HII[cell], n_HeII[cell], n_HeIII[cell]])\n                \n                indices = self.coeff.Interpolate.GetIndices(ncol[cell])\n                               \n                args = [nabs, nion, n_H_all[cell], n_He_all[cell], n_e_all[cell]]  \n                args.extend(self.coeff.ConstructArgs(args, indices, Lbol, r, ncol[cell], T[cell], dx, t, self.z))\n           \n                # Unpack so we have everything by name\n                nabs, nion, n_H, n_He, n_e, Gamma, gamma, Beta, alpha, \\\n                    k_H, zeta, eta, psi, xi, omega, hubble, compton = args \n                \n                dtphot[cell] = self.control.ComputePhotonTimestep(tau[:,cell], \n                    nabs, nion, ncol[cell], n_H, n_He, \n                    n_e, n_B_all[cell], Gamma, gamma, Beta, alpha, k_H, zeta, \n                    eta, psi, xi, omega, hubble, compton, T[cell], self.z, dt) \n                    \n                if self.pf['LightCrossingTimeRestrictedTimestep']: \n                    dtphot[cell] = min(dtphot[cell], \n                        self.LightCrossingTimeRestrictedTimestep * self.CellCrossingTime[cell])    \n                    \n        # Update photon packages   \n        newdata['PhotonPackages'] = np.array(self.UpdatePhotonPackages(packs, t + dt))\n                \n        return newdata, dtphot\n        \n    #def ConserveParticleNumber(self, newxHII, newxHeII, newxHeIII, newE):\n    #    \"\"\"\n    #    Take solver.y and make sure ion fractions sum to 1 - MinimumSpeciesFraction.\n    #    \"\"\"    \n    #    \n    #    if newxHII >= 1:\n    #        newxHII = 1. - self.pf['MinimumSpeciesFraction']\n    #        \n    #    if (newxHeII + newxHeIII) >= 1:\n    #        if newxHeII > newxHeIII:\n    #            newxHeII += 1. - (newxHeII + newxHeIII)\n    #            newxHeIII -= self.pf['MinimumSpeciesFraction']\n    #        else:\n    #            newxHeIII += 1. - (newxHeII + newxHeIII)\n    #            newxHeII -= self.pf['MinimumSpeciesFraction']\n    #\n    #    return newxHII, newxHeII, newxHeIII, newE\n    #\n    #def UpdatePhotonPackages(self, packs, t_next):\n    #    \"\"\"\n    #    Get rid of old photon packages.\n    #    \"\"\"    \n    #            \n    #    to_eliminate = []\n    #    for i, pack in enumerate(packs):\n    #        if (t_next - pack[0]) > (self.pf['LengthUnits'] / c): \n    #            to_eliminate.append(i)\n    #        \n    #    to_eliminate.reverse()    \n    #    for element in to_eliminate: \n    #        packs.pop(element)\n    #              \n    #    return np.array(packs)\n    #   \n    #def StoreData(self, newdata, cell, newHI, newHII, newHeI, newHeII, newHeIII, newT,\n    #    tau, Gamma, k_H, Beta, alpha, zeta, eta, psi, gamma, xi, omega, hubble, compton, \n    #    Jc, Ji, Ts, dTb, packs = None):\n    #    \"\"\"\n    #    Copy fields to newdata dictionary.\n    #    \"\"\"\n    #    \n    #    # Update quantities in 'data' -> 'newdata'                \n    #    newdata[\"HIDensity\"][cell] = newHI                                                                                            \n    #    newdata[\"HIIDensity\"][cell] = newHII\n    #    newdata[\"HeIDensity\"][cell] = newHeI\n    #    newdata[\"HeIIDensity\"][cell] = newHeII\n    #    newdata[\"HeIIIDensity\"][cell] = newHeIII\n    #    newdata[\"ElectronDensity\"][cell] = newHII + newHeII + 2.0 * newHeIII\n    #    newdata[\"Temperature\"][cell] = newT    \n    #    newdata[\"OpticalDepth\"][cell] = tau\n    #    newdata[\"SpinTemperature\"][cell] = Ts\n    #    newdata[\"BrightnessTemperature\"][cell] = dTb\n    #            \n    #    if self.pf['OutputRates']:\n    #        for i in xrange(3):\n    #            \n    #            for j in xrange(self.rs.Ns):\n    #                newdata['PhotoIonizationRate%i_src%i' % (i, j)][cell] = Gamma[i][j]\n    #                newdata['PhotoHeatingRate%i_src%i' % (i, j)][cell] = k_H[i][j]\n    #                newdata['SecondaryIonizationRate%i_src%i' % (i, j)][cell] = gamma[i,:,j] \n    #                \n    #                newdata['InjectedLyAFlux%i_src%i' % (i, j)][cell] = Ji[i][j]\n    #                \n    #                if i == 0:\n    #                    newdata['ContinuumLyAFlux_src%i' % j][cell] = Jc[j]\n    #            \n    #            newdata['CollisionalIonizationRate%i' % i][cell] = Beta[i] \n    #            newdata['RadiativeRecombinationRate%i' % i][cell] = alpha[i] \n    #            newdata['CollisionalIonizationCoolingRate%i' % i][cell] = zeta[i] \n    #            newdata['RecombinationCoolingRate%i' % i][cell] = eta[i] \n    #            newdata['CollisionalExcitationCoolingRate%i' % i][cell] = psi[i]                \n    #            \n    #            if i == 2:\n    #                newdata['DielectricRecombinationRate'][cell] = xi[i]\n    #                newdata['DielectricRecombinationCoolingRate'][cell] = omega[i]   \n    #                \n    #        newdata['HubbleCoolingRate'][cell] = hubble                      \n    #                \n    #    return newdata            \n    #    \n    #def RateEquations(self, t, q, args):    \n    #    \"\"\"\n    #    This function returns the right-hand side of our ODE's (Equations 1, 2, 3 and 9 in Mirocha et al. 2012).\n    #\n    #    q = [x_HII, x_HeII, x_HeIII, E] - our four coupled equations. q = generalized quantity I guess.\n    #    \n    #    args = (nabs, nion, n_H, n_He, n_e, Gamma, gamma, Beta, alpha, k_H, zeta, eta, psi, xi, omega)\n    #    \n    #    where nabs, nion, Gamma, gamma, Beta, alpha, k_H, zeta, eta, psi, xi = 3 element arrays \n    #        (one entry per species)\n    #                \n    #    \"\"\"\n    #    \n    #    nabs, nion, n_H, n_He, n_e, Gamma, gamma, Beta, alpha, k_H, zeta, eta, \\\n    #        psi, xi, omega, hubble, compton, Jc, Ji = args\n    #                    \n    #    dqdt = self.zeros_tmp\n    #    \n    #    # Neutrals (current time-step)\n    #    nHI = n_H * (1. - q[0])\n    #    nHII = n_H * q[0]\n    #    nHeI = n_He * (1. - q[1] - q[2])\n    #    nHeII = n_He * q[1]\n    #    nHeIII = n_He * q[2]\n    #    \n    #    nabs = [nHI, nHeI, nHeII]\n    #    nion = [nHII, nHeII, nHeIII]\n    #    \n    #    xHI = 1. - q[0]\n    #    xHII = q[0]\n    #    xHeI = 1. - q[1] - q[2]\n    #    xHeII = q[1]\n    #    xHeIII = q[2]\n    #    \n    #    n_e = q[0] * n_H + q[1] * n_He + 2. * q[2] * n_He\n    #    \n    #    # Always solve hydrogen rate equation\n    #    dqdt[0] = (Gamma[0] + Beta[0] * n_e) * xHI + \\\n    #              (gamma[0][0] * xHI + gamma[0][1] * nHeI / n_H + gamma[0][2] * nHeII / n_H) - \\\n    #               alpha[0] * n_e * xHII        \n    #            \n    #    # Helium rate equations  \n    #    if self.pf['MultiSpecies']:       \n    #        dqdt[1] = (Gamma[1] + Beta[1] * n_e) * xHeI + \\\n    #                  (gamma[1][0] * nHI / n_He + gamma[1][1] * nHeI / n_He + gamma[1][2] * xHeII / n_He)  + \\\n    #                   alpha[2] * n_e * xHeIII - \\\n    #                  (Beta[1] + alpha[1] + xi[1]) * n_e * nHeII / n_He\n    #                          \n    #        dqdt[2] = (Gamma[2] + Beta[2] * n_e) * xHeII - alpha[2] * n_e * nHeIII / n_He\n    #            \n    #    # Temperature evolution - looks dumb but using np.sum is slow\n    #    if not self.pf['Isothermal']:\n    #        phoheat = k_H[0] * nHI\n    #        ioncool = zeta[0] * nHI\n    #        reccool = eta[0] * nHII\n    #        exccool = psi[0] * nHI\n    #        \n    #        if self.pf['MultiSpecies']:\n    #            phoheat += k_H[1] * nabs[1] + k_H[2] * nabs[2]\n    #            ioncool += zeta[1] * nabs[1] + zeta[2] * nabs[2]\n    #            reccool += eta[1] * nion[1] + eta[2] * nion[2]\n    #            exccool += psi[1] * nabs[1] + psi[2] * nabs[2]\n    #        \n    #        dqdt[3] = phoheat - n_e * (ioncool + reccool + exccool + nHeIII * omega[1])\n    #                           \n    #        if self.pf['CosmologicalExpansion']:\n    #            dqdt[3] -= 2. * hubble * q[3]\n    #           \n    #            #if self.pf['ComptonHeating']:\n    #            #    dqdt[3] += compton\n    #        \n    #    return dqdt\n    #    \n    #def Jacobian(self, t, q, args):\n    #    \"\"\"\n    #    Jacobian of the rate equations.\n    #    \"\"\"    \n    #    \n    #    nabs, nion, n_H, n_He, n_e, Gamma, gamma, Beta, alpha, k_H, zeta, eta, \\\n    #        psi, xi, omega, hubble, compton = args\n    #                            \n    #    # Neutrals (current time-step)\n    #    nHI = n_H * (1. - q[0])\n    #    nHII = n_H * q[0]\n    #    nHeI = n_He * (1. - q[1] - q[2])\n    #    nHeII = n_He * q[1]\n    #    nHeIII = n_He * q[2]\n    #    \n    #    xHI = 1. - q[0]\n    #    xHII = q[0]\n    #    xHeI = 1. - q[1] - q[2]\n    #    xHeII = q[1]\n    #    xHeIII = q[2]\n    #    \n    #    J = np.zeros([4, 4])\n    #    \n    #    J[0][0] = -(Gamma[0] + Beta[0] * n_e - gamma[0][0]) - alpha[0] * n_e\n    #    J[0][1] = -gamma[0][1] / n_H + gamma[0][2] / n_H\n    #    J[0][2] = -gamma[0][1] / n_H\n    #    J[1][0] = -gamma[1][0] / n_He\n    #    J[1][1] = -(Gamma[1] + Beta[0] * n_e + gamma[1][1] / n_He - gamma[1][2] / n_He) \\\n    #              +(Beta[1] + alpha[1] + xi[1]) * n_e / n_He\n    #    J[1][2] = -gamma[1][1] / n_He + alpha[2] * n_e\n    #    J[2][1] = (Gamma[2] + Beta[2] * n_e)\n    #    J[2][2] = -alpha[2] * n_e / n_He\n    #    J[3][0] = n_e * (zeta[0] - eta[0] + psi[0]) - k_H[0]\n    #    J[3][1] = n_e * (zeta[1] - eta[1] + psi[1]) - k_H[1]\n    #    J[3][2] = n_e * (zeta[2] - eta[2] + psi[2] - omega[1]) - k_H[2]\n    #                                                           \n    #    return J\n    #    \n    #def ComputeOpticalDepths(self, ncol):\n    #    \"\"\"\n    #    Compute optical depths *between* source and all cells.  Used solely (I think)\n    #    for calculating next timestep. \n    #    \"\"\"\n    #    \n    #    tau_all_arr = np.zeros([3, self.GridDimensions, self.pf['NumberOfSources']]) \n    #    for rs, source in enumerate(self.rs.all_sources):\n    #        if not source.TableAvailable:\n    #            tmp_nHI = np.transpose(len(source.E) * [ncol[0]])   \n    #            tau_all_arr[0,:,rs] = np.sum(tmp_nHI * source.sigma[0, rs], axis = 1)\n    #                        \n    #            if self.pf['MultiSpecies']:\n    #                tmp_nHeI = np.transpose(len(source.E) * [ncol[1]])\n    #                tmp_nHeII = np.transpose(len(source.E) * [ncol[2]])\n    #                tau_all_arr[1,:,rs] = np.sum(tmp_nHeI * source.sigma[1, rs], axis = 1)\n    #                tau_all_arr[2,:,rs] = np.sum(tmp_nHeII * source.sigma[2, rs], axis = 1)\n    #        else:\n    #            for i, col in enumerate(np.log10(ncol[0])):\n    #                tau_all_arr[0,i,rs] = source.Interpolate.OpticalDepth(col, 0)\n    #                \n    #                if self.pf['MultiSpecies']:\n    #                    tau_all_arr[1,i,rs] = source.Interpolate.OpticalDepth(np.log10(ncol[1][i]), 1)\n    #                    tau_all_arr[2,i,rs] = source.Interpolate.OpticalDepth(np.log10(ncol[2][i]), 2)\n    #                    \n    #            tau_all_arr[0][0][rs] = tau_all_arr[1][0] = tau_all_arr[2][0] = neglible_tau \n    #\n    #    # Take minimum optical depth over sources to be conservative with dt\n    #    return np.min(tau_all_arr, axis = -1)\n    #\n#    def EvolvePhotons(self, data, t, dt, h, lb):\n    #    \"\"\"\n    #    This routine calls our solvers and updates 'data' -> 'newdata'\n    #    \"\"\"\n    #    \n    #    # Make data globally accessible\n    #    self.data = data\n    #    \n    #    # Figure out which processors will solve which cells and create newdata dict\n    #    self.solve_arr, newdata = self.control.DistributeDataAcrossProcessors(data, lb)\n    #                      \n    #    # If we're in an expanding universe, prepare to dilute densities by (1 + z)**3\n    #    self.z = 0 \n    #    self.dz = 0   \n    #    if self.pf['CosmologicalExpansion']: \n    #        self.z = self.cosm.TimeToRedshiftConverter(0., t, self.pf['InitialRedshift'])\n    #        self.dz = dt / self.cosm.dtdz(self.z)\n    #           \n    #    # Nice names for densities, ionized fractions\n    #    self.n_H_arr = data[\"HIDensity\"] + data[\"HIIDensity\"]\n    #    self.x_HI_arr = data[\"HIDensity\"] / self.n_H_arr\n    #    self.x_HII_arr = data[\"HIIDensity\"] / self.n_H_arr\n    #    \n    #    if self.pf['MultiSpecies']:\n    #        self.n_He_arr = data[\"HeIDensity\"] + data[\"HeIIDensity\"] + data[\"HeIIIDensity\"]\n    #        self.x_HeI_arr = data[\"HeIDensity\"] / self.n_He_arr\n    #        self.x_HeII_arr = data[\"HeIIDensity\"] / self.n_He_arr\n    #        self.x_HeIII_arr = data[\"HeIIIDensity\"] / self.n_He_arr\n    #    else: \n    #        self.n_He_arr = self.x_HeI_arr = self.x_HeII_arr = self.x_HeIII_arr = np.zeros_like(self.x_HI_arr)\n    #                                                    \n    #    # Compute column densities - meaning column density *between* source and cell\n    #    self.ncol_HI = np.roll(np.cumsum(data[\"HIDensity\"] * self.dx), 1)\n    #    self.ncol_HeI = np.roll(np.cumsum(data[\"HeIDensity\"] * self.dx), 1)\n    #    self.ncol_HeII = np.roll(np.cumsum(data[\"HeIIDensity\"] * self.dx), 1)\n    #    self.ncol_HI[0] = self.ncol_HeI[0] = self.ncol_HeII[0] = neglible_column\n    #    \n    #    # Convenience arrays for column densities, absorbers, ion densities, and some others\n    #    self.ncol_all = np.transpose(np.log10([self.ncol_HI, self.ncol_HeI, self.ncol_HeII]))\n    #    self.nabs_all = np.transpose([data[\"HIDensity\"], data[\"HeIDensity\"], data[\"HeIIDensity\"]])\n    #    self.nion_all = np.transpose([data[\"HIIDensity\"], data[\"HeIIDensity\"], data[\"HeIIIDensity\"]])\n    #    self.mu_all = 1. / (self.cosm.X * (1. + self.x_HII_arr) + self.cosm.Y * (1. + self.x_HeII_arr + self.x_HeIII_arr) / 4.)\n    #    self.ne_all = data[\"ElectronDensity\"]\n    #    self.nB_all = self.n_H_arr + self.n_He_arr + self.ne_all\n    #    \n    #    self.q_all = np.transpose([self.x_HII_arr, self.x_HeII_arr, self.x_HeIII_arr, \n    #        3. * k_B * self.nB_all * data[\"Temperature\"] / 2.])\n    #                                                                                                 \n    #    # Retrieve indices used for N-D interpolation\n    #    self.indices_all = []\n    #    for i, col in enumerate(self.ncol_all):\n    #        tmp = []\n    #        for rs in self.rs.all_sources:\n    #            if rs.TableAvailable:\n    #                tmp.append(rs.Interpolate.GetIndices([col[0], col[1], col[2], np.log10(self.x_HII_arr[i]), t]))\n    #            else:\n    #                tmp.append(None)\n    #        self.indices_all.append(tmp)\n    #                                            \n    #    # Compute tau *between* source and all cells\n    #    tau_all_arr = self.ComputeOpticalDepths([self.ncol_HI, self.ncol_HeI, self.ncol_HeII])\n    #    self.tau_all = zip(*tau_all_arr) \n    #                                    \n    #    # Print status, and update progress bar\n    #    if rank == 0: \n    #        print \"rt1d: %g < t < %g\" % (t / self.pf['TimeUnits'], (t + dt) / self.pf['TimeUnits'])\n    #    if rank == 0 and self.ProgressBar: \n    #        self.pbar = ProgressBar(widgets = widget, maxval = self.grid[-1]).start()        \n    #            \n    #    # SOLVE: c -> inf\n    #    if self.pf['InfiniteSpeedOfLight']: \n    #        newdata, dtphot = self.EvolvePhotonsAtInfiniteSpeed(newdata, t, dt, h)\n    #            \n    #    # SOLVE: c = finite   \n    #    else:\n    #        newdata, dtphot = self.EvolvePhotonsAtFiniteSpeed(newdata, t, dt, h)\n    #          \n    #    ### \n    #    ## Tidy up a bit\n    #    ###\n    #    \n    #    # If multiple processors at work, communicate data and timestep                                                                                          \n    #    if (size > 1) and (self.pf['ParallelizationMethod'] == 1):\n    #        for key in newdata.keys(): \n    #            newdata[key] = MPI.COMM_WORLD.allreduce(newdata[key], newdata[key])\n    #            \n    #        dtphot = MPI.COMM_WORLD.allreduce(dtphot, dtphot) \n    #                            \n    #    # Compute timestep for next cycle based on minimum dt required over entire grid                        \n    #    if self.AdaptiveGlobalStep: \n    #        newdt = min(np.min(dtphot), 2 * dt)\n    #        \n    #        if self.pf['CosmologicalExpansion'] and self.pf['RedshiftRestrictedTimestep']:\n    #            newdt = min(newdt, self.cosm.dtdz(self.z) * self.pf['MaxRedshiftStep'])\n    #        \n    #    else: \n    #        newdt = dt            \n    #    \n    #    # Store timestep information\n    #    newdata['dtPhoton'] = dtphot\n    #                            \n    #    # Load balance grid for next timestep                     \n    #    if size > 1 and self.pf['ParallelizationMethod'] == 1: \n    #        lb = self.control.LoadBalance(dtphot)   \n    #    else: \n    #        lb = None      \n    #        \n    #    if rank == 0 and self.ProgressBar: \n    #        self.pbar.finish()    \n    #                                                                                                                                                              \n    #    return newdata, h, newdt, lb\n    #", "meta": {"hexsha": "39bd779828a52ca4b1e69123cd87dd743a9179e5", "size": 36126, "ext": "py", "lang": "Python", "max_stars_repo_path": "rt1d/evolve/Radiate.py", "max_stars_repo_name": "astrojhgu/rt1d", "max_stars_repo_head_hexsha": "cb49510ae9850d1491dcf9336e3994fb1b153438", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rt1d/evolve/Radiate.py", "max_issues_repo_name": "astrojhgu/rt1d", "max_issues_repo_head_hexsha": "cb49510ae9850d1491dcf9336e3994fb1b153438", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rt1d/evolve/Radiate.py", "max_forks_repo_name": "astrojhgu/rt1d", "max_forks_repo_head_hexsha": "cb49510ae9850d1491dcf9336e3994fb1b153438", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.6218034993, "max_line_length": 770, "alphanum_fraction": 0.441676355, "include": true, "reason": "import numpy", "num_tokens": 9457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.2814055953761018, "lm_q1q2_score": 0.1730891641901084}}
{"text": "#!/usr/bin/env python\nimport os\nimport sys\nimport numpy as np\nfrom glob import glob\nimport matplotlib\nmatplotlib.use('PDF')\nfrom mgplottools.mpl import set_axis, new_figure, get_color, set_color_cycle, ls\n\ndef create_figure(outfile, data):\n    \"\"\"\n    data is a dict\n    run_folder => {\n        'E' => array of amplitudes\n        'concurrence' => array of concurrences for each value in E,\n        'pop_loss' => array of population loss from log subsp (E)\n        'nq_vals' => array of number of qubit levels included in prop (E),\n        'nc_vals' => array of number of qubit levels included in prop (E)\n    }\n    \"\"\"\n\n    # Layout\n    fig_width       = 12.5              # Total canvas (cv) width\n    legend_offset   = fig_width-3.9     # Left cv -> legend\n    left_margin     = 1.1               # Left cv -> plot area\n    right_margin    = 4.1               # plot area -> right cv\n    top_margin      = 0.4               # top cv -> plot area\n    bottom_margin   = 1.0               # bottom cv -> plot area\n    h               = 2.0               # height of each panel\n    gap             = 0.0               # gap between panels\n    w = fig_width - (left_margin + right_margin)  # width of panel\n\n    n_panels = 2\n    panels_total_height = n_panels*h + (n_panels-1)*gap\n\n    fig_height = bottom_margin + n_panels*h + (n_panels-1)*gap + top_margin\n    fig = new_figure(fig_width, fig_height)\n\n    E = data[data.keys()[0]]['E'] # pulse amplitude, for all axes\n\n    axes = [] # panels\n    # create axes from top to bottom\n    for i in xrange(n_panels):\n        p_offset = bottom_margin + (n_panels-i-1)*(h+gap)\n        pos = [left_margin/fig_width, p_offset/fig_height,\n               w/fig_width, h/fig_height]\n        ax = fig.add_axes(pos)\n        if i == n_panels-1:\n            set_axis(ax, 'x', E[0], E[-1], 50, minor=5,\n                     label=r'peak pulse amplitude $\\epsilon_0$ (MHz)')\n        else:\n            set_axis(ax, 'x', E[0], E[-1], 50, minor=5, ticklabels=False)\n        set_axis(ax, 'y', 0, 1, 0.5, minor=5)\n        if i == 0: # top panel\n            ax.set_yticklabels(['0', '0.5', '1.0'])\n        else:\n            ax.set_yticklabels(['0', '0.5', ''])\n        axes.append(ax)\n\n    titles = [# title for each panel (top to bottom)\n        r'$\\omega_c = \\SI{6.0}{GHz} < \\omega_1, \\omega_2$',\n        r'$\\omega_c = \\SI{8.1}{GHz} > \\omega_1, \\omega_2$',\n    ]\n\n    # do the plotting\n    for (file, label, color, line_style) in (\n        ('params1d-60_T200', r'$\\omega_d = \\omega_c - 60$~MHz', 'blue',   'solid'),\n        ('params1d-40_T200', r'$\\omega_d = \\omega_c - 40$~MHz', 'orange', 'solid'),\n        ('params1d40_T200',  r'$\\omega_d = \\omega_c + 40$~MHz', 'red',    'long-dashed'),\n        ('params1d60_T200',  r'$\\omega_d = \\omega_c + 60$~MHz', 'green',  'long-dashed')\n     ):\n        try:\n            axes[0].plot(data[file]['E'], data[file]['concurrence'],\n                        label=label, color=get_color(color),\n                        dashes=ls[line_style])\n        except KeyError:\n            pass\n    for (file, label, color, line_style) in (\n        ('params2d-60_T200', r'$\\omega_d = \\omega_c - 60$~MHz', 'blue',   'solid'),\n        ('params2d-40_T200', r'$\\omega_d = \\omega_c - 40$~MHz', 'orange', 'solid'),\n        ('params2d40_T200',  r'$\\omega_d = \\omega_c + 40$~MHz', 'red',    'long-dashed'),\n        ('params2d60_T200',  r'$\\omega_d = \\omega_c + 60$~MHz', 'green',  'long-dashed')\n     ):\n        try:\n            axes[1].plot(data[file]['E'], data[file]['concurrence'],\n                        label=label, color=get_color(color),\n                        dashes=ls[line_style])\n        except KeyError:\n            pass\n\n    # label points\n    marker_x = (125, 250)\n    marker_y = (0.9984, 0.9857)\n    marker_text = (\"1\", \"2\")\n    axes[0].scatter(marker_x,  marker_y, c='black', clip_on=False,\n                    edgecolors='none', zorder=10)\n    for i, txt in enumerate(marker_text):\n            axes[0].annotate(txt, (marker_x[i],marker_y[i]),\n                             xytext=(2, 3), textcoords='offset points')\n    marker_x = (425,)\n    marker_y = (0.9968, )\n    marker_text = (\"3\",)\n    axes[1].scatter(marker_x,  marker_y, c='black', clip_on=False,\n                    edgecolors='none', zorder=10)\n    for i, txt in enumerate(marker_text):\n            axes[1].annotate(txt, (marker_x[i],marker_y[i]),\n                             xytext=(2, 3), textcoords='offset points')\n\n\n    # legend\n    for i, ax in enumerate(axes):\n        p_offset = bottom_margin + (n_panels-i-1)*(h+gap)\n        ax.legend(loc='center left', title=titles[i],\n                  bbox_to_anchor=(legend_offset/fig_width,\n                                 (p_offset + 0.5*h)/fig_height),\n                  bbox_transform=fig.transFigure,\n                  labelspacing=0.1, fontsize=\"small\",\n                  borderpad=0.0, borderaxespad=0.0)\n\n    # y axis label\n    fig.text(0, (bottom_margin + 0.5*panels_total_height)/fig_height,\n             'concurrence after $T=\\SI{200}{ns}$',\n             rotation='vertical', ha='left', va='center')\n\n    # output\n    fig.savefig(outfile, format=os.path.splitext(outfile)[1][1:])\n\n\ndef read_data(data_folder):\n    \"\"\"\n    Return dictionary\n\n    run_folder => {\n        'E' => array of amplitudes\n        'concurrence' => array of concurrences for each value in E,\n        'pop_loss' => array of population loss from log subsp (E)\n        'nq_vals' => array of number of qubit levels included in prop (E),\n        'nc_vals' => array of number of qubit levels included in prop (E)\n    }\n    \"\"\"\n    result = {}\n    subdirs = [os.path.join(data_folder,o) for o in os.listdir(data_folder)\n               if os.path.isdir(os.path.join(data_folder,o))]\n    for folder in subdirs:\n        foldername = os.path.split(folder)[-1]\n        datfile = glob(os.path.join(folder, 'entanglement*.dat'))[0]\n        try:\n            E, concurrence, pop_loss = np.genfromtxt(datfile, usecols=(0,1,2),\n                                                    unpack=True)\n            nq_vals, nc_vals = np.genfromtxt(datfile, usecols=(3,4),\n                                            dtype=np.int, unpack=True)\n\n            result[foldername] = {\n                'E':  E,\n                'concurrence':  concurrence,\n                'pop_loss':  pop_loss,\n                'nq_vals':  nq_vals,\n                'nc_vals':  nc_vals\n            }\n        except ValueError:\n            # skip if the data file is empty (run has not finished yet)\n            pass\n    return result\n\n\ndef main(argv=None):\n    if argv is None:\n        argv = sys.argv\n    basename = os.path.splitext(__file__)[0]\n    outfile = basename + '.pdf'\n    data_folder = basename\n    create_figure(outfile, read_data(data_folder))\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n", "meta": {"hexsha": "cd266c3d66ae3c221b0e112081289074baefd3a7", "size": 6805, "ext": "py", "lang": "Python", "max_stars_repo_path": "chapters/transmon/holonomic_entanglement.py", "max_stars_repo_name": "goerz/dissertation", "max_stars_repo_head_hexsha": "ee8ae29b5da1bc6033260224ae6444fd7f4c4a2f", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-05-09T03:22:23.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-11T13:33:43.000Z", "max_issues_repo_path": "chapters/transmon/holonomic_entanglement.py", "max_issues_repo_name": "goerz/dissertation", "max_issues_repo_head_hexsha": "ee8ae29b5da1bc6033260224ae6444fd7f4c4a2f", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/transmon/holonomic_entanglement.py", "max_forks_repo_name": "goerz/dissertation", "max_forks_repo_head_hexsha": "ee8ae29b5da1bc6033260224ae6444fd7f4c4a2f", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6647727273, "max_line_length": 89, "alphanum_fraction": 0.5419544453, "include": true, "reason": "import numpy", "num_tokens": 1882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.17299968151092637}}
{"text": "import logging\nimport os\nimport pathlib\n\nimport appdirs\nfrom netCDF4 import Dataset\nimport numpy as np\nfrom scipy.interpolate import griddata\nfrom scipy.interpolate.fitpack2 import RectBivariateSpline\n\nfrom pyschism.forcing.bctides.base import TidalDataProvider\n\n\nlogger = logging.getLogger(__name__)\n\nTPXO_ELEVATION = 'h_tpxo9.v1.nc'\nTPXO_VELOCITY = 'u_tpxo9.v1.nc'\n\n\ndef raise_missing_file(fpath, fname):\n    raise FileNotFoundError('\\n'.join([\n        f'No TPXO file found at \"{fpath}\".',\n        'New users will need to register and request a copy of '\n        f'the TPXO9 NetCDF file (specifically `{fname}`) '\n        'from the authors at https://www.tpxo.net.',\n        'Once you obtain `h_tpxo9.v1.nc`, you can follow one of the '\n        'following options: ',\n        f'1) copy or symlink the file to \"{fpath}\"',\n        f'2) set the environment variable `{fname}` to point'\n        ' to the file',\n    ]))\n\n\nclass TPXO(TidalDataProvider):\n\n    def __init__(self, h_file=None, u_file=None):\n        self._h_file = h_file\n        self._u_file = u_file\n\n    def get_elevation(self, constituent, vertices):\n        logger.info('Querying TPXO for elevation constituent '\n                    f'{constituent}.')\n        amp = self._get_interpolation(\n            'elevation', 'ha', constituent, vertices)\n        phase = self._get_interpolation(\n            'elevation', 'hp', constituent, vertices)\n        return amp, phase\n\n    def get_velocity(self, constituent, vertices):\n        logger.info('Querying TPXO for velocity constituent '\n                    f'{constituent}.')\n        uamp = self._get_interpolation(\n            'velocity', 'ua', constituent, vertices) / 100.\n        uphase = self._get_interpolation(\n            'velocity', 'up', constituent, vertices)\n        vamp = self._get_interpolation(\n            'velocity', 'va', constituent, vertices) / 100.\n        vphase = self._get_interpolation(\n            'velocity', 'vp', constituent, vertices)\n        return uamp, uphase, vamp, vphase\n\n    @property\n    def constituents(self):\n        return ['M2', 'S2', 'N2', 'K2', 'K1', 'O1', 'P1',\n                'Q1', 'Mm', 'Mf', 'M4', 'MN4', 'MS4', '2N2', 'S1']\n        if not hasattr(self, '_constituents'):\n            self._constituents = [\n                c.capitalize() for c in self.h['con'][:].astype(\n                    '|S1').tobytes().decode('utf-8').split()]\n        return self._constituents\n\n    @property\n    def x(self) -> np.ndarray:\n        return self.h['lon_z'][:, 0].data\n\n    @property\n    def y(self) -> np.ndarray:\n        return self.h['lat_z'][0, :].data\n\n    @property\n    def h(self):\n        if not hasattr(self, '_h'):\n            if self._h_file is None:\n                self._h_file = os.getenv('TPXO_ELEVATION')\n                if self._h_file is None:\n                    self._h_file = pathlib.Path(\n                        appdirs.user_data_dir('tpxo')) / TPXO_ELEVATION\n            if not self._h_file.exists():\n                raise_missing_file(self._h_file, TPXO_ELEVATION)\n            self._h = Dataset(self._h_file)\n        return self._h\n\n    @property\n    def uv(self):\n        if not hasattr(self, '_uv'):\n            if self._u_file is None:\n                self._u_file = os.getenv('TPXO_VELOCITY')\n                if self._u_file is None:\n                    self._u_file = pathlib.Path(\n                        appdirs.user_data_dir('tpxo')) / TPXO_VELOCITY\n            if not self._u_file.exists():\n                raise_missing_file(self._u_file, TPXO_VELOCITY)\n            self._uv = Dataset(self._u_file)\n        return self._uv\n\n    def _get_interpolation(self, phys_var, ncvar, constituent, vertices):\n        lower_c = [c.lower() for c in self.constituents]\n        if phys_var == 'elevation':\n            ncarray = self.h\n        elif phys_var == 'velocity':\n            ncarray = self.uv\n        zi = ncarray[ncvar][\n            lower_c.index(constituent.lower()), :, :]\n        xo = np.asarray(\n            [x + 360. if x < 0. else x for x in vertices[:, 0]]).flatten()\n        yo = vertices[:, 1].flatten()\n        xi, yi = np.meshgrid(self.x, self.y, indexing='ij')\n        xi = xi.flatten()\n        yi = yi.flatten()\n        zi = zi.flatten()\n        dx = np.mean(np.diff(self.x))\n        dy = np.mean(np.diff(self.y))\n        # buffer the bbox by 2 difference units\n        mask1 = np.logical_and(\n            np.logical_and(\n                xi >= np.min(xo) - 2 * dx,\n                xi <= np.max(xo) + 2 * dx\n            ),\n            np.logical_and(\n                yi >= np.min(yo) - 2 * dy,\n                yi <= np.max(yo) + 2 * dy\n            )\n        )\n        # remove junk values from input array\n        mask2 = np.ma.masked_where(zi != 0., zi)\n        iidx = np.where(np.logical_and(mask1, mask2))\n        values = griddata(\n            (xi[iidx], yi[iidx]),\n            zi[iidx],\n            (xo, yo),\n            method='linear',\n            fill_value=np.nan,\n        )\n        nan_idxs = np.where(np.isnan(values))\n        values[nan_idxs] = griddata(\n            (xi[iidx], yi[iidx]),\n            zi[iidx],\n            (xo[nan_idxs], yo[nan_idxs]),\n            method='nearest',\n        )\n        return values\n", "meta": {"hexsha": "4834e6775c7133046f8d037e518c2e75ea3e6561", "size": 5214, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyschism/forcing/bctides/tpxo.py", "max_stars_repo_name": "SorooshMani-NOAA/pyschism", "max_stars_repo_head_hexsha": "df803edb53184625b12399f38a8bd26a022abbc1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2020-02-02T09:48:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T19:28:58.000Z", "max_issues_repo_path": "pyschism/forcing/bctides/tpxo.py", "max_issues_repo_name": "SorooshMani-NOAA/pyschism", "max_issues_repo_head_hexsha": "df803edb53184625b12399f38a8bd26a022abbc1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2020-03-04T13:40:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T15:30:42.000Z", "max_forks_repo_path": "pyschism/forcing/bctides/tpxo.py", "max_forks_repo_name": "SorooshMani-NOAA/pyschism", "max_forks_repo_head_hexsha": "df803edb53184625b12399f38a8bd26a022abbc1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-03-04T09:54:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T00:14:25.000Z", "avg_line_length": 34.3026315789, "max_line_length": 74, "alphanum_fraction": 0.5506329114, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.17299967809818959}}
{"text": "#!/usr/bin/env python3\n\"\"\"\nMulti-compartmental OLM cell example\n\nFile: olm-example.py\n\nCopyright 2021 NeuroML contributors\nAuthors: Padraig Gleeson, Ankur Sinha\n\"\"\"\n\nfrom neuroml import (NeuroMLDocument, IncludeType, Population, PulseGenerator, ExplicitInput, Network, SegmentGroup, Member, Property, Include, Instance, Location)\nfrom CellBuilder import (create_cell, add_segment, add_channel_density, set_init_memb_potential, set_resistivity, set_specific_capacitance, get_seg_group_by_id)\nfrom pyneuroml import pynml\nfrom pyneuroml.lems import LEMSSimulation\nimport numpy as np\n\n\ndef main():\n    \"\"\"Main function\n\n    Include the NeuroML model into a LEMS simulation file, run it, plot some\n    data.\n    \"\"\"\n    # Simulation bits\n    sim_id = \"olm_example_sim\"\n    simulation = LEMSSimulation(sim_id=sim_id, duration=600, dt=0.01, simulation_seed=123)\n    # Include the NeuroML model file\n    simulation.include_neuroml2_file(create_olm_network())\n    # Assign target for the simulation\n    simulation.assign_simulation_target(\"single_olm_cell_network\")\n\n    # Recording information from the simulation\n    simulation.create_output_file(id=\"output0\", file_name=sim_id + \".dat\")\n    simulation.add_column_to_output_file(\"output0\", column_id=\"pop0_0_v\", quantity=\"pop0[0]/v\")\n    simulation.add_column_to_output_file(\"output0\",\n                                         column_id=\"pop0_0_v_Seg0_soma_0\",\n                                         quantity=\"pop0/0/olm/0/v\")\n    simulation.add_column_to_output_file(\"output0\",\n                                         column_id=\"pop0_0_v_Seg1_soma_0\",\n                                         quantity=\"pop0/0/olm/1/v\")\n    simulation.add_column_to_output_file(\"output0\",\n                                         column_id=\"pop0_0_v_Seg0_axon_0\",\n                                         quantity=\"pop0/0/olm/2/v\")\n    simulation.add_column_to_output_file(\"output0\",\n                                         column_id=\"pop0_0_v_Seg1_axon_0\",\n                                         quantity=\"pop0/0/olm/3/v\")\n    simulation.add_column_to_output_file(\"output0\",\n                                         column_id=\"pop0_0_v_Seg0_dend_0\",\n                                         quantity=\"pop0/0/olm/4/v\")\n    simulation.add_column_to_output_file(\"output0\",\n                                         column_id=\"pop0_0_v_Seg1_dend_0\",\n                                         quantity=\"pop0/0/olm/6/v\")\n    simulation.add_column_to_output_file(\"output0\",\n                                         column_id=\"pop0_0_v_Seg0_dend_1\",\n                                         quantity=\"pop0/0/olm/5/v\")\n    simulation.add_column_to_output_file(\"output0\",\n                                         column_id=\"pop0_0_v_Seg1_dend_1\",\n                                         quantity=\"pop0/0/olm/7/v\")\n    # Save LEMS simulation to file\n    sim_file = simulation.save_to_file()\n\n    # Run the simulation using the NEURON simulator\n    pynml.run_lems_with_jneuroml_neuron(sim_file, max_memory=\"2G\", nogui=True,\n                                        plot=False, skip_run=False)\n    # Plot the data\n    plot_data(sim_id)\n\n\ndef plot_data(sim_id):\n    \"\"\"Plot the sim data.\n\n    Load the data from the file and plot the graph for the membrane potential\n    using the pynml generate_plot utility function.\n\n    :sim_id: ID of simulaton\n\n    \"\"\"\n    data_array = np.loadtxt(sim_id + \".dat\")\n    pynml.generate_plot([data_array[:, 0]], [data_array[:, 1]], \"Membrane potential (soma seg 0)\", show_plot_already=False, save_figure_to=sim_id + \"_seg0_soma0-v.png\", xaxis=\"time (s)\", yaxis=\"membrane potential (V)\")\n    pynml.generate_plot([data_array[:, 0]], [data_array[:, 2]], \"Membrane potential (soma seg 1)\", show_plot_already=False, save_figure_to=sim_id + \"_seg1_soma0-v.png\", xaxis=\"time (s)\", yaxis=\"membrane potential (V)\")\n    pynml.generate_plot([data_array[:, 0]], [data_array[:, 3]], \"Membrane potential (axon seg 0)\", show_plot_already=False, save_figure_to=sim_id + \"_seg0_axon0-v.png\", xaxis=\"time (s)\", yaxis=\"membrane potential (V)\")\n    pynml.generate_plot([data_array[:, 0]], [data_array[:, 4]], \"Membrane potential (axon seg 1)\", show_plot_already=False, save_figure_to=sim_id + \"_seg1_axon0-v.png\", xaxis=\"time (s)\", yaxis=\"membrane potential (V)\")\n\n\ndef create_olm_network():\n    \"\"\"Create the network\n\n    :returns: name of network nml file\n    \"\"\"\n    net_doc = NeuroMLDocument(id=\"network\",\n                              notes=\"OLM cell network\")\n    net_doc_fn = \"olm_example_net.nml\"\n    net_doc.includes.append(IncludeType(href=create_olm_cell()))\n    # Create a population: convenient to create many cells of the same type\n    pop = Population(id=\"pop0\", notes=\"A population for our cell\",\n                     component=\"olm\", size=1, type=\"populationList\")\n    pop.instances.append(Instance(id=1, location=Location(0., 0., 0.)))\n    # Input\n    pulsegen = PulseGenerator(id=\"pg_olm\", notes=\"Simple pulse generator\", delay=\"100ms\", duration=\"100ms\", amplitude=\"0.08nA\")\n\n    exp_input = ExplicitInput(target=\"pop0[0]\", input=\"pg_olm\")\n\n    net = Network(id=\"single_olm_cell_network\", note=\"A network with a single population\")\n    net_doc.pulse_generators.append(pulsegen)\n    net.explicit_inputs.append(exp_input)\n    net.populations.append(pop)\n    net_doc.networks.append(net)\n\n    pynml.write_neuroml2_file(nml2_doc=net_doc, nml2_file_name=net_doc_fn, validate=True)\n    return net_doc_fn\n\n\ndef create_olm_cell():\n    \"\"\"Create the complete cell.\n\n    :returns: cell object\n    \"\"\"\n    nml_cell_doc = NeuroMLDocument(id=\"oml_cell\")\n    cell = create_cell(\"olm\")\n    nml_cell_file = cell.id + \".cell.nml\"\n\n    # Add two soma segments\n    diam = 10.0\n    soma_0 = add_segment(cell,\n                         prox=[0.0, 0.0, 0.0, diam],\n                         dist=[0.0, 10., 0.0, diam],\n                         name=\"Seg0_soma_0\",\n                         group=\"soma_0\")\n\n    soma_1 = add_segment(cell,\n                         prox=None,\n                         dist=[0.0, 10. + 10., 0.0, diam],\n                         name=\"Seg1_soma_0\",\n                         parent=soma_0,\n                         group=\"soma_0\")\n\n    # Add axon segments\n    diam = 1.5\n    axon_0 = add_segment(cell,\n                         prox=[0.0, 0.0, 0.0, diam],\n                         dist=[0.0, -75, 0.0, diam],\n                         name=\"Seg0_axon_0\",\n                         parent=soma_0,\n                         fraction_along=0.0,\n                         group=\"axon_0\")\n    axon_1 = add_segment(cell,\n                         prox=None,\n                         dist=[0.0, -150, 0.0, diam],\n                         name=\"Seg1_axon_0\",\n                         parent=axon_0,\n                         group=\"axon_0\")\n\n    # Add 2 dendrite segments\n\n    diam = 3.0\n    dend_0_0 = add_segment(cell,\n                           prox=[0.0, 20, 0.0, diam],\n                           dist=[100, 120, 0.0, diam],\n                           name=\"Seg0_dend_0\",\n                           parent=soma_1,\n                           fraction_along=1,\n                           group=\"dend_0\")\n\n    dend_1_0 = add_segment(cell,\n                           prox=None,\n                           dist=[177, 197, 0.0, diam],\n                           name=\"Seg1_dend_0\",\n                           parent=dend_0_0,\n                           fraction_along=1,\n                           group=\"dend_0\")\n\n    dend_0_1 = add_segment(cell,\n                           prox=[0.0, 20, 0.0, diam],\n                           dist=[-100, 120, 0.0, diam],\n                           name=\"Seg0_dend_1\",\n                           parent=soma_1,\n                           fraction_along=1,\n                           group=\"dend_1\")\n    dend_1_1 = add_segment(cell,\n                           prox=None,\n                           dist=[-177, 197, 0.0, diam],\n                           name=\"Seg1_dend_1\",\n                           parent=dend_0_1,\n                           fraction_along=1,\n                           group=\"dend_1\")\n\n    # XXX: For segment groups to be correctly mapped to sections in NEURON,\n    # they must include the correct neurolex ID\n    for section_name in [\"soma_0\", \"axon_0\", \"dend_0\", \"dend_1\"]:\n        section_group = get_seg_group_by_id(section_name, cell)\n        section_group.neuro_lex_id = 'sao864921383'\n\n    den_seg_group = get_seg_group_by_id(\"dendrite_group\", cell)\n    den_seg_group.includes.append(Include(segment_groups=\"dend_0\"))\n    den_seg_group.includes.append(Include(segment_groups=\"dend_1\"))\n    den_seg_group.properties.append(Property(tag=\"color\", value=\"0.8 0 0\"))\n\n    ax_seg_group = get_seg_group_by_id(\"axon_group\", cell)\n    ax_seg_group.includes.append(Include(segment_groups=\"axon_0\"))\n    ax_seg_group.properties.append(Property(tag=\"color\", value=\"0 0.8 0\"))\n\n    soma_seg_group = get_seg_group_by_id(\"soma_group\", cell)\n    soma_seg_group.includes.append(Include(segment_groups=\"soma_0\"))\n\n    soma_seg_group.properties.append(Property(tag=\"color\", value=\"0 0 0.8\"))\n\n    # Other cell properties\n    set_init_memb_potential(cell, \"-67mV\")\n    set_resistivity(cell, \"0.15 kohm_cm\")\n    set_specific_capacitance(cell, \"1.3 uF_per_cm2\")\n\n    # channels\n    # leak\n    add_channel_density(cell, nml_cell_doc,\n                        cd_id=\"leak_all\",\n                        cond_density=\"0.01 mS_per_cm2\",\n                        ion_channel=\"leak_chan\",\n                        ion_chan_def_file=\"olm-example/leak_chan.channel.nml\",\n                        erev=\"-67mV\",\n                        ion=\"non_specific\")\n    # HCNolm_soma\n    add_channel_density(cell, nml_cell_doc,\n                        cd_id=\"HCNolm_soma\",\n                        cond_density=\"0.5 mS_per_cm2\",\n                        ion_channel=\"HCNolm\",\n                        ion_chan_def_file=\"olm-example/HCNolm.channel.nml\",\n                        erev=\"-32.9mV\",\n                        ion=\"h\",\n                        group=\"soma_group\")\n    # Kdrfast_soma\n    add_channel_density(cell, nml_cell_doc,\n                        cd_id=\"Kdrfast_soma\",\n                        cond_density=\"73.37 mS_per_cm2\",\n                        ion_channel=\"Kdrfast\",\n                        ion_chan_def_file=\"olm-example/Kdrfast.channel.nml\",\n                        erev=\"-77mV\",\n                        ion=\"k\",\n                        group=\"soma_group\")\n    # Kdrfast_dendrite\n    add_channel_density(cell, nml_cell_doc,\n                        cd_id=\"Kdrfast_dendrite\",\n                        cond_density=\"105.8 mS_per_cm2\",\n                        ion_channel=\"Kdrfast\",\n                        ion_chan_def_file=\"olm-example/Kdrfast.channel.nml\",\n                        erev=\"-77mV\",\n                        ion=\"k\",\n                        group=\"dendrite_group\")\n    # Kdrfast_axon\n    add_channel_density(cell, nml_cell_doc,\n                        cd_id=\"Kdrfast_axon\",\n                        cond_density=\"117.392 mS_per_cm2\",\n                        ion_channel=\"Kdrfast\",\n                        ion_chan_def_file=\"olm-example/Kdrfast.channel.nml\",\n                        erev=\"-77mV\",\n                        ion=\"k\",\n                        group=\"axon_group\")\n    # KvAolm_soma\n    add_channel_density(cell, nml_cell_doc,\n                        cd_id=\"KvAolm_soma\",\n                        cond_density=\"4.95 mS_per_cm2\",\n                        ion_channel=\"KvAolm\",\n                        ion_chan_def_file=\"olm-example/KvAolm.channel.nml\",\n                        erev=\"-77mV\",\n                        ion=\"k\",\n                        group=\"soma_group\")\n    # KvAolm_dendrite\n    add_channel_density(cell, nml_cell_doc,\n                        cd_id=\"KvAolm_dendrite\",\n                        cond_density=\"2.8 mS_per_cm2\",\n                        ion_channel=\"KvAolm\",\n                        ion_chan_def_file=\"olm-example/KvAolm.channel.nml\",\n                        erev=\"-77mV\",\n                        ion=\"k\",\n                        group=\"dendrite_group\")\n    # Nav_soma\n    add_channel_density(cell, nml_cell_doc,\n                        cd_id=\"Nav_soma\",\n                        cond_density=\"10.7 mS_per_cm2\",\n                        ion_channel=\"Nav\",\n                        ion_chan_def_file=\"olm-example/Nav.channel.nml\",\n                        erev=\"50mV\",\n                        ion=\"na\",\n                        group=\"soma_group\")\n    # Nav_dendrite\n    add_channel_density(cell, nml_cell_doc,\n                        cd_id=\"Nav_dendrite\",\n                        cond_density=\"23.4 mS_per_cm2\",\n                        ion_channel=\"Nav\",\n                        ion_chan_def_file=\"olm-example/Nav.channel.nml\",\n                        erev=\"50mV\",\n                        ion=\"na\",\n                        group=\"dendrite_group\")\n    # Nav_axon\n    add_channel_density(cell, nml_cell_doc,\n                        cd_id=\"Nav_axon\",\n                        cond_density=\"17.12 mS_per_cm2\",\n                        ion_channel=\"Nav\",\n                        ion_chan_def_file=\"olm-example/Nav.channel.nml\",\n                        erev=\"50mV\",\n                        ion=\"na\",\n                        group=\"axon_group\")\n\n    nml_cell_doc.cells.append(cell)\n    pynml.write_neuroml2_file(nml_cell_doc, nml_cell_file, True, True)\n    return nml_cell_file\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "210c5e0f64da50f751e59116f416e820c2cee416", "size": 13412, "ext": "py", "lang": "Python", "max_stars_repo_path": "source/Userdocs/NML2_examples/olm-example.py", "max_stars_repo_name": "NeuroML/Documentation", "max_stars_repo_head_hexsha": "06e355a8268c848b872b4e4c44d990b77b1fcb37", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-09-28T20:47:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-23T16:46:30.000Z", "max_issues_repo_path": "source/Userdocs/NML2_examples/olm-example.py", "max_issues_repo_name": "NeuroML/Documentation", "max_issues_repo_head_hexsha": "06e355a8268c848b872b4e4c44d990b77b1fcb37", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 86, "max_issues_repo_issues_event_min_datetime": "2020-11-05T12:32:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:45:00.000Z", "max_forks_repo_path": "source/Userdocs/NML2_examples/olm-example.py", "max_forks_repo_name": "NeuroML/Documentation", "max_forks_repo_head_hexsha": "06e355a8268c848b872b4e4c44d990b77b1fcb37", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-23T16:46:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T00:43:11.000Z", "avg_line_length": 43.264516129, "max_line_length": 218, "alphanum_fraction": 0.5378019684, "include": true, "reason": "import numpy", "num_tokens": 3252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.17299967809818956}}
{"text": "#!/usr/bin/env python\n# coding: utf8\n#\n# Copyright (c) 2020 Centre National d'Etudes Spatiales (CNES).\n#\n# This file is part of PANDORA\n#\n#     https://github.com/CNES/Pandora\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\"\"\"\nThis module contains functions associated to the Cross Based Cost Aggregation (cbca) method.\n\"\"\"\n\nfrom typing import Dict, Union, Tuple, List\n\nimport numpy as np\nimport xarray as xr\nfrom json_checker import Checker, And\nfrom numba import njit\n\nfrom pandora.filter import AbstractFilter\nfrom pandora.img_tools import shift_right_img\nfrom . import aggregation\n\n\n@aggregation.AbstractAggregation.register_subclass(\"cbca\")\nclass CrossBasedCostAggregation(aggregation.AbstractAggregation):\n    \"\"\"\n    CrossBasedCostAggregation class, allows to perform the aggregation step\n    \"\"\"\n\n    # Default configuration, do not change these values\n    _CBCA_INTENSITY = 30.0\n    _CBCA_DISTANCE = 5\n\n    def __init__(self, **cfg: dict):\n        \"\"\"\n        :param cfg: optional configuration, {'cbca_intensity': value, 'cbca_distance': value}\n        :type cfg: dict\n        \"\"\"\n        self.cfg = self.check_conf(**cfg)  # type: ignore\n        self._cbca_intensity = self.cfg[\"cbca_intensity\"]\n        self._cbca_distance = self.cfg[\"cbca_distance\"]\n\n    def check_conf(self, **cfg: Union[str, float, int]) -> Dict[str, Union[str, float, int]]:\n        \"\"\"\n        Add default values to the dictionary if there are missing elements and check if the dictionary is correct\n\n        :param cfg: aggregation configuration\n        :type cfg: dict\n        :return cfg: aggregation configuration updated\n        :rtype: dict\n        \"\"\"\n        # Give the default value if the required element is not in the configuration\n        if \"cbca_intensity\" not in cfg:\n            cfg[\"cbca_intensity\"] = self._CBCA_INTENSITY\n        if \"cbca_distance\" not in cfg:\n            cfg[\"cbca_distance\"] = self._CBCA_DISTANCE\n\n        schema = {\n            \"aggregation_method\": And(str, lambda input: \"cbca\"),\n            \"cbca_intensity\": And(float, lambda input: input > 0),\n            \"cbca_distance\": And(int, lambda input: input > 0),\n        }\n\n        checker = Checker(schema)\n        checker.validate(cfg)\n        return cfg\n\n    def desc(self):\n        \"\"\"\n        Describes the aggregation method\n        \"\"\"\n        print(\"CrossBasedCostAggregation method\")\n\n    def cost_volume_aggregation(\n        self, img_left: xr.Dataset, img_right: xr.Dataset, cv: xr.Dataset, **cfg: Union[str, int]\n    ) -> None:\n        \"\"\"\n        Aggregated the cost volume with Cross-Based Cost Aggregation, using the pipeline define in\n        Zhang, K., Lu, J., & Lafruit, G. (2009).\n        Cross-based local stereo matching using orthogonal integral images.\n        IEEE transactions on circuits and systems for video technology, 19(7), 1073-1079.\n\n        :param img_left: left Dataset image containing :\n\n                - im : 2D (row, col) xarray.DataArray\n                - msk (optional): 2D (row, col) xarray.DataArray\n        :type img_left: xarray.Dataset\n        :param img_right: right Dataset image containing :\n\n                - im : 2D (row, col) xarray.DataArray\n                - msk (optional): 2D (row, col) xarray.DataArray\n        :type img_right: xarray.Dataset\n        :param cv: cost volume dataset with the data variables:\n\n                - cost_volume 3D xarray.DataArray (row, col, disp)\n                - confidence_measure 3D xarray.DataArray (row, col, indicator)\n        :type cv: xarray.Dataset\n        :param cfg: images configuration containing the mask convention : valid_pixels, no_data\n        :type cfg: dict\n        :return: None\n        \"\"\"\n        cross_left, cross_right = self.computes_cross_supports(img_left, img_right, cv)\n\n        offset = int(cv.attrs[\"offset_row_col\"])\n        # Cost volume has input image size, if offset > 0 do not consider the marge\n        if offset > 0:\n            cv_data = cv[\"cost_volume\"].data[offset:-offset, offset:-offset]\n        else:\n            cv_data = cv[\"cost_volume\"].data\n        n_col_, n_row_, nb_disp = cv_data.shape\n\n        # Allocate the numpy aggregated cost volume cv = (disp, col, row), for efficient memory management\n        agg = np.zeros((nb_disp, n_row_, n_col_), dtype=np.float32)\n\n        # Add invalid costs (i.e = np.nan ) to the output aggregated cost volume (because the step 1 of cbca do not\n        # propagate invalid pixels, we need to retrieve them at the end of aggregation )\n        # Much faster than :\n        # id_nan = np.isnan(cv['cost_volume'].data)\n        # compute the aggregation ..\n        # cv['cost_volume'].data[id_nan] = np.nan\n        agg += np.swapaxes(cv_data, 0, 2)\n        agg *= 0\n\n        disparity_range = cv.coords[\"disp\"].data\n        range_col = np.arange(0, n_row_)\n\n        for dsp in range(nb_disp):\n            i_right = int((disparity_range[dsp] % 1) * cv.attrs[\"subpixel\"])\n\n            # Step 1 : horizontal integral image\n            step1 = cbca_step_1(cv_data[:, :, dsp])\n\n            range_col_right = range_col + disparity_range[dsp]\n            valid_index = np.where((range_col_right >= 0) & (range_col_right < cross_right[i_right].shape[1]))\n\n            # Step 2 : horizontal matching cost\n            step2, sum2 = cbca_step_2(\n                step1,\n                cross_left,\n                cross_right[i_right],\n                range_col[valid_index],\n                range_col_right[valid_index].astype(int),\n            )\n\n            # Step 3 : vertical integral image\n            step3 = cbca_step_3(step2)\n\n            # Step 4 : aggregate cost volume\n            step4, sum4 = cbca_step_4(\n                step3,\n                sum2,\n                cross_left,\n                cross_right[i_right],\n                range_col[valid_index],\n                range_col_right[valid_index].astype(int),\n            )\n\n            # Added the pixel anchor pixel to the number of support pixels used during the aggregation\n            sum4 += 1\n            # Add the aggregate cost to the output\n            agg[dsp, :, :] += np.swapaxes(step4, 0, 1)\n            # Normalize the aggregated cost\n            agg[dsp, :, :] /= np.swapaxes(sum4, 0, 1)\n\n        cv_data = np.swapaxes(agg, 0, 2)\n        if offset > 0:\n            cv[\"cost_volume\"].data[offset:-offset, offset:-offset] = cv_data\n        else:\n            cv[\"cost_volume\"].data = cv_data\n        cv.attrs[\"aggregation\"] = \"cbca\"\n\n        # Maximal cost of the cost volume after agregation\n        cmax = cv.attrs[\"cmax\"] * ((self._cbca_distance * 2) - 1) ** 2  # type: ignore\n        cv.attrs[\"cmax\"] = cmax\n\n    def computes_cross_supports(\n        self, img_left: xr.Dataset, img_right: xr.Dataset, cv: xr.Dataset\n    ) -> Tuple[np.ndarray, List[np.ndarray]]:\n        \"\"\"\n        Prepare images and compute the cross support region of the left and right images.\n        A 3x3 median filter is applied to the images before calculating the cross support region.\n\n        :param img_left: left Dataset image containing :\n\n                - im : 2D (row, col) xarray.DataArray\n                - msk (optional): 2D (row, col) xarray.DataArray\n        :type img_left: xarray.Dataset\n        :param img_right: right Dataset image containing :\n\n                - im : 2D (row, col) xarray.DataArray\n                - msk (optional): 2D (row, col) xarray.DataArray\n        :type img_right: xarray.Dataset\n        :param cv: cost volume dataset with the data variables:\n\n                - cost_volume 3D xarray.DataArray (row, col, disp)\n                - confidence_measure 3D xarray.DataArray (row, col, indicator)\n        :type cv: xarray.Dataset\n        :return: the left and right cross support region\n        :rtype: Tuples(left cross support region, List(right cross support region))\n        \"\"\"\n        subpix = cv.attrs[\"subpixel\"]\n        offset = int(cv.attrs[\"offset_row_col\"])\n\n        # shift the right image\n        img_right_shift = shift_right_img(img_right, subpix)\n\n        # Median filter on valid pixels\n        filter_ = AbstractFilter(**{\"filter_method\": \"median\", \"filter_size\": 3})  # type: ignore\n\n        # Invalid and no data pixels are masked with np.nan to avoid propagating the values with the median filter\n        left_masked = np.copy(img_left[\"im\"].data)\n        if \"msk\" in img_left.data_vars:\n            left_masked[np.where(img_left[\"msk\"].data != img_left.attrs[\"valid_pixels\"])] = np.nan\n\n        left_masked = filter_.median_filter(left_masked)  # type: ignore\n        # Convert nan to inf to be able to use the comparison operators < and > in cross_support function\n        np.nan_to_num(left_masked, copy=False, nan=np.inf)\n        # Compute left cross support using numba to reduce running time\n        if offset != 0:\n            # Cross support to the size of the cost volume\n            cross_left = cross_support(\n                left_masked[offset:-offset, offset:-offset],\n                self._cbca_distance,\n                self._cbca_intensity,\n            )\n        else:\n            cross_left = cross_support(left_masked, self._cbca_distance, self._cbca_intensity)\n\n        # Compute the right cross support. Apply a 3×3 median filter to the input image\n        cross_right = []\n        for shift, img in enumerate(img_right_shift):\n            # Invalid and nodata pixels are masked with np.nan to avoid propagating the values with the median filter\n            right_masked = np.copy(img[\"im\"].data)\n\n            # Pixel precision\n            if (\"msk\" in img_right.data_vars) and (shift == 0):\n                right_masked[np.where(img_right[\"msk\"].data != img_right.attrs[\"valid_pixels\"])] = np.nan\n\n            # Subpixel precision : computes the shifted right mask\n            if (\"msk\" in img_right.data_vars) and (shift != 0):\n                shift_mask = np.zeros(img_right[\"msk\"].data.shape)\n                shift_mask[np.where(img_right[\"msk\"].data != img_right.attrs[\"valid_pixels\"])] = np.nan\n\n                # Since the interpolation of the right image is of order 1, the shifted right mask corresponds\n                # to an aggregation of two columns of the right mask\n\n                # Create a sliding window of shape 2 using as_strided function : this function create a new a view (by\n                # manipulating data pointer)of the shift_mask array with a different shape. The new view pointing to the\n                # same memory block as shift_mask so it does not consume any additional memory.\n                (  # pylint: disable=unpacking-non-sequence\n                    str_row,\n                    str_col,\n                ) = shift_mask.strides\n                shape_windows = (shift_mask.shape[0], shift_mask.shape[1] - 1, 2)\n                strides_windows = (str_row, str_col, str_col)\n                aggregation_window = np.lib.stride_tricks.as_strided(\n                    shift_mask, shape_windows, strides_windows, writeable=False\n                )\n                shift_mask = np.sum(aggregation_window, 2)\n                right_masked += shift_mask\n\n            #  Apply a 3×3 median filter to the input image\n            right_masked = filter_.median_filter(right_masked)  # type: ignore\n            # Convert nan to inf to be able to use the comparison operators < and > in cross_support function\n            np.nan_to_num(right_masked, copy=False, nan=np.inf)\n            # Compute right cross support using numba to reduce running time\n            if offset != 0:\n                # Cross support to the size of the cost volume\n                cross_right.append(\n                    cross_support(\n                        right_masked[offset:-offset, offset:-offset],\n                        self._cbca_distance,\n                        self._cbca_intensity,\n                    )\n                )\n            else:\n                cross_right.append(cross_support(right_masked, self._cbca_distance, self._cbca_intensity))\n\n        return cross_left, cross_right\n\n\n@njit(\"f4[:, :](f4[:, :])\", cache=True)\ndef cbca_step_1(cv: np.ndarray) -> np.ndarray:\n    \"\"\"\n    Giving the matching cost for one disparity, build a horizontal integral image storing the cumulative row sum,\n    S_h(row, col) = S_h(row-1, col) + cv(row, col)\n\n    :param cv: cost volume for the current disparity\n    :type cv: 2D np.array (row, col) dtype = np.float32\n    :return: the horizontal integral image, step 1\n    :rtype: 2D np.array (row, col + 1) dtype = np.float32\n    \"\"\"\n    n_col_, n_row_ = cv.shape\n    # Allocate the intermediate cost volume S_h\n    # added a column to manage the case in the step 2 : row - left_arm_length -1 = -1\n    step1 = np.zeros((n_col_, n_row_ + 1), dtype=np.float32)\n\n    for col in range(n_col_):\n        for row in range(n_row_):\n            # Do not propagate nan\n            if not np.isnan(cv[col, row]):\n                step1[col, row] = step1[col, row - 1] + cv[col, row]\n            else:\n                step1[col, row] = step1[col, row - 1]\n\n    return step1\n\n\n@njit(\"(f4[:, :], i2[:, :, :], i2[:, :, :], i8[:], i8[:])\", cache=True)\ndef cbca_step_2(\n    step1: np.ndarray,\n    cross_left: np.ndarray,\n    cross_right: np.ndarray,\n    range_col: np.ndarray,\n    range_col_right: np.ndarray,\n) -> Tuple[np.ndarray, np.ndarray]:\n    \"\"\"\n    Giving the horizontal integral image, computed the horizontal matching cost for one disparity,\n    E_h(row, col) = S_h(row + right_arm_length, col) - S_h(row - left_arm_length -1, col)\n\n    :param step1: horizontal integral image, from the cbca_step1, with an extra column that contains 0\n    :type step1: 2D np.array (row, col + 1) dtype = np.float32\n    :param cross_left: cross support of the left image\n    :type cross_left: 3D np.array (row, col, [left, right, top, bot]) dtype=np.int16\n    :param cross_right: cross support of the right image\n    :type cross_right: 3D np.array (row, col, [left, right, tpo, bot]) dtype=np.int16\n    :param range_col: left column for the current disparity (i.e : np.arrange(nb columns), where the correspondent \\\n    in the right image is reachable)\n    :type range_col: 1D np.array\n    :param range_col_right: right column for the current disparity (i.e : np.arrange(nb columns) - disparity, where \\\n    column - disparity >= 0 and <= nb columns)\n    :type range_col_right: 1D np.array\n    :return: the horizontal matching cost for the current disparity, and the number of support pixels used for the \\\n    step 2\n    :rtype: tuple (2D np.array (row, col) dtype = np.float32, 2D np.array (row, col) dtype = np.float32)\n    \"\"\"\n    n_col_, n_row_ = step1.shape\n    # Allocate the intermediate cost volume E_h\n    # , remove the extra column from the step 1\n    step2 = np.zeros((n_col_, n_row_ - 1), dtype=np.float32)\n    sum_step2 = np.zeros((n_col_, n_row_ - 1), dtype=np.float32)\n\n    for col in range(step1.shape[0]):\n        for row in range(range_col.shape[0]):\n            right = min(\n                cross_left[col, range_col[row], 1],\n                cross_right[col, range_col_right[row], 1],\n            )\n            left = min(\n                cross_left[col, range_col[row], 0],\n                cross_right[col, range_col_right[row], 0],\n            )\n            step2[col, range_col[row]] = step1[col, range_col[row] + right] - step1[col, range_col[row] - left - 1]\n            sum_step2[col, range_col[row]] += right + left\n\n    return step2, sum_step2\n\n\n@njit(\"f4[:, :](f4[:, :])\", cache=True)\ndef cbca_step_3(step2: np.ndarray) -> np.ndarray:\n    \"\"\"\n    Giving the horizontal matching cost, build a vertical integral image for one disparity,\n    S_v = S_v(row, col - 1) + E_h(row, col)\n\n    :param step2: horizontal matching cost, from the cbca_step2\n    :type step2: 3D xarray.DataArray (row, col, disp)\n    :return: the vertical integral image for the current disparity\n    :rtype: 2D np.array (row + 1, col) dtype = np.float32\n    \"\"\"\n    n_col_, n_row_ = step2.shape\n    # Allocate the intermediate cost volume S_v\n    # added a row to manage the case in the step 4 : col - up_arm_length -1 = -1\n    step3 = np.zeros((n_col_ + 1, n_row_), dtype=np.float32)\n    step3[0, :] = step2[0, :]\n\n    for col in range(1, n_col_):\n        for row in range(n_row_):\n            step3[col, row] = step3[col - 1, row] + step2[col, row]\n\n    return step3\n\n\n@njit(\"(f4[:, :], f4[:, :], i2[:, :, :], i2[:, :, :], i8[:], i8[:])\", cache=True)\ndef cbca_step_4(\n    step3: np.ndarray,\n    sum2: np.ndarray,\n    cross_left: np.ndarray,\n    cross_right: np.ndarray,\n    range_col: np.ndarray,\n    range_col_right: np.ndarray,\n) -> Tuple[np.ndarray, np.ndarray]:\n    \"\"\"\n    Giving the vertical integral image, build the fully aggregated matching cost for one disparity,\n    E = S_v(row, col + bottom_arm_length) - S_v(row, col - top_arm_length - 1)\n\n    :param step3: vertical integral image, from the cbca_step3, with an extra row that contains 0\n    :type step3: 2D np.array (row + 1, col) dtype = np.float32\n    :param sum2: the number of support pixels used for the step 2\n    :type sum2: 2D np.array (row, col) dtype = np.float32\n    :param cross_left: cross support of the left image\n    :type cross_left: 3D np.array (row, col, [left, right, top, bot]) dtype=np.int16\n    :param cross_right: cross support of the right image\n    :type cross_right: 3D np.array (row, col, [left, right, tpo, bot]) dtype=np.int16\n    :param range_col: left column for the current disparity (i.e : np.arrange(nb columns), where the correspondent \\\n    in the right image is reachable)\n    :type range_col: 1D np.array\n    :param range_col_right: right column for the current disparity (i.e : np.arrange(nb columns) - disparity, where \\\n    column - disparity >= 0 and <= nb columns)\n    :type range_col_right: 1D np.array\n    :return: the fully aggregated matching cost, and the total number of support pixels used for the aggregation\n    :rtype: tuple(2D np.array (row , col) dtype = np.float32, 2D np.array (row , col) dtype = np.float32)\n    \"\"\"\n    n_col_, n_row_ = step3.shape\n    # Allocate the final cost volume E\n    # , remove the extra row from the step 3\n    step4 = np.zeros((n_col_ - 1, n_row_), dtype=np.float32)\n    sum4 = np.copy(sum2)\n    for col in range(step4.shape[0]):\n        for row in range(range_col.shape[0]):\n            top = min(\n                cross_left[col, range_col[row], 2],\n                cross_right[col, range_col_right[row], 2],\n            )\n            bot = min(\n                cross_left[col, range_col[row], 3],\n                cross_right[col, range_col_right[row], 3],\n            )\n\n            step4[col, range_col[row]] = step3[col + bot, range_col[row]] - step3[col - top - 1, range_col[row]]\n\n            sum4[col, range_col[row]] += top + bot\n            if top != 0:\n                sum4[col, range_col[row]] += np.sum(sum2[col - top : col, range_col[row]])\n            if bot != 0:\n                sum4[col, range_col[row]] += np.sum(sum2[col + 1 : col + bot + 1, range_col[row]])\n\n    return step4, sum4\n\n\n@njit(\"i2[:, :, :](f4[:, :], i2, f4)\", cache=True)\ndef cross_support(image: np.ndarray, len_arms: int, intensity: float) -> np.ndarray:\n    \"\"\"\n    Compute the cross support for an image: find the 4 arms.\n    Enforces a minimum support region of 3×3 if pixels are valid.\n    The cross support of invalid pixels (pixels that are np.inf) is 0 for the 4 arms.\n\n    :param image: image\n    :type image: 2D np.array (row , col) dtype = np.float32\n    :param len_arms: maximal length arms\n    :param len_arms: int16\n    :param intensity: maximal intensity\n    :param intensity: float 32\n    :return: a 3D np.array ( row, col, [left, right, top, bot] ), with the four arms lengths computes for each pixel\n    :rtype:  3D np.array ( row, col, [left, right, top, bot] ), dtype=np.int16\n    \"\"\"\n    n_col_, n_row_ = image.shape\n    # By default, all cross supports are 0\n    cross = np.zeros((n_col_, n_row_, 4), dtype=np.int16)\n\n    for col in range(n_col_):\n        for row in range(n_row_):\n\n            # If the pixel is valid (np.isfinite = True) compute the cross support\n            # Else (np.isfinite = False) the pixel is not valid (no data or invalid) and the cross support value is 0\n            # for the 4 arms (default value of the variable cross).\n            if np.isfinite(image[col, row]):\n                left_len = 0\n                left = row\n                for left in range(row - 1, max(row - len_arms, -1), -1):\n                    if abs(image[col, row] - image[col, left]) >= intensity:\n                        break\n                    left_len += 1\n                # enforces a minimum support region of 3×3 if pixels are valid\n                cross[col, row, 0] = max(left_len, 1 * (row >= 1) * np.isfinite(image[col, left]))\n\n                right_len = 0\n                right = row\n                for right in range(row + 1, min(row + len_arms, n_row_)):\n                    if abs(image[col, row] - image[col, right]) >= intensity:\n                        break\n                    right_len += 1\n                # enforces a minimum support region of 3×3 if pixels are valid\n                cross[col, row, 1] = max(right_len, 1 * (row < n_row_ - 1) * np.isfinite(image[col, right]))\n\n                up_len = 0\n                up_col = col\n                for up_col in range(col - 1, max(col - len_arms, -1), -1):\n                    if abs(image[col, row] - image[up_col, row]) >= intensity:\n                        break\n                    up_len += 1\n                # enforces a minimum support region of 3×3 if pixels are valid\n                cross[col, row, 2] = max(up_len, 1 * (col >= 1) * np.isfinite(image[up_col, row]))\n\n                bot_len = 0\n                bot = col\n                for bot in range(col + 1, min(col + len_arms, n_col_)):\n                    if abs(image[col, row] - image[bot, row]) >= intensity:\n                        break\n                    bot_len += 1\n                # enforces a minimum support region of 3×3 if pixels are valid\n                cross[col, row, 3] = max(bot_len, 1 * (col < n_col_ - 1) * np.isfinite(image[bot, row]))\n\n    return cross\n", "meta": {"hexsha": "cb342d11de28e4aad9c91e4910c89a769d5c3fcd", "size": 22601, "ext": "py", "lang": "Python", "max_stars_repo_path": "pandora/aggregation/cbca.py", "max_stars_repo_name": "njimenezd/Pandora", "max_stars_repo_head_hexsha": "9e3c2054415301edac6da7510056af0136790277", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2020-09-18T14:12:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T15:12:16.000Z", "max_issues_repo_path": "pandora/aggregation/cbca.py", "max_issues_repo_name": "qfardet/Pandora", "max_issues_repo_head_hexsha": "67c23134844e5468ca529f1c605f540035fe57c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-01-14T18:43:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T08:00:43.000Z", "max_forks_repo_path": "pandora/aggregation/cbca.py", "max_forks_repo_name": "qfardet/Pandora", "max_forks_repo_head_hexsha": "67c23134844e5468ca529f1c605f540035fe57c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-01-25T17:03:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T08:14:49.000Z", "avg_line_length": 43.6312741313, "max_line_length": 120, "alphanum_fraction": 0.6075837352, "include": true, "reason": "import numpy,from numba", "num_tokens": 5721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.1729996746854528}}
{"text": "import numpy\nimport struct\nimport warnings\n\nfrom .compat import structured_cast\n# from .logger import logger\nfrom ..lib.arraybase import set_or_add_to_structured, to_structured\nfrom ..lib.iterable import split\n\ntry:\n    import xxhash\n    _HAS_XXHASH = True\nexcept ImportError:\n    _HAS_XXHASH = False\n    import hashlib\n\n# Pure numpy implementation of hashmaps\n# This file implements low level classes, but as a user you should try to use:\n#    unique, unique_count, search, get_dense_labels_map, factorize or Hashmap\n\nUINT64 = numpy.uint64\nINV_PHI = UINT64(11400714819323198485)  # 1<<64/phi\nSTEP_MULT = UINT64(11223344556677889999)  # arbitrary, could be optimized\n_DEFAULT = object()\n\n\nclass _BaseHashmap(object):\n    \"\"\"\n    template for HashMap keys => values\n\n    * hashmaps gives efficient O(n) search in un-sorted set of keys or map keys => values\n    * hashmaps without values are called hashtables\n    * this implementation relies on Fibonacci hashing\n    * we support any dtype for the keys and values, by implementing these sub-classes:\n    * - vanilla hash for uint64 keys\n    * - python's tuple-hash for struct of uint64 fields\n    * - xxhash or sha1 for bytes objects (or encoded str objects), or struct of them\n    * - python's object hash for any object\n    * for the first two, the keys are casted into uint64 or uint64-tuple\n    * when possible for struct of a few tiny field, we view them as a single uint64\n    \"\"\"\n\n    @classmethod\n    def new(cls, keys, values=None, cast_dtype=None, view_dtype=None, empty=_DEFAULT):\n        \"\"\"\n        :param array keys: (n,) key-dtype array\n        :param array? values: (n,) val-dtype array\n        :param dtype? cast_dtype: dtype to cast ``keys``\n        :param dtype? view_dtype: dtype to view ``keys``\n        :param int? empty: empty value (default: 0)\n        \"\"\"\n        original_dtype = keys.dtype\n        cast_dtype = numpy.dtype(cast_dtype or keys.dtype)\n        view_dtype = numpy.dtype(view_dtype or keys.dtype)\n        _keys = cls._cast(keys, cast_dtype, view_dtype)\n        # keys = structured_cast(keys, dtype)\n        empty = cls._choose_empty_value(_keys, view_dtype, empty)\n        n, = _keys.shape\n        log_size = (cls.init_space_ratio(n) * n - 1).bit_length()\n        size = 1 << log_size\n        table = numpy.full(size, empty, dtype=view_dtype)\n        values_table = numpy.zeros(\n            size, dtype=values.dtype) if values is not None else None\n        hashmap = cls(table, values_table, empty,\n                      log_size, original_dtype, cast_dtype)\n        hashmap._set_initial(_keys, values)\n        return hashmap\n\n    def __init__(self, table, values, empty, log_size, original_dtype, cast_dtype, can_resize=True):\n        \"\"\" low-level constructor, use .new instead \"\"\"\n        self._table = table\n        self.values = values\n        self._empty = empty\n        self.log_size = log_size\n        self.can_resize = can_resize\n        self.shift = UINT64(64 - self.log_size)\n        self.n_used = (self._table != self._empty).sum()\n        self.original_dtype = original_dtype\n        self.cast_dtype = cast_dtype\n\n    @property\n    def size(self):\n        return self._table.size\n\n    @property\n    def nbytes(self):\n        summed = self._table.nbytes\n        if self.values is not None:\n            summed += self.values.nbytes\n        return summed\n\n    def set_many(self, keys, values=None):\n        \"\"\"\n        :param array keys: (n,) key-dtype array\n        :param array? values: (n,) val-dtype array\n        \"\"\"\n        _keys = self._cast(keys, self.cast_dtype, self._table.dtype)\n        if values is not None and self.values.dtype.names:\n            # align fields\n            values = values[[k for k in self.values.dtype.names]]\n        if _keys.size > 0 and (_keys == self._empty).any():\n            self._change_empty(_keys)\n        n, = _keys.shape\n        if self.min_space_ratio(n) * (self.n_used + n) > self.size:\n            self._resize(self.n_used + n)\n        # step=0\n        step = UINT64(0)\n        indexes = self._shifted_hash(_keys, step)\n        done = False\n        max_steps = self.max_steps(n)\n        for _ in range(max_steps):\n            available = self._table[indexes] == self._empty\n            available_indexes = indexes[available]\n            self._table[available_indexes] = _keys[available]\n            collisions = self._table[indexes] != _keys\n            if values is not None:\n                self.values[indexes[~collisions]] = values[~collisions]\n            if not collisions.any():\n                done = True\n                break\n            # next step: work only in `collisions`\n            step += UINT64(1)\n            _keys = _keys[collisions]\n            if values is not None:\n                values = values[collisions]\n            indexes = self._shifted_hash(_keys, step)\n        if not done:\n            raise RuntimeError(f'could not set_many within {max_steps} steps')\n        self.n_used = (self._table != self._empty).sum()\n\n    def lookup(self, keys):\n        \"\"\"\n        Search keys in hashtable (do not confuse with ``get_many`` of hashmap)\n        :param array keys: (n,) key-dtype array\n        :returns: tuple(\n            indexes: (n,) uint64 array,\n            found: (n,) bool array,\n        )\n        \"\"\"\n        _keys = self._cast(keys, self.cast_dtype, self._table.dtype)\n        if _keys.size > 0 and (_keys == self._empty).any():\n            self._change_empty(_keys)\n        n, = _keys.shape\n        # working idx in all (lazy build at first collisions)\n        idx_in_all = None\n        # step=0\n        step = UINT64(0)\n        all_indexes = self._shifted_hash(_keys, step)\n        indexes = all_indexes\n        table_values = self._table[indexes]\n        all_found = table_values != self._empty\n        found = all_found\n        done = False\n        max_steps = self.max_steps(n)\n        for _ in range(max_steps):\n            collisions = found & (table_values != _keys)\n            if not collisions.any():\n                done = True\n                break\n            # next step: work only in `collisions`\n            step += UINT64(1)\n            _keys = _keys[collisions]\n            if idx_in_all is None:\n                idx_in_all = numpy.where(collisions)[0]\n            else:\n                idx_in_all = idx_in_all[collisions]\n            indexes = self._shifted_hash(_keys, step)\n            all_indexes[idx_in_all] = indexes\n            table_values = self._table[indexes]\n            found = table_values != self._empty\n            all_found[idx_in_all] = found\n        if not done:\n            raise RuntimeError(f'could not lookup within {max_steps} steps')\n        return all_indexes, all_found\n\n    def contains(self, keys):\n        \"\"\"\n        :param array keys: (n,) key-dtype array\n        :returns: (n,) bool array\n        \"\"\"\n        _, found = self.lookup(keys)\n        return found\n\n    def get_many(self, keys):\n        \"\"\"\n        :param array keys: (n,) key-dtype array\n        :returns: tuple(\n            values: (n,) val-dtype array,\n            found: (n,) bool array,\n        )\n        \"\"\"\n        if self.values is None:\n            raise ValueError(\n                '`get_many` is only available when values is not None, use `lookup`')\n        indexes, found = self.lookup(keys)\n        values = self.values[indexes]\n        return values, found\n\n    def unique_keys(self, return_table_mask=False, return_values=False):\n        \"\"\" :returns: (\n            (n,) key-dtype array,\n            [if return_table_mask] (m,) bool array with n \"1s\"\n            [if return_values] (n,) val-dtype array,\n        )\n         \"\"\"\n        has_key = self._table != self._empty\n        _keys = self._table[has_key]\n        keys = self._cast_back(_keys)\n        if not return_table_mask and not return_values:\n            return keys\n        out = (keys,)\n        if return_table_mask:\n            out = out + (has_key,)\n        if return_values:\n            out = out + (self.values[has_key],)\n        return out\n\n    def keys_hash(self):\n        \"\"\" returns order-invarient hash of keys (not __hash__ because we don't look at values) \"\"\"\n        # combine raw hash (pre-shift) by global sum\n        has_key = self._table != self._empty\n        _keys = self._table[has_key]\n        # compute raw uint64 hash\n        _keys_hsh = self._hash(_keys, UINT64(0))\n        # aggregate\n        hsh_uint64 = numpy.bitwise_xor.reduce(_keys_hsh)\n        return int(hsh_uint64.view(numpy.int64))  # return as int\n\n    @classmethod\n    def init_space_ratio(cls, n):\n        \"\"\" multiplier to set table size \"\"\"\n        return 4 if n < (1<<26) else 2\n\n    @classmethod\n    def min_space_ratio(cls, n):\n        \"\"\" when to trigger resize \"\"\"\n        return 3 if n < (1<<26) else 1.5\n\n    @classmethod\n    def max_steps(cls, n):\n        \"\"\" prevent infinite loop by a cap on the nb of steps (heuristic but very large) \"\"\"\n        return max(64, n // (32 * cls.init_space_ratio(n)))\n\n    def _resize(self, n):\n        log_size = int(self.init_space_ratio(n) * n - 1).bit_length()\n        has_value = self._table != self._empty\n        _keys = self._table[has_value]\n        if self.values is not None:\n            values = self.values[has_value]\n        else:\n            values = None\n        if values is not None:\n            self.values = numpy.zeros(self.size, dtype=values.dtype)\n        # re-allocate tables\n        self.log_size = log_size\n        self.shift = UINT64(64 - self.log_size)\n        new_size = 1 << log_size\n        self._table = numpy.full(\n            new_size, self._empty, dtype=self._table.dtype)\n        if values is not None:\n            self.values = numpy.zeros(new_size, dtype=values.dtype)\n        self._set_initial(_keys, values)\n\n    def _set_initial(self, _keys, values):\n        n, = _keys.shape\n        # step=0\n        step = UINT64(0)\n        indexes = self._shifted_hash(_keys, step)\n        self._table[indexes] = _keys\n        if values is not None:\n            self.values[indexes] = values\n        done = False\n        max_steps = self.max_steps(n)\n        for _ in range(max_steps):\n            collisions = self._table[indexes] != _keys\n            if not collisions.any():\n                done = True\n                break\n            # next step: work only in `collisions`\n            step += UINT64(1)\n            _keys = _keys[collisions]\n            if values is not None:\n                values = values[collisions]\n            # TOOPTIMIZE re-use computed hashes\n            indexes = self._shifted_hash(_keys, step)\n            available = self._table[indexes] == self._empty\n            available_indexes = indexes[available]\n            self._table[available_indexes] = _keys[available]\n            if values is not None:\n                self.values[available_indexes] = values[available]\n        if not done:\n            raise RuntimeError(f'could not _set_initial within {max_steps} steps')\n        self.n_used = (self._table != self._empty).sum()\n\n    def _change_empty(self, new_keys):\n        # edge case: the empty value we set clashes with a new key\n        _uniq_keys = self._table[self._table != self._empty]\n        all_keys = numpy.r_[_uniq_keys, new_keys]\n        new_empty = self._choose_empty_value(all_keys, self._table.dtype)\n        self._table[self._table == self._empty] = new_empty\n        self._empty = new_empty\n\n    @classmethod\n    def _hash(cls, _keys, step):\n        raise NotImplementedError()\n\n    def _shifted_hash(self, _keys, step):\n        _hash = self._hash(_keys, step)\n        _hash >>= self.shift\n        return _hash\n\n    @classmethod\n    def _fibonacci_hash_uint64(cls, _keys, step, copy=True):\n        if copy:\n            _keys = _keys.copy()\n        with warnings.catch_warnings():\n            warnings.filterwarnings(\n                'ignore', r'overflow encountered in ulong(long)?_scalars')\n            _keys += STEP_MULT * step\n            _keys *= INV_PHI\n            return _keys\n\n    @classmethod\n    def _choose_empty_value(cls, _keys, dtype, empty=_DEFAULT):\n        raise NotImplementedError()\n\n    @classmethod\n    def _cast(cls, keys, cast_dtype, view_dtype):\n        if keys.dtype != cast_dtype:\n            keys = structured_cast(keys, cast_dtype)\n        if keys.dtype != view_dtype:\n            if not keys.dtype.hasobject and not view_dtype.hasobject:\n                keys = keys.view(view_dtype)\n            else:\n                # HACK! numpy doesn't allow views with object, so we use a workaround\n                # warning: SegFault if `keys.dtype` has offsets, but we clean in structured_cast\n                keys = numpy.ndarray(keys.shape, view_dtype, keys.data)\n        return keys\n\n    def _cast_back(self, keys):\n        if keys.dtype != self.cast_dtype:\n            if not keys.dtype.hasobject and not self.cast_dtype.hasobject:\n                keys = keys.view(self.cast_dtype)\n            else:\n                # HACK! numpy doesn't allow views with object, so we use a workaround\n                # warning: SegFault if `keys.dtype` has offsets, but we clean in structured_cast\n                keys = numpy.ndarray(keys.shape, self.cast_dtype, keys.data)\n        if keys.dtype != self.original_dtype:\n            keys = structured_cast(keys, self.original_dtype)\n        return keys\n\n\nclass UInt64Hashmap(_BaseHashmap):\n    \"\"\"\n    a mapping from uint64 to arbitrary values in a numpy array\n    consider using the higher-level ``Hashmap`` instead\n    \"\"\"\n\n    @classmethod\n    def new(cls, keys, values=None, cast_dtype=None, view_dtype=None, empty=_DEFAULT):\n        \"\"\"\n        :param array keys: (n,) uint64 array\n        :param array? values: (n,) val-dtype array\n        :param dtype? cast_dtype: dtype to cast ``keys`` (default: uint64)\n        :param dtype? view_dtype: dtype to view ``keys`` (default: uint64)\n        :param object? empty: empty value (default: row of 0)\n        \"\"\"\n        cast_dtype = cast_dtype or UINT64\n        view_dtype = view_dtype or UINT64\n        return super().new(keys, values, cast_dtype, view_dtype, empty)\n\n    @classmethod\n    def _hash(cls, _keys, step):\n        # (_keys << 21) ^ (_keys >> 33)\n        _keys_cpy = _keys << 21\n        _keys_cpy ^= _keys >> 33\n        return cls._fibonacci_hash_uint64(_keys_cpy, step, copy=False)\n\n    @classmethod\n    def _choose_empty_value(cls, _keys, dtype, empty=_DEFAULT):\n        # empty defined by user\n        if empty is not _DEFAULT:\n            return empty\n        # use zero if keys are strictly positive\n        zero = UINT64(0)\n        if zero not in _keys:\n            return zero\n        # otherwise pick a random number\n        while True:\n            empty = numpy.random.randint(\n                low=1<<62, high=1<<63, dtype='uint64')\n            if empty not in _keys:\n                return empty\n\n\nclass UInt64StructHashmap(_BaseHashmap):\n    \"\"\"\n    a mapping from uint64-struct to arbitrary values in a numpy array\n    can be used on any structured dtypes without ``'O'`` by using views\n    consider using the higher-level ``Hashmap`` instead\n    \"\"\"\n    # almost INV_PHI but different one (used in xxhash.c)\n    _PRIME_1 = UINT64(11400714785074694791)\n    _PRIME_2 = UINT64(14029467366897019727)\n    _PRIME_5 = UINT64(2870177450012600261)\n\n    @classmethod\n    def new(cls, keys, values=None, cast_dtype=None, view_dtype=None, empty=_DEFAULT):\n        \"\"\"\n        :param array keys: (n,) uint64-struct array\n        :param array? values: (n,) val-dtype array\n        :param dtype? cast_dtype: dtype to cast ``keys`` (default: uint64 for each field)\n        :param dtype? view_dtype: dtype to view ``keys`` (default: uint64 for each field)\n        :param object? empty: empty value (default: row of 0)\n        \"\"\"\n        cast_dtype = cast_dtype or [(name, 'uint64')\n                                    for name in keys.dtype.names]\n        view_dtype = view_dtype or [(name, 'uint64')\n                                    for name in keys.dtype.names]\n        return super().new(keys, values, cast_dtype, view_dtype, empty)\n\n    @classmethod\n    def _hash(cls, _keys, step):\n        \"\"\" use Python's algorithm for tuple to get consistent values \"\"\"\n        n, = _keys.shape\n        n_cols = len(_keys.dtype)\n        acc = numpy.full(n, cls._PRIME_5)\n        buf = numpy.empty_like(acc)\n        for col in sorted(_keys.dtype.names):\n            # acc += _keys[col] * cls._PRIME_2\n            buf[:] = _keys[col]\n            buf *= cls._PRIME_2\n            acc += buf\n            # acc = (acc << 31) | (acc >> 33)\n            buf[:] = acc\n            buf >>= 33\n            acc <<= 31\n            acc |= buf\n            #\n            acc *= cls._PRIME_1\n        acc += UINT64(n_cols) ^ (cls._PRIME_5 ^ UINT64(3527539))\n        return cls._fibonacci_hash_uint64(acc, step, copy=False)\n\n    @classmethod\n    def _choose_empty_value(cls, _keys, dtype, empty=_DEFAULT):\n        # empty defined by user\n        if empty is not _DEFAULT:\n            return empty\n        # use zeros if keys are strictly positive\n        wrapper = numpy.zeros(1, dtype=dtype)\n        empty = wrapper[0]\n        if empty not in _keys:\n            return empty\n        # otherwise pick random numbers\n        d = len(dtype) or None\n        while True:\n            rdm = numpy.random.randint(low=1<<62, high=1<<63, size=d, dtype='uint64')\n            if d:\n                rdm = tuple(rdm)\n            wrapper[0] = rdm\n            empty = wrapper[0]\n            if empty not in _keys:\n                return empty\n\n\nclass ObjectHashmap(_BaseHashmap):\n    \"\"\"\n    a mapping from arbitrary keys to arbitrary values in a numpy array\n    internally uses python ``hash``, so hashes are not consistent (not even for string or bytes)\n    consider using the higher-level ``Hashmap`` instead\n    \"\"\"\n\n    @classmethod\n    def new(cls, keys, values=None, cast_dtype=None, view_dtype=None, empty=_DEFAULT):\n        \"\"\"\n        :param array keys: (n,) object array\n        :param array? values: (n,) val-dtype array\n        :param dtype? cast_dtype: dtype to cast ``keys`` (default: keys.type)\n        :param dtype? view_dtype: dtype to view ``keys`` (default: keys.type)\n        :param object? empty: empty value (default: row of 0)\n        \"\"\"\n        cast_dtype = cast_dtype or keys.dtype\n        view_dtype = view_dtype or cast_dtype\n        return super().new(keys, values, cast_dtype, view_dtype, empty)\n\n    @classmethod\n    def _hash(cls, _keys, step):\n        n = _keys.shape[0]\n        hashes = numpy.fromiter((cls._hash_single_obj(obj) for obj in _keys),\n                                count=n, dtype=UINT64)\n        return cls._fibonacci_hash_uint64(hashes, step, copy=False)\n\n    @classmethod\n    def _hash_single_obj(cls, obj):\n        try:\n            return hash(obj)\n        except TypeError:\n            # cast single numpy array to bytes\n            if isinstance(obj, numpy.ndarray):\n                return hash(obj.tobytes())\n            # cast all numpy arrays in tuple/void to bytes\n            if isinstance(obj, (tuple, numpy.void)):\n                obj_ = tuple((a.tobytes() if isinstance(a, numpy.ndarray) else a)\n                             for a in tuple(obj))\n                return hash(obj_)\n            raise\n\n    @classmethod\n    def _choose_empty_value(cls, _keys, dtype, empty=_DEFAULT):\n        return UInt64StructHashmap._choose_empty_value(_keys, dtype, empty)\n\n\nclass BytesObjectHashmap(ObjectHashmap):\n    \"\"\"\n    hashmap from bytes strings keys encoded as object\n    internally uses xxhash or hashlib to get consistent hashes\n    consider using the higher-level ``Hashmap`` instead\n    \"\"\"\n\n    if _HAS_XXHASH:\n        @classmethod\n        def _hash_single_obj(cls, obj):\n            return xxhash.xxh3_64_intdigest(obj)\n    else:\n        @classmethod\n        def _hash_single_obj(cls, obj):\n            sha1 = hashlib.sha1()\n            sha1.update(obj)\n            return struct.unpack('<Q', sha1.digest()[:8])[0]\n\n\nclass StrObjectHashmap(BytesObjectHashmap):\n    \"\"\"\n    hashmap from unicode strings keys encoded as object\n    internally uses xxhash or hashlib to get consistent hashes\n    consider using the higher-level ``Hashmap`` instead\n    \"\"\"\n    @classmethod\n    def _hash_single_obj(cls, obj):\n        return super()._hash_single_obj(obj.encode(errors='ignore'))\n\n\nclass BytesObjectTupleHashmap(BytesObjectHashmap):\n    \"\"\"\n    hashmap from tuple of either non-object, or bytes/unicode strings keys encoded as object\n    internally uses xxhash or hashlib to get consistent hashes\n    consider using the higher-level ``Hashmap`` instead\n    \"\"\"\n    @classmethod\n    def _hash_single_obj(cls, obj_tuple):\n        h = xxhash.xxh3_64() if _HAS_XXHASH else hashlib.sha1()\n        for obj in obj_tuple:\n            if isinstance(obj, str):\n                obj = obj.encode(errors='ignore')\n            h.update(obj)\n        return struct.unpack('<Q', h.digest()[:8])[0]\n\n\ndef Hashmap(keys, values=None):\n    \"\"\"\n    fake class to select between uint64/struct/object from dtype of arguments\n    :param array keys: (n,) key-dtype array\n    :param array? values: (n,) val-dtype array\n    \"\"\"\n    # switch type from keys\n    cls, cast_dtype, view_dtype = _get_optimal_cast(keys)\n    # build hashmap\n    return cls.new(keys, values, cast_dtype, view_dtype)\n\n\ndef _get_optimal_cast(keys, allow_object_hashmap=False):\n    \"\"\"\n    select best hashmap type to fit ``dtype``\n\n    :param array keys:\n    :param bool? allow_object_hashmap:\n    :returns: cls, cast_dtype, view_dtype\n    \"\"\"\n    dtype = keys.dtype\n    kind = dtype.kind\n    names = dtype.names\n    # scalar input (or strings of less than 8 bytes) we can view as uint64\n    if kind in 'buifcSUV' and dtype.itemsize <= 8 and not names:\n        if kind == 'b':\n            kind = 'u'\n        # how many units of `kind` we need for get 8 bytes, e.g. 2 for 'U'\n        inner_dtype_len = 8 // numpy.dtype(f'{kind}1').itemsize\n        cast_dtype = f'{kind}{inner_dtype_len}'\n        view_dtype = UINT64\n        return UInt64Hashmap, numpy.dtype(cast_dtype), numpy.dtype(view_dtype)\n    # cast string of more than 8 bytes to tuple of uint64\n    elif kind in 'SUV' and not names:\n        # number of uint64 (8 bytes) we need to view original dtype, e.g. 5 for 'U9'\n        n_uint64 = int(numpy.ceil(float(dtype.itemsize) / 8))\n        # how many 'S1' or 'U1' we need for get 8 bytes, e.g. 2 for 'U'\n        inner_dtype_len = 8 / numpy.dtype(f'{kind}1').itemsize\n        # first cast to bigger string to fit exactly a multiple of 8 bytes, e.g. 'U10'\n        cast_dtype = f'{kind}{int(n_uint64 * inner_dtype_len)}'\n        # then view as a tuple of uint64, e.g. 'u8,u8,u8,u8,u8'\n        view_dtype = [(f'f{i}', 'u8') for i in range(n_uint64)]\n        return UInt64StructHashmap, numpy.dtype(cast_dtype), numpy.dtype(view_dtype)\n    # struct input\n    if names and all(dtype[n].kind in 'buifcSUV' for n in names):\n        dtypes = [(n, dtype[n]) for n in names]\n        # check if we need padding to fit in a multiple of 8 bytes\n        nbytes = sum(dt.itemsize for n, dt in dtypes)\n        npad = 8 * int(numpy.ceil(nbytes / 8)) - nbytes\n        if npad == 0:\n            cast_dtype = dtypes  # simply remove offsets\n        else:\n            # add 'S{npad}' padding field\n            cast_dtype = dtypes + [('__pad__', f'S{npad}')]\n        # if all fields fit inside 8 bytes, use uint64 hashmap\n        if nbytes <= 8:\n            view_dtype = UINT64\n            return UInt64Hashmap, numpy.dtype(cast_dtype), numpy.dtype(view_dtype)\n        # otherwise view as a struct of multiple uint64\n        n_uint64 = (nbytes + npad) // 8\n        view_dtype = [(f'f{i}', 'u8') for i in range(n_uint64)]\n        return UInt64StructHashmap, numpy.dtype(cast_dtype), numpy.dtype(view_dtype)\n    # bytes/str objects\n    if keys.size and kind == 'O':\n        if all(isinstance(k, bytes) for k in keys):\n            return BytesObjectHashmap, numpy.dtype('O'), numpy.dtype('O')\n        if all(isinstance(k, str) for k in keys):\n            return StrObjectHashmap, numpy.dtype('O'), numpy.dtype('O')\n    # struct with bytes/str objects\n    if keys.size and names and all(dtype[n].kind in 'buifcSUVO' for n in names):\n        dtypes = [(n, dtype[n]) for n in names]\n        obj_dtypes, nonobj_dtypes = split(dtypes, lambda ndt: ndt[1] == 'O')\n        if all(isinstance(k, (str, bytes)) for n, _ in obj_dtypes for k in keys[n]):\n            # view all non-object as a single byte string\n            cast_dtype = nonobj_dtypes + obj_dtypes  # move all non-obj first\n            nonobj_size = sum(dt.itemsize for _, dt in nonobj_dtypes)\n            view_dtype = [('__nonobj__', f'V{nonobj_size}')] + obj_dtypes\n            return BytesObjectTupleHashmap, numpy.dtype(cast_dtype), numpy.dtype(view_dtype)\n    # use arbitrary object but it is dangerous, so we raise if not explicitely allowed\n    if allow_object_hashmap:\n        return ObjectHashmap, dtype, dtype\n    raise NotImplementedError(dtype)\n\n\ndef unique(values, return_inverse=False, return_index=False):\n    \"\"\"\n    :param array values: (n,) dtype array\n    :param bool? return_inverse:\n    :param bool? return_index:\n    :returns: (\n        uniques: (n2,) dtype array with n2<=n,\n        [if return_inverse=1] idx_in_uniques: (n,) uint32 array of indexes <= n2,\n        [if return_index=1] unique_idx: (n2,) uint32 array of indexes <= n,\n    )\n    \"\"\"\n    _vals = numpy.arange(\n        values.size, dtype='uint32') if return_index or return_inverse else None\n    hashmap = Hashmap(keys=values, values=_vals)\n    unique_values, table_mask = hashmap.unique_keys(return_table_mask=True)\n    if not return_inverse and not return_index:\n        return unique_values\n    out = (unique_values,)\n    if return_index:\n        unique_idx = hashmap.values[table_mask]\n    if return_inverse:\n        # for return_inverse, we change hashmap values to be indexes in `unique_values`\n        uniq_idx_in_uniq = numpy.arange(unique_values.size, dtype='uint32')\n        hashmap.values[table_mask] = uniq_idx_in_uniq\n        idx_in_uniques, found = hashmap.get_many(values)\n        assert found.all()\n        out = out + (idx_in_uniques,)\n    if return_index:\n        out = out + (unique_idx,)\n    return out\n\n\ndef get_dense_labels_map(values, idx_dtype='uint32'):\n    \"\"\"\n    convert unique values into dense int labels [0..n_uniques]\n    :param array values: (n,) dtype array\n    :param dtype? idx_dtype: (default: 'uint32')\n    :returns: tuple(\n        labels2values: (n_uniques,) dtype array,\n        values2labels: HashMap(dtype->int),\n    )\n    \"\"\"\n    # get unique values\n    unique_values = unique(values)\n    # build labels from 0 to n_uniques\n    labels = numpy.arange(unique_values.shape[0], dtype=idx_dtype)\n    # build small hashmap with just the unique items\n    values2labels = Hashmap(unique_values, labels)\n    return unique_values, values2labels\n\n\ndef factorize(values):\n    \"\"\"\n    Build dense int labels maps and return labels\n    :param array values: (n,) dtype array\n    :returns: tuple(\n        labels: (n,) int array,\n        labels2values: (n_uniques,) dtype array,\n        values2labels: HashMap(dtype->int),\n    )\n    \"\"\"\n    labels2values, values2labels = get_dense_labels_map(values)\n    values_labels, found = values2labels.get_many(values)\n    assert found.all()\n    return values_labels, labels2values, values2labels\n\n\ndef update_dense_labels_map(hashmap, values):\n    \"\"\"\n    update hashmap values -> dense labels, and return mapped values\n    :param HashMap hashmap: HashMap(dtype->int)\n    :param array values: (n,) dtype array\n    :returns: (n,) int array\n    :changes: update ``hashmap`` in-place\n    \"\"\"\n    # get current values\n    labels, found = hashmap.get_many(values)\n    new_values = values[~found]\n    if not new_values.size:\n        return labels\n    # check unique new values\n    unique_new_values, new_values_idx_in_uniques = unique(\n        new_values, return_inverse=True)\n    # build new labels\n    idx_dtype = hashmap.values.dtype\n    _, current_labels = hashmap.unique_keys(return_values=True)\n    if current_labels.size == 0:\n        start_at = 0\n    else:\n        start_at = current_labels.max() + 1\n    new_labels = numpy.arange(\n        start_at, start_at + unique_new_values.shape[0], dtype=idx_dtype)\n    hashmap.set_many(unique_new_values, new_labels)\n    # return all labels\n    labels, found = hashmap.get_many(values)\n    assert found.all()\n    return labels\n\n\ndef empty_hashmap(key_dtype, val_dtype='uint32'):\n    \"\"\"\n    Build empty Hashmap\n    :param dtype key_dtype:\n    :param dtype? val_dtype: (default: uint32)\n    :returns: Hashmap\n    \"\"\"\n    key_dtype = numpy.dtype(key_dtype)\n    val_dtype = numpy.dtype(val_dtype)\n    return Hashmap(numpy.empty(0, dtype=key_dtype), numpy.empty(0, dtype=val_dtype))\n\n\ndef reverse_values2labels(values2labels, dtype=None):\n    \"\"\"\n    Reverse a hashmap values2labels.\n    Normally you should not call this function but use the values provided in ``factorize``\n    :param Hashmap values2labels: labels hashmap with n items\n    :param dtype? dtype:\n    :returns: (n,) dtype array\n    \"\"\"\n    values = values2labels.unique_keys()\n    labels, found = values2labels.get_many(values)\n    assert found.all()\n    out = numpy.empty_like(values, dtype=dtype)\n    out[labels] = values\n    return out\n\n\ndef array_hash(array, order_matters):\n    \"\"\"\n    Return consistent hash of array that may or may not be order invarient\n    :param array array: array with or without structure\n    :param bool order_matters:\n    :returns: int\n    \"\"\"\n    if order_matters:\n        order_num = STEP_MULT * numpy.arange(array.size, dtype=UINT64)\n        if array.dtype.names is None:\n            array = to_structured([('f0', array), ('__index__', order_num)])\n        else:\n            array = set_or_add_to_structured(array, [('__index__', order_num)])\n    hashtable = Hashmap(array)\n    return hashtable.keys_hash()\n\n\ndef values_hash(array, step=0):\n    \"\"\"\n    Return consistent hash of array values\n    :param array array: (n,) array with or without structure\n    :param uint64 step: optional step number to modify hash values\n    :returns: (n,) uint64 array\n    \"\"\"\n    cls, cast_dtype, view_dtype = _get_optimal_cast(array)\n    array = cls._cast(array, cast_dtype, view_dtype)\n    return cls._hash(array, UINT64(step))\n", "meta": {"hexsha": "19b0ecc8961092d1c707bb72bc78db03531a9398", "size": 30299, "ext": "py", "lang": "Python", "max_stars_repo_path": "xminds/_lib/hashmap.py", "max_stars_repo_name": "Crossing-Minds/xminds-python", "max_stars_repo_head_hexsha": "8ee345e3a9ec41016c6a866e1af5eb13f7ff4f1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-10-27T00:11:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T21:15:25.000Z", "max_issues_repo_path": "xminds/_lib/hashmap.py", "max_issues_repo_name": "Crossing-Minds/xminds-python", "max_issues_repo_head_hexsha": "8ee345e3a9ec41016c6a866e1af5eb13f7ff4f1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xminds/_lib/hashmap.py", "max_forks_repo_name": "Crossing-Minds/xminds-python", "max_forks_repo_head_hexsha": "8ee345e3a9ec41016c6a866e1af5eb13f7ff4f1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0163111669, "max_line_length": 100, "alphanum_fraction": 0.6173141028, "include": true, "reason": "import numpy", "num_tokens": 7415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.33807711081162, "lm_q1q2_score": 0.17299967127271607}}
{"text": "# Copyright (C) H.R. Oosterhuis 2020.\n# Distributed under the MIT License (see the accompanying README.md and LICENSE files).\n\nimport argparse\nimport dataset\nimport multi_click_models as clk\nimport numpy as np\nimport os\nimport time\nfrom multiprocessing import Pool\nimport utils.arp_ips as ips\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"prop_model\", type=str,\n                    help=\"Name of propensity model to use.\",)\nparser.add_argument(\"model_file\", type=str,\n                    help=\"Model file output from pretrained model.\")\nparser.add_argument(\"output_path\", type=str,\n                    help=\"Path to output model.\")\nparser.add_argument(\"--loss\", type=str,\n                    help=\"Loss to optimize.\",\n                    default='relevant_rank')\nparser.add_argument(\"--click_model\", type=str,\n                    help=\"Name of click model to use.\",\n                    default='binarized')\nparser.add_argument(\"--dataset\", type=str,\n                    default=\"Webscope_C14_Set1\",\n                    help=\"Name of dataset to sample from.\")\nparser.add_argument(\"--dataset_info_path\", type=str,\n                    default=\"datasets_info.txt\",\n                    help=\"Path to dataset info file.\")\nparser.add_argument(\"--eta\", type=float,\n                    default=1.0,\n                    help=\"Eta parameter for observance probabilities.\")\nparser.add_argument(\"--cutoff\", type=int,\n                    default=5,\n                    help=\"Item selection cutoff in ranking for generating clicks.\")\nparser.add_argument(\"--cutoff_opt\", type=int,\n                    default=5,\n                    help=\"Cutoff for optimization.\")\nparser.add_argument(\"--num_clicks\", type=int,\n                    default=10000000,\n                    help=\"Number of clicks to generate.\")\nparser.add_argument(\"--scale\", type=float,\n                    default=5.0,\n                    help=\"Scaling the linear scorer.\")\nparser.add_argument(\"--num_proc\", type=int,\n                    default=1,\n                    help=\"Number of processes to use.\")\nargs = parser.parse_args()\n\ncutoff = args.cutoff\neta = args.eta\nnum_proc = args.num_proc\nprop_model = args.prop_model\nassert num_proc >= 0, 'Invalid number of processes: %d' % num_proc\n\nif prop_model in ['deterministic_clipped', 'deterministic_unclipped']:\n  cutoff = 0\n\nrerank = '_rerank' in prop_model\n\nif '_clipped' in args.prop_model:\n  num_clicks = args.num_clicks\n  c = np.log(num_clicks)/np.log(10)\n  if args.dataset == 'Webscope_C14_Set1':\n    a = -3.\n    b = 32.\n  elif args.dataset == 'MSLR-WEB30k':\n    # MSLR\n    a = -57\n    b = 86.\n  elif args.dataset == 'istella':\n    # Istella\n    a = 30.\n    b = 0.\n\n  clip_thres = (c-4.)*(a) + (c-4.)**2.*b + 1.\n  clip_thres = max(clip_thres, 1.)\n  if c < 4:\n    clip_thres = 1.\nelif '_naive' in args.prop_model:\n  clip_thres = 1.\nelse:\n  clip_thres = 0\n\ndata = dataset.get_dataset_from_json_info(\n                  args.dataset,\n                  args.dataset_info_path,\n                  shared_resource = num_proc > 1,\n                )\n\ndata = data.get_data_folds()[0]\n\nstart = time.time()\ndata.read_data()\nprint('Time past for reading data: %d seconds' % (time.time() - start))\n\npretrain_model = clk.read_model(args.model_file, data, args.scale)\n\nnum_train_clicks = int(args.num_clicks)\nnum_validation_clicks = int(num_train_clicks*0.15)\n\nstart = time.time()\ntrain_clicks = clk.generate_squashed_clicks(\n                    prop_model,\n                    data.train,\n                    pretrain_model,\n                    args.click_model,\n                    num_train_clicks,\n                    cutoff,\n                    eta,\n                    clip_thres)\nprint('Time past for generating train clicks: %d seconds' % (time.time() - start))\nstart = time.time()\nvalidation_clicks = clk.generate_squashed_clicks(\n                    prop_model,\n                    data.validation,\n                    pretrain_model,\n                    args.click_model,\n                    num_validation_clicks,\n                    cutoff,\n                    eta,\n                    0)\nprint('Time past for generating validation clicks: %d seconds' % (time.time() - start))\n\n\ndef _make_shared(numpy_matrix):\n    \"\"\"\n    Avoids the copying of Read-Only shared memory.\n    \"\"\"\n    if numpy_matrix is None:\n      return None\n    else:\n      shared = sharedmem.empty(numpy_matrix.shape,\n                               dtype=numpy_matrix.dtype)\n      shared[:] = numpy_matrix[:]\n      return shared\n\nif args.num_proc > 1:\n  train_clicks['average_weights'] = _make_shared(train_clicks['average_weights'])\n  train_clicks['clicks_per_doc'] = _make_shared(train_clicks['clicks_per_doc'])\n  train_clicks['queries'] = _make_shared(train_clicks['queries'])\n  validation_clicks['average_weights'] = _make_shared(validation_clicks['average_weights'])\n  validation_clicks['clicks_per_doc'] = _make_shared(validation_clicks['clicks_per_doc'])\n  validation_clicks['queries'] = _make_shared(validation_clicks['queries'])\n\n\nepsilon_thres=0.0001\nif args.loss in ['lambdaloss-truncated', 'monotonic']:\n  epsilon_thres /= 100.\n# lr_range = np.geomspace(10**-4., 10**-11., 30)\nclick_order = np.log(args.num_clicks)/np.log(10)\nif args.dataset == 'Webscope_C14_Set1':\n  if args.loss in ['monotonic']:\n    lr_range = [500.]\n    tries = 30+int(10*click_order)\n  elif args.loss in ['lambdaloss-truncated']:\n    lr_range = [5.]\n    tries = 30+int(20*click_order)\n  else:\n    lr_range = [1.]\n    tries = 20+int(10*click_order)\nelif args.dataset == 'MSLR-WEB30k':\n  # MSLR\n  if args.loss in ['monotonic']:\n    if 'rerank' in prop_model:\n      lr_range = [100.]\n    else:\n      lr_range = [1000.]\n    tries = 30+int(10*click_order)\n  elif args.loss in ['lambdaloss-truncated', 'lambdaloss@k', 'lambdaloss-full']:\n    lr_range = [50.]\n    tries = 30+int(10*click_order)\n  else:\n    lr_range = [.5]\n    tries = 20+int(10*click_order)\n\nelif args.dataset == 'istella':\n  # Istella\n  lr_range = [.01]\n  tries = 20+int(2*click_order)\n\ndef multi_optimize(m_args):\n  lr = m_args\n  if args.loss == 'lambdaloss-truncated':\n    if train_clicks['rerank']:\n      # with this hack we can compute the deterministic grad\n      # using the replacelast code\n      cutoff_hack = args.cutoff\n      if 'deterministic' in prop_model:\n        cutoff_hack += 1\n      return ips.optimize_rerank_dcg(\n                      args.loss,\n                      data,\n                      train_clicks,\n                      validation_clicks,\n                      learning_rate=lr,\n                      learning_rate_decay=1.,\n                      trial_epochs=tries,\n                      max_epochs=1000,\n                      epsilon_thres=epsilon_thres,\n                      cutoff=args.cutoff_opt,\n                      log_cutoff=cutoff_hack\n                     )\n    else:\n      return ips.optimize_dcg(\n                      args.loss,\n                      data,\n                      train_clicks,\n                      validation_clicks,\n                      learning_rate=lr,\n                      learning_rate_decay=1.,\n                      trial_epochs=tries,\n                      max_epochs=1000,\n                      epsilon_thres=epsilon_thres,\n                      cutoff=args.cutoff_opt,\n                     )\n  else:\n    return ips.optimize(\n                    args.loss,\n                    data,\n                    train_clicks,\n                    validation_clicks,\n                    learning_rate=lr,\n                    learning_rate_decay=1.,\n                    trial_epochs=tries,\n                    max_epochs=1000,\n                    epsilon_thres=epsilon_thres,\n                    cutoff=cutoff,\n                   )\n\narg_list = lr_range\n\nif args.num_proc > 1:\n  pool = Pool(processes=args.num_proc)\n  results = pool.map(multi_optimize, arg_list)\nelse:\n  results = [multi_optimize(x) for x in arg_list]\n\nbest_result = results[0]\nfor r in results:\n  if r['estimated_loss'] < best_result['estimated_loss']:\n    best_result = r\n\nbest_result['clipping_threshold'] = clip_thres\n\ndef _doc_feat_str(doc_feat):\n  doc_str = \"\"\n  for f_i, f_v in enumerate(doc_feat):\n    if f_v == 1.:\n      doc_str += ' %d:1' % data.feature_map[f_i]\n    elif f_v != 0.:\n      doc_str += ' %d:%f' % (data.feature_map[f_i], f_v)\n  return doc_str\n\noutput = ''\noutput += '--Simulation Arguments--\\n'\noutput += 'propensity model: %s\\n' % args.prop_model\noutput += 'click_model model: %s\\n' % args.click_model\noutput += 'number of clicks: %s\\n' % args.num_clicks\noutput += 'eta: %s\\n' % args.eta\noutput += 'cutoff: %s\\n' % args.cutoff\noutput += 'dataset: %s\\n' % args.dataset\noutput += '--Model Found--\\n'\nfor k in sorted(best_result.keys()):\n  if k != 'model':\n    output += '%s: %s\\n' % (k, best_result[k])\noutput += '1 %s\\n' % _doc_feat_str(best_result['model'])\nprint(output)\n\nwith open(args.output_path, 'w') as f:\n  f.write(output)", "meta": {"hexsha": "9213ccc3aaa3224c17c5efb0614e73a9ca0392cd", "size": 8908, "ext": "py", "lang": "Python", "max_stars_repo_path": "topktrain.py", "max_stars_repo_name": "HarrieO/2020topkunbiasedltr", "max_stars_repo_head_hexsha": "f6e191a6cb6d52a375a1ec213e42dbbda8fdb8ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-05-04T04:42:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-06T09:41:28.000Z", "max_issues_repo_path": "topktrain.py", "max_issues_repo_name": "HarrieO/2020topkunbiasedltr", "max_issues_repo_head_hexsha": "f6e191a6cb6d52a375a1ec213e42dbbda8fdb8ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "topktrain.py", "max_forks_repo_name": "HarrieO/2020topkunbiasedltr", "max_forks_repo_head_hexsha": "f6e191a6cb6d52a375a1ec213e42dbbda8fdb8ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.63003663, "max_line_length": 91, "alphanum_fraction": 0.585765604, "include": true, "reason": "import numpy", "num_tokens": 2148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3140505578320071, "lm_q1q2_score": 0.17291855029275408}}
{"text": "\"\"\"\nThe classes in this file do preprocessing on data and monte carlo to be used\nto do a point source analysis.\n\"\"\"\n\n__author__ = 'John Evans'\n__copyright__ = 'Copyright 2020 John Evans'\n__credits__ = ['John Evans', 'Jason Fan', 'Michael Larson']\n__license__ = 'Apache License 2.0'\n__version__ = '0.0.1'\n__maintainer__ = 'John Evans'\n__email__ = 'john.evans@icecube.wisc.edu'\n__status__ = 'Development'\n\nfrom typing import Optional, Tuple, Union\n\nimport copy\nimport scipy\nimport numpy as np\nimport numpy.lib.recfunctions as rf\nfrom scipy.interpolate import UnivariateSpline as Spline\n\nfrom dataclasses import dataclass\nfrom dataclasses import field\nfrom dataclasses import InitVar\n\nfrom . import sources\nfrom . import time_profiles\nfrom . import test_statistics\n\n\ndef cross_matrix(mat: np.array) -> np.array:\n    \"\"\"Calculate cross product matrix.\n    A[ij] = x_i * y_j - y_i * x_j\n    Args:\n        mat: A 2D array to take the cross product of.\n    Returns:\n        The cross matrix.\n    \"\"\"\n    skv = np.roll(np.roll(np.diag(mat.ravel()), 1, 1), -1, 0)\n    return skv - skv.T\n\n\ndef rotate(ra1: float, dec1: float, ra2: float, dec2: float,\n           ra3: float, dec3: float) -> Tuple[float, float]:\n    \"\"\"Rotation matrix for rotation of (ra1, dec1) onto (ra2, dec2).\n\n    The rotation is performed on (ra3, dec3).\n\n    Args:\n        ra1: The right ascension of the point to be rotated from.\n        dec1: The declination of the point to be rotated from.\n        ra2: the right ascension of the point to be rotated onto.\n        dec2: the declination of the point to be rotated onto.\n        ra3: the right ascension of the point that will actually be rotated.\n        dec3: the declination of the point that will actually be rotated.\n\n    Returns:\n        The rotated ra3 and dec3.\n\n    Raises:\n        IndexError: Arguments must all have the same dimension.\n    \"\"\"\n    ra1 = np.atleast_1d(ra1)\n    dec1 = np.atleast_1d(dec1)\n    ra2 = np.atleast_1d(ra2)\n    dec2 = np.atleast_1d(dec2)\n    ra3 = np.atleast_1d(ra3)\n    dec3 = np.atleast_1d(dec3)\n\n    if not (\n        len(ra1) == len(dec1) == len(ra2) == len(dec2) == len(ra3) == len(dec3)\n    ):\n        raise IndexError('Arguments must all have the same dimension.')\n\n    cos_alpha = np.cos(ra2 - ra1) * np.cos(dec1) * np.cos(dec2) \\\n        + np.sin(dec1) * np.sin(dec2)\n\n    # correct rounding errors\n    cos_alpha[cos_alpha > 1] = 1\n    cos_alpha[cos_alpha < -1] = -1\n\n    alpha = np.arccos(cos_alpha)\n    vec1 = np.vstack([np.cos(ra1) * np.cos(dec1),\n                      np.sin(ra1) * np.cos(dec1),\n                      np.sin(dec1)]).T\n    vec2 = np.vstack([np.cos(ra2) * np.cos(dec2),\n                      np.sin(ra2) * np.cos(dec2),\n                      np.sin(dec2)]).T\n    vec3 = np.vstack([np.cos(ra3) * np.cos(dec3),\n                      np.sin(ra3) * np.cos(dec3),\n                      np.sin(dec3)]).T\n    nvec = np.cross(vec1, vec2)\n    norm = np.sqrt(np.sum(nvec**2, axis=1))\n    nvec[norm > 0] /= norm[np.newaxis, norm > 0].T\n\n    one = np.diagflat(np.ones(3))\n    ntn = np.array([np.outer(nv, nv) for nv in nvec])\n    nx = np.array([cross_matrix(nv) for nv in nvec])\n\n    r = np.array([(1. - np.cos(a)) * ntn_i + np.cos(a) * one + np.sin(a) * nx_i\n                  for a, ntn_i, nx_i in zip(alpha, ntn, nx)])\n    vec = np.array([np.dot(r_i, vec_i.T) for r_i, vec_i in zip(r, vec3)])\n\n    r_a = np.arctan2(vec[:, 1], vec[:, 0])\n    dec = np.arcsin(vec[:, 2])\n\n    r_a += np.where(r_a < 0., 2. * np.pi, 0.)\n\n    return r_a, dec\n\n\n@dataclass\nclass EventModelBase:\n    \"\"\"Stores the events and pre-processed parameters used in analyses.\n\n    Currently, this class uses internal data and monte-carlo datasets. This\n    will be updated before the first release to use the upcoming public data\n    release.\n\n    Attributes:\n        data (np.ndarray): Real neutrino event data.\n        sim (np.ndarray): Simulated neutrino events.\n        grl (np.ndarray): A list of runs/times when the detector was working\n            properly.\n        reduced_sim (np.ndarray):\n        gamma (float):\n    \"\"\"\n    source: InitVar[sources.Source]\n    data: InitVar[np.ndarray]\n    sim: InitVar[np.ndarray]\n    grl: InitVar[np.ndarray]\n    gamma: InitVar[float]\n\n    _source: sources.Source = field(init=False)\n    _data: np.ndarray = field(init=False)\n    _sim: np.ndarray = field(init=False)\n    _gamma: float = field(init=False)\n    _n_background: int = field(init=False)\n    _grl: np.ndarray = field(init=False)\n    _grl_rates: np.ndarray = field(init=False)\n    _reduced_sim: np.ndarray = field(init=False)\n    _background_dec_spline: Spline = field(init=False)\n    _livetime: float = field(init=False)\n    _sampling_width: Optional[float] = field(init=False)\n\n\n@dataclass\nclass EventModelDefaultsBase:\n    \"\"\"Stores the events and pre-processed parameters used in analyses.\n\n    Currently, this class uses internal data and monte-carlo datasets. This\n    will be updated before the first release to use the upcoming public data\n    release.\n\n    Attributes:\n        sampling_width:\n        background_dec_spline: A spline fit of neutrino flux vs. sin(dec).\n    \"\"\"\n    sampling_width: InitVar[Optional[float]] = field(default=np.deg2rad(3))\n    background_sin_dec_bins: InitVar[Union[np.array, int]] = field(default=500)\n\n\n@dataclass\nclass EventModel(EventModelDefaultsBase, EventModelBase):\n    \"\"\"Stores the events and pre-processed parameters used in analyses.\n\n    Currently, this class uses internal data and monte-carlo datasets. This\n    will be updated before the first release to use the upcoming public data\n    release.\n    \"\"\"\n    def __post_init__(\n        self,\n        source: sources.Source,\n        data: np.ndarray,\n        sim: np.ndarray,\n        grl: np.ndarray,\n        gamma: float,\n        sampling_width: Optional[float],\n        background_sin_dec_bins: Union[np.array, int],\n    ) -> None:\n        \"\"\"Initializes EventModel and calculates energy sob maps.\n\n        Args:\n            source:\n            grl:\n            background_sin_dec_bins: If an int, then the number of bins\n                spanning -1 -> 1, otherwise, a numpy array of bin edges.\n\n        Raises:\n            ValueError:\n        \"\"\"\n        try:\n            self._data = rf.append_fields(\n                data,\n                'sindec',\n                np.sin(data['dec']),\n                usemask=False,\n            )\n            # The full simulation set,this is for the overall normalization of\n            # the Energy S/B ratio\n        except ValueError:  # sindec already exist\n            self._data = data\n\n        try:\n            self._sim = rf.append_fields(\n                sim,\n                'sindec',\n                np.sin(sim['dec']),\n                usemask=False,\n            )\n            # The full simulation set,this is for the overall normalization of\n            # the Energy S/B ratio\n        except ValueError:  # sindec already exist\n            self._sim = sim\n\n        self._source = source\n        min_mjd = np.min(self._data['time'])\n        max_mjd = np.max(self._data['time'])\n        self._grl = grl[(grl['start'] < max_mjd) & (grl['stop'] > min_mjd)]\n\n        self._gamma = gamma\n        self._sampling_width = sampling_width\n        self._init_reduced_sim(source)\n\n        if isinstance(background_sin_dec_bins, int):\n            background_sin_dec_bins = np.linspace(-1, 1,\n                                                  1 + background_sin_dec_bins)\n\n        self._background_dec_spline = self._init_background_dec_spline(\n            background_sin_dec_bins)\n\n        self._livetime = self._grl['livetime'].sum()\n        self._n_background = self._grl['events'].sum()\n        self._grl_rates = self._grl['events'] / self._grl['livetime']\n\n    def _init_background_dec_spline(self, sin_dec_bins: np.array, *args,\n                                    **kwargs) -> Spline:\n        \"\"\"Builds a histogram of neutrino flux vs. sin(dec) and splines it.\n\n        The UnivariateSpline function call uses these default arguments:\n        bbox=[-1.0, 1.0], s=1.5e-5, ext=1. To replace any of these defaults, or\n        to pass any other args/kwargs to UnivariateSpline, just pass them to\n        this function.\n\n        Args:\n            sin_dec_bins: A numpy array of bin edges to use to build the\n                histogram to spline.\n\n        Returns:\n            A spline function of the neutrino flux vs. sin(dec) histogram.\n        \"\"\"\n        # Our background PDF only depends on declination.\n        # In order for us to capture the dec-dependent\n        # behavior, we first take a look at the dec values\n        # in the data. We can do this by histogramming them.\n        hist, bins = np.histogram(self._data['sindec'], bins=sin_dec_bins,\n                                  density=True)\n        bin_centers = bins[:-1] + np.diff(bins) / 2\n\n        # These values have a lot of \"noise\": they jump\n        # up and down quite a lot. We could use fewer\n        # bins, but that may hide some features that\n        # we care about. We want something that captures\n        # the right behavior, but is smooth and continuous.\n        # The best way to do that is to use a \"spline\",\n        # which will fit a continuous and differentiable\n        # piecewise polynomial function to our data.\n        # We can set a smoothing factor (s) to control\n        # how smooth our spline is.\n\n        if 'bbox' not in kwargs:\n            kwargs['bbox'] = [-1.0, 1.0]\n        if 's' not in kwargs:\n            kwargs['s'] = 1.5e-5\n        if 'ext' not in kwargs:\n            kwargs['ext'] = 3\n\n        return Spline(bin_centers, hist, *args, **kwargs)\n\n    def _init_reduced_sim(self, source: sources.Source) -> None:\n        \"\"\"Gets a small simulation dataset to use for injecting signal.\n\n        Prunes the simulation set to only events close to a given source and\n        calculate the weight for each event. Adds the weights as a new column\n        to the simulation set.\n\n        Args:\n            source:\n\n        Returns:\n            A reweighted simulation set around the source declination.\n        \"\"\"\n        if self._sampling_width is not None:\n            self._cut_sim_truedec(source)\n        else:\n            self._reduced_sim = self._sim.copy()\n        self._reduced_sim = self._weight_reduced_sim(self._reduced_sim)\n        self._randomize_sim_times()\n\n    def _randomize_sim_times(self) -> None:\n        \"\"\"Docstring\"\"\"\n        # Randomly assign times to the simulation events within the data time\n        # range.\n        min_time = np.min(self._data['time'])\n        max_time = np.max(self._data['time'])\n        self._reduced_sim['time'] = np.random.uniform(\n            min_time, max_time, size=len(self._reduced_sim))\n\n    def _cut_sim_truedec(self, source: sources.Source) -> None:\n        \"\"\"Select simulation events in a true dec band(for ns calculation)\n\n        Args:\n            source:\n        \"\"\"\n        sindec_dist = np.abs(source.dec - self._sim['trueDec'])\n        close = sindec_dist < self._sampling_width\n        self._reduced_sim = self._sim[close].copy()\n\n        omega = 2 * np.pi * (np.min(\n            [np.sin(source.dec + self._sampling_width), 1]\n        ) - np.max([np.sin(source.dec - self._sampling_width), -1]))\n        self._reduced_sim['ow'] /= omega\n\n    def _weight_reduced_sim(self, reduced_sim: np.ndarray) -> np.ndarray:\n        \"\"\"Docstring\"\"\"\n        if 'weight' not in reduced_sim.dtype.names:\n            reduced_sim = rf.append_fields(\n                reduced_sim, 'weight',\n                np.zeros(len(reduced_sim)),\n                dtypes=np.float32\n            )\n\n        # Assign the weights using the newly defined \"time profile\"\n        # classes above. If you want to make this a more complicated\n        # shape, talk to me and we can work it out.\n        rescaled_energy = (reduced_sim['trueE'] / 100.e3)**self._gamma\n        reduced_sim['weight'] = reduced_sim['ow'] * rescaled_energy\n        return reduced_sim\n\n    def signal_spatial_pdf(self, source: sources.Source,\n                           events: np.ndarray) -> np.array:\n        \"\"\"Calculates the signal probability of events.\n\n        Gives a gaussian probability based on their angular distance from the\n        source object.\n\n        Args:\n            source:\n            events: An array of events including their positional data.\n\n        Returns:\n            The value for the signal spatial pdf for the given events angular\n            distances.\n        \"\"\"\n        sigma = events['angErr']\n        dist = test_statistics.angular_distance(\n            events['ra'], events['dec'], source.ra, source.dec)\n        norm = 1 / (2 * np.pi * sigma**2)\n        return norm * np.exp(-dist**2 / (2 * sigma**2))\n\n    def background_spatial_pdf(self, events: np.array) -> np.array:\n        \"\"\"Calculates the background probability of events based on their dec.\n\n        Uses the background_dec_spline() function from the given event_model to\n        get the probabilities.\n\n        Args:\n            events: An array of events including their declination.\n            event_model: Preprocessed data and simulation.\n\n        Returns:\n            The value for the background space pdf for the given events decs.\n        \"\"\"\n        bg_densities = self._background_dec_spline(events['sindec'])\n        return (1 / (2 * np.pi)) * bg_densities\n\n    def inject_background_events(self) -> np.ndarray:\n        \"\"\"Injects background events for a trial.\n\n        Args:\n            event_model: Preprocessed data and simulation.\n\n        Returns:\n            An array of injected background events.\n        \"\"\"\n        # Get the number of events we see from these runs\n        n_background_observed = np.random.poisson(self._n_background)\n\n        # How many events should we add in? This will now be based on the\n        # total number of events actually observed during these runs\n        background = np.random.choice(self._data, n_background_observed).copy()\n\n        # Randomize the background RA\n        background['ra'] = np.random.uniform(0, 2 * np.pi, len(background))\n\n        return background\n\n    def inject_signal_events(\n        self,\n        flux_norm: float,\n        n_signal_observed: Optional[int] = None,\n    ) -> np.ndarray:\n        \"\"\"Injects signal events for a trial.\n\n        Args:\n            flux_norm:\n            n_signal_observed:\n\n        Returns:\n            An array of injected signal events.\n        \"\"\"\n\n        # Pick the signal events\n        total = self._reduced_sim['weight'].sum()\n\n        if n_signal_observed is None:\n            n_signal_observed = scipy.stats.poisson.rvs(total * flux_norm)\n\n        signal = np.random.choice(\n            self._reduced_sim,\n            n_signal_observed,\n            p=self._reduced_sim['weight'] / total,\n            replace=False,\n        ).copy()\n\n        if len(signal) > 0:\n            ra, dec = self._source.sample_location(len(signal))\n\n            signal['ra'], signal['dec'] = rotate(\n                signal['trueRa'],\n                signal['trueDec'],\n                ra,\n                dec,\n                signal['ra'],\n                signal['dec'],\n            )\n\n            signal['trueRa'], signal['trueDec'] = rotate(\n                signal['trueRa'],\n                signal['trueDec'],\n                ra,\n                dec,\n                signal['trueRa'],\n                signal['trueDec'],\n            )\n\n            signal['sindec'] = np.sin(signal['dec'])\n\n        return signal\n\n    def get_ns(self, time_integrated_flux: float) -> float:\n        \"\"\"Docstring\"\"\"\n        ns = self._reduced_sim['weight'].sum() * time_integrated_flux\n        return ns\n\n    def scramble_times(self, times: np.ndarray,\n                       background: bool = True) -> np.ndarray:\n        \"\"\"Docstring\"\"\"\n        p = None\n\n        if background:\n            p = self._grl_rates / self._grl_rates.sum()\n\n        runs = np.random.choice(\n            self._grl,\n            size=len(times),\n            replace=True,\n            p=p,\n        )\n\n        return np.random.uniform(runs['start'], runs['stop'])\n\n    @property\n    def gamma(self) -> float:\n        \"\"\"Docstring\"\"\"\n        return self._gamma\n\n    @gamma.setter\n    def gamma(self, new_gamma) -> None:\n        \"\"\"Docstring\"\"\"\n        self._gamma = new_gamma\n        self._reduced_sim = self._weight_reduced_sim(self._reduced_sim)\n\n    @property\n    def source(self) -> sources.Source:\n        \"\"\"Docstring\"\"\"\n        return self._source\n\n    @source.setter\n    def source(self, new_source: sources.Source) -> None:\n        \"\"\"Docstring\"\"\"\n        self._source = new_source\n        self._init_reduced_sim(new_source)\n\n    @property\n    def data(self) -> np.ndarray:\n        \"\"\"Docstring\"\"\"\n        return self._data\n\n    @property\n    def sim(self) -> np.ndarray:\n        \"\"\"Docstring\"\"\"\n        return self._sim\n\n    @property\n    def livetime(self) -> float:\n        \"\"\"Docstring\"\"\"\n        return self._livetime\n\n    @property\n    def sampling_width(self) -> float:\n        \"\"\"Docstring\"\"\"\n        return self._sampling_width\n\n\n@dataclass\nclass TdEventModelDefaultsBase(EventModelDefaultsBase):\n    \"\"\"Docstring\"\"\"\n    background_time_profile: Optional[time_profiles.GenericProfile] = None\n    signal_time_profile: Optional[time_profiles.GenericProfile] = None\n    background_window: InitVar[float] = field(default=14)\n    withinwindow: InitVar[bool] = field(default=False)\n\n\n@dataclass\nclass TdEventModel(EventModel, TdEventModelDefaultsBase, EventModelBase):\n    \"\"\"Docstring\"\"\"\n    def __post_init__(\n        self,\n        source: sources.Source,\n        data: np.ndarray,\n        sim: np.ndarray,\n        grl: np.ndarray,\n        gamma: np.ndarray,\n        sampling_width: Optional[float],\n        background_sin_dec_bins: Union[np.array, int],\n        background_window: float,\n        withinwindow: bool,\n    ) -> None:\n        \"\"\"Initializes EventModel and calculates energy sob maps.\n\n        Args:\n            source:\n            grl:\n            background_sin_dec_bins: If an int, then the number of bins\n                spanning -1 -> 1, otherwise, a numpy array of bin edges.\n            background_window:\n            withinwindow:\n\n        Raises:\n            RuntimeError:\n        \"\"\"\n        super().__post_init__(\n            source,\n            data,\n            sim,\n            grl,\n            gamma,\n            sampling_width,\n            background_sin_dec_bins,\n        )\n\n        if self.background_time_profile is None:\n            self.background_time_profile = time_profiles.UniformProfile(\n                start=np.min(data['time']),\n                length=np.max(data['time']) - np.min(data['time']),\n            )\n\n        if self.signal_time_profile is None:\n            self.signal_time_profile = copy.deepcopy(\n                self.background_time_profile,\n            )\n\n        # Find the run contian in the background time window\n        start, stop = self.background_time_profile.range\n        return_stop_contained = True\n\n        if not withinwindow:\n            start -= background_window\n            stop = start\n            return_stop_contained = False\n\n        background_run_mask = self._contained_run_mask(\n            start,\n            stop,\n            return_stop_contained=return_stop_contained,\n        )\n\n        if not np.any(background_run_mask):\n            print('ERROR: No runs found in GRL for calculation of '\n                  'background rates!')\n            raise RuntimeError\n\n        background_grl = self._grl[background_run_mask]\n        self._n_background = background_grl['events'].sum()\n        self._n_background /= background_grl['livetime'].sum()\n        self._n_background *= self._contained_livetime(\n            *self.background_time_profile.range,\n            background_grl,\n        )\n\n    def _contained_run_mask(\n        self,\n        start: float,\n        stop: float,\n        return_stop_contained: bool = True,\n    ) -> np.ndarray:\n        \"\"\"Docstring\"\"\"\n        fully_contained = (\n            self._grl['start'] >= start\n        ) & (self._grl['stop'] < stop)\n\n        start_contained = (\n            self._grl['start'] < start\n        ) & (self._grl['stop'] > start)\n\n        if not return_stop_contained:\n            return fully_contained | start_contained\n\n        stop_contained = (\n            self._grl['start'] < stop\n        ) & (self._grl['stop'] > stop)\n\n        return fully_contained | start_contained | stop_contained\n\n    def contained_livetime(self, start: float, stop: float) -> float:\n        \"\"\"Docstring\"\"\"\n        contained_runs = self._grl[self._contained_run_mask(start, stop)]\n        return self._contained_livetime(start, stop, contained_runs)\n\n    def _contained_livetime(\n        self,\n        start: float,\n        stop: float,\n        contained_runs: np.ndarray,\n    ) -> float:\n        \"\"\"Docstring\"\"\"\n        runs_before_start = contained_runs[contained_runs['start'] < start]\n        runs_after_stop = contained_runs[contained_runs['stop'] > stop]\n        contained_livetime = contained_runs['livetime'].sum()\n\n        if len(runs_before_start) == 1:\n            contained_livetime -= start - runs_before_start['start'][0]\n\n        if len(runs_after_stop) == 1:\n            contained_livetime -= runs_after_stop['stop'][0] - stop\n\n        return contained_livetime\n\n    def scramble_times(self, times: np.ndarray,\n                       background: bool = True) -> np.ndarray:\n        \"\"\"Docstring\"\"\"\n        if background:\n            profile = self.background_time_profile\n        else:\n            profile = self.signal_time_profile\n\n        grl_start_cdf = profile.cdf(\n            self._grl['start'])\n        grl_stop_cdf = profile.cdf(\n            self._grl['stop'])\n\n        valid = np.logical_and(grl_start_cdf < 1, grl_stop_cdf > 0)\n        grl_weighted_rates = grl_stop_cdf[valid] - grl_start_cdf[valid]\n\n        if background:\n            grl_weighted_rates *= self._grl_rates[valid]\n\n        runs = np.random.choice(\n            self._grl[valid],\n            size=len(times),\n            replace=True,\n            p=grl_weighted_rates / grl_weighted_rates.sum(),\n        )\n\n        return profile.inverse_transform_sample(runs['start'], runs['stop'])\n", "meta": {"hexsha": "20fc502ab79aa107b01c55256361bb4a8687ce77", "size": 22244, "ext": "py", "lang": "Python", "max_stars_repo_path": "mla/_models.py", "max_stars_repo_name": "thejevans/mla", "max_stars_repo_head_hexsha": "0c583741cfc7626b0653bf58f4efaa1e7681424c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-20T15:47:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-20T15:47:00.000Z", "max_issues_repo_path": "mla/_models.py", "max_issues_repo_name": "thejevans/mla", "max_issues_repo_head_hexsha": "0c583741cfc7626b0653bf58f4efaa1e7681424c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-27T02:23:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T20:14:24.000Z", "max_forks_repo_path": "mla/_models.py", "max_forks_repo_name": "thejevans/mla", "max_forks_repo_head_hexsha": "0c583741cfc7626b0653bf58f4efaa1e7681424c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.808259587, "max_line_length": 79, "alphanum_fraction": 0.5945873044, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 5248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.17291854322284556}}
{"text": "#!/usr/bin/python\n#\n# Simulates an MDP-Strategy\n\nimport math\nimport os\nimport sys, code\nimport resource\nimport copy\nimport itertools\nimport random\nfrom PIL import Image\nimport os, pygame, pygame.locals\nfrom pybrain3.rl.environments import Environment\nfrom pybrain3.rl.environments import Task\nfrom pybrain3.rl.agents import LearningAgent\nfrom pybrain3.rl.experiments import Experiment\nfrom my_pybrain.my_explorer import MyUCBExplorer\nfrom my_pybrain.my_explorer import MyGreedyExplorer\nfrom my_pybrain.my_table import MyActionValueTable\nfrom my_pybrain.my_learner import MyQ, SARSA\nfrom pybrain3.utilities import abstractMethod\n\nimport numpy as np\nfrom itertools import product\nfrom copy import deepcopy\nfrom scipy import argmax\nfrom scipy import where\nfrom random import choice\nimport importlib\n\n# from scenario_9x9_shield_multi3 import Shield\n# from cycling_enemy_shield_incl_enemy_multi3 import Shield\n\nnp.set_printoptions(threshold=np.inf)\n\nimport argparse\n\nparser = argparse.ArgumentParser(description='Simulator')\nparser.add_argument(dest=\"png_file_base\")\nparser.add_argument(\"-c\", \"--collect-data\", dest=\"collect_data_file\", help=\"Provide a file for collecting convergence data\")\nparser.add_argument('-g', \"--gen-spec\", dest='gen_spec', help='Generate shield files', action='store_true', default=False)\nparser.add_argument('-l', \"--load\", dest='load_file', help='Load Q-Table from file')\nparser.add_argument('-s', \"--save\", dest='save_file', help='Save Q-Table to file')\nparser.add_argument('-t', \"--train\", dest='train', help='Training activated', type=float, default=.2)\nparser.add_argument('-o', \"--shield_options\", dest='shield_options', help='Number of actions the shield can choose of. 0 disables the shield', type=int, default=1)\nparser.add_argument('-n', \"--negative-reward\", dest='neg_reward', help='Indicated whether negative reward should be used for unsafe actions', action='store_true', default=False)\nparser.add_argument('-p', \"--huge-negative-reward\", dest='huge_neg_reward', help='Indicated whether a huge negative reward should be used for unsafe actions', action='store_true', default=False)\nparser.add_argument('-r', \"--sarsa\", dest='sarsa', help='Indicated whether to use SARSA or default Q-learning', action='store_true', default=False)\nparser.add_argument(\"--num-steps\", dest='num_steps', help='Number of interactions', type=int, default=1000000)\n\nargs = parser.parse_args()\n\ncollect_data_file = args.collect_data_file\ngen_spec = args.gen_spec\nspecFile = args.png_file_base\nshield_options = args.shield_options\nload_file = args.load_file\nsave_file = args.save_file\nexploration = args.train\nneg_reward = args.neg_reward\nhuge_neg_reward = args.huge_neg_reward\nMAX_STEPS = args.num_steps\n\npngfile = Image.open(specFile)\npngFileBasis = specFile[0:specFile.rfind(\".png\")]\npath = pngFileBasis[:pngFileBasis.rfind(os.path.sep)]\n\n# ==================================\n# Settings\n# ==================================\nMAGNIFY = 64\n\n# ==================================\n# Read parameter file\n# ==================================\nparameterFileName = pngFileBasis+\".params\"\nallParams = {}\nfor a in open(parameterFileName,\"r\").readlines():\n    a = a.strip()\n    if len(a)>0 and a[0]!='#':\n        posEqual = a.index(\"=\")\n        allParams[a[0:posEqual].strip()] = a[posEqual+1:].strip()\n\n# ==================================            \n# Parse parameter file\n# ==================================\ninitX = int(allParams[\"initX\"])\ninitY = int(allParams[\"initY\"])\npositionUpdateNoise = float(allParams[\"positionUpdateNoise\"])\nWALL = int(allParams[\"wall\"])\nNORMAL_FIELD = int(allParams[\"normalField\"])\nNUMBER_OF_COLORS = int(allParams[\"numberOfColors\"])\n\nenemies_enabled = False\nif \"enemies\" in allParams:\n    try:\n        mode_name = allParams[\"enemies\"]\n        mode_name = path + \".\" + mode_name[:mode_name.rfind(\".py\")]\n        enemy_handler = importlib.import_module(mode_name.replace(os.path.sep, \".\")).EnemyHandler()\n        enemies_enabled = True\n    except ImportError as e:\n        print (\"Could not find file \" + enemy_handler_file)\n        print (e)\n        exit()\n\nbombs = []\nif \"bombs\" in allParams:\n    # careful with evil evals\n    bombs = eval(allParams[\"bombs\"])\nelse:\n    bombs = []\n\n# ==================================\n# Read input image\n# ==================================\n\nif shield_options > 0:\n    try:\n        mod_name = pngFileBasis + \"_\" + str(shield_options)\n        Shield = importlib.import_module(mod_name.replace(os.path.sep, \".\")).Shield\n    except ImportError as e:\n        print (\"Could not find file \" + pngFileBasis + \"_\" + str(shield_options) + \".py\")\n        print (e)\n        exit()\n\nelse:\n    from no_shield import Shield\n    \n\n\nxsize = pngfile.size[0]\nysize = pngfile.size[1]\nimageData = pngfile.getdata()\npalette = pngfile.getpalette()\n\n# for i in range(len(imageData)):\n#     print (imageData[i])\n    \nif \"colorOrder\" in allParams:\n    colors = eval(allParams[\"colorOrder\"])\nelse:\n    assert(max(imageData) == NUMBER_OF_COLORS + 1)\n    colors = range(max(imageData) + 1)\n    colors.remove(WALL) \n    colors.remove(NORMAL_FIELD)\n\n# ==================================\n# Construct MDP --> States\n# ==================================\nstateMapper = {}\nfor xA in range(0,xsize):\n    for yA in range(0,ysize):\n        for (csf,payoff) in [(x, 0) for x in range(NUMBER_OF_COLORS)] + [(0,1)]:\n            if (imageData[xA+yA*xsize]!=WALL):\n                stateNum = len(stateMapper)                    \n                stateMapper[(xA,yA,csf,payoff)] = stateNum\n\n# print (stateMapper)\nBAD_STATE = len(stateMapper)\n# Add error state\nerrorState = len(stateMapper)\nerrorStateKey = (-1,-1,0,0)\nstateMapper[errorStateKey] = errorState\n\n\n# ==================================\n# Construct MDP --> Transition file\n# ==================================\n\n# First, a function that computes the possible/likely\n# transitions when going from a (x,y)-cell into some\n# direction. It computes the image of the complete cell\n# and then performs probability-weighting according to\n# the areas of overlap\ndef computeSuccs(xpos,ypos,direction):\n\n    # If direction is \"4\", this means no move\n    if (direction==4):\n        return [(xpos,ypos,1.0)]\n\n    finalSuccs = []\n    errorProb = 0.0\n    if (direction==0):\n        succs = [(xpos+1,ypos),(xpos+1,ypos+1)]\n    elif (direction==1):\n        succs = [(xpos,ypos+1),(xpos-1,ypos+1)]\n    elif (direction==2):\n        succs = [(xpos-1,ypos),(xpos-1,ypos-1)]\n    elif (direction==3):\n        succs = [(xpos,ypos-1),(xpos+1,ypos-1)]\n    \n    if succs[0][0]<0:\n        errorProb += 1-positionUpdateNoise\n    elif succs[0][0]>=xsize:\n        errorProb += 1-positionUpdateNoise\n    elif succs[0][1]<0:\n        errorProb += 1-positionUpdateNoise\n    elif succs[0][1]>=ysize:\n        errorProb += 1-positionUpdateNoise\n    else:\n        finalSuccs.append((succs[0][0],succs[0][1],1-positionUpdateNoise))\n\n    if succs[1][0]<0:\n        errorProb += positionUpdateNoise\n    elif succs[1][0]>=xsize:\n        errorProb += positionUpdateNoise\n    elif succs[1][1]<0:\n        errorProb += positionUpdateNoise\n    elif succs[1][1]>=ysize:\n        errorProb += positionUpdateNoise\n    else:\n        finalSuccs.append((succs[1][0],succs[1][1],positionUpdateNoise))\n\n    if errorProb>0.0:\n        finalSuccs.append((-1,-1,errorProb))\n        \n    return finalSuccs\n    \n                        \n# Iterate over all cells and compute transition probabilities\ntransitionLines = []\noverallNofTransitions = 0\nfor xA in range(0,xsize):\n    for yA in range(0,ysize):\n        for (csf,payoff) in [(x,0) for x in range(NUMBER_OF_COLORS)] + [(0,1)]:\n            if (imageData[xA+yA*xsize]!=WALL):\n                sourceState = stateMapper[(xA,yA,csf,payoff)]\n                overallNofTransitions += 5\n                for dirA in [0,1,2,3,4]: # Action 4 is standing still\n                    errorProb = 0\n                    succA = computeSuccs(xA,yA,dirA)\n                    for (destXA,destYA,probA) in succA:\n                        if destXA==-1:\n                            errorProb += probA\n                        elif (imageData[destXA+destYA*xsize]==WALL):\n                            errorProb += probA\n                        else:\n                            if imageData[destXA+destYA*xsize]==colors[csf]:\n                                csfPrime = csf + 1\n                                payoffPrime = 1\n                            else:\n                                csfPrime = csf\n                                payoffPrime = 0\n                            if csfPrime==NUMBER_OF_COLORS:\n                                csfPrime = 0\n                            else:\n                                payoffPrime = 0\n                                \n                            # transitionLines.append([sourceState,dirA,stateMapper[(destXA,destYA,csfPrime,payoffPrime)],probA*0.99999])\n                            transitionLines.append([sourceState,dirA,stateMapper[(destXA,destYA,csfPrime,payoffPrime)],probA])\n                    # errorProb += 0.00001*(1-errorProb)\n                    if errorProb>0:\n                        transitionLines.append([sourceState,dirA,errorState,errorProb])\n     \n# ==================================\n# Prepare reverse state mapper and\n# Searchable transition list\n# ==================================\nreverseStateMapper = {}\nfor (a,b) in stateMapper.items():\n    reverseStateMapper[b] = a\ntransitionLists = {}\nfor (a,b,c,d) in transitionLines:\n    if not (a,b) in transitionLists:\n        transitionLists[(a,b)] = [(c,d)]\n    else:\n        transitionLists[(a,b)].append((c,d))\n        \nNUMBER_OF_BITS = int(math.ceil(math.log((len(reverseStateMapper) - 1) / (NUMBER_OF_COLORS + 1), 2))) \n# print (\"Number of bits for states:\", NUMBER_OF_BITS)\ndanger_zone = [(7, 6), (7, 7), (7, 8), (8, 6), (8, 7), (8, 8), (9, 6), (9, 7), (9, 8)]\nmax_steps_in_zone = 3\n\nnum_steps_on_bomb = 3\n\n# recharging_zone = [(5, 10)]\n# max_steps_in_zone = 20\n# danger_zone = []\n# for state in xrange(0, len(reverseStateMapper) - 1, 5): #exclude error state\n#     (x, y, _, _) = reverseStateMapper[state]\n#     danger_zone.append((x,y))\n\n# danger_zone = [(7, 6), (7, 7), (8, 6), (8, 7)]\n# max_steps_in_zone = 3\n\nif gen_spec:\n    with open(\"avoid_walls_shield.dfa\", \"w\") as file:\n        directions = [0, 1, 2, 3]\n        transitions = []\n        \n        for combination in sum([list(map(list, itertools.combinations(directions, i))) for i in range(5)], []):\n            sensors_enc = [str(x + 1 if x in combination else -(x + 1)) for x in directions]\n            for action in range(4):\n                action_enc = [str(-(idx + 5) if x == '0' else (idx + 5)) for idx, x in enumerate(list(bin(action)[2:].rjust(3, '0')))]\n                target_state = 1 if action not in combination else 2\n                transitions.append(\"1 {0} {1} {2}\\n\".format(target_state, \" \".join(sensors_enc), \" \".join(action_enc)))\n        action_enc = [str(-(idx + 5) if x == '0' else (idx + 5)) for idx, x in enumerate(list(bin(4)[2:].rjust(3, '0')))]\n        transitions.append(\"1 1 {0}\\n\".format(\" \".join(action_enc)))\n\n        #print unused action transitions\n        for action in range(5, 8):\n            action_enc = [str(-(idx + 5) if x == '0' else (idx + 5)) for idx, x in enumerate(list(bin(action)[2:].rjust(3, '0')))]\n            transitions.append(\"1 2 {0}\\n\".format(\" \".join(action_enc)))\n            \n        # print 'bad' state loop\n        transitions.append(\"2 2\\n\")\n            \n        #print header & start/end states\n        file.write(\"dfa 2 4 3 1 1 {0}\\n1\\n2\\n\".format(len(transitions)))\n        \n        #print transitions\n        file.write(\"\".join(transitions))        \n        file.write(\"1 sensor_right\\n\")\n        file.write(\"2 sensor_down\\n\")\n        file.write(\"3 sensor_left\\n\")\n        file.write(\"4 sensor_up\\n\")\n        \n        for bit in range(1, 4):\n            file.write(\"{0} o{1}\\n\".format(4 + bit, 4 - bit))\n        \n    \n   \n            \n    #shield preventing collision with second robot\n    with open(\"enemy_shield.dfa\", \"w\") as file:\n        #\n        # x x x x x  1  6 11 16 21\n        # x x x x x  2  7 12 17 22\n        # x x o x x  3  8 13 18 23\n        # x x x x x  4  9 14 19 24\n        # x x x x x  5 10 15 20 25\n        #\n        # state 0 means no enemy in range\n        \n        transitions = []\n        unused_states = [0, 13]\n        for (enemy_x, enemy_y) in list(product(range(1, 6), repeat=2)):\n            if enemy_x == 3 and enemy_y == 3:\n                continue\n            enemy_state = 5 * (enemy_x - 1) + enemy_y\n            if abs(enemy_x - 3) + abs(enemy_y - 3) > 2:\n                unused_states.append(enemy_state)\n                continue\n            num_state_bits = 5\n            for action in range(4):\n                action_allowed = True\n                for enemy_action in range(5):\n                    enemy_next = filter(lambda t: t[0] != -1, list(map(lambda t: (t[0], t[1]) if t[2] > 0 else (-1, -1), computeSuccs(enemy_x, enemy_y, enemy_action))))\n                    next = filter(lambda t: t[0] != -1, list(map(lambda t: (t[0], t[1]) if t[2] > 0 else (-1, -1), computeSuccs(3, 3, action))))\n                \n                    intersection = set(next).intersection(set(enemy_next))\n                    if len(intersection) > 0:\n                        action_allowed = False\n                        break\n                state_enc = [str(-(idx + 1) if x == '0' else (idx + 1)) for idx, x in enumerate(list(bin(enemy_state)[2:].rjust(num_state_bits, '0')))]\n                action_enc = [str(-(idx + 1 + num_state_bits) if x == '0' else (idx + 1 + num_state_bits)) for idx, x in enumerate(list(bin(action)[2:].rjust(3, '0')))]\n                \n                transitions.append(\"1 {0} {1} {2}\\n\".format(1 if action_allowed else 2, \" \".join(state_enc), \" \".join(action_enc)))\n                \n        action_enc = [str(-(idx + 1 + num_state_bits) if x == '0' else (idx + 1 + num_state_bits)) for idx, x in enumerate(list(bin(4)[2:].rjust(3, '0')))]\n        transitions.append(\"1 1 \" + \" \".join(action_enc) + \"\\n\")\n  #              \n        #print unused action transitions\n        for action in range(5, 8):\n            action_enc = [str(-(idx + 1 + num_state_bits) if x == '0' else (idx + 1 + num_state_bits)) for idx, x in enumerate(list(bin(action)[2:].rjust(3, '0')))]\n            transitions.append(\"1 2 \" + \" \".join(action_enc) + \"\\n\")\n        \n        for state in unused_states:\n            state_enc = [str(-(idx + 1) if x == '0' else (idx + 1)) for idx, x in enumerate(list(bin(state)[2:].rjust(num_state_bits, '0')))]\n            transitions.append(\"1 1 \" + \" \".join(state_enc) + \"\\n\")\n        \n        #print ununsed state transitions\n        for state in range(26, int(math.pow(2, num_state_bits))):\n            state_enc = [str(-(idx + 1) if x == '0' else (idx + 1)) for idx, x in enumerate(list(bin(state)[2:].rjust(num_state_bits, '0')))]\n            transitions.append(\"1 1 \" + \" \".join(state_enc) + \"\\n\")\n        \n        #print final state transition\n        transitions.append(\"2 2\\n\")\n        \n        # print header\n        file.write(\"dfa 2 {0} 3 1 1 {1}\\n1\\n2\\n\".format(num_state_bits, len(transitions)))\n        \n        #print transitions\n        for transition in transitions:\n            file.write(transition)\n                \n        # print labels\n        for bit in range(1, num_state_bits + 1):\n            file.write(\"{0} e{1}\\n\".format(bit, num_state_bits + 1 - bit))\n        for bit in range(1, 4):\n            file.write(\"{0} o{1}\\n\".format(num_state_bits + bit, 4 - bit))\n        \n    with open(\"bomb_shield.dfa\", \"w\") as file:\n        \n        transitions = []\n        for state in range(1, num_steps_on_bomb + 1):\n            transitions.append(\"{0} 1 -1\".format(state))\n            \n            actions = range(8)\n            actions.remove(4) # remove stay\n            for action in actions:\n                action_enc = [str(-(idx + 2) if x == '0' else (idx + 2)) for idx, x in enumerate(list(bin(action)[2:].rjust(3, '0')))]\n                transitions.append(\"{0} 1 1 {1}\".format(state, \" \".join(action_enc)))\n            \n            action_enc = [str(-(idx + 2) if x == '0' else (idx + 2)) for idx, x in enumerate(list(bin(4)[2:].rjust(3, '0')))]\n            transitions.append(\"{0} {1} 1 {2}\".format(state, state + 1, \" \".join(action_enc)))\n            \n        transitions.append(\"{0} {0}\".format(num_steps_on_bomb + 1))\n                \n        file.write(\"dfa {0} 1 3 1 1 {1}\\n1\\n{0}\\n\".format(num_steps_on_bomb + 1, len(transitions)))\n        file.write(\"\\n\".join(transitions))\n        file.write(\"\\n1 b\\n\")\n        for bit in range(1, 4):\n            file.write(\"{0} o{1}\\n\".format(1 + bit, 4 - bit))\n    \n    #shield for danger zones\n    with open(\"danger_zone_shield.dfa\", \"w\") as file:\n        zone = set(danger_zone)\n        zones = {}\n        #compute zones:\n        current_zone = 1\n        while len(zone) > 0:\n            zones[current_zone] = set()\n            for (x, y) in zone:\n                at_boundary = False\n                for action in range(4):\n                    # we are looking for an action which leads for sure out of the danger zone\n                    succs = computeSuccs(x, y, action)\n                    at_boundary = True\n                    for (new_x, new_y, prob) in succs:\n                        if prob > 0 and ((new_x,new_y) in zone or (new_x,new_y,0,0) not in stateMapper):\n                            # in the danger zone\n                            at_boundary = False\n                            break\n                    if at_boundary:\n                        break\n                if at_boundary:\n                   zones[current_zone].add((x,y))\n                    \n            zone -= zones[current_zone]\n            current_zone += 1\n        \n        # print (zones)\n        \n        end_state = max_steps_in_zone + 1\n        transitions = []\n        num_state_bits = 7\n        for num_steps_in_zone in range(1,end_state):\n            print (\"state \" + str(num_steps_in_zone))\n            for state in xrange(0, len(reverseStateMapper) - 1, 5): #exclude error state\n                (x,y,_,_) = reverseStateMapper[state]\n                state_enc = [str(-(idx + 1) if bit == '0' else (idx + 1)) for idx, bit in enumerate(list(bin(state / 5)[2:].rjust(num_state_bits, '0')))]\n                zone_idx = 0\n                for idx, zone in zones.iteritems():\n                    if (x,y) in zone:\n                        zone_idx = idx\n                        break\n        \n                if zone_idx == 0:\n                    transitions.append(\"{0} 1 {1}\\n\".format(num_steps_in_zone, \" \".join(state_enc)))\n                    continue\n                max_acceptable_zone = max_steps_in_zone - num_steps_in_zone # maximal acceptable zone as target\n                if zone_idx < max_acceptable_zone or max(zones.keys()) <= max_acceptable_zone:\n                    transitions.append(\"{0} {1} {2}\\n\".format(num_steps_in_zone, num_steps_in_zone + 1, \" \".join(state_enc)))\n                    continue\n                \n                print( \"max_zone: \" + str(max_acceptable_zone))\n                if zone_idx <= max_acceptable_zone + 1:\n                    for action in range(5):\n                        succs = computeSuccs(x, y, action)\n                        next_zone_idx = 0\n                        for (next_x,next_y,prob) in succs:\n                            if prob == 0: continue\n                            for idx, zone in zones.iteritems():\n                                if (next_x,next_y) in zone:\n                                    next_zone_idx = max(next_zone_idx, idx)\n                        print( \"action \" + str(action) + \" leads to zone: \" + str(next_zone_idx))\n                        next_state = end_state if next_zone_idx > max_acceptable_zone else (num_steps_in_zone + 1 if next_zone_idx > 0 else 1)\n                        action_enc = [str(-(idx + 1 + num_state_bits) if bit == '0' else (idx + 1 + num_state_bits)) for idx, bit in enumerate(list(bin(action)[2:].rjust(3, '0')))]\n                        transitions.append(\"{0} {1} {2} {3}\\n\".format(num_steps_in_zone, next_state, \" \".join(state_enc), \" \".join(action_enc)))\n                    for action in range(5,8):\n                        action_enc = [str(-(idx + 1 + num_state_bits) if bit == '0' else (idx + 1 + num_state_bits)) for idx, bit in enumerate(list(bin(action)[2:].rjust(3, '0')))]\n                        transitions.append(\"{0} {1} {2} {3}\\n\".format(num_steps_in_zone, end_state, \" \".join(state_enc), \" \".join(action_enc)))\n                        \n                    continue\n                \n                # this should never happen .. do whatever we want to\n                transitions.append(\"{0} 1 {1}\\n\".format(num_steps_in_zone, \" \".join(state_enc)))\n          \n            #print ununsed state transitions\n            for state in xrange((len(reverseStateMapper) - 1) / 5, int(math.pow(2, num_state_bits))):\n                state_enc = [str(-(idx + 1) if x == '0' else (idx + 1)) for idx, x in enumerate(list(bin(state)[2:].rjust(num_state_bits, '0')))]\n                transitions.append(\"{0} 1 {1}\\n\".format(num_steps_in_zone, \" \".join(state_enc)))\n             \n            \n        transitions.append(\"{0} {0}\\n\".format(end_state))\n        # print header\n        file.write(\"dfa {0} {1} 3 1 1 {2}\\n1\\n{0}\\n\".format(num_steps_in_zone + 1, num_state_bits, len(transitions)))\n        \n        #print transitions\n        for transition in transitions:\n            file.write(transition)\n                \n        # print labels\n        for bit in range(1, num_state_bits + 1):\n            file.write(\"{0} i{1}\\n\".format(bit, num_state_bits + 1 - bit))\n        for bit in range(1, 4):\n            file.write(\"{0} o{1}\\n\".format(num_state_bits + bit, 4 - bit))\n                \n    exit()\n        \n# =========================================\n# Initialize interactive display\n# =========================================\npygame.init()\ndisplayInfo = pygame.display.Info()\nMAGNIFY = min(MAGNIFY,displayInfo.current_w*3/4/xsize)\nMAGNIFY = min(MAGNIFY,displayInfo.current_h*3/4/ysize)\n\n\nclass Map(Environment):\n    def __init__(self):\n        self.reset()\n        \n    def reset(self):\n        # print \"reset called\"\n        self.state = 0\n        self.penalty = 0\n        \n    def performAction(self, action):   \n        error = len(reverseStateMapper) - 1\n        # action = int(action[0])\n        \n        \n        actions = action[action != -1]\n        actions = list(map(int, actions))\n        \n        # print action\n        # state_enc = map(int, list(bin(self.state / (NUMBER_OF_COLORS + 1))[2:].rjust(NUMBER_OF_BITS, '0')))\n        \n        encoded_actions = []\n        for a in actions:\n            encoded_actions.append(list(map(int, list(bin(a)[2:].rjust(3, '0')))))\n            \n        (robotXA, robotYA, csf, payoff) = reverseStateMapper[self.state]\n        \n        # simulate sensors\n        state_enc = []\n        for a in range(4):\n            # print computeSuccs(robotXA, robotYA, a)\n            succs = filter(lambda t: t[2] > 0, computeSuccs(robotXA, robotYA, a))\n            valid = True\n            for succ in succs:\n                if succ[0] == -1 or not (succ[0], succ[1], 0, 0) in stateMapper:\n                    valid = False\n                    break\n            state_enc.append(0 if valid else 1)\n            \n                \n        # print state_enc\n # print \"action\" + str(encoded_actions[0])\n        \n        if enemies_enabled:\n            enemy_state = 0\n            (robotXA,robotYA,csf,payoff) = reverseStateMapper[level.state]\n            for enemy in enemy_handler.getEnemyPositions():\n                x_diff = abs(enemy[0] - robotXA)\n                y_diff = abs(enemy[1] - robotYA)\n                if x_diff + y_diff <= 2:\n                    enemy_state = (enemy[0] - robotXA + 2) * 5 + (enemy[1] - robotYA + 3)\n                    break        \n            enemy_state_enc = list(map(int, list(bin(enemy_state)[2:].rjust(5, '0'))))\n        \n            state_enc.extend(enemy_state_enc)\n                    \n        # print \"Colors seen so far:\", csf\n        if len(bombs) > 0:\n            state_enc.append(1 if (robotXA + 1, robotYA + 1) in bombs else 0)\n        for enc_action in encoded_actions:\n            state_enc.extend(enc_action)\n \n        # print state_enc\n        corr_action = shield.tick(state_enc)\n\n        # print corr_action\n                \n        corr_action = int(\"\".join(list(map(str, corr_action[:len(corr_action) -1]))), 2)\n\n\n        if (actions[0] != corr_action) and huge_neg_reward:\n            self.penalty += 1.\n\n        if (actions[0] != corr_action) and neg_reward and args.sarsa:\n            self.penalty += 0.1\n            # qvalue = self.module.getValue(self.laststate, action)\n            # self.module.updateValue(self.laststate, action, qvalue + self.alpha * ((-1 if self.neg_reward else self.lastreward) - qvalue))\n            #experiment.acc_reward -= .3\n        #     print False\n        used_actions = []\n        for a in actions:\n            if a == corr_action: break\n            used_actions.append(a)\n            # learner.explorer.n_values.params.reshape(learner.explorer.n_values.numRows,learner.explorer.n_values.numColumns)[self.state, a] += 1\n        if huge_neg_reward:\n            action = actions[0]\n        else:\n            action = corr_action\n        \n        used_actions.append(action)\n        \n        while len(used_actions) < 5:\n            used_actions.append(-1)\n                \n        agent.lastaction = used_actions\n       \n        transitionList = transitionLists[(self.state, action)]\n        \n        dest = None\n        randomNumber = random.random()\n        for (a,b) in transitionList:\n            if randomNumber<=b:\n                dest = a\n                randomNumber = 123.0\n            else:\n                randomNumber -= b\n        # Rounding error?\n        if (dest==None):\n            dest = transitionList[0][0]\n             \n        if dest == len(reverseStateMapper) - 1: \n            experiment.acc_reward -= 1\n            self.penalty += 1\n            # self.reset()\n            if shield_options > 0 and not args.huge_neg_reward:\n                print (\"Shields are not allowed to make errors!\")\n                exit()\n            transitionList = transitionLists[(self.state, 4)]\n            dest = None\n            randomNumber = random.random()\n            for (a,b) in transitionList:\n                if randomNumber<=b:\n                    dest = a\n                    randomNumber = 123.0\n                else:\n                    randomNumber -= b\n            # Rounding error?\n            if (dest==None):\n                dest = transitionList[0][0]\n            \n        # learner.explorer.n_values.params.reshape(learner.explorer.n_values.numRows,learner.explorer.n_values.numColumns)[self.state, action] += 1\n        \n        self.state = dest\n            \n    def getSensors(self):\n        return [self.state]\n        \nclass VisitAllColors(Task):\n    def __init__(self, env):\n        Task.__init__(self, env)\n        self.last_reward = 0\n        \n    def getReward(self):\n        # if (reverseStateMapper[self.env.state][3] != 0):\n        # print \"all colors visited\"\n        ret = self.last_reward\n        self.last_reward = reverseStateMapper[self.env.state][3] - self.env.penalty\n        self.env.penalty = 0\n        return self.last_reward\n\n        \nclass MyExperiment(Experiment):\n    def __init__(self, task, agent):\n        Experiment.__init__(self, task, agent)\n        \n        agent.learner.explorer.experiment = self\n        # agent.learner.module.getValue()\n        \n        self.screen = pygame.display.set_mode(((xsize+2)*MAGNIFY,(ysize+2)*MAGNIFY))\n        pygame.display.set_caption('Policy Visualizer')\n        self.clock = pygame.time.Clock()\n\n        self.screenBuffer = pygame.Surface(self.screen.get_size())\n        self.screenBuffer = self.screenBuffer.convert()\n        self.screenBuffer.fill((64, 64, 64)) # Dark Gray\n        \n        self.bombImage = pygame.image.load(\"bomb_image.png\")\n        self.bombImage = pygame.transform.scale(self.bombImage, (MAGNIFY - 2, MAGNIFY - 2))\n\n    \n        self.isPaused = False\n        self.isCrashed = False\n        self.speed = 10\n        self.num = 0\n        self.robotXA = -1\n        self.robotYA = -1\n        self.bomb_counter = 0\n        \n        self.count = 0\n        self.acc_reward = 0\n        self.collect_data = False\n        if collect_data_file != None:\n            self.collect_data = True\n            self.collect_episode_data_file = open(collect_data_file + \"_episodelen.data\", \"w\")\n            self.collect_reward_data_file = open(collect_data_file + \"_avg_reward.data\", \"w\")\n    \n    def _oneInteraction(self):\n        global draw\n        \n        resetInThisRound = False\n        \n        # Process events\n        for event in pygame.event.get():\n            if event.type == pygame.locals.QUIT or (event.type == pygame.locals.KEYDOWN and event.key in [pygame.locals.K_ESCAPE,pygame.locals.K_q]):\n                return\n            if (event.type == pygame.locals.KEYDOWN and event.key == pygame.locals.K_SPACE):\n                controller.params.reshape(controller.numRows, controller.numColumns).tofile(\"test.table\")\n                self.isPaused = not self.isPaused\n            if (event.type == pygame.locals.KEYDOWN and event.key == pygame.locals.K_r):\n                resetInThisRound = True\n            if (event.type == pygame.locals.KEYDOWN and event.key == pygame.locals.K_PLUS):\n                self.speed += 1\n            if (event.type == pygame.locals.KEYDOWN and event.key == pygame.locals.K_MINUS):\n                self.speed = max(self.speed-1,1)\n            if (event.type == pygame.locals.KEYDOWN and event.key == pygame.locals.K_d):\n                draw = not draw\n            \n        # if self.isCrashed:\n  #           self.isCrashed = False\n  #           # level.reset()\n  # \n        # Update \n        if resetInThisRound:\n            print (\"reset\")\n            level.reset()\n\n                \n        old = (self.robotXA, self.robotYA)\n        (self.robotXA,self.robotYA,csf,payoff) = reverseStateMapper[level.state]\n        \n        if not self.isCrashed and enemies_enabled:\n            enemy_handler.update(old)\n            for e in enemy_handler.getEnemyPositions():\n                if (self.robotXA, self.robotYA) == e:\n                    self.isCrashed = True\n                    level.penalty += 1\n                    self.acc_reward -= 1\n                    if shield_options > 0 and not args.huge_neg_reward:\n                        print (\"Shields are not allowed to make errors!\")\n                        exit()\n                    break\n        \n        if (self.robotXA + 1, self.robotYA + 1) in bombs:\n            self.bomb_counter += 1\n            if self.bomb_counter == 4:\n                self.isCrashed = True\n                level.penalty += 1\n                self.acc_reward -= 1\n                if shield_options > 0 and not args.huge_neg_reward:\n                    print (\"Shields are not allowed to make errors!\")\n                    exit()\n        else:\n            self.bomb_counter = 0\n\n        if draw:\n            q_max = 0\n            for state in range(len(reverseStateMapper) - 1):\n                q_max = max(q_max, max(controller.getActionValues(state)))\n                \n            # Draw Field\n            for x in xrange(0,xsize):\n                for y in xrange(0,ysize):\n                    paletteColor = imageData[y*xsize+x]\n                    color = palette[paletteColor*3:paletteColor*3+3]\n                    pygame.draw.rect(self.screenBuffer,color,((x+1)*MAGNIFY,(y+1)*MAGNIFY,MAGNIFY,MAGNIFY),0)\n        \n            # Draw boundary\n            if self.robotXA==-1 or self.isCrashed:\n                boundaryColor = (255,0,0)\n            else:\n                boundaryColor = (64,64,64)\n            pygame.draw.rect(self.screenBuffer,boundaryColor,(0,0,MAGNIFY*(xsize+2),MAGNIFY),0)\n            pygame.draw.rect(self.screenBuffer,boundaryColor,(0,MAGNIFY,MAGNIFY,MAGNIFY*(ysize+1)),0)\n            pygame.draw.rect(self.screenBuffer,boundaryColor,(MAGNIFY*(xsize+1),MAGNIFY,MAGNIFY,MAGNIFY*(ysize+1)),0)\n            pygame.draw.rect(self.screenBuffer,boundaryColor,(MAGNIFY,MAGNIFY*(ysize+1),MAGNIFY*xsize,MAGNIFY),0)\n            # pygame.draw.rect(screenBuffer,boundaryColor,(0,0,MAGNIFY*(xsize+2),MAGNIFY),0)\n\n            # Draw cell frames\n            for x in xrange(0,xsize):\n                for y in xrange(0,ysize):\n                    pygame.draw.rect(self.screenBuffer,(0,0,0),((x+1)*MAGNIFY,(y+1)*MAGNIFY,MAGNIFY,MAGNIFY),1)\n                    if (x+1,y+1) in bombs:\n                        self.screenBuffer.blit(self.bombImage, ((x+1)*MAGNIFY+1,(y+1)*MAGNIFY+1))\n            pygame.draw.rect(self.screenBuffer,(0,0,0),(MAGNIFY-1,MAGNIFY-1,MAGNIFY*xsize+2,MAGNIFY*ysize+2),1)\n\n            # Draw \"Good\" Robot\n            if self.robotXA!=-1:\n                pygame.draw.circle(self.screenBuffer, (192,32,32), ((self.robotXA+1)*MAGNIFY+MAGNIFY/2,(self.robotYA+1)*MAGNIFY+MAGNIFY/2) , MAGNIFY/3-2, 0)\n                pygame.draw.circle(self.screenBuffer, (255,255,255), ((self.robotXA+1)*MAGNIFY+MAGNIFY/2,(self.robotYA+1)*MAGNIFY+MAGNIFY/2) , MAGNIFY/3-1, 1)\n                pygame.draw.circle(self.screenBuffer, (0,0,0), ((self.robotXA+1)*MAGNIFY+MAGNIFY/2,(self.robotYA+1)*MAGNIFY+MAGNIFY/2) , MAGNIFY/3, 1)\n\n            # Draw \"Bad\" Robots\n            if enemies_enabled:\n                for (e_x, e_y) in enemy_handler.getEnemyPositions():\n                    pygame.draw.circle(self.screenBuffer, (32,32,192), ((e_x+1)*MAGNIFY+MAGNIFY/2,(e_y+1)*MAGNIFY+MAGNIFY/2) , MAGNIFY/3-2, 0)\n                    pygame.draw.circle(self.screenBuffer, (255,255,255), ((e_x+1)*MAGNIFY+MAGNIFY/2,(e_y+1)*MAGNIFY+MAGNIFY/2) , MAGNIFY/3-1, 1)\n                    pygame.draw.circle(self.screenBuffer, (0,0,0), ((e_x+1)*MAGNIFY+MAGNIFY/2,(e_y+1)*MAGNIFY+MAGNIFY/2) , MAGNIFY/3, 1)\n                \n\n            # zone_width = danger_zone[-1][0] - danger_zone[0][0] + 1\n     #        zone_height = danger_zone[-1][1] - danger_zone[0][1] + 1\n     # pygame.draw.rect(screenBuffer,(200,200,0),(MAGNIFY*(danger_zone[0][0]+1),MAGNIFY*(danger_zone[0][1]+1),MAGNIFY*zone_width,MAGNIFY*zone_height),5)\n\n\n            # Flip!\n            self.screen.blit(self.screenBuffer, (0, 0))\n            pygame.display.flip()\n                                \n            # Make the transition\n            if not self.isPaused:\n                # Done\n                self.clock.tick(self.speed)\n            else:\n                self.clock.tick(3)\n\n        self.acc_reward += payoff * 10\n        if self.collect_data:\n            self.count += 1\n            if payoff > 0:\n                self.collect_episode_data_file.write(str(self.count) + \"\\n\")\n                self.count = 0\n            if self.stepid % 100 == 0:\n                self.collect_reward_data_file.write(str(self.acc_reward / 100.) + \"\\n\")\n                self.acc_reward = 0\n            if self.stepid % 100000 == 0:\n                pass\n        \n        if self.stepid % 100 == 0:\n            sys.stdout.write(\"\\033[K\")\n            sys.stdout.write(\"[{2}{3}] ({0}/{1}) | alpha = {4} | epsilon = {5}\\n\".format(self.stepid, MAX_STEPS, '#'*int(math.floor(self.stepid/float(MAX_STEPS)*20)), ' '*int((20 - math.floor(self.stepid/float(MAX_STEPS)*20))), learner.alpha, learner.explorer.exploration))\n            sys.stdout.write(\"\\033[F\")\n            \n           \n            \n        \n        if self.stepid >= MAX_STEPS:\n            print (\"\\nSimulation done!\")\n            \n            sys.exit()          \n            \n        if payoff > 0:\n            # episode done\n            if save_file != None:\n                controller.params.reshape(controller.numRows, controller.numColumns).tofile(save_file)\n            learner.alpha *= 1.#0.999\n            learner.explorer.exploration *= 1.#0.999\n            \n        self.isCrashed = False\n        if not self.isPaused:\n            return Experiment._oneInteraction(self)\n        else: return self.stepid\n\n\n        \n# ==================================\n# Call main program\n# ==================================\n\n    \n\n#\n# def enemy_random(enemy, good):\n#     possible_next_positions = set([])\n#     for action in range(5):\n#         next = computeSuccs(enemy[0], enemy[1], action)\n#         for t in next:\n#             if t[0] != -1 and t[2] > 0 and (t[0], t[1], 0, 0) in stateMapper:\n#                 possible_next_positions.add((t[0], t[1]))\n#\n#     next_position_invalid = True\n#     while next_position_invalid:\n#         idx = random.randint(0, len(possible_next_positions) - 1)\n#         enemy = list(possible_next_positions)[idx]\n#         # we do not allow to drive at the old position of the good robot\n#         next_position_invalid = enemy == good\n#\n#     return enemy\n#\n#\n#\n# enemies = []\n\nshield = Shield()\nlevel = Map()\ntask = VisitAllColors(level)\ncontroller = MyActionValueTable(len(reverseStateMapper) - 1, 5)\nif load_file != None:\n    controller.initialize(np.fromfile(load_file))\nelse:\n    controller.initialize(0.)\nalpha = .2\ngamma = .95\nif not args.sarsa:\n    learner = MyQ(alpha, gamma, neg_reward)\n    learner.explorer = MyGreedyExplorer(shield_options, exploration)\nelif args.sarsa:\n    learner = SARSA(alpha, gamma)\nlearner.explorer = MyGreedyExplorer(shield_options, exploration)\nlearner.explorer._setModule(controller)\nagent = LearningAgent(controller, learner)\n\ndraw = False\nEXPLORATION_FACTOR = exploration\n\nexperiment = MyExperiment(task, agent)  \nwhile 1:\n    experiment.doInteractions(100)\n    \n    agent.learn()\n    agent.reset()\n", "meta": {"hexsha": "7e3437c6a023f9e6abbb104a3c9b8baf538cb9c1", "size": 37722, "ext": "py", "lang": "Python", "max_stars_repo_path": "envs/grid_world/simulator.py", "max_stars_repo_name": "safe-rl/safe-rl-shielding", "max_stars_repo_head_hexsha": "287d540df6b26928eed512a57297d44d72f19832", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2018-12-30T20:32:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T06:11:40.000Z", "max_issues_repo_path": "envs/grid_world/simulator.py", "max_issues_repo_name": "safe-rl/safe-rl-shielding", "max_issues_repo_head_hexsha": "287d540df6b26928eed512a57297d44d72f19832", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2018-08-29T10:34:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T23:16:24.000Z", "max_forks_repo_path": "envs/grid_world/simulator.py", "max_forks_repo_name": "safe-rl/safe-rl-shielding", "max_forks_repo_head_hexsha": "287d540df6b26928eed512a57297d44d72f19832", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2019-05-11T01:59:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T14:12:40.000Z", "avg_line_length": 40.9576547231, "max_line_length": 273, "alphanum_fraction": 0.5530459679, "include": true, "reason": "import numpy,from scipy", "num_tokens": 9625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.17291730148369583}}
{"text": "import itertools\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport seaborn as sns\nimport pandas as pd\nfrom typing import Union\nimport numpy as np\nimport re\nimport sys\n\nfrom ..utils import compl, sbs_annotation_converter\nfrom ..context import context96, context78, context83, context1536, context_composite, signature_composite, signature_cosmic, signature_DBS, signature_ID, context_polymerase96\n\ndef stacked_bar(H: pd.DataFrame, ref_type: str, figsize: tuple = (8,8)):\n    \"\"\"\n    Plot stacked barchart & normalized stacked barchart.\n    --------------------------------------\n    Args:\n        * H: matrix output from NMF\n        * figsize: size of figure (int,int)\n\n    Returns:\n        * figure\n\n    Example usage:\n        plot_bar(H)\n    \"\"\"\n    H = H.iloc[:,:-3].copy()\n    # Map signature etiology\n    if ref_type in ['pcawg_COMPOSITE', 'pcawg_COMPOSITE96', 'pcawg_SBS', 'pcawg_SBS96_ID', 'pcawg_SBS_ID']:\n        H.columns = H.columns.map(lambda x: x[x.index('SBS') : x.index('_')]).map(signature_composite)\n    elif ref_type in ['cosmic3', 'cosmic3_exome']:\n        H.columns = H.columns.map(lambda x: x[x.index('SBS'):]).map(signature_cosmic)\n    elif ref_type == 'cosmic3_DBS':\n        H.columns = H.columns.map(lambda x: x[x.index('DBS'):]).map(signature_DBS)\n    elif ref_type == 'cosmic3_ID':\n        H.columns = H.columns.map(lambda x: x[x.index('ID'):]).map(signature_ID)\n\n    # Sort H matrix by mutation burden for relevant mutation type\n    H['sum'] = H.sum(1)\n    H = H.sort_values('sum', ascending=False)\n\n    fig,axes = plt.subplots(2,1,figsize=figsize, sharex=True)\n\n    H.iloc[:,:-1].plot(\n        kind='bar',\n        stacked=True,\n        ax=axes[0],\n        width=1.0,\n        rasterized=True\n    )\n\n    axes[0].set_xticklabels([])\n    axes[0].set_xticks([])\n    axes[0].set_ylabel('Counts', fontsize=20)\n\n    H_norm = H.iloc[:,:-1].div(H['sum'].values,axis=0)\n    H_norm.plot(\n        kind='bar',\n        stacked=True,\n        ax=axes[1],\n        width=1.0,\n        rasterized=True\n    )\n\n    axes[1].set_xticklabels([])\n    axes[1].set_xticks([])\n    axes[1].set_xlabel('Samples', fontsize=16)\n    axes[1].set_ylabel('Fractions', fontsize=20)\n    axes[1].get_legend().remove()\n    axes[1].set_ylim([0,1])\n\n    return fig\n\ndef _map_sbs_sigs_back(df: pd.DataFrame) -> pd.Series:\n    \"\"\"\n    Map Back Single-Base Substitution Signatures.\n    -----------------------\n    Args:\n        * df: pandas.core.frame.DataFrame with index to be mapped\n\n    Returns:\n        * pandas.core.series.Series with matching indices to context96\n    \"\"\"\n    def _check_to_flip(x, ref):\n        if x in ref:\n            return x\n        else:\n            return compl(x)\n\n    if df.index.name is None: df.index.name = 'index'\n    df_idx = df.index.name\n\n    if \">\" in df.index[0]:\n        # Already in arrow format\n        context_s = df.reset_index()[df_idx].apply(sbs_annotation_converter)\n    else:\n        # Already in word format\n        context_s = df.reset_index()[df_idx]\n\n    return context_s.apply(lambda x: _check_to_flip(x, context96.keys()))\n\ndef _map_id_sigs_back(df: pd.DataFrame) -> pd.Series:\n    \"\"\"\n        Map Back Insertion-Deletion Signatures.\n        -----------------------\n        Args:\n            * df: pandas.core.frame.DataFrame with index to be mapped\n\n        Returns:\n            * pandas.core.series.Series with matching indices to context83\n        \"\"\"\n    if df.index.name is None: df.index.name = 'index'\n    df_idx = df.index.name\n\n    context_s = df.reset_index()[df_idx]\n\n    def _convert_from_cosmic(x):\n        if x in context83:\n            return x\n        i1, i2, i3, i4 = x.split('_')\n        pre = i2 if i3 == '1' else i3\n        main = i1.lower() + ('m' if i2 == 'MH' else '')\n        if main == 'del':\n            post = str(int(i4[0]) + 1) + i4[1:]\n        else:\n            post = i4\n        return pre + main + post\n\n    return context_s.apply(_convert_from_cosmic)\n\ndef signature_barplot(W: pd.DataFrame, contributions: Union[int, pd.Series] = 1):\n    \"\"\"\n    Plots signatures from W-matrix for Single-Base Substitutions\n    --------------------------------------\n    Args:\n        * W: W-matrix\n        * contributions: Series of total contributions, np.sum(H), from each\n            signature if W is normalized; else, 1\n\n    Returns:\n        * fig\n\n    Example usage:\n        signature_barplot(W, np.sum(H))\n    \"\"\"\n    W = W.copy()\n    W.index = _map_sbs_sigs_back(W)\n\n    # Fill in any missing contexts\n    for c in context96:\n        if c not in W.index:\n            W.loc[c] = 0\n\n    # Sort contexts\n    W.sort_index(inplace=True)\n\n    # Extract columns corresponding to signatures\n    sig_columns = [c for c in W if c.startswith('S')]\n\n    # Calculate total number of mutations at each context for every signature\n    if isinstance(contributions, pd.Series):\n        W = W[sig_columns] * contributions[sig_columns]\n    else:\n        W = W[sig_columns] * contributions\n\n    # Determine number of signatures\n    n_sigs = len(sig_columns)\n\n    # Initialize SBS C>N and T>N mutations and their contexts\n    # For each context, iterate through C>N and T>N mutations, and take reverse complement\n    # of context for A>N mutations\n    context_label = []\n    change_map = {'CA': [], 'CG': [], 'CT': [], 'TA': [], 'TC': [], 'TG': []}\n    for p in itertools.product('ACGT', 'ACGT'):\n        context = ''.join(p)\n        # Reverse complement of context\n        compl_context = compl(context, reverse=True)\n        context_label.append('-'.join(context))\n        for key in change_map:\n            if key.startswith('C'):\n                change_map[key].append(key + context)\n            else:\n                # Complement of mutation + reverse complement of context\n                change_map[key].append(compl(key) + compl_context)\n    color_map = {'CA': 'cyan', 'CG': 'red', 'CT': 'yellow', 'TA': 'purple', 'TC': 'green', 'TG': 'blue'}\n\n    # Plot contributions\n    x_coords = range(16)\n    fig, axes = plt.subplots(nrows=n_sigs, ncols=6, figsize=(20, 2.5 * n_sigs), sharex='col', sharey='row')\n    for row, sig in enumerate(sig_columns):\n        for col, chg in enumerate(['CA', 'CG', 'CT', 'TA', 'TC', 'TG']):\n            if n_sigs == 1:\n                ax = axes[col]\n            else:\n                ax = axes[row, col]\n            bar_heights = W[sig].loc[change_map[chg]]\n            ax.bar(x_coords, bar_heights, width=.95, linewidth=1.5, edgecolor='gray', color=color_map[chg], rasterized=True)\n            ax.set_xlim(-.55, 15.55)\n            if row == 0:\n                ax.set_title('>'.join(chg), fontsize=18)\n                if col == 0:\n                    ax.text(51.2 / 16, 1.3, 'Mutational Signatures', transform=ax.transAxes,\n                            horizontalalignment='center', fontsize=24)\n            if row < n_sigs - 1:\n                ax.tick_params(axis='x', length=0)\n            else:\n                ax.set_xticks(x_coords)\n                ax.set_xticklabels(context_label, fontfamily='monospace', rotation='vertical')\n                if col == 0:\n                    ax.text(51.2 / 16, -.4, 'Motifs', transform=ax.transAxes, horizontalalignment='center', fontsize=20,\n                            fontweight='bold')\n            if col > 0:\n                ax.tick_params(axis='y', length=0)\n            if col == 5:\n                ax.text(1.05, .5, sig, fontsize=14, rotation=270, transform=ax.transAxes, verticalalignment='center')\n\n    plt.subplots_adjust(wspace=.08, hspace=.15)\n    fig.text(.08, .5, 'Contributions', rotation='vertical', verticalalignment='center', fontsize=20, fontweight='bold')\n\n    return fig\n\ndef signature_barplot_DBS(W, contributions):\n    \"\"\"\n    Plots signatures from W-matrix for Doublet-Base Substitutions\n    --------------------------------------\n    Args:\n        * W: W-matrix\n        * contributions: Series of total contributions, np.sum(H), from each\n            signature if W is normalized; else, 1\n\n    Returns:\n        * fig\n\n    Example usage:\n        signature_barplot_DBS(W, np.sum(H))\n    \"\"\"\n    W = W.copy()\n    for c in context78:\n        if c not in W.index:\n            W.loc[c] = 0\n    W.sort_index(inplace=True)\n    sig_columns = [c for c in W if c.startswith('S')]\n    if isinstance(contributions, pd.Series):\n        W = W[sig_columns] * contributions[sig_columns]\n    else:\n        W = W[sig_columns] * contributions\n\n    n_sigs = len(sig_columns)\n\n    ref_map = {'AC': [], 'AT': [], 'CC': [], 'CG': [], 'CT': [], 'GC': [], 'TA': [], 'TC': [], 'TG': [], 'TT': []}\n    for x in W.index:\n        ref_map[x[:2]].append(x)\n    x_coords = {ref: range(len(sigs)) for ref, sigs in ref_map.items()}\n\n    color_map = {'AC': '#99CCFF', 'AT': '#0000FF', 'CC': '#CCFF99', 'CG': '#00FF00', 'CT': '#FF99CC',\n                 'GC': '#FF0000', 'TA': '#FFCC99', 'TC': '#FF8000', 'TG': '#CC99FF', 'TT': '#8000FF'}\n    fig, axes = plt.subplots(nrows=n_sigs, ncols=10, figsize=(20, 2.5 * n_sigs), sharex='col',\n                             sharey='row', gridspec_kw={'width_ratios': (3, 2, 3, 2, 3, 2, 2, 3, 3, 3)})\n    for row, sig in enumerate(sig_columns):\n        for col, ref in enumerate(ref_map):\n            if n_sigs == 1:\n                ax = axes[col]\n            else:\n                ax = axes[row, col]\n            bar_heights = W[sig].loc[ref_map[ref]]\n            ax.bar(x_coords[ref], bar_heights, width=.95, linewidth=1.5, edgecolor='gray', color=color_map[ref],\n                   rasterized=True)\n            ax.set_xlim(-.55, x_coords[ref][-1] + .55)\n            if row == 0:\n                ax.set_title(ref)\n                if col == 0:\n                    ax.text(44.5 / 6, 1.2, 'Mutational Signatures', transform=ax.transAxes,\n                            horizontalalignment='center', fontsize=24)\n            if row < n_sigs - 1:\n                ax.tick_params(axis='x', length=0)\n            else:\n                xlabels = [x[3:] for x in ref_map[ref]]\n                ax.set_xticks(x_coords[ref])\n                ax.set_xticklabels(xlabels, fontfamily='monospace', rotation='vertical')\n                if col == 0:\n                    ax.text(44.5 / 6, -.3, 'Motifs', transform=ax.transAxes, horizontalalignment='center', fontsize=20,\n                            fontweight='bold')\n            if col > 0:\n                ax.tick_params(axis='y', length=0)\n            if col == 9:\n                ax.text(1.05, .5, sig, fontsize=14, rotation=270, transform=ax.transAxes, verticalalignment='center')\n\n    plt.subplots_adjust(wspace=.08, hspace=.15)\n    fig.text(.08, .5, 'Contributions', rotation='vertical', verticalalignment='center', fontsize=20, fontweight='bold')\n\n    return fig\n\ndef signature_barplot_ID(W, contributions):\n    \"\"\"\n    Plots signatures from W-matrix for Insertions-Deletions\n    --------------------------------------\n    Args:\n        * W: W-matrix\n        * contributions: Series of total contributions, np.sum(H), from each\n            signature if W is normalized; else, 1\n\n    Returns:\n        * fig\n\n    Example usage:\n        signature_barplot_ID(W, np.sum(H))\n    \"\"\"\n    W = W.copy()\n    W.index = _map_id_sigs_back(W)\n    for c in context83:\n        if c not in W.index:\n            W.loc[c] = 0\n    W = W.loc[context83]\n    sig_columns = [c for c in W if c.startswith('S')]\n    if isinstance(contributions, pd.Series):\n        W = W[sig_columns] * contributions[sig_columns]\n    else:\n        W = W[sig_columns] * contributions\n\n    n_sigs = len(sig_columns)\n    group_map = {'Cdel': [], 'Tdel': [], 'Cins': [], 'Tins': [],\n                 '2del': [], '3del': [], '4del': [], '5+del': [],\n                 '2ins': [], '3ins': [], '4ins': [], '5+ins': [],\n                 '2delm': [], '3delm': [], '4delm': [], '5+delm': []}\n    for x in W.index:\n        group = re.search('.+?(?=[\\d])', x).group(0)\n        group_map[group].append(x)\n    x_coords = {group: range(len(sigs)) for group, sigs in group_map.items()}\n\n    color_map = {'Cdel': '#FFCC99', 'Tdel': '#FF8000', 'Cins': '#00FF00', 'Tins': '#00BB00',\n                 '2del': '#FF99CC', '3del': '#FF3377', '4del': '#FF0000', '5+del': '#880000',\n                 '2ins': '#99CCFF', '3ins': '#3377FF', '4ins': '#0000FF', '5+ins': '#000088',\n                 '2delm': '#CC99FF', '3delm': '#9966FF', '4delm': '#8000FF', '5+delm': '#6000AA'}\n\n    fig, axes = plt.subplots(nrows=n_sigs, ncols=16, figsize=(20, 2.5 * n_sigs), sharex='col',\n                             sharey='row', gridspec_kw={'width_ratios': (6,) * 12 + (1, 2, 3, 5)})\n    for row, sig in enumerate(sig_columns):\n        for col, group in enumerate(group_map):\n            if n_sigs == 1:\n                ax = axes[col]\n            else:\n                ax = axes[row, col]\n            bar_heights = W[sig].loc[group_map[group]]\n            ax.bar(x_coords[group], bar_heights, width=.95, linewidth=1.5, edgecolor='gray', color=color_map[group],\n                   rasterized=True)\n            ax.set_xlim(-.55, x_coords[group][-1] + .55)\n            if row == 0:\n                ax.set_title(re.search('[\\d+CT]+', group).group(0), color=color_map[group])\n                if col == 0:\n                    ax.text(44.5 / 6, 1.3, 'Mutational Signatures', transform=ax.transAxes,\n                            horizontalalignment='center', fontsize=24)\n                if group == 'Tdel':\n                    ax.text(-.02, 1.16, '1bp deletions at repeats', fontsize=10, transform=ax.transAxes,\n                            horizontalalignment='center', color=color_map[group])\n                if group == 'Tins':\n                    ax.text(-.02, 1.16, '1bp insertions at repeats', fontsize=10, transform=ax.transAxes,\n                            horizontalalignment='center', color=color_map[group])\n                if group == '4del':\n                    ax.text(-.02, 1.16, '>1bp deletions at repeats', fontsize=10, transform=ax.transAxes,\n                            horizontalalignment='center', color=color_map[group])\n                if group == '4ins':\n                    ax.text(-.02, 1.16, '>1bp insertions at repeats', fontsize=10, transform=ax.transAxes,\n                            horizontalalignment='center', color=color_map[group])\n                if group == '4delm':\n                    ax.text(.8, 1.16, '>1bp deletions with microhomology', fontsize=10, transform=ax.transAxes,\n                            horizontalalignment='center', color=color_map[group])\n            if row < n_sigs - 1:\n                ax.tick_params(axis='x', length=0)\n            else:\n                xlabels = [re.search('[\\d+]+$', x).group(0) for x in group_map[group]]\n                ax.set_xticks(x_coords[group])\n                ax.set_xticklabels(xlabels, fontfamily='monospace')\n                if col == 0:\n                    ax.text(44.5 / 6, -.3, 'Motifs', transform=ax.transAxes, horizontalalignment='center', fontsize=20,\n                            fontweight='bold')\n            if col > 0:\n                ax.tick_params(axis='y', length=0)\n            if col == 15:\n                ax.text(1.05, .5, sig, fontsize=14, rotation=270, transform=ax.transAxes, verticalalignment='center')\n\n    plt.subplots_adjust(wspace=.08, hspace=.15)\n    fig.text(.08, .5, 'Contributions', rotation='vertical', verticalalignment='center', fontsize=20, fontweight='bold')\n\n    return fig\n\ndef signature_barplot_composite(W: pd.DataFrame, contributions: Union[int, pd.Series] = 1):\n    \"\"\"\n    Plot signatures from W-matrix for SBS, DBS, and IDs from composite W matrix\n    --------------------------------------\n    Args:\n        * W: W-matrix\n        * contributions: Series of total contributions, np.sum(H), from each \n            signature if W is normalized; else, 1\n    Returns:\n       * fig\n    Example usage:\n        signature_barplot(W, np.sum(H))\n    \"\"\"\n    \n    W = W.copy()\n    # Fill in missing features\n    composite_index = list(context96)+list(context78)+list(context83)\n    for c in composite_index:\n        if c not in list(W.index):\n            W.loc[c] = 0\n    W = W.reindex(composite_index)\n\n    # Get signature labels\n    sig_columns = [c for c in W if c.startswith('S')]\n    n_sigs = len(sig_columns)\n\n    # Evaluate contributions\n    if isinstance(contributions, pd.Series):\n        W = W[sig_columns] * contributions[sig_columns]\n    else:\n        W = W[sig_columns] * contributions\n        \n    #### x coordinates for SBS contributions\n    context_label = []\n    change_map = {'CA': [], 'CG': [], 'CT': [], 'TA': [], 'TC': [], 'TG': []}\n    for p in itertools.product('ACGT', 'ACGT'):\n        context = ''.join(p)\n        compl_context = compl(context, reverse=True)\n        context_label.append('-'.join(context))\n        for key in change_map:\n            if key.startswith('C'):\n                change_map[key].append(key + context)\n            else:\n                change_map[key].append(compl(key) + compl_context)\n    color_map_sbs = {'CA': 'cyan', 'CG': 'red', 'CT': 'yellow', 'TA': 'purple', 'TC': 'green', 'TG': 'blue'}\n    x_coords_sbs = range(16)\n                \n    ##### x coordinates for DBS contributions\n    ref_map = {'AC': [], 'AT': [], 'CC': [], 'CG': [], 'CT': [], 'GC': [], 'TA': [], 'TC': [], 'TG': [], 'TT': []}\n    for x in context78:\n        ref_map[x[:2]].append(x)\n    x_coords_dbs = {ref: range(len(sigs)) for ref, sigs in ref_map.items()}\n    color_map_dbs = {'AC': '#99CCFF', 'AT': '#0000FF', 'CC': '#CCFF99', 'CG': '#00FF00', 'CT': '#FF99CC',\n                 'GC': '#FF0000', 'TA': '#FFCC99', 'TC': '#FF8000', 'TG': '#CC99FF', 'TT': '#8000FF'}\n    \n    ##### x coordinates for ID contributions\n    group_map = {'Cdel': [], 'Tdel': [], 'Cins': [], 'Tins': [],\n                 '2del': [], '3del': [], '4del': [], '5+del': [],\n                 '2ins': [], '3ins': [], '4ins': [], '5+ins': [],\n                 '2delm': [], '3delm': [], '4delm': [], '5+delm': []}\n    for x in context83:\n        group = re.search('.+?(?=[\\d])', x).group(0)\n        group_map[group].append(x)\n    x_coords_id = {group: range(len(sigs)) for group, sigs in group_map.items()}\n\n    color_map_id = {'Cdel': '#FFCC99', 'Tdel': '#FF8000', 'Cins': '#00FF00', 'Tins': '#00BB00',\n                 '2del': '#FF99CC', '3del': '#FF3377', '4del': '#FF0000', '5+del': '#880000',\n                 '2ins': '#99CCFF', '3ins': '#3377FF', '4ins': '#0000FF', '5+ins': '#000088',\n                 '2delm': '#CC99FF', '3delm': '#9966FF', '4delm': '#8000FF', '5+delm': '#6000AA'}\n\n    # Include spaces to separate feature types\n    all_columns = ['CA', 'CG', 'CT', 'TA', 'TC', 'TG'] + ['space'] + list(ref_map) + ['space'] + list(group_map)\n    fig, axes = plt.subplots(nrows=n_sigs, ncols=34, figsize=(60,2.5*n_sigs), sharex='col',\n                             gridspec_kw={'width_ratios': (16,)*6 + (1,)+ (9,6,9,6,9,6,6,9,9,9) + (1,) + (6,)*12+(1,2,3,5)})\n    max_height = 0  # Maximum height for scaling y-axis per feature type per signature\n    # Iterate through signatures, such that each row plots mutational landscape for a signature\n    for row, sig in enumerate(sig_columns):\n        for col, ref in enumerate(all_columns):\n            if n_sigs == 1:\n                ax = axes[col]\n            else:\n                ax = axes[row,col]\n            if col in [6,17]:  # Space between feature types...Remove ax and move to next feature (column)\n                ax.remove()\n                continue\n            # For SBS portion, iterate through 6 SNV types (C>A, C>T, C>G, T>A...)\n            if col < 6:\n                bar_heights = W[sig].loc[change_map[ref]]\n                for height in bar_heights:\n                    if height > max_height: max_height = height\n                ax.bar(x_coords_sbs, bar_heights, width=.95, linewidth=1.5, edgecolor='gray', color=color_map_sbs[ref], rasterized=True)\n                ax.set_xlim(-.55, 15.55)\n                if row == 0:\n                    ax.set_title('>'.join(ref), fontsize=18)\n                    if col == 0:\n                        ax.text(8.1, 1.3, 'Mutational Signatures', transform=ax.transAxes,\n                                horizontalalignment='center', fontsize=24)\n                if row < n_sigs - 1:\n                    ax.tick_params(axis='x', length=0, labelbottom=False)\n                else:\n                    ax.set_xticks(x_coords_sbs)\n                    ax.set_xticklabels(context_label, fontfamily='monospace', rotation='vertical')\n                    if col == 0:\n                        ax.text(8.1, -.4, 'Motifs', transform = ax.transAxes, horizontalalignment='center', fontsize=20)\n                if col == 5:\n                    if n_sigs == 1:\n                        for axis in axes[:col+1]:\n                            axis.set_ylim(0,max_height + 0.1*max_height+1)\n                    else:\n                        for axis in axes[row,:col+1]:\n                            axis.set_ylim(0,max_height + 0.1*max_height+1)\n                    max_height = 0\n                             \n            # For DBS portion\n            elif col < 17:\n                bar_heights = W[sig].loc[ref_map[ref]]\n                for height in bar_heights:\n                    if height > max_height: max_height = height\n                ax.bar(x_coords_dbs[ref], bar_heights, width=.95, linewidth=1.5, edgecolor='gray', color=color_map_dbs[ref],\n                       rasterized=True)\n                ax.set_xlim(-.55, x_coords_dbs[ref][-1] + .55)\n                if row == 0:\n                    ax.set_title(ref)\n                if row < n_sigs - 1:\n                    ax.tick_params(axis='x', length=0)\n                else:\n                    xlabels = [x[3:] for x in ref_map[ref]]\n                    ax.set_xticks(x_coords_dbs[ref])\n                    ax.set_xticklabels(xlabels, fontfamily='monospace', rotation='vertical')\n                if col == 15:\n                    if n_sigs == 1:\n                        for axis in axes[6:col+1]:\n                            axis.set_ylim(0,max_height + 0.1*max_height+1)\n                    else:\n                        for axis in axes[row,6:col+1]:\n                            axis.set_ylim(0,max_height + 0.1*max_height+1)\n                    max_height = 0\n                             \n            # For ID portion\n            else:\n                bar_heights = W[sig].loc[group_map[ref]]\n                for height in bar_heights:\n                    if height > max_height: max_height = height\n                ax.bar(x_coords_id[ref], bar_heights, width=.95, linewidth=1.5, edgecolor='gray', color=color_map_id[ref],\n                       rasterized=True)\n                ax.set_xlim(-.55, x_coords_id[ref][-1] + .55)\n                if row == 0:\n                    ax.set_title(re.search('[\\d+CT]+', ref).group(0), color=color_map_id[ref])\n                    if ref == 'Tdel':\n                        ax.text(-.02, 1.16, '1bp deletions at repeats', fontsize=10, transform=ax.transAxes,\n                                horizontalalignment='center', color=color_map_id[ref])\n                    if ref == 'Tins':\n                        ax.text(-.02, 1.16, '1bp insertions at repeats', fontsize=10, transform=ax.transAxes,\n                                horizontalalignment='center', color=color_map_id[ref])\n                    if ref == '4del':\n                        ax.text(-.02, 1.16, '>1bp deletions at repeats', fontsize=10, transform=ax.transAxes,\n                                horizontalalignment='center', color=color_map_id[ref])\n                    if ref == '4ins':\n                        ax.text(-.02, 1.16, '>1bp insertions at repeats', fontsize=10, transform=ax.transAxes,\n                                horizontalalignment='center', color=color_map_id[ref])\n                    if ref == '4delm':\n                        ax.text(.8, 1.16, '>1bp deletions with microhomology', fontsize=10, transform=ax.transAxes,\n                                horizontalalignment='center', color=color_map_id[ref])\n                if row < n_sigs - 1:\n                    ax.tick_params(axis='x', length=0)\n                else:\n                    xlabels = [re.search('[\\d+]+$', x).group(0) for x in group_map[ref]]\n                    ax.set_xticks(x_coords_id[ref])\n                    ax.set_xticklabels(xlabels, fontfamily='monospace')\n                if col == 33:\n                    if n_sigs == 1:\n                        for axis in axes[16:col+1]:\n                            axis.set_ylim(0,max_height + 0.1*max_height+1)\n                    else:\n                        for axis in axes[row,16:col+1]:\n                            axis.set_ylim(0,max_height + 0.1*max_height+1)\n                    max_height = 0\n\n            if col not in [0,7,18]:\n                ax.tick_params(axis='y', which='both',length=0, labelleft=False)\n            if col == 33:\n                ax.text(1.05, .5, sig, fontsize=14, rotation=270, transform=ax.transAxes, verticalalignment='center')\n\n    # Set titles and organize plot\n    plt.subplots_adjust(wspace=.12, hspace=.15)\n    fig.text(.105, .5, 'Contributions', rotation='vertical', verticalalignment='center', fontsize=20, fontweight='bold')\n    return fig\n\n\ndef signature_barplot_sbs_id(W: pd.DataFrame, contributions: Union[int, pd.Series] = 1):\n    \"\"\"\n    Plot signatures from W-matrix for SBS, DBS, and IDs from composite W matrix\n    --------------------------------------\n    Args:\n        * W: W-matrix\n        * contributions: Series of total contributions, np.sum(H), from each \n            signature if W is normalized; else, 1\n\n    Returns:\n       * fig\n\n    Example usage:\n        signature_barplot(W, np.sum(H))\n    \"\"\"\n    W = W.copy()\n\n    # Fill in missing features and sort\n    composite_index = list(context96)+list(context83)\n    for c in composite_index:\n        if c not in list(W.index):\n            W.loc[c] = 0\n    W = W.reindex(composite_index)\n            \n    # Get signature labels\n    sig_columns = [c for c in W if c.startswith('S')]\n    n_sigs = len(sig_columns)\n\n    # Evaluate contributions\n    if isinstance(contributions, pd.Series):\n        W = W[sig_columns] * contributions[sig_columns]\n    else:\n        W = W[sig_columns] * contributions\n        \n    #### x coordinates for SBS contributions\n    context_label = []\n    change_map = {'CA': [], 'CG': [], 'CT': [], 'TA': [], 'TC': [], 'TG': []}\n    for p in itertools.product('ACGT', 'ACGT'):\n        context = ''.join(p)\n        compl_context = compl(context, reverse=True)\n        context_label.append('-'.join(context))\n        for key in change_map:\n            if key.startswith('C'):\n                change_map[key].append(key + context)\n            else:\n                change_map[key].append(compl(key) + compl_context)\n    color_map_sbs = {'CA': 'cyan', 'CG': 'red', 'CT': 'yellow', 'TA': 'purple', 'TC': 'green', 'TG': 'blue'}\n    x_coords_sbs = range(16)\n    \n    ##### x coordinates for ID contributions\n    group_map = {'Cdel': [], 'Tdel': [], 'Cins': [], 'Tins': [],\n                 '2del': [], '3del': [], '4del': [], '5+del': [],\n                 '2ins': [], '3ins': [], '4ins': [], '5+ins': [],\n                 '2delm': [], '3delm': [], '4delm': [], '5+delm': []}\n    for x in context83:\n        group = re.search('.+?(?=[\\d])', x).group(0)\n        group_map[group].append(x)\n    x_coords_id = {group: range(len(sigs)) for group, sigs in group_map.items()}\n\n    color_map_id = {'Cdel': '#FFCC99', 'Tdel': '#FF8000', 'Cins': '#00FF00', 'Tins': '#00BB00',\n                 '2del': '#FF99CC', '3del': '#FF3377', '4del': '#FF0000', '5+del': '#880000',\n                 '2ins': '#99CCFF', '3ins': '#3377FF', '4ins': '#0000FF', '5+ins': '#000088',\n                 '2delm': '#CC99FF', '3delm': '#9966FF', '4delm': '#8000FF', '5+delm': '#6000AA'}\n\n    all_columns = ['CA', 'CG', 'CT', 'TA', 'TC', 'TG'] + ['space'] + list(group_map)\n    \n    fig, axes = plt.subplots(nrows=n_sigs, ncols=23, figsize=(60,2.5*n_sigs), sharex='col',\n                             gridspec_kw={'width_ratios': (16,)*6 + (1,) + (6,)*12+(1,2,3,5)})\n    max_height = 0\n    for row, sig in enumerate(sig_columns):\n        for col, ref in enumerate(all_columns):\n            if n_sigs == 1:\n                ax = axes[col]\n            else:\n                ax = axes[row,col]\n            if col == 6:\n                ax.remove()\n                continue\n            # For SBS portion\n            if col < 6:\n                bar_heights = W[sig].loc[change_map[ref]]\n                for height in bar_heights:\n                    if height > max_height: max_height = height\n                ax.bar(x_coords_sbs, bar_heights, width=.95, linewidth=1.5, edgecolor='gray', color=color_map_sbs[ref], rasterized=True)\n                ax.set_xlim(-.55, 15.55)\n                if row == 0:\n                    ax.set_title('>'.join(ref), fontsize=18)\n                    if col == 0:\n                        ax.text(5.5, 1.3, 'Mutational Signatures', transform=ax.transAxes,\n                                horizontalalignment='center', fontsize=24)\n                if row < n_sigs - 1:\n                    ax.tick_params(axis='x', length=0, labelbottom=False)\n                else:\n                    ax.set_xticks(x_coords_sbs)\n                    ax.set_xticklabels(context_label, fontfamily='monospace', rotation='vertical')\n                    if col == 0:\n                        ax.text(5.5, -.4, 'Motifs', transform = ax.transAxes, horizontalalignment='center', fontsize=20)\n                if col == 5:\n                    if n_sigs == 1:\n                        for axis in axes[:col+1]:\n                            axis.set_ylim(0,max_height + 0.1*max_height+1)\n                    else:\n                        for axis in axes[row,:col+1]:\n                            axis.set_ylim(0,max_height + 0.1*max_height+1)\n                    max_height = 0\n                             \n            # For ID portion\n            else:\n                bar_heights = W[sig].loc[group_map[ref]]\n                for height in bar_heights:\n                    if height > max_height: max_height = height\n                ax.bar(x_coords_id[ref], bar_heights, width=.95, linewidth=1.5, edgecolor='gray', color=color_map_id[ref],\n                       rasterized=True)\n                ax.set_xlim(-.55, x_coords_id[ref][-1] + .55)\n                if row == 0:\n                    ax.set_title(re.search('[\\d+CT]+', ref).group(0), color=color_map_id[ref])\n                    if ref == 'Tdel':\n                        ax.text(-.02, 1.16, '1bp deletions at repeats', fontsize=10, transform=ax.transAxes,\n                                horizontalalignment='center', color=color_map_id[ref])\n                    if ref == 'Tins':\n                        ax.text(-.02, 1.16, '1bp insertions at repeats', fontsize=10, transform=ax.transAxes,\n                                horizontalalignment='center', color=color_map_id[ref])\n                    if ref == '4del':\n                        ax.text(-.02, 1.16, '>1bp deletions at repeats', fontsize=10, transform=ax.transAxes,\n                                horizontalalignment='center', color=color_map_id[ref])\n                    if ref == '4ins':\n                        ax.text(-.02, 1.16, '>1bp insertions at repeats', fontsize=10, transform=ax.transAxes,\n                                horizontalalignment='center', color=color_map_id[ref])\n                    if ref == '4delm':\n                        ax.text(.8, 1.16, '>1bp deletions with microhomology', fontsize=10, transform=ax.transAxes,\n                                horizontalalignment='center', color=color_map_id[ref])\n                if row < n_sigs - 1:\n                    ax.tick_params(axis='x', length=0)\n                else:\n                    xlabels = [re.search('[\\d+]+$', x).group(0) for x in group_map[ref]]\n                    ax.set_xticks(x_coords_id[ref])\n                    ax.set_xticklabels(xlabels, fontfamily='monospace')\n                if col == 22:\n                    if n_sigs == 1:\n                        for axis in axes[6:col+1]:\n                            axis.set_ylim(0,max_height + 0.1*max_height+1)\n                    else:\n                        for axis in axes[row,6:col+1]:\n                            axis.set_ylim(0,max_height + 0.1*max_height+1)\n                    max_height = 0\n\n            if col not in [0,7]:\n                ax.tick_params(axis='y', which='both',length=0, labelleft=False)\n            if col == 22:\n                ax.text(1.05, .5, sig, fontsize=14, rotation=270, transform=ax.transAxes, verticalalignment='center')\n\n    # Set titles and organize plot\n    plt.subplots_adjust(wspace=.12, hspace=.15)\n    fig.text(.105, .5, 'Contributions', rotation='vertical', verticalalignment='center', fontsize=20, fontweight='bold')\n    return fig\n\ndef signature_barplot_polymerase(W: pd.DataFrame, contributions: Union[int, pd.Series] = 1):\n    W = W.copy()\n    # Fill in missing features\n    for c in context_polymerase96:\n        if c not in list(W.index):\n            W.loc[c] = 0\n    W = W.reindex(context_polymerase96)\n\n    # Get signature labels\n    sig_columns = [c for c in W if c.startswith('S')]\n    n_sigs = len(sig_columns)\n\n    # Evaluate contributions\n    if isinstance(contributions, pd.Series):\n        W = W[sig_columns] * contributions[sig_columns]\n    else:\n        W = W[sig_columns] * contributions\n\n    #### X coordinates for SBS contributions\n    context_label = []\n    change_map = {'CA': [], 'CG': [], 'CT': [], 'TA': [], 'TC': [], 'TG': []}\n    for p in itertools.product('ACGT','ACGT'):\n        context = ''.join(p)\n        compl_context = compl(context, reverse=True)\n        context_label.append('-'.join(context))\n        for key in change_map:\n            if key.startswith('C'):\n                change_map[key].append(key + context)\n            else:\n                change_map[key].append(compl(key) + compl_context)\n    color_map_sbs = {'CA': 'cyan', 'CG': 'red', 'CT': 'yellow', 'TA': 'purple', 'TC': 'green', 'TG': 'blue'}\n    x_coords_sbs = range(16)\n\n    #### X coordinates for ID contributions\n    group_map = {'INS': ['INS' + str(i+1) for i in range(4)], 'DEL': ['DEL' + str(i+1) for i in range(4)]}\n    color_map_id = {'INS':'#FFCC99', 'DEL':'#FF8000'}\n    x_coords_id = {'INS':range(0,4), 'DEL':range(0,4)}\n    all_columns = [x for x in change_map.keys()] + ['space', 'INS', 'DEL']\n\n    fig, axes = plt.subplots(nrows=n_sigs, ncols=9, figsize=(60,2.5*n_sigs), sharex='col',\n                             gridspec_kw={'width_ratios': (16,)*6 + (1,) + (4,)*2})\n    max_height = 0\n    # Iterate through signatures\n    for row, sig in enumerate(sig_columns):\n        # iterate through columns\n        for col, ref in enumerate(all_columns):\n            if n_sigs == 1:\n                ax = axes[col]\n            else:\n                ax  = axes[row,col]\n                if col == 6:\n                    ax.remove()\n                    continue\n            # For SBS portion\n            if col < 6:\n                bar_heights = W[sig].loc[change_map[ref]]\n                for height in bar_heights:\n                    if height > max_height: max_height = height\n                ax.bar(x_coords_sbs, bar_heights, width=.95, linewidth=1.5, edgecolor='gray', color=color_map_sbs[ref], rasterized=True)\n                ax.set_xlim(-.55, 15.55)\n                if row == 0:\n                    ax.set_title('>'.join(ref), fontsize=18)\n                    if col == 0:\n                        ax.text(4, 1.3, 'Mutational Signatures', transform=ax.transAxes,\n                                horizontalalignment='center', fontsize=24)\n                if row < n_sigs - 1:\n                    ax.tick_params(axis='x', length=0, labelbottom=False)\n                else:\n                    ax.set_xticks(x_coords_sbs)\n                    ax.set_xticklabels(context_label, fontfamily='monospace', rotation='vertical')\n                    if col == 0:\n                        ax.text(4, -.4, 'Motifs', transform = ax.transAxes, horizontalalignment='center', fontsize=20)\n                if col == 5:\n                    if n_sigs == 1:\n                        for axis in axes[:col+1]:\n                            axis.set_ylim(0,max_height + 0.1*max_height+1)\n                    else:\n                        for axis in axes[row,:col+1]:\n                            axis.set_ylim(0,max_height + 0.1*max_height+1)\n                    max_height = 0\n            # For ID portion\n            else:\n                bar_heights = W[sig].loc[group_map[ref]]\n                for height in bar_heights:\n                    if height > max_height: max_height = height\n                ax.bar(x_coords_id[ref], bar_heights, width=0.95, linewidth=1.5, edgecolor='gray', color=color_map_id[ref],\n                       rasterized=True)\n                ax.set_xlim(-.55, x_coords_id[ref][-1] + 0.55)\n                # Set column titles\n                if row == 0:\n                    ax.set_title(ref, color=color_map_id[ref])\n                if row < n_sigs - 1:\n                    ax.tick_params(axis='x', length=0)\n                else:\n                    xlabels = ['1','2','3','4+']\n                    ax.set_xticks(x_coords_id[ref])\n                    ax.set_xticklabels(xlabels, fontfamily='monospace')\n                if col == 8:\n                    ax.text(1.05, .5, sig, fontsize=14, rotation=270, transform=ax.transAxes, verticalalignment=\"center\")\n    # Set titles and organize plot\n    plt.subplots_adjust(wspace=.12, hspace=0.15)\n    fig.text(0.105, 0.5, 'Contributions', rotation='vertical', verticalalignment='center', fontsize=20, fontweight='bold')\n    return fig\n", "meta": {"hexsha": "e57a53c6f5696d5a33e7d839ff2a9cb22bdedfb4", "size": 37607, "ext": "py", "lang": "Python", "max_stars_repo_path": "signatureanalyzer/plotting/_muts.py", "max_stars_repo_name": "getzlab/getzlab-SignatureAnalyzer", "max_stars_repo_head_hexsha": "19a00a73195ba011913eefb818997d98e8d7485e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-11-23T16:19:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T01:36:41.000Z", "max_issues_repo_path": "signatureanalyzer/plotting/_muts.py", "max_issues_repo_name": "getzlab/SignatureAnalyzer", "max_issues_repo_head_hexsha": "19a00a73195ba011913eefb818997d98e8d7485e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2021-11-06T16:49:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T09:52:43.000Z", "max_forks_repo_path": "signatureanalyzer/plotting/_muts.py", "max_forks_repo_name": "getzlab/SignatureAnalyzer", "max_forks_repo_head_hexsha": "19a00a73195ba011913eefb818997d98e8d7485e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-11-09T04:34:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T19:43:52.000Z", "avg_line_length": 45.0383233533, "max_line_length": 175, "alphanum_fraction": 0.521525248, "include": true, "reason": "import numpy", "num_tokens": 9748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.17291729448362234}}
{"text": "#MIT License\n#\n#Copyright (c) 2020 Pierre Michel Joubert\n#\n#Permission is hereby granted, free of charge, to any person obtaining a copy\n#of this software and associated documentation files (the \"Software\"), to deal\n#in the Software without restriction, including without limitation the rights\n#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n#copies of the Software, and to permit persons to whom the Software is\n#furnished to do so, subject to the following conditions:\n#\n#The above copyright notice and this permission notice shall be included in all\n#copies or substantial portions of the Software.\n#\n#THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n#SOFTWARE.\nimport csv\nimport re\nimport random\nfrom scipy.stats import gaussian_kde\nimport numpy as np\nimport scipy.interpolate\nimport sys\n\n## USAGE ##\n# this python script uses an input distribution of eccDNAs called using uniquely mapped reads to probabilistically call putative eccDNAs with multi-mapped reads\n# this script specifically works on split reads with one side that is uniquely mapped\n# options\n# \"known_srs_length\" - input list of lengths of eccDNAs called using uniquely mapped reads\n# \"split_reads\" - input list of multi-mapped split reads with secondary alignments\n# \"column_cutoff\" - maximum length of output eccDNAs, usually determined by the maximum size of a molecule that can come out of a filtration column during circleseq library prep\n\nknown_srs_length = str(sys.argv[1])\nsplit_reads = str(sys.argv[2])\ncolumn_cutoff = int(sys.argv[3])\n\n# open the lengths of uniquely mapped eccDNAs and calculate a kernel density estimate\nwith open(known_srs_length, newline = '') as file: ## this is for each individual technical replicate\n    file_reader = csv.reader(file, delimiter = '\\t')\n    dsn_list = [int(row[0]) for row in file_reader]\ndensity = gaussian_kde(dsn_list)\nkde_max = 0\nwhile True:\n    if density(kde_max) == 0:\n        break\n    else:\n        kde_max += 100\nxs = np.linspace(0,kde_max,1000)\ndensities = density(xs)\ny_interp = scipy.interpolate.interp1d(xs,densities)\n\n## define regex for processing split reads\nstart_pattern = \"^([0-9]+)M.*[HS]$\"\nend_pattern = \".*[HS]([0-9]+)M$\"\n\n# use regex to grab the matches and nonmatches to the genome and count them\n# side one the uniquely mapped side, side two is the multimapped side\n# do this for each split read, to calculate all potential combinations of side one and side two later\ndef process_split_read(read):\n    matches = re.findall(r'(\\d+)([A-Z]{1})', read[6])\n    matches_sums = {'M': 0, 'other': 0}\n    for i in range(len(matches)):\n        if matches[i][1] == 'M':\n            matches_sums['M'] += int(matches[i][0])\n        else:\n            matches_sums['other'] += int(matches[i][0])\n    if str(read[5]) == '-':\n        sense = 'reverse'\n    elif str(read[5]) == '+':\n        sense = 'forward'\n    string = read[6]\n    if re.match(start_pattern, string):\n        loc = 'start'\n    elif re.match(end_pattern, string):\n        loc = 'end'\n    else:\n        return False ## if regexp doesn't work then just drop the split\n    if read[4] != 0:\n        split_read_side_one.append([read[0], int(read[1]), int(read[2]), sense, read[6], loc, matches_sums['M'], matches_sums['other']])\n    else:\n        split_read_side_two.append([read[0], int(read[1]), int(read[2]), sense, read[6], loc, matches_sums['M'], matches_sums['other']])\n    return True\n\n# go through all possible split read combinations and filter down to a subset that represent eccDNAs\n# then, of all of the possible combinations, randomly choose one\n# random choice is weighted based off KDE from uniquely mapped eccDNAs above\ndef choose_split_reads(split_read_side_one, split_read_side_two_pre):\n    if len(split_read_side_two_pre) == 0:\n        return False\n    split_read_side_two = np.array(split_read_side_two_pre, dtype=object)\n    combos = []\n    for i in range(len(split_read_side_one)):\n        split_read_first_side = split_read_side_one[i]\n        ## reduce to\n        # same chromosome\n        # same orientation\n        # distance smaller than column cutoff\n        # start and end pairs\n        # properly oriented (eccDNA vs intron)\n        # total of read lengths is around 150\n        if ((split_read_first_side[3] == 'forward' and split_read_first_side[5] == 'start') or \n            (split_read_first_side[3] == 'reverse' and split_read_first_side[5] == 'end')):\n                reduced = split_read_side_two[np.logical_and.reduce((split_read_side_two[:, 0] == split_read_first_side[0],\n                                       split_read_side_two[:, 3] == split_read_first_side[3],\n                                       abs(split_read_side_two[:,1] - split_read_first_side[1]) < column_cutoff,\n                                        split_read_side_two[:, 5] != split_read_first_side[5],\n                                        split_read_side_two[:,1] < split_read_first_side[1],\n                                        np.isclose((split_read_side_two[:,6] + split_read_first_side[6]).astype(int), (split_read_side_two[:,7] + split_read_first_side[7]).astype(int), atol=10)))]\n        if ((split_read_first_side[3] == 'forward' and split_read_first_side[5] == 'end') or\n            (split_read_first_side[3] == 'reverse' and split_read_first_side[5] == 'start')):\n                reduced = split_read_side_two[np.logical_and.reduce((split_read_side_two[:, 0] == split_read_first_side[0],\n                                       split_read_side_two[:, 3] == split_read_first_side[3],\n                                       abs(split_read_side_two[:,1] - split_read_first_side[1]) < column_cutoff,\n                                        split_read_side_two[:, 5] != split_read_first_side[5],\n                                        split_read_side_two[:,1] > split_read_first_side[1],\n                                        np.isclose((split_read_side_two[:,6] + split_read_first_side[6]).astype(int), (split_read_side_two[:,7] + split_read_first_side[7]).astype(int), atol=10)))]\n        if len(reduced) != 0:\n            for ii in range(len(reduced)):\n                split_read_second_side = reduced[ii]\n                start = min([split_read_first_side[1], split_read_first_side[2], split_read_second_side[1], split_read_second_side[2]])\n                end = max([split_read_first_side[1], split_read_first_side[2], split_read_second_side[1], split_read_second_side[2]])\n                combos.append([split_read_first_side[0], start, end])\n    if combos == []: # any of the options left?\n        return False\n    densities = []\n    for ii in range(len(combos)):\n        try:\n            densities.append(y_interp(abs(combos[ii][2]-combos[ii][1])))\n        except ValueError:\n            densities.append(0)\n    densities_sum = sum(densities)\n    if densities_sum == 0: ## any of the options possible?\n        return False\n    densities_array = np.array(densities)\n    densities_ratio = densities_array/densities_sum\n    choice = random.choices(combos, densities_ratio, k=1)[0]\n    return choice\n\n# run code without opening whole files into memory\n# write chosen split reads\nwith open(split_reads, newline = '') as file:\n    file_reader = csv.reader(file, delimiter = '\\t')\n    with open('singleunique_choices', 'w', newline = '') as confirmed:\n        w = csv.writer(confirmed, delimiter = '\\t')\n        for row in file_reader:\n            current_line = row\n            current_read = current_line[3]\n            split_read_side_one = []\n            split_read_side_two = []\n            while current_line[3] == current_read:\n                process_split_read(current_line)\n                try:\n                    current_line = next(file_reader)\n                except StopIteration:\n                    break\n            choice = choose_split_reads(split_read_side_one, split_read_side_two)\n            if choice:\n                w.writerow([choice[0], choice[1], choice[2]])", "meta": {"hexsha": "150167c5d8bd5ad778c1e83f8fcbf34f1af3bccc", "size": 8341, "ext": "py", "lang": "Python", "max_stars_repo_path": "python_scripts/ecc_calling_mapq0_singleunique.py", "max_stars_repo_name": "SentientFish/ecc_caller", "max_stars_repo_head_hexsha": "e2911dfbf0b3951e7c3345e3e6bec25a75ecf92e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-12-17T22:37:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T08:02:11.000Z", "max_issues_repo_path": "python_scripts/ecc_calling_mapq0_singleunique.py", "max_issues_repo_name": "SentientFish/ecc_caller", "max_issues_repo_head_hexsha": "e2911dfbf0b3951e7c3345e3e6bec25a75ecf92e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-30T19:39:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-02T19:25:30.000Z", "max_forks_repo_path": "python_scripts/ecc_calling_mapq0_singleunique.py", "max_forks_repo_name": "SentientFish/ecc_caller", "max_forks_repo_head_hexsha": "e2911dfbf0b3951e7c3345e3e6bec25a75ecf92e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-01-22T00:44:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-01T02:04:04.000Z", "avg_line_length": 51.1717791411, "max_line_length": 196, "alphanum_fraction": 0.6599928066, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 1951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.17278945800729079}}
{"text": "\"\"\"Lattice thermal conductivity calculation with RTA.\"\"\"\n# Copyright (C) 2020 Atsushi Togo\n# All rights reserved.\n#\n# This file is part of phono3py.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n#   notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n#   notice, this list of conditions and the following disclaimer in\n#   the documentation and/or other materials provided with the\n#   distribution.\n#\n# * Neither the name of the phonopy project nor the names of its\n#   contributors may be used to endorse or promote products derived\n#   from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport sys\n\nimport numpy as np\nfrom phonopy.phonon.group_velocity import GroupVelocity\nfrom phonopy.structure.tetrahedron_method import TetrahedronMethod\n\nfrom phono3py.file_IO import (\n    read_gamma_from_hdf5,\n    read_pp_from_hdf5,\n    write_gamma_detail_to_hdf5,\n    write_kappa_to_hdf5,\n)\nfrom phono3py.phonon3.conductivity import Conductivity, all_bands_exist, unit_to_WmK\nfrom phono3py.phonon3.conductivity import write_pp as _write_pp\nfrom phono3py.phonon3.imag_self_energy import ImagSelfEnergy, average_by_degeneracy\nfrom phono3py.phonon3.interaction import Interaction\nfrom phono3py.phonon3.triplets import get_all_triplets\nfrom phono3py.phonon.grid import get_grid_points_by_rotations\n\n\nclass Conductivity_RTA(Conductivity):\n    \"\"\"Lattice thermal conductivity calculation with RTA.\"\"\"\n\n    def __init__(\n        self,\n        interaction: Interaction,\n        grid_points=None,\n        temperatures=None,\n        sigmas=None,\n        sigma_cutoff=None,\n        is_isotope=False,\n        mass_variances=None,\n        boundary_mfp=None,  # in micrometre\n        use_ave_pp=False,\n        is_kappa_star=True,\n        gv_delta_q=None,\n        is_full_pp=False,\n        read_pp=False,\n        store_pp=False,\n        pp_filename=None,\n        is_N_U=False,\n        is_gamma_detail=False,\n        is_frequency_shift_by_bubble=False,\n        log_level=0,\n    ):\n        \"\"\"Init method.\"\"\"\n        self._pp: Interaction\n        self._grid_point_count: int\n        self._num_sampling_grid_points: int\n        self._gv_obj: GroupVelocity\n        self._temperatures = None\n        self._sigmas = None\n        self._sigma_cutoff = None\n        self._is_kappa_star = None\n        self._is_full_pp = None\n        self._is_N_U = is_N_U\n        self._is_gamma_detail = is_gamma_detail\n        self._is_frequency_shift_by_bubble = is_frequency_shift_by_bubble\n        self._log_level = None\n        self._boundary_mfp = None\n\n        self._point_operations = None\n        self._rotations_cartesian = None\n\n        self._grid_points = None\n        self._grid_weights = None\n\n        self._read_gamma = False\n        self._read_gamma_iso = False\n\n        self._frequencies = None\n        self._cv = None\n        self._gv = None\n        self._gv_sum2 = None\n        self._gamma = None\n        self._gamma_iso = None\n        self._gamma_N = None\n        self._gamma_U = None\n        self._gamma_detail_at_q = None\n        self._use_ave_pp = use_ave_pp\n        self._use_const_ave_pp = None\n        self._averaged_pp_interaction = None\n        self._num_ignored_phonon_modes = None\n\n        self._conversion_factor = None\n\n        self._is_isotope = None\n        self._isotope = None\n        self._mass_variances = None\n\n        super().__init__(\n            interaction,\n            grid_points=grid_points,\n            temperatures=temperatures,\n            sigmas=sigmas,\n            sigma_cutoff=sigma_cutoff,\n            is_isotope=is_isotope,\n            mass_variances=mass_variances,\n            boundary_mfp=boundary_mfp,\n            is_kappa_star=is_kappa_star,\n            gv_delta_q=gv_delta_q,\n            is_full_pp=is_full_pp,\n            log_level=log_level,\n        )\n\n        self._use_const_ave_pp = self._pp.get_constant_averaged_interaction()\n        self._read_pp = read_pp\n        self._store_pp = store_pp\n        self._pp_filename = pp_filename\n\n        if self._temperatures is not None:\n            self._allocate_values()\n\n    def set_kappa_at_sigmas(self):\n        \"\"\"Calculate kappa from ph-ph interaction results.\"\"\"\n        num_band = len(self._pp.primitive) * 3\n        for i, grid_point in enumerate(self._grid_points):\n            cv = self._cv[:, i, :]\n            gp = self._grid_points[i]\n            frequencies = self._frequencies[gp]\n\n            # Kappa\n            for j in range(len(self._sigmas)):\n                for k in range(len(self._temperatures)):\n                    g_sum = self._get_main_diagonal(i, j, k)\n                    for ll in range(num_band):\n                        if frequencies[ll] < self._pp.cutoff_frequency:\n                            self._num_ignored_phonon_modes[j, k] += 1\n                            continue\n\n                        old_settings = np.seterr(all=\"raise\")\n                        try:\n                            self._mode_kappa[j, k, i, ll] = (\n                                self._gv_sum2[i, ll]\n                                * cv[k, ll]\n                                / (g_sum[ll] * 2)\n                                * self._conversion_factor\n                            )\n                        except FloatingPointError:\n                            # supposed that g is almost 0 and |gv|=0\n                            pass\n                        except Exception:\n                            print(\"=\" * 26 + \" Warning \" + \"=\" * 26)\n                            print(\n                                \" Unexpected physical condition of ph-ph \"\n                                \"interaction calculation was found.\"\n                            )\n                            print(\n                                \" g=%f at gp=%d, band=%d, freq=%f\"\n                                % (g_sum[ll], gp, ll + 1, frequencies[ll])\n                            )\n                            print(\"=\" * 61)\n                        np.seterr(**old_settings)\n\n        N = self._num_sampling_grid_points\n        self._kappa = self._mode_kappa.sum(axis=2).sum(axis=2) / N\n\n    def get_gamma_N_U(self):\n        \"\"\"Return N and U parts of gamma.\"\"\"\n        return (self._gamma_N, self._gamma_U)\n\n    def set_gamma_N_U(self, gamma_N, gamma_U):\n        \"\"\"Set N and U parts of gamma.\"\"\"\n        self._gamma_N = gamma_N\n        self._gamma_U = gamma_U\n\n    def get_gamma_detail_at_q(self):\n        \"\"\"Return contribution of each triplet to gamma at current q-point.\"\"\"\n        return self._gamma_detail_at_q\n\n    def get_number_of_ignored_phonon_modes(self):\n        \"\"\"Return number of ignored phonon modes.\"\"\"\n        return self._num_ignored_phonon_modes\n\n    def set_averaged_pp_interaction(self, ave_pp):\n        \"\"\"Set averaged ph-ph interaction.\"\"\"\n        self._averaged_pp_interaction = ave_pp\n\n    def _run_at_grid_point(self):\n        i_gp = self._grid_point_count\n        self._show_log_header(i_gp)\n        grid_point = self._grid_points[i_gp]\n        self._set_cv(i_gp, i_gp)\n        self._set_gv(i_gp, i_gp)\n        self._set_gv_by_gv(i_gp, i_gp)\n\n        if self._read_gamma:\n            if self._use_ave_pp:\n                self._collision.set_grid_point(grid_point)\n                self._set_gamma_at_sigmas(i_gp)\n        else:\n            self._collision.set_grid_point(grid_point)\n            num_triplets = len(self._pp.get_triplets_at_q()[0])\n            if self._log_level:\n                print(\"Number of triplets: %d\" % num_triplets)\n\n            if (\n                self._is_full_pp\n                or self._read_pp\n                or self._store_pp\n                or self._use_ave_pp\n                or self._use_const_ave_pp\n                or self._is_gamma_detail\n            ):\n                self._set_gamma_at_sigmas(i_gp)\n            else:  # can save memory space\n                self._set_gamma_at_sigmas_lowmem(i_gp)\n\n        if self._isotope is not None and not self._read_gamma_iso:\n            gamma_iso = self._get_gamma_isotope_at_sigmas(i_gp)\n            self._gamma_iso[:, i_gp, :] = gamma_iso[:, self._pp.band_indices]\n\n        if self._log_level:\n            self._show_log(self._qpoints[i_gp], i_gp)\n\n    def _allocate_values(self):\n        num_band0 = len(self._pp.band_indices)\n        num_grid_points = len(self._grid_points)\n        num_temp = len(self._temperatures)\n        self._kappa = np.zeros(\n            (len(self._sigmas), num_temp, 6), order=\"C\", dtype=\"double\"\n        )\n        self._mode_kappa = np.zeros(\n            (len(self._sigmas), num_temp, num_grid_points, num_band0, 6),\n            order=\"C\",\n            dtype=\"double\",\n        )\n        if not self._read_gamma:\n            self._gamma = np.zeros(\n                (len(self._sigmas), num_temp, num_grid_points, num_band0),\n                order=\"C\",\n                dtype=\"double\",\n            )\n            if self._is_gamma_detail or self._is_N_U:\n                self._gamma_N = np.zeros_like(self._gamma)\n                self._gamma_U = np.zeros_like(self._gamma)\n        self._gv = np.zeros((num_grid_points, num_band0, 3), order=\"C\", dtype=\"double\")\n        self._gv_sum2 = np.zeros(\n            (num_grid_points, num_band0, 6), order=\"C\", dtype=\"double\"\n        )\n        self._cv = np.zeros(\n            (num_temp, num_grid_points, num_band0), order=\"C\", dtype=\"double\"\n        )\n        if self._isotope is not None:\n            self._gamma_iso = np.zeros(\n                (len(self._sigmas), num_grid_points, num_band0),\n                order=\"C\",\n                dtype=\"double\",\n            )\n        if self._is_full_pp or self._use_ave_pp or self._use_const_ave_pp:\n            self._averaged_pp_interaction = np.zeros(\n                (num_grid_points, num_band0), order=\"C\", dtype=\"double\"\n            )\n        self._num_ignored_phonon_modes = np.zeros(\n            (len(self._sigmas), num_temp), order=\"C\", dtype=\"intc\"\n        )\n        self._collision = ImagSelfEnergy(\n            self._pp, with_detail=(self._is_gamma_detail or self._is_N_U)\n        )\n\n    def _set_gamma_at_sigmas(self, i):\n        for j, sigma in enumerate(self._sigmas):\n            self._collision.set_sigma(sigma, sigma_cutoff=self._sigma_cutoff)\n            self._collision.set_integration_weights()\n\n            if self._log_level:\n                text = \"Collisions will be calculated with \"\n                if sigma is None:\n                    text += \"tetrahedron method.\"\n                else:\n                    text += \"sigma=%s\" % sigma\n                    if self._sigma_cutoff is None:\n                        text += \".\"\n                    else:\n                        text += \"(%4.2f SD).\" % self._sigma_cutoff\n                print(text)\n\n            if self._read_pp:\n                pp, _g_zero = read_pp_from_hdf5(\n                    self._pp.mesh_numbers,\n                    grid_point=self._grid_points[i],\n                    sigma=sigma,\n                    sigma_cutoff=self._sigma_cutoff,\n                    filename=self._pp_filename,\n                    verbose=(self._log_level > 0),\n                )\n                _, g_zero = self._collision.get_integration_weights()\n                if self._log_level:\n                    if len(self._sigmas) > 1:\n                        print(\n                            \"Multiple sigmas or mixing smearing and \"\n                            \"tetrahedron method is not supported.\"\n                        )\n                if _g_zero is not None and (_g_zero != g_zero).any():\n                    raise ValueError(\"Inconsistency found in g_zero.\")\n                self._collision.set_interaction_strength(pp)\n            elif self._use_ave_pp:\n                self._collision.set_averaged_pp_interaction(\n                    self._averaged_pp_interaction[i]\n                )\n            elif self._use_const_ave_pp:\n                if self._log_level:\n                    print(\n                        \"Constant ph-ph interaction of %6.3e is used.\"\n                        % self._pp.get_constant_averaged_interaction()\n                    )\n                self._collision.run_interaction()\n                self._averaged_pp_interaction[i] = self._pp.get_averaged_interaction()\n            elif j != 0 and (self._is_full_pp or self._sigma_cutoff is None):\n                if self._log_level:\n                    print(\"Existing ph-ph interaction is used.\")\n            else:\n                if self._log_level:\n                    print(\"Calculating ph-ph interaction...\")\n                self._collision.run_interaction(is_full_pp=self._is_full_pp)\n                if self._is_full_pp:\n                    self._averaged_pp_interaction[\n                        i\n                    ] = self._pp.get_averaged_interaction()\n\n            # Number of triplets depends on q-point.\n            # So this is allocated each time.\n            if self._is_gamma_detail:\n                num_temp = len(self._temperatures)\n                self._gamma_detail_at_q = np.empty(\n                    ((num_temp,) + self._pp.get_interaction_strength().shape),\n                    dtype=\"double\",\n                    order=\"C\",\n                )\n                self._gamma_detail_at_q[:] = 0\n\n            if self._log_level:\n                print(\"Calculating collisions at temperatures...\")\n            for k, t in enumerate(self._temperatures):\n                self._collision.set_temperature(t)\n                self._collision.run()\n                self._gamma[j, k, i] = self._collision.get_imag_self_energy()\n                if self._is_N_U or self._is_gamma_detail:\n                    g_N, g_U = self._collision.get_imag_self_energy_N_and_U()\n                    self._gamma_N[j, k, i] = g_N\n                    self._gamma_U[j, k, i] = g_U\n                if self._is_gamma_detail:\n                    self._gamma_detail_at_q[\n                        k\n                    ] = self._collision.get_detailed_imag_self_energy()\n\n    def _set_gamma_at_sigmas_lowmem(self, i):\n        \"\"\"Calculate gamma without storing ph-ph interaction strength.\n\n        `svecs` and `multi` below must not be simply replaced by\n        `self._pp.primitive.get_smallest_vectors()` because they must be in\n        dense format as always so in Interaction class instance.\n        `p2s`, `s2p`, and `masses` have to be also given from Interaction\n        class instance.\n\n        \"\"\"\n        band_indices = self._pp.band_indices\n        (\n            svecs,\n            multi,\n            p2s,\n            s2p,\n            masses,\n        ) = self._pp.get_primitive_and_supercell_correspondence()\n        fc3 = self._pp.fc3\n        triplets_at_q, weights_at_q, _, _ = self._pp.get_triplets_at_q()\n        symmetrize_fc3_q = 0\n\n        if None in self._sigmas:\n            thm = TetrahedronMethod(self._pp.bz_grid.microzone_lattice)\n\n        # It is assumed that self._sigmas = [None].\n        for j, sigma in enumerate(self._sigmas):\n            self._collision.set_sigma(sigma)\n            if self._is_N_U:\n                collisions = np.zeros(\n                    (2, len(self._temperatures), len(band_indices)),\n                    dtype=\"double\",\n                    order=\"C\",\n                )\n            else:\n                collisions = np.zeros(\n                    (len(self._temperatures), len(band_indices)),\n                    dtype=\"double\",\n                    order=\"C\",\n                )\n            import phono3py._phono3py as phono3c\n\n            if sigma is None:\n                phono3c.pp_collision(\n                    collisions,\n                    np.array(\n                        np.dot(thm.get_tetrahedra(), self._pp.bz_grid.P.T),\n                        dtype=\"int_\",\n                        order=\"C\",\n                    ),\n                    self._frequencies,\n                    self._eigenvectors,\n                    triplets_at_q,\n                    weights_at_q,\n                    self._pp.bz_grid.addresses,\n                    self._pp.bz_grid.gp_map,\n                    self._pp.bz_grid.store_dense_gp_map * 1 + 1,\n                    self._pp.bz_grid.D_diag,\n                    self._pp.bz_grid.Q,\n                    fc3,\n                    svecs,\n                    multi,\n                    masses,\n                    p2s,\n                    s2p,\n                    band_indices,\n                    self._temperatures,\n                    self._is_N_U * 1,\n                    symmetrize_fc3_q,\n                    self._pp.cutoff_frequency,\n                )\n            else:\n                if self._sigma_cutoff is None:\n                    sigma_cutoff = -1\n                else:\n                    sigma_cutoff = float(self._sigma_cutoff)\n                phono3c.pp_collision_with_sigma(\n                    collisions,\n                    sigma,\n                    sigma_cutoff,\n                    self._frequencies,\n                    self._eigenvectors,\n                    triplets_at_q,\n                    weights_at_q,\n                    self._pp.bz_grid.addresses,\n                    self._pp.bz_grid.D_diag,\n                    self._pp.bz_grid.Q,\n                    fc3,\n                    svecs,\n                    multi,\n                    masses,\n                    p2s,\n                    s2p,\n                    band_indices,\n                    self._temperatures,\n                    self._is_N_U * 1,\n                    symmetrize_fc3_q,\n                    self._pp.cutoff_frequency,\n                )\n            col_unit_conv = self._collision.get_unit_conversion_factor()\n            pp_unit_conv = self._pp.get_unit_conversion_factor()\n            if self._is_N_U:\n                col = collisions.sum(axis=0)\n                col_N = collisions[0]\n                col_U = collisions[1]\n            else:\n                col = collisions\n            for k in range(len(self._temperatures)):\n                self._gamma[j, k, i, :] = average_by_degeneracy(\n                    col[k] * col_unit_conv * pp_unit_conv,\n                    band_indices,\n                    self._frequencies[self._grid_points[i]],\n                )\n                if self._is_N_U:\n                    self._gamma_N[j, k, i, :] = average_by_degeneracy(\n                        col_N[k] * col_unit_conv * pp_unit_conv,\n                        band_indices,\n                        self._frequencies[self._grid_points[i]],\n                    )\n                    self._gamma_U[j, k, i, :] = average_by_degeneracy(\n                        col_U[k] * col_unit_conv * pp_unit_conv,\n                        band_indices,\n                        self._frequencies[self._grid_points[i]],\n                    )\n\n    def _show_log(self, q, i):\n        gp = self._grid_points[i]\n        frequencies = self._frequencies[gp][self._pp.band_indices]\n        gv = self._gv[i]\n        if self._averaged_pp_interaction is not None:\n            ave_pp = self._averaged_pp_interaction[i]\n        else:\n            ave_pp = None\n        self._show_log_value_names()\n\n        if self._log_level > 2:\n            self._show_log_values_on_kstar(frequencies, gv, ave_pp, gp, q)\n        else:\n            self._show_log_values(frequencies, gv, ave_pp)\n\n        sys.stdout.flush()\n\n    def _show_log_values(self, frequencies, gv, ave_pp):\n        if self._is_full_pp or self._use_ave_pp or self._use_const_ave_pp:\n            for f, v, pp in zip(frequencies, gv, ave_pp):\n                print(\n                    \"%8.3f   (%8.3f %8.3f %8.3f) %8.3f %11.3e\"\n                    % (f, v[0], v[1], v[2], np.linalg.norm(v), pp)\n                )\n        else:\n            for f, v in zip(frequencies, gv):\n                print(\n                    \"%8.3f   (%8.3f %8.3f %8.3f) %8.3f\"\n                    % (f, v[0], v[1], v[2], np.linalg.norm(v))\n                )\n\n    def _show_log_values_on_kstar(self, frequencies, gv, ave_pp, gp, q):\n        rotation_map = get_grid_points_by_rotations(gp, self._pp.bz_grid)\n        for i, j in enumerate(np.unique(rotation_map)):\n            for k, (rot, rot_c) in enumerate(\n                zip(self._point_operations, self._rotations_cartesian)\n            ):\n                if rotation_map[k] != j:\n                    continue\n\n                print(\n                    \" k*%-2d (%5.2f %5.2f %5.2f)\" % ((i + 1,) + tuple(np.dot(rot, q)))\n                )\n                if self._is_full_pp or self._use_ave_pp or self._use_const_ave_pp:\n                    for f, v, pp in zip(frequencies, np.dot(rot_c, gv.T).T, ave_pp):\n                        print(\n                            \"%8.3f   (%8.3f %8.3f %8.3f) %8.3f %11.3e\"\n                            % (f, v[0], v[1], v[2], np.linalg.norm(v), pp)\n                        )\n                else:\n                    for f, v in zip(frequencies, np.dot(rot_c, gv.T).T):\n                        print(\n                            \"%8.3f   (%8.3f %8.3f %8.3f) %8.3f\"\n                            % (f, v[0], v[1], v[2], np.linalg.norm(v))\n                        )\n        print(\"\")\n\n    def _show_log_value_names(self):\n        if self._is_full_pp or self._use_ave_pp or self._use_const_ave_pp:\n            text = \"Frequency     group velocity (x, y, z)     |gv|       Pqj\"\n        else:\n            text = \"Frequency     group velocity (x, y, z)     |gv|\"\n        if self._gv_obj.q_length is None:\n            pass\n        else:\n            text += \"  (dq=%3.1e)\" % self._gv_obj.q_length\n        print(text)\n\n\ndef get_thermal_conductivity_RTA(\n    interaction: Interaction,\n    temperatures=None,\n    sigmas=None,\n    sigma_cutoff=None,\n    mass_variances=None,\n    grid_points=None,\n    is_isotope=False,\n    boundary_mfp=None,  # in micrometre\n    use_ave_pp=False,\n    is_kappa_star=True,\n    gv_delta_q=None,\n    is_full_pp=False,\n    write_gamma=False,\n    read_gamma=False,\n    is_N_U=False,\n    write_kappa=False,\n    write_pp=False,\n    read_pp=False,\n    write_gamma_detail=False,\n    compression=\"gzip\",\n    input_filename=None,\n    output_filename=None,\n    log_level=0,\n):\n    \"\"\"Run RTA thermal conductivity calculation.\"\"\"\n    if temperatures is None:\n        _temperatures = np.arange(0, 1001, 10, dtype=\"double\")\n    else:\n        _temperatures = temperatures\n\n    if log_level:\n        print(\n            \"-------------------- Lattice thermal conducitivity (RTA) \"\n            \"--------------------\"\n        )\n    br = Conductivity_RTA(\n        interaction,\n        grid_points=grid_points,\n        temperatures=_temperatures,\n        sigmas=sigmas,\n        sigma_cutoff=sigma_cutoff,\n        is_isotope=is_isotope,\n        mass_variances=mass_variances,\n        boundary_mfp=boundary_mfp,\n        use_ave_pp=use_ave_pp,\n        is_kappa_star=is_kappa_star,\n        gv_delta_q=gv_delta_q,\n        is_full_pp=is_full_pp,\n        read_pp=read_pp,\n        store_pp=write_pp,\n        pp_filename=input_filename,\n        is_N_U=is_N_U,\n        is_gamma_detail=write_gamma_detail,\n        log_level=log_level,\n    )\n\n    if read_gamma:\n        if not _set_gamma_from_file(br, filename=input_filename):\n            print(\"Reading collisions failed.\")\n            return False\n\n    for i in br:\n        if write_pp:\n            _write_pp(\n                br, interaction, i, compression=compression, filename=output_filename\n            )\n        if write_gamma:\n            _write_gamma(\n                br,\n                interaction,\n                i,\n                compression=compression,\n                filename=output_filename,\n                verbose=log_level,\n            )\n        if write_gamma_detail:\n            _write_gamma_detail(\n                br,\n                interaction,\n                i,\n                compression=compression,\n                filename=output_filename,\n                verbose=log_level,\n            )\n\n    if grid_points is None and all_bands_exist(interaction):\n        br.set_kappa_at_sigmas()\n        if log_level:\n            _show_kappa(br, log_level)\n        if write_kappa:\n            _write_kappa(\n                br,\n                interaction.primitive.volume,\n                compression=compression,\n                filename=output_filename,\n                log_level=log_level,\n            )\n\n    return br\n\n\ndef _write_gamma_detail(\n    br, interaction, i, compression=\"gzip\", filename=None, verbose=True\n):\n    gamma_detail = br.get_gamma_detail_at_q()\n    temperatures = br.get_temperatures()\n    mesh = br.get_mesh_numbers()\n    grid_points = br.get_grid_points()\n    gp = grid_points[i]\n    sigmas = br.get_sigmas()\n    sigma_cutoff = br.get_sigma_cutoff_width()\n    triplets, weights, _, _ = interaction.get_triplets_at_q()\n    all_triplets = get_all_triplets(gp, interaction.bz_grid)\n\n    if all_bands_exist(interaction):\n        for j, sigma in enumerate(sigmas):\n            write_gamma_detail_to_hdf5(\n                temperatures,\n                mesh,\n                gamma_detail=gamma_detail,\n                grid_point=gp,\n                triplet=triplets,\n                weight=weights,\n                triplet_all=all_triplets,\n                sigma=sigma,\n                sigma_cutoff=sigma_cutoff,\n                compression=compression,\n                filename=filename,\n                verbose=verbose,\n            )\n    else:\n        for j, sigma in enumerate(sigmas):\n            for k, bi in enumerate(interaction.get_band_indices()):\n                write_gamma_detail_to_hdf5(\n                    temperatures,\n                    mesh,\n                    gamma_detail=gamma_detail[:, :, k, :, :],\n                    grid_point=gp,\n                    triplet=triplets,\n                    weight=weights,\n                    band_index=bi,\n                    sigma=sigma,\n                    sigma_cutoff=sigma_cutoff,\n                    compression=compression,\n                    filename=filename,\n                    verbose=verbose,\n                )\n\n\ndef _write_gamma(br, interaction, i, compression=\"gzip\", filename=None, verbose=True):\n    \"\"\"Write mode kappa related properties into a hdf5 file.\"\"\"\n    grid_points = br.grid_points\n    group_velocities = br.group_velocities\n    gv_by_gv = br.gv_by_gv\n    mode_heat_capacities = br.mode_heat_capacities\n    ave_pp = br.averaged_pp_interaction\n    mesh = br.mesh_numbers\n    temperatures = br.temperatures\n    gamma = br.gamma\n    gamma_isotope = br.gamma_isotope\n    sigmas = br.sigmas\n    sigma_cutoff = br.sigma_cutoff_width\n    volume = interaction.primitive.volume\n    gamma_N, gamma_U = br.get_gamma_N_U()\n\n    gp = grid_points[i]\n    if all_bands_exist(interaction):\n        if ave_pp is None:\n            ave_pp_i = None\n        else:\n            ave_pp_i = ave_pp[i]\n        frequencies = interaction.get_phonons()[0][gp]\n        for j, sigma in enumerate(sigmas):\n            if gamma_isotope is not None:\n                gamma_isotope_at_sigma = gamma_isotope[j, i]\n            else:\n                gamma_isotope_at_sigma = None\n            if gamma_N is None:\n                gamma_N_at_sigma = None\n            else:\n                gamma_N_at_sigma = gamma_N[j, :, i]\n            if gamma_U is None:\n                gamma_U_at_sigma = None\n            else:\n                gamma_U_at_sigma = gamma_U[j, :, i]\n\n            write_kappa_to_hdf5(\n                temperatures,\n                mesh,\n                frequency=frequencies,\n                group_velocity=group_velocities[i],\n                gv_by_gv=gv_by_gv[i],\n                heat_capacity=mode_heat_capacities[:, i],\n                gamma=gamma[j, :, i],\n                gamma_isotope=gamma_isotope_at_sigma,\n                gamma_N=gamma_N_at_sigma,\n                gamma_U=gamma_U_at_sigma,\n                averaged_pp_interaction=ave_pp_i,\n                grid_point=gp,\n                sigma=sigma,\n                sigma_cutoff=sigma_cutoff,\n                kappa_unit_conversion=unit_to_WmK / volume,\n                compression=compression,\n                filename=filename,\n                verbose=verbose,\n            )\n    else:\n        for j, sigma in enumerate(sigmas):\n            for k, bi in enumerate(interaction.band_indices):\n                if ave_pp is None:\n                    ave_pp_ik = None\n                else:\n                    ave_pp_ik = ave_pp[i, k]\n                frequencies = interaction.get_phonons()[0][gp, bi]\n                if gamma_isotope is not None:\n                    gamma_isotope_at_sigma = gamma_isotope[j, i, k]\n                else:\n                    gamma_isotope_at_sigma = None\n                if gamma_N is None:\n                    gamma_N_at_sigma = None\n                else:\n                    gamma_N_at_sigma = gamma_N[j, :, i, k]\n                if gamma_U is None:\n                    gamma_U_at_sigma = None\n                else:\n                    gamma_U_at_sigma = gamma_U[j, :, i, k]\n                write_kappa_to_hdf5(\n                    temperatures,\n                    mesh,\n                    frequency=frequencies,\n                    group_velocity=group_velocities[i, k],\n                    gv_by_gv=gv_by_gv[i, k],\n                    heat_capacity=mode_heat_capacities[:, i, k],\n                    gamma=gamma[j, :, i, k],\n                    gamma_isotope=gamma_isotope_at_sigma,\n                    gamma_N=gamma_N_at_sigma,\n                    gamma_U=gamma_U_at_sigma,\n                    averaged_pp_interaction=ave_pp_ik,\n                    grid_point=gp,\n                    band_index=bi,\n                    sigma=sigma,\n                    sigma_cutoff=sigma_cutoff,\n                    kappa_unit_conversion=unit_to_WmK / volume,\n                    compression=compression,\n                    filename=filename,\n                    verbose=verbose,\n                )\n\n\ndef _show_kappa(br, log_level):\n    temperatures = br.temperatures\n    sigmas = br.sigmas\n    kappa = br.kappa\n    num_ignored_phonon_modes = br.get_number_of_ignored_phonon_modes()\n    num_band = br.frequencies.shape[1]\n    num_phonon_modes = br.get_number_of_sampling_grid_points() * num_band\n    for i, sigma in enumerate(sigmas):\n        text = \"----------- Thermal conductivity (W/m-k) \"\n        if sigma:\n            text += \"for sigma=%s -----------\" % sigma\n        else:\n            text += \"with tetrahedron method -----------\"\n        print(text)\n        if log_level > 1:\n            print(\n                (\"#%6s       \" + \" %-10s\" * 6 + \"#ipm\")\n                % (\"T(K)\", \"xx\", \"yy\", \"zz\", \"yz\", \"xz\", \"xy\")\n            )\n            for j, (t, k) in enumerate(zip(temperatures, kappa[i])):\n                print(\n                    (\"%7.1f\" + \" %10.3f\" * 6 + \" %d/%d\")\n                    % (\n                        (t,)\n                        + tuple(k)\n                        + (num_ignored_phonon_modes[i, j], num_phonon_modes)\n                    )\n                )\n        else:\n            print(\n                (\"#%6s       \" + \" %-10s\" * 6)\n                % (\"T(K)\", \"xx\", \"yy\", \"zz\", \"yz\", \"xz\", \"xy\")\n            )\n            for j, (t, k) in enumerate(zip(temperatures, kappa[i])):\n                print((\"%7.1f \" + \" %10.3f\" * 6) % ((t,) + tuple(k)))\n        print(\"\")\n\n\ndef _write_kappa(br, volume, compression=\"gzip\", filename=None, log_level=0):\n    temperatures = br.temperatures\n    sigmas = br.sigmas\n    sigma_cutoff = br.sigma_cutoff_width\n    gamma = br.gamma\n    gamma_isotope = br.gamma_isotope\n    gamma_N, gamma_U = br.get_gamma_N_U()\n    mesh = br.mesh_numbers\n    frequencies = br.frequencies\n    gv = br.group_velocities\n    gv_by_gv = br.gv_by_gv\n    mode_cv = br.mode_heat_capacities\n    ave_pp = br.averaged_pp_interaction\n    qpoints = br.qpoints\n    weights = br.grid_weights\n    kappa = br.kappa\n    mode_kappa = br.mode_kappa\n\n    for i, sigma in enumerate(sigmas):\n        kappa_at_sigma = kappa[i]\n        if gamma_isotope is not None:\n            gamma_isotope_at_sigma = gamma_isotope[i]\n        else:\n            gamma_isotope_at_sigma = None\n        if gamma_N is None:\n            gamma_N_at_sigma = None\n        else:\n            gamma_N_at_sigma = gamma_N[i]\n        if gamma_U is None:\n            gamma_U_at_sigma = None\n        else:\n            gamma_U_at_sigma = gamma_U[i]\n\n        write_kappa_to_hdf5(\n            temperatures,\n            mesh,\n            frequency=frequencies,\n            group_velocity=gv,\n            gv_by_gv=gv_by_gv,\n            heat_capacity=mode_cv,\n            kappa=kappa_at_sigma,\n            mode_kappa=mode_kappa[i],\n            gamma=gamma[i],\n            gamma_isotope=gamma_isotope_at_sigma,\n            gamma_N=gamma_N_at_sigma,\n            gamma_U=gamma_U_at_sigma,\n            averaged_pp_interaction=ave_pp,\n            qpoint=qpoints,\n            weight=weights,\n            sigma=sigma,\n            sigma_cutoff=sigma_cutoff,\n            kappa_unit_conversion=unit_to_WmK / volume,\n            compression=compression,\n            filename=filename,\n            verbose=log_level,\n        )\n\n\ndef _set_gamma_from_file(br, filename=None, verbose=True):\n    \"\"\"Read kappa-*.hdf5 files for thermal conductivity calculation.\"\"\"\n    sigmas = br.get_sigmas()\n    sigma_cutoff = br.get_sigma_cutoff_width()\n    mesh = br.get_mesh_numbers()\n    grid_points = br.get_grid_points()\n    temperatures = br.get_temperatures()\n    num_band = br.get_frequencies().shape[1]\n\n    gamma = np.zeros(\n        (len(sigmas), len(temperatures), len(grid_points), num_band), dtype=\"double\"\n    )\n    gamma_N = np.zeros_like(gamma)\n    gamma_U = np.zeros_like(gamma)\n    gamma_iso = np.zeros((len(sigmas), len(grid_points), num_band), dtype=\"double\")\n    ave_pp = np.zeros((len(grid_points), num_band), dtype=\"double\")\n\n    is_gamma_N_U_in = False\n    is_ave_pp_in = False\n    read_succeeded = True\n\n    for j, sigma in enumerate(sigmas):\n        data = read_gamma_from_hdf5(\n            mesh,\n            sigma=sigma,\n            sigma_cutoff=sigma_cutoff,\n            filename=filename,\n            verbose=verbose,\n        )\n        if data:\n            gamma[j] = data[\"gamma\"]\n            if \"gamma_isotope\" in data:\n                gamma_iso[j] = data[\"gamma_isotope\"]\n            if \"gamma_N\" in data:\n                is_gamma_N_U_in = True\n                gamma_N[j] = data[\"gamma_N\"]\n                gamma_U[j] = data[\"gamma_U\"]\n            if \"ave_pp\" in data:\n                is_ave_pp_in = True\n                ave_pp[:] = data[\"ave_pp\"]\n        else:\n            for i, gp in enumerate(grid_points):\n                data_gp = read_gamma_from_hdf5(\n                    mesh,\n                    grid_point=gp,\n                    sigma=sigma,\n                    sigma_cutoff=sigma_cutoff,\n                    filename=filename,\n                    verbose=verbose,\n                )\n                if data_gp:\n                    gamma[j, :, i] = data_gp[\"gamma\"]\n                    if \"gamma_iso\" in data_gp:\n                        gamma_iso[j, i] = data_gp[\"gamma_iso\"]\n                    if \"gamma_N\" in data_gp:\n                        is_gamma_N_U_in = True\n                        gamma_N[j, :, i] = data_gp[\"gamma_N\"]\n                        gamma_U[j, :, i] = data_gp[\"gamma_U\"]\n                    if \"ave_pp\" in data_gp:\n                        is_ave_pp_in = True\n                        ave_pp[i] = data_gp[\"ave_pp\"]\n                else:\n                    for bi in range(num_band):\n                        data_band = read_gamma_from_hdf5(\n                            mesh,\n                            grid_point=gp,\n                            band_index=bi,\n                            sigma=sigma,\n                            sigma_cutoff=sigma_cutoff,\n                            filename=filename,\n                            verbose=verbose,\n                        )\n                        if data_band:\n                            gamma[j, :, i, bi] = data_band[\"gamma\"]\n                            if \"gamma_iso\" in data_band:\n                                gamma_iso[j, i, bi] = data_band[\"gamma_iso\"]\n                            if \"gamma_N\" in data_band:\n                                is_gamma_N_U_in = True\n                                gamma_N[j, :, i, bi] = data_band[\"gamma_N\"]\n                                gamma_U[j, :, i, bi] = data_band[\"gamma_U\"]\n                            if \"ave_pp\" in data_band:\n                                is_ave_pp_in = True\n                                ave_pp[i, bi] = data_band[\"ave_pp\"]\n                        else:\n                            read_succeeded = False\n\n    if read_succeeded:\n        br.set_gamma(gamma)\n        if is_ave_pp_in:\n            br.set_averaged_pp_interaction(ave_pp)\n        if is_gamma_N_U_in:\n            br.set_gamma_N_U(gamma_N, gamma_U)\n        return True\n    else:\n        return False\n", "meta": {"hexsha": "22dc65776a6603dcaf669409e6469e313294ea3a", "size": 37769, "ext": "py", "lang": "Python", "max_stars_repo_path": "phono3py/phonon3/conductivity_RTA.py", "max_stars_repo_name": "phonopy/phono3py", "max_stars_repo_head_hexsha": "c3246c0384f3596cb2ff109193b9106ddb466b56", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2020-05-28T09:52:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T10:37:21.000Z", "max_issues_repo_path": "phono3py/phonon3/conductivity_RTA.py", "max_issues_repo_name": "phonopy/phono3py", "max_issues_repo_head_hexsha": "c3246c0384f3596cb2ff109193b9106ddb466b56", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 56, "max_issues_repo_issues_event_min_datetime": "2020-05-02T22:11:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T20:35:12.000Z", "max_forks_repo_path": "phono3py/phonon3/conductivity_RTA.py", "max_forks_repo_name": "phonopy/phono3py", "max_forks_repo_head_hexsha": "c3246c0384f3596cb2ff109193b9106ddb466b56", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2020-06-06T21:20:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T10:24:13.000Z", "avg_line_length": 37.1376597837, "max_line_length": 87, "alphanum_fraction": 0.527257804, "include": true, "reason": "import numpy", "num_tokens": 8350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.30735801052067535, "lm_q1q2_score": 0.17278945538290136}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#\n\n'''\nRestricted open-shell Hartree-Fock for periodic systems at a single k-point\n\nSee Also:\n    pyscf/pbc/scf/khf.py : Hartree-Fock for periodic systems with k-point sampling\n'''\n\nimport numpy as np\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf.scf import rohf as mol_rohf\nfrom pyscf.pbc.scf import hf as pbchf\nfrom pyscf.pbc.scf import uhf as pbcuhf\nfrom pyscf import __config__\n\n\nget_fock = mol_rohf.get_fock\nget_occ = mol_rohf.get_occ\nget_grad = mol_rohf.get_grad\nmake_rdm1 = mol_rohf.make_rdm1\nenergy_elec = mol_rohf.energy_elec\n\nclass ROHF(mol_rohf.ROHF, pbchf.RHF):\n    '''ROHF class for PBCs.\n    '''\n\n    direct_scf = getattr(__config__, 'pbc_scf_SCF_direct_scf', False)\n\n    def __init__(self, cell, kpt=np.zeros(3),\n                 exxdiv=getattr(__config__, 'pbc_scf_SCF_exxdiv', 'ewald')):\n        pbchf.SCF.__init__(self, cell, kpt, exxdiv)\n        self.nelec = None\n        self._keys = self._keys.union(['nelec'])\n\n    def dump_flags(self):\n        pbchf.SCF.dump_flags(self)\n        if self.nelec is None:\n            nelec = self.cell.nelec\n        else:\n            nelec = self.nelec\n        logger.info(self, 'number of electrons per unit cell  '\n                    'alpha = %d beta = %d', *nelec)\n        return self\n\n    build = pbchf.SCF.build\n    check_sanity = pbchf.SCF.check_sanity\n    get_hcore = pbchf.SCF.get_hcore\n    get_ovlp = pbchf.SCF.get_ovlp\n    get_jk = pbchf.SCF.get_jk\n    get_j = pbchf.SCF.get_j\n    get_k = pbchf.SCF.get_k\n    get_jk_incore = pbchf.SCF.get_jk_incore\n    energy_tot = pbchf.SCF.energy_tot\n\n    def get_veff(self, cell=None, dm=None, dm_last=0, vhf_last=0, hermi=1,\n                 kpt=None, kpts_band=None):\n        if cell is None: cell = self.cell\n        if dm is None: dm = self.make_rdm1()\n        if kpt is None: kpt = self.kpt\n        if isinstance(dm, np.ndarray) and dm.ndim == 2:\n            dm = np.asarray((dm*.5,dm*.5))\n        if hasattr(dm, 'mo_coeff'):\n            mo_coeff = dm.mo_coeff\n            mo_occ_a = (dm.mo_occ > 0).astype(np.double)\n            mo_occ_b = (dm.mo_occ ==2).astype(np.double)\n            dm = lib.tag_array(dm, mo_coeff=(mo_coeff,mo_coeff),\n                               mo_occ=(mo_occ_a,mo_occ_b))\n        vj, vk = self.get_jk(cell, dm, hermi, kpt, kpts_band)\n        vhf = vj[0] + vj[1] - vk\n        return vhf\n\n    def get_bands(self, kpts_band, cell=None, dm=None, kpt=None):\n        '''Get energy bands at the given (arbitrary) 'band' k-points.\n\n        Returns:\n            mo_energy : (nmo,) ndarray or a list of (nmo,) ndarray\n                Bands energies E_n(k)\n            mo_coeff : (nao, nmo) ndarray or a list of (nao,nmo) ndarray\n                Band orbitals psi_n(k)\n        '''\n        raise NotImplementedError\n\n    def dip_moment(self, mol=None, dm=None, unit='Debye', verbose=logger.NOTE,\n                   **kwargs):\n        # skip dipole memont for crystal\n        return\n\n    def get_init_guess(self, cell=None, key='minao'):\n        if cell is None: cell = self.cell\n        dm = mol_rohf.ROHF.get_init_guess(self, cell, key)\n        if cell.dimension < 3:\n            if isinstance(dm, np.ndarray) and dm.ndim == 2:\n                ne = np.einsum('ij,ji->', dm, self.get_ovlp(cell))\n            else:\n                ne = np.einsum('xij,ji->', dm, self.get_ovlp(cell))\n            if abs(ne - cell.nelectron).max() > 1e-7:\n                logger.warn(self, 'Big error detected in the electron number '\n                            'of initial guess density matrix (Ne/cell = %g)!\\n'\n                            '  This can cause huge error in Fock matrix and '\n                            'lead to instability in SCF for low-dimensional '\n                            'systems.\\n  DM is normalized to correct number '\n                            'of electrons', ne)\n                dm *= cell.nelectron / ne\n        return dm\n\n    def init_guess_by_1e(self, cell=None):\n        if cell is None: cell = self.cell\n        if cell.dimension < 3:\n            logger.warn(self, 'Hcore initial guess is not recommended in '\n                        'the SCF of low-dimensional systems.')\n        return mol_uhf.UHF.init_guess_by_1e(cell)\n\n    def init_guess_by_chkfile(self, chk=None, project=True, kpt=None):\n        if chk is None: chk = self.chkfile\n        if kpt is None: kpt = self.kpt\n        return pbcuhf.init_guess_by_chkfile(self.cell, chk, project, kpt)\n\n    dump_chk = pbchf.SCF.dump_chk\n    _is_mem_enough = pbchf.SCF._is_mem_enough\n\n    density_fit = pbchf.SCF.density_fit\n    # mix_density_fit inherits from hf.SCF.mix_density_fit\n\n    x2c = x2c1e = sfx2c1e = pbchf.SCF.sfx2c1e\n\n    def convert_from_(self, mf):\n        '''Convert given mean-field object to RHF/ROHF'''\n        from pyscf.pbc.scf import addons\n        addons.convert_to_rhf(mf, self)\n        return self\n\n    stability = None\n    nuc_grad_method = None\n\n", "meta": {"hexsha": "fb77d2e894473abeab02527a5d3ecee5ef725b4a", "size": 5557, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/pbc/scf/rohf.py", "max_stars_repo_name": "fdmalone/pyscf", "max_stars_repo_head_hexsha": "021b17ac721e292b277d2b740e2ff8ab38bb6a4a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyscf/pbc/scf/rohf.py", "max_issues_repo_name": "fdmalone/pyscf", "max_issues_repo_head_hexsha": "021b17ac721e292b277d2b740e2ff8ab38bb6a4a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscf/pbc/scf/rohf.py", "max_forks_repo_name": "fdmalone/pyscf", "max_forks_repo_head_hexsha": "021b17ac721e292b277d2b740e2ff8ab38bb6a4a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3202614379, "max_line_length": 82, "alphanum_fraction": 0.6215583948, "include": true, "reason": "import numpy", "num_tokens": 1543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.17278945087373354}}
{"text": "#!/usr/bin/env python3\n\"\"\"create metamers\n\n\"\"\"\nfrom . import utils\nimport re\nimport torch\nimport torchvision\nimport plenoptic as po\nimport pyrtools as pt\nimport time\nimport numpy as np\nimport os.path as op\nimport imageio\nimport matplotlib as mpl\nfrom skimage import color\nimport warnings\nimport sys\nimport yaml\nwith open(op.join(op.dirname(op.realpath(__file__)), '..', 'config.yml')) as f:\n    fov_path = yaml.safe_load(f)['FOVEATED_METAMERS_PATH']\nsys.path.append(op.join(fov_path, 'extra_packages'))\nimport plenoptic_part as pop\n\n\ndef setup_initial_image(initial_image_type, image):\n    r\"\"\"Set up the initial image.\n\n    Parameters\n    ----------\n    initial_image_type : {'white', 'pink', 'gray', 'blue'} or path to file\n        What to use for the initial image. If 'white', we use white\n        noise. If 'pink', we use pink noise\n        (``pyrtools.synthetic_images.pink_noise(fract_dim=1)``). If\n        'blue', we use blue noise\n        (``pyrtools.synthetic_images.blue_noise(fract_dim=1)``). If\n        'gray', we use a flat image with values of .5 everywhere. If\n        path to a file, that's what we use as our initial image (and so\n        the seed will have no effect on this).\n    image : torch.Tensor\n        The reference image tensor\n\n    Returns\n    -------\n    initial_image : torch.Tensor\n        The initial image to pass to metamer.synthesize\n\n    \"\"\"\n    if initial_image_type == 'white':\n        initial_image = torch.rand_like(image, dtype=torch.float32)\n    elif initial_image_type == 'gray':\n        initial_image = .5 * torch.ones_like(image, dtype=torch.float32)\n    elif initial_image_type == 'pink':\n        # this `.astype` probably isn't necessary, but just in case\n        initial_image = pt.synthetic_images.pink_noise(image.shape[-2:]).astype(np.float32)\n        # need to rescale this so it lies between 0 and 1\n        initial_image += np.abs(initial_image.min())\n        initial_image /= initial_image.max()\n        initial_image = torch.Tensor(initial_image).unsqueeze(0).unsqueeze(0)\n    elif initial_image_type == 'blue':\n        # this `.astype` probably isn't necessary, but just in case\n        initial_image = pt.synthetic_images.blue_noise(image.shape[-2:]).astype(np.float32)\n        # need to rescale this so it lies between 0 and 1\n        initial_image += np.abs(initial_image.min())\n        initial_image /= initial_image.max()\n        initial_image = torch.Tensor(initial_image).unsqueeze(0).unsqueeze(0)\n    elif op.isfile(initial_image_type):\n        warnings.warn(\"Using image %s as initial image!\" % initial_image_type)\n        initial_image = imageio.imread(initial_image_type)\n        initial_image = convert_im_to_float(initial_image)\n        initial_image = torch.tensor(initial_image, dtype=torch.float32).unsqueeze(0).unsqueeze(0)\n    else:\n        raise Exception(\"Don't know how to handle initial_image_type %s! Must be one of {'white',\"\n                        \" 'gray', 'pink', 'blue'}\" % initial_image_type)\n    return torch.nn.Parameter(initial_image)\n\n\ndef setup_image(image, n_channels=1):\n    r\"\"\"Set up the image.\n\n    We load in the image, if it's not already done so (converting it to\n    gray-scale in the process), make sure it lies between 0 and 1, and\n    make sure it's a tensor of the correct type and specified device\n\n    Parameters\n    ----------\n    image : str or array_like\n        Either the path to the file to load in or the loaded-in\n        image. If array_like, we assume it's already 2d (i.e.,\n        grayscale)\n    n_channels : int, optional\n        How many channels the image should have. Will always be grayscale, but\n        we may duplicate along one of the channels so we can feed this into\n        VGG16\n\n    Returns\n    -------\n    image : torch.Tensor\n        The image tensor, ready to go\n\n    \"\"\"\n    if isinstance(image, str):\n        print(\"Loading in reference image from %s\" % image)\n        image = imageio.imread(image)\n    if image.dtype == np.uint8:\n        warnings.warn(\"Image is int8, with range (0, 255)\")\n        image = utils.convert_im_to_float(image)\n    elif image.dtype == np.uint16:\n        warnings.warn(\"Image is int16 , with range (0, 65535)\")\n        image = utils.convert_im_to_float(image)\n    else:\n        warnings.warn(\"Image is float 32, so we assume image range is (0, 1)\")\n        if image.max() > 1:\n            raise Exception(\"Image is neither int8 nor int16, but its max is greater than 1!\")\n    # we use skimage.color.rgb2gray in order to handle rgb\n    # correctly. this uses the ITU-R 601-2 luma transform, same as\n    # matlab. we do this after the above, because it changes the image\n    # dtype to float32\n    if image.ndim == 3:\n        # then it's a color image, and we need to make it grayscale\n        image = color.rgb2gray(image)\n    image = torch.tensor(image, dtype=torch.float32)\n    while image.ndimension() < 4:\n        image = image.unsqueeze(0)\n    return image.repeat(1, n_channels, 1, 1)\n\n\ndef setup_model(model_name, image, min_ecc, max_ecc, cache_dir,\n                normalize_dict=None):\n    r\"\"\"Set up the model.\n\n    We initialize the model, with the specified parameters, and return it.\n\n    `model_name` must be 'VGG16_poolN' (where N is an int between 1 and 5),\n    'PSTexture' or one of our foveated models. If a foveated model, it must be\n    constructed of several parts, for which you have several chocies:\n    `'{visual_area}{options}_{window_type}_scaling-{scaling}'`:\n    - `visual_area`: which visual area we're modeling.`'RGC'` (retinal\n      ganglion cells, `plenoptic.simul.PooledRGC` class) or\n      `'V1'` (primary visual cortex,\n      `plenoptic.simul.PrimaryVisualCortex` class)\n    - `options`: you can additionally include the following strs,\n      separated by `_`:\n      - `'norm'`: if included, we normalize the models' `cone_responses`\n        and (if V1) `complex_cell_responses` attributes. In this case,\n        `normalize_dict` must also be set (and include those two\n        keys). If not included, the model is not normalized\n        (normalization makes the optimization easier because the\n        different scales of the steerable pyramid have different\n        magnitudes).\n      - `s#` (V1 only), where `#` is an integer. The number of scales to\n        inlude in the steerable pyramid that forms the basis fo the `V1`\n        models. If not included, will use 4.\n    - `window_type`: `'gaussian'` or `'cosine'`. whether to build the\n      model with gaussian or raised-cosine windows. Regardless, scaling\n      will always give the ratio between the FWHM and eccentricity of\n      the windows, but the gaussian windows are much tighter packed, and\n      so require more windows (and thus more memory), but also seem to\n      have fewer aliasing issues.\n    - `scaling`: float giving the scaling values of these models\n\n    The recommended model_name values that correspond to our foveated models\n    are: `RGC_norm_gaussian_scaling-{scaling}`,\n    `V1_norm_s6_gaussian_scaling-{scaling}` (pick whatever scaling value you\n    like).\n\n    For the other model_name choices:\n\n    - PSTexture: the Portilla-Simoncelli texture stats with n_scales=4,\n      n_orientations=4, spatial_corr_width=9, use_true_correlations=True\n\n    - VGG16_poolN: pretrained VGG16 from torchvision, through Nth max pooling\n      layer (where N is an int from 1 to 5)\n\n    Parameters\n    ----------\n    model_name : str\n        str specifying which of the models we should initialize. See above for\n        more details.\n    image : torch.tensor or np.array\n        The image we will call the model on. This is only necessary\n        because we need to know how big it is; we just use its shape\n    min_ecc : float\n        The minimum eccentricity for the pooling windows (see\n        plenoptic.simul.VentralStream for more details)\n    max_ecc : float\n        The maximum eccentricity for the pooling windows (see\n        plenoptic.simul.VentralStream for more details)\n    cache_dir : str or None, optional\n        The directory to cache the windows tensor in. If set, we'll look\n        there for cached versions of the windows we create, load them if\n        they exist and create and cache them if they don't. If None, we\n        don't check for or cache the windows.\n    normalize_dict : dict or None, optional\n        If a dict, should contain the stats to use for normalization. If\n        None, we don't normalize. This can only be set (and must be set)\n        if the model is \"V1_norm\". In any other case, we'll throw an\n        Exception.\n\n    Returns\n    -------\n    model : torch.nn.Module\n        A ventral stream model, ready to use\n\n    \"\"\"\n    if 'gaussian' in model_name:\n        window_type = 'gaussian'\n        t_width = None\n        std_dev = 1\n    elif 'cosine' in model_name:\n        window_type = 'cosine'\n        t_width = 1\n        std_dev = None\n    if model_name.startswith('RGC') or model_name.startswith('V1'):\n        model_name, scaling = re.findall('([a-zA-z_0-9-.]+)_scaling-([0-9.]+)', model_name)[0]\n        scaling = float(scaling)\n        if 'norm' not in model_name:\n            if normalize_dict:\n                raise Exception(f\"Cannot normalize model {model_name} (norm must be part of model_name to do so)!\")\n            normalize_dict = {}\n        if not normalize_dict and 'norm' in model_name:\n            raise Exception(f\"If model_name is {model_name}, normalize_dict must be set!\")\n        if model_name.startswith('RGC'):\n            model = pop.PooledRGC(scaling, image.shape[-2:],\n                                  min_eccentricity=min_ecc,\n                                  max_eccentricity=max_ecc,\n                                  window_type=window_type,\n                                  transition_region_width=t_width,\n                                  cache_dir=cache_dir,\n                                  std_dev=std_dev,\n                                  normalize_dict=normalize_dict)\n        elif model_name.startswith('V1'):\n            try:\n                num_scales = int(re.findall('_s([0-9]+)_', model_name)[0])\n            except (IndexError, ValueError):\n                num_scales = 4\n            try:\n                moments = int(re.findall('_m([0-9]+)_', model_name)[0])\n                moments = list(range(2, moments+1))\n            except (IndexError, ValueError):\n                moments = []\n            model = pop.PooledV1(scaling, image.shape[-2:],\n                                 min_eccentricity=min_ecc,\n                                 max_eccentricity=max_ecc,\n                                 std_dev=std_dev,\n                                 transition_region_width=t_width,\n                                 cache_dir=cache_dir,\n                                 normalize_dict=normalize_dict,\n                                 num_scales=num_scales,\n                                 window_type=window_type,\n                                 moments=moments)\n    elif model_name.startswith('OnOff'):\n        pretrained, kernel_size = re.findall('OnOff_pretrained-([a-zA-z]+)_size-([0-9]+)', model_name)[0]\n        if pretrained == 'True':\n            pretrained = True\n        else:\n            pretrained = False\n        if pretrained:\n            assert int(kernel_size) == 31\n        model = po.simul.OnOff(int(kernel_size), pretrained=pretrained)\n    elif model_name == 'PSTexture':\n        model = po.simul.PortillaSimoncelli(image.shape[-2:], n_scales=4,\n                                            n_orientations=4,\n                                            spatial_corr_width=9,\n                                            use_true_correlations=True)\n    elif 'VGG16' in model_name:\n        model = torchvision.models.vgg16(pretrained=True).eval()\n        # through the first max pooling layer\n        if 'pool1' in model_name:\n            model = torch.nn.Sequential(*list(model.children())[0][:5])\n        # through the second max pooling layer\n        elif 'pool2' in model_name:\n            model = torch.nn.Sequential(*list(model.children())[0][:10])\n        # etc\n        elif 'pool3' in model_name:\n            model = torch.nn.Sequential(*list(model.children())[0][:17])\n        elif 'pool4' in model_name:\n            model = torch.nn.Sequential(*list(model.children())[0][:24])\n        elif 'pool5' in model_name:\n            model = torch.nn.Sequential(*list(model.children())[0][:31])\n        else:\n            raise Exception(f\"Don't know what to do with model_name {model_name}!\")\n    else:\n        raise Exception(\"Don't know how to handle model_name %s\" % model_name)\n    return model\n\n\ndef setup_device(*args, gpu_id=None):\n    r\"\"\"Setup device and get everything onto it\n\n    This simple function checks whether ``torch.cuda.is_available()``\n    and ``gpu_id`` is not None. If not, we use the cpu as the device\n\n    We then call a.to(device) for every a in args (so this can be called\n    with an arbitrary number of objects, each of which just needs to have\n    .to method).\n\n    Note that we always return a list (even if you only pass one item),\n    so if you pass a single object, you'll need to either grab it\n    specifically, either by doing ``im = setup_device(im,\n    gpu_id=0)[0]`` or ``im, = setup_device(im)`` (notice the\n    comma).\n\n    Parameters\n    ----------\n    args :\n        Some number of torch objects that we want to get on the proper\n        device\n    gpu_id : int or None, optional\n        If not None, the GPU we will use. If None, we run on CPU. We\n        don't do anything clever to handle that here, but the\n        contextmanager utils.get_gpu_id does, so you should use that to\n        make sure you're using a GPU that exists and is available (see\n        Snakefile for example). Note that, to set this,\n        you must set it as a keyword, i.e., ``setup_device(im, 0)``\n        won't work but ``setup_device(im, gpu_id=True)`` will (this is\n        because the ``*args`` in our function signature will greedily\n        grab every non-keyword argument).\n\n    Returns\n    -------\n    args : list\n        Every item we were passed in arg, now on the proper device\n\n    \"\"\"\n    if gpu_id is not None:\n        if not torch.cuda.is_available():\n            raise Exception(\"CUDA is not available but gpu_id is not None!\")\n        device = torch.device(\"cuda:%s\" % gpu_id)\n        dtype = torch.float32\n    else:\n        device = torch.device(\"cpu\")\n        dtype = torch.float32\n    print(\"On device %s\" % device)\n    if dtype is not None:\n        print(\"Changing dtype to %s\" % dtype)\n        args = [a.to(dtype) for a in args]\n    return [a.to(device) for a in args]\n\n\ndef add_center_to_image(model, image, reference_image):\n    r\"\"\"Add the reference image center to an image\n\n    The VentralStream class of models will do nothing to the center of\n    the image (they don't see the fovea), so we add the fovea to the\n    image before synthesis.\n\n    Parameters\n    ----------\n    model : plenoptic.simul.VentralStream\n        The model used to create the metamer. Specifically, we need its\n        windows attribute\n    image : torch.Tensor\n        The image to add the center back to\n    reference_image : torch.Tensor\n        The reference/target image for synthesis\n        (``metamer.base_signal``); the center comes from this image.\n\n    Returns\n    -------\n    recentered_image : torch.Tensor\n        ``image`` with the reference image center added back in\n\n    \"\"\"\n    model(image)\n    rep = model.representation['mean_luminance']\n    dummy_ones = torch.ones_like(rep)\n    windows = model.PoolingWindows.project(dummy_ones).squeeze().to(image.device)\n    # these aren't exactly zero, so we can't convert it to boolean\n    anti_windows = 1 - windows\n    return ((windows * image) + (anti_windows * reference_image))\n\n\ndef save(save_path, metamer):\n    \"\"\"Save Metamer object and its outputs.\n\n    We save the object itself, plus:\n    - The finished metamer in its original float32 format (with\n      values between 0 and 1, as a numpy array), at\n      ``os.path.splitext(save_path)[0] + \"_metamer.npy\"``.\n    - The finished metamer 8-bit image, at\n      ``os.path.splitext(save_path)[0] + \"_metamer.png\"``.\n    - Picture showing synthesis progress summary at\n      ``os.path.splitext(save_path)[0] + \"_synthesis.png\"``.\n\n    Parameters\n    ----------\n    save_path : str\n        The path to save the MADCompetition object at, which we use as a\n        starting-point for the other save paths\n    metamer : plenoptic.synth.MADCompetition\n        The Metamer object after synthesis\n\n    \"\"\"\n    if metamer.model(metamer.synthesized_signal).ndimension() == 4:\n        # these VGG representations have many channels, plotting them all takes\n        # too much time\n        plot_model_response_error = False\n    else:\n        plot_model_response_error = True\n    print(\"Saving at %s\" % save_path)\n    if hasattr(metamer.model, 'PoolingWindows'):\n        # If we're using one of our foveated models, we add the center back at\n        # the end because our gradients are not exactly zero in the center, and\n        # thus those pixels end up getting moved around a little bit. Not\n        # entirely sure why, but probably not worth tracing down, since we're\n        # interested in the periphery\n        metamer.synthesized_signal = torch.nn.Parameter(add_center_to_image(metamer.model,\n                                                                            metamer.synthesized_signal,\n                                                                            metamer.target_signal))\n    metamer.save(save_path)\n    # save png of mad\n    metamer_path = op.splitext(save_path)[0] + \"_metamer.png\"\n    metamer_image = po.to_numpy(metamer.synthesized_signal).squeeze()\n    print(\"Saving metamer float32 array at %s\" % metamer_path.replace('.png', '.npy'))\n    np.save(metamer_path.replace('.png', '.npy'), metamer_image)\n    print(\"Saving metamer image at %s\" % metamer_path)\n    if metamer_image.ndim == 3:\n        # then this is an RGB, from the VGG16 models, and we want to move the\n        # channels dim to the last dimension\n        metamer_image = metamer_image.transpose(1, 2, 0)\n    imageio.imwrite(metamer_path, utils.convert_im_to_int(metamer_image))\n    synthesis_path = op.splitext(save_path)[0] + \"_synthesis.png\"\n    print(f\"Saving synthesis image at {synthesis_path}\")\n    fig, _ = po.synth.metamer.plot_synthesis_status(metamer,\n                                                    model_response_error=plot_model_response_error)\n    fig.savefig(synthesis_path)\n\n\ndef main(model_name, image, seed=0, min_ecc=.5, max_ecc=15, learning_rate=1,\n         max_iter=100, stop_criterion=1e-4, stop_iters_to_check=50,\n         save_path=None, initial_image='white', gpu_id=None, cache_dir=None,\n         normalize_dict=None, optimizer='Adam', loss_func='mse',\n         range_penalty_lambda=.1, coarse_to_fine=False,\n         coarse_to_fine_kwargs={}, continue_path=None, num_threads=None):\n    r\"\"\"Create metamer images.\n\n    Given a model_name, model parameters, a target image, and some\n    optimization parameters, we do our best to synthesize a metamer,\n    saving the outputs after it finishes.\n\n    `model_name` must either a model, 'VGG16_poolN' (where N is an int between\n    1 and 5), 'PSTexture' or one of our foveated models. If a foveated model,\n    it must be constructed of several parts, for which you have several\n    chocies:\n    `'{visual_area}{options}_{window_type}_scaling-{scaling}'`:\n    - `visual_area`: which visual area we're modeling.`'RGC'` (retinal\n      ganglion cells, `plenoptic.simul.PooledRGC` class) or\n      `'V1'` (primary visual cortex,\n      `plenoptic.simul.PrimaryVisualCortex` class)\n    - `options`: you can additionally include the following strs,\n      separated by `_`:\n      - `'norm'`: if included, we normalize the models' `cone_responses`\n        and (if V1) `complex_cell_responses` attributes. In this case,\n        `normalize_dict` must also be set (and include those two\n        keys). If not included, the model is not normalized\n        (normalization makes the optimization easier because the\n        different scales of the steerable pyramid have different\n        magnitudes).\n      - `s#` (V1 only), where `#` is an integer. The number of scales to\n        inlude in the steerable pyramid that forms the basis fo the `V1`\n        models. If not included, will use 4.\n    - `window_type`: `'gaussian'` or `'cosine'`. whether to build the\n      model with gaussian or raised-cosine windows. Regardless, scaling\n      will always give the ratio between the FWHM and eccentricity of\n      the windows, but the gaussian windows are much tighter packed, and\n      so require more windows (and thus more memory), but also seem to\n      have fewer aliasing issues.\n    - `scaling`: float giving the scaling values of these models\n\n    The recommended model_name values that correspond to our foveated models\n    are: `RGC_norm_gaussian_scaling-{scaling}`,\n    `V1_norm_s6_gaussian_scaling-{scaling}` (pick whatever scaling value you\n    like).\n\n    For the other model_name choices:\n\n    - PSTexture: the Portilla-Simoncelli texture stats with n_scales=4,\n      n_orientations=4, spatial_corr_width=9, use_true_correlations=True\n\n    - VGG16_poolN: pretrained VGG16 from torchvision, through Nth max pooling\n      layer (where N is an int from 1 to 5)\n\n    If you want to resume synthesis from an earlier run that didn't\n    finish, set `continue_path` to the path of the `.pt` file created by\n    that earlier run. We will then load it in and continue. For right\n    now, we don't do anything to make sure that the arguments you pass\n    to the function are the same as the first time, we just use the ones\n    passed in. Generally, they should be identical, with the exception\n    of learning_rate (which can be None to resume where you left off)\n    and max_iter (which gives the number of extra iterations you want to\n    do). Specifically, I think things might get weird if you do this\n    initially on a GPU and then try to resume on a CPU (or vice versa),\n    for example. When resuming, there's always a slight increase in the\n    loss that, as far as I can tell, is unavoidable; it goes away\n    quickly (and the loss continues its earlier trend) and so I don't\n    think is an issue.\n\n    Parameters\n    ----------\n    model_name : str\n        str specifying which of the model we should use. See above for more\n        details.\n    image : str or array_like\n        Either the path to the file to load in or the loaded-in\n        image. If array_like, we assume it's already 2d (i.e.,\n        grayscale)\n    seed : int, optional\n        The number to use for initializing numpy and torch's random\n        number generators\n    min_ecc : float, optional\n        The minimum eccentricity for the pooling windows (see\n        plenoptic.simul.VentralStream for more details)\n    max_ecc : float, optional\n        The maximum eccentricity for the pooling windows (see\n        plenoptic.simul.VentralStream for more details)\n    learning_rate : float, optional\n        The learning rate to pass to metamer.synthesize's optimizer\n    max_iter : int, optional\n        The maximum number of iterations we allow the synthesis\n        optimization to run for\n    stop_criterion : float, optional\n        The stop criterion. If the loss has changed by less than this over the\n        past stop_iters_to_check iterations, we quit out.\n    stop_iters_to_check : int, optional\n        How many iterations back to check in order to see if the loss has\n        stopped decreasing.\n    save_path : str or None, optional\n        If a str, the path to the file to save the metamer object to. If\n        None, we don't save the synthesis output (that's probably a bad\n        idea)\n    initial_image : {'white', 'pink', 'gray', 'blue'} or path to a file\n        What to use for the initial image. If 'white', we use white\n        noise. If 'pink', we use pink noise\n        (``pyrtools.synthetic_images.pink_noise(fract_dim=1)``). If\n        'blue', we use blue noise\n        (``pyrtools.synthetic_images.blue_noise(fract_dim=1)``). If\n        'gray', we use a flat image with values of .5 everywhere. If\n        path to a file, that's what we use as our initial image (and so\n        the seed will have no effect on this).\n        std dev of Gaussian noise added to image to initialize synthesis.\n    gpu_id : int or None, optional\n        If not None, the GPU we will use. If None, we run on CPU. We\n        don't do anything clever to handle that here, but the\n        contextmanager utils.get_gpu_id does, so you should use that to\n        make sure you're using a GPU that exists and is available (see\n        Snakefile for example)\n    cache_dir : str or None, optional\n        The directory to cache the windows tensor in. If set, we'll look\n        there for cached versions of the windows we create, load them if\n        they exist and create and cache them if they don't. If None, we\n        don't check for or cache the windows.\n    normalize_dict : str or None, optional\n        If a str, the path to the dictionary containing the statistics to use\n        for normalization for the model. If None, we don't normalize anything\n    optimizer: {'Adam', 'SGD'}\n        The choice of optimization algorithm\n    loss_func : {'mse', 'l2'}, optional\n        Which loss function to use.\n    range_penalty_lambda :\n        Lambda to multiply by range penalty and add to loss.\n    coarse_to_fine : { 'together', 'separate', False}, optional\n        If False, don't do coarse-to-fine optimization. Else, there\n        are two options for how to do it:\n        - 'together': start with the coarsest scale, then gradually\n          add each finer scale. this is like blurring the objective\n          function and then gradually adding details and is probably\n          what you want.\n        - 'separate': compute the gradient with respect to each\n          scale separately (ignoring the others), then with respect\n          to all of them at the end.\n    coarse_to_fine_kwargs : dict, optional\n        Dictionary of args for coarse to fine optimization. See\n        Metamer.synthesize() docstring for details.\n    continue_path : str or None, optional\n        If None, we synthesize a new metamer. If str, this should be the\n        path to a previous synthesis run, which we are resuming. In that\n        case, you may set learning_rate to None (in which case we resume\n        where we left off) and set max_iter to a different value (the\n        number of extra iterations to run) otherwise the rest of the\n        arguments should be the same as the first run.\n    num_threads : int or None, optional\n        If int, the number of CPU threads to use. If None, we don't restrict it\n        and so we'll use all available resources. If using the GPU, this won't\n        matter (all costly computations are done on the GPU). If one the CPU,\n        we seem to only improve performance up to ~12 threads (at least with\n        RGC model), and actively start to harm performance as we get above 40.\n\n    \"\"\"\n    print(\"Using seed %s\" % seed)\n    if num_threads is not None:\n        print(f\"Using {num_threads} threads\")\n        torch.set_num_threads(num_threads)\n    else:\n        print(\"Not restricting number of threads, will probably use max \"\n              f\"available ({torch.get_num_threads()})\")\n    po.tools.set_seed(seed)\n    image = setup_image(image, 3 if 'VGG16' in model_name else 1)\n    print(f\"Using initial image {initial_image}\")\n    initial_image = setup_initial_image(initial_image, image)\n    # this will be false if normalize_dict is None or an empty list\n    if normalize_dict:\n        normalize_dict = torch.load(normalize_dict)\n    model = setup_model(model_name, image, min_ecc, max_ecc, cache_dir,\n                        normalize_dict)\n    model_str = f\"Using model {model_name}\"\n    if model_name.startswith('RGC') or model_name.startswith(\"V1\"):\n        model_str += f\" from {min_ecc} degrees to {max_ecc} degrees\"\n    print(model_str)\n    image, initial_image, model = setup_device(image, initial_image, model, gpu_id=gpu_id)\n    store_progress = max(10, max_iter//100)\n    if loss_func == 'mse':\n        loss_func = po.tools.optim.mse\n    elif loss_func == 'l2':\n        loss_func = po.tools.optim.l2_norm\n    else:\n        raise Exception(f\"Don't know how to handle loss_func {loss_func}!\")\n    metamer = po.synth.Metamer(image, model, loss_func, range_penalty_lambda,\n                               initial_image=initial_image)\n    print(f\"Using optimizer {optimizer}\")\n    if optimizer == 'Adam':\n        opt = torch.optim.Adam([metamer.synthesized_signal], lr=learning_rate, amsgrad=True)\n    elif optimizer == 'SGD':\n        opt = torch.optim.SGD([metamer.synthesized_signal], lr=learning_rate)\n    if continue_path is not None:\n        print(\"Resuming synthesis saved at %s\" % continue_path)\n        metamer = metamer.load(continue_path)\n        opt = None\n    print(f\"Using learning rate {learning_rate}, stop_criterion {stop_criterion} (stop_iters_to_check \"\n          f\"{stop_iters_to_check}), and max_iter {max_iter}\")\n    print(f\"Using coarse-to-fine {coarse_to_fine} with kwargs {coarse_to_fine_kwargs}\")\n    start_time = time.time()\n    metamer.synthesize(max_iter=max_iter, optimizer=opt,\n                       store_progress=store_progress,\n                       stop_criterion=stop_criterion,\n                       stop_iters_to_check=stop_iters_to_check,\n                       coarse_to_fine=coarse_to_fine,\n                       coarse_to_fine_kwargs=coarse_to_fine_kwargs)\n    duration = time.time() - start_time\n    print(f\"Synthesis took {duration} seconds\")\n    # make sure everything's on the cpu for saving\n    metamer.to('cpu')\n    if save_path is not None:\n        save(save_path, metamer)\n", "meta": {"hexsha": "f0153302c7f3b31f69fd59760372f819e0e49fd8", "size": 29842, "ext": "py", "lang": "Python", "max_stars_repo_path": "synth/create_metamers.py", "max_stars_repo_name": "billbrod/synthesis-examples", "max_stars_repo_head_hexsha": "891c25c2396f556a93e2bd0dc12ca53731a434b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "synth/create_metamers.py", "max_issues_repo_name": "billbrod/synthesis-examples", "max_issues_repo_head_hexsha": "891c25c2396f556a93e2bd0dc12ca53731a434b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "synth/create_metamers.py", "max_forks_repo_name": "billbrod/synthesis-examples", "max_forks_repo_head_hexsha": "891c25c2396f556a93e2bd0dc12ca53731a434b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.2666666667, "max_line_length": 115, "alphanum_fraction": 0.652402654, "include": true, "reason": "import numpy", "num_tokens": 7047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3276683139517237, "lm_q1q2_score": 0.17278491613466745}}
{"text": "import pickle\nfrom typing import Tuple, Callable, Sequence\n\nimport numpy as np\n\n__all__ = [\"Neuron\", \"Callback\"]\n\nCallback = Callable[[float], np.ndarray]\n\n\nclass BaseNeuron:\n    @staticmethod\n    def logistic(z: np.ndarray) -> np.ndarray:\n        return 1 / (2 + np.expm1(-z))\n\n    @staticmethod\n    def tanh(z: np.ndarray, *args, **kwargs) -> np.ndarray:\n        return np.tanh(z, *args, **kwargs)\n\n    @staticmethod\n    def softplus(z: np.ndarray) -> np.ndarray:\n        return np.log(np.expm1(z) + 2)\n\n    @staticmethod\n    def relu(z: np.ndarray) -> np.ndarray:\n        return np.array([max(0, zz) for zz in z])\n\n    @staticmethod\n    def relu6(z: np.ndarray) -> np.ndarray:\n        return np.array([min(max(zz, 0), 6) for zz in z])\n\n    @staticmethod\n    def binary(z: np.ndarray) -> np.ndarray:\n        return np.array([[-1, 1][zz > 0] for zz in z])\n\n    @staticmethod\n    def identity(z: np.ndarray) -> np.ndarray:\n        return z\n\n\nclass Neuron(BaseNeuron):\n    \"\"\"\n    In the framework of the Echo State Neuron, an individual neuron is vastly more complicated and capable than\n    traditional neural network nodes.  In the traditional case the dot product of an input vector and a learned\n    weight vector plus a bias are passed through some non linearity (or not) to produce the neuron's activation.  The\n    formulation is thus:\n\n    $$ a_{out} = \\sigma(\\vec{a_{in}} \\cdot \\vec{w} + b) $$\n\n    The basic problem with this is that it is static. It completely misses the dynamics possible in a real neuron and\n    does now allow for spatiotemporal receptive field mapping without playing with approximations of time,\n    etc. And even then, the output really does not vary based on the input to the system.\n\n    I propose an ESNeuron.  The ESNeuron gets its name from echo state networks.  In an ESNeuron multiple inputs\n    still exist and there is a single output.  The distinction comes when everything else is considered.  In an\n    ESNeuron the inputs are fully connected to a dynamical pool.  If we assume learning or processing occurs in the\n    dendritic arbor of a neuron, then the dynamical pool is an analog to the dendritic arbor.  We can likewise assume\n    that the axon hillock is the integration point in a neuron. In this case, our ESNeuron performs a linear\n    transformation with the reservoir resulting in a value taken to be the ESNeuron activation.\n\n    The final step in the system is to connect the output via fixed weights to the reservoir.  Because we're passing\n    through an echo state network, our output is not entirely driven by the input to the system but works with inputs\n    received, feedback from prior outputs and the internal dynamical nature of the ESN.\n\n    In theory any output pattern can be trained given any input.  One could produce, given some random fixed pattern\n    virtually any wave form.  This wave form can act as the input to another ESN.  In that case, the ESN receives an\n    input pattern over time and this drives another potentially more complex output pattern.\n\n    Given the above there are several parameters that decide the ESNeuron:\n    \"\"\"\n    __version__ = \"0.9\"\n\n    def __init__(self,\n                 numInputs: int,\n                 numReservoir: int,\n                 numOutputs: int,\n                 pct: float,\n                 alpha: float,\n                 *,\n                 f: Callable[[np.ndarray], np.ndarray] = BaseNeuron.tanh,\n                 g: Callable[[np.ndarray], np.ndarray] = BaseNeuron.identity,\n                 feedback: bool = True\n                 ):\n        \"\"\"\n        Initialize the neuron with the architecture defined by the parameters\n\n        :param numInputs: The number of connections from precursor neurons to this neuron\n        :param numReservoir: The number of nodes in the internal echo state network\n        :param numOutputs: The number of connections to the internal integrator from the reservoir\n        :param pct: The probability of a connection between nodes of the echo state network\n        :param alpha: float: measure of speed of reservoir lower values faster 0 < alpha <= 1\n        :param f: callable: default Neuron.tanh\n        :param g: callable: default Neuron.identity\n        :param feedback: bool: default True - feed outputs back into the reservoir\n        \"\"\"\n        assert 0 <= numInputs, \"We restrict the number of inputs to be non-negative\"\n        assert 0 < numReservoir, \"We restrict the number of reservoir nodes to be strictly positive\"\n        assert 0 < numOutputs, \"We restrict the number of outputs to be strictly positive\"\n\n        assert 0 < pct <= 1, \"Probability of connection must be between 0 exclusive and 1 inclusive\"\n        # assert 0 < alpha < 1, \"alpha - must be 0 < alpha < 1\"\n\n        assert callable(f), \"f must be a function(arg) or None\"\n        assert callable(g), \"f must be a function(arg) or None\"\n\n        # These parameters are sufficient to describe the echo state network dimensions\n        self._numInputs = numInputs  # I  K\n        self._numReservoir = numReservoir  # H  N\n        self._numOutputs = numOutputs  # O  L\n\n        # Store the functions used to define how the neuron operates\n        self.f = f\n        self.g = g\n\n        # Construct the Input Matrix that transforms the input vector from length I to length H\n        self.Win = np.random.standard_normal((numReservoir, numInputs))\n\n        # Construct the Reservoir Matrix that transforms Hidden to Hidden.\n        self.W = np.eye(numReservoir)\n        self.W[np.random.rand(numReservoir, numReservoir) < pct] = 1\n        self.W[self.W > 0] = np.random.standard_normal((numReservoir, numReservoir))[self.W > 0]\n        self.W = self.W * alpha / np.max(np.abs(np.linalg.eig(self.W)[0]))\n\n        # Construct the feedback network\n        self.Wfb = np.random.randn(numReservoir, numOutputs) * int(feedback)\n\n        # Construct the output network\n        self._Wout = np.random.standard_normal((numOutputs, numReservoir + numInputs))\n        self.baseWout = self._Wout.copy()\n        # self._Wout = np.zeros(shape=(numOutputs, numReservoir + numInputs))\n\n        # Construct the basic activation vectors (neurons)\n        self.x = np.random.uniform(-1, 1, size=(numReservoir, 1))\n        self.y = np.random.uniform(-1, 1, size=(numOutputs, 1))\n        self.z = np.random.uniform(-1, 1, size=(numReservoir + numInputs, 1))\n\n        # number of iterations of no input (zero vector) used internally as setup and during training\n        self._washout = 500\n\n        # make sure the network has settled prior to finishing initialization\n        self.forget()\n        # self.settle(self.washout)\n\n    @property\n    def washout(self):\n        return self._washout\n\n    @washout.setter\n    def washout(self, washout):\n        self._washout = washout\n\n    @property\n    def Wout(self) -> np.ndarray:\n        return self._Wout\n\n    @Wout.setter\n    def Wout(self, Wout: np.ndarray):\n        assert self._Wout.shape == Wout.shape, \"Cannot set weights. The dimensions do not match\"\n        self._Wout = Wout.copy()\n\n    @property\n    def numInputs(self):\n        return self._numInputs\n\n    @property\n    def numReservoir(self):\n        return self._numReservoir\n\n    @property\n    def numOutputs(self):\n        return self._numOutputs\n\n    @classmethod\n    def load(cls):\n        try:\n            with open(\"esn_parameters.pkl\", \"rb\") as inp:\n                x = pickle.load(inp)\n            assert isinstance(x, cls), \"Pickled object is not a {}\".format(cls)\n            assert x.__version__ == cls.__version__, \"Version mismatch - pkl file is out of date\"\n            return x\n        except FileNotFoundError:\n            return None\n\n    def save(self):\n        with open(\"esn_parameters.pkl\", \"wb\") as out:\n            pickle.dump(self, out, pickle.HIGHEST_PROTOCOL)\n\n    def forget(self):\n        \"\"\"\n        Forget any prior learning by zeroing the output weight matrix and then running the network with\n        no input for a <washout> number of steps.\n        :return: None\n        \"\"\"\n\n        # Zero the output matrix and then let the network settle for the washout period\n        # self._Wout = np.zeros(shape=self._Wout.shape)\n        self._Wout = self.baseWout.copy()\n        self.settle(self.washout)\n\n    def settle(self, count: int):\n        \"\"\"\n        Cause the network to run <count> steps with no input.  This is intended to remove prior input traces\n        from the reservoir prior to training or when ever a clean slate is desired. The number of steps <count>\n        really should be computed based on the value of alpha - the spectral radius of the Reservoir.\n        :param count: int; The number of cycles to run the ESN with no input.\n        :return: None\n        \"\"\"\n\n        def fin(_: float) -> np.ndarray:\n            \"\"\"function returning zero vector size numInputs\"\"\"\n            return np.zeros((self.numInputs, 1))\n\n        self.cycle(1, count, [fin for _ in range(count)])\n\n    def cycle(self,\n              t0: int,\n              tn: int,\n              f_in: Sequence[Callback]) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:\n        \"\"\"\n        (1) x(n+1) = f(W * x(n) + Win * u(n+1) + Wfb * y(n))\n            z(n) = [x(n); u(n)]\n        (2) y(n) = g(Wout * z(n))\n\n        Execute a single pass through the echo state network potentially taking in some stimulus.\n        There is no learning when using this method. To train your ESN, please use <code>force_learn</code>.\n        :param t0: int: Starting index passed to f_teach to retrieve the t0'th teaching pair\n        :param tn: int: Ending index passed to f_teach to retrieve the tn'th teaching pair\n        :param f_in: callable(t: float) -> np.array a function that returns the network input at time t\n        :return: the current output vector\n        \"\"\"\n        assert t0 <= tn, \"Cannot observe backwards through time. tn must not be less than t0\"\n\n        nmax = tn - t0 + 1\n        u = None\n\n        for t in range(nmax):\n            u = f_in[t](t0 + t)  # retrieve the next input pattern\n            self.x = self.f((self.W @ self.x) + (self.Win @ u) + (self.Wfb @ self.y))\n            self.z = np.concatenate((self.x, u))\n            self.y = self.g(self._Wout @ self.z)\n\n        return u, self.x, self.y, self.z\n\n    def learn(self,\n              t0: int,\n              tn: int,\n              f_in: Sequence[Callback],\n              f_out: Sequence[Callback]) -> Tuple[np.ndarray, np.ndarray]:\n        \"\"\"\n        Execute a single forced learning phase taking stimulus and desired response into consideration.\n\n        (1) x(n+1) = f(W * x(n) + Win * u(n+1) + Wfb * y(n))\n            z(n) = [x(n); u(n)]\n        (2) y(n) = g(Wout * z(n))\n\n        Learning equations. In the state harvesting stage of the training, the ESN is driven by an input sequence\n        u(1),…,u(nmax) , which yields a sequence z(1),…,z(nmax) of extended system states. The system equations (1),\n        (2) are used here. If the model includes output feedback (i.e., nonzero Wfb), then during the generation of the\n        system states, the correct outputs d(n) (part of the training data) are written into the output units (\"teacher\n        forcing\"). The obtained extended system states are filed row-wise into a state collection matrix S of size\n        nmax×(N+K) . Usually some initial portion of the states thus collected are discarded to accommodate for a\n        washout of the arbitrary (random or zero) initial reservoir state needed at time 1. Likewise, the desired\n        outputs d(n) are sorted row-wise into a teacher output collection matrix D of size nmax×L .\n\n        The desired output weights Wout are the linear regression weights of the desired outputs d(n) on the harvested\n        extended states z(n) . A mathematically straightforward way to compute Wout is to invoke the pseudoinverse\n        (denoted by ⋅†) of S :\n\n        (3) Wout = (S†D)′\n             S = z(t0:tn)\n             D = y(t0:tn)\n             Wout = np.matmul(np.linalg.pinv(S), D).T\n\n        which is an offline algorithm (the prime denotes matrix transpose). Online adaptive methods known from linear\n        signal processing can also be used to compute output weights (Jaeger 2003).\n\n        A note on the function f_teach.  f_teach(t) should return a tuple of functions where the first\n        of the tuple, when called returns the t'th input pattern and the second tuple, when called returns\n        the t'th target pattern.  These returned functions take no parameters and each returns a vector.\n\n        :param t0: int: Starting index passed to f_teach to retrieve the t0'th teaching pair\n        :param tn: int: Ending index passed to f_teach to retrieve the tn'th teaching pair\n        :param f_in: callable(t: int) -> np.array a function that returns the network input at time t\n        :param f_out: callable(t: int) -> np.array a function that returns the target output at time t\n        :return:\n        \"\"\"\n        assert t0 <= tn, \"Cannot train backwards through time. tn must not be less than t0\"\n\n        nmax = tn - t0 + 1\n\n        S = np.empty(shape=(nmax, self.numReservoir + self.numInputs))\n        D = np.empty(shape=(nmax, self.numOutputs))\n\n        print(\"Learning sequence of {} inputs\".format(nmax))\n        for t in range(nmax):\n            # self.cycle(t0 + t, t0 + t, f_in)\n\n            u = f_in[t](t0 + t)  # retrieve the next input pattern\n            y = f_out[t](t0 + t)  # retrieve the next output pattern\n\n            reservoir = (self.W @ self.x)\n            inputData = (self.Win @ u)\n            feedBack = (self.Wfb @ self.y)\n\n            self.x = self.f(reservoir + inputData + feedBack)\n            self.z = np.concatenate((self.x, u))\n            self.y = self.g(self._Wout @ self.z)\n\n            # Teacher Forcing\n            self.y = y\n\n            # Save our state and target outputs\n            S[t] = self.z.copy().reshape(-1)\n            D[t] = y.copy().reshape(-1)\n\n        self._Wout += (np.linalg.pinv(S) @ D).T\n        return S, D\n", "meta": {"hexsha": "3825eb5668ac2cb809686d32abf72af3bdb533ab", "size": 14012, "ext": "py", "lang": "Python", "max_stars_repo_path": "ESNeuron/Neuron.py", "max_stars_repo_name": "ReggieCarey/EchoStateNetwork", "max_stars_repo_head_hexsha": "d43aaa1857e029d01bcc2e6556cc7d56f8fb7c06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-16T06:28:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T06:28:32.000Z", "max_issues_repo_path": "ESNeuron/Neuron.py", "max_issues_repo_name": "ReggieCarey/EchoStateNetwork", "max_issues_repo_head_hexsha": "d43aaa1857e029d01bcc2e6556cc7d56f8fb7c06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ESNeuron/Neuron.py", "max_forks_repo_name": "ReggieCarey/EchoStateNetwork", "max_forks_repo_head_hexsha": "d43aaa1857e029d01bcc2e6556cc7d56f8fb7c06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.0628930818, "max_line_length": 119, "alphanum_fraction": 0.6378104482, "include": true, "reason": "import numpy", "num_tokens": 3414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.17278490921046907}}
{"text": "from collections import namedtuple\nimport numpy as np\nimport scipy as sp\nfrom scipy.sparse.csgraph import minimum_spanning_tree\nfrom .. import logging as logg\nfrom ..neighbors import Neighbors\nfrom .. import utils\nfrom .. import settings\n\n\ndef paga(\n        adata,\n        groups='louvain',\n        use_rna_velocity=False,\n        copy=False):\n    \"\"\"\\\n    Generate cellular maps of differentiation manifolds with complex\n    topologies [Wolf17i]_.\n\n    Partition-based graph abstraction (PAGA) quantifies the connectivities of\n    partitions of a neighborhood graph of single cells, thereby generating a\n    much simpler abstracted graph whose nodes label the partitions. Together\n    with a random walk-based distance measure, this generates a partial\n    coordinatization of data useful for exploring and explaining its variation.\n\n    Parameters\n    ----------\n    adata : :class:`~scanpy.api.AnnData`\n        Annotated data matrix.\n    groups : categorical annotation of observations or 'louvain_groups', optional (default: 'louvain_groups')\n        Criterion to determine the resulting partitions of the single-cell\n        graph. 'louvain_groups' uses the Louvain algorithm and optimizes\n        modularity of the graph. You can also pass your predefined groups by\n        choosing any categorical annotation of observations (`adata.obs`).\n    use_rna_velocity : `bool` (default: `False`)\n        Use RNA velocity to orient edges in the abstracted graph and estimate transitions.\n    copy : `bool`, optional (default: `False`)\n        Copy `adata` before computation and return a copy. Otherwise, perform\n        computation inplace and return `None`.\n\n    Returns\n    -------\n    Returns or updates `adata` depending on `copy` with\n    connectivities : np.ndarray (adata.uns['connectivities'])\n        The full adjacency matrix of the abstracted graph, weights\n        correspond to connectivities.\n    confidence : np.ndarray (adata.uns['confidence'])\n        The full adjacency matrix of the abstracted graph, weights\n        correspond to confidence in the presence of an edge.\n    confidence_tree : sc.sparse csr matrix (adata.uns['confidence_tree'])\n        The adjacency matrix of the tree-like subgraph that best explains\n        the topology.\n    \"\"\"\n    if 'neighbors' not in adata.uns:\n        raise ValueError(\n            'You need to run `pp.neighbors` first to compute a neighborhood graph.')\n    adata = adata.copy() if copy else adata\n    utils.sanitize_anndata(adata)\n    logg.info('running partition-based graph abstraction (PAGA)', reset=True)\n    paga = PAGA(adata, groups, use_rna_velocity=use_rna_velocity)\n    paga.compute()\n    # only add if not present\n    if 'paga' not in adata.uns:\n        adata.uns['paga'] = {}\n    if not use_rna_velocity:\n        adata.uns['paga']['connectivities'] = paga.connectivities_coarse\n        adata.uns['paga']['confidence'] = paga.confidence\n        adata.uns['paga']['confidence_tree'] = paga.confidence_tree\n        adata.uns[groups + '_sizes'] = np.array(paga.vc.sizes())\n    else:\n        adata.uns['paga']['transitions_confidence'] = paga.transitions_confidence\n        adata.uns['paga']['transitions_ttest'] = paga.transitions_ttest\n    adata.uns['paga']['groups'] = groups\n    logg.info('    finished', time=True, end=' ' if settings.verbosity > 2 else '\\n')\n    if use_rna_velocity:\n        logg.hint(\n            'added\\n'\n            '    \\'paga/transitions_confidence\\', confidence adjacency (adata.uns)\\n'\n            '    \\'paga/transitions_ttest\\', confidence subtree (adata.uns)')\n    else:\n        logg.hint(\n            'added\\n'\n            '    \\'paga/connectivities\\', connectivities adjacency (adata.uns)\\n'\n            '    \\'paga/confidence\\', confidence adjacency (adata.uns)\\n'\n            '    \\'paga/confidence_tree\\', confidence subtree (adata.uns)')\n    return adata if copy else None\n\n\nclass PAGA(Neighbors):\n\n    def __init__(self, adata, groups, use_rna_velocity=False,\n                 tree_based_confidence=False):\n        super(PAGA, self).__init__(adata)\n        self._groups = groups\n        self._tree_based_confidence = tree_based_confidence\n        self._use_rna_velocity = use_rna_velocity\n\n    def compute(self):\n        if self._use_rna_velocity:\n            self.compute_transitions_coarse()\n        else:\n            self.compute_connectivities_coarse()\n            self.compute_confidence()\n\n    def compute_connectivities_coarse(self):\n        import igraph\n        ones = self.connectivities.copy()\n        # graph where edges carry weight 1\n        ones.data = np.ones(len(ones.data))\n        g = utils.get_igraph_from_adjacency(ones)\n        self.vc = igraph.VertexClustering(\n            g, membership=self._adata.obs[self._groups].cat.codes.values)\n        cg = self.vc.cluster_graph(combine_edges='sum')\n        self.connectivities_coarse = utils.get_sparse_from_igraph(cg, weight_attr='weight')/2\n\n    def compute_confidence(self):\n        \"\"\"Translates the connectivities_coarse measure into a confidence measure.\n        \"\"\"\n        pseudo_distance = self.connectivities_coarse.copy()\n        pseudo_distance.data = 1./pseudo_distance.data\n        connectivities_coarse_tree = minimum_spanning_tree(pseudo_distance)\n        connectivities_coarse_tree.data = 1./connectivities_coarse_tree.data\n        connectivities_coarse_tree_indices = [\n            connectivities_coarse_tree[i].nonzero()[1]\n            for i in range(connectivities_coarse_tree.shape[0])]\n        # inter- and intra-cluster based confidence\n        if not self._tree_based_confidence:\n            total_n = self.n_neighbors * np.array(self.vc.sizes())\n            maximum = self.connectivities_coarse.max()\n            confidence = self.connectivities_coarse.copy()  # initializing\n            for i in range(self.connectivities_coarse.shape[0]):\n                for j in range(i+1, self.connectivities_coarse.shape[1]):\n                    if self.connectivities_coarse[i, j] > 0:\n                        geom_mean = np.sqrt(total_n[i] * total_n[j])\n                        confidence[i, j] = self.connectivities_coarse[i, j] / geom_mean\n                        confidence[j, i] = confidence[i, j]\n        # tree-based confidence\n        else:\n            median_connectivities_coarse_tree = np.median(connectivities_coarse_tree.data)\n            confidence = self.connectivities_coarse.copy()\n            confidence.data[self.connectivities_coarse.data >= median_connectivities_coarse_tree] = 1\n            connectivities_coarse_adjusted = self.connectivities_coarse.copy()\n            connectivities_coarse_adjusted.data -= median_connectivities_coarse_tree\n            connectivities_coarse_adjusted.data = np.exp(connectivities_coarse_adjusted.data)\n            index = self.connectivities_coarse.data < median_connectivities_coarse_tree\n            confidence.data[index] = connectivities_coarse_adjusted.data[index]\n        confidence_tree = self.compute_confidence_tree(\n            confidence, connectivities_coarse_tree_indices)\n        self.confidence = confidence\n        self.confidence_tree = confidence_tree\n\n    def compute_confidence_tree(\n            self, confidence, connectivities_coarse_tree_indices):\n        confidence_tree = sp.sparse.lil_matrix(confidence.shape, dtype=float)\n        for i, neighbors in enumerate(connectivities_coarse_tree_indices):\n            if len(neighbors) > 0:\n                confidence_tree[i, neighbors] = confidence[i, neighbors]\n        return confidence_tree.tocsr()\n\n    def compute_transitions_coarse(self):\n        # analogous code using networkx\n        # membership = adata.obs['clusters'].cat.codes.tolist()\n        # partition = defaultdict(list)\n        # for n, p in zip(list(range(len(G))), membership):\n        #     partition[p].append(n)\n        # partition = partition.values()\n        # g_abstracted = nx.quotient_graph(g, partition, relabel=True)\n        # for some reason, though, edges aren't oriented in the quotient\n        # graph...\n        import igraph\n        g = utils.get_igraph_from_adjacency(\n            self._adata.uns['velocyto_transitions'], directed=True)\n        vc = igraph.VertexClustering(\n            g, membership=self._adata.obs[self._groups].cat.codes.values)\n        cg_full = vc.cluster_graph(combine_edges=False)\n\n        g_bool = utils.get_igraph_from_adjacency(\n            self._adata.uns['velocyto_transitions'].astype('bool'), directed=True)\n        vc_bool = igraph.VertexClustering(\n            g_bool, membership=self._adata.obs[self._groups].cat.codes.values)\n        cg_bool = vc_bool.cluster_graph(combine_edges='sum')  # collapsed version\n        transitions_coarse = utils.get_sparse_from_igraph(cg_bool, weight_attr='weight')\n        # translate this into a confidence measure\n        # the number of outgoing edges\n        # total_n = np.zeros(len(vc.sizes()))\n        # # (this is not the convention of standard stochastic matrices)\n        # total_outgoing = transitions_coarse.sum(axis=1)\n        # for i in range(len(total_n)):\n        #     total_n[i] = vc.subgraph(i).ecount()\n        #     total_n[i] += total_outgoing[i, 0]\n        # use the topology based reference, the velocity one might have very small numbers\n        total_n = self.n_neighbors * np.array(vc_bool.sizes())\n        transitions_ttest = transitions_coarse.copy()\n        transitions_confidence = transitions_coarse.copy()\n        from scipy.stats import ttest_1samp\n        for i in range(transitions_coarse.shape[0]):\n            # no symmetry in transitions_coarse, hence we should not restrict to\n            # upper triangle\n            neighbors = transitions_coarse[i].nonzero()[1]\n            for j in neighbors:\n                forward = cg_full.es.select(_source=i, _target=j)['weight']\n                backward = cg_full.es.select(_source=j, _target=i)['weight']\n                # backward direction: add minus sign\n                values = np.array(list(forward) + list(-np.array(backward)))\n                # require some minimal number of observations\n                if len(values) < 5:\n                    transitions_ttest[i, j] = 0\n                    transitions_ttest[j, i] = 0\n                    transitions_confidence[i, j] = 0\n                    transitions_confidence[j, i] = 0\n                    continue\n                t, prob = ttest_1samp(values, 0.0)\n                if t > 0:\n                    # number of outgoing edges greater than number of ingoing edges\n                    # i.e., transition from i to j\n                    transitions_ttest[i, j] = -np.log10(max(prob, 1e-10))\n                    transitions_ttest[j, i] = 0\n                else:\n                    transitions_ttest[j, i] = -np.log10(max(prob, 1e-10))\n                    transitions_ttest[i, j] = 0\n                # geom_mean\n                geom_mean = np.sqrt(total_n[i] * total_n[j])\n                diff = (len(forward) - len(backward)) / geom_mean\n                if diff > 0:\n                    transitions_confidence[i, j] = diff\n                    transitions_confidence[j, i] = 0\n                else:\n                    transitions_confidence[j, i] = -diff\n                    transitions_confidence[i, j] = 0\n        transitions_ttest.eliminate_zeros()\n        transitions_confidence.eliminate_zeros()\n        # transpose in order to match convention of stochastic matrices\n        # entry ij means transition from j to i\n        self.transitions_ttest = transitions_ttest.T\n        self.transitions_confidence = transitions_confidence.T\n\n\ndef paga_degrees(adata):\n    \"\"\"Compute the degree of each node in the abstracted graph.\n\n    Parameters\n    ----------\n    adata : AnnData\n        Annotated data matrix.\n\n    Returns\n    -------\n    degrees : list\n        List of degrees for each node.\n    \"\"\"\n    import networkx as nx\n    g = nx.Graph(adata.uns['paga']['confidence'])\n    degrees = [d for _, d in g.degree(weight='weight')]\n    return degrees\n\n\ndef paga_expression_entropies(adata):\n    \"\"\"Compute the median expression entropy for each node-group.\n\n    Parameters\n    ----------\n    adata : AnnData\n        Annotated data matrix.\n\n    Returns\n    -------\n    entropies : list\n        Entropies of median expressions for each node.\n    \"\"\"\n    from scipy.stats import entropy\n    groups_order, groups_masks = utils.select_groups(\n        adata, key=adata.uns['paga']['groups'])\n    entropies = []\n    for mask in groups_masks:\n        X_mask = adata.X[mask]\n        x_median = np.median(X_mask, axis=0)\n        x_probs = (x_median - np.min(x_median)) / (np.max(x_median) - np.min(x_median))\n        entropies.append(entropy(x_probs))\n    return entropies\n\n\ndef paga_compare_paths(adata1, adata2,\n                       adjacency_key='confidence', adjacency_key2=None):\n    \"\"\"Compare paths in abstracted graphs in two datasets.\n\n    Compute the fraction of consistent paths between leafs, a measure for the\n    topological similarity between graphs.\n\n    By increasing the verbosity to level 4 and 5, the paths that do not agree\n    and the paths that agree are written to the output, respectively.\n\n    The PAGA \"groups key\" needs to be the same in both objects.\n\n    Parameters\n    ----------\n    adata1, adata2 : AnnData\n        Annotated data matrices to compare.\n    adjacency_key : str\n        Key for indexing the adjacency matrices in `.uns['paga']` to be used in\n        adata1 and adata2.\n    adjacency_key2 : str, None\n        If provided, used for adata2.\n\n\n    Returns\n    -------\n    OrderedTuple with attributes ``n_steps`` (total number of steps in paths)\n    and ``frac_steps`` (fraction of consistent steps), ``n_paths`` and\n    ``frac_paths``.\n    \"\"\"\n    import networkx as nx\n    g1 = nx.Graph(adata1.uns['paga'][adjacency_key])\n    g2 = nx.Graph(adata2.uns['paga'][adjacency_key2 if adjacency_key2 is not None else adjacency_key])\n    leaf_nodes1 = [str(x) for x in g1.nodes() if g1.degree(x) == 1]\n    logg.msg('leaf nodes in graph 1: {}'.format(leaf_nodes1), v=5, no_indent=True)\n    paga_groups = adata1.uns['paga']['groups']\n    asso_groups1 = utils.identify_groups(adata1.obs[paga_groups].values,\n                                         adata2.obs[paga_groups].values)\n    asso_groups2 = utils.identify_groups(adata2.obs[paga_groups].values,\n                                         adata1.obs[paga_groups].values)\n    orig_names1 = adata1.obs[paga_groups].cat.categories\n    orig_names2 = adata2.obs[paga_groups].cat.categories\n\n    import itertools\n    n_steps = 0\n    n_agreeing_steps = 0\n    n_paths = 0\n    n_agreeing_paths = 0\n    # loop over all pairs of leaf nodes in the reference adata1\n    for (r, s) in itertools.combinations(leaf_nodes1, r=2):\n        r2, s2 = asso_groups1[r][0], asso_groups1[s][0]\n        orig_names = [orig_names1[int(i)] for i in [r, s]]\n        orig_names += [orig_names2[int(i)] for i in [r2, s2]]\n        logg.msg('compare shortest paths between leafs ({}, {}) in graph1 and ({}, {}) in graph2:'\n               .format(*orig_names), v=4, no_indent=True)\n        no_path1 = False\n        try:\n            path1 = [str(x) for x in nx.shortest_path(g1, int(r), int(s))]\n        except nx.NetworkXNoPath:\n            no_path1 = True\n        no_path2 = False\n        try:\n            path2 = [str(x) for x in nx.shortest_path(g2, int(r2), int(s2))]\n        except nx.NetworkXNoPath:\n            no_path2 = True\n        if no_path1 and no_path2:\n            # consistent behavior\n            n_paths += 1\n            n_agreeing_paths += 1\n            n_steps += 1\n            n_agreeing_steps += 1\n            logg.msg('there are no connecting paths in both graphs', v=5, no_indent=True)\n            continue\n        elif no_path1 or no_path2:\n            # non-consistent result\n            n_paths += 1\n            n_steps += 1\n            continue\n        if len(path1) >= len(path2):\n            path_mapped = [asso_groups1[l] for l in path1]\n            path_compare = path2\n            path_compare_id = 2\n            path_compare_orig_names = [[orig_names2[int(s)] for s in l] for l in path_compare]\n            path_mapped_orig_names = [[orig_names2[int(s)] for s in l] for l in path_mapped]\n        else:\n            path_mapped = [asso_groups2[l] for l in path2]\n            path_compare = path1\n            path_compare_id = 1\n            path_compare_orig_names = [[orig_names1[int(s)] for s in l] for l in path_compare]\n            path_mapped_orig_names = [[orig_names1[int(s)] for s in l] for l in path_mapped]\n        n_agreeing_steps_path = 0\n        ip_progress = 0\n        for il, l in enumerate(path_compare[:-1]):\n            for ip, p in enumerate(path_mapped):\n                if ip >= ip_progress and l in p:\n                    # check whether we can find the step forward of path_compare in path_mapped\n                    if (ip + 1 < len(path_mapped)\n                        and\n                        path_compare[il + 1] in path_mapped[ip + 1]):\n                        # make sure that a step backward leads us to the same value of l\n                        # in case we \"jumped\"\n                        logg.msg('found matching step ({} -> {}) at position {} in path{} and position {} in path_mapped'\n                               .format(l, path_compare_orig_names[il + 1], il, path_compare_id, ip), v=6)\n                        consistent_history = True\n                        for iip in range(ip, ip_progress, -1):\n                            if l not in path_mapped[iip - 1]:\n                                consistent_history = False\n                        if consistent_history:\n                            # here, we take one step further back (ip_progress - 1); it's implied that this\n                            # was ok in the previous step\n                            logg.msg('    step(s) backward to position(s) {} in path_mapped are fine, too: valid step'\n                                   .format(list(range(ip - 1, ip_progress - 2, -1))), v=6)\n                            n_agreeing_steps_path += 1\n                            ip_progress = ip + 1\n                            break\n        n_steps_path = len(path_compare) - 1\n        n_agreeing_steps += n_agreeing_steps_path\n        n_steps += n_steps_path\n        n_paths += 1\n        if n_agreeing_steps_path == n_steps_path: n_agreeing_paths += 1\n\n        # only for the output, use original names\n        path1_orig_names = [orig_names1[int(s)] for s in path1]\n        path2_orig_names = [orig_names2[int(s)] for s in path2]\n        logg.msg('      path1 = {},\\n'\n               'path_mapped = {},\\n'\n               '      path2 = {},\\n'\n               '-> n_agreeing_steps = {} / n_steps = {}.'\n               .format(path1_orig_names,\n                       [list(p) for p in path_mapped_orig_names],\n                       path2_orig_names,\n                       n_agreeing_steps_path, n_steps_path), v=5, no_indent=True)\n    Result = namedtuple('paga_compare_paths_result',\n                        ['frac_steps', 'n_steps', 'frac_paths', 'n_paths'])\n    return Result(frac_steps=n_agreeing_steps/n_steps if n_steps > 0 else np.nan,\n                  n_steps=n_steps if n_steps > 0 else np.nan,\n                  frac_paths=n_agreeing_paths/n_paths if n_steps > 0 else np.nan,\n                  n_paths=n_paths if n_steps > 0 else np.nan)\n", "meta": {"hexsha": "d800cdce3e86b3fb748785cf5b0ccbdfe3714b0c", "size": 19335, "ext": "py", "lang": "Python", "max_stars_repo_path": "scanpy/tools/paga.py", "max_stars_repo_name": "LuckyMD/scanpy", "max_stars_repo_head_hexsha": "4b38130cb7a76f284058fb788c8279999389e3c5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scanpy/tools/paga.py", "max_issues_repo_name": "LuckyMD/scanpy", "max_issues_repo_head_hexsha": "4b38130cb7a76f284058fb788c8279999389e3c5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scanpy/tools/paga.py", "max_forks_repo_name": "LuckyMD/scanpy", "max_forks_repo_head_hexsha": "4b38130cb7a76f284058fb788c8279999389e3c5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.1455847255, "max_line_length": 121, "alphanum_fraction": 0.6179467287, "include": true, "reason": "import numpy,import scipy,from scipy,import networkx", "num_tokens": 4495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.17278490574836985}}
{"text": "import glob, os, sys\nimport numpy as np\nimport scipy.integrate as integrate\nimport scipy.ndimage\nimport matplotlib.pylab as plt\nfrom scipy.interpolate import griddata\n\nclass Dist:\n    \"\"\"\n    This class load the data given a filename\n    and gives the possibility to generate a plot with the uploaded data\n    \"\"\"\n    def __init__(self, filename, is_avoid_zeros=True):\n        # It is better to make general x,y arrays\n        self.x, self.y = np.loadtxt(filename, comments=\"#\", unpack=True)\n        if is_avoid_zeros:\n            s_len = len(self.x)\n            self.x, self.y = self.avoid_zeros()\n            print(\"%i lines deleted\" % (s_len - len(self.x)))\n    \n    def avoid_zeros(self):\n        is_not_zero = self.y != 0\n        x = self.x[is_not_zero]\n        y = self.y[is_not_zero]\n        return x, y\n\n    def plot(self, loglog=True):\n        fig = plt.figure()\n        ax = fig.add_subplot(111)\n        if loglog:\n            ax.loglog(self.x, self.y, 'o')\n        else:\n            ax.plot(self.x, self.y, 'o')\n\nclass DistCollector:\n    \"\"\"\n    this is class to collects all the filenames \n    in a dictionary of instances and allows to produce different plots\n    selecting four main parameters.\n    First the type of structure. Subsequently for the given nanostructure it is possible to select the quantity or type of distribution to plot,\n    and restrict the analysis to a given diameter or thickness.\n    Parameters:\n    ===========\n    mainDir: str\n        Directory containing the files\n    maxLex: int, opt\n        max lenght of string describing the file types to consider\n        such in dot_Hy_300_t20_bis.dat\n    structure: string, opt\n        the structure used in the experiment (dot,pillar,ring)\n    \"\"\"\n    def __init__(self, mainDir, maxLen=4, structure=\"dot\"):  \n        self._mainDir = mainDir\n        # Check if the dist_type exists\n        # How can we do it?\n        self.plotTypes=dict()\n        self.plotTypes= {'Hy': 'Hysteresis Loop','Hyst': 'Hysteresis Loop', 'Ener': 'Energies'}\n        self.dis_types = self._get_distribution_types(maxLen)\n        self.diameters = self._get_diameters(maxLen)\n        self.thicknesses= self._get_thicknesses(maxLen)\n        print(self.dis_types)\n        print(self.thicknesses)\n        self.distrs = dict()\n        for dis_type in self.dis_types:\n            self.distrs[dis_type] = dict()\n            for diameter in self.diameters:\n               pattern = \"%s_%s_%s_t*_*.dat\" % (structure, dis_type,diameter)\n               pattern = os.path.join(self._mainDir, pattern)\n               filenames = sorted(glob.glob(pattern))\n               print('\\n'.join(filenames))\n               self.distrs[dis_type][diameter] = dict()\n               for filename in filenames:\n                    fname = os.path.join(self._mainDir, filename)\n                    thick = self._get_thickness(fname)\n                    self.distrs[dis_type][diameter][thick] = Dist(fname)\n\n    def plot(self, dis_type,diameter=\"*\",thickness=\"*\", loglog=False):\n        \"\"\"\n        plot all the distributions\n        just giving the type ('S', 'T', 'E', etc)\n        \"\"\"\n        if dis_type not in self.dis_types:\n            print(\"Type %s does not exist, please check it\" % dis_type)\n            return\n        if diameter != \"*\" and (diameter not in self.diameters):\n            print(\"Diameter %s does not exist, please check it\" % diameter)\n            return\n        if thickness != \"*\" and (thickness not in self.thicknesses):\n            print(\"thickness %s does not exist, please check it\" % thickness)\n            return\n        fig = plt.figure()\n        ax = fig.add_subplot(111)\n        ax.set_title('%s' % self.plotTypes[dis_type])\n        if diameter != \"*\":\n            if thickness != \"*\":\n                ax.set_title('%s , diameter = %s nm, thickness = %s nm' % (self.plotTypes[dis_type],diameter,thickness))\n            else:\n                ax.set_title('%s , diameter = %s nm' % (self.plotTypes[dis_type],diameter))\n            \n        if (thickness != \"*\" and diameter == \"*\"):\n            ax.set_title('%s , thickness = %s nm' % (self.plotTypes[dis_type],thickness))\n\n        for diam in sorted(self.distrs[dis_type]):\n            if (diam==diameter and diameter!=\"*\") or diameter==\"*\":\n                for thick in sorted(self.distrs[dis_type][diam]):\n                    if (thick==thickness and thickness!=\"*\") or thickness==\"*\":\n                        d = self.distrs[dis_type][diam][thick]\n                        if thickness==\"*\" and diameter==\"*\":\n                            lb = \" d= %s nm, t= %s nm\" % (diam,thick)\n                        else:\n                            if diameter==\"*\":\n                                lb = \"d= %s nm\" % (diam)\n                            else:\n                                lb = \"t= %s nm\" % (thick)\n                        ax.plot(d.x, d.y, label=lb)\n        \n        ax.legend(numpoints=1,loc=4)\n        ax.grid(True)\n        # Here we need to explicity say to show the plot\n        plt.show()\n\n    def _get_distribution_types(self, maxLen=4):\n        \"\"\"\n        find the type of distributions in the given directory, reading the 2nd position in the files name\n        and returns all the availble diameters as in dot_Hyst_100_00_s20.dat\n        Parameters:\n        ===========\n            maxLen: int, opt\n            max length of the string to be searched \n        \"\"\"\n        filenames = glob.glob(os.path.join(self._mainDir, \"*.dat\"))\n        filenames = [os.path.splitext(filename)[0] for filename in filenames]\n        filenames = [os.path.split(filename)[1] for filename in filenames]\n        filenames = [filename.split(\"_\", 2)[1] for filename in filenames]\n        dis_types = [filename for filename in filenames if len(filename) <= maxLen]\n        dis_types = set(dis_types)\n        return dis_types\n\n    def _get_diameters(self, maxLen=3):\n        \"\"\"\n        find the diameter or maxdimension of the object (denoted by dimension in nanometers)\n        in the given directory, reading the 3rd position in the file names and returns all the availble diameters\n        as in dot_Hyst_100_00_s20.dat\n        Parameters:\n        ===========\n            maxLen: int, opt\n            max length of the string to be searched \n        \"\"\"\n        filenames = glob.glob(os.path.join(self._mainDir, \"*.dat\"))\n        filenames = [os.path.splitext(filename)[0] for filename in filenames]\n        filenames = [os.path.split(filename)[1] for filename in filenames]\n        print('\\n'.join(filenames))\n        filenames = [filename.split(\"_\",3)[2] for filename in filenames]\n        diameters = [filename for filename in filenames if len(filename) <= maxLen]\n        diameters = set(diameters)\n        return diameters\n    def _get_thicknesses(self, maxLen=4):\n        \"\"\"\n        find the diameter or maxdimension of the objecr (denoted by dimension in nanometers)\n        looking at the last character of the filenames \n        as in dot_Hyst_100_00_s20.dat\n        Parameters:\n        ===========\n            maxLen: int, opt\n            max length of the string to be searched \n        \"\"\"\n        filenames = glob.glob(os.path.join(self._mainDir, \"*.dat\"))\n        filenames = [os.path.splitext(filename)[0] for filename in filenames]\n        filenames = [os.path.split(filename)[1] for filename in filenames]\n        filenames = [filename.split(\"_t\",1)[1] for filename in filenames]\n        filenames = [filename.split(\"_\",1)[0] for filename in filenames]\n        for filename in filenames:\n           if \"v\" in filename:\n              filename = ['%s.%s' %(filename.split(\"v\",1)[0],filename.split(\"v\",1)[1])]\n        thicknesses = [filename for filename in filenames if len(filename) <= maxLen]\n        thicknesses = set(thicknesses)\n        return thicknesses\n    def _get_diameter(self,filename,maxLen=3):\n        \"\"\"\n        find the diameter or maxdimension of the objecr (denoted by dimension in nanometers)\n        looking at the last character of the filenames \n        as in dot_Hyst_100_00_s20.dat\n        Parameters:\n        ===========\n            filename\n            maxLen: int, opt\n            max length of the string to be searched \n        \"\"\"\n        filename = os.path.splitext(filename)[0] \n        filename = os.path.split(filename)[1] \n        filename = filename.split(\"_\",3)[2] \n        diameter = filename \n        return diameter\n\n    def _get_thickness(self,filename, maxLen=3):\n        \"\"\"\n        find the diameter or maxdimension of the objecr (denoted by dimension in nanometers)\n        looking at the last character of the filenames \n        as in dot_Hyst_100_00_s20.dat\n        Parameters:\n        ===========\n            filename\n            maxLen: int, opt\n            max length of the string to be searched \n        \"\"\"\n        filename = os.path.splitext(filename)[0] \n        filename = os.path.split(filename)[1] \n        filename = filename.split(\"_t\")[-1] \n        filename = filename.split(\"_\")[0]\n        if \"v\" in filename:\n              part1=filename.split(\"v\",1)[0]\n              part2=filename.split(\"v\",1)[1]\n              filename = ''.join((filename.split(\"v\",1)[0],'.',filename.split(\"v\",1)[1]))#['%s.%s' %(filename.split(\"v\",1)[0],filename.split(\"v\",1)[1])]\n        print(filename)\n        thickness = filename\n        return thickness\n\nclass integral:\n    \"\"\"\n    This class load the data given a filename and integrates the curve\n    \"\"\"\n    def __init__(self, filename, mainDir, is_avoid_zeros=True):\n        # It is better to make general x,y arrays\n        self._mainDir = mainDir\n        fname = os.path.join(self._mainDir, filename)\n        self.x, self.y = np.loadtxt(fname , comments=\"#\", unpack=True)\n        if is_avoid_zeros:\n            s_len = len(self.x)\n            self.x, self.y = self.avoid_zeros()\n            print(\"%i lines deleted\" % (s_len - len(self.x)))\n        self.fullHyst=self.x[-1]-self.x[0]\n        value=self.integra()\n        self.energy=2*4*np.pi*1.e-7*value\n\n    def avoid_zeros(self):\n        is_not_zero = self.y != 0\n        x = self.x[is_not_zero]\n        y = self.y[is_not_zero]\n        return x, y\n\n    def integra(self):\n        \n        if self.fullHyst==0:\n           middle=int(np.round(self.x.size/4))\n           top=int(np.round(self.x.size/2))\n           self._branchup=integrate.simps(self.y[0:middle],self.x[0:middle])\n           self._branchdown=integrate.simps(self.y[middle:top],self.x[middle:top])\n           self.result=-self._branchdown-self._branchup\n        else:\n           middle=int(np.round(self.x.size/2))\n           self._branchdown=integrate.simps(self.y,self.x)\n           self._branchup=integrate.simps(-np.flipud(self.y),-np.flipud(self.x))\n           self.result=(-self._branchdown+self._branchup)/2\n        return self.result\n\nclass mapsHystEnergy:\n    \"\"\"\n    this is class to collect all the filenames \n    in a dictionary of instances and plot the desired map givien the parameters\n    Parameters:\n    ===========\n    mainDir: str\n        Directory containing the files\n    maxLex: int, opt\n        max lenght of string describing the file types to consider\n        such in dot_Hyst_500_00_s30.dat\n    structure: string, opt\n        the structure used in the experiment (dot,pillar,thorus)\n    \"\"\"\n    def __init__(self, mainDir,structure=\"dot\"):\n        self.dist=DistCollector(mainDir)\n    def integra(self,x,y):\n        self.fullHyst=x[-1]-x[0]\n        if self.fullHyst==0:\n           middle=int(np.round(x.size/4))\n           top=int(np.round(x.size/2))\n           self._branchup=integrate.simps(y[0:middle],x[0:middle])\n           self._branchdown=integrate.simps(y[middle:top],x[middle:top])\n           self.result=-self._branchdown-self._branchup\n        else:\n           middle=int(np.round(x.size/2))\n           self._branchdown=integrate.simps(y,x)\n           self._branchup=integrate.simps(-np.flipud(y),-np.flipud(x))\n           self.result=(-self._branchdown+self._branchup)/2\n        return self.result\n\n    def setData(self,outName=\"mapdata\",structure=\"dot\",dis_type=\"Hy\"): \n        points=np.array([])    \n        values = np.array([])\n        mappatxt = np.array([])\n        for diam in sorted(self.dist.distrs[dis_type]):\n            for thick in sorted(self.dist.distrs[dis_type][diam]):\n                points=np.append(points,(int(diam),float(thick)))\n                value=self.integra(self.dist.distrs[dis_type][diam][thick].x,self.dist.distrs[dis_type][diam][thick].y)\n                self.energy=2*4*np.pi*1.e-7*value\n                values=np.append(values,self.energy)\n                print(self.energy,diam,thick)\n                mappatxt=np.append(mappatxt,(int(diam),float(thick),self.energy))\n        mappatxt=np.reshape(mappatxt,(-1,3))\n        points=np.reshape(points,(-1,2))\n        values=np.reshape(values,(-1,1))\n        np.savetxt(outName,mappatxt[:],\"%4d  %4.2f %12.8e\")\n        return (points,values)\n\n    def plotMap(self):\n        points,values=self.setData()\n        #xmin=np.min(points[:,0])\n        #xmax=np.max(points[:,0])\n        #ymin=np.min(points[:,1])\n        #ymax=np.max(points[:,1])\n        \n        grid_x, grid_y = np.mgrid[np.min(points[:,0]):np.max(points[:,0]):100j, np.min(points[:,1]):np.max(points[:,1]):100j]\n        #print(grid_x, grid_y)\n        \n        grid_z0 = griddata((points[:,0],points[:,1]), values, (grid_x, grid_y), method='linear',fill_value=0)\n        print(np.min(values)/2)\n        #\n        origin = 'lower'\n        CS=plt.contourf(grid_x,grid_y,grid_z0[:,:,0],100)\n        plt.rcParams['contour.negative_linestyle'] = 'solid'\n        CS2 = plt.contour(CS, levels=CS.levels[::10],\n                          colors='k',\n                          origin=origin,\n                          hold='on')\n        plt.clabel(CS2, fontsize=9, inline=1)\n        #plt.axis([200, 650, 10, 30])\n        plt.colorbar(CS)\n        plt.show()\n\nif __name__ == \"__main__\":\n    mainDir = \"W:\\\\Micro\\\\Riccardo\\\\Dot\\\\Single\\\\Results\\\\Hyst_new\\\\Bis\"\n    #mainDir = \"D:\\\\git\\\\Python-In-The-Lab_Project\\\\Python-In-The-Lab_Project\\\\Hyst\"\n\n\n    dcoll = DistCollector(mainDir)\n    dcoll.plot(\"Hy\", diameter=\"300\")\n    #integ=integral(\"dot_Hy_650_t30_bis.dat\",mainDir)\n    #print(integ.result)\n    #integ=integral(\"dot_Hy_650_t25_bis.dat\",mainDir)\n    #print(integ.result)\n    #integ=integral(\"dot_Hy_500_t30_bis.dat\",mainDir)\n    #print(integ.result)\n    #integ=integral(\"dot_Hy_500_t25_bis.dat\",mainDir)\n    #print(integ.result)\n    maps=mapsHystEnergy(mainDir)\n    maps.plotMap()\n    #point,values=maps.setData()\n\n    #print(dcoll.distrs[\"Hyst\"][\"300\"][\"30\"].x)\n    #print(integ.energy)\n\n\n", "meta": {"hexsha": "1dd09dbbc3bc13e2ab6b2a2c0a43fa03ebc2ca78", "size": 14609, "ext": "py", "lang": "Python", "max_stars_repo_path": "distributions4_alt_name_convention.py", "max_stars_repo_name": "Morrighan89/Python-In-The-Lab_Project", "max_stars_repo_head_hexsha": "dadcb6618eb6fcc39bc4812918ca0c56c22b4bd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-05-03T17:56:02.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-03T17:56:02.000Z", "max_issues_repo_path": "distributions4_alt_name_convention.py", "max_issues_repo_name": "Morrighan89/Python-In-The-Lab_Project", "max_issues_repo_head_hexsha": "dadcb6618eb6fcc39bc4812918ca0c56c22b4bd3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "distributions4_alt_name_convention.py", "max_forks_repo_name": "Morrighan89/Python-In-The-Lab_Project", "max_forks_repo_head_hexsha": "dadcb6618eb6fcc39bc4812918ca0c56c22b4bd3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3852691218, "max_line_length": 152, "alphanum_fraction": 0.5861455267, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 3630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3276682876897044, "lm_q1q2_score": 0.17278490228627075}}
{"text": "\"\"\" Simple Solar abundance calculations.\n\"\"\"\nfrom __future__ import (print_function, absolute_import, division,\n                        unicode_literals)\n\n# Python 2 & 3 compatibility\ntry:\n    basestring\nexcept NameError:\n    basestring = str\n\nimport numpy as np\nimport numbers\nimport imp\n\nfrom astropy.io import ascii\nfrom astropy.utils.misc import isiterable\n\n#from xastropy.xutils import xdebug as xdb\nl_path = imp.find_module('linetools')[1]\n\n#\nclass SolarAbund(object):\n    \"\"\"Class to handle simple Solar Abundance calculations\n\n    Parameters\n    ----------\n    ref: str, optional\n       'Asplund2009' :: Asplund et al. 2009, ARA&A, 47, 481 meteoritic\n       table (several photospheric though)\n    \"\"\"\n    # Init\n    def __init__(self, ref='Asplund2009', verbose=False):\n\n        # Error catching\n        if not isinstance(ref, basestring):\n            raise TypeError('SolarAbund__init__: Wrong ref type for '\n                            'SolarAbund input')\n        self.ref = ref\n\n        # Load Data\n        print('Loading abundances from {:s}'.format(self.ref))\n        self.load_data()\n        print('Abundances are relative by number on a '\n              'logarithmic scale with H=12') \n\n    def load_data(self):\n        \"\"\"Grab the Solar Abundance data (in linetools/abund)\n        \"\"\"\n        # Data file\n        if self.ref == 'Asplund2009':\n            dat_file = l_path + '/data/abund/solar_Asplund2009.dat'\n            # Read table\n            names = ('Elm', 'Abund', 'Z')\n            table = ascii.read(dat_file, format='no_header', names=names) \n            # \n        else:\n            raise ValueError('Unrecognized reference for SolarAbund: {:s}'.format(self.ref))\n        # Save\n        self._data = table\n\n\n    def get_ratio(self, rtio):\n        \"\"\" Return abundance ratio\n\n        Parameters\n        ----------\n        rtio : str \n          Element ratio (e.g. 'Si/Fe')        \n        \"\"\"\n        # Elements\n        elm1, elm2 = rtio.split('/')\n        # Abundances\n        ab1 = self[elm1]\n        ab2 = self[elm2]\n        # ratio\n        return ab1 - ab2\n\n    def __getitem__(self, k):\n        \"\"\" Return abundance given an element\n \n        Parameters\n        ----------\n        k : int or str or list/tuple\n          * int -- Atomic number (6)\n          * str -- Element name (e.g. 'C')\n\n        Returns\n        -------\n        Abund : float\n        \"\"\"\n        # Iterate?\n        if isiterable(k) and not isinstance(k, basestring): \n            out_abnd = []\n            for ik in k:\n                out_abnd.append(self[ik])\n            out_abnd = np.array(out_abnd)\n            return out_abnd\n\n        if isinstance(k, numbers.Integral): # Atomic number\n            mt = np.where(self._data['Z'] == k)[0]\n            if len(mt) != 1:\n                raise ValueError('Atomic Number not in Table: {:d}'.format(k))\n        elif isinstance(k, basestring): # Name\n            mt = np.where(self._data['Elm'] == k)[0]\n            if len(mt) != 1:\n                raise ValueError('Element not in Table: {:s}'.format(k))\n        else:\n            raise IndexError('Not prepared for this type of input', k)\n\n        # Return\n        return self._data['Abund'][mt][0]\n\n    # Printing\n    def __repr__(self):\n        # Generate sets string\n        return '<SolarAbund: {:s}>'.format(self.ref)\n", "meta": {"hexsha": "27775c374ddf84e69da9f1b7bf6eb7f0b5cfa643", "size": 3322, "ext": "py", "lang": "Python", "max_stars_repo_path": "linetools/abund/solar.py", "max_stars_repo_name": "jchowk/linetools", "max_stars_repo_head_hexsha": "5a0eafa96ab854c52c070ce756033c0499414dde", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2015-07-09T02:24:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T15:13:31.000Z", "max_issues_repo_path": "linetools/abund/solar.py", "max_issues_repo_name": "jchowk/linetools", "max_issues_repo_head_hexsha": "5a0eafa96ab854c52c070ce756033c0499414dde", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 491, "max_issues_repo_issues_event_min_datetime": "2015-06-21T20:01:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-11T03:29:19.000Z", "max_forks_repo_path": "linetools/abund/solar.py", "max_forks_repo_name": "jchowk/linetools", "max_forks_repo_head_hexsha": "5a0eafa96ab854c52c070ce756033c0499414dde", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2015-05-25T00:18:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-30T06:53:14.000Z", "avg_line_length": 28.1525423729, "max_line_length": 92, "alphanum_fraction": 0.5466586394, "include": true, "reason": "import numpy,from astropy", "num_tokens": 815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.17252097950077863}}
{"text": "#!/usr/bin/env python\n\"\"\"\nPopulates 2D or 3D arrays with data from an Insight3 analysis file.\n\nHazen 7/09\n\nModified (incompletely) to support lazy loading, which helps\nwhen dealing with super huge insight3 files.\n\nHazen 11/11\n\"\"\"\n\nimport numpy\nimport os\nimport sys\n\nimport storm_analysis.sa_library.datareader as datareader\nimport storm_analysis.sa_library.grid_c as grid_c\nimport storm_analysis.sa_library.i3dtype as i3dtype\nimport storm_analysis.sa_library.readinsight3 as readinsight3\nimport storm_analysis.sa_library.regfilereader as regfilereader\n\n\ndef getFilmSize(filename, i3_data):\n    \"\"\"\n    Determine the (analyzed) film size.\n    \"\"\"\n\n    # First try to load meta data.\n    metadata = readinsight3.loadI3Metadata(filename, verbose = False)\n    if metadata is not None:\n        movie_data = metadata.find(\"movie\")\n        movie_x = int(movie_data.find(\"movie_x\").text)\n        movie_y = int(movie_data.find(\"movie_y\").text)\n        movie_l = int(movie_data.find(\"movie_l\").text)\n\n        # Check if analysis stopped before the end of the movie.\n        settings = metadata.find(\"settings\")\n        max_frame = int(settings.find(\"max_frame\").text)\n        if (max_frame > 0):\n            movie_l = max_frame\n        return [movie_x, movie_y, movie_l]\n\n    # Next try and load the corresponding movie file.\n    names = [filename[:-9], filename[:-10]]\n    extensions = [\".dax\", \".spe\", \".tif\"]\n    for name in names:\n        for ext in extensions:\n            if os.path.exists(name + ext):\n                movie_file = datareader.inferReader(name + ext)\n                return movie_file.filmSize()\n\n    # Finally, just guess / hope. Assume that\n    # the image size is a power of 2..\n    film_l = int(numpy.max(i3_data['fr']))+1\n    \n    max_x = numpy.max(i3_data['x'])\n    x_size = 2\n    while(x_size < max_x):\n        x_size = x_size * 2\n\n    max_y = numpy.max(i3_data['y'])\n    y_size = 2\n    while(y_size < max_y):\n        y_size = y_size * 2\n    \n    print(\"Could not find movie file for\", filename, \"assuming\", x_size, \"x\", y_size, \"by\", str(film_l))\n    return [x_size, y_size, film_l]\n\n\nclass I3GGeneric(object):\n    \"\"\"\n    Generic Insight3 grid class.\n    \"\"\"\n    def __init__(self, filename, scale = 4, verbose = True):\n\n        # Setup names.\n        self.filename = filename\n        self.fullname = filename\n        self.dirname = os.path.dirname(filename)\n        if (len(self.dirname) > 0):\n            self.dirname = self.dirname + \"/\"\n            self.filename = os.path.splitext(os.path.basename(filename))[0]\n            \n        # Other class variables\n        self.scale = int(scale)\n        self.z_range = 1000.0\n\n\nclass I3GData(I3GGeneric):\n    \"\"\"\n    The I3 grid class.\n\n    This class will attempt to load the entire localization list\n    into memory. This is fine for smaller data sets but can\n    be problematic for large data sets.\n    \"\"\"\n    def __init__(self, filename, scale = 4, verbose = True):\n        I3GGeneric.__init__(self,\n                            filename,\n                            scale = scale,\n                            verbose = verbose)\n        \n        self.i3data = readinsight3.loadI3GoodOnly(filename, verbose = verbose)\n        self.i3data['fr'] -= 1\n\n        # Determine film size.\n        [image_x, image_y, self.film_l] = getFilmSize(filename, self.i3data)\n        self.im_size = [image_x, image_y]\n\n        # Determine what channels the image has.\n        self.channels = []\n        for i in range(10):\n            mask = (self.i3data['c'] == i)\n            if mask.sum() > 0:\n                self.channels.append(i)\n\n    # Utility\n    def applyXYDriftCorrection(self, dx, dy):\n        if isinstance(dx, numpy.ndarray):\n            f = self.i3data['fr']\n            i = numpy.arange(f.size, dtype=int)\n            dx = dx.astype(numpy.float32)\n            dy = dy.astype(numpy.float32)\n            self.i3data['xc'][i] = self.i3data['x'] + dx[f]\n            self.i3data['yc'][i] = self.i3data['y'] + dy[f]\n        else:\n            self.i3data['xc'] = self.i3data['x'] + dx\n            self.i3data['yc'] = self.i3data['y'] + dy\n\n    def applyZDriftCorrection(self, dz):\n        if isinstance(dz, numpy.ndarray):\n            f = self.i3data['fr']\n            i = numpy.arange(f.size, dtype=int)\n            self.i3data['zc'][i] = self.i3data['z'] + dz[f]\n        else:\n            self.i3data['zc'] = self.i3data['z'] + dz\n\n    def get2D(self, zmin = -1000.0, zmax = 1000.0):\n        return self.i3To2DGridAllChannelsMerged(verbose = 0, zmin = zmin, zmax = zmax)\n\n    def get3D(self, zbins, zmin = -1000.0, zmax = 1000.0):\n        return self.i3To3DGridAllChannelsMerged(zbins, zmin = zmin, zmax = zmax, verbose = 0)\n\n    def getData(self):\n        return self.i3data\n\n    def getDirname(self):\n        return self.dirname\n\n    def getFilename(self):\n        return self.filename\n\n    def getFilmLength(self):\n        return self.film_l\n\n    def getFullname(self):\n        return self.fullname\n\n    def getImageSize(self):\n        return self.im_size\n\n    def getNumberMolecules(self):\n        return self.i3data['x'].size\n\n    def getScale(self):\n        return self.scale\n\n    def getXY(self):\n        return [self.i3data['xc'],\n                self.i3data['yc']]\n\n    def getXYZ(self):\n        return [self.i3data['xc'],\n                self.i3data['yc'],\n                self.i3data['zc']]\n\n    def getXYZCat(self):\n        return [self.i3data['xc'],\n                self.i3data['yc'],\n                self.i3data['zc'],\n                self.i3data['c']]\n\n    def getXYZICat(self):\n        return [self.i3data['xc'],\n                self.i3data['yc'],\n                self.i3data['zc'],\n                self.i3data['i'],\n                self.i3data['c']]\n\n    def getZRange(self):\n        return self.z_range\n\n    def offsetX(self, dx):\n        self.i3data['xc'] += dx\n\n    def offsetY(self, dy):\n        self.i3data['yc'] += dy\n\n    def offsetZ(self, dz):\n        self.i3data['zc'] += dz\n\n    def setScale(self, scale):\n        self.scale = scale\n\n    # Gridding data\n    def i3To2DGrid(self, fmin = 0, fmax = 500000, zmin = -1000.0, zmax = 1000.0, uncorrected = False, matrix = False, translate = False, verbose = True):\n\n        if uncorrected:\n            [x, y, z] = [self.i3data['x'],\n                         self.i3data['y'],\n                         self.i3data['z']]\n        else:\n            [x, y, z] = [self.i3data['xc'],\n                         self.i3data['yc'],\n                         self.i3data['zc']]\n            \n        cat = self.i3data['c']\n        f = self.i3data['fr']\n\n        [image_x, image_y] = self.im_size\n        scale = int(self.scale)\n\n        if isinstance(matrix, numpy.ndarray):\n            if translate:\n                [x, y] = regfilereader.applyTransform(matrix, x, y)\n            else:\n                [x, y] = regfilereader.applyTransformNoTranslation(matrix, x, y)\n\n        max_max = 0.0\n        max_counts = []\n        image_data = []\n        for channel in self.channels:\n            mask = (cat == channel) & (f >= fmin) & (f < fmax) & (z > zmin) & (z < zmax)\n            #print numpy.sum(mask)\n            i_x = numpy.floor(x[mask] * scale).astype(int)\n            i_y = numpy.floor(y[mask] * scale).astype(int)\n            if (i_x.shape[0] > 0):\n                channel_data = grid_c.grid2D(i_x,i_y,(image_x*scale,image_y*scale))\n            else:\n                channel_data = numpy.zeros((image_x*scale, image_y*scale))\n            image_data.append(channel_data.astype(numpy.float32))\n            max_count = numpy.max(channel_data)\n            if max_count > max_max:\n                max_max = max_count\n            max_counts.append(max_count)\n\n        return [image_data, self.channels, max_counts, max_max]\n\n    def i3To2DGridAllChannelsMerged(self, fmin = 0, fmax = 500000, zmin = -1000.0, zmax = 1000.0, uncorrected = False, verbose = True):\n        [image_data, channels, max_counts, max_max] = self.i3To2DGrid(fmin = fmin, \n                                                                      zmin = zmin,\n                                                                      zmax = zmax,\n                                                                      fmax = fmax, \n                                                                      uncorrected = uncorrected,\n                                                                      verbose = verbose)\n        if (len(image_data) > 0):\n            merged_image = image_data[0]\n            for i in range(len(image_data)-1):\n                merged_image += image_data[i+1]\n            return merged_image\n\n    def i3To3DGrid(self, z_bins, fmin = 0, fmax = 500000, zmin = -1000.0, zmax = 1000.0, uncorrected = False, verbose = True):\n\n        if uncorrected:\n            [x, y, z] = [self.i3data['x'],\n                         self.i3data['y'],\n                         self.i3data['z']]\n        else:\n            [x, y, z] = [self.i3data['xc'],\n                         self.i3data['yc'],\n                         self.i3data['zc']]\n            \n        cat = self.i3data['c']\n        f = self.i3data['fr']\n\n        [image_x, image_y] = self.im_size\n        xy_scale = int(self.scale)\n        z_bins = int(z_bins)\n        z_range = zmax - zmin\n\n        max_max = 0.0\n        max_counts = []\n        image_data = []\n        for channel in self.channels:\n            mask = (cat == channel) & (f >= fmin) & (f < fmax) & (z > zmin) & (z < zmax)\n            i_x = numpy.floor(x[mask] * xy_scale).astype(int)\n            i_y = numpy.floor(y[mask] * xy_scale).astype(int)\n            i_z = numpy.floor((z[mask] - zmin) * float(z_bins)/z_range).astype(int)\n            if (i_x.shape[0] > 0):\n                channel_data = grid_c.grid3D(i_x, i_y, i_z, (image_x*xy_scale, image_y*xy_scale, z_bins))\n            else:\n                channel_data = numpy.zeros((image_x*xy_scale, image_y*xy_scale, z_bins))\n            image_data.append(channel_data.astype(numpy.float32))\n            max_count = numpy.max(channel_data)\n            if max_count > max_max:\n                max_max = max_count\n            max_counts.append(max_count)\n\n        return [image_data, self.channels, max_counts, max_max]\n\n    def i3To3DGridAllChannelsMerged(self, z_bins, fmin = 0, fmax = 500000, zmin = -1000.0, zmax = 1000.0, uncorrected = False, verbose = True):\n        [image_data, channels, max_counts, max_max] = self.i3To3DGrid(z_bins, \n                                                                      fmin = fmin, \n                                                                      fmax = fmax,\n                                                                      zmin = zmin,\n                                                                      zmax = zmax,\n                                                                      uncorrected = uncorrected,\n                                                                      verbose = verbose)\n        merged_image = image_data[0]\n        for i in range(len(image_data)-1):\n            merged_image += image_data[i+1]\n        return merged_image\n\n\nclass I3GDataLL(I3GData):\n    \"\"\"\n    The I3 grid lazy-load class.\n\n    This class will only load the localizations as needed, making\n    it quite a bit less memory intensive.\n\n    FIXME: Ugh, this inherits I3GData, but initializes using I3GGeneric.\n    \"\"\"\n    def __init__(self, filename, scale = 4, verbose = True):\n        I3GGeneric.__init__(self, \n                            filename,\n                            scale = scale,\n                            verbose = verbose)\n\n        self.i3_in = readinsight3.I3Reader(filename)\n        self.i3data = self.i3_in.nextBlock()\n        self.resetFp()\n\n        # Determine film size.\n        [image_x, image_y, self.film_l] = getFilmSize(filename, self.i3data)\n        self.im_size = [image_x, image_y]\n\n        # Determine what channels the image has.\n        self.channels = []\n        if (self.getNumberMolecules() > 0):\n            for i in range(10):\n                mask = (self.i3data['c'] == i)\n                if mask.sum() > 0:\n                    self.channels.append(i)\n\n    def close(self):\n        self.i3_in.close()\n\n    def dataIsGood(self):\n        if(type(self.i3data)==type(numpy.array([]))):\n            return True\n        else:\n            return False\n\n    def getCurrentFrameRange(self):\n        return [self.i3data['fr'][0], self.i3data['fr'][-1]]\n\n    def getNumberMolecules(self):\n        return self.i3_in.getNumberMolecules()\n\n    def loadDataInFrames(self, fmin = 0, fmax = 500000):\n        self.i3data = self.i3_in.getMoleculesInFrameRange(fmin+1, fmax+1)\n        self.i3data['fr'] -= 1\n\n    def i3ToXDGridAllChannelsMergedLL(self, grid_fn, verbose):\n        self.i3_in.resetFp()\n        self.i3data = self.i3_in.nextBlock()\n        merged = grid_fn()\n\n        self.i3data = self.i3_in.nextBlock()        \n        while(isinstance(self.i3data, numpy.ndarray)):\n            if verbose:\n                sys.stdout.write(\".\")\n                sys.stdout.flush()\n            merged += grid_fn()\n            self.i3data = self.i3_in.nextBlock()\n        if verbose:\n            print(\"\")\n\n        return merged\n\n    def i3To2DGridAllChannelsMergedLL(self, zmin = -1000.0, zmax = 1000.0, uncorrected = False, verbose = True):\n        def gridFn():\n            return self.i3To2DGridAllChannelsMerged(zmin = zmin,\n                                                    zmax = zmax,\n                                                    uncorrected = uncorrected,\n                                                    verbose = verbose)\n        return self.i3ToXDGridAllChannelsMergedLL(gridFn, verbose)\n\n    def i3To2DGridSpecificChannelLL(self, channel, zmin = -1000.0, zmax = 1000.0, uncorrected = False, verbose = True):\n        def gridFn():\n            mask = (self.i3data['c'] == channel)\n            self.i3data = i3dtype.maskData(self.i3data, mask)\n            return self.i3To2DGridAllChannelsMerged(zmin = zmin,\n                                                    zmax = zmax,\n                                                    uncorrected = uncorrected,\n                                                    verbose = verbose)\n        return self.i3ToXDGridAllChannelsMergedLL(gridFn, verbose)\n\n    def i3To3DGridAllChannelsMergedLL(self, z_bins, zmin = -1000.0, zmax = 1000.0, uncorrected = False, verbose = True):\n        def gridFn():\n            return self.i3To3DGridAllChannelsMerged(z_bins,\n                                                    zmin = zmin,\n                                                    zmax = zmax,\n                                                    uncorrected = uncorrected,\n                                                    verbose = verbose)\n        return self.i3ToXDGridAllChannelsMergedLL(gridFn, verbose)\n\n    def i3To3DGridSpecificChannelLL(self, channel, z_bins, zmin = -1000.0, zmax = 1000.0, uncorrected = False, verbose = True):\n        def gridFn():\n            mask = (self.i3data['c'] == channel)\n            self.i3data = i3dtype.maskData(self.i3data, mask)\n            return self.i3To3DGridAllChannelsMerged(z_bins,\n                                                    zmin = zmin,\n                                                    zmax = zmax,\n                                                    uncorrected = uncorrected,\n                                                    verbose = verbose)\n        return self.i3ToXDGridAllChannelsMergedLL(gridFn, verbose)\n\n    def nextBlock(self, block_size = 500000):\n        self.i3data = self.i3_in.nextBlock(block_size = block_size)\n        if(type(self.i3data)==type(numpy.array([]))):\n            self.i3data['fr'] -= 1\n            return True\n        else:\n            return False\n\n    def resetFp(self):\n        self.i3_in.resetFp()\n\n\n#\n# The MIT License\n#\n# Copyright (c) 2012 Zhuang Lab, Harvard University\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n", "meta": {"hexsha": "b5f23c8663d211ea475afed58ce5b9b2edb543a1", "size": 16931, "ext": "py", "lang": "Python", "max_stars_repo_path": "storm_analysis/sa_library/i3togrid.py", "max_stars_repo_name": "bintulab/storm-analysis", "max_stars_repo_head_hexsha": "71ae493cbd17ddb97938d0ae2032d97a0eaa76b2", "max_stars_repo_licenses": ["CNRI-Python"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "storm_analysis/sa_library/i3togrid.py", "max_issues_repo_name": "bintulab/storm-analysis", "max_issues_repo_head_hexsha": "71ae493cbd17ddb97938d0ae2032d97a0eaa76b2", "max_issues_repo_licenses": ["CNRI-Python"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "storm_analysis/sa_library/i3togrid.py", "max_forks_repo_name": "bintulab/storm-analysis", "max_forks_repo_head_hexsha": "71ae493cbd17ddb97938d0ae2032d97a0eaa76b2", "max_forks_repo_licenses": ["CNRI-Python"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-19T18:17:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-19T18:17:06.000Z", "avg_line_length": 37.1293859649, "max_line_length": 153, "alphanum_fraction": 0.538302522, "include": true, "reason": "import numpy", "num_tokens": 4125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.3345894478883556, "lm_q1q2_score": 0.1725209779410987}}
{"text": "import os\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom typing_extensions import Literal\n\nfrom qubekit.molecules import CloudPen, Dipole, Quadrupole\nfrom qubekit.utils.constants import ANGS_TO_NM\n\nif TYPE_CHECKING:\n    from qubekit.molecules import Ligand\n\n\nclass ExtractChargeData:\n    \"\"\"\n    Choose between extracting (the more extensive) data from Chargemol, or from ONETEP.\n    Store all info back into the molecule object\n    \"\"\"\n\n    @classmethod\n    def extract_charge_data_chargemol(\n        cls,\n        molecule: \"Ligand\",\n        dir_path: str,\n        ddec_version: Literal[3, 6],\n    ) -> \"Ligand\":\n        \"\"\"\n        From Chargemol output files, extract the necessary parameters for calculation of L-J.\n        Args:\n            molecule: Usual molecule object.\n            ddec_version: Which ddec version was used to run chargemol? 3 or 6.\n            dir_path: Directory containing the ddec output files.\n        Return:\n            Updated molecule object.\n        \"\"\"\n\n        if ddec_version == 6:\n            net_charge_file_path = os.path.join(\n                dir_path, \"DDEC6_even_tempered_net_atomic_charges.xyz\"\n            )\n\n        elif ddec_version == 3:\n            net_charge_file_path = os.path.join(\n                dir_path, \"DDEC3_net_atomic_charges.xyz\"\n            )\n\n        else:\n            raise ValueError(\"Unsupported DDEC version; please use version 3 or 6.\")\n\n        try:\n            with open(net_charge_file_path, \"r+\") as charge_file:\n                lines = charge_file.readlines()\n        except FileNotFoundError:\n            raise FileNotFoundError(\n                \"Cannot find the DDEC output file.\\nThis could be indicative of several issues.\\n\"\n                \"Please check Chargemol is installed in the correct location and that the configs \"\n                \"point to that location.\"\n            )\n\n        # Find number of atoms\n        atom_total = int(lines[0])\n\n        # Find data markers:\n        ddec_start_pos, cloud_pen_pos = 0, 0\n        for pos, row in enumerate(lines):\n            if \"The following XYZ\" in row:\n                ddec_start_pos = pos + 2\n\n            # [sic]\n            elif \"The sperically averaged\" in row:\n                cloud_pen_pos = pos + 2\n\n            if ddec_start_pos and cloud_pen_pos:\n                break\n        else:\n            raise EOFError(\n                f\"Cannot find charge or cloud penetration data in {net_charge_file_path}.\"\n            )\n\n        chargemol_xyz = []\n        for line in lines[ddec_start_pos : ddec_start_pos + atom_total]:\n            # _'s are the atomic symbol, xyz coords, then the quadrupole moment tensor eigenvalues.\n            (\n                atom_count,\n                _,\n                x,\n                y,\n                z,\n                charge,\n                x_dipole,\n                y_dipole,\n                z_dipole,\n                _,\n                q_xy,\n                q_xz,\n                q_yz,\n                q_x2_y2,\n                q_3z2_r2,\n                *_,\n            ) = line.split()\n\n            # File counts from 1 not 0; thereby requiring -1 to get the index.\n            atom_index = int(atom_count) - 1\n\n            molecule.atoms[atom_index].aim.charge = float(charge)\n\n            molecule.atoms[atom_index].dipole = Dipole(\n                x=float(x_dipole),\n                y=float(y_dipole),\n                z=float(z_dipole),\n            )\n\n            molecule.atoms[atom_index].quadrupole = Quadrupole(\n                q_xy=float(q_xy),\n                q_xz=float(q_xz),\n                q_yz=float(q_yz),\n                q_xx=(float(q_x2_y2) / 2 - float(q_3z2_r2) / 6),\n                q_yy=(-float(q_x2_y2) / 2 - float(q_3z2_r2) / 6),\n                q_zz=float(q_3z2_r2) / 3,\n            )\n\n            # save the chargemol reorientated positions\n            chargemol_xyz.append([x, y, z])\n\n        molecule.chargemol_coords = chargemol_xyz\n\n        for line in lines[cloud_pen_pos : cloud_pen_pos + atom_total]:\n            # _'s are the xyz coords and the r_squared.\n            atom_count, _, _, _, _, a, b, _ = line.split()\n            atom_index = int(atom_count) - 1\n            molecule.atoms[atom_index].cloud_pen = CloudPen(\n                a=float(a),\n                b=float(b),\n            )\n\n        r_cubed_file_name = os.path.join(dir_path, \"DDEC_atomic_Rcubed_moments.xyz\")\n\n        with open(r_cubed_file_name, \"r+\") as vol_file:\n            lines = vol_file.readlines()\n\n        volumes = [float(line.split()[-1]) for line in lines[2 : atom_total + 2]]\n\n        for atom_index in range(atom_total):\n            molecule.atoms[atom_index].aim.volume = volumes[atom_index]\n\n        return molecule\n\n    @classmethod\n    def extract_charge_data_onetep(cls, molecule: \"Ligand\", dir_path: str) -> \"Ligand\":\n        \"\"\"\n        From ONETEP output files, extract the necessary parameters for calculation of L-J.\n        Args:\n            molecule: Usual molecule object.\n            dir_path: Directory containing the ddec output files.\n        Return:\n            Updated molecule object.\n        \"\"\"\n\n        # Second file contains the rest (charges, dipoles and volumes):\n        ddec_output_file = (\n            \"ddec.onetep\" if os.path.exists(\"ddec.onetep\") else \"iter_1/ddec.onetep\"\n        )\n\n        ddec_file_path = os.path.join(dir_path, ddec_output_file)\n\n        with open(ddec_file_path, \"r\") as file:\n            lines = file.readlines()\n\n        charge_pos, vol_pos = None, None\n        for pos, line in enumerate(lines):\n\n            # Charges marker in file:\n            if \"DDEC density\" in line:\n                charge_pos = pos + 7\n\n            # Volumes marker in file:\n            if \"DDEC Radial\" in line:\n                vol_pos = pos + 4\n\n        if any(position is None for position in [charge_pos, vol_pos]):\n            raise EOFError(\n                \"Cannot locate charges and / or volumes in ddec.onetep file.\"\n            )\n\n        charges = [\n            float(line.split()[-1])\n            for line in lines[charge_pos : charge_pos + molecule.n_atoms]\n        ]\n\n        # Add the AIM-Valence and the AIM-Core to get V^AIM\n        volumes = [\n            float(line.split()[2]) + float(line.split()[3])\n            for line in lines[vol_pos : vol_pos + molecule.n_atoms]\n        ]\n\n        for atom_index in range(molecule.n_atoms):\n            molecule.atoms[atom_index].aim.volume = volumes[atom_index]\n            molecule.atoms[atom_index].aim.charge = charges[atom_index]\n\n        return molecule\n\n\ndef extract_c8_params(molecule: \"Ligand\", dir_path: str) -> \"Ligand\":\n    \"\"\"\n    Extract the C8 dispersion coefficients from the MCLF calculation's output file.\n    Args:\n        molecule: Usual molecule object.\n        dir_path: Directory containing the C8 xyz file from Chargemol.\n    returns: Updated molecule object.\n    \"\"\"\n\n    with open(os.path.join(dir_path, \"MCLF_C8_dispersion_coefficients.xyz\")) as c8_file:\n        lines = c8_file.readlines()\n        for i, line in enumerate(lines):\n            if line.startswith(\" The following \"):\n                lines = lines[i + 2 : -2]\n                break\n        else:\n            raise EOFError(\"Cannot locate c8 parameters in file.\")\n\n        # c8 params IN ATOMIC UNITS\n        c8_params = [float(line.split()[-1].strip()) for line in lines]\n        for atom_index in range(molecule.n_atoms):\n            molecule.atoms[atom_index].aim.c8 = c8_params[atom_index]\n\n    return molecule\n\n\ndef extract_extra_sites_onetep(molecule: \"Ligand\"):\n    \"\"\"\n    Gather the extra sites from the xyz file and insert them into the molecule object.\n    * Find parent and 2 reference atoms\n    * Calculate the local coords site\n    Args:\n        molecule: Usual molecule object.\n    \"\"\"\n\n    with open(\"xyz_with_extra_point_charges.xyz\") as xyz_sites:\n        lines = xyz_sites.readlines()\n\n    parent = 0\n    site_number = 0\n\n    for i, line in enumerate(lines[2:]):\n        if line.split()[0] != \"X\":\n            parent += 1\n            # Search the following entries for sites connected to this atom\n            for virtual_site in lines[i + 3 :]:\n                site_data = {}\n                element, *site_coords, site_charge = virtual_site.split()\n                # Not a virtual site:\n                if element != \"X\":\n                    break\n                else:\n                    site_data[\"charge\"] = site_charge\n                    site_data[\"parent_index\"] = parent\n                    site_coords = np.array([float(coord) for coord in site_coords])\n\n                    closest_atoms = list(molecule.to_topology().neighbors(parent))\n                    if (len(closest_atoms) < 2) or (\n                        len(molecule.atoms[parent].bonds) > 3\n                    ):\n                        for atom in list(\n                            molecule.to_topology().neighbors(closest_atoms[0])\n                        ):\n                            if atom not in closest_atoms and atom != parent:\n                                closest_atoms.append(atom)\n                                break\n\n                    # Get the xyz coordinates of the reference atoms\n                    coords = molecule.coordinates\n                    parent_coords = coords[parent]\n                    close_a_coords = coords[closest_atoms[0]]\n                    close_b_coords = coords[closest_atoms[1]]\n\n                    site_data[\"closest_a_index\"] = closest_atoms[0]\n                    site_data[\"closest_b_index\"] = closest_atoms[1]\n\n                    parent_atom = molecule.atoms[parent]\n                    if parent_atom.atomic_symbol == \"N\" and len(parent_atom.bonds) == 3:\n                        close_c_coords = coords[closest_atoms[2]]\n                        site_data[\"closest_c_index\"] = closest_atoms[2]\n\n                        x_dir = (\n                            (close_a_coords + close_b_coords + close_c_coords) / 3\n                        ) - parent_coords\n                        x_dir /= np.linalg.norm(x_dir)\n\n                        site_data[\"p2\"] = 0\n                        site_data[\"p3\"] = 0\n\n                        site_data[\"o_weights\"] = [1.0, 0.0, 0.0, 0.0]\n                        site_data[\"x_weights\"] = [\n                            -1.0,\n                            0.33333333,\n                            0.33333333,\n                            0.33333333,\n                        ]\n                        site_data[\"y_weights\"] = [1.0, -1.0, 0.0, 0.0]\n\n                    else:\n                        x_dir = close_a_coords - parent_coords\n                        x_dir /= np.linalg.norm(x_dir)\n\n                        z_dir = np.cross(\n                            (close_a_coords - parent_coords),\n                            (close_b_coords - parent_coords),\n                        )\n                        z_dir /= np.linalg.norm(z_dir)\n\n                        y_dir = np.cross(z_dir, x_dir)\n\n                        p2 = float(\n                            np.dot((site_coords - parent_coords), y_dir.reshape(3, 1))\n                            * ANGS_TO_NM\n                        )\n                        site_data[\"p2\"] = round(p2, 4)\n                        p3 = float(\n                            np.dot((site_coords - parent_coords), z_dir.reshape(3, 1))\n                            * ANGS_TO_NM\n                        )\n                        site_data[\"p3\"] = round(p3, 4)\n\n                        site_data[\"o_weights\"] = [1.0, 0.0, 0.0]\n                        site_data[\"x_weights\"] = [-1.0, 1.0, 0.0]\n                        site_data[\"y_weights\"] = [-1.0, 0.0, 1.0]\n\n                    p1 = float(\n                        np.dot((site_coords - parent_coords), x_dir.reshape(3, 1))\n                        * ANGS_TO_NM\n                    )\n                    site_data[\"p1\"] = round(p1, 4)\n\n                    molecule.extra_sites.create_site(**site_data)\n\n                    site_number += 1\n", "meta": {"hexsha": "09591fc0916e6b4970aa3cce65c4dda49ff54b9a", "size": 11981, "ext": "py", "lang": "Python", "max_stars_repo_path": "qubekit/charges/utils.py", "max_stars_repo_name": "qubekit/QUBEK", "max_stars_repo_head_hexsha": "9f0bfeba50dd5b7c900353e4e7a363a5f47cbd00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45, "max_stars_repo_stars_event_min_datetime": "2019-04-10T09:23:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:59:21.000Z", "max_issues_repo_path": "qubekit/charges/utils.py", "max_issues_repo_name": "qubekit/QUBEK", "max_issues_repo_head_hexsha": "9f0bfeba50dd5b7c900353e4e7a363a5f47cbd00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 127, "max_issues_repo_issues_event_min_datetime": "2019-04-12T09:40:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T15:49:15.000Z", "max_forks_repo_path": "qubekit/charges/utils.py", "max_forks_repo_name": "qubekit/QUBEK", "max_forks_repo_head_hexsha": "9f0bfeba50dd5b7c900353e4e7a363a5f47cbd00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2019-05-31T17:46:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T21:44:43.000Z", "avg_line_length": 35.5519287834, "max_line_length": 99, "alphanum_fraction": 0.5171521576, "include": true, "reason": "import numpy", "num_tokens": 2672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.1725209760795531}}
{"text": "import copy\nimport itertools\n\nimport numpy as np\nfrom sortedcontainers import SortedListWithKey\n\nfrom .tabled_trie import Trie, make_trie\n\n\nclass LevenshteinSearcher:\n    \"\"\"\n    Класс для поиска близких слов\n    в соответствии с расстоянием Левенштейна\n\n    \"\"\"\n    def __init__(self, alphabet, dictionary, operation_costs=None,\n                 allow_spaces=False, euristics='none'):\n        self.alphabet = alphabet\n        self.allow_spaces = allow_spaces\n        if isinstance(euristics, int):\n            if euristics < 0:\n                raise ValueError(\"Euristics should be non-negative integer or None\")\n            else:\n                self.euristics = euristics if euristics != 0 else None\n        elif euristics in [\"none\", \"None\", None]:\n            self.euristics = None\n        else:\n            raise ValueError(\"Euristics should be non-negative integer or None\")\n        if isinstance(dictionary, Trie):\n            # словарь передан уже в виде бора\n            self.dictionary = dictionary\n        else:\n            self.dictionary = make_trie(alphabet, dictionary, make_cashed=True,\n                                        precompute_symbols=self.euristics,\n                                        allow_spaces=self.allow_spaces)\n        self.transducer = SegmentTransducer(\n            alphabet, operation_costs=operation_costs, allow_spaces=allow_spaces)\n        self._precompute_euristics()\n        self._define_h_function()\n\n    def __contains__(self, word):\n        return word in self.dictionary\n\n    def search(self, word, d, allow_spaces=True, return_cost=True):\n        \"\"\"\n        Finds all dictionary words in d-window from word\n        \"\"\"\n        if not all((c in self.alphabet\n                    or (c == \" \" and self.allow_spaces)) for c in word):\n            return []\n            # raise ValueError(\"{0} contains an incorrect symbol\".format(word))\n        return self._trie_search(\n            word, d, allow_spaces=allow_spaces, return_cost=return_cost)\n\n    def _trie_search(self, word, d, transducer=None,\n                     allow_spaces=True, return_cost=True):\n        \"\"\"\n        Находит все слова в префиксном боре, расстояние до которых\n        в соответствии с заданным преобразователем не превышает d\n        \"\"\"\n        if transducer is None:\n            # разобраться с пробелами\n            transducer = self.transducer.inverse()\n        allow_spaces &= self.allow_spaces\n        trie = self.dictionary\n        #  инициализация переменных\n        used_agenda_keys = set()\n        agenda = SortedListWithKey(key=(lambda x:x[1]))\n        h = self.h_func(word, trie.root)\n        # agenda[self.agenda_key(\"\", 0, trie.root)] = (0.0, 0.0, h)\n        key, value = (\"\", 0, trie.root), (0.0, 0.0, h)\n        agenda.add((key, value))\n        answer = dict()\n        k = 0\n        # очередь с приоритетом с промежуточными результатами\n        while len(agenda) > 0:\n            key, value = agenda.pop(0)\n            if key in used_agenda_keys:\n                continue\n            used_agenda_keys.add(key)\n            low, pos, index = key\n            cost, g, h = value\n            # g --- текущая стоимость, h --- нижняя оценка будущей стоимости\n            # cost = g + h --- нижняя оценка суммарной стоимости\n            k += 1\n            max_upperside_length = min(len(word) - pos, transducer.max_up_length)\n            for upperside_length in range(max_upperside_length + 1):\n                new_pos = pos + upperside_length\n                curr_up = word[pos: new_pos]\n                if curr_up not in transducer.operation_costs:\n                    continue\n                for curr_low, curr_cost in transducer.operation_costs[curr_up].items():\n                    new_g = g + curr_cost\n                    if new_g > d:  #если g > d, то h можно не вычислять\n                        continue\n                    if curr_low == \" \":\n                        if allow_spaces and trie.is_final(index):\n                            new_index = trie.root\n                        else:\n                            new_index = Trie.NO_NODE\n                    else:\n                        new_index = trie.descend(index, curr_low)\n                    if new_index is Trie.NO_NODE:\n                        continue\n                    new_low = low + curr_low\n                    new_h = self.h_func(word[new_pos: ], new_index)\n                    new_cost = new_g + new_h\n                    if new_cost > d:\n                        continue\n                    new_key = (new_low, new_pos, new_index)\n                    new_value = (new_cost, new_g, new_h)\n                    if new_pos == len(word) and trie.is_final(new_index):\n                        old_g = answer.get(new_low, None)\n                        if old_g is None or new_g < old_g:\n                            answer[new_low] = new_g\n                    agenda.add((new_key, new_value))\n        answer = sorted(answer.items(), key=(lambda x: x[1]))\n        if return_cost:\n            return answer\n        else:\n            return [elem[0] for elem in answer]\n\n    def _precompute_euristics(self):\n        \"\"\"\n        Предвычисляет будущие символы и стоимости операций с ними\n        для h-эвристики\n        \"\"\"\n        if self.euristics is None:\n            return\n        # вычисление минимальной стоимости операции,\n        # приводящей к появлению ('+') или исчезновению ('-') данного символа\n        removal_costs = {a : np.inf for a in self.alphabet}\n        insertion_costs = {a : np.inf for a in self.alphabet}\n        if self.allow_spaces:\n            removal_costs[' '] = np.inf\n            insertion_costs[' '] = np.inf\n        for up, costs in self.transducer.operation_costs.items():\n            for low, cost in costs.items():\n                if up == low:\n                    continue\n                if up != '':\n                    removal_cost = cost / len(up)\n                    for a in up:\n                        removal_costs[a] = min(removal_costs[a], removal_cost)\n                if low != '':\n                    insertion_cost = cost / len(low)\n                    for a in low:\n                        insertion_costs[a] = min(insertion_costs[a], insertion_cost)\n        # предвычисление возможных будущих символов в узлах дерева\n        # precompute_future_symbols(self.dictionary, self.euristics, self.allow_spaces)\n        # предвычисление стоимостей потери символа в узлах дерева\n        self._absense_costs_by_node = _precompute_absense_costs(\n            self.dictionary, removal_costs, insertion_costs,\n            self.euristics, self.allow_spaces)\n        # массив для сохранения эвристик\n        self._temporary_euristics = [dict() for i in range(len(self.dictionary))]\n\n    def _define_h_function(self):\n        if self.euristics in [None, 0]:\n            self.h_func = (lambda *x: 0.0)\n        else:\n            self.h_func = self._euristic_h_function\n\n    def _euristic_h_function(self, suffix, index):\n        \"\"\"\n        Вычисление h-эвристики из работы Hulden,2009 для текущей вершины словаря\n\n        Аргументы:\n        ----------\n        suffix : string\n            непрочитанный суффикс входного слова\n        index : int\n            индекс текущего узла в словаре\n\n        Возвращает:\n        -----------\n        cost : float\n            оценка снизу для стоимости замены,\n            приводящей к входному слову с суффиксом suffix,\n            если прочитанный префикс слова без опечатки\n            привёл в вершину с номером index\n        \"\"\"\n        if self.euristics > 0:\n            suffix = suffix[:self.euristics]\n        # кэширование результатов\n        index_temporary_euristics = self._temporary_euristics[index]\n        cost = index_temporary_euristics.get(suffix, None)\n        if cost is not None:\n            return cost\n        # извлечение нужных данных из массивов\n        absense_costs = self._absense_costs_by_node[index]\n        data = self.dictionary.data[index]\n        costs = np.zeros(dtype=np.float64, shape=(self.euristics,))\n        # costs[j] --- оценка штрафа при предпросмотре вперёд на j символов\n        for i, a in enumerate(suffix):\n            costs[i:] += absense_costs[a][i:]\n        cost = max(costs)\n        index_temporary_euristics[suffix] = cost\n        return cost\n\n    def _minimal_replacement_cost(self, first, second):\n        first_symbols, second_symbols = set(), set()\n        removal_cost, insertion_cost = 0, 0\n        for a, b in itertools.zip_longest(first, second, fillvalue=None):\n            if a is not None:\n                first_symbols.add(a)\n            if b is not None:\n                second_symbols.add(b)\n            removal_cost = max(removal_cost, len(first_symbols - second_symbols))\n            insertion_cost = max(insertion_cost, len(second_symbols - first_symbols))\n        return min(removal_cost, insertion_cost)\n\n\ndef _precompute_absense_costs(dictionary, removal_costs, insertion_costs, n,\n                              allow_spaces=False):\n    \"\"\"\n    Вычисляет минимальную стоимость появления нового символа в узлах словаря\n    в соответствии со штрафами из costs\n\n    Аргументы:\n    ---------------\n    dictionary : Trie\n        словарь, хранящийся в виде ациклического автомата\n\n    removal_costs : dict\n        штрафы за удаление символов\n\n    insertion_costs : dict\n        штрафы за вставку символов\n\n    n : int\n        глубина ``заглядывания вперёд'' в словаре\n\n    Возвращает\n    ---------------\n    answer : list of dicts, len(answer)=len(dictionary)\n        answer[i][a][j] равно минимальному штрафу за появление символа a\n        в j-ой позиции в вершине с номером i\n    \"\"\"\n    answer = [dict() for node in dictionary.data]\n    if n == 0:\n        return answer\n    curr_alphabet = copy.copy(dictionary.alphabet)\n    if allow_spaces:\n        curr_alphabet += [' ']\n    for l, (costs_in_node, node) in enumerate(zip(answer, dictionary.data)):\n        # определение минимальной стоимости удаления символов\n        curr_node_removal_costs = np.empty(dtype=np.float64, shape=(n,))\n        if len(node[0]) > 0:\n            curr_node_removal_costs[0] = min(removal_costs[symbol] for symbol in node[0])\n            for j, symbols in enumerate(node[1:], 1):\n                if len(symbols) == 0:\n                    curr_node_removal_costs[j:] = curr_node_removal_costs[j-1]\n                    break\n                curr_cost = min(removal_costs[symbol] for symbol in symbols)\n                curr_node_removal_costs[j] = min(curr_node_removal_costs[j-1], curr_cost)\n        else:\n            curr_node_removal_costs[:] = np.inf\n        # определение минимальной стоимости вставки\n        for a in curr_alphabet:\n            curr_symbol_costs = np.empty(dtype=np.float64, shape=(n,))\n            curr_symbol_costs.fill(insertion_costs[a])\n            for j, symbols in enumerate(node):\n                if a in symbols:\n                    curr_symbol_costs[j:] = 0.0\n                    break\n                curr_symbol_costs[j] = min(curr_symbol_costs[j], curr_node_removal_costs[j])\n            costs_in_node[a] = curr_symbol_costs\n    return answer\n\n\nclass SegmentTransducer:\n    \"\"\"\n    Класс, реализующий взвешенный конечный преобразователь,\n    осуществляющий замены из заданного списка операций\n\n    Аргументы:\n    ----------\n    alphabet : list\n        алфавит\n\n    operation_costs : dict or None(optional, default=None)\n        словарь вида {(up,low) : cost}\n\n    allow_spaces : bool(optional, default=False)\n        разрешены ли элементы трансдукции, содержащие пробел\n        (используется только если явно не заданы operation costs\n        и они равны значению по умолчанию)\n\n    \"\"\"\n    def __init__(self, alphabet, operation_costs=None, allow_spaces=False):\n        self.alphabet = alphabet\n        if operation_costs is None:\n            self._make_default_operation_costs(allow_spaces=allow_spaces)\n        elif not isinstance(operation_costs, dict):\n            raise TypeError(\"Operation costs must be a dictionary\")\n        else:\n            self.operation_costs = operation_costs\n        self._make_reversed_operation_costs()\n        self._make_maximal_key_lengths()\n        # self.maximal_value_lengths = {}\n        # for up, probs in self.operation_costs.items():\n            # СЛИШКОМ МНОГО ВЫЗОВОВ, НАДО КАК-ТО ЗАПОМНИТЬ\n            # МАКСИМАЛЬНЫЕ ДЛИНЫ КЛЮЧЕЙ ПРИ ОБРАЩЕНИИ\n            # max_low_length = max(len(low) for low in probs) if (len(probs) > 0) else -1\n            # self.maximal_value_lengths[up] = self.maximal_key_length\n\n    def get_operation_cost(self, up, low):\n        \"\"\"\n        Возвращает стоимость элементарной трансдукции up->low\n        или np.inf, если такой элементарной трансдукции нет\n\n        Аргументы:\n        ----------\n        up, low : string\n            элементы элементарной трансдукции\n\n        Возвращает:\n        -----------\n        cost : float\n            стоимость элементарной трансдукции up->low\n            (np.inf, если такая трансдукция отсутствует)\n        \"\"\"\n        up_costs = self.operation_costs.get(up, None)\n        if up_costs is None:\n            return np.inf\n        cost = up_costs.get(low, np.inf)\n        return cost\n\n    def inverse(self):\n        \"\"\"\n        Строит пробразователь, задающий обратное конечное преобразование\n        \"\"\"\n        # УПРОСТИТЬ ОБРАЩЕНИЕ!!!\n        inversed_transducer = SegmentTransducer(self.alphabet, operation_costs=dict())\n        inversed_transducer.operation_costs = self._reversed_operation_costs\n        inversed_transducer._reversed_operation_costs = self.operation_costs\n        inversed_transducer.max_low_length = self.max_up_length\n        inversed_transducer.max_up_length = self.max_low_length\n        inversed_transducer.max_low_lengths_by_up = self.max_up_lengths_by_low\n        inversed_transducer.max_up_lengths_by_low = self.max_low_lengths_by_up\n        return inversed_transducer\n\n    def distance(self, first, second, return_transduction = False):\n        \"\"\"\n        Вычисляет трансдукцию минимальной стоимости,\n        отображающую first в second\n\n        Аргументы:\n        -----------\n        first : string\n        second : string\n            Верхний и нижний элементы трансдукции\n\n        return_transduction : bool (optional, default=False)\n            следует ли возвращать трансдукцию минимального веса\n            (см. возвращаемое значение)\n\n        Возвращает:\n        -----------\n        (final_cost, transductions) : tuple(float, list)\n            если return_transduction=True, то возвращает\n            минимальную стоимость трансдукции, переводящей first в second\n            и список трансдукций с данной стоимостью\n\n        final_cost : float\n            если return_transduction=False, то возвращает\n            минимальную стоимость трансдукции, переводящей first в second\n        \"\"\"\n        if return_transduction:\n            add_pred = (lambda x, y: (y == np.inf or x < y))\n        else:\n            add_pred = (lambda x, y: (y == np.inf or x <= y))\n        clear_pred = (lambda x, y: (y < np.inf and x < y))\n        update_func = lambda x, y: min(x, y)\n        costs, backtraces = self._fill_levenshtein_table(first, second,\n                                                        update_func, add_pred, clear_pred)\n        final_cost = costs[-1][-1]\n        if final_cost == np.inf:\n            transductions = [None]\n        elif return_transduction:\n            transductions = self._backtraces_to_transductions(first, second, backtraces,\n                                                              final_cost, return_cost=False)\n        if return_transduction:\n            return final_cost, transductions\n        else:\n            return final_cost\n\n    def transduce(self, first, second, threshold):\n        \"\"\"\n        Возвращает все трансдукции, переводящие first в second,\n        чья стоимость не превышает threshold\n\n        Возвращает:\n        ----------\n        result : list\n            список вида [(трансдукция, стоимость)]\n        \"\"\"\n        add_pred = (lambda x, y: x <= threshold)\n        clear_pred =(lambda x, y: False)\n        update_func = (lambda x, y: min(x, y))\n        costs, backtraces = self._fill_levenshtein_table(first, second,\n                                                        update_func, add_pred, clear_pred,\n                                                        threshold=threshold)\n        result = self._backtraces_to_transductions(first, second,\n                                                   backtraces, threshold, return_cost=True)\n        return result\n\n    def lower_transductions(self, word, max_cost, return_cost=True):\n        \"\"\"\n        Возвращает все трансдукции с верхним элементом word,\n        чья стоимость не превышает max_cost\n\n    `   Возвращает:\n        ----------\n        result : list\n            список вида [(трансдукция, стоимость)], если return_cost=True\n            список трансдукций, если return_cost=False\n            список отсортирован в порядке возрастания стоимости трансдукции\n        \"\"\"\n        prefixes = [[] for i in range(len(word) + 1)]\n        prefixes[0].append(((), 0.0))\n        for pos in range(len(prefixes)):\n            # вставки\n            prefixes[pos] = self._perform_insertions(prefixes[pos], max_cost)\n            max_upperside_length = min(len(word) - pos, self.max_up_length)\n            for upperside_length in range(1, max_upperside_length + 1):\n                up = word[pos: pos + upperside_length]\n                for low, low_cost in self.operation_costs.get(up, dict()).items():\n                    for transduction, cost in prefixes[pos]:\n                        new_cost = cost + low_cost\n                        if new_cost <= max_cost:\n                            new_transduction = transduction +(up, low)\n                            prefixes[pos + upperside_length].append((new_transduction, new_cost))\n        answer = sorted(prefixes[-1], key=(lambda x: x[0]))\n        if return_cost:\n            return answer\n        else:\n            return [elem[0] for elem in answer]\n\n    def lower(self, word, max_cost, return_cost=True):\n        transductions = self.lower_transductions(word, max_cost, return_cost=True)\n        answer = dict()\n        for transduction, cost in transductions:\n            low = \"\".join(elem[1] for elem in transductions)\n            curr_cost = answer.get(low, None)\n            if curr_cost is None or cost < curr_cost:\n                answer[low] = cost\n        answer = sorted(answer.items(), key=(lambda x: x[1]))\n        if return_cost:\n            return answer\n        else:\n            return [elem[0] for elem in answer]\n\n    def upper(self, word, max_cost, return_cost=True):\n        inversed_transducer = self.inverse()\n        return inversed_transducer.lower(word, max_cost, return_cost)\n\n    def upper_transductions(self, word, max_cost, return_cost=True):\n        inversed_transducer = self.inverse()\n        return inversed_transducer.lower_transductions(word, max_cost, return_cost)\n\n    def _fill_levenshtein_table(self, first, second, update_func, add_pred, clear_pred,\n                               threshold=None):\n        \"\"\"\n        Функция, динамически заполняющая таблицу costs стоимости трансдукций,\n        costs[i][j] --- минимальная стоимость трансдукции,\n        переводящей first[:i] в second[:j]\n\n        Аргументы:\n        ----------\n        first, second : string\n            Верхний и нижний элементы трансдукции\n        update_func : callable, float*float -> bool\n            update_func(x, y) возвращает новое значение в ячейке таблицы costs,\n            если старое значение --- y, а потенциально новое значение --- x\n            везде update_func = min\n        add_pred : callable : float*float -> bool\n            add_pred(x, y) возвращает, производится ли добавление\n            нового элемента p стоимости x в ячейку backtraces[i][j]\n            в зависимости от значения costs[i][j]=y и текущей стоимости x\n        clear_pred : callable : float*float -> bool\n            clear_pred(x, y) возвращает, производится ли очистка\n            ячейки backtraces[i][j] в зависимости от значения costs[i][j]=y\n            и текущей стоимости x элемента p, добавляемого в эту ячейку\n\n        Возвращает:\n        -----------\n        costs : array, dtype=float, shape=(len(first)+1, len(second)+1)\n            массив, в ячейке с индексами i, j которого хранится\n            минимальная стоимость трансдукции, переводящей first[:i] в second[:j]\n        backtraces : array, dtype=list, shape=(len(first)+1, len(second)+1)\n            массив, в ячейке с индексами i, j которого хранятся\n            обратные ссылки на предыдущую ячейку в оптимальной трансдукции,\n            приводящей в ячейку backtraces[i][j]\n        \"\"\"\n        m, n = len(first), len(second)\n        # если threshold=None, то в качестве порога берётся удвоенная стоимость\n        # трансдукции, отображающей символы на одинаковых позициях друг в друга\n        if threshold is None:\n            threshold = 0.0\n            for a, b in zip(first, second):\n                threshold += self.get_operation_cost(a, b)\n            if m > n:\n                for a in first[n: ]:\n                    threshold += self.get_operation_cost(a, '')\n            elif m < n:\n                for b in second[m: ]:\n                    threshold += self.get_operation_cost('', b)\n            threshold *= 2\n        # инициализация возвращаемых массивов\n        costs = np.zeros(shape=(m + 1, n + 1), dtype=np.float64)\n        costs[:] = np.inf\n        backtraces = [None] * (m + 1)\n        for i in range(m + 1):\n            backtraces[i] = [[] for j in range(n + 1)]\n        costs[0][0] = 0.0\n        for i in range(m + 1):\n            for i_right in range(i, min(i + self.max_up_length, m) + 1):\n                up = first[i: i_right]\n                max_low_length = self.max_low_lengths_by_up.get(up, -1)\n                if max_low_length == -1: # no up key in transduction\n                    continue\n                up_costs = self.operation_costs[up]\n                for j in range(n + 1):\n                    if costs[i][j] > threshold:\n                        continue\n                    if len(backtraces[i][j]) == 0 and i + j > 0:\n                        continue # не нашлось обратных ссылок\n                    for j_right in range((j if i_right > i else j + 1),\n                                         min(j + max_low_length, n) + 1):\n                        low = second[j: j_right]\n                        curr_cost = up_costs.get(low, np.inf)\n                        old_cost = costs[i_right][j_right]\n                        new_cost = costs[i][j] + curr_cost\n                        if new_cost > threshold:\n                            continue\n                        if add_pred(new_cost, old_cost):\n                            if clear_pred(new_cost, old_cost):\n                                backtraces[i_right][j_right] = []\n                            costs[i_right][j_right] = update_func(new_cost, old_cost)\n                            backtraces[i_right][j_right].append((i, j))\n        return costs, backtraces\n\n    def _make_reversed_operation_costs(self):\n        \"\"\"\n        Заполняет массив _reversed_operation_costs\n        на основе имеющегося массива operation_costs\n        \"\"\"\n        _reversed_operation_costs = dict()\n        for up, costs in self.operation_costs.items():\n            for low, cost in costs.items():\n                if low not in _reversed_operation_costs:\n                    _reversed_operation_costs[low] = dict()\n                _reversed_operation_costs[low][up] = cost\n        self._reversed_operation_costs = _reversed_operation_costs\n\n    def _make_maximal_key_lengths(self):\n        \"\"\"\n        Вычисляет максимальную длину элемента low\n        в элементарной трансдукции (up, low) для каждого up\n        и максимальную длину элемента up\n        в элементарной трансдукции (up, low) для каждого low\n        \"\"\"\n        self.max_up_length =\\\n            (max(len(up) for up in self.operation_costs)\n             if len(self.operation_costs) > 0 else -1)\n        self.max_low_length =\\\n            (max(len(low) for low in self._reversed_operation_costs)\n             if len(self._reversed_operation_costs) > 0 else -1)\n        self.max_low_lengths_by_up, self.max_up_lengths_by_low = dict(), dict()\n        for up, costs in self.operation_costs.items():\n            self.max_low_lengths_by_up[up] =\\\n                max(len(low) for low in costs) if len(costs) > 0 else -1\n        for low, costs in self._reversed_operation_costs.items():\n            self.max_up_lengths_by_low[low] =\\\n                max(len(up) for up in costs) if len(costs) > 0 else -1\n\n    def _backtraces_to_transductions(self, first, second, backtraces, threshold, return_cost=False):\n        \"\"\"\n        Восстанавливает трансдукции по таблице обратных ссылок\n\n        Аргументы:\n        ----------\n        first, second : string\n            верхние и нижние элементы трансдукции\n        backtraces : array-like, dtype=list, shape=(len(first)+1, len(second)+1)\n            таблица обратных ссылок\n        threshold : float\n            порог для отсева трансдукций,\n            возвращаются только трансдукции стоимостью <= threshold\n        return_cost : bool (optional, default=False)\n            если True, то вместе с трансдукциями возвращается их стоимость\n\n        Возвращает:\n        -----------\n        result : list\n            список вида [(трансдукция, стоимость)], если return_cost=True\n            и вида [трансдукция], если return_cost=False,\n            содержащий все трансдукции, переводящие first в second,\n            чья стоимость не превышает threshold\n        \"\"\"\n        m, n = len(first), len(second)\n        agenda = [None] * (m + 1)\n        for i in range(m + 1):\n            agenda[i] = [[] for j in range(n+1)]\n        agenda[m][n] = [((), 0.0)]\n        for i_right in range(m, -1, -1):\n            for j_right in range(n, -1, -1):\n                current_agenda = agenda[i_right][j_right]\n                if len(current_agenda) == 0:\n                    continue\n                for (i, j) in backtraces[i_right][j_right]:\n                    up, low = first[i:i_right], second[j:j_right]\n                    add_cost = self.operation_costs[up][low]\n                    for elem, cost in current_agenda:\n                        new_cost = cost + add_cost\n                        if new_cost <= threshold: # удаление трансдукций большой стоимости\n                            agenda[i][j].append((((up, low),) + elem, new_cost))\n        if return_cost:\n            return agenda[0][0]\n        else:\n            return [elem[0] for elem in agenda[0][0]]\n\n    def _perform_insertions(self, initial, max_cost):\n        \"\"\"\n        возвращает все трансдукции стоимости <= max_cost,\n        которые можно получить из элементов initial\n\n        Аргументы:\n        ----------\n        initial : list of tuples\n            список исходных трансдукций вида [(трансдукция, стоимость)]\n        max_cost : float\n            максимальная стоимость трансдукции\n\n        Возвращает:\n        -----------\n        final : list of tuples\n            финальный список трансдукций вида [(трансдукция, стоимость)]\n        \"\"\"\n        queue = list(initial)\n        final = initial\n        while len(queue) > 0:\n            transduction, cost = queue[0]\n            queue = queue[1:]\n            for string, string_cost in self.operation_costs[\"\"].items():\n                new_cost = cost + string_cost\n                if new_cost <= max_cost:\n                    new_transduction = transduction + (\"\", string)\n                    final.append((new_transduction, new_cost))\n                    queue.append((new_transduction, new_cost))\n        return final\n\n    def _make_default_operation_costs(self, allow_spaces=False):\n        \"\"\"\n        sets 1.0 cost for every replacement, insertion, deletion and transposition\n        \"\"\"\n        self.operation_costs = dict()\n        self.operation_costs[\"\"] = {c: 1.0 for c in list(self.alphabet) + [' ']}\n        for a in self.alphabet:\n            current_costs = {c: 1.0 for c in self.alphabet}\n            current_costs[a] = 0.0\n            current_costs[\"\"] = 1.0\n            if allow_spaces:\n                current_costs[\" \"] = 1.0\n            self.operation_costs[a] = current_costs\n        # транспозиции\n        for a, b in itertools.permutations(self.alphabet, 2):\n            self.operation_costs[a + b] = {b + a: 1.0}\n        # пробелы\n        if allow_spaces:\n            self.operation_costs[\" \"] = {c: 1.0 for c in self.alphabet}\n            self.operation_costs[\" \"][\"\"] = 1.0\n", "meta": {"hexsha": "eaa5b8fa0d6558d0d4948141a2e57f0230557df2", "size": 28634, "ext": "py", "lang": "Python", "max_stars_repo_path": "deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py", "max_stars_repo_name": "alexeyyakimovich/DeepPavlov", "max_stars_repo_head_hexsha": "a95149294bc7fa30baaa15c629adad4c1cba264e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-04-16T04:25:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-07T23:04:43.000Z", "max_issues_repo_path": "deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py", "max_issues_repo_name": "alexeyyakimovich/DeepPavlov", "max_issues_repo_head_hexsha": "a95149294bc7fa30baaa15c629adad4c1cba264e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-01-28T22:14:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T00:10:17.000Z", "max_forks_repo_path": "deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py", "max_forks_repo_name": "alexeyyakimovich/DeepPavlov", "max_forks_repo_head_hexsha": "a95149294bc7fa30baaa15c629adad4c1cba264e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-08T14:41:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T14:41:28.000Z", "avg_line_length": 42.4207407407, "max_line_length": 100, "alphanum_fraction": 0.5761681917, "include": true, "reason": "import numpy", "num_tokens": 7290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.1725209760795531}}
{"text": "from typing import Union\nimport torch\nimport numpy as np\nfrom dqc.utils.datastruct import ZType\n\nperiodic_table_atomz = {\n    \"H\": 1,\n    \"He\": 2,\n    \"Li\": 3,\n    \"Be\": 4,\n    \"B\": 5,\n    \"C\": 6,\n    \"N\": 7,\n    \"O\": 8,\n    \"F\": 9,\n    \"Ne\": 10,\n    \"Na\": 11,\n    \"Mg\": 12,\n    \"Al\": 13,\n    \"Si\": 14,\n    \"P\": 15,\n    \"S\": 16,\n    \"Cl\": 17,\n    \"Ar\": 18,\n    \"K\": 19,\n    \"Ca\": 20,\n    \"Sc\": 21,\n    \"Ti\": 22,\n    \"V\": 23,\n    \"Cr\": 24,\n    \"Mn\": 25,\n    \"Fe\": 26,\n    \"Co\": 27,\n    \"Ni\": 28,\n    \"Cu\": 29,\n    \"Zn\": 30,\n    \"Ga\": 31,\n    \"Ge\": 32,\n    \"As\": 33,\n    \"Se\": 34,\n    \"Br\": 35,\n    \"Kr\": 36,\n    \"Rb\": 37,\n    \"Sr\": 38,\n    \"Y\": 39,\n    \"Zr\": 40,\n    \"Nb\": 41,\n    \"Mo\": 42,\n    \"Tc\": 43,\n    \"Ru\": 44,\n    \"Rh\": 45,\n    \"Pd\": 46,\n    \"Ag\": 47,\n    \"Cd\": 48,\n    \"In\": 49,\n    \"Sn\": 50,\n    \"Sb\": 51,\n    \"Te\": 52,\n    \"I\": 53,\n    \"Xe\": 54,\n}\n\natom_masses = {  # isotope-averaged atom masses in a.m.u.\n    # from https://www.angelo.edu/faculty/kboudrea/periodic/structure_mass.htm\n    1: 1.00797,\n    2: 4.00260,\n    3: 6.941,\n    4: 9.01218,\n    5: 10.81,\n    6: 12.011,\n    7: 14.0067,\n    8: 15.9994,\n    9: 18.998403,\n    10: 20.179,\n    11: 22.98977,\n    12: 24.305,\n    13: 26.98154,\n    14: 28.0855,\n    15: 30.97376,\n    16: 32.06,\n    17: 35.453,\n    18: 39.948,\n    19: 39.0983,\n    20: 40.08,\n    21: 44.9559,\n    22: 47.90,\n    23: 50.9415,\n    24: 51.996,\n    25: 54.9380,\n    26: 55.847,\n    27: 58.9332,\n    28: 58.70,\n    29: 63.546,\n    30: 65.38,\n    31: 69.72,\n    32: 72.59,\n    33: 74.9216,\n    34: 78.96,\n    35: 79.904,\n    36: 83.80,\n    37: 85.4678,\n    38: 87.62,\n    39: 88.9059,\n    40: 91.22,\n    41: 92.9064,\n    42: 95.94,\n    43: 98.,\n    44: 101.07,\n    45: 102.9055,\n    46: 106.4,\n    47: 107.868,\n    48: 112.41,\n    49: 114.82,\n    50: 118.69,\n    51: 121.75,\n    53: 126.9045,\n    52: 127.60,\n    54: 131.30,\n}\n\n# JCP 41, 3199 (1964); DOI:10.1063/1.1725697\n# taken from PySCF:\n# https://github.com/pyscf/pyscf/blob/45582e915e91890722fcae2bc30fb04867d5c95f/pyscf/data/radii.py#L23\n# I don't know why H has 0.35 while in the reference it is 0.\n# They are in angstrom, so we need to convert it to Bohr\natom_bragg_radii = list(np.array([\n    2.00,                                                        # Ghost atom\n    0.35,                                     1.40,              # 1s\n    1.45, 1.05, 0.85, 0.70, 0.65, 0.60, 0.50, 1.50,              # 2s2p\n    1.80, 1.50, 1.25, 1.10, 1.00, 1.00, 1.00, 1.80,              # 3s3p\n    2.20, 1.80,                                                  # 4s\n    1.60, 1.40, 1.35, 1.40, 1.40, 1.40, 1.35, 1.35, 1.35, 1.35,  # 3d\n                1.30, 1.25, 1.15, 1.15, 1.15, 1.90,              # 4p\n    2.35, 2.00,                                                  # 5s\n    1.80, 1.55, 1.45, 1.45, 1.35, 1.30, 1.35, 1.40, 1.60, 1.55,  # 4d\n                1.55, 1.45, 1.45, 1.40, 1.40, 2.10,              # 5p\n    2.60, 2.15,                                                  # 6s\n    1.95, 1.85, 1.85, 1.85, 1.85, 1.85, 1.85,                    # La, Ce-Eu\n    1.80, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75,              # Gd, Tb-Lu\n          1.55, 1.45, 1.35, 1.35, 1.30, 1.35, 1.35, 1.35, 1.50,  # 5d\n                1.90, 1.80, 1.60, 1.90, 1.45, 2.10,              # 6p\n    1.80, 2.15,                                                  # 7s\n    1.95, 1.80, 1.80, 1.75, 1.75, 1.75, 1.75,\n    1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75,\n    1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75,\n                1.75, 1.75, 1.75, 1.75, 1.75, 1.75,\n    1.75, 1.75,\n    1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75]) / 0.52917721092)\n\natom_expected_radii = [1.0,  # Ghost atom\n    1.0,  # 1\n    0.927272,  # 2\n    3.873661,  # 3\n    2.849396,  # 4\n    2.204757,  # 5\n    1.714495,  # 6\n    1.409631,  # 7\n    1.232198,  # 8\n    1.084786,  # 9\n    0.965273,  # 10\n    4.208762,  # 11\n    3.252938,  # 12\n    3.433889,  # 13\n    2.752216,  # 14\n    2.322712,  # 15\n    2.060717,  # 16\n    1.842024,  # 17\n    1.662954,  # 18\n    5.243652,  # 19\n    4.218469,  # 20\n    3.959716,  # 21\n    3.778855,  # 22\n    3.626288,  # 23\n    3.675012,  # 24\n    3.381917,  # 25\n    3.258487,  # 26\n    3.153572,  # 27\n    3.059109,  # 28\n    3.330979,  # 29\n    2.897648,  # 30\n    3.424103,  # 31\n    2.866859,  # 32\n    2.512233,  # 33\n    2.299617,  # 34\n    2.111601,  # 35\n    1.951590,  # 36\n    5.631401,  # 37\n    4.632850,  # 38\n    4.299870,  # 39\n    4.091705,  # 40\n    3.985219,  # 41\n    3.841740,  # 42\n    3.684647,  # 43\n    3.735235,  # 44\n    3.702057,  # 45\n    1.533028,  # 46\n    3.655961,  # 47\n    3.237216,  # 48\n    3.777242,  # 49\n    3.248093,  # 50\n    2.901067,  # 51\n    2.691328,  # 52\n    2.501704,  # 53\n    2.337950]  # 54\n\ndef get_atomz(elmt: Union[str, ZType]) -> ZType:\n    # returns the atomic number from the given element\n    if isinstance(elmt, str):\n        return periodic_table_atomz[elmt]\n    elif isinstance(elmt, torch.Tensor):\n        assert elmt.numel() == 1\n        return elmt\n    else:  # float or int\n        return elmt\n\ndef get_atom_mass(atomz: int) -> float:\n    # returns the atomic mass in atomic unit\n    return atom_masses[atomz] * 1822.888486209\n\ndef get_period(atz: int) -> int:\n    # get the period of the given atom z\n    if atz <= 2:\n        return 1\n    elif atz <= 10:\n        return 2\n    elif atz <= 18:\n        return 3\n    elif atz <= 36:\n        return 4\n    elif atz <= 54:\n        return 5\n    elif atz <= 86:\n        return 6\n    elif atz <= 118:\n        return 7\n    else:\n        raise RuntimeError(\"Unimplemented atomz: %d\" % atz)\n", "meta": {"hexsha": "83da1d37223f86f1cfbdd944616b4eb6acb197f2", "size": 5601, "ext": "py", "lang": "Python", "max_stars_repo_path": "dqc/utils/periodictable.py", "max_stars_repo_name": "Jaikinator/dqc", "max_stars_repo_head_hexsha": "47c964c7d1323a35f4f69521d40476c41843810e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2021-05-31T17:01:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T19:20:35.000Z", "max_issues_repo_path": "dqc/utils/periodictable.py", "max_issues_repo_name": "Jaikinator/dqc", "max_issues_repo_head_hexsha": "47c964c7d1323a35f4f69521d40476c41843810e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-09-01T13:39:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T16:45:39.000Z", "max_forks_repo_path": "dqc/utils/periodictable.py", "max_forks_repo_name": "Jaikinator/dqc", "max_forks_repo_head_hexsha": "47c964c7d1323a35f4f69521d40476c41843810e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-07-16T09:08:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T01:13:54.000Z", "avg_line_length": 23.5336134454, "max_line_length": 102, "alphanum_fraction": 0.4425995358, "include": true, "reason": "import numpy", "num_tokens": 2805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.1725209760795531}}
{"text": "# This file is part of QuTiP: Quantum Toolbox in Python.\n#\n#    Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.\n#    All rights reserved.\n#\n#    Redistribution and use in source and binary forms, with or without\n#    modification, are permitted provided that the following conditions are\n#    met:\n#\n#    1. Redistributions of source code must retain the above copyright notice,\n#       this list of conditions and the following disclaimer.\n#\n#    2. Redistributions in binary form must reproduce the above copyright\n#       notice, this list of conditions and the following disclaimer in the\n#       documentation and/or other materials provided with the distribution.\n#\n#    3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names\n#       of its contributors may be used to endorse or promote products derived\n#       from this software without specific prior written permission.\n#\n#    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n#    \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n#    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n#    PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n#    HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n#    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n#    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n#    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n#    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n#    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n#    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n###############################################################################\nimport warnings\n\nimport numpy as np\n\nfrom qutip.operators import tensor, identity, destroy, sigmax, sigmaz\nfrom qutip.states import basis\nfrom qutip.qip.circuit import QubitCircuit, Gate\nfrom qutip.qip.device.processor import Processor\nfrom qutip.qip.device.modelprocessor import ModelProcessor, GateDecomposer\nfrom qutip.qobj import Qobj\nfrom qutip.qobjevo import QobjEvo\n\n\n__all__ = ['DispersivecQED', 'CQEDGateDecomposer']\n\n\nclass DispersivecQED(ModelProcessor):\n    \"\"\"\n    The processor based on the physical implementation of\n    a dispersive cavity QED system.\n    The available Hamiltonian of the system is predefined.\n    For a given pulse amplitude matrix, the processor can\n    calculate the state evolution under the given control pulse,\n    either analytically or numerically.\n\n    Parameters\n    ----------\n    N: int\n        The number of qubits in the system.\n\n    correct_global_phase: float, optional\n        Save the global phase, the analytical solution\n        will track the global phase.\n        It has no effect on the numerical solution.\n\n    num_levels: int, optional\n        The number of energy levels in the resonator.\n\n    deltamax: int or list, optional\n        The sigma-x paraicient for each of the qubits in the system.\n\n    epsmax: int or list, optional\n        The sigma-z paraicient for each of the qubits in the system.\n\n    w0: int, optional\n        The base frequency of the resonator.\n\n    eps: int or list, optional\n        The epsilon for each of the qubits in the system.\n\n    delta: int or list, optional\n        The epsilon for each of the qubits in the system.\n\n    g: int or list, optional\n        The interaction strength for each of the qubit with the resonator.\n\n    t1: list or float\n        Characterize the decoherence of amplitude damping for\n        each qubit. A list of size ``N`` or a float for all qubits.\n\n    t2: list of float\n        Characterize the decoherence of dephasing for\n        each qubit. A list of size ``N`` or a float for all qubits.\n\n    Attributes\n    ----------\n    N: int\n        The number of component systems.\n\n    ctrls: list\n        A list of the control Hamiltonians driving the evolution.\n\n    tlist: array_like\n        A NumPy array specifies the time of each coefficient.\n\n    coeffs: array_like\n        A 2d NumPy array of the shape, the length is dependent on the\n        spline type\n\n    t1: list\n        Characterize the decoherence of amplitude damping for\n        each qubit.\n\n    t2: list\n        Characterize the decoherence of dephasing for\n        each qubit.\n\n    noise: :class:`qutip.qip.Noise`, optional\n        A list of noise objects. They will be processed when creating the\n        noisy :class:`qutip.QobjEvo` from the processor or run the simulation.\n\n    dims: list\n        The dimension of each component system.\n        Default value is a\n        qubit system of ``dim=[2,2,2,...,2]``\n\n    spline_kind: str\n        Type of the coefficient interpolation.\n        Note that they have different requirement for the length of ``coeffs``.\n\n        -\"step_func\":\n        The coefficient will be treated as a step function.\n        E.g. ``tlist=[0,1,2]`` and ``coeffs=[3,2]``, means that the coefficient\n        is 3 in t=[0,1) and 2 in t=[2,3). It requires\n        ``coeffs.shape[1]=len(tlist)-1`` or ``coeffs.shape[1]=len(tlist)``, but\n        in the second case the last element has no effect.\n\n        -\"cubic\": Use cubic interpolation for the coefficient. It requires\n        ``coeffs.shape[1]=len(tlist)``\n\n    sx_ops: list\n        A list of sigmax Hamiltonians for each qubit.\n\n    sz_ops: list\n        A list of sigmaz Hamiltonians for each qubit.\n\n    cavityqubit_ops: list\n        A list of interacting Hamiltonians between cavity and each qubit.\n\n    sx_u: array_like\n        Pulse matrix for sigmax Hamiltonians.\n\n    sz_u: array_like\n        Pulse matrix for sigmaz Hamiltonians.\n\n    g_u: array_like\n        Pulse matrix for interacting Hamiltonians\n        between cavity and each qubit.\n\n    wq: list of float\n        The frequency of the qubits calculated from\n        eps and delta for each qubit.\n\n    Delta: list of float\n        The detuning with repect to w0 calculated\n        from wq and w0 for each qubit.\n    \"\"\"\n\n    def __init__(self, N, correct_global_phase=True,\n                 num_levels=10, deltamax=1.0,\n                 epsmax=9.5, w0=10., wq=None, eps=9.5,\n                 delta=0.0, g=0.01, t1=None, t2=None):\n        super(DispersivecQED, self).__init__(\n            N, correct_global_phase=correct_global_phase,\n            t1=t1, t2=t2)\n        self.correct_global_phase = correct_global_phase\n        self.spline_kind = \"step_func\"\n        self.num_levels = num_levels\n        self._paras = {}\n        self.set_up_params(\n            N=N, num_levels=num_levels, deltamax=deltamax,\n            epsmax=epsmax, w0=w0, wq=wq, eps=eps,\n            delta=delta, g=g)\n        self.set_up_ops(N)\n        self.dims = [num_levels] + [2] * N\n\n    def set_up_ops(self, N):\n        \"\"\"\n        Generate the Hamiltonians for the spinchain model and save them in the\n        attribute `ctrls`.\n\n        Parameters\n        ----------\n        N: int\n            The number of qubits in the system.\n        \"\"\"\n        # single qubit terms\n        self.a = tensor([destroy(self.num_levels)] +\n                        [identity(2) for n in range(N)])\n        self.ctrls.append(self.a.dag() * self.a)\n        self.ctrls += [tensor([identity(self.num_levels)] +\n                              [sigmax() if m == n else identity(2)\n                               for n in range(N)])\n                       for m in range(N)]\n        self.ctrls += [tensor([identity(self.num_levels)] +\n                              [sigmaz() if m == n else identity(2)\n                               for n in range(N)])\n                       for m in range(N)]\n        # interaction terms\n        for n in range(N):\n            sm = tensor([identity(self.num_levels)] +\n                        [destroy(2) if m == n else identity(2)\n                         for m in range(N)])\n            self.ctrls.append(self.a.dag() * sm + self.a * sm.dag())\n\n        self.psi_proj = tensor([basis(self.num_levels, 0)] +\n                               [identity(2) for n in range(N)])\n\n    def set_up_params(\n            self, N, num_levels, deltamax,\n            epsmax, w0, wq, eps, delta, g):\n        \"\"\"\n        Save the parameters in the attribute `params` and check the validity.\n\n        Parameters\n        ----------\n        N: int\n            The number of qubits in the system.\n\n        num_levels: int\n            The number of energy levels in the resonator.\n\n        deltamax: list\n            The sigma-x paraicient for each of the qubits in the system.\n\n        epsmax: list\n            The sigma-z paraicient for each of the qubits in the system.\n\n        wo: int\n            The base frequency of the resonator.\n\n        wq: list\n            The frequency of the qubits.\n\n        eps: list\n            The epsilon for each of the qubits in the system.\n\n        delta: list\n            The delta for each of the qubits in the system.\n\n        g: list\n            The interaction strength for each of the qubit with the resonator.\n\n        Notes\n        -----\n        All parameters will be multiplied by 2*pi for simplicity\n        \"\"\"\n        sx_para = super(DispersivecQED, self)._para_list(deltamax, N)\n        self._paras[\"sx\"] = sx_para\n        sz_para = super(DispersivecQED, self)._para_list(epsmax, N)\n        self._paras[\"sz\"] = sz_para\n        w0 = w0 * 2 * np.pi\n        self._paras[\"w0\"] = w0\n        eps = super(DispersivecQED, self)._para_list(eps, N)\n        self._paras[\"eps\"] = eps\n        delta = super(DispersivecQED, self)._para_list(delta, N)\n        self._paras[\"delta\"] = delta\n        g = super(DispersivecQED, self)._para_list(g, N)\n        self._paras[\"g\"] = g\n\n        # computed\n        self.wq = [np.sqrt(eps[i]**2 + delta[i]**2) for i in range(N)]\n        self.Delta = [self.wq[i] - w0 for i in range(N)]\n\n        # rwa/dispersive regime tests\n        if any([g[i] / (w0 - self.wq[i]) > 0.05 for i in range(N)]):\n            warnings.warn(\"Not in the dispersive regime\")\n\n        if any([(w0 - self.wq[i])/(w0 + self.wq[i]) > 0.05 for i in range(N)]):\n            warnings.warn(\n                \"The rotating-wave approximation might not be valid.\")\n\n    @property\n    def sx_ops(self):\n        return self.ctrls[1: self.N + 1]\n\n    @property\n    def sz_ops(self):\n        return self.ctrls[self.N + 1: 2*self.N + 1]\n\n    @property\n    def cavityqubit_ops(self):\n        return self.ctrls[2*self.N + 1: 3*self.N + 1]\n\n    @property\n    def sx_u(self):\n        return self.coeffs[1: self.N + 1]\n\n    @property\n    def sz_u(self):\n        return self.coeffs[self.N + 1: 2*self.N + 1]\n\n    @property\n    def g_u(self):\n        return self.coeffs[2*self.N + 1: 3*self.N + 1]\n\n    def get_ops_labels(self):\n        \"\"\"\n        Get the labels for each Hamiltonian.\n        \"\"\"\n        return ([r\"$a^\\dagger a$\"] +\n                [r\"$\\sigma_x^%d$\" % n for n in range(self.N)] +\n                [r\"$\\sigma_z^%d$\" % n for n in range(self.N)] +\n                [r\"$g_{%d}$\" % (n) for n in range(self.N)])\n\n    def optimize_circuit(self, qc):\n        \"\"\"\n        Take a quantum circuit/algorithm and convert it into the\n        optimal form/basis for the desired physical system.\n\n        Parameters\n        ----------\n        qc: :class:`qutip.QubitCircuit`\n            Takes the quantum circuit to be implemented.\n\n        Returns\n        -------\n        qc: :class:`qutip.QubitCircuit`\n            The circuit representation with elementary gates\n            that can be implemented in this model.\n        \"\"\"\n        self.qc0 = qc\n        self.qc1 = self.qc0.resolve_gates(\n            basis=[\"SQRTISWAP\", \"ISWAP\", \"RX\", \"RZ\"])\n        return self.qc1\n\n    def eliminate_auxillary_modes(self, U):\n        \"\"\"\n        Eliminate the auxillary modes like the cavity modes in cqed.\n        \"\"\"\n        return self.psi_proj.dag() * U * self.psi_proj\n\n    def load_circuit(self, qc):\n        \"\"\"\n        Decompose a :class:`qutip.QubitCircuit` in to the control\n        amplitude generating the corresponding evolution.\n\n        Parameters\n        ----------\n        qc: :class:`qutip.QubitCircuit`\n            Takes the quantum circuit to be implemented.\n\n        Returns\n        -------\n        tlist: array_like\n            A NumPy array specifies the time of each coefficient\n\n        coeffs: array_like\n            A 2d NumPy array of the shape (len(ctrls), len(tlist)). Each\n            row corresponds to the control pulse sequence for\n            one Hamiltonian.\n        \"\"\"\n        gates = self.optimize_circuit(qc).gates\n\n        dec = CQEDGateDecomposer(\n            self.N, self._paras, self.wq, self.Delta,\n            global_phase=0., num_ops=len(self.ctrls))\n        self.tlist, self.coeffs, self.global_phase = dec.decompose(gates)\n\n        # TODO The amplitude of the first control a.dag()*a\n        # was set to zero before I made this refactoring.\n        # It is probably due to the fact that\n        # it contributes only a constant (N) and can be neglected.\n        # but change the below line to np.ones leads to test error.\n        self.coeffs[0] = self._paras[\"w0\"] * np.zeros((self.sx_u.shape[1]))\n        return self.tlist, self.coeffs\n\n\nclass CQEDGateDecomposer(GateDecomposer):\n    \"\"\"\n    Decompose a :class:`qutip.QubitCircuit` into\n    the pulse sequence for the processor.\n\n    Parameters\n    ----------\n    N: int\n        The number of qubits in the system.\n\n    params: dict\n        A Python dictionary contains the name and the value of the parameters,\n        such as laser frequency, detuning etc.\n\n    wq: list of float\n        The frequency of the qubits calculated from\n        eps and delta for each qubit.\n\n    Delta: list of float\n        The detuning with repect to w0 calculated\n        from wq and w0 for each qubit.\n\n    global_phase: bool\n        Record of the global phase change and will be returned.\n\n    num_ops: int\n        Number of Hamiltonians in the processor.\n\n    Attributes\n    ----------\n    N: int\n        The number of the component systems.\n\n    params: dict\n        A Python dictionary contains the name and the value of the parameters,\n        such as laser frequency, detuning etc.\n\n    num_ops: int\n        Number of control Hamiltonians in the processor.\n\n    gate_decomps: dict\n        The Python dictionary in the form of {gate_name: decompose_function}.\n        It saves the decomposition scheme for each gate.\n    \"\"\"\n    def __init__(self, N, params, wq, Delta, global_phase, num_ops):\n        super(CQEDGateDecomposer, self).__init__(\n            N=N, params=params, num_ops=num_ops)\n        self.gate_decomps = {\"ISWAP\": self.iswap_dec,\n                             \"SQRTISWAP\": self.sqrtiswap_dec,\n                             \"RZ\": self.rz_dec,\n                             \"RX\": self.rx_dec,\n                             \"GLOBALPHASE\": self.globalphase_dec\n                             }\n        self._sx_ind = list(range(1, N + 1))\n        self._sz_ind = list(range(N + 1, 2*N + 1))\n        self._g_ind = list(range(2*N + 1, 3*N + 1))\n        self.wq = wq\n        self.Delta = Delta\n        self.global_phase = global_phase\n\n    def decompose(self, gates):\n        tlist, coeffs = super(CQEDGateDecomposer, self).decompose(gates)\n        return tlist, coeffs, self.global_phase\n\n    def rz_dec(self, gate):\n        \"\"\"\n        Decomposer for the RZ gate\n        \"\"\"\n        pulse = np.zeros(self.num_ops)\n        q_ind = gate.targets[0]\n        g = self.params[\"sz\"][q_ind]\n        pulse[self._sz_ind[q_ind]] = np.sign(gate.arg_value) * g\n        t = abs(gate.arg_value) / (2 * g)\n        self.dt_list.append(t)\n        self.coeff_list.append(pulse)\n\n    def rx_dec(self, gate):\n        \"\"\"\n        Decomposer for the RX gate\n        \"\"\"\n        pulse = np.zeros(self.num_ops)\n        q_ind = gate.targets[0]\n        g = self.params[\"sx\"][q_ind]\n        pulse[self._sx_ind[q_ind]] = np.sign(gate.arg_value) * g\n        t = abs(gate.arg_value) / (2 * g)\n        self.dt_list.append(t)\n        self.coeff_list.append(pulse)\n\n    def sqrtiswap_dec(self, gate):\n        \"\"\"\n        Decomposer for the SQRTISWAP gate\n\n        Notes\n        -----\n        This version of sqrtiswap_dec has very low fidelity, please use\n        iswap\n        \"\"\"\n        # FIXME This decomposition has poor behaviour\n        pulse = np.zeros(self.num_ops)\n        q1, q2 = gate.targets\n        pulse[self._sz_ind[q1]] = self.wq[q1] - self.params[\"w0\"]\n        pulse[self._sz_ind[q2]] = self.wq[q2] - self.params[\"w0\"]\n        pulse[self._g_ind[q1]] = self.params[\"g\"][q1]\n        pulse[self._g_ind[q2]] = self.params[\"g\"][q2]\n        J = self.params[\"g\"][q1] * self.params[\"g\"][q2] * (\n            1 / self.Delta[q1] + 1 / self.Delta[q2]) / 2\n        t = (4 * np.pi / abs(J)) / 8\n        self.dt_list.append(t)\n        self.coeff_list.append(pulse)\n\n        # corrections\n        gate1 = Gate(\"RZ\", [q1], None, arg_value=-np.pi/4)\n        self.rz_dec(gate1)\n        gate2 = Gate(\"RZ\", [q2], None, arg_value=-np.pi/4)\n        self.rz_dec(gate2)\n        gate3 = Gate(\"GLOBALPHASE\", None, None, arg_value=-np.pi/4)\n        self.globalphase_dec(gate3)\n\n    def iswap_dec(self, gate):\n        \"\"\"\n        Decomposer for the ISWAP gate\n        \"\"\"\n        pulse = np.zeros(self.num_ops)\n        q1, q2 = gate.targets\n        pulse[self._sz_ind[q1]] = self.wq[q1] - self.params[\"w0\"]\n        pulse[self._sz_ind[q2]] = self.wq[q2] - self.params[\"w0\"]\n        pulse[self._g_ind[q1]] = self.params[\"g\"][q1]\n        pulse[self._g_ind[q2]] = self.params[\"g\"][q2]\n        J = self.params[\"g\"][q1] * self.params[\"g\"][q2] * (\n            1 / self.Delta[q1] + 1 / self.Delta[q2]) / 2\n        t = (4 * np.pi / abs(J)) / 4\n        self.dt_list.append(t)\n        self.coeff_list.append(pulse)\n\n        # corrections\n        gate1 = Gate(\"RZ\", [q1], None, arg_value=-np.pi/2.)\n        self.rz_dec(gate1)\n        gate2 = Gate(\"RZ\", [q2], None, arg_value=-np.pi/2)\n        self.rz_dec(gate2)\n        gate3 = Gate(\"GLOBALPHASE\", None, None, arg_value=-np.pi/2)\n        self.globalphase_dec(gate3)\n\n    def globalphase_dec(self, gate):\n        \"\"\"\n        Decomposer for the GLOBALPHASE gate\n        \"\"\"\n        self.global_phase += gate.arg_value\n", "meta": {"hexsha": "4e6e3a868391cc2f8c3e3b614414badabcbb209a", "size": 18227, "ext": "py", "lang": "Python", "max_stars_repo_path": "qutip/qip/device/cqed.py", "max_stars_repo_name": "dweigand/qutip", "max_stars_repo_head_hexsha": "b57d5e4b4846880e894afa390c62f4d095c642e1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "qutip/qip/device/cqed.py", "max_issues_repo_name": "dweigand/qutip", "max_issues_repo_head_hexsha": "b57d5e4b4846880e894afa390c62f4d095c642e1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qutip/qip/device/cqed.py", "max_forks_repo_name": "dweigand/qutip", "max_forks_repo_head_hexsha": "b57d5e4b4846880e894afa390c62f4d095c642e1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5208333333, "max_line_length": 79, "alphanum_fraction": 0.5968617984, "include": true, "reason": "import numpy", "num_tokens": 4648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.17252097265832753}}
{"text": "from abc import ABC, abstractmethod\n\nfrom sklearn.base import BaseEstimator, RegressorMixin, MultiOutputMixin\nfrom sklearn.utils.validation import check_is_fitted\nfrom sklearn.model_selection import check_cv\n\nfrom ._solvers import RIDGE_SOLVERS\nfrom ._random_search import GROUP_RIDGE_SOLVERS\nfrom ._random_search import solve_ridge_cv_svd\n\nfrom ..validation import check_array\nfrom ..validation import _get_string_dtype\nfrom ..backend import get_backend\nfrom ..backend import force_cpu_backend\nfrom ..scoring import r2_score\nfrom ..scoring import r2_score_split\n\n\nclass _BaseRidge(ABC, MultiOutputMixin, RegressorMixin, BaseEstimator):\n    \"\"\"Base class for ridge estimators\"\"\"\n\n    @property\n    @classmethod\n    @abstractmethod\n    def ALL_SOLVERS(cls):\n        ...\n\n    def _call_solver(self, **direct_params):\n        if self.solver not in self.ALL_SOLVERS:\n            raise ValueError(\"Unknown solver=%r.\" % self.solver)\n\n        function = self.ALL_SOLVERS[self.solver]\n        solver_params = self.solver_params or {}\n\n        # check duplicated parameters\n        intersection = set(direct_params.keys()).intersection(\n            set(solver_params.keys()))\n        if intersection:\n            raise ValueError(\n                'Parameters %s should not be given in solver_params, since '\n                'they are either fixed or have a direct parameter in %s.' %\n                (intersection, self.__class__.__name__))\n\n        return function(**direct_params, **solver_params)\n\n    def _more_tags(self):\n        return {'requires_y': True}\n\n\nclass Ridge(_BaseRidge):\n    \"\"\"Ridge regression.\n\n    Solve the ridge regression::\n\n        b* = argmin_b ||X @ b - Y||^2 + alpha ||b||^2.\n\n    Parameters\n    ----------\n    alpha : float, or array of shape (n_targets, )\n        L2 regularization parameter.\n\n    fit_intercept : boolean\n        Whether to fit an intercept.\n        If False, X and Y must be zero-mean over samples.\n\n    solver : str\n        Algorithm used during the fit, in {\"svd\"}.\n\n    solver_params : dict or None\n        Additional parameters for the solver.\n        See more details in the docstring of the function:\n        ``Ridge.ALL_SOLVERS[solver]``\n\n    force_cpu : bool\n        If True, computations will be performed on CPU, ignoring the\n        current backend. If False, use the current backend.\n\n    Attributes\n    ----------\n    coef_ : array of shape (n_features) or (n_features, n_targets)\n        Ridge coefficients.\n\n    intercept_ : float or array of shape (n_targets, )\n        Intercept. Only present if fit_intercept is True.\n\n    n_features_in_ : int\n        Number of features used during the fit.\n\n    dtype_ : str\n        Dtype of input data.\n\n    Examples\n    --------\n    >>> from himalaya.ridge import Ridge\n    >>> import numpy as np\n    >>> n_samples, n_features, n_targets = 10, 5, 3\n    >>> X = np.random.randn(n_samples, n_features)\n    >>> Y = np.random.randn(n_samples, n_targets)\n    >>> model = Ridge()\n    >>> model.fit(X, Y)\n    Ridge()\n    \"\"\"\n    ALL_SOLVERS = RIDGE_SOLVERS\n\n    def __init__(self, alpha=1, fit_intercept=False, solver=\"svd\",\n                 solver_params=None, force_cpu=False):\n        self.alpha = alpha\n        self.fit_intercept = fit_intercept\n        self.solver = solver\n        self.solver_params = solver_params\n        self.force_cpu = force_cpu\n\n    @force_cpu_backend\n    def fit(self, X, y=None):\n        \"\"\"Fit the model.\n\n        Parameters\n        ----------\n        X : array of shape (n_samples, n_features)\n            Training data.\n\n        y : array of shape (n_samples,) or (n_samples, n_targets)\n            Target values.\n\n        Returns\n        -------\n        self : returns an instance of self.\n        \"\"\"\n        # backend = get_backend()\n        X = check_array(X, ndim=2)\n        self.dtype_ = _get_string_dtype(X)\n        y = check_array(y, dtype=self.dtype_, ndim=[1, 2])\n        if X.shape[0] != y.shape[0]:\n            raise ValueError(\"Inconsistent number of samples.\")\n\n        self.n_features_in_ = X.shape[1]\n\n        ravel = False\n        if y.ndim == 1:\n            y = y[:, None]\n            ravel = True\n\n        # ------------------ call the solver\n        tmp = self._call_solver(X=X, Y=y, alpha=self.alpha,\n                                fit_intercept=self.fit_intercept)\n        if self.fit_intercept:\n            self.coef_, self.intercept_ = tmp\n        else:\n            self.coef_ = tmp\n\n        if ravel:\n            self.coef_ = self.coef_[:, 0]\n            if self.fit_intercept:\n                self.intercept_ = self.intercept_[0]\n\n        return self\n\n    @force_cpu_backend\n    def predict(self, X):\n        \"\"\"Predict using the model.\n\n        Parameters\n        ----------\n        X : array of shape (n_samples_test, n_features)\n            Testing features.\n\n        Returns\n        -------\n        Y_hat : array of shape (n_samples,) or (n_samples, n_targets)\n            Returns predicted values.\n        \"\"\"\n        check_is_fitted(self)\n        backend = get_backend()\n        X = check_array(X, dtype=self.dtype_, ndim=2)\n        if X.shape[1] != self.n_features_in_:\n            raise ValueError(\n                'Different number of features in X than during fit.')\n\n        Y_hat = backend.to_cpu(X) @ backend.to_cpu(self.coef_)\n        if self.fit_intercept:\n            Y_hat += backend.to_cpu(self.intercept_)\n        return Y_hat\n\n    @force_cpu_backend\n    def score(self, X, y):\n        \"\"\"Return the coefficient of determination R^2 of the prediction.\n\n        Parameters\n        ----------\n        X : array of shape (n_samples_test, n_features)\n            Testing features.\n\n        y : array-like of shape (n_samples,) or (n_samples, n_targets)\n            True values for X.\n\n        Returns\n        -------\n        score : array of shape (n_targets, )\n            R^2 of self.predict(X) versus y.\n        \"\"\"\n        y_pred = self.predict(X)\n        y_true = check_array(y, dtype=self.dtype_, ndim=self.coef_.ndim)\n\n        if y_true.ndim == 1:\n            return r2_score(y_true[:, None], y_pred[:, None])[0]\n        else:\n            return r2_score(y_true, y_pred)\n\n\nclass RidgeCV(Ridge):\n    \"\"\"Ridge regression with efficient cross-validation over alpha.\n\n    Solve the ridge regression::\n\n        b* = argmin_b ||X @ b - Y||^2 + alpha ||b||^2,\n\n    with a grid-search over cross-validation to find the best alpha.\n\n    Parameters\n    ----------\n    alphas : array of shape (n_alphas, )\n        List of L2 regularization parameter to try.\n\n    fit_intercept : boolean\n        Whether to fit an intercept.\n        If False, X and Y must be zero-mean over samples.\n\n    solver : str\n        Algorithm used during the fit, \"svd\" only for now.\n\n    solver_params : dict or None\n        Additional parameters for the solver.\n        See more details in the docstring of the function:\n        ``RidgeCV.ALL_SOLVERS[solver]``\n\n    cv : int or scikit-learn splitter\n        Cross-validation splitter. If an int, KFold is used.\n\n    Y_in_cpu : bool\n        If True, keep the target values ``y`` in CPU memory (slower).\n\n    force_cpu : bool\n        If True, computations will be performed on CPU, ignoring the\n        current backend. If False, use the current backend.\n\n    Attributes\n    ----------\n    coef_ : array of shape (n_features) or (n_features, n_targets)\n        Ridge coefficients.\n\n    intercept_ : float or array of shape (n_targets, )\n        Intercept. Only returned when fit_intercept is True.\n\n    best_alphas_ : array of shape (n_targets, )\n        Selected best hyperparameter alphas.\n\n    cv_scores_ : array of shape (n_targets, )\n        Cross-validation scores averaged over splits, for the best alpha.\n\n    n_features_in_ : int\n        Number of features used during the fit.\n\n    Examples\n    --------\n    >>> from himalaya.ridge import RidgeCV\n    >>> import numpy as np\n    >>> n_samples, n_features, n_targets = 10, 5, 3\n    >>> X = np.random.randn(n_samples, n_features)\n    >>> Y = np.random.randn(n_samples, n_targets)\n    >>> clf = RidgeCV()\n    >>> clf.fit(X, Y)\n    RidgeCV()\n    \"\"\"\n    ALL_SOLVERS = dict(svd=solve_ridge_cv_svd)\n\n    def __init__(self, alphas=[0.1, 1], fit_intercept=False, solver=\"svd\",\n                 solver_params=None, cv=5, Y_in_cpu=False, force_cpu=False):\n        self.alphas = alphas\n        self.fit_intercept = fit_intercept\n        self.solver = solver\n        self.solver_params = solver_params\n        self.cv = cv\n        self.Y_in_cpu = Y_in_cpu\n        self.force_cpu = force_cpu\n\n    @force_cpu_backend\n    def fit(self, X, y=None):\n        \"\"\"Fit ridge regression model\n\n        Parameters\n        ----------\n        X : array of shape (n_samples, n_features).\n            Training data.\n\n        y : array of shape (n_samples,) or (n_samples, n_targets)\n            Target values.\n\n        Returns\n        -------\n        self : returns an instance of self.\n        \"\"\"\n        # backend = get_backend()\n        X = check_array(X, ndim=2)\n        self.dtype_ = _get_string_dtype(X)\n        device = \"cpu\" if self.Y_in_cpu else None\n        y = check_array(y, dtype=self.dtype_, ndim=[1, 2], device=device)\n        if X.shape[0] != y.shape[0]:\n            raise ValueError(\"Inconsistent number of samples.\")\n\n        alphas = check_array(self.alphas, dtype=self.dtype_, ndim=1)\n        self.n_features_in_ = X.shape[1]\n\n        ravel = False\n        if y.ndim == 1:\n            y = y[:, None]\n            ravel = True\n\n        cv = check_cv(self.cv)\n\n        # ------------------ call the solver\n        tmp = self._call_solver(X=X, Y=y, cv=cv, alphas=alphas,\n                                fit_intercept=self.fit_intercept,\n                                Y_in_cpu=self.Y_in_cpu)\n        if self.fit_intercept:\n            self.best_alphas_, self.coef_, self.cv_scores_ = tmp[:3]\n            self.intercept_, = tmp[3:]\n        else:\n            self.best_alphas_, self.coef_, self.cv_scores_ = tmp\n\n        self.cv_scores_ = self.cv_scores_[0]\n\n        if ravel:\n            self.coef_ = self.coef_[:, 0]\n            if self.fit_intercept:\n                self.intercept_ = self.intercept_[0]\n\n        return self\n\n\n###############################################################################\n###############################################################################\n###############################################################################\n###############################################################################\n\n\nclass GroupRidgeCV(_BaseRidge):\n    \"\"\"Group ridge regression with cross-validation.\n\n    Solve the group-regularized ridge regression::\n\n        b* = argmin_b ||Z @ b - Y||^2 + ||b||^2\n\n    where the feature space X_i is scaled by a group scaling ::\n\n        Z_i = exp(deltas[i] / 2) X_i\n\n    The solver optimizes the log group scalings ``deltas`` over\n    cross-validation, using random search (``solver=\"random_search\"``).\n\n    Parameters\n    ----------\n    groups : array of shape (n_features, ), \"input\", or None\n        Encoding of the group of each feature. If None, all features are\n        gathered in one group, and the problem is equivalent to RidgeCV.\n        If \"input\", the input features ``X`` should be a list of 2D arrays,\n        corresponding to each group.\n\n    solver : str\n        Algorithm used during the fit, only \"random_search\" for now.\n\n    solver_params : dict or None\n        Additional parameters for the solver.\n        See more details in the docstring of the function:\n        ``GroupRidgeCV.ALL_SOLVERS[solver]``\n\n    fit_intercept : boolean\n        Whether to fit an intercept.\n        If False, X and Y must be zero-mean over samples.\n\n    cv : int or scikit-learn splitter\n        Cross-validation splitter. If an int, KFold is used.\n\n    random_state : int, or None\n        Random generator seed. Use an int for deterministic search.\n\n    Y_in_cpu : bool\n        If True, keep the target values ``y`` in CPU memory (slower).\n\n    force_cpu : bool\n        If True, computations will be performed on CPU, ignoring the\n        current backend. If False, use the current backend.\n\n    Attributes\n    ----------\n    coef_ : array of shape (n_features) or (n_features, n_targets)\n        Ridge coefficients.\n\n    intercept_ : float or array of shape (n_targets, )\n        Intercept. Only returned when fit_intercept is True.\n\n    deltas_ : array of shape (n_groups, n_targets)\n        Log of the group scalings.\n\n    cv_scores_ : array of shape (n_iter, n_targets)\n        Cross-validation scores, averaged over splits.\n\n    n_features_in_ : int\n        Number of features used during the fit.\n\n    dtype_ : str\n        Dtype of input data.\n\n    best_alphas_ : array of shape (n_targets, )\n        Equal to ``1. / exp(self.deltas_).sum(0)``. For the \"random_search\"\n        solver, it corresponds to the best hyperparameter alphas, assuming that\n        each squared group scaling vector sums to one (in particular, it is the\n        case when ``solver_params['n_iter']`` is an integer).\n\n    Examples\n    --------\n    >>> from himalaya.ridge import GroupRidgeCV\n    >>> from himalaya.ridge import ColumnTransformerNoStack\n    >>> from sklearn.pipeline import make_pipeline\n\n    >>> # create a dataset\n    >>> import numpy as np\n    >>> n_samples, n_features, n_targets = 10, 5, 3\n    >>> X = np.random.randn(n_samples, n_features)\n    >>> Y = np.random.randn(n_samples, n_targets)\n\n    >>> # Separate the first three columns and the last two\n    >>> # columns, creating two groups of shape (n_samples, n_feature_i).\n    >>> from sklearn.preprocessing import StandardScaler\n    >>> ct = ColumnTransformerNoStack(\n    ...     [(\"group_1\", StandardScaler(), [0, 1, 2]),\n    ...      (\"group_2\", StandardScaler(), slice(3, 5))])\n\n    >>> # A model with automatic groups, as output by ColumnTransformerNoStack\n    >>> model = GroupRidgeCV(groups=\"input\")\n    >>> pipe = make_pipeline(ct, model)\n    >>> _ = pipe.fit(X, Y)\n    \"\"\"\n    ALL_SOLVERS = GROUP_RIDGE_SOLVERS\n\n    def __init__(self, groups=None, solver=\"random_search\", solver_params=None,\n                 fit_intercept=False, cv=5, random_state=None, Y_in_cpu=False,\n                 force_cpu=False):\n\n        self.groups = groups\n        self.solver = solver\n        self.solver_params = solver_params\n        self.fit_intercept = fit_intercept\n        self.cv = cv\n        self.random_state = random_state\n        self.Y_in_cpu = Y_in_cpu\n        self.force_cpu = force_cpu\n\n    @force_cpu_backend\n    def fit(self, X, y=None):\n        \"\"\"Fit the model.\n\n        Parameters\n        ----------\n        X : array of shape (n_samples, n_features), or list of length \\\n                (n_groups) with arrays of shape (n_samples, n_features)\n            Training data.\n            Must be a 2D array if ``groups`` is given.\n            Must be a list of 2D arrays if ``groups=\"input\"``.\n\n        y : array of shape (n_samples,) or (n_samples, n_targets)\n            Target values.\n\n        Returns\n        -------\n        self : returns an instance of self.\n        \"\"\"\n        backend = get_backend()\n\n        Xs = self._split_groups(X, check=True)\n        del X\n\n        self.n_features_in_ = sum(Xi.shape[1] for Xi in Xs)\n\n        self.dtype_ = _get_string_dtype(Xs[0])\n        device = \"cpu\" if self.Y_in_cpu else None\n        y = check_array(y, dtype=self.dtype_, ndim=[1, 2], device=device)\n\n        if any([Xi.shape[0] != y.shape[0] for Xi in Xs]):\n            raise ValueError(\"Inconsistent number of samples.\")\n\n        ravel = False\n        if y.ndim == 1:\n            y = y[:, None]\n            ravel = True\n\n        cv = check_cv(self.cv)\n\n        # ------------------ call the solver\n        tmp = self._call_solver(Xs=Xs, Y=y, cv=cv, return_weights=True,\n                                random_state=self.random_state,\n                                fit_intercept=self.fit_intercept,\n                                Y_in_cpu=self.Y_in_cpu)\n        if self.fit_intercept:\n            self.deltas_, self.coef_, self.cv_scores_ = tmp[:3]\n            self.intercept_, = tmp[3:]\n        else:\n            self.deltas_, self.coef_, self.cv_scores_ = tmp\n\n        if self.solver == \"random_search\":\n            self.best_alphas_ = 1. / backend.exp(self.deltas_).sum(0)\n        else:\n            self.best_alphas_ = None\n\n        if ravel:\n            self.coef_ = self.coef_[:, 0]\n            self.deltas_ = self.deltas_[:, 0]\n            if self.fit_intercept:\n                self.intercept_ = self.intercept_[0]\n\n        return self\n\n    @force_cpu_backend\n    def predict(self, X, split=False):\n        \"\"\"Predict using the model.\n\n        Parameters\n        ----------\n        X : array of shape (n_samples_test, n_features), or list of length \\\n                (n_groups) with arrays of shape (n_samples_test, n_features)\n            Training data.\n            Must be a 2D array if ``groups`` is given.\n            Must be a list of 2D arrays if ``groups=\"input\"``.\n\n        split : bool\n            If True, the prediction is split on each feature space, and this\n            method returns an array with one extra dimension (first dimension).\n            The sum over this extra dimension corresponds to split=False.\n\n        Returns\n        -------\n        Y_hat : array of shape (n_samples,) or (n_samples, n_targets)\n            Returns predicted values.\n            If parameter split is True, the array is of shape\n            (n_groups, n_samples,) or (n_groups, n_samples, n_targets).\n        \"\"\"\n        backend = get_backend()\n        check_is_fitted(self)\n\n        Xs = self._split_groups(X, dtype=self.dtype_, check=True)\n\n        n_features = sum(Xi.shape[1] for Xi in Xs)\n        if n_features != self.n_features_in_:\n            raise ValueError(\n                'Different number of features in X than during fit.')\n        if split:\n            if self.fit_intercept:\n                raise NotImplementedError(\n                    \"Splitting the predictions is not implemented with \"\n                    \"fit_intercept=True.\")\n\n            start = 0\n            Ys_hat = None\n            for ii, X_i in enumerate(Xs):\n                n_features_i = X_i.shape[1]\n                coef = self.coef_[start:start + n_features_i]\n                start += n_features_i\n                Y_hat = backend.to_cpu(X_i) @ backend.to_cpu(coef)\n                if Ys_hat is None:\n                    Ys_hat = backend.zeros_like(Y_hat,\n                                                shape=(len(Xs), *Y_hat.shape))\n                Ys_hat[ii] = Y_hat\n            return Ys_hat\n\n        else:\n            X = backend.to_cpu(backend.concatenate(Xs, 1))\n            del Xs\n\n            Y_hat = X @ backend.to_cpu(self.coef_)\n            if self.fit_intercept:\n                Y_hat += backend.to_cpu(self.intercept_)\n            return Y_hat\n\n    @force_cpu_backend\n    def score(self, X, y, split=False):\n        \"\"\"Return the coefficient of determination R^2 of the prediction.\n\n        Parameters\n        ----------\n        X : array of shape (n_samples_test, n_features), or list of length \\\n                (n_groups) with arrays of shape (n_samples_test, n_features)\n            Training data.\n            Must be a 2D array if ``groups`` is given.\n            Must be a list of 2D arrays if ``groups=\"input\"``.\n\n        y : array-like of shape (n_samples,) or (n_samples, n_targets)\n            True values for X.\n\n        split : bool\n            If True, the prediction is split on each kernel, and the R2 score\n            is decomposed over sub-predictions, adding an extra dimension\n            in the first axis. The sum over this extra dimension corresponds to\n            split=False.\n\n        Returns\n        -------\n        score : array of shape (n_targets, ) or (n_kernels, n_targets)\n            R^2 of self.predict(X) versus y.\n            If parameter split is True, the array is of shape\n            (n_kernels, n_targets).\n        \"\"\"\n        y_pred = self.predict(X, split=split)\n        y_true = check_array(y, dtype=self.dtype_, ndim=self.coef_.ndim)\n\n        score_func = r2_score_split if split else r2_score\n\n        if y_true.ndim == 1:\n            return score_func(y_true[:, None], y_pred[:, None])[0]\n        else:\n            return score_func(y_true, y_pred)\n\n    def _split_groups(self, X, check=True, **check_kwargs):\n        backend = get_backend()\n\n        # groups defined in X\n        if isinstance(self.groups, str) and self.groups == \"input\":\n            if check:\n                X = [check_array(Xi, ndim=2, **check_kwargs) for Xi in X]\n            return X\n\n        # groups defined in self.groups\n        if check:\n            X = check_array(X, ndim=2, **check_kwargs)\n        if self.groups is None:\n            groups = backend.zeros((X.shape[1]))\n        else:\n            groups = self.groups\n        groups = backend.asarray(groups)[:]\n        Xs = [X[:, groups == u] for u in backend.unique(groups) if u >= 0]\n        return Xs\n", "meta": {"hexsha": "e8364e76d41c9ee4f10b0c5d22e61df412d60577", "size": 20969, "ext": "py", "lang": "Python", "max_stars_repo_path": "himalaya/ridge/_sklearn_api.py", "max_stars_repo_name": "mvdoc/himalaya", "max_stars_repo_head_hexsha": "7e3866287b835e2cc0a5c9848331e19c14896309", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2021-09-14T14:55:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T22:32:56.000Z", "max_issues_repo_path": "himalaya/ridge/_sklearn_api.py", "max_issues_repo_name": "mvdoc/himalaya", "max_issues_repo_head_hexsha": "7e3866287b835e2cc0a5c9848331e19c14896309", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2021-11-11T03:55:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T20:20:37.000Z", "max_forks_repo_path": "himalaya/ridge/_sklearn_api.py", "max_forks_repo_name": "mvdoc/himalaya", "max_forks_repo_head_hexsha": "7e3866287b835e2cc0a5c9848331e19c14896309", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-09-13T19:10:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T17:56:42.000Z", "avg_line_length": 32.7640625, "max_line_length": 79, "alphanum_fraction": 0.5806666985, "include": true, "reason": "import numpy", "num_tokens": 4878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.1723190611967502}}
{"text": "\"\"\"\n    Implements PPO\n\n    PPO: https://arxiv.org/abs/1707.06347\n    Modified from policy Written by Patrick Coady (pat-coady.github.io) to implement\n    latest version of PPO with pessimistic ratio clipping\n\n    o Has an option to servo both the learning rate and the clip_param to keep KL \n      within  a specified range. This helps on some control tasks\n      (i.e., Mujoco Humanid-v2)\n \n    o Uses approximate KL \n\n    o Models distribution of actions as a Gaussian with variance not conditioned on state\n\n    o Has option to discretize sampled actions\n \n\"\"\"\nimport numpy as np\nimport tensorflow as tf\nfrom utils import Action_converter\nimport utils\nimport sklearn.utils \n\nclass Policy(object):\n    \"\"\" NN-based policy approximation \"\"\"\n    def __init__(self, obs_dim, act_dim, actions_per_dim=3, kl_targ=0.003,epochs=20,discretize=False,\n                 input_network_scale=10,output_network_scale=10,test_mode=False,shuffle=True,\n                 entropy_coeff=0.0,eta=0.0, servo_kl=False, beta=0.1, lr=None):\n        \"\"\"\n        Args:\n            obs_dim:                num observation dimensions (int)\n            act_dim:                num action dimensions (int)\n            actions_per_dim:        used when discretizing action space\n            kl_targ:                target KL divergence between pi_old and pi_new\n            epochs:                 number of epochs per update\n            discretize:             boolean, True discretizes action space\n            input_network_scale:    NN input layer is of dim <input_network_scale> * obs_dim\n            output_network_scale:   NN layer prior to output layer is of dim <input_network_scale> * act_dim\n            test_mode:              boolean, True removes all exploration noise\n            shuffle:                boolean, shuffles data each epoch                   \n            entropy_coeff:          adds a loss term that encourages exploration.  This almost always makes things\n                                    worse for control tasks\n            eta:                    KL hingle loss parameter\n            servo_kl:               boolean:  set to False to not servo beta to KL, which is original PPO implementation\n            beta:                   clipping parameter for pessimistic loss ratio\n \n        \"\"\"\n        print('PPO Policy 1')\n        self.servo_kl = servo_kl\n        self.input_network_scale = input_network_scale\n        self.output_network_scale = output_network_scale\n        self.test_mode = test_mode\n        self.entropy_coeff = entropy_coeff \n        self.discretize = discretize\n        self.shuffle = shuffle\n        self.actions_per_dim = actions_per_dim\n        self.kl_stat = None\n        self.entropy_stat = None\n        self.eta = eta  # multiplier for D_KL-kl_targ hinge-squared loss\n        self.kl_targ = kl_targ\n        self.epochs = epochs \n        self.lr = lr \n        self.lr_multiplier = 1.0  # dynamically adjust lr when D_KL out of control\n        self.obs_dim = obs_dim\n        self.act_dim = act_dim\n        self.max_beta = 0.5\n        self.min_beta = 0.01 \n        self.beta = beta\n        self._build_graph()\n        self._init_session()\n        self.action_converter = Action_converter(1,actions_per_dim)\n        print(self.input_network_scale)\n        print('Actor Test Mode: ',self.test_mode)\n        print('clip param: ',self.beta)\n\n    def _build_graph(self):\n        \"\"\" Build and initialize TensorFlow graph \"\"\"\n        self.g = tf.Graph()\n        with self.g.as_default():\n            self._placeholders()\n            self._policy_nn()\n            self._logprob()\n            self._kl_entropy()\n            self._sample()\n            self._loss_train_op()\n            self.init = tf.global_variables_initializer()\n\n    def _placeholders(self):\n        \"\"\" Input placeholders\"\"\"\n        # observations, actions and advantages:\n        self.obs_ph = tf.placeholder(tf.float32, (None, self.obs_dim), 'obs')\n        self.act_ph = tf.placeholder(tf.float32, (None, self.act_dim), 'act')\n        self.advantages_ph = tf.placeholder(tf.float32, (None,), 'advantages')\n        # strength of D_KL loss terms:\n        self.beta_ph = tf.placeholder(tf.float32, (), 'beta')\n        self.eta_ph = tf.placeholder(tf.float32, (), 'eta')\n        # learning rate:\n        self.lr_ph = tf.placeholder(tf.float32, (), 'eta')\n        # log_vars and means with pi_old (previous step's policy parameters):\n        self.old_logp_ph =  tf.placeholder(tf.float32, (None,), 'old_logp')\n\n        #self.old_log_vars_ph = tf.placeholder(tf.float32, (self.act_dim,), 'old_log_vars')\n        #self.old_means_ph = tf.placeholder(tf.float32, (None, self.act_dim), 'old_means')\n\n    def _policy_nn(self):\n        \"\"\" Neural net for policy approximation function\n\n        Policy parameterized by Gaussian means and variances. NN outputs mean\n         action based on observation. Trainable variables hold log-variances\n         for each action dimension (i.e. variances not determined by NN).\n        \"\"\"\n        # hidden layer sizes determined by obs_dim and act_dim (hid2 is geometric mean)\n        hid1_size = self.obs_dim * self.input_network_scale  # 10 empirically determined\n        hid3_size = self.act_dim * self.output_network_scale  # 10 empirically determined\n        hid2_size = int(np.sqrt(hid1_size * hid3_size))\n        # heuristic to set learning rate based on NN size (tuned on 'Hopper-v1')\n        if self.lr is None:\n            self.lr = 9e-4 / np.sqrt(hid2_size)  # 9e-4 empirically determined\n        # 3 hidden layers with tanh activations\n        out = tf.layers.dense(self.obs_ph, hid1_size, tf.tanh,\n                              kernel_initializer=tf.random_normal_initializer(\n                                  stddev=np.sqrt(1 / self.obs_dim)), name=\"h1\")\n        out = tf.layers.dense(out, hid2_size, tf.tanh,\n                              kernel_initializer=tf.random_normal_initializer(\n                                  stddev=np.sqrt(1 / hid1_size)), name=\"h2\")\n        out = tf.layers.dense(out, hid3_size, tf.tanh,\n                              kernel_initializer=tf.random_normal_initializer(\n                                  stddev=np.sqrt(1 / hid2_size)), name=\"h3\")\n        self.means = tf.layers.dense(out, self.act_dim,\n                                     kernel_initializer=tf.random_normal_initializer(\n                                         stddev=np.sqrt(1 / hid3_size)), name=\"means\")\n        # logvar_speed is used to 'fool' gradient descent into making faster updates\n        # to log-variances. heuristic sets logvar_speed based on network size.\n        logvar_speed = (10 * hid3_size) // 48\n        log_vars = tf.get_variable('logvars', (logvar_speed, self.act_dim), tf.float32,\n                                   tf.constant_initializer(0.0))\n        self.log_vars = tf.reduce_sum(log_vars, axis=0) - 1.0\n\n        print('Policy Params -- h1: {}, h2: {}, h3: {}, lr: {:.3g}, logvar_speed: {}'\n              .format(hid1_size, hid2_size, hid3_size, self.lr, logvar_speed))\n\n    def _policy_rnn(self):\n        \"\"\" Neural net for policy approximation function\n\n        Policy parameterized by Gaussian means and variances. NN outputs mean\n         action based on observation. Trainable variables hold log-variances\n         for each action dimension (i.e. variances not determined by NN).\n        \"\"\"\n        # hidden layer sizes determined by obs_dim and act_dim (hid2 is geometric mean)\n        hid1_size = self.obs_dim * self.input_network_scale  # 10 empirically determined\n        hid3_size = self.act_dim * self.output_network_scale  # 10 empirically determined\n        hid2_size = int(np.sqrt(hid1_size * hid3_size))\n        # heuristic to set learning rate based on NN size (tuned on 'Hopper-v1')\n        if self.lr is None:\n            self.lr = 9e-4 / np.sqrt(hid2_size)  # 9e-4 empirically determined\n        # 3 hidden layers with tanh activations\n        out1 = tf.layers.dense(self.obs_ph, hid1_size, tf.tanh,\n                              kernel_initializer=tf.random_normal_initializer(\n                                  stddev=np.sqrt(1 / self.obs_dim)), name=\"h1\")\n        out2 = tf.layers.dense(tf.concat(concat_dim=1,values=[out1,out3]), hid2_size, tf.tanh,\n                              kernel_initializer=tf.random_normal_initializer(\n                                  stddev=np.sqrt(1 / hid1_size)), name=\"h2\")\n        out3 = tf.layers.dense(out2, hid3_size, tf.tanh,\n                              kernel_initializer=tf.random_normal_initializer(\n                                  stddev=np.sqrt(1 / hid2_size)), name=\"h3\")\n        self.means = tf.layers.dense(out3, self.act_dim,\n                                     kernel_initializer=tf.random_normal_initializer(\n                                         stddev=np.sqrt(1 / hid3_size)), name=\"means\")\n        # logvar_speed is used to 'fool' gradient descent into making faster updates\n        # to log-variances. heuristic sets logvar_speed based on network size.\n        logvar_speed = (10 * hid3_size) // 48\n        log_vars = tf.get_variable('logvars', (logvar_speed, self.act_dim), tf.float32,\n                                   tf.constant_initializer(0.0))\n        self.log_vars = tf.reduce_sum(log_vars, axis=0) - 1.0\n\n        print('Policy Params -- h1: {}, h2: {}, h3: {}, lr: {:.3g}, logvar_speed: {}'\n              .format(hid1_size, hid2_size, hid3_size, self.lr, logvar_speed))\n\n    def _logprob(self):\n        \"\"\" Calculate log probabilities of a batch of observations & actions\n\n        Calculates log probabilities using previous step's model parameters and\n        new parameters being trained.\n        \"\"\"\n        logp = -0.5 * tf.reduce_sum(self.log_vars)\n        logp += -0.5 * tf.reduce_sum(tf.square(self.act_ph - self.means) /\n                                     tf.exp(self.log_vars), axis=1)\n        logp += -0.5 * np.log(2.0 * np.pi) * self.act_dim \n        self.logp = logp\n\n    def _kl_entropy(self):\n        \"\"\"\n        Add to Graph:\n            1. KL divergence between old and new distributions\n            2. Entropy of present policy given states and actions\n\n        https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Kullback.E2.80.93Leibler_divergence\n        https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Entropy\n        \"\"\"\n\n        self.kl = 0.5 * tf.reduce_mean(tf.square(self.logp - self.old_logp_ph))\n        \n        self.entropy = 0.5 * (self.act_dim * (np.log(2 * np.pi) + 1) +\n                              tf.reduce_sum(self.log_vars))\n\n    def _sample(self):\n        \"\"\" Sample from distribution, given observation \"\"\"\n        self.sampled_act = (self.means +\n                            tf.exp(self.log_vars / 2.0) *\n                            tf.random_normal(shape=(self.act_dim,)))\n\n        self.deterministic_act = (self.means)\n       \n \n\n    def _loss_train_op(self):\n        ratio = tf.exp(self.logp - self.old_logp_ph)\n        surr1 = self.advantages_ph * ratio\n        surr2 = self.advantages_ph * tf.clip_by_value(ratio, 1.0 - self.beta_ph, 1.0 + self.beta_ph)\n\n        loss1 = -tf.reduce_mean(tf.minimum(surr1,surr2)) - self.entropy_coeff * self.entropy\n        loss2 = self.eta_ph * tf.square(tf.maximum(0.0, self.kl - 2.0 * self.kl_targ))\n\n        self.loss = loss1 + loss2\n        optimizer = tf.train.AdamOptimizer(self.lr_ph)\n        self.train_op = optimizer.minimize(self.loss)\n\n    def train(self, observes, actions, advantages, old_logp_np):\n\n        feed_dict = {self.obs_ph: observes,\n                     self.act_ph: actions,\n                     self.advantages_ph: advantages,\n                     self.old_logp_ph: old_logp_np,\n                     self.beta_ph: self.beta,\n                     self.eta_ph: self.eta,\n                     self.lr_ph: self.lr * self.lr_multiplier}\n\n        _, loss, kl, entropy, log_var_monitor = self.sess.run([self.train_op, self.loss, self.kl, self.entropy, self.log_vars], feed_dict)\n\n        return loss, kl, entropy, log_var_monitor \n\n    def _init_session(self):\n        \"\"\"Launch TensorFlow session and initialize variables\"\"\"\n        self.sess = tf.Session(graph=self.g)\n        self.sess.run(self.init)\n\n    def sample(self, obs):\n        \"\"\"Draw sample from policy distribution\"\"\"\n        feed_dict = {self.obs_ph: obs}\n\n        if self.test_mode:\n            action = self.sess.run(self.deterministic_act , feed_dict=feed_dict)\n        else:\n            action = self.sess.run(self.sampled_act , feed_dict=feed_dict)\n\n        if self.discretize:\n            idx = self.action_converter.action2idx(action[0])\n            discrete_action = self.action_converter.idx2action(idx)\n            env_action = discrete_action\n        else:  \n            env_action = action\n        #print('env act: ',env_action)\n        return action, env_action\n\n\n    def update(self, observes, actions, advantages, logger):\n        \"\"\" Update policy based on observations, actions and advantages\n\n        Args:\n            observes: observations, shape = (N, obs_dim)\n            actions: actions, shape = (N, act_dim)\n            advantages: advantages, shape = (N,)\n            logger: Logger object, see utils.py\n        \"\"\"\n\n        feed_dict = {self.obs_ph: observes,\n                     self.act_ph: actions,\n                     self.advantages_ph: advantages}\n        old_logp_np = np.squeeze(self.sess.run([self.logp],feed_dict))\n\n        loss, kl, entropy = 0, 0, 0\n \n        for e in range(self.epochs):\n\n            if self.shuffle:\n                    observes, actions, advantages, old_logp_np = sklearn.utils.shuffle(observes,actions,advantages,old_logp_np)\n\n\n            loss, kl, entropy, log_var_monitor = self.train(observes, actions, advantages, old_logp_np)\n\n            if kl > 4.0 * self.kl_targ and self.servo_kl:\n                print(' *** BROKE ***')\n                break \n\n        if self.servo_kl:\n            self.adjust_beta(kl)\n        print('kl = ',kl, ' beta = ',self.beta,' lr_mult = ',self.lr_multiplier)\n        self.kl_stat = kl\n        self.entropy_stat = entropy\n        var_monitor = np.exp(log_var_monitor/2.0)\n        print('var: ' ,var_monitor),\n        logger.log({'PolicyLoss': loss,\n                    'PolicyEntropy': entropy,\n                    'KL': kl,\n                    'Beta': self.beta,\n                    'Variance' : np.max(var_monitor),\n                    'lr_multiplier': self.lr_multiplier})\n\n    def adjust_beta(self,kl):\n        if  kl < self.kl_targ / 2:\n            self.beta = np.minimum(self.max_beta, 1.5 * self.beta)  # max clip beta\n            #print('too low')\n            if self.beta > (self.max_beta/2) and self.lr_multiplier < 10:\n                self.lr_multiplier *= 1.5\n        elif kl > self.kl_targ * 2:\n            #print('too high')\n            self.beta = np.maximum(self.min_beta, self.beta / 1.5)  # min clip beta\n            if self.beta <= (2*self.min_beta) and self.lr_multiplier > 0.1:\n                self.lr_multiplier /= 1.5\n\n\n    def close_sess(self):\n        \"\"\" Close TensorFlow session \"\"\"\n        self.sess.close()\n", "meta": {"hexsha": "8fd1cd4fbcec49f7fe7724edf780dace9ed0fd9d", "size": 15080, "ext": "py", "lang": "Python", "max_stars_repo_path": "AAS_18-290_3dof_journal/policy_rnn.py", "max_stars_repo_name": "Aerospace-AI/AAS-18-290_3dof", "max_stars_repo_head_hexsha": "eed5d66de5514fdd2a19c48db8ae8120bd5e25ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-04-09T08:38:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T14:21:45.000Z", "max_issues_repo_path": "AAS_18-290_3dof_manuscript/policy_rnn.py", "max_issues_repo_name": "Aerospace-AI/AAS-18-290_3dof", "max_issues_repo_head_hexsha": "eed5d66de5514fdd2a19c48db8ae8120bd5e25ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-03-03T22:53:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-03T22:53:37.000Z", "max_forks_repo_path": "AAS_18-290_3dof_manuscript/policy_rnn.py", "max_forks_repo_name": "Aerospace-AI/AAS-18-290_3dof", "max_forks_repo_head_hexsha": "eed5d66de5514fdd2a19c48db8ae8120bd5e25ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-21T14:21:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T14:21:40.000Z", "avg_line_length": 46.2576687117, "max_line_length": 138, "alphanum_fraction": 0.5972811671, "include": true, "reason": "import numpy", "num_tokens": 3447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.1723190611967502}}
{"text": "\"\"\"\nThis module includes the description of a (multiturn) WakeField as well\nas the implementation of the WakeSource objects.\n\nA WakeField is defined as a composition of the elementary WakeKick\nobjects (see .wake_kicks module). They originate from WakeSources,\ne.g. a WakeTable, Resonator and/or a ResistiveWall. The WakeField does\nnot directly accept the WakeKick objects, but takes a list of\nWakeSources first (can be of different kinds), each of which knows how\nto generate its WakeKick objects via the factory method\nWakeSource.get_wake_kicks(..). The collection of WakeKicks from all the\nWakeSources define the WakeField and are the elementary objects that are\nstored, (i.e. the WakeField forgets about the origin of the WakeKicks\nonce they have been created).\n\n@author Hannes Bartosik, Kevin Li, Giovanni Rumolo, Michael Schenk\n@date March 2014\n@brief Implementation of a WakeField as a composition of WakeKicks\n       originating from different WakeSources.\n@copyright CERN\n\"\"\"\n\n\n\nimport numpy as np\nfrom collections import deque\nfrom scipy.constants import c, physical_constants\nfrom scipy.interpolate import interp1d\nfrom abc import ABCMeta, abstractmethod\n\nfrom PyHEADTAIL.impedances.wake_kicks import *\nfrom PyHEADTAIL.general.element import Element, Printing\nfrom PyHEADTAIL.general.decorators import deprecated\n\nsin = np.sin\ncos = np.cos\n\n\ndef check_wake_sampling(bunch, slicer, wakes, beta=1, wake_column=None, bins=False):\n    '''\n    Handy function for quick visual check of sampling of the wake functions.\n    For now only implemented for wake table type wakes.\n    '''\n    from scipy.constants import c\n    import matplotlib.pyplot as plt\n\n    ss = bunch.get_slices(slicer).z_centers\n    zz = bunch.get_slices(slicer).z_bins\n    ss = ss[:-1]\n    ll = bunch.get_slices(slicer).lambda_z(ss, sigma=100)\n    # ss = np.concatenate((s.z_centers-s.z_centers[-1], (s.z_centers-s.z_centers[0])[1:]))\n\n    A = [wakes.wake_table['time'] * beta*c*1e-9, wakes.wake_table[wake_column] * 1e15]\n    W = [ss[::-1], wakes.function_transverse(wake_column)(beta, ss)]\n\n\n    fig, (ax1, ax2) = plt.subplots(2, figsize=(16,12), sharex=True)\n\n    ax1.plot(ss, ll)\n\n    ax2.plot(A[0], (A[1]), 'b-+', ms=12)\n    ax2.plot(W[0][:-1], (-1*W[1][1:]), 'r-x')\n    if bins:\n        [ax2.axvline(z, color='g') for z in zz]\n\n    ax2.grid()\n    lgd = ['Table', 'Interpolated']\n    if bins:\n        lgd += ['Bin edges']\n    ax2.legend(lgd)\n\n    print('\\n--> Resulting number of slices: {:g}'.format(len(ss)))\n\n    return ax1\n\n\nclass WakeField(Element):\n    \"\"\" A WakeField is defined by elementary WakeKick objects that may\n    originate from different WakeSource objects. Usually, there is\n    no need for the user to define more than one instance of the\n    WakeField class in a simulation - except if one wants to use\n    different slicing configurations (one WakeField object is allowed\n    to have exactly one slicing configuration, i.e. only one instance\n    of the Slicer class). A WakeField also is able to calculate the wake\n    forces coming from earlier turns (multiturn wakes) by archiving the\n    longitudinal bunch distribution (SliceSet instances) a number of\n    turns back. \"\"\"\n\n    def __init__(self, slicer, *wake_sources):\n        \"\"\" Accepts a list of WakeSource objects. Each WakeSource object\n        knows how to generate its corresponding WakeKick objects. The\n        collection of all the WakeKick objects of each of the passed\n        WakeSource objects defines the WakeField.\n        When instantiating the WakeField object, the WakeKick objects\n        for each WakeSource defined in wake_sources are requested. The\n        returned WakeKick lists are all stored in the\n        WakeField.wake_kicks list. The WakeField itself forgets about\n        the origin (WakeSource) of the kicks as soon as they have been\n        generated.\n        Exactly one instance of the Slicer class must be passed to the\n        WakeField constructor. All the wake field components (kicks)\n        hence use the same slicing and thus the same slice_set to\n        calculate the strength of the kicks.\n        To calculate the contributions from multiturn wakes, the\n        longitudinal beam distributions (SliceSet instances) are\n        archived in a deque. In parallel to the slice_set_deque,\n        there is a slice_set_age_deque to keep track of the age of\n        each of the SliceSet instances.\"\"\"\n        self.slicer = slicer\n\n        self.wake_kicks = []\n        for source in wake_sources:\n            kicks = source.get_wake_kicks(self.slicer)\n            self.wake_kicks.extend(kicks)\n\n        n_turns_wake_max = max([ source.n_turns_wake\n                                 for source in wake_sources ])\n        self.slice_set_deque = deque([], maxlen=n_turns_wake_max)\n        self.slice_set_age_deque = deque([], maxlen=n_turns_wake_max)\n\n    def track(self, bunch):\n        \"\"\" Calls the WakeKick.apply(bunch, slice_set) method of each of\n        the WakeKick objects stored in self.wake_kicks. A slice_set is\n        necessary to perform this operation. It is requested from the\n        bunch (instance of the Particles class) using the\n        Particles.get_slices(self.slicer) method, where self.slicer is\n        the instance of the Slicer class used for this particluar\n        WakeField object. A slice_set is returned according to the\n        self.slicer configuration. The statistics mean_x and mean_y are\n        requested to be calculated and saved in the SliceSet instance,\n        too, s.t. the first moments x, y can be calculated by the\n        WakeKick instances. \"\"\"\n\n        # Update ages of stored SliceSet instances.\n        for i in range(len(self.slice_set_age_deque)):\n            self.slice_set_age_deque[i] += (\n                bunch.circumference / (bunch.beta * c))\n\n        slice_set = bunch.get_slices(self.slicer,\n                                     statistics=['mean_x', 'mean_y'])\n        self.slice_set_deque.appendleft(slice_set)\n        self.slice_set_age_deque.appendleft(0.)\n\n        for kick in self.wake_kicks:\n            kick.apply(bunch, self.slice_set_deque, self.slice_set_age_deque)\n\n\n''' WakeSource classes. '''\n\nclass WakeSource(Printing, metaclass=ABCMeta):\n    \"\"\" Abstract base class for wake sources, such as WakeTable,\n    Resonator or ResistiveWall. \"\"\"\n\n    @abstractmethod\n    def get_wake_kicks(self, slicer_mode):\n        \"\"\" Factory method. Creates instances of the WakeKick objects\n        for the given WakeSource and returns them as a list wake_kicks.\n        This method is usually only called by a WakeField object to\n        collect and create all the WakeKick objects originating from the\n        different sources. (The slicer mode Slicer.mode must be passed\n        at instantiation of a WakeKick object only to set the\n        appropriate convolution method. See docstrings of WakeKick\n        class.) \"\"\"\n        pass\n\n\nclass WakeTable(WakeSource):\n    \"\"\" Class to define wake functions and WakeKick objects using wake\n    data from a table. \"\"\"\n\n    def __init__(self, wake_file, wake_file_columns, n_turns_wake=1,\n                 *args, **kwargs):\n        \"\"\" Load data from the wake_file and store them in a dictionary\n        self.wake_table. Keys are the names specified by the user in\n        wake_file_columns and describe the names of the wake field\n        components (e.g. dipole_x or dipole_yx). The dict values are\n        given by the corresponding data read from the table. The\n        nomenclature of the wake components must be strictly obeyed.\n        Valid names for wake components are:\n\n        'constant_x', 'constant_y', 'dipole_x', 'dipole_y', 'dipole_xy',\n        'dipole_yx', 'quadrupole_x', 'quadrupole_y', 'quadrupole_xy',\n        'quadrupole_yx', 'longitudinal'.\n\n        The order of wake_file_columns is relevant and must correspond\n        to the one in the wake_file. There is no way to check this here\n        and it is in the responsibility of the user to ensure it is\n        correct. Two checks made here are whether the length of\n        wake_file_columns corresponds to the number of columns in the\n        wake_file and whether a column 'time' is specified.\n\n        The units and signs of the wake table data are assumed to follow\n        the HEADTAIL conventions, i.e.\n          time: [ns]\n          transverse wake components: [V/pC/mm]\n          longitudinal wake component: [V/pC].\n\n        The parameter 'n_turns_wake' defines how many turns are\n        considered for the multiturn wakes. It is 1 by default, i.e.\n        multiturn wakes are off. \"\"\"\n        super(WakeTable, self).__init__(*args, **kwargs)\n\n        self.wake_table = {}\n\n        wake_data = np.loadtxt(wake_file)\n        if len(wake_file_columns) != wake_data.shape[1]:\n            raise ValueError(\"Length of wake_file_columns list does not\" +\n                             \" correspond to the number of columns in the\" +\n                             \" specified wake_file. \\n\")\n        if 'time' not in wake_file_columns:\n            raise ValueError(\"No wake_file_column with name 'time' has\" +\n                             \" been specified. \\n\")\n\n        for i, column_name in enumerate(wake_file_columns):\n            self.wake_table.update({ column_name : wake_data[:,i] })\n\n        self.n_turns_wake = n_turns_wake\n\n    def get_wake_kicks(self, slicer):\n        \"\"\" Factory method. Creates instances of the appropriate\n        WakeKick objects for all the wake components provided by the\n        user (and the wake table data). The WakeKick objects are\n        returned as a list wake_kicks. \"\"\"\n        wake_kicks = []\n\n        # Constant wake kicks.\n        if self._is_provided('constant_x'):\n            wake_function = self.function_transverse('constant_x')\n            wake_kicks.append(ConstantWakeKickX(\n                wake_function, slicer, self.n_turns_wake))\n\n        if self._is_provided('constant_y'):\n            wake_function = self.function_transverse('constant_y')\n            wake_kicks.append(ConstantWakeKickY(\n                wake_function, slicer, self.n_turns_wake))\n\n        if self._is_provided('longitudinal'):\n            wake_function = self.function_longitudinal()\n            wake_kicks.append(ConstantWakeKickZ(\n                wake_function, slicer, self.n_turns_wake))\n\n        # Dipolar wake kicks.\n        if self._is_provided('dipole_x'):\n            wake_function = self.function_transverse('dipole_x')\n            wake_kicks.append(DipoleWakeKickX(\n                wake_function, slicer, self.n_turns_wake))\n\n        if self._is_provided('dipole_y'):\n            wake_function = self.function_transverse('dipole_y')\n            wake_kicks.append(DipoleWakeKickY(\n                wake_function, slicer, self.n_turns_wake))\n\n        if self._is_provided('dipole_xy'):\n            wake_function = self.function_transverse('dipole_xy')\n            wake_kicks.append(DipoleWakeKickXY(\n                wake_function, slicer, self.n_turns_wake))\n\n        if self._is_provided('dipole_yx'):\n            wake_function = self.function_transverse('dipole_yx')\n            wake_kicks.append(DipoleWakeKickYX(\n                wake_function, slicer, self.n_turns_wake))\n\n        # Quadrupolar wake kicks.\n        if self._is_provided('quadrupole_x'):\n            wake_function = self.function_transverse('quadrupole_x')\n            wake_kicks.append(QuadrupoleWakeKickX(\n                wake_function, slicer, self.n_turns_wake))\n\n        if self._is_provided('quadrupole_y'):\n            wake_function = self.function_transverse('quadrupole_y')\n            wake_kicks.append(QuadrupoleWakeKickY(\n                wake_function, slicer, self.n_turns_wake))\n\n        if self._is_provided('quadrupole_xy'):\n            wake_function = self.function_transverse('quadrupole_xy')\n            self.kicks.append(QuadrupoleWakeKickXY(\n                wake_function, slicer, self.n_turns_wake))\n\n        if self._is_provided('quadrupole_yx'):\n            wake_function = self.function_transverse('quadrupole_yx')\n            wake_kicks.append(QuadrupoleWakeKickYX(\n                wake_function, slicer, self.n_turns_wake))\n\n        return wake_kicks\n\n    def _is_provided(self, wake_component):\n        \"\"\" Check whether wake_component is a valid name and available\n        in wake table data. Return 'True' if yes and 'False' if no. \"\"\"\n        if wake_component in list(self.wake_table.keys()):\n            return True\n        else:\n            # self.warns(wake_component + ' \\n' +\n            #       'Wake component is either not provided or does not \\n'+\n            #       'use correct nomenclature. See docstring of WakeTable \\n' +\n            #       'constructor to display valid names. \\n')\n            return False\n\n    def function_transverse(self, wake_component):\n        \"\"\" Defines and returns the wake(beta, dz) function for the\n        given wake_component (transverse). Data from the wake table are\n        used, but first converted to SI units assuming that time is\n        specified in [ns] and transverse wake field strengths in\n        [V/pC/mm]. Sign conventions are applied (HEADTAIL conventions).\n        dz is related to wake table time data by dz = beta c dt (dz < 0\n        for the ultrarelativistic case).\n        The wake(dt) uses the scipy.interpolate.interp1d linear\n        interpolation to calculate the wake strength at an arbitrary\n        value of dt (provided it is in the valid range). The valid range\n        of dt is given by the time range from the wake table. If values\n        of wake(dt) are requested for dt outside the valid range, a\n        ValueError is raised by interp1d.\n        Very basic conformity checks for the wake table data are already\n        performed at definition time of the wake(dt) method. E.g.\n        whether the specified wake is valid only for ultrarelativistic\n        cases or low beta cases. In the former case, the wake strength\n        at time 0 must be defined by the user! \"\"\"\n        convert_to_s = 1e-9\n        convert_to_V_per_Cm = 1e15\n\n        time = convert_to_s * self.wake_table['time']\n        wake_strength = -convert_to_V_per_Cm * self.wake_table[wake_component]\n        interpolation_function = interp1d(time, wake_strength)\n\n        if (time[0] == 0) and (wake_strength[0] == 0):\n            def wake(dt, *args, **kwargs):\n                dt = dt.clip(max=0)\n                return interpolation_function(-dt)\n            self.prints(wake_component +\n                  ' Assuming ultrarelativistic wake.')\n\n        elif (time[0] < 0):\n            def wake(dt, *args, **kwargs):\n                return interpolation_function(-dt)\n            self.prints(wake_component +  ' Found low beta wake.')\n\n        else:\n            raise ValueError(wake_component +\n                             ' does not meet requirements.')\n        return wake\n\n    def function_longitudinal(self):\n        \"\"\" Defines and returns the wake(dt) function for the given\n        wake_component (longitudinal). Data from the wake table are\n        used, but first converted to SI units assuming that time is\n        specified in [ns] and longitudinal wake field strength in\n        [V/pC]. Sign conventions are applied (HEADTAIL conventions).\n        The wake(dt) uses the scipy.interpolate.interp1d linear\n        interpolation to calculate the wake strength at an arbitrary\n        value of dt (provided it is in the valid range). The valid range\n        of dt is given by the time range from the wake table. If values\n        of wake(dt) are requested for dt outside the valid range, a\n        ValueError is raised by interp1d.\n        The beam loading theorem is respected and applied for dt=0. \"\"\"\n        convert_to_s = 1e-9\n        convert_to_V_per_C = 1e12\n\n        time = convert_to_s * self.wake_table['time']\n        wake_strength = -convert_to_V_per_C * self.wake_table['longitudinal']\n        interpolation_function = interp1d(time, wake_strength)\n\n        def wake(dt, *args, **kwargs):\n            wake_interpolated = interpolation_function(-dt)\n            if time[0] == 0:\n                # Beam loading theorem: Half value of wake strength at\n                # dt = 0.\n                return (np.sign(-dt) + 1.) / 2. * wake_interpolated\n            elif time[0] < 0:\n                return wake_interpolated\n            else:\n                raise ValueError('Longitudinal wake component does not meet' +\n                                 ' requirements.')\n        return wake\n\n\nclass Resonator(WakeSource):\n    \"\"\" Class to describe the wake functions originating from a\n    resonator impedance. Alex Chao's resonator model (Eq. 2.82) is used\n    as well as the definitions from HEADTAIL. \"\"\"\n\n    def __init__(self, R_shunt, frequency, Q,\n                 Yokoya_X1, Yokoya_Y1, Yokoya_X2, Yokoya_Y2, switch_Z,\n                 n_turns_wake=1, *args, **kwargs):\n        \"\"\" General constructor to create a Resonator WakeSource object\n        describing the wake functions of a resonator impedance. Alex\n        Chao's resonator model (Eq. 2.82) is used as well as definitions\n        from HEADTAIL.\n        Note that it is no longer allowed to pass a LIST of parameters\n        to generate a number of resonators with different parameters\n        within the same Resonator object. Instead, create the Resonator\n        objects and pass all of them to the WakeField constructor.\n        The parameter 'n_turns_wake' defines how many turns are\n        considered for the multiturn wakes. It is 1 by default, i.e.\n        multiturn wakes are off. \"\"\"\n        super(Resonator, self).__init__(*args, **kwargs)\n\n        self.R_shunt = R_shunt\n        self.frequency = frequency\n        self.Q = Q\n        self.Yokoya_X1 = Yokoya_X1\n        self.Yokoya_X2 = Yokoya_X2\n        self.Yokoya_Y1 = Yokoya_Y1\n        self.Yokoya_Y2 = Yokoya_Y2\n        self.switch_Z = switch_Z\n        self.n_turns_wake = n_turns_wake\n\n    def get_wake_kicks(self, slicer):\n        \"\"\" Factory method. Creates instances of the appropriate\n        WakeKick objects for a Resonator WakeSource with the specified\n        parameters. A WakeKick object is instantiated only if the\n        corresponding Yokoya factor is non-zero. The WakeKick objects\n        are returned as a list wake_kicks. \"\"\"\n        wake_kicks = []\n\n        # Dipole wake kick x.\n        if self.Yokoya_X1:\n            wake_function = self.function_transverse(self.Yokoya_X1)\n            wake_kicks.append(DipoleWakeKickX(\n                wake_function, slicer, self.n_turns_wake))\n\n        # Quadrupole wake kick x.\n        if self.Yokoya_X2:\n            wake_function = self.function_transverse(self.Yokoya_X2)\n            wake_kicks.append(QuadrupoleWakeKickX(\n                wake_function, slicer, self.n_turns_wake))\n\n        # Dipole wake kick y.\n        if self.Yokoya_Y1:\n            wake_function = self.function_transverse(self.Yokoya_Y1)\n            wake_kicks.append(DipoleWakeKickY(\n                wake_function, slicer, self.n_turns_wake))\n\n        # Quadrupole wake kick y.\n        if self.Yokoya_Y2:\n            wake_function = self.function_transverse(self.Yokoya_Y2)\n            wake_kicks.append(QuadrupoleWakeKickY(\n                wake_function, slicer, self.n_turns_wake))\n\n        # Constant wake kick z.\n        if self.switch_Z:\n            wake_function = self.function_longitudinal()\n            wake_kicks.append(ConstantWakeKickZ(\n                wake_function, slicer, self.n_turns_wake))\n\n        return wake_kicks\n\n    def function_transverse(self, Yokoya_factor):\n        \"\"\" Define the wake function (transverse) of a resonator with\n        the given parameters according to Alex Chao's resonator model\n        (Eq. 2.82) and definitions of the resonator in HEADTAIL. \"\"\"\n        omega = 2 * np.pi * self.frequency\n        alpha = omega / (2 * self.Q)\n        omegabar = np.sqrt(np.abs(omega**2 - alpha**2))\n\n        def wake(dt, *args, **kwargs):\n            dt = dt.clip(max=0)\n            if self.Q > 0.5:\n                y = (Yokoya_factor * self.R_shunt * omega**2 / (self.Q *\n                     omegabar) * np.exp(alpha*dt) * sin(omegabar*dt))\n            elif self.Q == 0.5:\n                y = (Yokoya_factor * self.R_shunt * omega**2 / self.Q *\n                      np.exp(alpha*dt) * dt)\n            else:\n                y = (Yokoya_factor * self.R_shunt * omega**2 / (self.Q *\n                     omegabar) * np.exp(alpha*dt) * np.sinh(omegabar*dt))\n            return y\n        return wake\n\n    def function_longitudinal(self):\n        \"\"\" Define the wake function (longitudinal) of a resonator with\n        the given parameters according to Alex Chao's resonator model\n        (Eq. 2.82) and definitions of the resonator in HEADTAIL. \"\"\"\n        omega = 2 * np.pi * self.frequency\n        alpha = omega / (2 * self.Q)\n        omegabar = np.sqrt(np.abs(omega**2 - alpha**2))\n\n        def wake(dt, *args, **kwargs):\n            if self.Q > 0.5:\n                y = (-(np.sign(dt) - 1) * self.R_shunt * alpha *\n                     np.exp(alpha * dt) * (cos(omegabar * dt) +\n                     alpha / omegabar * sin(omegabar*dt)))\n            elif self.Q == 0.5:\n                y = (-(np.sign(dt) - 1) * self.R_shunt * alpha *\n                     np.exp(alpha * dt) * (1. + alpha * dt))\n            elif self.Q < 0.5:\n                y = (-(np.sign(dt) - 1) * self.R_shunt * alpha *\n                     np.exp(alpha * dt) * (np.cosh(omegabar * dt) +\n                     alpha / omegabar * np.sinh(omegabar * dt)))\n            return y\n        return wake\n\n\nclass CircularResonator(Resonator):\n    '''Circular Resonator.'''\n    def __init__(self, R_shunt, frequency, Q, n_turns_wake=1,\n                 *args, **kwargs):\n        \"\"\" Special case of circular resonator. \"\"\"\n        Yokoya_X1 = 1.\n        Yokoya_Y1 = 1.\n        Yokoya_X2 = 0.\n        Yokoya_Y2 = 0.\n        switch_Z  = False\n\n        super(CircularResonator, self).__init__(\n            R_shunt, frequency, Q, Yokoya_X1, Yokoya_Y1,\n            Yokoya_X2, Yokoya_Y2, switch_Z, n_turns_wake, *args, **kwargs)\n\n\nclass ParallelHorizontalPlatesResonator(Resonator):\n    '''Broad-band resonator for horizontal parallel plates.'''\n    def __init__(self, R_shunt, frequency, Q, n_turns_wake=1,\n                 *args, **kwargs):\n        \"\"\" Special case of parallel plate resonator. \"\"\"\n        Yokoya_X1 = np.pi**2 / 24.\n        Yokoya_Y1 = np.pi**2 / 12.\n        Yokoya_X2 = -np.pi**2 / 24.\n        Yokoya_Y2 = np.pi**2 / 24.\n        switch_Z  = False\n\n        super(ParallelHorizontalPlatesResonator, self).__init__(\n            R_shunt, frequency, Q, Yokoya_X1, Yokoya_Y1,\n            Yokoya_X2, Yokoya_Y2, switch_Z, n_turns_wake, *args, **kwargs)\n\n\n@deprecated('--> \"ParallelPlatesResonator\" will be removed '\n            'in the near future. '\n            'Use \"ParallelHorizontalPlatesResonator\" instead.\\n')\nclass ParallelPlatesResonator(ParallelHorizontalPlatesResonator):\n    pass\n\n\nclass ParallelVerticalPlatesResonator(Resonator):\n    '''Broad-band resonator for vertical parallel plates.'''\n    def __init__(self, R_shunt, frequency, Q, n_turns_wake=1,\n                 *args, **kwargs):\n        \"\"\" Special case of parallel plate resonator. \"\"\"\n        Yokoya_X1 = np.pi**2 / 12.\n        Yokoya_Y1 = np.pi**2 / 24.\n        Yokoya_X2 = np.pi**2 / 24.\n        Yokoya_Y2 = -np.pi**2 / 24.\n        switch_Z  = False\n\n        super(ParallelVerticalPlatesResonator, self).__init__(\n            R_shunt, frequency, Q, Yokoya_X1, Yokoya_Y1,\n            Yokoya_X2, Yokoya_Y2, switch_Z, n_turns_wake, *args, **kwargs)\n\n\nclass ResistiveWall(WakeSource):\n    \"\"\" Class to describe the wake functions originating from a\n    resistive wall impedance. \"\"\"\n\n    def __init__(self, pipe_radius, resistive_wall_length, conductivity,\n                 dt_min, Yokoya_X1, Yokoya_Y1, Yokoya_X2, Yokoya_Y2,\n                 n_turns_wake=1, *args, **kwargs):\n        \"\"\" General constructor to create a ResistiveWall WakeSource\n        object describing the wake functions of a resistive wall\n        impedance.\n        The parameter 'n_turns_wake' defines how many turns are\n        considered for the multiturn wakes. It is 1 by default, i.e.\n        multiturn wakes are off. \"\"\"\n        super(ResistiveWall, self).__init__(*args, **kwargs)\n\n        self.pipe_radius = np.array([pipe_radius]).flatten()\n        self.resistive_wall_length = resistive_wall_length\n        self.conductivity = conductivity\n        self.dt_min = dt_min\n\n        self.Yokoya_X1 = Yokoya_X1\n        self.Yokoya_Y1 = Yokoya_Y1\n        self.Yokoya_X2 = Yokoya_X2\n        self.Yokoya_Y2 = Yokoya_Y2\n        self.n_turns_wake = n_turns_wake\n\n    def get_wake_kicks(self, slicer):\n        \"\"\" Factory method. Creates instances of the appropriate\n        WakeKick objects for the ResistiveWall WakeSource with the\n        specified parameters. A WakeKick object is instantiated only if\n        the corresponding Yokoya factor is non-zero. The WakeKick\n        objects are returned as a list wake_kicks. \"\"\"\n        wake_kicks = []\n\n        # Dipole wake kick x.\n        if self.Yokoya_X1:\n            wake_function = self.function_transverse(self.Yokoya_X1)\n            wake_kicks.append(DipoleWakeKickX(\n                wake_function, slicer, self.n_turns_wake))\n\n        # Quadrupole wake kick x.\n        if self.Yokoya_X2:\n            wake_function = self.function_transverse(self.Yokoya_X2)\n            wake_kicks.append(QuadrupoleWakeKickX(\n                wake_function, slicer, self.n_turns_wake))\n\n        # Dipole wake kick y.\n        if self.Yokoya_Y1:\n            wake_function = self.function_transverse(self.Yokoya_Y1)\n            wake_kicks.append(DipoleWakeKickY(\n                wake_function, slicer, self.n_turns_wake))\n\n        # Quadrupole wake kick y.\n        if self.Yokoya_Y2:\n            wake_function = self.function_transverse(self.Yokoya_Y2)\n            wake_kicks.append(QuadrupoleWakeKickY(\n                wake_function, slicer, self.n_turns_wake))\n\n        return wake_kicks\n\n    def function_transverse(self, Yokoya_factor):\n        \"\"\" Define the wake function (transverse) of a resistive wall\n        with the given parameters. \"\"\"\n        mu_r = 1\n        # The impedance of free space [Ohm]\n        Z_0 = 119.9169832 * np.pi\n\n        def wake(dt, *args, **kwargs):\n            y = (Yokoya_factor * (np.sign(dt + np.abs(self.dt_min)) - 1) / 2. *\n                 np.sqrt(kwargs['beta']) * self.resistive_wall_length / np.pi /\n                 self.pipe_radius**3 * np.sqrt(-mu_r / np.pi /\n                 self.conductivity / dt.clip(max=-abs(self.dt_min))))*np.sqrt(Z_0*c)\n            return y\n        return wake\n\n\nclass CircularResistiveWall(ResistiveWall):\n    '''Circular resistive wall.'''\n    def __init__(self, pipe_radius, resistive_wall_length, conductivity,\n                 dt_min, n_turns_wake=1, *args, **kwargs):\n        \"\"\" Special case of a circular resistive wall. \"\"\"\n        Yokoya_X1 = 1.\n        Yokoya_Y1 = 1.\n        Yokoya_X2 = 0.\n        Yokoya_Y2 = 0.\n\n        super(CircularResistiveWall, self).__init__(\n            pipe_radius, resistive_wall_length, conductivity, dt_min,\n            Yokoya_X1, Yokoya_Y1, Yokoya_X2, Yokoya_Y2, n_turns_wake,\n            *args, **kwargs)\n\n\nclass ParallelHorizontalPlatesResistiveWall(ResistiveWall):\n    '''Resistive wall impedance for horizontal parallel plates.'''\n    def __init__(self, pipe_radius, resistive_wall_length, conductivity,\n                 dt_min, n_turns_wake=1, *args, **kwargs):\n        \"\"\" Special case of a parallel plates resistive wall. \"\"\"\n        Yokoya_X1 = np.pi**2 / 24.\n        Yokoya_Y1 = np.pi**2 / 12.\n        Yokoya_X2 = -np.pi**2 / 24.\n        Yokoya_Y2 = np.pi**2 / 24.\n\n        super(ParallelHorizontalPlatesResistiveWall, self).__init__(\n            pipe_radius, resistive_wall_length, conductivity, dt_min,\n            Yokoya_X1, Yokoya_Y1, Yokoya_X2, Yokoya_Y2, n_turns_wake,\n            *args, **kwargs)\n\n@deprecated('--> \"ParallelPlatesResistiveWall\" will be removed '\n            'in the near future. '\n            'Use \"ParallelHorizontalPlatesResistiveWall\" instead.\\n')\nclass ParallelPlatesResistiveWall(ParallelHorizontalPlatesResistiveWall):\n    pass\n\n\nclass ParallelVerticalPlatesResistiveWall(Resonator):\n    '''Resistive wall impedance for vertical parallel plates.'''\n    def __init__(self, pipe_radius, resistive_wall_length, conductivity,\n                 dt_min, n_turns_wake=1, *args, **kwargs):\n        \"\"\" Special case of a parallel plates resistive wall. \"\"\"\n        Yokoya_X1 = np.pi**2 / 12.\n        Yokoya_Y1 = np.pi**2 / 24.\n        Yokoya_X2 = np.pi**2 / 24.\n        Yokoya_Y2 = -np.pi**2 / 24.\n\n        super(ParallelVerticalPlatesResistiveWall, self).__init__(\n            pipe_radius, resistive_wall_length, conductivity, dt_min,\n            Yokoya_X1, Yokoya_Y1, Yokoya_X2, Yokoya_Y2, n_turns_wake,\n            *args, **kwargs)\n", "meta": {"hexsha": "82c9a11b55865411209dac42249397665dc20abd", "size": 28906, "ext": "py", "lang": "Python", "max_stars_repo_path": "PyHEADTAIL/impedances/wakes.py", "max_stars_repo_name": "fsoubelet/PyHEADTAIL", "max_stars_repo_head_hexsha": "51cae8845cceb61cc3f140db4ab0eeb68469110f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PyHEADTAIL/impedances/wakes.py", "max_issues_repo_name": "fsoubelet/PyHEADTAIL", "max_issues_repo_head_hexsha": "51cae8845cceb61cc3f140db4ab0eeb68469110f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PyHEADTAIL/impedances/wakes.py", "max_forks_repo_name": "fsoubelet/PyHEADTAIL", "max_forks_repo_head_hexsha": "51cae8845cceb61cc3f140db4ab0eeb68469110f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.8237037037, "max_line_length": 90, "alphanum_fraction": 0.6428077216, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.1723190565014915}}
{"text": "from __future__ import print_function\nimport argparse\nfrom math import log10, ceil\nimport random, shutil, json\nfrom os.path import join, exists, isfile, realpath, dirname\nfrom os import makedirs, remove, chdir, environ\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader, SubsetRandomSampler\nfrom torch.utils.data.dataset import Subset\nimport torchvision.transforms as transforms\nfrom PIL import Image\nfrom datetime import datetime\nimport torchvision.datasets as datasets\nimport torchvision.models as models\nimport h5py\nimport faiss\n\nfrom tensorboardX import SummaryWriter\nimport numpy as np\nimport netvlad\n\nfrom ipdb import set_trace as bp\nimport sys;sys.path.insert(0,'netvlad/ccsmmutils');import img_utils as myiu\n\n\nparser = argparse.ArgumentParser(description='pytorch-NetVlad')\nparser.add_argument('--mode', type=str, default='train', help='Mode', choices=['train', 'test', 'cluster'])\nparser.add_argument('--batchSize', type=int, default=4, \n        help='Number of triplets (query, pos, negs). Each triplet consists of 12 images.')\nparser.add_argument('--cacheBatchSize', type=int, default=24, help='Batch size for caching and testing')\nparser.add_argument('--cacheRefreshRate', type=int, default=1000, \n        help='How often to refresh cache, in number of queries. 0 for off')\nparser.add_argument('--nEpochs', type=int, default=30, help='number of epochs to train for')\nparser.add_argument('--start-epoch', default=0, type=int, metavar='N', \n        help='manual epoch number (useful on restarts)')\nparser.add_argument('--nGPU', type=int, default=1, help='number of GPU to use.')\nparser.add_argument('--optim', type=str, default='SGD', help='optimizer to use', choices=['SGD', 'ADAM'])\nparser.add_argument('--lr', type=float, default=0.0001, help='Learning Rate.')\nparser.add_argument('--lrStep', type=float, default=5, help='Decay LR ever N steps.')\nparser.add_argument('--lrGamma', type=float, default=0.5, help='Multiply LR by Gamma for decaying.')\nparser.add_argument('--weightDecay', type=float, default=0.001, help='Weight decay for SGD.')\nparser.add_argument('--momentum', type=float, default=0.9, help='Momentum for SGD.')\nparser.add_argument('--nocuda', action='store_true', help='Dont use cuda')\nparser.add_argument('--threads', type=int, default=8, help='Number of threads for each data loader to use')\nparser.add_argument('--seed', type=int, default=123, help='Random seed to use.')\nparser.add_argument('--dataPath', type=str, default='netvlad_v100_datasets/', help='Path for centroid data.')\nparser.add_argument('--runsPath', type=str, default='checkpoints/runs/', help='Path to save runs to.')\nparser.add_argument('--savePath', type=str, default='checkpoints', \n        help='Path to save checkpoints to in logdir. Default=checkpoints/')\nparser.add_argument('--cachePath', type=str, default=environ['TMPDIR'], help='Path to save cache to.')\nparser.add_argument('--resume', type=str, default='', help='Path to load checkpoint from, for resuming training or testing.')\nparser.add_argument('--ckpt', type=str, default='latest', \n        help='Resume from latest or best checkpoint.', choices=['latest', 'best'])\nparser.add_argument('--evalEvery', type=int, default=1, \n        help='Do a validation set run, and save, every N epochs.')\nparser.add_argument('--patience', type=int, default=10, help='Patience for early stopping. 0 is off.')\nparser.add_argument('--dataset', type=str, default='pittsburgh', \n        help='Dataset to use', choices=['pittsburgh'])\nparser.add_argument('--arch', type=str, default='vgg16', \n        help='basenetwork to use', choices=['vgg16', 'alexnet'])\nparser.add_argument('--vladv2', action='store_true', help='Use VLAD v2')\nparser.add_argument('--pooling', type=str, default='netvlad', help='type of pooling to use',\n        choices=['netvlad', 'max', 'avg'])\nparser.add_argument('--num_clusters', type=int, default=64, help='Number of NetVlad clusters. Default=64')\nparser.add_argument('--margin', type=float, default=0.1, help='Margin for triplet loss. Default=0.1')\nparser.add_argument('--split', type=str, default='val', help='Data split to use for testing. Default is val', \n        choices=['test', 'test250k', 'train', 'val'])\nparser.add_argument('--fromscratch', action='store_true', help='Train from scratch rather than using pretrained models')\n\ndef train(epoch):\n    epoch_loss = 0\n    startIter = 1 # keep track of batch iter across subsets for logging\n\n    if opt.cacheRefreshRate > 0:\n        subsetN = ceil(len(train_set) / opt.cacheRefreshRate)\n        #TODO randomise the arange before splitting?\n        subsetIdx = np.array_split(np.arange(len(train_set)), subsetN)\n    else:\n        subsetN = 1\n        subsetIdx = [np.arange(len(train_set))]\n\n    nBatches = (len(train_set) + opt.batchSize - 1) // opt.batchSize\n\n    for subIter in range(subsetN):\n        print('====> Building Cache')\n        model.eval()\n        train_set.cache = join(opt.cachePath, train_set.whichSet + '_feat_cache.hdf5')\n        with h5py.File(train_set.cache, mode='w') as h5: \n            pool_size = encoder_dim\n            if opt.pooling.lower() == 'netvlad': pool_size *= opt.num_clusters\n            h5feat = h5.create_dataset(\"features\", \n                    [len(whole_train_set), pool_size], \n                    dtype=np.float32)\n            with torch.no_grad():\n                for iteration, (input, indices) in enumerate(whole_training_data_loader, 1):\n                    input = input.to(device)\n                    image_encoding = model.encoder(input)\n                    vlad_encoding = model.pool(image_encoding) \n                    h5feat[indices.detach().numpy(), :] = vlad_encoding.detach().cpu().numpy()\n                    del input, image_encoding, vlad_encoding\n\n        sub_train_set = Subset(dataset=train_set, indices=subsetIdx[subIter])\n\n        training_data_loader = DataLoader(dataset=sub_train_set, num_workers=opt.threads, \n                    batch_size=opt.batchSize, shuffle=True, \n                    collate_fn=dataset.collate_fn, pin_memory=cuda)\n\n        print('Allocated:', torch.cuda.memory_allocated())\n        print('Cached:', torch.cuda.memory_cached())\n\n        model.train()\n        for iteration, (query, positives, negatives, \n                negCounts, indices) in enumerate(training_data_loader, startIter):\n            # some reshaping to put query, pos, negs in a single (N, 3, H, W) tensor\n            # where N = batchSize * (nQuery + nPos + nNeg)\n            if query is None: continue # in case we get an empty batch\n\n            B, C, H, W = query.shape\n            nNeg = torch.sum(negCounts)\n            input = torch.cat([query, positives, negatives])\n\n            input = input.to(device)\n            image_encoding = model.encoder(input)\n            vlad_encoding = model.pool(image_encoding) \n\n            vladQ, vladP, vladN = torch.split(vlad_encoding, [B, B, nNeg])\n\n            optimizer.zero_grad()\n            \n            # calculate loss for each Query, Positive, Negative triplet\n            # due to potential difference in number of negatives have to \n            # do it per query, per negative\n            loss = 0\n            for i, negCount in enumerate(negCounts):\n                for n in range(negCount):\n                    negIx = (torch.sum(negCounts[:i]) + n).item()\n                    loss += criterion(vladQ[i:i+1], vladP[i:i+1], vladN[negIx:negIx+1])\n\n            loss /= nNeg.float().to(device) # normalise by actual number of negatives\n            loss.backward()\n            optimizer.step()\n            del input, image_encoding, vlad_encoding, vladQ, vladP, vladN\n            del query, positives, negatives\n\n            batch_loss = loss.item()\n            epoch_loss += batch_loss\n\n            if iteration % 50 == 0 or nBatches <= 10:\n                print(\"==> Epoch[{}]({}/{}): Loss: {:.4f}\".format(epoch, iteration, \n                    nBatches, batch_loss), flush=True)\n                writer.add_scalar('Train/Loss', batch_loss, \n                        ((epoch-1) * nBatches) + iteration)\n                writer.add_scalar('Train/nNeg', nNeg, \n                        ((epoch-1) * nBatches) + iteration)\n                print('Allocated:', torch.cuda.memory_allocated())\n                print('Cached:', torch.cuda.memory_cached())\n\n        startIter += len(training_data_loader)\n        del training_data_loader, loss\n        optimizer.zero_grad()\n        torch.cuda.empty_cache()\n        remove(train_set.cache) # delete HDF5 cache\n\n    avg_loss = epoch_loss / nBatches\n\n    print(\"===> Epoch {} Complete: Avg. Loss: {:.4f}\".format(epoch, avg_loss), \n            flush=True)\n    writer.add_scalar('Train/AvgLoss', avg_loss, epoch)\n\ndef test(eval_set, epoch=0, write_tboard=False):\n    # TODO what if features dont fit in memory? \n    test_data_loader = DataLoader(dataset=eval_set, \n                num_workers=opt.threads, batch_size=opt.cacheBatchSize, shuffle=False, \n                pin_memory=cuda)\n\n    model.eval()\n    with torch.no_grad():\n        print('====> Extracting Features')\n        pool_size = encoder_dim\n        if opt.pooling.lower() == 'netvlad': pool_size *= opt.num_clusters\n        dbFeat = np.empty((len(eval_set), pool_size))\n\n        for iteration, (input, indices) in enumerate(test_data_loader, 1):\n            input = input.to(device) #[24, 3, 480, 640]\n            image_encoding = model.encoder(input) #[24, 512, 30, 40]\n            vlad_encoding = model.pool(image_encoding) #[24,32768] \n\n            #dbFeat : [17608, 32768]\n            dbFeat[indices.detach().numpy(), :] = vlad_encoding.detach().cpu().numpy() #[24,32768]\n            if iteration % 50 == 0 or len(test_data_loader) <= 10:\n                print(\"==> Batch ({}/{})\".format(iteration,len(test_data_loader)), flush=True)\n                myiu.clf()\n                myiu.imshow(input,221,'input')\n                myiu.imshow(image_encoding[:,:3,:,:],222,'encoding')\n                myiu.plot(vlad_encoding,223,'vlad')\n\n            del input, image_encoding, vlad_encoding\n    del test_data_loader\n\n    # extracted for both db and query, now split in own sets\n    qFeat = dbFeat[eval_set.dbStruct.numDb:].astype('float32') #[7608,32768]\n    dbFeat = dbFeat[:eval_set.dbStruct.numDb].astype('float32') #[10000,32768]\n    \n    print('====> Building faiss index')\n    #qFeat  : [7608,32768], pool_size = 32768 as dimension of feature\n    #dbFeat : [10000,32768]\n    faiss_index = faiss.IndexFlatL2(pool_size) #32768\n    faiss_index.add(dbFeat)\n\n    print('====> Calculating recall @ N')\n    n_values = [1,5,10,20] #n nearest neighbors\n\n    #we want to see 20 nearnest neighbors using following search command.\n    _, predictions = faiss_index.search(qFeat, max(n_values)) #predictions : [7608,20]\n\n    # for each query get those within threshold distance\n    gt = eval_set.getPositives() #Ground Truth\n\n    correct_at_n = np.zeros(len(n_values))\n    #TODO can we do this on the matrix in one go?\n    for qIx, pred in enumerate(predictions):\n        for i,n in enumerate(n_values):\n            # if in top N then also in top NN, where NN > N\n            if np.any(np.in1d(pred[:n], gt[qIx])):\n                correct_at_n[i:] += 1\n                break\n    recall_at_n = correct_at_n / eval_set.dbStruct.numQ\n\n    recalls = {} #make dict for output\n    for i,n in enumerate(n_values):\n        recalls[n] = recall_at_n[i]\n        print(\"====> Recall@{}: {:.4f}\".format(n, recall_at_n[i]))\n        if write_tboard: writer.add_scalar('Val/Recall@' + str(n), recall_at_n[i], epoch)\n\n\n    return recalls\n\ndef get_clusters(cluster_set):\n    nDescriptors = 50000\n    nPerImage = 100\n    nIm = ceil(nDescriptors/nPerImage)\n\n    sampler = SubsetRandomSampler(np.random.choice(len(cluster_set), nIm, replace=False))\n    data_loader = DataLoader(dataset=cluster_set, \n                num_workers=opt.threads, batch_size=opt.cacheBatchSize, shuffle=False, \n                pin_memory=cuda,\n                sampler=sampler)\n\n    if not exists(join(opt.dataPath, 'centroids')):\n        makedirs(join(opt.dataPath, 'centroids'))\n\n    initcache = join(opt.dataPath, 'centroids', opt.arch + '_' + cluster_set.dataset + '_' + str(opt.num_clusters) + '_desc_cen.hdf5')\n    with h5py.File(initcache, mode='w') as h5: \n        with torch.no_grad():\n            model.eval()\n            print('====> Extracting Descriptors')\n            dbFeat = h5.create_dataset(\"descriptors\", \n                        [nDescriptors, encoder_dim], \n                        dtype=np.float32)\n\n            for iteration, (input, indices) in enumerate(data_loader, 1):\n                input = input.to(device)\n                image_descriptors = model.encoder(input).view(input.size(0), encoder_dim, -1).permute(0, 2, 1)\n\n                batchix = (iteration-1)*opt.cacheBatchSize*nPerImage\n                for ix in range(image_descriptors.size(0)):\n                    # sample different location for each image in batch\n                    sample = np.random.choice(image_descriptors.size(1), nPerImage, replace=False)\n                    startix = batchix + ix*nPerImage\n                    dbFeat[startix:startix+nPerImage, :] = image_descriptors[ix, sample, :].detach().cpu().numpy()\n\n                if iteration % 50 == 0 or len(data_loader) <= 10:\n                    print(\"==> Batch ({}/{})\".format(iteration, \n                        ceil(nIm/opt.cacheBatchSize)), flush=True)\n                del input, image_descriptors\n        \n        print('====> Clustering..')\n        niter = 100\n        kmeans = faiss.Kmeans(encoder_dim, opt.num_clusters, niter=niter, verbose=False)\n        kmeans.train(dbFeat[...])\n\n        print('====> Storing centroids', kmeans.centroids.shape)\n        h5.create_dataset('centroids', data=kmeans.centroids)\n        print('====> Done!')\n\ndef save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):\n    model_out_path = join(opt.savePath, filename)\n    torch.save(state, model_out_path)\n    if is_best:\n        shutil.copyfile(model_out_path, join(opt.savePath, 'model_best.pth.tar'))\n\nclass Flatten(nn.Module):\n    def forward(self, input):\n        return input.view(input.size(0), -1)\n\nclass L2Norm(nn.Module):\n    def __init__(self, dim=1):\n        super().__init__()\n        self.dim = dim\n\n    def forward(self, input):\n        return F.normalize(input, p=2, dim=self.dim)\n\nif __name__ == \"__main__\":\n    opt = parser.parse_args()\n\n    restore_var = ['lr', 'lrStep', 'lrGamma', 'weightDecay', 'momentum', \n            'runsPath', 'savePath', 'arch', 'num_clusters', 'pooling', 'optim',\n            'margin', 'seed', 'patience']\n    if opt.resume:\n        flag_file = join(opt.resume, 'checkpoints', 'flags.json')\n        if exists(flag_file):\n            with open(flag_file, 'r') as f:\n                stored_flags = {'--'+k : str(v) for k,v in json.load(f).items() if k in restore_var}\n                to_del = []\n                for flag, val in stored_flags.items():\n                    for act in parser._actions:\n                        if act.dest == flag[2:]:\n                            # store_true / store_false args don't accept arguments, filter these \n                            if type(act.const) == type(True):\n                                if val == str(act.default):\n                                    to_del.append(flag)\n                                else:\n                                    stored_flags[flag] = ''\n                for flag in to_del: del stored_flags[flag]\n\n                train_flags = [x for x in list(sum(stored_flags.items(), tuple())) if len(x) > 0]\n                print('Restored flags:', train_flags)\n                opt = parser.parse_args(train_flags, namespace=opt)\n\n    print(opt)\n\n    if opt.dataset.lower() == 'pittsburgh':\n        import pittsburgh as dataset\n    else:\n        raise Exception('Unknown dataset')\n\n    cuda = not opt.nocuda\n    if cuda and not torch.cuda.is_available():\n        raise Exception(\"No GPU found, please run with --nocuda\")\n\n    device = torch.device(\"cuda\" if cuda else \"cpu\")\n\n    random.seed(opt.seed)\n    np.random.seed(opt.seed)\n    torch.manual_seed(opt.seed)\n    if cuda:\n        torch.cuda.manual_seed(opt.seed)\n\n    print('===> Loading dataset(s)')\n    if opt.mode.lower() == 'train':\n        whole_train_set = dataset.get_whole_training_set()\n        whole_training_data_loader = DataLoader(dataset=whole_train_set, \n                num_workers=opt.threads, batch_size=opt.cacheBatchSize, shuffle=False, \n                pin_memory=cuda)\n\n        train_set = dataset.get_training_query_set(opt.margin)\n\n        print('====> Training query set:', len(train_set))\n        whole_test_set = dataset.get_whole_val_set()\n        print('===> Evaluating on val set, query count:', whole_test_set.dbStruct.numQ)\n    elif opt.mode.lower() == 'test':\n        if opt.split.lower() == 'test':\n            whole_test_set = dataset.get_whole_test_set()\n            print('===> Evaluating on test set')\n        elif opt.split.lower() == 'test250k':\n            whole_test_set = dataset.get_250k_test_set()\n            print('===> Evaluating on test250k set')\n        elif opt.split.lower() == 'train':\n            whole_test_set = dataset.get_whole_training_set()\n            print('===> Evaluating on train set')\n        elif opt.split.lower() == 'val':\n            whole_test_set = dataset.get_whole_val_set()\n            print('===> Evaluating on val set')\n        else:\n            raise ValueError('Unknown dataset split: ' + opt.split)\n        print('====> Query count:', whole_test_set.dbStruct.numQ)\n    elif opt.mode.lower() == 'cluster':\n        whole_train_set = dataset.get_whole_training_set(onlyDB=True)\n\n    print('===> Building model')\n\n    pretrained = not opt.fromscratch\n    if opt.arch.lower() == 'alexnet':\n        encoder_dim = 256\n        encoder = models.alexnet(pretrained=pretrained)\n        # capture only features and remove last relu and maxpool\n        layers = list(encoder.features.children())[:-2]\n\n        if pretrained:\n            # if using pretrained only train conv5\n            for l in layers[:-1]:\n                for p in l.parameters():\n                    p.requires_grad = False\n\n    elif opt.arch.lower() == 'vgg16':\n        encoder_dim = 512\n        encoder = models.vgg16(pretrained=pretrained)\n        # capture only feature part and remove last relu and maxpool\n    \n        layers = list(encoder.features.children())[:-2]\n\n        if pretrained:\n            # if using pretrained then only train conv5_1, conv5_2, and conv5_3\n            for l in layers[:-5]: \n                for p in l.parameters():\n                    p.requires_grad = False\n\n    if opt.mode.lower() == 'cluster' and not opt.vladv2:\n        layers.append(L2Norm())\n\n    encoder = nn.Sequential(*layers)\n    model = nn.Module() \n    model.add_module('encoder', encoder)\n\n\n    if opt.mode.lower() != 'cluster':\n        if opt.pooling.lower() == 'netvlad':\n            net_vlad = netvlad.NetVLAD(num_clusters=opt.num_clusters, dim=encoder_dim, vladv2=opt.vladv2)\n            if not opt.resume: \n                if opt.mode.lower() == 'train':\n                    initcache = join(opt.dataPath, 'centroids', opt.arch + '_' + train_set.dataset + '_' + str(opt.num_clusters) +'_desc_cen.hdf5')\n                else:\n                    initcache = join(opt.dataPath, 'centroids', opt.arch + '_' + whole_test_set.dataset + '_' + str(opt.num_clusters) +'_desc_cen.hdf5')\n\n\n                if not exists(initcache):\n                    raise FileNotFoundError('Could not find clusters, please run with --mode=cluster before proceeding')\n\n                with h5py.File(initcache, mode='r') as h5: \n                    clsts = h5.get(\"centroids\")[...]\n                    traindescs = h5.get(\"descriptors\")[...]\n                    net_vlad.init_params(clsts, traindescs) \n                    del clsts, traindescs\n\n            model.add_module('pool', net_vlad)\n        elif opt.pooling.lower() == 'max':\n            global_pool = nn.AdaptiveMaxPool2d((1,1))\n            model.add_module('pool', nn.Sequential(*[global_pool, Flatten(), L2Norm()]))\n        elif opt.pooling.lower() == 'avg':\n            global_pool = nn.AdaptiveAvgPool2d((1,1))\n            model.add_module('pool', nn.Sequential(*[global_pool, Flatten(), L2Norm()]))\n        else:\n            raise ValueError('Unknown pooling type: ' + opt.pooling)\n\n    isParallel = False\n    if opt.nGPU > 1 and torch.cuda.device_count() > 1:\n        model.encoder = nn.DataParallel(model.encoder)\n        if opt.mode.lower() != 'cluster':\n            model.pool = nn.DataParallel(model.pool)\n        isParallel = True\n\n    if not opt.resume:\n        model = model.to(device)\n    \n    if opt.mode.lower() == 'train':\n        if opt.optim.upper() == 'ADAM':\n            optimizer = optim.Adam(filter(lambda p: p.requires_grad, \n                model.parameters()), lr=opt.lr)#, betas=(0,0.9))\n        elif opt.optim.upper() == 'SGD':\n            optimizer = optim.SGD(filter(lambda p: p.requires_grad, \n                model.parameters()), lr=opt.lr,\n                momentum=opt.momentum,\n                weight_decay=opt.weightDecay)\n\n            scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=opt.lrStep, gamma=opt.lrGamma)\n        else:\n            raise ValueError('Unknown optimizer: ' + opt.optim)\n\n        # original paper/code doesn't sqrt() the distances, we do, so sqrt() the margin, I think :D\n        criterion = nn.TripletMarginLoss(margin=opt.margin**0.5, \n                p=2, reduction='sum').to(device)\n\n    if opt.resume:\n        if opt.ckpt.lower() == 'latest':\n            resume_ckpt = join(opt.resume, 'checkpoints', 'checkpoint.pth.tar')\n        elif opt.ckpt.lower() == 'best':\n            resume_ckpt = join(opt.resume, 'checkpoints', 'model_best.pth.tar')\n\n        if isfile(resume_ckpt):\n            print(\"=> loading checkpoint '{}'\".format(resume_ckpt))\n            checkpoint = torch.load(resume_ckpt, map_location=lambda storage, loc: storage)\n            opt.start_epoch = checkpoint['epoch']\n            best_metric = checkpoint['best_score']\n            model.load_state_dict(checkpoint['state_dict'])\n            model = model.to(device)\n            if opt.mode == 'train':\n                optimizer.load_state_dict(checkpoint['optimizer'])\n            print(\"=> loaded checkpoint '{}' (epoch {})\"\n                  .format(resume_ckpt, checkpoint['epoch']))\n        else:\n            print(\"=> no checkpoint found at '{}'\".format(resume_ckpt))\n\n    bp()\n    if opt.mode.lower() == 'test':\n        print('===> Running evaluation step')\n        epoch = 1\n        recalls = test(whole_test_set, epoch, write_tboard=False)\n    elif opt.mode.lower() == 'cluster':\n        print('===> Calculating descriptors and clusters')\n        get_clusters(whole_train_set)\n    elif opt.mode.lower() == 'train':\n        print('===> Training model')\n        writer = SummaryWriter(log_dir=join(opt.runsPath, datetime.now().strftime('%b%d_%H-%M-%S')+'_'+opt.arch+'_'+opt.pooling))\n\n        # write checkpoints in logdir\n        logdir = writer.file_writer.get_logdir()\n        opt.savePath = join(logdir, opt.savePath)\n        if not opt.resume:\n            makedirs(opt.savePath)\n\n        with open(join(opt.savePath, 'flags.json'), 'w') as f:\n            f.write(json.dumps(\n                {k:v for k,v in vars(opt).items()}\n                ))\n        print('===> Saving state to:', logdir)\n\n        not_improved = 0\n        best_score = 0\n        for epoch in range(opt.start_epoch+1, opt.nEpochs + 1):\n            if opt.optim.upper() == 'SGD':\n                scheduler.step(epoch)\n            train(epoch)\n            if (epoch % opt.evalEvery) == 0:\n                recalls = test(whole_test_set, epoch, write_tboard=True)\n                is_best = recalls[5] > best_score \n                if is_best:\n                    not_improved = 0\n                    best_score = recalls[5]\n                else: \n                    not_improved += 1\n\n                save_checkpoint({\n                        'epoch': epoch,\n                        'state_dict': model.state_dict(),\n                        'recalls': recalls,\n                        'best_score': best_score,\n                        'optimizer' : optimizer.state_dict(),\n                        'parallel' : isParallel,\n                }, is_best)\n\n                if opt.patience > 0 and not_improved > (opt.patience / opt.evalEvery):\n                    print('Performance did not improve for', opt.patience, 'epochs. Stopping.')\n                    break\n\n        print(\"=> Best Recall@5: {:.4f}\".format(best_score), flush=True)\n        writer.close()\n", "meta": {"hexsha": "1f8a24eef9a26f1e5b9e7dd24300ae2c2e0c781c", "size": 24787, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/vps/netvlad/main.py", "max_stars_repo_name": "deepguider/RoadGPS", "max_stars_repo_head_hexsha": "7db4669a54da98a854886b89b6922fb8c7a60f33", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-05-22T12:47:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-23T15:43:47.000Z", "max_issues_repo_path": "src/vps/netvlad/main.py", "max_issues_repo_name": "deepguider/RoadGPS", "max_issues_repo_head_hexsha": "7db4669a54da98a854886b89b6922fb8c7a60f33", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vps/netvlad/main.py", "max_forks_repo_name": "deepguider/RoadGPS", "max_forks_repo_head_hexsha": "7db4669a54da98a854886b89b6922fb8c7a60f33", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-09T06:50:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-09T06:50:46.000Z", "avg_line_length": 44.8227848101, "max_line_length": 152, "alphanum_fraction": 0.6049945536, "include": true, "reason": "import numpy", "num_tokens": 5816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.1722708591215669}}
{"text": "from hierarc.Likelihood.transformed_cosmography import TransformedCosmography\nfrom hierarc.Likelihood.LensLikelihood.base_lens_likelihood import LensLikelihoodBase\nfrom hierarc.Likelihood.anisotropy_scaling import AnisotropyScalingIFU\nfrom hierarc.Util.distribution_util import PDFSampling\nimport numpy as np\nimport copy\n\n\nclass LensLikelihood(TransformedCosmography, LensLikelihoodBase, AnisotropyScalingIFU):\n    \"\"\"\n    master class containing the likelihood definitions of different analysis\n    \"\"\"\n    def __init__(self, z_lens, z_source, name='name', likelihood_type='TDKin', anisotropy_model='NONE',\n                 ani_param_array=None, ani_scaling_array_list=None, ani_scaling_array=None,\n                 num_distribution_draws=50, kappa_ext_bias=False, kappa_pdf=None, kappa_bin_edges=None, mst_ifu=False,\n                 lambda_scaling_property=0, **kwargs_likelihood):\n        \"\"\"\n\n        :param z_lens: lens redshift\n        :param z_source: source redshift\n        :param name: string (optional) to name the specific lens\n        :param likelihood_type: string to specify the likelihood type\n        :param ani_param_array: array of anisotropy parameter values for which the kinematics are predicted\n        :param ani_scaling_array: velocity dispersion sigma**2 scaling (also J scaling) of anisotropy parameter relative\n         to default prediction. The scaling corresponds to the ani_param_array parameter spacing\n         (to generate an interpolation function). A value =1 in ani_scaling_array results in the value stored in the\n         provided J() predictions.\n        :param ani_scaling_array_list: list of array with the scalings of J() for each IFU\n        :param num_distribution_draws: int, number of distribution draws from the likelihood that are being averaged over\n        :param kappa_ext_bias: bool, if True incorporates the global external selection function into the likelihood.\n        If False, the likelihood needs to incorporate the individual selection function with sufficient accuracy.\n        :param kappa_pdf: array of probability density function of the external convergence distribution\n         binned according to kappa_bin_edges\n        :param kappa_bin_edges: array of length (len(kappa_pdf)+1), bin edges of the kappa PDF\n        :param mst_ifu: bool, if True replaces the lambda_mst parameter by the lambda_ifu parameter (and distribution)\n         in sampling this lens.\n        :param lambda_scaling_property: float (optional), scaling of lambda_mst = lambda_mst_global + alpha * lambda_scaling_property\n        :param kwargs_likelihood: keyword arguments specifying the likelihood function,\n        see individual classes for their use\n        \"\"\"\n        TransformedCosmography.__init__(self, z_lens=z_lens, z_source=z_source)\n        if ani_scaling_array_list is None and ani_scaling_array is not None:\n            ani_scaling_array_list = [ani_scaling_array]\n        AnisotropyScalingIFU.__init__(self, anisotropy_model=anisotropy_model, ani_param_array=ani_param_array,\n                                      ani_scaling_array_list=ani_scaling_array_list)\n        LensLikelihoodBase.__init__(self, z_lens=z_lens, z_source=z_source, likelihood_type=likelihood_type, name=name,\n                                    **kwargs_likelihood)\n        self._num_distribution_draws = int(num_distribution_draws)\n        self._kappa_ext_bias = kappa_ext_bias\n        self._mst_ifu = mst_ifu\n        if kappa_pdf is not None and kappa_bin_edges is not None:\n            self._kappa_dist = PDFSampling(bin_edges=kappa_bin_edges, pdf_array=kappa_pdf)\n            self._draw_kappa = True\n        else:\n            self._draw_kappa = False\n        self._lambda_scaling_property = lambda_scaling_property\n\n    def lens_log_likelihood(self, cosmo, kwargs_lens=None, kwargs_kin=None, kwargs_source=None):\n        \"\"\"\n\n        :param cosmo: astropy.cosmology instance\n        :param kwargs_lens: keywords of the hyper parameters of the lens model\n        :param kwargs_kin: keyword arguments of the kinematic model hyper parameters\n        :param kwargs_source: keyword argument of the source model (such as SNe)\n        :return: log likelihood of the data given the model\n        \"\"\"\n\n        # here we compute the unperturbed angular diameter distances of the lens system given the cosmology\n        # Note: Distances are in physical units of Mpc. Make sure the posteriors to evaluate this likelihood is in the\n        # same units\n        ddt, dd = self.angular_diameter_distances(cosmo)\n        delta_lum_dist = self.luminosity_distance_modulus(cosmo)\n        # here we effectively change the posteriors of the lens, but rather than changing the instance of the KDE we\n        # displace the predicted angular diameter distances in the opposite direction\n        return self.hyper_param_likelihood(ddt, dd, delta_lum_dist, kwargs_lens=kwargs_lens, kwargs_kin=kwargs_kin,\n                                           kwargs_source=kwargs_source)\n\n    def hyper_param_likelihood(self, ddt, dd, delta_lum_dist, kwargs_lens=None, kwargs_kin=None, kwargs_source=None):\n        \"\"\"\n\n        :param ddt: time-delay distance\n        :param dd: angular diameter distance to the deflector\n        :param delta_lum_dist: relative luminosity distance to pivot redshift\n        :param kwargs_lens: keywords of the hyper parameters of the lens model\n        :param kwargs_kin: keyword arguments of the kinematic model hyper parameters\n        :param kwargs_source: keyword argument of the source model (such as SNe)\n        :return: log likelihood given the single lens analysis for the given hyper parameter\n        \"\"\"\n        kwargs_lens = self._kwargs_init(kwargs_lens)\n        kwargs_kin = self._kwargs_init(kwargs_kin)\n        kwargs_source = self._kwargs_init(kwargs_source)\n        kwargs_kin_copy = copy.deepcopy(kwargs_kin)\n        sigma_v_sys_error = kwargs_kin_copy.pop('sigma_v_sys_error', None)\n\n        if self.check_dist(kwargs_lens, kwargs_kin, kwargs_source):  # sharp distributions\n            return self.log_likelihood_single(ddt, dd, delta_lum_dist, kwargs_lens, kwargs_kin_copy, kwargs_source,\n                                              sigma_v_sys_error=sigma_v_sys_error)\n        else:\n            likelihood = 0\n            for i in range(self._num_distribution_draws):\n                logl = self.log_likelihood_single(ddt, dd, delta_lum_dist, kwargs_lens, kwargs_kin_copy, kwargs_source,\n                                                  sigma_v_sys_error=sigma_v_sys_error)\n                exp_logl = np.exp(logl)\n                if np.isfinite(exp_logl) and exp_logl > 0:\n                    likelihood += exp_logl\n            if likelihood <= 0:\n                return -np.inf\n            return np.log(likelihood/self._num_distribution_draws)\n\n    def log_likelihood_single(self, ddt, dd, delta_lum_dist, kwargs_lens, kwargs_kin, kwargs_source, sigma_v_sys_error=None):\n        \"\"\"\n\n        :param ddt: time-delay distance\n        :param dd: angular diameter distance to the deflector\n        :param delta_lum_dist: relative luminosity distance to pivot redshift\n        :param kwargs_lens: keywords of the hyper parameters of the lens model\n        :param kwargs_kin: keyword arguments of the kinematic model hyper parameters\n        :param kwargs_source: keyword arguments of source brightness\n        :param sigma_v_sys_error: unaccounted uncertainty in the velocity dispersion measurement\n        :return: log likelihood given the single lens analysis for a single (random) realization of the hyper parameter distribution\n        \"\"\"\n        lambda_mst, kappa_ext, gamma_ppn = self.draw_lens(**kwargs_lens)\n        # draw intrinsic source magnitude\n        mag_source = self.draw_source(lum_dist=delta_lum_dist, **kwargs_source)\n        ddt_, dd_, mag_source_ = self.displace_prediction(ddt, dd, gamma_ppn=gamma_ppn, lambda_mst=lambda_mst,\n                                                          kappa_ext=kappa_ext, mag_source=mag_source)\n        aniso_param_array = self.draw_anisotropy(**kwargs_kin)\n        aniso_scaling = self.ani_scaling(aniso_param_array)\n\n        lnlikelihood = self.log_likelihood(ddt_, dd_, aniso_scaling=aniso_scaling, sigma_v_sys_error=sigma_v_sys_error,\n                                           mu_intrinsic=mag_source_)\n        return lnlikelihood\n\n    def angular_diameter_distances(self, cosmo):\n        \"\"\"\n        time-delay distance Ddt, angular diameter distance to the lens (dd)\n\n        :param cosmo: astropy.cosmology instance (or equivalent with interpolation)\n        :return: ddt, dd, ds in units physical Mpc\n        \"\"\"\n        dd = cosmo.angular_diameter_distance(z=self._z_lens).value\n        ds = cosmo.angular_diameter_distance(z=self._z_source).value\n        dds = cosmo.angular_diameter_distance_z1z2(z1=self._z_lens, z2=self._z_source).value\n        ddt = (1. + self._z_lens) * dd * ds / dds\n        return ddt, dd\n\n    def luminosity_distance_modulus(self, cosmo):\n        \"\"\"\n        the difference in luminosity distance between a pivot redshift (z=0.1) and the source redshift\n        (effectively the ratio as this is the magnitude transform)\n\n        :param cosmo: astropy.cosmology instance (or equivalent with interpolation)\n        :return: lum_dist(z_source) - lum_dist(z_pivot)\n        \"\"\"\n        angular_diameter_distances = cosmo.angular_diameter_distance(self._z_source).value\n        lum_dists = (5 * np.log10((1 + self._z_source) * (1 + self._z_source) * angular_diameter_distances))\n\n        z_anchor = 0.1\n        ang_dist_anchor = cosmo.angular_diameter_distance(z_anchor).value\n        lum_dist_anchor = (5 * np.log10((1 + z_anchor) * (1 + z_anchor) * ang_dist_anchor))\n        delta_lum_dist = lum_dists - lum_dist_anchor\n        return delta_lum_dist\n\n    def check_dist(self, kwargs_lens, kwargs_kin, kwargs_source):\n        \"\"\"\n        checks if the provided keyword arguments describe a distribution function of hyper parameters or are single\n        values\n\n        :param kwargs_lens: lens model hyper parameter keywords\n        :param kwargs_kin: kinematic model hyper parameter keywords\n        :param kwargs_source: source brightness hyper parameter keywords\n        :return: bool, True if delta function, else False\n        \"\"\"\n        lambda_mst_sigma = kwargs_lens.get('lambda_mst_sigma', 0)  # scatter in MST\n        kappa_ext_sigma = kwargs_lens.get('kappa_ext_sigma', 0)\n        a_ani_sigma = kwargs_kin.get('a_ani_sigma', 0)\n        beta_inf_sigma = kwargs_kin.get('beta_inf_sigma', 0)\n        sne_sigma = kwargs_source.get('sigma_sne', 0)\n        if a_ani_sigma == 0 and lambda_mst_sigma == 0 and kappa_ext_sigma == 0 and beta_inf_sigma == 0 and sne_sigma == 0:\n            if self._draw_kappa is False:\n                return True\n        return False\n\n    def draw_lens(self, lambda_mst=1, lambda_mst_sigma=0, kappa_ext=0, kappa_ext_sigma=0, gamma_ppn=1, lambda_ifu=1,\n                  lambda_ifu_sigma=0, alpha_lambda=0):\n        \"\"\"\n\n        :param lambda_mst: MST transform\n        :param lambda_mst_sigma: spread in the distribution\n        :param kappa_ext: external convergence mean in distribution\n        :param kappa_ext_sigma: spread in the distribution\n        :param gamma_ppn: Post-Newtonian parameter\n        :param lambda_ifu: secondary lambda_mst parameter for subset of lenses specified for\n        :param lambda_ifu_sigma: secondary lambda_mst_sigma parameter for subset of lenses specified for\n        :param alpha_lambda: float, linear slope of the lambda_int scaling relation with lens quantity self._lambda_scaling_property\n        :return: draw from the distributions\n        \"\"\"\n        if self._mst_ifu is True:\n            lambda_lens = lambda_ifu + alpha_lambda * self._lambda_scaling_property\n            lambda_mst_draw = np.random.normal(lambda_lens, lambda_ifu_sigma)\n        else:\n            lambda_lens = lambda_mst + alpha_lambda * self._lambda_scaling_property\n            lambda_mst_draw = np.random.normal(lambda_lens, lambda_mst_sigma)\n        if self._draw_kappa is True:\n            kappa_ext_draw = self._kappa_dist.draw_one\n        elif self._kappa_ext_bias is True:\n            kappa_ext_draw = np.random.normal(kappa_ext, kappa_ext_sigma)\n        else:\n            kappa_ext_draw = 0\n        return lambda_mst_draw, kappa_ext_draw, gamma_ppn\n\n    @staticmethod\n    def draw_source(mu_sne=1, sigma_sne=0, lum_dist=0):\n        \"\"\"\n\n        :param mu_sne: mean brightness of SNe\n        :param sigma_sne: std of brightness distribution of SNe relative to the mean brightness\n        :param lum_dist: luminosity distance\n        (astronomical magnitude scaling of defined brightness to the source redshift)\n        :return: realization of source amplitude given distribution\n        \"\"\"\n        # draw apparent magnitude at pivot luminosity distance (z=0.1)\n        mag_draw = np.random.normal(loc=mu_sne, scale=sigma_sne/mu_sne)\n        # move apparent magnitude to redshift of source with relative luminosity distance\n        mag_source = mag_draw + lum_dist\n        # return linear amplitude with base log 10\n        return mag_source\n\n    def sigma_v_measured_vs_predict(self, cosmo, kwargs_lens={}, kwargs_kin={}):\n        \"\"\"\n        mean and error covariance of velocity dispersion measurement\n        mean and error covariance of velocity dispersion predictions\n\n        :param cosmo: astropy.cosmology instance\n        :param kwargs_lens: keywords of the hyper parameters of the lens model\n        :param kwargs_kin: keyword arguments of the kinematic model hyper parameters\n        :return: sigma_v_measurement, cov_error_measurement, sigma_v_predict_mean, cov_error_predict\n        \"\"\"\n        # if no kinematics is provided, return None's\n        if not self.likelihood_type in ['DdtHistKin', 'IFUKinCov', 'DdtGaussKin']:\n            return None, None, None, None\n        kwargs_kin_copy = copy.deepcopy(kwargs_kin)\n        sigma_v_sys_error = kwargs_kin_copy.pop('sigma_v_sys_error', None)\n        ddt, dd = self.angular_diameter_distances(cosmo)\n        sigma_v_measurement, cov_error_measurement = self.sigma_v_measurement(sigma_v_sys_error=sigma_v_sys_error)\n        sigma_v_predict_list = []\n        sigma_v_predict_mean = np.zeros_like(sigma_v_measurement)\n        cov_error_predict = np.zeros_like(cov_error_measurement)\n        for i in range(self._num_distribution_draws):\n            lambda_mst, kappa_ext, gamma_ppn = self.draw_lens(**kwargs_lens)\n            ddt_, dd_, _ = self.displace_prediction(ddt, dd, gamma_ppn=gamma_ppn, lambda_mst=lambda_mst,\n                                                    kappa_ext=kappa_ext)\n            aniso_param_array = self.draw_anisotropy(**kwargs_kin_copy)\n            aniso_scaling = self.ani_scaling(aniso_param_array)\n            sigma_v_predict_i, cov_error_predict_i = self.sigma_v_prediction(ddt_, dd_, aniso_scaling=aniso_scaling)\n            sigma_v_predict_mean += sigma_v_predict_i\n            cov_error_predict += cov_error_predict_i\n            sigma_v_predict_list.append(sigma_v_predict_i)\n\n        sigma_v_predict_mean /= self._num_distribution_draws\n        cov_error_predict /= self._num_distribution_draws\n        sigma_v_mean_std = np.std(sigma_v_predict_list, axis=0)\n        cov_error_predict += np.outer(sigma_v_mean_std, sigma_v_mean_std)\n        return sigma_v_measurement, cov_error_measurement, sigma_v_predict_mean, cov_error_predict\n\n    def ddt_dd_model_prediction(self, cosmo, kwargs_lens={}):\n        \"\"\"\n        predicts the model uncertainty corrected ddt prediction of the applied model (e.g. power-law)\n\n        :param cosmo: astropy.cosmology instance\n        :param kwargs_lens: keywords of the hyper parameters of the lens model\n        :return: ddt_model mean, ddt_model sigma, dd_model mean, dd_model sigma\n        \"\"\"\n        ddt, dd = self.angular_diameter_distances(cosmo)\n        ddt_draws = []\n        dd_draws = []\n        for i in range(self._num_distribution_draws):\n            lambda_mst, kappa_ext, gamma_ppn = self.draw_lens(**kwargs_lens)\n            ddt_, dd_, _ = self.displace_prediction(ddt, dd, gamma_ppn=gamma_ppn, lambda_mst=lambda_mst,\n                                                    kappa_ext=kappa_ext)\n            ddt_draws.append(ddt_)\n            dd_draws.append(dd_)\n        return np.mean(ddt_draws), np.std(ddt_draws), np.mean(dd_draws), np.std(dd_draws)\n\n    @staticmethod\n    def _kwargs_init(kwargs=None):\n        \"\"\"\n\n        :param kwargs: keyword argument or None\n        :return: keyword argument\n        \"\"\"\n        if kwargs is None:\n            kwargs = {}\n        return kwargs\n\n", "meta": {"hexsha": "e09d0e5174760391d6bc84231fc96bbf42ebfbfd", "size": 16635, "ext": "py", "lang": "Python", "max_stars_repo_path": "hierarc/Likelihood/hierarchy_likelihood.py", "max_stars_repo_name": "aymgal/hierArc", "max_stars_repo_head_hexsha": "a52cb6f2ad1d7a8cbd08c215ef7d5189fa329269", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hierarc/Likelihood/hierarchy_likelihood.py", "max_issues_repo_name": "aymgal/hierArc", "max_issues_repo_head_hexsha": "a52cb6f2ad1d7a8cbd08c215ef7d5189fa329269", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hierarc/Likelihood/hierarchy_likelihood.py", "max_forks_repo_name": "aymgal/hierArc", "max_forks_repo_head_hexsha": "a52cb6f2ad1d7a8cbd08c215ef7d5189fa329269", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.1993243243, "max_line_length": 133, "alphanum_fraction": 0.695581605, "include": true, "reason": "import numpy", "num_tokens": 3710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.2751297297667525, "lm_q1q2_score": 0.17226537568125336}}
{"text": "\"\"\"\nCode implement MEMR in https://arxiv.org/abs/2006.04802\n\"\"\"\n\nfrom typing import Callable\nfrom typing import Dict\n\nimport gym\nimport numpy as np\nimport rlutils.algos.tf.mf.sac as sac\nimport rlutils.infra as rl_infra\nimport rlutils.np as rln\nimport rlutils.replay_buffers as replay_buffers\nimport rlutils.tf as rlu\nimport tensorflow as tf\n\n\nclass PyPrioritizedReplayBuffer(replay_buffers.DictPrioritizedReplayBuffer):\n    def reset(self):\n        super(PyPrioritizedReplayBuffer, self).reset()\n        self.last_priority_ptr = 0\n\n    def get_priority_uninitialized_data(self):\n        idx = np.arange(self.last_priority_ptr, len(self))\n        self.last_priority_ptr = len(self)\n        return idx, self.__getitem__(idx)\n\n\nclass SegmentReplayBuffer(replay_buffers.DictReplayBuffer):\n    \"\"\"\n    When adding, the input size must be equal to the segment size.\n    When sampling, first sample a segment, then sample the data.\n    \"\"\"\n\n    def __init__(self, segment_size, *args, **kwargs):\n        self.segment_size = segment_size\n        super(SegmentReplayBuffer, self).__init__(*args, **kwargs)\n\n    def add(self, data: Dict[str, np.ndarray]):\n        batch_size = list(data.values())[0].shape[0]\n        assert batch_size == self.segment_size\n        super(SegmentReplayBuffer, self).add(data=data)\n\n    def sample(self):\n        assert not self.is_empty()\n        num_segment = len(self) // self.segment_size\n        segment_idx = self.np_random.randint(num_segment)\n        start = segment_idx * self.segment_size\n        end = (segment_idx + 1) * self.segment_size\n        idx_range = np.arange(start, end)\n        idxs = self.np_random.choice(idx_range, size=self.batch_size)\n        return self.__getitem__(idxs)\n\n\nclass MEMRUpdater(rl_infra.OffPolicyUpdater):\n    def __init__(self, total_steps, model_update_every, model_replay_buffer, model_rollout_freq,\n                 **kwargs):\n        super(MEMRUpdater, self).__init__(**kwargs)\n        self.total_steps = total_steps\n        self.model_update_every = model_update_every\n        self.model_replay_buffer = model_replay_buffer\n        self.model_rollout_freq = model_rollout_freq\n        self.beta_scheduler = rln.schedulers.LinearSchedule(total_steps, initial_p=0.4, final_p=1.0)\n        self.update_scheduler = rln.schedulers.LinearSchedule(total_steps, initial_p=1,\n                                                              final_p=self.update_per_step)\n\n    def log_tabular(self):\n        super(MEMRUpdater, self).log_tabular()\n        self.logger.log_tabular('Priority', with_min_and_max=True)\n\n    def update(self, global_step):\n        if global_step % self.model_update_every == 0:\n            self.agent.update_model(self.replay_buffer.get())\n\n        if global_step % self.model_rollout_freq == 0:\n            # update uninitialized priority\n            idx, data = self.replay_buffer.get_priority_uninitialized_data()\n            priorities = self.agent.compute_priority(obs=data['obs'])\n            self.replay_buffer.update_priorities(idx, priorities)\n            # sample obs and unroll transitions.\n            data, idx = self.replay_buffer.sample(beta=self.beta_scheduler.value(global_step))\n            transitions = self.agent.unroll_trajectory(data['obs'])\n            transitions['weights'] = data['weights'] / np.mean(data['weights'])\n            self.agent.behavior_policy.train_on_batch(x=transitions['obs'],\n                                                      y=transitions['act'])\n            # update the priority after update the behavior policy\n            priorities = self.agent.compute_priority(obs=transitions['obs']).numpy()\n            self.replay_buffer.update_priorities(idx, priorities)\n            self.logger.store(Priority=priorities)\n            # add transitions to the model_replay_buffer\n            transitions = rlu.functional.to_numpy_or_python_type(transitions)\n            self.model_replay_buffer.add(transitions)\n\n        if global_step % self.update_every == 0:\n            update_per_step = int(self.update_scheduler.value(global_step))\n            for _ in range(self.update_every):\n                for _ in range(update_per_step):\n                    batch = self.model_replay_buffer.sample()\n                    batch['update_target'] = ((self.policy_updates + 1) % self.policy_delay == 0)\n                    self.agent.train_on_batch(data=batch)\n                    self.policy_updates += 1\n\n\nclass SquashedGaussianMLPActor(rlu.nn.SquashedGaussianMLPActor):\n    @tf.function\n    def compute_log_prob_and_log_std(self, obs, raw_actions):\n        pi_distribution = self((obs, tf.constant(False)))[-1]\n        logp_pi = pi_distribution.log_prob(raw_actions)\n        log_std = tf.reduce_mean(tf.math.log(pi_distribution.stddev()), axis=-1)\n        return logp_pi / self.ac_dim, log_std\n\n\nclass MEMRAgent(tf.keras.Model):\n    def __init__(self, obs_spec, act_spec,\n                 model_mlp_hidden=512, model_lr=1e-3, model_num_ensembles=5, reward_fn=None, terminate_fn=None,\n                 policy_mlp_hidden=256, policy_lr=3e-4):\n        super(MEMRAgent, self).__init__()\n        self.obs_spec = obs_spec\n        self.act_spec = act_spec\n        self.act_dim = self.act_spec.shape[0]\n        if len(self.obs_spec.shape) == 1:  # 1D observation\n            self.obs_dim = self.obs_spec.shape[0]\n        else:\n            raise NotImplementedError\n        self.dynamics_model = rlu.nn.EnsembleWorldModel(obs_dim=self.obs_dim, act_dim=self.act_dim,\n                                                        mlp_hidden=model_mlp_hidden, num_layers=4,\n                                                        num_ensembles=model_num_ensembles, lr=model_lr,\n                                                        reward_fn=reward_fn, terminate_fn=terminate_fn)\n        self.agent = sac.SACAgent(obs_spec=obs_spec, act_spec=act_spec, policy_mlp_hidden=policy_mlp_hidden,\n                                  policy_lr=policy_lr, q_mlp_hidden=policy_mlp_hidden, q_lr=policy_lr, alpha=1.0,\n                                  alpha_lr=policy_lr, tau=5e-3, gamma=0.99, target_entropy=-(self.act_dim // 2),\n                                  auto_alpha=True)\n        self.behavior_policy = SquashedGaussianMLPActor(ob_dim=self.obs_dim, ac_dim=self.act_dim,\n                                                        mlp_hidden=policy_mlp_hidden)\n        self.behavior_policy.compile(optimizer=rlu.future.get_adam_optimizer(policy_lr))\n\n    def set_logger(self, logger):\n        self.dynamics_model.set_logger(logger)\n        self.agent.set_logger(logger)\n\n    def log_tabular(self):\n        self.agent.log_tabular()\n        self.dynamics_model.log_tabular()\n\n    @tf.function\n    def compute_priority(self, obs):\n        raw_actions = self.agent.policy_net((obs, tf.constant(False)))[2]\n        logp_pi, log_std = self.behavior_policy.compute_log_prob_and_log_std(obs, raw_actions)\n        constant = 0.5 * np.log(2. * np.pi)\n        priorities = -(logp_pi + log_std + constant)\n        priorities = tf.clip_by_value(priorities, clip_value_min=1e-4, clip_value_max=50.)\n        return priorities\n\n    def update_model(self, data):\n        self.dynamics_model.update(inputs=data, sample_weights=None, batch_size=512, num_epochs=100,\n                                   patience=5, validation_split=0.1, shuffle=True)\n\n    @tf.function\n    def unroll_trajectory(self, obs):\n        act = self.agent.act_batch_explore_tf(obs)\n        next_obs, rew, done = self.dynamics_model.predict_on_batch_tf(obs, act)\n        done = tf.cast(done, tf.float32)\n        return dict(\n            obs=obs,\n            act=act,\n            next_obs=next_obs,\n            rew=rew,\n            done=done\n        )\n\n    def train_on_batch(self, data, **kwargs):\n        return self.agent.train_on_batch(data=data)\n\n    def act_batch_explore(self, obs):\n        return self.agent.act_batch_explore(obs)\n\n    def act_batch_test(self, obs):\n        return self.agent.act_batch_test(obs)\n\n\nclass Runner(rl_infra.runner.TFOffPolicyRunner):\n    def on_epoch_end(self, epoch):\n        self.tester.test_agent(get_action=lambda obs: self.agent.act_batch_test(obs),\n                               name=self.agent.__class__.__name__,\n                               num_test_episodes=self.num_test_episodes)\n        # Log info about epoch\n        self.logger.log_tabular('Epoch', epoch)\n        self.tester.log_tabular()\n        self.sampler.log_tabular()\n        self.updater.log_tabular()\n        self.logger.log_tabular(key='EnvDatsetSize', val=len(self.replay_buffer))\n        self.logger.log_tabular(key='ModelDatasetSize', val=len(self.model_replay_buffer))\n        self.timer.log_tabular()\n        self.logger.dump_tabular()\n\n    def setup_updater(self, update_after, policy_delay, update_per_step, update_every, model_rollout_freq=None):\n        self.update_after = update_after\n        self.updater = MEMRUpdater(total_steps=self.epochs * self.steps_per_epoch,\n                                   model_update_every=self.steps_per_epoch // 4,\n                                   agent=self.agent,\n                                   replay_buffer=self.replay_buffer,\n                                   model_replay_buffer=self.model_replay_buffer,\n                                   model_rollout_freq=model_rollout_freq,\n                                   policy_delay=policy_delay,\n                                   update_per_step=update_per_step,\n                                   update_every=update_every\n                                   )\n\n    def setup_agent(self, **kwargs):\n        from rlutils.gym import static\n        static_fn = static.get_static_fn(self.env_name)\n        self.agent = MEMRAgent(obs_spec=self.env.single_observation_space,\n                               act_spec=self.env.single_action_space,\n                               reward_fn=None,\n                               terminate_fn=static_fn.terminate_fn_tf_batch,\n                               **kwargs)\n\n    def setup_replay_buffer(self, replay_size, batch_size, segment_size=None):\n        segment_size = segment_size\n        self.seeds_info['replay_buffer'] = self.seeder.generate_seed()\n        self.seeds_info['model_replay_buffer'] = self.seeder.generate_seed()\n        self.replay_buffer = PyPrioritizedReplayBuffer.from_vec_env(vec_env=self.env, capacity=replay_size,\n                                                                    batch_size=segment_size, alpha=0.6,\n                                                                    seed=self.seeds_info['replay_buffer'])\n        data_spec = {\n            'obs': self.env.single_observation_space,\n            'act': self.env.single_action_space,\n            'next_obs': self.env.single_observation_space,\n            'rew': gym.spaces.Space(shape=None, dtype=np.float32),\n            'done': gym.spaces.Space(shape=None, dtype=np.float32),\n            'weights': gym.spaces.Space(shape=None, dtype=np.float32)\n        }\n        self.model_replay_buffer = SegmentReplayBuffer(data_spec=data_spec, capacity=replay_size,\n                                                       batch_size=batch_size,\n                                                       seed=self.seeds_info['model_replay_buffer'],\n                                                       segment_size=segment_size)\n\n    @classmethod\n    def main(cls,\n             env_name,\n             env_fn: Callable = None,\n             exp_name: str = None,\n             steps_per_epoch=1000,\n             epochs=100,\n             start_steps=3000,\n             update_after=750,\n             update_every=50,\n             update_per_step=20,\n             policy_delay=1,\n             batch_size=4000,\n             model_rollout_freq=50,\n             num_model_rollouts=400,\n             num_parallel_env=1,\n             num_test_episodes=30,\n             seed=1,\n             # agent\n             model_mlp_hidden=512,\n             model_lr=1e-3,\n             model_num_ensembles=5,\n             policy_mlp_hidden=256,\n             policy_lr=3e-4,\n             # replay\n             replay_size=int(1e6),\n             logger_path='data'\n             ):\n        config = locals()\n        runner = cls(seed=seed, steps_per_epoch=steps_per_epoch, epochs=epochs, exp_name=None,\n                     logger_path=logger_path)\n        runner.setup_env(env_name=env_name, env_fn=env_fn, num_parallel_env=1, asynchronous=False,\n                         num_test_episodes=num_test_episodes)\n        agent_kwargs = dict(\n\n        )\n        runner.setup_agent(**agent_kwargs)\n        runner.setup_replay_buffer(replay_size=replay_size,\n                                   batch_size=batch_size,\n                                   segment_size=num_model_rollouts * model_rollout_freq\n                                   )\n        runner.setup_sampler(start_steps=start_steps)\n        runner.setup_tester(num_test_episodes=num_test_episodes)\n        runner.setup_updater(update_after=update_after,\n                             policy_delay=policy_delay,\n                             update_per_step=update_per_step,\n                             update_every=update_every,\n                             model_rollout_freq=model_rollout_freq)\n        runner.setup_logger(config=config, tensorboard=False)\n        runner.run()\n\n\nif __name__ == '__main__':\n    rl_infra.runner.run_func_as_main(Runner.main)\n", "meta": {"hexsha": "50b226b2e4960bd80e6a3eb441131f9532969901", "size": 13371, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/memr.py", "max_stars_repo_name": "vermouth1992/rl-util", "max_stars_repo_head_hexsha": "4c06ab8f5c96a44e58f88cf30146bcb837057112", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/memr.py", "max_issues_repo_name": "vermouth1992/rl-util", "max_issues_repo_head_hexsha": "4c06ab8f5c96a44e58f88cf30146bcb837057112", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/memr.py", "max_forks_repo_name": "vermouth1992/rl-util", "max_forks_repo_head_hexsha": "4c06ab8f5c96a44e58f88cf30146bcb837057112", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.7910958904, "max_line_length": 113, "alphanum_fraction": 0.610649914, "include": true, "reason": "import numpy", "num_tokens": 2767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.1722368831182616}}
{"text": "\"\"\"\ngauge_dynamics.py\n\nImplements the GaugeDynamics class by subclassing the `BaseDynamics` class.\n\nReference [Generalizing Hamiltonian Monte Carlo with Neural\nNetworks](https://arxiv.org/pdf/1711.09268.pdf)\n\nCode adapted from the released TensorFlow graph implementation by original\nauthors https://github.com/brain-research/l2hmc.\n\nReference [Robust Parameter Estimation with a Neural Network Enhanced\nHamiltonian Markov Chain Monte Carlo Sampler]\nhttps://infoscience.epfl.ch/record/264887/files/robust_parameter_estimation.pdf\n\nAuthor: Sam Foreman (github: @saforem2)\nDate: 7/3/2020\n\"\"\"\n# noqa:401\n# pylint:disable=no-name-in-module\n# pylint:disable=too-many-instance-attributes,too-many-locals\n# pylint:disable=invalid-name,too-many-arguments,too-many-ancestors\n# pylint:disable=unused-import,unused-argument,attribute-defined-outside-init\nfrom __future__ import absolute_import, division, print_function, annotations\nfrom dataclasses import asdict\nfrom pathlib import Path\n\nimport sys\nimport os\nimport json\nimport time\n\nfrom math import pi\nfrom typing import Any, Optional, Tuple, Union\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.python.keras import backend as K\n\nfrom utils.hvd_init import SIZE, RANK, LOCAL_RANK, HAS_HOROVOD\n\n\ntry:\n    import horovod.tensorflow as hvd\n    COMPRESS = True\n    HAS_HOROVOD = True\nexcept ImportError:\n    from utils import Horovod as hvd\n    HAS_HOROVOD = False\n    COMPRESS = False\n\n\nhere = os.path.dirname(__file__)\nparent = os.path.abspath(os.path.dirname(here))\nif parent not in sys.path:\n    sys.path.append(parent)\n\n\nimport utils.file_io as io\nfrom utils.logger import Logger\n\nfrom config import BIN_DIR\nfrom lattice.gauge_lattice import GaugeLattice, Charges, area_law\nfrom utils.attr_dict import AttrDict\nfrom utils.seed_dict import vnet_seeds  # noqa:F401\nfrom utils.seed_dict import xnet_seeds  # noqa:F401\nfrom network.config import (ConvolutionConfig, LearningRateConfig,\n                            NetworkConfig)\nfrom network.functional_net import get_gauge_network\nfrom dynamics.config import GaugeDynamicsConfig\nfrom dynamics.base_dynamics import (BaseDynamics, MonteCarloStates, NetWeights,\n                                    State)\n\nTIMING_FILE = os.path.join(BIN_DIR, 'timing_file.log')\nTF_FLOAT = tf.keras.backend.floatx()\n\nlogger = Logger()\n\nPI = pi\nTWO_PI = 2. * PI\n\ndef project_angle(x: tf.Tensor) -> tf.Tensor:\n    \"\"\"Returns the projection of an angle `x` from [-4pi, 4pi] to [-pi, pi].\"\"\"\n    return x - TWO_PI * tf.math.floor((x + PI) / TWO_PI)\n\n\ndef convert_to_angle(x: tf.Tensor) -> tf.Tensor:\n    \"\"\"Returns x in -pi <= x < pi.\"\"\"\n    x = tf.math.floormod(x + PI, TWO_PI) - PI\n    return x\n\n\ndef build_test_dynamics() -> GaugeDynamics:\n    \"\"\"Build quick test dynamics for debugging.\"\"\"\n    jfile = os.path.abspath(os.path.join(BIN_DIR, 'test_dynamics_flags.json'))\n    with open(jfile, 'rt') as f:\n        flags = json.load(f)\n    flags = AttrDict(flags)\n    return build_dynamics(flags)\n\n\ndef build_dynamics(configs: dict[str, Any]) -> GaugeDynamics:\n    \"\"\"Build dynamics using configs from FLAGS.\"\"\"\n    config = GaugeDynamicsConfig(**dict(configs.get('dynamics_config', None)))\n\n    lr_config = None\n    if configs.get('lr_config', None) is not None:\n        lr_config = LearningRateConfig(**dict(configs.get('lr_config', None)))\n\n    net_config = None\n    if configs.get('network_config', None) is not None:\n        net_config = NetworkConfig(**dict(configs.get('network_config', None)))\n\n    conv_config = None\n    if configs.get('conv_config', None) is not None and config.use_conv_net:\n        conv_config = configs.get('conv_config', {})\n\n        if isinstance(conv_config, ConvolutionConfig):\n            conv_config = asdict(conv_config)\n\n        conv_config['input_shape'] = config.x_shape[1:]\n        if isinstance(conv_config, dict):\n            conv_config = ConvolutionConfig(**conv_config)\n\n    dynamics = GaugeDynamics(\n        params=configs,\n        config=config,\n        network_config=net_config,\n        lr_config=lr_config,\n        conv_config=conv_config,\n    )\n\n    return dynamics\n\n\nclass GaugeDynamics(BaseDynamics):\n    \"\"\"Implements the dynamics engine for the L2HMC sampler.\"\"\"\n\n    def __init__(\n            self,\n            params: AttrDict,\n            config: GaugeDynamicsConfig,\n            network_config: NetworkConfig = None,\n            lr_config: LearningRateConfig = None,\n            conv_config: ConvolutionConfig = None,\n    ):\n        # -- Set attributes from `config` -----------\n        self.aux_weight = config.aux_weight\n        self.plaq_weight = config.plaq_weight\n        self.charge_weight = config.charge_weight\n        self._gauge_eq_masks = config.gauge_eq_masks\n        self.lattice_shape = config.x_shape\n        self._xshape = config.x_shape\n        #  self.lattice_shape = config.lattice_shape\n        self._combined_updates = config.combined_updates\n        self._alpha = tf.constant(1.)\n\n        self.lattice = GaugeLattice(self.lattice_shape)\n        self.batch_size = self.lattice_shape[0]\n        self.xdim = np.cumprod(self.lattice_shape[1:])[-1]\n\n        self.config = config\n        self.lr_config = lr_config\n        self.conv_config = conv_config\n        self.net_config = network_config\n\n        if HAS_HOROVOD:\n            if COMPRESS:\n                self._fp16 = hvd.Compression.fp16\n            else:\n                self._fp16 = hvd.Compression.none\n        else:\n            self._fp16 = None\n\n        if not self.config.use_conv_net:\n            self.conv_config = None\n\n        params.update({\n            'batch_size': self.lattice_shape[0],\n            'xdim': np.cumprod(self.lattice_shape[1:])[-1],\n        })\n\n        super().__init__(\n            params=params,\n            config=config,\n            name='GaugeDynamics',\n            normalizer=convert_to_angle,\n            network_config=network_config,\n            lr_config=lr_config,\n            potential_fn=self.lattice.calc_actions,\n            should_build=False,\n        )\n        self._has_trainable_params = True\n        if self.config.hmc:\n            net_weights = NetWeights(0., 0., 0., 0., 0., 0.)\n            self.config.use_ncp = False\n            self.config.separate_networks = False\n            self.config.use_conv_net = False\n            if self.config.eps_fixed:\n                self._has_trainable_params = False\n\n            self.xnet, self.vnet = self._build_hmc_networks()\n\n        else:\n            if self.config.use_ncp:\n                net_weights = NetWeights(1., 1., 1., 1., 1., 1.)\n            else:\n                net_weights = NetWeights(0., 1., 1., 1., 1., 1.)\n\n            self.xnet, self.vnet = self._build_networks(\n                net_config=self.net_config,\n                conv_config=self.conv_config,\n            )\n\n        if self.config.net_weights is None:\n            self.net_weights = self._parse_net_weights(net_weights)\n        else:\n            net_weights = NetWeights(*self.config.net_weights)\n            self.net_weights = self._parse_net_weights(net_weights)\n\n        if not self.config.hmc and not self.config.eps_fixed:\n            self.lr_config = lr_config\n            self.lr = self._create_lr(lr_config, auto=True)\n            self.optimizer = self._create_optimizer()\n\n    def _set_net_weights(self, net_weights: NetWeights):\n        self.net_weights = net_weights\n        self._xsw = net_weights.x_scale\n        self._xtw = net_weights.x_translation\n        self._xqw = net_weights.x_transformation\n        self._vsw = net_weights.v_scale\n        self._vtw = net_weights.v_translation\n        self._vqw = net_weights.v_transformation\n\n    def _load_eps(self, log_dir: str):\n        \"\"\"Load xeps and veps from saved files.\"\"\"\n\n        models_dir = os.path.join(log_dir, 'training', 'models')\n        if not os.path.isdir(models_dir):\n            raise ValueError('Unable to locate `models_dir`: {models_dir}')\n\n        veps_file = os.path.join(models_dir, 'veps.z')\n        xeps_file = os.path.join(models_dir, 'xeps.z')\n        xeps = io.loadz(xeps_file)\n        veps = io.loadz(veps_file)\n\n        xeps = list(xeps)\n        veps = list(veps)\n\n        return xeps, veps\n\n    def _load_networks(self, log_dir: str) -> dict:\n        \"\"\"Load networks from `log_dir`.\n\n        Builds new networks if unable to load or\n        self.config.num_steps > # networks available to load.\n        \"\"\"\n        models_dir = os.path.join(log_dir, 'training', 'models')\n        if not self.config.separate_networks:\n            vp = os.path.join(models_dir, 'dynamics_vnet')\n            vnet = [tf.keras.models.load_model(vp)]\n\n            xp = os.path.join(models_dir, 'dynamics_xnet')\n            xnet = [tf.keras.models.load_model(xp)]\n        else:\n            xnet, vnet = [], []\n            for i in range(self.config.num_steps):\n                vp = os.path.join(models_dir, f'dynamics_vnet{i}')\n                logger.debug(f'Loading vnet{i}_second from: {vp}...')\n                vnet.append(tf.keras.models.load_model(vp))\n\n                # Check if xnet_first and xnet_second networks exist...\n                xp0 = os.path.join(models_dir, f'dynamics_xnet_first{i}')\n                xp1 = os.path.join(models_dir, f'dynamics_xnet_second{i}')\n                if os.path.isdir(xp0) and os.path.isdir(xp1):\n                    # If so, load them into `xnets_first`, `xnets_second`\n                    #  xnets_first.append(xp0)\n                    #  xnets_second.append(xp1)\n                    logger.debug(f'Loading xnet{i}_first from: {xp0}...')\n                    logger.debug(f'Loading xnet{i}_second from: {xp1}...')\n                    xnet.append(\n                        (tf.keras.models.load_model(xp0),\n                         tf.keras.models.load_model(xp1))\n                    )\n\n                else:\n                    xp = os.path.join(models_dir, f'dynamics_xnet{i}')\n                    xnet.append(tf.keras.models.load_model(xp))\n\n        return {'xnet': xnet, 'vnet': vnet}\n\n    def save_networks(self, log_dir):\n        \"\"\"Save networks to disk.\"\"\"\n        models_dir = os.path.join(log_dir, 'training', 'models')\n        io.check_else_make_dir(models_dir)\n        veps_file = os.path.join(models_dir, 'veps.z')\n        xeps_file = os.path.join(models_dir, 'xeps.z')\n\n        io.savez([e.numpy() for e in self.veps], veps_file, name='veps')\n        io.savez([e.numpy() for e in self.xeps], xeps_file, name='xeps')\n        if self.config.separate_networks:\n            xnet_first_paths = [\n                os.path.join(models_dir, f'dynamics_xnet_first{i}')\n                for i in range(self.config.num_steps)\n            ]\n            xnet_second_paths = [\n                os.path.join(models_dir, f'dynamics_xnet_second{i}')\n                for i in range(self.config.num_steps)\n            ]\n\n            vnet_paths = [\n                os.path.join(models_dir, f'dynamics_vnet{i}')\n                for i in range(self.config.num_steps)\n            ]\n\n            paths = zip(xnet_first_paths, xnet_second_paths, vnet_paths)\n            for idx, (xf0, xf1, vf) in enumerate(paths):\n                xnets = self.xnet[idx]  # type: tf.keras.models.Model\n                vnet = self.vnet[idx]  # type: tf.keras.models.Model\n                xnets[0].save(xf0)\n                xnets[1].save(xf1)\n                vnet.save(vf)\n        else:\n            xnet = self.xnet[0]  # type: tf.keras.models.Model\n            vnet = self.vnet[0]  # type: tf.keras.models.Model\n            xnet.save(os.path.join(models_dir, 'dynamics_xnet'))\n            vnet.save(os.path.join(models_dir, 'dynamics_vnet'))\n\n    def _get_network_configs(\n            self,\n            net_config: NetworkConfig,\n            conv_config: ConvolutionConfig\n    ):\n        \"\"\"Returns `cfgs` for passing to `get_gauge_network`.\"\"\"\n        if net_config is None:\n            net_config = self.net_config\n\n        if conv_config is None and self.config.use_conv_net:\n            conv_config = self.conv_config\n\n        # -- xNetwork ---------------------------------------------\n        xshape = (self.xdim, 2)  # NOTE: x = [cos(x), sin(x)]\n        if self.config.use_conv_net:\n            xshape = (*self.lattice_shape[1:], 2)\n\n        xnet_cfg = {\n            'factor': 2.0,              # xFactor\n            'net_config': net_config,\n            'conv_config': conv_config,\n            'x_shape': self.lattice_shape,\n            # NOTE: input_shapes differ for xNet, vNet\n            'input_shapes': {'x': xshape, 'v': (self.xdim,)}\n        }\n\n        # -- vNetwork ---------------------------------------------\n        vnet_cfg = {\n            'factor': 1.0,              # vFactor\n            'net_config': net_config,\n            'conv_config': None,        # use dense layers for vNet\n            'x_shape': self.lattice_shape,\n            # NOTE: input_shapes differ for xNet, vNet\n            'input_shapes': {'x': (self.xdim,), 'v': (self.xdim,)}\n        }\n\n        return AttrDict({'xnet': xnet_cfg, 'vnet': vnet_cfg})\n\n    def _build_network(\n            self,\n            step: int = None,\n            net_config: NetworkConfig = None,\n            conv_config: ConvolutionConfig = None,\n    ):\n        \"\"\"Build single instances of the position and momentum networks.\n\n        Returns:\n            xnet: tf.keras.models.Model\n            vnet: tf.keras.models.Model\n        \"\"\"\n        cfgs = self._get_network_configs(net_config, conv_config)\n        vn = f'vnet{step}' if self.config.separate_networks else 'vnet'\n        vnet = get_gauge_network(**cfgs['vnet'], name=vn)\n\n        if self.config.separate_networks:\n            xnet = (\n                get_gauge_network(**cfgs['xnet'], name=f'xnet_first{step}'),\n                get_gauge_network(**cfgs['xnet'], name=f'xnet_second{step}')\n            )\n        else:\n            xnet = get_gauge_network(**cfgs['xnet'], name=f'xnet')\n\n        return xnet, vnet\n\n    def _build_networks(\n            self,\n            net_config: NetworkConfig = None,\n            conv_config: ConvolutionConfig = None,\n            log_dir: str = None,\n    ):\n        \"\"\"Build position and momentum networks.\n\n        If `self.config.separate_networks`, build an array of identical copies\n        of `xnet`, `vnet` for each leapfrog step (generally makes the model\n        more expressive).\n\n        Otherwise, build a single instance of `xnet` and `vnet` to use for\n        different leapfrog steps.\n\n        Returns:\n            xnet: tf.keras.models.Model\n            vnet: tf.keras.models.Model\n        \"\"\"\n        if log_dir is not None:\n            return self._load_networks(log_dir)\n\n        cfgs = self._get_network_configs(net_config, conv_config)\n\n        if self.config.separate_networks:\n            logger.debug('Using separate (x, v)-networks for each LF step!!')\n            vnet = [\n                get_gauge_network(**cfgs['vnet'], name=f'vnet{i}')\n                for i in range(self.config.num_steps)\n            ]\n            xnet = [\n                (get_gauge_network(**cfgs['xnet'], name=f'xnet_first{i}'),\n                 get_gauge_network(**cfgs['xnet'], name=f'xnet_second{i}'))\n                for i in range(self.config.num_steps)\n            ]\n\n        else:\n            logger.debug('Using a single (x, v)-network for all LF steps!!')\n            vnet = [get_gauge_network(**cfgs['vnet'], name='vnet')]\n            xnet = [get_gauge_network(**cfgs['xnet'], name='xnet')]\n\n        return xnet, vnet\n\n    def _init_metrics(\n            self,\n            state: State,\n    ) -> dict[str, tf.TensorArray]:\n        \"\"\"Create logdet/energy metrics for verbose logging.\"\"\"\n        metrics = super()._init_metrics(state)\n\n        if not self._verbose:\n            return metrics\n\n        kwargs = {\n            'size': self.config.num_steps+1,\n            'element_shape': (state.x.shape[0],),\n            'dynamic_size': False,\n            'clear_after_read': False\n        }\n        sinq = tf.TensorArray(TF_FLOAT, **kwargs)\n        intq = tf.TensorArray(TF_FLOAT, **kwargs)\n        plaqs = tf.TensorArray(TF_FLOAT, **kwargs)\n        p4x4 = tf.TensorArray(TF_FLOAT, **kwargs)\n\n        #  sinq = self.lattice.calc_charges(x=state.x, use_sin=True)\n        plaqs_arr, charges, plaqs4x4_arr = self._calc_observables(state)\n        plaqs = plaqs.write(0, plaqs_arr)\n        p4x4 = p4x4.write(0, plaqs4x4_arr)\n        sinq = sinq.write(0, charges.sinQ)\n        intq = intq.write(0, charges.intQ)\n        metrics.update({\n            'sinQ': sinq,\n            'intQ': intq,\n            'plaqs': plaqs,\n            'p4x4': p4x4,\n        })\n\n        return metrics\n\n    def _update_metrics(self, metrics, step, state, sumlogdet, **kwargs):\n        \"\"\"Write to metrics.\"\"\"\n        sinq = self.lattice.calc_charges(x=state.x, use_sin=True)\n        metrics['sinQ'] = metrics['sinQ'].write(step, sinq)\n\n        return super()._update_metrics(metrics, step, state,\n                                       sumlogdet, **kwargs)\n\n    def transition_kernel_directional(\n            self,\n            state: State,\n            forward: bool,\n            training: bool = None,\n    ):\n        \"\"\"Implements a series of directional updates.\"\"\"\n        state_prop = State(x=state.x, v=state.v, beta=state.beta)\n        sumlogdet = tf.zeros((state.x.shape[0],))\n        metrics = self._init_metrics(state_prop)\n\n        def _update_metrics(data, step):\n            for key, val in data.items():\n                try:\n                    metrics[key] = metrics[key].write(step, val)\n                except AttributeError:\n                    metrics[key][step] = val\n\n            return metrics\n\n        def _get_metrics(state, logdet):\n            energy = self.hamiltonian(state)\n            plaqs, charges, p4x4 = self._calc_observables(state)\n            escaled = energy - logdet\n            return {\n                'H': energy, 'Hw': escaled, 'logdets': logdet,\n                'sinQ': charges.sinQ, 'intQ': charges.intQ,\n                'plaqs': plaqs, 'p4x4': p4x4,\n            }\n\n        def _stack_metrics():\n            for key, val in metrics.items():\n                if isinstance(val, tf.TensorArray):\n                    metrics[key] = val.stack()\n            return metrics\n\n        # -- Forward for first half of trajectory ---------------------------\n        for step in range(self.config.num_steps // 2):\n            state_prop, logdet = self._forward_lf(step, state_prop, training)\n            sumlogdet += logdet\n            if self._verbose:\n                data = _get_metrics(state_prop, sumlogdet)\n                metrics = _update_metrics(data, step+1)\n\n        # -- Flip momentum --------------------------------------------------\n        state_prop = State(state_prop.x, -1. * state_prop.v, state_prop.beta)\n\n        # -- Backward for second half of trajectory -------------------------\n        for step in range(self.config.num_steps // 2, self.config.num_steps):\n            state_prop, logdet = self._backward_lf(step, state_prop, training)\n            sumlogdet += logdet\n            if self._verbose:\n                data = _get_metrics(state_prop, sumlogdet)\n                metrics = _update_metrics(data, step+1)\n\n        accept_prob = self.compute_accept_prob(state, state_prop, sumlogdet)\n        metrics['sumlogdet'] = sumlogdet\n        metrics['accept_prob'] = accept_prob\n        if self._verbose:\n            data = _get_metrics(state_prop, sumlogdet)\n            metrics = _update_metrics(data, step+1)\n            metrics = _stack_metrics()\n\n        return state_prop, metrics\n\n    def _transition_kernel_forward(\n            self,\n            state: State,\n            training: bool = None\n    ):\n        \"\"\"Run the augmented leapfrog sampler in the forward direction.\"\"\"\n        state_prop = State(x=state.x, v=state.v, beta=state.beta)\n        sumlogdet = tf.zeros((state.x.shape[0],))\n        metrics = self._init_metrics(state_prop)\n\n        def _update_metrics(data, step):\n            for key, val in data.items():\n                metrics[key] = metrics[key].write(step, val)\n\n            return metrics\n\n        def _get_metrics(state, logdet):\n            energy = self.hamiltonian(state)\n            charges = self.lattice.calc_both_charges(x=state_prop.x)\n            escaled = energy - logdet\n            return {\n                'H': energy, 'Hw': escaled, 'logdets': logdet,\n                'sinQ': charges.sinQ, 'intQ': charges.intQ,\n            }\n\n        def _stack_metrics():\n            for key, val in metrics.items():\n                if isinstance(val, tf.TensorArray):\n                    metrics[key] = val.stack()\n            return metrics\n\n        state_prop, logdet = self._half_v_update_forward(state_prop,\n                                                         0, training)\n        sumlogdet += logdet\n        for step in range(self.config.num_steps):\n            state_prop, logdet = self._full_x_update_forward(state_prop,\n                                                             step, training)\n            sumlogdet += logdet\n\n            if step < self.config.num_steps - 1:\n                state_prop, logdet = self._full_v_update_forward(\n                    state_prop, step, training\n                )\n                sumlogdet += logdet\n                if self._verbose:\n                    data = _get_metrics(state_prop, sumlogdet)\n                    metrics = _update_metrics(data, step+1)\n\n        state_prop, logdet = self._half_v_update_forward(state_prop,\n                                                         step, training)\n        sumlogdet += logdet\n\n        accept_prob = self.compute_accept_prob(state, state_prop, sumlogdet)\n        metrics['sumlogdet'] = sumlogdet\n        metrics['accept_prob'] = accept_prob\n        if self._verbose:\n            data = _get_metrics(state_prop, sumlogdet)\n            metrics = _update_metrics(data, step + 1)\n            metrics = _stack_metrics()\n\n        return state_prop, metrics\n\n    def _transition_kernel_backward(\n            self,\n            state: State,\n            training: bool = None\n    ):\n        \"\"\"Run the augmented leapfrog sampler in the forward direction.\"\"\"\n        state_prop = State(x=state.x, v=state.v, beta=state.beta)\n        sumlogdet = tf.zeros((state.x.shape[0],))\n        metrics = self._init_metrics(state_prop)\n\n        def _update_metrics(data, step):\n            for key, val in data.items():\n                metrics[key] = metrics[key].write(step, val)\n\n            return metrics\n\n        def _get_metrics(state, logdet):\n            energy = self.hamiltonian(state)\n            charges = self.lattice.calc_both_charges(x=state_prop.x)\n            escaled = energy - logdet\n            return {\n                'H': energy, 'Hw': escaled, 'logdets': logdet,\n                'sinQ': charges.sinQ, 'intQ': charges.intQ,\n            }\n\n        def _stack_metrics():\n            for key, val in metrics.items():\n                if isinstance(val, tf.TensorArray):\n                    metrics[key] = val.stack()\n            return metrics\n\n        state_prop, logdet = self._half_v_update_backward(state_prop,\n                                                          0, training)\n        sumlogdet += logdet\n        for step in range(self.config.num_steps):\n            state_prop, logdet = self._full_x_update_backward(state_prop,\n                                                              step, training)\n            sumlogdet += logdet\n\n            if step < self.config.num_steps - 1:\n                state_prop, logdet = self._full_v_update_backward(\n                    state_prop, step, training\n                )\n                sumlogdet += logdet\n                if self._verbose:\n                    data = _get_metrics(state_prop, sumlogdet)\n                    metrics = _update_metrics(data, step+1)\n\n        state_prop, logdet = self._half_v_update_backward(state_prop,\n                                                          step, training)\n        sumlogdet += logdet\n\n        accept_prob = self.compute_accept_prob(state, state_prop, sumlogdet)\n        metrics['sumlogdet'] = sumlogdet\n        metrics['accept_prob'] = accept_prob\n        if self._verbose:\n            data = _get_metrics(state_prop, sumlogdet)\n            metrics = _update_metrics(data, step+1)\n            metrics = _stack_metrics()\n\n        return state_prop, metrics\n\n    @staticmethod\n    def split_metrics_by_accept_reject(metrics, mask_a, mask_r=None):\n        if mask_r is None:\n            mask_r = 1. - mask_a\n\n        metrics_a = {}\n        metrics_r = {}\n        for key, val in metrics.items():\n            if len(val.shape) == 1:\n                val_a = mask_a * val\n                val_r = mask_r * val\n            if len(val.shape) == 2:\n                val_a = tf.convert_to_tensor([mask_a * i for i in val])\n                val_r = tf.convert_to_tensor([mask_r * i for i in val])\n\n            metrics_a[key] = val_a\n            metrics_r[key] = val_r\n\n        return {\n            'accept': metrics_a,\n            'reject': metrics_r\n        }\n\n    def _transition_kernel(\n            self,\n            state: State,\n            forward: bool,\n            training: bool = None,\n    ):\n        \"\"\"Implements a transition kernel when using separate networks.\"\"\"\n        # -- Setup -------------------------------------------------\n        lf_fn = self._forward_lf if forward else self._backward_lf\n        state_prop = State(x=state.x, v=state.v, beta=state.beta)\n        sumlogdet = tf.zeros((state.x.shape[0],))\n        metrics = self._init_metrics(state_prop)\n\n        def _update_metrics(data, step):\n            for key, val in data.items():\n                metrics[key] = metrics[key].write(step, val)\n\n            return metrics\n\n        def _get_metrics(state, logdet):\n            energy = self.hamiltonian(state)\n            plaqs, charges, p4x4 = self._calc_observables(state)\n            return {\n                'H': energy, 'Hw': energy - logdet, 'logdets': logdet,\n                'sinQ': charges.sinQ, 'intQ': charges.intQ,\n                'plaqs': plaqs, 'p4x4': p4x4,\n            }\n\n        def _stack_metrics():\n            for key, val in metrics.items():\n                if isinstance(val, tf.TensorArray):\n                    metrics[key] = val.stack()\n            return metrics\n\n        # -- Loop over leapfrog steps ----------------------------\n        for step in range(self.config.num_steps):\n            state_prop, logdet = lf_fn(step, state_prop, training)\n            sumlogdet += logdet\n            if self._verbose:\n                data = _get_metrics(state_prop, sumlogdet)\n                metrics = _update_metrics(data, step+1)\n\n        # -- Compute accept prob and update metrics ------------------------\n        accept_prob = self.compute_accept_prob(state, state_prop, sumlogdet)\n        metrics.update({'sumlogdet': sumlogdet, 'accept_prob': accept_prob})\n        if self._verbose:\n            data = _get_metrics(state_prop, sumlogdet)\n            metrics = _update_metrics(data, step+1)\n            metrics = _stack_metrics()\n\n        return state_prop, metrics\n\n    def transition_kernel(\n            self,\n            state: State,\n            forward: bool,\n            training: bool = None,\n            verbose: bool = False,\n    ):\n        \"\"\"Transition kernel of the augmented leapfrog integrator.\"\"\"\n        # -- NOTE --------------------------------------------------------\n        # If using `self._combined_updates`, we combine the half-step\n        # momentum-updates into a single full-step momentum updates in the\n        # inner leapfrog steps.\n        if self._combined_updates:\n            return (\n                self._transition_kernel_forward(state, training)\n                if forward else\n                self._transition_kernel_backward(state, training)\n            )\n\n        # ====\n        # Using directional updates? (Experimental, not well tested!!)\n        if self.config.directional_updates:\n            return self.transition_kernel_directional(state, training)\n\n        return self._transition_kernel(state, forward, training)\n\n    def _scattered_xnet(self, inputs, mask, step, training=None):\n        \"\"\"Call `self.xnet` on non-zero entries of `x` via `tf.gather_nd`.\"\"\"\n        if len(mask) == 2:\n            mask, _ = mask\n\n        x, v = inputs\n        shape = (x.shape[0], -1)\n        m = tf.reshape(mask, shape)\n        idxs = tf.where(m)\n        _x = tf.reshape(tf.gather_nd(x, idxs), shape)\n        _x = tf.concat([tf.math.cos(_x), tf.math.sin(_x)], axis=-1)\n        if not self.config.separate_networks:\n            S, T, Q = self.xnet((_x, v), training)\n        else:\n            xnet = self.xnet[step]\n            S, T, Q = xnet((x, v), training)\n\n        return S, T, Q\n\n    def _call_vnet(self, inputs, step, training=None):\n        \"\"\"Call `self.xnet` to get Sx, Tx, Qx for updating `x`.\"\"\"\n        if self.config.hmc:\n            return [tf.zeros_like(inputs[0]) for _ in range(3)]\n\n        step = 0 if not self.config.separate_networks else step\n        return self.vnet[step](inputs, training)\n\n    def _convert_to_cartesian(self, x: tf.Tensor, mask: tf.Tensor):\n        \"\"\"Convert `x` from an angle to [cos(x), sin(x)].\"\"\"\n        if mask.shape[0] == 2:\n            mask, _ = mask\n\n        xcos = mask * tf.math.cos(x)\n        xsin = mask * tf.math.sin(x)\n        if self.config.use_conv_net:\n            xcos = tf.reshape(xcos, self.lattice_shape)\n            xsin = tf.reshape(xsin, self.lattice_shape)\n\n        x = tf.stack([xcos, xsin], axis=-1)\n\n        return x\n\n    def _call_xnet(\n            self,\n            inputs: tuple,\n            mask: tf.Tensor,\n            step: int,\n            training: bool = None,\n            first: bool = False\n    ):\n        \"\"\"Call `self.xnet` to get Sx, Tx, Qx for updating `x`.\"\"\"\n        if self.config.hmc:\n            return [tf.zeros_like(inputs[0]) for _ in range(3)]\n\n        x, v = inputs\n        x = self._convert_to_cartesian(x, mask)\n\n        # -- self.xnet is a list of tf.keras.Models -----------\n        step = 0 if not self.config.separate_networks else step\n        xnet = self.xnet[step]\n        # -- only a single xnet -------------------------------\n        if callable(xnet):\n            return xnet((x, v), training)\n        # -- xnets split into even/odd updates-----------------\n        if first:\n            return xnet[0]((x, v), training)\n        return xnet[1]((x, v), training)\n\n    def _full_v_update_forward(\n            self,\n            state: State,\n            step: int,\n            training: bool = None,\n    ):\n        \"\"\"Perform a full-step momentum update in the forward direction.\"\"\"\n        eps = self.veps[step]\n        x = self.normalizer(state.x)\n        grad = self.grad_potential(x, state.beta)\n        S, T, Q = self._call_vnet((x, grad), step, training)\n\n        scale = self._vsw * (eps * S)\n        transl = self._vtw * T\n        transf = self._vqw * (eps * Q)\n\n        expS = tf.exp(scale)\n        expQ = tf.exp(transf)\n\n        vf = state.v * expS - eps * (grad * expQ - transl)\n\n        state_out = State(x=x, v=vf, beta=state.beta)\n        logdet = tf.reduce_sum(scale, axis=1)\n\n        return state_out, logdet\n\n    def _half_v_update_forward(\n            self,\n            state: State,\n            step: int,\n            training: bool = None,\n    ):\n        \"\"\"Perform a half-step momentum update in the forward direction.\"\"\"\n        eps = self.veps[step]\n        x = self.normalizer(state.x)\n        grad = self.grad_potential(x, state.beta)\n        S, T, Q = self._call_vnet((x, grad), step, training)\n\n        scale = self._vsw * (0.5 * eps * S)\n        transl = self._vtw * T\n        transf = self._vqw * (eps * Q)\n\n        expS = tf.exp(scale)\n        expQ = tf.exp(transf)\n\n        vf = state.v * expS - 0.5 * eps * (grad * expQ - transl)\n\n        state_out = State(x=x, v=vf, beta=state.beta)\n        logdet = tf.reduce_sum(scale, axis=1)\n\n        return state_out, logdet\n\n    def _update_v_forward(\n                self,\n                state: State,\n                step: int,\n                training: bool = None\n    ):\n        \"\"\"Update the momentum `v` in the forward leapfrog step.\n\n        Args:\n            network (tf.keras.Layers): Network to use\n            state (State): Input state\n            t (float): Current leapfrog step, represented as periodic time.\n            training (bool): Currently training?\n\n        Returns:\n            new_state (State): New state, with updated momentum.\n            logdet (float): Jacobian factor\n        \"\"\"\n        if self.config.hmc:\n            return super()._update_v_forward(state, step, training)\n\n        eps = self.veps[step]\n        x = self.normalizer(state.x)\n        grad = self.grad_potential(x, state.beta)\n        S, T, Q = self._call_vnet((x, grad), step, training)\n\n        scale = self._vsw * (0.5 * eps * S)\n        transl = self._vtw * T\n        transf = self._vqw * (eps * Q)\n\n        expS = tf.exp(scale)\n        expQ = tf.exp(transf)\n\n        vf = state.v * expS - 0.5 * eps * (grad * expQ - transl)\n\n        state_out = State(x=x, v=vf, beta=state.beta)\n        logdet = tf.reduce_sum(scale, axis=1)\n\n        return state_out, logdet\n\n    def _full_x_update_forward(\n            self,\n            state: State,\n            step: int,\n            training: bool = None\n    ):\n        \"\"\"Perform a full-step position update in the forward direction.\"\"\"\n        m, mc = self._get_mask(step)\n        sumlogdet = tf.zeros((state.x.shape[0],))\n        state, logdet = self._update_x_forward(state, step,\n                                               (m, mc), training, first=True)\n        sumlogdet += logdet\n        state, logdet = self._update_x_forward(state, step,\n                                               (mc, m), training, first=False)\n        sumlogdet += logdet\n\n        return state, sumlogdet\n\n    def _update_x_forward(\n                self,\n                state: State,\n                step: int,\n                masks: Tuple[tf.Tensor, tf.Tensor],  # [m, 1. - m]\n                training: bool = None,\n                first: bool = True,\n    ):\n        \"\"\"Update the position `x` in the forward leapfrog step.\n\n        Args:\n            state (State): Input state\n            t (float): Current leapfrog step, represented as periodic time.\n            training (bool): Currently training?\n\n        Returns:\n            new_state (State): New state, with updated momentum.\n            logdet (float): logdet of Jacobian factor.\n        \"\"\"\n        if self.config.hmc:\n            return super()._update_x_forward(state, step, masks, training)\n\n        m, mc = masks\n        eps = self.xeps[step]\n        x = self.normalizer(state.x)\n\n        S, T, Q = self._call_xnet((x, state.v), m, step, training, first)\n\n        scale = self._xsw * (eps * S)\n        transl = self._xtw * T\n        transf = self._xqw * (eps * Q)\n\n        expS = tf.exp(scale)\n        expQ = tf.exp(transf)\n\n        if self.config.use_ncp:\n            _x = 2 * tf.math.atan(tf.math.tan(x/2.) * expS)\n            _y = _x + eps * (state.v * expQ + transl)\n            xf = (m * x) + (mc * _y)\n\n            cterm = tf.math.cos(x / 2) ** 2\n            sterm = (expS * tf.math.sin(x / 2)) ** 2\n            logdet_ = tf.math.log(expS / (cterm + sterm))\n            logdet = tf.reduce_sum(mc * logdet_, axis=1)\n\n        else:\n            y = x * expS + eps * (state.v * expQ + transl)\n            xf = (m * x) + (mc * y)\n            logdet = tf.reduce_sum(mc * scale, axis=1)\n\n        xf = self.normalizer(xf)\n        state_out = State(x=xf, v=state.v, beta=state.beta)\n\n        return state_out, logdet\n\n    def _full_v_update_backward(\n            self,\n            state: State,\n            step: int,\n            training: bool = None\n    ):\n        \"\"\"Perform a full update of the momentum in the backward direction.\"\"\"\n        step_r = self.config.num_steps - step - 1\n        eps = self.veps[step_r]\n        x = self.normalizer(state.x)\n        grad = self.grad_potential(x, state.beta)\n        S, T, Q = self._call_vnet((x, grad), step_r, training)\n\n        scale = self._vsw * (-eps * S)\n        transf = self._vqw * (eps * Q)\n        transl = self._vtw * T\n\n        expS = tf.exp(scale)\n        expQ = tf.exp(transf)\n\n        vb = expS * (state.v + eps * (grad * expQ - transl))\n\n        state_out = State(x=x, v=vb, beta=state.beta)\n        logdet = tf.reduce_sum(scale, axis=1)\n\n        return state_out, logdet\n\n    def _half_v_update_backward(\n            self,\n            state: State,\n            step: int,\n            training: bool = None\n    ):\n        \"\"\"Perform a half update of the momentum in the backward direction.\"\"\"\n        step_r = self.config.num_steps - step - 1\n        eps = self.veps[step_r]\n        x = self.normalizer(state.x)\n        grad = self.grad_potential(x, state.beta)\n        S, T, Q = self._call_vnet((x, grad), step_r, training)\n\n        scale = self._vsw * (-0.5 * eps * S)\n        transf = self._vqw * (eps * Q)\n        transl = self._vtw * T\n\n        expS = tf.exp(scale)\n        expQ = tf.exp(transf)\n\n        vb = expS * (state.v + 0.5 * eps * (grad * expQ - transl))\n\n        state_out = State(x=x, v=vb, beta=state.beta)\n        logdet = tf.reduce_sum(scale, axis=1)\n\n        return state_out, logdet\n\n    def _update_v_backward(\n            self,\n            state: State,\n            step: int,\n            training: bool = None\n    ):\n        \"\"\"Update the momentum `v` in the backward leapfrog step.\n\n        Args:\n            state (State): Input state.\n            t (float): Current leapfrog step, represented as periodic time.\n            training (bool): Currently training?\n\n        Returns:\n            new_state (State): New state, with updated momentum.\n            logdet (float): Jacobian factor.\n        \"\"\"\n        eps = self.veps[step]\n        x = self.normalizer(state.x)\n        grad = self.grad_potential(x, state.beta)\n        S, T, Q = self._call_vnet((x, grad), step, training)\n\n        scale = self._vsw * (-0.5 * eps * S)\n        transf = self._vqw * (eps * Q)\n        transl = self._vtw * T\n\n        expS = tf.exp(scale)\n        expQ = tf.exp(transf)\n\n        vb = expS * (state.v + 0.5 * eps * (grad * expQ - transl))\n\n        state_out = State(x=x, v=vb, beta=state.beta)\n        logdet = tf.reduce_sum(scale, axis=1)\n\n        return state_out, logdet\n\n    def _full_x_update_backward(\n            self,\n            state: State,\n            step: int,\n            training: bool = None\n    ):\n        \"\"\"Perform a full-step position update in the backward direction.\"\"\"\n        step_r = self.config.num_steps - step - 1\n        m, mc = self._get_mask(step_r)\n        sumlogdet = tf.zeros((state.x.shape[0],))\n\n        state, logdet = self._update_x_backward(state, step_r,\n                                                (mc, m), training)\n        sumlogdet += logdet\n\n        state, logdet = self._update_x_backward(state, step_r,\n                                                (m, mc), training)\n        sumlogdet += logdet\n\n        return state, sumlogdet\n\n    def _update_x_backward(\n                self,\n                state: State,\n                step: int,\n                masks: Tuple[tf.Tensor, tf.Tensor],   # [m, 1. - m]\n                training: bool = None,\n                first: bool = True,\n    ):\n        \"\"\"Update the position `x` in the backward leapfrog step.\n\n        Args:\n            state (State): Input state\n            t (float): Current leapfrog step, represented as periodic time.\n            training (bool): Currently training?\n\n\n        Returns:\n            new_state (State): New state, with updated momentum.\n            logdet (float): logdet of Jacobian factor.\n        \"\"\"\n        if self.config.hmc:\n            return super()._update_x_backward(state, step, masks, training)\n\n        # Call `XNet` using `self._scattered_xnet`\n        m, mc = masks\n        eps = self.xeps[step]\n        x = self.normalizer(state.x)\n        S, T, Q = self._call_xnet((x, state.v), m, step, training, first)\n\n        scale = self._xsw * (-eps * S)\n        transl = self._xtw * T\n        transf = self._xqw * (eps * Q)\n\n        expS = tf.exp(scale)\n        expQ = tf.exp(transf)\n\n        if self.config.use_ncp:\n            term1 = 2 * tf.math.atan(expS * tf.math.tan(state.x / 2))\n            term2 = expS * eps * (state.v * expQ + transl)\n            y = term1 - term2\n            xb = (m * x) + (mc * y)\n\n            cterm = tf.math.cos(x / 2) ** 2\n            sterm = (expS * tf.math.sin(x / 2)) ** 2\n            logdet_ = tf.math.log(expS / (cterm + sterm))\n            logdet = tf.reduce_sum(mc * logdet_, axis=1)\n\n        else:\n            y = expS * (x - eps * (state.v * expQ + transl))\n            xb = m * x + mc * y\n            logdet = tf.reduce_sum(mc * scale, axis=1)\n\n        xb = self.normalizer(xb)\n        state_out = State(xb, v=state.v, beta=state.beta)\n        return state_out, logdet\n\n    @staticmethod\n    def mixed_loss(loss: tf.Tensor, weight: float) -> (tf.Tensor):\n        \"\"\"Returns: tf.reduce_mean(weight / loss - loss / weight).\"\"\"\n        return tf.reduce_mean((weight / loss) - (loss / weight))\n\n    def calc_losses(self, states: MonteCarloStates, accept_prob: tf.Tensor):\n        \"\"\"Calculate the total loss.\"\"\"\n        wl_init = self.lattice.calc_wilson_loops(states.init.x)\n        wl_prop = self.lattice.calc_wilson_loops(states.proposed.x)\n\n        # Calculate the plaquette loss\n        ploss = tf.constant(0.)\n        if self.plaq_weight > 0:\n            dwloops = 2 * (1. - tf.math.cos(wl_prop - wl_init))\n            ploss = accept_prob * tf.reduce_sum(dwloops, axis=(1, 2))\n\n            # ==== FIXME: Try using mixed loss??\n            if self.config.use_mixed_loss:\n                ploss = self.mixed_loss(ploss, self.plaq_weight)\n            else:\n                ploss = tf.reduce_mean(-ploss / self.plaq_weight, axis=0)\n\n        # Calculate the charge loss\n        qloss = tf.constant(0.)\n        if self.charge_weight > 0:\n            q_init = tf.reduce_sum(tf.sin(wl_init), axis=(1, 2)) / (2 * np.pi)\n            q_prop = tf.reduce_sum(tf.sin(wl_prop), axis=(1, 2)) / (2 * np.pi)\n            qloss = (accept_prob * (q_prop - q_init) ** 2) + 1e-4\n            if self.config.use_mixed_loss:\n                qloss = self.mixed_loss(qloss, self.charge_weight)\n            else:\n                qloss = tf.reduce_mean(-qloss / self.charge_weight, axis=0)\n\n        return ploss, qloss\n\n    def _get_lr(self, step=None) -> (tf.Tensor):\n        if step is None:\n            step = self.optimizer.iterations\n\n        if callable(self.lr):\n            return self.lr(step)\n\n        return K.get_value(self.optimizer.lr)\n\n    @tf.function\n    def train_step(\n            self,\n            inputs: Tuple[tf.Tensor, tf.Tensor],\n    ) -> tuple[tf.Tensor, AttrDict]:\n        \"\"\"Perform a single training step.\n\n        Returns:\n            states.out.x (tf.Tensor): Next `x` state in the Markov Chain.\n            metrics (AttrDict): Dictionary of various metrics for logging.\n        \"\"\"\n        def _traj_summ(x, key=None):\n            if key is not None:\n                return {\n                    f'{key}': tf.squeeze(x),\n                    f'{key}_start': x[0],\n                    f'{key}_mid': x[midpt],\n                    f'{key}_end': x[-1],\n                }\n\n            return (x[0], x[midpt], x[1])\n\n        start = time.time()\n        with tf.GradientTape() as tape:\n            x, beta = inputs\n            tape.watch(x)\n            states, metrics = self((x, beta), training=True)\n            accept_prob = metrics.get('accept_prob', None)\n            ploss, qloss = self.calc_losses(states, accept_prob)\n            loss = ploss + qloss\n\n            if self.aux_weight > 0:\n                z = tf.random.normal(x.shape, dtype=x.dtype)\n                states_, metrics_ = self((z, beta), training=True)\n                accept_prob_ = metrics_.get('accept_prob', None)\n                ploss_, qloss_ = self.calc_losses(states_, accept_prob_)\n                loss += ploss_ + qloss_\n\n        if HAS_HOROVOD:\n            tape = hvd.DistributedGradientTape(tape, compression=self._fp16)\n\n        grads = tape.gradient(loss, self.trainable_variables)\n\n        self.optimizer.apply_gradients(\n            zip(grads, self.trainable_variables),\n        )\n\n        # -- NOTE (Horovod) --------------------------------------------------\n        # * Broadcast initial variable states from rank 0 to all other\n        #   processes. This is necessary to ensure consistent initialization\n        #   of all workers when training is started with random weights or\n        #   restored from a checkpoint.\n        # * Broadcast should be done after the first gradient step to ensure\n        #   optimizer intialization.\n        if self.optimizer.iterations == 0 and HAS_HOROVOD:\n            hvd.broadcast_variables(self.variables, root_rank=0)\n            hvd.broadcast_variables(self.optimizer.variables(), root_rank=0)\n\n        data = AttrDict({\n            #  'lr': self._get_lr(),\n            'dt': time.time() - start,\n            'loss': loss,\n        })\n        if self.plaq_weight > 0 and self.charge_weight > 0:\n            data.update({\n                'ploss': ploss,\n                'qloss': qloss\n            })\n        if self.aux_weight > 0:\n            data.update({\n                'ploss_aux': ploss_,\n                'qloss_aux': qloss_,\n                'accept_prob_aux': accept_prob_,\n            })\n\n        midpt = self.config.num_steps // 2\n\n        # Separated from [1038] for ordering when printing\n        #  mask_a = metrics.get('accept_mask', None)\n        data.update({\n            'accept_prob': accept_prob,\n            'accept_mask': metrics.get('accept_mask', None),\n            'beta': states.init.beta,\n            'sumlogdet': metrics.get('sumlogdet', None),\n        })\n        data.update(**_traj_summ(self.xeps, 'xeps'))\n        data.update(**_traj_summ(self.veps, 'veps'))\n\n        if self._verbose and not self.config.hmc:\n            metricsf = metrics.get('forward', None)\n            metricsb = metrics.get('backward', None)\n            for (kf, vf), (kb, vb) in zip(metricsf.items(), metricsb.items()):\n                data.update(**_traj_summ(vf, f'{kf}f'))\n                data.update(**_traj_summ(vb, f'{kb}b'))\n\n        data.update(metrics)\n        data.update(self.calc_observables(states))\n\n        return states.out.x, data\n\n    @tf.function\n    def test_step(\n            self,\n            inputs: Tuple[tf.Tensor, tf.Tensor]\n    ) -> (tf.Tensor, AttrDict):\n        \"\"\"Perform a single training step.\n\n        Returns:\n            states.out.x (tf.Tensor): Next `x` state in the Markov Chain.\n            metrics (AttrDict): Dictionary of various metrics for logging.\n        \"\"\"\n        def _traj_summ(x, key=None):\n            \"\"\"Helper fn for summarizing `x` along the trajectory\"\"\"\n            return (x[0], x[midpt], x[1]) if key is None else {\n                f'{key}': tf.squeeze(x)\n            }\n\n        start = time.time()\n        x, beta = inputs\n        states, metrics = self((x, beta), training=True)\n        accept_prob = metrics.get('accept_prob', None)\n        ploss, qloss = self.calc_losses(states, accept_prob)\n        loss = ploss + qloss\n        dt = time.time() - start\n        data = AttrDict({'dt': dt, 'loss': loss})\n        if self.plaq_weight > 0 and self.charge_weight > 0:\n            data.update({'ploss': ploss, 'qloss': qloss})\n\n        midpt = self.config.num_steps // 2\n        data.update({\n            'accept_prob': accept_prob,\n            'beta': states.init.beta,\n        })\n        data.update(**_traj_summ(self.xeps, 'xeps'))\n        data.update(**_traj_summ(self.veps, 'veps'))\n\n        if self._verbose and not self.config.hmc:\n            for (kf, vf), (kb, vb) in zip(metrics.forward.items(),\n                                          metrics.backward.items()):\n                data.update(**_traj_summ(vf, f'{kf}f'))\n                data.update(**_traj_summ(vb, f'{kb}b'))\n        data.update(metrics)\n        data.update(self.calc_observables(states))\n\n        return states.out.x, data\n\n    def _calc_observables(\n            self, state: State\n    ):\n        \"\"\"Calculate the observables for a particular state.\n\n        NOTE: We track the error in the plaquette instead of the actual value.\n        \"\"\"\n        wloops = self.lattice.calc_wilson_loops(state.x)\n        p4x4_obs = self.lattice.calc_plaqs4x4(x=state.x, beta=state.beta)\n        p4x4_err = p4x4_obs # - p4x4_exp\n        charges = self.lattice.calc_both_charges(x=state.x)\n        plaqs = self.lattice.calc_plaqs(wloops=wloops, beta=state.beta)\n\n        return plaqs, charges, p4x4_err\n\n    def calc_observables(\n            self,\n            states: MonteCarloStates\n    ):\n        \"\"\"Calculate observables.\"\"\"\n        _, q_init, _ = self._calc_observables(states.init)\n        plaqs, q_out, p4x4 = self._calc_observables(states.out)\n        dqsin = tf.math.abs(q_out.sinQ - q_init.sinQ)\n        dqint = tf.math.abs(q_out.intQ - q_init.intQ)\n\n        observables = AttrDict({\n            'dq_int': dqint,\n            'dq_sin': dqsin,\n            'charges': q_out.intQ,\n            'sin_charges': q_out.sinQ,\n            'plaqs': plaqs,\n            'p4x4': p4x4,\n        })\n\n        return observables\n\n    def save_config(self, config_dir: str):\n        \"\"\"Helper method for saving configuration objects.\"\"\"\n        io.save_dict(self.config.__dict__,\n                     config_dir, name='dynamics_config')\n        io.save_dict(self.net_config.__dict__,\n                     config_dir, name='network_config')\n        io.save_dict(self.lr_config.__dict__,\n                     config_dir, name='lr_config')\n        if self.conv_config is not None and self.config.use_conv_net:\n            io.save_dict(self.conv_config.__dict__,\n                         config_dir, name='conv_config')\n\n    def get_config(self):\n        \"\"\"Get configuration as dict.\"\"\"\n        return {\n            'config': self.config,\n            'network_config': self.net_config,\n            'conv_config': self.conv_config,\n            'lr_config': self.lr_config,\n            #  'params': params\n        }\n\n    def _get_time(self, i, tile=1):\n        \"\"\"Format the current leapfrog step as:\n        ```\n        [cos(2pi * step/num_steps), sin(2pi * step/num_steps)]\n        ```\n        for step in [0, 1, ..., num_steps], and reshape so that each chain in\n        our batch of inputs gets a copy.\n        \"\"\"\n        trig_t = tf.squeeze([\n            tf.cos(2 * np.pi * i / self.config.num_steps),\n            tf.sin(2 * np.pi * i / self.config.num_steps),\n        ])\n\n        t = tf.tile(tf.expand_dims(trig_t, 0), (tile, 1))\n\n        return t\n\n    def _build_conv_mask(self):\n        \"\"\"Construct checkerboard mask with size L * L and 2 channels.\"\"\"\n        _, tsize, xsize, channels = self.lattice_shape\n        arr = np.linspace(0, xsize * (xsize + 1) - 1, xsize * (xsize + 1))\n        mask = (arr % 2 == 1).reshape(xsize, xsize+1)[:, :-1]\n        mask_conj = ~mask\n        x_mask = np.stack([mask, mask_conj], axis=0)\n        x_mask = x_mask.reshape(1, channels, xsize, xsize)\n        x_mask_conj = ~x_mask\n\n        return tf.convert_to_tensor(x_mask), tf.convert_to_tensor(x_mask_conj)\n\n    def _build_masks(self):\n        \"\"\"Construct different binary masks for different time steps.\"\"\"\n        masks = []\n        zeros = np.zeros(self.lattice_shape, dtype=np.float32)\n\n        def rolled_reshape(m, ax, shape=None):\n            if shape is None:\n                shape = (self.batch_size, -1)\n\n            return sum([tf.roll(m, i, ax).reshape(shape) for i in range(4)])\n\n        if self._gauge_eq_masks:\n            mh_ = zeros.copy()\n            mv_ = zeros.copy()\n            mh_[:, ::4, :, 1] = 1.  # Horizontal masks\n            mv_[:, :, ::4, 0] = 1.  # Vertical masks\n\n            mh = rolled_reshape(mh_, ax=1)\n            mv = rolled_reshape(mv_, ax=2)\n            for i in range(self.config.num_steps):\n                mask = mh if i % 2 == 0 else mv\n                masks.append(tf.constant(mask))\n        else:\n            p = zeros.copy()\n            for idx, _ in np.ndenumerate(zeros):\n                p[idx] = (sum(idx) % 2 == 0)\n\n            for i in range(self.config.num_steps):\n                m = p if i % 2 == 0 else (1. - p)\n                mask = tf.reshape(tf.constant(m), (self.batch_size, -1))\n                mask = tf.convert_to_tensor(mask)\n                masks.append(mask)\n\n        return masks\n", "meta": {"hexsha": "e2df550eb49634253b4d227d9b57515496d5e554", "size": 52605, "ext": "py", "lang": "Python", "max_stars_repo_path": "l2hmc-qcd/dynamics/gauge_dynamics.py", "max_stars_repo_name": "saforem2/l2hmc-qcd", "max_stars_repo_head_hexsha": "b5fe06243fae663607b6c88e71373b68b19558fc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2019-04-18T18:50:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T18:30:48.000Z", "max_issues_repo_path": "l2hmc-qcd/dynamics/gauge_dynamics.py", "max_issues_repo_name": "saforem2/l2hmc-qcd", "max_issues_repo_head_hexsha": "b5fe06243fae663607b6c88e71373b68b19558fc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2019-09-09T21:10:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T17:43:51.000Z", "max_forks_repo_path": "l2hmc-qcd/dynamics/gauge_dynamics.py", "max_forks_repo_name": "saforem2/l2hmc-qcd", "max_forks_repo_head_hexsha": "b5fe06243fae663607b6c88e71373b68b19558fc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-10-31T02:25:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-25T00:49:14.000Z", "avg_line_length": 35.495951417, "max_line_length": 79, "alphanum_fraction": 0.5525140196, "include": true, "reason": "import numpy", "num_tokens": 12688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.17223688311826157}}
{"text": "import os\nimport numpy as np\nimport pandas as pd\nimport re\nimport time\nimport requests\nimport sys\nimport numba\nfrom bs4 import BeautifulSoup\nfrom scipy.interpolate import UnivariateSpline as Interp\nfrom .hapi import molecularMass, moleculeName, isotopologueName\n\nfrom .calculate import produce_total_cross_section_VALD_atom, bin_cross_section_atom\n\nfrom excalibur.constants import c, kb, u, P_ref, T_ref, \\\n                                gamma_0_fixed, n_L_fixed\n\nimport excalibur.ExoMol as ExoMol\nimport excalibur.HITRAN as HITRAN\nimport excalibur.HITEMP as HITEMP\nimport excalibur.VALD as VALD\nimport excalibur.downloader as download\nimport excalibur.broadening as broadening\nimport excalibur.Voigt as Voigt\nimport excalibur.calculate as calculate\n\nfrom excalibur.misc import write_output, check_molecule\n\n\ndef mass(species, isotopologue, linelist):\n    \"\"\"\n    Determine the mass of a given chemical species-isotopologue combination\n\n    Parameters\n    ----------\n    species : String\n        Molecule we are calculating the mass for.\n    isotopologue : String\n        Isotopologue of this species we are calculating the mass for.\n    linelist : String\n        The line list this species' cross-section will later be calculated for. Used to \n        identify between ExoMol, HITRAN/HITEMP, and VALD\n\n    Returns\n    -------\n    int\n        Mass of the given species-isotopologue combination.\n\n    \"\"\"\n    \n    # For HITRAN or HITEMP line lists\n    if linelist == 'hitran' or linelist == 'hitemp':\n        mol_ID = 1\n        while moleculeName(mol_ID) != species:\n            mol_ID += 1\n            \n        iso_ID = 1\n        \n        while True:\n            iso_name = isotopologueName(mol_ID, iso_ID) # Need to format the isotopologue name to match ExoMol formatting\n    \n            # 'H' not followed by lower case letter needs to become '(1H)'\n            iso_name = re.sub('H(?![a-z])', '(1H)', iso_name)\n    \n            # Number of that atom needs to be enclosed by parentheses ... so '(1H)2' becomes '(1H2)'\n            matches = re.findall('[)][0-9]{1}', iso_name)\n            for match in matches:\n                number = re.findall('[0-9]{1}', match)\n                iso_name = re.sub('[)][0-9]{1}', number[0] + ')', iso_name)\n    \n            # replace all ')(' with '-'\n            iso_name = iso_name.replace(')(', '-')\n            \n            if iso_name == isotopologue:\n                return molecularMass(mol_ID, iso_ID)\n            \n            else:\n                iso_ID += 1\n      \n    # For VALD line lists\n    elif linelist == 'vald':   \n        \n        # Atomic masses - Weighted average based on isotopic natural abundances found here: \n        # https://www.chem.ualberta.ca/~massspec/atomic_mass_abund.pdf\n        mass_dict = {'H': 1.00794072, 'He': 4.00260165, 'Li': 6.94003706, 'Be': 9.012182, 'B': 10.81102777,\n                     'C': 12.0107359, 'N': 14.00674309, 'O': 15.9994053, 'F': 18.998403, 'Ne': 20.1800463,\n                     'Na': 22.989770, 'Mg': 24.30505187, 'Al': 26.981538, 'Si': 28.0853852, 'P': 30.973762,\n                     'S': 32.06608499, 'Cl': 35.45653261, 'Ar': 39.94767659, 'K': 39.09830144, \n                     'Ca': 40.07802266, 'Sc': 44.955910, 'Ti': 47.86674971, 'Va': 50.941472, 'Cr': 51.99613764,\n                     'Mn': 54.938050, 'Fe': 55.84515013, 'Co': 58.933200, 'Ni': 58.69335646, 'Cu': 63.5456439, \n                     'Zn': 65.3955669, 'Ga': 69.72307155, 'Ge': 72.61275896, 'As': 74.921596, 'Se': 78.95938897,\n                     'Br': 79.90352862, 'Kr': 83.79932508, 'Rb': 85.46766375, 'Sr': 87.61664598, \n                     'Y': 88.905848, 'Zr': 91.22364739, 'Nb': 92.906378, 'Mo': 95.93129084, 'Ru': 101.06494511,\n                     'Rh': 102.905504, 'Pd': 106.41532721, 'Ag': 107.8681507, 'Cd': 112.41155267, \n                     'In': 114.81808585, 'Sn': 118.71011064, 'Sb': 121.7597883, 'Te': 127.60312538, \n                     'I': 126.904468, 'Xe': 131.29248065, 'Cs': 132.905447, 'Ba': 137.32688569, \n                     'La': 138.90544868, 'Ce': 140.11572155, 'Pr': 140.907648, 'Nd': 144.23612698, \n                     'Sm': 149.46629229, 'Eu': 151.96436622, 'Gd': 157.25211925, 'Tb': 158.925343, \n                     'Dy': 162.49703004, 'Ho': 164.930319, 'Er': 167.25630107, 'Tm': 168.934211, \n                     'Yb': 173.0376918, 'Lu': 174.96671757, 'Hf': 178.48497094, 'Ta': 180.94787594, \n                     'W': 183.84177868, 'Re': 186.20670567, 'Os': 190.22755215, 'Ir': 192.21605379, \n                     'Pt': 194.73875746, 'Au': 196.966552, 'Hg': 200.59914936, 'Tl': 204.38490867, \n                     'Pb': 207.21689158, 'Bi': 208.980383, 'Th': 232.038050, 'Pa': 231.035879, 'U': 238.02891307\n                     }\n        \n        return mass_dict.get(species)\n\n    # For ExoMol line lists\n    else:\n        \n        isotopologue = isotopologue.replace('(', '')\n        isotopologue = isotopologue.replace(')', '')\n\n        url = 'http://exomol.com/data/molecules/' + species + '/' + isotopologue + '/' + linelist + '/'\n        \n        # Parse the webpage to find the .def file and read it\n        web_content = requests.get(url).text\n        soup = BeautifulSoup(web_content, \"lxml\")\n        def_tag = soup.find('a', href = re.compile(\"def\"))\n        new_url = 'http://exomol.com' + def_tag.get('href')\n        \n        out_file = './def'\n        with requests.get(new_url, stream=True) as request:\n            with open(out_file, 'wb') as file:\n                for chunk in request.iter_content(chunk_size = 1024 * 1024):\n                    file.write(chunk)\n                    \n        data = pd.read_csv(out_file, delimiter = '#', names = ['Value', 'Key'])  # Store the .def file in a pandas DataFrame\n        data = data[data['Key'].str.contains('mass')]  # Only use the row that contains the isotopologue mass\n        data = data.reset_index(drop = True)  # Reset the index of the DataFrame\n        mass = data['Value'][0]\n        mass = re.findall('[0-9|.]+', mass)[0]\n        \n        os.remove(out_file)\n        \n        return float(mass)\n        \n\ndef load_pf(input_directory):\n    '''\n    Read in a pre-downloaded partition function.\n\n    Parameters\n    ----------\n    input_directory : String\n        DESCRIPTION.\n\n    Returns\n    -------\n    T_pf_raw : TYPE\n        DESCRIPTION.\n    Q_raw : TYPE\n        DESCRIPTION.\n\n    '''\n    \n    print(\"Loading partition function\")\n    \n    # Look for files in input directory ending in '.pf'\n    pf_file_name = [filename for filename in os.listdir(input_directory) if filename.endswith('.pf')]\n    \n    # Read partition function\n    pf_file = pd.read_csv(input_directory + pf_file_name[0], sep= ' ', header=None, skiprows=1)\n    \n    # First column in standard format is temperature, second is the partition function\n    T_pf_raw = np.array(pf_file[0]).astype(np.float64)\n    Q_raw = np.array(pf_file[1])\n    \n    return T_pf_raw, Q_raw\n\n\ndef interpolate_pf(T_pf_raw, Q_raw, T, T_ref):\n    '''\n    Interpolate partition function to the temperature of the cross section computation.\n\n    Parameters\n    ----------\n    T_pf_raw : TYPE\n        DESCRIPTION.\n    Q_raw : TYPE\n        DESCRIPTION.\n    T : TYPE\n        DESCRIPTION.\n    T_ref : TYPE\n        DESCRIPTION.\n\n    Returns\n    -------\n    Q_T : TYPE\n        DESCRIPTION.\n    Q_T_ref : TYPE\n        DESCRIPTION.\n\n    '''\n    \n    # Interpolate partition function onto a fine grid using a 5th order spline\n    pf_spline = Interp(T_pf_raw, Q_raw, k=5)\n    \n    # Define a new temperature grid (extrapolated to 10,000K)\n    T_pf_fine = np.linspace(1.0, 10000.0, 9999)      \n    \n    # Using spline, interpolate and extrapolate the partition function to the new T grid\n    Q_fine = pf_spline(T_pf_fine)                    \n    \n    # Find the indices in the fine temperature grid closest to the user specified and reference temperatures\n    idx_T = np.argmin(np.abs(T_pf_fine - T))\n    idx_T_ref = np.argmin(np.abs(T_pf_fine - T_ref))   \n    \n    # Find partition function at the user specified and reference temperatures\n    Q_T = Q_fine[idx_T]                               \n    Q_T_ref = Q_fine[idx_T_ref]                       \n    \n    return Q_T, Q_T_ref\n\n\ndef create_nu_grid_atom_OLD(atom, T, m, gamma, nu_0, Voigt_sub_spacing, \n                            dnu_out, nu_out_min, nu_out_max, Voigt_cutoff, cut_max):\n    '''\n    Create the computational (fine) and output (coarse) wavenumber grids for\n    an atomic cross section calculation.\n    \n    Note: for atoms a single grid is used over the entire wavenumber range.\n\n    '''\n    \n    # Define the minimum and maximum wavenumber on grid to go slightly beyond user's output limits\n    nu_min = 1\n    nu_max = nu_out_max + 1000\n    \n    # First, we need to find values of gamma_V for reference wavenumber (1000 cm^-1)\n    alpha_ref = np.sqrt(2.0*kb*T*np.log(2)/m) * (np.array(1000.0)/c)  # Doppler HWHM at reference wavenumber\n    gamma_ref = np.min(gamma)                                            # Find minimum value of Lorentzian HWHM\n    gamma_V_ref = Voigt.HWHM(gamma_ref, alpha_ref)                       # Reference Voigt width\n    \n    # Calculate Voigt width for each transition\n    alpha = np.sqrt(2.0*kb*T*np.log(2)/m) * (np.array(nu_0)/c)   # Doppler HWHM for each transition\n    gamma_V = Voigt.HWHM(gamma, alpha)   # Voigt HWHM\n    \n    #**** Now compute properties of computational (fine) and output (coarse) wavenumber grid *****\n    \n    # Wavenumber spacing of of computational grid (smallest of gamma_V_ref/6 or 0.01cm^-1)\n    dnu_fine = np.minimum(gamma_V_ref*Voigt_sub_spacing, dnu_out)      \n    \n    # Number of points on fine grid (rounded)\n    N_points_fine = int((nu_max-nu_min)/dnu_fine + 1)\n    \n    # Adjust dnu_fine slightly to match an exact integer number of grid spaces\n    dnu_fine = (nu_max-nu_min)/(N_points_fine - 1)\n    \n    cutoffs = np.zeros(len(nu_0))   # Line wing cutoffs for each line\n    \n    # Line cutoffs at min(500 gamma_V, 1000cm^-1)\n    for i in range(len(nu_0)):\n        \n        cutoffs[i] = dnu_fine * (int((Voigt_cutoff*gamma_V[i])/dnu_fine))\n\n        if (cutoffs[i] >= cut_max): cutoffs[i] = cut_max\n                \n        # Special cases for alkali resonant lines\n        if ((atom == 'Na') and (int(nu_0[i]) in [16978, 16960])):\n            cutoffs[i] = 9000.0   # Cutoff @ +/- 9000 cm^-1\n        elif ((atom == 'K') and  (int(nu_0[i]) in [13046, 12988])): \n            cutoffs[i] = 9000.0   # Cutoff @ +/- 9000 cm^-1\n      \n    # Calculate detuning frequencies for Na and K resonance lines (after Baudino+2015)\n    if (atom == 'Na'): \n        nu_detune = 30.0 * np.power((T/500.0), 0.6)\n    elif (atom == 'K'): \n        nu_detune = 20.0 * np.power((T/500.0), 0.6)\n    else: \n        nu_detune = cut_max\n    \n    # Evaluate number of frequency points for each Voigt function up to cutoff (one tail)\n    N_Voigt_points = ((cutoffs/dnu_fine).astype(np.int64)) + 1  \n    \n    # Define start and end points of fine grid\n    nu_fine_start = nu_min\n    nu_fine_end = nu_max\n    \n    # Initialise output grid\n    N_points_out = int((nu_out_max-nu_out_min)/dnu_out + 1)     # Number of points on coarse grid (uniform)\n    nu_out = np.linspace(nu_out_min, nu_out_max, N_points_out)  # Create coarse (output) grid\n    \n    # Initialise cross section arrays on each grid\n    sigma_fine = np.zeros(N_points_fine)    # Computational (fine) grid\n    sigma_out = np.zeros(N_points_out)      # Coarse (output) grid\n    \n    return (sigma_fine, sigma_out, nu_detune, N_points_fine, N_Voigt_points, alpha, \n            cutoffs, nu_min, nu_max, nu_fine_start, nu_fine_end, nu_out, N_points_out)\n\ndef create_nu_grid(nu_out_min, nu_out_max, dnu_out):\n\n    # Define the minimum and maximum wavenumber on grid to go slightly beyond user's output limits\n    nu_min = min(1, nu_out_min)\n    nu_max = nu_out_max + 1000\n        \n    # Initialise computational grid\n    N_compute = int((nu_max - nu_min)/dnu_out + 1)       # Number of points on computational grid (uniform)\n    nu_compute = np.linspace(nu_min, nu_max, N_compute)  # Create computational (output) grid\n      \n    return nu_compute\n    \n\ndef summon(database = '', species = '', isotope = 'default', VALD_data_dir = '',\n           linelist = 'default', ionization_state = 1, **kwargs):\n    '''\n    Makes calls to other downloader files to retrieve the data from the desired database\n\n\n    Parameters\n    ----------\n    database : TYPE, optional\n        DESCRIPTION. The default is ''.\n    species : TYPE, optional\n        DESCRIPTION. The default is ''.\n    isotope : TYPE, optional\n        DESCRIPTION. The default is 'default'.\n    linelist : TYPE, optional\n        DESCRIPTION. The default is 'default'.\n    ionization_state : TYPE, optional\n        DESCRIPTION. The default is 1.\n    **kwargs : TYPE\n        DESCRIPTION.\n\n    Returns\n    -------\n    None.\n\n    '''\n    \n    # Check if the user has specified a chemical species and line list database\n    if database != '' and species != '': \n        user_prompt = False\n    else: \n        user_prompt = True\n        \n    # If the user wants to be guided via terminal prompts\n    if user_prompt: \n        \n        while True:\n            database = input('Which line list database do you wish to download from (ExoMol, HITRAN, HITEMP, or VALD)?\\n')\n            database = database.lower()\n            if database == 'exomol' or database == 'hitran' or database == 'hitemp' or database == 'vald' :\n                break\n            else:\n                print(\"\\n ----- This is not a supported database, please try again ----- \")\n        \n        if database == 'exomol': \n            mol, iso, lin, URL = ExoMol.determine_linelist()\n            ExoMol.summon_ExoMol(mol, iso, lin, URL)\n            \n        if database == 'hitran':\n            mol, iso = HITRAN.determine_linelist()\n            HITRAN.summon_HITRAN(mol, iso)\n            \n        if database == 'hitemp':\n            mol, iso = HITEMP.determine_linelist()\n            HITEMP.summon_HITEMP(mol, iso)\n            \n        if database == 'vald':\n            mol, ion = VALD.determine_linelist(VALD_data_dir)\n            VALD.summon_VALD(mol, ion, VALD_data_dir)\n            \n    # If the user calls summon with parameters directly passed in\n    if not user_prompt: \n        \n        db = database.lower()\n        spe = species\n        \n        if isinstance(isotope, str):\n            try:\n                isotope = int(isotope)\n            except ValueError:\n                pass\n            \n        iso = isotope\n        lin = linelist\n        ion = ionization_state\n        \n        if db == 'exomol':\n            \n            spe = re.sub('[+]', '_p', spe)  # Handle ions\n            iso = re.sub('[+]', '_p', iso)  # Handle ions\n            \n            if isotope == 'default':\n                ExoMol.check(spe)\n                iso = ExoMol.get_default_iso(spe)\n            if linelist == 'default':\n                ExoMol.check(spe, iso)\n                lin = ExoMol.get_default_linelist(spe, iso)\n\n            ExoMol.check(spe, iso, lin)\n            URL = \"http://exomol.com/data/molecules/\" + spe + '/' + iso + '/' + lin + '/'\n            ExoMol.summon_ExoMol(spe, iso, lin, URL)\n            \n        elif db == 'hitran':\n            \n            if isotope == 'default':\n                iso = 1\n            \n            spe = HITRAN.check(spe, iso)\n            HITRAN.summon_HITRAN(spe, iso)\n            \n        elif db == 'hitemp':\n            \n            if isotope == 'default':\n                iso = 1\n                \n            spe = HITEMP.check(spe, iso)\n            HITEMP.summon_HITEMP(spe, iso)\n            \n        elif db == 'vald':\n            \n            VALD.check(spe, ion, VALD_data_dir)\n            VALD.summon_VALD(spe, ion, VALD_data_dir)\n        \n        else:\n            print(\"\\n ----- You have not passed in a valid database. Please try calling the summon() function again. ----- \")\n            sys.exit(0)\n        \n    print(\"\\nLine list ready.\\n\")\n    \n    \ndef compute_cross_section(input_dir, database, species, log_pressure, temperature, isotope = 'default', \n                          ionization_state = 1, linelist = 'default', cluster_run = False, \n                          nu_out_min = 200, nu_out_max = 25000, dnu_out = 0.01, broad_type = 'default', \n                          X_H2 = 0.85, X_He = 0.15, Voigt_cutoff = 500, Voigt_sub_spacing = (1.0/6.0), \n                          N_alpha_samples = 500, S_cut = 1.0e-100, cut_max = 30.0, N_cores = 1, **kwargs):\n    '''\n    Main function to calculate molecular and atomic cross sections.\n\n    '''\n    \n    print(\"Beginning cross-section computations...\")\n    \n    # Start clock for timing program\n    t_start = time.perf_counter()\n    \n    # Configure numba to paralelise with the user specified number of cores\n    numba.set_num_threads(N_cores)\n    \n    # Cast log_pressure and temperature to lists if they are not already\n    if not isinstance(log_pressure, list) and not isinstance(log_pressure, np.ndarray):  \n        log_pressure = [log_pressure]\n    \n    if not isinstance(temperature, list) and not isinstance(temperature, np.ndarray):  \n        temperature = [temperature]\n        \n    # Cast all temperatures and pressures to floats\n    for i in range(len(log_pressure) - 1):\n        log_pressure[i] = float(log_pressure[i])\n    \n    for i in range(len(temperature) - 1):\n        temperature[i] = float(temperature[i])\n    \n    database = database.lower()\n    \n    # Locate the input_directory where the line list is stored\n    input_directory = download.find_input_dir(input_dir, database, species, isotope, ionization_state, linelist)\n    \n    # Use the input directory to define these right at the start\n    linelist, isotopologue = download.parse_directory(input_directory, database)\n    \n    # HITRAN, HITEMP, and VALD do not have seperate line list names\n    if database != 'exomol':\n        linelist = database\n    \n    # Load full set of downloaded line list files\n    linelist_files = [filename for filename in os.listdir(input_directory) if filename.endswith('.h5')]\n    \n    if database == 'exomol':\n        print(\"Loading ExoMol format\")\n        E, g, J = ExoMol.load_states(input_directory)  # Load from .states file\n    \n    elif database == 'hitran':\n        print(\"Loading HITRAN format\")\n        # Nothing else required at this stage\n    \n    elif database == 'hitemp':\n        print(\"Loading HITEMP format\")\n        # Nothing else required at this stage\n        \n    elif database == 'vald':\n        print(\"Loading VALD format\")\n        nu_0, gf, E_low, E_up, J_low, l_low, l_up, \\\n        Gamma_nat, Gamma_vdw, alkali = VALD.load_line_list(input_directory, species)\n        \n    # Load partition function\n    T_pf_raw, Q_raw = load_pf(input_directory)\n    \n    # Find mass of the species\n    m = mass(species, isotopologue, linelist) * u\n\n    # Check if we have a molecule or an atom\n    is_molecule = check_molecule(species)\n    \n    # Store ionisation state as roman numeral for later (atoms only)\n    roman_num = ''\n    if is_molecule == False:\n        for i in range(ionization_state):\n            roman_num += 'I'\n        \n    # If user didn't specify a type of pressure broadening, determine based on available broadening data\n    if is_molecule and broad_type == 'default':\n        \n        broad_type = broadening.det_broad(input_directory)\n        \n        if broad_type == 'H2-He':\n            J_max, gamma_0_H2, n_L_H2, gamma_0_He, n_L_He = broadening.read_H2_He(input_directory)\n            \n        elif broad_type == 'air':\n            J_max, gamma_0_air, n_L_air = broadening.read_air(input_directory)\n            \n        elif broad_type == 'SB07':\n            J_max, gamma_0_SB07 = broadening.read_SB07(input_directory)\n            \n    # If user specifed a pressure broadening prescription, proceed to load the relevant broadening file\n    elif is_molecule and broad_type != 'default':\n        \n        if (broad_type == 'H2-He' and 'H2.broad' in os.listdir(input_directory) \n                                  and 'He.broad' in os.listdir(input_directory)):\n            J_max, gamma_0_H2, n_L_H2, gamma_0_He, n_L_He = broadening.read_H2_He(input_directory)\n        \n        elif broad_type == 'air' and 'air.broad' in os.listdir(input_directory):\n            J_max, gamma_0_air, n_L_air = broadening.read_air(input_directory)\n            \n        elif broad_type == 'SB07':\n            broadening.create_SB07(input_directory)\n            J_max, gamma_0_SB07 = broadening.read_SB07(input_directory)\n            \n        elif broad_type == 'custom' and 'custom.broad' in os.listdir(input_directory):\n            J_max, gamma_0_air, n_L_air = broadening.read_custom(input_directory)\n        \n        elif broad_type == 'fixed':\n            J_max = 0\n        \n        else:\n            print(\"\\nYou did not enter a valid type of pressure broadening. Please try again.\")\n            sys.exit(0)\n            \n    # For atoms, only H2-He pressure broadening is currently supported\n    elif is_molecule == False:\n        \n        if broad_type != 'default' and broad_type != 'H2-He':\n            print(\"You did not specify a valid choice of pressure broadening.\\n\" \n                  \"For atoms the only supported option is 'H2-He', so we will continue by using that.\" )\n        \n        broad_type = 'H2-He'\n        \n        gamma_0_H2, gamma_0_He, \\\n        n_L_H2, n_L_He = broadening.read_atom(species, nu_0, gf, E_low, E_up, \n                                              J_low, l_low, l_up, Gamma_nat, \n                                              Gamma_vdw, alkali, m)\n    \n    #***** Load pressure and temperature for this calculation *****#\n    P_arr = np.power(10.0, log_pressure)  # Pressure array (bar)\n    log_P_arr = np.array(log_pressure)    # log_10 (Pressure/bar) array\n    T_arr = np.array(temperature)         # Temperature array (K)\n    \n    # If conducting a batch run on a cluster\n    if (cluster_run == True):\n            \n        try:\n            idx_PT = int(sys.argv[1])\n            \n        except IndexError:\n            print(\"\\n----- You need to enter a command line argument if cluster_run is set to True. ----- \")\n            sys.exit(0)\n            \n        except ValueError:\n            print(\"\\n----- The command line argument needs to be an int. -----\")\n            sys.exit(0)\n            \n        if idx_PT >= len(log_P_arr) * len(T_arr):\n            print(\"\\n----- You have provided a command line argument that is out of range for the specified pressure and temperature arrays. -----\")\n            sys.exit(0)\n        \n        P = P_arr[idx_PT//len(T_arr)]   # Atmospheric pressure (bar)\n        T = T_arr[idx_PT%len(T_arr)]    # Atmospheric temperature (K)\n        \n        # For a cluster run, each core separately handles a single (P,T) combination\n        N_P = 1\n        N_T = 1\n        \n    # If running on a single machine, compute a cross section for each (P,T) pair sequentially\n    else:\n        \n        N_P = len(log_P_arr)\n        N_T = len(T_arr)\n    \n    # Compute cross section for each pressure and temperature point\n    for p in range(N_P):\n        for t in range(N_T):\n            \n            # When not running on a cluster, select the next (P,T) pair\n            if (cluster_run == False):\n                \n                P = P_arr[p]   # Atmospheric pressure (bar)\n                T = T_arr[t]   # Atmospheric temperature (K)\n            \n            # Interpolate the tabulated partition function to the desired temperature and reference temperature\n            Q_T, Q_T_ref = interpolate_pf(T_pf_raw, Q_raw, T, T_ref)\n            \n            # Handle pressure broadening, wavenumber grid creation and Voigt profile pre-computation for molecules\n            if is_molecule:\n                \n                # Compute Lorentzian HWHM as a function of J_low\n                if broad_type == 'H2-He':\n                    gamma = broadening.compute_H2_He(gamma_0_H2, T_ref, T, \n                                                     n_L_H2, P, P_ref, X_H2, \n                                                     gamma_0_He, n_L_He, X_He)\n                elif broad_type == 'air':\n                    gamma = broadening.compute_air(gamma_0_air, T_ref, T, \n                                                   n_L_air, P, P_ref)\n                elif broad_type == 'SB07':\n                    gamma = broadening.compute_SB07(gamma_0_SB07, P, P_ref)\n                elif broad_type == 'custom': \n                    gamma = broadening.compute_air(gamma_0_air, T_ref, T,    # Computation step is the same as for air broadening\n                                                   n_L_air, P, P_ref)\n                elif broad_type == 'fixed':\n                    gamma = np.array([(gamma_0_fixed * np.power((T_ref/T), n_L_fixed) * (P/P_ref))])  # Fixed Lorentizian HWHM (1 element array)\n                    \n                # Create wavenumber grid for cross section compuation\n                nu_compute = create_nu_grid(nu_out_min, nu_out_max, dnu_out)\n                                                                                                                            \n                # Initialise cross section arrays for computations\n                sigma_compute = np.zeros(len(nu_compute))    # Computational grid\n                \n                #***** Pre-compute Voigt function array for molecules *****#\n    \n                print('Pre-computing Voigt profiles...')\n    \n                t1 = time.perf_counter()    \n                \n                # Pre-compute template Voigt profiles\n                (nu_sampled, alpha_sampled, \n                 cutoffs, N_Voigt, Voigt_arr, \n                 dV_da_arr, dV_dnu_arr, \n                 dnu_Voigt) = Voigt.precompute_molecules(nu_compute, dnu_out, m, T, \n                                                         Voigt_sub_spacing, Voigt_cutoff, \n                                                         N_alpha_samples, gamma, cut_max)\n                \n                t2 = time.perf_counter()\n                time_precompute = t2-t1\n            \n                print('Voigt profiles computed in ' + str(time_precompute) + ' s')  \n                \n            # Handle pressure broadening and wavenumber grid creation for atoms\n            elif is_molecule == False: \n                \n                # Compute Lorentzian HWHM line-by-line for atoms\n                gamma = broadening.compute_H2_He(gamma_0_H2, T_ref, T, n_L_H2, \n                                                 P, P_ref, X_H2, gamma_0_He, \n                                                 n_L_He, X_He)\n                \n                # Add natural broadening for each line\n                gamma += ((1.0/(4.0*np.pi*(100.0*c))) * Gamma_nat)  \n            \n                # Create wavenumber grid properties for cross section calculation      \n                nu_compute = create_nu_grid(nu_out_min, nu_out_max, dnu_out)\n                \n                # Initialise cross section arrays for computations\n                sigma_compute = np.zeros(len(nu_compute))    # Computational grid\n                \n                #***** Pre-compute Voigt function array for molecules *****#\n    \n                print('Pre-computing Voigt profiles...')\n    \n                t1 = time.perf_counter()    \n                \n                # Pre-compute Voigt profiles for each line on computational grid\n                cutoffs, N_Voigt, Voigt_arr = Voigt.precompute_atoms(species, nu_compute, m, T, gamma, \n                                                                     nu_0, Voigt_cutoff, cut_max)\n                \n                t2 = time.perf_counter()\n                time_precompute = t2-t1\n            \n                print('Voigt profiles computed in ' + str(time_precompute) + ' s')  \n                \n\n                                                                                                                                        \n            print(\"Pre-computation steps complete\")\n            \n            if is_molecule:\n                print('Generating cross section for ' + species + ' at P = ' + str(P) + ' bar, T = ' + str(T) + ' K')\n            else:\n                print('Generating cross section for ' + species + ' ' + roman_num + ' at P = ' + str(P) + ' bar, T = ' + str(T) + ' K')\n\n            # Call relevant cross section computation function for given line list\n            if database == 'exomol':    \n                calculate.cross_section_EXOMOL(linelist_files, input_directory, \n                                               nu_compute, sigma_compute, alpha_sampled, \n                                               m, T, Q_T, g, E, J, J_max, N_Voigt, cutoffs,\n                                               Voigt_arr, dV_da_arr, dV_dnu_arr, dnu_Voigt, S_cut)\n                \n            elif database in ['hitran', 'hitemp']:\n                calculate.cross_section_HITRAN(linelist_files, input_directory, \n                                               nu_compute, sigma_compute, alpha_sampled, \n                                               m, T, Q_T, Q_T_ref, J_max, N_Voigt, cutoffs,\n                                               Voigt_arr, dV_da_arr, dV_dnu_arr, dnu_Voigt, S_cut)\n                \n            elif database == 'vald':\n                produce_total_cross_section_VALD_atom(nu_compute, sigma_compute, nu_0, \n                                                      E_low, gf, m, T, Q_T, N_Voigt, \n                                                      cutoffs, Voigt_arr, S_cut)\n                                    \n            # Clip ends from computational grid to leave output wavenumber and cross section grids            \n            nu_out = nu_compute[(nu_compute >= nu_out_min) & (nu_compute <= nu_out_max)]\n            sigma_out = sigma_compute[(nu_compute >= nu_out_min) & (nu_compute <= nu_out_max)]\n        \n            # Create output directory (if not already present)\n            output_directory = re.sub('/input/', '/output/', input_directory)\n    \n            if not os.path.exists(output_directory):\n                os.makedirs(output_directory)\n    \n            # Write cross section to file\n            write_output(output_directory, species, roman_num, \n                         T, np.log10(P), nu_out, sigma_out)\n    \n    # Print final runtime\n    t_final = time.perf_counter()\n    total_final = t_final-t_start\n    \n    print('Total runtime: ' + str(total_final) + ' s')\n    \n    return nu_out, sigma_out\n", "meta": {"hexsha": "63763d6728be7c5c0c496381a63057cfc72ce5e5", "size": 30528, "ext": "py", "lang": "Python", "max_stars_repo_path": "excalibur/core.py", "max_stars_repo_name": "arnav-agrawal/excalibur-alpha", "max_stars_repo_head_hexsha": "0e77341b310147caeba52aea00ccf2dccf7feb72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "excalibur/core.py", "max_issues_repo_name": "arnav-agrawal/excalibur-alpha", "max_issues_repo_head_hexsha": "0e77341b310147caeba52aea00ccf2dccf7feb72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-23T07:39:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-23T07:39:17.000Z", "max_forks_repo_path": "excalibur/core.py", "max_forks_repo_name": "arnav-agrawal/excalibur-alpha", "max_forks_repo_head_hexsha": "0e77341b310147caeba52aea00ccf2dccf7feb72", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9340659341, "max_line_length": 148, "alphanum_fraction": 0.5577502621, "include": true, "reason": "import numpy,from scipy,import numba", "num_tokens": 7681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.17214552767449207}}
{"text": "\"\"\"\n\nIntergalacticMedium.py\n\nAuthor: Jordan Mirocha\nAffiliation: University of Colorado at Boulder\nCreated on: Fri May 24 11:31:06 2013\n\nDescription: \n\n\"\"\"\n\nimport numpy as np\nfrom ..util.Warnings import *\nfrom ..util import ProgressBar\nfrom ..physics.Constants import *\nimport types, os, re, sys, pickle\nfrom ..util.Misc import num_freq_bins\nfrom ..physics import SecondaryElectrons\nfrom scipy.integrate import dblquad, romb, simps, quad, trapz\nfrom ..util.Warnings import tau_tab_z_mismatch, tau_tab_E_mismatch\n\ntry:\n    import h5py\n    have_h5py = True    \nexcept ImportError:\n    have_h5py = False\n\ntry:\n    from mpi4py import MPI\n    rank = MPI.COMM_WORLD.rank\n    size = MPI.COMM_WORLD.size\nexcept ImportError:\n    rank = 0\n    size = 1\n\nlog10 = np.log(10.)\nE_th = np.array([13.6, 24.4, 54.4])\n\ndefkwargs = \\\n{\n 'zf':None, \n 'xray_flux':None, \n 'epsilon_X': None,\n 'Gamma': None,\n 'gamma': None,\n 'return_rc': False, \n 'energy_units':False, \n 'Emax': None,\n #'zxavg':0.0,\n #'igm':True,\n 'xavg': 0.0,\n 'igm_h_1': 1.0,\n 'igm_h_2': 0.0,\n 'igm_he_2': 0.0,\n 'igm_he_3': 0.0,\n 'cgm_h_1': 1.0,\n 'cgm_h_2': 0.0,\n 'cgm_he_2': 0.0,\n 'cgm_he_3': 0.0,\n 'igm_e': 0.0,\n}\n\nspecies_i_to_str = {0:'h_1', 1:'he_1', 2:'he_2'}\n\nclass GlobalVolume(object):\n    def __init__(self, background):\n        \"\"\"\n        Initialize a GlobalVolume.\n        \n        Parameters\n        ----------\n        background : ares.solvers.UniformBackground instance.\n        \n        \"\"\"\n\n        self.background = background\n        self.pf = background.pf\n        self.grid = background.grid\n        self.cosm = background.cosm\n        self.hydr = background.hydr\n        self.pops = background.pops\n        self.Npops = len(self.pops)\n        \n        # Include helium opacities approximately?\n        self.approx_He = self.pf['include_He'] and self.pf['approx_He']\n        \n        # Include helium opacities self-consistently?\n        self.self_consistent_He = self.pf['include_He'] \\\n            and (not self.pf['approx_He'])\n\n        self.esec = \\\n            SecondaryElectrons(method=self.pf[\"secondary_ionization\"])  \n\n        # Choose function for computing bound-free absorption cross-sections                \n        if self.pf['approx_sigma']:\n            from ..physics.CrossSections import \\\n                ApproximatePhotoIonizationCrossSection as sigma\n        else:\n            from ..physics.CrossSections import \\\n                PhotoIonizationCrossSection as sigma\n\n        self.sigma = sigma\n        self.sigma0 = sigma(E_th[0])    # Hydrogen ionization threshold\n\n        self._set_integrator()\n\n    @property\n    def rates_no_RT(self):\n        if not hasattr(self, '_rates_no_RT'):\n            self._rates_no_RT = \\\n                {'k_ion': np.zeros((self.grid.dims,\n                    self.grid.N_absorbers)),\n                 'k_heat': np.zeros((self.grid.dims,\n                    self.grid.N_absorbers)),\n                 'k_ion2': np.zeros((self.grid.dims,\n                    self.grid.N_absorbers, self.grid.N_absorbers)),\n                }\n\n        return self._rates_no_RT\n\n    #def _fetch_tau(self, pop, zpf, Epf):\n    #    \"\"\"\n    #    Look for optical depth tables. Supply corrected energy and redshift\n    #    arrays if there is a mistmatch between those generated from information\n    #    in the parameter file and those found in the optical depth table.\n    #    \n    #    .. note:: This will only be called from UniformBackground, and on\n    #        populations which are using the generator framework.\n    #    \n    #    Parameters\n    #    ----------\n    #    popid : int\n    #        ID # for population of interest.\n    #    zpf : np.ndarray\n    #        What the redshifts should be according to the parameter file.    \n    #    Epf : np.ndarray\n    #        What the energies should be according to the parameter file.\n    #    \n    #    Returns\n    #    -------\n    #    Energies and redshifts, potentially revised from Epf and zpf.\n    #    \n    #    \"\"\"\n    #    \n    #    for i in range(self.Npops):\n    #        if pop == self.pops[i]:\n    #            band = self.background.bands_by_pop[i]\n    #            break\n    #        \n    #    # First, look in CWD or $ARES (if it exists)\n    #    self.tabname = self._load_tau(pop, pop.pf['tau_prefix'])\n    #            \n    #    if not self.tabname:\n    #        return zpf, Epf, None\n    #    \n    #    # If we made it this far, we found a table that may be suitable\n    #    ztab, Etab, tau = self._read_tau(self.tabname)\n    #            \n    #    # Return right away if there's no potential for conflict\n    #    if (zpf is None) and (Epf is None):\n    #        return ztab, Etab, tau\n    #        \n    #    # Figure out if the tables need fixing    \n    #    zmax_ok = \\\n    #        (ztab.max() >= zpf.max()) or \\\n    #        np.allclose(ztab.max(), zpf.max())\n    #    zmin_ok = \\\n    #        (ztab.min() <= zpf.min()) or \\\n    #        np.allclose(ztab.min(), zpf.min())\n    #                            \n    #    Emin_ok = \\\n    #        (Etab.min() <= Epf.min()) or \\\n    #        np.allclose(Etab.min(), Epf.min())\n    #    \n    #    # Results insensitive to Emax (so long as its relatively large)\n    #    # so be lenient with this condition (100 eV or 1% difference\n    #    # between parameter file and lookup table)\n    #    Emax_ok = np.allclose(Etab.max(), Epf.max(), atol=100., rtol=1e-2)\n    #            \n    #    # Check redshift bounds\n    #    if not (zmax_ok and zmin_ok):\n    #        if not zmax_ok:\n    #            tau_tab_z_mismatch(self, zmin_ok, zmax_ok, ztab)\n    #            sys.exit(1)\n    #        else:\n    #            if self.pf['verbose']:\n    #                tau_tab_z_mismatch(self, zmin_ok, zmax_ok, ztab)\n    #    \n    #    if not (Emax_ok and Emin_ok):\n    #        if self.pf['verbose']:\n    #            tau_tab_E_mismatch(pop, self.tabname, Emin_ok, Emax_ok, Etab)\n    #            \n    #        if Etab.max() < Epf.max():\n    #            sys.exit(1)\n    #                                                        \n    #    # Correct for inconsistencies between parameter file and table\n    #    # By effectively masking out those elements with tau -> inf\n    #    if Epf.min() > Etab.min():\n    #        Ediff = Etab - Epf.min()\n    #        i_E0 = np.argmin(np.abs(Ediff))\n    #        if Ediff[i_E0] < 0:\n    #            i_E0 += 1\n    #    \n    #        #tau[:,0:i_E0+1] = np.inf\n    #    else:\n    #        i_E0 = 0\n    #    \n    #    if Epf.max() < Etab.max():\n    #        Ediff = Etab - Epf.max()\n    #        i_E1 = np.argmin(np.abs(Ediff))\n    #        if Ediff[i_E1] < 0:\n    #            i_E1 += 1\n    #    \n    #        #tau[:,i_E1+1:] = np.inf\n    #    else:\n    #        i_E1 = None\n    #        \n    #    # We're done!\n    #    return ztab, Etab[i_E0:i_E1], tau[:,i_E0:i_E1]\n\n    @property\n    def E(self):\n        if not hasattr(self, '_E'):\n            self._tabulate_atomic_data()\n    \n        return self._E\n\n    @property\n    def sigma_E(self):\n        if not hasattr(self, '_sigma_E'):\n            self._tabulate_atomic_data()\n        \n        return self._sigma_E\n        \n    def _tabulate_atomic_data(self):\n        \"\"\"\n        Pre-compute cross sections and such for each source population.\n        \n        Returns\n        -------\n        Nothing. Sets the following attributes:\n        \n        sigma_E\n        log_sigma_E\n        fheat, flya, fion\n        \n        \"\"\"\n\n        # Remember: these will all be [Npops, Nbands/pop, Nenergies/band]\n        self._E = self.background.energies\n        self.logE = [[] for k in range(self.Npops)]\n        self.dlogE = [[] for k in range(self.Npops)]\n        self.fheat = [[] for k in range(self.Npops)]\n        self.flya = [[] for k in range(self.Npops)]\n        \n        # These are species dependent\n        self._sigma_E = {}\n        self.fion = {}\n        for species in ['h_1', 'he_1', 'he_2']:\n            self._sigma_E[species] = [[] for k in range(self.Npops)]\n            self.fion[species] = [[] for k in range(self.Npops)]\n            \n        ##\n        # Note: If secondary_ionization > 1, there will be an ionized fraction\n        # dimension in fion and fheat.\n        ##    \n        \n        # Loop over populations\n        for i, pop in enumerate(self.pops):\n                  \n            # This means the population is completely approximate\n            if not np.any(self.background.solve_rte[i]):\n                self.logE[i] = [None]\n                self.dlogE[i] = [None]\n                self.fheat[i] = [None]\n                self.flya[i] = [None]\n                \n                for species in ['h_1', 'he_1', 'he_2']:\n                    self.fion[species][i] = [None]\n                    self._sigma_E[species][i] = [None]\n                \n                continue\n            \n            ##\n            # If we make it here, the population has at least one band that\n            # requires a detailed solution to the RTE    \n            ##\n            \n            Nbands = len(self.background.energies[i])\n            \n            self.logE[i] = [None for k in range(Nbands)]\n            self.dlogE[i] = [None for k in range(Nbands)]\n            self.fheat[i] = [None for k in range(Nbands)]\n            self.flya[i] = [None for k in range(Nbands)]\n            for species in ['h_1', 'he_1', 'he_2']:\n                self.fion[species][i] = [None for k in range(Nbands)]\n                self._sigma_E[species][i] = [None for k in range(Nbands)]\n\n            # Loop over each band for this population\n            for j, band in enumerate(self.background.bands_by_pop[i]):\n\n                if band is None:\n                    continue\n                            \n                need_tab = self.pops[i].is_xray_src \\\n                    and np.any(np.array(band) > E_LL)\n                                                                    \n                if (not self.background.solve_rte[i][j]) or \\\n                   (not need_tab):\n                    continue\n                else:    \n                    self.fheat[i][j] = \\\n                        [np.ones([self.background.energies[i][j].size, \n                         len(self.esec.x)]) \\\n                         for j in range(Nbands)]\n                    self.flya[i] = \\\n                        [np.ones([self.background.energies[i][j].size, \n                         len(self.esec.x)]) \\\n                         for j in range(Nbands)]\n                \n                    for species in ['h_1', 'he_1', 'he_2']:\n                        if self.esec.method > 1:\n                            self._sigma_E[species][i] = \\\n                                [np.ones([self.background.energies[i][j].size, \n                                 len(self.esec.x)]) \\\n                                 for j in range(Nbands)]\n                            self.fion[species][i] = \\\n                                [np.ones([self.background.energies[i][j].size, \n                                 len(self.esec.x)]) \\\n                                 for j in range(Nbands)]\n\n                        else:\n                            self._sigma_E[species][i] = [None for k in range(Nbands)]\n                            self.fion[species][i] = [None for k in range(Nbands)]\n                            self.fheat[i] = [None for k in range(Nbands)]\n                            self.flya[i] = [None for k in range(Nbands)]    \n                \n                # More convenient variables\n                E = self._E[i][j]\n                N = E.size\n\n                # Compute some things we need, like bound-free cross-section\n                self.logE[i][j] = np.log10(E)\n                self.dlogE[i][j] = np.diff(self.logE[i][j])\n                \n                # \n                for k, species in enumerate(['h_1', 'he_1', 'he_2']):\n                    self._sigma_E[species][i][j] = \\\n                        np.array(map(lambda E: self.sigma(E, k), E))\n\n                # Pre-compute secondary ionization and heating factors\n                if self.esec.method > 1:\n                \n                    # Don't worry: we'll fill these in in a sec!\n                    self.fheat[i][j] = np.ones([N, len(self.esec.x)])\n                    self.flya[i][j] = np.ones([N, len(self.esec.x)])\n                \n                    # Must evaluate at ELECTRON energy, not photon energy\n                    for k, nrg in enumerate(E - E_th[0]):\n                        self.fheat[i][j][k] = \\\n                            self.esec.DepositionFraction(self.esec.x, E=nrg, \n                            channel='heat')\n                        self.fion['h_1'][i][j][k] = \\\n                            self.esec.DepositionFraction(self.esec.x, E=nrg, \n                            channel='h_1')\n                \n                        if self.pf['secondary_lya']:\n                            self.flya[i][j][k] = \\\n                                self.esec.DepositionFraction(self.esec.x, E=nrg, \n                                channel='lya') \n                \n                    # Helium\n                    if self.pf['include_He'] and not self.pf['approx_He']:\n                \n                        # Don't worry: we'll fill these in in a sec!\n                        self.fion['he_1'][i][j] = np.ones([N, len(self.esec.x)])\n                        self.fion['he_2'][i][j] = np.ones([N, len(self.esec.x)])\n                \n                        for k, nrg in enumerate(E - E_th[1]):\n                            self.fion['he_1'][i][j][k] = \\\n                                self.esec.DepositionFraction(self.esec.x, \n                                E=nrg, channel='he_1')\n                \n                        for k, nrg in enumerate(E - E_th[2]):\n                            self.fion['he_2'][i][j][k] = \\\n                                self.esec.DepositionFraction(self.esec.x, \n                                E=nrg, channel='he_2')    \n                \n                    else:\n                        self.fion['he_1'][i][j] = np.zeros([N, len(self.esec.x)])\n                        self.fion['he_2'][i][j] = np.zeros([N, len(self.esec.x)])\n            \n            \n            \n            \n                \n        return        \n                                            \n    def _set_integrator(self):\n        self.integrator = self.pf[\"unsampled_integrator\"]\n        self.sampled_integrator = self.pf[\"sampled_integrator\"]\n        self.rtol = self.pf[\"integrator_rtol\"]\n        self.atol = self.pf[\"integrator_atol\"]\n        self.divmax = int(self.pf[\"integrator_divmax\"])\n    \n    #def _read_tau(self, fn):\n    #    \"\"\" Read optical depth table. \"\"\"\n    #    \n    #    if type(fn) is dict:\n    #        \n    #        E0 = fn['E'].min()\n    #        E1 = fn['E'].max()\n    #        E = fn['E']\n    #        z = fn['z']\n    #        x = z + 1\n    #        N = E.size\n    #            \n    #        R = x[1] / self.x[0]\n    #        \n    #        tau = fn['tau']\n    #\n    #    elif re.search('hdf5', fn):\n    #\n    #        f = h5py.File(self.tabname, 'r')\n    #\n    #        E0 = min(f['photon_energy'].value)\n    #        E1 = max(f['photon_energy'].value)\n    #        E = f['photon_energy'].value\n    #        z = f['redshift'].value\n    #        x = z + 1\n    #        N = E.size\n    #            \n    #        R = x[1] / x[0]\n    #        \n    #        tau = f['tau'].value\n    #        f.close()\n    #\n    #    elif re.search('npz', fn) or re.search('pkl', fn):    \n    #\n    #        if re.search('pkl', fn):\n    #            f = open(fn, 'rb')\n    #            data = pickle.load(f)\n    #        else:\n    #            f = open(fn, 'r')\n    #            data = dict(np.load(f))\n    #        \n    #        E0 = data['E'].min()\n    #        E1 = data['E'].max()            \n    #        E = data['E']\n    #        z = data['z']\n    #        x = z + 1\n    #        N = E.size\n    #        \n    #        R = x[1] / x[0]\n    #        \n    #        tau = tau = data['tau']\n    #        f.close()\n    #    else:\n    #        raise NotImplemented('Don\\'t know how to read %s.' % fn)\n    #\n    #    return z, E, tau\n    \n    #def _tau_name(self, pop, suffix='hdf5'):\n    #    \"\"\"\n    #    Return name of table based on its properties.\n    #    \"\"\"\n    #\n    #    if not have_h5py:\n    #        suffix == 'pkl'\n    #\n    #    HorHe = 'He' if self.pf['include_He'] else 'H'\n    #\n    #    zf = self.pf['final_redshift']\n    #    zi = self.pf['initial_redshift']\n    #\n    #    L, N = self._tau_shape(pop)\n    #\n    #    E0 = pop.pf['pop_Emin']\n    #    E1 = pop.pf['pop_Emax']\n    #\n    #    fn = lambda z1, z2, E1, E2: \\\n    #        'optical_depth_%s_%ix%i_z_%i-%i_logE_%.2g-%.2g.%s' \\\n    #        % (HorHe, L, N, z1, z2, E1, E2, suffix)\n    #\n    #    return fn(zf, zi, np.log10(E0), np.log10(E1)), fn\n    \n    #def _load_tau(self, pop, prefix=None):\n    #    \"\"\"\n    #    Find an optical depth table.\n    #    \"\"\"\n    #    \n    #    fn, fn_func = self._tau_name(pop)\n    #\n    #    if prefix is None:\n    #        ares_dir = os.environ.get('ARES')\n    #        if not ares_dir:\n    #            print \"No ARES environment variable.\"\n    #            return None\n    #        \n    #        input_dirs = [os.path.join(ares_dir,'input','optical_depth')]\n    #\n    #    else:\n    #        if type(prefix) is str:\n    #            input_dirs = [prefix]\n    #        else:\n    #            input_dirs = prefix\n    #\n    #    guess = os.path.join(input_dirs[0], fn)\n    #    if os.path.exists(guess):\n    #        return guess\n    #\n    #    ## Find exactly what table should be\n    #    zmin, zmax, Nz, lEmin, lEmax, chem, pre, post = self._parse_tab(fn)\n    #\n    #    ok_matches = []\n    #    perfect_matches = []\n    #    \n    #    # Loop through input directories\n    #    for input_dir in input_dirs:\n    #                        \n    #        # Loop over files in input_dir, look for best match\n    #        for fn1 in os.listdir(input_dir):\n    #            \n    #            if re.search('hdf5', fn1) and (not have_h5py):\n    #                continue\n    #\n    #            tab_name = os.path.join(input_dir, fn1)\n    #            \n    #            try:\n    #                zmin_f, zmax_f, Nz_f, lEmin_f, lEmax_f, chem_f, p1, p2 = \\\n    #                    self._parse_tab(fn1)\n    #            except:\n    #                continue\n    #\n    #            # Dealbreakers\n    #            if Nz_f != Nz:\n    #                continue\n    #            if zmax_f < zmax:\n    #                continue\n    #            if chem_f != chem:\n    #                continue\n    #\n    #            # Continue with possible matches\n    #            for fmt in ['pkl', 'npz', 'hdf5']:\n    #\n    #                if fn1 == fn and fmt == self.pf['preferred_format']:\n    #                    perfect_matches.append(tab_name)\n    #                    continue\n    #\n    #                if c and fmt == self.pf['preferred_format']:\n    #                    perfect_matches.append(tab_name)\n    #                    continue\n    #\n    #                # If number of redshift bins and energy range right...\n    #                if re.search(pre, fn1) and re.search(post, fn1):\n    #                    if re.search(fmt, fn1) and fmt == self.pf['preferred_format']:\n    #                        perfect_matches.append(tab_name)\n    #                    else:\n    #                        ok_matches.append(tab_name)\n    #                \n    #                # If number of redshift bins is right...\n    #                elif re.search(pre, fn1):\n    #                                            \n    #                    if re.search(fmt, fn1) and fmt == self.pf['preferred_format']:\n    #                        perfect_matches.append(tab_name)\n    #                    else:\n    #                        ok_matches.append(tab_name)\n    #    \n    #    if perfect_matches:\n    #        return perfect_matches[0]\n    #    elif ok_matches:\n    #        return ok_matches[0]\n    #    else:\n    #        return None\n            \n    #def _parse_tab(self, fn):\n    #            \n    #    tmp1, tmp2 = fn.split('_z_')\n    #    pre = tmp1[0:tmp1.rfind('x')]\n    #    red, tmp3 = fn.split('_logE_')\n    #    post = '_logE_' + tmp3.replace('.hdf5', '')\n    #    \n    #    # Find exactly what table should be\n    #    zmin, zmax = map(float, red[red.rfind('z')+2:].partition('-')[0::2])\n    #    logEmin, logEmax = map(float, tmp3[tmp3.rfind('E')+1:tmp3.rfind('.')].partition('-')[0::2])\n    #    \n    #    Nz = pre[pre.rfind('_')+1:]\n    #    \n    #    # Hack off Nz string and optical_depth_\n    #    chem = pre.strip(Nz)[14:-1]#.strip('optical_depth_')\n    #    \n    #    return zmin, zmax, int(Nz), logEmin, logEmax, chem, pre, post\n    #            \n    #def _tau_shape(self, pop):\n    #    \"\"\"\n    #    Determine dimensions of optical depth table.\n    #    \n    #    Unfortunately, this is a bit redundant with the procedure in\n    #    self._init_xrb, but that's the way it goes.\n    #    \"\"\"\n    #    \n    #    # Set up log-grid in parameter x = 1 + z\n    #    x = np.logspace(np.log10(1+self.pf['final_redshift']),\n    #        np.log10(1+self.pf['initial_redshift']),\n    #        int(pop.pf['pop_tau_Nz']))\n    #    z = x - 1.\n    #    logx = np.log10(x)\n    #    logz = np.log10(z)\n    #\n    #    # Constant ratio between elements in x-grid\n    #    R = x[1] / x[0]\n    #    logR = np.log10(R)\n    #    \n    #    E0 = pop.pf['pop_Emin']\n    #    \n    #    # Create mapping to frequency space\n    #    E = 1. * E0\n    #    n = 1\n    #    while E < pop.pf['pop_Emax']:\n    #        E = E0 * R**(n - 1)\n    #        n += 1    \n    #    \n    #    # Set attributes for dimensions of optical depth grid\n    #    L = len(x)\n    #    \n    #    # Frequency grid must be index 1-based.\n    #    N = num_freq_bins(L, zi=self.pf['initial_redshift'], \n    #        zf=self.pf['final_redshift'], Emin=E0, \n    #        Emax=pop.pf['pop_Emax'])\n    #    N -= 1\n    #    \n    #    return L, N\n    \n    def RestFrameEnergy(self, z, E, zp):\n        \"\"\"\n        Return energy of a photon observed at (z, E) and emitted at zp.\n        \"\"\"\n        \n        return E * (1. + zp) / (1. + z)\n    \n    def ObserverFrameEnergy(self, z, Ep, zp):\n        \"\"\"\n        What is the energy of a photon observed at redshift z and emitted \n        at redshift zp and energy Ep?\n        \"\"\"\n\n        return Ep * (1. + z) / (1. + zp)\n\n    def Jc(self, z, E):\n        \"\"\"\n        Flux corresponding to one photon per hydrogen atom at redshift z.\n        \"\"\"\n\n        return c * self.cosm.nH0 * (1. + z)**3 / 4. / np.pi \\\n            / (E * erg_per_ev / h)\n\n    def rate_to_coefficient(self, z, species=0, zone='igm', **kw):\n        \"\"\"\n        Convert an ionization/heating rate to a rate coefficient.\n        \n        Provides units of per atom.\n        \"\"\"\n\n        if self.pf['photon_counting']:\n            prefix = zone\n        else:\n            prefix = 'igm'\n        \n        if species == 0:     \n            weight = 1. / self.cosm.nH(z) / kw['%s_h_1' % prefix]\n        elif species == 1:\n            weight = 1. / self.cosm.nHe(z) / kw['%s_he_1' % prefix]\n        elif species == 2:\n            weight = 1. / self.cosm.nHe(z) / kw['%s_he_2' % prefix]\n\n        return weight\n\n    def coefficient_to_rate(self, z, species=0, **kw):\n        return 1. / self.rate_to_coefficient(z, species, **kw)\n\n    def _fix_kwargs(self, functionify=False, popid=0, band=0, **kwargs):\n\n        kw = defkwargs.copy()\n        kw.update(kwargs)\n\n        pop = self.pops[popid]\n\n        if functionify and type(kw['xavg']) is not types.FunctionType:\n            tmp = kw['xavg']\n            kw['xavg'] = lambda z: tmp\n\n        if kw['zf'] is None and pop is not None:\n            kw['zf'] = pop.zform\n        \n        if not self.background.solve_rte[popid][band]:\n            pass\n        elif (kw['Emax'] is None) and self.background.solve_rte[popid][band] and \\\n            np.any(self.background.bands_by_pop[popid] > pop.pf['pop_EminX']):\n            \n            kw['Emax'] = self.background.energies[popid][band][-1]\n                        \n        return kw\n        \n    def HeatingRate(self, z, species=0, popid=0, band=0, **kwargs):\n        \"\"\"\n        Compute heating rate density due to emission from this population. \n        \n        Parameters\n        ----------\n        z : int, float\n            Redshift of interest.\n        species : int\n            Atom whose liberated electrons cause heating.\n            Can be 0, 1, or 2 (HI, HeI, and HeII, respectively)\n        \n        ===============\n        relevant kwargs\n        ===============\n        xray_flux : np.ndarray\n            Array of fluxes corresponding to photon energies in self.igm.E.\n        return_rc : bool\n            Return actual heating rate, or rate coefficient for heating?\n            Former has units of erg s**-1 cm**-3, latter has units of \n            erg s**-1 cm**-3 atom**-1.    \n        \n        Returns\n        -------\n        Proper heating rate density in units of in erg s**-1 cm**-3 at redshift z,\n        due to electrons previously bound to input species.\n\n        \"\"\"\n                \n        pop = self.pops[popid]\n                                \n        if not pop.pf['pop_heat_src_igm'] or (z >= pop.zform):\n            return 0.0    \n            \n        if pop.pf['pop_heat_rate'] is not None:\n            return pop.HeatingRate(z)\n                \n        # Grab defaults, do some patches if need be    \n        kw = self._fix_kwargs(**kwargs)\n        \n        species_str = species_i_to_str[species]\n\n        if pop.pf['pop_k_heat_igm'] is not None:\n            return pop.pf['pop_k_heat_igm'](z)\n            \n        if band is not None:\n            solve_rte = self.background.solve_rte[popid][band]\n        else:\n            solve_rte = False    \n            \n        # Compute fraction of photo-electron energy deposited as heat\n        if pop.pf['pop_fXh'] is None:\n            \n            # Interpolate in energy and ionized fraction\n            if (self.esec.method > 1) and solve_rte:\n                if kw['igm_e'] <= self.esec.x[0]:\n                    fheat = self.fheat[popid][band][:,0]\n                else:\n                    i_x = np.argmin(np.abs(kw['igm_e'] - self.esec.x))\n                    if self.esec.x[i_x] > kw['igm_e']:\n                        i_x -= 1\n                        \n                    j = i_x + 1    \n                    \n                    fheat = self.fheat[popid][band][:,i_x] \\\n                        + (self.fheat[popid][band][:,j] - self.fheat[popid][band][:,i_x]) \\\n                        * (kw['igm_e'] - self.esec.x[i_x]) \\\n                        / (self.esec.x[j] - self.esec.x[i_x])                \n            elif self.esec.method > 1:\n                raise ValueError('Only know how to do advanced secondary ionization with solve_rte=True')\n            else:\n                fheat = self.esec.DepositionFraction(kw['igm_e'])[0]\n\n        else:\n            fheat = pop.pf['pop_fXh']\n         \n        # Assume heating rate density at redshift z is only due to emission\n        # from sources at redshift z\n        if not solve_rte:\n            weight = self.rate_to_coefficient(z, species, **kw)\n            \n            Lx = pop.LuminosityDensity(z, Emin=pop.pf['pop_Emin_xray'], \n                Emax=pop.pf['pop_Emax'])\n                                                \n            return weight * fheat * Lx * (1. + z)**3\n            \n        ##\n        # Otherwise, do the full calculation\n        ##\n        \n        # Re-normalize to help integrator\n        norm = J21_num * self.sigma0\n                \n        # Computes excess photo-electron energy due to ionizations by\n        # photons with energy E (normalized by sigma0 * Jhat)\n        if kw['fluxes'][popid] is None:\n\n            # If we're approximating helium, must add contributions now\n            # since we'll never explicitly call this method w/ species=1.\n            if self.approx_He:\n                integrand = lambda E, zz: \\\n                    self.rb.AngleAveragedFluxSlice(z, E, zz, xavg=kw['xavg']) \\\n                    * (self.sigma(E) * (E - E_th[0]) \\\n                    + self.cosm.y * self.sigma(E, species=1) * (E - E_th[1])) \\\n                    * fheat / norm / ev_per_hz\n                    \n            # Otherwise, just heating via hydrogen photo-electrons\n            else:\n                integrand = lambda E, zz: \\\n                    self.rb.AngleAveragedFluxSlice(z, E, zz, xavg=kw['xavg'], \n                    zxavg=kw['zxavg']) * self.sigma(E, species=1) \\\n                    * (E - E_th[species]) * fheat / norm / ev_per_hz\n        \n        # This means the fluxes have been computed already - integrate\n        # over discrete set of points\n        else:\n            \n            integrand = self.sigma_E[species_str][popid][band] \\\n                * (self._E[popid][band] - E_th[species])\n\n            if self.approx_He:\n                integrand += self.cosm.y * self.sigma_E['he_1'][popid][band] \\\n                    * (self._E[popid][band] - E_th[1])\n                    \n            integrand *= kw['fluxes'][popid][band] * fheat / norm / ev_per_hz\n                         \n        # Compute integral over energy\n        if type(integrand) == types.FunctionType:\n            heat, err = dblquad(integrand, z, kw['zf'], lambda a: self.E0, \n                lambda b: kw['Emax'], epsrel=self.rtol, epsabs=self.atol)\n        else:\n            if kw['Emax'] is not None:\n                imax = np.argmin(np.abs(self._E[popid][band] - kw['Emax']))\n                if imax == 0:\n                    return 0.0\n                elif imax == (len(self._E[popid][band]) - 1):  \n                    imax = None \n                                        \n                if self.sampled_integrator == 'romb':\n                    raise ValueError(\"Romberg's method cannot be used for integrating subintervals.\")\n                    heat = romb(integrand[0:imax] * self.E[0:imax], \n                        dx=self.dlogE[0:imax])[0] * log10\n                else:\n                    heat = simps(integrand[0:imax] * self._E[popid][band][0:imax], \n                        x=self.logE[popid][band][0:imax]) * log10\n            \n            else:\n                imin = np.argmin(np.abs(self._E[popid][band] - pop.pf['pop_Emin']))\n                \n                if self.sampled_integrator == 'romb':\n                    heat = romb(integrand[imin:] * self._E[popid][band][imin:], \n                        dx=self.dlogE[popid][band][imin:])[0] * log10\n                elif self.sampled_integrator == 'trapz':\n                    heat = np.trapz(integrand[imin:] * self._E[popid][band][imin:], \n                        x=self.logE[popid][band][imin:]) * log10\n                else:\n                    heat = simps(integrand[imin:] * self._E[popid][band][imin:], \n                        x=self.logE[popid][band][imin:]) * log10\n          \n        # Re-normalize, get rid of per steradian units\n        heat *= 4. * np.pi * norm * erg_per_ev\n\n        # Currently a rate coefficient, returned value depends on return_rc                                      \n        if kw['return_rc']:\n            pass\n        else:\n            heat *= self.coefficient_to_rate(z, species, **kw)\n\n        return heat    \n        \n    def IonizationRateCGM(self, z, species=0, popid=0, band=0, **kwargs):\n        \"\"\"\n        Compute growth rate of HII regions.\n\n        Parameters\n        ----------\n        z : float\n            current redshift\n        species : int\n            Ionization rate for what atom?\n            Can be 0, 1, or 2 (HI, HeI, and HeII, respectively)\n            \n        ===============\n        relevant kwargs\n        ===============\n        fluxes : np.ndarray\n            Array of fluxes corresponding to photon energies in self.igm.E.\n        return_rc : bool\n            Return actual heating rate, or rate coefficient for heating?\n            Former has units of erg s**-1 cm**-3, latter has units of \n            erg s**-1 cm**-3 atom**-1.    \n\n        Returns\n        -------\n        Ionization rate. Units determined by value of return_rc keyword\n        argument, which is False by default.\n\n        \"\"\"\n            \n        pop = self.pops[popid]\n        \n        if band is not None:\n            b = self.background.bands_by_pop[popid][band]\n            if not np.any(np.array(b) > E_LL):\n                return 0.0\n            if not np.allclose(b[0], E_LL, atol=0.1, rtol=0):\n                return 0.0\n        else:\n            b = [13.6, 24.6]\n        \n        if (not pop.pf['pop_ion_src_cgm']) or (z > pop.zform):\n            return 0.0\n            \n        # Need some guidance from 1-D calculations to do this\n        if species > 0:\n            return 0.0\n\n        if pop.pf['pop_ion_rate'] is not None:\n            return pop.IonizationRateCGM(z)    \n\n        kw = defkwargs.copy()\n        kw.update(kwargs)\n\n        if pop.pf['pop_k_ion_cgm'] is not None:\n            return self.pf['pop_k_ion_cgm'](z)\n\n        if kw['return_rc']:\n            weight = self.rate_to_coefficient(z, species, **kw)\n        else:\n            weight = 1.0\n            \n        Qdot = pop.PhotonLuminosityDensity(z, Emin=13.6, Emax=24.6)\n                                                                                                               \n        return weight * Qdot * (1. + z)**3\n            \n    def IonizationRateIGM(self, z, species=0, popid=0, band=0, **kwargs):\n        \"\"\"\n        Compute volume averaged hydrogen ionization rate.\n        \n        Parameters\n        ----------\n        z : float\n            redshift\n        species : int\n            HI, HeI, or HeII (species=0, 1, 2, respectively)\n            \n        Returns\n        -------\n        Volume averaged ionization rate in units of ionizations per \n        second. If return_rc=True, will be in units of ionizations per\n        second per atom.\n        \n        \"\"\"\n\n        pop = self.pops[popid]\n\n        # z between zform, zdead? must be careful for BHs\n        if (not pop.pf['pop_ion_src_igm']) or (z > pop.zform):\n            return 0.0\n\n        # Grab defaults, do some patches if need be\n        kw = self._fix_kwargs(**kwargs)\n        \n        species_str = species_i_to_str[species]\n\n        if pop.pf['pop_k_ion_igm'] is not None:\n            return pop.pf['pop_k_ion_igm'](z)\n\n        if band is not None:\n            solve_rte = self.background.solve_rte[popid][band]\n        else:\n            solve_rte = False\n\n        if (not solve_rte) or \\\n            (not np.any(self.background.bands_by_pop[popid] > pop.pf['pop_EminX'])):\n            \n            Lx = pop.LuminosityDensity(z, Emin=pop.pf['pop_Emin_xray'], \n                Emax=pop.pf['pop_Emax'])\n            \n            weight = self.rate_to_coefficient(z, species, **kw)\n            primary = weight * Lx \\\n                * (1. + z)**3 / pop.pf['pop_Ex'] / erg_per_ev\n            fion = self.esec.DepositionFraction(kw['igm_e'], channel='h_1')[0]\n\n            return primary * (1. + fion) * (pop.pf['pop_Ex'] - E_th[0]) \\\n                / E_th[0]\n\n        # Full calculation - much like computing integrated flux\n        norm = J21_num * self.sigma0\n        \n        # Integrate over function\n        if kw['fluxes'][popid] is None:\n            integrand = lambda E, zz: \\\n                self.rb.AngleAveragedFluxSlice(z, E, zz, xavg=kw['xavg'], \n                zxavg=kw['zxavg']) * self.sigma(E, species=species) \\\n                / norm / ev_per_hz\n                \n            ion, err = dblquad(integrand, z, kw['zf'], lambda a: self.E0, \n                lambda b: kw['Emax'], epsrel=self.rtol, epsabs=self.atol)    \n        \n        # Integrate over set of discrete points\n        else:  \n            integrand = self.sigma_E[species_str][popid][band] \\\n                * kw['fluxes'][popid][band] / norm / ev_per_hz\n        \n            if self.sampled_integrator == 'romb':\n                ion = romb(integrand * self.E[popid][band], \n                    dx=self.dlogE[popid][band])[0] * log10\n            else:\n                ion = simps(integrand * self.E[popid][band], \n                    x=self.logE[popid][band]) * log10\n                \n        # Re-normalize\n        ion *= 4. * np.pi * norm\n        \n        # Currently a rate coefficient, returned value depends on return_rc\n        if kw['return_rc']:\n            pass\n        else:\n            ion *= self.coefficient_to_rate(z, species, **kw) \n        \n        return ion\n                \n    def SecondaryIonizationRateIGM(self, z, species=0, donor=0, popid=0, \n        band=0, **kwargs):\n        \"\"\"\n        Compute volume averaged secondary ionization rate.\n\n        Parameters\n        ----------\n        z : float\n            redshift\n        species : int\n            Ionization rate of what atom?\n            Can be 0, 1, or 2 (HI, HeI, and HeII, respectively)\n        donor : int\n            Which atom gave the electron?\n            Can be 0, 1, or 2 (HI, HeI, and HeII, respectively)        \n\n        ===============\n        relevant kwargs\n        ===============\n        fluxes : np.ndarray\n            Array of fluxes corresponding to photon energies in self.igm.E.\n        return_rc : bool\n            Return actual heating rate, or rate coefficient for heating?\n            Former has units of erg s**-1 cm**-3, latter has units of \n            erg s**-1 cm**-3 atom**-1.    \n\n        Returns\n        -------\n        Volume averaged ionization rate due to secondary electrons, \n        in units of ionizations per second.\n\n        \"\"\"    \n        \n        pop = self.pops[popid]\n        \n        if self.pf['secondary_ionization'] == 0:\n            return 0.0\n\n        if not pop.pf['pop_ion_src_igm']:\n            return 0.0 \n\n        if band is not None:\n            solve_rte = self.background.solve_rte[popid][band]\n        else:\n            solve_rte = False\n\n        # Computed in IonizationRateIGM in this case\n        if not solve_rte:\n            return 0.0\n\n        if not np.any(self.background.bands_by_pop[popid] > pop.pf['pop_EminX']):\n            return 0.0\n        \n        if ((donor or species) in [1,2]) and (not self.pf['include_He']):\n            return 0.0\n\n        # Grab defaults, do some patches if need be\n        kw = self._fix_kwargs(**kwargs)\n\n        #if self.pf['gamma_igm'] is not None:\n        #    return self.pf['gamma_igm'](z)\n\n        species_str = species_i_to_str[species]\n        donor_str = species_i_to_str[donor]\n\n        if self.esec.method > 1 and solve_rte:\n\n            fion_const = 1.\n            if kw['igm_e'] == 0:\n                fion = self.fion[species_str][popid][band][:,0]\n            else:\n                i_x = np.argmin(np.abs(kw['igm_e'] - self.esec.x))\n                if self.esec.x[i_x] > kw['igm_e']:\n                    i_x -= 1\n\n                j = i_x + 1    \n\n                fion = self.fion[species_str][popid][band][:,i_x] \\\n                    + (self.fion[species_str][popid][band][:,j] - self.fion[species_str][popid][:,i_x]) \\\n                    * (kw['igm_e'] - self.esec.x[i_x]) \\\n                    / (self.esec.x[j] - self.esec.x[i_x])\n        elif self.esec.method > 1:\n            raise ValueError('Only know how to do advanced secondary ionization with solve_rte=True')\n        else:\n            fion = 1.0\n            fion_const = self.esec.DepositionFraction(kw['igm_e'], \n                channel=species_str)[0]\n\n        norm = J21_num * self.sigma0\n                                \n        if kw['fluxes'][popid] is None:        \n            if self.pf['approx_He']: # assumes lower integration limit > 4 Ryd\n                integrand = lambda E, zz: \\\n                    self.rb.AngleAveragedFluxSlice(z, E, zz, xavg=kw['xavg'], \n                    zxavg=kw['zxavg']) * (self.sigma(E) * (E - E_th[0]) \\\n                    + self.cosm.y * self.sigma(E, 1) * (E - E_th[1])) \\\n                    / E_th[0] / norm / ev_per_hz\n            else:\n                integrand = lambda E, zz: \\\n                    self.rb.AngleAveragedFluxSlice(z, E, zz, xavg=kw['xavg'], \n                    zxavg=kw['zxavg']) * self.sigma(E) * (E - E_th[0]) \\\n                    / E_th[0] / norm / ev_per_hz\n        else:\n            integrand = fion * self.sigma_E[donor_str][popid][band] \\\n                * (self.E[popid][band] - E_th[donor])\n            \n            if self.pf['approx_He']:\n                integrand += self.cosm.y * self.sigma_E['he_1'][popid][band] \\\n                    * (self.E[popid][band] - E_th[1])\n            \n            integrand = integrand\n            integrand *= kw['fluxes'][popid][band] / E_th[species] / norm \\\n                / ev_per_hz\n        \n        if type(integrand) == types.FunctionType:\n            ion, err = dblquad(integrand, z, kw['zf'], lambda a: self.E0, \n                lambda b: kw['Emax'], epsrel=self.rtol, epsabs=self.atol)\n        else:\n            if self.sampled_integrator == 'romb':\n                ion = romb(integrand * self.E[popid][band], \n                    dx=self.dlogE[popid][band])[0] * log10\n            else:\n                ion = simps(integrand * self.E[popid][band], \n                    x=self.logE[popid][band]) * log10    \n                \n        # Re-normalize\n        ion *= 4. * np.pi * norm * fion_const\n                \n        # Currently a rate coefficient, returned value depends on return_rc\n        if kw['return_rc']:\n            pass\n        else:\n            ion *= self.coefficient_to_rate(z, species, **kw) \n        \n        return ion\n        \n    def DiffuseLymanAlphaFlux(self, z, **kwargs):\n        \"\"\"\n        Flux of Lyman-alpha photons induced by photo-electron collisions.\n        \n        \"\"\"\n        \n        raise NotImplemented('hey fix me')\n            \n        if not self.pf['secondary_lya']:\n            return 0.0\n        \n        #return 1e-25\n        \n        # Grab defaults, do some patches if need be    \n        kw = self._fix_kwargs(**kwargs)\n                \n        # Compute fraction of photo-electron energy deposited as Lya excitation\n        if self.esec.method > 1 and (kw['fluxes'][popid] is not None):\n            if kw['igm_e'] == 0:\n                flya = self.flya[:,0]\n            else:\n                i_x = np.argmin(np.abs(kw['igm_e'] - self.esec.x))\n                if self.esec.x[i_x] > kw['igm_e']:\n                    i_x -= 1\n                    \n                j = i_x + 1    \n                \n                flya = self.flya[:,i_x] \\\n                    + (self.flya[:,j] - self.flya[:,i_x]) \\\n                    * (kw['igm_e'] - self.esec.x[i_x]) \\\n                    / (self.esec.x[j] - self.esec.x[i_x])                \n        else:\n            return 0.0\n                \n        # Re-normalize to help integrator\n        norm = J21_num * self.sigma0\n                \n        # Compute integrand\n        integrand = self.sigma_E[species_str] * (self.E - E_th[species])\n       \n        integrand *= kw['fluxes'] * flya / norm / ev_per_hz\n                         \n        if kw['Emax'] is not None:\n            imax = np.argmin(np.abs(self.E - kw['Emax']))\n            if imax == 0:\n                return 0.0\n                \n            if self.sampled_integrator == 'romb':\n                raise ValueError(\"Romberg's method cannot be used for integrating subintervals.\")\n                heat = romb(integrand[0:imax] * self.E[0:imax], dx=self.dlogE[0:imax])[0] * log10\n            else:\n                heat = simps(integrand[0:imax] * self.E[0:imax], x=self.logE[0:imax]) * log10\n        \n        else:\n            imin = np.argmin(np.abs(self.E - self.pop.pf['source_Emin']))\n            \n            if self.sampled_integrator == 'romb':\n                heat = romb(integrand[imin:] * self.E[imin:], \n                    dx=self.dlogE[imin:])[0] * log10\n            elif self.sampled_integrator == 'trapz':\n                heat = np.trapz(integrand[imin:] * self.E[imin:], \n                    x=self.logE[imin:]) * log10\n            else:\n                heat = simps(integrand[imin:] * self.E[imin:], \n                    x=self.logE[imin:]) * log10\n          \n        # Re-normalize, get rid of per steradian units\n        heat *= 4. * np.pi * norm * erg_per_ev\n\n        # Currently a rate coefficient, returned value depends on return_rc                                      \n        if kw['return_rc']:\n            pass\n        else:\n            heat *= self.coefficient_to_rate(z, species, **kw)\n\n        return heat\n        \n", "meta": {"hexsha": "f7ca129b88f15e3cdbdea7d854bd8a2f48ccd46c", "size": 44536, "ext": "py", "lang": "Python", "max_stars_repo_path": "ares/static/VolumeGlobal.py", "max_stars_repo_name": "astrojhgu/ares", "max_stars_repo_head_hexsha": "42008c8e4bf79f0b000cc833e02a86510bce7611", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-04T15:13:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-04T15:13:18.000Z", "max_issues_repo_path": "ares/static/VolumeGlobal.py", "max_issues_repo_name": "astrojhgu/ares", "max_issues_repo_head_hexsha": "42008c8e4bf79f0b000cc833e02a86510bce7611", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ares/static/VolumeGlobal.py", "max_forks_repo_name": "astrojhgu/ares", "max_forks_repo_head_hexsha": "42008c8e4bf79f0b000cc833e02a86510bce7611", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8871877518, "max_line_length": 113, "alphanum_fraction": 0.4684300341, "include": true, "reason": "import numpy,from scipy", "num_tokens": 11501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.17214552341735082}}
{"text": "# calculates performance of decision trees\n\nimport csv\n\nimport statsmodels.api as statsmodels\n\nfrom atcs import *\nfrom icd import *\n\nbo_true_positive = 0\nbo_true_negative = 0\nbo_false_positive = 0\nbo_false_negative = 0\n\nchf_true_positive = 0\nchf_true_negative = 0\nchf_false_positive = 0\nchf_false_negative = 0\n\ncad_true_positive = 0\ncad_true_negative = 0\ncad_false_positive = 0\ncad_false_negative = 0\n\nepilepsy_true_positive = 0\nepilepsy_true_negative = 0\nepilepsy_false_positive = 0\nepilepsy_false_negative = 0\n\ngout_true_positive = 0\ngout_true_negative = 0\ngout_false_positive = 0\ngout_false_negative = 0\n\ngout_contraindications = 0\nepilepsy_contraindications = 0\ncad_contraindications = 0\nchf_contraindications = 0\nbo_contraindications = 0\n\nhighrisk_prescription_identified = 0\n\ncad_contraindicated = celecoxib | etoricoxib | parecoxib | diclofenac | triptan | fludrocortison\nbo_contraindicated = sotalol | dextrometorphan | carvedilol | metoprolol | propranolol | atenolol\ngout_contraindicated = xipamid | hydrochlorothiazid | torasemid\nchf_contraindicated = celecoxib | diclofenac | domperidon | dronedaron | eletriptan | etoricoxib \\\n                             | flecainid | methylphenidat | moxonidin | parecoxib | pioglitazon | tadalafil \\\n                             | cilostazol | desmopressin | fludrocortison\nepilepsy_contraindicated = baclofen | bethanechol | buspiron | dimenhydrinat | diphenhydramin | doxylamin | \\\n                           levofloxacin | methocarbamol | metoclopramid | ofloxacin_oral | sulpirid | terizidon\n\nfile = open('test_1847_geputzt.csv')\nreader = csv.reader(file, delimiter=';')\nheaders = next(reader)\n\ndata = []\nfor row in reader:\n    data.append(dict(zip(headers, row)))\n\nfor row in data:\n\n    atc_codes = set()\n    for pos in range(1, 25 + 1):\n        row_name = 'atc_%02d' % pos\n        if row[row_name]:\n            atc_codes.add(row[row_name])\n\n    icd_codes = set()\n    for pos in range(1, 20 + 1):\n        row_name = 'icd10_%02d' % pos\n        if row[row_name]:\n            icd_codes.add(row[row_name])\n\n# bronchial obstruction\n    if any([is_r03al(atc) for atc in atc_codes]):\n        if any([is_bronchial_obstruction(icd) for icd in icd_codes]):\n            bo_true_positive += 1\n            if bo_contraindicated & atc_codes:\n                bo_contraindications += 1\n        if not any([is_bronchial_obstruction(icd) for icd in icd_codes]):\n            bo_false_positive += 1\n\n    elif not any([is_r03al(atc) for atc in atc_codes]) and any([is_r03ak(atc) for atc in atc_codes]):\n        if any([is_bronchial_obstruction(icd) for icd in icd_codes]):\n            bo_true_positive += 1\n            if bo_contraindicated & atc_codes:\n                bo_contraindications += 1\n        if not any([is_bronchial_obstruction(icd) for icd in icd_codes]):\n            bo_false_positive += 1\n\n    elif not any([is_r03al(atc) for atc in atc_codes]) and not any([is_r03ak(atc) for atc in atc_codes]) and any([is_r03bb(atc) for atc in atc_codes]):\n        if any([is_bronchial_obstruction(icd) for icd in icd_codes]):\n            bo_true_positive += 1\n            if bo_contraindicated & atc_codes:\n                bo_contraindications += 1\n        if not any([is_bronchial_obstruction(icd) for icd in icd_codes]):\n            bo_false_positive += 1\n\n    else:\n        if any([is_bronchial_obstruction(icd) for icd in icd_codes]):\n            bo_false_negative += 1\n        if not any([is_bronchial_obstruction(icd) for icd in icd_codes]):\n            bo_true_negative += 1\n\n# CHF\n    if any([is_c03ca(atc) for atc in atc_codes]) and any([is_c03ba(atc) for atc in atc_codes]) and not any([is_b05bb(atc) for atc in atc_codes]):\n        if any([is_chf(icd) for icd in icd_codes]):\n            chf_true_positive += 1\n            if chf_contraindicated & atc_codes:\n                chf_contraindications += 1\n        if not any([is_chf(icd) for icd in icd_codes]):\n            chf_false_positive += 1\n\n    elif any([is_c03ca(atc) for atc in atc_codes]) and not any([is_c03ba(atc) for atc in atc_codes]) and any([is_s01xa(atc) for atc in atc_codes]):\n        if any([is_chf(icd) for icd in icd_codes]):\n            chf_true_positive += 1\n            if chf_contraindicated & atc_codes:\n                chf_contraindications += 1\n        if not any([is_chf(icd) for icd in icd_codes]):\n            chf_false_positive += 1\n\n    elif not any([is_c03ca(atc) for atc in atc_codes]) and any([is_a10bj(atc) for atc in atc_codes]):\n        if any([is_chf(icd) for icd in icd_codes]):\n            chf_true_positive += 1\n            if chf_contraindicated & atc_codes:\n                chf_contraindications += 1\n        if not any([is_chf(icd) for icd in icd_codes]):\n            chf_false_positive += 1\n\n    elif not any([is_c03ca(atc) for atc in atc_codes]) and not any([is_a10bj(atc) for atc in atc_codes]) and any([is_m05bb(atc) for atc in atc_codes]):\n        if any([is_chf(icd) for icd in icd_codes]):\n            chf_true_positive += 1\n            if chf_contraindicated & atc_codes:\n                chf_contraindications += 1\n        if not any([is_chf(icd) for icd in icd_codes]):\n            chf_false_positive += 1\n\n    else:\n        if any([is_chf(icd) for icd in icd_codes]):\n            chf_false_negative += 1\n        if not any([is_chf(icd) for icd in icd_codes]):\n            chf_true_negative += 1\n\n# CAD\n    if any([is_c10aa(atc) for atc in atc_codes]) and any([is_b01ac(atc) for atc in atc_codes]):\n        if any([is_cad(icd) for icd in icd_codes]):\n            cad_true_positive += 1\n            if cad_contraindicated & atc_codes:\n                cad_contraindications += 1\n        if not any([is_cad(icd) for icd in icd_codes]):\n            cad_false_positive += 1\n\n    elif any([is_c10aa(atc) for atc in atc_codes]) and not any([is_b01ac(atc) for atc in atc_codes]) and any([is_n02ba(atc) for atc in atc_codes]):\n        if any([is_cad(icd) for icd in icd_codes]):\n            cad_true_positive += 1\n            if cad_contraindicated & atc_codes:\n                cad_contraindications += 1\n        if not any([is_cad(icd) for icd in icd_codes]):\n            cad_false_positive += 1\n\n    elif not any([is_c10aa(atc) for atc in atc_codes]) and any([is_b01ac(atc) for atc in atc_codes]) and any([is_a10bh(atc) for atc in atc_codes]):\n        if any([is_cad(icd) for icd in icd_codes]):\n            cad_true_positive += 1\n            if cad_contraindicated & atc_codes:\n                cad_contraindications += 1\n        if not any([is_cad(icd) for icd in icd_codes]):\n            cad_false_positive += 1\n\n    elif not any([is_c10aa(atc) for atc in atc_codes]) and not any([is_b01ac(atc) for atc in atc_codes]) and any([is_c01da(atc) for atc in atc_codes]):\n        if any([is_cad(icd) for icd in icd_codes]):\n            cad_true_positive += 1\n            if cad_contraindicated & atc_codes:\n                cad_contraindications += 1\n        if not any([is_cad(icd) for icd in icd_codes]):\n            cad_false_positive += 1\n\n    else:\n        if any([is_cad(icd) for icd in icd_codes]):\n            cad_false_negative += 1\n        if not any([is_cad(icd) for icd in icd_codes]):\n            cad_true_negative += 1\n\n# epilepsy\n    if any([is_n03ax(atc) for atc in atc_codes]) and any([is_b01af(atc) for atc in atc_codes]) and any([is_m03bx(atc) for atc in atc_codes]):\n        if any([is_epilepsy(icd) for icd in icd_codes]):\n            epilepsy_true_positive += 1\n            if epilepsy_contraindicated & atc_codes:\n                epilepsy_contraindications += 1\n        if not any([is_epilepsy(icd) for icd in icd_codes]):\n            epilepsy_false_positive += 1\n\n    elif any([is_n03ax(atc) for atc in atc_codes]) and not any([is_b01af(atc) for atc in atc_codes]) and any([is_n03ag(atc) for atc in atc_codes]):\n        if any([is_epilepsy(icd) for icd in icd_codes]):\n            epilepsy_true_positive += 1\n            if epilepsy_contraindicated & atc_codes:\n                epilepsy_contraindications += 1\n        if not any([is_epilepsy(icd) for icd in icd_codes]):\n            epilepsy_false_positive += 1\n\n    elif not any([is_n03ax(atc) for atc in atc_codes]) and any([is_n03aa(atc) for atc in atc_codes]):\n        if any([is_epilepsy(icd) for icd in icd_codes]):\n            epilepsy_true_positive += 1\n            if epilepsy_contraindicated & atc_codes:\n                epilepsy_contraindications += 1\n        if not any([is_epilepsy(icd) for icd in icd_codes]):\n            epilepsy_false_positive += 1\n\n    else:\n        if any([is_epilepsy(icd) for icd in icd_codes]):\n            epilepsy_false_negative += 1\n        if not any([is_epilepsy(icd) for icd in icd_codes]):\n            epilepsy_true_negative += 1\n\n# gout\n    if any([is_m04aa(atc) for atc in atc_codes]):\n        if any([is_gout(icd) for icd in icd_codes]):\n            gout_true_positive += 1\n            if gout_contraindicated & atc_codes:\n                gout_contraindications += 1\n        if not any([is_gout(icd) for icd in icd_codes]):\n            gout_false_positive += 1\n\n    elif not any([is_m04aa(atc) for atc in atc_codes]) and any([is_m04ac(atc) for atc in atc_codes]):\n        if any([is_gout(icd) for icd in icd_codes]):\n            gout_true_positive += 1\n            if gout_contraindicated & atc_codes:\n                gout_contraindications += 1\n        if not any([is_gout(icd) for icd in icd_codes]):\n            gout_false_positive += 1\n\n    elif not any([is_m04aa(atc) for atc in atc_codes]) and not any([is_m04ac(atc) for atc in atc_codes]) and any([is_r06ax(atc) for atc in atc_codes]):\n        if any([is_gout(icd) for icd in icd_codes]):\n            gout_true_positive += 1\n            if gout_contraindicated & atc_codes:\n                gout_contraindications += 1\n        if not any([is_gout(icd) for icd in icd_codes]):\n            gout_false_positive += 1\n\n    else:\n        if any([is_gout(icd) for icd in icd_codes]):\n            gout_false_negative += 1\n        if not any([is_gout(icd) for icd in icd_codes]):\n            gout_true_negative += 1\n\n\nprint('High risk prescriptions', highrisk_prescription_identified)\nprint('gout contraindications:', gout_contraindications)\nprint('epilepsy contraindications:', epilepsy_contraindications)\nprint('CAD contraindications:', cad_contraindications)\nprint('CHF contraindications:', chf_contraindications)\nprint('BO contraindications', bo_contraindications)\n\n# BO\ntry:\n    bo_specificity = bo_true_negative / (bo_true_negative + bo_false_positive)\nexcept:\n    bo_specificity = 1\n\ntry:\n    bo_sensitivity = bo_true_positive / (bo_true_positive + bo_false_negative)\nexcept:\n    bo_sensitivity = 1\n\nbo_ppv = bo_true_positive / (bo_true_positive + bo_false_positive)\nbo_npv = bo_true_negative / (bo_true_negative + bo_false_negative)\nprint('BO_Specificity:', bo_specificity,\n      statsmodels.stats.proportion_confint(bo_true_negative, bo_true_negative + bo_false_positive, alpha=0.05, method='wilson'))\nprint('BO_Sensitivity:', bo_sensitivity,\n      statsmodels.stats.proportion_confint(bo_true_positive, bo_true_positive + bo_false_negative, alpha=0.05, method='wilson'))\nprint('BO_PPV:', bo_ppv,\n      statsmodels.stats.proportion_confint(bo_true_positive, bo_true_positive + bo_false_positive, alpha=0.05, method='wilson'))\nprint('BO_NPV:', bo_npv,\n      statsmodels.stats.proportion_confint(bo_true_negative, bo_true_negative + bo_false_negative, alpha=0.05, method='wilson'))\n\nprint('BO_True Positives:', bo_true_positive, 'BO_True Negatives:', bo_true_negative, 'BO_False Positives:', bo_false_positive,\n      'BO_False Negatives:', bo_false_negative)  # validation: bronchial_obstruction(true) - true_positive = false_negative\n\nbo_precision = bo_ppv\nbo_recall = bo_sensitivity\nprint('BO_Precision:', bo_precision, 'BO_Recall:', bo_recall, 'BO_F1:', 2 * bo_precision * bo_recall / (bo_precision + bo_recall),\n      'BO_Accuracy:', (bo_true_positive + bo_true_negative) / (bo_true_positive + bo_true_negative + bo_false_positive + bo_false_negative))\n\n# CHF\ntry:\n    chf_specificity = chf_true_negative / (chf_true_negative + chf_false_positive)\nexcept:\n    chf_specificity = 1\n\ntry:\n    chf_sensitivity = chf_true_positive / (chf_true_positive + chf_false_negative)\nexcept:\n    chf_sensitivity = 1\n\nchf_ppv = chf_true_positive / (chf_true_positive + chf_false_positive)\nchf_npv = chf_true_negative / (chf_true_negative + chf_false_negative)\n\nprint('CHF_Specificity:', chf_specificity,\n      statsmodels.stats.proportion_confint(chf_true_negative, chf_true_negative + chf_false_positive, alpha=0.05, method='wilson'))\nprint('CHF_Sensitivity:', chf_sensitivity,\n      statsmodels.stats.proportion_confint(chf_true_positive, chf_true_positive + chf_false_negative, alpha=0.05, method='wilson'))\nprint('CHF_PPV:', chf_ppv,\n      statsmodels.stats.proportion_confint(chf_true_positive, chf_true_positive + chf_false_positive, alpha=0.05, method='wilson'))\nprint('CHF_NPV:', chf_npv,\n      statsmodels.stats.proportion_confint(chf_true_negative, chf_true_negative + chf_false_negative, alpha=0.05, method='wilson'))\n\nprint('CHF_True Positives:', chf_true_positive, 'CHF_True Negatives:', chf_true_negative, 'CHF_False Positives:', chf_false_positive,\n      'CHF_False Negatives:', chf_false_negative)  # validation: CHF(true) - true_positive = false_negative\n\nchf_precision = chf_ppv\nchf_recall = chf_sensitivity\nprint('CHF_Precision:', chf_precision, 'CHF_Recall:', chf_recall, 'CHF_F1:', 2 * chf_precision * chf_recall / (chf_precision + chf_recall),\n      'CHF_Accuracy:', (chf_true_positive + chf_true_negative) / (chf_true_positive + chf_true_negative + chf_false_positive + chf_false_negative))\n\n# CAD\ntry:\n    cad_specificity = cad_true_negative / (cad_true_negative + cad_false_positive)\nexcept:\n    cad_specificity = 1\n\ntry:\n    cad_sensitivity = cad_true_positive / (cad_true_positive + cad_false_negative)\nexcept:\n    cad_sensitivity = 1\n\ncad_ppv = cad_true_positive / (cad_true_positive + cad_false_positive)\ncad_npv = cad_true_negative / (cad_true_negative + cad_false_negative)\n\nprint('CAD_Specificity:', cad_specificity,\n      statsmodels.stats.proportion_confint(cad_true_negative, cad_true_negative + cad_false_positive, alpha=0.05, method='wilson'))\nprint('CAD_Sensitivity:', cad_sensitivity,\n      statsmodels.stats.proportion_confint(cad_true_positive, cad_true_positive + cad_false_negative, alpha=0.05, method='wilson'))\nprint('CAD_PPV:', cad_ppv,\n      statsmodels.stats.proportion_confint(cad_true_positive, cad_true_positive + cad_false_positive, alpha=0.05, method='wilson'))\nprint('CAD_NPV:', cad_npv,\n      statsmodels.stats.proportion_confint(cad_true_negative, cad_true_negative + cad_false_negative, alpha=0.05, method='wilson'))\n\nprint('CAD_True Positives:', cad_true_positive, 'CAD_True Negatives:', cad_true_negative, 'CAD_False Positives:', cad_false_positive,\n      'CAD_False Negatives:', cad_false_negative)  # validation: CAD(true) - true_positive = false_negative\n\ncad_precision = cad_ppv\ncad_recall = cad_sensitivity\nprint('CAD_Precision:', cad_precision, 'CAD_Recall:', cad_recall, 'CAD_F1:', 2 * cad_precision * cad_recall / (cad_precision + cad_recall),\n      'CAD_Accuracy:', (cad_true_positive + cad_true_negative) / (cad_true_positive + cad_true_negative + cad_false_positive + cad_false_negative))\n\n# Epilepsy\ntry:\n    epilepsy_specificity = epilepsy_true_negative / (epilepsy_true_negative + epilepsy_false_positive)\nexcept:\n    epilepsy_specificity = 1\n\ntry:\n    epilepsy_sensitivity = epilepsy_true_positive / (epilepsy_true_positive + epilepsy_false_negative)\nexcept:\n    epilepsy_sensitivity = 1\n\nepilepsy_ppv = epilepsy_true_positive / (epilepsy_true_positive + epilepsy_false_positive)\nepilepsy_npv = epilepsy_true_negative / (epilepsy_true_negative + epilepsy_false_negative)\n\nprint('Epilepsy_Specificity:', epilepsy_specificity,\n      statsmodels.stats.proportion_confint(epilepsy_true_negative, epilepsy_true_negative + epilepsy_false_positive, alpha=0.05, method='wilson'))\nprint('Epilepsy_Sensitivity:', epilepsy_sensitivity,\n      statsmodels.stats.proportion_confint(epilepsy_true_positive, epilepsy_true_positive + epilepsy_false_negative, alpha=0.05, method='wilson'))\nprint('Epilepsy_PPV:', epilepsy_ppv,\n      statsmodels.stats.proportion_confint(epilepsy_true_positive, epilepsy_true_positive + epilepsy_false_positive, alpha=0.05, method='wilson'))\nprint('Epilepsy_NPV:', epilepsy_npv,\n      statsmodels.stats.proportion_confint(epilepsy_true_negative, epilepsy_true_negative + epilepsy_false_negative, alpha=0.05, method='wilson'))\n\nprint('Epilepsy_True Positives:', epilepsy_true_positive, 'Epilepsy_True Negatives:', epilepsy_true_negative, 'Epilepsy_False Positives:', epilepsy_false_positive,\n      'Epilepsy_False Negatives:', epilepsy_false_negative)  # validation: Epilepsy(true) - true_positive = false_negative\n\nepilepsy_precision = epilepsy_ppv\nepilepsy_recall = epilepsy_sensitivity\nprint('Epilepsy_Precision:', epilepsy_precision, 'Epilepsy_Recall:', epilepsy_recall, 'Epilepsy_F1:', 2 * epilepsy_precision * epilepsy_recall / (epilepsy_precision + epilepsy_recall),\n      'Epilepsy_Accuracy:', (epilepsy_true_positive + epilepsy_true_negative) / (epilepsy_true_positive + epilepsy_true_negative + epilepsy_false_positive + epilepsy_false_negative))\n\n# Gout\ntry:\n    gout_specificity = gout_true_negative / (gout_true_negative + gout_false_positive)\nexcept:\n    gout_specificity = 1\n\ntry:\n    gout_sensitivity = gout_true_positive / (gout_true_positive + gout_false_negative)\nexcept:\n    gout_sensitivity = 1\n\ngout_ppv = gout_true_positive / (gout_true_positive + gout_false_positive)\ngout_npv = gout_true_negative / (gout_true_negative + gout_false_negative)\n\nprint('Gout_Specificity:', gout_specificity,\n      statsmodels.stats.proportion_confint(gout_true_negative, gout_true_negative + gout_false_positive, alpha=0.05, method='wilson'))\nprint('Gout_Sensitivity:', gout_sensitivity,\n      statsmodels.stats.proportion_confint(gout_true_positive, gout_true_positive + gout_false_negative, alpha=0.05, method='wilson'))\nprint('Gout_PPV:', gout_ppv,\n      statsmodels.stats.proportion_confint(gout_true_positive, gout_true_positive + gout_false_positive, alpha=0.05, method='wilson'))\nprint('Gout_NPV:', gout_npv,\n      statsmodels.stats.proportion_confint(gout_true_negative, gout_true_negative + gout_false_negative, alpha=0.05, method='wilson'))\n\nprint('Gout_True Positives:', gout_true_positive, 'Gout_True Negatives:', gout_true_negative, 'Gout_False Positives:', gout_false_positive,\n      'Gout_False Negatives:', gout_false_negative)  # validation: Gout(true) - true_positive = false_negative\n\ngout_precision = gout_ppv\ngout_recall = gout_sensitivity\nprint('Gout_Precision:', gout_precision, 'Gout_Recall:', gout_recall, 'Gout_F1:', 2 * gout_precision * gout_recall / (gout_precision + gout_recall),\n      'Gout_Accuracy:', (gout_true_positive + gout_true_negative) / (gout_true_positive + gout_true_negative + gout_false_positive + gout_false_negative))\n", "meta": {"hexsha": "858e1329c9ce52d470e1c40593e652b73f53cea9", "size": 18958, "ext": "py", "lang": "Python", "max_stars_repo_path": "decision_trees_applied.py", "max_stars_repo_name": "wahram/atc_icd", "max_stars_repo_head_hexsha": "e7b9a095bfd2186e85e7d1a276669b7ccab9d5f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "decision_trees_applied.py", "max_issues_repo_name": "wahram/atc_icd", "max_issues_repo_head_hexsha": "e7b9a095bfd2186e85e7d1a276669b7ccab9d5f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "decision_trees_applied.py", "max_forks_repo_name": "wahram/atc_icd", "max_forks_repo_head_hexsha": "e7b9a095bfd2186e85e7d1a276669b7ccab9d5f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.6945812808, "max_line_length": 184, "alphanum_fraction": 0.7136301298, "include": true, "reason": "import statsmodels", "num_tokens": 5412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.17212553258922503}}
{"text": "\"\"\"\nPython implementation for parallel imaging and compressed sensing MRI image reconstruction with temporal finite difference constraint\n\nUse example\npython demo_recon_python.py --path_to_data data/ --filename sub001/2drt/raw/sub001_2drt_vcv1_r1_raw.h5 --n_arms 2 --n_recon_frames 0 --reg_lambda 0.08 --max_iter 100 --cuda --gpu_id 0\n\nImplemented by Yongwan Lim (yongwanl@usc.edu) Feb. 2020\n\"\"\"\n\nimport os\nimport argparse\n\nimport ismrmrd.xsd\n# import numpy as np\n# import cupy as cp\nimport sigpy as sp\nfrom cs_recon.plot_mri import img_play\nfrom cs_recon.recon import TotalVariationRecon, TotalVariationReconNLCG\nfrom cs_recon.util import estimate_coilmap_walsh\nimport h5py\n\nparser = argparse.ArgumentParser(description='Python PICS with temporal FD constrained reconstruction')\n\nparser.add_argument('--path_to_data', type=str, default='dataset/', help='path to data')\nparser.add_argument('--filename', type=str, default='sub001/2drt/raw/sub001_2drt_vcv1_r1_raw.h5', help='filename')\n\nparser.add_argument('--n_arms', type=int, default=2, help='Number of spiral arms to use to reconstruct per frame')\nparser.add_argument('--n_recon_frames', type=int, default=50,\n                    help='Number of frames you want to reconstruct. If 0, reconstruct maximum number of frames')\n\nparser.add_argument('--n_full_arms', type=int, default=13, help='Number of fully sampled spirals')\n\nparser.add_argument('--reg_lambda', type=float, default=0.08, help='temporal FD regularization parameter')\nparser.add_argument('--max_iter', type=int, default=100, help='maximum iteration for recon')\n\nparser.add_argument('--cuda', action='store_true', help='use cuda?')\nparser.add_argument('--gpu_id', type=int, default=0, help='gpu id, only being seen if --cuda')\nparser.add_argument('--tr', type=float, default=6.004e-3, help='Repetition time (TR), will be used to generate video')\n\nparser.add_argument('--methods', type=str, default='nlcg', help='recon methos: nlcg or pdhg')\nopt = parser.parse_args()\n\nimport time\n\nstart = time.time()\n\n# path_to_data = 'ismrmrd_data/Spiral/'\n# filename = 'spiral'\n\nif opt.cuda:\n    device_id = opt.gpu_id\nelse:\n    device_id = -1\n\ndevice = sp.Device(device_id)\nxp = device.xp\n\nwith device:\n# Load parameters from opt\n    n_full_arms = opt.n_full_arms                       # number of fully sampled spirals\n    n_arms = opt.n_arms                                 # number of spiral arms to use per frame\n    reg_lambda = opt.reg_lambda\n    max_iter = opt.max_iter\n    filename = opt.filename\n    path_to_data = opt.path_to_data\n\n\n################################################################################\n# Load Data\n#\n\n    print('Loading data...', end='', flush=True)\n\n    filename = filename.strip('.h5')\n\n    # Load file\n    filename = os.path.join(path_to_data, '%s.h5' % filename)\n    if not os.path.isfile(filename):\n        print(\"%s is not a valid file\" % filename)\n        raise SystemExit\n\n\n    dset = ismrmrd.Dataset(filename, 'dataset', create_if_needed=False)\n\n    header = ismrmrd.xsd.CreateFromDocument(dset.read_xml_header())\n    enc = header.encoding[0]\n    \n    acq_header = dset.read_acquisition(0).getHead()\n    nk = acq_header.number_of_samples                               # number of samples per spiral\n    nc = header.acquisitionSystemInformation.receiverChannels       # number of coils\n    ns = dset.number_of_acquisitions()                              # number of spirals\n\n    # Matrix size\n    eNx = enc.encodedSpace.matrixSize.x\n    eNy = enc.encodedSpace.matrixSize.y\n    eNz = enc.encodedSpace.matrixSize.z\n    rNx = enc.reconSpace.matrixSize.x\n    rNy = enc.reconSpace.matrixSize.y\n    rNz = enc.reconSpace.matrixSize.z\n\n    # Field of View\n    eFOVx = enc.encodedSpace.fieldOfView_mm.x\n    eFOVy = enc.encodedSpace.fieldOfView_mm.y\n    eFOVz = enc.encodedSpace.fieldOfView_mm.z\n    rFOVx = enc.reconSpace.fieldOfView_mm.x\n    rFOVy = enc.reconSpace.fieldOfView_mm.y\n    rFOVz = enc.reconSpace.fieldOfView_mm.z\n\n    # Initialize a storage array\n    kdata = xp.zeros((ns, nc, nk), dtype=xp.complex64)\n    kloc = xp.zeros((ns, nk, 2), dtype=xp.float32)\n    kweight = xp.zeros((nk, 1), dtype=xp.float32)\n    spokeindex = xp.zeros((ns,), dtype=xp.uint32)\n\n    # Loop through the rest of the acquisitions and stuff\n    for acqnum in range(dset.number_of_acquisitions()):\n        acq = dset.read_acquisition(acqnum)\n\n        # Stuff into the buffer\n        kdata[acqnum, :, :] = xp.array(acq.data)\n        kloc[acqnum, :, :] = xp.array(acq.traj[:, :2])\n        spokeindex[acqnum] = acq.idx.kspace_encode_step_1\n\n        if acqnum == 0:\n            kweight = xp.array(acq.traj[:, 2])\n\n    # TODO:\n    # this number 1.4790e3 may be just an arbitrary number\n    # and the scaling/normalization may need to be determined.\n    kdata = 1.4790e3*kdata/xp.max(kdata)\n\n    # the range of kloc should be between -N/2 and N/2\n    # Note: xp.max(xp.sum(kloc**2, axis=2) ** 0.5) is 0.5 but xp.max(kloc) is < 0.5\n    #       We may need to scale the kloc based on xp.max(kloc)\n\n    kloc = kloc / xp.max(kloc) * 0.5 * xp.ushort(rNy)\n    # kloc = kloc*rNy\n    # print(xp.max(kloc))\n\n    # number of time frames possible to recon\n    n_total_frames = int(xp.floor(ns/n_arms))\n\n    assert opt.n_recon_frames <= n_total_frames, \\\n        'n_recon_frames exceeds the total number of frames possible to recon. Please set -n_recon_frames smaller'\n\n    # if this is set to 0, then reconstruct the entire data\n    if opt.n_recon_frames == 0:\n        n_recon_frames = n_total_frames\n    # this option is for fast debugging, but make sure recon quality can be depending on the number of frames\n    else:\n        n_recon_frames = opt.n_recon_frames\n\n    print('Done!')\n\n\n################################################################################\n# Estimate coil maps using Walsh's method from temporal averaged data\n#\nwith device:\n\n    # assume spiral sampling patterns repeat every n_full_arms\n    n_avr = int(xp.floor(ns/n_full_arms))\n\n    kdata_avr = kdata[:n_avr*n_full_arms, :, :].reshape(n_avr, n_full_arms, nc, nk)\n    kdata_avr = xp.mean(kdata_avr, axis=0)\n    kdata_avr = xp.transpose(kdata_avr, (1, 0, 2))\n\n    kloc_avr = kloc[:n_full_arms, :, :]\n\n    avr_img = sp.nufft_adjoint(kdata_avr*kweight[xp.newaxis, xp.newaxis, :], kloc_avr)\n\n    # needs to process on CPUs\n    sens_map = estimate_coilmap_walsh(sp.to_device(avr_img, -1), smoothing=20, thresh=0.0)\n\n    # copy it to GPU\n    sens_map = sp.to_device(sens_map, device_id)\n    # pl.ImagePlot(xp.squeeze(avr_img), z=0, title='Multi-channel Time Averaged Image')\n    # pl.ImagePlot(xp.squeeze(xp.abs(sens_map)), z=0, title='Walsh (Python)')\n\n    # TODO Espirit coil map estimation needs to be improved\n\n\n################################################################################\n# Reshape Data\n#\nwith device:\n\n    # crop kdata to keep only the first (n_frames*n_arms) data\n    kdata = kdata[:n_recon_frames*n_arms, :, :]\n    kdata = kdata.reshape(n_recon_frames, n_arms, nc, nk)            # [n_recon_frames, n_arms, n_ch, n_samples]\n    kdata = xp.transpose(kdata, (0, 2, 1, 3))                           # [n_recon_frames, n_ch, n_arms, n_samples]\n\n    kweight = xp.expand_dims(kweight, axis=0)                             # [1, n_samples]\n\n    kloc = kloc[:n_recon_frames*n_arms, :, :]\n    kloc = kloc.reshape(n_recon_frames, n_arms, nk, -1)                # [n_recon_frames, n_arms, n_samples, 2]\n\n    print('kdata array shape: {}'.format(kdata.shape))\n    print('kweight array shape: {}'.format(kweight.shape))\n    print('kloc array shape: {}'.format(kloc.shape))\n\n\n################################################################################\n# Gridding Example for one frame\n#\nwith device:\n\n    zero_filed_img = sp.nufft_adjoint(kdata[0, :, :, :] * kweight, kloc[0, :, :, :], (nc, rNy, rNx))\n    # pl.ImagePlot(xp.squeeze(zero_filed_img), z=0, title='Multi-channel Gridding')\n\n\n################################################################################\n# CS Reconstruction\n#\n    \n    reg_lambda_scaled = reg_lambda * xp.max(xp.abs(zero_filed_img))\n    if opt.methods == \"nlcg\": # non-linear conjugate gradient\n        img, fnorm, tnorm, cost = TotalVariationReconNLCG(kdata, kweight, kloc, sens_map, reg_lambda_scaled, max_iter).run()\n    elif opt.methods == \"pdhg\": # primal dual hybrid gradient\n        img = TotalVariationRecon(kdata, kweight, kloc, sens_map, reg_lambda=reg_lambda_scaled, dim_fd=(0,), max_iter=max_iter, device=device).run()\n\n################################################################################\n# Save video\n#\n\nimg_cpu = sp.to_device(img,-1)\n\n(f_dir, f_basename) = os.path.split(filename)\nf_basename = 'recon_' + f_basename.strip(\".h5\") + '_'\nf_param = 'narms{}_nt{}_l1{}_niter{}_{}_gpuid{}'.format(n_arms, n_recon_frames, reg_lambda, max_iter, opt.methods, device_id)\nf_name = os.path.join(f_dir, f_basename+f_param)\n\n# TODO Save reconstruction in some accessable file format\n\nend = time.time()\ncomp_time = end -start\nprint(end - start)\n\nh5 = h5py.File(f_name + '.h5', 'w')\nh5.create_dataset('image', data=img_cpu)\n#h5.create_dataset('cost', data=cost)\n#h5.create_dataset('tnorm', data=tnorm)\n#h5.create_dataset('fnorm', data=fnorm)\n#h5.create_dataset('lambda_t', data=reg_lambda_scaled)\nh5.create_dataset('comp_time', data=comp_time)\nh5.close()\n\nani2 = img_play(img_cpu, opt.tr*1000*n_arms, name=f_name)\n\n", "meta": {"hexsha": "c7ca47e49b894682b3a3e3d8d1710410bee7e7a4", "size": 9354, "ext": "py", "lang": "Python", "max_stars_repo_path": "demo_recon_python.py", "max_stars_repo_name": "usc-mrel/usc_speech_mri", "max_stars_repo_head_hexsha": "e873b9b2bffea95e6b4804e3058857b3796858f7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2021-02-18T02:42:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T18:06:58.000Z", "max_issues_repo_path": "demo_recon_python.py", "max_issues_repo_name": "usc-mrel/usc_speech_mri", "max_issues_repo_head_hexsha": "e873b9b2bffea95e6b4804e3058857b3796858f7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demo_recon_python.py", "max_forks_repo_name": "usc-mrel/usc_speech_mri", "max_forks_repo_head_hexsha": "e873b9b2bffea95e6b4804e3058857b3796858f7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-03-02T14:30:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T11:42:28.000Z", "avg_line_length": 37.416, "max_line_length": 183, "alphanum_fraction": 0.6525550567, "include": true, "reason": "import numpy,import cupy", "num_tokens": 2553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061556288288, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.1721255308770706}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nLocal functions for all orientation codes\nA. Doran and G. Laske\n\"\"\"\n\n#############################\n# Import all packages for entire program\n#############################\n\nfrom numpy import *\nfrom geographiclib.geodesic import *\nimport subprocess\nimport numpy as np\nimport scipy.signal as sig\nimport obspy \nimport matplotlib.pyplot as plt\nfrom obspy.clients.fdsn import Client\nfrom obspy.core import UTCDateTime\nfrom scipy.stats import circmean as cmean\nfrom scipy.stats import circstd as cstd\nfrom scipy.stats import hmean as hm\nimport os\n\n#############################\n# Functions for driver program\n#############################\n\n\n# First pass at detrending\ndef detr(T):\n    T.detrend()\n    T.detrend('linear')\n    return T\n    \n# Organize channels by coordinate system\ndef org(T,nameconv):\n    # Need to add to this in case other type (eg LHZ) is used\n    if nameconv==1:\n        bhz=T.select(channel=\"??Z\")\n        bh1=T.select(channel=\"??N\")\n        bh2=T.select(channel=\"??E\")    \n    if nameconv==2:\n        bhz=T.select(channel=\"??Z\")\n        bh1=T.select(channel=\"??1\")\n        bh2=T.select(channel=\"??2\")\n    if nameconv==3:\n        bhz=T.select(channel=\"??Z\")\n        bh1=T.select(channel=\"??2\")\n        bh2=T.select(channel=\"??1\")\n    \n    s=bh1+bh2+bhz\n\n    # decimate just to make things easier\n    # for now assume all channels are same sampling rate\n    while s[0].stats.sampling_rate >= 10.0 and s[0].stats.sampling_rate / 10.0 == int(s[0].stats.sampling_rate / 10.0):\n        s.decimate(10)\n\n    while s[0].stats.sampling_rate / 5.0 == int(s[0].stats.sampling_rate / 5.0):\n        s.decimate(5)\n\n    return s\n  \n# used by catclean\ndef close(x1,x2):\n    if abs(x1-x2)<0.8:\n        return True\n    else:\n        return False\n\n# look for repeat events\ndef catclean(stime,lat,lon,mag):\n    rep=array([],dtype=int)\n    for k in arange((len(stime))):\n        for kk in arange((len(stime))):\n            if stime[kk]-stime[k]<60*15 and close(lat[kk],lat[k]) and close(lon[kk],lon[k]) and mag[kk]<mag[k]-0.3:\n                rep=append(rep,kk)\n    return rep\n    \n\n#############################\n# PHASE VELOCITY CALCULATIONS\n#############################\n\ndef getf(freq,A):\n    for i in arange((len(A))):\n        if A[i,0]==freq:\n            v=A[i,1]\n    return v            \n\n###\n# find nearest value in an array\ndef nv(x,v):\n    # x is array\n    # v is value\n    idx = (abs(x-v)).argmin()\n    return x[idx]\n\n# Overall function to get path-averaged group velocity\ndef pathvels(lat1,lon1,lat2,lon2,map10,map15,map20,map25,map30,map35,map40):\n\n    Rearth=6371.25;\n    circE=2*np.pi*Rearth;\n    \n    # Get distance and azimuth\n    p=Geodesic.WGS84.Inverse(lat1,lon1,lat2,lon2)\n    \n    minor=float(p['s12']) / 1000.00\n    major=circE-minor\n            \n    l1=Geodesic.WGS84.Line(lat1,lon1,p['azi1'])         \n    l2=Geodesic.WGS84.Line(lat1,lon1,p['azi1']-180)     \n    \n    deg=111.17\n    D1=zeros([1,2])\n    for i in arange((361)):\n        b=l1.Position(deg*1000*i)\n        p2=array([b['lat2'],b['lon2']])\n    \n        if i==0:\n            D1[0,0]=p2[0]\n            D1[0,1]=p2[1]\n        else:\n            D1=vstack((D1,p2))\n        \n        bb=Geodesic.WGS84.Inverse(lat2,lon2,b['lat2'],b['lon2'])\n        if bb['s12'] <= deg*1000.0 :\n            break\n    \n    \n    D2=zeros([1,2])\n    for i in arange((361)):\n        b=l2.Position(deg*1000*i)\n        p2=array([b['lat2'],b['lon2']])\n    \n        if i==0:\n            D2[0,0]=p2[0]\n            D2[0,1]=p2[1]\n        else:\n            D2=vstack((D2,p2))\n        \n        bb=Geodesic.WGS84.Inverse(lat2,lon2,b['lat2'],b['lon2'])\n        if bb['s12'] <= deg*1000.0 :\n            break\n    \n    \"\"\"\n    We now have lat and lon points along the major and minor great circles.\n    We calcaulte the group velocity of at each point, and then\n    find the average velocities. \n    \"\"\"\n    \n    for k in arange((len(D1))):\n        if D1[k,1]<0:\n            D1[k,1]+=360\n    for k in arange((len(D2))):\n        if D2[k,1]<0:\n            D2[k,1]+=360\n\n    def Ray(D):\n        U1=zeros([len(D),7])\n        for k in arange((len(D))):\n            # do latitude first\n            \n            ## get correct precision\n            ## designed to match results of Ma et al codes\n            if abs(D[k,1]) < 10:\n                D[k,1]=round(D[k,1],5)\n            if abs(D[k,1]) >= 10 and abs(D[k,1]) < 100:\n                D[k,1]=round(D[k,1],4)\n            if abs(D[k,1]) > 100:\n                D[k,1]=round(D[k,1],3)\n            if abs(D[k,0]) < 10:\n                D[k,0]=round(D[k,0],5)\n            if abs(D[k,0]) >= 10:\n                D[k,0]=round(D[k,0],4)\n            #    \n            # find right index\n            q=where( map10[:,1] == nv(map10[:,1], (D[k,0])  ))[0]\n            qq=where( map10[q,0]==nv(map10[q,0],  (D[k,1])  ))[0]\n            idx=q[qq]\n            \n            # update path\n            U1[k,0]= map10[ idx, 2]\n            U1[k,1]= map15[ idx, 2]\n            U1[k,2]= map20[ idx, 2]\n            U1[k,3]= map25[ idx, 2]\n            U1[k,4]= map30[ idx, 2]\n            U1[k,5]= map35[ idx, 2]\n            U1[k,6]= map40[ idx, 2]\n        mhz=array([10,15,20,25,30,35,40])\n        return array((mhz, hm(U1,axis=0))).T\n\n    return Ray(D1),Ray(D2)\n\n#####################\n## ANGLE CALCULATION FUNCTIONS\n#####################\n\n# keep eqs above certain cc limit\n# also keep which earthquakes were kept\n# Different version of C1\ndef C1_2(phi,cc,clim):\n    PHI=array([]); C=array([]); ix=array([])\n    for i in arange((len(phi))):\n        if cc[i]>clim:\n            PHI=append(PHI,phi[i])\n            C=append(C,cc[i])\n            ix=append(ix,i)\n    return PHI, C, ix\n\n# C2 culling - keep values within 95% circ conf of circ mean\n# also keep which earthquakes were kept\n\n# Get unique events used in final calculation\ndef uniqueevents(phis,ccs,n,R1cc,R2cc):\n    L=len(phis)/2\n    ii=zeros((len(n)))\n    for i in arange((len(n))):\n        if n[i]<L:\n            ii[i]=where(R1cc==ccs[int(n[i])])[0][0]\n        else:\n            ii[i]=where(R2cc==ccs[int(n[i])])[0][0]\n\n    return unique(ii)\n\n\n# Plotting function\ndef centerat(phi,m=0):\n    phinew=copy(phi)\n    if len(shape(phi))==1:\n        for i in arange((len(phi))):\n            if phi[i]>=m+180:\n                phinew[i]-=360\n            if phi[i]<=m-180:\n                phinew[i]+=360\n    else:\n        for k in arange((shape(phi)[1])):\n            for i in arange((shape(phi)[0])):\n                if phi[i,k]>=m+180:\n                    phinew[i,k]-=360\n                if phi[i,k]<=m-180:\n                    phinew[i,k]+=360\n    return phinew\n\n\n# Function to flatten result arrays\ndef flatten(X):\n    return reshape(X,[X.shape[0]*X.shape[1],1])\n\n# median absolute deviation\ndef mad(x):\n    return median(abs(x-median(x)))\n\n# remove outliars\ndef outlier1(Tphi,ix,lim=5.0):\n    devs=abs(Tphi-median(Tphi))/mad(Tphi)\n    ixs=where(devs<lim)\n    return Tphi[ixs],ix[ixs]\n\n# bootstrap mean\ndef boot1(phi,bootnum):\n    m=zeros((bootnum)); L=len(phi)\n    for i in arange((bootnum)):\n        a=np.random.choice(phi,size=L,replace=True)\n        m[i]=cmean(a,high=360)\n    return m\n\n# reorganize results\ndef resort(phi,col2):\n    phi2=centerat(phi,m=cmean(phi,high=360))\n    t=zeros((len(phi2),2))\n    t[:,0]=phi2; t[:,1]=col2\n    t = t[t[:,0].argsort()]\n    return t[:,0], t[:,1]\n\n# final Doran-Laske calculation\ndef fcalc1(phi,cc,lim,R1cc,R2cc):\n    # keep cc over limit\n    Tphi,Tcc,ii=C1_2(phi,cc,lim)\n    if len(Tphi)==0:\n        return 0,180,array([0]),0\n    if mad(Tphi)==0:\n        return mean(Tphi),90,array([1]),len(Tphi)\n    # remove outliers using MAD\n    Tphi,ii=resort(Tphi,ii)\n    Tphi2,ii2=outlier1(Tphi,ii)\n    # bootstrap results for statistic\n    m=boot1(Tphi2,5000)\n    \n    \n    return cmean(m,high=360),2*1.96*cstd(m,high=360),uniqueevents(phi,cc,ii2,R1cc,R2cc),len(Tphi2) \n\n# create histogram of results\ndef fhist1(phi,cc,lim):\n    Tphi,Tcc,ii=C1_2(phi,cc,lim)\n    Tphi,ii=resort(Tphi,ii)\n    Tphi2,ii2=outlier1(Tphi,ii)\n#    plt.figure()\n    plt.hist(Tphi2,bins=25)\n    plt.xlabel('Orientation Estimate')\n    plt.ylabel('Counts')\n    return \n\n    \n    \n    \n#############################\n# A few other random necessary ones\n#############################\n\n# Define rotation function\n#   -rotates horizontal components CW from N by alpha (in degrees)\ndef rot2d(N,E,alpha):\n    a=deg2rad(alpha)  # convert from degrees to radians\n    r=cos(a)*N - sin(a)*E\n    t=sin(a)*N + cos(a)*E\n    return(r,t)\n\n# root mean square\ndef rms(x):\n    return sqrt(mean(abs(x)**2))\n\ndef find_nearest(array,value):\n    return (abs(array-value)).argmin()\n\ndef checklen(st,hrs):\n    # checks to see if there is enough downloaded data to run program\n    L=len(st)\n    for i in arange((L)):\n        if (UTCDateTime(st[i].stats.endtime)-UTCDateTime(st[i].stats.starttime))+100 < hrs:\n            return True        \n    if var(st[0].data)<1 or var(st[1].data)<1 or var(st[2].data)<1:\n        return True\n    return False\n\n# save resutls\ndef saved(R1cc,R2cc,R1phi,R2phi,loc='temp.dir'):\n    if not os.path.exists(loc):\n        os.mkdir(loc)\n    savetxt(loc+'/'+'R1cc',R1cc)\n    savetxt(loc+'/'+'R2cc',R2cc)\n    savetxt(loc+'/'+'R1phi',R1phi)\n    savetxt(loc+'/'+'R2phi',R2phi)\n    return\n\n\"\"\"\nFunctions from file formerly called Phases\nMostly deal with computing correlations\nand rotating data\n\"\"\"\n\n\n\n# Resize arrays to all identical shapes\ndef resiz(x1,x2,x3):\n    a1=len(x1); a2=len(x2); a3=len(x3)\n    L=min(array([a1,a2,a3]))\n    return x1[0:L], x2[0:L], x3[0:L]\n    \n# preprocess segments of data\n# taper, zerophase filter, detrend\ndef sw1proc(T,LPF,HPF,corn=4):\n    T.taper(type='hann',max_percentage=0.05)\n    T.filter(\"lowpass\",freq=LPF,corners=corn,zerophase=True)\n    T.filter(\"highpass\",freq=HPF,corners=corn,zerophase=True)\n    T.detrend()\n    \n    return T\n\n# DORAN-LASKE calculation for one freq, one orbit of surface wave\ndef SW1(TT,Rf,LPF,HPF,daz1,A,nameconv,winlen=10.0,ptype=0):\n    # event info\n    daz=daz1[0]/1000.0 # convert to KM\n    baz=daz1[1] # angle from station to event        \n\n    Rvel=getf(Rf,A) # Group velocity at Rf\n    R1window=(1.0/(Rf/1000.0))*winlen\n\n    # Process\n    T=sw1proc(TT.copy(),LPF,HPF)\n\n    # Window info\n    arv=1.0/Rvel * daz\n    r1=arv-R1window/2.0\n    r2=arv+R1window/2.0\n\n    dt=T[0].stats.starttime\n    P=T.slice(starttime=dt+r1,endtime=dt+r2)\n    \n    rdat=P[0].data\n    rdat2=P[1].data\n    vdat=imag(sig.hilbert(P[2].data))\n    \n    # Ensure all data vectors are same length\n    rdat,rdat2,vdat=resiz(rdat,rdat2,vdat)\n    \n    # rotate through and find max cc\n    degs=360*4\n    ang=arange((degs))\n    cc=zeros((degs)); cc2=zeros((degs)); cc3=zeros((degs))\n    for k in ang:\n        n,e=rot2d(rdat,rdat2,k/4.0)\n        covmat=corrcoef(n,vdat)\n        cc[k]=covmat[0,1]\n        cstar=cov(vdat,n)/cov(vdat)\n        cc2[k]=cstar[0,1]\n        cstar=cov(vdat,e)/cov(vdat)\n        cc3[k]=cstar[0,1]\n\n    # Keep angle determined by cstar, but use rating from corrcoef\n    #   Formulas in Stachnik paper\n    ANG=cc2.argmax(); #CC[j]=cc[ANG]\n    # correct for angles above 360\n    or_ang= (baz- (360 - ANG/4.0) )\n\n    # ADJUST FOR NAMING CONVENTION\n    if nameconv==3: or_ang+=180\n\n    if or_ang<0: or_ang+=360\n    if or_ang>=360: or_ang-=360\n    # Can plot xc\n\n    # plotting:\n    # ptype=0, no plot\n    # ptype=1, Rayleigh plot\n    # ptype=2, Love plot\n\n    if ptype==1:\n        import matplotlib.dates as dat\n        X=P[0].times()\n        T=zeros((len(X)))\n        for q in arange((len(T))):\n            T[q]=dt+r1+X[q]\n        ZZ=dat.epoch2num(T)\n        Z=dat.num2date(ZZ)\n        n,e=rot2d(rdat,rdat2,ANG/4.0)\n#        plt.figure()\n        plt.plot(Z,vdat,label='Vetical')\n#        savetxt('/Users/adoran/Desktop/T.txt',T)\n#        savetxt('/Users/adoran/Desktop/vdat.txt',vdat)\n#        savetxt('/Users/adoran/Desktop/n.txt',n)\n        plt.hold(\"on\")\n        plt.plot(Z,n,label='BH1')    \n        plt.legend(loc=4)\n        plt.xlabel('Time')\n        plt.ylabel('Counts')\n        plt.title('D-L Results (%i mHz)' %(Rf))\n    elif ptype==2:\n        import matplotlib.dates as dat\n        X=P[0].times()\n        T=zeros((len(X)))\n        for q in arange((len(T))):\n            T[q]=dt+r1+X[q]\n        ZZ=dat.epoch2num(T)\n        Z=dat.num2date(ZZ)\n        n,e=rot2d(rdat,rdat2,ANG/4.0)\n        plt.figure()\n        plt.subplot(121)\n        plt.plot(Z,vdat,label='Vetical')\n        plt.hold(\"on\")\n        plt.plot(Z,n,label='BH1')    \n        plt.legend(loc=4)\n        plt.xlabel('Time')\n        plt.suptitle('D-L Results (%i mHz)' %(Rf))\n        plt.subplot(122)\n        plt.plot(Z,e,label='BH2')\n        plt.xlabel('Time')\n        plt.ylabel('Counts')\n        plt.legend(loc=4)\n    elif ptype==3:\n        import matplotlib.dates as dat\n        X=P[0].times()\n        T=zeros((len(X)))\n        for q in arange((len(T))):\n            T[q]=dt+r1+X[q]\n        n,e=rot2d(rdat,rdat2,ANG/4.0)\n        plt.figure()\n        plt.plot(T,vdat,label='Vetical')\n        \n#\n    return or_ang, cc[ANG]\n\n\n\n\n\n", "meta": {"hexsha": "8231de48045dfd4f2ffcf389edcc12cd9137a031", "size": 12985, "ext": "py", "lang": "Python", "max_stars_repo_path": "locfuns.py", "max_stars_repo_name": "kschramm-usgs/DLOPy", "max_stars_repo_head_hexsha": "190b83c179eeec4501550d59c757f1455c707174", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-08-25T11:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-25T11:11:59.000Z", "max_issues_repo_path": "locfuns.py", "max_issues_repo_name": "kschramm-usgs/DLOPy", "max_issues_repo_head_hexsha": "190b83c179eeec4501550d59c757f1455c707174", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "locfuns.py", "max_forks_repo_name": "kschramm-usgs/DLOPy", "max_forks_repo_head_hexsha": "190b83c179eeec4501550d59c757f1455c707174", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6632443532, "max_line_length": 119, "alphanum_fraction": 0.5474778591, "include": true, "reason": "import numpy,from numpy,import scipy,from scipy", "num_tokens": 4134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.17212552921171415}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Built-in imports\nimport warnings\nimport itertools\n\n# 3rd party imports\nimport numpy as np\nimport xarray as xr\n\n# Local imports\nfrom .feeps_pitch_angles import feeps_pitch_angles\nfrom .feeps_active_eyes import feeps_active_eyes\n\n__author__ = \"Louis Richard\"\n__email__ = \"louisr@irfu.se\"\n__copyright__ = \"Copyright 2020-2021\"\n__license__ = \"MIT\"\n__version__ = \"2.3.7\"\n__status__ = \"Prototype\"\n\n# Angular response (finite field of view) of instruments electrons can use\n# +/- 21.4 deg on each pitch angle as average response angle; ions can start\n# with +/-10 deg, but both need to be further refined\nangular_repsonse = {\"electron\": 21.4, \"ion\": 10}\n\n\ndef _pa_data_map(idx_maps, d_type, d_rate):\n    pa_data_map = {}\n\n    if d_rate == \"srvy\":\n        pa_data_map[f\"top-{d_type}\"] = idx_maps[f\"{d_type}-top\"]\n        pa_data_map[f\"bottom-{d_type}\"] = idx_maps[f\"{d_type}-bottom\"]\n    else:\n        # note: the following are indices of the top/bottom sensors in pa_data\n        # they should be consistent with pa_dlimits.labels\n        pa_data_map[\"top-electron\"] = np.arange(9)\n        pa_data_map[\"bottom-electron\"] = np.arange(9, 18)\n\n        # and ions:\n        pa_data_map[\"top-ion\"] = [0, 1, 2]\n        pa_data_map[\"bottom-ion\"] = [3, 4, 5]\n\n    return pa_data_map\n\n\ndef _dpa_dflux(inp_dataset, pitch_angles, pa_data_map, energy, d_type, mms_id):\n    pa_times = pitch_angles.time\n    pa_data = pitch_angles.data\n\n    trange = np.datetime_as_string(np.hstack([np.min(pa_times.data),\n                                              np.max(pa_times.data)]), \"ns\")\n\n    eyes = feeps_active_eyes(inp_dataset.attrs, list(trange), mms_id)\n\n    sensor_types = [\"top\", \"bottom\"]\n\n    n_times = len(pa_times)\n    n_top = len(pa_data_map[f\"top-{d_type}\"])\n    n_bottom = len(pa_data_map[f\"bottom-{d_type}\"])\n\n    dflux, dpa = [np.zeros([n_times, n_top + n_bottom]) for _ in range(2)]\n\n    for s_type in sensor_types:\n        pa_map = pa_data_map[f\"{s_type}-{d_type}\"]\n\n        particle_idxs = [eye - 1 for eye in eyes[s_type]]\n\n        for isen, sensor_num in enumerate(particle_idxs):\n            var_name = \"{}-{:d}\".format(s_type, sensor_num + 1)\n\n            data = inp_dataset[var_name].data\n            energies = inp_dataset[inp_dataset[var_name].dims[1]].data\n\n            # remove any 0s before averaging\n            data[data == 0] = \"nan\"\n\n            # assumes all energies are NaNs if the first is\n            if np.isnan(energies[0]):\n                continue\n\n            # energy indices to use:\n            idx = np.where(np.logical_and(energies >= energy[0],\n                                          energies <= energy[1]))[0]\n\n            with warnings.catch_warnings():\n                warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n                dflux[:, pa_map[isen]] = np.nanmean(data[:, idx], axis=1)\n\n            dpa[:, pa_map[isen]] = pa_data[:, pa_map[isen]]\n\n    # we need to replace the 0.0s left in after populating dpa with NaNs;\n    # these 0.0s are left in there because these points aren't covered by\n    # sensors loaded for this datatype/d_ratee\n    dpa[dpa == 0] = \"nan\"\n\n    return dpa, dflux\n\n\ndef _pa_flux(pa_times, pa_bins, pa_labels, dpa, dflux, d_type):\n    n_pabins = len(pa_bins) - 1\n    # Account for angular response\n    dangresp = angular_repsonse[d_type]\n\n    pa_flux = np.zeros([len(pa_times), int(n_pabins)])\n    delta_pa = (pa_bins[1] - pa_bins[0]) / 2.0\n\n    # Now loop through PA bins and time, find the telescopes where there is\n    # data in those bins and average it up!\n    for (pa_idx, pa_time), ipa in itertools.product(enumerate(pa_times),\n                                                    range(n_pabins)):\n        if not np.isnan(dpa[pa_idx, :][0]):\n            with warnings.catch_warnings():\n                warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n                ind = np.where(\n                    (dpa[pa_idx, :] + dangresp >= pa_labels[ipa] - delta_pa)\n                    & (dpa[pa_idx, :] - dangresp < pa_labels[ipa] + delta_pa))\n\n                if ind[0].size != 0:\n                    if len(ind[0]) > 1:\n                        pa_flux[pa_idx, ipa] = np.nanmean(\n                            dflux[pa_idx, ind[0]], axis=0)\n                    else:\n                        pa_flux[pa_idx, ipa] = dflux[pa_idx, ind[0]]\n\n    pa_flux[pa_flux == 0] = \"nan\"  # fill any missed bins with NAN\n\n    return pa_flux\n\n\ndef feeps_pad(inp_dataset, b_bcs, bin_size: float = 16.3636,\n              energy: list = None):\n    r\"\"\"Compute pitch angle distribution using FEEPS data.\n\n    Parameters\n    ----------\n    inp_dataset : xarray.Dataset\n        Energy spectrum of all eyes.\n    b_bcs : xarray.DataArray\n        Time series of the magnetic field in spacecraft coordinates.\n    bin_size : float, Optional\n        Width of the pitch angles bins. Default is 16.3636.\n    energy : array_like, Optional\n        Energy range of particles. Default is [70., 600.]\n\n    Returns\n    -------\n    pad : xarray.DataArray\n        Time series of the pitch angle distribution.\n\n    \"\"\"\n\n    if energy is None:\n        energy = [70., 600.]\n\n    assert energy[0] > 32., \"Please use a starting energy of 32 keV or above\"\n\n    time = inp_dataset.time.data\n    attrs = inp_dataset.attrs\n    mms_id, d_type, d_rate = list(map(attrs.get, [\"mmsId\", \"dtype\", \"tmmode\"]))\n\n    assert d_rate in [\"srvy\", \"brst\"]\n    assert d_type in [\"electron\", \"ion\"]\n\n    n_pabins = int(180 / bin_size)\n    pa_bins = [180. * pa_bin / n_pabins for pa_bin in range(n_pabins + 1)]\n    pa_labels = [pa_bin  + bin_size / 2. for pa_bin in pa_bins[:-1]]\n\n    pitch_angles, idx_maps = feeps_pitch_angles(inp_dataset, b_bcs)\n\n    pa_data_map = _pa_data_map(idx_maps, d_type, d_rate)\n\n    dpa, dflux = _dpa_dflux(inp_dataset, pitch_angles, pa_data_map, energy,\n                            d_type, mms_id)\n\n    pa_flux = _pa_flux(pitch_angles.time, pa_bins, pa_labels, dpa, dflux,\n                       d_type)\n\n    pad = xr.DataArray(pa_flux, coords=[time, pa_labels],\n                       dims=[\"time\", \"theta\"], attrs=attrs)\n\n    return pad\n", "meta": {"hexsha": "8bbc1757db4c0e43572ef144e5cf842affea6869", "size": 6129, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyrfu/mms/feeps_pad.py", "max_stars_repo_name": "ablotekar/irfu-python", "max_stars_repo_head_hexsha": "740cb51ca9ce2ab0d62cb6fef3a7a722d430d79e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-27T11:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-17T11:08:10.000Z", "max_issues_repo_path": "pyrfu/mms/feeps_pad.py", "max_issues_repo_name": "ablotekar/irfu-python", "max_issues_repo_head_hexsha": "740cb51ca9ce2ab0d62cb6fef3a7a722d430d79e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-04T07:55:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-10T12:45:27.000Z", "max_forks_repo_path": "pyrfu/mms/feeps_pad.py", "max_forks_repo_name": "ablotekar/irfu-python", "max_forks_repo_head_hexsha": "740cb51ca9ce2ab0d62cb6fef3a7a722d430d79e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-17T11:08:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-18T18:41:42.000Z", "avg_line_length": 33.3097826087, "max_line_length": 79, "alphanum_fraction": 0.6069505629, "include": true, "reason": "import numpy", "num_tokens": 1653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.17212552921171415}}
{"text": "import numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras.layers import Layer\n\n\nclass ScheduledDropout(Layer):\n    \"\"\"Applies Scheduled Dropout to the input.\n        The Dropout layer randomly sets input units to 0 with a frequency of `rate`\n        scheduled by network layer's depth and training step at each step, which\n        helps prevent overfitting.\n        Inputs not set to 0 are scaled up by 1/(1 - rate) such that the sum over\n        all inputs is unchanged.\n        Note that the Dropout layer only applies when `training` is set to True\n        such that no values are dropped during inference. When using `model.fit`,\n        `training` will be appropriately set to True automatically, and in other\n        contexts, you can set the kwarg explicitly to True when calling the layer.\n        (This is in contrast to setting `trainable=False` for a Dropout layer.\n        `trainable` does not affect the layer's behavior, as Dropout does\n        not have any variables/weights that can be frozen during training.)\n        Arguments:\n            drop_rate: Float between 0 and 1. Fraction of the input units to drop.\n            cell_num: Cell number in the network\n            total_num_cells: Number of cells in the network\n            total_training_steps: Number of total steps performed during training\n            seed: A Python integer to use as random seed.\n        Call arguments:\n            inputs: Input tensor (of any rank).\n            training: Python boolean indicating whether the layer should behave in\n                training mode (adding dropout) or in inference mode (doing nothing).\n    \"\"\"\n\n    def __init__(self, drop_rate, cell_num, total_num_cells, total_training_steps, seed=None, **kwargs):\n        super(ScheduledDropout, self).__init__(**kwargs)\n        self.drop_rate = drop_rate\n        self._cell_num = cell_num\n        self._total_num_cells = total_num_cells\n        self._total_training_steps = total_training_steps\n        self.seed = seed\n\n    def call(self, inputs, training=None):\n        if training is None:\n            training = K.learning_phase()\n        scheduled_drop_rate = self._compute_scheduled_dropout_rate()\n\n        def dropped_inputs():\n            noise_shape = tf.shape(inputs)\n            random_tensor = 1 - scheduled_drop_rate\n            random_tensor += tf.random.uniform(noise_shape, dtype=tf.float32)\n            binary_tensor = tf.cast(tf.floor(random_tensor), inputs.dtype)\n            keep_prob_inv = tf.cast(1.0 / (1-scheduled_drop_rate), inputs.dtype)\n            outputs = inputs * keep_prob_inv * binary_tensor\n            return outputs\n\n        if training:\n            output = dropped_inputs()\n        else:\n            output = tf.identity(inputs)\n        return output\n\n    def _compute_scheduled_dropout_rate(self):\n        drop_rate = self.drop_rate\n        if self._total_num_cells is not None:\n            # Scale keep prob by layer number\n            assert self._cell_num != -1\n            # The added 2 is for the reduction cells\n            num_cells = self._total_num_cells\n            layer_ratio = (self._cell_num + 1) / float(num_cells)\n            drop_rate = layer_ratio * drop_rate\n        if self._total_training_steps is not None:\n            # Decrease the keep probability over time\n            current_step = tf.convert_to_tensor(tf.compat.v1.train.get_or_create_global_step())\n            tf.compat.v1.get_variable_scope().reuse_variables()\n            current_step = tf.cast(current_step, tf.float32)\n            drop_path_burn_in_steps = self._total_training_steps\n            current_ratio = current_step / drop_path_burn_in_steps\n            current_ratio = tf.minimum(1.0, current_ratio)\n            drop_rate = current_ratio * drop_rate\n        return drop_rate\n\n    def compute_output_shape(self, input_shape):\n        return input_shape\n\n    def get_config(self):\n        config = {\n            'drop_rate': self.drop_rate,\n            'cell_num': self._cell_num,\n            'total_num_cells': self._total_num_cells,\n            'total_training_steps': self._total_training_steps,\n            'seed': self.seed\n        }\n        base_config = super(ScheduledDropout, self).get_config()\n        return dict(list(base_config.items()) + list(config.items()))\n\n\nclass ScheduledDroppath(Layer):\n    \"\"\"Applies Scheduled Droppath to the input.\n        The Droppath layer randomly sets whole input path inside to 0 with a\n        frequency of `rate` scheduled by network layer's depth and training\n        step at each step, which helps prevent overfitting.\n        Inputs not set to 0 are scaled up by 1/(1 - rate) such that the sum over\n        all inputs is unchanged.\n        Note that the Scheduled Droppath layer only applies when `training` is set to True.\n        When using `model.fit`, `training` will be appropriately set to True\n        automatically, and in other contexts, you can set the kwarg explicitly\n        to True when calling the layer. (This is in contrast to setting\n        `trainable=False` for a Droppath layer. `trainable` does not affect the\n        layer's behavior, as Droppath does not have any variables/weights that\n        can be frozen during training.)\n        Arguments:\n            drop_rate: Float between 0 and 1. Fraction of the inputs to drop.\n            cell_num: Cell number in the network\n            total_num_cells: Number of cells in the network\n            total_training_steps: Number of total steps performed during training\n            seed: A Python integer to use as random seed.\n        Call arguments:\n            inputs: Input tensor (of any rank).\n            training: Python boolean indicating whether the layer should behave in\n                training mode (adding dropout) or in inference mode (doing nothing).\n    \"\"\"\n\n    def __init__(self, drop_rate, cell_num, total_num_cells, total_training_steps, seed=None, **kwargs):\n        super(ScheduledDroppath, self).__init__(**kwargs)\n        self.drop_rate = drop_rate\n        self._cell_num = cell_num\n        self._total_num_cells = total_num_cells\n        self._total_training_steps = total_training_steps\n        self.seed = seed\n\n    def call(self, inputs, training=None):\n        if training is None:\n            training = K.learning_phase()\n        scheduled_drop_rate = self._compute_scheduled_drop_rate()\n\n        def dropped_inputs():\n            noise_shape = [tf.shape(input=inputs)[0], 1, 1, 1]\n            random_tensor = 1 - scheduled_drop_rate\n            random_tensor += tf.random.uniform(noise_shape, dtype=tf.float32)\n            binary_tensor = tf.cast(tf.floor(random_tensor), inputs.dtype)\n            keep_prob_inv = tf.cast(1.0 / (1-scheduled_drop_rate), inputs.dtype)\n            tf.print('binary tesnor:', binary_tensor)\n            outputs = inputs * keep_prob_inv * binary_tensor\n            return outputs\n\n        if training:\n            output = dropped_inputs()\n        else:\n            output = tf.identity(inputs)\n        return output\n\n    def _compute_scheduled_drop_rate(self):\n        drop_rate = self.drop_rate\n        if self._total_num_cells is not None:\n            # Scale keep prob by layer number\n            assert self._cell_num != -1\n            # The added 2 is for the reduction cells\n            num_cells = self._total_num_cells\n            layer_ratio = (self._cell_num + 1) / float(num_cells)\n            drop_rate = layer_ratio * drop_rate\n        if self._total_training_steps is not None:\n            # Decrease the keep probability over time\n            current_step = tf.convert_to_tensor(tf.compat.v1.train.get_or_create_global_step())\n            tf.compat.v1.get_variable_scope().reuse_variables()\n            current_step = tf.cast(current_step, tf.float32)\n            drop_path_burn_in_steps = self._total_training_steps\n            current_ratio = current_step / drop_path_burn_in_steps\n            current_ratio = tf.minimum(1.0, current_ratio)\n            drop_rate = current_ratio * drop_rate\n        return drop_rate\n\n    def compute_output_shape(self, input_shape):\n        return input_shape\n\n    def get_config(self):\n        config = {\n            'drop_rate': self.drop_rate,\n            'cell_num': self._cell_num,\n            'total_num_cells': self._total_num_cells,\n            'total_training_steps': self._total_training_steps,\n            'seed': self.seed\n        }\n        base_config = super(ScheduledDroppath, self).get_config()\n        return dict(list(base_config.items()) + list(config.items()))\n\n\nclass ConcreteDropout(Layer):\n    \"\"\"Applies Concrete Dropout to the input.\n        The Concrete Droppath layer randomly sets input path to 0 with a\n        frequency considered as a weight of the layer optimized during training\n        time, which helps prevent overfitting.\n        Inputs not set to 0 are scaled up by 1/(1 - rate) such that the sum over\n        all inputs is unchanged.\n        Note that the Concrete Dropout layer only applies when `training` is set\n        to True. When using `model.fit`, `training` will be appropriately set to\n        True automatically, and in other contexts, you can set the kwarg explicitly\n        to True when calling the layer. (This is in contrast to setting\n        `trainable=False` for a Concrete Dropout layer. `trainable` does not affect\n        the layer's behavior, as Dropout does not have any variables/weights that\n        can be frozen during training.)\n        Arguments:\n            dropout_regularizer: A positive number which satisfies\n                $dropout_regularizer = 2 / (\\tau * N)$ with model precision\n                $\\tau$ (inverse observation noise) and N the number of\n                instances in the dataset.\n            init_min: dropout probability initializer min\n            init_max: dropout probability initializer max\n            seed: A Python integer to use as random seed.\n        Call arguments:\n            inputs: Input tensor (of any rank).\n            training: Python boolean indicating whether the layer should behave in\n                training mode (adding dropout) or in inference mode (doing nothing).\n    \"\"\"\n\n    def __init__(self, dropout_regularizer=1e-5, init_min=0.1, init_max=0.1,\n                 seed=None, **kwargs):\n        super(ConcreteDropout, self).__init__(**kwargs)\n        self.dropout_regularizer = dropout_regularizer\n        self.init_min = tf.math.log(init_min) - tf.math.log(1. - init_min)\n        self.init_max = tf.math.log(init_max) - tf.math.log(1. - init_max)\n        self.p_logit = None\n        self.seed = seed\n\n    @tf.function\n    def get_p(self):\n        return tf.nn.sigmoid(self.p_logit[0])\n\n    def build(self, input_shape=None):\n        super(ConcreteDropout, self).build(input_shape)\n        # initialise p\n        self.p_logit = self.add_weight(name='p_logit',\n                                       shape=(1,),\n                                       initializer=tf.initializers.RandomUniform(self.init_min, self.init_max),\n                                       trainable=True)\n        # initialise regulariser / prior KL term\n        input_dim = np.prod(input_shape[1:])\n        dropout_regularizer = self.get_p() * K.log(self.get_p())\n        dropout_regularizer += (1. - self.get_p()) * K.log(1. - self.get_p())\n        dropout_regularizer *= self.dropout_regularizer * input_dim\n        regularizer = dropout_regularizer\n        self.add_loss(regularizer)\n\n    def call(self, inputs, training=None):\n        if training:\n            return self.concrete_dropout(inputs)\n        else:\n            tf.identity(inputs)\n\n    def concrete_dropout(self, x):\n        '''\n        Concrete dropout - used at training time and testing time (gradients can be propagated)\n        :param x: input\n        :return:  approx. dropped out input\n        '''\n\n        eps = K.cast_to_floatx(K.epsilon())\n        temp = 0.1\n        unif_noise = K.random_uniform(K.shape(x))\n        drop_prob = (\n            K.log(self.get_p() + eps)\n            - K.log(1. - self.get_p() + eps)\n            + K.log(unif_noise + eps)\n            - K.log(1. - unif_noise + eps)\n        )\n        drop_prob = K.sigmoid(drop_prob / temp)\n        random_tensor = 1. - drop_prob\n        retain_prob = 1. - self.get_p()\n        x *= random_tensor\n        x /= retain_prob\n        return x\n\n    def compute_output_shape(self, input_shape):\n        return input_shape\n\n    def get_config(self):\n        config = {\n            'dropout_regularizer': self.dropout_regularizer,\n            'init_min': self.init_min.numpy(),\n            'init_max': self.init_max.numpy(),\n            'p_logit': self.p_logit.numpy(),\n            'seed': self.seed\n        }\n        base_config = super(ConcreteDropout, self).get_config()\n        return dict(list(base_config.items()) + list(config.items()))\n\n\nclass ConcreteDroppath(Layer):\n    \"\"\"Applies Concrete Droppath to the input.\n        The Concrete Droppath layer randomly sets input path to 0 with a\n        frequency considered as a weight of the layer optimized during training\n        time, which helps prevent overfitting.\n        Inputs not set to 0 are scaled up by 1/(1 - rate) such that the sum over\n        all inputs is unchanged.\n        Note that the Concrete Droppath layer only applies when `training` is set\n        to True. When using `model.fit`, `training` will be appropriately set to\n        True automatically, and in other contexts, you can set the kwarg explicitly\n        to True when calling the layer. (This is in contrast to setting\n        `trainable=False` for a Concrete Droppath layer. `trainable` does not affect\n        the layer's behavior, as Dropout does not have any variables/weights that\n        can be frozen during training.)\n        Arguments:\n            dropout_regularizer: A positive number which satisfies\n                $dropout_regularizer = 2 / (\\tau * N)$ with model precision\n                $\\tau$ (inverse observation noise) and N the number of\n                instances in the dataset.\n            init_min: dropout probability initializer min\n            init_max: dropout probability initializer max\n            seed: A Python integer to use as random seed.\n        Call arguments:\n            inputs: Input tensor (of any rank).\n            training: Python boolean indicating whether the layer should behave in\n                training mode (adding dropout) or in inference mode (doing nothing).\n    \"\"\"\n\n    def __init__(self, dropout_regularizer=1e-5, init_min=0.1, init_max=0.1,\n                 seed=None, **kwargs):\n        super(ConcreteDroppath, self).__init__(**kwargs)\n        self.dropout_regularizer = dropout_regularizer\n        self.init_min = tf.math.log(init_min) - tf.math.log(1. - init_min)\n        self.init_max = tf.math.log(init_max) - tf.math.log(1. - init_max)\n        self.p_logit = None\n        self.seed = seed\n\n    @tf.function\n    def get_p(self):\n        return tf.nn.sigmoid(self.p_logit[0])\n\n    def build(self, input_shape=None):\n        super(ConcreteDroppath, self).build(input_shape)\n        # initialise p\n        self.p_logit = self.add_weight(name='p_logit',\n                                       shape=(1,),\n                                       initializer=tf.initializers.RandomUniform(self.init_min, self.init_max),\n                                       trainable=True)\n        # initialise regulariser / prior KL term\n        input_dim = 1\n        dropout_regularizer = self.get_p() * K.log(self.get_p())\n        dropout_regularizer += (1. - self.get_p()) * K.log(1. - self.get_p())\n        dropout_regularizer *= self.dropout_regularizer * input_dim\n        regularizer = dropout_regularizer\n        self.add_loss(regularizer)\n\n    def call(self, inputs, training=None):\n        if training:\n            return self.concrete_droppath(inputs)\n        else:\n            tf.identity(inputs)\n\n    def concrete_droppath(self, x):\n        \"\"\"\n        Concrete droppath - used at training and testing time (gradients can be propagated)\n        :param x: input\n        :return:  approx. dropped out input\n        \"\"\"\n\n        eps = K.cast_to_floatx(K.epsilon())\n        temp = 0.1\n        unif_noise = tf.random.uniform(shape=[K.shape(x)[0], 1, 1, 1])\n        drop_prob = (\n            K.log(self.get_p() + eps)\n            - K.log(1. - self.get_p() + eps)\n            + K.log(unif_noise + eps)\n            - K.log(1. - unif_noise + eps)\n        )\n        drop_prob = K.sigmoid(drop_prob / temp)\n        random_tensor = 1. - drop_prob\n        retain_prob = 1. - self.get_p()\n        x *= random_tensor\n        x /= retain_prob\n        return x\n\n    def compute_output_shape(self, input_shape):\n        return input_shape\n\n    def get_config(self):\n        config = {\n            'dropout_regularizer': self.dropout_regularizer,\n            'init_min': self.init_min.numpy(),\n            'init_max': self.init_max.numpy(),\n            'p_logit': self.p_logit.numpy(),\n            'seed': self.seed\n        }\n        base_config = super(ConcreteDroppath, self).get_config()\n        return dict(list(base_config.items()) + list(config.items()))\n", "meta": {"hexsha": "1ec656496c63a15bf6ed0753356bf4ea736cde2e", "size": 17149, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/models/nasnet_utils_do.py", "max_stars_repo_name": "Vole1/MC-CDP-BraTS2018", "max_stars_repo_head_hexsha": "32430dc87d40c8d1f41092598c839e0b34f32e7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-29T09:11:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T09:11:12.000Z", "max_issues_repo_path": "src/models/nasnet_utils_do.py", "max_issues_repo_name": "Vole1/MC-CDP-BraTS2018", "max_issues_repo_head_hexsha": "32430dc87d40c8d1f41092598c839e0b34f32e7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/models/nasnet_utils_do.py", "max_forks_repo_name": "Vole1/MC-CDP-BraTS2018", "max_forks_repo_head_hexsha": "32430dc87d40c8d1f41092598c839e0b34f32e7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.5428571429, "max_line_length": 111, "alphanum_fraction": 0.6316986413, "include": true, "reason": "import numpy", "num_tokens": 3711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.1721255292117141}}
{"text": "\"\"\"\nauthor : JAWAD FAYAZ (email: jfayaz@uci.edu) (website: https://jfayaz.github.io) \n\n------------------------------ Instructions ------------------------------------- \nThis code develops the RotD50 Sa and RotD100 Sa Spectra of the Bi-Directional \nGround Motion records as '.AT2' files provided in the current directory \n\nThe two directions of the ground motion record must be named as 'GM1i' and 'GM2i',\nwhere 'i' is the ground motion number which goes from 1 to 'n', 'n' being the total\nnumber of ground motions for which the Spectra needs to be generated. The extension\nof the files must be '.AT2'\n\nFor example: If the Spectra of two ground motion records are required, 4 files with\nthe following names must be provided in the given 'GM' folder:\n    'GM11.AT2' - Ground Motion 1 in direction 1 (direction 1 can be either one of the bi-directional GM as we are rotating the ground motions it does not matter) \n    'GM21.AT2' - Ground Motion 1 in direction 2 (direction 2 is the other direction of the bi-directional GM)\n    'GM12.AT2' - Ground Motion 2 in direction 1 (direction 1 can be either one of the bi-directional GM as we are rotating the ground motions it does not matter)  \n    'GM22.AT2' - Ground Motion 2 in direction 2 (direction 2 is the other direction of the bi-directional GM)\n\nThe Ground Motion file must be a vector file with 4 header lines.The first 3 lines can have\nany content, however, the 4th header line must be written exactly as per the following example:\n    'NPTS=  15864, DT= 0.0050'\nThe 'ReadGMFile.py' can be edited accordingly  for any other format \n   \nYou may run this code in python IDE: 'Spyder' or any other similar IDE\n\nMake sure you have the following python libraries installed:\n    os \n    sys \n    pathlib\n    fnmatch\n    shutil\n    IPython\n    pandas \n    numpy\n    matplotlib.pyplot \n \nINPUT:\nThis codes provides the option to have 3 different regions of developing the Spectra of ground motions with different period intervals (discretizations)\nThe following inputs within the code are required:\n    'Path_to_openpyfiles'--> Path where the library files 'opensees.pyd' and 'LICENSE.rst' of OpenSeesPy are included (for further details go to https://openseespydoc.readthedocs.io/en/latest/windows.html)\n    'Int_T_Reg_1'        --> Period Interval for the first region of the Spectrum \n    'End_T_Reg_1'        --> Last Period of the first region of the Spectrum (where to end the first region)\n    'Int_T_Reg_2'        --> Period Interval for the second region of the Spectrum \n    'End_T_Reg_2'        --> Last Period of the second region of the Spectrum (where to end the second region)\n    'Int_T_Reg_3'        --> Period Interval for the third region of the Spectrum \n    'End_T_Reg_3'        --> Last Period of the third region of the Spectrum (where to end the third region)\n    'Plot_Spectra'       --> whether to plot the generated Spectra of the ground motions (options: 'Yes', 'No')    \n\nOUTPUT:\nThe output will be provided in a saperate 'GMi_Spectra.txt' file for each ground motion record, where 'i' denotes the number of ground motion in the same of\nprovided 'GM1i.AT2' and 'GM2i.AT2' files. The output files will be generated in a saperate folder 'Spectra' which will be created in the current folder\nThe 'GMi_Spectra.txt' file will consist of space-saperated file with:\n    'Periods (secs)' 'RotD50 Sa (g)' 'RotD100 Sa (g)' \n    \n%%%%% ========================================================================================================================================================================= %%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\"\"\"\n\n##### ================== INPUTS  ================== #####\n\n# Path where the library files 'opensees.pyd' and 'LICENSE.rst' are included (for further details go to https://openseespydoc.readthedocs.io/en/latest/windows.html)\nPath_to_openpyfiles = 'C:\\Tcl'\n\n# For periods 0 to 'End_T_Reg_1' in an interval of 'Int_T_Reg_1'\nInt_T_Reg_1       = 0.1\nEnd_T_Reg_1       = 1\n\n# For periods ['End_T_Reg_1'+'Int_T_Reg_2'] to 'End_T_Reg_2' in an interval of 'Int_T_Reg_2'\nInt_T_Reg_2       = 0.2\nEnd_T_Reg_2       = 2\n\n# For periods ['End_T_Reg_2'+'Int_T_Reg_3'] to 'End_T_Reg_3' in an interval of 'Int_T_Reg_3'\nInt_T_Reg_3       = 0.5\nEnd_T_Reg_3       = 5\n\n# Plot Spectra  (options: 'Yes' or 'No')\nPlot_Spectra      = 'Yes'\n\n\n##### =============== CODE BEGINS ================ #######\n## Importing Libraries\nimport os, sys, pathlib, fnmatch\nimport shutil as st\nfrom IPython import get_ipython\n\nfrom openseespy.opensees import *\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport warnings\nimport matplotlib.cbook\nwarnings.filterwarnings(\"ignore\",category=matplotlib.cbook.mplDeprecation)\nwipe()\n\n# Getting Number of Ground Motions from the GM folder\nGMdir = os.getcwd()\nNo_of_GMs = int(len(fnmatch.filter(os.listdir(GMdir),'*.AT2'))/2)\nprint('\\nGenerating Spectra for {} provided GMs \\n\\n'.format(np.round(No_of_GMs,0)))\n\n# Initializations\nDISPLACEMENTS = pd.DataFrame(columns=['uX','uY'])\nGM_SPECTRA = pd.DataFrame(columns=['Period(s)','RotD50Sa(g)', 'RotD100Sa(g)'])\nSDOF_RESPONSE = [[]]\nGM_RESPONSE = [[]]\n\n# Spectra Generation\nfor iEQ in range(1,No_of_GMs+1):\n    print('Generating Spectra for GM: {} ...\\n'.format(np.round(iEQ,0)))   \n    Periods = np.concatenate((list(np.arange(Int_T_Reg_1,End_T_Reg_1+Int_T_Reg_1,Int_T_Reg_1)),list(np.arange(End_T_Reg_1+Int_T_Reg_2,End_T_Reg_2+Int_T_Reg_2,Int_T_Reg_2)),list(np.arange(End_T_Reg_2+Int_T_Reg_3,End_T_Reg_3+Int_T_Reg_3,Int_T_Reg_3))),axis=0)\n    ii = 0\n    \n    for T in Periods:\n        ii = ii+1\n        GMinter = 0\n               \n        # Storing Periods\n        GM_SPECTRA.loc[ii-1,'Period(s)'] = T\n                \n        # Setting modelbuilder\n        model('basic', '-ndm', 3, '-ndf', 6)\n        \n        # Setting SODF Variables        \n        g = 386.1                   # value of g\n        L = 1.0                     # Length \n        d = 2                       # Diameter\n        r = d/2                     # Radius\n        A = np.pi*(r**2)            # Area\n        E = 1.0                     # Elastic Modulus\n        G = 1.0                     # Shear Modulus\n        I3 = np.pi*(r**4)/4         # Moment of Inertia (zz)                \n        J = np.pi*(r**4)/2          # Polar Moment of Inertia\n        I2 = np.pi*(r**4)/4         # Moment of Inertia (yy)\n        K = 3*E*I3/(L**3)           # Stiffness \n        M = K*(T**2)/4/(np.pi**2)   # Mass\n        omega = np.sqrt(K/M)        # Natural Frequency\n        Tn = 2*np.pi/omega          # Natural Period\n                \n        # Creating nodes\n        node(1, 0.0, 0.0, 0.0)\n        node(2, 0.0, 0.0, L)\n        \n        # Transformation\n        transfTag = 1\n        geomTransf('Linear',transfTag,0.0,1.0,0.0)\n        \n        # Setting boundary condition\n        fix(1, 1, 1, 1, 1, 1, 1)\n        \n        # Defining materials\n        uniaxialMaterial(\"Elastic\", 11, E)\n        \n        # Defining elements\n        element(\"elasticBeamColumn\",12,1,2,A,E,G,J,I2,I3,1)\n        \n        # Defining mass\n        mass(2,M,M,0.0,0.0,0.0,0.0)\n        \n        # Eigen Value Analysis (Verifying Period)\n        numEigen = 1\n        eigenValues = eigen(numEigen)\n        omega = np.sqrt(eigenValues)\n        T = 2*np.pi/omega\n        print('   Calculating Spectral Ordinate for Period = {} secs'.format(np.round(T,3)))\n    \n        ## Reading GM Files \n        exec(open(\"ReadGMFile.py\").read())\t            # read in procedure Multinition \n        iGMinput = 'GM1'+str(iEQ)+' GM2'+str(iEQ) ;\n        GMinput  = iGMinput.split(' ');\n        gmXY     = {}        \n        for i in range(0,2):\n            inFile   = GMdir + '\\\\'+ GMinput[i]+'.AT2';\n            dt, NumPts , gmXY = ReadGMFile()\n        \n        # Storing GM Histories\n        gmX = gmXY[1]\n        gmY = gmXY[2]       \n        gmXY_mat = np.column_stack((gmX,gmX,gmY,gmY))\n        \n        # Bidirectional Uniform Earthquake ground motion (uniform acceleration input at all support nodes)\n        iGMfile      = 'GM1'+str(iEQ)+' GM2'+str(iEQ) ;\t\t\t\n        GMfile       = iGMfile.split(' ')\n        GMdirection  = [1,1,2,2];\t\t\t\t\t\n        GMfact\t     = [np.cos(GMinter*np.pi/180),np.sin(-GMinter*np.pi/180), np.sin(GMinter*np.pi/180), np.cos(GMinter*np.pi/180)];\n        IDTag        = 2\n        loop         = [1,2,3,4]\n        \n        for i in loop:\n            # Setting time series to be passed to uniform excitation\n            timeSeries('Path',IDTag +i, '-dt', dt, '-values', *list(gmXY_mat[:,i-1]), '-factor', GMfact[i-1]*g)\n            # Creating UniformExcitation load pattern\n            pattern('UniformExcitation',  IDTag+i,   GMdirection[i-1],  '-accel', IDTag+i)\n        \n        # Defining Damping\n        # Applying Rayleigh Damping from $xDamp\n        # D=$alphaM*M + $betaKcurr*Kcurrent + $betaKcomm*KlastCommit + $beatKinit*$Kinitial\n        xDamp \t\t= 0.05;\t\t\t\t\t\t\t\t# 5% damping ratio\n        alphaM \t\t= 0.;\t\t\t\t\t\t\t\t# M-prop. damping; D = alphaM*M\n        betaKcurr \t= 0.;         \t\t\t\t\t\t# K-proportional damping;      +beatKcurr*KCurrent\n        betaKcomm \t= 2.*xDamp/omega;   \t\t\t\t# K-prop. damping parameter;   +betaKcomm*KlastCommitt\n        betaKinit \t= 0.;         \t\t\t\t\t\t# initial-stiffness proportional damping      +beatKinit*Kini\n        rayleigh(alphaM,betaKcurr,betaKinit,betaKcomm); # RAYLEIGH damping\n                \n        # Creating the analysis\n        wipeAnalysis()\t\t\t            # clear previously-define analysis parameters\n        constraints(\"Penalty\",1e18, 1e18)   # how to handle boundary conditions\n        numberer(\"RCM\")                     # renumber dof's to minimize band-width (optimization), if you want to\n        system('SparseGeneral')             # how to store and solve the system of equations in the analysis\n        algorithm('Linear')\t                # use Linear algorithm for linear analysis\n        integrator(\"TRBDF2\")                # determine the next time step for an analysis\n        algorithm(\"NewtonLineSearch\")       # define type of analysis: time-dependent\n        test('EnergyIncr',1.0e-6, 100, 0)\n        analysis(\"Transient\")\n        \n        # Variables (Can alter the speed of analysis)\n        dtAnalysis    = dt\n        TmaxAnanlysis = dt*NumPts\n        tFinal        = int(TmaxAnanlysis/dtAnalysis)\n        tCurrent      = getTime()\n        ok            = 0\n        time          = [tCurrent]\n        \n        # Initializations of response\n        u1            = [0.0]\n        u2            = [0.0]\n                \n        # Performing the transient analysis (Performance is slow in this loop, can be altered by changing the parameters)\n        while ok == 0 and tCurrent < tFinal:\n            ok = analyze(1, dtAnalysis)\n            # if the analysis fails try initial tangent iteration\n            if ok != 0:\n                print(\"Iteration failed .. lets try an initial stiffness for this step\")\n                test('NormDispIncr', 1.0e-12,  100, 0)\n                algorithm('ModifiedNewton', '-initial')\n                ok =analyze( 1, .001)\n                \n                if ok == 0:\n                    print(\"that worked .. back to regular newton\")\n                    test('NormDispIncr', 1.0e-12,  10 )\n                    algorithm('Newton')\n                    \n            tCurrent = getTime()\n            time.append(tCurrent)\n            u1.append(nodeDisp(2,1))\n            u2.append(nodeDisp(2,2))  \n            \n        # Storing responses\n        DISPLACEMENTS.loc[ii-1,'uX'] = np.array(u1)\n        DISPLACEMENTS.loc[ii-1,'uY'] = np.array(u2)\n        DISP_X_Y = np.column_stack((np.array(u1),np.array(u2)))\n        \n        # Rotating the Spectra (Projections)\n        Rot_Matrix = np.zeros((2,2))\n        Rot_Disp = np.zeros((180,1))\n        for theta in range (0,180,1):\n            Rot_Matrix [0,0] = np.cos(np.deg2rad(theta))\n            Rot_Matrix [0,1] = np.sin(np.deg2rad(-theta))\n            Rot_Matrix [1,0] = np.sin(np.deg2rad(theta))\n            Rot_Matrix [1,1] = np.cos(np.deg2rad(theta))\n            Rot_Disp[theta,0] = np.max(np.matmul(DISP_X_Y,Rot_Matrix)[:,0])\n        \n        # Storing Spectra\n        Rot_Acc = np.dot(Rot_Disp,(omega**2)/g)\n        GM_SPECTRA.loc[ii-1,'RotD50Sa(g)'] = np.median(Rot_Acc)\n        GM_SPECTRA.loc[ii-1,'RotD100Sa(g)']= np.max(Rot_Acc)\n        wipe()\n\n    # Writing Spectra to Files                \n    if not os.path.exists('Spectra'):\n        os.makedirs('Spectra')            \n    GM_SPECTRA.to_csv('Spectra//GM'+str(iEQ)+'_Spectra.txt', sep=' ',header=True,index=False)\n        \n    # Plotting Spectra\n    if Plot_Spectra == 'Yes':\n        \n        def plot_spectra(PlotTitle,SpectraType,iGM):\n            axes = fig.add_subplot(1, 1, 1)\n            axes.plot(GM_SPECTRA['Period(s)'] , GM_SPECTRA[SpectraType] , '.-',lw=7,markersize=20, label='GM'+str(iGM)) \n            axes.set_xlabel('Period (sec)',fontsize=30,fontweight='bold')\n            axes.set_ylabel(SpectraType,fontsize=30,fontweight='bold')\n            axes.set_title(PlotTitle,fontsize=40,fontweight='bold')\n            axes.tick_params(labelsize= 25)\n            axes.grid(True)\n            axes.set_xlim(0, np.ceil(max(GM_SPECTRA['Period(s)'])))\n            axes.set_ylim(0, np.ceil(max(GM_SPECTRA[SpectraType])))\n            axes.axhline(linewidth=10,color='black')        \n            axes.axvline(linewidth=10,color='black')\n            axes.hold(True)\n            axes.legend(fontsize =30)\n       \n        fig = plt.figure(1,figsize=(18,12))\n        plot_spectra('RotD50 Spectra','RotD50Sa(g)',iEQ)\n       \n        fig = plt.figure(2,figsize=(18,12))\n        plot_spectra('RotD100 Spectra','RotD100Sa(g)',iEQ)\n\n    SDOF_RESPONSE.insert(iEQ-1,DISPLACEMENTS)\n    GM_RESPONSE.insert(iEQ-1,GM_SPECTRA)\n    \n    print('\\nGenerated Spectra for GM: {}\\n\\n'.format(np.round(iEQ,0)))\n", "meta": {"hexsha": "21713fbeed5b62b96e8f7072c7231f66f5ddddc4", "size": 13986, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyExamples/example_RotD_Spectra_Generation.py", "max_stars_repo_name": "gaaraujo/OpenSeesPyDoc", "max_stars_repo_head_hexsha": "a7424f5a1ac5cbda2c221fd68af5b5f3564e2dbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 79, "max_stars_repo_stars_event_min_datetime": "2017-12-25T14:37:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T19:28:20.000Z", "max_issues_repo_path": "pyExamples/example_RotD_Spectra_Generation.py", "max_issues_repo_name": "gaaraujo/OpenSeesPyDoc", "max_issues_repo_head_hexsha": "a7424f5a1ac5cbda2c221fd68af5b5f3564e2dbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 212, "max_issues_repo_issues_event_min_datetime": "2018-02-23T21:03:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T15:41:23.000Z", "max_forks_repo_path": "pyExamples/example_RotD_Spectra_Generation.py", "max_forks_repo_name": "gaaraujo/OpenSeesPyDoc", "max_forks_repo_head_hexsha": "a7424f5a1ac5cbda2c221fd68af5b5f3564e2dbe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 97, "max_forks_repo_forks_event_min_datetime": "2017-12-25T14:37:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T17:14:06.000Z", "avg_line_length": 46.1584158416, "max_line_length": 257, "alphanum_fraction": 0.5783640784, "include": true, "reason": "import numpy", "num_tokens": 3835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3415824927356586, "lm_q1q2_score": 0.17212552583420318}}
{"text": "\"\"\"\nCopyright 2013 Steven Diamond\n\nThis file is part of CVXPY.\n\nCVXPY is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nCVXPY is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with CVXPY.  If not, see <http://www.gnu.org/licenses/>.\n\nTHIS FILE IS DEPRECATED AND MAY BE REMOVED WITHOUT WARNING!\nDO NOT CALL THESE FUNCTIONS IN YOUR CODE!\nWE ARE MOVING ALL SOLVER INTERFACES TO THE REDUCTIONS FOLDER.\n\"\"\"\n\nimport cvxpy.interface as intf\nimport cvxpy.settings as s\nfrom cvxpy.problems.problem_data.compr_matrix import compress_matrix\nfrom cvxpy.problems.solvers.solver import Solver\nfrom cvxpy.problems.kktsolver import get_kktsolver\nimport scipy.sparse as sp\nimport scipy\nimport numpy as np\nimport copy\n\n\nclass CVXOPT(Solver):\n    \"\"\"An interface for the CVXOPT solver.\n    \"\"\"\n    NL_DUAL = 'nl_dual'\n\n    # Solver capabilities.\n    LP_CAPABLE = True\n    SOCP_CAPABLE = True\n    PSD_CAPABLE = True\n    EXP_CAPABLE = True\n    MIP_CAPABLE = False\n\n    # Map of CVXOPT status to CVXPY status.\n    STATUS_MAP = {'optimal': s.OPTIMAL,\n                  'primal infeasible': s.INFEASIBLE,\n                  'dual infeasible': s.UNBOUNDED,\n                  'unknown': s.SOLVER_ERROR}\n\n    def name(self):\n        \"\"\"The name of the solver.\n        \"\"\"\n        return s.CVXOPT\n\n    def import_solver(self):\n        \"\"\"Imports the solver.\n        \"\"\"\n        import cvxopt\n        cvxopt  # For flake8\n\n    def matrix_intf(self):\n        \"\"\"The interface for matrices passed to the solver.\n        \"\"\"\n        return intf.DEFAULT_SPARSE_INTF\n\n    def vec_intf(self):\n        \"\"\"The interface for vectors passed to the solver.\n        \"\"\"\n        return intf.DEFAULT_NP_INTF\n\n    def split_constr(self, constr_map):\n        \"\"\"Extracts the equality, inequality, and nonlinear constraints.\n\n        Parameters\n        ----------\n        constr_map : dict\n            A dict of the canonicalized constraints.\n\n        Returns\n        -------\n        tuple\n            (eq_constr, ineq_constr, nonlin_constr)\n        \"\"\"\n        return (constr_map[s.EQ], constr_map[s.LEQ], constr_map[s.EXP])\n\n    def get_problem_data(self, objective, constraints, cached_data):\n        \"\"\"Returns the argument for the call to the solver.\n\n        Parameters\n        ----------\n        objective : LinOp\n            The canonicalized objective.\n        constraints : list\n            The list of canonicalized cosntraints.\n        cached_data : dict\n            A map of solver name to cached problem data.\n\n        Returns\n        -------\n        dict\n            The arguments needed for the solver.\n        \"\"\"\n        # Returns CVXOPT matrices so can be used by raw CVXOPT solver.\n        data = super(CVXOPT, self).get_problem_data(objective, constraints,\n                                                    cached_data)\n        # Convert A, b, G, h, c to CVXOPT matrices.\n        data[s.A] = intf.sparse2cvxopt(data[s.A])\n        data[s.G] = intf.sparse2cvxopt(data[s.G])\n        data[s.B] = intf.dense2cvxopt(data[s.B])\n        data[s.H] = intf.dense2cvxopt(data[s.H])\n        data[s.C] = intf.dense2cvxopt(data[s.C])\n        return data\n\n    def solve(self, objective, constraints, cached_data,\n              warm_start, verbose, solver_opts):\n        \"\"\"Returns the result of the call to the solver.\n\n        Parameters\n        ----------\n        objective : LinOp\n            The canonicalized objective.\n        constraints : list\n            The list of canonicalized cosntraints.\n        cached_data : dict\n            A map of solver name to cached problem data.\n        warm_start : bool\n            Not used.\n        verbose : bool\n            Should the solver print output?\n        solver_opts : dict\n            Additional arguments for the solver.\n\n        Returns\n        -------\n        tuple\n            (status, optimal value, primal, equality dual, inequality dual)\n        \"\"\"\n        import cvxopt\n        import cvxopt.solvers\n        data = super(CVXOPT, self).get_problem_data(objective, constraints,\n                                                    cached_data)\n        # Save old data in case need to use robust solver.\n        data[s.DIMS] = copy.deepcopy(data[s.DIMS])\n        # Convert all longs to ints.\n        for key, val in data[s.DIMS].items():\n            if isinstance(val, list):\n                data[s.DIMS][key] = [int(v) for v in val]\n            else:\n                data[s.DIMS][key] = int(val)\n        # User chosen KKT solver option.\n        kktsolver = self.get_kktsolver_opt(solver_opts)\n        # Cannot have redundant rows unless using robust LDL kktsolver.\n        if kktsolver != s.ROBUST_KKTSOLVER:\n            # Will detect infeasibility.\n            if self.remove_redundant_rows(data) == s.INFEASIBLE:\n                return {s.STATUS: s.INFEASIBLE}\n        # Convert A, b, G, h, c to CVXOPT matrices.\n        data[s.A] = intf.sparse2cvxopt(data[s.A])\n        data[s.G] = intf.sparse2cvxopt(data[s.G])\n        data[s.B] = intf.dense2cvxopt(data[s.B])\n        data[s.H] = intf.dense2cvxopt(data[s.H])\n        data[s.C] = intf.dense2cvxopt(data[s.C])\n        # Save original cvxopt solver options.\n        old_options = cvxopt.solvers.options.copy()\n        # Silence cvxopt if verbose is False.\n        cvxopt.solvers.options[\"show_progress\"] = verbose\n\n        # Apply any user-specific options.\n        # Rename max_iters to maxiters.\n        if \"max_iters\" in solver_opts:\n            solver_opts[\"maxiters\"] = solver_opts[\"max_iters\"]\n        for key, value in solver_opts.items():\n            cvxopt.solvers.options[key] = value\n\n        # Always do 1 step of iterative refinement after solving KKT system.\n        if \"refinement\" not in cvxopt.solvers.options:\n            cvxopt.solvers.options[\"refinement\"] = 1\n\n        try:\n            # Target cvxopt clp if nonlinear constraints exist.\n            if data[s.DIMS][s.EXP_DIM]:\n                results_dict = self.cpl_solve(data, kktsolver)\n            else:\n                results_dict = self.conelp_solve(data, kktsolver)\n        # Catch exceptions in CVXOPT and convert them to solver errors.\n        except ValueError:\n            results_dict = {\"status\": \"unknown\"}\n\n        # Restore original cvxopt solver options.\n        self._restore_solver_options(old_options)\n        return self.format_results(results_dict, data, cached_data)\n\n    def cpl_solve(self, data, kktsolver):\n        \"\"\"Solve using the cpl solver.\n\n        Parameters\n        ----------\n        data : dict\n            All the problem data.\n        kktsolver : The kktsolver to use.\n        robust : Use the robust kktsolver?\n\n        Returns\n        -------\n        dict\n            The solver output.\n\n        Raises\n        ------\n        ValueError\n            If CVXOPT fails.\n        \"\"\"\n        import cvxopt.solvers\n        if kktsolver == s.ROBUST_KKTSOLVER:\n            # Get custom kktsolver.\n            kktsolver = get_kktsolver(data[s.G],\n                                      data[s.DIMS],\n                                      data[s.A],\n                                      data[s.F])\n        return cvxopt.solvers.cpl(data[s.C],\n                                  data[s.F],\n                                  data[s.G],\n                                  data[s.H],\n                                  data[s.DIMS],\n                                  data[s.A],\n                                  data[s.B],\n                                  kktsolver=kktsolver)\n\n    def conelp_solve(self, data, kktsolver):\n        \"\"\"Solve using the conelp solver.\n\n        Parameters\n        ----------\n        data : dict\n            All the problem data.\n        kktsolver : The kktsolver to use.\n        robust : Use the robust kktsolver?\n\n        Returns\n        -------\n        dict\n            The solver output.\n\n        Raises\n        ------\n        ValueError\n            If CVXOPT fails.\n        \"\"\"\n        import cvxopt.solvers\n        if kktsolver == s.ROBUST_KKTSOLVER:\n            # Get custom kktsolver.\n            kktsolver = get_kktsolver(data[s.G],\n                                      data[s.DIMS],\n                                      data[s.A])\n        return cvxopt.solvers.conelp(data[s.C],\n                                     data[s.G],\n                                     data[s.H],\n                                     data[s.DIMS],\n                                     data[s.A],\n                                     data[s.B],\n                                     kktsolver=kktsolver)\n\n    @staticmethod\n    def remove_redundant_rows(data):\n        \"\"\"Remove redundant constraints from A and G.\n\n        Parameters\n        ----------\n        data : dict\n            All the problem data.\n\n        Returns\n        -------\n        str\n            A status indicating if infeasibility was detected.\n        \"\"\"\n        # Extract data.\n        dims = data[s.DIMS]\n        A = data[s.A]\n        G = data[s.G]\n        b = data[s.B]\n        h = data[s.H]\n        # Remove redundant rows in A.\n        if A.shape[0] > 0:\n            # The pivoting improves robustness.\n            Q, R, P = scipy.linalg.qr(A.todense(), pivoting=True)\n            rows_to_keep = []\n            for i in range(R.shape[0]):\n                if np.linalg.norm(R[i, :]) > 1e-10:\n                    rows_to_keep.append(i)\n            R = R[rows_to_keep, :]\n            Q = Q[:, rows_to_keep]\n            # Invert P from col -> var to var -> col.\n            Pinv = np.zeros(P.size, dtype='int')\n            for i in range(P.size):\n                Pinv[P[i]] = i\n            # Rearrage R.\n            R = R[:, Pinv]\n            A = R\n            b_old = b\n            b = Q.T.dot(b)\n            # If b is not in the range of Q,\n            # the problem is infeasible.\n            if not np.allclose(b_old, Q.dot(b)):\n                return s.INFEASIBLE\n            dims[s.EQ_DIM] = int(b.shape[0])\n            data[\"Q\"] = intf.dense2cvxopt(Q)\n        # Remove obviously redundant rows in G's <= constraints.\n        if dims[s.LEQ_DIM] > 0:\n            G = G.tocsr()\n            G_leq = G[:dims[s.LEQ_DIM], :]\n            h_leq = h[:dims[s.LEQ_DIM]].ravel()\n            G_other = G[dims[s.LEQ_DIM]:, :]\n            h_other = h[dims[s.LEQ_DIM]:].ravel()\n            G_leq, h_leq, P_leq = compress_matrix(G_leq, h_leq)\n            dims[s.LEQ_DIM] = int(h_leq.shape[0])\n            data[\"P_leq\"] = intf.sparse2cvxopt(P_leq)\n            G = sp.vstack([G_leq, G_other])\n            h = np.hstack([h_leq, h_other])\n        # Convert A, b, G, h to CVXOPT matrices.\n        data[s.A] = A\n        data[s.G] = G\n        data[s.B] = b\n        data[s.H] = h\n        return s.OPTIMAL\n\n    @staticmethod\n    def _restore_solver_options(old_options):\n        import cvxopt.solvers\n        for key, value in list(cvxopt.solvers.options.items()):\n            if key in old_options:\n                cvxopt.solvers.options[key] = old_options[key]\n            else:\n                del cvxopt.solvers.options[key]\n\n    def nonlin_constr(self):\n        \"\"\"Returns whether nonlinear constraints are needed.\n        \"\"\"\n        return True\n\n    @staticmethod\n    def get_kktsolver_opt(solver_opts):\n        \"\"\"Returns the KKT solver selected by the user.\n\n        Removes the KKT solver from solver_opts.\n\n        Parameters\n        ----------\n        solver_opts : dict\n            Additional arguments for the solver.\n\n        Returns\n        -------\n        str or None\n            The KKT solver chosen by the user.\n        \"\"\"\n        if \"kktsolver\" in solver_opts:\n            kktsolver = solver_opts[\"kktsolver\"]\n            del solver_opts[\"kktsolver\"]\n        else:\n            kktsolver = 'chol'\n        return kktsolver\n\n    def format_results(self, results_dict, data, cached_data):\n        \"\"\"Converts the solver output into standard form.\n\n        Parameters\n        ----------\n        results_dict : dict\n            The solver output.\n        data : dict\n            Information about the problem.\n        cached_data : dict\n            A map of solver name to cached problem data.\n\n        Returns\n        -------\n        dict\n            The solver output in standard form.\n        \"\"\"\n        import cvxopt\n        new_results = {}\n        status = self.STATUS_MAP[results_dict['status']]\n        new_results[s.STATUS] = status\n        if new_results[s.STATUS] in s.SOLUTION_PRESENT:\n            primal_val = results_dict['primal objective']\n            new_results[s.VALUE] = primal_val + data[s.OFFSET]\n            new_results[s.PRIMAL] = results_dict['x']\n            new_results[s.EQ_DUAL] = results_dict['y']\n            if data[s.DIMS][s.EXP_DIM]:\n                new_results[s.INEQ_DUAL] = results_dict['zl']\n                new_results[self.NL_DUAL] = results_dict['znl']\n            else:\n                new_results[s.INEQ_DUAL] = results_dict['z']\n            # Need to multiply duals by Q and P_leq.\n            if \"Q\" in data:\n                y = results_dict['y']\n                # Test if all constraints eliminated.\n                if y.size[0] == 0:\n                    dual_len = data[\"Q\"].size[0]\n                    new_results[s.EQ_DUAL] = cvxopt.matrix(0., (dual_len, 1))\n                else:\n                    new_results[s.EQ_DUAL] = data[\"Q\"]*y\n            if \"P_leq\" in data:\n                leq_len = data[s.DIMS][s.LEQ_DIM]\n                P_rows = data[\"P_leq\"].size[1]\n                new_len = P_rows + new_results[s.INEQ_DUAL].size[0] - leq_len\n                new_dual = cvxopt.matrix(0., (new_len, 1))\n                z = new_results[s.INEQ_DUAL][:leq_len]\n                # Test if all constraints eliminated.\n                if z.size[0] == 0:\n                    new_dual[:P_rows] = 0\n                else:\n                    new_dual[:P_rows] = data[\"P_leq\"].T*z\n                new_dual[P_rows:] = new_results[s.INEQ_DUAL][leq_len:]\n                new_results[s.INEQ_DUAL] = new_dual\n\n            for key in [s.PRIMAL, s.EQ_DUAL, s.INEQ_DUAL]:\n                new_results[key] = intf.cvxopt2dense(new_results[key])\n            if data[s.DIMS][s.EXP_DIM]:\n                nl_dual = intf.cvxopt2dense(new_results[self.NL_DUAL])\n                new_results[s.INEQ_DUAL] = np.vstack([new_results[s.INEQ_DUAL], nl_dual])\n\n        return new_results\n", "meta": {"hexsha": "8ac0714a3ecb4c781cd4a67b437b6220d7b3eaf9", "size": 14679, "ext": "py", "lang": "Python", "max_stars_repo_path": "cvxpy/problems/solvers/cvxopt_intf.py", "max_stars_repo_name": "NunoEdgarGFlowHub/cvxpy", "max_stars_repo_head_hexsha": "43270fcc8af8fc4742f1b3519800b0074f2e6693", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cvxpy/problems/solvers/cvxopt_intf.py", "max_issues_repo_name": "NunoEdgarGFlowHub/cvxpy", "max_issues_repo_head_hexsha": "43270fcc8af8fc4742f1b3519800b0074f2e6693", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cvxpy/problems/solvers/cvxopt_intf.py", "max_forks_repo_name": "NunoEdgarGFlowHub/cvxpy", "max_forks_repo_head_hexsha": "43270fcc8af8fc4742f1b3519800b0074f2e6693", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.296728972, "max_line_length": 89, "alphanum_fraction": 0.5365488112, "include": true, "reason": "import numpy,import scipy,import cvxpy,from cvxpy", "num_tokens": 3427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.17212552245669233}}
{"text": "\"\"\"This module defines the fundamental interfaces and functions related to causal graphs in graphical causal models.\n\nClasses and functions in this module should be considered experimental, meaning there might be breaking API changes in\nthe future.\n\"\"\"\n\nfrom abc import abstractmethod, ABC\nfrom typing import Any, List\n\nimport networkx as nx\nimport numpy as np\nfrom networkx.algorithms.dag import has_cycle\nfrom typing_extensions import Protocol\n\n# This constant is used as key when storing/accessing models as causal mechanisms in graph node attributes\nCAUSAL_MECHANISM = 'causal_mechanism'\n\n# This constant is used as key when storing the parents of a node during fitting. It's used for validation purposes\n# afterwards.\nPARENTS_DURING_FIT = 'parents_during_fit'\n\n\nclass HasNodes(Protocol):\n    \"\"\"This protocol defines a trait for classes having nodes.\"\"\"\n    @property\n    @abstractmethod\n    def nodes(self):\n        \"\"\":returns Dict[Any, Dict[Any, Any]]\"\"\"\n        raise NotImplementedError\n\n\nclass HasEdges(Protocol):\n    \"\"\"This protocol defines a trait for classes having edges.\"\"\"\n    @property\n    @abstractmethod\n    def edges(self):\n        \"\"\":returns a Dict[Tuple[Any, Any], Dict[Any, Any]]\"\"\"\n        raise NotImplementedError\n\n\nclass DirectedGraph(HasNodes, HasEdges, Protocol):\n    \"\"\"A protocol representing a directed graph as needed by graphical causal models.\n\n    This protocol specifically defines a subset of the networkx.DiGraph class, which make that class automatically\n    compatible with DirectedGraph. While in most cases a networkx.DiGraph is the class of choice when constructing\n    a causal graph, anyone can choose to provide their own implementation of the DirectGraph interface.\n    \"\"\"\n    @abstractmethod\n    def predecessors(self, node):\n        raise NotImplementedError\n\n\nclass StochasticModel(ABC):\n    \"\"\"A stochastic model represents a model used for causal mechanisms for root nodes in a graphical causal model.\"\"\"\n\n    @abstractmethod\n    def fit(self, X: np.ndarray) -> None:\n        \"\"\"Fits the model according to the data.\"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def draw_samples(self, num_samples: int) -> np.ndarray:\n        \"\"\"Draws samples for the fitted model.\"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def clone(self):\n        raise NotImplementedError\n\n\nclass ConditionalStochasticModel(ABC):\n    \"\"\"A conditional stochastic model represents a model used for causal mechanisms for non-root nodes in a graphical\n    causal model.\"\"\"\n\n    @abstractmethod\n    def fit(self, X: np.ndarray, Y: np.ndarray) -> None:\n        \"\"\"Fits the model according to the data.\"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def draw_samples(self, parent_samples: np.ndarray) -> np.ndarray:\n        \"\"\"Draws samples for the fitted model.\"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def clone(self):\n        raise NotImplementedError\n\n\nclass FunctionalCausalModel(ConditionalStochasticModel):\n    \"\"\"Represents a Functional Causal Model (FCM), a specific type of conditional stochastic model, that is defined\n    as:\n        Y := f(X, N), N: Noise\n    \"\"\"\n\n    def draw_samples(self, parent_samples: np.ndarray) -> np.ndarray:\n        return self.evaluate(parent_samples, self.draw_noise_samples(parent_samples.shape[0]))\n\n    @abstractmethod\n    def draw_noise_samples(self, num_samples: int) -> np.ndarray:\n        raise NotImplementedError\n\n    @abstractmethod\n    def evaluate(self, parent_samples: np.ndarray, noise_samples: np.ndarray) -> np.ndarray:\n        raise NotImplementedError\n\n\nclass InvertibleFunctionalCausalModel(FunctionalCausalModel, ABC):\n    @abstractmethod\n    def estimate_noise(self, target_samples: np.ndarray, parent_samples: np.ndarray) -> np.ndarray:\n        raise NotImplementedError\n\n\ndef is_root_node(causal_graph: DirectedGraph, node: Any) -> bool:\n    return list(causal_graph.predecessors(node)) == []\n\n\ndef get_ordered_predecessors(causal_graph: DirectedGraph, node: Any) -> List[Any]:\n    \"\"\"This function returns predecessors of a node in a well-defined order.\n\n    This is necessary, because we select subsets of columns in Dataframes by using a node's parents, and these parents\n    might not be returned in a reliable order.\n    \"\"\"\n    return sorted(causal_graph.predecessors(node))\n\n\ndef node_connected_subgraph_view(g: DirectedGraph, node: Any) -> Any:\n    \"\"\"Returns a view of the provided graph g that contains only nodes connected to the node passed in\"\"\"\n    # can't use nx.node_connected_component, because it doesn't work with DiGraphs.\n    # Hence a manual loop:\n    return nx.induced_subgraph(g, [n for n in g.nodes if nx.has_path(g, n, node)])\n\n\ndef clone_causal_models(source: HasNodes, destination: HasNodes):\n    for node in destination.nodes:\n        if CAUSAL_MECHANISM in source.nodes[node]:\n            destination.nodes[node][CAUSAL_MECHANISM] = source.nodes[node][CAUSAL_MECHANISM].clone()\n\n\ndef validate_acyclic(causal_graph: DirectedGraph) -> None:\n    if has_cycle(causal_graph):\n        raise RuntimeError('The graph contains a cycle, but an acyclic graph is expected!')\n\n\ndef validate_causal_dag(causal_graph: DirectedGraph) -> None:\n    validate_acyclic(causal_graph)\n    validate_causal_graph(causal_graph)\n\n\ndef validate_causal_graph(causal_graph: DirectedGraph) -> None:\n    for node in causal_graph.nodes:\n        validate_node(causal_graph, node)\n\n\ndef validate_node(causal_graph: DirectedGraph, node: Any) -> None:\n    validate_causal_model_assignment(causal_graph, node)\n    validate_local_structure(causal_graph, node)\n\n\ndef validate_causal_model_assignment(causal_graph: DirectedGraph, target_node: Any) -> None:\n    validate_node_has_causal_model(causal_graph, target_node)\n\n    causal_model = causal_graph.nodes[target_node][CAUSAL_MECHANISM]\n\n    if is_root_node(causal_graph, target_node):\n        if not isinstance(causal_model, StochasticModel):\n            raise RuntimeError('Node %s is a root node and, thus, requires a StochasticModel, '\n                               'but a %s was found!' % (target_node, causal_model))\n    elif not isinstance(causal_model, ConditionalStochasticModel):\n        raise RuntimeError('Node %s has parents and, thus, requires a ConditionalStochasticModel, '\n                           'but a %s was found!' % (target_node, causal_model))\n\n\ndef validate_local_structure(causal_graph: DirectedGraph, node: Any) -> None:\n    if PARENTS_DURING_FIT not in causal_graph.nodes[node] \\\n            or causal_graph.nodes[node][PARENTS_DURING_FIT] \\\n            != get_ordered_predecessors(causal_graph, node):\n        raise RuntimeError('The causal mechanism of node %s is not fitted to the graphical structure! Fit all'\n                           'causal models in the graph first. If the mechanism is already fitted based on the causal'\n                           'parents, consider to update the persisted parents for that node manually.' % node)\n\n\ndef validate_node_has_causal_model(causal_graph: HasNodes, node: Any) -> None:\n    validate_node_in_graph(causal_graph, node)\n\n    if CAUSAL_MECHANISM not in causal_graph.nodes[node]:\n        raise ValueError(\"Node %s has no assigned causal mechanism!\" % node)\n\n\ndef validate_node_in_graph(causal_graph: HasNodes, node: Any) -> None:\n    if node not in causal_graph.nodes:\n        raise ValueError(\"Node %s can not be found in the given graph!\" % node)\n", "meta": {"hexsha": "974b291ae1dddd30b33b3a5def73180c0f5d454a", "size": 7427, "ext": "py", "lang": "Python", "max_stars_repo_path": "dowhy/gcm/graph.py", "max_stars_repo_name": "Microsoft/dowhy", "max_stars_repo_head_hexsha": "b84e257142df91e4ed792dcf6eee159f446ffef9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 840, "max_stars_repo_stars_event_min_datetime": "2018-06-25T22:31:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-06T13:45:17.000Z", "max_issues_repo_path": "dowhy/gcm/graph.py", "max_issues_repo_name": "Microsoft/dowhy", "max_issues_repo_head_hexsha": "b84e257142df91e4ed792dcf6eee159f446ffef9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 51, "max_issues_repo_issues_event_min_datetime": "2018-07-05T09:31:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-03T15:37:10.000Z", "max_forks_repo_path": "dowhy/gcm/graph.py", "max_forks_repo_name": "Microsoft/dowhy", "max_forks_repo_head_hexsha": "b84e257142df91e4ed792dcf6eee159f446ffef9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 106, "max_forks_repo_forks_event_min_datetime": "2018-06-28T12:35:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-06T16:16:32.000Z", "avg_line_length": 38.481865285, "max_line_length": 118, "alphanum_fraction": 0.7262690184, "include": true, "reason": "import numpy,import networkx,from networkx", "num_tokens": 1595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.17212552245669233}}
{"text": "import torch\nimport numpy as np\nimport redner\nimport pyredner\nimport time\nimport skimage.io\n\n# There is a bias-variance trade off in the backward pass.\n# If the forward pass and the backward pass are correlated\n# the gradients are biased for L2 loss.\n# (E[d/dx(f(x) - y)^2] = E[(f(x) - y) d/dx f(x)])\n#                      = E[f(x) - y] E[d/dx f(x)]\n# The last equation only holds when f(x) and d/dx f(x) are independent.\n# It is usually better to use the unbiased one, but we left it as an option here\nuse_correlated_random_number = False\ndef set_use_correlated_random_number(v):\n    global use_correlated_random_number\n    use_correlated_random_number = v\n\ndef get_use_correlated_random_number():\n    global use_correlated_random_number\n    return use_correlated_random_number\n\nprint_timing = True\n\nclass RenderFunction(torch.autograd.Function):\n    \"\"\"\n        The PyTorch interface of Redner.\n    \"\"\"\n\n    @staticmethod\n    def serialize_scene(scene,\n                        num_samples,\n                        max_bounces,\n                        channels = [redner.channels.radiance],\n                        sampler_type = redner.SamplerType.independent,\n                        use_primary_edge_sampling = True,\n                        use_secondary_edge_sampling = True):\n        \"\"\"\n            Given a PyRedner scene & rendering options, convert them to a linear list of argument,\n            so that we can use it in PyTorch.\n\n            Keyword arguments:\n            scene -- A pyredner.Scene\n            num_samples -- Number of samples per pixel for forward and backward passes,\n                           can be an integer or a tuple of 2 integers.\n            max_bounces -- Number of bounces for global illumination, 1 means direct lighting only.\n            channels -- A list of channels that should present in the output image.\n                        Following channels are supported:\n                            redner.channels.radiance,\n                            redner.channels.alpha,\n                            redner.channels.depth,\n                            redner.channels.position,\n                            redner.channels.geometry_normal,\n                            redner.channels.shading_normal,\n                            redner.channels.uv,\n                            redner.channels.diffuse_reflectance,\n                            redner.channels.specular_reflectance,\n                            redner.channels.roughness,\n                            redner.channels.shape_id,\n                            redner.channels.material_id\n                        All channels, except for shape id and material id, are differentiable.\n            sampler_type -- Which sampling pattern to use.\n                            See Chapter 7 of the PBRT book for an explanation of the difference between\n                            different samplers.\n                            http://www.pbr-book.org/3ed-2018/Sampling_and_Reconstruction.html\n                            Following samplers are supported:\n                                redner.SamplerType.independent\n                                redner.SamplerType.sobol\n            use_primary_edge_sampling -- A boolean\n            use_secondary_edge_sampling -- A boolean\n        \"\"\"\n        cam = scene.camera\n        num_shapes = len(scene.shapes)\n        num_materials = len(scene.materials)\n        num_lights = len(scene.area_lights)\n        for light_id, light in enumerate(scene.area_lights):\n            scene.shapes[light.shape_id].light_id = light_id\n        args = []\n        args.append(num_shapes)\n        args.append(num_materials)\n        args.append(num_lights)\n        assert(torch.isfinite(cam.position).all())\n        assert(torch.isfinite(cam.look_at).all())\n        assert(torch.isfinite(cam.up).all())\n        assert(torch.isfinite(cam.ndc_to_cam).all())\n        assert(torch.isfinite(cam.cam_to_ndc).all())\n        args.append(cam.position)\n        args.append(cam.look_at)\n        args.append(cam.up)\n        args.append(cam.ndc_to_cam)\n        args.append(cam.cam_to_ndc)\n        args.append(cam.clip_near)\n        args.append(cam.resolution)\n        args.append(cam.camera_type)\n        for shape in scene.shapes:\n            assert(torch.isfinite(shape.vertices).all())\n            if (shape.uvs is not None):\n                assert(torch.isfinite(shape.uvs).all())\n            if (shape.normals is not None):\n                assert(torch.isfinite(shape.normals).all())\n            args.append(shape.vertices)\n            args.append(shape.indices)\n            args.append(shape.uvs)\n            args.append(shape.normals)\n            args.append(shape.uv_indices)\n            args.append(shape.normal_indices)\n            args.append(shape.material_id)\n            args.append(shape.light_id)\n        for material in scene.materials:\n            assert(torch.isfinite(material.diffuse_reflectance.mipmap).all())\n            assert(torch.isfinite(material.diffuse_reflectance.uv_scale).all())\n            assert(torch.isfinite(material.specular_reflectance.mipmap).all())\n            assert(torch.isfinite(material.specular_reflectance.uv_scale).all())\n            assert(torch.isfinite(material.roughness.mipmap).all())\n            assert(torch.isfinite(material.roughness.uv_scale).all())\n            args.append(material.diffuse_reflectance.mipmap)\n            args.append(material.diffuse_reflectance.uv_scale)\n            args.append(material.specular_reflectance.mipmap)\n            args.append(material.specular_reflectance.uv_scale)\n            args.append(material.roughness.mipmap)\n            args.append(material.roughness.uv_scale)\n            if material.normal_map is not None:\n                assert(torch.isfinite(material.normal_map.mipmap).all())\n                assert(torch.isfinite(material.normal_map.uv_scale).all())\n                args.append(material.normal_map.mipmap)\n                args.append(material.normal_map.uv_scale)\n            else:\n                args.append(None)\n                args.append(None)\n            args.append(material.two_sided)\n        for light in scene.area_lights:\n            args.append(light.shape_id)\n            args.append(light.intensity)\n            args.append(light.two_sided)\n        if scene.envmap is not None:\n            assert(torch.isfinite(scene.envmap.values.mipmap).all())\n            assert(torch.isfinite(scene.envmap.values.uv_scale).all())\n            assert(torch.isfinite(scene.envmap.env_to_world).all())\n            assert(torch.isfinite(scene.envmap.world_to_env).all())\n            assert(torch.isfinite(scene.envmap.sample_cdf_ys).all())\n            assert(torch.isfinite(scene.envmap.sample_cdf_xs).all())\n            args.append(scene.envmap.values.mipmap)\n            args.append(scene.envmap.values.uv_scale)\n            args.append(scene.envmap.env_to_world)\n            args.append(scene.envmap.world_to_env)\n            args.append(scene.envmap.sample_cdf_ys)\n            args.append(scene.envmap.sample_cdf_xs)\n            args.append(scene.envmap.pdf_norm)\n        else:\n            args.append(None)\n            args.append(None)\n            args.append(None)\n            args.append(None)\n            args.append(None)\n            args.append(None)\n            args.append(None)\n        args.append(num_samples)\n        args.append(max_bounces)\n        args.append(channels)\n        args.append(sampler_type)\n        args.append(use_primary_edge_sampling)\n        args.append(use_secondary_edge_sampling)\n\n        return args\n    \n    @staticmethod\n    def forward(ctx,\n                seed,\n                *args):\n        \"\"\"\n            Forward rendering pass: given a scene and output an image.\n        \"\"\"\n        # Unpack arguments\n        current_index = 0\n        num_shapes = args[current_index]\n        current_index += 1\n        num_materials = args[current_index]\n        current_index += 1\n        num_lights = args[current_index]\n        current_index += 1\n        cam_position = args[current_index]\n        current_index += 1\n        cam_look_at = args[current_index]\n        current_index += 1\n        cam_up = args[current_index]\n        current_index += 1\n        ndc_to_cam = args[current_index]\n        current_index += 1\n        cam_to_ndc = args[current_index]\n        current_index += 1\n        clip_near = args[current_index]\n        current_index += 1\n        resolution = args[current_index]\n        current_index += 1\n        camera_type = args[current_index]\n        current_index += 1\n        camera = redner.Camera(resolution[1],\n                               resolution[0],\n                               redner.float_ptr(cam_position.data_ptr()),\n                               redner.float_ptr(cam_look_at.data_ptr()),\n                               redner.float_ptr(cam_up.data_ptr()),\n                               redner.float_ptr(ndc_to_cam.data_ptr()),\n                               redner.float_ptr(cam_to_ndc.data_ptr()),\n                               clip_near,\n                               camera_type)\n        shapes = []\n        for i in range(num_shapes):\n            vertices = args[current_index]\n            current_index += 1\n            indices = args[current_index]\n            current_index += 1\n            uvs = args[current_index]\n            current_index += 1\n            normals = args[current_index]\n            current_index += 1\n            uv_indices = args[current_index]\n            current_index += 1\n            normal_indices = args[current_index]\n            current_index += 1\n            material_id = args[current_index]\n            current_index += 1\n            light_id = args[current_index]\n            current_index += 1\n            assert(vertices.is_contiguous())\n            assert(indices.is_contiguous())\n            if uvs is not None:\n                assert(uvs.is_contiguous())\n            if normals is not None:\n                assert(normals.is_contiguous())\n            if uv_indices is not None:\n                assert(uv_indices.is_contiguous())\n            if normal_indices is not None:\n                assert(normal_indices.is_contiguous())\n            shapes.append(redner.Shape(\\\n                redner.float_ptr(vertices.data_ptr()),\n                redner.int_ptr(indices.data_ptr()),\n                redner.float_ptr(uvs.data_ptr() if uvs is not None else 0),\n                redner.float_ptr(normals.data_ptr() if normals is not None else 0),\n                redner.int_ptr(uv_indices.data_ptr() if uv_indices is not None else 0),\n                redner.int_ptr(normal_indices.data_ptr() if normal_indices is not None else 0),\n                int(vertices.shape[0]),\n                int(uvs.shape[0]) if uvs is not None else 0,\n                int(normals.shape[0]) if normals is not None else 0,\n                int(indices.shape[0]),\n                material_id,\n                light_id))\n        materials = []\n        for i in range(num_materials):\n            diffuse_reflectance = args[current_index]\n            current_index += 1\n            diffuse_uv_scale = args[current_index]\n            current_index += 1\n            specular_reflectance = args[current_index]\n            current_index += 1\n            specular_uv_scale = args[current_index]\n            current_index += 1\n            roughness = args[current_index]\n            current_index += 1\n            roughness_uv_scale = args[current_index]\n            current_index += 1\n            normal_map = args[current_index]\n            current_index += 1\n            normal_map_uv_scale = args[current_index]\n            current_index += 1\n            two_sided = args[current_index]\n            current_index += 1\n            assert(diffuse_reflectance.is_contiguous())\n            if diffuse_reflectance.dim() == 1:\n                diffuse_reflectance = redner.Texture3(\\\n                    redner.float_ptr(diffuse_reflectance.data_ptr()), 0, 0, 0,\n                    redner.float_ptr(diffuse_uv_scale.data_ptr()))\n            else:\n                diffuse_reflectance = redner.Texture3(\\\n                    redner.float_ptr(diffuse_reflectance.data_ptr()),\n                    int(diffuse_reflectance.shape[2]), # width\n                    int(diffuse_reflectance.shape[1]), # height\n                    int(diffuse_reflectance.shape[0]), # num levels\n                    redner.float_ptr(diffuse_uv_scale.data_ptr()))\n            assert(specular_reflectance.is_contiguous())\n            if specular_reflectance.dim() == 1:\n                specular_reflectance = redner.Texture3(\\\n                    redner.float_ptr(specular_reflectance.data_ptr()), 0, 0, 0,\n                    redner.float_ptr(specular_uv_scale.data_ptr()))\n            else:\n                specular_reflectance = redner.Texture3(\\\n                    redner.float_ptr(specular_reflectance.data_ptr()),\n                    int(specular_reflectance.shape[2]), # width\n                    int(specular_reflectance.shape[1]), # height\n                    int(specular_reflectance.shape[0]), # num levels\n                    redner.float_ptr(specular_uv_scale.data_ptr()))\n            assert(roughness.is_contiguous())\n            if roughness.dim() == 1:\n                roughness = redner.Texture1(\\\n                    redner.float_ptr(roughness.data_ptr()), 0, 0, 0,\n                    redner.float_ptr(roughness_uv_scale.data_ptr()))\n            else:\n                assert(roughness.dim() == 4)\n                roughness = redner.Texture1(\\\n                    redner.float_ptr(roughness.data_ptr()),\n                    int(roughness.shape[2]), # width\n                    int(roughness.shape[1]), # height\n                    int(roughness.shape[0]), # num levels\n                    redner.float_ptr(roughness_uv_scale.data_ptr()))\n            if normal_map is not None:\n                assert(normal_map.dim() == 4)\n                normal_map = redner.Texture3(\\\n                    redner.float_ptr(normal_map.data_ptr()),\n                    int(normal_map.shape[2]), # width\n                    int(normal_map.shape[1]), # height\n                    int(normal_map.shape[0]), # num levels\n                    redner.float_ptr(normal_map_uv_scale.data_ptr()))\n            else:\n                normal_map = redner.Texture3(\\\n                    redner.float_ptr(0), 0, 0, 0, redner.float_ptr(0))\n            materials.append(redner.Material(\\\n                diffuse_reflectance,\n                specular_reflectance,\n                roughness,\n                normal_map,\n                two_sided))\n\n        area_lights = []\n        for i in range(num_lights):\n            shape_id = args[current_index]\n            current_index += 1\n            intensity = args[current_index]\n            current_index += 1\n            two_sided = args[current_index]\n            current_index += 1\n\n            area_lights.append(redner.AreaLight(\\\n                shape_id,\n                redner.float_ptr(intensity.data_ptr()),\n                two_sided))\n\n        envmap = None\n        if args[current_index] is not None:\n            values = args[current_index]\n            current_index += 1\n            envmap_uv_scale = args[current_index]\n            current_index += 1\n            env_to_world = args[current_index]\n            current_index += 1\n            world_to_env = args[current_index]\n            current_index += 1\n            sample_cdf_ys = args[current_index]\n            current_index += 1\n            sample_cdf_xs = args[current_index]\n            current_index += 1\n            pdf_norm = args[current_index]\n            current_index += 1\n            values = redner.Texture3(\\\n                redner.float_ptr(values.data_ptr()),\n                int(values.shape[2]), # width\n                int(values.shape[1]), # height\n                int(values.shape[0]), # num levels\n                redner.float_ptr(envmap_uv_scale.data_ptr()))\n            envmap = redner.EnvironmentMap(\\\n                values,\n                redner.float_ptr(env_to_world.data_ptr()),\n                redner.float_ptr(world_to_env.data_ptr()),\n                redner.float_ptr(sample_cdf_ys.data_ptr()),\n                redner.float_ptr(sample_cdf_xs.data_ptr()),\n                pdf_norm)\n        else:\n            current_index += 7\n\n        # Options\n        num_samples = args[current_index]\n        current_index += 1\n        max_bounces = args[current_index]\n        current_index += 1\n        channels = args[current_index]\n        current_index += 1\n        sampler_type = args[current_index]\n        current_index += 1\n        use_primary_edge_sampling = args[current_index]\n        current_index += 1\n        use_secondary_edge_sampling = args[current_index]\n        current_index += 1\n\n        start = time.time()\n        scene = redner.Scene(camera,\n                             shapes,\n                             materials,\n                             area_lights,\n                             envmap,\n                             pyredner.get_use_gpu(),\n                             pyredner.get_device().index if pyredner.get_device().index is not None else -1,\n                             use_primary_edge_sampling,\n                             use_secondary_edge_sampling)\n        time_elapsed = time.time() - start\n        if print_timing:\n            print('Scene construction, time: %.5f s' % time_elapsed)\n\n        # check that num_samples is a tuple\n        if isinstance(num_samples, int):\n            num_samples = (num_samples, num_samples)\n\n        options = redner.RenderOptions(seed, num_samples[0], max_bounces, channels, sampler_type)\n        num_channels = redner.compute_num_channels(channels)\n        rendered_image = torch.zeros(resolution[0], resolution[1], num_channels,\n            device = pyredner.get_device())\n        start = time.time()\n        redner.render(scene,\n                      options,\n                      redner.float_ptr(rendered_image.data_ptr()),\n                      redner.float_ptr(0),\n                      None,\n                      redner.float_ptr(0))\n        time_elapsed = time.time() - start\n        if print_timing:\n            print('Forward pass, time: %.5f s' % time_elapsed)\n\n        # # For debugging\n        # debug_img = torch.zeros(256, 256, 3)\n        # redner.render(scene,\n        #               options,\n        #               redner.float_ptr(rendered_image.data_ptr()),\n        #               redner.float_ptr(0),\n        #               None,\n        #               redner.float_ptr(debug_img.data_ptr()))\n        # pyredner.imwrite(debug_img, 'debug.exr')\n        # exit()\n\n        ctx.shapes = shapes\n        ctx.materials = materials\n        ctx.area_lights = area_lights\n        ctx.envmap = envmap\n        ctx.scene = scene\n        ctx.options = options\n        ctx.num_samples = num_samples\n        return rendered_image\n\n    @staticmethod\n    def backward(ctx,\n                 grad_img):\n        if not grad_img.is_contiguous():\n            grad_img = grad_img.contiguous()\n        scene = ctx.scene\n        options = ctx.options\n\n        d_cam_position = torch.zeros(3, device = pyredner.get_device())\n        d_cam_look = torch.zeros(3, device = pyredner.get_device())\n        d_cam_up = torch.zeros(3, device = pyredner.get_device())\n        d_ndc_to_cam = torch.zeros(3, 3, device = pyredner.get_device())\n        d_cam_to_ndc = torch.zeros(3, 3, device = pyredner.get_device())\n        d_camera = redner.DCamera(redner.float_ptr(d_cam_position.data_ptr()),\n                                  redner.float_ptr(d_cam_look.data_ptr()),\n                                  redner.float_ptr(d_cam_up.data_ptr()),\n                                  redner.float_ptr(d_ndc_to_cam.data_ptr()),\n                                  redner.float_ptr(d_cam_to_ndc.data_ptr()))\n        d_vertices_list = []\n        d_uvs_list = []\n        d_normals_list = []\n        d_shapes = []\n        for shape in ctx.shapes:\n            num_vertices = shape.num_vertices\n            num_uv_vertices = shape.num_uv_vertices\n            d_vertices = torch.zeros(num_vertices, 3,\n                device = pyredner.get_device())\n            d_uvs = torch.zeros(num_uv_vertices, 2,\n                device = pyredner.get_device()) if shape.has_uvs() else None\n            d_normals = torch.zeros(num_vertices, 3,\n                device = pyredner.get_device()) if shape.has_normals() else None\n            d_vertices_list.append(d_vertices)\n            d_uvs_list.append(d_uvs)\n            d_normals_list.append(d_normals)\n            d_shapes.append(redner.DShape(\\\n                redner.float_ptr(d_vertices.data_ptr()),\n                redner.float_ptr(d_uvs.data_ptr() if d_uvs is not None else 0),\n                redner.float_ptr(d_normals.data_ptr() if d_normals is not None else 0)))\n\n        d_diffuse_list = []\n        d_diffuse_uv_scale_list = []\n        d_specular_list = []\n        d_specular_uv_scale_list = []\n        d_roughness_list = []\n        d_roughness_uv_scale_list = []\n        d_normal_map_list = []\n        d_normal_map_uv_scale_list = []\n        d_materials = []\n        for material in ctx.materials:\n            diffuse_size = material.get_diffuse_size()\n            specular_size = material.get_specular_size()\n            roughness_size = material.get_roughness_size()\n            normal_map_size = material.get_normal_map_size()\n            if diffuse_size[0] == 0:\n                d_diffuse = torch.zeros(3, device = pyredner.get_device())\n            else:\n                d_diffuse = torch.zeros(diffuse_size[2],\n                                        diffuse_size[1],\n                                        diffuse_size[0],\n                                        3, device = pyredner.get_device())\n            if specular_size[0] == 0:\n                d_specular = torch.zeros(3, device = pyredner.get_device())\n            else:\n                d_specular = torch.zeros(specular_size[2],\n                                         specular_size[1],\n                                         specular_size[0],\n                                         3, device = pyredner.get_device())\n            if roughness_size[0] == 0:\n                d_roughness = torch.zeros(1, device = pyredner.get_device())\n            else:\n                d_roughness = torch.zeros(roughness_size[2],\n                                          roughness_size[1],\n                                          roughness_size[0],\n                                          1, device = pyredner.get_device())\n            if normal_map_size[0] == 0:\n                d_normal_map = None\n            else:\n                d_normal_map = torch.zeros(normal_map_size[2],\n                                           normal_map_size[1],\n                                           normal_map_size[0],\n                                           3, device = pyredner.get_device())\n            d_diffuse_list.append(d_diffuse)\n            d_specular_list.append(d_specular)\n            d_roughness_list.append(d_roughness)\n            d_normal_map_list.append(d_normal_map)\n            d_diffuse_uv_scale = torch.zeros(2, device = pyredner.get_device())\n            d_specular_uv_scale = torch.zeros(2, device = pyredner.get_device())\n            d_roughness_uv_scale = torch.zeros(2, device = pyredner.get_device())\n            d_diffuse_uv_scale_list.append(d_diffuse_uv_scale)\n            d_specular_uv_scale_list.append(d_specular_uv_scale)\n            d_roughness_uv_scale_list.append(d_roughness_uv_scale)\n            if d_normal_map is None:\n                d_normal_map_uv_scale = None\n            else:\n                d_normal_map_uv_scale = torch.zeros(2, device = pyredner.get_device())\n            d_normal_map_uv_scale_list.append(d_normal_map_uv_scale)\n            d_diffuse_tex = redner.Texture3(\\\n                redner.float_ptr(d_diffuse.data_ptr()),\n                diffuse_size[0], diffuse_size[1], diffuse_size[2],\n                redner.float_ptr(d_diffuse_uv_scale.data_ptr()))\n            d_specular_tex = redner.Texture3(\\\n                redner.float_ptr(d_specular.data_ptr()),\n                specular_size[0], specular_size[1], specular_size[2],\n                redner.float_ptr(d_specular_uv_scale.data_ptr()))\n            d_roughness_tex = redner.Texture1(\\\n                redner.float_ptr(d_roughness.data_ptr()),\n                roughness_size[0], roughness_size[1], roughness_size[2],\n                redner.float_ptr(d_roughness_uv_scale.data_ptr()))\n            if d_normal_map is None:\n                d_normal_map = redner.Texture3(\\\n                    redner.float_ptr(0), 0, 0, 0, redner.float_ptr(0))\n            else:\n                d_normal_map = redner.Texture3(\\\n                    redner.float_ptr(d_normal_map.data_ptr()),\n                    normal_map_size[0], normal_map_size[1], normal_map_size[2],\n                    redner.float_ptr(d_normal_map_uv_scale.data_ptr()))\n            d_materials.append(redner.DMaterial(\\\n                d_diffuse_tex, d_specular_tex, d_roughness_tex, d_normal_map))\n\n        d_intensity_list = []\n        d_area_lights = []\n        for light in ctx.area_lights:\n            d_intensity = torch.zeros(3, device = pyredner.get_device())\n            d_intensity_list.append(d_intensity)\n            d_area_lights.append(\\\n                redner.DAreaLight(redner.float_ptr(d_intensity.data_ptr())))\n\n        d_envmap = None\n        if ctx.envmap is not None:\n            envmap = ctx.envmap\n            size = envmap.get_size()\n            d_envmap_values = \\\n                torch.zeros(size[2],\n                            size[1],\n                            size[0],\n                            3,\n                            device = pyredner.get_device())\n            d_envmap_uv_scale = torch.zeros(2, device = pyredner.get_device())\n            d_envmap_tex = redner.Texture3(\\\n                redner.float_ptr(d_envmap_values.data_ptr()),\n                size[0], size[1], size[2],\n                redner.float_ptr(d_envmap_uv_scale.data_ptr()))\n            d_world_to_env = torch.zeros(4, 4, device = pyredner.get_device())\n            d_envmap = redner.DEnvironmentMap(\\\n                d_envmap_tex,\n                redner.float_ptr(d_world_to_env.data_ptr()))\n\n        d_scene = redner.DScene(d_camera,\n                                d_shapes,\n                                d_materials,\n                                d_area_lights,\n                                d_envmap,\n                                pyredner.get_use_gpu(),\n                                pyredner.get_device().index if pyredner.get_device().index is not None else -1)\n        if not get_use_correlated_random_number():\n            # Decouple the forward/backward random numbers by adding a big prime number\n            options.seed += 1000003\n\n        options.num_samples = ctx.num_samples[1]\n        start = time.time()\n        redner.render(scene, options,\n                      redner.float_ptr(0),\n                      redner.float_ptr(grad_img.data_ptr()),\n                      d_scene,\n                      redner.float_ptr(0))\n        time_elapsed = time.time() - start\n        if print_timing:\n            print('Backward pass, time: %.5f s' % time_elapsed)\n\n        # For debugging\n        # pyredner.imwrite(grad_img, 'grad_img.exr')\n        # grad_img = torch.ones(256, 256, 3, device = pyredner.get_device())\n        # debug_img = torch.zeros(256, 256, 3)\n        # start = time.time()\n        # redner.render(scene, options,\n        #               redner.float_ptr(0),\n        #               redner.float_ptr(grad_img.data_ptr()),\n        #               d_scene,\n        #               redner.float_ptr(debug_img.data_ptr()))\n        # time_elapsed = time.time() - start\n        # if print_timing:\n        #     print('Backward pass, time: %.5f s' % time_elapsed)\n        # debug_img = debug_img[:, :, 0]\n        # pyredner.imwrite(debug_img, 'debug.exr')\n        # pyredner.imwrite(-debug_img, 'debug_.exr')\n        # debug_img = debug_img.numpy()\n        # print(np.max(debug_img))\n        # print(np.unravel_index(np.argmax(debug_img), debug_img.shape))\n        # print(np.min(debug_img))\n        # print(np.unravel_index(np.argmin(debug_img), debug_img.shape))\n        # print(np.sum(debug_img) / 3)\n        # debug_max = 0.5\n        # debug_min = -0.5\n        # debug_img = np.clip((debug_img - debug_min) / (debug_max - debug_min), 0, 1)\n        # # debug_img = debug_img[:, :, 0]\n        # import matplotlib.cm as cm\n        # debug_img = cm.viridis(debug_img)\n        # skimage.io.imsave('debug.png', np.power(debug_img, 1/2.2))\n        # exit()\n\n        ret_list = []\n        ret_list.append(None) # seed\n        ret_list.append(None) # num_shapes\n        ret_list.append(None) # num_materials\n        ret_list.append(None) # num_lights\n        ret_list.append(d_cam_position.cpu())\n        ret_list.append(d_cam_look.cpu())\n        ret_list.append(d_cam_up.cpu())\n        ret_list.append(d_ndc_to_cam.cpu())\n        ret_list.append(d_cam_to_ndc.cpu())\n        ret_list.append(None) # clip near\n        ret_list.append(None) # resolution\n        ret_list.append(None) # camera_type\n\n        num_shapes = len(ctx.shapes)\n        for i in range(num_shapes):\n            ret_list.append(d_vertices_list[i])\n            ret_list.append(None) # indices\n            ret_list.append(d_uvs_list[i])\n            ret_list.append(d_normals_list[i])\n            ret_list.append(None) # uv_indices\n            ret_list.append(None) # normal_indices\n            ret_list.append(None) # material id\n            ret_list.append(None) # light id\n\n        num_materials = len(ctx.materials)\n        for i in range(num_materials):\n            ret_list.append(d_diffuse_list[i])\n            ret_list.append(d_diffuse_uv_scale_list[i])\n            ret_list.append(d_specular_list[i])\n            ret_list.append(d_specular_uv_scale_list[i])\n            ret_list.append(d_roughness_list[i])\n            ret_list.append(d_roughness_uv_scale_list[i])\n            ret_list.append(d_normal_map_list[i])\n            ret_list.append(d_normal_map_uv_scale_list[i])\n            ret_list.append(None) # two sided\n\n        num_area_lights = len(ctx.area_lights)\n        for i in range(num_area_lights):\n            ret_list.append(None) # shape id\n            ret_list.append(d_intensity_list[i].cpu())\n            ret_list.append(None) # two sided\n\n        if ctx.envmap is not None:\n            ret_list.append(d_envmap_values)\n            ret_list.append(d_envmap_uv_scale)\n            ret_list.append(None) # env_to_world\n            ret_list.append(d_world_to_env.cpu())\n            ret_list.append(None) # sample_cdf_ys\n            ret_list.append(None) # sample_cdf_xs\n            ret_list.append(None) # pdf_norm\n        else:\n            ret_list.append(None)\n            ret_list.append(None)\n            ret_list.append(None)\n            ret_list.append(None)\n            ret_list.append(None)\n            ret_list.append(None)\n            ret_list.append(None)\n        \n        ret_list.append(None) # num samples\n        ret_list.append(None) # num bounces\n        ret_list.append(None) # channels\n        ret_list.append(None) # sampler type\n        ret_list.append(None) # use_primary_edge_sampling\n        ret_list.append(None) # use_secondary_edge_sampling\n\n        return tuple(ret_list)\n", "meta": {"hexsha": "6ab89cedcbb5c956eb527a52fce847da851749a3", "size": 31440, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyredner/render_pytorch.py", "max_stars_repo_name": "saipraveenb25/redner", "max_stars_repo_head_hexsha": "628efadb5499959756c9ca5dc1e556d4b973940f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyredner/render_pytorch.py", "max_issues_repo_name": "saipraveenb25/redner", "max_issues_repo_head_hexsha": "628efadb5499959756c9ca5dc1e556d4b973940f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyredner/render_pytorch.py", "max_forks_repo_name": "saipraveenb25/redner", "max_forks_repo_head_hexsha": "628efadb5499959756c9ca5dc1e556d4b973940f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.6590909091, "max_line_length": 111, "alphanum_fraction": 0.5603371501, "include": true, "reason": "import numpy", "num_tokens": 6484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3415824860330003, "lm_q1q2_score": 0.1721255224566923}}
{"text": "\nmeld_NMR_script = '''#!/usr/bin/env python\n# encoding: utf-8\n\nimport numpy as np\nfrom meld.remd import ladder, adaptor, leader\nfrom meld import comm, vault\nfrom meld import system\nfrom meld import parse\nimport meld.system.montecarlo as mc\nfrom meld.system.restraints import LinearRamp,ConstantRamp\nfrom collections import namedtuple\nimport glob as glob\n\n\nN_REPLICAS = 30\nN_STEPS =10000\nBLOCK_SIZE = 100\n\n\nhydrophobes = 'AILMFPWV'\nhydrophobes_res = ['ALA','ILE','LEU','MET','PHE','PRO','TRP','VAL']\n\ndef gen_state_templates(index, templates):\n    n_templates = len(templates)\n    print((index,n_templates,index%n_templates))\n    a = system.ProteinMoleculeFromPdbFile(templates[index%n_templates])\n    #Note that it does not matter which forcefield we use here to build\n    #as that information is not passed on, it is used for all the same as\n    #in the setup part of the script\n    b = system.SystemBuilder(forcefield=\"ff14sbside\")\n    c = b.build_system_from_molecules([a])\n    pos = c._coordinates\n    c._box_vectors=np.array([0.,0.,0.])\n    vel = np.zeros_like(pos)\n    alpha = index / (N_REPLICAS - 1.0)\n    energy = 0 \n    return system.SystemState(pos, vel, alpha, energy,c._box_vectors)\n\n\ndef get_dist_restraints(filename, s, scaler):\n    dists = []\n    rest_group = []\n    lines = open(filename).read().splitlines()\n    lines = [line.strip() for line in lines]\n    for line in lines:\n        if not line:\n            dists.append(s.restraints.create_restraint_group(rest_group, 1))\n            rest_group = []\n        else:\n            cols = line.split()\n            i = int(cols[0])\n            name_i = cols[1]\n            j = int(cols[2])\n            name_j = cols[3]\n            dist = float(cols[4]) / 10.\n\n            rest = s.restraints.create_restraint('distance', scaler,LinearRamp(0,100,0,1),\n                                                  r1=0.0, r2=0.0, r3=dist, r4=dist+0.2, k=350,\n                                                  atom_1_res_index=i, atom_2_res_index=j,\n                                                  atom_1_name=name_i, atom_2_name=name_j)\n            rest_group.append(rest)\n    return dists\n\ndef get_torsion_restraints(filename, s, scaler):\n    torsion_rests = []\n    rotamer_group = []\n    for line in open(filename,'r'):\n        if not line:\n            torsion_rests.append(s.restraints.create_restraint_group(rotamer_group, 1))\n            rotamer_group = []\n        else:\n            (res1, at1, res2, at2, res3, at3, res4, at4, rotamer_min, rotamer_max) = line.split()\n            rotamer_max = float(rotamer_max)\n            rotamer_min = float(rotamer_min)\n            rotamer_avg = (rotamer_max+rotamer_min)/2.\n            rotamer_sd = rotamer_max - rotamer_min\n            rotamer_rest = s.restraints.create_restraint('torsion', scaler, LinearRamp(0,100,0,1),\n                                                 phi=rotamer_avg, delta_phi=rotamer_sd, k=2.5,\n                                                 atom_1_res_index=int(res1), atom_1_name=at1,\n                                                 atom_2_res_index=int(res2), atom_2_name=at2,\n                                                 atom_3_res_index=int(res3), atom_3_name=at3,\n                                                 atom_4_res_index=int(res4), atom_4_name=at4)\n            rotamer_group.append(rotamer_rest)\n    return torsion_rests\n\ndef setup_system():\n    #\n    # Start system from minimized structure(s) deposited in TEMPLATES directory\n    #\n\n    templates = glob.glob('TEMPLATES/*.pdb')\n    \n    #\n    # build the system with force field\n    #\n\n    p = system.ProteinMoleculeFromPdbFile(templates[0])\n    b = system.SystemBuilder(forcefield=\"ff14sbside\")\n    s = b.build_system_from_molecules([p])\n    n_res = s.residue_numbers[-1]\n\n    #\n    # Temperature ladder\n    #\n    s.temperature_scaler = system.GeometricTemperatureScaler(0, 0.4, 300., 500.)\n\n    #\n    # Scalers\n    #\n    distance_scaler = s.restraints.create_scaler('nonlinear', alpha_min=0.4, alpha_max=1.0, factor=4.0)\n    torsion_scaler = s.restraints.create_scaler('constant')\n\n    #\n    # Distance Restraints\n    #\n    for noe in glob.glob('noe_*.dat'):\n        NOESY = get_dist_restraints(noe,s,scaler=distance_scaler)\n        s.restraints.add_selectively_active_collection(NOESY, int( len(NOESY)*0.95 ) )\n\n    #\n    # Torsion Restraints\n    #\n    for rotamer in glob.glob('rotamer_*.dat'):\n        TALOS = get_torsion_restraints(rotamer, s, torsion_scaler)\n        s.restraints.add_selectively_active_collection(TALOS, int( len(TALOS) * 0.95) )\n\n\n    #\n    # setup mc minimizer moves\n    #\n    movers= []\n    n_atoms = s.n_atoms\n    for i in range(1, n_res +1):\n        n=s.index_of_atom(i, 'N') -1\n        ca = s.index_of_atom(i, 'CA') -1\n        c= s.index_of_atom(i, 'C') -1\n        mover= mc.DoubleTorsionMover(n, ca, list(range(ca,n_atoms)), \n                                     ca, c, list(range(c, n_atoms)))\n\n        movers.append((mover,1))\n    sched= mc.MonteCarloScheduler(movers, n_res *60)\n \n    #\n    # create the simulation options\n    #\n    options = system.RunOptions()\n    options.implicit_solvent_model = 'gbNeck2'\n    options.use_big_timestep = False\n    options.use_bigger_timestep = True\n    options.cutoff = 1.8\n\n    options.use_amap = False\n    options.amap_alpha_bias = 1.0\n    options.amap_beta_bias = 1.0\n    options.timesteps = 11111\n    options.minimize_steps = 20000\n\n    #\n    # MC minimizer?\n    #\n    options.min_mc = None\n    options.run_mc = None\n    #options.min_mc = sched\n\n    #\n    # Handle how to store the data\n    #\n    store = vault.DataStore(s.n_atoms, N_REPLICAS, s.get_pdb_writer(), block_size=BLOCK_SIZE)\n    store.initialize(mode='w')\n    store.save_system(s)\n    store.save_run_options(options)\n\n    #\n    # Adaptation policy and REMD protocol\n    #\n    l = ladder.NearestNeighborLadder(n_trials=100)\n    policy = adaptor.AdaptationPolicy(2.0, 50, 50)\n    a = adaptor.EqualAcceptanceAdaptor(n_replicas=N_REPLICAS, adaptation_policy=policy)\n\n    #\n    # create and store the remd_runner\n    #\n    remd_runner = leader.LeaderReplicaExchangeRunner(N_REPLICAS, max_steps=N_STEPS, ladder=l, adaptor=a)\n    store.save_remd_runner(remd_runner)\n\n    #\n    # create and store the communicator\n    #\n    c = comm.MPICommunicator(s.n_atoms, N_REPLICAS)\n    store.save_communicator(c)\n\n    #\n    # create and save the initial states\n    #\n    states = [gen_state_templates(i,templates) for i in range(N_REPLICAS)]\n    store.save_states(states, 0)\n\n    #\n    # save data_store\n    #\n    store.save_data_store()\n\n    return s.n_atoms\n\n\nsetup_system()\n'''\n\n", "meta": {"hexsha": "4dc6ae16e0f8776a1095cd613dcf968d8c486414", "size": 6596, "ext": "py", "lang": "Python", "max_stars_repo_path": "prepareMELD.py", "max_stars_repo_name": "alberto99/MELDNMRParser", "max_stars_repo_head_hexsha": "cabffff5dcb6fbc9ff01446367659d42ce236644", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prepareMELD.py", "max_issues_repo_name": "alberto99/MELDNMRParser", "max_issues_repo_head_hexsha": "cabffff5dcb6fbc9ff01446367659d42ce236644", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prepareMELD.py", "max_forks_repo_name": "alberto99/MELDNMRParser", "max_forks_repo_head_hexsha": "cabffff5dcb6fbc9ff01446367659d42ce236644", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4095238095, "max_line_length": 104, "alphanum_fraction": 0.6215888417, "include": true, "reason": "import numpy", "num_tokens": 1770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3415824860330003, "lm_q1q2_score": 0.1721255224566923}}
{"text": "# -*- coding: utf-8 -*-\n\nimport sys\nfrom collections import namedtuple\n\nimport numpy as np\n\nfrom .matrix import BLOSUM62\n\n\n__all__ = [\"AlignmentResult\", \"aligner\"]\n\n\nIS_PY2 = False\nif sys.version_info.major == 2:\n    IS_PY2 = True\n\n# Container for alignment result\nAlignmentResult = namedtuple(\n    'AlignmentResult',\n    ['seq1', 'seq2', 'start1', 'start2',\n     'end1', 'end2', 'n_gaps1', 'n_gaps2',\n     'n_mismatches', 'score'])\n\n\ndef aligner(seqj, seqi, method='global', gap_open=-7, gap_extend=-7,\n            gap_double=-7, matrix=BLOSUM62, max_hits=1):\n    '''Calculates the alignment of two sequences.\n\n    The supported 'methods' are:\n        * 'global' for a global Needleman-Wunsh algorithm\n        * 'local' for a local Smith-Waterman alignment\n        * 'global_cfe' for a global alignment with cost-free ends\n        * 'glocal' for an alignment which is 'global' only with respect to\n          the shorter sequence (also known as a 'semi-global' alignment)\n\n    Returns the aligned (sub)sequences as character arrays.\n\n    Gotoh, O. (1982). J. Mol. Biol. 162, 705-708.\n    Needleman, S. & Wunsch, C. (1970). J. Mol. Biol. 48(3), 443-53.\n    Smith, T.F. & Waterman M.S. (1981). J. Mol. Biol. 147, 195-197.\n\n    Arguments:\n\n        - seqj (``sequence``) First aligned iterable object of symbols.\n        - seqi (``sequence``) Second aligned iterable object of symbols.\n        - method (``str``) Type of alignment: 'global', 'global_cfe', 'local',\n          'glocal'.\n        - gap_open (``float``) The gap-opening cost.\n        - gap_extend (``float``) The cost of extending an open gap.\n        - gap_double (``float``) The gap-opening cost if a gap is already open\n          in the other sequence.\n        - matrix (``dict``) A score matrix dictionary.\n        - max_hits (``int``) The maximum number of results to return in\n          case multiple alignments with the same score are found. If set to 1,\n          a single ``AlignmentResult`` object is returned. If set to values\n          larger than 1, a list containing ``AlignmentResult`` objects are\n          returned. If set to `None`, all alignments with the maximum score\n          are returned.\n    '''\n    assert max_hits is None or max_hits > 0\n    NONE, LEFT, UP, DIAG = range(4)  # NONE is 0\n    GAP_CHAR = ord('-') if not IS_PY2 else '-'\n    max_j = len(seqj)\n    max_i = len(seqi)\n\n    if max_j > max_i:\n        flip = 1\n        seqi, seqj = seqj, seqi\n        max_i, max_j = max_j, max_i\n    else:\n        flip = 0\n\n    seqi = seqi.encode() if not isinstance(seqi, bytes) else seqi\n    seqj = seqj.encode() if not isinstance(seqj, bytes) else seqj\n\n    F = np.zeros((max_i + 1, max_j + 1), dtype=np.float32)\n    I = np.ndarray((max_i + 1, max_j + 1), dtype=np.float32)\n    I.fill(-np.inf)\n    J = np.ndarray((max_i + 1, max_j + 1), dtype=np.float32)\n    J.fill(-np.inf)\n    pointer = np.zeros((max_i + 1, max_j + 1), dtype=np.uint)  # NONE\n\n    if method == 'global':\n        pointer[0, 1:] = LEFT\n        pointer[1:, 0] = UP\n        F[0, 1:] = gap_open + gap_extend * \\\n            np.arange(0, max_j, dtype=np.float32)\n        F[1:, 0] = gap_open + gap_extend * \\\n            np.arange(0, max_i, dtype=np.float32)\n    elif method == 'global_cfe':\n        pointer[0, 1:] = LEFT\n        pointer[1:, 0] = UP\n    elif method == 'glocal':\n        pointer[0, 1:] = LEFT\n        F[0, 1:] = gap_open + gap_extend * \\\n            np.arange(0, max_j, dtype=np.float32)\n\n    for i in range(1, max_i + 1):\n        ci = seqi[i - 1:i]\n        for j in range(1, max_j + 1):\n            cj = seqj[j - 1:j]\n            # I\n            I[i, j] = max(\n                         F[i, j - 1] + gap_open,\n                         I[i, j - 1] + gap_extend,\n                         J[i, j - 1] + gap_double)\n            # J\n            J[i, j] = max(\n                         F[i - 1, j] + gap_open,\n                         J[i - 1, j] + gap_extend,\n                         I[i - 1, j] + gap_double)\n            # F\n            diag_score = F[i - 1, j - 1] + matrix[cj][ci]\n            left_score = I[i, j]\n            up_score = J[i, j]\n            max_score = max(diag_score, up_score, left_score)\n\n            F[i, j] = max(0, max_score) if method == 'local' else max_score\n\n            if method == 'local':\n                if F[i, j] == 0:\n                    pass  # point[i,j] = NONE\n                elif max_score == diag_score:\n                    pointer[i, j] = DIAG\n                elif max_score == up_score:\n                    pointer[i, j] = UP\n                elif max_score == left_score:\n                    pointer[i, j] = LEFT\n            elif method == 'glocal':\n                # In a semi-global alignment we want to consume as much as\n                # possible of the longer sequence.\n                if max_score == up_score:\n                    pointer[i, j] = UP\n                elif max_score == diag_score:\n                    pointer[i, j] = DIAG\n                elif max_score == left_score:\n                    pointer[i, j] = LEFT\n            else:\n                # global\n                if max_score == up_score:\n                    pointer[i, j] = UP\n                elif max_score == left_score:\n                    pointer[i, j] = LEFT\n                else:\n                    pointer[i, j] = DIAG\n\n    # container for traceback coordinates\n    ij_pairs = []\n    if method == 'local':\n        # max anywhere\n        maxv_indices = np.argwhere(F == F.max())[:max_hits]\n        for index in maxv_indices:\n            ij_pairs.append(index)\n    elif method == 'glocal':\n        # max in last col\n        max_score = F[:, -1].max()\n        maxi_indices = np.argwhere(F[:, -1] == F[:, -1].max())\\\n            .flatten()[:max_hits]\n        for i in maxi_indices:\n            ij_pairs.append((i, max_j))\n    elif method == 'global_cfe':\n        # from i,j to max(max(last row), max(last col)) for free\n        row_max = F[-1].max()\n        col_max = F[:, -1].max()\n        # expecting max to exist on either last column or last row\n        if row_max > col_max:\n            col_idces = np.argwhere(F[-1] == row_max).flatten()[:max_hits]\n            for cid in col_idces:\n                ij_pairs.append((i, cid))\n        elif row_max < col_max:\n            row_idces = np.argwhere(F[:, -1] == col_max).flatten()[:max_hits]\n            for rid in row_idces:\n                ij_pairs.append((rid, j))\n        # special case: max is on last row, last col\n        elif row_max == col_max == F[i, j]:\n            # check if max score also exist on other cells in last row\n            # or last col. we expect only one of the case.\n            col_idces = np.argwhere(F[-1] == row_max).flatten()\n            row_idces = np.argwhere(F[:, -1] == col_max).flatten()\n            ncol_idces = len(col_idces)\n            nrow_idces = len(row_idces)\n\n            # tiebreaker between row/col is whichever has more max scores\n            if ncol_idces > nrow_idces:\n                for cid in col_idces[:max_hits]:\n                    ij_pairs.append((i, cid))\n            elif ncol_idces < nrow_idces:\n                for rid in row_idces[:max_hits]:\n                    ij_pairs.append((rid, j))\n            elif ncol_idces == nrow_idces == 1:\n                ij_pairs.append((i, j))\n            else:\n                raise RuntimeError('Unexpected multiple maximum global_cfe'\n                                   ' scores.')\n        else:\n            raise RuntimeError('Unexpected global_cfe scenario.')\n    else:\n        # method must be global at this point\n        ij_pairs.append((i, j))\n\n    results = []\n    for i, j in ij_pairs:\n        align_j = []\n        align_i = []\n        score = F[i, j]\n        p = pointer[i, j]\n        # mimic Python's coord system\n        if method.startswith(\"global\"):\n            end_i, end_j = max_i, max_j\n        else:\n            end_i, end_j = i, j\n        n_gaps_i, n_gaps_j, n_mmatch = 0, 0, 0\n\n        # special case for global_cfe ~ one cell may contain multiple pointer\n        # directions\n        if method == 'global_cfe':\n            if i < max_i:\n                align_i.extend([c for c in seqi[i:][::-1]])\n                align_j.extend([GAP_CHAR] * (max_i - i))\n                n_gaps_j += 1\n            elif j < max_j:\n                align_i.extend([GAP_CHAR] * (max_j - j))\n                align_j.extend([c for c in seqj[j:][::-1]])\n                n_gaps_i += 1\n\n        while p != NONE:\n            if p == DIAG:\n                i -= 1\n                j -= 1\n                ichar = seqi[i]\n                jchar = seqj[j]\n                if ichar != jchar:\n                    n_mmatch += 1\n                align_j.append(jchar)\n                align_i.append(ichar)\n            elif p == LEFT:\n                j -= 1\n                align_j.append(seqj[j])\n                if not align_i or align_i[-1] != GAP_CHAR:\n                    n_gaps_i += 1\n                align_i.append(GAP_CHAR)\n            elif p == UP:\n                i -= 1\n                align_i.append(seqi[i])\n                if not align_j or align_j[-1] != GAP_CHAR:\n                    n_gaps_j += 1\n                align_j.append(GAP_CHAR)\n            else:\n                raise Exception('wtf!')\n            p = pointer[i, j]\n\n        align_i = bytes(align_i[::-1]) \\\n            if not IS_PY2 else ''.join(align_i[::-1])\n        align_j = bytes(align_j[::-1]) \\\n            if not IS_PY2 else ''.join(align_j[::-1])\n\n        aln = (AlignmentResult(align_i, align_j, i, j, end_i, end_j,\n                               n_gaps_i, n_gaps_j, n_mmatch, score)\n               if flip else\n               AlignmentResult(align_j, align_i, j, i, end_j, end_i,\n                               n_gaps_j, n_gaps_i, n_mmatch, score))\n\n        results.append(aln)\n\n    return results", "meta": {"hexsha": "6922e8dfcab665c119147697d1b9ce34f6e3aff4", "size": 9795, "ext": "py", "lang": "Python", "max_stars_repo_path": "core/align.py", "max_stars_repo_name": "WenchaoLin/myTyper", "max_stars_repo_head_hexsha": "e3a56584a397ef9fd21c2a660c9d9e8f65df8246", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core/align.py", "max_issues_repo_name": "WenchaoLin/myTyper", "max_issues_repo_head_hexsha": "e3a56584a397ef9fd21c2a660c9d9e8f65df8246", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core/align.py", "max_forks_repo_name": "WenchaoLin/myTyper", "max_forks_repo_head_hexsha": "e3a56584a397ef9fd21c2a660c9d9e8f65df8246", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8233082707, "max_line_length": 78, "alphanum_fraction": 0.5061766207, "include": true, "reason": "import numpy", "num_tokens": 2596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3040416812727289, "lm_q1q2_score": 0.17209322707254995}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nr\"\"\"Provide the manipulability task.\n\nThe manipulability task implements a task that tries to maximize the manipulability measure given in [1]:\n\n.. math:: w(q) = \\sqrt{ \\det( J(q) W J(q)^\\top ) }\n\nwhere :math:`W` is a constant weight matrix, :math:`q` are the joint positions, and :math:`J(q)` is the jacobian.\nThe gradient of :math:`w` is then computed and projected using the gradient projection method [2].\n\nThe quadratic cost being minimized is:\n\n.. math:: ||\\dot{q} - \\dot{q}_0||^2\n\nwhere :math:`\\dot{q}` are the joint velocities being optimized,\n:math:`\\dot{q}_0 = k_0 \\left( \\frac{\\partial w(q)}{\\partial q} \\right)^\\top` where :math:`k_0 > 0` and\n:math:`w(q)` is an objective function of the joint variables, where in this case, the manipulability measure is\ngiven by :math:`w(q) = \\sqrt{\\det( J(q) J^\\top(q) )}`. By maximizing this measure, we move away from singularities.\n\n\nThe implementation of this class is inspired by [1] (which is licensed under the LGPLv2).\n\nReferences:\n    - [1] \"OpenSoT: A whole-body control library for the compliant humanoid robot COMAN\", Rocchi et al., 2015\n\"\"\"\n\n# TODO: finish to implement this\n\nimport numpy as np\n\nfrom pyrobolearn.priorities.tasks import JointVelocityTask\n\n\n__author__ = \"Brian Delhaisse\"\n__copyright__ = \"Copyright 2019, PyRoboLearn\"\n__credits__ = [\"Enrico Mingo Hoffman (C++)\", \"Brian Delhaisse (Python + doc)\"]\n__license__ = \"GNU GPLv3\"\n__version__ = \"1.0.0\"\n__maintainer__ = \"Brian Delhaisse\"\n__email__ = \"briandelhaisse@gmail.com\"\n__status__ = \"Development\"\n\n\nclass ManipulabilityTask(JointVelocityTask):\n    r\"\"\"Manipulability Task\n\n    The manipulability task implements a task that tries to maximize the manipulability measure given in [1]:\n\n    .. math:: w(q) = \\sqrt{ \\det( J(q) W J(q)^\\top ) }\n\n    where :math:`W` is a constant weight matrix, :math:`q` are the joint positions, and :math:`J(q)` is the jacobian.\n    The gradient of :math:`w` is then computed and projected using the gradient projection method [2].\n\n    The quadratic cost being minimized is:\n\n    .. math:: ||\\dot{q} - \\dot{q}_0||^2\n\n    where :math:`\\dot{q}` are the joint velocities being optimized,\n    :math:`\\dot{q}_0 = k_0 \\left( \\frac{\\partial w(q)}{\\partial q} \\right)^\\top` where :math:`k_0 > 0` and\n    :math:`w(q)` is an objective function of the joint variables, where in this case, the manipulability measure is\n    given by :math:`w(q) = \\sqrt{\\det( J(q) J^\\top(q) )}`. By maximizing this measure, we move away from singularities.\n\n    References:\n        - [1] \"Robotics: Modelling, Planning, and Control\", Siciliano et al., 2010\n        - [2] \"OpenSoT: A whole-body control library for the compliant humanoid robot COMAN\", Rocchi et al., 2015\n    \"\"\"\n\n    def __init__(self, model, weight=1., constraints=[]):\n        \"\"\"\n        Initialize the task.\n\n        Args:\n            model (ModelInterface): model interface\n            weight (float, np.array[float[N,N]]): weight scalar or matrix associated to the task.\n            constraints (list[Constraint]): list of constraints associated with the task.\n        \"\"\"\n        super(ManipulabilityTask, self).__init__(model=model, weight=weight, constraints=constraints)\n\n        raise NotImplementedError(\"This class has not been implemented yet.\")\n", "meta": {"hexsha": "5348bd928be98036a3ffbeb2725109a19d750d2d", "size": 3300, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyrobolearn/priorities/tasks/velocity/manipulability.py", "max_stars_repo_name": "Pandinosaurus/pyrobolearn", "max_stars_repo_head_hexsha": "9cd7c060723fda7d2779fa255ac998c2c82b8436", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-21T21:08:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:45:49.000Z", "max_issues_repo_path": "pyrobolearn/priorities/tasks/velocity/manipulability.py", "max_issues_repo_name": "Pandinosaurus/pyrobolearn", "max_issues_repo_head_hexsha": "9cd7c060723fda7d2779fa255ac998c2c82b8436", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyrobolearn/priorities/tasks/velocity/manipulability.py", "max_forks_repo_name": "Pandinosaurus/pyrobolearn", "max_forks_repo_head_hexsha": "9cd7c060723fda7d2779fa255ac998c2c82b8436", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-29T21:25:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-29T21:25:39.000Z", "avg_line_length": 40.7407407407, "max_line_length": 119, "alphanum_fraction": 0.6851515152, "include": true, "reason": "import numpy", "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.30404168127272885, "lm_q1q2_score": 0.17209322707254993}}
{"text": "# -*- coding: utf-8 -*-\n\nimport numpy as np\n\n\nclass AEP_load():\n    \"\"\" Calculate AEP (and fatigue load) of a given wind farm.\n\n    Parameters\n    ----------\n    site_conditions: class object (WindResource class)\n        Storing the terrain flow and wind resource data, and providing a\n        function to get the site conditions of given location(s) for certain\n        inflow wind direction.\n\n    wind_farm: class object (WindFarm class)\n        Defining the design of the wind farm, i.e., the layout and turbine type\n        and hub height information for all turbines.\n\n    wake_model: class object (WakeModel class)\n        Specifying the wake models to use in the calculation. The default ones\n        are N.O. Jensen for wake deficit and G.C. Larsen for turbulence.\n\n    ws_binned: array:float, np.linspace(1, 30, num=30)\n        Discretized wind speed bins at a reference height above the ground for\n        far field inflow. ) [m/s]\n\n    wd_binned: array:float, np.linspace(0, 330, num=12)\n        Discretized wind direction bins at a reference height above the ground\n        for far field inflow [deg]. This should be equally spaced and contains\n        at least two wind directions, as we derive the sector width from it.\n\n    height_ref: float, 85\n        Reference height above the ground for defining the far field inflow\n        condition [m].\n\n    k_star: float, 0.075\n        Wake decay parameter used in the N.O. Jensen wake model for the\n        wake_model [-].\n\n    availability: float, 1.0\n        Availability factor for the wind farm [-].\n\n    num_evals: integer, 0\n        Number of evluations of .cal_AEP_load() [-].\n\n    z0: float, 0.001\n        Used to transfer far field inflow wind speeds between different heights\n        above the ground [m].\n\n    Returns\n    -------\n    wind2load: wind2load class\n        Specifying the load model for calculating mean equivalent fatigue loads\n        for each turbine at different channels. Currently it is the surrogate\n        load model implemented. Note that when wind2load is not provided as\n        input, this class will only calculate AEP.\n\n\n    Methods\n    -------\n    reset_num_evals()\n        Reset the number of AEP (and load) evalutions to zero.\n\n    cal_AEP_load(cal_load=True)\n        Calculate gross AEP, net AEP (and mean load) of this wind farm.\n    \"\"\"\n\n    def __init__(self,\n                 site_conditions,  # include terrain and wind resource\n                 wind_farm,  # defines the design of wind farm\n                 wake_model,  # wake model to use\n                 wind2load=None,  # optional input, calc only AEP when None\n                 ws_binned=np.linspace(1, 30, num=30),  # [m/s]\n                 wd_binned=np.linspace(0, 330, num=12),  # [deg]\n                 height_ref=85,  # [m]\n                 k_star=0.075,  # wake decay parameter\n                 availability=1.0,  # availability factor for the wind farm\n                 num_evals=0,    # number of evluations of .cal_AEP_load()\n                 z0=0.001  # used to transfer wind speed between diff height\n                 ):\n        \"\"\" ws_binned, wd_binned and height_ref defines a set of discretized\n        ideal far field inflow condition at the a height above the ground\n        (height_ref), which controls and specifies the bin sizes of wind speed\n        and wind direction in the AEP calculation.\n        \"\"\"\n        # inputed attributes\n        self.site_conditions = site_conditions\n        self.wind_farm = wind_farm\n        self.wake_model = wake_model\n        self.wind2load = wind2load\n        self.ws_binned = ws_binned\n        self.wd_binned = wd_binned\n        self.height_ref = height_ref\n        self.k_star = k_star\n        self.availability = availability\n        self.num_evals = num_evals\n        self.z0 = z0\n\n        # calculated attributes (storing necessary data during calculation)\n        self.num_ws_bins = len(ws_binned)\n        self.num_wd_bins = len(wd_binned)\n        self.wf_design = wind_farm.get_summary().values  # [x, y, z, D, H, P]\n        self.num_turbines = len(self.wf_design[:, 0])\n        if self.wind2load is not None:\n            self.num_channels = self.wind2load.num_channel\n\n        # Extend the wind dir bins to include an extra dir for integration\n        self.num_wd_bins = self.num_wd_bins + 1\n        self.wd_binned = np.hstack(\n                (self.wd_binned,\n                 self.wd_binned[-1] + self.wd_binned[1] - self.wd_binned[0]))\n        # note we assume wd_binned is equally spaced.\n\n        # index i, k, l denotes the ith turbine, the kth wind speed and the lth\n        # wind direction, which is defined in self.ws_binned and self.wd_binned\n        shape_ikl = [self.num_turbines, self.num_ws_bins, self.num_wd_bins]\n        self.local_ws_ideal_ikl = np.zeros(shape_ikl)\n        self.local_wd_ideal_ikl = np.zeros(shape_ikl)\n        self.local_power_ideal_ikl = np.zeros(shape_ikl)\n        self.local_ws_real_ikl = np.zeros(shape_ikl)\n        self.local_wd_real_ikl = np.zeros(shape_ikl)\n        self.local_power_real_ikl = np.zeros(shape_ikl)\n        self.local_pdf_ikl = np.zeros(shape_ikl)\n        self.local_TI_real_ikl = np.zeros(shape_ikl)\n        self.local_Ct_ikl = np.zeros(shape_ikl)\n\n        if self.wind2load is not None:\n            self.load_iklm = np.zeros([self.num_turbines,\n                                       self.num_ws_bins,\n                                       self.num_wd_bins,\n                                       self.num_channels])\n\n    def reset_num_evals(self):\n        \"\"\" Reset the number of evaluation to 0.\n        \"\"\"\n        self.num_evals = 0\n\n    def cal_AEP_load(self, cal_load=True):\n        \"\"\" Calculate gross AEP, net AEP (and mean load) of this wind farm.\n\n        If wind2load is provided and load calculation is turned on (cal_load=\n        True), returns (AEP_gross, AEP_net and mean_loads).\n\n        If wind2load is not provided or load calculation is turned off\n        (cal_load=False), returns (AEP_gross, AEP_net)\n\n        This is the vectorized version.\n\n        Parameters\n        ----------\n        cal_load: boolean (default: True)\n            A flag to turn on/off the load calculation.\n\n        Returns\n        -------\n        AEP_gross: array:float\n            Gross AEP values of each turbine in the wind farm.\n\n        AEP_net: array:float\n            Net AEP values of each turbine in the wind farm.\n\n        mean_loads: array:float\n            Mean equivalent fatigue loads for each turbine at different\n            channels. Note this one is only returned when the wind2load\n            instance is provided and the load calculation is turned on.\n        \"\"\"\n        num_hrs_a_year = 8760\n\n        #######################################################################\n        # Step 1. Get and store sector (wind direction) wise site conditions\n        speed_up_il = np.zeros([self.num_turbines, self.num_wd_bins])\n        turning_il = np.zeros([self.num_turbines, self.num_wd_bins])\n        inclination_il = np.zeros([self.num_turbines, self.num_wd_bins])\n        Weibull_A_il = np.zeros([self.num_turbines, self.num_wd_bins])\n        Weibull_k_il = np.zeros([self.num_turbines, self.num_wd_bins])\n        frequency_il = np.zeros([self.num_turbines, self.num_wd_bins])\n        turbulence_il = np.zeros([self.num_turbines, self.num_wd_bins])\n        wind_shear_il = np.zeros([self.num_turbines, self.num_wd_bins])\n        rho_il = np.zeros([self.num_turbines, self.num_wd_bins])\n\n        for l_wd in range(self.num_wd_bins):\n            wd = self.wd_binned[l_wd]\n            # For this general inflow direcion, get wind resource and terrain\n            # effect information for all turbine locations.\n\n            conditions = self.site_conditions.get_site_conditions(\n                self.wf_design[:, (0, 1, 4)], wd)\n\n            speed_up_il[:, l_wd] = conditions['spd_up'].values\n            turning_il[:, l_wd] = conditions['deviation'].values\n            inclination_il[:, l_wd] = conditions['inflow_angle'].values\n            Weibull_A_il[:, l_wd] = conditions['A'].values\n            Weibull_k_il[:, l_wd] = conditions['k'].values\n            frequency_il[:, l_wd] = conditions['freq_per_degree'].values\n            turbulence_il[:, l_wd] = conditions['tke_amb'].values\n            wind_shear_il[:, l_wd] = conditions['alpha'].values\n            rho_il[:, l_wd] = conditions['rho'].values\n\n        #######################################################################\n        # Step 2. Calculate ideal local flow field (ws, wd) and related pdf\n        for l_wd in range(self.num_wd_bins):\n            wd = self.wd_binned[l_wd]\n\n            for k_ws in range(self.num_ws_bins):\n                ws = self.ws_binned[k_ws]\n\n                for i_wt in range(self.num_turbines):\n                    H_hub = self.wf_design[i_wt, 4]\n\n                    # calculate local wind speed and wind direction without\n                    # wake effects by considering terrain effect\n                    local_ws_ideal = (ws * np.log(H_hub / self.z0) /\n                                      np.log(self.height_ref / self.z0) *\n                                      speed_up_il[i_wt, l_wd])\n\n                    local_wd_ideal = (wd + turning_il[i_wt, l_wd])\n\n                    self.local_ws_ideal_ikl[i_wt, k_ws, l_wd] = local_ws_ideal\n                    self.local_wd_ideal_ikl[i_wt, k_ws, l_wd] = local_wd_ideal\n\n                    # calculating related pdf for all wind speeds\n                    self.local_pdf_ikl[i_wt, k_ws, l_wd] = \\\n                        self.cal_pdf_Weibull(self.local_ws_ideal_ikl[i_wt,\n                                                                     k_ws,\n                                                                     l_wd],\n                                             Weibull_A_il[i_wt, l_wd],\n                                             Weibull_k_il[i_wt, l_wd]) \\\n                        * frequency_il[i_wt, l_wd]\n\n        #######################################################################\n        # Step 3. Calculate ideal local Ct and power\n        for i_wt in range(self.num_turbines):\n            self.local_power_ideal_ikl[i_wt, :, :] = (\n                    self.wind_farm.get_power(i_wt,\n                                             self.local_ws_ideal_ikl[i_wt, :,\n                                                                     :]))\n\n            self.local_Ct_ikl[i_wt, :, :] = (\n                    self.wind_farm.get_ct(i_wt,\n                                          self.local_ws_ideal_ikl[i_wt, :,\n                                                                  :]))\n\n        #######################################################################\n        # Step 4. Calculate real local wind speed and turbulence intensity\n\n        # assuming same wake decay coefficients for all turbines\n        k_star_list = [self.k_star] * self.num_turbines\n\n        (self.local_ws_real_ikl, self.local_TI_real_ikl) = self.wake_model.cal_wake(\n                    self.wf_design[:, 0],   # [x_i]\n                    self.wf_design[:, 1],   # [y_i]\n                    self.wf_design[:, 4],   # [H_i]]\n                    self.wf_design[:, 3],   # [D_i]\n                    self.local_ws_ideal_ikl,\n                    self.local_wd_ideal_ikl,\n                    self.local_Ct_ikl,\n                    turbulence_il,\n                    k_star_list)\n\n        #######################################################################\n        # Step 5. Calculate real power of each turbine\n        for i_wt in range(self.num_turbines):\n            self.local_power_real_ikl[i_wt, :, :] = (\n                    self.wind_farm.get_power(i_wt,\n                                             self.local_ws_real_ikl[i_wt, :,\n                                                                    :]))\n\n        #######################################################################\n        # Step 6. Calculate loads\n\n        # if the wind2load is available and load calculation is turned on\n        if (self.wind2load is not None) and cal_load:\n            # for the single value 0 dimension vectorized calculation\n            # for l_wd in range(self.num_wd_bins):\n            #     for k_ws in range(self.num_ws_bins):\n            #         for i_wt in range(self.num_turbines):\n            #\n            #             self.load_iklm[i_wt, k_ws, l_wd, :] = (\n            #                 self.wind2load.load_calculation(\n            #                     self.local_ws_real_ikl[i_wt, k_ws, l_wd],\n            #                     self.local_TI_real_ikl[i_wt, k_ws, l_wd],\n            #                     wind_shear_il[i_wt, l_wd],\n            #                     inclination_il[i_wt, l_wd],\n            #                     rho_il[i_wt, l_wd],\n            #                     self.wf_design[i_wt, 4],      # H\n            #                     self.wf_design[i_wt, 3],      # D\n            #                     self.wf_design[i_wt, 5]))     # P_rated\n            # 2d dimensional data passing of vectorized calculation\n            for i_wt in range(self.num_turbines):\n                self.load_iklm[i_wt, :, :, :] = (\n                    self.wind2load.load_calculation_2d(\n                        self.local_ws_real_ikl[i_wt, :, :],\n                        self.local_TI_real_ikl[i_wt, :, :],\n                        np.tile(wind_shear_il[i_wt, :],\n                                (self.num_ws_bins, 1)),\n                        np.tile(inclination_il[i_wt, :],\n                                (self.num_ws_bins, 1)),\n                        np.tile(rho_il[i_wt, :], (self.num_ws_bins, 1)),\n                        self.wf_design[i_wt, 4],  # H\n                        self.wf_design[i_wt, 3],  # D\n                        self.wf_design[i_wt, 5]))  # P_rated\n\n        #######################################################################\n        # Step 7. Calculate mean power and AEP values using numerical integ.\n\n        delta_ws = (self.local_ws_ideal_ikl[:, 1:, 1:] -\n                    self.local_ws_ideal_ikl[:, :-1, 1:])\n\n        delta_wd = (self.local_wd_ideal_ikl[:, 1:, 1:] -\n                    self.local_wd_ideal_ikl[:, 1:, :-1])\n\n        pdf_array = (self.local_pdf_ikl[:, 1:, 1:] +\n                     self.local_pdf_ikl[:, :-1, 1:]) / 2\n\n        power_ideal_array = (self.local_power_ideal_ikl[:, 1:, 1:] +\n                             self.local_power_ideal_ikl[:, :-1, 1:]) / 2\n\n        power_real_array = (self.local_power_real_ikl[:, 1:, 1:] +\n                            self.local_power_real_ikl[:, :-1, 1:]) / 2\n\n        mean_power_ideal = np.sum(\n            delta_ws * delta_wd * pdf_array * power_ideal_array, (1, 2))\n\n        mean_power_real = np.sum(\n            delta_ws * delta_wd * pdf_array * power_real_array, (1, 2))\n\n        AEP_gross = num_hrs_a_year * mean_power_ideal * self.availability\n        AEP_net = num_hrs_a_year * mean_power_real * self.availability\n\n        #######################################################################\n        # Step 8. Calculate loads\n\n        # if the wind2load is available and load calculation is turned on\n        if (self.wind2load is not None) and cal_load:\n            load_array = (self.load_iklm[:, 1:, 1:, :]\n                          + self.load_iklm[:, :-1, 1:, :])/2\n            slope_array = self.wind2load.pce_slopes\n            mean_loads = np.zeros([self.num_turbines, self.num_channels])\n\n            for m_channel in range(self.num_channels):\n                mean_loads[:, m_channel] = (np.sum(\n                    delta_ws * delta_wd * pdf_array *\n                    (load_array[:, :, :, m_channel] **\n                     slope_array[m_channel]), (1, 2))\n                     / self.wind2load.frequence) ** \\\n                    (1 / slope_array[m_channel])\n\n        #################################################################\n        # updating number of evluations\n        self.num_evals = self.num_evals + 1\n\n        if (self.wind2load is not None) and cal_load:\n            return (AEP_gross, AEP_net, mean_loads)\n        else:\n            return (AEP_gross, AEP_net)\n\n    def cal_AEP_load_naive(self, cal_load=True):\n        \"\"\" Calculate gross AEP, net AEP and mean load of this wind farm\n\n        This is the naive version with all in for loops. This naive version is\n        only kept here for understanding the process and possible testing\n        usages.\n        \"\"\"\n        num_hrs_a_year = 8760\n\n        #######################################################################\n        # Step 1. Calculate flow field, pdf , power and load\n\n        for l_wd in range(self.num_wd_bins):\n            wd = self.wd_binned[l_wd]\n            # For this general inflow direcion, get wind resource and terrain\n            # effect information for all turbine locations. All thess lists are\n            # one dimensional array with self.num_turbs elements.\n\n            conditions = self.site_conditions.get_site_conditions(\n                self.wf_design[:, (0, 1, 4)], wd)\n\n            speed_up_list = conditions['spd_up'].values\n            turning_list = conditions['deviation'].values\n            inclination_list = conditions['inflow_angle'].values\n            Weibull_A_list = conditions['A'].values\n            Weibull_k_list = conditions['k'].values\n            frequency_list = conditions['freq_per_degree'].values\n            turbulence_list = conditions['tke_amb'].values\n            wind_shear_list = conditions['alpha'].values\n            rho_list = conditions['rho'].values\n\n            for k_ws in range(self.num_ws_bins):\n                ws = self.ws_binned[k_ws]\n                Ct_list = np.zeros(self.num_turbines)\n\n                ###########################################################\n                # ideal case: without wake effects\n                for i_wt in range(self.num_turbines):\n                    H_hub = self.wf_design[i_wt, 4]\n\n                    # calculate local wind speed and wind direction without\n                    # wake effects by considering terrain effect\n                    local_ws_ideal = (ws * np.log(H_hub / self.z0) /\n                                      np.log(self.height_ref / self.z0) *\n                                      speed_up_list[i_wt])\n                    local_wd_ideal = (wd + turning_list[i_wt])\n\n                    self.local_ws_ideal_ikl[i_wt, k_ws, l_wd] = local_ws_ideal\n                    self.local_wd_ideal_ikl[i_wt, k_ws, l_wd] = local_wd_ideal\n\n                    # calculating relating pdf and power\n                    self.local_pdf_ikl[i_wt, k_ws, l_wd] = (\n                        (self.cal_pdf_Weibull(\n                            local_ws_ideal,\n                            Weibull_A_list[i_wt],\n                            Weibull_k_list[i_wt])) *\n                        frequency_list[i_wt])\n\n                    self.local_power_ideal_ikl[i_wt, k_ws, l_wd] = (\n                        self.wind_farm.get_power(i_wt, local_ws_ideal))\n\n                    # get Ct\n                    Ct_list[i_wt] = self.wind_farm.get_ct(i_wt,\n                                                          local_ws_ideal)\n\n                ###########################################################\n                # Real case: with wake effects\n                # caculate wake influced flow field\n                k_star_list = [self.k_star] * self.num_turbines\n\n                (ws_eff, TI_eff) = self.wake_model.cal_wake(\n                    self.wf_design[:, 0],\n                    self.wf_design[:, 1],\n                    self.wf_design[:, 4],\n                    self.wf_design[:, 3],\n                    self.local_ws_ideal_ikl[:, k_ws, l_wd],\n                    self.local_wd_ideal_ikl[:, k_ws, l_wd],\n                    Ct_list,\n                    turbulence_list,\n                    k_star_list)\n\n                self.local_ws_real_ikl[:, k_ws, l_wd] = ws_eff\n\n                if (self.wind2load is not None) and cal_load:\n\n                    for i_wt in range(self.num_turbines):\n                        self.local_power_real_ikl[i_wt, k_ws, l_wd] = (\n                            self.wind_farm.get_power(i_wt,\n                                                     ws_eff[i_wt]))\n\n                        # Calculate laod for each WT\n                        wind_condition = np.array([ws_eff[i_wt],\n                                                   TI_eff[i_wt],\n                                                   wind_shear_list[i_wt],\n                                                   inclination_list[i_wt],\n                                                   rho_list[i_wt]])\n                        turbine_parameter = np.array([self.wf_design[i_wt, 4],\n                                                      self.wf_design[i_wt, 3],\n                                                      self.wf_design[i_wt, 5]])\n                        print(cal_load)\n                        self.load_iklm[i_wt, k_ws, l_wd, :] = (\n                            self.wind2load.load_calculation(\n                                wind_condition,\n                                turbine_parameter))\n\n        #######################################################################\n        # Step 4. Calculate mean power and AEP values using numerical integ.\n        delta_ws = (self.local_ws_ideal_ikl[:, 1:, 1:] -\n                    self.local_ws_ideal_ikl[:, :-1, 1:])\n\n        delta_wd = (self.local_wd_ideal_ikl[:, 1:, 1:] -\n                    self.local_wd_ideal_ikl[:, 1:, :-1])\n\n        pdf_array = (self.local_pdf_ikl[:, 1:, 1:] +\n                     self.local_pdf_ikl[:, :-1, 1:]) / 2\n\n        power_ideal_array = (self.local_power_ideal_ikl[:, 1:, 1:] +\n                             self.local_power_ideal_ikl[:, :-1, 1:]) / 2\n\n        power_real_array = (self.local_power_real_ikl[:, 1:, 1:] +\n                            self.local_power_real_ikl[:, :-1, 1:]) / 2\n\n        mean_power_ideal = np.sum(\n            delta_ws * delta_wd * pdf_array * power_ideal_array, (1, 2))\n\n        mean_power_real = np.sum(\n            delta_ws * delta_wd * pdf_array * power_real_array, (1, 2))\n\n        AEP_gross = num_hrs_a_year * mean_power_ideal\n        AEP_net = num_hrs_a_year * mean_power_real\n\n        #######################\n        # mean loads\n        if (self.wind2load is not None) and cal_load:\n            load_array = (self.load_iklm[:, 1:, 1:, :]\n                          + self.load_iklm[:, :-1, 1:, :])/2\n\n            mean_loads = np.zeros([self.num_turbines, self.num_channels])\n\n            for m_channel in range(self.num_channels):\n                mean_loads[:, m_channel] = np.sum(\n                    delta_ws * delta_wd * pdf_array *\n                    load_array[:, :, :, m_channel], (1, 2))\n\n        if (self.wind2load is not None) and cal_load:\n            return (AEP_gross, AEP_net, mean_loads)\n        else:\n            return (AEP_gross, AEP_net)\n\n    def cal_pdf_Weibull(self, ws, Weibull_A, Weibull_k):\n        \"\"\" calculate pdf of a given wind speed based on Weibull distribution.\n\n        Parameters\n        ----------\n        ws: array:float\n            Wind speed [m/s]\n\n        Weibull_A: array:float\n            Scale parameter of Weibull distribution [m/s]\n        Weibull_k: array:float\n            Shape parameter of Weibull distribution [-].\n\n        Returns\n        -------\n        pdf: array:float\n            Probability density function calculated using Weibull distribution.\n\n        \"\"\"\n        pdf = ((Weibull_k / Weibull_A) * (ws / Weibull_A) ** (Weibull_k - 1) *\n               np.exp(-(ws / Weibull_A) ** Weibull_k))\n\n        return pdf\n", "meta": {"hexsha": "faf1208f7bdc59c6c12d14e1fc64d1e1175cc41c", "size": 23657, "ext": "py", "lang": "Python", "max_stars_repo_path": "topfarm/aep.py", "max_stars_repo_name": "rethore/topfarm", "max_stars_repo_head_hexsha": "ada9a24ebf8f643ad79320c446ce2be1b8487378", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "topfarm/aep.py", "max_issues_repo_name": "rethore/topfarm", "max_issues_repo_head_hexsha": "ada9a24ebf8f643ad79320c446ce2be1b8487378", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "topfarm/aep.py", "max_forks_repo_name": "rethore/topfarm", "max_forks_repo_head_hexsha": "ada9a24ebf8f643ad79320c446ce2be1b8487378", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-10-02T15:10:24.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T15:10:24.000Z", "avg_line_length": 44.6358490566, "max_line_length": 84, "alphanum_fraction": 0.5156190557, "include": true, "reason": "import numpy", "num_tokens": 5473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.28140560742914383, "lm_q1q2_score": 0.17204631556606917}}
{"text": "\"\"\"Implementations of interpolators, which representgeometric paths.\n\n\"\"\"\nimport logging\nimport warnings\nimport numpy as np\nfrom scipy.interpolate import UnivariateSpline, CubicSpline, PPoly\n\nlogger = logging.getLogger(__name__)\n\ntry:\n    import openravepy as orpy\nexcept ImportError as err:\n    logger.warning(\"Unable to import openravepy. Exception: %s\", err.args[0])\nexcept SyntaxError as err:\n    logger.warning(\"Unable to import openravepy. Exception: %s\", err.args[0])\n\n\ndef normalize(gridpoints):\n    # type: (np.ndarray) -> np.ndarray\n    \"\"\"Normalize the path discretization.\n\n    Parameters\n    ----------\n    gridpoints: Path position array.\n\n    Returns\n    -------\n    out: Normalized path position array.\n    \"\"\"\n    return np.array(gridpoints) / gridpoints[-1]\n\n\ndef _find_left_index(gridpoints, s):\n    # type: (np.ndarray, float) -> int\n    \"\"\"Find the least lowest entry that is larger or equal.\n\n    Parameters\n    ----------\n    gridpoints:\n        Array of path positions.\n    s:\n        A path position.\n\n    Returns\n    -------\n    out:\n        The desired index.\n\n    \"\"\"\n    for i in range(1, len(gridpoints)):\n        if gridpoints[i - 1] <= s < gridpoints[i]:\n            return i - 1\n    return len(gridpoints) - 2\n\n\nclass Interpolator(object):\n    \"\"\"Abstract class for interpolators.\"\"\"\n\n    def __init__(self):\n        pass\n\n    def get_dof(self):\n        # type: () -> int\n        \"\"\"Return the degree-of-freedom of the path.\n\n        Returns\n        -------\n        out:\n            Degree-of-freedom of the path.\n        \"\"\"\n        raise NotImplementedError\n\n    @property\n    def duration(self):\n        \"\"\"Return the duration of the path.\"\"\"\n        raise NotImplementedError\n\n    @property\n    def dof(self):\n        \"\"\"Return the degrees-of-freedom of the path.\"\"\"\n        raise NotImplementedError\n\n    def get_path_interval(self):\n        # type: () -> np.ndarray\n        \"\"\"Return the starting and ending path positions.\n\n        Returns\n        -------\n        out:\n            The starting and ending path positions.\n\n        \"\"\"\n        return np.array([self.s_start, self.s_end])\n\n    def eval(self, ss_sam):\n        # type: (any[np.ndarray, float]) -> np.ndarray\n        \"\"\"Evaluate joint positions at specified path positions.\n\n        Parameters\n        ----------\n        ss_sam :\n            Shape (m,) or float. The path positions to sample at.\n\n        Returns\n        -------\n        out :\n            Shape (m, dof) if input is an array: evaluated values at positions.\n            Shape (dof,) if input is a float.\n        \"\"\"\n        raise NotImplementedError\n\n    def evald(self, ss_sam):\n        # type: (any[np.ndarray, float]) -> np.ndarray\n        \"\"\"Evaluate first derivative at specified path positions.\n\n        Parameters\n        ----------\n        ss_sam :\n            Shape (m,) or float. The path positions to sample at.\n\n        Returns\n        -------\n        out :\n            Shape (m, dof) if input is an array: evaluated values at positions.\n            Shape (dof,) if input is a float.\n        \"\"\"\n        raise NotImplementedError\n\n    def evaldd(self, ss_sam):\n        # type: (Union[np.ndarray, float]) -> np.ndarray\n        \"\"\"Evaluate second derivative at specified path positions.\n\n        Parameters\n        ----------\n        ss_sam :\n            Shape (m,) or float. The path positions to sample at.\n\n        Returns\n        -------\n        out :\n            Shape (m, dof) if input is an array: evaluated values at positions.\n            Shape (dof,) if input is a float.\n        \"\"\"\n        raise NotImplementedError\n\n    def compute_rave_trajectory(self, robot):\n        \"\"\"Return the corresponding Openrave Trajectory.\"\"\"\n        raise NotImplementedError\n\n    def compute_ros_trajectory(self):\n        \"\"\"Return the corresponding ROS trajectory.\"\"\"\n        raise NotImplementedError\n\n\nclass RaveTrajectoryWrapper(Interpolator):\n    \"\"\"An interpolator that wraps OpenRAVE's :class:`GenericTrajectory`.\n\n    Only trajectories using quadratic interpolation or cubic\n    interpolation are supported.  The trajectory is represented as a\n    piecewise polynomial. The polynomial could be quadratic or cubic\n    depending the interpolation method used by the input trajectory\n    object.\n\n    \"\"\"\n\n    def __init__(self, traj, robot):\n        # type: (orpy.RaveTrajectory, orpy.Robot) -> None\n        \"\"\"Initialize the Trajectory Wrapper.\n\n        Parameters\n        ----------\n        traj:\n            An OpenRAVE joint trajectory.\n        robot:\n            An OpenRAVE robot.\n        \"\"\"\n        super(RaveTrajectoryWrapper, self).__init__()\n        self.traj = traj  #: init\n        self.spec = traj.GetConfigurationSpecification()\n        self._dof = robot.GetActiveDOF()\n\n        self._interpolation = self.spec.GetGroupFromName('joint').interpolation\n        if self._interpolation not in ['quadratic', 'cubic']:\n            raise ValueError(\n                \"This class only handles trajectories with quadratic or cubic interpolation\"\n            )\n        self._duration = traj.GetDuration()\n        all_waypoints = traj.GetWaypoints(0, traj.GetNumWaypoints()).reshape(\n            traj.GetNumWaypoints(), -1)\n        valid_wp_indices = [0]\n        self.ss_waypoints = [0.0]\n        for i in range(1, traj.GetNumWaypoints()):\n            dt = self.spec.ExtractDeltaTime(all_waypoints[i])\n            if dt > 1e-5:  # If delta is too small, skip it.\n                valid_wp_indices.append(i)\n                self.ss_waypoints.append(self.ss_waypoints[-1] + dt)\n\n        self.n_waypoints = len(valid_wp_indices)\n        self.ss_waypoints = np.array(self.ss_waypoints)\n        self.s_start = self.ss_waypoints[0]\n        self.s_end = self.ss_waypoints[-1]\n\n        self.waypoints = np.array([\n            self.spec.ExtractJointValues(all_waypoints[i], robot,\n                                         robot.GetActiveDOFIndices())\n            for i in valid_wp_indices\n        ])\n        self.waypoints_d = np.array([\n            self.spec.ExtractJointValues(all_waypoints[i], robot,\n                                         robot.GetActiveDOFIndices(), 1)\n            for i in valid_wp_indices\n        ])\n\n        # Degenerate case: there is only one waypoint.\n        if self.n_waypoints == 1:\n            pp_coeffs = np.zeros((1, 1, self.dof))\n            for idof in range(self.dof):\n                pp_coeffs[0, 0, idof] = self.waypoints[0, idof]\n            # A constant function\n            self.ppoly = PPoly(pp_coeffs, [0, 1])\n\n        elif self._interpolation == \"quadratic\":\n            self.waypoints_dd = []\n            for i in range(self.n_waypoints - 1):\n                qdd = ((self.waypoints_d[i + 1] - self.waypoints_d[i]) /\n                       (self.ss_waypoints[i + 1] - self.ss_waypoints[i]))\n                self.waypoints_dd.append(qdd)\n            self.waypoints_dd = np.array(self.waypoints_dd)\n\n            # Fill the coefficient matrix for scipy.PPoly class\n            pp_coeffs = np.zeros((3, self.n_waypoints - 1, self.dof))\n            for idof in range(self.dof):\n                for iseg in range(self.n_waypoints - 1):\n                    pp_coeffs[:, iseg, idof] = [\n                        self.waypoints_dd[iseg, idof] / 2,\n                        self.waypoints_d[iseg, idof],\n                        self.waypoints[iseg, idof]\n                    ]\n            self.ppoly = PPoly(pp_coeffs, self.ss_waypoints)\n\n        elif self._interpolation == \"cubic\":\n            self.waypoints_dd = np.array([\n                self.spec.ExtractJointValues(all_waypoints[i], robot,\n                                             robot.GetActiveDOFIndices(), 2)\n                for i in valid_wp_indices\n            ])\n            self.waypoints_ddd = []\n            for i in range(self.n_waypoints - 1):\n                qddd = ((self.waypoints_dd[i + 1] - self.waypoints_dd[i]) /\n                        (self.ss_waypoints[i + 1] - self.ss_waypoints[i]))\n                self.waypoints_ddd.append(qddd)\n            self.waypoints_ddd = np.array(self.waypoints_ddd)\n\n            # Fill the coefficient matrix for scipy.PPoly class\n            pp_coeffs = np.zeros((4, self.n_waypoints - 1, self.dof))\n            for idof in range(self.dof):\n                for iseg in range(self.n_waypoints - 1):\n                    pp_coeffs[:, iseg, idof] = [\n                        self.waypoints_ddd[iseg, idof] / 6,\n                        self.waypoints_dd[iseg, idof] / 2,\n                        self.waypoints_d[iseg, idof],\n                        self.waypoints[iseg, idof]\n                    ]\n            self.ppoly = PPoly(pp_coeffs, self.ss_waypoints)\n\n        self.ppoly_d = self.ppoly.derivative()\n        self.ppoly_dd = self.ppoly.derivative(2)\n\n    def get_duration(self):\n        warnings.warn(\n            \"`get_duration` method is deprecated, use `duration` property instead\",\n            PendingDeprecationWarning)\n        return self.duration\n\n    def get_dof(self):  # type: () -> int\n        warnings.warn(\"This method is deprecated, use the property instead\",\n                      PendingDeprecationWarning)\n        return self.dof\n\n    @property\n    def duration(self):\n        return self._duration\n\n    @property\n    def dof(self):\n        return self._dof\n\n    def eval(self, ss_sam):\n        return self.ppoly(ss_sam)\n\n    def evald(self, ss_sam):\n        return self.ppoly_d(ss_sam)\n\n    def evaldd(self, ss_sam):\n        return self.ppoly_dd(ss_sam)\n\n\nclass SplineInterpolator(Interpolator):\n    \"\"\"Interpolate the given waypoints by cubic spline.\n\n    This interpolator is implemented as a simple wrapper over scipy's\n    CubicSpline class.\n\n    Parameters\n    ----------\n    ss_waypoints: array\n        Shaped (N+1,). Path positions of the waypoints.\n    waypoints: array\n        Shaped (N+1, dof). Waypoints.\n    bc_type: str, optional\n        Boundary condition. Can be 'not-a-knot', 'clamped', 'natural' or 'periodic'.\n        See scipy.CubicSpline documentation for more details.\n\n    Attributes\n    ----------\n    dof : int\n        Output dimension of the function\n    cspl : :class:`scipy.interpolate.CubicSpline`\n        The path.\n    cspld : :class:`scipy.interpolate.CubicSpline`\n        The path 1st derivative.\n    cspldd : :class:`scipy.interpolate.CubicSpline`\n        The path 2nd derivative.\n\n    \"\"\"\n\n    def __init__(self, ss_waypoints, waypoints, bc_type='clamped'):\n        super(SplineInterpolator, self).__init__()\n        assert ss_waypoints[0] == 0, \"First index must equals zero.\"\n        self.ss_waypoints = np.array(ss_waypoints)\n        self.waypoints = np.array(waypoints)\n        self.bc_type = bc_type\n\n        assert self.ss_waypoints.shape[0] == self.waypoints.shape[0]\n        self.s_start = self.ss_waypoints[0]\n        self.s_end = self.ss_waypoints[-1]\n\n        if len(ss_waypoints) == 1:\n\n            def _1dof_cspl(s):\n                try:\n                    ret = np.zeros((len(s), self.dof))\n                    ret[:, :] = self.waypoints[0]\n                except TypeError:\n                    ret = self.waypoints[0]\n                return ret\n\n            def _1dof_cspld(s):\n                try:\n                    ret = np.zeros((len(s), self.dof))\n                except TypeError:\n                    ret = np.zeros(self.dof)\n                return ret\n\n            self.cspl = _1dof_cspl\n            self.cspld = _1dof_cspld\n            self.cspldd = _1dof_cspld\n        else:\n            self.cspl = CubicSpline(ss_waypoints, waypoints, bc_type=bc_type)\n            self.cspld = self.cspl.derivative()\n            self.cspldd = self.cspld.derivative()\n\n    def get_waypoints(self):\n        \"\"\"Return the appropriate scaled waypoints.\"\"\"\n        return self.ss_waypoints, self.waypoints\n\n    def get_duration(self):\n        warnings.warn(\n            \"get_duration is deprecated, use duration (property) instead\",\n            PendingDeprecationWarning)\n        return self.duration\n\n    @property\n    def duration(self):\n        return self.ss_waypoints[-1] - self.ss_waypoints[0]\n\n    @property\n    def dof(self):\n        if np.isscalar(self.waypoints[0]):\n            return 1\n        return self.waypoints[0].shape[0]\n\n    def get_dof(self):  # type: () -> int\n        warnings.warn(\"get_dof is deprecated, use dof (property) instead\",\n                      PendingDeprecationWarning)\n        return self.dof\n\n    def eval(self, ss_sam):\n        return self.cspl(ss_sam)\n\n    def evald(self, ss_sam):\n        return self.cspld(ss_sam)\n\n    def evaldd(self, ss_sam):\n        return self.cspldd(ss_sam)\n\n    def compute_rave_trajectory(self, robot):\n        \"\"\"Compute an OpenRAVE trajectory equivalent to this trajectory.\n\n        Parameters\n        ----------\n        robot:\n            Openrave robot.\n\n        Returns\n        -------\n        trajectory:\n            Equivalent openrave trajectory.\n        \"\"\"\n\n        traj = orpy.RaveCreateTrajectory(robot.GetEnv(), \"\")\n        spec = robot.GetActiveConfigurationSpecification('cubic')\n        spec.AddDerivativeGroups(1, False)\n        spec.AddDerivativeGroups(2, True)\n\n        traj.Init(spec)\n        deltas = [0]\n        for i in range(len(self.ss_waypoints) - 1):\n            deltas.append(self.ss_waypoints[i + 1] - self.ss_waypoints[i])\n        if len(self.ss_waypoints) == 1:\n            q = self.eval(0)\n            qd = self.evald(0)\n            qdd = self.evaldd(0)\n            traj.Insert(traj.GetNumWaypoints(),\n                        list(q) + list(qd) + list(qdd) + [0])\n        else:\n            qs = self.eval(self.ss_waypoints)\n            qds = self.evald(self.ss_waypoints)\n            qdds = self.evaldd(self.ss_waypoints)\n            for (q, qd, qdd, dt) in zip(qs, qds, qdds, deltas):\n                traj.Insert(traj.GetNumWaypoints(),\n                            q.tolist() + qd.tolist() + qdd.tolist() + [dt])\n        return traj\n\n\nclass UnivariateSplineInterpolator(Interpolator):\n    \"\"\" Smooth given wayspoints by a cubic spline.\n\n    This is a simple wrapper over `scipy.UnivariateSplineInterpolator`\n    class.\n\n    Parameters\n    ----------\n    ss_waypoints: ndarray\n        Path positions of the waypoints.\n    waypoints: ndarray\n        The waypoints.\n    \"\"\"\n\n    def __init__(self, ss_waypoints, waypoints):\n        super(UnivariateSplineInterpolator, self).__init__()\n        assert ss_waypoints[0] == 0, \"First index must equals zero.\"\n        self.ss_waypoints = np.array(ss_waypoints)\n        self.waypoints = np.array(waypoints)\n        if np.isscalar(waypoints[0]):\n            self.dof = 1\n        else:\n            self.dof = waypoints[0].shape[0]\n        self.duration = ss_waypoints[-1]\n        assert self.ss_waypoints.shape[0] == self.waypoints.shape[0]\n        self.s_start = self.ss_waypoints[0]\n        self.s_end = self.ss_waypoints[-1]\n\n        self.uspl = []\n        for i in range(self.dof):\n            self.uspl.append(\n                UnivariateSpline(self.ss_waypoints, self.waypoints[:, i]))\n        self.uspld = [spl.derivative() for spl in self.uspl]\n        self.uspldd = [spl.derivative() for spl in self.uspld]\n\n    def get_duration(self):\n        return self.duration\n\n    def eval(self, ss_sam):\n        data = []\n        for spl in self.uspl:\n            data.append(spl(ss_sam))\n        return np.array(data).T\n\n    def evald(self, ss_sam):\n        data = []\n        for spl in self.uspld:\n            data.append(spl(ss_sam))\n        return np.array(data).T\n\n    def evaldd(self, ss_sam):\n        data = []\n        for spl in self.uspldd:\n            data.append(spl(ss_sam))\n        return np.array(data).T\n\n\nclass PolynomialPath(Interpolator):\n    \"\"\" A class representing polynominal paths.\n\n    If coeff is a 1d array, the polynomial's equation is given by\n\n    .. math::\n\n    coeff[0] + coeff[1] s + coeff[2] s^2 + ...\n\n    If coeff is a 2d array, the i-th joint position is the polynomial\n\n    .. math::\n\n    coeff[i, 0] + coeff[i, 1] s + coeff[i, 2] s^2 + ...\n    \"\"\"\n\n    def __init__(self, coeff, s_start=0.0, s_end=1.0):\n        # type: (np.ndarray, float, float) -> None\n        \"\"\"Initialize the polynomial path.\n\n        Parameters\n        ----------\n        coeff\n            Coefficients of the polynomials.\n        s_start\n            Starting path position.\n        s_end\n            Ending path position.\n        \"\"\"\n        super(PolynomialPath, self).__init__()\n        self.coeff = np.array(coeff)\n        self.s_end = s_end\n        self.s_start = s_start\n        if np.isscalar(self.coeff[0]):\n            self.poly = [np.polynomial.Polynomial(self.coeff)]\n            self.coeff = self.coeff.reshape(1, -1)\n        else:\n            self.poly = [\n                np.polynomial.Polynomial(self.coeff[i])\n                for i in range(self.dof)\n            ]\n\n        self.polyd = [poly.deriv() for poly in self.poly]\n        self.polydd = [poly.deriv() for poly in self.polyd]\n\n    @property\n    def dof(self):\n        return self.coeff.shape[0]\n\n    @property\n    def duration(self):\n        return self.s_end - self.s_start\n\n    def get_duration(self):\n        warnings.warn(\"get_duration is deprecated, use duration\",\n                      PendingDeprecationWarning)\n        return self.duration\n\n    def get_dof(self):\n        warnings.warn(\"get_dof is deprecated, use dof\",\n                      PendingDeprecationWarning)\n        return self.dof\n\n    def eval(self, ss_sam):\n        res = [poly(np.array(ss_sam)) for poly in self.poly]\n        if self.dof == 1:\n            return np.array(res).flatten()\n        return np.array(res).T\n\n    def evald(self, ss_sam):\n        res = [poly(np.array(ss_sam)) for poly in self.polyd]\n        if self.dof == 1:\n            return np.array(res).flatten()\n        return np.array(res).T\n\n    def evaldd(self, ss_sam):\n        res = [poly(np.array(ss_sam)) for poly in self.polydd]\n        if self.dof == 1:\n            return np.array(res).flatten()\n        return np.array(res).T\n", "meta": {"hexsha": "867fc70bf09c94b749465d3e5f025225e9c155e4", "size": 17972, "ext": "py", "lang": "Python", "max_stars_repo_path": "toppra/interpolator.py", "max_stars_repo_name": "mrunaljsarvaiya/toppra", "max_stars_repo_head_hexsha": "468d81d23f37fdee06ea1aa3f1d445d747fad7f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "toppra/interpolator.py", "max_issues_repo_name": "mrunaljsarvaiya/toppra", "max_issues_repo_head_hexsha": "468d81d23f37fdee06ea1aa3f1d445d747fad7f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toppra/interpolator.py", "max_forks_repo_name": "mrunaljsarvaiya/toppra", "max_forks_repo_head_hexsha": "468d81d23f37fdee06ea1aa3f1d445d747fad7f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3101045296, "max_line_length": 92, "alphanum_fraction": 0.5715557534, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.33111975283019596, "lm_q1q2_score": 0.1720237717147937}}
{"text": "# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Vision Transformer implementation.\"\"\"\n\nfrom importlib import import_module\nfrom easydict import EasyDict as edict\nimport numpy as np\n\nimport mindspore\nfrom mindspore.common.initializer import initializer\nfrom mindspore.common.parameter import Parameter\nfrom mindspore.nn import Cell, Dense, Dropout, SequentialCell\nfrom mindspore.ops import operations as P\nimport mindspore.common.dtype as mstype\nfrom mindspore import Tensor\n\nMIN_NUM_PATCHES = 4\n\nclass VitConfig:\n    \"\"\"\n    VitConfig\n    \"\"\"\n    def __init__(self, configs):\n        self.configs = configs\n\n        # network init\n        self.network_norm = mindspore.nn.LayerNorm((configs.normalized_shape,))\n        self.network_init = mindspore.common.initializer.Normal(sigma=1.0)\n        self.network_dropout_rate = 0.1\n        self.network_pool = 'cls'\n        self.network = ViT\n\n        # stem\n        self.stem_init = mindspore.common.initializer.XavierUniform()\n        self.stem = VitStem\n\n        # body\n        self.body_norm = mindspore.nn.LayerNorm\n        self.body_drop_path_rate = 0.1\n        self.body = Transformer\n\n        # body attention\n        self.attention_init = mindspore.common.initializer.XavierUniform()\n        self.attention_activation = mindspore.nn.Softmax()\n        self.attention_dropout_rate = 0.1\n        self.attention = Attention\n\n        # body feedforward\n        self.feedforward_init = mindspore.common.initializer.XavierUniform()\n        self.feedforward_activation = mindspore.nn.GELU()\n        self.feedforward_dropout_rate = 0.1\n        self.feedforward = FeedForward\n\n        # head\n        self.head = origin_head\n        self.head_init = mindspore.common.initializer.XavierUniform()\n        self.head_dropout_rate = 0.1\n        self.head_norm = mindspore.nn.LayerNorm((configs.normalized_shape,))\n        self.head_activation = mindspore.nn.GELU()\n\n\nclass DropPath(Cell):\n    \"\"\"Drop paths (Stochastic Depth) per sample  (when applied in main path of residual blocks).\n    \"\"\"\n\n    def __init__(self, drop_prob=None, seed=0):\n        super(DropPath, self).__init__()\n        self.keep_prob = 1 - drop_prob\n        seed = min(seed, 0) # always be 0\n        self.rand = P.UniformReal(seed=seed) # seed must be 0, if set to other value, it's not rand for multiple call\n        self.shape = P.Shape()\n        self.floor = P.Floor()\n\n    def construct(self, x):\n        if self.training:\n            x_shape = self.shape(x) # B N C\n            random_tensor = self.rand((x_shape[0], 1, 1))\n            random_tensor = random_tensor + self.keep_prob\n            random_tensor = self.floor(random_tensor)\n            x = x / self.keep_prob\n            x = x * random_tensor\n        return x\n\n\nclass BatchDense(Cell):\n    \"\"\"BatchDense module.\"\"\"\n\n    def __init__(self, in_features, out_features, initialization, has_bias=True):\n        super().__init__()\n        self.out_features = out_features\n        self.dense = Dense(in_features, out_features, has_bias=has_bias)\n        self.dense.weight.set_data(initializer(initialization, [out_features, in_features]))\n        self.reshape = P.Reshape()\n\n    def construct(self, x):\n        bs, seq_len, d_model = x.shape\n        out = self.reshape(x, (bs * seq_len, d_model))\n        out = self.dense(out)\n        out = self.reshape(out, (bs, seq_len, self.out_features))\n        return out\n\n\nclass ResidualCell(Cell):\n    \"\"\"Cell which implements x + f(x) function.\"\"\"\n    def __init__(self, cell):\n        super().__init__()\n        self.cell = cell\n\n    def construct(self, x, **kwargs):\n        return self.cell(x, **kwargs) + x\n\n\ndef pretrain_head(vit_config):\n    \"\"\"Head for ViT pretraining.\"\"\"\n    d_model = vit_config.configs.d_model\n    mlp_dim = vit_config.configs.mlp_dim\n    num_classes = vit_config.configs.num_classes\n\n    dropout_rate = vit_config.head_dropout_rate\n    initialization = vit_config.head_init\n    normalization = vit_config.head_norm\n    activation = vit_config.head_activation\n\n    dense1 = Dense(d_model, mlp_dim)\n    dense1.weight.set_data(initializer(initialization, [mlp_dim, d_model]))\n    dense2 = Dense(mlp_dim, num_classes)\n    dense2.weight.set_data(initializer(initialization, [num_classes, mlp_dim]))\n\n    return SequentialCell([\n        normalization,\n        dense1,\n        activation,\n        Dropout(keep_prob=(1. - dropout_rate)),\n        dense2])\n\n\ndef origin_head(vit_config):\n    \"\"\"Head for ViT pretraining.\"\"\"\n    d_model = vit_config.configs.d_model\n    num_classes = vit_config.configs.num_classes\n    initialization = vit_config.head_init\n    dense = Dense(d_model, num_classes)\n    dense.weight.set_data(initializer(initialization, [num_classes, d_model]))\n    return SequentialCell([dense])\n\n\nclass VitStem(Cell):\n    \"\"\"Stem layer for ViT.\"\"\"\n\n    def __init__(self, vit_config):\n        super().__init__()\n        d_model = vit_config.configs.d_model\n        patch_size = vit_config.configs.patch_size\n        image_size = vit_config.configs.image_size\n        initialization = vit_config.stem_init\n        channels = 3\n\n        assert image_size % patch_size == 0, 'Image dimensions must be divisible by the patch size.'\n        num_patches = (image_size // patch_size) ** 2\n        assert num_patches > MIN_NUM_PATCHES, f'your number of patches {num_patches} is too small'\n        patch_dim = channels * patch_size ** 2\n\n        self.patch_size = patch_size\n        self.reshape = P.Reshape()\n        self.transpose = P.Transpose()\n        self.patch_to_embedding = BatchDense(patch_dim, d_model, initialization, has_bias=True)\n\n    def construct(self, img):\n        p = self.patch_size\n        bs, channels, h, w = img.shape\n        x = self.reshape(img, (bs, channels, h // p, p, w // p, p))\n        x = self.transpose(x, (0, 2, 4, 1, 3, 5))\n        x = self.reshape(x, (bs, (h//p)*(w//p), channels*p*p))\n        x = self.patch_to_embedding(x)\n        return x\n\n\nclass ViT(Cell):\n    \"\"\"Vision Transformer implementation.\"\"\"\n\n    def __init__(self, vit_config):\n        super().__init__()\n\n        d_model = vit_config.configs.d_model\n        patch_size = vit_config.configs.patch_size\n        image_size = vit_config.configs.image_size\n\n        initialization = vit_config.network_init\n        pool = vit_config.network_pool\n        dropout_rate = vit_config.network_dropout_rate\n        norm = vit_config.network_norm\n\n        stem = vit_config.stem(vit_config)\n        body = vit_config.body(vit_config)\n        head = vit_config.head(vit_config)\n\n        assert pool in {'cls', 'mean'}, 'pool type must be either cls or mean'\n        num_patches = (image_size // patch_size) ** 2\n\n        if pool == \"cls\":\n            self.cls_token = Parameter(initializer(initialization, (1, 1, d_model)),\n                                       name='cls', requires_grad=True)\n            self.pos_embedding = Parameter(initializer(initialization, (1, num_patches + 1, d_model)),\n                                           name='pos_embedding', requires_grad=True)\n            self.tile = P.Tile()\n            self.cat_1 = P.Concat(axis=1)\n        else:\n            self.pos_embedding = Parameter(initializer(initialization, (1, num_patches, d_model)),\n                                           name='pos_embedding', requires_grad=True)\n            self.mean = P.ReduceMean(keep_dims=False)\n        self.pool = pool\n\n        self.cast = P.Cast()\n        self.dropout = Dropout(keep_prob=(1. - dropout_rate))\n        self.stem = stem\n        self.body = body\n        self.head = head\n        self.norm = norm\n\n    def construct(self, img):\n        x = self.stem(img)\n        bs, seq_len, _ = x.shape\n\n        if self.pool == \"cls\":\n            cls_tokens = self.tile(self.cls_token, (bs, 1, 1))\n            x = self.cat_1((cls_tokens, x)) # now x has shape = (bs, seq_len+1, d)\n            x += self.pos_embedding[:, :(seq_len + 1)]\n        else:\n            x += self.pos_embedding[:, :seq_len]\n\n        y = self.cast(x, mstype.float32)\n        y = self.dropout(y)\n        x = self.cast(y, x.dtype)\n\n        x = self.body(x)\n\n        if self.norm is not None:\n            x = self.norm(x)\n\n        if self.pool == \"cls\":\n            x = x[:, 0]\n        else:\n            x = self.mean(x, (-2,))\n\n        return self.head(x)\n\n\nclass Attention(Cell):\n    \"\"\"Attention layer implementation.\"\"\"\n\n    def __init__(self, vit_config):\n        super().__init__()\n        d_model = vit_config.configs.d_model\n        dim_head = vit_config.configs.dim_head\n        heads = vit_config.configs.heads\n\n        initialization = vit_config.attention_init\n        activation = vit_config.attention_activation\n        dropout_rate = vit_config.attention_dropout_rate\n\n        inner_dim = heads * dim_head\n        self.dim_head = dim_head\n        self.heads = heads\n        self.scale = Tensor([dim_head ** -0.5])\n\n        self.to_q = Dense(d_model, inner_dim, has_bias=True)\n        self.to_q.weight.set_data(initializer(initialization, [inner_dim, d_model]))\n        self.to_k = Dense(d_model, inner_dim, has_bias=True)\n        self.to_k.weight.set_data(initializer(initialization, [inner_dim, d_model]))\n        self.to_v = Dense(d_model, inner_dim, has_bias=True)\n        self.to_v.weight.set_data(initializer(initialization, [inner_dim, d_model]))\n\n        self.to_out = Dense(inner_dim, d_model, has_bias=True)\n        self.to_out.weight.set_data(initializer(initialization, [inner_dim, d_model]))\n        self.dropout = Dropout(1 - dropout_rate)\n\n        self.activation = activation\n\n        #auxiliary functions\n        self.reshape = P.Reshape()\n        self.transpose = P.Transpose()\n        self.cast = P.Cast()\n        self.mul = P.Mul()\n        self.q_matmul_k = P.BatchMatMul(transpose_b=True)\n        self.attn_matmul_v = P.BatchMatMul()\n        self.softmax_nz = True\n\n    def construct(self, x):\n        '''x size - BxNxd_model'''\n        bs, seq_len, d_model, h, d = x.shape[0], x.shape[1], x.shape[2], self.heads, self.dim_head\n\n        x_2d = self.reshape(x, (-1, d_model))\n        q, k, v = self.to_q(x_2d), self.to_k(x_2d), self.to_v(x_2d)\n\n        if self.softmax_nz:\n            q = self.reshape(q, (bs, seq_len, h, d))\n            q = self.transpose(q, (0, 2, 1, 3))\n            q = self.cast(q, mstype.float32)\n            q = self.mul(q, self.scale)\n\n            k = self.reshape(k, (bs, seq_len, h, d))\n            k = self.transpose(k, (0, 2, 1, 3))\n            v = self.reshape(v, (bs, seq_len, h, d))\n            v = self.transpose(v, (0, 2, 1, 3))\n\n            q = self.cast(q, k.dtype)\n            attn_scores = self.q_matmul_k(q, k) #bs x h x seq_len x seq_len\n            attn_scores = self.cast(attn_scores, x.dtype)\n            attn_scores = self.activation(attn_scores)\n        else:\n            q = self.reshape(q, (bs, seq_len, h, d))\n            q = self.transpose(q, (0, 2, 1, 3))\n            k = self.reshape(k, (bs, seq_len, h, d))\n            k = self.transpose(k, (0, 2, 1, 3))\n            v = self.reshape(v, (bs, seq_len, h, d))\n            v = self.transpose(v, (0, 2, 1, 3))\n\n            attn_scores = self.q_matmul_k(q, k) #bs x h x seq_len x seq_len\n            attn_scores = self.cast(attn_scores, mstype.float32)\n            attn_scores = self.mul(attn_scores, self.scale)\n            attn_scores = self.cast(attn_scores, x.dtype)\n            attn_scores = self.activation(attn_scores)\n\n        out = self.attn_matmul_v(attn_scores, v) #bs x h x seq_len x dim_head\n        out = self.transpose(out, (0, 2, 1, 3))\n        out = self.reshape(out, (bs*seq_len, h*d))\n        out = self.to_out(out)\n        out = self.reshape(out, (bs, seq_len, d_model))\n        #out = self.dropout(out)\n        y = self.cast(out, mstype.float32)\n        y = self.dropout(y)\n        out = self.cast(y, out.dtype)\n        #out = self.reshape(out, (bs, seq_len, d_model))\n        return out\n\n\nclass FeedForward(Cell):\n    \"\"\"FeedForward layer implementation.\"\"\"\n\n    def __init__(self, vit_config):\n        super().__init__()\n\n        d_model = vit_config.configs.d_model\n        hidden_dim = vit_config.configs.mlp_dim\n\n        initialization = vit_config.feedforward_init\n        activation = vit_config.feedforward_activation\n        dropout_rate = vit_config.feedforward_dropout_rate\n\n        self.ff1 = BatchDense(d_model, hidden_dim, initialization)\n        self.activation = activation\n        self.dropout = Dropout(keep_prob=1.-dropout_rate)\n        self.ff2 = BatchDense(hidden_dim, d_model, initialization)\n        self.cast = P.Cast()\n\n    def construct(self, x):\n        y = self.ff1(x)\n        y = self.cast(y, mstype.float32)\n        y = self.activation(y)\n        y = self.dropout(y)\n        y = self.cast(y, x.dtype)\n        y = self.ff2(y)\n        y = self.cast(y, mstype.float32)\n        y = self.dropout(y)\n        y = self.cast(y, x.dtype)\n        return y\n\n\nclass Transformer(Cell):\n    \"\"\"Transformer implementation.\"\"\"\n\n    def __init__(self, vit_config):\n        super().__init__()\n\n        depth = vit_config.configs.depth\n        drop_path_rate = vit_config.body_drop_path_rate\n\n        dpr = [x.item() for x in np.linspace(0, drop_path_rate, depth)]\n        att_seeds = [np.random.randint(1024) for _ in range(depth)]\n        mlp_seeds = [np.random.randint(1024) for _ in range(depth)]\n\n        layers = []\n        for i in range(depth):\n            normalization = vit_config.body_norm((vit_config.configs.normalized_shape,))\n            normalization2 = vit_config.body_norm((vit_config.configs.normalized_shape,))\n            attention = vit_config.attention(vit_config)\n            feedforward = vit_config.feedforward(vit_config)\n\n            if drop_path_rate > 0:\n                layers.append(\n                    SequentialCell([\n                        ResidualCell(SequentialCell([normalization,\n                                                     attention,\n                                                     DropPath(dpr[i], att_seeds[i])])),\n                        ResidualCell(SequentialCell([normalization2,\n                                                     feedforward,\n                                                     DropPath(dpr[i], mlp_seeds[i])]))\n                    ])\n                )\n            else:\n                layers.append(\n                    SequentialCell([\n                        ResidualCell(SequentialCell([normalization,\n                                                     attention])),\n                        ResidualCell(SequentialCell([normalization2,\n                                                     feedforward]))\n                    ])\n                )\n\n        self.layers = SequentialCell(layers)\n\n    def construct(self, x):\n        return self.layers(x)\n\n\ndef load_function(func_name):\n    \"\"\"Load function using its name.\"\"\"\n    modules = func_name.split(\".\")\n    if len(modules) > 1:\n        module_path = \".\".join(modules[:-1])\n        name = modules[-1]\n        module = import_module(module_path)\n        return getattr(module, name)\n    return func_name\n\n\nvit_cfg = edict({\n    'd_model': 768,\n    'depth': 12,\n    'heads': 12,\n    'mlp_dim': 3072,\n    'dim_head': 64,\n    'patch_size': 32,\n    'normalized_shape': 768,\n    'image_size': 224,\n    'num_classes': 1001,\n})\n\n\ndef vit_base_patch16(args):\n    \"\"\"vit_base_patch16\"\"\"\n    vit_cfg.d_model = 768\n    vit_cfg.depth = 12\n    vit_cfg.heads = 12\n    vit_cfg.mlp_dim = 3072\n    vit_cfg.dim_head = vit_cfg.d_model // vit_cfg.heads\n    vit_cfg.patch_size = 16\n    vit_cfg.normalized_shape = vit_cfg.d_model\n    vit_cfg.image_size = args.train_image_size\n    vit_cfg.num_classes = args.class_num\n\n    if args.vit_config_path != '':\n        print(\"get vit_config_path\")\n        vit_config = load_function(args.vit_config_path)(vit_cfg)\n    else:\n        print(\"get default_vit_cfg\")\n        vit_config = VitConfig(vit_cfg)\n\n    model = vit_config.network(vit_config)\n    return model\n\n\ndef vit_base_patch32(args):\n    \"\"\"vit_base_patch32\"\"\"\n    vit_cfg.d_model = 768\n    vit_cfg.depth = 12\n    vit_cfg.heads = 12\n    vit_cfg.mlp_dim = 3072\n    vit_cfg.dim_head = vit_cfg.d_model // vit_cfg.heads\n    vit_cfg.patch_size = 32\n    vit_cfg.normalized_shape = vit_cfg.d_model\n    vit_cfg.image_size = args.train_image_size\n    vit_cfg.num_classes = args.class_num\n\n    if args.vit_config_path != '':\n        print(\"get vit_config_path\")\n        vit_config = load_function(args.vit_config_path)(vit_cfg)\n    else:\n        print(\"get default_vit_cfg\")\n        vit_config = VitConfig(vit_cfg)\n\n    model = vit_config.network(vit_config)\n\n    return model\n\ndef get_network(backbone_name, args):\n    \"\"\"get_network\"\"\"\n    if backbone_name == 'vit_base_patch32':\n        backbone = vit_base_patch32(args=args)\n    elif backbone_name == 'vit_base_patch16':\n        backbone = vit_base_patch16(args=args)\n    else:\n        raise NotImplementedError\n    return backbone\n", "meta": {"hexsha": "876cb7c52eca6b80759b5db84d0d4762192320ff", "size": 17496, "ext": "py", "lang": "Python", "max_stars_repo_path": "official/cv/vit/src/vit.py", "max_stars_repo_name": "leelige/mindspore", "max_stars_repo_head_hexsha": "5199e05ba3888963473f2b07da3f7bca5b9ef6dc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-18T08:17:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T08:17:44.000Z", "max_issues_repo_path": "official/cv/vit/src/vit.py", "max_issues_repo_name": "leelige/mindspore", "max_issues_repo_head_hexsha": "5199e05ba3888963473f2b07da3f7bca5b9ef6dc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "official/cv/vit/src/vit.py", "max_forks_repo_name": "leelige/mindspore", "max_forks_repo_head_hexsha": "5199e05ba3888963473f2b07da3f7bca5b9ef6dc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-09-01T06:17:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-04T08:39:45.000Z", "avg_line_length": 34.5088757396, "max_line_length": 117, "alphanum_fraction": 0.6100823045, "include": true, "reason": "import numpy", "num_tokens": 4184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3311197462295937, "lm_q1q2_score": 0.1720237682856401}}
{"text": "from functools import partial\nfrom typing import Callable\n\nimport jax\nimport jax.numpy as jnp\nimport jax.random\nfrom jax import ops\nfrom jax.tree_util import tree_map\n\nfrom numpyro import handlers\nfrom numpyro.contrib.funsor import enum, config_enumerate\nfrom numpyro.distributions import Distribution\nfrom numpyro.distributions.transforms import IdentityTransform\nfrom numpyro.infer import NUTS, MCMC, VI\nfrom numpyro.infer.guide import ReinitGuide\nfrom numpyro.infer.kernels import SteinKernel\nfrom numpyro.infer.util import transform_fn, get_parameter_transform, _guess_max_plate_nesting\nfrom numpyro.util import ravel_pytree\n\n\n# TODO\n# Fix MCMC updates to work reasonably with optimizer\n\n\n# Lots of code based on SVI interface and commonalities should be refactored\nclass Stein(VI):\n\n    def __init__(self, model, guide: ReinitGuide, optim, loss, kernel_fn: SteinKernel, num_particles: int = 10,\n                 loss_temperature: float = 1.0, repulsion_temperature: float = 1.0,\n                 classic_guide_params_fn: Callable[[str], bool] = lambda name: False,\n                 enum=True, sp_mcmc_crit='infl',\n                 sp_mode='local', num_mcmc_particles: int = 0, num_mcmc_warmup: int = 100, num_mcmc_updates: int = 10,\n                 sampler_fn=NUTS, sampler_kwargs=None, mcmc_kwargs=None, **static_kwargs):\n        \"\"\"\n        Stein Variational Gradient Descent for Non-parametric Inference.\n        :param model: Python callable with Pyro primitives for the model.\n        :param guide: Python callable with Pyro primitives for the guide\n            (recognition network).\n        :param optim: an instance of :class:`~numpyro.optim._NumpyroOptim`.\n        :param loss: ELBO loss, i.e. negative Evidence Lower Bound, to minimize.\n        :param kernel_fn: Function that produces a logarithm of the statistical kernel to use with Stein inference\n        :param num_particles: number of particles for Stein inference.\n            (More particles capture more of the posterior distribution)\n        :param loss_temperature: scaling of loss factor\n        :param repulsion_temperature: scaling of repulsive forces (Non-linear Stein)\n        :param enum: whether to apply automatic marginalization of discrete variables\n        :param classic_guide_param_fn: predicate on names of parameters in guide which should be optimized classically without Stein (E.g., parameters for large normal networks or other transformation)\n        :param sp_mcmc_crit: Stein Point MCMC update selection criterion, either 'infl' for most influential or 'rand' for random (EXPERIMENTAL)\n        :param sp_mode: Stein Point MCMC mode for calculating Kernelized Stein Discrepancy. Either 'local' for only the updated MCMC particles or 'global' for all particles. (EXPERIMENTAL)\n        :param num_mcmc_particles: Number of particles that should be updated with Stein Point MCMC (should be a subset of number of Stein particles) (EXPERIMENTAL)\n        :param num_mcmc_warmup: Number of warmup steps for the MCMC sampler (EXPERIMENTAL)\n        :param num_mcmc_updates: Number of MCMC update steps at each iteration (EXPERIMENTAL)\n        :param sampler_fn: The MCMC sampling kernel used for the Stein Point MCMC updates (EXPERIMENTAL)\n        :param sampler_kwargs: Keyword arguments provided to the MCMC sampling kernel (EXPERIMENTAL)\n        :param mcmc_kwargs: Keyword arguments provided to the MCMC interface (EXPERIMENTAL)\n        :param static_kwargs: Static keyword arguments for the model / guide, i.e. arguments\n            that remain constant during fitting.\n        \"\"\"\n        super().__init__(model, guide, optim, loss, name='Stein', **static_kwargs)\n        assert sp_mcmc_crit == 'infl' or sp_mcmc_crit == 'rand'\n        assert sp_mode == 'local' or sp_mode == 'global'\n        assert 0 <= num_mcmc_particles <= num_particles\n\n        self._inference_model = model\n        self.model = model\n        self.guide = guide\n        self.optim = optim\n        self.loss = loss\n        self.kernel_fn = kernel_fn\n        self.static_kwargs = static_kwargs\n        self.num_particles = num_particles\n        self.loss_temperature = loss_temperature\n        self.repulsion_temperature = repulsion_temperature\n        self.enum = enum\n        self.classic_guide_params_fn = classic_guide_params_fn\n        self.sp_mcmc_crit = sp_mcmc_crit\n        self.sp_mode = sp_mode\n        self.num_mcmc_particles = num_mcmc_particles\n        self.num_mcmc_warmup = num_mcmc_warmup\n        self.num_mcmc_updates = num_mcmc_updates\n        self.sampler_fn = sampler_fn\n        self.sampler_kwargs = sampler_kwargs or dict()\n        self.mcmc_kwargs = mcmc_kwargs or dict()\n        self.mcmc: MCMC = None\n        self.guide_param_names = None\n        self.constrain_fn = None\n        self.uconstrain_fn = None\n        self.particle_transform_fn = None\n\n    def _apply_kernel(self, kernel, x, y, v):\n        if self.kernel_fn.mode == 'norm' or self.kernel_fn.mode == 'vector':\n            return kernel(x, y) * v\n        else:\n            return kernel(x, y) @ v\n\n    def _kernel_grad(self, kernel, x, y):\n        if self.kernel_fn.mode == 'norm':\n            return jax.grad(lambda x: kernel(x, y))(x)\n        elif self.kernel_fn.mode == 'vector':\n            return jax.vmap(lambda i: jax.grad(lambda x: kernel(x, y)[i])(x)[i])(jnp.arange(x.shape[0]))\n        else:\n            return jax.vmap(lambda l: jnp.sum(jax.vmap(lambda m: jax.grad(lambda x: kernel(x, y)[l, m])(x)[m])\n                                              (jnp.arange(x.shape[0]))))(jnp.arange(x.shape[0]))\n\n    def _param_size(self, param):\n        if isinstance(param, tuple) or isinstance(param, list):\n            return sum(map(self._param_size, param))\n        return param.size\n\n    def _calc_particle_info(self, uparams, num_particles):\n        uparam_keys = list(uparams.keys())\n        uparam_keys.sort()\n        start_index = 0\n        res = {}\n        for k in uparam_keys:\n            end_index = start_index + self._param_size(uparams[k]) // num_particles\n            res[k] = (start_index, end_index)\n            start_index = end_index\n        return res\n\n    def _svgd_loss_and_grads(self, rng_key, unconstr_params, *args, **kwargs):\n        # 0. Separate model and guide parameters, since only guide parameters are updated using Stein\n        classic_uparams = {p: v for p, v in unconstr_params.items() if\n                           p not in self.guide_param_names or self.classic_guide_params_fn(p)}\n        stein_uparams = {p: v for p, v in unconstr_params.items() if p not in classic_uparams}\n        # 1. Collect each guide parameter into monolithic particles that capture correlations\n        # between parameter values across each individual particle\n        stein_particles, unravel_pytree = ravel_pytree(stein_uparams, batch_dims=1)\n        unravel_pytree_batched = jax.vmap(unravel_pytree)\n        particle_info = self._calc_particle_info(stein_uparams, stein_particles.shape[0])\n\n        # 2. Calculate loss and gradients for each parameter\n        def scaled_loss(rng_key, classic_params, stein_params):\n            params = {**classic_params, **stein_params}\n            loss_val = self.loss.loss(rng_key, params, handlers.scale(self._inference_model, self.loss_temperature),\n                                      self.guide, *args, **kwargs)\n            return - loss_val\n\n        def kernel_particle_loss_fn(ps):\n            return scaled_loss(rng_key, self.constrain_fn(classic_uparams),\n                               self.constrain_fn(unravel_pytree(ps)))\n\n        def particle_transform_fn(particle):\n            params = unravel_pytree(particle)\n            tparams = self.particle_transform_fn(params)\n            tparticle, _ = ravel_pytree(tparams)\n            return tparticle\n\n        tstein_particles = jax.vmap(particle_transform_fn)(stein_particles)\n\n        loss, particle_ljp_grads = jax.vmap(jax.value_and_grad(kernel_particle_loss_fn))(tstein_particles)\n        classic_param_grads = jax.vmap(lambda ps: jax.grad(lambda cps:\n                                                           scaled_loss(rng_key, self.constrain_fn(cps),\n                                                                       self.constrain_fn(unravel_pytree(ps))))(\n            classic_uparams))(stein_particles)\n        classic_param_grads = tree_map(partial(jnp.mean, axis=0), classic_param_grads)\n\n        # 3. Calculate kernel on monolithic particle\n        kernel = self.kernel_fn.compute(stein_particles, particle_info, kernel_particle_loss_fn)\n\n        # 4. Calculate the attractive force and repulsive force on the monolithic particles\n        attractive_force = jax.vmap(lambda y: jnp.sum(\n            jax.vmap(lambda x, x_ljp_grad: self._apply_kernel(kernel, x, y, x_ljp_grad))(tstein_particles,\n                                                                                         particle_ljp_grads), axis=0))(\n            tstein_particles)\n        repulsive_force = jax.vmap(lambda y: jnp.sum(\n            jax.vmap(lambda x: self.repulsion_temperature * self._kernel_grad(kernel, x, y))(tstein_particles),\n            axis=0))(\n            tstein_particles)\n\n        def single_particle_grad(particle, att_force, rep_force):\n            reparam_jac = jax.jacfwd(particle_transform_fn)(particle)\n            return (att_force + rep_force) @ reparam_jac\n\n        particle_grads = jax.vmap(single_particle_grad)(stein_particles, attractive_force,\n                                                        repulsive_force) / self.num_particles\n\n        # 5. Decompose the monolithic particle forces back to concrete parameter values\n        stein_param_grads = unravel_pytree_batched(particle_grads)\n\n        # 6. Return loss and gradients (based on parameter forces)\n        res_grads = tree_map(lambda x: -x, {**classic_param_grads, **stein_param_grads})\n        return -jnp.mean(loss), res_grads\n\n    def _score_sp_mcmc(self, rng_key, subset_idxs, stein_uparams, sp_mcmc_subset_uparams, classic_uparams,\n                       *args, **kwargs):\n        if self.sp_mode == 'local':\n            _, ksd = self._svgd_loss_and_grads(rng_key, {**sp_mcmc_subset_uparams, **classic_uparams}, *args, **kwargs)\n        else:\n            stein_uparams = {p: ops.index_update(v, subset_idxs, sp_mcmc_subset_uparams[p]) for p, v in\n                             stein_uparams.items()}\n            _, ksd = self._svgd_loss_and_grads(rng_key, {**stein_uparams, **classic_uparams}, *args, **kwargs)\n        ksd_res = jnp.sum(jnp.concatenate([jnp.ravel(v) for v in ksd.values()]))\n        return ksd_res\n\n    def _sp_mcmc(self, rng_key, unconstr_params, *args, **kwargs):\n        # 0. Separate classical and stein parameters\n        classic_uparams = {p: v for p, v in unconstr_params.items() if\n                           p not in self.guide_param_names or self.classic_guide_params_fn(p)}\n        stein_uparams = {p: v for p, v in unconstr_params.items() if p not in classic_uparams}\n\n        # 1. Run warmup on a subset of particles to tune the MCMC state\n        warmup_key, mcmc_key = jax.random.split(rng_key)\n        sampler = self.sampler_fn(\n            potential_fn=lambda params: self.loss.loss(warmup_key, {**params, **self.constrain_fn(classic_uparams)},\n                                                       self._inference_model, self.guide, *args, **kwargs))\n        mcmc = MCMC(sampler, self.num_mcmc_warmup, self.num_mcmc_updates, num_chains=self.num_mcmc_particles,\n                    progress_bar=False, chain_method='vectorized',\n                    **self.mcmc_kwargs)\n        stein_params = self.constrain_fn(stein_uparams)\n        stein_subset_params = {p: v[0:self.num_mcmc_particles] for p, v in stein_params.items()}\n        mcmc.warmup(warmup_key, *args, init_params=stein_subset_params, **kwargs)\n\n        # 2. Choose MCMC particles\n        mcmc_key, choice_key = jax.random.split(mcmc_key)\n        if self.num_mcmc_particles == self.num_particles:\n            idxs = jnp.arange(self.num_particles)\n        else:\n            if self.sp_mcmc_crit == 'rand':\n                idxs = jax.random.shuffle(choice_key, jnp.arange(self.num_particles))[:self.num_mcmc_particles]\n            elif self.sp_mcmc_crit == 'infl':\n                _, grads = self._svgd_loss_and_grads(choice_key, unconstr_params, *args, **kwargs)\n                ksd = jnp.linalg.norm(\n                    jnp.concatenate([jnp.reshape(grads[p], (self.num_particles, -1)) for p in stein_uparams.keys()],\n                                    axis=-1),\n                    ord=2, axis=-1)\n                idxs = jnp.argsort(ksd)[:self.num_mcmc_particles]\n            else:\n                assert False, \"Unsupported SP MCMC criterion: {}\".format(self.sp_mcmc_crit)\n\n        # 3. Run MCMC on chosen particles\n        stein_params = self.constrain_fn(stein_uparams)\n        stein_subset_params = {p: v[idxs] for p, v in stein_params.items()}\n        mcmc.run(mcmc_key, *args, init_params=stein_subset_params, **kwargs)\n        samples_subset_stein_params = mcmc.get_samples(group_by_chain=True)\n        sss_uparams = self.uconstrain_fn(samples_subset_stein_params)\n\n        # 4. Select best MCMC iteration to update particles\n        scores = jax.vmap(\n            lambda i: self._score_sp_mcmc(mcmc_key, idxs, stein_uparams, {p: v[:, i] for p, v in sss_uparams.items()},\n                                          classic_uparams, *args, **kwargs))(jnp.arange(self.num_mcmc_particles))\n        mcmc_idx = jnp.argmax(scores)\n        stein_uparams = {p: ops.index_update(v, idxs, sss_uparams[p][:, mcmc_idx]) for p, v in stein_uparams.items()}\n        return {**stein_uparams, **classic_uparams}\n\n    def init(self, rng_key, *args, **kwargs):\n        \"\"\"\n        :param jax.random.PRNGKey rng_key: random number generator seed.\n        :param args: arguments to the model / guide (these can possibly vary during\n            the course of fitting).\n        :param kwargs: keyword arguments to the model / guide (these can possibly vary\n            during the course of fitting).\n        :return: initial :data:`CurrentState`\n        \"\"\"\n        rng_key, model_seed, guide_seed = jax.random.split(rng_key, 3)\n        model_init = handlers.seed(self.model, model_seed)\n        guide_init = handlers.seed(self.guide, guide_seed)\n        guide_trace = handlers.trace(guide_init).get_trace(*args, **kwargs, **self.static_kwargs)\n        model_trace = handlers.trace(model_init).get_trace(*args, **kwargs, **self.static_kwargs)\n        rng_key, particle_seed = jax.random.split(rng_key)\n        particle_seeds = jax.random.split(particle_seed, num=self.num_particles)\n        self.guide.find_params(particle_seeds, *args, **kwargs,\n                               **self.static_kwargs)  # Get parameter values for each particle\n        guide_init_params = self.guide.init_params()\n        params = {}\n        transforms = {}\n        inv_transforms = {}\n        particle_transforms = {}\n        guide_param_names = set()\n        should_enum = False\n        for site in model_trace.values():\n            if isinstance(site['fn'], Distribution) and site['fn'].is_discrete:\n                if site['fn'].has_enumerate_support and self.enum:\n                    should_enum = True\n                else:\n                    raise Exception(\"Cannot enumerate model with discrete variables without enumerate support\")\n        # NB: params in model_trace will be overwritten by params in guide_trace\n        for site in list(model_trace.values()) + list(guide_trace.values()):\n            if site['type'] == 'param':\n                transform = get_parameter_transform(site)\n                inv_transforms[site['name']] = transform\n                transforms[site['name']] = transform.inv\n                particle_transforms[site['name']] = site.get('particle_transform', IdentityTransform())\n                if site['name'] in guide_init_params:\n                    pval, _ = guide_init_params[site['name']]\n                    if self.classic_guide_params_fn(site['name']):\n                        pval = tree_map(lambda x: x[0], pval)\n                else:\n                    pval = site['value']\n                params[site['name']] = transform.inv(pval)\n                if site['name'] in guide_trace:\n                    guide_param_names.add(site['name'])\n\n        if should_enum:\n            mpn = _guess_max_plate_nesting(model_trace)\n            self._inference_model = enum(config_enumerate(self.model), - mpn - 1)\n        self.guide_param_names = guide_param_names\n        self.constrain_fn = partial(transform_fn, inv_transforms)\n        self.uconstrain_fn = partial(transform_fn, transforms)\n        self.particle_transform_fn = partial(transform_fn, particle_transforms)\n        return VI.CurrentState(self.optim.init(params), rng_key)\n\n    def get_params(self, state):\n        \"\"\"\n        Gets values at `param` sites of the `model` and `guide`.\n        :param svi_state: current state of the optimizer.\n        \"\"\"\n        params = self.constrain_fn(self.optim.get_params(state.optim_state))\n        return params\n\n    def update(self, state, *args, **kwargs):\n        \"\"\"\n        Take a single step of Stein (possibly on a batch / minibatch of data),\n        using the optimizer.\n        :param state: current state of Stein.\n        :param args: arguments to the model / guide (these can possibly vary during\n            the course of fitting).\n        :param kwargs: keyword arguments to the model / guide (these can possibly vary\n            during the course of fitting).\n        :return: tuple of `(state, loss)`.\n        \"\"\"\n        rng_key, rng_key_mcmc, rng_key_step = jax.random.split(state.rng_key, num=3)\n        params = self.optim.get_params(state.optim_state)\n        # Run Stein Point MCMC\n        if self.num_mcmc_particles > 0:\n            new_params = self._sp_mcmc(rng_key_mcmc, params, *args, **kwargs, **self.static_kwargs)\n            grads = {p: new_params[p] - params[p] for p in params}\n            optim_state = self.optim.update(grads, state.optim_state)\n            params = self.optim.get_params(state.optim_state)\n        else:\n            optim_state = state.optim_state\n        loss_val, grads = self._svgd_loss_and_grads(rng_key_step, params,\n                                                    *args, **kwargs, **self.static_kwargs)\n        optim_state = self.optim.update(grads, optim_state)\n        return VI.CurrentState(optim_state, rng_key), loss_val\n\n    def evaluate(self, state, *args, **kwargs):\n        \"\"\"\n        Take a single step of Stein (possibly on a batch / minibatch of data).\n        :param state: current state of Stein.\n        :param args: arguments to the model / guide (these can possibly vary during\n            the course of fitting).\n        :param kwargs: keyword arguments to the model / guide.\n        :return: evaluate loss given the current parameter values (held within `state.optim_state`).\n        \"\"\"\n        # we split to have the same seed as `update_fn` given a state\n        _, rng_key_eval = jax.random.split(state.rng_key)\n        params = self.optim.get_params(state.optim_state)\n        loss_val, _ = self._svgd_loss_and_grads(rng_key_eval, params,\n                                                *args, **kwargs, **self.static_kwargs)\n        return loss_val\n\n    def predict(self, state, *args, num_samples=1, **kwargs):\n        _, rng_key_predict = jax.random.split(state.rng_key)\n        params = self.get_params(state)\n        classic_params = {p: v for p, v in params.items() if\n                          p not in self.guide_param_names or self.classic_guide_params_fn(p)}\n        stein_params = {p: v for p, v in params.items() if p not in classic_params}\n        if num_samples == 1:\n            return jax.vmap(lambda sp: self._predict_model(rng_key_predict, {**sp, **classic_params}, *args, **kwargs)\n                            )(stein_params)\n        else:\n            return jax.vmap(lambda rk: jax.vmap(lambda sp: self._predict_model(rk, {**sp, **classic_params},\n                                                                               *args, **kwargs)\n                                                )(stein_params))(jax.random.split(rng_key_predict, num_samples))\n", "meta": {"hexsha": "1a694a92ee2c6ac72d0334bc276de87a7f9b9b56", "size": 20231, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpyro/infer/stein.py", "max_stars_repo_name": "ahmadsalim/numpyro", "max_stars_repo_head_hexsha": "015c80ddd24cf6bc89006fc3a70b424fecd09331", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-08-25T14:31:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-26T02:23:08.000Z", "max_issues_repo_path": "numpyro/infer/stein.py", "max_issues_repo_name": "ahmadsalim/numpyro", "max_issues_repo_head_hexsha": "015c80ddd24cf6bc89006fc3a70b424fecd09331", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpyro/infer/stein.py", "max_forks_repo_name": "ahmadsalim/numpyro", "max_forks_repo_head_hexsha": "015c80ddd24cf6bc89006fc3a70b424fecd09331", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-11T10:08:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-11T10:08:27.000Z", "avg_line_length": 55.2759562842, "max_line_length": 201, "alphanum_fraction": 0.6405021996, "include": true, "reason": "from numpy,import jax,from jax", "num_tokens": 4675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.28457601028405616, "lm_q1q2_score": 0.17186451172526723}}
{"text": "import matplotlib\nimport matplotlib.pyplot as plt\nimport os\nimport pdb\nimport pickle\nimport copy\nimport scipy.signal\nimport scipy.interpolate\nimport numpy as np\nfrom astropy.modeling import models, fitting\nfrom astropy.nddata import CCDData, StdDevUncertainty\nfrom astropy.io import ascii, fits\nfrom astropy.convolution import convolve, Box1DKernel, Box2DKernel\nimport pyvista\nfrom pyvista import image\nfrom pyvista import tv\nfrom tools import plots\n\nROOT = os.path.dirname(os.path.abspath(__file__)) + '/../../'\n\n\nclass SpecData(CCDData) :\n    \"\"\" Class to include a wavelength array on top of CCDData, with simple read/write/plot methods\n    \"\"\"\n    def __init__(self,data,wave=None) :\n        if type(data) is str :\n            hdulist=fits.open(data)\n            self.meta = hdulist[0].header\n            self.unit = hdulist[0].header['BUNIT']\n            self.data = hdulist[1].data\n            self.uncertainty = StdDevUncertainty(hdulist[2].data)\n            self.mask = hdulist[3].data\n            self.wave = hdulist[4].data\n        elif type(data) is CCDData :\n            self.unit = data.unit\n            self.meta = data.meta\n            self.data = data.data\n            self.uncertainty = data.uncertainty\n            self.mask = data.mask\n            self.wave = wave\n        else :\n            print('Input must be a filename or CCDData object')\n\n    def write(self,file,overwrite=True) :\n        hdulist=fits.HDUList()\n        hdulist.append(fits.PrimaryHDU(header=self.meta))\n        hdulist.append(fits.ImageHDU(self.data))\n        hdulist.append(fits.ImageHDU(self.uncertainty.array))\n        hdulist.append(fits.ImageHDU(self.mask.astype(np.int16)))\n        hdulist.append(fits.ImageHDU(self.wave))\n        hdulist.writeto(file,overwrite=overwrite)\n\n    def plot(self,ax,**kwargs) :\n        for row in range(self.wave.shape[0]) :\n            gd = np.where(self.mask[row,:] == False)[0]\n            plots.plotl(ax,self.wave[row,gd],self.data[row,gd],**kwargs)\n        \n\n\ndef get_wavecal(file) :\n    \"\"\" load a wavecal object from disk file \n    \"\"\"\n    with open(file,'rb') as wavecal :\n        return pickle.load(wavecal) \n\nclass WaveCal() :\n    \"\"\" Class for wavelength solutions\n    \"\"\"\n    def __init__ (self,type='chebyshev',degree=2,ydegree=2,pix0=0,orders=[1]) :\n        \"\"\" Initialize the wavecal object\n\n            type : type of solution ('poly' or 'chebyshev')\n            degree : polynomial degree for wavelength\n            ydegree : polynomial degree for  y dimension\n            pix0 : reference pixel\n            orders : spectral order for each row\n            spectrum : spectrum from which fit is derived\n        \"\"\"\n        self.type = type\n        self.degree = degree\n        self.ydegree = ydegree\n        self.pix0 = pix0\n        self.orders = orders\n        self.waves = None\n        self.x = None\n        self.y = None\n        self.weights = None\n        self.model = None\n        self.ax = None\n\n    def wave(self,pixels=None,image=None) :\n        \"\"\" Wavelength from pixel using wavelength solution model\n\n            pix : input pixel positions [x] or [y,x]\n            image : for input image size [nrows,ncols], return wavelengths at all pixels\n            returns wavelength\n        \"\"\"\n        if pixels is not None :\n            out=np.zeros(len(pixels[0]))\n            for i,pixel in enumerate(pixels[0]) :\n                if self.type.find('2D') > 0 :\n                    order=self.orders[pixels[1][i]]\n                    out[i]=self.model(pixel-self.pix0,pixels[1][i])/order\n                else :\n                    out[i]=self.model(pixel-self.pix0)/self.orders[0]\n            return out\n        else :\n            out=np.zeros(image)\n            cols=np.arange(out.shape[-1])\n            if out.ndim == 2 :\n                for row in range(out.shape[0]) : \n                    rows=np.zeros(len(cols))+row\n                    try : order = self.orders[row]\n                    except : order=self.orders[0]\n                    out[row,:] = self.model(cols-self.pix0,rows)/order\n            else :\n                out= self.model(cols-self.pix0)/self.orders[0]\n            return out\n\n    def getmod(self) :\n        \"\"\" Return model for current attributes\n        \"\"\"\n\n        if self.type == 'poly' :\n            mod=models.Polynomial1D(degree=self.degree)\n        elif self.type == 'chebyshev' :\n            mod=models.Chebyshev1D(degree=self.degree)\n        elif self.type == 'chebyshev2D' :\n            sz=self.spectrum.data.shape\n            mod=models.Chebyshev2D(x_degree=self.degree,y_degree=self.ydegree,\n                                   x_domain=[0,sz[1]],y_domain=[0,sz[0]])\n        else :\n            raise ValueError('unknown fitting type: '+self.type)\n            return\n        return mod\n\n    def fit(self,plot=True) :\n        \"\"\" do a wavelength fit \n        \"\"\"\n        print(\"doing wavelength fit\")\n        # set up fitter and model\n        twod='2D' in self.type\n        fitter=fitting.LinearLSQFitter()\n        mod = self.getmod()\n\n        if not hasattr(self,'ax') : self.ax = None\n        if twod :\n            nold=-1\n            nbd=0\n            while nbd != nold :\n                nold=nbd\n                self.model=fitter(mod,self.pix-self.pix0,self.y,self.waves*self.waves_order,weights=self.weights)\n                diff=self.waves-self.wave(pixels=[self.pix,self.y])\n                gd = np.where(self.weights > 0)[0]\n                print('  rms: {:8.3f}'.format(diff[gd].std()))\n                bd = np.where(abs(diff) > 3*diff.std())[0]\n                nbd = len(bd)\n                print('rejecting {:d} points from {:d} total: '.format(nbd,len(self.waves)))\n                self.weights[bd] = 0.\n\n            if self.ax is not None : \n                self.ax[1].cla()\n                scat=self.ax[1].scatter(self.waves,diff,marker='o',c=self.y,s=2)\n                scat=self.ax[1].scatter(self.waves[bd],diff[bd],marker='o',c='r',s=2)\n                xlim=self.ax[1].get_xlim()\n                self.ax[1].set_ylim(diff.min()-0.5,diff.max()+0.5)\n                self.ax[1].plot(xlim,[0,0],linestyle=':')\n                self.ax[1].text(0.1,0.9,'rms: {:8.3f}'.format(diff[gd].std()),transform=self.ax[1].transAxes)\n                cb_ax = self.fig.add_axes([0.94,0.05,0.02,0.4])\n                cb = self.fig.colorbar(scat,cax=cb_ax)\n                cb.ax.set_ylabel('Row')\n                plt.draw()\n                self.fig.canvas.draw_idle()\n                input('  See 2D wavecal fit. Hit any key to continue....')\n\n        else :\n            self.model=fitter(mod,self.pix-self.pix0,self.waves*self.waves_order,weights=self.weights)\n            diff=self.waves-self.wave(pixels=[self.pix])\n            print('  rms: {:8.3f} Angstroms'.format(diff.std()))\n            if self.ax is not None :\n                # iterate allowing for interactive removal of points\n                done = False\n                ymax = self.ax[0].get_ylim()[1]\n                while not done :\n\n                    # do fit\n                    gd=np.where(self.weights>0.)[0]\n                    bd=np.where(self.weights<=0.)[0]\n                    self.model=fitter(mod,self.pix[gd]-self.pix0,self.waves[gd]*self.waves_order[gd],weights=self.weights[gd])\n                    diff=self.waves-self.wave(pixels=[self.pix])\n                    print('  rms: {:8.3f} Anstroms'.format(diff[gd].std()))\n\n                    # replot spectrum with new fit wavelength scale\n                    self.ax[0].cla()\n                    self.ax[0].plot(self.wave(image=self.spectrum.data.shape)[0,:],self.spectrum.data[0,:])\n                    # plot residuals\n                    self.ax[1].cla()\n                    self.ax[1].plot(self.waves[gd],diff[gd],'go')\n                    self.ax[1].text(0.1,0.9,'rms: {:8.3f} Angstroms'.format(diff[gd].std()),transform=self.ax[1].transAxes)\n                    self.ax[1].set_xlabel('Wavelength')\n                    self.ax[1].set_ylabel('obs wave - fit wave')\n                    if len(bd) > 0 : self.ax[1].plot(self.waves[bd],diff[bd],'ro')\n                    self.ax[1].set_ylim(diff[gd].min()-0.5,diff[gd].max()+0.5)\n                    for i in range(len(self.pix)) :\n                        self.ax[1].text(self.waves[i],diff[i],'{:2d}'.format(i),va='top',ha='center')\n                        if self.weights[i] > 0 :\n                            self.ax[0].plot([self.waves[i],self.waves[i]],[0,ymax],'g')\n                        else :\n                            self.ax[0].plot([self.waves[i],self.waves[i]],[0,ymax],'r')\n                    plt.draw()\n\n                    # get input from user on lines to remove\n                    for i in range(len(self.pix)) :\n                        print('{:3d}{:8.2f}{:8.2f}{:8.2f}{:8.2f}'.format(\n                               i, self.pix[i], self.waves[i], diff[i], self.weights[i]))\n                    i = input('  enter ID of line to remove (-n for all lines<n, +n for all lines>n, O for new degree, return to continue): ')\n                    if i == '' :\n                        done = True\n                    elif i == 'O' :\n                        print('  current degree of fit: {:d}'.format(self.degree))\n                        self.degree = int(input('  enter new degree of fit: '))\n                        mod = self.getmod()\n                    elif '+' in i :\n                        self.weights[int(i)+1:] = 0.\n                    elif '-' in i :\n                        self.weights[0:abs(int(i))] = 0.\n                    elif int(i) >= 0 :\n                        self.weights[int(i)] = 0.\n                    else :\n                        print('invalid input')\n\n    def set_spectrum(self,spectrum) :\n        \"\"\" Set spectrum used to derive fit\n        \"\"\"\n        self.spectrum = np.atleast_2d(spectrum)\n\n    def get_spectrum(self) :\n        \"\"\" Set spectrum used to derive fit\n        \"\"\"\n        return self.spectrum \n\n    def identify(self,spectrum,file=None,wav=None,wref=None,disp=None,display=None,plot=None,rad=5,thresh=10,\n                 xmin=None, xmax=None, lags=range(-300,300), nskip=1) :\n        \"\"\" Given some estimate of wavelength solution and file with lines,\n            identify peaks and centroid\n        \"\"\"\n\n        sz=spectrum.shape\n        if len(sz) == 1 : \n            spectrum.data = np.atleast_2d(spectrum.data)\n            spectrum.uncertainty.array = np.atleast_2d(spectrum.uncertainty.array)\n            sz=spectrum.shape\n        if xmin is None : xmin=0\n        if xmax is None : xmax=sz[-1]\n        nrow=sz[0]\n\n        # get initial reference wavelengths if not given\n        if wav is None :\n            pix=np.arange(sz[-1])\n            if self.spectrum is not None :\n                # cross correlate with reference image to get pixel shift\n                print('  cross correlating with reference spectrum using lags: ', lags)\n                fitpeak,shift = image.xcorr(self.spectrum.data,spectrum.data,lags)\n                if shift.ndim == 1 :\n                    pixshift=(fitpeak+lags[0])[0]\n                    print('  Derived pixel shift from input wcal: ',fitpeak+lags[0])\n                    if display is not None :\n                        display.plotax1.cla()\n                        display.plotax1.text(0.05,0.95,'spectrum and reference',transform=display.plotax1.transAxes)\n                        for row in range(spectrum.data.shape[0]) :\n                            display.plotax1.plot(spectrum.data[row,:],color='m')\n                            display.plotax1.plot(self.spectrum.data[row,:],color='g')\n                        display.plotax1.set_xlabel('Pixel')\n                        display.plotax2.cla()\n                        display.plotax2.text(0.05,0.95,'cross correlation: {:8.3f}'.format(pixshift),\n                                             transform=display.plotax2.transAxes)\n                        display.plotax2.plot(lags,shift)\n                        display.plotax1.set_xlabel('Lag')\n                        plt.draw()\n                        input(\"  See spectrum and template spectrum (top), cross corrleation(bottom). hit any key to continue\")\n                    # single shift for all pixels\n                    self.pix0 = self.pix0+fitpeak+lags[0]\n                    wav=np.atleast_2d(self.wave(image=np.array(sz)))\n                else :\n                    # different shift for each row\n                    wav=np.zeros(sz)\n                    cols = np.arange(sz[-1])\n                    orders=[]\n                    for row in range(wav.shape[0]) : \n                        print('  Derived pixel shift from input wcal for row: {:d} {:d}'.format\n                               (row,shift[row,:].argmax()+lags[0]),end='\\r')\n                        rows=np.zeros(len(cols))+row\n                        try : order = self.orders[row]\n                        except : order=self.orders[0]\n                        orders.append(order)\n                        pix0 = self.pix0+fitpeak[row]+lags[0]\n                        wav[row,:] = self.model(cols-pix0)/order\n                    # ensure we have 2D fit\n                    self.type = 'chebyshev2D'\n                    self.orders = orders\n                    print(\"\")\n            else :\n                # get dispersion guess from header cards if not given in disp\n                if disp is None: disp=hd.header['DISPDW']\n                if wref is not None :\n                    w0=wref[0]\n                    pix0=wref[1]\n                else:\n                    w0=hd.header['DISPWC']\n                    pix0=sz[1]/2 \n                wav=np.atleast_2d(w0+(pix-pix0)*disp)\n\n        # open file with wavelengths and read\n        if file is not None :\n            f=open(ROOT+'/data/lamps/'+file,'r')\n            lines=[]\n            for line in f :\n                if line[0] != '#' :\n                    w=float(line.split()[0])\n                    # if we have microns, convert to Angstroms\n                    if w<10 : w*=10000\n                    if w > wav.min() and w < wav.max() : lines.append(w)\n            lines=np.array(lines)\n            f.close()\n        else :\n            lines = self.waves\n            weights = self.weights\n            gd = np.where(weights >0)[0]\n            lines = lines[gd]\n\n        # get centroid around expected lines\n        x=[]\n        y=[]\n        waves=[]\n        waves_order=[]\n        weight=[]\n        diff=[]\n        if display is not None and  isinstance(display,pyvista.tv.TV) :\n            display.ax.cla()\n            display.ax.axis('off')\n            display.tv(spectrum.data)\n        if plot is not None : \n            if type(plot) is matplotlib.figure.Figure :\n                plot.clf()\n                plt.draw()\n                ax1=plot.add_subplot(2,1,1) \n                ax2=plot.add_subplot(2,1,2,sharex=ax1) \n                plot.subplots_adjust(left=0.05,right=0.92, hspace=1.05)\n                ax=[ax1,ax2]\n                self.fig = plot\n                self.ax = ax\n            else :\n                fig,ax = plt.subplots(2,1,sharex=True,figsize=(14,7))\n                fig.subplots_adjust(hspace=1.05)\n                self.fig = fig\n                self.ax = ax\n\n        if plot is not None : ax[0].cla()\n        for row in range(0,nrow,nskip) :\n            print('  identifying lines in row: ', row,end='\\r')\n            if plot is not None :\n                ax[0].plot(wav[row,:],spectrum.data[row,:])\n                #ax[0].set_yscale('log')\n                ax[0].set_ylim(1.,ax[0].get_ylim()[1])\n                ax[0].text(0.1,0.9,'row: {:d}'.format(row),transform=ax[0].transAxes)\n                ax[0].set_xlabel('Rough wavelength')\n                ax[0].set_ylabel('Intensity')\n            for line in lines :\n                peak=abs(line-wav[row,:]).argmin()\n                if isinstance(display,pyvista.tv.TV) :\n                    if (peak > xmin+rad) and (peak < xmax-rad) : display.ax.scatter(peak,row,marker='o',color='r',s=2)\n                if ( (peak > xmin+rad) and (peak < xmax-rad) and \n                     ((spectrum.data[row,peak-rad:peak+rad]/spectrum.uncertainty.array[row,peak-rad:peak+rad]).max() > thresh) ) :\n                    cent = (spectrum.data[row,peak-rad:peak+rad]*np.arange(peak-rad,peak+rad)).sum()/spectrum.data[row,peak-rad:peak+rad].sum()\n                    peak = int(cent)\n                    cent = (spectrum.data[row,peak-rad:peak+rad]*np.arange(peak-rad,peak+rad)).sum()/spectrum.data[row,peak-rad:peak+rad].sum()\n                    if display is not None and  isinstance(display,pyvista.tv.TV) :\n                        display.ax.scatter(cent,row,marker='o',color='g',s=2)\n                    if plot is not None :\n                        ax[0].text(line,1.,'{:7.1f}'.format(line),rotation='vertical',va='top',ha='center')\n                    x.append(cent)\n                    y.append(row)\n                    # we will fit for wavelength*order\n                    waves.append(line)\n                    try: order = self.orders[row]\n                    except: order=self.orders[0]\n                    waves_order.append(order)\n                    weight.append(1.)\n        if plot is not None : \n            if self.model is not None :\n                # if we have a solution already, see how good it is (after shift)\n                diff=self.wave(pixels=[x,y])-np.array(waves)\n                ax[1].cla()\n                ax[1].scatter(np.array(waves),diff,s=2,c=y)\n                ax[1].text(0.1,0.9,'from previous fit, rms: {:8.3f}'.format(diff.std()),transform=ax[1].transAxes)\n                xlim=ax[1].get_xlim()\n                ax[1].plot(xlim,[0,0],linestyle=':')\n                ax[1].set_ylim(diff.min()-0.5,diff.max()+0.5)\n                print(\"  rms from old fit (with shift): {:8.3f}\".format(diff.std()))\n            plt.figure(plot.number)\n            plt.draw()\n            input('  See identified lines. hit any key to continue....')\n        self.pix=np.array(x)\n        self.y=np.array(y)\n        self.waves=np.array(waves)\n        self.waves_order=np.array(waves_order)\n        self.weights=np.array(weight)\n        self.spectrum = spectrum\n        print('')\n\n    def scomb(self,hd,wav,average=True,usemask=True) :\n        \"\"\" Resample onto input wavelength grid\n        \"\"\"\n        #output grid\n        out=np.zeros(len(wav))\n        sig=np.zeros(len(wav))\n        mask=np.zeros(len(wav),dtype=bool)\n        # raw wavelengths\n        w=self.wave(image=np.array(np.atleast_2d(hd.data).shape))\n        for i in range(np.atleast_2d(hd).shape[0]) :\n            sort=np.argsort(w[i,:])\n            if usemask : \n                gd = np.where(~hd.mask[i,sort])\n                sort= sort[gd]\n            wmin=w[i,sort].min()\n            wmax=w[i,sort].max()\n            w2=np.abs(wav-wmin).argmin()\n            w1=np.abs(wav-wmax).argmin()\n            if average :\n                out[w2:w1] += ( np.interp(wav[w2:w1],w[i,sort],np.atleast_2d(hd.data)[i,sort]) /\n                                np.interp(wav[w2:w1],w[i,sort],np.atleast_2d(hd.uncertainty.array)[i,sort])**2 )\n                sig[w2:w1] += 1./np.interp(wav[w2:w1],w[i,sort],np.atleast_2d(hd.uncertainty.array)[i,sort])**2 \n            else :\n                out[w2:w1] += np.interp(wav[w2:w1],w[i,sort],np.atleast_2d(hd.data)[i,sort])\n                sig[w2:w1] += np.interp(wav[w2:w1],w[i,sort],np.atleast_2d(hd.uncertainty.array**2)[i,sort])\n        if average :\n            out = out / sig\n        else :\n            sig = np.sqrt(sig)\n        return CCDData(out,uncertainty=StdDevUncertainty(sig),mask=mask,header=hd.header,unit='adu')\n\n    def save(self,file) :\n        \"\"\" Save object to file\n        \"\"\"\n        try : delattr(self,'fig')\n        except: pass\n        try : delattr(self,'ax')\n        except: pass\n        f=open(file,'wb')\n        pickle.dump(self,f)\n        f.close()\n\nclass Trace() :\n    \"\"\" Class for spectral traces\n    \"\"\"\n\n    def __init__ (self,inst=None, type='poly',order=2,pix0=0,rad=5,spectrum=None,model=None,sc0=None,rows=None,lags=None,channel=None) :\n        self.type = type\n        self.order = order\n        self.pix0 = pix0\n        self.spectrum = spectrum\n        self.rad = rad\n        if inst == 'TSPEC' :\n            self.order = 3\n            self.rows = [[135,235],[295,395],[435,535],[560,660],[735,830]]\n            self.lags = range(-75,75) \n        elif inst == 'DIS' :\n            if channel == 0 : self.rows=[[215,915]]\n            elif channel == 1 : self.rows=[[100,800]]\n            else : raise ValueError('need to specify channel')\n            self.lags = range(-300,300) \n        elif inst == 'ARCES' :\n            self.lags = range(-10,10) \n        if rows is not None : self.rows=rows\n        if lags is not None : self.lags=lags\n        if model is not None : self.model=model\n        if sc0 is not None : self.sc0=sc0\n\n    def trace(self,hd,srows,sc0=None,plot=None,thresh=20) :\n        \"\"\" Trace a spectrum from starting position\n        \"\"\"\n\n        fitter=fitting.LinearLSQFitter()\n        if self.type == 'poly' :\n            mod=models.Polynomial1D(degree=self.order)\n        else :\n            raise ValueError('unknown fitting type: '+self.type)\n            return\n\n        nrow = hd.data.shape[0]\n        ncol = hd.data.shape[1]\n        if sc0 is None : self.sc0 = int(ncol/2)\n        else : self.sc0 = sc0\n        self.spectrum = hd[:,self.sc0]\n        self.spectrum.data[self.spectrum.data<0] = 0.\n        rows = np.arange(nrow)\n        ypos = np.zeros(ncol)\n        ysum = np.zeros(ncol)\n        yvar = np.zeros(ncol)\n        ymask = np.zeros(ncol,dtype=bool)\n\n        # we want to handle multiple traces, so make sure srows is iterable\n        if type(srows ) is int or type(srows) is float : srows=[srows]\n        oldmodel=copy.copy(self.model)\n        self.model=[]\n        if plot is not None : \n            plot.clear()\n            plot.tv(hd)\n\n        rad = self.rad-1\n        for irow,srow in enumerate(srows) :\n            print('  Tracing row: {:d}'.format(int(srow)),end='\\r')\n            sr=copy.copy(srow)\n            sr=int(round(sr))\n            sr=hd.data[sr-rad:sr+rad+1,self.sc0].argmax()+sr-rad\n            # march left from center\n            for col in range(self.sc0,0,-1) :\n                # centroid\n                cr=sr-rad+hd.data[sr-rad:sr+rad+1,col].argmax()\n                ysum[col] = np.sum(hd.data[cr-rad:cr+rad+1,col]) \n                ypos[col] = np.sum(rows[cr-rad:cr+rad+1]*hd.data[cr-rad:cr+rad+1,col]) / ysum[col]\n                yvar[col] = np.sum(hd.uncertainty.array[cr-rad:cr+rad+1,col]**2) \n                ymask[col] = np.any(hd.mask[cr-rad:cr+rad+1,col]) \n                # if centroid is too far from starting guess, mask as bad\n                if np.abs(ypos[col]-sr) > rad/2. : ymask[col] = True\n                # use this position as starting center for next if above threshold S/N\n                if (not ymask[col]) & np.isfinite(ysum[col]) & (ysum[col]/np.sqrt(yvar[col]) > thresh)  : sr=int(round(ypos[col]))\n            sr=copy.copy(srow)\n            sr=int(round(sr))\n            sr=hd.data[sr-rad:sr+rad+1,self.sc0].argmax()+sr-rad\n            # march right from center\n            for col in range(self.sc0+1,ncol,1) :\n                # centroid\n                cr=sr-rad+hd.data[sr-rad:sr+rad+1,col].argmax()\n                ysum[col] = np.sum(hd.data[cr-rad:cr+rad+1,col]) \n                ypos[col] = np.sum(rows[cr-rad:cr+rad+1]*hd.data[cr-rad:cr+rad+1,col]) / ysum[col]\n                yvar[col] = np.sum(hd.uncertainty.array[cr-rad:cr+rad+1,col]**2) \n                ymask[col] = np.any(hd.mask[cr-rad:cr+rad+1,col]) \n                if np.abs(ypos[col]-sr) > rad/2. : ymask[col] = True\n                # use this position as starting center for next if above threshold S/N\n                if (not ymask[col]) & np.isfinite(ysum[col]) & (ysum[col]/np.sqrt(yvar[col]) > thresh)  : sr=int(round(ypos[col]))\n\n            cols=np.arange(ncol)\n            gd = np.where((~ymask) & (ysum/np.sqrt(yvar)>thresh) )[0]\n            model=(fitter(mod,cols[gd],ypos[gd]))\n\n            # reject outlier points (>1 pixel) and refit\n            res = model(cols)-ypos\n            gd = np.where((~ymask) & (ysum/np.sqrt(yvar)>thresh) & (np.abs(res)<1))[0]\n            model=(fitter(mod,cols[gd],ypos[gd]))\n            if len(gd) < 10 : \n                print('  failed trace for row: {:d}, using old model'.format(irow))\n                model=copy.copy(oldmodel[irow])\n            self.model.append(model)\n\n            if plot : \n                plot.ax.scatter(cols,ypos,marker='o',color='r',s=4) \n                plot.ax.scatter(cols[gd],ypos[gd],marker='o',color='g',s=4) \n                plot.ax.plot(cols,model(cols),color='m')\n                #plt.pause(0.05)\n\n        self.pix0=0\n        print(\"\")\n        if plot : input('  See trace. Hit any key to continue....')\n\n    def retrace(self,hd,plot=None,thresh=20) :\n        \"\"\" Retrace starting with existing model\n        \"\"\"\n        self.find(hd)\n        srows = []\n        for row in range(len(self.model)) :\n            srows.append(self.model[row](self.sc0))\n        self.trace(hd,srows,plot=plot,thresh=thresh)\n     \n    def find(self,hd,lags=None,plot=None) :\n        \"\"\" Determine shift from existing trace to input frame\n        \"\"\"\n        if lags is None : lags = self.lags\n       \n        im=copy.deepcopy(hd.data)\n        # if we have a window, zero array outside of window\n        spec=im[:,self.sc0]\n        try:\n            spec[:self.rows[0]] = 0.  \n            spec[self.rows[1]:] = 0.  \n        except: pass\n        fitpeak,shift = image.xcorr(self.spectrum,spec,lags)\n        pixshift=(fitpeak+lags[0])[0]\n        print('  traces shift: ', fitpeak+lags[0])\n        if plot is not None :\n            plot.clear()\n            plot.tv(im)\n            plot.plotax1.cla()\n            plot.plotax1.text(0.05,0.95,'obj and ref cross-section',transform=plot.plotax1.transAxes)\n            plot.plotax1.plot(self.spectrum.data/self.spectrum.data.max())\n            plot.plotax1.plot(im[:,self.sc0]/im[:,self.sc0].max())\n            plot.plotax1.set_xlabel('row')\n            plot.plotax2.cla()\n            plot.plotax2.text(0.05,0.95,'cross correlation {:8.3f}'.format(pixshift),\n                              transform=plot.plotax2.transAxes)\n            plot.plotax2.plot(lags,shift)\n            plot.plotax2.set_xlabel('lag')\n            plt.draw()\n            input('  See spectra and cross-correlation. Hit any key to continue....')\n        self.pix0=fitpeak+lags[0]\n        return fitpeak+lags[0]\n \n    def extract(self,hd,rad=None,scat=False,plot=None,medfilt=None) :\n        \"\"\" Extract spectrum given trace(s)\n        \"\"\"\n        if rad is None : rad=self.rad\n        nrows=hd.data.shape[0]\n        ncols=hd.data.shape[-1]\n        spec = np.zeros([len(self.model),hd.data.shape[1]])\n        sig = np.zeros([len(self.model),hd.data.shape[1]])\n        mask = np.zeros([len(self.model),hd.data.shape[1]],dtype=bool)\n\n        if plot is not None:\n            plot.clear()\n            plot.tv(hd)\n\n        for i,model in enumerate(self.model) :\n            print('  extracting aperture {:d}'.format(i),end='\\r')\n            cr=model(np.arange(ncols))+self.pix0\n            icr=np.round(cr).astype(int)\n            rfrac=cr-icr+0.5   # add 0.5 because we rounded\n            rlo=[]\n            rhi=[]\n            for col in range(ncols) :\n                r1=icr[col]-rad\n                r2=icr[col]+rad\n                # sum inner pixels directly, outer pixels depending on fractional pixel location of trace\n                if r1>=0 and r2<nrows :\n                    spec[i,col]=np.sum(hd.data[r1+1:r2,col])\n                    sig[i,col]=np.sum(hd.uncertainty.array[r1+1:r2,col]**2)\n                    spec[i,col]+=hd.data[r1,col]*(1-rfrac[col])\n                    sig[i,col]+=hd.uncertainty.array[r1,col]**2*(1-rfrac[col])\n                    spec[i,col]+=hd.data[r2,col]*rfrac[col]\n                    sig[i,col]+=hd.uncertainty.array[r2,col]**2*rfrac[col]\n                    sig[i,col]=np.sqrt(sig[i,col])\n                    mask[i,col] = np.any(hd.mask[r1:r2+1,col]) \n                if plot is not None :\n                    rlo.append(r1)\n                    rhi.append(r2-1)\n            if medfilt is not None :\n                boxcar = Box1DKernel(medfilt)\n                median = convolve(spec[i,:],boxcar,boundary='extend')\n                spec[i,:]/=median\n                sig[i,:]/=median\n\n            if plot is not None :\n                if i%2 == 0 : color='b'\n                else : color='m'\n                plot.ax.plot(range(ncols),cr,color='g',linewidth=3)\n                plot.ax.plot(range(ncols),rlo,color=color,linewidth=1)\n                plot.ax.plot(range(ncols),rhi,color=color,linewidth=1)\n                plt.draw()\n        if plot is not None : input('  See extraction window(s). Hit any key to continue....')\n        print(\"\")\n        return CCDData(spec,uncertainty=StdDevUncertainty(sig),mask=mask,header=hd.header,unit='adu')\n  \n    def extract2d(self,hd,rows=None,plot=None) :\n        \"\"\"  Extract 2D spectrum given trace(s)\n             Assumes all requests row uses same trace, just offset, not a 2D model for traces\n        \"\"\"\n        nrows=hd.data.shape[0]\n        ncols=hd.data.shape[-1]\n        out=[]\n        if plot is not None:\n            plot.clear()\n            plot.tv(hd)\n        for model in self.model :\n            if plot is not None :\n                plot.ax.plot([0,ncols],[self.rows[0],self.rows[0]],color='g')\n                plot.ax.plot([0,ncols],[self.rows[1],self.rows[1]],color='g')\n                plt.draw()\n            outrows=np.arange(self.rows[0],self.rows[1])\n            noutrows=len(range(self.rows[0],self.rows[1]))\n            spec=np.zeros([noutrows,ncols])\n            sig=np.zeros([noutrows,ncols])\n            cr=model(np.arange(ncols))\n            cr-=cr[self.sc0]\n            for col in range(ncols) :\n                spec[:,col] = np.interp(outrows+cr[col],np.arange(nrows),hd.data[:,col])\n                sig[:,col] = np.sqrt(np.interp(outrows+cr[col],np.arange(nrows),hd.uncertainty.array[:,col]**2))\n            out.append(CCDData(spec,StdDevUncertainty(sig),unit='adu'))\n        if plot is not None: input('  enter something to continue....')\n\n        if len(out) == 1 : return out[0]\n        else : return out\n\n    def save(self,file) :\n        \"\"\" Save object to file\n        \"\"\"\n        try : delattr(self,'ax')\n        except: pass\n        f=open(file,'wb')\n        pickle.dump(self,f)\n        f.close()\n\ndef mash(hd,sp=None,bks=None) :\n    \"\"\"\n    Mash image into spectra using requested window\n    \"\"\"\n    if sp is None :\n        sp=[0,hd.data.shape[0]]\n    obj = hd.data[sp[0]:sp[1]].sum(axis=0)\n    obj = hd.data[sp[0]:sp[1]].sum(axis=0)\n\n    if bks is not None :\n        back=[]\n        for bk in bks :\n           tmp=np.median(data[bk[0]:bk[1]],axis=0)\n           back.append(tmp)\n        obj-= np.mean(back,axis=0)\n\n    return obj\n\ndef wavecal(hd,file=None,wref=None,disp=None,wid=[3],rad=5,snr=3,degree=2,wcal0=None,thresh=100,type='poly'):\n    \"\"\"\n    Get wavelength solution for single 1D spectrum\n    \"\"\"\n\n    # choose middle row +/ 5 rows\n    sz=hd.data.shape\n    spec=hd.data[int(sz[0]/2)-5:int(sz[0]/2)+5,:].sum(axis=0)\n    spec=spec-scipy.signal.medfilt(spec,kernel_size=101)\n    pix = np.arange(len(spec))\n\n    fig,ax = plt.subplots(2,1,sharex=True,figsize=(14,6))\n    ax[0].plot(spec)\n\n    # get wavelength guess from input WaveCal if given, else use wref and dispersion, else header\n    if wcal0 is not None :\n        lags=range(-300,300)\n        fitpeak,shift = image.xcorr(wcal0.spectrum,spec,lags)\n        wnew=copy.deepcopy(wcal0)\n        wnew.pix0 = wcal0.pix0+shift.argmax()+lags[0]\n        print('  Derived pixel shift from input wcal0: ',shift.argmax()+lags[0])\n        wav=wnew.wave(pix)\n    else :\n        # get dispersion guess from header cards if not given in disp\n        if disp is None: disp=hd.header['DISPDW']\n        if wref is not None :\n            w0=wref[0]\n            pix0=wref[1]\n            wav=w0+(pix-pix0)*disp\n        else:\n            w0=hd.header['DISPWC']\n            pix0=sz[1]/2 \n            wav=w0+(pix-pix0)*disp\n    ax[1].plot(wav,spec)\n\n    # open file with wavelengths and read\n    f=open(file,'r')\n    lines=[]\n    for line in f :\n        if line[0] != '#' :\n            w=float(line.split()[0])\n            name=line[10:].strip()\n            lpix=abs(w-wav).argmin()\n            if lpix > 1 and lpix < sz[1]-1 :\n                ax[0].text(lpix,0.,'{:7.1f}'.format(w),rotation='vertical',va='top',ha='center')\n                lines.append(w)\n    lines=np.array(lines)\n    f.close()\n\n    # get centroid around expected lines\n    cents=[]\n    for line in lines :\n        peak=abs(line-wav).argmin()\n        if (peak > rad) and (peak < sz[1]-rad) and (spec[peak-rad:peak+rad].max() > thresh) :\n            print(peak,spec[peak-rad:peak+rad].max())\n            cents.append((spec[peak-rad:peak+rad]*np.arange(peak-rad,peak+rad)).sum()/spec[peak-rad:peak+rad].sum())\n    cents=np.array(cents)\n    print('  cents:', cents)\n\n    waves=[]\n    weight=[]\n    print('  Centroid  W0  Wave')\n    for cent in cents :\n        w=wav[int(cent)]\n        ax[0].plot([cent,cent],[0,10000],'k')\n        print('  {:8.2f}{:8.2f}{:8.2f}'.format(cent, w, lines[np.abs(w-lines).argmin()]))\n        waves.append(lines[np.abs(w-lines).argmin()])\n        weight.append(1.)\n    waves=np.array(waves)\n    weight=np.array(weight)\n\n    # set up new WaveCal object\n    pix0 = int(sz[1]/2)\n    wcal = WaveCal(order=degree,type=type,spectrum=spec,pix0=pix0)\n\n    # iterate allowing for interactive removal of points\n    done = False\n    ymax = ax[0].get_ylim()[1]\n    while not done :\n        gd=np.where(weight>0.)[0]\n        bd=np.where(weight<=0.)[0]\n        wcal.fit(cents[gd],waves[gd],weights=weight[gd])\n\n        # plot\n        ax[1].cla()\n        ax[1].plot(cents[gd],wcal.wave(cents[gd])-waves[gd],'go')\n        if len(bd) > 0 : ax[1].plot(cents[bd],wcal.wave(cents[bd])-waves[bd],'ro')\n        diff=wcal.wave(cents[gd])-waves[gd]\n        ax[1].set_ylim(diff.min()-1,diff.max()+1)\n        for i in range(len(cents)) :\n            ax[1].text(cents[i],wcal.wave(cents[i])-waves[i],'{:2d}'.format(i),va='top',ha='center')\n            if weight[i] > 0 :\n              ax[0].plot([cents[i],cents[i]],[0,ymax],'g')\n            else :\n              ax[0].plot([cents[i],cents[i]],[0,ymax],'r')\n        plt.draw()\n\n        # get input from user on lines to remove\n        for i in range(len(cents)) :\n            print('  {:3d}{:8.2f}{:8.2f}{:8.2f}{:8.2f}{:8.2f}'.format(\n                   i, cents[i], wcal.wave(cents[i]), waves[i], waves[i]-wcal.wave(cents[i]),weight[i]))\n        print('  rms: {:8.2f} Anstroms'.format(diff.std()))\n        i = input('enter ID of line to remove (-n for all lines<n, +n for all lines>n, return to continue): ')\n        if i is '' :\n            done = True\n        elif '+' in i :\n            weight[int(i)+1:] = 0.\n        elif '-' in i :\n            weight[0:abs(int(i))] = 0.\n        elif int(i) >= 0 :\n            weight[int(i)] = 0.\n        else :\n            print('invalid input')\n\n    plt.close()\n\n    return wcal.wave(pix),wcal\n\ndef fluxcal(obs,wobs,file=None) :\n    \"\"\"\n    flux calibration\n    \"\"\"\n\n    fluxdata=ascii.read(file)\n    stan=np.interp(wobs,fluxdata['col1'],fluxdata['col2'])\n    return stan/obs\n  \n\ndef trace(hd,apertures=None,pix0=1024) : \n    \"\"\" Get all traces\n        apertures is a list of row numbers at pixel 1024\n    \"\"\"\n    alltr=[]\n    for i in range(len(apertures)) :\n        tr=Trace()\n        print('tracing aperture {:d}'.format(i),end='\\r')\n        sr=apertures[i]\n        tr.trace(hd,pix0,sr)\n        alltr.append(tr)\n\n    return alltr\n\ndef extract(hd,apertures) :\n    \"\"\" Do all extractions\n    \"\"\"\n    spec = np.zeros([len(apertures),hd.data.shape[1]])\n    for i,order in enumerate(apertures) :\n        print('extracting aperture {:d}'.format(i),end='\\r')\n        spec[i] = order.extract(hd)\n\n    return spec\n\n\n", "meta": {"hexsha": "ee88b24eca82ddcab181129272a9f62d15dd7605", "size": 36064, "ext": "py", "lang": "Python", "max_stars_repo_path": "external/pyvista/python/pyvista/spectra.py", "max_stars_repo_name": "dnidever/apogee", "max_stars_repo_head_hexsha": "83ad7496a0b4193df9e2c01b06dc36cb879ea6c1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-11T13:35:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-14T06:12:51.000Z", "max_issues_repo_path": "external/pyvista/python/pyvista/spectra.py", "max_issues_repo_name": "dnidever/apogee", "max_issues_repo_head_hexsha": "83ad7496a0b4193df9e2c01b06dc36cb879ea6c1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/pyvista/python/pyvista/spectra.py", "max_forks_repo_name": "dnidever/apogee", "max_forks_repo_head_hexsha": "83ad7496a0b4193df9e2c01b06dc36cb879ea6c1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-09-20T22:07:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-15T07:13:38.000Z", "avg_line_length": 41.3577981651, "max_line_length": 143, "alphanum_fraction": 0.51918811, "include": true, "reason": "import numpy,import scipy,from astropy", "num_tokens": 9404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.29746994260479465, "lm_q1q2_score": 0.17178751313635832}}
{"text": "\"\"\"\nThe purpose of this stage is to simulate event classification sorting the\nreconstructed particles into PID-signature channels.\n\nFor each PID signature, the input map is transformed by the probability for\nevents in each of its bins to be ID'd as that signature. Therefore the ouptut\nbinning is similar to the input binning, but with the added 'pid' dimension,\nwhich has as many bins as PID signatures.\n\"\"\"\n\n\nfrom __future__ import division\n\nfrom collections import Mapping, OrderedDict\n\nimport numpy as np\nimport scipy as sp\n\n# NOTE: need both versions of the imported names, as eval strings can name\n# numpy and scipy either ways\nimport numpy\nimport scipy\n\nfrom pisa.core.stage import Stage\nfrom pisa.core.transform import BinnedTensorTransform, TransformSet\nfrom pisa.utils.fileio import from_file\nfrom pisa.utils.flavInt import flavintGroupsFromString, NuFlavIntGroup\nfrom pisa.utils.hash import hash_obj\nfrom pisa.utils.log import logging\nfrom pisa.utils.profiler import profile\n\n\n__all__ = ['param']\n\n__author__ = 'L. Schulte, J.L. Lanfranchi, S. Mandalia'\n\n__license__ = '''Copyright (c) 2014-2017, The IceCube Collaboration\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n   http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.'''\n\n\ndef load_pid_energy_param(source):\n    \"\"\"Load pid energy-dependent parameterisation from file or dictionary.\n\n    Parameters\n    ----------\n    source : string or mapping\n        If string, interprete as resource location of the file; if mapping, use\n        directly.\n\n    Returns\n    -------\n    pid_energy_param_dict : OrderedDict\n        Keys are `NuFlavIntGroup`s and values are callables of one arg.\n\n    \"\"\"\n    # Get the original dict\n    if isinstance(source, basestring):\n        orig_dict = from_file(source)\n    elif isinstance(source, Mapping):\n        orig_dict = source\n    else:\n        raise TypeError('`source` must either be string or mapping; got %s'\n                        ' instead.' % type(source))\n\n    # Build dict with flavintgroups as keys; subdict with signatures as keys\n    # and callables as values\n    pid_energy_param_dict = OrderedDict()\n\n    for flavintgroup_str, subdict in orig_dict.iteritems():\n        flavintgroup = NuFlavIntGroup(flavintgroup_str)\n\n        pid_energy_param_dict[flavintgroup] = OrderedDict()\n\n        for signature, sig_param_spec in subdict.iteritems():\n            if isinstance(sig_param_spec, basestring):\n                sig_param_func = eval(sig_param_spec)\n                if not callable(sig_param_func):\n                    raise ValueError(\n                        'Group %s PID signature %s param spec \"%s\" does'\n                        ' not evaluate to a callable.'\n                        % (xform_flavints, signature, sig_param_spec)\n                    )\n            elif callable(sig_param_spec):\n                sig_param_func = sig_param_spec\n            else:\n                raise TypeError(\n                    'Group %s PID signature %s parameterization is a \"%s\"'\n                    ' but must be a string or callable.'\n                    % (xform_flavints, signature, type(sig_param_spec))\n                )\n\n            pid_energy_param_dict[flavintgroup][signature] = sig_param_func\n\n    return pid_energy_param_dict\n\n\nclass param(Stage):\n    \"\"\"Parameterised MC PID based on an input json file containing functions\n    describing the PID as a function of energy.\n\n    Transforms an input map of the specified particle \"signature\" (aka ID) into\n    a map of the track-like events ('track') and a map of the shower-like events\n    ('cascade').\n\n    Parameters\n    ----------\n    params : ParamSet or sequence with which to instantiate a ParamSet\n\n        Parameters which set everything besides the binning.\n\n        If str, interpret as resource location and load params from resource.\n        If dict, set contained params. Format expected is\n            {'<param_name>': <Param object or passable to Param()>}\n\n        Parameters required by this service are\n            * pid_energy_paramfile : dict or filepath\n                json file or equivalent dict containing the PID functions for\n                each flavor. The structure should be:\n                  {\n                    \"numu_cc + numubar_cc\": {\n                      \"track\" : \"lambda E: some function\",\n                      \"cascade\" : \"lambda E: 1 - some function\"\n                    },\n                    \"nue_cc + nuebar_cc\": {\n                      \"track\" : \"lambda E: some function\",\n                      \"cascade\" : \"lambda E: 1 - some function\"\n                    },\n                    \"nutau_cc + nutaubar_cc\": {\n                      \"track\" : \"lambda E: some function\",\n                      \"cascade\" : \"lambda E: 1 - some function\"\n                    },\n                    \"nuall_nc + nuallbar_nc\": {\n                      \"track\" : \"lambda E: some function\",\n                      \"cascade\" : \"lambda E: 1 - some function\"\n                    }\n                  }\n\n    particles : string\n\n    input_names : sequence of strings\n\n    transform_groups\n\n    sum_grouped_flavints : bool\n\n    input_binning : MultiDimBinning\n        Arbitrary number of dimensions accepted. Contents of the input\n        `pid_events` parameter defines the possible binning dimensions. Name(s)\n        of given binning(s) must match to a reco variable in `pid_events`.\n\n    output_binning : MultiDimBinning\n\n    error_method : None, bool, or string\n\n    transforms_cache_depth : int >= 0\n\n    outputs_cache_depth : int >= 0\n\n    memcache_deepcopy : bool\n\n    debug_mode : None, bool, or string\n        Whether to store extra debug info for this service.\n\n\n    Input Names\n    ----------\n    The `inputs` container must include objects with `name` attributes:\n        * 'nue_cc'\n        * 'nuebar_cc'\n        * 'numu_cc'\n        * 'numubar_cc'\n        * 'nutau_cc'\n        * 'nutaubar_cc'\n        * 'nuall_nc'\n        * 'nuallbar_nc'\n\n    Output Names\n    ----------\n    The `outputs` container generated by this service will be objects with the\n    following `name` attribute; pid is added as a binning dimension:\n        * 'nue_cc'\n        * 'nuebar_cc'\n        * 'numu_cc'\n        * 'numubar_cc'\n        * 'nutau_cc'\n        * 'nutaubar_cc'\n        * 'nuall_nc'\n        * 'nuallbar_nc'\n\n    \"\"\"\n    def __init__(self, params, particles, input_names, transform_groups,\n                 sum_grouped_flavints, input_binning, output_binning,\n                 memcache_deepcopy, error_method, transforms_cache_depth,\n                 outputs_cache_depth, debug_mode=None):\n        assert particles in ['muons', 'neutrinos']\n        self.particles = particles.strip().lower()\n        \"\"\"Whether stage is instantiated to process neutrinos or muons\"\"\"\n\n        self.transform_groups = flavintGroupsFromString(transform_groups)\n        \"\"\"Particle/interaction types to group for computing transforms\"\"\"\n\n        self.sum_grouped_flavints = sum_grouped_flavints\n\n        # All of the following params (and no more) must be passed via\n        # the `params` argument.\n        expected_params = (\n            'pid_energy_paramfile'\n        )\n\n        if isinstance(input_names, basestring):\n            input_names = input_names.replace(' ', '').split(',')\n\n        if self.particles == 'neutrinos':\n            if self.sum_grouped_flavints:\n                output_names = [str(g) for g in self.transform_groups]\n            else:\n                output_names = input_names\n        elif self.particles == 'muons':\n            raise NotImplementedError('%s not implemented.' % self.particles)\n\n        super(self.__class__, self).__init__(\n            use_transforms=True,\n            params=params,\n            expected_params=expected_params,\n            input_names=input_names,\n            output_names=output_names,\n            error_method=error_method,\n            outputs_cache_depth=outputs_cache_depth,\n            transforms_cache_depth=transforms_cache_depth,\n            memcache_deepcopy=memcache_deepcopy,\n            input_binning=input_binning,\n            output_binning=output_binning,\n            debug_mode=debug_mode\n        )\n\n        self.include_attrs_for_hashes('particles')\n        self.include_attrs_for_hashes('sum_grouped_flavints')\n        self.include_attrs_for_hashes('transform_groups')\n\n        self.signatures = output_binning.pid.bin_names\n        \"\"\"PID signatures that this stage generates\"\"\"\n\n        # If no bin names are present, use the integer bin indices instead\n        if self.signatures is None:\n            self.signatures = range(len(output_binning.pid))\n\n        # Define the transform binnning...\n\n        # Note that Numpy broadcasting rules start with last axis and work\n        # inwards. We want the input map (say MxN) to automatically be\n        # broadcast to multiply into each of L PID bins. Therefore, if\n        # we _prepend_ the PID dimension to the transform, we have an MxN input\n        # multiplying an LxMxN transform, and Numpy treats this as L separate\n        # MxN by MxN multiplies which populate an output array of dimension\n        # LxMxN... exactly what we want, and with maximal computational\n        # efficiency (for Numpy to handle, at least). If the user's output\n        # binning does not follow the same ordering, this is okay, as the\n        # output is passed through the `rebin` function each time it is\n        # computed, and this takes care of any axis swapping necessary.\n\n        self.transform_output_binning = (\n            self.output_binning.pid * self.input_binning\n        )\n\n        self.ebin_centers = (\n            self.input_binning.reco_energy.weighted_centers.m_as('GeV')\n        )\n\n        self.pid_energy_param_dict = None\n        self._pid_energy_param_hash = None\n\n    def validate_binning(self):\n        \"\"\"Validate input and output binning\"\"\"\n        required_input_binning_dims = 'reco_energy', 'reco_coszen'\n        required_output_binning_dims = 'reco_energy', 'reco_coszen', 'pid'\n\n        msg = ('%s binning must contain dimensions %s, but has dimensions %s'\n               ' instead.')\n\n        if set(self.input_binning.names) != set(required_input_binning_dims):\n            raise ValueError(msg % ('Input', required_input_binning_dims,\n                                    self.input_binning.names))\n\n        if set(self.output_binning.names) != set(required_output_binning_dims):\n            raise ValueError(msg % ('Output', required_output_binning_dims,\n                                    self.input_binning.names))\n\n        # While output binning will have a 'pid' dimension, the remaining\n        # dimensions must be the same in both input and output binnings\n        for dim in self.input_binning.dims:\n            if dim != self.output_binning[dim.name]:\n                raise NotImplementedError(\n                    'Input and output dimensions %s are not equal, but stage'\n                    ' %s / service %s does not implement binning up- or'\n                    ' downsampling.'\n                    % (dim.name, self.stage_name, self.service_name)\n                )\n\n    def load_pid_energy_param(self, source):\n        \"\"\"Load pid energy-dependent parameterisation from file or dictionary.\n\n        Parameters\n        ----------\n        source : string\n            Resource location of the file\n\n        \"\"\"\n        this_hash = hash_obj(source)\n        if (self._pid_energy_param_hash is not None\n                and this_hash == self._pid_energy_param_hash):\n            return\n\n        # Invalidate the hash and clear the entry, so we aren't left in an\n        # inconsistent state if any of the below fails\n        self._pid_energy_param_hash = None\n        self.pid_energy_param_dict = None\n\n        # Call external function for basic loading and conversion\n        pid_energy_param_dict = load_pid_energy_param(source)\n\n        # Perform validation\n        for flavintgroup, subdict in pid_energy_param_dict.iteritems():\n            if set(subdict.keys()) != set(self.signatures):\n                raise ValueError(\n                    'Expected PID specs for %s, but the energy PID'\n                    ' parameterization for %s specifies %s instead.'\n                    % (self.signatures, flavintgroup, subdict.keys())\n                )\n\n        # Transform groups are implicitly defined by keys\n        implicit_transform_groups = pid_energy_param_dict.keys()\n\n        # Make sure these match the transform groups specified for the stage\n        if set(implicit_transform_groups) != set(self.transform_groups):\n            raise ValueError(\n                'Transform groups (%s) defined implicitly by `source` \"%s\" do'\n                ' not match those defined as the stage\\'s configured'\n                ' `transform_groups` (%s).'\n                % (implicit_transform_groups, source, self.transform_groups)\n            )\n\n        # Verify that each input name--which specifies a flavint or\n        # flavintgroup--is wholly encapsulated by one of the transform\n        # flavintgroups\n        for name in self.input_names:\n            if not any(name in group for group in implicit_transform_groups):\n                raise ValueError(\n                    'Input \"%s\" either not present in or spans multiple'\n                    ' transform groups (transform_groups = %s)'\n                    % (name, implicit_transform_groups)\n                )\n\n        self.pid_energy_param_dict = pid_energy_param_dict\n        self._pid_energy_param_hash = this_hash\n\n    @profile\n    def _compute_nominal_transforms(self):\n        \"\"\"Compute new PID transforms.\"\"\"\n        logging.debug('Updating pid.param PID histograms...')\n\n        self.load_pid_energy_param(self.params.pid_energy_paramfile.value)\n\n        nominal_transforms = []\n        for xform_flavints in self.transform_groups:\n            logging.debug('Working on %s PID', xform_flavints)\n\n            xform_array = np.empty(self.transform_output_binning.shape)\n\n            subdict = self.pid_energy_param_dict[xform_flavints]\n            for signature, sig_param_func in subdict.iteritems():\n                # Get the PID probabilities vs. energy at the energy bins'\n                # (weighted) centers\n                pid1d = sig_param_func(self.ebin_centers)\n\n                # Broadcast this 1d array across the reco_coszen dimension\n                # since it's independent of reco_coszen\n                broadcasted_pid = self.transform_output_binning.broadcast(\n                    pid1d, from_dim='reco_energy', to_dims='reco_coszen'\n                )\n\n                pid_indexer = (\n                    self.transform_output_binning.indexer(pid=signature)\n                )\n\n                # Assign the broadcasted array to the correct PID bin\n                xform_array[pid_indexer] = broadcasted_pid\n\n            if self.sum_grouped_flavints:\n                xform_input_names = []\n                for input_name in self.input_names:\n                    input_flavs = NuFlavIntGroup(input_name)\n                    if set(xform_flavints).intersection(input_flavs):\n                        xform_input_names.append(input_name)\n\n                for output_name in self.output_names:\n                    if output_name not in xform_flavints:\n                        continue\n                    xform = BinnedTensorTransform(\n                        input_names=xform_input_names,\n                        output_name=str(xform_flavints),\n                        input_binning=self.input_binning,\n                        output_binning=self.transform_output_binning,\n                        xform_array=xform_array,\n                        sum_inputs=self.sum_grouped_flavints\n                    )\n                    nominal_transforms.append(xform)\n\n            else:\n                for input_name in self.input_names:\n                    if input_name not in xform_flavints:\n                        continue\n                    xform = BinnedTensorTransform(\n                        input_names=input_name,\n                        output_name=input_name,\n                        input_binning=self.input_binning,\n                        output_binning=self.transform_output_binning,\n                        xform_array=xform_array,\n                    )\n                    nominal_transforms.append(xform)\n\n        return TransformSet(transforms=nominal_transforms)\n\n    def _compute_transforms(self):\n        \"\"\"There are no systematics in this stage, so the transforms are just\n        the nominal transforms. Thus, this function just returns the nominal\n        transforms, computed by `_compute_nominal_transforms`..\n        \"\"\"\n        return self.nominal_transforms\n\n    def validate_params(self, params):\n        \"\"\"Do checks on the parameters\"\"\"\n        val = params.pid_energy_paramfile.value\n        if not isinstance(val, (basestring, Mapping)):\n            raise TypeError(\n                'Expecting either a path to a file or a dictionary provided'\n                ' as the store of the parameterisations. Got \"%s\".' % type(val)\n            )\n", "meta": {"hexsha": "866b6225bfc0c3b744d1424ffe87c783f92924e7", "size": 17494, "ext": "py", "lang": "Python", "max_stars_repo_path": "pisa/stages/pid/param.py", "max_stars_repo_name": "torkjellsdatter/pisa", "max_stars_repo_head_hexsha": "7b26b0ac40c873a87786286acfd1c96abf724a99", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pisa/stages/pid/param.py", "max_issues_repo_name": "torkjellsdatter/pisa", "max_issues_repo_head_hexsha": "7b26b0ac40c873a87786286acfd1c96abf724a99", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pisa/stages/pid/param.py", "max_forks_repo_name": "torkjellsdatter/pisa", "max_forks_repo_head_hexsha": "7b26b0ac40c873a87786286acfd1c96abf724a99", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9621380846, "max_line_length": 80, "alphanum_fraction": 0.6171830342, "include": true, "reason": "import numpy,import scipy", "num_tokens": 3584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.17170341459858163}}
{"text": "#!/usr/bin/env python\n\"\"\" Where you at? \"\"\"\nimport sys,os\nimport logging\nfrom collections import OrderedDict as odict\nfrom datetime import datetime,timedelta,tzinfo\nimport dateutil.parser\n\nimport mpl_toolkits.basemap as basemap\nfrom matplotlib.patches import Ellipse, Circle\nimport matplotlib.patheffects as patheffects\nfrom _tkinter import TclError\n\nimport numpy as np\nimport pylab as plt\nimport ephem\n\n__author__  = \"Alex Drlica-Wagner\"\n__email__   = \"kadrlica@fnal.gov\"\n__version__ = \"2.1.3\"\n\nMAXREF=5000 # Maximum number of refreshes\nDECAM=1.1   # DECam radius (deg)\n\n# Accurate DECam marker size depends on figsize and DPI\n# This is a mess...\nFIGSIZE=(10.5,8.5)\nSCALE=np.sqrt((8.0*6.0)/(FIGSIZE[0]*FIGSIZE[1]))\nDPI=80;\n\nFILTERS = ['u','g','r','i','z','Y','VR']\nBANDS = FILTERS + ['all']\nCOLORS = odict([\n    ('none','black'),\n    ('u','blue'),\n    ('g','green'),\n    ('r','red'),\n    ('i','gold'),\n    ('z','magenta'),\n    ('Y','black'),\n    ('VR','gray'),\n])\n\n# Allowed map projections\nPROJ = odict([\n    ('ortho'  , dict(projection='ortho',celestial=True)),\n    ('moll'   , dict(projection='moll',celestial=True)),\n    ('mol'    , dict(projection='moll',celestial=True)),\n    ('ait'    , dict(projection='hammer',celestial=True)),\n    ('mbt'    , dict(projection='mbtfpq',celestial=True)),\n    ('mbtfpq' , dict(projection='mbtfpq',celestial=True)),\n    ('mcbryde', dict(projection='mbtfpq',celestial=True)),\n])\n\n# Derived from telra,teldec of 10000 exposures\nSN = odict([\n    ('E1',(7.874, -43.010)),\n    ('E2',(9.500, -43.999)),\n    ('X1',(34.476, -4.931)),\n    ('X2',(35.664,-6.413)),\n    ('X3',(36.449, -4.601)),\n    ('S1',(42.818, 0.000)),\n    ('S2',(41.193, -0.991)),\n    ('C1',(54.274, -27.113)),\n    ('C2',(54.274, -29.090)),\n    ('C3',(52.647, -28.101)),\n])\n\nSN_LABELS = odict([\n    ('SN-E',(8,-41)),\n    ('SN-X',(35,-12)),\n    ('SN-S',(45,1)),\n    ('SN-C',(55,-35)),\n])\n\n# The allowed footprint outlines\nFOOTPRINTS = ['none','des','des-sn','smash','maglites','bliss','decals','delve']\n\n# CTIO location taken from:\n#http://www.ctio.noao.edu/noao/content/Coordinates-Observatories-Cerro-Tololo-and-Cerro-Pachon\n#http://arxiv.org/pdf/1210.1616v3.pdf\n#(-30h 10m 10.73s, -70h 48m 23.52s, 2213m)\n\nTEL_LON = -70.80653\nTEL_LAT = -30.169647\nTEL_HEIGHT = 2213\n\n# Create the observatory object\nCTIO = ephem.Observer()\nCTIO.lon,CTIO.lat = str(TEL_LON),str(TEL_LAT)\nCTIO.elevation = TEL_HEIGHT\n\ndef get_datadir():\n    \"\"\" Path to data directory. \"\"\"\n    return os.path.join(os.path.dirname(os.path.realpath(__file__)),'data')\n\ndef setdefaults(kwargs,defaults):\n    \"\"\" set dictionary with defaults. \"\"\"\n    for k,v in defaults.items():\n        kwargs.setdefault(k,v)\n    return kwargs\n\ndef gal2cel(glon, glat):\n    \"\"\"\n    Converts Galactic (deg) to Celestial J2000 (deg) coordinates\n    \"\"\"\n    glat = np.radians(glat)\n    sin_glat = np.sin(glat)\n    cos_glat = np.cos(glat)\n\n    glon = np.radians(glon)\n    ra_gp = np.radians(192.85948)\n    de_gp = np.radians(27.12825)\n    lcp = np.radians(122.932)\n\n    sin_lcp_glon = np.sin(lcp - glon)\n    cos_lcp_glon = np.cos(lcp - glon)\n\n    sin_d = (np.sin(de_gp) * sin_glat) \\\n            + (np.cos(de_gp) * cos_glat * cos_lcp_glon)\n    ramragp = np.arctan2(cos_glat * sin_lcp_glon,\n                         (np.cos(de_gp) * sin_glat) \\\n                         - (np.sin(de_gp) * cos_glat * cos_lcp_glon))\n    dec = np.arcsin(sin_d)\n    ra = (ramragp + ra_gp + (2. * np.pi)) % (2. * np.pi)\n    return np.degrees(ra), np.degrees(dec)\n\ndef cel2gal(ra, dec):\n    \"\"\"\n    Converts Celestial J2000 (deg) to Calactic (deg) coordinates\n    \"\"\"\n    dec = np.radians(dec)\n    sin_dec = np.sin(dec)\n    cos_dec = np.cos(dec)\n\n    ra = np.radians(ra)\n    ra_gp = np.radians(192.85948)\n    de_gp = np.radians(27.12825)\n\n    sin_ra_gp = np.sin(ra - ra_gp)\n    cos_ra_gp = np.cos(ra - ra_gp)\n\n    lcp = np.radians(122.932)\n    sin_b = (np.sin(de_gp) * sin_dec) \\\n            + (np.cos(de_gp) * cos_dec * cos_ra_gp)\n    lcpml = np.arctan2(cos_dec * sin_ra_gp,\n                       (np.cos(de_gp) * sin_dec) \\\n                       - (np.sin(de_gp) * cos_dec * cos_ra_gp))\n    glat = np.arcsin(sin_b)\n    glon = (lcp - lcpml + (2. * np.pi)) % (2. * np.pi)\n    return np.degrees(glon), np.degrees(glat)\n\n# Stupid timezone definition\nZERO = timedelta(0)\nHOUR = timedelta(hours=1)\nclass UTC(tzinfo):\n    \"\"\"UTC\"\"\"\n    def utcoffset(self, dt):\n        return ZERO\n\n    def tzname(self, dt):\n        return \"UTC\"\n\n    def dst(self, dt):\n        return ZERO\n\ndef safe_proj(bmap,lon,lat,inverse=False):\n    \"\"\" Remove points outside of projection \n    \n    Parameters:\n    -----------\n    bmap : basemap\n    lon  : longitude\n    lat  : latitude\n    inverse : inverse projection\n\n    Returns:\n    --------\n    x,y : projected coordinates    \n    \"\"\"\n    x,y = bmap(np.atleast_1d(lon),np.atleast_1d(lat),inverse=inverse)\n    x[np.abs(x) > 1e29] = None\n    y[np.abs(y) > 1e29] = None\n    return x,y\n\ndef get_boundary(bmap,projection,fact=0.99):\n    # Check that point inside boundary\n    # Doesn't work for 'ait' and 'moll' projections\n    if projection in basemap._pseudocyl:\n        # This was estimated by eye...\n        rminor=9.00995e6; rmajor = 2*rminor\n        boundary = Ellipse((rmajor,rminor),\n                           2*(fact*rmajor),2*(fact*rminor))\n    else:\n        boundary = Ellipse((bmap.rmajor,bmap.rminor),\n                           2*(fact*bmap.rmajor),2*(fact*bmap.rminor))\n\n    return boundary\n\n\ndef airmass_angle(x=1.4):\n    \"\"\" Zenith angle for a given airmass limit \"\"\"\n    return 90.-np.degrees(np.arcsin(1./x))\n\ndef load_data(opts):\n    \"\"\" Load the data (either from DB of file). \n\n    Parameters:\n    -----------\n    opts : command line options\n    \n    Returns:\n    --------\n    data : numpy recarray\n    \"\"\"\n    since = parse_since(opts.since)\n    propid = '%' if opts.propid is None else opts.propid\n    dtype=[('expnum',int),('telra',float),('teldec',float),('filter',object)]\n\n    if opts.infile is None:\n        selection = ['id','telra','teldec','filter']\n        #filter = \"exposed = TRUE AND flavor LIKE '%s' AND date > '%s' AND propid LIKE '%s' ORDER BY id DESC\"%(opts.flavor,since.isoformat(),propid)\n        filter = \"exposed = TRUE AND flavor SIMILAR TO '%s' AND date > '%s' AND propid LIKE '%s' ORDER BY id DESC\"%(opts.flavor,since.isoformat(),propid)\n        # Use the FNAL mirror to avoid overloading CTIO\n        try: from database import Database\n        except ImportError: from pointing.database import Database\n        db = Database(dbname='db-'+opts.db)\n        db.connect()\n        query = \"SELECT %s FROM exposure WHERE %s\"%(','.join(selection),filter)\n        #query = \"SELECT id as expnum,telra as ra,teldec as dec,filter as band FROM exposure WHERE exposed = TRUE AND flavor LIKE 'object' and telra between 80 and 82 AND teldec between -71 and -69\"\n        data = db.execute(query)\n\n        if len(data): ret = np.rec.array(data,dtype=dtype)\n        else:         ret = np.rec.recarray(0,dtype=dtype)\n\n        return ret\n    else:\n        return np.loadtxt(opts.infile,dtype=dtype)\n\ndef mjd(datetime):\n    \"\"\" Modified Julian Date (MJD) \"\"\"\n    mjd_epoch = dateutil.parser.parse('1858-11-17T00:00:00Z')\n    mjd_date = (datetime-mjd_epoch).total_seconds()/float(24*60*60)\n    return mjd_date\n\ndef lmst(observatory):\n    \"\"\" Calculate Local Mean Sidereal Time (LMST) \"\"\"\n    lmst = np.degrees(observatory.sidereal_time())\n    logging.debug('Using pyephem for LMST: %.3f'%lmst)\n    return lmst\n\ndef moon(datetime):\n    \"\"\" Moon location \n    \n    Parameters:\n    -----------\n    datetime : the datetime of moon location request\n    \n    Returns:\n    --------\n    (ra, dec), phase : moon parameters [(deg, deg), %]\n    \"\"\"\n    moon = ephem.Moon()\n    moon.compute(CTIO)\n    moon_phase = moon.moon_phase * 100\n    moon_ra,moon_dec = np.degrees([moon.ra,moon.dec])\n    return (moon_ra, moon_dec),moon_phase\n\ndef boolean(string):\n    \"\"\" Convert strings to booleans for argparse \"\"\"\n    string = string.lower()\n    if string in ['0', 'f', 'false', 'no', 'off']:\n        return False\n    elif string in ['1', 't', 'true', 'yes', 'on']:\n        return True\n    else:\n        raise ValueError()\n\ndef splash_screen():\n    \"\"\" Splash text to print \"\"\"\n    splash = \"\"\"Running Alex Drlica-Wagner's DECam pointing script...\"\"\"\n    logging.info(splash)\n\ndef parse_utc(value):\n    \"\"\" Parse isoformat 'utc' option string. \"\"\"\n    if value is None:\n        utc = datetime.now(tz=UTC())\n    elif isinstance(value,datetime):\n        utc = value\n    else:\n        utc = dateutil.parser.parse(value,tzinfos={'UTC':UTC})\n    logging.debug(\"UTC: %s\"%utc.strftime('%Y-%m-%d %H:%M:%S'))\n    return utc\n\ndef parse_since(value):\n    \"\"\" Parse isoformat 'since' option string. \"\"\"\n    if value is None:\n        since = datetime.now(tz=UTC()) - timedelta(hours=12)\n    elif isinstance(value,datetime):\n        since = value\n    elif value.lower() in ['all','none','forever']:\n        since = dateutil.parser.parse('2012-01-01 12:00',tzinfos={'UTC':UTC})\n    else:\n        since = dateutil.parser.parse(value,tzinfos={'UTC':UTC})\n    logging.debug(\"Since: %s\"%since.strftime('%Y-%m-%d %H:%M:%S'))\n    return since\n\ndef draw_constellation(bmap,name):\n    \"\"\" Draw a map of the constellations (work in progress). \"\"\"\n    from constellations import CONSTELLATIONS\n    points = np.array(CONSTELLATIONS[name])\n\n    drawtype = points[:,0]\n    radeg = points[:,1] * 1.0 / 1800 * 15\n    decdeg = points[:,2] * 1.0 / 60\n    print(radeg,decdeg)\n    verts = zip(safe_proj(bmap,radeg,decdeg))\n    codes = [XEPHEM2PATH[c] for c in points[:,0]]\n    print(x,y)\n\ndef draw_milky_way(bmap,width=10,**kwargs):\n    \"\"\" Draw the Milky Way galaxy. \"\"\"\n    defaults = dict(color='k',lw=1.5,ls='-')\n    setdefaults(kwargs,defaults)\n\n    logging.debug(\"Plotting the Milky Way\")\n    glon = np.linspace(0,360,500)\n    glat = np.zeros_like(glon)\n    ra,dec = gal2cel(glon,glat)\n    ra -= 360*(ra > 180)\n\n    proj = safe_proj(bmap,ra,dec)\n    bmap.plot(*proj,**kwargs)\n\n    if width:\n        kwargs.update(dict(ls='--',lw=1))\n        for delta in [+width,-width]:\n            ra,dec = gal2cel(glon,glat+delta)\n            proj = safe_proj(bmap,ra,dec)\n            bmap.plot(*proj,**kwargs)\n\ndef draw_des(bmap,**kwargs):\n    \"\"\"\n    Plot the DES wide-field footprint.\n\n    Parameters:\n    -----------\n    bmap   : The basemap object\n    kwargs : Various plotting arguments\n\n    Returns:\n    --------\n    None\n    \"\"\"\n    # Plot the wide-field survey footprint\n    logging.debug(\"Plotting footprint: %s\"%opts.footprint)\n    #basedir = os.path.dirname(os.path.abspath(__file__))\n    infile = os.path.join(get_datadir(),'des-round19-poly.txt')\n    perim = np.loadtxt(infile,dtype=[('ra',float),('dec',float)])\n    proj = safe_proj(bmap,perim['ra'],perim['dec'])\n    bmap.plot(*proj,**kwargs)\n\ndef draw_des_sn(bmap,**kwargs):\n    \"\"\"\n    Plot the DES supernova fields.\n\n    Parameters:\n    -----------\n    bmap   : The basemap object\n    kwargs : Various plotting arguments\n\n    Returns:\n    --------\n    None\n    \"\"\"\n    # Plot the SN fields\n    logging.debug(\"Plotting DES supernova fields.\")\n\n    boundary = get_boundary(bmap,kwargs.pop('projection',None),fact=0.99)\n    for v in SN.values():\n        if not boundary.contains_point(bmap(*v)):\n            continue\n        # This does the projection correctly, but fails at boundary\n        bmap.tissot(v[0],v[1],DECAM,100,**kwargs)\n\n    # The SN labels\n    sntxt_kwargs = dict(zorder=kwargs['zorder'],fontsize=12,\n                        bbox=dict(boxstyle='round,pad=0',fc='w',ec='none',\n                                  alpha=0.25))\n    for k,v in SN_LABELS.items():\n        plt.gca().annotate(k,bmap(*v),**sntxt_kwargs)\n\ndef draw_smash(bmap,**kwargs):\n    \"\"\" Draw the SMASH fields \n\n    Parameters:\n    -----------\n    bmap   : The basemap object\n    kwargs : Various plotting arguments\n\n    Returns:\n    --------\n    None\n    \"\"\"\n    filename = os.path.join(get_datadir(),'smash_fields_final.txt')\n\n    smash=np.genfromtxt(filename,dtype=[('ra',float),('dec',float)],usecols=[4,5])\n    smash_x,smash_y = safe_proj(bmap,smash['ra'],smash['dec'])\n    kwargs.update(dict(facecolor='none'))\n    bmap.scatter(smash_x,smash_y,color='k',**kwargs)\n\ndef draw_maglites(bmap,**kwargs):\n    \"\"\"\n    Plot the MagLiteS Phase-I footprint.\n\n    Parameters:\n    -----------\n    bmap   : The basemap object\n    kwargs : Various plotting arguments\n\n    Returns:\n    --------\n    None\n    \"\"\"\n\n    # Plot the wide-field survey footprint\n    logging.debug(\"Plotting MagLiteS footprint\")\n    infile = os.path.join(get_datadir(),'maglites-poly.txt')\n    perim = np.loadtxt(infile,dtype=[('ra',float),('dec',float)])\n    proj = safe_proj(bmap,perim['ra'],perim['dec'])\n    bmap.plot(*proj,**kwargs)\n\ndef draw_maglites2(bmap,**kwargs):\n    \"\"\"\n    Plot the MagLiteS Phase-II footprint.\n\n    Parameters:\n    -----------\n    bmap   : The basemap object\n    kwargs : Various plotting arguments\n\n    Returns:\n    --------\n    None\n    \"\"\"\n    # Plot the wide-field survey footprint\n    logging.debug(\"Plotting footprint: %s\"%opts.footprint)\n    infile = os.path.join(get_datadir(),'maglitesII-poly.txt')\n    perim = np.loadtxt(infile,dtype=[('ra',float),('dec',float),('poly',int)])\n    for p in np.unique(perim['poly']):\n        sel = (perim['poly'] == p)\n        proj = safe_proj(bmap,perim[sel]['ra'],perim[sel]['dec'])\n        bmap.plot(*proj,**kwargs)\n\ndef draw_bliss(bmap,**kwargs):\n    \"\"\"\n    Plot the BLISS wide-field footprint.\n\n    Parameters:\n    -----------\n    bmap   : The basemap object\n    kwargs : Various plotting arguments\n\n    Returns:\n    --------\n    None\n    \"\"\"\n    # Plot the wide-field survey footprint\n    logging.debug(\"Plotting footprint: %s\"%opts.footprint)\n    infile = os.path.join(get_datadir(),'bliss-poly.txt')\n    perim = np.loadtxt(infile,dtype=[('ra',float),('dec',float),('poly',int)])\n    for p in np.unique(perim['poly']):\n        sel = (perim['poly'] == p)\n        proj = safe_proj(bmap,perim[sel]['ra'],perim[sel]['dec'])\n        bmap.plot(*proj,**kwargs)\n\ndef draw_decals(bmap,**kwargs):\n    \"\"\"\n    Plot the DECaLS wide-field footprint.\n\n    Parameters:\n    -----------\n    bmap   : The basemap object\n    kwargs : Various plotting arguments\n\n    Returns:\n    --------\n    None\n    \"\"\"\n    # Plot the wide-field survey footprint\n    logging.debug(\"Plotting footprint: %s\"%opts.footprint)\n    infile = os.path.join(get_datadir(),'decals-poly.txt')\n    perim = np.loadtxt(infile,dtype=[('ra',float),('dec',float),('poly',int)])\n    for p in np.unique(perim['poly']):\n        sel = (perim['poly'] == p)\n        proj = safe_proj(bmap,perim[sel]['ra'],perim[sel]['dec'])\n        bmap.plot(*proj,**kwargs)\n\ndef draw_delve(bmap,**kwargs):\n    \"\"\" Draw DELVE footprint \"\"\"\n    defaults=dict(color='red', lw=2)\n    setdefaults(kwargs,defaults)\n\n    logging.debug(\"Plotting footprint: %s\"%opts.footprint)\n    deep = odict([\n        ('SextansB', (150.00,   5.33, 3.0)),\n        ('IC5152',   (330.67, -51.30, 3.0)),\n        ('NGC300',   ( 13.72, -37.68, 3.0)),\n        ('NGC55',    (  3.79, -39.22, 3.0)),\n    ])\n    boundary = get_boundary(bmap,kwargs.pop('projection',None),fact=0.98)\n\n    for ra,dec,radius in deep.values():\n        if not boundary.contains_point(bmap(ra,dec)): continue\n        # This does the projection correctly, but fails at boundary\n        bmap.tissot(ra,dec,radius,100,fc='none',edgecolor=kwargs['color'],lw=kwargs['lw'])\n\n    #for ra,dec,radius in deep.values():\n    #    # This doesn't deal with boundaries well\n    #    #self.tissot(ra, dec, radius, 100, fc='none',**kwargs)\n    #    x,y = safe_proj(bmap,np.array([ra]), np.array([dec]))\n    #    bmap.scatter(x,y,facecolor='none',edgecolor=kwargs['color'],lw=2,s=400)\n\n    filename = os.path.join(get_datadir(),'delve-poly.txt')\n    perim = np.loadtxt(filename,dtype=[('ra',float),('dec',float),('poly',int)])\n    for p in np.unique(perim['poly']):\n        sel = (perim['poly'] == p)\n        proj = safe_proj(bmap,perim[sel]['ra'],perim[sel]['dec'])\n        bmap.plot(*proj,**kwargs)\n\ndef plot(opts):\n    \"\"\" \n    Core plotting function. Creates the basemap, overplots all of the\n    requested features, and returns the map object.\n\n    Parameters:\n    -----------\n    opts : command line options\n    \n    Returns:\n    --------\n    m : the basemap object\n    \"\"\"\n    utc = parse_utc(opts.utc)\n    CTIO.date = utc\n    since = parse_since(opts.since)\n\n    # Grab the data\n    data = load_data(opts)\n\n    # Subselect the data\n    sel = np.in1d(data['filter'],FILTERS)\n    if opts.band in FILTERS:\n        sel &= (data['filter'] == opts.band)\n    data = data[sel]\n\n    expnum,telra,teldec,band = data['expnum'],data['telra'],data['teldec'],data['filter']\n\n    # Set the colors\n    if opts.color:\n        nexp = len(expnum)\n        ncolors = len(COLORS)\n        color_repeat = np.repeat(COLORS.keys(),nexp).reshape(ncolors,nexp)\n        color_idx = np.argmax(band==color_repeat,axis=0)\n        color = np.array(COLORS.values())[color_idx]\n    else:\n        color = COLORS['none']\n\n    # Select the exposure of interest\n    if opts.expnum:\n        match = np.char.array(expnum).endswith(str(opts.expnum))\n        if not match.any():\n            msg = \"Exposure matching %s not found\"%opts.expnum\n            raise ValueError(msg)\n        idx = np.nonzero(match)[0][0]\n    elif len(data)==0:\n        idx = slice(None)\n    else:\n        idx = 0\n\n    # Create the figure\n    if plt.get_fignums():\n        fig,ax = plt.gcf(),plt.gca()\n    else:\n        fig,ax = plt.subplots(figsize=FIGSIZE,dpi=DPI)\n        fig.canvas.set_window_title(\"DECam Pointings\")\n    #fig,ax = plt.subplots()\n\n    # Zenith position\n    lon_zen=lmst(CTIO); lat_zen = TEL_LAT\n    # Create the Basemap\n    proj_kwargs = PROJ[opts.proj]\n    # Centering position\n    if proj_kwargs['projection'] in basemap._pseudocyl:\n        ### This should work, but doesn't.\n        ### Compare lon_0=-80.58345277606 to lon_0=-80.6 or lon_0=-80.5\n        #lon_0=lon_zen-360*(lon_zen>180),lat_zen=0\n        lon_0,lat_0 = 0,0\n    else:\n        lon_0,lat_0 = -lon_zen, lat_zen # Center position\n\n    proj_kwargs.update(lon_0=lon_0,lat_0=lat_0)\n\n    bmap = basemap.Basemap(**proj_kwargs)\n    def format_coord(x,y):\n        #Format matplotlib cursor to display RA, Dec\n        lon,lat = safe_proj(bmap,x,y,inverse=True)\n        lon += 360*(lon < 0)\n        return 'ra=%1.3f, dec=%1.3f'%(lon,lat)\n    plt.gca().format_coord = format_coord\n\n    parallels = np.arange(-90.,120.,30.)\n    bmap.drawparallels(parallels)\n    meridians = np.arange(0.,420.,60.)\n    bmap.drawmeridians(meridians)\n    for mer in meridians[:-1]:\n        plt.annotate(r'$%i^{\\circ}$'%mer,bmap(mer,5),ha='center')\n    plt.annotate('West',xy=(1.0,0.5),ha='left',xycoords='axes fraction')\n    plt.annotate('East',xy=(0.0,0.5),ha='right',xycoords='axes fraction')\n\n    # markersize defined at minimum distortion point\n    if proj_kwargs['projection'] in basemap._pseudocyl:\n        x1,y1=ax.transData.transform(bmap(lon_0,lat_0+DECAM))\n        x2,y2=ax.transData.transform(bmap(lon_0,lat_0-DECAM))\n    else:\n        x1,y1=ax.transData.transform(bmap(lon_zen,lat_zen+DECAM))\n        x2,y2=ax.transData.transform(bmap(lon_zen,lat_zen-DECAM))\n\n    # Since markersize defined in \"points\" in scales with figsize/dpi\n    size = SCALE * (y1-y2)**2\n\n    # Scale the marker size to the size of an exposure\n    exp_zorder = 10\n    exp_kwargs = dict(s=size,marker='H',zorder=exp_zorder,edgecolor='k',lw=1)\n\n    # Projected exposure locations\n    x,y = safe_proj(bmap,telra,teldec)\n\n    # Plot exposure of interest\n    if len(data):\n        logging.debug(\"Plotting exposure: %i (%3.2f,%3.2f)\"%(expnum[idx],telra[idx],teldec[idx]))\n        # Hacked path effect (fix if matplotlib is updated)\n        bmap.scatter(x[idx],y[idx],color='w',**dict(exp_kwargs,edgecolor='w',s=70,lw=2))\n        bmap.scatter(x[idx],y[idx],color=color,**dict(exp_kwargs,alpha=1.0,linewidth=2))\n\n    # Once matplotlib is updated\n    #x = bmap.scatter(x[idx],y[idx],color=color,**exp_kwargs)\n    #ef = patheffects.withStroke(foreground=\"w\", linewidth=3)\n    #x.set_path_effects([ef])\n\n    # Plot previous exposures\n    nexp_kwargs = dict(exp_kwargs)\n    nexp_kwargs.update(zorder=exp_zorder-1,alpha=0.2,edgecolor='none')#,lw=0)\n\n    exp_slice = slice(None,opts.numexp)\n    numexp = len(x[exp_slice])\n    logging.debug(\"Plotting last %s exposures\"%(numexp))\n    bmap.scatter(x[exp_slice],y[exp_slice],color=color[exp_slice],**nexp_kwargs)\n\n    # Plot zenith position & focal plane scale\n    zen_x,zen_y = bmap(lon_zen,lat_zen)\n    #zen_kwargs = dict(color='green',alpha=0.75,lw=1,zorder=0)\n    zen_kwargs = dict(color='green',alpha=0.75,lw=1,zorder=1000)\n    if opts.zenith:\n        logging.debug(\"Plotting zenith: (%.2f,%.2f)\"%(lon_zen,lat_zen))\n        bmap.plot(zen_x,zen_y,'+',ms=10,**zen_kwargs)\n        logging.debug(\"Plotting focal plane scale.\")\n        bmap.tissot(lon_zen, lat_zen, DECAM, 100, fc='none', **zen_kwargs)\n\n        # To test exposure size\n        #bmap.tissot(lon_zen, lat_zen, DECAM, 100, fc='none', **zen_kwargs)\n        #bmap.scatter(*bmap(lon_zen,lat_zen),**nexp_kwargs)\n        #bmap.tissot(0, 0, DECAM, 100, fc='none', **zen_kwargs)\n        #bmap.scatter(*bmap(0,0),**nexp_kwargs)\n\n\n    # Plot airmass circle\n    if opts.airmass < 1:\n        logging.warning(\"Airmass must be greater than one.\")\n        opts.airmass = np.nan\n    else:\n        logging.debug(\"Plotting airmass: %s\"%opts.airmass)\n        angle = airmass_angle(opts.airmass)\n        bmap.tissot(lon_zen, lat_zen, angle, 100, fc='none',**zen_kwargs)\n\n    # Moon location and phase\n    (moon_ra,moon_dec),moon_phase = moon(utc)\n    if opts.moon:\n        logging.debug(\"Plotting moon: %i%%,(%.1f,%.1f)\"%(moon_phase,moon_ra,moon_dec))\n        moon_txt = '%i%%'%moon_phase\n        #bbox = dict(boxstyle='circle,pad=0.4',fc='k',ec='k',alpha=0.25,lw=2)\n        moon_kwargs = dict(zorder=exp_zorder-1,fontsize=11,va='center',ha='center',weight='bold')\n        ax.annotate(moon_txt,bmap(moon_ra,moon_dec),**moon_kwargs)\n        # Again old matplotlib making things difficult\n        moon_kwargs2 = dict(facecolor='k',alpha=0.25,lw=2,s=2000)\n        ax.scatter(*bmap(moon_ra,moon_dec),**moon_kwargs2)\n\n    if opts.mw:\n        mw_kwargs = dict(color='k')\n        draw_milky_way(bmap,**mw_kwargs)\n\n    # Plot footprint(s)\n    fp_zorder=exp_zorder-1\n    fp_kwargs=dict(marker='o',mew=0,mfc='none',color='k',lw=2,zorder=fp_zorder)\n    if 'none' in opts.footprint:\n        opts.footprint = ['none']\n    if 'des' in opts.footprint:\n        des_kwargs = dict(fp_kwargs,color='b')\n        draw_des(bmap,**des_kwargs)\n    if 'des' in opts.footprint or 'des-sn' in opts.footprint:\n        sn_kwargs = dict(facecolor='none',edgecolor='b',projection=proj_kwargs['projection'],zorder=fp_zorder)\n        draw_des_sn(bmap,**sn_kwargs)\n    if 'smash' in opts.footprint:\n        smash_kwargs = dict(facecolor='none',**exp_kwargs)\n        smash_kwargs.update(zorder=exp_zorder+1)\n        draw_smash(bmap,**smash_kwargs)\n    if 'maglites' in opts.footprint:\n        maglites_kwargs = dict(fp_kwargs,color='r')\n        draw_maglites(bmap,**maglites_kwargs)\n        draw_maglites2(bmap,**maglites_kwargs)\n    if 'bliss' in opts.footprint:\n        bliss_kwargs = dict(fp_kwargs,color='r')\n        draw_bliss(bmap,**bliss_kwargs)\n    if 'decals' in opts.footprint:\n        decals_kwargs = dict(fp_kwargs,color='m')\n        draw_decals(bmap,**decals_kwargs)\n    if 'delve' in opts.footprint:\n        delve_kwargs = dict(fp_kwargs,color='r')\n        draw_delve(bmap,**delve_kwargs)\n\n    # Annotate with some information\n    if opts.legend:\n        logging.debug(\"Adding info text.\")\n        bbox_props = dict(boxstyle='round', facecolor='white')\n        textstr= \"%s %s\\n\"%(\"UTC:\",utc.strftime('%Y-%m-%d %H:%M:%S'))\n        if len(data):\n            textstr+=\"%s %i (%s)\\n\"%(\"Exposure:\",expnum[idx],band[idx])\n        textstr+=\"%s %i\\n\"%(\"Num. Exp.:\",numexp)\n        textstr+=\"%s (%.1f$^{\\circ}$, %.1f$^{\\circ}$)\\n\"%(\"Zenith:\",lon_zen,lat_zen)\n        textstr+=\"%s %s\\n\"%(\"Airmass:\",np.nan_to_num(opts.airmass))\n        textstr+=\"%s %i%% (%.1f$^{\\circ}$, %.1f$^{\\circ}$)\\n\"%(\"Moon:\",moon_phase,moon_ra,moon_dec)\n        textstr+=\"%s %s\"%(\"Footprint:\",', '.join(opts.footprint))\n\n        ax.annotate(textstr, xy=(0.90,1.05), xycoords='axes fraction',\n                    fontsize=10,ha='left',va='top', bbox=bbox_props)\n\n    # Plot filter legend\n    if opts.color:\n        logging.debug(\"Adding filter legend.\")\n        leg_kwargs = dict(scatterpoints=1,fontsize=10,bbox_to_anchor=(0.08,0.20))\n        handles, labels = [],[]\n        for k in FILTERS:\n            if k == 'VR' and not (band=='VR').any(): continue\n            labels.append(k)\n            handles.append(plt.scatter(None,None,color=COLORS[k],**exp_kwargs))\n        plt.legend(handles,labels,**leg_kwargs)\n\n    # Plot the version number\n    vers_kwargs = dict(xy=(0.985,0.015),ha='right',va='bottom',\n                       xycoords='figure fraction',size=8)\n    plt.annotate('pointing v.%s'%__version__,**vers_kwargs)\n\n    # Plot the author's name\n    auth_kwargs = dict(xy=(0.015,0.015),ha='left',va='bottom',\n                       xycoords='figure fraction',size=8)\n    plt.annotate(u'\\u00a9'+' %s'%__author__,**auth_kwargs)\n\n    return bmap\n\nif __name__ == \"__main__\":\n    import argparse\n    description = __doc__\n    parser = argparse.ArgumentParser(description=description,\n                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n    parser.add_argument('expnum',nargs='?',type=int,default=None,\n                        help=\"exposure number to plot\")\n    parser.add_argument('-a','--airmass',default=1.4,type=float,\n                        help='draw airmass limit')\n    parser.add_argument('-b','--band',default='all',choices=BANDS,\n                        help='draw exposures in specific band')\n    parser.add_argument('-c','--color',default=True,type=boolean,\n                        help='color corresponding to filter')\n    parser.add_argument('--db',default='fnal',choices=['ctio','fnal'],\n                        help='database to query for exposures')\n    parser.add_argument('-f','--footprint',action='append',choices=FOOTPRINTS,\n                        help='footprint to draw')\n    parser.add_argument('--flavor',default='object|standard',type=str,\n                        help='exposure type [object,zero,dome flat,etc.]')\n    parser.add_argument('-i','--infile',default=None,\n                        help='list of exposures to draw')\n    parser.add_argument('--legend',default=True,type=boolean,\n                        help='draw figure legend')\n    parser.add_argument('-m','--moon',default=True,type=boolean,\n                        help='draw moon location and phase')\n    parser.add_argument('--mw',action='store_true',\n                        help='draw the Milky Way plane')\n    parser.add_argument('-n','--numexp',default=None,type=int,\n                        help='number of most recent exposures to plot')\n    parser.add_argument('-o','--outfile',default=None,\n                        help='output file for saving figure')\n    parser.add_argument('--propid',default=None,\n                        help='draw exposures from specific propid')\n    parser.add_argument('--proj',default='ortho',choices=PROJ.keys(),\n                        help='projection for plot')\n    parser.add_argument('--refresh',nargs='?',default=None,const=60,type=int,\n                        help=\"refresh interval for figure (seconds).\")\n    parser.add_argument('--since',default=None,\n                        help=\"UTC for first exposure (defaults to 12 hours)\")\n    parser.add_argument('--utc',default=None,\n                        help=\"UTC for zenith position (defaults to 'now')\")\n    parser.add_argument('-v','--verbose',action='store_true',\n                        help='output verbosity')\n    parser.add_argument('--version',action='version',\n                        version='%(prog)s '+__version__)\n    parser.add_argument('-z','--zenith',default=True,type=boolean,\n                        help=\"draw zenith position\")\n\n    opts = parser.parse_args()\n\n    # Set logging level\n    logging.basicConfig(level=logging.DEBUG if opts.verbose else logging.INFO,\n                        format='%(message)s',stream=sys.stdout)\n\n    if not opts.footprint: opts.footprint = ['des']\n\n    # Do the plotting\n    m = plot(opts)\n\n    # In interactive session\n    if sys.flags.interactive: plt.ion()\n\n    if opts.outfile:\n        # Save the figure\n        logging.debug(\"Saving figure to: %s\"%opts.outfile)\n        plt.savefig(opts.outfile,dpi=250)\n    elif not opts.refresh:\n        # Show plot\n        plt.show()\n    else:\n        # Refresh the plot\n        plt.show(block=False)\n        for i in range(MAXREF): # safer than while loop\n            try: \n                plt.pause(opts.refresh)\n            except TclError:\n                # Catch the TclError thrown when window closed\n                break\n            logging.debug(\"Refreshing plot...\")\n            plt.cla()\n            m = plot(opts)\n        if i == MAXREF:\n            logging.info(\"Reached max refresh number.\")\n", "meta": {"hexsha": "04aaa72f73670a0060b1dd60d4a40d7365bda8d5", "size": 29180, "ext": "py", "lang": "Python", "max_stars_repo_path": "pointing/pointing.py", "max_stars_repo_name": "kadrlica/pointing", "max_stars_repo_head_hexsha": "9b09d937eb512e659a077159fb23d65b6a91b446", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pointing/pointing.py", "max_issues_repo_name": "kadrlica/pointing", "max_issues_repo_head_hexsha": "9b09d937eb512e659a077159fb23d65b6a91b446", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pointing/pointing.py", "max_forks_repo_name": "kadrlica/pointing", "max_forks_repo_head_hexsha": "9b09d937eb512e659a077159fb23d65b6a91b446", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2086752638, "max_line_length": 198, "alphanum_fraction": 0.6060315284, "include": true, "reason": "import numpy", "num_tokens": 8246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.3140505321516081, "lm_q1q2_score": 0.17170341221718183}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\nfrom functools import lru_cache\nfrom collections import Counter, defaultdict\nimport re\nimport datetime\nimport torch\nimport numpy as np\nimport pickle\nfrom pathlib import Path\nfrom enum import IntEnum\nfrom matplotlib import pyplot as plt\nfrom itertools import product\nimport pandas as pd\nimport matplotlib\nfrom tqdm.auto import tqdm\nfrom multiprocessing import Pool\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nclass State(IntEnum):\n    M = 0\n    I = 1\n    D = 2\n\n\nclass Transition(IntEnum):\n    M2M = 0\n    M2I = 1\n    M2D = 2\n    I2M = 3\n    I2I = 4\n    D2M = 5\n    D2D = 6\n\n\nclass nt_index(IntEnum):\n    A = 0\n    T = 1\n    G = 2\n    C = 3\n    PAD = 4\n    SOS = 5\n    EOS = 6\n    U = 1\n\n\ndef one_hot_index(seq):\n    return [int(nt_index[char]) for char in seq]\n\n\ndef one_hot_encode(nucleotide, padding=0):\n    \"\"\"入力された文字列に対してOne-hotなnp形式を返す\n    \"\"\"\n    # パディングの大きさを指定する\n    arr = np.vstack((np.eye(4), np.ones(4)[None, :]*0.25))\n    return arr[one_hot_index(\"N\"*padding + nucleotide + \"N\"*padding)].T\n\n\nclass SNV(IntEnum):\n    Mutation = 0\n    Insertion = 1\n    Deletion = 2\n\n\nclass SequenceGenerator():\n    def __init__(self, num_motifs=1, motif_length=10, motifs=None,\n                 target_length=20, fix_random_region_length=True, error_rate=0, generate_motifs=True, middle_insert_range=[2, 6],\n                 seed=0, add_primer=True, forward_primer=\"AAAAA\", reverse_primer=\"GGGGG\", one_side_proba=0.5, paired=False):\n        np.random.seed(seed)\n\n        if generate_motifs:\n            self.motifs = [\"\".join(np.random.choice(\n                list(\"ATGC\"), motif_length)) for _ in range(num_motifs)]\n        else:\n            self.motifs = motifs\n\n        self.error_indices = 1 + \\\n            np.argsort(np.random.random(size=motif_length-1))[:3]\n        self.mut_idx, self.ins_idx, self.del_idx = self.error_indices\n\n        logger.info(f\"error rate is {error_rate*100:.1f}%\")\n        for idx, motif in enumerate(self.motifs):\n            seq = [ch for ch in motif]\n            mut = self.mutate(seq[self.mut_idx])\n            if error_rate != 0:\n                seq[self.mut_idx] = f\"[{seq[self.mut_idx]}>{mut}]\"\n                seq[self.ins_idx] = f\"[+]{seq[self.ins_idx]}\"\n                seq[self.del_idx] = f\"{seq[self.del_idx].lower()}\"\n            seq = \"\".join(seq)\n            logger.info(f\"motif {idx} is {seq}\")\n\n        self.num_motifs = num_motifs\n        self.error_rate = error_rate\n        self.target_length = target_length\n        self.forward_primer = forward_primer\n        self.reverse_primer = reverse_primer\n        self.add_primer = add_primer\n\n        self.one_side_proba = one_side_proba\n        self.middle_insert_range = middle_insert_range\n        self.paired = paired\n\n    def mutate(self, char):\n        return \"TGCA\"[\"ATGC\".index(char)]\n\n    def sample_motif(self, n):\n        motif_indices = np.random.randint(self.num_motifs, size=n)\n        has_errors = np.random.random(size=n) < self.error_rate\n        # mutation, insertion, deletion\n        error_types = np.random.choice(SNV, size=n)\n        sequences = []\n        for motif_index, has_error, error_type in zip(motif_indices, has_errors, error_types):\n            motif = self.motifs[motif_index]\n            seq = [ch for ch in motif]\n            if has_error:\n                if error_type == SNV.Mutation:\n                    seq[self.mut_idx] = self.mutate(seq[self.mut_idx])\n                elif error_type == SNV.Insertion:\n                    seq[self.ins_idx] = np.random.choice(\n                        list(\"ATGC\")) + seq[self.ins_idx]\n                elif error_type == SNV.Deletion:\n                    seq[self.del_idx] = \"\"\n                else:\n                    raise NotImplementedError\n            seq = \"\".join(seq)\n            sequences.append(seq)\n        return sequences, motif_indices.tolist()\n\n    def sample(self, n=1, with_indices=True):\n        motifs, motif_indices = self.sample_motif(n)\n        sequences = []\n        paired_indices = []\n        for seq in motifs:\n            if self.paired:\n                seq, idx = self.insert_in_the_middle(\n                    seq, nrange=self.middle_insert_range, one_side_proba=self.one_side_proba)\n                paired_indices += [idx]\n            random_region = \"\".join(np.random.choice(\n                list(\"ATGC\"), size=self.target_length-len(seq)))\n            l = np.random.randint(len(random_region))\n            if self.add_primer:\n                sequences.append(\n                    self.forward_primer + random_region[:l] + seq + random_region[l:] + self.reverse_primer)\n            else:\n                sequences.append(random_region[:l] + seq + random_region[l:])\n\n        if self.paired and with_indices:\n            return sequences, motif_indices, paired_indices\n        elif with_indices:\n            return sequences, motif_indices\n        return sequences\n\n    def insert_in_the_middle(self, sequence, nrange=[2, 6], one_side_proba=0.5):\n        n = np.random.randint(*nrange)\n        if np.random.random() < one_side_proba:\n            if np.random.choice([\"l\", \"r\"]) == \"l\":\n                l_motif = sequence[:len(sequence)//2]\n                r_motif = \"\"\n                idx = 1\n            else:\n                l_motif = \"\"\n                r_motif = sequence[len(sequence)//2:]\n                idx = 2\n        else:\n            l_motif = sequence[:len(sequence)//2]\n            r_motif = sequence[len(sequence)//2:]\n            idx = 0\n        return l_motif + \"\".join(np.random.choice(list(\"ATGC\"), size=n)) + r_motif, idx\n\n\ndef get_reads_with_id_prefix(path, prefix_on, prefix_off):\n    reads = []\n    read = \"\"\n    switch = False\n    with path.open() as f:\n        for line in f.readlines():\n            if line[0] == prefix_off:\n                switch = False\n                reads.append(read)\n                read = \"\"\n            if switch:\n                read = read + line.strip()\n            if line[0] == prefix_on:\n                switch = True\n                read = \"\"\n        # write last read line\n        reads.append(read)\n    return reads\n\n\ndef read_fasta(path):\n    return get_reads_with_id_prefix(Path(path), \">\", \">\")\n\n\ndef read_fastq(path):\n    return get_reads_with_id_prefix(Path(path), \"@\", \"+\")\n\n\nclass SingleRound:\n    \"\"\"pass path or raw_reads to make class of selex experiment per round.\n    \"\"\"\n\n    def __init__(self, raw_reads: list = None, forward_adapter=None, reverse_adapter=None, name=None, tolerance=0, path: str = None, max_len=None):\n        assert path is not None or raw_reads is not None, \"either path or raw_reads has to be specified\"\n        if path:\n            path = Path(path)\n            if path .suffix == \".fastq\":\n                logger.info(\"reading fastq format sequence\")\n                raw_reads = read_fastq(path)\n            elif path.suffix in {\".fasta\", \".fa\"}:\n                logger.info(\"reading fasta format sequence\")\n                raw_reads = read_fasta(path)\n            else:\n                logger.critical(\n                    \"please specify a file with fasta or fastq format\")\n                quit()\n\n        self.raw_reads = raw_reads\n        self.calc_target_length()\n        self.max_len = max_len\n\n        if forward_adapter is None or reverse_adapter is None:\n            logger.info(\"adapter info not provided. estimating value\")\n            self.calc_experimental_settings()\n        else:\n            logger.info(\n                f\"sequence design : {forward_adapter}-[random]-{reverse_adapter}\")\n            self.set_adapters(forward_adapter, reverse_adapter,\n                              self.max_len is not None)\n\n        if name:\n            self.name = name\n        else:\n            self.name = re.sub(r'[-\\.\\:]', \"\",\n                               str(datetime.datetime.now())).replace(\" \", \"_\")\n        logger.info(f\"experiment name : {self.name}\")\n        self.tolerance = tolerance\n\n    def get_adapters(self):\n        return self.forward_adapter, self.reverse_adapter\n\n    def set_adapters(self, forward_adapter: str, reverse_adapter: str, set_max_len=False):\n        self.forward_adapter = forward_adapter\n        self.forward_adapter_length = len(forward_adapter)\n\n        self.reverse_adapter = reverse_adapter\n        self.reverse_adapter_length = len(reverse_adapter)\n\n        self.random_region_length = self.target_length - \\\n            self.reverse_adapter_length - self.forward_adapter_length\n        if set_max_len:\n            self.random_region_length = self.max_len\n\n    def calc_target_length(self):\n        from collections import Counter, defaultdict\n        self.read_counter = Counter(self.raw_reads)\n\n        # calc most common length\n        d = defaultdict(int)\n        for key, value in self.read_counter.items():\n            d[len(key)] += value\n        self.target_length = sorted(d.items(), key=lambda x: -x[1])[0][0]\n\n    def calc_experimental_settings(self):\n        \"\"\"calculate sequence adapters in a heuristic way\n        \"\"\"\n\n        # fwd\n        max_count = None\n        est_adapter = \"\"\n        for i in range(1, self.target_length):\n            d = defaultdict(int)\n            for seq, count in self.read_counter.most_common():\n                if len(seq) < i or len(d) > 100 and seq[:i] not in d.keys():\n                    continue\n                d[seq[:i]] += count\n            top_seq, top_count = sorted(d.items(), key=lambda x: -x[1])[0]\n            if max_count is not None and top_count < max_count * 0.5:  # heuristics\n                logger.info(\n                    f\"estimated forward adapter len is {i-1} : {est_adapter}\")\n                break\n            max_count = sorted(d.items(), key=lambda x: -x[1])[0][1]\n            if max_count < sum(self.read_counter.values()) * 0.5:\n                logger.info(\n                    f\"no match found.\")\n                break\n            est_adapter = top_seq\n        fwd_len = i - 1\n        fwd_adapter = est_adapter\n\n        # rev\n        max_count = None\n        est_adapter = \"\"\n        for i in range(1, self.target_length):\n            d = defaultdict(int)\n            for seq, count in self.read_counter.most_common():\n                if len(seq) < i or len(d) > 100 and seq[-i:] not in d.keys():\n                    continue\n                d[seq[-i:]] += count\n            top_seq, top_count = sorted(d.items(), key=lambda x: -x[1])[0]\n            if max_count is not None and top_count < max_count * 0.5:  # heuristics\n                logger.info(\n                    f\"estimated reverse adapter len is {i-1} : {est_adapter}\")\n                break\n            max_count = sorted(d.items(), key=lambda x: -x[1])[0][1]\n            if max_count < sum(self.read_counter.values()) * 0.5:\n                logger.info(\n                    f\"no match found.\")\n                break\n            est_adapter = top_seq\n        rev_len = i - 1\n        rev_adapter = est_adapter\n\n        rand_len = self.target_length - rev_len - fwd_len\n\n        logger.info(\n            f\"filtering with : {fwd_adapter}({fwd_len}N)-{rand_len}N-{rev_adapter}({rev_len}N)\")\n\n        # write estimated experimental settings\n        self.set_adapters(fwd_adapter, rev_adapter, self.max_len is not None)\n\n    def get_sequences_and_count(self):\n        c = Counter(self.raw_reads)\n        return c.most_common()\n\n    def get_filter_passed_sequences_and_count(self, random_only=False):\n        if random_only:\n            return {self.cut_adapters(key): value for key, value in self.get_sequences_and_count()}\n        else:\n            c = Counter(self.get_filter_passed_sequences())\n            return c.most_common()\n\n    def filter_function(self, read):\n        has_forward = read[: self.forward_adapter_length] == self.forward_adapter \\\n            or self.forward_adapter_length == 0\n        has_reverse = read[-self.reverse_adapter_length:] == self.reverse_adapter \\\n            or self.reverse_adapter_length == 0\n        match_random_region_len = abs(\n            len(read) - self.target_length) <= self.tolerance\n        return has_forward and has_reverse and match_random_region_len\n\n    def get_filter_passed_sequences(self, random_only=False):\n        self.filter_passed = list(filter(self.filter_function, self.raw_reads))\n        if random_only:\n            return [self.cut_adapters(read) for read in self.filter_passed]\n        return self.filter_passed\n\n    def cut_adapters(self, seq):\n        if self.reverse_adapter_length == 0:\n            ret = seq[self.forward_adapter_length:]\n        else:\n            ret = seq[self.forward_adapter_length: -\n                      self.reverse_adapter_length]\n        if self.max_len is not None:\n            return ret[len(ret) // 2 - self.max_len // 2: len(ret) // 2 - self.max_len // 2 + self.max_len]\n        else:\n            return ret\n\n    def __str__(self):\n        return f\"experiment of {len(self.raw_reads)} raw reads\"\n\n    def get_dataloader(self, min_count=1, test_size=0.1, batch_size=512, shuffle=True, use_cuda=True):\n        from sklearn.model_selection import train_test_split\n        from torch.utils.data import DataLoader\n\n        self.min_count = min_count\n        kwargs = {'num_workers': 1, 'pin_memory': True} if (\n            use_cuda and torch.cuda.is_available()) else {}\n        # load RAPT1-4R and filter reads to count>1, then make it to one hot encoded tensor\n        c = self.get_filter_passed_sequences(random_only=True)\n        sequences = list(\n            filter(lambda seq_count: seq_count[1] >= min_count, Counter(c).most_common()))\n        seq, _ = zip(*sequences)\n\n        train_test = np.array(list(map(one_hot_index, seq)))\n        logger.info(f\"# of sequences -> {len(train_test)}\")\n        train_data, test_data = train_test_split(\n            train_test, test_size=test_size, shuffle=shuffle)\n        train_data = torch.from_numpy(train_data).long()\n        test_data = torch.from_numpy(test_data).long()\n        train_loader = DataLoader(\n            train_data, batch_size=batch_size, shuffle=True,  **kwargs)\n        test_loader = DataLoader(\n            test_data,  batch_size=batch_size, shuffle=False, **kwargs)\n        return train_loader, test_loader\n\n\nclass Dataset(torch.utils.data.Dataset):\n    def __init__(self, data, transform=None):\n        self.transform = transform\n        self.data = data\n\n    def __len__(self):\n        return len(self.data)\n\n    def __getitem__(self, index):\n        out_data = self.data[index]\n        return out_data\n\n\ndef local_alignment(s1, s2, print_result=False, global_alignment=False):\n    GAP_COST = -1\n    MATCH_COST = +1\n    MISMATCH_COST = -1\n\n    # [[(0,0) for i in range(len(s2)+1)] for j in range(len(s1)+1)]\n    dp = np.zeros((len(s1) + 1, len(s2) + 1, 2), dtype=np.int)\n\n    def s(c1, c2):\n        return MATCH_COST if c1 == c2 else MISMATCH_COST\n\n    def idx_max(*args):\n        argmax_i = np.argmax(args)\n        return argmax_i, args[argmax_i]\n\n    def concat(ret, a, b):\n        return a + ret[0], b + ret[1]\n\n    OBJ = 1\n    POINTER_INDEX_TO_COND = [\"MATCH\", \"S1_GAP\", \"S2_GAP\", \"END\"]\n\n    # DP\n    for i1, c1 in enumerate(s1):\n        for i2, c2 in enumerate(s2):\n            l = [dp[i1][i2][OBJ] + s(c1, c2),\n                 dp[i1][i2 + 1][OBJ] + GAP_COST,\n                 dp[i1 + 1][i2][OBJ] + GAP_COST]\n            if not global_alignment:\n                l += [0]\n            dp[i1 + 1][i2 + 1] = idx_max(*l)\n\n    # local_alignment_traceback\n    # logger.info(list(zip(*np.where(dp[:,:,OBJ]==dp[:,:,OBJ].max()))))\n    result = []\n    if global_alignment:\n        traceback_starts = [(len(s1), len(s2))]\n    else:\n        traceback_starts = list(\n            zip(*np.where(dp[:, :, OBJ] == dp[:, :, OBJ].max())))\n    for i1, i2 in traceback_starts:\n        traceback_pointer = dp[i1, i2, 0]\n        ret = [\"\", \"\"]\n        while True:\n            if print_result:\n                logger.info(i1, i2, POINTER_INDEX_TO_COND[traceback_pointer])\n            if POINTER_INDEX_TO_COND[traceback_pointer] == \"MATCH\":\n                i1 -= 1\n                i2 -= 1\n                if i1 < 0 or i2 < 0:\n                    break\n                if s1[i1] != s2[i2]:\n                    ret = concat(ret, s1[i1].lower(), s2[i2].lower())\n                else:\n                    ret = concat(ret, s1[i1], s2[i2])\n                traceback_pointer = dp[i1, i2, 0]\n            elif POINTER_INDEX_TO_COND[traceback_pointer] == \"S1_GAP\":\n                i1 -= 1\n                if i1 < 0 or i2 < 0:\n                    break\n                ret = concat(ret, s1[i1], \"-\")\n                traceback_pointer = dp[i1, i2, 0]\n            elif POINTER_INDEX_TO_COND[traceback_pointer] == \"S2_GAP\":\n                i2 -= 1\n                if i1 < 0 or i2 < 0:\n                    break\n                ret = concat(ret, \"-\", s2[i2])\n                traceback_pointer = dp[i1, i2, 0]\n            else:\n                break\n        if print_result:\n            logger.info(ret, dp[:, :, OBJ].max())\n        result.append(ret)\n    return dp[:, :, OBJ].max(), result\n\n\n# from https://rosettacode.org/wiki/Levenshtein_distance#Memoized_recursive_version_2\n@lru_cache(maxsize=2**26)\ndef edit_distance(s, t):\n    if not s:\n        return len(t)\n    if not t:\n        return len(s)\n    if s[0] == t[0]:\n        return edit_distance(s[1:], t[1:])\n    l1 = edit_distance(s, t[1:])\n    l2 = edit_distance(s[1:], t)\n    l3 = edit_distance(s[1:], t[1:])\n    return 1 + min(l1, l2, l3)\n\n\ndef get_complement_sequence(seq):\n    return \"\".join(reversed([list(\"ATGC\")[\"TACG\".index(char)] for char in seq]))\n\n\nclass ProfileHMMSampler():\n    def __init__(self, transition_proba, emission_proba, proba_is_log=False):\n        self.e = emission_proba\n        self.a = transition_proba\n        if proba_is_log:\n            self.e = np.exp(self.e)\n            self.a = np.exp(self.a)\n        self.e = self.e / np.sum(self.e, axis=1)[:, None]\n\n    def sample(self, sequence_only=False, debug=False):\n        idx, state = (0, State.M)\n        states = [(idx, state)]\n        seq = \"\"\n        while True:\n            if state == State.M:\n                p = self.a[idx][np.array([\n                    Transition.M2M.value,\n                    Transition.M2I.value,\n                    Transition.M2D.value])]\n            elif state == State.I:\n                p = np.stack([\n                    self.a[idx][Transition.I2M.value],\n                    self.a[idx][Transition.I2I.value],\n                    0])\n            elif state == State.D:\n                p = np.stack([\n                    self.a[idx][Transition.D2M.value],\n                    0,\n                    self.a[idx][Transition.D2D.value]])\n            else:\n                logger.info(\"something wrong\")\n\n            state = np.random.choice([State.M, State.I, State.D], p=p/sum(p))\n            if state != State.I:\n                idx += 1\n            states.append((idx, state))\n            if idx == self.a.shape[0]:\n                break\n\n            if state == State.M:\n                # logger.info(\"{:.2f}, {:.2f}, {:.2f}, {:.2f}\".format(*self.e[idx-1]))\n\n                seq += np.random.choice(list(\"ATGC\"), p=self.e[idx-1])\n                if debug:\n                    logger.info(idx, state, self.e[idx-1], seq[-1])\n            elif state == State.I:\n                seq += np.random.choice(list(\"atgc\"))\n            else:\n                seq += \"_\"\n        if not sequence_only:\n            return states, seq\n        else:\n            return seq\n\n    def most_probable(self, sequence_only=False):\n        idx, state = (0, State.M)\n        states = [(idx, state)]\n        seq = \"\"\n        while True:\n            if state == State.M:\n                p = self.a[idx][np.array([\n                    Transition.M2M.value,\n                    Transition.M2I.value,\n                    Transition.M2D.value])]\n            elif state == State.I:\n                p = [\n                    self.a[idx][Transition.I2M.value],\n                    0,\n                    0]\n            elif state == State.D:\n                p = [\n                    self.a[idx][Transition.D2M.value],\n                    0,\n                    self.a[idx][Transition.D2D.value]]\n            else:\n                logger.info(\"something wrong\")\n            p[np.argmax(p)] += 1000000\n            state = np.random.choice([State.M, State.I, State.D], p=p/sum(p))\n            if state != State.I:\n                idx += 1\n            states.append((idx, state))\n\n            if idx == self.a.shape[0]:\n                break\n\n            if state == State.M:\n                # logger.info(\"{:.2f}, {:.2f}, {:.2f}, {:.2f}\".format(*self.e[idx-1]))\n                p = np.copy(self.e[idx-1])\n                p[np.argmax(p)] += 100000\n                seq += np.random.choice(list(\"ATGC\"), p=p/sum(p))\n            elif state == State.I:\n                seq += \"N\"\n            else:\n                seq += \"_\"\n        if not sequence_only:\n            return states, seq\n        else:\n            return seq\n\n    def calc_seq_proba(self, seq: str):\n        one_hot_seq = torch.tensor(one_hot_index(seq))\n        model_len = self.e.shape[0]\n        random_len = len(seq)\n\n        e = np.log(self.e)\n        a = np.log(self.a)\n\n        F = torch.ones((3, model_len + 2, random_len + 1)) * (-100)\n\n        # init\n        F[0, 0, 0] = 0\n\n        for i in range(random_len + 1):\n            for j in range(model_len + 1):\n                # State M\n                if j*i != 0:\n                    F[State.M, j, i] = e[j - 1][one_hot_seq[i - 1]] + \\\n                        torch.logsumexp(torch.stack((\n                            a[j - 1, Transition.M2M] +\n                            F[State.M, j - 1, i - 1],\n                            a[j - 1, Transition.I2M] +\n                            F[State.I, j - 1, i - 1],\n                            a[j - 1, Transition.D2M] + F[State.D, j - 1, i - 1])), dim=0)\n\n                # State I\n                if i != 0:\n                    F[State.I, j, i] = - 1.3863 + \\\n                        torch.logsumexp(torch.stack((\n                            a[j, Transition.M2I] + F[State.M, j, i-1],\n                            a[j, Transition.I2I] + F[State.I, j, i-1]\n                        )), dim=0)\n\n                # State D\n                if j != 0:\n                    F[State.D, j, i] = \\\n                        torch.logsumexp(torch.stack((\n                            a[j - 1, Transition.M2D] + F[State.M, j - 1, i],\n                            a[j - 1, Transition.D2D] + F[State.D, j - 1, i]\n                        )), dim=0)\n\n        F[State.M, model_len+1, random_len] = \\\n            torch.logsumexp(torch.stack((\n                a[model_len, Transition.M2M] +\n                F[State.M, model_len, random_len],\n                a[model_len, Transition.I2M] +\n                F[State.I, model_len, random_len],\n                a[model_len, Transition.D2M] +\n                F[State.D, model_len, random_len]\n            )), dim=0)\n\n        return F[State.M, model_len+1, random_len]\n\n\nclass Result():\n    \"\"\"実験結果の保存のためのクラス\"\"\"\n    from raptgen.visualization import provide_ax\n\n    def __init__(self,\n                 model,\n                 path_to_selex: str = None,\n                 experiment: SingleRound = None,\n                 path_to_result_csv: str = None,\n                 path_to_model: str = None,\n                 lazy_mu_eval=False,\n                 path_to_save_results=None,\n                 evaluated_X=None,\n                 evaluated_y=None,\n                 load_if_exists=False,\n                 min_count=1\n                 ):\n\n        if experiment is None:\n            self.experiment = SingleRound(path=Path(path_to_selex))\n        else:\n            self.experiment = experiment\n\n        if path_to_result_csv:\n            self.result_df = pd.read_csv(Path(path_to_result_csv))\n        else:\n            logger.info(\"skip loading training result\")\n\n        if path_to_model:\n            model.load_state_dict(torch.load(path_to_model))\n        else:\n            logger.info(\"skip loading model parameters\")\n\n        self.model = model\n\n        if path_to_save_results is None:\n            self.path_to_save_results = Path(\n                \"result_\" + self.get_result_hash())\n        else:\n            self.path_to_save_results = Path(path_to_save_results)\n        if load_if_exists:\n            self.path_to_save_results.mkdir(parents=True, exist_ok=True)\n        else:\n            self.path_to_save_results.mkdir(parents=True)\n\n        self.is_phmm = \"PHMM\" in str(model.__class__)\n        self.min_count = min_count\n        if not lazy_mu_eval:\n            logger.info(\"evaluating mu\")\n            self.get_mean_vectors_from_experiment()\n\n        self.evaluated_X = evaluated_X\n        self.evaluated_y = evaluated_y\n\n    def get_mean_vectors_from_experiment(self, get_raw_seq=False, force=False):\n        if not hasattr(self, \"mus\") or not hasattr(self, \"seqs\") or force:\n            loaders = self.experiment.get_dataloader(\n                shuffle=False, min_count=self.min_count)\n            with torch.no_grad():\n                self.model.eval()\n                mus = []\n                seqs = []\n                for loader in loaders:\n                    for data in loader:\n                        _, mu, logvar = self.model(data, deterministic=True)\n                        mus += [*mu.detach().numpy()]\n                        for datum in data:\n                            seq = \"\".join(np.array(list(\"ATGC\"))\n                                          [datum.numpy()])\n                            seqs.append(seq)\n\n            self.mus = np.stack(mus)\n            self.seqs = seqs\n\n        if get_raw_seq:\n            return self.mus, self.seqs\n        return self.mus\n\n    def get_result_hash(self):\n        # modelのパラメタが一意に決まっていてhashしやすいのでこれを利用する\n        import hashlib\n        b = \"\".join([\"{:.2f}\".format(i.flatten()[0].cpu().detach().numpy())\n                     for i in self.model.parameters()])\n        self.hash = hashlib.sha1(b.encode()).hexdigest()[:10]\n        logger.info(f\"hash : {self.hash}\")\n        return self.hash\n\n    def calc_gmm(self, dim=10, calc_times=100, force=False):\n        from sklearn.mixture import GaussianMixture\n        logger.info(\"calculating gmm centers\")\n        X = self.mus\n        gmm_path = self.path_to_save_results/\"gmm.pkl\"\n        if gmm_path.exists():\n            logger.info(f\"loading {gmm_path}\")\n            with gmm_path.open(\"rb\") as f:\n                best_gmm = pickle.load(f)\n                best_aic = best_gmm.aic(X)\n        else:\n            best_aic = np.inf\n            pbar = tqdm(range(calc_times))\n            for i in pbar:\n                gmm = GaussianMixture(dim, covariance_type=\"full\").fit(X)\n                if gmm.aic(X) < best_aic:\n                    best_aic = gmm.aic(X)\n                    best_gmm = gmm\n                pbar.set_description(\n                    \"[\" + \"⠸⠴⠦⠇⠋⠙\"[i % 6] + \"]\" + f\"{best_aic:.2f}\")\n\n            with gmm_path.open(\"wb\") as f:\n                pickle.dump(best_gmm, f)\n\n        logger.info(f\"best aic : {best_aic}\")\n        self.gmm = best_gmm\n        self.aic = best_aic\n        self.gmm_classes = best_gmm.predict(X)\n        self.gmm_centers = best_gmm.means_\n\n    def embed_sequences(self, sequences):\n        \"\"\"\n        docstring\n        \"\"\"\n        if type(sequences) == str:\n            sequences = [sequences]\n\n        # https://discuss.pytorch.org/t/how-to-check-if-model-is-on-cuda/180\n        model_device = next(self.model.parameters()).device\n        with torch.no_grad():\n            self.model.eval()\n            mus = []\n            for sequence in sequences:\n                recon, mu, logvar = self.model(\n                    torch.Tensor(\n                        [one_hot_index(sequence)],\n                        device=model_device).long())\n                mus += [mu]\n        return torch.cat(mus)\n\n    @provide_ax\n    def plot_gmm(self, ax, fig=None, save=True, no_colors=False, no_gmm_centers=False):\n        if not hasattr(self, \"gmm\"):\n            logger.info(\"calculating gmm\")\n            self.calc_gmm()\n        if len(self.gmm_classes) > 1000:\n            if no_colors:\n                ax.scatter(*self.mus[:1000].T, s=2, c=\"silver\")\n            else:\n                ax.scatter(*self.mus[:1000].T, c=self.gmm_classes[:1000], s=2)\n        else:\n            if no_colors:\n                ax.scatter(*self.mus.T, s=2, c=\"silver\")\n            else:\n                ax.scatter(*self.mus.T, c=self.gmm_classes, s=2)\n        if not no_gmm_centers:\n            ax.scatter(*self.gmm_centers.T, c=\"r\", marker=\"*\",\n                       s=10, zorder=50, label=\"gmm center\")\n            for i, (x, y) in enumerate(self.gmm_centers):\n                ax.text(x, y, f\" {i}\", ha=\"left\", va=\"center\", c=\"r\", bbox=dict(\n                    facecolor='white', alpha=0.5), zorder=40)\n\n        ax.axis(\"square\")\n        if save:\n            fig.savefig(self.path_to_save_results/'gmm.png')\n        return ax\n\n    @provide_ax\n    def plot_means(self, ax, fig=None, with_count=False, save=True, meshgrid=True):\n        if self.mus is None:\n            logger.info(\"running estimation\")\n            self.get_mean_vectors_from_experiment()\n\n        if with_count:\n            c = Counter(\n                self.experiment.get_filter_passed_sequences(random_only=True))\n            counts = [np.log2(c[seq]) for seq in self.seqs]\n            XY = self.mus[np.argsort(counts)]\n            if meshgrid:\n                XY_ = []\n                for xy, cnt in zip(XY, [c[seq] for seq in self.seqs]):\n                    XY_ += [xy]*int(np.log2(cnt))\n                heatmap, xedges, yedges = np.histogram2d(\n                    * np.stack(XY_).T, bins=100, range=((-3, 3), (-3, 3)))\n            else:\n                cs = ax.scatter(*XY.T, s=2, c=sorted(counts), vmin=0)\n                cbar = fig.colorbar(cs)\n                cbar.ax.set_title(\"log2 counts\")\n                legend = ax.legend(*cs.legend_elements(num=6),\n                                   loc=\"lower right\", title=\"log2 count\")\n                ax.add_artist(legend)\n\n        else:\n            ax.scatter(*self.mus.T, s=2)\n        ax.axis(\"square\")\n\n        if save:\n            fig.savefig(self.path_to_save_results/'means.png')\n        return ax\n\n    @provide_ax\n    def plot_bo(self, ax, fig=None, n_grid=101, save=True, with_index=True, plot_range=(-2, 2)):\n        from mpl_toolkits.axes_grid1 import make_axes_locatable\n        if not hasattr(self, \"next_locations\"):\n            self.get_bo_result()\n\n        self.bo_grid_x, self.bo_grid_y = np.meshgrid(\n            np.linspace(*plot_range, n_grid),\n            np.linspace(*plot_range, n_grid))\n        self.bo_X = np.stack(map(np.ravel, (self.bo_grid_x, self.bo_grid_y))).T\n\n        mu, sigma = self.bo.model.predict(self.bo_X)\n        self.bo_mu = mu\n        self.bo_sigma = sigma\n\n        cont = ax.contour(self.bo_grid_x, self.bo_grid_y, -\n                          (self.bo_mu-self.bo_sigma).reshape(n_grid, n_grid))\n        cont.clabel(fmt='%1.1f', fontsize=8)\n        divider = make_axes_locatable(ax)\n        cax = divider.append_axes('right', size='5%', pad=0.05)\n\n        ax.scatter(*self.evaluated_X.T,\n                   c=self.evaluated_y[:, 0], cmap=\"bwr_r\", ec=\"grey\", lw=0.5, zorder=40, label=\"evaluated\")\n        if with_index:\n            for i, (x, y) in enumerate(self.evaluated_X):\n                ax.text(x, y, \" \"+str(i), color=\"blue\", va=\"center\")\n\n        ax.scatter(*self.next_locations.T, marker=\"*\",\n                   color=\"k\", zorder=50, label=\"bo proposed\")\n        if with_index:\n            for i, (x, y) in enumerate(self.next_locations):\n                ax.text(x, y, f\" {i}\", color=\"k\", zorder=51, va=\"center\")\n        fig.colorbar(cont, cax=cax)\n\n        return ax\n\n    def get_bo_result(self, n=10, domain=(-2, 2), force_rerun=False):\n        if hasattr(self, \"next_locations\") and not force_rerun:\n            return self.next_locations\n        import GPyOpt\n        bo_path = self.path_to_save_results/\"bo.pkl\"\n        if bo_path.exists() and not force_rerun:\n            logger.info(f\"loading {bo_path}\")\n            with bo_path.open(\"rb\") as f:\n                self.bo = pickle.load(f)\n        else:\n            logger.info(\"calculating bo\")\n            assert self.evaluated_X is not None and self.evaluated_y is not None,\\\n                \"(N, d) array: `evaluated_X` and (N, 1) array: `evaluated_y` should be set\"\n            self.domain = domain\n            self.constraints = [{\"name\": f\"var_{i+1}\",\n                                 \"type\": \"continuous\",\n                                 \"domain\": self.domain}\n                                for i in range(self.evaluated_X.shape[1])]\n\n            self.bo = GPyOpt.methods.BayesianOptimization(\n                None,\n                domain=self.constraints,\n                model_type='GP',\n                acquisition_type='LCB',\n                evaluator_type=\"local_penalization\",\n                batch_size=n,\n                X=self.evaluated_X,\n                Y=self.evaluated_y)\n            with bo_path.open(\"wb\") as f:\n                pickle.dump(self.bo, f)\n\n        self.next_locations = self.bo.suggest_next_locations()\n        return self.next_locations\n\n    def _points_to_score(self, points, eval_max=256):\n        a, e_m = self.model.decoder(points)\n        a = a.detach().numpy()\n        e_m = e_m.detach().numpy()\n\n        logger.info(\n            f\"calculating most probable sequences up to {eval_max} candidates\")\n        pbar = tqdm(range(len(points)))\n        scores = []\n        for j in pbar:\n            sampler = ProfileHMMSampler(a[j], e_m[j], proba_is_log=True)\n            seq_pattern = sampler.most_probable()[1].replace(\n                \"_\", \"\").replace(\"N\", \"*\")\n            products = product(*[list(\"ATGC\")\n                                 for _ in range(seq_pattern.count(\"*\"))])\n\n            rets = []\n            for nt_set in products:\n                ret = \"\"\n                for part, nt in zip(seq_pattern.split(\"*\"), list(nt_set)+[\"\"]):\n                    ret += part+nt\n                rets += [ret]\n            if len(rets) > eval_max:\n                rets = [rets[idx] for idx in np.argsort(\n                    np.random.randn(len(rets)))[:eval_max]]\n            with Pool() as p:\n                probas = p.map(sampler.calc_seq_proba, rets)\n\n            most_probable_seq, min_value = sorted(\n                list(zip(rets, probas)), key=lambda x: x[1])[0]\n            min_value = min_value.item()\n            scores += [(seq_pattern, most_probable_seq, min_value)]\n        self.scores = scores\n        return scores\n\n    def _save_scores(self, scores, model_type, filename, id_header=\"\", force=False, loc=None):\n        from datetime import datetime\n        if filename is not None:\n            assert not ((not force) and (self.path_to_save_results /\n                                         filename).exists()), \"file exists. to override, try: 'force=True'\"\n            with open(self.path_to_save_results / filename, \"w\") as f:\n                f.write(\"id,method,max_model,max_seq,log_proba\")\n                if loc is not None:\n                    f.write(\",pos_x,pos_y\\n\")\n                else:\n                    f.write(\"\\n\")\n\n                for i, (seq_pattern, most_probable_seq, min_value) in enumerate(scores):\n                    id_str = datetime.now().strftime(\n                        \"%-y%m%d_\") + id_header + f\"_{i}\"\n                    f.write(\n                        f\"{id_str},{model_type},{seq_pattern},{most_probable_seq},{min_value}\")\n                    if loc is not None:\n                        f.write(f\",{loc[i][0]},{loc[i][1]}\\n\")\n                    else:\n                        f.write(\"\\n\")\n            logger.info(f\"saved to {self.path_to_save_results}/{filename}\")\n\n    def get_gmm_probable_sequences(self, filename=None):\n        if hasattr(self, \"scores\"):\n            return [most_probable for seq_pattern, most_probable, min_value in self.scores]\n        if not hasattr(self, \"gmm_centers\"):\n            self.calc_gmm()\n\n        scores = self._points_to_score(torch.Tensor(self.gmm_centers))\n\n        self._save_scores(scores, \"GMM\", filename)\n\n        return [most_probable for seq_pattern, most_probable, min_value in scores]\n\n    def plot_training_result(self, nwarmup=100, save=True, fig=None, axes=None):\n        from raptgen.visualization import get_ax\n        if axes is not None and fig is not None:\n            ax, ay = axes\n        fig, (ax, ay) = get_ax(row_col=(2, 1), return_fig=True)\n\n        # for mean plot\n        length = 20\n        v = np.sin(np.arange(length)/(length-1)*np.pi)\n        v /= sum(v)\n\n        i = 0\n        for arr_name in [\"test_loss\", \"test_recon\", \"train_loss\"]:\n            cmap = plt.get_cmap(\"Paired\")\n            test_losses = np.array(self.result_df[arr_name])\n            epochs = np.arange(len(test_losses))\n            conv_indices, conv_values = np.array(\n                epochs[:-length+1])+length//2, np.convolve(test_losses, v, mode='valid')\n            ax.plot(test_losses, c=cmap(i))\n\n            ax.plot(conv_indices, conv_values, c=cmap(i+1), label=arr_name)\n            ax.plot(conv_indices[-1], conv_values[-1], marker='.', c=cmap(i+1))\n            ax.text(np.argmin(test_losses) + 1, np.min(test_losses),\n                    f\"←{np.min(test_losses):.2f}\", ha=\"left\", va=\"top\", c=cmap(i+1), rotation=-45, fontsize=8,\n                    bbox=dict(ec=(1, 1, 1, 1), facecolor=\"w\", alpha=1, pad=0))\n            i += 2\n\n        for arr_name in [\"test_kld\"]:\n            cmap = plt.get_cmap(\"Paired\")\n            test_losses = np.array(self.result_df[arr_name])\n            epochs = np.arange(len(test_losses))\n            conv_indices, conv_values = np.array(\n                epochs[:-length+1])+length//2, np.convolve(test_losses, v, mode='valid')\n            ay.plot(test_losses, c=cmap(i))\n\n            ay.plot(conv_indices, conv_values, c=cmap(i+1), label=arr_name)\n            ay.plot(conv_indices[-1], conv_values[-1], marker='.', c=cmap(i+1))\n\n            i += 2\n\n        min_test_loss = min(self.result_df.test_loss)\n        min_test_recon = min(self.result_df.test_recon)\n        dloss = abs(min_test_loss-min_test_recon)\n        ax.set_ylim(min_test_recon-dloss*0.6, min_test_loss+dloss*0.6)\n        ay.set_ylim(-dloss*0.1, dloss*2.1)\n\n        ax.plot((nwarmup, nwarmup), (0, 100), \"--\",\n                c=\"gray\", label=\"profile hmm warmup\")\n        ay.plot((nwarmup, nwarmup), (0, 100), \"--\",\n                c=\"gray\", label=\"profile hmm warmup\")\n        ay.set_xlabel(\"epochs\")\n        ax.set_ylabel(\"loss\")\n        ay.set_ylabel(\"loss\")\n\n        ax.legend()\n        ay.legend()\n        ax.set_title(\"training result\")\n        if save:\n            fig.savefig(self.path_to_save_results/'training.png')\n\n\nclass Experiments():\n    \"\"\"whole selex experiment\"\"\"\n\n    def __init__(self, read_paths: list, has_same_adapters=True, k=3):\n        adapters = None\n        self.rounds = []\n        for read_path in sorted(read_paths):\n            logger.info(f\"reading ... {read_path}\")\n            path = Path(read_path)\n            if adapters is not None and has_same_adapters:\n                fwd, rev = adapters\n                single_round = SingleRound(path=path, name=path.stem,\n                                           forward_adapter=fwd, reverse_adapter=rev)\n            else:\n                single_round = SingleRound(path=path, name=path.stem)\n                adapters = single_round.get_adapters()\n            self.rounds += [single_round]\n        self.k = k\n        self.kmer_list = sorted(list(\"\".join(l)\n                                     for l in product(list(\"ATGC\"), repeat=k)))\n\n    def has_exact_match(self, sequences):\n        if type(sequences) is str:\n            sequences = [sequences]\n        results = dict()\n        for sequence in sequences:\n            appeared = set()\n            for experiment in self.rounds:\n                if sequence in set(experiment.get_filter_passed_sequences(random_only=True)):\n                    appeared |= {experiment.name}\n            results[sequence] = appeared\n        return results\n\n    def kmer(self, seq):\n        return [seq[i: i+self.k] for i in range(len(seq)-self.k+1)]\n\n    def kmer_count(self, seq, to_list=False):\n        from collections import Counter\n        c = Counter(self.kmer(seq))\n        if to_list:\n            return [c[kmer] for kmer in self.kmer_list]\n        return c\n\n    def save_frequencies(self, save_path, sequences, min_count=2, idx_header=\"\"):\n        from functools import partial\n\n        if type(sequences) is str:\n            sequences = [sequences]\n        pbar = tqdm(total=len(sequences))\n\n        whole_read_counts = Counter(\n            [seq for experiment in self.rounds for seq in experiment.get_filter_passed_sequences(random_only=True)])\n        whole_reads = [x[0] for x in filter(\n            lambda x:x[1] >= min_count, whole_read_counts.most_common())]\n        pbar.set_description(\"calculating kmer distribution\")\n        if not hasattr(self, \"whole_reads_kmer\"):\n            self.whole_reads_kmer = np.stack(\n                [np.array(self.kmer_count(seq, to_list=True)) for seq in whole_reads])\n\n        with open(save_path, \"w\") as f:\n            f.write(\n                \"idx\\tgenerate_seq\\texact_match_in\\tnearest_selex_seq\\tscore\\tselex_aligned\\tgenerate_aligned\\t\")\n            f.write(\n                \"\\t\".join([experiment.name for experiment in self.rounds])+\"\\n\")\n\n            # for sequence in query\n            for idx, most_probable_seq in enumerate(sequences):\n                pbar.set_description(\"taking alignments\")\n                func = partial(local_alignment, s2=most_probable_seq)\n                with Pool() as p:\n                    alignments = p.map(func, whole_reads)\n                arr = np.array(list(zip(*alignments))[0])\n\n                matches = self.has_exact_match(most_probable_seq)[\n                    most_probable_seq]\n\n                pbar.set_description(\"writing to file\")\n                for jdx in np.argwhere(arr == max(arr)).flatten():\n                    score = alignments[jdx][0]\n                    opt_seq_align, check_seq_align = alignments[jdx][1][0]\n                    f.write(\n                        f\"{idx_header}{idx}\\t{most_probable_seq}\\t{matches}\\t{whole_reads[jdx]}\\t{score}\\t{opt_seq_align}\\t{check_seq_align}\")\n\n                    for experiment in self.rounds:\n                        c = experiment.get_filter_passed_sequences_and_count(\n                            random_only=True)\n                        if whole_reads[jdx] in c.keys():\n                            ratio = f\"\\t{c[whole_reads[jdx]] / len(experiment.get_filter_passed_sequences()):.6f}\"\n                            f.write(ratio)\n                        else:\n                            f.write(\"\\t0.000000\")\n                    f.write(\"\\n\")\n                pbar.update(1)\n        return pd.read_table(save_path)\n", "meta": {"hexsha": "6a10ba764f147dfced4a7904cc9e89a4c01e6165", "size": 43052, "ext": "py", "lang": "Python", "max_stars_repo_path": "raptgen/data.py", "max_stars_repo_name": "unkosan/raptgen", "max_stars_repo_head_hexsha": "3777f1712c965aa4af2e7f1d2c508271ac3fa4bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-02-20T02:03:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T08:36:29.000Z", "max_issues_repo_path": "raptgen/data.py", "max_issues_repo_name": "unkosan/raptgen", "max_issues_repo_head_hexsha": "3777f1712c965aa4af2e7f1d2c508271ac3fa4bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-29T13:42:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-29T13:42:08.000Z", "max_forks_repo_path": "raptgen/data.py", "max_forks_repo_name": "unkosan/raptgen", "max_forks_repo_head_hexsha": "3777f1712c965aa4af2e7f1d2c508271ac3fa4bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-25T03:29:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-26T06:23:25.000Z", "avg_line_length": 37.665791776, "max_line_length": 147, "alphanum_fraction": 0.5363978445, "include": true, "reason": "import numpy", "num_tokens": 10195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.171703406449641}}
{"text": "# -*- coding: utf-8 -*-\nimport logging\nimport warnings\nimport numpy as np\nfrom scipy.interpolate import RectBivariateSpline\nimport xarray as xr\nimport dask\nimport rasterio\nimport rasterio.features\nimport rioxarray\nfrom scipy.interpolate import interp1d\nfrom shapely.geometry import Polygon, box\nimport shapely\nfrom .utils import timing, haversine, map_blocks_coords, bbox_coords, BlockingActorProxy, merge_yaml, get_glob, \\\n    to_lon180\nfrom numpy import asarray\nfrom affine import Affine\nfrom .sentinel1_meta import Sentinel1Meta\nfrom .ipython_backends import repr_mimebundle\nimport yaml\n\nlogger = logging.getLogger('xsar.sentinel1_dataset')\nlogger.addHandler(logging.NullHandler())\n\n# we know tiff as no geotransform : ignore warning\nwarnings.filterwarnings(\"ignore\", category=rasterio.errors.NotGeoreferencedWarning)\n\n# allow nan without warnings\n# some dask warnings are still non filtered: https://github.com/dask/dask/issues/3245\nnp.errstate(invalid='ignore')\n\n\nclass Sentinel1Dataset:\n    \"\"\"\n    Handle a SAFE subdataset.\n    A dataset might contain several tiff files (multiples polarizations), but all tiff files must share the same footprint.\n\n    The main attribute useful to the end-user is `self.dataset` (`xarray.Dataset` , with all variables parsed from xml and tiff files.)\n\n    Parameters\n    ----------\n    dataset_id: str or Sentinel1Meta object\n\n        if str, it can be a path, or a gdal dataset identifier like `'SENTINEL1_DS:%s:WV_001' % filename`)\n\n    resolution: dict, number or string, optional\n        resampling dict like `{'atrack': 20, 'xtrack': 20}` where 20 is in pixels.\n\n        if a number, dict will be constructed from `{'atrack': number, 'xtrack': number}`\n\n        if str, it must end with 'm' (meters), like '100m'. dict will be computed from sensor pixel size.\n\n    resampling: rasterio.enums.Resampling or str, optional\n\n        Only used if `resolution` is not None.\n\n        ` rasterio.enums.Resampling.rms` by default. `rasterio.enums.Resampling.nearest` (decimation) is fastest.\n\n    luts: bool, optional\n\n        if `True` return also luts as variables (ie `sigma0_lut`, `gamma0_lut`, etc...). False by default.\n\n    chunks: dict, optional\n\n        dict with keys ['pol','atrack','xtrack'] (dask chunks).\n\n    dtypes: None or dict, optional\n\n        Specify the data type for each variable.\n\n    patch_variable: bool, optional\n\n        activate or not variable pathching ( currently noise lut correction for IPF2.9X)\n\n    See Also\n    --------\n    xsar.open_dataset\n    \"\"\"\n\n    def __init__(self, dataset_id, resolution=None,\n                 resampling=rasterio.enums.Resampling.rms,\n                 luts=False, chunks={'atrack': 5000, 'xtrack': 5000},\n                 dtypes=None, patch_variable=True):\n\n        # miscellaneous attributes that are not know from xml files\n        attrs_dict = {\n            'pol': {\n                'comment': 'ordered polarizations (copol, crosspol)'\n            },\n            'atrack': {\n                'units': '1',\n                'comment': 'azimuth direction, in pixels from full resolution tiff'\n            },\n            'xtrack': {\n                'units': '1',\n                'comment': 'cross track direction, in pixels from full resolution tiff'\n            },\n            'sigma0_raw': {\n                'units': 'm2/m2'\n            },\n            'gamma0_raw': {\n                'units': 'm2/m2'\n            },\n            'nesz': {\n                'units': 'm2/m2',\n                'comment': 'sigma0 noise'\n            },\n            'negz': {\n                'units': 'm2/m2',\n                'comment': 'beta0 noise'\n            },\n        }\n\n        # default dtypes\n        self._dtypes = {\n            'latitude': 'f4',\n            'longitude': 'f4',\n            'incidence': 'f4',\n            'elevation': 'f4',\n            'altitude': 'f4',\n            'ground_heading': 'f4',\n            'nesz': None,\n            'negz': None,\n            'sigma0_raw': None,\n            'gamma0_raw': None,\n            'noise_lut': 'f4',\n            'noise_lut_range': 'f4',\n            'noise_lut_azi': 'f4',\n            'sigma0_lut': 'f8',\n            'gamma0_lut': 'f8',\n            'azimuth_time': np.datetime64,\n            'slant_range_time': None\n        }\n        if dtypes is not None:\n            self._dtypes.update(dtypes)\n\n        # default meta for map_blocks output.\n        # as asarray is imported from numpy, it's a numpy array.\n        # but if later we decide to import asarray from cupy, il will be a cupy.array (gpu)\n        self._default_meta = asarray([], dtype='f8')\n\n        self.s1meta = None\n        \"\"\"`xsar.Sentinel1Meta` object\"\"\"\n\n        if not isinstance(dataset_id, Sentinel1Meta):\n            self.s1meta = BlockingActorProxy(Sentinel1Meta, dataset_id)\n            # check serializable\n            # import pickle\n            # s1meta = pickle.loads(pickle.dumps(self.s1meta))\n            # assert isinstance(s1meta.coords2ll(100, 100),tuple)\n        else:\n            # we want self.s1meta to be a dask actor on a worker\n            self.s1meta = BlockingActorProxy(Sentinel1Meta.from_dict, dataset_id.dict)\n        del dataset_id\n\n        if self.s1meta.multidataset:\n            raise IndexError(\n                \"\"\"Can't open an multi-dataset. Use `xsar.Sentinel1Meta('%s').subdatasets` to show availables ones\"\"\" % self.s1meta.path\n            )\n\n        self._dataset = self._load_digital_number(resolution=resolution, resampling=resampling, chunks=chunks)\n        self._dataset = xr.merge([xr.Dataset({'time': self._burst_azitime}), self._dataset])\n\n        # dataset no-pol template for function evaluation on coordinates (*no* values used)\n        # what's matter here is the shape of the image, not the values.\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\", np.ComplexWarning)\n            if self.s1meta._bursts['burst'].size != 0:\n                # SLC TOPS, tune the high res grid because of bursts overlapping\n                atrack_time = self._burst_azitime\n                self._da_tmpl = xr.DataArray(\n                    dask.array.empty_like(\n                        np.empty((len(atrack_time), len(self._dataset.digital_number.xtrack))),\n                        dtype=np.int8, name=\"empty_var_tmpl-%s\" % dask.base.tokenize(self.s1meta.name)),\n                    dims=('atrack', 'xtrack'),\n                    coords={\n                        'atrack': self._dataset.digital_number.atrack,\n                        'xtrack': self._dataset.digital_number.xtrack,\n                        'atrack_time': atrack_time.astype(float),\n                    },\n                )\n            else:\n\n                self._da_tmpl = xr.DataArray(\n                    dask.array.empty_like(\n                        self._dataset.digital_number.isel(pol=0).drop('pol'),\n                        dtype=np.int8, name=\"empty_var_tmpl-%s\" % dask.base.tokenize(self.s1meta.name)),\n                    dims=('atrack', 'xtrack'),\n                    coords={'atrack': self._dataset.digital_number.atrack,\n                            'xtrack': self._dataset.digital_number.xtrack}\n                )\n\n        # FIXME possible memory leak\n        # when calling a self.s1meta method, an ActorFuture is returned.\n        # But this seems to break __del__ methods from both Sentinel1Meta and XmlParser\n        # Is it a memory leak ?\n        # see https://github.com/dask/distributed/issues/5610\n        # tmp_f = self.s1meta.to_dict(\"all\")\n        # del tmp_f\n        # return\n\n        self._dataset.attrs.update(self.s1meta.to_dict(\"all\"))\n\n        # dict mapping for variables names to create by applying specified lut on digital_number\n        self._map_var_lut = {\n            'sigma0_raw': 'sigma0_lut',\n            'gamma0_raw': 'gamma0_lut',\n        }\n\n        # dict mapping for lut names to file type (from self.files columns)\n        self._map_lut_files = {\n            'sigma0_lut': 'calibration',\n            'gamma0_lut': 'calibration',\n            'noise_lut_range': 'noise',\n            'noise_lut_azi': 'noise',\n        }\n\n        # dict mapping specifying if the variable has 'pol' dimension\n        self._vars_with_pol = {\n            'sigma0_lut': True,\n            'gamma0_lut': True,\n            'noise_lut_range': True,\n            'noise_lut_azi': True,\n            'incidence': False,\n            'elevation': False,\n            'altitude': False,\n            'azimuth_time': False,\n            'slant_range_time': False,\n            'longitude': False,\n            'latitude': False\n        }\n\n        # variables not returned to the user (unless luts=True)\n        self._hidden_vars = ['sigma0_lut', 'gamma0_lut', 'noise_lut', 'noise_lut_range', 'noise_lut_azi']\n        # attribute to activate correction on variables, if available\n        self._patch_variable = patch_variable\n\n        self._luts = self._lazy_load_luts(self._map_lut_files.keys())\n\n        # noise_lut is noise_lut_range * noise_lut_azi\n        if 'noise_lut_range' in self._luts.keys() and 'noise_lut_azi' in self._luts.keys():\n            self._luts = self._luts.assign(noise_lut=self._luts.noise_lut_range * self._luts.noise_lut_azi)\n            self._luts.noise_lut.attrs['history'] = merge_yaml(\n                [self._luts.noise_lut_range.attrs['history'] + self._luts.noise_lut_azi.attrs['history']],\n                section='noise_lut'\n            )\n\n        self._rasterized_masks = self._load_rasterized_masks()\n\n        ds_merge_list = [self._dataset, self._rasterized_masks, self._load_ground_heading(),  # lon_lat\n                         self._luts.drop_vars(self._hidden_vars, errors='ignore')]\n\n        if luts:\n            ds_merge_list.append(self._luts[self._hidden_vars])\n        attrs = self._dataset.attrs\n        self._dataset = xr.merge(ds_merge_list)\n        self._dataset.attrs = attrs\n\n        for var_name, lut_name in self._map_var_lut.items():\n            if lut_name in self._luts:\n                # merge var_name into dataset (not denoised)\n                self._dataset = self._dataset.merge(self._apply_calibration_lut(var_name))\n                # merge noise equivalent for var_name (named 'ne%sz' % var_name[0)\n                self._dataset = self._dataset.merge(self._get_noise(var_name))\n            else:\n                logger.debug(\"Skipping variable '%s' ('%s' lut is missing)\" % (var_name, lut_name))\n\n        self._dataset = self._dataset.merge(self._load_from_geoloc(['altitude', 'azimuth_time', 'slant_range_time',\n                                                                    'incidence', 'elevation', 'longitude', 'latitude']))\n\n        rasters = self._load_rasters_vars()\n        if rasters is not None:\n            self._dataset = xr.merge([self._dataset, rasters])\n\n        self._dataset = self._dataset.merge(self._get_sensor_velocity())\n        self._dataset = self._dataset.merge(self._range_ground_spacing())\n        self._dataset = self._add_denoised(self._dataset)\n        self._dataset.attrs = self._recompute_attrs()\n\n        # set miscellaneous attrs\n        for var, attrs in attrs_dict.items():\n            try:\n                self._dataset[var].attrs.update(attrs)\n            except KeyError:\n                pass\n\n        self.sliced = False\n        \"\"\"True if dataset is a slice of original L1 dataset\"\"\"\n\n        self.resampled = resolution is not None\n        \"\"\"True if dataset is not a sensor resolution\"\"\"\n\n        # save original bbox\n        self._bbox_coords_ori = self._bbox_coords\n\n    def __del__(self):\n        logger.debug('__del__')\n\n    @property\n    def dataset(self):\n        \"\"\"\n        `xarray.Dataset` representation of this `xsar.Sentinel1Dataset` object.\n        This property can be set with a new dataset, if the dataset was computed from the original dataset.\n        \"\"\"\n        return self._dataset\n\n    @dataset.setter\n    def dataset(self, ds):\n        if self.s1meta.name == ds.attrs['name']:\n            # check if new ds has changed coordinates\n            if not self.sliced:\n                self.sliced = any(\n                    [list(ds[d].values) != list(self._dataset[d].values) for d in ['atrack', 'xtrack', 'pol']])\n            self._dataset = ds\n            self._dataset.attrs = self._recompute_attrs()\n        else:\n            raise ValueError(\"dataset must be same kind as original one.\")\n\n    @dataset.deleter\n    def dataset(self):\n        logger.debug('deleter dataset')\n\n    @property\n    def _bbox_coords(self):\n        \"\"\"\n        Dataset bounding box, in atrack/xtrack coordinates\n        \"\"\"\n        bbox_ext = bbox_coords(self.dataset.atrack.values, self.dataset.xtrack.values)\n        return bbox_ext\n\n    @property\n    def _bbox_ll(self):\n        \"\"\"Dataset bounding box, lon/lat\"\"\"\n        return self.s1meta.coords2ll(*zip(*self._bbox_coords))\n\n    @property\n    def geometry(self):\n        \"\"\"\n        geometry of this dataset, as a `shapely.geometry.Polygon` (lon/lat coordinates)\n        \"\"\"\n        return Polygon(zip(*self._bbox_ll))\n\n    @property\n    def footprint(self):\n        \"\"\"alias for `xsar.Sentinel1Dataset.geometry`\"\"\"\n        return self.geometry\n\n    def ll2coords(self, *args):\n        \"\"\"\n        Get `(atracks, xtracks)` from `(lon, lat)`,\n        or convert a lon/lat shapely shapely object to atrack/xtrack coordinates.\n\n        Parameters\n        ----------\n        *args: lon, lat or shapely object\n\n            lon and lat might be iterables or scalars\n\n        Returns\n        -------\n        tuple of np.array or tuple of float (atracks, xtracks) , or a shapely object\n\n        Notes\n        -----\n        The difference with `xsar.Sentinel1Meta.ll2coords` is that coordinates are rounded to the nearest dataset coordinates.\n\n        See Also\n        --------\n        xsar.Sentinel1Meta.ll2coords\n\n        \"\"\"\n        if isinstance(args[0], shapely.geometry.base.BaseGeometry):\n            return self.s1meta.ll2coords_shapely(args[0].intersection(self.geometry))\n\n        atrack, xtrack = self.s1meta.ll2coords(*args)\n\n        if hasattr(args[0], '__iter__'):\n            scalar = False\n        else:\n            scalar = True\n\n        tolerance = np.max([np.percentile(np.diff(self.dataset[c].values), 90) / 2 for c in ['atrack', 'xtrack']]) + 1\n        try:\n            # select the nearest valid pixel in ds\n            ds_nearest = self.dataset.sel(atrack=atrack, xtrack=xtrack, method='nearest', tolerance=tolerance)\n            if scalar:\n                (atrack, xtrack) = (ds_nearest.atrack.values.item(), ds_nearest.xtrack.values.item())\n            else:\n                (atrack, xtrack) = (ds_nearest.atrack.values, ds_nearest.xtrack.values)\n        except KeyError:\n            # out of bounds, because of `tolerance` keyword\n            (atrack, xtrack) = (atrack * np.nan, xtrack * np.nan)\n\n        return atrack, xtrack\n\n    def coords2ll(self, *args, **kwargs):\n        \"\"\"\n         Alias for `xsar.Sentinel1Meta.coords2ll`\n\n         See Also\n         --------\n         xsar.Sentinel1Meta.coords2ll\n        \"\"\"\n        return self.s1meta.coords2ll(*args, **kwargs)\n\n    @property\n    def len_atrack_m(self):\n        \"\"\"atrack length, in meters\"\"\"\n        bbox_ll = list(zip(*self._bbox_ll))\n        len_m, _ = haversine(*bbox_ll[1], *bbox_ll[2])\n        return len_m\n\n    @property\n    def len_xtrack_m(self):\n        \"\"\"xtrack length, in meters \"\"\"\n        bbox_ll = list(zip(*self._bbox_ll))\n        len_m, _ = haversine(*bbox_ll[0], *bbox_ll[1])\n        return len_m\n\n    @property\n    def pixel_atrack_m(self):\n        \"\"\"atrack pixel spacing, in meters (relative to dataset)\"\"\"\n        return self.len_atrack_m / self.dataset.atrack.size\n\n    @property\n    def pixel_xtrack_m(self):\n        \"\"\"xtrack pixel spacing, in meters (relative to dataset)\"\"\"\n        return self.len_xtrack_m / self.dataset.xtrack.size\n\n    @property\n    def coverage(self):\n        \"\"\"coverage string\"\"\"\n        return \"%dkm * %dkm (atrack * xtrack )\" % (self.len_atrack_m / 1000, self.len_xtrack_m / 1000)\n\n    @property\n    def _regularly_spaced(self):\n        return max(\n            [np.unique(np.round(np.diff(self._dataset[dim].values), 1)).size for dim in ['atrack', 'xtrack']]) == 1\n\n    def _recompute_attrs(self):\n        if not self._regularly_spaced:\n            warnings.warn(\n                \"Irregularly spaced dataset (probably multiple selection). Some attributes will be incorrect.\")\n        attrs = self._dataset.attrs\n        attrs['pixel_xtrack_m'] = self.pixel_xtrack_m\n        attrs['pixel_atrack_m'] = self.pixel_atrack_m\n        attrs['coverage'] = self.coverage\n        attrs['footprint'] = self.footprint\n        return attrs\n\n    def _patch_lut(self, lut):\n        \"\"\"\n        patch proposed by MPC Sentinel-1 : https://jira-projects.cls.fr/browse/MPCS-2007 for noise vectors of WV SLC IPF2.9X products\n        adjustement proposed by BAE are the same for HH and VV, and suppose to work for both old and new WV2 EAP\n        they were estimated using WV image with very low NRCS (black images) and computing std(sigma0).\n        Parameters\n        ----------\n        lut xarray.Dataset\n\n        Returns\n        -------\n        lut xarray.Dataset\n        \"\"\"\n        if self.s1meta.swath == 'WV':\n            if lut.name in ['noise_lut_azi'] and self.s1meta.ipf in [2.9, 2.91] and \\\n                    self.s1meta.platform in ['SENTINEL-1A', 'SENTINEL-1B']:\n                noise_calibration_cst_pp1 = {\n                    'SENTINEL-1A':\n                        {'WV1': -38.13,\n                         'WV2': -36.84\n                         },\n                    'SENTINEL-1B':\n                        {'WV1': -39.30,\n                         'WV2': -37.44,\n                         }\n                }\n                cst_db = noise_calibration_cst_pp1[self.s1meta.platform][self.s1meta.image['swath_subswath']]\n                cst_lin = 10 ** (cst_db / 10)\n                lut = lut * cst_lin\n                lut.attrs['comment'] = 'patch on the noise_lut_azi : %s dB' % cst_db\n        return lut\n\n    @timing\n    def _lazy_load_luts(self, luts_names):\n        \"\"\"\n        lazy load luts from xml files\n        Parameters\n        ----------\n        luts_names: list of str\n\n\n        Returns\n        -------\n        xarray.Dataset with variables from `luts_names`.\n\n        \"\"\"\n\n        luts_list = []\n        luts = None\n        for lut_name in luts_names:\n            xml_type = self._map_lut_files[lut_name]\n            xml_files = self.s1meta.files.copy()\n            # polarization is a category. we use codes (ie index),\n            # to have well ordered polarizations in latter combine_by_coords\n            xml_files['pol_code'] = xml_files['polarization'].cat.codes\n            xml_files = xml_files.set_index('pol_code')[xml_type]\n\n            if not self._vars_with_pol[lut_name]:\n                # luts are identical in all pols: take the fist one\n                xml_files = xml_files.iloc[[0]]\n\n            for pol_code, xml_file in xml_files.iteritems():\n                pol = self.s1meta.files['polarization'].cat.categories[pol_code]\n                if self._vars_with_pol[lut_name]:\n                    name = \"%s_%s\" % (lut_name, pol)\n                else:\n                    name = lut_name\n\n                # get the lut function. As it takes some time to parse xml, make it delayed\n                lut_f_delayed = dask.delayed(self.s1meta.xml_parser.get_compound_var)(xml_file, lut_name)\n                lut = map_blocks_coords(\n                    self._da_tmpl.astype(self._dtypes[lut_name]),\n                    lut_f_delayed,\n                    name='blocks_%s' % name\n                )\n\n                # needs to add pol dim ?\n                if self._vars_with_pol[lut_name]:\n                    lut = lut.assign_coords(pol_code=pol_code).expand_dims('pol_code')\n\n                # set xml file and xpath used as history\n                histo = self.s1meta.xml_parser.get_compound_var(xml_file, lut_name,\n                                                                describe=True)\n                lut.name = lut_name\n                if self._patch_variable:\n                    lut = self._patch_lut(lut)\n                lut.attrs['history'] = histo\n                lut = lut.to_dataset()\n\n                luts_list.append(lut)\n            luts = xr.combine_by_coords(luts_list)\n\n            # convert pol_code to string\n            pols = self.s1meta.files['polarization'].cat.categories[luts.pol_code.values.tolist()]\n            luts = luts.rename({'pol_code': 'pol'}).assign_coords({'pol': pols})\n        return luts\n\n    @timing\n    def _load_digital_number(self, resolution=None, chunks=None, resampling=rasterio.enums.Resampling.rms):\n        \"\"\"\n        load digital_number from self.s1meta.files['measurement'], as an `xarray.Dataset`.\n\n        Parameters\n        ----------\n        resolution: None, number, str or dict\n            see `xsar.open_dataset`\n        resampling: rasterio.enums.Resampling\n            see `xsar.open_dataset`\n\n        Returns\n        -------\n        xarray.Dataset\n            dataset (possibly dual-pol), with basic coords/dims naming convention\n        \"\"\"\n\n        map_dims = {\n            'pol': 'band',\n            'atrack': 'y',\n            'xtrack': 'x'\n        }\n\n        if resolution is not None:\n            comment = 'resampled at \"%s\" with %s.%s.%s' % (\n                resolution, resampling.__module__, resampling.__class__.__name__, resampling.name)\n        else:\n            comment = 'read at full resolution'\n\n        # arbitrary rio object, to get shape, etc ... (will not be used to read data)\n        rio = rasterio.open(self.s1meta.files['measurement'].iloc[0])\n\n        chunks['pol'] = 1\n        # sort chunks keys like map_dims\n        chunks = dict(sorted(chunks.items(), key=lambda pair: list(map_dims.keys()).index(pair[0])))\n        chunks_rio = {map_dims[d]: chunks[d] for d in map_dims.keys()}\n\n        if resolution is None:\n            # using tiff driver: need to read individual tiff and concat them\n            # riofiles['rio'] is ordered like self.s1meta.manifest_attrs['polarizations']\n\n            dn = xr.concat(\n                [\n                    rioxarray.open_rasterio(\n                        f, chunks=chunks_rio, parse_coordinates=False\n                    ) for f in self.s1meta.files['measurement']\n                ], 'band'\n            ).assign_coords(band=np.arange(len(self.s1meta.manifest_attrs['polarizations'])) + 1)\n\n            # set dimensions names\n            dn = dn.rename(dict(zip(map_dims.values(), map_dims.keys())))\n\n            # create coordinates from dimension index (because of parse_coordinates=False)\n            dn = dn.assign_coords({'atrack': dn.atrack, 'xtrack': dn.xtrack})\n            dn = dn.drop_vars('spatial_ref', errors='ignore')\n        else:\n            if not isinstance(resolution, dict):\n                if isinstance(resolution, str) and resolution.endswith('m'):\n                    resolution = float(resolution[:-1])\n                resolution = dict(atrack=resolution / self.s1meta.pixel_atrack_m,\n                                  xtrack=resolution / self.s1meta.pixel_xtrack_m)\n\n            # resample the DN at gdal level, before feeding it to the dataset\n            out_shape = (\n                int(rio.height / resolution['atrack']),\n                int(rio.width / resolution['xtrack'])\n            )\n            out_shape_pol = (1,) + out_shape\n            # read resampled array in one chunk, and rechunk\n            # this doesn't optimize memory, but total size remain quite small\n\n            if isinstance(resolution['atrack'], int):\n                # legacy behaviour: winsize is the maximum full image size that can be divided  by resolution (int)\n                winsize = (0, 0, rio.width // resolution['xtrack'] * resolution['xtrack'],\n                           rio.height // resolution['atrack'] * resolution['atrack'])\n                window = rasterio.windows.Window(*winsize)\n            else:\n                window = None\n\n            dn = xr.concat(\n                [\n                    xr.DataArray(\n                        dask.array.from_array(\n                            rasterio.open(f).read(\n                                out_shape=out_shape_pol,\n                                resampling=resampling,\n                                window=window\n                            ),\n                            chunks=chunks_rio\n                        ),\n                        dims=tuple(map_dims.keys()), coords={'pol': [pol]}\n                    ) for f, pol in\n                    zip(self.s1meta.files['measurement'], self.s1meta.manifest_attrs['polarizations'])\n                ],\n                'pol'\n            ).chunk(chunks)\n\n            # create coordinates at box center\n            translate = Affine.translation((resolution['xtrack'] - 1) / 2, (resolution['atrack'] - 1) / 2)\n            scale = Affine.scale(\n                rio.width // resolution['xtrack'] * resolution['xtrack'] / out_shape[1],\n                rio.height // resolution['atrack'] * resolution['atrack'] / out_shape[0])\n            xtrack, _ = translate * scale * (dn.xtrack, 0)\n            _, atrack = translate * scale * (0, dn.atrack)\n            dn = dn.assign_coords({'atrack': atrack, 'xtrack': xtrack})\n\n        # for GTiff driver, pols are already ordered. just rename them\n        dn = dn.assign_coords(pol=self.s1meta.manifest_attrs['polarizations'])\n\n        if not all(self.s1meta.denoised.values()):\n            descr = 'denoised'\n        else:\n            descr = 'not denoised'\n        var_name = 'digital_number'\n\n        dn.attrs = {\n            'comment': '%s digital number, %s' % (descr, comment),\n            'history': yaml.safe_dump(\n                {\n                    var_name: get_glob(\n                        [p.replace(self.s1meta.path + '/', '') for p in self.s1meta.files['measurement']])\n                }\n            )\n        }\n        ds = dn.to_dataset(name=var_name)\n        astype = self._dtypes.get(var_name)\n        if astype is not None:\n            ds = ds.astype(self._dtypes[var_name])\n\n        return ds\n\n    @timing\n    def _load_from_geoloc(self, varnames):\n        \"\"\"\n        Interpolate (with RectBiVariateSpline) variables from `self.s1meta.geoloc` to `self._dataset`\n\n        Parameters\n        ----------\n        varnames: list of str\n            subset of variables names in `self.s1meta.geoloc`\n\n        Returns\n        -------\n        xarray.Dataset\n            With interpolated vaiables\n\n        \"\"\"\n\n        da_list = []\n\n        def interp_func_slc(vect1dazti, vect1dxtrac, **kwargs):\n            \"\"\"\n\n            Parameters\n            ----------\n            vect1dazti (np.ndarray) : azimuth times at high resolution\n            vect1dxtrac (np.ndarray): range coords\n\n            Returns\n            -------\n\n            \"\"\"\n            # exterieur de boucle\n            rbs = kwargs['rbs']\n\n            def wrapperfunc(*args, **kwargs):\n                rbs2 = args[2]\n                return rbs2(args[0], args[1], grid=False)\n\n            return wrapperfunc(vect1dazti[:, np.newaxis], vect1dxtrac[np.newaxis, :], rbs)\n\n        for varname in varnames:\n            logger.debug('varname : %s', varname)\n            if varname in ['azimuth_time']:\n                z_values = self.s1meta.geoloc[varname].astype(float)\n            elif varname == 'longitude':\n                z_values = self.s1meta.geoloc[varname]\n                if self.s1meta.cross_antemeridian:\n                    logger.debug('translate longitudes between 0 and 360')\n                    z_values = z_values % 360\n            else:\n                z_values = self.s1meta.geoloc[varname]\n            if self.s1meta._bursts['burst'].size != 0:\n                # TOPS SLC\n                rbs = RectBivariateSpline(\n                    self.s1meta.geoloc.azimuth_time[:, 0].astype(float),\n                    self.s1meta.geoloc.xtrack,\n                    z_values,\n                    kx=1, ky=1,\n                )\n                interp_func = interp_func_slc\n            else:\n                rbs = None\n                interp_func = RectBivariateSpline(\n                    self.s1meta.geoloc.atrack,\n                    self.s1meta.geoloc.xtrack,\n                    z_values,\n                    kx=1, ky=1\n                )\n            # the following take much cpu and memory, so we want to use dask\n            # interp_func(self._dataset.atrack, self.dataset.xtrack)\n            typee = self.s1meta.geoloc[varname].dtype\n            if self.s1meta._bursts['burst'].size != 0:\n                datemplate = self._da_tmpl.astype(typee).copy()\n                # replace the atrack coordinates by atrack_time coordinates\n                datemplate = datemplate.assign_coords({'atrack': datemplate.coords['atrack_time']})\n                da_var = map_blocks_coords(\n                    datemplate,\n                    interp_func,\n                    func_kwargs={\"rbs\": rbs}\n                )\n                # put back the real atrack coordinates\n                da_var = da_var.assign_coords({'atrack': self._dataset.digital_number.atrack})\n            else:\n                da_var = map_blocks_coords(\n                    self._da_tmpl.astype(typee),\n                    interp_func\n                )\n            if varname == 'longitude':\n                if self.s1meta.cross_antemeridian:\n                    da_var.data = da_var.data.map_blocks(to_lon180)\n\n            da_var.name = varname\n\n            # copy history\n            try:\n                da_var.attrs['history'] = self.s1meta.geoloc[varname].attrs['history']\n            except KeyError:\n                pass\n\n            da_list.append(da_var)\n\n        return xr.merge(da_list)\n\n\n    @timing\n    def _load_ground_heading(self):\n        def coords2heading(atracks, xtracks):\n            return self.s1meta.coords2heading(atracks, xtracks, to_grid=True, approx=True)\n\n        gh = map_blocks_coords(\n            self._da_tmpl.astype(self._dtypes['ground_heading']),\n            coords2heading,\n            name='ground_heading'\n        )\n\n        gh.attrs = {\n            'comment': 'at ground level, computed from lon/lat in atrack direction'\n        }\n\n        return gh.to_dataset(name='ground_heading')\n\n    @timing\n    def _load_rasterized_masks(self):\n        def _test(atrack, xtrack, mask=None):\n            chunk_coords = bbox_coords(atrack, xtrack, pad=None)\n            # chunk footprint polygon, in dataset coordinates (with buffer, to enlarge a little the footprint)\n            chunk_footprint_coords = Polygon(chunk_coords).buffer(10)\n            tmp = self.s1meta.name\n            # vector_mask_ll = s1meta.get_mask(mask) #\n            return np.meshgrid(xtrack, atrack)[0] * 0\n\n        def _rasterize_mask_by_chunks(atrack, xtrack, mask='land'):\n            chunk_coords = bbox_coords(atrack, xtrack, pad=None)\n            # chunk footprint polygon, in dataset coordinates (with buffer, to enlarge a little the footprint)\n            chunk_footprint_coords = Polygon(chunk_coords).buffer(10)\n            # chunk footprint polygon, in lon/lat\n            chunk_footprint_ll = self.s1meta.coords2ll(chunk_footprint_coords)\n\n            # get vector mask over chunk, in lon/lat\n            vector_mask_ll = self.s1meta.get_mask(mask).intersection(chunk_footprint_ll)\n\n            if vector_mask_ll.is_empty:\n                # no intersection with mask, return zeros\n                return np.zeros((atrack.size, xtrack.size))\n\n            # vector mask, in atrack/xtrack coordinates\n            vector_mask_coords = self.s1meta.ll2coords(vector_mask_ll)\n\n            # shape of the returned chunk\n            out_shape = (atrack.size, xtrack.size)\n\n            # transform * (x, y) -> (atrack, xtrack)\n            # (where (x, y) are index in out_shape)\n            # Affine.permutation() is used because (atrack, xtrack) is transposed from geographic\n\n            transform = Affine.translation(*chunk_coords[0]) * Affine.scale(\n                *[np.unique(np.diff(c))[0] for c in [atrack, xtrack]]) * Affine.permutation()\n\n            raster_mask = rasterio.features.rasterize(\n                [vector_mask_coords],\n                out_shape=out_shape,\n                all_touched=False,\n                transform=transform\n            )\n            return raster_mask\n\n        da_list = []\n        for mask in self.s1meta.mask_names:\n            da_mask = map_blocks_coords(\n                self._da_tmpl,\n                _rasterize_mask_by_chunks,\n                func_kwargs={'mask': mask}\n            )\n            name = '%s_mask' % mask\n            da_mask.attrs['history'] = yaml.safe_dump({name: self.s1meta.get_mask(mask, describe=True)})\n            da_list.append(da_mask.to_dataset(name=name))\n\n        return xr.merge(da_list)\n\n    @timing\n    def _load_rasters_vars(self):\n        # load and map variables from rasterfile (like ecmwf) on dataset\n        if self.s1meta.rasters.empty:\n            return None\n        else:\n            logger.warning('Raster variable are experimental')\n\n        if self.s1meta.cross_antemeridian:\n            raise NotImplementedError('Antimeridian crossing not yet checked')\n\n        # get lon/lat box for xsar dataset\n        lons, lats = list(zip(*self.s1meta.footprint.exterior.coords))\n        lon_range = [min(lons), max(lons)]\n        lat_range = [min(lats), max(lats)]\n\n        # will contain xr.DataArray to merge\n        da_var_list = []\n\n        for name, infos in self.s1meta.rasters.iterrows():\n            # read the raster file using helpers functions\n            read_function = infos['read_function']\n            get_function = infos['get_function']\n            resource = infos['resource']\n\n            kwargs = {\n                's1meta': self,\n                'date': self.s1meta.start_date,\n                'footprint': self.s1meta.footprint\n            }\n\n            logger.debug('adding raster \"%s\" from resource \"%s\"' % (name, str(resource)))\n            if get_function is not None:\n                try:\n                    resource_dec = get_function(resource, **kwargs)\n                except TypeError:\n                    resource_dec = get_function(resource)\n\n            if read_function is None:\n                raster_ds = xr.open_dataset(resource_dec, chunk=1000)\n            else:\n                # read_function should return a chunked dataset (so it's fast)\n                raster_ds = read_function(resource_dec)\n\n            # add globals raster attrs to globals dataset attrs\n            hist_res = {'resource': resource}\n            if get_function is not None:\n                hist_res.update({'resource_decoded': resource_dec})\n\n            if not raster_ds.rio.crs.is_geographic:\n                raise NotImplementedError(\"Non geographic crs not implemented\")\n\n            # ensure dim ordering\n            raster_ds = raster_ds.transpose('y', 'x')\n            if np.all(raster_ds.y.diff('y') <= 0):\n                # sort y (lat) ascending (for RectBiVariateSpline)\n                raster_ds = raster_ds.reindex(y=raster_ds.y[::-1])\n\n            # from lon/lat box in xsar dataset, get the corresponding box in raster_ds (by index)\n            ilon_range = [\n                np.searchsorted(raster_ds.x.values, lon_range[0], side='right'),\n                np.searchsorted(raster_ds.x.values, lon_range[1], side='left')\n            ]\n            ilat_range = [\n                np.searchsorted(raster_ds.y.values, lat_range[0], side='right'),\n                np.searchsorted(raster_ds.y.values, lat_range[1], side='left')\n            ]\n            # select the xsar box in the raster\n            raster_ds = raster_ds.isel(x=slice(*ilon_range), y=slice(*ilat_range))\n\n            # 1D array of lons/lats, trying to have same spacing as dataset (if not to high)\n            num = min((self._dataset.xtrack.size + self._dataset.atrack.size) // 2, 1000)\n            lons = np.linspace(*lon_range, num=num)\n            lats = np.linspace(*lat_range, num=num)\n\n            @dask.delayed\n            def _map_raster2xsar(da):\n                # map the 'da' dataarray variable from the raster to xsar dataset\n                da = da.drop_vars(['spatial_ref', 'crs'], errors='ignore')\n\n                upscaled_da = map_blocks_coords(\n                    xr.DataArray(dims=['y', 'x'], coords={'x': lons, 'y': lats}).chunk(1000),\n                    RectBivariateSpline(da.y.values, da.x.values, da.values)\n                )\n\n                reprojected_da = upscaled_da.interp(\n                    x=self._dataset.longitude,\n                    y=self._dataset.latitude\n                )\n                reprojected_da = reprojected_da.drop_vars(['x', 'y', 'spatial_ref', 'crs'], errors='ignore')\n                reprojected_da.attrs.update(da.attrs)\n\n                reprojected_da.name = '%s_%s' % (name, da.name)\n\n                # reprojected_da has same shape as other variables is xsar dataset, with optional 3rd dim\n                return reprojected_da\n\n            for var in raster_ds:\n                var_name = '%s_%s' % (name, raster_ds[var].name)\n                da_var = xr.DataArray(\n                    dask.array.from_delayed(\n                        _map_raster2xsar(raster_ds[var]),\n                        self._da_tmpl.shape,\n                        dtype='f8',\n                        name='%s' % var_name\n                    ),\n                    dims=['atrack', 'xtrack'],\n                    coords={'atrack': self._da_tmpl.atrack, 'xtrack': self._da_tmpl.xtrack},\n                    attrs=raster_ds[var].attrs\n                ).chunk(self._da_tmpl.chunks)\n                da_var.attrs['history'] = yaml.safe_dump({var_name: hist_res})\n                logger.debug('adding variable \"%s\" from raster \"%s\"' % (var_name, name))\n                da_var_list.append(da_var)\n\n        return xr.merge(da_var_list)\n\n    def _get_lut(self, var_name):\n        \"\"\"\n        Get lut for `var_name`\n\n        Parameters\n        ----------\n        var_name: str\n\n        Returns\n        -------\n        xarray.Dataarray\n            lut for `var_name`\n        \"\"\"\n        try:\n            lut_name = self._map_var_lut[var_name]\n        except KeyError:\n            raise ValueError(\"can't find lut name for var '%s'\" % var_name)\n        try:\n            lut = self._luts[lut_name]\n        except KeyError:\n            raise ValueError(\"can't find lut from name '%s' for variable '%s' \" % (lut_name, var_name))\n        return lut\n\n    def _apply_calibration_lut(self, var_name):\n        \"\"\"\n        Apply calibration lut to `digital_number` to compute `var_name`.\n        see https://sentinel.esa.int/web/sentinel/radiometric-calibration-of-level-1-products\n\n        Parameters\n        ----------\n        var_name: str\n            Variable name to compute by applying lut. Must exist in `self._map_var_lut`` to be able to get the corresponding lut.\n\n        Returns\n        -------\n        xarray.Dataset\n            with one variable named by `var_name`\n        \"\"\"\n        lut = self._get_lut(var_name)\n        res = (np.abs(self._dataset.digital_number) ** 2. / (lut ** 2))\n        # dn default value is 0: convert to Nan\n        res = res.where(res > 0)\n        astype = self._dtypes.get(var_name)\n        if astype is not None:\n            res = res.astype(astype)\n\n        res.attrs.update(lut.attrs)\n        res.attrs['history'] = merge_yaml([lut.attrs['history']], section=var_name)\n        res.attrs['references'] = 'https://sentinel.esa.int/web/sentinel/radiometric-calibration-of-level-1-products'\n\n        return res.to_dataset(name=var_name)\n\n    def reverse_calibration_lut(self, ds_var):\n        \"\"\"\n        TODO: replace ds_var by var_name\n        Inverse of `_apply_calibration_lut` : from `var_name`, reverse apply lut, to get digital_number.\n        See `official ESA documentation <https://sentinel.esa.int/web/sentinel/radiometric-calibration-of-level-1-products>`_ .\n        > Level-1 products provide four calibration Look Up Tables (LUTs) to produce ß0i, σ0i and γi\n        > or to return to the Digital Number (DN)\n\n        A warning message may be issued if original complex 'digital_number' is converted to module during this operation.\n\n        Parameters\n        ----------\n        ds_var: xarray.Dataset\n            with only one variable name that must exist in `self._map_var_lut` to be able to reverse the lut to get digital_number\n\n        Returns\n        -------\n        xarray.Dataset\n            with one variable named 'digital_number'.\n        \"\"\"\n        var_names = list(ds_var.keys())\n        assert len(var_names) == 1\n        var_name = var_names[0]\n        if var_name not in self._map_var_lut:\n            raise ValueError(\n                \"Unable to find lut for var '%s'. Allowed : %s\" % (var_name, str(self._map_var_lut.keys())))\n        da_var = ds_var[var_name]\n        lut = self._luts[self._map_var_lut[var_name]]\n\n        # resize lut with same a/xtrack as da_var\n        lut = lut.sel(atrack=da_var.atrack, xtrack=da_var.xtrack, method='nearest')\n        # as we used 'nearest', force exact coords\n        lut['atrack'] = da_var.atrack\n        lut['xtrack'] = da_var.xtrack\n        # waiting for https://github.com/pydata/xarray/pull/4155\n        # lut = lut.interp(atrack=da_var.atrack, xtrack=da_var.xtrack)\n\n        # revert lut to get dn\n        dn = np.sqrt(da_var * lut ** 2)\n\n        if self._dataset.digital_number.dtype == np.complex and dn.dtype != np.complex:\n            warnings.warn(\n                \"Unable to retrieve 'digital_number' as dtype '%s'. Fallback to '%s'\"\n                % (str(self._dataset.digital_number.dtype), str(dn.dtype))\n            )\n\n        name = 'digital_number'\n        ds = dn.to_dataset(name=name)\n\n        return ds\n\n    def _get_noise(self, var_name):\n        \"\"\"\n        Get noise equivalent for  `var_name`.\n        see https://sentinel.esa.int/web/sentinel/radiometric-calibration-of-level-1-products\n\n        Parameters\n        ----------\n        var_name: str\n            Variable name to compute. Must exist in `self._map_var_lut` to be able to get the corresponding lut.\n\n        Returns\n        -------\n        xarray.Dataset\n            with one variable named by `'ne%sz' % var_name[0]` (ie 'nesz' for 'sigma0', 'nebz' for 'beta0', etc...)\n        \"\"\"\n        noise_lut = self._luts['noise_lut']\n        lut = self._get_lut(var_name)\n        dataarr = noise_lut / lut ** 2\n        name = 'ne%sz' % var_name[0]\n        astype = self._dtypes.get(name)\n        if astype is not None:\n            dataarr = dataarr.astype(astype)\n        dataarr.attrs['history'] = merge_yaml([lut.attrs['history'], noise_lut.attrs['history']], section=name)\n        return dataarr.to_dataset(name=name)\n\n    def _add_denoised(self, ds, clip=False, vars=None):\n        \"\"\"add denoised vars to dataset\n\n        Parameters\n        ----------\n        ds : xarray.DataSet\n            dataset with non denoised vars, named `%s_raw`.\n        clip : bool, optional\n            If True, negative signal will be clipped to 0. (default to False )\n        vars : list, optional\n            variables names to add, by default `['sigma0' , 'beta0' , 'gamma0']`\n\n        Returns\n        -------\n        xarray.DataSet\n            dataset with denoised vars\n        \"\"\"\n        if vars is None:\n            vars = ['sigma0', 'beta0', 'gamma0']\n        for varname in vars:\n            varname_raw = varname + '_raw'\n            noise = 'ne%sz' % varname[0]\n            if varname_raw not in ds:\n                continue\n            if all(self.s1meta.denoised.values()):\n                # already denoised, just add an alias\n                ds[varname] = ds[varname_raw]\n            elif len(set(self.s1meta.denoised.values())) != 1:\n                # TODO: to be implemented\n                raise NotImplementedError(\"semi denoised products not yet implemented\")\n            else:\n                denoised = ds[varname_raw] - ds[noise]\n                denoised.attrs['history'] = merge_yaml(\n                    [ds[varname_raw].attrs['history'], ds[noise].attrs['history']],\n                    section=varname\n                )\n                if clip:\n                    denoised = denoised.clip(min=0)\n                    denoised.attrs['comment'] = 'clipped, no values <0'\n                else:\n                    denoised.attrs['comment'] = 'not clipped, some values can be <0'\n                ds[varname] = denoised\n        return ds\n\n    @property\n    def _burst_azitime(self):\n        \"\"\"\n        Get azimuth time at high resolution.\n\n        Returns\n        -------\n        xarray.DataArray\n            the high resolution azimuth time vector interpolated at the middle of the sub-swath\n        \"\"\"\n        azitime = self.s1meta._burst_azitime()\n        iz = np.searchsorted(azitime.atrack, self._dataset.atrack)\n        azitime = azitime.isel({'atrack': iz})\n        azitime = azitime.assign_coords({\"atrack\": self._dataset.atrack})\n        return azitime\n\n    def _get_sensor_velocity(self):\n        \"\"\"\n        Interpolated sensor velocity\n        Returns\n        -------\n        xarray.Dataset()\n            containing a single variable velocity\n        \"\"\"\n\n        azimuth_times = self._burst_azitime\n        orbstatevect = self.s1meta.orbit\n        azi_times = orbstatevect.index.values\n        velos = np.array([[uu.x ** 2., uu.y ** 2., uu.z ** 2.] for uu in orbstatevect['velocity'].values])\n        vels = np.sqrt(np.sum(velos, axis=1))\n        interp_f = interp1d(azi_times.astype(float), vels)\n        _vels = interp_f(azimuth_times.astype(float))\n        res = xr.DataArray(_vels, dims=['atrack'], coords={'atrack': self.dataset.atrack})\n        return xr.Dataset({'velocity': res})\n\n    def _range_ground_spacing(self):\n        \"\"\"\n        Get SAR image range ground spacing.\n\n        Parameters\n        ----------\n        Returns\n        -------\n        range_ground_spacing_vect : xarray.DataArray\n            range ground spacing (xtrack coordinates)\n\n        Notes\n        -----\n        For GRD products is it the same same value along xtrack axis\n        \"\"\"\n        ground_spacing = np.array(self.s1meta.image['slant_pixel_spacing'])\n        if self.s1meta.product == 'SLC':\n            atrack_tmp = self._dataset['atrack']\n            xtrack_tmp = self._dataset['xtrack']\n            # get the incidence at the middle of atrack dimension of the part of image selected\n            inc = self._dataset['incidence'].isel({'atrack': int(len(atrack_tmp) / 2),\n                                                   })\n            range_ground_spacing_vect = ground_spacing[1] / np.sin(np.radians(inc))\n            range_ground_spacing_vect.attrs['history'] = ''\n\n        else:  # GRD\n            valuess = np.ones((len(self._dataset['xtrack']))) * ground_spacing[1]\n            range_ground_spacing_vect = xr.DataArray(valuess, coords={'xtrack': self._dataset['xtrack']},\n                                                     dims=['xtrack'])\n        return xr.Dataset({'range_ground_spacing': range_ground_spacing_vect})\n\n    def __repr__(self):\n        if self.sliced:\n            intro = \"sliced\"\n        else:\n            intro = \"full covevage\"\n        return \"<Sentinel1Dataset %s object>\" % intro\n\n    def _repr_mimebundle_(self, include=None, exclude=None):\n        return repr_mimebundle(self, include=include, exclude=exclude)\n", "meta": {"hexsha": "0fc7e505799c63a578e88d7ea15da178963b6def", "size": 47493, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/xsar/sentinel1_dataset.py", "max_stars_repo_name": "agrouaze/xsar", "max_stars_repo_head_hexsha": "b59b03ecb445124db390e81afc2a95ecdd615578", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/xsar/sentinel1_dataset.py", "max_issues_repo_name": "agrouaze/xsar", "max_issues_repo_head_hexsha": "b59b03ecb445124db390e81afc2a95ecdd615578", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/xsar/sentinel1_dataset.py", "max_forks_repo_name": "agrouaze/xsar", "max_forks_repo_head_hexsha": "b59b03ecb445124db390e81afc2a95ecdd615578", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8649754501, "max_line_length": 136, "alphanum_fraction": 0.565199082, "include": true, "reason": "import numpy,from numpy,from scipy,from cupy", "num_tokens": 10948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.33807713748839185, "lm_q1q2_score": 0.17167958145815718}}
{"text": "#/usr/bin/python\n\n'''\n\nThis function collects NEXMD populations from surface hopping\nand populations from Schrodinger equation.\n\nTwo files are generated in the current working directory if\ncollecting NEXMD populations are requested, 'pop.out' and\n'pop.err'.  In 'pop.out', first column is time in fs, followed by\nthe average population on each PES, followed by the sum of all\nPES populations (should be = 1.0), followed by the average\npopulations from quantum coefficients, followed by the sum of\nquantum populations (should be = 1.0).  In 'pop.err', first\ncolumn is directory of trajectory, third column is the time at\nwhich the trajectory has ended in fs, or 'does not exist'.  The\n'pop.err' file is not generated if all trajectories are complete.              \n\n'Completed' trajectories are trajectories that have completed\nwithin the time defined by user while executing this function.\n'Excellent' trajectories are trajectories that have completed\nwithin the time defined in 'header' located in the NEXMD\ndirectory.                                                        \n\nOutput Files:\n- pop_[type].out, where [type] = mean_ensemble\n\nError Files:\n- pop_[type].err, where [type] = mean_ensemble\n\n'''\n\nimport numpy as np\nimport os\nimport sys\nimport glob\n\ncwd = os.getcwd()\n\ndef population(header):\n\n    print 'Collecting populations.'\n\n    ## Directory names ##\n    NEXMDir = raw_input('NEXMD directory: ')\n    if not os.path.exists(NEXMDir):\n        print 'Path %s does not exist.' % (NEXMDir)\n        sys.exit()\n    ## Check if NEXMD folders exist ##\n    NEXMDs = glob.glob('%s/NEXMD*/' % (NEXMDir))\n    NEXMDs.sort()\n    if len(NEXMDs) == 0:\n        print 'There are no NEXMD folders in %s.' % (NEXMDir)\n        sys.exit()\n\n    ## Information from header ##\n    if not os.path.exists('%s/header' % (NEXMDir)):\n        print 'Path %s/header does not exist.' % (NEXMDir)\n        sys.exit()\n    header = header('%s/header' % (NEXMDir))\n        \n    ## Adding + 1 to include zeroth time-step ##\n    header.n_class_steps = header.n_class_steps + 1\n\n    ## Collection time ##\n    tcoll = input('Calculate populations up to what time in femtoseconds?\\nNote that averaged results will only include trajectories that are complete up to this time: ')\n    if isinstance(tcoll, int) == False and isinstance(tcoll, float) == False:\n        print 'Time must be integer or float.'\n        sys.exit()\n    if tcoll < 0:\n        print 'Time must be integer or float greater than zero.'\n        sys.exit()\n    tcoll = np.float(tcoll)\n    if tcoll > (header.n_class_steps - 1)*header.time_step:\n        tcoll = (header.n_class_steps -1)*header.time_step\n\n    ## Number of classical time-steps ##\n    tscol = 0\n    while tscol*header.time_step*header.out_data_steps <= tcoll:\n        tscol += 1\n    \n    ## Collection time array ##\n    times = np.around(np.linspace(header.time_init, tcoll, tscol), decimals = 3)\n    fpoph = np.zeros((tscol,header.n_exc_states_propagate))\n    fpopc = np.zeros((tscol,header.n_exc_states_propagate))\n    \n    ## Collect populations ##\n    output = open('%s/pop_mean_ensemble.out' % (cwd),'w')\n    error = open('%s/pop_mean_ensemble.err' % (cwd),'w')\n    ttraj = 0\n    ctraj = 0\n    etraj = 0\n    errflag = 0\n    for NEXMD in NEXMDs:\n        if not os.path.exists('%s/dirlist1' % (NEXMD)):\n            print 'Path %sdirlist1 does not exist.' % (NEXMD)\n            sys.exit()\n        dirlist1 = np.int_(np.genfromtxt('%s/dirlist1' % (NEXMD)))\n        if isinstance(dirlist1,int) == True:\n            dirlist1 = np.array([dirlist1])\n        for dir in dirlist1:\n            if not os.path.exists('%s/%04d/coeff-n.out' % (NEXMD,dir)):\n                print >> error, 'Path %s%04d/coeff-n.out does not exist.' % (NEXMD,dir)\n                errflag = 1\n                ttraj += 1\n                continue\n            data = open('%s/%04d/coeff-n.out' % (NEXMD,dir),'r')\n            data = data.readlines()\n            tsteps = len(data)\n            tflag = 0\n            if tsteps >= tscol:\n                poph = np.zeros((tscol,header.n_exc_states_propagate))\n                popc = np.zeros((tscol,header.n_exc_states_propagate))\n                index = 0\n                for line in data[0:tscol:1]:\n                    val = line.split()\n                    pes = np.int(val[0])\n                    time = np.around(np.float(val[1]), decimals = 3)\n                    if time != times[index]:\n                        print >> error, 'There is an inconsistency in time-step in %s%04d at %.3f fs' % (NEXMD,dir,times[index])\n                        tflag = 1\n                        errflag = 1\n                        break\n                    poph[index][pes-1] = 1.0\n                    popc[index] = np.float_(val[2:2+header.n_exc_states_propagate])\n                    index += 1\n                if tflag == 0:\n                    fpoph += poph\n                    fpopc += popc\n                    print '%s%04d' % (NEXMD,dir), '%0*.2f' % (len(str((header.n_class_steps))) + 2, (tsteps - 1)*header.time_step)\n                    ctraj += 1\n                    if tsteps == header.n_class_steps:\n                        etraj += 1\n            else:\n                print '%s%04d' % (NEXMD,dir), '%0*.2f' % (len(str((header.n_class_steps))) + 2, (tsteps - 1)*header.time_step)\n                print >> error, '%s%04d' % (NEXMD,dir), '%0*.2f' % (len(str((header.n_class_steps))) + 2, (tsteps - 1)*header.time_step)\n                errflag = 1\n            ttraj += 1\n    if ctraj == 0:\n        print 'No trajectories completed within %0*.2f fs.' % (len(str(header.n_class_steps)),tcoll)\n        os.remove('%s/pop_mean_ensemble.out' % (cwd))\n    else:\n        fpoph = fpoph/ctraj\n        fpopc = fpopc/ctraj\n        print 'Total trajectories:', '%04d' % (ttraj)\n        print 'Completed trajectories:', '%04d' % (ctraj)\n        print 'Excellent trajectories:', '%04d' % (etraj)\n        print >> output, 'Total trajectories: ', '%04d' % (ttraj)\n        print >> output, 'Completed trajectories: ', '%04d' % (ctraj)\n        print >> output, 'Excellent trajectories: ', '%04d' % (etraj)\n        for tstep in np.arange(tscol):\n            print >> output, '%0*.2f' % (len(str((header.n_class_steps))) + 2,header.time_step*tstep), ' '.join(str('%.3f' % (x)) for x in fpoph[tstep]), '%.3f' % (np.sum(fpoph[tstep])), ' '.join(str('%.3f' % (x)) for x in fpopc[tstep]), '%.3f' % (np.sum(fpopc[tstep]))\n    if errflag == 1:\n        print 'One or more trajectories have experienced an error, check pop_mean_ensemble.err.'\n    else:\n        os.remove('%s/pop_mean_ensemble.err' % (cwd))\n", "meta": {"hexsha": "eab6b2f38ec3d3a17881a6891bd902348317e39c", "size": 6590, "ext": "py", "lang": "Python", "max_stars_repo_path": "getexcited/getexcited_package/population.py", "max_stars_repo_name": "lanl/NEXMD", "max_stars_repo_head_hexsha": "f2cbf1bce06df972bb6596beb979800da833708c", "max_stars_repo_licenses": ["BSD-3-Clause", "Unlicense"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-10-08T13:38:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T20:33:43.000Z", "max_issues_repo_path": "getexcited/getexcited_package/population.py", "max_issues_repo_name": "lanl/NEXMD", "max_issues_repo_head_hexsha": "f2cbf1bce06df972bb6596beb979800da833708c", "max_issues_repo_licenses": ["BSD-3-Clause", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "getexcited/getexcited_package/population.py", "max_forks_repo_name": "lanl/NEXMD", "max_forks_repo_head_hexsha": "f2cbf1bce06df972bb6596beb979800da833708c", "max_forks_repo_licenses": ["BSD-3-Clause", "Unlicense"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-10-08T13:39:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T20:35:10.000Z", "avg_line_length": 41.974522293, "max_line_length": 269, "alphanum_fraction": 0.5792109256, "include": true, "reason": "import numpy", "num_tokens": 1795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.1716795746847665}}
{"text": "# -*- coding: utf-8 -*-\n\n# Copyright (c) 2012, Sergio Callegari\n# All rights reserved.\n\n# This file is part of PyDSM.\n\n# PyDSM is free software: you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# PyDSM is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with PyDSM.  If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"\nComputation of the impulse response of a DT filter (:mod:`pydsm.ir`)\n====================================================================\n\nCompute (approximating by truncation) the impulse response\nof a discrete time filter, trying to (roughly) guess the appropriate\ntruncation.\n\n.. currentmodule:: pydsm.ir\n\nFunctions\n---------\n\n.. autosummary::\n   :toctree: generated/\n\n    guess_ir_length  -- Guess appropriate truncation length\n    impulse_response  -- Compute impulse response of DT filter\n\"\"\"\n\nfrom __future__ import division, print_function\n\nimport numpy as np\nimport scipy as sp\n__import__(\"scipy.signal\")\n\n__all__ = [\"impulse_response\", \"guess_ir_length\"]\n\n\ndef impulse_response(h, m=None, db=80):\n    \"\"\"\n    Computes the filter impulse response\n\n    Parameters\n    ----------\n    h : tuple_like\n        the filter definition either in zpk or in nd form.\n\n    Returns\n    -------\n    ir : ndarray\n        the truncated impulse response\n\n    Other Parameters\n    ----------------\n    m : int, optional\n        the number of samples after which the impulse response should be\n        truncated. Defaults to None, which means *try to guess*\n    db : real, optional\n        a hint about how to guess the length where the impuls response\n        should be truncated (defaults to 80)\n\n    Notes\n    -----\n    The guess about the lenght where the impulse response can be truncated\n    is extremely rough. See :func:`guess_ir_length` in this module for\n    further info.\n    \"\"\"\n    if len(h) == 3:\n        (b, a) = sp.signal.zpk2tf(*h)\n        b = b.real\n        a = a.real\n    else:\n        (b, a) = h\n    if m is None:\n        m = guess_ir_length(h, db)\n    ins = np.zeros(m)\n    ins[0] = 1\n    return sp.signal.lfilter(b, a, ins)\n\n\ndef guess_ir_length(h, db=80):\n    \"\"\"\n    Tries to estimate an appropriate length for the filter response\n\n    Parameters\n    ----------\n    h : tuple_like\n        the filter definition either in zpk or in nd form.\n    db : real, optional\n        a hint about how to guess the length where the impulse response\n        should be truncated. This is defined on a log scale. The larger\n        the longer the resulting length. Defaults to 80.\n\n    Returns\n    -------\n    m : int\n        a guess about the appropriate number of samples to represent the\n        filter impulse response with the required accuracy\n\n    Notes\n    -----\n    The guess is based on the slowlest pole of the filter, considering when\n    its response is attenuated to -db. This can be by far too optimistic in\n    some cases and particularly when there are overlapping or similar poles.\n\n    Do not try to use this function for filters with poles in 1.\n    \"\"\"\n    # Put h in zpk form if it is in tf form\n    if len(h) == 2:\n        h = sp.signal.tf2zpk(*h)\n    pp = h[1]\n    t_z = len(h[0])+1\n    if len(pp) == 0:\n        t_p = 0\n    else:\n        # Try to estimate length of decay of the filter h.\n        # The estimation is extremely rough, based on the decay\n        # rate of the pole with maximum magnitude.\n        # Thus, it breaks easily when there are poles very close\n        # one to the other or overlapping.\n        # Furthermore, this code should not be called if there is\n        # a pole in z=1.\n        os = np.seterr(divide='ignore')\n        sr = np.log(np.abs(pp))\n        np.seterr(**os)\n        # Take slowlest pole\n        wmin = np.min(np.abs(sr))\n        # 1/omega min is time constant in sample periods.\n        # Let's multiply the time constant in order to have\n        # the transient attenuated by db decibels\n        t_p = int(np.ceil(db/20*np.log(10)/wmin))\n    return t_p+t_z\n", "meta": {"hexsha": "249c776510d3b4d567f79be22ea85876c3d13713", "size": 4356, "ext": "py", "lang": "Python", "max_stars_repo_path": "pydsm/ir.py", "max_stars_repo_name": "EnjoyLifeFund/macHighSierra-py36-pkgs", "max_stars_repo_head_hexsha": "5668b5785296b314ea1321057420bcd077dba9ea", "max_stars_repo_licenses": ["BSD-3-Clause", "BSD-2-Clause", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pydsm/ir.py", "max_issues_repo_name": "EnjoyLifeFund/macHighSierra-py36-pkgs", "max_issues_repo_head_hexsha": "5668b5785296b314ea1321057420bcd077dba9ea", "max_issues_repo_licenses": ["BSD-3-Clause", "BSD-2-Clause", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pydsm/ir.py", "max_forks_repo_name": "EnjoyLifeFund/macHighSierra-py36-pkgs", "max_forks_repo_head_hexsha": "5668b5785296b314ea1321057420bcd077dba9ea", "max_forks_repo_licenses": ["BSD-3-Clause", "BSD-2-Clause", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.25, "max_line_length": 76, "alphanum_fraction": 0.6414141414, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118493816807, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.17167956964825454}}
{"text": "#-*-coding:utf-8-*-\n'''\nDpCas-Light\n||||      ||||       ||||         ||        ||||\n||  ||    ||  ||   ||    ||      ||||     ||    ||\n||    ||  ||   || ||      ||    ||  ||     ||\n||    ||  ||  ||  ||           ||====||      ||||\n||    ||  ||||    ||      ||  ||======||         ||\n||  ||    ||       ||    ||  ||        ||  ||    ||\n||||      ||         ||||   ||          ||   ||||\n\n/------------------ Who You Want 2 See ------------------/\n'''\n# date:2021-04-17\n# Author: Eric.Lee\n# function: pipline\n\nimport os\nimport numpy as np\nimport cv2\nimport torch\nfrom PIL import Image\n\ndef compute_iou(rec1, rec2):\n    \"\"\"\n    computing IoU\n    :param rec1: (y0, x0, y1, x1), which reflects\n            (top, left, bottom, right)\n    :param rec2: (y0, x0, y1, x1)\n    :return: scala value of IoU\n    \"\"\"\n    # computing area of each rectangles\n    S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1])\n    S_rec2 = (rec2[2] - rec2[0]) * (rec2[3] - rec2[1])\n\n    # computing the sum_area\n    sum_area = S_rec1 + S_rec2\n\n    # find the each edge of intersect rectangle\n    left_line = max(rec1[1], rec2[1])\n    right_line = min(rec1[3], rec2[3])\n    top_line = max(rec1[0], rec2[0])\n    bottom_line = min(rec1[2], rec2[2])\n\n    # judge if there is an intersect\n    if left_line >= right_line or top_line >= bottom_line:\n        return 0\n    else:\n        intersect = (right_line - left_line) * (bottom_line - top_line)\n        #return (intersect / (sum_area - intersect))*1.0\n        return (intersect / (S_rec1 + 1e-6))*1.0\n\ndef draw_landmarks(img,output,face_w,face_h,x0,y0,vis = False):\n    img_width = img.shape[1]\n    img_height = img.shape[0]\n    dict_landmarks = {}\n    eyes_center = []\n    x_list = []\n    y_list = []\n    for i in range(int(output.shape[0]/2)):\n        x = output[i*2+0]*float(face_w) + x0\n        y = output[i*2+1]*float(face_h) + y0\n\n        x_list.append(x)\n        y_list.append(y)\n\n        if 41>= i >=33:\n            if 'left_eyebrow' not in dict_landmarks.keys():\n                dict_landmarks['left_eyebrow'] = []\n            dict_landmarks['left_eyebrow'].append([int(x),int(y),(0,255,0)])\n            if vis:\n                cv2.circle(img, (int(x),int(y)), 2, (0,255,0),-1)\n        elif 50>= i >=42:\n            if 'right_eyebrow' not in dict_landmarks.keys():\n                dict_landmarks['right_eyebrow'] = []\n            dict_landmarks['right_eyebrow'].append([int(x),int(y),(0,255,0)])\n            if vis:\n                cv2.circle(img, (int(x),int(y)), 2, (0,255,0),-1)\n        elif 67>= i >=60:\n            if 'left_eye' not in dict_landmarks.keys():\n                dict_landmarks['left_eye'] = []\n            dict_landmarks['left_eye'].append([int(x),int(y),(255,55,255)])\n            if vis:\n                cv2.circle(img, (int(x),int(y)), 2, (255,0,255),-1)\n        elif 75>= i >=68:\n            if 'right_eye' not in dict_landmarks.keys():\n                dict_landmarks['right_eye'] = []\n            dict_landmarks['right_eye'].append([int(x),int(y),(255,55,255)])\n            if vis:\n                cv2.circle(img, (int(x),int(y)), 2, (255,0,255),-1)\n        elif 97>= i >=96:\n            eyes_center.append((x,y))\n            if vis:\n                cv2.circle(img, (int(x),int(y)), 2, (0,0,255),-1)\n        elif 54>= i >=51:\n            if 'bridge_nose' not in dict_landmarks.keys():\n                dict_landmarks['bridge_nose'] = []\n            dict_landmarks['bridge_nose'].append([int(x),int(y),(0,170,255)])\n            if vis:\n                cv2.circle(img, (int(x),int(y)), 2, (0,170,255),-1)\n        elif 32>= i >=0:\n            if 'basin' not in dict_landmarks.keys():\n                dict_landmarks['basin'] = []\n            dict_landmarks['basin'].append([int(x),int(y),(255,30,30)])\n            if vis:\n                cv2.circle(img, (int(x),int(y)), 2, (255,30,30),-1)\n        elif 59>= i >=55:\n            if 'wing_nose' not in dict_landmarks.keys():\n                dict_landmarks['wing_nose'] = []\n            dict_landmarks['wing_nose'].append([int(x),int(y),(0,255,255)])\n            if vis:\n                cv2.circle(img, (int(x),int(y)), 2, (0,255,255),-1)\n        elif 87>= i >=76:\n            if 'out_lip' not in dict_landmarks.keys():\n                dict_landmarks['out_lip'] = []\n            dict_landmarks['out_lip'].append([int(x),int(y),(255,255,0)])\n            if vis:\n                cv2.circle(img, (int(x),int(y)), 2, (255,255,0),-1)\n        elif 95>= i >=88:\n            if 'in_lip' not in dict_landmarks.keys():\n                dict_landmarks['in_lip'] = []\n            dict_landmarks['in_lip'].append([int(x),int(y),(50,220,255)])\n            if vis:\n                cv2.circle(img, (int(x),int(y)), 2, (50,220,255),-1)\n        else:\n            if vis:\n                cv2.circle(img, (int(x),int(y)), 2, (255,0,255),-1)\n    face_area = (max(x_list) - min(x_list))*(max(y_list) - min(y_list))\n    return dict_landmarks,eyes_center,face_area\n\ndef draw_contour(image,dict,vis = False):\n    x0 = 0# 偏置\n    y0 = 0\n\n    for key in dict.keys():\n        # print(key)\n        _,_,color = dict[key][0]\n\n        if 'left_eye' == key:\n            eye_x = np.mean([dict[key][i][0]+x0 for i in range(len(dict[key]))])\n            eye_y = np.mean([dict[key][i][1]+y0 for i in range(len(dict[key]))])\n            if vis:\n                cv2.circle(image, (int(eye_x),int(eye_y)), 3, (255,255,55),-1)\n        if 'right_eye' == key:\n            eye_x = np.mean([dict[key][i][0]+x0 for i in range(len(dict[key]))])\n            eye_y = np.mean([dict[key][i][1]+y0 for i in range(len(dict[key]))])\n            if vis:\n                cv2.circle(image, (int(eye_x),int(eye_y)), 3, (255,215,25),-1)\n\n        if 'basin' == key or 'wing_nose' == key:\n            pts = np.array([[dict[key][i][0]+x0,dict[key][i][1]+y0] for i in range(len(dict[key]))],np.int32)\n            if vis:\n                cv2.polylines(image,[pts],False,color,thickness = 2)\n\n        else:\n            points_array = np.zeros((1,len(dict[key]),2),dtype = np.int32)\n            for i in range(len(dict[key])):\n                x,y,_ = dict[key][i]\n                points_array[0,i,0] = x+x0\n                points_array[0,i,1] = y+y0\n\n            # cv2.fillPoly(image, points_array, color)\n            if vis:\n                cv2.drawContours(image,points_array,-1,color,thickness=2)\n\n\ndef plot_box(x, img, color=None, label=None, line_thickness=None):\n    # Plots one bounding box on image img\n    tl = line_thickness or round(0.002 * max(img.shape[0:2])) + 1  # line thickness\n    color = color or [random.randint(0, 255) for _ in range(3)]\n    c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))\n    cv2.rectangle(img, c1, c2, color, thickness=tl)\n    if label:\n        tf = max(tl - 1, 2)  # font thickness\n        t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]\n        c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3\n        cv2.rectangle(img, c1, c2, color, -1)  # filled\n        cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [185, 195,190], thickness=tf, lineType=cv2.LINE_AA)\n#-------------------------------------------------------------------------------\n\ndef face_alignment(imgn,eye_left_n,eye_right_n,\\\ndesiredLeftEye=(0.34, 0.42),desiredFaceWidth=256, desiredFaceHeight=None):\n\n    if desiredFaceHeight is None:\n        desiredFaceHeight = desiredFaceWidth\n\n    leftEyeCenter = eye_left_n\n    rightEyeCenter = eye_right_n\n    # compute the angle between the eye centroids\n    dY = rightEyeCenter[1] - leftEyeCenter[1]\n    dX = rightEyeCenter[0] - leftEyeCenter[0]\n    angle = np.degrees(np.arctan2(dY, dX))\n\n\n    # compute the desired right eye x-coordinate based on the\n    # desired x-coordinate of the left eye\n    desiredRightEyeX = 1.0 - desiredLeftEye[0]\n\t# determine the scale of the new resulting image by taking\n\t# the ratio of the distance between eyes in the *current*\n\t# image to the ratio of distance between eyes in the\n\t# *desired* image\n    dist = np.sqrt((dX ** 2) + (dY ** 2))\n    desiredDist = (desiredRightEyeX - desiredLeftEye[0])\n    desiredDist *= desiredFaceWidth\n    scale = desiredDist / dist\n    # compute center (x, y)-coordinates (i.e., the median point)\n    # between the two eyes in the input image\n    eyesCenter = ((leftEyeCenter[0] + rightEyeCenter[0]) / 2,(leftEyeCenter[1] + rightEyeCenter[1]) / 2)\n    # grab the rotation matrix for rotating and scaling the face\n    M = cv2.getRotationMatrix2D(eyesCenter, angle, scale)\n    # update the translation component of the matrix\n    tX = desiredFaceWidth * 0.5\n    tY = desiredFaceHeight * desiredLeftEye[1]\n    M[0, 2] += (tX - eyesCenter[0])\n    M[1, 2] += (tY - eyesCenter[1])\n\n    M_reg = np.zeros((3,3),dtype = np.float32)\n    M_reg[0,:] = M[0,:]\n    M_reg[1,:] = M[1,:]\n    M_reg[2,:] = (0,0,1.)\n    # print(M_reg)\n    M_I = np.linalg.inv(M_reg)#矩阵求逆，从而获得，目标图到原图的关系\n    # print(M_I)\n    # apply the affine transformation\n    (w, h) = (desiredFaceWidth, desiredFaceHeight)\n    # cv_resize_model = [cv2.INTER_LINEAR,cv2.INTER_CUBIC,cv2.INTER_NEAREST,cv2.INTER_AREA]\n\n    output = cv2.warpAffine(imgn, M, (w, h),flags=cv2.INTER_LINEAR,borderMode=cv2.BORDER_CONSTANT)#\n\n    #---------------------------------------------------------------------------------------\n\n    # ptx1 = int(eye_left_gt_n[0]*M[0][0] + eye_left_gt_n[1]*M[0][1] + M[0][2])\n    # pty1 = int(eye_left_gt_n[0]*M[1][0] + eye_left_gt_n[1]*M[1][1] + M[1][2])\n    #\n    # ptx2 = int(eye_right_gt_n[0]*M[0][0] + eye_right_gt_n[1]*M[0][1] + M[0][2])\n    # pty2 = int(eye_right_gt_n[0]*M[1][0] + eye_right_gt_n[1]*M[1][1] + M[1][2])\n\n    return output\n\ndef refine_face_bbox(bbox,img_shape):\n    height,width,_ = img_shape\n\n    x1,y1,x2,y2 = bbox\n\n    expand_w = (x2-x1)\n    expand_h = (y2-y1)\n\n    x1 -= expand_w*0.12\n    y1 -= expand_h*0.12\n    x2 += expand_w*0.12\n    y2 += expand_h*0.08\n\n    x1,y1,x2,y2 = int(x1),int(y1),int(x2),int(y2)\n\n    x1 = np.clip(x1,0,width-1)\n    y1 = np.clip(y1,0,height-1)\n    x2 = np.clip(x2,0,width-1)\n    y2 = np.clip(y2,0,height-1)\n\n    return (x1,y1,x2,y2)\n\ndef get_faces_batch_attribute(face_multitask_model,face_euler_model,dets,img_raw,use_cuda,face_size = 256,vis = False):\n\n    face_map = np.zeros([112*3,112*3,3]).astype(np.uint8)\n    face_map[:,:,0].fill(205)\n    face_map[:,:,1].fill(205)\n    face_map[:,:,2].fill(205)\n    if len(dets) == 0:\n        return [],[],[],face_map\n    img_align = img_raw.copy()\n    # 绘制图像\n    image_batch = None\n    r_bboxes = []\n    imgs_crop = []\n    for b in dets:\n        b = list(map(int, b))\n\n        r_bbox = refine_face_bbox((b[0],b[1],b[2],b[3]),img_raw.shape)\n        r_bboxes.append(r_bbox)\n        img_crop = img_raw[r_bbox[1]:r_bbox[3],r_bbox[0]:r_bbox[2]]\n        imgs_crop.append(img_crop)\n        img_ = cv2.resize(img_crop, (face_size,face_size), interpolation = cv2.INTER_LINEAR) # INTER_LINEAR INTER_CUBIC\n\n        img_ = img_.astype(np.float32)\n        img_ = (img_-128.)/256.\n\n        img_ = img_.transpose(2, 0, 1)\n        img_ = np.expand_dims(img_,0)\n\n        if image_batch is None:\n            image_batch = img_\n        else:\n            image_batch = np.concatenate((image_batch,img_),axis=0)\n\n    # # 填充最大 关键点 批次数据\n    # if len(dets) < ops.max_batch_size:\n    #     im_mask = np.zeros([1,3,ops.landmarks_img_size[0],ops.landmarks_img_size[1]], dtype = np.float32)\n    #     for i in range(ops.max_batch_size-len(dets)):\n    #         if image_batch is None:\n    #             image_batch = im_mask\n    #         else:\n    #             image_batch = np.concatenate((image_batch,im_mask),axis=0)\n    #\n    # print(\"image_batch shape:\",image_batch.shape)\n    # image_batch = torch.from_numpy(image_batch).float()\n    # #\n    # if use_cuda:\n    #     image_batch = image_batch.cuda()  # (bs, 3, h, w)\n\n    landmarks_pre,gender_pre,age_pre = face_multitask_model.predict(image_batch)\n    euler_angles = face_euler_model.predict(image_batch)\n    # print(\" -------->>> euler_angles : \",euler_angles)\n    # print(\"landmarks_pre,gender_pre,age_pre :\",landmarks_pre.shape,gender_pre.shape,age_pre.shape)\n\n    faces_identify = [] # 符合要求，需要识别的人的图像\n    faces_identify_bboxes = []# 符合要求，需要识别的人脸边界框\n    faceid_idx = 0 # 符合要求，需要识别的人的索引计数器\n    for i in range(len(dets)):\n        x0,y0 = r_bboxes[i][0],r_bboxes[i][1]\n        face_w = r_bboxes[i][2]-r_bboxes[i][0]\n        face_h = r_bboxes[i][3]-r_bboxes[i][1]\n        dict_landmarks,eyes_center,face_area = draw_landmarks(img_raw,landmarks_pre[i],face_w,face_h,x0,y0,vis = False)\n\n        gray_ = cv2.cvtColor(img_align[r_bboxes[i][1]:r_bboxes[i][3],r_bboxes[i][0]:r_bboxes[i][2],:], cv2.COLOR_BGR2GRAY)\n\n        blur_ = cv2.Laplacian(gray_, cv2.CV_64F).var()\n\n        gender_max_index = np.argmax(gender_pre[i])#概率最大类别索引\n        score_gender = gender_pre[i][gender_max_index]# 最大概率\n\n        yaw,pitch,roll = euler_angles[i]\n\n        cv2.putText(img_raw, \"yaw:{:.1f},pitch:{:.1f},roll:{:.1f}\".format(yaw,pitch,roll),(int(r_bboxes[i][0]-20),int(r_bboxes[i][1]-30)),cv2.FONT_HERSHEY_DUPLEX, 0.65, (253,139,54), 5)\n        cv2.putText(img_raw, \"yaw:{:.1f},pitch:{:.1f},roll:{:.1f}\".format(yaw,pitch,roll),(int(r_bboxes[i][0]-20),int(r_bboxes[i][1]-30)),cv2.FONT_HERSHEY_DUPLEX, 0.65, (20,185,255), 1)\n\n        cv2.putText(img_raw, \"{}\".format(int(face_area)),(int(r_bboxes[i][0]-1),int(r_bboxes[i][3]-3)),cv2.FONT_HERSHEY_DUPLEX, 0.65, (253,39,54), 5) # face_area\n        cv2.putText(img_raw, \"{}\".format(int(face_area)),(int(r_bboxes[i][0]-1),int(r_bboxes[i][3]-3)),cv2.FONT_HERSHEY_DUPLEX, 0.65, (20,185,255), 1)\n        if gender_max_index == 1.:\n            gender_str = \"male\"\n        else:\n            gender_str = \"female\"\n\n        if abs(yaw)<45.:\n            face_align_output = face_alignment(img_align,eyes_center[0],eyes_center[1],\n                desiredLeftEye=(0.365, 0.38),desiredFaceWidth=112, desiredFaceHeight=None)\n        else:\n            face_align_output = face_alignment(img_align,eyes_center[0],eyes_center[1],\n                desiredLeftEye=(0.38, 0.40),desiredFaceWidth=112, desiredFaceHeight=None)\n\n\n        # plot_box(r_bboxes[i][0:4], img_raw,label=\"{}, age: {:.1f}, unblur:{}\".format(gender_str,age_pre[i][0],int(blur_)), color=(255,90,90), line_thickness=2)\n        plot_box(r_bboxes[i][0:4], img_raw,label=\"{}, age: {:.1f}\".format(gender_str,age_pre[i][0]), color=(255,90,90), line_thickness=2)\n        # print(\"face_area:\",face_area)\n        # if (blur_>35) and abs(yaw)<36. and abs(pitch)<30. and (face_area>(60*60)):\n        if abs(yaw)<36. and abs(pitch)<36. and (face_area>(60*60)):\n            if vis :\n                draw_contour(img_raw,dict_landmarks,vis = True)\n\n            faces_identify.append(Image.fromarray(face_align_output))\n            faces_identify_bboxes.append(r_bboxes[i][0:4])\n\n            if faceid_idx<9:\n                y1_map,y2_map = int(faceid_idx/3)*112,(int(faceid_idx/3)+1)*112\n                x1_map,x2_map = int(faceid_idx%3)*112,(int(faceid_idx%3)+1)*112\n                face_map[y1_map:y2_map,x1_map:x2_map,:] = face_align_output\n                cv2.rectangle(face_map, (int(x1_map),int(y1_map)), (int(x2_map),int(y2_map)), (55,255,255), 2)\n                faceid_idx += 1\n        else:\n            cv2.putText(img_raw, \"bad for face reco\",(int(r_bboxes[i][0]-1),int(r_bboxes[i][3]+20)),cv2.FONT_HERSHEY_DUPLEX, 0.65, (20,15,255), 4)\n            cv2.putText(img_raw, \"bad for face reco\",(int(r_bboxes[i][0]-1),int(r_bboxes[i][3]+20)),cv2.FONT_HERSHEY_DUPLEX, 0.65, (220,185,25), 1)\n\n    return faces_identify,faces_identify_bboxes,r_bboxes,face_map\n", "meta": {"hexsha": "0f58ab591fb9293950b48bb3f37e90a5f0661b36", "size": 15487, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/wyw2s_lib/cores/wyw2s_fuction.py", "max_stars_repo_name": "JamesFengi/handPose_Eric", "max_stars_repo_head_hexsha": "3e329181930ebc7ef0fed2abb9a9d092a8541f9c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/wyw2s_lib/cores/wyw2s_fuction.py", "max_issues_repo_name": "JamesFengi/handPose_Eric", "max_issues_repo_head_hexsha": "3e329181930ebc7ef0fed2abb9a9d092a8541f9c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/wyw2s_lib/cores/wyw2s_fuction.py", "max_forks_repo_name": "JamesFengi/handPose_Eric", "max_forks_repo_head_hexsha": "3e329181930ebc7ef0fed2abb9a9d092a8541f9c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5201072386, "max_line_length": 185, "alphanum_fraction": 0.5644734293, "include": true, "reason": "import numpy", "num_tokens": 4985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.32082128783705344, "lm_q1q2_score": 0.1716709669915731}}
{"text": "#!/usr/bin/env python\n\"\"\"\nsubstitution_model.py\n\nContains classes for defining Markov models of substitution.\nThese classes depend on an Alphabet class member for defining the set\nof motifs that each represent a state in the Markov chain. Examples of\na 'dna' type alphabet motif is 'a', and of a 'codon' type motif is'atg'.\n\nBy default all models include the gap motif ('-' for a 'dna' alphabet or\n'---' for a 'codon' alphabet). This differs from software such as PAML,\nwhere gaps are treated as ambiguituous states (specifically, as 'n'). The gap\nmotif state can be excluded from the substitution model using the method\nexcludeGapMotif(). It is recommended that to ensure the alignment and the\nsubstitution model are defined with the same alphabet that modifications\nare done to the substitution model alphabet and this instance is then given\nto the alignment.\n\nThe model's substitution rate parameters are represented as a dictionary\nwith the parameter names as keys, and predicate functions as the values.\nThese predicate functions compare a pair of motifs, returning True or False.\nMany such functions are provided as methods of the class. For instance,\nthe istransition method is pertinent to dna based models. This method returns\nTrue if an 'a'/'g' or 'c'/'t' pair is passed to it, False otherwise. In this\nway the positioning of parameters in the instantaneous rate matrix (commonly\ncalled Q) is determined.\n\n>>> model = Nucleotide(equal_motif_probs=True)\n>>> model.setparameterrules({'alpha': model.istransition})\n>>> parameter_controller = model.make_likelihood_function(tree)\n\"\"\"\n\nimport inspect\nimport json\nimport warnings\n\nfrom collections.abc import Callable\n\nimport numpy\n\nfrom numpy.linalg import svd\n\nfrom cogent3.core import moltype\nfrom cogent3.evolve import motif_prob_model, parameter_controller, predicate\nfrom cogent3.evolve.discrete_markov import PsubMatrixDefn\nfrom cogent3.evolve.likelihood_tree import make_likelihood_tree_leaf\nfrom cogent3.evolve.substitution_calculation import (\n    AlignmentAdaptDefn,\n    CalcDefn,\n    CallDefn,\n    ConstDefn,\n    ExpDefn,\n    GammaDefn,\n    LengthDefn,\n    MonotonicDefn,\n    NonParamDefn,\n    PartitionDefn,\n    ProductDefn,\n    RateDefn,\n    SelectForDimension,\n)\nfrom cogent3.evolve.substitution_calculation import (\n    SubstitutionParameterDefn as ParamDefn,\n)\nfrom cogent3.evolve.substitution_calculation import WeightedPartitionDefn\nfrom cogent3.maths.optimisers import ParameterOutOfBoundsError\nfrom cogent3.util.misc import extend_docstring_from, get_object_provenance\n\n\n__author__ = \"Peter Maxwell, Gavin Huttley and Andrew Butterfield\"\n__copyright__ = \"Copyright 2007-2020, The Cogent Project\"\n__contributors__ = [\n    \"Gavin Huttley\",\n    \"Andrew Butterfield\",\n    \"Peter Maxwell\",\n    \"Matthew Wakefield\",\n    \"Brett Easton\",\n    \"Rob Knight\",\n    \"Von Bing Yap\",\n]\n__license__ = \"BSD-3\"\n__version__ = \"2020.7.2a\"\n__maintainer__ = \"Gavin Huttley\"\n__email__ = \"gavin.huttley@anu.edu.au\"\n__status__ = \"Production\"\n\n\ndef predicate2matrix(alphabet, pred, mask=None):\n    \"\"\"From a test like istransition() produce an MxM boolean matrix\"\"\"\n    M = len(alphabet)\n    result = numpy.zeros([M, M], int)\n    for i in range(M):\n        for j in range(M):\n            if mask is None or mask[i, j]:\n                result[i, j] = pred(alphabet[i], alphabet[j])\n    return result\n\n\ndef redundancy_in_predicate_masks(preds):\n    # Calculate the nullity of the predicates.  If non-zero\n    # there is some redundancy and the model will be overparameterised.\n    if len(preds) <= 1:\n        return 0\n    eqns = 1.0 * numpy.array([list(mask.flat) for mask in list(preds.values())])\n    svs = svd(eqns)[1]\n    # count non-duplicate non-zeros singular values\n    matrix_rank = len([sv for sv in svs if abs(sv) > 1e-8])\n    return len(preds) - matrix_rank\n\n\ndef _maxWidthIfTruncated(pars, delim, each):\n    # 'pars' is an array of lists of strings, how long would the longest\n    # list representation be if the strings were truncated at 'each'\n    # characters and joined together with 'delim'.\n    return max(\n        [\n            sum([min(len(par), each) for par in par_list])\n            + len(delim) * (len(par_list) - 1)\n            for par_list in pars.flat\n        ]\n    )\n\n\ndef _isSymmetrical(matrix):\n    return numpy.alltrue(numpy.alltrue(matrix == numpy.transpose(matrix)))\n\n\nclass _SubstitutionModel(object):\n    # Subclasses must provide\n    #  .make_param_controller_defns()\n\n    def __init__(\n        self,\n        alphabet,\n        motif_probs=None,\n        optimise_motif_probs=False,\n        equal_motif_probs=False,\n        motif_probs_from_data=None,\n        motif_probs_alignment=None,\n        mprob_model=None,\n        model_gaps=False,\n        recode_gaps=False,\n        motif_length=1,\n        name=\"\",\n        motifs=None,\n    ):\n        # subclasses can extend this incomplete docstring\n        \"\"\"\n\n        alphabet:\n         - alphabet - An Alphabet object\n         - motif_length: Use a tuple alphabet based on 'alphabet'.\n         - motifs: Use a subalphabet that only contains those motifs.\n         - model_gaps: Whether the gap motif should be included as a state.\n         - recode_gaps: Whether gaps in an alignment should be treated as an\n           ambiguous state instead.\n\n        Motif Probability:\n         - motif_probs: Dictionary of probabilities.\n         - equal_motif_probs: Flag to set alignment motif probs equal.\n         - motif_probs_alignment: An alignment from which motif probs are set.\n\n         If none of these options are set then motif probs will be derived\n         from the data: ie the particular alignment provided later.\n\n         - optimise_motif_probs: Treat like other free parameters.  Any values\n           set by the other motif_prob options will be used as initial values.\n\n         - mprob_model: 'tuple', 'conditional', 'monomer' or 'monomers' to specify how\n           tuple-alphabet (including codon) motif probs are used.\n\n        \"\"\"\n        d = locals()\n        exclude = (\"self\", \"__class__\")\n        self._serialisable = {k: v for k, v in d.items() if k not in exclude}\n        # MISC\n        assert len(alphabet) < 65, (\n            \"Alphabet too big. Try explicitly \" \"setting alphabet to PROTEIN or DNA\"\n        )\n\n        self.name = name\n        self._optimise_motif_probs = optimise_motif_probs\n\n        # ALPHABET\n        if recode_gaps:\n            if model_gaps:\n                warnings.warn(\"Converting gaps to wildcards AND modeling gaps\")\n            else:\n                model_gaps = False\n\n        self.recode_gaps = recode_gaps\n\n        self.moltype = alphabet.moltype\n        if model_gaps:\n            alphabet = alphabet.with_gap_motif()\n\n        if motif_length > 1:\n            alphabet = alphabet.get_word_alphabet(motif_length)\n\n        if motifs is not None:\n            alphabet = alphabet.get_subset(motifs)\n        self.alphabet = alphabet\n        self.gapmotif = alphabet.get_gap_motif()\n        self._word_length = alphabet.get_motif_len()\n\n        # MOTIF PROB ALPHABET MAPPING\n        if mprob_model is None:\n            mprob_model = \"tuple\" if self._word_length == 1 else \"conditional\"\n        elif mprob_model == \"word\":\n            mprob_model = \"tuple\"\n\n        if model_gaps and mprob_model != \"tuple\":\n            raise ValueError(\"mprob_model must be 'tuple' to model gaps\")\n\n        isinst = self._is_instantaneous\n        self._instantaneous_mask = predicate2matrix(self.alphabet, isinst)\n        self._instantaneous_mask_f = self._instantaneous_mask * 1.0\n        self._mprob_model = mprob_model\n        self.mprob_model = motif_prob_model.make_model(\n            mprob_model, alphabet, self._instantaneous_mask_f\n        )\n\n        # MOTIF PROBS\n        if equal_motif_probs:\n            assert not (\n                motif_probs or motif_probs_alignment\n            ), \"Motif probs equal or provided but not both\"\n            motif_probs = self.mprob_model.make_equal_motif_probs()\n        elif motif_probs_alignment is not None:\n            assert (\n                not motif_probs\n            ), \"Motif probs from alignment or provided but not both\"\n            motif_probs = self.count_motifs(motif_probs_alignment)\n            motif_probs = motif_probs.astype(float) / sum(motif_probs)\n            assert len(alphabet) == len(motif_probs)\n            motif_probs = dict(list(zip(alphabet, motif_probs)))\n        if motif_probs:\n            self.adapt_motif_probs(motif_probs)  # to check\n            self.motif_probs = motif_probs\n            if motif_probs_from_data is None:\n                motif_probs_from_data = False\n        else:\n            self.motif_probs = None\n            if motif_probs_from_data is None:\n                motif_probs_from_data = True\n        self.motif_probs_from_align = motif_probs_from_data\n\n    def __getnewargs_ex__(self, *args, **kw):\n        data = self.to_rich_dict(for_pickle=True)\n        return (), data\n\n    def to_rich_dict(self, for_pickle=False):\n        data = self._serialisable.copy()\n        if not for_pickle:\n            for key, value in data.items():\n                type_ = get_object_provenance(value)\n                if type_.startswith(\"cogent3\"):\n                    try:\n                        value = value.to_rich_dict(for_pickle=False)\n                    except AttributeError:\n                        pass\n                    finally:\n                        data[key] = value\n            if \"predicates\" in data and data[\"predicates\"]:\n                data[\"predicates\"] = [str(p) for p in data[\"predicates\"]]\n            data[\"type\"] = get_object_provenance(self)\n            data[\"version\"] = __version__\n        return data\n\n    def to_json(self):\n        \"\"\"returns result of json formatted string\"\"\"\n        data = self.to_rich_dict(for_pickle=False)\n        return json.dumps(data)\n\n    def get_param_list(self):\n        return []\n\n    def __str__(self):\n        s = [\"\\n%s (\" % self.__class__.__name__]\n        s.append(\n            \"name = '%s'; type = '%s';\"\n            % (getattr(self, \"name\", None), getattr(self, \"type\", None))\n        )\n        if hasattr(self, \"predicate_masks\"):\n            parlist = list(self.predicate_masks.keys())\n            s.append(\"params = %s;\" % parlist)\n        motifs = self.get_motifs()\n        s.append(\"number of motifs = %s;\" % len(motifs))\n        s.append(\"motifs = %s)\\n\" % motifs)\n        return \" \".join(s)\n\n    def get_alphabet(self):\n        return self.alphabet\n\n    def get_mprob_alphabet(self):\n        return self.mprob_model.get_input_alphabet()\n\n    def get_motifs(self):\n        return list(self.get_alphabet())\n\n    @property\n    def word_length(self):\n        return self._word_length\n\n    def get_motif_probs(self):\n        \"\"\"Return the dictionary of motif probabilities.\"\"\"\n        return self.motif_probs.copy()\n\n    def set_param_controller_motif_probs(self, pc, mprobs, **kw):\n        return self.mprob_model.set_param_controller_motif_probs(pc, mprobs, **kw)\n\n    def make_likelihood_function(\n        self,\n        tree,\n        motif_probs_from_align=None,\n        optimise_motif_probs=None,\n        aligned=True,\n        expm=None,\n        digits=None,\n        space=None,\n        **kw,\n    ):\n\n        if motif_probs_from_align is None:\n            motif_probs_from_align = self.motif_probs_from_align\n\n        if optimise_motif_probs is None:\n            optimise_motif_probs = self._optimise_motif_probs\n\n        kw[\"optimise_motif_probs\"] = optimise_motif_probs\n        kw[\"motif_probs_from_align\"] = motif_probs_from_align\n\n        if aligned:\n            klass = parameter_controller.AlignmentLikelihoodFunction\n        else:\n            alphabet = self.get_alphabet()\n            assert alphabet.get_gap_motif() not in alphabet\n            klass = parameter_controller.SequenceLikelihoodFunction\n\n        result = klass(self, tree, **kw)\n\n        if self.motif_probs is not None:\n            result.set_motif_probs(\n                self.motif_probs, is_constant=not optimise_motif_probs, auto=True\n            )\n\n        if expm is None:\n            expm = self._default_expm_setting\n        if expm is not None:\n            result.set_expm(expm)\n\n        if digits or space:\n            result.set_tables_format(digits=digits, space=space)\n\n        return result\n\n    def convert_alignment(self, alignment):\n        # this is to support for everything but HMM\n        result = {}\n        for seq_name in alignment.names:\n            sequence = alignment.get_gapped_seq(seq_name, self.recode_gaps)\n            result[seq_name] = self.convert_sequence(sequence, seq_name)\n        return result\n\n    def convert_sequence(self, sequence, name):\n        # make_likelihood_tree_leaf, sort of an indexed profile where duplicate\n        # columns stored once, so likelihoods only calc'd once\n        return make_likelihood_tree_leaf(sequence, self.get_alphabet(), name)\n\n    def count_motifs(self, alignment, include_ambiguity=False):\n        return self.mprob_model.count_motifs(\n            alignment, include_ambiguity, self.recode_gaps\n        )\n\n    def make_alignment_defn(self, model):\n        align = NonParamDefn(\"alignment\", (\"locus\",))\n        # The name of this matters, it's used in likelihood_function.py\n        # to retrieve the correct (adapted) alignment.\n        return AlignmentAdaptDefn(model, align)\n\n    def adapt_motif_probs(self, motif_probs, auto=False):\n        return self.mprob_model.adapt_motif_probs(motif_probs, auto=auto)\n\n    def calc_monomer_probs(self, word_probs):\n        # Not presently used, always go monomer->word instead\n        return self.mprob_model.calc_monomer_probs(word_probs)\n\n    def calc_word_probs(self, monomer_probs):\n        return self.mprob_model.calc_word_probs(monomer_probs)\n\n    def calc_word_weight_matrix(self, monomer_probs):\n        return self.mprob_model.calc_word_weight_matrix(monomer_probs)\n\n    def make_param_controller_defns(self, bin_names, endAtQd=False):\n        (\n            input_probs,\n            word_probs,\n            mprobs_matrix,\n        ) = self.mprob_model.make_motif_word_prob_defns()\n\n        if len(bin_names) > 1:\n            bprobs = PartitionDefn(\n                [1.0 / len(bin_names) for bin in bin_names],\n                name=\"bprobs\",\n                dimensions=[\"locus\"],\n                dimension=(\"bin\", bin_names),\n            )\n        else:\n            bprobs = None\n\n        defns = {\n            \"align\": self.make_alignment_defn(ConstDefn(self, \"model\")),\n            \"bprobs\": bprobs,\n            \"word_probs\": word_probs,\n        }\n\n        rate_params = self.make_rate_params(bprobs)\n        if endAtQd:\n            defns[\"Qd\"] = self.make_Qd_defn(word_probs, mprobs_matrix, rate_params)\n        else:\n            defns[\"psubs\"] = self.make_psubs_defn(\n                bprobs, word_probs, mprobs_matrix, rate_params\n            )\n        return defns\n\n\ndef non_zero_coords(matrix):\n    dim = matrix.shape[0]\n    coords = [(i, j) for i in range(dim) for j in range(dim) if matrix[i, j] != 0]\n    return coords\n\n\nclass _ContinuousSubstitutionModel(_SubstitutionModel):\n    # subclass must provide:\n    #\n    # - parameter_order: a list of parameter names corresponding to the\n    #   arguments of:\n    #\n    # - calc_exchangeability_matrix(*params)\n    #   convert len(self.parameter_order) params to a matrix\n\n    \"\"\"A substitution model for which the rate matrix (P) is derived from an\n    instantaneous rate matrix (Q).  The nature of the parameters used to define\n    Q is up to the subclasses.\n    \"\"\"\n\n    # At some point this can be made variable, and probably\n    # the default changed to False\n    long_indels_are_instantaneous = True\n\n    _exponentiator = None\n    _default_expm_setting = \"either\"\n\n    @extend_docstring_from(_SubstitutionModel.__init__)\n    def __init__(\n        self,\n        alphabet,\n        with_rate=False,\n        ordered_param=None,\n        distribution=None,\n        partitioned_params=None,\n        **kw,\n    ):\n        \"\"\"\n        - with_rate: Add a 'rate' parameter which varies by bin.\n        - ordered_param: name of a single parameter which distinguishes any bins.\n        - distribution: choices of 'free' or 'gamma' or an instance of some\n          distribution. Could probably just deprecate free\n        - partitioned_params: names of params to be partitioned across bins\n        \"\"\"\n\n        _SubstitutionModel.__init__(self, alphabet, **kw)\n        d = locals()\n        exclude = (\"self\", \"__class__\")\n        d = {k: v for k, v in d.items() if k not in exclude}\n        self._serialisable.update(d)\n        alphabet = self.get_alphabet()  # as may be altered by recode_gaps etc.\n\n        # BINS\n        if not ordered_param:\n            if ordered_param is not None:\n                warnings.warn(\"ordered_param should be a string or None\")\n                ordered_param = None\n            if distribution:\n                if with_rate:\n                    ordered_param = \"rate\"\n                else:\n                    raise ValueError(\"distribution provided without ordered_param\")\n        elif not isinstance(ordered_param, str):\n            warnings.warn(\"ordered_param should be a string or None\")\n            assert len(ordered_param) == 1, \"More than one ordered_param\"\n            ordered_param = ordered_param[0]\n            assert ordered_param, \"False value hidden in list\"\n        self.ordered_param = ordered_param\n\n        if distribution == \"gamma\":\n            distribution = GammaDefn\n        elif distribution in [None, \"free\"]:\n            distribution = MonotonicDefn\n        elif isinstance(distribution, str):\n            raise ValueError('Unknown distribution \"%s\"' % distribution)\n        self.distrib_class = distribution\n\n        if not partitioned_params:\n            partitioned_params = ()\n        elif isinstance(partitioned_params, str):\n            partitioned_params = (partitioned_params,)\n        else:\n            partitioned_params = tuple(partitioned_params)\n        if self.ordered_param:\n            if self.ordered_param not in partitioned_params:\n                partitioned_params += (self.ordered_param,)\n        self.partitioned_params = partitioned_params\n\n        if \"rate\" in partitioned_params:\n            with_rate = True\n        self.with_rate = with_rate\n\n        # CACHED SHORTCUTS\n        self._exponentiator = None\n        # self._ident = numpy.identity(len(self.alphabet), float)\n\n    def check_params_exist(self):\n        \"\"\"Raise an error if the parameters specified to be partitioned or\n        ordered don't actually exist.\"\"\"\n        for param in self.partitioned_params:\n            if param not in self.parameter_order and param != \"rate\":\n                desc = [\"partitioned\", \"ordered\"][param == self.ordered_param]\n                raise ValueError('%s param \"%s\" unknown' % (desc, param))\n\n    def _is_instantaneous(self, x, y):\n        diffs = sum([X != Y for (X, Y) in zip(x, y)])\n        return diffs == 1 or (\n            diffs > 1\n            and self.long_indels_are_instantaneous\n            and self._is_any_indel(x, y)\n        )\n\n    def _is_any_indel(self, x, y):\n        \"\"\"An indel of any length\"\"\"\n        # Things get complicated when a contigous indel of any length is OK:\n        if x == y:\n            return False\n        gap_start = gap_end = gap_strand = None\n        for (i, (X, Y)) in enumerate(zip(x, y)):\n            G = self.gapmotif[i]\n            if X != Y:\n                if X != G and Y != G:\n                    return False  # non-gap differences had their chance above\n                elif gap_start is None:\n                    gap_start = i\n                    gap_strand = [X, Y].index(G)\n                elif gap_end is not None or [X, Y].index(G) != gap_strand:\n                    return False  # can't start a second gap\n                else:\n                    pass  # extend open gap\n            elif gap_start is not None:\n                gap_end = i\n        return True\n\n    def calcQ(self, word_probs, mprobs_matrix, *params):\n        Q = self.calc_exchangeability_matrix(word_probs, *params)\n        row_totals = Q.sum(axis=1)\n        Q -= numpy.diag(row_totals)\n        Q *= 1.0 / (word_probs * row_totals).sum()\n        return Q\n\n    def get_reference_cell(self):\n        \"\"\"returns the reference cell of a given model\"\"\"\n        dim = len(self.alphabet)\n        mats = numpy.zeros((dim, dim), dtype=int)\n        for m in self.predicate_masks.values():\n            mats += m\n        ref_mask = self._instantaneous_mask - mats\n        ref_cells = set(non_zero_coords(ref_mask))\n        return ref_cells\n\n    def get_param_matrix_coords(self, include_ref_cell=False):\n        \"\"\"returncoordinates for every predicate\"\"\"\n        dim = len(self.alphabet)\n        mats = numpy.zeros((dim, dim), dtype=int)\n        param_coords = {}\n        for key, m in self.predicate_masks.items():\n            coords = [(i, j) for i in range(dim) for j in range(dim) if m[i, j] != 0]\n            coords = set(coords)\n            param_coords[key] = coords\n\n        if include_ref_cell:\n            param_coords[\"ref_cell\"] = self.get_reference_cell()\n        return param_coords\n\n    def make_Qd_defn(self, word_probs, mprobs_matrix, rate_params):\n        \"\"\"Diagonalized Q, ie: rate matrix prepared for exponentiation\"\"\"\n        Q = CalcDefn(self.calcQ, name=\"Q\")(word_probs, mprobs_matrix, *rate_params)\n        expm = NonParamDefn(\"expm\")\n        exp = ExpDefn(expm)\n        Qd = CallDefn(exp, Q, name=\"Qd\")\n        return Qd\n\n    def _make_bin_param_defn(self, edge_par_name, bin_par_name, bprob_defn):\n        # if no ordered param defined, behaves as old, everything indexed by\n        # and edge\n        if edge_par_name not in self.partitioned_params:\n            return ParamDefn(dimensions=[\"bin\"], name=bin_par_name)\n\n        if edge_par_name == self.ordered_param:\n            whole = self.distrib_class(bprob_defn, bin_par_name)\n        else:\n            # this forces them to average to one, but no forced order\n            # this means you can't force a param value to be shared across bins\n            # so 1st above approach has to be used\n            whole = WeightedPartitionDefn(bprob_defn, bin_par_name + \"_partn\")\n        whole.bin_names = bprob_defn.bin_names\n        return SelectForDimension(whole, \"bin\", name=bin_par_name)\n\n    def make_rate_params(self, bprobs):\n        params = []\n        for param_name in self.parameter_order:\n            if bprobs is None or param_name not in self.partitioned_params:\n                defn = ParamDefn(param_name)\n            else:\n                e_defn = ParamDefn(param_name, dimensions=[\"edge\", \"locus\"])\n                # should be weighted by bprobs*rates not bprobs\n                b_defn = self._make_bin_param_defn(\n                    param_name, param_name + \"_factor\", bprobs\n                )\n                defn = ProductDefn(b_defn, e_defn, name=param_name + \"_BE\")\n            params.append(defn)\n        return params\n\n    def make_fundamental_param_controller_defns(self, bin_names):\n        \"\"\"Everything one step short of the psubs, because cogent3.align code\n        needs to handle Q*t itself.\"\"\"\n        defns = self.make_param_controller_defns(bin_names, endAtQd=True)\n        assert \"length\" not in defns\n        defns[\"length\"] = LengthDefn()\n        return defns\n\n    def make_psubs_defn(self, bprobs, word_probs, mprobs_matrix, rate_params):\n        distance = self.make_distance_defn(bprobs)\n        P = self.make_continuous_psub_defn(\n            word_probs, mprobs_matrix, distance, rate_params\n        )\n        return P\n\n    def make_distance_defn(self, bprobs):\n        length = LengthDefn()\n        if self.with_rate and bprobs is not None:\n            b_rate = self._make_bin_param_defn(\"rate\", \"rate\", bprobs)\n            distance = ProductDefn(length, b_rate, name=\"distance\")\n        else:\n            distance = length\n        return distance\n\n    def make_continuous_psub_defn(\n        self, word_probs, mprobs_matrix, distance, rate_params\n    ):\n        Qd = self.make_Qd_defn(word_probs, mprobs_matrix, rate_params)\n        P = CallDefn(Qd, distance, name=\"psubs\")\n        return P\n\n\nclass StationaryQ:\n    \"Contains the Original Definition of calcQ\"\n\n    def calcQ(self, word_probs, mprobs_matrix, *params):\n        Q = self.calc_exchangeability_matrix(word_probs, *params)\n        Q *= mprobs_matrix\n        row_totals = Q.sum(axis=1)\n        Q -= numpy.diag(row_totals)\n        Q *= 1.0 / (word_probs * row_totals).sum()\n        return Q\n\n\nclass Empirical(StationaryQ, _ContinuousSubstitutionModel):\n    \"\"\"A continuous substitution model with a predefined instantaneous rate\n    matrix.\"\"\"\n\n    @extend_docstring_from(_ContinuousSubstitutionModel.__init__)\n    def __init__(self, alphabet, rate_matrix, **kw):\n        \"\"\"\n        - rate_matrix: The instantaneous rate matrix\n        \"\"\"\n        _ContinuousSubstitutionModel.__init__(self, alphabet, **kw)\n        d = locals()\n        exclude = (\"self\", \"__class__\")\n        d = {k: v for k, v in d.items() if k not in exclude}\n        self._serialisable.update(d)\n\n        alphabet = self.get_alphabet()  # as may be altered by recode_gaps etc.\n        N = len(alphabet)\n        assert rate_matrix.shape == (N, N)\n        assert numpy.alltrue(numpy.diagonal(rate_matrix) == 0)\n        self._instantaneous_mask_f = rate_matrix * 1.0\n        self._instantaneous_mask = self._instantaneous_mask_f != 0.0\n        self.symmetric = _isSymmetrical(self._instantaneous_mask_f)\n        self.parameter_order = []\n        self.check_params_exist()\n\n    def calc_exchangeability_matrix(self, mprobs):\n        return self._instantaneous_mask_f.copy()\n\n\nclass Parametric(_ContinuousSubstitutionModel):\n    \"\"\"A continuous substitution model with only user-specified substitution\n    parameters. This is a general process -- non-stationary and, if specified\n    via predicates, non-reversible\"\"\"\n\n    @extend_docstring_from(_ContinuousSubstitutionModel.__init__)\n    def __init__(self, alphabet, predicates=None, scales=None, **kw):\n        \"\"\"\n        - predicates: a dict of {name:predicate}. See cogent3.evolve.predicate\n        - scales: scale rules, dict with predicates\n        \"\"\"\n        self._canned_predicates = None\n        _ContinuousSubstitutionModel.__init__(self, alphabet, **kw)\n\n        d = locals()\n        exclude = (\"self\", \"__class__\")\n        d = {k: v for k, v in d.items() if k not in exclude}\n        self._serialisable.update(d)\n\n        (predicate_masks, predicate_order) = self._adapt_predicates(predicates or [])\n\n        # Check for redundancy in predicates, ie: 1 or more than combine\n        # to be equivalent to 1 or more others, or the distance params.\n        # Give a clearer error in simple cases like always false or true.\n        for (name, matrix) in list(predicate_masks.items()):\n            if numpy.alltrue((matrix == 0).flat):\n                raise ValueError(\"Predicate %s is always false.\" % name)\n        predicates_plus_scale = predicate_masks.copy()\n        predicates_plus_scale[None] = self._instantaneous_mask\n        for (name, matrix) in list(predicate_masks.items()):\n            if numpy.alltrue((matrix == self._instantaneous_mask).flat):\n                raise ValueError(\"Predicate %s is always true.\" % name)\n        if redundancy_in_predicate_masks(predicate_masks):\n            raise ValueError(\"Redundancy in predicates.\")\n        if redundancy_in_predicate_masks(predicates_plus_scale):\n            raise ValueError(\n                \"Some combination of predicates is\"\n                \" equivalent to the overall rate parameter.\"\n            )\n\n        self.predicate_masks = predicate_masks\n        self.parameter_order = []\n        self.predicate_indices = []\n        self.symmetric = _isSymmetrical(self._instantaneous_mask)\n        for pred in predicate_order:\n            mask = predicate_masks[pred]\n            if not _isSymmetrical(mask):\n                self.symmetric = False\n            indices = numpy.nonzero(mask)\n            assert numpy.alltrue(mask[indices] == 1)\n            self.parameter_order.append(pred)\n            self.predicate_indices.append(indices)\n        (self.scale_masks, scale_order) = self._adapt_predicates(scales or [])\n        self.check_params_exist()\n\n    def calc_exchangeability_matrix(self, mprobs, *params):\n        assert len(params) == len(self.predicate_indices), self.parameter_order\n        R = self._instantaneous_mask_f.copy()\n        for (indices, par) in zip(self.predicate_indices, params):\n            R[indices] *= par\n        return R\n\n    def ascii_art(self, delim=\"\", delim2=\"|\", max_width=70, return_table=False):\n        \"\"\"An ASCII-art table representing the model.  'delim' delimits\n        parameter names, 'delim2' delimits motifs\"\"\"\n        from cogent3.util.table import Table\n\n        labels = [m for m in self.alphabet]\n        pars = self.get_matrix_params()\n        rows = []\n        for i, row in enumerate(pars):\n            r = [labels[i]] + [delim.join(cell) for cell in row]\n            r[i + 1] = \"*\"  # identity\n            rows.append(r)\n\n        labels.insert(0, r\"From\\To\")\n        if self.name:\n            title = \"%s rate matrix\" % self.name\n        else:\n            title = \"rate matrix\"\n\n        t = Table(\n            header=labels,\n            data=rows,\n            max_width=max_width,\n            title=title,\n            index_name=r\"From\\To\",\n        )\n        result = t if return_table else t.to_string(center=True)\n        return result\n\n    def get_matrix_params(self):\n        \"\"\"Return the parameter assignment matrix.\"\"\"\n        dim = len(self.alphabet)\n        Pars = numpy.zeros([dim, dim], object)\n        for x, y in [(x, y) for x in range(dim) for y in range(dim)]:\n            Pars[x][y] = []  # a limitation of numpy.  [x,y] = [] fails!\n            if not self._instantaneous_mask[x, y]:\n                continue\n            for par in self.predicate_masks:\n                if self.predicate_masks[par][x, y]:\n                    Pars[x, y].append(par)\n            # sort the matrix entry to facilitate scaling calculations\n            Pars[x, y].sort()\n        return Pars\n\n    def get_param_list(self):\n        \"\"\"Return a list of parameter names.\"\"\"\n        return list(self.predicate_masks.keys())\n\n    def is_instantaneous(self, x, y):\n        return self._is_instantaneous(x, y)\n\n    def get_substitution_rate_value_from_Q(self, Q, motif_probs, pred):\n        pred_mask = list(self._adapt_predicates([pred])[0].values())[0]\n        pred_row_totals = numpy.sum(pred_mask * Q, axis=1)\n        inst_row_totals = numpy.sum(self._instantaneous_mask * Q, axis=1)\n        r = sum(pred_row_totals * motif_probs)\n        t = sum(inst_row_totals * motif_probs)\n        pred_size = numpy.sum(pred_mask.flat)\n        inst_size = sum(self._instantaneous_mask.flat)\n        return (r / pred_size) / ((t - r) / (inst_size - pred_size))\n\n    def get_scaled_lengths_from_Q(self, Q, motif_probs, length):\n        lengths = {}\n        for rule in self.scale_masks:\n            lengths[rule] = length * self.get_scale_from_Qs(\n                [Q], [1.0], motif_probs, rule\n            )\n        return lengths\n\n    def get_scale_from_Qs(self, Qs, bin_probs, motif_probss, rule):\n        rule = self.get_predicate_mask(rule)\n        weighted_scale = 0.0\n        bin_probs = numpy.asarray(bin_probs)\n        for (Q, bin_prob, motif_probs) in zip(Qs, bin_probs, motif_probss):\n            row_totals = numpy.sum(rule * Q, axis=1)\n            motif_probs = numpy.asarray(motif_probs)\n            word_probs = self.calc_word_probs(motif_probs)\n            scale = sum(row_totals * word_probs)\n            weighted_scale += bin_prob * scale\n        return weighted_scale\n\n    def get_predefined_predicates(self):\n        # overridden in subclasses\n        return {\"indel\": predicate.parse(\"-/?\")}\n\n    def get_predefined_predicate(self, name):\n        # Called by predicate parsing code\n        if self._canned_predicates is None:\n            self._canned_predicates = self.get_predefined_predicates()\n        return self._canned_predicates[name].interpret(self)\n\n    def _adapt_predicates(self, rules):\n        # dict or list of callables, predicate objects or predicate strings\n        if isinstance(rules, dict):\n            rules = list(rules.items())\n        else:\n            rules = [(None, rule) for rule in rules]\n        predicate_masks = {}\n        order = []\n        for (key, pred) in rules:\n            (label, mask) = self.adapt_predicate(pred, key)\n            if label in predicate_masks:\n                raise KeyError('Duplicate predicate name \"%s\"' % label)\n            predicate_masks[label] = mask\n            order.append(label)\n        return predicate_masks, order\n\n    def adapt_predicate(self, pred, label=None):\n        if isinstance(pred, str):\n            pred = predicate.parse(pred)\n        elif isinstance(pred, Callable):\n            pred = predicate.UserPredicate(pred)\n        pred_func = pred.make_model_predicate(self)\n        label = label or repr(pred)\n        mask = predicate2matrix(\n            self.get_alphabet(), pred_func, mask=self._instantaneous_mask\n        )\n        return (label, mask)\n\n    def get_predicate_mask(self, pred):\n        if pred in self.scale_masks:\n            mask = self.scale_masks[pred]\n        elif pred in self.predicate_masks:\n            mask = self.predicate_masks[pred]\n        else:\n            (label, mask) = self.adapt_predicate(pred)\n        return mask\n\n\nclass Stationary(StationaryQ, Parametric):\n    def __init__(self, *args, **kw):\n        Parametric.__init__(self, *args, **kw)\n\n\nclass TimeReversible(Stationary):\n    def __init__(self, *args, **kw):\n        \"\"\"\"\"\"\n        Stationary.__init__(self, *args, **kw)\n        if not self.symmetric:\n            raise ValueError(\n                \"TimeReversible exchangeability terms must be fully balanced\"\n            )\n\n\nclass _TimeReversibleNucleotide(TimeReversible):\n    def get_predefined_predicates(self):\n        return {\n            \"transition\": predicate.parse(\"R/R\") | predicate.parse(\"Y/Y\"),\n            \"transversion\": predicate.parse(\"R/Y\"),\n            \"indel\": predicate.parse(\"-/?\"),\n            \"kappa\": (predicate.parse(\"R/R\") | predicate.parse(\"Y/Y\")).aliased(\"kappa\"),\n        }\n\n\nclass TimeReversibleNucleotide(_TimeReversibleNucleotide):\n    \"\"\"A nucleotide substitution model.\"\"\"\n\n    def __init__(self, *args, **kw):\n        _TimeReversibleNucleotide.__init__(self, moltype.DNA.alphabet, *args, **kw)\n\n\nclass TimeReversibleDinucleotide(_TimeReversibleNucleotide):\n    \"\"\"A dinucleotide substitution model.\"\"\"\n\n    def __init__(self, *args, **kw):\n        _TimeReversibleNucleotide.__init__(\n            self, moltype.DNA.alphabet, motif_length=2, *args, **kw\n        )\n\n\nclass TimeReversibleTrinucleotide(_TimeReversibleNucleotide):\n    \"\"\"A trinucleotide substitution model.\"\"\"\n\n    def __init__(self, *args, **kw):\n        _TimeReversibleNucleotide.__init__(\n            self, moltype.DNA.alphabet, motif_length=3, *args, **kw\n        )\n\n\nclass TimeReversibleProtein(TimeReversible):\n    \"\"\"base protein substitution model.\"\"\"\n\n    def __init__(self, with_selenocysteine=False, *args, **kw):\n        alph = moltype.PROTEIN.alphabet\n        if not with_selenocysteine:\n            alph = alph.get_subset(\"U\", excluded=True)\n        TimeReversible.__init__(self, alph, *args, **kw)\n\n\ndef EmpiricalProteinMatrix(\n    matrix, motif_probs=None, optimise_motif_probs=False, recode_gaps=True, **kw\n):\n    alph = moltype.PROTEIN.alphabet.get_subset(\"U\", excluded=True)\n    return Empirical(\n        alph,\n        rate_matrix=matrix,\n        motif_probs=motif_probs,\n        model_gaps=False,\n        recode_gaps=recode_gaps,\n        optimise_motif_probs=optimise_motif_probs,\n        **kw,\n    )\n\n\nclass _CodonPredicates:\n    \"\"\"predicates for silent and replacement substitutions\"\"\"\n\n    def __init__(self, gc):\n        \"\"\"\n        Parameters\n        ----------\n\n        gc\n            a genetic code instance\n        \"\"\"\n        self.gc = gc\n\n    def silent(self, x, y):\n        return x != \"---\" and y != \"---\" and self.gc[x] == self.gc[y]\n\n    def replacement(self, x, y):\n        return x != \"---\" and y != \"---\" and self.gc[x] != self.gc[y]\n\n\nclass _Codon:\n    long_indels_are_instantaneous = True\n\n    def _is_instantaneous(self, x, y):\n        if x == self.gapmotif or y == self.gapmotif:\n            return x != y\n        else:\n            ndiffs = sum([X != Y for (X, Y) in zip(x, y)])\n            return ndiffs == 1\n\n    def get_predefined_predicates(self):\n        codon_preds = _CodonPredicates(self.get_alphabet().get_genetic_code())\n\n        preds = _TimeReversibleNucleotide.get_predefined_predicates(self)\n        preds.update(\n            {\n                \"indel\": predicate.parse(\"???/---\"),\n                \"silent\": predicate.UserPredicate(codon_preds.silent),\n                \"replacement\": predicate.UserPredicate(codon_preds.replacement),\n                \"omega\": predicate.UserPredicate(codon_preds.replacement),\n            }\n        )\n        return preds\n\n\nclass TimeReversibleCodon(_Codon, _TimeReversibleNucleotide):\n    \"\"\"Core substitution model for codons\"\"\"\n\n    def __init__(self, alphabet=None, gc=None, **kw):\n        if gc is not None:\n            alphabet = moltype.CodonAlphabet(gc=gc)\n        alphabet = alphabet or moltype.STANDARD_CODON\n        _TimeReversibleNucleotide.__init__(self, alphabet, **kw)\n", "meta": {"hexsha": "7c61173f9361a9f82a88949f4ac2f58ddebf72f8", "size": 37497, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/cogent3/evolve/substitution_model.py", "max_stars_repo_name": "aberki1234/cogent3", "max_stars_repo_head_hexsha": "af98b248a999bfeefd4cfed6bd59b4f30442e2d4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cogent3/evolve/substitution_model.py", "max_issues_repo_name": "aberki1234/cogent3", "max_issues_repo_head_hexsha": "af98b248a999bfeefd4cfed6bd59b4f30442e2d4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cogent3/evolve/substitution_model.py", "max_forks_repo_name": "aberki1234/cogent3", "max_forks_repo_head_hexsha": "af98b248a999bfeefd4cfed6bd59b4f30442e2d4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6539589443, "max_line_length": 88, "alphanum_fraction": 0.629383684, "include": true, "reason": "import numpy,from numpy", "num_tokens": 8709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.32082128783705344, "lm_q1q2_score": 0.1716709669915731}}
{"text": "# Copyright Contributors to the Pyro-Cov project.\n# SPDX-License-Identifier: Apache-2.0\n\nimport datetime\nimport functools\nimport logging\nimport math\nimport pickle\nimport re\nimport warnings\nfrom collections import Counter, OrderedDict, defaultdict\nfrom timeit import default_timer\nfrom typing import List\n\nimport numpy as np\nimport pyro\nimport pyro.distributions as dist\nimport torch\nimport tqdm\nfrom pyro import poutine\nfrom pyro.infer import SVI, JitTrace_ELBO, Trace_ELBO\nfrom pyro.infer.autoguide import (\n    AutoDelta,\n    AutoGuideList,\n    AutoLowRankMultivariateNormal,\n    AutoNormal,\n    AutoStructured,\n)\nfrom pyro.infer.autoguide.initialization import InitMessenger\nfrom pyro.infer.reparam import LocScaleReparam\nfrom pyro.nn.module import PyroModule, PyroParam\nfrom pyro.ops.streaming import CountMeanVarianceStats, StatsOfDict\nfrom pyro.optim import ClippedAdam\nfrom pyro.poutine.util import site_is_subsample\nfrom torch.distributions import constraints\n\nimport pyrocov.geo\n\nfrom . import pangolin, sarscov2\nfrom .ops import sparse_multinomial_likelihood\nfrom .util import pearson_correlation, quotient_central_moments\n\n# Requires https://github.com/pyro-ppl/pyro/pull/2953\ntry:\n    from pyro.infer.autoguide.effect import AutoRegressiveMessenger\nexcept ImportError:\n    AutoRegressiveMessenger = object\n\nlogger = logging.getLogger(__name__)\n\n# Reasonable values might be week (7), fortnight (14), or month (28)\nTIMESTEP = 14  # in days\nGENERATION_TIME = 5.5  # in days\nSTART_DATE = \"2019-12-01\"\n\n\ndef date_range(stop):\n    start = datetime.datetime.strptime(START_DATE, \"%Y-%m-%d\")\n    step = datetime.timedelta(days=TIMESTEP)\n    return np.array([start + step * t for t in range(stop)])\n\n\ndef get_fine_regions(columns, min_samples):\n    \"\"\"\n    Select regions that have at least ``min_samples`` samples.\n    Remaining regions will be coarsely aggregated up to country level.\n    \"\"\"\n    # Count number of samples in each subregion.\n    counts = Counter()\n    for location in columns[\"location\"]:\n        parts = location.split(\"/\")\n        if len(parts) < 2:\n            continue\n        parts = tuple(p.strip() for p in parts[:3])\n        counts[parts] += 1\n\n    # Select fine countries.\n    return frozenset(parts for parts, count in counts.items() if count >= min_samples)\n\n\ndef rank_loo_lineages(full_dataset: dict, min_samples: int = 50) -> List[str]:\n    \"\"\"\n    Compute a list of lineages ranked in descending order of cut size.\n    This is used in growth rate leave-one-out prediction experiments.\n    \"\"\"\n\n    def get_parent(lineage):\n        lineage = pangolin.decompress(lineage)\n        parent = pangolin.get_parent(lineage)\n        if parent is not None:\n            parent = pangolin.compress(parent)\n        return parent\n\n    # Compute sample counts.\n    lineage_id_inv = full_dataset[\"lineage_id_inv\"]\n    lineage_id = full_dataset[\"lineage_id\"]\n    clade_counts = full_dataset[\"weekly_clades\"].sum([0, 1])\n    lineage_counts = clade_counts.new_zeros(len(lineage_id)).scatter_add_(\n        0, full_dataset[\"clade_id_to_lineage_id\"], clade_counts\n    )\n    weekly_clades = full_dataset[\"weekly_clades\"]  # [T, P, C]\n    lineage_counts = weekly_clades.sum([0, 1])  # [C]\n    descendent_counts = lineage_counts.clone()\n    for c, lineage in enumerate(lineage_id_inv):\n        ancestor = get_parent(lineage)\n        while ancestor is not None:\n            a = lineage_id.get(ancestor)\n            if a is not None:\n                descendent_counts[a] += lineage_counts[c]\n            ancestor = get_parent(ancestor)\n    total = lineage_counts.sum().item()\n    cut_size = torch.min(descendent_counts, total - descendent_counts)\n\n    # Filter and sort lineages by cut size.\n    ranked_lineages = [\n        (size, lineage)\n        for size, lineage in zip(cut_size.tolist(), lineage_id_inv)\n        if lineage not in (\"A\", \"B\", \"B.1\")\n        if size >= min_samples\n    ]\n    ranked_lineages.sort(reverse=True)\n    return [name for gap, name in ranked_lineages]\n\n\ndef dense_to_sparse(x):\n    index = x.nonzero(as_tuple=False).T.contiguous()\n    value = x[tuple(index)]\n    total = x.sum(-1)\n    return {\"index\": index, \"value\": value, \"total\": total}\n\n\ndef load_gisaid_data(\n    *,\n    device=\"cpu\",\n    min_region_size=50,\n    include={},\n    exclude={},\n    end_day=None,\n    columns_filename=\"results/usher.columns.pkl\",\n    features_filename=\"results/usher.features.pt\",\n    feature_type=\"aa\",\n) -> dict:\n    \"\"\"\n    Loads the two files columns_filename and features_filename,\n    converts the input to PyTorch tensors and truncates the data according to\n    ``include`` and ``exclude``.\n\n    :param str device: torch device to use\n    :param dict include: filters of data to include\n    :param dict exclude: filters of data to exclude\n    :param end_day: last day to include\n    :param str columns_filename:\n    :param str features_filename:\n    :param str feature_type: Either \"aa\" for amino acid features or \"nuc\" for\n        nucleotide features.\n    :returns: A dataset dict\n    :rtype: dict\n    \"\"\"\n    logger.info(\"Loading data\")\n    include = include.copy()\n    exclude = exclude.copy()\n\n    if end_day:\n        logger.info(f\"Load gisaid data end_day: {end_day}\")\n\n    # Load column data.\n    with open(columns_filename, \"rb\") as f:\n        columns = pickle.load(f)\n    # Clean up location ids (temporary; this should be done in preprocess_gisaid.py).\n    columns[\"location\"] = list(map(pyrocov.geo.gisaid_normalize, columns[\"location\"]))\n    logger.info(f\"Training on {len(columns['day'])} rows with columns:\")\n    logger.info(\", \".join(columns.keys()))\n\n    # Aggregate regions smaller than min_region_size to country level.\n    fine_regions = get_fine_regions(columns, min_region_size)\n\n    # Filter features into numbers of mutations and possibly genes.\n    usher_features = torch.load(features_filename)\n    mutations = usher_features[f\"{feature_type}_mutations\"]\n    features = usher_features[f\"{feature_type}_features\"].to(\n        device=device, dtype=torch.get_default_dtype()\n    )\n    keep = [m.count(\",\") == 0 for m in mutations]  # restrict to single mutations\n    if include.get(\"gene\"):\n        re_gene = re.compile(include.pop(\"gene\"))\n        keep = [k and bool(re_gene.search(m)) for k, m in zip(keep, mutations)]\n    if exclude.get(\"gene\"):\n        re_gene = re.compile(exclude.pop(\"gene\"))\n        keep = [k and not re_gene.search(m) for k, m in zip(keep, mutations)]\n    if include.get(\"region\"):\n        gene, region = include.pop(\"region\")\n        lb, ub = sarscov2.GENE_STRUCTURE[gene][region]\n        for i, m in enumerate(mutations):\n            g, m = m.split(\":\")\n            if g != gene:\n                keep[i] = False\n                continue\n            match = re.search(\"[0-9]+\", m)\n            assert match is not None\n            pos = int(match.group())\n            if not (lb < pos <= ub):\n                keep[i] = False\n    mutations = [m for k, m in zip(keep, mutations) if k]\n    if mutations:\n        features = features[:, keep]\n    else:\n        warnings.warn(\"No mutations selected; using empty features\")\n        mutations = [\"S:D614G\"]  # bogus\n        features = features[:, :1] * 0\n    logger.info(\"Loaded {} feature matrix\".format(\" x \".join(map(str, features.shape))))\n\n    # Construct the list of clades.\n    clade_id_inv = usher_features[\"clades\"]\n    clade_id = {k: i for i, k in enumerate(clade_id_inv)}\n    clades = columns[\"clade\"]\n\n    # Generate sparse_data.\n    sparse_data: dict = Counter()\n    countries = set()\n    states = set()\n    state_to_country_dict = {}\n    location_id: dict = OrderedDict()\n    skipped_clades = set()\n    num_obs = 0\n    for day, location, clade in zip(columns[\"day\"], columns[\"location\"], clades):\n        if clade not in clade_id:\n            if clade not in skipped_clades:\n                skipped_clades.add(clade)\n                if not clade.startswith(\"fine\"):\n                    logger.warning(f\"WARNING skipping unsampled clade {clade}\")\n            continue\n\n        # Filter by include/exclude\n        row = {\n            \"location\": location,\n            \"day\": day,\n            \"clade\": clade,\n        }\n        if not all(re.search(v, row[k]) for k, v in include.items()):\n            continue\n        if any(re.search(v, row[k]) for k, v in exclude.items()):\n            continue\n\n        # Filter by day\n        if end_day is not None:\n            if day > end_day:\n                continue\n\n        # preprocess parts\n        parts = location.split(\"/\")\n        if len(parts) < 2:\n            continue\n        parts = tuple(p.strip() for p in parts[:3])\n        if len(parts) == 3 and parts not in fine_regions:\n            parts = parts[:2]\n        location = \" / \".join(parts)\n        # Populate countries on the left and states on the right.\n        if len(parts) == 2:  # country only\n            countries.add(location)\n            p = location_id.setdefault(location, len(countries) - 1)\n        else:  # state and country\n            country = \" / \".join(parts[:2])\n            countries.add(country)\n            c = location_id.setdefault(country, len(countries) - 1)\n            states.add(location)\n            p = location_id.setdefault(location, -len(states))\n            state_to_country_dict[p] = c\n\n        # Save sparse data.\n        num_obs += 1\n        t = day // TIMESTEP\n        c = clade_id[clade]\n        sparse_data[t, p, c] += 1\n    logger.warning(f\"WARNING skipped {len(skipped_clades)} unsampled clades\")\n    state_to_country = torch.full((len(states),), 999999, dtype=torch.long)\n    for s, c in state_to_country_dict.items():\n        state_to_country[s] = c\n    logger.info(f\"Found {len(states)} states in {len(countries)} countries\")\n    location_id_inv = [None] * len(location_id)\n    for k, i in location_id.items():\n        location_id_inv[i] = k\n    assert all(location_id_inv)\n\n    # Generate weekly_clades tensor from sparse_data.\n    if end_day is not None:\n        T = 1 + end_day // TIMESTEP\n    else:\n        T = 1 + max(columns[\"day\"]) // TIMESTEP\n    P = len(location_id)\n    C = len(clade_id)\n    weekly_clades = torch.zeros(T, P, C)\n    for tps, n in sparse_data.items():\n        weekly_clades[tps] = n\n    logger.info(f\"Dataset size [T x P x C] {T} x {P} x {C}\")\n\n    logger.info(\n        f\"Keeping {num_obs}/{len(clades)} rows \"\n        f\"(dropped {len(clades) - int(num_obs)})\"\n    )\n\n    # Construct sparse representation.\n    pc_index = weekly_clades.ne(0).any(0).reshape(-1).nonzero(as_tuple=True)[0]\n    sparse_counts = dense_to_sparse(weekly_clades)\n\n    # Construct time scales centered around observations.\n    time = torch.arange(float(T)) * TIMESTEP / GENERATION_TIME\n    time -= time.mean()\n\n    # Construct lineage <-> clade mappings.\n    lineage_to_clade = usher_features[\"lineage_to_clade\"]\n    clade_to_lineage = usher_features[\"clade_to_lineage\"]\n    lineage_id_inv = sorted(lineage_to_clade)\n    lineage_id = {k: i for i, k in enumerate(lineage_id_inv)}\n    clade_id_to_lineage_id = torch.zeros(len(clade_to_lineage), dtype=torch.long)\n    for c, l in clade_to_lineage.items():\n        clade_id_to_lineage_id[clade_id[c]] = lineage_id[l]\n    lineage_id_to_clade_id = torch.zeros(len(lineage_to_clade), dtype=torch.long)\n    for l, c in lineage_to_clade.items():\n        lineage_id_to_clade_id[lineage_id[l]] = clade_id[c]\n\n    dataset = {\n        \"clade_id\": clade_id,\n        \"clade_id_inv\": clade_id_inv,\n        \"clade_id_to_lineage_id\": clade_id_to_lineage_id,\n        \"clade_to_lineage\": usher_features[\"clade_to_lineage\"],\n        \"features\": features,\n        \"lineage_id\": lineage_id,\n        \"lineage_id_inv\": lineage_id_inv,\n        \"lineage_id_to_clade_id\": lineage_id_to_clade_id,\n        \"lineage_to_clade\": usher_features[\"lineage_to_clade\"],\n        \"location_id\": location_id,\n        \"location_id_inv\": location_id_inv,\n        \"mutations\": mutations,\n        \"pc_index\": pc_index,\n        \"sparse_counts\": sparse_counts,\n        \"state_to_country\": state_to_country,\n        \"time\": time,\n        \"weekly_clades\": weekly_clades,\n    }\n    return dataset\n\n\ndef subset_gisaid_data(\n    gisaid_dataset: dict,\n    location_queries=None,\n    max_clades=math.inf,\n) -> dict:\n    \"\"\"\n    Selects a small subset of data for exploratory fitting of a small model.\n    This is not used in the final published results.\n    \"\"\"\n    old = gisaid_dataset\n    new = old.copy()\n\n    # Select locations.\n    if location_queries is not None:\n        locations = sorted(\n            {\n                location\n                for location in new[\"location_id\"]\n                if any(q in location for q in location_queries)\n            }\n        )\n        ids = torch.tensor([old[\"location_id\"][location] for location in locations])\n        new[\"location_id\"] = {name: i for i, name in enumerate(locations)}\n        new[\"weekly_clades\"] = new[\"weekly_clades\"].index_select(1, ids)\n\n    # Select clades.\n    if new[\"weekly_clades\"].size(-1) > max_clades:\n        ids = (\n            new[\"weekly_clades\"]\n            .sum([0, 1])\n            .sort(0, descending=True)\n            .indices[:max_clades]\n        )\n        new[\"weekly_clades\"] = new[\"weekly_clades\"].index_select(-1, ids)\n        new[\"features\"] = new[\"features\"].index_select(0, ids)\n        new[\"clade_id_inv\"] = [new[\"clade_id_inv\"][i] for i in ids.tolist()]\n        new[\"clade_id\"] = {name: i for i, name in enumerate(new[\"clade_id_inv\"])}\n        new[\"sparse_counts\"] = dense_to_sparse(new[\"weekly_clades\"])\n\n    # Select mutations.\n    gaps = new[\"features\"].max(0).values - new[\"features\"].min(0).values\n    ids = (gaps >= 0.5).nonzero(as_tuple=True)[0]\n    new[\"mutations\"] = [new[\"mutations\"][i] for i in ids.tolist()]\n    new[\"features\"] = new[\"features\"].index_select(-1, ids)\n\n    logger.info(\n        \"Selected {}/{} places, {}/{} clades, {}/{} mutations, {}/{} samples\".format(\n            len(new[\"location_id\"]),\n            len(old[\"location_id\"]),\n            len(new[\"clade_id\"]),\n            len(old[\"clade_id\"]),\n            len(new[\"mutations\"]),\n            len(old[\"mutations\"]),\n            int(new[\"weekly_clades\"].sum()),\n            int(old[\"weekly_clades\"].sum()),\n        )\n    )\n\n    return new\n\n\ndef load_jhu_data(gisaid_data: dict) -> dict:\n    \"\"\"\n    Load case count time series.\n\n    This is used for plotting but is not used for fitting a model.\n    \"\"\"\n    # Load raw JHU case count data.\n    us_cases_df = pyrocov.geo.read_csv(\"time_series_covid19_confirmed_US.csv\")\n    global_cases_df = pyrocov.geo.read_csv(\"time_series_covid19_confirmed_global.csv\")\n    daily_cases = torch.cat(\n        [\n            pyrocov.geo.pd_to_torch(us_cases_df, columns=slice(11, None)),\n            pyrocov.geo.pd_to_torch(global_cases_df, columns=slice(4, None)),\n        ]\n    ).T\n    logger.info(\n        \"Loaded {} x {} daily case data, totaling {}\".format(\n            *daily_cases.shape, daily_cases[-1].sum().item()\n        )\n    )\n\n    # Convert JHU locations to GISAID locations.\n    locations = list(gisaid_data[\"location_id\"])\n    matrix = pyrocov.geo.gisaid_to_jhu_location(locations, us_cases_df, global_cases_df)\n    assert matrix.shape == (len(locations), daily_cases.shape[-1])\n    daily_cases = daily_cases @ matrix.T\n    daily_cases[1:] -= daily_cases[:-1].clone()  # cumulative -> density\n    daily_cases.clamp_(min=0)\n    assert daily_cases.shape[1] == len(gisaid_data[\"location_id\"])\n\n    # Convert daily counts to TIMESTEP counts (e.g. weekly).\n    start_date = datetime.datetime.strptime(START_DATE, \"%Y-%m-%d\")\n    jhu_start_date = pyrocov.geo.parse_date(us_cases_df.columns[11])\n    assert start_date < jhu_start_date\n    dt = (jhu_start_date - start_date).days\n    T = len(gisaid_data[\"weekly_clades\"])\n    weekly_cases = daily_cases.new_zeros(T, len(locations))\n    for w in range(TIMESTEP):\n        t0 = (w + dt) // TIMESTEP\n        source = daily_cases[w::TIMESTEP]\n        destin = weekly_cases[t0 : t0 + len(source)]\n        destin[:] += source[: len(destin)]\n    assert weekly_cases.sum() > 0\n\n    return {\n        \"daily_cases\": daily_cases.clamp(min=0),\n        \"weekly_cases\": weekly_cases.clamp(min=0),\n    }\n\n\ndef model(dataset, model_type, *, forecast_steps=None):\n    \"\"\"\n    Bayesian regression model of clade portions as a function of mutation features.\n\n    This function can be run in two different modes:\n    - During training, ``forecast_steps=None`` and the model is conditioned on\n      observed data.\n    - During prediction (after training), the likelihood statement is omitted\n      and instead a ``probs`` tensor is recorded; this is the predicted clade\n      portions in each (time, regin) bin.\n    \"\"\"\n    # Tensor shapes are commented at at the end of some lines.\n    features = dataset[\"features\"]\n    time = dataset[\"time\"]  # [T]\n    weekly_clades = dataset[\"weekly_clades\"]\n    sparse_counts = dataset[\"sparse_counts\"]\n    clade_id_to_lineage_id = dataset[\"clade_id_to_lineage_id\"]\n    pc_index = dataset[\"pc_index\"]\n    T, P, C = weekly_clades.shape\n    C, F = features.shape\n    L = len(dataset[\"lineage_id\"])\n    PC = len(pc_index)\n    assert PC <= P * C\n    assert time.shape == (T,)\n    assert clade_id_to_lineage_id.shape == (C,)\n\n    # Optionally extend time axis.\n    if forecast_steps is not None:  # During prediction.\n        T = T + forecast_steps\n        t0 = time[0]\n        dt = time[1] - time[0]\n        time = t0 + dt * torch.arange(float(T))\n        assert time.shape == (T,)\n\n    clade_plate = pyro.plate(\"clade\", C, dim=-1)\n    place_plate = pyro.plate(\"place\", P, dim=-2)\n    time_plate = pyro.plate(\"time\", T, dim=-3)\n    pc_plate = pyro.plate(\"place_clade\", PC, dim=-1)\n\n    # Configure reparametrization (which does not affect model density).\n    reparam = {}\n    if \"reparam\" in model_type:\n        reparam[\"coef\"] = LocScaleReparam()\n        reparam[\"pc_rate\"] = LocScaleReparam()\n        reparam[\"pc_init\"] = LocScaleReparam()\n    with poutine.reparam(config=reparam):\n\n        # Sample global random variables.\n        coef_scale = pyro.sample(\"coef_scale\", dist.LogNormal(-4, 2))\n        rate_scale = pyro.sample(\"rate_scale\", dist.LogNormal(-4, 2))\n        init_scale = pyro.sample(\"init_scale\", dist.LogNormal(0, 2))\n\n        # Assume relative growth rate depends strongly on mutations and weakly\n        # on clade and place. Assume initial infections depend strongly on\n        # clade and place.\n        coef = pyro.sample(\n            \"coef\", dist.Laplace(torch.zeros(F), coef_scale).to_event(1)\n        )  # [F]\n        with clade_plate:\n            rate_loc = pyro.deterministic(\"rate_loc\", 0.01 * coef @ features.T)  # [C]\n        with pc_plate:\n            pc_rate_loc = rate_loc.expand(P, C).reshape(-1)\n            pc_rate = pyro.sample(\n                \"pc_rate\", dist.Normal(pc_rate_loc[pc_index], rate_scale)\n            )  # [PC]\n            pc_init = pyro.sample(\"pc_init\", dist.Normal(0, init_scale))  # [PC]\n        with place_plate, clade_plate:\n            rate = pyro.deterministic(\n                \"rate\",\n                pc_rate_loc.scatter(0, pc_index, pc_rate).reshape(P, C),\n            )  # [P, C]\n            init = pyro.deterministic(\n                \"init\",\n                torch.full((P * C,), -1e2).scatter(0, pc_index, pc_init).reshape(P, C),\n            )  # [P, C]\n        logits = init + rate * time[:, None, None]  # [T, P, C]\n\n        # Optionally predict probabilities (during prediction).\n        if forecast_steps is not None:\n            probs = logits.new_zeros(logits.shape[:2] + (L,)).scatter_add_(\n                -1, clade_id_to_lineage_id.expand_as(logits), logits.softmax(-1)\n            )\n            with time_plate, place_plate, pyro.plate(\"lineage\", L, dim=-1):\n                pyro.deterministic(\"probs\", probs)\n            return\n\n        # Finally observe counts (during inference).\n        if \"dense\" in model_type:  # equivalent either way\n            # Compute a dense likelihood.\n            with time_plate, place_plate:\n                pyro.sample(\n                    \"obs\",\n                    dist.Multinomial(logits=logits.unsqueeze(-2), validate_args=False),\n                    obs=weekly_clades.unsqueeze(-2),\n                )  # [T, P, 1, C]\n            return\n        # Compromise between sparse and dense.\n        logits = logits.log_softmax(-1)\n        t, p, c = sparse_counts[\"index\"]\n        pyro.factor(\n            \"obs\",\n            sparse_multinomial_likelihood(\n                sparse_counts[\"total\"], logits[t, p, c], sparse_counts[\"value\"]\n            ),\n        )\n\n\nclass InitLocFn:\n    \"\"\"\n    Initializer for latent variables.\n\n    This is passed as the ``init_loc_fn`` to guides.\n    \"\"\"\n\n    def __init__(self, dataset):\n        # Initialize init.\n        init = dataset[\"weekly_clades\"].sum(0)  # [P, C]\n        init.add_(1 / init.size(-1)).div_(init.sum(-1, True))\n        init.log_().sub_(init.median(-1, True).values).add_(torch.randn(init.shape))\n        self.init = init  # [P, C]\n        self.init_decentered = init / 2\n        self.init_loc = init.mean(0)  # [C]\n        self.init_loc_decentered = self.init_loc / 2\n        self.pc_init = self.init.reshape(-1)[dataset[\"pc_index\"]]\n        self.pc_init = self.pc_init / 2\n        assert not torch.isnan(self.init).any()\n        logger.info(f\"init stddev = {self.init.std():0.3g}\")\n\n    def __call__(self, site):\n        name = site[\"name\"]\n        shape = site[\"fn\"].shape()\n        if hasattr(self, name):\n            result = getattr(self, name)\n            assert result.shape == shape\n            return result\n        if name in (\n            \"coef_scale\",\n            \"init_scale\",\n            \"init_loc_scale\",\n        ):\n            return torch.ones(shape)\n        if name == \"logits_scale\":\n            return torch.full(shape, 0.002)\n        if name in (\n            \"rate_scale\",\n            \"place_scale\",\n            \"clade_scale\",\n        ):\n            return torch.full(shape, 0.01)\n        if name in (\n            \"rate_loc\",\n            \"rate_loc_decentered\",\n            \"coef\",\n            \"coef_decentered\",\n            \"rate\",\n            \"rate_decentered\",\n            \"pc_rate\",\n            \"pc_rate_decentered\",\n        ):\n            return torch.rand(shape).sub_(0.5).mul_(0.01)\n        if name == \"coef_loc\":\n            return torch.rand(shape).sub_(0.5).mul_(0.01).add_(1.0)\n        raise ValueError(f\"InitLocFn found unhandled site {repr(name)}; please update.\")\n\n\nclass Guide(AutoGuideList):\n    \"\"\"\n    Custom guide for large-scale inference.\n\n    This combines a low-rank multivariate normal guide over small variables\n    with a mean field guide over remaining latent variables.\n    \"\"\"\n\n    def __init__(self, model, init_loc_fn, init_scale, rank):\n        super().__init__(InitMessenger(init_loc_fn)(model))\n\n        # Jointly estimate globals, mutation coefficients, and clade coefficients.\n        mvn = [\n            \"coef_scale\",\n            \"rate_loc_scale\",\n            \"init_loc_scale\",\n            \"rate_scale\",\n            \"init_scale\",\n            \"coef\",\n            \"coef_decentered\",\n            \"rate_loc\",\n            \"rate_loc_decentered\",\n            \"init_loc\",\n            \"init_loc_decentered\",\n        ]\n        self.append(\n            AutoLowRankMultivariateNormal(\n                poutine.block(model, expose=mvn),\n                init_loc_fn=init_loc_fn,\n                init_scale=init_scale,\n                rank=rank,\n            )\n        )\n        model = poutine.block(model, hide=mvn)\n\n        # Mean-field estimate all remaining latent variables.\n        self.append(AutoNormal(model, init_loc_fn=init_loc_fn, init_scale=init_scale))\n\n\nclass RegressiveGuide(AutoRegressiveMessenger):\n    def get_posterior(self, name, prior):\n        if name == \"coef\":\n            if not hasattr(self, \"coef\"):\n                # Initialize.\n                self.coef = PyroModule()\n                n = prior.shape()[-1]\n                rank = 100\n                assert n > 1\n                init_loc = self.init_loc_fn({\"name\": name, \"fn\": prior})\n                self.coef.loc = PyroParam(init_loc, event_dim=1)\n                self.coef.scale = PyroParam(\n                    torch.full((n,), self._init_scale),\n                    event_dim=1,\n                    constraint=constraints.positive,\n                )\n                self.coef.cov_factor = PyroParam(\n                    torch.empty(n, rank).normal_(0, 1 / rank ** 0.5),\n                    event_dim=2,\n                )\n            scale = self.coef.scale\n            cov_factor = self.coef.cov_factor * scale.unsqueeze(-1)\n            cov_diag = scale * scale\n            return dist.LowRankMultivariateNormal(self.coef.loc, cov_factor, cov_diag)\n\n        return super().get_posterior(name, prior)\n\n\n@torch.no_grad()\n@poutine.mask(mask=False)\ndef predict(\n    model,\n    guide,\n    dataset,\n    model_type,\n    *,\n    num_samples=1000,\n    vectorize=None,\n    save_params=(\"rate\", \"init\", \"probs\"),\n    forecast_steps=0,\n) -> dict:\n    def get_conditionals(data):\n        trace = poutine.trace(poutine.condition(model, data)).get_trace(\n            dataset, model_type, forecast_steps=forecast_steps\n        )\n        return {\n            name: site[\"value\"].detach()\n            for name, site in trace.nodes.items()\n            if site[\"type\"] == \"sample\" and not site_is_subsample(site)\n            if not name.startswith(\"obs\")\n        }\n\n    # Compute median point estimate.\n    result: dict = defaultdict(dict)\n    for name, value in get_conditionals(guide.median(dataset)).items():\n        if value.numel() < 1e5 or name in save_params:\n            result[\"median\"][name] = value\n\n    # Compute moments.\n    save_params = {\n        k for k, v in result[\"median\"].items() if v.numel() < 1e5 or k in save_params\n    }\n    if vectorize is None:\n        vectorize = result[\"median\"][\"probs\"].numel() < 1e6\n    if vectorize:\n        with pyro.plate(\"particles\", num_samples, dim=-4):\n            samples = get_conditionals(guide())\n        for k, v in samples.items():\n            if k in save_params:\n                result[\"mean\"][k] = v.mean(0).squeeze()\n                result[\"std\"][k] = v.std(0).squeeze()\n    else:\n        stats = StatsOfDict({k: CountMeanVarianceStats for k in save_params})\n        for _ in tqdm.tqdm(range(num_samples)):\n            stats.update(get_conditionals(guide()))\n        for name, stats_ in stats.get().items():\n            if \"mean\" in stats_:\n                result[\"mean\"][name] = stats_[\"mean\"]\n            if \"variance\" in stats_:\n                result[\"std\"][name] = stats_[\"variance\"].sqrt()\n    return dict(result)\n\n\ndef fit_svi(\n    dataset: dict,\n    *,\n    model_type: str,\n    guide_type: str,\n    cond_data={},\n    forecast_steps=0,\n    learning_rate=0.05,\n    learning_rate_decay=0.1,\n    num_steps=3001,\n    num_samples=1000,\n    clip_norm=10.0,\n    rank=200,\n    jit=True,\n    log_every=50,\n    seed=20210319,\n    check_loss=False,\n) -> dict:\n    \"\"\"\n    Fits a variational posterior using stochastic variational inference (SVI).\n    \"\"\"\n    start_time = default_timer()\n\n    logger.info(f\"Fitting {guide_type} guide via SVI\")\n    pyro.set_rng_seed(seed)\n    pyro.clear_param_store()\n    param_store = pyro.get_param_store()\n\n    # Initialize guide so we can count parameters and register hooks.\n    cond_data = {k: torch.as_tensor(v) for k, v in cond_data.items()}\n    model_ = poutine.condition(model, cond_data)\n    init_loc_fn = InitLocFn(dataset)\n    Elbo = JitTrace_ELBO if jit else Trace_ELBO\n    if guide_type == \"map\":\n        guide = AutoDelta(model_, init_loc_fn=init_loc_fn)\n    elif guide_type == \"normal\":\n        guide = AutoNormal(model_, init_loc_fn=init_loc_fn, init_scale=0.01)\n    elif guide_type == \"full\":\n        guide = AutoLowRankMultivariateNormal(\n            model_, init_loc_fn=init_loc_fn, init_scale=0.01, rank=rank\n        )\n    elif guide_type == \"structured\":\n        guide = AutoStructured(\n            model_,\n            init_loc_fn=init_loc_fn,\n            init_scale=0.01,\n            conditionals=defaultdict(\n                lambda: \"normal\",\n                rate_scale=\"delta\",\n                init_loc_scale=\"delta\",\n                init_scale=\"delta\",\n                coef=\"mvn\",\n                coef_decentered=\"mvn\",\n            ),\n        )\n    elif guide_type == \"regressive\":\n        guide = RegressiveGuide(model_, init_loc_fn=init_loc_fn, init_scale=0.01)\n    else:\n        guide = Guide(model_, init_loc_fn=init_loc_fn, init_scale=0.01, rank=rank)\n    # This initializes the guide:\n    latent_shapes = {k: v.shape for k, v in guide(dataset, model_type).items()}\n    latent_numel = {k: v.numel() for k, v in latent_shapes.items()}\n    logger.info(\n        \"\\n\".join(\n            [f\"Model has {sum(latent_numel.values())} latent variables of shapes:\"]\n            + [f\" {k} {tuple(v)}\" for k, v in latent_shapes.items()]\n        )\n    )\n    param_shapes = {k: v.shape for k, v in pyro.get_param_store().named_parameters()}\n    param_numel = {k: v.numel() for k, v in param_shapes.items()}\n    logger.info(\n        \"\\n\".join(\n            [f\"Guide has {sum(param_numel.values())} parameters of shapes:\"]\n            + [f\" {k} {tuple(v)}\" for k, v in param_shapes.items()]\n        )\n    )\n\n    # Log gradient norms during inference.\n    series: dict = defaultdict(list)\n\n    def hook(g, series):\n        series.append(torch.linalg.norm(g.reshape(-1), math.inf).item())\n\n    for name, value in pyro.get_param_store().named_parameters():\n        value.register_hook(functools.partial(hook, series=series[name]))\n\n    def optim_config(param_name):\n        config: dict = {\n            \"lr\": learning_rate,\n            \"lrd\": learning_rate_decay ** (1 / num_steps),\n            \"clip_norm\": clip_norm,\n        }\n        scalars = [k for k, v in latent_numel.items() if v == 1]\n        if any(\"locs.\" + s in name for s in scalars):\n            config[\"lr\"] *= 0.2\n        elif \"scales\" in param_name:\n            config[\"lr\"] *= 0.1\n        elif \"scale_tril\" in param_name:\n            config[\"lr\"] *= 0.05\n        elif \"factors\" in param_name or \"prec_sqrts\" in param_name:\n            config[\"lr\"] *= 0.05\n        elif \"weight_\" in param_name:\n            config[\"lr\"] *= 0.01\n        elif \"weight\" in param_name:\n            config[\"lr\"] *= 0.03\n        elif \"_centered\" in param_name:\n            config[\"lr\"] *= 0.1\n        return config\n\n    optim = ClippedAdam(optim_config)\n    elbo = Elbo(max_plate_nesting=3, ignore_jit_warnings=True)\n    svi = SVI(model_, guide, optim, elbo)\n    losses = []\n    num_obs = dataset[\"weekly_clades\"].count_nonzero()\n    for step in range(num_steps):\n        loss = svi.step(dataset=dataset, model_type=model_type)\n        assert not math.isnan(loss)\n        losses.append(loss)\n        median = guide.median()\n        for name, value in median.items():\n            if value.numel() == 1:\n                series[name].append(float(value))\n        if log_every and step % log_every == 0:\n            logger.info(\n                \" \".join(\n                    [f\"step {step: >4d} L={loss / num_obs:0.6g}\"]\n                    + [\n                        \"{}={:0.3g}\".format(\n                            \"\".join(p[0] for p in k.split(\"_\")).upper(), v.item()\n                        )\n                        for k, v in median.items()\n                        if v.numel() == 1\n                    ]\n                )\n            )\n        if check_loss and step >= 50:\n            prev = torch.tensor(losses[-50:-25], device=\"cpu\").median().item()\n            curr = torch.tensor(losses[-25:], device=\"cpu\").median().item()\n            assert (curr - prev) < num_obs, \"loss is increasing\"\n\n    result = predict(\n        model_,\n        guide,\n        dataset,\n        model_type,\n        num_samples=num_samples,\n        forecast_steps=forecast_steps,\n    )\n    result[\"losses\"] = losses\n    series[\"loss\"] = losses\n    result[\"series\"] = dict(series)\n    result[\"params\"] = {\n        k: v.detach().float().cpu().clone()\n        for k, v in param_store.items()\n        if v.numel() < 1e8\n    }\n    result[\"walltime\"] = default_timer() - start_time\n    return result\n\n\n@torch.no_grad()\ndef log_stats(dataset: dict, result: dict) -> dict:\n    \"\"\"\n    Logs statistics of predictions and model fit in the ``result`` of\n    ``fit_svi()``.\n\n    :param dict dataset: The dataset dictionary.\n    :param dict result: The output of :func:`fit_svi`.\n    :returns: A dictionary of statistics.\n    \"\"\"\n    stats = {k: float(v) for k, v in result[\"median\"].items() if v.numel() == 1}\n    stats[\"loss\"] = float(np.median(result[\"losses\"][-100:]))\n    mutations = dataset[\"mutations\"]\n    mean = result[\"mean\"][\"coef\"].cpu()\n    if not mean.shape:\n        return stats  # Work around error in map estimation.\n\n    # Statistical significance.\n    std = result[\"std\"][\"coef\"].cpu()\n    sig = mean.abs() / std\n    logger.info(f\"|μ|/σ [median,max] = [{sig.median():0.3g},{sig.max():0.3g}]\")\n    stats[\"|μ|/σ median\"] = sig.median()\n    stats[\"|μ|/σ max\"] = sig.max()\n\n    # Effects of individual mutations.\n    for name in [\"S:D614G\", \"S:N501Y\", \"S:E484K\", \"S:L452R\"]:\n        if name not in mutations:\n            continue\n        i = mutations.index(name)\n        m = mean[i] * 0.01\n        s = std[i] * 0.01\n        logger.info(f\"ΔlogR({name}) = {m:0.3g} ± {s:0.2f}\")\n        stats[f\"ΔlogR({name}) mean\"] = m\n        stats[f\"ΔlogR({name}) std\"] = s\n\n    # Growth rates of individual clades.\n    rate = quotient_central_moments(\n        result[\"mean\"][\"rate\"].mean(0), dataset[\"clade_id_to_lineage_id\"]\n    )[1]\n    rate = rate - rate[dataset[\"lineage_id\"][\"A\"]]\n    for lineage in [\"B.1.1.7\", \"B.1.617.2\", \"AY.23.1\"]:\n        R_RA = float(rate[dataset[\"lineage_id\"][lineage]].exp())\n        logger.info(f\"R({lineage})/R(A) = {R_RA:0.3g}\")\n        stats[f\"R({lineage})/R(A)\"] = R_RA\n\n    # Posterior predictive error.\n    L = len(dataset[\"lineage_id\"])\n    weekly_clades = dataset[\"weekly_clades\"]\n    weekly_lineages = torch.zeros(weekly_clades.shape[:-1] + (L,)).scatter_add_(\n        -1, dataset[\"clade_id_to_lineage_id\"].expand_as(weekly_clades), weekly_clades\n    )\n    true = weekly_lineages + 1e-20  # avoid nans\n    counts = true.sum(-1, True)\n    true_probs = true / counts\n    pred = result[\"median\"][\"probs\"][: len(true)] + 1e-20  # truncate, avoid nans\n    kl = true.mul(true_probs.log() - pred.log()).sum([0, -1])\n    error = (pred - true_probs) * counts ** 0.5  # scaled by Poisson stddev\n    mae = error.abs().mean(0)  # average over time\n    mse = error.square().mean(0)  # average over time\n    stats[\"MAE\"] = float(mae.sum(-1).mean())  # average over region\n    stats[\"RMSE\"] = float(mse.sum(-1).mean().sqrt())  # root average over region\n    stats[\"KL\"] = float(kl.sum() / counts.sum())  # in units of nats / observation\n    logger.info(\"KL = {KL:0.4g}, MAE = {MAE:0.4g}, RMSE = {RMSE:0.4g}\".format(**stats))\n\n    # Examine the MSE and RMSE over a few regions of interest.\n    queries = {\n        \"England\": [\"B.1.1.7\"],\n        # \"England\": [\"B.1.1.7\", \"B.1.177\", \"B.1.1\", \"B.1\"],\n        # \"USA / California\": [\"B.1.1.7\", \"B.1.429\", \"B.1.427\", \"B.1.2\", \"B.1\", \"P.1\"],\n    }\n    for place, lineages in queries.items():\n        matches = [p for name, p in dataset[\"location_id\"].items() if place in name]\n        if not matches:\n            continue\n        assert len(matches) == 1, matches\n        p = matches[0]\n        stats[f\"{place} KL\"] = float(kl[p].sum() / true[:, p].sum())\n        stats[f\"{place} MAE\"] = float(mae[p].sum())\n        stats[f\"{place} RMSE\"] = float(mse[p].sum().sqrt())\n        logger.info(\n            \"{}\\tKL = {:0.3g}, MAE = {:0.3g}, RMSE = {:0.3g}\".format(\n                place,\n                stats[f\"{place} KL\"],\n                stats[f\"{place} MAE\"],\n                stats[f\"{place} RMSE\"],\n            )\n        )\n\n        for lineage in lineages:\n            i = dataset[\"lineage_id\"][lineage]\n            stats[f\"{place} {lineage} MAE\"] = mae[p, i]\n            stats[f\"{place} {lineage} RMSE\"] = mse[p, i].sqrt()\n            logger.info(\n                \"{} {}\\tMAE = {:0.3g}, RMSE = {:0.3g}\".format(\n                    place,\n                    lineage,\n                    stats[f\"{place} {lineage} MAE\"],\n                    stats[f\"{place} {lineage} RMSE\"],\n                )\n            )\n\n    return {k: float(v) for k, v in stats.items()}\n\n\n@torch.no_grad()\ndef log_holdout_stats(fits: dict) -> dict:\n    \"\"\"\n    Logs statistics comparing multiple results from ``fit_svi``.\n    \"\"\"\n    assert len(fits) > 1\n    fits = list(fits.items())\n    stats = {}\n    for i, (name1, fit1) in enumerate(fits[:-1]):\n        for name2, fit2 in fits[i + 1 :]:\n            # Compute mutation similarity.\n            mutations = sorted(set(fit1[\"mutations\"]) & set(fit2[\"mutations\"]))\n            medians = []\n            for fit in (fit1, fit2):\n                mutation_id = {m: i for i, m in enumerate(fit[\"mutations\"])}\n                idx = torch.tensor([mutation_id[m] for m in mutations])\n                medians.append(fit[\"median\"][\"coef\"][idx] * 0.01)\n            error = medians[0] - medians[1]\n            mutation_std = torch.cat(medians).std().item()\n            mutation_rmse = error.square().mean().sqrt().item()\n            mutation_mae = error.abs().mean().item()\n            mutation_correlation = pearson_correlation(medians[0], medians[1]).item()\n\n            # Compute lineage similarity.\n            means = []\n            for fit in (fit1, fit2):\n                rate = fit[\"mean\"][\"rate\"]\n                if rate.dim() == 2:\n                    rate = rate.mean(0)\n                means.append(rate)\n            error = means[0] - means[1]\n            lineage_std = torch.cat(means).std().item()\n            lineage_rmse = error.square().mean().sqrt().item()\n            lineage_mae = error.abs().mean().item()\n            lineage_correlation = pearson_correlation(means[0], means[1]).item()\n\n            # Print stats.\n            logger.info(\n                f\"{name1} vs {name2} mutations: \"\n                f\"ρ = {mutation_correlation:0.3g}, \"\n                f\"RMSE = {mutation_rmse:0.3g}, \"\n                f\"MAE = {mutation_mae:0.3g}\"\n            )\n            logger.info(\n                f\"{name1} vs {name2} lineages: \"\n                f\"ρ = {lineage_correlation:0.3g}, \"\n                f\"RMSE = {lineage_rmse:0.3g}, \"\n                f\"MAE = {lineage_mae:0.3g}\"\n            )\n\n            # Save stats.\n            stats[\"mutation_corr\"] = mutation_correlation\n            stats[\"mutation_rmse\"] = mutation_rmse\n            stats[\"mutation_mae\"] = mutation_mae\n            stats[\"mutation_stddev\"] = mutation_std\n            stats[\"lineage_corr\"] = lineage_correlation\n            stats[\"lineage_rmse\"] = lineage_rmse\n            stats[\"lineage_mae\"] = lineage_mae\n            stats[\"lineage_stdev\"] = lineage_std\n\n    return {k: float(v) for k, v in stats.items()}\n", "meta": {"hexsha": "3182950687768e176edebd38a206842d2aee48ab", "size": 38920, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyrocov/mutrans.py", "max_stars_repo_name": "broadinstitute/pyro-cov", "max_stars_repo_head_hexsha": "c74bf06eaddb2c9ea59a36546a5576d3e938582d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2021-09-14T04:33:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T21:33:05.000Z", "max_issues_repo_path": "pyrocov/mutrans.py", "max_issues_repo_name": "broadinstitute/pyro-cov", "max_issues_repo_head_hexsha": "c74bf06eaddb2c9ea59a36546a5576d3e938582d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-11-02T13:48:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T18:08:35.000Z", "max_forks_repo_path": "pyrocov/mutrans.py", "max_forks_repo_name": "broadinstitute/pyro-cov", "max_forks_repo_head_hexsha": "c74bf06eaddb2c9ea59a36546a5576d3e938582d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-09-18T01:06:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T02:22:06.000Z", "avg_line_length": 36.5103189493, "max_line_length": 88, "alphanum_fraction": 0.5893627955, "include": true, "reason": "import numpy", "num_tokens": 9963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.1716342601049254}}
{"text": "import os\nimport shutil\nimport sys\nfrom collections import defaultdict\nimport warnings\n\n#Anaconda\nimport numpy as np\nfrom astropy.time import Time, TimeDelta\nfrom astropy import units as U\nfrom astropy.io import ascii as asc\nfrom astropy.io import fits\n\n#Pip\nimport extinction\nimport pymysql\n#Local\nfrom .define_filters import define_filters, get_cenwave\nfrom . import connect_to_sndavis, connect_to_supernova\nfrom . import spectroscopy as spec\n\n\nclass LightCurve(object):\n    def __init__(self, name, ra, dec, type=None, dist_mod=None, dist_mod_err=None, \n                       ebv_mw=None, ebv_mw_err=None, ebv_host=None, ebv_host_err=None, \n                       jdexpl=None, jdexplerr=None):\n        self.name=name\n        self.ra = result['ra0']\n        self.dec = result['dec0']\n        self.type = result['sntype'] #TODO - update this to look at the type table and make a human readable type\n        self.dist_mod = result['mu']\n        self.dist_mod_err = result['muerr']\n        self.ebv_mw = result['ebvg']\n        self.ebv_mw_err = result['ebvgerr']\n        self.ebv_host = result['ebvi'] \n        self.ebv_host_err = result['ebvierr']\n        self.jdexpl = result['jdexpl']\n        self.jdexpl_err = result['jdexplerr']\n        self.phase = defaultdict(list)\n        self.jd = defaultdict(list)\n        self.apparent_mag = defaultdict(list)\n        self.apparent_mag_err = defaultdict(list)\n        self.abs_mag = defaultdict(list)\n        self.abs_mag_err = defaultdict(list)\n        self.A_host = defaultdict(list)\n        self.A_err_host = defaultdict(list)\n        self.A_mw = defaultdict(list)\n        self.A_err_mw = defaultdict(list)\n        \n    def add_photometry(filter, jd, phot, phot_err):\n        self.jd[filter] = jd\n        self.apparent_mag[filter] = phot\n        self.apparent_mag_err[filter] = phot_err\n        if self.jdexpl:\n            self.phase[filter] = self.jd[filter] -self.jdexpl\n\ndef calc_abs_mag(app_mag, dist_mod, A_mw, A_host=0, dist_mod_err=0, app_mag_err=0, A_err_mw=0, A_err_host=0):\n    '''\n    Calculate the absolute magnitude in a given filter given the apparent magnitude, distance modulus, and extinction\n    app_mag: arr or float\n        array of apparent magnitudes\n    dist_mod: float\n        distance modulus\n    A_mw: float\n        Magnitudes of extinction in filter due to the Milky Way\n    A_host: float\n        Magnitudes of extinction in filter due to host; default=0\n    dist_mod_err: float\n        error in the distance modulus; default=0\n    app_mag_err: arr or float\n        array of error values for apparent magnitude (should be same size as app_mag); default=0\n    A_err_mw: float\n        error on A_mw (in magnitudes); default=0\n    A_err_host: float\n        err on A_host (in magnitudes); default=0\n    '''\n    abs_mag = app_mag - dist_mod - A_mw - A_host\n    abs_mag_err = np.sqrt(app_mag_err**2 + dist_mod_err**2 + A_err_mw**2 + A_err_host**2)\n    return abs_mag, abs_mag_err\n\nclass LightCurve2(object):\n    '''\n    Retrieve information from sndavis database\n    \n    Absolute magnitudes are corrected for extinction, apparent magnitude is not\n    '''\n    def __init__(self, name):\n        self.name=name\n        self.db, self.cursor = connect_to_sndavis.get_cursor()\n        self.id = self.get_sn_id()\n        if self.id is not None:\n            self.cursor.execute('SELECT * FROM idsupernovae WHERE id = {}'.format(self.id))\n            result = self.cursor.fetchone()\n            self.ra = result['ra0']\n            self.dec = result['dec0']\n            self.type = result['sntype'] #TODO - update this to look at the type table and make a human readable type\n            self.dist_mod = result['mu']\n            self.dist_mod_err = result['muerr']\n            self.ebv_mw = result['ebvg']\n            self.ebv_mw_err = result['ebvgerr']\n            if result['ebvi'] is None:\n                self.ebv_host = 0\n                self.ebv_host_err = 0\n                print('WARNING: host extinciton is None, setting to 0')\n            else:\n                self.ebv_host = result['ebvi'] \n                self.ebv_host_err = result['ebvierr']\n            self.quality = result['quality']\n            self.jdexpl = result['jdexpl']\n            self.jdexpl_err = result['jdexplerr']\n            self.jd = {}\n            self.apparent_mag = {}\n            self.apparent_mag_err = {}\n            self.phase = {}\n            self.abs_mag = {}\n            self.abs_mag_err = {}\n            self.slopes = {'s1':{}, 's2':{}, 's50':{}, 'tail':{}, \n                            's1_range':{}, 's2_range':{}, 's50_range':{}, 'tail_range':{},\n                            's1_err':{}, 's2_err':{}, 's50_err':{}, 'tail_err':{}}\n            self.A_host = {}\n            self.A_err_host = {}\n            self.A_mw = {}\n            self.A_err_mw = {}\n            self.jd_limit = {}\n            self.phase_limit = {}\n            self.apparent_mag_limit = {}\n            self.apparent_mag_err_limit = {}\n            self.abs_mag_limit = {}\n            self.abs_mag_err_limit = {}\n            self.telescope = {}\n            self.telescope_limit = {}\n            self.project = {}\n            self.project_limit = {}\n        else:\n            print('SN {} not found in database'.format(self.name))\n            #TODO add an absolute magnitude error\n             \n    def get_sn_id(self):\n        self.cursor.execute('SELECT targetid FROM supernovanames WHERE name = {}'.format('\"{}\"'.format(self.name)))\n        result = self.cursor.fetchone()\n        if result is None:\n            return None\n        return result['targetid']\n \n    def get_photometry(self, band='all'):\n        '''\n        Get apparent magnitude of a specific band\n        '''\n        filter_dict =  define_filters()\n        if band == 'all':\n            self.cursor.execute(\"SELECT DISTINCT BINARY(filter) FROM photometry WHERE targetid={}\".format(self.id))\n            results = self.cursor.fetchall()\n            bands = [iband['BINARY(filter)'].decode('utf-8') for iband in results]\n\n        elif len(band)==1 or isinstance(band, str): #Single filter\n            bands = [band]\n        else: #multiple filters\n            bands = band\n        for ifilter in bands:   \n            if ifilter in filter_dict.keys():\n                A_host_band, A_err_host_band = spec.calc_extinction(self.ebv_host, ifilter)\n                A_mw_band, A_err_mw_band = spec.calc_extinction(self.ebv_mw, ifilter)\n            else:\n                print('Could not calculate extinction for {} because not in filter dictionary'.format(ifilter))\n                A_host_band = 0\n                A_err_host_band = 0\n                A_mw_band = 0\n                A_err_mw_band = 0\n            #self.cursor.execute(\"SELECT jd, mag, magerr, datatype, configuration  FROM photometry JOIN photometrysource on photometry.source=photometrysource.source WHERE targetid={} AND filter=BINARY('{}')\".format(self.id, ifilter))\n            self.cursor.execute(\"SELECT jd, mag, magerr, datatype, source FROM photometry WHERE targetid={} AND filter=BINARY('{}')\".format(self.id, ifilter))\n            results = self.cursor.fetchall()\n            jd = []\n            mag = []\n            mag_err = []\n            telescope = []\n            project=[]\n            jd_limit = []\n            mag_limit = []\n            mag_err_limit = []\n            telescope_limit = []\n            project_limit = []\n            for irow in results:\n                if irow['magerr'] is None:\n                    irow['magerr'] = 0\n                if irow['datatype'] < 0: #photometry represents a limit\n                    jd_limit.append(float(irow['jd']))\n                    mag_limit.append(float(irow['mag']))\n                    mag_err_limit.append(float(irow['magerr']))\n                    #telescope_limit.append(irow['configuration'])\n                    #telescope_limit.append(irow['source'])\n                    #if irow['configuration'].startswith('1m'):\n                    #    project_limit.append('LCO')\n                    #elif irow['configuration'] == 'Meckering' or irow['configuration'] == 'Prompt5':\n                    #    project_limit.append('DLT40')\n                    #else:\n                    #    project_limit.append(None)\n                    telescope_limit.append(irow['source'])\n                    if irow['source'] in [5209, 5109, 5009, 4809, 4909, 4709, 4609, 4509, 140, 141, 142, 165, 166, 167]:\n                        project_limit.append('LCO')\n                    elif irow['source'] in [5300, 5400]:\n                        project_limit.append('DLT40')\n                    else:\n                        project_limit.append(None)\n                else:\n                    jd.append(float(irow['jd']))\n                    mag.append(float(irow['mag']))\n                    mag_err.append(float(irow['magerr']))\n                    # telescope.append(irow['configuration'])\n                    # if irow['configuration'].startswith('1m'):\n                    #     project.append('LCO')\n                    # elif irow['configuration'] == 'Meckering' or irow['configuration'] == 'Prompt5':\n                    #     project.append('DLT40')\n                    # else:\n                    #     project.append(None)\n                    telescope.append(irow['source'])\n                    if irow['source'] in [5209, 5109, 5009, 4809, 4909, 4709, 4609, 4509, 140, 141, 142, 165, 166, 167]:\n                        project.append('LCO')\n                    elif irow['source'] in [5300, 5400]:\n                        project.append('DLT40')\n                    else:\n                        project.append(None)\n            self.jd[ifilter] = np.array(jd)\n            self.apparent_mag[ifilter] = np.array(mag)\n            self.apparent_mag_err[ifilter] = np.array(mag_err)\n            if self.jdexpl is not None:\n                self.phase[ifilter] = self.jd[ifilter] - self.jdexpl\n            else:\n                print('WARNING: No explosion epoch in database, phase is not calculated')\n            self.A_host[ifilter] = A_host_band\n            self.A_err_host[ifilter] = A_err_host_band\n            self.A_mw[ifilter] = A_mw_band\n            self.A_err_mw[ifilter] = A_err_mw_band\n            self.jd_limit[ifilter] = np.array(jd_limit)\n            self.apparent_mag_limit[ifilter] = np.array(mag_limit)\n            self.apparent_mag_err_limit[ifilter] = np.array(mag_err_limit)\n            if self.jdexpl is not None:\n                self.phase_limit[ifilter] = self.jd_limit[ifilter] - self.jdexpl\n            else:\n                print('WARNING: No explosion epoch in database, phase is not calculated')\n            self.telescope[ifilter] = np.array(telescope)\n            self.telescope_limit[ifilter] = np.array(telescope_limit)\n            self.project[ifilter] = np.array(project)\n            self.project_limit[ifilter] = np.array(project_limit)\n            \n\n            \n    def get_abs_mag(self, band='all'):\n        '''\n        Calcualte absolute magnitude\n        '''\n        print('Calculating Absolute Magntidue with Extinction')\n        if band == 'all':\n            bands = self.apparent_mag.keys()\n        elif len(band)==1:\n            bands = [band]\n        else:\n            bands = band\n        if self.dist_mod_err is None:\n            self.dist_mod_err = 0\n        for iband in bands:\n            if self.ebv_host is None:\n                self.abs_mag[iband], self.abs_mag_err[iband] = calc_abs_mag(self.apparent_mag[iband], \n                                                   self.dist_mod, \n                                                   self.A_mw[iband], \n                                                   app_mag_err=self.apparent_mag_err[iband], \n                                                   dist_mod_err=self.dist_mod_err)\n                self.abs_mag_limit[iband], self.abs_mag_err_limit[iband] = calc_abs_mag(self.apparent_mag_limit[iband], \n                                                   self.dist_mod, \n                                                   self.A_mw[iband], \n                                                   app_mag_err=self.apparent_mag_err_limit[iband], \n                                                   dist_mod_err=self.dist_mod_err)\n            else:\n                self.abs_mag[iband], self.abs_mag_err[iband] = calc_abs_mag(self.apparent_mag[iband], \n                                                                            self.dist_mod, \n                                                                            self.A_mw[iband], \n                                                                            A_host=self.A_host[iband],\n                                                                            app_mag_err=self.apparent_mag_err[iband], \n                                                                            dist_mod_err=self.dist_mod_err,\n                                                                            A_err_mw=self.A_err_mw[iband],\n                                                                            A_err_host=self.A_err_host[iband])\n                self.abs_mag_limit[iband], self.abs_mag_err_limit[iband] = calc_abs_mag(self.apparent_mag_limit[iband], \n                                                                            self.dist_mod, \n                                                                            self.A_mw[iband], \n                                                                            A_host=self.A_host[iband],\n                                                                            app_mag_err=self.apparent_mag_err_limit[iband], \n                                                                            dist_mod_err=self.dist_mod_err,\n                                                                            A_err_mw=self.A_err_mw[iband],\n                                                                            A_err_host=self.A_err_host[iband])\n    \n    def get_slope(self,slope_type, band='V'):\n        '''\n        '''\n        self.cursor.execute('SELECT * FROM snslope WHERE  targetid={} AND \\\n                                                         slopetype=\"{}\" AND \\\n                                                         filter=BINARY(\"{}\")'.format(self.id, slope_type, band))\n        result = self.cursor.fetchone()\n        if result is not None:\n            self.slopes['{}'.format(slope_type)][band]       = result['slope']\n            self.slopes['{}_err'.format(slope_type)][band]   = result['slopeerr']\n            self.slopes['{}_range'.format(slope_type)][band] = (result['tstart'], result['tstop'])\n        else:\n            self.slopes['{}'.format(slope_type)][band]       = None\n            self.slopes['{}_err'.format(slope_type)][band]   = None\n            self.slopes['{}_range'.format(slope_type)][band] = [None, None]\n\n########################################\n\nclass LightCurveLCO(object):\n    '''\n    Retrieve information from LCO supernova database\n    '''\n    def __init__(self, name, **kwargs):\n        if 'config_dir' not in kwargs.keys():\n            kwargs['config_dir'] = os.environ['LCOSNDIR']\n        if 'config_filename' not in kwargs.keys():\n            kwargs['config_filename'] = 'configure'\n        self.name=name\n        self.db, self.cursor = connect_to_supernova.get_cursor(**kwargs)\n        self.id = self.get_sn_id()\n        if self.id is not None:\n            self.cursor.execute('SELECT * FROM targets WHERE id = {}'.format(self.id))\n            result = self.cursor.fetchone()\n            self.ra = result['ra0']\n            self.dec = result['dec0']\n            self.type = result['classification'] #TODO - update this to look at the type table and make a human readable type\n            self.z = result['redshift']\n            #These are set by the get_photometry method\n            self.quality = {}\n            self.jd = {}\n            self.apparent_mag = {}\n            self.apparent_mag_err = {}\n            self.telescope = {}\n\n    def get_sn_id(self):\n        num_results = self.cursor.execute(\"SELECT DISTINCT targetid FROM targetnames WHERE name LIKE '%{}%'\".format(self.name))\n        result = self.cursor.fetchall()\n        if num_results == 0:\n            return None\n        elif num_results>1:\n            warnings.warn('Multiple targetids match your query. Please enter the targetid you would like to select')\n            for iresult in result:\n                target = self.cursor.execute(\"SELECT name FROM targetnames WHERE targetid = {}\".format(iresult['targetid']))\n                target_results = target.fetchall()\n                print('targetid: {}'.format(iresult['targetid']))\n                for itarget_result in target_results:\n                    print(itarget_result['name'])\n            targetid = input('Enter target id: ')\n        else:\n            targetid = result[0]['targetid']\n        return targetid\n \n    def get_photometry(self, band='all'):\n        '''\n        Get apparent magnitude of a specific band\n        '''\n        filter_dict =  define_filters()\n        if band == 'all':\n            self.cursor.execute(\"SELECT DISTINCT BINARY(filter) FROM photlco WHERE targetid={}\".format(self.id))\n            results = self.cursor.fetchall()\n            bands = [iband['BINARY(filter)'].decode('utf-8') for iband in results]\n\n        elif len(band)==1 or isinstance(band, str): #Single filter\n            bands = [band]\n        else: #multiple filters\n            bands = band\n        for ifilter in bands:   \n            #self.cursor.execute(\"SELECT jd, mag, magerr, datatype, configuration  FROM photometry JOIN photometrysource on photometry.source=photometrysource.source WHERE targetid={} AND filter=BINARY('{}')\".format(self.id, ifilter))\n            sql_str = \"SELECT mjd, mag, dmag, telescope, quality FROM photlco WHERE\"\\\n                                + \" wcs != 9999 AND (psf != 'X' AND psf != 9999) AND (zcat != 'X' OR abscat !='X') AND mag != 9999\"\\\n                                + \" AND targetid={} AND filter=BINARY('{}')\".format(self.id, ifilter)\n            self.cursor.execute(sql_str)\n            results = self.cursor.fetchall()\n            jd = []\n            mag = []\n            mag_err = []\n            quality = []\n            telescope = []\n            for irow in results:\n                if irow['dmag'] is None:\n                    irow['dmag'] = 0\n                jd.append(Time(float(irow['mjd']), format='mjd').jd)\n                mag.append(float(irow['mag']))\n                mag_err.append(float(irow['dmag']))\n                quality.append(int(irow['quality']))\n                telescope.append(irow['telescope'])\n            self.jd[ifilter] = np.array(jd)\n            self.apparent_mag[ifilter] = np.array(mag)\n            self.apparent_mag_err[ifilter] = np.array(mag_err)\n            self.quality[ifilter] = np.array(quality)\n            self.telescope[ifilter] = np.array(telescope)\n################\n\ndef get_closest_photometry(date_obs, jd, phot_mag):\n    '''\n    Find the closest photometric observations to a given date\n    \n    Inputs:\n    ----------\n        date_obs: Time object\n            astropy Time object of the observervation date that you want to find the closest observations to\n        jd: list\n            list of photometric observations in JD\n        phot_mag: list\n            list of magnitudes corresponding to the jd list for a single filter\n        \n    Returns:\n    -----------\n        closest_mag: float\n            the closest magnitude to the date_obs given\n        date_sep: float\n            the difference in days between the observation and the closest photometric point\n    '''\n    date_indx = np.argmin(np.abs(jd - date_obs.jd))\n    closest_mag = phot_mag[date_indx]\n    date_sep = (jd - date_obs.jd)[date_indx]\n    return closest_mag, date_sep\n\ndef get_interpolated_photometry(date_obs, jd, phot_mag):\n    '''\n    Interpolate between photometric points in a given band to get the value at a single date\n        Inputs:\n    ----------\n        date_obs: Time object\n            astropy Time object of the observervation date that you want to find the closest observations to\n        jd: list\n            list of photometric observations in JD\n        phot_mag: list\n            list of magnitudes corresponding to the jd list for a single filter\n        \n    Returns:\n    -----------\n        interp_mag: float\n            the magnitude interpolated to the date_obs given\n        date_sep: tup\n            the difference in days between the observation and the two points used in the interpolation\n    '''\n\n    before_indx = jd < date_obs.jd\n    after_indx = jd >= date_obs.jd\n    if (before_indx==False).all():\n        before_sep = None\n    else:\n        before_sep = Time(jd[before_indx][-1], format='jd') - date_obs\n    if (after_indx == False).all():\n        after_sep = None\n    else:\n        after_sep =  Time(jd[after_indx][0],   format='jd') - date_obs\n    if (before_sep is not None) and (after_sep is not None):\n        interp_mag = np.interp(date_obs.jd, jd, phot_mag)\n    else:\n        interp_mag = None\n    return interp_mag, (before_sep, after_sep)\n    \ndef convert_mag_to_flux(phot_mag, ifilter):\n    '''\n    Converts magnitude units to flux units (ergs/cm^2/s/A)\n    \n    Inputs:\n    --------\n    phot_mag: list or array\n        list or array of magnitudes\n    ifilter: str\n        filter that phot_mag observations were taken with\n        \n    Returns:\n    --------\n    flux : array\n        list of flux values\n    '''\n    bandpar_dict = define_filters()\n    flux = 10**(np.array(phot_mag)/-2.5)*bandpar_dict[ifilter][4]\n    return flux\n    \ndef get_cenwave(ifilter):\n    '''\n    return the central wavelength of a given filter\n    \n    Inputs:\n    -------\n    ifilter: str\n        the name of a filter (must be present in define_filters)\n    \n    Returns:\n    --------\n    cenwave: float\n        central wavelength of filter\n    '''\n    bandpar_dict = define_filters()\n    cenwave = bandpar_dict[ifilter][2]\n    return cenwave\n\ndef scale_spectra_quba(snname, filename, filter_dir=None, date_kw='date-obs', max_sep=7, \n                        header_date=False, sndavis=True, lightcurve=None, verbose=False):\n    '''\n    You must be connected to dark\n    filter_dir should be /Users/bostroem/Dropbox/DLT40_all/script/scalespectra/filters/\n    if header_date is True, then date_kw contains the keyword to read from the header.\n    if header_date is False, then the date_kw should be treated as the date of the observation\n    \n    Inputs:\n    ---------\n    snname: str\n        name of supernova - will be used to find in SNDAVIS database is sndavis is True\n    filename: str\n        name of spectrum file. \n    filter_dir: str\n        location of information filter throughput\n    date_kw: str\n        if header_date is True: name of keyword in fits file to use to find date\n        if header_date is False: date of observation\n    max_set: float\n        number of days that can separate photometry point and date of spectrum\n    header_date: bool\n        controls whether spectrum date is read from header\n    sndavis: bool\n        if True: use SNDAVIS database to get light curve\n        if False: pass a light curve into the light curve keyword\n    lightcurve: LightCurve object\n        an object that has a jd attribute and an app_mag attribute that are dictionaries with filters as keys\n    \n    \n    \n    '''\n    import qubascalespectra\n    if lightcurve is None:\n        lightcurve = LightCurve2(snname)\n        lightcurve.get_photometry()\n    if header_date is True:\n        date_obs = Time(fits.getval(filename, date_kw, 0))\n    else:\n        date_obs = Time(date_kw)\n    spec_phase = (date_obs - Time(lightcurve.jdexpl, format='jd')).value\n    band = ''\n    mphot = []\n    for ifilter in lightcurve.jd.keys():\n        if ifilter not in ['us', 'vs', 'bs', 'uw1', 'uw2', 'um1', 'um2', 'UVW1', 'UVW2', 'UVM1', 'UVM2']: #avoid swift filters\n            cenwave = get_cenwave(ifilter)\n            if (cenwave > 3500):\n                mag, date_sep = get_interpolated_photometry(date_obs, lightcurve.jd[ifilter], lightcurve.apparent_mag[ifilter])\n                if mag is not None:\n                    print('using {}={} interpolated to {} from {} and {}'.format(ifilter, mag, date_obs.iso,\n                                                                               (date_sep[0]+date_obs).iso,\n                                                                               (date_sep[1]+date_obs).iso))\n                    if ifilter.endswith('p'): #strip off p for LCO filters since qubascalespectra assumes filters are single character\n                        band = band+ifilter[0]\n                    else:\n                        band=band+ifilter\n                    mphot.append(mag)\n                else:\n                    if date_sep[0] is None:\n                        print('No data for {} before {}'.format(ifilter, date_obs))\n                    if date_sep[1] is None:\n                        print('No data for {} after {}'.format(ifilter, date_obs))\n    if len(mphot) > 0:\n        if verbose:\n            print('bands: {}, photometry: {}'.format(band, mphot))\n        qubascalespectra.scale_spectrum(filename, band, mphot, filter_dir)\n        shutil.move('log.txt', filename.split('.')[0]+'.log')\n        with open(filename.split('.')[0]+'.log', 'a') as ofile:\n            ofile.write(band+'\\n')\n            mphot_str = [str(iphot) for iphot in mphot]\n            ofile.write(','.join(mphot_str)+'\\n')\n    else:\n        print('WARNING: no photometry within {} days of observation date ({}) ({})'.format(max_sep, date_obs, filename))\n    \n        \n            \n    \n        \n", "meta": {"hexsha": "26d7d3a13db0205c3515bda3180148802e2126d9", "size": 25681, "ext": "py", "lang": "Python", "max_stars_repo_path": "utilities_az/supernova.py", "max_stars_repo_name": "abostroem/utilities", "max_stars_repo_head_hexsha": "d43df81910116b0cf50b74619fc88c613d9f9434", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utilities_az/supernova.py", "max_issues_repo_name": "abostroem/utilities", "max_issues_repo_head_hexsha": "d43df81910116b0cf50b74619fc88c613d9f9434", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utilities_az/supernova.py", "max_forks_repo_name": "abostroem/utilities", "max_forks_repo_head_hexsha": "d43df81910116b0cf50b74619fc88c613d9f9434", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.0543859649, "max_line_length": 234, "alphanum_fraction": 0.5434367821, "include": true, "reason": "import numpy,from astropy", "num_tokens": 5667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.17160627419890903}}
{"text": "\"\"\" Parse q-chem log files and created displaced structures\n    using normal modes\n\"\"\"\n\n\nimport numpy as np\nimport glob\nimport sys\nimport cclib\nfrom cclib.parser import ccopen\n\nNAME = {\n    1:  'H'  ,\n    2:  'He' ,\n    3:  'Li' ,\n    4:  'Be' ,\n    5:  'B'  ,\n    6:  'C'  ,\n    7:  'N'  ,\n    8:  'O'  ,\n    9:  'F'  ,\n   10:  'Ne' ,\n   11:  'Na' ,\n   12:  'Mg' ,\n   13:  'Al' ,\n   14:  'Si' ,\n   15:  'P'  ,\n   16:  'S'  ,\n   17:  'Cl' ,\n   18:  'Ar' ,\n   19:  'K'  ,\n   20:  'Ca' ,\n   21:  'Sc' ,\n   22:  'Ti' ,\n   23:  'V'  ,\n   24:  'Cr' ,\n   25:  'Mn' ,\n   26:  'Fe' ,\n   27:  'Co' ,\n   28:  'Ni' ,\n   29:  'Cu' ,\n   30:  'Zn' ,\n   31:  'Ga' ,\n   32:  'Ge' ,\n   33:  'As' ,\n   34:  'Se' ,\n   35:  'Br' ,\n   36:  'Kr' ,\n   37:  'Rb' ,\n   38:  'Sr' ,\n   39:  'Y'  ,\n   40:  'Zr' ,\n   41:  'Nb' ,\n   42:  'Mo' ,\n   43:  'Tc' ,\n   44:  'Ru' ,\n   45:  'Rh' ,\n   46:  'Pd' ,\n   47:  'Ag' ,\n   48:  'Cd' ,\n   49:  'In' ,\n   50:  'Sn' ,\n   51:  'Sb' ,\n   52:  'Te' ,\n   53:  'I'  ,\n   54:  'Xe' ,\n   55:  'Cs' ,\n   56:  'Ba' ,\n   57:  'La' ,\n   58:  'Ce' ,\n   59:  'Pr' ,\n   60:  'Nd' ,\n   61:  'Pm' ,\n   62:  'Sm' ,\n   63:  'Eu' ,\n   64:  'Gd' ,\n   65:  'Tb' ,\n   66:  'Dy' ,\n   67:  'Ho' ,\n   68:  'Er' ,\n   69:  'Tm' ,\n   70:  'Yb' ,\n   71:  'Lu' ,\n   72:  'Hf' ,\n   73:  'Ta' ,\n   74:  'W'  ,\n   75:  'Re' ,\n   76:  'Os' ,\n   77:  'Ir' ,\n   78:  'Pt' ,\n   79:  'Au' ,\n   80:  'Hg' ,\n   81:  'Tl' ,\n   82:  'Pb' ,\n   83:  'Bi' ,\n   84:  'Po' ,\n   85:  'At' ,\n   86:  'Rn' ,\n   87:  'Fr' ,\n   88:  'Ra' ,\n   89:  'Ac' ,\n   90:  'Th' ,\n   91:  'Pa' ,\n   92:  'U'  ,\n   93:  'Np' ,\n   94:  'Pu' ,\n   95:  'Am' ,\n   96:  'Cm' ,\n   97:  'Bk' ,\n   98:  'Cf' ,\n   99:  'Es' ,\n  100:  'Fm' ,\n  101:  'Md' ,\n  102:  'No' ,\n  103:  'Lr' ,\n  104:  'Rf' ,\n  105:  'Db' ,\n  106:  'Sg' ,\n  107:  'Bh' ,\n  108:  'Hs' ,\n  109:  'Mt' ,\n  110:  'Ds' ,\n  111:  'Rg' ,\n  112:  'Cn' ,\n  114:  'Uuq',\n  116:  'Uuh'}\n\n\ndef create_displaced_structures():\n    \"\"\" Creates 10 displaced xyz files for T = 300, 600, 1200\n        by normal mode sampling.\n    \"\"\"\n    log_files = glob.glob(\"./log_files/**/*.log\", recursive=True)\n    output_folder = \"./xyz\"\n    # Makes flat modes less likely to explode molecule\n    force_min = 0.2\n    for i, log_file in enumerate(log_files):\n        if i < 43000:\n            continue\n        if i % 500 == 0:\n            print(f\"{i} of {len(log_files)} processed\")\n        mylogfile = ccopen(log_file)\n        data = mylogfile.parse()\n        force = get_force_constants(log_file)\n        coords = data.atomcoords[-1]\n        atoms = [NAME[i] for i in data.atomnos]\n        modes = data.vibdisps\n        # Only keep modes from last job\n        modes = modes[-force.size:]\n        normalized_modes = modes / np.linalg.norm(modes, axis=(1,2))[:,None,None]\n        write_xyz(f\"{output_folder}/{i}_0.xyz\", coords, atoms)\n        counter = 0\n        for T in 300, 600, 1200:\n            for n in range(10):\n                dcoords = coords[:]\n                counter += 1\n                c = np.random.uniform(0, 1, size=len(force))\n                c /= np.sum(c)\n                r_scale = np.random.uniform(0, 1)\n                c *= r_scale\n                for j, mode in enumerate(normalized_modes):\n                    sign = np.random.choice([-1.0, 1.0])\n                    frc = max(force_min, force[j])\n                    r = sign * np.sqrt(3 * c[j] * len(atoms) * 1.380e-5 * T / frc)\n                    dcoords += mode * r\n                write_xyz(f\"{output_folder}/{i}_{counter}.xyz\", dcoords, atoms)\n\ndef write_xyz(filename, coords, atoms):\n    \"\"\" Writes xyz files\n    \"\"\"\n    with open(filename, \"w\") as f:\n        f.write(f\"{len(atoms)}\\n\")\n        for j, atom in enumerate(atoms):\n            f.write(\"\\n%2s %20.12f %20.12f %20.12f\" % \\\n                (atom, coords[j,0], coords[j,1], coords[j,2]))\n#\n# atomcoords, atommasses, charge, mult, vibdisps, vibfreqs\n\ndef get_force_constants(filename):\n    \"\"\" Reads the force constants of the last job in\n        the Q-Chem output file\n    \"\"\"\n    force_constants = []\n    last_job_flag = False\n    with open(filename) as f:\n        for line in f:\n            if line.startswith(\"Running Job\"):\n                tokens = line.split()\n                current_job = tokens[2]\n                last_job = tokens[4]\n                if current_job == last_job:\n                    last_job_flag = True\n            if last_job_flag and line.startswith(\" Force Cnst:\"):\n                tokens = line.split()\n                force_constants.extend(tokens[2:])\n            else:\n                continue\n    #try:\n    return np.asarray(force_constants, dtype=float)\n    #except:\n    #    print(filename)\n    #    print(force_constants)\n    #    quit()\n\nif __name__ == \"__main__\":\n    create_displaced_structures()\n", "meta": {"hexsha": "533557665e247297d4ce4bc089f1199ace83368d", "size": 4770, "ext": "py", "lang": "Python", "max_stars_repo_path": "normal_mode_sampling.py", "max_stars_repo_name": "larsbratholm/reactive_ff", "max_stars_repo_head_hexsha": "717dbc2e3a028f134a3ad5dc8e4568fd4ec4702f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "normal_mode_sampling.py", "max_issues_repo_name": "larsbratholm/reactive_ff", "max_issues_repo_head_hexsha": "717dbc2e3a028f134a3ad5dc8e4568fd4ec4702f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "normal_mode_sampling.py", "max_forks_repo_name": "larsbratholm/reactive_ff", "max_forks_repo_head_hexsha": "717dbc2e3a028f134a3ad5dc8e4568fd4ec4702f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0434782609, "max_line_length": 82, "alphanum_fraction": 0.4467505241, "include": true, "reason": "import numpy", "num_tokens": 1836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.17160627419890903}}
{"text": "# Copyright 2014-2020 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Oliver J. Backhouse <olbackhouse@gmail.com>\n#         George H. Booth <george.booth@kcl.ac.uk>\n#\n\n'''\nAuxiliary second-order Green's function perturbation theory\nwith density fitting\n'''\n\nimport numpy as np\nimport ctypes\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf import __config__\nfrom pyscf import ao2mo, df\nfrom pyscf.agf2 import ragf2, mpi_helper, _agf2\nfrom pyscf.agf2 import aux_space as aux\n\nBLKMIN = getattr(__config__, 'agf2_blkmin', 100)\n\n\ndef build_se_part(agf2, eri, gf_occ, gf_vir, os_factor=1.0, ss_factor=1.0):\n    ''' Builds either the auxiliaries of the occupied self-energy,\n        or virtual if :attr:`gf_occ` and :attr:`gf_vir` are swapped.\n\n    Args:\n        eri : _ChemistsERIs\n            Electronic repulsion integrals\n        gf_occ : GreensFunction\n            Occupied Green's function\n        gf_vir : GreensFunction\n            Virtual Green's function\n\n    Kwargs:\n        os_factor : float\n            Opposite-spin factor for spin-component-scaled (SCS)\n            calculations. Default 1.0\n        ss_factor : float\n            Same-spin factor for spin-component-scaled (SCS)\n            calculations. Default 1.0\n\n    Returns:\n        :class:`SelfEnergy`\n    '''\n\n    cput0 = (logger.process_clock(), logger.perf_counter())\n    log = logger.Logger(agf2.stdout, agf2.verbose)\n\n    assert type(gf_occ) is aux.GreensFunction\n    assert type(gf_vir) is aux.GreensFunction\n\n    nmo = eri.nmo\n    nocc, nvir = gf_occ.naux, gf_vir.naux\n    naux = agf2.with_df.get_naoaux()\n    tol = agf2.weight_tol\n    facs = dict(os_factor=os_factor, ss_factor=ss_factor)\n\n    ei, ci = gf_occ.energy, gf_occ.coupling\n    ea, ca = gf_vir.energy, gf_vir.coupling\n\n    qxi, qja = _make_qmo_eris_incore(agf2, eri, (ci, ci, ca))\n\n    himem_required = naux*(nvir+nmo) + (nocc*nvir)*(2*nmo+1) + (2*nmo**2)\n    himem_required *= 8e-6\n    himem_required *= lib.num_threads()\n\n    if ((himem_required*1.05 + lib.current_memory()[0]) > agf2.max_memory\n            and agf2.allow_lowmem_build) or agf2.allow_lowmem_build == 'force':\n        log.debug('Thread-private memory overhead %.3f exceeds max_memory, using '\n                  'low-memory version.', himem_required)\n        vv, vev = _agf2.build_mats_dfragf2_lowmem(qxi, qja, ei, ea, **facs)\n    else:\n        vv, vev = _agf2.build_mats_dfragf2_incore(qxi, qja, ei, ea, **facs)\n\n    e, c = _agf2.cholesky_build(vv, vev)\n    se = aux.SelfEnergy(e, c, chempot=gf_occ.chempot)\n    se.remove_uncoupled(tol=tol)\n\n    if not (agf2.frozen is None or agf2.frozen == 0):\n        mask = ragf2.get_frozen_mask(agf2)\n        coupling = np.zeros((nmo, se.naux))\n        coupling[mask] = se.coupling\n        se = aux.SelfEnergy(se.energy, coupling, chempot=se.chempot)\n\n    log.timer('se part', *cput0)\n\n    return se\n\ndef get_jk(agf2, eri, rdm1, with_j=True, with_k=True):\n    ''' Get the J/K matrices.\n\n    Args:\n        eri : ndarray or H5 dataset\n            Electronic repulsion integrals (NOT as _ChemistsERIs). In\n            the case of no bra/ket symmetry, a tuple can be passed.\n        rdm1 : 2D array\n            Reduced density matrix\n\n    Kwargs:\n        with_j : bool\n            Whether to compute J. Default value is True\n        with_k : bool\n            Whether to compute K. Default value is True\n\n    Returns:\n        tuple of ndarrays corresponding to J and K, if either are\n        not requested then they are set to None.\n    '''\n\n    nmo = rdm1.shape[0]\n    npair = nmo*(nmo+1)//2\n    naux = agf2.with_df.get_naoaux()\n    vj = vk = None\n\n    if with_j:\n        rdm1_tril = lib.pack_tril(rdm1 + np.tril(rdm1, k=-1))\n        vj = np.zeros((npair,))\n\n    if with_k:\n        vk = np.zeros((nmo, nmo))\n\n    fdrv = ao2mo._ao2mo.libao2mo.AO2MOnr_e2_drv\n    fmmm = ao2mo._ao2mo.libao2mo.AO2MOmmm_bra_nr_s2\n    ftrans = ao2mo._ao2mo.libao2mo.AO2MOtranse2_nr_s2\n\n    if isinstance(eri, tuple):\n        bra, ket = eri\n    else:\n        bra = ket = eri\n\n    blksize = _agf2.get_blksize(agf2.max_memory, (npair, npair, 1, nmo**2, nmo**2))\n    blksize = min(nmo, max(BLKMIN, blksize))\n    logger.debug1(agf2, 'blksize (dfragf2.get_jk) = %d' % blksize)\n    buf = (np.empty((blksize, nmo, nmo)), np.empty((blksize, nmo, nmo)))\n\n    for p0, p1 in mpi_helper.prange(0, naux, blksize):\n        bra0 = bra[p0:p1]\n        ket0 = ket[p0:p1]\n        rho = np.dot(ket0, rdm1_tril)\n\n        if with_j:\n            vj += np.dot(rho, bra0)\n\n        if with_k:\n            buf1 = buf[0][:p1-p0]\n            fdrv(ftrans, fmmm,\n                 buf1.ctypes.data_as(ctypes.c_void_p),\n                 bra0.ctypes.data_as(ctypes.c_void_p),\n                 rdm1.ctypes.data_as(ctypes.c_void_p),\n                 ctypes.c_int(p1-p0), ctypes.c_int(nmo),\n                 (ctypes.c_int*4)(0, nmo, 0, nmo),\n                 lib.c_null_ptr(), ctypes.c_int(0))\n\n            buf2 = lib.unpack_tril(ket0, out=buf[1])\n            buf1 = buf1.reshape(-1, nmo)\n            buf2 = buf2.reshape(-1, nmo)\n\n            vk = lib.dot(buf1.T, buf2, c=vk, beta=1)\n\n\n    if with_j:\n        mpi_helper.barrier()\n        mpi_helper.allreduce_safe_inplace(vj)\n        mpi_helper.barrier()\n        vj = lib.unpack_tril(vj)\n\n    if with_k:\n        mpi_helper.barrier()\n        mpi_helper.allreduce_safe_inplace(vk)\n\n    return vj, vk\n\n\nclass DFRAGF2(ragf2.RAGF2):\n    ''' Restricted AGF2 with canonical HF reference with density fitting\n\n    Attributes:\n        verbose : int\n            Print level. Default value equals to :class:`Mole.verbose`\n        max_memory : float or int\n            Allowed memory in MB. Default value equals to :class:`Mole.max_memory`\n        incore_complete : bool\n            Avoid all I/O. Default is False.\n        allow_lowmem_build : bool or str\n            Allow the self-energy build to switch to a serially slower\n            code with lower thread-private memory overhead if needed. One\n            of True, False or 'force'. Default value is True.\n        conv_tol : float\n            Convergence threshold for AGF2 energy. Default value is 1e-7\n        conv_tol_rdm1 : float\n            Convergence threshold for first-order reduced density matrix.\n            Default value is 1e-8.\n        conv_tol_nelec : float\n            Convergence threshold for the number of electrons. Default\n            value is 1e-6.\n        max_cycle : int\n            Maximum number of AGF2 iterations. Default value is 50.\n        max_cycle_outer : int\n            Maximum number of outer Fock loop iterations. Default\n            value is 20.\n        max_cycle_inner : int\n            Maximum number of inner Fock loop iterations. Default\n            value is 50.\n        weight_tol : float\n            Threshold in spectral weight of auxiliaries to be considered\n            zero. Default 1e-11.\n        diis : bool or lib.diis.DIIS\n            Whether to use DIIS, can also be a lib.diis.DIIS object. Default\n            value is True.\n        diis_space : int\n            DIIS space size. Default value is 8.\n        diis_min_space : int\n            Minimum space of DIIS. Default value is 1.\n        fock_diis_space : int\n            DIIS space size for Fock loop iterations. Default value is 6.\n        fock_diis_min_space :\n            Minimum space of DIIS. Default value is 1.\n        os_factor : float\n            Opposite-spin factor for spin-component-scaled (SCS)\n            calculations. Default 1.0\n        ss_factor : float\n            Same-spin factor for spin-component-scaled (SCS)\n            calculations. Default 1.0\n        damping : float\n            Damping factor for the self-energy. Default value is 0.0\n\n    Saved results\n\n        e_corr : float\n            AGF2 correlation energy\n        e_tot : float\n            Total energy (HF + correlation)\n        e_1b : float\n            One-body part of :attr:`e_tot`\n        e_2b : float\n            Two-body part of :attr:`e_tot`\n        e_init : float\n            Initial correlation energy (truncated MP2)\n        converged : bool\n            Whether convergence was successful\n        se : SelfEnergy\n            Auxiliaries of the self-energy\n        gf : GreensFunction\n            Auxiliaries of the Green's function\n    '''\n\n    def __init__(self, mf, frozen=None, mo_energy=None, mo_coeff=None, mo_occ=None):\n        ragf2.RAGF2.__init__(self, mf, frozen=frozen, mo_energy=mo_energy,\n                             mo_coeff=mo_coeff, mo_occ=mo_occ)\n\n        if getattr(mf, 'with_df', None) is not None:\n            self.with_df = mf.with_df\n        else:\n            self.with_df = df.DF(mf.mol)\n            self.with_df.auxbasis = df.make_auxbasis(mf.mol, mp2fit=True)\n\n        self.allow_lowmem_build = True\n\n        self._keys.update(['_with_df', 'allow_lowmem_build'])\n\n    build_se_part = build_se_part\n    get_jk = get_jk\n\n    def ao2mo(self, mo_coeff=None):\n        ''' Get the density-fitted electronic repulsion integrals in\n            MO basis.\n        '''\n\n        eri = _make_mo_eris_incore(self, mo_coeff)\n\n        return eri\n\n    def reset(self, mol=None):\n        self.with_df.reset(mol)\n        return ragf2.RAGF2.reset(self, mol)\n\n    @property\n    def with_df(self):\n        return self._with_df\n    @with_df.setter\n    def with_df(self, val):\n        self._with_df = val\n        self._with_df.__class__ = DF\n\n\nclass DF(df.DF):\n    ''' Replaces the :class:`DF.prange` function with one which\n        natively supports MPI, if used.\n    '''\n    def prange(self, start=None, stop=None, step=None):\n        if start is None: start = 0\n        if stop is None: stop = self.get_naoaux()\n        if step is None: step = self.blockdim\n\n        for p0, p1 in mpi_helper.prange(start, stop, step):\n            yield p0, p1\n\n\nclass _ChemistsERIs(ragf2._ChemistsERIs):\n    ''' (pq|rs) as (pq|J)(J|rs)\n\n    MO tensors stored in tril form, we only need QMO tensors\n    in low-symmetry\n    '''\n    pass\n\n\ndef _make_mo_eris_incore(agf2, mo_coeff=None):\n    ''' Returns _ChemistsERIs\n    '''\n\n    cput0 = (logger.process_clock(), logger.perf_counter())\n    log = logger.Logger(agf2.stdout, agf2.verbose)\n\n    eris = _ChemistsERIs()\n    eris._common_init_(agf2, mo_coeff)\n    with_df = agf2.with_df\n    nmo = eris.fock.shape[0]\n    npair = nmo*(nmo+1)//2\n    naux = with_df.get_naoaux()\n\n    qxy = np.zeros((naux, npair))\n    mo = np.asarray(eris.mo_coeff, order='F')\n    sij = (0, nmo, 0, nmo)\n    sym = dict(aosym='s2', mosym='s2')\n\n    for p0, p1 in with_df.prange():\n        eri0 = with_df._cderi[p0:p1]\n        qxy[p0:p1] = ao2mo._ao2mo.nr_e2(eri0, mo, sij, out=qxy[p0:p1], **sym)\n\n    mpi_helper.barrier()\n    mpi_helper.allreduce_safe_inplace(qxy)\n\n    eris.eri = eris.qxy = qxy\n\n    log.timer('MO integral transformation', *cput0)\n\n    return eris\n\ndef _make_qmo_eris_incore(agf2, eri, coeffs):\n    ''' Returns tuple of ndarray\n    '''\n\n    cput0 = (logger.process_clock(), logger.perf_counter())\n    log = logger.Logger(agf2.stdout, agf2.verbose)\n\n    cx = np.eye(agf2.nmo)\n    if not (agf2.frozen is None or agf2.frozen == 0):\n        mask = ragf2.get_frozen_mask(agf2)\n        cx = cx[:,mask]\n\n    nmo = eri.fock.shape[0]\n    npair = nmo*(nmo+1)//2\n    with_df = agf2.with_df\n    naux = with_df.get_naoaux()\n    ci, cj, ca = coeffs\n\n    xisym, nxi, cxi, sxi = ao2mo.incore._conc_mos(cx, ci, compact=False)\n    jasym, nja, cja, sja = ao2mo.incore._conc_mos(cj, ca, compact=False)\n    sym = dict(aosym='s2', mosym='s1')\n\n    qxi = np.zeros((naux, nxi))\n    qja = np.zeros((naux, nja))\n    buf = np.zeros((with_df.blockdim, npair))\n\n    for p0, p1 in mpi_helper.prange(0, naux, with_df.blockdim):\n        naux0 = p1 - p0\n        buf0 = buf[:naux0]\n        buf0[:] = eri.eri[p0:p1]\n\n        qxi[p0:p1] = ao2mo._ao2mo.nr_e2(buf0, cxi, sxi, out=qxi[p0:p1], **sym)\n        qja[p0:p1] = ao2mo._ao2mo.nr_e2(buf0, cja, sja, out=qja[p0:p1], **sym)\n\n    qxi = qxi.reshape(naux, -1)\n    qja = qja.reshape(naux, -1)\n\n    mpi_helper.barrier()\n    mpi_helper.allreduce_safe_inplace(qxi)\n    mpi_helper.allreduce_safe_inplace(qja)\n\n    log.timer('QMO integral transformation', *cput0)\n\n    return (qxi, qja)\n\n\n\nif __name__ == '__main__':\n    from pyscf import gto, scf, mp\n\n    mol = gto.M(atom='O 0 0 0; H 0 0 1; H 0 1 0', basis='cc-pvdz', verbose=3)\n    rhf = scf.RHF(mol).density_fit()\n    rhf.conv_tol = 1e-11\n    rhf.run()\n\n    ragf2 = DFRAGF2(rhf)\n\n    ragf2.run()\n    ragf2.ipagf2(nroots=5)\n    ragf2.eaagf2(nroots=5)\n", "meta": {"hexsha": "042408a8d3feb8dd3acc877607c8f7eb86dacec2", "size": 12982, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/agf2/dfragf2.py", "max_stars_repo_name": "umamibeef/pyscf", "max_stars_repo_head_hexsha": "1263d54b02914caf4476a3ed9a2de5e0c848954c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 501, "max_stars_repo_stars_event_min_datetime": "2018-12-06T23:48:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:53:18.000Z", "max_issues_repo_path": "pyscf/agf2/dfragf2.py", "max_issues_repo_name": "umamibeef/pyscf", "max_issues_repo_head_hexsha": "1263d54b02914caf4476a3ed9a2de5e0c848954c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 710, "max_issues_repo_issues_event_min_datetime": "2018-11-26T22:04:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:53:12.000Z", "max_forks_repo_path": "pyscf/agf2/dfragf2.py", "max_forks_repo_name": "umamibeef/pyscf", "max_forks_repo_head_hexsha": "1263d54b02914caf4476a3ed9a2de5e0c848954c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 273, "max_forks_repo_forks_event_min_datetime": "2018-11-26T10:10:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:25:28.000Z", "avg_line_length": 31.3574879227, "max_line_length": 84, "alphanum_fraction": 0.6212448005, "include": true, "reason": "import numpy", "num_tokens": 3872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.3073580168652638, "lm_q1q2_score": 0.1716062732235979}}
{"text": "__all__ = ['fit_spectra']\n\nimport sys\nimport copy\nimport pathlib\nimport inspect\nfrom datetime import datetime\nimport multiprocessing as mp\nimport numpy as np\nimport eispac.core.fitting_functions as fit_fns\nfrom eispac.core.eiscube import EISCube\nfrom eispac.core.read_cube import read_cube\nfrom eispac.core.read_template import EISFitTemplate\nfrom eispac.core.eisfitresult import EISFitResult\nfrom eispac.core.eisfitresult import create_fit_dict\nfrom eispac.core.scale_guess import scale_guess\nfrom eispac.core.mpfit import mpfit\nfrom eispac.instr import calc_velocity\n\n# i'm sure that there is a better way to do this!\ncntr = mp.Value(\"i\", 0) # a counter\nnexp = mp.Value(\"i\", 0) # total exposures\n\ndef check_for_name_guard(debug=False):\n    \"\"\"Check to see if the top level script has a \"name guard\" that will\n    protect against multiprocessing spawning infinite child processes.\n    \"\"\"\n    name_guard = False\n    # Walk up the call stack and find the first program or script with\n    # __name__ == \"__main__\". This should be the top-level program.\n    if debug:\n        print('')\n        print('Checking call stack for a name guard...')\n    call_stack = inspect.stack()\n    for s in range(len(call_stack)):\n        frame = call_stack[s][0]\n        frame_filename = call_stack[s][1]\n        if debug:\n            print('Stack frame index:', s)\n            print('   filename = ', frame_filename)\n        if '__name__' in frame.f_locals:\n            if debug:\n                print('   __name__ = ', frame.f_locals['__name__'])\n                print('   pathlib.Path.is_file() = ',\n                      str(pathlib.Path(frame_filename).is_file()))\n            if frame.f_locals['__name__'] == '__main__':\n                if not frame_filename.endswith('.py'):\n                    # Probably running in a Python terminal or interactive shell\n                    name_guard = False\n                else:\n                    if pathlib.Path(frame_filename).is_file() == False:\n                        # Probably running in an entry point executable\n                        name_guard = True\n                        break\n                    # Examine the source code of __main__ script\n                    with open(frame_filename, 'r') as f_file:\n                        for line in f_file.readlines():\n                            sl = line.replace(' ','') # Remove whitespace\n                            sl = sl.replace('\"', \"'\") # Convert \" to '\n                            if sl.startswith(\"if__name__=='__main__':\"):\n                                name_guard = True\n                break\n\n    return name_guard\n\ndef fit_with_mpfit(wave_cube, inten_cube, errs_cube, template, parinfo,\n                   min_points=7,  chunk=1, data_units='unknown'):\n    \"\"\"Helper function for fit_spectra(). Fits one or more intensity spectra\n    using the mpfit module.\n    \"\"\"\n\n    with cntr.get_lock():\n        cntr.value += 1\n    #print(f' + working on exposure {cntr.value:03d}') #, end='\\r')\n    print(f' + working on exposure {chunk:03d}', end='\\r')\n\n    inten_size = inten_cube.shape\n    n_pxls = inten_size[0]\n    n_steps = inten_size[1]\n    n_wave = inten_size[2]\n    line_ids = template['line_ids']\n    if isinstance(line_ids, bytes):\n        line_ids = [line_ids.decode('utf-8')]\n\n    # Extract fit information from template\n    n_gauss = template['n_gauss']\n    n_poly = template['n_poly']\n    min_wave = template['data_x'][0]\n    max_wave = template['data_x'][-1]\n    oldguess = template['fit']\n\n    # Create fit dictionary, mask array, and parameter indices\n    fit_dict = create_fit_dict(n_pxls, n_steps, n_wave, n_gauss, n_poly,\n                               data_units=data_units)\n    fit_dict['line_ids'] = line_ids\n    fit_dict['wave_range'][0] = min_wave\n    fit_dict['wave_range'][1] = max_wave\n    mask_ij = np.ones(n_wave)\n    loc_peaks = np.arange(n_gauss)*3\n    loc_cen = np.arange(n_gauss)*3+1\n    loc_wid = np.arange(n_gauss)*3+2\n    loc_backs = np.arange(n_poly)+n_gauss*3\n\n    # loop over pixel positions and slit steps in the entire raster\n    for ii in range(n_pxls):\n        for jj in range(n_steps):\n\n            # Extract a single profile from the raster\n            wave_ij = wave_cube[ii,jj,::]\n            inten_ij = inten_cube[ii,jj,::]\n            errs_ij = errs_cube[ii,jj,::]\n\n            # Cut data to only \"good\" nonzero errs within the wavelength range\n            mask_ij[0:-1] = 1 # reset the mask (remember: 1 = True = masked val)\n            loc_good = np.where((errs_ij > 0) & (wave_ij >= min_wave)\n                                & (wave_ij <= max_wave))\n            num_good_data = len(loc_good[0])\n            if num_good_data > 0:\n                mask_ij[loc_good] = 0 # unmask good data\n\n            fit_dict['mask'][ii,jj,:] = mask_ij[:] # always save the mask\n\n            if num_good_data < min_points:\n                fit_dict['status'][ii,jj] = -1\n                continue\n            wave_ij = wave_ij[loc_good]\n            inten_ij = inten_ij[loc_good]\n            errs_ij = errs_ij[loc_good]\n\n            # Scale guess parameters to data (should speed up fitting some)\n            newguess = scale_guess(wave_ij, inten_ij, oldguess, n_gauss, n_poly)\n\n            # Plug in new guess values to parinfo\n            for i in range(len(newguess)):\n                parinfo[i]['value'] = newguess[i]\n\n            # Assemble dict of extra args to pass to mpfit\n            fa = {'x': wave_ij, 'y': inten_ij, 'error': errs_ij,\n                  'n_gauss': n_gauss, 'n_poly': n_poly}\n\n            # Fit the profile\n            out = mpfit(fit_fns.multigaussian_deviates, parinfo=parinfo,\n                        functkw=fa, xtol=1.0E-6, ftol=1.0E-6, gtol=1.0E-6,\n                        maxiter=2000, quiet=1)\n\n            # check convergence status for a valid result\n            if out.status > 0:\n                # compute line inten and errors directly (may need to revisit)\n                fpeaks = out.params[loc_peaks]\n                fwdths = out.params[loc_wid]\n                epeaks = out.perror[loc_peaks]\n                ewdths = out.perror[loc_wid]\n                l_inten = np.sqrt(2*np.pi)*fpeaks*fwdths\n                e_inten = np.zeros(n_gauss)\n                for n in range(n_gauss):\n                    if fpeaks[n] != 0 and fwdths[n] != 0:\n                        e_inten[n] = (l_inten[n]*np.sqrt((epeaks[n]/fpeaks[n])**2\n                                                         +(ewdths[n]/fwdths[n])**2))\n                    else:\n                        e_inten[n] = 0.0\n\n                # assemble fit structure\n                fit_dict['status'][ii,jj] = out.status\n                fit_dict['chi2'][ii,jj] = out.fnorm/out.dof\n                fit_dict['wavelength'][ii,jj,:] = wave_cube[ii,jj,:]\n                fit_dict['params'][ii,jj,:] = out.params\n                fit_dict['perror'][ii,jj,:] = out.perror\n                fit_dict['int'][ii,jj,:] = l_inten\n                fit_dict['err_int'][ii,jj,:] = e_inten\n            else:\n                print(' ! fit did not converge!')\n                fit_dict['status'][ii,jj] = out.status\n\n    return fit_dict\n\ndef fit_spectra(inten, template, parinfo=None, wave=None, errs=None, min_points=7,\n                ncpu='max', unsafe_mp=False, ignore_warnings=False,\n                skip_fitting=False, debug=False):\n    \"\"\"Fit one or more EIS line spectra using mpfit (with multiprocessing).\n\n    Parameters\n    ----------\n    inten : EISCube object, array_like, or filepath\n        One or more intensity profiles to be fit. The code will loop over the data\n        according to its dimensionality. 3D data is assumed to be a full EIS raster\n        (or a sub region), 2D data is assumed to be a single EIS slit, and 1D data\n        is assumed to be a single profile.\n    template : EISFitTemplate object, dict, or filepath\n        Either an EISFitTemplate, a 'template' dictionary, or the path to a\n        template file.\n    parinfo : list, optional\n        List of dictionaries with fit parameters formatted for use with mpfit.\n        Will supercede any parinfo lists loaded from an EISFitTemplate. Required\n        if the 'template' parameter is given as a dictionary.\n    wave : array_like, optional\n        Associated wavelength values for the spectra. Required if 'inten' is\n        given as an array and ignored otherwise.\n    errs : array_like, optional\n        Intensity error values for the spectra. Required if 'inten' is given as\n        an array and ignored otherwise.\n    min_points : int, optional\n        Minimum number of good quality data points (i.e. non-zero values & errs)\n        to be used in each fit. Spectra with fewer data points will be skipped.\n        Must be a number >= the total number of fit parameters. Default is 7.\n    ncpu : int, optional\n        Number of cpu processes to parallelize over. Must be less than or equal\n        to the total number of cores the system has. If set to 'max' or None, the\n        code will use the maximum number of cores available. Default is 'max'.\n        Important: due to the specifics of how the multiprocessing library works,\n        any statements that call fit_spectra() using ncpu > 1 MUST be wrapped in\n        a \"if __name__ == __main__:\" statement in the top-level program. If such\n        a \"name guard\" statement is not detected, this function will fall back to\n        using a single process.\n    unsafe_mp : bool, optional\n        If set to True, will use multiprocessing even if there is no name guard\n        no name guard (if ncpu > 0). Used by the console script \"eit_fit_files\".\n        Default is False (name guard enforced). Disabling the name guard runs the\n        risk of spawning infinite processes if run incorrectly. USE AT YOUR OWN\n        RISK!\n    ignore_warnings : bool, optional\n        If set to True, will silence the warning about a missing or disabled name\n        guard (we are serious at it, be careful). Default is False.\n    skip_fitting : bool, optional\n        If set to True, will skip the fitting altogether and just return an empty\n        EISFitResult instance. Used mainly for testing. Default is False.\n    debug : bool, optional\n        If set to True, will print some extra information useful for debugging\n        development versions of the code. Default is False.\n\n    Returns\n    -------\n    fit_res : EISFitResult class instance\n        An EISFitResult object containing the output fit parameters.\n    \"\"\"\n    # Validate template & parinfo and read / copy as needed\n    if isinstance(template, (str, pathlib.Path)):\n        template_obj = EISFitTemplate.read_template(template)\n        if template_obj is None:\n            return None\n        template_copy = copy.deepcopy(template_obj.template)\n        parinfo_copy = copy.deepcopy(template_obj.parinfo)\n        tmplt_filename = template_obj.filename_temp\n    elif isinstance(template, EISFitTemplate):\n        template_copy = copy.deepcopy(template.template)\n        parinfo_copy = copy.deepcopy(template.parinfo)\n        tmplt_filename = template.filename_temp\n    elif isinstance(template, dict):\n        template_copy = copy.deepcopy(template)\n        parinfo_copy = None\n        tmplt_filename = 'unknown'\n    else:\n        print('Please input either the path to a template file, an'\n             +' EISFitTemplate instance, or dictionary.', file=sys.stderr)\n        return None\n\n    if isinstance(parinfo, list):\n        # Direct user-input always supercedes automatically loaded data\n        parinfo_copy = copy.deepcopy(parinfo)\n    elif parinfo_copy is None:\n        print('Please input a parinfo list or a full EISFitTemplate.', file=sys.stderr)\n        return None\n\n    # If given an EISCube, extract data arrays and zero out masked values.\n    # Otherwise, make local copies and just zero out negative values\n    # TODO: Add more validation for the case of input arrays\n    if isinstance(inten, (str, pathlib.Path)):\n        central_wave = np.mean([template_copy['wmin'], template_copy['wmax']])\n        eis_cube = read_cube(inten, window=float(central_wave))\n        if eis_cube is None:\n            return None\n        wave_cube = eis_cube.wavelength.copy()\n        errs_cube = eis_cube.uncertainty.array.copy()\n        inten_cube = eis_cube.data.copy()\n        metadata = copy.deepcopy(eis_cube.meta)\n        data_units = eis_cube.unit.to_string()\n        data_radcal = copy.deepcopy(eis_cube.radcal)\n        loc_masked = np.where(eis_cube.mask == True)\n        inten_cube[loc_masked] = 0\n        errs_cube[loc_masked] = 0\n        del eis_cube\n    elif isinstance(inten, EISCube):\n        wave_cube = inten.wavelength.copy()\n        errs_cube = inten.uncertainty.array.copy()\n        inten_cube = inten.data.copy()\n        metadata = copy.deepcopy(inten.meta)\n        data_units = inten.unit.to_string()\n        data_radcal = copy.deepcopy(inten.radcal)\n        loc_masked = np.where(inten.mask == True)\n        inten_cube[loc_masked] = 0\n        errs_cube[loc_masked] = 0\n    elif isinstance(inten, np.ndarray):\n        if not isinstance(wave, np.ndarray):\n            print('Please input a wavelength array or a full EISCube.', file=sys.stderr)\n            return None\n        elif not isinstance(errs, np.ndarray):\n            print('Please input an error array or a full EISCube.', file=sys.stderr)\n            return None\n        wave_cube = wave.copy()\n        errs_cube = errs.copy()\n        inten_cube = inten.copy()\n        metadata = {'filename_data':'unknown', 'index':{}, 'pointing':{},\n                    'radcal':'unknown', 'wave':'unknown'}\n        data_units = 'unknown'\n        data_radcal = 'unknown'\n        loc_bad = np.where(errs_cube <= 0)\n        inten_cube[loc_bad] = 0\n        errs_cube[loc_bad] = 0\n    else:\n        print('Error: missing or invalid data. Please input a filepath, EISCube,'\n             +' or complete set of intensity, wavelength, and error arrays.', file=sys.stderr)\n        return None\n\n    # Validate input ncpu value\n    if str(ncpu).lower() == 'max' or str(ncpu).lower() == 'none':\n        ncpu = mp.cpu_count()\n    else:\n        ncpu = int(ncpu)\n\n    if ncpu <= 0:\n        ncpu = 1\n    elif ncpu > mp.cpu_count():\n        ncpu = mp.cpu_count()\n\n    # Ensure that multiprocessing will not spawn infinite child processes\n    if ncpu > 1:\n        name_guard = check_for_name_guard(debug=debug)\n        if unsafe_mp == True and name_guard == False:\n            if ignore_warnings == False:\n                print('CRITICAL WARNING: unsafe_mp == True while no name guard'\n                     +' was found in the top-level script! Be aware, parallel'\n                     +' processes may freeze or behave unexpectedly.')\n        elif name_guard == False:\n            ncpu = 1\n            if ignore_warnings == False:\n                print('WARNING: no name guard was found in the top-level script!'\n                     +' Falling back to a single process for safety.')\n\n    # Check value of min_points\n    n_params = len(parinfo_copy)\n    if min_points is None or min_points < n_params:\n        print('WARNING: min_points must be >= total number of fit parameters.'\n             +' min_points has been set to '+str(n_params))\n        min_points = n_params\n\n    # Check the dimensions of input data.\n    # If the the arrays are not 3D, add shallow dimensions of size 1\n    num_dims = inten_cube.ndim\n    dims_size = inten_cube.shape\n    if num_dims == 1:\n        n_pxls = 1\n        n_steps = 1\n        wave_cube = wave_cube[np.newaxis, np.newaxis, :]\n        inten_cube = inten_cube[np.newaxis, np.newaxis, :]\n        errs_cube = errs_cube[np.newaxis, np.newaxis, :]\n    elif num_dims == 2:\n        n_pxls = dims_size[0]\n        n_steps = 1\n        wave_cube = wave_cube[:, np.newaxis, :]\n        inten_cube = inten_cube[:, np.newaxis, :]\n        errs_cube = errs_cube[:, np.newaxis, :]\n    elif num_dims == 3:\n        n_pxls = dims_size[0]\n        n_steps = dims_size[1]\n        wave_cube = wave_cube\n        inten_cube = inten_cube\n        errs_cube = errs_cube\n\n    # Initalize output object which will contain the fit results\n    fit_res = EISFitResult(wave_cube, template_copy, parinfo_copy,\n                           func_name='multigaussian', data_units=data_units,\n                           radcal=data_radcal)\n    fit_res.meta = metadata\n    fit_res.meta['filename_template'] = tmplt_filename\n    fit_res.fit_module = 'mpfit'\n    fit_res.fit_method = 'LevMarLSQ'\n\n    if skip_fitting != True:\n        t1 = datetime.now() # start a simple timer\n        nexp.value = n_steps\n        print(f' + computing fits for {n_steps:d} exposures, each with {n_pxls:d} spectra')\n\n        # Run fitting in either a single process (default) or using multiprocessing\n        if ncpu == 1:\n            print(' + running mpfit in a single process')\n            fit_dict = fit_with_mpfit(wave_cube, inten_cube, errs_cube,\n                                      template_copy, parinfo_copy, min_points,\n                                      data_units=data_units)\n            fit_res.fit = fit_dict\n        else:\n            if ncpu > n_steps:\n                ncpu = n_steps\n            print(f' + running mpfit on {ncpu:d} cores (of {mp.cpu_count():d})')\n\n            # initialize pool of workers\n            pool = mp.Pool(processes=ncpu)\n\n            # Split out the data for each single slit and run the pool\n            args = [(wave_cube[:,jj:jj+1,:], inten_cube[:,jj:jj+1,:], errs_cube[:,jj:jj+1,:],\n                     template_copy, parinfo_copy, min_points, jj+1, data_units)\n                     for jj in range(n_steps)]\n            pool_out = pool.starmap(fit_with_mpfit, args)\n            pool.close()\n\n            # Now, loop over each slit and copy fit results values to full output object\n            for jj in range(n_steps):\n                fit_res.fit['status'][:,jj] = pool_out[jj]['status'][:,0]\n                fit_res.fit['chi2'][:,jj] = pool_out[jj]['chi2'][:,0]\n                fit_res.fit['mask'][:,jj,:] = pool_out[jj]['mask'][:,0,:]\n                fit_res.fit['wavelength'][:,jj,:] = pool_out[jj]['wavelength'][:,0,:]\n                fit_res.fit['params'][:,jj,:] = pool_out[jj]['params'][:,0,:]\n                fit_res.fit['perror'][:,jj,:] = pool_out[jj]['perror'][:,0,:]\n                fit_res.fit['int'][:,jj,:] = pool_out[jj]['int'][:,0,:]\n                fit_res.fit['err_int'][:,jj,:] = pool_out[jj]['err_int'][:,0,:]\n\n        # Calculate the Doppler velocity for each line\n        # TODO: revisit error estimation\n        for gg in range(fit_res.n_gauss):\n            base_wave = parinfo_copy[1+3*gg]['value']\n            obs_cent = fit_res.fit['params'][:,:,1+3*gg]\n            obs_errs = fit_res.fit['perror'][:,:,1+3*gg]\n            velocity = calc_velocity(obs_cent, base_wave)\n            fit_res.fit['vel'][:,:,gg] = velocity\n            rel_err = obs_errs/obs_cent\n            fit_res.fit['err_vel'][:,:,gg] = rel_err*velocity\n\n        # print status\n        t2 = datetime.now() # end timer\n        num_fit = len(np.where(fit_res.fit['status'] > -0)[0])\n        num_too_few = len(np.where((fit_res.fit['status'] == -2) |\n                                   (fit_res.fit['status'] == -1))[0])\n        num_bad_params = len(np.where((fit_res.fit['status'] == -3) |\n                                      (fit_res.fit['status'] == 0))[0])\n        print('\\n')\n        print('Finished computing fits!')\n        print(f'   runtime : {t2-t1}')\n        print(f'   {num_fit} spectra fit without issues')\n        print(f'   {num_too_few} spectra have < {min_points} good data points')\n        print(f'   {num_bad_params} spectra have bad or invalid parameters')\n\n        # reset global counters\n        cntr.value = 0\n        nexp.value = 0\n\n    return fit_res\n\n\nif __name__ == '__main__':\n    import matplotlib.pyplot as plt\n    import astropy.units as u\n    # from read_cube import read_cube\n    # from read_template import read_template\n\n    # input data and template files\n    # file_data = './data/eis_20120924_105026.head.h5'\n    file_data = './data/eis_20190404_131513.data.h5'\n    file_template = './templates/eis_template_dir/fe_12_195_119.2c.template.h5'\n\n    # read fit template\n    Fe_XII_195_119 = EISFitTemplate.read_template(file_template)\n\n    # read spectra window\n    raster = read_cube(file_data, Fe_XII_195_119.central_wave)\n\n    # fit profile\n    # wave_coords = raster.axis_world_coords('em.wl')\n    # lower_corner = (300*u.arcsec, 50*u.arcsec, wave_coords[0])\n    # upper_corner = (400*u.arcsec, 150*u.arcsec, wave_coords[-1])\n    # sub_raster = raster.crop_by_coords(lower_corner, upper_corner=upper_corner)\n    sub_raster = raster[0:10, 0:10, :]\n\n    fit_res = fit_spectra(sub_raster, Fe_XII_195_119, ncpu=4)\n\n    # Quick plot raster\n    plot_aspect_ratio = raster.meta['pointing']['y_scale']/raster.meta['pointing']['x_scale']\n    raster.sum_spectra().plot(aspect=plot_aspect_ratio)\n\n    # Plot example fit\n    ex_pxl_coords = [5, 5]\n    # ex_pxl_coords = [4, 8]\n    fit_x, fit_y = fit_res.get_fit_profile(coords=ex_pxl_coords, num_wavelengths=100)\n    c0_fit_x, c0_fit_y = fit_res.get_fit_profile(component=0, coords=ex_pxl_coords,\n                                                 num_wavelengths=100)\n    c1_fit_x, c1_fit_y = fit_res.get_fit_profile(component=1, coords=ex_pxl_coords,\n                                                 num_wavelengths=100)\n    c2_fit_x, c2_fit_y = fit_res.get_fit_profile(component=2, coords=ex_pxl_coords,\n                                                 num_wavelengths=100)\n    sub_data = sub_raster.data[ex_pxl_coords[0], ex_pxl_coords[1], :]\n    sub_wave = sub_raster.wavelength[ex_pxl_coords[0], ex_pxl_coords[1], :]\n    sub_err = sub_raster.uncertainty.array[ex_pxl_coords[0], ex_pxl_coords[1], :]\n\n    fig = plt.figure()\n    profile_subplt = fig.add_subplot(111)\n    profile_subplt.errorbar(sub_wave, sub_data, yerr=sub_err,\n                            ls='', marker='o', color='k')\n    profile_subplt.plot(fit_x, fit_y, color='b')\n    profile_subplt.plot(c0_fit_x, c0_fit_y, color='r')\n    profile_subplt.plot(c1_fit_x, c1_fit_y, color='r', ls='--')\n    profile_subplt.plot(c2_fit_x, c2_fit_y, color='g')\n    profile_subplt.set_xlabel(r'Wavelength [$\\AA$]')\n    profile_subplt.set_ylabel('Intensity ['+raster.unit.to_string()+']')\n    plt.show()\n", "meta": {"hexsha": "f51c6ea2aece2dbd626a56a2f9ee88f849e25d7d", "size": 22295, "ext": "py", "lang": "Python", "max_stars_repo_path": "eispac/core/fit_spectra.py", "max_stars_repo_name": "MJWeberg/eispac", "max_stars_repo_head_hexsha": "8de2b282fc08da9ac66d48c396060aab6e17be70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2021-02-18T00:24:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T06:48:06.000Z", "max_issues_repo_path": "eispac/core/fit_spectra.py", "max_issues_repo_name": "MJWeberg/eispac", "max_issues_repo_head_hexsha": "8de2b282fc08da9ac66d48c396060aab6e17be70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2021-04-09T16:34:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-09T16:55:29.000Z", "max_forks_repo_path": "eispac/core/fit_spectra.py", "max_forks_repo_name": "MJWeberg/eispac", "max_forks_repo_head_hexsha": "8de2b282fc08da9ac66d48c396060aab6e17be70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-04-09T16:47:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T15:45:29.000Z", "avg_line_length": 44.4123505976, "max_line_length": 94, "alphanum_fraction": 0.607176497, "include": true, "reason": "import numpy,import astropy", "num_tokens": 5485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.30074559147596, "lm_q1q2_score": 0.1713806727036947}}
{"text": "##Remaining tasks: -ve value of velocity, maxlimit of velocity, 0-acceleration\nimport numpy as np\nimport math\nimport copy\nimport dubins\nimport shapely.geometry as geom\nimport threading    \nfrom statistics import median \n\n\n\n\n#Change radius of curvature for 0.9\nfrom vel_acc_to_throttle import *\n\n\nlock = threading.Lock()\ninf = 1e9\nNo_of_threads = 11\n\nacc= {}\nacc[0] = [-1.0, -0.5, 0.5, 1.0, 2.0, 4.0]\nacc[1] = [-1.0, -0.5, 0.5, 1.0, 2.0, 4.0]\nacc[2] = [-1.0, -0.5, 0.5, 1.0, 2.0, 4.0]\nacc[3] = [-1.0, -0.5, 0.5, 1.0, 2.0, 4.0]\nacc[4] = [-1.0, -0.5, 0.5, 1.0, 2.0, 4.0]\nacc[5] = [-1.0, 0.0, 1.0, 2.0, 4.0]\nacc[6] = [-1.0, 0.0, 1.0, 2.0, 4.0]\nacc[7] = [-1.0, 0.0, 1.0, 2.0, 4.0]\nacc[8] = [-1.0, 0.0, 1.0, 2.0, 4.0]\nacc[9] =  [-3.0, -1.0, 0.0, 1.0, 2.0, 4.0]\nacc[10] = [-3.0, -1.0, 0.0, 1.0, 2.0, 4.0]\nacc[11] = [-3.0, -1.0, 0.0, 1.0, 2.0, 4.0]\nacc[12] = [-3.0, -1.0, 0.0, 1.0, 2.0, 4.0]\nacc[13] = [-3.0, -1.0, 0.0, 1.0, 2.0, 4.0]\nacc[14] = [-3.0, -1.0, 0.0, 1.0, 2.0, 4.0]\nacc[15] = [-3.0, -1.0, 0.0, 1.0, 2.0, 4.0]\nacc[16] = [-5.0, -3.0, -1.0, 0.0, 1.5, 3.0]\nacc[17] = [-5.0, -3.0, -1.0, 0.0, 1.5, 3.0]\nacc[18] = [-5.0, -3.0, -1.0, 0.0, 1.5, 3.0]\nacc[19] = [-5.0, -3.0, -1.0, 0.0, 1.5, 3.0]\nacc[20] = [-5.0, -3.0, -1.0, 0.0, 1.5, 3.0]\nacc[21] = [-5.0, -3.0, -1.0, 0.0, 1.5]\nacc[22] = [-5.0, -3.0, -1.2, 0.0, 1.5]\nacc[23] = [-5.0, -3.0, -1.2, 0.0, 1.0]\nacc[24] = [-5.0, -3.0, -1.2, 0.0, 1.0]\nacc[25] = [-5.0, -3.0, -1.2, 0.0, 1.0]\nacc[26] = [-5.0, -3.0, -1.3, 0.0, 1.0]\nacc[27] = [-5.0, -3.0, -1.4, 0.0, 1.0]\nacc[28] = [-5.0, -3.0, -1.4, 0.0, 0.5]\nacc[29] = [-5.0, -3.0, -1.4, 0.0, 0.5]\nacc[30] = [-5.0, -3.0, -1.5, 0.0]\n\n\ntotal_distance = 150.0\ngrid_points = []\n\nactual_vel = {} #key = (i,j,v,t)\nactual_tim = {} #key = (i,j,v,t)\nprev_acc = {} #key = (i,j,v,t)\nc = {} #key = (j,v,t)\np = {} #key = (i,j,v,t)\nvelocities = []\ntimes= []\n\n\n#Used for updation across different layers\ntemp_tim = {}\ntemp_vel = {}\ntemp_acc = {}\ntemp_c = {}\ntemp_p = {}\n\ntemp_theta = {}\ncur_theta = {}\n#-----------------------------------------\n\n\ny_step = 0.6\nx_step = 5.0\nw = 3.6\nobs_initial_pos = [450.0,0.0]\nobs_vel = 5.0\n\ncorner_local_coords = [[-2.5, -1.1], [-2.5, 1.1], [2.5, 1.1], [2.5, -1.1]]\n\nRadius_of_road = 20.0\n    \nObs2_initial_pos = [360.0, 2.4]\nObs2_vel = 5.0\n\ndef RadiusofCurvature(start_pt, end_pt, turn_radius=30.0, step_size=1.0):\n    \"\"\"Generate points along a Dubins path connecting start point to end point.\n    Format for input / output points: (x, y, angle)\"\"\"\n    min_turn_radius = min(0.1, turn_radius)\n    satisfied = False\n    configurations = [start_pt, end_pt]\n    while not satisfied:\n        dubins_path = dubins.shortest_path(start_pt, end_pt, turn_radius)\n        configurations, _ = dubins_path.sample_many(step_size)\n        cex_found = False\n        for configuration in configurations:\n            if not (min(start_pt[0], end_pt[0]) - 0.1 <= configuration[0] <= max(start_pt[0], end_pt[0]) + 0.1 and\n                    min(start_pt[1], end_pt[1]) - 0.1 <= configuration[1] <= max(start_pt[1], end_pt[1]) + 0.1):\n                cex_found = True\n                break\n        satisfied = not cex_found\n        if cex_found:\n            # Decrease radius until finding a satisfying result.\n            # We could do a binary search but that requires a termination condition.\n            turn_radius = turn_radius*0.8\n            if turn_radius < min_turn_radius:\n                break\n    if not satisfied:\n        return 0.1\n    return turn_radius\n\n\ndef rotate_point_cw(point, theta):\n    cos_theta = math.cos(theta)\n    sin_theta = math.sin(theta)\n    return np.dot(np.array([[cos_theta, sin_theta], [-sin_theta, cos_theta]]), point)\n\ndef ObsPosition(t):\n    Total_time = (1000.0 + 2*math.pi*20.0)/obs_vel\n    t = t - Total_time * int(t/Total_time)\n    offset = t * obs_vel\n    if( obs_initial_pos[0] - offset >=0):\n        return [obs_initial_pos[0]-offset,obs_initial_pos[1], math.pi]\n    elif( obs_initial_pos[0] - (offset - math.pi * Radius_of_road) >=0 ):\n        turned_theta = (offset - obs_initial_pos[0])/Radius_of_road\n        return [-Radius_of_road*math.sin(turned_theta), -Radius_of_road + Radius_of_road*math.cos(turned_theta), math.pi + turned_theta]\n    elif( offset <= obs_initial_pos[0] + 500.0 + Radius_of_road*math.pi):\n        return [offset - obs_initial_pos[0] - Radius_of_road*math.pi, -2*Radius_of_road, 0.0]\n    elif(offset <= 2*Radius_of_road*math.pi + obs_initial_pos[0]+500.0):\n        turned_theta = (offset - Radius_of_road*math.pi - 500.0 - obs_initial_pos[0])/Radius_of_road\n        return [500.0+Radius_of_road*math.sin(turned_theta),-Radius_of_road- Radius_of_road*math.cos(turned_theta), turned_theta]\n    else:\n        return [1000.0 - offset + 2*Radius_of_road*math.pi + obs_initial_pos[0], 0.0, math.pi]\n\n\ndef computeD(x1,x2,y1,y2,xp,yp):\n    D = (x2 - x1) * (yp - y1) - (xp - x1) * (y2 - y1)\n    return D\n\n\ndef check_colliding(pt2):\n    turned = pt2[0][2]-pt2[4]\n    # obstacle_position = [obs_initial_pos[0] - obs_vel*pt2[3],obs_initial_pos[1]]\n    obstacle_position =  ObsPosition(pt2[3])\n    car_corner_pos = []\n    for local_coord in corner_local_coords:\n        rotated_local_coord = \\\n            rotate_point_cw(point=np.transpose(np.array(local_coord)),\n                             theta=pt2[4])\n        \n        car_corner_pos.append([pt2[0][0]+rotated_local_coord[0],pt2[0][1]+rotated_local_coord[1]])\n\n    # print(car_corner_pos)\n\n    obs_corner_pos = []\n    for local_coord in corner_local_coords:\n        # rotated_local_coord = \\\n        #     rotate_point_ccw(point=np.transpose(np.array(local_coord)),\n        #                      rotation_angle=-detected_objects[obj_ind].object_yaw_angle)\n        rotated_local_coord = \\\n            rotate_point_cw(point=np.transpose(np.array(local_coord)),\n                             theta=pt2[0][2])\n        \n        obs_corner_pos.append([obstacle_position[0] + rotated_local_coord[0],\n                             obstacle_position[1] + rotated_local_coord[1]])\n\n        # print(rotated_local_coord)\n    # print(obs_corner_pos)\n\n    \n    collision = 0\n    for dx in np.arange(-max(pt2[2],10),max(pt2[2],10),4.9):\n        for pos in car_corner_pos:\n            x = pos[0] + dx*math.cos(pt2[4])\n            y = pos[1] + dx*math.sin(pt2[4])\n            D1 = computeD(obs_corner_pos[0][0],obs_corner_pos[1][0],obs_corner_pos[0][1],obs_corner_pos[1][1],x,y)\n            D2 = computeD(obs_corner_pos[2][0],obs_corner_pos[3][0],obs_corner_pos[2][1],obs_corner_pos[3][1],x,y)\n            D3 = computeD(obs_corner_pos[1][0],obs_corner_pos[2][0],obs_corner_pos[1][1],obs_corner_pos[2][1],x,y)\n            D4 = computeD(obs_corner_pos[3][0],obs_corner_pos[0][0],obs_corner_pos[3][1],obs_corner_pos[0][1],x,y)\n            if ( D1*D2 >=0 and D3*D4>=0): \n                collision=1\n                break\n\n    if(collision == 1):\n        return collision\n\n    obstacle_position = [Obs2_initial_pos[0] + Obs2_vel*pt2[3],Obs2_initial_pos[1]]\n    obs_corner_pos = []\n    for local_coord in corner_local_coords:\n        # rotated_local_coord = \\\n        #     rotate_point_ccw(point=np.transpose(np.array(local_coord)),\n        #                      rotation_angle=-detected_objects[obj_ind].object_yaw_angle)\n        rotated_local_coord = \\\n            rotate_point_cw(point=np.transpose(np.array(local_coord)),\n                             theta=pt2[0][2])\n        \n        obs_corner_pos.append([obstacle_position[0] + rotated_local_coord[0],\n                             obstacle_position[1] + rotated_local_coord[1]])\n\n\n    \n    for dx in np.arange(-max(pt2[2],10),max(pt2[2],10),4.9):\n        for pos in car_corner_pos:\n            x = pos[0] + dx*math.cos(pt2[4])\n            y = pos[1] + dx*math.sin(pt2[4])\n            D1 = computeD(obs_corner_pos[0][0],obs_corner_pos[1][0],obs_corner_pos[0][1],obs_corner_pos[1][1],x,y)\n            D2 = computeD(obs_corner_pos[2][0],obs_corner_pos[3][0],obs_corner_pos[2][1],obs_corner_pos[3][1],x,y)\n            D3 = computeD(obs_corner_pos[1][0],obs_corner_pos[2][0],obs_corner_pos[1][1],obs_corner_pos[2][1],x,y)\n            D4 = computeD(obs_corner_pos[3][0],obs_corner_pos[0][0],obs_corner_pos[3][1],obs_corner_pos[0][1],x,y)\n            if ( D1*D2 >=0 and D3*D4>=0): \n                collision=1\n                break\n\n    return collision    \n\ndef cost(c1, pt1,pt2, off=0.0):\n    # print(pt1)\n    # print(pt2)\n    # r = RadiusofCurvature(pt1[0],pt2[0])\n    R={}\n    R[(5,0)] = inf\n    # For straight line only\n\n    deltay = abs(pt2[0][1]-pt1[0][1])\n    deltax = abs(pt2[0][0]-pt1[0][0])\n    temp = (deltax,deltay)\n    if(temp in R):\n        r = R[temp]\n    else:\n        r = RadiusofCurvature([pt1[0][0],pt1[0][1],pt1[4]],[pt2[0][0],pt2[0][1],pt2[4]])\n        if(r==30):\n            r=inf\n        R[temp] = r\n\n    obstacle_position = [obs_initial_pos[0] - obs_vel*pt2[3],obs_initial_pos[1]]\n    \n    static_cost =  c1 + math.sqrt((pt2[0][0]-pt1[0][0])**2 + (pt2[0][1]-pt1[0][1])**2) + 10.0/r + 1.0*abs(off) + 0.1*math.exp(-0.1*math.sqrt((pt2[0][0]-obstacle_position[0])**2 + (pt2[0][1]-obstacle_position[1])**2))\n\n    dynamic_cost = 15.0*(pt2[3]-pt1[3]) + (pt2[2]**2)*0.0 + 0.0*(pt2[1]**2) + 1.7e-10*(((pt2[1]-pt1[1])/(pt2[3]-pt1[3]))**2) + 1.0*(((pt2[2])**2)/r)\n    \n    return static_cost + dynamic_cost + check_colliding(pt2)*inf\n\n    #off = 1 or 0.5\ndef Grid1(cur_pt,dist_to_cover):\n    global grid_points\n    x1 = round(cur_pt[0],2)\n    x2 = max(x1-dist_to_cover,0) ##path to travel in first part of the road\n    for i in np.arange(x1,x2,-x_step):\n        gp = []\n        for j in np.arange(w,-w,-y_step):\n            gp.append([i,round(j,2),math.pi])\n        grid_points.append(gp)\n    return dist_to_cover - (x1-x2)\n\ndef Grid2(cur_pt,dist_to_cover):\n    global grid_points\n    theta_covered = math.atan(abs(cur_pt[0])/(Radius_of_road+cur_pt[1]))\n    if(theta_covered<0):\n        theta_covered = theta_covered + math.pi\n    theta_to_cover = dist_to_cover/Radius_of_road\n    final_theta = min(theta_covered + theta_to_cover,math.pi)\n    for theta in np.arange(theta_covered,final_theta+0.00001,x_step/Radius_of_road):\n        gp = []\n        for j in np.arange(Radius_of_road+w,Radius_of_road-w,-y_step):\n            x_coord = round(-j*math.sin(theta),2)\n            y_coord = round(-Radius_of_road+j*math.cos(theta),2)\n            gp.append([x_coord,y_coord,math.pi+theta])\n        grid_points.append(gp)\n    return (theta_covered + theta_to_cover - final_theta)*Radius_of_road \n\ndef Grid3(cur_pt,dist_to_cover):\n    global grid_points\n    x1 = round(cur_pt[0],2)\n    x2 = min(x1+dist_to_cover,500.0) ##path to travel in first part of the road\n    for i in np.arange(x1,x2,x_step):\n        gp = []\n        for j in np.arange(-2*Radius_of_road + w,-2*Radius_of_road-w,-y_step):\n            gp.append([i,round(j,2),0.0])\n        grid_points.append(gp)\n    return (dist_to_cover - (x2-x1))    \n\n\ndef Grid4(cur_pt,dist_to_cover):\n    global grid_points\n    theta_covered = math.atan(abs(cur_pt[0]-500.0)/(-Radius_of_road-cur_pt[1]))\n    if(theta_covered<0):\n        theta_covered = theta_covered + math.pi\n    theta_to_cover = dist_to_cover/Radius_of_road\n    final_theta = min(theta_covered + theta_to_cover,math.pi)\n    for theta in np.arange(theta_covered,final_theta+0.0000001,x_step/Radius_of_road):\n        gp = []\n        for j in np.arange(Radius_of_road+w,Radius_of_road-w,-y_step):\n            x_coord = round(500.0+j*math.sin(theta),2)\n            y_coord = round(-Radius_of_road-j*math.cos(theta),2)\n            gp.append([x_coord,y_coord,theta])\n        grid_points.append(gp)\n    return (theta_covered + theta_to_cover - final_theta)*Radius_of_road \n\n\ndef calculate_grid(cur_pt,dist_to_cover):\n    global grid_points\n    grid_points = []\n    if(cur_pt[0]>0 and cur_pt[0]<=500 and cur_pt[1]>-20.0):  ##check in first part of the road\n        remaining_dist = Grid1(cur_pt,dist_to_cover)\n        if(remaining_dist > 0):\n            remaining_dist = Grid2([0.0,0.0],remaining_dist)\n        if(remaining_dist > 0):\n            remaining_dist = Grid3([0.0,-2*Radius_of_road],remaining_dist)\n        if(remaining_dist > 0):\n            remaining_dist = Grid4([500.0,-2*Radius_of_road],remaining_dist)\n    elif(cur_pt[0]<=0):\n        remaining_dist = Grid2(cur_pt,dist_to_cover)\n        if(remaining_dist>0):\n            remaining_dist = Grid3([0.0,-2*Radius_of_road],remaining_dist)\n        if(remaining_dist > 0):\n            remaining_dist = Grid4([500.0,-2*Radius_of_road],remaining_dist)\n    elif(cur_pt[0]>=0 and cur_pt[0]<500 and cur_pt[1]<-20.0):\n        remaining_dist = Grid3(cur_pt,dist_to_cover)\n        if(remaining_dist > 0):\n            remaining_dist = Grid4([500.0,-2*Radius_of_road],remaining_dist)\n        if(remaining_dist > 0):\n            remaining_dist = Grid1([500.0,0.0],remaining_dist)\n    else:\n        remaining_dist = Grid4([500.0,-2*Radius_of_road],dist_to_cover)    \n        if(remaining_dist > 0):\n            remaining_dist = Grid1([500.0,0.0],remaining_dist)\n\n\n\ndef computeTargetPath(cur_pt, dist_to_cover):\n    \n    calculate_grid(cur_pt,dist_to_cover)\n    global grid_points\n    global c\n    global p\n    global actual_vel\n    global actual_tim\n    global prev_acc\n    global cur_theta\n       \n    # print(grid_points)\n\n    ##########change from here\n    X = round(2*w/y_step)\n    Y = len(grid_points)\n    \n\n\n    ind2 = -1\n    min_dist = inf\n    for j in range(X):\n        cur_dist = (grid_points[0][j][1]-cur_pt[1])**2 + (grid_points[0][j][0]-cur_pt[0])**2\n        if(cur_dist < min_dist):\n            min_dist = cur_dist\n            ind2 = j\n\n    #Initialisation\n    i3 = math.ceil(cur_pt[3])\n    i4 = math.ceil(cur_pt[4])\n    c[(ind2,i3,i4)] = 0.0\n    p[(0,ind2,i3,i4)] = -1\n    actual_tim[(0,ind2,i3,i4)] = cur_pt[4]\n    actual_vel[(0,ind2,i3,i4)] = cur_pt[3]\n    prev_acc[(0,ind2,i3,i4)] = cur_pt[2]\n    cur_theta[(0,ind2,i3,i4)] = cur_pt[5]\n\n    global velocities\n    global times\n    global temp_vel\n    global temp_c\n    global temp_tim\n    global temp_p\n    global temp_acc\n    global temp_theta\n\n\n    cf = inf\n    final_pos = -1\n    \n    for i in  range(Y-1):\n        t0= threading.Thread(target=parallel_func, args=(0,i,X,))\n        t1= threading.Thread(target=parallel_func, args=(1,i,X,))\n        t2= threading.Thread(target=parallel_func, args=(2,i,X,))\n        t3= threading.Thread(target=parallel_func, args=(3,i,X,))\n        t4= threading.Thread(target=parallel_func, args=(4,i,X,))\n        t5= threading.Thread(target=parallel_func, args=(5,i,X,))\n        t6= threading.Thread(target=parallel_func, args=(6,i,X,))\n        t7= threading.Thread(target=parallel_func, args=(7,i,X,))\n        t8= threading.Thread(target=parallel_func, args=(8,i,X,))\n        t9= threading.Thread(target=parallel_func, args=(9,i,X,))\n        t10= threading.Thread(target=parallel_func, args=(10,i,X,))\n        t0.start()\n        t1.start()\n        t2.start()\n        t3.start()\n        t4.start()\n        t5.start()\n        t6.start()\n        t7.start()\n        t8.start()\n        t9.start()\n        t10.start()\n        t0.join()\n        t1.join()\n        t2.join()\n        t3.join()\n        t4.join()\n        t5.join()\n        t6.join()\n        t7.join()\n        t8.join()\n        t9.join()\n        t10.join()\n\n        # print(velocities)\n        # print(\" \")\n        v_m = median(velocities)\n        t_m = median(times)\n        v_min = v_m-5\n        v_max = v_m+5\n        t_max = t_m+5\n        t_min = t_m-5\n\n        # print(c)\n        c = {}\n        for (j,v,t) in temp_c:\n            ind_v = math.ceil(v)\n            if(v > v_max):\n                ind_v = inf\n            if(v < v_min):\n                ind_v = v_min\n            ind_t = math.ceil(t)\n            if(t > t_max):\n                ind_t = inf\n            if(t < t_min):\n                ind_t = t_min\n            \n            if ((j,ind_v,ind_t) not in c) or (c[(j,ind_v,ind_t)] > temp_c[(j,v,t)] ):\n                c[(j,ind_v,ind_t)] = temp_c[(j,v,t)]\n                p[(i+1,j,ind_v,ind_t)] = temp_p[(i+1,j,v,t)]\n                actual_vel[(i+1,j,ind_v,ind_t)] = temp_vel[(i+1,j,v,t)]\n                actual_tim[(i+1,j,ind_v,ind_t)] = temp_tim[(i+1,j,v,t)]\n                prev_acc[(i+1,j,ind_v,ind_t)] = temp_acc[(i+1,j,v,t)]\n                cur_theta[(i+1,j,ind_v,ind_t)] = temp_theta[(i+1,j,v,t)]\n                if(i==Y-2) and (cf>c[(j,ind_v,ind_t)]):\n                    cf = c[(j,ind_v,ind_t)]\n                    final_pos = (i+1,j,ind_v,ind_t)\n\n\n\n\n        velocities = []\n        times = []\n        temp_c = {}\n        temp_vel = {}\n        temp_acc = {}\n        temp_p = {}\n        temp_tim = {}\n        temp_theta = {}\n\n\n\n    travel_path = []\n    (i,j,ind2,ind3) = final_pos\n    while ( (p[(i,j,ind2,ind3)]) != -1 ):\n        travel_path = [[float(grid_points[i][j][0]),float(grid_points[i][j][1]),prev_acc[(i,j,ind2,ind3)],actual_vel[(i,j,ind2,ind3)],actual_tim[(i,j,ind2,ind3)],cur_theta[(i,j,ind2,ind3)]]] + travel_path\n        (i,j,ind2,ind3) = (p[(i,j,ind2,ind3)])\n    \n    return travel_path\n\n\n    \n\ndef parallel_func(ind4,i,X):\n    global c\n    global p\n    global actual_vel\n    global actual_tim\n    global prev_acc\n\n\n    global temp_c\n    global temp_p\n    global temp_acc\n    global temp_vel\n    global temp_tim\n    global temp_theta\n\n    global velocities\n    global times\n    global lock\n                \n    for (j,ind2,ind3) in c:\n\n        v_i = math.ceil(actual_vel[(i,j,ind2,ind3)])\n        if(ind4 < len(acc[v_i])):\n            m1 = max(0,j-1)\n            m2 = min(9,j+1)\n            for k in range(m1,m2+1):\n                a_f = acc[v_i][ind4]\n                cur_cost = 0\n                v_f = ( (actual_vel[(i,j,ind2,ind3)]**2) +2*a_f*x_step)\n                if(v_f < 0):\n                    continue\n                else:\n                    v_f = v_f ** 0.5\n                if(v_f > 30):\n                    continue\n                v_f = round(v_f,4)\n                \n                ind5 = math.ceil(v_f)\n                if v_f == actual_vel[(i,j,ind2,ind3)]:\n                    t_f = x_step/v_f + actual_tim[(i,j,ind2,ind3)]\n                else: \n                    t_f = (v_f-actual_vel[(i,j,ind2,ind3)])/a_f + actual_tim[(i,j,ind2,ind3)]\n                t_f = round(t_f,2)         \n                ind6 = math.ceil(t_f)\n                \n                x1 = grid_points[i][j][0]\n                y1 = grid_points[i][j][1]\n                x2 = grid_points[i+1][k][0]\n                y2 = grid_points[i+1][k][1]\n                if(x2 < x1):\n                    if(y2 >= y1):\n                        curtheta = math.pi + math.atan((y2-y1)/(x2-x1))\n                    else:\n                        curtheta = math.pi + math.atan((y2-y1)/(x2-x1))\n                elif(x2 > x1):\n                    if(y2 >= y1):\n                        curtheta = math.atan((y2-y1)/(x2-x1))\n                    else:\n                        curtheta = 2*math.pi + math.atan((y2-y1)/(x2-x1))\n                else:\n                    if(y2>y1):\n                        curtheta = math.pi/2.0\n                    else:\n                        curtheta = 1.5*math.pi\n\n\n\n                # curtheta = grid_points[i+1][k][2] - math.atan((k-j)*y_step/x_step)\n                \n                cur_cost = cost(c[(j,ind2,ind3)],(grid_points[i][j],prev_acc[(i,j,ind2,ind3)],actual_vel[(i,j,ind2,ind3)],actual_tim[(i,j,ind2,ind3)], cur_theta[(i,j,ind2,ind3)]),(grid_points[i+1][k],a_f,v_f,t_f,curtheta),off=abs(w-k*y_step))\n                if(cur_cost > inf):\n                    continue\n                velocities.append(v_f)\n                times.append(t_f)\n                lock.acquire(True)\n                if( (k,ind5,ind6) not in temp_c) or (temp_c[(k,ind5,ind6)] > cur_cost):\n                    temp_tim[(i+1,k,ind5,ind6)] = t_f\n                    temp_c[(k,ind5,ind6)] = cur_cost\n                    temp_vel[(i+1,k,ind5,ind6)] = v_f\n                    temp_acc[(i+1,k,ind5,ind6)] = a_f\n                    temp_p[(i+1,k,ind5,ind6)] = (i,j,ind2,ind3)\n                    temp_theta[(i+1,k,ind5,ind6)] = curtheta\n                lock.release()\n                \n\n\n\n\n\n# cur_pt = [16.77,0.0,0.5,34.45,26.0, math.pi]\n# cur_pt =  [500.0, 0.0, 0.0, 0.0, 0.0, math.pi]\n# cur_pt = [[405.0, 0.0, math.pi], 1.5, 16.583, 8.9, math.pi]\n# c = check_colliding(cur_pt)\n# print(c)\n\n\ncur_pt =  [500.0, 0.0, 0.0, 10.0, 0.0, math.pi]\npath = [cur_pt]\ntotal_distance_covered = 0\nwhile(total_distance_covered < 400):\n    # path = path + computeTargetPath(cur_pt,100)\n    future_path = computeTargetPath(cur_pt,100)\n    path = path + future_path[:10]\n    print(path)\n    # print(\"path=====================\")\n    # print(path)\n    total_distance_covered = 50.0 + total_distance_covered\n    cur_pt = path[-1]\n    actual_vel = {}\n    actual_tim = {}\n    prev_acc = {}\n    c = {}\n    p = {}\n    # print(cur_pt)\n    # print(path)\n\n\n\noutput = path\nprint(output)\nprint(\" \")\ntarget_path = []\n# v = []\nt = []\n# a= []\nthrottle = []\nprev = -1\n\n\nfor i in output:\n    target_path.append([i[0],i[1]])\n    # a.append(i[2])\n    # v.append(i[3])\n    \n    if(prev == -1):\n        prev = (i[3],i[2])\n    else:\n        t.append(i[4])\n        throttle.append(throttle_value( (i[3]+prev[0])/2.0,i[2]))\n        prev = (i[3],i[2])\n        \nprint(throttle)\nprint(\" \")\nprint(target_path)\nprint(\" \")\nprint(t)\n\n\n\n# r= RadiusofCurvature([5.0,0.0,math.pi],[0.0,0.25,math.pi])\n# print(r)", "meta": {"hexsha": "89d64f665cce4dde51e91b18cf4b1419c7f04f00", "size": 21307, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Optimal path/optimalPath2obs.py", "max_stars_repo_name": "SahilDhull/autonomous", "max_stars_repo_head_hexsha": "378fc7d6c5a9c34c4e915f080fb78ed5c11195d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-02-28T12:04:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T00:42:56.000Z", "max_issues_repo_path": "src/Optimal path/optimalPath2obs.py", "max_issues_repo_name": "SahilDhull/autonomous", "max_issues_repo_head_hexsha": "378fc7d6c5a9c34c4e915f080fb78ed5c11195d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Optimal path/optimalPath2obs.py", "max_forks_repo_name": "SahilDhull/autonomous", "max_forks_repo_head_hexsha": "378fc7d6c5a9c34c4e915f080fb78ed5c11195d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8206349206, "max_line_length": 242, "alphanum_fraction": 0.5532923452, "include": true, "reason": "import numpy", "num_tokens": 7125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.30074559147596, "lm_q1q2_score": 0.1713806727036947}}
{"text": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\nfrom abc import ABCMeta\nfrom collections import namedtuple\nimport inspect\n\nfrom jax import random, tree_map, vmap\nfrom jax.flatten_util import ravel_pytree\nimport jax.numpy as jnp\nimport tensorflow_probability.substrates.jax as tfp\n\nfrom numpyro.infer import init_to_uniform\nfrom numpyro.infer.mcmc import MCMCKernel\nfrom numpyro.infer.util import initialize_model\nfrom numpyro.util import identity\n\nTFPKernelState = namedtuple('TFPKernelState', ['z', 'kernel_results', 'rng_key'])\n\n\ndef _extract_kernel_functions(kernel):\n\n    def init_fn(z, rng_key):\n        z_flat, _ = ravel_pytree(z)\n        results = kernel.bootstrap_results(z_flat)\n        return TFPKernelState(z, results, rng_key)\n\n    def sample_fn(state, model_args=(), model_kwargs=None):\n        rng_key, rng_key_transition = random.split(state.rng_key)\n        z_flat, unravel_fn = ravel_pytree(state.z)\n        z_new_flat, results = kernel.one_step(z_flat, state.kernel_results, seed=rng_key_transition)\n        return TFPKernelState(unravel_fn(z_new_flat), results, rng_key)\n\n    return init_fn, sample_fn\n\n\ndef _make_log_prob_fn(potential_fn, unravel_fn):\n\n    def log_prob_fn(x):\n        # we deal with batched x in case the kernel is ReplicaExchangeMC\n        batch_shape = jnp.shape(x)[:-1]\n        if batch_shape:\n            flatten_result = vmap(lambda a: -potential_fn(unravel_fn(a)))(\n                jnp.reshape(x, (-1,) + jnp.shape(x)[-1:]))\n            return tree_map(lambda a: jnp.reshape(a, batch_shape + jnp.shape(a)[1:]),\n                            flatten_result)\n        else:\n            return - potential_fn(unravel_fn(x))\n\n    return log_prob_fn\n\n\nclass _TFPKernelMeta(ABCMeta):\n    def __getitem__(cls, kernel_class):\n        assert issubclass(kernel_class, tfp.mcmc.TransitionKernel)\n        assert 'target_log_prob_fn' in inspect.getfullargspec(kernel_class).args, \\\n            f\"the first argument of {kernel_class} must be `target_log_prob_fn`\"\n\n        _PyroKernel = type(kernel_class.__name__, (TFPKernel,), {})\n        _PyroKernel.kernel_class = kernel_class\n        return _PyroKernel\n\n\nclass TFPKernel(MCMCKernel, metaclass=_TFPKernelMeta):\n    \"\"\"\n    A thin wrapper for TensorFlow Probability (TFP) MCMC transition kernels.\n    The argument `target_log_prob_fn` in TFP is replaced by either `model`\n    or `potential_fn` (which is the negative of `target_log_prob_fn`).\n\n    This class can be used to convert a TFP kernel to a NumPyro-compatible one\n    as follows::\n\n        kernel = TFPKernel[tfp.mcmc.NoUTurnSampler](model, step_size=1.)\n\n    .. note:: By default, uncalibrated kernels will be inner kernels of the\n        :class:`~tensorflow_probability.substrates.jax.mcmc.MetropolisHastings` kernel.\n\n    .. note:: For :class:`~numpyro.contrib.tfp.mcmc.ReplicaExchangeMC`, TFP requires\n        that the shape of `step_size` of the inner kernel must be\n        `[len(inverse_temperatures), 1]` or `[len(inverse_temperatures), latent_size]`.\n\n    :param model: Python callable containing Pyro :mod:`~numpyro.primitives`.\n        If model is provided, `potential_fn` will be inferred using the model.\n    :param potential_fn: Python callable that computes the target potential energy\n        given input parameters. The input parameters to `potential_fn`\n        can be any python collection type, provided that `init_params` argument to\n        :meth:`init` has the same type.\n    :param callable init_strategy: a per-site initialization function.\n        See :ref:`init_strategy` section for available functions.\n    :param kernel_kwargs: other arguments to be passed to TFP kernel constructor.\n    \"\"\"\n    kernel_class = None\n\n    def __init__(self, model=None, potential_fn=None, init_strategy=init_to_uniform,\n                 **kernel_kwargs):\n        if not (model is None) ^ (potential_fn is None):\n            raise ValueError('Only one of `model` or `potential_fn` must be specified.')\n        self._model = model\n        self._potential_fn = potential_fn\n        self._kernel_kwargs = kernel_kwargs\n        self._init_strategy = init_strategy\n        # Set on first call to init\n        self._init_fn = None\n        self._postprocess_fn = None\n        self._sample_fn = None\n\n    def _init_state(self, rng_key, model_args, model_kwargs, init_params):\n        if self._model is not None:\n            init_params, potential_fn, postprocess_fn, model_trace = initialize_model(\n                rng_key,\n                self._model,\n                init_strategy=self._init_strategy,\n                dynamic_args=True,\n                model_args=model_args,\n                model_kwargs=model_kwargs)\n            init_params = init_params.z\n            if self._init_fn is None:\n                _, unravel_fn = ravel_pytree(init_params)\n                kernel = self.kernel_class(\n                    _make_log_prob_fn(potential_fn(*model_args, **model_kwargs), unravel_fn),\n                    **self._kernel_kwargs)\n                # Uncalibrated... kernels have to used inside MetropolisHastings, see\n                # https://www.tensorflow.org/probability/api_docs/python/tfp/substrates/jax/mcmc/UncalibratedLangevin\n                if self.kernel_class.__name__.startswith(\"Uncalibrated\"):\n                    kernel = tfp.mcmc.MetropolisHastings(kernel)\n                self._init_fn, self._sample_fn = _extract_kernel_functions(kernel)\n            self._postprocess_fn = postprocess_fn\n        elif self._init_fn is None:\n            _, unravel_fn = ravel_pytree(init_params)\n            kernel = self.kernel_class(\n                _make_log_prob_fn(self._potential_fn, unravel_fn),\n                **self._kernel_kwargs)\n            if self.kernel_class.__name__.startswith(\"Uncalibrated\"):\n                kernel = tfp.mcmc.MetropolisHastings(kernel)\n            self._init_fn, self._sample_fn = _extract_kernel_functions(kernel)\n        return init_params\n\n    @property\n    def model(self):\n        return self._model\n\n    @property\n    def sample_field(self):\n        return 'z'\n\n    @property\n    def default_fields(self):\n        return ('z',)\n\n    def get_diagnostics_str(self, state):\n        \"\"\"\n        Given the current `state`, returns the diagnostics string to\n        be added to progress bar for diagnostics purpose.\n        \"\"\"\n        return ''\n\n    def init(self, rng_key, num_warmup, init_params=None, model_args=(), model_kwargs={}):\n        # non-vectorized\n        if rng_key.ndim == 1:\n            rng_key, rng_key_init_model = random.split(rng_key)\n        # vectorized\n        else:\n            rng_key, rng_key_init_model = jnp.swapaxes(vmap(random.split)(rng_key), 0, 1)\n        init_params = self._init_state(rng_key_init_model, model_args, model_kwargs, init_params)\n        if self._potential_fn and init_params is None:\n            raise ValueError('Valid value of `init_params` must be provided with'\n                             ' `target_log_prob_fn`.')\n\n        if rng_key.ndim == 1:\n            init_state = self._init_fn(init_params, rng_key)\n        else:\n            # XXX it is safe to run hmc_init_fn under vmap despite that hmc_init_fn changes some\n            # nonlocal variables: momentum_generator, wa_update, trajectory_len, max_treedepth,\n            # wa_steps because those variables do not depend on traced args: init_params, rng_key.\n            init_state = vmap(self._init_fn)(init_params, rng_key)\n            sample_fn = vmap(self._sample_fn, in_axes=(0, None, None))\n            self._sample_fn = sample_fn\n        return init_state\n\n    def postprocess_fn(self, args, kwargs):\n        if self._postprocess_fn is None:\n            return identity\n        return self._postprocess_fn(*args, **kwargs)\n\n    def sample(self, state, model_args, model_kwargs):\n        \"\"\"\n        Run the kernel from the given :data:`~numpyro.contrib.tfp.mcmc.TFPKernelState`\n        and return the resulting :data:`~numpyro.contrib.tfp.mcmc.TFPKernelState`.\n\n        :param TFPKernelState state: Represents the current state.\n        :param model_args: Arguments provided to the model.\n        :param model_kwargs: Keyword arguments provided to the model.\n        :return: Next `state` after running the kernel.\n        \"\"\"\n        return self._sample_fn(state, model_args, model_kwargs)\n\n\n__all__ = ['TFPKernel']\nfor _name, _Kernel in tfp.mcmc.__dict__.items():\n    if not isinstance(_Kernel, type):\n        continue\n    if not issubclass(_Kernel, tfp.mcmc.TransitionKernel):\n        continue\n    if 'target_log_prob_fn' not in inspect.getfullargspec(_Kernel).args:\n        continue\n\n    _PyroKernel = TFPKernel[_Kernel]\n    _PyroKernel.__module__ = __name__\n    locals()[_name] = _PyroKernel\n\n    _PyroKernel.__doc__ = '''\n    Wraps `{}.{} <https://www.tensorflow.org/probability/api_docs/python/tfp/substrates/jax/mcmc/{}>`_\n    with :class:`~numpyro.contrib.tfp.mcmc.TFPKernel`. The first argument `target_log_prob_fn`\n    in TFP kernel construction is replaced by either `model` or `potential_fn`.\n    '''.format(_Kernel.__module__, _Kernel.__name__, _Kernel.__name__)\n\n    __all__.append(_name)\n\n\n# Create sphinx documentation.\n__doc__ = '\\n\\n'.join([\n\n    '''\n    {0}\n    ----------------------------------------------------------------\n    .. autoclass:: numpyro.contrib.tfp.mcmc.{0}\n    '''.format(_name)\n    for _name in __all__[:1] + sorted(__all__[1:])\n])\n", "meta": {"hexsha": "8a0d71d01d224eecee9ddb6bb91d76ddf6eac1ff", "size": 9412, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpyro/contrib/tfp/mcmc.py", "max_stars_repo_name": "ahoho/numpyro", "max_stars_repo_head_hexsha": "64e94e346c51a6c0c1ba51aa7b608e73513f158f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numpyro/contrib/tfp/mcmc.py", "max_issues_repo_name": "ahoho/numpyro", "max_issues_repo_head_hexsha": "64e94e346c51a6c0c1ba51aa7b608e73513f158f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpyro/contrib/tfp/mcmc.py", "max_forks_repo_name": "ahoho/numpyro", "max_forks_repo_head_hexsha": "64e94e346c51a6c0c1ba51aa7b608e73513f158f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9217391304, "max_line_length": 117, "alphanum_fraction": 0.6667020824, "include": true, "reason": "from numpy,import jax,from jax", "num_tokens": 2213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.3007455664065234, "lm_q1q2_score": 0.17138065841780983}}
{"text": "from . import ccllib as lib\nfrom . import constants as const\nfrom .core import check\nimport numpy as np\n\nimport collections\n\n# Same mapping for non-Limber integration methods\nnonlimber_methods = {\n    'native': const.CCL_NONLIMBER_METHOD_NATIVE,\n    'angpow': const.CCL_NONLIMBER_METHOD_ANGPOW,\n}\n\nfunction_types = {\n    'dndz': const.CCL_CLT_NZ,\n    'bias': const.CCL_CLT_BZ,\n    'mag_bias': const.CCL_CLT_SZ,\n    'red_frac': const.CCL_CLT_RF,\n    'ia_bias': const.CCL_CLT_BA,\n    'lensing_win': const.CCL_CLT_WL,\n    'mag_win': const.CCL_CLT_WM,\n}\n\n# Define symbolic 'None' type for arrays, to allow proper handling by swig\n# wrapper\nNoneArr = np.array([])\n\n\nclass Tracer(object):\n    \"\"\"A tracer of the matter density field.\n\n    .. note:: This class cannot be used directly. Use one of\n              :obj:`NumberCountsTracer`, :obj:`WeakLensingTracer`\n              or :obj:`CMBLensingTracer` instead.\n\n    This class contains all information describing the transfer functon of\n    a tracer (e.g., galaxy density, lensing shear) of the matter distribution.\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        raise NotImplementedError(\n            \"A `Tracer` object cannot be used directly. Use one of \"\n            \"`NumberCountsTracer`, `WeakLensingTracer` or `CMBLensingTracer` \"\n            \"instead.\")\n\n    def _build_tracer(\n            self, cosmo, tracer_type, has_rsd=False,\n            dndz=None, bias=None, mag_bias=None, ia_bias=None,\n            red_frac=None, z_source=1100.):\n        \"\"\"Build the CCL_ClTracer.\n\n        Args:\n            cosmo (:obj:`Cosmology`): Cosmology object.\n            tracer_type (:obj:): Specifies the type of tracer. Must be one of\n                    const.CL_TRACER_NC: number count tracer\n                    const.CL_TRACER_WL: lensing tracer\n                    const.CL_TRACER_CL: CMB lensing tracer\n            has_rsd (bool, optional): Flag for whether the tracer has a\n                redshift-space distortion term. Defaults to False.\n            dndz (tuple of arrays, optional): A tuple of arrays (z, N(z))\n                giving the redshift distribution of the objects. The units are\n                arbitrary; N(z) will be normalized to unity. If `None`, the\n                tracer is assumed to not have a redshift distribution (e.g.,\n                it has a single source source redshift like the CMB). Defaults\n                to None.\n            bias (tuple of arrays, optional): A tuple of arrays (z, b(z))\n                giving the galaxy bias. If `None`, the tracer is assumbed to\n                not have a bias parameter. Defaults to None.\n            mag_bias (tuple of arrays, optional): A tuple of arrays (z, s(z))\n                giving the magnification bias as a function of redshift. If\n                `None`, the tracer is assumed to not have magnification bias\n                terms. Defaults to None.\n            ia_bias (tuple of arrays, optional): A tuple of arrays\n                (z, b_IA(z)) giving the intrinsic alignment amplitude b_IA(z).\n                If `None`, the tracer is assumped to not have intrinsic\n                alignments. Defaults to None.\n            red_frac (tuple of arrays,, optional): A tuple of arrays\n                (z, f_red(z)) givng the red fraction of galaxies as a function\n                of redshift. If `None`, then the tracer is assumed to not have\n                a red fraction. Defaults to None.\n            z_source (float, optional): Redshift of source plane for CMB\n                lensing. Defaults to 1100.\n        \"\"\"\n\n        # Verify cosmo object\n        cosmo = cosmo.cosmo\n\n        has_magnification = mag_bias is not None\n        if (red_frac is None) != (ia_bias is None):\n            raise ValueError(\n                \"Either both or none of `red_frac` and `ia_bias` \"\n                \"must be specified.\")\n        has_intrinsic_alignment = red_frac is not None\n\n        # Passing None for certain arguments causes segmentation faults at the\n        # moment. The following checks try to guard against these instances\n        # but this should probably be checked for at the C level.\n        if tracer_type in [const.CL_TRACER_WL,\n                           const.CL_TRACER_NC]:\n            if not isinstance(dndz, collections.Iterable) \\\n               or len(dndz) != 2 \\\n               or not (isinstance(dndz[0], collections.Iterable)\n                       and isinstance(dndz[1], collections.Iterable)):\n                raise ValueError(\"dndz needs to be a tuple of two arrays.\")\n        if tracer_type in [const.CL_TRACER_NC]:\n            if not isinstance(bias, collections.Iterable) \\\n               or len(bias) != 2 \\\n               or not (isinstance(bias[0], collections.Iterable)\n                       and isinstance(bias[1], collections.Iterable)):\n                raise ValueError(\"bias needs to be a tuple of two arrays.\")\n\n        # Convert array arguments that are 'None' into 'NoneArr' type and\n        # check whether arrays were specified as tuples\n        self.z_n, self.n = _check_array_params(dndz)\n        self.z_b, self.b = _check_array_params(bias)\n        self.z_s, self.s = _check_array_params(mag_bias)\n        self.z_ba, self.ba = _check_array_params(ia_bias)\n        self.z_rf, self.rf = _check_array_params(red_frac)\n        self.z_source = z_source\n\n        # Construct new ccl_cl_tracer\n        status = 0\n        return_val = lib.cl_tracer_new_wrapper(\n                            cosmo,\n                            tracer_type,\n                            int(has_rsd),\n                            int(has_magnification),\n                            int(has_intrinsic_alignment),\n                            self.z_n, self.n,\n                            self.z_b, self.b,\n                            self.z_s, self.s,\n                            self.z_ba, self.ba,\n                            self.z_rf, self.rf,\n                            float(self.z_source),\n                            status)\n\n        if (isinstance(return_val, int)):\n            self.has_cltracer = False\n            check(return_val)\n        else:\n            self.has_cltracer = True\n            self.cltracer, status = return_val\n\n    def get_internal_function(self, cosmo, function, a):\n        \"\"\"\n        Method to evaluate any internal function of redshift for this tracer.\n\n        Args:\n            cosmo (:obj:`Cosmology`): Cosmology object.\n            function (:obj:`str`): Specifies which function to evaluate. Must\n                be one of\n                    'dndz': number density\n                    'bias': bias\n                    'mag_bias': magnification bias\n                    'red_frac': red fraction\n                    'ia_bias': intrinsic alignment bias\n                    'lensing_win': weak lensing window function\n                    'mag_win': magnification window function\n            a (:obj: float or array-like): list of scale factors at which to\n                evaluate the function.\n\n        Returns:\n            Array of function values at the input scale factors.\n        \"\"\"\n        # Access ccl_cosmology object\n        cosmo_in = cosmo\n        cosmo = cosmo.cosmo\n\n        # Check that specified function type exists\n        if function not in function_types.keys():\n            raise ValueError(\n                \"Internal function type '%s' not recognized.\"\n                % function)\n\n        # Check input types\n        status = 0\n        is_scalar = False\n        if isinstance(a, float):\n            is_scalar = True\n            aarr = np.array([a])\n            na = 1\n        elif isinstance(a, np.ndarray):\n            aarr = a\n            na = a.size\n        else:\n            aarr = a\n            na = len(a)\n\n        # Evaluate function\n        farr, status = lib.clt_fa_vec(cosmo, self.cltracer,\n                                      function_types[function],\n                                      aarr, na, status)\n        check(status, cosmo_in)\n        if is_scalar:\n            return farr[0]\n        else:\n            return farr\n\n    def __del__(self):\n        \"\"\"Free memory associated with CCL_ClTracer object.\n        \"\"\"\n        if hasattr(self, 'has_cltracer'):\n            if self.has_cltracer:\n                lib.cl_tracer_free(self.cltracer)\n\n\nclass NumberCountsTracer(Tracer):\n    \"\"\"A Tracer for galaxy number counts (galaxy clustering).\n\n    Args:\n        cosmo (:obj:`Cosmology`): Cosmology object.\n        has_rsd (bool): Flag for whether the tracer has a\n            redshift-space distortion term.\n        dndz (tuple of arrays): A tuple of arrays (z, N(z))\n            giving the redshift distribution of the objects. The units are\n            arbitrary; N(z) will be normalized to unity.\n        bias (tuple of arrays): A tuple of arrays (z, b(z))\n            giving the galaxy bias.\n        mag_bias (tuple of arrays, optional): A tuple of arrays (z, s(z))\n            giving the magnification bias as a function of redshift. If\n            `None`, the tracer is assumed to not have magnification bias\n            terms. Defaults to None.\n    \"\"\"\n\n    def __init__(self, cosmo, has_rsd, dndz, bias, mag_bias=None):\n        # Call Tracer constructor with appropriate arguments\n        self._build_tracer(\n            cosmo=cosmo, tracer_type=const.CL_TRACER_NC,\n            has_rsd=has_rsd,\n            dndz=dndz, bias=bias, mag_bias=mag_bias,\n            ia_bias=None, red_frac=None)\n\n\nclass WeakLensingTracer(Tracer):\n    \"\"\"A Tracer for weak lensing shear (galaxy shapes).\n\n    Args:\n        cosmo (:obj:`Cosmology`): Cosmology object.\n        dndz (tuple of arrays): A tuple of arrays (z, N(z))\n            giving the redshift distribution of the objects. The units are\n            arbitrary; N(z) will be normalized to unity.\n        ia_bias (tuple of arrays, optional): A tuple of arrays\n            (z, b_IA(z)) giving the intrinsic alignment amplitude b_IA(z).\n            If `None`, the tracer is assumped to not have intrinsic\n            alignments. Defaults to None.\n        red_frac (tuple of arrays,, optional): A tuple of arrays\n            (z, f_red(z)) givng the red fraction of galaxies as a function\n            of redshift. If `None`, then the tracer is assumed to not have\n            a red fraction. Defaults to None.\n    \"\"\"\n\n    def __init__(self, cosmo, dndz, ia_bias=None, red_frac=None):\n        # Call Tracer constructor with appropriate arguments\n        self._build_tracer(\n            cosmo=cosmo, tracer_type=const.CL_TRACER_WL,\n            has_rsd=False,\n            dndz=dndz, bias=None, mag_bias=None,\n            ia_bias=ia_bias, red_frac=red_frac)\n\n\nclass CMBLensingTracer(Tracer):\n    \"\"\"A Tracer for CMB lensing.\n\n    Args:\n        cosmo (:obj:`Cosmology`): Cosmology object.\n        z_source (float): Redshift of source plane for CMB lensing.\n    \"\"\"\n\n    def __init__(self, cosmo, z_source):\n        # Call Tracer constructor with appropriate arguments\n        self._build_tracer(\n            cosmo=cosmo, tracer_type=const.CL_TRACER_CL,\n            has_rsd=False,\n            dndz=None, bias=None, mag_bias=None,\n            ia_bias=None, red_frac=None, z_source=z_source)\n\n\ndef _check_array_params(f_arg):\n    \"\"\"Check whether an argument `f_arg` passed into the constructor of\n    Tracer() is valid.\n\n    If the argument is set to `None`, it will be replaced with a special array\n    that signals to the CCL wrapper that this argument is NULL.\n    \"\"\"\n    if f_arg is None:\n        # Return empty array if argument is None\n        f = NoneArr\n        z_f = NoneArr\n    else:\n        z_f = np.atleast_1d(np.array(f_arg[0], dtype=float))\n        f = np.atleast_1d(np.array(f_arg[1], dtype=float))\n    return z_f, f\n\n\ndef angular_cl(cosmo, cltracer1, cltracer2, ell,\n               l_limber=-1., l_logstep=1.05, l_linstep=20., dchi=3.,\n               dlk=0.003, zmin=0.05, non_limber_method=\"native\"):\n    \"\"\"Calculate the angular (cross-)power spectrum for a pair of tracers.\n\n    Args:\n        cosmo (:obj:`Cosmology`): A Cosmology object.\n        cltracer1, cltracer2 (:obj:`Tracer`): Tracer objects, of any kind.\n        ell (float or array_like): Angular wavenumber(s) at which to evaluate\n            the angular power spectrum.\n        l_limber (float) : Angular wavenumber beyond which Limber's\n            approximation will be used. Defaults to 1.\n        l_logstep (float) : logarithmic step in ell at low multipoles.\n            Defaults to 1.05.\n        l_linstep (float) : linear step in ell at high multipoles.\n            Defaults to 20.\n        dchi (float) : comoving distance step size in non-limber native\n            integrals. Defaults to 3.\n        dlk (float) : logarithmic step for the k non-limber native integral.\n            Defaults to 0.003.\n        zmin (float) : minimal redshift for the integrals. Defualts to 0.05.\n        non_limber_method (str) : non-Limber integration method. Supported:\n            \"native\" and \"angpow\". Defaults to 'native'.\n\n    Returns:\n        float or array_like: Angular (cross-)power spectrum values,\n            :math:`C_\\\\ell`, for the pair of tracers, as a function of\n            :math:`\\\\ell`.\n    \"\"\"\n    # Access ccl_cosmology object\n    cosmo = cosmo.cosmo\n\n    if non_limber_method not in nonlimber_methods.keys():\n        raise ValueError(\n            \"'%s' is not a valid non-Limber integration method.\" %\n            non_limber_method)\n\n    # Access CCL_ClTracer objects\n    clt1 = cltracer1.cltracer\n    clt2 = cltracer2.cltracer\n\n    status = 0\n    # Return Cl values, according to whether ell is an array or not\n    if isinstance(ell, float) or isinstance(ell, int):\n        # Use single-value function\n        cl_one, status = lib.angular_cl_vec(\n            cosmo, clt1, clt2, l_limber, l_logstep, l_linstep, dchi, dlk, zmin,\n            nonlimber_methods[non_limber_method], [ell], 1, status)\n        cl = cl_one[0]\n    elif isinstance(ell, np.ndarray):\n        # Use vectorised function\n        cl, status = lib.angular_cl_vec(\n            cosmo, clt1, clt2, l_limber, l_logstep, l_linstep, dchi, dlk, zmin,\n            nonlimber_methods[non_limber_method], ell, ell.size, status)\n    else:\n        # Use vectorised function\n        cl, status = lib.angular_cl_vec(\n            cosmo, clt1, clt2, l_limber, l_logstep, l_linstep, dchi, dlk, zmin,\n            nonlimber_methods[non_limber_method], ell, len(ell), status)\n    check(status)\n    return cl\n", "meta": {"hexsha": "d98da8aa6d8c1fefd742a15588c42a3346d8416a", "size": 14422, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyccl/cls.py", "max_stars_repo_name": "Russell-Jones-OxPhys/CCL", "max_stars_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyccl/cls.py", "max_issues_repo_name": "Russell-Jones-OxPhys/CCL", "max_issues_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyccl/cls.py", "max_forks_repo_name": "Russell-Jones-OxPhys/CCL", "max_forks_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6253521127, "max_line_length": 79, "alphanum_fraction": 0.5952017751, "include": true, "reason": "import numpy", "num_tokens": 3471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.2909808662149068, "lm_q1q2_score": 0.1713554693753673}}
{"text": "import numba\nimport numpy as np\nimport strax\nfrom immutabledict import immutabledict\nfrom strax.processing.general import _touching_windows\nimport straxen\nfrom .pulse_processing import HITFINDER_OPTIONS, HITFINDER_OPTIONS_he, HE_PREAMBLE\nfrom straxen.get_corrections import is_cmt_option\nfrom .peaklet_classification import PeakletClassification\n\n\nexport, __all__ = strax.exporter()\nFAKE_MERGED_S2_TYPE = -42\n\n\n@export\n@strax.takes_config(\n    strax.Option('peaklet_gap_threshold', default=700, infer_type=False,\n                 help=\"No hits for this many ns triggers a new peak\"),\n    strax.Option('peak_left_extension', default=30, infer_type=False,\n                 help=\"Include this many ns left of hits in peaks\"),\n    strax.Option('peak_right_extension', default=200, infer_type=False,\n                 help=\"Include this many ns right of hits in peaks\"),\n    strax.Option('peak_min_pmts', default=2, infer_type=False,\n                 help=\"Minimum number of contributing PMTs needed to define a peak\"),\n    strax.Option('peak_split_gof_threshold',\n                 # See https://xe1t-wiki.lngs.infn.it/doku.php?id=\n                 # xenon:xenonnt:analysis:strax_clustering_classification\n                 # #natural_breaks_splitting\n                 # for more information\n                 default=(\n                     None,  # Reserved\n                     ((0.5, 1.0), (6.0, 0.4)),\n                     ((2.5, 1.0), (5.625, 0.4))), infer_type=False,\n                 help='Natural breaks goodness of fit/split threshold to split '\n                      'a peak. Specify as tuples of (log10(area), threshold).'),\n    strax.Option('peak_split_filter_wing_width', default=70, infer_type=False,\n                 help='Wing width of moving average filter for '\n                      'low-split natural breaks'),\n    strax.Option('peak_split_min_area', default=40., infer_type=False,\n                 help='Minimum area to evaluate natural breaks criterion. '\n                      'Smaller peaks are not split.'),\n    strax.Option('peak_split_iterations', default=20, infer_type=False,\n                 help='Maximum number of recursive peak splits to do.'),\n    strax.Option('diagnose_sorting', track=False, default=False, infer_type=False,\n                 help=\"Enable runtime checks for sorting and disjointness\"),\n    strax.Option('gain_model', infer_type=False,\n                 help='PMT gain model. Specify as '\n                 '(str(model_config), str(version), nT-->boolean'),\n    strax.Option('tight_coincidence_window_left', default=50, infer_type=False,\n                 help=\"Time range left of peak center to call \"\n                      \"a hit a tight coincidence (ns)\"),\n    strax.Option('tight_coincidence_window_right', default=50, infer_type=False,\n                 help=\"Time range right of peak center to call \"\n                      \"a hit a tight coincidence (ns)\"),\n    strax.Option('n_tpc_pmts', type=int,\n                 help='Number of TPC PMTs'),\n    strax.Option('saturation_correction_on', default=True, infer_type=False,\n                 help='On off switch for saturation correction'),\n    strax.Option('saturation_reference_length', default=100, infer_type=False,\n                 help=\"Maximum number of reference sample used \"\n                      \"to correct saturated samples\"),\n    strax.Option('saturation_min_reference_length', default=20, infer_type=False,\n                 help=\"Minimum number of reference sample used \"\n                      \"to correct saturated samples\"),\n    strax.Option('peaklet_max_duration', default=int(10e6), infer_type=False,\n                 help=\"Maximum duration [ns] of a peaklet\"),\n    strax.Option('channel_map', track=False, type=immutabledict,\n                 help=\"immutabledict mapping subdetector to (min, max) \"\n                      \"channel number.\"),\n    *HITFINDER_OPTIONS,\n)\nclass Peaklets(strax.Plugin):\n    \"\"\"\n    Split records into:\n        -peaklets\n        -lone_hits\n\n    Peaklets are very aggressively split peaks such that we are able\n    to find S1-S2s even if they are close to each other. (S2) Peaks\n    that are split into too many peaklets will be merged later on.\n\n    To get Peaklets from records apply/do:\n        1. Hit finding\n        2. Peak finding\n        3. Peak splitting using the natural breaks algorithm\n        4. Compute the digital sum waveform\n\n    Lone hits are all hits which are outside of any peak. The area of\n    lone_hits includes the left and right hit extension, except the\n    extension overlaps with any peaks or other hits.\n    \"\"\"\n    depends_on = ('records',)\n    provides = ('peaklets', 'lone_hits')\n    data_kind = dict(peaklets='peaklets',\n                     lone_hits='lone_hits')\n    parallel = 'process'\n    compressor = 'zstd'\n\n    __version__ = '0.5.0'\n\n    def infer_dtype(self):\n        return dict(peaklets=strax.peak_dtype(\n                        n_channels=self.config['n_tpc_pmts']),\n                    lone_hits=strax.hit_dtype)\n\n    def setup(self):\n        if self.config['peak_min_pmts'] > 2:\n            # Can fix by re-splitting,\n            raise NotImplementedError(\n                f\"Raising the peak_min_pmts to {self.config['peak_min_pmts']} \"\n                f\"interferes with lone_hit definition. \"\n                f\"See github.com/XENONnT/straxen/issues/295\")\n\n        self.to_pe = straxen.get_correction_from_cmt(self.run_id,\n                                       self.config['gain_model'])\n\n        # Check config of `hit_min_amplitude` and define hit thresholds\n        # if cmt config\n        if is_cmt_option(self.config['hit_min_amplitude']):\n            self.hit_thresholds = straxen.get_correction_from_cmt(self.run_id,\n                self.config['hit_min_amplitude'])\n        # if hitfinder_thresholds config\n        elif isinstance(self.config['hit_min_amplitude'], str):\n            self.hit_thresholds = straxen.hit_min_amplitude(\n                self.config['hit_min_amplitude'])\n        else: # int or array\n            self.hit_thresholds = self.config['hit_min_amplitude']\n            \n        self.channel_range = self.config['channel_map']['tpc']\n\n    def compute(self, records, start, end):\n        r = records\n\n        hits = strax.find_hits(r, min_amplitude=self.hit_thresholds)\n\n        # Remove hits in zero-gain channels\n        # they should not affect the clustering!\n        hits = hits[self.to_pe[hits['channel']] != 0]\n\n        hits = strax.sort_by_time(hits)\n\n        # Use peaklet gap threshold for initial clustering\n        # based on gaps between hits\n        peaklets = strax.find_peaks(\n            hits, self.to_pe,\n            gap_threshold=self.config['peaklet_gap_threshold'],\n            left_extension=self.config['peak_left_extension'],\n            right_extension=self.config['peak_right_extension'],\n            min_channels=self.config['peak_min_pmts'],\n            result_dtype=self.dtype_for('peaklets'),\n            max_duration=self.config['peaklet_max_duration'],\n        )\n\n        # Make sure peaklets don't extend out of the chunk boundary\n        # This should be very rare in normal data due to the ADC pretrigger\n        # window.\n        self.clip_peaklet_times(peaklets, start, end)\n\n        # Get hits outside peaklets, and store them separately.\n        # fully_contained is OK provided gap_threshold > extension,\n        # which is asserted inside strax.find_peaks.\n        is_lone_hit = strax.fully_contained_in(hits, peaklets) == -1\n        lone_hits = hits[is_lone_hit]\n        strax.integrate_lone_hits(\n            lone_hits, records, peaklets,\n            save_outside_hits=(self.config['peak_left_extension'],\n                               self.config['peak_right_extension']),\n            n_channels=len(self.to_pe))\n\n        # Compute basic peak properties -- needed before natural breaks\n        hits = hits[~is_lone_hit]\n        # Define regions outside of peaks such that _find_hit_integration_bounds\n        # is not extended beyond a peak.\n        outside_peaks = self.create_outside_peaks_region(peaklets, start, end)\n        strax.find_hit_integration_bounds(\n            hits, outside_peaks, records,\n            save_outside_hits=(self.config['peak_left_extension'],\n                               self.config['peak_right_extension']),\n            n_channels=len(self.to_pe),\n            allow_bounds_beyond_records=True,\n        )\n\n        # Transform hits to hitlets for naming conventions. A hit refers\n        # to the central part above threshold a hitlet to the entire signal\n        # including the left and right extension.\n        # (We are not going to use the actual hitlet data_type here.)\n        hitlets = hits\n        del hits\n\n        hitlet_time_shift = (hitlets['left'] - hitlets['left_integration']) * hitlets['dt']\n        hitlets['time'] = hitlets['time'] - hitlet_time_shift\n        hitlets['length'] = (hitlets['right_integration'] - hitlets['left_integration'])\n        hitlets = strax.sort_by_time(hitlets)\n        rlinks = strax.record_links(records)\n\n        strax.sum_waveform(peaklets, hitlets, r, rlinks, self.to_pe)\n\n        strax.compute_widths(peaklets)\n\n        # Split peaks using low-split natural breaks;\n        # see https://github.com/XENONnT/straxen/pull/45\n        # and https://github.com/AxFoundation/strax/pull/225\n        peaklets = strax.split_peaks(\n            peaklets, hitlets, r, rlinks, self.to_pe,\n            algorithm='natural_breaks',\n            threshold=self.natural_breaks_threshold,\n            split_low=True,\n            filter_wing_width=self.config['peak_split_filter_wing_width'],\n            min_area=self.config['peak_split_min_area'],\n            do_iterations=self.config['peak_split_iterations'])\n\n        # Saturation correction using non-saturated channels\n        # similar method used in pax\n        # see https://github.com/XENON1T/pax/pull/712\n        # Cases when records is not writeable for unclear reason\n        # only see this when loading 1T test data\n        # more details on https://numpy.org/doc/stable/reference/generated/numpy.ndarray.flags.html\n        if not r['data'].flags.writeable:\n            r = r.copy()\n\n        if self.config['saturation_correction_on']:\n            peak_list = peak_saturation_correction(\n                r, rlinks, peaklets, hitlets, self.to_pe,\n                reference_length=self.config['saturation_reference_length'],\n                min_reference_length=self.config['saturation_min_reference_length'])\n\n            # Compute the width again for corrected peaks\n            strax.compute_widths(peaklets, select_peaks_indices=peak_list)\n\n        # Compute tight coincidence level.\n        # Making this a separate plugin would\n        # (a) doing hitfinding yet again (or storing hits)\n        # (b) increase strax memory usage / max_messages,\n        #     possibly due to its currently primitive scheduling.\n        hit_max_times = np.sort(\n            hitlets['time']\n            + hitlets['dt'] * hit_max_sample(records, hitlets)\n            + hitlet_time_shift  # add time shift again to get correct maximum\n        )\n        peaklet_max_times = (\n                peaklets['time']\n                + np.argmax(peaklets['data'], axis=1) * peaklets['dt'])\n        tight_coincidence, tight_coincidence_channel = get_tight_coin(\n            hit_max_times,\n            hitlets['channel'],\n            peaklet_max_times,\n            self.config['tight_coincidence_window_left'],\n            self.config['tight_coincidence_window_right'],\n            self.channel_range)\n\n        peaklets['tight_coincidence'] = tight_coincidence\n        peaklets['tight_coincidence_channel'] = tight_coincidence_channel\n\n        if self.config['diagnose_sorting'] and len(r):\n            assert np.diff(r['time']).min(initial=1) >= 0, \"Records not sorted\"\n            assert np.diff(hitlets['time']).min(initial=1) >= 0, \"Hits/Hitlets not sorted\"\n            assert np.all(peaklets['time'][1:]\n                          >= strax.endtime(peaklets)[:-1]), \"Peaks not disjoint\"\n\n        # Update nhits of peaklets:\n        counts = strax.touching_windows(hitlets, peaklets)\n        counts = np.diff(counts, axis=1).flatten()\n        peaklets['n_hits'] = counts\n\n        return dict(peaklets=peaklets,\n                    lone_hits=lone_hits)\n\n    def natural_breaks_threshold(self, peaks):\n        rise_time = -peaks['area_decile_from_midpoint'][:, 1]\n\n        # This is ~1 for an clean S2, ~0 for a clean S1,\n        # and transitions gradually in between.\n        f_s2 = 8 * np.log10(rise_time.clip(1, 1e5) / 100)\n        f_s2 = 1 / (1 + np.exp(-f_s2))\n\n        log_area = np.log10(peaks['area'].clip(1, 1e7))\n        thresholds = self.config['peak_split_gof_threshold']\n        return (\n            f_s2 * np.interp(\n                log_area,\n                *np.transpose(thresholds[2]))\n            + (1 - f_s2) * np.interp(\n                log_area,\n                *np.transpose(thresholds[1])))\n\n    @staticmethod\n    @numba.njit(nogil=True, cache=True)\n    def clip_peaklet_times(peaklets, start, end):\n        for p in peaklets:\n            if p['time'] < start:\n                p['time'] = start\n            if strax.endtime(p) > end:\n                p['length'] = (end - p['time']) // p['dt']\n\n    @staticmethod\n    def create_outside_peaks_region(peaklets, start, end):\n        \"\"\"\n        Creates time intervals which are outside peaks.\n\n        :param peaklets: Peaklets for which intervals should be computed.\n        :param start: Chunk start\n        :param end: Chunk end\n        :return: array of strax.time_fields dtype.\n        \"\"\"\n        if not len(peaklets):\n            return np.zeros(0, dtype=strax.time_fields)\n        \n        outside_peaks = np.zeros(len(peaklets) + 1,\n                                 dtype=strax.time_fields)\n        \n        outside_peaks[0]['time'] = start\n        outside_peaks[0]['endtime'] = peaklets[0]['time']\n        outside_peaks[1:-1]['time'] = strax.endtime(peaklets[:-1])\n        outside_peaks[1:-1]['endtime'] = peaklets['time'][1:]\n        outside_peaks[-1]['time'] = strax.endtime(peaklets[-1])\n        outside_peaks[-1]['endtime'] = end\n        return outside_peaks\n\n\n@numba.jit(nopython=True, nogil=True, cache=True)\ndef peak_saturation_correction(records, rlinks, peaks, hitlets, to_pe,\n                               reference_length=100,\n                               min_reference_length=20,\n                               use_classification=False,\n                               ):\n    \"\"\"Correct the area and per pmt area of peaks from saturation\n    :param records: Records\n    :param rlinks: strax.record_links of corresponding records.\n    :param peaks: Peaklets / Peaks\n    :param hitlets: Hitlets found in records to build peaks.\n        (Hitlets are hits including the left/right extension)\n    :param to_pe: adc to PE conversion (length should equal number of PMTs)\n    :param reference_length: Maximum number of reference sample used\n    to correct saturated samples\n    :param min_reference_length: Minimum number of reference sample used\n    to correct saturated samples\n    :param use_classification: Option of using classification to pick only S2\n    \"\"\"\n\n    if not len(records):\n        return\n    if not len(peaks):\n        return\n\n    # Search for peaks with saturated channels\n    mask = peaks['n_saturated_channels'] > 0\n    if use_classification:\n        mask &= peaks['type'] == 2\n    peak_list = np.where(mask)[0]\n    # Look up records that touch each peak\n    record_ranges = _touching_windows(\n        records['time'],\n        strax.endtime(records),\n        peaks[peak_list]['time'],\n        strax.endtime(peaks[peak_list]))\n\n    # Create temporary arrays for calculation\n    dt = records[0]['dt']\n    n_channels = len(peaks[0]['saturated_channel'])\n    len_buffer = np.max(peaks['length'] * peaks['dt']) // dt + 1\n    max_nrecord = len_buffer // len(records[0]['data']) + 1\n\n    # Buff the sum wf [pe] of non-saturated channels\n    b_sumwf = np.zeros(len_buffer, dtype=np.float32)\n    # Buff the records 'data' [ADC] in saturated channels\n    b_pulse = np.zeros((n_channels, len_buffer), dtype=np.int16)\n    # Buff the corresponding record index of saturated channels\n    b_index = np.zeros((n_channels, max_nrecord), dtype=np.int64)\n\n    # Main\n    for ix, peak_i in enumerate(peak_list):\n        # reset buffers\n        b_sumwf[:] = 0\n        b_pulse[:] = 0\n        b_index[:] = -1\n\n        p = peaks[peak_i]\n        channel_saturated = p['saturated_channel'] > 0\n\n        for record_i in range(record_ranges[ix][0], record_ranges[ix][1]):\n            r = records[record_i]\n            r_slice, b_slice = strax.overlap_indices(\n                r['time'] // dt, r['length'],\n                p['time'] // dt, p['length'] * p['dt'] // dt)\n\n            ch = r['channel']\n            if channel_saturated[ch]:\n                b_pulse[ch, slice(*b_slice)] += r['data'][slice(*r_slice)]\n                b_index[ch, np.argmin(b_index[ch])] = record_i\n            else:\n                b_sumwf[slice(*b_slice)] += r['data'][slice(*r_slice)] \\\n                    * to_pe[ch]\n\n        _peak_saturation_correction_inner(\n            channel_saturated, records, p,\n            to_pe, b_sumwf, b_pulse, b_index,\n            reference_length, min_reference_length)\n\n        # Back track sum wf downsampling\n        peaks[peak_i]['length'] = p['length'] * p['dt'] / dt\n        peaks[peak_i]['dt'] = dt\n\n    strax.sum_waveform(peaks, hitlets, records, rlinks, to_pe, peak_list)\n    return peak_list\n\n\n@numba.jit(nopython=True, nogil=True, cache=True)\ndef _peak_saturation_correction_inner(channel_saturated, records, p,\n                                      to_pe, b_sumwf, b_pulse, b_index,\n                                      reference_length=100,\n                                      min_reference_length=20,\n                                      ):\n    \"\"\"Would add a third level loop in peak_saturation_correction\n    Which is not ideal for numba, thus this function is written\n    :param channel_saturated: (bool, n_channels)\n    :param p: One peak/peaklet\n    :param to_pe: adc to PE conversion (length should equal number of PMTs)\n    :param b_sumwf, b_pulse, b_index: Filled buffers\n    \"\"\"\n    dt = records['dt'][0]\n    n_channels = len(channel_saturated)\n\n    for ch in range(n_channels):\n        if not channel_saturated[ch]:\n            continue\n        b = b_pulse[ch]\n        r0 = records[b_index[ch][0]]\n\n        # Define the reference region as reference_length before the first saturation point\n        # unless there are not enough samples\n        bl = np.inf\n        for record_i in b_index[ch]:\n            if record_i == -1:\n                break\n            bl = min(bl, records['baseline'][record_i])\n\n        s0 = np.argmax(b >= np.int16(bl))\n        ref = slice(max(0, s0-reference_length), s0)\n\n        if (b[ref] * to_pe[ch] > 1).sum() < min_reference_length:\n            # the pulse is saturated, but there are not enough reference samples to get a good ratio\n            # This actually distinguished between S1 and S2 and will only correct S2 signals\n            continue\n        if (b_sumwf[ref] > 1).sum() < min_reference_length:\n            # the same condition applies to the waveform model\n            continue\n        if np.sum(b[ref]) * to_pe[ch] / np.sum(b_sumwf[ref]) > 1:\n            # The pulse is saturated, but insufficient information is available in the other channels\n            # to reliably reconstruct it\n            continue\n\n        scale = np.sum(b[ref]) / np.sum(b_sumwf[ref])\n\n        # Loop over the record indices of the saturated channel (saved in b_index buffer)\n        for record_i in b_index[ch]:\n            if record_i == -1:\n                break\n            r = records[record_i]\n            r_slice, b_slice = strax.overlap_indices(\n                r['time'] // dt, r['length'],\n                p['time'] // dt + s0,  p['length'] * p['dt'] // dt - s0)\n\n            if r_slice[1] == r_slice[0]:  # This record proceeds saturation\n                continue\n            b_slice = b_slice[0] + s0, b_slice[1] + s0\n\n            # First is finding the highest point in the desaturated record\n            # because we need to bit shift the whole record if it exceeds int16 range\n            apax = scale * max(b_sumwf[slice(*b_slice)])\n\n            if np.int32(apax) >= 2**15:  # int16(2**15) is -2**15\n                bshift = int(np.floor(np.log2(apax) - 14))\n\n                tmp = r['data'].astype(np.int32)\n                tmp[slice(*r_slice)] = b_sumwf[slice(*b_slice)] * scale\n\n                r['area'] = np.sum(tmp)  # Auto covert to int64\n                r['data'][:] = np.right_shift(tmp, bshift)\n                r['amplitude_bit_shift'] += bshift\n            else:\n                r['data'][slice(*r_slice)] = b_sumwf[slice(*b_slice)] * scale\n                r['area'] = np.sum(r['data'])\n\n\n@export\n@strax.takes_config(\n    strax.Option('n_he_pmts', track=False, default=752, infer_type=False,\n                 help=\"Maximum channel of the he channels\"),\n    strax.Option('he_channel_offset', track=False, default=500, infer_type=False,\n                 help=\"Minimum channel number of the he channels\"),\n    strax.Option('le_to_he_amplification', default=20, track=True, infer_type=False,\n                 help=\"Difference in amplification between low energy and high \"\n                      \"energy channels\"),\n    strax.Option('peak_min_pmts_he', default=2, infer_type=False,\n                 child_option=True, parent_option_name='peak_min_pmts',\n                 track=True,\n                 help=\"Minimum number of contributing PMTs needed to define a peak\"),\n    strax.Option('saturation_correction_on_he', default=False, infer_type=False,\n                 child_option=True, parent_option_name='saturation_correction_on',\n                 track=True,\n                 help='On off switch for saturation correction for High Energy'\n                      ' channels'),\n    *HITFINDER_OPTIONS_he\n)\nclass PeakletsHighEnergy(Peaklets):\n    __doc__ = HE_PREAMBLE + Peaklets.__doc__\n    depends_on = 'records_he'\n    provides = 'peaklets_he'\n    data_kind = 'peaklets_he'\n    __version__ = '0.0.2'\n    child_plugin = True\n    save_when = strax.SaveWhen.TARGET\n\n    def infer_dtype(self):\n        return strax.peak_dtype(n_channels=self.config['n_he_pmts'])\n\n    def setup(self):\n        self.to_pe = straxen.get_correction_from_cmt(self.run_id,\n                                       self.config['gain_model'])\n\n        buffer_pmts = np.zeros(self.config['he_channel_offset'])\n        self.to_pe = np.concatenate((buffer_pmts, self.to_pe))\n        self.to_pe *= self.config['le_to_he_amplification']\n\n        # Check config of `hit_min_amplitude_he` and define hit thresholds\n        # if cmt config\n        if is_cmt_option(self.config['hit_min_amplitude_he']):\n            self.hit_thresholds = straxen.get_correction_from_cmt(self.run_id,\n                self.config['hit_min_amplitude_he'])\n        # if hitfinder_thresholds config\n        elif isinstance(self.config['hit_min_amplitude_he'], str):\n            self.hit_thresholds = straxen.hit_min_amplitude(\n                self.config['hit_min_amplitude_he'])\n        else: # int or array\n            self.hit_thresholds = self.config['hit_min_amplitude_he']\n            \n        self.channel_range = self.config['channel_map']['he']\n\n    def compute(self, records_he, start, end):\n        result = super().compute(records_he, start, end)\n        return result['peaklets']\n\n@export\nclass PeakletClassificationHighEnergy(PeakletClassification):\n    __doc__ = HE_PREAMBLE + PeakletClassification.__doc__\n    provides = 'peaklet_classification_he'\n    depends_on = ('peaklets_he',)\n    __version__ = '0.0.2'\n    child_plugin = True\n\n    def compute(self, peaklets_he):\n        return super().compute(peaklets_he)\n\n\n@export\n@strax.takes_config(\n    strax.Option('s2_merge_max_duration', default=50_000, infer_type=False,\n                 help=\"Do not merge peaklets at all if the result would be a peak \"\n                      \"longer than this [ns]\"),\n    strax.Option('s2_merge_gap_thresholds', default=((1.7, 2.65e4), (4.0, 2.6e3), (5.0, 0.)),\n                 infer_type=False,\n                 help=\"Points to define maximum separation between peaklets to allow \"\n                      \"merging [ns] depending on log10 area of the merged peak\\n\"\n                      \"where the gap size of the first point is the maximum gap to allow merging\"\n                      \"and the area of the last point is the maximum area to allow merging. \"\n                      \"The format is ((log10(area), max_gap), (..., ...), (..., ...))\"\n                 ),\n    strax.Option('gain_model', infer_type=False,\n                 help='PMT gain model. Specify as '\n                      '(str(model_config), str(version), nT-->boolean'),\n    strax.Option('merge_without_s1', default=True, infer_type=False,\n                 help=\"If true, S1s will be igored during the merging. \"\n                      \"It's now possible for a S1 to be inside a S2 post merging\"),\n)\nclass MergedS2s(strax.OverlapWindowPlugin):\n    \"\"\"\n    Merge together peaklets if peak finding favours that they would\n    form a single peak instead.\n    \"\"\"\n    depends_on = ('peaklets', 'peaklet_classification', 'lone_hits')\n    data_kind = 'merged_s2s'\n    provides = 'merged_s2s'\n    __version__ = '0.4.2'\n\n    def setup(self):\n        self.to_pe = straxen.get_correction_from_cmt(self.run_id,\n                                                     self.config['gain_model'])\n\n    def infer_dtype(self):\n        # wrong order\n        dtype = (strax.unpack_dtype(self.deps['peaklets'].dtype_for('peaklets'))\n                 +[(('Bayes peak classification type', 'type_bayes'), np.dtype('i1'))]\n                 +[(('S1 ln probability', 's1_prob'), np.dtype('<f4'))]\n                 +[(('S2 ln probability', 's2_prob'), np.dtype('<f4'))]\n                )     \n        tocount = len(dtype)        \n        # shamless hack  \n        order = [0, 1, 2, 3, 4, tocount-3, tocount-2, tocount-1, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]\n        dtype = [dtype[i] for i in order]\n        return  dtype\n    \n    def get_window_size(self):\n        return 5 * (int(self.config['s2_merge_gap_thresholds'][0][1])\n                    + self.config['s2_merge_max_duration'])\n\n    def compute(self, peaklets, lone_hits):\n        if self.config['merge_without_s1']:\n            peaklets = peaklets[peaklets['type'] != 1]\n\n        if len(peaklets) <= 1:\n            return np.zeros(0, dtype=peaklets.dtype)\n\n        gap_thresholds = self.config['s2_merge_gap_thresholds']\n        max_gap = gap_thresholds[0][1]\n        max_area = 10 ** gap_thresholds[-1][0]\n\n        if max_gap < 0:\n            # Do not merge at all\n            return np.zeros(0, dtype=peaklets.dtype)\n        else:\n            # Max gap and area should be set by the gap thresholds\n            # to avoid contradictions\n            start_merge_at, end_merge_at = self.get_merge_instructions(\n                peaklets['time'], strax.endtime(peaklets),\n                areas=peaklets['area'],\n                types=peaklets['type'],\n                gap_thresholds=gap_thresholds,\n                max_duration=self.config['s2_merge_max_duration'],\n                max_gap=max_gap,\n                max_area=max_area,\n            )\n            merged_s2s = strax.merge_peaks(\n                peaklets,\n                start_merge_at, end_merge_at,\n                max_buffer=int(self.config['s2_merge_max_duration']//np.gcd.reduce(peaklets['dt'])),\n            )\n            merged_s2s['type'] = 2\n            \n            # Updated time and length of lone_hits and sort again:\n            lh = np.copy(lone_hits)\n            del lone_hits\n            lh_time_shift = (lh['left'] - lh['left_integration']) *lh['dt']\n            lh['time'] = lh['time'] - lh_time_shift\n            lh['length'] = (lh['right_integration'] - lh['left_integration'])\n            lh = strax.sort_by_time(lh)\n            strax.add_lone_hits(merged_s2s, lh, self.to_pe)\n\n            strax.compute_widths(merged_s2s)\n\n        return merged_s2s\n\n    @staticmethod\n    @numba.njit(cache=True, nogil=True)\n    def get_merge_instructions(\n            peaklet_starts, peaklet_ends, areas, types,\n            gap_thresholds, max_duration, max_gap, max_area):\n        \"\"\"\n        Finding the group of peaklets to merge. To do this start with the\n        smallest gaps and keep merging until the new, merged S2 has such a\n        large area or gap to adjacent peaks that merging is not required\n        anymore.\n        see https://github.com/XENONnT/straxen/pull/548 and https://github.com/XENONnT/straxen/pull/568\n\n        :returns: list of the first index of peaklet to be merged and\n        list of the exclusive last index of peaklet to be merged\n        \"\"\"\n\n        peaklet_gaps = peaklet_starts[1:] - peaklet_ends[:-1]\n        peaklet_start_index = np.arange(len(peaklet_starts))\n        peaklet_end_index = np.arange(len(peaklet_starts))\n\n        for gap_i in np.argsort(peaklet_gaps):\n            start_idx = peaklet_start_index[gap_i]\n            inclusive_end_idx = peaklet_end_index[gap_i + 1]\n            sum_area = np.sum(areas[start_idx:inclusive_end_idx + 1])\n            this_gap = peaklet_gaps[gap_i]\n\n            if inclusive_end_idx < start_idx:\n                raise ValueError('Something went wrong, left is bigger then right?!')\n\n            if this_gap > max_gap:\n                break\n            if sum_area > max_area:\n                # For very large S2s, we assume that natural breaks is taking care\n                continue\n            if (sum_area > 0) and (\n                    this_gap > merge_s2_threshold(np.log10(sum_area),\n                                                  gap_thresholds)):\n                # The merged peak would be too large\n                continue\n\n            peak_duration = (peaklet_ends[inclusive_end_idx] - peaklet_starts[start_idx])\n            if peak_duration >= max_duration:\n                continue\n\n            # Merge gap in other words this means p @ gap_i and p @gap_i + 1 share the same\n            # start, end and area:\n            peaklet_start_index[start_idx:inclusive_end_idx + 1] = peaklet_start_index[start_idx]\n            peaklet_end_index[start_idx:inclusive_end_idx + 1] = peaklet_end_index[inclusive_end_idx]\n\n        start_merge_at = np.unique(peaklet_start_index)\n        end_merge_at = np.unique(peaklet_end_index)\n        if not len(start_merge_at) == len(end_merge_at):\n            raise ValueError('inconsistent start and end merge instructions')\n\n        merge_start, merge_stop_exclusive = _filter_s1_starts(\n            start_merge_at, types, end_merge_at)\n\n        return merge_start, merge_stop_exclusive\n\n\n@numba.njit(cache=True, nogil=True)\ndef _filter_s1_starts(start_merge_at, types, end_merge_at):\n    for start_merge_idx, _ in enumerate(start_merge_at):\n        while types[start_merge_at[start_merge_idx]] != 2:\n            if end_merge_at[start_merge_idx] - start_merge_at[start_merge_idx] <= 1:\n                break\n            start_merge_at[start_merge_idx] += 1\n\n    start_merge_with_s2 = types[start_merge_at] == 2\n    merges_at_least_two_peaks = end_merge_at - start_merge_at >= 1\n\n    keep_merges = start_merge_with_s2 & merges_at_least_two_peaks\n    return start_merge_at[keep_merges], end_merge_at[keep_merges] + 1\n\n\n@numba.njit(cache=True, nogil=True)\ndef merge_s2_threshold(log_area, gap_thresholds):\n    \"\"\"Return gap threshold for log_area of the merged S2\n    with linear interpolation given the points in gap_thresholds\n    :param log_area: Log 10 area of the merged S2\n    :param gap_thresholds: tuple (n, 2) of fix points for interpolation\n    \"\"\"\n    for i, (a1, g1) in enumerate(gap_thresholds):\n        if log_area < a1:\n            if i == 0:\n                return g1\n            a0, g0 = gap_thresholds[i - 1]\n            return (log_area - a0) * (g1 - g0) / (a1 - a0) + g0\n    return gap_thresholds[-1][1]\n\n\n@export\nclass MergedS2sHighEnergy(MergedS2s):\n    __doc__ = HE_PREAMBLE + MergedS2s.__doc__\n    depends_on = ('peaklets_he', 'peaklet_classification_he')\n    data_kind = 'merged_s2s_he'\n    provides = 'merged_s2s_he'\n    __version__ = '0.0.1'\n    child_plugin = True\n\n    def infer_dtype(self):\n        return strax.unpack_dtype(self.deps['peaklets_he'].dtype_for('peaklets_he'))\n\n    def compute(self, peaklets_he):\n        # There are not any lone hits for the high energy channel, \n        #  so create a dummy for the compute method.\n        lone_hits = np.zeros(0, dtype=strax.hit_dtype)\n        return super().compute(peaklets_he, lone_hits)\n\n\n@export\n@strax.takes_config(\n    strax.Option('diagnose_sorting', track=False, default=False, infer_type=False,\n                 help=\"Enable runtime checks for sorting and disjointness\"),\n    strax.Option('merge_without_s1', default=True, infer_type=False,\n                 help=\"If true, S1s will be igored during the merging. \"\n                      \"It's now possible for a S1 to be inside a S2 post merging\"),\n)\nclass Peaks(strax.Plugin):\n    \"\"\"\n    Merge peaklets and merged S2s such that we obtain our peaks\n    (replacing all peaklets that were later re-merged as S2s). As this\n    step is computationally trivial, never save this plugin.\n    \"\"\"\n    depends_on = ('peaklets', 'peaklet_classification', 'merged_s2s')\n    data_kind = 'peaks'\n    provides = 'peaks'\n    parallel = True\n    save_when = strax.SaveWhen.EXPLICIT\n\n    __version__ = '0.1.2'\n\n    def infer_dtype(self):\n        # wrong order\n        dtype = (strax.unpack_dtype(self.deps['peaklets'].dtype_for('peaklets'))\n                 +[(('Bayes peak classification type', 'type_bayes'), np.dtype('i1'))]\n                 +[(('S1 ln probability', 's1_prob'), np.dtype('<f4'))]\n                 +[(('S2 ln probability', 's2_prob'), np.dtype('<f4'))]\n                )     \n        tocount = len(dtype)        \n        # shamless hack  \n        order = [0, 1, 2, 3, 4, tocount-3, tocount-2, tocount-1, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]\n        dtype = [dtype[i] for i in order]\n        return  dtype\n\n    def compute(self, peaklets, merged_s2s):\n        # Remove fake merged S2s from dirty hack, see above\n        merged_s2s = merged_s2s[merged_s2s['type'] != FAKE_MERGED_S2_TYPE]\n        \n        if self.config['merge_without_s1']:\n            is_s1 = peaklets['type'] == 1\n            peaks = strax.replace_merged(peaklets[~is_s1], merged_s2s)\n            peaks = strax.sort_by_time(np.concatenate([peaklets[is_s1],\n                                                       peaks]))\n        else:\n            peaks = strax.replace_merged(peaklets, merged_s2s)\n\n        if self.config['diagnose_sorting']:\n            assert np.all(np.diff(peaks['time']) >= 0), \"Peaks not sorted\"\n            if self.config['merge_without_s1']:\n                to_check = peaks['type'] != 1\n            else:\n                to_check = peaks['type'] != FAKE_MERGED_S2_TYPE\n\n            assert np.all(peaks['time'][to_check][1:]\n                            >= strax.endtime(peaks)[to_check][:-1]), \"Peaks not disjoint\"\n        return peaks\n\n\n@export\nclass PeaksHighEnergy(Peaks):\n    __doc__ = HE_PREAMBLE + Peaks.__doc__\n    depends_on = ('peaklets_he', 'peaklet_classification_he', 'merged_s2s_he')\n    data_kind = 'peaks_he'\n    provides = 'peaks_he'\n    __version__ = '0.0.1'\n    child_ends_with = '_he'\n\n    def infer_dtype(self):\n        return self.deps['peaklets_he'].dtype_for('peaklets')\n\n    def compute(self, peaklets_he, merged_s2s_he):\n        return super().compute(peaklets_he, merged_s2s_he)\n\n\n@numba.jit(nopython=True, nogil=True, cache=True)\ndef get_tight_coin(hit_max_times, hit_channel, peak_max_times, left, right,\n                   channels=(0, 493)):\n    \"\"\"Calculates the tight coincidence based on hits and PMT channels.\n\n    Defined by number of hits within a specified time range of the\n    the peak's maximum amplitude.\n    Imitates tight_coincidence variable in pax:\n    github.com/XENON1T/pax/blob/master/pax/plugins/peak_processing/BasicProperties.py\n\n    :param hit_max_times: Time of the hit amplitude in ns.\n    :param hit_channel: PMT channels of the hits\n    :param peak_max_times: Time of the peaks maximum in ns.\n    :param left: Left boundary in which we search for the tight\n        coincidence in ns.\n    :param right: Right boundary in which we search for the tight\n        coincidence in ns.\n    :param channel_range: (min/max) channel for the corresponding detector.\n\n    :returns: n_coin_hit, n_coin_channel of length peaks containing the\n        tight coincidence.\n    \"\"\"\n    left_hit_i = 0\n    n_coin_hit = np.zeros(len(peak_max_times), dtype=np.int16)\n    n_coin_channel = np.zeros(len(peak_max_times), dtype=np.int16)\n    start_ch, end_ch = channels\n    channels_seen = np.zeros(end_ch-start_ch+1, dtype=np.bool_)\n\n    # loop over peaks\n    for p_i, p_t in enumerate(peak_max_times):\n        channels_seen[:] = 0\n        # loop over hits starting from the last one we left at\n        for left_hit_i in range(left_hit_i, len(hit_max_times)):\n\n            # if the hit is in the window, its a tight coin\n            d = hit_max_times[left_hit_i] - p_t\n            if (-left <= d) & (d <= right):\n                n_coin_hit[p_i] += 1\n                channels_seen[hit_channel[left_hit_i]-start_ch] = 1\n\n            # stop the loop when we know we're outside the range\n            if d > right:\n                n_coin_channel[p_i] = np.sum(channels_seen)\n                break\n        \n        # Add channel information in case there are no hits beyond \n        # the last peak:\n        n_coin_channel[p_i] = np.sum(channels_seen)\n\n    return n_coin_hit, n_coin_channel\n\n\n@numba.njit(cache=True, nogil=True)\ndef hit_max_sample(records, hits):\n    \"\"\"Return the index of the maximum sample for hits\"\"\"\n    result = np.zeros(len(hits), dtype=np.int16)\n    for i, h in enumerate(hits):\n        r = records[h['record_i']]\n        w = r['data'][h['left']:h['right']]\n        result[i] = np.argmax(w)\n    return result\n", "meta": {"hexsha": "6a3947c94a76f630cd9430b840d14deee24a1fc7", "size": 38164, "ext": "py", "lang": "Python", "max_stars_repo_path": "straxen/plugins/peaklet_processing.py", "max_stars_repo_name": "ahiguera-mx/straxen", "max_stars_repo_head_hexsha": "25b92dd4f18b51700e6df83b230e58ec3bbb7163", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "straxen/plugins/peaklet_processing.py", "max_issues_repo_name": "ahiguera-mx/straxen", "max_issues_repo_head_hexsha": "25b92dd4f18b51700e6df83b230e58ec3bbb7163", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-10-08T22:52:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-12T07:48:48.000Z", "max_forks_repo_path": "straxen/plugins/peaklet_processing.py", "max_forks_repo_name": "ahiguera-mx/straxen", "max_forks_repo_head_hexsha": "25b92dd4f18b51700e6df83b230e58ec3bbb7163", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4516129032, "max_line_length": 107, "alphanum_fraction": 0.6140079656, "include": true, "reason": "import numpy,import numba", "num_tokens": 9223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.2689414330889797, "lm_q1q2_score": 0.17132397478936556}}
{"text": "\"\"\"Compute positions from an ephemeris installed as a Python package.\"\"\"\n\nimport os\nimport numpy as np\n\n\nclass DateError(ValueError):\n    \"\"\"Date input is outside the range covered by the ephemeris.\"\"\"\n\n\nclass Ephemeris(object):\n    \"\"\"A JPL planetary ephemeris that, given dates, computes positions.\"\"\"\n\n    def __init__(self, module):\n        self.name = module.__name__.upper()\n        self.dirpath = os.path.dirname(module.__file__)\n        self.names = tuple(sorted(\n            name.split('-')[-1].split('.')[0]\n            for name in os.listdir(self.dirpath)\n            if not name.startswith('constants') and name.endswith('.npy')\n            ))\n        path = self.path('constants.npy')\n        self.__dict__.update((k.decode('ascii'), v) for k, v in np.load(path))\n        self.earth_share = 1.0 / (1.0 + self.EMRAT)\n        self.moon_share = self.EMRAT / (1.0 + self.EMRAT)\n        self.sets = {}\n\n    def path(self, filename):\n        \"\"\"Compute the path to a particular file in the ephemeris.\"\"\"\n        return os.path.join(self.dirpath, filename)\n\n    def load(self, name):\n        \"\"\"Load the polynomial series for `name` and return it.\"\"\"\n        s = self.sets.get(name)\n        if s is None:\n            self.sets[name] = s = np.load(self.path('jpl-%s.npy' % name))\n        return s\n\n    def position(self, name, tdb, tdb2=0.0):\n        \"\"\"Compute the position of `name` at time ``tdb [+ tdb2]``.\n\n        The position is returned as a NumPy array ``[x y z]``.\n\n        The barycentric dynamical time `tdb` argument should be a float.\n        If there are many dates you want computed, then make `tdb` an\n        array, which is more efficient than calling this method multiple\n        times; the return value will be a two-dimensional array giving a\n        row of values for each coordinate.\n\n        For extra precision, the time can be split into two floats; a\n        popular choice is to use `tdb` for the integer or half-integer\n        date, and `tdb2` to hold the remaining fraction.\n\n        Consult the `names` attribute of this ephemeris for the values\n        of `name` it supports, such as ``'mars'`` or ``'earthmoon'``.\n\n        \"\"\"\n        bundle = self.compute_bundle(name, tdb, tdb2)\n        return self.position_from_bundle(bundle)\n\n    def position_and_velocity(self, name, tdb, tdb2=0.0):\n        \"\"\"Compute the position and velocity of `name` at ``tdb [+ tdb2]``.\n\n        The position and velocity are returned in a 2-tuple::\n\n            ([x y z], [xdot ydot zdot])\n\n        The barycentric dynamical time `tdb` argument should be a float.\n        If there are many dates you want computed, then make `tdb` an\n        array, which is more efficient than calling this method multiple\n        times; the return values will be two-dimensional arrays giving a\n        row of values for each coordinate.\n\n        For extra precision, the time can be split into two floats; a\n        popular choice is to use `tdb` for the integer or half-integer\n        date, and `tdb2` to hold the remaining fraction.\n\n        Consult the `names` attribute of this ephemeris for the values\n        of `name` it supports, such as ``'mars'`` or ``'earthmoon'``.\n\n        \"\"\"\n        bundle = self.compute_bundle(name, tdb, tdb2)\n        position = self.position_from_bundle(bundle)\n        velocity = self.velocity_from_bundle(bundle)\n        return position, velocity\n\n    def compute(self, name, tdb):\n        \"\"\"Legacy routine that concatenates position and velocity vectors.\n\n        This routine is deprecated.  Use the methods `position()` and\n        `position_and_velocity()` instead.  This method follows the same\n        calling convention, but incurs extra copy operations in order to\n        return a single NumPy array::\n\n            [x y z xdot ydot zdot]\n\n        \"\"\"\n        bundle = self.compute_bundle(name, tdb, 0.0)\n        position = self.position_from_bundle(bundle)\n        velocity = self.velocity_from_bundle(bundle)\n        return np.concatenate((position, velocity))\n\n    def compute_bundle(self, name, tdb, tdb2=0.0):\n        \"\"\"Return a tuple of coefficients and parameters for `tdb`.\n\n        The return value is a tuple that bundles together the\n        coefficients and other Chebyshev intermediate values that are\n        needed for the computation of either the position or velocity.\n        The bundle can then be passed to either `position_from_bundle()`\n        or `velocity_from_bundle()` to finish the computation.  See the\n        package-level documentation for details; most users will simply\n        call `position()` or `position_and_velocity()` instead.\n\n        The barycentric dynamical time `tdb` argument should be a float.\n        If there are many dates you want computed, then make `tdb` an\n        array, which is more efficient than calling this method multiple\n        times; the return values will be arrays providing a value for\n        each time in `tdb`.\n\n        For extra precision, the time can be split into two floats; a\n        popular choice is to use `tdb` for the integer or half-integer\n        date, and `tdb2` to hold the remaining fraction.\n\n        Consult the `names` attribute of this ephemeris for the values\n        of `name` it supports, such as ``'mars'`` or ``'earthmoon'``.\n\n        \"\"\"\n        input_was_scalar = getattr(tdb, 'shape', ()) == ()\n        if input_was_scalar:\n            tdb = np.array((tdb,))\n        # no need to deal with tdb2; numpy broadcast will add fine below.\n\n        coefficient_sets = self.load(name)\n        number_of_sets, axis_count, coefficient_count = coefficient_sets.shape\n\n        jalpha, jomega = self.jalpha, self.jomega\n        days_per_set = (jomega - jalpha) / number_of_sets\n        # to keep precision, first subtract, then add\n        index, offset = divmod((tdb - jalpha) + tdb2, days_per_set)\n        index = index.astype(int)\n\n        if (index < 0).any() or (number_of_sets < index).any():\n            raise DateError('ephemeris %s only covers dates %.1f through %.1f'\n                            % (self.name, jalpha, jomega))\n\n        omegas = (index == number_of_sets)\n        index[omegas] -= 1\n        offset[omegas] += days_per_set\n\n        coefficients = np.rollaxis(coefficient_sets[index], 1)\n\n        # Chebyshev recurrence:\n\n        T = np.empty((coefficient_count, len(index)))\n        T[0] = 1.0\n        T[1] = t1 = 2.0 * offset / days_per_set - 1.0\n        twot1 = t1 + t1\n        for i in range(2, coefficient_count):\n            T[i] = twot1 * T[i-1] - T[i-2]\n\n        bundle = coefficients, days_per_set, T, twot1\n        return bundle\n\n    def position_from_bundle(self, bundle):\n        \"\"\"Return position, given the `coefficient_bundle()` return value.\"\"\"\n\n        coefficients, days_per_set, T, twot1 = bundle\n        return (T.T * coefficients).sum(axis=2)\n\n    def velocity_from_bundle(self, bundle):\n        \"\"\"Return velocity, given the `coefficient_bundle()` return value.\"\"\"\n\n        coefficients, days_per_set, T, twot1 = bundle\n        coefficient_count = coefficients.shape[2]\n\n        # Chebyshev derivative:\n\n        dT = np.empty_like(T)\n        dT[0] = 0.0\n        dT[1] = 1.0\n        dT[2] = twot1 + twot1\n        for i in range(3, coefficient_count):\n            dT[i] = twot1 * dT[i-1] - dT[i-2] + T[i-1] + T[i-1]\n        dT *= 2.0\n        dT /= days_per_set\n\n        return (dT.T * coefficients).sum(axis=2)\n", "meta": {"hexsha": "a3cc70f48b78b68239cfd536658420e4b9c6c10b", "size": 7395, "ext": "py", "lang": "Python", "max_stars_repo_path": "otherSource/jplephem-2.5/jplephem/ephem.py", "max_stars_repo_name": "atmelino/PAT8", "max_stars_repo_head_hexsha": "b83b5ff8453017e4a7bec8e47b1a3a7619fffe53", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "otherSource/jplephem-2.5/jplephem/ephem.py", "max_issues_repo_name": "atmelino/PAT8", "max_issues_repo_head_hexsha": "b83b5ff8453017e4a7bec8e47b1a3a7619fffe53", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "otherSource/jplephem-2.5/jplephem/ephem.py", "max_forks_repo_name": "atmelino/PAT8", "max_forks_repo_head_hexsha": "b83b5ff8453017e4a7bec8e47b1a3a7619fffe53", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.335106383, "max_line_length": 78, "alphanum_fraction": 0.6273157539, "include": true, "reason": "import numpy", "num_tokens": 1857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.2689414272294874, "lm_q1q2_score": 0.17132397476322273}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*\n''' Functions to compute MESE weights\n'''\nfrom __future__ import print_function, division\n\nimport numpy as np\nfrom scipy.spatial import ConvexHull\n\nfrom icecube import dataclasses\nfrom icecube import icetray\nfrom icecube import NewNuFlux\nfrom icecube import AtmosphericSelfVeto\nfrom icecube.icetray.i3logging import log_info, log_warn\n\nfrom ic3_labels.labels.utils import muon as mu_utils\nfrom ic3_labels.labels.utils import tau as tau_utils\nfrom ic3_labels.labels.utils.cascade import get_cascade_of_primary_nu\n\n\ndef atmosphericFlux(\n        neutrinoEnergy,\n        neutrinoZenith,\n        neutrinoType,\n        atmFluxConv,\n        atmFluxPrompt):\n    \"\"\"\n    Excessively complicated flux_atm calculation.\n\n    This bundle is adapted from Nancy's adaptation-for-mrichman of her dataset\n    wrangling scripts.  Each part is more flexible than it really needs to be\n    for this application, but I considered it safer to keep it all rather than\n    go through the potentially error-prone process of streamlining the code.\n    \"\"\"\n    if isinstance(neutrinoEnergy, float):\n        neutrinoEnergy = np.atleast_1d(neutrinoEnergy)\n        neutrinoZenith = np.atleast_1d(neutrinoZenith)\n        neutrinoType = np.atleast_1d(neutrinoType)\n\n    p_types = [dataclasses.I3Particle.ParticleType(t) for t in neutrinoType]\n    atmflux = np.zeros(len(neutrinoEnergy))\n\n    badmask = neutrinoEnergy < 10.\n    if atmFluxConv is not None:\n        conv = atmFluxConv.getFlux(\n            p_types,\n            neutrinoEnergy, np.cos(neutrinoZenith))\n        conv[badmask] = np.nan\n        atmflux += conv\n    if atmFluxPrompt is not None:\n        prompt = atmFluxPrompt.getFlux(\n            p_types,\n            neutrinoEnergy, np.cos(neutrinoZenith))\n        prompt[badmask] = np.nan\n        atmflux += prompt\n    # return atmflux\n\n    if ((isinstance(neutrinoZenith, float))\n            and (isinstance(neutrinoType, str))):\n        for i in range(len(neutrinoEnergy)):\n            if neutrinoEnergy[i] < 10.:\n                atmflux[i] = np.nan\n                continue\n\n            conv = 0.\n            prompt = 0.\n            if atmFluxConv is not None:\n                conv = atmFluxConv.getFlux(\n                    dataclasses.I3Particle.ParticleType(neutrinoType),\n                    neutrinoEnergy[i],\n                    np.cos(neutrinoZenith))\n            if atmFluxPrompt is not None:\n                prompt = atmFluxPrompt.getFlux(\n                    dataclasses.I3Particle.ParticleType(neutrinoType),\n                    neutrinoEnergy[i],\n                    np.cos(neutrinoZenith))\n            atmflux[i] = conv+prompt\n    else:\n        for i in range(len(neutrinoEnergy)):\n            if neutrinoEnergy[i] < 10.:\n                atmflux[i] = np.nan\n                continue\n            conv = 0.\n            prompt = 0.\n            if atmFluxConv is not None:\n                conv = atmFluxConv.getFlux(\n                    dataclasses.I3Particle.ParticleType(neutrinoType[i]),\n                    neutrinoEnergy[i],\n                    np.cos(neutrinoZenith[i]))\n            if atmFluxPrompt is not None:\n                prompt = atmFluxPrompt.getFlux(\n                    dataclasses.I3Particle.ParticleType(neutrinoType[i]),\n                    neutrinoEnergy[i],\n                    np.cos(neutrinoZenith[i]))\n            atmflux[i] = conv+prompt\n\n    if len(atmflux) == 1:\n        atmflux = atmflux[0]\n\n    return atmflux\n\n\nclass MESEWeights(icetray.I3ConditionalModule):\n\n    \"\"\"Calculate weights for MESE 7yr cascade ps paper.\n    The returned weights are rates in Hz. To obtain number of events, this\n    still has to be multiplied by livetime.\n    \"\"\"\n\n    def __init__(self, context):\n        icetray.I3ConditionalModule.__init__(self, context)\n        self.AddParameter(\"DatasetType\",\n                          \"Type of dataset. Must be one of: \"\n                          \"'muongun', 'nugen', 'genie'\")\n        self.AddParameter(\"DatasetNFiles\", \"Number of files\")\n        self.AddParameter(\"DatasetNEventsPerRun\",\n                          \"Number of generated events per file\")\n        self.AddParameter(\"OutputKey\", \"Save weights to this frame key.\",\n                          'MESE_weights')\n\n    def Configure(self):\n        self._dataset_type = self.GetParameter(\"DatasetType\")\n        self._n_files = self.GetParameter(\"DatasetNFiles\")\n        self._n_events_per_run = self.GetParameter(\"DatasetNEventsPerRun\")\n        self._ngen = self._n_events_per_run * self._n_files\n        self._output_key = self.GetParameter(\"OutputKey\")\n\n        self._dataset_type = self._dataset_type.lower()\n\n        if self._dataset_type not in ['muongun', 'nugen', 'genie']:\n            raise ValueError('Unkown dataset_type: {!r}'.format(dataset_type))\n\n        # get Honda2006\n        self.honda = NewNuFlux.makeFlux(\"honda2006\")\n        self.honda.knee_reweighting_model = 'gaisserH3a_elbert'\n        self.honda.relative_kaon_contribution = .91\n        # get self-veto\n        self.af = AtmosphericSelfVeto.AnalyticPassingFraction\n        self.honda_veto_hese = self.af('conventional', veto_threshold=1.25e3)\n        self.honda_veto_mese = self.af('conventional', veto_threshold=1e2)\n        # get the sarcevic model for prompt neutrinos\n        self.enberg = NewNuFlux.makeFlux(\"sarcevic_std\")\n        self.enberg_veto_hese = self.af('charm', veto_threshold=1.25e3)\n        self.enberg_veto_mese = self.af('charm', veto_threshold=1e2)\n        self.conv_flux_multiplier = 1.07\n        self.prompt_flux_multiplier = .2\n\n    def Geometry(self, frame):\n        geoMap = frame['I3Geometry'].omgeo\n        domPosDict = {(i[0][0], i[0][1]): (i[1].position.x,\n                                           i[1].position.y,\n                                           i[1].position.z)\n                      for i in geoMap if i[1].omtype.name == 'IceCube'}\n        points = [\n            domPosDict[(31, 1)], domPosDict[(1, 1)],\n            domPosDict[(6, 1)], domPosDict[(50, 1)],\n            domPosDict[(74, 1)], domPosDict[(72, 1)],\n            domPosDict[(78, 1)], domPosDict[(75, 1)],\n\n            domPosDict[(31, 60)], domPosDict[(1, 60)],\n            domPosDict[(6, 60)], domPosDict[(50, 60)],\n            domPosDict[(74, 60)], domPosDict[(72, 60)],\n            domPosDict[(78, 60)], domPosDict[(75, 60)]\n            ]\n        self._convex_hull = ConvexHull(points)\n        self._dom_pos_dict = domPosDict\n        self.PushFrame(frame)\n\n    def Physics(self, frame):\n\n        mese_dict = {\n            'n_files': self._n_files,\n            'n_events_per_run': self._n_events_per_run,\n        }\n\n        # get MC info\n        energy_true = frame['MCPrimary'].energy\n        zenith_true = frame['MCPrimary'].dir.zenith\n        azimuth_true = frame['MCPrimary'].dir.azimuth\n\n        # -------\n        # NuGen\n        # -------\n        if self._dataset_type in ['nugen', 'genie']:\n            # get oneweight / n_gen\n            oneweight = frame['I3MCWeightDict']['OneWeight'] / self._ngen\n            true_type = frame['I3MCWeightDict']['PrimaryNeutrinoType']\n            is_tau = (np.abs(true_type) == 16).all()\n\n            # calculate astrophysical weights\n            mese_dict['weight_E269'] = 2.09e-18 * oneweight * (\n                                                    energy_true / 1e5)**-2.69\n            mese_dict['weight_E250'] = 2.23e-18 * oneweight * (\n                                                    energy_true / 1e5)**-2.5\n\n            # calculate atmospheric weights\n            if is_tau:\n                mese_dict['weight_conv'] = oneweight * atmosphericFlux(\n                        neutrinoEnergy=energy_true,\n                        neutrinoZenith=zenith_true,\n                        neutrinoType=true_type,\n                        atmFluxConv=None,\n                        atmFluxPrompt=None,) * 2. * self.conv_flux_multiplier\n\n                mese_dict['weight_prompt'] = oneweight * atmosphericFlux(\n                        neutrinoEnergy=energy_true,\n                        neutrinoZenith=zenith_true,\n                        neutrinoType=true_type,\n                        atmFluxConv=None,\n                        atmFluxPrompt=None,) * 2. * self.prompt_flux_multiplier\n            else:\n                mese_dict['weight_conv'] = oneweight * atmosphericFlux(\n                        neutrinoEnergy=energy_true,\n                        neutrinoZenith=zenith_true,\n                        neutrinoType=true_type,\n                        atmFluxConv=self.honda,\n                        atmFluxPrompt=None,) * 2. * self.conv_flux_multiplier\n                mese_dict['weight_prompt'] = oneweight * atmosphericFlux(\n                    neutrinoEnergy=energy_true,\n                    neutrinoZenith=zenith_true,\n                    neutrinoType=true_type,\n                    atmFluxConv=None,\n                    atmFluxPrompt=self.enberg,)*2.*self.prompt_flux_multiplier\n\n            # ---------------------\n            # Atmospheric Self Veto\n            # ---------------------\n            # get true_depth\n            if 'IntersectionPoint' in frame:\n                true_depth = frame['IntersectionPoint'].z\n            else:\n                muon = mu_utils.get_muon_of_inice_neutrino(frame)\n                tau = tau_utils.get_tau_of_inice_neutrino(frame)\n\n                if muon is not None:\n                    # found a muon\n                    entry = self._get_muon_entry(frame, muon)\n                    true_depth = entry.z\n\n                elif tau is not None:\n                    # found a tau\n                    entry = self._get_particle_entry(tau)\n                    true_depth = entry.z\n                else:\n\n                    # no muon or tau exists: cascade\n                    cascade = get_cascade_of_primary_nu(frame,\n                                                        frame['MCPrimary'],\n                                                        convex_hull=None,\n                                                        extend_boundary=800)[0]\n\n                    if cascade is not None:\n                        true_depth = cascade.pos.z\n                    else:\n                        cascade = get_cascade_of_primary_nu(\n                            frame,\n                            frame['MCPrimary'],\n                            convex_hull=None,\n                            extend_boundary=float('inf'))[0]\n\n                        # Muon coming out of hadronic shower?\n                        daughters = frame['I3MCTree'].get_daughters(cascade)\n\n                        # collect possible muons from daughters of daughters\n                        # e.g. Nu -> Nu + Hadrons -> Mu\n                        muons = []\n                        for d in daughters:\n                            muons.extend([\n                                m for m in frame['I3MCTree'].get_daughters(d)\n                                if mu_utils.is_muon(m)])\n                        if muons:\n                            # pick highest energy muon\n                            indices = np.argsort([m.energy for m in muons])\n                            muon = muons[indices[-1]]\n                            entry = self._get_muon_entry(frame, muon)\n                            true_depth = entry.z\n                        else:\n                            true_depth = cascade.pos.z\n\n            # apply self veto\n            veto_args = (true_type, energy_true,\n                         np.cos(zenith_true),\n                         1950. - true_depth\n                         )\n\n            if 'IsHese' in frame:\n                if frame['IsHese'].value:\n                    mese_dict['veto_conv'] = self.honda_veto_hese(*veto_args)\n                    mese_dict['veto_prompt'] = self.enberg_veto_hese(\n                                                                    *veto_args)\n                else:\n                    mese_dict['veto_conv'] = self.honda_veto_mese(*veto_args)\n                    mese_dict['veto_prompt'] = self.enberg_veto_mese(\n                                                                    *veto_args)\n\n            else:\n                log_warn('WARNING: IsHese does not exist. Using MESE veto')\n                mese_dict['veto_conv'] = self.honda_veto_mese(*veto_args)\n                mese_dict['veto_prompt'] = self.honda_veto_mese(*veto_args)\n\n            mese_dict['weight_conv'] *= mese_dict['veto_conv']\n            mese_dict['weight_prompt'] *= mese_dict['veto_prompt']\n            # ---------------------\n\n        # -------\n        # MuonGun\n        # -------\n        elif self._dataset_type == 'muongun':\n            if 'MuonWeight_GaisserH4a' in frame:\n                # --- Where does magic number of 1.6 come from? MuonMultiplier\n                mese_dict['muon_weight'] = \\\n                    frame['MuonWeight_GaisserH4a'].value * 1.6 / self._ngen\n\n        # -----------------\n        # Experimental Data\n        # -----------------\n        elif self._dataset_type == 'data':\n            mjd = frame['I3EventHeader'].start_time.mod_julian_day_double\n\n        # -----------------------------------------------------\n        # final track cut:\n        # drop low energy downgoing tracks and duplicate events\n        # -----------------------------------------------------\n        try:\n            # get TrackFit_zenith\n            TrackFit_zenith = frame['TrackFit'].dir.zenith\n\n            # get energy_millipede\n            energy_millipede = frame['MillipedeDepositedEnergy'].value\n\n            # mask events\n            track_mask = data_dict['is_cascade_reco'] | \\\n                ~((np.cos(TrackFit_zenith) > 0.3) & (energy_millipede < 10e3))\n\n            if self._dataset_type in ['muongun', 'nugen', 'genie']:\n                uniq_mask = np.r_[True, np.diff(energy_true) != 0]\n            else:\n                uniq_mask = np.r_[True, np.diff(mjd) != 0]\n            mese_dict['passed_final_track_cut'] = track_mask & uniq_mask\n        except Exception as e:\n            # log_warn(e)\n            pass\n        # -----------------------------------------------------\n        for k, item in mese_dict.items():\n            mese_dict[k] = float(item)\n        frame[self._output_key] = dataclasses.I3MapStringDouble(mese_dict)\n\n        self.PushFrame(frame)\n\n    def _get_particle_entry(self, particle):\n\n        entry = mu_utils.get_muon_initial_point_inside(\n                                        particle, self._convex_hull)\n        if entry is None:\n            # get closest approach point as entry approximation\n            entry = mu_utils.get_particle_closest_approach_to_position(\n                                    particle, dataclasses.I3Position(0, 0, 0))\n        return entry\n\n    def _get_muon_entry(self, frame, muon):\n\n        entry = mu_utils.get_muon_initial_point_inside(muon, self._convex_hull)\n        if entry is None:\n            # get closest approach point as entry approximation\n            entry = mu_utils.get_muon_closest_approach_to_center(frame, muon)\n\n        return entry\n", "meta": {"hexsha": "df3dc8251a0e76082e0cfd3181e85bc071a3cbd1", "size": 15054, "ext": "py", "lang": "Python", "max_stars_repo_path": "ic3_labels/weights/mese_weights.py", "max_stars_repo_name": "IceCubeOpenSource/ic3-labels", "max_stars_repo_head_hexsha": "049565e1dd423115020484fca5b891afdd1f97bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-21T09:06:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-21T09:06:12.000Z", "max_issues_repo_path": "ic3_labels/weights/mese_weights.py", "max_issues_repo_name": "icecube/ic3-labels", "max_issues_repo_head_hexsha": "049565e1dd423115020484fca5b891afdd1f97bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ic3_labels/weights/mese_weights.py", "max_forks_repo_name": "icecube/ic3-labels", "max_forks_repo_head_hexsha": "049565e1dd423115020484fca5b891afdd1f97bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-06-10T13:37:17.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-21T06:16:35.000Z", "avg_line_length": 40.9076086957, "max_line_length": 79, "alphanum_fraction": 0.5281652717, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.27202455109402257, "lm_q1q2_score": 0.17131415486959986}}
{"text": "'''\n说明：\n没有文件写操作，完全将数据集加载到内存中进行操作\n对于较大的数据集会很耗内存，但训练速度快！！！\n'''\n\nimport os\nimport time\nimport numpy as np\nimport pandas as pd\nimport pickle\nimport yaml\nimport jieba.analyse\nimport warnings\n# import logging\nimport multiprocessing\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n# from collections import Counter\nimport keras\nfrom keras import losses\nfrom keras.preprocessing import sequence\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\nfrom keras.layers import Dense, Dropout, SpatialDropout1D, Flatten\nfrom keras.layers.embeddings import Embedding\nfrom keras.layers.wrappers import Bidirectional\nfrom keras.layers.recurrent import LSTM\nfrom keras.layers.convolutional import Conv1D, Convolution1D\nfrom keras.layers.pooling import GlobalMaxPool1D, MaxPooling1D\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard\nfrom keras.models import Sequential, model_from_yaml\nfrom keras import backend as K\nwarnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')\nfrom gensim.models.word2vec import Word2Vec\nfrom gensim.corpora.dictionary import Dictionary\nfrom log.logger import MyLogger\nfrom models.text_utils import TextUtils\n\n#设置日志级别，默认是logging.WARNING，低于该级别的不会输出，级别排序:CRITICAL>ERROR>WARNING>INFO>DEBUG\n# logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\n# logging.basicConfig(filename='log/new.log', #日志文件\n#                     filemode='a', #模式，有w和a，w就是写模式，每次都会重新写日志，覆盖之前的日志，a是追加模式，默认是追加模式\n#                     format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s', #日志格式\n#                     level=logging.DEBUG,#控制台打印的日志级别\n#                 ) #只会保存log到文件，不会输出到控制台\n\n#随机数和种子之间的关系遵从以下两个规则：种子不同，产生不同的随机数；种子相同，即使实例不同也产生相同的随机数\nnp.random.seed(3347)\nLABEL_POS, LABEL_NEG = 1, 0 #正样例标签1、负样例标签0\nN_ROWS = 260000 #每个类别的评论数\nN_ITER = 8  #词向量训练的迭代次数\nWIN_SIZE = 8  #词向量上下文最大距离，一般取[5-10]\nMIN_COUNT = 5 #需要计算词向量的最小词频。这个值可以去掉一些很生僻的低频词\nEMBEDDING_SIZE = 300 #词向量的维度，数据集越大该值越大\nHIDDEN_LAYER_SIZE = 64 #隐层的大小\nBATCH_SIZE = 64 #批的大小\nNUM_EPOCHS = 10 #LSTM样本训练的轮数\nTEST_SIZE = 0.2 #总样本中，测试样本的占比\nCPU_COUNT = multiprocessing.cpu_count() #cpu线程数量\n\nCOMMENT_DIR = '../comment' #源评论文件目录\nUSER_DIR = '../user' #用户自定义文件目录\nMODEL_DIR = '../log' #保存模型目录\nUSER_DICT_PATH = os.path.join(USER_DIR, 'user_dict.txt') #自定义用户表\nSTOP_WORDS_PATH = os.path.join(USER_DIR, 'stop_words.txt') #停用词表\nLSTM_MODEL_PATH = os.path.join(MODEL_DIR, 'lstm.yml') #保存LSTM模型结构的路径\nLSTM_WEIGHT_PATH = os.path.join(MODEL_DIR, 'lstm.h5') #保存LSTM权重的路径\n# WORD2VEC_PATH = os.path.join(MODEL_DIR, 'word2vec_model.pkl') #保存word2vec词向量模型的路径\nWORD2VEC_PATH = os.path.join('../model_lstm', 'word2vec.model') #保存word2vec词向量模型的路径\nHIST_PATH = os.path.join(MODEL_DIR, 'hist.pkl') #保存训练过程中的历史记录\njieba.load_userdict(USER_DICT_PATH)\njieba.analyse.set_stop_words(STOP_WORDS_PATH)\npos_tags = ['n', 'vn', 'v', 'ad', 'a', 'e', 'y'] #是名词、形容词、动词、副词、叹词、语气词\nBEST_MODEL_PATH = os.path.join(MODEL_DIR, 'model-{epoch:02d}-{val_acc:.2f}.h5') #保存训练最好的模型的权值\n\n\nclass SentimentModel:\n    def __init__(self):\n        self.max_len = 100  # 文本保留的最大长度\n\n        self.logging = MyLogger()  # 自定义日志器\n        self.margin = 0.6  # 阈值\n        self.theta = lambda t: (K.sign(t)+1)/2\n        # self.theta = lambda t: K.sigmoid(100 * t)  # 软化\n        self.logging.info('###该模型为情感二分类模型###')\n        self.logging.info('CPU线程数：{}'.format(CPU_COUNT))\n\n    # 二分类：自定义损失函数（hinge loss+triplet loss）\n    def loss_new(self, y_true, y_pred):\n        return -(1 - self.theta(y_true - self.margin) * self.theta(y_pred - self.margin) - self.theta(\n            1 - self.margin - y_true) * self.theta(1 - self.margin - y_pred)) * (\n                           y_true * K.log(y_pred + K.epsilon()) + (1 - y_true) * K.log(1 - y_pred + K.epsilon()))\n\n    # 二分类：focal_loss损失函数，解决样本不均衡分布问题\n    def focal_loss(self, y_true, y_pred, alpha=0.25, gamma=2.0):\n        pt_1 = tf.where(tf.equal(y_true, LABEL_POS), y_pred, tf.ones_like(y_pred))\n        pt_0 = tf.where(tf.equal(y_true, LABEL_NEG), y_pred, tf.zeros_like(y_pred))\n        return -K.sum(alpha * K.pow(1. - pt_1, gamma) * K.log(pt_1)) \\\n               - K.sum((1. - alpha) * K.pow(pt_0, gamma) * K.log(1. - pt_0))\n\n    '''\n     input_csv_dir：csv格式的评论数据集目录\n     返回值：DataFrame对象\n     '''\n    def load_train_data(self, input_csv_dir):\n        self.logging.info('开始加载数据......')\n        t1 = time.time()\n        df_data = pd.DataFrame()\n        if os.path.isdir(input_csv_dir):\n            for f in os.listdir(input_csv_dir):\n                csv_file = os.path.join(input_csv_dir, f)\n                csv_data = pd.read_csv(csv_file, usecols=['label', 'segs'], nrows=N_ROWS)\n                df_data = df_data.append(csv_data, ignore_index=True)\n        else:\n            df_data = pd.read_csv(input_csv_dir, usecols=['label', 'segs'], nrows=N_ROWS)\n\n        t2 = time.time()\n        self.logging.info('数据加载完成！总用时：{}s'.format(t2 - t1))\n        # self.max_len = max(df['segs'].apply(lambda x: len(x)))  # 序列的最大长度\n\n        self.logging.info('数据集总记录数：{}'.format(len(df_data)))\n        nb_pos = len(df_data[df_data['label'] == LABEL_POS])  # 正样例数\n        nb_neg = len(df_data[df_data['label'] == LABEL_NEG])  # 负样例数\n        self.logging.info('正面例数：{} 负面样例数：{}'.format(nb_pos, nb_neg))\n        return shuffle(df_data)  # 随机打乱数据集\n\n    #训练词向量模型\n    def train_wd2vect(self, sentences): #分词列表\n        if os.path.exists(WORD2VEC_PATH):\n            word2vec_model = Word2Vec.load(WORD2VEC_PATH)\n        else:\n            self.logging.info('开始训练词向量模型......')\n            t1 = time.time()\n            word2vec_model = Word2Vec(sentences,\n                                      size=EMBEDDING_SIZE, #词向量的维度\n                                      window=WIN_SIZE,  #在一个句子中，当前词和预测词的最大距离(词向量上下文最大距离)\n                                      min_count=MIN_COUNT, #词频少于min_count次数的单词会被丢弃掉\n                                      sg=0, #训练算法：sg=0 使用cbow训练, sg=1 使用skip-gram 对低频词较为敏感\n                                      workers=CPU_COUNT, #设置多线程训练模型，机器的核数越多，训练越快\n                                      iter=N_ITER  #随机梯度下降法中迭代的最大次数，默认是5。对于大语料，可以增大这个值\n                                    )\n            t2 = time.time()\n            self.logging.info('词向量训练结束！总用时：{}min'.format((t2 - t1) / 60.0))\n\n            if not os.path.exists(MODEL_DIR):\n                os.mkdir(MODEL_DIR)\n            word2vec_model.save(WORD2VEC_PATH) #保存词向量模型\n            self.logging.info('词向量模型已保存......')\n            # word2vec_model.save_word2vec_format(out.model, binary=False)\n        return word2vec_model\n\n\n    # 根据词向量模型得到词索引{词: 索引} 和 词向量{词: 词向量}\n    def create_dicts(self, wd2vec_model):\n        if wd2vec_model is not None:\n            gensim_dict = Dictionary()  # {索引: 词}\n            # 实现词袋模型\n            gensim_dict.doc2bow(wd2vec_model.wv.vocab.keys(), allow_update=True)  # (token_id, token_count)\n            word2index = {wd: idx + 1 for idx, wd in gensim_dict.items()}  # 词索引字典 {词: 索引}，索引从1开始计数\n            word_vectors = {wd: wd2vec_model.wv[wd] for wd in word2index.keys()}  # 词向量 {词: 词向量}\n            return word2index, word_vectors\n        else:\n            return None\n\n\n    # 获取字典长度和权重矩阵\n    def get_embedding_weights(self, word2index, word_vectors):\n        vocab_size = len(word2index) + 1  # 字段大小(索引数字的个数)，因为有的词语索引为0，所以+1\n        embedding_weights = np.zeros((vocab_size, EMBEDDING_SIZE))  # vocab_size * EMBEDDING_SIZE的0矩阵\n        for wd, idx in word2index.items():  # 从索引为1的词语开始，用词向量填充矩阵\n            embedding_weights[idx, :] = word_vectors[wd]  # 词向量矩阵，第一行是0向量（没有索引为0的词语）\n        return embedding_weights\n\n\n    #构建CNN模型\n    def build_cnn_model(self, embedding_weights):\n        model = Sequential()\n        vocab_size = len(embedding_weights)\n        # 嵌入层将正整数（下标）转换为具有固定大小的向量. eg. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]\n        model.add(Embedding(input_dim=vocab_size,  # 字典长度\n                            output_dim=EMBEDDING_SIZE,\n                            input_length=self.max_len,\n                            weights=[embedding_weights]))  # (None, MAX_SENTENCE_LENGTH, EMBEDDING_SIZE), where None is the batch dimension\n        model.add(SpatialDropout1D(0.2))\n        model.add(Convolution1D(filters=128, kernel_size=3, activation='relu'))\n        model.add(GlobalMaxPool1D())  # 对于时间信号的全局最大池化,MaxPooling1D限制每一步的池化大小\n        model.add(Dense(1, activation=\"sigmoid\"))\n        # model.add(Dense(2, activation='softmax'))\n\n        model.summary()\n        return model\n\n    # def build_cnn_model(self, embedding_weights):\n    #     model = Sequential()\n    #     vocab_size = len(embedding_weights)\n    #     # 嵌入层将正整数（下标）转换为具有固定大小的向量. eg. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]\n    #     model.add(Embedding(input_dim=vocab_size,  # 字典长度\n    #                         output_dim=EMBEDDING_SIZE,\n    #                         input_length=self.max_len,\n    #                         weights=[embedding_weights]))  # (None, MAX_SENTENCE_LENGTH, EMBEDDING_SIZE), where None is the batch dimension\n    #     model.add(SpatialDropout1D(0.2))\n    #     model.add(Conv1D(filters=128, kernel_size=3, activation='relu'))\n    #     model.add(MaxPooling1D(pool_size=3)) #对于时间信号的全局最大池化,MaxPooling1D限制每一步的池化大小\n    #     model.add(Conv1D(filters=64, kernel_size=3, activation='relu'))\n    #     model.add(MaxPooling1D(pool_size=3))  # 对于时间信号的全局最大池化,MaxPooling1D限制每一步的池化大小\n    #     model.add(Conv1D(filters=32, kernel_size=3, activation='relu'))\n    #     model.add(Flatten())\n    #     model.add(Dense(1, activation=\"sigmoid\"))\n    #     # model.add(Dense(2, activation='softmax'))\n    #     model.summary()\n    #     return model\n\n    #构建LSTM模型\n    def build_lstm_model(self, embedding_weights):\n        model = Sequential()\n        vocab_size = len(embedding_weights)\n        # 嵌入层将正整数（下标）转换为具有固定大小的向量. eg. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]\n        model.add(Embedding(input_dim=vocab_size,  # 字典长度\n                            output_dim=EMBEDDING_SIZE,\n                            # mask_zero=True,\n                            input_length=self.max_len,\n                            weights=[embedding_weights]))  # (None, MAX_SENTENCE_LENGTH, EMBEDDING_SIZE), where None is the batch dimension\n        model.add(SpatialDropout1D(0.2))\n        model.add(LSTM(HIDDEN_LAYER_SIZE, dropout=0.2, recurrent_dropout=0.2, return_sequences=False))\n        #     model.add(GRU(HIDDEN_LAYER_SIZE, dropout=0.2, recurrent_dropout=0.2, return_sequences=False))\n        model.add(Dense(HIDDEN_LAYER_SIZE//2, activation='relu'))\n        model.add(Dropout(0.3))\n        # model.add(Dense(1, activation=\"sigmoid\"))\n        model.add(Dense(2, activation=\"softmax\"))\n\n        model.summary()\n        return model\n\n    #构建CNN-LSTM模型\n    def build_cnn_lstm_model(self, embedding_weights):\n        model = Sequential()\n        vocab_size = len(embedding_weights)\n        # 嵌入层将正整数（下标）转换为具有固定大小的向量. eg. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]\n        model.add(Embedding(input_dim=vocab_size,  # 字典长度\n                            output_dim=EMBEDDING_SIZE,\n                            input_length=self.max_len,\n                            weights=[embedding_weights]))  # (None, MAX_SENTENCE_LENGTH, EMBEDDING_SIZE), where None is the batch dimension\n        model.add(SpatialDropout1D(0.2))\n        model.add(Conv1D(filters=128, kernel_size=3, strides=1, padding='same', activation='relu'))\n        model.add(MaxPooling1D(pool_size=2, strides=2))\n        # model.add(Conv1D(filters=64, kernel_size=3, strides=1, padding='same', activation='relu'))\n        # model.add(MaxPooling1D(pool_size=2, strides=2))\n        model.add(LSTM(HIDDEN_LAYER_SIZE, dropout=0.2, recurrent_dropout=0.2))\n        #     model.add(GRU(HIDDEN_LAYER_SIZE, dropout=0.2, recurrent_dropout=0.2))\n        model.add(Dense(1, activation=\"sigmoid\"))\n\n        model.summary()\n        return model\n\n    #构建LSTM-CNN模型\n    def build_lstm_cnn_model(self, embedding_weights):\n        model = Sequential()\n        vocab_size = len(embedding_weights)\n        # 嵌入层将正整数（下标）转换为具有固定大小的向量. eg. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]\n        model.add(Embedding(input_dim=vocab_size,  # 字典长度\n                            output_dim=EMBEDDING_SIZE,\n                            # mask_zero=True,\n                            input_length=self.max_len,\n                            weights=[embedding_weights]))  # (None, MAX_SENTENCE_LENGTH, EMBEDDING_SIZE), where None is the batch dimension\n        model.add(SpatialDropout1D(0.2))\n        model.add(LSTM(HIDDEN_LAYER_SIZE, dropout=0.2, recurrent_dropout=0.2))\n        #     model.add(GRU(HIDDEN_LAYER_SIZE, dropout=0.2, recurrent_dropout=0.2))\n        model.add(Conv1D(filters=32, kernel_size=3, strides=1, padding='same', activation='relu'))\n        model.add(MaxPooling1D(pool_size=2, strides=2))\n        model.add(Dense(1, activation=\"sigmoid\"))\n\n        model.summary()\n        return model\n\n\n    #构建Bi-LSTM模型\n    def build_bilstm_model(self, embedding_weights):\n        vocab_size = len(embedding_weights)\n        # 嵌入层将正整数（下标）转换为具有固定大小的向量. eg. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]\n        model = Sequential()\n        model.add(Embedding(input_dim=vocab_size,\n                            output_dim=EMBEDDING_SIZE,\n                            input_length=self.max_len,\n                            weights=[embedding_weights]))  # (None, MAX_SENTENCE_LENGTH, EMBEDDING_SIZE), where None is the batch dimension\n        model.add(SpatialDropout1D(0.2))\n        model.add(Bidirectional(LSTM(HIDDEN_LAYER_SIZE, dropout=0.2, recurrent_dropout=0.2, return_sequences=True)))\n        model.add(Bidirectional(LSTM(HIDDEN_LAYER_SIZE, dropout=0.2)))\n        # model.add(Dense(128, activation='relu'))\n        # model.add(Dropout(0.5))\n        # model.add(Flatten())\n        model.add(Dense(1, activation=\"sigmoid\"))\n\n        # inputs = Input(shape=(None,))\n        # embedded = Embedding(vocab_size, EMBEDDING_SIZE, input_length=self.max_len)(inputs)\n        # lstm_out = LSTM(HIDDEN_LAYER_SIZE, dropout=0.2, recurrent_dropout=0.2, return_sequences=False)(embedded)\n        # predict = Dense(1, activation='softmax')(lstm_out)\n        # model = Model(inputs=inputs, outputs=predict)\n        model.summary()\n        return model\n\n    def F1_score(self, y_true, y_pred):\n        # Only computes a batch-wise average of recall.\n        def recall(y_true, y_pred):\n            true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n            possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n            recall = true_positives / (possible_positives + K.epsilon())\n            return recall\n\n        # Only computes a batch-wise average of precision.\n        def precision(y_true, y_pred):\n            true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n            predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n            precision = true_positives / (predicted_positives + K.epsilon())\n            return precision\n\n        precision = precision(y_true, y_pred)\n        recall = recall(y_true, y_pred)\n        return 2 * ((precision * recall) / (precision + recall + K.epsilon()))\n\n    #构建并训练LSTM模型\n    def train_lstm_model(self, embedding_weights, X, y):\n        lstm_model = self.build_lstm_model(embedding_weights)\n        # lstm_model.compile(loss=losses.binary_crossentropy, optimizer=\"adam\", metrics=[\"acc\", self.F1_score])\n        lstm_model.compile(loss=self.loss_new, optimizer=\"adam\", metrics=[\"acc\", self.F1_score])\n        Xtrain, Xtest, ytrain, ytest = train_test_split(X, y, test_size=TEST_SIZE, random_state=42, shuffle=True)\n        ytrain = keras.utils.to_categorical(ytrain, num_classes=2)\n        ytest = keras.utils.to_categorical(ytest, num_classes=2)\n\n        self.logging.info('开始训练LSTM模型......')\n        self.logging.info('训练集大小：{} 测试集大小：{}'.format(round((1-TEST_SIZE)*len(X)), round(len(X)*TEST_SIZE)))\n        t1 = time.time()\n        # 保存训练最好的模型（每3轮训练检测一次）\n        # cp = ModelCheckpoint(filepath=BEST_MODEL_PATH, monitor='val_acc', mode='max', save_best_only=True, verbose=1,\n        #                      period=2)\n        # tb = TensorBoard(log_dir='log')\n        es = EarlyStopping(monitor='val_loss', patience=NUM_EPOCHS / 2)  # 经过NUM_EPOCHS/2轮训练，当val_acc不再提升，则停止训练\n        callbacks_lst = [es]\n        hist = lstm_model.fit(Xtrain,\n                        ytrain,\n                        batch_size=BATCH_SIZE,\n                        epochs=NUM_EPOCHS,\n                        callbacks=callbacks_lst,\n                        validation_data=(Xtest, ytest))\n        t2 = time.time()\n        self.logging.info('LSTM模型训练结束！总用时：{}min'.format((t2 - t1) / 60.0))\n\n        with open(HIST_PATH, 'wb') as output: #保存history对象\n            pickle.dump(hist.history, output)\n\n        # yaml_string = lstm_model.to_yaml()  # 保存模型结构为YAML字符串\n        # with open(LSTM_MODEL_PATH, 'w') as fout:\n        #     fout.write(yaml.dump(yaml_string, default_flow_style=True))\n        # lstm_model.save_weights(LSTM_WEIGHT_PATH)  # 保存模型权重\n        # self.logging.info('LSTM模型已经保存......')\n\n        self.logging.info(lstm_model.metrics_names)\n        loss, acc, F1_score = lstm_model.evaluate(Xtest, ytest, batch_size=BATCH_SIZE//2)\n        self.logging.info('模型评估结果：loss:{} acc:{} F1:{}'.format(loss, acc, F1_score))\n\n    def plot_hist(self):\n        # plot loss and accuracy\n        with open(HIST_PATH, 'rb') as pkl_hist:\n            history = pickle.load(pkl_hist)\n        plt.subplot(211)\n        plt.title(\"Accuracy\")\n        # plt.plot(history[\"acc\"], color=\"g\", label=\"Train\")\n        plt.plot(history[\"val_acc\"], color=\"b\", label=\"Validation\")\n        plt.legend(loc=\"best\")\n        plt.subplot(212)\n        plt.title(\"Loss\")\n        # plt.plot(history[\"loss\"], color=\"g\", label=\"Train\")\n        plt.plot(history[\"val_loss\"], color=\"r\", label=\"Validation\")\n        plt.legend(loc=\"best\")\n        plt.tight_layout() #自动调整子图间的间距\n        plt.show()\n\n    #加载LSTM模型\n    def load_lstm_model(self):\n        self.logging.info('loading models......')\n        with open(LSTM_MODEL_PATH, 'r') as f:\n            yaml_string = yaml.load(f)\n        lstm_model = model_from_yaml(yaml_string)\n        self.logging.info('loading weights......')\n        lstm_model.load_weights(LSTM_WEIGHT_PATH)\n        lstm_model.compile(loss=self.focal_loss, optimizer=\"adam\", metrics=[\"accuracy\"])\n        return lstm_model\n\n\n    #将分词序列转换成索引序列（分词序列由list列表传入）\n    def text2index_from_lst(self, word2index, comm_seqs):\n        data = []\n        for seqs in comm_seqs:\n            wd_idxs = []\n            for wd in seqs:\n                if wd in word2index.keys():\n                    wd_idxs.append(word2index[wd])  # 单词转索引数字\n                else:\n                    wd_idxs.append(0)  # 索引字典里没有的词转为数字0\n            data.append(wd_idxs)\n\n        return sequence.pad_sequences(data, self.max_len)  # 对齐序列\n\n\n\n    #情感预测（传入评论列表）\n    def predict_by_lst(self, new_comms):\n        lstm_model = self.load_lstm_model() #LSTM模型\n        word2vec_model = Word2Vec.load(WORD2VEC_PATH) #词向量模型\n        word2index, _ = self.create_dicts(word2vec_model)\n        new_comms = [TextUtils.process(com) for com in new_comms if not TextUtils.is_blank(com)]\n        wd_seqs = [TextUtils.tokenize(com) for com in new_comms if not TextUtils.is_blank(com)]\n        X = self.text2index_from_lst(word2index, wd_seqs)\n        for i, x in enumerate(X):\n            x = np.array(x).reshape(1, -1)\n            res = lstm_model.predict_classes(x)\n            if res[0][0] == LABEL_POS:\n                print(new_comms[i], '\\n', 'positive!')\n            else:\n                print(new_comms[i], '\\n', 'negative!')\n\n\n\n    #情感预测（传入文件路径）\n    def predict_by_file(self, file_path):\n        with open(file_path, 'r', encoding='utf-8') as fin:\n            # new_comms = fin.read().splitlines()\n            new_coms = [line.strip() for line in fin if not TextUtils.is_blank(line)]\n            self.predict_by_lst(new_coms)\n\n    #训练\n    def train(self, comment_dir=COMMENT_DIR):\n        #加载数据\n        df_data = self.load_train_data(comment_dir)\n        #训练词向量模型\n        word2vec_model = self.train_wd2vect(df_data['segs'])\n        #创建索引词典和词向量\n        word2index, word_vectors = self.create_dicts(word2vec_model)\n        # 获取权值矩阵\n        embedding_weights = self.get_embedding_weights(word2index, word_vectors)\n        #文本序列索引化\n        comms_seqs = self.text2index_from_lst(word2index, df_data['segs'])\n        #序列LSTM\n        self.train_lstm_model(embedding_weights, comms_seqs, df_data['label'])\n\n\nif __name__ == \"__main__\":\n    model = SentimentModel()\n    model.train('data/test.csv')\n    model.plot_hist()\n    # new_comms = ['性价比非常高，显示屏幕高清，处理速度快！不带鼠标。很轻，没有想象中的薄。自带的office365需要激活',\n    #              '非常好看！很满意，这个价钱买到质量这么好的鞋子简直太感动了，客服推荐的码数刚好，很合脚，穿起来不磨脚，防滑，耐脏，绝对值！',\n    #              '什么破商家。我申请换货，不让我换，硬要求我退货，我说不退，直接把我电话挂掉，服务差评',\n    #              '冰箱收到了，空间挺大的，冷冻室有点小，能效是三级，冷冻，冷藏，保鲜三室可以调温，送来的时候冰箱里面有点味道！送电以后就没了！总得来说这次购物不错！',\n    #              '发申通物流，很不靠谱，太慢了，本来就是冲着京东物流才买的，结果发的申通，下次再不买它家的了',\n    #              '鞋子已是第二双，朋友看到好看帮忙买的，质量杠杠的，又轻又舒服，春天到了配啥衣服都好看，出去玩也不怕累脚了，值得推荐！！！！',\n    #              '用了两天才过来评论的，首先电脑颜值高，四面窄观影简直不要太舒服，背光键盘也很nice，尺寸大小也很合适，开机使用反应超快的。刚拿到手就插上电@了，语音助手指导小白也能上手。值得购买！',\n    #              '很差，给老爸买的靴子，本来想着尽一份孝心，结果给我的感触很大，家里在县城，那么多快递可以到，偏偏发一个到不了的快递，也不跟买家核实地址，也不打招呼，哪怕跟我们核实一下，我们可以自己选择快递啊。那么大老远，还下着大雨，直接让老人去取。这次购物体验很差，很差。卖家服务态度也很差，很差']\n    # model.predict_by_lst(new_comms)\n\n    # model.predict_by_file(\"user/samples.txt\")", "meta": {"hexsha": "3fbcc1c0e3b13e4811901ce84833f6a832ba813d", "size": 21370, "ext": "py", "lang": "Python", "max_stars_repo_path": "jd_sentiment_analysis_proj/models/LSTM_2_Memory.py", "max_stars_repo_name": "ncuwlz/E-commerce-commentary-sentiment-analysis-platform-based-on-LSTM", "max_stars_repo_head_hexsha": "c893a18f197fd4dc628cde9d57a3bf9a8fbe8167", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-03-16T12:28:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T08:42:35.000Z", "max_issues_repo_path": "jd_sentiment_analysis_proj/models/LSTM_2_Memory.py", "max_issues_repo_name": "ncuwlz/sentiment-analysis-platform", "max_issues_repo_head_hexsha": "c893a18f197fd4dc628cde9d57a3bf9a8fbe8167", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-04-22T16:50:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T20:48:44.000Z", "max_forks_repo_path": "jd_sentiment_analysis_proj/models/LSTM_2_Memory.py", "max_forks_repo_name": "ncuwlz/sentiment-analysis-platform", "max_forks_repo_head_hexsha": "c893a18f197fd4dc628cde9d57a3bf9a8fbe8167", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.2554112554, "max_line_length": 162, "alphanum_fraction": 0.6281703322, "include": true, "reason": "import numpy", "num_tokens": 7170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166195971441, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.17121497783097758}}
{"text": "#!/usr/bin/python\n\n'''\n\nThe header is defined as a class and the attributes\nof header are all input parameters.\n\n'''\n\nimport numpy as np\n\nclass header(object):\n    \n    def __init__(self, path):\n        self.path = path\n        file = open(path,'r')\n        #self.file = file = file.readlines()\n        self.file = file.readlines()\n        \n        line_num = 0\n        for line in self.file:\n            ## Determine lines defining the qmmm block ##\n            if '&qmmm' in line:\n                qmmm_block_start = line_num\n            if '&endqmmm' in line:\n                qmmm_block_end  = line_num\n            ## Determine lines defining the moldyn block ##\n            if '&moldyn' in line:\n                moldyn_block_start = line_num\n            if '&endmoldyn' in line:\n                moldyn_block_end = line_num\n            line_num += 1\n            \n        line_num = 0\n        for line in self.file:\n            '''\n            ## Start geometry optimization ##\n            if 'maxcyc=' in line and 'dav_maxcyc=' not in line:\n                self.maxcyc = np.int(line.split()[0][len('maxcyc='):-1])\n            if 'ntpr=' in line:\n                self.ntpr = np.int(line.split()[0][len('ntpr='):-1])\n            if 'grms_tol=' in line:\n                self.grms_tol = np.float(line.split()[0][len('grms_tol='):-1])\n            ## End geometry optimization ##\n\n            ## Start ground-state and output parameters ##\n            if 'qm_theory=' in line:\n                self.qm_theory = np.str(line.split()[0][len('qm_theory='):-1])\n            if 'scfconv=' in line:\n                self.scfconv = np.float(line.split()[0][len('scfconv='):-1])\n            if 'verbosity=' in line:\n                self.verbosity = np.int(line.split()[0][len('verbosity='):-1])\n            if 'printdipole=' in line:\n                self.printdipole = np.int(line.split()[0][len('printdipole='):-1])\n            if 'printbondorders=' in line:\n                self.printbondorders = np.int(line.split()[0][len('printbondorders='):-1])\n            if 'density_predict=' in line:\n                self.density_predict = np.int(line.split()[0][len('density_predict='):-1])\n            if 'itrmax=' in line:\n                self.itrmax = np.int(line.split()[0][len('itrmax='):-1])\n            ## End ground-state and output parameters ##\n\n            ## Start excited-state parameters ##\n            if 'exst_method=' in line:\n                self.exst_method = np.int(line.split()[0][len('exst_method='):-1])\n            if 'dav_guess=' in line:\n                self.dav_guess = np.int(line.split()[0][len('dav_guess='):-1])\n            if 'ftol0=' in  line:\n                self.ftol0 = np.float(line.split()[0][len('ftol0='):-1])\n            if 'ftol1=' in line:\n                self.ftol1 = np.float(line.split()[0][len('ftol1='):-1])\n            if 'dav_maxcyc=' in line:\n                self.dav_maxcyc = np.int(line.split()[0][len('dav_maxcyc='):-1])\n            if 'printcharges=' in line:\n                self.printcharges = np.int(line.split()[0][len('printcharges='):-1])\n            if 'calcxdens=' in line:\n                self.calcxdens = np.str(line.split()[0][len('calcxdens='):-1])\n            ## End excited-state parameters ##\n\n            ## Start solvent models and external electric fields ##\n            if 'solvent_model=' in line:\n                self.solvent_model = np.int(line.split()[0][len('solvent_model='):-1])\n            if 'potential_type=' in line:\n                self.potential_type = np.int(line.split()[0][len('potential_type='):-1])\n            if 'onsager_radius=' in line:\n                self.onsager_radius = np.float(line.split()[0][len('onsager_radius='):-1])\n            if 'ceps=' in line:\n                self.ceps = np.float(line.split()[0][len('ceps='):-1])\n            if 'linmixparam=' in line:\n                self.linmixparam = np.float(line.split()[0][len('linmixparam='):-1])\n            if 'cosmo_scf_ftol=' in line:\n                self.cosmo_scf_ftol = np.float(line.split()[0][len('cosmo_scf_ftol='):-1])\n            if 'doZ=' in line:\n                self.doZ = np.str(line.split()[0][len('doZ='):-1])\n            if 'index_of_refraction=' in line:\n                self.index_of_refraction = np.float(line.split()[0][len('index_of_refraction='):-1])\n            if 'EF=' in line:\n                self.EF = np.int(line.split()[0][len('EF='):-1])\n            if 'Ex=' in line:\n                self.Ex = np.float(line.split()[0][len('Ex='):-1])\n            if 'Ey=' in line:\n                self.Ey = np.float(line.split()[0][len('Ey='):-1])\n            if 'Ez=' in line:\n                self.Ez = np.float(line.split()[0][len('Ez='):-1])\n            ## End solvent models and external electric fields ##\n            '''\n            ## Start general parameters ##\n            if 'natoms=' in line:\n                self.natoms = np.int(line.split()[0][len('natoms='):-1])\n            '''\n            if 'rnd_seed=' in line:\n                self.rnd_seed = np.int(line.split()[0][len('rnd_seed='):-1])\n            '''\n            if 'bo_dynamics_flag=' in line:\n                self.bo_dynamics_flag = np.int(line.split()[0][len('bo_dynamics_flag='):-1])\n            if 'exc_state_init=' in line:\n                self.exc_state_init = np.int(line.split()[0][len('exc_state_init='):-1])\n            if 'n_exc_states_propagate=' in line:\n                self.n_exc_states_propagate = np.int(line.split()[0][len('n_exc_states_propagate='):-1])\n            ## End general parameters ###\n            \n            ## Start dynamics parameters ##\n            if 'time_init=' in line:\n                self.time_init = np.float(line.split()[0][len('time_init='):-1])\n            if 'time_step=' in line:\n                self.time_step = np.float(line.split()[0][len('time_step='):-1])\n            if 'n_class_steps=' in line:\n                self.n_class_steps = np.int(line.split()[0][len('n_class_steps='):-1])\n            if 'n_quant_steps=' in line:\n                self.n_quant_steps = np.int(line.split()[0][len('n_quant_steps='):-1])\n            '''\n            if 'moldyn_deriv_flag=' in line:\n                self.moldyn_deriv_flag = np.int(line.split()[0][len('moldyn_deriv_flag='):-1])\n            if 'num_deriv_step=' in line:\n                self.num_deriv_step = np.float(line.split()[0][len('num_deriv_step='):-1])\n            if 'rk_tolerance=' in line:\n                self.rk_tolerance = np.float(line.split()[0][len('rk_tolerance='):-1])\n            ## End dynamics parameters ##\n\n            ## Start Nonadiabatic parameters ##\n            if 'decoher_type=' in line:\n                self.decoher_type = np.int(line.split()[0][len('decoher_type='):-1])\n            if 'decoher_e0=' in line:\n                self.decoher_e0 = np.float(line.split()[0][len('decoher_e0='):-1])\n            if 'decoher_c=' in line:\n                self.decoher_c = np.float(line.split()[0][len('decoher_c='):-1])\n            if 'dotrivial=' in line:\n                self.dotrivial = np.int(line.split()[0][len('dotrivial='):-1])\n            if 'quant_step_reduction_factor=' in line:\n                self.quant_step_reduction_factor = np.float(line.split()[0][len('quant_step_reduction_factor='):-1])\n            ## End Nonadiabatic parameters ##\n\n            ## Start thermostat parameters ##\n            if 'therm_type=' in line:\n                self.therm_type = np.int(line.split()[0][len('therm_type='):-1])\n            if 'therm_temperature=' in line:\n                self.therm_temperature = np.float(line.split()[0][len('therm_temperature='):-1])\n            if 'therm_friction=' in line:\n                self.therm_friction = np.float(line.split()[0][len('therm_friction='):-1])\n            if 'berendsen_relax_const=' in line:\n                self.berendsen_relax_const = np.float(line.split()[0][len('berendsen_relax_const='):-1])\n            if 'heating=' in line:\n                self.heating = np.int(line.split()[0][len('heating='):-1])\n            if 'heating_steps_per_degree=' in line:\n                self.heating_steps_per_degree = np.int(line.split()[0][len('heating_steps_per_degree='):-1])\n            ## End thermostat parameters ##\n            '''\n            ## Start output and log parameters ##\n            if 'verbosity=' in line and moldyn_block_start < line_num < moldyn_block_end:\n                self.moldyn_verbosity = np.int(line.split()[0][len('verbosity='):-1])\n            if 'out_data_steps=' in line:\n                self.out_data_steps = np.int(line.split()[0][len('out_data_steps='):-1])\n            if 'out_coords_steps=' in line:\n                self.out_coords_steps = np.int(line.split()[0][len('out_coords_steps='):-1])\n            '''\n            if 'out_data_cube=' in line:\n                self.out_data_cube = np.int(line.split()[0][len('out_data_cube='):-1])\n            if 'out_count_init=' in line:\n                self.out_count_init = np.int(line.split()[0][len('out_count_init='):-1])\n            ## End output and log parameters ##\n            '''\n            ## Check if coefficients are set ##\n            if 'quant_amp_phase_flag' in line:\n                header.quant_amp_phase_flag = 'The quant_amp_phase_flag is in the header.'\n\n            line_num += 1\n", "meta": {"hexsha": "5ce1a1d64d38f43109062c52280cc55dd77fb98a", "size": 9263, "ext": "py", "lang": "Python", "max_stars_repo_path": "getexcited/getexcited_package/header.py", "max_stars_repo_name": "lanl/NEXMD", "max_stars_repo_head_hexsha": "f2cbf1bce06df972bb6596beb979800da833708c", "max_stars_repo_licenses": ["BSD-3-Clause", "Unlicense"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-10-08T13:38:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T20:33:43.000Z", "max_issues_repo_path": "getexcited/getexcited_package/header.py", "max_issues_repo_name": "lanl/NEXMD", "max_issues_repo_head_hexsha": "f2cbf1bce06df972bb6596beb979800da833708c", "max_issues_repo_licenses": ["BSD-3-Clause", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "getexcited/getexcited_package/header.py", "max_forks_repo_name": "lanl/NEXMD", "max_forks_repo_head_hexsha": "f2cbf1bce06df972bb6596beb979800da833708c", "max_forks_repo_licenses": ["BSD-3-Clause", "Unlicense"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-10-08T13:39:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T20:35:10.000Z", "avg_line_length": 49.5347593583, "max_line_length": 116, "alphanum_fraction": 0.5267192054, "include": true, "reason": "import numpy", "num_tokens": 2330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.17121497284794415}}
{"text": "# coding=utf-8\n# !/usr/bin/python3.6 ## Please use python 3.6\n\"\"\"\n__synopsis__    : Builds a matching network, the training and evaluation ops as well as data_loader augmentation routines.\n\n__description__ : Builds a matching network, the training and evaluation ops as well as data_loader augmentation routines.\n__project__     : MNXC\n__author__      : Samujjwal Ghosh <cs16resch01001@iith.ac.in>\n__version__     : \"0.1\"\n__date__        : \"08-11-2018\"\n__copyright__   : \"Copyright (c) 2019\"\n__license__     : This source code is licensed under the MIT-style license found in the LICENSE file in the root\n                  directory of this source tree.\n\n__classes__     : MatchingNetwork\n\n__variables__   :\n\n__methods__     :\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\nfrom models import Attn\nfrom models import PairCosineSim\nfrom logger.logger import logger\nfrom models import BiLSTM\nfrom models import EmbedText\n\nfrom config import configuration as config\n\n\nclass MatchingNetwork(nn.Module):\n    \"\"\"Builds a matching network, the training and evaluation ops as well as data_loader augmentation routines.\"\"\"\n\n    def __init__(self,num_channels: int,layer_size: int,fce: bool = config[\"model\"][\"fce\"]) -> None:\n        \"\"\"\n        Builds a matching network, the training and evaluation ops as well as data_loader augmentation routines.\n\n        :param dropout: A placeholder of type torch.float32 denotes the amount of dropout to be used\n        :param batch_size: The batch size for the experiment\n        :param num_channels: Number of channels of the samples.\n        :param is_training: Flag indicating whether we are training or evaluating\n        :param rotate_flag: Flag indicating whether to rotate the samples.\n        :param fce: Flag indicating whether to use full context embeddings (i.e. apply an LSTM on the CNNText embeddings)\n        # :param num_classes_per_set: Integer indicating the number of classes per set\n        # :param num_samples_per_class: Integer indicating the number of samples per class\n        :param classify_count: total number of classes. It changes the text_lstm size of the classifier g with a final FC layer.\n        :param sample_input: size of the input sample. It is needed in case we want to create the last FC classification.\n        \"\"\"\n        super(MatchingNetwork,self).__init__()\n        self.fce = fce\n\n        self.attn = Attn()\n        self.cosine_dis = PairCosineSim.PairCosineSim()\n        self.g = EmbedText(num_channels,layer_size)\n        if self.fce:\n            self.lstm = BiLSTM(input_size=self.g.output_size + 1)\n\n    def forward(self,supports_x: torch.Tensor,supports_hots: torch.Tensor,targets_x: torch.Tensor,\n                targets_hots: torch.Tensor,target_cat_indices: torch.Tensor,requires_grad: bool = True,\n                batch_size: int = config[\"sampling\"][\"batch_size\"],\n                dropout_external: float = config[\"model\"][\"dropout_external\"]) -> [torch.Tensor,torch.Tensor]:\n        \"\"\"\n        Builds graph for Matching Networks, produces losses and summary statistics.\n\n        :param target_cat_indices:\n        :param requires_grad:\n        :param dropout_external:\n        :param batch_size:\n        :param supports_x: A tensor containing the support set samples.\n            [batch_size, sequence_size, n_channels, 28]\n            torch.Size([32, 25, 1, 28])\n        :param supports_hots: A tensor containing the support set labels.\n            [batch_size, sequence_size, n_classes]\n            torch.Size([32, 25, 5])\n        :param targets_x: A tensor containing the target sample (sample to produce label for).\n            [batch_size, n_channels, 28]\n            torch.Size([32, 5, 1, 28])\n        :param targets_hots: A tensor containing the target label.\n            [batch_size, 1]\n            torch.Size([32, 5])\n        :return:\n        \"\"\"\n        ## Convert target indices to Pytorch multi-label loss format.\n        # target_y_mlml = self.create_mlml_data(target_cat_indices, output_shape=targets_hots.shape)\n\n        logger.debug(\"targets: \\n{}\".format(targets_x))\n        logger.debug(\"supports: \\n{}\".format(supports_x))\n        logger.debug(\n            \"targets X targets: \\n{}\".format(self.cosine_dis(supports=targets_x,targets=targets_x,normalize=False)))\n        logger.debug(\n            \"supports X supports: \\n{}\".format(self.cosine_dis(supports=supports_x,targets=supports_x,normalize=False)))\n        logger.debug(\n            \"supports X targets: \\n{}\".format(self.cosine_dis(supports=supports_x,targets=targets_x,normalize=False)))\n        ## Encode supports\n        supports_x = self.g(supports_x,dropout_external=dropout_external)\n        # logger.debug(\"supports_x [{}] output: {}\".format(supports_x.shape,supports_x))\n\n        ## Encode targets\n        # targets_x = self.g(targets_x, dropout_external=dropout_external)\n        # logger.debug(\"targets_x[{}] output: {}\".format(targets_x.shape,targets_x))\n        # logger.debug(\"emb_targets: \\n{}\".format(targets_x))\n        logger.debug(\"emb_supports: \\n{}\".format(supports_x))\n\n        # logger.debug(\"emb_targets X emb_targets: \\n{}\".format(self.cosine_dis(supports=targets_x, targets=targets_x, normalize=False)))\n        logger.debug(\"emb_supports X emb_supports: \\n{}\".format(\n            self.cosine_dis(supports=supports_x,targets=supports_x,normalize=False)))\n        logger.debug(\"emb_supports X emb_targets: \\n{}\".format(\n            self.cosine_dis(supports=supports_x,targets=targets_x,normalize=False)))\n        if self.fce:\n            # supports_x, _ = self.lstm(supports_x, requires_grad=requires_grad)\n            targets_x,_ = self.lstm(targets_x,requires_grad=requires_grad)\n            # logger.debug(\"FCE supports_x: \\n{}\".format(supports_x))\n            logger.debug(\"FCE targets_x: \\n{}\".format(targets_x))\n            logger.debug(\"FCE_targets X FCE_targets: \\n{}\".format(\n                self.cosine_dis(supports=targets_x,targets=targets_x,normalize=False)))\n            # logger.debug(\"FCE supports_x X FCE supports_x: \\n{}\".format(self.cosine_dis(supports=supports_x, targets=supports_x, normalize=False)))\n\n        ## Calculate similarity between encoded supports and targets\n        similarities = self.cosine_dis(supports=supports_x,targets=targets_x,normalize=True)\n\n        logger.debug(\"FCE supports_x X FCE targets_x: \\n{}\".format(similarities))\n\n        ## Produce predictions for target probabilities. targets_preds.shape = batch_size x # classes\n        targets_preds = self.attn(similarities,supports_hots=supports_hots.float())\n        # logger.debug(\"target_cat_indices: {}\".format(target_cat_indices))\n        # logger.debug(\"targets_preds output: {}\".format(targets_preds))\n\n        loss = 0\n        # multilabel_batch_loss = F.multilabel_margin_loss(targets_preds, target_y_mlml.long())\n\n        ## Calculate loss, need to calculate loss for each sample but for whole batch.\n        for j in np.arange(targets_preds.size(1)):\n            # logger.debug((targets_preds[:, j, :].shape, target_y_mlml.long()[:, j, :].shape))\n            # logger.debug(targets_preds[:, j, :])\n            # logger.debug(target_y_mlml.long()[:, j, :])\n            # logger.debug(targets_preds[:, j, :][0])\n            # logger.debug(target_y_mlml.long()[:, j, :][0])\n            # loss += F.multilabel_margin_loss(targets_preds[:, j, :], target_y_mlml.long()[:, j, :])\n            loss += F.cross_entropy(targets_preds[:,j,:],target_cat_indices[:,j].long())\n        multilabel_batch_loss = loss / targets_x.size(1)\n\n        return multilabel_batch_loss,targets_preds\n\n    @staticmethod\n    def create_mlml_data(target_cat_indices: list,output_shape: tuple) -> torch.Tensor:\n        \"\"\"\n        Generates true labels in proper format for Pytorch Multilabel_Margin_Loss.\n\n        Converts target indices to Pytorch 'multilabel_margin_loss' format. Takes class indices at the beginning and\n        rest should be filled with -1.\n        Link 1: https://gist.github.com/bartolsthoorn/36c813a4becec1b260392f5353c8b7cc#gistcomment-2742606\n        Link 2: https://gist.github.com/bartolsthoorn/36c813a4becec1b260392f5353c8b7cc#gistcomment-2840045\n\n        :param output_shape: Shape of the output = batch_size, target count, # labels.\n        :param target_cat_indices: List of categories.\n        \"\"\"\n        target_y_mlml = torch.full(output_shape,-1)  ## Createing a tensor filled with -1.\n        ## Replacing -1 with label indices at the begining of the tensor row.\n        for i in np.arange(target_y_mlml.size(0)):\n            # logger.debug(target_cat_indices[i])\n            for j in np.arange(target_y_mlml.size(1)):\n                # logger.debug(type(target_cat_indices[i][j]))\n                # logger.debug((i,j,target_cat_indices[i][j]))\n                for k in range(len(target_cat_indices[i][j])):\n                    # logger.debug(target_cat_indices[i][j][k])\n                    target_y_mlml[i,j,k] = torch.tensor(target_cat_indices[i][j][k],dtype=torch.int32)\n\n        return target_y_mlml.long()\n\n\nif __name__ == '__main__':\n    import torch\n\n    support_set = torch.rand(4,2,4)  # [batch_size, sequence_size, input_size]\n    support_set_hot = torch.zeros(4,2,1)  # [batch_size, n_classes]\n    x_hat = torch.rand(4,2,4)\n    x_hat_hot = torch.zeros(4,2,1)\n    logger.debug(support_set_hot)\n    logger.debug(x_hat_hot)\n\n    # support_set = torch.tensor([[[1., 0.4],\n    #                              [1., 1.]],\n    #                             [[1., 0.4],\n    #                              [0., 1.5]],\n    #                             [[1., 0.4],\n    #                              [1., 1.5]]])\n    #\n    support_set_hot = torch.tensor([[[1.,0.],\n                                     [0.,1.]],\n\n                                    [[1.,0.],\n                                     [0.,1.]],\n\n                                    [[1.,0.],\n                                     [0.,1.]],\n\n                                    [[1.,0.],\n                                     [0.,1.]]])\n    #\n    # x_hat = torch.tensor([[[1., 0.4],\n    #                        [0., 1.5]],\n    #                       [[1., 0.4],\n    #                        [1., 1.5]]])\n    #\n    x_hat_hot = torch.tensor([[[1.,0.],\n                               [0.,1.]],\n\n                              [[1.,0.],\n                               [0.,1.]],\n\n                              [[1.,0.],\n                               [0.,1.]],\n\n                              [[1.,0.],\n                               [0.,1.]]])\n\n    logger.debug(support_set.shape)\n    logger.debug(support_set_hot.shape)\n    logger.debug(x_hat.shape)\n    logger.debug(x_hat_hot.shape)\n\n    cls = MatchingNetwork(input_size=4,hid_size=4,classify_count=5,use_cuda=False)\n    logger.debug(cls)\n    sim = cls.forward(support_set,support_set_hot,x_hat,x_hat_hot,batch_size=4)\n    logger.debug(sim)\n", "meta": {"hexsha": "d363f3cfcef16d10ce93e91e675ea87b0d3e9f01", "size": 10894, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/MatchingNetwork.py", "max_stars_repo_name": "SamujjwalSam/MatchingNetworks4XC", "max_stars_repo_head_hexsha": "2519cc1a527ea121c4966c1a860d890d5182f887", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/MatchingNetwork.py", "max_issues_repo_name": "SamujjwalSam/MatchingNetworks4XC", "max_issues_repo_head_hexsha": "2519cc1a527ea121c4966c1a860d890d5182f887", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/MatchingNetwork.py", "max_forks_repo_name": "SamujjwalSam/MatchingNetworks4XC", "max_forks_repo_head_hexsha": "2519cc1a527ea121c4966c1a860d890d5182f887", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1601731602, "max_line_length": 149, "alphanum_fraction": 0.6199742978, "include": true, "reason": "import numpy", "num_tokens": 2587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.17121497284794415}}
{"text": "import numpy as np\n\ntry:\n    import cPickle as pickle\nexcept ImportError:\n    import pickle\n\nfrom src.SpectralAnalysis import utils\nfrom src.SpectralAnalysis import LightCurve\nfrom src.SpectralAnalysis import powerspectrum\nfrom src.SpectralAnalysis import bayes\nfrom src.SpectralAnalysis import mcmc\nfrom src.SpectralAnalysis.parametricmodels import pl, bpl\n\nclass Burst(object):\n    def __init__(self, bstart, blength,\n                 energies=None,\n                 photons=None,\n                 events=None,\n                 filename=None,\n                 instrument=\"gbm\",\n                 fnyquist=4096.0,\n                 norm='leahy',\n                 fluence=None,\n                 epeak=None,\n                 ttrig=None,\n                 addfrac=0.2):\n\n        ### which instrument was used to record this data\n        ### note: this makes a difference in terms of file formats\n        ### and general data structure\n        self.instrument = instrument\n\n        if \":\" in str(bstart):\n            self.bst = self.convert_time(bstart)\n        else:\n            self.bst = bstart\n\n        self.blen = blength + 2. * addfrac * blength\n\n        start = self.bst - addfrac * blength\n        length = (1. + 2. * addfrac) * self.blen\n        end = start + length\n\n        ### assume burst length is in seconds\n        self.fluence = fluence\n        self.epeak = epeak\n        self.ttrig = ttrig\n\n        ### data is in form of Photon objects such that time/energy filtering\n        ### becomes easy\n        if photons is None and filename:\n            self.read_data(filename)\n\n        elif not photons is None:\n            self.photons = photons\n\n        else:\n            raise Exception(\"Data missing! You must specify either a photon \"\n                            \"object or a file name from which to read the data!\")\n\n        if not events is None:\n            self.energies = events\n        startind = photons.searchsorted(start)\n        endind = photons.searchsorted(end)\n        self.photons = self.photons[startind:endind]\n        self.energies = self.energies[startind:endind]\n\n        ### filter for energy selection, if this is specified\n        # if energies:\n        #    gt.Data.filterenergy(self, energies[0], energies[1])\n        if energies:\n            self.photons = np.array([s for s, e in zip(self.photons, self.energies) if energies[0] <= e <= energies[1]])\n            self.energies = np.array(\n                [e for s, e in zip(self.photons, self.energies) if energies[0] <= e <= energies[1]])\n\n        #### filter for burst times\n        # gt.Data.filterburst([self.bst-0.1*self.blen, self.bend+0.1*self.blen])\n\n        ### make a light curve\n        self.time = self.photons\n        # print(\"length time: \" + str(len(self.time)))\n        # print(\"tseg: \" + str(self.time[-1] - self.time[0]))\n\n        # self.time = np.array([s.time for s in self.photons])\n        self.lc = LightCurve.LightCurve(self.time, timestep=0.5 / fnyquist, tseg=self.blen, tstart=self.bst)\n\n        # print(\"length lc: \" + str(len(self.lc.time)))\n\n        ### make a periodogram\n        self.ps = powerspectrum.PowerSpectrum(self.lc, norm=norm)\n\n        return\n\n    #### CONVERT TIME ##############\n    #\n    # convert from HH:MM:SS to seconds\n    #\n    def convert_time(self, time):\n        hours = float(time[:2]) * 3600.0\n        minutes = float(time[3:5]) * 60.0\n        seconds = float(time[6:])\n        tnew = hours + minutes + seconds\n        return tnew\n\n    #### READ DATA FROM FILE\n    #\n    # read time-tagged event data from file\n    # keyword 'type' can be either one of\n    #                - \"ascii\" = read ascii data\n    #                - \"pickle\" = read data from python pickle file\n    #                   that contains a list of photon objects\n    def read_data(self, filename, type=\"ascii\"):\n        if type in [\"a\", \"ascii\"]:\n            data = utils.conversion(filename)\n            time = np.array([float(t) for t in data[0]])\n            events = np.array([float(e) for e in data[1]])\n            self.photons = [utils.Photon(t, e) for t, e in zip(time, events)]\n        elif type in [\"p\", \"pickle\"]:\n            self.photons = utils.getpickle(filename)\n        else:\n            raise Exception(\"File type not recognized! Must be one of 'pickle' or 'ascii'!\")\n        return\n\n    def bayesian_analysis(self, namestr='test', nchain=500, niter=100, nsim=1000, m=1, fitmethod='bfgs'):\n\n        btest = bayes.Bayes(self.ps, namestr=namestr, m=m)\n        psfit, fakeper, self.model_summary = btest.choose_noise_model(pl, [2, 3, 0.5],\n                                                                      bpl, [1, 3, 2, 3, 0.5],\n                                                                      nchain=nchain, niter=niter, nsim=nsim,\n                                                                      fitmethod=fitmethod)\n\n        if not psfit:\n            print(\"Analysis of burst \" + str(namestr) + \" failed. Returning ...\")\n            return\n\n        else:\n            if self.model_summary[\"p_lrt\"][0] < 0.05:\n                print(\"Model not adequately fit by a power law! Using broken power law instead!\")\n                self.model = bpl\n                self.psfit = getattr(psfit, str(self.model).split()[1] + \"fit\")\n            else:\n                self.model = pl\n                self.psfit = getattr(psfit, str(self.model).split()[1] + \"fit\")\n\n            self.per_summary = btest.find_periodicity(self.model, self.psfit[\"popt\"], nchain=nchain, niter=niter,\n                                                      nsim=nsim, fitmethod=fitmethod)\n\n            self.mcmc = self.per_summary[\"mcobs\"]\n            return\n\n    #### MAKE AN MCMC SAMPLE #######################\n    #\n    # Runs the MarkovChainMonteCarlo code to make\n    # an MCMC sample independent of the Bayes routines.\n    #\n    def mcmc_sample(self, func, pars, cov, nchain=500, niter=100, nsim=1000):\n\n        mcobs = mcmc.MarkovChainMonteCarlo(self.ps, func=func, topt=pars, tcov=cov, nchain=nchain, niter=niter,\n                                           nsim=nsim)\n\n        return mcobs\n\n    def save_burst(self, filename):\n\n        burstfile = open(filename, 'w')\n        pickle.dump(self, burstfile)\n        burstfile.close()\n        return\n\n\n#####################################################\n#####################################################\n#####################################################\n\n\n#### BURST SUBCLASS FOR GBM DATA ###################\n#\n# Subclass of class Burst to deal with GBM data\n# and GBM specific issues\n#\n#\nclass GBMBurst(Burst):\n    def __init__(self, bid, bstart, blength,\n                 energies=None,\n                 photons=None,\n                 events=None,\n                 filename=None,\n                 instrument=\"gbm\",\n                 fnyquist=4096.0,\n                 norm='leahy',\n                 fluence=None,\n                 epeak=None,\n                 ttrig=None,\n                 addfrac=0.2):\n        ### set burst ID\n        self.bid = bid\n\n        ### if photons and filename aren't given, then data comes from procdata file\n        if photons is None and filename is None:\n            filename = \"tte_bn\" + str(bid) + \"_procdata.dat\"\n\n        Burst.__init__(self, bstart, blength, energies,\n                       photons, events, filename,\n                       instrument, fnyquist, norm,\n                       fluence, epeak, ttrig, addfrac)\n        # super(self.__class__, self).__init__(bstart, blength, energies,\n        #                               photons, events, filename,\n        #                               instrument, fnyquist, norm,\n        #                               fluence, epeak, ttrig, addfrac)\n\n        return\n\n    def read_data(self, filename, filetype='ascii', det=\"combined\"):\n        Burst.read_data(self, filename, type=filetype)\n\n        evt = self.photons[det]\n        self.photons = np.array([x.time for x in evt.photons])\n        self.energies = np.array([x.energy for x in evt.photons])\n        return\n", "meta": {"hexsha": "c06336d470084bf4da76688852e61d971521824f", "size": 8027, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/SpectralAnalysis/burst.py", "max_stars_repo_name": "axr6077/Black-Hole-X-ray-binary-Evolution", "max_stars_repo_head_hexsha": "50364d05903166a67778026cc975349dd58a0043", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-19T19:13:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-19T19:13:52.000Z", "max_issues_repo_path": "src/SpectralAnalysis/burst.py", "max_issues_repo_name": "axr6077/Black-Hole-X-ray-binary-Evolution", "max_issues_repo_head_hexsha": "50364d05903166a67778026cc975349dd58a0043", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-04-02T07:24:19.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-02T21:15:32.000Z", "max_forks_repo_path": "src/SpectralAnalysis/burst.py", "max_forks_repo_name": "axr6077/Black-Hole-X-ray-binary-Evolution", "max_forks_repo_head_hexsha": "50364d05903166a67778026cc975349dd58a0043", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3212669683, "max_line_length": 120, "alphanum_fraction": 0.5282172667, "include": true, "reason": "import numpy", "num_tokens": 1895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.3174262785020255, "lm_q1q2_score": 0.17108743321666}}
{"text": "import sys\nimport os.path\nfrom numpy import logical_and\n\n# print sys.path\nsys.path.append(\"~/git/py-mmcif\")\nfrom mmcif.io.PdbxReader import PdbxReader\nfrom NEFTranslator import NEFTranslator\nfrom math import sqrt, acos\nimport numpy\nimport pynmrstar\nfrom monkeypatch import patch_parser\nimport xml.etree.ElementTree as ET\nfrom operator import itemgetter\n\npatch_parser(pynmrstar)\n\nimport json\n\n\nclass Validate_NMR_Restraints:\n    \"\"\"\n    NMR restraints validation module\n    \"\"\"\n    __version__ = \"v0.8\"\n\n    def __init__(self,cif_file, star_file):\n        self.run_validation(cif_file,star_file)\n\n\n    def run_validation(self,cif_file,star_file):\n        #nt = NEFTranslator.NEFTranslator()\n        pdb, atom_ids = self.get_coordinates(cif_file)\n        max_models = len(pdb.keys())\n        distance, angle, chain_dict = self.get_restraints(star_file)\n        dv = self.calculate_distance_violations(pdb, distance)\n        av = self.calculate_angle_violations(pdb, angle)\n        self.write_xml(dv, av, distance, angle, atom_ids)\n        # self.write_xml_simple(dv, av)\n        dist_viol_stat, dist_viol = self.calculate_violation_statistics(dv)\n        ang_viol_stat, ang_viol = self.calculate_violation_statistics(av)\n        self.bin_distance_violations(dv)\n        sorted_dist_viol_stat = sorted(dist_viol_stat, reverse=True, key=itemgetter(0, 3))\n        sorted_dist_viol = sorted(dist_viol, reverse=True, key=itemgetter(0))\n        sorted_ang_viol_stat = sorted(ang_viol_stat, reverse=True, key=itemgetter(0, 3))\n        sorted_ang_viol = sorted(ang_viol, reverse=True, key=itemgetter(0))\n        type_stat_dist = self.restraints_type_statistics(dist_viol_stat, max_models)\n        type_stat_ang = self.restraints_type_statistics(ang_viol_stat, max_models)\n        json_data = self.generate_json(type_stat_dist, type_stat_ang, sorted_dist_viol_stat, sorted_dist_viol,\n                                       sorted_ang_viol_stat, sorted_ang_viol)\n        with open('data_json.json', 'w') as write_file:\n            json.dump(json_data, write_file)\n        return json_data\n\n    @staticmethod\n    def generate_json(type_stat_dist, type_stat_ang, dist_viol_stat, dist_viol, ang_viol_stat, ang_viol):\n        restraints_validation = {}\n        distance = {}\n        distance['summary'] = type_stat_dist[0]\n        distance['violated'] = type_stat_dist[2]\n        distance['consistently_violated'] = type_stat_dist[1]\n        distance['sorted_average_violations'] = dist_viol_stat\n        distance['sorted_violations'] = dist_viol\n        angle = {}\n        angle['summary'] = type_stat_ang[0]\n        angle['violated'] = type_stat_ang[2]\n        angle['consistently_violated'] = type_stat_ang[1]\n        angle['sorted_average_violations'] = ang_viol_stat\n        angle['sorted_violations'] = ang_viol\n        restraints_validation['distance'] = distance\n        restraints_validation['angle'] = angle\n        return restraints_validation\n\n    @staticmethod\n    def restraints_type_statistics(violation_statistics, max_models):\n        \"\"\"\n        Counts the number of restraints and violations in each restraints type(distance: intraresidue, sequential,\n        medium, long; angle : PHI, PSI, etc.. )\n        :param violation_statistics: output from calculate_violation_statisitcs\n        :param max_models: Number of models in the ensemble (required to estimate the consistently violated restraitns)\n        :return: three statistics in a dictionary format (General summary, Consistently violated, Violated)\n        \"\"\"\n        rest_type_v = [i[5] for i in violation_statistics if i[3] != 0]  # Violated at lease in one model\n        rest_type_cv = [i[5] for i in violation_statistics if i[3] == max_models]  # Violated in all modes\n        rest_type_all = [i[5] for i in violation_statistics]\n        uniq_type = list(set(rest_type_all))\n        type_count_all = {}\n        type_count_v = {}\n        type_count_cv = {}\n        total_all = len(violation_statistics)\n        type_count_all['total'] = (total_all, 100.00)  # Count and percentage\n        for i in uniq_type:\n            type_count_all[i] = (\n                rest_type_all.count(i), round(((float(rest_type_all.count(i)) / float(total_all)) * 100.00), 2))\n            type_count_v[i] = (\n                rest_type_v.count(i),\n                round(((float(rest_type_v.count(i)) / float(rest_type_all.count(i))) * 100.00), 2))\n            type_count_cv[i] = (\n                rest_type_cv.count(i),\n                round(((float(rest_type_cv.count(i)) / float(rest_type_all.count(i))) * 100.00), 2))\n        return type_count_all, type_count_cv, type_count_v\n\n    @staticmethod\n    def get_coordinates(cif_file):\n        \"\"\"\n        Extract coordinate information from cif file as a dictionary\n        {model_id : {(seq_id,chain_id,res_id,atom_id) : array[x,y,x],...},...}\n        :param cif_file: Input coordinate file\n        :return: dictionary\n        \"\"\"\n        cif_data = []\n        ifh = open(cif_file, 'r')\n        pRd = PdbxReader(ifh)\n        pRd.read(cif_data)\n        ifh.close()\n        c0 = cif_data[0]\n        atom_site = c0.getObj('atom_site')\n        max_models = int(atom_site.getValue('pdbx_PDB_model_num', -1))\n        col_names = atom_site.getAttributeList()\n        model_id = col_names.index('pdbx_PDB_model_num')\n        x_id = col_names.index('Cartn_x')\n        y_id = col_names.index('Cartn_y')\n        z_id = col_names.index('Cartn_z')\n        atom_id = col_names.index('label_atom_id')\n        comp_id = col_names.index('label_comp_id')\n        asym_id = col_names.index('label_asym_id')\n        entity_id = col_names.index('label_entity_id')\n        seq_id = col_names.index('label_seq_id')\n        icode_id = col_names.index('pdbx_PDB_ins_code')\n        alt_id = col_names.index('label_alt_id')\n        aut_seq_id = col_names.index('auth_seq_id')\n        aut_aym_id = col_names.index('auth_asym_id')\n        pdb_models = {}\n        atom_ids = {}\n        for model in range(1, max_models + 1):\n            pdb = {}\n            aid = {}\n            for dat in atom_site.getRowList():\n                if int(dat[model_id]) == model:\n                    aid[(dat[seq_id], dat[asym_id], dat[comp_id], dat[atom_id])] = \\\n                        (dat[entity_id], dat[asym_id], dat[comp_id], dat[seq_id], dat[aut_seq_id],\n                         dat[alt_id], dat[icode_id], dat[aut_aym_id])\n                    pdb[(dat[seq_id], dat[asym_id], dat[comp_id], dat[atom_id])] = \\\n                        numpy.array([float(dat[x_id]), float(dat[y_id]), float(dat[z_id])])\n            pdb_models[model] = pdb\n            atom_ids[model] = aid\n        return pdb_models, atom_ids\n\n    @staticmethod\n    def get_restraints(star_file):\n        \"\"\"\n        Extracts restraints from NMR-STAR file\n        :param star_file: NMR-STAR file\n        :return: distance restraints in dictionary format, angle restraints in dictionary format, chain map as dictionary\n        \"\"\"\n        lp_flg = 0\n        dat_flg = 1\n        try:\n            star_data = pynmrstar.Entry.from_file(star_file)\n            dist_sf = star_data.get_saveframes_by_category('general_distance_constraints')\n        except ValueError:\n            try:\n                sf_data = pynmrstar.Saveframe.from_file(star_file)\n                if sf_data.get_tag('Sf_category')[0] == 'general_distance_constraints':\n                    dist_sf = [sf_data]\n                else:\n                    print(\"Error : file doesn't have restraints data\")\n                    dat_flg = 0\n            except ValueError:\n                try:\n                    lp_data = pynmrstar.Loop.from_file(star_file)\n                    lp_flg = 1\n                    if lp_data.category == '_Gen_dist_constraint':\n                        dist_sf = [lp_data]\n                    else:\n                        print(\"Error : file doesn't have restraints data\")\n                        dat_flg = 0\n                except ValueError:\n                    print(\"ERROR : File contains no valid saveframe or loop\")\n                    dat_flg = 0\n        except IOError:\n            print(\"Error file not found\")\n            dat_flg = 0\n\n        try:\n            entity_assembly = star_data.get_loops_by_category('_Entity_assembly')[0]\n            col_names = entity_assembly.get_tag_names()\n            id_index = col_names.index('_Entity_assembly.ID')\n            asym_index = col_names.index('_Entity_assembly.Asym_ID')\n            chain_dict = {}\n            for row in entity_assembly:\n                chain_map[row[id_index]] = row[asym_index]\n        except IndexError:\n            print(\"Entity_assembly loop not found, No chain mapping created\")\n            chain_dict = {}\n        if dat_flg:\n            dist_dict2 = {}\n            dist_dict = {}\n            for sf in dist_sf:\n                if lp_flg:\n                    dat = sf\n                else:\n                    dat = sf.get_loop_by_category('_Gen_dist_constraint')\n                col_names = dat.get_tag_names()\n                rest_id = col_names.index('_Gen_dist_constraint.ID')\n                seq_id_1 = col_names.index('_Gen_dist_constraint.Comp_index_ID_1')\n                asym_id_1 = col_names.index('_Gen_dist_constraint.Auth_asym_ID_1')\n                entity_id_1 = col_names.index('_Gen_dist_constraint.Entity_assembly_ID_1')\n                comp_id_1 = col_names.index('_Gen_dist_constraint.Comp_ID_1')\n                atom_id_1 = col_names.index('_Gen_dist_constraint.Atom_ID_1')\n                seq_id_2 = col_names.index('_Gen_dist_constraint.Comp_index_ID_2')\n                asym_id_2 = col_names.index('_Gen_dist_constraint.Auth_asym_ID_2')\n                entity_id_2 = col_names.index('_Gen_dist_constraint.Entity_assembly_ID_2')\n                comp_id_2 = col_names.index('_Gen_dist_constraint.Comp_ID_2')\n                atom_id_2 = col_names.index('_Gen_dist_constraint.Atom_ID_2')\n                lb_id = col_names.index('_Gen_dist_constraint.Distance_lower_bound_val')\n                ub_id = col_names.index('_Gen_dist_constraint.Distance_upper_bound_val')\n                list_id = col_names.index('_Gen_dist_constraint.Gen_dist_constraint_list_ID')\n                r_dict = {}\n                for rest in dat:\n                    if rest[rest_id] not in r_dict.keys():\n                        r_dict[rest[rest_id]] = []\n                    if (rest[list_id], rest[rest_id]) not in dist_dict2.keys():\n                        dist_dict2[(rest[list_id], rest[rest_id])] = []\n                    if rest[asym_id_1] == '.':\n                        eid1 = chain_dict[rest[entity_id_1]]\n                    else:\n                        eid1 = rest[asym_id_1]\n                    if rest[asym_id_2] == '.':\n                        eid2 = chain_dict[rest[entity_id_2]]\n                    else:\n                        eid2 = rest[asym_id_2]\n\n                    atom1 = (rest[seq_id_1], eid1, rest[comp_id_1], rest[atom_id_1])\n                    atom2 = (rest[seq_id_2], eid2, rest[comp_id_2], rest[atom_id_2])\n                    if atom1[1] != atom2[1]:\n                        cat = 'long'\n                    elif abs(int(atom1[0]) - int(atom2[0])) == 0:\n                        cat = 'intraresidue'\n                    elif abs(int(atom1[0]) - int(atom2[0])) == 1:\n                        cat = 'sequential'\n                    elif 1 < abs(int(atom1[0]) - int(atom2[0])) < 5:\n                        cat = 'medium'\n                    elif abs(int(atom1[0]) - int(atom2[0])) >= 5:\n                        cat = 'long'\n                    try:\n                        lb = float(rest[lb_id])\n                    except ValueError:\n                        lb = -999.9\n                    try:\n                        ub = float(rest[ub_id])\n                    except ValueError:\n                        ub = 999.9\n                    if lb == -999.9 and ub == 999.9:\n                        print(\"Error: Distance restraint value not readable for restraint id {}; \"\n                              \"for atoms {},{}\".format(rest[rest_id], atom1, atom2))\n                    else:\n                        r_dict[rest[rest_id]].append([atom1, atom2, lb, ub, cat])\n                        dist_dict2[(rest[list_id], rest[rest_id])].append([atom1, atom2, cat, lb, ub])\n                if lp_flg:\n                    dist_dict['distance_restraints'] = r_dict\n                else:\n                    dist_dict[sf.name] = r_dict\n        else:\n            dist_dict2 = None\n        dat_flg = 1\n        lp_flg = 0\n        try:\n            star_data = pynmrstar.Entry.from_file(star_file)\n            ang_sf = star_data.get_saveframes_by_category('torsion_angle_constraints')\n        except ValueError:\n            try:\n                sf_data = pynmrstar.Saveframe.from_file(star_file)\n                if sf_data.get_tag('Sf_category')[0] == 'torsion_angle_constraints':\n                    ang_sf = [sf_data]\n                else:\n                    print(\"Error : file doesn't have restraints data\")\n                    dat_flg = 0\n            except ValueError:\n                try:\n                    lp_data = pynmrstar.Loop.from_file(star_file)\n                    lp_flg = 1\n                    if lp_data.category == '_Torsion_angle_constraint':\n                        ang_sf = [lp_data]\n                    else:\n                        print(\"Error : file doesn't have restraints data\")\n                        dat_flg = 0\n                except ValueError:\n                    print(\"ERROR : File contains no valid saveframe or loop\")\n                    dat_flg = 0\n        except IOError:\n            print(\"Error file not found\")\n            dat_flg = 0\n        if dat_flg:\n            angle_dict = {}\n            angle_dict2 = {}\n            for sf in ang_sf:\n                if lp_flg:\n                    dat = sf\n                else:\n                    dat = sf.get_loop_by_category('_Torsion_angle_constraint')\n                col_names = dat.get_tag_names()\n                rest_id = col_names.index('_Torsion_angle_constraint.ID')\n                rest_name_id = col_names.index(\"_Torsion_angle_constraint.Torsion_angle_name\")\n                seq_id_1 = col_names.index('_Torsion_angle_constraint.Comp_index_ID_1')\n                asym_id_1 = col_names.index('_Torsion_angle_constraint.Auth_asym_ID_1')\n                entity_id_1 = col_names.index('_Torsion_angle_constraint.Entity_assembly_ID_1')\n                comp_id_1 = col_names.index('_Torsion_angle_constraint.Comp_ID_1')\n                atom_id_1 = col_names.index('_Torsion_angle_constraint.Atom_ID_1')\n                seq_id_2 = col_names.index('_Torsion_angle_constraint.Comp_index_ID_2')\n                asym_id_2 = col_names.index('_Torsion_angle_constraint.Auth_asym_ID_2')\n                entity_id_2 = col_names.index('_Torsion_angle_constraint.Entity_assembly_ID_2')\n                comp_id_2 = col_names.index('_Torsion_angle_constraint.Comp_ID_2')\n                atom_id_2 = col_names.index('_Torsion_angle_constraint.Atom_ID_2')\n                seq_id_3 = col_names.index('_Torsion_angle_constraint.Comp_index_ID_3')\n                asym_id_3 = col_names.index('_Torsion_angle_constraint.Auth_asym_ID_3')\n                entity_id_3 = col_names.index('_Torsion_angle_constraint.Entity_assembly_ID_3')\n                comp_id_3 = col_names.index('_Torsion_angle_constraint.Comp_ID_3')\n                atom_id_3 = col_names.index('_Torsion_angle_constraint.Atom_ID_3')\n                seq_id_4 = col_names.index('_Torsion_angle_constraint.Comp_index_ID_4')\n                asym_id_4 = col_names.index('_Torsion_angle_constraint.Auth_asym_ID_4')\n                entity_id_4 = col_names.index('_Torsion_angle_constraint.Entity_assembly_ID_4')\n                comp_id_4 = col_names.index('_Torsion_angle_constraint.Comp_ID_4')\n                atom_id_4 = col_names.index('_Torsion_angle_constraint.Atom_ID_4')\n                lb_id = col_names.index('_Torsion_angle_constraint.Angle_lower_bound_val')\n                ub_id = col_names.index('_Torsion_angle_constraint.Angle_upper_bound_val')\n                list_id = col_names.index('_Torsion_angle_constraint.Torsion_angle_constraint_list_ID')\n                r_dict = {}\n                for rest in dat:\n                    if rest[rest_id] not in r_dict.keys():\n                        r_dict[rest[rest_id]] = []\n                    if (rest[list_id], rest[rest_id]) not in angle_dict2.keys():\n                        angle_dict2[(rest[list_id], rest[rest_id])] = []\n\n                    if rest[asym_id_1] == '.':\n                        eid1 = chain_dict[rest[entity_id_1]]\n                    else:\n                        eid1 = rest[asym_id_1]\n                    if rest[asym_id_2] == '.':\n                        eid2 = chain_dict[rest[entity_id_2]]\n                    else:\n                        eid2 = rest[asym_id_2]\n                    if rest[asym_id_3] == '.':\n                        eid3 = chain_dict[rest[entity_id_3]]\n                    else:\n                        eid3 = rest[asym_id_3]\n                    if rest[asym_id_4] == '.':\n                        eid4 = chain_dict[rest[entity_id_4]]\n                    else:\n                        eid4 = rest[asym_id_4]\n\n                    atom1 = (rest[seq_id_1], eid1, rest[comp_id_1], rest[atom_id_1])\n                    atom2 = (rest[seq_id_2], eid2, rest[comp_id_2], rest[atom_id_2])\n                    atom3 = (rest[seq_id_3], eid3, rest[comp_id_3], rest[atom_id_3])\n                    atom4 = (rest[seq_id_4], eid4, rest[comp_id_4], rest[atom_id_4])\n                    rest_name = rest[rest_name_id]\n                    try:\n                        lb = float(rest[lb_id])\n                    except ValueError:\n                        lb = -999.9\n                    try:\n                        ub = float(rest[ub_id])\n                    except ValueError:\n                        ub = 999.9\n                    if lb == -999.9 and ub == 999.9:\n                        print(\"Error: Distance restraint value not readable for restraint id {}; \"\n                              \"for atoms {},{}\".format(rest[rest_id], atom1, atom2))\n                    else:\n                        r_dict[rest[rest_id]].append([atom1, atom2, atom3, atom4, rest_name, lb, ub])\n                        angle_dict2[(rest[list_id], rest[rest_id])].append(\n                            [atom1, atom2, atom3, atom4, rest_name, lb, ub])\n                if lp_flg:\n                    angle_dict['angle_restraints'] = r_dict\n                else:\n                    angle_dict[sf.name] = r_dict\n        else:\n            angle_dict = None\n            angle_dict2 = None\n        return dist_dict2, angle_dict2, chain_dict\n\n    @staticmethod\n    def get_distance(c1, c2):\n        \"\"\"\n        Calculates the distance between two coordinate points\n        :param c1: array of x,y,z\n        :param c2: array of x,y,z\n        :return: distance between two ponts\n        \"\"\"\n        return numpy.linalg.norm(c1 - c2)\n\n    @staticmethod\n    def get_dihedral_angle(c1, c2, c3, c4):\n        \"\"\"\n        Calculates the dihedral angle from the given set of four coordinate values\n        :param c1: array of x,y,z\n        :param c2: array of x,y,z\n        :param c3: array of x,y,z\n        :param c4: array of x,y,z\n        :return: angle in degrees\n        \"\"\"\n        bv12 = c1 - c2\n        bv32 = c3 - c2\n        bv43 = c4 - c3\n        pv13 = numpy.cross(bv12, bv32)\n        pv24 = numpy.cross(bv43, bv32)\n        pro = numpy.dot(pv13, pv24)\n        sqdist13 = numpy.dot(pv13, pv13)\n        sqdist24 = numpy.dot(pv24, pv24)\n        cosin = pro / sqrt(sqdist13 * sqdist24)\n        cosin - min(1.0, max(-1.0, cosin))\n        angle = acos(cosin)\n\n        if numpy.dot(pv13, numpy.cross(pv24, bv32)) < 0:\n            angle = -angle\n        return round(numpy.degrees(angle), 4)\n\n\n\n    @staticmethod\n    def r6sum(dist_list):\n        \"\"\"\n        Calculates 1/r^6 sum for ambiguous restraints as recommended by NMR VTF\n        :param dist_list: list of distances\n        :return: r6 sum\n        \"\"\"\n        return (sum([i ** (-6.) for i in dist_list])) ** (-1. / 6.)\n\n    def calculate_distance_violations(self, coordinates, restraints):\n        \"\"\"\n        Calculates violation for each restraint\n        :param coordinates:  output from get_coordinates\n        :param restraints:  output from get_restraints\n        :return: dictionary { rest identifier : { model no : (value, 'type') }} example {('1', '1210'):\n        {1: (0.22874009681108554, 'long'), 2: (0.084672752498432757, 'long')...}}\n        \"\"\"\n        violations = {}\n        for rest_id in restraints.keys():\n            m = {}\n            for model in coordinates.keys():\n                dist_list = []\n                for rest in restraints[rest_id]:\n                    atom_1 = rest[0]\n                    atom_2 = rest[1]\n                    cat = rest[2]\n                    lb = rest[3]\n                    ub = rest[4]\n                    pos_1 = coordinates[model][atom_1]\n                    pos_2 = coordinates[model][atom_2]\n                    d = self.get_distance(pos_1, pos_2)\n                    dist_list.append(d)\n                r6dist = self.r6sum(dist_list)\n                if lb <= r6dist <= ub:\n                    err = 0.0\n                elif r6dist < lb:\n                    err = abs(r6dist - lb)\n                else:\n                    err = abs(r6dist - ub)\n                m[model] = (err, cat)\n            violations[rest_id] = m\n        return violations\n\n    def calculate_angle_violations(self, coordinates, restraints):\n        \"\"\"\n        Calculates violation for each restraint\n        :param coordinates: output from get_coordinates\n        :param restraints:  output from get_restraints\n        :return: dictionary { rest identifier : { model no : (value, 'type') }} example {('1', '121'):\n        {1: (0.22874009681108554, 'PSI'), 2: (0.084672752498432757, 'PHI')...}}\n        \"\"\"\n        violations = {}\n        for rest_id in restraints.keys():\n            m = {}\n            for model in coordinates.keys():\n                ang_list = []\n                for rest in restraints[rest_id]:\n                    atom_1 = rest[0]\n                    atom_2 = rest[1]\n                    atom_3 = rest[2]\n                    atom_4 = rest[3]\n                    cat = rest[4]\n                    lb = rest[5]\n                    ub = rest[6]\n                    pos_1 = coordinates[model][atom_1]\n                    pos_2 = coordinates[model][atom_2]\n                    pos_3 = coordinates[model][atom_3]\n                    pos_4 = coordinates[model][atom_4]\n                    ang = self.get_dihedral_angle(pos_1, pos_2, pos_3, pos_4)\n                    ang_list.append(ang)\n                avg_viol = numpy.mean(ang_list)\n                if lb <= avg_viol <= ub:\n                    err = 0.0\n                elif avg_viol < lb:\n                    err = abs(avg_viol - lb)\n                else:\n                    err = abs(avg_viol - ub)\n                m[model] = (err, cat)\n            violations[rest_id] = m\n        return violations\n\n    @staticmethod\n    def write_xml(distance_violations, angle_violations, distance, angle, atom_ids):\n        rest_ids = list(distance_violations.keys())\n        model_ids = list(distance_violations[rest_ids[0]].keys())\n        violations = ET.Element('RestraintsViolations')\n        dist_viol = ET.SubElement(violations, 'DistanceViolations')\n        for m_id in model_ids[:50]:\n            models = ET.SubElement(dist_viol, 'Model')\n            models.set('model', str(m_id))\n            for r_id in rest_ids[:50]:\n                for rest in distance[r_id]:\n                    if distance_violations[r_id][m_id][0] > 0.0:\n                        model = ET.SubElement(models, 'Violation')\n                        model.set('rest_id', str(r_id[1]))\n                        model.set('rest_list_id', str(r_id[0]))\n                        model.set('model_1', str(m_id))\n                        model.set('chain_1', atom_ids[m_id][rest[0]][7])\n                        model.set('resnum_1', atom_ids[m_id][rest[0]][4])\n                        model.set('ent_1', atom_ids[m_id][rest[0]][0])\n                        model.set('altcode_1', atom_ids[m_id][rest[0]][5])\n                        model.set('icode_1', atom_ids[m_id][rest[0]][6])\n                        model.set('seq_1', atom_ids[m_id][rest[0]][3])\n                        model.set('said_1', atom_ids[m_id][rest[0]][1])\n                        model.set('resname_1', atom_ids[m_id][rest[0]][2])\n                        model.set('model_2', str(m_id))\n                        model.set('chain_2', atom_ids[m_id][rest[1]][7])\n                        model.set('resnum_2', atom_ids[m_id][rest[1]][4])\n                        model.set('ent_2', atom_ids[m_id][rest[1]][0])\n                        model.set('altcode_2', atom_ids[m_id][rest[1]][5])\n                        model.set('icode_2', atom_ids[m_id][rest[1]][6])\n                        model.set('seq_2', atom_ids[m_id][rest[1]][3])\n                        model.set('said_2', atom_ids[m_id][rest[1]][1])\n                        model.set('resname_2', atom_ids[m_id][rest[1]][2])\n\n                        # model.set('seq_1', str(rest[0][0]))\n                        # model.set('chain_1', str(rest[0][1]))\n                        # model.set('res_1', str(rest[0][2]))\n                        # model.set('atom_1', str(rest[0][3]))\n                        # model.set('seq_2', str(rest[1][0]))\n                        # model.set('chain_2', str(rest[1][1]))\n                        # model.set('res_2', str(rest[1][2]))\n                        # model.set('atom_2', str(rest[1][3]))3\n                        model.set('violation', str(distance_violations[r_id][m_id][0]))\n                        model.set('rest_type', distance_violations[r_id][m_id][1])\n        rest_ids = list(angle_violations.keys())\n        ang_viol = ET.SubElement(violations, 'AngleViolations')\n        for m_id in model_ids[:50]:\n            models = ET.SubElement(ang_viol, 'Model')\n            models.set('model', str(m_id))\n            for r_id in rest_ids[:50]:\n                for rest in angle[r_id]:\n                    if angle_violations[r_id][m_id][0] > 0.0:\n                        model = ET.SubElement(models, 'Violation')\n                        model.set('rest_id', str(r_id[1]))\n                        model.set('rest_list_id', str(r_id[0]))\n                        model.set('model_1', str(m_id))\n                        model.set('chain_1', atom_ids[m_id][rest[0]][7])\n                        model.set('resnum_1', atom_ids[m_id][rest[0]][4])\n                        model.set('ent_1', atom_ids[m_id][rest[0]][0])\n                        model.set('altcode_1', atom_ids[m_id][rest[0]][5])\n                        model.set('icode_1', atom_ids[m_id][rest[0]][6])\n                        model.set('seq_1', atom_ids[m_id][rest[0]][3])\n                        model.set('said_1', atom_ids[m_id][rest[0]][1])\n                        model.set('resname_1', atom_ids[m_id][rest[0]][2])\n                        model.set('model_2', str(m_id))\n                        model.set('chain_2', atom_ids[m_id][rest[1]][7])\n                        model.set('resnum_2', atom_ids[m_id][rest[1]][4])\n                        model.set('ent_2', atom_ids[m_id][rest[1]][0])\n                        model.set('altcode_2', atom_ids[m_id][rest[1]][5])\n                        model.set('icode_2', atom_ids[m_id][rest[1]][6])\n                        model.set('seq_2', atom_ids[m_id][rest[1]][3])\n                        model.set('said_2', atom_ids[m_id][rest[1]][1])\n                        model.set('resname_2', atom_ids[m_id][rest[1]][2])\n                        model.set('model_3', str(m_id))\n                        model.set('chain_3', atom_ids[m_id][rest[2]][7])\n                        model.set('resnum_3', atom_ids[m_id][rest[2]][4])\n                        model.set('ent_3', atom_ids[m_id][rest[2]][0])\n                        model.set('altcode_3', atom_ids[m_id][rest[2]][5])\n                        model.set('icode_3', atom_ids[m_id][rest[2]][6])\n                        model.set('seq_3', atom_ids[m_id][rest[2]][3])\n                        model.set('said_3', atom_ids[m_id][rest[2]][1])\n                        model.set('resname_4', atom_ids[m_id][rest[2]][2])\n                        model.set('model_4', str(m_id))\n                        model.set('chain_4', atom_ids[m_id][rest[3]][7])\n                        model.set('resnum_4', atom_ids[m_id][rest[3]][4])\n                        model.set('ent_4', atom_ids[m_id][rest[3]][0])\n                        model.set('altcode_4', atom_ids[m_id][rest[3]][5])\n                        model.set('icode_4', atom_ids[m_id][rest[3]][6])\n                        model.set('seq_4', atom_ids[m_id][rest[3]][3])\n                        model.set('said_4', atom_ids[m_id][rest[3]][1])\n                        model.set('resname_4', atom_ids[m_id][rest[3]][2])\n\n                        # model.set('seq_1', str(rest[0][0]))\n                        # model.set('chain_1', str(rest[0][1]))\n                        # model.set('res_1', str(rest[0][2]))\n                        # model.set('atom_1', str(rest[0][3]))\n                        # model.set('seq_2', str(rest[1][0]))\n                        # model.set('chain_2', str(rest[1][1]))\n                        # model.set('res_2', str(rest[1][2]))\n                        # model.set('atom_2', str(rest[1][3]))\n                        # model.set('seq_3', str(rest[2][0]))\n                        # model.set('chain_3', str(rest[2][1]))\n                        # model.set('res_3', str(rest[2][2]))\n                        # model.set('atom_3', str(rest[2][3]))\n                        # model.set('seq_4', str(rest[3][0]))\n                        # model.set('chain_4', str(rest[3][1]))\n                        # model.set('res_4', str(rest[3][2]))\n                        # model.set('atom_4', str(rest[3][3]))\n                        model.set('violation', str(angle_violations[r_id][m_id][0]))\n                        model.set('rest_type', angle_violations[r_id][m_id][1])\n        ET.tostring(violations)\n        t = ET.ElementTree(violations)\n        t.write('full.xml')\n\n\n    @staticmethod\n    def calculate_violation_statistics(violations):\n        \"\"\"\n        Calculates average violation value for each restraint for an ensemble\n        :param violations: output from calculate_distance_violations or calculate_angle_violations\n        :return: list of average violation for each restraint, list of violations\n        example output [0.050748176870277231, 0.00147115297574274, 0.11772253375387987, 7, [2, 5, 7, 11, 14, 18, 19],\n         'medium', ('1', '1')],[0.041170250870272262, 2, 'medium', ('1', '1')]\n        \"\"\"\n        rest_list = list(violations.keys())\n        models = list(violations[rest_list[0]].keys())\n        avg_violations = {}\n        viol = []\n        for rest in rest_list:\n            v = []\n            m_id = []\n            for m in models:\n                cat = violations[rest][m][1]\n                if violations[rest][m][0] > 0.0:\n                    v.append(violations[rest][m][0])\n                    viol.append([violations[rest][m][0], m, cat, rest])\n                    m_id.append(m)\n\n            if len(v) > 0:\n                avg_violations[rest] = [numpy.mean(v), min(v), max(v), len(v), m_id, cat]\n            else:\n                avg_violations[rest] = [0.0, 0.0, 0.0, 0, m_id, cat]\n        avg_viol_list = []\n        for rest in rest_list:\n            avg_viol_list.append(avg_violations[rest])\n            avg_viol_list[-1].append(rest)\n        return avg_viol_list, viol\n\n    @staticmethod\n    def bin_distance_violations(violations):\n        \"\"\"\n        Count the number of violations in different bins (not violated)(0-0.2),(0.2-0.5),(0.5-1.0),(1.0-2.0),(2.0-5.0),(>5)\n        :param violations: output from calculate_distance_violations\n        :return: disctionary {model id : [count in each bin]} example {1: [1475, 19, 7, 12, 19, 7, 0],\n         2: [1469, 30, 7, 9, 15, 9, 0], 3: [1473, 23, 7, 7, 20, 9, 0]...}\n        \"\"\"\n        rest_list = list(violations.keys())\n        models = list(violations[rest_list[0]].keys())\n        stat = {}\n        for m in models:\n            c = [0, 0, 0, 0, 0, 0, 0]\n            for rest in rest_list:\n                if violations[rest][m][0] == 0.0:\n                    c[0] += 1\n                elif 0.0 < violations[rest][m][0] <= 0.2:\n                    c[1] += 1\n                elif 0.2 < violations[rest][m][0] <= 0.5:\n                    c[2] += 1\n                elif 0.5 < violations[rest][m][0] <= 1.0:\n                    c[3] += 1\n                elif 1.0 < violations[rest][m][0] <= 2.0:\n                    c[4] += 1\n                elif 2.0 < violations[rest][m][0] <= 5.0:\n                    c[5] += 1\n                elif 5.0 < violations[rest][m][0]:\n                    c[6] += 1\n                else:\n                    print(\"Error in violation calculation\")\n            stat[m] = c\n        return stat\n\n    @staticmethod\n    def bin_angle_violations(violations):\n        \"\"\"\n        Count the number of violations in different bins (not violated)(0-5),(5-10),(10-20),(20-40),(40-80),(>80)\n        :param violations: output from calculate_angle_violations\n        :return: dictionary {model id : [count in each bin]} example {1: [1475, 19, 7, 12, 19, 7, 0],\n         2: [1469, 30, 7, 9, 15, 9, 0], 3: [1473, 23, 7, 7, 20, 9, 0]...}\n        \"\"\"\n        rest_list = list(violations.keys())\n        models = list(violations[rest_list[0]].keys())\n        stat = {}\n        for m in models:\n            c = [0, 0, 0, 0, 0, 0, 0]\n            for rest in rest_list:\n                if violations[rest][m][0] == 0.0:\n                    c[0] += 1\n                elif 0.0 < violations[rest][m][0] <= 5.0:\n                    c[1] += 1\n                elif 5.0 < violations[rest][m][0] <= 10.0:\n                    c[2] += 1\n                elif 10.0 < violations[rest][m][0] <= 20.0:\n                    c[3] += 1\n                elif 20.0 < violations[rest][m][0] <= 40.0:\n                    c[4] += 1\n                elif 40.0 < violations[rest][m][0] <= 80.0:\n                    c[5] += 1\n                elif 80.0 < violations[rest][m][0]:\n                    c[6] += 1\n                else:\n                    print(\"Error in violation calculation\")\n            stat[m] = c\n        return stat\n\n\nif __name__ == \"__main__\":\n    #cif  = sys.argv[1]\n    #star = sys.argv[2]\n    p = Validate_NMR_Restraints('nef_examples/2lci.cif', 'nef_examples/2lci.str')\n", "meta": {"hexsha": "3df9a1d54fe67143ce8e0d08fb92ef1672d5c3cd", "size": 34733, "ext": "py", "lang": "Python", "max_stars_repo_path": "Validate_NMR_Restraints.py", "max_stars_repo_name": "kumar-physics/RestraintsValidation", "max_stars_repo_head_hexsha": "b6b6529425c3940a91ae4b3931cad3a6b9460bea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Validate_NMR_Restraints.py", "max_issues_repo_name": "kumar-physics/RestraintsValidation", "max_issues_repo_head_hexsha": "b6b6529425c3940a91ae4b3931cad3a6b9460bea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Validate_NMR_Restraints.py", "max_forks_repo_name": "kumar-physics/RestraintsValidation", "max_forks_repo_head_hexsha": "b6b6529425c3940a91ae4b3931cad3a6b9460bea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.3073713491, "max_line_length": 123, "alphanum_fraction": 0.5231624104, "include": true, "reason": "import numpy,from numpy", "num_tokens": 8625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.17108743095730972}}
{"text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport re\nimport os\nimport json\nimport numpy as np\nimport pandas as pd\n\nfrom scipy.interpolate import interp1d\n\nfrom .data import _get_connection\nfrom .plotting import _init_plot, _draw_plot\nfrom .element import ELEMENTS, Element\n\nCOMPOUND_LIST = list(map(str, pd.read_sql('SELECT compound FROM compounds', _get_connection('ziegler'))['compound']))\n\nclass Compound(object):\n\t\"\"\"Data and properties of atomic compounds\n\n\tThe compound class provides the same functionality as the\n\telement class, but for compounds of atomic elements rather\n\tthan the individual atomic elements.  The compound is described\n\tby a set of elements, a set of weights for each element, and a \n\tdensity.  \n\n\tThe weights can be either given as atom-weights, e.g.\n\tin H2O the atom weights are 0.67 for H and 0.33 for O, or as \n\tmass-weights, e.g. brass is 0.33 Zn by weight and 0.67 Cu by\n\tweight.  Some preset compounds are available; their names can be\n\tfound by printing `ci.COMPOUND_LIST`.\n\t\n\tParameters\n\t----------\n\tcompound : str\n\t\tThe name of the compound.  If the compound is in `ci.COMPOUND_LIST`,\n\t\tthe weights and density will take preset values, if not given.\n\t\tIf the name of the compound is given in chemical notation, e.g. NaCl\n\t\tor H2O2, the atom-weights can be inferred if not given explicitly.  Note\n\t\tthat full chemical notation is not supported, so Ca3(PO4)2 must be written\n\t\tas Ca3P2O8.  Decimal weights are supported, e.g. C0.5O is equivalent to CO2.\n\n\tweights : dict, str or pd.DataFrame, optional\n\t\tThe weights of each element in the compound.  Multiple formats are supported.\n\t\tIf weights is a dict, it must be formatted as {'el1':wt1, 'el2':wt2}, where\n\t\tatom-weights are positive, and mass-weights are negative. \n\n\t\tIf weights is a pandas DataFrame, it must contain an 'element' column, \n\t\tand one of 'weight', 'atom_weight', or 'mass_weight'.  If 'weight' is the column \n\t\tgiven, the convention of positive atom-weights and negative mass-weights is followed.  \n\n\t\tIf weights is a str, it can either be formatted as 'el1:wt1, el2:wt2', or it can be \n\t\ta path to a .csv, .json or .db file.  These files must contain the same information \n\t\tas the DataFrame option, and can contain weights for multiple compounds, if 'compound' \n\t\tis one of the columns/keys.\n\t\t\n\t\tIf a .json file, it must follow the 'records' formatting convention (see pandas docs).\n\n\tdensity : float, optional\n\t\tDensity of the compound in g/cm^3.  The density is required for the cm.attenuation(),\n\t\tcm.S(), cm.range() and cm.plot_range() functions, but is an optional argument in each\n\t\tof those functions if not provided at construction.  Can also be specified by using\n\t\ta 'density' column/key in the file/DataFrame for weights.\n\n\tAttributes\n\t----------\n\tname : str\n\t\tThe name of the compound.\n\n\tweights : pd.DataFrame\n\t\tThe weights for each element in the compound.  DataFrame columns are\n\t\t'element', 'Z', 'mass_weight', 'atom_weight'.\n\n\tdensity : float\n\t\tDensity of the compound in g/cm^3. The density is used in\n\t\tcalculations of charged particle dEdx and photon attenuation, so\n\t\tif the density was not explicitly given at construction,\n\t\tyou can assign a new density using `cm.density = new_density` if\n\t\tneeded, or using the `density` keyword in either of those functions.\n\n\telements : list of ci.Element\n\t\tElements in the compound.\n\n\tmass_coeff : pd.DataFrame\n\t\tTable of mass-attenuation coefficients as a function of photon\n\t\tenergy, from the NIST XCOM database.  Energies are in keV, and\n\t\tmass-attenuation coefficients, or mu/rho, are given in cm^2/g.\n\t\tDataFrame columns are 'energy', 'mu' and 'mu_en' for the \n\t\tmass-energy absorption coefficient.\n\n\tExamples\n\t--------\n\t>>> print('Silicone' in ci.COMPOUND_LIST)\n\tTrue\n\t>>> cm = ci.Compound('Silicone') # preset compound\n\t>>> print(list(map(str, cm.elements)))\n\t['H', 'C', 'O', 'Si']\n\t>>> cm = ci.Compound('H2O', density=1.0)\n\tprint(cm.weights)\n\t  element  Z  atom_weight  mass_weight\n\t0       H  1     0.666667     0.111907\n\t1       O  8     0.333333     0.888093\n\t>>> cm = ci.Compound('Brass', weights={'Zn':-33,'Cu':-66})\n\t>>> print(cm.weights)\n\t  element   Z  atom_weight  mass_weight\n\t0      Zn  30     0.327041     0.333333\n\t1      Cu  29     0.672959     0.666667\n\t>>> cm.saveas('brass.csv')\n\n\t\"\"\"\n\n\tdef __init__(self, compound, weights=None, density=None):\n\t\tself.name = compound\n\t\tself.density = None\n\n\t\tif compound in COMPOUND_LIST:\n\t\t\tdf = pd.read_sql('SELECT * FROM compounds WHERE compound=\"{}\"'.format(compound), _get_connection('ziegler'))\n\t\t\tself.density = df['density'][0]\n\n\t\t\tif weights is None:\n\t\t\t\twts = df['weights'][0].split(',')\n\t\t\t\telements = [str(i.split(':')[0]) for i in wts]\n\t\t\t\tatom_weights = np.array([float(i.split(':')[1]) for i in wts])\n\t\t\t\tself._set_weights(elements, atom_weights=atom_weights)\n\t\t\t\n\t\telif weights is None:\n\t\t\telements = []\n\t\t\tfor el_gp in [i for i in re.split('[0-9]+|\\\\.', compound) if i]:\n\t\t\t\tfor s in [i for i in re.split('([A-Z])', el_gp) if i]:\n\t\t\t\t\tif s.upper()==s:\n\t\t\t\t\t\telements.append(s)\n\t\t\t\t\telse:\n\t\t\t\t\t\telements[-1] += s\n\n\t\t\tif all([e in ELEMENTS for e in elements]):\n\t\t\t\twts = re.split('|'.join(sorted(elements, key=lambda i:-len(i))), compound)\n\t\t\t\tatom_weights = np.array([float(wts[n+1]) if wts[n+1] else 1.0 for n,e in enumerate(elements)])\n\t\t\t\tself._set_weights(elements, atom_weights=atom_weights)\n\n\t\tif weights is not None:\n\n\t\t\tif type(weights)==dict:\n\t\t\t\telements = [e for e in weights]\n\t\t\t\twts = np.array([weights[e] for e in elements], dtype=np.float64)\n\t\t\t\tweights = pd.DataFrame({'element':elements, 'weight':wts})\n\n\t\t\telif type(weights)==str:\n\t\t\t\tif weights.endswith('.json'):\n\t\t\t\t\tweights = pd.read_json(weights, orient='records').fillna(method='ffill')\n\t\t\t\t\tweights.columns = map(str.lower, map(str, weights.columns))\n\t\t\t\t\tif 'compound' in weights.columns:\n\t\t\t\t\t\tweights = weights[weights['compound']==self.name]\n\n\t\t\t\telif weights.endswith('.csv'):\n\t\t\t\t\tweights = pd.read_csv(weights, header=0).fillna(method='ffill')\n\t\t\t\t\tweights.columns = map(str.lower, map(str, weights.columns))\n\t\t\t\t\tif 'compound' in weights.columns:\n\t\t\t\t\t\tweights = weights[weights['compound']==self.name]\n\n\t\t\t\telif weights.endswith('.db'):\n\t\t\t\t\tweights = pd.read_sql('SELECT * FROM compounds WHERE compound={}'.format(self.name), _get_connection(weights))\n\t\t\t\t\tweights.columns = map(str.lower, map(str, weights.columns))\n\t\t\t\t\tif 'compound' in weights.columns:\n\t\t\t\t\t\tweights = weights[weights['compound']==self.name]\n\n\t\t\t\telse:\n\t\t\t\t\telements = [str(i.split(':')[0]).strip() for i in weights.split(',')]\n\t\t\t\t\twts = np.array([float(i.split(':')[1].strip()) for i in weights.split(',')])\n\n\t\t\t\t\tif wts[0]>0:\n\t\t\t\t\t\tself._set_weights(elements, atom_weights=wts)\n\t\t\t\t\telse:\n\t\t\t\t\t\tself._set_weights(elements, mass_weights=np.abs(wts))\n\n\t\t\tif type(weights)==pd.DataFrame:\n\t\t\t\tweights.columns = map(str.lower, map(str, weights.columns))\n\t\t\t\tif 'density' in weights.columns:\n\t\t\t\t\tself.density = weights['density'].iloc[0]\n\n\t\t\t\tcols = ['element', 'Z', 'atom_weight', 'mass_weight']\n\t\t\t\tif all([i in weights.columns for i in cols]):\n\t\t\t\t\tself.weights = weights[cols]\n\n\t\t\t\telif 'atom_weight' in weights.columns:\n\t\t\t\t\tself._set_weights(list(weights['element']), atom_weights=weights['atom_weight'].to_numpy())\n\n\t\t\t\telif 'mass_weight' in weights.columns:\n\t\t\t\t\tself._set_weights(list(weights['element']), mass_weights=weights['mass_weight'].to_numpy())\n\n\t\t\t\telse:\n\t\t\t\t\telements, wts = list(weights['element']), weights['weight'].to_numpy()\n\n\t\t\t\t\tif wts[0]>0:\n\t\t\t\t\t\tself._set_weights(elements, atom_weights=wts)\n\t\t\t\t\telse:\n\t\t\t\t\t\tself._set_weights(elements, mass_weights=np.abs(wts))\n\n\n\t\tif density is not None:\n\t\t\tself.density = density\n\n\t\tself.elements = [Element(el) for el in self.weights['element']]\n\n\t\tif self.density is None and len(self.weights)==1:\n\t\t\tself.density = self.elements[0].density\n\n\t\tE = np.unique(np.concatenate([el.mass_coeff['energy'].to_numpy() for el in self.elements]))\n\t\tmu = np.average([el.mu(E) for el in self.elements], weights=self.weights['mass_weight'], axis=0)\n\t\tmu_en = np.average([el.mu_en(E) for el in self.elements], weights=self.weights['mass_weight'], axis=0)\n\t\tself.mass_coeff = pd.DataFrame({'energy':E,'mu':mu,'mu_en':mu_en})\n\t\tself._mc_interp, self._mc_en_interp = None, None\n\n\n\tdef _set_weights(self, elements, atom_weights=None, mass_weights=None):\n\t\tamu = pd.read_sql('SELECT * FROM weights', _get_connection('ziegler'))\n\t\tZs = [ELEMENTS.index(el) for el in elements]\n\n\t\tif mass_weights is None:\n\t\t\tmass_weights = np.array([amu[amu['Z']==z]['amu'][z-1]*atom_weights[n] for n,z in enumerate(Zs)])\n\t\telif atom_weights is None:\n\t\t\tatom_weights = np.array([mass_weights[n]/amu[amu['Z']==z]['amu'][z-1] for n,z in enumerate(Zs)])\n\n\t\tatom_weights, mass_weights = atom_weights/np.sum(atom_weights), mass_weights/np.sum(mass_weights)\n\t\tself.weights = pd.DataFrame({'element':elements, 'Z':Zs, 'atom_weight':atom_weights, 'mass_weight':mass_weights}, \n\t\t\t\t\t\t\t\tcolumns=['element','Z','atom_weight','mass_weight'])\n\n\n\tdef __str__(self):\n\t\treturn self.name\n\n\tdef saveas(self, filename, replace=False):\n\t\t\"\"\"Save the compound definition to a file\n\n\t\tThe weights and density of the compound can be saved to one of\n\t\tthe following file formats: .csv, .json, .db.  If the file exists,\n\t\tthe data will be appended, unless `replace=True`, in which case\n\t\tthe file will be replaced.  If a definition for the compound exists\n\t\tin the file already, it will be replaced.\n\n\t\tParameters\n\t\t----------\n\t\tfilename : str\n\t\t\tFilename where the compound will be saved.  Available formats\n\t\t\tare .csv, .json and .db.\n\n\t\treplace : bool, optional\n\t\t\tIf `True`, replace the file if it exists.  Default `False`, which\n\t\t\tappends the data to the file.\n\n\t\tExamples\n\t\t--------\n\t\t>>> cm = ci.Compound('Brass', weights={'Zn':-33,'Cu':-66})\n\t\t>>> cm.saveas('brass.csv')\n\t\t>>> cm = ci.Compound('Water', weights={'H':2, 'O':1}, density=1.0)\n\t\t>>> cm.saveas('water.json')\n\n\t\t\"\"\"\n\t\twts = self.weights.copy()\n\t\twts['compound'] = self.name\n\t\tif self.density is not None:\n\t\t\twts['density'] = self.density\n\n\t\tif filename.endswith('.csv'):\n\t\t\tif os.path.exists(filename) and not replace:\n\t\t\t\tdf = pd.read_csv(filename, header=0)\n\t\t\t\tdf = df[df['compound']!=self.name]\n\t\t\t\tdf = pd.concat([df, wts])\n\t\t\t\tdf.to_csv(filename, index=False)\n\t\t\telse:\n\t\t\t\twts.to_csv(filename, index=False)\n\n\t\tif filename.endswith('.db'):\n\t\t\tif os.path.exists(filename) and not replace:\n\t\t\t\tcon = _get_connection(filename)\n\t\t\t\tdf = pd.read_sql('SELECT * FROM weights', con)\n\t\t\t\tdf = df[df['compound']!=self.name]\n\t\t\t\tdf = pd.concat([df, wts])\n\t\t\t\tdf.to_sql('weights', con, if_exists='replace', index=False)\n\t\t\telse:\n\t\t\t\twts.to_sql('weights', _get_connection(filename), if_exists='replace', index=False)\n\n\t\tif filename.endswith('.json'):\n\t\t\tif os.path.exists(filename) and not replace:\n\t\t\t\tdf = pd.read_json(filename, orient='records')\n\t\t\t\tdf = df[df['compound']!=self.name][wts.columns]\n\t\t\t\tdf = pd.concat([df, wts])\n\t\t\t\tjson.dump(json.loads(df.to_json(orient='records')), open(filename, 'w'), indent=4)\n\t\t\telse:\n\t\t\t\tjson.dump(json.loads(wts.to_json(orient='records')), open(filename, 'w'), indent=4)\n\n\tdef mu(self, energy):\n\t\t\"\"\"Mass-attenuation coefficient\n\n\t\tInterpolates the mass-attenuation coefficient, mu/rho,\n\t\tfor the compound along the input energy grid.\n\n\t\tParameters\n\t\t----------\n\t\tenergy : array_like\n\t\t\tThe incident photon energy, in keV.\n\n\t\tReturns\n\t\t-------\n\t\tmu : np.ndarray\n\t\t\tMass attenuation coefficient, mu/rho, in cm^2/g.\n\n\t\tExamples\n\t\t--------\n\t\t>>> cm = ci.Compound('H2O')\n\t\t>>> print(cm.mu(200))\n\t\t0.13703928393005832\n\n\t\t\"\"\"\n\n\t\tif self._mc_interp is None:\n\t\t\tself._mc_interp = interp1d(np.log(self.mass_coeff['energy']), np.log(self.mass_coeff['mu']), bounds_error=False, fill_value='extrapolate')\n\t\treturn np.exp(self._mc_interp(np.log(energy)))\n\n\tdef mu_en(self, energy):\n\t\t\"\"\"Mass energy-absorption coefficient\n\n\t\tInterpolates the mass-energy absorption coefficient, mu_en/rho,\n\t\tfor the compound along the input energy grid.\n\n\t\tParameters\n\t\t----------\n\t\tenergy : array_like\n\t\t\tThe incident photon energy, in keV.\n\n\t\tReturns\n\t\t-------\n\t\tmu_en : np.ndarray\n\t\t\tMass energy absorption coefficient, mu_en/rho, in cm^2/g.\n\n\t\tExamples\n\t\t--------\n\t\t>>> cm = ci.Compound('H2O')\n\t\t>>> print(cm.mu_en(200))\n\t\t0.029671598667776862\n\n\t\t\"\"\"\n\n\t\tif self._mc_en_interp is None:\n\t\t\tself._mc_en_interp = interp1d(np.log(self.mass_coeff['energy']), np.log(self.mass_coeff['mu_en']), bounds_error=False, fill_value='extrapolate')\n\t\treturn np.exp(self._mc_en_interp(np.log(energy)))\n\n\tdef attenuation(self, energy, x, density=None):\n\t\t\"\"\"Photon attenuation in matter\n\n\t\tCalculate the attenuation factor I(x)/I_0 = e^(-mu*x) for a given\n\t\tphoton energy (in keV) and slab thickness (in cm).\n\n\t\tParameters\n\t\t----------\n\t\tenergy : array_like\n\t\t\tIncident photon energy in keV.\n\n\t\tx : float\n\t\t\tThickness of slab of given compound, in cm. \n\n\t\tdensity : float, optional\n\t\t\tDensity of the compound in g/cm^3.  Default behavior is to\n\t\t\tuse `Compound.density`, which must be supplied at construction.\n\n\t\tReturns\n\t\t-------\n\t\tattenuation : numpy.ndarray\n\t\t\tThe slab attenuation factor as an absolute number (i.e. from 0 to 1).\n\t\t\tE.g. if the incident intensity is I_0, the transmitted intensity I(x) \n\t\t\tis I_0 times the attenuation factor.\n\n\t\tExamples\n\t\t--------\n\t\t>>> cm = ci.Compound('SS_316') # preset compound for 316 Stainless\n\t\t>>> print(cm.attenuation(511, x=0.3))\n\t\t0.8199829388434694\n\t\t>>> print(cm.attenuation(300, x=1.0, density=5.0))\n\t\t0.5752140388004373\n\n\t\t\"\"\"\n\n\t\tenergy = np.asarray(energy, dtype=np.float64)\n\t\tx = np.asarray(x, dtype=np.float64)\n\t\tif density is None:\n\t\t\tdensity = self.density\n\n\t\treturn np.exp(-self.mu(energy)*x*density)\n\t\t\n\tdef S(self, energy, particle='p', density=None):\n\t\t\"\"\"Charged particle stopping power in matter\n\n\t\tCalculate the stopping power, S=-dE/dx, for a given ion as a \n\t\tfunction of the ion energy in MeV.  Units of S are MeV/cm.  To return\n\t\tstopping power in units of MeV/(mg/cm^2), use option `density=1E-3`.\n\t\tThe stopping power is calculated using the Element.S() methods for\n\t\teach element in cm.elements, added using Bragg's rule.\n\n\t\tParameters\n\t\t----------\n\t\tenergy : array_like\n\t\t\tIncident ion energy in MeV.\n\n\t\tparticle : str, optional\n\t\t\tIncident ion.  For light ions, options are 'p' (default), 'd', 't', 'a' for proton, \n\t\t\tdeuteron, triton and alpha, respectively.  Additionally, heavy ions can be\n\t\t\tspecified either by element or isotope, e.g. 'Fe', '40CA', 'U', 'Bi-209'. For\n\t\t\tlight ions, the charge state is assumed to be fully stripped. For heavy ions\n\t\t\tthe charge state is handled by a Bohr/Northcliffe parameterization consistent\n\t\t\twith the Anderson-Ziegler formalism.\n\n\t\tdensity : float, optional\n\t\t\tDensity of the compound in g/cm^3.  Default behavior is to use\n\t\t\t`Compound.density`.  To return stopping power in units of MeV/(mg/cm^2), i.e.\n\t\t\tthe mass-stopping power, use `density=1E-3`.\n\n\t\tReturns\n\t\t-------\n\t\tstopping_power : numpy.ndarray\n\t\t\tStopping power, S=-dE/dx, for a given ion as a function of the \n\t\t\tion energy in MeV.  Units of S are MeV/cm.\n\n\t\tExamples\n\t\t--------\n\t\t>>> cm = ci.Compound('SrCO3', density=3.5)\n\t\t>>> print(cm.S(60.0))\n\t\t27.196387031247834\n\t\t>>> print(cm.S(55.0, density=1E-3)) ### S in MeV/(mg/cm^2)\n\t\t0.008307827781861116\n\n\t\t\"\"\"\n\n\t\tenergy = np.asarray(energy, dtype=np.float64)\n\t\tif density is None:\n\t\t\tdensity = self.density\n\n\t\treturn np.average([el.S(energy, particle=particle, density=1E-3) for el in self.elements], weights=self.weights['mass_weight'], axis=0)*1E3*density\n\t\t\n\tdef range(self, energy, particle='p', density=None):\n\t\t\"\"\"Charged particle range in matter\n\n\t\tCalculates the charged particle range in the compound, in cm.  Incident\n\t\tenergy should be in MeV, and the particle type definition is identical\n\t\tto `Compound.S()`.\n\n\t\tParameters\n\t\t----------\n\t\tenergy : array_like\n\t\t\tIncident ion energy in MeV.\n\n\t\tparticle : str, optional\n\t\t\tIncident ion.  For light ions, options are 'p' (default), 'd', 't', 'a' for proton, \n\t\t\tdeuteron, triton and alpha, respectively.  Additionally, heavy ions can be\n\t\t\tspecified either by element or isotope, e.g. 'Fe', '40CA', 'U', 'Bi-209'. For\n\t\t\tlight ions, the charge state is assumed to be fully stripped. For heavy ions\n\t\t\tthe charge state is handled by a Bohr/Northcliffe parameterization consistent\n\t\t\twith the Anderson-Ziegler formalism.\n\n\t\tdensity : float, optional\n\t\t\tDensity of the compound in g/cm^3.  Default behavior is to use\n\t\t\t`Compound.density`, which must be supplied at construction.\n\t\t\n\t\tReturns\n\t\t-------\n\t\trange : np.ndarray\n\t\t\tCharged particle range in the compound, in cm.\n\n\t\tExamples\n\t\t--------\n\t\t>>> cm = ci.Compound('Fe') # same behavior as element\n\t\t>>> print(cm.range(60.0))\n\t\t0.5858151125192633\n\t\t>>> cm = ci.Compound('SS_316') # preset compound\n\t\t>>> print(cm.range(60.0))\n\t\t0.5799450918147814\n\n\t\t\"\"\"\n\n\t\tenergy = np.asarray(energy, dtype=np.float64)\n\t\t\n\t\tdE = np.max(energy)/1E3\n\t\tE_min = min((np.min(energy), 1.0))\n\t\tE_grid = np.arange(E_min, np.max(energy)+dE, dE)\n\n\t\tS = self.S(E_grid, particle=particle, density=density)\n\t\tx = np.cumsum((1.0/S)*dE)\n\t\treturn interp1d(np.log(E_grid), x, bounds_error=None, fill_value='extrapolate')(np.log(energy))\n\t\t\n\tdef plot_mass_coeff(self, energy=None, **kwargs):\n\t\t\"\"\"Plot the mass-attenuation coefficient in the compound\n\n\t\tCreates a plot of the mass-attenuation coefficient (in cm^2/g)\n\t\tas a function of photon energy in keV.\n\n\t\tParameters\n\t\t----------\n\t\tenergy : array_like, optional\n\t\t\tEnergy grid on which to plot, replacing the default energy grid.\n\t\t\tUnits are in keV.\n\t\t\n\t\tOther Parameters\n\t\t----------------\n\t\t**kwargs\n\t\t\tOptional keyword arguments for plotting.  See the \n\t\t\tplotting section of the curie API for a complete\n\t\t\tlist of kwargs.\n\n\t\tExamples\n\t\t--------\n\t\t>>> cm = ci.Compound('Fe')\n\t\t>>> cm.plot_mass_coeff()\n\t\t>>> cm = ci.Compound('H2O')\n\t\t>>> cm.plot_mass_coeff(style='poster')\n\n\t\t\"\"\"\n\n\t\tif energy is None:\n\t\t\tenergy, mu = self.mass_coeff['energy'], self.mass_coeff['mu']\n\t\t\t\n\t\telse:\n\t\t\tenergy = np.asarray(energy, dtype=np.float64)\n\t\t\tmu = self.mu(energy)\n\n\t\tf,ax = _init_plot(**kwargs)\n\n\t\tax.plot(energy, mu, label=r'$\\mu/\\rho$'+' ({})'.format(self.name))\n\t\tax.set_xlabel('Photon Energy (keV)')\n\t\tax.set_ylabel(r'Attenuation Coeff. (cm$^2$/g)')\n\t\tax.set_xscale('log')\n\t\tax.set_yscale('log')\n\t\tax.legend()\n\t\t\n\t\treturn _draw_plot(f, ax, **kwargs)\n\t\t\n\tdef plot_mass_coeff_en(self, energy=None, **kwargs):\n\t\t\"\"\"Plot the mass energy-absorption coefficient in the compound\n\n\t\tCreates a plot of the mass energy-absorption coefficient (in cm^2/g)\n\t\tas a function of photon energy in keV.\n\n\t\tParameters\n\t\t----------\n\t\tenergy : array_like, optional\n\t\t\tEnergy grid on which to plot, replacing the default energy grid.\n\t\t\tUnits are in keV.\n\n\t\tOther Parameters\n\t\t----------------\n\t\t**kwargs\n\t\t\tOptional keyword arguments for plotting.  See the \n\t\t\tplotting section of the curie API for a complete\n\t\t\tlist of kwargs.\n\n\t\tExamples\n\t\t--------\n\t\t>>> cm = ci.Compound('Silicone') # preset compound\n\t\t\n\t\tExample plotting the mass-attenuation coefficient together with the mass\n\t\tenergy-absorption coefficient, on the same axes.\n\n\t\t>>> f,ax = cm.plot_mass_coeff(return_plot=True)\n\t\t>>> cm.plot_mass_coeff_en(f=f, ax=ax)\n\n\t\t\"\"\"\n\n\t\tif energy is None:\n\t\t\tenergy, mu = self.mass_coeff['energy'], self.mass_coeff['mu_en']\n\t\t\t\n\t\telse:\n\t\t\tenergy = np.asarray(energy, dtype=np.float64)\n\t\t\tmu = self.mu_en(energy)\n\n\t\tf,ax = _init_plot(**kwargs)\n\n\t\tax.plot(energy, mu, label=r'$\\mu_{en}/\\rho$'+' ({})'.format(self.name))\n\t\tax.set_xlabel('Photon Energy (keV)')\n\t\tax.set_ylabel(r'Attenuation Coeff. (cm$^2$/g)')\n\t\tax.set_xscale('log')\n\t\tax.set_yscale('log')\n\t\tax.legend()\n\n\t\treturn _draw_plot(f, ax, **kwargs)\n\t\t\n\t\t\n\tdef plot_S(self, particle='p', energy=None, **kwargs):\n\t\t\"\"\"Plot the stopping power in the compound\n\n\t\tCreates a plot of the charged particle stopping power (in MeV/(mg/cm^2))\n\t\tin the compound as a function of the incident ion energy (in MeV).\n\n\t\tParameters\n\t\t----------\n\t\tparticle : str\n\t\t\tIncident ion.  For light ions, options are 'p' (default), 'd', 't', 'a' for proton, \n\t\t\tdeuteron, triton and alpha, respectively.  Additionally, heavy ions can be\n\t\t\tspecified either by element or isotope, e.g. 'Fe', '40CA', 'U', 'Bi-209'.\n\n\t\tenergy : array_like, optional\n\t\t\tEnergy grid on which to plot, replacing the default energy grid.\n\t\t\tUnits are in MeV.\n\n\t\tOther Parameters\n\t\t----------------\n\t\t**kwargs\n\t\t\tOptional keyword arguments for plotting.  See the \n\t\t\tplotting section of the curie API for a complete\n\t\t\tlist of kwargs.\n\n\t\tExamples\n\t\t--------\n\t\t>>> cm = ci.Compound('He') # same as element\n\t\t>>> cm.plot_S(particle='a')\n\t\t>>> cm = ci.Compound('Kapton')\n\t\t>>> cm.plot_S(particle='d')\n\n\t\t\"\"\"\n\n\t\tif energy is None:\n\t\t\tenergy = 10.0**np.arange(-1.5, 2.8, 0.05)\n\n\t\tf,ax = _init_plot(**kwargs)\n\t\tax.plot(energy, self.S(energy, particle=particle, density=1E-3), label=r'$-\\frac{dE}{dx}$ ('+self.name+')')\n\n\t\tax.set_xlabel('Incident Energy (MeV)')\n\t\tax.set_ylabel(r'Stopping Power (MeV/(mg/cm$^2$))')\n\t\tax.set_xscale('log')\n\t\tax.legend()\n\n\t\treturn _draw_plot(f, ax, **kwargs)\n\t\t\n\tdef plot_range(self, particle='p', energy=None, density=None, **kwargs):\n\t\t\"\"\"Plot the charged particle range in the compound\n\n\t\tCreates a plot of the charged particle range (in cm)\n\t\tin the compound as a function of the incident ion energy (in MeV).\n\n\t\tParameters\n\t\t----------\n\t\tparticle : str\n\t\t\tIncident ion.  For light ions, options are 'p' (default), 'd', 't', 'a' for proton, \n\t\t\tdeuteron, triton and alpha, respectively.  Additionally, heavy ions can be\n\t\t\tspecified either by element or isotope, e.g. 'Fe', '40CA', 'U', 'Bi-209'.\n\n\t\tenergy : array_like, optional\n\t\t\tEnergy grid on which to plot, replacing the default energy grid.\n\t\t\tUnits are in MeV.\n\n\t\tdensity : float, optional\n\t\t\tDensity of the compound in g/cm^3.  Default behavior is to use\n\t\t\t`Compound.density`.\n\n\t\tOther Parameters\n\t\t----------------\n\t\t**kwargs\n\t\t\tOptional keyword arguments for plotting.  See the \n\t\t\tplotting section of the curie API for a complete\n\t\t\tlist of kwargs.\n\n\t\tExamples\n\t\t--------\n\t\t>>> cm = ci.Compound('Bronze', weights={'Cu':-80, 'Sn':-20}, density=8.9)\n\t\t>>> f,ax = cm.plot_range(return_plot=True)\n\t\t>>> cm.plot_range(particle='d', f=f, ax=ax)\n\n\t\t\"\"\"\n\n\t\tif energy is None:\n\t\t\tenergy = 10.0**np.arange(-1.5, 2.8, 0.05)\n\n\t\tf,ax = _init_plot(**kwargs)\n\t\tax.plot(energy, self.range(energy, particle=particle, density=density), label='Range ({})'.format(self.name))\n\n\t\tax.set_xlabel('Incident Energy (MeV)')\n\t\tax.set_ylabel('Range (cm)')\n\t\tax.set_xscale('log')\n\t\tax.set_yscale('log')\n\t\tax.legend()\n\n\t\treturn _draw_plot(f, ax, **kwargs)", "meta": {"hexsha": "c8295f280e4468f374832fcf3977f0ddbfea165e", "size": 22597, "ext": "py", "lang": "Python", "max_stars_repo_path": "curie/compound.py", "max_stars_repo_name": "jtmorrell/curie", "max_stars_repo_head_hexsha": "cf63d7771432a58ab79ee6dfb83b9c211ee33a1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-15T15:33:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:33:24.000Z", "max_issues_repo_path": "curie/compound.py", "max_issues_repo_name": "jtmorrell/curie", "max_issues_repo_head_hexsha": "cf63d7771432a58ab79ee6dfb83b9c211ee33a1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-07T23:25:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-07T23:25:09.000Z", "max_forks_repo_path": "curie/compound.py", "max_forks_repo_name": "jtmorrell/curie", "max_forks_repo_head_hexsha": "cf63d7771432a58ab79ee6dfb83b9c211ee33a1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2798232695, "max_line_length": 149, "alphanum_fraction": 0.678054609, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.17108742747700087}}
{"text": "# Implementation of the CS-BuFLO defense (Cai et al., 14).\n# Author: Giovanni Cherubin (@gchers)\n\nimport os\nimport sys\nimport math\nimport random\nfrom collections import deque\nfrom shutil import copyfile\n\nimport click\nimport numpy as np\n\nfrom tqdm import tqdm\nfrom numpy import median\n\n# Direction\nIN = -1\nOUT = 1\nMTU = 1\nINF = float(\"inf\")\n\n# Upstream: from the current endpoint to the defence\n# Downstream: from the other endpoint to the defence\n# Define MODES of packets\nUPSTREAM_APPLICATION_DATA = \"upstream_application_data\"\nDOWNSTREAM_APPLICATION_DATA = \"downstream_application_data\"\nON_LOAD = \"onLoad\"\nTIMEOUT = \"timeout\"\n\n# Time is specified in ms\n# NOTE: a QUIET_TIME too small causes the defence to fail,\n# raising a TimeTravel exception: one endpoint was silent\n# for too long, and then wants to catch up with the padding\n# (junk) messages it didn't send.\n# NOTE: The above problem was solved by using endpoint's\n# \"more_data\" attribute, which is set to False only when\n# the endpoint has no more data to transmit\nQUIET_TIME = 2000\nINIT_RHO = 200\nMIN_RHO = 2 ** (-4) * 1000\nMAX_RHO = 2 ** 3 * 1000\n\n\nclass TimeTravel(Exception):\n    \"\"\"This exception is raised when there are time inconsistencies.\n    \"\"\"\n\n    pass\n\n\nclass Queue(deque, object):\n    \"\"\"A deque that allows seeing the element at the\n    left of the queue without popping it.\n    \"\"\"\n\n    def seeleft(self):\n        \"\"\"Returns the next element at the left of the\n        queue, without removing it from the queue.\n\n        Returns None if the queue is empty.\n        \"\"\"\n        if self:\n            return self[0]\n        else:\n            return None\n\n\nclass CSBuFLOEndpoint:\n    \"\"\"Implements one endpoint (client, server) of the CS-BuFLO defence as\n    described in:\n        http://pub.cs.sunysb.edu/~rob/papers/csbuflo.pdf\n    \"\"\"\n\n    def __init__(self, output_trace, direction, initial_rho=0.2, quiet_time=QUIET_TIME):\n        # Direction is OUT for client, IN for server\n        self.direction = direction\n        # Defended packets\n        self.defended_trace = output_trace\n        # Internal buffer for packets to send\n        self.output_buff = Queue()  # Packets to send\n        # Packets that have been sent\n        # NOTE: don't rely on this to see which packets were sent,\n        # because the function defend() pops from this queue.\n        self.sent = Queue()\n        # Bytes of real and padding (junk) traffic sent\n        self.real_bytes = 0\n        self.junk_bytes = 0\n        self.last_site_response_time = None\n        # onLoad and padding_done events\n        self.on_load = False\n        self.padding_done = False\n        # The timeout it sampled uniformly in [0, 2*self.rho]\n        # rho_stats are used to adjust rho\n        self.initial_rho = initial_rho\n        self.rho = initial_rho\n        self.rho_stats = []\n        self.timeout = initial_rho\n        # \"As a backup mechanism, the CS-BuFLO server considers\n        # the website idle if quiet-time seconds pass without receiving\n        # new data from the website. We used a quiet-time of 2\n        # seconds in our prototype implementation.\"\n        # (Section 4.5)\n        self.quiet_time = quiet_time\n        # Triggered to True when self.done_xmitting() == True\n        self.done = False\n        # This was not present in the original paper. Is is\n        # set to False when no more data needs to be transmitted\n        # from this endpoint\n        self.more_data = True\n\n    def next_timeout(self):\n        ## No timeout if it finished transmitting\n        # if self.done_xmitting():\n        if self.padding_done:\n            return INF\n        # NOTE: need to check last sent packet time on defended_trace\n        # rather than self.sent, as self.sent may be changed externally\n        last_time = 0.0\n        if self.defended_trace:\n            for i in range(len(self.defended_trace) - 1, -1, -1):\n                if self.defended_trace[i][1] == MTU * self.direction:\n                    # last_time, _ = self.defended_trace[i]\n                    last_time, _ = self.defended_trace[i]\n                    break\n\n        return last_time + self.timeout\n\n    def process(self, packet, mode):\n        # print('process {} {}'.format(packet, mode))\n        # print('rho {}'.format(self.rho))\n        # print('timeout {}'.format(self.timeout))\n        time, size = packet\n\n        if mode == UPSTREAM_APPLICATION_DATA:\n            # this endpoint is trying to send data\n            self.output_buff.append((time, size))\n            self.real_bytes += abs(size)\n            self.last_site_response_time = time\n            # self.padding_done = False\n        elif mode == DOWNSTREAM_APPLICATION_DATA:\n            # would pass data back to this endpoint\n            self.rho_stats.append(None)\n            self.on_load = False\n            # NOTE: This is only done for the server\n            # endpoint (i.e., direction == IN)\n            # This was not specified by the original paper\n            # but without this we would encounter instable\n            # situations\n            if self.direction == IN:\n                self.padding_done = False\n        elif mode == ON_LOAD:\n            self.on_load = True\n        elif mode == TIMEOUT:\n            if self.output_buff:\n                self.rho_stats.append(time)\n            padding = self.cs_send(time)\n            self.junk_bytes += padding\n\n        if self.done_xmitting(time):\n            self.padding_done = True\n        else:\n            # Set rho to the average time between sends to client\n            if self.rho == INF:\n                self.rho = self.initial_rho\n            elif self.crossed_threshold():\n                self.rho = self.rho_estimator()\n                self.rho_stats = []\n\n            if mode == TIMEOUT:\n                # Random in [0, 2*rho]\n                self.timeout = random.random() * 2 * self.rho\n\n    def cs_send(self, time):\n        padding = 0\n\n        if self.output_buff:\n            _, size = self.output_buff.popleft()\n            # We use the timeout time\n            packet = (time, size)\n        else:\n            # Padding packet\n            packet = (time, self.direction * MTU)\n            padding = 1\n\n        self.sent.append(packet)\n        self.defended_trace.append(packet)\n\n        return padding\n\n    def padding_finished(self):\n        \"\"\"Using \"payload padding\", which pads until the bytes\n        sent are a multiple of the real bytes.\n\n        Implements \"Payload padding\" as in paper.\n        \"\"\"\n        if self.real_bytes == 0:\n            return False\n\n        total_bytes = self.real_bytes + self.junk_bytes\n        next_multiple = 2 ** math.ceil(math.log(self.real_bytes, 2))\n\n        return total_bytes % next_multiple == 0\n\n    def done_xmitting(self, cur_time):\n        condition1 = self.padding_finished() or self.crossed_threshold()\n        # NOTE: The paper writes \"length(output_buff) <- 0\" as first\n        # condition. Since the expression makes no sense, I assume\n        # the authors meant \"length(output_buff) == 0\".\n        condition2 = not self.output_buff\n        condition3 = self.channel_idle(cur_time)\n        # NOTE: I add the following condition, because if one\n        # endpoint gets silent for too long and then wants to transmit\n        # again the defence would fail\n        condition4 = not self.more_data\n\n        # print(self.direction, condition1, condition2, condition3, condition4)\n\n        return condition1 and condition2 and condition3 and condition4\n\n    def channel_idle(self, cur_time):\n        if self.last_site_response_time is not None:\n            is_quiet = self.last_site_response_time + self.quiet_time < cur_time\n        else:\n            is_quiet = False\n\n        return self.on_load or is_quiet\n\n    def rho_estimator(self):\n        it = []\n        for i in range(len(self.rho_stats) - 1):\n            if self.rho_stats[i] is not None and self.rho_stats[i + 1] is not None:\n                it.append(self.rho_stats[i + 1] - self.rho_stats[i])\n\n        if not it:\n            return self.rho\n\n        med = median(it)\n        if not med:\n            rho = self.rho\n\n        rho = 2 ** math.floor(math.log(med, 2))\n\n        # NOTE: to my understanding, the original CS-BuFLO\n        # implemented in SSH has a minimum and maximum RHO\n        # values. By doing some experiments I observed the\n        # following values allow containing overheads\n        if rho < MIN_RHO:\n            rho = MIN_RHO\n        elif rho > MAX_RHO:\n            rho = MAX_RHO\n\n        return rho\n\n    def crossed_threshold(self):\n        # From Algorithm 1 in the paper, this function seems to be\n        # called on two arguments: (real_bytes, junk_bytes).\n        # However, the function only accepts one argument (Algorithm 4).\n        # Thankfully, DONE_XMITTING() in Algorithm 4 calls the function\n        # on real_bytes + junk_bytes, so I assume this is what was\n        # intended in Algorithm 1.\n        x = self.real_bytes + self.junk_bytes\n\n        # NOTE: I'm adding this, because otherwise (_by design_)\n        # when x == MTU (which does happen) the log is indefinite\n        if x == MTU or x == 0:\n            return False\n\n        # The following comment does not apply anymore, and I'll\n        # only keep it for record.\n        ## NOTE: This is an edit from the original function.\n        ## As in Figure 1, it returns True only if the number\n        ## of bytes sent so far is a multiple of 2^k, for\n        ## some integer k\n        ##log = math.log(x, 2)\n        ##return log == math.floor(log)\n\n        return math.floor(math.log(x - MTU, 2)) < math.floor(math.log(x, 2))\n\n\nclass CSBuFLO:\n    def __init__(self, initial_rho=INIT_RHO):\n        self.initial_rho = initial_rho\n\n    def reset(self):\n        self.defended_trace = Queue()\n        self.client = CSBuFLOEndpoint(self.defended_trace, OUT, self.initial_rho)\n        self.server = CSBuFLOEndpoint(self.defended_trace, IN, self.initial_rho)\n        # For each endpoint (client, server), there are two\n        # queues of packets: those read from the trace and those\n        # that were actually sent by the defence (output).\n        # The output ones can be found as client.sent, server.sent,\n        # the others we define as follows\n        self.client_packets = Queue()\n        self.server_packets = Queue()\n\n    def defend(self, packets):\n        self.reset()\n\n        # Add packets to the respective pipelines\n        for t, s in packets:\n            if s > 0:\n                self.client_packets.append((t, s))\n            else:\n                self.server_packets.append((t, s))\n\n        # Record what events happen for debugging purposes\n        nevents = {}\n\n        # Keep time, to check for errors\n        self.cur_time = 0.0\n\n        running = True\n        while running:\n            # Detect onLoad\n            cond1 = not self.client_packets and not self.client.output_buff\n            cond2 = not self.server_packets and not self.server.output_buff\n            if cond1 and cond2:\n                # print('onLoad')\n                self.server.process((self.cur_time, None), ON_LOAD)\n                self.client.process((self.cur_time, None), ON_LOAD)\n\n            # Notify endpoint if no more data to transmit\n            if not self.client_packets:\n                self.client.more_data = False\n            if not self.server_packets:\n                self.server.more_data = False\n\n            # We break if either there's no more data to transmit\n            # or self.process_next() returns None; the latter happens\n            # when there are no more packets to transmit and\n            # padding is done.\n            if self.client.done_xmitting(self.cur_time) and self.server.done_xmitting(\n                self.cur_time\n            ):\n                break\n\n            # Keep log of events\n            next_event = self.process_next()\n            if next_event not in nevents:\n                nevents[next_event] = 1\n            else:\n                nevents[next_event] += 1\n\n            # print('client out: {}'.format(self.client.output_buff))\n            # print('server out: {}'.format(self.server.output_buff))\n            ##print('defended: {}'.format(defended_trace))\n            # print('client rho: {}'.format(self.client.timeout))\n            # print('server rho: {}'.format(self.server.timeout))\n\n        return list(self.defended_trace)\n\n    def process_next(self):\n        \"\"\"Process next event.\n\n        Get the time of each event, and process the one\n        that comes first.\n        \"\"\"\n        # Find what is the next event\n        time_c_read_packet = self.client_packets.seeleft()\n        time_s_read_packet = self.server_packets.seeleft()\n        # Little hack to use the \"min\" expression later on both\n        # packets and timeouts\n        c_timeout = (self.client.next_timeout(),)\n        s_timeout = (self.server.next_timeout(),)\n\n        t_events = [time_c_read_packet, time_s_read_packet, c_timeout, s_timeout]\n\n        next_packet = min([x for x in t_events if x is not None], key=lambda x: x[0])\n        next_event = t_events.index(next_packet)\n\n        # DEBUG\n        # print('t-events {}'.format(t_events))\n        # print('next {}'.format(next_event))\n        # print(self.client.timeout)\n        # print(len(self.client_packets))\n\n        # Check the time is consistent\n        next_time = next_packet[0]\n        # NOTE: if next_time is INF, it means both endpoints\n        # have been silent for a while. Try increasing QUIET_TIME.\n        if next_time < self.cur_time:\n            print(\"I travelled back in time:\")\n            print(\"{} => {}\".format(self.cur_time, next_time))\n            print(t_events)\n            raise TimeTravel\n        self.cur_time = next_time\n\n        # Process the event\n        process_event = {\n            0: self.client_read,\n            1: self.server_read,\n            2: self.client_timeout,\n            3: self.server_timeout,\n        }\n\n        process_event[next_event]()\n        # After event, send packet (if any) to the other\n        # endpoint\n        if self.client.sent.seeleft() is not None:\n            self.client_sent()\n        if self.server.sent.seeleft() is not None:\n            self.server_sent()\n\n        return next_event\n\n    def client_read(self):\n        packet = self.client_packets.popleft()\n        self.client.process(packet, UPSTREAM_APPLICATION_DATA)\n\n    def server_read(self):\n        packet = self.server_packets.popleft()\n        self.server.process(packet, UPSTREAM_APPLICATION_DATA)\n\n    def client_sent(self):\n        packet = self.client.sent.popleft()\n        self.server.process(packet, DOWNSTREAM_APPLICATION_DATA)\n\n    def server_sent(self):\n        packet = self.server.sent.popleft()\n        self.client.process(packet, DOWNSTREAM_APPLICATION_DATA)\n\n    def client_timeout(self):\n        packet = (self.client.next_timeout(), None)\n        self.client.process(packet, TIMEOUT)\n\n    def server_timeout(self):\n        packet = (self.server.next_timeout(), None)\n        self.server.process(packet, TIMEOUT)\n\n\ndef normalise_timings(packets):\n    \"\"\"Returns a packet sequence with sorted packets, and\n    timing starting at 0.\n    \"\"\"\n    if not packets:\n        return []\n    res = sorted(packets, key=lambda x: x[0])\n    min_time = res[0][0]\n\n    for i in range(len(res)):\n        t, s = res[i]\n        res[i] = (t - min_time, s)\n        if t == INF:\n            print(\"Try increasing QUIET_TIME\")\n            raise TimeTravel\n\n    return res\n\n\n@click.command()\n@click.option(\"--data_path\")\n@click.option(\"--out_path\")\ndef main(data_path, out_path):\n    DEFENDED = out_path\n    dataset = data_path\n    outdirectory = DEFENDED\n\n    if not os.path.exists(outdirectory):\n        os.makedirs(outdirectory)\n\n    unmod = []\n    mod = []\n    added = []\n    count = 0\n\n    # Defend\n    for fname in tqdm(os.listdir(dataset)):\n        infname = os.path.join(dataset, fname)\n        outfname = os.path.join(outdirectory, fname)\n        # Skip open world traces\n        if \"-\" not in fname:\n            # copyfile(infname, outfname)\n            continue\n\n        packets = []\n        with open(infname, \"r\") as f:\n            for x in f.readlines():\n                t, s = x.split(\"\\t\")\n                t = float(t) * 1000.0  # To milliseconds\n                s = int(s)\n                packets.append((t, s))\n        success = False\n        while not success:\n            try:\n                defended = CSBuFLO().defend(packets)\n                success = True\n            except TimeTravel:\n                pass\n\n        defended = normalise_timings(defended)\n\n        # Store defended trace\n        with open(outfname, \"w\") as f:\n            for t, s in defended:\n                t /= 1000.0  # To seconds\n                s = 1 if s > 0 else -1\n                f.write(repr(t) + \"\\t\" + repr(s) + \"\\n\")\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "2c5d1bc9b54b5fafbae3d4d90ada183740b0716c", "size": 16858, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/wfp_defenses/cs_buflo.py", "max_stars_repo_name": "spring-epfl/trickster", "max_stars_repo_head_hexsha": "070a8ea8894d8bf3e97d0774b12c64458aa2c219", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2018-12-07T18:45:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T12:55:52.000Z", "max_issues_repo_path": "scripts/wfp_defenses/cs_buflo.py", "max_issues_repo_name": "spring-epfl/trickster", "max_issues_repo_head_hexsha": "070a8ea8894d8bf3e97d0774b12c64458aa2c219", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-03-24T16:30:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-01T23:08:51.000Z", "max_forks_repo_path": "scripts/wfp_defenses/cs_buflo.py", "max_forks_repo_name": "spring-epfl/trickster", "max_forks_repo_head_hexsha": "070a8ea8894d8bf3e97d0774b12c64458aa2c219", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-08-23T10:35:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-30T23:31:48.000Z", "avg_line_length": 33.5149105368, "max_line_length": 88, "alphanum_fraction": 0.5982322933, "include": true, "reason": "import numpy,from numpy", "num_tokens": 3835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.17108742625604245}}
{"text": "'''\nEssential functions and classes for calibration. See, in particular:\n\n- `OPT_BOUNDS`, which has lower and upper bounds on calibration parameters\n\n**You must create a configuration JSON file before calibrating L4C.** There\nis a template available in the directory:\n\n    pyl4c/data/fixtures/files\n\nThe optimization routines here are best used with multiple `--trials`, i.e.,\nmultiple, random initial parameter values. This can help avoiding falling into\na local optimum when a better solution set is available. However, if you are\nrepeatedly seeing the message:\n\n    Error in objective function; restarting...\n\nMost likely, the bounds on your parameters are producing initial parameter\nvalues that are totally unreasonable.\n\nNote that calibration of L4C (i.e., updating the BPLUT) can be performed using\nthe command-line interface in `pyl4c.apps.calibration.main`, for example:\n\n    # Build the scratch dataset needed for calibration\n    python main.py setup\n\n    # You can get a preview of what filtering the data would look like...\n    python main.py pft <pft_number> filter-preview gpp <window_size>\n    python main.py pft <pft_number> filter-preview reco <window_size>\n\n    # Optionally, filter the tower datasets to remove spurious spikes\n    python main.py filter-all gpp <window_size>\n    python main.py filter-all reco <window_size>\n\n    # Run the GPP calibration for a given Plant Functional Type (PFT)\n    python main.py pft <pft_number> tune-gpp\n\n    # Run the RECO calibration for a given Plant Functional Type (PFT)\n    python main.py pft <pft_number> tune-reco\n\n    # Finally, to dump the updated BPLUT into a CSV or Python pickle file...\n    python main.py bplut pickle <output_path> --version-id=<version_id>\n\n    # Get help on any command with --help, for example:\n    python main.py plot-gpp --help\n'''\n\nimport os\nimport pickle\nimport nlopt\nimport netCDF4 # Necessary to import this before HDF5 due to a bug\nimport h5py\nimport numpy as np\nfrom collections import OrderedDict\nfrom scipy import optimize\nfrom pyl4c import suppress_warnings\nfrom pyl4c.stats import detrend, rmsd, sum_of_squares\nfrom pyl4c.science import k_mult\n\n# Constrained optimization bounds\nOPT_BOUNDS = {\n    'gpp': ( # lue, tmin0, tmin1, vpd0, vpd1, smrz0, smrz1, ft0\n        np.array((0.5, 230, 276,    0,  1501,  0,  30.1, 0.)), # Lower bound\n        np.array((4.0, 275, 320, 1500, 10000, 30, 100,   1.))), # Upper bound\n    'reco': ( # CUE, beta_tsoil, smsf0, smsf1\n        np.array((0.0,   1,    0,  25)),\n        np.array((0.7, 800, 24.9, 100)))\n}\n\n\nclass BPLUT(object):\n    '''\n    Represents a Biome Properties Look-Up Table (BPLUT) with PFT classes along\n    the rows and parameters along the columns.\n\n    If initialized with a `params_dict`, these are the values of the BPLUT.\n    If initialized with an `hdf5_path` but without a `params_dict`, the\n    parameters are read-in from the HDF5 file.\n    '''\n    _labels = [\n        'LUE', 'CUE', 'tmin0', 'tmin1', 'vpd0', 'vpd1', 'smrz0', 'smrz1',\n        'smsf0', 'smsf1', 'ft0', 'ft1', 'tsoil', 'decay_rates0',\n        'decay_rates1', 'decay_rates2', 'f_metabolic', 'f_structural'\n    ]\n    _npft = 10 # Number of (possible) PFT classes\n    _valid_pft = range(1, 9) # Canonical range of valid PFTs\n\n    def __init__(\n            self, params_dict = None, labels = None, hdf5_path = None,\n            hdf5_group = 'BPLUT'):\n        '''\n        Parameters\n        ----------\n        params_dict : dict\n            A BPLUT to initialize the new BPLUT\n        labels : tuple or list\n            Names of the parameters\n        hdf5_path : str\n            Path to an HDF5 file to use as a temporary store\n        hdf5_group : str\n            Field name with which to store data in HDF5 file\n            (Default: \"BPLUT\")\n        '''\n        self.hdf5_group = hdf5_group\n        self.hdf5_path = hdf5_path\n        if labels is not None:\n            print('WARNING: Parameter names ending with a number are assumed to be bounds on ramp functions!')\n            self._labels = labels\n        # Create an in-memory parameter dictionary\n        empty = self._empty_dict(self.labels)\n        if params_dict is None:\n            init_data = empty # No prior BPLUT, use empty table\n        else:\n            init_data = params_dict.copy()\n            # IMPORTANT: Make sure prior BPLUT has all the necessary params\n            for key in empty.keys():\n                init_data.setdefault(key, empty[key])\n        # Optionally, maintain a file BPLUT\n        if hdf5_path is not None:\n            # Restore from the file data, filling in NaNs with initial\n            if os.path.exists(hdf5_path):\n                with h5py.File(hdf5_path, 'r') as hdf:\n                    if hdf5_group in hdf.keys():\n                        init_data = self.hdf5_restore(hdf, init_data = init_data)\n            # Then, if file dataset doesn't exist, create a new one and store\n            #   the initial data\n            with h5py.File(hdf5_path, 'a') as hdf:\n                self.hdf5_flush(hdf, data = init_data)\n        self.data = init_data\n\n    @property\n    def data(self):\n        'The parameters dictionary or `dict` instance'\n        return self._data\n\n    @data.setter\n    def data(self, data):\n        self._data = data\n\n    @property\n    def labels(self):\n        'Names of the free parameters'\n        return self._labels\n\n    def __getitem__(self, key):\n        return self.data[key]\n\n    def __setitem__(self, key, value):\n        self.data[key] = value\n\n    def _empty_dict(self, labels = None, dtype = np.float32):\n        '''\n        Given sequence of labels, convert to legacy, human-readable dict,\n        e.g.:\n\n            { 'LUE': array([[ nan, 1.17, ..., nan ]]), ... }\n        '''\n        labels_dedupe = self._canonical(labels)\n        result = dict()\n        for name in labels_dedupe:\n            size = len(list(filter(lambda x: x.startswith(name), labels)))\n            result[name] = np.ones((size, self._npft), dtype = dtype) * np.nan\n        return result\n\n    def _canonical(self, labels = None):\n        '''\n        Returns a short list of labels, without duplicates. Specifically,\n        a list of labels like, e.g., (\"tmin0\", \"tmin1\", \"decay_rates1\")\n        becomes (\"tmin\", \"decay_rates\").\n\n        Parameters\n        ----------\n        labels : tuple or list or None\n\n        Returns\n        -------\n        list\n        '''\n        labels = self.labels if labels is None else labels\n        # Remove numeric suffixes and de-duplicate the list\n        return list(OrderedDict([\n            (p.strip('0123456789'), 0) for p in labels\n        ]).keys())\n\n    def flat(self, pft, labels = None):\n        '''\n        Retrieves a flat list of parameters for a specific PFT.\n\n        Parameters\n        ----------\n        pft : int\n            Numeric code of the PFT for which to return parameter values\n        labels : tuple or list\n            (Optional) A sequence of parameter names desired, if not all;\n            defaults to returning all parameters\n\n        Returns\n        -------\n        numpy.ndarray\n        '''\n        labels_dedupe = self._canonical(labels)\n        return np.hstack([\n            self.data[p][:,pft].ravel() if p in self.data.keys() else np.nan\n            for p in labels_dedupe\n        ])\n\n    def hdf5_flush(self, hdf, data = None):\n        '''\n        Writes the current BPLUT to an HDF5 file.\n\n        Parameters\n        ----------\n        hdf : h5py.File\n            HDF5 file open for writing\n        data : dict\n        '''\n        assert hdf.mode != 'r', 'File not open for writing!'\n        data = self.data if data is None else data\n        if self.hdf5_group not in hdf.keys():\n            hdf.create_group(self.hdf5_group)\n        for key, value in data.items():\n            if key.startswith('_'):\n                continue # Skip keys that are not parameter names\n            field = '%s/%s' % (self.hdf5_group, key)\n            if key not in hdf[self.hdf5_group].keys():\n                hdf.create_dataset(field, value.shape, np.float32, value)\n            else:\n                # Overwrite NaNs in the file data\n                _value = hdf[field][:]\n                hdf[field][:] = np.where(np.isnan(_value), value, _value)\n        hdf.flush()\n\n    def hdf5_restore(self, hdf, init_data = None, dtype = np.float32):\n        '''\n        Reads in the BPLUT table stored in the HDF5 file.\n\n        Parameters\n        ----------\n        hdf : h5py.File\n        init_data : dict\n            Initital data; will be over-written by HDF5 file contents\n\n        Returns\n        -------\n        dict\n        '''\n        data = dict() if init_data is None else init_data\n        for key in hdf[self.hdf5_group].keys():\n            # Update the in-memory BPLUT\n            from_hdf5 = hdf[self.hdf5_group][key][:]\n            data[key] = np.where(\n                ~np.isnan(from_hdf5), from_hdf5, init_data.get(key)\n            ).astype(dtype)\n        return data\n\n    def pickle(self, output_path, version_id = None):\n        '''\n        Writes the current BPLUT parameters, as a dictionary, to a pickle\n        file.\n\n        Parameters\n        ----------\n        output_path : str\n            The output path for the pickle file (*.pickle)\n        version_id : str\n            (Optional) The version identifier for this BPLUT\n        '''\n        with open(output_path, 'wb') as file:\n            output = self.data.copy()\n            if version_id is not None:\n                output['_version'] = version_id\n            pickle.dump(output, file)\n\n    def show(self, pft, param, precision = 2):\n        '''\n        Prints the current BPLUT parameters for a given PFT, the values of a\n        given parameter for all PFTs, or the value of a specific PFT-parameter\n        combination.\n\n        Parameters\n        ----------\n        pft : int or None\n            The PFT class\n        param : str or None\n            The name of the parameter\n        precision : int\n            Decimal precision to use for printing numbers\n        '''\n        assert not (pft is None and param is None),\\\n            'Either one or both must be specified: --pft or --param'\n        set_of_labels = self._canonical() if param is None else [param]\n        set_of_pfts = self._valid_pft if pft is None else [pft]\n        for each in set_of_labels:\n            assert each in self._canonical(), 'Unrecognized parameter: %s' % each\n        for each in set_of_pfts:\n            assert each in range(0, self._npft), 'PFT code out of range'\n        pad = max(len(l) for l in set_of_labels) + 2\n        fmt_string = '{:>%d} {:>%d}' % (pad, 5 + precision)\n        for pft in set_of_pfts:\n            print('BPLUT parameters for PFT %d:' % pft)\n            for label in set_of_labels:\n                param_values = self.data[label][:,pft]\n                for i, value in enumerate(param_values):\n                    # If there are multiple values for a parameter (group),\n                    #   append a number to the end of the label\n                    if len(param_values) > 1:\n                        prefix = '%s%d:' % (label, i)\n                    else:\n                        prefix = '%s:' % label\n                    print(\n                        fmt_string.format(prefix, ('%%.%df' % precision) % value))\n\n    def update(self, pft, values, labels, flush = True):\n        '''\n        Updates the BPLUT with the specified parameters for a single PFT.\n\n        Parameters\n        ----------\n        pft : int\n            The PFT class\n        values : tuple or list\n            Sequence of parameter values, one for each parameter named in\n            `labels`\n        labels : tuple or list\n            Sequence of parameter names, one for each value in `values`\n        flush : bool\n            True to write the result to disk (attached HDF5 file storage)\n            (Default: True)\n        '''\n        assert len(values) == len(labels),\\\n            'Vectors of values and parameter labels must have the same length'\n        if flush:\n            assert self.hdf5_path is not None,\\\n                'No HDF5 file storage is attached'\n            hdf = h5py.File(self.hdf5_path, 'a')\n        for i, name in enumerate(labels):\n            abbrv = name.strip('0123456789')\n            # In case parameter has multiple levels, like a ramp function\n            #   (e.g., \"smsf0\" and \"smsf1\" are two rows)\n            dupes = list(filter(lambda x: x.startswith(abbrv), self.labels))\n            j = dupes.index(name) # If it has one level (e.g., \"LUE\"), j = 0\n            self.data[abbrv][j,pft] = values[i]\n            if flush:\n                path = '%s/%s' % (self.hdf5_group, abbrv)\n                hdf[path][:,pft] = self.data[abbrv][:,pft]\n        if flush:\n            hdf.flush()\n            hdf.close()\n\n\nclass ModelParameters(OrderedDict):\n    '''\n    Convenience wrapper for an OrderedDict, allowing both vectorized and\n    keyword access to model parameters.\n\n    Parameters\n    ----------\n    group : str\n        Name of this model parameters group, usually the name of the model or\n        sub-model to which they belong\n    *params : spotpy.parameter\n        One or more parameters\n    '''\n    def __init__(self, group, *params):\n        self._group = group\n        # Create {name: spotpy.parameter, ...} dictionary\n        super().__init__(**dict([(p.name, p) for p in params]))\n\n\nclass GenericOptimization(object):\n    '''\n    A more generic and expansive tool for optimization; includes many more\n    algorithms for minimization/ maximization problems, including sequential\n    quadratic programming (SQP), which is the default here and is closest to\n    what is performed in Matlab's `fmincon`. Despite the similarity to `fmincon`,\n    SQP will tend to deviate strongly from the initial parameters derived via\n    fmincon. This solver is SLOW for gradient descent methods relative to\n    `scipy.optimize.least_squares()`, because the gradient is calculated with\n    a finite element approach.\n\n        opt = GenericOptimization(residuals, OPT_BOUNDS['gpp'],\n            step_size = (0.01, 0.1, 0.1, 1, 1, 0.1, 0.1, 0.05))\n        opt.solve(init_params)\n\n    See: https://nlopt.readthedocs.io/en/latest/NLopt_Python_Reference/\n\n    Parameters\n    ----------\n    func : function\n        Function to calculate the residuals\n    bounds : list or tuple\n        2-element sequence of (lower, upper) bounds where each element is an\n        array\n    method : str\n        One of the nlopt algorithms\n    step_size : list or tuple or numpy.ndarray\n        Sequence of steps to take in gradient descent; not needed for\n        derivative-free methods\n    verbose : bool\n        True to print all output to the screen\n    '''\n    def __init__(\n            self, func, bounds, method: int = nlopt.LD_SLSQP,\n            step_size = None, verbose = True):\n        # https://nlopt.readthedocs.io/en/latest/NLopt_Algorithms/#slsqp\n        assert isinstance(method, int), 'Did not recognize \"method\" argument'\n        self._bounds = bounds\n        self._method = method\n        self._residuals = func\n        self._step_size = step_size\n        self._verbose = verbose\n\n    def solve(self, init_params, ftol = 1e-8, xtol = 1e-8, maxeval = 500):\n        '''\n        Using the sum-of-squared errors (SSE) as the objective function,\n        solves a minimization problem.\n\n        Parameters\n        ----------\n        init_params : list or tuple or numpy.ndarray\n            Sequence of starting parameters (or \"initial guesses\")\n        ftol : float\n        xtol : float\n        maxeval : int\n            Maximum number of objective function evaluations\n\n        Returns\n        -------\n        numpy.ndarray\n        '''\n        @suppress_warnings\n        def sse(x):\n            return np.power(self._residuals(x), 2).sum()\n\n        @suppress_warnings\n        def objf(x, grad):\n            if grad.size > 0:\n                # Approximate the gradient using finite element method\n                grad[...] = optimize.approx_fprime(\n                    x, sse, self._step_size)\n            return sse(x)\n\n        opt = nlopt.opt(self._method, len(init_params))\n        # https://nlopt.readthedocs.io/en/latest/NLopt_Python_Reference/#localsubsidiary-optimization-algorithm\n        if self._method == nlopt.G_MLSL_LDS:\n            opt.set_local_optimizer(\n                nlopt.opt(nlopt.LN_COBYLA, len(init_params)))\n        opt.set_min_objective(objf)\n        opt.set_lower_bounds(self._bounds[0])\n        opt.set_upper_bounds(self._bounds[1])\n        opt.set_ftol_abs(ftol)\n        opt.set_xtol_abs(xtol)\n        opt.set_maxeval(maxeval)\n        if self._verbose:\n            print('Solving...')\n        return opt.optimize(init_params)\n\n\ndef cbar(rh, k_mult, q_rh = 75, q_k = 50):\n    '''\n    Calculates \"Cbar,\" the time-constant upper quantile of the RH/Kmult\n    ratio. Where Kmult is >/= `q_k`, return the `q_rh` quantile of RH/Kmult;\n    intended for T x N arrays where T is the number of time steps and\n    N is the number of (flux tower) sites.\n\n    Parameters\n    ----------\n    rh : numpy.ndarray\n        (T x N) vector of heterotrophic respiration\n    k_mult : numpy.ndarray\n        (T x N) vector of Kmult\n    q_rh : float\n        Percentile of RH/Kmult to return\n    q_k : float\n        Percentile of Kmult below which RH/Kmult values are masked\n\n    Returns\n    -------\n    numpy.float64\n    '''\n    cutoff = np.apply_along_axis(\n        np.percentile, 0, k_mult, q = q_k).reshape((1, k_mult.shape[1]))\n    return np.nanpercentile(\n        np.where(k_mult >= cutoff,\n            np.divide(rh, np.where(k_mult == 0, np.nan, k_mult)), np.nan),\n        q = q_rh, axis = 0)\n\n\ndef reco(params, tsoil, smsf, reco_tower, gpp_tower, q_rh = 75, q_k = 50):\n    '''\n    Calculate empirical ecosystem respiration, RECO, based on current model\n    parameters and the inferred soil organic carbon (SOC) storage; i.e., this\n    calculation should be used in model calibration when SOC is not a priori\n    known, see `pyl4c.apps.calibration.cbar()`. The expected model parameter\n    names are \"CUE\" for the carbon use efficiency of plants.\n\n    Parameters\n    ----------\n    params : dict\n        A dict-like data structure with named model parameters\n    tsoil : numpy.ndarray\n        (T x N) vector of soil temperature (deg K), where T is the number of\n        time steps, N the number of sites\n    smsf : numpy.ndarray\n        (T x N) vector of surface soil wetness (%), where T is the number of\n        time steps, N the number of sites\n    reco_tower : numpy.ndarray\n        (T x N) vector of observed RECO from eddy covariance tower sites\n    gpp_tower : numpy.ndarray\n        (T x N) vector of observed GPP from eddy covariance tower sites\n    q_rh : int\n        The percentile of RH/Kmult to use in calculating Cbar\n    q_k : int\n        The percentile of Kmult below which RH/Kmult values are masked\n\n    Returns\n    -------\n    numpy.ndarray\n    '''\n    # Calculate RH as (RECO - RA) or (RECO - (faut * GPP));\n    #   globals \"reco_tower\", \"gpp_tower\"\n    ra = ((1 - params['CUE']) * gpp_tower)\n    rh = reco_tower - ra\n    rh = np.where(rh < 0, 0, rh) # Mask out negative RH values\n    # Compute Cbar with globals \"q_rh\" and \"q_k\"\n    kmult0 = k_mult(params, tsoil, smsf)\n    cbar0 = cbar(rh, kmult0, q_rh, q_k)\n    return ra + (kmult0 * cbar0)\n\n\ndef report_fit_stats(obs, pred, weights = np.array([1]), verbose = True):\n    '''\n    Reports the RMSE, ubRMSE, and Bias for observed and predicted values.\n\n    Parameters\n    ----------\n    obs : numpy.ndarray\n        Vector of observed (\"true\") values\n    pred : numpy.ndarray\n        Vector of predicted values\n    weights : numpy.ndarray\n        (Optional) Vector of weights for each sample\n\n    Returns\n    -------\n    tuple\n        (R-squared, RMSE, ubRMSE, Bias)\n    '''\n    y = np.apply_along_axis(detrend, 0, obs, fill = True)\n    yhat = np.apply_along_axis(detrend, 0, pred, fill = True)\n    rmse = rmsd(obs, pred, weights = weights)\n    ubrmse = rmsd(y, yhat, weights = weights)\n    bias = np.nanmean(np.subtract(pred, obs))\n    mask = np.logical_or(np.isnan(obs), np.isnan(pred))\n    r_squared = 1 - np.divide(\n        sum_of_squares(\n            obs[~mask], pred[~mask], add_intercept = False, which = 'sse'),\n        sum_of_squares(\n            obs[~mask], pred[~mask], add_intercept = False, which = 'sst'))\n    if verbose:\n        print('Fit statistics:')\n        print('--    R^2: %s' % ('%.3f' % r_squared).rjust(6))\n        print('--   RMSE: %s' % ('%.3f' % rmse).rjust(6))\n        print('-- ubRMSE: %s' % ('%.3f' % ubrmse).rjust(6))\n        print('--   Bias: %s' % ('%.3f' % bias).rjust(6))\n    return (r_squared, rmse, ubrmse, bias)\n\n\ndef solve_least_squares(func, init_params, labels, bounds, **kwargs):\n    '''\n    Apply constrained, non-linear least-squares optimization. Mostly a\n    wrapper for `scipy.optimize.least_squares()`.\n\n    Parameters\n    ----------\n    func : function\n        Function to calculate the residuals\n    init_params : list or tuple or numpy.ndarray\n        Sequence of starting parameters (or \"initial guesses\")\n    labels : list or tuple or numpy.ndarray\n        Sequence of parameter names\n    bounds : list or tuple\n        2-element sequence of (lower, upper) bounds where each element is an\n        array\n\n    Returns\n    -------\n    scipy.optimize.OptimizeResult\n    '''\n    # Update the optimization settings; this loss function produces\n    #   an estimate for the FT multiplier that is closest to prior\n    kwargs.setdefault('loss', 'arctan')\n    kwargs.setdefault('method', 'trf')\n    kwargs.setdefault('max_nfev', 500)\n    kwargs.setdefault('ftol', 1e-8)\n    kwargs.setdefault('xtol', 1e-8)\n    kwargs.setdefault('gtol', 1e-8)\n    try:\n        solution = optimize.least_squares(\n            func, init_params, bounds = bounds, **kwargs)\n    except ValueError:\n        below = [\n            labels[i]\n            for i in np.argwhere(init_params < bounds[0]).flatten().tolist()\n        ]\n        above = [\n            labels[i]\n            for i in np.argwhere(init_params > bounds[1]).flatten().tolist()\n        ]\n        if np.isnan(init_params).any():\n            raise ValueError(\n                'Error in candidate parameter values; residual function probably returning NaNs')\n        else:\n            raise ValueError(\n                '\"Infeasibility\" error; check lower bound on %s; upper bound on %s' % (\n                '(None)' if len(below) == 0 else ', '.join(below),\n                '(None)' if len(above) == 0 else ', '.join(above)))\n    return solution\n", "meta": {"hexsha": "41ffb5ecb684e181decdbcc4c4d45f5f032fb414", "size": 22571, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyl4c/apps/calibration/__init__.py", "max_stars_repo_name": "arthur-e/pyl4c", "max_stars_repo_head_hexsha": "97e1225c8b70ed9b21edc9e54ee66c78a02cded8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-01T18:30:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-01T18:30:21.000Z", "max_issues_repo_path": "pyl4c/apps/calibration/__init__.py", "max_issues_repo_name": "arthur-e/pyl4c", "max_issues_repo_head_hexsha": "97e1225c8b70ed9b21edc9e54ee66c78a02cded8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyl4c/apps/calibration/__init__.py", "max_forks_repo_name": "arthur-e/pyl4c", "max_forks_repo_head_hexsha": "97e1225c8b70ed9b21edc9e54ee66c78a02cded8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4636510501, "max_line_length": 111, "alphanum_fraction": 0.598156927, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.31742625913050115, "lm_q1q2_score": 0.17108742277573374}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, print_function\n\nimport io\nimport json\nimport math\nimport os\nimport shutil\nimport struct\n\nimport h5py\nimport numpy as np\nimport obspy\nimport xarray\n\n# LASIF can already deal with the binary SES3D models. Thus we can utilize\n# this here!\nfrom lasif.ses3d_models import RawSES3DModelHandler\nfrom lasif.scripts.lasif_cli import _find_project_comm\n\n\ndef binary_ses3d_to_hdf5_model(input_folder, lasif_project, output_filename):\n    \"\"\"\n    Function converting a binary SES3D model consisting of many files to an\n    HDF5 model.\n\n    Requires access to a LASIF project that determines the potentially\n    rotated geometry. Not super clean but workable.\n\n    :param input_folder: The folder containing the input model.\n    :param lasif_project: The folder with the LASIF project.\n    :param output_filename: The output filename.\n    \"\"\"\n    assert not os.path.exists(output_filename), \\\n        \"'%s' already exists\" % output_filename\n    _dirname = os.path.dirname(output_filename)\n    if not os.path.exists(_dirname) and _dirname:\n        os.makedirs(_dirname)\n\n    # We need the project to get the domain definition which stores the\n    # rotation settings.\n    comm = _find_project_comm(lasif_project, read_only_caches=True)\n\n    if any(_i.startswith(\"grad_\") for _i in os.listdir(input_folder)):\n        model_type = \"kernel\"\n    else:\n        model_type = \"earth_model\"\n\n    m = RawSES3DModelHandler(\n        directory=input_folder, domain=comm.project.domain,\n        model_type=model_type)\n\n    f = h5py.File(output_filename)\n\n    try:\n        data_group = f.create_group(\"data\")\n\n        if model_type == \"earth_model\":\n            # We will also store A, C, and Q which we don't invert for but\n            # have to take into account in any case.\n            components = [\"vp\", \"vsh\", \"vsv\", \"rho\", \"A\", \"C\"]\n            # Q might not exist.\n            if \"Q\" in m.components:\n                components.append(\"Q\")\n        elif model_type == \"kernel\":\n            components = [\"grad_cp\", \"grad_csh\", \"grad_csv\", \"grad_rho\"]\n        else:\n            raise NotImplementedError\n\n        # Make it compatible with seismopt.\n        rename_dict = {\n            \"grad_cp\": \"vp\",\n            \"grad_csh\": \"vsh\",\n            \"grad_csv\": \"vsv\",\n            \"grad_rho\": \"rho\",\n        }\n\n        for c in components:\n            m.parse_component(c)\n            _d = xarray.DataArray(\n                np.require(m.parsed_components[c],\n                           requirements=[\"C_CONTIGUOUS\"]),\n                coords=[90.0 - m.collocation_points_lats[::-1],\n                        m.collocation_points_lngs,\n                        (6371.0 - m.collocation_points_depth) * 1000.0],\n                dims=[\"colatitude\", \"longitude\", \"radius_in_m\"])\n\n            # Write to HDF5 file.\n            if c in rename_dict:\n                c = rename_dict[c]\n\n            data = _d.data\n\n            # Make sure it is g\\cm^3 in the hdf5 files.\n            if c == \"rho\":\n                if data.mean() > 1000.0:\n                    data /= 1000.0\n\n            data_group[c] = np.require(data, dtype=np.float32)\n\n            data_group[c].attrs[\"variable_name\"] = \\\n                np.string_((c + \"\\x00\").encode())\n\n        # Write coordinate axes.\n        f[\"coordinate_0\"] = np.require(_d.colatitude.data, dtype=np.float32)\n        f[\"coordinate_0\"].attrs[\"name\"] = \\\n            np.string_((\"colatitude\" + \"\\x00\").encode())\n        f[\"coordinate_1\"] = np.require(_d.longitude.data, dtype=np.float32)\n        f[\"coordinate_1\"].attrs[\"name\"] = \\\n            np.string_((\"longitude\" + \"\\x00\").encode())\n        f[\"coordinate_2\"] = np.require(_d.radius_in_m.data, dtype=np.float32)\n        f[\"coordinate_2\"].attrs[\"name\"] = \\\n            np.string_((\"radius_in_m\" + \"\\x00\").encode())\n\n        # Create dimension scales.\n        for c in components:\n            if c in rename_dict:\n                c = rename_dict[c]\n            f[\"data\"][c].dims[0].label = \"colatitude\"\n            f[\"data\"][c].dims[1].label = \"longitude\"\n            f[\"data\"][c].dims[2].label = \"radius_in_m\"\n\n            f[\"data\"][c].dims.create_scale(f[\"coordinate_0\"], \"values\")\n            f[\"data\"][c].dims.create_scale(f[\"coordinate_1\"], \"values\")\n            f[\"data\"][c].dims.create_scale(f[\"coordinate_2\"], \"values\")\n\n            f[\"data\"][c].dims[0].attach_scale(f[\"coordinate_0\"])\n            f[\"data\"][c].dims[1].attach_scale(f[\"coordinate_1\"])\n            f[\"data\"][c].dims[2].attach_scale(f[\"coordinate_2\"])\n\n        # Also add some meta information.\n        _meta = f.create_group(\"_meta\")\n        model_name = os.path.split(os.path.normpath(os.path.abspath(\n            input_folder)))[-1]\n        _meta.attrs[\"model_name\"] = np.string_((model_name + \"\\x00\").encode())\n\n        # Everything needed to reconstruct the domain objects.\n        _domain = _meta.create_group(\"domain\")\n        d = comm.project.domain\n        _domain.attrs[\"min_longitude\"] = d.min_longitude\n        _domain.attrs[\"max_longitude\"] = d.max_longitude\n        _domain.attrs[\"min_latitude\"] = d.min_latitude\n        _domain.attrs[\"max_latitude\"] = d.max_latitude\n        _domain.attrs[\"min_depth_in_km\"] = d.min_depth_in_km\n        _domain.attrs[\"max_depth_in_km\"] = d.max_depth_in_km\n        _domain.attrs[\"rotation_axis\"] = d.rotation_axis\n        _domain.attrs[\"rotation_angle_in_degree\"] = d.rotation_angle_in_degree\n        _domain.attrs[\"boundary_width_in_degree\"] = d.boundary_width_in_degree\n\n        # We also need to store the boxfile.\n        _meta.create_dataset(\"boxfile\",\n                             data=np.fromfile(m.boxfile, dtype=np.uint8))\n    finally:\n        try:\n            f.close()\n        except:\n            pass\n\n\ndef hdf5_model_to_binary_ses3d_model(input_filename, output_folder):\n    with h5py.File(input_filename, \"r\") as f:\n        _hdf5_model_to_binary_ses3d_model(f=f,\n                                          output_folder=output_folder)\n\n\ndef _hdf5_model_to_binary_ses3d_model(f, output_folder):\n    lpd = 4\n\n    assert not os.path.exists(output_folder), \\\n        \"Folder '%s' already exists.\" % output_folder\n    os.makedirs(output_folder)\n\n    with io.BytesIO(f[\"_meta\"][\"boxfile\"].value.tostring()) as buf:\n        setup = _read_boxfile(buf)\n        # Also write to output folder\n        buf.seek(0, 0)\n        with io.open(os.path.join(output_folder, \"boxfile\"), \"wb\") as fh:\n            fh.write(buf.read())\n\n    data = {}\n\n    # SES3D internally expects a density in kg/m^3 - The hdf5 files might\n    # have g/cm^3.\n    rho = f[\"data\"][\"rho\"][:]\n    if rho.mean() < 1000:\n        rho *= 1000.0\n    data[\"rhoinv\"] = 1.0 / rho\n\n    data[\"mu\"] = (f[\"data\"][\"vsh\"][:] * 1000) ** 2 / data[\"rhoinv\"]\n    data[\"lambda\"] = \\\n        (f[\"data\"][\"vp\"][:] * 1000) ** 2 / data[\"rhoinv\"] - 2 * data[\"mu\"]\n    data[\"A\"] = (f[\"data\"][\"A\"][:])\n    data[\"B\"] = (f[\"data\"][\"vsv\"][:] * 1000) ** 2 / data[\"rhoinv\"] - data[\"mu\"]\n    data[\"C\"] = (f[\"data\"][\"C\"][:])\n    # Q might now always be given.\n    if \"Q\" in f[\"data\"]:\n        data[\"Q\"] = (f[\"data\"][\"Q\"][:])\n\n    for key in sorted(data.keys()):\n        for number, domain in enumerate(setup[\"subdomains\"]):\n            x_min, x_max = domain[\"boundaries_x\"]\n            y_min, y_max = domain[\"boundaries_y\"]\n            z_min, z_max = domain[\"boundaries_z\"]\n\n            # Minimum indices\n            x_min, y_min, z_min = \\\n                [lpd * _j for _j in (x_min, y_min, z_min)]\n            # Maximum indices\n            x_max, y_max, z_max = \\\n                [lpd * (_j + 1) for _j in (x_max, y_max, z_max)]\n\n            _d = data[key][x_min: x_max + 1,\n                           y_min: y_max + 1,\n                           z_min: z_max + 1]\n            # Invert last components.\n            _d = _d[:, :, ::-1]\n            # Reduplicate the GLL points.\n            for _i in xrange(3):\n                _s = _d.shape[_i]\n                left_idx = np.arange(_s - lpd)[::lpd]\n                right_idx = np.arange(_s + lpd)[lpd + 1::lpd]\n                if _i == 0:\n                    _t = [_d[_l:_r, :, :]\n                          for _l, _r in zip(left_idx, right_idx)]\n                elif _i == 1:\n                    _t = [_d[:, _l:_r, :]\n                          for _l, _r in zip(left_idx, right_idx)]\n                elif _i == 2:\n                    _t = [_d[:, :, _l:_r]\n                          for _l, _r in zip(left_idx, right_idx)]\n                else:\n                    raise NotImplementedError\n\n                _d = np.concatenate(_t, axis=_i)\n            # Reshape to restore 6 dimensional layout.\n            _d = np.require(_d, requirements=[\"C_CONTIGUOUS\"])\n            shape = (domain[\"index_x_count\"], lpd + 1,\n                     domain[\"index_y_count\"], lpd + 1,\n                     domain[\"index_z_count\"], lpd + 1)\n            _d = _d.reshape(shape, order=\"C\")\n            # Roll to retrieve original SES3D memory order.\n            _d = np.rollaxis(_d, 2, 1)\n            _d = np.rollaxis(_d, 4, 2)\n            _d = np.require(_d, requirements=[\"F_CONTIGUOUS\"])\n\n            filename = os.path.join(output_folder, \"%s%i\" % (key, number))\n            with io.open(filename, \"wb\") as fh:\n                fh.write(struct.pack(\"<I\", 520000))\n                fh.write(_d.tobytes(order=\"F\"))\n                fh.write(struct.pack(\"<I\", 520000))\n\n\ndef _read_boxfile(fh):\n    \"\"\"\n    Copied straight from LASIF.\n    \"\"\"\n    setup = {\"subdomains\": []}\n\n    # The first 14 lines denote the header\n    lines = fh.readlines()[14:]\n    # Strip lines and remove empty lines.\n    lines = [_i.strip() for _i in lines if _i.strip()]\n\n    # The next 4 are the global CPU distribution.\n    setup[\"total_cpu_count\"] = int(lines.pop(0))\n    setup[\"cpu_count_in_x_direction\"] = int(lines.pop(0))\n    setup[\"cpu_count_in_y_direction\"] = int(lines.pop(0))\n    setup[\"cpu_count_in_z_direction\"] = int(lines.pop(0))\n\n    if set(lines[0]) == set(\"-\"):\n        lines.pop(0)\n    # Small sanity check.\n    if setup[\"total_cpu_count\"] != setup[\"cpu_count_in_x_direction\"] * \\\n            setup[\"cpu_count_in_y_direction\"] * \\\n            setup[\"cpu_count_in_z_direction\"]:\n        msg = (\"Invalid boxfile. Total and individual processor \"\n               \"counts do not match.\")\n        raise ValueError(msg)\n\n    # Now parse the rest of file which contains the subdomains.\n    def subdomain_generator(data):\n        \"\"\"\n        Simple generator looping over each defined box and yielding\n        a dictionary for each.\n\n        :param data: The text.\n        \"\"\"\n        while data:\n            subdom = {}\n            # Convert both indices to 0-based indices\n            subdom[\"single_index\"] = int(data.pop(0)) - 1\n            subdom[\"multi_index\"] = map(lambda x: int(x) - 1,\n                                        data.pop(0).split())\n            subdom[\"boundaries_x\"] = map(int, data.pop(0).split())\n            subdom[\"boundaries_y\"] = map(int, data.pop(0).split())\n            subdom[\"boundaries_z\"] = map(int, data.pop(0).split())\n            # Convert radians to degree.\n            subdom[\"physical_boundaries_x\"] = map(\n                    lambda x: math.degrees(float(x)), data.pop(0).split())\n            subdom[\"physical_boundaries_y\"] = map(\n                    lambda x: math.degrees(float(x)), data.pop(0).split())\n            # z is in meter.\n            subdom[\"physical_boundaries_z\"] = \\\n                map(float, data.pop(0).split())\n            for component in (\"x\", \"y\", \"z\"):\n                idx = \"boundaries_%s\" % component\n                index_count = subdom[idx][1] - subdom[idx][0] + 1\n                subdom[\"index_%s_count\" % component] = index_count\n                # The boxfiles are slightly awkward in that the indices\n                # are not really continuous. For example if one box\n                # has 22 as the last index, the first index of the next\n                # box will also be 22, even though it should be 23. The\n                # next snippet attempts to fix this deficiency.\n                offset = int(round(subdom[idx][0] /\n                                   float(index_count - 1)))\n                subdom[idx][0] += offset\n                subdom[idx][1] += offset\n            # Remove separator_line if existent.\n            if set(lines[0]) == set(\"-\"):\n                lines.pop(0)\n            yield subdom\n    # Sort them after with the single index.\n    setup[\"subdomains\"] = sorted(list(subdomain_generator(lines)),\n                                 key=lambda x: x[\"single_index\"])\n    # Do some more sanity checks.\n    if len(setup[\"subdomains\"]) != setup[\"total_cpu_count\"]:\n        msg = (\"Invalid boxfile. Number of processors and subdomains \"\n               \"to not match.\")\n        raise ValueError(msg)\n    for component in (\"x\", \"y\", \"z\"):\n        idx = \"index_%s_count\" % component\n        if len(set([_i[idx] for _i in setup[\"subdomains\"]])) != 1:\n            msg = (\"Invalid boxfile. Unequal %s index count across \"\n                   \"subdomains.\") % component\n            raise ValueError(msg)\n\n    # Now generate the absolute indices for the whole domains.\n    for component in (\"x\", \"y\", \"z\"):\n        setup[\"boundaries_%s\" % component] = (\n            min([_i[\"boundaries_%s\" % component][0]\n                 for _i in setup[\"subdomains\"]]),\n            max([_i[\"boundaries_%s\" %\n                    component][1] for _i in setup[\"subdomains\"]]))\n        setup[\"physical_boundaries_%s\" % component] = (\n            min([_i[\"physical_boundaries_%s\" % component][0] for\n                 _i in setup[\"subdomains\"]]),\n            max([_i[\"physical_boundaries_%s\" % component][1] for _i in\n                 setup[\"subdomains\"]]))\n\n    return setup\n\n\ndef plot_hdf5_model(filename, plot_type=\"horizontal\", *args, **kwargs):\n    with h5py.File(filename, \"r\") as f:\n        if plot_type == \"horizontal\":\n            _plot_hdf5_model_horizontal(f=f, *args, **kwargs)\n        elif plot_type == \"vertical\":\n            _plot_hdf5_model_vertical(f=f, *args, **kwargs)\n        else:\n            raise NotImplementedError\n\n\ndef _plot_hdf5_model_vertical(f, component, output_filename, vmin=None,\n                              vmax=None):\n    import matplotlib.cm\n    import matplotlib.pylab as plt\n\n    data = xarray.DataArray(\n        f[\"data\"][component][:], [\n            (\"latitude\", 90.0 - f[\"coordinate_0\"][:]),\n            (\"longitude\", f[\"coordinate_1\"][:]),\n            (\"radius\", f[\"coordinate_2\"][:] / 1000.0)])\n\n    plt.style.use('seaborn-pastel')\n\n    plt.figure(figsize=(32, 18))\n\n    plt.suptitle(\"Component %s - File %s\" % (component, output_filename),\n                 fontsize=20)\n\n    count = 12\n    lats = plt.linspace(data[\"latitude\"].min(), data[\"latitude\"].max(),\n                        count)\n    lngs = plt.linspace(data[\"longitude\"].min(), data[\"longitude\"].max(),\n                        count)\n\n    import lasif.colors\n    my_colormap = lasif.colors.get_colormap(\n        \"tomo_full_scale_linear_lightness\")\n\n    # Overwrite colormap things if given.\n    if vmin is not None and vmax is not None:\n        min_val_plot = vmin\n        max_val_plot = vmax\n    else:\n        mean = data.mean()\n        max_diff = max(abs(mean - data.min()),\n                       abs(data.max() - mean))\n        min_val_plot = mean - max_diff\n        max_val_plot = mean + max_diff\n        # Plotting essentially constant models.\n        min_delta = 0.001 * abs(max_val_plot)\n        if (max_val_plot - min_val_plot) < min_delta:\n            max_val_plot = max_val_plot + min_delta\n            min_val_plot = min_val_plot - min_delta\n\n    for _i in range(count):\n        plt.subplot(4, count // 2, _i + 1)\n\n        x, y = np.meshgrid(data.longitude, data.radius)\n\n        plot_data = data.sel(latitude=lats[_i], method=\"nearest\")\n        plot_data = np.ma.masked_invalid(plot_data.data)\n\n        # Plot.\n        plt.pcolormesh(\n            x, y, plot_data.T,\n            cmap=my_colormap, vmin=min_val_plot, vmax=max_val_plot,\n            shading=\"flat\")\n\n        # make a colorbar and title\n        plt.colorbar()\n        plt.title(\"@Latitude: \" + str(lats[_i]))\n\n\n    for _i in range(count):\n        plt.subplot(4, count // 2, count + _i + 1)\n\n        x, y = np.meshgrid(data.latitude, data.radius)\n\n        plot_data = data.sel(longitude=lngs[_i], method=\"nearest\")\n        plot_data = np.ma.masked_invalid(plot_data.data)\n\n        # Plot.\n        plt.pcolormesh(\n            x, y, plot_data.T,\n            cmap=my_colormap, vmin=min_val_plot, vmax=max_val_plot,\n            shading=\"flat\")\n\n        # make a colorbar and title\n        plt.colorbar()\n        plt.title(\"@Longitude: \" + str(lngs[_i]))\n\n\n    plt.tight_layout(rect=(0, 0, 1, 0.95))\n    plt.savefig(output_filename, dpi=150)\n    plt.close()\n\n\n\n\ndef _plot_hdf5_model_horizontal(f, component, output_filename,\n                                vmin=None, vmax=None):\n    import matplotlib.cm\n    import matplotlib.pylab as plt\n\n    data = xarray.DataArray(\n        f[\"data\"][component][:], [\n            (\"latitude\", 90.0 - f[\"coordinate_0\"][:]),\n            (\"longitude\", f[\"coordinate_1\"][:]),\n            (\"radius\", f[\"coordinate_2\"][:] / 1000.0)])\n\n    plt.style.use('seaborn-pastel')\n\n    from lasif.domain import RectangularSphericalSection\n    domain = RectangularSphericalSection(**dict(f[\"_meta\"][\"domain\"].attrs))\n\n    plt.figure(figsize=(32, 18))\n\n    depth_position_map = {\n        50: (0, 0),\n        100: (0, 1),\n        150: (1, 0),\n        250: (1, 1),\n        400: (2, 0),\n        600: (2, 1)\n    }\n\n    for depth, location in depth_position_map.items():\n        ax = plt.subplot2grid((3, 5), location)\n        radius = 6371.0 - depth\n\n        # set up a map and colourmap\n        m = domain.plot(ax=ax, resolution=\"c\", skip_map_features=True)\n\n        import lasif.colors\n        my_colormap = lasif.colors.get_colormap(\n                \"tomo_full_scale_linear_lightness\")\n\n        from lasif import rotations\n\n        x, y = np.meshgrid(data.longitude, data.latitude)\n\n        x_shape = x.shape\n        y_shape = y.shape\n\n        lat_r, lon_r = rotations.rotate_lat_lon(\n                y.ravel(), x.ravel(),\n                domain.rotation_axis,\n                domain.rotation_angle_in_degree)\n\n        x, y = m(lon_r, lat_r)\n\n        x.shape = x_shape\n        y.shape = y_shape\n\n        plot_data = data.sel(radius=radius, method=\"nearest\")\n        plot_data = np.ma.masked_invalid(plot_data.data)\n\n        # Overwrite colormap things if given.\n        if vmin is not None and vmax is not None:\n            min_val_plot = vmin\n            max_val_plot = vmax\n        else:\n            mean = plot_data.mean()\n            max_diff = max(abs(mean - plot_data.min()),\n                           abs(plot_data.max() - mean))\n            min_val_plot = mean - max_diff\n            max_val_plot = mean + max_diff\n            # Plotting essentially constant models.\n            min_delta = 0.001 * abs(max_val_plot)\n            if (max_val_plot - min_val_plot) < min_delta:\n                max_val_plot = max_val_plot + min_delta\n                min_val_plot = min_val_plot - min_delta\n\n        # Plot.\n        im = m.pcolormesh(\n                x, y, plot_data,\n                cmap=my_colormap, vmin=min_val_plot, vmax=max_val_plot,\n                shading=\"gouraud\")\n\n        # make a colorbar and title\n        m.colorbar(im, \"right\", size=\"3%\", pad='2%')\n        plt.title(str(depth) + ' km')\n\n\n    # Depth based statistics.\n    plt.subplot2grid((3, 5), (0, 4), rowspan=3)\n    plt.title(\"Depth statistics\")\n    mean = data.mean(axis=(0, 1))\n    std = data.std(axis=(0, 1))\n    _min = data.min(axis=(0, 1))\n    _max = data.max(axis=(0, 1))\n\n    plt.fill_betweenx(data.radius, mean - std, mean + std,\n                      label=\"std\", color=\"#FF3C83\")\n    plt.plot(mean, data.radius, label=\"mean\", color=\"k\", lw=2)\n    plt.plot(_min, data.radius, color=\"grey\", label=\"min\")\n    plt.plot(_max, data.radius, color=\"grey\", label=\"max\")\n    plt.legend(loc=\"best\")\n    plt.xlabel(\"Value\")\n    plt.ylabel(\"Radius\")\n\n    plt.hlines(data.radius, plt.xlim()[0], plt.xlim()[1], color=\"0.8\",\n               zorder=-10, linewidth=0.5)\n\n    # Roughness plots.\n    plt.subplot2grid((3, 5), (0, 2))\n    _d = np.abs(data.diff(\"latitude\", n=1)).sum(\"latitude\").data\n    plt.title(\"Roughness in latitude direction, Total: %g\" % _d.sum())\n    plt.pcolormesh(data.longitude.data, data.radius.data,\n                   _d.T, cmap=matplotlib.cm.viridis)\n    try:\n        plt.colorbar()\n    except:\n        pass\n    plt.xlabel(\"Longitude\")\n    plt.ylabel(\"Radius\")\n\n    plt.subplot2grid((3, 5), (1, 2))\n    _d = np.abs(data.diff(\"longitude\", n=1)).sum(\"longitude\").data\n    plt.title(\"Roughness in longitude direction. Total: %g\" % data.sum())\n    plt.pcolormesh(data.latitude.data, data.radius.data, _d.T,\n                   cmap=matplotlib.cm.viridis)\n    try:\n        plt.colorbar()\n    except:\n        pass\n    plt.xlabel(\"Latitude\")\n    plt.ylabel(\"Radius\")\n\n    plt.subplot2grid((3, 5), (2, 2))\n    _d = np.abs(data.diff(\"radius\", n=1)).sum(\"radius\").data\n    plt.title(\"Roughness in radius direction. Total: %g\" % _d.sum())\n    plt.pcolormesh(data.longitude.data, data.latitude.data,\n                   _d, cmap=matplotlib.cm.viridis)\n    try:\n        plt.colorbar()\n    except:\n        pass\n    plt.xlabel(\"Longitude\")\n    plt.ylabel(\"Latitude\")\n\n    # L2\n    plt.subplot2grid((3, 5), (0, 3))\n    _d = (data ** 2).sum(\"latitude\").data\n    plt.title(\"L2 Norm in latitude direction, Total: %g\" % _d.sum())\n    plt.pcolormesh(data.longitude.data, data.radius.data,\n                   _d.T, cmap=matplotlib.cm.viridis)\n    try:\n        plt.colorbar()\n    except:\n        pass\n    plt.xlabel(\"Longitude\")\n    plt.ylabel(\"Radius\")\n\n    plt.subplot2grid((3, 5), (1, 3))\n    _d = (data ** 2).sum(\"longitude\").data\n    plt.title(\"L2 Norm in longitude direction, Total: %g\" % _d.sum())\n    plt.pcolormesh(data.latitude.data, data.radius.data, _d.T,\n                   cmap=matplotlib.cm.viridis)\n    try:\n        plt.colorbar()\n    except:\n        pass\n    plt.xlabel(\"Latitude\")\n    plt.ylabel(\"Radius\")\n\n    plt.subplot2grid((3, 5), (2, 3))\n    _d = (data ** 2).sum(\"radius\").data\n    plt.title(\"L2 Norm in radius direction, Total: %g\" % _d.sum())\n    plt.pcolormesh(data.longitude.data, data.latitude.data,\n                   _d, cmap=matplotlib.cm.viridis)\n    try:\n        plt.colorbar()\n    except:\n        pass\n    plt.xlabel(\"Longitude\")\n    plt.ylabel(\"Latitude\")\n\n    plt.suptitle(\"Component %s - File %s\" % (component, output_filename),\n                 fontsize=20)\n\n    plt.tight_layout(rect=(0, 0, 1, 0.95))\n\n    plt.savefig(output_filename, dpi=150)\n    plt.close()\n\n\ndef taper_and_precondition_hdf5_model(\n        input_filename, output_filename, taper_colatitude_offset_in_km,\n        taper_colatitude_width_in_km, taper_longitude_offset_in_km,\n        taper_longitude_width_in_km, taper_depth_offset_in_km,\n        taper_depth_width_in_km, scaling_file):\n    # Make a copy of the file and then modify in-place.\n    assert not os.path.exists(output_filename), \"File '%s' already exists.\" % \\\n        output_filename\n\n    shutil.copy2(input_filename, output_filename)\n\n    with h5py.File(output_filename, \"r+\") as f:\n        _taper_and_precondition_hdf5_model(\n            f=f,\n            taper_colatitude_offset_in_km=taper_colatitude_offset_in_km,\n            taper_colatitude_width_in_km=taper_colatitude_width_in_km,\n            taper_longitude_offset_in_km=taper_longitude_offset_in_km,\n            taper_longitude_width_in_km=taper_longitude_width_in_km,\n            taper_depth_offset_in_km=taper_depth_offset_in_km,\n            taper_depth_width_in_km=taper_depth_width_in_km,\n            scaling_file=scaling_file)\n\n\ndef _taper_and_precondition_hdf5_model(f, taper_colatitude_offset_in_km,\n                                       taper_colatitude_width_in_km,\n                                       taper_longitude_offset_in_km,\n                                       taper_longitude_width_in_km,\n                                       taper_depth_offset_in_km,\n                                       taper_depth_width_in_km,\n                                       scaling_file):\n\n    # Read the scaling file and make sure it plays nice with the gradient at\n    # hand.\n    with io.open(scaling_file, \"rb\") as fh:\n        scaling = json.load(fh)\n    np.testing.assert_allclose(scaling[\"radius\"], f[\"coordinate_2\"][:])\n    scaling = np.array(scaling[\"weights\"], dtype=np.float32)\n\n    fac = 111.19492664455873\n    colatitude_in_km = f[\"coordinate_0\"][:] * fac\n    longitude_in_km = f[\"coordinate_1\"][:] * fac\n    radius_in_km = f[\"coordinate_2\"][:] / 1000.0\n\n    # Convert into distance from either end.\n    for _i in [colatitude_in_km, longitude_in_km]:\n        _i[:] = np.fmin(_i - _i.min(), _i.max() - _i)\n    # In the radial direction we only taper at the bottom.\n    radius_in_km -= radius_in_km.min()\n\n    # Apply the offsets\n    colatitude_in_km -= taper_colatitude_offset_in_km\n    longitude_in_km -= taper_longitude_offset_in_km\n    radius_in_km -= taper_depth_offset_in_km\n\n    # Apply the taper width\n    colatitude_in_km /= taper_colatitude_width_in_km\n    longitude_in_km /= taper_longitude_width_in_km\n    radius_in_km /= taper_depth_width_in_km\n\n    # Clip\n    longitude_in_km = longitude_in_km.clip(min=0.0, max=1.0)\n    colatitude_in_km = colatitude_in_km.clip(min=0.0, max=1.0)\n    radius_in_km = radius_in_km.clip(min=0.0, max=1.0)\n\n    # Apply Hanning taper. This finalizes the taper we have to multiply the\n    # data with.\n    for x in [longitude_in_km, colatitude_in_km, radius_in_km]:\n        x[:] = 0.5 * (1.0 - np.cos(x * np.pi))\n\n    # Apply the tapers.\n    for name, data in f[\"data\"].items():\n        data = data[:]\n        data *= colatitude_in_km[:, np.newaxis, np.newaxis]\n        data *= longitude_in_km[np.newaxis, :, np.newaxis]\n        data *= radius_in_km[np.newaxis, np.newaxis, :]\n        # Apply the depth weighting.\n        data *= scaling[np.newaxis, np.newaxis, :]\n        f[\"data\"][name][:] = data\n\n\ndef determine_depth_scaling(input_filename, output_filename, max_kernel_value):\n    with h5py.File(input_filename, mode=\"r\") as f:\n        _determine_depth_scaling(f=f,\n                                 output_filename=output_filename,\n                                 max_kernel_value=max_kernel_value)\n\n\ndef _determine_depth_scaling(f, output_filename, max_kernel_value):\n    all_scales = []\n\n    for data in f[\"data\"].values():\n        data = data[:]\n        # Zeros mess with everything - replace with the smallest\n        # non-zero number!\n        data[data == 0] = np.abs(data[data != 0]).min()\n\n        # Damping factor - the higher the damping the lesser the effect of\n        # the depth scaling.\n        damp = 0.1\n\n        m = np.max(np.abs(data))\n        fac = np.zeros(data.shape[-1])\n        for _i in range(len(fac)):\n            fac[_i] = 1.0 / (damp * m + np.abs(data[:, :, _i]).max())\n\n        all_scales.append(fac)\n\n    s = np.sum(all_scales, axis=0)\n\n    import scipy.signal\n    # Smooth a tiny bit to avoid wild oscillations.\n    w = scipy.signal.gaussian(5, 3)\n    w /= w.sum()\n\n    # Scale this for funsies.\n    s /= s.min()\n\n    # Avoid boundary effects.\n    l = len(s)\n    s = np.concatenate([np.ones_like(s) * s[0], s, np.ones_like(s) * s[-1]])\n\n    smooth_s = np.convolve(s, w, mode=\"same\")\n    # Cut out the original segment.\n    smooth_s = smooth_s[l:-l]\n    s = s[l:-l]\n\n    # Abuse ObsPy to taper a bit at both ends.\n    smooth_s = obspy.Trace(data=smooth_s).taper(\n        max_percentage=0.2, type=\"cosine\", side=\"left\").data.clip(min=1.0)\n\n    # Get the max absolute value in depth for the vsv kernel.\n    max_vsv = np.abs(f[\"data\"][\"vsv\"][:]).max(axis=(0, 1))\n\n    factor = max_kernel_value / (smooth_s * max_vsv).max()\n\n    import matplotlib.pyplot as plt\n    plt.style.use(\"ggplot\")\n\n    y = f[\"coordinate_2\"][:] / 1000.0\n\n    plt.subplot(141)\n    m = max_vsv\n    plt.plot(m, y)\n    plt.xlim(-0.1 * m.ptp(), 1.1 * m.max())\n    plt.ylim(y[0], y[-1])\n    plt.title(\"max abs vsv\")\n\n    plt.subplot(142)\n    plt.plot(s, y)\n    plt.ylim(y[0], y[-1])\n    plt.title(\"raw\")\n\n    plt.subplot(143)\n    plt.plot(smooth_s, y)\n    plt.xlim(0, smooth_s.max() * 1.5)\n    plt.ylim(y[0], y[-1])\n    plt.title(\"smoothed\")\n\n    plt.subplot(144)\n    m = smooth_s * factor * max_vsv\n    plt.plot(m, y)\n    plt.xlim(-0.1 * max_kernel_value, 1.1 * max_kernel_value)\n    plt.ylim(y[0], y[-1])\n    plt.title(\"after\")\n\n    plt.suptitle(\"Factor: %s\" % str(factor))\n\n    output = {\n        \"radius\": [float(i) for i in f[\"coordinate_2\"][:]],\n        \"weights\": [float(i) for i in smooth_s * factor]\n    }\n\n    with io.open(output_filename, \"wb\") as fh:\n        json.dump(output, fh)\n\n    plt.show()\n", "meta": {"hexsha": "a5e3ac2ec628d61aa11853756d3888657cb1856f", "size": 28840, "ext": "py", "lang": "Python", "max_stars_repo_path": "ses3d_ctrl/hdf5_model.py", "max_stars_repo_name": "krischer/ses3d_ctrl", "max_stars_repo_head_hexsha": "ebf293407d163f897e687a424c426b0335ff4843", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-01-22T23:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-08T03:29:47.000Z", "max_issues_repo_path": "ses3d_ctrl/hdf5_model.py", "max_issues_repo_name": "krischer/ses3d_ctrl", "max_issues_repo_head_hexsha": "ebf293407d163f897e687a424c426b0335ff4843", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ses3d_ctrl/hdf5_model.py", "max_forks_repo_name": "krischer/ses3d_ctrl", "max_forks_repo_head_hexsha": "ebf293407d163f897e687a424c426b0335ff4843", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-01-15T14:22:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-08T01:51:34.000Z", "avg_line_length": 35.299877601, "max_line_length": 79, "alphanum_fraction": 0.5724687933, "include": true, "reason": "import numpy,import scipy", "num_tokens": 7414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.17107062285693797}}
{"text": "########################################################################\n# Code to generate BOSS and 2dFLenS data and random lens catalogues    #\n# in the KiDS regions, including magnitude weights, from the           #\n# publicly-available datasets. \n# Author:  Chris Blake\n# Questions to: cblake@swin.edu.au\n# Original version 13th May 2019                                        #\n# History\n# CH 20th Nov - update output to ldac format (still compatible with fits)\n# also included KiDS MASK information and 2dFLenS overlap information\n# CH 24th March - update to DR4.1 Masks\n########################################################################\n\nimport sys\nimport numpy as np\nimport scipy.spatial\nimport matplotlib.pyplot as plt\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\nfrom astropy.io import fits\nimport ldac\nfrom astropy.wcs import WCS\nimport astropy.wcs as pywcs\n\n#============================================\n# Generate the lens catalogues\ndef makecats(ired):\n\n# Read in KiDS photometric catalogue both N and S\n# (rmin_N,rmax_N,dmin_N,dmax_N) are returned as the precise boundaries of the KiDS-N region\n# (rmin_S,rmax_S,dmin_S,dmax_S) are returned as the precise boundaries of the KiDS-S region\n  raskids,deckids,grcolkids,ricolkids,rmagkids,maskkids,rmin_N,rmax_N,dmin_N,dmax_N,rmin_S,rmax_S,dmin_S,dmax_S = readkids()\n\n# Read in BOSS data and random lenses\n\n# K1000-N has rough min/max RA (238.6, 128.4) and min/max DEC (-4.1, 3.1)\n# We want to measure GGL out to 6 degrees so we should select the BOSS region\n# to be 6.0 degrees larger than the KiDS region (buffer for good measure)\n\n# (R.A., Dec.) boundaries to use for BOSS catalogue\n  edge = 6.0\n  rmin,rmax,dmin,dmax = rmin_N-edge,rmax_N+edge,dmin_N-edge,dmax_N+edge\n  rasbossdat,decbossdat,redbossdat,weicompbossdat,weifkpbossdat,nbossdat = readboss(1,ired,rmin,rmax,dmin,dmax)\n  rasbossran,decbossran,redbossran,weicompbossran,weifkpbossran,nbossran = readboss(2,ired,rmin,rmax,dmin,dmax)\n  \n# You might want to sub-sample the BOSS randoms to increase your speed\n# but we need high signal-to-noise random gamma_t signals though so we do not sub-sample here\n\n# Sub-sample BOSS randoms to 40x data for consistency with 2dFLenS\n#  cut = np.random.choice(nbossran,40*nbossdat,replace=False)\n#  rasbossran,decbossran,redbossran,weicompbossran,weifkpbossran = rasbossran[cut],decbossran[cut], \\\n#                                                                  redbossran[cut],weicompbossran[cut],weifkpbossran[cut]\n#  nbossran = 40*nbossdat\n#  print ('Sub-sampled BOSS randoms to',nbossran,'lenses')\n\n# Read in 2dFLenS data and random lenses \n# We do not need to apply ra/dec cuts here as 2dFLenS is designed to overlap with KiDS\n  ras2dfdat,dec2dfdat,red2dfdat,weifkp2dfdat,n2dfdat = read2dflens(1,ired)\n  ras2dfran,dec2dfran,red2dfran,weifkp2dfran,n2dfran = read2dflens(2,ired)\n# completeness weights=1 for 2dFLenS\n  weicomp2dfdat,weicomp2dfran = np.ones(n2dfdat),np.ones(n2dfran)\n\n# Find KiDS mags/colours of BOSS and 2dFLenS data lenses\n# iphot is a flag which is 1 if there is a photometry match, otherwise 0\n\n  print ('\\nMatching catalogues...')\n\n  grcolbossdat,ricolbossdat,rmagbossdat,kidsmaskbossdat_match,iphotbossdat = matchlenstosource(rasbossdat,decbossdat,raskids,deckids,\\\n                                                                          grcolkids,ricolkids,rmagkids,maskkids,\\\n                                                                          rmin_N,rmax_N,dmin_N,dmax_N,rmin_S,rmax_S,dmin_S,dmax_S)\n  grcol2dfdat,ricol2dfdat,rmag2dfdat,kidsmask2dfdat_match,iphot2dfdat = matchlenstosource(ras2dfdat,dec2dfdat,raskids,deckids,\\\n                                                                     grcolkids,ricolkids,rmagkids,maskkids,\\\n                                                                     rmin_N,rmax_N,dmin_N,dmax_N,\\\n                                                                     rmin_S,rmax_S,dmin_S,dmax_S)\n\n# Determine magnitude weights of 2dFLenS data with BOSS as reference\n# For the reference sample we only want to use BOSS galaxies that haven't been masked in the gri KiDS data\n# but it's OK to reweight the 2dFLens galaxies in a mask - we can use the mask later to add caution\n\n#We want to  know where the gri information is for this we want bitmask=0x681C\n#info here:http://lensingkids.strw.leidenuniv.nl/doku.php?id=kids-1000#mask_values_and_meanings\n\n  bitmask=0x681C\n  ifilter=np.logical_not(np.array(kidsmaskbossdat_match & bitmask, dtype=bool))\n  cutboss = ((iphotbossdat > 0) & (ifilter))\n  cut2df = (iphot2dfdat > 0)\n\n  magsbossdat = np.dstack([grcolbossdat[cutboss],ricolbossdat[cutboss],rmagbossdat[cutboss]])[0]\n  mags2dfdat = np.dstack([grcol2dfdat[cut2df],ricol2dfdat[cut2df],rmag2dfdat[cut2df]])[0]\n  \n  #set all gri colour re-weights to zero\n  weimag2dfdat = np.zeros(n2dfdat)\n  #if matched to an accurate  BOSS galaxy, the weight is then calculated\n  weimag2dfdat[cut2df] = calcmagweights(mags2dfdat,magsbossdat,weicompbossdat[cutboss])\n\n# Determine magnitude weights of BOSS data with 2dFLenS as reference\n# For the reference sample we only want to use 2dfLenS galaxies that haven't been masked in the gri KiDS data\n# but it's OK to reweight the BOSS galaxies in a mask- we can use the mask later to add caution\n\n  ifilter=np.logical_not(np.array(kidsmask2dfdat_match & bitmask, dtype=bool))\n  cutboss = (iphotbossdat > 0 )\n  cut2df = ((iphot2dfdat > 0) & (ifilter))\n\n  magsbossdat = np.dstack([grcolbossdat[cutboss],ricolbossdat[cutboss],rmagbossdat[cutboss]])[0]\n  mags2dfdat = np.dstack([grcol2dfdat[cut2df],ricol2dfdat[cut2df],rmag2dfdat[cut2df]])[0]\n  #set all gri colour re-weights to zero\n  weimagbossdat = np.zeros(nbossdat)\n  #if matched to an accurate 2dFLenS galaxy, the weight is then calculated\n  weimagbossdat[cutboss] = calcmagweights(magsbossdat,mags2dfdat,weicomp2dfdat[cut2df])\n  \n# magnitudes=0, and weights=1 for randoms\n  \n  iphotbossran,weimagbossran,grcolbossran,ricolbossran,rmagbossran= np.zeros(nbossran,dtype='int'),np.ones(nbossran),\\\n                                                                     np.zeros(nbossran),np.zeros(nbossran),np.zeros(nbossran)\n  iphot2dfran,weimag2dfran,grcol2dfran,ricol2dfran,rmag2dfran = np.zeros(n2dfran,dtype='int'),np.ones(n2dfran),\\\n                                                                     np.zeros(n2dfran),np.zeros(n2dfran),np.zeros(n2dfran)\n\n# add kids mask to the random catalogue to allow for gri KiDS overlap matching requirement\n# also do this for the data so the rare blend objects that aren't matched don't automatically get a wcs mask flag\n\n  Nfitsmask='/home/cech/KiDSLenS/THELI_catalogues/MOSAIC_MASK/DR4.1_FITS_MASK/KiDS_N.16bit.6arcs.AIT.reg2.fits'\n  kidsmaskbossran = addkidsmask(rasbossran,decbossran,Nfitsmask)\n  kidsmaskbossdat = addkidsmask(rasbossdat,decbossdat,Nfitsmask)\n\n  Sfitsmask='/home/cech/KiDSLenS/THELI_catalogues/MOSAIC_MASK/DR4.1_FITS_MASK/KiDS_S.16bit.6arcs.AIT.reg2.fits'\n  kidsmask2dfran = addkidsmask(ras2dfran,dec2dfran,Sfitsmask)\n  kidsmask2dfdat = addkidsmask(ras2dfdat,dec2dfdat,Sfitsmask)\n  \n  print ('\\nWriting out final catalogues...')\n\n  # Write out fits file catalogues\n  outfile = OUTDIR +'/BOSS_data_z' + str(ired) + '.fits'\n  writelensldaccat(outfile,rasbossdat,decbossdat,redbossdat,weicompbossdat,weifkpbossdat,\\\n                       iphotbossdat,weimagbossdat,grcolbossdat,ricolbossdat,rmagbossdat,kidsmaskbossdat)\n  #outfile = OUTDIR +'/BOSS_random_CMASS_z' + str(ired) + '.fits'\n  #outfile = OUTDIR +'/BOSS_random_LOWZ_z' + str(ired) + '.fits'\n  outfile = OUTDIR +'/BOSS_random_z' + str(ired) + '.fits'\n  writelensldaccat(outfile,rasbossran,decbossran,redbossran,weicompbossran,weifkpbossran,\\\n                       iphotbossran,weimagbossran,grcolbossran,ricolbossran,rmagbossran,kidsmaskbossran)\n  outfile = OUTDIR +'/2dFLenS_data_z' + str(ired) + '.fits'\n  writelensldaccat(outfile,ras2dfdat,dec2dfdat,red2dfdat,weicomp2dfdat,weifkp2dfdat,\\\n                       iphot2dfdat,weimag2dfdat,grcol2dfdat,ricol2dfdat,rmag2dfdat,kidsmask2dfdat)\n  outfile = OUTDIR +'/2dFLenS_random_z' + str(ired) + '.fits'\n  writelensldaccat(outfile,ras2dfran,dec2dfran,red2dfran,weicomp2dfran,weifkp2dfran,\\\n                       iphot2dfran,weimag2dfran,grcol2dfran,ricol2dfran,rmag2dfran,kidsmask2dfran)\n  return\n\n#============================================\n# Read in the KiDS mask in order to add a KiDS MASK value to the randoms\ndef addkidsmask(ra,dec,fitsmask):\n  print ('\\nReading KIDS mask....')\n  \n  inimage = fits.open(fitsmask) # axis flipped!\n  imagedata = inimage[0].data\n  \n  w = WCS(fitsmask)\n  c = SkyCoord(ra, dec, unit=\"deg\")\n\n  pos=pywcs.utils.skycoord_to_pixel(c, w)\n\n  ngals=np.shape(pos)[1]\n  mask=np.zeros(ngals).astype(int)\n  for k in range(ngals):\n    if int(pos[1][k])>=0 and int(pos[1][k])<np.shape(imagedata)[0] and \\\n       int(pos[0][k])>=0 and int(pos[0][k])<np.shape(imagedata)[1]:\n        mask[k]=imagedata[int(pos[1][k]),int(pos[0][k])]\n    else:\n        mask[k]=16384\n\n  return mask\n#============================================\n# Read in KiDS photometric catalogue\ndef readkids():\n  print ('\\nReading in KiDS bright source data...')\n\n  raskids,deckids,grcolkids,ricolkids,rmagkids,maskkids = [],[],[],[],[],[]\n\n  # Read in KiDS N and KiDS S and combine into a single data vector\n  # Do not do this with anything other than a bright sample\n\n  for ireg in range(1,3):\n    if (ireg == 1):\n      datfile = 'K1000_N_'+KiDS_VER\n    else:\n      datfile = 'K1000_S_'+KiDS_VER\n\n    hdulist = fits.open(KiDS_DIR+'/'+datfile)\n\n    # The KiDS catalogues are ldac tables in the 2nd extension\n    table = hdulist[2].data\n    \n    raskids1 = table.field('ALPHA_J2000')\n    # trick to deal with the zero-crossing\n    if (ireg == 2):\n      raskids1[raskids1 > 180.] -= 360.\n\n    deckids1 = table.field('DELTA_J2000')\n    raskids = np.append(raskids,raskids1)\n    deckids = np.append(deckids,deckids1)\n    gmaggaap = table.field('MAG_GAAP_g')\n    rmaggaap = table.field('MAG_GAAP_r')\n    imaggaap = table.field('MAG_GAAP_i')\n    rmagtot = table.field('MAG_AUTO')\n    grcolkids = np.append(grcolkids,gmaggaap-rmaggaap)\n    ricolkids = np.append(ricolkids,rmaggaap-imaggaap)\n    rmagkids = np.append(rmagkids,rmagtot)\n    maskkids1 = table.field('MASK')\n    maskkids = np.append(maskkids,maskkids1)\n\n    if (ireg == 1):\n      rmin_N,rmax_N,dmin_N,dmax_N = np.amin(raskids1),np.amax(raskids1),np.amin(deckids1),np.amax(deckids1)\n    else:\n      rmin_S,rmax_S,dmin_S,dmax_S = np.amin(raskids1),np.amax(raskids1),np.amin(deckids1),np.amax(deckids1)\n    hdulist.close()\n\n  print (len(raskids),'KiDS sources')\n  # trick to deal with the zero-crossing\n  raskids[raskids < 0.] += 360.\n  \n  return raskids,deckids,grcolkids,ricolkids,rmagkids,maskkids,rmin_N,rmax_N,dmin_N,dmax_N,rmin_S,rmax_S,dmin_S,dmax_S\n\n#============================================\n# Read in BOSS lenses: datopt -- 1) data 2) random\ndef readboss(datopt,ired,rmin,rmax,dmin,dmax):\n\n  # this will break if the file name is longer than 500\n  datfile=np.chararray(2, itemsize=500)\n\n  if (datopt == 1):\n    print ('\\nReading in BOSS data lenses...')\n  else:\n    print ('\\nReading in BOSS random lenses...')\n  if (ired == 1):\n    zmin,zmax = 0.2,0.5\n  elif (ired == 2):\n    zmin,zmax = 0.5,0.75\n  else:\n    zmin,zmax = 0.4,0.6  # Overlap bin - not used\n  if (datopt == 1):\n    datfile[0] = 'galaxy_DR12v5_CMASSLOWZTOT_North.fits'\n    nfiles = 1\n  else:\n    datfile[0] = 'random0_DR12v5_CMASSLOWZTOT_North.fits'\n    datfile[1] = 'random1_DR12v5_CMASSLOWZTOT_North.fits'\n    #datfile[0] = 'random0_DR12v5_LOWZ_North.fits'\n    #datfile[1] = 'random1_DR12v5_LOWZ_North.fits'\n    #datfile[0] = 'random0_DR12v5_CMASS_North.fits'\n    #datfile[1] = 'random1_DR12v5_CMASS_North.fits'\n    nfiles = 2\n\n  #rasboss_out,decboss_out,redboss_out,weicompboss_out,weifkpboss_out = [],[],[],[],[]\n\n  # read in files - there are two for the randoms\n  for ifile in range(nfiles):\n    hdulist = fits.open(BOSS_DIR+'/'+datfile[ifile].decode(\"utf-8\"))\n    table = hdulist[1].data\n    rasboss = table.field('RA')\n    decboss = table.field('DEC')\n    redboss = table.field('Z')\n    weifkpboss = table.field('WEIGHT_FKP')\n    if (datopt == 1):\n      weicp = table.field('WEIGHT_CP')\n      weinoz = table.field('WEIGHT_NOZ')\n      weisys = table.field('WEIGHT_SYSTOT')\n      weicompboss = weisys*(weinoz+weicp-1.)\n      print (len(rasboss),'BOSS lenses')\n    else:\n      weicompboss = np.ones(len(rasboss), dtype='f')\n      print (len(rasboss),'BOSS randoms', ifile)\n    hdulist.close()\n\n    #ra/dec cuts\n    cut = (rasboss > rmin) & (rasboss < rmax) & (decboss > dmin) & (decboss < dmax) & (redboss > zmin) & (redboss < zmax)\n\n    rasboss_out=rasboss[cut]    \n    decboss_out=decboss[cut]\n    redboss_out=redboss[cut]\n    weicompboss_out=weicompboss[cut]\n    weifkpboss_out=weifkpboss[cut] \n  \n    if (ifile>0):\n      rasboss_out=np.append(rasboss_out,rasboss[cut]) \n      decboss_out=np.append(decboss_out,decboss[cut])\n      redboss_out=np.append(redboss_out,redboss[cut]) \n      weifkpboss_out=np.append(weifkpboss_out,weifkpboss[cut])\n      weicompboss_out=np.append(weicompboss_out,weicompboss[cut])\n      \n  nboss = len(rasboss_out)\n  print ('Cut to',nboss,'BOSS lenses with',rmin,'< R.A. <',rmax,dmin,'< Dec. <',dmax,zmin,'< z <',zmax)\n  return rasboss_out,decboss_out,redboss_out,weicompboss_out,weifkpboss_out,nboss\n\n#============================================\n# Read in 2dFLenS lenses: datopt -- 1) data 2) random\ndef read2dflens(datopt,ired):\n  if (datopt == 1):\n    print ('\\nReading in 2dFLenS data lenses...')\n    nset = 1\n  else:\n    print ('\\nReading in 2dFLenS random lenses...')\n    nset = 100\n    \n  ras2df,dec2df,red2df,weifkp2df = [],[],[],[]\n  for iset in range(nset):\n    for ireg in range(2,3):   #for K1000 analysis we only use the SGP\n      if (ireg == 1):\n        creg = '_atlas_kidsn_160105'\n      else:\n        creg = '_atlas_kidss_160105'\n      if (ired == 1):\n        cred = '_bz1'\n      elif (ired == 2):  # this is not a typo - Since the random catalogues have been created I have renamed \n                         # bins 2 and 3 as we will not use the overlap bin and it's easier to script over bins 1&2\n                         # rather than over bins 1&3\n        cred = '_bz3'\n      else:\n        cred = '_bz2'\n      if (datopt == 1):\n        #datfile = twodF_DIR + '/data' + cred + creg + '_ntar.dat'\n        datfile = twodF_DIR + '/data' + cred + creg + '_rat.dat'\n      else:\n        if (iset < 9):\n          cset = '00' + str(iset+1)\n        elif (iset<99):\n          cset = '0' + str(iset+1)\n        else:\n          cset = str(iset+1)\n        #datfile = twodF_DIR + '/rand' + cset + cred + creg + '_ntar.dat'\n        datfile = twodF_DIR + '/rand' + cset + cred + creg + '_rat.dat'\n      print (datfile)\n\n      f = open(datfile,'r')\n      lines = f.readlines()[3:]\n\n      for line in lines:\n        fields = line.split()\n        ras2df.append(float(fields[0]))\n        dec2df.append(float(fields[1]))\n        red2df.append(float(fields[2]))\n        weifkp2df.append(float(fields[6]))\n  f.close()\n  ras2df,dec2df,red2df,weifkp2df = np.array(ras2df),np.array(dec2df),np.array(red2df),np.array(weifkp2df)\n  n2df = len(ras2df)\n  print (n2df,'2dFLenS lenses')\n  \n  return ras2df,dec2df,red2df,weifkp2df,n2df\n\n#============================================\n# Find magnitudes/colours of closest source to each lens\ndef matchlenstosource(raslens,declens,rassource,decsource,grcolsource,ricolsource,rmagsource,masksource,rmin1,rmax1,dmin1,dmax1,rmin2,rmax2,dmin2,dmax2):\n  print ('\\nFinding closest source to each lens...')\n  separcmax = 2. # Matching separation in arcsec - using BOSS fibre size as maximum separation\n  nlens = len(raslens)\n  #initialise the KiDS colours and mags to 0, and the mask to 16384 - i.e out of the KiDS footprint\n  grcollens,ricollens,rmaglens,masklens,iphotlens = np.zeros(nlens),np.zeros(nlens),np.zeros(nlens),np.ones(nlens,dtype='int')*16384,np.zeros(nlens,dtype='int')\n  indexlens = np.arange(nlens)\n  cut1 = (raslens > rmin1) & (raslens < rmax1) & (declens > dmin1) & (declens < dmax1)\n  cut2 = ((raslens > rmin2+360.) | (raslens < rmax2)) & (declens > dmin2) & (declens < dmax2)\n  cut = (cut1 | cut2)\n  raslens1,declens1,indexlens1 = raslens[cut],declens[cut],indexlens[cut]\n  print (len(raslens1),'lenses in angular area')\n  coosource = SkyCoord(rassource*u.deg,decsource*u.deg)\n  coolens = SkyCoord(raslens1*u.deg,declens1*u.deg)\n  indexsource,sep,d3d = coolens.match_to_catalog_sky(coosource)\n  grcollens1,ricollens1,rmaglens1,masklens1 = grcolsource[indexsource],ricolsource[indexsource],rmagsource[indexsource],masksource[indexsource]\n  cut = (sep.arcsec < separcmax)\n  raslens1,declens1,grcollens1,ricollens1,rmaglens1,masklens1,indexlens1 = raslens1[cut],declens1[cut], \\\n                                                                 grcollens1[cut],ricollens1[cut],\\\n                                                                 rmaglens1[cut],masklens1[cut],indexlens1[cut]\n  nlens = len(raslens1)\n  print (nlens,'lenses matched within',separcmax,'arcsec')\n  grcollens[indexlens1] = grcollens1\n  ricollens[indexlens1] = ricollens1\n  rmaglens[indexlens1] = rmaglens1\n  masklens[indexlens1] = masklens1\n  iphotlens[indexlens1] = 1\n  return grcollens,ricollens,rmaglens,masklens,iphotlens\n\n#============================================\n# Determine weights of catalogue to match magnitudes of reference using\n# the KV450 DIR method\ndef calcmagweights(magscat,magsref,weiref):\n  print ('\\nCalculating magnitude weights...')\n  no_NN = 10\n  ncat = magscat.shape[0]\n  nref = magsref.shape[0]\n# Build tree\n  print ('\\nBuilding trees...')\n  treecat = scipy.spatial.cKDTree(magscat,leafsize=100)\n  treeref = scipy.spatial.cKDTree(magsref,leafsize=100)\n# Nearest catalogue neighbours to each catalogue object\n  neighbours_cat_of_cat = ( treecat.query(magscat,k=no_NN) )\n  average_ref_weight = np.average(weiref)\n  no_neighbours_ref_of_cat = np.zeros(ncat)\n  neighbours_ref_of_cat = []\n  weight_ref_of_cat = np.zeros(ncat)\n  weicat = np.zeros(ncat) # if it is unmatched the returned weight is zero\n# Loop over each catalogue object\n  for i in range(ncat):\n# Indices of nearest reference neighbours to each catalogue object\n    x = magscat[i,:]\n    r = neighbours_cat_of_cat[0][i,no_NN-1]\n    iref = treeref.query_ball_point(x,r)\n    neighbours_ref_of_cat.append(iref)\n    no_neighbours_ref_of_cat[i] = float(len(neighbours_ref_of_cat[i]))\n    if (no_neighbours_ref_of_cat[i] > 0.):\n      weight_ref_of_cat[i] = (np.average(weiref[neighbours_ref_of_cat[i]]))\n      weicat[i] = (\n                    (float(ncat)/float(nref)) *\n                    (weight_ref_of_cat[i]/average_ref_weight) *\n                    (no_neighbours_ref_of_cat[i]/float(no_NN))\n                  )\n  print (len(no_neighbours_ref_of_cat[no_neighbours_ref_of_cat == 0.]),'catalogue objects with no neighbours')\n  print ('Mean reference weight =',np.average(weiref))\n  print ('Mean catalogue weight =',np.average(weicat))\n  return weicat\n\n#============================================\n# Write out lens fits catalogue\ndef writelenscat(outfile,raslens,declens,redlens,weicomplens,weifkplens,iphotlens,weimaglens,grcollens,ricollens,rmaglens,kidsmask):\n  print ('\\nWriting out lens catalogue...')\n  print (outfile)\n  col1 = fits.Column(name='ALPHA_J2000',format='D',array=raslens)\n  col2 = fits.Column(name='DELTA_J2000',format='D',array=declens)\n  col3 = fits.Column(name='Z',format='E',array=redlens)\n  col4 = fits.Column(name='WEICOMP',format='E',array=weicomplens)\n  col5 = fits.Column(name='WEIFKP',format='E',array=weifkplens)\n  col6 = fits.Column(name='FLAGPHOT',format='J',array=iphotlens)\n  col7 = fits.Column(name='WEIMAG',format='E',array=weimaglens)\n  col8 = fits.Column(name='GRCOL',format='E',array=grcollens)\n  col9 = fits.Column(name='RICOL',format='E',array=ricollens)\n  col10 = fits.Column(name='RMAG',format='E',array=rmaglens)\n  col11 = fits.Column(name='KIDSMASK',format='J',array=kidsmask)\n  hdulist = fits.BinTableHDU.from_columns([col1,col2,col3,col4,col5,col6,col7,col8,col9,col10,col11])\n  hdulist.writeto(outfile)\n  return\n\n#============================================\n# Write out lens ldac catalogue\ndef writelensldaccat(outfile,raslens,declens,redlens,weicomplens,weifkplens,iphotlens,weimaglens,grcollens,ricollens,rmaglens,kidsmask):\n  print ('\\nWriting out lens catalogue in ldac format...')\n  print (outfile)\n  \n  #create a new ldac table\n  ldac_table=ldac.LDACTable(hdu=None)\n  ldac_table['ALPHA_J2000']=raslens\n  ldac_table['DELTA_J2000']=declens\n  ldac_table['Z']=redlens\n  ldac_table['WEICOMP']=weicomplens\n  ldac_table['WEIFKP']=weifkplens\n  ldac_table['FLAGPHOT']=iphotlens\n  ldac_table['WEIMAG']=weimaglens\n  ldac_table['GRCOL']=grcollens\n  ldac_table['RICOL']=ricollens\n  ldac_table['RMAG']=rmaglens\n  ldac_table['KIDSMASK']=kidsmask\n  # for the Treecorr hack to calculate Npairs for a weighted sample\n  # we also write out the weight squared\n  ldac_table['WEICOMPsq']=weicomplens*weicomplens\n  \n  ldac_table.saveas(outfile, overwrite=True)\n  return\n\n#============================================\n# Read in lens fits catalogue - used by testcats \ndef readlenscat(infile):\n  print ('\\nReading in lens catalogue...')\n  print (infile)\n  hdulist = fits.open(infile)\n  table = hdulist[1].data\n  raslens = table.field('ALPHA_J2000')\n  declens = table.field('DELTA_J2000')\n  redlens = table.field('Z')\n  weicomplens = table.field('WEICOMP')\n  weifkplens = table.field('WEIFKP')\n  iphotlens = table.field('FLAGPHOT')\n  weimaglens = table.field('WEIMAG')\n  grcollens = table.field('GRCOL')\n  ricollens = table.field('RICOL')\n  rmaglens = table.field('RMAG')\n  hdulist.close()\n  nlens = len(raslens)\n  print ('Read in',nlens,'lenses')\n  return raslens,declens,redlens,weicomplens,weifkplens,iphotlens,weimaglens,grcollens,ricollens,rmaglens,nlens\n\n#============================================\n# Run test plots of the lens catalogues\ndef testcats(ired):\n  opt = 4 # 1) (R.A., Dec.) overplot\n          # 2) redshift overplot\n          # 3) magnitude files\n          # 4) weighted distributions\n          # 5) weights\n# Read in lens fits catalogues\n#  stem = '/Users/cblake/Data/kids1000/lenscats/'\n  stem = '/disk09/KIDS/K1000_TWO_PT_STATS/GGLCATS/'\n  if (ired == 1):\n    cred = '_bz1'\n    zmin,zmax = 0.2,0.5\n  elif (ired == 2):\n    cred = '_bz2'\n    zmin,zmax = 0.4,0.6\n  else:\n    cred = '_bz3'\n    zmin,zmax = 0.5,0.75\n  infile = stem + 'boss_data_lenses' + cred + '.fits'\n  rasbossdat,decbossdat,redbossdat,weicompbossdat,weifkpbossdat,iphotbossdat,weimagbossdat,grcolbossdat,ricolbossdat,rmagbossdat,nbossdat = readlenscat(infile)\n  infile = stem + 'boss_random_lenses' + cred + '.fits'\n  rasbossran,decbossran,redbossran,weicompbossran,weifkpbossran,iphotbossran,weimagbossran,grcolbossran,ricolbossran,rmagbossran,nbossran = readlenscat(infile)\n  infile = stem + '2dflens_data_lenses' + cred + '.fits'\n  ras2dfdat,dec2dfdat,red2dfdat,weicomp2dfdat,weifkp2dfdat,iphot2dfdat,weimag2dfdat,grcol2dfdat,ricol2dfdat,rmag2dfdat,n2dfdat = readlenscat(infile)\n  infile = stem + '2dflens_random_lenses' + cred + '.fits'\n  ras2dfran,dec2dfran,red2dfran,weicomp2dfran,weifkp2dfran,iphot2dfran,weimag2dfran,grcol2dfran,ricol2dfran,rmag2dfran,n2dfran = readlenscat(infile)\n# Overplot data and random lenses\n  if (opt == 1):\n    ras1,dec1,lab1 = rasbossdat,decbossdat,'Data'\n    ras2,dec2,lab2 = rasbossran,decbossran,'Randoms'\n#    ras1,dec1,lab1 = ras2dfdat,dec2dfdat,'Data'\n#    ras2,dec2,lab2 = ras2dfran,dec2dfran,'Randoms'\n#    ras1,dec1,lab1 = rasbossdat,decbossdat,'BOSS'\n#    ras2,dec2,lab2 = ras2dfdat,dec2dfdat,'2dFLenS'\n#    ras1[ras1 > 180.] = ras1[ras1 > 180.] - 360.\n#    ras2[ras2 > 180.] = ras2[ras2 > 180.] - 360.\n#    rmin,rmax,dmin,dmax = 90.,270.,-15.,90.\n#    rmin,rmax,dmin,dmax = -90.,90.,-90.,-25.\n#    cut = (ras1 > rmin) & (ras1 < rmax) & (dec1 > dmin) & (dec1 < dmax)\n#    ras1,dec1 = ras1[cut],dec1[cut]\n#    cut = (ras2 > rmin) & (ras2 < rmax) & (dec2 > dmin) & (dec2 < dmax)\n#    ras2,dec2 = ras2[cut],dec2[cut]\n    fig = plt.figure()\n    n1,n2 = len(ras1),len(ras2)\n    nplot = min(10000,n1,n2)\n    if (n1 > nplot):\n      cut = np.random.choice(n1,nplot,replace=False)\n    else:\n      cut = np.full(n1,True,dtype=bool)\n    plt.scatter(ras1[cut],dec1[cut],s=0.5,marker='o',color='black',alpha=0.25,label=lab1)\n    if (n2 > nplot):\n      cut = np.random.choice(n2,nplot,replace=False)\n    else:\n      cut = np.full(n2,True,dtype=bool)\n    plt.scatter(ras2[cut],dec2[cut],s=0.5,marker='o',color='red',alpha=0.25,label=lab2)\n    plt.xlabel('R.A. [deg]')\n    plt.ylabel('Dec. [deg]')\n    plt.legend()\n    plt.show()\n    sys.exit()\n  elif (opt == 2):\n    nz = 100\n    red1,lab1 = redbossdat,'Data'\n    red2,lab2 = redbossran,'Randoms'\n#    red1,lab1 = red2dfdat,'Data'\n#    red2,lab2 = red2dfran,'Randoms'\n#    red1,lab1 = redbossdat,'BOSS'\n#    red2,lab2 = red2dfdat,'2dFLenS'\n    fig = plt.figure()\n    hist1,zlims = np.histogram(red1,bins=nz,range=[zmin,zmax],normed=True)\n    zcen = zlims[:-1] + 0.5*(zmax-zmin)/nz\n    plt.plot(zcen,hist1,color='black',label=lab1)\n    hist2,zlims = np.histogram(red2,bins=nz,range=[zmin,zmax],normed=True)\n    plt.plot(zcen,hist2,color='red',label=lab2)\n    plt.xlabel('z')\n    plt.ylabel('p(z)')\n    plt.legend()\n    plt.show()\n    sys.exit()\n# Write out matched catalogues\n  elif (opt == 3):\n    if (ired == 1):\n      fileboss = 'phot_bossz1.dat'\n      file2df = 'phot_2dflz1.dat'\n      outfile2df = 'weights_2dflz1.dat'\n    elif (ired == 2):\n      fileboss = 'phot_bossz2.dat'\n      file2df = 'phot_2dflz2.dat'\n      outfile2df = 'weights_2dflz2.dat'\n    elif (ired == 3):\n      fileboss = 'phot_bossz3.dat'\n      file2df = 'phot_2dflz3.dat'\n      outfile2df = 'weights_2dflz3.dat'\n    print (fileboss)\n    f = open(fileboss,'w')\n    for i in range(nbossdat):\n      if (iphotbossdat[i] > 0):\n        f.write('{} {} {} {} {} {} {}'.format(rasbossdat[i],decbossdat[i],redbossdat[i],weicompbossdat[i],grcolbossdat[i],ricolbossdat[i],rmagbossdat[i]) + '\\n')\n    f.close()\n    print (file2df)\n    f = open(file2df,'w')\n    for i in range(n2dfdat):\n      if (iphot2dfdat[i] > 0):\n        f.write('{} {} {:7.5f} {} {} {} {}'.format(ras2dfdat[i],dec2dfdat[i],red2dfdat[i],weicomp2dfdat[i],grcol2dfdat[i],ricol2dfdat[i],rmag2dfdat[i]) + '\\n')\n    f.close()\n    print (outfile2df)\n    f = open(outfile2df,'w')\n    f.write('# R.A., Dec., redshift, weight\\n')\n    for i in range(n2dfdat):\n      if (iphot2dfdat[i] > 0):\n        f.write('{} {} {:7.5f} {}'.format(ras2dfdat[i],dec2dfdat[i],red2dfdat[i],weimag2dfdat[i]) + '\\n')\n    f.close()\n  elif (opt == 4):\n    iphotcat,redcat,grcolcat,ricolcat,rmagcat,weimagcat = iphot2dfdat,red2dfdat,grcol2dfdat,ricol2dfdat,rmag2dfdat,weimag2dfdat\n    iphotref,redref,grcolref,ricolref,rmagref,weicompref = iphotbossdat,redbossdat,grcolbossdat,ricolbossdat,rmagbossdat,weicompbossdat\n#    iphotcat,redcat,grcolcat,ricolcat,rmagcat,weimagcat = iphotbossdat,redbossdat,grcolbossdat,ricolbossdat,rmagbossdat,weimagbossdat\n#    iphotref,redref,grcolref,ricolref,rmagref,weicompref = iphot2dfdat,red2dfdat,grcol2dfdat,ricol2dfdat,rmag2dfdat,weicomp2dfdat\n    cutref = (iphotref > 0)\n    cutcat = (iphotcat > 0)\n    norm = np.sum(weicompref[cutref])/np.sum(weimagcat[cutcat])\n    normed = False\n    label1,label2,label3 = 'ref','cat','cat weighted'\n    fig = plt.figure()\n    nrow,ncol = 2,2\n    sub = fig.add_subplot(nrow,ncol,1)\n    xmin,xmax = 0.5,2.5\n    sub.hist(grcolref[cutref],bins=100,range=[xmin,xmax],histtype='step',normed=normed,facecolor='None',edgecolor='black',label=label1)\n    sub.hist(grcolcat[cutcat],bins=100,range=[xmin,xmax],histtype='step',normed=normed,facecolor='None',edgecolor='red',label=label2)\n    sub.hist(grcolcat[cutcat],weights=norm*weimagcat[cutcat],bins=100,range=[xmin,xmax],histtype='step',normed=normed,facecolor='None',edgecolor='blue',label=label3)\n    sub.set_xlabel('g-r')\n    sub.set_xlim(xmin,xmax)\n    ymin,ymax = sub.get_ylim()\n    sub.set_ylim(0.,1.1*ymax)\n    plt.legend(prop={'size':10},loc=2)\n    sub = fig.add_subplot(nrow,ncol,2)\n    xmin,xmax = 0.,1.5\n    sub.hist(ricolref[cutref],bins=100,range=[xmin,xmax],histtype='step',normed=normed,facecolor='None',edgecolor='black',label=label1)\n    sub.hist(ricolcat[cutcat],bins=100,range=[xmin,xmax],histtype='step',normed=normed,facecolor='None',edgecolor='red',label=label2)\n    sub.hist(ricolcat[cutcat],weights=norm*weimagcat[cutcat],bins=100,range=[xmin,xmax],histtype='step',normed=normed,facecolor='None',edgecolor='blue',label=label3)\n    sub.set_xlabel('r-i')\n    sub.set_xlim(xmin,xmax)\n    ymin,ymax = sub.get_ylim()\n    sub.set_ylim(0.,1.1*ymax)\n    sub = fig.add_subplot(nrow,ncol,3)\n    xmin,xmax = 16.,23.\n    sub.set_xlabel('r')\n    sub.hist(rmagref[cutref],bins=100,range=[xmin,xmax],histtype='step',normed=normed,facecolor='None',edgecolor='black',label=label1)\n    sub.hist(rmagcat[cutcat],bins=100,range=[xmin,xmax],histtype='step',normed=normed,facecolor='None',edgecolor='red',label=label2)\n    sub.hist(rmagcat[cutcat],weights=norm*weimagcat[cutcat],bins=100,range=[xmin,xmax],histtype='step',normed=normed,facecolor='None',edgecolor='blue',label=label3)\n    sub.set_xlim(xmin,xmax)\n    ymin,ymax = sub.get_ylim()\n    sub.set_ylim(0.,1.1*ymax)\n    sub = fig.add_subplot(nrow,ncol,4)\n    xmin,xmax = zmin,zmax\n    sub.hist(redref[cutref],bins=100,range=[xmin,xmax],histtype='step',normed=normed,facecolor='None',edgecolor='black',label=label1)\n    sub.hist(redcat[cutcat],bins=100,range=[xmin,xmax],histtype='step',normed=normed,facecolor='None',edgecolor='red',label=label2)\n    sub.hist(redcat[cutcat],weights=norm*weimagcat[cutcat],bins=100,range=[xmin,xmax],histtype='step',normed=normed,facecolor='None',edgecolor='blue',label=label3)\n    sub.set_xlabel('Redshift')\n    sub.set_xlim(xmin,xmax)\n    ymin,ymax = sub.get_ylim()\n    sub.set_ylim(0.,1.1*ymax)\n    fig.tight_layout()\n    plt.show()\n    sys.exit()\n  elif (opt == 5):\n    wmin,wmax,nw = -0.1,5.1,100\n    wei1,lab1 = weicompbossdat,'BOSS completeness weight'\n    wei2,lab2 = weifkpbossdat,'BOSS FKP weight'\n    wei3,lab3 = weimagbossdat,'BOSS magnitude weight'\n#    wei1,lab1 = weicomp2dfdat,'2dFLenS completeness weight'\n#    wei2,lab2 = weifkp2dfdat,'2dFLenS FKP weight'\n#    wei3,lab3 = weimag2dfdat,'2dFLenS magnitude weight'\n#    wei1,lab1 = weicompbossran,'BOSS completeness weight'\n#    wei2,lab2 = weifkpbossran,'BOSS FKP weight'\n#    wei3,lab3 = weimagbossran,'BOSS magnitude weight'\n#    wei1,lab1 = weicomp2dfran,'2dFLenS completeness weight'\n#    wei2,lab2 = weifkp2dfran,'2dFLenS FKP weight'\n#    wei3,lab3 = weimag2dfran,'2dFLenS magnitude weight'\n    fig = plt.figure()\n    hist1,lims = np.histogram(wei1,bins=nw,range=[wmin,wmax],normed=True)\n    wcen = lims[:-1] + 0.5*(wmax-wmin)/nw\n    plt.plot(wcen,hist1,color='black',label=lab1)\n    hist2,lims = np.histogram(wei2,bins=nw,range=[wmin,wmax],normed=True)\n    plt.plot(wcen,hist2,color='red',label=lab2)\n    hist3,lims = np.histogram(wei3,bins=nw,range=[wmin,wmax],normed=True)\n    plt.plot(wcen,hist3,color='blue',label=lab3)\n    plt.xlabel('weight')\n    plt.ylabel('Frequency')\n    plt.legend()\n    plt.show()\n    sys.exit()\n  return\n\n#===================================\n# We're now ready to run the script with command line options\n# To do this in main we would need to define them as global\n\n# Read in user input to set the location of the input/output and the desired bin\nif len(sys.argv) <6: \n  print (\"Usage: %s lens_bin KiDS_Location KiDS_Version BOSS_Location 2dFLenS_Location Out_Directory\" % sys.argv[0]) \n  print (\"Example python3 makelenscats.py 1 /disk09/KIDS/KIDSCOLLAB_V1.0.0/K1000_CATALOGUES_PATCH/ rband_23_BRIGHT_v3.cat \\\n          /disk09/KIDS/K1000_TWO_PT_STATS/GGLCATS/BOSS_original /disk09/KIDS/K1000_TWO_PT_STATS/GGLCATS/2dFLenS_original \\\n          /disk09/KIDS/K1000_TWO_PT_STATS/GGLCATS\")\n  sys.exit(1)\nelse:\n  ired = int(sys.argv[1]) \n  KiDS_DIR = sys.argv[2]\n  KiDS_VER = sys.argv[3]\n  BOSS_DIR = sys.argv[4]\n  twodF_DIR = sys.argv[5]\n  OUTDIR = sys.argv[6]\n\n# Redshift bin for catalogues\n# These are fixed by the Sanchez et al paper and so\n# we hardwire these properties here\n#  ired #(1) 0.2-0.5 (2) 0.5-0.75 (3) overlap - 0.4-0.6 - not used\n\n# Generate the lens catalogues\nmakecats(ired)\n\n# Run test plots of the lens catalogues\n#  testcats(ired)\n", "meta": {"hexsha": "e975c9837f20a5b2067a7eae218ad378302d78a4", "size": 32334, "ext": "py", "lang": "Python", "max_stars_repo_path": "GGL_LensCats/makelenscats.py", "max_stars_repo_name": "KiDS-WL/Cat_to_Obs_K1000_P1", "max_stars_repo_head_hexsha": "0de7f79cab150416859ffe58ac2d0f5659aedb5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-11-18T12:58:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T08:54:29.000Z", "max_issues_repo_path": "GGL_LensCats/makelenscats.py", "max_issues_repo_name": "KiDS-WL/Cat_to_Obs_K1000_P1", "max_issues_repo_head_hexsha": "0de7f79cab150416859ffe58ac2d0f5659aedb5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GGL_LensCats/makelenscats.py", "max_forks_repo_name": "KiDS-WL/Cat_to_Obs_K1000_P1", "max_forks_repo_head_hexsha": "0de7f79cab150416859ffe58ac2d0f5659aedb5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-12-09T13:30:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T01:40:13.000Z", "avg_line_length": 45.605077574, "max_line_length": 165, "alphanum_fraction": 0.6755736995, "include": true, "reason": "import numpy,import scipy,import astropy,from astropy", "num_tokens": 11023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.17107061934264994}}
{"text": "# -----------------------------------------------------------------------------\n# ISC License\n#\n# Copyright (c) 2013--2017, librosa development team.\n#\n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n# -----------------------------------------------------------------------------\n\nimport typing\nfrom dataclasses import dataclass\n\nimport numpy as np\n\n\n@dataclass\nclass AudioSettings:\n    \"\"\"Settings for mel denormalization\"\"\"\n\n    # STFT settings\n    filter_length: int = 1024\n    hop_length: int = 256\n    win_length: int = 256\n    mel_channels: int = 80\n    sample_rate: int = 22050\n    sample_bytes: int = 2\n    channels: int = 1\n    mel_fmin: float = 0.0\n    mel_fmax: typing.Optional[float] = 8000.0\n    ref_level_db: float = 20.0\n    spec_gain: float = 1.0\n\n    # Normalization\n    signal_norm: bool = False\n    min_level_db: float = -100.0\n    max_norm: float = 4.0\n    clip_norm: bool = True\n    symmetric_norm: bool = True\n    do_dynamic_range_compression: bool = True\n    convert_db_to_amp: bool = True\n\n    # -------------------------------------------------------------------------\n    # Mel Spectrogram\n    # -------------------------------------------------------------------------\n\n    def amp_to_db(self, mel_amp: np.ndarray) -> np.ndarray:\n        return self.spec_gain * np.log10(np.maximum(1e-5, mel_amp))\n\n    def db_to_amp(self, mel_db: np.ndarray) -> np.ndarray:\n        return np.power(10.0, mel_db / self.spec_gain)\n\n    # -------------------------------------------------------------------------\n    # Normalization\n    # -------------------------------------------------------------------------\n\n    def normalize(self, mel_db: np.ndarray) -> np.ndarray:\n        \"\"\"Put values in [0, max_norm] or [-max_norm, max_norm]\"\"\"\n        mel_norm = ((mel_db - self.ref_level_db) - self.min_level_db) / (\n            -self.min_level_db\n        )\n        if self.symmetric_norm:\n            # Symmetric norm\n            mel_norm = ((2 * self.max_norm) * mel_norm) - self.max_norm\n            if self.clip_norm:\n                mel_norm = np.clip(mel_norm, -self.max_norm, self.max_norm)\n        else:\n            # Asymmetric norm\n            mel_norm = self.max_norm * mel_norm\n            if self.clip_norm:\n                mel_norm = np.clip(mel_norm, 0, self.max_norm)\n\n        return mel_norm\n\n    def denormalize(self, mel_db: np.ndarray) -> np.ndarray:\n        \"\"\"Pull values out of [0, max_norm] or [-max_norm, max_norm]\"\"\"\n        if self.symmetric_norm:\n            # Symmetric norm\n            if self.clip_norm:\n                mel_denorm = np.clip(mel_db, -self.max_norm, self.max_norm)\n\n            mel_denorm = (\n                (mel_denorm + self.max_norm) * -self.min_level_db / (2 * self.max_norm)\n            ) + self.min_level_db\n        else:\n            # Asymmetric norm\n            if self.clip_norm:\n                mel_denorm = np.clip(mel_db, 0, self.max_norm)\n\n            mel_denorm = (\n                mel_denorm * -self.min_level_db / self.max_norm\n            ) + self.min_level_db\n\n        mel_denorm += self.ref_level_db\n\n        return typing.cast(np.ndarray, mel_denorm)\n\n    def dynamic_range_compression(self, x, C=1, clip_val=1e-5):\n        \"\"\"Compression function from hifi-gan training\"\"\"\n        return np.log(np.clip(x, a_min=clip_val, a_max=None) * C)\n\n    def dynamic_range_decompression(self, x, C=1):\n        \"\"\"Decompression function from hifi-gan training\"\"\"\n        return np.exp(x) / C\n\n\n# -----------------------------------------------------------------------------\n\n\ndef audio_float_to_int16(\n    audio: np.ndarray, max_wav_value: float = 32767.0\n) -> np.ndarray:\n    \"\"\"Normalize audio and convert to int16 range\"\"\"\n    audio_norm = audio * (max_wav_value / max(0.01, np.max(np.abs(audio))))\n    audio_norm = np.clip(audio_norm, -max_wav_value, max_wav_value)\n    audio_norm = audio_norm.astype(\"int16\")\n    return audio_norm\n\n\n# -----------------------------------------------------------------------------\n\n\ndef mel_basis(sr, n_fft, n_mels=80, fmin=0.0, fmax=None, dtype=np.float32):\n\n    if fmax is None:\n        fmax = float(sr) / 2\n\n    # Initialize the weights\n    n_mels = int(n_mels)\n    weights = np.zeros((n_mels, int(1 + n_fft // 2)), dtype=dtype)\n\n    # Center freqs of each FFT bin\n    fftfreqs = fft_frequencies(sr=sr, n_fft=n_fft)\n\n    # 'Center freqs' of mel bands - uniformly spaced between limits\n    mel_f = mel_frequencies(n_mels + 2, fmin=fmin, fmax=fmax)\n\n    fdiff = np.diff(mel_f)\n    ramps = np.subtract.outer(mel_f, fftfreqs)  # pylint: disable=no-member\n\n    for i in range(n_mels):\n        # lower and upper slopes for all bins\n        lower = -ramps[i] / fdiff[i]\n        upper = ramps[i + 2] / fdiff[i + 1]\n\n        # .. then intersect them with each other and zero\n        weights[i] = np.maximum(0, np.minimum(lower, upper))\n\n    # Slaney-style mel is scaled to be approx constant energy per channel\n    enorm = 2.0 / (mel_f[2 : n_mels + 2] - mel_f[:n_mels])\n    weights *= enorm[:, np.newaxis]\n\n    return weights\n\n\ndef dynamic_range_decompression(x, C=1):\n    return np.exp(x) / C\n\n\ndef mel_frequencies(n_mels=128, fmin=0.0, fmax=11025.0):\n    # 'Center freqs' of mel bands - uniformly spaced between limits\n    min_mel = hz_to_mel(fmin)\n    max_mel = hz_to_mel(fmax)\n\n    mels = np.linspace(min_mel, max_mel, n_mels)\n\n    return mel_to_hz(mels)\n\n\ndef fft_frequencies(sr=22050, n_fft=2048):\n    return np.linspace(0, float(sr) / 2, int(1 + n_fft // 2), endpoint=True)\n\n\ndef hz_to_mel(frequencies):\n    frequencies = np.asanyarray(frequencies)\n\n    # Fill in the linear part\n    f_min = 0.0\n    f_sp = 200.0 / 3\n\n    mels = (frequencies - f_min) / f_sp\n\n    # Fill in the log-scale part\n\n    min_log_hz = 1000.0  # beginning of log region (Hz)\n    min_log_mel = (min_log_hz - f_min) / f_sp  # same (Mels)\n    logstep = np.log(6.4) / 27.0  # step size for log region\n\n    if frequencies.ndim:\n        # If we have array data, vectorize\n        log_t = frequencies >= min_log_hz\n        mels[log_t] = min_log_mel + np.log(frequencies[log_t] / min_log_hz) / logstep\n    elif frequencies >= min_log_hz:\n        # If we have scalar data, heck directly\n        mels = min_log_mel + np.log(frequencies / min_log_hz) / logstep\n\n    return mels\n\n\ndef mel_to_hz(mels):\n    mels = np.asanyarray(mels)\n\n    # Fill in the linear scale\n    f_min = 0.0\n    f_sp = 200.0 / 3\n    freqs = f_min + f_sp * mels\n\n    # And now the nonlinear scale\n    min_log_hz = 1000.0  # beginning of log region (Hz)\n    min_log_mel = (min_log_hz - f_min) / f_sp  # same (Mels)\n    logstep = np.log(6.4) / 27.0  # step size for log region\n\n    if mels.ndim:\n        # If we have vector data, vectorize\n        log_t = mels >= min_log_mel\n        freqs[log_t] = min_log_hz * np.exp(logstep * (mels[log_t] - min_log_mel))\n    elif mels >= min_log_mel:\n        # If we have scalar data, check directly\n        freqs = min_log_hz * np.exp(logstep * (mels - min_log_mel))\n\n    return freqs\n\n\ndef stft(x, fft_size, hopsamp):\n    \"\"\"Compute and return the STFT of the supplied time domain signal x.\n    Args:\n        x (1-dim Numpy array): A time domain signal.\n        fft_size (int): FFT size. Should be a power of 2, otherwise DFT will be used.\n        hopsamp (int):\n    Returns:\n        The STFT. The rows are the time slices and columns are the frequency bins.\n    \"\"\"\n    window = np.hanning(fft_size)\n    fft_size = int(fft_size)\n    hopsamp = int(hopsamp)\n    return np.array(\n        [\n            np.fft.rfft(window * x[i : i + fft_size])\n            for i in range(0, len(x) - fft_size, hopsamp)\n        ]\n    )\n\n\ndef istft(X, fft_size, hopsamp):\n    \"\"\"Invert a STFT into a time domain signal.\n    Args:\n        X (2-dim Numpy array): Input spectrogram. The rows are the time slices and columns are the frequency bins.\n        fft_size (int):\n        hopsamp (int): The hop size, in samples.\n    Returns:\n        The inverse STFT.\n    \"\"\"\n    fft_size = int(fft_size)\n    hopsamp = int(hopsamp)\n    window = np.hanning(fft_size)\n    time_slices = X.shape[0]\n    len_samples = int(time_slices * hopsamp + fft_size)\n    x = np.zeros(len_samples)\n    for n, i in enumerate(range(0, len(x) - fft_size, hopsamp)):\n        x[i : i + fft_size] += window * np.real(np.fft.irfft(X[n]))\n    return x\n\n\ndef inverse(magnitude, phase):\n    recombine_magnitude_phase = np.concatenate(\n        [magnitude * np.cos(phase), magnitude * np.sin(phase)], axis=1\n    )\n\n    x_org = recombine_magnitude_phase\n    n_b, n_f, n_t = x_org.shape  # pylint: disable=unpacking-non-sequence\n    x = np.empty([n_b, n_f // 2, n_t], dtype=np.complex64)\n    x.real = x_org[:, : n_f // 2]\n    x.imag = x_org[:, n_f // 2 :]\n    inverse_transform = []\n    for y in x:\n        y_ = istft(y.T, fft_size=1024, hopsamp=256)\n        inverse_transform.append(y_[None, :])\n\n    inverse_transform = np.concatenate(inverse_transform, 0)\n\n    return inverse_transform\n\n\ndef transform(input_data):\n    x = input_data\n    real_part = []\n    imag_part = []\n    for y in x:\n        y_ = stft(y, fft_size=1024, hopsamp=256).T\n        real_part.append(y_.real[None, :, :])  # pylint: disable=unsubscriptable-object\n        imag_part.append(y_.imag[None, :, :])  # pylint: disable=unsubscriptable-object\n    real_part = np.concatenate(real_part, 0)\n    imag_part = np.concatenate(imag_part, 0)\n\n    magnitude = np.sqrt(real_part ** 2 + imag_part ** 2)\n    phase = np.arctan2(imag_part.data, real_part.data)\n\n    return magnitude, phase\n", "meta": {"hexsha": "573ad07673dddb91057425466ed6d3f495063adb", "size": 10127, "ext": "py", "lang": "Python", "max_stars_repo_path": "larynx/audio.py", "max_stars_repo_name": "fquirin/larynx", "max_stars_repo_head_hexsha": "bc586b60f11dc2c228e07a47736e7a54597f0ad1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 540, "max_stars_repo_stars_event_min_datetime": "2020-10-31T21:39:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T23:16:03.000Z", "max_issues_repo_path": "larynx/audio.py", "max_issues_repo_name": "fquirin/larynx", "max_issues_repo_head_hexsha": "bc586b60f11dc2c228e07a47736e7a54597f0ad1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2020-11-26T10:02:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T05:16:27.000Z", "max_forks_repo_path": "larynx/audio.py", "max_forks_repo_name": "fquirin/larynx", "max_forks_repo_head_hexsha": "bc586b60f11dc2c228e07a47736e7a54597f0ad1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 37, "max_forks_repo_forks_event_min_datetime": "2021-01-23T16:41:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T05:41:55.000Z", "avg_line_length": 32.986970684, "max_line_length": 114, "alphanum_fraction": 0.5982028241, "include": true, "reason": "import numpy", "num_tokens": 2728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.31069438959712015, "lm_q1q2_score": 0.1710706193426499}}
{"text": "\nimport os\nimport sys\nimport numpy as np\nimport warnings\n\nfrom sph import sph\nfrom smart_dict import SmartDict\nfrom vector import Vector, KVector\nfrom safe_open import safe_open\n\n__author__ = 'Johan G. McQuillan'\n__email__ = 'johan.mcquillan.13@ucl.ac.uk'\n\n\nclass Cell(object):\n    \"\"\"Simulation cell which holds Atom objects in a 3D mesh.\n\n    All lengths measured in Bohr radii (a0).\n    All energies measured in electron volts (eV).\n    \n    Attributes:\n        name (string): Name of simulation; used for plot titles\n        fermi_level (float): Fermi Level of simulation\n        vector (Vector): Vector from origin to far corner of cell.\n            Components are maximum lengths of cell in each dimension\n        grid_spacing (float): Resolution of mesh points\n        real_mesh (array(float)): Mesh of real space; [i, j, k] returns np.array([x, y, z])\n        atoms ({int : Atom}): Atom objects of simulation indexed by atom number\n        bands ({Vector : [float]}): List of band energies indexed by k-point vector\n        support_mesh (array(SmartDict)): Mesh of support function values.\n            Indexed by [i, j, k][atom_key][l][zeta][m]\n    \"\"\"\n\n    BOLTZMANN = 8.6173303E-5        # Boltzmann's Constant in eV/K\n    ELECTRON_MASS = 9.10938E-31     # Electron Mass in kg\n    H_BAR = 4.135667662E-15         # Reduced Planck's Constant in eV.s\n    DELTA_S_FACTOR = 2              # Default delta S given by minimum delta S scaled by this factor\n\n    MESH_FOLDER = 'meshes'          # Folder to save mesh files\n    SUPPORT_FNAME = 'supp'          # Prefix for support mesh files\n    LDOS_FNAME = 'ldos'             # Prefix for summed LDOS files\n    PSI_FNAME = 'psi'               # Prefix for wavefunction files\n    PROP_PSI_FNAME = 'prop'         # Prefix for propagated wavefunction files\n    CURRENT_FNAME = 'current'       # Prefix for current files\n    EXT = 'dat'                     # Mesh file extension\n\n    PRINT_RELATIVE_TO_EF = True     # Print energies as absolute or relative to Fermi level\n    PROG_BAR_INTERVALS = 20         # Number of intervals in debug progress bar\n    PROG_BAR_CHARACTER = '>'\n\n    def __init__(self, name, fermi_level, x_length, y_length, z_length,\n                 grid_spacing=0.5, group_size=400):\n        \"\"\"Constructs 3D cell with given dimensional.\n\n        All lengths measured in Bohr radii (a0);\n        All energies measured in Hartrees (Ha).\n\n        Args:\n            name (string): Name of simulation; used for plot titles.\n            fermi_level (float): Fermi Level of simulation.\n            x_length (float): Length of cell along x.\n            y_length (float): Length of cell along y.\n            z_length (float): Length of cell along z.\n            grid_spacing (float, opt): Resolution of mesh points.\n            group_size (int, opt): Maximum number of atoms to be saved to same support file.\n        \"\"\"\n\n        self.name = name\n        self.fermi_level = fermi_level\n        self.grid_spacing = grid_spacing\n        self.atom_group_size = group_size\n\n        vector_x = int(x_length / grid_spacing) * grid_spacing\n        vector_y = int(y_length / grid_spacing) * grid_spacing\n        vector_z = int(z_length / grid_spacing) * grid_spacing\n        self.vector = Vector(vector_x, vector_y, vector_z)\n\n        # Initialise Cartesian meshes\n        self.real_mesh = np.transpose(np.mgrid[0:x_length:grid_spacing,\n                                               0: y_length: grid_spacing, 0:\n                                               z_length: grid_spacing],\n                                      (1, 2, 3, 0))\n\n        # Total number of mesh points\n        self.mesh_points = self.real_mesh.size\n\n        # Initialise atoms and bands\n        self.atoms = {}\n        self.bands = {}\n\n        # Currently support function mesh\n        self.support_mesh = None\n        # Support meshes are split into groups, each with self.group_size atoms\n        # For number of atoms > 400, storing mesh for all atoms takes huge amounts of RAM\n        # First group is 0, second is 1 etc.\n        # -1 indicates no group stored\n        self.current_group = -1  # Current atom group stored\n\n        self.default_delta_s = self.delta_s()  # Default delta_s\n\n        # Vectorised method to calculate wavefunction\n        self.psi_vec = np.vectorize(self.calculate_psi_grid_vec)\n\n    def energy_list(self):\n        \"\"\"Return sorted list of energies from all k-points.\"\"\"\n        \n        energies = []\n        for K in self.bands:\n            energies.extend(self.bands[K])\n        return sorted(energies)\n\n    def has_band(self, K, E):\n        \"\"\"Check if cell stores specified band.\n\n        Args:\n            K (Vector): 3D Cartesian k-space vector.\n            E (float): Band energy.\n        \"\"\"\n        \n        return K in self.bands and E in self.bands[K]\n\n    def add_atom(self, atom, atom_key):\n        \"\"\"Add atom to self.atoms, indexed by atom_key.\n\n        Args:\n            atom (Atom): Atom object.\n            atom_key (int): Atom number, as given in Conquest_out.\n        \"\"\"\n        \n        # Add atom to dict\n        self.atoms[atom_key] = atom\n\n        # Add band energies and k-points to self.bands\n        for K in atom.bands:\n            # If cell does not have k-point, create empty band energy list\n            if K not in self.bands:\n                self.bands[K] = []\n                \n            # Add band energies to k-point\n            for E in atom.bands[K]:\n                if E not in self.bands[K]:\n                    self.bands[K].append(E)\n                    \n            # Sort energy list\n            self.bands[K] = sorted(self.bands[K])\n\n    def fermi_dirac(self, energy, temperature):\n        \"\"\"Calculate Fermi-Dirac occupation factor.\n\n        Args:\n            energy (float): Energy in eV.\n            temperature (float): Absolute temperature in K.\n\n        Returns:\n            float: Occupation factor, between 0 and 1.\n        \"\"\"\n        \n        with warnings.catch_warnings():\n            # Suppress RuntimeWarning from overflow and underflow in np.exp\n            warnings.simplefilter('ignore', RuntimeWarning)\n            f = 1.0 / (np.exp((energy - self.fermi_level) / (self.BOLTZMANN * temperature)) + 1)\n        return f\n\n    def bias_to_energy_range(self, V):\n        \"\"\"Return absolute energy range from the Fermi level to the bias voltage.\"\"\"\n        \n        if V > 0:\n            min_E = self.fermi_level\n            max_E = self.fermi_level + V\n        else:\n            min_E = self.fermi_level + V\n            max_E = self.fermi_level\n        return min_E, max_E\n\n    def get_nearest_mesh_value(self, x, points=None):\n        \"\"\"Return nearest mesh point to x. Not constrained to lie within simulation cell.\n\n        Args:\n            x (float): Value in a0 to find nearest point; Works for x, y, and z dimensions.\n            points (float, opt): Number of points in cell dimension.\n                If given, will return mesh index of the found point\n\n        Returns:\n            float: Nearest mesh point value\n            int: Index of mesh point; only given if points argument is specified\n        \"\"\"\n        \n        # Get quotient and remainder wrt grid spacing\n        div_x, mod_x = divmod(x, self.grid_spacing)\n        \n        # Check if x should be rounded up or down\n        if mod_x >= self.grid_spacing / 2:\n            div_x += 1\n            \n        # Get new point\n        new_x = div_x * self.grid_spacing\n        if points is not None:\n            i = div_x - 1\n            while i < 0:\n                i += points\n            while i >= points:\n                i -= points\n            return new_x, int(i)\n        else:\n            return new_x\n\n    def constrain_relative_vector(self, vector):\n        \"\"\"Using periodic boundaries, return smallest Vector that is equivalent to input Vector.\"\"\"\n        \n        x, y, z = vector.components\n\n        # Check if vector components are greater than half of cell sides\n        # If greater, add or subtract cell length\n\n        while x > self.vector.x / 2:\n            x -= self.vector.x\n        while x <= -self.vector.x / 2:\n            x += self.vector.x\n\n        while y > self.vector.y / 2:\n            y -= self.vector.y\n        while y <= -self.vector.y / 2:\n            y += self.vector.y\n\n        while z > self.vector.z / 2:\n            z -= self.vector.z\n        while z <= -self.vector.z / 2:\n            z += self.vector.z\n\n        return Vector(x, y, z)\n\n    def calculate_support_group(self, group, interpolation='cubic', debug=False):\n        \"\"\"Evaluate support function for each PAO for a given atom group.\n\n        Args:\n            group (int): Atom group\n            interpolation (string, opt): Method of interpolation.\n                Possible arguments are 'linear', 'quadratic', 'cubic'.\n            debug (bool, opt): If true, print extra information during runtime.\n\n        Returns:\n            array(SmartDict): Mesh of support function values.\n                Indexed by [x, y, z][atom_key][l][zeta][m]\n        \"\"\"\n        \n        if debug:\n            sys.stdout.write('Calculating support mesh for atom group {}\\n'.format(group))\n            sys.stdout.flush()\n        \n        # Initialise support grid\n        support_grid = np.empty(self.real_mesh.shape[:3], dtype=SmartDict)\n\n        # Get first and last atom numbers for this group\n        lower_bound = group * self.atom_group_size\n        upper_bound = (group + 1) * self.atom_group_size\n\n        # Get atom keys for group\n        atom_list = sorted([a for a in self.atoms.keys() if lower_bound <= a < upper_bound])\n\n        # Iterate over atoms\n        for atom_key in atom_list:\n            atom = self.atoms[atom_key]\n\n            debug_str = '  Support grid for atom {:3} - {!s}: '.format(atom_key, atom.ion_name)\n            if debug:\n                sys.stdout.write(debug_str)\n                sys.stdout.flush()\n\n            # Get atom cutoff radius\n            cut = atom.get_max_cutoff()\n\n            # Get mesh points of maximum range of atoms orbitals in each direction\n            x_lower_lim, i_start = self.get_nearest_mesh_value(atom.atom_pos.x - cut,\n                                                               points=self.real_mesh.shape[0])\n            x_upper_lim = self.get_nearest_mesh_value(atom.atom_pos.x + cut) + self.grid_spacing\n            y_lower_lim, j_start = self.get_nearest_mesh_value(atom.atom_pos.y - cut,\n                                                               points=self.real_mesh.shape[1])\n            y_upper_lim = self.get_nearest_mesh_value(atom.atom_pos.y + cut) + self.grid_spacing\n            z_lower_lim, k_start = self.get_nearest_mesh_value(atom.atom_pos.z - cut,\n                                                               points=self.real_mesh.shape[2])\n            z_upper_lim = self.get_nearest_mesh_value(atom.atom_pos.z + cut) + self.grid_spacing\n\n            # Get array of mesh points within cutoff\n            local_mesh = np.transpose(np.mgrid[x_lower_lim:x_upper_lim:self.grid_spacing,\n                                               y_lower_lim:y_upper_lim:self.grid_spacing,\n                                               z_lower_lim:z_upper_lim:self.grid_spacing],\n                                      (1, 2, 3, 0))\n            lm_shape = local_mesh.shape[:3]\n\n            # Progress bar initialisation\n            points_done = 0\n            bars_done = 0\n            total_points = local_mesh.shape[0]*local_mesh.shape[1]*local_mesh.shape[2]\n\n            # The local mesh may exist over the periodic boundaries\n            # Roll the full support mesh such the [0, 0, 0] entry corresponds\n            #   physically to the same point as the [0, 0, 0] point on the local mesh\n            rolled_mesh = np.roll(support_grid, -i_start, 0)\n            rolled_mesh = np.roll(rolled_mesh, -j_start, 1)\n            rolled_mesh = np.roll(rolled_mesh, -k_start, 2)\n\n            # Extract the part of the full support mesh that corresponds to\n            #   the same physical space as the local mesh\n            partial_mesh = rolled_mesh[0:lm_shape[0], 0:lm_shape[1], 0:lm_shape[2]]\n\n            # Iterate over the local mesh\n            for local_ijk in np.ndindex(lm_shape):\n                position = local_mesh[local_ijk]\n                r = Vector(*position)\n\n                # Find the shortest Vector between r and atom_pos using periodic boundaries\n                relative_position = self.constrain_relative_vector(r - atom.atom_pos)\n\n                # Convert indices of local mesh point from tuple into a list\n                partial_ijk_list = list(local_ijk)\n                for i in range(len(partial_ijk_list)):\n                    # If point is outside boundary, reduce to lie within cell\n                    if partial_ijk_list[i] >= self.real_mesh.shape[i]:\n                        partial_ijk_list[i] -= self.real_mesh.shape[i]\n                \n                # Convert back to tuple\n                partial_ijk = tuple(partial_ijk_list)\n\n                # Iterate over orbitals\n                for l in atom.radials:\n                    for zeta in atom.radials[l]:\n                        # Get radial part of wavefunction\n                        R = atom.get_radial_value_relative(l, zeta, relative_position,\n                                                           interpolation=interpolation)\n\n                        # If R == 0, do not store\n                        if R != 0.0:\n                            for m in range(-l, l + 1):\n                                # Get spherical harmonic\n                                Y = sph(l, m, relative_position)\n\n                                # Initialise support mesh entry\n                                if partial_mesh[partial_ijk] is None:\n                                    partial_mesh[partial_ijk] = SmartDict()\n\n                                if m not in partial_mesh[partial_ijk][atom_key][l][zeta]:\n                                    partial_mesh[partial_ijk][atom_key][l][zeta][m] = 0.0\n\n                                # Store support function value\n                                partial_mesh[partial_ijk][atom_key][l][zeta][m] += R * Y\n                points_done += 1\n\n                # Update progress bar\n                prog = float(points_done) / total_points\n                if debug and prog * self.PROG_BAR_INTERVALS >= bars_done:\n                    percent = prog * 100\n                    sys.stdout.write('\\r')\n                    sys.stdout.write(debug_str)\n                    sys.stdout.write(\n                        ' [{:<{}}]'.format(self.PROG_BAR_CHARACTER * bars_done,\n                                           self.PROG_BAR_INTERVALS))\n                    sys.stdout.write(' {:3.0f}%'.format(percent))\n                    sys.stdout.flush()\n                    bars_done += 1\n\n            # Copy partial support mesh into full support mesh\n            rolled_mesh[0:lm_shape[0], 0:lm_shape[1], 0:lm_shape[2]] = partial_mesh\n\n            # Roll mesh back to original position\n            rolled_mesh = np.roll(rolled_mesh, i_start, 0)\n            rolled_mesh = np.roll(rolled_mesh, j_start, 1)\n            support_grid = np.roll(rolled_mesh, k_start, 2)\n\n            if debug:\n                sys.stdout.write('\\n')\n                sys.stdout.flush()\n\n        return support_grid\n\n    def support_group_filename(self, group):\n        \"\"\"Return standardised filename for relevant support function file.\"\"\"\n        \n        return os.path.join(self.MESH_FOLDER, '{}_{}_{}_{}_{}.{}'.format(\n                self.SUPPORT_FNAME, self.name, self.grid_spacing, self.atom_group_size, group,\n                self.EXT))\n\n    def write_support_group(self, group, support_mesh, debug=False):\n        \"\"\"Write support function group to file.\"\"\"\n        \n        filename = self.support_group_filename(group)\n        support_file = safe_open(filename, 'w')\n\n        if debug:\n            sys.stdout.write('Writing support group to {}: '.format(filename))\n            sys.stdout.flush()\n        points_done = 0\n        bars_done = 0\n\n        # Iterate over mesh points\n        for ijk in np.ndindex(self.real_mesh.shape[:3]):\n            i, j, k = ijk\n\n            # If support function values exist at mesh point\n            if support_mesh[ijk]:\n                support_file.write('{} {} {}\\n'.format(i, j, k))\n\n                # Iterate over atoms\n                for atom_key in support_mesh[ijk]:\n                    # Write atom index\n                    support_file.write('{}\\n'.format(atom_key))\n\n                    # Iterate over orbitals\n                    for l in support_mesh[ijk][atom_key]:\n                        for zeta in support_mesh[ijk][atom_key][l]:\n                            for m in support_mesh[ijk][atom_key][l][zeta]:\n                                # Write orbital data\n                                support_file.write('{} {} {} {}\\n'.format(\n                                    l, zeta, m, support_mesh[ijk][atom_key][l][zeta][m]))\n\n            # Update progress bar\n            points_done += 1\n            if debug and float(points_done) / self.mesh_points*self.PROG_BAR_INTERVALS > bars_done:\n                sys.stdout.write('\\r')\n                sys.stdout.write(' [{:<{}}]'.format(self.PROG_BAR_CHARACTER * bars_done,\n                                                    self.PROG_BAR_INTERVALS))\n                sys.stdout.flush()\n                bars_done += 1\n\n        if debug:\n            sys.stdout.write('\\n')\n            sys.stdout.flush()\n        support_file.close()\n\n    def read_support_group(self, group, debug=False):\n        \"\"\"Read support function group from file.\"\"\"\n        \n        filename = self.support_group_filename(group)\n        support_file = open(filename, 'r')\n        support_mesh = np.empty(self.real_mesh.shape[:3], dtype=SmartDict)\n\n        if debug:\n            sys.stdout.write('Reading support group from {}\\n'.format(filename))\n            sys.stdout.flush()\n\n        # Iterate over file lines\n        end_of_file = False\n        line = support_file.next()\n        line_split = line.split()\n        while not end_of_file:\n            try:\n                # Get mesh indices\n                i, j, k = [int(a) for a in line_split[:3]]\n\n                # Read atom data\n                reading_atoms = True\n                line = support_file.next()\n                line_split = line.split()\n                while reading_atoms:\n                    if len(line_split) == 1:\n                        # Get atom index\n                        atom_key = int(line)\n                        # Read orbital data\n                        reading_orbitals = True\n                        while reading_orbitals:\n                            line = support_file.next()\n                            line_split = line.split()\n                            if len(line_split) != 4:\n                                reading_orbitals = False\n                            elif len(line_split) == 1:\n                                reading_atoms = True\n                            else:\n                                l = int(line_split[0])\n                                zeta = int(line_split[1])\n                                m = int(line_split[2])\n                                value = float(line_split[3])\n                                if support_mesh[i, j, k] is None:\n                                    support_mesh[i, j, k] = SmartDict()\n                                support_mesh[i, j, k][atom_key][l][zeta][m] = value\n                    else:\n                        reading_atoms = False\n            except StopIteration:\n                end_of_file = True\n        if debug:\n            sys.stdout.write('Support grid successfully read\\n')\n            sys.stdout.flush()\n        return support_mesh\n\n    def get_support_group(self, group, recalculate=False, interpolation='cubic', debug=False):\n        \"\"\"Get support function mesh for given atom group.\n\n        If it is already stored in a file and recalculate is False, then it will read from file.\n        Otherwise, it will calculate support functions.\n\n        Args:\n            group (int): Atom group\n            recalculate (bool, opt): Force recalculation, even if already stored.\n            interpolation (string, opt): Method of interpolation.\n                Possible arguments are 'linear', 'quadratic', 'cubic'.\n            debug (bool, opt): Print extra information during runtime.\n\n        Returns:\n            array(SmartDict): Mesh of support function values.\n                Indexed by [i, j, k][atom_key][l][zeta][m].\n        \"\"\"\n        \n        # Check if support function group is already stored in field\n        if group == self.current_group and self.support_mesh is not None:\n            return self.support_mesh\n        else:\n            if not recalculate and os.path.isfile(self.support_group_filename(group)):\n                # Read support grid from file\n                support_mesh = self.read_support_group(group, debug=debug)\n            else:\n                # Recalculate support grid\n                support_mesh = self.calculate_support_group(group, interpolation=interpolation,\n                                                            debug=debug)\n                # Write to file\n                self.write_support_group(group, support_mesh, debug=debug)\n            self.current_group = group\n            self.support_mesh = support_mesh\n            return support_mesh\n\n    def calculate_psi_grid_vec(self, support_dict, atom_key, l, zeta, m, coefficient):\n        \"\"\"Calculate wavefunction contribution from a point of the support function mesh\n        for a given orbital and atom.\"\"\"\n        \n        if (support_dict is not None and atom_key in support_dict and l in support_dict[atom_key]\n                and zeta in support_dict[atom_key][l] and m in support_dict[atom_key][l][zeta]):\n            psi = coefficient * support_dict[atom_key][l][zeta][m]\n        else:\n            psi = complex(0, 0)\n        return psi\n\n    def calculate_psi_grid(self, K, E, recalculate=False, vectorised=True, interpolation='cubic',\n                           debug=False):\n        \"\"\"Evaluate wavefunction over the mesh for a given k-point and energy.\n\n        Args:\n            K (KVector): K-point Vector.\n            E (float): Band energy.\n            recalculate (bool, opt): Force recalculation, even if already stored.\n            vectorised (bool, opt): If true, use NumPy vectorisation.\n            interpolation (string, opt): Method of interpolation.\n                Possible arguments are 'linear', 'quadratic', 'cubic'\n            debug (bool, opt): Print extra information during runtime.\n\n        Returns:\n            array(complex): Mesh of complex wavefunction values.\n        \"\"\"\n\n        # Initialise progress bar\n        atoms_done = 0\n        total_atoms = len(self.atoms)\n        bars_done = 0\n\n        # Initialise wavefunction mesh\n        psi_grid = np.zeros_like(self.real_mesh[..., 0], dtype=complex)\n\n        # Print debug info\n        if self.PRINT_RELATIVE_TO_EF:\n            E_str = '{} eV'.format(E - self.fermi_level)\n        else:\n            E_str = '{} eV'.format(E)\n        debug_str = 'Calculating psi(r) at k = {}, E = {}:\\n'.format(K, E_str)\n        if debug:\n            sys.stdout.write(debug_str)\n            sys.stdout.flush()\n\n        # Iterate over all atoms\n        previous_group = 0\n        support_grid = self.get_support_group(0, recalculate=recalculate, debug=debug)\n        for atom_key in sorted(self.atoms.iterkeys()):\n            atom = self.atoms[atom_key]\n            group = atom_key / self.atom_group_size\n\n            # Check if current atom group is the one currently read from file\n            if group != previous_group:\n                support_grid = self.get_support_group(group, recalculate=recalculate,\n                                                      interpolation=interpolation, debug=debug)\n                previous_group = group\n\n            # Iterate over orbitals\n            for l in atom.bands[K][E]:\n                for zeta in atom.bands[K][E][l]:\n                    for m in atom.bands[K][E][l][zeta]:\n                        # Evaluate wavefunction contribution over mesh\n                        coefficient = atom.get_coefficient(K, E, l, zeta, m)\n                        if vectorised:\n                            psi_grid += self.psi_vec(support_grid, atom_key, l, zeta, m, coefficient)\n                        else:\n                            for ijk in np.ndindex(self.real_mesh.shape[:3]):\n                                if support_grid[ijk]:\n                                    if atom_key in support_grid[ijk]:\n                                        psi_grid[ijk] += coefficient*support_grid[ijk][atom_key][l][zeta][m]\n            # Update progress bar\n            atoms_done += 1\n            prog = float(atoms_done) / total_atoms\n            if debug and prog * self.PROG_BAR_INTERVALS >= bars_done:\n                percent = prog * 100\n                sys.stdout.write('\\r')\n                sys.stdout.write(' [{:<{}}]'.format(self.PROG_BAR_CHARACTER * bars_done,\n                                                    self.PROG_BAR_INTERVALS))\n                sys.stdout.write(' {:3.0f}%'.format(percent))\n                sys.stdout.flush()\n                bars_done = int(prog * self.PROG_BAR_INTERVALS)\n        if debug:\n            sys.stdout.write('\\n')\n            sys.stdout.flush()\n        return psi_grid\n\n    def psi_filename(self, K, E):\n        \"\"\"Return standardised filename for relevant wavefunction file.\"\"\"\n        \n        return os.path.join(self.MESH_FOLDER, '{}_{}_{}_{}_{}_{}_{}.{}'.format(\n                self.PSI_FNAME, self.name, self.grid_spacing, K.x, K.y, K.z, E, self.EXT))\n\n    def write_psi_grid(self, psi_grid, K, E):\n        \"\"\"Write wavefunction function mesh to file.\"\"\"\n        \n        filename = self.psi_filename(K, E)\n        psi_file = safe_open(filename, 'w')\n        for ijk in np.ndindex(self.real_mesh.shape[:3]):\n            i, j, k = ijk\n            if psi_grid[ijk] != 0:\n                psi = psi_grid[ijk]\n                psi_file.write('{} {} {} {} {}\\n'.format(i, j, k, psi.real, psi.imag))\n        psi_file.close()\n\n    def read_psi_grid(self, K, E, debug=False):\n        \"\"\"Read wavefunction mesh from file.\"\"\"\n        \n        filename = self.psi_filename(K, E)\n        psi_file = open(filename, 'r')\n        psi_grid = np.zeros_like(self.real_mesh[..., 0], dtype=complex)\n\n        if debug:\n            if self.PRINT_RELATIVE_TO_EF:\n                E_str = '{} eV'.format(E - self.fermi_level)\n            else:\n                E_str = '{} eV'.format(E)\n            sys.stdout.write('Reading psi(r) at k = {!s}, E = {}\\n'.format(K, E_str))\n\n        for line in psi_file:\n            line_split = line.split()\n            i = int(line_split[0])\n            j = int(line_split[1])\n            k = int(line_split[2])\n            real = float(line_split[3])\n            imag = float(line_split[4])\n            psi_grid[i, j, k] = complex(real, imag)\n        return psi_grid\n\n    def get_psi_grid(self, K, E, recalculate=False, vectorised=True, interpolation='cubic',\n                     debug=False):\n        \"\"\"Get mesh of complex wavefunction values.\n\n        If it is already stored in a file and recalculate is False, then it will read from file.\n        Otherwise, it will calculate wavefunction.\n\n        Args:\n            K (KVector): K-point Vector\n            E (float): Band energy\n            recalculate (bool, opt): Force recalculation, even if already stored\n            vectorised (bool, opt): If true, use NumPy vectorisation\n            interpolation (string, opt): Method of interpolation.\n                Possible arguments are 'linear', 'quadratic', 'cubic'\n            debug (bool, opt): Print extra information during runtime\n\n        Returns:\n            array(complex): Mesh of complex wavefunction values\n        \"\"\"\n        \n        if not recalculate and os.path.isfile(self.psi_filename(K, E)):\n            # Read data from file\n            psi_grid = self.read_psi_grid(K, E, debug=debug)\n        else:\n            psi_grid = self.calculate_psi_grid(K, E, recalculate=recalculate, vectorised=vectorised,\n                                               interpolation=interpolation, debug=debug)\n            self.write_psi_grid(psi_grid, K, E)\n        return psi_grid\n\n    def calculate_ldos_grid(self, min_E, max_E, T, recalculate=False, vectorised=True,\n                            interpolation='cubic', debug=False):\n        \"\"\"Calculate summed LDOS.\n\n        Args:\n            min_E (float): Minimum absolute energy\n            max_E (float): Maximum absolute energy\n            T (float): Absolute temperature in Kelvin\n            recalculate (bool, opt): Force recalculation, even if already stored\n            vectorised (bool, opt): If true, use NumPy vectorisation\n            interpolation (string, opt): Method of interpolation.\n                Possible arguments are 'linear', 'quadratic', 'cubic'\n            debug (bool, opt): Print extra information during runtime\n\n        Returns:\n            array(float): LDoS mesh\n        \"\"\"\n        \n        # Print debug info\n        if debug:\n            sys.stdout.write('Calculating local density of states grid\\n')\n            sys.stdout.flush()\n\n        # Initialise mesh\n        ldos_grid = np.zeros_like(self.real_mesh[..., 0], dtype=float)\n\n        total_k_weight = sum([K.weight for K in self.bands])\n\n        # Iterate over energies\n        for K in self.bands:\n            for E in self.bands[K]:\n                if min_E <= E <= max_E:\n                    psi_grid = self.get_psi_grid(K, E, recalculate=recalculate,\n                                                 vectorised=vectorised, interpolation=interpolation,\n                                                 debug=debug)\n                    fd = self.fermi_dirac(E, T)\n                    if E > self.fermi_level:\n                        fd = 1 - fd\n                    if vectorised:\n                        ldos_grid += (K.weight / total_k_weight) * fd * (abs(psi_grid))**2\n                    else:\n                        for ijk in np.ndindex(self.real_mesh.shape[:3]):\n                            ldos_grid[ijk] += (K.weight/total_k_weight)*fd*(abs(psi_grid[ijk]))**2\n        return ldos_grid\n\n    def ldos_filename(self, min_E, max_E, T):\n        \"\"\"Return standardised filename for relevant LDOS file\"\"\"\n        \n        return os.path.join(self.MESH_FOLDER, '{}_{}_{}_{}_{}_{}.{}'.format(\n                self.LDOS_FNAME, self.name, self.grid_spacing, min_E, max_E, T, self.EXT))\n\n    def write_ldos_grid(self, ldos_grid, min_E, max_E, T, debug=False):\n        \"\"\"Write LDoS mesh to file.\n\n        Args:\n            ldos_grid (array(float)): 3D array of LDOS values.\n            min_E (float): Minimum energy.\n            max_E (float): Maximum energy.\n            T (float): Absolute temperature in K.\n            debug (bool, opt): Print extra information during runtime.\n        \"\"\"\n        \n        filename = self.ldos_filename(min_E, max_E, T)\n        \n        # Get LDOS mesh\n        ldos_file = safe_open(filename, 'w')\n        if debug:\n            sys.stdout.write('Writing LDOS grid to {}\\n'.format(filename))\n            sys.stdout.flush()\n            \n        # Iterate over mesh points\n        for i, j, k in np.ndindex(self.real_mesh.shape[:3]):\n            # If LDOS is non-zero at mesh point, write data to file\n            if ldos_grid[i, j, k]:\n                ldos_file.write('{} {} {} {}\\n'.format(i, j, k, ldos_grid[i, j, k]))\n            \n        ldos_file.close()\n\n    def read_ldos_grid(self, min_E, max_E, T, debug=False):\n        \"\"\"Read LDOS mesh from file.\"\"\"\n        \n        filename = self.ldos_filename(min_E, max_E, T)\n        ldos_file = open(filename, 'r')\n        ldos_grid = np.zeros_like(self.real_mesh[..., 0])\n\n        if debug:\n            sys.stdout.write('Reading LDoS grid from {}\\n'.format(filename))\n            sys.stdout.flush()\n\n        for line in ldos_file:\n            line_split = line.split()\n            # Get mesh indices\n            i = int(line_split[0])\n            j = int(line_split[1])\n            k = int(line_split[2])\n            # Get LDoS value\n            value = float(line_split[3])\n            ldos_grid[i, j, k] = value\n\n        if debug:\n            sys.stdout.write('LDoS grid successfully read\\n')\n            sys.stdout.flush()\n        return ldos_grid\n\n    def get_ldos_grid(self, min_E, max_E, T, recalculate=False, vectorised=True,\n                      interpolation='cubic', debug=False):\n        \"\"\"Get LDOS mesh by calculating or reading from file.\n\n        Args:\n            min_E (float): Minimum absolute energy\n            max_E (float): Maximum absolute energy\n            T (float): Absolute temperature in K\n            recalculate (bool, opt): Force recalculation of meshes, even if already stored\n            vectorised (bool, opt): If true, use NumPy vectorisation\n            interpolation (string, opt): Method of interpolation.\n                Possible arguments are 'linear', 'quadratic', 'cubic'\n            debug (bool, opt): Print extra information during runtime\n\n        Returns:\n            array(float): 3D mesh of LDOS values\n        \"\"\"\n        \n        # Read ldos grid from file if not stored by cell\n        if not recalculate and os.path.isfile(self.ldos_filename(min_E, max_E, T)):\n            ldos_grid = self.read_ldos_grid(min_E, max_E, T, debug=debug)\n        else:\n            # Calculate LDOS on mesh\n            ldos_grid = self.calculate_ldos_grid(min_E, max_E, T, recalculate=recalculate,\n                                                 vectorised=vectorised, interpolation=interpolation,\n                                                 debug=debug)\n            self.write_ldos_grid(ldos_grid, min_E, max_E, T, debug=debug)\n        return ldos_grid\n\n    def periodic_gradient(self, mesh):\n        \"\"\"Calculate gradient of mesh with periodic boundary conditions enforced.\n\n        This is done by padding the mesh with extra columns in each dimension, then copying the\n        columns from the other side of the mesh into the pads. This makes the columns corresponding\n        to a boundary of the simulation cell effectively next to the columns near the opposing\n        boundary, such that numerical calculation of the gradient should be continuous over the\n        boundary.\n        \"\"\"\n\n        # Width of padding\n        pad = 3\n        # Get shape of padded array\n        padded_shape = (mesh.shape[0] + 2*pad, mesh.shape[1] + 2*pad, mesh.shape[2] + 2*pad)\n\n        # Copy mesh into padded mesh\n        padded_mesh = np.zeros(padded_shape, dtype=mesh.dtype)\n        padded_mesh[pad:-pad, pad:-pad, pad:-pad] = mesh\n\n        # Copy boundary regions into padding\n        padded_mesh[:pad, pad:-pad, pad:-pad] = mesh[-pad:, :, :]\n        padded_mesh[pad:-pad, :pad, pad:-pad] = mesh[:, -pad:, :]\n        padded_mesh[pad:-pad, pad:-pad, :pad] = mesh[:, :, -pad:]\n        padded_mesh[-pad:, pad:-pad, pad:-pad] = mesh[:pad, :, :]\n        padded_mesh[pad:-pad, -pad:, pad:-pad] = mesh[:, :pad, :]\n        padded_mesh[pad:-pad, pad:-pad, -pad:] = mesh[:, :, :pad]\n\n        # Get gradient\n        padded_gradient = np.transpose(np.array(np.gradient(padded_mesh, self.grid_spacing)),\n                                       (1, 2, 3, 0))\n\n        # Return unpadded gradient\n        return padded_gradient[pad:-pad, pad:-pad, pad:-pad]\n\n    def delta_s(self):\n        \"\"\"Calculate the default value for delta S.\n        \n        This is the minimum delta S from Paz and Soler, multiplied by DELTA_S_FACTOR.\"\"\"\n        \n        min_delta_s = 2.0 * self.grid_spacing / self.H_BAR * np.sqrt(4.85*2.0*self.ELECTRON_MASS)\n        return self.DELTA_S_FACTOR * min_delta_s\n\n    def kappa_squared(self, tip_work_func, tip_fermi_level):\n        \"\"\"Calculate decay constant of tip wavefunction\"\"\"\n        \n        return 2*self.ELECTRON_MASS/(self.H_BAR**2)*(tip_work_func - tip_fermi_level)\n\n    def greens_function(self, distance, tip_work_func, tip_energy):\n        \"\"\"Evaluate Tersoff-Hamann Green's Function\"\"\"\n        \n        if distance == 0:\n            return 0\n        else:\n            kappa2 = self.kappa_squared(tip_work_func, tip_energy)\n            return np.exp(- kappa2 * distance) / (4*np.pi*distance)\n\n    def broadened_surface(self, charge_density_mesh, fraction, max_height_index, delta_s=None):\n        \"\"\"Calculate the magnitude of the c mesh\"\"\"\n        \n        if delta_s is None:\n            delta_s = self.default_delta_s\n\n        # Get isovalue\n        max_value = np.max(charge_density_mesh)\n        isovalue = fraction * max_value\n\n        # Evaluate logarithm on all non-zero entrie\n        log_mesh = np.empty(charge_density_mesh.shape, dtype=float)\n        zero_points = charge_density_mesh == 0\n        log_mesh[~zero_points] = np.log(charge_density_mesh[charge_density_mesh != 0] / isovalue)\n        log_mesh[zero_points] = np.inf\n\n        # Apply broadening to surface\n        broadened_mesh = np.where(abs(log_mesh) < delta_s,\n                                  15.0 / (16.0 * delta_s) * (1.0 - (log_mesh / delta_s) ** 2) ** 2, 0)\n\n        # Remove overlapping layers of surface\n        # Iterate over x and y\n        for i, j in np.ndindex(broadened_mesh.shape[:2]):\n            on_surface = False\n            past_surface = False\n            # Iterate over z, starting from top\n            for k in reversed(range(broadened_mesh.shape[2])):\n                if k < max_height_index:\n                    if past_surface:\n                        # First surface has been traversed, replace subsequent elements with zeros\n                        broadened_mesh[i, j, k] = 0\n                    elif broadened_mesh[i, j, k] != 0 and not on_surface:\n                        # Highest surface has been reached\n                        on_surface = True\n                    elif on_surface and broadened_mesh[i, j, k] == 0:\n                        # Was on surface, now just below\n                        on_surface = False\n                        past_surface = True\n                else:\n                    broadened_mesh[i, j, k] = 0\n        return broadened_mesh\n\n    def get_c(self, charge_density_mesh, fraction, tip_height_index, delta_s=None):\n        \"\"\"Return c mesh for surface integration.\n\n        Args:\n            charge_density_mesh (array(float)): Charge density or LDOS mesh.\n            fraction (float): Isovalue given by fraction of maximum mesh value.\n            tip_height_index (int): Z-index of tip height.\n            delta_s (float, opt): Surface broadening parameter; If None, uses default value.\n        \"\"\"\n        \n        if delta_s is None:\n            delta_s = self.default_delta_s\n\n        # Find all points of zero density\n        zero_points = charge_density_mesh == 0\n\n        # Get magnitude of c mesh\n        broadened_mesh = self.broadened_surface(charge_density_mesh, fraction, tip_height_index,\n                                                delta_s=delta_s)\n\n        # Get gradient of density mesh\n        gradient_surface = self.periodic_gradient(charge_density_mesh)\n\n        # Calculate final mesh\n        vector_surface = np.zeros(gradient_surface.shape, dtype=float)\n        for i in range(3):\n            gradient_surface[~zero_points, i] = gradient_surface[~zero_points, i] / charge_density_mesh[~zero_points]\n            gradient_surface[zero_points, i] = 0\n            vector_surface[..., i] = np.multiply(broadened_mesh, gradient_surface[..., i])\n\n        return vector_surface\n\n    def get_A_mesh(self, c, wavefunction_mesh):\n        \"\"\"Calculate A mesh.\"\"\"\n        \n        grad_wavefunction = self.periodic_gradient(wavefunction_mesh)\n        return self.mesh_dot_product(c, grad_wavefunction)\n\n    @staticmethod\n    def mesh_dot_product(vector_mesh_A, vector_mesh_B):\n        \"\"\"Return dot/scalar product of two vector meshes.\"\"\"\n        \n        # Check if resulting mesh will be complex\n        if vector_mesh_A.dtype == complex or vector_mesh_B.dtype == complex:\n            dtype = complex\n        else:\n            dtype = float\n\n        scalar_mesh = np.zeros(vector_mesh_A.shape[:3], dtype=dtype)\n        for i in range(3):\n            scalar_mesh += vector_mesh_A[..., i]*vector_mesh_B[..., i]\n        return scalar_mesh\n\n    def get_B_mesh(self, c, wavefunction_mesh):\n        \"\"\"Calculate B mesh.\"\"\"\n        \n        B = np.zeros_like(c, dtype=complex)\n        for i in range(3):\n            B[..., i] = c[..., i] * wavefunction_mesh\n        return B\n\n    def greens_function_mesh(self, z_index, tip_work_func, tip_energy, debug=False):\n        \"\"\"Calculate Tersoff-Hamann tip Greens function over entire mesh.\n\n        Uses symmetry of the function to reduce number of calculations.\n\n        Args:\n            z_index (float): z-index of tip plane.\n            tip_work_func (float): Work function of tip.\n            tip_energy (float): Fermi-level of tip.\n            debug (bool, opt): Print extra information during runtime.\n        \"\"\"\n\n        # Create square grid with sides equal to the size of the x or y=axis of the real mesh\n        #   whichever is larger\n        plane_length_half = - (- (max(self.real_mesh.shape[:2]) + 1) / 2)\n        plane_length_full = plane_length_half * 2 - 1\n        plane_shape_half = (plane_length_half,) * 2\n        plane_UR = np.zeros(plane_shape_half, dtype=float)\n\n        # Initialise Green's function mesh\n        G_shape = (plane_length_full, plane_length_full, self.real_mesh.shape[2])\n        G_mesh = np.zeros(G_shape, dtype=float)\n\n        # Print debug info\n        debug_str = 'Calculating G(r - R): '\n        if debug:\n            sys.stdout.write(debug_str)\n            sys.stdout.flush()\n        points_done = 0\n        bars_done = 0\n\n        # Iterate over z values\n        for k in range(G_shape[2]):\n            # Iterate over right-angle triangle in x and y\n            # The tip is considered to be in corner of the mesh at i = j = 0\n            for i in range(plane_length_half):\n                for j in range(i + 1):\n                    # If above tip, define as 0\n                    if k >= z_index:\n                        G = 0\n                    else:\n                        # Calculate Green's function\n                        distance = self.grid_spacing * np.sqrt(i**2 + j**2 + (z_index - k)**2)\n                        G = self.greens_function(distance, tip_work_func, tip_energy)\n\n                    # Copy values from this side of triangle into other\n                    # In effect, reflect values along x = y\n                    for x, y in [i, j], [j, i]:\n                        plane_UR[x, y] = G\n            # Flip square to create four subsquares\n            plane_UL = np.flipud(plane_UR[1:, :])\n            plane_LR = np.fliplr(plane_UR[:, 1:])\n            plane_LL = np.flipud(plane_LR[1:, :])\n\n            # Combine subsquares\n            # Tip is now defined above the centre of mesh\n            plane_U = np.concatenate((plane_UL, plane_UR), axis=0)\n            plane_L = np.concatenate((plane_LL, plane_LR), axis=0)\n            plane = np.concatenate((plane_L, plane_U), axis=1)\n\n            G_mesh[..., k] = plane\n\n            # Update progress bar\n            points_done += 1\n            prog = float(points_done) / self.real_mesh.shape[2]\n            if debug and prog * self.PROG_BAR_INTERVALS >= bars_done:\n                percent = prog * 100\n                sys.stdout.write('\\r')\n                sys.stdout.write(debug_str)\n                sys.stdout.write(' [{:<{}}]'.format(self.PROG_BAR_CHARACTER * bars_done,\n                                                    self.PROG_BAR_INTERVALS))\n                sys.stdout.write(' {:3.0f}%'.format(percent))\n                sys.stdout.flush()\n                bars_done += 1\n\n        if debug:\n            sys.stdout.write('\\n')\n            sys.stdout.flush()\n        return G_mesh\n\n    def propagated_psi_filename(self, K, E, T, fraction, z, delta_s=None):\n        \"\"\"Return standardised filename for relevant propagated wavefunction file.\"\"\"\n        \n        if delta_s is None:\n            delta_s = self.default_delta_s\n        \n        return os.path.join(self.MESH_FOLDER, '{}_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}.{}'.format(\n                self.PROP_PSI_FNAME, self.name, self.grid_spacing, K.x, K.y, K.z, E, T, fraction, z,\n                delta_s, self.EXT))\n\n    def write_prop_psi(self, psi, K, E, T, fraction, z, delta_s=None):\n        \"\"\"Write propagated wavefunction function mesh to file.\"\"\"\n        \n        if delta_s is None:\n            delta_s = self.default_delta_s\n        \n        filename = self.propagated_psi_filename(K, E, T, fraction, z, delta_s=delta_s)\n        psi_file = safe_open(filename, 'w')\n        for i, j in np.ndindex(psi.shape):\n            if psi[i, j] != 0:\n                p = psi[i, j]\n                psi_file.write('{} {} {} {}\\n'.format(i, j, p.real, p.imag))\n        \n        psi_file.close()\n\n    def read_prop_psi(self, K, E, T, fraction, z, delta_s=None, debug=False):\n        \"\"\"Read propagated wavefunction mesh from file.\"\"\"\n        \n        if delta_s is None:\n            delta_s = self.default_delta_s\n\n        filename = self.propagated_psi_filename(K, E, T, fraction, z, delta_s=delta_s)\n        psi_file = open(filename, 'r')\n        psi = np.zeros(self.real_mesh.shape[:2], dtype=complex)\n\n        if debug:\n            if self.PRINT_RELATIVE_TO_EF:\n                E_str = '{} eV'.format(E - self.fermi_level)\n            else:\n                E_str = '{} eV'.format(E)\n            sys.stdout.write('Reading psi(R) at k = {!s}, E = {}\\n'.format(K, E_str))\n            sys.stdout.flush()\n\n        for line in psi_file:\n            line_split = line.split()\n            i = int(line_split[0])\n            j = int(line_split[1])\n            real = float(line_split[2])\n            imag = float(line_split[3])\n            psi[i, j] = complex(real, imag)\n        \n        return psi\n\n    def calculate_current_scan(self, z, V, T, tip_work_func, tip_energy, delta_s=None,\n                               fraction=0.025, recalculate=False, vectorised=True,\n                               interpolation='cubic', debug=False):\n        \"\"\"Calculate tunnelling current across a plane ie. in constant-height mode.\n\n        Args:\n            z (float): z-value of plane in Bohr radii; Uses nearest mesh point to given value\n            V (float): Bias voltage\n            T (float): Absolute temperature\n            tip_work_func (float): Work function of tip\n            tip_energy (float): Fermi-level of tip\n            delta_s (float, opt): Surface broadening parameter; If None, uses default value\n            fraction (float, opt): Fraction of max charge density to use as value for isosurface\n            recalculate (bool, opt): Force recalculation, even if already stored.\n            vectorised (bool, opt): If true, use NumPy vectorisation.\n            interpolation (str, opt): Method of interpolation.\n                Possible arguments are 'linear', 'quadratic', 'cubic'.\n            debug (bool, opt): Print extra information during runtime.\n\n        Returns:\n            array(float): 2D array of current values.\n        \"\"\"\n\n        if delta_s is None:\n            delta_s = self.default_delta_s\n\n        if debug:\n            sys.stdout.write('Calculating I(R) at V = {}V\\n'.format(V))\n            sys.stdout.flush()\n\n        min_E, max_E = self.bias_to_energy_range(V)\n\n        total_k_weight = 0\n        total_energies = 0\n        for K in self.bands:\n            total_k_weight += K.weight\n            for E in self.bands[K]:\n                if min_E <= E <= max_E:\n                    total_energies += 1\n        energies_done = 0\n\n        # Find nearest mesh z-value to given\n        z, k = self.get_nearest_mesh_value(z, points=self.real_mesh.shape[2])\n\n        # Initialise meshes\n        current = np.zeros(self.real_mesh.shape[:2], dtype=float)\n        psi = np.zeros_like(current, dtype=complex)\n        elements = current.shape[0]*current.shape[1]\n\n        # Calculate meshes\n        ldos = self.get_ldos_grid(min_E, max_E, T, recalculate=recalculate, vectorised=vectorised,\n                                  interpolation=interpolation, debug=debug)\n        c = self.get_c(ldos, fraction, k, delta_s=delta_s)\n        G_conjugate = np.conjugate(self.greens_function_mesh(k, tip_work_func,\n                                                             tip_energy, debug=debug))\n\n        # Print debug info\n        if debug:\n            sys.stdout.write('Calculating grad(G)\\n')\n            sys.stdout.flush()\n\n        G_conjugate_gradient = self.periodic_gradient(G_conjugate)\n        G_centre = G_conjugate.shape[0] / 2\n\n        # Iterate over energies\n        for K in self.bands:\n            w = K.weight\n            for E in self.bands[K]:\n                if min_E <= E <= max_E:\n                    fd = self.fermi_dirac(E - V, T)\n                    if V < 0:\n                        fd = 1 - fd\n\n                    # Get propagated wavefunction\n                    if not recalculate and os.path.isfile(\n                            self.propagated_psi_filename(K, E, T, fraction, z, delta_s=delta_s)):\n                        # Read data from file\n                        psi = self.read_prop_psi(K, E, T, fraction, z, delta_s=delta_s, debug=debug)\n                        read = True\n                    else:\n                        read = False\n                        points_done = 0\n                        bars_done = 0\n\n                        # Get unpropagated wavefunction\n                        raw_psi = self.get_psi_grid(K, E, recalculate=recalculate,\n                                                    vectorised=vectorised,\n                                                    interpolation=interpolation, debug=debug)\n\n                        # Print debug info\n                        prog = float(energies_done) / total_energies * 100\n                        if self.PRINT_RELATIVE_TO_EF:\n                            E_str = '{} eV'.format(E - self.fermi_level)\n                        else:\n                            E_str = '{} eV'.format(E)\n                        debug_str = 'Calculating psi(R) at k = {!s}, E = {}:\\n  {:5.1f}%'.format(\n                                K, E_str, prog)\n                        if debug:\n                            sys.stdout.write(debug_str)\n                            sys.stdout.flush()\n\n                        # Get meshes\n                        A = self.get_A_mesh(c, raw_psi)\n                        B = self.get_B_mesh(c, raw_psi)\n\n                        # Iterate over tip positions\n                        for i, j in np.ndindex(current.shape):\n                            # By rolling the tip Green's function, we move the position of the tip\n                            G_conjugate_rolled = np.roll(G_conjugate, (i - G_centre), 0)\n                            G_conjugate_rolled = np.roll(G_conjugate_rolled, (j - G_centre), 1)[\n                                                 :self.real_mesh.shape[0], :self.real_mesh.shape[1]]\n                            G_conjugate_gradient_rolled = np.roll(G_conjugate_gradient, (i - G_centre), 0)\n                            G_conjugate_gradient_rolled = np.roll(G_conjugate_gradient_rolled, (j - G_centre), 1)[\n                                                          :self.real_mesh.shape[0], :self.real_mesh.shape[1]]\n\n                            # Perform volume integral\n                            integrand = G_conjugate_rolled * A - self.mesh_dot_product(B, G_conjugate_gradient_rolled)\n                            psi[i, j] = np.sum(integrand) * self.grid_spacing ** 3\n\n                            # Update progress bar\n                            points_done += 1\n                            prog = float(points_done) / elements\n                            if debug and prog * self.PROG_BAR_INTERVALS >= bars_done:\n                                percent = prog * 100\n                                sys.stdout.write('\\r')\n                                sys.stdout.write(' [{:<{}}] {:3.0f}%'.format(\n                                        self.PROG_BAR_CHARACTER * bars_done,\n                                        self.PROG_BAR_INTERVALS, percent))\n                                sys.stdout.flush()\n                                bars_done += 1\n                                \n                        # Save propagated wavefunction\n                        self.write_prop_psi(psi, K, E, T, fraction, z, delta_s=delta_s)\n\n                    # Add to current total\n                    current += fd * (w / total_k_weight) * abs(psi)**2\n\n                    energies_done += 1\n                    if debug and not read:\n                        sys.stdout.write('\\n')\n                        sys.stdout.flush()\n        return current\n\n    def current_filename(self, z, V, T, fraction, delta_s=None):\n        \"\"\"Return standardised filename for relevant current file.\"\"\"\n        \n        if delta_s is None:\n            delta_s = self.default_delta_s\n        return os.path.join(self.MESH_FOLDER, '{}_{}_{}_{}_{}_{}_{}_{}.{}'.format(\n                self.CURRENT_FNAME, self.name, self.grid_spacing, z, V, T, fraction, delta_s,\n                self.EXT))\n\n    def write_current(self, current, z, V, T, fraction, delta_s=None, debug=False):\n        \"\"\"Write current to file.\"\"\"\n        \n        filename = self.current_filename(z, V, T, fraction, delta_s)\n\n        current_file = safe_open(filename, 'w')\n        if debug:\n            sys.stdout.write('Writing current grid to {}\\n'.format(filename))\n            \n        # Iterate over mesh points\n        for i, j in np.ndindex(current.shape):\n            # If LDOS is non-zero at mesh point, write data to file\n            if current[i, j] != 0:\n                current_file.write('{} {} {}\\n'.format(i, j, current[i, j]))\n                \n        current_file.close()\n\n    def read_current(self, z, V, T, fraction, delta_s=None, debug=False):\n        \"\"\"Read current grid from file.\"\"\"\n        \n        filename = self.current_filename(z, V, T, fraction, delta_s=delta_s)\n        current_file = open(filename, 'r')\n        current = np.zeros(self.real_mesh.shape[:2], dtype=float)\n\n        if debug:\n            sys.stdout.write('Reading I(R) from {}\\n'.format(filename))\n            sys.stdout.flush()\n\n        for line in current_file:\n            line_split = line.split()\n            # Get mesh indices\n            i = int(line_split[0])\n            j = int(line_split[1])\n\n            # Get current value\n            value = float(line_split[2])\n            current[i, j] = value\n\n        if debug:\n            sys.stdout.write('I(R) successfully read\\n')\n            sys.stdout.flush()\n            \n        return current\n\n    def get_current_scan(self, z, V, T, tip_work_func, tip_energy, delta_s=None, fraction=0.025,\n                         recalculate=False, vectorised=True, interpolation='cubic', debug=False):\n        \"\"\"Get constant-height tunnelling current as 2d array.\n\n        If it is already stored in a file and recalculate is False, then it will read from file.\n        Otherwise, it will calculate current.\n\n        Args:\n            z (float): z-value of plane in Bohr radii; Uses nearest mesh point to given value.\n            V (float): Bias voltage.\n            T (float): Absolute temperature.\n            tip_work_func (float): Work function of tip.\n            tip_energy (float): Fermi-level of tip.\n            delta_s (float, opt): Surface broadening parameter; If None, uses default value.\n            fraction (float, opt): Fraction of max charge density to use as value for isosurface.\n            recalculate (bool, opt): Force recalculation, even if already stored.\n            vectorised (bool, opt): If true, use NumPy vectorisation.\n            debug (bool, opt): Print extra information during runtime.\n\n        Returns:\n            array(float): 2D array of current values.\n        \"\"\"\n        \n        if delta_s is None:\n            delta_s = self.default_delta_s\n        if not recalculate and os.path.isfile(self.current_filename(z, V, T, fraction)):\n            # Read data from file\n            current = self.read_current(z, V, T, fraction, debug=debug)\n        else:\n            current = self.calculate_current_scan(z, V, T, tip_work_func, tip_energy,\n                                                  delta_s=delta_s, fraction=fraction,\n                                                  recalculate=recalculate,\n                                                  interpolation=interpolation,\n                                                  vectorised=vectorised, debug=debug)\n            self.write_current(current, z, V, T, fraction)\n            \n        return current\n\n    def get_spectrum_th(self, xy, min_V, max_V, sigma, T, fraction, z, delta_s=None, dE=0.005, debug=False):\n        \"\"\"Get spectroscopic data from a list of specific tip positions.\n\n        Args:\n            xy (list(list(float)): x-y points of tip in a0; Given as [[x1, y1], [x2, y2], ...].\n                Uses nearest mesh point.\n            min_V (float): Lower bound for voltage range.\n            max_V (float): Upper bound for voltage range.\n            sigma (float): State smearing parameter in eV.\n            T (float): Absolute temperature in K.\n            z (float): z-value of plane in a0; Uses nearest mesh point to given value.\n            fraction (float): Fraction of maximum charge density to use as value for isosurface.\n            delta_s (float, opt): Surface broadening parameter; If None, uses default value.\n            dE (float, opt): Energy resolution of data points.\n            debug (bool, opt): Print extra information during runtime.\n\n        Returns:\n            array(float): Range of voltage values with resolution dE.\n            array(float): Tunnelling conductance values for each tip position.\n        \"\"\"\n        \n        # Convert voltage range into absolute energies\n        min_E = min_V + self.fermi_level\n        max_E = max_V + self.fermi_level\n\n        # Get positions of tip\n        mesh_positions = []\n        mesh_indices = []\n        for l in range(len(xy)):\n            x, i = self.get_nearest_mesh_value(xy[l][0], points=self.real_mesh.shape[0])\n            y, j = self.get_nearest_mesh_value(xy[l][1], points=self.real_mesh.shape[1])\n            mesh_positions.append((x, y))\n            mesh_indices.append((i, j))\n\n        Es = []\n        psis = []\n        weights = []\n        l = 0\n        # Iterate over energies in voltage range\n        for K in self.bands:\n            for E in self.bands[K]:\n                # Assume states 3*sigma away from the edges contribute negligibly\n                if min_E - 3*sigma < E < max_E + 3*sigma:\n                    Es.append(E)\n                    weights.append(K.weight)\n                    psi = self.read_prop_psi(K, E, T, fraction, z, delta_s=delta_s, debug=debug)\n                    psis.append([])\n\n                    # Get wavefunction for each tip position\n                    for m in range(len(mesh_positions)):\n                        psis[l].append(abs(psi[mesh_indices[m]])**2)\n                    l += 1\n        \n        # Convert lists to arrays\n        Es = np.array(Es)\n        psis = np.array(psis)\n        weights = np.array(weights)\n\n        # Generate energy points for plot\n        E_range = np.arange(min_E, max_E, dE)\n        # Initialise LDOS\n        LDOS = np.zeros((E_range.shape[0], len(xy)))\n\n        for u in range(len(E_range)):\n            LDOS[u] = np.sum(weights[..., None] * psis *\n                             np.exp(-(((E_range[u] - Es[..., None]) / sigma)**2) / 2), axis=0)\n        V_range = E_range - self.fermi_level\n\n        return V_range, LDOS\n\n    def get_cits(self, V, T, fraction, sigma, delta_s=None, debug=False):\n        \"\"\"Calculate Current Imaging Tunnelling Spectroscopy scan - UNFINISHED and UNRELIABLE.\"\"\"\n        \n        if delta_s is None:\n            delta_s = self.default_delta_s\n\n        min_E, max_E = self.bias_to_energy_range(V)\n\n        ldos = self.get_ldos_grid(min_E, max_E, T, debug=debug)\n        b = self.broadened_surface(ldos, fraction, self.real_mesh[..., -1, 2], delta_s=delta_s)\n\n        scan = np.zeros(b.shape[:2])\n\n        for K in self.bands:\n            w = K.weight\n            for E in self.bands[K]:\n                if -3*sigma < E - V - self.fermi_level < 3*sigma:\n                    exp = np.exp(-(((E - V - self.fermi_level) / sigma)**2) / 2)\n                    psi = self.get_psi_grid(K, E, debug=debug)\n                    b_psi = b * abs(psi)**2\n\n                    for i, j in np.ndindex(scan.shape):\n                        scan[i, j] += w * exp * np.sum(b_psi[i, j])\n        scan = scan.reshape(b.shape[:2])\n\n        return scan\n", "meta": {"hexsha": "0acf3c82a4aa6c9b7dd1309e4b6c454c8d55acc6", "size": 61001, "ext": "py", "lang": "Python", "max_stars_repo_path": "conquest_stm/cell.py", "max_stars_repo_name": "johanmcquillan/conquest_stm", "max_stars_repo_head_hexsha": "b4501f69004dd8a7e684284bd4adc4a06b7a4dc1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-28T03:45:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-28T03:45:42.000Z", "max_issues_repo_path": "conquest_stm/cell.py", "max_issues_repo_name": "johanmcquillan/conquest_stm", "max_issues_repo_head_hexsha": "b4501f69004dd8a7e684284bd4adc4a06b7a4dc1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conquest_stm/cell.py", "max_forks_repo_name": "johanmcquillan/conquest_stm", "max_forks_repo_head_hexsha": "b4501f69004dd8a7e684284bd4adc4a06b7a4dc1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.5687369156, "max_line_length": 118, "alphanum_fraction": 0.5439746889, "include": true, "reason": "import numpy", "num_tokens": 13390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.17102808049781074}}
{"text": "\nimport torch\nimport torch.nn as nn\n\n\nclass FCOSLoss(nn.Module):\n    def __init__(self, limit_range, central_sampling=True, central_sampling_radius=1.5, \\\n                        strides=[8, 16, 32, 64, 128], regression_loss_type='giou', num_classes=81):\n        super(FCOSLoss, self).__init__()\n        self.limit_range = limit_range\n        self.strides = strides\n        self.num_classes = num_classes\n        self.central_sampling = central_sampling\n        self.regression_loss_type = regression_loss_type\n        self.central_sampling_radius = central_sampling_radius\n        \n        \n    def forward(self, prediction, batch_bboxes):\n        # prediction   : list of 3 tensors cls_probs, cnt_logits, reg_values\n        # batch_bboxes : [B x M x 5] --> [x1, y1, x2, y2, cls_id]\n        \n        cls_probs_pred, cnt_logits_pred, reg_values_pred = prediction\n        # cls_probs_pred  : [[B x 81 x H x W], [B x 81 x H x W], ...]\n        # cnt_logits_pred : [[B x 1 x H x W], [B x 1 x H x W], ...]\n        # reg_values_pred : [[B x 4 x H x W], [B x 4 x H x W], ...]\n        \n        comb_cls_probs_pred = []\n        comb_cnt_logits_pred = []\n        comb_reg_values_pred = []\n        \n        comb_cls_probs_target = []\n        comb_cnt_logits_target = []\n        comb_reg_values_target = []\n\n        for i, (cls_p, cnt_p, reg_p) in enumerate(zip(cls_probs_pred, cnt_logits_pred, reg_values_pred)):\n            num_classes, feat_h, feat_w = cls_p.shape[1:4]\n            cls_target, cnt_target, reg_target = \\\n                self.generate_targets(feat_h, feat_w, batch_bboxes, \\\n                                        self.strides[i], self.limit_range[i])    \n            # cls_target : [B x H*W x 81]\n            # cnt_target : [B x H*W x 1]\n            # reg_target : [B x H*W x 4]\n            \n            # TODO : Cant we just calculate loss for each scale inside this loop rather than \n            #        Combining these tensors and computing together.\n            cls_p = torch.reshape(cls_p, (-1, num_classes, feat_h*feat_w)).permute([0, 2, 1])      # [B x H*W x 81]\n            cnt_p = torch.reshape(cnt_p, (-1, 1, feat_h*feat_w)).permute([0, 2, 1])                # [B x H*W x 1]\n            reg_p = torch.reshape(reg_p, (-1, 4, feat_h*feat_w)).permute([0, 2, 1])                # [B x H*W x 4]\n            \n            comb_cls_probs_pred.append(cls_p)\n            comb_cnt_logits_pred.append(cnt_p)\n            comb_reg_values_pred.append(reg_p)\n            \n            comb_cls_probs_target.append(cls_target)\n            comb_cnt_logits_target.append(cnt_target)\n            comb_reg_values_target.append(reg_target)\n            \n        comb_cls_probs_target = torch.cat(comb_cls_probs_target, dim=1)      # [B x sum of all H*W x 81]\n        comb_cnt_logits_target = torch.cat(comb_cnt_logits_target, dim=1)    # [B x sum of all H*W x 1]\n        comb_reg_values_target = torch.cat(comb_reg_values_target, dim=1)    # [B x sum of all H*W x 4]\n        \n        comb_cls_probs_pred = torch.cat(comb_cls_probs_pred, dim=1)    # [B x sum of all H*W x 81]\n        comb_cnt_logits_pred = torch.cat(comb_cnt_logits_pred, dim=1)  # [B x sum of all H*W x 1]\n        comb_reg_values_pred = torch.cat(comb_reg_values_pred, dim=1)  # [B x sum of all H*W x 4]\n        \n        mask_pos = comb_cnt_logits_target > -1                         # [B x sum of all H*W x 1]\n        cls_loss = self.compute_cls_loss(comb_cls_probs_pred, comb_cls_probs_target, mask_pos)\n        cnt_loss = self.compute_centerness_loss(comb_cnt_logits_pred, comb_cnt_logits_target, mask_pos) \n        reg_loss = self.compute_coordinate_reg_loss(comb_reg_values_pred, comb_reg_values_target, mask_pos)\n        return cls_loss, cnt_loss, reg_loss\n        \n        \n    def generate_targets(self, feat_h, feat_w, batch_bbox, \\\n                                stride, limit_range):\n        # feat_h     : Height of the feature map\n        # feat_w     : Width of the feature map\n        # batch_bbox : [B x M x 5]  --> [x1, y1, x2, y2, cls_id]\n        #            : Not all images in B are having M bboxes but the are padded to make them M\n        #            : So that they can be stacked in a tensor.\n        # stride : value of stride for this feature-map\n        # limit_range : [min_val, max_val]. To filter most relevant bboxes out of these feature-map\n        \n        target_device = batch_bbox.device\n        grid_y = torch.arange(0, feat_h * stride, stride, dtype=torch.float32)\n        grid_x = torch.arange(0, feat_w * stride, stride, dtype=torch.float32)\n        \n        grid_y, grid_x = torch.meshgrid(grid_y, grid_x)\n        coords = torch.stack([torch.reshape(grid_x, [-1]), \\\n                                torch.reshape(grid_y, [-1])], -1) + stride // 2\n        coords = torch.unsqueeze(coords, 0).to(target_device)\n        # coords : [1 x H*W x 2] : center-points of each grid-cell : [x, y] at last dim.\n        #                        : This coords are now in original image space i.e. 800x1024\n        coords_x, coords_y = coords[:, :, 0], coords[:, :, 1]   # [1 x H*W]\n        \n        batch_bb_x1, batch_bb_y1, batch_bb_x2, batch_bb_y2 = \\\n            batch_bbox[:, :, 0], batch_bbox[:, :, 1], batch_bbox[:, :, 2], batch_bbox[:, :, 3]\n        # [B x M]\n        \n        # coords_x   : [1 x H*W] --> [1 x H*W x 1]\n        # batch_bb_x1: [B x M] --> [B x 1 x M]\n        l_off = torch.unsqueeze(coords_x, 2) - torch.unsqueeze(batch_bb_x1, 1)\n        r_off = torch.unsqueeze(batch_bb_x2, 1) - torch.unsqueeze(coords_x, 2)\n        t_off = torch.unsqueeze(coords_y, 2) - torch.unsqueeze(batch_bb_y1, 1)\n        b_off = torch.unsqueeze(batch_bb_y2, 1) - torch.unsqueeze(coords_y, 2)\n        ltrb_off = torch.stack([l_off, t_off, r_off, b_off], -1)    # [B x H*W x M x 4]\n        # [left_x, top_y, right_x, bottom_y]\n        \n        areas = (l_off + r_off) * (t_off + b_off)            # [B x H*W x M]\n        # For each location we have relationg with All M bboxes.\n        # But we will select only one bbox out of these M bboxes for which  \n        # the area is lowest. \n        \n        off_min = torch.min(ltrb_off, axis=-1)[0]           # [B x H*W x M]\n        off_max = torch.max(ltrb_off, axis=-1)[0]           # [B x H*W x M]\n        \n        mask_feat_map_limit = (off_max > limit_range[0]) & (off_max <= limit_range[1])\n        # [B x H*W x M]\n        \n        mask_in_gtbbox = off_min > 0        # [B x H*W x M]\n        # The bbox out of M which are padded, for such bbox this area will return\n        # -ve and it will be the minimum area out of all the M bboxes. This would \n        # break the next logic. So to prevent it, this mask is introduced.\n        \n        if self.central_sampling:\n            # Ref. : https://github.com/yqyao/FCOS_PLUS/issues/13#issuecomment-564823086\n            img_level_radius = self.central_sampling_radius * stride\n        \n            gtbbox_xc = (batch_bb_x1 + batch_bb_x2) / 2     # [B x M]\n            gtbbox_yc = (batch_bb_y1 + batch_bb_y2) / 2     # [B x M]\n            \n            # coords_x   : [1 x H*W] --> [1 x H*W x 1]\n            # batch_bb_x1: [B x M] --> [B x 1 x M]\n            center_x_off = torch.abs(torch.unsqueeze(coords_x, 2) - torch.unsqueeze(gtbbox_xc, 1))\n            center_y_off = torch.abs(torch.unsqueeze(coords_y, 2) - torch.unsqueeze(gtbbox_yc, 1))\n            center_xy_off = torch.stack([center_x_off, center_y_off], dim=-1)   # [B x H*W x M x 2]\n            center_off_max = torch.max(center_xy_off, dim=-1)[0]                # [B x H*W x M] \n            mask_central_sampling = center_off_max < img_level_radius           # [B x H*W X M]\n\n        else:\n            mask_central_sampling = torch.ones_like(mask_in_gtbbox)     # [B x H*W X M]\n        \n        mask_positive_bbox = mask_feat_map_limit & mask_in_gtbbox & mask_central_sampling\n        # [B x H*W x M]\n        \n        areas[~mask_positive_bbox] = 9999999            # [B x H*W x M]\n        # We would make area for negative bboxes infinite so that the minimum area\n        # will be computed from positive bboxes only.\n        \n        \n        area_min_idx = torch.min(areas, dim=-1)[1]      # [B x H*W]\n        \n        # areas : [B x H*W x M]            \n        ltrb_off_mask = torch.zeros_like(areas, dtype=torch.bool).scatter_(\\\n                                -1, area_min_idx.unsqueeze(dim=-1), 1)\n        # This is the binary mask of shape [B x H*W x M] with value 1 for \n        # all the indexes mentioned by area_min_idx at the last dimension which is having\n        # M values. So out of those M values at last dimension, only one value which is \n        # specified in area_min_idx will be made to 1.0 and rest will be kept as it is at 0.0\n        \n        reg_targets = ltrb_off[ltrb_off_mask]       # [B*H*W x 4]\n        reg_targets = torch.reshape(reg_targets, (-1, feat_h * feat_w, 4))  # [B x H*W x 4]\n        \n        classes = torch.unsqueeze(batch_bbox[:, :, 4], dim=1)           # [B x 1 x M]\n        classes = torch.broadcast_tensors(classes, areas.long())[0]     # [B x H*W x M]\n        \n        cls_targets = classes[ltrb_off_mask]                                # [B*H*W x 1]\n        cls_targets = torch.reshape(cls_targets, (-1, feat_h * feat_w, 1))  # [B x H*W x 1]\n        \n        mask_positive_bbox_2 = mask_positive_bbox.long().sum(dim=-1)        # [B x H*W]\n        mask_positive_bbox_2 = mask_positive_bbox_2 >= 1\n    \n\n        left_right_min = torch.min(reg_targets[:, :, 0], reg_targets[:, :, 2])      # [B x H*W]\n        left_right_max = torch.max(reg_targets[:, :, 0], reg_targets[:, :, 2])      # [B x H*W]\n        top_bottom_min = torch.min(reg_targets[:, :, 1], reg_targets[:, :, 3])      # [B x H*W]\n        top_bottom_max = torch.max(reg_targets[:, :, 1], reg_targets[:, :, 3])      # [B x H*W]\n        cnt_targets = torch.unsqueeze(torch.sqrt((left_right_min * top_bottom_min) / \n                            (left_right_max * top_bottom_max + 1e-9)), dim=-1)     # [B x H*W x 1]\n        \n        \n        cls_targets[~mask_positive_bbox_2] = 0              # [B x H*W x 1]\n        # Assigning label=0 which is background class, for all such locations \n        # which are negative i.e. locations which dont get associated to any bbox\n        # print(cls_targets.shape)\n        \n        cls_targets = torch.nn.functional.one_hot(cls_targets[:, :, 0].long(), num_classes=self.num_classes)\n        # [B x H*W x 1] ---> [B x H*W x 81]\n        \n        cnt_targets[~mask_positive_bbox_2] = -1             # [B x H*W x 1]\n        reg_targets[~mask_positive_bbox_2] = -1             # [B x H*W x 4]\n        return cls_targets, cnt_targets, reg_targets\n    \n    \n    def compute_cls_loss(self, comb_cls_probs_pred, comb_cls_probs_target, mask_pos, \n                            alpha=0.25, gamma=2.0):\n        # comb_cls_probs_pred   : [B x sum of all H*W x 81]\n        # comb_cls_probs_target : [B x sum of all H*W x 81]\n        # mask_pos              : [B x sum of all H*W x 1]\n        \n        assert comb_cls_probs_pred.shape[:2] == comb_cls_probs_target.shape[:2]\n        \n        num_pos = torch.sum(mask_pos, dim=[1, 2]).clamp_(min=1).float()     # [B]\n        \n        # Focal loss to be computed for all grid points\n        # Positive as well as negative\n        pt = comb_cls_probs_pred * comb_cls_probs_target + \\\n            (1 - comb_cls_probs_pred) * (1 - comb_cls_probs_target)        \n        w = alpha * comb_cls_probs_target + (1 - alpha) * (1 - comb_cls_probs_target)\n        focal_loss = (-1) * w * torch.pow((1 - pt), gamma) * torch.log(pt + 1e-10)\n        focal_loss = focal_loss.sum(dim=[1, 2])         # [B]\n\n        focal_loss = focal_loss / num_pos               # [B]\n        return focal_loss.mean()                        # [1]\n        \n        \n    def compute_centerness_loss(self, comb_cnt_logits_pred, comb_cnt_logits_target, mask_pos):\n        # comb_cnt_logits_pred   : [B x sum of all H*W x 1]\n        # comb_cnt_logits_target : [B x sum of all H*W x 1]\n        # mask_pos               : [B x sum of all H*W x 1]\n        \n        num_pos = torch.sum(mask_pos, dim=[1, 2]).clamp_(min=1).float()     # [B]\n        \n        cnt_loss_batch = []\n        batch_size = comb_cnt_logits_pred.shape[0]\n        for i in range(batch_size):\n            preds = comb_cnt_logits_pred[i][mask_pos[i]]          # [n]\n            targets = comb_cnt_logits_target[i][mask_pos[i]]      # [n]\n        \n            cnt_loss = nn.functional.binary_cross_entropy_with_logits(input=preds, \\\n                                target=targets, reduction='none') # [n]\n            cnt_loss = torch.sum(cnt_loss)                        # [1]\n            cnt_loss_batch.append(cnt_loss)\n\n        cnt_loss_batch = torch.stack(cnt_loss_batch, dim=0)       # [B]\n        cnt_loss_batch = cnt_loss_batch / num_pos                 # [B]\n        return cnt_loss_batch.mean()                              # [1]\n        \n        \n    def compute_coordinate_reg_loss(self, comb_reg_values_pred, comb_reg_values_target, mask_pos):\n        # comb_reg_values_pred   : [B x sum of all H*W x 4]\n        # comb_reg_values_target : [B x sum of all H*W x 4]\n        # mask_pos               : [B x sum of all H*W x 1]\n        \n        num_pos = torch.sum(mask_pos, dim=[1, 2]).clamp_(min=1).float()     # [B]\n        \n        reg_loss_batch = []\n        batch_size = comb_reg_values_pred.shape[0]\n        for i in range(batch_size):\n            pred_pos = comb_reg_values_pred[i][mask_pos[i, :, 0]]           # [n, 4]\n            target_pos = comb_reg_values_target[i][mask_pos[i, :, 0]]       # [n, 4]\n            \n            if self.regression_loss_type == 'iou':\n                reg_loss = self.iou_loss(pred_pos, target_pos)  # [1]\n            elif self.regression_loss_type == 'giou':\n                reg_loss = self.giou_loss(pred_pos, target_pos) # [1]\n            else:\n                raise NotImplementedError(f\"Regression Loss type: {self.regression_loss_type} is not supported.\")    \n            reg_loss_batch.append(reg_loss)\n            \n        reg_loss_batch = torch.stack(reg_loss_batch, dim=0)     # [B]\n        reg_loss_batch = reg_loss_batch / num_pos\n        return reg_loss_batch.mean()                            # [1]\n    \n    \n    def iou_loss(self, pred_pos, target_pos):\n        # pred_pos      : [n, 4]    : [left_x, top_y, right_x, bottom_y]\n        # target_pos    : [n, 4]    : [left_x, top_y, right_x, bottom_y]\n        \n        x1y1_intersection = torch.min(pred_pos[:, :2], target_pos[:, :2])   # [n, 2]\n        x2y2_intersection = torch.min(pred_pos[:, 2:], target_pos[:, 2:])   # [n, 2]\n        wh = (x1y1_intersection + x2y2_intersection).clamp(min=0)           # [n, 2]\n        overlap_area = wh[:, 0] * wh[:, 1]                                  # [n]\n        area1 = (pred_pos[:, 2] + pred_pos[:, 0]) \\\n                    * (pred_pos[:, 3] + pred_pos[:, 1])             # [n]\n        area2 = (target_pos[:, 2] + target_pos[:, 0]) \\\n                    * (target_pos[:, 3] + target_pos[:, 1])         # [n]\n        \n        iou = overlap_area / (area1 + area2 - overlap_area + 1e-9)  # [n]\n        \n        iou_loss = -torch.log(iou.clamp(1e-9))                      # [n]\n        \n        return iou_loss.sum()                                       # [1]\n        \n    \n    def giou_loss(self, pred_pos, target_pos):\n        # pred_pos      : [n, 4]    : [left_x, top_y, right_x, bottom_y]\n        # target_pos    : [n, 4]    : [left_x, top_y, right_x, bottom_y]\n        \n        x1y1_outer = torch.max(pred_pos[:, :2], target_pos[:, :2])   # [n, 2]\n        x2y2_outer = torch.max(pred_pos[:, 2:], target_pos[:, 2:])   # [n, 2]\n        wh_outer = (x1y1_outer + x2y2_outer).clamp(min=0)            # [n, 2]\n        outer_area = wh_outer[:, 0] * wh_outer[:, 1]                 # [n]\n        \n        x1y1_intersection = torch.min(pred_pos[:, :2], target_pos[:, :2])   # [n, 2]\n        x2y2_intersection = torch.min(pred_pos[:, 2:], target_pos[:, 2:])   # [n, 2]\n        wh = (x1y1_intersection + x2y2_intersection).clamp(min=0)           # [n, 2]\n        overlap_area = wh[:, 0] * wh[:, 1]                                  # [n]\n        area1 = (pred_pos[:, 2] + pred_pos[:, 0]) \\\n                    * (pred_pos[:, 3] + pred_pos[:, 1])             # [n]\n        area2 = (target_pos[:, 2] + target_pos[:, 0]) \\\n                    * (target_pos[:, 3] + target_pos[:, 1])         # [n]\n        \n        union = area1 + area2 - overlap_area                        # [n]\n        iou = overlap_area / (union + 1e-9)                         # [n]\n\n        giou_loss = 1 - iou + \\\n                        ((outer_area - union) / (outer_area + 1e-9))    # [n] \n    \n        return giou_loss.sum()                                      # [1]\n    \n    \nif __name__ == '__main__':\n    import sys\n    import numpy as np\n    sys.path.append(\"../\")\n    import config_temp as config\n    loss_fn = FCOSLoss(limit_range=config.limit_range, central_sampling=config.central_sampling, \\\n                        central_sampling_radius=config.central_sampling_radius, strides=config.strides, \\\n                        regression_loss_type=config.regression_loss_type, num_classes=config.num_classes)\n    \n    cls_probs_pred = []\n    cnt_logits_pred = []\n    reg_values_pred = []\n    batch_bboxes = []\n    for s in config.strides:\n        f_h, f_w = config.input_size[0] // s, config.input_size[1] // s\n        \n        cls_probs_pred.append(torch.randn(1, config.num_classes, f_h, f_w))\n        cnt_logits_pred.append(torch.randn(1, 1, f_h, f_w))\n        reg_values_pred.append(torch.randn(1, 4, f_h, f_w))\n        \n        rnd_num = np.random.randint(low=1, high=10)\n        pad_len = 10 - rnd_num\n        bbox = torch.randn(1, rnd_num, 5)\n        bbox = torch.nn.functional.pad(bbox, pad=(0, 0, 0, pad_len))        \n        batch_bboxes.append(bbox)\n        \n    prediction = [cls_probs_pred, cnt_logits_pred, reg_values_pred]\n    \n    batch_bboxes = torch.cat(batch_bboxes, dim=1)\n    \n    loss_fn(prediction, batch_bboxes)", "meta": {"hexsha": "98d402ebb1b0a0d377a58b6149be713bd8c30f1b", "size": 18016, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/FCOSLoss.py", "max_stars_repo_name": "meet-minimalist/FCOS-Pytorch-Implementation", "max_stars_repo_head_hexsha": "e8ac1c6230174902732dbe8bcff3a87034f99517", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/FCOSLoss.py", "max_issues_repo_name": "meet-minimalist/FCOS-Pytorch-Implementation", "max_issues_repo_head_hexsha": "e8ac1c6230174902732dbe8bcff3a87034f99517", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/FCOSLoss.py", "max_forks_repo_name": "meet-minimalist/FCOS-Pytorch-Implementation", "max_forks_repo_head_hexsha": "e8ac1c6230174902732dbe8bcff3a87034f99517", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.6783625731, "max_line_length": 117, "alphanum_fraction": 0.5501221137, "include": true, "reason": "import numpy", "num_tokens": 4948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.2942149721629888, "lm_q1q2_score": 0.17102807263217604}}
{"text": "\nimport time, os, math\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom body_model.body_model import BodyModel\nfrom body_model.utils import SMPLH_PATH, SMPL_JOINTS, VPOSER_PATH, SMPL_PARENTS, KEYPT_VERTS\nfrom utils.transforms import rotation_matrix_to_angle_axis\nfrom datasets.amass_utils import CONTACT_INDS\n\nNUM_BODY_JOINTS = len(SMPL_JOINTS) - 1\nBETA_SIZE = 16\nCONTACT_THRESH = 0.5\n\nclass HumorLoss(nn.Module):\n\n    def __init__(self,\n                    kl_loss=1.0,\n                    kl_loss_anneal_start=0,\n                    kl_loss_anneal_end=0,\n                    kl_loss_cycle_len=-1, # if > 0 will anneal KL loss cyclicly\n                    regr_trans_loss=1.0,\n                    regr_trans_vel_loss=1.0,\n                    regr_root_orient_loss=1.0,\n                    regr_root_orient_vel_loss=1.0,\n                    regr_pose_loss=1.0,\n                    regr_pose_vel_loss=1.0,\n                    regr_joint_loss=1.0,\n                    regr_joint_vel_loss=1.0,\n                    regr_joint_orient_vel_loss=1.0,\n                    regr_vert_loss=1.0,\n                    regr_vert_vel_loss=1.0,\n                    contacts_loss=0.0, # classification loss on binary contact prediction\n                    contacts_vel_loss=0.0, # velocity near 0 at predicted contacts\n                    smpl_joint_loss=0.0,\n                    smpl_mesh_loss=0.0,\n                    smpl_joint_consistency_loss=0.0,\n                    smpl_vert_consistency_loss=0.0,\n                    smpl_batch_size=480):\n        super(HumorLoss, self).__init__()\n        '''\n        All loss inputs are weights for that loss term. If the weight is 0, the loss is not used.\n\n        - regr_*_loss :                 L2 regression losses on various state terms (root trans/orient, body pose, joint positions, and joint velocities)\n        - smpl_joint_loss :             L2 between GT joints and joint locations resulting from SMPL model (parameterized by trans/orient/body poase)\n        - smpl_mesh_loss :              L2 between GT and predicted vertex locations resulting from SMPL model (parameterized by trans/orient/body poase)\n        - smpl_joint_consistency_loss : L2 between regressed joints and predicted joint locations from SMPL model (ensures consistency between\n                                        state joint locations and joint angle predictions)\n        - kl_loss :                     divergence between predicted posterior and prior\n\n        - smpl_batch_size : the size of batches that will be given to smpl. if less than this is passed in, will be padded accordingly. however, passed\n                            in batches CANNOT be greater than this number.\n        '''\n        self.kl_loss_weight = kl_loss\n        self.kl_loss_anneal_start = kl_loss_anneal_start\n        self.kl_loss_anneal_end = kl_loss_anneal_end\n        self.use_kl_anneal = self.kl_loss_anneal_end > self.kl_loss_anneal_start\n\n        self.kl_loss_cycle_len = kl_loss_cycle_len\n        self.use_kl_cycle = False\n        if self.kl_loss_cycle_len > 0:\n            self.use_kl_cycle = True\n            self.use_kl_anneal = False\n\n        self.contacts_loss_weight = contacts_loss\n        self.contacts_vel_loss_weight = contacts_vel_loss\n        self.bce_loss = nn.BCEWithLogitsLoss(reduction='none')\n\n        # build dict of all possible regression losses based on inputs\n        # keys must be the same as we expect from the pred/gt data\n        self.regr_loss_weight_dict = {\n            'trans' : regr_trans_loss,\n            'trans_vel' : regr_trans_vel_loss,\n            'root_orient' : regr_root_orient_loss,\n            'root_orient_vel' : regr_root_orient_vel_loss,\n            'pose_body' : regr_pose_loss,\n            'pose_body_vel' : regr_pose_vel_loss,\n            'joints' : regr_joint_loss,\n            'joints_vel' : regr_joint_vel_loss,\n            'joints_orient_vel' : regr_joint_orient_vel_loss,\n            'verts' : regr_vert_loss,\n            'verts_vel' : regr_vert_vel_loss\n        }\n\n        self.smpl_joint_loss_weight = smpl_joint_loss\n        self.smpl_mesh_loss_weight = smpl_mesh_loss\n        self.smpl_joint_consistency_loss_weight = smpl_joint_consistency_loss\n        self.smpl_vert_consistency_loss_weight = smpl_vert_consistency_loss\n\n        self.l2_loss = nn.MSELoss(reduction='none')\n        self.regr_loss = nn.MSELoss(reduction='none')\n\n        smpl_losses = [self.smpl_joint_loss_weight, self.smpl_mesh_loss_weight, self.smpl_joint_consistency_loss_weight, self.smpl_vert_consistency_loss_weight]\n        self.smpl_batch_size = smpl_batch_size\n        self.use_smpl_losses = False\n        if sum(smpl_losses) > 0.0:\n            self.use_smpl_losses = True\n            # need a body model to compute the losses\n            male_bm_path = os.path.join(SMPLH_PATH, 'male/model.npz')\n            self.male_bm = BodyModel(bm_path=male_bm_path, num_betas=16, batch_size=self.smpl_batch_size)\n            female_bm_path = os.path.join(SMPLH_PATH, 'female/model.npz')\n            self.female_bm = BodyModel(bm_path=female_bm_path, num_betas=16, batch_size=self.smpl_batch_size)\n\n    def forward(self, pred_dict, gt_dict, cur_epoch, gender=None, betas=None):\n        '''\n        Compute the loss.\n\n        All data in the dictionaries should be of size B x D.\n\n        group_regr_losses will be used to aggregate every group_regr_lossth batch idx together into\n        the stats_dict. This can be useful when there are multiple output steps and you want to track\n        each separately.\n        '''\n        loss = 0.0\n        stats_dict = dict()\n\n        #\n        # KL divergence\n        #\n        if self.kl_loss_weight > 0.0:\n            qm, qv = pred_dict['posterior_distrib']\n            pm, pv = pred_dict['prior_distrib']\n            kl_loss = self.kl_normal(qm, qv, pm, pv)\n            kl_stat_loss = kl_loss.mean()\n            kl_loss = kl_stat_loss\n            # print(kl_loss.size())\n            stats_dict['kl_loss'] = kl_stat_loss\n            anneal_weight = 1.0\n            if self.use_kl_anneal or self.use_kl_cycle:\n                anneal_epoch = cur_epoch\n                anneal_start = self.kl_loss_anneal_start\n                anneal_end = self.kl_loss_anneal_end\n                if self.use_kl_cycle:\n                    anneal_epoch = cur_epoch % self.kl_loss_cycle_len\n                    anneal_start = 0\n                    anneal_end = self.kl_loss_cycle_len // 2 # optimize full weight for second half of cycle\n                if anneal_epoch >= anneal_start:\n                    anneal_weight = (anneal_epoch - anneal_start) / (anneal_end - anneal_start)\n                else:\n                    anneal_weight = 0.0\n                anneal_weight = 1.0 if anneal_weight > 1.0 else anneal_weight\n\n            loss = loss + anneal_weight*self.kl_loss_weight*kl_loss\n\n            stats_dict['kl_anneal_weight'] = anneal_weight\n            stats_dict['kl_weighted_loss'] = loss\n\n        # \n        # Reconstruction \n        #\n\n        # regression terms\n        for cur_key in gt_dict.keys():\n            # print(cur_key)\n            if cur_key not in self.regr_loss_weight_dict:\n                continue\n            cur_regr_weight = self.regr_loss_weight_dict[cur_key]\n            if cur_regr_weight > 0.0:\n                pred_val = pred_dict[cur_key]\n                gt_val = gt_dict[cur_key]\n\n                if cur_key == 'root_orient' or cur_key == 'pose_body':\n                    # rotations use L2 for matrices\n                    cur_regr_loss = self.l2_loss(pred_val, gt_val)\n                else:\n                    cur_regr_loss = self.regr_loss(pred_val, gt_val)\n                agg_cur_regr_loss = cur_regr_loss\n                cur_regr_stat_loss = agg_cur_regr_loss.mean()\n                agg_cur_regr_loss = cur_regr_stat_loss\n                stats_dict[cur_key + '_loss'] = cur_regr_stat_loss\n                loss = loss + cur_regr_weight*agg_cur_regr_loss\n\n        if self.contacts_loss_weight > 0.0:\n            if 'contacts' in gt_dict.keys() and 'contacts' in pred_dict.keys():\n                gt_contacts = gt_dict['contacts']\n                pred_contacts = pred_dict['contacts']\n                # pred is assumed to be logits from network (i.e. sigmoid has not been applied yet)\n                cur_contacts_loss = self.bce_loss(pred_contacts, gt_contacts)\n                cur_stat_contacts_loss = cur_contacts_loss.mean()\n                cur_contacts_loss = cur_stat_contacts_loss\n                stats_dict['contacts_loss'] = cur_stat_contacts_loss\n                loss = loss + self.contacts_loss_weight*cur_contacts_loss\n\n                # other accuracy statistics\n                pred_contacts = (torch.sigmoid(pred_contacts) > CONTACT_THRESH).to(torch.bool)\n                gt_contacts = gt_contacts.to(torch.bool)\n                # counts for confusion matrix\n                # true positive (pred contact, labeled contact)\n                true_pos = pred_contacts & gt_contacts\n                true_pos_cnt = torch.sum(true_pos).to(torch.float)\n                # false positive (pred contact, not lebeled contact)\n                false_pos = pred_contacts & ~(gt_contacts)\n                false_pos_cnt = torch.sum(false_pos).to(torch.float)\n                # false negative (pred no contact, labeled contact)\n                false_neg = ~(pred_contacts) & gt_contacts\n                false_neg_cnt = torch.sum(false_neg).to(torch.float)\n                # true negative (pred no contact, no labeled contact)\n                true_neg = (~pred_contacts) & (~gt_contacts)\n                true_neg_cnt = torch.sum(true_neg).to(torch.float)\n\n                acc = (true_pos_cnt + true_neg_cnt) / (true_pos_cnt + false_pos_cnt + false_neg_cnt + true_neg_cnt)\n                pos_acc = true_pos_cnt / (true_pos_cnt + false_neg_cnt)\n                neg_acc = true_neg_cnt / (true_neg_cnt + false_pos_cnt)\n                stats_dict['contacts_acc'] = acc\n                stats_dict['contacts_pos_acc'] = pos_acc\n                stats_dict['contacts_neg_acc'] = neg_acc\n            else:\n                print('Cannot compute contact loss without contact pred/gt! Skipping...')\n            \n\n        if self.contacts_vel_loss_weight > 0.0:\n            if 'contacts' in pred_dict.keys() and 'joints_vel' in pred_dict.keys():\n                pred_contacts = torch.sigmoid(pred_dict['contacts'])\n                pred_joints_vel = pred_dict['joints_vel'].reshape((-1, len(SMPL_JOINTS), 3))\n                contact_joints_vel = pred_joints_vel[:,CONTACT_INDS,:]\n                # use predicted contact probability to weight regularization on joint velocity\n                vel_mag = torch.norm(contact_joints_vel, dim=-1)\n                cur_contact_vel_loss = pred_contacts*(vel_mag**2)\n                cur_stat_contact_vel_loss = cur_contact_vel_loss.mean()\n                cur_contact_vel_loss = cur_stat_contact_vel_loss\n                stats_dict['contacts_vel_loss'] = cur_stat_contact_vel_loss\n                loss = loss + self.contacts_vel_loss_weight*cur_contact_vel_loss\n            else:\n                print('Cannot compute contact vel loss without contact and joints_vel pred! Skipping...')\n\n        # terms requiring SMPL reconstruction\n        if self.use_smpl_losses:\n            if gender is None or betas is None:\n                raise Exception('Must pass gender and betas to MotionVAE loss to use SMPL losses!')\n            \n            try:\n                pred_trans = pred_dict['trans']\n                pred_orient = pred_dict['root_orient']\n                pred_pose = pred_dict['pose_body']\n                gt_trans = gt_dict['trans']\n                gt_orient = gt_dict['root_orient']\n                gt_pose = gt_dict['pose_body']\n            except KeyError:\n                print('ERROR: In order to use SMPL losses must have trans, root_orient, and pose_body in pred and gt dicts!')\n                exit()\n\n            # need to transform rotation matrices to aa for SMPL model\n            B = pred_trans.size(0)\n            pred_orient = rotation_matrix_to_angle_axis(pred_orient.reshape((B, 3, 3)))\n            gt_orient = rotation_matrix_to_angle_axis(gt_orient.reshape((B, 3, 3)))\n            pred_pose = rotation_matrix_to_angle_axis(pred_pose.reshape((B*NUM_BODY_JOINTS, 3, 3))).reshape((B, NUM_BODY_JOINTS*3))\n            gt_pose = rotation_matrix_to_angle_axis(gt_pose.reshape((B*NUM_BODY_JOINTS, 3, 3))).reshape((B, NUM_BODY_JOINTS*3))\n\n            pred_vals = [pred_trans, pred_orient, pred_pose]\n            gt_vals = [gt_trans, gt_orient, gt_pose, betas]\n\n            # have to split by gender to make sure we use the correct body model\n            gender_names = ['male', 'female']\n            mask_list = []\n            pred_joints = []\n            pred_mesh = []\n            gt_joints = []\n            gt_mesh = []\n            for gender_name in gender_names:\n                # print(gender_name)\n                gender_idx = gender[:, 0] == gender_name\n                mask_list.append(gender_idx)\n                cur_pred_vals = [val[gender_idx] for val in pred_vals] \n                cur_gt_vals = [val[gender_idx] for val in gt_vals]\n\n                # need to pad extra frames with zeros in case not as long as expected \n                pad_size = self.smpl_batch_size - cur_pred_vals[0].size(0)\n                if pad_size == self.smpl_batch_size:\n                    # skip if no frames for this gender\n                    continue\n                pad_list = cur_pred_vals + cur_gt_vals\n                if pad_size < 0:\n                    raise Exception('SMPL model batch size not large enough to accomodate!')\n                elif pad_size > 0:\n                    pad_list = self.zero_pad_tensors(pad_list, pad_size)\n                \n                # reconstruct SMPL\n                cur_pred_trans, cur_pred_orient, cur_pred_pose, cur_gt_trans, cur_gt_orient, cur_gt_pose, cur_betas = pad_list\n                bm = self.male_bm if gender_name == 'male' else self.female_bm\n                pred_body = bm(pose_body=cur_pred_pose, betas=cur_betas, root_orient=cur_pred_orient, trans=cur_pred_trans)\n                gt_body = bm(pose_body=cur_gt_pose, betas=cur_betas, root_orient=cur_gt_orient, trans=cur_gt_trans)\n                if pad_size > 0:\n                    pred_joints.append(pred_body.Jtr[:-pad_size])\n                    pred_mesh.append(pred_body.v[:-pad_size])\n                    gt_joints.append(gt_body.Jtr[:-pad_size])\n                    gt_mesh.append(gt_body.v[:-pad_size])\n                else:\n                    pred_joints.append(pred_body.Jtr)\n                    pred_mesh.append(pred_body.v)\n                    gt_joints.append(gt_body.Jtr)\n                    gt_mesh.append(gt_body.v)\n\n            pred_joints = torch.cat(pred_joints, axis=0)[:,:len(SMPL_JOINTS),:]\n            pred_mesh = torch.cat(pred_mesh, axis=0)\n            gt_joints = torch.cat(gt_joints, axis=0)[:,:len(SMPL_JOINTS),:]\n            gt_mesh = torch.cat(gt_mesh, axis=0)\n\n            pred_verts = pred_mesh[:,KEYPT_VERTS,:]\n            gt_verts = gt_mesh[:,KEYPT_VERTS,:]\n\n            # now compute SMPL-related losses\n            if self.smpl_joint_loss_weight > 0.0:\n                smpl_joint_loss = self.regr_loss(pred_joints, gt_joints)\n                smpl_joint_stat_loss = smpl_joint_loss.mean()\n                smpl_joint_loss = smpl_joint_stat_loss\n                stats_dict['smpl_joint_loss'] = smpl_joint_stat_loss\n                loss = loss + self.smpl_joint_loss_weight*smpl_joint_loss\n            if self.smpl_mesh_loss_weight > 0.0:\n                smpl_mesh_loss = self.regr_loss(pred_mesh, gt_mesh)\n                smpl_mesh_stat_loss = smpl_mesh_loss.mean()\n                smpl_mesh_loss = smpl_mesh_stat_loss\n                stats_dict['smpl_mesh_loss'] = smpl_mesh_stat_loss\n                loss = loss + self.smpl_mesh_loss_weight*smpl_mesh_loss\n            if self.smpl_joint_consistency_loss_weight > 0.0:\n                if not 'joints' in pred_dict.keys():\n                    print('Must regress joints in order to use smpl joint consistency loss!')\n                    exit()\n                regressed_joints = pred_dict['joints'].reshape((B, len(SMPL_JOINTS), -1))\n                # need to reorder regressed joints with mask_list to ensure consistency with smpl joints\n                regressed_joints = torch.cat([regressed_joints[mask_list[i]] for i in range(len(mask_list))], axis=0)\n\n                smpl_joint_consistency_loss = self.regr_loss(pred_joints, regressed_joints)\n                smpl_joint_consistency_stat_loss = smpl_joint_consistency_loss.mean()\n                smpl_joint_consistency_loss = smpl_joint_consistency_stat_loss\n                stats_dict['smpl_joint_consistency_loss'] = smpl_joint_consistency_stat_loss\n                loss = loss + self.smpl_joint_consistency_loss_weight*smpl_joint_consistency_loss\n            if self.smpl_vert_consistency_loss_weight > 0.0:\n                if not 'verts' in pred_dict.keys():\n                    print('Must regress verts in order to use smpl vert consistency loss!')\n                    exit()\n                regressed_verts = pred_dict['verts'].reshape((B, len(KEYPT_VERTS), -1))\n                # need to reorder regressed verts with mask_list to ensure consistency with smpl verts\n                regressed_verts = torch.cat([regressed_verts[mask_list[i]] for i in range(len(mask_list))], axis=0)\n\n                smpl_vert_consistency_loss = self.regr_loss(pred_verts, regressed_verts)\n                smpl_vert_consistency_stat_loss = smpl_vert_consistency_loss.mean()\n                smpl_vert_consistency_loss = smpl_vert_consistency_stat_loss\n                stats_dict['smpl_vert_consistency_loss'] = smpl_vert_consistency_stat_loss\n                loss = loss + self.smpl_vert_consistency_loss_weight*smpl_vert_consistency_loss\n\n        if self.kl_loss_weight > 0.0:\n            stats_dict['reconstr_weighted_loss'] = loss - stats_dict['kl_weighted_loss']\n        \n        return loss, stats_dict\n\n    def zero_pad_tensors(self, pad_list, pad_size):\n        '''\n        Assumes tensors in pad_list are B x D\n        '''\n        new_pad_list = []\n        for pad_idx, pad_tensor in enumerate(pad_list):\n            padding = torch.zeros((pad_size, pad_tensor.size(1))).to(pad_tensor)\n            new_pad_list.append(torch.cat([pad_tensor, padding], dim=0))\n        return new_pad_list\n\n    \n    def kl_normal(self, qm, qv, pm, pv):\n        \"\"\"\n        Computes the elem-wise KL divergence between two normal distributions KL(q || p) and\n        sum over the last dimension\n        ​\n        Args:\n            qm: tensor: (batch, dim): q mean\n            qv: tensor: (batch, dim): q variance\n            pm: tensor: (batch, dim): p mean\n            pv: tensor: (batch, dim): p variance\n        ​\n        Return:\n            kl: tensor: (batch,): kl between each sample\n        \"\"\"\n        element_wise = 0.5 * (torch.log(pv) - torch.log(qv) + qv / pv + (qm - pm).pow(2) / pv - 1)\n        kl = element_wise.sum(-1)\n        return kl\n\n    def log_normal(self, x, m, v):\n        \"\"\"\n        Computes the elem-wise log probability of a Gaussian and then sum over the\n        last dim. Basically we're assuming all dims are batch dims except for the\n        last dim.    Args:\n            x: tensor: (batch_1, batch_2, ..., batch_k, dim): Observation\n            m: tensor: (batch_1, batch_2, ..., batch_k, dim): Mean\n            v: tensor: (batch_1, batch_2, ..., batch_k, dim): Variance    Return:\n            log_prob: tensor: (batch_1, batch_2, ..., batch_k): log probability of\n                each sample. Note that the summation dimension is not kept\n        \"\"\"\n        log_prob = -torch.log(torch.sqrt(v)) - math.log(math.sqrt(2*math.pi)) \\\n                        - ((x - m)**2 / (2*v))\n        log_prob = torch.sum(log_prob, dim=-1)\n        return log_prob\n\n    ", "meta": {"hexsha": "3556356ce6559bc8019c5fb8157376d8f2a8d463", "size": 19973, "ext": "py", "lang": "Python", "max_stars_repo_path": "humor/losses/humor_loss.py", "max_stars_repo_name": "DalhousieAI/humor", "max_stars_repo_head_hexsha": "1d2ceaed71241ec9e69ffa987bcc562bc414465f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 143, "max_stars_repo_stars_event_min_datetime": "2021-10-09T22:10:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:33:19.000Z", "max_issues_repo_path": "humor/losses/humor_loss.py", "max_issues_repo_name": "DalhousieAI/humor", "max_issues_repo_head_hexsha": "1d2ceaed71241ec9e69ffa987bcc562bc414465f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2021-10-12T07:49:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T09:44:34.000Z", "max_forks_repo_path": "humor/losses/humor_loss.py", "max_forks_repo_name": "DalhousieAI/humor", "max_forks_repo_head_hexsha": "1d2ceaed71241ec9e69ffa987bcc562bc414465f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2021-10-10T10:41:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T02:37:33.000Z", "avg_line_length": 50.8218829517, "max_line_length": 160, "alphanum_fraction": 0.6087217744, "include": true, "reason": "import numpy", "num_tokens": 4587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.2814056074291439, "lm_q1q2_score": 0.1709998234191439}}
{"text": "#!/usr/bin/env python3\n\n#\n# https://github.com/mseitzer/pytorch-fid\n#\n\n\"\"\"Calculates the Frechet Inception Distance (FID) to evalulate GANs\n\nThe FID metric calculates the distance between two distributions of images.\nTypically, we have summary statistics (mean & covariance matrix) of one\nof these distributions, while the 2nd distribution is given by a GAN.\n\nWhen run as a stand-alone program, it compares the distribution of\nimages that are stored as PNG/JPEG at a specified location with a\ndistribution given by summary statistics (in pickle format).\n\nThe FID is calculated by assuming that X_1 and X_2 are the activations of\nthe pool_3 layer of the inception net for generated samples and real world\nsamples respectively.\n\nSee --help to see further details.\n\nCode apapted from https://github.com/bioinf-jku/TTUR to use PyTorch instead\nof Tensorflow\n\nCopyright 2018 Institute of Bioinformatics, JKU Linz\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n   http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport os\nimport pathlib\nfrom argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\n\nimport numpy as np\nimport torch\nfrom scipy import linalg\nfrom torch.nn.functional import adaptive_avg_pool2d\n\nfrom PIL import Image\n\ntry:\n\tfrom tqdm import tqdm\nexcept ImportError:\n\t# If not tqdm is not available, provide a mock version of it\n\tdef tqdm(x): return x\n\nfrom .inceptionV3 import InceptionV3\n\ncuda = True if torch.cuda.is_available() else False\n\n\n\nparser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)\nparser.add_argument('path', type=str, nargs=2,\n\t\t\t\t\thelp=('Path to the generated images or '\n\t\t\t\t\t\t  'to .npz statistic files'))\nparser.add_argument('--batch-size', type=int, default=50,\n\t\t\t\t\thelp='Batch size to use')\nparser.add_argument('--dims', type=int, default=2048,\n\t\t\t\t\tchoices=list(InceptionV3.BLOCK_INDEX_BY_DIM),\n\t\t\t\t\thelp=('Dimensionality of Inception features to use. '\n\t\t\t\t\t\t  'By default, uses pool3 features'))\nparser.add_argument('-c', '--gpu', default='', type=str,\n\t\t\t\t\thelp='GPU to use (leave blank for CPU only)')\n\n\n\n\ndef calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):\n\t\"\"\"Numpy implementation of the Frechet Distance.\n\tThe Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)\n\tand X_2 ~ N(mu_2, C_2) is\n\t\t\td^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).\n\n\tStable version by Dougal J. Sutherland.\n\n\tParams:\n\t-- mu1   : Numpy array containing the activations of a layer of the\n\t\t\t   inception net (like returned by the function 'get_predictions')\n\t\t\t   for generated samples.\n\t-- mu2   : The sample mean over activations, precalculated on an\n\t\t\t   representative data set.\n\t-- sigma1: The covariance matrix over activations for generated samples.\n\t-- sigma2: The covariance matrix over activations, precalculated on an\n\t\t\t   representative data set.\n\n\tReturns:\n\t--   : The Frechet Distance.\n\t\"\"\"\n\n\tmu1 = np.atleast_1d(mu1)\n\tmu2 = np.atleast_1d(mu2)\n\n\tsigma1 = np.atleast_2d(sigma1)\n\tsigma2 = np.atleast_2d(sigma2)\n\n\tassert mu1.shape == mu2.shape, \\\n\t\t'Training and test mean vectors have different lengths'\n\tassert sigma1.shape == sigma2.shape, \\\n\t\t'Training and test covariances have different dimensions'\n\n\tdiff = mu1 - mu2\n\n\t# Product might be almost singular\n\tcovmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)\n\tif not np.isfinite(covmean).all():\n\t\tmsg = ('fid calculation produces singular product; '\n\t\t\t   'adding %s to diagonal of cov estimates') % eps\n\t\tprint(msg)\n\t\toffset = np.eye(sigma1.shape[0]) * eps\n\t\tcovmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))\n\n\t# Numerical error might give slight imaginary component\n\tif np.iscomplexobj(covmean):\n\t\tif not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):\n\t\t\tm = np.max(np.abs(covmean.imag))\n\t\t\traise ValueError('Imaginary component {}'.format(m))\n\t\tcovmean = covmean.real\n\n\ttr_covmean = np.trace(covmean)\n\n\treturn (diff.dot(diff) + np.trace(sigma1) +\n\t\t\tnp.trace(sigma2) - 2 * tr_covmean)\n\n\n\n\n\n\ndef get_activations(batch, model, batch_size=50, dims=2048):\n\n\tmodel.eval()\n\n\tif batch_size > batch.shape[0]:\n\t\tprint(('Warning: batch size is bigger than the data size. '\n\t\t\t   'Setting batch size to data size'))\n\t\tbatch_size = batch.shape[0]\n\n\tpred_arr = np.empty((batch.shape[0], dims))\n\n\tfor i in tqdm(range(0, batch.shape[0], batch_size)): #tqdm: progressive bar\n\n\t\tstart = i\n\t\tend = i + batch_size\n\n\t\tdata = batch[start:end]\n\n\t\tif cuda:\n\t\t\tdata=data.type(torch.cuda.FloatTensor)\n\n\t\t#pred = model(batch)[0]\n\t\tpred = model(data)[0]\n\n\t\t# If model output is not scalar, apply global spatial average pooling.\n\t\t# This happens if you choose a dimensionality not equal 2048.\n\t\tif pred.size(2) != 1 or pred.size(3) != 1:\n\t\t\tpred = adaptive_avg_pool2d(pred, output_size=(1, 1))\n\n\t\tpred_arr[start:end] = pred.cpu().data.numpy().reshape(pred.size(0), -1)\n\n\treturn pred_arr\n\ndef calculate_activation_statistics(batch, model, batch_size=50, dims=2048):\n\n\tact = get_activations(batch, model, batch_size, dims)\n\tmu = np.mean(act, axis=0)\n\tsigma = np.cov(act, rowvar=False)\n\treturn mu, sigma\n\n\ndef _compute_statistics_of_batch(batch, model, batch_size, dims):\n\t\n\tm, s = calculate_activation_statistics(batch, model, batch_size, dims)\n\n\treturn m, s\n\n\n#def calculate_fid_given_paths(paths, batch_size, cuda, dims):\ndef calculate_fid_given_batches(batch1, batch2, batch_size, dims=2048):\n\n\n\t# gray image\n\tif batch1.shape[1] < 3:  batch1 = batch1.expand(-1,3,-1,-1) \n\tif batch2.shape[1] < 3:  batch2 = batch2.expand(-1,3,-1,-1) \n\n\tblock_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims]\n\n\tmodel = InceptionV3([block_idx])\n\n\tif cuda:\n\t\tmodel.cuda()\n\n\n\tm1, s1 = _compute_statistics_of_batch(batch1, model, batch_size, dims)\n\tm2, s2 = _compute_statistics_of_batch(batch2, model, batch_size, dims)\n\tfid_value = calculate_frechet_distance(m1, s1, m2, s2)\n\n\treturn fid_value\n\n\nif __name__ == '__main__':\n\targs = parser.parse_args()\n\tos.environ['CUDA_VISIBLE_DEVICES'] = args.gpu\n\n\tfid_value = calculate_fid_given_paths(args.path, args.batch_size, args.gpu != '', args.dims)\n\tprint('FID: ', fid_value)\n", "meta": {"hexsha": "97281bb85404f36f269bf7958ec2fce7ebd76210", "size": 6475, "ext": "py", "lang": "Python", "max_stars_repo_path": "util/fid_score.py", "max_stars_repo_name": "Tak-jae-ho/RGBD-GAN-pytorch", "max_stars_repo_head_hexsha": "4fb1bc1de7b7807fd4f2d346d9b688a2d257eedb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "util/fid_score.py", "max_issues_repo_name": "Tak-jae-ho/RGBD-GAN-pytorch", "max_issues_repo_head_hexsha": "4fb1bc1de7b7807fd4f2d346d9b688a2d257eedb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-10-30T18:31:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-30T18:31:10.000Z", "max_forks_repo_path": "util/fid_score.py", "max_forks_repo_name": "Tak-jae-ho/RGBD-GAN-pytorch", "max_forks_repo_head_hexsha": "4fb1bc1de7b7807fd4f2d346d9b688a2d257eedb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-30T19:00:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-30T19:00:18.000Z", "avg_line_length": 29.8387096774, "max_line_length": 93, "alphanum_fraction": 0.7345173745, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.17097468334722268}}
{"text": "\"\"\"Eigensolvers with a few extra computation methods\n\nThe :class:`.Solver` class is the main interface for dealing with eigenvalue problems. It\nis made to work specifically with pybinding's :class:`.Model` objects, but it may use any\neigensolver algorithm under the hood.\n\nA few different algorithms are provided out of the box: the :func:`.lapack`, :func:`.arpack`\nand :func:`.feast` functions return concrete :class:`.Solver` implementation using the LAPACK,\nARPACK and FEAST algorithms, respectively.\n\nThe :class:`.Solver` may easily be extended with new eigensolver algorithms. All that is\nrequired is a function which takes a Hamiltonian matrix and returns the computed\neigenvalues and eigenvectors. See :class:`._SolverPythonImpl` for example.\n\"\"\"\nimport time\nimport math\n\nimport numpy as np\n\nfrom . import _cpp\nfrom . import results\nfrom .model import Model\nfrom .system import System\n\n__all__ = ['Solver', 'arpack', 'feast', 'lapack']\n\n\nclass Solver:\n    \"\"\"Computes the eigenvalues and eigenvectors of a Hamiltonian matrix\n\n    This the common interface for various eigensolver implementations. It should not\n    be created directly, but via the specific functions: :func:`.lapack`, :func:`.arpack`\n    and :func:`.feast`. Those functions will set up their specific solver strategy and\n    return a properly configured :class:`.Solver` object.\n    \"\"\"\n    def __init__(self, impl: _cpp.Solver):\n        self.impl = impl\n\n    @property\n    def model(self) -> Model:\n        \"\"\"The tight-binding model attached to this solver\"\"\"\n        return self.impl.model\n\n    @model.setter\n    def model(self, model):\n        self.impl.model = model\n\n    @property\n    def system(self) -> System:\n        \"\"\"The tight-binding system attached to this solver (shortcut for Solver.model.system)\"\"\"\n        return System(self.impl.system, self.model.lattice)\n\n    @property\n    def eigenvalues(self) -> np.ndarray:\n        \"\"\"1D array of computed energy states\"\"\"\n        return self.impl.eigenvalues\n\n    @property\n    def eigenvectors(self) -> np.ndarray:\n        \"\"\"2D array where each column represents a wave function\n\n        eigenvectors.shape == (system.num_sites, eigenvalues.size)\n        \"\"\"\n        return self.impl.eigenvectors\n\n    def solve(self):\n        \"\"\"Explicitly solve the eigenvalue problem right now\n\n        This method is usually not needed because the main result properties,\n        :attr:`.eigenvalues` and :attr:`.eigenvectors`, will call this implicitly\n        the first time they are accessed. However, since the :meth:`solve()` routine\n        may be computationally expensive, it is useful to have the ability to call it\n        ahead of time as needed.\n        \"\"\"\n        self.impl.solve()\n\n    def clear(self):\n        \"\"\"Clear the computed results and start over\"\"\"\n        self.impl.clear()\n\n    def report(self, shortform=False) -> str:\n        \"\"\"Return a report of the last :meth:`solve()` computation\n\n        Parameters\n        ----------\n        shortform : bool, optional\n            Return a short one line version of the report\n        \"\"\"\n        return self.impl.report(shortform)\n\n    def set_wave_vector(self, k):\n        \"\"\"Set the wave vector for periodic models\n\n        Parameters\n        ----------\n        k : array_like\n            Wave vector in reciprocal space.\n        \"\"\"\n        self.clear()\n        self.model.set_wave_vector(k)\n\n    def calc_eigenvalues(self, map_probability_at=None):\n        \"\"\"Return an :class:`.Eigenvalues` result object with an optional probability colormap\n\n        While the :attr:`.eigenvalues` property returns the raw values array, this\n        method returns a result object with more data. In addition to the energy\n        states, this result may show a colormap of the probability density for each\n        state at a single position.\n\n        Parameters\n        ----------\n        map_probability_at : array_like, optional\n            Cartesian position where the probability density of each energy state\n            should be calculated.\n\n        Returns\n        -------\n        :class:`~pybinding.Eigenvalues`\n        \"\"\"\n        if not map_probability_at:\n            return results.Eigenvalues(self.eigenvalues)\n        else:\n            site_idx = self.system.find_nearest(position=map_probability_at)\n            probability = abs(self.eigenvectors[site_idx, :])**2\n\n            # sum probabilities of degenerate states\n            for idx in self.find_degenerate_states(self.eigenvalues):\n                probability[idx] = np.sum(probability[idx]) / len(idx)\n\n            return results.Eigenvalues(self.eigenvalues, probability)\n\n    def calc_probability(self, n, reduce=1e-5):\n        r\"\"\"Calculate the spatial probability density\n\n        .. math::\n            \\text{P}(r) = |\\Psi_n(r)|^2\n\n        for each position :math:`r` in `system.positions` where :math:`\\Psi_n(r)`\n        is `eigenvectors[:, n]`.\n\n        Parameters\n        ----------\n        n : int or array_like\n            Index of the desired eigenstate. If an array of indices is given, the\n            probability will be calculated at each one and a sum will be returned.\n        reduce : float, optional\n            Reduce degenerate states by summing their probabilities. Neighboring\n            states are considered degenerate if their energy is difference is lower\n            than the value of `reduce`. This is disabled by passing `reduce=0`.\n\n        Returns\n        -------\n        :class:`~pybinding.StructureMap`\n        \"\"\"\n        if reduce and np.isscalar(n):\n            n = np.flatnonzero(abs(self.eigenvalues[n] - self.eigenvalues) < reduce)\n\n        probability = abs(self.eigenvectors[:, n]) ** 2\n        if probability.ndim > 1:\n            probability = np.sum(probability, axis=1)\n        return self.system.with_data(probability)\n\n    def calc_dos(self, energies, broadening):\n        r\"\"\"Calculate the density of states as a function of energy\n\n        .. math::\n            \\text{DOS}(E) = \\frac{1}{c \\sqrt{2\\pi}}\n                            \\sum_n{e^{-\\frac{(E_n - E)^2}{2 c^2}}}\n\n        for each :math:`E` in `energies`, where :math:`c` is `broadening` and\n        :math:`E_n` is `eigenvalues[n]`.\n\n        Parameters\n        ----------\n        energies : array_like\n            Values for which the DOS is calculated.\n        broadening : float\n            Controls the width of the Gaussian broadening applied to the DOS.\n\n        Returns\n        -------\n        :class:`~pybinding.Series`\n        \"\"\"\n        if hasattr(self.impl, 'calc_dos'):\n            dos = self.impl.calc_dos(energies, broadening)\n        else:\n            scale = 1 / (broadening * math.sqrt(2 * math.pi))\n            delta = self.eigenvalues[:, np.newaxis] - energies\n            dos = scale * np.sum(np.exp(-0.5 * delta**2 / broadening**2), axis=0)\n        return results.Series(energies, dos, labels=dict(variable=\"E (eV)\", data=\"DOS\"))\n\n    def calc_ldos(self, energies, broadening, position, sublattice=\"\", reduce=True):\n        r\"\"\"Calculate the local density of states as a function of energy at the given position\n\n        .. math::\n            \\text{LDOS}(E) = \\frac{1}{c \\sqrt{2\\pi}}\n                             \\sum_n{|\\Psi_n(r)|^2 e^{-\\frac{(E_n - E)^2}{2 c^2}}}\n\n        for each :math:`E` in `energies`, where :math:`c` is `broadening`,\n        :math:`E_n` is `eigenvalues[n]` and :math:`r` is a single site position\n        determined by the arguments `position` and `sublattice`.\n\n        Parameters\n        ----------\n        energies : array_like\n            Values for which the DOS is calculated.\n        broadening : float\n            Controls the width of the Gaussian broadening applied to the DOS.\n        position : array_like\n            Cartesian position of the lattice site for which the LDOS is calculated.\n            Doesn't need to be exact: the method will find the actual site which is\n            closest to the given position.\n        sublattice : str\n            Only look for sites of a specific sublattice, closest to `position`.\n            The default value considers any sublattice.\n        reduce : bool\n            This option is only relevant for multi-orbital models. If true, the\n            resulting LDOS will summed over all the orbitals at the target site\n            and the result will be a 1D array. If false, the individual orbital\n            results will be preserved and the result will be a 2D array with\n            `shape == (energy.size, num_orbitals)`.\n\n        Returns\n        -------\n        :class:`~pybinding.Series`\n        \"\"\"\n        if hasattr(self.impl, 'calc_ldos'):\n            ldos = self.impl.calc_ldos(energies, broadening, position, sublattice)\n        else:\n            delta = self.eigenvalues[:, np.newaxis] - energies\n            gaussian = np.exp(-0.5 * delta**2 / broadening**2)\n            scale = 1 / (broadening * math.sqrt(2 * math.pi))\n\n            sys_idx = self.system.find_nearest(position, sublattice)\n            ham_idx = self.system.to_hamiltonian_indices(sys_idx)\n\n            def calc_single(index):\n                psi2 = np.abs(self.eigenvectors[index])**2\n                return scale * np.sum(psi2[:, np.newaxis] * gaussian, axis=0)\n\n            ldos = np.array([calc_single(i) for i in ham_idx]).T\n            if reduce:\n                ldos = np.sum(ldos, axis=1)\n\n        return results.Series(energies, ldos.squeeze(), labels=dict(variable=\"E (eV)\", data=\"LDOS\",\n                                                                    columns=\"orbitals\"))\n\n    def calc_spatial_ldos(self, energy, broadening):\n        r\"\"\"Calculate the spatial local density of states at the given energy\n\n        .. math::\n            \\text{LDOS}(r) = \\frac{1}{c \\sqrt{2\\pi}}\n                             \\sum_n{|\\Psi_n(r)|^2 e^{-\\frac{(E_n - E)^2}{2 c^2}}}\n\n        for each position :math:`r` in `system.positions`, where :math:`E` is `energy`,\n        :math:`c` is `broadening`, :math:`E_n` is `eigenvalues[n]` and :math:`\\Psi_n(r)`\n        is `eigenvectors[:, n]`.\n\n        Parameters\n        ----------\n        energy : float\n            The energy value for which the spatial LDOS is calculated.\n        broadening : float\n            Controls the width of the Gaussian broadening applied to the DOS.\n\n        Returns\n        -------\n        :class:`~pybinding.StructureMap`\n        \"\"\"\n        if hasattr(self.impl, 'calc_spatial_ldos'):\n            ldos = self.impl.calc_spatial_ldos(energy, broadening)\n        else:\n            scale = 1 / (broadening * math.sqrt(2 * math.pi))\n            gaussian = np.exp(-0.5 * (self.eigenvalues - energy)**2 / broadening**2)\n            psi2 = np.abs(self.eigenvectors)**2\n            ldos = scale * np.sum(psi2 * gaussian, axis=1)\n\n        return self.system.with_data(ldos)\n\n    def calc_bands(self, k0, k1, *ks, step=0.1):\n        \"\"\"Calculate the band structure on a path in reciprocal space\n\n        Parameters\n        ----------\n        k0, k1, *ks : array_like\n            Points in reciprocal space which form the path for the band calculation.\n            At least two points are required.\n        step : float, optional\n            Calculation step length in reciprocal space units. Lower `step` values\n            will return more detailed results.\n\n        Returns\n        -------\n        :class:`~pybinding.Bands`\n        \"\"\"\n        k_points = [np.atleast_1d(k) for k in (k0, k1) + ks]\n        k_path = results.make_path(*k_points, step=step)\n\n        bands = []\n        for k in k_path:\n            self.set_wave_vector(k)\n            bands.append(self.eigenvalues)\n\n        return results.Bands(k_path, np.vstack(bands))\n\n    @staticmethod\n    def find_degenerate_states(energies, abs_tolerance=1e-5):\n        \"\"\"Return groups of indices which belong to degenerate states\n\n        Parameters\n        ----------\n        energies : array_like\n        abs_tolerance : float, optional\n\n        Examples\n        --------\n        >>> energies = np.array([0.1, 0.1, 0.2, 0.5, 0.5, 0.5, 0.7, 0.8, 0.8])\n        >>> Solver.find_degenerate_states(energies)\n        [[0, 1], [3, 4, 5], [7, 8]]\n\n        >>> energies = np.array([0.1, 0.2, 0.5, 0.7])\n        >>> Solver.find_degenerate_states(energies)\n        []\n        \"\"\"\n        # when:   energy == [0.1, 0.1, 0.2, 0.5, 0.5, 0.5, 0.7, 0.8, 0.8]\n        # ...     idx == [0, 3, 4, 7]\n        idx = np.flatnonzero(abs(np.diff(energies)) < abs_tolerance)\n        if idx.size == 0:\n            return []\n        groups = np.split(idx, np.flatnonzero(np.diff(idx) != 1) + 1)\n        # ...     groups == [[0], [3, 4], [7]]\n        # return: [[0, 1], [3, 4, 5], [7, 8]]\n        return [list(g) + [g[-1] + 1] for g in groups]\n\n\nclass _SolverPythonImpl:\n    \"\"\"Python eigensolver implementation\n\n    This is intended to make use of scipy's LAPACK and ARPACK solvers.\n    \"\"\"\n    def __init__(self, solve_func, model, **kwargs):\n        self.solve_func = solve_func\n        self._model = model\n\n        self.kwargs = kwargs\n        self.vals = np.empty(0)\n        self.vecs = np.empty(0)\n        self.compute_time = .0\n\n    def clear(self):\n        self.vals = np.empty(0)\n        self.vecs = np.empty(0)\n        self.compute_time = .0\n\n    @property\n    def model(self):\n        return self._model\n\n    @model.setter\n    def model(self, model):\n        self.clear()\n        self._model = model\n\n    @property\n    def system(self):\n        return self.model.system.impl\n\n    @property\n    def eigenvalues(self) -> np.ndarray:\n        self.solve()\n        return self.vals\n\n    @property\n    def eigenvectors(self) -> np.ndarray:\n        self.solve()\n        return self.vecs\n\n    def solve(self):\n        if len(self.vals):\n            return\n\n        start_time = time.time()\n\n        self.vals, self.vecs = self.solve_func(self.model.hamiltonian, **self.kwargs)\n        idx = self.vals.argsort()\n        self.vals = self.vals[idx]\n        self.vecs = self.vecs[:, idx]\n\n        self.compute_time = time.time() - start_time\n\n    def report(self, _=False):\n        from .utils.time import pretty_duration\n        return \"Converged in \" + pretty_duration(self.compute_time)\n\n\ndef lapack(model, **kwargs):\n    \"\"\"LAPACK :class:`.Solver` implementation for dense matrices\n\n    This solver is intended for small models which are best represented by\n    dense matrices. Always solves for all the eigenvalues and eigenvectors.\n    Internally this solver uses the :func:`scipy.linalg.eigh` function for\n    dense Hermitian matrices.\n\n    Parameters\n    ----------\n    model : Model\n        Model which will provide the Hamiltonian matrix.\n    **kwargs\n        Advanced arguments: forwarded to :func:`scipy.linalg.eigh`.\n\n    Returns\n    -------\n    :class:`~pybinding.solver.Solver`\n    \"\"\"\n    def solver_func(hamiltonian, **kw):\n        from scipy.linalg import eigh\n        return eigh(hamiltonian.toarray(), **kw)\n\n    return Solver(_SolverPythonImpl(solver_func, model, **kwargs))\n\n\ndef arpack(model, k, sigma=0, **kwargs):\n    \"\"\"ARPACK :class:`.Solver` implementation for sparse matrices\n\n    This solver is intended for large models with sparse Hamiltonian matrices.\n    It only computes a small targeted subset of eigenvalues and eigenvectors.\n    Internally this solver uses the :func:`scipy.sparse.linalg.eigsh` function\n    for sparse Hermitian matrices.\n\n    Parameters\n    ----------\n    model : Model\n        Model which will provide the Hamiltonian matrix.\n    k : int\n        The desired number of eigenvalues and eigenvectors. This number must be smaller\n        than the size of the matrix, preferably much smaller for optimal performance.\n        The computed eigenvalues are the ones closest to `sigma`.\n    sigma : float, optional\n        Look for eigenvalues near `sigma`.\n    **kwargs\n        Advanced arguments: forwarded to :func:`scipy.sparse.linalg.eigsh`.\n\n    Returns\n    -------\n    :class:`~pybinding.solver.Solver`\n    \"\"\"\n    from scipy.sparse.linalg import eigsh\n    if sigma == 0:\n        # eigsh can cause problems when sigma is exactly zero\n        sigma = np.finfo(model.hamiltonian.dtype).eps\n    return Solver(_SolverPythonImpl(eigsh, model, k=k, sigma=sigma, **kwargs))\n\n\ndef feast(model, energy_range, initial_size_guess, recycle_subspace=False, is_verbose=False):\n    \"\"\"FEAST :class:`.Solver` implementation for sparse matrices\n\n    This solver is only available if the C++ extension module was compiled with FEAST.\n\n    Parameters\n    ----------\n    model : Model\n        Model which will provide the Hamiltonian matrix.\n    energy_range : tuple of float\n        The lowest and highest eigenvalue between which to compute the solutions.\n    initial_size_guess : int\n        Initial user guess for number of eigenvalues which will be found in the given\n        `energy_range`. This value may be completely wrong - the solver will auto-correct\n        as needed. However, for optimal performance the estimate should be as close to\n        1.5 * actual_size as possible.\n    recycle_subspace : bool, optional\n        Reuse previously computed values as a starting point for the next computation.\n        This improves performance when subsequent computations differ only slightly, as\n        is the case for the band structure of periodic systems where the results change\n        gradually as a function of the wave vector. It may hurt performance otherwise.\n    is_verbose : bool, optional\n        Show the raw output from the FEAST routine.\n\n    Returns\n    -------\n    :class:`~pybinding.solver.Solver`\n    \"\"\"\n    try:\n        # noinspection PyUnresolvedReferences\n        return Solver(_cpp.FEAST(model, energy_range, initial_size_guess,\n                                 recycle_subspace, is_verbose))\n    except AttributeError:\n        raise Exception(\"The module was compiled without the FEAST solver.\\n\"\n                        \"Use a different solver or recompile the module with FEAST.\")\n", "meta": {"hexsha": "37e9c977324d06881a4b100fb2878a2363370e82", "size": 17892, "ext": "py", "lang": "Python", "max_stars_repo_path": "pybinding/solver.py", "max_stars_repo_name": "lise1020/pybinding", "max_stars_repo_head_hexsha": "921d5c2ac0ecc0ef317ba28b0bf68899ea30709a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 159, "max_stars_repo_stars_event_min_datetime": "2016-01-20T17:40:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T06:08:55.000Z", "max_issues_repo_path": "pybinding/solver.py", "max_issues_repo_name": "deilynazar/pybinding", "max_issues_repo_head_hexsha": "ec1128aaa84a1b43a74fb970479ce4544bd63179", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2016-11-01T17:15:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T14:31:51.000Z", "max_forks_repo_path": "pybinding/solver.py", "max_forks_repo_name": "deilynazar/pybinding", "max_forks_repo_head_hexsha": "ec1128aaa84a1b43a74fb970479ce4544bd63179", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 57, "max_forks_repo_forks_event_min_datetime": "2016-04-23T22:12:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T12:33:04.000Z", "avg_line_length": 36.5889570552, "max_line_length": 99, "alphanum_fraction": 0.6150793651, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.17097467990390294}}
{"text": "import torch\nimport os\nimport shutil\nimport numpy as np\nimport logging\nimport salem\nimport rasterio\nfrom scipy.optimize import minimize\nimport matplotlib.pyplot as plt\nfrom combine2d.core import data_logging\nfrom combine2d.core.data_logging import DataLogger\nfrom combine2d.core.arithmetics import RMSE, mean_BIAS\nfrom combine2d.core.utils import NonRGIGlacierDirectory\nfrom combine2d.core.cost_function import create_cost_func\nfrom combine2d.core.data_logging import write_pickle, load_pickle\n# -------------------------------\n# Further initialization / extended import tasks\n# Module logger\nlog = logging.getLogger(__name__)\n\n\nclass InversionDirectory(object):\n\n    def __init__(self, gdir: NonRGIGlacierDirectory):\n        self.gdir = gdir\n        self.inv_settings = gdir.inversion_settings\n        self.true_bed = None\n        self.first_guessed_bed = None\n        self.surf_noise = None\n        self.ref_surf = None\n        self.ice_mask = None\n        self.minimize_log = ''\n        self.cost_func = None\n        self.data_logger = None\n        self.bed_measurements = None\n        if not 'minimize_bounds' in self.inv_settings:\n            self.inv_settings['minimize_bounds'] = None\n\n    def iteration_info_callback(self, x0):\n        i = len(self.data_logger.costs) - 1\n        if i >= 0:\n            dl = self.data_logger\n            dl.step_indices.append(i)\n            b = self.true_bed\n            log_entry = '''\n            ----------------------------------------------\n            Function Call: {func_call:d}\n            Iteration: {iteration:d}\n            Cost: {cost:g}\n            Bed RMSE: {bed_rmse:g}\n            Bed Bias: {bed_bias:g}\n            Bed Max_diff: {bed_maxdiff:g}\n            Surface RMSE: {surf_rmse:g}\n            Surface Max_diff: {surf_maxdiff:g}\n            '''\n            myargs = {\n                'func_call': i,\n                'iteration': len(dl.step_indices),\n                'cost': dl.costs[i],\n                'bed_rmse': RMSE(dl.beds[i], b),\n                'bed_bias': mean_BIAS(dl.beds[i], b, np.sum(self.ice_mask)),\n                'bed_maxdiff': np.max(np.abs(dl.beds[i] - b)),\n                'surf_rmse': RMSE(dl.surfs[i], self.ref_surf),\n                'surf_maxdiff': np.max(np.abs(dl.surfs[i] - self.ref_surf))\n            }\n\n            if self.surf_noise is not None:\n                log_entry += 'RMSE to perturbed surf: {:g}\\n'.format(\n                    RMSE(dl.surfs[i], self.ref_surf + self.surf_noise))\n            log_entry = log_entry.format(**myargs)\n            print(log_entry)\n            self.minimize_log += log_entry\n\n    def write_string_to_file(self, filename, text):\n        dir = self.get_current_basedir()\n        if not os.path.exists(dir):\n            os.makedirs(dir, exist_ok=True)\n        with open(os.path.join(dir, filename), 'w') as f:\n            f.write(text)\n\n    def get_current_basedir(self):\n        return os.path.join(self.gdir.dir,\n                            self.inv_settings['inversion_subdir'])\n\n    def clear_dir(self, dir):\n        if os.path.exists(dir):\n            for f in os.listdir(dir):\n                if (not str.endswith(f, '.py')) and (\n                        not os.path.isdir(os.path.join(dir, f))):\n                    os.remove(os.path.join(dir, f))\n                elif os.path.isdir(os.path.join(dir, f)):\n                    shutil.rmtree(os.path.join(dir, f))\n        else:\n            if not os.path.exists(dir):\n                os.makedirs(dir, exist_ok=True)\n\n    def _read_all_data(self):\n        \"\"\"\n        Reads all necessary information from files in gdir for\n        minimization/optimization and logging.\n        \"\"\"\n        self.true_bed = salem.GeoTiff(\n            self.gdir.get_filepath('dem')).get_vardata()\n        self.ref_surf = salem.GeoTiff(\n            self.gdir.get_filepath('ref_dem')).get_vardata()\n        self.first_guessed_bed = salem.GeoTiff(\n            self.get_subdir_filepath('first_guessed_bed')).get_vardata()\n        self.ice_mask = np.load(self.gdir.get_filepath('ref_ice_mask'))\n        if os.path.exists(self.gdir.get_filepath('dem_noise')): #TODO: once\n            # surface noise is present, it cant get rid off ...\n            shutil.copy(self.gdir.get_filepath('dem_noise'),\n                        self.get_subdir_filepath('dem_noise'))\n            self.surf_noise = np.load(self.get_subdir_filepath('dem_noise'))\n        else:\n            self.surf_noise = None\n\n        if os.path.exists(self.gdir.get_filepath('bed_measurements')):\n            shutil.copy(self.gdir.get_filepath('bed_measurements'),\n                        self.get_subdir_filepath('bed_measurements'))\n            self.bed_measurements = np.load(self.get_subdir_filepath(\n                'bed_measurements'))\n        else:\n            self.bed_measurements = None\n\n    def get_subdir_filepath(self, filename, filesuffix=None):\n        \"\"\"\n        Gets the filepath for a file with a given name (without extension).\n        Works as and is based on get_filepath in GlacierDirectory,\n        but returns filepath in this inversion directory.\n\n        Parameters\n        ----------\n        filename: str\n            name of the file\n        filesuffix: str\n            optional filesuffix to the filename\n\n        Returns\n        -------\n        Entire path to this file in this inversion directory\n\n        \"\"\"\n        original_path = self.gdir.get_filepath(filename, filesuffix=filesuffix)\n        original_path = os.path.split(original_path)\n        return os.path.join(self.get_current_basedir(), original_path[1])\n\n    def get_bounds(self):\n        \"\"\"\n        Creates bounds for the minimization on the current domain. If\n        'bounds_min_max' in inversion settings is None, no bounds are set.\n        Else, in Areas without ice, upper and lower bound are exactly as the\n        observed surface, otherwise min and max values for ice thickness are\n        taken from 'bounds_min_max' and give bounds in glacierized areas. (\n        min ice thickness determines upper bound and max ice thickness\n        determines lower bound)\n\n        Returns\n        -------\n        bounds for this domain and this inversion settings\n        \"\"\"\n        bounds = None\n        if self.inv_settings['bounds_min_max'] is not None:\n            surf = self.ref_surf\n            if self.surf_noise is not None:\n                surf += self.surf_noise\n\n            upper_bounds = surf.copy()\n            lower_bounds = surf.copy()\n\n            min_ice_thickness = self.inv_settings['bounds_min_max'][0]\n            max_ice_thickness = self.inv_settings['bounds_min_max'][1]\n            if min_ice_thickness is not None:\n                upper_bounds = upper_bounds - min_ice_thickness * self.ice_mask\n            else:\n                upper_bounds = np.where(self.ice_mask, None, upper_bounds)\n\n            if max_ice_thickness is not None:\n                lower_bounds = lower_bounds - max_ice_thickness * self.ice_mask\n            else:\n                lower_bounds = np.where(self.ice_mask, None, lower_bounds)\n\n            bounds = np.c_[lower_bounds.flatten(), upper_bounds.flatten()]\n        return bounds\n\n    def run_minimize(self):\n        \"\"\"\n        Here the actual minimization of the cost_function is done via\n        scipy.optimize.minimize.\n        First, data from the glacier directory is read and optionally a\n        DataLogger is created. The inversion settings used for this\n        particular inversion are saved in this subdirectory. Bounds for the\n        minimization are derived. Then the cost function is created and the\n        minimization of this cost function started. In the end, the result is\n        written to disk and optionally, further information is written to disk.\n\n        The whole process is dominated by the set inversion settings\n\n        Returns\n        -------\n        Result of minimization as scipy.optimize.minimize returns (res.x\n        gives flattened ndarray with bed, needs to be reshaped)\n\n        \"\"\"\n\n        # Copy first_guessed_bed to inversion directory\n        if self.inv_settings['log_minimize_steps']:\n            # TODO: really useful? -> respect reset argument in gdir?\n            self.clear_dir(self.get_current_basedir())\n\n        with rasterio.open(self.gdir.get_filepath('first_guessed_bed')) as src:\n            profile = src.profile\n            data = src.read(1)\n        with rasterio.open(self.get_subdir_filepath('first_guessed_bed'),\n                           'w', **profile) as dst:\n            dst.write(data, 1)\n        if os.path.exists(self.gdir.get_filepath('first_guessed_bed_noise')):\n            shutil.copy(self.gdir.get_filepath('first_guessed_bed_noise'),\n                        self.get_subdir_filepath('first_guessed_bed_noise'))\n\n        write_pickle(self.inv_settings,\n                     self.get_subdir_filepath('inversion_settings'))\n        # Write out reg_parameters to check easier later on\n        self.write_string_to_file(self.get_subdir_filepath('reg_parameters'),\n                                  str(self.inv_settings['reg_parameters']))\n        self.inv_settings = load_pickle(\n            self.get_subdir_filepath('inversion_settings'))\n        self._read_all_data()\n        self.minimize_log = ''\n        self.data_logger = None\n        callback = None\n\n        if self.inv_settings['log_minimize_steps']:\n            dl = DataLogger(self)\n            self.data_logger = dl\n            callback = self.iteration_info_callback\n\n        # ----------------------------------------------------------------------\n        # Core: things are happening here:\n        bounds = self.get_bounds()\n\n        self.cost_func = create_cost_func(self.gdir, self.data_logger,\n                                          self.surf_noise,\n                                          self.bed_measurements)\n        res = None\n        try:\n            res = minimize(fun=self.cost_func,\n                           x0=self.first_guessed_bed.astype(np.float64).flatten(),\n                           method=self.inv_settings['solver'], jac=True,\n                           bounds=bounds,\n                           options=self.inv_settings['minimize_options'],\n                           callback=callback)\n\n\n            inverted_bed = res.x.reshape(self.first_guessed_bed.shape)\n            # ----------------------------------------------------------------------\n\n            profile['dtype'] = 'float64'\n            with rasterio.open(self.get_subdir_filepath('inverted_bed'),\n                               'w', **profile) as dst:\n                dst.write(inverted_bed, 1)\n\n        except MemoryError as me:\n            self.write_string_to_file(os.path.join(self.get_current_basedir(),\n                                                   'warning.txt'),\n                                      'Error during iteration: ' + str(me))\n\n\n        if self.inv_settings['log_minimize_steps']:\n            self.write_string_to_file('log.txt', self.minimize_log)\n            dir = self.get_current_basedir()\n            dl.filter_data_from_optimization()  # Optional, if we want to\n            data_logging.write_pickle(dl,\n                                      self.get_subdir_filepath('data_logger'))\n            #dl.plot_all(dir)\n            #plt.close('all')\n\n        return res", "meta": {"hexsha": "a1d89924fc953a3ef84b712c547eb0f58a43bcc3", "size": 11293, "ext": "py", "lang": "Python", "max_stars_repo_path": "combine2d/core/inversion.py", "max_stars_repo_name": "phigre/cobi", "max_stars_repo_head_hexsha": "bb6cd9a49eb22862be6d87f0a2b0c8baf65cadb5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-02-08T20:10:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T12:43:16.000Z", "max_issues_repo_path": "combine2d/core/inversion.py", "max_issues_repo_name": "phigre/cobi", "max_issues_repo_head_hexsha": "bb6cd9a49eb22862be6d87f0a2b0c8baf65cadb5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-10-18T07:11:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-09T23:16:10.000Z", "max_forks_repo_path": "combine2d/core/inversion.py", "max_forks_repo_name": "phigre/COBBI", "max_forks_repo_head_hexsha": "bb6cd9a49eb22862be6d87f0a2b0c8baf65cadb5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-12-30T13:13:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-11T16:15:11.000Z", "avg_line_length": 40.7689530686, "max_line_length": 84, "alphanum_fraction": 0.5842557336, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.17097467508683994}}
{"text": "import numpy as np\n\n\n# This section of code is copied from ProFET (Ofer & Linial, DOI: 10.1093/bioinformatics/btv345)\n# Original comment by the ProFET authors: 'Acquired from georgiev's paper of\n# AAscales using helper script \"GetTextData.py\". + RegEx cleaning DOI: 10.1089/cmb.2008.0173'\ngg_1 = {'Q': -2.54, 'L': 2.72, 'T': -0.65, 'C': 2.66, 'I': 3.1, 'G': 0.15, 'V': 2.64, 'K': -3.89, 'M': 1.89, 'F': 3.12, 'N': -2.02, 'R': -2.8, 'H': -0.39, 'E': -3.08, 'W': 1.89, 'A': 0.57, 'D': -2.46, 'Y': 0.79, 'S': -1.1, 'P': -0.58}\ngg_2 = {'Q': 1.82, 'L': 1.88, 'T': -1.6, 'C': -1.52, 'I': 0.37, 'G': -3.49, 'V': 0.03, 'K': 1.47, 'M': 3.88, 'F': 0.68, 'N': -1.92, 'R': 0.31, 'H': 1, 'E': 3.45, 'W': -0.09, 'A': 3.37, 'D': -0.66, 'Y': -2.62, 'S': -2.05, 'P': -4.33}\ngg_3 = {'Q': -0.82, 'L': 1.92, 'T': -1.39, 'C': -3.29, 'I': 0.26, 'G': -2.97, 'V': -0.67, 'K': 1.95, 'M': -1.57, 'F': 2.4, 'N': 0.04, 'R': 2.84, 'H': -0.63, 'E': 0.05, 'W': 4.21, 'A': -3.66, 'D': -0.57, 'Y': 4.11, 'S': -2.19, 'P': -0.02}\ngg_4 = {'Q': -1.85, 'L': 5.33, 'T': 0.63, 'C': -3.77, 'I': 1.04, 'G': 2.06, 'V': 2.34, 'K': 1.17, 'M': -3.58, 'F': -0.35, 'N': -0.65, 'R': 0.25, 'H': -3.49, 'E': 0.62, 'W': -2.77, 'A': 2.34, 'D': 0.14, 'Y': -0.63, 'S': 1.36, 'P': -0.21}\ngg_5 = {'Q': 0.09, 'L': 0.08, 'T': 1.35, 'C': 2.96, 'I': -0.05, 'G': 0.7, 'V': 0.64, 'K': 0.53, 'M': -2.55, 'F': -0.88, 'N': 1.61, 'R': 0.2, 'H': 0.05, 'E': -0.49, 'W': 0.72, 'A': -1.07, 'D': 0.75, 'Y': 1.89, 'S': 1.78, 'P': -8.31}\ngg_6 = {'Q': 0.6, 'L': 0.09, 'T': -2.45, 'C': -2.23, 'I': -1.18, 'G': 7.47, 'V': -2.01, 'K': 0.1, 'M': 2.07, 'F': 1.62, 'N': 2.08, 'R': -0.37, 'H': 0.41, 'E': 0, 'W': 0.86, 'A': -0.4, 'D': 0.24, 'Y': -0.53, 'S': -3.36, 'P': -1.82}\ngg_7 = {'Q': 0.25, 'L': 0.27, 'T': -0.65, 'C': 0.44, 'I': -0.21, 'G': 0.41, 'V': -0.33, 'K': 4.01, 'M': 0.84, 'F': -0.15, 'N': 0.4, 'R': 3.81, 'H': 1.61, 'E': -5.66, 'W': -1.07, 'A': 1.23, 'D': -5.15, 'Y': -1.3, 'S': 1.39, 'P': -0.12}\ngg_8 = {'Q': 2.11, 'L': -4.06, 'T': 3.43, 'C': -3.49, 'I': 3.45, 'G': 1.62, 'V': 3.93, 'K': -0.01, 'M': 1.85, 'F': -0.41, 'N': -2.47, 'R': 0.98, 'H': -0.6, 'E': -0.11, 'W': -1.66, 'A': -2.32, 'D': -1.17, 'Y': 1.31, 'S': -1.21, 'P': -1.18}\ngg_9 = {'Q': -1.92, 'L': 0.43, 'T': 0.34, 'C': 2.22, 'I': 0.86, 'G': -0.47, 'V': -0.21, 'K': -0.26, 'M': -2.05, 'F': 4.2, 'N': -0.07, 'R': 2.43, 'H': 3.55, 'E': 1.49, 'W': -5.87, 'A': -2.01, 'D': 0.73, 'Y': -0.56, 'S': -2.83, 'P': 0}\ngg_10 = {'Q': -1.67, 'L': -1.2, 'T': 0.24, 'C': -3.78, 'I': 1.98, 'G': -2.9, 'V': 1.27, 'K': -1.66, 'M': 0.78, 'F': 0.73, 'N': 7.02, 'R': -0.99, 'H': 1.52, 'E': -2.26, 'W': -0.66, 'A': 1.31, 'D': 1.5, 'Y': -0.95, 'S': 0.39, 'P': -0.66}\ngg_11 = {'Q': 0.7, 'L': 0.67, 'T': -0.53, 'C': 1.98, 'I': 0.89, 'G': -0.98, 'V': 0.43, 'K': 5.86, 'M': 1.53, 'F': -0.56, 'N': 1.32, 'R': -4.9, 'H': -2.28, 'E': -1.62, 'W': -2.49, 'A': -1.14, 'D': 1.51, 'Y': 1.91, 'S': -2.92, 'P': 0.64}\ngg_12 = {'Q': -0.27, 'L': -0.29, 'T': 1.91, 'C': -0.43, 'I': -1.67, 'G': -0.62, 'V': -1.71, 'K': -0.06, 'M': 2.44, 'F': 3.54, 'N': -2.44, 'R': 2.09, 'H': -3.12, 'E': -3.97, 'W': -0.3, 'A': 0.19, 'D': 5.61, 'Y': -1.26, 'S': 1.27, 'P': -0.92}\ngg_13 = {'Q': -0.99, 'L': -2.47, 'T': 2.66, 'C': -1.03, 'I': -1.02, 'G': -0.11, 'V': -2.93, 'K': 1.38, 'M': -0.26, 'F': 5.25, 'N': 0.37, 'R': -3.08, 'H': -1.45, 'E': 2.3, 'W': -0.5, 'A': 1.66, 'D': -3.85, 'Y': 1.57, 'S': 2.86, 'P': -0.37}\ngg_14 = {'Q': -1.56, 'L': -4.79, 'T': -3.07, 'C': 0.93, 'I': -1.21, 'G': 0.15, 'V': 4.22, 'K': 1.78, 'M': -3.09, 'F': 1.73, 'N': -0.89, 'R': 0.82, 'H': -0.77, 'E': -0.06, 'W': 1.64, 'A': 4.39, 'D': 1.28, 'Y': 0.2, 'S': -1.88, 'P': 0.17}\ngg_15 = {'Q': 6.22, 'L': 0.8, 'T': 0.2, 'C': 1.43, 'I': -1.78, 'G': -0.53, 'V': 1.06, 'K': -2.71, 'M': -1.39, 'F': 2.14, 'N': 3.13, 'R': 1.32, 'H': -4.18, 'E': -0.35, 'W': -0.72, 'A': 0.18, 'D': -1.98, 'Y': -0.76, 'S': -2.42, 'P': 0.36}\ngg_16 = {'Q': -0.18, 'L': -1.43, 'T': -2.2, 'C': 1.45, 'I': 5.71, 'G': 0.35, 'V': -1.31, 'K': 1.62, 'M': -1.02, 'F': 1.1, 'N': 0.79, 'R': 0.69, 'H': -2.91, 'E': 1.51, 'W': 1.75, 'A': -2.6, 'D': 0.05, 'Y': -5.19, 'S': 1.75, 'P': 0.08}\ngg_17 = {'Q': 2.72, 'L': 0.63, 'T': 3.73, 'C': -1.15, 'I': 1.54, 'G': 0.3, 'V': -1.97, 'K': 0.96, 'M': -4.32, 'F': 0.68, 'N': -1.54, 'R': -2.62, 'H': 3.37, 'E': -2.29, 'W': 2.73, 'A': 1.49, 'D': 0.9, 'Y': -2.56, 'S': -2.77, 'P': 0.16}\ngg_18 = {'Q': 4.35, 'L': -0.24, 'T': -5.46, 'C': -1.64, 'I': 2.11, 'G': 0.32, 'V': -1.21, 'K': -1.09, 'M': -1.34, 'F': 1.46, 'N': -1.71, 'R': -1.49, 'H': 1.87, 'E': -1.47, 'W': -2.2, 'A': 0.46, 'D': 1.38, 'Y': 2.87, 'S': 3.36, 'P': -0.34}\ngg_19 = {'Q': 0.92, 'L': 1.01, 'T': -0.73, 'C': -1.05, 'I': -4.18, 'G': 0.05, 'V': 4.77, 'K': 1.36, 'M': 0.09, 'F': 2.33, 'N': -0.25, 'R': -2.57, 'H': 2.17, 'E': 0.15, 'W': 0.9, 'A': -4.22, 'D': -0.03, 'Y': -3.43, 'S': 2.67, 'P': 0.04}\n\n# Package all georgiev parameters\ngeorgiev_parameters = [gg_1, gg_2, gg_3, gg_4, gg_5, gg_6, gg_7, gg_8, gg_9,\n                       gg_10, gg_11, gg_12, gg_13, gg_14, gg_15, gg_16, gg_17,\n                       gg_18, gg_19]\n\n\ndef get_georgiev_params_for_aa(aa):\n    return [gg[aa] for gg in georgiev_parameters]\n\n\ndef get_georgiev_params_for_seq(s):\n    return np.concatenate([get_georgiev_params_for_aa(aa) for aa in s])\n\n\ndef seqs_to_georgiev(seqs):\n    return np.stack([get_georgiev_params_for_seq(s) for s in seqs])\n", "meta": {"hexsha": "379d00ccca3b0a92cd6ffe461aaf1222129ac67d", "size": 5297, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/utils/georgiev_utils.py", "max_stars_repo_name": "brycejoh16/combining-evolutionary-and-assay-labelled-data", "max_stars_repo_head_hexsha": "36ffcf10ad6eacf5d44c81d69f0bc6f7f9cae73b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2022-01-19T02:39:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T21:55:29.000Z", "max_issues_repo_path": "src/utils/georgiev_utils.py", "max_issues_repo_name": "brycejoh16/combining-evolutionary-and-assay-labelled-data", "max_issues_repo_head_hexsha": "36ffcf10ad6eacf5d44c81d69f0bc6f7f9cae73b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-03-09T06:18:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T14:55:59.000Z", "max_forks_repo_path": "src/utils/georgiev_utils.py", "max_forks_repo_name": "brycejoh16/combining-evolutionary-and-assay-labelled-data", "max_forks_repo_head_hexsha": "36ffcf10ad6eacf5d44c81d69f0bc6f7f9cae73b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2022-01-22T07:27:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T23:23:17.000Z", "avg_line_length": 123.1860465116, "max_line_length": 240, "alphanum_fraction": 0.4057013404, "include": true, "reason": "import numpy", "num_tokens": 3377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.17092508495615077}}
{"text": "# Copyright 2014-2019 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Samragni Banerjee <samragnibanerjee4@gmail.com>\n#         Alexander Sokolov <alexander.y.sokolov@gmail.com>\n#\n\nimport numpy as np\nimport pyscf.ao2mo\n\n### Integral transformation ###\ndef transform_integrals(myadc):\n    occ_a = myadc.mo_coeff[0][:,:myadc._nocc[0]]\n    occ_b = myadc.mo_coeff[1][:,:myadc._nocc[1]]\n    vir_a = myadc.mo_coeff[0][:,myadc._nocc[0]:]\n    vir_b = myadc.mo_coeff[1][:,myadc._nocc[1]:]\n\n\n    occ = occ_a, occ_b\n    vir = vir_a, vir_b\n\n    eris = lambda:None\n\n    eris.oovv = transform_antisymmetrize_integrals(myadc._scf._eri, (occ,occ,vir,vir))\n    eris.vvvv = transform_antisymmetrize_integrals(myadc._scf._eri, (vir,vir,vir,vir))\n    eris.oooo = transform_antisymmetrize_integrals(myadc._scf._eri, (occ,occ,occ,occ))\n    eris.voov = transform_antisymmetrize_integrals(myadc._scf._eri, (vir,occ,occ,vir))\n    eris.ooov = transform_antisymmetrize_integrals(myadc._scf._eri, (occ,occ,occ,vir))\n    eris.vovv = transform_antisymmetrize_integrals(myadc._scf._eri, (vir,occ,vir,vir))\n    eris.vvoo = transform_antisymmetrize_integrals(myadc._scf._eri, (vir,vir,occ,occ))\n    eris.vvvo = transform_antisymmetrize_integrals(myadc._scf._eri, (vir,vir,vir,occ))\n    eris.ovoo = transform_antisymmetrize_integrals(myadc._scf._eri, (occ,vir,occ,occ))\n    eris.ovov = transform_antisymmetrize_integrals(myadc._scf._eri, (occ,vir,occ,vir))\n    eris.vooo = transform_antisymmetrize_integrals(myadc._scf._eri, (vir,occ,occ,occ))\n    eris.oovo = transform_antisymmetrize_integrals(myadc._scf._eri, (occ,occ,vir,occ))\n    eris.vovo = transform_antisymmetrize_integrals(myadc._scf._eri, (vir,occ,vir,occ))\n    eris.vvov = transform_antisymmetrize_integrals(myadc._scf._eri, (vir,vir,occ,vir))\n    eris.ovvo = transform_antisymmetrize_integrals(myadc._scf._eri, (occ,vir,vir,occ))\n    eris.ovvv = transform_antisymmetrize_integrals(myadc._scf._eri, (occ,vir,vir,vir))\n\n    return eris\n\n# TODO: disk flag\ndef transform_antisymmetrize_integrals(v2e_ao, mo, disk = False):\n\n    mo_1, mo_2, mo_3, mo_4 = mo\n\n    mo_1_a, mo_1_b = mo_1\n    mo_2_a, mo_2_b = mo_2\n    mo_3_a, mo_3_b = mo_3\n    mo_4_a, mo_4_b = mo_4\n\n    v2e_a = None\n    v2e_a = pyscf.ao2mo.general(v2e_ao, (mo_1_a, mo_3_a, mo_2_a, mo_4_a), compact=False)\n    v2e_a = v2e_a.reshape(mo_1_a.shape[1], mo_3_a.shape[1], mo_2_a.shape[1], mo_4_a.shape[1])\n    v2e_a = v2e_a.transpose(0,2,1,3).copy()\n\n    if (mo_1_a is mo_2_a):\n        v2e_a -= v2e_a.transpose(1,0,2,3).copy()\n    elif (mo_3_a is mo_4_a):\n        v2e_a -= v2e_a.transpose(0,1,3,2).copy()\n    else:\n        v2e_temp = None\n        v2e_temp = pyscf.ao2mo.general(v2e_ao, (mo_1_a, mo_4_a, mo_2_a, mo_3_a), compact=False)\n        v2e_temp = v2e_temp.reshape(mo_1_a.shape[1], mo_4_a.shape[1], mo_2_a.shape[1], mo_3_a.shape[1])\n        v2e_a -= v2e_temp.transpose(0,2,3,1).copy()\n        del v2e_temp\n\n    v2e_a = disk_helper.dataset(v2e_a) if disk else v2e_a\n\n    v2e_b = None\n    v2e_b = pyscf.ao2mo.general(v2e_ao, (mo_1_b, mo_3_b, mo_2_b, mo_4_b), compact=False)\n    v2e_b = v2e_b.reshape(mo_1_b.shape[1], mo_3_b.shape[1], mo_2_b.shape[1], mo_4_b.shape[1])\n    v2e_b = v2e_b.transpose(0,2,1,3).copy()\n\n    if (mo_1_b is mo_2_b):\n        v2e_b -= v2e_b.transpose(1,0,2,3).copy()\n    elif (mo_3_b is mo_4_b):\n        v2e_b -= v2e_b.transpose(0,1,3,2).copy()\n    else:\n        v2e_temp = None\n        v2e_temp = pyscf.ao2mo.general(v2e_ao, (mo_1_b, mo_4_b, mo_2_b, mo_3_b), compact=False)\n        v2e_temp = v2e_temp.reshape(mo_1_b.shape[1], mo_4_b.shape[1], mo_2_b.shape[1], mo_3_b.shape[1])\n        v2e_b -= v2e_temp.transpose(0,2,3,1).copy()\n        del v2e_temp\n\n    v2e_b = disk_helper.dataset(v2e_b) if disk else v2e_b\n\n    v2e_ab = None\n    v2e_ab = pyscf.ao2mo.general(v2e_ao, (mo_1_a, mo_3_a, mo_2_b, mo_4_b), compact=False)\n    v2e_ab = v2e_ab.reshape(mo_1_a.shape[1], mo_3_a.shape[1], mo_2_b.shape[1], mo_4_b.shape[1])\n    v2e_ab = v2e_ab.transpose(0,2,1,3).copy()\n\n    v2e_ab = disk_helper.dataset(v2e_ab) if disk else v2e_ab\n\n    return (v2e_a, v2e_ab, v2e_b)\n", "meta": {"hexsha": "41aea5d3a1fe79f193c99f48f0a7657128a4f777", "size": 4618, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/adc/uadc_ao2mo.py", "max_stars_repo_name": "azag0/pyscf", "max_stars_repo_head_hexsha": "1e3e27b61b3cfd22c9679d2c9851c13b3ebc5a1b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-03T12:32:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T08:19:02.000Z", "max_issues_repo_path": "pyscf/adc/uadc_ao2mo.py", "max_issues_repo_name": "azag0/pyscf", "max_issues_repo_head_hexsha": "1e3e27b61b3cfd22c9679d2c9851c13b3ebc5a1b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscf/adc/uadc_ao2mo.py", "max_forks_repo_name": "azag0/pyscf", "max_forks_repo_head_hexsha": "1e3e27b61b3cfd22c9679d2c9851c13b3ebc5a1b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-06-01T05:31:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T02:38:33.000Z", "avg_line_length": 42.7592592593, "max_line_length": 103, "alphanum_fraction": 0.703118233, "include": true, "reason": "import numpy", "num_tokens": 1788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3040416686603661, "lm_q1q2_score": 0.17092508141096383}}
{"text": "#!/usr/bin/env python\n\"\"\"\nClassy data\n\"\"\"\n__author__ = \"Sid Mau\"\n\n# Python libraries\nimport os\nimport glob\nimport numpy as np\nimport healpy as hp\nimport fitsio as fits\nimport scipy.ndimage\n\n# Ugali libraries\nimport ugali.utils.healpix\nimport ugali.utils.projector\n\n# Simple libraries\nimport simple.filters\nimport simple.objects.result\n\n# TODO:\n# - use point\n# - make derived classes for each survey\n\n########################################################################\n\nclass Data:\n    \"\"\"\n    Class object for analyzing photometric data.\n    \"\"\"\n    def __init__(self, survey, nside, datadir, fracdet, band_1, band_2, mag, mag_err, mag_dered, basis_1, basis_2, mag_max):\n        self.survey      = survey\n        self.nside       = nside\n        self.datadir     = datadir\n        self.fracdet     = fracdet\n        self.band_1      = band_1\n        self.band_2      = band_2\n        self.mag_1       = mag.format(band_1.upper())\n        self.mag_2       = mag.format(band_2.upper())\n        self.mag_err_1   = mag_err.format(band_1.upper())\n        self.mag_err_2   = mag_err.format(band_2.upper())\n        self.mag_dered_1 = mag_dered.format(band_1.upper())\n        self.mag_dered_2 = mag_dered.format(band_2.upper())\n        self.basis_1     = basis_1\n        self.basis_2     = basis_2\n        self.mag_max     = mag_max\n\n    def quality_filter(self, data):\n        \"\"\"\n        Return cut on high quality objects.\n        \"\"\"\n        return simple.filters.quality_filter(self.survey, data)\n\n    def star_filter(self, data):\n        \"\"\"\n        Return cut on star-like objects.\n        \"\"\"\n        return simple.filters.star_filter(self.survey, data)\n\n    def galaxy_filter(self, data):\n        \"\"\"\n        Return cut on galaxy-like objects.\n        \"\"\"\n        return simple.filters.galaxy_filter(self.survey, data)\n\n    def color_filter(self, data):\n        \"\"\"\n        Return cut on blue objects.\n        \"\"\"\n        return simple.filters.color_filter(self.survey, data)\n\n    def dered_mag(self, data):\n        \"\"\"\n        Deredden magnitudes.\n        \"\"\"\n        return simple.filters.dered_mag(self.survey, data)\n\n\n    @property\n    def load_fracdet(self):\n        \"\"\"\n        Load fracdet if given.\n        \"\"\"\n        if self.fracdet is not None:\n            return fits.read(self.fracdet)\n        else:\n            msg = \"No fracdet found at {}\".format(self.fracdet)\n            raise Exception(msg)\n            return None\n\n    def load_local_data(self, ra, dec):\n        \"\"\"\n        Load data corresponding to the 8 nearest neighbors of the\n        centroid at (ra, dec) into memory.\n        \"\"\"\n        hpixel  = ugali.utils.healpix.angToPix(self.nside, ra, dec)\n        hpixels = np.concatenate([[hpixel], hp.get_all_neighbours(self.nside, hpixel)])\n\n        data_array = []\n        for hpix in hpixels:\n            inlist = glob.glob('{}/*_{:05d}.fits'.format(self.dirname, hpix))\n            for infile in inlist:\n                if not os.path.exists(infile):\n                    continue\n                data_array.append(fits.read(infile))\n        data = np.concatenate(data_array)\n\n        return data\n\n    def compute_char_density(self, ra, dec):\n        \"\"\"\n        Compute the characteristic density of a region.\n        \"\"\"\n    \n        data = self.load_local_data(ra, dec)\n\n        mag_cut = (data[self.mag_1] < self.mag_max)\n    \n        proj = ugali.utils.projector.Projector(ra, dec)\n        x, y = proj.sphereToImage(data[self.basis_1][mag_cut], data[self.basis_2][mag_cut]) # Trimmed magnitude range for hotspot finding\n        delta_x = 0.01\n        area = delta_x**2\n        smoothing = 2. / 60. # Was 3 arcmin\n        bins = np.arange(-8., 8. + 1.e-10, delta_x)\n        centers = 0.5 * (bins[0: -1] + bins[1:])\n        yy, xx = np.meshgrid(centers, centers)\n    \n        h = np.histogram2d(x, y, bins=[bins, bins])[0]\n    \n        h_g = scipy.ndimage.filters.gaussian_filter(h, smoothing / delta_x)\n    \n        delta_x_coverage = 0.1\n        area_coverage = (delta_x_coverage)**2\n        bins_coverage = np.arange(-5., 5. + 1.e-10, delta_x_coverage)\n        h_coverage = np.histogram2d(x, y, bins=[bins_coverage, bins_coverage])[0]\n        h_goodcoverage = np.histogram2d(x, y, bins=[bins_coverage, bins_coverage])[0]\n    \n        n_goodcoverage = h_coverage[h_goodcoverage > 0].flatten()\n    \n        characteristic_density = np.median(n_goodcoverage) / area_coverage # per square degree\n        print('Characteristic density = {:0.1f} deg^-2').format(characteristic_density)\n    \n        # Use pixels with fracdet ~1.0 to estimate the characteristic density\n        if self.fracdet is not None:\n            fracdet = fits.read(self.fracdet)\n            fracdet_zero = np.tile(0., len(fracdet))\n            cut = (fracdet != hp.UNSEEN)\n            fracdet_zero[cut] = fracdet[cut]\n    \n            nside_fracdet = hp.npix2nside(len(fracdet))\n            \n            subpix_region_array = []\n            for pix in np.unique(ugali.utils.healpix.angToPix(self.nside, data[self.basis_1], data[self.basis_2])):\n                subpix_region_array.append(ugali.utils.healpix.subpixel(pix, self.nside, nside_fracdet))\n            subpix_region_array = np.concatenate(subpix_region_array)\n    \n            # Compute mean fracdet in the region so that this is available as a correction factor\n            cut = (fracdet[subpix_region_array] != hp.UNSEEN)\n            mean_fracdet = np.mean(fracdet[subpix_region_array[cut]])\n    \n            # Correct the characteristic density by the mean fracdet value\n            characteristic_density_raw = 1. * characteristic_density\n            characteristic_density /= mean_fracdet \n            print('Characteristic density (fracdet corrected) = {:0.1f} deg^-2').format(characteristic_density)\n    \n        return characteristic_density\n    \n    def compute_local_char_density(self, ra, dec, x_peak, y_peak, angsep_peak):\n        \"\"\"\n        Compute the local characteristic density of a region.\n        \"\"\"\n    \n        data = self.load_local_data(ra, dec)\n\n        characteristic_density = self.compute_char_density(ra, dec)\n\n        mag_cut = (data[mag_dered_1] < self.mag_max)\n    \n        proj = ugali.utils.projector.Projector(ra, dec)\n        x, y = proj.sphereToImage(data[basis_1][mag_cut], data[basis_2][mag_cut]) # Trimmed magnitude range for hotspot finding\n    \n        # If fracdet map is available, use that information to either compute local density,\n        # or in regions of spotty coverage, use the typical density of the region\n        if self.fracdet is not None:\n            fracdet = fits.read(self.fracdet)\n            fracdet_zero = np.tile(0., len(fracdet))\n            cut = (fracdet != hp.UNSEEN)\n            fracdet_zero[cut] = fracdet[cut]\n    \n            nside_fracdet = hp.npix2nside(len(fracdet))\n            \n            subpix_region_array = []\n            for pix in np.unique(ugali.utils.healpix.angToPix(nside, data[basis_1], data[basis_2])):\n                subpix_region_array.append(ugali.utils.healpix.subpixel(pix, self.nside, nside_fracdet))\n            subpix_region_array = np.concatenate(subpix_region_array)\n    \n            # Compute mean fracdet in the region so that this is available as a correction factor\n            cut = (fracdet[subpix_region_array] != hp.UNSEEN)\n            mean_fracdet = np.mean(fracdet[subpix_region_array[cut]])\n    \n            subpix_region_array = subpix_region_array[fracdet[subpix_region_array] > 0.99]\n            subpix = ugali.utils.healpix.angToPix(nside_fracdet, \n                                                  data[self.basis_1][mag_cut], \n                                                  data[self.basis_2][mag_cut]) # Remember to apply mag threshold to objects\n    \n            # This is where the local computation begins\n            ra_peak, dec_peak = proj.imageToSphere(x_peak, y_peak)\n            subpix_all = ugali.utils.healpix.angToDisc(nside_fracdet, ra_peak, dec_peak, 0.5)\n            subpix_inner = ugali.utils.healpix.angToDisc(nside_fracdet, ra_peak, dec_peak, 0.3)\n            subpix_annulus = subpix_all[~np.in1d(subpix_all, subpix_inner)]\n            mean_fracdet = np.mean(fracdet_zero[subpix_annulus])\n            print('mean_fracdet {}'.format(mean_fracdet))\n            if mean_fracdet < 0.5:\n                characteristic_density_local = characteristic_density\n                print('characteristic_density_local baseline {}').format(characteristic_density_local)\n            else:\n                # Check pixels in annulus with complete coverage\n                subpix_annulus_region = np.intersect1d(subpix_region_array, subpix_annulus)\n                print('{} percent pixels with complete coverage'.format(float(len(subpix_annulus_region)) / len(subpix_annulus)))\n                if (float(len(subpix_annulus_region)) / len(subpix_annulus)) < 0.25:\n                    characteristic_density_local = characteristic_density\n                    print('characteristic_density_local spotty {}'.format(characteristic_density_local))\n                else:\n                    characteristic_density_local = float(np.sum(np.in1d(subpix, subpix_annulus_region))) \\\n                                                   / (hp.nside2pixarea(nside_fracdet, degrees=True) * len(subpix_annulus_region)) # deg^-2\n                    print('characteristic_density_local cleaned up {}'.format(characteristic_density_local))\n        else:\n            # Compute the local characteristic density\n            area_field = np.pi * (0.5**2 - 0.3**2)\n            n_field = np.sum((angsep_peak > 0.3) & (angsep_peak < 0.5))\n            characteristic_density_local = n_field / area_field\n    \n            # If not good azimuthal coverage, revert\n            cut_annulus = (angsep_peak > 0.3) & (angsep_peak < 0.5) \n            #phi = np.degrees(np.arctan2(y_full[cut_annulus] - y_peak, x_full[cut_annulus] - x_peak)) # Use full magnitude range, NOT TESTED!!!\n            phi = np.degrees(np.arctan2(y[cut_annulus] - y_peak, x[cut_annulus] - x_peak)) # Impose magnitude threshold\n            h = np.histogram(phi, bins=np.linspace(-180., 180., 13))[0]\n            if np.sum(h > 0) < 10 or np.sum(h > 0.5 * np.median(h)) < 10:\n                #angsep_peak = np.sqrt((x - x_peak)**2 + (y - y_peak)**2)\n                characteristic_density_local = characteristic_density\n    \n        print('Characteristic density local = {:0.1f} deg^-2 = {:0.3f} arcmin^-2'.format(characteristic_density_local, characteristic_density_local / 60.**2))\n    \n        return characteristic_density_local\n\n\n    def find_peaks(self, ra, dec, distance_modulus):\n        \"\"\"\n        Convolve field to find characteristic density and peaks within the selected pixel.\n        \"\"\"\n\n        pix_nside_select = ugali.utils.healpix.angToPix(self.nside, ra, dec)\n        data = self.load_local_data(ra, dec)\n        characteristic_density = self.compute_char_density(ra, dec)\n        mag_cut = (data[mag_dered_1] < self.mag_max)\n    \n        # convolve field and find peaks\n        proj = ugali.utils.projector.Projector(ra, dec)\n        x, y = proj.sphereToImage(data[self.basis_1][mag_cut], data[self.basis_2][mag_cut]) # Trimmed magnitude range for hotspot finding\n        delta_x = 0.01\n        area = delta_x**2\n        smoothing = 2. / 60. # Was 3 arcmin\n        bins = np.arange(-8., 8. + 1.e-10, delta_x)\n        centers = 0.5 * (bins[0: -1] + bins[1:])\n        yy, xx = np.meshgrid(centers, centers)\n    \n        h = np.histogram2d(x, y, bins=[bins, bins])[0]\n        \n        h_g = scipy.ndimage.filters.gaussian_filter(h, smoothing / delta_x)\n    \n        factor_array = np.arange(1., 5., 0.05)\n        rara, decdec = proj.imageToSphere(xx.flatten(), yy.flatten())\n        cutcut = (ugali.utils.healpix.angToPix(self.nside, rara, decdec) == pix_nside_select).reshape(xx.shape)\n        threshold_density = 5 * characteristic_density * area\n        for factor in factor_array:\n            h_region, n_region = scipy.ndimage.measurements.label((h_g * cutcut) > (area * characteristic_density * factor))\n            #print 'factor', factor, n_region, n_region < 10\n            if n_region < 10:\n                threshold_density = area * characteristic_density * factor\n                break\n    \n        h_region, n_region = scipy.ndimage.measurements.label((h_g * cutcut) > threshold_density)\n        h_region = np.ma.array(h_region, mask=(h_region < 1))\n    \n        x_peak_array = []\n        y_peak_array = []\n        angsep_peak_array = []\n    \n        for index in range(1, n_region + 1): # loop over peaks\n            index_peak = np.argmax(h_g * (h_region == index))\n            x_peak, y_peak = xx.flatten()[index_peak], yy.flatten()[index_peak]\n            #print index, np.max(h_g * (h_region == index))\n            \n            #angsep_peak = np.sqrt((x_full - x_peak)**2 + (y_full - y_peak)**2) # Use full magnitude range, NOT TESTED!!!\n            angsep_peak = np.sqrt((x - x_peak)**2 + (y - y_peak)**2) # Impose magnitude threshold\n    \n            x_peak_array.append(x_peak)\n            y_peak_array.append(y_peak)\n            angsep_peak_array.append(angsep_peak)\n        \n        return x_peak_array, y_peak_array, angsep_peak_array\n\n    def fit_aperture(self, ra, dec, proj, distance_modulus, x_peak, y_peak, angsep_peak):\n        \"\"\"\n        Fit aperture by varing radius and computing the significance.\n        \"\"\"\n    \n        # use result.Result()\n        ra_peak_array          = []\n        dec_peak_array         = []\n        r_peak_array           = []\n        sig_peak_array         = []\n        distance_modulus_array = []\n        n_obs_peak_array       = []\n        n_obs_half_peak_array  = []\n        n_model_peak_array     = []\n    \n        size_array = np.arange(0.01, 0.3, 0.01)\n        sig_array = np.tile(0., len(size_array))\n        \n        size_array_zero = np.concatenate([[0.], size_array])\n        area_array = np.pi * (size_array_zero[1:]**2 - size_array_zero[0:-1]**2)\n\n        characteristic_density_local = self.compute_local_char_density(ra, dec, x_peak, y_peak, angsep_peak)\n    \n        n_obs_array = np.tile(0, len(size_array))\n        n_model_array = np.tile(0., len(size_array))\n        for ii in range(0, len(size_array)):\n            n_obs = np.sum(angsep_peak < size_array[ii])\n            n_model = characteristic_density_local * (np.pi * size_array[ii]**2)\n            sig_array[ii] = np.clip(scipy.stats.norm.isf(scipy.stats.poisson.sf(n_obs, n_model)), 0., 37.5) # Clip at 37.5\n            n_obs_array[ii] = n_obs\n            n_model_array[ii] = n_model\n    \n        ra_peak, dec_peak = proj.imageToSphere(x_peak, y_peak)\n    \n        index_peak = np.argmax(sig_array)\n        r_peak = size_array[index_peak]\n        #if np.max(sig_array) >= 37.5:\n        #    r_peak = 0.5\n        n_obs_peak = n_obs_array[index_peak]\n        n_model_peak = n_model_array[index_peak]\n        n_obs_half_peak = np.sum(angsep_peak < (0.5 * r_peak))\n    \n        # Compile resilts\n        print('Candidate: x_peak: {:12.3f}, y_peak: {:12.3f}, r_peak: {:12.3f}, sig: {:12.3f}, ra_peak: {:12.3f}, dec_peak: {:12.3f}'.format(x_peak, y_peak, r_peak, np.max(sig_array), ra_peak, dec_peak))\n        ra_peak_array.append(ra_peak)\n        dec_peak_array.append(dec_peak)\n        r_peak_array.append(r_peak)\n        #sig_peak_array.append(np.max(sig_array))\n        sig_peak_array.append(sig_array[index_peak])\n        distance_modulus_array.append(distance_modulus)\n        n_obs_peak_array.append(n_obs_peak)\n        n_obs_half_peak_array.append(n_obs_half_peak)\n        n_model_peak_array.append(n_model_peak)\n    \n        return (ra_peak_array, dec_peak_array, r_peak_array, sig_peak_array, distance_modulus_array, n_obs_peak_array, n_obs_half_peak_array, n_model_peak_array)\n", "meta": {"hexsha": "54941ef781dce6cf7f9fc8af29f2165056939bdc", "size": 15764, "ext": "py", "lang": "Python", "max_stars_repo_path": "simple/objects/data.py", "max_stars_repo_name": "mcnanna/simple", "max_stars_repo_head_hexsha": "5d96abb3994d9034fff1dcec590d0fdced8ba784", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-10-12T03:02:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T23:28:26.000Z", "max_issues_repo_path": "simple/objects/data.py", "max_issues_repo_name": "mcnanna/simple", "max_issues_repo_head_hexsha": "5d96abb3994d9034fff1dcec590d0fdced8ba784", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2017-12-28T07:16:44.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-10T19:36:11.000Z", "max_forks_repo_path": "simple/objects/data.py", "max_forks_repo_name": "mcnanna/simple", "max_forks_repo_head_hexsha": "5d96abb3994d9034fff1dcec590d0fdced8ba784", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-12T03:01:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T22:07:37.000Z", "avg_line_length": 43.7888888889, "max_line_length": 203, "alphanum_fraction": 0.6127886323, "include": true, "reason": "import numpy,import scipy", "num_tokens": 3913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.28457601635158564, "lm_q1q2_score": 0.17079921233886344}}
{"text": "import numpy as np\n\ndef provide_PSF_2D(x=None,y=None,PSF_version=None):\n    \"\"\" Provide 2D PSF at any position in the detector plane\n        This a version which takes a finite nubmer of pregenerated PSF and \\\n        creates the interpolated version at required position\n        (Future: version which takes interpolated values for Zernike \\\n        coefficients and generates image on the fly?)\n        \n    This version with      \n        \n\n    @param[in] x            x-coordinate\n    @param[in] y            y-coordinate\n    @param[in] PSF_version  version of the PSF input files\n    \n    @returns                numpy array, (if PSF input file is  Apr15_v2 is 189x189, oversampled 9 times, \\\n                            corresponding to 21x21 physical pixels (315x315 microns))\n    \"\"\"    \n    \n    # on tiger this directory is at:\n    #DATA_DIRECTORY='/tigress/ncaplar/PIPE2D-521/'\n    DATA_DIRECTORY='/Users/nevencaplar/Documents/PFS/Tickets/PIPE2D-521/'\n    \n    if PSF_version is None:\n        PSF_version='Apr15_v2'\n\n    positions_of_simulation=np.load(DATA_DIRECTORY+'positions_of_simulation_00_from_'+PSF_version+'.npy',allow_pickle=True)\n    array_of_simulation=np.load(DATA_DIRECTORY+'array_of_simulation_00_from_'+PSF_version+'.npy',allow_pickle=True)\n    \n    # x and y position with simulated PSFs\n    x_positions_of_simulation=positions_of_simulation[:,1]\n    y_positions_of_simulation=positions_of_simulation[:,2]\n    \n    # This is a simple code that finds the closest avaliable PSFs, given the x and y position\n    # This will have to be improved in order when we get to work with the full populated dectector plane\n    \n    \n    # how far in x-dimension are you willing to search for suitable simulated PSFs\n    x_search_distance=20\n    # positions of all simulated PSFs in that range\n    positions_of_simulation_in_acceptable_x_range=\\\n    positions_of_simulation[(x_positions_of_simulation<(x+x_search_distance))\\\n                            &(x_positions_of_simulation>(x-x_search_distance))]\n    \n    # if there are no simulated PSF avaliable in the specified x-range we are not able to provide the solution\n    if len(positions_of_simulation_in_acceptable_x_range)<2:\n        print('No simulated PSFs are avaliable in this x-area of the detector,')\n        print('probably because this fiber has not been illuminated;')\n        print('returning the closest avaliable PSFs, BUT that is probably not what you want')\n        distances=np.sqrt(((x-x_positions_of_simulation)**2+\\\n                           (y-y_positions_of_simulation)**2).astype(float))\n        index_of_closest_distance=np.where(distances[distances==\\\n                                                     np.min(distances)])[0][0]\n        \n        # ! change here on April 22, 2020!\n        #       changed so the output is more similar (output as a list) to more general case below\n        return [array_of_simulation[index_of_closest_distance]]\n        # ! end of change here on April 22, 2020\n    \n    # y-distance from the requested positions for all of the suitable simulated PSFs\n    distances_of_y_requested_position_from_avaliable=\\\n    y-positions_of_simulation_in_acceptable_x_range[:,2]\n    \n    # if you request for a spot exactly at the position of a input from the array\n    if np.min(np.abs(distances_of_y_requested_position_from_avaliable))==0:\n        index_of_simulated_psf=\\\n        np.where(distances_of_y_requested_position_from_avaliable==0)[0][0]   \n        \n        y1_distance=0\n        y2_distance=0\n        \n        \n        # where are that exact PSF in the initial table\n        index_of_1st_closest_simulated_psf_in_positions_of_simulation=\\\n        np.where(np.sum(positions_of_simulation,axis=1)==\\\n                 np.sum(positions_of_simulation_in_acceptable_x_range[index_of_simulated_psf]))[0][0]\n        print(index_of_1st_closest_simulated_psf_in_positions_of_simulation)\n            # extract the 2 simulated PSFs\n        first_array_simulation=\\\n        array_of_simulation[index_of_1st_closest_simulated_psf_in_positions_of_simulation]\n        second_array_simulation=\\\n        array_of_simulation[index_of_1st_closest_simulated_psf_in_positions_of_simulation]\n        \n    else:\n        # ! change here on April 22, 2020!\n        # separate the distances into distances which are for the spots above the requested position and below the requested position\n        distances_of_y_requested_position_from_avaliable_which_are_above_the_spot=distances_of_y_requested_position_from_avaliable[distances_of_y_requested_position_from_avaliable<0]\n        distances_of_y_requested_position_from_avaliable_which_are_below_the_spot=distances_of_y_requested_position_from_avaliable[distances_of_y_requested_position_from_avaliable>0]\n\n        # if there are no sources above, do not do interpolation and select the nearest source\n        if len(distances_of_y_requested_position_from_avaliable_which_are_above_the_spot)==0:\n            index_of_1st_closest_above_simulated_psf=-99 \n        else:\n            index_of_1st_closest_above_simulated_psf=\\\n            np.where(distances_of_y_requested_position_from_avaliable==\\\n                     np.max(distances_of_y_requested_position_from_avaliable_which_are_above_the_spot))[0][0]    \n\n        # if there are no sources below, do not do interpolation and select the nearest source\n        if len(distances_of_y_requested_position_from_avaliable_which_are_below_the_spot)==0:\n            index_of_1st_closest_below_simulated_psf=-99\n        else:\n            index_of_1st_closest_below_simulated_psf=\\\n            np.where(distances_of_y_requested_position_from_avaliable==\\\n                     np.min(distances_of_y_requested_position_from_avaliable_which_are_below_the_spot))[0][0]       \n\n        if index_of_1st_closest_below_simulated_psf==-99:\n            index_of_1st_closest_below_simulated_psf=index_of_1st_closest_above_simulated_psf\n        if index_of_1st_closest_above_simulated_psf==-99:\n            index_of_1st_closest_above_simulated_psf=index_of_1st_closest_below_simulated_psf\n        # ! end of change here on April 22, 2020\n\n        # where are these 2 closest PSF in the initial table\n        index_of_1st_closest_simulated_psf_in_positions_of_simulation=\\\n        np.where(np.sum(positions_of_simulation,axis=1)==\\\n                 np.sum(positions_of_simulation_in_acceptable_x_range[index_of_1st_closest_above_simulated_psf]))[0][0]\n        index_of_2nd_closest_simulated_psf_in_positions_of_simulation=\\\n        np.where(np.sum(positions_of_simulation,axis=1)==\\\n                 np.sum(positions_of_simulation_in_acceptable_x_range[index_of_1st_closest_below_simulated_psf]))[0][0]\n\n\n\n        # extract the 2 simulated PSFs\n        first_array_simulation=\\\n        array_of_simulation[index_of_1st_closest_simulated_psf_in_positions_of_simulation]\n        second_array_simulation=\\\n        array_of_simulation[index_of_2nd_closest_simulated_psf_in_positions_of_simulation]\n\n        #print('1st:'+str(positions_of_simulation[index_of_1st_closest_simulated_psf_in_positions_of_simulation]),\\\n        #      '2nd:'+str(positions_of_simulation[index_of_2nd_closest_simulated_psf_in_positions_of_simulation]))\n\n        # distance of each PSF from the proposed position\n        #print(positions_of_simulation[index_of_1st_closest_simulated_psf_in_positions_of_simulation],positions_of_simulation[index_of_2nd_closest_simulated_psf_in_positions_of_simulation])\n        y1_distance=\\\n        y-positions_of_simulation[index_of_1st_closest_simulated_psf_in_positions_of_simulation][2]\n        y2_distance=\\\n        y-positions_of_simulation[index_of_2nd_closest_simulated_psf_in_positions_of_simulation][2]\n\n    # ! change here on April 22, 2020!\n    #       if you requested psf at the exact position of existing PSF use that one OR\n    #       if you are outside of the range covered by spots, use the last avaliable image\n    if y1_distance==0 or y1_distance==y2_distance:\n\n\n        #    changed so the output is equivalent as in more general case\n        return first_array_simulation,first_array_simulation,second_array_simulation,y1_distance,y2_distance\n        # ! end of change here on April 22, 2020\n    else:    \n        # create the predicted PSF as a linear interpolation of these two PSFs\n        predicted_psf=(second_array_simulation-first_array_simulation*(y2_distance/y1_distance))/(1-y2_distance/y1_distance)\n        return predicted_psf,first_array_simulation,second_array_simulation,y1_distance,y2_distance\n    \n    ", "meta": {"hexsha": "11f502135306033ea2705f6d734d3d1b6f9038fd", "size": 8531, "ext": "py", "lang": "Python", "max_stars_repo_path": "2d_PSF_code/PIPE2D-521/Provide_PSF_2D.py", "max_stars_repo_name": "Subaru-PFS/dev_pfsmodel", "max_stars_repo_head_hexsha": "d01cf03a4c4eaa01ba5a9590ccf17744a33bdb05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2d_PSF_code/PIPE2D-521/Provide_PSF_2D.py", "max_issues_repo_name": "Subaru-PFS/dev_pfsmodel", "max_issues_repo_head_hexsha": "d01cf03a4c4eaa01ba5a9590ccf17744a33bdb05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2d_PSF_code/PIPE2D-521/Provide_PSF_2D.py", "max_forks_repo_name": "Subaru-PFS/dev_pfsmodel", "max_forks_repo_head_hexsha": "d01cf03a4c4eaa01ba5a9590ccf17744a33bdb05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.7581699346, "max_line_length": 189, "alphanum_fraction": 0.7347321533, "include": true, "reason": "import numpy", "num_tokens": 1973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.2845759920814681, "lm_q1q2_score": 0.17079919777222144}}
{"text": "#!/usr/bin/env python\n# Started: Jan 2015 (KDG)\n#    Revised to read in all the data from files: Mar 2016 (KDG)\n#       observed data defines the wavelength grids to fit on\n\"\"\"\nObsData class\n  observed data that will be used to constrain the dust model\n\"\"\"\nfrom __future__ import print_function\n\nimport numpy as np\nfrom astropy.table import Table\nfrom astropy.io import fits\n\n__all__ = [\"ObsData\"]\n\n\n# Object for the observed dust data\nclass ObsData():\n    \"\"\"\n    ObsData Class\n\n    Parameters\n    ----------\n    ext_filenames: list of 'string'\n        filenames with the observed extincction curve\n\n    avnhi_filenames: list of 'string'\n        filename with the observed A(V)/N(HI) value + unc\n\n    abund_filename: 'string'\n        filename with the observed atomic abundances\n\n    ir_emis_filename: 'string'\n        filename with the observed infrared dust emission\n\n    dust_scat_filename: 'string'\n        filename with the observed dust scattering (a, g) parameters\n        [currently not used - hard coded for MW diffuse - need to change]\n\n    ext_tags : list of 'string'\n        list of tags identifying the origin of the\n        dust extinction curve segments\n\n    Attributes\n    ----------\n    alnhi : float\n        A(lamda)/N(HI) value for extinction curve\n\n    alnhi_unc : float\n        uncertainty in A(lamda)/N(HI) value for extinction curve\n\n    ext_waves : 'numpy.ndarray'\n        wavelengths for the extinction curve\n\n    ext_alav : 'numpy.ndarray'\n        extinction curve in A(lambda)/A(V) units\n\n    ext_alav_unc : 'numpy.ndarray'\n        extinction curve uncertainties in A(lambda)/A(V) units\n\n    ext_alnhi : 'numpy.ndarray'\n        extinction curve in A(lambda)/N(HI) units\n\n    ext_alnhi_unc : 'numpy.ndarray'\n        extinction curve uncertainties in A(lambda)/N(HI) units\n\n    ext_tags : 'numpy.ndarray'\n        string tags identifying the origin of the extinction curve measurement\n\n\n    \"\"\"\n\n    # read in the data from files\n    def __init__(self, ext_filenames, avnhi_filename,\n                 abund_filename, ir_emis_filename,\n                 dust_scat_filename, ext_tags=None,\n                 scat_path=\"./\"):\n\n        # extinction curve\n        self.fit_extinction = True\n        self.ext_waves = np.empty((0))\n        self.ext_alav = np.empty((0))\n        self.ext_alav_unc = np.empty((0))\n        self.ext_tags = []\n\n        if isinstance(ext_filenames, (list, tuple)):\n            for i, filename in enumerate(ext_filenames):\n                t = Table.read(filename, format='ascii.commented_header')\n                self.ext_waves = np.concatenate([self.ext_waves,\n                                                 1.0/t['wave']])\n                self.ext_alav = np.concatenate([self.ext_alav,\n                                                t['A(l)/A(V)']])\n                self.ext_alav_unc = np.concatenate([self.ext_alav_unc,\n                                                    t['unc']])\n                if ext_tags is not None:\n                    cur_tag = ext_tags[i]\n                else:\n                    cur_tag = 'Tag' + str(i+1)\n                self.ext_tags = self.ext_tags + len(t['wave'])*[cur_tag]\n        else:\n            # assume it is a FITS file (need to add checks)\n            hdulist = fits.open(ext_filenames)\n            for i in range(1, len(hdulist)):\n                t = hdulist[i].data\n                # hack to get AzV 215 to work\n                #  need to get a better file format for FITS extinction curves\n                #  units, etc.\n                trv = 3.65\n                ext = (t['EXT']/trv) + 1\n                ext_unc = t['UNC']/trv\n\n                # only keep positive measurements\n                gindxs, = np.where(ext > 0.0)\n                self.ext_waves = np.concatenate([self.ext_waves,\n                                                 t['WAVELENGTH'][gindxs]])\n                self.ext_alav = np.concatenate([self.ext_alav, ext[gindxs]])\n                self.ext_alav_unc = np.concatenate([self.ext_alav_unc,\n                                                    ext_unc[gindxs]])\n                self.ext_tags = self.ext_tags + \\\n                    len(t['WAVELENGTH'])*[hdulist[i].header['EXTNAME']]\n\n            hdulist.close()\n\n        # sort\n        sindxs = np.argsort(self.ext_waves)\n        self.ext_waves = self.ext_waves[sindxs]\n        self.ext_alav = self.ext_alav[sindxs]\n        self.ext_alav_unc = self.ext_alav_unc[sindxs]\n        self.ext_tags = np.array(self.ext_tags)[sindxs]\n\n        # normalization from A(V) to N(HI)\n        t = Table.read(avnhi_filename,\n                       format='ascii.commented_header',\n                       header_start=-1)\n        self.avnhi = t['Av_to_NHI'][0]\n        self.avnhi_unc = t['unc'][0]\n\n        # change the extinction normalization from A(V) to N(HI)\n        self.ext_alnhi = self.ext_alav*self.avnhi\n        self.ext_alnhi_unc = (np.square(self.ext_alav_unc/self.ext_alav)\n                              + np.square(self.avnhi_unc/self.avnhi))\n        self.ext_alnhi_unc = self.ext_alnhi*np.sqrt(self.ext_alnhi_unc)\n\n        # dust abundances\n        self.fit_abundance = False\n        if abund_filename is not None:\n            self.fit_abundance = True\n            t = Table.read(abund_filename, format='ascii.commented_header')\n            self.abundance = {}\n            self.total_abundance = {}\n            for i in range(len(t)):\n                self.abundance[t['atom'][i]] = (t['abund'][i],\n                                                t['abund_unc'][i])\n                self.total_abundance[t['atom'][i]] = (t['total_abund'][i],\n                                                      t['total_abund_unc'][i])\n\n        # diffuse IR emission spectrum\n        self.fit_ir_emission = False\n        if ir_emis_filename is not None:\n            self.fit_ir_emission = True\n            t = Table.read(ir_emis_filename, format='ascii.commented_header')\n            self.ir_emission_waves = np.array(t['WAVE'])\n            self.ir_emission = np.array(t['SPEC'])/1e20\n            self.ir_emission_unc = np.array(t['ERROR'])/1e20\n            # check if any uncs are zero\n            gindxs, = np.where(self.ir_emission_unc == 0.0)\n            if len(gindxs) > 0:\n                self.ir_emission_unc[gindxs] = 0.1*self.ir_emission[gindxs]\n\n            # sort\n            sindxs = np.argsort(self.ir_emission_waves)\n            self.ir_emission_waves = self.ir_emission_waves[sindxs]\n            self.ir_emission = self.ir_emission[sindxs]\n            self.ir_emission_unc = self.ir_emission_unc[sindxs]\n\n        # dust albedo (Gordon et al. AoD proceedings)\n        self.fit_scat_a = False\n        self.fit_scat_g = False\n        if dust_scat_filename is not None:\n            self.fit_scat_a = True\n            self.fit_scat_g = True\n            files_dgl = [\"mathis73\", \"morgan76\", \"lillie76\", \"toller81\",\n                         \"murthy93\", \"murthy95\", \"petersohn97\", \"witt97\",\n                         \"schiminovich01\", \"shalima04\", \"sujatha05\",\n                         \"sujatha07\", \"sujatha10\"]\n\n            scat_waves = []\n            scat_albedo = []\n            scat_albedo_unc = []\n            scat_g = []\n            scat_g_unc = []\n            scat_ref = []\n            for sfile in files_dgl:\n                f = open(scat_path + sfile + '.dat', 'r')\n                ref = f.readline().rstrip()\n                f.close()\n\n                t = Table.read(scat_path+sfile+'.dat',\n                               format='ascii',\n                               header_start=1)\n                for k in range(len(t)):\n                    scat_waves.append(t['wave,'][k])\n                    scat_albedo.append(t['albedo,'][k])\n                    scat_albedo_unc.append(t['delta,'][k])\n                    scat_g.append(t['g,'][k])\n                    scat_g_unc.append(t['delta'][k])\n                    scat_ref.append(ref)\n\n            # remove all the measurements with zero uncertainty\n            gindxs, = np.where(np.array(scat_albedo_unc) > 0.0)\n            self.scat_a_waves = np.array(scat_waves)[gindxs]*1e-4\n            self.scat_albedo = np.array(scat_albedo)[gindxs]\n            self.scat_albedo_unc = np.array(scat_albedo_unc)[gindxs]\n            self.scat_a_ref = np.array(scat_ref)[gindxs]\n\n            # sort\n            sindxs = np.argsort(self.scat_a_waves)\n            self.scat_a_waves = self.scat_a_waves[sindxs]\n            self.scat_albedo = self.scat_albedo[sindxs]\n            self.scat_albedo_unc = self.scat_albedo_unc[sindxs]\n            self.scat_a_ref = self.scat_a_ref[sindxs]\n\n            # remove all the measurements with zero uncertainty\n            gindxs, = np.where(np.array(scat_g_unc) > 0.0)\n            self.scat_g_waves = np.array(scat_waves)[gindxs]*1e-4\n            self.scat_g = np.array(scat_g)[gindxs]\n            self.scat_g_unc = np.array(scat_g_unc)[gindxs]\n            self.scat_g_ref = np.array(scat_ref)[gindxs]\n\n            # sort\n            sindxs = np.argsort(self.scat_g_waves)\n            self.scat_g_waves = self.scat_g_waves[sindxs]\n            self.scat_g = self.scat_g[sindxs]\n            self.scat_g_unc = self.scat_g_unc[sindxs]\n            self.scat_g_ref = self.scat_g_ref[sindxs]\n", "meta": {"hexsha": "8959e2a0192b0c4f6dbd5bcbb52bd91e15d5703a", "size": 9221, "ext": "py", "lang": "Python", "max_stars_repo_path": "DGFit/ObsData.py", "max_stars_repo_name": "bsipocz/DGFit", "max_stars_repo_head_hexsha": "265dfb4621432948edbae6eb824d58d67b72c4b6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DGFit/ObsData.py", "max_issues_repo_name": "bsipocz/DGFit", "max_issues_repo_head_hexsha": "265dfb4621432948edbae6eb824d58d67b72c4b6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DGFit/ObsData.py", "max_forks_repo_name": "bsipocz/DGFit", "max_forks_repo_head_hexsha": "265dfb4621432948edbae6eb824d58d67b72c4b6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9071729958, "max_line_length": 78, "alphanum_fraction": 0.5521093157, "include": true, "reason": "import numpy,from astropy", "num_tokens": 2241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3311197462295937, "lm_q1q2_score": 0.17073193564512945}}
{"text": "import numpy as np\r\nimport pygame\r\nimport time\r\n\r\npygame.init() # iniciamos el pygame\r\n\r\nancho, alto = 600, 600\r\npantalla = pygame.display.set_mode((ancho,alto)) # creamos la pantalla\r\nfondoPantalla = 35,35,35 # de color casi negro\r\n\r\npantalla.fill(fondoPantalla) # se pinta el fondo de la pantalla\r\n\r\n# numero de celdas en cada eje\r\nceldasX, celdasY = 50,50\r\n\r\nanchoCeldas = ancho / celdasX # ancho de la celda\r\naltoCeldas = alto / celdasY # alto de la celda\r\n\r\npauseExecution = True # control de la ejecución del juego\r\n\r\n# celda a 1 --> viva || celda a 0 --> muerta\r\nestadoTablero = np.zeros((celdasX,celdasY)) # matriz de tamaño del tablero\r\n\r\n# inicialización del tablero\r\n# palo\r\nestadoTablero[5,3] = 1\r\nestadoTablero[5,4] = 1\r\nestadoTablero[5,5] = 1\r\n\r\n# automata que se mueve por pantalla\r\nestadoTablero[21,21] = 1\r\nestadoTablero[22,22] = 1\r\nestadoTablero[22,23] = 1\r\nestadoTablero[21,23] = 1\r\nestadoTablero[20,23] = 1\r\n\r\nwhile True:\r\n    # para no sobreescribir el tablero puesto que las comparaciones se hacen con el estado inicial y no con el actualizado en el momento\r\n    copiaTablero = np.copy(estadoTablero)\r\n\r\n    # limpiamos la pantalla\r\n    pantalla.fill(fondoPantalla) # se pinta el fondo de la pantalla\r\n\r\n    # delay\r\n    time.sleep(0.1)\r\n\r\n    ev = pygame.event.get() \r\n\r\n    for event in ev:\r\n        if event.type == pygame.KEYDOWN: # al pulsar el teclado\r\n            pauseExecution = not pauseExecution\r\n        \r\n        mouseClick = pygame.mouse.get_pressed() # nos da el boton izq, rueda o boton derecho pulsado\r\n\r\n        if sum(mouseClick) > 0:\r\n            posX, posY = pygame.mouse.get_pos() # lo devuelve en pixeles\r\n            celX, celY = int(np.floor(posX / anchoCeldas)), int(np.floor(posY / altoCeldas)) # pos celda\r\n            copiaTablero[celX,celY] = not mouseClick[2] # si pulso el izq pon 0, si pulso otro pon 1\r\n\r\n    # recorremos el tablero\r\n    for y in range (0,celdasY):\r\n        for x in range (0,celdasX):\r\n\r\n            if  not pauseExecution:\r\n                # vecinos cercanos a cada x,y\r\n                # con el modulo conseguimos que el vecino del tablero de un borde actue como un toroide [de la izquierda se pasa a la derecha y de arriba a abajo]\r\n                vecinos = estadoTablero[(x-1) % celdasX,(y-1) % celdasY] + \\\r\n                        estadoTablero[(x-1) % celdasX,(y) % celdasY] + \\\r\n                        estadoTablero[(x-1) % celdasX,(y+1) % celdasY] + \\\r\n                        estadoTablero[(x) % celdasX,(y-1) % celdasY] + \\\r\n                        estadoTablero[(x) % celdasX,(y+1) % celdasY] + \\\r\n                        estadoTablero[(x+1) % celdasX,(y-1) % celdasY] + \\\r\n                        estadoTablero[(x+1) % celdasX,(y) % celdasY] + \\\r\n                        estadoTablero[(x+1) % celdasX,(y+1) % celdasY] \r\n\r\n                # regla 1 del juego de la vida: si muerto y tres vecinos vivos, entonces revive\r\n                if estadoTablero[x,y] == 0 and vecinos == 3:\r\n                    copiaTablero[x,y] = 1\r\n                \r\n                # regla 2 del juego de la vida: si vivo y vecinos menor que 2 o mayor que 3, entonces muere\r\n                elif estadoTablero[x,y] == 1 and (vecinos < 2 or vecinos > 3):\r\n                    copiaTablero[x,y] = 0\r\n\r\n            # polígono\r\n            poligono = [((x)*anchoCeldas, (y)*altoCeldas),\r\n                        ((x+1)*anchoCeldas, (y)*altoCeldas),\r\n                        ((x+1)*anchoCeldas, (y+1)*altoCeldas),\r\n                        ((x)*anchoCeldas, (y+1)*altoCeldas)]\r\n\r\n            # el ultimo término es el grosor del poligono\r\n            if copiaTablero[x,y] == 0: # muerto en negro\r\n                pygame.draw.polygon(pantalla, (128,128,128), poligono, 1) \r\n            else: # vivo en blanco\r\n                pygame.draw.polygon(pantalla, (255,255,255), poligono, 0)\r\n\r\n    estadoTablero = np.copy(copiaTablero)\r\n\r\n    pygame.display.flip() # actualizo los fotogramas", "meta": {"hexsha": "7ba4eed3cbdf191e88cf26ecd6de29e3636c4f27", "size": 3942, "ext": "py", "lang": "Python", "max_stars_repo_path": "juegoDeLaVida.py", "max_stars_repo_name": "rsanchezm98/juego-de-la-vida", "max_stars_repo_head_hexsha": "0b5244f8c0fda7969d66ed5a63649721fccb368b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-25T22:07:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-25T22:07:22.000Z", "max_issues_repo_path": "juegoDeLaVida.py", "max_issues_repo_name": "rsanchezm98/juego-de-la-vida", "max_issues_repo_head_hexsha": "0b5244f8c0fda7969d66ed5a63649721fccb368b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "juegoDeLaVida.py", "max_forks_repo_name": "rsanchezm98/juego-de-la-vida", "max_forks_repo_head_hexsha": "0b5244f8c0fda7969d66ed5a63649721fccb368b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2244897959, "max_line_length": 163, "alphanum_fraction": 0.5819381025, "include": true, "reason": "import numpy", "num_tokens": 1215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.17073193224172747}}
{"text": "from __future__ import print_function, division, absolute_import\n\nfrom ..basis import spin_basis_1d as _default_basis\nfrom ..basis import isbasis as _isbasis\n\n#from ._oputils import _get_matvec_function, matvec as _matvec\n\nfrom ..tools.matvec import _matvec\nfrom ..tools.matvec import _get_matvec_function\n\nfrom ._make_hamiltonian import make_static\nfrom ._make_hamiltonian import _check_almost_zero\n\nfrom . import hamiltonian_core\n\n# need linear algebra packages\nimport scipy.sparse.linalg as _sla\nimport scipy.linalg as _la\nimport scipy.sparse as _sp\nimport numpy as _np\n\nimport functools\nfrom six import iteritems,itervalues,viewkeys\n\n__all__=[\"quantum_operator\",\"isquantum_operator\"]\n\t\t\n# function used to create Linearquantum_operator with fixed set of parameters. \ndef _quantum_operator_dot(op,pars,v):\n\treturn op.dot(v,pars=pars,check=False)\n\nclass quantum_operator(object):\n\t\"\"\"Constructs parameter-dependent (hermitian and nonhermitian) operators.\n\n\t\tThe `quantum_operator` class maps quantum operators to keys of a dictionary. When calling various methods\n\t\tof `quantum_operator`, it allows one to 'dynamically' specify the pre-factors of these operators.\n\n\t\tExamples\n\t\t---------\n\n\t\tIt is often required to be able to handle a parameter-dependent Hamiltonian :math:`H(\\\\lambda)=H_1 + \\\\lambda H_2`, e.g.\n\n\t\t.. math::\n\t\t\tH_1=\\sum_j J_{zz}S^z_jS^z_{j+1} + h_xS^x_j, \\\\qquad H_2=\\\\sum_j S^z_j\n\n\t\tThe following code snippet shows how to use the `quantum_operator` class to vary the parameter :math:`\\\\lambda`\n\t\twithout having to re-build the Hamiltonian every time.\n\n\t\t.. literalinclude:: ../../doc_examples/quantum_operator-example.py\n\t\t\t:linenos:\n\t\t\t:language: python\n\t\t\t:lines: 7-\n\n\t\"\"\"\n\tdef __init__(self,input_dict,N=None,basis=None,shape=None,copy=True,check_symm=True,check_herm=True,check_pcon=True,matrix_formats={},dtype=_np.complex128,**basis_args):\n\t\t\"\"\"Intializes the `quantum_operator` object (parameter dependent quantum quantum_operators).\n\n\t\tParameters\n\t\t-----------\n\t\tinput_dict : dict\n\t\t\tThe `values` of this dictionary contain quantum_operator lists, in the same format as the `static_list` \n\t\t\targument of the `hamiltonian` class.\n\n\t\t\tThe `keys` of this dictionary correspond to the parameter values, e.g. :math:`J_{zz},h_x`, and are \n\t\t\tused to specify the coupling strength during calls of the `quantum_operator` class methods.\n\n\t\t\t>>> # use \"Jzz\" and \"hx\" keys to specify the zz and x coupling strengths, respectively\n\t\t\t>>> input_dict = { \"Jzz\": [[\"zz\",Jzz_bonds]], \"hx\" : [[\"x\" ,hx_site ]] } \n\n\t\tN : int, optional\n\t\t\tNumber of lattice sites for the `hamiltonian` object.\n\t\tdtype : 'type'\n\t\t\tData type (e.g. numpy.float64) to construct the quantum_operator with.\n\t\tshape : tuple, optional\n\t\t\tShape to create the `hamiltonian` object with. Default is `shape = None`.\n\t\tcopy: bool, optional\n\t\t\tIf set to `True`, this option creates a copy of the input array. \n\t\tcheck_symm : bool, optional \n\t\t\tEnable/Disable symmetry check on `static_list` and `dynamic_list`.\n\t\tcheck_herm : bool, optional\n\t\t\tEnable/Disable hermiticity check on `static_list` and `dynamic_list`.\n\t\tcheck_pcon : bool, optional\n\t\t\tEnable/Disable particle conservation check on `static_list` and `dynamic_list`.\n\t\tmatrix_formats: dict, optional\n\t\t\tDictionary of key,value pairs which, given a key associated with an operator in `input_dict`, the value of this key\n\t\t\tspecifies the sparse matrix format {\"csr\",\"csc\",\"dia\",\"dense\"}.\n\t\tkw_args : dict\n\t\t\tOptional additional arguments to pass to the `basis` class, if not already using a `basis` object\n\t\t\tto create the quantum_operator.\t\t\n\t\t\t\n\t\t\"\"\"\n\t\tself._is_dense = False\n\t\tself._ndim = 2\n\t\tself._basis = basis\n\n\n\n\t\tif not (dtype in hamiltonian_core.supported_dtypes):\n\t\t\traise TypeError('hamiltonian does not support type: '+str(dtype))\n\t\telse:\n\t\t\tself._dtype=dtype\n\t\t\n\t\topstr_dict = {}\n\t\tother_dict = {}\n\t\tself._quantum_operator = {}\n\t\tif isinstance(input_dict,dict):\n\t\t\tfor key,op in iteritems(input_dict):\n\t\t\t\tif type(key) is not str:\n\t\t\t\t\traise ValueError(\"keys to input_dict must be strings.\")\n\t\t\t\t\t\n\t\t\t\tif type(op) not in [list,tuple]:\n\t\t\t\t\traise ValueError(\"input_dict must contain values which are lists/tuples.\")\n\n\t\t\t\topstr_list = []\n\t\t\t\tother_list = []\n\t\t\t\tfor ele in op:\n\t\t\t\t\tif hamiltonian_core._check_static(ele):\n\t\t\t\t\t\topstr_list.append(ele)\n\t\t\t\t\telse:\n\t\t\t\t\t\tother_list.append(ele)\n\n\t\t\t\tif opstr_list:\n\t\t\t\t\topstr_dict[key] = opstr_list\n\t\t\t\tif other_list:\n\t\t\t\t\tother_dict[key] = other_list\n\t\telse:\n\t\t\traise ValueError(\"input_dict must be dictionary or another quantum_operator quantum_operators\")\n\t\t\t\n\t\tif opstr_dict:\n\t\t\t# check if user input basis\n\n\t\t\tif basis is not None:\n\t\t\t\tif len(basis_args) > 0:\n\t\t\t\t\twrong_keys = set(basis_args.keys())\n\t\t\t\t\ttemp = \", \".join([\"{}\" for key in wrong_keys])\n\t\t\t\t\traise ValueError((\"unexpected optional argument(s): \"+temp).format(*wrong_keys))\n\n\t\t\t# if not\n\t\t\tif basis is None: \n\t\t\t\tif N is None: # if L is missing \n\t\t\t\t\traise Exception('if opstrs in use, argument N needed for basis class')\n\n\t\t\t\tif type(N) is not int: # if L is not int\n\t\t\t\t\traise TypeError('argument N must be integer')\n\n\t\t\t\tbasis=_default_basis(N,**basis_args)\n\n\t\t\telif not _isbasis(basis):\n\t\t\t\traise TypeError('expecting instance of basis class for argument: basis')\n\n\n\t\t\tstatic_opstr_list = []\n\t\t\tfor key,opstr_list in iteritems(opstr_dict):\n\t\t\t\tstatic_opstr_list.extend(opstr_list)\n\n\t\t\tif check_herm:\n\t\t\t\tbasis.check_hermitian(static_opstr_list, [])\n\n\t\t\tif check_symm:\n\t\t\t\tbasis.check_symm(static_opstr_list,[])\n\n\t\t\tif check_pcon:\n\t\t\t\tbasis.check_pcon(static_opstr_list,[])\n\n\t\t\tself._shape=(basis.Ns,basis.Ns)\n\n\t\t\tfor key,opstr_list in iteritems(opstr_dict):\n\t\t\t\tO = make_static(basis,opstr_list,dtype)\n\t\t\t\tself._quantum_operator[key] = O\n\n\n\t\tif other_dict:\n\t\t\tif not hasattr(self,\"_shape\"):\n\t\t\t\tfound = False\n\t\t\t\tif shape is None: # if no shape argument found, search to see if the inputs have shapes.\n\t\t\t\t\tfor key,O_list in iteritems(other_dict):\n\t\t\t\t\t\tfor O in O_list:\n\t\t\t\t\t\t\ttry: # take the first shape found\n\t\t\t\t\t\t\t\tshape = O.shape\n\t\t\t\t\t\t\t\tfound = True\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\texcept AttributeError: \n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tfound = True\n\n\t\t\t\tif not found:\n\t\t\t\t\traise ValueError('no dictionary entries have shape attribute.')\n\t\t\t\tif shape[0] != shape[1]:\n\t\t\t\t\traise ValueError('quantum_operator must be square matrix')\n\n\t\t\t\tself._shape=shape\n\n\n\n\t\t\tfor key,O_list in iteritems(other_dict):\n\t\t\t\tfor i,O in enumerate(O_list):\n\t\t\t\t\tif _sp.issparse(O):\n\t\t\t\t\t\tself._mat_checks(O)\n\t\t\t\t\t\tif i == 0:\n\t\t\t\t\t\t\tself._quantum_operator[key] = O\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tself._quantum_operator[key] += O\n\t\t\t\t\t\t\texcept NotImplementedError:\n\t\t\t\t\t\t\t\tself._quantum_operator[key] = self._quantum_operator[key] + O\n\n\t\t\t\t\telif O.__class__ is _np.ndarray:\n\t\t\t\t\t\tself._mat_checks(O)\n\t\t\t\t\t\tself._is_dense=True\n\t\t\t\t\t\tif i == 0:\n\t\t\t\t\t\t\tself._quantum_operator[key] = O\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tself._quantum_operator[key] += O\n\t\t\t\t\t\t\texcept NotImplementedError:\n\t\t\t\t\t\t\t\tself._quantum_operator[key] = self._quantum_operator[key] + O\n\n\t\t\t\t\telif O.__class__ is _np.matrix:\n\t\t\t\t\t\tself._mat_checks(O)\n\t\t\t\t\t\tself._is_dense=True\n\t\t\t\t\t\tif i == 0:\n\t\t\t\t\t\t\tself._quantum_operator[key] = O\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tself._quantum_operator[key] += O\n\t\t\t\t\t\t\texcept NotImplementedError:\n\t\t\t\t\t\t\t\tself._quantum_operator[key] = self._quantum_operator[key] + O\n\n\t\t\t\t\telse:\n\t\t\t\t\t\tO = _np.asanyarray(O)\n\t\t\t\t\t\tself._mat_checks(O)\n\t\t\t\t\t\tif i == 0:\n\t\t\t\t\t\t\tself._quantum_operator[key] = O\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tself._quantum_operator[key] += O\n\t\t\t\t\t\t\texcept NotImplementedError:\n\t\t\t\t\t\t\t\tself._quantum_operator[key] = self._quantum_operator[key] + O\n\n\t\t\t\t\t\n\n\t\telse:\n\t\t\tif not hasattr(self,\"_shape\"):\n\t\t\t\tif shape is None:\n\t\t\t\t\t# check if user input basis\n\t\t\t\t\tbasis=basis_args.get('basis')\t\n\n\t\t\t\t\t# if not\n\t\t\t\t\tif basis is None: \n\t\t\t\t\t\tif N is None: # if N is missing \n\t\t\t\t\t\t\traise Exception(\"argument N or shape needed to create empty quantum_operator\")\n\n\t\t\t\t\t\tif type(N) is not int: # if L is not int\n\t\t\t\t\t\t\traise TypeError('argument N must be integer')\n\n\t\t\t\t\t\tbasis=_default_basis(N,**basis_args)\n\n\t\t\t\t\telif not _isbasis(basis):\n\t\t\t\t\t\traise TypeError('expecting instance of basis class for argument: basis')\n\n\t\t\t\t\tshape = (basis.Ns,basis.Ns)\n\n\t\t\t\telse:\n\t\t\t\t\tbasis=basis_args.get('basis')\t\n\t\t\t\t\tif not basis is None: \n\t\t\t\t\t\traise ValueError(\"empty hamiltonian only accepts basis or shape, not both\")\n\n\t\t\t\tif len(shape) != 2:\n\t\t\t\t\traise ValueError('expecting ndim = 2')\n\t\t\t\tif shape[0] != shape[1]:\n\t\t\t\t\traise ValueError('hamiltonian must be square matrix')\n\n\t\t\t\tself._shape=shape\n\n\t\tif basis is not None:\n\t\t\tself._basis = basis\n\n\t\tself._Ns = self._shape[0]\n\n\t\tkeys = list(self._quantum_operator.keys())\n\t\tfor key in keys:\n\t\t\tif _check_almost_zero(self._quantum_operator[key]):\n\t\t\t\tself._quantum_operator.pop(key)\n\n\t\tself.update_matrix_formats(matrix_formats)\n\n\t@property\n\tdef get_operators(self,key):\n\t\treturn self._quantum_operator[key]\n\t\n\t@property\n\tdef shape(self):\n\t\treturn self._shape\n\t\n\n\t@property\n\tdef basis(self):\n\t\t\"\"\":obj:`basis`: basis used to build the `hamiltonian` object. Defaults to `None` if quantum_operator has \n\t\tno basis (i.e. was created externally and passed as a precalculated array).\n\n\t\t\"\"\"\n\t\tif self._basis is not None:\n\t\t\treturn self._basis\n\t\telse:\n\t\t\traise AttributeError(\"object has no attribute 'basis'\")\n\n\t@property\n\tdef ndim(self):\n\t\t\"\"\"int: number of dimensions, always equal to 2. \"\"\"\n\t\treturn self._ndim\n\t\n\t@property\n\tdef Ns(self):\n\t\t\"\"\"int: number of states in the (symmetry-reduced) Hilbert space spanned by `basis`.\"\"\"\n\t\treturn self._Ns\n\n\t@property\n\tdef get_shape(self):\n\t\t\"\"\"tuple: shape of the `quantum_operator` object, always equal to `(Ns,Ns)`.\"\"\"\n\t\treturn self._shape\n\n\t@property\n\tdef is_dense(self):\n\t\t\"\"\"bool: `True` if the quantum_operator contains a dense matrix as a componnent of either \n\t\tthe static or dynamic lists.\n\n\t\t\"\"\"\n\t\treturn self._is_dense\n\n\t@property\n\tdef dtype(self):\n\t\t\"\"\"type: data type of `quantum_operator` object.\"\"\"\n\t\treturn _np.dtype(self._dtype).name\n\n\t@property\n\tdef T(self):\n\t\t\"\"\":obj:`quantum_operator`: transposes the operator matrix: :math:`H_{ij}\\\\mapsto H_{ji}`.\"\"\"\n\t\treturn self.transpose()\n\n\t@property\n\tdef H(self):\n\t\t\"\"\":obj:`quantum_operator`: transposes and conjugates the operator matrix: :math:`H_{ij}\\\\mapsto H_{ji}^*`.\"\"\"\n\t\treturn self.getH()\n\n\n\n\n\t### state manipulation/observable routines\n\n\tdef matvec(self,x):\n\t\t\"\"\"Matrix-vector multiplication.\n\n\t\tPerforms the operation y=A*x where A is an MxN linear operator and x is a column vector or 1-d array.\n\n\t\tNotes\n\t\t-----\n\t\tThis matvec wraps the user-specified matvec routine or overridden _matvec method to ensure that y has the correct shape and type.\n\t\n\t\tParameters\n\t\t----------\n\t\tx : {matrix, ndarray}\n\t\t\tAn array with shape (N,) or (N,1).\n\n\t\tReturns\n\t\t-------\n\t\ty : {matrix, ndarray}\n\t\t\tA matrix or ndarray with shape (M,) or (M,1) depending on the type and shape of the x argument.\n\n\t\t\"\"\"\n\n\t\treturn self.dot(x)\n\n\tdef rmatvec(self,x):\n\t\t\"\"\"Adjoint matrix-vector multiplication.\n\n\t\tPerforms the operation y = A^H * x where A is an MxN linear operator and x is a column vector or 1-d array.\n\n\t\tNotes\n\t\t-----\n\t\tThis rmatvec wraps the user-specified rmatvec routine or overridden _rmatvec method to ensure that y has the correct shape and type.\n\n\t\tParameters\n\t\t----------\n\t\tx : {matrix, ndarray}\n\t\t\tAn array with shape (M,) or (M,1).\n\t\t\n\t\tReturns\n\t\t-------\n\t\ty : {matrix, ndarray}\n\t\t\tA matrix or ndarray with shape (N,) or (N,1) depending on the type and shape of the x argument.\n\n\t\t\"\"\"\n\t\treturn self.H.dot(x)\n\n\tdef matmat(self,X):\n\t\t\"\"\"Matrix-matrix multiplication.\n\n\t\tPerforms the operation y=A*X where A is an MxN linear operator and X dense N*K matrix or ndarray.\n\n\t\tNotes\n\t\t-----\n\t\tThis matmat wraps any user-specified matmat routine or overridden _matmat method to ensure that y has the correct type.\n\n\t\tParameters\n\t\t----------\n\t\tX : {matrix, ndarray}\n\t\t\tAn array with shape (N,K).\n\n\t\tReturns\n\t\t-------\n\t\tY : {matrix, ndarray}\n\t\t\tA matrix or ndarray with shape (M,K) depending on the type of the X argument.\n\n\t\t\"\"\"\n\t\treturn self.dot(X)\n\n\tdef dot(self,V,pars={},check=True,out=None,overwrite_out=True,a=1.0):\n\t\t\"\"\"Matrix-vector multiplication of `quantum_operator` quantum_operator for parameters `pars`, with state `V`.\n\n\t\t.. math::\n\t\t\taH(\\\\lambda)|V\\\\rangle\n\n\t\tNotes\n\t\t-----\n\n\t\tParameters\n\t\t-----------\n\t\tV : numpy.ndarray\n\t\t\tVector (quantums tate) to multiply the `quantum_operator` quantum_operator with.\n\t\tpars : dict, optional\n\t\t\tDictionary with same `keys` as `input_dict` and coupling strengths as `values`. Any missing `keys`\n\t\t\tare assumed to be set to unity.\n\t\tcheck : bool, optional\n\t\t\tWhether or not to do checks for shape compatibility.\n\t\tout : array_like, optional\n\t\t\tspecify the output array for the the result. This is not supported if `V` is a sparse matrix. \n\t\toverwrite_out : bool, optional\n\t\t\tflag used to toggle between two different ways to treat `out`. If set to `True` all values in `out` will be overwritten with the result of the dot product. \n\t\t\tIf `False` the result of the dot product will be added to the values of `out`.\n\t\ta : scalar, optional\n\t\t\tscalar to multiply the final product with: :math:`B = aHV`. \t\t\t\n\n\t\tReturns\n\t\t--------\n\t\tnumpy.ndarray\n\t\t\tVector corresponding to the `quantum_operator` quantum_operator applied on the state `V`.\n\n\t\tExamples\n\t\t---------\n\t\t>>> B = H.dot(A,pars=pars,check=True)\n\n\t\tcorresponds to :math:`B = HA`. \n\t\n\t\t\"\"\"\n\n\t\t\n\t\tpars = self._check_scalar_pars(pars)\n\n\n\t\tif check:\n\t\t\ttry:\n\t\t\t\tshape = V.shape\n\t\t\texcept AttributeError:\n\t\t\t\tV =_np.asanyarray(V)\n\t\t\t\tshape = V.shape\n\n\t\t\tif shape[0] != self._shape[1]:\n\t\t\t\traise ValueError(\"matrix dimension mismatch with shapes: {0} and {1}.\".format(V.shape,self._shape))\n\n\t\t\tif V.ndim not in [1,2]:\n\t\t\t\traise ValueError(\"Expecting  0< V.ndim < 3.\")\n\n\t\tresult_dtype = _np.result_type(V.dtype,self._dtype)\n\n\t\tif not (result_dtype in hamiltonian_core.supported_dtypes):\n\t\t\traise TypeError('hamiltonian does not support type: '+str(dtype))\n\n\t\tif self.Ns <= 0:\n\t\t\treturn _np.asarray([],dtype=result_dtype)\n\n\t\tif _sp.issparse(V):\n\t\t\tif out is not None:\n\t\t\t\traise TypeError(\"'out' option does not apply for sparse inputs.\")\n\n\t\t\tsparse_constuctor = getattr(_sp,V.get_format()+\"_matrix\")\n\t\t\tout = sparse_constuctor(V.shape,dtype=result_dtype)\n\t\t\tfor key,J in pars.items():\n\t\t\t\tout = out + J*self._quantum_operator[key].dot(V)\n\t\t\tout = a*out\n\n\t\telse:\n\t\t\tif out is not None:\n\t\t\t\ttry:\n\t\t\t\t\tif out.dtype != result_dtype:\n\t\t\t\t\t\traise TypeError(\"'out' must be array with correct dtype and dimensions for output array.\")\n\t\t\t\t\tif out.shape != V.shape:\n\t\t\t\t\t\traise ValueError(\"'out' must be array with correct dtype and dimensions for output array.\")\n\t\t\t\texcept AttributeError:\n\t\t\t\t\traise TypeError(\"'out' must be C-contiguous array with correct dtype and dimensions for output array.\")\n\n\t\t\t\tif overwrite_out:\n\t\t\t\t\tout[...] = 0\n\t\t\telse:\n\t\t\t\tout = _np.zeros_like(V,dtype=result_dtype)\n\n\t\t\teps = _np.finfo(self.dtype).eps\n\t\t\tV = _np.asarray(V,dtype=result_dtype)\n\t\t\tfor key,J in pars.items():\n\t\t\t\tif _np.abs(J)>eps:\n\t\t\t\t\tself._matvec_functions[key](self._quantum_operator[key],V,overwrite_out=False,a=a*J,out=out)\n\n\n\t\treturn out\n\n\tdef rdot(self,V,pars={},check=False,out=None,overwrite_out=True,a=1.0):\n\t\t\"\"\"Vector-matrix multiplication of `quantum_operator` quantum_operator for parameters `pars`, with state `V`.\n\n\t\t.. math::\n\t\t\ta\\\\langle V]H(\\\\lambda)\n\n\t\t\n\t\tParameters\n\t\t-----------\n\t\tV : numpy.ndarray\n\t\t\tVector (quantums tate) to multiply the `quantum_operator` quantum_operator with.\n\t\tpars : dict, optional\n\t\t\tDictionary with same `keys` as `input_dict` and coupling strengths as `values`. Any missing `keys`\n\t\t\tare assumed to be set to unity.\n\t\tcheck : bool, optional\n\t\t\tWhether or not to do checks for shape compatibility.\n\t\tout : array_like, optional\n\t\t\tspecify the output array for the the result. This is not supported if `V` is a sparse matrix. \n\t\toverwrite_out : bool, optional\n\t\t\tflag used to toggle between two different ways to treat `out`. If set to `True` all values in `out` will be overwritten with the result. \n\t\t\tIf `False` the result of the dot product will be added to the values of `out`. \n\t\ta : scalar, optional\n\t\t\tscalar to multiply the final product with: :math:`B = aVH`. \n\t\t\t\n\n\t\tReturns\n\t\t--------\n\t\tnumpy.ndarray\n\t\t\tVector corresponding to the `quantum_operator` quantum_operator applied on the state `V`.\n\n\t\tExamples\n\t\t---------\n\t\t>>> B = H.dot(A,pars=pars,check=True)\n\n\t\tcorresponds to :math:`B = AH`. \n\t\n\t\t\"\"\"\n\t\treturn self.transpose().dot(V.transpose(),pars=pars,check=check,out=out.T,overwrite_out=overwrite_out,a=a).transpose()\n\n\tdef quant_fluct(self,V,pars={},check=True,enforce_pure=False):\n\t\t\"\"\"Calculates the quantum fluctuations (variance) of `hamiltonian` operator at time `time`, in state `V`.\n\n\t\t.. math::\n\t\t\t\\\\langle V|H^2(t=\\\\texttt{time})|V\\\\rangle - \\\\langle V|H(t=\\\\texttt{time})|V\\\\rangle^2\n\n\t\tParameters\n\t\t-----------\n\t\tV : numpy.ndarray\n\t\t\tDepending on the shape, can be a single state or a collection of pure or mixed states\n\t\t\t[see `enforce_pure`].\n\t\tpars : dict, optional\n\t\t\tDictionary with same `keys` as `input_dict` and coupling strengths as `values`. Any missing `keys`\n\t\t\tare assumed to be set to unity.\n\n\t\tenforce_pure : bool, optional\n\t\t\tFlag to enforce pure expectation value of `V` is a square matrix with multiple pure states\n\t\t\tin the columns.\n\t\tcheck : bool, optional\n\t\t\t\n\t\tReturns\n\t\t--------\n\t\tfloat\n\t\t\tQuantum fluctuations of `hamiltonian` operator in state `V`.\n\n\t\tExamples\n\t\t---------\n\t\t>>> H_fluct = H.quant_fluct(V,time=0,diagonal=False,check=True)\n\n\t\tcorresponds to :math:`\\\\Delta H = \\\\sqrt{ \\\\langle V|H^2(t=\\\\texttt{time})|V\\\\rangle - \\\\langle V|H(t=\\\\texttt{time})|V\\\\rangle^2 }`. \n\t\t\t \n\t\t\"\"\"\n\n\t\tfrom .exp_op_core import isexp_op\n\n\t\tif self.Ns <= 0:\n\t\t\treturn _np.asarray([])\n\n\t\tif hamiltonian_core.ishamiltonian(V):\n\t\t\traise TypeError(\"Can't take expectation value of hamiltonian\")\n\n\t\tif isexp_op(V):\n\t\t\traise TypeError(\"Can't take expectation value of exp_op\")\n\n\t\t# fluctuations =  expctH2 - expctH^2\n\t\tkwargs = dict(enforce_pure=enforce_pure)\n\t\tV_dot = self.dot(V,pars=pars,check=check)\n\t\texpt_value_sq = self._expt_value_core(V,V_dot,**kwargs)**2\n\n\t\tif V.shape[0] != V.shape[1] or enforce_pure:\n\t\t\tsq_expt_value = self._expt_value_core(V_dot,V_dot,**kwargs)\n\t\telse:\n\t\t\tV_dot = self.dot(V_dot,time=time,check=check)\n\t\t\tsq_expt_value = self._expt_value_core(V,V_dot,**kwargs)\n\n\t\treturn sq_expt_value - expt_value_sq\n\n\tdef expt_value(self,V,pars={},check=True,enforce_pure=False):\n\t\t\"\"\"Calculates expectation value of `hamiltonian` operator at time `time`, in state `V`.\n\n\t\t.. math::\n\t\t\t\\\\langle V|H(t=\\\\texttt{time})|V\\\\rangle\n\n\t\tParameters\n\t\t-----------\n\t\tV : numpy.ndarray\n\t\t\tDepending on the shape, can be a single state or a collection of pure or mixed states\n\t\t\t[see `enforce_pure` argument of `basis.ent_entropy`].\n\t\tpars : dict, optional\n\t\t\tDictionary with same `keys` as `input_dict` and coupling strengths as `values`. Any missing `keys`\n\t\t\tare assumed to be set to unity.\n\t\tenforce_pure : bool, optional\n\t\t\tFlag to enforce pure expectation value of `V` is a square matrix with multiple pure states\n\t\t\tin the columns.\n\t\tcheck : bool, optional\n\t\t\t\n\t\tReturns\n\t\t--------\n\t\tfloat\n\t\t\tExpectation value of `hamiltonian` operator in state `V`.\n\n\t\tExamples\n\t\t---------\n\t\t>>> H_expt = H.expt_value(V,time=0,diagonal=False,check=True)\n\n\t\tcorresponds to :math:`H_{expt} = \\\\langle V|H(t=0)|V\\\\rangle`. \n\t\t\t \n\t\t\"\"\"\n\t\tfrom .exp_op_core import isexp_op\n\n\t\tif self.Ns <= 0:\n\t\t\treturn _np.asarray([])\n\n\t\tif hamiltonian_core.ishamiltonian(V):\n\t\t\traise TypeError(\"Can't take expectation value of hamiltonian\")\n\n\t\tif isexp_op(V):\n\t\t\traise TypeError(\"Can't take expectation value of exp_op\")\n\n\t\t\n\t\tV_dot = self.dot(V,check=check,pars=pars)\n\t\treturn self._expt_value_core(V,V_dot,enforce_pure=enforce_pure)\n\n\tdef _expt_value_core(self,V_left,V_right,enforce_pure=False):\n\t\tif _sp.issparse(V_right):\n\t\t\tif V_left.shape[0] != V_left.shape[1] or enforce_pure: # pure states\n\t\t\t\treturn _np.asscalar((V_left.H.dot(V_right)).toarray())\n\t\t\telse: # density matrix\n\t\t\t\treturn V_right.diagonal().sum()\n\t\telse:\n\t\t\tV_right = _np.asarray(V_right).squeeze()\n\t\t\tif V_right.ndim == 1: # pure state\n\t\t\t\treturn _np.vdot(V_left,V_right)\n\t\t\telif V_left.shape[0] != V_left.shape[1] or enforce_pure: # multiple pure states\n\t\t\t\treturn _np.einsum(\"ij,ij->j\",V_left.conj(),V_right)\n\t\t\telse: # density matrix\n\t\t\t\treturn V_right.trace()\n\n\tdef matrix_ele(self,Vl,Vr,pars={},diagonal=False,check=True):\n\t\t\"\"\"Calculates matrix element of `quantum_operator` quantum_operator for parameters `pars` in states `Vl` and `Vr`.\n\n\t\t.. math::\n\t\t\t\\\\langle V_l|H(\\\\lambda)|V_r\\\\rangle\n\n\t\tNotes\n\t\t-----\n\t\tTaking the conjugate or transpose of the state `Vl` is done automatically.  \n\n\t\tParameters\n\t\t-----------\n\t\tVl : numpy.ndarray\n\t\t\tVector(s)/state(s) to multiple with on left side.\n\t\tVl : numpy.ndarray\n\t\t\tVector(s)/state(s) to multiple with on right side.\n\t\tpars : dict, optional\n\t\t\tDictionary with same `keys` as `input_dict` and coupling strengths as `values`. Any missing `keys`\n\t\t\tare assumed to be set to unity.\n\t\tdiagonal : bool, optional\n\t\t\tWhen set to `True`, returs only diagonal part of expectation value. Default is `diagonal = False`.\n\t\tcheck : bool,\n\n\t\tReturns\n\t\t--------\n\t\tfloat\n\t\t\tMatrix element of `quantum_operator` quantum_operator between the states `Vl` and `Vr`.\n\n\t\tExamples\n\t\t---------\n\t\t>>> H_lr = H.expt_value(Vl,Vr,pars=pars,diagonal=False,check=True)\n\n\t\tcorresponds to :math:`H_{lr} = \\\\langle V_l|H(\\\\lambda=0)|V_r\\\\rangle`. \n\n\t\t\"\"\"\n\t\tVr = self.dot(Vr,pars=pars,check=check)\n\n\t\tif check:\n\t\t\ttry:\n\t\t\t\tshape = Vl.shape\n\t\t\texcept AttributeError:\n\t\t\t\tVl =_np.asanyarray(Vl)\n\t\t\t\tshape = Vl.shape\n\n\t\t\tif shape[0] != self._shape[1]:\n\t\t\t\traise ValueError(\"matrix dimension mismatch with shapes: {0} and {1}.\".format(V.shape,self._shape))\n\n\t\t\tif Vl.ndim > 2:\n\t\t\t\traise ValueError(\"Expecting  0< V.ndim < 3.\")\n\n\t\tif _sp.issparse(Vl):\n\t\t\tif diagonal:\n\t\t\t\treturn Vl.H.dot(Vr).diagonal()\n\t\t\telse:\n\t\t\t\treturn Vl.H.dot(Vr)\n\t\telse:\n\t\t\tif diagonal:\n\t\t\t\treturn _np.einsum(\"ij,ij->j\",Vl.conj(),Vr)\n\t\t\telse:\n\t\t\t\treturn Vl.T.conj().dot(Vr)\n\n\t### Diagonalisation routines\n\n\tdef eigsh(self,pars={},**eigsh_args):\n\t\t\"\"\"Computes SOME eigenvalues and eigenvectors of hermitian `quantum_operator` quantum_operator using SPARSE hermitian methods.\n\n\t\tThis function method solves for eigenvalues and eigenvectors, but can only solve for a few of them accurately.\n\t\tIt calls `scipy.sparse.linalg.eigsh <https://docs.scipy.org/doc/scipy/reference/generated/generated/scipy.sparse.linalg.eigsh.html>`_, which is a wrapper for ARPACK.\n\n\t\tNotes\n\t\t-----\n\t\tAssumes the quantum_operator is hermitian! If the flat `check_hermiticity = False` is used, we advise the user\n\t\tto reassure themselves of the hermiticity properties before use. \n\n\t\tParameters\n\t\t-----------\n\t\tpars : dict, optional\n\t\t\tDictionary with same `keys` as `input_dict` and coupling strengths as `values`. Any missing `keys`\n\t\t\tare assumed to be set to unity.\n\t\teigsh_args : \n\t\t\tFor all additional arguments see documentation of `scipy.sparse.linalg.eigsh <https://docs.scipy.org/doc/scipy/reference/generated/generated/scipy.sparse.linalg.eigsh.html>`_.\n\t\t\t\n\t\tReturns\n\t\t--------\n\t\ttuple\n\t\t\tTuple containing the `(eigenvalues, eigenvectors)` of the `quantum_operator` quantum_operator.\n\n\t\tExamples\n\t\t---------\n\t\t>>> eigenvalues,eigenvectors = H.eigsh(pars=pars,**eigsh_args)\n\n\t\t\"\"\"\n\t\tif self.Ns == 0:\n\t\t\treturn _np.array([]),_np.array([[]])\n\n\t\treturn _sla.eigsh(self.tocsr(pars),**eigsh_args)\n\n\tdef eigh(self,pars={},**eigh_args):\n\t\t\"\"\"Computes COMPLETE eigensystem of hermitian `quantum_operator` quantum_operator using DENSE hermitian methods.\n\n\t\tThis function method solves for all eigenvalues and eigenvectors. It calls \n\t\t`numpy.linalg.eigh <https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.linalg.eigh.html>`_, \n\t\tand uses wrapped LAPACK functions which are contained in the module py_lapack.\n\n\t\tNotes\n\t\t-----\n\t\tAssumes the quantum_operator is hermitian! If the flat `check_hermiticity = False` is used, we advise the user\n\t\tto reassure themselves of the hermiticity properties before use. \n\n\t\tParameters\n\t\t-----------\n\t\tpars : dict, optional\n\t\t\tDictionary with same `keys` as `input_dict` and coupling strengths as `values`. Any missing `keys`\n\t\t\tare assumed to be set to unity.\n\t\teigh_args : \n\t\t\tFor all additional arguments see documentation of `numpy.linalg.eigh <https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.linalg.eigh.html>`_.\n\t\t\t\n\t\tReturns\n\t\t--------\n\t\ttuple\n\t\t\tTuple containing the `(eigenvalues, eigenvectors)` of the `quantum_operator` quantum_operator.\n\n\t\tExamples\n\t\t---------\n\t\t>>> eigenvalues,eigenvectors = H.eigh(pars=pars,**eigh_args)\n\n\t\t\"\"\"\n\t\teigh_args[\"overwrite_a\"] = True\n\t\t\n\t\tif self.Ns <= 0:\n\t\t\treturn _np.asarray([]),_np.asarray([[]])\n\n\t\t# fill dense array with hamiltonian\n\t\tH_dense = self.todense(pars=pars)\t\t\n\t\t# calculate eigh\n\t\tE,H_dense = _la.eigh(H_dense,**eigh_args)\n\t\treturn E,H_dense\n\n\tdef eigvalsh(self,pars={},**eigvalsh_args):\n\t\t\"\"\"Computes ALL eigenvalues of hermitian `quantum_operator` quantum_operator using DENSE hermitian methods.\n\n\t\tThis function method solves for all eigenvalues. It calls \n\t\t`numpy.linalg.eigvalsh <https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.linalg.eigvalsh.html#numpy.linalg.eigvalsh>`_, \n\t\tand uses wrapped LAPACK functions which are contained in the module py_lapack.\n\n\t\tNotes\n\t\t-----\n\t\tAssumes the quantum_operator is hermitian! If the flat `check_hermiticity = False` is used, we advise the user\n\t\tto reassure themselves of the hermiticity properties before use. \n\n\t\tParameters\n\t\t-----------\n\t\tpars : dict, optional\n\t\t\tDictionary with same `keys` as `input_dict` and coupling strengths as `values`. Any missing `keys`\n\t\t\tare assumed to be set to unity.\n\t\teigvalsh_args : \n\t\t\tFor all additional arguments see documentation of `numpy.linalg.eigvalsh <https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.linalg.eigvalsh.html#numpy.linalg.eigvalsh>`_.\n\t\t\t\n\t\tReturns\n\t\t--------\n\t\tnumpy.ndarray\n\t\t\tEigenvalues of the `quantum_operator` quantum_operator.\n\n\t\tExamples\n\t\t---------\n\t\t>>> eigenvalues = H.eigvalsh(pars=pars,**eigvalsh_args)\n\n\t\t\"\"\"\n\n\t\tif self.Ns <= 0:\n\t\t\treturn _np.asarray([])\n\n\t\tH_dense = self.todense(pars=pars)\n\t\tE = _np.linalg.eigvalsh(H_dense,**eigvalsh_args)\n\t\t#eigvalsh_args[\"overwrite_a\"] = True\n\t\t#E = _la.eigvalsh(H_dense,**eigvalsh_args)\n\t\treturn E\n\n\n\t### routines to change object type\t\n\n\tdef tocsr(self,pars={}):\n\t\t\"\"\"Returns copy of a `quantum_operator` object for parameters `pars` as a `scipy.sparse.csr_matrix`.\n\n\t\tCasts the `quantum_operator` object as a\n\t\t`scipy.sparse.csr_matrix <https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html>`_\n\t\tobject.\n\n\t\tParameters\n\t\t-----------\n\t\tpars : dict, optional\n\t\t\tDictionary with same `keys` as `input_dict` and coupling strengths as `values`. Any missing `keys`\n\t\t\tare assumed to be set to unity. \n\n\t\tReturns\n\t\t--------\n\t\t:obj:`scipy.sparse.csr_matrix`\n\n\t\tExamples\n\t\t---------\n\t\t>>> H_csr=H.tocsr(pars=pars)\n\n\t\t\"\"\"\n\t\tpars = self._check_scalar_pars(pars)\n\n\t\tH = _sp.csr_matrix(self.get_shape,dtype=self._dtype)\n\n\t\tfor key,J in pars.items():\n\t\t\ttry:\n\t\t\t\tH += J*_sp.csr_matrix(self._quantum_operator[key])\n\t\t\texcept:\n\t\t\t\tH = H + J*_sp.csr_matrix(self._quantum_operator[key])\n\n\t\treturn H\n\n\tdef tocsc(self,pars={}):\n\t\t\"\"\"Returns copy of a `quantum_operator` object for parameters `pars` as a `scipy.sparse.csc_matrix`.\n\n\t\tCasts the `quantum_operator` object as a\n\t\t`scipy.sparse.csc_matrix <https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csc_matrix.html>`_\n\t\tobject.\n\n\t\tParameters\n\t\t-----------\n\t\tpars : dict, optional\n\t\t\tDictionary with same `keys` as `input_dict` and coupling strengths as `values`. Any missing `keys`\n\t\t\tare assumed to be set to unity.\n\n\t\tReturns\n\t\t--------\n\t\t:obj:`scipy.sparse.csc_matrix`\n\n\t\tExamples\n\t\t---------\n\t\t>>> H_csc=H.tocsc(pars=pars)\n\n\t\t\"\"\"\n\t\tpars = self._check_scalar_pars(pars)\n\n\t\tH = _sp.csc_matrix(self.get_shape,dtype=self._dtype)\n\n\t\tfor key,J in pars.items():\n\t\t\ttry:\n\t\t\t\tH += J*_sp.csc_matrix(self._quantum_operator[key])\n\t\t\texcept:\n\t\t\t\tH = H + J*_sp.csc_matrix(self._quantum_operator[key])\n\n\t\treturn H\n\n\tdef todense(self,pars={},out=None):\n\t\t\"\"\"Returns copy of a `quantum_operator` object for parameters `pars` as a dense array.\n\n\t\tThis function can overflow memory if not used carefully!\n\n\t\tNotes\n\t\t-----\n\t\tIf the array dimension is too large, scipy may choose to cast the `quantum_operator` quantum_operator as a\n\t\t`numpy.matrix` instead of a `numpy.ndarray`. In such a case, one can use the `quantum_operator.toarray()`\n\t\tmethod.\n\n\t\tParameters\n\t\t-----------\n\t\tpars : dict, optional\n\t\t\tDictionary with same `keys` as `input_dict` and coupling strengths as `values`. Any missing `keys`\n\t\t\tare assumed to be set to unity.\n\t\tout : numpy.ndarray\n\t\t\tArray to fill in with the output.\n\t\t\n\t\tReturns\n\t\t--------\n\t\tobj\n\t\t\tDepending of size of array, can be either one of\n\n\t\t\t* `numpy.ndarray`.\n\t\t\t* `numpy.matrix`.\n\n\t\tExamples\n\t\t---------\n\t\t>>> H_dense=H.todense(pars=pars)\n\n\t\t\"\"\"\n\t\tpars = self._check_scalar_pars(pars)\n\n\t\tif out is None:\n\t\t\tout = _np.zeros(self._shape,dtype=self.dtype)\n\t\t\tout = _np.asmatrix(out)\n\n\t\tfor key,J in pars.items():\n\t\t\tout += J * self._quantum_operator[key]\n\t\t\n\t\treturn out\n\n\tdef toarray(self,pars={},out=None):\n\t\t\"\"\"Returns copy of a `quantum_operator` object for parameters `pars` as a dense array.\n\n\t\tThis function can overflow memory if not used carefully!\n\n\n\t\tParameters\n\t\t-----------\n\t\tpars : dict, optional\n\t\t\tDictionary with same `keys` as `input_dict` and coupling strengths as `values`. Any missing `keys`\n\t\t\tare assumed to be set to unity.\n\t\tout : numpy.ndarray\n\t\t\tArray to fill in with the output.\n\t\t\n\t\tReturns\n\t\t--------\n\t\tnumpy.ndarray\n\t\t\tDense array.\n\n\t\tExamples\n\t\t---------\n\t\t>>> H_dense=H.toarray(pars=pars)\n\n\t\t\"\"\"\n\n\t\tpars = self._check_scalar_pars(pars)\n\n\t\tif out is None:\n\t\t\tout = _np.zeros(self._shape,dtype=self.dtype)\n\n\t\tfor key,J in pars.items():\n\t\t\tout += J * self._quantum_operator[key]\n\t\t\n\t\treturn out\n\n\tdef aslinearoperator(self,pars={}):\n\t\t\"\"\"Returns copy of a `quantum_operator` object for parameters `pars` as a `scipy.sparse.linalg.Linearquantum_operator`.\n\n\t\tCasts the `quantum_operator` object as a\n\t\t`scipy.sparse.linalg.Linearquantum_operator <https://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.sparse.linalg.Linearquantum_operator.html>`_\n\t\tobject.\n\n\t\tParameters\n\t\t-----------\n\t\tpars : dict, optional\n\t\t\tDictionary with same `keys` as `input_dict` and coupling strengths as `values`. Any missing `keys`\n\t\t\tare assumed to be set to unity.\n\n\t\tReturns\n\t\t--------\n\t\t:obj:`scipy.sparse.linalg.Linearquantum_operator`\n\n\t\tExamples\n\t\t---------\n\t\t>>> H_aslinop=H.aslinearquantum_operator(pars=pars)\n\n\t\t\"\"\"\n\t\tpars = self._check_scalar_pars(pars)\n\t\tmatvec = functools.partial(_quantum_operator_dot,self,pars)\n\t\trmatvec = functools.partial(_quantum_operator_dot,self.H,pars)\n\t\treturn _sla.LinearOperator(self.get_shape,matvec,rmatvec=rmatvec,matmat=matvec,dtype=self._dtype)\t\t\n\n\tdef tohamiltonian(self,pars={}):\n\t\t\"\"\"Returns copy of a `quantum_operator` object for parameters `pars` as a `hamiltonian` object.\n\n\t\tParameters\n\t\t-----------\n\t\tpars : dict, optional\n\t\t\tDictionary with same `keys` as `input_dict` and coupling strengths as `values`. Any missing `keys`\n\t\t\tare assumed to be set to unity.\n\n\t\tReturns\n\t\t--------\n\t\t:obj:`hamiltonian`\n\n\t\tExamples\n\t\t---------\n\t\t>>> H_aslinop=H.tohamiltonian(pars=pars)\n\n\t\t\"\"\"\n\t\tpars = self._check_hamiltonian_pars(pars)\n\n\t\tstatic=[]\n\t\tdynamic=[]\n\n\t\tfor key,J in pars.items():\n\t\t\tif type(J) is tuple and len(J) == 2:\n\t\t\t\tdynamic.append([self._quantum_operator[key],J[0],J[1]])\n\t\t\telse:\n\t\t\t\tif J == 1.0:\n\t\t\t\t\tstatic.append(self._quantum_operator[key])\n\t\t\t\telse:\n\t\t\t\t\tstatic.append(J*self._quantum_operator[key])\n\n\t\treturn hamiltonian_core.hamiltonian(static,dynamic,dtype=self._dtype)\n\n\tdef update_matrix_formats(self,matrix_formats):\n\t\t\"\"\"Change the internal structure of the matrices in-place.\n\n\t\tParameters\n\t\t-----------\n\t\tmatrix_formats: dict, optional\n\t\t\tDictionary of key,value pairs which, given a key associated with an operator in `input_dict`, the value of this key\n\t\t\tspecifies the sparse matrix format {\"csr\",\"csc\",\"dia\",\"dense\"}.\n\n\t\tExamples\n\t\t---------\n\t\tGiven `O` which has two operators defined by strings: 'Hx' for transverse field, and 'Hising' is the Ising part. The Ising part must be diagonal\n\t\ttherefore it is useful to cast it to a DIA matrix format, while the transverse field is not diagonal so it is most efficient to use CSR matrix format.\n\t\tThis can be accomplished by the following:\n\n\t\t>>> O.update_matrix_formats(dict(Hx=\"csr\",Hising=\"dia\"))\n\n\t\t\"\"\"\n\t\tif type(matrix_formats) is not dict:\n\t\t\traise ValueError(\"matrix_formats must be a dictionary with the formats of the matrices being values and keys being the operator keys.\")\n\n\t\textra = set(matrix_formats.keys()) - set(self._quantum_operator.keys())\n\t\tif extra:\n\t\t\traise ValueError(\"unexpected couplings: {}\".format(extra))\n\n\t\tfor key in self._quantum_operator.keys():\n\t\t\tif key in matrix_formats:\n\t\t\t\tfmt = matrix_formats[key]\n\t\t\t\tif fmt not in [\"dia\",\"csr\",\"csc\",\"dense\"]:\n\t\t\t\t\traise TypeError(\"sparse formats must be either 'csr','csc', 'dia' or 'dense'.\")\n\n\t\t\t\tif fmt == \"dense\":\n\t\t\t\t\tO = self._quantum_operator[key]\n\t\t\t\t\ttry:\n\t\t\t\t\t\tself._quantum_operator[key] = O.toarray()\n\t\t\t\t\texcept AttributeError:\n\t\t\t\t\t\tself._quantum_operator[key] = _np.ascontiguousarray(O)\n\t\t\t\telse:\n\t\t\t\t\tsparse_constuctor = getattr(_sp,fmt+\"_matrix\")\n\t\t\t\t\tO = self._quantum_operator[key]\n\t\t\t\t\tif _sp.issparse(O):\n\t\t\t\t\t\tself._quantum_operator[key] = sparse_constuctor(O)\t\n\n\t\tself._update_matvecs()\t\n\n\t### algebra operations\n\n\tdef transpose(self,copy=False):\n\t\t\"\"\"Transposes `quantum_operator` quantum_operator.\n\n\t\tNotes\n\t\t-----\n\t\tThis function does NOT conjugate the quantum_operator.\n\n\t\tReturns\n\t\t--------\n\t\t:obj:`quantum_operator`\n\t\t\t:math:`H_{ij}\\\\mapsto H_{ji}`\n\n\t\tExamples\n\t\t---------\n\n\t\t>>> H_tran = H.transpose()\n\n\t\t\"\"\"\n\t\t\n\t\tnew_dict = {key:[op.transpose()] for key,op in iteritems(self._quantum_operator)}\n\t\treturn quantum_operator(new_dict,basis=self._basis,dtype=self._dtype,shape=self._shape,copy=copy)\n\n\tdef conjugate(self):\n\t\t\"\"\"Conjugates `quantum_operator` quantum_operator.\n\n\t\tNotes\n\t\t-----\n\t\tThis function does NOT transpose the quantum_operator.\n\n\t\tReturns\n\t\t--------\n\t\t:obj:`quantum_operator`\n\t\t\t:math:`H_{ij}\\\\mapsto H_{ij}^*`\n\n\t\tExamples\n\t\t---------\n\n\t\t>>> H_conj = H.conj()\n\n\t\t\"\"\"\n\t\tnew_dict = {key:[op.conjugate()] for key,op in iteritems(self._quantum_operator)}\n\t\treturn quantum_operator(new_dict,basis=self._basis,dtype=self._dtype,shape=self._shape,copy=False)\n\n\tdef conj(self):\n\t\t\"\"\"Conjugates `quantum_operator` quantum_operator.\n\n\t\tNotes\n\t\t-----\n\t\tThis function does NOT transpose the quantum_operator.\n\n\t\tReturns\n\t\t--------\n\t\t:obj:`quantum_operator`\n\t\t\t:math:`H_{ij}\\\\mapsto H_{ij}^*`\n\n\t\tExamples\n\t\t---------\n\n\t\t>>> H_conj = H.conj()\n\n\t\t\"\"\"\n\t\treturn self.conjugate()\n\n\tdef getH(self,copy=False):\n\t\t\"\"\"Calculates hermitian conjugate of `quantum_operator` quantum_operator.\n\n\t\tParameters\n\t\t-----------\n\t\tcopy : bool, optional\n\t\t\tWhether to return a deep copy of the original object. Default is `copy = False`.\n\n\t\tReturns\n\t\t--------\n\t\t:obj:`quantum_operator`\n\t\t\t:math:`H_{ij}\\\\mapsto H_{ij}^*`\n\n\t\tExamples\n\t\t---------\n\n\t\t>>> H_herm = H.getH()\n\n\t\t\"\"\"\n\t\treturn self.conjugate().transpose(copy=copy)\n\n\tdef copy(self):\n\t\t\"\"\"Returns a deep copy of `quantum_operator` object.\"\"\"\n\t\tnew_dict = {key:[op] for key,op in iteritems(self._quantum_operator)}\n\t\treturn quantum_operator(new_dict,basis=self._basis,dtype=self._dtype,shape=self._shape,copy=True)\n\n\tdef astype(self,dtype,copy=False,casting=\"unsafe\"):\n\t\t\"\"\" Changes data type of `quantum_operator` object.\n\n\t\tParameters\n\t\t-----------\n\t\tdtype : 'type'\n\t\t\tThe data type (e.g. numpy.float64) to cast the Hamiltonian with.\n\n\t\tReturns\n\t\t`quantum_operator`\n\t\t\tquantum_operator with altered data type.\n\n\t\tExamples\n\t\t---------\n\t\t>>> H_cpx=H.astype(np.complex128)\n\n\t\t\"\"\"\n\t\tif dtype not in hamiltonian_core.supported_dtypes:\n\t\t\traise ValueError(\"quantum_operator can only be cast to floating point types\")\n\n\t\tnew_dict = {key:[op.astype(dtype,copy=copy,casting=casting)] for key,op in iteritems(self._quantum_operator)}\n\n\t\treturn quantum_operator(new_dict,basis=self._basis,dtype=dtype,shape=self._shape,copy=copy)\n\n\n\t### lin-alg operations\n\n\tdef diagonal(self,pars={}):\n\t\t\"\"\" Returns diagonal of `quantum_operator` quantum_operator for parameters `pars`.\n\n\t\tParameters\n\t\t-----------\n\t\tpars : dict, optional\n\t\t\tDictionary with same `keys` as `input_dict` and coupling strengths as `values`. Any missing `keys`\n\t\t\tare assumed to be set to unity.\n\n\t\tReturns\n\t\t--------\n\t\tnumpy.ndarray\n\t\t\tarray containing the diagonal part of the operator :math:`diag_j = H_{jj}(\\\\lambda)`.\n\n\t\tExamples\n\t\t---------\n\n\t\t>>> H_diagonal = H.diagonal(pars=pars)\n\n\t\t\"\"\"\n\t\tpars = self._check_scalar_pars(pars)\n\t\tdiag = _np.zeros(self.Ns,dtype=self._dtype)\n\t\tfor key,value in iteritems(self._quantum_operator):\n\t\t\tdiag += pars[key] * value.diagonal()\n\t\treturn diag\n\n\tdef trace(self,pars={}):\n\t\t\"\"\" Calculates trace of `quantum_operator` quantum_operator for parameters `pars`.\n\n\t\tParameters\n\t\t-----------\n\t\tpars : dict, optional\n\t\t\tDictionary with same `keys` as `input_dict` and coupling strengths as `values`. Any missing `keys`\n\t\t\tare assumed to be set to unity.\n\n\t\tReturns\n\t\t--------\n\t\tfloat\n\t\t\tTrace of quantum_operator :math:`\\\\sum_{j=1}^{Ns} H_{jj}(\\\\lambda)`.\n\n\t\tExamples\n\t\t---------\n\n\t\t>>> H_tr = H.trace(pars=pars)\n\n\t\t\"\"\"\n\t\tpars = self._check_scalar_pars(pars)\n\t\ttr = 0.0\n\t\tfor key,value in iteritems(self._quantum_operator):\n\t\t\ttry:\n\t\t\t\ttr += pars[key] * value.trace()\n\t\t\texcept AttributeError:\n\t\t\t\ttr += pars[key] * value.diagonal().sum()\n\t\treturn tr\n\n\tdef __str__(self):\n\t\ts = \"\"\n\t\tfor key,op in iteritems(self._quantum_operator):\n\t\t\ts = s + (\"{}:\\n{}\\n\".format(key,op))\n\n\t\treturn s\n\n\tdef __repr__(self):\n\t\treturn \"<{} x {} quspin.operator.quantum_operator with {} operator(s)>\".format(self.shape[0],self.shape[1],len(self._quantum_operator))\n\n\tdef __call__(self,**pars):\n\t\tpars = self._check_scalar_pars(pars)\n\t\tif self.is_dense:\n\t\t\treturn self.todense(pars)\n\t\telse:\n\t\t\treturn self.tocsr(pars)\n\n\tdef __neg__(self):\n\t\treturn self.__imul__(-1)\n\n\tdef __iadd__(self,other):\n\t\tself._is_dense = self._is_dense or other._is_dense\n\t\tif isinstance(other,quantum_operator):\n\t\t\tfor key,value in iteritems(other._quantum_operator):\n\t\t\t\tif key in self._quantum_operator:\n\t\t\t\t\tself._quantum_operator[key] = self._quantum_operator[key] + value\n\t\t\t\telse:\n\t\t\t\t\tself._quantum_operator[key] = value\n\n\t\t\t\tif _check_almost_zero(self._quantum_operator[key]):\n\t\t\t\t\tself._quantum_operator.pop(key)\n\n\t\t\tself._update_matvecs()\n\t\t\treturn self\n\t\telif other == 0:\n\t\t\treturn self\n\t\telse:\n\t\t\treturn NotImplemented\n\n\tdef __add__(self,other):\n\t\tresult_dtype = _np.result_type(self._dtype, other.dtype)\n\t\tnew = self.astype(result_dtype,copy=True)\n\t\tnew += other\n\t\treturn new\n\n\tdef __isub__(self,other):\n\t\tself._is_dense = self._is_dense or other._is_dense\n\t\tif isinstance(other,quantum_operator):\n\t\t\tfor key,value in iteritems(other._quantum_operator):\n\t\t\t\tif key in self._quantum_operator:\n\t\t\t\t\tself._quantum_operator[key] = self._quantum_operator[key] - value\n\t\t\t\telse:\n\t\t\t\t\tself._quantum_operator[key] = -value\n\n\t\t\t\tif _check_almost_zero(self._quantum_operator[key]):\n\t\t\t\t\tself._quantum_operator.pop(key)\n\n\t\t\tself._update_matvecs()\n\t\t\treturn self\n\t\telif other == 0:\n\t\t\treturn self\n\t\telse:\n\t\t\treturn NotImplemented\n\n\tdef __sub__(self,other):\n\t\tresult_dtype = _np.result_type(self._dtype, other.dtype)\n\t\tnew = self.astype(result_dtype,copy=True)\n\t\tnew -= other\n\t\treturn new\t\t\n\n\tdef __imul__(self,other):\n\t\tif isinstance(other,quantum_operator):\n\t\t\treturn NotImplemented\n\t\telif not _np.isscalar(other):\n\t\t\treturn NotImplemented\n\t\telse:\n\t\t\tfor op in itervalues(self._quantum_operator):\n\t\t\t\top *= other\n\n\t\t\tself._update_matvecs()\n\t\t\treturn self\n\n\tdef __mul__(self,other):\n\t\tresult_dtype = _np.result_type(self._dtype, other.dtype)\n\t\tnew = self.astype(result_dtype,copy=True)\n\t\tnew *= other\n\t\treturn new\n\n\tdef __idiv__(self,other):\n\t\tif isinstance(other,quantum_operator):\n\t\t\treturn NotImplemented\n\t\telif not _np.isscalar(other):\n\t\t\treturn NotImplemented\n\t\telse:\n\t\t\tfor op in itervalues(self._quantum_operator):\n\t\t\t\top /= other\n\t\t\tself._update_matvecs()\n\t\t\treturn self\n\n\tdef __div__(self,other):\n\t\tresult_dtype = _np.result_type(self._dtype, other.dtype)\n\t\tnew = self.astype(result_dtype,copy=True)\n\t\tnew /= other\n\t\treturn new\n\n\n\n\n\tdef _check_hamiltonian_pars(self,pars):\n\n\t\tif not isinstance(pars,dict):\n\t\t\traise ValueError(\"expecing dictionary for parameters.\")\n\n\t\textra = set(pars.keys()) - set(self._quantum_operator.keys())\n\t\tif extra:\n\t\t\traise ValueError(\"unexpected couplings: {}\".format(extra))\n\n\t\tmissing = set(self._quantum_operator.keys()) - set(pars.keys())\n\t\tfor key in missing:\n\t\t\tpars[key] = _np.array(1,dtype=_np.int32)\n\n\n\t\tfor key,J in pars.items():\n\t\t\tif type(J) is tuple:\n\t\t\t\tif len(J) != 2:\n\t\t\t\t\traise ValueError(\"expecting parameters to be either scalar or tuple of function and arguements of function.\")\n\t\t\telse:\n\t\t\t\tJ = _np.array(J)\t\t\t\t\n\t\t\t\tif J.ndim > 0:\n\t\t\t\t\traise ValueError(\"expecting parameters to be either scalar or tuple of function and arguements of function.\")\n\n\t\treturn pars\n\n\tdef _check_scalar_pars(self,pars):\n\n\t\tif not isinstance(pars,dict):\n\t\t\traise ValueError(\"expecing dictionary for parameters.\")\n\n\t\textra = set(pars.keys()) - set(self._quantum_operator.keys())\n\t\tif extra:\n\t\t\traise ValueError(\"unexpected couplings: {}\".format(extra))\n\n\t\tmissing =  set(self._quantum_operator.keys()) - set(pars.keys())\n\t\tfor key in missing:\n\t\t\tpars[key] = 1.0\n\n\t\treturn pars\n\n\t# checks\n\tdef _mat_checks(self,other,casting=\"same_kind\"):\n\t\ttry:\n\t\t\tif other.shape != self._shape: # only accepts square matricies \n\t\t\t\traise ValueError('shapes do not match')\n\t\t\tif not _np.can_cast(other.dtype,self._dtype,casting=casting):\n\t\t\t\traise ValueError('cannot cast types')\n\t\texcept AttributeError:\n\t\t\tif other._shape != self._shape: # only accepts square matricies \n\t\t\t\traise ValueError('shapes do not match')\n\t\t\tif not _np.can_cast(other.dtype,self._dtype,casting=casting):\n\t\t\t\traise ValueError('cannot cast types')\t\n\n\tdef _update_matvecs(self):\n\t\tself._matvec_functions = {}\n\n\t\tfor key in self._quantum_operator.keys():\n\t\t\tself._matvec_functions[key] = _get_matvec_function(self._quantum_operator[key])\n\ndef isquantum_operator(obj):\n\t\"\"\"Checks if instance is object of `quantum_operator` class.\n\n\tParameters\n\t-----------\n\tobj : \n\t\tArbitraty python object.\n\n\tReturns\n\t--------\n\tbool\n\t\tCan be either of the following:\n\n\t\t* `True`: `obj` is an instance of `quantum_operator` class.\n\t\t* `False`: `obj` is NOT an instance of `quantum_operator` class.\n\n\t\"\"\"\n\treturn isinstance(obj,quantum_operator)\n\n\t\n", "meta": {"hexsha": "4d0c0f0f43e2e74f3d3a26e05cd582f2118a3dbe", "size": 42747, "ext": "py", "lang": "Python", "max_stars_repo_path": "quspin/operators/quantum_operator_core.py", "max_stars_repo_name": "nelsond/QuSpin", "max_stars_repo_head_hexsha": "769d3817870f6ff55c4283af46f94e11c36f4121", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-14T08:13:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-14T08:13:00.000Z", "max_issues_repo_path": "quspin/operators/quantum_operator_core.py", "max_issues_repo_name": "cileeky/QuSpin", "max_issues_repo_head_hexsha": "769d3817870f6ff55c4283af46f94e11c36f4121", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quspin/operators/quantum_operator_core.py", "max_forks_repo_name": "cileeky/QuSpin", "max_forks_repo_head_hexsha": "769d3817870f6ff55c4283af46f94e11c36f4121", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1788395904, "max_line_length": 189, "alphanum_fraction": 0.6915573023, "include": true, "reason": "import numpy,import scipy", "num_tokens": 11783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.17073193224172742}}
{"text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"Tools for reading/writing of files and performing operations.\"\"\"\n\nimport csv\nimport functools\nimport multiprocessing\nimport glob\nimport os\nimport sys\n\nimport numpy as np\n\nfrom pyrvt.peak_calculators import get_peak_calculator, get_region\nfrom pyrvt import motions\n\n# Try to load the modules required for reading/writing files\ntry:\n    import xlrd\nexcept ImportError:\n    xlrd = None\n\ntry:\n    import xlwt\nexcept ImportError:\n    xlwt = None\n\ntry:\n    import openpyxl\nexcept ImportError:\n    openpyxl = None\n\nPARAMETER_NAMES = [\n    ('magnitude', 'Magnitude'),\n    ('distance', 'Distance (km)'),\n    ('vs30', 'Vs30 (m/s)'),\n    ('kappa', 'Site Atten., Kappa0 (sec)'),  # Site Atten., κ₀\n    ('duration', 'Duration (sec)'),\n    ('region', 'Region'),\n]\n\n\ndef read_events(fname, response_type):\n    \"\"\"Read data from the file an Excel work book.\n\n    Parameters\n    ----------\n    fname : str\n        Filename of the input file.\n    response_type : str\n        Type of response. Valid options are: 'psa' for psuedo-spectral\n        acceleration, or 'fa' for Fourier amplitude.\n\n    Returns\n    -------\n    ext : str\n        Extension of input file\n    reference : :class:`numpy.ndarray`\n        Reference of the response. This is either period (sec) for\n        response_type 'psa' or frequency (Hz) for response_type 'fa'\n    events : List[dict]\n        List of events read from the file. See ``Note`` in\n        :func:`.calc_compatible_spectra` for more information on structure of\n        the dictionaries.\n\n    \"\"\"\n    assert response_type in ['psa', 'fa']\n\n    ext = os.path.splitext(fname)[1].lower()\n    # Load the file depending on the format\n    if ext == '.csv':\n\n        def parse(s):\n            try:\n                return float(s)\n            except ValueError:\n                return s\n\n        with open(fname) as fp:\n            reader = csv.reader(fp)\n            rows = [[parse(r) for r in row] for row in reader]\n    elif ext == '.xls':\n        if xlrd is None:\n            raise RuntimeError('xlrd is required to open an xls file')\n        wb = xlrd.open_workbook(fname)\n        ws = wb.sheet_by_index(0)\n        rows = [ws.row_values(i) for i in range(ws.nrows)]\n    elif ext == '.xlsx':\n        if openpyxl is None:\n            raise RuntimeError('openpyxl is required to open an xlsx file')\n        wb = openpyxl.load_workbook(fname, read_only=True)\n        ws = wb.worksheets[0]\n        rows = [[r.value for r in row] for row in ws.rows]\n        # Close the file so that it may be deleted if needed. This is only\n        # important so that in the test cases the temporary .xlsx file can be\n        # deleted.\n        wb._archive.close()\n    else:\n        raise NotImplementedError\n\n    parameters = {\n        key: rows[i][1:]\n        for i, (key, label) in enumerate(PARAMETER_NAMES)\n    }\n\n    event_row = len(parameters) + 1\n    event_count = len(rows[0]) - 1\n\n    reference = np.array([row[0] for row in rows[event_row:]])\n\n    events = []\n    for i in range(event_count):\n        resps = np.array([row[i + 1] for row in rows[event_row:]])\n        # Extract the appropriate attributes\n        e = {k: v[i] for k, v in parameters.items()}\n        e[response_type] = resps\n\n        if 'region' in e:\n            e['region'] = get_region(e['region'])\n\n        events.append(e)\n\n    return ext, reference, events\n\n\ndef write_events(fname, reference, reference_label, response_type,\n                 response_label, events):\n    \"\"\"Write the events to a file.\n\n    Parameters\n    ----------\n    fname : str\n        Save the events to this file. The directory is created if needed.\n    reference : array_like\n        Periods of the oscillator response shared across all events.\n    reference_label : str\n        Label of the reference (e.g., 'Frequency (Hz)').\n    response_type : str\n        Type of response. Valid options: `psa` for pseudo-spectral\n        accleration, or `fa` for Fourier amplitude.\n    response_label : str\n        Label of the response type (e.g., 'Fourier Ampl. (g/sec)')\n    events : List[dict]\n        Events to write to file. See ``Note`` in\n        :func:`.compute_compatible_spectra` for more information.\n\n    Raises\n    ------\n    NotImplementedError:\n        If extension is not supported\n\n    \"\"\"\n    # Create the rows of output\n    rows = []\n    # Output the parameters\n    for key, label in PARAMETER_NAMES:\n        rows.append([label] + [e[key] for e in events])\n\n    rows.append([reference_label] + len(events) * [response_label])\n\n    # Output the response spectra\n    for i in range(len(reference)):\n        rows.append([reference[i]] + [e[response_type][i] for e in events])\n\n    # Create the directory\n    dirname = os.path.dirname(fname)\n    if not os.path.exists(dirname):\n        os.makedirs(dirname)\n\n    # Write the file\n    ext = os.path.splitext(fname)[1].lower()\n\n    if ext == '.csv':\n        if sys.version_info < (3, 1):\n            fp = open(fname, 'wt')\n        else:\n            fp = open(fname, 'wt', newline='')\n        writer = csv.writer(fp)\n        writer.writerows(rows)\n        fp.close()\n    elif ext == '.xls':\n        if xlwt is None:\n            raise RuntimeError('xlwt is required to open an xls file')\n        wb = xlwt.Workbook()\n        ws = wb.add_sheet('Sheet 1')\n        for i, row in enumerate(rows):\n            for j, cell in enumerate(row):\n                ws.write(i, j, cell)\n        wb.save(fname)\n    elif ext == '.xlsx':\n        if openpyxl is None:\n            raise RuntimeError('openpyxl is required to open an xlsx file')\n        wb = openpyxl.Workbook()\n        ws = wb.worksheets[0]\n        for row in rows:\n            ws.append(row)\n        wb.save(fname)\n    else:\n        raise NotImplementedError\n\n\ndef _calc_fa(target_freqs, damping, method, event):\n    \"\"\"Calculate the fourier amplitudes for an event.\n\n    Note that this is intended as a helper function to be called by\n    multiprocessing.Pool.\n    \"\"\"\n    event_keys = ['magnitude', 'distance', 'region']\n    event_kwds = {key: event[key] for key in event_keys}\n    crm = motions.CompatibleRvtMotion(\n        target_freqs,\n        event['psa'],\n        duration=event['duration'],\n        osc_damping=damping,\n        event_kwds=event_kwds,\n        peak_calculator=get_peak_calculator(method, event_kwds))\n    psa_calc = crm.calc_osc_accels(target_freqs, damping)\n    return crm, psa_calc\n\n\ndef calc_compatible_spectra(method, periods, events, damping=0.05):\n    \"\"\"Compute the response spectrum compatible motions.\n\n    Parameters\n    ----------\n    method : str\n        RVT peak factor method, see\n        :func:`~.peak_calculators.get_peak_calculator`.\n    periods : array_like\n        Periods of the oscillator response shared across all events.\n    events : List[dict]\n        All events to consider. See ``Note``.\n    damping : float, optional\n        Fractional damping of the oscillator (decimal). Default value of 0.05\n        for a damping ratio of 5%.\n\n    Returns\n    -------\n    :class:`numpy.ndarray`\n        Frequency of the computed Fourier amplitude spectra.\n\n    Note\n    ----\n    Each event dictionary should have the following keys:\n\n    - **psa** : :class:`numpy.ndarray` -- pseudo-spectral accelerations. This\n      is the target for the :class:`~.motions.CompatibleRvtMotion`.\n    - **duration** : float, optional -- duration of the ground motion\n    - **magnitude** : float, optional -- earthquake magnitude\n    - **distance** : float, optional -- earthquake distance (km)\n    - **region** : str, optional -- earthquake source region, see\n      :func:`~.peak_calculators.get_region` If no duration is provided one\n      is estimated from the magnitude, distance, and region.\n\n    The `events` dictionary is modified by this function and adds the\n    following keys:\n\n    - **duration** : float -- duration of the ground motion if one was not\n      specified\n    - **fa** : :class:`numpy.ndarray` -- Fourier amplitude spectra in units of\n      g/sec\n    - **psa_calc** : :class:`numpy.ndarray` -- Pseudo-spectral acceleration\n      calculated from `fa`. This will differ slightly from `psa_target`.\n\n    \"\"\"\n    target_freqs = 1. / periods\n    with multiprocessing.Pool() as pool:\n        results = pool.map(\n            functools.partial(_calc_fa, target_freqs, damping, method), events)\n\n    # Copy values back into the dictionary\n    for event, (crm, psa_calc) in zip(events, results):\n        if not event['duration']:\n            event['duration'] = crm.duration\n        event['fa'] = crm.fourier_amps\n        event['psa_calc'] = psa_calc\n\n    # Return the frequency from one of the computed motions.\n    freqs = results[0][0].freqs\n    return freqs\n\n\ndef operation_psa2fa(src,\n                     dst,\n                     damping,\n                     method='LP99',\n                     fixed_spacing=True,\n                     verbose=True):\n    \"\"\"Compute the accel. response spectrum from a Fourier amplitude spectrum.\n\n    Parameters\n    ----------\n    src : str\n        Source for the pseudo-spectral accelerations (PSA). This can be a\n        filename or pattern used in :func:`glob.glob`.\n    dst : str\n        Destination directory for the output PSA. The directory is created if\n        it does not exist.\n    damping : float\n        Fractional damping of the oscillator ( decimal).\n    method : str\n        RVT peak factor method, see\n        :func:`~.peak_calculators.get_peak_calculator`.\n    fixed_spacing : bool, optional\n        If `True`, then the periods are interpolated to 301 points equally\n        space in log-space from 0.01 to 10.\n    verbose : bool, optional\n        Print status of calculation.\n\n    \"\"\"\n    for filename_src in glob.iglob(src):\n        if verbose:\n            print('Processing:', filename_src)\n        ext, periods, events = read_events(filename_src, 'psa')\n\n        if fixed_spacing:\n            # Interpolate the periods to a smaller range\n            _periods = np.logspace(-2, 1, 301)\n\n            for e in events:\n                e['psa'] = np.exp(\n                    np.interp(_periods, periods, np.log(e['psa'])))\n\n            periods = _periods\n\n        # Compute the FA from the PSA\n        freqs = calc_compatible_spectra(\n            method, periods, events, damping=damping)\n\n        if not os.path.exists(dst):\n            os.makedirs(dst)\n\n        basename = os.path.basename(filename_src)\n        pathname_dst = os.path.join(dst, basename.rsplit('_', 1)[0])\n\n        write_events(pathname_dst + '_sa' + ext, periods, 'Period (s)',\n                     'psa_calc', 'Sa (g)', events)\n        write_events(pathname_dst + '_fa' + ext, freqs, 'Frequency (Hz)', 'fa',\n                     'FA (g-s)', events)\n\n\ndef _calc_psa(osc_freqs, damping, method, freqs, event):\n    \"\"\"Calculate the response spectra for an event.\n\n    Note that this is intended as a helper function to be called by\n    multiprocessing.Pool.\n    \"\"\"\n    m = motions.RvtMotion(\n        freqs=freqs,\n        fourier_amps=event['fa'],\n        duration=event['duration'],\n        peak_calculator=get_peak_calculator(method,\n                                            dict(\n                                                region=event['region'],\n                                                mag=event['magnitude'],\n                                                dist=event['distance'])))\n    psa = m.calc_osc_accels(osc_freqs, damping)\n    return psa\n\n\ndef operation_fa2psa(src,\n                     dst,\n                     damping,\n                     method='LP99',\n                     fixed_spacing=True,\n                     verbose=True):\n    \"\"\"Compute the Fourier amplitude spectrum from a accel. response spectrum.\n\n    Parameters\n    ----------\n    src : str\n        Source for the Fourier amplitudes. This can be a filename or pattern\n        used in :func:`glob.glob`.\n    dst : str\n        Destination directory for the output PSA. The directory is created if\n        it does not exist.\n    damping : float\n        Fractional damping of the oscillator (decimal).\n    method : str\n        RVT peak factor method, see\n        :func:`~.peak_calculators.get_peak_calculator`.\n    fixed_spacing : bool, optional\n        If `True`, then the periods are interpolated to 301 points equally\n        space in log-space from 0.01 to 10.\n\n    \"\"\"\n    if fixed_spacing:\n        periods = np.logspace(-2, 1, 301)\n        osc_freqs = 1. / periods\n\n    for filename_src in glob.iglob(src):\n        if verbose:\n            print('Processing:', filename_src)\n        ext, freqs, events = read_events(filename_src, 'fa')\n\n        if not fixed_spacing:\n            osc_freqs = freqs\n            periods = 1. / osc_freqs\n\n        with multiprocessing.Pool() as pool:\n            psas = pool.map(\n                functools.partial(_calc_psa, osc_freqs, damping, method,\n                                  freqs), events)\n\n        for event, psa in zip(events, psas):\n            event['psa'] = psa\n\n        if not os.path.exists(dst):\n            os.makedirs(dst)\n\n        basename = os.path.basename(filename_src)\n\n        pathname_dst = os.path.join(dst, basename.rsplit('_', 1)[0])\n\n        write_events(pathname_dst + '_sa' + ext, periods, 'Period (s)', 'psa',\n                     'PSA (g)', events)\n", "meta": {"hexsha": "331af291b4abc1a970e4c7e85e0f58cad06d0ff0", "size": 13272, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyrvt/tools.py", "max_stars_repo_name": "g-weatherill/pyrvt", "max_stars_repo_head_hexsha": "1f9288b4aede2a8943220d0c0f977e901974fa64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyrvt/tools.py", "max_issues_repo_name": "g-weatherill/pyrvt", "max_issues_repo_head_hexsha": "1f9288b4aede2a8943220d0c0f977e901974fa64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyrvt/tools.py", "max_forks_repo_name": "g-weatherill/pyrvt", "max_forks_repo_head_hexsha": "1f9288b4aede2a8943220d0c0f977e901974fa64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7511961722, "max_line_length": 79, "alphanum_fraction": 0.5961422544, "include": true, "reason": "import numpy", "num_tokens": 3110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3311197396289914, "lm_q1q2_score": 0.1707319322417274}}
{"text": "# -*- coding: utf-8 -*-\nimport os\nimport numpy as np\nimport pandas as pd\nimport pickle\nimport pystan\nimport bokeh.plotting\nimport tqdm\nfrom .stats import compute_statistics\n\n\nclass StanModel(object):\n    r\"\"\"\n    Custom StanModel class for crafting and sampling from Stan\n    models.\n    \"\"\"\n\n    def __init__(self, file, data_dict=None, samples=None, force_compile=False):\n        \"\"\"\n        Parameters\n        ----------\n        model: str\n            Relative path to saved Stan model code. To deter bad habits,\n            this class does not accept a string as the model code. Save \n            your Stan models. \n        data_dict: dictionary\n            Dictonary of all data block parameters for the model.\n        force_compile: bool\n            If True, model will be forced to compile. If False, \n            a precompiled file will be loaded if present. \n        \"\"\"\n        if \".pkl\" in file:\n            s = _load(file)\n            self.model = s[0]\n            self.samples = s[1]\n        else:\n            self.model = loadStanModel(file, force=force_compile)\n            self.data = data_dict\n            self.samples = samples\n            self.df = None\n\n    def sample(self, data_dict=None, iter=2000, chains=4, return_df=True, **kwargs):\n        \"\"\"\n        Samples the assembled model given the supplied data dictionary\n        and returns output as a dataframe.\n        \"\"\"\n        if data_dict == None:\n            data_dict = self.data\n        self.chains = chains\n        self.iter = iter\n        self.samples = self.model.sampling(\n            data_dict, chains=chains, iter=iter, **kwargs\n        )\n        if return_df:\n            self.df = self.samples.to_dataframe(diagnostics=True)\n            return [self.samples, self.df]\n        else:\n            return self.samples\n\n    # Pickling objects\n    def dump(fname):\n        \"\"\"Saves StanFit4Model object and sampling summary as a pickled dictionary.\"\"\"\n        with open(f\"{fname.split('.')[0]}.pkl\", \"wb\") as _file:\n            pickle.dump({\"model\": self.model, \"fit\": self.samples}, _file, protocol=-1)\n\n    def _load(fname):\n        with open(file, \"rb\") as _file:\n            fit_dict = pickle.load(_file)\n        self.model = fit_dict[0]\n        self.samples = fit_dict[1]\n        return [self.model, self.samples]\n\n    def summarize_parameters(self, parnames=[], mass_frac=0.95):\n        \"\"\"\n        Summarizes all or a subset of parameters from a Stan model. \n        \n        Parameters\n        ----------\n        parnames: list\n            List of desired parnames. If left empty, all parameters \n            are summarized and returned. \n        mass_frac: float [0, 1]\n            The probability mass fraction for the HPD. Default is \n            the 95% credible region. \n            \n        Returns\n        -------\n        summary_df: pandas DataFrame\n            Dataframe of summarized parameters. The columns are as\n            follows:\n                parameter = name of parameter in Stan model\n                dimension = index (dimension) of the parameter\n                mean = mean of samples\n                median = median of samples\n                mode = parameter value when the log posterior is maximized\n                hpd_min = minimum bound of the highest probability density\n                    defined by the mass fraction.\n                hpd_max = upper bound of the highest probability density\n                    defined by the mass fraction\n        \"\"\"\n        # Extract the sampling information and find the mode\n        samples = self.samples\n        fit = samples.extract()\n        mode_ind = np.argmax(fit[\"lp__\"])\n\n        # Get a list of all parameters defined in the model and assign a dimension\n        pars = samples.model_pars\n\n        # Convert the dimensions for each parameter to integers.\n        _dims = []\n        for d in samples.par_dims:\n            if len(d) == 0:\n                _dims.append(1)\n            else:\n                _dims.append(int(d[0]))\n\n        par_dims = {p: v for p, v in zip(pars, _dims)}\n        if len(parnames) != 0:\n            pars = parnames\n            desired_pars = {k: v for k, v in par_dims.items() if k in parnames}\n            par_dims = desired_pars\n\n        # Iterate through each parameter and compute the aggregate properties.\n        df = pd.DataFrame(\n            [],\n            columns=[\n                \"parameter\",\n                \"dimension\",\n                \"mean\" \"mode\",\n                \"median\",\n                \"hpd_min\",\n                \"hpd_max\",\n                \"mass_fraction\",\n            ],\n        )\n        for par, dim in par_dims.items():\n            par_samples = fit[par]\n            if dim == 1:\n                par_samples = par_samples[:, np.newaxis]\n            for j in range(dim):\n                # Compute the summary statistics\n                par_mode = par_samples[:, j][mode_ind]\n                par_mean = np.mean(par_samples[:, j])\n                par_median = np.median(par_samples[:, j])\n                hpd_min, hpd_max = compute_hpd(par_samples[:, j], mass_frac=mass_frac)\n\n                # Assemble a dictionary to append to the data frame\n                par_dict = {\n                    \"parameter\": par,\n                    \"dimension\": j + 1,\n                    \"mean\": par_mean,\n                    \"mode\": par_mode,\n                    \"median\": par_median,\n                    \"hpd_min\": hpd_min,\n                    \"hpd_max\": hpd_max,\n                    \"mass_fraction\": mass_frac,\n                }\n                df = df.append(par_dict, ignore_index=True)\n        df[\"dimension\"] = df[\"dimension\"].astype(int)\n        return df\n\n\ndef loadStanModel(fname, force=False):\n    \"\"\"Loads a precompiled Stan model. If no compiled model is found, one will be saved.\"\"\"\n    # Identify the model name and directory structure\n    rel, sm_dir = fname.split(\"/stan/\")\n    sm_name = sm_dir.split(\".stan\")[0]\n    pkl_name = f\"{rel}/stan/{sm_name}.pkl\"\n    # Check if the model is precompiled\n    if (os.path.exists(pkl_name) == True) and (force != True):\n        print(\"Found precompiled model. Loading...\")\n        model = pickle.load(open(pkl_name, \"rb\"))\n        print(\"finished!\")\n    else:\n        print(\"Precompiled model not found. Compiling model...\")\n        _path = rel + \"/stan/\"\n        model = pystan.StanModel(fname, include_paths=_path)\n        print(\"finished!\")\n        with open(pkl_name, \"wb\") as f:\n            pickle.dump(model, f)\n    return model\n\n\ndef infer_empirical_bohr(\n    data,\n    model,\n    groupby=[\"mutant\", \"repressors\", \"operator\", \"IPTGuM\"],\n    verbose=True,\n    force_compile=False,\n    **kwargs,\n):\n    \"\"\"\n    Infers the empirical bohr parameter (and relevant correction) for a collection of \n    fold-change measurements\n    \n    Parameters\n    ----------\n    data: pandas DataFrame object\n        The data from which the empirical bohr will be determined. This should have at least\n        a fold-change column and a grouping parameter.\n    model: str\n        Path to Stan model to load. Model will be compiled if `force_compile`==True.\n    groupby: list, optional\n        List of identifiers by which to group the supplied data. Default groups by \n        'mutant', 'repressors', 'operator', and 'IPTGuM'\n    verbose: bool\n        If true, the progress will be printed to screen as a bar. \n    force_compile: bool\n        If True, the stan model will be recompiled.\n    **kwargs: keyword arguments\n        kwargs to be passed to the sampler.\n        \n    Returns\n    -------\n    statistics: pandas DataFrame\n        Dataframe of statistics for relevant parameters.\n    \"\"\"\n\n    # Load the stan model and compile if needed.\n    model = StanModel(model, force_compile=force_compile)\n\n    # Make a storage list for the individual statistics\n    fc_stats = []\n\n    # Make a quiet or loud iterator.\n    if verbose:\n        iter = tqdm.tqdm(data.groupby(groupby))\n    else:\n        iter = data.groupby(groupby)\n\n    # Iter through each grouping and infer\n    for g, d in iter:\n        # Define parameters of the reference state\n        ref = d[\"ref_bohr\"].unique()[0]\n        fc_ref = (1 + np.exp(-ref)) ** -1\n\n        # Assemble the data dictionary and sample the posterior\n        data_dict = {\"N\": len(d), \"foldchange\": d[\"fold_change\"]}\n        fit, samples = model.sample(data_dict, **kwargs)\n\n        # Identify the extrema\n        extrema = (samples[\"fc_mu\"] < samples[\"fc_sigma\"]).astype(int) + (\n            1 - samples[\"fc_mu\"] < samples[\"fc_sigma\"]\n        ).astype(int)\n\n        # Compute the empirical bohr parameter and the delta bohr\n        samples[\"empirical_bohr\"] = -np.log((samples[\"fc_mu\"]) ** -1 - 1)\n        samples[\"delta_bohr\"] = ref - samples[\"empirical_bohr\"]\n\n        # Compute the delta F error of the reference, given the sigma\n        delta_F_ref_upper = np.nan_to_num(\n            ref + np.log((fc_ref + samples[\"fc_sigma\"]) ** -1 - 1)\n        )\n        delta_F_ref_lower = np.nan_to_num(\n            ref + np.log((fc_ref - samples[\"fc_sigma\"]) ** -1 - 1)\n        )\n        samples[\"correction\"] = (delta_F_ref_upper + delta_F_ref_lower) * extrema\n        samples[\"delta_bohr_corrected\"] = samples[\"delta_bohr\"] - samples[\"correction\"]\n\n        _dbohr_stats = compute_statistics(\n            samples,\n            varnames=[\n                \"delta_bohr\",\n                \"empirical_bohr\",\n                \"fc_mu\",\n                \"fc_sigma\",\n                \"delta_bohr_corrected\",\n                \"correction\",\n            ],\n            logprob_name=\"lp__\",\n        )\n        _dbohr_stats[\"mutant\"] = g[0]\n        _dbohr_stats[\"repressors\"] = g[1]\n        _dbohr_stats[\"operator\"] = g[2]\n        _dbohr_stats[\"IPTGuM\"] = g[3]\n        _dbohr_stats[\"class\"] = d[\"class\"].unique()[0]\n        fc_stats.append(_dbohr_stats)\n\n    return pd.concat(fc_stats)\n", "meta": {"hexsha": "433062027026fd09f98ac4e26d36f9a0fa1ad26f", "size": 9848, "ext": "py", "lang": "Python", "max_stars_repo_path": "phd/bayes.py", "max_stars_repo_name": "mrazomej/phd", "max_stars_repo_head_hexsha": "8a20de50b02ccad49f51845fdc58d5586257ebba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-01-14T01:12:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T10:33:20.000Z", "max_issues_repo_path": "phd/bayes.py", "max_issues_repo_name": "mrazomej/phd", "max_issues_repo_head_hexsha": "8a20de50b02ccad49f51845fdc58d5586257ebba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-10-13T03:30:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-11T18:21:43.000Z", "max_forks_repo_path": "phd/bayes.py", "max_forks_repo_name": "gchure/phd", "max_forks_repo_head_hexsha": "cf5941e467ee57c6c93c78dda151335cb320f831", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1714285714, "max_line_length": 92, "alphanum_fraction": 0.5645816409, "include": true, "reason": "import numpy", "num_tokens": 2226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.1707319288383255}}
{"text": "\"\"\"\nlvmspec.fluxcalibration\n========================\n\nFlux calibration routines.\n\"\"\"\nfrom __future__ import absolute_import\nimport numpy as np\nfrom .resolution import Resolution\nfrom .linalg import cholesky_solve, cholesky_solve_and_invert, spline_fit\nfrom .interpolation import resample_flux\nfrom lvmutil.log import get_logger\nfrom .io.filters import load_filter\nfrom lvmspec import util\nimport scipy, scipy.sparse, scipy.ndimage\nimport sys\nimport time\nfrom astropy import units\nimport multiprocessing\nfrom pkg_resources import resource_exists, resource_filename\n\n\ndef applySmoothingFilter(flux,width=200) :\n    \"\"\" Return a smoothed version of the input flux array using a median filter\n\n    Args:\n        flux  : 1D array of flux\n        width : size of the median filter box\n\n    Returns:\n        smooth_flux : median filtered flux of same size as input\n    \"\"\"\n\n    # it was checked that the width of the median_filter has little impact on best fit stars\n    # smoothing the ouput (with a spline for instance) does not improve the fit\n    return scipy.ndimage.filters.median_filter(flux,width,mode='constant')\n#\n# Import some global constants.\n#\n# Why not use astropy constants?\n#\n# This is VERY inconvenient when trying to build documentation!\n# The documentation may be build in an environment that does not have\n# scipy installed.  There is no obvious reason why this has to be a module-level\n# calculation.\n#\nimport scipy.constants as const\nh=const.h\npi=const.pi\ne=const.e\nc=const.c\nerg=const.erg\ntry:\n    hc = const.h/const.erg*const.c*1.e10  # (in units of ergsA)\nexcept TypeError:\n    hc = 1.9864458241717586e-08\n\ndef resample_template(data_wave_per_camera,resolution_data_per_camera,template_wave,template_flux,template_id) :\n    \"\"\"Resample a spectral template on the data wavelength grid. Then convolve the spectra by the resolution\n    for each camera. Also returns the result of applySmoothingFilter. This routine is used internally in\n    a call to multiprocessing.Pool.\n\n    Args:\n        data_wave_per_camera : A dictionary of 1D array of vacuum wavelengths [Angstroms], one entry per camera and exposure.\n        resolution_data_per_camera :  A dictionary of resolution corresponding for the fiber, one entry per camera and exposure.\n        template_wave : 1D array, input spectral template wavelength [Angstroms] (arbitrary spacing).\n        template_flux : 1D array, input spectral template flux density.\n        template_id   : int, template identification index, used to ensure matching of input/output after a multiprocessing run.\n\n    Returns:\n        template_id   : int, template identification index, same as input.\n        output_wave   : A dictionary of 1D array of vacuum wavelengths\n        output_flux   : A dictionary of 1D array of output template flux\n        output_norm   : A dictionary of 1D array of output template smoothed flux\n    \"\"\"\n    output_wave=np.array([])\n    output_flux=np.array([])\n    output_norm=np.array([])\n    sorted_keys = list(data_wave_per_camera.keys())\n    sorted_keys.sort() # force sorting the keys to agree with data (found unpredictable ordering in tests)\n    for cam in sorted_keys :\n        flux1=resample_flux(data_wave_per_camera[cam],template_wave,template_flux) # this is slow\n        flux2=Resolution(resolution_data_per_camera[cam]).dot(flux1) # this is slow\n        norme=applySmoothingFilter(flux2) # this is fast\n        flux3=flux2/(norme+(norme==0))\n        output_flux = np.append(output_flux,flux3)\n        output_norm = np.append(output_norm,norme)\n        output_wave = np.append(output_wave,data_wave_per_camera[cam]) # need to add wave to avoid wave/flux matching errors\n    return template_id,output_wave,output_flux,output_norm\n\n\ndef _func(arg) :\n    \"\"\" Used for multiprocessing.Pool \"\"\"\n    return resample_template(**arg)\n\ndef _smooth_template(template_id,camera_index,template_flux) :\n    \"\"\" Used for multiprocessing.Pool \"\"\"\n    norme = applySmoothingFilter(template_flux)\n    return template_id,camera_index,norme\n\ndef _func2(arg) :\n    \"\"\" Used for multiprocessing.Pool \"\"\"\n    return _smooth_template(**arg)\n\ndef redshift_fit(wave, flux, ivar, resolution_data, stdwave, stdflux, z_max=0.005, z_res=0.00005, template_error=0.):\n    \"\"\" Redshift fit of a single template\n\n    Args:\n        wave : A dictionary of 1D array of vacuum wavelengths [Angstroms]. Example below.\n        flux : A dictionary of 1D observed flux for the star\n        ivar : A dictionary 1D inverse variance of flux\n        resolution_data: resolution corresponding to the star's fiber\n        stdwave : 1D standard star template wavelengths [Angstroms]\n        stdflux : 1D[nwave] template flux\n        z_max : float, maximum blueshift and redshift in scan, has to be positive\n        z_res : float, step of of redshift scan between [-z_max,+z_max]\n        template_error : float, assumed template flux relative error\n\n    Returns:\n        redshift : redshift of standard star\n\n\n    Notes:\n      - wave and stdwave can be on different grids that don't\n        necessarily overlap\n      - wave does not have to be uniform or monotonic.  Multiple cameras\n        can be supported by concatenating their wave and flux arrays\n    \"\"\"\n    cameras = list(flux.keys())\n    log = get_logger()\n    log.debug(time.asctime())\n\n    # resampling on a log wavelength grid\n    #####################################\n    # need to go fast so we resample both data and model on a log grid\n\n    # define grid\n    minwave = 100000.\n    maxwave = 0.\n    for cam in cameras :\n        minwave=min(minwave,np.min(wave[cam]))\n        maxwave=max(maxwave,np.max(wave[cam]))\n    # ala boss\n    lstep=np.log10(1+z_res)\n    margin=int(np.log10(1+z_max)/lstep)+1\n    minlwave=np.log10(minwave)\n    maxlwave=np.log10(maxwave) # desired, but readjusted\n    nstep=(maxlwave-minlwave)/lstep\n\n    resampled_lwave=minlwave+lstep*np.arange(nstep)\n    resampled_wave=10**resampled_lwave\n\n    # map data on grid\n    resampled_data={}\n    resampled_ivar={}\n    resampled_model={}\n    for cam in cameras :\n        tmp_flux,tmp_ivar=resample_flux(resampled_wave,wave[cam],flux[cam],ivar[cam])\n        resampled_data[cam]=tmp_flux\n        resampled_ivar[cam]=tmp_ivar\n\n        # we need to have the model on a larger grid than the data wave for redshifting\n        dwave=wave[cam][-1]-wave[cam][-2]\n        npix=int((wave[cam][-1]*z_max)/dwave+2)\n        extended_cam_wave=np.append( wave[cam][0]+dwave*np.arange(-npix,0) ,  wave[cam])\n        extended_cam_wave=np.append( extended_cam_wave, wave[cam][-1]+dwave*np.arange(1,npix+1))\n        # ok now we also need to increase the resolution\n        tmp_res=np.zeros((resolution_data[cam].shape[0],resolution_data[cam].shape[1]+2*npix))\n        tmp_res[:,:npix] = np.tile(resolution_data[cam][:,0],(npix,1)).T\n        tmp_res[:,npix:-npix] = resolution_data[cam]\n        tmp_res[:,-npix:] = np.tile(resolution_data[cam][:,-1],(npix,1)).T\n        # resampled model at camera resolution, with margin\n        tmp=resample_flux(extended_cam_wave,stdwave,stdflux)\n        tmp=Resolution(tmp_res).dot(tmp)\n        # map on log lam grid\n        resampled_model[cam]=resample_flux(resampled_wave,extended_cam_wave,tmp)\n\n        # we now normalize both model and data\n        tmp=applySmoothingFilter(resampled_data[cam])\n        resampled_data[cam]/=(tmp+(tmp==0))\n        resampled_ivar[cam]*=tmp**2\n\n        if template_error>0 :\n            ok=np.where(resampled_ivar[cam]>0)[0]\n            if ok.size > 0 :\n                resampled_ivar[cam][ok] = 1./ ( 1/resampled_ivar[cam][ok] + template_error**2 )\n\n        tmp=applySmoothingFilter(resampled_model[cam])\n        resampled_model[cam]/=(tmp+(tmp==0))\n        resampled_ivar[cam]*=(tmp!=0)\n\n    # fit the best redshift\n    chi2=np.zeros((2*margin+1))\n    ndata=np.zeros((2*margin+1))\n    for i in range(-margin,margin+1) :\n        for cam in cameras :\n            ndata[i+margin] += np.sum(resampled_ivar[cam][margin:-margin]>0)\n            if i<margin :\n                chi2[i+margin] += np.sum(resampled_ivar[cam][margin:-margin]*(resampled_data[cam][margin:-margin]-resampled_model[cam][margin+i:-margin+i])**2)\n            else :\n                chi2[i+margin] += np.sum(resampled_ivar[cam][margin:-margin]*(resampled_data[cam][margin:-margin]-resampled_model[cam][margin+i:])**2)\n    import matplotlib.pyplot as plt\n\n    i=np.argmin(chi2)-margin\n    z=10**(-i*lstep)-1\n    log.debug(\"Best z=%f\"%z)\n    '''\n    log.debug(\"i=%d\"%i)\n    log.debug(\"lstep=%f\"%lstep)\n    log.debug(\"margin=%d\"%margin)\n    plt.figure()\n    #plt.plot(chi2)\n    for cam in cameras :\n        ok=np.where(resampled_ivar[cam]>0)[0]\n        #plt.plot(resampled_wave[ok],resampled_data[cam][ok],\"o\",c=\"gray\")\n        plt.errorbar(resampled_wave[ok],resampled_data[cam][ok],1./np.sqrt(resampled_ivar[cam][ok]),fmt=\"o\",color=\"gray\")\n        plt.plot(resampled_wave[margin:-margin],resampled_model[cam][margin+i:-margin+i],\"-\",c=\"r\")\n    plt.show()\n    '''\n    return z\n\n\ndef _compute_coef(coord,node_coords) :\n    \"\"\" Function used by interpolate_on_parameter_grid2\n\n    Args:\n        coord : 1D array of coordinates of size n_axis\n        node_coords : 2D array of coordinates of nodes, shape = (n_nodes,n_axis)\n\n    Returns:\n        coef : 1D array of linear coefficients for each node, size = n_nodes\n    \"\"\"\n\n    n_nodes=node_coords.shape[0]\n    npar=node_coords.shape[1]\n    coef=np.ones(n_nodes)\n    for s in range(n_nodes) :\n        coef[s]=1.\n        for a in range(npar) :\n            dist=np.abs(node_coords[s,a]-coord[a]) # distance between model point and node along axis a\n\n            # piece-wise linear version\n            if dist>1 :\n                coef[s]=0.\n                break\n            coef[s] *= (1.-dist)\n\n            # we could alternatively have used b-spline of higher order\n\n    norme=np.sum(coef)\n    if norme<=0 : # we are outside of valid grid\n        return np.zeros(coef.shape) # will be detected in fitter\n    coef /= norme\n    return coef\n\n\ndef interpolate_on_parameter_grid(data_wave, data_flux, data_ivar, template_flux, teff, logg, feh, template_chi2) :\n    \"\"\" 3D Interpolation routine among templates based on a grid of parameters teff, logg, feh.\n        The tricky part is to define a cube on the parameter grid populated with templates, and it is not always possible.\n        The routine never extrapolates, so that we stay in the range of input parameters.\n\n    Args:\n        data_wave : 1D[nwave] array of wavelength (concatenated list of input wavelength of different cameras and exposures)\n        data_flux : 1D[nwave] array of normalized flux = (input flux)/median_filter(input flux) (concatenated list)\n        data_ivar : 1D[nwave] array of inverse variance of normalized flux\n        template_flux : 2D[ntemplates,nwave] array of normalized flux of templates (after resample, convolution and division by median_filter)\n        teff : 1D[ntemplates]\n        logg : 1D[ntemplates]\n        feh  : 1D[ntemplates]\n        template_chi2 : 1D[ntemplatess] array of precomputed chi2 = sum(data_ivar*(data_flux-template_flux)**2)\n\n    Returns:\n        coefficients : best fit coefficient of linear combination of templates\n        chi2 : chi2 of the linear combination\n    \"\"\"\n\n    log = get_logger()\n    log.debug(\"starting interpolation on grid\")\n\n    best_model_id = np.argmin(template_chi2)\n    ndata=np.sum(data_ivar>0)\n\n    log.debug(\"best model id=%d chi2/ndata=%f teff=%d logg=%2.1f feh=%2.1f\"%(best_model_id,template_chi2[best_model_id]/ndata,teff[best_model_id],logg[best_model_id],feh[best_model_id]))\n\n    ntemplates=template_flux.shape[0]\n\n    log_linear = False # if True , model = exp( sum_i a_i * log(template_flux_i) ), else model = sum_i a_i * template_flux_i\n\n    # physical parameters define axes\n    npar=3\n    param=np.zeros((npar,ntemplates))\n    param[0]=teff\n    param[1]=logg\n    param[2]=feh\n\n    # grid nodes coordinates (unique values of the parameters)\n    uparam=[]\n    for a in range(npar) :\n        uparam.append(np.unique(param[a]))\n    #for a in range(npar) :\n    #    log.debug(\"param %d : %s\"%(a,str(uparam[a])))\n\n\n    node_grid_coords=np.zeros((npar,3)).astype(int)\n    for a in range(npar) : # a is an axis\n        # this is the coordinate on axis 'a' of the best node\n        i=np.where(uparam[a]==param[a,best_model_id])[0][0]\n        node_grid_coords[a]=np.array([i-1,i,i+1])\n        log.debug(\"node_grid_coords[%d]=%s\"%(a,node_grid_coords[a]))\n\n    # we don't always have a template on all nodes\n    node_template_ids=[]\n    node_cube_coords=[]\n    for i0,j0 in zip(node_grid_coords[0],[-1,0,1]) :\n        for i1,j1 in zip(node_grid_coords[1],[-1,0,1]) :\n            for i2,j2 in zip(node_grid_coords[2],[-1,0,1]) :\n\n                # check whether coord is in grid\n                in_grid = (i0>=0)&(i0<uparam[0].size)&(i1>=0)&(i1<uparam[1].size)&(i2>=0)&(i2<uparam[2].size)\n                if not in_grid :\n                    continue\n                # check whether there is a template on this node\n                selection=np.where((param[0]==uparam[0][i0])&(param[1]==uparam[1][i1])&(param[2]==uparam[2][i2]))[0]\n                if selection.size == 0 : # no template on node\n                    log.debug(\"not template for params = %f,%f,%f\"%(uparam[0][i0],uparam[1][i1],uparam[2][i2]))\n                    continue\n                # we have one\n                node_cube_coords.append([j0,j1,j2])\n                node_template_ids.append(selection[0])\n    node_template_ids=np.array(node_template_ids).astype(int)\n    node_cube_coords=np.array(node_cube_coords).astype(int)\n\n    # the parameters of the fit are npar coordinates in the range [-1,1] centered on best fit node\n    coord=np.zeros(npar)\n\n    n_templates = node_template_ids.size\n\n    # we are done with the indexing and choice of template nodes\n    node_template_flux = template_flux[node_template_ids]\n\n    # compute all weighted scalar products among templates (only works if linear combination, not the log version)\n    HB=np.zeros(n_templates)\n    HA=np.zeros((n_templates,n_templates))\n    for t in range(n_templates) :\n        HB[t] = np.sum(data_ivar*data_flux*node_template_flux[t])\n        for t2 in range(n_templates) :\n            if HA[t2,t] != 0 :\n                HA[t,t2] = HA[t2,t]\n            else :\n                HA[t,t2] = np.sum(data_ivar*node_template_flux[t]*node_template_flux[t2])\n\n    chi2_0 = np.sum(data_ivar*data_flux**2)\n\n    # chi2  =  np.sum(data_ivar*(data_flux-model)**2)\n    #       =  chi2_0 - 2*np.sum(data_ivar*data_flux*model) + np.sum(data_ivar*model**2)\n    # model = sum_i coef_i model_i\n    # chi2  =  chi2_0 - 2* sum_i coef_i * HB[i] + sum_ij coef_i * coef_j * HA[i,j]\n    # chi2  =  chi2_0 - 2*np.inner(coef,HB) + np.inner(coef,HA.dot(coef))\n\n\n    # initial state\n    coef = _compute_coef(coord,node_cube_coords)\n    chi2 = chi2_0 - 2*np.inner(coef,HB) + np.inner(coef,HA.dot(coef))\n    log.debug(\"init coord=%s chi2/ndata=%f\"%(coord,chi2/ndata))\n\n    # now we have to do the fit\n    # fitting one axis at a time (simultaneous fit of 3 axes was tested and found inefficient : rapidly stuck on edges)\n    # it has to be iterative because the model is a non-linear combination of parameters w, ex: w[0]*(1-w[1])*(1-w[2])\n    for loop in range(50) :\n\n        previous_chi2=chi2.copy()\n        previous_coord=coord.copy()\n\n        for a in range(npar) :\n            previous_chi2_a=chi2.copy()\n\n            # it's a linear combination of templates, but the model is non-linear function of coordinates\n            # so there is no gain in trying to fit robustly with Gauss-Newton, we simply do a scan\n            # it is converging rapidely (need however to iterate on axes)\n            xcoord=coord.copy()\n            xx=np.linspace(-1,1,41) # keep points on nodes , 41 is the resolution, 0.05 of node inter-distance\n            chi2=np.zeros(xx.shape)\n            for i,x in enumerate(xx) :\n                xcoord[a]=x\n                coef = _compute_coef(xcoord,node_cube_coords)\n                if np.sum(coef)==0 : # outside valid range\n                    chi2[i]=1e20\n                else :\n                    chi2[i] = chi2_0 - 2*np.inner(coef,HB) + np.inner(coef,HA.dot(coef))\n\n            ibest=np.argmin(chi2)\n            chi2=chi2[ibest]\n            coord[a]=xx[ibest]\n\n        log.debug(\"loop #%d coord=%s chi2/ndata=%f (-dchi2_loop=%f -dchi2_tot=%f)\"%(loop,coord,chi2/ndata,previous_chi2-chi2,template_chi2[best_model_id]-chi2))\n        diff=np.max(np.abs(coord-previous_coord))\n        if diff < 0.001 :\n            break\n\n    # finally perform an exact best fit per axis\n    for loop in range(50) :\n        previous_chi2=chi2.copy()\n        previous_coord=coord.copy()\n        for a in range(npar) :\n            if coord[a]==-1 or coord[a]==1 :\n                continue # we are on edge, no gain in refitting\n            xcoord=coord.copy()\n            coef_minus = _compute_coef(xcoord,node_cube_coords)\n            eps=0.001\n            xcoord[a] += eps\n            coef_plus  = _compute_coef(xcoord,node_cube_coords)\n            dcoef_dcoord = (coef_plus-coef_minus)/eps # do a numeric derivative\n            #log.debug(\"dcoef_dcoord=%s\"%dcoef_dcoord)\n            B = np.inner(dcoef_dcoord,HB) - np.inner(dcoef_dcoord,HA.dot(coef_minus))\n            A = np.inner(dcoef_dcoord,HA.dot(dcoef_dcoord))\n            if A>0 :\n                dcoord=B/A\n                #log.debug(\"dcoord=%f\"%dcoord)\n                tmp_coord=coord.copy()\n                tmp_coord[a] += dcoord\n                if tmp_coord[a]<-1 or tmp_coord[a]>1 :\n                    #log.debug(\"do not allow extrapolations\")\n                    continue\n                coef = _compute_coef(tmp_coord,node_cube_coords)\n                tmp_chi2 = chi2_0 - 2*np.inner(coef,HB) + np.inner(coef,HA.dot(coef))\n                if tmp_chi2 < chi2 :\n                    log.debug(\"Improved chi2 by %f with a shift along %d of %f\"%(chi2-tmp_chi2,a,dcoord))\n                    coord=tmp_coord\n                    chi2 = tmp_chi2\n        diff=np.max(np.abs(coord-previous_coord))\n        if diff < 0.001 :\n            break\n\n    coef = _compute_coef(coord,node_cube_coords)\n    chi2 = chi2_0 - 2*np.inner(coef,HB) + np.inner(coef,HA.dot(coef))\n\n    input_number_of_templates=template_flux.shape[0]\n    final_coefficients=np.zeros(input_number_of_templates)\n    final_coefficients[node_template_ids]=coef\n\n    log.debug(\"COORD=%s\"%coord)\n    log.debug(\"COEF=%s\"%coef)\n    #for i in np.where(final_coefficients>0)[0] :\n    #    log.debug(\"TEFF[%d]=%f\"%(i,teff[i]))\n    #    log.debug(\"LOGG[%d]=%f\"%(i,logg[i]))\n    #    log.debug(\"FEH[%d]=%f\"%(i,feh[i]))\n    log.debug(\"TEFF=%f\"%np.inner(final_coefficients,teff))\n    log.debug(\"LOGG=%f\"%np.inner(final_coefficients,logg))\n    log.debug(\"FEH=%f\"%np.inner(final_coefficients,feh))\n    log.debug(\"Contributing template Ids=%s\"%np.where(final_coefficients!=0)[0])\n\n    '''\n    # useful debugging plot\n    import matplotlib.pyplot as plt\n    plt.figure()\n    ok=np.where(data_ivar>0)[0]\n    ii=np.argsort(data_wave[ok])\n    twave=data_wave[ok][ii]\n    tflux=data_flux[ok][ii]\n    tivar=data_ivar[ok][ii]\n    #plt.errorbar(twave,tflux,1./np.sqrt(tivar),fmt=\"o\")\n    plt.plot(twave,tflux,\".\",c=\"gray\",alpha=0.2)\n    dw=np.min(twave[twave>twave[0]+0.5]-twave[0])\n    bins=np.linspace(twave[0],twave[-1],(twave[-1]-twave[0])/dw+1)\n    sw,junk=np.histogram(twave,bins=bins,weights=tivar)\n    swx,junk=np.histogram(twave,bins=bins,weights=tivar*twave)\n    swy,junk=np.histogram(twave,bins=bins,weights=tivar*tflux)\n    tflux=swy[sw>0]/sw[sw>0]\n    twave2=swx[sw>0]/sw[sw>0]\n    terr=1./np.sqrt(sw[sw>0])\n    plt.errorbar(twave2,tflux,terr,fmt=\"o\",alpha=0.5)\n    model = np.zeros(data_flux.shape)\n    for c,t in zip(coef,node_template_flux) :\n        model += c*t\n    plt.plot(twave,model[ok][ii],\"-\",c=\"r\")\n    plt.show()\n    '''\n\n\n    return final_coefficients,chi2\n\n\ndef match_templates(wave, flux, ivar, resolution_data, stdwave, stdflux, teff, logg, feh, ncpu=1, z_max=0.005, z_res=0.00002, template_error=0):\n    \"\"\"For each input spectrum, identify which standard star template is the closest\n    match, factoring out broadband throughput/calibration differences.\n\n    Args:\n        wave : A dictionary of 1D array of vacuum wavelengths [Angstroms]. Example below.\n        flux : A dictionary of 1D observed flux for the star\n        ivar : A dictionary 1D inverse variance of flux\n        resolution_data: resolution corresponding to the star's fiber\n        stdwave : 1D standard star template wavelengths [Angstroms]\n        stdflux : 2D[nstd, nwave] template flux\n        teff : 1D[nstd] effective model temperature\n        logg : 1D[nstd] model surface gravity\n        feh : 1D[nstd] model metallicity\n        ncpu : number of cpu for multiprocessing\n\n    Returns:\n        coef : numpy.array of linear coefficient of standard stars\n        redshift : redshift of standard star\n        chipdf : reduced chi2\n\n    Notes:\n      - wave and stdwave can be on different grids that don't\n        necessarily overlap\n      - wave does not have to be uniform or monotonic.  Multiple cameras\n        can be supported by concatenating their wave and flux arrays\n    \"\"\"\n    # I am treating the input arguments from three frame files as dictionary. For example\n    # wave{\"r\":rwave,\"b\":bwave,\"z\":zwave}\n    # Each data(3 channels) is compared to every model.\n    # flux should be already flat fielded and sky subtracted.\n\n\n\n    cameras = list(flux.keys())\n    log = get_logger()\n    log.debug(time.asctime())\n\n    # fit continuum and save it\n    continuum={}\n    for cam in wave.keys() :\n        tmp=applySmoothingFilter(flux[cam]) # this is fast\n        continuum[cam] = tmp\n\n    # mask out wavelength that could bias the fit\n\n    log.debug(\"mask potential cosmics (3 sigma positive fluctuations)\")\n    for cam in wave.keys() :\n        ok=np.where((ivar[cam]>0))[0]\n        if ok.size>0 :\n            ivar[cam][ok] *= (flux[cam][ok]<(continuum[cam][ok]+3/np.sqrt(ivar[cam][ok])))\n\n\n    log.debug(\"mask sky lines\")\n    # in vacuum\n    # mask blue lines that can affect fit of Balmer series\n    # line at 5577 has a stellar line close to it !\n    # line at 7853. has a stellar line close to it !\n    # mask everything above 8270A because it can bias the star redshift\n    # all of this is based on analysis of a few exposures of BOSS data\n    # in vacuum\n    skylines=np.array([4047.5,4359.3,5462.3,5578.9,5891.3,5897.3,6301.8,6365.4,7823.3,7855.2])\n\n    hw=6. # A\n    for cam in wave.keys() :\n        for line in skylines :\n            ivar[cam][(wave[cam]>=(line-hw))&(wave[cam]<=(line+hw))]=0.\n        ivar[cam][wave[cam]>8270]=0.\n\n    # mask telluric lines\n    srch_filename = \"data/arc_lines/telluric_lines.txt\"\n    if not resource_exists('lvmspec', srch_filename):\n        log.error(\"Cannot find telluric mask file {:s}\".format(srch_filename))\n        raise Exception(\"Cannot find telluric mask file {:s}\".format(srch_filename))\n    telluric_mask_filename = resource_filename('lvmspec', srch_filename)\n    telluric_features = np.loadtxt(telluric_mask_filename)\n    log.debug(\"Masking telluric features from file %s\"%telluric_mask_filename)\n    for cam in wave.keys() :\n        for feature in telluric_features :\n            ivar[cam][(wave[cam]>=feature[0])&(wave[cam]<=feature[1])]=0.\n\n\n\n    # add error propto to flux to account for model error\n    if template_error>0  :\n        for cam in wave.keys() :\n            ok=np.where(ivar[cam]>0)[0]\n            if ok.size>0 :\n                ivar[cam][ok] = 1./ ( 1./ivar[cam][ok] + (template_error*continuum[cam][ok] )**2 )\n\n    # normalize data and store them in single array\n    data_wave=np.array([])\n    data_flux=np.array([])\n    data_continuum=np.array([])\n    data_ivar=np.array([])\n    data_index=np.array([])\n    sorted_keys = list(wave.keys())\n    sorted_keys.sort() # force sorting the keys to agree with models (found unpredictable ordering in tests)\n    for index,cam in enumerate(sorted_keys) :\n        data_index=np.append(data_index,np.ones(wave[cam].size)*index)\n        data_wave=np.append(data_wave,wave[cam])\n        data_flux=np.append(data_flux,flux[cam]/(continuum[cam]+(continuum[cam]==0)))\n        data_continuum=np.append(data_continuum,continuum[cam])\n        data_ivar=np.append(data_ivar,ivar[cam]*continuum[cam]**2)\n    data_index=data_index.astype(int)\n\n    ndata = np.sum(data_ivar>0)\n\n\n    # start looking at models\n\n    # find canonical f-type model: Teff=6000, logg=4, Fe/H=-1.5\n    canonical_model=np.argmin((teff-6000.0)**2+(logg-4.0)**2+(feh+1.5)**2)\n\n    # fit redshift on canonical model\n    # we use the original data to do this\n    # because we resample both the data and model on a logarithmic grid in the routine\n\n    if True : # mask Ca H&K lines. Present in ISM, can bias the stellar redshift fit\n        log.debug(\"Mask ISM lines for redshift\")\n        ismlines=np.array([3934.77,3969.59])\n        hw=6. # A\n        for cam in wave.keys() :\n            for line in ismlines :\n                ivar[cam][(wave[cam]>=(line-hw))&(wave[cam]<=(line+hw))]=0.\n\n    z = redshift_fit(wave, flux, ivar, resolution_data, stdwave, stdflux[canonical_model], z_max, z_res)\n\n    # now we go back to the model spectra , redshift them, resample, apply resolution, normalize and chi2 match\n\n    ntemplates=stdflux.shape[0]\n\n    # here we take into account the redshift once and for all\n    shifted_stdwave=stdwave*(1+z)\n\n    func_args = []\n    # need to parallelize the model resampling\n    for template_id in range(ntemplates) :\n        arguments={\"data_wave_per_camera\":wave,\n                   \"resolution_data_per_camera\":resolution_data,\n                   \"template_wave\":shifted_stdwave,\n                   \"template_flux\":stdflux[template_id],\n                   \"template_id\":template_id}\n        func_args.append( arguments )\n\n\n    if ncpu > 1:\n        log.debug(\"creating multiprocessing pool with %d cpus\"%ncpu); sys.stdout.flush()\n        pool = multiprocessing.Pool(ncpu)\n        log.debug(\"Running pool.map() for {} items\".format(len(func_args))); sys.stdout.flush()\n        results  =  pool.map(_func, func_args)\n        log.debug(\"Finished pool.map()\"); sys.stdout.flush()\n        pool.close()\n        pool.join()\n        log.debug(\"Finished pool.join()\"); sys.stdout.flush()\n    else:\n        log.debug(\"Not using multiprocessing for {} cpus\".format(ncpu))\n\n        results = [_func(x) for x in func_args]\n        log.debug(\"Finished serial loop\")\n\n    # collect results\n    # in case the exit of the multiprocessing pool is not ordered as the input\n    # we returned the template_id\n    template_flux=np.zeros((ntemplates,data_flux.size))\n    template_norm=np.zeros((ntemplates,data_flux.size))\n    for result in results :\n        template_id       = result[0]\n        template_tmp_wave = result[1]\n        template_tmp_flux = result[2]\n        template_tmp_norm = result[3]\n        mdiff=np.max(np.abs(data_wave-template_tmp_wave)) # just a safety check\n        if mdiff>1.e-5 :\n            log.error(\"error indexing of wave and flux somewhere above, checking if it's just an ordering issue, max diff=%f\"%mdiff)\n            raise ValueError(\"wavelength array difference cannot be fixed with reordering, ordered max diff=%f\"%mdiff)\n        template_flux[template_id] = template_tmp_flux\n        template_norm[template_id] = template_tmp_norm\n\n    # compute model chi2\n    template_chi2=np.zeros(ntemplates)\n    for template_id in range(ntemplates) :\n        template_chi2[template_id] = np.sum(data_ivar*(data_flux-template_flux[template_id])**2)\n\n    best_model_id=np.argmin(template_chi2)\n    best_chi2=template_chi2[best_model_id]\n    log.debug(\"selected best model {} chi2/ndf {}\".format(best_model_id, best_chi2/ndata))\n\n    # interpolate around best model using parameter grid\n    coef,chi2 = interpolate_on_parameter_grid(data_wave, data_flux, data_ivar, template_flux, teff, logg, feh, template_chi2)\n    log.debug(\"after interpolation chi2/ndf {}\".format(chi2/ndata))\n\n    log.debug(\"use best fit to derive calibration and apply it to the templates before refitting the star ...\")\n    # the division by the median filtered spectrum leaves some imprint of the input transmission\n    # so we will apply calibration to the model and redo the whole fit\n    # to make sure this is not driving the stellar model selection.\n\n\n    log.debug(\"remultiply template by their norme\")\n    template_flux *= template_norm\n\n    log.debug(\"compute best fit model\")\n    model=np.zeros(data_wave.size)\n    for c,t in zip(coef,template_flux) :\n        if c>0 : model += c*t\n\n\n    func_args=[]\n    for index in np.unique(data_index) :\n        log.debug(\"compute calib for cam index %d\"%index)\n        ii=np.where(data_index==index)[0]\n        calib = (data_flux[ii]*data_continuum[ii])/(model[ii]+(model[ii]==0))\n        scalib = applySmoothingFilter(calib,width=400)\n\n        min_scalib=0.\n        bad=scalib<=min_scalib\n        if np.sum(bad)>0 :\n            scalib[bad]=min_scalib\n\n        log.debug(\"multiply templates by calib for cam index %d\"%index)\n        template_flux[:,ii] *= scalib\n\n        # apply this to all the templates and recompute median filter\n        for t in range(template_flux.shape[0]) :\n            arguments={\"template_id\":t,\"camera_index\":index,\"template_flux\":template_flux[t][ii]}\n            func_args.append(arguments)\n\n    if ncpu > 1:\n        log.debug(\"divide templates by median filters using multiprocessing.Pool of ncpu=%d\"%ncpu)\n        pool = multiprocessing.Pool(ncpu)\n        results  =  pool.map(_func2, func_args)\n        log.debug(\"finished pool.map()\"); sys.stdout.flush()\n        pool.close()\n        pool.join()\n        log.debug(\"finished pool.join()\"); sys.stdout.flush()\n    else :\n        log.debug(\"divide templates serially\")\n        results = [_func2(x) for x in func_args]\n        log.debug(\"Finished serial loop\")\n\n    # collect results\n    for result in results :\n        template_id = result[0]\n        index  = result[1]\n        template_flux[template_id][data_index==index] /= (result[2] + (result[2]==0))\n\n    log.debug(\"refit the model ...\")\n    template_chi2=np.zeros(ntemplates)\n    for template_id in range(ntemplates) :\n        template_chi2[template_id] = np.sum(data_ivar*(data_flux-template_flux[template_id])**2)\n\n    best_model_id=np.argmin(template_chi2)\n    best_chi2=template_chi2[best_model_id]\n\n    log.debug(\"selected best model {} chi2/ndf {}\".format(best_model_id, best_chi2/ndata))\n\n    # interpolate around best model using parameter grid\n    coef,chi2 = interpolate_on_parameter_grid(data_wave, data_flux, data_ivar, template_flux, teff, logg, feh, template_chi2)\n    log.debug(\"after interpolation chi2/ndf {}\".format(chi2/ndata))\n\n\n    return coef,z,chi2/ndata\n\n\ndef normalize_templates(stdwave, stdflux, mags, filters):\n    \"\"\"Returns spectra normalized to input magnitudes.\n\n    Args:\n        stdwave : 1D array of standard star wavelengths [Angstroms]\n        stdflux : 1D observed flux\n        mags : 1D array of observed AB magnitudes\n        filters : list of filter names for mags, e.g. ['SDSS_r', 'DECAM_g', ...]\n\n    Returns:\n        stdwave : same as input\n        normflux : normalized flux array\n\n    Only SDSS_r band is assumed to be used for normalization for now.\n    \"\"\"\n    log = get_logger()\n\n    nstdwave=stdwave.size\n    normflux=np.array(nstdwave)\n\n    fluxunits = 1e-17 * units.erg / units.s / units.cm**2 / units.Angstrom\n\n    for i,v in enumerate(filters):\n        #Normalizing using only SDSS_R band magnitude\n        if v.upper() == 'SDSS_R' or v.upper() =='DECAM_R' or v.upper()=='DECAM_G' :\n            #-TODO: Add more filters for calibration. Which one should be used if multiple mag available?\n            refmag=mags[i]\n            filter_response=load_filter(v)\n            apMag=filter_response.get_ab_magnitude(stdflux*fluxunits,stdwave)\n            log.info('scaling {} mag {:f} to {:f}.'.format(v, apMag,refmag))\n            scalefac=10**((apMag-refmag)/2.5)\n            normflux=stdflux*scalefac\n\n            break  #- found SDSS_R or DECAM_R; we can stop now\n        count=0\n        for k,f in enumerate(['SDSS_R','DECAM_R','DECAM_G']):\n            ii,=np.where((np.asarray(filters)==f))\n            count=count+ii.shape[0]\n        if (count==0):\n            log.error(\"No magnitude given for SDSS_R, DECAM_R or DECAM_G filters\")\n            sys.exit(0)\n    return normflux\n\ndef compute_flux_calibration(frame, input_model_wave,input_model_flux,input_model_fibers, nsig_clipping=4.,deg=2,debug=False):\n    \"\"\"Compute average frame throughput based on data frame.(wave,flux,ivar,resolution_data)\n    and spectro-photometrically calibrated stellar models (model_wave,model_flux).\n    Wave and model_wave are not necessarily on the same grid\n\n    Args:\n      frame : Frame object with attributes wave, flux, ivar, resolution_data\n      input_model_wave : 1D[nwave] array of model wavelengths\n      input_model_flux : 2D[nstd, nwave] array of model fluxes\n      input_model_fibers : 1D[nstd] array of model fibers\n      nsig_clipping : (optional) sigma clipping level\n\n    Returns:\n         lvmspec.FluxCalib object\n         calibration: mean calibration (without resolution)\n\n    Notes:\n      - we first resample the model on the input flux wave grid\n      - then convolve it to the data resolution (the input wave grid is supposed finer than the spectral resolution)\n      - then iteratively\n        - fit the mean throughput (deconvolved, this is needed because of sharp atmospheric absorption lines)\n        - compute broad band correction to fibers (to correct for small mis-alignement for instance)\n        - perform outlier rejection\n\n     There is one subtelty with the relation between calibration and resolution.\n      - The input frame flux is on average flux^frame_fiber = R_fiber*C*flux^true where C is the true calibration (or throughput)\n        which is a function of wavelength. This is the system we solve.\n      - But we want to return a calibration vector per fiber C_fiber defined by flux^cframe_fiber = flux^frame_fiber/C_fiber,\n        such that flux^cframe can be compared with a convolved model of the truth, flux^cframe_fiber = R_fiber*flux^true,\n        i.e. (R_fiber*C*flux^true)/C_fiber = R_fiber*true_flux, giving C_fiber = (R_fiber*C*flux^true)/(R_fiber*flux^true)\n      - There is no solution for this for all possible input specta. The solution for a flat spectrum is returned,\n        which is very close to C_fiber = R_fiber*C (but not exactly).\n\n    \"\"\"\n\n    log=get_logger()\n    log.info(\"starting\")\n\n    #- Pull out just the standard stars for convenience, but keep the\n    #- full frame of spectra around because we will later need to convolved\n    #- the calibration vector for each fiber individually\n    stdfibers = np.intersect1d( np.where(frame.fibermap['OBJTYPE'] == 'STD')[0] , input_model_fibers)\n    stdstars = frame[stdfibers]\n\n    nwave=stdstars.nwave\n    nstds=stdstars.flux.shape[0]\n\n    dwave=(stdstars.wave-np.mean(stdstars.wave))/(stdstars.wave[-1]-stdstars.wave[0]) # normalized wave for polynomial fit\n\n    # resample model to data grid and convolve by resolution\n    model_flux=np.zeros((nstds, nwave))\n    convolved_model_flux=np.zeros((nstds, nwave))\n    for fiber in range(model_flux.shape[0]) :\n        model_flux[fiber]=resample_flux(stdstars.wave,input_model_wave,input_model_flux[fiber])\n        convolved_model_flux[fiber]=stdstars.R[fiber].dot(model_flux[fiber])\n\n    # iterative fitting and clipping to get precise mean spectrum\n    current_ivar=stdstars.ivar*(stdstars.mask==0)\n\n    #- Start with a first pass median rejection\n    calib = (convolved_model_flux!=0)*(stdstars.flux/(convolved_model_flux + (convolved_model_flux==0)))\n    median_calib = np.median(calib, axis=0)\n\n    # First fit of smooth correction per fiber, and 10% model error to variance,  and perform first outlier rejection\n    smooth_fiber_correction=np.ones((stdstars.flux.shape))\n    chi2=np.zeros((stdstars.flux.shape))\n\n    for fiber in range(nstds) :\n        M = median_calib*stdstars.R[fiber].dot(model_flux[fiber])\n\n        try:\n            pol=np.poly1d(np.polyfit(dwave,stdstars.flux[fiber]/(M+(M==0)),deg=deg,w=current_ivar[fiber]*M**2))\n            smooth_fiber_correction[fiber]=pol(dwave)\n        except ValueError :\n            log.warning(\"polynomial fit for fiber %d failed\"%fiber)\n            current_ivar[fiber]=0.\n\n        chi2[fiber]=current_ivar[fiber]*(stdstars.flux[fiber]-smooth_fiber_correction[fiber]*M)**2\n\n\n    bad=(chi2>nsig_clipping**2)\n    current_ivar[bad] = 0\n\n    sqrtw=np.sqrt(current_ivar)\n    sqrtwflux=np.sqrt(current_ivar)*stdstars.flux\n\n    # diagonal sparse matrices\n    D1=scipy.sparse.lil_matrix((nwave,nwave))\n    D2=scipy.sparse.lil_matrix((nwave,nwave))\n\n\n    nout_tot=0\n    previous_mean=0.\n    for iteration in range(20) :\n\n        # fit mean calibration\n        A=scipy.sparse.lil_matrix((nwave,nwave)).tocsr()\n        B=np.zeros((nwave))\n\n        # loop on fiber to handle resolution\n        for fiber in range(nstds) :\n            if fiber%10==0 :\n                log.info(\"iter %d fiber %d\"%(iteration,fiber))\n\n            R = stdstars.R[fiber]\n\n            # diagonal sparse matrix with content = sqrt(ivar)*flat\n            D1.setdiag(sqrtw[fiber]*smooth_fiber_correction[fiber])\n            D2.setdiag(model_flux[fiber])\n            sqrtwmodelR = D1.dot(R.dot(D2)) # chi2 = sum (sqrtw*data_flux -diag(sqrtw)*smooth_fiber_correction*R*diag(model_flux)*calib )\n\n            A = A+(sqrtwmodelR.T*sqrtwmodelR).tocsr()\n            B += sqrtwmodelR.T*sqrtwflux[fiber]\n\n        if np.sum(current_ivar>0)==0 :\n            log.error(\"null ivar, cannot calibrate this frame\")\n            raise ValueError(\"null ivar, cannot calibrate this frame\")\n\n        #- Add a weak prior that calibration = median_calib\n        #- to keep A well conditioned\n        minivar = np.min(current_ivar[current_ivar>0])\n        log.debug('min(ivar[ivar>0]) = {}'.format(minivar))\n        epsilon = minivar/10000\n        A = epsilon*np.eye(nwave) + A   #- converts sparse A -> dense A\n        B += median_calib*epsilon\n\n        log.info(\"iter %d solving\"%iteration)\n        ### log.debug('cond(A) {:g}'.format(np.linalg.cond(A)))\n        #calibration=cholesky_solve(A, B)\n        w = np.diagonal(A)>0\n        A_pos_def = A[w,:]\n        A_pos_def = A_pos_def[:,w]\n        calibration = B*0\n        try:\n            calibration[w]=cholesky_solve(A_pos_def, B[w])\n        except np.linalg.linalg.LinAlgError:\n            log.info('cholesky fails in iteration {}, trying svd'.format(iteration))\n            calibration[w] = np.linalg.lstsq(A_pos_def,B[w])[0]\n\n        log.info(\"iter %d fit smooth correction per fiber\"%iteration)\n        # fit smooth fiberflat and compute chi2\n        for fiber in range(nstds) :\n            if fiber%10==0 :\n                log.info(\"iter %d fiber %d(smooth)\"%(iteration,fiber))\n\n            M = stdstars.R[fiber].dot(calibration*model_flux[fiber])\n\n            try:\n                pol=np.poly1d(np.polyfit(dwave,stdstars.flux[fiber]/(M+(M==0)),deg=deg,w=current_ivar[fiber]*M**2))\n                smooth_fiber_correction[fiber]=pol(dwave)\n            except ValueError :\n                log.warning(\"polynomial fit for fiber %d failed\"%fiber)\n                current_ivar[fiber]=0.\n            chi2[fiber]=current_ivar[fiber]*(stdstars.flux[fiber]-smooth_fiber_correction[fiber]*M)**2\n\n        log.info(\"iter {0:d} rejecting\".format(iteration))\n\n        nout_iter=0\n        if iteration<1 :\n            # only remove worst outlier per wave\n            # apply rejection iteratively, only one entry per wave among fibers\n            # find waves with outlier (fastest way)\n            nout_per_wave=np.sum(chi2>nsig_clipping**2,axis=0)\n            selection=np.where(nout_per_wave>0)[0]\n            for i in selection :\n                worst_entry=np.argmax(chi2[:,i])\n                current_ivar[worst_entry,i]=0\n                sqrtw[worst_entry,i]=0\n                #sqrtwmodel[worst_entry,i]=0\n                sqrtwflux[worst_entry,i]=0\n                nout_iter += 1\n\n        else :\n            # remove all of them at once\n            bad=(chi2>nsig_clipping**2)\n            current_ivar *= (bad==0)\n            sqrtw *= (bad==0)\n            #sqrtwmodel *= (bad==0)\n            sqrtwflux *= (bad==0)\n            nout_iter += np.sum(bad)\n\n        nout_tot += nout_iter\n\n        sum_chi2=float(np.sum(chi2))\n        ndf=int(np.sum(chi2>0)-nwave-nstds*2)\n        chi2pdf=0.\n        if ndf>0 :\n            chi2pdf=sum_chi2/ndf\n\n        # normalize to get a mean fiberflat=1\n        mean=np.nanmean(smooth_fiber_correction,axis=0)\n        smooth_fiber_correction /= mean\n\n        log.info(\"iter #%d chi2=%f ndf=%d chi2pdf=%f nout=%d mean=%f\"%(iteration,sum_chi2,ndf,chi2pdf,nout_iter,np.mean(mean)))\n\n        if nout_iter == 0 and np.max(np.abs(mean-previous_mean))<0.0001 :\n            break\n        previous_mean = mean\n\n    # smooth_fiber_correction does not converge exactly to one on average, so we apply its mean to the calibration\n    # (tested on sims)\n    calibration /= mean\n\n    log.info(\"nout tot=%d\"%nout_tot)\n\n    # solve once again to get deconvolved variance\n    #calibration,calibcovar=cholesky_solve_and_invert(A.todense(),B)\n    calibcovar=np.linalg.inv(A)\n    calibvar=np.diagonal(calibcovar)\n    log.info(\"mean(var)={0:f}\".format(np.mean(calibvar)))\n\n    calibvar=np.array(np.diagonal(calibcovar))\n    # apply the mean (as in the iterative loop)\n    calibvar *= mean**2\n    calibivar=(calibvar>0)/(calibvar+(calibvar==0))\n\n    # we also want to save the convolved calibration and a calibration variance\n    # first compute average resolution\n    mean_res_data=np.mean(frame.resolution_data,axis=0)\n    R = Resolution(mean_res_data)\n    # compute convolved calib\n    ccalibration = np.zeros(frame.flux.shape)\n    for i in range(frame.nspec):\n        norme = frame.R[i].dot(np.ones(calibration.shape))\n        ok=np.where(norme>0)[0]\n        if ok.size :\n            ccalibration[i][ok]=frame.R[i].dot(calibration)[ok]/norme[ok]\n\n    # Use diagonal of mean calibration covariance for output.\n    ccalibcovar=R.dot(calibcovar).dot(R.T.todense())\n    ccalibvar=np.array(np.diagonal(ccalibcovar))\n\n    # apply the mean (as in the iterative loop)\n    ccalibvar *= mean**2\n    ccalibivar=(ccalibvar>0)/(ccalibvar+(ccalibvar==0))\n\n    # convert to 2D\n    # For now this is the same for all fibers; in the future it may not be\n    ccalibivar = np.tile(ccalibivar, frame.nspec).reshape(frame.nspec, frame.nwave)\n\n    # need to do better here\n    mask = frame.mask.copy()\n\n    # return calibration, calibivar, mask, ccalibration, ccalibivar\n    return FluxCalib(stdstars.wave, ccalibration, ccalibivar, mask, R.dot(calibration))\n\n\n\nclass FluxCalib(object):\n    def __init__(self, wave, calib, ivar, mask, meancalib=None):\n        \"\"\"Lightweight wrapper object for flux calibration vectors\n\n        Args:\n            wave : 1D[nwave] input wavelength (Angstroms)\n            calib: 2D[nspec, nwave] calibration vectors for each spectrum\n            ivar : 2D[nspec, nwave] inverse variance of calib\n            mask : 2D[nspec, nwave] mask of calib (0=good)\n            meancalib : 1D[nwave] mean convolved calibration (optional)\n\n        All arguments become attributes, plus nspec,nwave = calib.shape\n\n        The calib vector should be such that\n\n            [1e-17 erg/s/cm^2/A] = [photons/A] / calib\n        \"\"\"\n        assert wave.ndim == 1\n        assert calib.ndim == 2\n        assert calib.shape == ivar.shape\n        assert calib.shape == mask.shape\n        assert np.all(ivar >= 0)\n\n        self.nspec, self.nwave = calib.shape\n        self.wave = wave\n        self.calib = calib\n        self.ivar = ivar\n        self.mask = util.mask32(mask)\n        self.meancalib = meancalib\n\n        self.meta = dict(units='photons/(erg/s/cm^2)')\n\n    def __repr__(self):\n        txt = '<{:s}: nspec={:d}, nwave={:d}, units={:s}'.format(\n            self.__class__.__name__, self.nspec, self.nwave, self.meta['units'])\n\n        # Finish\n        txt = txt + '>'\n        return (txt)\n\n\ndef apply_flux_calibration(frame, fluxcalib):\n    \"\"\"\n    Applies flux calibration to input flux and ivar\n\n    Args:\n        frame: Spectra object with attributes wave, flux, ivar, resolution_data\n        fluxcalib : FluxCalib object with wave, calib, ...\n\n    Modifies frame.flux and frame.ivar\n    \"\"\"\n    log=get_logger()\n    log.info(\"starting\")\n\n    # check same wavelength, die if not the case\n    mval=np.max(np.abs(frame.wave-fluxcalib.wave))\n    #if mval > 0.00001 :\n    if mval > 0.001 :\n        log.error(\"not same wavelength (should raise an error instead)\")\n        sys.exit(12)\n\n    nwave=frame.nwave\n    nfibers=frame.nspec\n\n    \"\"\"\n    F'=F/C\n    Var(F') = Var(F)/C**2 + F**2*(  d(1/C)/dC )**2*Var(C)\n    = 1/(ivar(F)*C**2) + F**2*(1/C**2)**2*Var(C)\n    = 1/(ivar(F)*C**2) + F**2*Var(C)/C**4\n    = 1/(ivar(F)*C**2) + F**2/(ivar(C)*C**4)\n    \"\"\"\n    # for fiber in range(nfibers) :\n    #     C = fluxcalib.calib[fiber]\n    #     flux[fiber]=frame.flux[fiber]*(C>0)/(C+(C==0))\n    #     ivar[fiber]=(ivar[fiber]>0)*(civar[fiber]>0)*(C>0)/(   1./((ivar[fiber]+(ivar[fiber]==0))*(C**2+(C==0))) + flux[fiber]**2/(civar[fiber]*C**4+(civar[fiber]*(C==0)))   )\n\n    C = fluxcalib.calib\n    frame.flux = frame.flux * (C>0) / (C+(C==0))\n    frame.ivar *= (fluxcalib.ivar>0) * (C>0)\n    for i in range(nfibers) :\n        ok=np.where(frame.ivar[i]>0)[0]\n        if ok.size>0 :\n            frame.ivar[i,ok] = 1./( 1./(frame.ivar[i,ok]*C[i,ok]**2)+frame.flux[i,ok]**2/(fluxcalib.ivar[i,ok]*C[i,ok]**4)  )\n\n\ndef ZP_from_calib(exptime, wave, calib):\n    \"\"\" Calculate the ZP in AB magnitudes given the calibration and the wavelength arrays\n    Args:\n        exptime:  float;  exposure time in seconds\n        wave:  1D array (A)\n        calib:  1D array (converts erg/s/A to photons/s/A)\n\n    Returns:\n      ZP_AB: 1D array of ZP values in AB magnitudes\n\n    \"\"\"\n    ZP_flambda = 1e-17 / (calib/exptime)  # erg/s/cm^2/A\n    ZP_fnu = ZP_flambda * wave**2 / (2.9979e18)  # c in A/s\n    # Avoid 0 values\n    ZP_AB = np.zeros_like(ZP_fnu)\n    gdZ = ZP_fnu > 0.\n    ZP_AB[gdZ] = -2.5 * np.log10(ZP_fnu[gdZ]) - 48.6\n    # Return\n    return ZP_AB\n\n\ndef qa_fluxcalib(param, frame, fluxcalib):\n    \"\"\"\n    Args:\n        param: dict of QA parameters\n        frame: Frame\n        fluxcalib: FluxCalib\n\n    Returns:\n        qadict: dict of QA outputs\n          Need to record simple Python objects for yaml (str, float, int)\n\n    \"\"\"\n    log = get_logger()\n    qadict = {}\n\n    # Unpack model\n    exptime = frame.meta['EXPTIME']\n\n    # Standard stars\n    stdfibers = np.where((frame.fibermap['OBJTYPE'] == 'STD'))[0]\n    stdstars = frame[stdfibers]\n    nstds = len(stdfibers)\n    #try:\n    #    assert np.array_equal(frame.fibers[stdfibers], input_model_fibers)\n    #except AssertionError:\n    #    log.error(\"Bad indexing in standard stars\")\n\n    # Calculate ZP for mean spectrum\n    #medcalib = np.median(fluxcalib.calib,axis=0)\n    medcalib = np.median(fluxcalib.calib[stdfibers],axis=0)\n    ZP_AB = ZP_from_calib(exptime, fluxcalib.wave, medcalib)  # erg/s/cm^2/A\n\n    # ZP at fiducial wavelength (AB mag for 1 photon/s/A)\n    iZP = np.argmin(np.abs(fluxcalib.wave-param['ZP_WAVE']))\n    qadict['ZP'] = float(np.median(ZP_AB[iZP-10:iZP+10]))\n\n    # Unpack star data\n    #sqrtwmodel, sqrtwflux, current_ivar, chi2 = indiv_stars\n\n    # RMS\n    qadict['NSTARS_FIBER'] = int(nstds)\n    ZP_fiducial = np.zeros(nstds)\n\n    for ii in range(nstds):\n        # Good pixels\n        gdp = stdstars.ivar[ii, :] > 0.\n        icalib = fluxcalib.calib[stdfibers[ii]][gdp]\n        i_wave = fluxcalib.wave[gdp]\n        # ZP\n        ZP_stars = ZP_from_calib(exptime, i_wave, icalib)\n        iZP = np.argmin(np.abs(i_wave-param['ZP_WAVE']))\n        ZP_fiducial[ii] = float(np.median(ZP_stars[iZP-10:iZP+10]))\n    #import pdb; pdb.set_trace()\n    qadict['RMS_ZP'] = float(np.std(ZP_fiducial))\n\n    # MAX ZP Offset\n    #stdfibers = np.where(frame.fibermap['OBJTYPE'] == 'STD')[0]\n    ZPoffset = ZP_fiducial-qadict['ZP']\n    imax = np.argmax(np.abs(ZPoffset))\n    qadict['MAX_ZP_OFF'] = [float(ZPoffset[imax]),\n                            int(stdfibers[np.argmax(ZPoffset)])]\n    if qadict['MAX_ZP_OFF'][0] > param['MAX_ZP_OFF']:\n        log.warning(\"Bad standard star ZP {:g}, in fiber {:d}\".format(\n                qadict['MAX_ZP_OFF'][0], qadict['MAX_ZP_OFF'][1]))\n    # Return\n    return qadict\n", "meta": {"hexsha": "465ad79f3c125c1a2ef30cc9997383adcea6207b", "size": 48479, "ext": "py", "lang": "Python", "max_stars_repo_path": "py/lvmspec/fluxcalibration.py", "max_stars_repo_name": "sdss/lvmspec", "max_stars_repo_head_hexsha": "befd6991537c4947fdf63ca262937f2bb845148f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "py/lvmspec/fluxcalibration.py", "max_issues_repo_name": "sdss/lvmspec", "max_issues_repo_head_hexsha": "befd6991537c4947fdf63ca262937f2bb845148f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "py/lvmspec/fluxcalibration.py", "max_forks_repo_name": "sdss/lvmspec", "max_forks_repo_head_hexsha": "befd6991537c4947fdf63ca262937f2bb845148f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0984284533, "max_line_length": 186, "alphanum_fraction": 0.647187442, "include": true, "reason": "import numpy,import scipy,from astropy", "num_tokens": 13225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.1707319288383255}}
{"text": "#!/usr/bin/env python3\nimport os\nimport numpy as np\nimport gzip\n\n\nimport datetime\n\nfrom LoLIM.IO.metadata import geoditic_to_ITRF, convertITRFToLocal, latlonCS002, ITRFCS002\n\n\"\"\" this is a set of code designed to read LMA data \"\"\"\n\nclass LMA_header:\n    \"\"\"LMA header data. Doesn't do much yet\"\"\"\n    \n    class ant_info:\n        def __init__(self, line):\n            data = line.split()\n            self.id = data[1]\n            self.name = data[2]\n            self.lat = float(data[3])\n            self.lon = float(data[4])\n            self.alt = float(data[5])\n            self.antenna_delay = float(data[6])\n            self.board_rev = int(data[7])\n            self.rec_ch = int(data[8])\n            \n        def add_station_data(self, line):\n            data = line.split()\n            if data[1] != self.id:\n                print(\"PROBLEM IN LMA HEADER 1\")\n                quit()\n                \n            if len(data) != 10:\n                print(\"PROBLEM IN LMA HEADER 2\")\n                quit()\n                \n            self.window = int( data[3] )\n            self.data_ver = int( data[4] )\n            self.RMS_error = float( data[5] )\n            self.sources = int( data[6] )\n            self.percent = float( data[7] )\n            self.power_fraction = float( data[8] )\n            self.active = data[9]\n            \n        def get_XYZ(self, center='LOFAR'):\n            ## TODO: use python package instead.\n            \n            ITRF = geoditic_to_ITRF( [self.lat, self.lon, self.alt] )\n            \n            if center=='LOFAR':\n                phase_center = ITRFCS002\n                reflatlon = latlonCS002\n            elif center==\"LMA\":\n                array_latlonalt = np.array([ self.array_lat, self.array_lon, self.array_alt ])\n                reflatlon = array_latlonalt[:2]\n                phase_center = geoditic_to_ITRF( array_latlonalt )\n            else:\n                ## assume center is lat lon alt\n                array_latlonalt = np.array( center )\n                reflatlon = array_latlonalt[:2]\n                phase_center = geoditic_to_ITRF( array_latlonalt )\n            \n            return convertITRFToLocal( np.array( [ITRF] ), phase_center, reflatlon )[0]\n                \n    def __init__(self, fin, decode_func):\n        self.file_name = fin.name\n        \n        self.antenna_info_list = [] ##NOTE: order is critical!\n        self.num_stations = 0\n        \n        sta_data_index = 0\n         \n        for line in fin:\n            line = decode_func(line)\n            \n            if len(line)>17 and line[:17]=='Number of events:':\n                self.number_events = int( line[17:] )\n                return\n            \n            elif len(line)>17 and line[:16] == \"Data start time:\":\n                line_data = line.split()\n                self.start_date = line_data[-2]\n                self.start_time = line_data[-1]\n            \n            elif len(line)>9 and line[:9]==\"Sta_info:\":\n                new_antenna = LMA_header.ant_info( line )\n                self.antenna_info_list.append( new_antenna )\n                self.num_stations += 1\n                \n            elif len(line)>17 and line[:17] == \"Coordinate center\":\n                lat,lon,alt = line.split()[-3:]\n                self.array_lat = float(lat)\n                self.array_lon = float(lon)\n                self.array_alt = float(alt)\n                \n            elif len(line)>9 and line[:9]==\"Sta_data:\":\n                self.antenna_info_list[ sta_data_index ].add_station_data( line )\n                sta_data_index += 1\n                \n    def midnight_datetime(self):\n        month,day,year = self.start_date.split('/')\n        date = datetime.date( day=int(day), month=int(month), year=int(year) )\n        \n        return datetime.datetime.combine(date,  datetime.time(0), tzinfo= datetime.timezone.utc )\n                \n    def read_aux_file(self, fname=None):\n        \n        class aux_data:\n            def __init__(self, peak_times, raw_powers, above_thresholds, upper_covariance_tri):\n                self.peak_times = peak_times\n                self.raw_powers = raw_powers\n                self.above_thresholds = above_thresholds\n                self.upper_covariance_tri = upper_covariance_tri\n                \n            def get_covariance_matrix(self):\n                covariance_matrix = np.empty( (4,4) )\n                covariance_matrix[0,0] = self.upper_covariance_tri[0]\n                covariance_matrix[0,1] = self.upper_covariance_tri[1]\n                covariance_matrix[0,2] = self.upper_covariance_tri[2]\n                covariance_matrix[0,3] = self.upper_covariance_tri[3]\n                \n                covariance_matrix[1,1] = self.upper_covariance_tri[4]\n                covariance_matrix[1,2] = self.upper_covariance_tri[5]\n                covariance_matrix[1,3] = self.upper_covariance_tri[6]\n                \n                covariance_matrix[2,2] = self.upper_covariance_tri[7]\n                covariance_matrix[2,3] = self.upper_covariance_tri[8]\n                \n                covariance_matrix[3,3] = self.upper_covariance_tri[9]\n                \n                covariance_matrix[1,0] = covariance_matrix[0,1]\n                covariance_matrix[2,0] = covariance_matrix[0,2]\n                covariance_matrix[3,0] = covariance_matrix[0,3] \n                covariance_matrix[2,1] = covariance_matrix[1,2]\n                covariance_matrix[3,1] = covariance_matrix[1,3]\n                covariance_matrix[3,2] = covariance_matrix[2,3]\n                \n                return covariance_matrix\n        \n        if fname is not None:\n            new_fname = fname\n        else:\n            new_fname = self.file_name.replace('dat', 'aux')\n        \n        if new_fname[-3:] =='.gz':\n            func = gzip.open\n            symbol = 'rb'\n        else:\n            func = open\n            symbol = 'r'\n            \n        return_data = []\n            \n        with func(new_fname, symbol) as file:\n            \n            for line in file:\n                line = line.decode()\n                \n                if len(line)>=12 and line[:12] == \"*** data ***\":\n                    break\n                \n            for source_i in range(self.number_events):\n                peak_times = file.readline().decode().split()\n                raw_powers = file.readline().decode().split()\n                above_threshold = file.readline().decode().split()\n                upper_tri_covariance = file.readline().decode().split()\n                \n                N = len(peak_times)\n                if N != len(self.antenna_info_list):\n                    print(\"ERROR A\")\n                    quit()\n                if N != len(raw_powers):\n                    print(\"ERROR B\")\n                    quit()\n                if N != len(above_threshold):\n                    print(\"ERROR C\")\n                    quit()\n                if len(upper_tri_covariance) != 10:\n                    print(\"ERROR D\")\n                    quit()\n                    \n                peak_times = np.array([float(d) for d in peak_times])\n                raw_powers = np.array([int(d) for d in raw_powers])\n                above_threshold = np.array([int(d) for d in above_threshold])\n                upper_tri_covariance = np.array([float(d) for d in upper_tri_covariance])\n                    \n                new_data = aux_data(peak_times, raw_powers, above_threshold, upper_tri_covariance)\n                return_data.append( new_data )\n                \n        return return_data\n                    \n            \n            \nclass LMA_source:\n    def __init__(self, header):\n        self.header = header\n        \n        self.time_of_day = None\n        self.latitude = None\n        self.longitude = None\n        self.altitude = None\n        self.red_chi_squared = None\n        self.power = None\n        self.mask = None\n        self.local_XYZ = None\n        \n    def get_XYZ(self, center='LOFAR'):\n        \n        ## TODO: use python package instead.\n        \n        if self.local_XYZ is None:\n            ITRF = geoditic_to_ITRF( [self.latitude, self.longitude, self.altitude] )\n            \n            if center=='LOFAR':\n                phase_center = ITRFCS002\n                reflatlon = latlonCS002\n            elif center==\"LMA\":\n                array_latlonalt = np.array([ self.header.array_lat, self.header.array_lon, self.header.array_alt ])\n                reflatlon = array_latlonalt[:2]\n                phase_center = geoditic_to_ITRF( array_latlonalt )\n            else:\n                ## assume center is lat lon alt\n                array_latlonalt = np.array( center )\n                reflatlon = array_latlonalt[:2]\n                phase_center = geoditic_to_ITRF( array_latlonalt )\n            \n            self.local_XYZ = convertITRFToLocal( np.array( [ITRF] ), phase_center, reflatlon )[0]\n        \n        \n        return self.local_XYZ\n    \n    def in_XYZ_bounds(self, bounds, center='LOFAR'):\n        XYZ = self.get_XYZ(center)\n        in_X = ( bounds[0][0] <= XYZ[0] <= bounds[0][1] )\n        in_Y = ( bounds[1][0] <= XYZ[1] <= bounds[1][1] )\n        in_Z = ( bounds[2][0] <= XYZ[2] <= bounds[2][1] )\n        return in_X and in_Y and in_Z\n        \n    \n    def get_number_stations(self):\n        mask_str = '{0:0'+str(self.header.num_stations)+'d}'\n        mask2 = mask_str.format(int(bin(int(self.mask, 16))[2:]))\n        self.num_stations = mask2.count('1')\n        return self.num_stations\n    \n    def time_as_datetime(self, midnight_datetime = None):\n        \"\"\"returns datetime, accurate to microsecond, and excess time beyond that (in units of seconds)\"\"\"\n        TD = datetime.timedelta(seconds = self.time_of_day)\n        excess = self.time_of_day - TD.total_seconds() \n        \n        if midnight_datetime is None:\n            midnight_datetime = self.header.midnight_datetime()\n        \n        return midnight_datetime + TD, excess\n        \n        \ndef LMA_fname_info(fname):\n    info = fname.split('_')\n    array_name = info[0]\n    date = info[1]\n    time = info[2]\n    end_stuff = info[3].split('.')\n    seconds_processed = end_stuff[0]\n    is_gzip = end_stuff[-1]=='gz'\n    return array_name, date, time, int(seconds_processed), is_gzip\n    \ndef read_LMA_file_data(fname):\n    source_list = []\n    \n    is_gzip = fname[-3:] =='.gz'\n    if is_gzip:\n        func = gzip.open\n        symbol = 'rb'\n        decode_func = lambda X: X.decode()\n    else:\n        func = open\n        symbol = 'r'\n        decode_func = lambda X: X\n    \n    status = 0 ## 0 means read header, 1 means read source\n    with func(fname, symbol) as file:\n        \n        header = LMA_header(file, decode_func)\n        \n        for line in file:\n            line = decode_func( line )\n            \n            if len(line)>=12 and line[:12] == \"*** data ***\":\n                status = 1\n            elif status==0:\n                pass ## nothing here yet\n            elif status==1:\n                new_LMA_source = LMA_source(header)\n                \n                time, lat, lon, alt, fit, power, mask = line.split()\n                new_LMA_source.time_of_day = float(time)\n                new_LMA_source.latitude = float(lat)\n                new_LMA_source.longitude = float(lon)\n                new_LMA_source.altitude = float(alt)\n                new_LMA_source.red_chi_squared = float(fit)\n                new_LMA_source.power = float(power)\n                new_LMA_source.mask = mask\n                \n#                if new_LMA_source.red_chi_squared < 1:\n                source_list.append(new_LMA_source)\n                \n    return header, source_list\n\ndef read_LMA_multiple_files(LMA_files):\n    \n    ret = []\n    for file in LMA_files:\n        header, sources = read_LMA_file_data(file)\n        print(file, len(sources))\n        ret += sources\n        \n    return ret\n            \n\ndef read_LMA_folder_data(folder, date=None, min_time=None, max_time=None):\n    LMA_fnames = (fname for fname in os. listdir(folder) if fname[-4:]==\".dat\" or fname[-3:]=='.gz')\n    \n    if (date is not None):\n        new_LMA_fnames = []\n        for fname in LMA_fnames:\n            throw, LMA_date, time, throw, throw = LMA_fname_info(fname)\n            if date==LMA_date and (min_time is None or min_time<=time) and (max_time is None or time<max_time):\n                new_LMA_fnames.append( fname )\n        LMA_fnames = new_LMA_fnames\n            \n    if folder[-1] != '/':\n        folder = folder + '/'\n    LMA_fnames = [folder + fname for fname in LMA_fnames]\n      \n    print(LMA_fnames)\n    \n    return read_LMA_multiple_files(LMA_fnames)\n\n\n\n\n", "meta": {"hexsha": "2728a89101f38cff7e22d8fe44b825400be775ea", "size": 12639, "ext": "py", "lang": "Python", "max_stars_repo_path": "LIM_scripts/read_LMA.py", "max_stars_repo_name": "Bhare8972/LOFAR-LIM", "max_stars_repo_head_hexsha": "89f25be8c02cb8980c2e237da3eaac279d40a06a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-04-21T13:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-15T12:44:23.000Z", "max_issues_repo_path": "LIM_scripts/read_LMA.py", "max_issues_repo_name": "Bhare8972/LOFAR-LIM", "max_issues_repo_head_hexsha": "89f25be8c02cb8980c2e237da3eaac279d40a06a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LIM_scripts/read_LMA.py", "max_forks_repo_name": "Bhare8972/LOFAR-LIM", "max_forks_repo_head_hexsha": "89f25be8c02cb8980c2e237da3eaac279d40a06a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-11-06T18:34:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-04T14:16:57.000Z", "avg_line_length": 36.8483965015, "max_line_length": 115, "alphanum_fraction": 0.5243294564, "include": true, "reason": "import numpy", "num_tokens": 2854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.1707319273124741}}
{"text": "# coding: utf-8\n# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\n\"\"\"\nThis module provides some useful functions for dealing with magnetic Structures\n(e.g. Structures with associated magmom tags).\n\"\"\"\n\nimport warnings\nimport numpy as np\nimport os\nimport logging\n\nfrom enum import Enum, unique\nfrom collections import namedtuple\n\nfrom scipy.stats import gaussian_kde\nfrom scipy.signal import argrelextrema\n\nfrom pymatgen.core.structure import Species, Structure, Element, DummySpecies\nfrom pymatgen.electronic_structure.core import Magmom\nfrom pymatgen.symmetry.analyzer import SpacegroupAnalyzer\nfrom pymatgen.transformations.standard_transformations import (\n    AutoOxiStateDecorationTransformation,\n)\nfrom pymatgen.transformations.advanced_transformations import (\n    MagOrderingTransformation,\n    MagOrderParameterConstraint,\n)\nfrom pymatgen.symmetry.groups import SpaceGroup\nfrom monty.serialization import loadfn\n\nfrom typing import Union, List, Dict, Tuple, Optional, Any\nfrom pymatgen.util.typing import Vector3Like\n\n\"\"\"\nThis module provides some useful functions for dealing with magnetic Structures\n(e.g. Structures with associated magmom tags).\n\"\"\"\n\n__author__ = \"Matthew Horton\"\n__copyright__ = \"Copyright 2017, The Materials Project\"\n__version__ = \"0.1\"\n__maintainer__ = \"Matthew Horton\"\n__email__ = \"mkhorton@lbl.gov\"\n__status__ = \"Development\"\n__date__ = \"Feb 2017\"\n\nMODULE_DIR = os.path.dirname(os.path.abspath(__file__))\n\ntry:\n    DEFAULT_MAGMOMS = loadfn(os.path.join(MODULE_DIR, \"default_magmoms.yaml\"))\nexcept Exception:\n    warnings.warn(\n        \"Could not load default_magmoms.yaml, falling back to VASPIncarBase.yaml\"\n    )\n    DEFAULT_MAGMOMS = loadfn(\n        os.path.join(MODULE_DIR, \"../../io/vasp/VASPIncarBase.yaml\")\n    )\n    DEFAULT_MAGMOMS = DEFAULT_MAGMOMS[\"MAGMOM\"]\n\n\n@unique\nclass Ordering(Enum):\n    \"\"\"\n    Enumeration defining possible magnetic orderings.\n    \"\"\"\n\n    FM = \"FM\"  # Ferromagnetic\n    AFM = \"AFM\"  # Antiferromagnetic\n    FiM = \"FiM\"  # Ferrimagnetic\n    NM = \"NM\"  # Non-magnetic\n    Unknown = \"Unknown\"\n\n\n@unique\nclass OverwriteMagmomMode(Enum):\n    \"\"\"\n    Enumeration defining different modes for analyzer.\n    \"\"\"\n\n    none = \"none\"\n    respect_sign = \"respect_sign\"\n    respect_zero = \"respect_zeros\"\n    replace_all = \"replace_all\"\n    normalize = \"normalize\"\n\n\nclass CollinearMagneticStructureAnalyzer:\n    \"\"\"\n    A class which provides a few helpful methods to analyze\n    collinear magnetic structures.\n    \"\"\"\n    def __init__(\n        self,\n        structure: Structure,\n        overwrite_magmom_mode: Union[OverwriteMagmomMode, str] = \"none\",\n        round_magmoms: bool = False,\n        detect_valences: bool = False,\n        make_primitive: bool = True,\n        default_magmoms: dict = None,\n        set_net_positive: bool = True,\n        threshold: float = 0.00,\n        threshold_nonmag: float = 0.1,\n    ):\n        r\"\"\"\n        If magnetic moments are not defined, moments will be\n        taken either from default_magmoms.yaml (similar to the\n        default magmoms in MPRelaxSet, with a few extra definitions)\n        or from a specie:magmom dict provided by the default_magmoms\n        kwarg.\n\n        Input magmoms can be replaced using the 'overwrite_magmom_mode'\n        kwarg. This can be:\n        * \"none\" to do nothing,\n        * \"respect_sign\" which will overwrite existing magmoms with\n          those from default_magmoms but will keep sites with positive magmoms\n          positive, negative magmoms negative and zero magmoms zero,\n        * \"respect_zeros\", which will give a ferromagnetic structure\n          (all positive magmoms from default_magmoms) but still keep sites with\n          zero magmoms as zero,\n        * \"replace_all\" which will try to guess initial magmoms for\n          all sites in the structure irrespective of input structure\n          (this is most suitable for an initial DFT calculation),\n        * \"replace_all_if_undefined\" is the same as \"replace_all\" but only if\n          no magmoms are defined in input structure, otherwise it will respect\n          existing magmoms.\n        * \"normalize\" will normalize magmoms to unity, but will respect sign\n          (used for comparing orderings), magmoms < theshold will be set to zero\n\n        Args:\n            structure: input Structure object\n            overwrite_magmom_mode: \"respect_sign\", \"respect_zeros\", \"replace_all\",\n                \"replace_all_if_undefined\", \"normalize\" (default \"none\")\n            round_magmoms: will round input magmoms to\n                specified number of decimal places if integer is supplied, if set\n                to a float will try and group magmoms together using a kernel density\n                estimator of provided width, and extracting peaks of the estimator\n                detect_valences: if True, will attempt to assign valences\n                to input structure\n            make_primitive: if True, will transform to primitive\n                magnetic cell\n            default_magmoms: (optional) dict specifying default magmoms\n            set_net_positive: if True, will change sign of magnetic\n                moments such that the net magnetization is positive. Argument will be\n                ignored if mode \"respect_sign\" is used.\n            threshold: number (in Bohr magnetons) below which magmoms\n                will be rounded to zero\n            threshold_nonmag: number (in Bohr magneton)\n                below which nonmagnetic ions (with no magmom specified\n                in default_magmoms) will be rounded to zero\n        \"\"\"\n\n        if default_magmoms:\n            self.default_magmoms = default_magmoms\n        else:\n            self.default_magmoms = DEFAULT_MAGMOMS\n\n        structure = structure.copy()\n\n        # check for disorder\n        if not structure.is_ordered:\n            raise NotImplementedError(\n                \"Not implemented for disordered structures, \"\n                \"make ordered approximation first.\"\n            )\n\n        if detect_valences:\n            trans = AutoOxiStateDecorationTransformation()\n            try:\n                structure = trans.apply_transformation(structure)\n            except ValueError:\n                warnings.warn(\n                    \"Could not assign valences \"\n                    \"for {}\".format(structure.composition.reduced_formula)\n                )\n\n        # check to see if structure has magnetic moments\n        # on site properties or species spin properties,\n        # prioritize site properties\n\n        has_magmoms = bool(structure.site_properties.get(\"magmom\", False))\n\n        has_spin = False\n        for comp in structure.species_and_occu:\n            for sp, occu in comp.items():\n                if getattr(sp, \"spin\", False):\n                    has_spin = True\n\n        # perform input sanitation ...\n        # rest of class will assume magnetic moments\n        # are stored on site properties:\n        # this is somewhat arbitrary, arguments can\n        # be made for both approaches\n\n        if has_magmoms and has_spin:\n            raise ValueError(\n                \"Structure contains magnetic moments on both \"\n                \"magmom site properties and spin species \"\n                \"properties. This is ambiguous. Remove one or \"\n                \"the other.\"\n            )\n        elif has_magmoms:\n            if None in structure.site_properties[\"magmom\"]:\n                warnings.warn(\n                    \"Be careful with mixing types in your magmom \"\n                    \"site properties. Any 'None' magmoms have been \"\n                    \"replaced with zero.\"\n                )\n            magmoms = [m if m else 0 for m in structure.site_properties[\"magmom\"]]\n        elif has_spin:\n            magmoms = [getattr(sp, \"spin\", 0) for sp in structure.species]\n            structure.remove_spin()\n        else:\n            # no magmoms present, add zero magmoms for now\n            magmoms = [0] * len(structure)\n            # and overwrite magmoms with default magmoms later unless otherwise stated\n            if overwrite_magmom_mode == \"replace_all_if_undefined\":\n                overwrite_magmom_mode = \"replace_all\"\n\n        # test to see if input structure has collinear magmoms\n        self.is_collinear = Magmom.are_collinear(magmoms)\n\n        if not self.is_collinear:\n            warnings.warn(\n                \"This class is not designed to be used with \"\n                \"non-collinear structures. If your structure is \"\n                \"only slightly non-collinear (e.g. canted) may still \"\n                \"give useful results, but use with caution.\"\n            )\n\n        # this is for collinear structures only, make sure magmoms\n        # are all floats\n        magmoms = list(map(float, magmoms))\n\n        # set properties that should be done /before/ we process input magmoms\n        self.total_magmoms = sum(magmoms)\n        self.magnetization = sum(magmoms) / structure.volume\n\n        # round magmoms on magnetic ions below threshold to zero\n        # and on non magnetic ions below threshold_nonmag\n        magmoms = [\n            m\n            if abs(m) > threshold and a.species_string in self.default_magmoms\n            else m\n            if abs(m) > threshold_nonmag\n            and a.species_string not in self.default_magmoms\n            else 0\n            for (m, a) in zip(magmoms, structure.sites)\n        ]\n\n        # overwrite existing magmoms with default_magmoms\n        if overwrite_magmom_mode not in (\n            \"none\",\n            \"respect_sign\",\n            \"respect_zeros\",\n            \"replace_all\",\n            \"replace_all_if_undefined\",\n            \"normalize\",\n        ):\n            raise ValueError(\"Unsupported mode.\")\n\n        for idx, site in enumerate(structure):\n\n            if site.species_string in self.default_magmoms:\n                # look for species first, e.g. Fe2+\n                default_magmom = self.default_magmoms[site.species_string]\n            elif (\n                isinstance(site.specie, Species)\n                and str(site.specie.element) in self.default_magmoms\n            ):\n                # look for element, e.g. Fe\n                default_magmom = self.default_magmoms[str(site.specie.element)]\n            else:\n                default_magmom = 0\n\n            # overwrite_magmom_mode = \"respect_sign\" will change magnitude of\n            # existing moments only, and keep zero magmoms as\n            # zero: it will keep the magnetic ordering intact\n\n            if overwrite_magmom_mode == \"respect_sign\":\n                set_net_positive = False\n                if magmoms[idx] > 0:\n                    magmoms[idx] = default_magmom\n                elif magmoms[idx] < 0:\n                    magmoms[idx] = -default_magmom\n\n            # overwrite_magmom_mode = \"respect_zeros\" will give a ferromagnetic\n            # structure but will keep zero magmoms as zero\n\n            elif overwrite_magmom_mode == \"respect_zeros\":\n                if magmoms[idx] != 0:\n                    magmoms[idx] = default_magmom\n\n            # overwrite_magmom_mode = \"replace_all\" will ignore input magmoms\n            # and give a ferromagnetic structure with magnetic\n            # moments on *all* atoms it thinks could be magnetic\n\n            elif overwrite_magmom_mode == \"replace_all\":\n                magmoms[idx] = default_magmom\n\n            # overwrite_magmom_mode = \"normalize\" set magmoms magnitude to 1\n\n            elif overwrite_magmom_mode == \"normalize\":\n                if magmoms[idx] != 0:\n                    magmoms[idx] = int(magmoms[idx] / abs(magmoms[idx]))\n\n        # round magmoms, used to smooth out computational data\n        magmoms = (\n            self._round_magmoms(magmoms, round_magmoms) if round_magmoms else magmoms\n        )\n\n        if set_net_positive:\n            sign = np.sum(magmoms)\n            if sign < 0:\n                magmoms = -np.array(magmoms)\n\n        structure.add_site_property(\"magmom\", magmoms)\n\n        if make_primitive:\n            structure = structure.get_primitive_structure(use_site_props=True)\n\n        self.structure = structure\n\n    @staticmethod\n    def _round_magmoms(\n        magmoms: Vector3Like, round_magmoms_mode: Union[int, float]\n    ) -> np.ndarray:\n        \"\"\"If round_magmoms_mode is an integer, simply round to that number\n        of decimal places, else if set to a float will try and round\n        intelligently by grouping magmoms.\n        \"\"\"\n\n        if isinstance(round_magmoms_mode, int):\n\n            # simple rounding to number of decimal places\n            magmoms = np.around(magmoms, decimals=round_magmoms_mode)\n\n        elif isinstance(round_magmoms_mode, float):\n\n            try:\n\n                # get range of possible magmoms, pad by 50% just to be safe\n                range_m = max([max(magmoms), abs(min(magmoms))]) * 1.5\n\n                # construct kde, here \"round_magmoms_mode\" is the width of the kde\n                kernel = gaussian_kde(magmoms, bw_method=round_magmoms_mode)\n\n                # with a linearly spaced grid 1000x finer than width\n                xgrid = np.linspace(\n                    -range_m, range_m, int(1000 * range_m / round_magmoms_mode)\n                )\n\n                # and evaluate the kde on this grid, extracting the maxima of the kde peaks\n                kernel_m = kernel.evaluate(xgrid)\n                extrema = xgrid[argrelextrema(kernel_m, comparator=np.greater)]\n\n                # round magmoms to these extrema\n                magmoms = [extrema[(np.abs(extrema - m)).argmin()] for m in magmoms]\n\n            except Exception as e:\n\n                # TODO: typically a singular matrix warning, investigate this\n                warnings.warn(\n                    \"Failed to round magmoms intelligently, \"\n                    \"falling back to simple rounding.\"\n                )\n                warnings.warn(str(e))\n\n            # and finally round roughly to the number of significant figures in our kde width\n            num_decimals = len(str(round_magmoms_mode).split(\".\")[1]) + 1\n            magmoms = np.around(magmoms, decimals=num_decimals)\n\n        return magmoms\n\n    def get_structure_with_spin(self) -> Structure:\n        \"\"\"Returns a Structure with species decorated with spin values instead\n        of using magmom site properties.\n        \"\"\"\n\n        structure = self.structure.copy()\n        structure.add_spin_by_site(structure.site_properties[\"magmom\"])\n        structure.remove_site_property(\"magmom\")\n\n        return structure\n\n    def get_structure_with_only_magnetic_atoms(\n        self, make_primitive: bool = True\n    ) -> Structure:\n        \"\"\"Returns a Structure with only magnetic atoms present.\n\n        Args:\n          make_primitive: Whether to make structure primitive after\n            removing non-magnetic atoms (Default value = True)\n\n        Returns: Structure\n        \"\"\"\n\n        sites = [site for site in self.structure if abs(site.properties[\"magmom\"]) > 0]\n\n        structure = Structure.from_sites(sites)\n\n        if make_primitive:\n            structure = structure.get_primitive_structure(use_site_props=True)\n\n        return structure\n\n    def get_nonmagnetic_structure(self, make_primitive: bool = True) -> Structure:\n        \"\"\"Returns a Structure without magnetic moments defined.\n\n        Args:\n          make_primitive: Whether to make structure primitive after\n            removing magnetic information (Default value = True)\n\n        Returns:\n          Structure\n\n        \"\"\"\n\n        structure = self.structure.copy()\n        structure.remove_site_property(\"magmom\")\n\n        if make_primitive:\n            structure = structure.get_primitive_structure()\n\n        return structure\n\n    def get_ferromagnetic_structure(self, make_primitive: bool = True) -> Structure:\n        \"\"\"Returns a Structure with all magnetic moments positive\n        or zero.\n\n        Args:\n          make_primitive: Whether to make structure primitive after\n            making all magnetic moments positive (Default value = True)\n\n        Returns:\n          Structure\n\n        \"\"\"\n\n        structure = self.structure.copy()\n\n        structure.add_site_property(\"magmom\", [abs(m) for m in self.magmoms])\n\n        if make_primitive:\n            structure = structure.get_primitive_structure(use_site_props=True)\n\n        return structure\n\n    @property\n    def is_magnetic(self) -> bool:\n        \"\"\"Convenience property, returns True if any non-zero magmoms present.\n        \"\"\"\n        return any(map(abs, self.structure.site_properties[\"magmom\"]))\n\n    @property\n    def magmoms(self) -> np.ndarray:\n        \"\"\"Convenience property, returns magmoms as a numpy array.\n        \"\"\"\n\n        return np.array(self.structure.site_properties[\"magmom\"])\n\n    @property\n    def types_of_magnetic_species(self) -> Tuple[Union[Element, Species, DummySpecies], ...]:\n        \"\"\"Equivalent to Structure.types_of_specie but only returns\n        magnetic species.\n\n        Returns: types of Species as a list\n\n        \"\"\"\n        if self.number_of_magnetic_sites > 0:\n            structure = self.get_structure_with_only_magnetic_atoms()\n            return tuple(sorted(structure.types_of_species))\n        else:\n            return tuple()\n\n    @property\n    def types_of_magnetic_specie(self) -> Tuple[Union[Element, Species, DummySpecies], ...]:\n        \"\"\"\n        Specie->Species rename. Used to maintain backwards compatibility.\n        \"\"\"\n        return self.types_of_magnetic_species\n\n    @property\n    def magnetic_species_and_magmoms(self) -> Dict[str, Any]:\n        \"\"\"Returns a dict of magnetic species and the magnitude of\n        their associated magmoms. Will return a list if there are\n        multiple magmoms per species.\n\n        Returns: dict of magnetic species and magmoms\n        \"\"\"\n\n        structure = self.get_ferromagnetic_structure()\n\n        magtypes: Dict = {\n            str(site.specie): set()\n            for site in structure\n            if site.properties[\"magmom\"] != 0\n        }\n\n        for site in structure:\n            if site.properties[\"magmom\"] != 0:\n                magtypes[str(site.specie)].add(site.properties[\"magmom\"])\n\n        for sp, magmoms in magtypes.items():\n            if len(magmoms) == 1:\n                magtypes[sp] = magmoms.pop()\n            else:\n                magtypes[sp] = sorted(list(magmoms))\n\n        return magtypes\n\n    @property\n    def number_of_magnetic_sites(self) -> int:\n        \"\"\"Number of magnetic sites present in structure.\"\"\"\n        return int(np.sum([abs(m) > 0 for m in self.magmoms]))\n\n    def number_of_unique_magnetic_sites(\n        self, symprec: float = 1e-3, angle_tolerance: float = 5\n    ) -> int:\n        \"\"\"\n\n        Args:\n          symprec: same as in SpacegroupAnalyzer (Default value = 1e-3)\n          angle_tolerance: same as in SpacegroupAnalyzer (Default value = 5)\n\n        Returns: Number of symmetrically-distinct magnetic sites present\n        in structure.\n\n        \"\"\"\n\n        structure = self.get_nonmagnetic_structure()\n\n        sga = SpacegroupAnalyzer(\n            structure, symprec=symprec, angle_tolerance=angle_tolerance\n        )\n\n        symm_structure = sga.get_symmetrized_structure()\n\n        num_unique_mag_sites = 0\n\n        for group_of_sites in symm_structure.equivalent_sites:\n            if group_of_sites[0].specie in self.types_of_magnetic_species:\n                num_unique_mag_sites += 1\n\n        return num_unique_mag_sites\n\n    @property\n    def ordering(self) -> Ordering:\n        \"\"\"Applies heuristics to return a magnetic ordering for a collinear\n        magnetic structure. Result is not guaranteed for correctness.\n\n        Returns: Ordering Enum ('FiM' is used as the abbreviation for\n        ferrimagnetic)\n        \"\"\"\n\n        if not self.is_collinear:\n            warnings.warn(\n                \"Detecting ordering in non-collinear structures not yet implemented.\"\n            )\n            return Ordering.Unknown\n\n        if \"magmom\" not in self.structure.site_properties:\n            # maybe this was a non-spin-polarized calculation, or we've\n            # lost the magnetic moment information\n            return Ordering.Unknown\n\n        magmoms = self.magmoms\n\n        max_magmom = max(magmoms)\n\n        total_magnetization = abs(sum(magmoms))\n\n        is_potentially_ferromagnetic = np.all(magmoms >= 0) or np.all(magmoms <= 0)\n\n        if total_magnetization > 0 and is_potentially_ferromagnetic:\n            return Ordering.FM\n        elif total_magnetization > 0:\n            return Ordering.FiM\n        elif max_magmom > 0:\n            return Ordering.AFM\n        else:\n            return Ordering.NM\n\n    def get_exchange_group_info(\n        self, symprec: float = 1e-2, angle_tolerance: float = 5.0\n    ) -> Tuple[str, int]:\n        \"\"\"Returns the information on the symmetry of the Hamiltonian\n        describing the exchange energy of the system, taking into\n        account relative direction of magnetic moments but not their\n        absolute direction.\n\n        This is not strictly accurate (e.g. some/many atoms will\n        have zero magnetic moments), but defining symmetry this\n        way is a useful way of keeping track of distinct magnetic\n        orderings within pymatgen.\n\n        Args:\n          symprec: same as SpacegroupAnalyzer (Default value = 1e-2)\n          angle_tolerance: same as SpacegroupAnalyzer (Default value = 5.0)\n\n        Returns:\n          spacegroup_symbol, international_number\n\n        \"\"\"\n\n        structure = self.get_structure_with_spin()\n\n        return structure.get_space_group_info(\n            symprec=symprec, angle_tolerance=angle_tolerance\n        )\n\n    def matches_ordering(self, other: Structure) -> bool:\n        \"\"\"Compares the magnetic orderings of one structure with another.\n\n        Args:\n          other: Structure to compare\n\n        Returns: True or False\n        \"\"\"\n\n        a = CollinearMagneticStructureAnalyzer(\n            self.structure, overwrite_magmom_mode=\"normalize\"\n        ).get_structure_with_spin()\n\n        # sign of spins doesn't matter, so we're comparing both\n        # positive and negative versions of the structure\n        # this code is possibly redundant, but is included out of\n        # an abundance of caution\n        b_positive = CollinearMagneticStructureAnalyzer(\n            other, overwrite_magmom_mode=\"normalize\", make_primitive=False\n        )\n\n        b_negative = b_positive.structure.copy()\n        b_negative.add_site_property(\n            \"magmom\", np.multiply(-1, b_negative.site_properties[\"magmom\"])\n        )\n\n        b_negative = CollinearMagneticStructureAnalyzer(\n            b_negative, overwrite_magmom_mode=\"normalize\", make_primitive=False\n        )\n\n        b_positive = b_positive.get_structure_with_spin()\n        b_negative = b_negative.get_structure_with_spin()\n\n        if a.matches(b_positive) or a.matches(\n            b_negative\n        ):  # sometimes returns None (bug?)\n            return True\n        else:\n            return False\n\n    def __str__(self):\n        \"\"\"\n        Sorts a Structure (by fractional co-ordinate), and\n        prints sites with magnetic information. This is\n        useful over Structure.__str__ because sites are in\n        a consistent order, which makes visual comparison between\n        two identical Structures with different magnetic orderings\n        easier.\n        \"\"\"\n\n        frac_coords = self.structure.frac_coords\n        sorted_indices = np.lexsort(\n            (frac_coords[:, 2], frac_coords[:, 1], frac_coords[:, 0])\n        )\n        s = Structure.from_sites([self.structure[idx] for idx in sorted_indices])\n\n        # adapted from Structure.__repr__\n        outs = [\"Structure Summary\", repr(s.lattice)]\n        outs.append(\"Magmoms Sites\")\n        for site in s:\n            if site.properties[\"magmom\"] != 0:\n                prefix = \"{:+.2f}   \".format(site.properties[\"magmom\"])\n            else:\n                prefix = \"        \"\n            outs.append(prefix + repr(site))\n        return \"\\n\".join(outs)\n\n\nclass MagneticStructureEnumerator:\n    \"\"\"Combines MagneticStructureAnalyzer and MagOrderingTransformation to\n    automatically generate a set of transformations for a given structure\n    and produce a list of plausible magnetic orderings.\n    \"\"\"\n\n    available_strategies = (\n        \"ferromagnetic\",\n        \"antiferromagnetic\",\n        \"ferrimagnetic_by_motif\",\n        \"ferrimagnetic_by_species\",\n        \"antiferromagnetic_by_motif\",\n        \"nonmagnetic\",\n    )\n\n    def __init__(\n        self,\n        structure: Structure,\n        default_magmoms: Optional[Dict[str, float]] = None,\n        strategies: Union[List[str], Tuple[str, ...]] = (\"ferromagnetic\", \"antiferromagnetic\"),\n        automatic: bool = True,\n        truncate_by_symmetry: bool = True,\n        transformation_kwargs: Optional[Dict] = None,\n    ):\n        \"\"\"\n        This class will try generated different collinear\n        magnetic orderings for a given input structure.\n\n        If the input structure has magnetic moments defined, it\n        is possible to use these as a hint as to which elements are\n        magnetic, otherwise magnetic elements will be guessed\n        (this can be changed using default_magmoms kwarg).\n\n        Args:\n            structure: input structure\n            default_magmoms: (optional, defaults provided) dict of\n                magnetic elements to their initial magnetic moments in µB, generally\n                these are chosen to be high-spin since they can relax to a low-spin\n                configuration during a DFT electronic configuration\n            strategies: different ordering strategies to use, choose from:\n                ferromagnetic, antiferromagnetic, antiferromagnetic_by_motif,\n                ferrimagnetic_by_motif and ferrimagnetic_by_species (here, \"motif\",\n                means to use a different ordering parameter for symmetry inequivalent\n                sites)\n            automatic: if True, will automatically choose sensible strategies\n            truncate_by_symmetry: if True, will remove very unsymmetrical\n                orderings that are likely physically implausible\n            transformation_kwargs: keyword arguments to pass to\n                MagOrderingTransformation, to change automatic cell size limits, etc.\n        \"\"\"\n\n        self.logger = logging.getLogger(self.__class__.__name__)\n\n        self.structure = structure\n\n        # decides how to process input structure, which sites are magnetic\n        self.default_magmoms = default_magmoms\n\n        # different strategies to attempt, default is usually reasonable\n        self.strategies = list(strategies)\n        # and whether to automatically add strategies that may be appropriate\n        self.automatic = automatic\n\n        # and whether to discard low symmetry structures\n        self.truncate_by_symmetry = truncate_by_symmetry\n\n        # other settings\n        self.num_orderings = 64\n        self.max_unique_sites = 8\n\n        # kwargs to pass to transformation (ultimately to enumlib)\n        default_transformation_kwargs = {\"check_ordered_symmetry\": False, \"timeout\": 5}\n        transformation_kwargs = transformation_kwargs or {}\n        transformation_kwargs.update(default_transformation_kwargs)\n        self.transformation_kwargs = transformation_kwargs\n\n        # our magnetically ordered structures will be\n        # stored here once generated and also store which\n        # transformation created them, this is used for\n        # book-keeping/user interest, and\n        # is be a list of strings in (\"fm\", \"afm\",\n        # \"ferrimagnetic_by_species\", \"ferrimagnetic_by_motif\",\n        # \"afm_by_motif\", \"input_structure\")\n        self.ordered_structures: List[Structure] = []\n        self.ordered_structure_origins: List[str] = []\n\n        formula = structure.composition.reduced_formula\n\n        # to process disordered magnetic structures, first make an\n        # ordered approximation\n        if not structure.is_ordered:\n            raise ValueError(\n                \"Please obtain an ordered approximation of the \"\n                \"input structure ({}).\".format(formula)\n            )\n\n        # CollinearMagneticStructureAnalyzer is used throughout:\n        # it can tell us whether the input is itself collinear (if not,\n        # this workflow is not appropriate), and has many convenience\n        # methods e.g. magnetic structure matching, etc.\n        self.input_analyzer = CollinearMagneticStructureAnalyzer(\n            structure, default_magmoms=default_magmoms, overwrite_magmom_mode=\"none\"\n        )\n\n        # this workflow enumerates structures with different combinations\n        # of up and down spin and does not include spin-orbit coupling:\n        # if your input structure has vector magnetic moments, this\n        # workflow is not appropriate\n        if not self.input_analyzer.is_collinear:\n            raise ValueError(\"Input structure ({}) is non-collinear.\".format(formula))\n\n        self.sanitized_structure = self._sanitize_input_structure(structure)\n\n        # we will first create a set of transformations\n        # and then apply them to our input structure\n        self.transformations = self._generate_transformations(self.sanitized_structure)\n        self._generate_ordered_structures(\n            self.sanitized_structure, self.transformations\n        )\n\n    @staticmethod\n    def _sanitize_input_structure(input_structure: Structure) -> Structure:\n        \"\"\"Sanitize our input structure by removing magnetic information\n        and making primitive.\n\n        Args:\n          input_structure: Structure\n\n        Returns: Structure\n\n        \"\"\"\n\n        input_structure = input_structure.copy()\n\n        # remove any annotated spin\n        input_structure.remove_spin()\n\n        # sanitize input structure: first make primitive ...\n        input_structure = input_structure.get_primitive_structure(use_site_props=False)\n\n        # ... and strip out existing magmoms, which can cause conflicts\n        # with later transformations otherwise since sites would end up\n        # with both magmom site properties and Species spins defined\n        if \"magmom\" in input_structure.site_properties:\n            input_structure.remove_site_property(\"magmom\")\n\n        return input_structure\n\n    def _generate_transformations(\n        self, structure: Structure\n    ) -> Dict[str, MagOrderingTransformation]:\n        \"\"\"The central problem with trying to enumerate magnetic orderings is\n        that we have to enumerate orderings that might plausibly be magnetic\n        ground states, while not enumerating orderings that are physically\n        implausible. The problem is that it is not always obvious by e.g.\n        symmetry arguments alone which orderings to prefer. Here, we use a\n        variety of strategies (heuristics) to enumerate plausible orderings,\n        and later discard any duplicates that might be found by multiple\n        strategies. This approach is not ideal, but has been found to be\n        relatively robust over a wide range of magnetic structures.\n\n        Args:\n          structure: A sanitized input structure (_sanitize_input_structure)\n        Returns: A dict of a transformation class instance (values) and name of\n        enumeration strategy (keys)\n\n        Returns: dict of Transformations keyed by strategy\n\n        \"\"\"\n\n        formula = structure.composition.reduced_formula\n        transformations: Dict[str, MagOrderingTransformation] = {}\n\n        # analyzer is used to obtain information on sanitized input\n        analyzer = CollinearMagneticStructureAnalyzer(\n            structure,\n            default_magmoms=self.default_magmoms,\n            overwrite_magmom_mode=\"replace_all\",\n        )\n\n        if not analyzer.is_magnetic:\n            raise ValueError(\n                \"Not detected as magnetic, add a new default magmom for the \"\n                \"element you believe may be magnetic?\"\n            )\n\n        # now we can begin to generate our magnetic orderings\n        self.logger.info(\"Generating magnetic orderings for {}\".format(formula))\n\n        mag_species_spin = analyzer.magnetic_species_and_magmoms\n        types_mag_species = sorted(\n            analyzer.types_of_magnetic_species,\n            key=lambda sp: analyzer.default_magmoms.get(str(sp), 0),\n            reverse=True,\n        )\n        num_mag_sites = analyzer.number_of_magnetic_sites\n        num_unique_sites = analyzer.number_of_unique_magnetic_sites()\n\n        # enumerations become too slow as number of unique sites (and thus\n        # permutations) increase, 8 is a soft limit, this can be increased\n        # but do so with care\n        if num_unique_sites > self.max_unique_sites:\n            raise ValueError(\"Too many magnetic sites to sensibly perform enumeration.\")\n\n        # maximum cell size to consider: as a rule of thumb, if the primitive cell\n        # contains a large number of magnetic sites, perhaps we only need to enumerate\n        # within one cell, whereas on the other extreme if the primitive cell only\n        # contains a single magnetic site, we have to create larger supercells\n        if \"max_cell_size\" not in self.transformation_kwargs:\n            # TODO: change to 8 / num_mag_sites ?\n            self.transformation_kwargs[\"max_cell_size\"] = max(1, int(4 / num_mag_sites))\n        self.logger.info(\n            \"Max cell size set to {}\".format(\n                self.transformation_kwargs[\"max_cell_size\"]\n            )\n        )\n\n        # when enumerating ferrimagnetic structures, it's useful to detect\n        # symmetrically distinct magnetic sites, since different\n        # local environments can result in different magnetic order\n        # (e.g. inverse spinels)\n        # initially, this was done by co-ordination number, but is\n        # now done by a full symmetry analysis\n        sga = SpacegroupAnalyzer(structure)\n        structure_sym = sga.get_symmetrized_structure()\n        wyckoff = [\"n/a\"] * len(structure)\n        for indices, symbol in zip(\n            structure_sym.equivalent_indices, structure_sym.wyckoff_symbols\n        ):\n            for index in indices:\n                wyckoff[index] = symbol\n        is_magnetic_sites = [\n            True if site.specie in types_mag_species else False for site in structure\n        ]\n        # we're not interested in sites that we don't think are magnetic,\n        # set these symbols to None to filter them out later\n        wyckoff = [\n            symbol if is_magnetic_site else \"n/a\"\n            for symbol, is_magnetic_site in zip(wyckoff, is_magnetic_sites)\n        ]\n        structure.add_site_property(\"wyckoff\", wyckoff)\n        wyckoff_symbols = set(wyckoff) - {\"n/a\"}\n\n        # if user doesn't specifically request ferrimagnetic orderings,\n        # we apply a heuristic as to whether to attempt them or not\n        if self.automatic:\n            if (\n                \"ferrimagnetic_by_motif\" not in self.strategies\n                and len(wyckoff_symbols) > 1\n                and len(types_mag_species) == 1\n            ):\n                self.strategies += [\"ferrimagnetic_by_motif\"]\n\n            if (\n                \"antiferromagnetic_by_motif\" not in self.strategies\n                and len(wyckoff_symbols) > 1\n                and len(types_mag_species) == 1\n            ):\n                self.strategies += [\"antiferromagnetic_by_motif\"]\n\n            if (\n                \"ferrimagnetic_by_species\" not in self.strategies\n                and len(types_mag_species) > 1\n            ):\n                self.strategies += [\"ferrimagnetic_by_species\"]\n\n        # we start with a ferromagnetic ordering\n        if \"ferromagnetic\" in self.strategies:\n            # TODO: remove 0 spins !\n\n            fm_structure = analyzer.get_ferromagnetic_structure()\n            # store magmom as spin property, to be consistent with output from\n            # other transformations\n            fm_structure.add_spin_by_site(fm_structure.site_properties[\"magmom\"])\n            fm_structure.remove_site_property(\"magmom\")\n\n            # we now have our first magnetic ordering...\n            self.ordered_structures.append(fm_structure)\n            self.ordered_structure_origins.append(\"fm\")\n\n        # we store constraint(s) for each strategy first,\n        # and then use each to perform a transformation later\n        all_constraints: Dict[str, Any] = {}\n\n        # ...to which we can add simple AFM cases first...\n        if \"antiferromagnetic\" in self.strategies:\n\n            constraint = MagOrderParameterConstraint(\n                0.5,\n                # TODO: update MagOrderParameterConstraint in\n                # pymatgen to take types_mag_species directly\n                species_constraints=list(map(str, types_mag_species)),\n            )\n            all_constraints[\"afm\"] = [constraint]\n\n            # allows for non-magnetic sublattices\n            if len(types_mag_species) > 1:\n                for sp in types_mag_species:\n                    constraints = [\n                        MagOrderParameterConstraint(0.5, species_constraints=str(sp))\n                    ]\n\n                    all_constraints[\"afm_by_{}\".format(sp)] = constraints\n\n        # ...and then we also try ferrimagnetic orderings by motif if a\n        # single magnetic species is present...\n        if \"ferrimagnetic_by_motif\" in self.strategies and len(wyckoff_symbols) > 1:\n\n            # these orderings are AFM on one local environment, and FM on the rest\n            for symbol in wyckoff_symbols:\n                constraints = [\n                    MagOrderParameterConstraint(\n                        0.5, site_constraint_name=\"wyckoff\", site_constraints=symbol\n                    ),\n                    MagOrderParameterConstraint(\n                        1.0,\n                        site_constraint_name=\"wyckoff\",\n                        site_constraints=list(wyckoff_symbols - {symbol}),\n                    ),\n                ]\n\n                all_constraints[\"ferri_by_motif_{}\".format(symbol)] = constraints\n\n        # and also try ferrimagnetic when there are multiple magnetic species\n        if \"ferrimagnetic_by_species\" in self.strategies:\n\n            sp_list = [str(site.specie) for site in structure]\n            num_sp = {sp: sp_list.count(str(sp)) for sp in types_mag_species}\n            total_mag_sites = sum(num_sp.values())\n\n            for sp in types_mag_species:\n                # attempt via a global order parameter\n                all_constraints[\"ferri_by_{}\".format(sp)] = num_sp[sp] / total_mag_sites\n\n                # attempt via afm on sp, fm on remaining species\n\n                constraints = [\n                    MagOrderParameterConstraint(0.5, species_constraints=str(sp)),\n                    MagOrderParameterConstraint(\n                        1.0,\n                        species_constraints=list(\n                            map(str, set(types_mag_species) - {sp})\n                        ),\n                    ),\n                ]\n\n                all_constraints[\"ferri_by_{}_afm\".format(sp)] = constraints\n\n        # ...and finally, we can try orderings that are AFM on one local\n        # environment, and non-magnetic on the rest -- this is less common\n        # but unless explicitly attempted, these states are unlikely to be found\n        if \"antiferromagnetic_by_motif\" in self.strategies:\n\n            for symbol in wyckoff_symbols:\n                constraints = [\n                    MagOrderParameterConstraint(\n                        0.5, site_constraint_name=\"wyckoff\", site_constraints=symbol\n                    )\n                ]\n\n                all_constraints[\"afm_by_motif_{}\".format(symbol)] = constraints\n\n        # and now construct all our transformations for each strategy\n        transformations = {}\n        for name, constraints in all_constraints.items():\n            trans = MagOrderingTransformation(\n                mag_species_spin,\n                order_parameter=constraints,\n                **self.transformation_kwargs\n            )\n\n            transformations[name] = trans\n\n        return transformations\n\n    def _generate_ordered_structures(\n        self,\n        sanitized_input_structure: Structure,\n        transformations: Dict[str, MagOrderingTransformation],\n    ):\n        \"\"\"Apply our input structure to our list of transformations and output a list\n        of ordered structures that have been pruned for duplicates and for those\n        with low symmetry (optional).\n\n        Args:\n            sanitized_input_structure: A sanitized input structure\n            (_sanitize_input_structure)\n            transformations: A dict of transformations (values) and name of\n            enumeration strategy (key), the enumeration strategy name is just\n            for record keeping\n\n        Returns: None (sets self.ordered_structures\n        and self.ordered_structures_origins instance variables)\n\n        Returns: List of Structures\n        \"\"\"\n\n        ordered_structures = self.ordered_structures\n        ordered_structures_origins = self.ordered_structure_origins\n\n        # utility function to combine outputs from several transformations\n        def _add_structures(\n            ordered_structures, ordered_structures_origins, structures_to_add, origin=\"\"\n        ):\n            \"\"\"Transformations with return_ranked_list can return either\n            just Structures or dicts (or sometimes lists!) -- until this\n            is fixed, we use this function to concat structures given\n            by the transformation.\n            \"\"\"\n            if structures_to_add:\n                # type conversion\n                if isinstance(structures_to_add, Structure):\n                    structures_to_add = [structures_to_add]\n                structures_to_add = [\n                    s[\"structure\"] if isinstance(s, dict) else s\n                    for s in structures_to_add\n                ]\n                # concatenation\n                ordered_structures += structures_to_add\n                ordered_structures_origins += [origin] * len(structures_to_add)\n                self.logger.info(\n                    \"Adding {} ordered structures: {}\".format(\n                        len(structures_to_add), origin\n                    )\n                )\n\n            return ordered_structures, ordered_structures_origins\n\n        for origin, trans in self.transformations.items():\n            structures_to_add = trans.apply_transformation(\n                self.sanitized_structure, return_ranked_list=self.num_orderings\n            )\n            ordered_structures, ordered_structures_origins = _add_structures(\n                ordered_structures,\n                ordered_structures_origins,\n                structures_to_add,\n                origin=origin,\n            )\n\n        # in case we've introduced duplicates, let's remove them\n        self.logger.info(\"Pruning duplicate structures.\")\n        structures_to_remove: List[int] = []\n        for idx, ordered_structure in enumerate(ordered_structures):\n            if idx not in structures_to_remove:\n                duplicate_checker = CollinearMagneticStructureAnalyzer(\n                    ordered_structure, overwrite_magmom_mode=\"none\"\n                )\n                for check_idx, check_structure in enumerate(ordered_structures):\n                    if check_idx not in structures_to_remove and check_idx != idx:\n                        if duplicate_checker.matches_ordering(check_structure):\n                            structures_to_remove.append(check_idx)\n\n        if len(structures_to_remove):\n            self.logger.info(\n                \"Removing {} duplicate ordered structures\".format(\n                    len(structures_to_remove)\n                )\n            )\n            ordered_structures = [\n                s\n                for idx, s in enumerate(ordered_structures)\n                if idx not in structures_to_remove\n            ]\n            ordered_structures_origins = [\n                o\n                for idx, o in enumerate(ordered_structures_origins)\n                if idx not in structures_to_remove\n            ]\n\n        # also remove low symmetry structures\n        if self.truncate_by_symmetry:\n\n            # by default, keep structures with 5 most symmetric space groups\n            if not isinstance(self.truncate_by_symmetry, int):\n                self.truncate_by_symmetry = 5\n\n            self.logger.info(\"Pruning low symmetry structures.\")\n\n            # first get a list of symmetries present\n            symmetry_int_numbers = [\n                s.get_space_group_info()[1] for s in ordered_structures\n            ]\n\n            # then count the number of symmetry operations for that space group\n            num_sym_ops = [\n                len(SpaceGroup.from_int_number(n).symmetry_ops)\n                for n in symmetry_int_numbers\n            ]\n\n            # find the largest values...\n            max_symmetries = sorted(list(set(num_sym_ops)), reverse=True)\n\n            # ...and decide which ones to keep\n            if len(max_symmetries) > self.truncate_by_symmetry:\n                max_symmetries = max_symmetries[0:5]\n            structs_to_keep = [\n                (idx, num)\n                for idx, num in enumerate(num_sym_ops)\n                if num in max_symmetries\n            ]\n\n            # sort so that highest symmetry structs are first\n            structs_to_keep = sorted(\n                structs_to_keep, key=lambda x: (x[1], -x[0]), reverse=True\n            )\n\n            self.logger.info(\n                \"Removing {} low symmetry \"\n                \"ordered structures\".format(\n                    len(ordered_structures) - len(structs_to_keep)\n                )\n            )\n\n            ordered_structures = [ordered_structures[i] for i, _ in structs_to_keep]\n            ordered_structures_origins = [\n                ordered_structures_origins[i] for i, _ in structs_to_keep\n            ]\n\n            # and ensure fm is always at index 0\n            fm_index = ordered_structures_origins.index(\"fm\")\n            ordered_structures.insert(0, ordered_structures.pop(fm_index))\n            ordered_structures_origins.insert(\n                0, ordered_structures_origins.pop(fm_index)\n            )\n\n        # if our input structure isn't in our generated structures,\n        # let's add it manually and also keep a note of which structure\n        # is our input: this is mostly for book-keeping/benchmarking\n        self.input_index = None\n        self.input_origin = None\n        if self.input_analyzer.ordering != Ordering.NM:\n            matches = [\n                self.input_analyzer.matches_ordering(s) for s in ordered_structures\n            ]\n            if not any(matches):\n                ordered_structures.append(self.input_analyzer.structure)\n                ordered_structures_origins.append(\"input\")\n                self.logger.info(\n                    \"Input structure not present in enumerated structures, adding...\"\n                )\n            else:\n                self.logger.info(\n                    \"Input structure was found in enumerated \"\n                    \"structures at index {}\".format(matches.index(True))\n                )\n                self.input_index = matches.index(True)\n                self.input_origin = ordered_structures_origins[self.input_index]\n\n        self.ordered_structures = ordered_structures\n        self.ordered_structure_origins = ordered_structures_origins\n\n\nMagneticDeformation = namedtuple(\"MagneticDeformation\", \"type deformation\")\n\n\ndef magnetic_deformation(\n    structure_A: Structure, structure_B: Structure\n) -> MagneticDeformation:\n    \"\"\"Calculates 'magnetic deformation proxy',\n    a measure of deformation (norm of finite strain)\n    between 'non-magnetic' (non-spin-polarized) and\n    ferromagnetic structures.\n\n    Adapted from Bocarsly et al. 2017,\n    doi: 10.1021/acs.chemmater.6b04729\n\n    Args:\n      structure_A: Structure\n      structure_B: Structure\n\n    Returns: Magnetic deformation\n    \"\"\"\n\n    # retrieve orderings of both input structures\n    ordering_a = CollinearMagneticStructureAnalyzer(\n        structure_A, overwrite_magmom_mode=\"none\"\n    ).ordering\n    ordering_b = CollinearMagneticStructureAnalyzer(\n        structure_B, overwrite_magmom_mode=\"none\"\n    ).ordering\n\n    # get a type string, this is either 'NM-FM' for between non-magnetic\n    # and ferromagnetic, as in Bocarsly paper, or e.g. 'FM-AFM'\n    type_str = \"{}-{}\".format(ordering_a.value, ordering_b.value)\n\n    lattice_a = structure_A.lattice.matrix.T\n    lattice_b = structure_B.lattice.matrix.T\n    lattice_a_inv = np.linalg.inv(lattice_a)\n    p = np.dot(lattice_a_inv, lattice_b)\n    eta = 0.5 * (np.dot(p.T, p) - np.identity(3))\n    w, v = np.linalg.eig(eta)\n    deformation = 100 * (1.0 / 3.0) * np.sqrt(w[0] ** 2 + w[1] ** 2 + w[2] ** 2)\n\n    return MagneticDeformation(deformation=deformation, type=type_str)\n", "meta": {"hexsha": "ed0bacdba9037f82ff734512a96d8f234b8a1d5d", "size": 49006, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymatgen/analysis/magnetism/analyzer.py", "max_stars_repo_name": "Chessmag/pymatgen", "max_stars_repo_head_hexsha": "61a4bb7a1792e1ea2379abd45b3c40efb816fd64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-18T01:26:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-18T01:26:50.000Z", "max_issues_repo_path": "pymatgen/analysis/magnetism/analyzer.py", "max_issues_repo_name": "Chessmag/pymatgen", "max_issues_repo_head_hexsha": "61a4bb7a1792e1ea2379abd45b3c40efb816fd64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pymatgen/analysis/magnetism/analyzer.py", "max_forks_repo_name": "Chessmag/pymatgen", "max_forks_repo_head_hexsha": "61a4bb7a1792e1ea2379abd45b3c40efb816fd64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4059561129, "max_line_length": 95, "alphanum_fraction": 0.62618863, "include": true, "reason": "import numpy,from scipy", "num_tokens": 10182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.17048651342160362}}
{"text": "import re\r\nimport sys\r\nimport warnings\r\n\r\nimport numpy as np\r\nfrom scipy.optimize import fsolve\r\n\r\n# suppress sqrt warning. it's going to happen. Don't really care if it does.\r\nwarnings.filterwarnings('ignore', 'invalid value encountered in sqrt')\r\n\r\n\r\ndef new_duct_network():\r\n    ducts = dict(title=None, fan_pressure=None, air_density=None, roughness=None, rounding=None, fittings=[])\r\n    return ducts\r\n\r\n\r\ndef new_fitting():\r\n    fitting = dict(ID=None, type=None, IDup=None, BranchUP=None, IDdownMain=None, IDdownBranch=None, flow=None,\r\n                   flowMain=None, flowBranch=None, size=None, sizeMain=None, sizeBranch=None,\r\n                   pdrop=None, pdropMain=None, pdropBranch=None, length=None, fandist=None, diffuser_psum=None)\r\n    return fitting\r\n\r\n\r\ndef read_input_file(filename):\r\n    file = open(filename, 'r')\r\n    data = file.readlines()\r\n    file.close()\r\n    return data\r\n\r\n\r\ndef process_keywords(data):\r\n    ducts = new_duct_network()\r\n    for line in data:\r\n        line = line.lower()\r\n        if line.find('#') != -1:\r\n            continue  # comment line. not the lines we are looking for.\r\n        else:\r\n            item = [x.strip() for x in line.split(',')]\r\n            if item[0] == 'title':\r\n                ducts['title'] = item[1]\r\n            elif item[0] == 'fan_pressure':\r\n                ducts['fan_pressure'] = float(item[1])\r\n            elif item[0] == 'air_density':\r\n                ducts['air_density'] = float(item[1])\r\n            elif item[0] == 'roughness':\r\n                ducts['roughness'] = float(item[1])\r\n            elif item[0] == 'rounding':\r\n                ducts['rounding'] = item[1]\r\n            elif item[0] == 'fitting':  # initializing fittings information\r\n                fitting = new_fitting()\r\n                fitting['fandist'] = 0\r\n                fitting['ID'] = float(item[1])\r\n                fitting['type'] = item[2]\r\n                try:  # checking for air handeling units\r\n                    fitting['IDup'] = item[3]\r\n                except Exception:\r\n                    pass\r\n                if item[2] == 'duct':  # check for ducts. Ducts should have length feet\r\n                    fitting['length'] = float(item[4])\r\n                elif item[2] == 'diffuser':  # check for diffusers. Diffusers should have flowrate in CFM\r\n                    fitting['flow'] = float(item[4])\r\n                else:  # Everything not a duct or diffuser\r\n                    pass\r\n                ducts['fittings'].append(fitting)\r\n            else:\r\n                continue\r\n    return ducts\r\n\r\n\r\ndef find_fitting(ID, fittings):\r\n    for fitting in fittings:\r\n        if fitting['ID'] == ID:\r\n            return fitting\r\n\r\n\r\ndef make_connections(fittings):\r\n    # regex patterns for matching main and branch ID up text\r\n    main_pattern = re.compile(r'\\d+\\b-main\\b')\r\n    branch_pattern = re.compile(r'\\d+\\b-branch\\b')\r\n    for fitting in fittings:\r\n        if fitting['IDup'] is None:  # check for AHUs\r\n            continue\r\n        elif main_pattern.match(fitting['IDup']):  # main line from Tee\r\n            # Find index of hyphen when present\r\n            index_of_hyphen = fitting['IDup'].find('-')\r\n            tee_ID = int(fitting['IDup'][:index_of_hyphen])\r\n            tee_fitting = find_fitting(tee_ID, fittings)\r\n            tee_fitting['IDdownMain'] = fitting['ID']\r\n        elif branch_pattern.match(fitting['IDup']):  # branch from Tee\r\n            index_of_hyphen = fitting['IDup'].find('-')\r\n            tee_ID = int(fitting['IDup'][:index_of_hyphen])\r\n            tee_fitting = find_fitting(tee_ID, fittings)\r\n            tee_fitting['IDdownBranch'] = fitting['ID']\r\n        else:  # all other fittings\r\n            fittingUp = find_fitting(float(fitting['IDup']), fittings)\r\n            fittingUp['IDdownMain'] = fitting['ID']\r\n\r\n\r\ndef setup_fan_distances(fittings):\r\n    for fitting in fittings:\r\n        # check for AHU\r\n        if fitting['type'] == 'air_handling_unit':\r\n            fitting['fandist'] = 0\r\n        # fittingUp is a tee\r\n        elif fitting['IDup'].find('-') != -1:\r\n            index_of_hyphen = fitting['IDup'].find('-')\r\n            tee_ID = int(fitting['IDup'][:index_of_hyphen])\r\n            fittingUp = find_fitting(tee_ID, fittings)\r\n            fitting['fandist'] = fittingUp['fandist']\r\n        # fittings up is duct. Add length\r\n        elif find_fitting(int(fitting['IDup']), fittings)['type'] == 'duct':\r\n            fittingUp = find_fitting(int(fitting['IDup']), fittings)\r\n            fitting['fandist'] = fittingUp['fandist'] + fittingUp['length']\r\n        # all the elbow, tee, and duct fittings\r\n        else:\r\n            fittingUp = find_fitting(int(fitting['IDup']), fittings)\r\n            fitting['fandist'] = fittingUp['fandist']\r\n\r\n\r\ndef setup_flowrates(fittings):  # Iterates, takes flow from duct downstream and makes it the flow of the fitting\r\n    for i in range(1000):  # Iterations\r\n        for fitting in fittings:\r\n            if fitting['IDdownBranch'] is None and fitting['IDdownMain'] is not None:  # Straightaways\r\n                MainDown = find_fitting(fitting['IDdownMain'], fittings)\r\n                flow = MainDown['flow']\r\n                if flow is None:  # Avoids errors\r\n                    continue\r\n                fitting['flow'] = flow  # Sets flowrate to singular downstream piece\r\n            elif fitting['IDdownMain'] is None:  # Diffusers\r\n                continue\r\n            elif fitting['IDdownBranch'] is not None and fitting['IDdownMain'] is not None:  # Tee's\r\n                MainDown = find_fitting(fitting['IDdownMain'], fittings)\r\n                flow = MainDown['flow']  # Sets partial flow to main downstream piece\r\n                if flow is None:  # Avoids errors\r\n                    continue\r\n                BranchDown = find_fitting(fitting['IDdownBranch'], fittings)\r\n                if BranchDown['flow'] is None:  # Avoids errors\r\n                    continue\r\n                flow = BranchDown['flow'] + flow  # Adds branch flow to mainflow\r\n                fitting['flow'] = flow  # Sets flow for fitting\r\n            else:\r\n                print(\"There was an error in the flow rate.\")  # Error message, just in case\r\n\r\n\r\ndef get_little_f(dia, velocity, roughness):\r\n    def func(vals):\r\n        f = vals\r\n        Re = 8.5 * (dia / 12) * velocity  # eqn (21)\r\n\r\n        # eqn (19) 2013 version corrected for units\r\n        left_side = 1 / np.sqrt(f)\r\n        right_right = (-1) * 2 * np.log10((roughness / (3.7 * (dia / 12))) + (2.51 / (Re * np.sqrt(f))))\r\n        return (right_right - left_side)\r\n\r\n    guess = 10\r\n    finished = False\r\n    while not finished:\r\n        f = fsolve(func, guess, full_output=True)\r\n        if int(f[2]) == 1:  # check solution flag\r\n            finished = True\r\n        else:\r\n            guess = guess / 2.0  # update guess\r\n    return f[0][0]\r\n\r\n\r\ndef largest_path(fittings):  # Finds the diffuser with the longest path to the fan\r\n    fitting_compare = find_fitting(1, fittings)  # Sets the initial fitting that will be compared\r\n    for fitting in fittings:\r\n        if fitting['type'] == 'diffuser':\r\n            if fitting['fandist'] > fitting_compare['fandist']:  # compare fan distances\r\n                fitting_compare = fitting  # sets new comparison\r\n    return fitting_compare\r\n\r\n\r\ndef duct_pressure_drop(dia, flow, length, density, roughness):  # dia [inches], length [ft]\r\n    area = (np.pi * (dia / 12) ** 2) / 4  # [ft^2]\r\n    velocity = flow / area  # [ft/min=fpm]\r\n    f = get_little_f(dia, velocity, roughness)\r\n    pdrop = ((12 * f * length) / (dia / 12)) * density * (velocity / 1097) ** 2\r\n    return pdrop\r\n\r\n\r\n# Nick and Charlie\r\ndef pressure_drop_sum(ID, fittings):  # calculates total pressure loss of ANY RUN\r\n    # find the fitting dictionary attached to the ID in quesiton\r\n    fitting = find_fitting(int(ID), fittings)\r\n    route = [int(fitting['ID'])]\r\n    main_pattern = re.compile(r'\\d+\\b-main\\b')\r\n    branch_pattern = re.compile(r'\\d+\\b-branch\\b')\r\n\r\n    # find route IDs\r\n    while fitting['type'] != 'air_handling_unit':  # while not at the air handler\r\n        if main_pattern.match(fitting['IDup']):  # matching main if IDup is tee\r\n            index_of_hyphen = fitting['IDup'].find('-')\r\n            ID = int(fitting['IDup'][:index_of_hyphen])\r\n            route.append(ID)\r\n            fitting = find_fitting(ID, fittings)\r\n        elif branch_pattern.match(fitting['IDup']):  # matching branch if IDup is tee\r\n            index_of_hyphen = fitting['IDup'].find('-')\r\n            ID = int(fitting['IDup'][:index_of_hyphen])\r\n            route.append(ID)\r\n            fitting = find_fitting(ID, fittings)\r\n        else:\r\n            ID = int(fitting['IDup'])\r\n            route.append(ID)\r\n            fitting = find_fitting(ID, fittings)\r\n\r\n    pdrop_sum = 0\r\n    for i in range(len(route)):\r\n        fitting = find_fitting(int(route[i]), fittings)\r\n        if fitting['type'] == 'duct' or fitting['type'] == 'elbow':\r\n            pdrop_sum += fitting['pdrop']\r\n        elif fitting['type'] == 'tee':\r\n            # next downstream fitting ID\r\n            next_fitting_ID = route[i - 1]\r\n            if next_fitting_ID == fitting['IDdownMain']:\r\n                pdrop_sum += find_fitting(int(next_fitting_ID), fittings)['pdropMain']\r\n            elif next_fitting_ID == fitting['IDdownBranch']:\r\n                pdrop_sum += find_fitting(int(next_fitting_ID), fittings)['pdropBranch']\r\n    return pdrop_sum\r\n\r\n\r\ndef fitting_loss_sum(fittings):  # calculates total pressure loss of tees and elbows only, of LONGEST RUN\r\n    farthest_fitting = largest_path(fittings)\r\n    fitting = farthest_fitting\r\n    longest_route = [int(fitting['ID'])]\r\n    main_pattern = re.compile(r'\\d+\\b-main\\b')\r\n    branch_pattern = re.compile(r'\\d+\\b-branch\\b')\r\n\r\n    # find longest route using farthest diffusers\r\n    while fitting['type'] != 'air_handling_unit':  # while not at the air handler\r\n        if main_pattern.match(fitting['IDup']):  # matching main if IDup is tee\r\n            index_of_hyphen = fitting['IDup'].find('-')\r\n            ID = int(fitting['IDup'][:index_of_hyphen])\r\n            longest_route.append(ID)\r\n            fitting = find_fitting(ID, fittings)\r\n        elif branch_pattern.match(fitting['IDup']):  # matching branch if IDup is tee\r\n            index_of_hyphen = fitting['IDup'].find('-')\r\n            ID = int(fitting['IDup'][:index_of_hyphen])\r\n            longest_route.append(ID)\r\n            fitting = find_fitting(ID, fittings)\r\n        else:\r\n            ID = int(fitting['IDup'])\r\n            longest_route.append(ID)\r\n            fitting = find_fitting(ID, fittings)\r\n\r\n    pdrop_fitloss_sum = 0\r\n    for i in range(len(longest_route)):\r\n        fitting = find_fitting(int(longest_route[i]), fittings)\r\n        if fitting['type'] == 'elbow':\r\n            pdrop_fitloss_sum += fitting['pdrop']\r\n        elif fitting['type'] == 'tee':\r\n            # next downstream fitting ID\r\n            next_fitting_ID = longest_route[i - 1]\r\n            if next_fitting_ID == fitting['IDdownMain']:\r\n                pdrop_fitloss_sum += find_fitting(int(next_fitting_ID), fittings)['pdropMain']\r\n            elif next_fitting_ID == fitting['IDdownBranch']:\r\n                pdrop_fitloss_sum += find_fitting(int(next_fitting_ID), fittings)['pdropBranch']\r\n    return pdrop_fitloss_sum\r\n\r\n\r\ndef get_duct_size(deltap, flow, length, density, roughness):\r\n    def func(vals):\r\n        dia = vals\r\n        return deltap - duct_pressure_drop(dia, flow, length, density, roughness)\r\n\r\n    finished = False\r\n    guess = .01\r\n    while not finished:\r\n        # print(guess)\r\n        f = fsolve(func, guess, full_output=True)\r\n        if int(f[2]) == 1:\r\n            finished = True\r\n        else:\r\n            guess = guess * 2.0\r\n    diameter = f[0][0]\r\n    return diameter\r\n\r\n\r\ndef findBetween(x, xlist):\r\n    # iterate over xlist to find where x fits in\r\n    for position in range(0, len(xlist) - 1):\r\n        # check if the current iteration in xlist is good\r\n        if (xlist[position] <= x <= xlist[position + 1]) or (xlist[position] >= x >= xlist[position + 1]):\r\n            return position\r\n\r\n\r\ndef interp1D(x, xlist, ylist):\r\n    # find between value\r\n    position = findBetween(x, xlist)\r\n\r\n    # gather needed numbers from xlist and ylist\r\n    x1 = xlist[position]\r\n    x3 = xlist[position + 1]\r\n    y1 = ylist[position]\r\n    y3 = ylist[position + 1]\r\n\r\n    # interpolate value of y\r\n    y = (((x - x1) * (y3 - y1)) / (x3 - x1)) + y1\r\n    return y\r\n\r\n\r\ndef interp2D(x, y, xlist, ylist, zmatrix):\r\n    # find the correct column to use\r\n    yposition = findBetween(y, ylist)\r\n\r\n    # extract and interpolate each column\r\n    x1 = interp1D(x, xlist, zmatrix[:, yposition])\r\n    x2 = interp1D(x, xlist, zmatrix[:, yposition + 1])\r\n\r\n    # interpolate between columns\r\n    z = interp1D(y, ylist[yposition:yposition + 2], [x1, x2])\r\n    return z\r\n\r\n\r\ndef tee_pressure_drop(dia, density, flow, outlet_flow, outlet_dia, branch):\r\n    '''\r\n\r\n    :param dia:\r\n    :param density:\r\n    :param flow:\r\n    :param outlet_flow:\r\n    :param outlet_dia:\r\n    :param branch: Boolean\r\n    :return:\r\n    '''\r\n    Q = np.array([.1, .2, .3, .4, .5, .6, .7, .8, .9])  # top most row Q_(branch/main)/Q_common\r\n    A = np.array([.1, .2, .3, .4, .5, .6, .7, .8, .9])  # right most column A_(branch/main)/A_common\r\n\r\n    # Table from 2009 ASHRAE Handbook 21.50 for SD5-10 Tee, Concial Branch Tapered into Body, Diverging\r\n    # c_branch values\r\n    sd5cb = np.array([[0.65, 0.24, 0.15, 0.11, 0.09, 0.07, 0.06, 0.05, 0.05],\r\n                      [2.98, 0.65, 0.33, 0.24, 0.18, 0.15, 0.13, 0.11, 0.10],\r\n                      [7.36, 1.56, 0.65, 0.39, 0.29, 0.24, 0.20, 0.17, 0.15],\r\n                      [13.78, 2.98, 1.20, 0.65, 0.43, 0.33, 0.27, 0.24, 0.21],\r\n                      [22.24, 4.92, 1.98, 1.04, 0.65, 0.47, 0.36, 0.30, 0.26],\r\n                      [32.73, 7.36, 2.98, 1.56, 0.96, 0.65, 0.49, 0.39, 0.33],\r\n                      [45.26, 10.32, 4.21, 2.21, 1.34, 0.90, 0.65, 0.51, 0.42],\r\n                      [59.82, 13.78, 5.67, 2.98, 1.80, 1.20, 0.86, 0.65, 0.52],\r\n                      [76.41, 17.75, 7.36, 3.88, 2.35, 1.56, 1.11, 0.83, 0.65]])\r\n    # c_main values\r\n    sd5cm = np.array([[0.13, 0.16, 0.57, 0.74, 0.74, 0.70, 0.65, 0.60, 0.56],\r\n                      [0.20, 0.13, 0.15, 0.16, 0.28, 0.57, 0.69, 0.74, 0.75],\r\n                      [0.90, 0.13, 0.13, 0.14, 0.15, 0.16, 0.20, 0.42, 0.57],\r\n                      [2.88, 0.20, 0.14, 0.13, 0.14, 0.15, 0.15, 0.16, 0.34],\r\n                      [6.25, 0.37, 0.17, 0.14, 0.13, 0.14, 0.14, 0.15, 0.15],\r\n                      [11.88, 0.90, 0.20, 0.13, 0.14, 0.13, 0.14, 0.14, 0.15],\r\n                      [18.62, 1.71, 0.33, 0.18, 0.16, 0.14, 0.13, 0.15, 0.14],\r\n                      [26.88, 2.88, 0.50, 0.20, 0.15, 0.14, 0.13, 0.13, 0.14],\r\n                      [36.45, 4.46, 0.90, 0.30, 0.19, 0.16, 0.15, 0.14, 0.13]])\r\n    area = (np.pi * (dia / 12) ** 2) / 4\r\n    velocity = flow / area\r\n    p_v = density * (velocity / 1097) ** 2\r\n    A_common = (np.pi * (dia / 12) ** 2) / 4\r\n    A_outlet = (np.pi * (outlet_dia / 12) ** 2) / 4\r\n    area_ratio = A_outlet / A_common\r\n    flow_ratio = outlet_flow / flow\r\n\r\n    # protect from extrapolating on the table\r\n    if area_ratio > .9:\r\n        area_ratio = .9\r\n    elif area_ratio < .1:\r\n        area_ratio = .1\r\n    if flow_ratio > .9:\r\n        flow_ratio = .9\r\n    elif flow_ratio < .1:\r\n        flow_ratio = .1\r\n    if branch:\r\n        c_branch = interp2D(area_ratio, flow_ratio, A, Q, sd5cb)\r\n        pdrop = c_branch * p_v\r\n    else:\r\n        c_main = interp2D(area_ratio, flow_ratio, A, Q, sd5cm)\r\n        pdrop = c_main * p_v\r\n    return pdrop\r\n\r\n\r\ndef elbow_pressure_drop(dia, flow, density):\r\n    # Table from ASHRAE 2009 chapter 21 for pleated 90 degree elbow\r\n    D = np.array([4, 6, 8, 10, 12, 14, 16])\r\n    Co = np.array([0.57, 0.43, 0.34, 0.28, 0.26, 0.25, 0.25])\r\n\r\n    # protect from extrapolating on the table\r\n    if dia >= 16:\r\n        c_o = 0.25\r\n    elif dia <= 4:\r\n        c_o = 0.57\r\n    else:\r\n        c_o = interp1D(dia, D, Co)\r\n\r\n    area = (np.pi * (dia / 12) ** 2) / 4\r\n    velocity = flow / area\r\n    p_v = density * (velocity / 1097) ** 2\r\n    pdrop = c_o * p_v\r\n    return pdrop\r\n\r\n\r\n# Nick Nelsen 5/4/17\r\ndef sizing_iterate_nick(ducts):\r\n    # assign for easier use later\r\n    density = ducts['air_density']\r\n    roughness = ducts['roughness']\r\n    fan_pressure = ducts['fan_pressure']\r\n    fittings = ducts['fittings']\r\n    maxlength = largest_path(fittings)['fandist']\r\n\r\n    # take care of nonetype errors the cheesy way\r\n    for fitting in fittings:\r\n        if fitting['pdrop'] is None:\r\n            fitting['pdrop'] = 0.0\r\n        if fitting['pdropMain'] is None:\r\n            fitting['pdropMain'] = 0.0\r\n        if fitting['pdropBranch'] is None:\r\n            fitting['pdropBranch'] = 0.0\r\n\r\n    psum = fitting_loss_sum(fittings)\r\n    dpdl = (fan_pressure - psum) / maxlength\r\n    dpdl_old = 0\r\n    count = 0\r\n    # main loop to size ducts first, then elbows, and finally tees\r\n    while abs(dpdl - dpdl_old) >= 1e-10:\r\n        for fitting in fittings:  # solving ducts\r\n            if fitting['type'] == 'duct':\r\n                length = fitting['length']\r\n                deltap = dpdl * length\r\n                flow = fitting['flow']\r\n                diameter = get_duct_size(deltap, flow, length, density, roughness)\r\n                fitting['size'] = diameter\r\n                # p_duct = duct_pressure_drop(diameter, flow, length, density, roughness)\r\n                p_duct = deltap\r\n                # print(p_duct, p_duct2)\r\n                fitting['pdrop'] = p_duct\r\n\r\n        for fitting in fittings:  # solving elbows\r\n            if fitting['type'] == 'elbow':\r\n                down_fitting = find_fitting(int(fitting['IDdownMain']), fittings)\r\n                if down_fitting['type'] == 'duct':\r\n                    e_diameter = down_fitting['size']\r\n                    p_elbow = elbow_pressure_drop(e_diameter, fitting['flow'], density)\r\n                    fitting['size'] = e_diameter\r\n                    fitting['pdrop'] = p_elbow\r\n\r\n                # if up_fitting is a tee\r\n                elif fitting['IDup'].find('-') != -1:\r\n                    index_of_hyphen = fitting['IDup'].find('-')\r\n                    tee_ID = int(fitting['IDup'][:index_of_hyphen])\r\n                    up_fitting = find_fitting(tee_ID, fittings)\r\n                    e_diameter = up_fitting['size']\r\n                    p_elbow = elbow_pressure_drop(e_diameter, fitting['flow'], density)\r\n                    fitting['size'] = e_diameter\r\n                    fitting['pdrop'] = p_elbow\r\n                # if up_fitting has no hyphen\r\n                else:\r\n                    up_fitting = find_fitting(int(fitting['IDup']), fittings)\r\n                    # if up_fitting['size'] is not None:\r\n                    e_diameter = up_fitting['size']\r\n                    p_elbow = elbow_pressure_drop(e_diameter, fitting['flow'], density)\r\n                    fitting['size'] = e_diameter\r\n                    fitting['pdrop'] = p_elbow\r\n\r\n        for fitting in fittings:  # solving tees\r\n            if fitting['type'] == 'tee':\r\n                up_fitting = find_fitting(int(fitting['IDup']), fittings)\r\n                tee_inlet_diameter = up_fitting['size']\r\n                p_tee_main = tee_pressure_drop(tee_inlet_diameter, density, fitting['flow'],\r\n                                               find_fitting(fitting['IDdownMain'], fittings)['flow'],\r\n                                               find_fitting(fitting['IDdownMain'], fittings)['size'], False)\r\n                p_tee_branch = tee_pressure_drop(tee_inlet_diameter, density, fitting['flow'],\r\n                                                 find_fitting(fitting['IDdownBranch'], fittings)['flow'],\r\n                                                 find_fitting(fitting['IDdownBranch'], fittings)['size'], True)\r\n                fitting['size'] = tee_inlet_diameter\r\n                fitting['sizeMain'] = find_fitting(fitting['IDdownMain'], fittings)['size']\r\n                fitting['sizeBranch'] = find_fitting(fitting['IDdownBranch'], fittings)['size']\r\n                fitting['pdropMain'] = p_tee_main\r\n                fitting['pdropBranch'] = p_tee_branch\r\n\r\n        psum = fitting_loss_sum(fittings)\r\n        dpdl_old = dpdl\r\n        dpdl = (fan_pressure - psum) / maxlength\r\n\r\n    for fitting in fittings:\r\n        if fitting['type'] == 'diffuser':\r\n            fitting['diffuser_psum'] = pressure_drop_sum(int(fitting['ID']), fittings)\r\n\r\n    # rounding stuff\r\n    if ducts['rounding'] is not None:\r\n        if ducts['rounding'] == 'nearest':\r\n            for fitting in fittings:\r\n                if fitting['type'] != 'air_handling_unit' and fitting['type'] != 'diffuser':\r\n                    fitting['size'] = round(fitting['size'])\r\n                    if fitting['type'] == 'tee':\r\n                        fitting['sizeMain'] = round(fitting['sizeMain'])\r\n                        fitting['sizeBranch'] = round(fitting['sizeBranch'])\r\n        elif ducts['rounding'] == 'up':\r\n            for fitting in fittings:\r\n                if fitting['type'] != 'air_handling_unit' and fitting['type'] != 'diffuser':\r\n                    fitting['size'] = np.ceil(fitting['size'])\r\n                    if fitting['type'] == 'tee':\r\n                        fitting['sizeMain'] = np.ceil(fitting['sizeMain'])\r\n                        fitting['sizeBranch'] = np.ceil(fitting['sizeBranch'])\r\n        elif ducts['rounding'] == 'down':\r\n            for fitting in fittings:\r\n                if fitting['type'] != 'air_handling_unit' and fitting['type'] != 'diffuser':\r\n                    fitting['size'] = np.floor(fitting['size'])\r\n                    if fitting['type'] == 'tee':\r\n                        fitting['sizeMain'] = np.floor(fitting['sizeMain'])\r\n                        fitting['sizeBranch'] = np.floor(fitting['sizeBranch'])\r\n\r\n        # recalculate pdrop everything after rounding\r\n        for fitting in fittings:\r\n            if fitting['type'] == 'duct':\r\n                fitting['pdrop'] = duct_pressure_drop(fitting['size'], fitting['flow'], fitting['length'], density,\r\n                                                      roughness)\r\n            elif fitting['type'] == 'tee':\r\n                fitting['flowMain'] = find_fitting(int(fitting['IDdownMain']), fittings)['flow']\r\n                fitting['pdropMain'] = tee_pressure_drop(fitting['size'], density, fitting['flow'], fitting['flowMain'],\r\n                                                         fitting['sizeMain'], False)\r\n                fitting['flowBranch'] = find_fitting(int(fitting['IDdownBranch']), fittings)['flow']\r\n                fitting['pdropBranch'] = tee_pressure_drop(fitting['size'], density, fitting['flow'],\r\n                                                           fitting['flowBranch'], fitting['sizeBranch'], True)\r\n            elif fitting['type'] == 'elbow':\r\n                fitting['pdrop'] = elbow_pressure_drop(fitting['size'], fitting['flow'], density)\r\n\r\n    # finally apply sizes to diffuers\r\n    for fitting in fittings:\r\n        if fitting['type'] == 'diffuser':\r\n            fitting['size'] = find_fitting(int(fitting['IDup']), fittings)['size']\r\n\r\n    return\r\n\r\n\r\ndef print_results(fittings):\r\n    # file=open(\"pyductresults.txt\",\"w\")\r\n    print('ID'.rjust(4), 'Fitting'.rjust(20), 'Velocity (fpm)'.rjust(15), 'Q (cfm)'.rjust(15), 'DeltaP (in. wg)'.rjust(16),\r\n          'Diameter (in)'.rjust(17), 'Diffuser pressure (in. wg)'.rjust(25))\r\n    print('-'*120)\r\n    orig_stdout = sys.stdout\r\n    file = open(\"pyductresult.txt\", \"w+\")\r\n    sys.stdout = file\r\n    print('ID'.rjust(4), 'Fitting'.rjust(20), 'Velocity (fpm)'.rjust(15), 'Q (cfm)'.rjust(15), 'DeltaP (in. wg)'.rjust(16),\r\n          'Diameter (in)'.rjust(17), 'Diffuser pressure (in. wg)'.rjust(25))\r\n    print('-'*120)\r\n    sys.stdout = orig_stdout\r\n    for fitting in fittings:\r\n        if fitting['type'] != 'air_handling_unit':\r\n            # TODO: @sziske needs to fix this\r\n            # velocity = 5\r\n            velocity = fitting['flow'] / (np.pi * (fitting['size'] / 12) * (fitting['size'] / 12))\r\n        else:\r\n            velocity = 0.0\r\n            fitting['size'] = 0.0\r\n        if fitting['pdrop'] is None:\r\n            fitting['pdrop'] = 0.0\r\n        if fitting['size'] is None:\r\n            fitting['size'] = 0.0\r\n        if fitting['diffuser_psum'] is None:\r\n            print(repr(fitting['ID']).rjust(4), fitting['type'].rjust(20), (\"%.3f\" % velocity).rjust(15),\r\n                  (\"%.1f\" % fitting['flow']).rjust(15), (\"%.3f\" % fitting['pdrop']).rjust(16),\r\n                  (\"%.3f\" % fitting['size']).rjust(17))\r\n            orig_stdout = sys.stdout\r\n            sys.stdout = file\r\n            print(repr(fitting['ID']).rjust(4), fitting['type'].rjust(20), (\"%.3f\" % velocity).rjust(15),\r\n                  (\"%.1f\" % fitting['flow']).rjust(15), (\"%.3f\" % fitting['pdrop']).rjust(16),\r\n                  (\"%.3f\" % fitting['size']).rjust(17))\r\n            sys.stdout = orig_stdout\r\n        else:\r\n            print(repr(fitting['ID']).rjust(4), fitting['type'].rjust(20), (\"%.3f\" % velocity).rjust(15),\r\n                  (\"%.1f\" % fitting['flow']).rjust(15), (\"%.3f\" % fitting['pdrop']).rjust(16),\r\n                  (\"%.3f\" % fitting['size']).rjust(17), (\"%.3f\" % fitting['diffuser_psum']).rjust(25))\r\n            orig_stdout = sys.stdout\r\n            sys.stdout = file\r\n            print(repr(fitting['ID']).rjust(4), fitting['type'].rjust(20), (\"%.3f\" % velocity).rjust(15),\r\n                  (\"%.1f\" % fitting['flow']).rjust(15), (\"%.3f\" % fitting['pdrop']).rjust(16),\r\n                (\"%.3f\" % fitting['size']).rjust(17), (\"%.3f\" % fitting['diffuser_psum']).rjust(25))\r\n            sys.stdout = orig_stdout\r\n\r\n    file.close()\r\n\r\n\r\ndef print_fitting(f):\r\n    print(' ', int(f['ID']), ' ', end='')\r\n    print(f['type'], ' ', end='')\r\n    if f['IDup'] is not None:\r\n        print('connects to: ', f['IDup'], end='')\r\n    if f['BranchUP'] is not None:\r\n        print('-', f['branchUp'])\r\n    else:\r\n        print('\\n', end='')\r\n    if f['length'] is not None:\r\n        print('    length: ', f['length'])\r\n    if f['IDdownMain'] is not None:\r\n        print('    IDdownMain: ', int(f['IDdownMain']))\r\n    if f['IDdownBranch'] is not None:\r\n        print('    IDdownBranch', int(f['IDdownBranch']))\r\n    if f['flow'] is not None:\r\n        print('    flow: ', f['flow'])\r\n    if f['fandist'] is not None:\r\n        print('    fandist: ', f['fandist'])\r\n    if f['size'] is not None:\r\n        print('    size: ', f['size'])\r\n    if f['pdrop'] is not None:\r\n        print('    pdrop: ', f['pdrop'])\r\n    if f['pdropMain'] is not None:\r\n        print('    pdropMain: ', f['pdropMain'])\r\n    if f['pdropBranch'] is not None:\r\n        print('    pdropBranch: ', f['pdropBranch'])\r\n    if f['diffuser_psum'] is not None:\r\n        print('    diffuser_psum: ', f['diffuser_psum'])\r\n\r\n\r\ndef print_summary(ducts):\r\n    print('title: ', ducts['title'])\r\n    print('fan_pressure: ', ducts['fan_pressure'])\r\n    print('air_density: ', ducts['air_density'])\r\n    print('roughness: ', ducts['roughness'])\r\n    print('rounding: ', ducts['rounding'])\r\n    fittings = ducts['fittings']\r\n    for f in fittings:\r\n        print_fitting(f)\r\n\r\n\r\ndef calculate(filename):\r\n    file_data = read_input_file(filename)\r\n    ducts = process_keywords(file_data)\r\n    fittings = ducts['fittings']\r\n    make_connections(fittings)\r\n    setup_flowrates(fittings)\r\n    setup_fan_distances(fittings)\r\n    sizing_iterate_nick(ducts)\r\n    print_results(fittings)\r\n\r\n\r\nif __name__ == '__main__':\r\n    # filename = 'Duct Design Sample Input.txt'\r\n    # calculate(filename)\r\n    print('Please run from main.py')\r\n", "meta": {"hexsha": "22fcbd759cc15db46b9050225013518d692150ad", "size": 27878, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyduct.py", "max_stars_repo_name": "cpjohns/pyduct", "max_stars_repo_head_hexsha": "67ef2e06c16a2ca7c2b032ec8c908bf8898437dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyduct.py", "max_issues_repo_name": "cpjohns/pyduct", "max_issues_repo_head_hexsha": "67ef2e06c16a2ca7c2b032ec8c908bf8898437dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyduct.py", "max_forks_repo_name": "cpjohns/pyduct", "max_forks_repo_head_hexsha": "67ef2e06c16a2ca7c2b032ec8c908bf8898437dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.8333333333, "max_line_length": 124, "alphanum_fraction": 0.5417174833, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.170423285625548}}
{"text": "# -*- coding:utf-8 -*-\n'''\n主要功能：建立算法库，主要是储存与时间序列曲线匹配的算法程序\n@ author: zhyin\n@ time: 2019/09/20\n'''\n\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\n\n### -*-LC8相关-*- ###\n\ndef dn_to_ref(values):\n    '''\n    完成DN值到反射率值的转化\n    :param values: DN值 values\n    :return: 反射率值 values\n    '''\n    values = np.array(values).astype(float)\n    #\n    multiple_reflectence = 2e-5\n    add_reflectance = -0.1\n    values[:, 1:] = values[:, 1:] * multiple_reflectence + add_reflectance\n    values = values.tolist()\n    #\n    return values\n\n#\n# ANN\nclass bpNet(object):\n    def __init__(self, BpInNode, BpHideNode, BpOutNode, imgNum=1, Greedy=False):\n        #\n        self.ih_w = np.zeros([BpInNode, BpHideNode])  # 隐含层结点权值\n        self.ho_w = np.zeros([BpHideNode, BpOutNode])  # 输出层结点权值\n        self.hide_b0 = np.zeros([BpHideNode])  # 隐含层结点阈值\n        self.out_b0 = np.zeros([BpOutNode])  # 输出层结点阈值\n        self.in_x0 = np.zeros([BpInNode])  # 输入向量值\n        self.hide_s0 = np.zeros([BpHideNode])  # 隐含层结点值\n        self.out_y0 = np.zeros([BpOutNode])  # 输出层结点值【预测值】\n        self.outErr = np.zeros([BpOutNode])\n        self.hideErr = np.zeros([BpHideNode])\n        #\n        self.rate_ih_w = 0.1  # 权值学习率（输入层->隐含层）\n        self.rate_ho_w = 0.1  # 权值学习率（隐含层->输出层）\n        self.rate_Hide_b0 = 0.1  # 阈值学习率（隐含层）\n        self.rate_Out_b0 = 0.1  # 阈值学习率（输出层）\n        self.totalErr = 1.0  # 允许的总误差\n        #\n        self.bpInNode = BpInNode  # 输入层结点数\n        self.bpHideNode = BpHideNode  # 隐藏层结点数\n        self.bpOutNode = BpOutNode  # 输出层结点数\n        #\n        if Greedy is False:\n            self.out_yd = np.zeros([BpOutNode])  # 真值\n        else:\n            self.out_yd = np.zeros([imgNum, BpOutNode])\n\n    def genc_randVal(self, low, high):  # 生成[low,high]之间的随机数\n        import random\n        var = random.random() * (high - low) + low\n        return var\n\n    def sigmoidFunc(self, t0):  # 激励函数\n        m0 = math.exp(-t0)\n        h0 = 1.0 / (1.0 + m0)\n        return h0\n\n    def winit(self, weight,dimension):\n        if dimension == 1:\n            for i in range(np.shape(weight)[0]):\n                weight[i] = self.genc_randVal(-0.01, 0.01)\n        if dimension == 2:\n            for i in range(np.shape(weight)[0]):\n                for j in range(np.shape(weight)[1]):\n                    weight[i, j] = self.genc_randVal(-0.01, 0.01)\n\n    def bpInitNetFunc(self):\n        self.winit(self.ih_w,2)\n        self.winit(self.ho_w,2)\n        self.winit(self.hide_b0,1)\n        self.winit(self.out_b0,1)\n\n    def bpNetTrainFunc(self, InSam, OutSam, imgNum=1, Greedy=False,Ver=1):\n        '''\n        训练样本\n        :param InSam: [8000]一维数组\n        :param OutSam: [8000,1]二维数组\n        '''\n        #\n        InSam = np.array(InSam).astype(float)\n        OutSam = np.array(OutSam).astype(float)\n        trainSample = np.shape(InSam)[0]\n        self.totalErr = 0  # 总的误差\n        sum = 0  # 和\n        z0 = 0  # 激活值\n        #\n        for isamp in range(trainSample):\n            #\n            # 输入层 eg:[8000] or [8000,bpInNode]\n            if self.bpInNode == 1:\n                self.in_x0[0] = InSam[isamp]\n            else:\n                self.in_x0 = InSam[isamp, :]  # 输入的样本值\n            #\n            # 输出层\n            if Greedy is True and Ver == 1:  # 贪婪算法中输出值 eg[imgNum,isamp] or [imgNum,isamp,bpOutNode]\n                if self.bpOutNode == 1:\n                    self.out_yd[:,0] = OutSam[:, isamp]\n                else:\n                    self.out_yd = OutSam[:, isamp, :]  # 期待输出的样本值\n            if Greedy is False and Ver == 1:\n                if self.bpOutNode == 1:\n                    self.out_yd[0] = OutSam[isamp]\n                else:\n                    self.out_yd = OutSam[isamp, :]  # 期待输出的样本值\n            #\n            if Greedy is False and Ver ==2:    # Ver2.0版本中真值有所变化:[bpOutNode,isamp]\n                self.out_yd = OutSam[:,isamp]  # 期待输出的样本值\n            #\n            # 正向传播的过程\n            # 1）输入层->隐含层1\n            for j in range(self.bpHideNode):\n                sum = 0.0\n                for i in range(self.bpInNode):\n                    sum += self.ih_w[i, j] * self.in_x0[i]\n                z0 = sum + self.hide_b0[j]\n                self.hide_s0[j] = self.sigmoidFunc(z0)  # 隐含层各个单元的输出 1.0/( 1.0 + exp(-z0))\n            #\n            # 2) 隐含层->输出层\n            for j in range(self.bpOutNode):\n                sum = 0.0\n                for i in range(self.bpHideNode):\n                    sum += self.ho_w[i, j] * self.hide_s0[i]\n                z0 = sum + self.out_b0[j]\n                self.out_y0[j] = self.sigmoidFunc(z0)  # 输出层各个单元的输出 1.0/(1.0 + exp(-z0)\n            #\n            # 误差反向传播：对于网络中每个输出单元，计算误差值，更新权值\n            # 1）输出层->隐含层\n            sum = 0.0\n            # 计算总均方差\n            for j in range(self.bpOutNode):\n                #\n                # 引入贪婪算法，则此处需要修改\n                if Greedy is False:\n                    z0 = self.out_yd[j] - self.out_y0[j]\n                    self.outErr[j] = z0\n                    sum += z0 * z0\n                if Greedy is True and Ver == 1:\n                    h = 0.0\n                    sum = 0.0\n                    for m in range(imgNum):\n                        h += self.out_yd[m,j] - self.out_y0    # 理论上进行求导\n                        sum += (self.out_yd[m,j] - self.out_y0) * (self.out_yd[m,j] - self.out_y0)\n                    z0 = h\n                    self.outErr[j] = z0\n            #\n            self.totalErr += sum / 2.0\n            #\n            for j in range(self.bpOutNode):\n                self.outErr[j] = self.outErr[j] * \\\n                                 self.out_y0[j] * (1.0 - self.out_y0[j])  # 输出层δ2 = ei * θ'(si2)  期望误差*输出层Outy0激励函数导数\n                for i in range(self.bpHideNode):\n                    self.ho_w[i,j] += self.rate_ho_w * self.outErr[j] * self.hide_s0[i]      # 更新权重\n            for j in range(self.bpOutNode):\n                self.out_b0[j] += self.rate_Out_b0 * self.outErr[j]     # 更新阈值\n            #\n            # 2) 隐含层->输入层\n            for j in range(self.bpHideNode):\n                sum = 0.0\n                for i in range(self.bpOutNode):\n                    sum += self.outErr[i] * self.ho_w[j,i]\n                self.hideErr[j] = sum * self.hide_s0[j] * (1. - self.hide_s0[j]) #隐含层δ1 = （∑out_Er *ho_w） * θ'(si2)  隐含层误差*隐含层Hides0激励函数导数\n                for i in range(self.bpInNode):\n                    self.ih_w[i,j] += self.rate_ih_w * self.hideErr[j] * self.in_x0[i]  # 更新权重\n            for j in range(self.bpHideNode):\n                self.hide_b0[j] += self.rate_Hide_b0 * self.hideErr[j]  # 更新阈值\n\n    def bpNetRecognizeFunc(self,testSam):\n        '''\n        BP神经网络测试样本\n        :param testSam: 测试样本\n        :return:\n        '''\n        testSam = np.array(testSam).astype(float)\n        # self.totalErr = 0  # 单个样本的误差\n        #\n        # 输入层 eg:[8000] or [8000,bpInNode]\n        if self.bpInNode == 1:\n            self.in_x0[0] = testSam\n        else:\n            self.in_x0 = testSam  # 输入的样本值\n        #\n        # 输入->隐含层\n        for j in range(self.bpHideNode):\n            sum = 0.0\n            for i in range(self.bpInNode):\n                sum += self.ih_w[i, j] * self.in_x0[i]\n            z0 = sum + self.hide_b0[j]\n            self.hide_s0[j] = self.sigmoidFunc(z0)  # 隐含层各个单元的输出 1.0/( 1.0 + exp(-z0))\n        #\n        # 2) 隐含层->输出层\n        for j in range(self.bpOutNode):\n            sum = 0.0\n            for i in range(self.bpHideNode):\n                sum += self.ho_w[i, j] * self.hide_s0[i]\n            z0 = sum + self.out_b0[j]\n            self.out_y0[j] = self.sigmoidFunc(z0)  # 输出层各个单元的输出 1.0/(1.0 + exp(-z0)\n        #\n    pass\n\n#\n# demo测试\nif __name__ == \"__main__\":\n    file = open('./txt/bpTest.txt','w')\n    err = []\n    err_time = []\n    m_Insample = [[1.78, 1.14], [1.96, 1.18], [1.86, 1.20], [1.72, 1.24], [2.00, 1.26], [2.00, 1.28], [1.96, 1.30],\n                  [1.74, 1.36], [1.64, 1.38], [1.82, 1.38], [1.90, 1.38], [1.70, 1.40], [1.82, 1.48], [1.82, 1.54],\n                  [2.08, 1.56]]\n    m_Outsample = [1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]\n    m_Tsample = [[1.80,1.24],[1.84,1.28],[2.04,1.40]]\n    # m_Insample = [[1.16,0.116],[1.35,0.104],[1.72,0.078],[1.86,0.107],[1.97,0.136],[2.15,0.082],[2.23,0.125],\n    #               [2.48,0.076],[2.79,0.122],[2.85,0.092],[3.07,0.081],[3.45,0.068],[3.59,0.077],[3.80,0.108],\n    #               [3.93,0.128],[4.14,0.063],[4.46,0.135],[4.55,0.070],[4.84,0.126],[5.03,0.087]]\n    # m_Outsample = [0.502,0.595,0.588,0.662,0.655,0.645,0.736,0.764,0.785,0.792,0.814,0.903,0.931,0.982,0.973,0.981,0.973,0.988,0.969,0.986]\n    # m_Tsample = [[1.42,0.086],[2.51,0.071],[3.21,0.107],[4.29,0.096],[5.24,0.065]]\n    #\n    bp = bpNet(BpInNode=2,BpHideNode=10,BpOutNode=1)\n    bp.bpInitNetFunc()\n\n    # 训练\n    times = 0\n    while bp.totalErr > 0.0001 and times < 10000:\n        times += 1\n        bp.bpNetTrainFunc(m_Insample,m_Outsample)\n        if (times + 1) % 100 == 0:\n            file.write('BP %5d DT:%10.5f\\n' % ((times+1),bp.totalErr))\n            print('BP %5d DT:%10.5f\\n' % ((times+1),bp.totalErr))\n        err.append(bp.totalErr)\n        err_time.append(times+1)\n    plt.plot(err_time,err)\n    plt.show()\n    # 测试\n    testSample = np.shape(np.array(m_Tsample))[0]\n    for j in range(testSample):\n        bp.bpNetRecognizeFunc(np.array(m_Tsample)[j,:])\n        print(bp.out_y0)\n    pass", "meta": {"hexsha": "e28c550e051c4d7c2cbab021b1b23d740d8ae3cf", "size": 9310, "ext": "py", "lang": "Python", "max_stars_repo_path": "argrithms.py", "max_stars_repo_name": "zhaohyin/NormSITS", "max_stars_repo_head_hexsha": "29fce816dfe6341970eec56a45edd9759fa9a444", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-17T14:24:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T14:24:22.000Z", "max_issues_repo_path": "argrithms.py", "max_issues_repo_name": "zhaohyin/NormSITS", "max_issues_repo_head_hexsha": "29fce816dfe6341970eec56a45edd9759fa9a444", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "argrithms.py", "max_forks_repo_name": "zhaohyin/NormSITS", "max_forks_repo_head_hexsha": "29fce816dfe6341970eec56a45edd9759fa9a444", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.24, "max_line_length": 141, "alphanum_fraction": 0.4915145005, "include": true, "reason": "import numpy", "num_tokens": 3491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.17042328562554798}}
{"text": "#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# graph_tool -- a general graph manipulation python module\n#\n# Copyright (C) 2006-2018 Tiago de Paula Peixoto <tiago@skewed.de>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom __future__ import division, absolute_import, print_function\nimport sys\nif sys.version_info < (3,):\n    range = xrange\n\nfrom .. import _degree, _prop, Graph, GraphView, libcore, _get_rng, PropertyMap, \\\n    conv_pickle_state\n\nimport random\nfrom numpy import *\nimport numpy\nfrom collections import defaultdict\n\nfrom .. import group_vector_property, ungroup_vector_property\n\nfrom .. dl_import import dl_import\ndl_import(\"from . import libgraph_tool_inference as libinference\")\n\nfrom . blockmodel import *\nfrom . blockmodel import _bm_test\n\nclass OverlapBlockState(BlockState):\n    r\"\"\"The overlapping stochastic block model state of a given graph.\n\n    Parameters\n    ----------\n    g : :class:`~graph_tool.Graph`\n        Graph to be modelled.\n    b : :class:`~graph_tool.PropertyMap` or :class:`numpy.ndarray` (optional, default: ``None``)\n        Initial block labels on the vertices or half-edges. If not supplied, it\n        will be randomly sampled.\n        If the value passed is a vertex property map, it will be assumed to be a\n        non-overlapping partition of the vertices. If it is an edge property\n        map, it should contain a vector for each edge, with the block labels at\n        each end point (sorted according to their vertex index, in the case of\n        undirected graphs, otherwise from source to target). If the value is an\n        :class:`numpy.ndarray`, it will be assumed to correspond directly to a\n        partition of the list of half-edges.\n    B : ``int`` (optional, default: ``None``)\n        Number of blocks (or vertex groups). If not supplied it will be obtained\n        from the parameter ``b``.\n    recs : list of :class:`~graph_tool.PropertyMap` instances (optional, default: ``[]``)\n        List of real or discrete-valued edge covariates.\n    rec_types : list of edge covariate types (optional, default: ``[]``)\n        List of types of edge covariates. The possible types are:\n        ``\"real-exponential\"``, ``\"real-normal\"``, ``\"discrete-geometric\"``,\n        ``\"discrete-poisson\"`` or ``\"discrete-binomial\"``.\n    rec_params : list of ``dict`` (optional, default: ``[]``)\n        Model hyperparameters for edge covariates. This should a list of\n        ``dict`` instances. See :class:`~graph_tool.inference.blockmodel.BlockState` for\n        more details.\n    clabel : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)\n        Constraint labels on the vertices. If supplied, vertices with different\n        label values will not be clustered in the same group.\n    deg_corr : ``bool`` (optional, default: ``True``)\n        If ``True``, the degree-corrected version of the blockmodel ensemble will\n        be assumed, otherwise the traditional variant will be used.\n    allow_empty : ``bool`` (optional, default: ``False``)\n        If ``True``, partition description length computed will allow for empty\n        groups.\n    max_BE : ``int`` (optional, default: ``1000``)\n        If the number of blocks exceeds this number, a sparse representation of\n        the block graph is used, which is slightly less efficient, but uses less\n        memory,\n    \"\"\"\n\n    def __init__(self, g, b=None, B=None, recs=[], rec_types=[], rec_params=[],\n                 clabel=None, pclabel=None, deg_corr=True, allow_empty=False,\n                 max_BE=1000, **kwargs):\n\n        kwargs = kwargs.copy()\n\n        # determine if there is a base graph, and overlapping structure\n        self.base_g = kwargs.pop(\"base_g\", None)\n\n        # overlapping information\n        node_index = kwargs.pop(\"node_index\", None)\n        node_in_degs = kwargs.pop(\"node_in_degs\", None)\n        node_out_degs = kwargs.pop(\"node_out_degs\", None)\n        half_edges = kwargs.pop(\"half_edges\", None)\n        eindex = kwargs.pop(\"eindex\", None)\n\n        if node_index is not None and self.base_g is None:\n            raise ValueError(\"Must specify base graph if node_index is specified...\")\n\n        # create overlapping structure\n        if node_index is None:\n            # keep base graph\n            self.base_g = g\n\n            if len(recs) == 0:\n                rec = self.base_g.new_ep(\"vector<double>\")\n            else:\n                recs = [x.copy(\"double\") for x in recs]\n                rec = group_vector_property(recs)\n\n            # substitute provided graph by its half-edge graph\n            g, b, node_index, half_edges, eindex, rec = \\\n                                                half_edge_graph(g, b, B, rec)\n\n            if len(recs) > 0:\n                recs = ungroup_vector_property(rec, range(len(recs)))\n\n        # create half edges set if absent\n        if half_edges is None:\n            half_edges = self.base_g.new_vertex_property(\"vector<int64_t>\")\n            libinference.get_nodeset_overlap(g._Graph__graph,\n                                             _prop(\"v\", g, node_index),\n                                             _prop(\"v\", self.base_g, half_edges))\n\n        self.overlap = True\n        self.node_index = node_index\n        self.half_edges = half_edges\n        self.eindex = eindex\n\n        # configure the main graph and block model parameters\n        self.g = g\n\n        self.deg_corr = deg_corr\n\n        self.is_edge_weighted = False\n        self.is_vertex_weighted = False\n        self.is_weighted = False\n\n        if b is None:\n            # create a random partition into B blocks.\n            B = min(B, self.g.num_vertices())\n            ba = random.randint(0, B, self.g.num_vertices())\n            ba[:B] = arange(B)        # avoid empty blocks\n            if B < self.g.num_vertices():\n                random.shuffle(ba)\n            b = g.new_vertex_property(\"int\")\n            b.fa = ba\n            self.b = b\n        else:\n            # if a partition is available, we will incorporate it.\n            # in the overlapping case\n            # at this point, *b* must correspond to the partition of\n            # *half-edges*\n            if isinstance(b, numpy.ndarray):\n                self.b = g.new_vertex_property(\"int\")\n                self.b.fa = b\n            else:\n                b = b.copy(value_type=\"int\")\n                b = g.own_property(b)\n                self.b = b\n            if B is None:\n                B = int(self.b.fa.max()) + 1\n\n        if self.b.fa.max() >= B:\n            raise ValueError(\"Maximum value of b is larger or equal to B!\")\n\n        self.rec = [self.g.own_property(p) for p in recs]\n        for i in range(len(self.rec)):\n            if self.rec[i].value_type() != \"double\":\n                self.rec[i] = self.rec[i].copy(\"double\")\n        self.drec = kwargs.pop(\"drec\", None)\n        if self.drec is None:\n            self.drec = []\n            for rec in self.rec:\n                self.drec.append(self.g.new_ep(\"double\", rec.fa ** 2))\n        else:\n            self.drec = [self.g.own_property(p) for p in self.drec]\n\n        rec_types = list(rec_types)\n        rec_params = list(rec_params)\n\n        # if len(rec_params) < len(rec_types):\n        #     rec_params += [{} for i in range((len(rec_types) -\n        #                                       len(rec_params)))]\n\n        if len(self.rec) > 0 and rec_types[0] != libinference.rec_type.count:\n            rec_types.insert(0, libinference.rec_type.count)\n            rec_params.insert(0, {})\n            self.rec.insert(0, self.g.new_ep(\"double\", 1))\n            self.drec.insert(0, self.g.new_ep(\"double\"))\n\n        # Construct block-graph\n        self.bg = get_block_graph(g, B, self.b, rec=self.rec, drec=self.drec)\n        self.bg.set_fast_edge_removal()\n\n        self.mrs = self.bg.ep[\"count\"]\n        self.wr = self.bg.vp[\"count\"]\n\n        self.mrp = self.bg.degree_property_map(\"out\", weight=self.mrs)\n\n        if g.is_directed():\n            self.mrm = self.bg.degree_property_map(\"in\", weight=self.mrs)\n        else:\n            self.mrm = self.mrp\n\n        self.B = B\n\n        self.candidate_blocks = Vector_size_t()\n        self.candidate_blocks.extend(arange(self.B, dtype=\"int\"))\n\n        if pclabel is not None:\n            if isinstance(pclabel, PropertyMap):\n                self.pclabel = self.g.own_property(pclabel).copy(\"int\")\n            else:\n                self.pclabel = self.g.new_vp(\"int\")\n                self.pclabel.fa = pclabel\n        else:\n            self.pclabel = self.g.new_vp(\"int\")\n\n        if clabel is not None:\n            if isinstance(clabel, PropertyMap):\n                self.clabel = self.g.own_property(clabel).copy(\"int\")\n            else:\n                self.clabel = self.g.new_vp(\"int\")\n                self.clabel.fa = clabel\n        elif self.pclabel.fa.max() > 0:\n            self.clabel = self.pclabel\n        else:\n            self.clabel = self.g.new_vp(\"int\")\n\n        self.bclabel = self.get_bclabel()\n        self.hclabel = self.bg.new_vp(\"int\")\n\n        BlockState._init_recs(self, self.rec, rec_types, rec_params)\n        self.recdx = libcore.Vector_double(len(self.rec))\n        self.Lrecdx = kwargs.pop(\"Lrecdx\", None)\n        if self.Lrecdx is None:\n            self.Lrecdx = libcore.Vector_double(len(self.rec)+1)\n            self.Lrecdx[0] = -1\n        self.Lrecdx.resize(len(self.rec)+1)\n        self.epsilon = kwargs.pop(\"epsilon\", None)\n        if self.epsilon is None:\n            self.epsilon = libcore.Vector_double(len(self.rec))\n            for i in range(len(self.rec)):\n                idx = self.rec[i].a != 0\n                if numpy.any(idx):\n                    self.epsilon[i] = abs(self.rec[i].a[idx]).min() / 10\n\n        self.max_BE = max_BE\n\n        self.use_hash = self.B > self.max_BE\n\n        self.allow_empty = True\n\n        self._abg = self.bg._get_any()\n        self._state = libinference.make_overlap_block_state(self, _get_rng())\n\n        if deg_corr:\n            init_q_cache(max(self.get_E(), self.get_N()) + 1)\n\n        self._entropy_args = dict(adjacency=True, deg_entropy=True, dl=True,\n                                  partition_dl=True, degree_dl=True,\n                                  degree_dl_kind=\"distributed\", edges_dl=True,\n                                  dense=False, multigraph=True, exact=True,\n                                  recs=True, recs_dl=True, beta_dl=1.)\n\n        self._coupled_state = None\n\n        vweight = kwargs.pop(\"vweight\", \"unity\")\n        eweight = kwargs.pop(\"eweight\", \"unity\")\n\n        if vweight != \"unity\":\n            kwargs[\"vweight\"] = vweight\n        if eweight != \"unity\":\n            kwargs[\"eweight\"] = eweight\n\n        self.ignore_degrees = kwargs.pop(\"ignore_degrees\", self.g.new_vp(\"bool\"))\n\n        if len(kwargs) > 0:\n            warnings.warn(\"unrecognized keyword arguments: \" +\n                          str(list(kwargs.keys())))\n\n    def __repr__(self):\n        return \"<OverlapBlockState object with %d blocks,%s%s for graph %s, at 0x%x>\" % \\\n            (self.B, \" degree corrected,\" if self.deg_corr else \"\",\n             ((\" with %d edge covariate%s,\" % (len(self.rec_types) - 1,\n                                               \"s\" if len(self.rec_types) > 2 else \"\"))\n              if len(self.rec_types) > 0 else \"\"),\n             str(self.base_g), id(self))\n\n    def __copy__(self):\n        return self.copy()\n\n    def __deepcopy__(self, memo):\n        g = copy.deepcopy(self.g, memo)\n        node_index = g.own_property(copy.deepcopy(self.node_index, memo))\n        eindex = g.own_property(copy.deepcopy(self.eindex, memo))\n        half_edges = base_g.own_property(copy.deepcopy(self.half_edges, memo))\n        base_g = copy.deepcopy(self.base_g, memo)\n        return self.copy(g=g, node_index=node_index, eindex=eindex,\n                         half_edges=half_edges, base_g=base_g)\n\n    def copy(self, g=None, b=None, B=None, deg_corr=None, clabel=None,\n             pclabel=None, **kwargs):\n        r\"\"\"Copies the block state. The parameters override the state properties, and\n         have the same meaning as in the constructor. If ``overlap=False`` an\n         instance of :class:`~graph_tool.inference.blockmodel.BlockState` is returned. This\n         is by default a shallow copy.\"\"\"\n\n        state = OverlapBlockState(self.g if g is None else g,\n                                  b=self.b if b is None else b,\n                                  B=(self.B if b is None else None) if B is None else B,\n                                  clabel=self.clabel.fa if clabel is None else clabel,\n                                  pclabel=self.pclabel if pclabel is None else pclabel,\n                                  deg_corr=self.deg_corr if deg_corr is None else deg_corr,\n                                  recs=kwargs.pop(\"recs\", self.rec),\n                                  drec=kwargs.pop(\"drec\", self.drec),\n                                  rec_types=kwargs.pop(\"rec_types\", self.rec_types),\n                                  rec_params=kwargs.pop(\"rec_params\",\n                                                        self.rec_params),\n                                  half_edges=kwargs.get(\"half_edges\", self.half_edges),\n                                  node_index=kwargs.get(\"node_index\", self.node_index),\n                                  eindex=kwargs.get(\"eindex\", self.eindex),\n                                  max_BE=kwargs.get(\"max_BE\", self.max_BE),\n                                  base_g=kwargs.get(\"base_g\", self.base_g),\n                                  Lrecdx=kwargs.pop(\"Lrecdx\", self.Lrecdx.copy()),\n                                  epsilon=kwargs.pop(\"epsilon\",\n                                                     self.epsilon.copy()),\n                                  allow_empty=kwargs.pop(\"allow_empty\",\n                                                         self.allow_empty),\n                                  **dmask(kwargs, [\"half_edges\", \"node_index\",\n                                                   \"eindex\", \"base_g\", \"drec\",\n                                                   \"max_BE\"]))\n        if self._coupled_state is not None:\n            state._couple_state(state.get_block_state(b=state.get_bclabel(),\n                                                      vweight=\"nonempty\",\n                                                      copy_bg=False,\n                                                      Lrecdx=state.Lrecdx,\n                                                      allow_empty=False),\n                                self._coupled_state[1])\n        return state\n\n    def __getstate__(self):\n        state = dict(g=self.g,\n                     b=self.b,\n                     B=self.B,\n                     clabel=array(self.clabel.fa),\n                     deg_corr=self.deg_corr,\n                     recs=ungroup_vector_property(self.rec,\n                                                  range(len(self.recs))),\n                     drec=self.drec,\n                     rec_types=list(self.rec_types),\n                     rec_params=self.rec_params,\n                     half_edges=self.half_edges,\n                     node_index=self.node_index,\n                     eindex=self.eindex,\n                     max_BE=self.max_BE,\n                     base_g=self.base_g)\n        return state\n\n    def __setstate__(self, state):\n        conv_pickle_state(state)\n        self.__init__(**state)\n\n    def get_E(self):\n        r\"Returns the total number of edges.\"\n        return self.g.num_edges()\n\n    def get_N(self):\n        r\"Returns the total number of nodes.\"\n        return self.base_g.num_vertices()\n\n    def get_B(self):\n        r\"Returns the total number of blocks.\"\n        return self.bg.num_vertices()\n\n    def get_nonempty_B(self):\n        r\"Returns the total number of nonempty blocks.\"\n        return int((self.wr.a > 0).sum())\n\n    def get_edge_blocks(self):\n        r\"\"\"Returns an edge property map which contains the block labels pairs for each\n        edge.\"\"\"\n        be = self.base_g.new_edge_property(\"vector<int>\")\n        self._state.get_be_overlap(self.base_g._Graph__graph,\n                                    _prop(\"e\", self.base_g, be))\n        return be\n\n    def get_overlap_blocks(self):\n        r\"\"\"Returns the mixed membership of each vertex.\n\n        Returns\n        -------\n        bv : :class:`~graph_tool.PropertyMap`\n           A vector-valued vertex property map containing the block memberships\n           of each node.\n        bc_in : :class:`~graph_tool.PropertyMap`\n           The labelled in-degrees of each node, i.e. how many in-edges belong\n           to each group, in the same order as the ``bv`` property above.\n        bc_out : :class:`~graph_tool.PropertyMap`\n           The labelled out-degrees of each node, i.e. how many out-edges belong\n           to each group, in the same order as the ``bv`` property above.\n        bc_total : :class:`~graph_tool.PropertyMap`\n           The labelled total degrees of each node, i.e. how many incident edges\n           belong to each group, in the same order as the ``bv`` property above.\n\n        \"\"\"\n        bv = self.base_g.new_vertex_property(\"vector<int>\")\n        bc_in = self.base_g.new_vertex_property(\"vector<int>\")\n        bc_out = self.base_g.new_vertex_property(\"vector<int>\")\n        bc_total = self.base_g.new_vertex_property(\"vector<int>\")\n        self._state.get_bv_overlap(self.base_g._Graph__graph,\n                                    _prop(\"v\", self.base_g, bv),\n                                    _prop(\"v\", self.base_g, bc_in),\n                                    _prop(\"v\", self.base_g, bc_out),\n                                    _prop(\"v\", self.base_g, bc_total))\n        return bv, bc_in, bc_out, bc_total\n\n    def get_nonoverlap_blocks(self):\n        r\"\"\"Returns a scalar-valued vertex property map with the block mixture\n        represented as a single number.\"\"\"\n\n        bv = self.get_overlap_blocks()[0]\n        b = self.base_g.new_vertex_property(\"int\")\n        self._state.get_overlap_split(self.base_g._Graph__graph,\n                                       _prop(\"v\", self.base_g, bv),\n                                       _prop(\"v\", self.base_g, b))\n        return b\n\n    def get_majority_blocks(self):\n        r\"\"\"Returns a scalar-valued vertex property map with the majority block\n        membership of each node.\"\"\"\n\n        bv = self.get_overlap_blocks()\n        bv, bc = bv[0], bv[-1]\n        b = self.base_g.new_vertex_property(\"int\")\n        self._state.get_maj_overlap(self.base_g._Graph__graph,\n                                     _prop(\"v\", self.base_g, bv),\n                                     _prop(\"v\", self.base_g, bc),\n                                     _prop(\"v\", self.base_g, b))\n        return b\n\n    def entropy(self, adjacency=True, dl=True, partition_dl=True,\n                degree_dl=True, degree_dl_kind=\"distributed\", edges_dl=True,\n                dense=False, multigraph=True, deg_entropy=True, recs=True,\n                recs_dl=True, beta_dl=1., exact=True, **kwargs):\n        r\"\"\"Calculate the entropy associated with the current block partition.\n\n        Parameters\n        ----------\n        adjacency : ``bool`` (optional, default: ``True``)\n            If ``True``, the adjacency term of the description length will be\n            included.\n        dl : ``bool`` (optional, default: ``True``)\n            If ``True``, the description length for the parameters will be\n            included.\n        partition_dl : ``bool`` (optional, default: ``True``)\n            If ``True``, and ``dl == True`` the partition description length\n            will be included.\n        degree_dl : ``bool`` (optional, default: ``True``)\n            If ``True``, and ``dl == True`` the degree sequence description\n            length will be included (for degree-corrected models).\n        degree_dl_kind : ``str`` (optional, default: ``\"distributed\"``)\n            This specifies the prior used for the degree sequence. It must be\n            one of: ``\"uniform\"``, ``\"distributed\"`` (default) or ``\"entropy\"``.\n        edges_dl : ``bool`` (optional, default: ``True``)\n            If ``True``, and ``dl == True`` the edge matrix description length\n            will be included.\n        dense : ``bool`` (optional, default: ``False``)\n            If ``True``, the \"dense\" variant of the entropy will be computed.\n        multigraph : ``bool`` (optional, default: ``True``)\n            If ``True``, the multigraph entropy will be used.\n        deg_entropy : ``bool`` (optional, default: ``True``)\n            If ``True``, the degree entropy term that is independent of the\n            network partition will be included (for degree-corrected models).\n        recs : ``bool`` (optional, default: ``True``)\n            If ``True``, the likelihood for real or discrete-valued edge\n            covariates is computed.\n        recs_dl : ``bool`` (optional, default: ``True``)\n            If ``True``, and ``dl == True`` the edge covariate description\n            length will be included.\n        beta_dl : ``double`` (optional, default: ``1.``)\n            Prior inverse temperature.\n        exact : ``bool`` (optional, default: ``True``)\n            If ``True``, the exact expressions will be used. Otherwise,\n            Stirling's factorial approximation will be used for some terms.\n\n        Notes\n        -----\n\n        The \"entropy\" of the state is minus the log-likelihood of the\n        microcanonical SBM, that includes the generated graph\n        :math:`\\boldsymbol{A}` and the model parameters :math:`\\boldsymbol{\\theta}`,\n\n        .. math::\n\n           \\mathcal{S} &= - \\ln P(\\boldsymbol{A},\\boldsymbol{\\theta}) \\\\\n                       &= - \\ln P(\\boldsymbol{A}|\\boldsymbol{\\theta}) - \\ln P(\\boldsymbol{\\theta}).\n\n        This value is also called the `description length\n        <https://en.wikipedia.org/wiki/Minimum_description_length>`_ of the data,\n        and it corresponds to the amount of information required to describe it\n        (in `nats <https://en.wikipedia.org/wiki/Nat_(unit)>`_).\n\n        For the traditional blockmodel (``deg_corr == False``), the model\n        parameters are :math:`\\boldsymbol{\\theta} = \\{\\boldsymbol{e},\n        \\boldsymbol{b}\\}`, where :math:`\\boldsymbol{e}` is the matrix of edge\n        counts between blocks, and :math:`\\boldsymbol{b}` is the `overlapping`\n        partition of the nodes into blocks. For the degree-corrected blockmodel\n        (``deg_corr == True``), we have an additional set of parameters, namely\n        the `labelled` degree sequence :math:`\\boldsymbol{k}`.\n\n        The model likelihood :math:`P(\\boldsymbol{A}|\\theta)` is given\n        analogously to the non-overlapping case, as described in\n        :meth:`graph_tool.inference.blockmodel.BlockState.entropy`.\n\n        If ``dl == True``, the description length :math:`\\mathcal{L} = -\\ln\n        P(\\boldsymbol{\\theta})` of the model will be returned as well. The\n        edge-count prior :math:`P(\\boldsymbol{e})` is described in described in\n        :func:`~graph_tool.inference.blockmodel.model_entropy`. For the\n        overlapping partition :math:`P(\\boldsymbol{b})`, we have\n\n        .. math::\n\n           -\\ln P(\\boldsymbol{b}) = \\ln\\left(\\!\\!{D \\choose N}\\!\\!\\right) + \\sum_d \\ln {\\left(\\!\\!{{B\\choose d}\\choose n_d}\\!\\!\\right)} + \\ln N! - \\sum_{\\vec{b}}\\ln n_{\\vec{b}}!,\n\n        where :math:`d \\equiv |\\vec{b}|_1 = \\sum_rb_r` is the mixture\n        size, :math:`n_d` is the number of nodes in a mixture of size :math:`d`,\n        :math:`D` is the maximum value of :math:`d`, :math:`n_{\\vec{b}}` is the\n        number of nodes in mixture :math:`\\vec{b}`.\n\n\n        For the degree-corrected model we need to specify the prior\n        :math:`P(\\boldsymbol{k})` for the `labelled` degree sequence as well:\n\n        .. math::\n\n            -\\ln P(\\boldsymbol{k}) = \\sum_r\\ln\\left(\\!\\!{m_r \\choose e_r}\\!\\!\\right) - \\sum_{\\vec{b}}\\ln P(\\boldsymbol{k}|{\\vec{b}}),\n\n        where :math:`m_r` is the number of non-empty mixtures which contain type\n        :math:`r`, and :math:`P(\\boldsymbol{k}|{\\vec{b}})` is the likelihood of\n        the labelled degree sequence inside mixture :math:`\\vec{b}`. For this\n        term we have three options:\n\n        1. ``degree_dl_kind == \"uniform\"``\n\n            .. math::\n\n                P(\\boldsymbol{k}|\\vec{b}) = \\prod_r\\left(\\!\\!{n_{\\vec{b}}\\choose e^r_{\\vec{b}}}\\!\\!\\right)^{-1}.\n\n        2. ``degree_dl_kind == \"distributed\"``\n\n            .. math::\n\n                P(\\boldsymbol{k}|\\vec{b}) = \\prod_{\\vec{b}}\\frac{\\prod_{\\vec{k}}\\eta_{\\vec{k}}^{\\vec{b}}!}{n_{\\vec{b}}!} \\prod_r q(e_{\\vec{b}}^r - n_{\\vec{b}}, n_{\\vec{b}})\n\n            where :math:`n^{\\vec{b}}_{\\vec{k}}` is the number of nodes in\n            mixture :math:`\\vec{b}` with labelled degree :math:`\\vec{k}`, and\n            :math:`q(n,m)` is the number of `partitions\n            <https://en.wikipedia.org/wiki/Partition_(number_theory)>`_ of\n            integer :math:`n` into at most :math:`m` parts.\n\n        3. ``degree_dl_kind == \"entropy\"``\n\n            .. math::\n\n                P(\\boldsymbol{k}|\\vec{b}) = \\prod_{\\vec{b}}\\exp\\left(-n_{\\vec{b}}H(\\boldsymbol{k}_{\\vec{b}})\\right)\n\n            where :math:`H(\\boldsymbol{k}_{\\vec{b}}) =\n            -\\sum_{\\vec{k}}p_{\\vec{b}}(\\vec{k})\\ln p_{\\vec{b}}(\\vec{k})` is the\n            entropy of the labelled degree distribution inside mixture\n            :math:`\\vec{b}`.\n\n            Note that, differently from the other two choices, this represents\n            only an approximation of the description length. It is meant to be\n            used only for comparison purposes, and should be avoided in practice.\n\n\n        For the directed case, the above expressions are duplicated for the in-\n        and out-degrees.\n\n        \"\"\"\n\n        return BlockState.entropy(self, adjacency=adjacency, dl=dl,\n                                  partition_dl=partition_dl,\n                                  degree_dl=degree_dl,\n                                  degree_dl_kind=degree_dl_kind,\n                                  edges_dl=edges_dl, dense=dense,\n                                  multigraph=multigraph,\n                                  deg_entropy=deg_entropy, recs=recs,\n                                  recs_dl=recs_dl, beta_dl=beta_dl, exact=exact,\n                                  **kwargs)\n\n    def _clear_egroups(self):\n        self._state.clear_egroups()\n\n    def _mcmc_sweep_dispatch(self, mcmc_state):\n        dS, nattempts, nmoves = \\\n                    libinference.overlap_mcmc_sweep(mcmc_state, self._state,\n                                                    _get_rng())\n        if self.__bundled:\n            ret = libinference.overlap_mcmc_bundled_sweep(mcmc_state,\n                                                          self._state,\n                                                          _get_rng())\n            dS += ret[0]\n            nattempts += ret[1]\n            nmoves += ret[2]\n        del self.__bundled\n        return dS, nattempts, nmoves\n\n    def _mcmc_sweep_parallel_dispatch(states, mcmc_states):\n        return libinference.overlap_mcmc_sweep_parallel(mcmc_states,\n                                                        [s._state for s in states],\n                                                        _get_rng())\n\n    def mcmc_sweep(self, bundled=False, **kwargs):\n        r\"\"\"Perform sweeps of a Metropolis-Hastings rejection sampling MCMC to sample\n        network partitions. If ``bundled == True``, the half-edges incident of\n        the same node that belong to the same group are moved together. All\n        remaining parameters are passed to\n        :meth:`graph_tool.inference.blockmodel.BlockState.mcmc_sweep`.\"\"\"\n        self.__bundled = bundled\n        return BlockState.mcmc_sweep(self, **kwargs)\n\n    def _multiflip_mcmc_sweep_dispatch(self, mcmc_state):\n        return libinference.overlap_multiflip_mcmc_sweep(mcmc_state,\n                                                         self._state,\n                                                         _get_rng())\n\n    def _multiflip_mcmc_sweep_parallel_dispatch(states, mcmc_states):\n        return libinference.overlap_multiflip_mcmc_sweep_parallel(mcmc_states,\n                                                                  [s._state for s in states],\n                                                                  _get_rng())\n\n    def _multicanonical_sweep_dispatch(self, multicanonical_state):\n        if multicanonical_state.multiflip:\n            return libinference.overlap_multicanonical_sweep(multicanonical_state,\n                                                             self._state,\n                                                             _get_rng())\n        else:\n            return libinference.overlap_multicanonical_multiflip_sweep(multicanonical_state,\n                                                                       self._state,\n                                                                       _get_rng())\n\n    def _exhaustive_sweep_dispatch(self, exhaustive_state, callback, hist):\n        if callback is not None:\n            return libinference.overlap_exhaustive_sweep(exhaustive_state,\n                                                         self._state, callback)\n        else:\n            if hist is None:\n                return libinference.overlap_exhaustive_sweep_iter(exhaustive_state,\n                                                                  self._state)\n            else:\n                return libinference.overlap_exhaustive_dens(exhaustive_state,\n                                                            self._state,\n                                                            hist[0], hist[1],\n                                                            hist[2])\n\n    def _gibbs_sweep_dispatch(self, gibbs_state):\n        return libinference.gibbs_overlap_sweep(gibbs_state, self._state,\n                                                _get_rng())\n\n    def _gibbs_sweep_parallel_dispatch(states, gibbs_states):\n        return libinference.overlap_gibbs_sweep_parallel(gibbs_states,\n                                                         [s._state for s in states],\n                                                         _get_rng())\n\n    def _merge_sweep_dispatch(self, merge_state):\n        return libinference.vacate_overlap_sweep(merge_state, self._state,\n                                                 _get_rng())\n\n    def shrink(self, B, **kwargs):\n        \"\"\"Reduces the order of current state by progressively merging groups,\n        until only ``B`` are left. All remaining keyword arguments are passed to\n        :meth:`graph_tool.inference.blockmodel.BlockState.merge_sweep`.\n\n        This function leaves the current state untouched and returns instead a\n        copy with the new partition.\n        \"\"\"\n\n        b = self.b.copy()\n        continuous_map(b)\n        bstate = self.copy(b=b)\n\n        assert self.get_nonempty_B() == bstate.get_nonempty_B(), \\\n            \"Error: inconsistent number of groups after copying (%d, %d)\" % \\\n            (self.get_nonempty_B(), bstate.get_nonempty_B())\n\n        if bstate.get_nonempty_B() < B:\n            raise ValueError(\"cannot shrink state to a larger number\" +\n                             \" of groups: %d -> %d (total: %d)\" %\n                             (bstate.get_nonempty_B(), B, self.B))\n\n        while bstate.get_nonempty_B() > B:\n            bstate.merge_sweep(bstate.get_nonempty_B() - B, **kwargs)\n\n        continuous_map(bstate.b)\n        bstate = self.copy(b=bstate.b.a, Lrecdx=bstate.Lrecdx)\n\n        if _bm_test():\n            assert bstate.get_nonempty_B() == B, \\\n                \"wrong number of groups after shrink: %d, %d\" % \\\n                (bstate.get_nonempty_B(), B)\n            assert bstate.wr.a.min() > 0, \"empty group after shrink!\"\n\n        return bstate\n\n    def draw(self, **kwargs):\n        r\"\"\"Convenience wrapper to :func:`~graph_tool.draw.graph_draw` that\n        draws the state of the graph as colors on the vertices and edges.\"\"\"\n\n        bv, bc_in, bc_out, bc_total = self.get_overlap_blocks()\n        if self.deg_corr:\n            pie_fractions = bc_total.copy(\"vector<double>\")\n        else:\n            pie_fractions = self.base_g.new_vp(\"vector<double>\",\n                                               vals=[ones(len(bv[v])) for v\n                                                     in self.base_g.vertices()])\n\n        gradient = kwargs.get(\"edge_gradient\",\n                              get_block_edge_gradient(self.base_g,\n                                                      self.get_edge_blocks(),\n                                                      cmap=kwargs.get(\"ecmap\",\n                                                                      None)))\n        from graph_tool.draw import graph_draw\n        return graph_draw(self.base_g,\n                          vertex_shape=kwargs.get(\"vertex_shape\", \"pie\"),\n                          vertex_pie_colors=kwargs.get(\"vertex_pie_colors\", bv),\n                          vertex_pie_fractions=kwargs.get(\"vertex_pie_fractions\",\n                                                          pie_fractions),\n                          edge_gradient=gradient,\n                          **dmask(kwargs, [\"vertex_shape\", \"vertex_pie_colors\",\n                                           \"vertex_pie_fractions\",\n                                           \"edge_gradient\"]))\n\n\ndef half_edge_graph(g, b=None, B=None, rec=None):\n    r\"\"\"Generate a half-edge graph, where each half-edge is represented by a node,\n    and an edge connects the half-edges like in the original graph.\"\"\"\n\n    E = g.num_edges()\n\n    b_array = None\n    if b is None:\n        # if no partition is given, obtain a random one.\n        ba = random.randint(0, B, 2 * E)\n        ba[:B] = arange(B)        # avoid empty blocks\n        if B < len(ba):\n            random.shuffle(ba)\n        b = ba\n\n    if isinstance(b, numpy.ndarray):\n        # if given an array, assume it corresponds to the *final* half-edge\n        # partitions\n        b_array = b\n        b = g.new_vertex_property(\"int\")\n\n    if b.key_type() == \"v\":\n        # If a vertex partition is given, we convert it into a\n        # non-overlapping edge partition\n        be = g.new_edge_property(\"vector<int>\")\n        libinference.get_be_from_b_overlap(g._Graph__graph,\n                                           _prop(\"e\", g, be),\n                                           _prop(\"v\", g, b))\n        b = be\n    else:\n        # If an half-edge partition is provided, we incorporate it\n        b = b.copy(value_type=\"vector<int32_t>\")\n\n    if B is None:\n        if b_array is None:\n            bs, bt = ungroup_vector_property(b, [0, 1])\n            B = int(max(bs.fa.max(), bt.fa.max())) + 1\n        else:\n            B = b_array.max() + 1\n\n    bs, bt = ungroup_vector_property(b, [0, 1])\n\n    if bs.fa.max() >= B or bt.fa.max() >= B or (b_array is not None and b_array.max() >= B):\n        raise ValueError(\"Maximum value of b is larger or equal to B!\")\n\n    eg = Graph(directed=g.is_directed())\n    node_index = eg.new_vertex_property(\"int64_t\")\n    half_edges = g.new_vertex_property(\"vector<int64_t>\")\n    be = eg.new_vertex_property(\"int\")\n    eindex = eg.new_edge_property(\"int64_t\")\n    erec = eg.new_edge_property(\"vector<double>\")\n\n    if rec is None:\n        rec_ = g.new_edge_property(\"vector<double>\")\n    else:\n        rec_ = g.own_property(rec)\n\n    # create half-edge graph\n    libinference.get_eg_overlap(g._Graph__graph,\n                                eg._Graph__graph,\n                                _prop(\"e\", g, b),\n                                _prop(\"v\", eg, be),\n                                _prop(\"v\", eg, node_index),\n                                _prop(\"v\", g, half_edges),\n                                _prop(\"e\", eg, eindex),\n                                _prop(\"e\", g, rec_),\n                                _prop(\"e\", eg, erec))\n\n    if b_array is not None:\n        be.a = b_array\n\n    if rec is None:\n        erec = None\n\n    return eg, be, node_index, half_edges, eindex, erec\n\ndef augmented_graph(g, b, node_index, eweight=None):\n    r\"\"\"Generates an augmented graph from the half-edge graph ``g`` partitioned\n    according to ``b``, where each half-edge belonging to a different group\n    inside each node forms a new node.\"\"\"\n\n    node_map = g.new_vertex_property(\"int\")\n    br_b = libcore.Vector_int32_t()\n    br_ni = libcore.Vector_int32_t()\n    libinference.get_augmented_overlap(g._Graph__graph,\n                                       _prop(\"v\", g, b),\n                                       _prop(\"v\", g, node_index),\n                                       _prop(\"v\", g, node_map),\n                                       br_b, br_ni)\n\n\n    au, idx, vcount, ecount = condensation_graph(g, node_map,\n                                                 eweight=eweight,\n                                                 self_loops=True)[:4]\n    anidx = idx.copy(\"int\")\n    libinference.vector_map(anidx.a, br_ni.a)\n\n    ab = idx.copy(\"int\")\n    libinference.vector_map(ab.a, br_b.a)\n\n    return au, ab, anidx, ecount, node_map\n\ndef get_block_edge_gradient(g, be, cmap=None):\n    r\"\"\"Get edge gradients corresponding to the block membership at the endpoints of\n    the edges given by the ``be`` edge property map.\n\n    Parameters\n    ----------\n    g : :class:`~graph_tool.Graph`\n        The graph.\n    be : :class:`~graph_tool.PropertyMap`\n        Vector-valued edge property map with the block membership at each\n        endpoint.\n    cmap : :class:`matplotlib.colors.Colormap` (optional, default: ``default_cm``)\n        Color map used to construct the gradient.\n\n    Returns\n    -------\n    cp : :class:`~graph_tool.PropertyMap`\n       A vector-valued edge property map containing a color gradient.\n    \"\"\"\n\n    if cmap is None:\n        from .. draw import default_cm\n        cmap = default_cm\n\n    cp = g.new_edge_property(\"vector<double>\")\n    rg = [numpy.inf, -numpy.inf]\n    for e in g.edges():\n        s, t = be[e]\n        rg[0] = min(s, rg[0])\n        rg[0] = min(t, rg[0])\n        rg[1] = max(s, rg[1])\n        rg[1] = max(t, rg[1])\n\n    for e in g.edges():\n        if int(e.source()) < int(e.target()) or g.is_directed():\n            s, t = be[e]\n        else:\n            t, s = be[e]\n        cs = cmap((s - rg[0]) / max(rg[1] - rg[0], 1))\n        ct = cmap((t - rg[0]) / max(rg[1] - rg[0], 1))\n        cp[e] = [0] + list(cs) + [1] + list(ct)\n    return cp\n", "meta": {"hexsha": "b483a968b90a56d48c42f40b70cfddc354ca0546", "size": 39147, "ext": "py", "lang": "Python", "max_stars_repo_path": "graph-tool-2.27/src/graph_tool/inference/overlap_blockmodel.py", "max_stars_repo_name": "Znigneering/CSCI-3154", "max_stars_repo_head_hexsha": "bc318efc73d2a80025b98f5b3e4f7e4819e952e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "graph-tool-2.27/src/graph_tool/inference/overlap_blockmodel.py", "max_issues_repo_name": "Znigneering/CSCI-3154", "max_issues_repo_head_hexsha": "bc318efc73d2a80025b98f5b3e4f7e4819e952e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graph-tool-2.27/src/graph_tool/inference/overlap_blockmodel.py", "max_forks_repo_name": "Znigneering/CSCI-3154", "max_forks_repo_head_hexsha": "bc318efc73d2a80025b98f5b3e4f7e4819e952e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.1341600902, "max_line_length": 178, "alphanum_fraction": 0.5451503308, "include": true, "reason": "import numpy,from numpy", "num_tokens": 8809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3208213008246071, "lm_q1q2_score": 0.1704232821759929}}
{"text": "\"\"\"An interface between Skyfield and the Python ``sgp4`` library.\"\"\"\n\nfrom numpy import array, cross, einsum, zeros_like\nfrom sgp4.earth_gravity import wgs72\nfrom sgp4.io import twoline2rv\nfrom sgp4.propagation import sgp4\n\nfrom .constants import AU_KM, DAY_S, T0, tau\nfrom .functions import rot_x, rot_y, rot_z\nfrom .positionlib import Apparent, Geocentric, ITRF_to_GCRS\nfrom .timelib import JulianDate, takes_julian_date\n\n# important ones:\n# jdsatepoch\n# bstar\n# inclo - inclination\n# nodeo - right ascension of ascending node\n# ecco - eccentricity\n# argpo - argument of perigee\n# mo - mean anomaly\n# no - mean motion\n\n_minutes_per_day = 1440.\n\nclass EarthSatellite(object):\n    \"\"\"An Earth satellite loaded from a TLE file and propagated with SGP4.\"\"\"\n\n    def __init__(self, lines, earth):\n        sat = twoline2rv(*lines[-2:], whichconst=wgs72)\n        self._sgp4_satellite = sat\n        self._earth = earth\n        self.epoch = JulianDate(utc=(sat.epochyr, 1, sat.epochdays - 1.0))\n\n    def __repr__(self):\n        sat = self._sgp4_satellite\n        return '<EarthSatellite number={1!r} epoch={0}>'.format(\n            self.epoch.utc_iso(), sat.satnum)\n\n    def _position_and_velocity_TEME_km(self, jd):\n        \"\"\"Return the raw true equator mean equinox (TEME) vectors from SGP4.\n\n        Returns a tuple of NumPy arrays ``([x y z], [xdot ydot zdot])``\n        expressed in kilometers and kilometers per second.  Note that we\n        assume the TLE epoch to be a UTC date, per AIAA 2006-6753.\n\n        \"\"\"\n        sat = self._sgp4_satellite\n        epoch = sat.jdsatepoch\n        minutes_past_epoch = (jd._utc_float() - epoch) * 1440.\n        if getattr(minutes_past_epoch, 'shape', None):\n            position = []\n            velocity = []\n            error = []\n            for m in minutes_past_epoch:\n                p, v = sgp4(sat, m)\n                position.append(p)\n                velocity.append(v)\n                error.append(sat.error_message)\n            return array(position).T, array(velocity).T, error\n        else:\n            position, velocity = sgp4(sat, minutes_past_epoch)\n            return array(position), array(velocity), sat.error_message\n\n    def _compute_GCRS(self, jd):\n        \"\"\"Compute where satellite is in space on a given date.\"\"\"\n\n        rTEME, vTEME, error = self._position_and_velocity_TEME_km(jd)\n        rTEME /= AU_KM\n        vTEME /= AU_KM\n        vTEME *= DAY_S\n\n        rITRF, vITRF = TEME_to_ITRF(jd.ut1, rTEME, vTEME)\n        rGCRS = ITRF_to_GCRS(jd, rITRF)\n        vGCRS = zeros_like(rGCRS)  # todo: someday also compute vGCRS?\n\n        return rGCRS, vGCRS, error\n\n    @takes_julian_date\n    def gcrs(self, jd):\n        \"\"\"Return a GCRS position for this Earth satellite.\n\n        Uses standard SGP4 theory to predict the satellite location.\n\n        \"\"\"\n        position_au, velociy_au_per_d, error = self._compute_GCRS(jd)\n        g = Geocentric(position_au, velociy_au_per_d, jd)\n        g.sgp4_error = error\n        return g\n\n    def _observe_from_bcrs(self, observer):\n        # TODO: what if someone on Mars tries to look at the ISS?\n\n        jd = observer.jd\n        rGCRS, vGCRS, error = self._compute_GCRS(jd)\n        rGCRS - observer.rGCRS\n        vGCRS - observer.vGCRS\n        g = Apparent(rGCRS - observer.rGCRS, vGCRS - observer.vGCRS, jd)\n        g.sgp4_error = error\n        g.observer = observer\n        # g.distance = euclidian_distance\n        return g\n\n\n_second = 1.0 / (24.0 * 60.0 * 60.0)\n\ndef theta_GMST1982(jd_ut1):\n    \"\"\"Return the angle of Greenwich Mean Standard Time 1982 given the JD.\n\n    This angle defines the difference between the idiosyncratic True\n    Equator Mean Equinox (TEME) frame of reference used by SGP4 and the\n    more standard Pseudo Earth Fixed (PEF) frame of reference.\n\n    From AIAA 2006-6753 Appendix C.\n\n    \"\"\"\n    t = (jd_ut1 - T0) / 36525.0\n    g = 67310.54841 + (8640184.812866 + (0.093104 + (-6.2e-6) * t) * t) * t\n    dg = 8640184.812866 + (0.093104 * 2.0 + (-6.2e-6 * 3.0) * t) * t\n    theta = (jd_ut1 % 1.0 + g * _second % 1.0) * tau\n    theta_dot = (1.0 + dg * _second / 36525.0) * tau\n    return theta, theta_dot\n\ndef TEME_to_ITRF(jd_ut1, rTEME, vTEME, xp=0.0, yp=0.0):\n    \"\"\"Convert TEME position and velocity into standard ITRS coordinates.\n\n    This converts a position and velocity vector in the idiosyncratic\n    True Equator Mean Equinox (TEME) frame of reference used by the SGP4\n    theory into vectors into the more standard ITRS frame of reference.\n    The velocity should be provided in units per day, not per second.\n\n    From AIAA 2006-6753 Appendix C.\n\n    \"\"\"\n    theta, theta_dot = theta_GMST1982(jd_ut1)\n    zero = theta_dot * 0.0\n    angular_velocity = array([zero, zero, -theta_dot])\n    R = rot_z(-theta)\n\n    if len(rTEME.shape) == 1:\n        rPEF = (R).dot(rTEME)\n        vPEF = (R).dot(vTEME) + cross(angular_velocity, rPEF)\n    else:\n        rPEF = einsum('ij...,j...->i...', R, rTEME)\n        vPEF = einsum('ij...,j...->i...', R, vTEME) + cross(\n            angular_velocity, rPEF, 0, 0).T\n\n    if xp == 0.0 and yp == 0.0:\n        rITRF = rPEF\n        vITRF = vPEF\n    else:\n        W = (rot_x(yp)).dot(rot_y(xp))\n        rITRF = (W).dot(rPEF)\n        vITRF = (W).dot(vPEF)\n    return rITRF, vITRF\n", "meta": {"hexsha": "ae5fabfc85f22497477151f9fe26524a4700af73", "size": 5250, "ext": "py", "lang": "Python", "max_stars_repo_path": "skyfield/sgp4lib.py", "max_stars_repo_name": "aarose/python-skyfield", "max_stars_repo_head_hexsha": "a6c56247d1a888f57fc442530948779cec5c1db1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "skyfield/sgp4lib.py", "max_issues_repo_name": "aarose/python-skyfield", "max_issues_repo_head_hexsha": "a6c56247d1a888f57fc442530948779cec5c1db1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "skyfield/sgp4lib.py", "max_forks_repo_name": "aarose/python-skyfield", "max_forks_repo_head_hexsha": "a6c56247d1a888f57fc442530948779cec5c1db1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8709677419, "max_line_length": 77, "alphanum_fraction": 0.6295238095, "include": true, "reason": "from numpy", "num_tokens": 1634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604272, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.17042094603848465}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nSynfit\n======\n\nThis routine allows the user to automatically fit a spectral line or wavelength\nregion. Is is allowed any number of parameters.\n\nThe best fit is found by minimizing the chi^2. `Synfit` calculates the\nsynthetic spectrum for all values asked and then select the one with minimum\nchi^2 and returns it to the user.\n\nIt is also possible to select a subregion of the spectrum by using the\n`windows` argument.\n\"\"\"\nimport os\nimport shutil\nimport re\nimport json\nimport shutil\nfrom copy import deepcopy\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom itertools import product\nfrom ..io import specio\nfrom ..synthesis import Synplot\nfrom ..spectools import rvcorr\n\n# Loads the chemical elements and their atomic numbers\nPERIODIC = json.load(open(os.getenv('HOME')+'/.s4/extra_resc'+\\\n                          '/chemical_elements.json'))\n\nREVERSE_PERIODIC = {val:key for key, val in PERIODIC.iteritems()}\n\ndef iterator(fit_keys, iter_params):\n    \"\"\"\n    Create an array with the values to iterate.\n\n    Parameters\n    ----------\n\n    fit_keys: dict;\n        A dictionary containing the name of the parameters,\n\n    fit_params: dict;\n        A dictionary containing the parameters as keys and the values to be\n        fitted.\n\n    Returns\n    -------\n\n    iter_values: numpy.ndarray;\n        The values to be fitted as a structured array\n    \"\"\"\n    # Create the iterator vector.\n    args = [iter_params[k] for k in fit_keys]\n    iter_values = list(product(*args))\n\n    ## add the iterrating values to self as a numpy array\n    data_type = [float] *len(fit_keys)\n\n    return np.array(iter_values, dtype={'names':fit_keys, 'formats':data_type})\n\nclass Synfit:\n    \"\"\"\n    Fit a spectral line by iterating on user defined parameter\n    an returns the best fit by minimizing the $\\chi^2$ of the\n    synthetic spectrum and the observed spectrum.\n\n    Based on the homonym IDL software created by Dr. Ivan\n    Hubeny.\n\n    Parameters\n    ----------\n\n    fit_params: dic;\n        Parameters to be fitted. It should be a dictionary in\n        which each key is the setllar parameter of the chemical\n        element to be fitted. The values should be list with three\n        elements: the initial and findal values and the step.\n\n    kwargs;\n        All Synplot parameters desired to be use, including `teff`,\n        `logg`, `synplot_path`, `idl`, `noplot`.\n\n        abund: dic (optional);\n            Abundance of chosen chemical elements.\n\n            Should be passsed as a dictionary which the keys are the chemical\n            element symbol or atomic number i(can be mixed) and the values are\n            the abundance, e.g, for Helium and Oxygen abundance of 10.93 and\n            8.69, respectively:\n\n            {2:10.93, 'O':8.69}\n\n\n            ATTENTION: it does not accept the Synplot format.\n\n        windows: list (optional);\n            Spectral region in which the chi-sqaure will be calculated. At\n            this point, it only accept a single window, i.e., the list should\n            contains only two values: the lower and the upper wavelength.\n    \"\"\"\n\n    def __init__(self, fit_params, **kwargs):\n        # Parameters to be fitted\n        self.fit_params = deepcopy(fit_params)\n        # Fixed parameters\n        self.syn_params = deepcopy(kwargs)\n        ##########\n\n        # Initalizaze varibales.\n        self.iter_params = None\n        self.fit_keys = None\n        self.no_rot_keys = None\n        self.rot_keys = None\n\n        # Check for radial velocity\n        if 'rv' in self.syn_params:\n            self.rad_vel = self.syn_params['rv']\n        else:\n            self.rad_vel = 0\n\n        # Check if there is a an observed spectrum.\n        # If not quit.\n        try:\n            # If there is, load it to calculate the weights\n            obs_spec = specio.load_spectrum(self.syn_params['observ'])\n            # Correct for radial velocity\n            obs_spec[:,0] *= rvcorr(self.rad_vel)\n        except IOError:\n            raise IOError('There is not any observed spectrum.')\n\n\n        #Prepare kwargs\n        if 'synplot_path' in self.syn_params:\n            self.synplot_path = self.syn_params.pop('synplot_path')\n        else:\n            self.synplot_path = os.getenv('HOME')+'/.s4/synthesis/synplot/'\n\n        if 'idl' in self.syn_params:\n            self.idl = self.syn_params.pop('idl')\n        else:\n            self.idl = False  # It will run GDL\n\n        if 'noplot' in self.syn_params and self.syn_params['noplot'] == True:\n            self.noplot = True\n            del self.syn_params['noplot']\n        else:\n            self.noplot = False\n\n        if 'windows' in self.syn_params:\n            self.weights = np.zeros_like(obs_spec[:, 0])\n\n            for window in np.reshape(self.syn_params['windows'], (-1, 2)):\n                index_lower = obs_spec[:, 0] > window[0]\n                index_upper = obs_spec[:, 0] < window[1]\n                self.weights[index_lower & index_upper] = 1\n\n            self.windows = self.syn_params.pop('windows')\n        else:\n            self.weights = np.ones_like(obs_spec[:,0])\n            self.windows = None\n\n        # Obtain teff and logg if set on syn_params\n        if 'teff' in self.syn_params:\n            self.teff = self.syn_params.pop('teff')\n\n        if 'logg' in self.syn_params:\n            self.logg = self.syn_params.pop('logg')\n\n        # Initialize variable to store the best fit values\n        self.best_fit = {}\n\n\n    def sample_params(self):\n        \"\"\"\n        Creates the values to fit for each parameter. It also merge\n        the chemical elements to a parameter accepted by `Synplot`.\n        \"\"\"\n        def values_to_fit(key, val):\n            \"\"\"\n            Creates the values to fit from a three-value list.\n\n            Parameters\n            ----------\n\n            key: string\n                Parameter to be fitted.\n\n            val: list;\n                List with initial value, final value and the step.\n            \"\"\"\n            try:\n            # Test if the parameters were inserted correctly.\n                assert len(val) == 3\n\n                min_value, max_value, step = [float(i) for i in val]\n\n                n_values = np.rint((max_value - min_value)/step + 1)\n                vector = np.linspace(min_value, max_value, n_values)\n\n                return vector\n            except :\n                raise Exception(\"Value of '{}' must be a \".format(key)+\\\n                                \"list with three values.\")\n\n\n        self.iter_params = {key:values_to_fit(key, val)\n                            for key, val in self.fit_params.iteritems()}\n\n        # Get the name of the parameters to be fitted\n        self.fit_keys = self.iter_params.keys()\n\n        # Segregate paramates in convolution related and unrelated.\n        ## Get the keys convolution unrelated (i.e. not in ['vrot', 'vmac_rt'])\n        self.no_rot_keys = [key\n                            for key in self.fit_keys\n                            if key not in ['vrot', 'vmac_rt']]\n        ## Get the keys convolution related (i.e. in ['vrot', 'vmac_rt'])\n        self.rot_keys = [key\n                         for key in self.fit_keys\n                         if key in ['vrot', 'vmac_rt']]\n\n\n\n    def fit(self):\n        r\"\"\"\n        Fit a spectral line by iterating on user defined parameter\n        an returns the best fit by minimizing the $\\chi^2$ of the\n        synthetic spectrum and the observed spectrum.\n\n        Based on the homonym IDL software created by Dr. Ivan\n        Hubeny.\n        \"\"\"\n        # Creates the values in which each parameter will be fitted\n        self.sample_params()\n\n        # Create iterator.\n        iter_values = iterator(self.fit_keys, self.iter_params)\n\n        #Obtain the number of varying params\n        n_params = len(self.fit_keys)\n\n        ######\n        # Array to store the values of each parameter and the chisquare\n\n        ## Create an array of NaN\n        chisquare = np.empty([len(iter_values), 1])\n        chisquare.fill(np.nan)\n\n        ## Create the array with the iteration avlues + NaN for the chisquare\n\n        ### Remove the data type of the iter_values array.\n        ### this is necessary in order to add the chisquare array\n        #### Removes data type\n        tmp_array = iter_values.view((float, n_params))\n        #### Guarantee that the format will be correct for any number of\n        #### parameters\n        tmp_array = tmp_array.reshape(len(iter_values), -1)\n\n        ### Join the arrays\n        self.chisq_values = np.hstack((tmp_array, chisquare))\n\n        ### Set the data type for the chisq_values array\n        data_type = self.fit_keys + ['chisquare']\n        self.chisq_values.dtype = {'names':data_type,\n                                   'formats':[float]*len(data_type)}\n        ######\n\n        # Create a library of unconvolved spectra\n        self.build_library()\n\n        # Loop it!\n        for n, it in enumerate(iter_values):\n            self.iteration(n, it)\n\n        # Find the best value\n        self.find_best_fit()\n\n\n    def build_library(self):\n        \"\"\"Build spectra library of unconvolved spectra\"\"\"\n        if len(self.no_rot_keys) > 0 and len(self.rot_keys) > 0:\n            # Build library for non rotation parameters with vsini=vmac_rt=0\n            no_rot_values = iterator(self.no_rot_keys, self.iter_params)\n            for n, it in enumerate(no_rot_values):\n                ## Creates a dic with the parameters and values to be fitted\n                ## in this loop\n                params = {key:val for key, val in zip(it.dtype.names, it)}\n\n                ## Set vsini=vmac_rt=0\n                params['vrot'] = 0\n                params['vmac_rt'] = 0\n\n                ## Check if teff and logg were selected to be fitted.\n                ## If yes, set a variable to them.\n                if 'teff' in params:\n                    self.teff = params.pop('teff')\n\n                if 'logg' in params:\n                    self.logg = params.pop('logg')\n\n                ## Join the abundances\n\n                ### Gets all chemical elements asked to be fit\n                abund = {key:it[key]\n                         for key in it.dtype.names\n                         if (key in PERIODIC) or (key in REVERSE_PERIODIC)}\n                if abund:\n                    ### delete the chemical elements parameters from the\n                    ### dictionary\n                    for key in abund:\n                        del params[key]\n\n                ## Set parameters for synplot\n                synplot_params = deepcopy(self.syn_params)\n                synplot_params.update(params)\n\n                ## Deal with fixed and varying abundances\n                self.merge_abundances(abund, synplot_params)\n\n                ## Synthesize spectrum\n                self.synthesis = Synplot(self.teff, self.logg,\n                                         self.synplot_path, self.idl,\n                                         **synplot_params)\n                self.synthesis.run()\n\n                ## Backup fort.7 and fort.17\n                spec_name = '_'.join(['{}_{}'.format(key, val)\n                                      for key, val in zip(it.dtype.names, it)])\n                shutil.move('{}fort.7'.format(self.synplot_path),\n                            '/tmp/synfit_{}.7'.format(spec_name))\n                shutil.move('{}fort.17'.format(self.synplot_path),\n                            '/tmp/synfit_{}.17'.format(spec_name))\n\n        elif len(self.no_rot_keys) == 0 and len(self.rot_keys) > 0:\n            # There is only 'vrot' or/and 'vmac_rt'. All iteration fits will\n            # be just convolutions. It creates only one spectrum\n\n            ## Set parameters for synplot\n            synplot_params = deepcopy(self.syn_params)\n\n            ## Set values of rotation to 0\n            synplot_params['vrot'] = 0\n            synplot_params['vmac_rt'] = 0\n\n            ## Synthesize spectrum\n            synthesis = Synplot(self.teff, self.logg, self.synplot_path,\n                                self.idl, **synplot_params)\n            synthesis.run()\n\n            ## Backup fort.7 and fort.17\n            shutil.move('{}fort.7'.format(self.synplot_path),\n                        '/tmp/synfit.7')\n            shutil.move('{}fort.17'.format(self.synplot_path),\n                        '/tmp/synfit.17')\n\n        elif len(self.no_rot_keys) > 0 and len(self.rot_keys) == 0:\n            # No rotational parameters\n            # Do not build library.\n            # There is no need since Synspec will have to run every time.\n            pass\n        else:\n            # There is no parameters. Something wen wrong?\n            raise RuntimeError(\"There is no parameters or it was not \" + \\\n                               \"classified as rotational or non rotational. \" +\\\n                               \"It seems that something went wrong.\")\n\n\n    def iteration(self, n, it):\n        \"\"\"Code to be iterated on a loop.\"\"\"\n\n        # Creates a dic with the parameters and values to be fitted\n        #in this loop\n        params = {key:val for key, val in zip(it.dtype.names, it)}\n\n\n        #make plot title before removing teff and logg\n        if self.noplot == False:\n            plot_title = ', '.join(['{}={}'.format(key, val)\n                                    for key, val in params.iteritems()])\n\n        # Check if teff and logg were selected to be fitted.\n        # If yes, set a variable to them.\n        if 'teff' in params:\n            self.teff = params.pop('teff')\n\n        if 'logg' in params:\n            self.logg = params.pop('logg')\n\n        # Join the abundances\n\n        ## Gets all chemical elements asked to be fit\n        abund = {key:it[key]\n                 for key in it.dtype.names\n                 if (key in PERIODIC) or (key in REVERSE_PERIODIC)}\n        if abund:\n            ## delete the chemical elements parameters from the dictionary\n            for key in abund:\n                del params[key]\n\n        # Set parameters for synplot\n        synplot_params = deepcopy(self.syn_params)\n        synplot_params.update(params)\n\n        # Deal with fixed and varying abundances\n        self.merge_abundances(abund, synplot_params)\n\n\n        # Copy not convolved spectrum to Synplot folder\n        if len(self.no_rot_keys) > 0 and len(self.rot_keys) > 0:\n            # Set to not calculate spectrum, just convolve\n            ## I tried to set the parameter 'ispec' to -1 but it didn't work.\n            ## So it will use the parameter 'norun'.\n            synplot_params['norun'] = 1\n\n            ## There are rotational and non rotational parameters\n            spec_name = '_'.join(['{}_{}'.format(key, val)\n                                  for key, val in zip(it.dtype.names, it)\n                                  if key not in ['vrot', 'vmac_rt']])\n            shutil.copy('/tmp/synfit_{}.7'.format(spec_name),\n                        '{}fort.7'.format(self.synplot_path))\n            shutil.copy('/tmp/synfit_{}.17'.format(spec_name),\n                        '{}fort.17'.format(self.synplot_path))\n\n        elif len(self.no_rot_keys) == 0 and len(self.rot_keys) > 0:\n            # Set to not calculate spectrum, just convolve\n            ## I tried to set the parameter 'ispec' to -1 but it didn't work.\n            ## So it will use the parameter 'norun'.\n            synplot_params['norun'] = 1\n\n            ## There is only 'vrot' or/and 'vmac_rt'.\n            shutil.copy('/tmp/synfit.7',\n                        '{}fort.7'.format(self.synplot_path))\n            shutil.copy('/tmp/synfit.17',\n                        '{}fort.17'.format(self.synplot_path))\n        elif len(self.no_rot_keys) > 0 and len(self.rot_keys) == 0:\n            # No rotational parameters\n            pass\n        else:\n            # There is no parameters. Something wen wrong?\n            raise RuntimeError(\"There is no parameters or it was not \" + \\\n                               \"classified as rotational or non rotational. \" +\\\n                               \"It seems that something went wrong.\")\n\n\n        # Synthesize spectrum\n        self.synthesis = Synplot(self.teff, self.logg, self.synplot_path,\n                                 self.idl, **synplot_params)\n        self.synthesis.run()\n\n        # Apply scale and radial velocity if needed\n        if 'scale' in self.synthesis.parameters:\n            self.synthesis.apply_scale()\n\n        self.synthesis.observation[:, 0] *= rvcorr(self.rad_vel)\n\n        #Do an interpolation\n\n        flm = np.interp(self.synthesis.observation[:,0],\n                        self.synthesis.spectrum[:,0],\n                        self.synthesis.spectrum[:,1])\n                        #/max(syn.observation[:,1])\n\n        #Some kind of normalization on the observed flux?\n        fobm = self.synthesis.observation[:,1]#/max(syn.observation[:,1])\n\n        # Calculate the chi**2\n        chisq = np.sum(((fobm - flm)**2/flm) * self.weights)\n        #chisq = chisq * max(fobs)                 #????\n\n        # store the values of the parameters\n        self.chisq_values['chisquare'][n] = chisq\n\n        # Plot, if desired\n        if self.noplot == False:\n            # The synthetic spectrum was corrected by scale and the\n            #observed one by radial velocity. The plot function in Synplot\n            #also does that, so we need to set those parameters to 1 and 0,\n            # respectively.\n            self.synthesis.parameters['scale'] = 1\n            self.synthesis.parameters['rv'] = 0\n\n            # Adds the value of chisquare to the title\n            plot_title += r'$\\chi^2$='+'{:.06f}'.format(chisq)\n            self.synthesis.plot(title=plot_title, windows=self.windows)\n\n\n    @staticmethod\n    def merge_abundances(abund, synplot_params):\n        \"\"\"\n        Merge varying and fixed parameters. It change the `abund` and\n        `synplot_params` in place.\n        \"\"\"\n        # The abundance should be merged individually because it could be\n        # a mix of fixed and varying abundances.\n        if abund and 'abund' in synplot_params:\n            ## Check for overlapping elements.\n            ### Transform all elements to its symbol\n            for key, val in deepcopy(abund).iteritems():\n                try:\n                    abund[REVERSE_PERIODIC[key]] = val\n                    del abund[key]\n                except KeyError:\n                    #### The chemical element is already as a symbol\n                    pass\n\n            for key, val in deepcopy(synplot_params['abund']).iteritems():\n                try:\n                    synplot_params['abund'][REVERSE_PERIODIC[key]] = val\n                    del synplot_params['abund'][key]\n                except KeyError:\n                    #### The chemical element is already as a symbol\n                    pass\n\n            ## Get the fixed abundances\n            try:\n                abund.update({k:v\n                              for k, v in synplot_params['abund'].iteritems()\n                              if k not in deepcopy(abund)})\n            except ValueError:\n                # There no fixed abundance\n                pass\n\n            ## Adds to the synplot_params dictionary\n            synplot_params['abund'] = abund\n        if abund and 'abund' not in synplot_params:\n            synplot_params['abund'] = abund\n\n\n    def find_best_fit(self):\n        \"\"\"\n        Obtain the fitted parameters for the chosen parameters and the\n        value of the chi^2.\n        \"\"\"\n        fitted_vals = self.chisq_values[np.argmin(\n                                        self.chisq_values['chisquare'])]\n\n        self.best_fit = {param:fitted_value\n                           for param, fitted_value\n                           in zip(self.iter_params.keys(),\n                                  fitted_vals.view(float))}\n        self.best_fit['chisquare'] = fitted_vals['chisquare'][0]\n\n\n    def plot_best_fit(self, title=None):\n        \"\"\"\n        Plot the observed spectrum and the synthetic using the best values\n        found.\n\n        Parameters\n        ----------\n\n        title: str (optional);\n            A title for the plot. If the string 'default' is passed, it will\n            contain the parameters fitted with the best values found.\n        \"\"\"\n\n        # Set parameters for synplot\n        synplot_params = deepcopy(self.syn_params)\n        best_fit = deepcopy(self.best_fit)\n        chisq = best_fit.pop('chisquare')\n\n        #make plot title before removing teff and logg\n        if title == 'default':\n            title = r'$\\chi^2$=' + '{:.4f}: '.format(chisq)\n            title += ', '.join(['{}={}'.format(key, val)\n                                    for key, val in best_fit.iteritems()])\n\n        ## Replace parameters for best value\n        if 'teff' in best_fit:\n            self.teff = best_fit.pop('teff')\n\n        if 'logg' in best_fit:\n            self.logg = best_fit.pop('logg')\n\n\n        # Join the abundances\n\n        ## Gets all chemical elements asked to be fit\n        abund = {key:val\n                 for key, val in self.best_fit.iteritems()\n                 if (key in PERIODIC) or (key in REVERSE_PERIODIC)}\n        if abund:\n            for key in abund:\n                del best_fit[key]\n\n        # Deal with fixed and varying abundances\n        self.merge_abundances(abund, synplot_params)\n\n        # Add the best values found to the Synplot parameters\n        for key, value in best_fit.iteritems():\n            synplot_params[key] = value\n\n\n        # Synthesize spectrum\n        synthesis = Synplot(self.teff, self.logg, self.synplot_path,\n                            self.idl, **synplot_params)\n        synthesis.plot(title=title, windows=self.windows)\n\n\n    def plot_chisquare(self, interpolation='linear', logscale=False, **kwargs):\n        \"\"\"\n        Plot the distribution of chi-square for one given parameter.\n        It obly works if the number of parameters to be fitted are one or two.\n\n        Parameters\n        ----------\n\n        interpolation: str (optional);\n            Type of interpolation for the color plot when fitting two\n            parameters. One of ['nearest', 'linear', 'cubic']. More explanation\n            here:\n\n            http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html\n\n        scale: boolean (optional):\n            If set to True, it will plot the logarithmic of the chi-square.\n\n        kwargs;\n            Matplotlib.pyplot.plot kwargs.\n        \"\"\"\n        # Number of parameters fitted.\n        number_params = len(self.fit_keys)\n\n        fig = plt.figure()\n        ax = fig.add_subplot(111)\n\n        if number_params == 1:\n            if logscale:\n                y_axis = np.log(self.chisq_values['chisquare'])\n            else:\n                y_axis = self.chisq_values['chisquare']\n\n            ax.plot(self.iter_params[self.fit_keys[0]],\n                    y_axis, zorder=5, **kwargs)\n\n            xlabel = self.fit_keys[0]\n\n            ax.set_xlabel(xlabel)\n            ax.set_xticks(self.iter_params[xlabel])\n            if xlabel in PERIODIC:\n                ax.set_xticklabels(ax.get_xticks(), rotation=-45)\n\n            ax.set_ylabel(r'$\\chi^2$')\n\n            ax.grid(axis='x', zorder=0)\n        elif number_params == 2:\n            from scipy.interpolate import griddata\n\n            # Transform the chisquare array in a proper array\n            #and not an array of tuples\n            chisq_values = deepcopy(self.chisq_values)\n\n            ## Check for abundance\n            if 'abund' in self.chisq_values.dtype.names:\n                elem = [param for param in self.fit_params.keys()\n                        if param in PERIODIC][0]\n\n                chisq_values['abund'] = [abund\n                                         for abund in chisq_values['abund']]\n\n            ## Removes data type\n            chisquare_arr = chisq_values.view((float, 3))\n            ## Guarantee that the format will be correct for any number of\n            ## parameters\n            chisquare_arr = chisquare_arr.reshape(len(chisq_values), -1)\n\n            edges = np.hstack([(min(param_vector), max(param_vector))\n                               for param_vector in chisquare_arr.T[:-1]])\n\n            # Points in wich the grid will be calculated\n            grid_points = [np.linspace(edges[i], edges[i+1], 200)\n                           for i in np.arange(0, 2*number_params, 2)]\n\n            # Makes a mesh grid to griddata\n            grid_params = np.meshgrid(*grid_points)\n            grid_params = tuple([i for i in grid_params])\n\n            # Grid the data\n            Z = griddata(chisquare_arr[:,:number_params], chisquare_arr[:,-1],\n                         grid_params, method=interpolation)\n\n            if logscale:\n                # Get the log to increase the contrast between limits\n                from matplotlib.colors import LogNorm\n                kwargs['norm'] = LogNorm()\n\n\n            # Plot\n            cs = ax.contour(Z, aspect='auto', extent=edges,\n                            origin='lower', zorder=5, **kwargs)\n            plt.clabel(cs, inline=1)\n\n            # Set labels\n            xlabel = self.fit_keys[0]\n            ylabel = self.fit_keys[1]\n\n            ax.set_xlabel(xlabel)\n            ax.set_xticks(self.iter_params[xlabel])\n            if xlabel in PERIODIC:\n                ax.set_xticklabels(ax.get_xticks(), rotation=-45)\n\n            ax.set_ylabel(ylabel)\n            ax.set_yticks(self.iter_params[ylabel])\n            if ylabel in PERIODIC:\n                ax.set_yticklabels(ax.get_yticks(), rotation=-45)\n\n            ax.grid(zorder=0)\n        else:\n            raise ValueError('The number of parameters is greater than 2.')\n", "meta": {"hexsha": "b265f69a2961383d1308cea7121bf9e4118a2581", "size": 25706, "ext": "py", "lang": "Python", "max_stars_repo_path": "s4/fitting/synfit.py", "max_stars_repo_name": "gabraganca/S4", "max_stars_repo_head_hexsha": "24b4c33fb7caccc52833e31e781fde0f4e25f9bc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-05-05T09:00:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T10:09:28.000Z", "max_issues_repo_path": "s4/fitting/synfit.py", "max_issues_repo_name": "gabraganca/S4", "max_issues_repo_head_hexsha": "24b4c33fb7caccc52833e31e781fde0f4e25f9bc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-03-21T18:19:31.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-30T20:01:18.000Z", "max_forks_repo_path": "s4/fitting/synfit.py", "max_forks_repo_name": "gabraganca/S4", "max_forks_repo_head_hexsha": "24b4c33fb7caccc52833e31e781fde0f4e25f9bc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-22T17:42:08.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-22T17:42:08.000Z", "avg_line_length": 36.0532959327, "max_line_length": 95, "alphanum_fraction": 0.5561347545, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.17042094252059772}}
{"text": "#!/usr/bin/env python\n\"\"\"\nCalculate Fisher matrix and P(k) constraints for all redshift bins for a given \nexperiment.\n\"\"\"\nimport numpy as np\nimport pylab as P\nimport radiofisher as rf\nfrom radiofisher import experiments\nfrom radiofisher.units import *\nfrom mpi4py import MPI\nimport sys\n\ncomm = MPI.COMM_WORLD\nmyid = comm.Get_rank()\nsize = comm.Get_size()\n\n################################################################################\n# Set-up experiment parameters\n################################################################################\n\n# Load cosmology and experimental settings\ne = experiments\ncosmo = experiments.cosmo\n\n# Label experiments with different settings\n#EXPT_LABEL = \"_2yr_3pbwedge\"\nEXPT_LABEL = \"_1bin_4000hr\" #\"_2yr\"\n#EXPT_LABEL = \"_2yr_horizwedge\"\n\n#cosmo['A_xi'] = 0.01\n#cosmo['logkmg'] = np.log10(0.005)\n\n# A_xi: 0.01 0.1\n# logkmg: 0.05, 0.01, 0.005, 0.001\n\nexpt_list = [\n    ( 'exptS',            e.exptS ),        # 0\n    ( 'aexptM',           e.exptM ),        # 1\n    ( 'exptL',            e.exptL ),        # 2\n    ( 'iexptL',           e.exptL ),        # 3\n    ( 'cexptL',           e.exptL ),        # 4\n    ( 'GBT',              e.GBT ),          # 5\n    ( 'Parkes',           e.Parkes ),       # 6\n    ( 'GMRT',             e.GMRT ),         # 7\n    ( 'WSRT',             e.WSRT ),         # 8\n    ( 'APERTIF',          e.APERTIF ),      # 9\n    ( 'VLBA',             e.VLBA ),         # 10\n    ( 'JVLA',             e.JVLA ),         # 11\n    ( 'iJVLA',            e.JVLA ),         # 12\n    ( 'BINGO',            e.BINGO ),        # 13\n    ( 'iBAOBAB32',        e.BAOBAB32 ),     # 14\n    ( 'iBAOBAB128',       e.BAOBAB128 ),    # 15\n    ( 'yCHIME',           e.CHIME ),        # 16\n    ( 'iAERA3',           e.AERA3 ),        # 17\n    ( 'iMFAA',            e.MFAA ),         # 18\n    ( 'yTIANLAIpath',     e.TIANLAIpath ),  # 19\n    ( 'yTIANLAI',         e.TIANLAI ),      # 20\n    ( 'yTIANLAIband2',    e.TIANLAIband2 ), # 21\n    ( 'FAST',             e.FAST ),         # 22\n    ( 'KAT7',             e.KAT7 ),         # 23\n    ( 'iKAT7',            e.KAT7 ),         # 24\n    ( 'cKAT7',            e.KAT7 ),         # 25\n    ( 'MeerKATb1',        e.MeerKATb1 ),    # 26\n    ( 'iMeerKATb1',       e.MeerKATb1 ),    # 27\n    ( 'cMeerKATb1',       e.MeerKATb1 ),    # 28\n    ( 'MeerKATb2',        e.MeerKATb2 ),    # 29\n    ( 'iMeerKATb2',       e.MeerKATb2 ),    # 30\n    ( 'cMeerKATb2',       e.MeerKATb2 ),    # 31\n    ( 'ASKAP',            e.ASKAP ),        # 32\n    ( 'SKA1MIDbase1',     e.SKA1MIDbase1 ), # 33\n    ( 'iSKA1MIDbase1',    e.SKA1MIDbase1 ), # 34\n    ( 'cSKA1MIDbase1',    e.SKA1MIDbase1 ), # 35\n    ( 'SKA1MIDbase2',     e.SKA1MIDbase2 ), # 36\n    ( 'iSKA1MIDbase2',    e.SKA1MIDbase2 ), # 37\n    ( 'cSKA1MIDbase2',    e.SKA1MIDbase2 ), # 38\n    ( 'SKA1MIDfull1',     e.SKA1MIDfull1 ), # 39\n    ( 'iSKA1MIDfull1',    e.SKA1MIDfull1 ), # 40\n    ( 'cSKA1MIDfull1',    e.SKA1MIDfull1 ), # 41\n    ( 'SKA1MIDfull2',     e.SKA1MIDfull2 ), # 42\n    ( 'iSKA1MIDfull2',    e.SKA1MIDfull2 ), # 43\n    ( 'cSKA1MIDfull2',    e.SKA1MIDfull2 ), # 44\n    ( 'fSKA1SURbase1',    e.SKA1SURbase1 ), # 45\n    ( 'fSKA1SURbase2',    e.SKA1SURbase2 ), # 46\n    ( 'fSKA1SURfull1',    e.SKA1SURfull1 ), # 47\n    ( 'fSKA1SURfull2',    e.SKA1SURfull2 ), # 48\n    ( 'exptCV',           e.exptCV ),       # 49\n    ( 'GBTHIM',           e.GBTHIM ),       # 50\n    ( 'SKA0MID',          e.SKA0MID ),      # 51\n    ( 'fSKA0SUR',         e.SKA0SUR ),      # 52\n    ( 'SKA1MID900',       e.SKA1MID900 ),   # 53\n    ( 'SKA1MID350',       e.SKA1MID350 ),   # 54\n    ( 'iSKA1MID900',      e.SKA1MID900 ),   # 55\n    ( 'iSKA1MID350',      e.SKA1MID350 ),   # 56\n    ( 'fSKA1SUR650',      e.SKA1SUR650 ),   # 57\n    ( 'fSKA1SUR350',      e.SKA1SUR350 ),   # 58\n    ( 'aSKA1LOW',         e.SKA1LOW ),      # 59\n    ( 'SKAMID_PLUS',      e.SKAMID_PLUS ),  # 60\n    ( 'SKAMID_PLUS2',     e.SKAMID_PLUS2 ), # 61\n    ( 'yCHIME_nocut',     e.CHIME_nocut ),  # 62\n    ( 'yCHIME_avglow',    e.CHIME_avglow ), # 63\n    ( 'MID_B1_Base',      e.MID_B1_Base ),  # 64\n    ( 'MID_B1_Alt',       e.MID_B1_Alt ),   # 65\n    ( 'MID_B2_Base',      e.MID_B2_Base ),  # 66\n    ( 'MID_B2_Upd',       e.MID_B2_Upd ),   # 67\n    ( 'MID_B2_Alt',       e.MID_B2_Alt ),   # 68\n    ( 'aLOW_Base',        e.LOW_Base ),     # 69\n    ( 'aLOW_Upd',         e.LOW_Upd ),      # 70\n    ( 'aLOW_Alt',         e.LOW_Alt ),      # 71\n    ( 'MID_B2_Alt2',      e.MID_B2_Alt2 ),  # 72\n    ( 'iMID_B1_Base',     e.MID_B1_Base ),  # 73\n    ( 'iMID_B1_Alt',      e.MID_B1_Alt ),   # 74\n    ( 'iMID_B2_Base',     e.MID_B2_Base ),  # 75\n    ( 'hMID_B1_Rebase',   e.MID_B1_Rebase), # 76\n    ( 'hMID_B1_Octave',   e.MID_B1_Octave), # 77\n    ( 'hMID_B2_Rebase',   e.MID_B2_Rebase), # 78\n    ( 'hMID_B2_Octave',   e.MID_B2_Octave), # 79\n    ( 'iCVTEST1',         e.CVlimited_z0to3), # 80\n    ( 'iCVTEST2',         e.CVlimited_z2to5), # 81\n    ( 'iHIRAX',           e.HIRAX),         # 82\n    ( 'iCosVis32x32',     e.CosVis32x32),   # 83\n    ( 'iCosVis32x32_dmin10m', e.CosVis32x32_dmin10m), # 84\n    ( 'iCosVis256x256',   e.CosVis256x256),   # 85\n    ( 'MID_B1_RedBook',   e.MID_B1_RedBook), # 86\n    ( 'MID_B2_RedBook',   e.MID_B2_RedBook), # 87\n    ( 'MID_B1_SKAonly_RedBook', e.MID_B1_SKAonly_RedBook), # 88\n    ( 'MID_B1_MK_RedBook', e.MID_B1_MK_RedBook), # 89\n    ( 'MID_B2_MK_RedBook', e.MID_B2_MK_RedBook), # 90\n    ( 'iHIRAX_highz',      e.HIRAX_highz),  # 91\n    ( 'MeerKATL',      e.MeerKAT_Lband),    # 92\n    ( 'MeerKATUHF',        e.MeerKAT_UHF),  # 93\n]\nnames, expts = zip(*expt_list)\nnames = list(names); expts = list(expts)\n\n################################################################################\n\n# Take command-line argument for which survey to calculate, or set manually\nif len(sys.argv) > 1:\n    k = int(sys.argv[1])\n    try:\n        Sarea = float(sys.argv[2])\n    except:\n        Sarea = None\n        pass\nelse:\n    raise IndexError(\"Need to specify ID for experiment.\")\n\nnames[k] += EXPT_LABEL\nif myid == 0:\n    print(\"=\"*50)\n    print(\"Survey:\", names[k])\n    print(\"=\"*50)\n\n# Tweak settings depending on chosen experiment\ncv_limited = False\nexpts[k]['mode'] = \"dish\"\nif names[k][0] == \"i\": expts[k]['mode'] = \"idish\"\nif names[k][0] == \"c\": expts[k]['mode'] = \"combined\"\nif names[k][0] == \"y\": expts[k]['mode'] = \"icyl\"\nif names[k][0] == \"f\": expts[k]['mode'] = \"paf\"\nif names[k][0] == \"t\": expts[k]['mode'] = \"ipaf\"\nif names[k][0] == \"a\": expts[k]['mode'] = \"iaa\"\nif names[k][0] == \"h\": expts[k]['mode'] = \"hybrid\"\n\nexpt = expts[k]\nif Sarea is None:\n    survey_name = names[k]\n    root = \"output/\" + survey_name\nelse:\n    expt['Sarea'] = Sarea * (D2RAD)**2.\n    survey_name = names[k] + \"_\" + str(int(Sarea))\n    root = \"output/\" + survey_name\n\n# Define redshift bins\nexpt_zbins = rf.overlapping_expts(expt)\nzs, zc = rf.zbins_equal_spaced(expt_zbins, dz=0.1)\n#zs, zc = rf.zbins_equal_spaced(expt_zbins, dz=0.25) # 0.2\n#zs, zc =  rf.zbins_const_dnu(expt_zbins, cosmo, dnu=20.)\n#zs, zc = rf.zbins_const_dr(expt_zbins, cosmo, bins=14)\n#zs, zc = rf.zbins_const_dnu(expt_zbins, cosmo, dnu=60.)\n#zs, zc = rf.zbins_const_dnu(expt_zbins, cosmo, dnu=30.)\n#zs = rf.zbins_fixed(expt_zbins, dz=0.1)\n\n# FIXME\n#print(\"FIXME! zbins set to manual\")\n#zs = np.array([0.25, 0.48])\n#zc = 0.5*(zs[1:] + zs[:-1])\n\n\n# Define kbins (used for output)\nkbins = np.logspace(np.log10(0.001), np.log10(1.), 61)\n#cosmo['f0_kbins'] = np.array([1e-4, 1e-2, 1e-1, 1e1])\n\nexpt['epsilon_fg'] = 1e-14\n#expt['ttot'] *= 17520. / 1e4 #8765. / 1e4 # 2 calendar years on-sky\nexpt['ttot'] *= 4000. / 1e4 #8765. / 1e4\nexpt['k_nl0'] = 0.2 # = 0.3 h/Mpc\nexpt['wedge'] = False #'horizon' #'3pb' #False\n\n# Neutrino mass\ncosmo['mnu'] = 0.\n\n# Precompute cosmological functions, P(k), massive neutrinos, and T(k) for f_NL\ncosmo_fns = rf.background_evolution_splines(cosmo)\nif cosmo['mnu'] != 0.:\n    # Massive neutrinos\n    mnu_str = \"mnu%03d\" % (cosmo['mnu']*100.)\n    fname_pk = \"cache_pk_%s.dat\" % mnu_str\n    fname_nu = \"cache_%s\" % mnu_str\n    survey_name += mnu_str; root += mnu_str\n    cosmo = rf.load_power_spectrum(cosmo, fname_pk, comm=comm)\n    mnu_fn = rf.deriv_neutrinos(cosmo, fname_nu, mnu=cosmo['mnu'], comm=comm)\nelse:\n    # Normal operation (no massive neutrinos or non-Gaussianity)\n    cosmo = rf.load_power_spectrum(cosmo, \"cache_pk.dat\", comm=comm)\n    mnu_fn = None\n\n# Non-Gaussianity\n#transfer_fn = rf.deriv_transfer(cosmo, \"cache_transfer.dat\", comm=comm)\ntransfer_fn = None\n\n# Effective no. neutrinos, N_eff\n#Neff_fn =  rf.deriv_neutrinos(cosmo, \"cache_Neff\", Neff=cosmo['N_eff'], comm=comm)\nNeff_fn = None\n\n# Optional additional parameters\nswitches = []\n#switches = ['mg', ] #'sdbias']\n\n# Scale-dependent growth\n#cosmo['fs8_kbins'] = [0., 1e-2, 1e-1, 1e0, 1e2]\n\nH, r, D, f = cosmo_fns\n\n################################################################################\n# Store cosmological functions\n################################################################################\n\n# Store values of cosmological functions\nif myid == 0:\n    # Calculate cosmo fns. at redshift bin centroids and save\n    _H = H(zc)\n    _dA = r(zc) / (1. + np.array(zc))\n    _D = D(zc)\n    _f = f(zc)\n    np.savetxt(root+\"-cosmofns-zc.dat\", np.column_stack((zc, _H, _dA, _D, _f)))\n    \n    # Calculate cosmo fns. as smooth fns. of z and save\n    zz = np.linspace(0., 1.05*np.max(zc), 1000)\n    _H = H(zz)\n    _dA = r(zz) / (1. + zz)\n    _D = D(zz)\n    _f = f(zz)\n    np.savetxt(root+\"-cosmofns-smooth.dat\", np.column_stack((zz, _H, _dA, _D, _f)) )\n\n# Precompute derivs for all processes\neos_derivs = rf.eos_fisher_matrix_derivs(cosmo, cosmo_fns, fsigma8=True)\n\n\"\"\"\n# Output all cosmo/instrumental parameters\nprint \"*\"*50\nfor key in cosmo.keys():\n    print \"%20s: %s\" % (key, cosmo[key])\nprint \"*\"*50\nfor key in expt.keys():\n    print \"%20s: %s\" % (key, expt[key])\nprint \"*\"*50\n\"\"\"\n\n################################################################################\n# Loop through redshift bins, assigning them to each process\n################################################################################\n\nfor i in range(zs.size-1):\n    if i % size != myid:\n      continue\n    print(\">>> %2d working on redshift bin %d / %d -- z = %3.3f\" \\\n          % (myid, i, zs.size, zc[i]))\n    \n    # Calculate effective experimental params. in the case of overlapping expts.\n    Sarea_rad = Sarea*(D2RAD)**2. if Sarea is not None else None\n    expt_eff = rf.overlapping_expts(expt, zs[i], zs[i+1], Sarea=Sarea_rad)\n    \n    # Calculate basic Fisher matrix\n    # (A, bHI, Tb, sigma_NL, sigma8, n_s, f, aperp, apar, [Mnu], [fNL], [pk]*Nkbins)\n    F_pk, kc, binning_info, paramnames = rf.fisher( \n                                         zs[i], zs[i+1], cosmo, expt_eff, \n                                         cosmo_fns=cosmo_fns,\n                                         transfer_fn=transfer_fn,\n                                         massive_nu_fn=mnu_fn,\n                                         Neff_fn=Neff_fn,\n                                         return_pk=True,\n                                         cv_limited=cv_limited, \n                                         switches=switches,\n                                         kbins=kbins )\n    \n    # Expand Fisher matrix with EOS parameters\n    ##F_eos =  rf.fisher_with_excluded_params(F, [10, 11, 12]) # Exclude P(k)\n    F_eos, paramnames = rf.expand_fisher_matrix(zc[i], eos_derivs, F_pk, \n                                                names=paramnames, exclude=[], \n                                                fsigma8=True)\n    \n    # Expand Fisher matrix for H(z), dA(z)\n    # Replace aperp with dA(zi), using product rule. aperp(z) = dA(fid,z) / dA(z)\n    # (And convert dA to Gpc, to help with the numerics)\n    paramnames[paramnames.index('aperp')] = 'DA'\n    da = r(zc[i]) / (1. + zc[i]) / 1000. # Gpc\n    F_eos[7,:] *= -1. / da\n    F_eos[:,7] *= -1. / da\n    \n    # Replace apar with H(zi)/100, using product rule. apar(z) = H(z) / H(fid,z)\n    paramnames[paramnames.index('apar')] = 'H'\n    F_eos[8,:] *= 1. / H(zc[i]) * 100.\n    F_eos[:,8] *= 1. / H(zc[i]) * 100.\n    \n    # Save Fisher matrix and k bins\n    np.savetxt(root+\"-fisher-full-%d.dat\" % i, F_eos, header=\" \".join(paramnames))\n    if myid == 0: np.savetxt(root+\"-fisher-kc.dat\", kc)\n    \n    # Save P(k) rebinning info\n    np.savetxt(root+\"-rebin-Fbase-%d.dat\" % i, np.array(binning_info['F_base']) )\n    np.savetxt(root+\"-rebin-cumul-%d.dat\" % i, np.array(binning_info['cumul']) )\n    np.savetxt(root+\"-rebin-kgrid-%d.dat\" % i, np.array(binning_info['kgrid']) )\n    np.savetxt(root+\"-rebin-Vfac-%d.dat\" % i, np.array([binning_info['Vfac'],]) )\n\ncomm.barrier()\nif myid == 0: print(\"Finished.\")\n", "meta": {"hexsha": "a5060eed317280c86bdeb39ae95e2db417cb35a8", "size": 12693, "ext": "py", "lang": "Python", "max_stars_repo_path": "full_experiment.py", "max_stars_repo_name": "sjforeman/RadioFisher", "max_stars_repo_head_hexsha": "fe25f969de9a700c5697168ba9e0d2645c55ed81", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-12-05T11:28:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-09T02:42:21.000Z", "max_issues_repo_path": "full_experiment.py", "max_issues_repo_name": "sjforeman/RadioFisher", "max_issues_repo_head_hexsha": "fe25f969de9a700c5697168ba9e0d2645c55ed81", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "full_experiment.py", "max_forks_repo_name": "sjforeman/RadioFisher", "max_forks_repo_head_hexsha": "fe25f969de9a700c5697168ba9e0d2645c55ed81", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-09T02:42:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-30T06:37:47.000Z", "avg_line_length": 38.5805471125, "max_line_length": 84, "alphanum_fraction": 0.5210746081, "include": true, "reason": "import numpy", "num_tokens": 4629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.30735800417608683, "lm_q1q2_score": 0.17042093548482382}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n.. py:currentmodule:: xray.mac.models.chantler2005\n.. moduleauthor:: Hendrix Demers <hendrix.demers@mail.mcgill.ca>\n\nChantler 2005 MAC model.\n\"\"\"\n\n###############################################################################\n# Copyright 2021 Hendrix Demers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n###############################################################################\n\n# Standard library modules.\nimport csv\nimport logging\n\n# Third party modules.\nfrom scipy.interpolate import interp1d\n\n# Local modules.\nfrom xray.mac import get_current_module_path\n\n# Globals and constants variables.\nSECTION_NAME = \"Chantler2005\"\nOPTION_PATHNAME = \"pathname\"\nOPTION_FILENAME = \"filename\"\nOPTION_ENERGY_UNIT = \"energyUnit\"\n\nENERGIES_eV = \"energies_eV\"\nMAC_cm2_g = \"mac_cm2_g\"\n\nENERGY_UNIT_eV = \"eV\"\nENERGY_UNIT_keV = \"keV\"\n\n\nclass Chantler2005:\n    def __init__(self):\n        self.minimum_energy_eV = 0.0\n        self.minimum_mac_cm2_g = 0.0\n\n        self.mac_data = {}\n        self.edge_energies_eV = {}\n\n        self.experimental_data = {}\n\n    def read_mac_data(self, file_path=None, energy_unit=ENERGY_UNIT_keV):\n        if file_path is None:\n            file_path = get_current_module_path(__file__, \"../../../data/chantler2005/FFastMAC.csv\")\n        self.reset_data()\n        input_file = csv.reader(open(file_path))\n\n        for items in input_file:\n            self.extract_data_from_items_line(items, energy_unit)\n\n    def reset_data(self):\n        self.experimental_data = {}\n\n    def extract_data_from_items_line(self, items, energy_unit):\n        index = 0\n        maximum_index = len(items)\n        atomic_number = 1\n\n        while index < maximum_index:\n            try:\n                if items[index] != '':\n                    if energy_unit == ENERGY_UNIT_keV:\n                        energy_keV = float(items[index])  # noqa\n                        energy_eV = energy_keV * 1.0e3  # noqa\n                    else:\n                        energy_eV = float(items[index])  # noqa\n\n                    mac_cm2_g = float(items[index+1])\n\n                    if energy_eV > 0.0:\n                        self.experimental_data.setdefault(atomic_number, {})\n                        self.experimental_data[atomic_number].setdefault(ENERGIES_eV, []).append(energy_eV)\n                        self.experimental_data[atomic_number].setdefault(MAC_cm2_g, []).append(mac_cm2_g)\n            except ValueError as status:\n                logging.error(status)\n                logging.info(items)\n\n            atomic_number += 1\n            index += 2\n\n    def compute_mac_cm2_g(self, energy_emitter_eV, atomic_number_absorber):  # noqa\n        return self._compute_mac_cm2_g(energy_emitter_eV, atomic_number_absorber)\n\n    def _compute_mac_cm2_g(self, energyEmitter_eV, atomic_number_absorber):  # noqa\n        if atomic_number_absorber not in self.mac_data:\n            self.read_mac_data()\n\n            energies_eV = self.experimental_data[atomic_number_absorber][ENERGIES_eV]  # noqa\n            macs_cm2_g = self.experimental_data[atomic_number_absorber][MAC_cm2_g]\n\n            if len(energies_eV) > 0:\n                self.mac_data.setdefault(atomic_number_absorber, {})\n\n                self.minimum_energy_eV = energies_eV[0]\n\n                self.minimum_mac_cm2_g = macs_cm2_g[0]\n\n                self.maximum_energy_eV = energies_eV[-1]\n\n                self.maximum_mac_cm2_g = macs_cm2_g[-1]\n\n                self.mac_data[atomic_number_absorber] = interp1d(energies_eV, macs_cm2_g)\n\n            else:\n                logging.error(\"No mac for %i and %0.1f\", atomic_number_absorber, energyEmitter_eV)\n                return 0.0\n\n        if energyEmitter_eV <= self.minimum_energy_eV:\n            return self.minimum_mac_cm2_g\n\n        if energyEmitter_eV >= self.maximum_energy_eV:\n            return self.maximum_mac_cm2_g\n\n        if atomic_number_absorber in self.mac_data:\n            try:\n                mac_value = self.mac_data[atomic_number_absorber](energyEmitter_eV)\n            except ValueError:\n                print(atomic_number_absorber, energyEmitter_eV)\n                mac_value = self.minimum_mac_cm2_g\n            return mac_value\n        else:\n            logging.error(\"No mac for %i and %0.1f\", atomic_number_absorber, energyEmitter_eV)\n            return 0.0\n\n\ndef compare_all_versions():\n    import matplotlib.pyplot as plt\n    from xray.mac.models.ionization_energies import IonizationEnergies, SUBSHELLS\n\n    mac = Chantler2005()\n\n    atomic_numbers = [1, 6, 22, 92]\n    filenames = {\"Default\": \"FFastMAC.csv\", \"NISTMonte2\": \"FFastMAC_nistMonte2.csv\", \"DTSA2\": \"FFastMAC_DTSA2.csv\"}\n\n    for atomic_number in atomic_numbers:\n        plt.figure()\n        for filename_key in filenames:\n            filename = filenames[filename_key]\n\n            if filename_key == \"NISTMonte2\":\n                file_path = get_current_module_path(__file__, \"../../data/chantler2005/%s\" % filename)\n                mac.read_mac_data(file_path, ENERGY_UNIT_eV)\n            else:\n                file_path = get_current_module_path(__file__, \"../../data/chantler2005/%s\" % filename)\n                mac.read_mac_data(file_path)\n\n            energies_eV = mac.experimental_data[atomic_number][ENERGIES_eV]  # noqa\n            mac_cm2_g = mac.experimental_data[atomic_number][MAC_cm2_g]\n\n            if filename_key == \"Default\":\n                plt.loglog(energies_eV, mac_cm2_g, '.', label=filename_key)\n            else:\n                plt.loglog(energies_eV, mac_cm2_g, label=filename_key)\n\n        plt.legend()\n        plt.title(atomic_number)\n\n        ionization_energies = IonizationEnergies()\n\n        for subshell in SUBSHELLS:\n            edge_energy_eV = ionization_energies.ionization_energy_eV(atomic_number, subshell)  # noqa\n            if edge_energy_eV > 0.0:\n                plt.axvline(edge_energy_eV, zorder=-10)\n    plt.show()\n\n\ndef create_hdf5_file():\n    import h5py\n    import numpy as np\n\n    filename = \"chantler2005.hdf5\"\n    file_path = get_current_module_path(__file__, \"../../data/chantler2005/%s\" % filename)\n\n    with h5py.File(file_path, \"w\") as hdf5_file:\n        mac = Chantler2005()\n        mac.read_mac_data()\n\n        group_elements = hdf5_file.require_group(\"elements\")\n\n        for atomic_number in sorted(mac.experimental_data.keys()):\n            group_name = \"{:02d}\".format(atomic_number)\n            group_atomic_number = group_elements.require_group(group_name)\n            energies_eV = np.array(mac.experimental_data[atomic_number][ENERGIES_eV])  # noqa\n            macs_cm2_g = np.array(mac.experimental_data[atomic_number][MAC_cm2_g])\n\n            group_atomic_number.create_dataset(ENERGIES_eV, data=energies_eV)\n            group_atomic_number.create_dataset(MAC_cm2_g, data=macs_cm2_g)\n", "meta": {"hexsha": "ab19300361efbf08c8390454470fa8a33921c97c", "size": 7316, "ext": "py", "lang": "Python", "max_stars_repo_path": "xray/mac/models/chantler2005.py", "max_stars_repo_name": "drix00/pyxraymac", "max_stars_repo_head_hexsha": "f9e2c4e073ff1f5d9fbfaa58b3b66c041433896a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "xray/mac/models/chantler2005.py", "max_issues_repo_name": "drix00/pyxraymac", "max_issues_repo_head_hexsha": "f9e2c4e073ff1f5d9fbfaa58b3b66c041433896a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xray/mac/models/chantler2005.py", "max_forks_repo_name": "drix00/pyxraymac", "max_forks_repo_head_hexsha": "f9e2c4e073ff1f5d9fbfaa58b3b66c041433896a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5145631068, "max_line_length": 115, "alphanum_fraction": 0.6354565336, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.17035914561326648}}
{"text": "\"\"\"Implementation of :class:`RealMesh` and :class:`ComplexMesh`, along with FFT engines.\"\"\"\n\nimport os\nimport ctypes\nimport numbers\n\nimport numpy as np\nfrom numpy import ctypeslib\nfrom numpy.lib.mixins import NDArrayOperatorsMixin as NDArrayLike\n\nfrom . import utils\nfrom .utils import BaseClass, BaseMetaClass\n\n\nclass MeshError(Exception):\n\n    \"\"\"Exception raised when issue with mesh.\"\"\"\n\n\nclass SetterProperty(object):\n    \"\"\"\n    Attribute setter, runs ``func`` when setting a class attribute.\n    Taken from https://stackoverflow.com/questions/17576009/python-class-property-use-setter-but-evade-getter\n    \"\"\"\n    def __init__(self, func, doc=None):\n        self.func = func\n        self.__doc__ = doc if doc is not None else func.__doc__\n\n    def __set__(self, obj, value):\n        return self.func(obj, value)\n\n\nclass BaseMesh(NDArrayLike,BaseClass,metaclass=BaseMetaClass):\n    \"\"\"\n    Base implementation for mesh.\n    What follows are just methods to make :class:`BaseMesh` behave like a numpy array.\n    numpy functions can be applied directly to any instance ``mesh`` through e.g.::\n\n        np.sum(mesh)\n\n    Note\n    ----\n    To get a deep copy of the mesh (including :attr:`value`), use :meth:`deepcopy`.\n    :meth:`copy` will return a shallow copy.\n\n    Attributes\n    ----------\n    value : array\n        Numpy array holding mesh values, or ``None`` when unset.\n        Can be set any time using ``mesh.value = newvalue``.\n\n    info : MeshInfo\n        Mesh information (boxsize, boxcenter, nmesh, etc.).\n\n    attrs : dict\n        Dictionary of other attributes.\n\n    boxsize : array\n        See :class:`MeshInfo`.\n\n    boxcenter : array\n        See :class:`MeshInfo`.\n\n    nmesh : array\n        See :class:`MeshInfo`.\n\n    cellsize : array\n        See :class:`MeshInfo`.\n\n    ndim : array\n        See :class:`MeshInfo`.\n    \"\"\"\n    _attrs = ['info', 'nthreads', 'attrs']\n    _HANDLED_TYPES = (np.ndarray, numbers.Number)\n\n    _path_lib = os.path.join(utils.lib_dir, 'mesh_{}.so')\n\n    def __init__(self, value=None, info=None, nthreads=None, attrs=None, **kwargs):\n        \"\"\"\n        Initalize :class:`BaseMesh`.\n\n        Parameters\n        ----------\n        value : array, default=None\n            Numpy array holding mesh values, or ``None`` (can set later through ``mesh.value = value``.\n\n        info : MeshInfo, default=None\n            Mesh information (boxsize, boxcenter, nmesh, etc.),\n            copied and updated with ``kwargs``.\n\n        nthreads : int, default=None\n            Number of threads to use in mesh calculations; defaults to OpenMP's default.\n\n        attrs : dict\n            Dictionary of other attributes.\n\n        kwargs : dict\n            Arguments for :class:`MeshInfo`.\n        \"\"\"\n        if info is None:\n            self.info = MeshInfo(value=value, **kwargs)\n        else:\n            self.info = info.clone(value=value, **kwargs)\n        self.value = None\n        self.dtype = self.info.dtype\n        self.value = value\n        self.set_num_threads(nthreads)\n        self.attrs = attrs or {}\n        self.fft_engine = None\n\n    @property\n    def shape(self):\n        return tuple(self.nmesh)\n\n    @property\n    def size(self):\n        return np.prod(self.shape)\n\n    @property\n    def _type_float_mesh(self):\n        # Return ctypes-type for numpy array\n        return ctypeslib.ndpointer(dtype=self._type_float, shape=self.size, flags='C')\n\n    @property\n    def dtype(self):\n        return self.info.dtype\n\n    @dtype.setter\n    def dtype(self, dtype):\n        \"\"\"Called when setting :attr:`dtype`, loading the relevant C-library.\"\"\"\n        self.info.dtype = dtype\n        self.value = self.value\n        self._lib = ctypes.CDLL(self._path_lib.format(self._precision), mode=ctypes.RTLD_LOCAL)\n\n    def set_num_threads(self, nthreads=None):\n        \"\"\"Set number of OpenMP threads used in mesh calculations.\"\"\"\n        if nthreads is not None:\n            func = self._lib.set_num_threads\n            func.argtypes = (ctypes.c_int,)\n            func(nthreads)\n\n    @property\n    def nthreads(self):\n        \"\"\"Number of OpenMP threads.\"\"\"\n        func = self._lib.get_num_threads\n        func.restype = ctypes.c_int\n        return func()\n\n    def __mul__(self, other):\n        r = self.deepcopy(copy_value=False)\n        r.value = r.value * other\n        return r\n\n    def __imul__(self, other):\n        self.value *= other\n        return self\n\n    def __div__(self, other):\n        r = self.deepcopy(copy_value=False)\n        r.value = r.value / other\n        return r\n\n    __truediv__ = __div__\n\n    def __rdiv__(self, other):\n        r = self.deepcopy()\n        r.value = other / r.value\n        return r\n\n    __rtruediv__ = __rdiv__\n\n    def __idiv__(self, other):\n        self.value /= other\n        return self\n\n    __itruediv__ = __idiv__\n\n    def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):\n        # Taken from https://numpy.org/doc/stable/reference/generated/numpy.lib.mixins.NDArrayOperatorsMixin.html\n        # See also https://github.com/rainwoodman/pmesh/blob/master/pmesh/pm.py\n        out = kwargs.get('out', ())\n        for x in inputs + out:\n            # Only support operations with instances of _HANDLED_TYPES.\n            # Use BaseMesh instead of type(self) for isinstance to\n            # allow subclasses that don't override __array_ufunc__ to\n            # handle BaseMesh objects.\n            if not isinstance(x, self._HANDLED_TYPES + (BaseMesh,)):\n                return NotImplemented\n\n        # Defer to the implementation of the ufunc on unwrapped values.\n        inputs = tuple(x.value if isinstance(x, BaseMesh) else x\n                       for x in inputs)\n        if out:\n            kwargs['out'] = tuple(\n                x.value if isinstance(x, BaseMesh) else x\n                for x in out)\n        result = getattr(ufunc, method)(*inputs, **kwargs)\n\n        def cast(result):\n            # booleans, cannot be reasonable BaseMesh objects\n            # just return the ndarray\n            if result.dtype == '?':\n                return result\n            # different shape, cannot be reasonable Field objects\n            # just return the ndarray\n            if result.shape != self.shape:\n                return result\n            # really only cast when we are using simple +-* **, etc.\n            new = self.deepcopy(copy_value=False)\n            new.value = result\n            return new\n\n        if type(result) is tuple:\n            # multiple return values\n            return tuple(cast(x) for x in result)\n        elif method == 'at':\n            # no return value\n            return None\n        else:\n            # one return value\n            return cast(result)\n\n    def __getitem__(self, index):\n        return self.value.__getitem__(index)\n\n    def __setitem__(self, index, value):\n        return self.value.__setitem__(index, value)\n\n    def __array__(self, dtype=None):\n        return self.value\n\n    @SetterProperty\n    def value(self, value):\n        if value is not None:\n            if isinstance(value, np.ndarray) and value.size == self.size:\n                value.shape = self.shape\n                value = value.astype(self.dtype, copy=False, order='C')\n            else:\n                value_ = value\n                value = np.empty(shape=self.shape, dtype=self.dtype, order='C')\n                value[...] = value_\n        self.__dict__['value'] = value\n\n    def zeros_like(self):\n        new = self.deepcopy(copy_value=False)\n        new.value = np.zeros(shape=self.shape, dtype=self.dtype, order='C')\n        return new\n\n    def empty_like(self, *args, **kwargs):\n        new = self.deepcopy(copy_value=False)\n        new.value = np.empty(shape=self.shape, dtype=self.dtype, order='C')\n        return new\n\n    def __repr__(self):\n        info = ['{}={}'.format(name,getattr(self.info, name)) for name in self.info._attrs]\n        return '{}({})'.format(self.__class__.__name__,', '.join(info))\n\n    def _copy_value(self, out=None):\n        if out is None: out = np.empty_like(self.value)\n        func = self._lib.copy\n        func.argtypes = (self._type_float_mesh, self._type_float_mesh, ctypes.c_size_t)\n        func.restype = ctypes.c_int\n        self.value.shape = out.shape = -1\n        flag = func(self.value, out, self.size)\n        if (flag != 0):\n            raise MeshError('Issue with _copy_value')\n        self.value.shape = out.shape = self.shape\n        return out\n\n    def deepcopy(self, copy_value=True):\n        kwargs = {name:getattr(self,name) for name in self._attrs}\n        kwargs['info'] = kwargs['info'].deepcopy()\n        new = self.__class__(self._copy_value() if copy_value and self.value is not None else self.value,**kwargs)\n        new.fft_engine = self.fft_engine\n        return new\n\n    def get_fft_engine(self, engine='numpy', **kwargs):\n        \"\"\"\n        Return engine for fast Fourier transform.\n\n        Parameters\n        ----------\n        engine : string, BaseFFTEngine, default='numpy'\n            If string, use 'numpy' or 'fftw' (package pyfftw must be installed);\n            else a FFT engine.\n\n        kwargs : dict\n            Options for the FFT engines, used if ``engine`` is a FFT engine name (string).\n            See :class:`NumpyFFTEngine` and :class:`FFTWEngine`.\n\n        Returns\n        -------\n        engine : BaseFFTEngine\n            FFT engine.\n        \"\"\"\n        kwargs.setdefault('nthreads',self.nthreads)\n        return get_fft_engine(engine,shape=self.shape,type_real=self.dtype,**kwargs)\n\n    def set_fft_engine(self, engine='numpy', **kwargs):\n        \"\"\"\n        Set engine for fast Fourier transform.\n        See :meth:`get_fft_engine`.\n        \"\"\"\n        self.fft_engine = self.get_fft_engine(engine=engine, **kwargs)\n\n\ndef _make_property(name):\n\n    @property\n    def func(self):\n        return getattr(self.info, name)\n\n    return func\n\nfor name in ['boxsize', 'boxcenter', 'nmesh', 'offset', 'cellsize', 'ndim', '_precision', '_type_float']:\n    setattr(BaseMesh, name, _make_property(name))\n\n\nclass MeshInfo(BaseClass):\n    \"\"\"\n    Class holding mesh information.\n\n    Attributes\n    ----------\n    dtype : np.dtype\n        Type for mesh array.\n\n    nmesh : array\n        Mesh size, i.e. number of mesh nodes along each axis.\n\n    boxsize : array\n        Physical size of the box.\n\n    boxcenter : array\n        Box center.\n    \"\"\"\n    _attrs = ['dtype', 'nmesh', 'boxsize', 'boxcenter']\n\n    def __init__(self, nmesh=None, boxsize=None, boxcenter=None, cellsize=None, value=None, positions=None, boxpad=1.5, dtype=None):\n        \"\"\"\n        Initalize :class:`MeshInfo`.\n\n        Parameters\n        ----------\n        nmesh : array, int, default=None\n            Mesh size, i.e. number of mesh nodes along each axis.\n            If not provided, see ``value``.\n\n        boxsize : array, float, default=None\n            Physical size of the box.\n            If not provided, see ``positions``.\n\n        boxcenter : array, float, default=None\n            Box center.\n            If not provided, see ``positions``.\n\n        cellsize : array, float, default=None\n            Physical size of mesh cells.\n            If not ``None``, and mesh size ``nmesh`` is not ``None``, used to set ``boxsize`` as ``nmesh * cellsize``.\n            If ``nmesh`` is ``None``, it is set as (the nearest integer(s) to) ``boxsize/cellsize``.\n\n        value : array, default=None\n            Only used to get mesh size.\n\n        positions : array of shape (N,3), default=None\n            If ``boxsize`` and / or ``boxcenter`` is ``None``, use these positions\n            to determine ``boxsize`` and / or ``boxcenter``.\n\n        boxpad : float, default=1.5\n            When ``boxsize`` is determined from ``positions``, take ``boxpad`` times the smallest box enclosing ``positions`` as ``boxsize``.\n\n        dtype : string, np.dtype, defaut=None\n            Type for :attr:`value` array.\n            If ``None``, defaults to ``np.asarray(value).dtype`` if ``value`` is not ``None``, else 'f8'.\n        \"\"\"\n        if value is not None:\n            value = np.asarray(value)\n            if dtype is None: dtype = value.dtype\n            if nmesh is None: nmesh = value.shape\n        dtype = np.dtype(dtype if dtype is not None else 'f8')\n\n        if boxsize is None or boxcenter is None:\n            if positions is None:\n                raise MeshError('boxsize and boxcenter must be specified if positions are not provided')\n            pos_min, pos_max = positions.min(axis=0), positions.max(axis=0)\n            delta = np.abs(pos_max - pos_min)\n            if boxcenter is None: boxcenter = 0.5 * (pos_min + pos_max)\n            if boxsize is None:\n                if cellsize is not None and nmesh is not None:\n                    boxsize = nmesh * cellsize\n                else:\n                    boxsize = delta.max() * boxpad\n            if (boxsize < delta).any(): raise MeshError('boxsize too small to contain all data')\n\n        if nmesh is None:\n            if cellsize is not None:\n                nmesh = np.rint(boxsize/cellsize).astype(int)\n            else:\n                raise MeshError('nmesh (or cellsize) must be specified')\n\n        self.__dict__['dtype'] = np.dtype(dtype)\n        self.boxsize = boxsize\n        self.boxcenter = boxcenter\n        self.nmesh = nmesh\n\n    def clone(self, **kwargs):\n        \"\"\"Clone current :class:`MeshInfo` instance, optionally updating attributes with ``kwargs``.\"\"\"\n        for name in self._attrs: kwargs.setdefault(name, getattr(self, name))\n        return self.__class__(**kwargs)\n\n    @SetterProperty\n    def dtype(self, dtype):\n        self.__dict__['dtype'] = np.dtype(dtype)\n        self.boxsize = self.boxsize # set correct type\n        self.boxcenter = self.boxcenter # set correct type\n\n    @property\n    def _precision(self):\n        # Return float if float32, double if float64\n        return self._type_float.__name__[len('c_'):]\n\n    @property\n    def _type_float(self):\n        # Return ctypes-type corresponding to numpy-dtype\n        # Take care of complex type\n        dtype = np.empty(0, dtype=self.dtype).real.dtype\n        return ctypeslib.as_ctypes_type(dtype)\n\n    @SetterProperty\n    def boxsize(self, boxsize):\n        # Called when setting :attr:`boxsize`, enforcing array of shape (3,).\n        _boxsize = np.empty(self.ndim, dtype=self._type_float, order='C')\n        _boxsize[:] = boxsize\n        self.__dict__['boxsize'] = _boxsize\n\n    @SetterProperty\n    def boxcenter(self, boxcenter):\n        # Called when setting :attr:`boxcenter`, enforcing array of shape (3,).\n        _boxcenter = np.empty(self.ndim, dtype=self._type_float, order='C')\n        _boxcenter[:] = boxcenter\n        self.__dict__['boxcenter'] = _boxcenter\n\n    @SetterProperty\n    def nmesh(self, nmesh):\n        # Called when setting :attr:`nmesh`, enforcing array of shape (3,).\n        _nmesh = np.empty(self.ndim, dtype=ctypes.c_int, order='C')\n        _nmesh[:] = nmesh\n        self.__dict__['nmesh'] = _nmesh\n\n    @property\n    def offset(self):\n        \"\"\"Coordinates of the (0,0,0) corner of the box.\"\"\"\n        return self.boxcenter - self.boxsize/2.\n\n    @property\n    def cellsize(self):\n        \"Physical size of mesh cells.\"\n        return self.boxsize/self.nmesh\n\n    @property\n    def ndim(self):\n        \"\"\"Number of dimensions: 3.\"\"\"\n        return 3\n\n    def wrap(self, positions):\n        \"\"\"Wrap input positions.\"\"\"\n        return ((positions - self.offset) % self.boxsize) + self.offset\n\n    def deepcopy(self):\n        import copy\n        return copy.deepcopy(self)\n\n\nclass RealMesh(BaseMesh):\n\n    \"\"\"Class holding a 3D real mesh.\"\"\"\n\n    _path_lib = os.path.join(utils.lib_dir,'mesh_{}.so')\n\n    def __init__(self, value=None, dtype=None, info=None, nthreads=None, attrs=None, **kwargs):\n        \"\"\"\n        Initalize :class:`RealMesh`.\n\n        Parameters\n        ----------\n        value : array, default=None\n            Numpy array holding mesh values, or ``None`` (can set later through ``mesh.value = value``.\n\n        dtype : string, np.dtype, defaut=None\n            Type for :attr:`value` array. Defaults to 'f8'.\n\n        info : MeshInfo, default=None\n            Mesh information (boxsize, boxcenter, nmesh, etc.),\n            copied and updated with ``kwargs``.\n\n        nthreads : int\n            Number of threads to use in mesh calculations.\n\n        attrs : dict\n            Dictionary of other attributes.\n\n        kwargs : dict\n            Arguments for :class:`MeshInfo`.\n        \"\"\"\n        if dtype is None and (value is None or np.ndim(value) == 0): dtype = 'f8' # accept single float as input\n        super(RealMesh, self).__init__(value=value, info=info, nthreads=nthreads, attrs=attrs, dtype=dtype, **kwargs)\n        if 'float' not in self.dtype.name:\n            raise MeshError('Provide float dtype')\n\n    def coords(self):\n        \"\"\"Return array of coordinates along each axis.\"\"\"\n        toret = []\n        for idim,(n,o,d) in enumerate(zip(self.nmesh,self.offset,self.boxsize/self.nmesh)):\n            toret.append(o + d*np.arange(n))\n        return tuple(toret)\n\n    def assign_cic(self, positions, weights=None, wrap=False):\n        \"\"\"\n        Assign (paint) positions to mesh with Cloud-in-Cell scheme.\n\n        Parameters\n        ----------\n        positions : array of shape (N,3)\n            Cartesian positions.\n\n        weights : array of shape (N,), default=None\n            Weights; default to 1.\n\n        wrap : boolean, default=False\n            If ``True``, wrap input particle positions into the box.\n        \"\"\"\n        size = len(positions)\n        if weights is None: weights = np.ones_like(positions,shape=size,dtype=self._type_float)\n        if wrap: positions = self.info.wrap(positions)\n        positions = ((positions - self.boxcenter)/self.boxsize + 0.5)*self.nmesh\n        positions = positions.astype(self._type_float, copy=False).ravel(order='C')\n        weights = weights.astype(self._type_float, copy=False).ravel(order='C')\n        if self.value is None: self.value = 0.\n        type_positions = ctypeslib.ndpointer(dtype=self._type_float,shape=positions.size,flags='C')\n        type_weights = ctypeslib.ndpointer(dtype=self._type_float,shape=weights.size,flags='C')\n        type_nmesh = ctypeslib.ndpointer(dtype=ctypes.c_int,shape=self.ndim,flags='C')\n        func = self._lib.assign_cic\n        func.argtypes = (self._type_float_mesh,type_nmesh,type_positions,type_weights,ctypes.c_size_t)\n        func.restype = ctypes.c_int\n        self.value.shape = -1\n        flag = func(self.value,self.nmesh.astype(ctypes.c_int,copy=False),positions,weights,size)\n        if (flag != 0):\n            raise MeshError('Issue with assign_cic')\n        self.value.shape = self.shape\n\n    def read_cic(self, positions, wrap=False):\n        \"\"\"\n        Read mesh values interpolated at input positions with Cloud-in-Cell scheme.\n\n        Parameters\n        ----------\n        positions : array of shape (N,3)\n            Cartesian positions.\n\n        wrap : boolean, default=False\n            If ``True``, wrap input particle positions into the box.\n\n        Returns\n        -------\n        values : array of shape (N,)\n            Mesh values interpolated at input positions.\n        \"\"\"\n        size = len(positions)\n        dtype = positions.dtype\n        if wrap: positions = self.info.wrap(positions)\n        positions = ((positions - self.boxcenter)/self.boxsize + 0.5)*self.nmesh\n        positions = positions.astype(self._type_float,copy=False).ravel(order='C')\n        values = np.empty_like(positions,shape=size,order='C')\n        type_positions = ctypeslib.ndpointer(dtype=self._type_float,shape=positions.size,flags='C')\n        type_values = ctypeslib.ndpointer(dtype=self._type_float,shape=values.size,flags='C')\n        type_nmesh = ctypeslib.ndpointer(dtype=ctypes.c_int,shape=self.ndim,flags='C')\n        func = self._lib.read_cic\n        func.argtypes = (self._type_float_mesh,type_nmesh,type_positions,type_values,ctypes.c_size_t)\n        func.restype = ctypes.c_int\n        flag = func(self.value.ravel(order='C'),self.nmesh.astype(ctypes.c_int,copy=False),positions,values,size)\n        if (flag != 0):\n            raise MeshError('Issue with read_cic')\n        return values.astype(dtype=dtype,copy=False)\n\n    def read_finite_difference_cic(self, positions, wrap=False):\n        \"\"\"\n        Read derivative (finite difference scheme) of mesh values along each axis interpolated at input positions with Cloud-in-Cell scheme.\n\n        Parameters\n        ----------\n        positions : array of shape (N,3)\n            Cartesian positions.\n\n        wrap : boolean, default=False\n            If ``True``, wrap input particle positions into the box.\n\n        Returns\n        -------\n        values : array of shape (N,)\n            Derivative of mesh values interpolated at input positions.\n        \"\"\"\n        size = len(positions)\n        dtype = positions.dtype\n        if wrap: positions = self.info.wrap(positions)\n        positions = ((positions - self.boxcenter)/self.boxsize + 0.5)*self.nmesh\n        positions = positions.astype(self._type_float,copy=False).ravel(order='C')\n        values = np.empty_like(positions,order='C')\n        type_positions = ctypeslib.ndpointer(dtype=self._type_float,shape=positions.size,flags='C')\n        type_nmesh = ctypeslib.ndpointer(dtype=ctypes.c_int,shape=self.ndim,flags='C')\n        type_boxsize = ctypeslib.ndpointer(dtype=self._type_float,shape=self.ndim,flags='C')\n        func = self._lib.read_finite_difference_cic\n        func.argtypes = (self._type_float_mesh,type_nmesh,type_boxsize,type_positions,type_positions,ctypes.c_size_t)\n        func.restype = ctypes.c_int\n        flag = func(self.value.ravel(order='C'),self.nmesh.astype(ctypes.c_int,copy=False),self.boxsize.astype(self._type_float,copy=False),positions,values,size)\n        if (flag != 0):\n            raise MeshError('Issue with read_finite_difference_cic')\n        values.shape = (size,self.ndim)\n        return values.astype(dtype=dtype,copy=False)\n\n    def smooth_gaussian(self, radius, method='fft', nsigmas=2.5, **kwargs):\n        \"\"\"\n        Apply Gaussian smoothing to mesh.\n\n        Parameters\n        ----------\n        radius : array, float\n            Smoothing scale (along each axis, or same for all axes).\n\n        method : string, default='fft'\n            Perform Gaussian smoothing in real space ('real') or using FFT ('fft').\n\n        nsigmas : float, default=2.5\n            If ``method`` is 'real', number of Gaussian sigmas where to stop convolution.\n\n        kwargs : dict\n            Optional arguments for :meth:`get_fft_engine`.\n        \"\"\"\n        radius_ = np.empty_like(self.boxsize,order='C')\n        radius_[:] = radius\n        if method == 'fft':\n            if kwargs or self.fft_engine is None: self.set_fft_engine(**kwargs)\n            valuek = self.to_complex()\n            k2 = sum(-0.5*(r*k)**2 for r,k in zip(radius_,utils.broadcast_arrays(*valuek.coords())))\n            valuek *= np.exp(k2)\n            self.value = valuek.to_real().value\n            #func = self._lib.smooth_fft_gaussian\n            #func.argtypes = (self._type_float_mesh,type_nmesh,type_boxsize)\n            #func(self.value.ravel(order='C'),self.nmesh,radius/self.boxsize)\n        else:\n            radius = radius_/self.boxsize\n            type_nmesh = ctypeslib.ndpointer(dtype=ctypes.c_int,shape=self.ndim,flags='C')\n            type_boxsize = ctypeslib.ndpointer(dtype=self._type_float,shape=self.ndim,flags='C')\n            func = self._lib.smooth_gaussian\n            func.argtypes = (self._type_float_mesh,type_nmesh,type_boxsize,self._type_float)\n            self.value.shape = -1\n            func.restype = ctypes.c_int\n            flag = func(self.value, self.nmesh.astype(ctypes.c_int,copy=False),radius.astype(self._type_float,copy=False),nsigmas)\n            if (flag != 0):\n                raise MeshError('Issue with read_finite_difference_cic')\n            self.value.shape = self.shape\n\n    def to_complex(self, *args, **kwargs):\n        \"\"\"\n        Return :class:`ComplexMesh` computed with fast Fourier transforms.\n        See :meth:`get_fft_engine` for arguments.\n        \"\"\"\n        if kwargs or self.fft_engine is None: self.set_fft_engine(**kwargs)\n        toret = ComplexMesh(self.fft_engine.forward(self.value),info=self.info,nthreads=self.nthreads,hermitian=self.fft_engine.hermitian,attrs=self.attrs)\n        toret.fft_engine = self.fft_engine\n        return toret\n\n    def prod_sum(self, arrays, exp=1):\n        \"\"\"\n        Multiply mesh by ``(arrays[0][:,None,None] + arrays[1][None,:,None] + arrays[2][None,None,:]) ** exp``\n\n        Parameters\n        ----------\n        arrays : sequence of 3 float arrays\n            Arrays to multiply mesh by.\n\n        exp : int, default=1\n            Exponent to raise broadcast sum of arrays to.\n        \"\"\"\n        if len(arrays) != 3:\n            raise MeshError('Provide a sequence of 3 arrays')\n        arrays = list(arrays)\n        #arrays = np.concatenate(arrays[::-1], axis=0, dtype=self._type_float) # ::-1 for prod_sum\n        # dtype keyword for np.concatenate appears in version 1.20.0.\n        arrays = np.concatenate([np.asarray(array, dtype=self._type_float) for array in arrays[::-1]], axis=0)\n        if arrays.size != sum(self.shape):\n            raise MeshError('Length of input arrays must match shape')\n        type_nmesh = ctypeslib.ndpointer(dtype=ctypes.c_int, shape=self.ndim, flags='C')\n        type_arrays = ctypeslib.ndpointer(dtype=self._type_float, shape=arrays.size, flags='C')\n        func = self._lib.prod_sum\n        func.argtypes = (self._type_float_mesh, type_nmesh, type_arrays, ctypes.c_int)\n        func.restype = ctypes.c_int\n        self.value.shape = -1\n        flag = func(self.value, self.nmesh.astype(ctypes.c_int,copy=False), arrays, exp)\n        self.value.shape = self.shape\n        if (flag != 0):\n            raise MeshError('Issue with prod_sum')\n\n\nclass ComplexMesh(BaseMesh):\n    \"\"\"\n    Class holding a 3D complex mesh.\n\n    Parameters\n    ----------\n    hermitian : bool\n        Whether mesh has Hermitian symmetry, i.e. is real when Fourier transformed.\n        In this case, :attr:`shape` is half :attr:`nmesh` on the last axis.\n    \"\"\"\n    _attrs = BaseMesh._attrs + ['hermitian']\n\n    def __init__(self, value=None, dtype=None, info=None, hermitian=True, nthreads=None, attrs=None, **kwargs):\n        \"\"\"\n        Initialize :class:`ComplexMesh`.\n\n        Parameters\n        ----------\n        value : array, default=None\n            Numpy array holding mesh values, or ``None`` (can set later through ``mesh.value = value``.\n\n        dtype : string, np.dtype, defaut=None\n            Type for :attr:`value` array. Defaults to 'c16'.\n\n        info : MeshInfo, default=None\n            Mesh information (boxsize, boxcenter, nmesh, etc.).\n\n        hermitian : bool\n            Whether mesh has Hermitian symmetry, i.e. is real when Fourier transformed.\n            In this case, :attr:`shape` is half :attr:`nmesh` on the last axis.\n\n        nthreads : int\n            Number of threads to use in mesh calculations.\n\n        attrs : dict\n            Dictionary of other attributes.\n\n        kwargs : dict\n            Arguments for :class:`MeshInfo`.\n        \"\"\"\n        self.hermitian = hermitian\n        if dtype is None and (value is None or np.ndim(value) == 0): dtype = 'c16' # accept single float as input\n        super(ComplexMesh, self).__init__(value=value, info=info, nthreads=nthreads, attrs=attrs, dtype=dtype, **kwargs)\n        if 'complex' not in self.dtype.name:\n            raise MeshError('Provide complex dtype')\n\n    def _copy_value(self, out=None):\n        if out is None: out = np.empty_like(self.value)\n        func = self._lib.copy\n        type_mesh = ctypeslib.ndpointer(dtype=self._type_float, shape=2*self.size, flags='C')\n        func.argtypes = (type_mesh, type_mesh, ctypes.c_size_t)\n        func.restype = ctypes.c_int\n        value_view = self.value.view(dtype=self._type_float)\n        out_view = out.view(dtype=self._type_float)\n        value_view.shape = out_view.shape = -1\n        flag = func(value_view, out_view, 2*self.size)\n        out = out_view.view(dtype=self.dtype)\n        out.shape = self.shape\n        if (flag != 0):\n            raise MeshError('Issue with _copy_value')\n        return out\n\n    @property\n    def shape(self):\n        if self.hermitian:\n            return tuple(self.nmesh[:-1]) + (self.nmesh[-1]//2 + 1,)\n        return tuple(self.nmesh)\n\n    @property\n    def fundamental_freq(self):\n        \"\"\"Fundamental frequency of the mesh along each axis.\"\"\"\n        return 2.*np.pi/self.boxsize\n\n    def coords(self):\n        \"\"\"Return array of frequency (wavenumbers) along each axis.\"\"\"\n        toret = []\n        for idim,(n,d) in enumerate(zip(self.nmesh, self.boxsize/self.nmesh)):\n            if (not self.hermitian) or (idim < self.ndim - 1):\n                toret.append(2*np.pi*np.fft.fftfreq(n,d=d))\n            else:\n                toret.append(2*np.pi*np.fft.rfftfreq(n,d=d))\n        return tuple(toret)\n\n    def get_fft_engine(self, engine='numpy', **kwargs):\n        \"\"\"Same as :meth:`RealMesh.get_fft_engine`.\"\"\"\n        kwargs.setdefault('nthreads', self.nthreads)\n        return get_fft_engine(engine, shape=self.nmesh, type_complex=self.dtype, hermitian=self.hermitian, **kwargs)\n\n    def to_real(self, *args, **kwargs):\n        \"\"\"\n        Return :class:`RealMesh` computed with fast Fourier transforms.\n        See :meth:`get_fft_engine` for arguments.\n        Raises a :class:`MeshError` if FFT engine has not same Hermitian symmetry.\n        \"\"\"\n        if kwargs or self.fft_engine is None: self.set_fft_engine(**kwargs)\n        if self.fft_engine.hermitian != self.hermitian:\n            raise MeshError('ComplexMesh has hermitian = {} but provided FFT engine has hermitian = {}'.format(self.hermitian,self.fft_engine.hermitian))\n        value = self.value\n        kwargs = {}\n        if isinstance(self.fft_engine, FFTWEngine):\n            if self.fft_engine.hermitian: # input destroyed only when hermitian\n                value = self._copy_value()\n            kwargs = {'destroy_input':True}\n        toret = RealMesh(self.fft_engine.backward(value, **kwargs).real, info=self.info, nthreads=self.nthreads, attrs=self.attrs)\n        toret.fft_engine = self.fft_engine\n        return toret\n\n    def prod_sum(self, arrays, exp=1):\n        \"\"\"\n        Multiply mesh by ``(arrays[0][:,None,None] + arrays[1][None,:,None] + arrays[2][None,None,:]) ** exp``\n\n        Parameters\n        ----------\n        arrays : sequence of 3 float arrays\n            Arrays to multiply mesh by.\n\n        exp : int, default=1\n            Exponent to raise broadcast sum of arrays to.\n        \"\"\"\n        if len(arrays) != 3:\n            raise MeshError('Provide a sequence of 3 arrays')\n        arrays = list(arrays)\n        arrays[-1] = np.repeat(arrays[-1], 2)\n        #arrays = np.concatenate(arrays[::-1], axis=0, dtype=self._type_float) # ::-1 for prod_sum\n        # dtype keyword for np.concatenate appears in version 1.20.0.\n        arrays = np.concatenate([np.asarray(array, dtype=self._type_float) for array in arrays[::-1]], axis=0)\n        if arrays.size != sum(self.shape) + self.shape[-1]:\n            raise MeshError('Length of input arrays must match shape')\n        shape = np.asarray(self.shape, dtype=ctypes.c_int)\n        shape[-1] *= 2\n        type_mesh = ctypeslib.ndpointer(dtype=self._type_float, shape=np.prod(shape), flags='C')\n        type_nmesh = ctypeslib.ndpointer(dtype=ctypes.c_int, shape=self.ndim, flags='C')\n        type_arrays = ctypeslib.ndpointer(dtype=self._type_float, shape=arrays.size, flags='C')\n        func = self._lib.prod_sum\n        func.argtypes = (type_mesh, type_nmesh, type_arrays, ctypes.c_int)\n        func.restype = ctypes.c_int\n        #value = np.array(self.value)\n        #print(value.shape, value.size)\n        #value.shape = (value.size,)\n        self.value.shape = -1\n        value_view = self.value.view(dtype=self._type_float)\n        flag = func(value_view, shape, arrays, exp)\n        self.value = value_view.view(dtype=self.dtype)\n        if (flag != 0):\n            raise MeshError('Issue with prod_sum')\n\n\nclass BaseFFTEngine(BaseClass):\n    \"\"\"\n    Base engine for fast Fourier transforms.\n    FFT engines should extend this class, by (at least) implementing:\n\n    - :meth:`forward`\n    - :meth:`backward`\n\n    Attributes\n    ----------\n    shape : tuple\n        Shape of array (in real-space, i.e. not accounting for Hermitian symmetry) to transform.\n\n    nthreads : int\n        Number of threads.\n\n    type_real : np.dtype\n        Type for real values.\n\n    type_complex : np.dtype\n        Type for complex values. Twice larger than :attr:`type_float`.\n\n    hermitian : bool\n        Whether complex array has Hermitian symmetry, i.e. is real when Fourier transformed.\n    \"\"\"\n    def __init__(self, shape, nthreads=None, type_complex=None, type_real=None, hermitian=True, **kwargs):\n        \"\"\"\n        Initialize FFT engine.\n        Default types are 'c16' for :attr:`type_complex` and 'f8' for :attr:`type_float`.\n\n        Parameters\n        ----------\n        shape : list, tuple\n            Array shape.\n\n        nthreads : int, default=None\n            Number of threads.\n\n        type_complex : string, np.dtype, default=None\n            Type for complex values.\n            If not provided, use ``type_real`` instead.\n\n        type_real : string, np.dtype, default=None\n            Type for real values.\n            If not provided, use ``type_complex`` instead.\n        \"\"\"\n        if nthreads is None:\n            self.nthreads = int(os.environ.get('OMP_NUM_THREADS', '1'))\n        else:\n            self.nthreads = nthreads\n        self.shape = tuple(shape)\n        if type_complex is not None:\n            self.type_complex = np.dtype(type_complex)\n            itemsize = np.dtype(self.type_complex).itemsize\n            self.type_real = np.dtype('f{:d}'.format(itemsize//2))\n        else:\n            if type_real is None: type_real = 'f8'\n            self.type_real = np.dtype(type_real)\n            itemsize = np.dtype(self.type_real).itemsize\n            self.type_complex = np.dtype('c{:d}'.format(itemsize*2))\n        self.hermitian = hermitian\n\n    @property\n    def ndim(self):\n        \"\"\"Number of dimensions.\"\"\"\n        return len(self.shape)\n\n    @property\n    def size(self):\n        \"\"\"Size of array (in real-space, i.e. not accounting for Hermitian symmetry) to transform.\"\"\"\n        return np.prod(self.shape)\n\n    @property\n    def hshape(self):\n        \"\"\"Shape in Fourier-space, accounting for Hermitian symmetry.\"\"\"\n        if self.hermitian:\n            return self.shape[:-1] + (self.shape[-1]//2 + 1,)\n        return tuple(self.shape)\n\n    def forward(self, fun):\n        \"\"\"Return forward transform of ``fun``.\"\"\"\n        raise NotImplementedError('Implement \"forward\" method in your \"BaseFFTEngine\"-inherited FFT engine.')\n\n    def backward(self, fun):\n        \"\"\"Return backward transform of ``fun``.\"\"\"\n        raise NotImplementedError('Implement \"backward\" method in your \"BaseFFTEngine\"-inherited FFT engine.')\n\n\nclass NumpyFFTEngine(BaseFFTEngine):\n\n    \"\"\"FFT engine based on :mod:`numpy.fft`.\"\"\"\n\n    def forward(self, fun):\n        \"\"\"Return forward transform of ``fun``.\"\"\"\n        if self.hermitian:\n            return np.fft.rfftn(fun).astype(self.type_complex, copy=False)\n        return np.fft.fftn(fun).astype(self.type_complex, copy=False)\n\n    def backward(self, fun):\n        \"\"\"Return backward transform of ``fun``.\"\"\"\n        if self.hermitian:\n            return np.fft.irfftn(fun).astype(self.type_real, copy=False)\n        return np.fft.ifftn(fun).astype(self.type_complex, copy=False)\n\n\ntry: import pyfftw\nexcept ImportError: pyfftw = None\n\n\nclass FFTWEngine(BaseFFTEngine):\n\n    \"\"\"FFT engine based on :mod:`pyfftw`.\"\"\"\n\n    def __init__(self, shape, nthreads=None, wisdom=None, save_wisdom=None, plan='measure', **kwargs):\n        \"\"\"\n        Initialize :mod:`pyfftw` engine.\n\n        Note\n        ----\n        :class:`pyfftw.FFTW` internally stores :attr:`pyfftw.FFTW._input_array` and :attr:`pyfftw.FFTW._output_array`,\n        which is a waste of memory if one does not want to save them.\n        e.g. performing ``engine.backward(engine.forward(array))`` would take as much as 3 times\n        (2 for the forward transform, and 1 output array in the backward transform) the memory footprint of ``array``.\n        As no access is provided to :attr:`pyfftw.FFTW._input_array` and :attr:`pyfftw.FFTW._output_array` attributes,\n        we choose to destroy and rebuild :class:`pyfftw.FFTW` for each transform, thereby allowing Python to destroy\n        undesired arrays, at a relatively modest overhead (~ 0.5 s).\n\n        Parameters\n        ----------\n        shape : list, tuple\n            Array shape.\n\n        nthreads : int, default=None\n            Number of threads.\n\n        wisdom : string, tuple, default=None\n            Precomputed :mod:`pyfftw` wisdom, used to accelerate FFTs.\n            If a string, should be a path to previously saved FFT wisdom (with :func:`numpy.save`).\n            If a tuple, directly corresponds to the wisdom.\n            By default the wisdom given in ``save_wisdom`` will be loaded, if exists.\n\n        save_wisdom : bool, string, default=None\n            If not ``None``, path where to save the wisdom.\n            If ``True``, the wisdom will be saved in the default path:\n            'wisdom.shape-{shape[0]}-{shape[1]}-{shape[2]}.type-{type}.nthreads-{nthreads}.npy'.\n\n        plan : string, default='measure'\n            Choices are ['estimate', 'measure', 'patient', 'exhaustive'].\n            The increasing amount of effort spent during the planning stage to create the fastest possible transform.\n            Usually 'measure' is a good compromise.\n\n        kwargs : dict\n            Optional arguments for :class:`BaseFFTEngine`.\n        \"\"\"\n        if pyfftw is None:\n            raise NotImplementedError('Install pyfftw to use {}'.format(self.__class__.__name__))\n        super(FFTWEngine, self).__init__(shape, nthreads=nthreads, **kwargs)\n        plan = plan.lower()\n        allowed_plans = ['estimate', 'measure', 'patient', 'exhaustive']\n        if plan not in allowed_plans:\n            raise MeshError('Plan {} unknown'.format(plan))\n        plan = 'FFTW_{}'.format(plan.upper())\n\n        dtype = self.type_real if self.hermitian else self.type_complex\n        wisdom_fn = 'wisdom.shape-{}.type-{}.nthreads-{:d}.npy'.format('-'.join(['{:d}'.format(s) for s in self.shape]), dtype.name, self.nthreads)\n        # Should we save wisdom?\n        if save_wisdom and isinstance(save_wisdom, str):\n            wisdom_fn = save_wisdom\n        save_wisdom = bool(save_wisdom)\n\n        if wisdom is None:\n            try:\n                wisdom = np.load(wisdom_fn)\n                pyfftw.import_wisdom(wisdom)\n            except:\n                pass\n            else:\n                self.log_info('Loading wisdom from {}.'.format(wisdom_fn))\n        elif isinstance(wisdom, str):\n            self.log_info('Loading wisdom from {}.'.format(wisdom))\n            wisdom = tuple(np.load(wisdom))\n        else:\n            pyfftw.import_wisdom(wisdom)\n\n        fftw_f = pyfftw.empty_aligned(self.shape, dtype=dtype, order='C')\n        fftw_fk = pyfftw.empty_aligned(self.hshape, dtype=self.type_complex, order='C')\n        self.flags = (plan,)\n        self.fftw_forward_object = pyfftw.FFTW(fftw_f, fftw_fk, axes=range(self.ndim), direction='FFTW_FORWARD', flags=self.flags, threads=self.nthreads)\n        self.fftw_backward_object = pyfftw.FFTW(fftw_fk, fftw_f, axes=range(self.ndim), direction='FFTW_BACKWARD', flags=self.flags, threads=self.nthreads)\n        # We delete these instances to save memory, see note above\n        self.fftw_forward_object, self.fftw_backward_object = None, None\n        # Allow the wisdom to be accessed from outside\n        self.wisdom = pyfftw.export_wisdom()\n        if save_wisdom:\n            self.log_info('Saving wisdom to {}.'.format(wisdom_fn))\n            np.save(wisdom_fn, self.wisdom)\n\n    def forward(self, fun):\n        \"\"\"Return forward transform of ``fun``.\"\"\"\n        output_array = pyfftw.empty_aligned(self.hshape, dtype=self.type_complex, order='C')\n        #if self.hermitian:\n        #    input_array = pyfftw.empty_aligned(self.shape,dtype=self.type_real,order='C')\n        #else:\n        #    input_array = pyfftw.empty_aligned(self.shape,dtype=self.type_complex,order='C')\n        if self.hermitian:\n            fun = fun.astype(self.type_real, copy=False)\n        else:\n            fun = fun.astype(self.type_complex, copy=False)\n        if self.fftw_forward_object is None:\n            fftw_forward_object = pyfftw.FFTW(fun, output_array, axes=range(self.ndim), direction='FFTW_FORWARD', flags=self.flags, threads=self.nthreads)\n            #input_array[...] = fun\n            toret = fftw_forward_object(normalise_idft=True)\n        else:\n            toret = self.fftw_forward_object(input_array=fun, output_array=output_array, normalise_idft=True)\n        return toret\n\n    def backward(self, fun, destroy_input=True):\n        \"\"\"Return backward transform of ``fun``; ``destroy_input = True`` to allow destroy ``fun`` (in case dimension > 1 and hermitian).\"\"\"\n        if destroy_input:\n            input_array = fun\n        else:\n            input_array = pyfftw.empty_aligned(self.hshape, dtype=self.type_complex, order='C')\n            input_array[...] = fun\n        if self.hermitian:\n            output_array = pyfftw.empty_aligned(self.shape, dtype=self.type_real, order='C')\n        else:\n            output_array = pyfftw.empty_aligned(self.shape, dtype=self.type_complex, order='C')\n        if self.fftw_backward_object is None:\n            fftw_backward_object = pyfftw.FFTW(input_array, output_array, axes=range(self.ndim), direction='FFTW_BACKWARD', flags=self.flags, threads=self.nthreads)\n            toret = fftw_backward_object(normalise_idft=True)\n        else:\n            toret = self.fftw_backward_object(input_array=fun, output_array=output_array, normalise_idft=True)\n        return toret\n\n\ndef get_fft_engine(engine, *args, **kwargs):\n    \"\"\"\n    Return FFT engine.\n\n    Parameters\n    ----------\n    engine : BaseFFTEngine, string\n        FFT engine, or one of ['numpy', 'fftw'].\n\n    args, kwargs : tuple, dict\n        Arguments for FFT engine.\n\n    Returns\n    -------\n    engine : BaseFFTEngine\n    \"\"\"\n    if isinstance(engine, str):\n        if engine.lower() == 'numpy':\n            return NumpyFFTEngine(*args, **kwargs)\n        if engine.lower() == 'fftw':\n            return FFTWEngine(*args, **kwargs)\n        raise ValueError('FFT engine {} is unknown'.format(engine))\n    return engine\n", "meta": {"hexsha": "f41d6e5a291dc7a985a573d4242c25568ac2a410", "size": 42835, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyrecon/mesh.py", "max_stars_repo_name": "seshnadathur/pyrecon", "max_stars_repo_head_hexsha": "262d90b8bb524d0676074a58c7a9ee195233b414", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyrecon/mesh.py", "max_issues_repo_name": "seshnadathur/pyrecon", "max_issues_repo_head_hexsha": "262d90b8bb524d0676074a58c7a9ee195233b414", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyrecon/mesh.py", "max_forks_repo_name": "seshnadathur/pyrecon", "max_forks_repo_head_hexsha": "262d90b8bb524d0676074a58c7a9ee195233b414", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6248872858, "max_line_length": 164, "alphanum_fraction": 0.6145441812, "include": true, "reason": "import numpy,from numpy", "num_tokens": 10085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.170359142252619}}
{"text": "# Standard library\nimport os, abc\nimport pickle\nimport numpy as np\nfrom copy import deepcopy\n\n# Third-party\nfrom scipy.integrate import quad\nfrom scipy.interpolate import interp1d\nfrom astropy.table import Table\nfrom astropy import units as u\n\n# Project\nfrom .. import MIST_PATH\nfrom ..util import check_random_state, check_units\nfrom ..log import logger\nfrom ..filters import *\nfrom .imf import sample_imf, build_galaxy, imf_dict, IMFIntegrator\nfrom .isochrones import MISTIsochrone\n\n\n__all__ = ['SSP', 'MISTSSP', 'constant_sb_stars_per_pix']\n\n\nclass StellarPopulation(metaclass=abc.ABCMeta):\n    \"\"\"\n    Stellar population base class.\n\n    Parameters\n    ----------\n    distance : float or `~astropy.units.Quantity`, optional\n        Distance to source. If float is given, the units are assumed\n        to be `~astropy.units.Mpc`. Default distance is 10 `~astropy.units.pc`\n        (i.e., the mags are in absolute units).\n    imf : str, optional\n        The initial stellar mass function. Default is `'kroupa'`.\n    \"\"\"\n\n    def __init__(self, distance=10.0 * u.pc, imf='kroupa', imf_kw={}):\n        self.imf = imf\n        self.imf_kw = imf_kw\n        self.distance = check_units(distance, 'Mpc')\n\n    def build_pop(self, num_stars=None, **kwargs):\n        \"\"\"Build stellar population.\"\"\"\n        return NotImplementedError()\n\n    @property\n    def dist_mod(self):\n        \"\"\"The distance modulus.\"\"\"\n        return 5 * np.log10(self.distance.to('pc').value) - 5\n\n    @property\n    def num_pops(self):\n        \"\"\"\n        The number of simple stellar populations that composes this pop.\n        \"\"\"\n        return 1 if type(self.isochrone) != list else len(self.isochrone)\n\n    @property\n    def total_initial_live_mass(self):\n        \"\"\"Total initial stellar mass in solar units.\"\"\"\n        return self.initial_masses.sum() * u.M_sun\n\n    @property\n    def num_stars(self):\n        \"\"\"Number stars in population.\"\"\"\n        return len(self.star_masses)\n\n    @property\n    def abs_mag_table(self):\n        \"\"\"Absolute magnitudes in a `~astropy.table.Table` object.\"\"\"\n        return Table(self.abs_mags)\n\n    @property\n    def mag_table(self):\n        \"\"\"Apparent magnitudes in a `~astropy.table.Table` object.\"\"\"\n        _mags = {}\n        for filt in self.filters:\n            _mags[filt] = self.star_mags(filt)\n        return Table(_mags)\n\n    def to_pickle(self, file_name):\n        \"\"\"Pickle stellar population object.\"\"\"\n        pkl_file = open(file_name, 'wb')\n        pickle.dump(self, pkl_file)\n        pkl_file.close()\n\n    @staticmethod\n    def from_pickle(file_name):\n        \"\"\"Load pickle of stellar population object.\"\"\"\n        pkl_file = open(file_name, 'rb')\n        data = pickle.load(pkl_file)\n        pkl_file.close()\n        return data\n\n    def _remnants_factor(self, **kwargs):\n        \"\"\"\n        Correction factor to account for stellar remnants in the final mass.\n        The mass in luminous stars is given by M_total * factor.\n        \"\"\"\n        m_without_remnants = self.isochrone.ssp_surviving_mass(\n            self.imf, add_remnants=False, **kwargs)\n        m_with_remnants = self.isochrone.ssp_surviving_mass(\n            self.imf, add_remnants=True, **kwargs)\n        factor = m_without_remnants / m_with_remnants\n        return factor\n\n    def copy(self):\n        return deepcopy(self)\n\n    def set_distance(self, distance):\n        \"\"\"\n        Change the distance to the stellar population.\n\n        Parameters\n        ----------\n        distance : float or `~astropy.units.Quantity`\n            Distance to source. If float is given, the units are assumed\n            to be `~astropy.units.Mpc`.\n        \"\"\"\n        self.distance = check_units(distance, 'Mpc')\n\n    def star_mags(self, bandpass, select=None):\n        \"\"\"\n        Get the stellar apparent magnitudes.\n\n        Parameters\n        ----------\n        bandpass : str\n            Filter of observation. Must be a filter in the given\n            photometric system(s).\n        select : `~numpy.ndarray`, optional\n            Boolean mask for selecting stars (True for stars to include).\n\n        Returns\n        -------\n        mags : `~numpy.ndarray`\n            The stellar apparent magnitudes in the given bandpass.\n        \"\"\"\n        mags = self.abs_mags[bandpass] + self.dist_mod\n        if select is not None:\n            mags = mags[select]\n        return mags\n\n    def mag_integrated_component(self, bandpass):\n        \"\"\"\n        Get the magnitude of the integrated component of the population if\n        it exists.\n\n        Parameters\n        ----------\n        bandpass : str\n            Filter of observation. Must be a filter in the given\n            photometric system(s).\n\n        Returns\n        -------\n        mag : float\n            The integrated magnitude if it exists. Otherwise None is returned.\n        \"\"\"\n        if hasattr(self, 'integrated_abs_mags'):\n            mag = self.integrated_abs_mags[bandpass] + self.dist_mod\n        else:\n            mag = None\n        return mag\n\n    def sbf_mag(self, bandpass):\n        \"\"\"\n        Calculate the apparent SBF magnitude of the stellar population.\n\n        Parameters\n        ----------\n        bandpass : str\n            Filter of observation. Must be a filter in the given\n            photometric system(s).\n\n        Returns\n        -------\n        mbar : float\n            The apparent SBF magnitude of the stellar population in the given\n            bandpass.\n        \"\"\"\n        integrated = self.mag_integrated_component(bandpass)\n        if integrated is not None:\n            f_int = 10**(-0.4*integrated)\n            log_dddd = 4 * np.log10(self.distance.to('cm').value)\n            ff_int = 10**(self._integrated_log_lumlum[bandpass] - log_dddd)\n        else:\n            f_int = 0.0\n            ff_int = 0.0\n        f_i = 10**(-0.4 * (self.star_mags(bandpass)))\n        ff = np.sum(f_i**2) + ff_int\n        f = np.sum(f_i) + f_int\n        mbar = -2.5 * np.log10(ff / f)\n        return mbar\n\n    def integrated_color(self, blue, red, select=None):\n        \"\"\"\n        Calculate the population's integrated color.\n\n        Parameters\n        ----------\n        blue : str\n            The blue bandpass. Must be a filter in the\n            given photometric system(s).\n        red : str\n            The red bandpass. Must be a filter in the\n            given photometric system(s).\n        select : `~numpy.ndarray`, optional\n            Boolean mask for selecting stars (True for stars to include).\n\n        Returns\n        -------\n        color : float\n            The integrated color.\n        \"\"\"\n        blue_int = self.mag_integrated_component(blue)\n        if select is None and blue_int is not None:\n            f_blue_int = 10**(-0.4*blue_int)\n            f_red_int = 10**(-0.4*self.mag_integrated_component(red))\n        else:\n            f_blue_int = 0.0\n            f_red_int = 0.0\n        blue_mag = self.star_mags(blue, select)\n        F_blue = np.sum(10**(-0.4 * blue_mag)) + f_blue_int\n        red_mag = self.star_mags(red, select)\n        F_red = np.sum(10**(-0.4 * red_mag)) + f_red_int\n        color = -2.5 * np.log10(F_blue / F_red)\n        return color\n\n    def mean_mag(self, bandpass, select=None):\n        \"\"\"\n        Calculate the population's mean magnitude.\n\n        Parameters\n        ----------\n        bandpass : str\n            Filter of observation. Must be a filter in the given\n            photometric system(s).\n        select : `~numpy.ndarray`, optional\n            Boolean mask for selecting stars (True for stars to include).\n\n        Returns\n        -------\n        mag : float\n            The mean magnitude in the given bandpass.\n        \"\"\"\n        integrated = self.mag_integrated_component(bandpass)\n        if select is None and integrated is not None:\n            f_int = 10**(-0.4*integrated)\n            n_int = self.num_stars_integrated\n        else:\n            f_int = 0.0\n            n_int = 0.0\n        mags = self.star_mags(bandpass, select)\n        mean_flux = ((10**(-0.4*mags)).sum() + f_int) / (len(mags) + n_int)\n        mag = -2.5 * np.log10(mean_flux)\n        return mag\n\n    def total_mag(self, bandpass, select=None):\n        \"\"\"\n        Calculate the population's total magnitude.\n\n        Parameters\n        ----------\n        bandpass : str\n            Filter of observation. Must be a filter in the given\n            photometric system(s).\n        select : `~numpy.ndarray`, optional\n            Boolean mask for selecting stars (True for stars to include).\n\n        Returns\n        -------\n        mag : float\n            The total magnitude in the given bandpass.\n        \"\"\"\n        integrated = self.mag_integrated_component(bandpass)\n        if select is None and integrated is not None:\n            f_int = 10**(-0.4*integrated)\n        else:\n            f_int = 0.0\n        mags = self.star_mags(bandpass, select)\n        total_flux = (10**(-0.4*mags)).sum() + f_int\n        mag = -2.5 * np.log10(total_flux)\n        return mag\n\n\nclass SSP(StellarPopulation):\n    \"\"\"\n    Generic Simple Stellar Population (SSP).\n\n    .. note::\n        You must give `total_mass` *or* `num_stars`.\n\n    Parameters\n    ----------\n    isochrone : `~artpop.stars.Isochrone`\n        Isochrone object.\n    num_stars : int or `None`\n        Number of stars in source. If `None`, then must give `total_mass`.\n    total_mass : float or `~astropy.units.Quantity` or `None`\n        Stellar mass of the source. If `None`, then must give `num_stars`. This\n        mass accounts for stellar remnants when ``add_remnants = True``, which\n        means the actual sampled mass will be less than the given value. If\n        float is given, the units are assumed to be solar masses.\n    distance : float or `~astropy.units.Quantity`, optional\n        Distance to source. If float is given, the units are assumed\n        to be `~astropy.units.Mpc`. Default distance is 10 `~astropy.units.pc`.\n    mag_limit : float, optional\n        Only sample individual stars that are brighter than this magnitude. All\n        fainter stars will be combined into an integrated component. Otherwise,\n        all stars in the population will be sampled. You must also give the\n        `mag_limit_band` if you use this parameter.\n    mag_limit_band : str, optional\n        Bandpass of the limiting magnitude. You must give this parameter if\n        you use the `mag_limit` parameter.\n    imf : str, optional\n        The initial stellar mass function. Default is `'kroupa'`.\n    imf_kw : dict, optional\n        Optional keyword arguments for sampling the stellar mass function.\n    mass_tolerance : float, optional\n        Tolerance in the fractional difference between the input mass and the\n        final mass of the population. The parameter is only used when\n        `total_mass` is given.\n    add_remnants : bool, optional\n        If True (default), apply scaling factor to total mass to account for\n        stellar remnants in the form of white dwarfs, neutron stars,\n        and black holes.\n    random_state : `None`, int, list of ints, or `~numpy.random.RandomState`\n        If `None`, return the `~numpy.random.RandomState` singleton used by\n        ``numpy.random``. If `int`, return a new `~numpy.random.RandomState`\n        instance seeded with the `int`.  If `~numpy.random.RandomState`,\n        return it. Otherwise raise ``ValueError``.\n    \"\"\"\n\n    def __init__(self, isochrone, num_stars=None, total_mass=None,\n                 distance=10*u.pc, mag_limit=None, mag_limit_band=None,\n                 imf='kroupa', imf_kw={}, mass_tolerance=0.01,\n                 add_remnants=True, random_state=None):\n        super(SSP, self).__init__(distance=distance, imf=imf, imf_kw=imf_kw)\n        self.isochrone = isochrone\n        self.filters = isochrone.filters\n        self.mag_limit = mag_limit\n        self.mag_limit_band = mag_limit_band\n        self.rng = check_random_state(random_state)\n        self.build_pop(num_stars, total_mass, mass_tolerance, add_remnants)\n        self._r = {'M_star': f'{self.total_mass.value:.2e} M_sun'}\n\n    def build_pop(self, num_stars=None, total_mass=None, mass_tolerance=0.01,\n                  add_remnants=True):\n        \"\"\"\n        Build the stellar population. You must give `total_mass`\n        *or* `num_stars` as an argument.\n\n        Parameters\n        ----------\n        num_stars : int or `None`\n            Number of stars in source. If `None`, then must give `total_mass`.\n        total_mass : float or `~astropy.units.Quantity` or `None`\n            Stellar mass of the source. If `None`, then must give `num_stars`.\n            This mass accounts for stellar remnants when ``add_remnants = True``\n            which means the actual sampled mass will be less than the given\n            value. If float is given, the units are assumed to be solar masses.\n        mass_tolerance : float, optional\n            Tolerance in the fractional difference between the input mass and\n            the final mass of the population. The parameter is only used when\n            `total_mass` is given.\n        add_remnants : bool, optional\n            If True (default), apply scaling factor to total mass to account\n            for stellar remnants in the form of white dwarfs, neutron stars,\n            and black holes.\n        \"\"\"\n\n        # get isochrone object and info\n        m_min, m_max = self.isochrone.m_min, self.isochrone.m_max\n        imf_kw = self.imf_kw.copy()\n        iso = self.isochrone\n        imfint = IMFIntegrator(self.imf, m_min=m_min, m_max=m_max)\n        remnants_factor = self._remnants_factor() if add_remnants else 1.0\n\n        # calculate the fraction of stars we will sample\n        m_lim, f_num_sampled, f_mass_sampled = self.sample_fraction(\n            self.mag_limit,\n            self.mag_limit_band\n        )\n\n        # the limiting mass is min mass if 100% of stars will be sampled\n        self.has_integrated_component = m_lim != m_min\n\n        m_min = m_lim\n        self.sampled_mass_lower_limit = m_lim\n        self.frac_num_sampled = f_num_sampled\n        self.frac_mass_sampled = f_mass_sampled\n\n        if num_stars is not None:\n\n            # sample imf\n            num_stars_sample = int(num_stars * f_num_sampled)\n            self.initial_masses = sample_imf(\n                num_stars_sample, m_min=m_min, m_max=m_max, imf=self.imf,\n                random_state=self.rng, imf_kw=imf_kw)\n\n            # star masses are interpolated from \"actual\" mass\n            self.star_masses = iso.interpolate('mact', self.initial_masses)\n\n            # will be < num_stars if f_num_sampled < 1.0.\n            self.num_stars_integrated = int(num_stars - len(self.star_masses))\n            self.sampled_mass = self.star_masses.sum()\n\n        elif total_mass is not None:\n\n            total_mass = check_units(total_mass, 'Msun').to('Msun').value\n\n            # calculate fraction of mass that remains after mass loss\n            mass_loss = iso.ssp_surviving_mass(\n                imf=self.imf, m_min=iso.m_min, m_max=iso.m_max,\n                add_remnants=False)\n\n            # we sample less mass than total_mass to account for\n            # stellar remnants and the sample fraction\n            sampled_mass = total_mass * remnants_factor * f_mass_sampled\n\n            # we increase the sampled mass to account for mass loss\n            sampled_mass /= mass_loss\n\n            # sample initial masses\n            mean_mass = imfint.m_integrate(m_min, m_max)\n            mean_mass /= imfint.integrate(m_min, m_max)\n            num_stars_iter = int(mass_tolerance * sampled_mass / mean_mass)\n            self.initial_masses = build_galaxy(\n                sampled_mass, m_min=m_min, m_max=m_max, imf=self.imf,\n                random_state=self.rng, num_stars_iter=num_stars_iter, **imf_kw)\n\n            # star masses are interpolated from \"actual\" mass\n            self.star_masses = iso.interpolate('mact', self.initial_masses)\n            self.sampled_mass = self.star_masses.sum()\n\n            # calculate approximate number of stars in integrated component\n            factor = (1 - f_num_sampled) / f_num_sampled\n            self.num_stars_integrated = int(self.num_stars * factor)\n\n        else:\n\n            raise Exception('you must give total mass *or* number of stars')\n\n        self.abs_mags = {}\n        for filt in self.filters:\n            self.abs_mags[filt] = iso.interpolate(filt, self.initial_masses)\n\n        # update masses and mags if there is an integrated component\n        if self.has_integrated_component:\n\n            # find evolved stars that are fainter than mag_limit\n            sampled_mags = self.abs_mags[self.mag_limit_band] + self.dist_mod\n            evolved_faint = sampled_mags > self.mag_limit\n\n            evolved_mags = {}\n            for filt in self.filters:\n                evolved_mags[filt] = self.abs_mags[filt][evolved_faint]\n                self.abs_mags[filt] = self.abs_mags[filt][~evolved_faint]\n\n            # calculate evolved mass and update integrated star count\n            evolved_mass = self.star_masses[evolved_faint].sum()\n            self.num_stars_integrated += evolved_faint.sum()\n\n            # update initial and sampled masses\n            self.initial_masses = self.initial_masses[~evolved_faint]\n            self.star_masses = self.star_masses[~evolved_faint]\n            self.sampled_mass = self.star_masses.sum()\n\n            # calculate normalized IMF weights\n            w = iso.imf_weights(self.imf, m_max_norm=m_max, norm_type='number')\n            _, arg = iso.nearest_mini(m_lim)\n\n            # update total mass\n            num_stars = self.num_stars_integrated + self.num_stars\n            _mass = num_stars * np.sum(iso.mact[:arg] * w[:arg])\n            _mass += evolved_mass\n            self.total_mass = (self.sampled_mass + _mass) / remnants_factor\n\n            # updated integrated absolute magnitudes and luminosity variances\n            self.integrated_abs_mags = {}\n            self._integrated_log_lumlum = {}\n            for filt in iso.filters:\n                mag = iso.mag_table[filt]\n                flux  = num_stars * np.sum(10**(-0.4 * mag[: arg]) * w[: arg])\n                flux += np.sum(10**(-0.4 * evolved_mags[filt]))\n                self.integrated_abs_mags[filt] = -2.5 * np.log10(flux)\n                ff = num_stars * np.sum(10**(-0.8 * mag[: arg]) * w[: arg])\n                ff += np.sum(10**(-0.8 * evolved_mags[filt]))\n                log_dddd = 4 * np.log10((10 * u.pc).to('cm').value)\n                self._integrated_log_lumlum[filt] = np.log10(ff) + log_dddd\n        else:\n            # calculate total_mass with stellar remnants\n            self.total_mass = self.sampled_mass / remnants_factor\n\n        self.live_star_mass = self.total_mass * remnants_factor\n        self.ssp_labels = np.ones(len(self.star_masses), dtype=int)\n\n        self.total_mass *= u.Msun\n        self.sampled_mass *= u.Msun\n        self.live_star_mass *= u.Msun\n\n        for attr in ['eep', 'log_L', 'log_Teff']:\n            if hasattr(iso, attr):\n                if getattr(iso, attr) is not None:\n                    vals_interp = iso.interpolate(attr, self.initial_masses)\n                    setattr(self, attr, vals_interp)\n\n    def sample_fraction(self, mag_limit, mag_limit_band):\n        \"\"\"\n        Calculate the fraction of stars by mass and number that will be\n        sampled with the give limiting magnitude.\n\n        Parameters\n        ----------\n        mag_limit : float, optional\n            Only sample individual stars that are brighter than this magnitude.\n        mag_limit_band : str, optional\n            Bandpass of the limiting magnitude.\n\n        Returns\n        -------\n        m_lim : float\n            Initial stellar mass associated with `mag_limit`.\n        f_num_sampled : float\n            Fraction of stars that will be sampled by number.\n        f_mass_sampled : float\n            Fraction of stars that will be sampled by mass.\n        \"\"\"\n        iso = self.isochrone\n        imfint = IMFIntegrator(self.imf, iso.m_min, iso.m_max)\n        m_lim = iso.m_min\n        f_num_sampled = 1.0\n        f_mass_sampled = 1.0\n        if mag_limit is not None:\n            if  mag_limit_band is None:\n                raise Exception('Must give bandpass of limiting magnitude.')\n            mags = iso.mag_table[mag_limit_band] + self.dist_mod\n            if mag_limit < mags.max() and mag_limit > mags.min():\n                m_lim = iso.mag_to_mass(\n                    mag_limit - self.dist_mod, mag_limit_band).min()\n                f_num_sampled  = imfint.integrate(m_lim, iso.m_max, True)\n                f_mass_sampled = imfint.m_integrate(m_lim, iso.m_max, True)\n            else:\n                logger.warning(f'mag_lim = {mag_limit} is outside mag range.')\n        return m_lim, f_num_sampled, f_mass_sampled\n\n    def __add__(self, ssp):\n        assert StellarPopulation in ssp.__class__.__mro__, 'invalid type(s)'\n        assert self.filters == ssp.filters, 'must have same filters'\n        assert self.distance == ssp.distance, 'SSPs must have same distance'\n        new = deepcopy(self)\n        if type(new.isochrone) != list:\n            new.isochrone = [new.isochrone]\n        if type(ssp.isochrone) != list:\n            new.isochrone.append(ssp.isochrone)\n        else:\n            new.isochrone.extend(ssp.isochrone)\n\n        if not hasattr(new, 'ssp_total_masses'):\n            new.ssp_total_masses = [new.total_mass]\n        if not hasattr(ssp, 'ssp_total_masses'):\n            ssp.ssp_total_masses = [ssp.total_mass]\n        new.ssp_total_masses.extend(ssp.ssp_total_masses)\n\n        if not hasattr(new, 'ssp_total_num_stars'):\n            _n = new.num_stars + new.num_stars_integrated\n            new.ssp_total_num_stars = [_n]\n        if not hasattr(ssp, 'ssp_total_num_stars'):\n            _n = ssp.num_stars + ssp.num_stars_integrated\n            ssp.ssp_total_num_stars = [_n]\n        new.ssp_total_num_stars.extend(ssp.ssp_total_num_stars)\n\n        new.total_mass = new.total_mass + ssp.total_mass\n        new.sampled_mass = new.sampled_mass + ssp.sampled_mass\n        new.live_star_mass = new.live_star_mass + ssp.live_star_mass\n        new.frac_mass_sampled = new.sampled_mass / new.live_star_mass\n\n        new_num_stars_total = new.num_stars + new.num_stars_integrated\n        ssp_num_stars_total = ssp.num_stars + ssp.num_stars_integrated\n        total_num_stars = new_num_stars_total + ssp_num_stars_total\n        new.num_stars_integrated += ssp.num_stars_integrated\n\n        new.initial_masses = np.concatenate(\n            [new.initial_masses, ssp.initial_masses])\n        new.star_masses = np.concatenate([new.star_masses, ssp.star_masses])\n        new.frac_num_sampled = new.num_stars / total_num_stars\n\n        new.ssp_num_fracs = []\n        new.ssp_mass_fracs = []\n        for n, m in zip(new.ssp_total_num_stars, new.ssp_total_masses):\n            new.ssp_num_fracs.append(n / total_num_stars)\n            new.ssp_mass_fracs.append(m / new.total_mass)\n\n        # Loop over optional attributes.\n        # Both SSPs must have the arrtibute to add them.\n        for attr in ['eep', 'log_L', 'log_Teff']:\n            if hasattr(new, attr) and hasattr(ssp, attr):\n                new_attr = getattr(new, attr)\n                ssp_attr = getattr(ssp, attr)\n                setattr(new, attr, np.concatenate([new_attr, ssp_attr]))\n\n        new_label = np.ones(len(ssp.star_masses), dtype=int)\n        new_label *= len(new.isochrone)\n        new.ssp_labels = np.concatenate([new.ssp_labels, new_label])\n\n        if hasattr(new, 'log_age'):\n            if type(new.log_age) != list:\n                new.log_age = [new.log_age]\n            new.log_age.append(ssp.log_age)\n        if hasattr(new, 'feh'):\n            if type(new.feh) != list:\n                new.feh = [new.feh]\n            new.feh.append(ssp.feh)\n\n        for filt in new.filters:\n            _mags = [new.abs_mags[filt], ssp.abs_mags[filt]]\n            new.abs_mags[filt] = np.concatenate(_mags)\n            if new.has_integrated_component and ssp.has_integrated_component:\n                new_flux = 10**(-0.4 * new.integrated_abs_mags[filt])\n                ssp_flux = 10**(-0.4 * ssp.integrated_abs_mags[filt])\n                flux = new_flux + ssp_flux\n                new.integrated_abs_mags[filt] = -2.5 * np.log10(flux)\n                new_lumlum = 10**new._integrated_log_lumlum[filt]\n                ssp_lumlum = 10**ssp._integrated_log_lumlum[filt]\n                log_lumlum = np.log10(new_lumlum + ssp_lumlum)\n                new._integrated_log_lumlum[filt] = log_lumlum\n            elif ssp.has_integrated_component:\n                new.integrated_abs_magw[filt] = ssp.integrated_abs_mags[filt]\n                log_lumlum =  ssp._integrated_log_lumlum[filt]\n                new._integrated_log_lumlum[filt] = log_lumlum\n\n        return CompositePopulation(new)\n\n    def __repr__(self):\n        r = [f'{k} = {v}' for k, v in self._r.items()]\n        t = 'Simple Stellar Population\\n-------------------------\\n'\n        return t + '\\n'.join(r)\n\n\nclass MISTSSP(SSP):\n    \"\"\"\n    MIST Simple Stellar Population.\n\n    .. note::\n        You must give `total_mass` *or* `num_stars`.\n\n    Parameters\n    ----------\n    log_age : float\n        Log (base 10) of the simple stellar population age in years.\n    feh : float\n        Metallicity [Fe/H] of the simple stellar population.\n    phot_system : str or list-like\n        Name of the photometric system(s).\n    num_stars : int or `None`\n        Number of stars in source. If `None`, then must give `total_mass`.\n    total_mass : float or `~astropy.units.Quantity` or `None`\n        Stellar mass of the source. If `None`, then must give `num_stars`. This\n        mass accounts for stellar remnants when ``add_remnants = True``, which\n        means the actual sampled mass will be less than the given value. If\n        float is given, the units are assumed to be solar masses.\n    distance : float or `~astropy.units.Quantity`, optional\n        Distance to source. If float is given, the units are assumed\n        to be `~astropy.units.Mpc`. Default distance is 10 `~astropy.units.pc`.\n    mag_limit : float, optional\n        Only sample individual stars that are brighter than this magnitude. All\n        fainter stars will be combined into an integrated component. Otherwise,\n        all stars in the population will be sampled. You must also give the\n        `mag_limit_band` if you use this parameter.\n    mag_limit_band : str, optional\n        Bandpass of the limiting magnitude. You must give this parameter if\n        you use the `mag_limit` parameter.\n    imf : str, optional\n        The initial stellar mass function. Default is `'kroupa'`.\n    mist_path : str, optional\n        Path to MIST isochrone grids. Use this if you want to use a different\n        path from the `MIST_PATH` environment variable.\n    imf_kw : dict, optional\n        Optional keyword arguments for sampling the stellar mass function.\n    mass_tolerance : float, optional\n        Tolerance in the fractional difference between the input mass and the\n        final mass of the population. The parameter is only used when\n        `total_mass` is given.\n    add_remnants : bool, optional\n        If True (default), apply scaling factor to total mass to account for\n        stellar remnants in the form of white dwarfs, neutron stars,\n        and black holes.\n    random_state : `None`, int, list of ints, or `~numpy.random.RandomState`\n        If `None`, return the `~numpy.random.RandomState` singleton used by\n        ``numpy.random``. If `int`, return a new `~numpy.random.RandomState`\n        instance seeded with the `int`.  If `~numpy.random.RandomState`,\n        return it. Otherwise raise ``ValueError``.\n    \"\"\"\n\n    phases = ['PMS', 'MS', 'giants', 'RGB', 'CHeB', 'AGB',\n              'EAGB', 'TPAGB', 'postAGB', 'WDCS']\n\n    def __init__(self, log_age, feh, phot_system, num_stars=None,\n                 total_mass=None, distance=10*u.pc, mag_limit=None,\n                 mag_limit_band=None, imf='kroupa', mist_path=MIST_PATH,\n                 imf_kw={}, mass_tolerance=0.05, add_remnants=True,\n                 random_state=None, **kwargs):\n\n        self.feh = feh\n        self.log_age = log_age\n        self.phot_system = phot_system\n        self.mist_path = mist_path\n        _iso = MISTIsochrone(log_age, feh, phot_system,  mist_path, **kwargs)\n\n        super(MISTSSP, self).__init__(\n            isochrone=_iso,\n            num_stars=num_stars,\n            total_mass=total_mass,\n            distance=distance,\n            mag_limit=mag_limit,\n            mag_limit_band=mag_limit_band,\n            imf=imf,\n            imf_kw=imf_kw,\n            mass_tolerance=mass_tolerance,\n            add_remnants=add_remnants,\n            random_state=random_state\n        )\n\n        self._r.update({'log(age/yr)': self.log_age,\n                        '[Fe/H]': self.feh,\n                        'photometric system': self.phot_system})\n\n    def select_phase(self, phase):\n        \"\"\"\n        Generate stellar evolutionary phase mask. The mask will be `True` for\n        sources that are in the give phase according to the MIST EEPs.\n\n        Parameters\n        ----------\n        phase : str\n            Evolutionary phase to select. Options are 'all', 'MS', 'giants',\n            'RGB', 'CHeB', 'AGB', 'EAGB', 'TPAGB', 'postAGB', or 'WDCS'.\n\n        Returns\n        -------\n        mask : `~numpy.ndarray`\n            Mask that is `True` for stars in input phase and `False` otherwise.\n\n        Notes\n        -----\n        The MIST EEP phases were taken from Table II: Primary Equivalent\n        Evolutionary Points (EEPs):\n        http://waps.cfa.harvard.edu/MIST/README_tables.pdf\n        \"\"\"\n        if phase == 'all':\n            mask = np.ones_like(self.eep, dtype=bool)\n        elif phase == 'PMS':\n            mask = self.eep < 202\n        elif phase == 'MS':\n            mask = (self.eep >= 202) & (self.eep < 454)\n        elif phase == 'giants':\n            mask = (self.eep >= 454) & (self.eep < 1409)\n        elif phase == 'RGB':\n            mask = (self.eep >= 454) & (self.eep <= 605)\n        elif phase == 'CHeB':\n            mask = (self.eep > 605) & (self.eep < 707)\n        elif phase == 'AGB':\n            mask = (self.eep >= 707) & (self.eep < 1409)\n        elif phase == 'EAGB':\n            mask = (self.eep >= 707) & (self.eep < 808)\n        elif phase == 'TPAGB':\n            mask = (self.eep >= 808) & (self.eep < 1409)\n        elif phase == 'postAGB':\n            mask = (self.eep >= 1409) & (self.eep <= 1710)\n        elif phase == 'WDCS':\n            mask = self.eep > 1710\n        else:\n            raise Exception('Uh, what phase u want?')\n\n        return mask\n\n    def get_star_phases(self):\n        \"\"\"Returns the stellar phases (as defined by the MIST EEPs).\"\"\"\n        phase_list = ['PMS', 'MS', 'RGB', 'CHeB', 'EAGB',\n                      'TPAGB', 'postAGB', 'WDCS']\n        star_phases = np.array([''] * self.num_stars, dtype='<U8')\n        for phase in phase_list:\n            star_phases[self.select_phase(phase)] = phase\n        return star_phases\n\n\nclass CompositePopulation(SSP):\n    \"\"\"\n    Composite stellar populations.\n    \"\"\"\n\n    def __init__(self, pop):\n\n        for name, attr in pop.__dict__.items():\n            setattr(self, name, attr)\n\n    def __repr__(self):\n        num_fracs = self.ssp_num_fracs\n        mass_fracs = self.ssp_mass_fracs\n        r = {'N_pops': self.num_pops,\n             'M_star': f'{self.total_mass.value:.2e} M_sun',\n             'number fractions': [f'{p * 100:.2f}%' for p in num_fracs],\n             'mass fractions': [f'{p * 100:.2f}%' for p in mass_fracs]}\n        if hasattr(self, 'log_age'):\n            r['log(age/yr)'] = self.log_age\n        if hasattr(self, 'feh'):\n            r['[Fe/H]'] = self.feh\n        if hasattr(self, 'phot_system'):\n            r['photometric system'] = self.phot_system\n        r = [f'{k} = {v}' for k, v in r.items()]\n        t = 'Composite Population\\n--------------------\\n'\n        return t + '\\n'.join(r)\n\n\ndef constant_sb_stars_per_pix(sb, mean_mag, distance=10*u.pc, pixel_scale=0.2):\n    \"\"\"\n    Calculate the number of stars per pixel for a uniform\n    distribution (i.e., constant surface brightness) of stars.\n\n    Parameters\n    ----------\n    sb : float\n        Surface brightness of stellar population.\n    mean_mag : float\n        Mean stellar magnitude of the stellar population.\n    distance : float or `~astropy.units.Quantity`\n        Distance to source. If float is given, the units are assumed\n        to be `~astropy.units.Mpc`.\n    pixel_scale : float or `~astropy.units.Quantity`, optional\n        The pixel scale of the mock image. If a float is given, the units will\n        be assumed to be `~astropy.units.arcsec` per `~astropy.units.pixels`.\n\n    Returns\n    -------\n    num_stars_per_pix : float\n        The number of stars per pixel.\n    \"\"\"\n    distance = check_units(distance, 'Mpc').to('pc').value\n    pixel_scale = check_units(pixel_scale, u.arcsec / u.pixel).value\n    dist_mod = 5 * np.log10(distance) - 5\n    num_stars_per_arsec_sq = 10**(0.4 * (mean_mag + dist_mod -  sb))\n    num_stars_per_pix = num_stars_per_arsec_sq * pixel_scale**2\n    return num_stars_per_pix\n", "meta": {"hexsha": "fa590a8c7c1a9fbbd98f62e10e4e506006189918", "size": 33257, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/artpop/stars/populations.py", "max_stars_repo_name": "eteq/ArtPop", "max_stars_repo_head_hexsha": "c510d409196c4296024214c2e01766d1ca97b3dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2021-09-22T21:28:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T02:52:46.000Z", "max_issues_repo_path": "src/artpop/stars/populations.py", "max_issues_repo_name": "eteq/ArtPop", "max_issues_repo_head_hexsha": "c510d409196c4296024214c2e01766d1ca97b3dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-12-16T17:43:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-07T20:12:13.000Z", "max_forks_repo_path": "src/artpop/stars/populations.py", "max_forks_repo_name": "eteq/ArtPop", "max_forks_repo_head_hexsha": "c510d409196c4296024214c2e01766d1ca97b3dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-12-17T03:50:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T16:58:57.000Z", "avg_line_length": 39.2644628099, "max_line_length": 80, "alphanum_fraction": 0.6050455543, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 8126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.2720245451923523, "lm_q1q2_score": 0.1703211407489033}}
{"text": "# Onufriev-Bashford-Case Generalized Born term\n# can be added to any other force field\n\nimport numpy as np\n\nfrom MMTK import ParticleScalar\nfrom MMTK.ForceFields.ForceField import ForceField\n\nclass OBCForceField(ForceField):\n\n    \"\"\"\n    Onufriev-Bashford-Case Generalized Born\n    \"\"\"\n\n    def __init__(self,\n          prmtopFN=None,\n          inv_prmtop_atom_order=None,\n          desolvationGridFN=None,\n          r_min = 0.14,\n          r_max = 1.0,\n          strength=1.0):\n        \"\"\"\n        @param prmtopFN: an AMBER parameter and topology file\n        @type strength:  C{str}\n        r_min and r_max should be in units of nanometers\n        \"\"\"\n        # Initialize the ForceField class, giving a name to this one.\n        ForceField.__init__(self, 'OBC')\n\n        # Store arguments that recreate the force field from a pickled\n        # universe or from a trajectory.\n        self.arguments = (prmtopFN, inv_prmtop_atom_order, \\\n          desolvationGridFN, r_min, r_max, strength)\n\n        # Load the desolvation grid\n        if desolvationGridFN is not None:\n          import AlGDock.IO\n          IO_Grid = AlGDock.IO.Grid()\n          self.grid_data = IO_Grid.read(desolvationGridFN, multiplier=0.1)\n          if not (self.grid_data['origin']==0.0).all():\n            raise Exception('Trilinear grid origin in %s not at (0, 0, 0)!'%FN)\n          self.useDesolvationGrid = True\n        else:\n          self.grid_data = {'spacing':np.array([0., 0., 0.]), \\\n                            'counts':np.array([0, 0, 0]), \\\n                            'vals':np.array([])}\n          self.useDesolvationGrid = False\n        \n        # Store arguments as class variables\n        self.prmtopFN = prmtopFN\n        self.inv_prmtop_atom_order = inv_prmtop_atom_order\n        self.desolvationGridFN = desolvationGridFN\n        self.r_min = r_min\n        self.r_max = r_max\n        self.strength = strength\n\n    def set_strength(self, strength):\n      self.strength = strength\n\n    # The following method is called by the energy evaluation engine\n    # to inquire if this force field term has all the parameters it\n    # requires. This is necessary for interdependent force field\n    # terms. In our case, we just say \"yes\" immediately.\n    def ready(self, global_data):\n        return True\n\n    # The following method is called by the energy evaluation engine\n    # to obtain a list of the low-level evaluator objects (the C routines)\n    # that handle the calculations.\n    def evaluatorTerms(self, universe, subset1, subset2, global_data):\n        # The energy for subsets is defined as consisting only\n        # of interactions within that subset, so the contribution\n        # of an external field is zero. Therefore we just return\n        # an empty list of energy terms.\n        if subset1 is not None or subset2 is not None:\n            return []\n\n        import numpy as np\n        if (self.prmtopFN is not None) and \\\n           (self.inv_prmtop_atom_order is not None):\n          # Get charges, radii, and scale factors from OpenMM\n          import simtk.openmm\n          import simtk.openmm.app as OpenMM_app\n          \n          prmtop = OpenMM_app.AmberPrmtopFile(self.prmtopFN)\n          OMM_system = prmtop.createSystem(\\\n            nonbondedMethod=OpenMM_app.CutoffNonPeriodic, \\\n            nonbondedCutoff=1.5, \\\n            constraints=None, \\\n            implicitSolvent=OpenMM_app.OBC2)\n          f = OMM_system.getForces()[-2]\n\n          numParticles = f.getNumParticles()\n          charges = np.zeros(numParticles)\n          atomicRadii = np.zeros(numParticles)\n          scaleFactors = np.zeros(numParticles)\n          for n in range(numParticles):\n            (charge, radius, scaleFactor) = f.getParticleParameters(n)\n            charges[n] = charge/simtk.unit.elementary_charge\n            atomicRadii[n] = radius/simtk.unit.nanometer\n            scaleFactors[n] = scaleFactor\n\n          charges = charges[self.inv_prmtop_atom_order]\n          atomicRadii = atomicRadii[self.inv_prmtop_atom_order]\n          scaleFactors = scaleFactors[self.inv_prmtop_atom_order]\n        else:\n          # Get charges, radii, and scale factors from the ligand database (preferred)\n          charges_ps = ParticleScalar(universe)\n          atomicRadii_ps = ParticleScalar(universe)\n          scaleFactors_ps = ParticleScalar(universe)\n          for o in universe:\n            for a in o.atomList():\n              charges_ps[a] = o.getAtomProperty(a, 'amber_charge')\n              atomicRadii_ps[a] = o.getAtomProperty(a, 'scaling_factor_BornRadii')\n              scaleFactors_ps[a] = o.getAtomProperty(a, 'scaling_factor_BornScreening')\n          charges = charges_ps.array\n          atomicRadii = atomicRadii_ps.array\n          scaleFactors = scaleFactors_ps.array\n          numParticles = charges.shape[0]\n          \n#        import time\n#        import os.path\n#        import MMTK_OBC\n#        OBCpath = MMTK_OBC.__file__\n#        print \"\"\"\n#        in {0}\n#        last modified {1}\n#            \"\"\".format(OBCpath, time.ctime(os.path.getmtime(OBCpath)))\n\n        # Here we pass all the parameters as \"simple\" data types to\n        # the C code that handles energy calculations.\n        if self.useDesolvationGrid:\n          # With desolvation grid\n          from MMTK_OBC_desolv import OBCDesolvTerm\n          return [OBCDesolvTerm(universe._spec, numParticles, self.strength, \\\n            charges, atomicRadii, scaleFactors, \\\n            self.grid_data['spacing'], self.grid_data['counts'], \\\n            self.grid_data['vals'], self.r_min, self.r_max)]\n        else:\n          # No desolvation grid\n          from MMTK_OBC import OBCTerm\n          return [OBCTerm(universe._spec, numParticles, self.strength, \\\n            charges, atomicRadii, scaleFactors)]\n", "meta": {"hexsha": "c72fcd5d3408617c2f57d711e97439b564d9b540", "size": 5777, "ext": "py", "lang": "Python", "max_stars_repo_path": "AlGDock/ForceFields/OBC/OBC.py", "max_stars_repo_name": "CCBatIIT/AlGDock", "max_stars_repo_head_hexsha": "25c376e9d860d50696f5e20f1b107d289ec0903c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2015-06-16T19:25:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T05:50:47.000Z", "max_issues_repo_path": "AlGDock/ForceFields/OBC/OBC.py", "max_issues_repo_name": "biocheming/AlGDock", "max_issues_repo_head_hexsha": "25c376e9d860d50696f5e20f1b107d289ec0903c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2015-05-06T21:05:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T09:51:45.000Z", "max_forks_repo_path": "AlGDock/ForceFields/OBC/OBC.py", "max_forks_repo_name": "biocheming/AlGDock", "max_forks_repo_head_hexsha": "25c376e9d860d50696f5e20f1b107d289ec0903c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2015-04-13T21:11:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T00:25:42.000Z", "avg_line_length": 40.1180555556, "max_line_length": 87, "alphanum_fraction": 0.6273152155, "include": true, "reason": "import numpy", "num_tokens": 1403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.27512973571032984, "lm_q1q2_score": 0.17024489719866873}}
{"text": "# Copyright 2016, FBPIC contributors\n# Authors: Remi Lehe, Manuel Kirchen\n# License: 3-Clause-BSD-LBNL\n\"\"\"\nThis file is part of the Fourier-Bessel Particle-In-Cell code (FB-PIC)\nIt defines the structure and methods associated with atomic ionization.\n\nThe implemented ionization model is the ADK model. The implementation\nis fully relativistic (i.e. it works in the boosted-frame as well).\n\nIonization is implemented by keeping ions at different ionization states in\nthe same Particles object, so that the number of macroparticles in this object\nremains constant and arrays do not have to be reallocated (except when the\nmoving window creates new particles.) An array `ionization_level` keeps track\nof the ionization state of each macroparticle.\n\nOn the other hand, the electrons generated by ionization do need to be added to\nan existing Particles object, and this implies that the number of\nmacroparticles in the object does not remain constant and that the arrays are\nreallocated.\n\nIn addition, at each PIC iteration, the number of new electrons need to\nbe counted in order to reallocate the array and copy the electrons to\nthe right indices. This basically involves a cumulative sum operation, which\ndifficult to implement on the GPU. For this reason, the corresponding array is\nsent to the CPU, which performs the cumulative sum and sends the data back to\nthe GPU. In order, to limit the amount of data to be transfered, particles are\nhandled in batches of 10 particles, so that only the cumulative sum of the\nnumber of particles in each batch need to be performed.\n\"\"\"\nimport numpy as np\nfrom scipy.constants import c, e, m_e, physical_constants\nfrom scipy.special import gamma\nfrom .read_atomic_data import get_ionization_energies\nfrom .numba_methods import ionize_ions_numba, copy_ionized_electrons_numba\nfrom ..cuda_numba_utils import allocate_empty, reallocate_and_copy_old, \\\n                                perform_cumsum_2d, generate_new_ids\n\n# Check if CUDA is available, then import CUDA functions\nfrom fbpic.utils.cuda import cuda_installed\nfrom fbpic.utils.printing import catch_gpu_memory_error\nif cuda_installed:\n    import cupy\n    from fbpic.utils.cuda import cuda_tpb_bpg_1d\n    from .cuda_methods import ionize_ions_cuda, copy_ionized_electrons_cuda\n    \nclass Ionizer(object):\n    \"\"\"\n    Class that contains the data associated with ionization (on the ions side)\n    and has method to calculate the ionization probability.\n\n    The implemented ionization model is the ADK model. The implementation\n    is fully relativistic (i.e. it works in the boosted-frame as well).\n\n    Main attributes\n    ---------------\n    - ionization_level: 1darray of integers (one element per particle)\n      which contains the ionization state of each particle\n    - w_times_level: 1darray of floats (one element per particle)\n      which contains the number of physical particle that correspond to each\n      macroparticle, multiplied by the ionization level. (This is updated\n      whenever further ionization happens, and is passed to the deposition\n      kernel as the effective weight of the particles)\n    \"\"\"\n    def __init__(self, element, ionizable_species, target_species,\n                 level_start, level_max=None):\n        \"\"\"\n        Initialize an Ionizer instance\n\n        Parameters\n        ----------\n        element: string\n            The atomic symbol of the considered ionizable species\n            (e.g. 'He', 'N' ;  do not use 'Helium' or 'Nitrogen')\n\n        ionizable_species: an fbpic.Particles object\n            This object is not modified or registered.\n            It is only used in order to pass a number of additional argument.\n\n        target_species: a `Particles` object, or a dictionary of `Particles`\n            Stores the electron macroparticles that are created in\n            the ionization process.\n\n            - If a single `Particles` object is passed, than electrons from all\n            ionization levels are stored into this object.\n\n            - If a dictionary is passed, then its keys should be integers\n            (corresponding to the ionizable levels of `element`, starting\n            at `level_start`), and its values should be `Particles` objects.\n            In this case, the electrons from each distinct ionizable level\n            will be stored into these separate objects. Note that using\n            separate objects will typically require longer computing time.\n\n            These objects are not modified when creating the class, but\n            they are when ionization occurs (i.e. more particles are created)\n\n        level_start: int\n            The ionization level at which the macroparticles are initially\n            (e.g. 0 for initially neutral atoms)\n\n        level_max: int, optional\n            If not None, defines the maximum ionization level that\n            macroparticles can reach. Should not exceed the physical\n            limit for the chosen element.\n        \"\"\"\n        # Register a few parameters\n        self.level_start = level_start\n        self.level_max = level_max\n        self.use_cuda = ionizable_species.use_cuda\n        # Process ionized particles into batches\n        self.batch_size = 10\n\n        # Initialize ionization-relevant meta-data\n        self.initialize_ADK_parameters( element, ionizable_species.dt )\n\n        # Initialize the required arrays\n        Ntot = ionizable_species.Ntot\n        self.ionization_level = np.ones( Ntot, dtype=np.uint64 ) * level_start\n        self.w_times_level = ionizable_species.w * self.ionization_level\n\n        # Check if electrons from different ionization levels should\n        # be stored into separate species\n        if type(target_species) is dict:\n            # When passing a dictionary\n            # Check that the keys are the right integers\n            for level in range(self.level_start, self.level_max):\n                if level not in target_species.keys():\n                    raise ValueError(\n                    'When passing a dictionary for `target_species`, its keys '\n                    'should be\\nthe integers corresponding to the ionizable '\n                    'levels.\\n (i.e. the integers from %d to %d'\n                    'for %s with level_start=%d.)' %(self.level_start,\n                    self.level_max, element, self.level_start))\n                # Check that the dictionary contains Particles objects\n                assert isinstance(target_species[level], type(ionizable_species))\n            # Convert to a list internally: the dictionary input is\n            # just for less error-prone user input.\n            self.target_species = [ target_species[level] \\\n                for level in range(self.level_start, self.level_max) ]\n            self.store_electrons_per_level = True\n        elif isinstance(target_species, type(ionizable_species)):\n            # When passing a single Particles object\n            self.target_species = [target_species]  # List of one element\n            self.store_electrons_per_level = False\n        else:\n            raise ValueError(\n                \"Unexpected type for target_species: %s\\n\"\n                \"Please pass a `Particles` object, or a dictionary\"\n                %type(target_species))\n\n        # Check that the target species are indeed electrons\n        for species in self.target_species:\n            assert species.q == -e\n            assert species.m == m_e\n\n\n    def initialize_ADK_parameters( self, element, dt ):\n        \"\"\"\n        Initialize parameters needed for the calculation of ADK ionization rate\n\n        Parameters\n        ----------\n        element: string\n            The atomic symbol of the considered ionizable species\n            (e.g. 'He', 'N' ;  do not use 'Helium' or 'Nitrogen')\n\n        dt: float (in seconds)\n            The timestep of the simulation. (The calculated ionization\n            probability is a probability *per timestep*.)\n\n        See Chen, JCP 236 (2013), equation (2) for the ionization rate formula\n        \"\"\"\n        # Get the array of energies\n        Uion = get_ionization_energies( element )\n        # Check whether the element string was valid\n        if Uion is None:\n            raise ValueError(\"Unknown ionizable element %s.\\n\" %element + \\\n            \"Please use atomic symbol (e.g. 'He') not full name (e.g. Helium)\")\n        else:\n            self.element = element\n\n        # Determine and set the maximum level of ionization\n        if self.level_max is None:\n            self.level_max = len(Uion)\n        else:\n            assert type(self.level_max) is int, \"level_max must be integer\"\n            if self.level_max>len(Uion):\n                raise ValueError(\"Chosen level_max for {}\".format(element) + \\\n                                 \" cannot exceed {}\".format(len(Uion)))\n\n        # Calculate the ADK prefactors (See Chen, JCP 236 (2013), equation (2))\n        # - Scalars\n        alpha = physical_constants['fine-structure constant'][0]\n        r_e = physical_constants['classical electron radius'][0]\n        wa = alpha**3 * c / r_e\n        Ea = m_e*c**2/e * alpha**4/r_e\n        # - Arrays (one element per ionization level)\n        UH = get_ionization_energies('H')[0]\n        Z = np.arange( len(Uion) ) + 1\n        n_eff = Z * np.sqrt( UH/Uion )\n        l_eff = n_eff[0] - 1\n        C2 = 2**(2*n_eff) / (n_eff * gamma(n_eff+l_eff+1) * gamma(n_eff-l_eff))\n        # For now, we assume l=0, m=0\n        self.adk_power = - (2*n_eff - 1)\n        self.adk_prefactor = dt * wa * C2 * ( Uion/(2*UH) ) \\\n            * ( 2*(Uion/UH)**(3./2)*Ea )**(2*n_eff - 1)\n        self.adk_exp_prefactor = -2./3 * ( Uion/UH )**(3./2) * Ea\n\n\n    @catch_gpu_memory_error\n    def handle_ionization( self, ion ):\n        \"\"\"\n        Handle ionization, either on CPU or GPU\n\n        - For each ion macroparticle, decide whether it is going to\n          be further ionized during this timestep, based on the ADK rate.\n        - Add the electrons created from ionization to the `target_species`\n\n        Parameters:\n        -----------\n        ion: an fbpic.Particles object\n            The ionizable species, from which new electrons are created.\n        \"\"\"\n        # Skip this function if there are no ions\n        if ion.Ntot == 0:\n            return\n        \n        # Process particles in batches (of typically 10, 20 particles)\n        N_batch = int( ion.Ntot / self.batch_size ) + 1\n        # Short-cuts\n        use_cuda = self.use_cuda\n\n        # Set the number of levels that should be distinguished\n        if self.store_electrons_per_level:\n            n_levels = self.level_max - self.level_start\n        else:\n            n_levels = 1\n\n        # Create temporary arrays (on CPU or GPU, depending on `use_cuda`)\n        ionized_from = allocate_empty( ion.Ntot, use_cuda, dtype=np.int16 )\n        n_ionized = allocate_empty( (n_levels, N_batch), use_cuda,\n                                    dtype=np.int64 )\n        # Draw random numbers\n        if self.use_cuda:\n            random_draw = cupy.random.rand( ion.Ntot, dtype=cupy.float32 )\n        else:\n            random_draw = np.random.rand( ion.Ntot )\n\n        # Determine the ions that are ionized, and count them in each batch\n        # (one thread per batch on GPU; parallel loop over batches on CPU)\n        if use_cuda:\n            batch_grid_1d, batch_block_1d = cuda_tpb_bpg_1d( N_batch )\n            ionize_ions_cuda[ batch_grid_1d, batch_block_1d ](\n                N_batch, self.batch_size, ion.Ntot,\n                self.level_start, self.level_max, n_levels,\n                n_ionized, ionized_from, self.ionization_level, random_draw,\n                self.adk_prefactor, self.adk_power, self.adk_exp_prefactor,\n                ion.ux, ion.uy, ion.uz, ion.Ex, ion.Ey, ion.Ez,\n                ion.Bx, ion.By, ion.Bz, ion.w, self.w_times_level )\n        else:\n            ionize_ions_numba(\n                N_batch, self.batch_size, ion.Ntot,\n                self.level_start, self.level_max, n_levels,\n                n_ionized, ionized_from, self.ionization_level, random_draw,\n                self.adk_prefactor, self.adk_power, self.adk_exp_prefactor,\n                ion.ux, ion.uy, ion.uz, ion.Ex, ion.Ey, ion.Ez,\n                ion.Bx, ion.By, ion.Bz, ion.w, self.w_times_level )\n\n        # Count the total number of new electrons \n        cumulative_n_ionized = perform_cumsum_2d( n_ionized, use_cuda )\n        # If no new particle was created, skip the rest of this function\n        if use_cuda:\n            if cupy.all( cumulative_n_ionized[:,-1] == 0 ):\n                return\n        else:\n            if np.all( cumulative_n_ionized[:,-1] == 0 ):\n                return\n\n        # Loop over the electron species associated to each level\n        # (when store_electrons_per_level is False, there is a single species)\n        # Reallocate electron species (on CPU or GPU depending on `use_cuda`),\n        # to accomodate the electrons produced by ionization,\n        # and copy the old electrons to the new arrays\n        assert len(self.target_species) == n_levels\n        for i_level, elec in enumerate(self.target_species):\n            old_Ntot = elec.Ntot\n            # Cast to int transfers the data from the GPU if needed\n            new_Ntot = old_Ntot + int( cumulative_n_ionized[i_level,-1] )\n            reallocate_and_copy_old( elec, use_cuda, old_Ntot, new_Ntot )\n            # Create the new electrons from ionization (one thread per batch)\n            if use_cuda:\n                copy_ionized_electrons_cuda[ batch_grid_1d, batch_block_1d ](\n                    N_batch, self.batch_size, old_Ntot, ion.Ntot,\n                    cumulative_n_ionized, ionized_from,\n                    i_level, self.store_electrons_per_level,\n                    elec.x, elec.y, elec.z, elec.inv_gamma,\n                    elec.ux, elec.uy, elec.uz, elec.w,\n                    elec.Ex, elec.Ey, elec.Ez, elec.Bx, elec.By, elec.Bz,\n                    ion.x, ion.y, ion.z, ion.inv_gamma,\n                    ion.ux, ion.uy, ion.uz, ion.w,\n                    ion.Ex, ion.Ey, ion.Ez, ion.Bx, ion.By, ion.Bz )\n                # Mark the new electrons as unsorted\n                elec.sorted = False\n            else:\n                copy_ionized_electrons_numba(\n                    N_batch, self.batch_size, old_Ntot, ion.Ntot,\n                    cumulative_n_ionized, ionized_from,\n                    i_level, self.store_electrons_per_level,\n                    elec.x, elec.y, elec.z, elec.inv_gamma,\n                    elec.ux, elec.uy, elec.uz, elec.w,\n                    elec.Ex, elec.Ey, elec.Ez, elec.Bx, elec.By, elec.Bz,\n                    ion.x, ion.y, ion.z, ion.inv_gamma,\n                    ion.ux, ion.uy, ion.uz, ion.w,\n                    ion.Ex, ion.Ey, ion.Ez, ion.Bx, ion.By, ion.Bz )\n\n            # If the electrons are tracked, generate new ids\n            # (on GPU or GPU depending on `use_cuda`)\n            generate_new_ids( elec, old_Ntot, new_Ntot )\n\n\n    def send_to_gpu( self ):\n        \"\"\"\n        Copy the ionization data to the GPU.\n        \"\"\"\n        if self.use_cuda:\n            # Arrays with one element per macroparticles\n            self.ionization_level = cupy.asarray( self.ionization_level )\n            self.w_times_level = cupy.asarray( self.w_times_level )\n            # Small-size arrays with ADK parameters\n            # (One element per ionization level)\n            self.adk_power = cupy.asarray( self.adk_power )\n            self.adk_prefactor = cupy.asarray( self.adk_prefactor )\n            self.adk_exp_prefactor = cupy.asarray( self.adk_exp_prefactor )\n\n    def receive_from_gpu( self ):\n        \"\"\"\n        Receive the ionization data from the GPU.\n        \"\"\"\n        if self.use_cuda:\n            # Arrays with one element per macroparticles\n            self.ionization_level = self.ionization_level.get()\n            self.w_times_level = self.w_times_level.get()\n            # Small-size arrays with ADK parameters\n            # (One element per ionization level)\n            self.adk_power = self.adk_power.get()\n            self.adk_prefactor = self.adk_prefactor.get()\n            self.adk_exp_prefactor = self.adk_exp_prefactor.get()\n", "meta": {"hexsha": "d4f70d9cd712fd26c474a44da1133232958185d5", "size": 16184, "ext": "py", "lang": "Python", "max_stars_repo_path": "fbpic/particles/elementary_process/ionization/ionizer.py", "max_stars_repo_name": "wilds9/fbpic", "max_stars_repo_head_hexsha": "902c3bc8757545496b8cbb772401de6b0974a3dc", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 131, "max_stars_repo_stars_event_min_datetime": "2016-09-26T05:57:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T04:32:32.000Z", "max_issues_repo_path": "fbpic/particles/elementary_process/ionization/ionizer.py", "max_issues_repo_name": "RemiLehe/fbpic", "max_issues_repo_head_hexsha": "f0d55048eb669081c26eff28fee39891b62aaeb2", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 398, "max_issues_repo_issues_event_min_datetime": "2016-09-26T14:09:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T23:11:57.000Z", "max_forks_repo_path": "fbpic/particles/elementary_process/ionization/ionizer.py", "max_forks_repo_name": "RemiLehe/fbpic", "max_forks_repo_head_hexsha": "f0d55048eb669081c26eff28fee39891b62aaeb2", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 61, "max_forks_repo_forks_event_min_datetime": "2016-09-26T05:38:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T14:42:53.000Z", "avg_line_length": 46.5057471264, "max_line_length": 81, "alphanum_fraction": 0.6312407316, "include": true, "reason": "import numpy,from scipy,import cupy", "num_tokens": 3750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.27512972382317524, "lm_q1q2_score": 0.17024488597474788}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 21 11:58:46 2021\n\n@author: wanxiang.shen@u.nus.edu\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler\nfrom biopandas.pdb import PandasPdb\nfrom Bio import PDB\nimport io, PIL\nfrom sklearn.metrics import pairwise_distances\n\nfrom .agg import AggMolMap\n\n\n\n#The hydrophobicity values are from JACS, 1962, 84: 4240-4246. (C. Tanford).\n_Hydrophobicity={\"A\":0.62,\"R\":-2.53,\"N\":-0.78,\"D\":-0.90,\"C\":0.29,\"Q\":-0.85,\n                 \"E\":-0.74,\"G\":0.48,\"H\":-0.40,\"I\":1.38,\"L\":1.06,\"K\":-1.50,\n                 \"M\":0.64,\"F\":1.19,\"P\":0.12,\"S\":-0.18,\"T\":-0.05,\"W\":0.81,\"Y\":0.26,\"V\":1.08}\n\n#The hydrophilicity values are from PNAS, 1981, 78:3824-3828 (T.P.Hopp & K.R.Woods).\n_hydrophilicity={\"A\":-0.5,\"R\":3.0,\"N\":0.2,\"D\":3.0,\"C\":-1.0,\"Q\":0.2,\"E\":3.0,\n                 \"G\":0.0,\"H\":-0.5,\"I\":-1.8,\"L\":-1.8,\"K\":3.0,\"M\":-1.3,\n                 \"F\":-2.5,\"P\":0.0,\"S\":0.3,\"T\":-0.4,\"W\":-3.4,\"Y\":-2.3,\"V\":-1.5}\n\n#The side-chain mass: CRC Handbook of Chemistry and Physics, 66th ed., CRC Press, Boca Raton, Florida (1985).\n\n_residuemass={\"A\":15.0,\"R\":101.0,\"N\":58.0,\"D\":59.0,\"C\":47.0,\"Q\":72.0,\n              \"E\":73.0,\"G\":1.000,\"H\":82.0,\"I\":57.0,\"L\":57.0,\"K\":73.0,\n              \"M\":75.0,\"F\":91.0,\"P\":42.0,\"S\":31.0,\"T\":45.0,\"W\":130.0,\"Y\":107.0,\"V\":43.0}\n\n\n#R.M.C. Dawson, D.C. Elliott, W.H. Elliott, K.M. Jones, Data for Biochemical Research 3rd ed., Clarendon Press Oxford (1986).\n_pK1={\"A\":2.35,\"C\":1.71,\"D\":1.88,\"E\":2.19,\"F\":2.58,\"G\":2.34,\"H\":1.78,\n      \"I\":2.32,\"K\":2.20,\"L\":2.36,\"M\":2.28,\"N\":2.18,\"P\":1.99,\"Q\":2.17,\n      \"R\":2.18,\"S\":2.21,\"T\":2.15,\"V\":2.29,\"W\":2.38,\"Y\":2.20}\n\n_pK2={\"A\":9.87,\"C\":10.78,\"D\":9.60,\"E\":9.67,\"F\":9.24,\"G\":9.60,\"H\":8.97,\n      \"I\":9.76,\"K\":8.90,\"L\":9.60,\"M\":9.21,\"N\":9.09,\"P\":10.6,\"Q\":9.13,\n      \"R\":9.09,\"S\":9.15,\"T\":9.12,\"V\":9.74,\"W\":9.39,\"Y\":9.11}\n\n_pI={\"A\":6.11,\"C\":5.02,\"D\":2.98,\"E\":3.08,\"F\":5.91,\"G\":6.06,\"H\":7.64,\n     \"I\":6.04,\"K\":9.47,\"L\":6.04,\"M\":5.74,\"N\":10.76,\"P\":6.30,\n     \"Q\":5.65,\"R\":10.76,\"S\":5.68,\"T\":5.60,\"V\":6.02,\"W\":5.88,\"Y\":5.63}\n\n_AvFlexibility={\"A\":0.357,\"R\":0.529,\"N\":0.463,\"D\":0.511,\"C\":0.346,\"Q\":0.493,\n                \"E\":0.497,\"G\":0.544,\"H\":0.323,\"I\":0.462,\"L\":0.365,\"K\":0.466,\"M\":0.295,\n                \"F\":0.314,\"P\":0.509,\"S\":0.507,\"T\":0.444,\"W\":0.305,\"Y\":0.420,\"V\":0.386}\n\n_Polarizability={\"A\":0.046,\"R\":0.291,\"N\":0.134,\"D\":0.105,\"C\":0.128,\"Q\":0.180,\n                 \"E\":0.151,\"G\":0.000,\"H\":0.230,\"I\":0.186,\"L\":0.186,\"K\":0.219,\n                 \"M\":0.221,\"F\":0.290,\"P\":0.131,\"S\":0.062,\"T\":0.108,\"W\":0.409,\"Y\":0.298,\"V\":0.140}\n\n_FreeEnergy={\"A\":-0.368,\"R\":-1.03,\"N\":0.0,\"D\":2.06,\"C\":4.53,\"Q\":0.731,\n             \"E\":1.77,\"G\":-0.525,\"H\":0.0,\"I\":0.791,\"L\":1.07,\"K\":0.0,\"M\":0.656,\n             \"F\":1.06,\"P\":-2.24,\"S\":-0.524,\"T\":0.0,\"W\":1.60,\"Y\":4.91,\"V\":0.401}\n\n_ResidueASA={\"A\":115.0,\"R\":225.0,\"N\":160.0,\"D\":150.0,\"C\":135.0,\"Q\":180.0,\n             \"E\":190.0,\"G\":75.0,\"H\":195.0,\"I\":175.0,\"L\":170.0,\"K\":200.0,\"M\":185.0,\n             \"F\":210.0,\"P\":145.0,\"S\":115.0,\"T\":140.0,\"W\":255.0,\"Y\":230.0,\"V\":155.0}\n\n_ResidueVol={\"A\":52.6,\"R\":109.1,\"N\":75.7,\"D\":68.4,\"C\":68.3,\"Q\":89.7,\"E\":84.7,\n             \"G\":36.3,\"H\":91.9,\"I\":102.0,\"L\":102.0,\"K\":105.1,\"M\":97.7,\"F\":113.9,\n             \"P\":73.6,\"S\":54.9,\"T\":71.2,\"W\":135.4,\"Y\":116.2,\"V\":85.1}\n\n_Steric={\"A\":0.52,\"R\":0.68,\"N\":0.76,\"D\":0.76,\"C\":0.62,\"Q\":0.68,\"E\":0.68,\n         \"G\":0.00,\"H\":0.70,\"I\":1.02,\"L\":0.98,\"K\":0.68,\"M\":0.78,\"F\":0.70,\n         \"P\":0.36,\"S\":0.53,\"T\":0.50,\"W\":0.70,\"Y\":0.70,\"V\":0.76}\n\n_Mutability={\"A\":100.0,\"R\":65.0,\"N\":134.0,\"D\":106.0,\"C\":20.0,\"Q\":93.0,\"E\":102.0,\n             \"G\":49.0,\"H\":66.0,\"I\":96.0,\"L\":40.0,\"K\":-56.0,\"M\":94.0,\"F\":41.0,\"P\":56.0,\n             \"S\":120.0,\"T\":97.0,\"W\":18.0,\"Y\":41.0,\"V\":74.0}\n\ndef standard_scale(aap):\n    scaler = StandardScaler()\n    s = pd.Series(aap)\n    res = scaler.fit_transform(s.values.reshape(-1,1)).reshape(-1,)\n    return pd.Series(res, index=s.index).to_dict()\n\nIntrinsicAAPs = {'Hydrophobicity':_Hydrophobicity,\n                'Hydrophilicity':_hydrophilicity,\n                'ASA':_ResidueASA,\n                'Flexibility': _AvFlexibility,\n                'FreeEnergy': _FreeEnergy, \n                'Steric': _Steric,                  \n                'pKa':_pK1,\n                'pKb':_pK2,\n                'pI':_pI}\n\n\nclass IntrinsicAAP:\n    def __init__(self, **entries):\n        self.__dict__.update(entries)\n\n\ndef get_pdb_xyzb_ca(df_aa):\n    \n    '''\n    https://en.wikipedia.org/wiki/Protein_contact_map:\n    df_aa is the dataframe that is groupbyed from `residue_name` and  `residue_number`\n    '''\n    #df_aa = df[(df['residue_name'] == 'PRO') & (df['residue_number'] ==2)]\n\n    ts = df_aa[df_aa.atom_name == 'CA'] \n    if len(ts == 1):\n        ts = ts.iloc[-1] ## if multi-CA, select the last one\n        x,y,z,b = ts.x_coord, ts.y_coord, ts.z_coord, ts.b_factor\n    else:\n        x,y,z,b = np.nan, np.nan, np.nan, np.nan\n        aa = df_aa[['residue_name', 'residue_number']].iloc[0].to_dict()\n        print('CA atom not exists in the residue: %s' % aa)  \n    return x,y,z,b\n\n\ndef get_pdb_xyzb_cb(df_aa):\n    '''\n    https://en.wikipedia.org/wiki/Protein_contact_map:\n    \n    df_aa is the dataframe that is groupbyed from `residue_name` and  `residue_number`\n    '''\n    #df_aa = df[(df['residue_name'] == 'PRO') & (df['residue_number'] ==2)]\n    \n    ts = df_aa[df_aa.atom_name == 'CB'] ## if multi-CA, select the last one\n    \n    if len(ts) ==1:\n        ts = ts.iloc[-1]\n        x,y,z,b = ts.x_coord, ts.y_coord, ts.z_coord, ts.b_factor\n    else:\n        ##distance between Cβ-Cβ atoms with threshold 6-12 Å (Cα is used for Glycine):\n        ts = df_aa[df_aa.atom_name == 'CA'] #Case Glycine\n        if len(ts) ==1:\n            ts = ts.iloc[-1]\n            x,y,z,b = ts.x_coord, ts.y_coord, ts.z_coord, ts.b_factor\n        else:\n            x,y,z,b = np.nan, np.nan, np.nan, np.nan\n            aa = df_aa[['residue_name', 'residue_number']].iloc[0].to_dict()\n            print('CA atom not exists in the residue: %s' % aa)            \n    return x,y,z,b\n\n\n\ndef get_pdb_xyzb_mean(df_aa):\n    \n    '''\n    get the mean coord.\n    https://en.wikipedia.org/wiki/Protein_contact_map:\n    df_aa is the dataframe that is groupbyed from `residue_name` and  `residue_number`\n    '''\n    #df_aa = df[(df['residue_name'] == 'PRO') & (df['residue_number'] ==2)]\n\n    x,y,z,b = df_aa[['x_coord', 'y_coord', 'z_coord', 'b_factor']].mean().tolist()\n    \n    return x,y,z,b\n\n\nclass PDB2Fmap:\n    \n    def __init__(self, embd_grain = 'CA', fmap_shape = None):\n        \n        '''\n        embd_grain: {'CA', 'CB', 'mean', 'all'}\n        '''\n        self.embd_grain = embd_grain \n        self.fmap_shape = fmap_shape\n\n        \n        \n    def fit(self, pdb_file, embd_chain = None):\n        '''\n        pdb_file: pdf file path\n        embd_chain: pdb chain to do embedding\n        '''\n        self.pdb_file = pdb_file\n        self.pdb = PandasPdb().read_pdb(self.pdb_file)\n        self.embd_chain = embd_chain\n        \n        if embd_chain != None:\n            self.dfpdb = self.pdb.df['ATOM'][self.pdb.df['ATOM'].chain_id == embd_chain]\n        else:\n            self.dfpdb = self.pdb.df['ATOM']\n        if self.embd_grain == 'mean':\n            df_embd = self.dfpdb.groupby(['residue_number', 'residue_name']).apply(get_pdb_xyzb_mean).apply(pd.Series)\n            df_embd.columns = ['x_coord', 'y_coord', 'z_coord', 'b_factor']\n            df_embd = df_embd.reset_index()\n\n        if self.embd_grain == 'CB':\n            df_embd = self.dfpdb.groupby(['residue_number', 'residue_name']).apply(get_pdb_xyzb_cb).apply(pd.Series) \n            df_embd.columns = ['x_coord', 'y_coord', 'z_coord', 'b_factor']\n            df_embd = df_embd.reset_index()\n\n        if self.embd_grain == 'CA':\n            df_embd = self.dfpdb.groupby(['residue_number', 'residue_name']).apply(get_pdb_xyzb_ca).apply(pd.Series)  \n            df_embd.columns = ['x_coord', 'y_coord', 'z_coord', 'b_factor']\n            df_embd = df_embd.reset_index()\n  \n        if self.embd_grain == 'all':\n            df_embd = self.dfpdb[['residue_name', 'residue_number', 'x_coord', 'y_coord','z_coord', 'b_factor']]\n        \n        df_embd['residue_name_1aa'] = df_embd['residue_name'].map(PDB.protein_letters_3to1)    \n        df_embd.index = df_embd.index.astype(str) + '-' + df_embd['residue_name_1aa']\n        dfx = df_embd[['x_coord','y_coord','z_coord']].T\n        self.dfx = dfx\n        self.df_embd = df_embd\n        self.mp = AggMolMap(dfx, metric='euclidean')\n        self.mp.fit(fmap_shape = self.fmap_shape, cluster_channels=1)\n        self.fmap_shape = self.mp.fmap_shape\n        \n    def transform_xyz(self, scale = True, feature_range=(0, 1)):\n        '''\n        x, y, z coordinates\n        '''\n        if scale:\n            scaler = MinMaxScaler(feature_range = feature_range)\n            x = scaler.fit_transform(self.dfx.T).T\n        else:\n            x = self.dfx.values\n        X = self.mp.batch_transform(x, scale=False)\n        return X\n\n    def transofrm_bf(self, scale = True, feature_range=(0, 1)):\n        '''\n        b-factor\n        '''\n        if scale:\n            scaler = MinMaxScaler(feature_range = feature_range)\n            x = scaler.fit_transform(self.df_embd[['b_factor']]).T\n        else:\n            x = self.df_embd[['b_factor']].values.T\n        X = self.mp.transform(x[0], scale=False)\n        return X\n\n\n    def transofrm_pkt(self, pkt_file):\n        '''\n        pocket pdb file\n        '''\n        self.pkt_file = pkt_file\n\n        ## pocket\n        self.pkt = PandasPdb().read_pdb(self.pkt_file)\n        if self.embd_chain != None:\n            self.dfpkt = self.pkt.df['ATOM'][self.pkt.df['ATOM'].chain_id == self.embd_chain]\n        else:\n            self.dfpkt = self.pkt.df['ATOM']\n            \n        pkt_residue_number = self.dfpkt.residue_number.unique()\n\n        self.df_embd['pocket'] = self.df_embd.residue_number.isin(pkt_residue_number)*1\n        x = self.df_embd[['pocket']].values.T\n        X = self.mp.transform(x[0], scale=False)\n        return X\n\n    def transform_custom(self, aap_df, scale = True, feature_range=(0, 1)):\n        \n        '''\n        aap_df: dataframe of animo acid propetries, each column is one type of property, total 20 rows for all 20 types of animo acids\n        aap_df example:\n        ==============\n        >>> from molmap.feature.sequence.aas.local_feature.aai import load_index\n        >>> aap_df = load_index.data.T        \n        '''\n\n        df_custom = pd.DataFrame(index = self.df_embd.index)\n        for k, v in aap_df.to_dict().items():\n            df_custom[k] = self.df_embd.residue_name_1aa.map(v)\n        self.df_custom = df_custom\n        if scale:\n            scaler = MinMaxScaler(feature_range = feature_range)\n            x = scaler.fit_transform(self.df_custom).T\n        else:\n            x = self.df_custom.values.T\n        X = self.mp.batch_transform(x, scale=False)       \n        \n        return X\n\n    \n    def transform_intrinsic(self, scale = True, feature_range=(0, 1)):\n        \n        df_intrinsic = pd.DataFrame(index = self.df_embd.index)\n        for k, v in IntrinsicAAPs.items():\n            df_intrinsic[k] = self.df_embd.residue_name_1aa.map(v)\n        self.df_intrinsic = df_intrinsic\n        if scale:\n            scaler = MinMaxScaler(feature_range = feature_range)\n            x = scaler.fit_transform(self.df_intrinsic).T\n        else:\n            x = self.df_intrinsic.values.T\n        X = self.mp.batch_transform(x, scale=False)        \n\n        return X\n\n\n\nclass PDB2Img:\n    \n    def __init__(self, pdb_file,  embd_grain = 'CA', embd_chain = None):\n        \n        '''\n        embd_grain: {'CA', 'CB', 'mean', 'all'}\n        pdb_file: pdf file path\n        embd_chain: pdb chain to do embedding\n        '''\n        self.embd_grain = embd_grain \n        self.pdb_file = pdb_file\n        self.pdb = PandasPdb().read_pdb(self.pdb_file)\n        self.embd_chain = embd_chain\n        \n        if embd_chain != None:\n            self.dfpdb = self.pdb.df['ATOM'][self.pdb.df['ATOM'].chain_id == embd_chain]\n        else:\n            self.dfpdb = self.pdb.df['ATOM']\n        if self.embd_grain == 'mean':\n            df_embd = self.dfpdb.groupby(['residue_number', 'residue_name']).apply(get_pdb_xyzb_mean).apply(pd.Series)\n            df_embd.columns = ['x_coord', 'y_coord', 'z_coord', 'b_factor']\n            df_embd = df_embd.reset_index()\n\n        if self.embd_grain == 'CB':\n            df_embd = self.dfpdb.groupby(['residue_number', 'residue_name']).apply(get_pdb_xyzb_cb).apply(pd.Series) \n            df_embd.columns = ['x_coord', 'y_coord', 'z_coord', 'b_factor']\n            df_embd = df_embd.reset_index()\n\n        if self.embd_grain == 'CA':\n            df_embd = self.dfpdb.groupby(['residue_number', 'residue_name']).apply(get_pdb_xyzb_ca).apply(pd.Series)  \n            df_embd.columns = ['x_coord', 'y_coord', 'z_coord', 'b_factor']\n            df_embd = df_embd.reset_index()\n  \n        if self.embd_grain == 'all':\n            df_embd = self.dfpdb[['residue_name', 'residue_number', 'x_coord', 'y_coord','z_coord', 'b_factor']]\n        \n        df_embd['residue_name_1aa'] = df_embd['residue_name'].map(PDB.protein_letters_3to1)    \n        df_embd.index = df_embd.index.astype(str) + '-' + df_embd['residue_name_1aa']\n        dfx = df_embd[['x_coord','y_coord','z_coord']]\n        self.dfx = dfx\n        self.df_embd = df_embd\n        self.dfx_dist = pairwise_distances(self.dfx)\n\n    def transform(self, fmap_shape = None, cmap='jet_r', vmin = 0, vmax=80, dpi=100):\n        '''\n        fig size: dpi*3\n        '''\n        fig, ax = plt.subplots()\n        ax.imshow(self.dfx_dist, cmap=cmap, vmin = vmin, vmax=vmax)\n        ax.axis('off')\n        with io.BytesIO() as buff:\n            fig.savefig(buff, bbox_inches='tight', pad_inches=0, dpi=dpi)\n            buff.seek(0)\n            im = PIL.Image.open(buff)\n            im = im.convert('RGB')    \n            if fmap_shape != None:\n                im = im.resize(fmap_shape)\n            x = np.array(im) / 255\n            \n        return fig, x\n    \nif __name__ == '__main__':\n    pm = PDB2Fmap(embd_grain='all', fmap_shape=None)\n    pm.fit(pdb_file='./1a1e/1a1e_protein.pdb', embd_chain='B')\n    X = pm.transform_xyz(scale=True, feature_range=(0.1,1))\n    X = pm.transofrm_bf(scale = True, feature_range=(0.2,1))\n    X = pm.transofrm_pkt('./1a1e/1a1e_pocket.pdb')\n    X = pm.transform_intrinsic()\n    sns.heatmap(X[2].reshape(*pm.fmap_shape), cmap = 'jet')\n\n", "meta": {"hexsha": "ff27024cba5194dd905e1d51890212f3019e14fe", "size": 14531, "ext": "py", "lang": "Python", "max_stars_repo_path": "molmap/pdb.py", "max_stars_repo_name": "riversdark/bidd-molmap", "max_stars_repo_head_hexsha": "7e3325433e2f29c189161859c63398574af6572b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 75, "max_stars_repo_stars_event_min_datetime": "2020-07-07T01:18:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T13:40:19.000Z", "max_issues_repo_path": "molmap/pdb.py", "max_issues_repo_name": "lfc350760007/bidd-molmap", "max_issues_repo_head_hexsha": "2a157dfdaec6f2c7952bafe3da95d78958a54f48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-09-28T14:11:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T04:33:25.000Z", "max_forks_repo_path": "molmap/pdb.py", "max_forks_repo_name": "lfc350760007/bidd-molmap", "max_forks_repo_head_hexsha": "2a157dfdaec6f2c7952bafe3da95d78958a54f48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2020-07-22T08:52:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T09:59:44.000Z", "avg_line_length": 39.272972973, "max_line_length": 134, "alphanum_fraction": 0.5539192072, "include": true, "reason": "import numpy", "num_tokens": 4923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.17023067221509314}}
{"text": "r'''Custom Printers for Sympy expressions\n\nThese classes are used by default by the QAlgebra printing systems as\nsub-printers for SymPy objects (e.g. for symbolic coefficients). They fix some\nissues with SymPy's builtin printers:\n\n* factors like $\\frac{1}{\\sqrt{2}}$ occur very commonly in quantum mechanics,\n  and it is standard notation to write them as such. SymPy insists on\n  rationalizing denominators, using $\\frac{\\sqrt{2}}{2}$ instead. Our custom\n  printers restore the canonical form. Note that internally, Sympy still uses\n  the rationalized structure; but in any case, Sympy makes no guarantees\n  between the algebraic structure of an expression and how it is printed.\n* Symbols (especially greek letters) are extremely common, and it's much more\n  readable if the string representation of an expression uses unicode for\n  these. SymPy supports unicode \"pretty-printing\"\n  (:func:`sympy.printing.pretty.pretty.pretty_print`) only in \"2D\", where\n  expressions are rendered as multiline unicode strings. While this is fine for\n  interactive display, it does not work so well for a simple ``str``. The\n  :class:`SympyUnicodePrinter` solves this by producing simple strings with\n  unicode symbols.\n* Some algebraic structures such as factorials, complex-conjugates and indexed\n  symbols have sub-optimal rendering in :class:`sympy.printing.str.StrPrinter`\n* QAlgebra contains some custom subclasses of SymPy objects (e.g.\n  :class:`.IdxSym`) that the default printers don't know how to deal with\n  (respectively, render incorrectly!)\n'''\nfrom collections import OrderedDict\n\nimport sympy\nfrom sympy import sqrt\nfrom sympy.core import Mul, Pow, Rational, S\nfrom sympy.core.mul import _keep_coeff\nfrom sympy.printing.latex import LatexPrinter\nfrom sympy.printing.precedence import PRECEDENCE, precedence\nfrom sympy.printing.pretty.pretty_symbology import pretty_symbol\nfrom sympy.printing.repr import ReprPrinter\nfrom sympy.printing.str import StrPrinter\n\nfrom ._unicode_mappings import _SUBSCRIPT_MAPPING, _SUPERSCRIPT_MAPPING\n\n\n__all__ = []\n__private__ = [\n    'SympyLatexPrinter',\n    'SympyStrPrinter',\n    'SympyUnicodePrinter',\n    'SympyReprPrinter',\n    'derationalize_denom',\n]\n\n\ndelattr(sympy.Indexed, '_sympystr')  # not sure how else to override printer\n\n\ndef derationalize_denom(expr):\n    \"\"\"Try to de-rationalize the denominator of the given expression.\n\n    The purpose is to allow to reconstruct e.g. ``1/sqrt(2)`` from\n    ``sqrt(2)/2``.\n\n    Specifically, this matches `expr` against the following pattern::\n\n        Mul(..., Rational(n, d), Pow(d, Rational(1, 2)), ...)\n\n    and returns a tuple ``(numerator, denom_sq, post_factor)``, where\n    ``numerator`` and ``denom_sq`` are ``n`` and ``d`` in the above pattern (of\n    type `int`), respectively, and ``post_factor`` is the product of the\n    remaining factors (``...`` in `expr`). The result will fulfill the\n    following identity::\n\n        (numerator / sqrt(denom_sq)) * post_factor == expr\n\n    If `expr` does not follow the appropriate pattern, a :exc:`ValueError` is\n    raised.\n    \"\"\"\n    r_pos = -1\n    p_pos = -1\n    numerator = S.Zero\n    denom_sq = S.One\n    post_factors = []\n    if isinstance(expr, Mul):\n        for pos, factor in enumerate(expr.args):\n            if isinstance(factor, Rational) and r_pos < 0:\n                r_pos = pos\n                numerator, denom_sq = factor.p, factor.q\n            elif isinstance(factor, Pow) and r_pos >= 0:\n                if factor == sqrt(denom_sq):\n                    p_pos = pos\n                else:\n                    post_factors.append(factor)\n            else:\n                post_factors.append(factor)\n        if r_pos >= 0 and p_pos >= 0:\n            return numerator, denom_sq, Mul(*post_factors)\n        else:\n            raise ValueError(\"Cannot derationalize\")\n    else:\n        raise ValueError(\"expr is not a Mul instance\")\n\n\nclass SympyStrPrinter(StrPrinter):\n    \"\"\"Variation of sympy ``StrPrinter`` that derationalizes denominators.\n\n    Additionally, it contains the following modifications:\n\n    * Support for :class:`.IdxSym`\n    * Rendering of :class:`sympy.tensor.indexed.Indexed` as subscripts\n    * Rendering of :class:`sympy.functions.combinatorial.factorials.factorial`\n      as ``!``\n    * Option `conjg_style` to configure how complex conjugates are rendered:\n      ``'func' renders it as ``conjugate(...)``, and ``'star'`` uses an\n      exponentiated asterisk\n    \"\"\"\n\n    printmethod = \"_sympystr\"\n    _default_settings = {\n        \"order\": None,\n        \"full_prec\": \"auto\",\n        \"sympy_integers\": False,\n        \"conjg_style\": 'func',\n    }\n\n    # _print_IdxSym(self, expr) is implemented in IdxSym._sympystr\n\n    def _print_Mul(self, expr):\n\n        prec = precedence(expr)\n\n        try:\n            numerator, denom_sq, post_factor = derationalize_denom(expr)\n            if post_factor == S.One:\n                return \"%s/sqrt(%s)\" % (numerator, denom_sq)\n            else:\n                if numerator == 1:\n                    return \"%s / sqrt(%s)\" % (\n                        self.parenthesize(post_factor, prec),\n                        denom_sq,\n                    )\n                else:\n                    return \"(%s/sqrt(%s)) %s\" % (\n                        numerator,\n                        denom_sq,\n                        self.parenthesize(post_factor, prec),\n                    )\n        except ValueError:\n            return super()._print_Mul(expr)\n\n    def _print_Indexed(self, expr):\n        indices = [self._print(i) for i in expr.indices]\n        sep = ','\n        if all([len(i.replace(\"'\", '')) == 1 for i in indices]):\n            sep = ''\n        return self._print(expr.base) + '_%s' % sep.join(indices)\n\n    def _print_factorial(self, expr, exp=None):\n        res = r\"%s!\" % self.parenthesize(expr.args[0], PRECEDENCE[\"Func\"])\n\n        if exp is not None:\n            return r\"%s^{%s}\" % (res, exp)\n        else:\n            return res\n\n    def _print_conjugate(self, expr, exp=None):\n        if self._settings['conjg_style'] == 'star':\n            res = self.parenthesize(expr.args[0], PRECEDENCE[\"Func\"]) + '^*'\n        elif self._settings['conjg_style'] in ['func', 'overbar']:\n            # recognizing \"overbar\" is just for compatibility with the other\n            # printers\n            res = r'conjugate(' + self._print(expr.args[0]) + r')'\n            pass\n        else:\n            raise ValueError(\n                \"The 'conjg_style' setting must be one of \" \"'star', 'func'\"\n            )\n        if exp is not None:\n            return r\"%s^%s\" % (res, exp)\n        else:\n            return res\n\n\nclass SympyLatexPrinter(LatexPrinter):\n    \"\"\"Variation of sympy ``LatexPrinter`` that derationalizes denominators.\n\n    Additionally, it contains the following modifications:\n\n    * Support for :class:`.IdxSym`\n    * A setting `conjg_style` that allows to specify how complex conjugate are\n      rendered: ``'overline'`` (the default) draws a line over the number,\n      'star' uses an exponentiated asterisk, and 'func' renders a a\n      ``conjugate`` function\n    \"\"\"\n\n    printmethod = \"_latex\"\n\n    _default_settings = LatexPrinter._default_settings.copy()\n    _default_settings.update(\n        {\n            \"order\": None,\n            \"mode\": \"plain\",\n            \"itex\": False,\n            \"fold_frac_powers\": False,\n            \"fold_func_brackets\": False,\n            \"fold_short_frac\": None,\n            \"long_frac_ratio\": 2,\n            \"mul_symbol\": None,\n            \"inv_trig_style\": \"abbreviated\",\n            \"mat_str\": None,\n            \"mat_delim\": \"[\",\n            \"symbol_names\": {},\n            \"conjg_style\": 'overline',\n        }\n    )\n\n    # _print_IdxSym(self, expr) is implemented in IdxSym._latex\n\n    def _print_Mul(self, expr):\n\n        prec = precedence(expr)\n\n        try:\n            numerator, denom_sq, post_factor = derationalize_denom(expr)\n            if post_factor == S.One:\n                return r'\\frac{%s}{\\sqrt{%s}}' % (numerator, denom_sq)\n            else:\n                if numerator == 1:\n                    return r'\\frac{%s}{\\sqrt{%s}}' % (\n                        self._print(post_factor),\n                        denom_sq,\n                    )\n                else:\n                    return r'\\frac{%s}{\\sqrt{%s}} %s' % (\n                        numerator,\n                        denom_sq,\n                        self.parenthesize(post_factor, prec),\n                    )\n        except ValueError:\n            return super()._print_Mul(expr)\n\n    def _print_conjugate(self, expr, exp=None):\n        if self._settings['conjg_style'] == 'overline':\n            tex = r\"\\overline{%s}\" % self._print(expr.args[0])\n        elif self._settings['conjg_style'] == 'star':\n            tex = r\"{%s}^*\" % self.parenthesize(\n                expr.args[0], PRECEDENCE[\"Func\"]\n            )\n        elif self._settings['conjg_style'] == 'func':\n            tex = (\n                r'\\operatorname{conjugate}\\left('\n                + self._print(expr.args[0])\n                + r'\\right)'\n            )\n        else:\n            raise ValueError(\n                \"The 'conjg_style' setting must be one of \"\n                \"'overline', 'star', 'func'\"\n            )\n\n        if exp is not None:\n            return r\"{%s}^{%s}\" % (tex, exp)\n        else:\n            return tex\n\n    def _print_Indexed(self, expr):\n        from qalgebra.printing.latexprinter import _TEX_SINGLE_LETTER_SYMBOLS\n\n        indices = [self._print(i) for i in expr.indices]\n        sep = ','\n        all_indices_are_single_letters = True\n        for i in indices:\n            i = i.replace(r'\\prime', '')\n            if (i not in _TEX_SINGLE_LETTER_SYMBOLS) and (len(i) > 1):\n                all_indices_are_single_letters = False\n        if all_indices_are_single_letters:\n            sep = ' '\n        return self._print(expr.base) + '_{%s}' % sep.join(indices)\n\n\nclass SympyUnicodePrinter(SympyStrPrinter):\n    \"\"\"Printer that represents SymPy expressions as (single-line) unicode\n    strings.\n\n    This is a mixture of SymPy's ``StrPrinter`` and\n    :class:`sympy.printing.pretty.pretty.PrettyPrinter` (minus the 2D\n    printing), with the same extensions as :class:`SympyStrPrinter`\n    \"\"\"\n\n    printmethod = \"_sympystr\"\n    _default_settings = {\n        \"order\": None,\n        \"full_prec\": \"auto\",\n        \"sympy_integers\": False,\n        \"superscript_asterisk_sym\": \"\\u00A0\\u20F0\",\n        \"conjg_style\": 'star',\n    }\n\n    def _print_Add(self, expr, order=None):\n        if self.order == 'none':\n            terms = list(expr.args)\n        else:\n            terms = self._as_ordered_terms(expr, order=order)\n\n        PREC = precedence(expr)\n        l = []\n        for term in terms:\n            t = str(self._print(term))\n            if t.startswith('-'):\n                sign = \"-\"\n                t = t[1:]\n            else:\n                sign = \"+\"\n            if precedence(term) < PREC:\n                l.extend([sign, \"(%s)\" % t])\n            else:\n                l.extend([sign, t])\n        sign = l.pop(0)\n        if sign == '+':\n            sign = \"\"\n        return sign + ' '.join(l)\n\n    def _print_ComplexInfinity(self, expr):\n        return '∞'\n\n    def _print_ImaginaryUnit(self, expr):\n        return 'ⅈ'\n\n    def _print_Infinity(self, expr):\n        return '∞'\n\n    def _print_Inverse(self, I):\n        return \"%s⁻¹\" % self.parenthesize(I.arg, PRECEDENCE[\"Pow\"])\n\n    def _print_Pi(self, expr):\n        return 'π'\n\n    def _print_Mul(self, expr):\n\n        prec = precedence(expr)\n\n        try:\n            numerator, denom_sq, post_factor = derationalize_denom(expr)\n            if post_factor == S.One:\n                return \"%s/√%s\" % (numerator, denom_sq)\n            else:\n                if numerator == 1:\n                    return \"%s / √%s\" % (\n                        self.parenthesize(post_factor, prec),\n                        denom_sq,\n                    )\n                else:\n                    return \"(%s/√%s) %s\" % (\n                        numerator,\n                        denom_sq,\n                        self.parenthesize(post_factor, prec),\n                    )\n        except ValueError:\n            pass  # Continue below\n\n        c, e = expr.as_coeff_Mul()\n        if c < 0:\n            expr = _keep_coeff(-c, e)\n            sign = \"-\"\n        else:\n            sign = \"\"\n\n        a = []  # items in the numerator\n        b = []  # items that are in the denominator (if any)\n\n        if self.order not in ('old', 'none'):\n            args = expr.as_ordered_factors()\n        else:\n            # use make_args in case expr was something like -x -> x\n            args = Mul.make_args(expr)\n\n        # Gather args for numerator/denominator\n        for item in args:\n            if (\n                item.is_commutative\n                and item.is_Pow\n                and item.exp.is_Rational\n                and item.exp.is_negative\n            ):\n                if item.exp != -1:\n                    b.append(Pow(item.base, -item.exp, evaluate=False))\n                else:\n                    b.append(Pow(item.base, -item.exp))\n            elif item.is_Rational and item is not S.Infinity:\n                if item.p != 1:\n                    a.append(Rational(item.p))\n                if item.q != 1:\n                    b.append(Rational(item.q))\n            else:\n                a.append(item)\n\n        a = a or [S.One]\n\n        a_str = [str(self.parenthesize(x, prec)) for x in a]\n        b_str = [str(self.parenthesize(x, prec)) for x in b]\n\n        if len(b) == 0:\n            return sign + ' '.join(a_str)\n        elif len(b) == 1:\n            return sign + ' '.join(a_str) + \"/\" + b_str[0]\n        else:\n            return sign + ' '.join(a_str) + \"/(%s)\" % ' '.join(b_str)\n\n    def _print_NegativeInfinity(self, expr):\n        return '-∞'\n\n    def _print_Pow(self, expr, rational=False):\n        PREC = precedence(expr)\n\n        if expr.exp is S.Half and not rational:\n            return \"√%s\" % self.parenthesize(expr.base, PREC)\n\n        if expr.is_commutative:\n            if -expr.exp is S.Half and not rational:\n                # Note: Don't test \"expr.exp == -S.Half\" here, because that\n                # will match -0.5, which we don't want.\n                return \"1/√%s\" % self.parenthesize(expr.base, PREC)\n            if expr.exp is -S.One:\n                # Similarly to the S.Half case, don't test with \"==\" here.\n                return '1/%s' % self.parenthesize(expr.base, PREC)\n\n        e = self.parenthesize(expr.exp, PREC)\n        if (\n            self.printmethod == '_sympyrepr'\n            and expr.exp.is_Rational\n            and expr.exp.q != 1\n        ):\n            # the parenthesized exp should be '(Rational(a, b))' so strip\n            # parens, but just check to be sure.\n            if e.startswith('(Rational'):\n                return '%s**%s' % (self.parenthesize(expr.base, PREC), e[1:-1])\n        try:\n            e_super = ''.join([_SUPERSCRIPT_MAPPING[l] for l in e])\n            return '%s%s' % (self.parenthesize(expr.base, PREC), e_super)\n        except KeyError:\n            return '%s**%s' % (self.parenthesize(expr.base, PREC), e)\n\n    def _print_MatPow(self, expr):\n        PREC = precedence(expr)\n        b = str(self.parenthesize(expr.base, PREC))\n        e = str(self.parenthesize(expr.exp, PREC))\n        try:\n            e_super = ''.join([_SUPERSCRIPT_MAPPING[l] for l in e])\n            return '%s%s' % (b, e_super)\n        except KeyError:\n            return '%s**%s' % (b, e)\n\n    def _print_Symbol(self, e):\n        return pretty_symbol(e.name)\n\n    _print_RandomSymbol = _print_Symbol\n\n    def _print_Identity(self, expr):\n        return \"𝟙\"\n\n    def _print_ZeroMatrix(self, expr):\n        return \"𝟘\"\n\n    def _print_Indexed(self, expr):\n        indices = [self._print(i) for i in expr.indices]\n        sep = ','\n        if all([len(i.replace(\"'\", '')) == 1 for i in indices]):\n            sep = ''\n        subscript = sep.join(indices)\n        try:\n            subscript = ''.join([_SUBSCRIPT_MAPPING[l] for l in subscript])\n            return self._print(expr.base) + subscript\n        except KeyError:\n            return self._print(expr.base) + '_%s' % subscript\n\n    def _print_conjugate(self, expr, exp=None):\n        if self._settings['conjg_style'] == 'star':\n            rendered_arg = self.parenthesize(expr.args[0], PRECEDENCE[\"Func\"])\n            if '_' in rendered_arg or '^' in rendered_arg:\n                if not rendered_arg.endswith(')'):\n                    rendered_arg = \"(%s)\" % rendered_arg\n            res = rendered_arg + self._settings['superscript_asterisk_sym']\n        elif self._settings['conjg_style'] in ['func', 'overbar']:\n            # recognizing \"overbar\" is just for compatibility with the other\n            # printers\n            res = r'conjugate(' + self._print(expr.args[0]) + r')'\n            pass\n        else:\n            raise ValueError(\n                \"The 'conjg_style' setting must be one of \" \"'star', 'func'\"\n            )\n        if exp is not None:\n            return r\"%s^%s\" % (res, exp)\n        else:\n            return res\n\n\nclass SympyReprPrinter(ReprPrinter):\n    \"\"\"Representation printer with support for\n    :class:`.IdxSym`\"\"\"\n\n    # _print_IdxSym(self, expr) is implemented in IdxSym._sympyrepr\n\n    def _print_Symbol(self, expr):\n        d = expr._assumptions.generator\n\n        d = OrderedDict([(key, d[key]) for key in sorted(d.keys())])\n        # the use of an OrderedDict is the only diffference between this and\n        # ReprPrinter._print_Symbol. It ensures that we always get the same\n        # repr\n\n        # print the dummy_index like it was an assumption\n        if expr.is_Dummy:\n            d['dummy_index'] = expr.dummy_index\n\n        if d == {}:\n            return \"%s(%s)\" % (expr.__class__.__name__, self._print(expr.name))\n        else:\n            attr = ['%s=%s' % (k, v) for k, v in d.items()]\n            return \"%s(%s, %s)\" % (\n                expr.__class__.__name__,\n                self._print(expr.name),\n                ', '.join(attr),\n            )\n\n        res = self._print_Symbol(expr)\n        if expr.primed > 0:\n            res = res[:-1] + \", primed=%d)\" % expr.primed\n        return res\n", "meta": {"hexsha": "b7fc6d2630b4c0e5dbbf9fca7af4256d21af3db8", "size": 18270, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/qalgebra/printing/sympy.py", "max_stars_repo_name": "anna-naden/qalgebra", "max_stars_repo_head_hexsha": "e7641ef77a2433caf2f587df27235800b894b631", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-17T12:18:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-25T11:17:27.000Z", "max_issues_repo_path": "src/qalgebra/printing/sympy.py", "max_issues_repo_name": "anna-naden/qalgebra", "max_issues_repo_head_hexsha": "e7641ef77a2433caf2f587df27235800b894b631", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-13T10:29:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-13T10:29:18.000Z", "max_forks_repo_path": "src/qalgebra/printing/sympy.py", "max_forks_repo_name": "anna-naden/qalgebra", "max_forks_repo_head_hexsha": "e7641ef77a2433caf2f587df27235800b894b631", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6679316888, "max_line_length": 79, "alphanum_fraction": 0.5544061303, "include": true, "reason": "import sympy,from sympy", "num_tokens": 4484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.17023066880417337}}
{"text": "#! /usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\n    ****************\n    Celestial Target\n    ****************\n\n    .. inheritance-diagram:: nenupy.astro.target.FixedTarget nenupy.astro.target.SolarSystemTarget\n        :parts: 3\n\n    .. autosummary::\n\n        ~FixedTarget\n        ~SolarSystemTarget\n\n\"\"\"\n\n\nfrom __future__ import annotations\n\n\n__author__ = \"Alan Loh\"\n__copyright__ = \"Copyright 2021, nenupy\"\n__credits__ = [\"Alan Loh\"]\n__maintainer__ = \"Alan\"\n__email__ = \"alan.loh@obspm.fr\"\n__status__ = \"Production\"\n__all__ = [\n    \"Target\",\n    \"FixedTarget\",\n    \"SolarSystemTarget\"\n]\n\n\nfrom abc import ABC, abstractmethod\nfrom typing import Callable\nimport numpy as np\nimport logging\nlog = logging.getLogger(__name__)\n\nimport astropy.units as u\nfrom astropy.time import Time, TimeDelta\nfrom astropy.coordinates import SkyCoord, EarthLocation, FK5, AltAz\n\nfrom nenupy import nenufar_position\nfrom nenupy.astro import common_sources\nfrom nenupy.astro.astro_tools import (\n    AstroObject,\n    hour_angle,\n    solar_system_source\n)\n\n\n# ============================================================= #\n# -------------------------- Target --------------------------- #\n# ============================================================= #\nclass Target(AstroObject, ABC):\n    \"\"\" Abstract class to handle target objects.\n\n        .. versionadded:: 2.0.0\n\n        .. rubric:: Attributes Summary\n\n        .. autosummary::\n\n            ~Target.coordinates\n            ~Target.time\n            ~Target.observer\n            ~Target.is_circumpolar\n            ~Target.culmination_azimuth\n\n        .. rubric:: Methods Summary\n\n        .. autosummary::\n\n            ~Target.meridian_transit\n            ~Target.next_meridian_transit\n            ~Target.previous_meridian_transit\n            ~Target.azimuth_transit\n            ~Target.rise_time\n            ~Target.next_rise_time\n            ~Target.previous_rise_time\n            ~Target.set_time\n            ~Target.next_set_time\n            ~Target.previous_set_time\n\n        .. rubric:: Attributes and Methods Documentation\n    \n    \"\"\"\n\n    def __init__(self,\n            coordinates: SkyCoord,\n            observer: EarthLocation = nenufar_position,\n            time: Time = Time.now()\n        ):\n        self.coordinates = coordinates\n        self.observer = observer\n        self.time = time\n\n\n    # --------------------------------------------------------- #\n    # --------------------- Getter/Setter --------------------- #\n    @property\n    def time(self) -> Time:\n        \"\"\" \"\"\"\n        return self._time\n    @time.setter\n    def time(self, t):\n        if t.isscalar:\n            t = t.reshape(1,)\n        self._time = t\n\n\n    @property\n    def is_circumpolar(self) -> bool:\n        r\"\"\" Whether the celestial object is circumpolar at the \n            observer's latitude.\n\n            .. math::\n                l + \\delta \\geq 90\\,{\\rm deg}\n            \n            where :math:`l` is the latitude (defined in\n            :attr:`~nenupy.astro.astro_tools.AstroObject.observer`),\n            :math:`\\delta` is the object's declination (defined in\n            :attr:`~nenupy.astro.astro_tools.AstroObject.coordinates`).\n        \"\"\"\n        return np.all((self.observer.lat + self.coordinates.dec) >= 90*u.deg)\n\n\n    @property\n    def culmination_azimuth(self) -> u.Quantity:\n        \"\"\" \"\"\"\n        if not self.is_circumpolar:\n            return 180*u.deg\n        else:\n            return 0*u.deg\n\n\n    # --------------------------------------------------------- #\n    # ------------------------ Methods ------------------------ #\n    def meridian_transit(self,\n            t_min: Time = Time.now(),\n            duration: TimeDelta = TimeDelta(86400, format='sec'),\n            precision: TimeDelta = TimeDelta(5, format='sec'),\n            fast_compute: bool = True\n        ) -> Time:\n        \"\"\" Computes the :class:`~nenupy.astro.target.Target` meridian transit time(s).\n            This method returns all the transit times found in the time\n            window ranging from ``t_min`` to ``t_min + duration``.\n\n            :param t_min:\n                Starting time of the temporal window within which\n                meridian transits are looked for.\n                Default is current time.\n            :type t_min:\n                :class:`~astropy.time.Time`\n            :param duration:\n                Width of the temporal window within which\n                meridian transits are looked for.\n                Default is ``1 day``.\n            :type duration:\n                :class:`~astropy.time.TimeDelta`\n            :param precision:\n                Temporal precision of the returned meridian transit values.\n                Default is ``5 sec``.\n            :type precision:\n                :class:`~astropy.time.TimeDelta`\n            :param fast_compute:\n                If set to ``True``, a fast approximation is used during\n                the computation of Local Sidereal Time.\n                Default is ``True``.\n            :type fast_compute:\n                `bool`\n\n            :returns:\n                Meridian transit times.\n                If no transit times are found (because the requested\n                time window doesn't contain any) an empty\n                :class:`~astropy.time.Time` object is returned.\n            :rtype:\n                :class:`~astropy.time.Time`\n\n            :Example:\n                >>> from nenupy.astro.target import FixedTarget\n                >>> from astropy.time import Time, TimeDelta\n                >>> cyg_a = FixedTarget.from_name(\"Cyg A\")\n                >>> cyg_a.meridian_transit(\n                        t_min=Time(\"2021-01-01\"),\n                        duration=TimeDelta(86400*2, format=\"sec\")\n                    )\n                <Time object: scale='utc' format='iso' value=['2021-01-01 13:05:47.868' '2021-01-02 13:01:51.882']>\n\n            .. seealso::\n                :ref:`ephemerides_sec`\n\n        \"\"\"\n        def find_ha_transit(times: Time):\n            \"\"\" \"\"\"\n            fk5 = self._get_source_coordinates(\n                time=times\n            ).transform_to(FK5(equinox=times))\n            ha = hour_angle(\n                radec=fk5,\n                time=times,\n                observer=self.observer,\n                fast_compute=fast_compute\n            )\n            return np.where(\n                (np.roll(ha, shift=-1, axis=1) - ha)[:, :-1] < 0\n            )\n        return self._find_crossing_times(\n            finding_function=find_ha_transit,\n            t_min=t_min,\n            duration=duration,\n            precision=precision\n        )\n\n\n    def azimuth_transit(self,\n            azimuth: u.Quantity = 180*u.deg,\n            t_min: Time = Time.now(),\n            duration: TimeDelta = TimeDelta(86400, format='sec'),\n            precision: TimeDelta = TimeDelta(5, format='sec'),\n        ) -> Time:\n        \"\"\" Computes the :class:`~nenupy.astro.target.Target` transit time(s) at a given ``azimuth`` value.\n            This method returns all the transit times found in the time\n            window ranging from ``t_min`` to ``t_min + duration``.\n\n            :param azimuth:\n                Azimuth at which the transit is computed.\n                Default is ``180 deg`` (i.e. South).\n            :type azimuth:\n                :class:`~astropy.units.Quantity`\n            :param t_min:\n                Starting time of the temporal window within which\n                azimuth transits are looked for.\n                Default is current time.\n            :type t_min:\n                :class:`~astropy.time.Time`\n            :param duration:\n                Width of the temporal window within which\n                azimuth transits are looked for.\n                Default is ``1 day``.\n            :type duration:\n                :class:`~astropy.time.TimeDelta`\n            :param precision:\n                Temporal precision of the returned azimuth transit values.\n                Default is ``5 sec``.\n            :type precision:\n                :class:`~astropy.time.TimeDelta`\n\n            :returns:\n                Azimuth transit times.\n                If no transit times are found (either because the requested\n                time window doesn't contain any or because the source apparent\n                sky position does not cross the desired ``azimuth``) an empty\n                :class:`~astropy.time.Time` object is returned.\n            :rtype:\n                :class:`~astropy.time.Time`\n\n            :Example:\n                >>> from nenupy.astro.target import FixedTarget\n                >>> from astropy.time import Time, TimeDelta\n                >>> import astropy.units as u\n                >>> cyg_a = FixedTarget.from_name(\"Cyg A\")\n                >>> cyg_a.azimuth_transit(\n                        azimuth=100*u.deg,\n                        t_min=Time(\"2021-01-01\"),\n                        duration=TimeDelta(86400*2, format=\"sec\")\n                    )\n                <Time object: scale='utc' format='iso' value=['2021-01-01 11:22:12.463' '2021-01-02 11:18:16.477']>\n\n            .. seealso::\n                :ref:`ephemerides_sec`\n\n        \"\"\"\n        def find_az_transit(times: Time):\n            \"\"\" \"\"\"\n            # altaz_coordinates = radec_to_altaz(\n            #     radec=self._get_source_coordinates(time=times),\n            #     time=times,\n            #     observer=self.observer,\n            #     fast_compute=fast_compute\n            # ).reshape(times.shape)\n            altaz_coordinates = self._get_source_coordinates(time=times).transform_to(\n                AltAz(\n                    obstime=times,\n                    location=self.observer\n                )\n            )\n            azimuths = altaz_coordinates.az.rad\n            az = azimuth.to(u.rad).value\n            if self.is_circumpolar:\n                complexAzStarts = np.angle(\n                    np.cos(azimuths[:, :-1]) + 1j*np.sin(azimuths[:, :-1])\n                )\n                complexAzStops = np.angle(\n                    np.cos(azimuths[:, 1:]) + 1j*np.sin(azimuths[:, 1:])\n                )\n                mask = (complexAzStarts <= az) &\\\n                    (complexAzStops >= az)\n                mask |= (complexAzStarts >= az) &\\\n                    (complexAzStops <= az)\n            else:\n                mask = (azimuths[:, :-1] <= az) &\\\n                    (azimuths[:, 1:] >= az)\n            return np.where(mask)\n        return self._find_crossing_times(\n            finding_function=find_az_transit,\n            t_min=t_min,\n            duration=duration,\n            precision=precision\n        )\n\n\n    def next_meridian_transit(self,\n            time: Time = Time.now(),\n            precision: TimeDelta = TimeDelta(5, format='sec'),\n            fast_compute: bool = True\n        ) -> Time:\n        \"\"\" Computes the :class:`~nenupy.astro.target.Target` next meridian transit time.\n            This method returns the next transit time found after ``time``.\n\n            :param time:\n                Relative time used to searching for the next meridian transit.\n            :type time:\n                :class:`~astropy.time.Time`\n            :param precision:\n                Temporal precision of the returned meridian transit value.\n                Default is ``5 sec``.\n            :type precision:\n                :class:`~astropy.time.TimeDelta`\n            :param fast_compute:\n                If set to ``True``, a fast approximation is used during\n                the computation of Local Sidereal Time.\n                Default is ``True``.\n            :type fast_compute:\n                `bool`\n\n            :returns:\n                Next meridian transit time.\n            :rtype:\n                :class:`~astropy.time.Time`\n\n            :Example:\n                >>> from nenupy.astro.target import FixedTarget\n                >>> from astropy.time import Time\n                >>> cyg_a = FixedTarget.from_name(\"Cyg A\")\n                >>> cyg_a.next_meridian_transit(\n                        time=Time(\"2021-01-01 12:00:00\")\n                    )\n                <Time object: scale='utc' format='iso' value=2021-01-01 13:05:47.868>\n\n            .. seealso::\n                :ref:`ephemerides_sec`, :meth:`~nenupy.astro.target.Target.meridian_transit`\n\n        \"\"\"\n        return self.meridian_transit(\n            t_min=time,\n            duration=TimeDelta(48*3600, format='sec'),\n            precision=precision,\n            fast_compute=fast_compute\n        )[0]\n\n\n    def previous_meridian_transit(self,\n            time: Time = Time.now(),\n            precision: TimeDelta = TimeDelta(5, format='sec'),\n            fast_compute: bool = True\n        ) -> Time:\n        \"\"\" Computes the :class:`~nenupy.astro.target.Target` previous meridian transit time.\n            This method returns the previous transit time found before ``time``.\n\n            :param time:\n                Relative time used to searching for the previous meridian transit.\n                Default is current time.\n            :type time:\n                :class:`~astropy.time.Time`\n            :param precision:\n                Temporal precision of the returned meridian transit value.\n                Default is ``5 sec``.\n            :type precision:\n                :class:`~astropy.time.TimeDelta`\n            :param fast_compute:\n                If set to ``True``, a fast approximation is used during\n                the computation of Local Sidereal Time.\n                Default is ``True``.\n            :type fast_compute:\n                `bool`\n\n            :returns:\n                Previous meridian transit time.\n            :rtype:\n                :class:`~astropy.time.Time`\n\n            :Example:\n                >>> from nenupy.astro.target import FixedTarget\n                >>> from astropy.time import Time\n                >>> cyg_a = FixedTarget.from_name(\"Cyg A\")\n                >>> cyg_a.previous_meridian_transit(\n                        time=Time(\"2021-01-01 12:00:00\")\n                    )\n                Time object: scale='utc' format='iso' value=2020-12-31 13:09:43.855>\n\n            .. seealso::\n                :ref:`ephemerides_sec`, :meth:`~nenupy.astro.target.Target.meridian_transit`\n\n        \"\"\"\n        return self.meridian_transit(\n            t_min=time - TimeDelta(48*3600, format='sec'),\n            duration=TimeDelta(48*3600, format='sec'),\n            precision=precision,\n            fast_compute=fast_compute\n        )[-1]\n\n\n    def rise_time(self,\n        t_min: Time = Time.now(),\n        elevation: u.Quantity = 0*u.deg,\n        duration: TimeDelta = TimeDelta(86400, format='sec'),\n        precision: TimeDelta = TimeDelta(5, format='sec'),\n        ):\n        \"\"\" Computes the :class:`~nenupy.astro.target.Target` rise time(s) above ``elevation``.\n            This method returns all the rise times found in the time\n            window ranging from ``t_min`` to ``t_min + duration``.\n\n            :param t_min:\n                Starting time of the temporal window within which\n                rise times are looked for.\n                Default is current time.\n            :type t_min:\n                :class:`~astropy.time.Time`\n            :param elevation:\n                Elevation above which the rise time is computed.\n                Default is ``0 deg``.\n            :type elevation:\n                :class:`~astropy.units.Quantity`\n            :param duration:\n                Width of the temporal window within which\n                rise times are looked for.\n                Default is ``1 day``.\n            :type duration:\n                :class:`~astropy.time.TimeDelta`\n            :param precision:\n                Temporal precision of the returned meridian transit values.\n                Default is ``5 sec``.\n            :type precision:\n                :class:`~astropy.time.TimeDelta`\n\n            :returns:\n                Rise times above a given elevation.\n                If no rise times are found (because the requested\n                time window doesn't contain any) an empty\n                :class:`~astropy.time.Time` object is returned.\n            :rtype:\n                :class:`~astropy.time.Time`\n\n            :Example:\n                >>> from nenupy.astro.target import FixedTarget\n                >>> from astropy.time import Time, TimeDelta\n                >>> import astropy.units as u\n                >>> cyg_a = FixedTarget.from_name(\"Cyg A\")\n                >>> cyg_a.rise_time(\n                        t_min=Time(\"2021-01-01\"),\n                        elevation=0*u.deg,\n                        duration=TimeDelta(86400*2, format=\"sec\")\n                    )\n                <Time object: scale='utc' format='iso' value=['2021-01-01 02:28:51.926' '2021-01-02 02:24:56.599']>\n\n            .. seealso::\n                :ref:`ephemerides_sec`\n\n        \"\"\"\n\n        def _find_elevation_rise_time(times):\n            \"\"\" \"\"\"\n            altaz_coordinates = self._get_source_coordinates(time=times).transform_to(\n                AltAz(\n                    obstime=times,\n                    location=self.observer\n                )\n            )\n            elevations = altaz_coordinates.alt\n            return np.where(\n                (elevations[:, :-1] <= elevation) & (elevations[:, 1:] >= elevation)\n            )\n        return self._find_crossing_times(\n            finding_function=_find_elevation_rise_time,\n            t_min=t_min,\n            duration=duration,\n            precision=precision\n        )\n\n\n    def next_rise_time(self,\n            time: Time = Time.now(),\n            elevation: u.Quantity = 0*u.deg,\n            precision: TimeDelta = TimeDelta(5, format='sec')\n        ) -> Time:\n        \"\"\" Computes the :class:`~nenupy.astro.target.Target` next rise time above ``elevation``.\n            This method returns the next rise time found after ``time``.\n\n            :param time:\n                Relative time used to searching for the next rise time.\n                Default is current time.\n            :type time:\n                :class:`~astropy.time.Time`\n            :param elevation:\n                Elevation above which the rise time is computed.\n                Default is ``0 deg``.\n            :type elevation:\n                :class:`~astropy.units.Quantity`\n            :param precision:\n                Temporal precision of the returned rise time value.\n                Default is ``5 sec``.\n            :type precision:\n                :class:`~astropy.time.TimeDelta`\n\n            :returns:\n                Next rise time.\n                If no rise time is found (because the source does not\n                cross the elevation) an empty\n                :class:`~astropy.time.Time` object is returned.\n            :rtype:\n                :class:`~astropy.time.Time`\n\n            :Example:\n                >>> from nenupy.astro.target import FixedTarget\n                >>> from astropy.time import Time, TimeDelta\n                >>> import astropy.units as u\n                >>> cyg_a = FixedTarget.from_name(\"Cyg A\")\n                >>> cyg_a.next_rise_time(\n                        time=Time(\"2021-01-01\"),\n                        elevation=40*u.deg,\n                    )\n                <Time object: scale='utc' format='iso' value=2021-01-01 08:20:16.447>\n\n            .. seealso::\n                :ref:`ephemerides_sec`, :meth:`~nenupy.astro.target.Target.rise_time`\n\n        \"\"\"\n        try:\n            return self.rise_time(\n                t_min=time,\n                elevation=elevation,\n                duration=TimeDelta(48*3600, format='sec'),\n                precision=precision\n            )[0]\n        except IndexError:\n            return Time([], format=\"jd\")\n\n\n    def previous_rise_time(self,\n            time: Time = Time.now(),\n            elevation: u.Quantity = 0*u.deg,\n            precision: TimeDelta = TimeDelta(5, format='sec')\n        ) -> Time:\n        \"\"\" Computes the :class:`~nenupy.astro.target.Target` previous rise time above ``elevation``.\n            This method returns the previous rise time found after ``time``.\n\n            :param time:\n                Relative time used to searching for the previous rise time.\n                Default is current time.\n            :type time:\n                :class:`~astropy.time.Time`\n            :param elevation:\n                Elevation above which the rise time is computed.\n                Default is ``0 deg``.\n            :type elevation:\n                :class:`~astropy.units.Quantity`\n            :param precision:\n                Temporal precision of the returned rise time value.\n                Default is ``5 sec``.\n            :type precision:\n                :class:`~astropy.time.TimeDelta`\n\n            :returns:\n                Previous rise time.\n                If no rise time is found (because the source does not\n                cross the elevation) an empty\n                :class:`~astropy.time.Time` object is returned.\n            :rtype:\n                :class:`~astropy.time.Time`\n\n            :Example:\n                >>> from nenupy.astro.target import FixedTarget\n                >>> from astropy.time import Time, TimeDelta\n                >>> import astropy.units as u\n                >>> cyg_a = FixedTarget.from_name(\"Cyg A\")\n                >>> cyg_a.previous_rise_time(\n                        time=Time(\"2021-01-01\"),\n                        elevation=40*u.deg,\n                    )\n                <Time object: scale='utc' format='iso' value=2020-12-31 08:24:12.434>\n\n            .. seealso::\n                :ref:`ephemerides_sec`, :meth:`~nenupy.astro.target.Target.rise_time`\n\n        \"\"\"\n        try:\n            return self.rise_time(\n                t_min=time - TimeDelta(48*3600, format='sec'),\n                elevation=elevation,\n                duration=TimeDelta(48*3600, format='sec'),\n                precision=precision\n            )[-1]\n        except IndexError:\n            return Time([], format=\"jd\")\n\n\n    def set_time(self,\n        t_min: Time = Time.now(),\n        elevation: u.Quantity = 0*u.deg,\n        duration: TimeDelta = TimeDelta(86400, format='sec'),\n        precision: TimeDelta = TimeDelta(5, format='sec'),\n        ):\n        \"\"\" Computes the :class:`~nenupy.astro.target.Target` set time(s) below ``elevation``.\n            This method returns all the set times found in the time\n            window ranging from ``t_min`` to ``t_min + duration``.\n\n            :param t_min:\n                Starting time of the temporal window within which\n                set times are looked for.\n                Default is current time.\n            :type t_min:\n                :class:`~astropy.time.Time`\n            :param elevation:\n                Elevation below which the set time is computed.\n                Default is ``0 deg``.\n            :type elevation:\n                :class:`~astropy.units.Quantity`\n            :param duration:\n                Width of the temporal window within which\n                set times are looked for.\n                Default is ``1 day``.\n            :type duration:\n                :class:`~astropy.time.TimeDelta`\n            :param precision:\n                Temporal precision of the returned meridian transit values.\n                Default is ``5 sec``.\n            :type precision:\n                :class:`~astropy.time.TimeDelta`\n\n            :returns:\n                Set times below a given elevation.\n                If no set times are found (because the requested\n                time window doesn't contain any) an empty\n                :class:`~astropy.time.Time` object is returned.\n            :rtype:\n                :class:`~astropy.time.Time`\n\n            :Example:\n                >>> from nenupy.astro.target import FixedTarget\n                >>> from astropy.time import Time, TimeDelta\n                >>> import astropy.units as u\n                >>> cyg_a = FixedTarget.from_name(\"Cyg A\")\n                >>> cyg_a.set_time(\n                        t_min=Time(\"2021-01-01\"),\n                        elevation=0*u.deg,\n                        duration=TimeDelta(86400*2, format=\"sec\")\n                    )\n                <Time object: scale='utc' format='iso' value=['2021-01-01 23:42:41.174' '2021-01-02 23:38:45.188']>\n\n            .. seealso::\n                :ref:`ephemerides_sec`\n\n        \"\"\"\n\n        def _find_elevation_set_time(times):\n            \"\"\" \"\"\"\n            altaz_coordinates = self._get_source_coordinates(time=times).transform_to(\n                AltAz(\n                    obstime=times,\n                    location=self.observer\n                )\n            )\n            elevations = altaz_coordinates.alt\n            return np.where(\n                (elevations[:, :-1] >= elevation) & (elevations[:, 1:] <= elevation)\n            )\n        return self._find_crossing_times(\n            finding_function=_find_elevation_set_time,\n            t_min=t_min,\n            duration=duration,\n            precision=precision\n        )\n\n\n    def next_set_time(self,\n            time: Time = Time.now(),\n            elevation: u.Quantity = 0*u.deg,\n            precision: TimeDelta = TimeDelta(5, format='sec')\n        ) -> Time:\n        \"\"\" Computes the :class:`~nenupy.astro.target.Target` next set time below ``elevation``.\n            This method returns the next set time found after ``time``.\n\n            :param time:\n                Relative time used to searching for the next set time.\n                Default is current time.\n            :type time:\n                :class:`~astropy.time.Time`\n            :param elevation:\n                Elevation below which the set time is computed.\n                Default is ``0 deg``.\n            :type elevation:\n                :class:`~astropy.units.Quantity`\n            :param precision:\n                Temporal precision of the returned set time value.\n                Default is ``5 sec``.\n            :type precision:\n                :class:`~astropy.time.TimeDelta`\n\n            :returns:\n                Next set time.\n                If no set time is found (because the source does not\n                cross the elevation) an empty\n                :class:`~astropy.time.Time` object is returned.\n            :rtype:\n                :class:`~astropy.time.Time`\n\n            :Example:\n                >>> from nenupy.astro.target import FixedTarget\n                >>> from astropy.time import Time, TimeDelta\n                >>> import astropy.units as u\n                >>> cyg_a = FixedTarget.from_name(\"Cyg A\")\n                >>> cyg_a.next_set_time(\n                        time=Time(\"2021-01-01\"),\n                        elevation=40*u.deg,\n                    )\n                <Time object: scale='utc' format='iso' value=2021-01-01 17:51:17.312>\n\n            .. seealso::\n                :ref:`ephemerides_sec`, :meth:`~nenupy.astro.target.Target.set_time`\n\n        \"\"\"\n        try:\n            return self.set_time(\n                t_min=time,\n                elevation=elevation,\n                duration=TimeDelta(48*3600, format='sec'),\n                precision=precision\n            )[0]\n        except IndexError:\n            return Time([], format=\"jd\")\n\n\n    def previous_set_time(self,\n            time: Time = Time.now(),\n            elevation: u.Quantity = 0*u.deg,\n            precision: TimeDelta = TimeDelta(5, format='sec')\n        ) -> Time:\n        \"\"\" Computes the :class:`~nenupy.astro.target.Target` previous set time below ``elevation``.\n            This method returns the next set time found before ``time``.\n\n            :param time:\n                Relative time used to searching for the previous set time.\n                Default is current time.\n            :type time:\n                :class:`~astropy.time.Time`\n            :param elevation:\n                Elevation below which the set time is computed.\n                Default is ``0 deg``.\n            :type elevation:\n                :class:`~astropy.units.Quantity`\n            :param precision:\n                Temporal precision of the returned set time value.\n                Default is ``5 sec``.\n            :type precision:\n                :class:`~astropy.time.TimeDelta`\n\n            :returns:\n                Previous set time.\n                If no set time is found (because the source does not\n                cross the elevation) an empty\n                :class:`~astropy.time.Time` object is returned.\n            :rtype:\n                :class:`~astropy.time.Time`\n\n            :Example:\n                >>> from nenupy.astro.target import FixedTarget\n                >>> from astropy.time import Time, TimeDelta\n                >>> import astropy.units as u\n                >>> cyg_a = FixedTarget.from_name(\"Cyg A\")\n                >>> cyg_a.previous_set_time(\n                        time=Time(\"2021-01-01\"),\n                        elevation=40*u.deg,\n                    )\n                <Time object: scale='utc' format='iso' value=2020-12-31 17:55:12.639>\n\n            .. seealso::\n                :ref:`ephemerides_sec`, :meth:`~nenupy.astro.target.Target.set_time`\n\n        \"\"\"\n        try:\n            return self.set_time(\n                t_min=time - TimeDelta(48*3600, format='sec'),\n                elevation=elevation,\n                duration=TimeDelta(48*3600, format='sec'),\n                precision=precision\n            )[-1]\n        except IndexError:\n            return Time([], format=\"jd\")\n\n\n\n    # --------------------------------------------------------- #\n    # ----------------------- Internal ------------------------ #\n    @abstractmethod\n    def _get_source_coordinates(self, time: Time) -> SkyCoord:\n        \"\"\" Abstract method that must be replaced by subclasses. \"\"\"\n        pass\n\n\n    @staticmethod\n    def _find_crossing_times(\n            finding_function: Callable,\n            t_min: Time,\n            duration: TimeDelta,\n            precision: TimeDelta\n        ) -> np.ndarray:\n        \"\"\" \"\"\"\n        # Set t_min to a higher dimension in preparation for multiple matches\n        t_min = t_min.reshape((1,))\n\n        # At each iteration, dt will be reduced by down_factor\n        down_factor = 5\n        dt = duration/down_factor\n\n        # If duration is too big, intial dt is quite big as well\n        # therefore, we set the max dt to 6h\n        max_dt = TimeDelta(6*3600, format=\"sec\")\n        if dt > max_dt:\n            down_factor = int(np.ceil(duration/max_dt))\n            dt = duration/down_factor\n\n        # Loop until the precision is reached\n        while dt*down_factor > precision:\n\n            # Prepare the time array upon which the coordinates are computed\n            n_steps = np.ceil(duration/dt)\n            times = t_min[:, None] + np.arange(n_steps + 1) * dt\n\n            # Find the indices depending on the function to apply\n            transit_indices = finding_function(times)\n\n            # Update t_min at the spots where the transit(s) have been found\n            t_min = times[transit_indices]\n\n            if t_min.size == 0:\n                # Nothing has been found\n                return Time([], format='jd')\n            elif t_min.isscalar:\n                t_min = t_min.reshape((1,))\n\n            # Next loop will occur on the last time step only\n            duration = dt\n            dt /= down_factor\n\n        return times[transit_indices] + dt/2.\n# ============================================================= #\n# ============================================================= #\n\n\n# ============================================================= #\n# ------------------------ FixedTarget ------------------------ #\n# ============================================================= #\nclass FixedTarget(Target):\n    \"\"\" Class to handle astronomical targets outside the Solar System.\n\n        .. versionadded:: 2.0.0\n\n        :param coordinates:\n        :type coordinates:\n            :class:`~astropy.coordinates.SkyCoord`\n        :param observer:\n        :type observer:\n            :class:`~astropy.coordinates.EarthLocation`\n        :param time:\n        :type time:\n            :class:`~astropy.time.Time`\n\n        .. rubric:: Attributes Summary\n\n        .. autosummary::\n\n            ~Target.coordinates\n            ~Target.time\n            ~Target.observer\n            ~Target.is_circumpolar\n            ~Target.culmination_azimuth\n\n        .. rubric:: Methods Summary\n\n        .. autosummary::\n\n            ~FixedTarget.from_name\n            ~Target.meridian_transit\n            ~Target.next_meridian_transit\n            ~Target.previous_meridian_transit\n            ~Target.azimuth_transit\n            ~Target.rise_time\n            ~Target.next_rise_time\n            ~Target.previous_rise_time\n            ~Target.set_time\n            ~Target.next_set_time\n            ~Target.previous_set_time\n\n        .. rubric:: Attributes and Methods Documentation\n        \n    \"\"\"\n\n    def __init__(self,\n            coordinates: SkyCoord,\n            time: Time = Time.now(),\n            observer: EarthLocation = nenufar_position\n        ):\n        super().__init__(\n            coordinates=coordinates,\n            observer=observer,\n            time=time\n        )\n\n\n    # --------------------------------------------------------- #\n    # --------------------- Getter/Setter --------------------- #\n    @property\n    def horizontal_coordinates(self):\n        \"\"\" \"\"\"\n        return super().horizontal_coordinates[:, 0]\n\n\n    # --------------------------------------------------------- #\n    # ------------------------ Methods ------------------------ #\n    @classmethod\n    def from_name(cls,\n            name: str,\n            time: Time = Time.now(),\n            observer: EarthLocation = nenufar_position\n        ) -> FixedTarget:\n        \"\"\" Instantiates a :class:`~nenupy.astro.target.FixedTarget`\n            object from a name that could be resolved by `Simbad <http://simbad.u-strasbg.fr/simbad/>`_.\n\n            :param name:\n                Source name.\n            :type name:\n                `str`\n            :param time:\n                Time at which the source is looked at.\n                Default is current time.\n            :type time:\n                :class:`~astropy.time.Time`\n            :param observer:\n                Earth location from where the source is observed.\n                Default is NenuFAR's location.\n            :type observer:\n                :class:`~astropy.coordinates.EarthLocation`\n\n            :returns:\n                :class:`~nenupy.astro.target.FixedTarget` instance.\n            :rtype:\n                :class:`~nenupy.astro.target.FixedTarget`\n            \n            :Example:\n                >>> from nenupy.astro.target import FixedTarget\n                >>> cyg_a = FixedTarget.from_name(\"Cyg A\")\n\n        \"\"\"\n\n        if name.lower() in common_sources.keys():\n            src = common_sources[name.lower()]\n            source = SkyCoord(src[\"ra\"], src[\"dec\"], unit=\"deg\")\n        else:\n            # Retrieve the Simbad coordinates\n            source = SkyCoord.from_name(name)\n\n        return cls(\n            coordinates=source,\n            observer=observer,\n            time=time\n        )\n\n\n    # --------------------------------------------------------- #\n    # ----------------------- Internal ------------------------ #\n    def _get_source_coordinates(self, time: Time):\n        \"\"\" \"\"\"\n        return SkyCoord(\n            ra=np.repeat(self.coordinates.ra.deg, time.size).reshape(time.shape),\n            dec=np.repeat(self.coordinates.dec.deg, time.size).reshape(time.shape),\n            unit=\"deg\",\n            frame=self.coordinates.frame\n        )\n        # return self.coordinates\n# ============================================================= #\n# ============================================================= #\n\n\n# ============================================================= #\n# --------------------- SolarSystemTarget --------------------- #\n# ============================================================= #\nclass SolarSystemTarget(Target):\n    \"\"\" Class to handle Solar System targets.\n\n        .. versionadded:: 2.0.0\n\n        .. rubric:: Attributes Summary\n\n        .. autosummary::\n\n            ~Target.coordinates\n            ~Target.time\n            ~Target.observer\n            ~Target.is_circumpolar\n            ~Target.culmination_azimuth\n\n        .. rubric:: Methods Summary\n\n        .. autosummary::\n\n            ~SolarSystemTarget.from_name\n            ~Target.meridian_transit\n            ~Target.next_meridian_transit\n            ~Target.previous_meridian_transit\n            ~Target.azimuth_transit\n            ~Target.rise_time\n            ~Target.next_rise_time\n            ~Target.previous_rise_time\n            ~Target.set_time\n            ~Target.next_set_time\n            ~Target.previous_set_time\n\n        .. rubric:: Attributes and Methods Documentation\n        \n    \"\"\"\n\n    def __init__(self,\n            name: str,\n            coordinates: SkyCoord,\n            time: Time = Time.now(),\n            observer: EarthLocation = nenufar_position\n        ):\n        super().__init__(\n            coordinates=coordinates,\n            observer=observer,\n            time=time\n        )\n        self.name = name\n\n\n    # --------------------------------------------------------- #\n    # --------------------- Getter/Setter --------------------- #\n    @property\n    def horizontal_coordinates(self):\n        \"\"\" \"\"\"\n        return super().horizontal_coordinates[np.identity(self.time.size, dtype=bool)]\n\n\n    # --------------------------------------------------------- #\n    # ------------------------ Methods ------------------------ #\n    @classmethod\n    def from_name(cls,\n            name: str,\n            time: Time = Time.now(),\n            observer: EarthLocation = nenufar_position\n        ) -> SolarSystemTarget:\n        \"\"\" \"\"\"\n\n        # Get the ICRS instance of the Solar System object\n        source = solar_system_source(\n            name=name,\n            time=time,\n            observer=observer\n        )\n\n        return cls(\n            name=name,\n            coordinates=source,\n            observer=observer,\n            time=time\n        )\n\n\n    # --------------------------------------------------------- #\n    # ----------------------- Internal ------------------------ #\n    def _get_source_coordinates(self, time: Time):\n        \"\"\" \"\"\"\n        return solar_system_source(\n            name=self.name,\n            time=time,\n            observer=self.observer\n        )\n# ============================================================= #\n# ============================================================= #\n", "meta": {"hexsha": "8e347b7276f9ead545a02042fce0ae88f9f58c72", "size": 38663, "ext": "py", "lang": "Python", "max_stars_repo_path": "nenupy/astro/target.py", "max_stars_repo_name": "coutouly/nenupy", "max_stars_repo_head_hexsha": "76cf9f6a6a93e9eed16f8450e3cfe385440a212e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nenupy/astro/target.py", "max_issues_repo_name": "coutouly/nenupy", "max_issues_repo_head_hexsha": "76cf9f6a6a93e9eed16f8450e3cfe385440a212e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nenupy/astro/target.py", "max_forks_repo_name": "coutouly/nenupy", "max_forks_repo_head_hexsha": "76cf9f6a6a93e9eed16f8450e3cfe385440a212e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.276459854, "max_line_length": 115, "alphanum_fraction": 0.4935985309, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 7887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.17023066880417337}}
{"text": "# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# python3\n\"\"\"A fork of PlaNet model.\n\nArchive paper: https://arxiv.org/abs/1811.04551\nOSS code repo: https://github.com/google-research/planet\n\"\"\"\n# pylint:disable=missing-docstring\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nimport gin\nimport gym\nimport numpy as np\nimport tensorflow.compat.v1 as tf\nimport tensorflow.compat.v2.summary as tfs\nfrom tensorflow_probability import distributions as tfd\nfrom world_models.imported_models import reward_models\nfrom world_models.utils import npz\nfrom world_models.utils import visualization\n\nfrom tensorflow.python.distribute import values\n\ngin.external_configurable(tf.distribute.MirroredStrategy,\n                          'tf.distribute.MirroredStrategy')\n\n\ndef static_scan(fn, inputs, start, reverse=False):\n  # pylint: disable=expression-not-assigned\n  # pylint: disable=cell-var-from-loop\n  \"\"\"drop-in replacement for tf.scan.\n\n  tf.scan has some issues with multiple devices.\n  \"\"\"\n  last = start\n  outputs = [[] for _ in tf.nest.flatten(start)]\n  indices = range(tf.nest.flatten(inputs)[0].shape[0])\n  if reverse:\n    indices = reversed(indices)\n  for index in indices:\n    inp = tf.nest.map_structure(lambda x: x[index], inputs)\n    last = fn(last, inp)\n    [o.append(l) for o, l in zip(outputs, tf.nest.flatten(last))]\n  if reverse:\n    outputs = [list(reversed(x)) for x in outputs]\n  outputs = [tf.stack(x, 0) for x in outputs]\n  return tf.nest.pack_sequence_as(start, outputs)\n\n\n@gin.configurable\nclass RecurrentStateSpaceModel(object):\n\n  def __init__(self,\n      stoch_size=30,\n      deter_size=200,\n      min_stddev=0.1,\n      layers=1,\n      reward_layers=3,\n      units=300,\n      free_nats=3.0,\n      reward_loss_multiplier=10,\n      frame_size=(64, 64, 3),\n      task=gin.REQUIRED,\n      reward_from_frames=False,\n      reward_stop_gradient=False,\n      include_frames_in_prediction=False,\n      activation=tf.nn.relu):\n    self._action_space = task.create_env().action_space\n    self._stoch_size = stoch_size\n    self._deter_size = deter_size\n    self._min_stddev = min_stddev\n    self._num_layers = layers\n    self._num_reward_layers = reward_layers\n    self._num_units = units\n    self._free_nats = free_nats\n    self._include_frames_in_prediction = include_frames_in_prediction\n    self._activation = activation\n    self._cell = tf.keras.layers.GRUCell(self._deter_size)\n    self._prior_tpl = tf.make_template('prior', self._prior)\n    self._posterior_tpl = tf.make_template('posterior', self._posterior)\n    self._encoder_tpl = tf.make_template('encoder', self._encoder)\n    self._reward_loss_mul = reward_loss_multiplier\n    self._frame_size = list(frame_size)\n    self._reward_from_frames = reward_from_frames\n    self._reward_stop_gradient = reward_stop_gradient\n    self._predict_frames_tpl = tf.make_template(\n        'predict_frames', self._predict_frames, out_shape=self._frame_size)\n    self._predict_reward_tpl = tf.make_template(\n        'predict_reward', self._predict_reward, out_shape=[1])\n\n  @property\n  def is_discrete_action(self):\n    return isinstance(self._action_space, gym.spaces.Discrete)\n\n  def get_trackables(self):\n    return {\n        'prior_tpl': self._prior_tpl,\n        'posterior_tpl': self._posterior_tpl,\n        'encoder_tpl': self._encoder_tpl,\n        'predict_frames_tpl': self._predict_frames_tpl,\n        'predict_reward_tpl': self._predict_reward_tpl,\n        'cell': self._cell,\n    }\n\n  def initialize(self, batch_size):\n    return {\n        'mean':\n          tf.zeros([batch_size, self._stoch_size]),\n        'std':\n          tf.zeros([batch_size, self._stoch_size]),\n        'stoch':\n          tf.zeros([batch_size, self._stoch_size]),\n        'deter':\n          self._cell.get_initial_state(\n              batch_size=batch_size, dtype=tf.float32)\n    }\n\n  def compute_losses(self, obs):\n    image = obs['image']\n    action = obs['action']\n    reward = obs['reward']\n    state = self.initialize(tf.shape(image)[0])\n    state['rewards'] = reward\n    priors, posteriors = self.observe(action, image, state)\n    features = self._get_features(posteriors)\n    frames = self._predict_frames_tpl(features)\n    if self._reward_from_frames:\n      rewards = self._predict_reward_tpl(frames.mode(), reward[:, -1])\n    else:\n      rewards = self._predict_reward_tpl(features, reward[:, -1])\n    obs_likelihood = frames.log_prob(image)\n    reward_likelihood = rewards.log_prob(tf.to_float(reward))\n\n    divergence = tfd.kl_divergence(\n        self._get_distribution(posteriors), self._get_distribution(priors))\n    divergence = tf.maximum(self._free_nats, divergence)\n    loss = tf.reduce_mean(divergence - obs_likelihood -\n                          reward_likelihood * self._reward_loss_mul)\n    frames_mode = tf.clip_by_value((frames.mode() + 0.5) * 255, 0, 255)\n    return (loss, tf.reduce_mean(reward_likelihood), tf.reduce_mean(divergence),\n            tf.cast(frames_mode, dtype=tf.uint8), rewards.mode(), obs['reward'],\n            tf.reduce_mean(tf.math.squared_difference(frames_mode, image)))\n\n  def observe(self, actions, images, state):\n    embedded_obs = self._encoder_tpl(images)\n    if self.is_discrete_action:\n      actions = tf.one_hot(\n          actions[:, :, 0], self._action_space.n, dtype=tf.float32)\n    else:\n      actions = tf.to_float(actions)\n    actions = tf.transpose(actions, [1, 0, 2])\n    embedded_obs = tf.transpose(embedded_obs, [1, 0, 2])\n    state.pop('rewards')\n    priors, posteriors = static_scan(\n        lambda prev, inp: self._posterior_tpl(prev[1], *inp),\n        (actions, embedded_obs), (state, state))\n    priors = {\n        key: tf.transpose(value, [1, 0, 2]) for key, value in priors.items()\n    }\n    posteriors = {\n        key: tf.transpose(value, [1, 0, 2])\n        for key, value in posteriors.items()\n    }\n    return priors, posteriors\n\n  def predict(self, actions, state):\n    if isinstance(self._action_space, gym.spaces.Discrete):\n      actions = tf.one_hot(\n          actions[:, :, 0], self._action_space.n, dtype=tf.float32)\n    else:\n      actions = tf.to_float(actions)\n    actions = tf.transpose(actions, [1, 0, 2])\n    rewards = tf.to_float(state.pop('rewards'))\n    priors = static_scan(self._prior_tpl, actions, state)\n    priors = {\n        key: tf.transpose(value, [1, 0, 2]) for key, value in priors.items()\n    }\n    features = self._get_features(priors)\n    results = {}\n    if self._reward_from_frames:\n      frames = self._predict_frames_tpl(features).mode()\n      results['reward'] = self._predict_reward_tpl(frames, rewards).mode()\n    else:\n      results['reward'] = self._predict_reward_tpl(features, rewards).mode()\n    if self._include_frames_in_prediction:\n      results['image'] = tf.cast(\n          tf.clip_by_value(\n              (self._predict_frames_tpl(features).mode() + 0.5) * 255, 0, 255),\n          dtype=tf.uint8)\n    return results\n\n  def _get_distribution(self, states):\n    return tfd.MultivariateNormalDiag(states['mean'], states['std'])\n\n  def _get_features(self, states):\n    return tf.concat([states['stoch'], states['deter']], -1)\n\n  def _prior(self, prev_state, prev_action):\n    hidden = tf.concat([prev_state['stoch'], prev_action], -1)\n    for _ in range(self._num_layers):\n      hidden = tf.layers.dense(hidden, self._num_units,\n                               self._activation)\n    hidden, deter = self._cell(hidden, [prev_state['deter']])\n    deter = deter[0]\n    for _ in range(self._num_layers):\n      hidden = tf.layers.dense(hidden, self._num_units,\n                               self._activation)\n    mean, std = tf.split(\n        tf.layers.dense(hidden, 2 * self._stoch_size), 2, -1)\n    std = tf.nn.softplus(std) + self._min_stddev\n    stoch = tfd.MultivariateNormalDiag(mean, std).sample()\n    return {'mean': mean, 'std': std, 'stoch': stoch, 'deter': deter}\n\n  def _posterior(self, prev_state, prev_action, embedded_obs):\n    prior = self._prior_tpl(prev_state, prev_action)\n    hidden = tf.concat([prior['deter'], embedded_obs], -1)\n    for _ in range(self._num_layers):\n      hidden = tf.layers.dense(hidden, self._num_units,\n                               self._activation)\n    mean, std = tf.split(\n        tf.layers.dense(hidden, 2 * self._stoch_size), 2, -1)\n    std = tf.nn.softplus(std) + self._min_stddev\n    stoch = tfd.MultivariateNormalDiag(mean, std).sample()\n    post = {'mean': mean, 'std': std, 'stoch': stoch, 'deter': prior['deter']}\n    return prior, post\n\n  def _encoder(self, images):\n    kwargs = dict(strides=2, activation=tf.nn.relu)\n    images = tf.to_float(images)\n    hidden = tf.reshape(images, [-1] + images.shape[2:].as_list())\n    hidden = tf.layers.conv2d(hidden, 32, 4, **kwargs)\n    hidden = tf.layers.conv2d(hidden, 64, 4, **kwargs)\n    hidden = tf.layers.conv2d(hidden, 128, 4, **kwargs)\n    hidden = tf.layers.conv2d(hidden, 256, 4, **kwargs)\n    hidden = tf.layers.flatten(hidden)\n    assert hidden.shape[1:].as_list() == [1024], hidden.shape.as_list()\n    embedded_obs = tf.reshape(hidden, [\n        tf.shape(images)[0],\n        tf.shape(images)[1],\n        np.prod(hidden.shape[1:].as_list())\n    ])\n    return embedded_obs\n\n  def _predict_frames(self, features, out_shape):\n    kwargs = dict(strides=2, activation=tf.nn.relu)\n    hidden = tf.layers.dense(features, 1024, None)\n    hidden = tf.reshape(hidden, [-1, 1, 1, hidden.shape[-1]])\n    hidden = tf.layers.conv2d_transpose(hidden, 128, 5, **kwargs)\n    hidden = tf.layers.conv2d_transpose(hidden, 64, 5, **kwargs)\n    hidden = tf.layers.conv2d_transpose(hidden, 32, 6, **kwargs)\n    mean = tf.layers.conv2d_transpose(hidden, 3, 6, strides=2)\n    assert mean.shape[1:].as_list() == [64, 64, 3], mean.shape\n    mean = tf.reshape(mean, tf.concat([tf.shape(features)[:-1], out_shape], 0))\n    mean = tf.cast(mean, tf.float32)\n    return tfd.Independent(tfd.Normal(mean, 1), len(out_shape))\n\n  def _predict_reward(self, features, rewards, out_shape):\n    if self._reward_stop_gradient:\n      hidden = tf.stop_gradient(features)\n    else:\n      hidden = features\n    if self._reward_from_frames:\n      split_frames = [\n          tf.squeeze(f, axis=1)\n          for f in tf.split(features, features.shape[1], axis=1)\n      ]\n      mean = reward_models.reward_prediction_video_conv(split_frames, rewards,\n                                                        len(split_frames))\n      return tfd.Independent(tfd.Normal(mean, 1), len(out_shape))\n    else:\n      for _ in range(self._num_reward_layers):\n        hidden = tf.layers.dense(hidden, self._num_units,\n                                 self._activation)\n      mean = tf.layers.dense(hidden, int(np.prod(out_shape)))\n      mean = tf.reshape(mean, tf.concat([tf.shape(features)[:-1], out_shape],\n                                        0))\n      return tfd.Independent(tfd.Normal(mean, 1), len(out_shape))\n\n\n@gin.configurable\ndef create_planet_reset_fn(model):\n  @tf.function\n  def reset(**kwargs):\n    batch_size = kwargs['proposals']\n    state = model.initialize(batch_size)\n    state['rewards'] = tf.zeros([batch_size, 1])\n    return state\n\n  return reset\n\n\n@gin.configurable\ndef create_planet_observe_fn(model, model_dir, strategy):\n  with strategy.scope():\n    checkpoint = tf.train.Checkpoint(**model.get_trackables())\n    manager = tf.train.CheckpointManager(checkpoint, model_dir, max_to_keep=1)\n    checkpoint.restore(manager.latest_checkpoint).expect_partial()\n\n  @tf.function\n  def observe(images, actions, rewards, state):\n    images = tf.to_float(images) / 255.0 - 0.5\n    # break down the inputs along the batch dimension to form equal sized\n    # tensors in each replica.\n    num_replicas = strategy.num_replicas_in_sync\n    images = tf.split(images, num_replicas)\n    actions = tf.split(actions, num_replicas)\n    state = {key: tf.split(value, num_replicas) for key, value in state.items()}\n    devices = values.ReplicaDeviceMap(strategy.extended.worker_devices)\n    dist_images = values.PerReplica(devices, tuple(images))\n    dist_actions = values.PerReplica(devices, tuple(actions))\n    dist_state = []\n    for i in range(num_replicas):\n      dist_state.append({key: value[i] for key, value in state.items()})\n    dist_state = values.PerReplica(devices, tuple(dist_state))\n    _, dist_posteriors = strategy.experimental_run_v2(\n        model.observe, args=(dist_actions, dist_images, dist_state))\n    dist_posteriors = {\n        key: strategy.experimental_local_results(value)\n        for key, value in dist_posteriors.items()\n    }\n    posteriors = {\n        key: tf.concat(value, axis=0) for key, value in dist_posteriors.items()\n    }\n    posteriors = {key: value[:, -1] for key, value in posteriors.items()}\n    posteriors['rewards'] = rewards[:, -1]\n    return posteriors\n\n  return observe\n\n\n@gin.configurable\ndef create_planet_predict_fn(model, strategy):\n  @tf.function\n  def predict(actions, state):\n    state = state.copy()\n    # break down the inputs along the batch dimension to form equal sized\n    # tensors in each replica.\n    num_replicas = strategy.num_replicas_in_sync\n    actions = tf.split(actions, num_replicas)\n    state = {key: tf.split(value, num_replicas) for key, value in state.items()}\n    devices = values.ReplicaDeviceMap(strategy.extended.worker_devices)\n    dist_actions = values.PerReplica(devices, tuple(actions))\n    dist_state = []\n    for i in range(num_replicas):\n      dist_state.append({key: value[i] for key, value in state.items()})\n    dist_state = values.PerReplica(devices, tuple(dist_state))\n\n    dist_predictions = strategy.experimental_run_v2(\n        model.predict, args=(dist_actions, dist_state))\n    dist_predictions = {\n        key: strategy.experimental_local_results(value)\n        for key, value in dist_predictions.items()\n    }\n    predictions = {\n        key: tf.concat(value, axis=0)\n        for key, value in dist_predictions.items()\n    }\n    return predictions\n\n  return predict\n\n\n@gin.configurable\ndef create_planet_train_fn(model: RecurrentStateSpaceModel = gin.REQUIRED,\n    train_steps: int = gin.REQUIRED,\n    batch: int = gin.REQUIRED,\n    duration: int = gin.REQUIRED,\n    learning_rate: float = gin.REQUIRED,\n    model_dir=gin.REQUIRED,\n    strategy: tf.distribute.Strategy = gin.REQUIRED,\n    save_rewards: bool = True):\n  \"\"\"creates a train_fn to train the `tf.Estimator` referenced in state.\n\n  Args:\n    model: a reference to the model.\n    train_steps: number of training steps.\n    batch: the batch size.\n    duration: how many timesteps to include in a single video sequence.\n    learning_rate: learning rate.\n    model_dir: the path to model directory.\n    strategy: a tf.distribute.Strategy object.\n    save_rewards: whether or not to save the predicted rewards.\n\n  Returns:\n    A train_fn with the following positional arguments:\n        * data_path: the path to all episodes.\n      This function returns nothing.\n  \"\"\"\n  iterator = None\n  optimizer = tf.keras.optimizers.Adam(learning_rate, epsilon=1e-3)\n\n  @tf.function\n  def train_step(obs):\n\n    def train_iter(obs):\n      obs = obs.copy()\n      obs['image'] = tf.to_float(obs['image']) / 255.0 - 0.5\n      with tf.GradientTape() as tape:\n        output = model.compute_losses(obs)\n        loss, reward_loss, divergence, frames = output[:4]\n        pred_rewards, true_rewards, frame_loss = output[4:]\n      variables = tape.watched_variables()\n      grads = tape.gradient(loss, variables)\n      grads, _ = tf.clip_by_global_norm(grads, 1000)\n      optimizer.apply_gradients(zip(grads, variables))\n      return loss, reward_loss, divergence, frames, pred_rewards, true_rewards, frame_loss\n\n    return strategy.experimental_run_v2(train_iter, args=(obs,))\n\n  def train_fn(data_path):\n    \"\"\"A train_fn to train the planet model.\"\"\"\n    nonlocal iterator\n    nonlocal optimizer\n\n    with strategy.scope():\n      global_step = tf.Variable(0, dtype=tf.int64, trainable=False)\n      checkpoint = tf.train.Checkpoint(\n          global_step=global_step,\n          optimizer=optimizer,\n          **model.get_trackables())\n      manager = tf.train.CheckpointManager(checkpoint, model_dir, max_to_keep=1)\n      checkpoint.restore(manager.latest_checkpoint)\n    if iterator is None:\n      dataset = npz.load_dataset_from_directory(data_path, duration, batch)\n      dataset = strategy.experimental_distribute_dataset(dataset)\n      iterator = dataset\n\n    writer = tfs.create_file_writer(model_dir)\n    tfs.experimental.set_step(global_step)\n    true_rewards, pred_rewards = None, None\n    with writer.as_default():\n      for step, obs in enumerate(iterator):\n        if step > train_steps:\n          if save_rewards:\n            # We are only saving the last training batch.\n            reward_dir = os.path.join(model_dir, 'train_rewards')\n            true_rewards = strategy.experimental_local_results(true_rewards)\n            pred_reward = strategy.experimental_local_results(pred_rewards)\n            true_rewards = np.concatenate([x.numpy() for x in true_rewards])\n            pred_reward = np.concatenate([x.numpy() for x in pred_reward])\n            rewards_to_save = {'true': true_rewards, 'pred': pred_reward}\n            npz.save_dictionary(rewards_to_save, reward_dir)\n          break\n        (loss, reward_loss, divergence, frames, pred_rewards, true_rewards,\n         frame_loss) = train_step(obs)\n        if step % 100 == 0:\n          loss = strategy.reduce(tf.distribute.ReduceOp.MEAN, loss)\n          reward_loss = strategy.reduce(tf.distribute.ReduceOp.MEAN,\n                                        reward_loss)\n          divergence = strategy.reduce(tf.distribute.ReduceOp.MEAN, divergence)\n          frame_loss = strategy.reduce(tf.distribute.ReduceOp.MEAN, frame_loss)\n          frames = strategy.experimental_local_results(frames)\n          frames = tf.concat(frames, axis=0)\n          pred_reward = strategy.experimental_local_results(pred_rewards)\n          pred_reward = tf.concat(pred_reward, axis=0)\n          tf.logging.info('loss at step %d: %f', step, loss)\n          tfs.scalar('loss/total', loss)\n          tfs.scalar('loss/reward', reward_loss)\n          tfs.scalar('loss/divergence', divergence)\n          tfs.scalar('loss/frames', frame_loss)\n          tfs.experimental.write_raw_pb(\n              visualization.py_gif_summary(\n                  tag='predictions/frames',\n                  images=frames.numpy(),\n                  max_outputs=6,\n                  fps=20))\n          ground_truth_rewards = (\n              tf.concat(\n                  strategy.experimental_local_results(obs['reward']),\n                  axis=0)[:, :, 0])\n          rewards = pred_reward[:, :, 0]\n          signals = tf.stack([ground_truth_rewards, rewards], axis=1)\n          visualization.py_plot_1d_signal(\n              name='predictions/reward',\n              signals=signals.numpy(),\n              labels=['ground_truth', 'prediction'],\n              max_outputs=6)\n        global_step.assign_add(1)\n\n      manager.save(global_step)\n\n  return train_fn\n", "meta": {"hexsha": "5602c330f80c1102e0fe859c8bc461fced08fa85", "size": 19529, "ext": "py", "lang": "Python", "max_stars_repo_path": "agents/planet.py", "max_stars_repo_name": "pacificlion/world_models", "max_stars_repo_head_hexsha": "dff58d80466f0b0fcee59ca25581ea986f8663d5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 106, "max_stars_repo_stars_event_min_datetime": "2020-12-08T22:45:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:21:32.000Z", "max_issues_repo_path": "agents/planet.py", "max_issues_repo_name": "pacificlion/world_models", "max_issues_repo_head_hexsha": "dff58d80466f0b0fcee59ca25581ea986f8663d5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-12-09T17:05:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T03:00:03.000Z", "max_forks_repo_path": "agents/planet.py", "max_forks_repo_name": "pacificlion/world_models", "max_forks_repo_head_hexsha": "dff58d80466f0b0fcee59ca25581ea986f8663d5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-12-10T04:46:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T11:34:14.000Z", "avg_line_length": 39.058, "max_line_length": 90, "alphanum_fraction": 0.6719750115, "include": true, "reason": "import numpy", "num_tokens": 4713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.17023066539325363}}
{"text": "#M3 -- Meka Robotics Robot Components\n#Copyright (c) 2010 Meka Robotics\n#Author: edsinger@mekabot.com (Aaron Edsinger)\n\n#M3 is free software: you can redistribute it and/or modify\n#it under the terms of the GNU Lesser General Public License as published by\n#the Free Software Foundation, either version 3 of the License, or\n#(at your option) any later version.\n\n#M3 is distributed in the hope that it will be useful,\n#but WITHOUT ANY WARRANTY; without even the implied warranty of\n#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n#GNU Lesser General Public License for more details.\n\n#You should have received a copy of the GNU Lesser General Public License\n#along with M3.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom m3.chain import M3Chain\nimport m3.toolbox as m3t\nimport m3.toolbox_ctrl as m3tc\nimport scipy.linalg\nimport numpy as nu\nfrom m3.unit_conversion import *\n\n#Wrapper only\nclass M3Arm(M3Chain):\n\t\"\"\"Wrapper for 7DOF SEA Arm\"\"\"\n\tdef __init__(self,name):\n\t\tM3Chain.__init__(self,name,ndof=7,ctype='m3arm')\n\t\tself.set_fts_transform(nu.identity(4,float)) #default\n\t\tself.ikjt_q=None\n\t# ############################################################################# \n\n\t\"\"\"Force-torque sensor support.\n\tAssumes that wrench is 6x1 Numeric array. \n\tSee documentation for frame definitions\"\"\"\n\n\tdef set_fts_transform(self,T):\n\t\t\"\"\" Set the homogenous transform from the force-torque-sensor frame to eff frame\"\"\"\n\t\tself.S2E = nu.array(T,float) #Transform point in sensor frame to eff\n\t\tself.E2S =  scipy.linalg.inv(self.S2E)  #Transform point in eff to sensor frame.\n\t\tself.FS2FE = m3tc.force_moment_transform(self.S2E)  #Transform wrench in sensor frame to eff frame\n\t\tself.FE2FS = m3tc.force_moment_transform(self.E2S)  #Transform wrench in eff frame to sensor frame\n\n\tdef fts_wrench_to_tool_wrench(self,wrench):\n\t\teffw=nu.matrixmultiply(self.FS2FE,wrench)\n\t\tendw=nu.matrixmultiply(self.eff_wrench_2_end_wrench_transform(),effw)\n\t\treturn self.end_wrench_2_tool_wrench(endw)\n\n\tdef tool_wrench_to_fts_wrench(self,wrench):\n\t\tendw=self.tool_wrench_2_end_wrench(wrench) \n\t\teffw=nu.matrixmultiply(self.end_wrench_2_eff_wrench_transform(),endw)\n\t\treturn nu.matrixmultiply(self.FE2FS,effw)\n\n\tdef fts_wrench_to_joint_torques(self,wrench):\n\t\teffw=nu.matrixmultiply(self.FS2FE,wrench)\n\t\tendw=nu.matrixmultiply(self.eff_wrench_2_end_wrench_transform(),effw)\n\t\treturn self.end_wrench_2_joint_torques(endw)\n\n\tdef joint_torques_to_fts_wrench(self,tq):\n\t\tendw=self.joint_torques_2_end_wrench(tq)\n\t\teffw=nu.matrixmultiply(self.end_wrench_2_eff_wrench_transform(),endw)\n\t\treturn nu.matrixmultiply(self.FE2FS,effw)\n\n\t# ############################################################################# \n\n\tdef start_ikjt_simple(self):\n\t\tself.ikjt_q=self.get_theta_rad()\n\n\tdef step_ikjt_simple(self,target,step_size):\n\t\t\"\"\" A simple method for doing inverse-kinematics using the Jacobian Transpose. Because\n\tof the redundant DOF , this only good for small excursions from a known\n\tgood posture in joint-space. Othewise strange elbow configurations can arise.\n\t\"\"\"\n\t\tself.set_virtual_theta_rad(self.ikjt_q)\n\t\tx=self.get_virtual_end_position()\n\t\tdx=(target-x)*step_size\n\t\tverror=nu.sqrt(sum((target-x)**2))\n\t\tdx.resize(6) #roll/pitch/yaw=0\n\t\tdq= nu.matrixmultiply(nu.transpose(self.vJ),dx)\n\t\tself.ikjt_q=self.ikjt_q+dq\n\t\treturn verror,self.ikjt_q\n\n\n\n\n\n\n\n", "meta": {"hexsha": "82f1e4a5a41c2fa849eacb1abdd454a81f01458b", "size": 3350, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/m3/arm.py", "max_stars_repo_name": "ahoarau/m3meka", "max_stars_repo_head_hexsha": "237739f0266ce60aaa3013b0d2b22fc07b6374c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-06-19T12:14:18.000Z", "max_stars_repo_stars_event_max_datetime": "2015-06-19T12:14:18.000Z", "max_issues_repo_path": "python/m3/arm.py", "max_issues_repo_name": "semeyerz/m3meka", "max_issues_repo_head_hexsha": "6e5d6b73ad3ebdd8429497923e601eae65d8b2fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/m3/arm.py", "max_forks_repo_name": "semeyerz/m3meka", "max_forks_repo_head_hexsha": "6e5d6b73ad3ebdd8429497923e601eae65d8b2fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-11-27T09:25:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-16T16:29:22.000Z", "avg_line_length": 37.2222222222, "max_line_length": 100, "alphanum_fraction": 0.743880597, "include": true, "reason": "import numpy,import scipy", "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.32766829425520916, "lm_q1q2_score": 0.17023066539325363}}
{"text": "#! /usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\n    ****\n    Beam\n    ****\n\"\"\"\n\n\n__author__ = 'Alan Loh'\n__copyright__ = 'Copyright 2020, nenupy'\n__credits__ = ['Alan Loh']\n__maintainer__ = 'Alan'\n__email__ = 'alan.loh@obspm.fr'\n__status__ = 'Production'\n__all__ = [\n    'Beam',\n    'ABeam',\n    'DBeam'\n]\n\n\nimport numpy as np\nimport astropy.units as u\nfrom astropy.coordinates import ICRS, SkyCoord, AltAz\nfrom astropy.time import Time\nfrom healpy.pixelfunc import get_interp_val\n\nfrom nenupy.instru import (\n    nenufar_ant_gain,\n    desquint_elevation,\n    analog_pointing,\n    ma_antpos,\n    ma_info,\n    ma_pos\n)\nfrom nenupy.astro import (\n    wavelength,\n    toAltaz,\n    ho_coord\n)\n\nimport logging\nlog = logging.getLogger(__name__)\n\n\n# ============================================================= #\n# --------------------------- Beam ---------------------------- #\n# ============================================================= #\nclass Beam(object):\n    \"\"\"\n    \"\"\"\n\n    def __init__(self, freq, polar):\n        self.freq = freq\n        self.polar = polar\n\n\n    # --------------------------------------------------------- #\n    # --------------------- Getter/Setter --------------------- #\n    @property\n    def freq(self):\n        return self._freq\n    @freq.setter\n    def freq(self, f):\n        if not isinstance(f, u.Quantity):\n            f *= u.MHz\n        if not f.isscalar:\n            raise ValueError(\n                'Only scalar frequency allowed'\n            )\n        self._freq = f\n        log.info(\n            'Frequency sets at {}'.format(self._freq)\n        )\n        return\n\n\n    @property\n    def polar(self):\n        return self._polar\n    @polar.setter\n    def polar(self, p):\n        if not np.isscalar(p):\n            raise ValueError(\n                'Only scalar polar allowed'\n            )\n        allowed = ['NW', 'NE']\n        if p.upper() not in allowed:\n            raise ValueError(\n                'Polarization {} not in {}'.format(\n                    p,\n                    allowed\n                )\n            )\n        self._polar = p.upper()\n        log.info(\n            'Polarization sets at {}'.format(self._polar)\n        )\n        return\n\n\n    # --------------------------------------------------------- #\n    # ------------------------ Methods ------------------------ #\n    def ant_gain(self, coords, time):\n        \"\"\" Returns NenuFAR antenna gain values interpolated at\n            coordinates ``coords`` at time ``time``.\n\n            :param coords:\n            :type coords: :class:`~astropy.coordinates.ICRS` or \n                :class:`~astropy.coordinates.SkyCoord`\n            :param time:\n            :type time: :class:`~astropy.time.Time`\n\n            :returns: NenuFAR normalized antenna gain\n            :rtype: `~numpy.ndarray`\n\n            :Example:\n                To get back the HEALPix ant gain:\n                \n                >>> from nenupy.beam import Beam\n                >>> import numpy as np\n                >>> import astropy.units as u\n                >>> from astropy.coordinates import ICRS\n                >>> from astropy.time import Time\n                >>> from healpy.pixelfunc import nside2npix, pix2ang\n                >>> from healpy.visufunc import mollview\n                >>> b = Beam(\n                        freq=50,\n                        polar='NE',\n                    )\n                >>> npix = nside2npix(nside=32)\n                >>> ra, dec = pix2ang(\n                        nside=32,\n                        ipix=np.arange(npix),\n                        lonlat=True\n                    )\n                >>> gain = b.ant_gain(\n                        coords=ICRS(\n                            ra=ra*u.deg,\n                            dec=dec*u.deg\n                        ),\n                        time=Time.now()\n                    )\n                >>> mollview(gain)\n\n        \"\"\"\n        if not isinstance(coords, (ICRS, SkyCoord)):\n            raise TypeError(\n                'coords should be ICRS or SkyCoord object'\n            )\n        if not isinstance(time, Time):\n            raise TypeError(\n                'time should be Time object'\n            )\n        hpxgain = nenufar_ant_gain(\n            freq=self.freq,\n            polar=self.polar,\n            nside=32,\n            time=time\n        )\n        log.info(\n            'NenuFAR HEALPix antenna gain loaded.'\n        )\n        vals = get_interp_val(\n            m=hpxgain,\n            theta=coords.ra.deg,\n            phi=coords.dec.deg,\n            lonlat=True\n        )\n        log.info(\n            'NenuFAR antenna gain values interpolated.'\n        )\n        return vals\n\n\n    def array_factor(self, phase_center, coords, antpos):\n        \"\"\"\n        \"\"\"\n        if not (isinstance(phase_center, AltAz) or hasattr(phase_center, 'altaz')):\n            raise TypeError(\n                'phase_center should be an AltAz instance'\n            )\n        if not (isinstance(coords, AltAz) or hasattr(coords, 'altaz')):\n            raise TypeError(\n                'coords should be an AltAz instance'\n            )\n        if not isinstance(antpos, np.ndarray):\n            raise TypeError(\n                'antpos should be an np.ndarray instance'\n            )\n        if antpos.shape[1] != 3:\n            raise IndexError(\n                'antpos should have 2nd dimension = 3 (x, y, z)'\n            )\n        def get_phi(az, el, antpos):\n            \"\"\" az, el in radians\n            \"\"\"\n            xyz_proj = np.array(\n                [\n                    np.cos(az) * np.cos(el),\n                    np.sin(az) * np.cos(el),\n                    np.sin(el)\n                ]\n            )\n            antennas = np.array(antpos)\n            phi = np.dot(antennas, xyz_proj)\n            return phi\n        phi0 = get_phi(\n            az=[phase_center.az.rad],\n            el=[phase_center.alt.rad],\n            antpos=antpos\n        )\n        phi_grid = get_phi(\n            az=coords.az.rad,\n            el=coords.alt.rad,\n            antpos=antpos\n        )\n        delay = phi_grid - phi0\n        coeff = 2j * np.pi / wavelength(self.freq).value\n        af = np.sum(np.exp(coeff*delay), axis=0)\n        return np.real(af * af.conjugate())\n    # --------------------------------------------------------- #\n    # ----------------------- Internal ------------------------ #\n\n\n# ============================================================= #\n\n\n# ============================================================= #\n# --------------------------- Beam ---------------------------- #\n# ============================================================= #\nclass ABeam(Beam):\n    \"\"\"\n    \"\"\"\n\n    def __init__(self, freq, polar, azana, elana, ma=0):\n        super().__init__(\n            freq=freq,\n            polar=polar\n        )\n        self.azana = azana\n        self.elana = elana\n        self.ma = ma\n        self.squint_freq = 30*u.MHz\n        self.beamsquint = True\n\n\n    # --------------------------------------------------------- #\n    # --------------------- Getter/Setter --------------------- #\n    @property\n    def azana(self):\n        \"\"\"\n        \"\"\"\n        return self._azana\n    @azana.setter\n    def azana(self, a):\n        if not isinstance(a, u.Quantity):\n            a *= u.deg\n        self._azana = a\n        log.info(\n            'Desired analog azimuth: {}'.format(self._azana)\n        )\n        return\n\n\n    @property\n    def elana(self):\n        \"\"\"\n        \"\"\"\n        return self._elana\n    @elana.setter\n    def elana(self, e):\n        if not isinstance(e, u.Quantity):\n            e *= u.deg\n        self._elana = e\n        log.info(\n            'Desired analog elevation: {}'.format(self._elana)\n        )\n        return\n\n\n    @property\n    def ma(self):\n        return self._ma\n    @ma.setter\n    def ma(self, m):\n        if not isinstance(m, (int, np.integer)):\n            raise TypeError(\n                'ma should be integer'\n            )\n        max_ma_name = ma_info['ma'].size - 1\n        if m > max_ma_name:\n            raise ValueError(\n                'select a MA name <= {}'.format(\n                    max_ma_name\n                )\n            )\n        self._ma = m\n        self._rot = ma_info['rot'][ma_info['ma'] == m][0]\n        log.info(\n            'MA {} selected (rotation {} mod 60 deg)'.format(\n                m,\n                self._rot%60\n            )\n        )\n        return\n\n\n    @property\n    def squint_freq(self):\n        return self._squint_freq\n    @squint_freq.setter\n    def squint_freq(self, f):\n        if not isinstance(f, u.Quantity):\n            f *= u.MHz\n        if not f.isscalar:\n            raise ValueError(\n                'Only scalar squint_freq allowed'\n            )\n        self._squint_freq = f\n        log.info(\n            'Squint frequency sets at {}'.format(f)\n        )\n        return\n\n\n    @property\n    def beamsquint(self):\n        return self._beamsquint\n    @beamsquint.setter\n    def beamsquint(self, b):\n        if not isinstance(b, bool):\n            raise TypeError(\n                'beamsquint should be a boolean'\n            )\n        self._beamsquint = b\n        if b:\n            log.info(\n                'Beam squint correction activated.'\n            )\n        else:\n            log.info(\n                'No beam squint correction.'\n            )\n\n\n    # --------------------------------------------------------- #\n    # ------------------------ Methods ------------------------ #\n    def beam_values(self, coords, time):\n        \"\"\"\n            :param coords:\n            :type coords: :class:`~astropy.coordinates.ICRS` or \n                :class:`~astropy.coordinates.SkyCoord`\n            :param time:\n            :type time: :class:`~astropy.time.Time`\n        \"\"\"\n        if not isinstance(coords, (ICRS, SkyCoord)):\n            raise TypeError(\n                'coords should be ICRS or SkyCoord object'\n            )\n        if coords.isscalar:\n            raise ValueError('coords should not be a scalar.')\n        if not isinstance(time, Time):\n            raise TypeError(\n                'time should be Time object'\n            )\n        # Real pointing\n        if self.beamsquint:\n            el = desquint_elevation(\n                elevation=self.elana,\n                opt_freq=self.squint_freq\n            )\n        else:\n            el = self.elana.copy()\n        az, el = analog_pointing(self.azana, el)\n        log.info(\n            'Effective analog pointing=({}, {})'.format(\n                az,\n                el\n            )\n        )\n        # Array factor\n        phase_center = ho_coord(\n                az=az,\n                alt=el,\n                time=time\n        )\n        altazcoords = toAltaz(\n            skycoord=coords,\n            time=time\n        )  \n        arrfac = self.array_factor(\n            phase_center=phase_center,\n            coords=altazcoords,\n            antpos=ma_antpos(\n                rot=self._rot\n            )\n        )\n        # Antenna Gain\n        antgain = self.ant_gain(\n            coords=coords,\n            time=time\n        )\n        anagain = arrfac * antgain\n        log.info(\n            'Anabeam (rot {}) computed for {} pixels.'.format(\n                self._rot%60,\n                anagain.size\n            )\n        )\n        return anagain\n# ============================================================= #\n\n\n# ============================================================= #\n# --------------------------- Beam ---------------------------- #\n# ============================================================= #\nclass DBeam(Beam):\n    \"\"\"\n    \"\"\"\n\n    def __init__(self, freq, polar, azdig, eldig, ma,\n        azana=None, elana=None, squint_freq=30, beamsquint=True):\n        super().__init__(\n            freq=freq,\n            polar=polar\n        )\n        self.azdig = azdig\n        self.eldig = eldig\n        self.ma = ma\n        self.azana = azdig if azana is None else azana\n        self.elana = eldig if elana is None else elana\n        self.squint_freq = squint_freq\n        self.beamsquint = beamsquint\n\n\n    # --------------------------------------------------------- #\n    # --------------------- Getter/Setter --------------------- #\n    @property\n    def azdig(self):\n        \"\"\"\n        \"\"\"\n        return self._azdig\n    @azdig.setter\n    def azdig(self, a):\n        if not isinstance(a, u.Quantity):\n            a *= u.deg\n        self._azdig = a\n        log.info(\n            'Digital azimuth: {}'.format(self._azdig)\n        )\n        return\n\n\n    @property\n    def eldig(self):\n        \"\"\"\n        \"\"\"\n        return self._eldig\n    @eldig.setter\n    def eldig(self, e):\n        if not isinstance(e, u.Quantity):\n            e *= u.deg\n        self._eldig = e\n        log.info(\n            'Digital elevation: {}'.format(self._eldig)\n        )\n        return\n\n\n    @property\n    def ma(self):\n        return self._ma\n    @ma.setter\n    def ma(self, m):\n        if isinstance(m, list):\n            m = np.array(m)\n        if np.isscalar(m):\n            raise ValueError(\n                'ma should at list be of length 2'\n            )\n        if not np.isin(m, ma_info['ma']).all():\n            raise ValueError(\n                'Some MA names are > {}'.format(\n                    ma_info['ma'].max()\n                )\n            )\n        self._ma = m.astype(int)\n        log.info(\n            'MAs {} selected for digital beam.'.format(\n                self._ma\n            )\n        )\n        return\n\n\n    # --------------------------------------------------------- #\n    # ------------------------ Methods ------------------------ #\n    def beam_values(self, coords, time):\n        \"\"\"\n            :param coords:\n            :type coords: :class:`~astropy.coordinates.ICRS` or \n                :class:`~astropy.coordinates.SkyCoord`\n            :param time:\n            :type time: :class:`~astropy.time.Time`\n        \"\"\"\n        if not isinstance(coords, (ICRS, SkyCoord)):\n            raise TypeError(\n                'coords should be ICRS or SkyCoord object'\n            )\n        if not isinstance(time, Time):\n            raise TypeError(\n                'time should be Time object'\n            )\n\n        # Build the Mini-Array 'summed' response\n        abeams = {}\n        for ma in self.ma:\n            rot = ma_info['rot'][ma_info['ma'] == ma][0]\n            if str(rot%60) not in abeams.keys():\n                ana = ABeam(\n                    freq=self.freq,\n                    polar=self.polar,\n                    azana=self.azana,\n                    elana=self.elana,\n                    ma=ma\n                )\n                ana.beamsquint = self.beamsquint\n                anavals = ana.beam_values(\n                    coords=coords,\n                    time=time\n                )\n                abeams[str(rot%60)] = anavals.copy()\n            if not 'summa' in locals():\n                summa = abeams[str(rot%60)]\n            else:\n                summa += abeams[str(rot%60)]\n         # Array factor\n        phase_center = ho_coord(\n                az=self.azdig,\n                alt=self.eldig,\n                time=time\n        )\n        altazcoords = toAltaz(\n            skycoord=coords,\n            time=time\n        )  \n        arrfac = self.array_factor(\n            phase_center=phase_center,\n            coords=altazcoords,\n            antpos=ma_pos[np.isin(ma_info['ma'], self.ma)]\n        )\n        # Arrayfactor * summed MA response\n        digigain = arrfac * summa\n        log.info(\n            'Digibeam computed for {} pixels.'.format(\n                digigain.size\n            )\n        )\n        return digigain\n# ============================================================= #\n\n", "meta": {"hexsha": "6139d9eeb16c5a9ce4925e27b9db9907e74cd290", "size": 15725, "ext": "py", "lang": "Python", "max_stars_repo_path": "nenupy/beam/beam.py", "max_stars_repo_name": "coutouly/nenupy", "max_stars_repo_head_hexsha": "76cf9f6a6a93e9eed16f8450e3cfe385440a212e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nenupy/beam/beam.py", "max_issues_repo_name": "coutouly/nenupy", "max_issues_repo_head_hexsha": "76cf9f6a6a93e9eed16f8450e3cfe385440a212e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nenupy/beam/beam.py", "max_forks_repo_name": "coutouly/nenupy", "max_forks_repo_head_hexsha": "76cf9f6a6a93e9eed16f8450e3cfe385440a212e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7826855124, "max_line_length": 83, "alphanum_fraction": 0.4207949126, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 3370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.3007455914759599, "lm_q1q2_score": 0.1702275747505782}}
{"text": "#   Copyright 2020 The PyMC Developers\n#\n#   Licensed under the Apache License, Version 2.0 (the \"License\");\n#   you may not use this file except in compliance with the License.\n#   You may obtain a copy of the License at\n#\n#       http://www.apache.org/licenses/LICENSE-2.0\n#\n#   Unless required by applicable law or agreed to in writing, software\n#   distributed under the License is distributed on an \"AS IS\" BASIS,\n#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#   See the License for the specific language governing permissions and\n#   limitations under the License.\nimport warnings\n\nfrom typing import (\n    Callable,\n    Dict,\n    Generator,\n    Iterable,\n    List,\n    Optional,\n    Set,\n    Tuple,\n    Union,\n)\n\nimport aesara\nimport aesara.tensor as at\nimport numpy as np\nimport scipy.sparse as sps\n\nfrom aeppl.logprob import CheckParameterValue\nfrom aesara import config, scalar\nfrom aesara.compile.mode import Mode, get_mode\nfrom aesara.gradient import grad\nfrom aesara.graph import local_optimizer\nfrom aesara.graph.basic import (\n    Apply,\n    Constant,\n    Variable,\n    clone_get_equiv,\n    graph_inputs,\n    walk,\n)\nfrom aesara.graph.fg import FunctionGraph\nfrom aesara.graph.op import Op, compute_test_value\nfrom aesara.sandbox.rng_mrg import MRG_RandomStream as RandomStream\nfrom aesara.tensor.elemwise import Elemwise\nfrom aesara.tensor.random.op import RandomVariable\nfrom aesara.tensor.shape import SpecifyShape\nfrom aesara.tensor.sharedvar import SharedVariable\nfrom aesara.tensor.subtensor import AdvancedIncSubtensor, AdvancedIncSubtensor1\nfrom aesara.tensor.var import TensorConstant, TensorVariable\n\nfrom pymc.exceptions import ShapeError\nfrom pymc.vartypes import continuous_types, int_types, isgenerator, typefilter\n\nPotentialShapeType = Union[\n    int, np.ndarray, Tuple[Union[int, Variable], ...], List[Union[int, Variable]], Variable\n]\n\n\n__all__ = [\n    \"gradient\",\n    \"hessian\",\n    \"hessian_diag\",\n    \"inputvars\",\n    \"cont_inputs\",\n    \"floatX\",\n    \"intX\",\n    \"smartfloatX\",\n    \"jacobian\",\n    \"CallableTensor\",\n    \"join_nonshared_inputs\",\n    \"make_shared_replacements\",\n    \"generator\",\n    \"set_at_rng\",\n    \"at_rng\",\n    \"take_along_axis\",\n    \"pandas_to_array\",\n]\n\n\ndef pandas_to_array(data):\n    \"\"\"Convert a pandas object to a NumPy array.\n\n    XXX: When `data` is a generator, this will return an Aesara tensor!\n\n    \"\"\"\n    if hasattr(data, \"to_numpy\") and hasattr(data, \"isnull\"):\n        # typically, but not limited to pandas objects\n        vals = data.to_numpy()\n        null_data = data.isnull()\n        if hasattr(null_data, \"to_numpy\"):\n            # pandas Series\n            mask = null_data.to_numpy()\n        else:\n            # pandas Index\n            mask = null_data\n        if mask.any():\n            # there are missing values\n            ret = np.ma.MaskedArray(vals, mask)\n        else:\n            ret = vals\n    elif isinstance(data, np.ndarray):\n        if isinstance(data, np.ma.MaskedArray):\n            if not data.mask.any():\n                # empty mask\n                ret = data.filled()\n            else:\n                # already masked and rightly so\n                ret = data\n        else:\n            # already a ndarray, but not masked\n            mask = np.isnan(data)\n            if np.any(mask):\n                ret = np.ma.MaskedArray(data, mask)\n            else:\n                # no masking required\n                ret = data\n    elif isinstance(data, Variable):\n        ret = data\n    elif sps.issparse(data):\n        ret = data\n    elif isgenerator(data):\n        ret = generator(data)\n    else:\n        ret = np.asarray(data)\n\n    # type handling to enable index variables when data is int:\n    if hasattr(data, \"dtype\"):\n        if \"int\" in str(data.dtype):\n            return intX(ret)\n        # otherwise, assume float:\n        else:\n            return floatX(ret)\n    # needed for uses of this function other than with pm.Data:\n    else:\n        return floatX(ret)\n\n\ndef change_rv_size(\n    rv_var: TensorVariable,\n    new_size: PotentialShapeType,\n    expand: Optional[bool] = False,\n) -> TensorVariable:\n    \"\"\"Change or expand the size of a `RandomVariable`.\n\n    Parameters\n    ==========\n    rv_var\n        The `RandomVariable` output.\n    new_size\n        The new size.\n    expand:\n        Expand the existing size by `new_size`.\n\n    \"\"\"\n    # Check the dimensionality of the `new_size` kwarg\n    new_size_ndim = np.ndim(new_size)\n    if new_size_ndim > 1:\n        raise ShapeError(\"The `new_size` must be ≤1-dimensional.\", actual=new_size_ndim)\n    elif new_size_ndim == 0:\n        new_size = (new_size,)\n\n    # Extract the RV node that is to be resized, together with its inputs, name and tag\n    if isinstance(rv_var.owner.op, SpecifyShape):\n        rv_var = rv_var.owner.inputs[0]\n    rv_node = rv_var.owner\n    rng, size, dtype, *dist_params = rv_node.inputs\n    name = rv_var.name\n    tag = rv_var.tag\n\n    if expand:\n        if rv_node.op.ndim_supp == 0 and at.get_vector_length(size) == 0:\n            size = rv_node.op._infer_shape(size, dist_params)\n        new_size = tuple(new_size) + tuple(size)\n\n    # Make sure the new size is a tensor. This dtype-aware conversion helps\n    # to not unnecessarily pick up a `Cast` in some cases (see #4652).\n    new_size = at.as_tensor(new_size, ndim=1, dtype=\"int64\")\n\n    new_rv_node = rv_node.op.make_node(rng, new_size, dtype, *dist_params)\n    rv_var = new_rv_node.outputs[-1]\n    rv_var.name = name\n    for k, v in tag.__dict__.items():\n        rv_var.tag.__dict__.setdefault(k, v)\n\n    if config.compute_test_value != \"off\":\n        compute_test_value(new_rv_node)\n\n    return rv_var\n\n\ndef extract_rv_and_value_vars(\n    var: TensorVariable,\n) -> Tuple[TensorVariable, TensorVariable]:\n    \"\"\"Return a random variable and it's observations or value variable, or ``None``.\n\n    Parameters\n    ==========\n    var\n        A variable corresponding to a ``RandomVariable``.\n\n    Returns\n    =======\n    The first value in the tuple is the ``RandomVariable``, and the second is the\n    measure/log-likelihood value variable that corresponds with the latter.\n\n    \"\"\"\n    if not var.owner:\n        return None, None\n\n    if isinstance(var.owner.op, RandomVariable):\n        rv_value = getattr(var.tag, \"observations\", getattr(var.tag, \"value_var\", None))\n        return var, rv_value\n\n    return None, None\n\n\ndef extract_obs_data(x: TensorVariable) -> np.ndarray:\n    \"\"\"Extract data from observed symbolic variables.\n\n    Raises\n    ------\n    TypeError\n\n    \"\"\"\n    if isinstance(x, Constant):\n        return x.data\n    if isinstance(x, SharedVariable):\n        return x.get_value()\n    if x.owner and isinstance(x.owner.op, (AdvancedIncSubtensor, AdvancedIncSubtensor1)):\n        array_data = extract_obs_data(x.owner.inputs[0])\n        mask_idx = tuple(extract_obs_data(i) for i in x.owner.inputs[2:])\n        mask = np.zeros_like(array_data)\n        mask[mask_idx] = 1\n        return np.ma.MaskedArray(array_data, mask)\n\n    raise TypeError(f\"Data cannot be extracted from {x}\")\n\n\ndef walk_model(\n    graphs: Iterable[TensorVariable],\n    walk_past_rvs: bool = False,\n    stop_at_vars: Optional[Set[TensorVariable]] = None,\n    expand_fn: Callable[[TensorVariable], Iterable[TensorVariable]] = lambda var: [],\n) -> Generator[TensorVariable, None, None]:\n    \"\"\"Walk model graphs and yield their nodes.\n\n    By default, these walks will not go past ``RandomVariable`` nodes.\n\n    Parameters\n    ==========\n    graphs\n        The graphs to walk.\n    walk_past_rvs\n        If ``True``, the walk will not terminate at ``RandomVariable``s.\n    stop_at_vars\n        A list of variables at which the walk will terminate.\n    expand_fn\n        A function that returns the next variable(s) to be traversed.\n    \"\"\"\n    if stop_at_vars is None:\n        stop_at_vars = set()\n\n    def expand(var):\n        new_vars = expand_fn(var)\n\n        if (\n            var.owner\n            and (walk_past_rvs or not isinstance(var.owner.op, RandomVariable))\n            and (var not in stop_at_vars)\n        ):\n            new_vars.extend(reversed(var.owner.inputs))\n\n        return new_vars\n\n    yield from walk(graphs, expand, False)\n\n\ndef replace_rvs_in_graphs(\n    graphs: Iterable[TensorVariable],\n    replacement_fn: Callable[[TensorVariable], Dict[TensorVariable, TensorVariable]],\n    initial_replacements: Optional[Dict[TensorVariable, TensorVariable]] = None,\n    **kwargs,\n) -> Tuple[TensorVariable, Dict[TensorVariable, TensorVariable]]:\n    \"\"\"Replace random variables in graphs\n\n    This will *not* recompute test values.\n\n    Parameters\n    ==========\n    graphs\n        The graphs in which random variables are to be replaced.\n\n    Returns\n    =======\n    Tuple containing the transformed graphs and a ``dict`` of the replacements\n    that were made.\n    \"\"\"\n    replacements = {}\n    if initial_replacements:\n        replacements.update(initial_replacements)\n\n    def expand_replace(var):\n        new_nodes = []\n        if var.owner and isinstance(var.owner.op, RandomVariable):\n            new_nodes.extend(replacement_fn(var, replacements))\n        return new_nodes\n\n    for var in walk_model(graphs, expand_fn=expand_replace, **kwargs):\n        pass\n\n    if replacements:\n        inputs = [i for i in graph_inputs(graphs) if not isinstance(i, Constant)]\n        equiv = {k: k for k in replacements.keys()}\n        equiv = clone_get_equiv(inputs, graphs, False, False, equiv)\n\n        fg = FunctionGraph(\n            [equiv[i] for i in inputs],\n            [equiv[o] for o in graphs],\n            clone=False,\n        )\n\n        fg.replace_all(replacements.items(), import_missing=True)\n\n        graphs = list(fg.outputs)\n\n    return graphs, replacements\n\n\ndef rvs_to_value_vars(\n    graphs: Iterable[TensorVariable],\n    apply_transforms: bool = False,\n    initial_replacements: Optional[Dict[TensorVariable, TensorVariable]] = None,\n    **kwargs,\n) -> Tuple[TensorVariable, Dict[TensorVariable, TensorVariable]]:\n    \"\"\"Clone and replace random variables in graphs with their value variables.\n\n    This will *not* recompute test values in the resulting graphs.\n\n    Parameters\n    ==========\n    graphs\n        The graphs in which to perform the replacements.\n    apply_transforms\n        If ``True``, apply each value variable's transform.\n    initial_replacements\n        A ``dict`` containing the initial replacements to be made.\n\n    \"\"\"\n\n    # Avoid circular dependency\n    from pymc.distributions import NoDistribution\n\n    def transform_replacements(var, replacements):\n        rv_var, rv_value_var = extract_rv_and_value_vars(var)\n\n        if rv_value_var is None:\n            # If RandomVariable does not have a value_var and corresponds to\n            # a NoDistribution, we allow further replacements in upstream graph\n            if isinstance(rv_var.owner.op, NoDistribution):\n                return rv_var.owner.inputs\n\n            else:\n                warnings.warn(\n                    f\"No value variable found for {rv_var}; \"\n                    \"the random variable will not be replaced.\"\n                )\n                return []\n\n        transform = getattr(rv_value_var.tag, \"transform\", None)\n\n        if transform is None or not apply_transforms:\n            replacements[var] = rv_value_var\n            # In case the value variable is itself a graph, we walk it for\n            # potential replacements\n            return [rv_value_var]\n\n        trans_rv_value = transform.backward(rv_value_var, *rv_var.owner.inputs)\n        replacements[var] = trans_rv_value\n\n        # Walk the transformed variable and make replacements\n        return [trans_rv_value]\n\n    # Clone original graphs\n    inputs = [i for i in graph_inputs(graphs) if not isinstance(i, Constant)]\n    equiv = clone_get_equiv(inputs, graphs, False, False, {})\n    graphs = [equiv[n] for n in graphs]\n\n    if initial_replacements:\n        initial_replacements = {\n            equiv.get(k, k): equiv.get(v, v) for k, v in initial_replacements.items()\n        }\n\n    return replace_rvs_in_graphs(graphs, transform_replacements, initial_replacements, **kwargs)\n\n\ndef inputvars(a):\n    \"\"\"\n    Get the inputs into Aesara variables\n\n    Parameters\n    ----------\n        a: Aesara variable\n\n    Returns\n    -------\n        r: list of tensor variables that are inputs\n    \"\"\"\n    return [\n        v\n        for v in graph_inputs(makeiter(a))\n        if isinstance(v, TensorVariable) and not isinstance(v, TensorConstant)\n    ]\n\n\ndef cont_inputs(a):\n    \"\"\"\n    Get the continuous inputs into Aesara variables\n\n    Parameters\n    ----------\n        a: Aesara variable\n\n    Returns\n    -------\n        r: list of tensor variables that are continuous inputs\n    \"\"\"\n    return typefilter(inputvars(a), continuous_types)\n\n\ndef floatX(X):\n    \"\"\"\n    Convert an Aesara tensor or numpy array to aesara.config.floatX type.\n    \"\"\"\n    try:\n        return X.astype(aesara.config.floatX)\n    except AttributeError:\n        # Scalar passed\n        return np.asarray(X, dtype=aesara.config.floatX)\n\n\n_conversion_map = {\"float64\": \"int32\", \"float32\": \"int16\", \"float16\": \"int8\", \"float8\": \"int8\"}\n\n\ndef intX(X):\n    \"\"\"\n    Convert a aesara tensor or numpy array to aesara.tensor.int32 type.\n    \"\"\"\n    intX = _conversion_map[aesara.config.floatX]\n    try:\n        return X.astype(intX)\n    except AttributeError:\n        # Scalar passed\n        return np.asarray(X, dtype=intX)\n\n\ndef smartfloatX(x):\n    \"\"\"\n    Converts numpy float values to floatX and leaves values of other types unchanged.\n    \"\"\"\n    if str(x.dtype).startswith(\"float\"):\n        x = floatX(x)\n    return x\n\n\n\"\"\"\nAesara derivative functions\n\"\"\"\n\n\ndef gradient1(f, v):\n    \"\"\"flat gradient of f wrt v\"\"\"\n    return at.flatten(grad(f, v, disconnected_inputs=\"warn\"))\n\n\nempty_gradient = at.zeros(0, dtype=\"float32\")\n\n\ndef gradient(f, vars=None):\n    if vars is None:\n        vars = cont_inputs(f)\n\n    if vars:\n        return at.concatenate([gradient1(f, v) for v in vars], axis=0)\n    else:\n        return empty_gradient\n\n\ndef jacobian1(f, v):\n    \"\"\"jacobian of f wrt v\"\"\"\n    f = at.flatten(f)\n    idx = at.arange(f.shape[0], dtype=\"int32\")\n\n    def grad_i(i):\n        return gradient1(f[i], v)\n\n    return aesara.map(grad_i, idx)[0]\n\n\ndef jacobian(f, vars=None):\n    if vars is None:\n        vars = cont_inputs(f)\n\n    if vars:\n        return at.concatenate([jacobian1(f, v) for v in vars], axis=1)\n    else:\n        return empty_gradient\n\n\ndef jacobian_diag(f, x):\n    idx = at.arange(f.shape[0], dtype=\"int32\")\n\n    def grad_ii(i, f, x):\n        return grad(f[i], x)[i]\n\n    return aesara.scan(\n        grad_ii, sequences=[idx], n_steps=f.shape[0], non_sequences=[f, x], name=\"jacobian_diag\"\n    )[0]\n\n\n@aesara.config.change_flags(compute_test_value=\"ignore\")\ndef hessian(f, vars=None):\n    return -jacobian(gradient(f, vars), vars)\n\n\n@aesara.config.change_flags(compute_test_value=\"ignore\")\ndef hessian_diag1(f, v):\n    g = gradient1(f, v)\n    idx = at.arange(g.shape[0], dtype=\"int32\")\n\n    def hess_ii(i):\n        return gradient1(g[i], v)[i]\n\n    return aesara.map(hess_ii, idx)[0]\n\n\n@aesara.config.change_flags(compute_test_value=\"ignore\")\ndef hessian_diag(f, vars=None):\n    if vars is None:\n        vars = cont_inputs(f)\n\n    if vars:\n        return -at.concatenate([hessian_diag1(f, v) for v in vars], axis=0)\n    else:\n        return empty_gradient\n\n\ndef makeiter(a):\n    if isinstance(a, (tuple, list)):\n        return a\n    else:\n        return [a]\n\n\nclass IdentityOp(scalar.UnaryScalarOp):\n    @staticmethod\n    def st_impl(x):\n        return x\n\n    def impl(self, x):\n        return x\n\n    def grad(self, inp, grads):\n        return grads\n\n    def c_code(self, node, name, inp, out, sub):\n        return f\"{out[0]} = {inp[0]};\"\n\n    def __eq__(self, other):\n        return isinstance(self, type(other))\n\n    def __hash__(self):\n        return hash(type(self))\n\n\ndef make_shared_replacements(point, vars, model):\n    \"\"\"\n    Makes shared replacements for all *other* variables than the ones passed.\n\n    This way functions can be called many times without setting unchanging variables. Allows us\n    to use func.trust_input by removing the need for DictToArrayBijection and kwargs.\n\n    Parameters\n    ----------\n    point: dictionary mapping variable names to sample values\n    vars: list of variables not to make shared\n    model: model\n\n    Returns\n    -------\n    Dict of variable -> new shared variable\n    \"\"\"\n    othervars = set(model.value_vars) - set(vars)\n    return {\n        var: aesara.shared(point[var.name], var.name + \"_shared\", broadcastable=var.broadcastable)\n        for var in othervars\n    }\n\n\ndef join_nonshared_inputs(\n    point: Dict[str, np.ndarray],\n    xs: List[TensorVariable],\n    vars: List[TensorVariable],\n    shared,\n    make_shared: bool = False,\n):\n    \"\"\"\n    Takes a list of Aesara Variables and joins their non shared inputs into a single input.\n\n    Parameters\n    ----------\n    point: a sample point\n    xs: list of Aesara tensors\n    vars: list of variables to join\n\n    Returns\n    -------\n    tensors, inarray\n    tensors: list of same tensors but with inarray as input\n    inarray: vector of inputs\n    \"\"\"\n    if not vars:\n        raise ValueError(\"Empty list of variables.\")\n\n    joined = at.concatenate([var.ravel() for var in vars])\n\n    if not make_shared:\n        tensor_type = joined.type\n        inarray = tensor_type(\"inarray\")\n    else:\n        if point is None:\n            raise ValueError(\"A point is required when `make_shared` is True\")\n        joined_values = np.concatenate([point[var.name].ravel() for var in vars])\n        inarray = aesara.shared(joined_values, \"inarray\")\n\n    if aesara.config.compute_test_value != \"off\":\n        inarray.tag.test_value = joined.tag.test_value\n\n    replace = {}\n    last_idx = 0\n    for var in vars:\n        shape = point[var.name].shape\n        arr_len = np.prod(shape, dtype=int)\n        replace[var] = reshape_t(inarray[last_idx : last_idx + arr_len], shape).astype(var.dtype)\n        last_idx += arr_len\n\n    replace.update(shared)\n\n    xs_special = [aesara.clone_replace(x, replace, strict=False) for x in xs]\n    return xs_special, inarray\n\n\ndef reshape_t(x, shape):\n    \"\"\"Work around fact that x.reshape(()) doesn't work\"\"\"\n    if shape != ():\n        return x.reshape(shape)\n    else:\n        return x[0]\n\n\nclass CallableTensor:\n    \"\"\"Turns a symbolic variable with one input into a function that returns symbolic arguments\n    with the one variable replaced with the input.\n    \"\"\"\n\n    def __init__(self, tensor):\n        self.tensor = tensor\n\n    def __call__(self, input):\n        \"\"\"Replaces the single input of symbolic variable to be the passed argument.\n\n        Parameters\n        ----------\n        input: TensorVariable\n        \"\"\"\n        (oldinput,) = inputvars(self.tensor)\n        return aesara.clone_replace(self.tensor, {oldinput: input}, strict=False)\n\n\nscalar_identity = IdentityOp(scalar.upgrade_to_float, name=\"scalar_identity\")\nidentity = Elemwise(scalar_identity, name=\"identity\")\n\n\nclass GeneratorOp(Op):\n    \"\"\"\n    Generator Op is designed for storing python generators inside aesara graph.\n\n    __call__ creates TensorVariable\n        It has 2 new methods\n        - var.set_gen(gen): sets new generator\n        - var.set_default(value): sets new default value (None erases default value)\n\n    If generator is exhausted, variable will produce default value if it is not None,\n    else raises `StopIteration` exception that can be caught on runtime.\n\n    Parameters\n    ----------\n    gen: generator that implements __next__ (py3) or next (py2) method\n        and yields np.arrays with same types\n    default: np.array with the same type as generator produces\n    \"\"\"\n\n    __props__ = (\"generator\",)\n\n    def __init__(self, gen, default=None):\n        from pymc.data import GeneratorAdapter\n\n        super().__init__()\n        if not isinstance(gen, GeneratorAdapter):\n            gen = GeneratorAdapter(gen)\n        self.generator = gen\n        self.set_default(default)\n\n    def make_node(self, *inputs):\n        gen_var = self.generator.make_variable(self)\n        return Apply(self, [], [gen_var])\n\n    def perform(self, node, inputs, output_storage, params=None):\n        if self.default is not None:\n            output_storage[0][0] = next(self.generator, self.default)\n        else:\n            output_storage[0][0] = next(self.generator)\n\n    def do_constant_folding(self, fgraph, node):\n        return False\n\n    __call__ = aesara.config.change_flags(compute_test_value=\"off\")(Op.__call__)\n\n    def set_gen(self, gen):\n        from pymc.data import GeneratorAdapter\n\n        if not isinstance(gen, GeneratorAdapter):\n            gen = GeneratorAdapter(gen)\n        if not gen.tensortype == self.generator.tensortype:\n            raise ValueError(\"New generator should yield the same type\")\n        self.generator = gen\n\n    def set_default(self, value):\n        if value is None:\n            self.default = None\n        else:\n            value = np.asarray(value, self.generator.tensortype.dtype)\n            t1 = (False,) * value.ndim\n            t2 = self.generator.tensortype.broadcastable\n            if not t1 == t2:\n                raise ValueError(\"Default value should have the same type as generator\")\n            self.default = value\n\n\ndef generator(gen, default=None):\n    \"\"\"\n    Generator variable with possibility to set default value and new generator.\n    If generator is exhausted variable will produce default value if it is not None,\n    else raises `StopIteration` exception that can be caught on runtime.\n\n    Parameters\n    ----------\n    gen: generator that implements __next__ (py3) or next (py2) method\n        and yields np.arrays with same types\n    default: np.array with the same type as generator produces\n\n    Returns\n    -------\n    TensorVariable\n        It has 2 new methods\n        - var.set_gen(gen): sets new generator\n        - var.set_default(value): sets new default value (None erases default value)\n    \"\"\"\n    return GeneratorOp(gen, default)()\n\n\n_at_rng = RandomStream()\n\n\ndef at_rng(random_seed=None):\n    \"\"\"\n    Get the package-level random number generator or new with specified seed.\n\n    Parameters\n    ----------\n    random_seed: int\n        If not None\n        returns *new* aesara random generator without replacing package global one\n\n    Returns\n    -------\n    `aesara.tensor.random.utils.RandomStream` instance\n        `aesara.tensor.random.utils.RandomStream`\n        instance passed to the most recent call of `set_at_rng`\n    \"\"\"\n    if random_seed is None:\n        return _at_rng\n    else:\n        ret = RandomStream(random_seed)\n        return ret\n\n\ndef set_at_rng(new_rng):\n    \"\"\"\n    Set the package-level random number generator.\n\n    Parameters\n    ----------\n    new_rng: `aesara.tensor.random.utils.RandomStream` instance\n        The random number generator to use.\n    \"\"\"\n    # pylint: disable=global-statement\n    global _at_rng\n    # pylint: enable=global-statement\n    if isinstance(new_rng, int):\n        new_rng = RandomStream(new_rng)\n    _at_rng = new_rng\n\n\ndef floatX_array(x):\n    return floatX(np.array(x))\n\n\ndef ix_(*args):\n    \"\"\"\n    Aesara np.ix_ analog\n\n    See numpy.lib.index_tricks.ix_ for reference\n    \"\"\"\n    out = []\n    nd = len(args)\n    for k, new in enumerate(args):\n        if new is None:\n            out.append(slice(None))\n        new = at.as_tensor(new)\n        if new.ndim != 1:\n            raise ValueError(\"Cross index must be 1 dimensional\")\n        new = new.reshape((1,) * k + (new.size,) + (1,) * (nd - k - 1))\n        out.append(new)\n    return tuple(out)\n\n\ndef largest_common_dtype(tensors):\n    dtypes = {\n        str(t.dtype) if hasattr(t, \"dtype\") else smartfloatX(np.asarray(t)).dtype for t in tensors\n    }\n    return np.stack([np.ones((), dtype=dtype) for dtype in dtypes]).dtype\n\n\ndef _make_along_axis_idx(arr_shape, indices, axis):\n    # compute dimensions to iterate over\n    if str(indices.dtype) not in int_types:\n        raise IndexError(\"`indices` must be an integer array\")\n    shape_ones = (1,) * indices.ndim\n    dest_dims = list(range(axis)) + [None] + list(range(axis + 1, indices.ndim))\n\n    # build a fancy index, consisting of orthogonal aranges, with the\n    # requested index inserted at the right location\n    fancy_index = []\n    for dim, n in zip(dest_dims, arr_shape):\n        if dim is None:\n            fancy_index.append(indices)\n        else:\n            ind_shape = shape_ones[:dim] + (-1,) + shape_ones[dim + 1 :]\n            fancy_index.append(at.arange(n).reshape(ind_shape))\n\n    return tuple(fancy_index)\n\n\ndef take_along_axis(arr, indices, axis=0):\n    \"\"\"Take values from the input array by matching 1d index and data slices.\n\n    This iterates over matching 1d slices oriented along the specified axis in\n    the index and data arrays, and uses the former to look up values in the\n    latter. These slices can be different lengths.\n\n    Functions returning an index along an axis, like argsort and argpartition,\n    produce suitable indices for this function.\n    \"\"\"\n    arr = at.as_tensor_variable(arr)\n    indices = at.as_tensor_variable(indices)\n    # normalize inputs\n    if axis is None:\n        arr = arr.flatten()\n        arr_shape = (len(arr),)  # flatiter has no .shape\n        _axis = 0\n    else:\n        if axis < 0:\n            _axis = arr.ndim + axis\n        else:\n            _axis = axis\n        if _axis < 0 or _axis >= arr.ndim:\n            raise ValueError(\n                \"Supplied `axis` value {} is out of bounds of an array with \"\n                \"ndim = {}\".format(axis, arr.ndim)\n            )\n        arr_shape = arr.shape\n    if arr.ndim != indices.ndim:\n        raise ValueError(\"`indices` and `arr` must have the same number of dimensions\")\n\n    # use the fancy index\n    return arr[_make_along_axis_idx(arr_shape, indices, _axis)]\n\n\n@local_optimizer(tracks=[CheckParameterValue])\ndef local_remove_check_parameter(fgraph, node):\n    \"\"\"Rewrite that removes Aeppl's CheckParameterValue\n\n    This is used when compile_rv_inplace\n    \"\"\"\n    if isinstance(node.op, CheckParameterValue):\n        return [node.inputs[0]]\n\n\n@local_optimizer(tracks=[CheckParameterValue])\ndef local_check_parameter_to_ninf_switch(fgraph, node):\n    if isinstance(node.op, CheckParameterValue):\n        logp_expr, *logp_conds = node.inputs\n        if len(logp_conds) > 1:\n            logp_cond = at.all(logp_conds)\n        else:\n            (logp_cond,) = logp_conds\n        out = at.switch(logp_cond, logp_expr, -np.inf)\n        out.name = node.op.msg\n\n        if out.dtype != node.outputs[0].dtype:\n            out = at.cast(out, node.outputs[0].dtype)\n\n        return [out]\n\n\naesara.compile.optdb[\"canonicalize\"].register(\n    \"local_remove_check_parameter\",\n    local_remove_check_parameter,\n    use_db_name_as_tag=False,\n)\n\naesara.compile.optdb[\"canonicalize\"].register(\n    \"local_check_parameter_to_ninf_switch\",\n    local_check_parameter_to_ninf_switch,\n    use_db_name_as_tag=False,\n)\n\n\ndef compile_pymc(inputs, outputs, mode=None, **kwargs):\n    \"\"\"Use ``aesara.function`` with specialized pymc rewrites always enabled.\n\n    Included rewrites\n    -----------------\n    random_make_inplace\n        Ensures that compiled functions containing random variables will produce new\n        samples on each call.\n    local_check_parameter_to_ninf_switch\n        Replaces Aeppl's CheckParameterValue assertions is logp expressions with Switches\n        that return -inf in place of the assert.\n\n    Optional rewrites\n    -----------------\n    local_remove_check_parameter\n        Replaces Aeppl's CheckParameterValue assertions is logp expressions. This is used\n        as an alteranative to the default local_check_parameter_to_ninf_switch whenenver\n        this function is called within a model context and the model `check_bounds` flag\n        is set to False.\n    \"\"\"\n\n    # Avoid circular dependency\n    from pymc.distributions import NoDistribution\n\n    # Set the default update of a NoDistribution RNG so that it is automatically\n    # updated after every function call\n    output_to_list = outputs if isinstance(outputs, (list, tuple)) else [outputs]\n    for rv in (\n        node\n        for node in walk_model(output_to_list, walk_past_rvs=True)\n        if node.owner and isinstance(node.owner.op, NoDistribution)\n    ):\n        rng = rv.owner.inputs[0]\n        if not hasattr(rng, \"default_update\"):\n            rng.default_update = rv.owner.outputs[0]\n\n    # If called inside a model context, see if check_bounds flag is set to False\n    try:\n        from pymc.model import modelcontext\n\n        model = modelcontext(None)\n        check_bounds = model.check_bounds\n    except TypeError:\n        check_bounds = True\n    check_parameter_opt = (\n        \"local_check_parameter_to_ninf_switch\" if check_bounds else \"local_remove_check_parameter\"\n    )\n\n    mode = get_mode(mode)\n    opt_qry = mode.provided_optimizer.including(\"random_make_inplace\", check_parameter_opt)\n    mode = Mode(linker=mode.linker, optimizer=opt_qry)\n    aesara_function = aesara.function(inputs, outputs, mode=mode, **kwargs)\n    return aesara_function\n", "meta": {"hexsha": "7c3d9350c867b55354338bf2b14ab540f19e0054", "size": 29191, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymc/aesaraf.py", "max_stars_repo_name": "austereantelope/pymc", "max_stars_repo_head_hexsha": "657eb2a7e46fa30e61d3c1b12a8ce15020794a2c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-02T07:40:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T07:40:25.000Z", "max_issues_repo_path": "pymc/aesaraf.py", "max_issues_repo_name": "austereantelope/pymc", "max_issues_repo_head_hexsha": "657eb2a7e46fa30e61d3c1b12a8ce15020794a2c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pymc/aesaraf.py", "max_forks_repo_name": "austereantelope/pymc", "max_forks_repo_head_hexsha": "657eb2a7e46fa30e61d3c1b12a8ce15020794a2c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2788365095, "max_line_length": 98, "alphanum_fraction": 0.648864376, "include": true, "reason": "import numpy,import scipy", "num_tokens": 6777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.16990848793091776}}
{"text": "import os\nimport shutil\n\nfrom joblib import Parallel, delayed\nimport multiprocessing\n\nfrom cached_property import cached_property\n\nimport datetime\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom bilby.core.prior import (Constraint, DeltaFunction,\n                              Interped, Prior)\nfrom bilby.gw.prior import (CBCPriorDict,\n                            convert_to_lal_binary_black_hole_parameters,\n                            fill_from_fixed_priors, generate_mass_parameters)\nfrom tqdm.auto import tqdm\n\nfrom deep_gw_pe_followup.sample_cacher.cacher import load_probabilities, store_probabilities\nfrom .conversions import calc_a2\nfrom .placeholder_prior import PlaceholderDelta\nfrom .prob_calculators import (get_p_cos2_given_xeff_q_a1_cos1, get_p_a1_given_xeff_q, get_p_cos1_given_xeff_q_a1)\n\nfrom deep_gw_pe_followup.plotting.hist2d import plot_heatmap\n\nimport logging\nfrom bilby.core.utils import logger\n\nlogger.setLevel(logging.INFO)\n\nnum_cores = multiprocessing.cpu_count()\n\nD = dict(a1=0.01, cos1=0.01, cos2=0.01)\nX = dict(\n    a1=np.linspace(0, 1, int(1. / D['a1'])),\n    cos1=np.linspace(-1, 1, int(2. / D['cos1'])),\n    cos2=np.linspace(-1, 1, int(2. / D['cos2']))\n)\nMCMC_N = int(5e4)\n\n\ndef find_nearest(array, value):\n    array = np.asarray(array)\n    idx = (np.abs(array - value)).argmin()\n    return array[idx]\n\n\ndef find_boundary_idx(x):\n    \"\"\"finds idx where data is non zero (assumes that there wont be gaps)\"\"\"\n    non_z = np.nonzero(x)[0]\n    return non_z[0], non_z[-1]\n\n\ndef find_boundary(x, y):\n    b1, b2 = find_boundary_idx(y)\n    vals = [x[b1], x[b2]]\n    start, end = min(vals), max(vals)\n    return start, end\n\n\nclass RestrictedPrior(CBCPriorDict):\n    def __init__(self, dictionary=None, filename=None, clean=False, build_cache=True, mcmc_n=MCMC_N, cache=None):\n        \"\"\"cache -- a dir with the cached prob files\"\"\"\n        super().__init__(dictionary=dictionary, filename=filename, conversion_function=None)\n        self.q = (self['q'] if 'q' in self else self['mass_ratio']).peak\n        self.xeff = (self['xeff'] if 'xeff' in self else self['chi_eff']).peak\n        self.mcmc_n = mcmc_n\n        self.filename = filename\n        if clean:\n            shutil.rmtree(self.cache)\n        self.cache = cache\n\n        self.search_params = self.get_search_params()\n        self.ndim = len(self.search_params)\n\n        # build cache\n        if build_cache:\n            self['a_1'] = self.get_a1_prior()\n            self['cos_tilt_1'] = self.get_cos1_prior(given_a1=0.5)\n            self['cos_tilt_2'] = self.get_cos2_prior(given_a1=0.5, given_cos1=0.5)\n\n        # we have forced the normalize_constraint_factor = 1\n        # if we need to deal with constraints in post-processing\n        self.constraint_prior_check()\n\n    @property\n    def cache(self):\n        return self._cache\n\n    @cache.setter\n    def cache(self, c):\n        if c is None:\n            prior_dirname = \"\"\n            # if self.filename and os.path.isfile(self.filename):\n            #     prior_dirname = os.path.dirname(self.filename)\n            c = os.path.join(\n                prior_dirname,\n                f\"cache_q{self.q}-xeff{self.xeff}\".replace(\".\", \"_\")\n            )\n        if os.path.isdir(c):\n            logger.debug(f\"Loading RestricedPrior from cache {c}\")\n            self._cache = c\n        else:\n            logger.debug(f\"Building RestricedPrior cache {c}\")\n            self._cache = c\n            os.makedirs(self._cache, exist_ok=True)\n        self._cache = os.path.abspath(self._cache)\n\n    @property\n    def restricted_params(self):\n        return ['a_1', 'cos_tilt_1', 'cos_tilt_2', 'a_2']\n\n    def constraint_prior_check(self):\n        constraint_present = False\n        for p,v in self.items():\n            if isinstance(v, Constraint):\n                constraint_present = True\n        if constraint_present:\n            logger.warning(\n                \"bilby prior contraints are present but `normalize_constraint_factor` is set to 1.\"\n                \"The user will need to compute the constraint factor in post-processing.\"\n            )\n\n    def get_a1_prior(self):\n        fname = os.path.join(self.cache, \"a1_given_qxeff.h5\")\n        if os.path.exists(fname):\n            data = load_probabilities(fname)\n            logger.debug(f\"Loaded {fname}\")\n        else:\n            logger.debug(f\"Creating {fname}\")\n            a1s = X['a1']\n            da1 = a1s[1] - a1s[0]\n            p_a1 = Parallel(n_jobs=num_cores, verbose=1)(\n                delayed(get_p_a1_given_xeff_q)(a1, self.xeff, self.q, self.mcmc_n * 100)\n                for a1 in tqdm(a1s, desc=\"Building a1 cache\"))\n\n            p_a1 = p_a1 / np.sum(p_a1) / da1\n            data = pd.DataFrame(dict(a1=a1s, p_a1=p_a1))\n            store_probabilities(data, fname)\n\n        a1 = data.a1.values\n        p_a1 = data.p_a1.values\n\n        min_b, max_b = find_boundary(a1, p_a1)\n\n        return Interped(xx=a1, yy=p_a1, minimum=min_b, maximum=max_b, name=\"a_1\", latex_label=r\"$a_1$\")\n\n    @cached_property\n    def cached_cos1_data(self):\n        fname = os.path.join(self.cache, \"cos1_given_qxeffa1.h5\")\n        if os.path.isfile(fname):\n            data = load_probabilities(fname)\n            logger.debug(f\"Loaded {fname}\")\n        else:\n            logger.debug(f\"Creating {fname}\")\n            a1s, cos1s = X['a1'], X['cos1']\n            data = dict(a1=np.array([]), cos1=np.array([]), p_cos1=np.array([]))\n            for a1 in tqdm(a1s, desc=\"Building p_cos1 cache\"):\n                p_cos1_for_a1 = Parallel(n_jobs=num_cores, verbose=1)(\n                    delayed(get_p_cos1_given_xeff_q_a1)(cos1, a1, self.xeff, self.q, self.mcmc_n) for cos1 in cos1s)\n                data['a1'] = np.append(data['a1'], np.array([a1 for _ in cos1s]))\n                data['cos1'] = np.append(data['cos1'], cos1s)\n                data['p_cos1'] = np.append(data['p_cos1'], p_cos1_for_a1)\n            data = pd.DataFrame(data)\n            store_probabilities(data, fname)\n        return data\n\n    @classmethod\n    def from_bbh_priordict(cls, dict):\n        dict = {k: v for k, v in dict.items()}\n        return cls(dictionary=dict)\n\n    def get_cos1_prior(self, given_a1, ):\n        data = self.cached_cos1_data\n        closest_a1 = find_nearest(data.a1, given_a1)\n        data = data[data.a1 == closest_a1]\n        cos1 = data.cos1.values\n        p_cos1 = data.p_cos1.values\n\n        try:\n            min_b, max_b = find_boundary(cos1, p_cos1)\n        except Exception:\n            min_b = min(cos1)\n            max_b = max(cos1)\n\n        return Interped(\n            xx=cos1, yy=p_cos1,\n            minimum=min_b, maximum=max_b, name=\"cos_tilt_1\",\n            latex_label=r\"$\\cos \\theta_1$\"\n        )\n\n    def get_cos2_prior(self, given_a1, given_cos1):\n        cos2s = X['cos2']\n        dc2 = cos2s[1] - cos2s[0]\n\n        args = (given_a1, self.xeff, self.q, given_cos1)\n        p_cos2 = np.array([get_p_cos2_given_xeff_q_a1_cos1(cos2, *args) for cos2 in cos2s])\n        p_cos2 = p_cos2 / np.sum(p_cos2) / dc2\n\n        try:\n            min_b, max_b = find_boundary(cos2s, p_cos2)\n        except Exception:\n            min_b = min(cos2s)\n            max_b = max(cos2s)\n\n        if min_b == max_b:\n            return PlaceholderDelta(peak=min_b, name=\"cos_tilt_2\", latex_label=r\"$\\cos \\theta_2$\")\n\n        return Interped(\n            xx=cos2s, yy=p_cos2,\n            minimum=min_b, maximum=max_b, name=\"cos_tilt_2\",\n            latex_label=r\"$\\cos \\theta_2$\"\n        )\n\n    def sample_restricted(self, size=1):\n        a1 = np.atleast_1d(self['a_1'].sample(size))\n        if isinstance(size, int) and size > 10:\n            cos1 = np.hstack([\n                self.get_cos1_prior(i).sample(1)\n                for i in tqdm(a1, desc=\"Getting cos1 samples\", total=size)\n            ])\n            cos2 = np.hstack([\n                self.get_cos2_prior(i, j).sample(1)\n                for i, j in tqdm(zip(a1, cos1), desc=\"Getting cos2 samples\", total=size)\n            ])\n\n        else:\n            cos1 = np.hstack([self.get_cos1_prior(given_a1=i).sample(1) for i in a1])\n            cos2 = np.hstack([\n                self.get_cos2_prior(given_a1=i, given_cos1=j).sample(1)\n                for i, j in zip(a1, cos1)\n            ])\n        return dict(\n            a_1=a1,\n            cos_tilt_1=cos1,\n            cos_tilt_2=cos2,\n        )\n\n    def update_restricted_priors(self, sample):\n        a1, c1 = sample['a_1'], sample['cos_tilt_1']\n        self['cos_tilt_1'] = self.get_cos1_prior(given_a1=a1)\n        self['cos_tilt_2'] = self.get_cos2_prior(given_a1=a1, given_cos1=c1)\n\n    def get_search_params(self):\n        \"\"\"\n        Go through the list of priors and add keys to the fixed and search\n        parameter key list depending on whether\n        the respective parameter is fixed.\n        \"\"\"\n        search_parameter = list()\n        for key in self:\n            if isinstance(self[key], Prior) \\\n                    and self[key].is_fixed is False:\n                search_parameter.append(key)\n        return search_parameter\n\n    # Overloaded functions\n\n    def default_conversion_function(self, sample):\n        if 'cos_tilt_1' in sample:\n            sample['tilt_1'] = np.arccos(sample['cos_tilt_1'])\n            sample['tilt_2'] = np.arccos(sample['cos_tilt_2'])\n        sample['a_2'] = calc_a2(xeff=self.xeff, q=self.q, cos1=sample['cos_tilt_1'], cos2=sample['cos_tilt_2'],\n                                a1=sample['a_1'])\n        out_sample = fill_from_fixed_priors(sample, self)\n        out_sample, _ = convert_to_lal_binary_black_hole_parameters(out_sample)\n        out_sample = generate_mass_parameters(out_sample)\n        return out_sample\n\n    def sample_subset(self, keys=iter([]), size=None):\n        samples = super().sample_subset(keys=keys, size=size)\n        restricted_samples = self.sample_restricted(size)\n        return {**samples, **restricted_samples}\n\n    def prob(self, sample, **kwargs):\n        self.update_restricted_priors(sample)\n        return super().prob(sample)\n\n    def ln_prob(self, sample, axis=None):\n        self.update_restricted_priors(sample)\n        self._prepare_evaluation(*zip(*sample.items()))\n        res = {key: self[key].ln_prob(sample[key], **self.get_required_variables(key)) for key in sample}\n        reslist = [v for v in res.values()]\n        ln_prob = np.sum(reslist, axis=axis)\n        return self.check_ln_prob(sample, ln_prob)\n\n    def cdf(self, sample):\n        self.update_restricted_priors(sample)\n        return super().cdf(sample)\n\n    def rescale_restricted(self, keys, theta):\n        \"\"\"theta:drawn from unit-cube\"\"\"\n        unit = {k: t for k, t in zip(keys, theta)}\n        scaled = {}\n        scaled['a_1'] = self['a_1'].rescale(unit['a_1'])\n        self['cos_tilt_1'] = self.get_cos1_prior(given_a1=scaled['a_1'])\n        scaled['cos_tilt_1'] = self['cos_tilt_1'].rescale(unit['cos_tilt_1'])\n        self['cos_tilt_2'] = self.get_cos2_prior(given_a1=scaled['a_1'], given_cos1=scaled['cos_tilt_1'])\n        scaled['cos_tilt_2'] = self['cos_tilt_2'].rescale(unit['cos_tilt_2'])\n        return scaled\n\n    def rescale(self, keys, theta):\n        \"\"\"theta:drawn from unit-cube\"\"\"\n        scaled = self.rescale_restricted(keys, theta)\n        self.update_restricted_priors(scaled)\n        return super().rescale(keys=keys, theta=theta)\n\n    def normalize_constraint_factor(self, keys, min_accept=10000, sampling_chunk=50000, nrepeats=10):\n        return 1.0\n\n    def debug_sample(self, sample, fname='debug_prior.png'):\n        self.update_restricted_priors(sample)\n        nparam = len(self)\n        fig, axes = plt.subplots(nparam, 1, figsize=(5, 2 * nparam))\n        for i, label in enumerate(self):\n            if not isinstance(self[label], DeltaFunction):\n                xx = np.linspace(start=self[label].minimum, stop=self[label].maximum, num=100)\n                yy = self[label].prob(xx)\n                axes[i].plot(xx, yy, \"C1\")\n                if label in sample:\n                    axes[i].axvline(sample[label], c=\"C2\", linestyle=\"--\")\n            else:\n                axes[i].axvline(self[label].peak, c=\"C1\")\n                axes[i].axvline(self[label].peak, c=\"C2\", linestyle=\"--\")\n            axes[i].set_xlabel(label.replace(\"_\", \" \"))\n        plt.tight_layout()\n        plt.savefig(fname)\n\n    def time_prior(self, n_evaluations=100):\n        \"\"\" Times the prior evaluation and print an info message\n\n        Parameters\n        ==========\n        n_evaluations: int\n            The number of evaluations to estimate the evaluation time from\n\n        \"\"\"\n\n        t1 = datetime.datetime.now()\n        for _ in range(n_evaluations):\n            theta = self.sample()\n        total_time = (datetime.datetime.now() - t1).total_seconds()\n        self._eval_time = total_time / n_evaluations\n\n        if self._eval_time == 0:\n            self._eval_time = np.nan\n            logger.info(\"Unable to measure single prior sample time\")\n        else:\n            logger.info(\"Single prior evaluation took {:.3e} s\".format(self._eval_time))\n\n    def plot_cache(self):\n        \"\"\" Plot of a1 and 2D plot of a1-cos1 \"\"\"\n        fig, axes = plt.subplots(2, 1, figsize=(5, 6), sharex=True)\n        axes[0].set_ylabel('p(a1)')\n        axes[1].set_ylabel('cos1')\n        axes[1].set_xlabel('a1')\n        axes[0].plot(self['a_1'].xx, self['a_1'].yy)\n        data = self.cached_cos1_data\n        plot_heatmap(x=data['a1'], y=data['cos1'], p=data['p_cos1'], ax=axes[1])\n        plt.tight_layout()\n        plt.savefig(f\"{self.cache}/plot.png\")\n", "meta": {"hexsha": "c5a7ecdc6958b42c62185343ee896a65ef17159f", "size": 13550, "ext": "py", "lang": "Python", "max_stars_repo_path": "deep_gw_pe_followup/restricted_prior/prior.py", "max_stars_repo_name": "avivajpeyi/gw_pe_judge", "max_stars_repo_head_hexsha": "151d597fdd6128a278e1d4cff65d3e6776e1fa83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deep_gw_pe_followup/restricted_prior/prior.py", "max_issues_repo_name": "avivajpeyi/gw_pe_judge", "max_issues_repo_head_hexsha": "151d597fdd6128a278e1d4cff65d3e6776e1fa83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deep_gw_pe_followup/restricted_prior/prior.py", "max_forks_repo_name": "avivajpeyi/gw_pe_judge", "max_forks_repo_head_hexsha": "151d597fdd6128a278e1d4cff65d3e6776e1fa83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3278236915, "max_line_length": 116, "alphanum_fraction": 0.6011070111, "include": true, "reason": "import numpy", "num_tokens": 3569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.16990848793091776}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy\nfrom pyscf.lib.parameters import BOHR\n\nunknown = 1.999999\n\n#########################\n# JCP 41 3199 (1964).\nBRAGG = 1/BOHR * numpy.array((unknown,  # Ghost atom\n        0.35,                                     1.40,             # 1s\n        1.45, 1.05, 0.85, 0.70, 0.65, 0.60, 0.50, 1.50,             # 2s2p\n        1.80, 1.50, 1.25, 1.10, 1.00, 1.00, 1.00, 1.80,             # 3s3p\n        2.20, 1.80,                                                 # 4s\n        1.60, 1.40, 1.35, 1.40, 1.40, 1.40, 1.35, 1.35, 1.35, 1.35, # 3d\n                    1.30, 1.25, 1.15, 1.15, 1.15, 1.90,             # 4p\n        2.35, 2.00,                                                 # 5s\n        1.80, 1.55, 1.45, 1.45, 1.35, 1.30, 1.35, 1.40, 1.60, 1.55, # 4d\n                    1.55, 1.45, 1.45, 1.40, 1.40, 2.10,             # 5p\n        2.60, 2.15,                                                 # 6s\n        1.95, 1.85, 1.85, 1.85, 1.85, 1.85, 1.85,                   # La, Ce-Eu\n        1.80, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75,             # Gd, Tb-Lu\n              1.55, 1.45, 1.35, 1.35, 1.30, 1.35, 1.35, 1.35, 1.50, # 5d\n                    1.90, 1.80, 1.60, 1.90, 1.45, 2.10,             # 6p\n        1.80, 2.15,                                                 # 7s\n        1.95, 1.80, 1.80, 1.75, 1.75, 1.75, 1.75,\n        1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75,\n        1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75,\n                    1.75, 1.75, 1.75, 1.75, 1.75, 1.75,\n        1.75, 1.75,\n        1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75))\n\n# from Gerald Knizia's CtDftGrid, which is based on\n#       http://en.wikipedia.org/wiki/Covalent_radius\n# and\n#       Beatriz Cordero, Veronica Gomez, Ana E. Platero-Prats, Marc Reves,\n#       Jorge Echeverria, Eduard Cremades, Flavia Barragan and Santiago\n#       Alvarez.  Covalent radii revisited. Dalton Trans., 2008, 2832-2838,\n#       doi:10.1039/b801115j\nCOVALENT = 1/BOHR * numpy.array((unknown,  # Ghost atom\n        0.31,                                     0.28,             # 1s\n        1.28, 0.96, 0.84, 0.73, 0.71, 0.66, 0.57, 0.58,             # 2s2p\n        1.66, 1.41, 1.21, 1.11, 1.07, 1.05, 1.02, 1.06,             # 3s3p\n        2.03, 1.76,                                                 # 4s\n        1.70, 1.60, 1.53, 1.39, 1.50, 1.42, 1.38, 1.24, 1.32, 1.22, # 3d\n                    1.22, 1.20, 1.19, 1.20, 1.20, 1.16,             # 4p\n        2.20, 1.95,                                                 # 5s\n        1.90, 1.75, 1.64, 1.54, 1.47, 1.46, 1.42, 1.39, 1.45, 1.44, # 4d\n                    1.42, 1.39, 1.39, 1.38, 1.39, 1.40,             # 5p\n        2.44, 2.15,                                                 # 6s\n        2.07, 2.04, 2.03, 2.01, 1.99, 1.98, 1.98,                   # La, Ce-Eu\n        1.96, 1.94, 1.92, 1.92, 1.89, 1.90, 1.87, 1.87,             # Gd, Tb-Lu\n              1.75, 1.70, 1.62, 1.51, 1.44, 1.41, 1.36, 1.36, 1.32, # 5d\n                    1.45, 1.46, 1.48, 1.40, 1.50, 1.50,             # 6p\n        2.60, 2.21,                                                 # 7s\n        2.15, 2.06, 2.00, 1.96, 1.90, 1.87, 1.80, 1.69))\n\n\n#\n# vdw from ASE\n#\n# Van der Waals radii in [A] taken from\n# http://www.webelements.com/periodicity/van_der_waals_radius/\n# and the references given there.\n# Additional source 5 from http://de.wikipedia.org/wiki/Van-der-Waals-Radius\n# \n# 1. A. Bondi, J. Phys. Chem., 1964, 68, 441.\n# \n# 2. L. Pauling, The Nature of the Chemical Bond,\n#    Cornell University Press, USA, 1945.\n# \n# 3. J.E. Huheey, E.A. Keiter, and R.L. Keiter in Inorganic Chemistry\n#    Principles of Structure and Reactivity, 4th edition, HarperCollins,\n#    New York, USA, 1993.W.W. Porterfield in Inorganic chemistry,\n#    a unified approach, Addison Wesley Publishing Co.,\n#    Reading Massachusetts, USA, 1984.\n# \n# 4. A.M. James and M.P. Lord in Macmillan's Chemical and Physical Data,\n#    Macmillan, London, UK, 1992.\n# \n# 5. Manjeera Mantina, Adam C. Chamberlin, Rosendo Valero,\n#    Christopher J. Cramer, Donald G. Truhlar Consistent van der Waals Radii\n#    for the Whole Main Group. In J. Phys. Chem. A. 2009, 113, 5806-5812,\n#    doi:10.1021/jp8111556\nVDW = 1/BOHR * numpy.array((unknown,  # Ghost atom\n    1.20,       #  1 H\n    1.40,       #  2 He [1]\n    1.82,       #  3 Li [1]\n    1.53,       #  4 Be [5]\n    1.92,       #  5 B  [5]\n    1.70,       #  6 C  [1]\n    1.55,       #  7 N  [1]\n    1.52,       #  8 O  [1]\n    1.47,       #  9 F  [1]\n    1.54,       # 10 Ne [1]\n    2.27,       # 11 Na [1]\n    1.73,       # 12 Mg [1]\n    1.84,       # 13 Al [5]\n    2.10,       # 14 Si [1]\n    1.80,       # 15 P  [1]\n    1.80,       # 16 S  [1]\n    1.75,       # 17 Cl [1]\n    1.88,       # 18 Ar [1]\n    2.75,       # 19 K  [1]\n    2.31,       # 20 Ca [5]\n    unknown,    # 21 Sc\n    unknown,    # 22 Ti\n    unknown,    # 23 V\n    unknown,    # 24 Cr\n    unknown,    # 25 Mn\n    unknown,    # 26 Fe\n    unknown,    # 27 Co\n    1.63,       # 28 Ni [1]\n    1.40,       # 29 Cu [1]\n    1.39,       # 30 Zn [1]\n    1.87,       # 31 Ga [1]\n    2.11,       # 32 Ge [5]\n    1.85,       # 33 As [1]\n    1.90,       # 34 Se [1]\n    1.85,       # 35 Br [1]\n    2.02,       # 36 Kr [1]\n    3.03,       # 37 Rb [5]\n    2.49,       # 38 Sr [5]\n    unknown,    # 39 Y\n    unknown,    # 40 Zr\n    unknown,    # 41 Nb\n    unknown,    # 42 Mo\n    unknown,    # 43 Tc\n    unknown,    # 44 Ru\n    unknown,    # 45 Rh\n    1.63,       # 46 Pd [1]\n    1.72,       # 47 Ag [1]\n    1.58,       # 48 Cd [1]\n    1.93,       # 49 In [1]\n    2.17,       # 50 Sn [1]\n    2.06,       # 51 Sb [5]\n    2.06,       # 52 Te [1]\n    1.98,       # 53 I  [1]\n    2.16,       # 54 Xe [1]\n    3.43,       # 55 Cs [5]\n    2.49,       # 56 Ba [5]\n    unknown,    # 57 La\n    unknown,    # 58 Ce\n    unknown,    # 59 Pr\n    unknown,    # 60 Nd\n    unknown,    # 61 Pm\n    unknown,    # 62 Sm\n    unknown,    # 63 Eu\n    unknown,    # 64 Gd\n    unknown,    # 65 Tb\n    unknown,    # 66 Dy\n    unknown,    # 67 Ho\n    unknown,    # 68 Er\n    unknown,    # 69 Tm\n    unknown,    # 70 Yb\n    unknown,    # 71 Lu\n    unknown,    # 72 Hf\n    unknown,    # 73 Ta\n    unknown,    # 74 W\n    unknown,    # 75 Re\n    unknown,    # 76 Os\n    unknown,    # 77 Ir\n    1.75,       # 78 Pt [1]\n    1.66,       # 79 Au [1]\n    1.55,       # 80 Hg [1]\n    1.96,       # 81 Tl [1]\n    2.02,       # 82 Pb [1]\n    2.07,       # 83 Bi [5]\n    1.97,       # 84 Po [5]\n    2.02,       # 85 At [5]\n    2.20,       # 86 Rn [5]\n    3.48,       # 87 Fr [5]\n    2.83,       # 88 Ra [5]\n    unknown,    # 89 Ac\n    unknown,    # 90 Th\n    unknown,    # 91 Pa\n    1.86,       # 92 U [1]\n    unknown,    # 93 Np\n    unknown,    # 94 Pu\n    unknown,    # 95 Am\n    unknown,    # 96 Cm\n    unknown,    # 97 Bk\n    unknown,    # 98 Cf\n    unknown,    # 99 Es\n    unknown,    #100 Fm\n    unknown,    #101 Md\n    unknown,    #102 No\n    unknown,    #103 Lr\n))\n\n# Universal Force Field (UFF)\n# J. Am. Chem. Soc., 1992, 114 (25), pp 10024-10035\nUFF = 1/BOHR * numpy.array((unknown,  # Ghost atom\n    1.4430,     #  1  H\n    1.8100,     #  2  He\n    1.2255,     #  3  Li\n    1.3725,     #  4  Be\n    2.0415,     #  5  B\n    1.9255,     #  6  C\n    1.8300,     #  7  N\n    1.7500,     #  8  O\n    1.6820,     #  9  F\n    1.6215,     # 10  Ne\n    1.4915,     # 11  Na\n    1.5105,     # 12  Mg\n    2.2495,     # 13  Al\n    2.1475,     # 14  Si\n    2.0735,     # 15  P\n    2.0175,     # 16  S\n    1.9735,     # 17  Cl\n    1.9340,     # 18  Ar\n    1.9060,     # 19  K\n    1.6995,     # 20  Ca\n    1.6475,     # 21  Sc\n    1.5875,     # 22  Ti\n    1.5720,     # 23  V\n    1.5115,     # 24  Cr\n    1.4805,     # 25  Mn\n    1.4560,     # 26  Fe\n    1.4360,     # 27  Co\n    1.4170,     # 28  Ni\n    1.7475,     # 29  Cu\n    1.3815,     # 30  Zn\n    2.1915,     # 31  Ga\n    2.1400,     # 32  Ge\n    2.1150,     # 33  As\n    2.1025,     # 34  Se\n    2.0945,     # 35  Br\n    2.0705,     # 36  Kr\n    2.0570,     # 37  Rb\n    1.8205,     # 38  Sr\n    1.6725,     # 39  Y\n    1.5620,     # 40  Zr\n    1.5825,     # 41  Nb\n    1.5260,     # 42  Mo\n    1.4990,     # 43  Tc\n    1.4815,     # 44  Ru\n    1.4645,     # 45  Rh\n    1.4495,     # 46  Pd\n    1.5740,     # 47  Ag\n    1.4240,     # 48  Cd\n    2.2315,     # 49  In\n    2.1960,     # 50  Sn\n    2.2100,     # 51  Sb\n    2.2350,     # 52  Te\n    2.2500,     # 53  I\n    2.2020,     # 54  Xe\n    2.2585,     # 55  Cs\n    1.8515,     # 56  Ba\n    1.7610,     # 57  La\n    1.7780,     # 58  Ce\n    1.8030,     # 59  Pr\n    1.7875,     # 60  Nd\n    1.7735,     # 61  Pm\n    1.7600,     # 62  Sm\n    1.7465,     # 63  Eu\n    1.6840,     # 64  Gd\n    1.7255,     # 65  Tb\n    1.7140,     # 66  Dy\n    1.7045,     # 67  Ho\n    1.6955,     # 68  Er\n    1.6870,     # 69  Tm\n    1.6775,     # 70  Yb\n    1.8200,     # 71  Lu\n    1.5705,     # 72  Hf\n    1.5850,     # 73  Ta\n    1.5345,     # 74  W\n    1.4770,     # 75  Re\n    1.5600,     # 76  Os\n    1.4200,     # 77  Ir\n    1.3770,     # 78  Pt\n    1.6465,     # 79  Au\n    1.3525,     # 80  Hg\n    2.1735,     # 81  Tl\n    2.1485,     # 82  Pb\n    2.1850,     # 83  Bi\n    2.3545,     # 84  Po\n    2.3750,     # 85  At\n    2.3825,     # 86  Rn\n    2.4500,     # 87  Fr\n    1.8385,     # 88  Ra\n    1.7390,     # 89  Ac\n    1.6980,     # 90  Th\n    1.7120,     # 91  Pa\n    1.6975,     # 92  U\n    1.7120,     # 93  Np\n    1.7120,     # 94  Pu\n    1.6905,     # 95  Am\n    1.6630,     # 96  Cm\n    1.6695,     # 97  Bk\n    1.6565,     # 98  Cf\n    1.6495,     # 99  Es\n    1.6430,     #100  Fm\n    1.6370,     #101  Md\n    1.6240,     #102  No\n    1.6180,     #103  Lr\n    unknown,    #104  Rf\n    unknown,    #105  Db\n    unknown,    #106  Sg\n    unknown,    #107  Bh\n    unknown,    #108  Hs\n    unknown,    #109  Mt\n    unknown,    #110  Ds\n    unknown,    #111  Rg\n    unknown,    #112  Cn\n    unknown,    #113  Nh\n    unknown,    #114  Fl\n    unknown,    #115  Mc\n    unknown,    #116  Lv\n    unknown,    #117  Ts\n    unknown,    #118  Og\n))\n\n# Allinger's MM3 radii\n# From http://pcmsolver.readthedocs.io/en/latest/users/input.html\nMM3 = 1/BOHR * numpy.array((unknown,  # Ghost atom\n    1.62,       #  1  H\n    1.53,       #  2  He\n    2.55,       #  3  Li\n    2.23,       #  4  Be\n    2.15,       #  5  B\n    2.04,       #  6  C\n    1.93,       #  7  N\n    1.82,       #  8  O\n    1.71,       #  9  F\n    1.60,       # 10  Ne\n    2.70,       # 11  Na\n    2.43,       # 12  Mg\n    2.36,       # 13  Al\n    2.29,       # 14  Si\n    2.22,       # 15  P\n    2.15,       # 16  S\n    2.07,       # 17  Cl\n    1.99,       # 18  Ar\n    3.09,       # 19  K\n    2.81,       # 20  Ca\n    2.61,       # 21  Sc\n    2.39,       # 22  Ti\n    2.29,       # 23  V\n    2.25,       # 24  Cr\n    2.24,       # 25  Mn\n    2.23,       # 26  Fe\n    2.23,       # 27  Co\n    2.22,       # 28  Ni\n    2.26,       # 29  Cu\n    2.29,       # 30  Zn\n    2.46,       # 31  Ga\n    2.44,       # 32  Ge\n    2.36,       # 33  As\n    2.29,       # 34  Se\n    2.22,       # 35  Br\n    2.15,       # 36  Kr\n    3.25,       # 37  Rb\n    3.00,       # 38  Sr\n    2.71,       # 39  Y\n    2.54,       # 40  Zr\n    2.43,       # 41  Nb\n    2.39,       # 42  Mo\n    2.36,       # 43  Tc\n    2.34,       # 44  Ru\n    2.34,       # 45  Rh\n    2.37,       # 46  Pd\n    2.43,       # 47  Ag\n    2.50,       # 48  Cd\n    2.64,       # 49  In\n    2.59,       # 50  Sn\n    2.52,       # 51  Sb\n    2.44,       # 52  Te\n    2.36,       # 53  I\n    2.28,       # 54  Xe\n    3.44,       # 55  Cs\n    3.07,       # 56  Ba\n    2.78,       # 57  La\n    2.74,       # 58  Ce\n    2.73,       # 59  Pr\n    2.73,       # 60  Nd\n    2.72,       # 61  Pm\n    2.71,       # 62  Sm\n    2.94,       # 63  Eu\n    2.71,       # 64  Gd\n    2.70,       # 65  Tb\n    2.69,       # 66  Dy\n    2.67,       # 67  Ho\n    2.67,       # 68  Er\n    2.67,       # 69  Tm\n    2.79,       # 70  Yb\n    2.65,       # 71  Lu\n    2.53,       # 72  Hf\n    2.43,       # 73  Ta\n    2.39,       # 74  W\n    2.37,       # 75  Re\n    2.35,       # 76  Os\n    2.36,       # 77  Ir\n    2.39,       # 78  Pt\n    2.43,       # 79  Au\n    2.53,       # 80  Hg\n    2.59,       # 81  Tl\n    2.74,       # 82  Pb\n    2.66,       # 83  Bi\n    2.59,       # 84  Po\n    2.51,       # 85  At\n    2.43,       # 86  Rn\n    3.64,       # 87  Fr\n    3.27,       # 88  Ra\n    3.08,       # 89  Ac\n    2.74,       # 90  Th\n    2.64,       # 91  Pa\n    2.52,       # 92  U\n    2.52,       # 93  Np\n    2.52,       # 94  Pu\n    unknown,    # 95  Am\n    unknown,    # 96  Cm\n    unknown,    # 97  Bk\n    unknown,    # 98  Cf\n    unknown,    # 99  Es\n    unknown,    #100  Fm\n    unknown,    #101  Md\n    unknown,    #102  No\n    unknown,    #103  Lr\n    2.73,       #104  Rf\n    2.63,       #105  Db\n    unknown,    #106  Sg\n    1.62,       #107  Bh\n    unknown,    #108  Hs\n    unknown,    #109  Mt\n    unknown,    #110  Ds\n    unknown,    #111  Rg\n    unknown,    #112  Cn\n    unknown,    #113  Nh\n    unknown,    #114  Fl\n    unknown,    #115  Mc\n    unknown,    #116  Lv\n    unknown,    #117  Ts\n    unknown,    #118  Og\n))\ndel unknown\n", "meta": {"hexsha": "96155243034eacefc8e5b03b0257af823b80773f", "size": 13757, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/data/radii.py", "max_stars_repo_name": "azag0/pyscf", "max_stars_repo_head_hexsha": "1e3e27b61b3cfd22c9679d2c9851c13b3ebc5a1b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-03T12:32:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T08:19:02.000Z", "max_issues_repo_path": "pyscf/data/radii.py", "max_issues_repo_name": "azag0/pyscf", "max_issues_repo_head_hexsha": "1e3e27b61b3cfd22c9679d2c9851c13b3ebc5a1b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscf/data/radii.py", "max_forks_repo_name": "azag0/pyscf", "max_forks_repo_head_hexsha": "1e3e27b61b3cfd22c9679d2c9851c13b3ebc5a1b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-06-01T05:31:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T02:38:33.000Z", "avg_line_length": 30.5711111111, "max_line_length": 79, "alphanum_fraction": 0.4033582903, "include": true, "reason": "import numpy", "num_tokens": 6491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.16990848793091773}}
{"text": "from typing import Union\nimport numpy as np\nfrom ._data_converter import NameProcess\nfrom .interpolators import Material, Interpolators, MaterialFactory\n\n_AVOGADRO = 0.60221367  # * 1e+24 mole^-1\n\nENERGY_GRID_DEFAULT = np.array([1.0E+03, 1.5E+03, 2.0E+03, 3.0E+03, 4.0E+03, 5.0E+03,\n                                6.0E+03, 8.0E+03, 1.0E+04, 1.5E+04, 2.0E+04, 3.0E+04, 4.0E+04,\n                                5.0E+04, 6.0E+04, 8.0E+04, 1.0E+05, 1.5E+05, 2.0E+05, 3.0E+05,\n                                4.0E+05, 5.0E+05, 6.0E+05, 8.0E+05, 1.0E+06, 1.022E+06, 1.25E+06,\n                                1.5E+06, 2.0E+06, 2.044E+06, 3.0E+06, 4.0E+06, 5.0E+06, 6.0E+06,\n                                7.0E+06, 8.0E+06, 9.0E+06, 1.0E+07, 1.1E+07, 1.2E+07, 1.3E+07,\n                                1.4E+07, 1.5E+07, 1.6E+07, 1.8E+07, 2.0E+07, 2.2E+07, 2.4E+07,\n                                2.6E+07, 2.8E+07, 3.0E+07, 4.0E+07, 5.0E+07, 6.0E+07, 8.0E+07,\n                                1.0E+08, 1.5E+08, 2.0E+08, 3.0E+08, 4.0E+08, 5.0E+08, 6.0E+08,\n                                8.0E+08, 1.0E+09, 1.5E+09, 2.0E+09, 3.0E+09, 4.0E+09, 5.0E+09,\n                                6.0E+09, 8.0E+09, 1.0E+10, 1.5E+10, 2.0E+10, 3.0E+10, 4.0E+10,\n                                5.0E+10, 6.0E+10, 8.0E+10, 1.0E+11], dtype='d')\n\n_INTERPOLATOS = Interpolators()\n\ndef calculate_attenuation(material: Material, energy: np.ndarray = None):\n    \"\"\"\n    Calculate attenuation (cm2/gramm) for gamma-ray (at energies between 1 keV and 100 GeV) for next process:\n\n        * Coherent scattering\n        * Incoherent (Compton) scattering\n        * Photoelectric absorption\n        * Pair production in the field of the atomic nucleus and in the field of the atomic electrons\n\n    Based on NIST XCOM data: https://www.nist.gov/pml/xcom-photon-cross-sections-database\n\n    Parameters\n    ----------\n    material\n            special class description simple material or compound\n\n    energy\n            energies of gamma-quanta in eV, used `ENERGY_GRID_DEFAULT` by default\n\n    Returns\n    -------\n    data : ndarray with attenuation in cm2/gramm\n    \"\"\"\n    if not isinstance(material, Material):\n        raise Exception(\"Except material\")\n\n    if len(material) == 1:\n        element = material.elements_by_Z[0]\n        data = calculate_cross_section(element, energy)\n        # Attenutaion coefficient = macro_cross_secction/denisty = \\\n        # = micro_cross_section/atom_weight[gr]\n        # atom_weight[gr] = atom_weight[amu] / AVOGADRO\n        atom_weigth = MaterialFactory.get_element_mass(element)\n        for name in data.dtype.names:\n            data[name] /= _AVOGADRO / atom_weigth\n        return data\n    elif len(material) > 1:\n        atom_weights_amu = MaterialFactory.get_elements_mass_list(material.elements_by_Z)\n        data = calculate_cross_section(material.elements_by_Z[0], energy)\n        for name in data.dtype.names:\n            data[name] *= ( material.weights[0] * _AVOGADRO / atom_weights_amu[0])\n\n        for atom_weight_amu, element, weight in zip(atom_weights_amu[1:], material.elements_by_Z[1:], material.weights):\n            temp = calculate_cross_section(element, energy)\n            for name in data.dtype.names:\n                data[name] +=  temp[name] * weight * _AVOGADRO / atom_weight_amu\n        return data\n    else:\n        raise Exception(\"Empty material\")\n\n\ndef calculate_cross_section(element : Union[int, str], energy: np.ndarray = None) -> np.ndarray:\n    \"\"\"\n    Calculate cross-section (barn/atom) for gamma-ray (at energies between 1 keV and 100 GeV) for next process:\n\n        * Coherent scattering\n        * Incoherent (Compton) scattering\n        * Photoelectric absorption\n        * Pair production in the field of the atomic nucleus and in the field of the atomic electrons\n\n    Based on NIST XCOM data: https://www.nist.gov/pml/xcom-photon-cross-sections-database\n\n    Parameters\n    ----------\n    element\n            atomic number or symbol of element\n\n    energy\n            energies of gamma-quanta in eV, used `ENERGY_GRID_DEFAULT` by default\n\n    Returns\n    -------\n    data : ndarray with cross-section in barn/atom\n    \"\"\"\n    if energy is None:\n        energy = ENERGY_GRID_DEFAULT\n\n    if not isinstance(element, int):\n        element = MaterialFactory.get_element_from_symbol(element)\n\n    n = len(energy)\n    dtype = np.dtype([(\"energy\", \"d\"),\n                      (NameProcess.COHERENT, 'd'),\n                      (NameProcess.INCOHERENT, 'd'),\n                      (NameProcess.PHOTOELECTRIC, 'd'),\n                      (NameProcess.PAIR_ATOM, 'd'),\n                      (NameProcess.PAIR_ELECTRON, 'd'),\n                      (\"total_without_coherent\", \"d\"),\n                      (\"total\", \"d\")])\n\n    data = np.zeros(n, dtype=dtype)\n    data[\"energy\"] = np.asarray(energy)\n\n    for k, v in _INTERPOLATOS.get_interpolators(element).items():\n        data[k] = v(data[\"energy\"])\n        data[\"total\"] += data[k]\n    data[\"total_without_coherent\"] -= data[NameProcess.COHERENT]\n    return data\n", "meta": {"hexsha": "0b4f8d0b127548b92cc705037271e7947151789b", "size": 5049, "ext": "py", "lang": "Python", "max_stars_repo_path": "xcom/xcom.py", "max_stars_repo_name": "lesnat/nist-calculators", "max_stars_repo_head_hexsha": "4b10b2a6fd222f8916efaa109150f267e0610bc0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "xcom/xcom.py", "max_issues_repo_name": "lesnat/nist-calculators", "max_issues_repo_head_hexsha": "4b10b2a6fd222f8916efaa109150f267e0610bc0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xcom/xcom.py", "max_forks_repo_name": "lesnat/nist-calculators", "max_forks_repo_head_hexsha": "4b10b2a6fd222f8916efaa109150f267e0610bc0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.7272727273, "max_line_length": 120, "alphanum_fraction": 0.586848881, "include": true, "reason": "import numpy", "num_tokens": 1591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.1699084845614999}}
{"text": "import numpy as np \nfrom .weighted_yield import SSP, lifetime_Argast, lifetime_Raiteri\nfrom .imf import IMF\nfrom .yields import SN2_feedback, AGB_feedback, SN1a_feedback, Hypernova_feedback\n\nclass SSP_wrap():\n    '''\n    This is the wrapper around the SSP function. It preloads the needed classes and calls all nucleosynthetic enrichment processes when the enrichment is calculated.\n    '''\n    def __init__(self, a):\n        '''\n        Upon initialization the default IMF, CC-SN yields, SN Ia yields and AGB yields is loaded.\n\n        INPUT:\n        \n        a = Modelparameter class. So the default IMF etc are loaded. If we want other yield sets etc. loaded we need to specify that in paramter.py\n        '''\n\n        ## loading the IMF and the yieldsets prescribed in a (containing all the model parameters)\n        basic_imf = IMF(a.mmin,a.mmax,a.mass_steps)\n        getattr(basic_imf, a.imf_type_name)(a.imf_parameter)\n        basic_sn2 = SN2_feedback()\n        getattr(basic_sn2, a.yield_table_name_sn2)()\n        basic_1a = SN1a_feedback()\n        getattr(basic_1a, a.yield_table_name_1a)()\n        basic_agb = AGB_feedback()\n        getattr(basic_agb, a.yield_table_name_agb)()\n        ## mixing of Nomoto CC-SN and HN yields\n        if a.yield_table_name_sn2 == 'Nomoto2013':\n            basic_hn = Hypernova_feedback()\n            getattr(basic_hn, a.yield_table_name_hn)()\n            for item in basic_sn2.metallicities:\n                x = np.copy(basic_sn2.table[item])\n                y = np.copy(basic_hn.table[item])\n                for jtem in basic_hn.masses:\n                    basic_sn2.table[item]['mass_in_remnants'][np.where(basic_sn2.table[item]['Mass']==jtem)] = a.sn2_to_hn * (x['mass_in_remnants'][np.where(x['Mass']==jtem)]) + (1-a.sn2_to_hn) * (y['mass_in_remnants'][np.where(y['Mass']==jtem)])\n                    basic_sn2.table[item]['unprocessed_mass_in_winds'][np.where(basic_sn2.table[item]['Mass']==jtem)] = a.sn2_to_hn * (x['unprocessed_mass_in_winds'][np.where(x['Mass']==jtem)]) + (1-a.sn2_to_hn) * (y['unprocessed_mass_in_winds'][np.where(y['Mass']==jtem)])\n                    hn_mass = []\n                    sn_mass = []\n                    for stem in basic_sn2.elements:\n                        sn_mass.append(x[stem][np.where(x['Mass']==jtem)])\n                        hn_mass.append(y[stem][np.where(y['Mass']==jtem)])\n                        basic_sn2.table[item][stem][np.where(basic_sn2.table[item]['Mass']==jtem)]= a.sn2_to_hn * (x[stem][np.where(x['Mass']==jtem)]) + (1-a.sn2_to_hn) * (y[stem][np.where(y['Mass']==jtem)])\n        ## to pass the information on to the feedback calculation\n        self.a = a\n        self.imf = basic_imf\n        self.sn2 = basic_sn2\n        self.sn1a = basic_1a\n        self.agb = basic_agb\n\n    def calculate_feedback(self, z, elements, element_fractions, time_steps):\n        '''\n        The feedback is calculated for the initializes SSP.\n\n        INPUT:\n        \n        z = metallicity of the SSP in mass fraction (not normed to solar!)\n        \n        elements = which elements to follow\n        \n        element_fractions = the birth material of the SSP in the same order as 'elements'\n        \n        time_steps = the time-steps for which the enrichment of the SSP should be calculated (usually the time-steps until the end of the chempy simulation)\n        '''\n        basic_ssp = SSP(False, float(z), np.copy(self.imf.x), np.copy(self.imf.dm), np.copy(self.imf.dn), np.copy(time_steps), list(elements), str(self.a.stellar_lifetimes), str(self.a.interpolation_scheme), bool(self.a.only_net_yields_in_process_tables))\n        basic_ssp.sn2_feedback(list(self.sn2.elements), dict(self.sn2.table), np.copy(self.sn2.metallicities), float(self.a.sn2mmin), float(self.a.sn2mmax),list(element_fractions))\n        basic_ssp.agb_feedback(list(self.agb.elements), dict(self.agb.table), list(self.agb.metallicities), float(self.a.agbmmin), float(self.a.agbmmax),np.hstack(element_fractions))\n        basic_ssp.sn1a_feedback(list(self.sn1a.elements), list(self.sn1a.metallicities), dict(self.sn1a.table), str(self.a.time_delay_functional_form), float(self.a.sn1ammin), float(self.a.sn1ammax), self.a.sn1a_parameter, float(self.a.total_mass), bool(self.a.stochastic_IMF))\n        basic_ssp.bh_feedback(float(self.a.bhmmin),float(self.a.bhmmax),list(elements), np.hstack(element_fractions) , float(self.a.percentage_of_bh_mass))\n        \n        # exposing these tables to the outside wrapper\n        self.table = basic_ssp.table\n        self.sn2_table = basic_ssp.sn2_table\n        self.agb_table = basic_ssp.agb_table\n        self.sn1a_table = basic_ssp.sn1a_table\n        self.bh_table = basic_ssp.bh_table\n        self.inverse_imf = basic_ssp.inverse_imf\n\ndef initialise_stuff(a):\n    '''\n    Convenience function initialising the solar abundance, SFR and infall with the default values provided in parameter.py as a\n    '''\n    from .solar_abundance import solar_abundances\n    from .sfr import SFR \n    from .infall import INFALL\n\n    basic_solar = solar_abundances()\n    getattr(basic_solar, a.solar_abundance_name)()\n    \n    basic_sfr = SFR(a.start,a.end,a.time_steps)\n    if a.basic_sfr_name == 'gamma_function':\n        getattr(basic_sfr, a.basic_sfr_name)(S0 = a.S_0 * a.mass_factor,a_parameter = a.a_parameter, loc = a.sfr_beginning, scale = a.sfr_scale)\n    elif a.basic_sfr_name == 'model_A':\n        basic_sfr.model_A(a.mass_factor*a.S_0,a.t_0,a.t_1)\n    elif a.basic_sfr_name == 'prescribed':\n        basic_sfr.prescribed(a.mass_factor, a.name_of_file)\n    elif a.basic_sfr_name == 'doubly_peaked':\n        basic_sfr.doubly_peaked(S0 = a.mass_factor*a.S_0, peak_ratio = a.peak_ratio, decay = a.sfr_decay, t0 = a.sfr_t0, peak1t0 = a.peak1t0, peak1sigma = a.peak1sigma)\n        \n    basic_sfr.sfr = np.divide(basic_sfr.sfr,sum(basic_sfr.sfr))\n    \n    \n    basic_infall = INFALL(np.copy(basic_sfr.t),np.copy(basic_sfr.sfr))\n    if a.basic_infall_name == 'exponential':\n        getattr(basic_infall, a.basic_infall_name)((a.infall_amplitude,a.tau_infall,a.infall_time_offset,a.c_infall,a.norm_infall))\n    elif a.basic_infall_name == 'gamma_function':\n        getattr(basic_infall, a.basic_infall_name)(mass_factor = a.norm_infall, a_parameter = a.infall_a_parameter, loc = a.infall_beginning, scale = a.infall_scale)\n    elif a.basic_infall_name == 'sfr_related':\n        getattr(basic_infall, a.basic_infall_name)()\n\n\n    return basic_solar, basic_sfr, basic_infall\n\ndef Chempy(a):\n    '''\n    Chemical evolution run with the default parameters using the net yields.\n\n    INPUT: \n    \n    a = ModelParameters() from parameter.py\n\n    OUTPUT:\n    \n    cube = The ISM evolution class\n    \n    abundances = The abundances of the ISM\n    '''\n    from .infall import PRIMORDIAL_INFALL\n    from .time_integration import ABUNDANCE_MATRIX\n    from .making_abundances import mass_fraction_to_abundances\n    from numpy.lib.recfunctions import append_fields    \n    basic_solar, basic_sfr, basic_infall = initialise_stuff(a)\n    elements_to_trace = a.elements_to_trace\n    basic_primordial = PRIMORDIAL_INFALL(list(elements_to_trace),np.copy(basic_solar.table))\n    basic_primordial.primordial()\n    \n    # Needed a rescaling for the shortened sfr  \n    gas_reservoir_mass_factor = a.gas_reservoir_mass_factor / a.shortened_sfr_rescaling\n    #sfr_factor_for_cosmic_accretion    = a.sfr_factor_for_cosmic_accretion / a.shortened_sfr_rescaling\n    gas_at_start = a.gas_at_start / a.shortened_sfr_rescaling\n    \n    cube = ABUNDANCE_MATRIX(np.copy(basic_sfr.t),np.copy(basic_sfr.sfr),np.copy(basic_infall.infall),list(elements_to_trace),\n        list(basic_primordial.symbols),list(basic_primordial.fractions),float(gas_at_start),list(basic_primordial.symbols),list(basic_primordial.fractions),\n        float(gas_reservoir_mass_factor),float(a.outflow_feedback_fraction),bool(a.check_processes),float(a.starformation_efficiency),float(a.gas_power),\n        float(a.sfr_factor_for_cosmic_accretion), list(basic_primordial.symbols), list(basic_primordial.fractions))\n\n    basic_ssp = SSP_wrap(a)\n    for i in range(len(basic_sfr.t)-1):\n        j = len(basic_sfr.t)-i\n        element_fractions = []\n        for item in elements_to_trace:\n            element_fractions.append(float(np.copy(cube.cube[item][max(i-1,0)]/cube.cube['gas'][max(i-1,0)])))## gas element fractions from one time step before    \n            if element_fractions[-1]<0:\n                print('-ve Error')\n                #raise Exception('-ve Error')\n        metallicity = float(cube.cube['Z'][i])\n        #print(metallicity)     \n                \n        time_steps = np.copy(basic_sfr.t[:j])\n        basic_ssp.calculate_feedback(float(metallicity), list(elements_to_trace), list(element_fractions), np.copy(time_steps)) \n        cube.advance_one_step(i+1,np.copy(basic_ssp.table),np.copy(basic_ssp.sn2_table),np.copy(basic_ssp.agb_table),np.copy(basic_ssp.sn1a_table),np.copy(basic_ssp.bh_table))\n        if cube.cube['gas'][i] < 0:\n            print(i, basic_sfr.t[i])\n            print('gas became negative. returning -inf')\n            return -np.inf, [0]\n        if cube.gas_reservoir['gas'][i] < 0:\n            print('gas_reservoir became negative. returning -inf')\n            return -np.inf, [0]\n\n    abundances,elements,numbers = mass_fraction_to_abundances(np.copy(cube.cube),np.copy(basic_solar.table))\n    weights = cube.cube['sfr']\n    abundances = append_fields(abundances,'weights',weights)\n    abundances = append_fields(abundances,'time', cube.cube['time'])\n    abundances = np.array(abundances)\n    \n    for element in elements:       \n        if element != 'Fe':\n            try:\n                abundances[element] -= abundances['Fe']\n            except RuntimeWarning: # Remove error from first Fe abundance = -inf\n                pass\n    #TEST output\n    #print('Chempy output')\n    #print(abundances[:][-1])\n    \n    return cube, abundances\n\ndef Chempy_all_times(a):\n    '''\n    Chemical evolution run with the default parameters using the net yields.\n\n    INPUT: \n    \n    a = ModelParameters() from parameter.py\n\n    OUTPUT:\n    \n    cube = The ISM evolution class\n    \n    abundances = The abundances of the ISM\n    '''\n    from .infall import PRIMORDIAL_INFALL\n    from .time_integration import ABUNDANCE_MATRIX\n    from .making_abundances import mass_fraction_to_abundances\n    from numpy.lib.recfunctions import append_fields    \n    basic_solar, basic_sfr, basic_infall = initialise_stuff(a)\n    elements_to_trace = a.elements_to_trace\n    basic_primordial = PRIMORDIAL_INFALL(list(elements_to_trace),np.copy(basic_solar.table))\n    basic_primordial.primordial()\n    gas_reservoir_mass_factor = a.gas_reservoir_mass_factor / a.shortened_sfr_rescaling\n    gas_at_start = a.gas_at_start / a.shortened_sfr_rescaling # unlikely to be needed unless a.gas_at_start is non-zero\n        \n    cube = ABUNDANCE_MATRIX(np.copy(basic_sfr.t),np.copy(basic_sfr.sfr),np.copy(basic_infall.infall),list(elements_to_trace),list(basic_primordial.symbols),\n        list(basic_primordial.fractions),float(gas_at_start),list(basic_primordial.symbols),list(basic_primordial.fractions),float(gas_reservoir_mass_factor),\n        float(a.outflow_feedback_fraction),bool(a.check_processes),float(a.starformation_efficiency),float(a.gas_power),\n        float(a.sfr_factor_for_cosmic_accretion),list(basic_primordial.symbols), list(basic_primordial.fractions))\n\n    basic_ssp = SSP_wrap(a)\n    \n    for i in range(len(basic_sfr.t)-1):\n        j = len(basic_sfr.t)-i\n        element_fractions = []\n        for item in elements_to_trace:\n            element_fractions.append(float(np.copy(cube.cube[item][max(i-1,0)]/cube.cube['gas'][max(i-1,0)])))## gas element fractions from one time step before    \n            if element_fractions[-1]<0:\n                print('-ve Error')\n                #raise Exception('-ve Error')\n        metallicity = float(cube.cube['Z'][i])\n        #print(metallicity)     \n                \n        time_steps = np.copy(basic_sfr.t[:j])\n        basic_ssp.calculate_feedback(float(metallicity), list(elements_to_trace), list(element_fractions), np.copy(time_steps)) \n        cube.advance_one_step(i+1,np.copy(basic_ssp.table),np.copy(basic_ssp.sn2_table),np.copy(basic_ssp.agb_table),np.copy(basic_ssp.sn1a_table),np.copy(basic_ssp.bh_table))\n        \n        \n        for item in elements_to_trace:\n            if cube.cube[item][i]<0:\n                print(i,item)\n                print('element %s became negative. returning -inf'%item)\n                return -np.inf,[0]\n        if cube.cube['gas'][i] < 0:\n            print(i, basic_sfr.t[i])\n            print('gas became negative. returning -inf')\n            return -np.inf, [0]\n        if cube.gas_reservoir['gas'][i] < 0:\n            print('gas_reservoir became negative. returning -inf')\n            return -np.inf, [0]\n\n    abundances,elements,numbers = mass_fraction_to_abundances(np.copy(cube.cube),np.copy(basic_solar.table))\n    weights = cube.cube['sfr']\n    abundances = append_fields(abundances,'weights',weights)\n    abundances = append_fields(abundances,'time', cube.cube['time'])\n    abundances = np.array(abundances)\n    \n    for element in elements:       \n        if element != 'Fe':\n            filt = np.where(np.logical_not(np.isfinite(abundances['Fe'])))\n            abundances[element][filt]=np.inf\n            filt2 = np.where(np.isfinite(abundances['Fe']))\n            abundances[element][filt2]-=abundances['Fe'][filt2]\n    #TEST output\n    #print('Chempy output')\n    #print(abundances[:][-1])\n    \n    return cube, abundances\n\n\n\ndef Chempy_gross(a):\n    '''\n    Chemical evolution run with the default parameters but now using solar scaled material (testing the worse case when total yields provided).\n\n    INPUT: \n    \n    a = ModelParameters() from parameter.py\n\n    OUTPUT:\n    \n    cube = The ISM evolution class\n    \n    abundances = The abundances of the ISM\n    '''\n    from infall import PRIMORDIAL_INFALL\n    from time_integration import ABUNDANCE_MATRIX\n    from making_abundances import mass_fraction_to_abundances\n    from numpy.lib.recfunctions import append_fields    \n    basic_solar, basic_sfr, basic_infall = initialise_stuff(a)\n    elements_to_trace = a.elements_to_trace\n    basic_primordial = PRIMORDIAL_INFALL(list(elements_to_trace),np.copy(basic_solar.table))\n    basic_primordial.primordial(0)\n    gas_reservoir_mass_factor = a.gas_reservoir_mass_factor / a.shortened_sfr_rescaling\n    gas_at_start = a.gas_at_start / a.shortened_sfr_rescaling\n    cube = ABUNDANCE_MATRIX(np.copy(basic_sfr.t),np.copy(basic_sfr.sfr),np.copy(basic_infall.infall),list(elements_to_trace),list(basic_primordial.symbols),\n        list(basic_primordial.fractions),float(gas_at_start),list(basic_primordial.symbols),list(basic_primordial.fractions),float(gas_reservoir_mass_factor),\n        float(a.outflow_feedback_fraction),bool(a.check_processes),float(a.starformation_efficiency),float(a.gas_power), float(a.sfr_factor_for_cosmic_accretion), \n        list(basic_primordial.symbols), list(basic_primordial.fractions))\n    basic_ssp = SSP_wrap(a)\n    for i in range(len(basic_sfr.t)-1):\n        j = len(basic_sfr.t)-i\n        metallicity = float(cube.cube['Z'][i])\n        solar_scaled_material = PRIMORDIAL_INFALL(list(elements_to_trace),np.copy(basic_solar.table))\n        solar_scaled_material.solar(np.log10(metallicity/basic_solar.z))\n        element_fractions = list(solar_scaled_material.fractions)\n        for item in elements_to_trace:\n            element_fractions.append(float(np.copy(cube.cube[item][max(i-1,0)]/cube.cube['gas'][max(i-1,0)])))## gas element fractions from one time step before    \n        time_steps = np.copy(basic_sfr.t[:j])\n        basic_ssp.calculate_feedback(float(metallicity), list(elements_to_trace), list(element_fractions), np.copy(time_steps))\n        cube.advance_one_step(i+1,np.copy(basic_ssp.table),np.copy(basic_ssp.sn2_table),np.copy(basic_ssp.agb_table),np.copy(basic_ssp.sn1a_table))\n    abundances,elements,numbers = mass_fraction_to_abundances(np.copy(cube.cube),np.copy(basic_solar.table))\n    weights = cube.cube['sfr']\n    abundances = append_fields(abundances,'weights',weights)\n    abundances = np.array(abundances)\n\n    return cube, abundances\n\n\ndef multi_star_optimization():\n    '''\n    This function will optimize the parameters of all stars in a hierachical manner (similar to gibbs sampling)\n\n    INPUT: \n\n    a = will be loaded from parameter.py (prepare all variables there)\n\n    OUTPUT:\n\n    log_list = a list of intermediate results (so far only for debugging)\n    '''\n    import time\n    import multiprocessing as mp\n    from .optimization import minimizer_initial, minimizer_global, minimizer_local\n    from .cem_function import global_optimization_error_returned\n    from .parameter import ModelParameters\n    \n    # For testing\n    import warnings\n    warnings.filterwarnings(\"ignore\")\n        \n    a = ModelParameters()\n    print(a.stellar_identifier_list)\n    start_time = time.time()\n\n    log_list = []\n    # I: Minimization for each star seperately\n    # 1: for each star make initial conditions (each star needs other model parameters) \n    parameter_list = []\n    for item in a.stellar_identifier_list:\n        parameter_list.append(item)\n    # 2: call posterior_function_for_minimization with scipy.optimize.minimize in multiprocess for each star and recover the found parameters\n    p = mp.Pool(len(parameter_list))\n    t = p.map(minimizer_initial, parameter_list)\n    p.close()\n    p.join()\n    result = np.vstack(t)\n\n    log_list.append(np.copy(result))\n    log_list.append('initial minimization')\n    initial = time.time()\n    print('first minimization for each star separately took: %2.f seconds' %(initial - start_time))\n\n    # IV: repeat II and III until posterior does not change much\n    result[:,:len(a.SSP_parameters)] = np.mean(result[:,:len(a.SSP_parameters)], axis = 0)\n    posteriors = []\n    counter = 0\n    while True:\n        counter += 1\n        if len(posteriors) > 1:\n            if np.abs(posteriors[-1] - posteriors[-2]) < a.gibbs_sampler_tolerance:\n                break\n            if len(posteriors) > a.gibbs_sampler_maxiter:\n                break\n\n        initial = time.time()\n        # II: Global parameter minimization:\n        # 1: only SSP parameters free. Use mean SSP parameter values and individual (but fixed ISM parameter values)\n        changing_parameter = result[0,:len(a.SSP_parameters)]\n        # 2: Call each star in multiprocess but only return the predictions\n        # 3: Calculate the likelihood for each star and optimize the common model error (is all done within minimizer global, which is calling 'global optimization')\n        x = minimizer_global(changing_parameter,  a.tol_minimization, a.maxiter_minimization, a.verbose, result)\n\n        # 4: return global SSP parameters and common model error\n        posterior, error_list, elements = global_optimization_error_returned(x, result)\n        posteriors.append(posterior)\n        print(posteriors)\n\n        global_iteration1 = time.time()\n        print('step %d global minimization took: %2.f seconds' %(counter, global_iteration1 - initial)) \n\n        # III: Local parameter minimization:\n        # 1: Use fixed global parameters and fixed common errors make initial conditions\n        result[:,:len(a.SSP_parameters)] = x\n\n        log_list.append((np.copy(x),posterior))\n        log_list.append('step %d global minimization' %(counter))\n\n        p0_list = []\n        parameter_list = []\n        x_list = []\n        error_list_mp = []\n        element_list_mp = []\n\n        for i,item in enumerate(a.stellar_identifier_list):\n            parameter_list.append(item)\n            p0_list.append(result[i,len(a.SSP_parameters):])\n            x_list.append(x)\n            error_list_mp.append(error_list)\n            element_list_mp.append(elements)\n\n        args = zip(p0_list,parameter_list,x_list,error_list_mp,element_list_mp)\n\n        # 2: Minimize each star ISM parameters in multiprocess\n        p = mp.Pool(len(parameter_list))\n        t = p.map(minimizer_local, args)\n        p.close()\n        p.join()\n        local_parameters = np.vstack(t)\n        result[:,len(a.SSP_parameters):] = local_parameters\n\n        log_list.append(np.copy(result))\n        log_list.append('step %d local minimization' %(counter))\n        local_iteration1 = time.time()\n        print('step %d local minimization took: %2.f seconds' %(counter, local_iteration1 - global_iteration1)) \n\n    log_list.append(posteriors)\n    print(log_list)\n\n    # V: MCMC run\n    ## reshape the result to have global parameters in the front and the local parameters following\n    changing_parameter = list(result[0,:len(a.SSP_parameters)])\n    for i in range(result.shape[0]):\n        changing_parameter.append(list(result[i,len(a.SSP_parameters):]))\n    changing_parameter = np.hstack(changing_parameter)\n    ## jitter the parameters to initialise the chain (add a validation later, i.e. testing that the particular parameters yield a result)\n    mcmc_multi(changing_parameter, error_list, elements)\n    # 1: Free all parameters and optimize common error (SSP should be the same for all stars)\n    # 2: Plug everything into emcee and sample the posterior\n    return log_list\n\ndef mcmc(a):\n    '''\n    Convenience function to use the MCMC. A subdirectory mcmc/ will be created in the current directory and intermediate chains will be stored there.\n    \n    The MCMC will sample the volume of best posterior for the likelihood functions that are declared in parameter.py. Default is ['sol_norm','gas_reservoir','sn_ratio'] which corresponds to 'Sun+' from the paper.\n    '''\n    import time\n    import os\n    import multiprocessing as mp\n    from .optimization import creating_chain, posterior_probability\n    import emcee\n\n    start1 = time.time()\n    directory = 'mcmc/'\n    if os.path.exists(directory):\n        if a.verbose:\n            print('%s already existed. Content might be overwritten' %(directory))\n    else:\n        os.makedirs(directory)\n    \n    a.check_processes = False\n    a.number_of_models_overplotted = 1\n    a.only_net_yields_in_process_tables = False\n    a.testing_output = False\n    a.summary_pdf = False\n    a.nthreads = mp.cpu_count()\n    if a.nthreads == 4:\n        a.nthreads = 2\n    \n    chain = creating_chain(a,np.copy(a.p0))\n    sampler = emcee.EnsembleSampler(a.nwalkers,a.ndim,posterior_probability,threads=a.nthreads, args = [a])\n    pos,prob,state,blobs = sampler.run_mcmc(chain,a.mburn)\n    \n    mean_prob = mean_prob_beginning = np.zeros((a.m))\n    posterior_list = []\n    posterior_std_list = []\n    for i in range(a.m):\n        print('step ', i+1 , 'of ',a.m)\n        pos, prob, state, blobs = sampler.run_mcmc(pos, a.save_state_every, rstate0=state, lnprob0=prob, blobs0 = blobs, storechain = True)\n        np.save('%s/flatchain' %(directory),sampler.chain)\n        np.save('%s/flatlnprobability' %(directory),sampler.lnprobability)\n        np.save('%s/flatblobs' %(directory),sampler.blobs)\n        posterior = np.load('%s/flatlnprobability.npy' %(directory))\n        posterior_list.append(np.mean(posterior, axis = 0)[-1])\n        posterior_std_list.append(np.std(posterior, axis = 0)[-1])\n        np.save('%s/flatmeanposterior' %(directory), posterior_list)\n        np.save('%s/flatstdposterior' %(directory), posterior_std_list)\n        print(np.mean(posterior, axis = 0)[0], np.mean(posterior, axis = 0)[-1])\n        \n        if i>202:\n            print('posterior -1, -100, -200',np.mean(posterior, axis = 0)[-1], np.mean(posterior, axis = 0)[-100], np.mean(posterior, axis = 0)[-200])\n            print('posterior 0, 100, 200',np.mean(posterior, axis = 0)[0], np.mean(posterior, axis = 0)[100], np.mean(posterior, axis = 0)[200])\n        #print(\"Mean acceptance fraction:\", sampler.acceptance_fraction)\n        elapsed1 = (time.time() - start1)\n        print('calculation so far took', elapsed1, ' seconds')\n        if i>a.min_mcmc_iterations and np.abs(np.mean(posterior, axis = 0)[-1] - np.mean(posterior, axis = 0)[-100]) < a.mcmc_tolerance and np.abs(np.mean(posterior, axis = 0)[-1] - np.mean(posterior, axis = 0)[-200]) < a.mcmc_tolerance:\n            break\n    if a.send_email:\n        send_email(a.nthreads, i, np.mean(posterior, axis = 0)[0], np.mean(posterior, axis = 0)[-1], a, elapsed1)\n\n\n\ndef mcmc_multi(changing_parameter, error_list, elements):\n    '''\n    Convenience function to use the MCMC for multiple zones (and therefore multiple observations). A subdirectory mcmc/ will be created in the current directory and intermediate chains will be stored there.\n    The MCMC will sample the volume of best posterior for the likelihood functions that are declared in parameter.py. \n    Default is a list of Proto-sun, Arcturus and B-stars. The MCMC uses many walkers and can use multiple threads. Each walker will evaluate a series of Chempy zones and add their posterior together which then will be returned.\n    \n    INPUT:\n\n    changing_parameter = the parameter vector for initialization (will usually be found from minimization before). The initial chain will be created by jittering slightly the initial parameter guess\n\n    error_list = the vector of element errors\n\n    elements = the corresponding element symbols\n\n    OUTPUT:\n\n    The function will create a folder and store the chain as well as the predicted element values\n\n    The MCMC stops when the convergence criteria is met, which is when the median posterior of all walkers does not change much inbetween 200 steps anymore.\n    '''\n    import time\n    import os\n    import multiprocessing as mp\n    from .cem_function import  posterior_function_many_stars\n    from .parameter import ModelParameters\n    import emcee\n\n    a = ModelParameters()\n    start1 = time.time()\n    directory = 'mcmc/'\n    if os.path.exists(directory):\n        if a.verbose:\n            print('%s already existed. Content might be overwritten' %(directory))\n    else:\n        os.makedirs(directory)\n    \n    nthreads = mp.cpu_count()\n    if nthreads == 4:\n        nthreads = 2\n    ndim = len(changing_parameter)\n    a.nwalkers = max(a.nwalkers, int(ndim*2))\n    chain = np.empty(shape = (a.nwalkers,ndim))\n    \n    for i in range(a.nwalkers):\n        result = -np.inf\n        while result == -np.inf:\n            jitter = np.random.normal(loc = 0, scale = 0.001, size = ndim)\n            result, dummy = posterior_function_many_stars(changing_parameter + jitter,error_list,elements)\n        chain[i] = changing_parameter + jitter\n    print('Chain created')\n    sampler = emcee.EnsembleSampler(a.nwalkers,ndim,posterior_function_many_stars,threads=nthreads, args = [error_list,elements])\n    pos,prob,state,blobs = sampler.run_mcmc(chain,a.mburn)\n    \n    mean_prob = mean_prob_beginning = np.zeros((a.m))\n    posterior_list = []\n    posterior_std_list = []\n    for i in range(a.m):\n        print('step ', i+1 , 'of ',a.m)\n        pos, prob, state, blobs = sampler.run_mcmc(pos, a.save_state_every, rstate0=state, lnprob0=prob, blobs0 = blobs, storechain = True)\n        np.save('%s/flatchain' %(directory),sampler.chain)\n        np.save('%s/flatlnprobability' %(directory),sampler.lnprobability)\n        np.save('%s/flatblobs' %(directory),sampler.blobs)\n        posterior = np.load('%s/flatlnprobability.npy' %(directory))\n        posterior_list.append(np.mean(posterior, axis = 0)[-1])\n        posterior_std_list.append(np.std(posterior, axis = 0)[-1])\n        np.save('%s/flatmeanposterior' %(directory), posterior_list)\n        np.save('%s/flatstdposterior' %(directory), posterior_std_list)\n        print(np.mean(posterior, axis = 0)[0], np.mean(posterior, axis = 0)[-1])\n        \n        if i>202:\n            print('posterior -1, -100, -200',np.mean(posterior, axis = 0)[-1], np.mean(posterior, axis = 0)[-100], np.mean(posterior, axis = 0)[-200])\n            print('posterior 0, 100, 200',np.mean(posterior, axis = 0)[0], np.mean(posterior, axis = 0)[100], np.mean(posterior, axis = 0)[200])\n        #print(\"Mean acceptance fraction:\", sampler.acceptance_fraction)\n        elapsed1 = (time.time() - start1)\n        print('calculation so far took', elapsed1, ' seconds')\n        if i>a.min_mcmc_iterations and np.abs(np.mean(posterior, axis = 0)[-1] - np.mean(posterior, axis = 0)[-100]) < a.mcmc_tolerance and np.abs(np.mean(posterior, axis = 0)[-1] - np.mean(posterior, axis = 0)[-200]) < a.mcmc_tolerance:\n            break\n    if a.send_email:\n        send_email(nthreads, i, np.mean(posterior, axis = 0)[0], np.mean(posterior, axis = 0)[-1], a, elapsed1)\n\n\ndef send_email(thread_count, iteration_count, posterior_beginning, posterior_end, parameters, time):\n    from email.MIMEMultipart import MIMEMultipart\n    from email.MIMEText import MIMEText\n    import smtplib\n\n\n    fromaddr = \"pythonspeaking@gmail.com\"\n    toaddr = \"philcox@mpia.de\"\n    msg = MIMEMultipart()\n    msg['From'] = fromaddr\n    msg['To'] = toaddr\n    msg['Subject'] = \"Threads = %d, Run finished after %.2f hours\" %(thread_count, time/3600.)\n    body = \"After %.1f hours %d threads produced %d iterations.\\n The posterior at beginning was: %.2f. The posterior now is: %.2f.\\n The stellar identifier list = %s.\\n The error marginalization is %s \\n  The yields are: %s %s %s \\n \" %(time/3600., thread_count, iteration_count, posterior_beginning, posterior_end, str(parameters.stellar_identifier_list), str(parameters.error_marginalization), parameters.yield_table_name_sn2, parameters.yield_table_name_agb, parameters.yield_table_name_1a)\n    msg.attach(MIMEText(body, 'plain'))\n\n    server = smtplib.SMTP('smtp.gmail.com', 587)\n    server.ehlo()\n    server.starttls()\n    server.ehlo()\n    server.login(\"pythonspeaking@gmail.com\", \"MPIA_Server_runs\")\n    text = msg.as_string()\n    server.sendmail(fromaddr, toaddr, text) \n    \ndef mcmc_quick(changing_parameter,elements,preload):\n    '''\n    Convenience function to use the MCMC for one zone. A subdirectory mcmc/ will be created in the current directory and intermediate chains will be stored there.\n    The MCMC will sample the volume of best posterior for the likelihood functions that are declared in parameter.py. \n    This is a cut down version to speed up MCMC for one star only\n    INPUT:\n\n    changing_parameter = the parameter vector for initialization (will usually be found from minimization before). The initial chain will be created by jittering slightly the initial parameter guess\n\n    error_list = the vector of element errors\n\n    elements = the corresponding element symbols\n\n    OUTPUT:\n\n    The function will create a folder and store the chain as well as the predicted element values\n\n    The MCMC stops when the convergence criteria is met, which is when the median posterior of all walkers does not change much inbetween 200 steps anymore.\n    '''\n    import time\n    import os\n    import multiprocessing as mp\n    from .cem_function import  posterior_function_mcmc_quick\n    from .score_function import preload_params_mcmc\n    from .parameter import ModelParameters\n    import emcee\n\n    a = ModelParameters()\n    start1 = time.time()\n    directory = 'mcmc/'\n    if os.path.exists(directory):\n        if a.verbose:\n            print('%s already existed. Content might be overwritten' %(directory))\n    else:\n        os.makedirs(directory)\n    \n    nthreads = mp.cpu_count()\n    if nthreads == 4:\n        nthreads = 2\n    ndim = len(changing_parameter)\n    a.nwalkers = max(a.nwalkers, int(ndim*2))\n    chain = np.empty(shape = (a.nwalkers,ndim))\n    \n    for i in range(a.nwalkers):\n        result = -np.inf\n        while result == -np.inf:\n            jitter = np.random.normal(loc = 0, scale = 0.001, size = ndim)\n            result = posterior_function_mcmc_quick(changing_parameter + jitter,elements,preload)\n        chain[i] = changing_parameter + jitter\n\n    pool=mp.Pool()\n    sampler = emcee.EnsembleSampler(a.nwalkers,ndim,posterior_function_mcmc_quick,threads=nthreads, args = [elements,preload],pool=pool)\n    pos,prob,state,blobs = sampler.run_mcmc(chain,a.mburn)\n        \n    \n    mean_prob = mean_prob_beginning = np.zeros((a.m))\n    posterior_list = []\n    posterior_std_list = []\n    for i in range(a.m):\n        print('step ', i+1 , 'of ',a.m)\n        pos, prob, state, blobs = sampler.run_mcmc(pos, a.save_state_every, rstate0=state, lnprob0=prob, blobs0 = blobs, storechain = True)\n    #   np.save('%s/flatchain' %(directory),sampler.chain)\n    #   np.save('%s/flatlnprobability' %(directory),sampler.lnprobability)\n    #   np.save('%s/flatblobs' %(directory),sampler.blobs)\n    #   posterior = np.load('%s/flatlnprobability.npy' %(directory))\n        posterior = sampler.lnprobability\n        posterior_list.append(np.mean(posterior, axis = 0)[-1])\n        posterior_std_list.append(np.std(posterior, axis = 0)[-1])\n    #   np.save('%s/flatmeanposterior' %(directory), posterior_list)\n    #   np.save('%s/flatstdposterior' %(directory), posterior_std_list)\n        print(np.mean(posterior, axis = 0)[0], np.mean(posterior, axis = 0)[-1])\n        \n        #if i>202:\n            #print('posterior -1, -100, -200',np.mean(posterior, axis = 0)[-1], np.mean(posterior, axis = 0)[-100], np.mean(posterior, axis = 0)[-200])\n            #print('posterior 0, 100, 200',np.mean(posterior, axis = 0)[0], np.mean(posterior, axis = 0)[100], np.mean(posterior, axis = 0)[200])\n        #print(\"Mean acceptance fraction:\", sampler.acceptance_fraction)\n        elapsed1 = (time.time() - start1)\n        print('calculation so far took', elapsed1, ' seconds')\n        if i>a.min_mcmc_iterations and np.abs(np.mean(posterior, axis = 0)[-1] - np.mean(posterior, axis = 0)[-100]) < a.mcmc_tolerance and np.abs(np.mean(posterior, axis = 0)[-1] - np.mean(posterior, axis = 0)[-200]) < a.mcmc_tolerance:\n            break\n    np.save('%s/flatchain' %(directory),sampler.chain)\n    np.save('%s/flatlnprobability' %(directory),sampler.lnprobability)\n    np.save('%s/flatblobs' %(directory),sampler.blobs)\n    posterior = sampler.lnprobability\n    #posterior = np.load('%s/flatlnprobability.npy' %(directory))\n    posterior_list.append(np.mean(posterior, axis = 0)[-1])\n    posterior_std_list.append(np.std(posterior, axis = 0)[-1])\n    np.save('%s/flatmeanposterior' %(directory), posterior_list)\n    np.save('%s/flatstdposterior' %(directory), posterior_std_list)\n    pool.close()    \n    if a.send_email:\n        send_email(nthreads, i, np.mean(posterior, axis = 0)[0], np.mean(posterior, axis = 0)[-1], a, elapsed1)\n\n\n    \ndef single_star_optimization():\n    '''\n    This function will optimize the parameters of a single zone quickly\n\n    INPUT: \n\n    a = will be loaded from parameter.py (prepare all variables there)\n\n    OUTPUT:\n\n    log_list = a list of intermediate results (so far only for debugging)\n    '''\n    import time\n    #import multiprocessing as mp\n    from .optimization import minimizer_initial_quick\n    from .cem_function import global_optimization_error_returned\n    from .parameter import ModelParameters\n    from .score_function import preload_params_mcmc\n    \n    # For testing\n    import warnings\n    warnings.filterwarnings(\"ignore\")\n        \n    a = ModelParameters()\n    preload = preload_params_mcmc()\n    \n    print(a.stellar_identifier_list)\n    start_time = time.time()\n\n    log_list = []\n    # I: Minimization for each star seperately\n    # 1: for each star make initial conditions (each star needs other model parameters) \n    parameter_list = []\n    for item in a.stellar_identifier_list:\n        parameter_list.append(item)\n    # 2: call posterior_function_for_minimization with scipy.optimize.minimize in multiprocess for each star and recover the found parameters\n    #p = mp.Pool(len(parameter_list))\n    #t = p.map(minimizer_initial_quick, parameter_list)\n    #p.close()\n    #p.join()\n    #result = np.vstack(t)\n    \n    result  = minimizer_initial_quick(parameter_list)\n    \n    log_list.append(np.copy(result))\n    log_list.append('initial minimization')\n    initial = time.time()\n    print('first minimization for each star separately took: %2.f seconds' %(initial - start_time))\n\n    # IV: repeat II and III until posterior does not change much\n    #result[:,:len(a.SSP_parameters)] = np.mean(result[:,:len(a.SSP_parameters)], axis = 0)\n    #posteriors = []\n    #counter = 0\n    #while True:\n    #   counter += 1\n    #   if len(posteriors) > 1:\n    #     if np.abs(posteriors[-1] - posteriors[-2]) < a.gibbs_sampler_tolerance:\n    #      break\n    #     if len(posteriors) > a.gibbs_sampler_maxiter:\n    #      break\n\n    #   initial = time.time()\n        # II: Global parameter minimization:\n        # 1: only SSP parameters free. Use mean SSP parameter values and individual (but fixed ISM parameter values)\n    #   changing_parameter = result[0,:len(a.SSP_parameters)]\n        # 2: Call each star in multiprocess but only return the predictions\n        # 3: Calculate the likelihood for each star and optimize the common model error (is all done within minimizer global, which is calling 'global optimization')\n    #   x = minimizer_global(changing_parameter,  a.tol_minimization, a.maxiter_minimization, a.verbose, result)\n\n        # 4: return global SSP parameters and common model error\n    #   posterior, error_list, elements = global_optimization_error_returned(x, result)\n    #   posteriors.append(posterior)\n    #   print(posteriors)\n\n    #   global_iteration1 = time.time()\n    #   print('step %d global minimization took: %2.f seconds' %(counter, global_iteration1 - initial))   \n\n        # III: Local parameter minimization:\n        # 1: Use fixed global parameters and fixed common errors make initial conditions\n    #   result[:,:len(a.SSP_parameters)] = x\n\n    #   log_list.append((np.copy(x),posterior))\n    #   log_list.append('step %d global minimization' %(counter))\n\n    #   p0_list = []\n    #   parameter_list = []\n    #   x_list = []\n    #   error_list_mp = []\n    #   element_list_mp = []\n\n    #   for i,item in enumerate(a.stellar_identifier_list):\n    #     parameter_list.append(item)\n    #     p0_list.append(result[i,len(a.SSP_parameters):])\n    #     x_list.append(x)\n    #     error_list_mp.append(error_list)\n    #     element_list_mp.append(elements)\n\n    #   args = zip(p0_list,parameter_list,x_list,error_list_mp,element_list_mp)\n\n        # 2: Minimize each star ISM parameters in multiprocess\n    #   p = mp.Pool(len(parameter_list))\n    #   t = p.map(minimizer_local, args)\n    #   p.close()\n    #   p.join()\n    #   local_parameters = np.vstack(t)\n    #   result[:,len(a.SSP_parameters):] = local_parameters\n\n    #   log_list.append(np.copy(result))\n    #   log_list.append('step %d local minimization' %(counter))\n    #   local_iteration1 = time.time()\n    #   print('step %d local minimization took: %2.f seconds' %(counter, local_iteration1 - global_iteration1))   \n\n    #log_list.append(posteriors)\n    #print(log_list)\n\n    # V: MCMC run\n    ## reshape the result to have global parameters in the front and the local parameters following\n    #changing_parameter = list(result[0,:len(a.SSP_parameters)])\n    \n    elements = np.unique(a.elements_to_trace,preload.wildcard.dtype.names)\n    changing_parameter = list(result)\n\n    #for i in range(result.shape[0]):\n    #   changing_parameter.append(list(result[i,len(a.SSP_parameters):]))\n    \n    changing_parameter = np.hstack(changing_parameter)\n    \n    ## jitter the parameters to initialise the chain (add a validation later, i.e. testing that the particular parameters yield a result)\n    \n    mcmc_quick(changing_parameter, elements,preload)\n    \n    # 1: Free all parameters and optimize common error (SSP should be the same for all stars)\n    # 2: Plug everything into emcee and sample the posterior\n    return log_list\n\n\ndef scoring_wrapper():\n    \"\"\"\n    NO LONGER USED \n    This function will calculate Bayes and CV scores for yield set, using the code in score_function.py.\n    \n    The neural network must be trained beforehand using training_data and create_network    \n    \n    Main outputs are labelled .npz files in the Scores/ file.\n    \n    MUST set a.UseNeural = True for this and select correct dataset.\n    \"\"\"\n    from Chempy.neural import training_data,create_network\n    import time\n    from Chempy.parameter import ModelParameters\n    from Chempy.score_function import CV_wrapper, Bayes_wrapper\n    init_time = time.time()\n    a = ModelParameters()\n    \n    print('Step 1 (at time %.2f s): Calculate Bayes score' %(time.time()-init_time))\n    Bayes_wrapper()\n    \n    print('Step 2 (at time %.2f s): Calculate cross-validation score' %(time.time()-init_time))\n    CV_wrapper()\n    \n    print('Process complete in time %.2f s' %(time.time()-init_time))   \n    return None \n    \n", "meta": {"hexsha": "035ef3d222fabd47d9af524c627b9e8bd3b293ed", "size": 40713, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chempy/wrapper.py", "max_stars_repo_name": "oliverphilcox/ChempyMulti", "max_stars_repo_head_hexsha": "1ab0d0c56a03c4f4b710ee8f0142bcccc7e84e22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-09-09T12:25:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T07:01:55.000Z", "max_issues_repo_path": "Chempy/wrapper.py", "max_issues_repo_name": "oliverphilcox/ChempyMulti", "max_issues_repo_head_hexsha": "1ab0d0c56a03c4f4b710ee8f0142bcccc7e84e22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chempy/wrapper.py", "max_forks_repo_name": "oliverphilcox/ChempyMulti", "max_forks_repo_head_hexsha": "1ab0d0c56a03c4f4b710ee8f0142bcccc7e84e22", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1761297798, "max_line_length": 494, "alphanum_fraction": 0.6815759094, "include": true, "reason": "import numpy,from numpy", "num_tokens": 10320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.16990778636624457}}
{"text": "# this is out of date, and no longer generates data that works for the analysis\n\nimport numpy as np\nimport networkx as nx\nimport json\nimport random\nimport string\nimport multiprocessing\n\n\n\ndef play(game_data, n_steps=100, treatment_id=\"\", adopt=None, forget=None):\n    \"\"\" play a single round of the game \"\"\"\n\n    def setup_game(game_data):\n        # set up agents\n        g = nx.from_dict_of_lists(game_data['neighbors'])\n\n        # give starting information\n        nx.set_node_attributes(\n            g,\n            name='M',  # M for mind/memory\n            values={i: nx.from_edgelist([game_data['clues'][bf]['nodes'] for bf in game_data['beliefs'][str(i)]])\n                    for i in g}\n        )\n\n        nx.set_node_attributes(\n            g,\n            name='F',  # F for forgetory\n            values={i: nx.Graph() for i in g}\n        )\n\n        ### this stuff is just for generating data that mirrors the experiment\n        # save initial state\n        nx.set_node_attributes(\n            g,\n            name=\"initialState\",\n            values={i: {\"promising_leads\": {\"clueIDs\": game_data['beliefs'][str(i)]},\n                        \"dead_ends\": {\"clueIDs\": []}\n                        }\n                    for i in g}\n        )\n\n        # assign random identifiers\n        nx.set_node_attributes(\n            g,\n            name=\"_id\",\n            values={i: ''.join(random.choices(string.ascii_letters + string.digits, k=16))\n                    for i in g}\n        )\n\n        # initialize logs\n        nx.set_node_attributes(\n            g,\n            name='data.log',  # M for mind\n            values={i: list() for i in g}\n        )\n\n        return g\n\n    def adopt(g, ego, edge, t, target):\n\n        if g.node[ego]['M'].has_edge(*edge):\n            return False\n\n        M = g.node[ego]['M']\n\n        exposers = [nb for nb in g[ego] if edge in g.node[nb]['M'].edges()]\n        exposure = len(exposers)\n        if exposure == 0:\n            return False\n\n        ends_present = len(set(edge).intersection(set(M.nodes())))\n\n        if M.has_node(edge[0]) and M.has_node(edge[1]):\n            #path_list = nx.all_simple_paths(M, *edge, cutoff=4)\n            path_list = nx.all_simple_paths(M, *edge, cutoff=2)\n        else:\n            path_list = []\n\n        path_counts = {i: 0 for i in range(6)}\n        for path in path_list:\n            path_counts[len(path)] += 1\n\n        n_beliefs = len(M.edges())\n\n        baseline = .01 / (100)\n        c_exposure = np.log(3)  # for each exposure multiply the likelihood by 1.5\n        c_ends_present = np.log(5)\n        c_len2paths = np.log(10)\n        c_len3paths = np.log(3)\n        c_len4paths = np.log(2)\n        c_offtarget = np.log(.6)\n\n        likelihood = baseline * np.exp(\n             c_exposure * exposure +\n            c_ends_present * ends_present +\n            c_len2paths * path_counts[2] +\n            c_len3paths * path_counts[3] +\n            c_len4paths * path_counts[4] +\n            c_offtarget * np.sign(n_beliefs - target)*(n_beliefs-target)**2\n        )\n\n        #adoption = path_counts[2] > 0\n\n        adoption = np.random.binomial(1, np.min([likelihood, .9999])) == 1\n\n        if adoption:\n            source = g.node[np.random.choice(exposers)][\"_id\"]\n            g.node[ego]['data.log'].append({\n                \"event\": \"drop\",\n                \"data\": {\n                    \"clue\": lookup_cluename(edge),\n                    \"source\": source,\n                    \"dest\": \"promising_leads\",\n                    \"destIndex\": 0\n                },\n                \"at\": t  # str(datetime.datetime.now()) # t + np.random.rand()  # unique timestamp within the second\n            })\n\n        return adoption\n\n    def forget(g, ego, edge, t, target):\n        if not g.node[ego]['M'].has_edge(*edge):\n            return False\n\n        M = g.node[ego]['M']\n\n        exposers = [nb for nb in g[ego] if edge in g.node[nb]['M'].edges()]\n        exposure = len(exposers)\n        if exposure == 0:\n            return False\n\n        ends_present = len(set(edge).intersection(set(M.nodes())))\n\n        if M.has_node(edge[0]) and M.has_node(edge[1]):\n            path_list = nx.all_simple_paths(M, *edge, cutoff=4)\n        else:\n            path_list = []\n\n        path_counts = {i: 0 for i in range(6)}\n        for path in path_list:\n            path_counts[len(path)] += 1\n\n        # path_counts = pd.Series(pd.Series([len(pth) - 1 for pth in path_list]).value_counts(),\n        #                         index=range(2, 5)).fillna(0)\n\n        n_beliefs = len(M.edges())\n\n        baseline = 10 / 100\n        c_exposure = np.log(1/3)  # for each exposure multiply the likelihood by 1.5\n        c_ends_present = np.log(1/5)\n        c_len2paths = np.log(1/10)\n        c_len3paths = np.log(1/3)\n        c_len4paths = np.log(1/2)\n        c_offtarget = np.log(1/.6)\n\n        likelihood = baseline * np.exp(\n            c_exposure * exposure +\n            c_ends_present * ends_present +\n            c_len2paths * path_counts[2] +\n            c_len3paths * path_counts[3] +\n            c_len4paths * path_counts[4] +\n            c_offtarget * np.sign(n_beliefs - target)*(n_beliefs-target)**2\n        )\n\n        forgetion = np.random.binomial(1, np.min([likelihood, .99])) == 1\n\n        if forgetion:\n            g.node[ego]['data.log'].append({\n                \"event\": \"drop\",\n                \"data\": {\n                    \"clue\": lookup_cluename(edge),\n                    \"source\": \"promising_leads\",\n                    \"dest\": \"dead_ends\",\n                    \"destIndex\": 0\n                },\n                \"at\": t  # + np.random.rand()  # unique timestamp within the second\n            })\n\n        return forgetion\n\n    target = game_data['parameters']['target']\n    g = setup_game(game_data)\n\n    # useful helper functions\n    beliefs = [cl[\"nodes\"] for _, cl in game_data[\"clues\"].items()]\n    hashtable = {hash(tuple(sorted(clue[\"nodes\"]))): key for key, clue in game_data[\"clues\"].items()}\n\n    def lookup_cluename(edge):\n        return hashtable[hash(tuple(sorted(edge)))]\n\n    # play the game\n    for step in range(n_steps):\n        substep = 0\n        for ego in np.random.permutation(g):  # select ego in random order\n            for edge in np.random.permutation(beliefs):  # select a belief in random order to propagate\n                substep += .000001  # ensure proper ordering\n                if adopt(g, ego, edge, step + substep, target):\n                    g.node[ego]['M'].add_edges_from([edge])\n                    if g.node[ego]['F'].has_edge(*edge):\n                        g.node[ego]['F'].remove_edges_from([edge])\n                substep += .000001  # so you can't have a forget event at the same time as an adopt event\n                if forget(g, ego, edge, step + substep, target):\n                    g.node[ego]['M'].remove_edges_from([edge])\n                    g.node[ego]['F'].add_edges_from([edge])\n\n    # save to json for postprocessing (keep as string here)\n    player_json = []\n    for n in g:\n        player_object = {\n            \"_id\": str(g.node[n][\"_id\"]),\n            \"initialState\": g.node[n][\"initialState\"],\n            \"log\": g.node[n][\"log\"],\n            \"alterIDs\": [g.node[nb][\"_id\"] for nb in g.neighbors(n)],\n            \"notebooks\": {\n                \"promising_leads\": {\"clueIDs\": [lookup_cluename(edge) for edge in g.node[n]['M'].edges()]},\n                \"dead_ends\": {\"clueIDs\": [lookup_cluename(edge) for edge in g.node[n]['F'].edges()]}\n            }\n        }\n        json_string = json.dumps(player_object)\n        player_json.append(json_string)\n\n    game_object = {\"_id\": ''.join(random.choices(string.ascii_letters + string.digits, k=16)),\n                   \"playerIds\": [g.node[n]['_id'] for n in g],\n                   \"treatmentId\": treatment_id,\n                   \"gameSetupId\": game_data[\"gameSetupId\"],\n                   \"createdAt\": 0,\n                   \"finishedAt\": n_steps}\n\n    game_json = [json.dumps(game_object)]\n\n    return game_json, player_json\n\n\ndef simulate_experiment(experiment_filename):\n    \"\"\"Run all the games in the experiment\"\"\"\n    with open(experiment_filename, 'r') as infile:\n        experiment = json.load(infile)\n\n    with multiprocessing.Pool() as p:\n        game_results = p.map(play, experiment[\"games\"].values())\n\n    #game_results = [play(g) for g in experiment[\"games\"].values()]\n\n    game_json_list = []\n    player_json_list = []\n    for res in game_results:\n        game_json_list += res[0]\n        player_json_list += res[1]\n\n    return game_json_list, player_json_list\n", "meta": {"hexsha": "e108d7432c1e5eaca4c1ae8864f8ce1bf6bd9f08", "size": 8562, "ext": "py", "lang": "Python", "max_stars_repo_path": "simulation/simulate_experiment.py", "max_stars_repo_name": "JamesPHoughton/detective-game-interdependent-diffusion", "max_stars_repo_head_hexsha": "36e3abd8c9bbf354dd10c6af8876845c62f6fad9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulation/simulate_experiment.py", "max_issues_repo_name": "JamesPHoughton/detective-game-interdependent-diffusion", "max_issues_repo_head_hexsha": "36e3abd8c9bbf354dd10c6af8876845c62f6fad9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulation/simulate_experiment.py", "max_forks_repo_name": "JamesPHoughton/detective-game-interdependent-diffusion", "max_forks_repo_head_hexsha": "36e3abd8c9bbf354dd10c6af8876845c62f6fad9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8418972332, "max_line_length": 116, "alphanum_fraction": 0.5335202056, "include": true, "reason": "import numpy,import networkx", "num_tokens": 2101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.29421497216298875, "lm_q1q2_score": 0.16990777851357036}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"This module define the Frames available for computation and their relations\nto each other.\n\nThe relations may be circular, thanks to the use of the Node class.\n\n.. code-block:: text\n\n    ,---.          ,-------.        ,----.\n    |G50|---bias---|EME2000|..bias..|GCRF|\n    `---'          `-------'        `----'\n                       |              |\n                   Precession         |\n                       |              |\n                     ,---.        Precession\n                     |MOD|            +\n                     `---'         Nutation\n                       |     + model corrections\n                    Nutation          |\n              + model corrections     |\n                       |              |\n    ,----.           ,---.         ,----.\n    |TEME|--Equinox--|TOD|         |CIRF|\n    `----'           `---'         `----'\n                       |              |\n                 Sideral time   Sideral time\n                       |              |\n                     ,---.         ,----.\n                     |PEF|         |TIRF|\n                     `---'         `----'\n                        \\\\            /\n                    IAU 1980       IAU 2010\n           Earth Orientation       Earth Orientation\n                  Parameters       Parameters\n                           \\\\     /\n         ,-----.            ,----.\n         |WGS84|--identity--|ITRF|\n         `-----'            `----'\n\"\"\"\n\nimport sys\nimport logging\nimport numpy as np\n\nfrom ..errors import UnknownFrameError\nfrom ..constants import Earth\nfrom ..utils.matrix import rot3\nfrom ..utils.node import Node\nfrom . import iau1980, iau2010\nfrom .local import to_qsw, to_tnw\n\nCIO = [\"ITRF\", \"TIRF\", \"CIRF\", \"GCRF\"]\nIAU1980 = [\"TOD\", \"MOD\"]\nOTHER = [\"EME2000\", \"TEME\", \"WGS84\", \"PEF\", \"G50\"]\n\n__all__ = CIO + IAU1980 + OTHER + [\"get_frame\"]\n\nlog = logging.getLogger(__name__)\n\n\nclass FrameCache(dict):\n    \"\"\"This class is here to emulate module behavior for dynamically\n    created frames.\n\n    It's useful when pickle is involved (e.g. multiprocessing)\n    \"\"\"\n\n    def __getattr__(self, name):\n        if name not in self:\n            raise AttributeError(name)\n        return self[name]\n\n\ndynamic = FrameCache()\n\"\"\"This dictionary contains all the frames. Those defined here, and those created on the fly\nby the developer.\n\"\"\"\n\nsys.modules[__name__ + \".dynamic\"] = dynamic\n\n\ndef get_frame(frame):\n    \"\"\"Frame factory\n\n    Args:\n        frame (str): name of the desired frame\n    Return:\n        ~beyond.frames.frames.Frame\n    \"\"\"\n    if frame not in dynamic.keys():\n        raise UnknownFrameError(frame)\n\n    return dynamic[frame]\n\n\nclass _MetaFrame(type, Node):\n    \"\"\"This MetaClass is here to join the behaviors of ``type`` and ``Node``\n    \"\"\"\n\n    def __init__(cls, name, bases, dct):\n\n        bypass = dct.pop(\"bypass\", False)\n\n        super(_MetaFrame, cls).__init__(name, bases, dct)\n        super(type, cls).__init__(name)\n\n        if not bypass and cls.__name__ in dynamic:\n            log.warning(\n                \"A frame with the name '%s' is already registered. Overriding\"\n                % cls.__name__\n            )\n\n        cls.__module__ = __name__ + \".dynamic\"\n\n        # Making the frame available to the get_frame function\n        dynamic[cls.__name__] = cls\n\n    def __repr__(cls):  # pragma: no cover\n        return \"<Frame '{}'>\".format(cls.name)\n\n\nclass Frame(metaclass=_MetaFrame):\n    \"\"\"Frame base class\n    \"\"\"\n\n    center = Earth\n\n    def __init__(self, date, orbit):\n        \"\"\"\n        Args:\n            date (~beyond.utils.Date)\n            orbit (numpy.ndarray)\n        \"\"\"\n        self.date = date\n        self.orbit = orbit\n\n    def __str__(self):  # pragma: no cover\n        return self.name\n\n    def __repr__(self):  # pragma: no cover\n        return \"<Frame obj '{}'>\".format(self.__class__.__name__)\n\n    @classmethod\n    def _convert(cls, x=None, y=None):\n        m = np.identity(6)\n\n        if x is not None:\n            m[:3, :3] = x\n        if y is not None:\n            m[3:, 3:] = y\n\n        return m\n\n    def transform(self, new_frame):\n        \"\"\"Change the frame of the orbit\n\n        Args:\n            new_frame (str)\n        Return:\n            numpy.ndarray\n        \"\"\"\n\n        steps = self.__class__.steps(new_frame)\n\n        orbit = self.orbit\n\n        for _from, _to in steps:\n\n            from_obj = _from(self.date, orbit)\n            direct = \"_to_%s\" % _to\n\n            if hasattr(from_obj, direct):\n                rotation, offset = getattr(from_obj, direct)()\n            else:\n                to_obj = _to(self.date, orbit)\n                inverse = \"_to_%s\" % _from\n                if hasattr(to_obj, inverse):\n                    rotation, offset = getattr(to_obj, inverse)()\n                    rotation = rotation.T\n                    offset = -offset\n                else:\n                    raise NotImplementedError(\n                        \"Unknown transformation {} to {}\".format(_from, _to)\n                    )\n\n            if getattr(_from, \"_rotation_before_translation\", False):\n                # In case of topocentric frame, the rotation is done before the translation\n                orbit = offset + (rotation @ orbit)\n            else:\n                orbit = rotation @ (offset + orbit)\n\n        return orbit\n\n\nclass TEME(Frame):\n    \"\"\"True Equator Mean Equinox\"\"\"\n\n    orientation = \"TEME\"\n\n    def _to_TOD(self):\n        equin = iau1980.equinox(\n            self.date, eop_correction=False, terms=4, kinematic=False\n        )\n        m = rot3(-np.deg2rad(equin))\n        return self._convert(m, m), np.zeros(6)\n\n\nclass GTOD(Frame):\n    \"\"\"Greenwich True Of Date\"\"\"\n\n    orientation = \"GTOD\"\n\n\nclass WGS84(Frame):\n    \"\"\"World Geodetic System 1984\"\"\"\n\n    orientation = \"WGS84\"\n\n    def _to_ITRF(self):\n        return np.identity(6), np.zeros(6)\n\n\nclass PEF(Frame):\n    \"\"\"Pseudo Earth Fixed\"\"\"\n\n    orientation = \"PEF\"\n\n    def _to_TOD(self):\n        m = iau1980.sideral(self.date, model=\"apparent\", eop_correction=False)\n        offset = np.zeros(6)\n        offset[3:] = np.cross(iau1980.rate(self.date), self.orbit[:3])\n        return self._convert(m, m), offset\n\n\nclass TOD(Frame):\n    \"\"\"True (Equator) Of Date\"\"\"\n\n    orientation = \"TOD\"\n\n    def _to_MOD(self):\n        m = iau1980.nutation(self.date, eop_correction=False)\n        return self._convert(m, m), np.zeros(6)\n\n\nclass MOD(Frame):\n    \"\"\"Mean (Equator) Of Date\"\"\"\n\n    orientation = \"MOD\"\n\n    def _to_EME2000(self):\n        m = iau1980.precesion(self.date)\n        return self._convert(m, m), np.zeros(6)\n\n\nclass EME2000(Frame):\n    \"\"\"EME2000 inertial frame (also known as J2000)\"\"\"\n\n    orientation = \"EME2000\"\n\n\nclass ITRF(Frame):\n    \"\"\"International Terrestrial Reference Frame\"\"\"\n\n    orientation = \"ITRF\"\n\n    def _to_PEF(self):\n        m = iau1980.earth_orientation(self.date)\n        return self._convert(m, m), np.zeros(6)\n\n    def _to_TIRF(self):\n        m = iau2010.earth_orientation(self.date)\n        return self._convert(m, m), np.zeros(6)\n\n\nclass TIRF(Frame):\n    \"\"\"Terrestrial Intermediate Reference Frame\"\"\"\n\n    orientation = \"TIRF\"\n\n    def _to_CIRF(self):\n        m = iau2010.sideral(self.date)\n        offset = np.zeros(6)\n        offset[3:] = np.cross(iau2010.rate(self.date), self.orbit[:3])\n        return self._convert(m, m), offset\n\n\nclass CIRF(Frame):\n    \"\"\"Celestial Intermediate Reference Frame\"\"\"\n\n    orientation = \"CIRF\"\n\n    def _to_GCRF(self):\n        m = iau2010.precesion_nutation(self.date)\n        return self._convert(m, m), np.zeros(6)\n\n\nclass GCRF(Frame):\n    \"\"\"Geocentric Celestial Reference Frame\"\"\"\n\n    orientation = \"GCRF\"\n\n\nclass G50(Frame):\n    \"\"\"Gamma50 Reference Frame\n    \"\"\"\n\n    orientation = \"G50\"\n\n    def _to_EME2000(self):\n\n        m = [\n            [0.9999256794956877, -0.0111814832204662, -0.0048590038153592],\n            [0.0111814832391717, 0.9999374848933135, -0.0000271625947142],\n            [0.0048590037723143, -0.0000271702937440, 0.9999881946023742],\n        ]\n\n        return self._convert(m, m), np.zeros(6)\n\n\ndef orbit2frame(name, ref_orbit, orientation=None, center=None, bypass=False):\n    \"\"\"Create a frame based on a Orbit or Ephem object.\n\n    Args:\n        name (str): Name to give the created frame\n        ref_orbit (Orbit or Ephem):\n        orientation (str): Orientation of the created frame\n        bypass (bool): By-pass the warning when creating a frame with an already\n            taken name\n    Return:\n        Frame:\n\n    If orientation is ``None``, the new frame will keep the orientation of the\n    reference frame of the Orbit and move along with the orbit.\n    Other acceptable values are ``\"QSW\"`` (and its aliases \"LVLH\" and \"RSW\") or ``\"TNW\"``.\n\n    See :py:func:`~beyond.frames.local.to_qsw` and :py:func:`~beyond.frames.local.to_tnw`\n    for informations regarding these orientations.\n    \"\"\"\n\n    if orientation is None:\n        orientation = ref_orbit.frame.orientation\n    elif orientation.upper() in (\"RSW\", \"LVLH\"):\n        orientation = \"QSW\"\n    elif orientation.upper() not in (\"QSW\", \"TNW\"):\n        raise ValueError(\"Unknown orientation '%s'\" % orientation)\n\n    if center is None:\n        center = Earth\n\n    def _to_parent_frame(self):\n        \"\"\"Conversion from orbit frame to parent frame\n        \"\"\"\n        offset = ref_orbit.propagate(self.date).base.copy()\n\n        if orientation.upper() in (\"QSW\", \"TNW\"):\n\n            # propagation of the reference orbit to the date of the\n            # converted orbit\n            orb = ref_orbit.propagate(self.date)\n\n            m = to_qsw(orb) if orientation.upper() == \"QSW\" else to_tnw(orb)\n\n            # we transpose the matrix because it represents the conversion\n            # from inertial to local frame, and we'd like the other way around\n            rotation = Frame._convert(m, m).T\n        else:\n            # The orientation is the same as the parent reference frame\n            rotation = np.identity(6)\n\n        return rotation, offset\n\n    # define the name of the method of conversion\n    mtd = \"_to_%s\" % ref_orbit.frame.__name__\n\n    # dictionary which defines attributes of the created class\n    dct = {\n        mtd: _to_parent_frame,\n        \"orientation\": orientation,\n        \"center\": center,\n        \"bypass\": bypass,\n    }\n\n    # Creation of the class\n    cls = _MetaFrame(name, (Frame,), dct)\n\n    # Link to the parent\n    cls + ref_orbit.frame\n    return cls\n\n\nWGS84 + ITRF + PEF + TOD + MOD + EME2000\nTOD + TEME\n# EME2000 + GCRF\nITRF + TIRF + CIRF + GCRF\nEME2000 + G50\n", "meta": {"hexsha": "8d473b19dd9dc30625aaeecec9aa08300173f99b", "size": 10577, "ext": "py", "lang": "Python", "max_stars_repo_path": "beyond/frames/frames.py", "max_stars_repo_name": "priyatharsan/beyond", "max_stars_repo_head_hexsha": "1061b870407d316d43e4d1351a7ec026629685ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "beyond/frames/frames.py", "max_issues_repo_name": "priyatharsan/beyond", "max_issues_repo_head_hexsha": "1061b870407d316d43e4d1351a7ec026629685ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "beyond/frames/frames.py", "max_forks_repo_name": "priyatharsan/beyond", "max_forks_repo_head_hexsha": "1061b870407d316d43e4d1351a7ec026629685ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5753768844, "max_line_length": 92, "alphanum_fraction": 0.5499669093, "include": true, "reason": "import numpy", "num_tokens": 2639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.31069438959712015, "lm_q1q2_score": 0.1698684764003171}}
{"text": "import matplotlib.pyplot as plt\nimport os\nimport numpy as np\nimport yt\n\nfrom pygrackle import \\\n    FluidContainer, \\\n    chemistry_data, \\\n    evolve_constant_density\n\nfrom pygrackle.utilities.physical_constants import \\\n    mass_hydrogen_cgs, \\\n    sec_per_Myr, \\\n    cm_per_mpc\n\nimport sys\n\nfrom multiprocessing import Pool\nfrom contextlib import closing\nimport itertools\n\ntiny_number = 1e-20\n\nclass NoStdStreams(object):\n    def __init__(self,stdout = None, stderr = None):\n        self.devnull = open(os.devnull,'w')\n        self._stdout = stdout or self.devnull or sys.stdout\n        self._stderr = stderr or self.devnull or sys.stderr\n\n    def __enter__(self):\n        self.old_stdout, self.old_stderr = sys.stdout, sys.stderr\n        self.old_stdout.flush(); self.old_stderr.flush()\n        sys.stdout, sys.stderr = self._stdout, self._stderr\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        self._stdout.flush(); self._stderr.flush()\n        sys.stdout = self.old_stdout\n        sys.stderr = self.old_stderr\n        self.devnull.close()\n\ndef cooling_cell(density = 12.2,\n                 initial_temperature = 2.0E4,\n                 final_time = 30.0,\n                 metal_fraction = 4.0E-4,\n                 make_plot = False,\n                 save_output = False, primordial_chemistry = 2,\n                 outname = None, save_H2_fraction = False,\n                 return_result = False,\n                 verbose = False, H2_converge = None,\n                 *args, **kwargs):\n\n\n    current_redshift = 0.\n\n    # Set solver parameters\n    my_chemistry = chemistry_data()\n    my_chemistry.use_grackle = 1\n    my_chemistry.with_radiative_cooling = 1\n    my_chemistry.primordial_chemistry = primordial_chemistry\n    my_chemistry.metal_cooling = 1\n    my_chemistry.UVbackground = 1\n    my_chemistry.self_shielding_method = 3\n\n    if primordial_chemistry > 1:\n        my_chemistry.H2_self_shielding = 2\n        my_chemistry.h2_on_dust = 1\n        my_chemistry.three_body_rate = 4\n\n    grackle_dir = \"/home/aemerick/code/grackle-emerick/\"\n    my_chemistry.grackle_data_file = os.sep.join( #['/home/aemerick/code/grackle-emerick/input/CloudyData_UVB=HM2012.h5'])\n        [grackle_dir, \"input\",\"CloudyData_UVB=HM2012_shielded.h5\"])\n\n\n    # set the factors\n    my_chemistry.LW_factor = kwargs.get(\"LW_factor\", 1.0)\n    my_chemistry.k27_factor = kwargs.get(\"k27_factor\", 1.0)\n    #if 'LW_factor' in kwargs.keys():\n    #    my_chemistry.LW_factor = kwargs['LW_factor']\n    #else:\n    #    my_chemistry.LW_factor = 1.0\n\n    #if 'k27_factor' in kwargs.keys():\n    #    my_chemistry.k27_factor = kwargs['k27_factor']\n    #else:\n    #    my_chemistry.k27_factor = 1.0\n\n    # Set units\n    my_chemistry.comoving_coordinates = 0 # proper units\n    my_chemistry.a_units = 1.0\n    my_chemistry.a_value = 1. / (1. + current_redshift) / \\\n        my_chemistry.a_units\n    my_chemistry.density_units = mass_hydrogen_cgs # rho = 1.0 is 1.67e-24 g\n    my_chemistry.length_units = cm_per_mpc         # 1 Mpc in cm\n    my_chemistry.time_units = sec_per_Myr          # 1 Myr in s\n    my_chemistry.velocity_units = my_chemistry.a_units * \\\n        (my_chemistry.length_units / my_chemistry.a_value) / \\\n        my_chemistry.time_units\n\n\n    rval = my_chemistry.initialize()\n\n    fc = FluidContainer(my_chemistry, 1)\n    fc[\"density\"][:] = density\n    if my_chemistry.primordial_chemistry > 0:\n        fc[\"HI\"][:] = 0.76 * fc[\"density\"]\n        fc[\"HII\"][:] = tiny_number * fc[\"density\"]\n        fc[\"HeI\"][:] = (1.0 - 0.76) * fc[\"density\"]\n        fc[\"HeII\"][:] = tiny_number * fc[\"density\"]\n        fc[\"HeIII\"][:] = tiny_number * fc[\"density\"]\n    if my_chemistry.primordial_chemistry > 1:\n        fc[\"H2I\"][:] = tiny_number * fc[\"density\"]\n        fc[\"H2II\"][:] = tiny_number * fc[\"density\"]\n        fc[\"HM\"][:] = tiny_number * fc[\"density\"]\n        fc[\"de\"][:] = tiny_number * fc[\"density\"]\n        fc['H2_self_shielding_length'][:] = 1.8E-6\n    if my_chemistry.primordial_chemistry > 2:\n        fc[\"DI\"][:] = 2.0 * 3.4e-5 * fc[\"density\"]\n        fc[\"DII\"][:] = tiny_number * fc[\"density\"]\n        fc[\"HDI\"][:] = tiny_number * fc[\"density\"]\n    if my_chemistry.metal_cooling == 1:\n        fc[\"metal\"][:] = metal_fraction * fc[\"density\"] * \\\n          my_chemistry.SolarMetalFractionByMass\n\n    fc[\"x-velocity\"][:] = 0.0\n    fc[\"y-velocity\"][:] = 0.0\n    fc[\"z-velocity\"][:] = 0.0\n\n    fc[\"energy\"][:] = initial_temperature / \\\n        fc.chemistry_data.temperature_units\n    fc.calculate_temperature()\n    fc[\"energy\"][:] *= initial_temperature / fc[\"temperature\"]\n\n    # timestepping safety factor\n    safety_factor = 0.001\n\n    # let gas cool at constant density\n\n    #if verbose:\n    print(\"Beginning Run\")\n    data = evolve_constant_density(\n            fc, final_time=final_time, H2_converge = H2_converge,\n            safety_factor=safety_factor, verbose = verbose)\n    #else:\n    #    print \"Beginning Run\"\n\n    #    with NoStdStreams():\n    #        data = evolve_constant_density(\n    #            fc, final_time=final_time, H2_converge = 1.0E-6,\n    #            safety_factor=safety_factor)\n    #    print \"Ending Run\"\n\n\n    if make_plot:\n        p1, = plt.loglog(data[\"time\"].to(\"Myr\"), data[\"temperature\"],\n                            color=\"black\", label=\"T\")\n        plt.xlabel(\"Time [Myr]\")\n        plt.ylabel(\"T [K]\")\n\n        data[\"mu\"] = data[\"temperature\"] / \\\n            (data[\"energy\"] * (my_chemistry.Gamma - 1.) *\n             fc.chemistry_data.temperature_units)\n        plt.twinx()\n        p2, = plt.semilogx(data[\"time\"].to(\"Myr\"), data[\"mu\"],\n                              color=\"red\", label=\"$\\\\mu$\")\n        plt.ylabel(\"$\\\\mu$\")\n        plt.legend([p1,p2],[\"T\",\"$\\\\mu$\"], fancybox=True,\n                      loc=\"center left\")\n        plt.savefig(\"cooling_cell.png\")\n\n\n    # save data arrays as a yt dataset\n    if outname is None:\n        outname = 'cooling_cell_%.2f_%.2f'%(my_chemistry.k27_factor,\n                                           my_chemistry.LW_factor)\n\n    if save_output:\n\n        yt.save_as_dataset({}, outname + '.h5', data)\n\n    if my_chemistry.primordial_chemistry > 1:\n        H2_fraction = (data['H2I'] + data['H2II']) / data['density']\n    else:\n        H2_fraction = np.zeros(np.size(data['density']))\n\n    if save_H2_fraction:\n        #np.savetxt(outname + \".dat\", [data['time'], H2_fraction])\n\n        f = open(\"all_runs_d_%.2f.dat\"%(density),\"a\")\n#        f.write(\"# k27 LW f_H2 T time\\n\")\n        f.write(\"%8.8E %8.8E %8.8E %8.8E %8.8E \\n\"%(my_chemistry.k27_factor,\n                                              my_chemistry.LW_factor,\n                                              H2_fraction[-1], data['temperature'][-1],\n                                              data['time'][-1] ))\n        f.close()\n\n    if return_result:\n        return data\n    else:\n        return\n\ndef _parallel_loop(i, k27, LW):\n\n    primordial_chemistry = 1\n\n    data = cooling_cell(k27_factor = k27, LW_factor = LW, save_output = False,\n                        save_H2_fraction = False, primordial_chemistry = primordial_chemistry,\n                        return_result = True)\n\n    if primordial_chemistry > 1:\n        H2_fraction = (data['H2I'] + data['H2II']) / data['density']\n    else:\n        H2_fraction = np.zeros(np.size(data['density']))\n\n    T           = (data['temperature'])\n\n    str_i = \"%00005i\"%(i)\n\n    result = { str_i : {}}\n    result[str_i]['k27'] = k27\n    result[str_i]['LW']  = LW\n    result[str_i]['H2_fraction'] = H2_fraction[-1]\n    result[str_i]['T'] = T[-1]\n\n\n    return result\n\ndef _parallel_loop_star(args):\n    return _parallel_loop(*args)\n\n\n\ndef cooling_cell_grid(k27_factors = None, LW_factors = None,\n                      fmin = 0.1, fmax = 10000.0, npoints = 100,\n                      nproc = 1, outname = None):\n\n    if outname is None:\n        outname = \"all_parallel_runs.dat\"\n\n    if k27_factors is None:\n        k27_factors = np.logspace(np.log10(fmin),\n                                  np.log10(fmax), npoints)\n    if LW_factors is None:\n        LW_factors  = 1.0 * k27_factors\n\n    if nproc == 1:\n        call_cell = lambda x, y : cooling_cell(k27_factor = x,\n                                               LW_factor  = y, save_H2_fraction = True)\n\n        for i,k27 in enumerate(k27_factors):\n            print((i)*np.size(LW_factors))\n\n            temp_cell = lambda y : call_cell(k27,y)\n            list(map(temp_cell, LW_factors)) # this may not work anymore - AE python 2 to 3\n    else:\n\n        LW_mesh, k27_mesh = np.meshgrid(LW_factors, k27_factors)\n\n        k27_mesh = k27_mesh.flatten()\n        LW_mesh  = LW_mesh.flatten()\n\n        for sub_list in itertools.zip_longest(*(iter( np.arange(np.size(k27_mesh))),) * nproc):\n            sub_list = list(sub_list)\n            sub_list = [s for s in sub_list if s is not None]\n            reduced_nproc = np.min( [len(sub_list), nproc])\n\n            print(\"running for \", sub_list)\n\n            imin,imax = sub_list[0], (sub_list[-1] + 1)\n\n            pool = Pool(reduced_nproc)\n            results = pool.map_async(_parallel_loop_star,\n                                     zip(sub_list,\n                                                    k27_mesh[imin:imax], LW_mesh[imin:imax]))\n            pool.close()\n            pool.join()\n\n            for r in results.get():\n                str_i = list(r.keys())[0]\n\n                f = open(outname,\"a\")\n                f.write(\"%8.8E %8.8E %8.8E %8.8E\\n\"%(  r[str_i]['k27'],\n                                                       r[str_i]['LW'], r[str_i]['H2_fraction'],\n                                                       r[str_i]['T']))\n                f.close()\n\n            del(results)\n\n    return\n\n\nif __name__ == \"__main__\":\n\n    # test this\n    #cooling_cell(k27_factor = 0.99, LW_factor = 0.99,\n    #             save_output = False, save_H2_fraction=True)\n    import time\n\n    npoints = 16\n    nproc   = 4\n\n    start = time.time()\n    cooling_cell_grid(npoints = npoints, nproc = nproc, outname = str(sys.argv[1]))\n    end = time.time()\n\n    dt = end - start\n    eff = dt / (1.0*nproc)\n    print(\"This run of %i models on %i processors took %.3E s - Eff = %.1E\"%(npoints*npoints, nproc, dt, eff))\n", "meta": {"hexsha": "f3eac9c7d7e26f03be11df9b5a8700b6876de9c2", "size": 10203, "ext": "py", "lang": "Python", "max_stars_repo_path": "grackle/cooling_cell_test.py", "max_stars_repo_name": "diamondjems016/galaxy_analysis", "max_stars_repo_head_hexsha": "fa1367085a6b9870de2546daf3163aaa41129ea0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-15T15:33:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:33:05.000Z", "max_issues_repo_path": "grackle/cooling_cell_test.py", "max_issues_repo_name": "diamondjems016/galaxy_analysis", "max_issues_repo_head_hexsha": "fa1367085a6b9870de2546daf3163aaa41129ea0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grackle/cooling_cell_test.py", "max_forks_repo_name": "diamondjems016/galaxy_analysis", "max_forks_repo_head_hexsha": "fa1367085a6b9870de2546daf3163aaa41129ea0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-29T00:15:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-29T00:15:25.000Z", "avg_line_length": 33.1266233766, "max_line_length": 122, "alphanum_fraction": 0.5711065373, "include": true, "reason": "import numpy", "num_tokens": 2767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.16986847291072465}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2020 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#\n\nfrom pyscf.grad import lagrange\nfrom pyscf.mcscf.addons import StateAverageMCSCFSolver, StateAverageFCISolver, StateAverageMixFCISolver, state_average_mix_\nfrom pyscf.grad.mp2 import _shell_prange\nfrom pyscf.mcscf import mc1step, mc1step_symm, newton_casscf\nfrom pyscf.grad import casscf as casscf_grad\nfrom pyscf.grad import rhf as rhf_grad\nfrom pyscf.fci.direct_spin1 import _unpack_nelec\nfrom pyscf.fci.spin_op import spin_square\nfrom pyscf.fci import cistring\nfrom pyscf import lib, ao2mo, mcscf\nimport numpy as np\nimport copy, time, gc\nfrom functools import reduce\nfrom itertools import product\nfrom scipy import linalg\n\ndef Lorb_dot_dgorb_dx (Lorb, mc, mo_coeff=None, ci=None, atmlst=None, mf_grad=None, eris=None, verbose=None):\n    ''' Modification of pyscf.grad.casscf.kernel to compute instead the orbital\n    Lagrange term nuclear gradient (sum_pq Lorb_pq d2_Ecas/d_lambda d_kpq)\n    This involves removing nuclear-nuclear terms and making the substitution\n    (D_[p]q + D_p[q]) -> D_pq\n    (d_[p]qrs + d_pq[r]s + d_p[q]rs + d_pqr[s]) -> d_pqrs\n    Where [] around an index implies contraction with Lorb from the left, so that the external index\n    (regardless of whether the index on the rdm is bra or ket) is always the first index of Lorb. '''\n\n    # dmo = smoT.dao.smo\n    # dao = mo.dmo.moT\n    t0 = (time.clock (), time.time ())\n\n    if mo_coeff is None: mo_coeff = mc.mo_coeff\n    if ci is None: ci = mc.ci\n    if mf_grad is None: mf_grad = mc._scf.nuc_grad_method()\n    if mc.frozen is not None:\n        raise NotImplementedError\n\n    mol = mc.mol\n    ncore = mc.ncore\n    ncas = mc.ncas\n    nocc = ncore + ncas\n    nelecas = mc.nelecas\n    nao, nmo = mo_coeff.shape\n    nao_pair = nao * (nao+1) // 2\n\n    mo_occ = mo_coeff[:,:nocc]\n    mo_core = mo_coeff[:,:ncore]\n    mo_cas = mo_coeff[:,ncore:nocc]\n\n    # MRH: new 'effective' MO coefficients including contraction from the Lagrange multipliers\n    moL_coeff = np.dot (mo_coeff, Lorb)\n    s0_inv = np.dot (mo_coeff,  mo_coeff.T)\n    moL_core = moL_coeff[:,:ncore]\n    moL_cas = moL_coeff[:,ncore:nocc]\n\n    # MRH: these SHOULD be state-averaged! Use the actual sacasscf object!\n    casdm1, casdm2 = mc.fcisolver.make_rdm12(ci, ncas, nelecas)\n\n    # gfock = Generalized Fock, Adv. Chem. Phys., 69, 63\n    # MRH: each index exactly once!\n    dm_core = np.dot(mo_core, mo_core.T) * 2\n    dm_cas = reduce(np.dot, (mo_cas, casdm1, mo_cas.T))\n    # MRH: new density matrix terms\n    dmL_core = np.dot(moL_core, mo_core.T) * 2\n    dmL_cas = reduce(np.dot, (moL_cas, casdm1, mo_cas.T))\n    dmL_core += dmL_core.T\n    dmL_cas += dmL_cas.T\n    dm1 = dm_core + dm_cas\n    dm1L = dmL_core + dmL_cas\n    # MRH: end new density matrix terms\n    # MRH: wrap the integral instead of the density matrix. I THINK the sign is the same!\n    # mo sets 0 and 2 should be transposed, 1 and 3 should be not transposed; this will lead to correct sign\n    # Except I can't do this for the external index, because the external index is contracted to ovlp matrix,\n    # not the 2RDM\n    aapa = np.zeros ((ncas, ncas, nmo, ncas), dtype=dm_cas.dtype)\n    aapaL = np.zeros ((ncas, ncas, nmo, ncas), dtype=dm_cas.dtype)\n    for i in range (nmo):\n        jbuf = eris.ppaa[i]\n        kbuf = eris.papa[i]\n        aapa[:,:,i,:] = jbuf[ncore:nocc,:,:].transpose (1,2,0)\n        aapaL[:,:,i,:] += np.tensordot (jbuf, Lorb[:,ncore:nocc], axes=((0),(0)))\n        kbuf = np.tensordot (kbuf, Lorb[:,ncore:nocc], axes=((1),(0))).transpose (1,2,0)\n        aapaL[:,:,i,:] += kbuf + kbuf.transpose (1,0,2)\n    # MRH: new vhf terms\n    vj, vk   = mc._scf.get_jk(mol, (dm_core,  dm_cas))\n    vjL, vkL = mc._scf.get_jk(mol, (dmL_core, dmL_cas))\n    h1 = mc.get_hcore()\n    vhf_c = vj[0] - vk[0] * .5\n    vhf_a = vj[1] - vk[1] * .5\n    vhfL_c = vjL[0] - vkL[0] * .5\n    vhfL_a = vjL[1] - vkL[1] * .5\n    # MRH: I rewrote this Feff calculation completely, double-check it\n    gfock  = np.dot (h1, dm1L) # h1e\n    gfock += np.dot ((vhf_c + vhf_a), dmL_core) # core-core and active-core, 2nd 1RDM linked\n    gfock += np.dot ((vhfL_c + vhfL_a), dm_core) # core-core and active-core, 1st 1RDM linked\n    gfock += np.dot (vhfL_c, dm_cas) # core-active, 1st 1RDM linked\n    gfock += np.dot (vhf_c, dmL_cas) # core-active, 2nd 1RDM linked\n    gfock  = np.dot (s0_inv, gfock) # Definition of quantity is in MO's; going (AO->MO->AO) incurs an inverse ovlp\n    gfock += reduce (np.dot, (mo_coeff, np.einsum('uviw,uvtw->it', aapaL, casdm2), mo_cas.T)) # active-active\n    # MRH: I have to contract this external 2RDM index explicitly on the 2RDM but fortunately I can do so here\n    gfock += reduce (np.dot, (mo_coeff, np.einsum('uviw,vuwt->it', aapa, casdm2), moL_cas.T))\n    # MRH: As of 04/18/2019, the two-body part of this is including aapaL is definitely, unambiguously correct\n    dme0 = (gfock+gfock.T)/2 # This transpose is for the overlap matrix later on\n    aapa = vj = vk = vhf_c = vhf_a = None\n\n    vj, vk = mf_grad.get_jk (mol, (dm_core, dm_cas, dmL_core, dmL_cas))\n    vhf1c, vhf1a, vhf1cL, vhf1aL = vj - vk * 0.5\n    #vhf1c, vhf1a, vhf1cL, vhf1aL = mf_grad.get_veff(mol, (dm_core, dm_cas, dmL_core, dmL_cas))\n    hcore_deriv = mf_grad.hcore_generator(mol)\n    s1 = mf_grad.get_ovlp(mol)\n\n    diag_idx = np.arange(nao)\n    diag_idx = diag_idx * (diag_idx+1) // 2 + diag_idx\n    casdm2_cc = casdm2 + casdm2.transpose(0,1,3,2)\n    dm2buf = ao2mo._ao2mo.nr_e2(casdm2_cc.reshape(ncas**2,ncas**2), mo_cas.T,\n                                (0, nao, 0, nao)).reshape(ncas**2,nao,nao)\n    # MRH: contract the final two indices of the active-active 2RDM with L as you change to AOs\n    # note tensordot always puts indices in the order of the arguments.\n    dm2Lbuf = np.zeros ((ncas**2,nmo,nmo))\n    # MRH: The second line below transposes the L; the third line transposes the derivative later on\n    # Both the L and the derivative have to explore all indices\n    dm2Lbuf[:,:,ncore:nocc]  = np.tensordot (Lorb[:,ncore:nocc], casdm2, axes=(1,2)).transpose (1,2,0,3).reshape (ncas**2,nmo,ncas)\n    dm2Lbuf[:,ncore:nocc,:] += np.tensordot (Lorb[:,ncore:nocc], casdm2, axes=(1,3)).transpose (1,2,3,0).reshape (ncas**2,ncas,nmo)\n    dm2Lbuf += dm2Lbuf.transpose (0,2,1)\n    dm2Lbuf = np.ascontiguousarray (dm2Lbuf)\n    dm2Lbuf = ao2mo._ao2mo.nr_e2(dm2Lbuf.reshape (ncas**2,nmo**2), mo_coeff.T,\n                                (0, nao, 0, nao)).reshape(ncas**2,nao,nao)\n    dm2buf = lib.pack_tril(dm2buf)\n    dm2buf[:,diag_idx] *= .5\n    dm2buf = dm2buf.reshape(ncas,ncas,nao_pair)\n    dm2Lbuf = lib.pack_tril(dm2Lbuf)\n    dm2Lbuf[:,diag_idx] *= .5\n    dm2Lbuf = dm2Lbuf.reshape(ncas,ncas,nao_pair)\n\n    if atmlst is None:\n        atmlst = list (range(mol.natm))\n    aoslices = mol.aoslice_by_atom()\n    de_hcore = np.zeros((len(atmlst),3))\n    de_renorm = np.zeros((len(atmlst),3))\n    de_eri = np.zeros((len(atmlst),3))\n    de = np.zeros((len(atmlst),3))\n\n    max_memory = mc.max_memory - lib.current_memory()[0]\n    blksize = int(max_memory*.9e6/8 / (4*(aoslices[:,3]-aoslices[:,2]).max()*nao_pair))\n    # MRH: 3 components of eri array and 1 density matrix array: FOUR arrays of this size are required!\n    blksize = min(nao, max(2, blksize))\n    lib.logger.info (mc, 'SA-CASSCF Lorb_dot_dgorb memory remaining for eri manipulation: {} MB; using blocksize = {}'.format (max_memory, blksize)) \n    t0 = lib.logger.timer (mc, 'SA-CASSCF Lorb_dot_dgorb 1-electron part', *t0)\n\n    for k, ia in enumerate(atmlst):\n        shl0, shl1, p0, p1 = aoslices[ia]\n        h1ao = hcore_deriv(ia)\n        # MRH: h1e and Feff terms\n        de_hcore[k] += np.einsum('xij,ij->x', h1ao, dm1L)\n        de_renorm[k] -= np.einsum('xij,ij->x', s1[:,p0:p1], dme0[p0:p1]) * 2\n\n        q1 = 0\n        for b0, b1, nf in _shell_prange(mol, 0, mol.nbas, blksize):\n            q0, q1 = q1, q1 + nf\n            dm2_ao  = lib.einsum('ijw,pi,qj->pqw', dm2Lbuf, mo_cas[p0:p1], mo_cas[q0:q1])\n            # MRH: now contract the first two indices of the active-active 2RDM with L as you go from MOs to AOs\n            dm2_ao += lib.einsum('ijw,pi,qj->pqw', dm2buf, moL_cas[p0:p1], mo_cas[q0:q1])\n            dm2_ao += lib.einsum('ijw,pi,qj->pqw', dm2buf, mo_cas[p0:p1], moL_cas[q0:q1])\n            shls_slice = (shl0,shl1,b0,b1,0,mol.nbas,0,mol.nbas)\n            gc.collect ()\n            eri1 = mol.intor('int2e_ip1', comp=3, aosym='s2kl',\n                             shls_slice=shls_slice).reshape(3,p1-p0,nf,nao_pair)\n            # MRH: I still don't understand why there is a minus here!\n            de_eri[k] -= np.einsum('xijw,ijw->x', eri1, dm2_ao) * 2\n            eri1 = dm2_ao = None\n            gc.collect ()\n            t0 = lib.logger.timer (mc, 'SA-CASSCF Lorb_dot_dgorb atom {} ({},{}|{})'.format (ia, p1-p0, nf, nao_pair), *t0)\n        # MRH: core-core and core-active 2RDM terms\n        de_eri[k] += np.einsum('xij,ij->x', vhf1c[:,p0:p1], dm1L[p0:p1]) * 2\n        de_eri[k] += np.einsum('xij,ij->x', vhf1cL[:,p0:p1], dm1[p0:p1]) * 2\n        # MRH: active-core 2RDM terms\n        de_eri[k] += np.einsum('xij,ij->x', vhf1a[:,p0:p1], dmL_core[p0:p1]) * 2\n        de_eri[k] += np.einsum('xij,ij->x', vhf1aL[:,p0:p1], dm_core[p0:p1]) * 2\n\n    # MRH: deleted the nuclear-nuclear part to avoid double-counting\n    # lesson learned from debugging - mol.intor computes -1 * the derivative and only\n    # for one index\n    # on the other hand, mf_grad.hcore_generator computes the actual derivative of\n    # h1 for both indices and with the correct sign\n\n    lib.logger.debug (mc, \"Orb lagrange hcore component:\\n{}\".format (de_hcore))\n    lib.logger.debug (mc, \"Orb lagrange renorm component:\\n{}\".format (de_renorm))\n    lib.logger.debug (mc, \"Orb lagrange eri component:\\n{}\".format (de_eri))\n    de = de_hcore + de_renorm + de_eri\n\n    return de\n\ndef Lci_dot_dgci_dx (Lci, weights, mc, mo_coeff=None, ci=None, atmlst=None, mf_grad=None, eris=None, verbose=None):\n    ''' Modification of pyscf.grad.casscf.kernel to compute instead the CI\n    Lagrange term nuclear gradient (sum_IJ Lci_IJ d2_Ecas/d_lambda d_PIJ)\n    This involves removing all core-core and nuclear-nuclear terms and making the substitution\n    sum_I w_I<L_I|p'q|I> + c.c. -> <0|p'q|0>\n    sum_I w_I<L_I|p'r'sq|I> + c.c. -> <0|p'r'sq|0>\n    The active-core terms (sum_I w_I<L_I|x'iyi|I>, sum_I w_I <L_I|x'iiy|I>, c.c.) must be retained.'''\n    if mo_coeff is None: mo_coeff = mc.mo_coeff\n    if ci is None: ci = mc.ci\n    if mf_grad is None: mf_grad = mc._scf.nuc_grad_method()\n    if mc.frozen is not None:\n        raise NotImplementedError\n\n    t0 = (time.clock (), time.time ())\n    mol = mc.mol\n    ncore = mc.ncore\n    ncas = mc.ncas\n    nocc = ncore + ncas\n    nelecas = mc.nelecas\n    nao, nmo = mo_coeff.shape\n    nao_pair = nao * (nao+1) // 2\n    nroots = len (ci)\n\n    mo_occ = mo_coeff[:,:nocc]\n    mo_core = mo_coeff[:,:ncore]\n    mo_cas = mo_coeff[:,ncore:nocc]\n\n    # MRH: TDMs + c.c. instead of RDMs; 06/30/2020: new interface in mcscf.addons makes this much more transparent\n    casdm1, casdm2 = mc.fcisolver.trans_rdm12 (Lci, ci, ncas, nelecas)\n    casdm1 += casdm1.transpose (1,0)\n    casdm2 += casdm2.transpose (1,0,3,2)\n\n# gfock = Generalized Fock, Adv. Chem. Phys., 69, 63\n    dm_core = np.dot(mo_core, mo_core.T) * 2\n    dm_cas = reduce(np.dot, (mo_cas, casdm1, mo_cas.T))\n    aapa = np.zeros ((ncas, ncas, nmo, ncas), dtype=dm_cas.dtype)\n    for i in range (nmo):\n        aapa[:,:,i,:] = eris.ppaa[i][ncore:nocc,:,:].transpose (1,2,0)\n    vj, vk = mc._scf.get_jk(mol, (dm_core, dm_cas))\n    h1 = mc.get_hcore()\n    vhf_c = vj[0] - vk[0] * .5\n    vhf_a = vj[1] - vk[1] * .5\n    # MRH: delete h1 + vhf_c from the first line below (core and core-core stuff)\n    # Also extend gfock to span the whole space\n    gfock = np.zeros_like (dm_cas)\n    gfock[:,:nocc]   = reduce(np.dot, (mo_coeff.T, vhf_a, mo_occ)) * 2\n    gfock[:,ncore:nocc]  = reduce(np.dot, (mo_coeff.T, h1 + vhf_c, mo_cas, casdm1))\n    gfock[:,ncore:nocc] += np.einsum('uvpw,vuwt->pt', aapa, casdm2)\n    dme0 = reduce(np.dot, (mo_coeff, (gfock+gfock.T)*.5, mo_coeff.T))\n    aapa = vj = vk = vhf_c = vhf_a = h1 = gfock = None\n\n    vj, vk = mf_grad.get_jk (mol, (dm_core, dm_cas))\n    vhf1c, vhf1a = vj - vk * 0.5\n    #vhf1c, vhf1a = mf_grad.get_veff(mol, (dm_core, dm_cas))\n    hcore_deriv = mf_grad.hcore_generator(mol)\n    s1 = mf_grad.get_ovlp(mol)\n\n    diag_idx = np.arange(nao)\n    diag_idx = diag_idx * (diag_idx+1) // 2 + diag_idx\n    casdm2_cc = casdm2 + casdm2.transpose(0,1,3,2)\n    dm2buf = ao2mo._ao2mo.nr_e2(casdm2_cc.reshape(ncas**2,ncas**2), mo_cas.T,\n                                (0, nao, 0, nao)).reshape(ncas**2,nao,nao)\n    dm2buf = lib.pack_tril(dm2buf)\n    dm2buf[:,diag_idx] *= .5\n    dm2buf = dm2buf.reshape(ncas,ncas,nao_pair)\n    casdm2 = casdm2_cc = None\n\n    if atmlst is None:\n        atmlst = range(mol.natm)\n    aoslices = mol.aoslice_by_atom()\n    de_hcore = np.zeros((len(atmlst),3))\n    de_renorm = np.zeros((len(atmlst),3))\n    de_eri = np.zeros((len(atmlst),3))\n    de = np.zeros((len(atmlst),3))\n\n    max_memory = mc.max_memory - lib.current_memory()[0]\n    blksize = int(max_memory*.9e6/8 / (4*(aoslices[:,3]-aoslices[:,2]).max()*nao_pair))\n    # MRH: 3 components of eri array and 1 density matrix array: FOUR arrays of this size are required!\n    blksize = min(nao, max(2, blksize))\n    lib.logger.info (mc, 'SA-CASSCF Lci_dot_dgci memory remaining for eri manipulation: {} MB; using blocksize = {}'.format (max_memory, blksize)) \n    t0 = lib.logger.timer (mc, 'SA-CASSCF Lci_dot_dgci 1-electron part', *t0)\n\n    for k, ia in enumerate(atmlst):\n        shl0, shl1, p0, p1 = aoslices[ia]\n        h1ao = hcore_deriv(ia)\n        # MRH: dm1 -> dm_cas in the line below\n        de_hcore[k] += np.einsum('xij,ij->x', h1ao, dm_cas)\n        de_renorm[k] -= np.einsum('xij,ij->x', s1[:,p0:p1], dme0[p0:p1]) * 2\n\n        q1 = 0\n        for b0, b1, nf in _shell_prange(mol, 0, mol.nbas, blksize):\n            q0, q1 = q1, q1 + nf\n            dm2_ao = lib.einsum('ijw,pi,qj->pqw', dm2buf, mo_cas[p0:p1], mo_cas[q0:q1])\n            shls_slice = (shl0,shl1,b0,b1,0,mol.nbas,0,mol.nbas)\n            gc.collect ()\n            eri1 = mol.intor('int2e_ip1', comp=3, aosym='s2kl',\n                             shls_slice=shls_slice).reshape(3,p1-p0,nf,nao_pair)\n            de_eri[k] -= np.einsum('xijw,ijw->x', eri1, dm2_ao) * 2\n            eri1 = dm2_ao = None\n            gc.collect ()\n            t0 = lib.logger.timer (mc, 'SA-CASSCF Lci_dot_dgci atom {} ({},{}|{})'.format (ia, p1-p0, nf, nao_pair), *t0)\n        # MRH: dm1 -> dm_cas in the line below. Also eliminate core-core terms\n        de_eri[k] += np.einsum('xij,ij->x', vhf1c[:,p0:p1], dm_cas[p0:p1]) * 2\n        de_eri[k] += np.einsum('xij,ij->x', vhf1a[:,p0:p1], dm_core[p0:p1]) * 2\n\n    lib.logger.debug (mc, \"CI lagrange hcore component:\\n{}\".format (de_hcore))\n    lib.logger.debug (mc, \"CI lagrange renorm component:\\n{}\".format (de_renorm))\n    lib.logger.debug (mc, \"CI lagrange eri component:\\n{}\".format (de_eri))\n    de = de_hcore + de_renorm + de_eri\n    return de\n\ndef as_scanner(mcscf_grad, state=None):\n    '''Generating a nuclear gradients scanner/solver (for geometry optimizer).\n\n    The returned solver is a function. This function requires one argument\n    \"mol\" as input and returns energy and first order nuclear derivatives.\n\n    The solver will automatically use the results of last calculation as the\n    initial guess of the new calculation.  All parameters assigned in the\n    nuc-grad object and SCF object (DIIS, conv_tol, max_memory etc) are\n    automatically applied in the solver.\n\n    Note scanner has side effects.  It may change many underlying objects\n    (_scf, with_df, with_x2c, ...) during calculation.\n\n    Examples:\n\n    >>> from pyscf import gto, scf, mcscf\n    >>> mol = gto.M(atom='N 0 0 0; N 0 0 1.1', verbose=0)\n    >>> mc_grad_scanner = mcscf.CASSCF(scf.RHF(mol), 4, 4).nuc_grad_method().as_scanner()\n    >>> etot, grad = mc_grad_scanner(gto.M(atom='N 0 0 0; N 0 0 1.1'))\n    >>> etot, grad = mc_grad_scanner(gto.M(atom='N 0 0 0; N 0 0 1.5'))\n    '''\n    from pyscf import gto\n    if isinstance(mcscf_grad, lib.GradScanner):\n        return mcscf_grad\n\n    #if state is None and (not hasattr (mcscf_grad, 'state') or (mcscf_grad.state is None)):\n    #    return casscf_grad.as_scanner (mcscf_grad)\n\n    lib.logger.info(mcscf_grad, 'Create scanner for %s', mcscf_grad.__class__)\n\n    class CASSCF_GradScanner(mcscf_grad.__class__, lib.GradScanner):\n        def __init__(self, g):\n            lib.GradScanner.__init__(self, g)\n            if state is None:\n                self.state = g.state\n            else:\n                self.state = state\n        def __call__(self, mol_or_geom, **kwargs):\n            if isinstance(mol_or_geom, gto.Mole):\n                mol = mol_or_geom\n            else:\n                mol = self.mol.set_geom_(mol_or_geom, inplace=False)\n            if 'state' in kwargs: self.state = kwargs['state']\n            mc_scanner = self.base\n            e_tot = mc_scanner(mol)\n            if hasattr (mc_scanner, 'e_mcscf'): self.e_mcscf = mc_scanner.e_mcscf\n            if hasattr (mc_scanner, 'e_states') and self.state is not None:\n                e_tot = mc_scanner.e_states[self.state]\n            self.mol = mol\n            if not ('state' in kwargs):\n                kwargs['state'] = self.state\n            de = self.kernel(**kwargs)\n            return e_tot, de\n            \n    return CASSCF_GradScanner(mcscf_grad)\n\n\nclass Gradients (lagrange.Gradients):\n\n    def __init__(self, mc, state=None):\n        self.__dict__.update (mc.__dict__)\n        nmo = mc.mo_coeff.shape[-1]\n        self.ngorb = np.count_nonzero (mc.uniq_var_indices (nmo, mc.ncore, mc.ncas, mc.frozen))\n        self.nroots = mc.fcisolver.nroots\n        neleca, nelecb = _unpack_nelec (mc.nelecas)\n        self.spin_states = [neleca - nelecb,] * self.nroots\n        self.na_states = [cistring.num_strings (mc.ncas, neleca),] * self.nroots\n        self.nb_states = [cistring.num_strings (mc.ncas, nelecb),] * self.nroots\n        if isinstance (mc.fcisolver, StateAverageMixFCISolver):\n            self.nroots = p0 = 0\n            for solver in mc.fcisolver.fcisolvers:\n                self.nroots += solver.nroots\n                nea, neb = mc.fcisolver._get_nelec (solver, (neleca, nelecb))\n                self.spin_states[p0:self.nroots] = (nea - neb for x in range (solver.nroots))\n                self.na_states[p0:self.nroots] = (cistring.num_strings (mc.ncas, nea) for x in range (solver.nroots))\n                self.nb_states[p0:self.nroots] = (cistring.num_strings (mc.ncas, neb) for x in range (solver.nroots))\n                p0 = self.nroots\n        self.nci = sum ([na * nb for na, nb in zip (self.na_states, self.nb_states)])\n        if state is not None:\n            self.state = state\n        elif hasattr (mc, 'nuc_grad_state'):\n            self.state = mc.nuc_grad_state\n        else:\n            self.state = None\n        self.eris = None\n        self.weights = np.array ([1])\n        try:\n            self.e_states = np.asarray (mc.e_states)\n        except AttributeError as e:\n            self.e_states = np.asarray (mc.e_tot)\n        if isinstance (mc, StateAverageMCSCFSolver):\n            self.weights = np.asarray (mc.weights)\n        assert (len (self.weights) == self.nroots), '{} {} {}'.format (mc.fcisolver.__class__, self.weights, self.nroots)\n        lagrange.Gradients.__init__(self, mc, self.ngorb+self.nci)\n        self.max_cycle = mc.max_cycle_macro\n\n    def pack_uniq_var (self, xorb, xci):\n        # TODO: point-group symmetry of the xci components? CSFs?\n        xorb = self.base.pack_uniq_var (xorb)\n        xci = np.concatenate ([x.ravel () for x in xci])\n        return np.append (xorb, xci)\n\n    def unpack_uniq_var (self, x):\n        # TODO: point-group symmetry of the xci components? CSFs?\n        xorb, x = self.base.unpack_uniq_var (x[:self.ngorb]), x[self.ngorb:]\n        xci = []\n        for na, nb in zip (self.na_states, self.nb_states):\n            xci.append (x[:na*nb].reshape (na, nb))\n            x = x[na*nb:]\n        return xorb, xci\n\n    def make_fcasscf (self, state=None, casscf_attr={}, fcisolver_attr={}):\n        ''' Make a fake CASSCF object for ostensible single-state calculations '''\n        fcasscf = mcscf.CASSCF (self.base._scf, self.base.ncas, self.base.nelecas)\n        fcasscf.__dict__.update (self.base.__dict__)\n\n        if isinstance (fcasscf.fcisolver, StateAverageFCISolver):\n            if isinstance (fcasscf.fcisolver, StateAverageMixFCISolver):\n                p0 = 0\n                for solver in fcasscf.fcisolver.fcisolvers:\n                    p1 = p0 + solver.nroots\n                    if p0 <= state < p1:\n                        solver_class = solver.__class__\n                        solver_obj = solver\n                        break\n                    p0 = p1\n            else:\n                solver_class = self.base.fcisolver._base_class\n                solver_obj = self.base.fcisolver\n            fcasscf.fcisolver = solver_class (self.base.mol)\n            fcasscf.fcisolver.__dict__.update (solver_obj.__dict__)\n            fcasscf.fcisolver.nroots = 1\n        fcasscf.__dict__.update (casscf_attr)\n        fcasscf.fcisolver.__dict__.update (fcisolver_attr)\n        fcasscf.verbose, fcasscf.stdout = self.verbose, self.stdout\n        fcasscf._tag_gfock_ov_nonzero = True\n        return fcasscf\n\n    def make_fcasscf_sa (self, casscf_attr={}, fcisolver_attr={}):\n        ''' Make a fake SA-CASSCF object to get around weird inheritance conflicts '''\n        fcasscf = self.make_fcasscf (state=0, casscf_attr={}, fcisolver_attr={})\n        fcasscf.__dict__.update (self.base.__dict__)\n        if isinstance (self.base, StateAverageMCSCFSolver):\n            if isinstance (self.base.fcisolver, StateAverageMixFCISolver):\n                fcasscf = state_average_mix_(fcasscf, self.base.fcisolver.fcisolvers, self.base.weights)\n            else:\n                fcasscf.state_average_(self.base.weights)\n        fcasscf.__dict__.update (casscf_attr)\n        fcasscf.fcisolver.__dict__.update (fcisolver_attr)\n        return fcasscf\n\n    def kernel (self, state=None, atmlst=None, verbose=None, mo=None, ci=None, eris=None, mf_grad=None, e_states=None, level_shift=None, **kwargs):\n        if state is None: state = self.state\n        if atmlst is None: atmlst = self.atmlst\n        if verbose is None: verbose = self.verbose\n        if mo is None: mo = self.base.mo_coeff\n        if ci is None: ci = self.base.ci\n        if eris is None:\n            eris = self.eris = self.base.ao2mo (mo)\n        if mf_grad is None: mf_grad = self.base._scf.nuc_grad_method ()\n        if state is None:\n            return casscf_grad.Gradients (self.base).kernel (mo_coeff=mo, ci=ci, atmlst=atmlst, verbose=verbose)\n        if e_states is None:\n            try:\n                e_states = self.e_states = np.asarray (self.base.e_states)\n            except AttributeError as e:\n                e_states = self.e_states = np.asarray (self.base.e_tot)\n        if level_shift is None: level_shift=self.level_shift\n        return lagrange.Gradients.kernel (self, state=state, atmlst=atmlst, verbose=verbose, mo=mo, ci=ci, eris=eris, mf_grad=mf_grad, e_states=e_states, level_shift=level_shift, **kwargs)\n\n    def get_wfn_response (self, atmlst=None, state=None, verbose=None, mo=None, ci=None, **kwargs):\n        if state is None: state = self.state\n        if atmlst is None: atmlst = self.atmlst\n        if verbose is None: verbose = self.verbose\n        if mo is None: mo = self.base.mo_coeff\n        if ci is None: ci = self.base.ci\n        ndet = self.na_states[state] * self.nb_states[state]\n        fcasscf = self.make_fcasscf (state)\n        fcasscf.mo_coeff = mo\n        fcasscf.ci = ci[state]\n        eris = fcasscf.ao2mo (mo)\n        g_all_state = newton_casscf.gen_g_hop (fcasscf, mo, ci[state], eris, verbose)[0]\n        g_all = np.zeros (self.nlag)\n        g_all[:self.ngorb] = g_all_state[:self.ngorb]\n        # No need to reshape or anything, just use the magic of repeated slicing\n        offs = sum ([na * nb for na, nb in zip (self.na_states[:state],\n            self.nb_states[:state])]) if state > 0 else 0\n        g_all[self.ngorb:][offs:][:ndet] = g_all_state[self.ngorb:]\n        return g_all\n\n    def get_Aop_Adiag (self, atmlst=None, state=None, verbose=None, mo=None, ci=None, eris=None, level_shift=None, **kwargs):\n        if state is None: state = self.state\n        if atmlst is None: atmlst = self.atmlst\n        if verbose is None: verbose = self.verbose\n        if mo is None: mo = self.base.mo_coeff\n        if ci is None: ci = self.base.ci\n        if eris is None and self.eris is None:\n            eris = self.eris = self.base.ao2mo (mo)\n        elif eris is None:\n            eris = self.eris\n        if not isinstance (self.base, StateAverageMCSCFSolver) and isinstance (ci, list): ci = ci[0]\n        fcasscf = self.make_fcasscf_sa ()\n        Aop, Adiag = newton_casscf.gen_g_hop (fcasscf, mo, ci, eris, verbose)[2:]\n        # Eliminate the component of Aop (x) which is parallel to the state-average space\n        # The Lagrange multiplier equations are not defined there\n        return self.project_Aop (Aop, ci, state), Adiag\n\n\n    def get_ham_response (self, state=None, atmlst=None, verbose=None, mo=None, ci=None, eris=None, mf_grad=None, **kwargs):\n        if state is None: state = self.state\n        if atmlst is None: atmlst = self.atmlst\n        if verbose is None: verbose = self.verbose\n        if mo is None: mo = self.base.mo_coeff\n        if ci is None: ci = self.base.ci\n        if eris is None and self.eris is None:\n            eris = self.eris = self.base.ao2mo (mo)\n        elif eris is None:\n            eris = self.eris\n        fcasscf_grad = casscf_grad.Gradients (self.make_fcasscf (state))\n        return fcasscf_grad.kernel (mo_coeff=mo, ci=ci[state], atmlst=atmlst, verbose=verbose)\n\n    def get_LdotJnuc (self, Lvec, state=None, atmlst=None, verbose=None, mo=None, ci=None, eris=None, mf_grad=None, **kwargs):\n        if state is None: state = self.state\n        if atmlst is None: atmlst = self.atmlst\n        if verbose is None: verbose = self.verbose\n        if mo is None: mo = self.base.mo_coeff\n        if ci is None: ci = self.base.ci[state]\n        if eris is None and self.eris is None:\n            eris = self.eris = self.base.ao2mo (mo)\n        elif eris is None:\n            eris = self.eris\n        ncas = self.base.ncas\n        nelecas = self.base.nelecas\n        if getattr(self.base.fcisolver, 'gen_linkstr', None):\n            linkstr  = self.base.fcisolver.gen_linkstr(ncas, nelecas, False)\n        else:\n            linkstr  = None\n\n        # Just sum the weights now... Lorb can be implicitly summed\n        # Lci may be in the csf basis\n        Lorb, Lci = self.unpack_uniq_var (Lvec)\n        #Lorb = self.base.unpack_uniq_var (Lvec[:self.ngorb])\n        #Lci = Lvec[self.ngorb:].reshape (self.nroots, -1)\n        #ci = np.ravel (ci).reshape (self.nroots, -1)\n\n        # CI part\n        t0 = (time.clock (), time.time ())\n        de_Lci = Lci_dot_dgci_dx (Lci, self.weights, self.base, mo_coeff=mo, ci=ci, atmlst=atmlst, mf_grad=mf_grad, eris=eris, verbose=verbose)\n        lib.logger.info (self, '--------------- %s gradient Lagrange CI response ---------------',\n                    self.base.__class__.__name__)\n        if verbose >= lib.logger.INFO: rhf_grad._write(self, self.mol, de_Lci, atmlst)\n        lib.logger.info (self, '----------------------------------------------------------------')\n        t0 = lib.logger.timer (self, '{} gradient Lagrange CI response'.format (self.base.__class__.__name__), *t0)\n\n        # Orb part\n        de_Lorb = Lorb_dot_dgorb_dx (Lorb, self.base, mo_coeff=mo, ci=ci, atmlst=atmlst, mf_grad=mf_grad, eris=eris, verbose=verbose)\n        lib.logger.info (self, '--------------- %s gradient Lagrange orbital response ---------------',\n                    self.base.__class__.__name__)\n        if verbose >= lib.logger.INFO: rhf_grad._write(self, self.mol, de_Lorb, atmlst)\n        lib.logger.info (self, '----------------------------------------------------------------------')\n        t0 = lib.logger.timer (self, '{} gradient Lagrange orbital response'.format (self.base.__class__.__name__), *t0)\n\n        return de_Lci + de_Lorb\n    \n    def debug_lagrange (self, Lvec, bvec, Aop, Adiag, state=None, mo=None, ci=None, **kwargs):\n        # This needs to be rewritten substantially to work properly with state_average_mix\n        if state is None: state = self.state\n        if mo is None: mo = self.base.mo_coeff\n        if ci is None: ci = self.base.ci\n        def _debug_cispace (xci, label):\n            xci_norm = [np.dot (c.ravel (), c.ravel ()) for c in xci]\n            try:\n                xci_ss = self.base.fcisolver.states_spin_square (xci, self.base.ncas, self.base.nelecas)[0]\n            except AttributeError:\n                nelec = sum (_unpack_nelec (self.base.nelecas))\n                xci_ss = [spin_square (x, self.base.ncas, ((nelec+m)//2,(nelec-m)//2))[0]\n                    for x, m in zip (xci, self.spin_states)]\n            xci_ss = [x / max (y, 1e-8) for x, y in zip (xci_ss, xci_norm)] \n            xci_multip = [np.sqrt (x+.25) - .5 for x in xci_ss]\n            for ix, (norm, ss, multip) in enumerate (zip (xci_norm, xci_ss, xci_multip)):\n                lib.logger.debug (self,\n                    ' State {} {} norm = {:.7e} ; <S^2> = {:.7f} ; 2S+1 = {:.7f}'.format\n                    (ix, label, norm, ss, multip))\n        borb, bci = self.unpack_uniq_var (bvec)\n        lib.logger.debug (self, 'Orbital rotation gradient norm = {:.7e}'.format (linalg.norm (borb)))\n        _debug_cispace (bci, 'CI gradient')\n        Aorb, Aci = self.unpack_uniq_var (Adiag)\n        lib.logger.debug (self, 'Orbital rotation Hamiltonian diagonal norm = {:.7e}'.format (linalg.norm (Aorb)))\n        _debug_cispace (Aci, 'Hamiltonian diagonal')\n        Lorb, Lci = self.unpack_uniq_var (Lvec)\n        lib.logger.debug (self, 'Orbital rotation Lagrange vector norm = {:.7e}'.format (linalg.norm (Lorb)))\n        _debug_cispace (Lci, 'Lagrange vector')\n        #lib.logger.info (self, '{} gradient: state = {}'.format (self.base.__class__.__name__, state))\n        #ngorb = self.ngorb\n        #nci = self.nci\n        #nroots = self.nroots\n        #ndet = nci // nroots\n        #ncore = self.base.ncore\n        #ncas = self.base.ncas\n        #nelecas = self.base.nelecas\n        #nocc = ncore + ncas\n        #nlag = self.nlag\n        #ci = np.asarray (self.base.ci).reshape (nroots, -1)\n        #err = Aop (Lvec) + bvec\n        #eorb = self.base.unpack_uniq_var (err[:ngorb])\n        #eci = err[ngorb:].reshape (nroots, -1)\n        #borb = self.base.unpack_uniq_var (bvec[:ngorb])\n        #bci = bvec[ngorb:].reshape (nroots, -1)\n        #Lorb = self.base.unpack_uniq_var (Lvec[:ngorb])\n        #Lci = Lvec[ngorb:].reshape (nroots, ndet)\n        #Aci = Adiag[ngorb:].reshape (nroots, ndet)\n        #Lci_ci_ovlp = (np.asarray (ci).reshape (nroots,-1).conjugate () @ Lci.T).T\n        #Lci_Lci_ovlp = (Lci.conjugate () @ Lci.T).T\n        #eci_ci_ovlp = (np.asarray (ci).reshape (nroots,-1).conjugate () @ eci.T).T\n        #bci_ci_ovlp = (np.asarray (ci).reshape (nroots,-1).conjugate () @ bci.T).T\n        #ci_ci_ovlp = ci.conjugate () @ ci.T\n        #lib.logger.debug (self, \"{} gradient RHS, inactive-active orbital rotations:\\n{}\".format (\n        #    self.base.__class__.__name__, borb[:ncore,ncore:nocc]))\n        #lib.logger.debug (self, \"{} gradient RHS, inactive-external orbital rotations:\\n{}\".format (\n        #    self.base.__class__.__name__, borb[:ncore,nocc:]))\n        #lib.logger.debug (self, \"{} gradient RHS, active-external orbital rotations:\\n{}\".format (\n        #    self.base.__class__.__name__, borb[ncore:nocc,nocc:]))\n        #lib.logger.debug (self, \"{} gradient residual, inactive-active orbital rotations:\\n{}\".format (\n        #    self.base.__class__.__name__, eorb[:ncore,ncore:nocc]))\n        #lib.logger.debug (self, \"{} gradient residual, inactive-external orbital rotations:\\n{}\".format (\n        #    self.base.__class__.__name__, eorb[:ncore,nocc:]))\n        #lib.logger.debug (self, \"{} gradient residual, active-external orbital rotations:\\n{}\".format (\n        #    self.base.__class__.__name__, eorb[ncore:nocc,nocc:]))\n        #lib.logger.debug (self, \"{} gradient Lagrange factor, inactive-active orbital rotations:\\n{}\".format (\n        #    self.base.__class__.__name__, Lorb[:ncore,ncore:nocc]))\n        #lib.logger.debug (self, \"{} gradient Lagrange factor, inactive-external orbital rotations:\\n{}\".format (\n        #    self.base.__class__.__name__, Lorb[:ncore,nocc:]))\n        #lib.logger.debug (self, \"{} gradient Lagrange factor, active-external orbital rotations:\\n{}\".format (\n        #    self.base.__class__.__name__, Lorb[ncore:nocc,nocc:]))\n        #'''\n        #lib.logger.debug (self, \"{} gradient RHS, inactive-inactive orbital rotations (redundant!):\\n{}\".format (\n        #    self.base.__class__.__name__, borb[:ncore,:ncore]))\n        #lib.logger.debug (self, \"{} gradient RHS, active-active orbital rotations (redundant!):\\n{}\".format (\n        #    self.base.__class__.__name__, borb[ncore:nocc,ncore:nocc]))\n        #lib.logger.debug (self, \"{} gradient RHS, external-external orbital rotations (redundant!):\\n{}\".format (\n        #    self.base.__class__.__name__, borb[nocc:,nocc:]))\n        #lib.logger.debug (self, \"{} gradient Lagrange factor, inactive-inactive orbital rotations (redundant!):\\n{}\".format (\n        #    self.base.__class__.__name__, Lorb[:ncore,:ncore]))\n        #lib.logger.debug (self, \"{} gradient Lagrange factor, active-active orbital rotations (redundant!):\\n{}\".format (\n        #    self.base.__class__.__name__, Lorb[ncore:nocc,ncore:nocc]))\n        #lib.logger.debug (self, \"{} gradient Lagrange factor, external-external orbital rotations (redundant!):\\n{}\".format (\n        #    self.base.__class__.__name__, Lorb[nocc:,nocc:]))\n        #'''\n        #lib.logger.debug (self, \"{} gradient Lagrange factor, CI part overlap with true CI SA space:\\n{}\".format ( \n        #    self.base.__class__.__name__, Lci_ci_ovlp))\n        #lib.logger.debug (self, \"{} gradient Lagrange factor, CI part self overlap matrix:\\n{}\".format ( \n        #    self.base.__class__.__name__, Lci_Lci_ovlp))\n        #lib.logger.debug (self, \"{} gradient Lagrange factor, CI vector self overlap matrix:\\n{}\".format ( \n        #    self.base.__class__.__name__, ci_ci_ovlp))\n        #lib.logger.debug (self, \"{} gradient Lagrange factor, CI part response overlap with SA space:\\n{}\".format ( \n        #    self.base.__class__.__name__, bci_ci_ovlp))\n        #lib.logger.debug (self, \"{} gradient Lagrange factor, CI part residual overlap with SA space:\\n{}\".format ( \n        #    self.base.__class__.__name__, eci_ci_ovlp))\n        #neleca, nelecb = _unpack_nelec (nelecas)\n        #spin = neleca - nelecb + 1\n        #csf = CSFTransformer (ncas, neleca, nelecb, spin)\n        #ecsf = csf.vec_det2csf (eci, normalize=False, order='C')\n        #err_norm_det = linalg.norm (err)\n        #err_norm_csf = linalg.norm (np.append (eorb, ecsf.ravel ()))\n        #lib.logger.debug (self, \"{} gradient: determinant residual = {}, CSF residual = {}\".format (\n        #    self.base.__class__.__name__, err_norm_det, err_norm_csf))\n        #ci_lbls, ci_csf   = csf.printable_largest_csf (ci,  10, isdet=True, normalize=True,  order='C')\n        #bci_lbls, bci_csf = csf.printable_largest_csf (bci, 10, isdet=True, normalize=False, order='C')\n        #eci_lbls, eci_csf = csf.printable_largest_csf (eci, 10, isdet=True, normalize=False, order='C')\n        #Lci_lbls, Lci_csf = csf.printable_largest_csf (Lci, 10, isdet=True, normalize=False, order='C')\n        #Aci_lbls, Aci_csf = csf.printable_largest_csf (Aci, 10, isdet=True, normalize=False, order='C')\n        #ncsf = bci_csf.shape[1]\n        #for iroot in range (self.nroots):\n        #    lib.logger.debug (self, \"{} gradient Lagrange factor, CI part root {} spin square: {}\".format (\n        #        self.base.__class__.__name__, iroot, spin_square (Lci[iroot], ncas, nelecas)))\n        #    lib.logger.debug (self, \"Base CI vector\")\n        #    for icsf in range (ncsf):\n        #        lib.logger.debug (self, '{} {}'.format (ci_lbls[iroot,icsf], ci_csf[iroot,icsf]))\n        #    lib.logger.debug (self, \"CI gradient:\")\n        #    for icsf in range (ncsf):\n        #        lib.logger.debug (self, '{} {}'.format (bci_lbls[iroot,icsf], bci_csf[iroot,icsf]))\n        #    lib.logger.debug (self, \"CI residual:\")\n        #    for icsf in range (ncsf):\n        #        lib.logger.debug (self, '{} {}'.format (eci_lbls[iroot,icsf], eci_csf[iroot,icsf]))\n        #    lib.logger.debug (self, \"CI Lagrange vector:\")\n        #    for icsf in range (ncsf):\n        #        lib.logger.debug (self, '{} {}'.format (Lci_lbls[iroot,icsf], Lci_csf[iroot,icsf]))\n        #    lib.logger.debug (self, \"Diagonal of Hessian matrix CI part:\")\n        #    for icsf in range (ncsf):\n        #        lib.logger.debug (self, '{} {}'.format (Aci_lbls[iroot,icsf], Aci_csf[iroot,icsf]))\n        #'''\n        #Afull = np.zeros ((nlag, nlag))\n        #dum = np.zeros ((nlag))\n        #for ix in range (nlag):\n        #    dum[ix] = 1\n        #    Afull[ix,:] = Aop (dum)\n        #    dum[ix] = 0\n        #Afull_orborb = Afull[:ngorb,:ngorb]\n        #Afull_orbci = Afull[:ngorb,ngorb:].reshape (ngorb, nroots, ndet)\n        #Afull_ciorb = Afull[ngorb:,:ngorb].reshape (nroots, ndet, ngorb)\n        #Afull_cici = Afull[ngorb:,ngorb:].reshape (nroots, ndet, nroots, ndet).transpose (0, 2, 1, 3)\n        #lib.logger.debug (self, \"Orb-orb Hessian:\\n{}\".format (Afull_orborb))\n        #for iroot in range (nroots):\n        #    lib.logger.debug (self, \"Orb-ci Hessian root {}:\\n{}\".format (iroot, Afull_orbci[:,iroot,:]))\n        #    lib.logger.debug (self, \"Ci-orb Hessian root {}:\\n{}\".format (iroot, Afull_ciorb[iroot,:,:]))\n        #    for jroot in range (nroots):\n        #        lib.logger.debug (self, \"Ci-ci Hessian roots {},{}:\\n{}\".format (iroot, jroot, Afull_cici[iroot,jroot,:,:]))\n        #'''\n\n\n    def get_lagrange_precond (self, Adiag, level_shift=None, ci=None, **kwargs):\n        if level_shift is None: level_shift = self.level_shift\n        if ci is None: ci = self.base.ci\n        return SACASLagPrec (Adiag=Adiag, level_shift=level_shift, ci=ci, grad_method=self)\n\n    def get_lagrange_callback (self, Lvec_last, itvec, geff_op):\n        def my_call (x):\n            itvec[0] += 1\n            geff = geff_op (x)\n            deltax = x - Lvec_last\n            gorb, gci = self.unpack_uniq_var (geff)\n            deltaorb, deltaci = self.unpack_uniq_var (deltax)\n            gci = np.concatenate ([g.ravel () for g in gci])\n            deltaci = np.concatenate ([d.ravel () for d in deltaci])\n            lib.logger.info (self, ('Lagrange optimization iteration {}, |gorb| = {}, |gci| = {}, '\n                '|dLorb| = {}, |dLci| = {}').format (itvec[0], linalg.norm (gorb), linalg.norm (gci),\n                linalg.norm (deltaorb), linalg.norm (deltaci))) \n            Lvec_last[:] = x[:]\n        return my_call\n\n    def project_Aop (self, Aop, ci, state):\n        ''' Wrap the Aop function to project out redundant degrees of freedom for the CI part.  What's redundant\n            changes between SA-CASSCF and MC-PDFT so modify this part in child classes. '''\n        def my_Aop (x):\n            Ax = Aop (x)\n            Ax_orb, Ax_ci = self.unpack_uniq_var (Ax)\n            for i, j in product (range (self.nroots), repeat=2):\n                # I'm assuming the only symmetry here that's actually built into the data structure is solver.spin\n                # This will be the case as long as the various solvers are determinants with a common total charge\n                # occupying a common set of orbitals\n                if self.spin_states[i] != self.spin_states[j]: continue\n                Ax_ci[i] -= np.dot (Ax_ci[i].ravel (), ci[j].ravel ()) * ci[j]\n            #Ax_ci = Ax[self.ngorb:].reshape (self.nroots, -1)\n            #ci_arr = np.asarray (ci).reshape (self.nroots, -1)\n            #ovlp = np.dot (ci_arr.conjugate (), Ax_ci.T)\n            #Ax_ci -= np.dot (ovlp.T, ci_arr)\n            #Ax[self.ngorb:] = Ax_ci.ravel ()\n            return self.pack_uniq_var (Ax_orb, Ax_ci)\n        return my_Aop\n\n    as_scanner = as_scanner\n\nclass SACASLagPrec (lagrange.LagPrec):\n    ''' A callable preconditioner for solving the Lagrange equations. Based on Mol. Phys. 99, 103 (2001).\n    Attributes:\n\n    nroots : integer\n        Number of roots in the SA space\n    nlag : integer\n        Number of Lagrange degrees of freedom\n    ngorb : integer\n        Number of Lagrange degrees of freedom which are orbital rotations\n    level_shift : float\n        numerical shift applied to CI rotation Hessian\n    ci : ndarray of shape (nroots, ndet or ncscf)\n        Ci vectors of the SA space\n    Rorb : ndarray of shape (ngorb)\n        Diagonal inverse Hessian matrix for orbital rotations\n    Rci : ndarray of shape (nroots, ndet or ncsf)\n        Diagonal inverse Hessian matrix for CI rotations including a level shift\n    Rci_sa : ndarray of shape (nroots (I), ndet or ncsf, nroots (K))\n        First two factors of the inverse diagonal CI Hessian projected into SA space:\n        Rci(I)|J> <J|Rci(I)|K>^{-1} <K|Rci(I)\n        note: right-hand bra and R_I factor not included due to storage considerations\n        Make the operand's matrix element with <K|Rci(I) before taking the dot product! \n'''\n\n    # TODO: fix me (subclass me? wrap me?) for state_average_mix\n    def __init__(self, Adiag=None, level_shift=None, ci=None, grad_method=None):\n        self.level_shift = level_shift\n        self.nroots = grad_method.nroots\n        self.nlag = grad_method.nlag\n        self.ngorb = grad_method.ngorb\n        self.spin_states = grad_method.spin_states\n        self.na_states = grad_method.na_states\n        self.nb_states = grad_method.nb_states\n        self.grad_method = grad_method\n        Aorb, Aci = self.unpack_uniq_var (Adiag)\n        self._init_orb (Aorb)\n        self._init_ci (Aci, ci)\n\n    def unpack_uniq_var (self, x):\n        return self.grad_method.unpack_uniq_var (x)\n\n    def pack_uniq_var (self, xorb, xci):\n        return self.grad_method.pack_uniq_var (xorb, xci)\n\n    def _init_orb (self, Aorb):\n        self.Rorb = Aorb\n        self.Rorb[abs(self.Rorb)<1e-8] = 1e-8\n        self.Rorb = 1./self.Rorb\n\n    def _init_ci (self, Aci_spins, ci_spins):\n        self.ci = []\n        self.Rci = []\n        self.Rci_sa = []\n        for [Aci, ci] in self._iterate_ci (Aci_spins, ci_spins):\n            nroots = Aci.shape[0]\n            Rci = Aci + self.level_shift\n            Rci[abs(Rci)<1e-8] = 1e-8\n            Rci = 1./Rci\n            # R_I|J> \n            # Indices: I, det, J\n            Rci_cross = Rci[:,:,None] * ci.T[None,:,:]\n            # S(I)_JK = <J|R_I|K> (first index of CI contract with middle index of R_I|J> and reshape to put I first)\n            Sci = np.tensordot (ci.conjugate (), Rci_cross, axes=(1,1)).transpose (1,0,2)\n            # R_I|J> S(I)_JK^-1 (can only loop explicitly because of necessary call to linalg.inv)\n            # Indices: I, det, K\n            Rci_sa = np.zeros_like (Rci_cross)\n            for iroot in range (nroots):\n                Rci_sa[iroot] = np.dot (Rci_cross[iroot], linalg.inv (Sci[iroot]))\n            self.ci.append (ci)\n            self.Rci.append (Rci)\n            self.Rci_sa.append (Rci_sa)\n\n    def _iterate_ci (self, *args):\n        # All args must be iterables over CI vectors in input order\n        # Eventually, get rid of copying (np.asarray, etc.)\n        # Don't assume args are ndarrays on input\n        for my_spin in np.unique (self.spin_states):\n            idx = np.where (self.spin_states == my_spin)[0]\n            yield [np.asarray ([arg[i] for i in idx]).reshape (len (idx), -1) for arg in args]\n\n    def __call__(self, x):\n        xorb, xci = self.unpack_uniq_var (x)\n        Mxorb = self.orb_prec (xorb)\n        Mxci = self.ci_prec (xci)\n        return self.pack_uniq_var (Mxorb, Mxci)\n\n    def orb_prec (self, xorb):\n        return self.Rorb * xorb\n\n    def ci_prec (self, xci_spins):\n        Mxci = [None,] * self.nroots\n        for ix_spin, [xci, desort_spin] in enumerate (self._iterate_ci (xci_spins, list(range(self.nroots)))):\n            desort_spin = np.atleast_1d (np.squeeze (desort_spin))\n            nroots = xci.shape[0]\n            ci = self.ci[ix_spin]\n            Rci = self.Rci[ix_spin]\n            Rci_sa = self.Rci_sa[ix_spin]\n            # R_I|H I> (indices: I, det)\n            Rx = Rci * xci\n            # <J|R_I|H I> (indices: J, I)\n            sa_ovlp = np.dot (ci.conjugate (), Rx.T) \n            # R_I|J> S(I)_JK^-1 <K|R_I|H I> (indices: I, det)\n            Rx_sub = np.zeros_like (Rx)\n            for iroot in range (nroots): \n                Rx_sub[iroot] = np.dot (Rci_sa[iroot], sa_ovlp[:,iroot])\n            for i, j in enumerate (desort_spin):\n                try:\n                    Mxci[j] = Rx[i] - Rx_sub[i]\n                except Exception as e:\n                    print (i, j, desort_spin)\n                    raise (e)\n        assert (all ([i is not None for i in Mxci]))\n        return Mxci\n\nfrom pyscf import mcscf\nmcscf.addons.StateAverageMCSCFSolver.Gradients = lib.class_as_method(Gradients)\n\n\n", "meta": {"hexsha": "45517b2213161c54fc7fb9c7ffce04dc2c6a96a5", "size": 46154, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/grad/sacasscf.py", "max_stars_repo_name": "mfkasim1/pyscf", "max_stars_repo_head_hexsha": "7be5e015b2b40181755c71d888449db936604660", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-24T13:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T13:35:42.000Z", "max_issues_repo_path": "pyscf/grad/sacasscf.py", "max_issues_repo_name": "mfkasim1/pyscf", "max_issues_repo_head_hexsha": "7be5e015b2b40181755c71d888449db936604660", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscf/grad/sacasscf.py", "max_forks_repo_name": "mfkasim1/pyscf", "max_forks_repo_head_hexsha": "7be5e015b2b40181755c71d888449db936604660", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-02-26T16:01:42.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-26T16:01:42.000Z", "avg_line_length": 51.7421524664, "max_line_length": 188, "alphanum_fraction": 0.6169129436, "include": true, "reason": "import numpy,from scipy", "num_tokens": 14205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.25386100696924885, "lm_q1q2_score": 0.16980261979090858}}
{"text": "#!/usr/bin/env python3\n# Copyright 2018 Mitsubishi Electric Research Labs (Takaaki Hori)\n#  Apache 2.0  (http://www.apache.org/licenses/LICENSE-2.0)\nimport numpy as np\nimport paddle\nimport six\n\n\nclass CTCPrefixScorePD():\n    \"\"\"Batch processing of CTCPrefixScore\n\n    which is based on Algorithm 2 in WATANABE et al.\n    \"HYBRID CTC/ATTENTION ARCHITECTURE FOR END-TO-END SPEECH RECOGNITION,\"\n    but extended to efficiently compute the label probablities for multiple\n    hypotheses simultaneously\n    See also Seki et al. \"Vectorized Beam Search for CTC-Attention-Based\n    Speech Recognition,\" In INTERSPEECH (pp. 3825-3829), 2019.\n    \"\"\"\n\n    def __init__(self, x, xlens, blank, eos, margin=0):\n        \"\"\"Construct CTC prefix scorer\n\n        `margin` is M in eq.(22,23)\n\n        :param paddle.Tensor x: input label posterior sequences (B, T, O)\n        :param paddle.Tensor xlens: input lengths (B,)\n        :param int blank: blank label id\n        :param int eos: end-of-sequence id\n        :param int margin: margin parameter for windowing (0 means no windowing)\n        \"\"\"\n        # In the comment lines,\n        # we assume T: input_length, B: batch size, W: beam width, O: output dim.\n        self.logzero = -10000000000.0\n        self.blank = blank\n        self.eos = eos\n        self.batch = x.size(0)\n        self.input_length = x.size(1)\n        self.odim = x.size(2)\n        self.dtype = x.dtype\n\n        # Pad the rest of posteriors in the batch\n        # TODO(takaaki-hori): need a better way without for-loops\n        for i, l in enumerate(xlens):\n            if l < self.input_length:\n                x[i, l:, :] = self.logzero\n                x[i, l:, blank] = 0\n        # Reshape input x\n        xn = x.transpose([1, 0, 2])  # (B, T, O) -> (T, B, O)\n        xb = xn[:, :, self.blank].unsqueeze(2).expand(-1, -1,\n                                                      self.odim)  # (T,B,O)\n        self.x = paddle.stack([xn, xb])  # (2, T, B, O)\n        self.end_frames = paddle.to_tensor(xlens) - 1  # (B,)\n\n        # Setup CTC windowing\n        self.margin = margin\n        if margin > 0:\n            self.frame_ids = paddle.arange(self.input_length, dtype=self.dtype)\n        # Base indices for index conversion\n        # B idx, hyp idx. shape (B*W, 1)\n        self.idx_bh = None\n        # B idx. shape (B,)\n        self.idx_b = paddle.arange(self.batch)\n        # B idx, O idx. shape (B, 1)\n        self.idx_bo = (self.idx_b * self.odim).unsqueeze(1)\n\n    def __call__(self, y, state, scoring_ids=None, att_w=None):\n        \"\"\"Compute CTC prefix scores for next labels\n\n        :param list y: prefix label sequences\n        :param tuple state: previous CTC state\n        :param paddle.Tensor scoring_ids: selected next ids to score (BW, O'), O' <= O\n        :param paddle.Tensor att_w: attention weights to decide CTC window\n        :return new_state, ctc_local_scores (BW, O)\n        \"\"\"\n        output_length = len(y[0]) - 1  # ignore sos\n        last_ids = [yi[-1] for yi in y]  # last output label ids\n        n_bh = len(last_ids)  # batch * hyps\n        n_hyps = n_bh // self.batch  # assuming each utterance has the same # of hyps\n        self.scoring_num = scoring_ids.size(\n            -1) if scoring_ids is not None else 0\n        # prepare state info\n        if state is None:\n            r_prev = paddle.full(\n                (self.input_length, 2, self.batch, n_hyps),\n                self.logzero,\n                dtype=self.dtype, )  # (T, 2, B, W)\n            r_prev[:, 1] = paddle.cumsum(self.x[0, :, :, self.blank],\n                                         0).unsqueeze(2)\n            r_prev = r_prev.view(-1, 2, n_bh)  # (T, 2, BW)\n            s_prev = 0.0  # score\n            f_min_prev = 0  # eq. 22-23\n            f_max_prev = 1  # eq. 22-23\n        else:\n            r_prev, s_prev, f_min_prev, f_max_prev = state\n\n        # select input dimensions for scoring\n        if self.scoring_num > 0:\n            # (BW, O)\n            scoring_idmap = paddle.full(\n                (n_bh, self.odim), -1, dtype=paddle.long)\n            snum = self.scoring_num\n            if self.idx_bh is None or n_bh > len(self.idx_bh):\n                self.idx_bh = paddle.arange(n_bh).view(-1, 1)  # (BW, 1)\n            scoring_idmap[self.idx_bh[:n_bh], scoring_ids] = paddle.arange(snum)\n            scoring_idx = (\n                scoring_ids + self.idx_bo.repeat(1, n_hyps).view(-1,\n                                                                 1)  # (BW,1)\n            ).view(-1)  # (BWO)\n            # x_ shape (2, T, B*W, O)\n            x_ = paddle.index_select(\n                self.x.view(2, -1, self.batch * self.odim), scoring_idx,\n                2).view(2, -1, n_bh, snum)\n        else:\n            scoring_ids = None\n            scoring_idmap = None\n            snum = self.odim\n            # x_ shape (2, T, B*W, O)\n            x_ = self.x.unsqueeze(3).repeat(1, 1, 1, n_hyps, 1).view(2, -1,\n                                                                     n_bh, snum)\n\n        # new CTC forward probs are prepared as a (T x 2 x BW x S) tensor\n        # that corresponds to r_t^n(h) and r_t^b(h) in a batch.\n        r = paddle.full(\n            (self.input_length, 2, n_bh, snum),\n            self.logzero,\n            dtype=self.dtype, )\n        if output_length == 0:\n            r[0, 0] = x_[0, 0]\n\n        r_sum = paddle.logsumexp(r_prev, 1)  #(T,BW)\n        log_phi = r_sum.unsqueeze(2).repeat(1, 1, snum)  # (T, BW, O)\n        if scoring_ids is not None:\n            for idx in range(n_bh):\n                pos = scoring_idmap[idx, last_ids[idx]]\n                if pos >= 0:\n                    log_phi[:, idx, pos] = r_prev[:, 1, idx]\n        else:\n            for idx in range(n_bh):\n                log_phi[:, idx, last_ids[idx]] = r_prev[:, 1, idx]\n\n        # decide start and end frames based on attention weights\n        if att_w is not None and self.margin > 0:\n            f_arg = paddle.matmul(att_w, self.frame_ids)\n            f_min = max(int(f_arg.min().cpu()), f_min_prev)\n            f_max = max(int(f_arg.max().cpu()), f_max_prev)\n            start = min(f_max_prev, max(f_min - self.margin, output_length, 1))\n            end = min(f_max + self.margin, self.input_length)\n        else:\n            f_min = f_max = 0\n            # if one frame one out, the output_length is the eating frame num now.\n            start = max(output_length, 1)\n            end = self.input_length\n\n        # compute forward probabilities log(r_t^n(h)) and log(r_t^b(h))\n        for t in range(start, end):\n            rp = r[t - 1]  # (2 x BW x O') \n            rr = paddle.stack([rp[0], log_phi[t - 1], rp[0], rp[1]]).view(\n                2, 2, n_bh, snum)  # (2,2,BW,O')\n            r[t] = paddle.logsumexp(rr, 1) + x_[:, t]\n\n        # compute log prefix probabilities log(psi)\n        log_phi_x = paddle.concat(\n            (log_phi[0].unsqueeze(0), log_phi[:-1]), axis=0) + x_[0]\n        if scoring_ids is not None:\n            log_psi = paddle.full(\n                (n_bh, self.odim), self.logzero, dtype=self.dtype)\n            log_psi_ = paddle.logsumexp(\n                paddle.concat(\n                    (log_phi_x[start:end], r[start - 1, 0].unsqueeze(0)),\n                    axis=0),\n                axis=0, )\n            for si in range(n_bh):\n                log_psi[si, scoring_ids[si]] = log_psi_[si]\n        else:\n            log_psi = paddle.logsumexp(\n                paddle.concat(\n                    (log_phi_x[start:end], r[start - 1, 0].unsqueeze(0)),\n                    axis=0),\n                axis=0, )\n\n        for si in range(n_bh):\n            log_psi[si, self.eos] = r_sum[self.end_frames[si // n_hyps], si]\n\n        # exclude blank probs\n        log_psi[:, self.blank] = self.logzero\n\n        return (log_psi - s_prev), (r, log_psi, f_min, f_max, scoring_idmap)\n\n    def index_select_state(self, state, best_ids):\n        \"\"\"Select CTC states according to best ids\n\n        :param state    : CTC state\n        :param best_ids : index numbers selected by beam pruning (B, W)\n        :return selected_state\n        \"\"\"\n        r, s, f_min, f_max, scoring_idmap = state\n        # convert ids to BHO space\n        n_bh = len(s)\n        n_hyps = n_bh // self.batch\n        vidx = (best_ids + (self.idx_b *\n                            (n_hyps * self.odim)).view(-1, 1)).view(-1)\n        # select hypothesis scores\n        s_new = paddle.index_select(s.view(-1), vidx, 0)\n        s_new = s_new.view(-1, 1).repeat(1, self.odim).view(n_bh, self.odim)\n        # convert ids to BHS space (S: scoring_num)\n        if scoring_idmap is not None:\n            snum = self.scoring_num\n            hyp_idx = (best_ids // self.odim +\n                       (self.idx_b * n_hyps).view(-1, 1)).view(-1)\n            label_ids = paddle.fmod(best_ids, self.odim).view(-1)\n            score_idx = scoring_idmap[hyp_idx, label_ids]\n            score_idx[score_idx == -1] = 0\n            vidx = score_idx + hyp_idx * snum\n        else:\n            snum = self.odim\n        # select forward probabilities\n        r_new = paddle.index_select(r.view(-1, 2, n_bh * snum), vidx, 2).view(\n            -1, 2, n_bh)\n        return r_new, s_new, f_min, f_max\n\n    def extend_prob(self, x):\n        \"\"\"Extend CTC prob.\n\n        :param paddle.Tensor x: input label posterior sequences (B, T, O)\n        \"\"\"\n\n        if self.x.shape[1] < x.shape[1]:  # self.x (2,T,B,O); x (B,T,O)\n            # Pad the rest of posteriors in the batch\n            # TODO(takaaki-hori): need a better way without for-loops\n            xlens = [x.size(1)]\n            for i, l in enumerate(xlens):\n                if l < self.input_length:\n                    x[i, l:, :] = self.logzero\n                    x[i, l:, self.blank] = 0\n            tmp_x = self.x\n            xn = x.transpose([1, 0, 2])  # (B, T, O) -> (T, B, O)\n            xb = xn[:, :, self.blank].unsqueeze(2).expand(-1, -1, self.odim)\n            self.x = paddle.stack([xn, xb])  # (2, T, B, O)\n            self.x[:, :tmp_x.shape[1], :, :] = tmp_x\n            self.input_length = x.size(1)\n            self.end_frames = paddle.to_tensor(xlens) - 1\n\n    def extend_state(self, state):\n        \"\"\"Compute CTC prefix state.\n\n\n        :param state    : CTC state\n        :return ctc_state\n        \"\"\"\n\n        if state is None:\n            # nothing to do\n            return state\n        else:\n            r_prev, s_prev, f_min_prev, f_max_prev = state\n\n            r_prev_new = paddle.full(\n                (self.input_length, 2),\n                self.logzero,\n                dtype=self.dtype, )\n            start = max(r_prev.shape[0], 1)\n            r_prev_new[0:start] = r_prev\n            for t in range(start, self.input_length):\n                r_prev_new[t, 1] = r_prev_new[t - 1, 1] + self.x[0, t, :,\n                                                                 self.blank]\n\n            return (r_prev_new, s_prev, f_min_prev, f_max_prev)\n\n\nclass CTCPrefixScore():\n    \"\"\"Compute CTC label sequence scores\n\n    which is based on Algorithm 2 in WATANABE et al.\n    \"HYBRID CTC/ATTENTION ARCHITECTURE FOR END-TO-END SPEECH RECOGNITION,\"\n    but extended to efficiently compute the probablities of multiple labels\n    simultaneously\n    \"\"\"\n\n    def __init__(self, x, blank, eos, xp):\n        self.xp = xp\n        self.logzero = -10000000000.0\n        self.blank = blank\n        self.eos = eos\n        self.input_length = len(x)\n        self.x = x  # (T, O)\n\n    def initial_state(self):\n        \"\"\"Obtain an initial CTC state\n\n        :return: CTC state\n        \"\"\"\n        # initial CTC state is made of a frame x 2 tensor that corresponds to\n        # r_t^n(<sos>) and r_t^b(<sos>), where 0 and 1 of axis=1 represent\n        # superscripts n and b (non-blank and blank), respectively.\n        # r shape (T, 2)\n        r = self.xp.full((self.input_length, 2), self.logzero, dtype=np.float32)\n        r[0, 1] = self.x[0, self.blank]\n        for i in six.moves.range(1, self.input_length):\n            r[i, 1] = r[i - 1, 1] + self.x[i, self.blank]\n        return r\n\n    def __call__(self, y, cs, r_prev):\n        \"\"\"Compute CTC prefix scores for next labels\n\n        :param y     : prefix label sequence\n        :param cs    : array of next labels\n        :param r_prev: previous CTC state\n        :return ctc_scores, ctc_states\n        \"\"\"\n        # initialize CTC states\n        output_length = len(y) - 1  # ignore sos\n        # new CTC states are prepared as a frame x (n or b) x n_labels tensor\n        # that corresponds to r_t^n(h) and r_t^b(h).\n        # r shape (T, 2, n_labels)\n        r = self.xp.ndarray((self.input_length, 2, len(cs)), dtype=np.float32)\n        xs = self.x[:, cs]\n        if output_length == 0:\n            r[0, 0] = xs[0]\n            r[0, 1] = self.logzero\n        else:\n            # Although the code does not exactly follow Algorithm 2, \n            # we don't have to change it because we can assume \n            # r_t(h)=0 for t < |h| in CTC forward computation \n            # (Note: we assume here that index t starts with 0).\n            # The purpose of this difference is to reduce the number of for-loops.\n            # https://github.com/espnet/espnet/pull/3655\n            # where we start to accumulate r_t(h) from t=|h| \n            # and iterate r_t(h) = (r_{t-1}(h) + ...) to T-1, \n            # avoiding accumulating zeros for t=1~|h|-1.\n            # Thus, we need to set r_{|h|-1}(h) = 0, \n            # i.e., r[output_length-1] = logzero, for initialization.\n            # This is just for reducing the computation.\n            r[output_length - 1] = self.logzero\n\n        # prepare forward probabilities for the last label\n        r_sum = self.xp.logaddexp(r_prev[:, 0],\n                                  r_prev[:, 1])  # log(r_t^n(g) + r_t^b(g))\n        last = y[-1]\n        if output_length > 0 and last in cs:\n            log_phi = self.xp.ndarray(\n                (self.input_length, len(cs)), dtype=np.float32)\n            for i in six.moves.range(len(cs)):\n                log_phi[:, i] = r_sum if cs[i] != last else r_prev[:, 1]\n        else:\n            log_phi = r_sum\n\n        # compute forward probabilities log(r_t^n(h)), log(r_t^b(h)),\n        # and log prefix probabilities log(psi)\n        start = max(output_length, 1)\n        log_psi = r[start - 1, 0]\n        for t in six.moves.range(start, self.input_length):\n            r[t, 0] = self.xp.logaddexp(r[t - 1, 0], log_phi[t - 1]) + xs[t]\n            r[t, 1] = (self.xp.logaddexp(r[t - 1, 0], r[t - 1, 1]) +\n                       self.x[t, self.blank])\n            log_psi = self.xp.logaddexp(log_psi, log_phi[t - 1] + xs[t])\n\n        # get P(...eos|X) that ends with the prefix itself\n        eos_pos = self.xp.where(cs == self.eos)[0]\n        if len(eos_pos) > 0:\n            log_psi[eos_pos] = r_sum[-1]  # log(r_T^n(g) + r_T^b(g))\n\n        # exclude blank probs\n        blank_pos = self.xp.where(cs == self.blank)[0]\n        if len(blank_pos) > 0:\n            log_psi[blank_pos] = self.logzero\n\n        # return the log prefix probability and CTC states, where the label axis\n        # of the CTC states is moved to the first axis to slice it easily\n        # log_psi shape (n_labels,), state shape (n_labels, T, 2)\n        return log_psi, self.xp.rollaxis(r, 2)\n", "meta": {"hexsha": "13429d491399e5b0f12268dfe6cde805691ba7cf", "size": 15289, "ext": "py", "lang": "Python", "max_stars_repo_path": "paddlespeech/s2t/decoders/scorers/ctc_prefix_score.py", "max_stars_repo_name": "JiehangXie/PaddleSpeech", "max_stars_repo_head_hexsha": "60090b49ec27437127ab62358026dd5bb95fccc7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1540, "max_stars_repo_stars_event_min_datetime": "2017-11-14T13:26:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T14:05:08.000Z", "max_issues_repo_path": "paddlespeech/s2t/decoders/scorers/ctc_prefix_score.py", "max_issues_repo_name": "JiehangXie/PaddleSpeech", "max_issues_repo_head_hexsha": "60090b49ec27437127ab62358026dd5bb95fccc7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 599, "max_issues_repo_issues_event_min_datetime": "2017-11-14T13:19:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-09T01:58:26.000Z", "max_forks_repo_path": "paddlespeech/s2t/decoders/scorers/ctc_prefix_score.py", "max_forks_repo_name": "JiehangXie/PaddleSpeech", "max_forks_repo_head_hexsha": "60090b49ec27437127ab62358026dd5bb95fccc7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 449, "max_forks_repo_forks_event_min_datetime": "2017-11-14T12:48:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-06T09:34:33.000Z", "avg_line_length": 41.2102425876, "max_line_length": 86, "alphanum_fraction": 0.5322781084, "include": true, "reason": "import numpy", "num_tokens": 4266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.30404168127272885, "lm_q1q2_score": 0.1697546780576766}}
{"text": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@File    :   WTM.py\n@Time    :   2020/10/06 17:13:43\n@Author  :   Leilan Zhang\n@Version :   1.0\n@Contact :   zhangleilan@gmail.com\n@Desc    :   None\n'''\n\n\nimport os\nimport re\nimport time\nimport pickle\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\nimport numpy as np\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nfrom .wae import WAE\nimport sys\nsys.path.append('..')\nfrom utils import evaluate_topic_quality, smooth_curve\n\nclass WTM:\n    def __init__(self, bow_dim=10000, n_topic=20, device=None, dist='gmm_std', taskname=None, dropout=0.0):\n        self.bow_dim = bow_dim\n        self.n_topic = n_topic\n        self.wae = WAE(encode_dims=[bow_dim, 1024, 512, n_topic], decode_dims=[n_topic, 512, bow_dim], dropout=dropout, nonlin='relu')\n        self.device = device\n        self.id2token = None\n        self.dist = dist\n        self.taskname = taskname\n        if device != None:\n            self.wae = self.wae.to(device)\n\n    def train(self, train_data, batch_size=256, learning_rate=1e-3, test_data=None, num_epochs=100, is_evaluate=False, log_every=5, beta=1.0):\n        self.wae.train()\n        self.id2token = {v: k for k,v in train_data.dictionary.token2id.items()}\n        data_loader = DataLoader(train_data, batch_size=batch_size,shuffle=True, num_workers=4, collate_fn=train_data.collate_fn)\n\n        optimizer = torch.optim.Adam(self.wae.parameters(), lr=learning_rate)\n        #scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.5)\n        trainloss_lst, valloss_lst = [], []\n        c_v_lst, c_w2v_lst, c_uci_lst, c_npmi_lst, mimno_tc_lst, td_lst = [], [], [], [], [], []\n        for epoch in range(num_epochs):\n            epochloss_lst = []\n            for iter, data in enumerate(data_loader):\n                optimizer.zero_grad()\n\n                txts, bows = data\n                bows = bows.to(self.device)\n\n                bows_recon, theta_q = self.wae(bows)\n                \n                theta_prior = self.wae.sample(dist=self.dist, batch_size=len(bows), ori_data=bows).to(self.device)\n\n                logsoftmax = torch.log_softmax(bows_recon, dim=1)\n                rec_loss = -1.0 * torch.sum(bows*logsoftmax)\n                #rec_loss = F.binary_cross_entropy(torch.softmax(bows_recon,dim=1),bows,reduction='sum')\n                #rec_loss = F.binary_cross_entropy(bows_recon,bows,reduction='sum')\n                mmd = self.wae.mmd_loss(theta_q, theta_prior, device=self.device, t=0.1)\n                #mmd = self.wae.mmd_loss(hid_vecs, theta_prior, device=self.device, t=0.1)\n                s = torch.sum(bows)/len(bows)\n                lamb = (5.0*s*torch.log(torch.tensor(1.0 *bows.shape[-1]))/torch.log(torch.tensor(2.0)))\n                mmd = mmd * lamb\n\n                loss = rec_loss + mmd * beta\n\n                loss.backward()\n                optimizer.step()\n\n                trainloss_lst.append(loss.item()/len(bows))\n                epochloss_lst.append(loss.item()/len(bows))\n                if (iter+1) % 10 == 0:\n                    print(f'Epoch {(epoch+1):>3d}\\tIter {(iter+1):>4d}\\tLoss:{loss.item()/len(bows):<.7f}\\tRec Loss:{rec_loss.item()/len(bows):<.7f}\\tMMD:{mmd.item()/len(bows):<.7f}')\n            #scheduler.step()\n            if (epoch+1) % log_every == 0:\n                print(f'Epoch {(epoch+1):>3d}\\tLoss:{sum(epochloss_lst)/len(epochloss_lst):<.7f}')\n                print('\\n'.join([str(lst) for lst in self.show_topic_words()]))\n                print('='*30)\n                smth_pts = smooth_curve(trainloss_lst)\n                plt.plot(np.array(range(len(smth_pts)))*log_every, smth_pts)\n                plt.xlabel('epochs')\n                plt.title('Train Loss')\n                plt.savefig('wlda_trainloss.png')\n                if test_data!=None:\n                    c_v,c_w2v,c_uci,c_npmi,mimno_tc, td = self.evaluate(test_data,calc4each=False)\n                    c_v_lst.append(c_v), c_w2v_lst.append(c_w2v), c_uci_lst.append(c_uci),c_npmi_lst.append(c_npmi), mimno_tc_lst.append(mimno_tc), td_lst.append(td)\n                save_name = f'./ckpt/WTM_{self.taskname}_tp{self.n_topic}_{self.dist}_{time.strftime(\"%Y-%m-%d-%H-%M\", time.localtime())}.ckpt'\n                torch.save(self.wae.state_dict(),save_name)\n        scrs = {'c_v':c_v_lst,'c_w2v':c_w2v_lst,'c_uci':c_uci_lst,'c_npmi':c_npmi_lst,'mimno_tc':mimno_tc_lst,'td':td_lst}\n        '''\n        for scr_name,scr_lst in scrs.items():\n            plt.cla()\n            plt.plot(np.array(range(len(scr_lst)))*log_every,scr_lst)\n            plt.savefig(f'wlda_{scr_name}.png')\n        '''\n        plt.cla()\n        for scr_name,scr_lst in scrs.items():\n            if scr_name in ['c_v','c_w2v','td']:\n                plt.plot(np.array(range(len(scr_lst)))*log_every,scr_lst,label=scr_name)\n        plt.title('Topic Coherence')\n        plt.xlabel('epochs')\n        plt.legend()\n        plt.savefig(f'wlda_tc_scores.png')\n\n\n    def evaluate(self, test_data, calc4each=False):\n        topic_words = self.show_topic_words()\n        return evaluate_topic_quality(topic_words, test_data, taskname=self.taskname, calc4each=calc4each)\n\n\n    def inference(self, doc_bow):\n        # doc_bow: torch.tensor [vocab_size]; optional: np.array [vocab_size]\n        if isinstance(doc_bow,np.array):\n            doc_bow = torch.from_numpy(doc_bow)\n        doc_bow = doc_bow.reshape(1,self.bow_dim).to(self.device)\n        with torch.no_grad():\n            theta = F.softmax(self.wae.encode(doc_bow),dim=1)\n            return theta.detach().cpu().squeeze(0).numpy()\n\n\n    def inference(self, doc_tokenized, dictionary,normalize=True):\n        doc_bow = torch.zeros(1,self.bow_dim)\n        for token in doc_tokenized:\n            try:\n                idx = dictionary.token2id[token]\n                doc_bow[0][idx] = 1.0\n            except:\n                print(f'{token} not in the vocabulary.')\n        doc_bow = doc_bow.to(self.device)\n        with torch.no_grad():\n            theta = self.wae.encode(doc_bow)\n            if normalize:\n                theta = F.softmax(theta,dim=1)\n            return theta.detach().cpu().squeeze(0).numpy()\n\n    def get_embed(self,train_data, num=1000):\n        self.wae.eval()\n        data_loader = DataLoader(train_data, batch_size=512,shuffle=False, num_workers=4, collate_fn=train_data.collate_fn)\n        embed_lst = []\n        txt_lst = []\n        for data_batch in data_loader:\n            txts, bows = data_batch\n            embed = self.inference(bows,train_data.dictionary)\n            embed_lst.append(embed)\n            txt_lst.append(txts)\n            cnt += embed.shape[0]\n            if cnt>=num:\n                break\n        embed_lst = torch.concat(embed_lst,dim=0)[:num]\n        txt_lst = torch.concat(txt_lst,dim=0)[:num]\n        return txt_lst, embed_lst\n\n\n    def get_topic_word_dist(self,normalize=True):\n        self.wae.eval()\n        with torch.no_grad():\n            idxes = torch.eye(self.n_topic).to(self.device)\n            word_dist = self.wae.decode(idxes)  # word_dist: [n_topic, vocab.size]\n            if normalize:\n                word_dist = F.softmax(word_dist,dim=1)\n            return word_dist.detach().cpu().numpy()\n\n    def show_topic_words(self, topic_id=None, topK=15):\n        self.wae.eval()\n        topic_words = []\n        idxes = torch.eye(self.n_topic).to(self.device)\n        word_dist = self.wae.decode(idxes)\n        word_dist = F.softmax(word_dist, dim=1)\n        vals, indices = torch.topk(word_dist, topK, dim=1)\n        vals = vals.cpu().tolist()\n        indices = indices.cpu().tolist()\n        if topic_id == None:\n            for i in range(self.n_topic):\n                topic_words.append([self.id2token[idx] for idx in indices[i]])\n        else:\n            topic_words.append([self.id2token[idx] for idx in indices[topic_id]])\n        return topic_words\n\n\nif __name__ == '__main__':\n    model = WAE(encode_dims=[1024, 512, 256, 20],\n                decode_dims=[20, 128, 768, 1024])\n    model = model.cuda()\n    inpt = torch.randn(234, 1024).cuda()\n    out, mu, log_var = model(inpt)\n    print(out.shape)\n    print(mu.shape)\n", "meta": {"hexsha": "3ab79bd1f81127df4a178865250902d216261d3f", "size": 8211, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/WTM.py", "max_stars_repo_name": "lipiji/Neural_Topic_Models", "max_stars_repo_head_hexsha": "a7812f3458d808709bcadeeb5e3f7bb34c7715e1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-25T03:20:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-25T03:20:24.000Z", "max_issues_repo_path": "models/WTM.py", "max_issues_repo_name": "lipiji/Neural_Topic_Models", "max_issues_repo_head_hexsha": "a7812f3458d808709bcadeeb5e3f7bb34c7715e1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/WTM.py", "max_forks_repo_name": "lipiji/Neural_Topic_Models", "max_forks_repo_head_hexsha": "a7812f3458d808709bcadeeb5e3f7bb34c7715e1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.1076923077, "max_line_length": 183, "alphanum_fraction": 0.5987090488, "include": true, "reason": "import numpy", "num_tokens": 2149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3040416749665474, "lm_q1q2_score": 0.16975467453676527}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n################################################################################\n#\n#   CanTherm - \n#    \n#   Copyright (c) 2010 by Joshua W. Allen (jwallen@mit.edu)\n#\n#   Permission is hereby granted, free of charge, to any person obtaining a\n#   copy of this software and associated documentation files (the 'Software'),\n#   to deal in the Software without restriction, including without limitation\n#   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n#   and/or sell copies of the Software, and to permit persons to whom the\n#   Software is furnished to do so, subject to the following conditions:\n#\n#   The above copyright notice and this permission notice shall be included in\n#   all copies or substantial portions of the Software.\n#\n#   THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n#   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n#   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n#   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n#   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n#   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n#   DEALINGS IN THE SOFTWARE.\n#\n################################################################################\n\nimport os.path\nimport logging\nimport math\nimport numpy\nimport matplotlib\nmatplotlib.rc('mathtext', default='regular')\n            \nfrom rmgpy.quantity import constants\nfrom rmgpy.statmech import HinderedRotor, HarmonicOscillator\nfrom rmgpy.species import Species, TransitionState\nfrom rmgpy.kinetics import Arrhenius\nfrom rmgpy.reaction import Reaction\n\nfrom gaussian import GaussianLog\nfrom states import projectRotors, applyEnergyCorrections\n\n################################################################################\n\n# The model chemistry used\n# The energies for each species and transition state will be automatically \n# adjusted using standard reference energies for that method\nmodelChemistry = ''\n\n# A dictionary associating species identifiers with species objects\nspeciesDict = {}\n# A dictionary associating transition state identifiers with transition state objects\ntransitionStateDict = {}\n# A dictionary associating reaction identifiers with reaction objects\nreactionDict = {}\n# A dictionary associated species and transition state identifiers with geometry objects\ngeometryDict = {}\n\n# The file to save the output to\noutputFile = ''\n\n################################################################################\n\ndef setOutputFile(path):\n    global outputFile\n    outputFile = path\n    f = open(path, 'w')\n    f.close()\n    \ndef setModelChemistry(method):\n    \"\"\"\n    Set the model chemistry used in this quantum chemisty calculation to\n    `method`.\n    \"\"\"\n    global modelChemistry\n    modelChemistry = method\n\n################################################################################\n\ndef hinderedRotor(scanLog, pivots, top, symmetry):\n    pivots = [p-1 for p in pivots]\n    top = [t-1 for t in top]\n    return [scanLog, pivots, top, symmetry]\n\n################################################################################\n\ndef loadConfiguration(energyLog, geomLog, statesLog, extSymmetry, spinMultiplicity, freqScaleFactor, linear, rotors, atoms, bonds, E0=None, TS=False):\n    \n    logging.debug('    Reading optimized geometry...')\n    log = GaussianLog(geomLog)\n    geom = log.loadGeometry()\n    \n    logging.debug('    Reading energy...')\n    if E0 is None:\n        if energyLog is not None: log = GaussianLog(energyLog)\n        E0 = log.loadEnergy()\n    else:\n        E0 *= 4.35974394e-18 * constants.Na     # Hartree/particle to J/mol\n    E0 = applyEnergyCorrections(E0, modelChemistry, atoms, bonds)\n    logging.debug('         E0 (0 K) = %g kcal/mol' % (E0 / 4184))\n    \n    logging.debug('    Reading molecular degrees of freedom...')\n    log = GaussianLog(statesLog)\n    states = log.loadStates(symmetry=extSymmetry)\n    states.spinMultiplicity = spinMultiplicity\n    \n    F = log.loadForceConstantMatrix()\n    \n    if F is not None and len(geom.mass) > 1 and len(rotors) > 0:\n        \n        logging.debug('    Fitting %i hindered rotors...' % len(rotors))\n        for scanLog, pivots, top, symmetry in rotors:\n            log = GaussianLog(scanLog)\n            \n            Vlist, angle = log.loadScanEnergies()\n            \n            inertia = geom.getInternalReducedMomentOfInertia(pivots, top)\n            \n            barr, symm = log.fitCosinePotential()\n            cosineRotor = HinderedRotor(inertia=(inertia*constants.Na*1e23,\"amu*angstrom^2\"), symmetry=symm, barrier=(barr/4184.,\"kcal/mol\"))\n            fourier = log.fitFourierSeriesPotential()\n            fourierRotor = HinderedRotor(inertia=(inertia*constants.Na*1e23,\"amu*angstrom^2\"), symmetry=symmetry, fourier=(fourier,\"J/mol\"))\n                \n            Vlist_cosine = cosineRotor.getPotential(angle)\n            Vlist_fourier = fourierRotor.getPotential(angle)\n            \n            rms_cosine = numpy.sqrt(numpy.sum((Vlist_cosine - Vlist) * (Vlist_cosine - Vlist)) / (len(Vlist) - 1)) / 4184.\n            rms_fourier = numpy.sqrt(numpy.sum((Vlist_fourier - Vlist) * (Vlist_fourier - Vlist))/ (len(Vlist) - 1)) / 4184.\n            print rms_cosine, rms_fourier, symm, symmetry\n            \n            # Keep the rotor with the most accurate potential\n            rotor = cosineRotor if rms_cosine < rms_fourier else fourierRotor\n            # However, keep the cosine rotor if it is accurate enough, the\n            # fourier rotor is not significantly more accurate, and the cosine\n            # rotor has the correct symmetry \n            if rms_cosine < 0.05 and rms_cosine / rms_fourier > 0.25 and rms_cosine / rms_fourier < 4.0 and symmetry == symm:\n                rotor = cosineRotor\n            \n            states.modes.append(rotor)\n            \n            import pylab\n            phi = numpy.arange(0, 6.3, 0.02, numpy.float64)\n            fig = pylab.figure()\n            pylab.plot(angle, Vlist / 4184, 'ok')\n            linespec = '-r' if rotor is cosineRotor else '--r'\n            pylab.plot(phi, cosineRotor.getPotential(phi) / 4184, linespec)\n            linespec = '-b' if rotor is fourierRotor else '--b'\n            pylab.plot(phi, fourierRotor.getPotential(phi) / 4184, linespec)\n            pylab.legend(['scan', 'cosine', 'fourier'], loc=1)\n            pylab.xlim(0, 2*math.pi)\n            \n            axes = fig.get_axes()[0]\n            axes.set_xticks([float(j*math.pi/4) for j in range(0,9)])\n            axes.set_xticks([float(j*math.pi/8) for j in range(0,17)], minor=True)\n            axes.set_xticklabels(['$0$', '$\\pi/4$', '$\\pi/2$', '$3\\pi/4$', '$\\pi$', '$5\\pi/4$', '$3\\pi/2$', '$7\\pi/4$', '$2\\pi$'])\n\n            \n        pylab.show()\n        \n        logging.debug('    Determining frequencies from reduced force constant matrix...')\n        frequencies = list(projectRotors(geom, F, rotors, linear, TS))\n        \n    elif len(states.modes) > 2:\n        frequencies = states.modes[2].frequencies.values\n        rotors = []\n    else:\n        frequencies = []\n        rotors = []\n\n    for mode in states.modes:\n        if isinstance(mode, HarmonicOscillator):\n            mode.frequencies.values = numpy.array(frequencies, numpy.float) * freqScaleFactor\n\n    return E0, geom, states\n\ndef loadSpecies(label, geomLog, statesLog, extSymmetry, spinMultiplicity, freqScaleFactor, linear, rotors, atoms, bonds, directory=None, E0=None, energyLog=None):\n    global modelChemistry\n    logging.info('Loading species %s...' % label)\n    if directory:\n        geomLog = os.path.join(directory, geomLog)\n        statesLog = os.path.join(directory, statesLog)\n        if energyLog: energyLog = os.path.join(directory, energyLog)\n        for rotor in rotors:\n            rotor[0] = os.path.join(directory, rotor[0])\n    E0, geom, states = loadConfiguration(energyLog, geomLog, statesLog, extSymmetry, spinMultiplicity, freqScaleFactor, linear, rotors, atoms, bonds, E0, TS=False)\n    speciesDict[label] = Species(label=label, thermo=None, states=states, E0=(E0/1000.,\"kJ/mol\"))\n    geometryDict[label] = geom\n\ndef loadTransitionState(label, geomLog, statesLog, extSymmetry, spinMultiplicity, freqScaleFactor, linear, rotors, atoms, bonds, directory=None, E0=None, energyLog=None):\n    global modelChemistry\n    logging.info('Loading transition state %s...' % label)\n    if directory:\n        geomLog = os.path.join(directory, geomLog)\n        statesLog = os.path.join(directory, statesLog)\n        if energyLog: energyLog = os.path.join(directory, energyLog)\n        for rotor in rotors:\n            rotor[0] = os.path.join(directory, rotor[0])\n    E0, geom, states = loadConfiguration(energyLog, geomLog, statesLog, extSymmetry, spinMultiplicity, freqScaleFactor, linear, rotors, atoms, bonds, E0, TS=True)\n    log = GaussianLog(statesLog)\n    frequency = log.loadNegativeFrequency() * freqScaleFactor\n    transitionStateDict[label] = TransitionState(label=label, states=states, frequency=(frequency,\"cm^-1\"), E0=(E0/1000.,\"kJ/mol\"))\n    geometryDict[label] = geom\n    \n################################################################################\n\ndef loadReaction(label, reactants, products, transitionState, degeneracy=1):\n    global speciesDict, transitionStateDict, reactionDict\n    logging.info('Loading reaction %s...' % label)\n    rxn = Reaction(\n        reactants=[speciesDict[s] for s in reactants],\n        products=[speciesDict[s] for s in products],\n        transitionState=transitionStateDict[transitionState],\n    )\n    rxn.degeneracy = degeneracy\n    reactionDict[label] = rxn\n\n################################################################################\n\ndef generateStates(label):\n    global outputFile, speciesDict, transitionStateDict\n    from states import saveStates\n    if label in speciesDict:\n        saveStates(speciesDict[label], geometryDict[label], label, outputFile)\n    elif label in transitionStateDict:\n        saveStates(transitionStateDict[label], geometryDict[label], label, outputFile)\n    \ndef generateThermo(label, model, plot=False):\n    global outputFile, speciesDict\n    from thermo import generateThermoModel, saveThermo\n    generateThermoModel(speciesDict[label], model, plot)\n    saveThermo(speciesDict[label], label, outputFile)\n    \ndef generateKinetics(label, tunneling='', plot=False):\n    global outputFile, reactionDict\n    from kinetics import generateKineticsModel, saveKinetics\n    generateKineticsModel(reactionDict[label], tunneling, plot)\n    saveKinetics(reactionDict[label], tunneling, label, outputFile)\n", "meta": {"hexsha": "e1c2bffb63c802d5d9e8cd50a98dd35002c55472", "size": 10708, "ext": "py", "lang": "Python", "max_stars_repo_path": "rmgpy/cantherm/input.py", "max_stars_repo_name": "sean-v8/RMG-Py", "max_stars_repo_head_hexsha": "7cc7c3bfb330786526c56113d98c785bcaaa161a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rmgpy/cantherm/input.py", "max_issues_repo_name": "sean-v8/RMG-Py", "max_issues_repo_head_hexsha": "7cc7c3bfb330786526c56113d98c785bcaaa161a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rmgpy/cantherm/input.py", "max_forks_repo_name": "sean-v8/RMG-Py", "max_forks_repo_head_hexsha": "7cc7c3bfb330786526c56113d98c785bcaaa161a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.4315352697, "max_line_length": 170, "alphanum_fraction": 0.637373926, "include": true, "reason": "import numpy", "num_tokens": 2465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.16971141391088007}}
{"text": "# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"THOR\"\"\"\nimport numpy as np\nfrom mindspore.ops import functional as F, composite as C, operations as P\nfrom mindspore.common.initializer import initializer\nfrom mindspore.common.parameter import Parameter, ParameterTuple\nfrom mindspore.common.tensor import Tensor\nimport mindspore.nn as nn\nimport mindspore.common.dtype as mstype\nfrom mindspore._checkparam import Validator\nfrom mindspore.nn.optim.optimizer import Optimizer\nfrom mindspore.parallel._utils import _get_device_num, _get_gradients_mean\nfrom mindspore import context\nfrom mindspore.context import ParallelMode\nfrom mindspore.nn.layer import Dense_Thor, Conv2d_Thor, Embedding_Thor\nfrom mindspore.nn.wrap import DistributedGradReducer\nfrom mindspore.train.train_thor.convert_utils import ConvertNetUntils\nfrom mindspore.parallel._auto_parallel_context import auto_parallel_context\n\n# Enumerates types of Layer\nOther = -1\nConv = 1\nFC = 2\nEmbedding = 3\nLayerNorm = 4\nBatchNorm = 5\n\n\n_momentum_opt = C.MultitypeFuncGraph(\"momentum_opt\")\n\nop_add = P.AddN()\napply_decay = C.MultitypeFuncGraph(\"apply_decay\")\n\n\n@apply_decay.register(\"Number\", \"Bool\", \"Tensor\", \"Tensor\")\ndef _tensor_apply_decay(weight_decay, if_apply, weight, gradient):\n    \"\"\"Get grad with weight_decay.\"\"\"\n    if if_apply:\n        return op_add((weight * weight_decay, gradient))\n    return gradient\n\n\n@_momentum_opt.register(\"Function\", \"Tensor\", \"Tensor\", \"Tensor\", \"Tensor\", \"Tensor\")\ndef _tensor_run_opt_ext(opt, momentum, learning_rate, gradient, weight, moment):\n    \"\"\"Apply momentum optimizer to the weight parameter using Tensor.\"\"\"\n    success = True\n    success = F.depend(success, opt(weight, moment, learning_rate, gradient, momentum))\n    return success\n\nC0 = 16\n\n\ndef caculate_device_shape(matrix_dim, channel, is_A):\n    ll = (0)\n    if is_A:\n        if channel // C0 == 0:\n            matrix_dim = (matrix_dim / channel) * C0\n        ll = (int(matrix_dim // C0), int(matrix_dim // C0), C0, C0), int(matrix_dim)\n    else:\n        ll = (int(matrix_dim // C0), int(matrix_dim // C0), C0, C0), int(matrix_dim)\n    return ll\n\n\ndef caculate_matmul_shape(matrix_A_dim, matrix_G_dim, split_dim):\n    \"\"\"get matmul shape\"\"\"\n    split_dimA = split_dim\n    split_dimG = split_dim\n    if matrix_A_dim % split_dim == 0:\n        batch_w = matrix_A_dim // split_dim\n    else:\n        if matrix_A_dim < split_dim:\n            batch_w = 1\n            split_dimA = matrix_A_dim\n        else:\n            batch_w = matrix_A_dim // split_dim + 1\n\n    if matrix_G_dim % split_dim == 0:\n        batch_h = matrix_G_dim // split_dim\n    else:\n        if matrix_G_dim < split_dim:\n            batch_h = 1\n            split_dimG = matrix_G_dim\n        else:\n            batch_h = matrix_G_dim // split_dim + 1\n    matrix_A_shape = (batch_h, batch_w, split_dimA, split_dimA)\n    matrix_G_shape = (batch_h, split_dimG, split_dimG)\n    return matrix_A_shape, matrix_G_shape\n\n\ndef find_net_layertype_recur(net, layertype_map):\n    \"\"\"get net layer type recursively.\"\"\"\n    cells = net.name_cells()\n    for name in cells:\n        subcell = cells[name]\n        print(\"thor subcell name: \", name)\n        if subcell == net:\n            continue\n        elif isinstance(subcell, Conv2d_Thor):\n            layertype_map.append(Conv)\n        elif isinstance(subcell, Dense_Thor):\n            layertype_map.append(FC)\n        elif isinstance(subcell, Embedding_Thor):\n            layertype_map.append(Embedding)\n        elif isinstance(subcell, nn.LayerNorm):\n            layertype_map.append(LayerNorm)\n        elif isinstance(subcell, nn.BatchNorm2d):\n            layertype_map.append(BatchNorm)\n        elif isinstance(subcell, (nn.Conv2d, nn.Dense, nn.Embedding, nn.Conv2dTranspose, nn.Conv1d, nn.Conv1dTranspose,\n                                  nn.BatchNorm1d, nn.GroupNorm, nn.GlobalBatchNorm)):\n            layertype_map.append(Other)\n        else:\n            find_net_layertype_recur(subcell, layertype_map)\n\ndef get_net_layertype_mask(net):\n    layertype_map = []\n    find_net_layertype_recur(net, layertype_map)\n    return layertype_map\n\ndef get_layer_counter(layer_type, layer_counter, params, idx):\n    \"\"\"get layer counter\"\"\"\n    if layer_type in [Conv, FC, LayerNorm, BatchNorm]:\n        if layer_type in [LayerNorm, BatchNorm]:\n            if \"beta\" in params[idx].name.lower():\n                layer_counter = layer_counter + 1\n        else:\n            if \"bias\" in params[idx].name.lower():\n                layer_counter = layer_counter + 1\n            else:\n                if idx < len(params) - 1 and \"bias\" not in params[idx + 1].name.lower():\n                    layer_counter = layer_counter + 1\n    else:\n        layer_counter = layer_counter + 1\n    return layer_counter\n\n\ndef THOR(net, learning_rate, damping, momentum, weight_decay=0.0, loss_scale=1.0, batch_size=32,\n         use_nesterov=False, decay_filter=lambda x: x.name not in [], split_indices=None):\n    context.set_context(max_call_depth=10000)\n    ConvertNetUntils().convert_to_thor_net(net)\n    if context.get_context(\"device_target\") == \"Ascend\":\n        return THOR_Ascend(net, learning_rate, damping, momentum, weight_decay, loss_scale, batch_size, decay_filter,\n                           split_indices=split_indices)\n    return THOR_GPU(net, learning_rate, damping, momentum, weight_decay, loss_scale, batch_size,\n                    use_nesterov, decay_filter, split_indices=split_indices)\n\n\nclass THOR_GPU(Optimizer):\n    \"\"\"\n    THOR_GPU\n    \"\"\"\n    def __init__(self, net, learning_rate, damping, momentum, weight_decay=0.0, loss_scale=1.0, batch_size=32,\n                 use_nesterov=False, decay_filter=lambda x: x.name not in [], split_indices=None):\n        params = filter(lambda x: x.requires_grad, net.get_parameters())\n        super(THOR_GPU, self).__init__(learning_rate, params, weight_decay, loss_scale)\n        Validator.check_value_type(\"momentum\", momentum, [float], self.cls_name)\n        if isinstance(momentum, float) and momentum < 0.0:\n            raise ValueError(\"momentum should be at least 0.0, but got momentum {}\".format(momentum))\n        self.momentum = Parameter(Tensor(momentum, mstype.float32), name=\"momentum\")\n        self.params = self.parameters\n        self.use_nesterov = Validator.check_bool(use_nesterov)\n        self.moments = self.params.clone(prefix=\"moments\", init='zeros')\n        self.hyper_map = C.HyperMap()\n        self.opt = P.ApplyMomentum(use_nesterov=self.use_nesterov)\n        self.net = net\n        self.matrix_A_cov = ParameterTuple(filter(lambda x: 'matrix_A' in x.name, net.get_parameters()))\n        self.matrix_G_cov = ParameterTuple(filter(lambda x: 'matrix_G' in x.name, net.get_parameters()))\n        self.A_normalizer = ParameterTuple(filter(lambda x: 'A_normalizer' in x.name, net.get_parameters()))\n        self.G_normalizer = ParameterTuple(filter(lambda x: 'G_normalizer' in x.name, net.get_parameters()))\n        self.transpose = P.Transpose()\n        self.shape = P.Shape()\n        self.reshape = P.Reshape()\n        self.matmul = P.MatMul()\n        self.assign = P.Assign()\n        self.mul = P.Mul()\n        self.damping = damping\n        self.gather = P.GatherV2()\n        self.one = Tensor(1, mstype.int32)\n        self.batch_size = Tensor(batch_size, mstype.float32)\n        self.loss_scale = Tensor(1 / (loss_scale * loss_scale), mstype.float32)\n        self.batch_size_scale = Tensor(batch_size * batch_size, mstype.float32)\n        self.feature_map = Tensor(1.0, mstype.float32)\n        self.axis = 0\n        self.cov_step = Parameter(initializer(0, [1], mstype.int32), name=\"cov_step\", requires_grad=False)\n        self.cast = P.Cast()\n        self.sqrt = P.Sqrt()\n        self.eye = P.Eye()\n        split_dim = 128\n        self.embedding_cholesky = P.CholeskyTrsm()\n        self.cholesky = P.CholeskyTrsm(split_dim=split_dim)\n        self.vector_matmul = P.BatchMatMul(transpose_a=True)\n        self.reduce_sum = P.ReduceSum(keep_dims=False)\n        self.inv = P.Reciprocal()\n        self.square = P.Square()\n        self.expand = P.ExpandDims()\n        self.thor = True\n\n        self.matrix_A = ()\n        self.matrix_G = ()\n        self.matrix_A_shape = ()\n        self.thor_layer_count = 0\n        self.conv_layer_count = 0\n        self.weight_fim_idx_map = ()\n        self.weight_conv_idx_map = ()\n        self.weight_layerType_idx_map = ()\n        layer_type_map = get_net_layertype_mask(net)\n\n        layer_counter = 0\n        for idx in range(len(self.params)):\n            layer_type = layer_type_map[layer_counter]\n            weight = self.params[idx]\n            weight_shape = self.shape(weight)\n            if layer_type in [Conv, FC] and \"bias\" not in self.params[idx].name.lower():\n                in_channels = weight_shape[1]\n                out_channels = weight_shape[0]\n                matrix_A_dim = in_channels\n                if layer_type == Conv:\n                    matrix_A_dim = in_channels * weight_shape[2] * weight_shape[3]\n                matrix_G_dim = out_channels\n                matrix_A_shape, matrix_G_shape = caculate_matmul_shape(matrix_A_dim, matrix_G_dim, split_dim)\n                matrix_A_inv = Parameter(np.zeros(matrix_A_shape).astype(np.float32),\n                                         name='matrix_A_inv_' + str(self.thor_layer_count), requires_grad=False)\n                matrix_G_inv = Parameter(np.zeros(matrix_G_shape).astype(np.float32),\n                                         name=\"matrix_G_inv_\" + str(self.thor_layer_count), requires_grad=False)\n                self.matrix_A = self.matrix_A + (matrix_A_inv,)\n                self.matrix_G = self.matrix_G + (matrix_G_inv,)\n                self.matrix_A_shape = self.matrix_A_shape + (matrix_A_shape,)\n            elif layer_type == Embedding:\n                vocab_size = weight_shape[0]\n                embedding_size = weight_shape[1]\n                matrix_A_inv = Parameter(Tensor(np.zeros([vocab_size]).astype(np.float32)),\n                                         name='matrix_A_inv_' + str(self.thor_layer_count), requires_grad=False)\n                matrix_G_inv = Parameter(Tensor(np.zeros([embedding_size, embedding_size]).astype(np.float32)),\n                                         name=\"matrix_G_inv_\" + str(self.thor_layer_count), requires_grad=False)\n                self.matrix_A = self.matrix_A + (matrix_A_inv,)\n                self.matrix_G = self.matrix_G + (matrix_G_inv,)\n                self.matrix_A_shape = self.matrix_A_shape + ((vocab_size,),)\n\n            if layer_type in [Conv, FC, Embedding] and \"bias\" not in self.params[idx].name.lower():\n                self.weight_fim_idx_map = self.weight_fim_idx_map + (self.thor_layer_count,)\n                self.weight_layerType_idx_map = self.weight_layerType_idx_map + (layer_type,)\n                self.thor_layer_count = self.thor_layer_count + 1\n                if layer_type == Conv:\n                    self.weight_conv_idx_map = self.weight_conv_idx_map + (self.conv_layer_count,)\n                    self.conv_layer_count = self.conv_layer_count + 1\n                else:\n                    self.weight_conv_idx_map = self.weight_conv_idx_map + (-1,)\n            else:\n                self.weight_fim_idx_map = self.weight_fim_idx_map + (-1,)\n                self.weight_conv_idx_map = self.weight_conv_idx_map + (-1,)\n                if layer_type == LayerNorm:\n                    self.weight_layerType_idx_map = self.weight_layerType_idx_map + (LayerNorm,)\n                else:\n                    self.weight_layerType_idx_map = self.weight_layerType_idx_map + (Other,)\n                # bert.cls1.output_bias: not a network layer, only a trainable param\n            if \"output_bias\" not in self.params[idx].name.lower():\n                layer_counter = get_layer_counter(layer_type, layer_counter, self.params, idx)\n\n        self.matrix_A = ParameterTuple(self.matrix_A)\n        self.matrix_G = ParameterTuple(self.matrix_G)\n        self.weight_decay = weight_decay\n        self.decay_flags = tuple(decay_filter(x) for x in self.parameters)\n        self.update_gradient = P.UpdateThorGradient(split_dim=split_dim)\n\n        self.parallel_mode = context.get_auto_parallel_context(\"parallel_mode\")\n        self.is_distributed = (self.parallel_mode != ParallelMode.STAND_ALONE)\n        if self.is_distributed:\n            mean = _get_gradients_mean()\n            degree = _get_device_num()\n            if self.conv_layer_count > 0:\n                if not split_indices:\n                    self.split_indices = split_indices\n                else:\n                    self.split_indices = [len(self.matrix_A) - 1]\n                auto_parallel_context().set_all_reduce_fusion_split_indices(self.split_indices, \"hccl_world_groupsum2\")\n                auto_parallel_context().set_all_reduce_fusion_split_indices(self.split_indices, \"hccl_world_groupsum4\")\n                auto_parallel_context().set_all_reduce_fusion_split_indices(self.split_indices, \"hccl_world_groupsum6\")\n                auto_parallel_context().set_all_reduce_fusion_split_indices(self.split_indices, \"hccl_world_groupsum8\")\n                self.grad_reducer_Amax = DistributedGradReducer(self.matrix_A, mean, degree, fusion_type=2)\n                self.grad_reducer_Gmax = DistributedGradReducer(self.matrix_A, mean, degree, fusion_type=4)\n                self.grad_reducer_A = DistributedGradReducer(self.matrix_A, mean, degree, fusion_type=6)\n                self.grad_reducer_G = DistributedGradReducer(self.matrix_A, mean, degree, fusion_type=8)\n            else:\n                if not split_indices:\n                    self.split_indices = split_indices\n                else:\n                    self.split_indices = [len(self.params) - 1]\n                auto_parallel_context().set_all_reduce_fusion_split_indices(self.split_indices, \"hccl_world_groupsum3\")\n                self.grad_reducer_g = DistributedGradReducer(self.params, mean, degree, fusion_type=3)\n\n    def _get_Ainv_Ginv_list(self, gradients, damping_step, matrix_a_allreduce, matrix_g_allreduce):\n        \"\"\"get matrixA inverse list and matrix G inverse list\"\"\"\n        for i in range(len(self.params)):\n            thor_layer_count = self.weight_fim_idx_map[i]\n            conv_layer_count = self.weight_conv_idx_map[i]\n            layer_type = self.weight_layerType_idx_map[i]\n            if layer_type in [Conv, FC, Embedding]:\n                g = gradients[i]\n                matrix_A = self.matrix_A_cov[thor_layer_count]\n                matrix_G = self.matrix_G_cov[thor_layer_count]\n                matrix_A = F.depend(matrix_A, g)\n                matrix_G = F.depend(matrix_G, g)\n                dampingA = damping_step\n                dampingG = damping_step\n                feature_map = self.feature_map\n                if layer_type == Conv:\n                    A_normalizer = self.A_normalizer[conv_layer_count]\n                    G_normalizer = self.G_normalizer[conv_layer_count]\n                    A_normalizer = F.depend(A_normalizer, g)\n                    G_normalizer = F.depend(G_normalizer, g)\n                    dampingA = self.mul(damping_step, 1.0 / A_normalizer)\n                    dampingG = self.mul(damping_step, 1.0 / G_normalizer)\n                    feature_map = self.sqrt(1.0 / A_normalizer)\n                A_shape = self.shape(matrix_A)\n                A_eye = self.eye(A_shape[0], A_shape[0], mstype.float32)\n                dampingA = self.sqrt(dampingA)\n                dampingG = self.sqrt(dampingG)\n                G_shape = self.shape(matrix_G)\n                G_eye = self.eye(G_shape[0], G_shape[1], mstype.float32)\n                matrix_G = self.mul(matrix_G, self.loss_scale)\n                matrix_G = self.mul(matrix_G, self.batch_size_scale)\n                matrix_G = matrix_G + dampingG * G_eye\n                if layer_type == Embedding:\n                    A_eye = P.OnesLike()(matrix_A)\n                    matrix_A = self.mul(matrix_A, 1.0 / self.batch_size)\n                    matrix_A = matrix_A + dampingA * A_eye\n                    matrix_A = self.inv(matrix_A)\n                    matrix_G = self.embedding_cholesky(matrix_G)\n                    matrix_G = self.matmul(matrix_G, matrix_G)\n                else:\n                    matrix_A = matrix_A + dampingA * A_eye\n                    matrix_A = self.cholesky(matrix_A)\n                    matrix_A = self.vector_matmul(matrix_A, matrix_A)\n                    matrix_A = P.BroadcastTo(self.matrix_A_shape[thor_layer_count])(matrix_A)\n                    matrix_G = self.cholesky(matrix_G)\n                    matrix_G = self.vector_matmul(matrix_G, matrix_G)\n                matrix_A = self.mul(matrix_A, feature_map)\n                matrix_G = self.mul(matrix_G, feature_map)\n                matrix_a_allreduce = matrix_a_allreduce + (matrix_A,)\n                matrix_g_allreduce = matrix_g_allreduce + (matrix_G,)\n        return matrix_a_allreduce, matrix_g_allreduce\n\n    def construct(self, gradients):\n        params = self.params\n        moments = self.moments\n        gradients = self.scale_grad(gradients)\n        damping_step = self.gather(self.damping, self.cov_step, self.axis)\n        damping_step = self.cast(damping_step, mstype.float32)\n        new_grads = ()\n        if self.thor:\n            matrix_Ainv_list = ()\n            matrix_Ginv_list = ()\n            matrix_A_allreduce, matrix_G_allreduce = self._get_Ainv_Ginv_list(gradients, damping_step,\n                                                                              matrix_Ainv_list, matrix_Ginv_list)\n            if self.is_distributed and self.conv_layer_count > 0:\n                matrix_A_allreduce = self.grad_reducer_A(matrix_A_allreduce)\n                matrix_G_allreduce = self.grad_reducer_G(matrix_G_allreduce)\n\n            for i in range(len(self.params)):\n                g = gradients[i]\n                thor_layer_count = self.weight_fim_idx_map[i]\n                conv_layer_count = self.weight_conv_idx_map[i]\n                layer_type = self.weight_layerType_idx_map[i]\n                if layer_type in [Conv, FC]:\n                    g_shape = self.shape(g)\n                    g = self.reshape(g, (g_shape[0], -1))\n                    matrix_A = matrix_A_allreduce[thor_layer_count]\n                    matrix_G = matrix_G_allreduce[thor_layer_count]\n                    g = self.update_gradient(matrix_G, g, matrix_A)\n                    fake_A = self.assign(self.matrix_A[thor_layer_count], matrix_A)\n                    fake_G = self.assign(self.matrix_G[thor_layer_count], matrix_G)\n                    g = F.depend(g, fake_A)\n                    g = F.depend(g, fake_G)\n                    if conv_layer_count != -1:\n                        g = self.reshape(g, g_shape)\n                elif layer_type == Embedding:\n                    matrix_A = matrix_A_allreduce[thor_layer_count]\n                    matrix_G = matrix_G_allreduce[thor_layer_count]\n                    fake_A = self.assign(self.matrix_A[thor_layer_count], matrix_A)\n                    fake_G = self.assign(self.matrix_G[thor_layer_count], matrix_G)\n                    g = F.depend(g, fake_A)\n                    g = F.depend(g, fake_G)\n                    temp_a = self.expand(matrix_A, 1)\n                    g = self.mul(temp_a, g)\n                    g = self.matmul(g, matrix_G)\n                elif layer_type == LayerNorm:\n                    damping = self.sqrt(damping_step)\n                    normalizer = self.batch_size\n                    normalizer = self.cast(normalizer, mstype.float32)\n                    fim_cov = self.square(g)\n                    fim_cov = self.mul(fim_cov, 1.0 / normalizer)\n                    fim_cov = fim_cov + damping\n                    fim_inv = self.inv(fim_cov)\n                    g = self.mul(fim_inv, g)\n                new_grads = new_grads + (g,)\n        else:\n            for j in range(len(self.params)):\n                g = gradients[j]\n                thor_layer_count = self.weight_fim_idx_map[j]\n                conv_layer_count = self.weight_conv_idx_map[j]\n                layer_type = self.weight_layerType_idx_map[j]\n                if layer_type in [Conv, FC]:\n                    g_shape = self.shape(g)\n                    g = self.reshape(g, (g_shape[0], -1))\n                    matrix_A = self.matrix_A[thor_layer_count]\n                    matrix_G = self.matrix_G[thor_layer_count]\n                    g = self.update_gradient(matrix_G, g, matrix_A)\n                    if conv_layer_count != -1:\n                        g = self.reshape(g, g_shape)\n                elif layer_type == Embedding:\n                    matrix_A = self.matrix_A[thor_layer_count]\n                    matrix_G = self.matrix_G[thor_layer_count]\n                    g = gradients[j]\n                    temp_a = self.expand(matrix_A, 1)\n                    g = self.mul(temp_a, g)\n                    g = self.matmul(g, matrix_G)\n                elif layer_type == LayerNorm:\n                    damping = self.sqrt(damping_step)\n                    normalizer = self.batch_size\n                    normalizer = self.cast(normalizer, mstype.float32)\n                    fim_cov = self.square(g)\n                    fim_cov = self.mul(fim_cov, 1.0 / normalizer)\n                    fim_cov = fim_cov + damping\n                    fim_inv = self.inv(fim_cov)\n                    g = self.mul(fim_inv, g)\n                new_grads = new_grads + (g,)\n        gradients = new_grads\n\n        if self.is_distributed and self.conv_layer_count == 0:\n            gradients = self.grad_reducer_g(gradients)\n        self.cov_step = self.cov_step + self.one\n        if self.weight_decay > 0:\n            gradients = self.hyper_map(F.partial(apply_decay, self.weight_decay), self.decay_flags, params, gradients)\n        lr = self.get_lr()\n        success = self.hyper_map(F.partial(_momentum_opt, self.opt, self.momentum, lr), gradients, params, moments)\n        return success\n\n\nclass THOR_Ascend(Optimizer):\n    \"\"\"THOR\"\"\"\n\n    def __init__(self, net, learning_rate, damping, momentum, weight_decay=0.0, loss_scale=1.0, batch_size=32,\n                 decay_filter=lambda x: x.name not in [], split_indices=None):\n        params = filter(lambda x: x.requires_grad, net.get_parameters())\n        super(THOR_Ascend, self).__init__(learning_rate, params, weight_decay, loss_scale)\n        if isinstance(momentum, float) and momentum < 0.0:\n            raise ValueError(\"momentum should be at least 0.0, but got momentum {}\".format(momentum))\n        self.momentum = Parameter(Tensor(momentum, mstype.float32), name=\"momentum\")\n        self.params = self.parameters\n        self.moments = self.params.clone(prefix=\"moments\", init='zeros')\n        self.hyper_map = C.HyperMap()\n        self.opt = P.ApplyMomentum()\n        self.net = net\n        self.matrix_A_cov = ParameterTuple(filter(lambda x: 'matrix_A' in x.name, net.get_parameters()))\n        self.matrix_G_cov = ParameterTuple(filter(lambda x: 'matrix_G' in x.name, net.get_parameters()))\n        self.A_normalizer = ParameterTuple(filter(lambda x: 'A_normalizer' in x.name, net.get_parameters()))\n        self.G_normalizer = ParameterTuple(filter(lambda x: 'G_normalizer' in x.name, net.get_parameters()))\n        self.cube_matmul_left = P.CusMatMulCubeFraczLeftCast()\n        self.cube_matmul_left_fc = P.CusMatMulCubeDenseLeft()\n        self.cube_matmul_right_fc = P.CusMatMulCubeDenseRight()\n        self.cube_matmul_right_mul = P.CusMatMulCubeFraczRightMul()\n        self.transpose = P.Transpose()\n        self.shape = P.Shape()\n        self.reshape = P.Reshape()\n        self.mul = P.Mul()\n\n        self.C0 = 16\n        self.matrix_A_dim = ()\n        self.padA_flag = ()\n        self.device_shape_pad_flag = ()\n        self.diag_block_dim = 128\n        self.matrix_A = ()\n        self.matrix_G = ()\n        print(\"matrix_A_cov len is\", len(self.matrix_A_cov))\n        self.thor_layer_count = 0\n        self.conv_layer_count = 0\n        self.weight_fim_idx_map = ()\n        self.weight_conv_idx_map = ()\n        self.weight_layerType_idx_map = ()\n        layer_type_map = get_net_layertype_mask(net)\n        layer_counter = 0\n        for idx in range(len(self.params)):\n            layer_type = layer_type_map[layer_counter]\n            weight = self.params[idx]\n            weight_shape = self.shape(weight)\n            if layer_type == Conv and \"bias\" not in self.params[idx].name.lower():\n                in_channels = weight_shape[1]\n                out_channels = weight_shape[0]\n                matrix_A_dim = in_channels * weight_shape[2] * weight_shape[3]\n                matrix_G_dim = out_channels\n                matrix_A_device_shape, matrix_A_device_dim = caculate_device_shape(matrix_A_dim, in_channels, True)\n                matrix_G_device_shape, matrix_G_device_dim = caculate_device_shape(matrix_G_dim, in_channels, False)\n                matrix_A_inv = Parameter(\n                    Tensor(np.reshape(np.identity(matrix_A_device_dim).astype(np.float16), matrix_A_device_shape)),\n                    name='matrix_A_inv_' + str(self.thor_layer_count), requires_grad=False)\n                matrix_G_inv = Parameter(\n                    Tensor(np.reshape(np.identity(matrix_G_device_dim).astype(np.float16), matrix_G_device_shape)),\n                    name=\"matrix_G_inv_\" + str(self.thor_layer_count), requires_grad=False)\n                self.matrix_A = self.matrix_A + (matrix_A_inv,)\n                self.matrix_G = self.matrix_G + (matrix_G_inv,)\n                self.matrix_A_dim = self.matrix_A_dim + (matrix_A_dim,)\n                padA_flag = False\n                if (matrix_A_dim // self.diag_block_dim) * self.diag_block_dim != matrix_A_dim \\\n                    and matrix_A_dim > self.diag_block_dim:\n                    padA_flag = True\n                self.padA_flag = self.padA_flag + (padA_flag,)\n                device_shape_pad_flag = False\n                if matrix_A_dim != matrix_A_device_dim:\n                    device_shape_pad_flag = True\n                self.device_shape_pad_flag = self.device_shape_pad_flag + (device_shape_pad_flag,)\n            elif layer_type == FC and \"bias\" not in self.params[idx].name.lower():\n                out_channels = weight_shape[0]\n                if out_channels == 1001:\n                    fc_matrix_A = Parameter(Tensor(np.zeros([128, 128, 16, 16]).astype(np.float16)),\n                                            name='matrix_A_inv_' + str(self.thor_layer_count),\n                                            requires_grad=False)\n                    fc_matrix_G = Parameter(Tensor(np.zeros([63, 63, 16, 16]).astype(np.float16)),\n                                            name=\"matrix_G_inv_\" + str(self.thor_layer_count),\n                                            requires_grad=False)\n                    self.matrix_A = self.matrix_A + (fc_matrix_A,)\n                    self.matrix_G = self.matrix_G + (fc_matrix_G,)\n\n            if layer_type in [Conv, FC, Embedding] and \"bias\" not in self.params[idx].name.lower():\n                self.weight_fim_idx_map = self.weight_fim_idx_map + (self.thor_layer_count,)\n                self.weight_layerType_idx_map = self.weight_layerType_idx_map + (layer_type,)\n                self.thor_layer_count = self.thor_layer_count + 1\n                if layer_type == Conv:\n                    self.weight_conv_idx_map = self.weight_conv_idx_map + (self.conv_layer_count,)\n                    self.conv_layer_count = self.conv_layer_count + 1\n                else:\n                    self.weight_conv_idx_map = self.weight_conv_idx_map + (-1,)\n            else:\n                self.weight_fim_idx_map = self.weight_fim_idx_map + (-1,)\n                self.weight_conv_idx_map = self.weight_conv_idx_map + (-1,)\n                if layer_type == LayerNorm:\n                    self.weight_layerType_idx_map = self.weight_layerType_idx_map + (LayerNorm,)\n                else:\n                    self.weight_layerType_idx_map = self.weight_layerType_idx_map + (Other,)\n            # bert.cls1.output_bias: not a network layer, only a trainable param\n            if \"output_bias\" not in self.params[idx].name.lower():\n                layer_counter = get_layer_counter(layer_type, layer_counter, self.params, idx)\n\n        self.matrix_A = ParameterTuple(self.matrix_A)\n        self.matrix_G = ParameterTuple(self.matrix_G)\n        self.matrix_max_inv = ()\n        for i in range(len(self.matrix_A)):\n            self.matrix_max_inv = self.matrix_max_inv + (\n                Parameter(initializer(1, [1], mstype.float32), name=\"matrix_max\" + str(i), requires_grad=False),)\n        self.log = P.Log()\n        self.exp = P.Exp()\n        self.sqrt = P.Sqrt()\n        self.matrix_max_inv = ParameterTuple(self.matrix_max_inv)\n        self.assign = P.Assign()\n        self.cast = P.Cast()\n        self.thor = True\n        self.weight_decay = weight_decay * loss_scale\n        self.decay_flags = tuple(decay_filter(x) for x in self.parameters)\n        self.damping = damping\n        self.gather = P.GatherV2()\n        self.one = Tensor(1, mstype.int32)\n        self.batch_size = Tensor(batch_size, mstype.float32)\n        self.loss_scale = Tensor(1 / (loss_scale * loss_scale), mstype.float32)\n        self.batch_size_scale = Tensor(batch_size * batch_size, mstype.float32)\n        self.axis = 0\n        self.cov_step = Parameter(initializer(0, [1], mstype.int32), name=\"cov_step\", requires_grad=False)\n        self.cast = P.Cast()\n        self.eye = P.Eye()\n        self.cholesky = P.CusCholeskyTrsm()\n        self.vector_matmul = P.CusBatchMatMul()\n        self.fused_abs_max2 = P.CusFusedAbsMax1()\n        self.matrix_combine = P.CusMatrixCombine()\n        self.slice = P.Slice()\n        self.expand = P.ExpandDims()\n        self.reduce_sum = P.ReduceSum(keep_dims=False)\n        self.square = P.Square()\n        self.inv = P.Inv()\n        self.matmul = P.MatMul()\n\n        self.parallel_mode = context.get_auto_parallel_context(\"parallel_mode\")\n        self.is_distributed = (self.parallel_mode != ParallelMode.STAND_ALONE)\n        if self.is_distributed:\n            mean = _get_gradients_mean()\n            degree = _get_device_num()\n            if self.conv_layer_count > 0:\n                if not split_indices:\n                    self.split_indices = split_indices\n                else:\n                    self.split_indices = [len(self.matrix_A) - 1]\n                auto_parallel_context().set_all_reduce_fusion_split_indices(self.split_indices, \"hccl_world_groupsum2\")\n                auto_parallel_context().set_all_reduce_fusion_split_indices(self.split_indices, \"hccl_world_groupsum4\")\n                auto_parallel_context().set_all_reduce_fusion_split_indices(self.split_indices, \"hccl_world_groupsum6\")\n                auto_parallel_context().set_all_reduce_fusion_split_indices(self.split_indices, \"hccl_world_groupsum8\")\n                self.grad_reducer_Amax = DistributedGradReducer(self.matrix_A, mean, degree, fusion_type=2)\n                self.grad_reducer_Gmax = DistributedGradReducer(self.matrix_A, mean, degree, fusion_type=4)\n                self.grad_reducer_A = DistributedGradReducer(self.matrix_A, mean, degree, fusion_type=6)\n                self.grad_reducer_G = DistributedGradReducer(self.matrix_A, mean, degree, fusion_type=8)\n            else:\n                if not split_indices:\n                    self.split_indices = split_indices\n                else:\n                    self.split_indices = [len(self.params) - 1]\n                auto_parallel_context().set_all_reduce_fusion_split_indices(self.split_indices, \"hccl_world_groupsum3\")\n                self.grad_reducer_g = DistributedGradReducer(self.params, mean, degree, fusion_type=3)\n\n    def _get_Ainv_Ginv_Amax_Gmax_list(self, gradients, damping_step, matrix_a_allreduce, matrix_g_allreduce,\n                                      matrix_a_max_allreduce, matrix_g_max_allreduce):\n        \"\"\"get matrixA inverse list, matrixG inverse list, matrixA_max list, matrixG_max list\"\"\"\n        for i in range(len(self.params)):\n            thor_layer_count = self.weight_fim_idx_map[i]\n            conv_layer_count = self.weight_conv_idx_map[i]\n            layer_type = self.weight_layerType_idx_map[i]\n            if layer_type in [Conv, FC, Embedding]:\n                g = gradients[i]\n                matrix_A = self.matrix_A_cov[thor_layer_count]\n                matrix_G = self.matrix_G_cov[thor_layer_count]\n                matrix_A = F.depend(matrix_A, g)\n                matrix_G = F.depend(matrix_G, g)\n                A_shape = self.shape(matrix_A)\n                A_eye = self.eye(A_shape[0], A_shape[0], mstype.float32)\n                G_shape = self.shape(matrix_G)\n                G_eye = self.eye(G_shape[0], G_shape[0], mstype.float32)\n                if layer_type == Conv:\n                    A_normalizer = self.A_normalizer[conv_layer_count]\n                    G_normalizer = self.G_normalizer[conv_layer_count]\n                    A_normalizer = F.depend(A_normalizer, g)\n                    G_normalizer = F.depend(G_normalizer, g)\n                    dampingA = self.mul(damping_step, self.batch_size / A_normalizer)\n                    dampingG = self.mul(damping_step, self.batch_size / G_normalizer)\n                    dampingA = self.sqrt(dampingA)\n                    matrix_A = matrix_A + dampingA * A_eye\n                    matrix_A_inv = self.cholesky(matrix_A)\n                    matrix_A_inv = self.vector_matmul(matrix_A_inv, matrix_A_inv)\n                    A_max = P.CusFusedAbsMax1([self.matrix_A_dim[conv_layer_count],\n                                               self.matrix_A_dim[conv_layer_count]])(matrix_A_inv)\n                    A_max = self.fused_abs_max2(A_max)\n                    matrix_A_inv = self.matrix_combine(matrix_A_inv)\n                    if self.padA_flag[conv_layer_count]:\n                        matrix_A_inv = self.slice(matrix_A_inv, (0, 0), (self.matrix_A_dim[conv_layer_count],\n                                                                         self.matrix_A_dim[conv_layer_count]))\n                    if self.device_shape_pad_flag[conv_layer_count]:\n                        weight = self.params[i]\n                        weight_shape = self.shape(weight)\n                        kernel_hw = weight_shape[2] * weight_shape[3]\n                        in_channels = weight_shape[1]\n                        matrix_A_inv = self.reshape(matrix_A_inv, (kernel_hw, in_channels, kernel_hw, in_channels))\n                        matrix_A_inv = P.Pad(((0, 0), (0, self.C0 - in_channels), (0, 0),\n                                              (0, self.C0 - in_channels)))(matrix_A_inv)\n                    matrix_A_inv_shape = self.shape(self.matrix_A[thor_layer_count])\n                    matrix_A_device_temp_shape = (matrix_A_inv_shape[0], matrix_A_inv_shape[2],\n                                                  matrix_A_inv_shape[1], matrix_A_inv_shape[3])\n                    matrix_A_inv = self.reshape(matrix_A_inv, matrix_A_device_temp_shape)\n                    matrix_A_inv = self.transpose(matrix_A_inv, (2, 0, 1, 3))\n\n                    dampingG = self.sqrt(dampingG)\n                    matrix_G = self.mul(matrix_G, self.loss_scale)\n                    matrix_G = self.mul(matrix_G, self.batch_size_scale)\n                    matrix_G = matrix_G + dampingG * G_eye\n                    matrix_G_inv = self.cholesky(matrix_G)\n                    matrix_G_inv = self.vector_matmul(matrix_G_inv, matrix_G_inv)\n                    G_max = self.fused_abs_max2(matrix_G_inv)\n                    G_max = self.fused_abs_max2(G_max)\n                    matrix_G_inv = self.matrix_combine(matrix_G_inv)\n                    matrix_G_inv_shape = self.shape(self.matrix_G[thor_layer_count])\n                    matrix_G_device_temp_shape = (matrix_G_inv_shape[0], matrix_G_inv_shape[2],\n                                                  matrix_G_inv_shape[1], matrix_G_inv_shape[3])\n                    matrix_G_inv = self.reshape(matrix_G_inv, matrix_G_device_temp_shape)\n                    matrix_G_inv = self.transpose(matrix_G_inv, (2, 0, 1, 3))\n\n                    A_max = F.depend(A_max, g)\n                    G_max = F.depend(G_max, g)\n                    matrix_a_allreduce = matrix_a_allreduce + (matrix_A_inv,)\n                    matrix_g_allreduce = matrix_g_allreduce + (matrix_G_inv,)\n                    matrix_a_max_allreduce = matrix_a_max_allreduce + (A_max,)\n                    matrix_g_max_allreduce = matrix_g_max_allreduce + (G_max,)\n                elif layer_type == FC:\n                    damping = self.sqrt(damping_step)\n                    matrix_A = matrix_A + damping * A_eye\n                    matrix_A_inv = self.cholesky(matrix_A)\n                    matrix_A_inv = self.vector_matmul(matrix_A_inv, matrix_A_inv)\n                    weight_shape = self.shape(self.params[i])\n                    out_channels = weight_shape[0]\n                    if out_channels == 2:\n                        matrix_A_inv = self.matrix_combine(matrix_A_inv)\n                        matrix_G_inv = G_eye\n                    else:\n                        matrix_G = self.mul(matrix_G, self.loss_scale)\n                        matrix_G = self.mul(matrix_G, self.batch_size_scale)\n                        matrix_G = matrix_G + damping * G_eye\n                        matrix_G_inv = self.cholesky(matrix_G)\n                        matrix_G_inv = self.vector_matmul(matrix_G_inv, matrix_G_inv)\n                        if out_channels == 1001:\n                            matrix_A_inv_max = self.fused_abs_max2(matrix_A_inv)\n                            A_max = self.fused_abs_max2(matrix_A_inv_max)\n                            matrix_A_inv = self.matrix_combine(matrix_A_inv)\n                            matrix_A_inv_shape = self.shape(matrix_A_inv)\n                            matrix_A_inv = self.reshape(matrix_A_inv,\n                                                        (matrix_A_inv_shape[0] / 16, 16,\n                                                         matrix_A_inv_shape[0] / 16, 16))\n                            matrix_A_inv = self.transpose(matrix_A_inv, (2, 0, 1, 3))\n                            matrix_G_inv_max = P.CusFusedAbsMax1([1001, 1001])(matrix_G_inv)\n                            G_max = self.fused_abs_max2(matrix_G_inv_max)\n                            matrix_G_inv = self.matrix_combine(matrix_G_inv)\n                            matrix_G_inv = self.slice(matrix_G_inv, (0, 0), (1001, 1001))\n                            matrix_G_inv = P.Pad(((0, 7), (0, 7)))(matrix_G_inv)\n                            matrix_G_inv_shape = self.shape(matrix_G_inv)\n                            matrix_G_inv = self.reshape(matrix_G_inv,\n                                                        (matrix_G_inv_shape[0] / 16, 16,\n                                                         matrix_G_inv_shape[0] / 16, 16))\n                            matrix_G_inv = self.transpose(matrix_G_inv, (2, 0, 1, 3))\n                            A_max = F.depend(A_max, g)\n                            G_max = F.depend(G_max, g)\n                            matrix_a_max_allreduce = matrix_a_max_allreduce + (A_max,)\n                            matrix_g_max_allreduce = matrix_g_max_allreduce + (G_max,)\n                        else:\n                            matrix_A_inv = self.matrix_combine(matrix_A_inv)\n                            matrix_G_inv = self.matrix_combine(matrix_G_inv)\n                    matrix_a_allreduce = matrix_a_allreduce + (matrix_A_inv,)\n                    matrix_g_allreduce = matrix_g_allreduce + (matrix_G_inv,)\n                elif layer_type == Embedding:\n                    damping = self.sqrt(damping_step)\n                    A_eye = P.OnesLike()(matrix_A)\n                    matrix_A = self.mul(matrix_A, 1.0 / self.batch_size)\n                    matrix_A = matrix_A + damping * A_eye\n                    matrix_A_inv = self.inv(matrix_A)\n                    matrix_G = self.mul(matrix_G, self.loss_scale)\n                    matrix_G = self.mul(matrix_G, self.batch_size_scale)\n                    matrix_G = matrix_G + damping * G_eye\n                    matrix_G_inv = self.cholesky(matrix_G)\n                    matrix_G_inv = self.vector_matmul(matrix_G_inv, matrix_G_inv)\n                    matrix_G_inv = self.matrix_combine(matrix_G_inv)\n                    matrix_a_allreduce = matrix_a_allreduce + (matrix_A_inv,)\n                    matrix_g_allreduce = matrix_g_allreduce + (matrix_G_inv,)\n        return matrix_a_allreduce, matrix_g_allreduce, matrix_a_max_allreduce, matrix_g_max_allreduce\n\n    def _process_layernorm(self, damping_step, gradient):\n        \"\"\"process layernorm layer for thor\"\"\"\n        damping = self.sqrt(damping_step)\n        normalizer = self.cast(self.batch_size, mstype.float32)\n        fim_cov = self.square(gradient)\n        fim_cov = self.mul(fim_cov, 1.0 / normalizer)\n        fim_cov = fim_cov + damping\n        fim_inv = self.inv(fim_cov)\n        gradient = self.mul(fim_inv, gradient)\n        return gradient\n\n    def _get_second_gradients(self, new_grads, damping_step, gradients):\n        \"\"\"get second gradients for thor\"\"\"\n        params_len = len(self.params)\n        for i in range(params_len):\n            g = gradients[i]\n            thor_layer_count = self.weight_fim_idx_map[i]\n            layer_type = self.weight_layerType_idx_map[i]\n            if self.conv_layer_count > 0:\n                matrix_A = self.matrix_A[thor_layer_count]\n                matrix_G = self.matrix_G[thor_layer_count]\n                matrix_max = self.matrix_max_inv[thor_layer_count]\n                if layer_type == FC:\n                    g = self.cube_matmul_left_fc(matrix_G, g)\n                    g = self.cube_matmul_right_fc(g, matrix_A, matrix_max)\n                elif layer_type == Conv:\n                    g = self.cube_matmul_left(matrix_G, g)\n                    g = self.cube_matmul_right_mul(g, matrix_A, matrix_max)\n            else:\n                if layer_type == Embedding:\n                    temp_a_ori = self.matrix_A_cov[thor_layer_count]\n                    temp_g = self.matrix_G_cov[thor_layer_count]\n                    temp_a = self.expand(temp_a_ori, 1)\n                    g = self.mul(temp_a, g)\n                    temp_g = self.cast(temp_g, mstype.float16)\n                    g = self.cast(g, mstype.float16)\n                    g = self.matmul(g, temp_g)\n                    g = self.cast(g, mstype.float32)\n                elif layer_type == FC:\n                    temp_a = self.matrix_A_cov[thor_layer_count]\n                    temp_g = self.matrix_G_cov[thor_layer_count]\n                    temp_a = self.cast(temp_a, mstype.float16)\n                    temp_g = self.cast(temp_g, mstype.float16)\n                    g = self.cast(g, mstype.float16)\n                    g = self.matmul(temp_g, g)\n                    g = self.matmul(g, temp_a)\n                    g = self.cast(g, mstype.float32)\n                elif layer_type == LayerNorm:\n                    g = self._process_layernorm(damping_step, g)\n            new_grads = new_grads + (g,)\n        return new_grads\n\n    def construct(self, gradients):\n        params = self.params\n        moments = self.moments\n        damping_step = self.gather(self.damping, self.cov_step, self.axis)\n        damping_step = self.cast(damping_step, mstype.float32)\n        if self.thor:\n            matrix_A_allreduce = ()\n            matrix_G_allreduce = ()\n            matrix_A_max_allreduce = ()\n            matrix_G_max_allreduce = ()\n            matrix_A_allreduce, matrix_G_allreduce, matrix_A_max_allreduce, matrix_G_max_allreduce = \\\n                self._get_Ainv_Ginv_Amax_Gmax_list(gradients, damping_step, matrix_A_allreduce, matrix_G_allreduce,\n                                                   matrix_A_max_allreduce, matrix_G_max_allreduce)\n            if self.is_distributed and self.conv_layer_count > 0:\n                matrix_A_allreduce = self.grad_reducer_A(matrix_A_allreduce)\n                matrix_G_allreduce = self.grad_reducer_G(matrix_G_allreduce)\n                matrix_A_max_allreduce = self.grad_reducer_Amax(matrix_A_max_allreduce)\n                matrix_G_max_allreduce = self.grad_reducer_Gmax(matrix_G_max_allreduce)\n\n            new_grads = ()\n            for i in range(len(self.params)):\n                g = gradients[i]\n                thor_layer_count = self.weight_fim_idx_map[i]\n                conv_layer_count = self.weight_conv_idx_map[i]\n                layer_type = self.weight_layerType_idx_map[i]\n                if self.conv_layer_count > 0:\n                    temp_a = matrix_A_allreduce[thor_layer_count]\n                    temp_g = matrix_G_allreduce[thor_layer_count]\n                    matrix_A_inv_max = self.log(matrix_A_max_allreduce[thor_layer_count])\n                    matrix_A_inv_max = self.mul(matrix_A_inv_max, -1)\n                    matrix_A_inv_max = self.exp(matrix_A_inv_max)\n                    temp_a = self.mul(temp_a, matrix_A_inv_max)\n                    matrix_G_inv_max = self.log(matrix_G_max_allreduce[thor_layer_count])\n                    matrix_G_inv_max = self.mul(matrix_G_inv_max, -1)\n                    matrix_G_inv_max = self.exp(matrix_G_inv_max)\n                    temp_g = self.mul(temp_g, matrix_G_inv_max)\n                    temp_max = self.mul(matrix_A_max_allreduce[thor_layer_count],\n                                        matrix_G_max_allreduce[thor_layer_count])\n                    temp_a = self.cast(temp_a, mstype.float16)\n                    temp_g = self.cast(temp_g, mstype.float16)\n                    if layer_type == FC:\n                        g = self.cube_matmul_left_fc(temp_g, g)\n                        g = self.cube_matmul_right_fc(g, temp_a, temp_max)\n                    elif layer_type == Conv:\n                        A_normalizer = self.A_normalizer[conv_layer_count]\n                        A_normalizer = F.depend(A_normalizer, g)\n                        temp_max = self.mul(temp_max, self.batch_size / A_normalizer)\n                        g = self.cube_matmul_left(temp_g, g)\n                        g = self.cube_matmul_right_mul(g, temp_a, temp_max)\n                    fake_A = self.assign(self.matrix_A[thor_layer_count], temp_a)\n                    fake_G = self.assign(self.matrix_G[thor_layer_count], temp_g)\n                    fake_max = self.assign(self.matrix_max_inv[thor_layer_count], temp_max)\n                    g = F.depend(g, fake_A)\n                    g = F.depend(g, fake_G)\n                    g = F.depend(g, fake_max)\n                else:\n                    if layer_type == Embedding:\n                        temp_a_ori = matrix_A_allreduce[thor_layer_count]\n                        temp_g = matrix_G_allreduce[thor_layer_count]\n                        fake_A = self.assign(self.matrix_A_cov[thor_layer_count], temp_a_ori)\n                        fake_G = self.assign(self.matrix_G_cov[thor_layer_count], temp_g)\n                        g = F.depend(g, fake_A)\n                        g = F.depend(g, fake_G)\n                        temp_a = self.expand(temp_a_ori, 1)\n                        g = self.mul(temp_a, g)\n                        temp_g = self.cast(temp_g, mstype.float16)\n                        g = self.cast(g, mstype.float16)\n                        g = self.matmul(g, temp_g)\n                        g = self.cast(g, mstype.float32)\n                    elif layer_type == FC:\n                        temp_a = matrix_A_allreduce[thor_layer_count]\n                        temp_g = matrix_G_allreduce[thor_layer_count]\n                        fake_A = self.assign(self.matrix_A_cov[thor_layer_count], temp_a)\n                        fake_G = self.assign(self.matrix_G_cov[thor_layer_count], temp_g)\n                        g = F.depend(g, fake_A)\n                        g = F.depend(g, fake_G)\n                        temp_a = self.cast(temp_a, mstype.float16)\n                        temp_g = self.cast(temp_g, mstype.float16)\n                        g = self.cast(g, mstype.float16)\n                        g = self.matmul(temp_g, g)\n                        g = self.matmul(g, temp_a)\n                        g = self.cast(g, mstype.float32)\n                    elif layer_type == LayerNorm:\n                        g = self._process_layernorm(damping_step, g)\n                new_grads = new_grads + (g,)\n            gradients = new_grads\n        else:\n            new_grads = ()\n            gradients = self._get_second_gradients(new_grads, damping_step, gradients)\n\n        if self.is_distributed and self.conv_layer_count == 0:\n            gradients = self.grad_reducer_g(gradients)\n        self.cov_step = self.cov_step + self.one\n        if self.weight_decay > 0:\n            gradients = self.hyper_map(F.partial(apply_decay, self.weight_decay), self.decay_flags, params, gradients)\n        gradients = self.scale_grad(gradients)\n        lr = self.get_lr()\n        success = self.hyper_map(F.partial(_momentum_opt, self.opt, self.momentum, lr), gradients, params, moments)\n        return success\n", "meta": {"hexsha": "07b964f953a1bf648bc0926402432a4e840e6a03", "size": 49824, "ext": "py", "lang": "Python", "max_stars_repo_path": "mindspore/nn/optim/thor.py", "max_stars_repo_name": "GeekHee/mindspore", "max_stars_repo_head_hexsha": "896b8e5165dd0a900ed5a39e0fb23525524bf8b0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mindspore/nn/optim/thor.py", "max_issues_repo_name": "GeekHee/mindspore", "max_issues_repo_head_hexsha": "896b8e5165dd0a900ed5a39e0fb23525524bf8b0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mindspore/nn/optim/thor.py", "max_forks_repo_name": "GeekHee/mindspore", "max_forks_repo_head_hexsha": "896b8e5165dd0a900ed5a39e0fb23525524bf8b0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.4832962138, "max_line_length": 119, "alphanum_fraction": 0.5926461143, "include": true, "reason": "import numpy", "num_tokens": 10856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.32423541204073586, "lm_q1q2_score": 0.16971141250787478}}
{"text": "# linflat.py - FlatSystem subclass for linear systems\n# RMM, 10 November 2012\n#\n# This file defines a FlatSystem class for a linear system.\n#\n# Copyright (c) 2012 by California Institute of Technology\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n#    notice, this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n#    notice, this list of conditions and the following disclaimer in the\n#    documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the California Institute of Technology nor\n#    the names of its contributors may be used to endorse or promote\n#    products derived from this software without specific prior\n#    written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL CALTECH\n# OR THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n# SUCH DAMAGE.\n\nimport numpy as np\nimport control\nfrom .flatsys import FlatSystem\nfrom ..iosys import LinearIOSystem\n\n\nclass LinearFlatSystem(FlatSystem, LinearIOSystem):\n    \"\"\"Base class for a linear, differentially flat system.\n\n    This class is used to create a differentially flat system representation\n    from a linear system.\n\n    Parameters\n    ----------\n    linsys : StateSpace\n        LTI StateSpace system to be converted\n    inputs : int, list of str or None, optional\n        Description of the system inputs.  This can be given as an integer\n        count or as a list of strings that name the individual signals.\n        If an integer count is specified, the names of the signal will be\n        of the form `s[i]` (where `s` is one of `u`, `y`, or `x`).  If\n        this parameter is not given or given as `None`, the relevant\n        quantity will be determined when possible based on other\n        information provided to functions using the system.\n    outputs : int, list of str or None, optional\n        Description of the system outputs.  Same format as `inputs`.\n    states : int, list of str, or None, optional\n        Description of the system states.  Same format as `inputs`.\n    dt : None, True or float, optional\n        System timebase.  None (default) indicates continuous\n        time, True indicates discrete time with undefined sampling\n        time, positive number is discrete time with specified\n        sampling time.\n    params : dict, optional\n        Parameter values for the systems.  Passed to the evaluation\n        functions for the system as default values, overriding internal\n        defaults.\n    name : string, optional\n        System name (used for specifying signals)\n\n    \"\"\"\n\n    def __init__(self, linsys, inputs=None, outputs=None, states=None,\n                 name=None):\n        \"\"\"Define a flat system from a SISO LTI system.\n\n        Given a reachable, single-input/single-output, linear time-invariant\n        system, create a differentially flat system representation.\n\n        \"\"\"\n        # Make sure we can handle the system\n        if (not control.isctime(linsys)):\n            raise control.ControlNotImplemented(\n                \"requires continuous time, linear control system\")\n        elif (not control.issiso(linsys)):\n            raise control.ControlNotImplemented(\n                \"only single input, single output systems are supported\")\n\n        # Initialize the object as a LinearIO system\n        LinearIOSystem.__init__(\n            self, linsys, inputs=inputs, outputs=outputs, states=states,\n            name=name)\n\n        # Find the transformation to chain of integrators form\n        # Note: store all array as ndarray, not matrix\n        zsys, Tr = control.reachable_form(linsys)\n        Tr = np.array(Tr[::-1, ::])     # flip rows\n\n        # Extract the information that we need\n        self.F = np.array(zsys.A[0, ::-1])      # input function coeffs\n        self.T = Tr                             # state space transformation\n        self.Tinv = np.linalg.inv(Tr)           # compute inverse once\n\n        # Compute the flat output variable z = C x\n        Cfz = np.zeros(np.shape(linsys.C)); Cfz[0, 0] = 1\n        self.Cf = Cfz @ Tr\n\n    # Compute the flat flag from the state (and input)\n    def forward(self, x, u):\n        \"\"\"Compute the flat flag given the states and input.\n\n        See :func:`control.flatsys.FlatSystem.forward` for more info.\n\n        \"\"\"\n        x = np.reshape(x, (-1, 1))\n        u = np.reshape(u, (1, -1))\n        zflag = [np.zeros(self.nstates + 1)]\n        zflag[0][0] = self.Cf @ x\n        H = self.Cf                     # initial state transformation\n        for i in range(1, self.nstates + 1):\n            zflag[0][i] = H @ (self.A @ x + self.B @ u)\n            H = H @ self.A       # derivative for next iteration\n        return zflag\n\n    # Compute state and input from flat flag\n    def reverse(self, zflag):\n        \"\"\"Compute the states and input given the flat flag.\n\n        See :func:`control.flatsys.FlatSystem.reverse` for more info.\n\n        \"\"\"\n        z = zflag[0][0:-1]\n        x = self.Tinv @ z\n        u = zflag[0][-1] - self.F @ z\n        return np.reshape(x, self.nstates), np.reshape(u, self.ninputs)\n", "meta": {"hexsha": "931446ca88b5a9d4d24ce3916266acc27b44d2c0", "size": 5965, "ext": "py", "lang": "Python", "max_stars_repo_path": "control/flatsys/linflat.py", "max_stars_repo_name": "berezhko/python-control", "max_stars_repo_head_hexsha": "78ec3eedd5a4a5f3d8409eec7c7f7e787793b357", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1112, "max_stars_repo_stars_event_min_datetime": "2015-01-14T08:01:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:54:00.000Z", "max_issues_repo_path": "control/flatsys/linflat.py", "max_issues_repo_name": "berezhko/python-control", "max_issues_repo_head_hexsha": "78ec3eedd5a4a5f3d8409eec7c7f7e787793b357", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 646, "max_issues_repo_issues_event_min_datetime": "2015-02-02T15:35:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T08:19:26.000Z", "max_forks_repo_path": "control/flatsys/linflat.py", "max_forks_repo_name": "berezhko/python-control", "max_forks_repo_head_hexsha": "78ec3eedd5a4a5f3d8409eec7c7f7e787793b357", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 366, "max_forks_repo_forks_event_min_datetime": "2015-01-28T17:58:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T11:04:10.000Z", "avg_line_length": 41.7132867133, "max_line_length": 76, "alphanum_fraction": 0.6660519698, "include": true, "reason": "import numpy", "num_tokens": 1364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.16971140908999655}}
{"text": "import os\nimport time\nimport logging\nimport torch\nimport torch.nn.functional as F\nimport torch.backends.cudnn as cudnn\nimport numpy as np\nimport nibabel as nib\nimport scipy.misc\nimport pdb\n\ncudnn.benchmark = True\n\npath = os.path.dirname(__file__)\n\n\n# dice socre is equal to f1 score\ndef dice_score(o, t, eps=1e-8):\n    num = 2 * (o * t).sum() + eps  #\n    den = o.sum() + t.sum() + eps  # eps\n    # print(o.sum(),t.sum(),num,den)\n    print('All_voxels:240*240*155 | numerator:{} | denominator:{} | pred_voxels:{} | GT_voxels:{}'.format(int(num),\n                                                                                                          int(den),\n                                                                                                          o.sum(),\n                                                                                                          int(t.sum())))\n    return num / den\n\n\ndef softmax_output_dice(output, target):\n    ret = []\n\n    # whole\n    o = output > 0;\n    t = target > 0  # ce\n    ret += dice_score(o, t),\n    # core\n    o = (output == 1) | (output == 3)\n    t = (target == 1) | (target == 4)\n    ret += dice_score(o, t),\n    # active\n    o = (output == 3);\n    t = (target == 4)\n    ret += dice_score(o, t),\n\n    return ret\n\n\nkeys = 'whole', 'core', 'enhancing', 'loss'\n\n\ndef validate_softmax(\n        valid_loader,\n        model,\n        cfg='',\n        savepath='',  # when in validation set, you must specify the path to save the 'nii' segmentation results here\n        names=None,  # The names of the patients orderly!\n        scoring=True,  # If true, print the dice score.\n        verbose=False,\n        use_TTA=False,  # Test time augmentation, False as default!\n        save_format=None,  # ['nii','npy'], use 'nii' as default. Its purpose is for submission.\n        snapshot=False,  # for visualization. Default false. It is recommended to generate the visualized figures.\n        postprocess=False,  # Defualt False, when use postprocess, the score of dice_ET would be changed.\n        cpu_only=False):\n    assert cfg is not None\n    H, W, T = 240, 240, 155\n    model.eval()\n    runtimes = []\n    vals = AverageMeter()\n    for i, data in enumerate(valid_loader):\n        target_cpu = data[1][0, :H, :W,\n                     :T].numpy() if scoring else None  # when validing, make sure that argument 'scoring' must be false, else it raise a error!\n\n        if cpu_only == False:\n            data = [t.cuda(non_blocking=True) for t in data]\n        x, target = data[:2]\n        # pdb.set_trace()\n        # compute output\n        if not use_TTA:\n\n            # torch.cuda.synchronize()\n            start_time = time.time()\n            logit = model(x)\n            # torch.cuda.synchronize()\n            elapsed_time = time.time() - start_time\n            runtimes.append(elapsed_time)\n\n            output = F.softmax(logit, dim=1)\n        else:\n            logit = F.softmax(model(x), 1)  # 000\n            logit += F.softmax(model(x.flip(dims=(2,))).flip(dims=(2,)), 1)\n            logit += F.softmax(model(x.flip(dims=(3,))).flip(dims=(3,)), 1)\n            logit += F.softmax(model(x.flip(dims=(4,))).flip(dims=(4,)), 1)\n            logit += F.softmax(model(x.flip(dims=(2, 3))).flip(dims=(2, 3)), 1)\n            logit += F.softmax(model(x.flip(dims=(2, 4))).flip(dims=(2, 4)), 1)\n            logit += F.softmax(model(x.flip(dims=(3, 4))).flip(dims=(3, 4)), 1)\n            logit += F.softmax(model(x.flip(dims=(2, 3, 4))).flip(dims=(2, 3, 4)), 1)\n            output = logit / 8.0  # mean\n        # pdb.set_trace()\n        output = output[:, :, :H, :W, :T].cpu().numpy()\n\n        ############\n        # todo 0->1\n        output = output.argmax(1)  # (channels,height,width,depth)\n\n        if postprocess == True:\n            for j in range(3):\n                ET_voxels = (output[j, :, :, :] == 3).sum()\n                if ET_voxels < 500:\n                    # zhuyi zai output hou jia 'J'\n                    output[j][np.where(output[j, :, :, :] == 3)] = 1\n\n                # todo\n\n                TC_voxels = (output[j, :, :, :] == 1).sum()\n                if TC_voxels < 100:\n                    output[j][np.where(output[j, :, :, :] == 2)] = 1\n\n        msg = 'Subject {}/{}, '.format(i + 1, len(valid_loader))\n        name = str(i)\n        if names:\n            # todo\n            name = [names[3 * i], names[3 * i + 1], names[3 * i + 2]]\n            # todo\n            msg += '{:>20}, {:>20},{:>20},'.format(name[0], name[1], name[2])\n\n        if savepath:\n            # .npy for farthur model ensemble\n            # .nii for directly model submission\n            assert save_format in ['npy', 'nii']\n            if save_format == 'npy':\n                np.save(os.path.join(savepath, name + '_preds'), output)\n            if save_format == 'nii':\n                for i in range(3):\n                    oname = os.path.join(savepath, 'submission', name[i] + '.nii.gz')\n                    seg_img = np.zeros(shape=(H, W, T), dtype=np.uint8)\n\n                    seg_img[np.where(output[i] == 1)] = 1\n                    seg_img[np.where(output[i] == 2)] = 2\n                    seg_img[np.where(output[i] == 3)] = 4\n                    if verbose:\n                        # todo\n                        # print('1:',np.sum(seg_img==1),' | 2:',np.sum(seg_img==2),' | 4:',np.sum(seg_img==4))\n                        # print('WT:',np.sum((seg_img==1)|(seg_img==2)|(seg_img==4)),' | TC:',np.sum((seg_img==1)|(seg_img==4)),' | ET:',np.sum(seg_img==4))\n                        # todo\n                        logging.info(\n                            ('1:', np.sum(seg_img == 1), ' | 2:', np.sum(seg_img == 2), ' | 4:', np.sum(seg_img == 4)))\n                        logging.info(('WT:', np.sum((seg_img == 1) | (seg_img == 2) | (seg_img == 4)), ' | TC:',\n                                      np.sum((seg_img == 1) | (seg_img == 4)), ' | ET:', np.sum(seg_img == 4)))\n                        nib.save(nib.Nifti1Image(seg_img, None), oname)\n                logging.info(msg)\n                if snapshot:\n                    \"\"\" --- grey figure---\"\"\"\n                    # Snapshot_img = np.zeros(shape=(H,W,T),dtype=np.uint8)\n                    # Snapshot_img[np.where(output[1,:,:,:]==1)] = 64\n                    # Snapshot_img[np.where(output[2,:,:,:]==1)] = 160\n                    # Snapshot_img[np.where(output[3,:,:,:]==1)] = 255\n                    \"\"\" --- colorful figure--- \"\"\"\n                    Snapshot_img = np.zeros(shape=(H, W, 3, T), dtype=np.uint8)\n                    Snapshot_img[:, :, 0, :][np.where(output == 1)] = 255\n                    Snapshot_img[:, :, 1, :][np.where(output == 2)] = 255\n                    Snapshot_img[:, :, 2, :][np.where(output == 3)] = 255\n\n                    for frame in range(T):\n                        os.makedirs(os.path.join(savepath, 'snapshot', name), exist_ok=True)\n                        scipy.misc.imsave(os.path.join(savepath, 'snapshot', name, str(frame) + '.png'),\n                                          Snapshot_img[:, :, :, frame])\n\n        if scoring:\n            scores = softmax_output_dice(output, target_cpu)\n            vals.update(np.array(scores))\n            msg += ', '.join(['{}: {:.4f}'.format(k, v) for k, v in zip(keys, scores)])\n\n            if snapshot:\n                # red: (255,0,0) green:(0,255,0) blue:(0,0,255) 1 for NCR & NET, 2 for ED, 4 for ET, and 0 for everything else.\n                gap_width = 2  # boundary width = 2\n                Snapshot_img = np.zeros(shape=(H, W * 2 + gap_width, 3, T), dtype=np.uint8)\n                Snapshot_img[:, W:W + gap_width, :] = 255  # white boundary\n\n                empty_fig = np.zeros(shape=(H, W, T), dtype=np.uint8)\n                empty_fig[np.where(output == 1)] = 255\n                Snapshot_img[:, :W, 0, :] = empty_fig\n                empty_fig = np.zeros(shape=(H, W, T), dtype=np.uint8)\n                empty_fig[np.where(target_cpu == 1)] = 255\n                Snapshot_img[:, W + gap_width:, 0, :] = empty_fig\n\n                empty_fig = np.zeros(shape=(H, W, T), dtype=np.uint8)\n                empty_fig[np.where(output == 2)] = 255\n                Snapshot_img[:, :W, 1, :] = empty_fig\n                empty_fig = np.zeros(shape=(H, W, T), dtype=np.uint8)\n                empty_fig[np.where(target_cpu == 2)] = 255\n                Snapshot_img[:, W + gap_width:, 1, :] = empty_fig\n\n                empty_fig = np.zeros(shape=(H, W, T), dtype=np.uint8)\n                empty_fig[np.where(output == 3)] = 255\n                Snapshot_img[:, :W, 2, :] = empty_fig\n                empty_fig = np.zeros(shape=(H, W, T), dtype=np.uint8)\n                empty_fig[np.where(target_cpu == 4)] = 255\n                Snapshot_img[:, W + gap_width:, 2, :] = empty_fig\n\n                for frame in range(T):\n                    os.makedirs(os.path.join('snapshot', cfg, name), exist_ok=True)\n                    scipy.misc.imsave(os.path.join('snapshot', cfg, name, str(frame) + '.png'),\n                                      Snapshot_img[:, :, :, frame])\n\n    if scoring:\n        msg = 'Average scores:'\n        msg += ', '.join(['{}: {:.4f}'.format(k, v) for k, v in zip(keys, vals.avg)])\n        logging.info(msg)\n    if len(runtimes):\n        computational_runtime(runtimes)\n\n    model.train()\n    return vals.avg\n\n\ndef computational_runtime(runtimes):\n    # remove the maximal value and minimal value\n    runtimes = np.array(runtimes)\n    maxvalue = np.max(runtimes)\n    minvalue = np.min(runtimes)\n    nums = runtimes.shape[0] - 2\n    meanTime = (np.sum(runtimes) - maxvalue - minvalue) / nums\n    fps = 1 / meanTime\n    print('mean runtime:', meanTime, 'fps:', fps)\n\n\nclass AverageMeter(object):\n    \"\"\"Computes and stores the average and current value\"\"\"\n\n    def __init__(self):\n        self.reset()\n\n    def reset(self):\n        self.val = 0\n        self.avg = 0\n        self.sum = 0\n        self.count = 0\n\n    def update(self, val, n=1):\n        self.val = val\n        self.sum += val * n\n        self.count += n\n        self.avg = self.sum / self.count\n", "meta": {"hexsha": "7603cfa6dff9bd145e9609672035d7440faec0c5", "size": 10078, "ext": "py", "lang": "Python", "max_stars_repo_path": "predict_1.py", "max_stars_repo_name": "easthorse/brain-tumor-segmentation-based-on-group-convolution", "max_stars_repo_head_hexsha": "98547a4c89cd96c85045e70b46f89cfdb74edfca", "max_stars_repo_licenses": ["OLDAP-2.3"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-08-30T15:48:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-20T02:46:43.000Z", "max_issues_repo_path": "predict_1.py", "max_issues_repo_name": "easthorse/brain-tumor-segmentation-based-on-group-convolution", "max_issues_repo_head_hexsha": "98547a4c89cd96c85045e70b46f89cfdb74edfca", "max_issues_repo_licenses": ["OLDAP-2.3"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "predict_1.py", "max_forks_repo_name": "easthorse/brain-tumor-segmentation-based-on-group-convolution", "max_forks_repo_head_hexsha": "98547a4c89cd96c85045e70b46f89cfdb74edfca", "max_forks_repo_licenses": ["OLDAP-2.3"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3032786885, "max_line_length": 156, "alphanum_fraction": 0.4820400873, "include": true, "reason": "import numpy,import scipy", "num_tokens": 2642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.16971140908999655}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Copyright (c) 2015 IAS / CNRS / Univ. Paris-Sud\n# BSD License - see attached LICENSE file\n# Author: Alexandre Boucaud <alexandre.boucaud@ias.u-psud.fr>\n\n\"\"\"\nPyPHER - Python-based PSF Homogenization kERnels\n================================================\n\nCompute the homogenization kernel between two PSFs\n\nUsage:\n  pypher psf_source psf_target output\n         [-s ANGLE_SOURCE] [-t ANGLE_TARGET] [-r REG_FACT]\n  pypher (-h | --help)\n\nExample:\n  pypher psf_a.fits psf_b.fits kernel_a_to_b.fits -r 1.e-5\n\"\"\"\nfrom __future__ import absolute_import, print_function, division\n\nimport os\nimport sys\nimport logging\nimport logging.handlers\nimport argparse\nimport numpy as np\n\nfrom scipy.ndimage import rotate, zoom\n\nfrom . import fitsutils as fits\nfrom .parser import ThrowingArgumentParser, ArgumentParserError\n\n__version__ = '0.6.4'\n\n\ndef parse_args():\n    \"\"\"Argument parser for the command line interface of `pypher`\"\"\"\n    parser = ThrowingArgumentParser(\n        formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n        prog='pypher',\n        description=\"Compute the homogenization kernel between two PSFs\")\n\n    parser.add_argument('psf_source', type=str,\n                        help=\"FITS file of PSF image with highest resolution\")\n\n    parser.add_argument('psf_target', type=str,\n                        help=\"FITS file of PSF image with lowest resolution\")\n\n    parser.add_argument('output', type=str,\n                        help=\"File name for the output kernel\")\n\n    parser.add_argument('-s', '--angle_source', type=float, default=0.0,\n                        help=\"Rotation angle to apply to `psf_source` (deg)\")\n\n    parser.add_argument('-t', '--angle_target', type=float, default=0.0,\n                        help=\"Rotation angle to apply to `psf_target` (deg)\")\n\n    parser.add_argument('-r', '--reg_fact', type=float, default=1.e-4,\n                        help=\"Regularisation parameter for the Wiener filter\")\n\n    return parser.parse_args()\n\n################\n# IMAGE METHODS\n################\n\n\ndef format_kernel_header(fits_file, args, pixel_scale):\n    \"\"\"\n    Write the input parameters of pypher as comments in the header\n\n    The kernel header therefore contains the name of the PSF files\n    it has been created from.\n    The pixel scale of the kernel is also written as a dedicated\n    kernel key.\n\n    Parameters\n    ----------\n    fits_file: str\n        Path to the FITS kernel image\n    args: `argparse.Namespace`\n        Container for the parsed values\n    pixel_scale: float\n        Pixel scale of the kernel\n\n    \"\"\"\n    fits.clear_comments(fits_file)\n\n    pypher_comments = [\n        '=' * 50, '',\n        'File written with PyPHER',\n        '------------------------', '',\n        'Kernel from PSF', '',\n        '=> {0}'.format(os.path.basename(args.psf_source)), '',\n        'to PSF', '',\n        '=> {0}'.format(os.path.basename(args.psf_target)), '',\n        'using a regularisation parameter '\n        'R = {0:1.1e}'.format(args.reg_fact), '',\n        '=' * 50\n    ]\n    fits.add_comments(fits_file, pypher_comments)\n\n    fits.write_pixelscale(fits_file, pixel_scale)\n\n\ndef imrotate(image, angle, interp_order=1):\n    \"\"\"\n    Rotate an image from North to East given an angle in degrees\n\n    Parameters\n    ----------\n    image : `numpy.ndarray`\n        Input data array\n    angle : float\n        Angle in degrees\n    interp_order : int, optional\n        Spline interpolation order [0, 5] (default 1: linear)\n\n    Returns\n    -------\n    output : `numpy.ndarray`\n        Rotated data array\n\n    \"\"\"\n    return rotate(image, -1.0 * angle,\n                  order=interp_order, reshape=False, prefilter=False)\n\n\ndef imresample(image, source_pscale, target_pscale, interp_order=1):\n    \"\"\"\n    Resample data array from one pixel scale to another\n\n    The resampling ensures the parity of the image is conserved\n    to preserve the centering.\n\n    Parameters\n    ----------\n    image : `numpy.ndarray`\n        Input data array\n    source_pscale : float\n        Pixel scale of ``image`` in arcseconds\n    target_pscale : float\n        Pixel scale of output array in arcseconds\n    interp_order : int, optional\n        Spline interpolation order [0, 5] (default 1: linear)\n\n    Returns\n    -------\n    output : `numpy.ndarray`\n        Resampled data array\n\n    \"\"\"\n    old_size = image.shape[0]\n    new_size_raw = old_size * source_pscale / target_pscale\n    new_size = int(np.ceil(new_size_raw))\n\n    if new_size > 10000:\n        raise MemoryError(\"The resampling will yield a too large image. \"\n                          \"Please resize the input PSF image.\")\n\n    # Chech for parity\n    if (old_size - new_size) % 2 == 1:\n        new_size += 1\n\n    ratio = new_size / old_size\n\n    return zoom(image, ratio, order=interp_order) / ratio**2\n\n\ndef trim(image, shape):\n    \"\"\"\n    Trim image to a given shape\n\n    Parameters\n    ----------\n    image: 2D `numpy.ndarray`\n        Input image\n    shape: tuple of int\n        Desired output shape of the image\n\n    Returns\n    -------\n    new_image: 2D `numpy.ndarray`\n        Input image trimmed\n\n    \"\"\"\n    shape = np.asarray(shape, dtype=int)\n    imshape = np.asarray(image.shape, dtype=int)\n\n    if np.alltrue(imshape == shape):\n        return image\n\n    if np.any(shape <= 0):\n        raise ValueError(\"TRIM: null or negative shape given\")\n\n    dshape = imshape - shape\n    if np.any(dshape < 0):\n        raise ValueError(\"TRIM: target size bigger than source one\")\n\n    if np.any(dshape % 2 != 0):\n        raise ValueError(\"TRIM: source and target shapes \"\n                         \"have different parity\")\n\n    idx, idy = np.indices(shape)\n    offx, offy = dshape // 2\n\n    return image[idx + offx, idy + offy]\n\n\ndef zero_pad(image, shape, position='corner'):\n    \"\"\"\n    Extends image to a certain size with zeros\n\n    Parameters\n    ----------\n    image: real 2d `numpy.ndarray`\n        Input image\n    shape: tuple of int\n        Desired output shape of the image\n    position : str, optional\n        The position of the input image in the output one:\n            * 'corner'\n                top-left corner (default)\n            * 'center'\n                centered\n\n    Returns\n    -------\n    padded_img: real `numpy.ndarray`\n        The zero-padded image\n\n    \"\"\"\n    shape = np.asarray(shape, dtype=int)\n    imshape = np.asarray(image.shape, dtype=int)\n\n    if np.alltrue(imshape == shape):\n        return image\n\n    if np.any(shape <= 0):\n        raise ValueError(\"ZERO_PAD: null or negative shape given\")\n\n    dshape = shape - imshape\n    if np.any(dshape < 0):\n        raise ValueError(\"ZERO_PAD: target size smaller than source one\")\n\n    pad_img = np.zeros(shape, dtype=image.dtype)\n\n    idx, idy = np.indices(imshape)\n\n    if position == 'center':\n        if np.any(dshape % 2 != 0):\n            raise ValueError(\"ZERO_PAD: source and target shapes \"\n                             \"have different parity.\")\n        offx, offy = dshape // 2\n    else:\n        offx, offy = (0, 0)\n\n    pad_img[idx + offx, idy + offy] = image\n\n    return pad_img\n\n\n##########\n# FOURIER\n##########\n\n\ndef udft2(image):\n    \"\"\"Unitary fft2\"\"\"\n    norm = np.sqrt(image.size)\n    return np.fft.fft2(image) / norm\n\n\ndef uidft2(image):\n    \"\"\"Unitary ifft2\"\"\"\n    norm = np.sqrt(image.size)\n    return np.fft.ifft2(image) * norm\n\n\ndef psf2otf(psf, shape):\n    \"\"\"\n    Convert point-spread function to optical transfer function.\n\n    Compute the Fast Fourier Transform (FFT) of the point-spread\n    function (PSF) array and creates the optical transfer function (OTF)\n    array that is not influenced by the PSF off-centering.\n    By default, the OTF array is the same size as the PSF array.\n\n    To ensure that the OTF is not altered due to PSF off-centering, PSF2OTF\n    post-pads the PSF array (down or to the right) with zeros to match\n    dimensions specified in OUTSIZE, then circularly shifts the values of\n    the PSF array up (or to the left) until the central pixel reaches (1,1)\n    position.\n\n    Parameters\n    ----------\n    psf : `numpy.ndarray`\n        PSF array\n    shape : int\n        Output shape of the OTF array\n\n    Returns\n    -------\n    otf : `numpy.ndarray`\n        OTF array\n\n    Notes\n    -----\n    Adapted from MATLAB psf2otf function\n\n    \"\"\"\n    if np.all(psf == 0):\n        return np.zeros_like(psf)\n\n    inshape = psf.shape\n    # Pad the PSF to outsize\n    psf = zero_pad(psf, shape, position='corner')\n\n    # Circularly shift OTF so that the 'center' of the PSF is\n    # [0,0] element of the array\n    for axis, axis_size in enumerate(inshape):\n        psf = np.roll(psf, -int(axis_size / 2), axis=axis)\n\n    # Compute the OTF\n    otf = np.fft.fft2(psf)\n\n    # Estimate the rough number of operations involved in the FFT\n    # and discard the PSF imaginary part if within roundoff error\n    # roundoff error  = machine epsilon = sys.float_info.epsilon\n    # or np.finfo().eps\n    n_ops = np.sum(psf.size * np.log2(psf.shape))\n    otf = np.real_if_close(otf, tol=n_ops)\n\n    return otf\n\n\n################\n# DECONVOLUTION\n################\n\nLAPLACIAN = np.array([[ 0, -1,  0],\n                      [-1,  4, -1],\n                      [ 0, -1,  0]])\n\n\ndef deconv_wiener(psf, reg_fact):\n    r\"\"\"\n    Create a Wiener filter using a PSF image\n\n    The signal is $\\ell_2$ penalized by a 2D Laplacian operator that\n    serves as a high-pass filter for the regularization process.\n    The key to the process is to use optical transfer functions (OTF)\n    instead of simple Fourier transform, since it ensures the phase\n    of the psf is adequately placed.\n\n    Parameters\n    ----------\n    psf: `numpy.ndarray`\n        PSF array\n    reg_fact: float\n        Regularisation parameter for the Wiener filter\n\n    Returns\n    -------\n    wiener: complex `numpy.ndarray`\n        Fourier space Wiener filter\n\n    \"\"\"\n    # Optical transfer functions\n    trans_func = psf2otf(psf, psf.shape)\n    reg_op = psf2otf(LAPLACIAN, psf.shape)\n\n    wiener = np.conj(trans_func) / (np.abs(trans_func)**2 +\n                                    reg_fact * np.abs(reg_op)**2)\n\n    return wiener\n\n\ndef homogenization_kernel(psf_target, psf_source, reg_fact=1e-4, clip=True):\n    r\"\"\"\n    Compute the homogenization kernel to match two PSFs\n\n    The deconvolution step is done using a Wiener filter with $\\ell_2$\n    penalization.\n    The output is given both in Fourier and in the image domain to serve\n    different purposes.\n\n    Parameters\n    ----------\n    psf_target: `numpy.ndarray`\n        2D array\n    psf_source: `numpy.ndarray`\n        2D array\n    reg_fact: float, optional\n        Regularisation parameter for the Wiener filter\n    clip: bool, optional\n        If `True`, enforces the non-amplification of the noise\n        (default `True`)\n\n    Returns\n    -------\n    kernel_image: `numpy.ndarray`\n        2D deconvolved image\n    kernel_fourier: `numpy.ndarray`\n        2D discrete Fourier transform of deconvolved image\n\n    \"\"\"\n    wiener = deconv_wiener(psf_source, reg_fact)\n\n    kernel_fourier = wiener * udft2(psf_target)\n    kernel_image = np.real(uidft2(kernel_fourier))\n\n    if clip:\n        kernel_image.clip(-1, 1)\n\n    return kernel_image, kernel_fourier\n\n\n########\n# DEBUG\n########\n\n\ndef setup_logger(log_filename='pypher.log'):  # pragma: no cover\n    \"\"\"\n    Set up and return a logger\n\n    The logger records the time, modulename, method and message\n\n    Parameters\n    ----------\n    log_filename: str\n        Name of the output logfile\n\n    \"\"\"\n    # create logger\n    logger = logging.getLogger('logger')\n    logger.setLevel(logging.DEBUG)\n    # Add the log message handler to the logger\n    handler = logging.handlers.RotatingFileHandler(log_filename)\n    # create formatter\n    formatter = logging.Formatter('%(asctime)s - '\n                                  '%(module)s - '\n                                  '%(levelname)s - '\n                                  '%(message)s')\n    handler.setFormatter(formatter)\n    # add handler to logger\n    logger.addHandler(handler)\n\n    return logger\n\n\n#######\n# MAIN\n#######\n\n\ndef main():  # pragma: no cover\n    \"\"\"Main script for pypher\"\"\"\n    try:\n        args = parse_args()\n    except ArgumentParserError:\n        print(__doc__)\n        sys.exit()\n\n    kernel_basename, _ = os.path.splitext(args.output)\n    kernel_fits = kernel_basename + '.fits'\n\n    logname = '%s.log' % kernel_basename\n    if os.path.exists(logname):\n        os.remove(logname)\n    log = setup_logger(logname)\n\n    # Load images (NaNs are set to 0)\n    psf_source = fits.getdata(args.psf_source)\n    psf_target = fits.getdata(args.psf_target)\n\n    log.info('Source PSF loaded: %s', args.psf_source)\n    log.info('Target PSF loaded: %s', args.psf_target)\n\n    # Set NaNs to 0.0\n    psf_source = np.nan_to_num(psf_source)\n    psf_target = np.nan_to_num(psf_target)\n\n    # Retrieve the pixel scale of each image\n    pixscale_source = fits.get_pixscale(args.psf_source)\n    pixscale_target = fits.get_pixscale(args.psf_target)\n\n    log.info('Source PSF pixel scale: %.2f arcsec', pixscale_source)\n    log.info('Target PSF pixel scale: %.2f arcsec', pixscale_target)\n\n    # Rotate images (if necessary)\n    if args.angle_source != 0.0:\n        psf_source = imrotate(psf_source, args.angle_source)\n    if args.angle_target != 0.0:\n        psf_target = imrotate(psf_target, args.angle_target)\n\n    log.info('Source PSF rotated by %.2f degrees', args.angle_source)\n    log.info('Target PSF rotated by %.2f degrees', args.angle_target)\n\n    # Normalize the PSFs\n    psf_source /= psf_source.sum()\n    psf_target /= psf_target.sum()\n\n    # Resample high resolution image to the low one\n    if pixscale_source != pixscale_target:\n        try:\n            psf_source = imresample(psf_source,\n                                    pixscale_source,\n                                    pixscale_target)\n        except MemoryError:\n            log.error('- COMPUTATION ABORTED -')\n            log.error('The size of the resampled PSF would have '\n                      'exceeded 10K x 10K')\n            log.error('Please resize your image and try again')\n\n            print('Issue during the resampling step - see pypher.log')\n            sys.exit()\n\n        log.info('Source PSF resampled to the target pixel scale')\n\n    # check the new size of the source vs. the target\n    if psf_source.shape > psf_target.shape:\n        psf_source = trim(psf_source, psf_target.shape)\n    else:\n        psf_source = zero_pad(psf_source, psf_target.shape, position='center')\n\n    kernel, _ = homogenization_kernel(psf_target, psf_source,\n                                      reg_fact=args.reg_fact)\n\n    log.info('Kernel computed using Wiener filtering and a regularisation '\n             'parameter r = %.2e', args.reg_fact)\n\n    # Write kernel to FITS file\n    fits.writeto(kernel_fits, data=kernel)\n    format_kernel_header(kernel_fits, args, pixscale_target)\n\n    log.info('Kernel saved in %s', kernel_fits)\n\n    print(\"pypher: Output kernel saved to %s\" % kernel_fits)\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "59943c2acbfd7c69bb21092ee1bef2408f4c5545", "size": 15063, "ext": "py", "lang": "Python", "max_stars_repo_path": "venv/Lib/site-packages/pypher/pypher.py", "max_stars_repo_name": "KwanYu/Airbnb-Backend", "max_stars_repo_head_hexsha": "61b4c89f891378181447fc251fa0d1c2c5f435de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2016-09-08T09:44:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T08:40:19.000Z", "max_issues_repo_path": "pypher/pypher.py", "max_issues_repo_name": "back2yes/pypher", "max_issues_repo_head_hexsha": "32f606ded9276ab28c86aefadd8b9261de10aebe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2016-10-06T07:29:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T18:24:29.000Z", "max_forks_repo_path": "pypher/pypher.py", "max_forks_repo_name": "back2yes/pypher", "max_forks_repo_head_hexsha": "32f606ded9276ab28c86aefadd8b9261de10aebe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2016-10-24T00:51:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T14:05:41.000Z", "avg_line_length": 27.4872262774, "max_line_length": 78, "alphanum_fraction": 0.6193985262, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.16971140567211837}}
{"text": "import os\nimport signal\nimport sys\nimport h5py\nimport lmfit\nimport numpy as np\nimport scipy.ndimage as snd\nfrom scipy.spatial.transform import Rotation\nimport skimage.morphology as skm\nimport kosselui\nfrom PyQt5.QtCore import QTimer\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QListWidgetItem, QMessageBox\n\nimport numexpr as ne\n\naxes = [\n    [-1, -1, -1],\n    [-1, 1, 1],\n    [1, -1, 1],\n    [1, 1, -1],\n    [-1, -1, 1],\n    [-1, 1, -1],\n    [1, -1, -1],\n    [1, 1, 1],\n    [-2, -2, 0],\n    [-2, 0, -2],\n    [-2, 0, 2],\n    [-2, 2, 0],\n    [0, -2, -2],\n    [0, -2, 2],\n    [0, 2, -2],\n    [0, 2, 2],\n    [2, -2, 0],\n    [2, 0, -2],\n    [2, 0, 2],\n    [2, 2, 0],\n    [-3, -1, 1],\n    [-3, 1, -1],\n    [-1, -3, 1],\n    [-1, -1, 3],\n    [-1, 1, -3],\n    [-1, 3, -1],\n    [1, -3, -1],\n    [1, -1, -3],\n    [1, 1, 3],\n    [1, 3, 1],\n    [3, -1, -1],\n    [3, 1, 1],\n    [-3, -1, -1],\n    [-3, 1, 1],\n    [-1, -3, -1],\n    [-1, -1, -3],\n    [-1, 1, 3],\n    [-1, 3, 1],\n    [1, -3, 1],\n    [1, -1, 3],\n    [1, 1, -3],\n    [1, 3, -1],\n    [3, -1, 1],\n    [3, 1, -1],\n    [-4, 0, 0],\n    [0, -4, 0],\n    [0, 0, -4],\n    [0, 0, 4],\n    [0, 4, 0],\n    [4, 0, 0],\n    [-4, -2, -2],\n    [-4, -2, 2],\n    [-4, 2, -2],\n    [-4, 2, 2],\n    [-2, -4, -2],\n    [-2, -4, 2],\n    [-2, -2, -4],\n    [-2, -2, 4],\n    [-2, 2, -4],\n    [-2, 2, 4],\n    [-2, 4, -2],\n    [-2, 4, 2],\n    [2, -4, -2],\n    [2, -4, 2],\n    [2, -2, -4],\n    [2, -2, 4],\n    [2, 2, -4],\n    [2, 2, 4],\n    [2, 4, -2],\n    [2, 4, 2],\n    [4, -2, -2],\n    [4, -2, 2],\n    [4, 2, -2],\n    [4, 2, 2],\n    [-3, -3, -1],\n    [-3, -1, -3],\n    [-3, 1, 3],\n    [-3, 3, 1],\n    [-1, -3, -3],\n    [-1, 3, 3],\n    [1, -3, 3],\n    [1, 3, -3],\n    [3, -3, 1],\n    [3, -1, 3],\n    [3, 1, -3],\n    [3, 3, -1],\n    [-3, -3, 1],\n    [-3, -1, 3],\n    [-3, 1, -3],\n    [-3, 3, -1],\n    [-1, -3, 3],\n    [-1, 3, -3],\n    [1, -3, -3],\n    [1, 3, 3],\n    [3, -3, -1],\n    [3, -1, -3],\n    [3, 1, 3],\n    [3, 3, 1],\n    [-4, -4, 0],\n    [-4, 0, -4],\n    [-4, 0, 4],\n    [-4, 4, 0],\n    [0, -4, -4],\n    [0, -4, 4],\n    [0, 4, -4],\n    [0, 4, 4],\n    [4, -4, 0],\n    [4, 0, -4],\n    [4, 0, 4],\n    [4, 4, 0],\n    [-5, -1, -1],\n    [-1, -5, -1],\n    [-1, -1, -5],\n    [-1, 1, 5],\n    [-1, 5, 1],\n    [1, -1, 5],\n    [1, 1, -5],\n    [5, -1, 1],\n    [5, 1, -1],\n    [-5, 1, 1],\n    [-3, 3, -3],\n    [1, -5, 1],\n    [1, 5, -1],\n    [3, -3, -3],\n    [3, 3, 3],\n    [-3, -3, 3],\n    [-5, -1, 1],\n    [-5, 1, -1],\n    [-1, -1, 5],\n    [-1, 1, -5],\n    [1, -5, -1],\n    [1, -1, -5],\n    [1, 1, 5],\n    [1, 5, 1],\n    [5, 1, 1],\n    [-3, -3, -3],\n    [-3, 3, 3],\n    [-1, -5, 1],\n    [-1, 5, -1],\n    [3, -3, 3],\n    [5, -1, -1],\n    [3, 3, -3],\n    [-6, -2, 0],\n    [-6, 0, -2],\n    [-6, 0, 2],\n    [-6, 2, 0],\n    [-2, -6, 0],\n    [-2, 0, -6],\n    [-2, 0, 6],\n    [-2, 6, 0],\n    [0, -6, -2],\n    [0, -6, 2],\n    [0, -2, -6],\n    [0, -2, 6],\n    [0, 2, -6],\n    [0, 2, 6],\n    [0, 6, -2],\n    [0, 6, 2],\n    [2, -6, 0],\n    [2, 0, -6],\n    [2, 0, 6],\n    [2, 6, 0],\n    [6, -2, 0],\n    [6, 0, -2],\n    [6, 0, 2],\n    [6, 2, 0],\n    [-4, -4, -4],\n    [-4, -4, 4],\n    [-4, 4, -4],\n    [-4, 4, 4],\n    [4, -4, -4],\n    [4, -4, 4],\n    [4, 4, -4],\n    [4, 4, 4],\n    [-5, -3, 1],\n    [-5, -1, 3],\n    [-5, 1, -3],\n    [-5, 3, -1],\n    [-3, -5, 1],\n    [-3, -1, 5],\n    [-3, 1, -5],\n    [-3, 5, -1],\n    [-1, -5, 3],\n    [-1, -3, 5],\n    [-1, 3, -5],\n    [-1, 5, -3],\n    [1, -5, -3],\n    [1, -3, -5],\n    [1, 3, 5],\n    [1, 5, 3],\n    [3, -5, -1],\n    [3, -1, -5],\n    [3, 1, 5],\n    [3, 5, 1],\n    [5, -3, -1],\n    [5, -1, -3],\n    [5, 1, 3],\n    [5, 3, 1],\n    [-5, -3, -1],\n    [-5, -1, -3],\n    [-5, 1, 3],\n    [-5, 3, 1],\n    [-3, -5, -1],\n    [-3, -1, -5],\n    [-3, 1, 5],\n    [-3, 5, 1],\n    [-1, -5, -3],\n    [-1, -3, -5],\n    [-1, 3, 5],\n    [-1, 5, 3],\n    [1, -5, 3],\n    [1, -3, 5],\n    [1, 3, -5],\n    [1, 5, -3],\n    [3, -5, 1],\n    [3, -1, 5],\n    [3, 1, -5],\n    [3, 5, -1],\n    [5, -3, 1],\n    [5, -1, 3],\n    [5, 1, -3],\n    [5, 3, -1],\n    [-6, -4, -2],\n    [-6, -4, 2],\n    [-6, -2, -4],\n    [-6, -2, 4],\n    [-6, 2, -4],\n    [-6, 2, 4],\n    [-6, 4, -2],\n    [-6, 4, 2],\n    [-4, -6, -2],\n    [-4, -6, 2],\n    [-4, -2, -6],\n    [-4, -2, 6],\n    [-4, 2, -6],\n    [-4, 2, 6],\n    [-4, 6, -2],\n    [-4, 6, 2],\n    [-2, -6, -4],\n    [-2, -6, 4],\n    [-2, -4, -6],\n    [-2, -4, 6],\n    [-2, 4, -6],\n    [-2, 4, 6],\n    [-2, 6, -4],\n    [-2, 6, 4],\n    [2, -6, -4],\n    [2, -6, 4],\n    [2, -4, -6],\n    [2, -4, 6],\n    [2, 4, -6],\n    [2, 4, 6],\n    [2, 6, -4],\n    [2, 6, 4],\n    [4, -6, -2],\n    [4, -6, 2],\n    [4, -2, -6],\n    [4, -2, 6],\n    [4, 2, -6],\n    [4, 2, 6],\n    [4, 6, -2],\n    [4, 6, 2],\n    [6, -4, -2],\n    [6, -4, 2],\n    [6, -2, -4],\n    [6, -2, 4],\n    [6, 2, -4],\n    [6, 2, 4],\n    [6, 4, -2],\n    [6, 4, 2],\n    [-8, 0, 0],\n    [0, -8, 0],\n    [0, 0, -8],\n    [0, 0, 8],\n    [0, 8, 0],\n    [8, 0, 0],\n    [-5, -3, -3],\n    [-5, 3, 3],\n    [-3, -5, -3],\n    [-3, -3, -5],\n    [-3, 3, 5],\n    [-3, 5, 3],\n    [3, -5, 3],\n    [3, -3, 5],\n    [3, 3, -5],\n    [3, 5, -3],\n    [5, -3, 3],\n    [5, 3, -3],\n    [-5, -3, 3],\n    [-5, 3, -3],\n    [-3, -5, 3],\n    [-3, -3, 5],\n    [-3, 3, -5],\n    [-3, 5, -3],\n    [3, -5, -3],\n    [3, -3, -5],\n    [3, 3, 5],\n    [3, 5, 3],\n    [5, -3, -3],\n    [5, 3, 3],\n    [-7, -1, 1],\n    [-7, 1, -1],\n    [-5, -1, -5],\n    [-1, -7, 1],\n    [-1, -5, -5],\n    [-1, -1, 7],\n    [-1, 1, -7],\n    [-1, 7, -1],\n    [1, -7, -1],\n    [1, -1, -7],\n    [1, 1, 7],\n    [1, 7, 1],\n    [7, 1, 1],\n    [-5, -5, -1],\n    [-5, 1, 5],\n    [-5, 5, 1],\n    [-1, 5, 5],\n    [1, -5, 5],\n    [1, 5, -5],\n    [5, -5, 1],\n    [5, -1, 5],\n    [5, 1, -5],\n    [5, 5, -1],\n    [7, -1, -1],\n    [-7, -1, -1],\n    [-1, -7, -1],\n    [-1, -1, -7],\n    [-1, 1, 7],\n    [-1, 7, 1],\n    [1, -7, 1],\n    [1, -1, 7],\n    [1, 1, -7],\n    [1, 5, 5],\n    [1, 7, -1],\n    [5, 1, 5],\n    [7, -1, 1],\n    [7, 1, -1],\n    [-7, 1, 1],\n    [-5, -5, 1],\n    [-5, -1, 5],\n    [-5, 1, -5],\n    [-5, 5, -1],\n    [-1, -5, 5],\n    [-1, 5, -5],\n    [1, -5, -5],\n    [5, -5, -1],\n    [5, -1, -5],\n    [5, 5, 1],\n    [7, 3, 3],\n    [-7, -3, 3],\n    [-7, 3, -3],\n    [-3, -7, 3],\n    [-3, -3, 7],\n    [-3, 7, -3],\n    [-3, 3, -7],\n    [3, 7, 3],\n    [3, 3, 7],\n    [7, -3, -3],\n    [3, -7, -3],\n    [3, -3, -7],\n    [-7, -3, -3],\n    [-7, 3, 3],\n    [-3, -7, -3],\n    [-3, -3, -7],\n    [-3, 7, 3],\n    [-3, 3, 7],\n    [3, 3, -7],\n    [3, 7, -3],\n    [7, 3, -3],\n    [7, -3, 3],\n    [3, -7, 3],\n    [3, -3, 7],\n    [-7, -3, -1],\n    [-7, -1, -3],\n    [-7, 1, 3],\n    [-7, 3, 1],\n    [-5, -5, 3],\n    [-5, -3, 5],\n    [-5, 3, -5],\n    [-5, 5, -3],\n    [-3, -7, -1],\n    [-3, -5, 5],\n    [-3, -1, -7],\n    [-3, 1, 7],\n    [-3, 5, -5],\n    [-3, 7, 1],\n    [-1, -7, -3],\n    [-1, -3, -7],\n    [-1, 3, 7],\n    [-1, 7, 3],\n    [1, -7, 3],\n    [1, -3, 7],\n    [1, 3, -7],\n    [1, 7, -3],\n    [3, -7, 1],\n    [3, -5, -5],\n    [3, -1, 7],\n    [3, 1, -7],\n    [3, 5, 5],\n    [3, 7, -1],\n    [5, -5, -3],\n    [5, -3, -5],\n    [5, 3, 5],\n    [5, 5, 3],\n    [7, -3, 1],\n    [7, -1, 3],\n    [7, 1, -3],\n    [7, 3, -1],\n    [-7, -3, 1],\n    [-7, -1, 3],\n    [-7, 1, -3],\n    [-7, 3, -1],\n    [-5, -5, -3],\n    [-5, -3, -5],\n    [-5, 3, 5],\n    [-5, 5, 3],\n    [-3, -7, 1],\n    [-3, -5, -5],\n    [-3, -1, 7],\n    [-3, 1, -7],\n    [-3, 5, 5],\n    [-3, 7, -1],\n    [-1, -7, 3],\n    [-1, -3, 7],\n    [-1, 3, -7],\n    [-1, 7, -3],\n    [1, -7, -3],\n    [1, -3, -7],\n    [1, 3, 7],\n    [1, 7, 3],\n    [3, -7, -1],\n    [3, -5, 5],\n    [3, -1, -7],\n    [3, 1, 7],\n    [3, 5, -5],\n    [3, 7, 1],\n    [5, -5, 3],\n    [5, -3, 5],\n    [5, 3, -5],\n    [5, 5, -3],\n    [7, -3, -1],\n    [7, -1, -3],\n    [7, 1, 3],\n    [7, 3, 1],\n    [-2, 0, 0],\n    [0, -2, 0],\n    [0, 0, -2],\n    [0, 0, 2],\n    [0, 2, 0],\n    [2, 0, 0],\n    [-2, -2, -2],\n    [-2, -2, 2],\n    [-2, 2, -2],\n    [-2, 2, 2],\n    [2, -2, -2],\n    [2, -2, 2],\n    [2, 2, -2],\n    [2, 2, 2],\n    [-4, -2, 0],\n    [-4, 0, -2],\n    [-4, 0, 2],\n    [-4, 2, 0],\n    [-2, -4, 0],\n    [-2, 0, -4],\n    [-2, 0, 4],\n    [-2, 4, 0],\n    [0, -4, -2],\n    [0, -4, 2],\n    [0, -2, -4],\n    [0, -2, 4],\n    [0, 2, -4],\n    [0, 2, 4],\n    [0, 4, -2],\n    [0, 4, 2],\n    [2, -4, 0],\n    [2, 0, -4],\n    [2, 0, 4],\n    [2, 4, 0],\n    [4, -2, 0],\n    [4, 0, -2],\n    [4, 0, 2],\n    [4, 2, 0],\n    [-4, -2, -4],\n    [-2, -4, -4],\n    [2, 4, 4],\n    [4, 2, 4],\n    [-6, 0, 0],\n    [-4, -4, -2],\n    [-4, -4, 2],\n    [-4, -2, 4],\n    [-4, 2, -4],\n    [-4, 2, 4],\n    [-4, 4, -2],\n    [-4, 4, 2],\n    [-2, -4, 4],\n    [-2, 4, -4],\n    [-2, 4, 4],\n    [0, -6, 0],\n    [0, 0, -6],\n    [0, 0, 6],\n    [0, 6, 0],\n    [2, -4, -4],\n    [2, -4, 4],\n    [2, 4, -4],\n    [4, -4, -2],\n    [4, -4, 2],\n    [4, -2, -4],\n    [4, -2, 4],\n    [4, 2, -4],\n    [4, 4, -2],\n    [4, 4, 2],\n    [6, 0, 0],\n    [-6, -2, -2],\n    [-6, -2, 2],\n    [-6, 2, -2],\n    [-6, 2, 2],\n    [-2, -6, -2],\n    [-2, -6, 2],\n    [-2, -2, -6],\n    [-2, -2, 6],\n    [-2, 2, -6],\n    [-2, 2, 6],\n    [-2, 6, -2],\n    [-2, 6, 2],\n    [2, -6, -2],\n    [2, -6, 2],\n    [2, -2, -6],\n    [2, -2, 6],\n    [2, 2, -6],\n    [2, 2, 6],\n    [2, 6, -2],\n    [2, 6, 2],\n    [6, -2, -2],\n    [6, -2, 2],\n    [6, 2, -2],\n    [6, 2, 2],\n    [-6, -4, 0],\n    [-6, 0, -4],\n    [-4, -6, 0],\n    [-4, 0, -6],\n    [-4, 0, 6],\n    [-4, 6, 0],\n    [0, -6, -4],\n    [0, -4, -6],\n    [0, -4, 6],\n    [0, 4, -6],\n    [0, 4, 6],\n    [0, 6, 4],\n    [4, -6, 0],\n    [4, 0, -6],\n    [4, 0, 6],\n    [4, 6, 0],\n    [6, 0, 4],\n    [6, 4, 0],\n    [-6, 0, 4],\n    [-6, 4, 0],\n    [0, -6, 4],\n    [0, 6, -4],\n    [6, -4, 0],\n    [6, 0, -4],\n]\n\naxesactive = tuple(\n    [\n        list(active)\n        for active in set(\n            [  # GaAs 1\n                (-1, 1, 1),\n                (-1, -1, 1),\n                (1, -1, 1),\n                (-2, -2, 0),\n                (2, -2, 0),\n                (2, 2, 0),\n                (-2, 2, 0),\n                (3, 1, 1),\n                (-3, -1, 1),\n                (-1, -3, 1),\n                (2, 2, 4),\n                (-2, 2, 4),\n                (-2, -2, 4),\n                (2, -2, 4),\n                (0, -4, 4),\n                (0, 4, 4),\n                (4, 0, 4),\n                (-4, 0, 4),\n            ]\n            + [  # GaAs 2\n                (0, 2, 2),\n                (2, -2, 0),\n                (-2, 0, 2),\n                (2, 2, 0),\n                (0, -2, 2),\n                (-2, 2, 0),\n                (2, 0, 2),\n                (-2, -2, 0),\n                (0, 4, 4),\n                (-4, 0, 4),\n                (4, 0, 4),\n                (0, -4, 4),\n                (-1, 3, 3),\n                (3, 1, 3),\n                (-1, -3, 3),\n                (1, 3, 3),\n                (-3, -1, 3),\n                (1, -3, 3),\n                (2, 0, 6),\n                (0, -2, 6),\n                (0, 2, 6),\n                (-2, 0, 6),\n            ]\n        )\n    ]\n)\n\n\ndef getpoints(axis, testpoints, E, a, N):\n    normaxis = np.linalg.norm(axis)\n    return np.where(\n        ne.evaluate(\n            \"abs(tp1*a1+tp2*a2+tp3*a3-c)<0.001\",\n            {\n                \"c\": (12398 * normaxis ** 2 / (E * 2 * a)),\n                \"tp1\": testpoints[:, 0],\n                \"tp2\": testpoints[:, 1],\n                \"tp3\": testpoints[:, 2],\n                \"a1\": axis[0],\n                \"a2\": axis[1],\n                \"a3\": axis[2],\n            },\n        ).reshape(N)\n    )\n\n\ndef residual(params, testpointsdet, axes):\n    r = Rotation.from_euler(\"xyz\", np.array((params[\"rot_x\"].value, params[\"rot_y\"].value, params[\"rot_z\"].value)))\n    testpoints = r.apply(testpointsdet + np.array((params[\"trans_x\"], params[\"trans_y\"], params[\"trans_z\"])), inverse=False)\n    testpoints = testpoints / np.linalg.norm(testpoints, axis=1)[:, None]\n    res = (np.dot(testpoints, axes.T)) / (np.linalg.norm(axes, axis=1)) ** 2 - params[\"c\"].value\n    res = np.take_along_axis(res, np.nanargmin(np.abs(res), axis=1)[:, None], 1)\n    return res\n\n\nclass Kossel(QMainWindow, kosselui.Ui_MainWindow):\n    def __init__(self):\n        super(self.__class__, self).__init__()\n        self.N0 = 1000\n        self.N1 = 1000\n\n        self.setupUi(self)\n        self.plotButton.clicked.connect(self.plot_data)\n        self.clearButton.clicked.connect(self.clear_data)\n        self.loadButton.clicked.connect(self.load_file)\n        self.peakButton.clicked.connect(self.find_peaks)\n\n        ## Not implemented\n        self.peakButton.setEnabled(False)\n        self.thresholdSlider.setEnabled(False)\n\n        self.saveButton.clicked.connect(self.save)\n        self.fitButton.clicked.connect(self.fit_data)\n        self.datasetCombo.currentTextChanged.connect(self.plot_bg)\n        self.removeBackgroundBox.stateChanged.connect(self.plot_bg)\n        self.data = np.zeros((self.N0, self.N1))\n        self.data[0, 0] = 1\n        self.data[-1, -1] = 1\n        self.inputfile = None\n        self.bgplot = self.plotarea.canvas.ax.matshow(self.data, vmin=0, vmax=1)\n        self.peaks = np.zeros((self.N0, self.N1))\n        self.peaks[:] = np.nan\n        self.peaksplot = self.plotarea.canvas.ax.matshow(self.peaks, vmin=0, vmax=1, cmap=\"gray\")\n        self.plotarea.canvas.ax.set_xlim(0, self.N1)\n        self.plotarea.canvas.ax.set_ylim(self.N0, 0)\n        self.plotarea.canvas.draw_idle()\n        self.rangeSlider.startValueChanged.connect(self.setclim)\n        self.rangeSlider.endValueChanged.connect(self.setclim)\n        self.redrawtimer = QTimer()\n        self.redrawtimer.setSingleShot(True)\n        self.redrawtimer.timeout.connect(self.plotarea.canvas.draw)\n        for i, ax in enumerate(axes):\n            label = np.array2string(np.array(ax), precision=0)\n            item = QListWidgetItem(label)\n            item.setData(1, ax)\n            self.reflexList.addItem(item)\n            if ax in axesactive:\n                item.setSelected(True)\n        for el in [\n            self.angleXSpin,\n            self.angleYSpin,\n            self.angleZSpin,\n            self.transXSpin,\n            self.transYSpin,\n            self.transZSpin,\n            self.energySpin,\n            self.latticeSpin,\n        ]:\n            el.valueChanged.connect(self.invalidate_plot)\n\n        self.plotpoints = {}\n        self.testpoints = None\n\n        def styles(i=0):\n            colors = (\n                \"#1f77b4\",\n                \"#aec7e8\",\n                \"#ff7f0e\",\n                \"#ffbb78\",\n                \"#2ca02c\",\n                \"#98df8a\",\n                \"#d62728\",\n                \"#ff9896\",\n                \"#9467bd\",\n                \"#c5b0d5\",\n                \"#8c564b\",\n                \"#c49c94\",\n                \"#e377c2\",\n                \"#f7b6d2\",\n                \"#7f7f7f\",\n                \"#c7c7c7\",\n                \"#bcbd22\",\n                \"#dbdb8d\",\n                \"#17becf\",\n                \"#9edae5\",\n            )\n            markers = (\".\", \"+\", \"x\")\n            while True:\n                yield colors[i % len(colors)], markers[(i // len(colors)) % len(markers)]\n                i += 1\n\n        self.sgen = styles()\n        self.inputfilename = None\n\n        self.plotarea.canvas.mpl_connect(\"motion_notify_event\", self.mpl_move)\n        self.plotarea.canvas.mpl_connect(\"button_release_event\", self.mpl_release)\n\n    def mpl_move(self, event):\n        if event.button == 1:\n            tmp = self.data[int(event.ydata) - 1 : int(event.ydata) + 2, int(event.xdata) - 1 : int(event.xdata) + 2]\n            m = tmp == tmp.max()\n            self.peaks[int(event.ydata) - 1 : int(event.ydata) + 2, int(event.xdata) - 1 : int(event.xdata) + 2][m] = 1\n        elif event.button == 3:\n            self.peaks[int(event.ydata) - 5 : int(event.ydata) + 5, int(event.xdata) - 5 : int(event.xdata) + 5] = np.nan\n\n    def mpl_release(self, event):\n        self.peaksplot.set_array(self.peaks)\n        self.plotarea.canvas.draw_idle()\n\n    def plot_bg(self):\n        if self.inputfile is not None:\n            data = np.array(self.inputfile[self.datasetCombo.currentText()])\n            if data.ndim == 2:\n                if self.removeBackgroundBox.isChecked():\n                    data = data - snd.grey_opening(data, structure=skm.disk(10))\n                data = data - np.nanmin(data)\n                data = data / np.nanmax(data)\n                self.data = data\n                self.bgplot.remove()\n                self.bgplot = self.plotarea.canvas.ax.matshow(self.data, vmin=0, vmax=1, zorder=0)\n                if data.shape[0] != self.N0 or data.shape[1] != self.N1:\n                    self.N0 = data.shape[0]\n                    self.N1 = data.shape[1]\n                    self.peaks = np.zeros((self.N0, self.N1))\n                    self.peaks[:] = np.nan\n                    self.peaksplot = self.plotarea.canvas.ax.matshow(self.peaks, vmin=0, vmax=1, cmap=\"gray\", zorder=1)\n                    self.invalidate_plot()\n                    self.plotarea.canvas.draw_idle()\n\n                self.plotarea.canvas.ax.set_xlim(0, self.N1)\n                self.plotarea.canvas.ax.set_ylim(self.N0, 0)\n\n        self.plotarea.canvas.draw_idle()\n\n    def save(self):\n        filename, _ = QFileDialog.getSaveFileName(self, \"save plot\", \"\", \"pdf (*.pdf)\")\n        if filename:\n            try:\n                self.plotarea.canvas.ax.get_figure().savefig(filename)\n            except Exception:\n                msg = QMessageBox()\n                msg.setIcon(QMessageBox.Critical)\n                msg.setText(\"Saving failed\")\n                msg.setWindowTitle(\"Error\")\n                retval = msg.exec_()\n\n    def setclim(self):\n        clim = np.array(self.rangeSlider.getRange()) / 100\n        self.bgplot.set_clim(clim)\n        self.redrawtimer.start(100)\n        # self.plotarea.canvas.draw_idle()\n\n    def invalidate_plot(self):\n        for label in self.plotpoints:\n            self.plotpoints[label][0] = None\n        self.testpoints = None\n\n    def load_file(self):\n        fname = QFileDialog.getOpenFileName(self, \"Open file\", \".\", \"h5 (*.h5 *.hdf5)\")\n        self.inputfileLabel.setText(os.path.split(fname[0])[1])\n        self.inputfilename = fname[0]\n        try:\n            if self.inputfile is not None:\n                self.inputfile.close()\n                self.inputfile = None\n            inputfile = h5py.File(fname[0], \"r\")\n            self.datasetCombo.clear()\n            self.datasetCombo.addItems(inputfile.keys())\n            self.inputfile = inputfile\n            self.plot_bg()\n        except Exception as e:\n            print(\"error opening file:\", e)\n\n    def fit_data(self):\n        x, y = np.where(~np.isnan(self.peaks))\n        testpointsdet = np.array((x, y, [0] * len(x))).T - np.array((self.N0 // 2, self.N1 // 2, 0))\n        fit_params = lmfit.Parameters()\n        fit_params.add(\n            \"rot_x\",\n            value=self.angleXSpin.value() / 180 * np.pi,\n            min=(self.angleXSpin.value() - 15) / 180 * np.pi,\n            max=(self.angleXSpin.value() + 15) / 180 * np.pi,\n            vary=not self.rotXFixBox.isChecked(),\n        )\n        fit_params.add(\n            \"rot_y\",\n            value=self.angleYSpin.value() / 180 * np.pi,\n            min=(self.angleYSpin.value() - 15) / 180 * np.pi,\n            max=(self.angleYSpin.value() + 15) / 180 * np.pi,\n            vary=not self.rotYFixBox.isChecked(),\n        )\n        fit_params.add(\n            \"rot_z\",\n            value=self.angleZSpin.value() / 180 * np.pi,\n            min=(self.angleZSpin.value() - 15) / 180 * np.pi,\n            max=(self.angleZSpin.value() + 15) / 180 * np.pi,\n            vary=not self.rotZFixBox.isChecked(),\n        )\n        fit_params.add(\n            \"trans_x\",\n            value=self.transXSpin.value(),\n            min=self.transXSpin.value() - 100,\n            max=self.transXSpin.value() + 100,\n            vary=not self.transXFixBox.isChecked(),\n        )\n        fit_params.add(\n            \"trans_y\",\n            value=self.transYSpin.value(),\n            min=self.transYSpin.value() - 100,\n            max=self.transYSpin.value() + 100,\n            vary=not self.transYFixBox.isChecked(),\n        )\n        fit_params.add(\n            \"trans_z\",\n            value=self.transZSpin.value(),\n            min=self.transZSpin.value() - 100,\n            max=self.transZSpin.value() + 100,\n            vary=not self.transZFixBox.isChecked(),\n        )\n        c = 12.398 / (self.energySpin.value() * 2 * self.latticeSpin.value())\n        fit_params.add(\"c\", value=c, min=0.8 * c, max=1.2 * c, vary=not self.latticeFixBox.isChecked())\n        axs = np.array([np.array(item.data(1)) for item in self.reflexList.selectedItems()])\n        minner = lmfit.Minimizer(residual, fit_params, fcn_args=(testpointsdet, axs))\n        result = minner.minimize(method=\"bfgs\")\n        print(lmfit.fit_report(result))\n        self.angleXSpin.setValue(result.params[\"rot_x\"] * 180 / np.pi)\n        self.angleYSpin.setValue(result.params[\"rot_y\"] * 180 / np.pi)\n        self.angleZSpin.setValue(result.params[\"rot_z\"] * 180 / np.pi)\n        self.transXSpin.setValue(result.params[\"trans_x\"])\n        self.transYSpin.setValue(result.params[\"trans_y\"])\n        self.transZSpin.setValue(result.params[\"trans_z\"])\n        self.latticeSpin.setValue(12.398 / (self.energySpin.value() * 2 * result.params[\"c\"]))\n\n    def plot_data(self):\n        if self.testpoints is None:\n            self.clear_data()\n            r = Rotation.from_euler(\"xyz\", np.array((self.angleXSpin.value(), self.angleYSpin.value(), self.angleZSpin.value())) / 180 * np.pi)\n            Y, X, Z = np.meshgrid(np.arange(-self.N1 // 2, self.N1 // 2, 1), np.arange(-self.N0 // 2, self.N0 // 2, 1), 0)\n            testpoints = np.array([m.ravel() for m in [X, Y, Z]]).T\n            testpoints = r.apply(testpoints + np.array((self.transXSpin.value(), self.transYSpin.value(), self.transZSpin.value())), inverse=False)\n            self.testpoints = testpoints / np.linalg.norm(testpoints, axis=1)[:, None]\n\n        E = self.energySpin.value() * 1000\n        a = self.latticeSpin.value()\n\n        items = self.reflexList.selectedItems()\n        selectedlabels = [item.data(0) for item in items]\n        for label, item in self.plotpoints.items():\n            if label not in selectedlabels:\n                if item[1] is not None:\n                    item[1].remove()\n                    item[1] = None\n                if item[2] is not None:\n                    item[2].remove()\n                    item[2] = None\n\n        for k, item in enumerate(items):\n            ax = np.array(item.data(1), dtype=int)\n            label = np.array2string(ax, precision=0)\n            ax = ax.astype(float)\n            self.progressBar.setValue(int(k / len(items) * 100))\n            self.progressBar.update()\n            QApplication.processEvents()\n            if label in self.plotpoints and self.plotpoints[label][0] is not None:\n                continue\n            points = getpoints(ax, testpoints=self.testpoints, E=E, a=a, N=(self.N0, self.N1))\n            self.plotpoints[label] = [points, None, None]\n\n        for label in selectedlabels:\n            points = self.plotpoints[label][0]\n\n            if len(points[0]) > 0:\n                s = next(self.sgen)\n                if self.plotpoints[label][1] is None:\n                    self.plotpoints[label][1] = self.plotarea.canvas.ax.scatter(points[1], points[0], label=label, c=s[0], s=1)\n\n                if self.plotpoints[label][2] is None:\n                    for j in range(15):\n                        i = np.random.choice(np.arange(0, len(points[0])))\n                        if 10 < points[0][i] < (self.N0 - 20) and 10 < points[1][i] < (self.N1 - 100):\n                            self.plotpoints[label][2] = self.plotarea.canvas.ax.text(points[1][i] + 5, points[0][i] + 5, s=label, c=s[0])\n                            break\n                    else:\n                        self.plotpoints[label][2] = self.plotarea.canvas.ax.text(\n                            np.clip(points[1][i] + 5, 20, self.N1 - 20), np.clip(points[0][i] + 5, 20, self.N0 - 100), s=label, c=s[0]\n                        )\n\n        self.plotarea.canvas.ax.set_xlim(0, self.N1)\n        self.plotarea.canvas.ax.set_ylim(self.N0, 0)\n        self.plotarea.canvas.draw_idle()\n\n    def clear_data(self):\n        for label in self.plotpoints:\n            if self.plotpoints[label][1] is not None:\n                self.plotpoints[label][1].remove()\n                self.plotpoints[label][1] = None\n\n            if self.plotpoints[label][2] is not None:\n                self.plotpoints[label][2].remove()\n                self.plotpoints[label][2] = None\n\n        self.plotarea.canvas.draw_idle()\n\n    def find_peaks(self):\n        if self.data is not None:\n            self.peaks[:] = np.nan\n            self.peaks[self.data > (self.thresholdSlider.value() / 100)] = 1\n            self.peaksplot.set_array(self.peaks)\n            self.plotarea.canvas.draw_idle()\n\n\ndef sigint_handler(*args):\n    sys.stderr.write(\"\\r\")\n    QApplication.quit()\n\n\nif __name__ == \"__main__\":\n    print('starting kossel')\n    signal.signal(signal.SIGINT, sigint_handler)\n    app = QApplication(sys.argv)\n    timer = QTimer()\n    timer.start(250)\n    timer.timeout.connect(lambda: None)\n    form = Kossel()\n    form.show()\n    r = app.exec_()\n    sys.exit(r)\n", "meta": {"hexsha": "506e9a917768b6d9f05a87cd0bf4a3a1e0ba253c", "size": 25172, "ext": "py", "lang": "Python", "max_stars_repo_path": "kossel/kossel.py", "max_stars_repo_name": "fzimmermann89/idi", "max_stars_repo_head_hexsha": "cf3108cffe2d9719e42ddef268998e79d941e190", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-22T16:18:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-22T16:18:00.000Z", "max_issues_repo_path": "kossel/kossel.py", "max_issues_repo_name": "fzimmermann89/idi", "max_issues_repo_head_hexsha": "cf3108cffe2d9719e42ddef268998e79d941e190", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-20T20:45:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-20T20:45:25.000Z", "max_forks_repo_path": "kossel/kossel.py", "max_forks_repo_name": "fzimmermann89/idi", "max_forks_repo_head_hexsha": "cf3108cffe2d9719e42ddef268998e79d941e190", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-22T16:24:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-22T16:24:51.000Z", "avg_line_length": 25.6595310907, "max_line_length": 147, "alphanum_fraction": 0.3962339107, "include": true, "reason": "import numpy,import scipy,from scipy,import numexpr", "num_tokens": 9692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.2974699363766585, "lm_q1q2_score": 0.16951403196023945}}
{"text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport numpy as np\nimport re\n\nfrom .libpyfeos import  _get_calc_limits, _initialize, _init_mat,\\\n       _get_eos_all,_get_eos, _get_mat_par, _get_crit_point,\\\n       _get_soft_shere_par, _get_energy_offsets, _delete_material\n\n\nfrom ..base import _pull_tables, TableBase, MaterialBase, GridBase\nfrom copy import deepcopy\n\n\navalable_tabs = np.unique([tab.format(s=spec) \\\n                for tab in ['P{s}_DT', 'U{s}_DT', 'S{s}_DT', 'A{s}_DT', 'Zfc_DT',\n                            'P{s}_DU{s}', 'T_DU{s}', 'S{s}_DU{s}', 'A{s}_DU{s}', 'Zfc_DU{s}']\\\n                for spec in ['t', 'iz', 'ec', 'e', 'ic']])\n\n# define a global global_table_handles variable\nif 'global_table_handles' not in globals():\n    global_table_handles = None\n\nclass FeosTable(TableBase):\n    _original_units = 'feos'\n\n    def __init__(self, _name, table_handle=None, options={},info={}, units='cgs'):\n        self._id = table_handle\n        self._name = _name\n        self._Nelements  = info['Nelements']\n        self.update(info)\n        super(FeosTable, self).__init__(_name, table_handle, options, units)\n        self.options = options\n\n    def _interpolate(self, X, Y, kind):\n        if type(X) in [float, int]:\n           X = np.array(X)\n           Y = np.array(Y)\n        if X.shape != Y.shape:\n            raise ValueError('X and Y arguments should be ndarrays of the same shape!')\n\n        init_shape = X.shape\n\n        Xvals = np.array(X.flatten(), dtype='float64')*self._X_convert\n        Yvals = np.array(Y.flatten(), dtype='float64')*self._Y_convert\n        Fvar, XY_vars =  self._name.split('_')\n        if XY_vars == 'DT':\n            if kind == 'F':\n                res = _get_eos_all(self._id, self._Nelements,\n                                          self.options['use_maxwell'], Xvals, Yvals)\n                fVals_f = res[Fvar]*self._F_convert\n\n                fVals = fVals_f.reshape(init_shape)\n                return fVals\n            else:\n                raise NotImplemented\n        else:\n            raise NotImplemented\n\n    def __getitem__(self, key):\n        \"\"\" Overwriting default dict's __getitem__ method \"\"\"\n        if key in ['abar', \"Mean_Atomic_Mass\"]:\n            return self['Atot']/self['Xtot']\n        if key in ['zbar', \"Mean_Atomic_Num\"]:\n            return self['Ztot']/self['Xtot']\n        if key == \"Normal_Density\": key = \"rho_ref\"\n        if key == \"Modulus\": key = \"bulk_mod_ref\"\n        if key == \"R_Array\": key = \"D_Array\"\n        if key == \"Exchange_Coeff\":\n            return 0.0\n        return super(FeosTable, self).__getitem__(key)\n\nclass FeosMaterial(MaterialBase):\n\n    _default_options = {'use_maxwell': True, 'use_softspheres': True,\n            'maxwell_temp_arr': None, 'max_materials': 1, 'debug': False,\n            'rho_grid': None, 'temp_grid': None,\n            'grid_subsample_default': 0, 'grid_kind': 'solid',\n            'interpolation_mode_inversed': 'linear', 'precalculate': True}\n    _backend = 'feos'\n    _original_units = 'feos'\n\n    def __init__(self, material=None, tables=['Pt_DT', 'Ut_DT'],\n        options={'use_maxwell': True, 'use_softspheres': True,\n            'maxwell_temp_arr': None, 'max_materials': 1, 'debug': False},\n            spec=['t'], units='cgs'):\n        \"\"\"\n        Parameters:\n        -----------\n         - material: int: 4 digit SESAME material ID\n         - tables: list: ['table1_id', 'table2_id', ..etc]\n         - options: dict: {'tableid_regexpr': {'opt1': optval}, etc}\n            For example {\".t_DT\": {'create_tzero': True}} would apply the\n            EOS_CREATE_TZERO option to both 'Pt_DT' and 'Ut_DT' tables. The\n            tableid_regexpr accepts regular expressions.\n            [see  help(re) for more details].\n\n        \"\"\"\n        self.options = self._validate_options(options)\n        opt = self.options\n\n        self.tables = _pull_tables(tables, spec, avalable_tabs)\n        self.material = int(material)\n\n        # making a global array to store table handles\n        # This makes sure that FEOS is only initalized once\n        global global_table_handles\n        if global_table_handles is None:\n            self._id = 1\n            _initialize(opt['max_materials'], int(opt['debug']))\n            global_table_handles = np.zeros(opt['max_materials'])\n        else:\n            for idx0, mat in enumerate(global_table_handles):\n                if not mat:\n                    self._id = idx0 + 1\n                    break\n            else:\n                raise ValueError('Could not allocate {0} material.\\n\\\n                    Please reinitialize all materials and increase the \"max_materials\" option!'.format(\n                    self.material))\n\n        global_table_handles[self._id-1] = self.material\n\n\n\n        self.info = self._get_info_init()\n\n        # default grid\n        default_grid = GridBase(self.info['rho_ref'], kind=opt['grid_kind'],\n                subsample_temp=opt['grid_subsample_default'],\n                subsample_rho=opt['grid_subsample_default'])\n\n        grid_units = self._set_units(units, 'Pt_DT')\n        if opt['rho_grid'] is None:\n            rho_grid = default_grid.rho_grid*grid_units.o2r('D', 'cgs', units)\n        else:\n            rho_grid = opt['rho_grid']\n\n        if opt['temp_grid'] is None:\n            temp_grid = default_grid.temp_grid*grid_units.o2r('T', 'cgs', units)\n        else:\n            temp_grid = opt['temp_grid']\n\n        self.info['T_Array'] = temp_grid\n        self.info['D_Array'] = rho_grid\n        temp_grid_feos = temp_grid*grid_units.o2r('T', units, 'feos')\n        rho_grid_feos = rho_grid*grid_units.o2r('D', units, 'feos')\n\n        self.info.update(self._get_info_final(temp_grid_feos))\n        if opt['precalculate']:\n            self.precalculated = self._precalculate_on_grid(rho_grid_feos,temp_grid_feos)\n            self.precalculated['D_Array'] = rho_grid_feos\n            self.precalculated['T_Array'] = temp_grid_feos\n        else:\n            self.precalculated = {}\n        for tab_idx, tab_key in enumerate(self.tables):\n           this_info = deepcopy(self.info)\n           if self.precalculated:\n               F_Array = self.precalculated[tab_key.split('_')[0]]*\\\n                        grid_units.o2r(tab_key[0], 'feos', units)\n               this_info['F_Array'] =  F_Array.T\n\n           setattr(self, tab_key,\n                FeosTable(tab_key,\n                            self._id,\n                            options=opt,\n                            info=this_info,\n                            units=units))\n        self._init_base()\n\n    def _precalculate_on_grid(self, rho_grid, temp_grid):\n        R, T = np.meshgrid(rho_grid, temp_grid, indexing='ij')\n        R_flat, T_flat = R.flatten(), T.flatten()\n        #res = self._Nelements\n        res_tmp = _get_eos_all(self._id, self._Nelements,\n                self.options['use_maxwell'], R_flat, T_flat)\n        res = {}\n\n        for key in res_tmp:\n            res[key] = res_tmp[key].reshape(R.shape)\n        return res\n\n\n\n    def _get_info_init(self):\n        \"\"\" We have to preinitialize the material just to get the rho_ref \"\"\"\n        opt = self.options\n        # preinitializint without Maxwell constructions to go faster\n        Nelements, N_maxwell_iso, Maxwell_temp_reliable = _init_mat(self._id,\n                self.material, False, False, \n                np.logspace(-4, 1, 100))\n\n        info  = {}\n        info.update(_get_mat_par(self._id, Nelements))\n        _delete_material(self._id)\n\n        return info\n\n    def _get_info_final(self, temp_grid):\n        \"\"\" We have to preinitialize the material just to get the density \"\"\"\n        opt = self.options\n        T_mask = temp_grid<100. # eV \n\n        Nelements, N_maxwell_iso, Maxwell_temp_reliable = _init_mat(self._id,\n                self.material, opt['use_maxwell'], opt['use_softspheres'],\n                temp_grid)\n\n        info  = {}\n        self._Nelements = Nelements\n        info['Nelements'] = Nelements\n        info['N_maxwell_iso'] = N_maxwell_iso\n        info['Maxwell_temp_reliable'] = Maxwell_temp_reliable\n        info.update(_get_mat_par(self._id, Nelements))\n        info.update(_get_energy_offsets(self._id))\n        if opt['use_maxwell']:\n            info.update(_get_crit_point(self._id))\n            if opt['use_softspheres']:\n                info.update(_get_soft_shere_par(self._id))\n\n        return info\n\n", "meta": {"hexsha": "56b73b408242cbe41c226df722da9f19f8dbff9d", "size": 8388, "ext": "py", "lang": "Python", "max_stars_repo_path": "eospac/feos/interface.py", "max_stars_repo_name": "luli/pyeospac", "max_stars_repo_head_hexsha": "bea5ad270885b6fefc197d587eafd944b0b4faee", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-03-23T01:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-19T10:52:05.000Z", "max_issues_repo_path": "eospac/feos/interface.py", "max_issues_repo_name": "luli/pyeospac", "max_issues_repo_head_hexsha": "bea5ad270885b6fefc197d587eafd944b0b4faee", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-10-20T16:18:18.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-20T16:23:22.000Z", "max_forks_repo_path": "eospac/feos/interface.py", "max_forks_repo_name": "luli/pyeospac", "max_forks_repo_head_hexsha": "bea5ad270885b6fefc197d587eafd944b0b4faee", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2015-12-17T14:29:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T07:44:42.000Z", "avg_line_length": 37.7837837838, "max_line_length": 103, "alphanum_fraction": 0.582141154, "include": true, "reason": "import numpy", "num_tokens": 2074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.16943947229111253}}
{"text": "#!/usr/bin/env python\n\nfrom __future__ import division, print_function\n\nimport sys, os\nimport copy\nimport numpy as np\nimport simtk.openmm as mm\nimport simtk.openmm.app as app\nimport simtk.unit as u\nimport parmed as pmd\nfrom parmed.openmm.reporters import NetCDFReporter\nfrom pymbar import mbar\nfrom openmm_surface_affinities_lib import *\nimport waterlib as wl\nfrom scipy import optimize\n\n#Given a topology and structure file, this script sets up a simulation of a solvated solute\n#(this code is for just in bulk!) and periodically kicks off NVE simulations from the NPT\n#configurations and temperatures. These NVE simulations are then used to assess dynamics, while\n#the trajectory in the NPT can be used to evaluate solute properties in the fully coupled \n#ensemble. The below script applies to bulk systems. \n\n\ndef normalExponential(t, A, Tau):\n  #A function to define a normal exponential for fitting decay of water residency in shells \n  return A*np.exp(-(t/Tau))\n\n\ndef stretchedExponential(t, A, Tau, B):\n  #A function to define a stretched exponential for fitting the dipole vector autocorrelation function\n  return A*np.exp(-(t/Tau)**B)\n\n\ndef doSimDynamics(top, systemRef, integratorRef, platform, prop, temperature, scalexy=False, inBulk=False, state=None, pos=None, vels=None, nSteps=10000000):\n  #Input a topology object, reference system, integrator, platform, platform properties, \n  #and optionally state file, positions, or velocities\n  #If state is specified including positions and velocities and pos and vels are not None, the \n  #positions and velocities from the provided state will be overwritten\n  #Does NPT, stopping periodically to run NVE to compute dynamics\n  #Only the NPT simulation will be saved, not the NVE \n\n  #Copy the reference system and integrator objects\n  system = copy.deepcopy(systemRef)\n  integrator = copy.deepcopy(integratorRef)\n\n  #For NPT, add the barostat as a force\n  #If not in bulk, use anisotropic barostat\n  if not inBulk:\n    system.addForce(mm.MonteCarloAnisotropicBarostat((1.0, 1.0, 1.0)*u.bar,\n                                                     temperature, #Temperature should be SAME as for thermostat\n                                                     scalexy, #Set with flag for flexibility\n                                                     scalexy,\n                                                     True, #Only scale in z-direction\n                                                     250 #Time-steps between MC moves\n                                                    )\n    )\n  #If in bulk, have to use isotropic barostat to avoid any weird effects with box changing dimensions\n  else:\n    system.addForce(mm.MonteCarloBarostat(1.0*u.bar,\n                                          temperature,\n                                          250\n                                         )\n    )\n\n  #Create new simulation object for NPT simulation\n  sim = app.Simulation(top.topology, system, integrator, platform, prop, state)\n\n  #Also create copies and simulation object for the NVE we will be running\n  systemNVE = copy.deepcopy(systemRef)\n  integratorNVE = mm.VerletIntegrator(2.0*u.femtoseconds)\n  integratorNVE.setConstraintTolerance(1.0E-08)\n  simNVE = app.Simulation(top.topology, systemNVE, integratorNVE, platform, prop)\n\n  #Set the particle positions in the NPT simulation\n  if pos is not None:\n    sim.context.setPositions(pos)\n\n  #Apply constraints before starting the simulation\n  sim.context.applyConstraints(1.0E-08)\n\n  #Check starting energy decomposition if want\n  #decompEnergy(sim.system, sim.context.getState(getPositions=True))\n\n  #Initialize velocities if not specified\n  if vels is not None:\n    sim.context.setVelocities(vels)\n  else:\n    try:\n      testvel = sim.context.getState(getVelocities=True).getVelocities()\n      print(\"Velocities included in state, starting with 1st particle: %s\"%str(testvel[0]))\n      #If all the velocities are zero, then set them to the temperature\n      if not np.any(testvel.value_in_unit(u.nanometer/u.picosecond)):\n        print(\"Had velocities, but they were all zero, so setting based on temperature.\")\n        sim.context.setVelocitiesToTemperature(temperature)\n    except:\n      print(\"Could not find velocities, setting with temperature\")\n      sim.context.setVelocitiesToTemperature(temperature)\n\n  #Set up the reporter to output energies, volume, etc.\n  sim.reporters.append(app.StateDataReporter(\n                                             'prod_out.txt', #Where to write - can be stdout or file name (default .csv, I prefer .txt)\n                                             500, #Number of steps between writes\n                                             step=True, #Write step number\n                                             time=True, #Write simulation time\n                                             potentialEnergy=True, #Write potential energy\n                                             kineticEnergy=True, #Write kinetic energy\n                                             totalEnergy=True, #Write total energy\n                                             temperature=True, #Write temperature\n                                             volume=True, #Write volume\n                                             density=False, #Write density\n                                             speed=True, #Estimate of simulation speed\n                                             separator='  ' #Default is comma, but can change if want (I like spaces)\n                                            )\n  )\n\n  #Set up reporter for printing coordinates (trajectory)\n  sim.reporters.append(NetCDFReporter(\n                                      'prod.nc', #File name to write trajectory to\n                                      500, #Number of steps between writes\n                                      crds=True, #Write coordinates\n                                      vels=True, #Write velocities\n                                      frcs=False #Write forces\n                                     )\n  )\n\n  #Identify solute indices and water oxygen indices\n  soluteInds = []\n  owInds = []\n  hw1Inds = []\n  hw2Inds = []\n  for res in top.residues:\n    if res.name not in ['OTM', 'CTM', 'STM', 'NTM', 'SOL']:\n      for atom in res.atoms:\n        soluteInds.append(atom.idx)\n    elif res.name == 'SOL':\n      for atom in res.atoms:\n        if atom.name == 'OW':\n          owInds.append(atom.idx)\n        elif atom.name == 'HW1':\n          hw1Inds.append(atom.idx)\n        elif atom.name == 'HW2':\n          hw2Inds.append(atom.idx)\n\n  print(\"Solute indices:\")\n  print(soluteInds)\n  #print(\"Water oxygen indices:\")\n  #print(owInds)\n  #print(\"Water hydrogen (1st) indices:\")\n  #print(hw1Inds)\n  #print(\"Water hydrogen (2nd) indices:\")\n  #print(hw2Inds)\n\n  #Define cutoffs for solute solvation shells\n  solShell1Cut = 0.55 #nanometers from all solute atoms (including hydrogens)\n  solShell2Cut = 0.85\n\n  #Create array to store the dynamic information of interest every 0.2 ps (100 steps) for 50 ps\n  calcSteps = 100\n  calcTotSteps = 25000\n  numWats = np.zeros((int(calcTotSteps/calcSteps)+1, 2)) #Number waters that started in shell that are in shell at later time\n  dipCorrs = np.zeros((int(calcTotSteps/calcSteps)+1, 2)) #Dipole correlation in both solute shells\n\n  #Start running dynamics\n  print(\"\\nRunning NPT simulation with interspersed NVE to find dynamics...\")\n  sim.context.setTime(0.0)\n\n  stepChunk = 5000 #Run NVE for 50 ps to find dynamics every 10 ps\n  countSteps = 0\n  \n  while countSteps < nSteps:\n  \n    countSteps += stepChunk\n    sim.step(stepChunk)\n\n    #Record the simulation state so can kick off the NVE simulation\n    thisState = sim.context.getState(getPositions=True, getVelocities=True)\n\n    #Get solute and water oxygen coordinates after wrapping around the solute\n    coords = thisState.getPositions(asNumpy=True)\n    boxDims = np.diagonal(thisState.getPeriodicBoxVectors(asNumpy=True))\n    wrapCOM = np.average(coords[soluteInds], axis=0)\n    coords = wl.reimage(coords, wrapCOM, boxDims) - wrapCOM\n    solCoords = coords[soluteInds]\n    owCoords = coords[owInds]\n    hw1Coords = coords[hw1Inds]\n    hw2Coords = coords[hw2Inds]\n\n    #Figure out which waters are in the solute solvation shells\n    shell1BoolMat = wl.nearneighbors(solCoords, owCoords, boxDims, 0.0, solShell1Cut)\n    shell1Bool = np.array(np.sum(shell1BoolMat, axis=0), dtype=bool)\n    shell2BoolMat = wl.nearneighbors(solCoords, owCoords, boxDims, solShell1Cut, solShell2Cut)\n    shell2Bool = np.array(np.sum(shell2BoolMat, axis=0), dtype=bool)\n\n    #Count number of waters in each shell (will need for averaging)\n    thisCount1 = int(np.sum(shell1Bool))\n    thisCount2 = int(np.sum(shell2Bool))\n\n    #print(\"Found %i waters in shell1\"%thisCount1)\n    #print(\"Found %i waters in shell2\"%thisCount2)\n\n    #Loop over waters in shells and compute dipole vectors as references\n    refDipoles1 = np.zeros((thisCount1, 3))\n    refDipoles2 = np.zeros((thisCount2, 3))\n    for k, pos in enumerate(owCoords[shell1Bool]):\n      thisOHvecs = wl.reimage([hw1Coords[shell1Bool][k], hw2Coords[shell1Bool][k]], pos, boxDims) - pos\n      thisDip = -0.5*(thisOHvecs[0] + thisOHvecs[1])\n      refDipoles1[k] = thisDip / np.linalg.norm(thisDip)\n    for k, pos in enumerate(owCoords[shell2Bool]):\n      thisOHvecs = wl.reimage([hw1Coords[shell2Bool][k], hw2Coords[shell2Bool][k]], pos, boxDims) - pos\n      thisDip = -0.5*(thisOHvecs[0] + thisOHvecs[1])\n      refDipoles2[k] = thisDip / np.linalg.norm(thisDip)\n\n    #Set up the NVE simulation\n    simNVE.context.setState(thisState)\n    simNVE.context.setTime(0.0)\n\n    #Loop over taking steps to computed dynamics\n    countStepsNVE = 0\n    while countStepsNVE <= calcTotSteps:\n      calcState = simNVE.context.getState(getPositions=True)\n      #Get solute and water oxygen coordinates after wrapping around the solute\n      coords = calcState.getPositions(asNumpy=True)\n      wrapCOM = np.average(coords[soluteInds], axis=0)\n      coords = wl.reimage(coords, wrapCOM, boxDims) - wrapCOM\n      solCoords = coords[soluteInds]\n      owCoords = coords[owInds]\n      hw1Coords = coords[hw1Inds]\n      hw2Coords = coords[hw2Inds]\n      #Count waters that started in each shell that are now in the shell at this time\n      #No absorbing boundaries\n      thisbool1Mat = wl.nearneighbors(solCoords, owCoords, boxDims, 0.0, solShell1Cut)\n      thisbool1 = np.array(np.sum(thisbool1Mat, axis=0), dtype=bool)\n      thisbool2Mat = wl.nearneighbors(solCoords, owCoords, boxDims, solShell1Cut, solShell2Cut)\n      thisbool2 = np.array(np.sum(thisbool2Mat, axis=0), dtype=bool)\n      numWats[int(countStepsNVE/calcSteps),0] += int(np.sum(thisbool1*shell1Bool))\n      numWats[int(countStepsNVE/calcSteps),1] += int(np.sum(thisbool2*shell2Bool))\n      #Loop over waters in shells and compute dipole vectors for this configuration\n      #Adding to sum that we will normalize to find average at each time point\n      for k, pos in enumerate(owCoords[shell1Bool]):\n        thisOHvecs = wl.reimage([hw1Coords[shell1Bool][k], hw2Coords[shell1Bool][k]], pos, boxDims) - pos\n        thisDip = -0.5*(thisOHvecs[0] + thisOHvecs[1])\n        thisDip /= np.linalg.norm(thisDip)\n        dipCorrs[int(countStepsNVE/calcSteps),0] += (np.dot(thisDip, refDipoles1[k]) / float(thisCount1))\n      for k, pos in enumerate(owCoords[shell2Bool]):\n        thisOHvecs = wl.reimage([hw1Coords[shell2Bool][k], hw2Coords[shell2Bool][k]], pos, boxDims) - pos\n        thisDip = -0.5*(thisOHvecs[0] + thisOHvecs[1])\n        thisDip /= np.linalg.norm(thisDip)\n        dipCorrs[int(countStepsNVE/calcSteps),1] += (np.dot(thisDip, refDipoles2[k]) / float(thisCount2))\n      simNVE.step(calcSteps)\n      countStepsNVE += calcSteps\n\n  #Finish normalizing dipole correlations (really cosine of angle between dipole vector at different times)\n  numWats /= float(int(nSteps/stepChunk))\n  dipCorrs /= float(int(nSteps/stepChunk))\n  print(\"Normalizing factor for finding averages: %f\"%float(int(nSteps/stepChunk)))\n\n  #And save the final state of the NPT simulation in case we want to extend it\n  sim.saveState('nptDynamicsState.xml')\n\n  #And return the dipole correlations and times at which they were computed\n  timeVals = 0.002*np.arange(0.0, calcTotSteps+0.0001, calcSteps)\n\n  return numWats, dipCorrs, timeVals\n\n\ndef main(args):\n  #Get the structure and topology files from the command line\n  #ParmEd accepts a wide range of file types (Amber, GROMACS, CHARMM, OpenMM... but not LAMMPS) \n  try:\n    topFile = args[0]\n    strucFile = args[1]\n  except IndexError:\n    print(\"Specify topology and structure files from the command line.\")\n    sys.exit(2)\n  \n  print(\"Using topology file: %s\" % topFile)\n  print(\"Using structure file: %s\" % strucFile)\n  \n  print(\"\\nSetting up system...\")\n  \n  #Load in the files for initial simulations\n  top = pmd.load_file(topFile)\n  struc = pmd.load_file(strucFile)\n  \n  #Transfer unit cell information to topology object\n  top.box = struc.box[:]\n\n  #Set up some global features to use in all simulations\n  temperature = 298.15*u.kelvin\n  \n  #Define the platform (i.e. hardware and drivers) to use for running the simulation\n  #This can be CUDA, OpenCL, CPU, or Reference \n  #CUDA is for NVIDIA GPUs\n  #OpenCL is for CPUs or GPUs, but must be used for old CPUs (not SSE4.1 compatible)\n  #CPU only allows single precision (CUDA and OpenCL allow single, mixed, or double)\n  #Reference is a clear, stable reference for other code development and is very slow, using double precision by default\n  platform = mm.Platform.getPlatformByName('CUDA')\n  prop = {#'Threads': '2', #number of threads for CPU - all definitions must be strings (I think)\n          'Precision': 'mixed', #for CUDA or OpenCL, select the precision (single, mixed, or double)\n          'DeviceIndex': '0', #selects which GPUs to use - set this to zero if using CUDA_VISIBLE_DEVICES\n          'DeterministicForces': 'True' #Makes sure forces with CUDA and PME are deterministic\n         }\n  \n  #Create the OpenMM system that can be used as a reference\n  systemRef = top.createSystem(\n                               nonbondedMethod=app.PME, #Uses PME for long-range electrostatics, simple cut-off for LJ\n                               nonbondedCutoff=12.0*u.angstroms, #Defines cut-off for non-bonded interactions\n                               rigidWater=True, #Use rigid water molecules\n                               constraints=app.HBonds, #Constrains all bonds involving hydrogens\n                               flexibleConstraints=False, #Whether to include energies for constrained DOFs\n                               removeCMMotion=True, #Whether or not to remove COM motion (don't want to if part of system frozen)\n  )\n\n  #Set up the integrator to use as a reference\n  integratorRef = mm.LangevinIntegrator(\n                                        temperature, #Temperature for Langevin\n                                        1.0/u.picoseconds, #Friction coefficient\n                                        2.0*u.femtoseconds, #Integration timestep\n  )\n  integratorRef.setConstraintTolerance(1.0E-08)\n\n  #Get solute atoms \n  soluteIndices = []\n  for res in top.residues:\n    if res.name not in ['OTM', 'CTM', 'STM', 'NTM', 'SOL']:\n      for atom in res.atoms:\n        soluteIndices.append(atom.idx)\n\n  print(\"\\nSolute indices: %s\" % str(soluteIndices))\n\n  #JUST for boric acid, add a custom bonded force\n  #Couldn't find a nice, compatible force field, but did find A forcefield, so using it\n  #But has no angle terms on O-B-O and instead a weird bond repulsion term\n  #This term also prevents out of plane bending\n  #Simple in our case because boric acid is symmetric, so only need one parameter\n  #Parameters come from Otkidach and Pletnev, 2001\n  #Here, Ad = (A^2) / (d^6) since Ai and Aj and di and dj are all the same\n  #In the original paper, B-OH bond had A = 1.72 and d = 0.354\n  #Note that d is dimensionless and A should have units of (Angstrom^3)*(kcal/mol)^(1/2)\n  #These units are inferred just to make things work out with kcal/mol and the given distance dependence\n  bondRepulsionFunction = 'Ad*(1.0/r)^6'\n  BondRepulsionForce = mm.CustomBondForce(bondRepulsionFunction)\n  BondRepulsionForce.addPerBondParameter('Ad') #Units are technically kJ/mol * nm^6\n  baOxInds = []\n  for aind in soluteIndices:\n    if top.atoms[aind].type == 'oh':\n      baOxInds.append(aind)\n  for i in range(len(baOxInds)):\n    for j in range(i+1, len(baOxInds)):\n      BondRepulsionForce.addBond(baOxInds[i], baOxInds[j], [0.006289686]) \n\n  systemRef.addForce(BondRepulsionForce)\n\n  #Setting up the alchemical system so we can repeat the calculation with a decoupled particle\n  #We need to add a custom non-bonded force for the solute being alchemically changed\n  #Will be helpful to have handle on non-bonded force handling LJ and coulombic interactions\n  NBForce = None\n  for frc in systemRef.getForces():\n    if (isinstance(frc, mm.NonbondedForce)):\n      NBForce = frc\n\n  #Turn off dispersion correction since have interface\n  NBForce.setUseDispersionCorrection(False)\n\n  forceLabelsRef = getForceLabels(systemRef)\n\n  decompEnergy(systemRef, struc.positions, labels=forceLabelsRef)\n\n  #Separate out alchemical and regular particles using set objects\n  alchemicalParticles = set(soluteIndices)\n  chemicalParticles = set(range(systemRef.getNumParticles())) - alchemicalParticles\n\n  #Define the soft-core function for turning on/off LJ interactions\n  #In energy expressions for CustomNonbondedForce, r is a special variable and refers to the distance between particles\n  #All other variables must be defined somewhere in the function.\n  #The exception are variables like sigma1 and sigma2.\n  #It is understood that a parameter will be added called 'sigma' and that the '1' and '2' are to specify the combining rule.\n  softCoreFunction = '4.0*lambdaLJ*epsilon*x*(x-1.0); x = (1.0/reff_sterics);'\n  softCoreFunction += 'reff_sterics = (0.5*(1.0-lambdaLJ) + ((r/sigma)^6));'\n  softCoreFunction += 'sigma=0.5*(sigma1+sigma2); epsilon = sqrt(epsilon1*epsilon2)'\n  #Define the system force for this function and its parameters\n  SoftCoreForce = mm.CustomNonbondedForce(softCoreFunction)\n  SoftCoreForce.addGlobalParameter('lambdaLJ', 1.0) #Throughout, should follow convention that lambdaLJ=1.0 is fully-interacting state\n  SoftCoreForce.addPerParticleParameter('sigma')\n  SoftCoreForce.addPerParticleParameter('epsilon')\n\n  #Will turn off electrostatics completely in the original non-bonded force\n  #In the end-state, only want electrostatics inside the alchemical molecule\n  #To do this, just turn ON a custom force as we turn OFF electrostatics in the original force\n  ONE_4PI_EPS0 = 138.935456 #in kJ/mol nm/e^2\n  soluteCoulFunction = '(1.0-(lambdaQ^2))*ONE_4PI_EPS0*charge/r;'\n  soluteCoulFunction += 'ONE_4PI_EPS0 = %.16e;' % (ONE_4PI_EPS0)\n  soluteCoulFunction += 'charge = charge1*charge2'\n  SoluteCoulForce = mm.CustomNonbondedForce(soluteCoulFunction)\n  #Note this lambdaQ will be different than for soft core (it's also named differently, which is CRITICAL)\n  #This lambdaQ corresponds to the lambda that scales the charges to zero\n  #To turn on this custom force at the same rate, need to multiply by (1.0-lambdaQ**2), which we do\n  SoluteCoulForce.addGlobalParameter('lambdaQ', 1.0) \n  SoluteCoulForce.addPerParticleParameter('charge')\n\n  #Also create custom force for intramolecular alchemical LJ interactions\n  #Could include with electrostatics, but nice to break up\n  #We could also do this with a separate NonbondedForce object, but it would be a little more work, actually\n  soluteLJFunction = '4.0*epsilon*x*(x-1.0); x = (sigma/r)^6;'\n  soluteLJFunction += 'sigma=0.5*(sigma1+sigma2); epsilon=sqrt(epsilon1*epsilon2)'\n  SoluteLJForce = mm.CustomNonbondedForce(soluteLJFunction)\n  SoluteLJForce.addPerParticleParameter('sigma')\n  SoluteLJForce.addPerParticleParameter('epsilon')\n  \n  #Loop over all particles and add to custom forces\n  #As we go, will also collect full charges on the solute particles\n  #AND we will set up the solute-solute interaction forces\n  alchemicalCharges = [[0]]*len(soluteIndices)\n  for ind in range(systemRef.getNumParticles()):\n    #Get current parameters in non-bonded force\n    [charge, sigma, epsilon] = NBForce.getParticleParameters(ind)\n    #Make sure that sigma is not set to zero! Fine for some ways of writing LJ energy, but NOT OK for soft-core!\n    if sigma/u.nanometer == 0.0:\n      newsigma = 0.3*u.nanometer #This 0.3 is what's used by GROMACS as a default value for sc-sigma\n    else:\n      newsigma = sigma\n    #Add the particle to the soft-core force (do for ALL particles)\n    SoftCoreForce.addParticle([newsigma, epsilon])\n    #Also add the particle to the solute only forces\n    SoluteCoulForce.addParticle([charge])\n    SoluteLJForce.addParticle([sigma, epsilon])\n    #If the particle is in the alchemical molecule, need to set it's LJ interactions to zero in original force\n    if ind in soluteIndices:\n      NBForce.setParticleParameters(ind, charge, sigma, epsilon*0.0)\n      #And keep track of full charge so we can scale it right by lambda\n      alchemicalCharges[soluteIndices.index(ind)] = charge\n\n  #Now we need to handle exceptions carefully\n  for ind in range(NBForce.getNumExceptions()):\n    [p1, p2, excCharge, excSig, excEps] = NBForce.getExceptionParameters(ind)\n    #For consistency, must add exclusions where we have exceptions for custom forces\n    SoftCoreForce.addExclusion(p1, p2)\n    SoluteCoulForce.addExclusion(p1, p2)\n    SoluteLJForce.addExclusion(p1, p2)\n\n  #Only compute interactions between the alchemical and other particles for the soft-core force\n  SoftCoreForce.addInteractionGroup(alchemicalParticles, chemicalParticles)\n\n  #And only compute alchemical/alchemical interactions for other custom forces\n  SoluteCoulForce.addInteractionGroup(alchemicalParticles, alchemicalParticles)\n  SoluteLJForce.addInteractionGroup(alchemicalParticles, alchemicalParticles)\n\n  #Set other soft-core parameters as needed\n  SoftCoreForce.setCutoffDistance(12.0*u.angstroms)\n  SoftCoreForce.setNonbondedMethod(mm.CustomNonbondedForce.CutoffPeriodic)\n  SoftCoreForce.setUseLongRangeCorrection(False) \n  systemRef.addForce(SoftCoreForce)\n\n  #Set other parameters as needed - note that for the solute force would like to set no cutoff\n  #However, OpenMM won't allow a bunch of potentials with cutoffs then one without...\n  #So as long as the solute is smaller than the cut-off, won't have any problems!\n  SoluteCoulForce.setCutoffDistance(12.0*u.angstroms)\n  SoluteCoulForce.setNonbondedMethod(mm.CustomNonbondedForce.CutoffPeriodic)\n  SoluteCoulForce.setUseLongRangeCorrection(False) \n  systemRef.addForce(SoluteCoulForce)\n\n  SoluteLJForce.setCutoffDistance(12.0*u.angstroms)\n  SoluteLJForce.setNonbondedMethod(mm.CustomNonbondedForce.CutoffPeriodic)\n  SoluteLJForce.setUseLongRangeCorrection(False) \n  systemRef.addForce(SoluteLJForce)\n\n  #First do simulation with fully coupled state\n  SoftCoreForce.setGlobalParameterDefaultValue(0, 1.0)\n  SoluteCoulForce.setGlobalParameterDefaultValue(0, 1.0)\n\n  for k, ind in enumerate(soluteIndices):\n    [charge, sig, eps] = NBForce.getParticleParameters(ind)\n    NBForce.setParticleParameters(ind, alchemicalCharges[k]*1.0, sig, eps)\n\n  forceLabelsRef = getForceLabels(systemRef)\n  decompEnergy(systemRef, struc.positions, labels=forceLabelsRef)\n\n  os.mkdir('coupled')\n  os.chdir('coupled')\n\n  #Do NVT simulation\n  stateFileNVT, stateNVT = doSimNVT(top, systemRef, integratorRef, platform, prop, temperature, pos=struc.positions)\n\n  #And do NPT simulation using state information from NVT\n  stateFileNPT, stateNPT = doSimNPT(top, systemRef, integratorRef, platform, prop, temperature, inBulk=True, state=stateFileNVT)\n\n  #Now perform dynamics simulation to get dynamics - this is defined here, NOT in openmm_surface_affinities_lib.py\n  numShellWaters, dipoleCosAng, timePoints = doSimDynamics(top, systemRef, integratorRef, platform, prop, temperature, inBulk=True, state=stateFileNPT)\n\n  #Finally, want to now save the water residency over time and then also fit to exponential decay\n  np.savetxt(\"shell_watCounts_coupled.txt\", np.hstack((np.array([timePoints]).T, numShellWaters)),\n             header=\"Time (ps)  Number waters in the 1st and 2nd solvation shells\")\n\n  opt1, pcov1 = optimize.curve_fit(normalExponential, timePoints, numShellWaters[:,0]/numShellWaters[0,0])\n  decayTime1 = opt1[1]\n  opt2, pcov2 = optimize.curve_fit(normalExponential, timePoints, numShellWaters[:,1]/numShellWaters[0,1])\n  decayTime2 = opt2[1]\n\n  print(\"\\nIn the fully coupled ensemble:\")\n  print(\"\\tWater residency correlation time for 1st shell waters: %f\"%decayTime1)\n  print(\"\\tWater residency correlation time for 2nd shell waters: %f\"%decayTime2)\n\n  #Finally, want to now save the dipoles over time and then also fit to stretched exponential\n  np.savetxt(\"rotational_timeCorr_coupled.txt\", np.hstack((np.array([timePoints]).T, dipoleCosAng)),\n             header=\"Time (ps)  Cos(angle) between starting dipole and dipole for 1st and 2nd solvation shells\")\n\n  opt1, pcov1 = optimize.curve_fit(stretchedExponential, timePoints, dipoleCosAng[:,0])\n  decayTime1 = opt1[1]\n  opt2, pcov2 = optimize.curve_fit(stretchedExponential, timePoints, dipoleCosAng[:,1])\n  decayTime2 = opt2[1]\n\n  print(\"\\tRotational correlation time for 1st shell waters: %f\"%decayTime1)\n  print(\"\\tRotational correlation time for 2nd shell waters: %f\"%decayTime2)\n\n  os.chdir('../')\n\n  #Next simulate with decoupled state, but do same analysis\n  #At least this way the volumes considered will be similar\n  SoftCoreForce.setGlobalParameterDefaultValue(0, 0.0)\n  SoluteCoulForce.setGlobalParameterDefaultValue(0, 0.0)\n\n  for k, ind in enumerate(soluteIndices):\n    [charge, sig, eps] = NBForce.getParticleParameters(ind)\n    NBForce.setParticleParameters(ind, alchemicalCharges[k]*0.0, sig, eps)\n\n  forceLabelsRef = getForceLabels(systemRef)\n  decompEnergy(systemRef, struc.positions, labels=forceLabelsRef)\n\n  os.mkdir('decoupled')\n  os.chdir('decoupled')\n\n  #Do NVT simulation\n  stateFileNVT, stateNVT = doSimNVT(top, systemRef, integratorRef, platform, prop, temperature, pos=struc.positions)\n\n  #And do NPT simulation using state information from NVT\n  stateFileNPT, stateNPT = doSimNPT(top, systemRef, integratorRef, platform, prop, temperature, inBulk=True, state=stateFileNVT)\n\n  #Now perform dynamics simulation to get dynamics - this is defined here, NOT in openmm_surface_affinities_lib.py\n  numShellWaters, dipoleCosAng, timePoints = doSimDynamics(top, systemRef, integratorRef, platform, prop, temperature, inBulk=True, state=stateFileNPT)\n\n  #Finally, want to now save the water residency over time and then also fit to exponential decay\n  np.savetxt(\"shell_watCounts_decoupled.txt\", np.hstack((np.array([timePoints]).T, numShellWaters)),\n             header=\"Time (ps)  Number waters in the 1st and 2nd solvation shells\")\n\n  opt1, pcov1 = optimize.curve_fit(normalExponential, timePoints, numShellWaters[:,0]/numShellWaters[0,0])\n  decayTime1 = opt1[1]\n  opt2, pcov2 = optimize.curve_fit(normalExponential, timePoints, numShellWaters[:,1]/numShellWaters[0,1])\n  decayTime2 = opt2[1]\n\n  print(\"\\nIn the perfectly decoupled ensemble:\")\n  print(\"\\tWater residency correlation time for 1st shell waters: %f\"%decayTime1)\n  print(\"\\tWater residency correlation time for 2nd shell waters: %f\"%decayTime2)\n\n  #Finally, want to now save the dipoles over time and then also fit to stretched exponential\n  np.savetxt(\"rotational_timeCorr_decoupled.txt\", np.hstack((np.array([timePoints]).T, dipoleCosAng)),\n             header=\"Time (ps)  Cos(angle) between starting dipole and dipole for 1st and 2nd solvation shells\")\n\n  opt1, pcov1 = optimize.curve_fit(stretchedExponential, timePoints, dipoleCosAng[:,0])\n  decayTime1 = opt1[1]\n  opt2, pcov2 = optimize.curve_fit(stretchedExponential, timePoints, dipoleCosAng[:,1])\n  decayTime2 = opt2[1]\n\n  print(\"\\tRotational correlation time for 1st shell waters: %f\"%decayTime1)\n  print(\"\\tRotational correlation time for 2nd shell waters: %f\"%decayTime2)\n\n  os.chdir('../')\n\n\nif __name__ == \"__main__\":\n  main(sys.argv[1:])\n\n", "meta": {"hexsha": "9add1bafccf5ac52ea64243b7dba72df60801ea1", "size": 28150, "ext": "py", "lang": "Python", "max_stars_repo_path": "analysis_scripts/ba_get_dynamics_bulk.py", "max_stars_repo_name": "JIMonroe/Surface_Affinities_Optimization", "max_stars_repo_head_hexsha": "94853571c690b099362431aac32d26611134a009", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analysis_scripts/ba_get_dynamics_bulk.py", "max_issues_repo_name": "JIMonroe/Surface_Affinities_Optimization", "max_issues_repo_head_hexsha": "94853571c690b099362431aac32d26611134a009", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analysis_scripts/ba_get_dynamics_bulk.py", "max_forks_repo_name": "JIMonroe/Surface_Affinities_Optimization", "max_forks_repo_head_hexsha": "94853571c690b099362431aac32d26611134a009", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-07T11:52:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-07T11:52:27.000Z", "avg_line_length": 49.127399651, "max_line_length": 157, "alphanum_fraction": 0.7052220249, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.16943946553583702}}
{"text": "from typing import List\n\nimport matplotlib as mpl\nimport numpy as np\nfrom astropy import units as u\nfrom astropy.coordinates import CartesianRepresentation\nfrom matplotlib import pyplot as plt\n\nfrom poliastro.plotting.util import BODY_COLORS, generate_label\nfrom poliastro.util import norm\n\nfrom ._base import Trajectory\n\n\nclass StaticOrbitPlotter:\n    \"\"\"StaticOrbitPlotter class.\n\n    This class holds the perifocal plane of the first\n    :py:class:`~poliastro.twobody.orbit.Orbit` plotted in it using\n    :py:meth:`plot`, so all following\n    plots will be projected on that plane. Alternatively, you can call\n    :py:meth:`set_frame` to set the frame before plotting.\n\n    \"\"\"\n\n    def __init__(self, ax=None, num_points=150, dark=False):\n        \"\"\"Constructor.\n\n        Parameters\n        ----------\n        ax : ~matplotlib.axes.Axes\n            Axes in which to plot. If not given, new ones will be created.\n        num_points : int, optional\n            Number of points to use in plots, default to 150.\n        dark : bool, optional\n            If set as True, plots the orbit in Dark mode.\n        \"\"\"\n        self.ax = ax\n        if not self.ax:\n            if dark:\n                with plt.style.context(\"dark_background\"):\n                    _, self.ax = plt.subplots(figsize=(6, 6))\n            else:\n                _, self.ax = plt.subplots(figsize=(6, 6))\n        self.num_points = num_points\n        self._frame = None\n        self._attractor = None\n        self._attractor_radius = np.inf * u.km\n        self._trajectories = []  # type: List[Trajectory]\n\n    @property\n    def trajectories(self):\n        return self._trajectories\n\n    def set_frame(self, p_vec, q_vec, w_vec):\n        \"\"\"Sets perifocal frame.\n\n        Raises\n        ------\n        ValueError\n            If the vectors are not a set of mutually orthogonal unit vectors.\n        \"\"\"\n        if not np.allclose([norm(v) for v in (p_vec, q_vec, w_vec)], 1):\n            raise ValueError(\"Vectors must be unit.\")\n        elif not np.allclose([p_vec.dot(q_vec), q_vec.dot(w_vec), w_vec.dot(p_vec)], 0):\n            raise ValueError(\"Vectors must be mutually orthogonal.\")\n        else:\n            self._frame = p_vec, q_vec, w_vec\n\n        if self._trajectories:\n            self._redraw()\n\n    def _redraw(self):\n        for artist in self.ax.lines + self.ax.collections:\n            artist.remove()\n\n        for trajectory, state, label, color in self._trajectories:\n            self._plot(trajectory, state, label, color)\n\n        self.ax.relim()\n        self.ax.autoscale()\n\n    def _plot_trajectory(self, trajectory, color=None):\n        rr = trajectory.represent_as(CartesianRepresentation).xyz.transpose()\n        x, y = self._project(rr)\n        lines = self.ax.plot(x.to(u.km).value, y.to(u.km).value, \"--\", color=color)\n\n        return lines\n\n    def plot_trajectory(self, trajectory, *, label=None, color=None):\n        \"\"\"Plots a precomputed trajectory.\n\n        Parameters\n        ----------\n        trajectory : ~astropy.coordinates.BaseRepresentation, ~astropy.coordinates.BaseCoordinateFrame\n            Trajectory to plot.\n        label : str, optional\n            Label.\n        color : str, optional\n            Color string.\n\n        \"\"\"\n        if self._attractor is None or self._frame is None:\n            raise ValueError(\n                \"An attractor and a frame must be set up first, please use \"\n                \"set_attractor(Major_Body) and set_frame(*orbit.pqw()) \"\n                \"or plot(orbit).\"\n            )\n\n        self._redraw_attractor(\n            trajectory.represent_as(CartesianRepresentation).norm().min() * 0.15\n        )  # Arbitrary threshold\n        lines = self._plot_trajectory(trajectory, color)\n\n        if label:\n            lines[0].set_label(label)\n            self.ax.legend(\n                loc=\"upper left\", bbox_to_anchor=(1.05, 1.015), title=\"Names and epochs\"\n            )\n\n        self._trajectories.append(\n            Trajectory(trajectory, None, label, lines[0].get_color())\n        )\n\n        return lines\n\n    def set_attractor(self, attractor):\n        \"\"\"Sets plotting attractor.\n\n        Parameters\n        ----------\n        attractor : ~poliastro.bodies.Body\n            Central body.\n\n        \"\"\"\n        if self._attractor is None:\n            self._attractor = attractor\n\n        elif attractor is not self._attractor:\n            raise NotImplementedError(\n                \"Attractor has already been set to {}.\".format(self._attractor.name)\n            )\n\n    def _project(self, rr):\n        rr_proj = rr - rr.dot(self._frame[2])[:, None] * self._frame[2]\n        x = rr_proj.dot(self._frame[0])\n        y = rr_proj.dot(self._frame[1])\n        return x, y\n\n    def _redraw_attractor(self, min_radius=0 * u.km):\n        radius = max(self._attractor.R.to(u.km), min_radius.to(u.km))\n        color = BODY_COLORS.get(self._attractor.name, \"#999999\")\n\n        for attractor in self.ax.findobj(match=mpl.patches.Circle):\n            attractor.remove()\n\n        if radius < self._attractor_radius:\n            self._attractor_radius = radius\n\n        self.ax.add_patch(\n            mpl.patches.Circle((0, 0), self._attractor_radius.value, lw=0, color=color)\n        )\n\n    def _plot(self, trajectory, state=None, label=None, color=None):\n        lines = self._plot_trajectory(trajectory, color)\n\n        if state is not None:\n            x0, y0 = self._project(state[None])\n\n            # Plot current position\n            l, = self.ax.plot(\n                x0.to(u.km).value,\n                y0.to(u.km).value,\n                \"o\",\n                mew=0,\n                color=lines[0].get_color(),\n            )\n            lines.append(l)\n\n        if label:\n            if not self.ax.get_legend():\n                size = self.ax.figure.get_size_inches() + [8, 0]\n                self.ax.figure.set_size_inches(size)\n\n            # This will apply the label to either the point or the osculating\n            # orbit depending on the last plotted line\n            # NOTE: What about generating both labels,\n            # indicating that one is the osculating orbit?\n            lines[-1].set_label(label)\n            self.ax.legend(\n                loc=\"upper left\", bbox_to_anchor=(1.05, 1.015), title=\"Names and epochs\"\n            )\n\n        self.ax.set_xlabel(\"$x$ (km)\")\n        self.ax.set_ylabel(\"$y$ (km)\")\n        self.ax.set_aspect(1)\n\n        return lines\n\n    def plot(self, orbit, label=None, color=None):\n        \"\"\"Plots state and osculating orbit in their plane.\n        \"\"\"\n        if not self._frame:\n            self.set_frame(*orbit.pqw())\n\n        self.set_attractor(orbit.attractor)\n        self._redraw_attractor(orbit.r_p * 0.15)  # Arbitrary threshold\n        positions = orbit.sample(self.num_points)\n        if label:\n            label = generate_label(orbit, label)\n\n        lines = self._plot(positions, orbit.r, label, color)\n\n        self._trajectories.append(\n            Trajectory(positions, orbit.r, label, lines[0].get_color())\n        )\n        return lines\n", "meta": {"hexsha": "f7b6fda307056b6bbadce685326d3f406a6e8a87", "size": 7057, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/poliastro/plotting/static.py", "max_stars_repo_name": "WolfsSky/poliastro", "max_stars_repo_head_hexsha": "fc5e0825b110a0d6095b4b174e47624147ae1a29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/poliastro/plotting/static.py", "max_issues_repo_name": "WolfsSky/poliastro", "max_issues_repo_head_hexsha": "fc5e0825b110a0d6095b4b174e47624147ae1a29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/poliastro/plotting/static.py", "max_forks_repo_name": "WolfsSky/poliastro", "max_forks_repo_head_hexsha": "fc5e0825b110a0d6095b4b174e47624147ae1a29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.371559633, "max_line_length": 102, "alphanum_fraction": 0.5839591895, "include": true, "reason": "import numpy,from astropy", "num_tokens": 1629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3140505514119072, "lm_q1q2_score": 0.16926797765873286}}
{"text": "from typing import Dict, List, Union, Optional, Tuple\nfrom warnings import warn\nfrom pathlib import Path\nimport pandas as pd\nimport numpy as np\nfrom mendeleev import element\nfrom chemicalc.instruments import InstConfig\nfrom chemicalc.utils import (\n    doppler_shift,\n    convolve_spec,\n    calc_gradient,\n)\nfrom chemicalc.file_mgmt import (\n    data_dir,\n    download_package_files,\n    precomputed_res,\n    precomputed_ref_id,\n    precomputed_label_id,\n    precomputed_alpha_included,\n)\n\n# noinspection PyTypeChecker\nelements_included: List[str] = [x.symbol for x in element(list(range(3, 100)))]\n\"\"\"\nList[str]: List of all elements included in the pre-computed spectral grids.\n\"\"\"\nalpha_el: List[str] = [\"O\", \"Ne\", \"Mg\", \"Si\", \"S\", \"Ar\", \"Ca\", \"Ti\"]\n\"\"\"\nList[str]: List of elements considered when calculating bulk [:math:`\\\\alpha`/H].\n\"\"\"\n\n\nclass ReferenceSpectra:\n    \"\"\"\n    Object for spectra of a specific reference star\n\n    :param str reference: Name of reference star to load (e.g., 'RGB_m1.5')\n    :param str init_res: Initial resolution of high-res reference spectra.\n                         Only 300000 is presently included for default spectra.\n                         Can be approximate if using custom reference spectra.\n    :param bool scale_by_iron: If true, scales all elemental abundances by [Fe/H]\n    :param bool alpha_included: If true, will include an alpha label after the atmospheric parameters\n                                and before the other elements (i.e., between v_micro and Li)\n    :param \\**kwargs: see below\n\n    :keyword str ref_spec_file: Full path to file of reference spectra\n    :keyword str ref_label_file: Full path to file of reference spectra labels\n\n    :ivar Dict[Union[str,float],int] resolution: Dictionary of resolving powers for each instrument\n    :ivar ref_spec_file: Full path to file of reference spectra\n    :ivar ref_label_file: Full path to file of reference spectra labels\n    :ivar Dict[Union[str,float],np.ndarray] wavelength: Dictionary of wavelength arrays for each instrument\n    :ivar Dict[Union[str,float],np.ndarray] spectra: Dictionary of spectral grids for each instrument\n    :ivar pd.DataFrame labels: Labels corresponding to each spectrum in the grid\n    :ivar Dict[Union[str,float],pd.DataFrame] gradients: Dictionary of partial derivatives for each instrument\n    :ivar int nspectra: Number of spectra included in the grid\n    :ivar int nlabels: Number of labels included\n    \"\"\"\n\n    def __init__(\n        self,\n        reference: str,\n        init_res: float = precomputed_res[0],\n        scale_by_iron: bool = False,\n        alpha_included: bool = True,\n        **kwargs,\n    ) -> None:\n        if not isinstance(reference, str):\n            raise TypeError(\"reference must be str\")\n        if not isinstance(init_res, (int, float)):\n            raise TypeError(\"init_res must be float\")\n        self.reference = reference\n        self.resolution = {\"init\": init_res}\n\n        if \"ref_spec_file\" in kwargs:\n            self.ref_spec_file = Path(kwargs[\"ref_spec_file\"])\n            if not self.ref_spec_file.exists():\n                raise ValueError(f\"ref_spec_file {self.ref_spec_file} does not exist\")\n        else:\n            if not self.resolution[\"init\"] in precomputed_res:\n                raise ValueError(f\"{init_res} not a precomputed resolution\")\n            self.ref_spec_file = data_dir.joinpath(\n                f\"reference_spectra_{init_res:06}.h5\"\n            )\n            if not self.ref_spec_file.exists():\n                print(\n                    \"Downloading reference file---this may take a few minutes but is only necessary once\"\n                )\n                download_package_files(\n                    id_str=precomputed_ref_id[init_res], destination=self.ref_spec_file\n                )\n\n        if \"ref_label_file\" in kwargs:\n            self.ref_label_file = Path(kwargs[\"ref_label_file\"])\n            if not self.ref_label_file.exists():\n                raise ValueError(f\"ref_label_file {self.ref_label_file} does not exist\")\n        else:\n            self.ref_label_file = data_dir.joinpath(\"reference_labels.h5\")\n            if not self.ref_label_file.exists():\n                print(\n                    \"Downloading label_file---this should be quick and is only necessary once\"\n                )\n                download_package_files(\n                    id_str=precomputed_label_id, destination=self.ref_label_file\n                )\n            if alpha_included and reference not in precomputed_alpha_included:\n                raise ValueError(\n                    f\"alpha offsets not currently included for {reference}\"\n                )\n\n        ref_list_spec = list(\n            pd.DataFrame(pd.read_hdf(self.ref_spec_file, \"ref_list\")).values.flatten()\n        )\n        ref_list_label = list(\n            pd.DataFrame(pd.read_hdf(self.ref_label_file, \"ref_list\")).values.flatten()\n        )\n        if not (reference in ref_list_spec) and (reference in ref_list_label):\n            raise ValueError(\n                f\"{reference} is not included in ref_label_file and/or ref_spec_file\"\n            )\n\n        wave_df = pd.DataFrame(pd.read_hdf(self.ref_spec_file, \"highres_wavelength\"))\n        spec_df = pd.DataFrame(pd.read_hdf(self.ref_spec_file, reference))\n        label_df = pd.DataFrame(pd.read_hdf(self.ref_label_file, reference))\n        if scale_by_iron:\n            label_df.loc[set(elements_included) ^ {\"Fe\"}] -= label_df.loc[\"Fe\"]\n        if alpha_included:\n            label_df = pd.concat(\n                [\n                    label_df.iloc[:3],\n                    pd.DataFrame(label_df.loc[alpha_el].mean()).T,\n                    label_df.iloc[3:],\n                ]\n            )\n            label_df.index = [\"Teff\", \"logg\", \"v_micro\", \"alpha\"] + elements_included\n            if (\n                np.abs(\n                    label_df.loc[\"alpha\"][[4, 6, 7]].max() - label_df.loc[\"alpha\"][0]\n                )\n                < 0.001\n            ):\n                warn(\n                    \"Expected offset in alpha not found. Are you sure this reference spectra includes alpha gradients?\"\n                    + \"\\nIf so, they must come immediately after v_micro offsets in both the label and spectra files.\",\n                    UserWarning,\n                )\n        else:\n            label_df.index = [\"Teff\", \"logg\", \"v_micro\"] + elements_included\n\n        self.wavelength = dict(init=wave_df.to_numpy().T[0])\n        self.spectra = dict(init=spec_df.to_numpy().T)\n        self.labels = label_df\n        self.gradients: Dict[Union[str, float], pd.DataFrame] = {}\n\n        self.nspectra = self.spectra[\"init\"].shape[0]\n        self.nlabels = self.labels.shape[0]\n\n    def add_rv_spec(self, d_rv: float, symmetric: bool = True) -> None:\n        \"\"\"\n        Adds spectra and labels corresponding to a small doppler shift of the reference spectra.\n        Assumes that the first spectra in ref_spec_file is a reference w/ no offsets to any labels.\n\n        :param float d_rv: small doppler shift in km/s\n        :param bool symmetric: if True, applies both positive and negative doppler shifts\n        :return:\n        \"\"\"\n        warn(\n            \"This feature is experimental and has not been sufficiently tested on either computational or \"\n            \"statistical grounds!\",\n            UserWarning,\n        )\n        self.labels.loc[\"RV\"] = 0.0\n        self.labels[\"fffff\"] = self.labels[\"aaaaa\"]\n        self.labels.loc[\"RV\", \"fffff\"] += d_rv\n        tmp1 = doppler_shift(self.wavelength[\"init\"], self.spectra[\"init\"][0], d_rv)\n        self.spectra[\"init\"] = np.append(\n            self.spectra[\"init\"], tmp1[np.newaxis, :], axis=0\n        )\n        if symmetric:\n            self.labels[\"ggggg\"] = self.labels[\"aaaaa\"]\n            self.labels.loc[\"RV\", \"ggggg\"] -= d_rv\n            tmp2 = doppler_shift(\n                self.wavelength[\"init\"], self.spectra[\"init\"][0], -d_rv\n            )\n            self.spectra[\"init\"] = np.append(\n                self.spectra[\"init\"], tmp2[np.newaxis, :], axis=0\n            )\n\n    def convolve(self, instrument, name: Optional[str] = None) -> None:\n        \"\"\"\n        Convolves spectra to instrument resolution and samples onto instrument's wavelength grid\n\n        :param InstConfig instrument: Instrument object to convolve and sample spectra onto\n        :param str name: Name to give spectra. If None, defaults to name of instrument\n        :return:\n        \"\"\"\n        if name is None:\n            name = instrument.name\n        outwave = instrument.wave\n        self.spectra[name] = convolve_spec(\n            wave=self.wavelength[\"init\"],\n            spec=self.spectra[\"init\"],\n            resolution=instrument.R_res,\n            outwave=outwave,\n            res_in=self.resolution[\"init\"],\n        )\n        self.wavelength[name] = outwave\n        self.resolution[name] = instrument.R_res\n\n    def calc_gradient(\n        self,\n        name: Union[str, InstConfig],\n        symmetric: bool = True,\n        ref_included: bool = True,\n    ) -> None:\n        \"\"\"\n        Calculates gradients of the reference spectra with respect to each label.\n\n        :param Union[str,InstConfig] name: Name of convolved spectra to calculate gradient for.\n            Will also accept an InstConfig object and use InstConfig.name.\n        :param bool symmetric: If True, calculates symmetric gradient around reference labels\n        :param bool ref_included: If True, expects first spectra to be reference spectra w/ no offsets to any labels.\n                                  Required for symmetric=False.\n        :return:\n        \"\"\"\n        if isinstance(name, InstConfig):\n            name = name.name\n\n        self.gradients[name] = calc_gradient(\n            spectra=self.spectra[name],\n            labels=self.labels,\n            symmetric=symmetric,\n            ref_included=ref_included,\n        )\n        self.gradients[name].columns = self.wavelength[name]\n\n    def zero_gradients(\n        self, name: Union[str, InstConfig], labels: Union[str, List[str]]\n    ):\n        \"\"\"\n        Sets gradients of a spectrum to zero for the specified labels. This is equivalent to setting a delta-function\n        prior on those labels (i.e., holding them fixed).\n\n        :param Union[str,InstConfig] name: Name of spectra to apply gradient zeroing to.\n            Will also accept an InstConfig object and use InstConfig.name.\n        :param Union[str,List[str]] labels: List of labels for which to zero gradients\n        :return:\n        \"\"\"\n        if isinstance(name, InstConfig):\n            name = name.name\n        self.gradients[name].loc[labels] = 0\n\n    def mask_wavelength(\n        self, name: Union[str, InstConfig], regions: List[Tuple[float, float]]\n    ) -> None:\n        \"\"\"\n        Masks the information content of a spectrum by setting the gradient to zero within the bounds of the mask.\n        Can be used to mimic the masking of skylines, non-LTE lines, or detector gaps.\n\n        :param Union[str,InstConfig] name: Name of the spectra to apply  mask to\n        :param List[Tuple[float,float]] regions: List of wavelength bounds on the regions to mask.\n        :return:\n        \"\"\"\n        if isinstance(name, InstConfig):\n            name = name.name\n        if not isinstance(regions, list):\n            regions = [regions]\n        for region in regions:\n            min_wave, max_wave = region\n            mask = (self.wavelength[name] > min_wave) & (\n                self.wavelength[name] < max_wave\n            )\n            self.gradients[name].iloc[:, mask] = 0\n\n    def get_names(self) -> List[str]:\n        \"\"\"\n        Get names of all spectra contained in this object\n\n        :return List[str]: List of spectra names that this object contains.\n        \"\"\"\n        return list(self.spectra.keys())\n\n    def duplicate(self, name: str, new_name: str) -> None:\n        \"\"\"\n        Duplicates set of spectra/gradients\n\n        :param str name: Name of spectra to duplicate\n        :param str new_name: Name given to new spectra\n        :return:\n        \"\"\"\n        self.resolution[new_name] = self.resolution[name]\n        self.wavelength[new_name] = np.copy(self.wavelength[name])\n        self.spectra[new_name] = np.copy(self.spectra[name])\n        self.gradients[new_name] = pd.DataFrame.copy(self.gradients[name])\n\n    def reset(self) -> None:\n        \"\"\"\n        Resets object to only the initial high-res spectra\n\n        :return:\n        \"\"\"\n        init_resolution = self.resolution[\"init\"]\n        self.resolution.clear()\n        self.resolution[\"init\"] = init_resolution\n\n        init_wavelength = self.wavelength[\"init\"]\n        self.wavelength.clear()\n        self.wavelength[\"init\"] = init_wavelength\n\n        init_spectra = self.spectra[\"init\"]\n        self.spectra.clear()\n        self.spectra[\"init\"] = init_spectra\n        self.spectra[\"init\"] = init_spectra\n\n        del self.gradients\n        self.gradients = {}\n", "meta": {"hexsha": "14ac0b96413003a068d65317881dffc377ae219d", "size": 12953, "ext": "py", "lang": "Python", "max_stars_repo_path": "chemicalc/reference_spectra.py", "max_stars_repo_name": "NathanSandford/Chem-I-Calc", "max_stars_repo_head_hexsha": "34ec9b9e6c23a7d55f64b20de3b17547e1471dfd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-06-18T15:38:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-09T04:49:16.000Z", "max_issues_repo_path": "chemicalc/reference_spectra.py", "max_issues_repo_name": "NathanSandford/Chem-I-Calc", "max_issues_repo_head_hexsha": "34ec9b9e6c23a7d55f64b20de3b17547e1471dfd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2019-08-02T15:13:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-22T16:18:15.000Z", "max_forks_repo_path": "chemicalc/reference_spectra.py", "max_forks_repo_name": "NathanSandford/Chem-I-Calc", "max_forks_repo_head_hexsha": "34ec9b9e6c23a7d55f64b20de3b17547e1471dfd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-09-16T23:10:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T08:19:42.000Z", "avg_line_length": 40.8611987382, "max_line_length": 119, "alphanum_fraction": 0.6117501737, "include": true, "reason": "import numpy", "num_tokens": 2826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.16926797073808075}}
{"text": "#!/usr/bin/env python3\n\nimport sys\nimport math\nimport numpy as np\nimport glob\nimport scipy.optimize as optimization\nimport os\nfrom itertools import islice\nimport re\n\n#Bond Types\n# 1-16 -> SP\n# 17-32 -> PS\n# 33-36 -> SB\n# 37-38 -> BB-inter\n# 39-54 -> BB-intra\n\nWC = {\n    'A': 'T',\n    'C': 'G',\n    'G': 'C',\n    'T': 'A'\n}\n\ntypeBond = {\n    'SP/AA': 1,\n    'SP/AC': 2,\n    'SP/AG': 3,\n    'SP/AT': 4,\n    'SP/CA': 5,\n    'SP/CC': 6,\n    'SP/CG': 7,\n    'SP/CT': 8,\n    'SP/GA': 9,\n    'SP/GC': 10,\n    'SP/GG': 11,\n    'SP/GT': 12,\n    'SP/TA': 13,\n    'SP/TC': 14,\n    'SP/TG': 15,\n    'SP/TT': 16,\n    'PS/AA': 17,\n    'PS/AC': 18,\n    'PS/AG': 19,\n    'PS/AT': 20,\n    'PS/CA': 21,\n    'PS/CC': 22,\n    'PS/CG': 23,\n    'PS/CT': 24,\n    'PS/GA': 25,\n    'PS/GC': 26,\n    'PS/GG': 27,\n    'PS/GT': 28,\n    'PS/TA': 29,\n    'PS/TC': 30,\n    'PS/TG': 31,\n    'PS/TT': 32,\n    'SB/A': 33,\n    'SB/C': 34,\n    'SB/G': 35,\n    'SB/T': 36,\n    'BB-inter/AT': 37,\n    'BB-inter/CG': 38,\n    'BB-inter/GC': 38,\n    'BB-inter/TA': 37,\n    'BB-intra/AA': 39,\n    'BB-intra/AC': 40,\n    'BB-intra/AG': 41,\n    'BB-intra/AT': 42,\n    'BB-intra/CA': 43,\n    'BB-intra/CC': 44,\n    'BB-intra/CG': 45,\n    'BB-intra/CT': 46,\n    'BB-intra/GA': 47,\n    'BB-intra/GC': 48,\n    'BB-intra/GG': 49,\n    'BB-intra/GT': 50,\n    'BB-intra/TA': 51,\n    'BB-intra/TC': 52,\n    'BB-intra/TG': 53,\n    'BB-intra/TT': 54\n}\n\nkbond = {\n    1: 108.849600,\n    2: 116.093000,\n    3: 130.551200,\n    4: 134.298200,\n    5: 117.795600,\n    6: 158.718400,\n    7: 121.876200,\n    8: 150.068000,\n    9: 98.948800,\n    10: 82.660600,\n    11: 150.242600,\n    12: 109.797800,\n    13: 139.538000,\n    14: 147.736200,\n    15: 115.540000,\n    16: 159.897200,\n    17: 29.178200,\n    18: 30.063800,\n    19: 23.022000,\n    20: 31.743400,\n    21: 29.641600,\n    22: 38.022200,\n    23: 20.852400,\n    24: 37.382800,\n    25: 30.260400,\n    26: 38.421000,\n    27: 33.503600,\n    28: 34.214400,\n    29: 38.532200,\n    30: 39.623000,\n    31: 32.780400,\n    32: 47.345800,\n    33: 78.459400,\n    34: 89.029200,\n    35: 98.264400,\n    36: 90.502800,\n    37: 42.968000,\n    38: 71.908800,\n    39: 11.723300,\n    40: 16.033040,\n    41: 6.953480,\n    42: 37.138400,\n    43: 11.678180,\n    44: 4.556460,\n    45: 8.929340,\n    46: 8.008620,\n    47: 12.141360,\n    48: 19.043940,\n    49: 6.154040,\n    50: 26.376000,\n    51: 16.652460,\n    52: 5.911920,\n    53: 7.927460,\n    54: 9.313280\n}\n\nr0bond = {\n    1: 3.737680,\n    2: 3.739850,\n    3: 3.750370,\n    4: 3.747050,\n    5: 3.758460,\n    6: 3.765150,\n    7: 3.760470,\n    8: 3.751930,\n    9: 3.738060,\n    10: 3.707210,\n    11: 3.760770,\n    12: 3.741210,\n    13: 3.758390,\n    14: 3.763810,\n    15: 3.758300,\n    16: 3.755310,\n    17: 4.083580,\n    18: 4.070020,\n    19: 4.094660,\n    20: 4.115280,\n    21: 4.127790,\n    22: 4.169700,\n    23: 4.087590,\n    24: 4.119970,\n    25: 4.108820,\n    26: 4.038130,\n    27: 4.173860,\n    28: 4.113180,\n    29: 4.143020,\n    30: 4.166030,\n    31: 4.133930,\n    32: 4.138290,\n    33: 4.894800,\n    34: 4.393840,\n    35: 5.012620,\n    36: 4.457900,\n    37: 6.089870,\n    38: 5.700030,\n    39: 3.871730,\n    40: 3.733100,\n    41: 4.123320,\n    42: 3.696230,\n    43: 4.235810,\n    44: 4.185290,\n    45: 4.259420,\n    46: 3.946020,\n    47: 3.819480,\n    48: 3.708220,\n    49: 4.148530,\n    50: 3.692320,\n    51: 4.358370,\n    52: 4.188390,\n    53: 4.483310,\n    54: 4.016420\n}\n\ndef create_bonds(seqstring):\n\tlseq = len(seqstring)\n\tnbonds = 9*lseq-6\n\tbondtype = np.zeros(nbonds+1, dtype=int)\n\tlistkbond = np.zeros(nbonds+1, dtype=float)\n\tlistr0bond = np.zeros(nbonds+1, dtype=float)\n\ti1list = np.zeros(nbonds+1, dtype=int)\n\ti2list = np.zeros(nbonds+1, dtype=int)\n\t\n\tfirstS1 = 1\n\tlastS1 = firstS1 + (lseq-1)*3\n\tfirstP1 = 3\n\tlastP1 = firstP1 + (lseq-2)*3\n\tfirstB1 = 2\n\tlastB1 = firstB1 + (lseq-1)*3\n\t\n\tfirstS2 = lastB1 + 1\n\tlastS2 = firstS2 + (lseq-1)*3\n\tfirstP2 = lastB1 + 3\n\tlastP2 = firstP2 + (lseq-2)*3\n\tfirstB2 = lastB1 + 2\n\tlastB2 = firstB2 + (lseq-1)*3\n\t\n\tibond = 1\n\t\n\t#### SP\n\tfor i in range(1,lseq):\n\t    i1list[ibond] = 3*i - 2\n\t    i2list[ibond] = i1list[ibond] + 2\n\t    bondtype[ibond] = typeBond['SP/'+seqstring[i-1]+seqstring[i]]\n\t    listkbond[ibond] = kbond[bondtype[ibond]]\n\t    listr0bond[ibond] = r0bond[bondtype[ibond]]\n\t    ibond += 1\n\tfor i in range(1,lseq):\n\t    i1list[ibond] = lastB1 + 3*i - 2\n\t    i2list[ibond] = i1list[ibond] + 2\n\t    bondtype[ibond] = typeBond['SP/'+WC[seqstring[lseq-1-(i-1)]]+WC[seqstring[lseq-1-i]]]\n\t    listkbond[ibond] = kbond[bondtype[ibond]]\n\t    listr0bond[ibond] = r0bond[bondtype[ibond]]\n\t    ibond += 1\n\t\n\t#### PS\n\tfor i in range(2,lseq+1):\n\t    i1list[ibond] = 3*i - 3\n\t    i2list[ibond] = i1list[ibond] + 1\n\t    bondtype[ibond] = typeBond['PS/'+seqstring[i-2]+seqstring[i-1]]\n\t    listkbond[ibond] = kbond[bondtype[ibond]]\n\t    listr0bond[ibond] = r0bond[bondtype[ibond]]\n\t    ibond += 1\n\tfor i in range(2,lseq+1):\n\t    i1list[ibond] = lastB1 + 3*i - 3\n\t    i2list[ibond] = i1list[ibond] + 1\n\t    bondtype[ibond] = typeBond['PS/'+WC[seqstring[lseq-1-(i-2)]]+WC[seqstring[lseq-1-(i-1)]]]\n\t    listkbond[ibond] = kbond[bondtype[ibond]]\n\t    listr0bond[ibond] = r0bond[bondtype[ibond]]\n\t    ibond += 1\n\t\n\t#### SB\n\tfor i in range(1,lseq+1):\n\t    i1list[ibond] = 3*i - 2\n\t    i2list[ibond] = i1list[ibond] + 1\n\t    bondtype[ibond] = typeBond['SB/'+seqstring[i-1]]\n\t    listkbond[ibond] = kbond[bondtype[ibond]]\n\t    listr0bond[ibond] = r0bond[bondtype[ibond]]\n\t    ibond += 1\n\tfor i in range(1,lseq+1):\n\t    i1list[ibond] = lastB1 + 3*i - 2\n\t    i2list[ibond] = i1list[ibond] + 1\n\t    bondtype[ibond] = typeBond['SB/'+WC[seqstring[lseq-1-(i-1)]]]\n\t    listkbond[ibond] = kbond[bondtype[ibond]]\n\t    listr0bond[ibond] = r0bond[bondtype[ibond]]\n\t    ibond += 1\n\t\n\t#### BB-inter\n\tfor i in range(1,lseq+1):\n\t    i1list[ibond] = 3*i - 1\n\t    i2list[ibond] = lastB2 + 2 - i1list[ibond]\n\t    bondtype[ibond] = typeBond['BB-inter/'+seqstring[i-1]+WC[seqstring[i-1]]]\n\t    listkbond[ibond] = kbond[bondtype[ibond]]\n\t    listr0bond[ibond] = r0bond[bondtype[ibond]]\n\t    ibond += 1\n\t\n\t#### BB-intra\n\tfor i in range(1,lseq):\n\t    i1list[ibond] = 3*i - 1\n\t    i2list[ibond] = i1list[ibond] + 3\n\t    bondtype[ibond] = typeBond['BB-intra/'+seqstring[i-1]+seqstring[i]]\n\t    listkbond[ibond] = kbond[bondtype[ibond]]\n\t    listr0bond[ibond] = r0bond[bondtype[ibond]]\n\t    ibond += 1\n\tfor i in range(1,lseq):\n\t    i1list[ibond] = lastB1 + 3*i - 1\n\t    i2list[ibond] = i1list[ibond] + 3\n\t    bondtype[ibond] = typeBond['BB-intra/'+WC[seqstring[lseq-1-(i-1)]]+WC[seqstring[lseq-1-i]]]\n\t    listkbond[ibond] = kbond[bondtype[ibond]]\n\t    listr0bond[ibond] = r0bond[bondtype[ibond]]\n\t    ibond += 1\n\t\n\treturn i1list, i2list, listr0bond, listkbond\n", "meta": {"hexsha": "7982fc7abe4fa968f9cb765feca4adab4deac0f7", "size": 6709, "ext": "py", "lang": "Python", "max_stars_repo_path": "structured/Tools/MADna/CreateMolecule/CreateBonds.py", "max_stars_repo_name": "PabloIbannez/UAMMD-structured", "max_stars_repo_head_hexsha": "897d7211c3d37123976a03bc5ffa545495d673cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "structured/Tools/MADna/CreateMolecule/CreateBonds.py", "max_issues_repo_name": "PabloIbannez/UAMMD-structured", "max_issues_repo_head_hexsha": "897d7211c3d37123976a03bc5ffa545495d673cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "structured/Tools/MADna/CreateMolecule/CreateBonds.py", "max_forks_repo_name": "PabloIbannez/UAMMD-structured", "max_forks_repo_head_hexsha": "897d7211c3d37123976a03bc5ffa545495d673cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5134228188, "max_line_length": 96, "alphanum_fraction": 0.5516470413, "include": true, "reason": "import numpy,import scipy", "num_tokens": 3156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017746, "lm_q2_score": 0.2598256379609837, "lm_q1q2_score": 0.16923869676777492}}
{"text": "\"\"\"Sound Heat Map generation and distribution.\"\"\"\n\nimport ast\nimport asyncio\nimport json\nimport logging\nimport optparse\nimport os\nimport re\nimport sys\nimport traceback\nfrom datetime import datetime, timedelta\n\nimport coloredlogs\nimport dateutil.parser as dp\nimport numpy as np\nimport pandas as pd\nimport requests\nfrom beeprint import pp\nfrom hbmqtt.client import ClientException, MQTTClient\nfrom hbmqtt.mqtt.constants import QOS_1\nfrom pyost import SensorThingStore\nfrom shapely.geometry import Point\nfrom shapely.geometry.polygon import Polygon\nfrom model import calculate_shm_dir, grid_area\nfrom weighting import weightfunc\n\nlogging.getLogger(\"urllib3\").setLevel(logging.WARNING)  # not from these\nlogging.getLogger(\"requests\").setLevel(logging.WARNING)\nlogging.getLogger(\"asyncio\").setLevel(logging.WARNING)\nlogging.getLogger(\"hbmqtt\").setLevel(logging.WARNING)\nlogging.getLogger(\"transitions\").setLevel(logging.WARNING)\n\nFREQUENCIES = np.array(ast.literal_eval(os.environ[\"FREQUENCIES\"]))\nMQTT_BROKER_PREFIX = os.environ[\"MQTT_BROKER_PREFIX\"]\nGOST_URL = os.environ[\"GOST_URL\"]\nUPDATE_DATASTREAMS_PERIODE = float(os.environ[\"UPDATE_DATASTREAMS_PERIODE\"])\nNEW_MAP_PERIODE = float(os.environ[\"NEW_MAP_PERIODE\"])\nMAP_LATENCY = float(os.environ[\"MAP_LATENCY\"])\nMAP_AVERAGING_TIME = float(os.environ[\"MAP_AVERAGING_TIME\"])\nFILTER_MICS = os.environ[\"FILTER_MICS\"]\nWEIGHTINGS = ast.literal_eval(os.environ[\"WEIGHTINGS\"])\n\ntry:\n    SHM_ID = os.environ[\"SHM_ID\"]\nexcept KeyError:\n    # No instance set\n    SHM_ID = None\n\ntry:\n    AUTH = (os.environ[\"GOST_USER\"], os.environ[\"GOST_PASS\"])\nexcept KeyError:\n    AUTH = None\n\n\ndef CPBLZeq_Observation_to_dataframe(message):\n    \"\"\"Convert MQTT CPBLZeq observation message to a time indexable Dataframe.\"\"\"\n    # multiple observations can be bundled in one message\n    observations = json.loads(message.data)[\"result\"][\"response\"][\"value\"]\n\n    all_values = []\n    all_times = []\n    for obs in observations:\n        values = np.array(obs[\"values\"])\n        nmeas, nfreq = values.shape\n        assert nfreq == 33\n\n        start = dp.parse(obs[\"startTime\"])\n        end = dp.parse(obs[\"endTime\"])\n\n        times = start + (end - start) / nmeas * np.arange(nmeas)\n\n        all_values.append(values)\n        all_times.append(times)\n\n    all_values = np.concatenate(all_values, axis=0)\n    all_times = np.concatenate(all_times)\n\n    return pd.DataFrame(all_values, index=all_times, columns=FREQUENCIES)\n\n\nclass Datastream:\n    \"\"\"Object representation of a Datastream.\"\"\"\n\n    def __init__(self, json):\n        self.id = json[\"@iot.id\"]\n        self.location = json[\"observedArea\"][\"coordinates\"]\n        # coordinates must be given in (x=lon, y=lat) format, but we use lat/lon intern.\n        self.location = self.location[::-1]\n        self.description = json[\"description\"]\n        self.name = json[\"name\"]\n        self.mqtt_topic = MQTT_BROKER_PREFIX + f\"/Datastreams({self.id})/Observations\"\n        self.recent_data = None\n\n    def add(self, data):\n        self.recent_data = pd.concat((self.recent_data, data))\n\n    def average_and_drop_old_data(self, starttime, endtime):\n        # average\n        if self.recent_data is None or self.recent_data.empty:\n            return None\n\n        avg = self.recent_data[starttime:endtime].mean(axis=0)\n\n        logging.debug(\n            \"datastream.recent_data before drop:\" + pp(self.recent_data, output=False)\n        )\n\n        # drop data that will never be used again\n        self.recent_data = self.recent_data[starttime:]\n        logging.debug(\n            \"datastream.recent_data after drop:\" + pp(self.recent_data, output=False)\n        )\n\n        # return as ndarray\n        return avg.values\n\n\nclass DatastreamManager:\n    \"\"\"Stores and updates active SLM Datastreams.\"\"\"\n\n    def __init__(self, store_url, mqtt_client, filter_mics, auth=None):\n        self.st_store = SensorThingStore(store_url, auth=auth)\n        self.datastreams = {}\n        self.mqtt_client = mqtt_client\n        self.filter_mics = filter_mics\n\n    async def update_datastreams(self):\n        \"\"\"Query for available SLM datastreams and subscribe.\"\"\"\n        logging.info(\"Updating list of datastreams.\")\n\n        # query for ObservedProperty CPBLZeq\n        observed_property = self.st_store.get_by_query(\n            \"ObservedProperties\", filter=\"equals(name, 'CPBLZeq')\"\n        )[0]\n\n        # query for all Datastreams that observe above property\n        all_datastreams = self.st_store.get_by_parent(\n            kind=\"Datastreams\",\n            parent=\"ObservedProperties\",\n            id=observed_property[\"@iot.id\"],\n            filter=self.filter_mics,\n        )\n        if not all_datastreams:\n            logging.warning(\n                f\"Could not find any datastreams with filter {self.filter_mics}.\"\n            )\n            return\n\n        # populate dictionary with new datastreams\n        polygon = Polygon(np.array(ast.literal_eval(os.environ[\"AREA_POLYGON\"])))\n        for jso in all_datastreams:\n            stream = Datastream(jso)\n            if stream.id not in self.datastreams:\n\n                # only include streams with location in area_polygon\n                if polygon.contains(Point(stream.location)):\n                    self.datastreams[stream.id] = stream\n                else:\n                    logging.info(\n                        f\"Excluding datastream {stream.id} with name {stream.name} at {stream.location}: not in polygon.\"\n                    )\n\n        if not self.datastreams:\n            logging.info(\"No datastreams matching criteria found.\")\n            return\n\n        # subscribe to all datastreams\n        topics = [(ds.mqtt_topic, QOS_1) for (_, ds) in self.datastreams.items()]\n\n        suback_codes = await self.mqtt_client.subscribe(topics)\n        for code, topic in zip(suback_codes, topics):\n            if code not in [0, 1, 2]:\n                logging.error(\n                    f\"\"\"SUBACK return code {code}. Could not subscribe to\n                    topic: {topic}\"\"\"\n                )\n            else:\n                logging.info(f\"Subscribed to topic: {topic}\")\n\n    async def start(self, rate=UPDATE_DATASTREAMS_PERIODE):\n        \"\"\"Continually update datastream subscriptions.\"\"\"\n        while True:\n            await self.update_datastreams()\n            logging.debug(\"Datastreams: {}\".format(pp(self.datastreams, output=False)))\n            await asyncio.sleep(rate)\n\n\nclass DataCollector:\n    \"\"\"Collects MQTT messages and their data.\"\"\"\n\n    def __init__(self, mqtt_client, datastreams):\n        self.mqtt_client = mqtt_client\n        self.datastreams = datastreams\n\n    def process(self, message):\n        \"\"\"Add contents of message to datastore.\"\"\"\n        # keep track of datastreams using their iot.id\n        datastream_id = int(re.search(r\"\\d+\", message.topic).group())\n        logging.debug(\n            f\"Processing message from Datastream({datastream_id})\"\n            + f\" from topic {message.topic}\"\n        )\n\n        data = CPBLZeq_Observation_to_dataframe(message)\n\n        if datastream_id in self.datastreams:\n            self.datastreams[datastream_id].add(data)\n        else:\n            logging.error(\n                f\"Received message from Datastream({datastream_id}), altough not subscribed ...\"\n            )\n\n        logging.debug(\n            \"Added data to datastreams:\"\n            + pp(self.datastreams[datastream_id], output=False)\n        )\n\n    async def start(self):\n        \"\"\"Listen to SLM observations and process incoming messages.\"\"\"\n\n        timeout = 60\n\n        while True:\n\n            try:\n                message = await self.mqtt_client.deliver_message(timeout=timeout)\n                logging.info(f\"Received message on {message.topic}\")\n                logging.debug(f\"Payload: {pp(json.loads(message.data), output=False)}\")\n\n                self.process(message)\n\n            except ClientException as ce:\n                logging.error(\"Client exception: %s\" % ce)\n            except asyncio.TimeoutError:\n                logging.error(\n                    f\"Timeout error: did not receive message since {timeout}s\"\n                )\n\n\nclass MapMaker:\n    def __init__(self, datastreams, mqtt_client, mqtt_shm_topics):\n        self.datastreams = datastreams\n        self.mqtt_client = mqtt_client\n        self.mqtt_shm_topics = mqtt_shm_topics\n\n    async def make_map(self):\n        now = datetime.utcnow()\n        starttime = now - timedelta(\n            seconds=MAP_LATENCY + NEW_MAP_PERIODE + MAP_AVERAGING_TIME\n        )\n        endtime = now - timedelta(seconds=MAP_LATENCY)\n\n        logging.debug(f\"starttime: {starttime}, endtime: {endtime}\")\n\n        spl_values = []\n        slm_latlon = []\n        for (_, ds) in self.datastreams.items():\n            avg = ds.average_and_drop_old_data(starttime, endtime)\n            if avg is not None:\n                # there was data to average in that microphone\n                spl_values.append(avg)\n                slm_latlon.append(ds.location)\n\n        if not spl_values:\n            logging.info(\"Couldn't create map: no data.\")\n            return None\n\n        logging.info(\"Making a map.\")\n\n        slm_latlon = np.array(slm_latlon).T  # to shape 2 x Nslm\n        spl_values = np.array(spl_values).T  # to shape Nf x Nslm\n\n        logging.debug(\n            pp({\"Locations\": slm_latlon, \"averages\": spl_values}, output=False)\n        )\n\n        temperature = float(os.environ[\"TEMPERATURE\"])\n        s_latlon = np.array(\n            ast.literal_eval(os.environ[\"SOURCES\"])\n        ).T  # to shape 2 x Ns\n        walls = os.environ[\"WALLS\"]\n        if walls:\n            wall_latlon = np.array(\n                ast.literal_eval(os.environ[\"WALLS\"])\n            ).T  # to shape 2 x 2 x Nw\n        else:\n            wall_latlon = None\n        polygon = np.array(ast.literal_eval(os.environ[\"AREA_POLYGON\"])).T\n        cellsize = float(os.environ[\"CELLSIZE\"])\n        source_direction = np.array(ast.literal_eval(os.environ[\"SOURCES_DIRECTION\"]))\n\n        assert s_latlon.ndim == 2\n        assert s_latlon.shape[0] == 2\n        if walls:\n            assert wall_latlon.ndim == 3\n            assert wall_latlon.shape[0] == 2 and wall_latlon.shape[1] == 2\n        assert polygon.ndim == 2\n        assert polygon.shape[0] == 2\n        assert isinstance(cellsize, float)\n        assert FREQUENCIES.size == spl_values.shape[0]\n        assert isinstance(temperature, float) or isinstance(temperature, int)\n\n        # make a grid of points that includes the polygon\n        r_latlon_all, mask_inside_polygon, grid_shape = grid_area(\n            polygon, dx=cellsize, dy=cellsize\n        )\n        r_latlon_inside_polygon = r_latlon_all[:, mask_inside_polygon]\n\n        # inside the polygon, one has the computed values\n        try:\n            shm = calculate_shm_dir(\n                s_latlon=s_latlon,\n                slm_latlon=slm_latlon,\n                wall_latlon=wall_latlon,\n                r_latlon=r_latlon_inside_polygon,\n                Lp=spl_values,\n                f=FREQUENCIES,\n                T=temperature,\n                alpha=source_direction,\n            )\n        except ValueError as e:\n            logging.error(f\"Could not create map: {e}\")\n            return\n\n        for weighting, topic in zip(WEIGHTINGS, self.mqtt_shm_topics):\n\n            # apply weightings\n            wfunc = weightfunc(weighting[0])\n            shm_weighted = np.round(shm, 1) + wfunc(FREQUENCIES.astype(float))[:, None]\n\n            # sum or not\n            if weighting.endswith(\"fullband\"):\n                # compute a fullband spectrum\n                band_frequencies = [\"fullband\"]\n\n                # outside the polygon everything is NaN\n                L_all = np.empty((len(band_frequencies), r_latlon_all.shape[1]), dtype=object)\n\n                # sum over rms pressures and convert back\n                rms = np.sum(10 ** (shm_weighted / 10), axis=0)[None]\n                shm_weighted = 10 * np.log10(rms)\n            else:\n                # compute 1/3 octave wise\n                band_frequencies = FREQUENCIES.tolist()\n                L_all = np.empty((len(band_frequencies), r_latlon_all.shape[1]), dtype=object)\n\n            # prepare output\n            L_all.fill(None)\n            L_all[:, mask_inside_polygon] = shm_weighted\n            L_all_final_shape = L_all.reshape((-1, grid_shape[0], grid_shape[1]))\n\n            msg = {\n                \"phenomenonTime\": endtime.isoformat(sep=\"T\", timespec=\"seconds\") + \"Z\",\n                \"resultTime\": datetime.utcnow().isoformat() + \"Z\",\n                \"result\": {\n                    \"starttime\": starttime.isoformat(sep=\"T\", timespec=\"seconds\"),\n                    \"endtime\": endtime.isoformat(sep=\"T\", timespec=\"seconds\"),\n                    \"timeStamp\": endtime.isoformat(sep=\"T\", timespec=\"seconds\"),\n                    \"lat_0\": r_latlon_all[0, 0],\n                    \"lon_0\": r_latlon_all[1, 0],\n                    \"nfreq\": len(band_frequencies),\n                    \"nrow\": L_all_final_shape.shape[1],\n                    \"ncols\": L_all_final_shape.shape[2],\n                    \"cellsize\": cellsize,\n                    \"data\": L_all_final_shape.tolist(),\n                    \"bandFrequencies\": band_frequencies,\n                    \"unit\": f\"SPL dB {weighting}\",\n                    \"input_positions\": {\n                        \"sources_latlon\": s_latlon.tolist(),\n                        \"slm_latlon\": slm_latlon.tolist(),\n                        \"walls_latlon\": wall_latlon.tolist()\n                        if wall_latlon is not None\n                        else [],\n                        \"shm_area\": polygon.tolist(),\n                    },\n                },\n            }\n\n            await self.mqtt_client.publish(topic, json.dumps(msg).encode())\n            logging.info(f\"Published map on {topic}\")\n\n    async def start(self):\n        while True:\n            await self.make_map()\n            await asyncio.sleep(NEW_MAP_PERIODE)\n\n\ndef register_shm_as_service(catalogue_url):\n    \"\"\"Register service at OGC service catalogue.\n\n    Returns MQTT topics for the three SHM variations and MQTT broker address and port\n    \"\"\"\n    topics = []\n    for weighting in WEIGHTINGS:\n        msg = {\n            \"externalId\": f\"SoundHeatMap/{SHM_ID}/{weighting}\",\n            \"metadata\": \"SoundHeatMapGenerator\",\n            \"sensorType\": f\"SoundHeatMap/L{weighting}eq\",\n            \"unitOfMeasurement\": f\"Sound Heat Map with {weighting}-weighted values.\",\n            \"fixedLatitude\": 0,\n            \"fixedLongitude\": 0,\n        }\n        r = requests.post(catalogue_url + \"/SearchOrCreateOGCDataStreamId\", json=msg)\n        r.raise_for_status()\n\n        # get MQTT topic and server\n        data = r.json()\n\n        topic = data[\"mqttTopic\"]\n        mqtt_address, mqtt_port = data[\"mqttServer\"].split(\":\")\n        mqtt_address = \"mqtt://\" + mqtt_address\n\n        logging.info(\n            f\"Registered {weighting} weighting at topic {topic}, {mqtt_address}:{mqtt_port}\"\n        )\n\n        topics.append(topic)\n\n    return topics, mqtt_address, mqtt_port\n\n\nasync def main():\n    parser = optparse.OptionParser()\n    parser.add_option(\"-l\", \"--logging-level\", help=\"Logging level\")\n    parser.add_option(\"-f\", \"--logging-file\", help=\"Logging file name\")\n    parser.add_option(\"-a\", \"--account\", help=\"account\")\n    parser.add_option(\"-p\", \"--password\", help=\"password\")\n    (options, args) = parser.parse_args()\n\n    if options.account and options.password:\n        # auth data provided in command line\n        auth = (options.account, options.password)\n    else:\n        # auth data provided from environment variables\n        auth = AUTH\n\n    # initialize logging\n    logging_levels = {\n        \"critical\": logging.CRITICAL,\n        \"error\": logging.ERROR,\n        \"warning\": logging.WARNING,\n        \"info\": logging.INFO,\n        \"debug\": logging.DEBUG,\n    }\n    logging_level = logging_levels.get(options.logging_level, logging.INFO)\n    logging.basicConfig(\n        level=logging_level,\n        filename=options.logging_file,\n        format=\"%(asctime)s %(levelname)-6s %(name)s [%(filename)s:%(lineno)d] %(message)s\",\n        datefmt=\"%d-%m-%Y:%H:%M:%S\",\n    )\n\n    logging.getLogger(\"pyost\").addHandler(logging.StreamHandler())\n    logging.getLogger(\"pyost\").setLevel(logging_level)\n    logging.getLogger(__name__).setLevel(logging_level)\n    coloredlogs.install(level=logging_level, logger=logging.getLogger(__name__))\n\n    mqtt_topics, mqtt_address, mqtt_port = register_shm_as_service(\n        os.environ[\"CATALOG_URL\"]\n    )\n\n    while True:\n        try:\n            # Connect to MQTT broker\n            mqtt_client = MQTTClient()\n            retcode = await mqtt_client.connect(mqtt_address, mqtt_port)\n            if retcode == 0:\n                logging.info(f\"Connected to MQTT broker: {mqtt_address}:{mqtt_port}\")\n            else:\n                raise ConnectionError(\n                    f\"Could not connect to broker, CONNACK code {retcode}\"\n                )\n\n            # Connect to OGC SensorThing store server\n            datastream_manager = DatastreamManager(\n                GOST_URL, mqtt_client, FILTER_MICS, auth=auth\n            )\n            data_collector = DataCollector(mqtt_client, datastream_manager.datastreams)\n            map_maker = MapMaker(\n                datastream_manager.datastreams, mqtt_client, mqtt_topics\n            )\n\n            # run concurrently\n            await asyncio.gather(\n                datastream_manager.start(), data_collector.start(), map_maker.start()\n            )\n        except KeyboardInterrupt:\n            logging.info(\"KeyboardInterrupt. Shutting down ...\")\n            sys.exit(0)\n        except ImportError:\n            logging.error(traceback.format_exc())\n            sys.exit(1)\n        except ConnectionError:\n            logging.error(traceback.format_exc())\n            logging.error(\"Restarting...\")\n        except Exception:\n            logging.error(traceback.format_exc())\n            logging.error(\"Restarting...\")\n        finally:\n            mqtt_client.disconnect()\n            break\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n", "meta": {"hexsha": "05820d8b6c776948784dd6bede5d0e618135522c", "size": 18149, "ext": "py", "lang": "Python", "max_stars_repo_path": "app/main.py", "max_stars_repo_name": "MONICA-Project/sound-heat-map", "max_stars_repo_head_hexsha": "616340a11a9b3e12fa330f86505de5514a4ff940", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-17T11:47:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-17T11:47:21.000Z", "max_issues_repo_path": "app/main.py", "max_issues_repo_name": "MONICA-Project/sound-heat-map", "max_issues_repo_head_hexsha": "616340a11a9b3e12fa330f86505de5514a4ff940", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/main.py", "max_forks_repo_name": "MONICA-Project/sound-heat-map", "max_forks_repo_head_hexsha": "616340a11a9b3e12fa330f86505de5514a4ff940", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7968441815, "max_line_length": 121, "alphanum_fraction": 0.6047165133, "include": true, "reason": "import numpy", "num_tokens": 3964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.16923358690262408}}
{"text": "\"\"\"\nThe pycity_scheduling framework\n\n\nCopyright (C) 2022,\nInstitute for Automation of Complex Power Systems (ACS),\nE.ON Energy Research Center (E.ON ERC),\nRWTH Aachen University\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\ndocumentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\nrights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the\nSoftware.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\nWARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\n\nimport numpy as np\nimport pyomo.environ as pyomo\n\nfrom pycity_scheduling.classes.thermal_entity_cooling import ThermalEntityCooling\nfrom pycity_scheduling.classes.thermal_entity_heating import ThermalEntityHeating\nfrom pycity_scheduling.classes.electrical_entity import ElectricalEntity\n\n\nclass EntityContainer(ThermalEntityCooling, ThermalEntityHeating, ElectricalEntity):\n    \"\"\"\n    Base class for entities containing other entities.\n\n    `p_th` and `p_el` imbalances are propagated to this entities variables.\n    During calls to its scheduling functions, the contained entities are also\n    called with the same parameters.\n\n    Notes\n    -----\n    - EntityContainers offer sets of constraints for operation. The following\n      constraints are added.\n\n    .. math::\n        p_{th\\\\_cool} &=& \\\\sum_i p_{th\\\\_cool\\\\_i} \\\\\\\\\n        p_{th\\\\_heat} &=& \\\\sum_i p_{th\\\\_heat\\\\_i} \\\\\\\\\n        p_{el} &=& \\\\sum_i p_{el\\\\_i}\n\n    - :math:`p_{th\\\\_cool\\\\_i}`, :math:`p_{th\\\\_heat\\\\_i}`, and :math:`p_{el\\\\_i}` are the variables from lower\n      entities. The Bounds from TEC, TEH, and EE are removed.\n    \"\"\"\n\n    def populate_model(self, model, mode=\"convex\"):\n        \"\"\"\n        Add entity block and lower entities blocks to pyomo ConcreteModel.\n\n        Call both parent's `populate_model` methods and set variables lower\n        bounds to `None`. Then call `populate_model` method of all contained\n        entities and add constraints that the sum of their variables for each\n        period equals the corresponding own variable.\n\n        Parameters\n        ----------\n        model : pyomo.ConcreteModel\n        mode : str, optional\n            Specifies which set of constraints to use.\n\n            - `convex`  : Use linear constraints\n            - `integer`  : Use same constraints as convex mode\n        \"\"\"\n        super().populate_model(model, mode)\n        m = self.model\n\n        if mode in [\"convex\", \"integer\"]:\n            p_th_cool_var_list = []\n            p_th_heat_var_list = []\n            p_el_var_list = []\n            for entity in self.get_lower_entities():\n                entity.populate_model(model, mode)\n                if isinstance(entity, ThermalEntityCooling):\n                    p_th_cool_var_list.append(entity.model.p_th_cool_vars)\n                if isinstance(entity, ThermalEntityHeating):\n                    p_th_heat_var_list.append(entity.model.p_th_heat_vars)\n                if isinstance(entity, ElectricalEntity):\n                    p_el_var_list.append(entity.model.p_el_vars)\n\n            m.p_th_cool_vars.setlb(None)\n            m.p_th_heat_vars.setlb(None)\n            m.p_el_vars.setlb(None)\n\n            def p_th_cool_sum_rule(model, t):\n                return model.p_th_cool_vars[t] == pyomo.quicksum(p_th_Cool_var[t] for\n                                                                 p_th_Cool_var in p_th_cool_var_list)\n            m.p_th_cool_constr = pyomo.Constraint(m.t, rule=p_th_cool_sum_rule)\n\n            def p_th_heat_sum_rule(model, t):\n                return model.p_th_heat_vars[t] == pyomo.quicksum(p_th_Heat_var[t] for\n                                                                 p_th_Heat_var in p_th_heat_var_list)\n            m.p_th_heat_constr = pyomo.Constraint(m.t, rule=p_th_heat_sum_rule)\n\n            def p_el_sum_rule(model, t):\n                return model.p_el_vars[t] == pyomo.quicksum(p_el_var[t] for p_el_var in p_el_var_list)\n            m.p_el_constr = pyomo.Constraint(m.t, rule=p_el_sum_rule)\n        else:\n            raise ValueError(\n                \"Mode %s is not implemented by class EntityContainer.\" % str(mode)\n            )\n        return\n\n    def update_model(self, mode=\"\"):\n        super().update_model(mode)\n        for entity in self.get_lower_entities():\n            entity.update_model(mode)\n        return\n\n    def update_schedule(self):\n        super().update_schedule()\n        for entity in self.get_lower_entities():\n            entity.update_schedule()\n        return\n\n    def reset(self, schedule=None):\n        super().reset(schedule)\n        for entity in self.get_lower_entities():\n            entity.reset(schedule)\n        return\n\n    def get_lower_entities(self):\n        raise NotImplementedError\n", "meta": {"hexsha": "d9de9b17b087ea634a2047b251570ca6eb1a29fc", "size": 5435, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/pycity_scheduling/classes/entity_container.py", "max_stars_repo_name": "ElsevierSoftwareX/SOFTX-D-20-00087", "max_stars_repo_head_hexsha": "d2d3f1effda2c0499cb05abf87435375a21379e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-11-01T15:13:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T18:01:06.000Z", "max_issues_repo_path": "src/pycity_scheduling/classes/entity_container.py", "max_issues_repo_name": "ElsevierSoftwareX/SOFTX-D-20-00087", "max_issues_repo_head_hexsha": "d2d3f1effda2c0499cb05abf87435375a21379e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-11-18T05:58:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T16:46:20.000Z", "max_forks_repo_path": "src/pycity_scheduling/classes/entity_container.py", "max_forks_repo_name": "ElsevierSoftwareX/SOFTX-D-20-00087", "max_forks_repo_head_hexsha": "d2d3f1effda2c0499cb05abf87435375a21379e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-11-01T15:13:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T21:28:48.000Z", "avg_line_length": 41.1742424242, "max_line_length": 118, "alphanum_fraction": 0.6610855566, "include": true, "reason": "import numpy,import pyomo", "num_tokens": 1183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.1692335844489417}}
{"text": "# Import smorgasbord\r\nimport os\r\nimport sys\r\nimport gc\r\nimport shutil\r\nimport pdb\r\nimport time\r\nimport copy\r\nimport numbers\r\nimport warnings\r\nimport psutil\r\nimport random\r\nimport multiprocessing as mp\r\nimport numpy as np\r\nimport scipy.optimize\r\nimport astropy.io.fits\r\nimport astropy.wcs\r\nimport astropy.convolution\r\nimport ChrisFuncs\r\nimport ChrisFuncs.Photom\r\nimport ChrisFuncs.FromGitHub\r\nimport CAAPR\r\n\r\n\r\n\r\n\r\n\r\n# The aperture-fitting sub-pipeline\r\ndef SubpipelineAperture(source_dict, band_dict, kwargs_dict):\r\n    source_id = source_dict['name']+'_'+band_dict['band_name']\r\n\r\n\r\n\r\n    # Carry out small random wait, to stop RAM checks from syncing up later\r\n    time.sleep(5.0*np.random.rand())\r\n\r\n\r\n\r\n    # Perform initial checks of target file type and location; return if not present\r\n    in_fitspath, file_found = CAAPR.CAAPR_Pipeline.FilePrelim(source_dict, band_dict, kwargs_dict)\r\n    if file_found == False:\r\n        return None\r\n\r\n\r\n\r\n    # Create the pod (Photometry Organisation Dictionary), which will read in the FITS file, and bundle all the photometry data for this source & band into one dictionary to be passed between functions\r\n    pod = CAAPR.CAAPR_Pipeline.PodInitiate(in_fitspath, source_dict, band_dict, kwargs_dict)\r\n\r\n\r\n\r\n    # Run pod through preliminary processing, to determine initial quantities; if target not within bounds of map, end processing here\r\n    pod = CAAPR.CAAPR_Pipeline.MapPrelim(pod, source_dict, band_dict)\r\n    if pod['within_bounds']==False:\r\n        return None\r\n    CAAPR.CAAPR_IO.MemCheck(pod)\r\n\r\n\r\n\r\n    # Check if this band is to be excluded from aperture-fitting; if so, return null aperture information\r\n    pod = ExcludeAperture(pod, source_dict, band_dict, kwargs_dict)\r\n    if pod['band_exclude']==True:\r\n        return pod['null_output_dict']\r\n\r\n\r\n\r\n    # If star-removal is required, run pod through AstroMagic\r\n    pod = CAAPR.CAAPR_AstroMagic.Magic(pod, source_dict, band_dict, kwargs_dict)\r\n\r\n\r\n\r\n    # Run pod through function that determines aperture shape, to provide preliminary estimate to facilitate removal of large-scale sky\r\n    pod = ApertureShape(pod)\r\n\r\n\r\n\r\n    # Run pod through function that removes large-scale sky using a 2-dimensional polynomial filter\r\n    pod = CAAPR.CAAPR_Pipeline.PolySub( pod, 2.0*pod['semimaj_initial_pix'], pod['opt_axial_ratio'], pod['opt_angle'], instant_quit=max([not kwargs_dict['polysub'],pod['band_exclude']]) )\r\n\r\n\r\n\r\n    # If sky polynomial removed, run pod through function that determines aperture shape, to provide final estiamte\r\n    if pod['sky_poly']!=False:\r\n        pod = ApertureShape(pod)\r\n\r\n\r\n\r\n    # Run pod through function that determines aperture size\r\n    pod = ApertureSize(pod, band_dict)\r\n\r\n\r\n\r\n    # If thumbnail images have been requested, save a copy of the current image (ie, with any star and/or background subtaction)\r\n    if kwargs_dict['thumbnails']==True:\r\n        astropy.io.fits.writeto(os.path.join(kwargs_dict['temp_dir_path'],'Processed_Maps',source_id+'.fits'), pod['cutout'], header=pod['in_header'], overwrite=True)\r\n\r\n\r\n\r\n    # Now return final aperture informaton to main pipeline, and clean up garbage\r\n    output_dict = {'band_name':band_dict['band_name'],\r\n                   'opt_semimaj_arcsec':pod['opt_semimaj_arcsec'],\r\n                   'opt_axial_ratio':pod['opt_axial_ratio'],\r\n                   'opt_angle':pod['opt_angle']}\r\n    gc.collect()\r\n    del(pod)\r\n    return output_dict\r\n\r\n\r\n\r\n\r\n\r\n# Define function that determines the shape (not the size) of the source aperture in this band\r\ndef ApertureShape(pod):\r\n    if pod['band_exclude']==True:\r\n        return pod\r\n    verbose = pod['verbose']\r\n    if pod['verbose']: print '['+pod['id']+'] Commencing determination of appropriate axial ratio and positional angle for source aperture.'\r\n\r\n\r\n\r\n    # Make preliminary per-pixel noise measurement by iteratively sigma-clipping cutout\r\n    if verbose: print '['+pod['id']+'] Making preliminary per-pixel noise measurement.'\r\n    clip_value = ChrisFuncs.SigmaClip(pod['cutout'], tolerance=0.001, sigma_thresh=3.0, median=True)\r\n    noise_value = clip_value[0]\r\n    field_value = clip_value[1]\r\n\r\n    # Find all significant pixels that are connected to the region of the source (ie, withing a beam-width of the provided target coords)\r\n    if verbose: print '['+pod['id']+'] Finding contiguous significant pixels around target.'\r\n    semimaj_initial = int(round(pod['beam_pix']*1.0))\r\n    cutoff = field_value + (4.0*noise_value)\r\n    #cont_structure = np.array([[1]*(2*semimaj_initial)]*(2*semimaj_initial))\r\n    cont_array_prelim = ChrisFuncs.Photom.ContiguousPixels(pod['cutout'], semimaj_initial, pod['centre_i'], pod['centre_j'], cutoff)#, custom_structure=cont_structure)\r\n\r\n    # Use binary erosion to remove thin artefacts (primarily diffraction spikes)\r\n    erode_size = int(np.ceil(3.0*pod['beam_pix']))\r\n    erode_centre = (0.5*float(erode_size))-0.5\r\n    erode_structure = ChrisFuncs.Photom.EllipseMask(np.zeros([erode_size,erode_size]), pod['beam_pix'], 1.0, 0.0, erode_centre, erode_centre)\r\n    erode_array = scipy.ndimage.morphology.binary_erosion(cont_array_prelim, structure=erode_structure).astype(int)\r\n    cont_array = ChrisFuncs.Photom.ContiguousPixels(erode_array, semimaj_initial, pod['centre_i'], pod['centre_j'], 1E-50)\r\n\r\n    # If remainging contiguous pixel region has same or fewer number of pixels than erosion structure, replace with erosion sturcture\r\n    if np.sum(cont_array)<=(np.sum(erode_structure)):\r\n        cont_array = erode_structure\r\n\r\n    # Find ellipse that best fits outline of contiguous region\r\n    if verbose: print '['+pod['id']+'] Fitting ellipse to perimeter of contiguous significant pixels.'\r\n    cont_x = ((np.where(cont_array==1))[1])\r\n    cont_y = ((np.where(cont_array==1))[0])\r\n    if cont_x.shape[0]>10:\r\n        try:\r\n            cont_ellipse = ChrisFuncs.Photom.EllipseFit(cont_x, cont_y)\r\n            opt_axial_ratio = max(cont_ellipse[1]) / min(cont_ellipse[1])\r\n            opt_angle = cont_ellipse[2]\r\n            semimaj_initial = max(cont_ellipse[1])\r\n        except:\r\n            opt_axial_ratio = 1.0\r\n            opt_angle = 0.0\r\n\r\n    # If too few significant pixels, default to circular aperture\r\n    else:\r\n        opt_axial_ratio = 1.0\r\n        opt_angle = 0.0\r\n    if verbose: print '['+pod['id']+'] Ellipse angle: '+str(ChrisFuncs.FromGitHub.randlet.ToPrecision(opt_angle,4))+' degrees; Ellipse axial ratio: '+str(ChrisFuncs.FromGitHub.randlet.ToPrecision(opt_axial_ratio,4))+'.'\r\n\r\n    # Clean garbage, record results to pod, and return\r\n    gc.collect()\r\n    pod['cutout_clip'] = clip_value\r\n    pod['opt_axial_ratio'] = opt_axial_ratio\r\n    pod['opt_angle'] = opt_angle\r\n    pod['semimaj_initial_pix'] = semimaj_initial\r\n    pod['semimaj_initial_arcsec'] = semimaj_initial * pod['pix_arcsec']\r\n    return pod\r\n\r\n\r\n\r\n\r\n\r\n# Define function that determines the size of the source aperture in this band\r\ndef ApertureSize(pod, band_dict):\r\n    if pod['band_exclude']:\r\n        return pod\r\n    if pod['verbose']: print '['+pod['id']+'] Commencing determination of appropriate size for source aperture.'\r\n    verbose = pod['verbose']\r\n\r\n    # Define sub-function that determines SNR of a defined annulus; and if requested, determines residual between the SNR of a defined annulus, and a target SNR of 2\r\n    def AnnulusSNR(semimaj, pod, cutout, width, i_trans, j_trans, residual):\r\n        semimaj = semimaj[0]\r\n        sig_annulus = ChrisFuncs.Photom.AnnulusQuickSum(cutout, semimaj, width, pod['opt_axial_ratio'], pod['opt_angle'], pod['centre_i'], pod['centre_j'], i_trans, j_trans)\r\n        sig_value = ChrisFuncs.SigmaClip(sig_annulus[2], tolerance=0.005, sigma_thresh=2.0, median=True)[1]#np.median(sig_annulus[2])\r\n        noise_value = pod['cutout_clip'][0]\r\n        field_value = pod['cutout_clip'][1]\r\n        ann_SNR = (sig_value - field_value) / noise_value\r\n        if residual==True:\r\n            ann_residual = abs(2.0-ann_SNR)\r\n            #print 'SNR: '+str(ann_SNR)+', Semi-Maj: '+str(semimaj)+', Residual:'+str(ann_residual)\r\n            return ann_residual\r\n        elif residual==False:\r\n            #print 'SNR: '+str(ann_SNR)+', Semi-Maj: '+str(semimaj)\r\n            return ann_SNR\r\n\r\n\r\n\r\n    # Construct kernel with FWHM equal to 3 beam-widths, by which to smooth map\r\n    if verbose: print '['+pod['id']+'] Convolving map to lower resolution (twice the beam width) for radial analysis.'\r\n    pix_size = pod['pix_arcsec']\r\n    res_in = band_dict['beam_arcsec']\r\n    res_out = 2.0*band_dict['beam_arcsec']#36.0\r\n    kernel_fwhm = np.sqrt( (res_out/pix_size)**2.0 - (res_in/pix_size)**2.0 )\r\n\r\n    # Determine if map contains NaN pixels, excluding those that simply represent edge of map\r\n    cutout_prelabel = pod['cutout'].copy()\r\n    cutout_prelabel = cutout_prelabel.byteswap().newbyteorder().astype('float64')\r\n    cutout_prelabel[ np.where(np.isnan(cutout_prelabel)) ] = 0.0\r\n    cutout_label = scipy.ndimage.label(cutout_prelabel)\r\n    cutout_preconv = pod['cutout'].copy()\r\n    cutout_preconv[ np.where(cutout_label==0) ] = 0.0\r\n\r\n    # If map contains no NaN pixels, smooth it the quick Scipy way\r\n    cutout_unconv = pod['cutout'].copy()\r\n    if np.where(np.isnan(cutout_preconv)==True)[0].shape[0]==0:\r\n        if verbose: print '['+pod['id']+'] No NaN pixels within coverage area; convolving using quick method.'\r\n        pod['cutout'] = scipy.ndimage.filters.gaussian_filter(cutout_preconv, kernel_fwhm)\r\n\r\n    # Else if map contains NaNs, do it the robust (but very-very slow, very-very memory intensive) Astropy way\r\n    else:\r\n        if verbose: print '['+pod['id']+'] NaN pixels within coverage area; convolving using slower NaN-compatible method.'\r\n        CAAPR.CAAPR_IO.MemCheck(pod, thresh_factor=20.0)\r\n        kernel = astropy.convolution.kernels.Gaussian2DKernel(kernel_fwhm)\r\n        pod['cutout'] = astropy.convolution.convolve_fft(pod['cutout'], kernel, nan_treatment='interpolate', normalize_kernel=True, allow_huge=True)\r\n        pod['cutout'][ np.where( np.isnan(cutout_unconv)==True ) ] = np.NaN\r\n\r\n\r\n\r\n    # Prepare arrays of transposed coordinates, to allow for rapid radial evaluating\r\n    if verbose: print '['+pod['id']+'] Constructing arrays of transposed radial coordinates.'\r\n    coords_trans = ChrisFuncs.Photom.AnnulusQuickPrepare(pod['cutout'], pod['opt_angle'], pod['centre_i'], pod['centre_j'])\r\n    i_trans, j_trans = coords_trans[0], coords_trans[1]\r\n\r\n    # To start with, to make new estimate of map noise that isn't contaminated by the target galaxy, by masking all pixels beyond semi-major axis suggested by contiguous significant pixels.\r\n    brute_mask = ChrisFuncs.Photom.EllipseMask(pod['cutout'], pod['semimaj_initial_pix'], pod['opt_axial_ratio'], pod['opt_angle'], pod['centre_i'], pod['centre_j'])\r\n    cutout_brute_masked = pod['cutout'].copy()\r\n    cutout_brute_masked[ np.where( brute_mask==1 ) ] = np.nan\r\n    cutout_clip_masked = ChrisFuncs.SigmaClip(cutout_brute_masked, tolerance=0.001, sigma_thresh=3.0, median=True)\r\n    pod['cutout_clip'] = cutout_clip_masked\r\n\r\n    # Now, perform a coarse brute force ckeck of a small number of radii over a wide range, to find rough location of edge of the source\r\n    if verbose: print '['+pod['id']+'] Finding size of target source with coarse analysis.'\r\n    ann_brute_range = np.linspace(0.75*pod['semimaj_initial_pix'], 2.25*pod['semimaj_initial_pix'], num=15)\r\n    ann_brute_range = ann_brute_range[::-1]\r\n    ann_brute_width = abs( ann_brute_range[1] - ann_brute_range[0] )\r\n    snr_success = False\r\n    for i in range(0, len(ann_brute_range)):\r\n        ann_brute_snr = AnnulusSNR([ann_brute_range[i]], pod, pod['cutout'], ann_brute_width, i_trans, j_trans, False)\r\n        if ann_brute_snr>2:\r\n            snr_success = True\r\n            #ann_brute_semimaj = ann_brute_range[i-1]\r\n            ann_bounds = [( ann_brute_range[ max(i-2,0) ], ann_brute_range[ min(i+1,len(ann_brute_range)-1) ] )]\r\n            if verbose: print '['+pod['id']+'] Course analysis finds that radial SNR=2 between semi-major axes of '+str(ChrisFuncs.FromGitHub.randlet.ToPrecision(ann_bounds[0][1]*pod['pix_arcsec'],4))+' and '+str(ChrisFuncs.FromGitHub.randlet.ToPrecision(ann_bounds[0][0]*pod['pix_arcsec'],4))+' arcseconds.'\r\n            break\r\n\r\n    # If SNR=2 threshold not reached, set to default minimum semi-major axis\r\n    if snr_success==False:\r\n        ann_bounds = [( ann_brute_range[i], np.floor(pod['cutout'].shape[0]/2.0) )]\r\n        opt_semimaj_pix = pod['beam_pix'] * 0.0\r\n        opt_semimaj_arcsec = opt_semimaj_pix * pod['pix_arcsec']\r\n        if verbose: print '['+pod['id']+'] No SNR=2 threshold found; hence reverting to default minimum aperture size of one beam-width.' #+str(ChrisFuncs.FromGitHub.randlet.ToPrecision(opt_semimaj_arcsec,4))+' arcseconds.'\r\n    else:\r\n\r\n        # Now use scipy differential evolution optimisation to find, with more precision, the semi-major axis at which annulus falls to a SNR of 2\r\n        ann_beams = 1.0\r\n        ann_width = np.ceil( ann_beams * pod['beam_pix'] )\r\n        if verbose: print '['+pod['id']+'] Refining size of target source with more precise analysis.'\r\n        ann_fit = scipy.optimize.differential_evolution(AnnulusSNR, ann_bounds, args=(pod, pod['cutout'], ann_width, i_trans, j_trans, True), maxiter=5, popsize=10, polish=False)\r\n        \"\"\"\r\n        ann_guess = ann_brute_semimaj\r\n        ann_fit = scipy.optimize.minimize(AnnulusSNR, ann_guess, args=(pod, pod['cutout'], ann_width, i_trans, j_trans))#method='Nelder-Mead', tol=1E-4, method='L-BFGS-B', bounds=[(pod['semimaj_initial_pix'], None)],\r\n        minimizer_kwargs = {'args':(pod, pod['cutout'], ann_width, i_trans, j_trans)}\r\n        ann_fit = scipy.optimize.basinhopping(AnnulusSNR, ann_guess, T=0.1, stepsize=5.0, minimizer_kwargs=minimizer_kwargs)\r\n        \"\"\"\r\n        # Extract results from fitting\r\n        opt_semimaj_pix = ann_fit['x'][0]\r\n        opt_semimaj_arcsec = opt_semimaj_pix * pod['pix_arcsec']\r\n        if verbose: print '['+pod['id']+'] Precision analysis finds that radial SNR=2 at semi-major axis of '+str(ChrisFuncs.FromGitHub.randlet.ToPrecision(opt_semimaj_arcsec,4))+' arcseconds.'\r\n        \"\"\"\r\n        # For small sources, default to minimum semi-major axis of one beam-width\r\n        if opt_semimaj_pix<(ann_beams*2.0):\r\n            opt_semimaj_pix = pod['beam_pix'] * 2.0\r\n            opt_semimaj_arcsec = opt_semimaj_pix * pod['pix_arcsec']\r\n            if verbose: print '['+pod['id']+'] Semi-major axis at which SNR=2 is less than one beam-width; hence reverting to two beam-width minimum value of '+str(ChrisFuncs.FromGitHub.randlet.ToPrecision(opt_semimaj_arcsec,4))+' arcseconds.'\r\n        \"\"\"\r\n    # Establish what fraction of the pixels inside a band's aperture are NaNs\r\n    pix_good = ChrisFuncs.Photom.EllipseQuickSum(pod['cutout'], opt_semimaj_pix, pod['opt_axial_ratio'], pod['opt_angle'], pod['centre_i'], pod['centre_j'], i_trans, j_trans)[1]\r\n    pix_tot = np.where( ChrisFuncs.Photom.EllipseMask(pod['cutout'], opt_semimaj_pix, pod['opt_axial_ratio'], pod['opt_angle'], pod['centre_i'], pod['centre_j']) == 1 )[0].shape[0]\r\n    if pix_tot==0.0:\r\n        pix_good_frac = 0.0\r\n    else:\r\n        pix_good_frac = float(pix_good) / float(pix_tot)\r\n\r\n    # Before final reporting, tidy up and return to unconvolved cutout\r\n    pod['cutout'] = cutout_unconv\r\n    del(cutout_unconv)\r\n    gc.collect()\r\n\r\n    # If more than 10% of the pixels in the aperture are NaNs, report default values for aperture dimensions\r\n    if pix_good_frac<0.9:\r\n        opt_semimaj_pix = pod['beam_pix'] * 1.0\r\n        opt_semimaj_arcsec = opt_semimaj_pix * pod['pix_arcsec']\r\n        if verbose: print '['+pod['id']+'] More than 10% of pixels in fitted aperture are NaNs; hence reverting to default minimum aperture size of one beam-width.' #+str(opt_semimaj_arcsec)[:7]+' arcseconds.'\r\n        pod['opt_semimaj_arcsec'] = opt_semimaj_arcsec\r\n        pod['opt_axial_ratio'] = 1.0\r\n        pod['opt_angle'] = 0.0\r\n\r\n    # If dimensions are otherwise default, report to pod\r\n    if abs( opt_semimaj_arcsec**2.0 - (0.5*band_dict['beam_arcsec'])**2.0 )**0.5<=0.0:\r\n        opt_semimaj_pix = pod['beam_pix'] * 1.0\r\n        pod['opt_semimaj_arcsec'] = opt_semimaj_pix * pod['pix_arcsec']\r\n        pod['opt_axial_ratio'] = 1.0\r\n        pod['opt_angle'] = 0.0\r\n\r\n    # Else deconvolve aperture semi-major axis with beam, by subtracting in quadrature, and record dimensions to pod\r\n    else:\r\n        adj_semimaj_arcsec = 0.5 * np.abs( (2.0*opt_semimaj_arcsec)**2.0 - band_dict['beam_arcsec']**2.0 )**0.5\r\n        opt_semimin_arcsec = opt_semimaj_arcsec / pod['opt_axial_ratio']\r\n        adj_semimin_arcsec = 0.5 * np.abs( (2.0*opt_semimin_arcsec)**2.0 - band_dict['beam_arcsec']**2.0 )**0.5\r\n        adj_ax_ratio = adj_semimaj_arcsec / adj_semimin_arcsec\r\n        pod['opt_semimaj_arcsec'] = adj_semimaj_arcsec\r\n        pod['opt_semimaj_pix'] = adj_semimaj_arcsec / pod['pix_arcsec']\r\n        pod['opt_axial_ratio'] = adj_ax_ratio\r\n\r\n    # Clean up, then return results\r\n    gc.collect()\r\n    return pod\r\n\r\n\r\n\r\n\r\n\r\n# Define function that combines a set of apertures for a given source into\r\ndef CombineAperture(aperture_output_list, source_dict, kwargs_dict):\r\n    if kwargs_dict['verbose']: print '['+source_dict['name']+'] Combining individual apertures from all bands to generate final aperture.'\r\n\r\n\r\n\r\n    # Extract various aperture values\r\n    semimaj_arcsec_list = []\r\n    axial_ratio_list = []\r\n    angle_list = []\r\n    for aperture in aperture_output_list:\r\n        if aperture==False:\r\n            continue\r\n        try:\r\n            semimaj_arcsec_list.append( aperture['opt_semimaj_arcsec'] )\r\n            axial_ratio_list.append( aperture['opt_axial_ratio'] )\r\n            angle_list.append( aperture['opt_angle'] )\r\n        except:\r\n            pdb.set_trace()\r\n\r\n    # Check to see if any bands have been designated for aperture consideration\r\n    if np.nanmax(np.array(axial_ratio_list)) == 0.0:\r\n        raise Exception('No usable apertures found; probably because no bands have consider_aperture set to True in the bands table')\r\n\r\n    # Find largest semi-major axis, and use to define size of enclosisity array (which will have pixels some fraction the size of the smallest semi-major axis)\r\n    semimaj_max = np.nanmax(semimaj_arcsec_list) #semimaj_min = np.nanmin(semimaj_arcsec_list)\r\n    ap_array_pix_size = 0.005 * semimaj_max\r\n    ap_array_scale = int( np.round( semimaj_max / ap_array_pix_size ) )\r\n    ap_array = np.zeros([ int(1+(2.2*ap_array_scale)), int(1+(2.2*ap_array_scale)) ])\r\n    centre_i, centre_j = 1+(1.1*ap_array_scale), 1+(1.1*ap_array_scale)\r\n    semimaj_pix_list = np.array(semimaj_arcsec_list) / ap_array_pix_size\r\n\r\n    # Loop over each aperture, adding to enclosisity array\r\n    for a in range(0, len(semimaj_pix_list)):\r\n        if np.isnan(semimaj_pix_list[a])==False:\r\n            ap_mask = ChrisFuncs.EllipseMask(ap_array, semimaj_pix_list[a], axial_ratio_list[a], angle_list[a], centre_i, centre_j)\r\n            ap_array[ np.where( ap_mask==1 ) ] += 1\r\n    #ChrisFuncs.Cutout(ap_array, '/home/saruman/spx7cjc/DustPedia/Ap.fits')\r\n\r\n    # Find ellipse that traces edge of enclosisity region\r\n    cont_rad_initial_pix = 2.0#( semimaj_min / np.nanmax(axial_ratio_list) ) / ap_array_pix_size\r\n    cont_array = ChrisFuncs.Photom.ContiguousPixels(ap_array, cont_rad_initial_pix, centre_i, centre_j, 0.1)\r\n    cont_x = ((np.where(cont_array==1))[1])\r\n    cont_y = ((np.where(cont_array==1))[0])\r\n    if cont_x.shape[0]>10:\r\n        try:\r\n            cont_ellipse = ChrisFuncs.Photom.EllipseFit(cont_x, cont_y)\r\n            cont_axial_ratio = max(cont_ellipse[1]) / min(cont_ellipse[1])\r\n            cont_angle = cont_ellipse[2]\r\n            cont_semimaj_pix = max([ cont_ellipse[1].max(), np.nanmax(semimaj_pix_list) ])\r\n        except:\r\n            cont_axial_ratio = 1.0\r\n            cont_angle = 0.0\r\n            cont_semimaj_pix = max([ cont_ellipse[1].max(), np.nanmax(semimaj_pix_list) ])\r\n    else:\r\n        pdb.set_trace()\r\n        cont_axial_ratio = 1.0\r\n        cont_angle = 0.0\r\n        cont_semimaj_pix = 2.0 * np.max('beam_width')\r\n\r\n    # Convert final semi-major axis back to arcsec and apply expanson factor, then clean garbage and return results\r\n    if isinstance(kwargs_dict['expansion_factor'], float) or isinstance(kwargs_dict['expansion_factor'], int):\r\n        expansion_facor = float(kwargs_dict['expansion_factor'])\r\n    else:\r\n        expansion_facor = 1.0\r\n    cont_semimaj_arcsec = cont_semimaj_pix * ap_array_pix_size * expansion_facor\r\n\r\n    # If final aperture is smaller than defined minimum aperture, switch to defined minimum\r\n    if cont_semimaj_arcsec<source_dict['fitting_min_semimaj_arcsec']:\r\n        if kwargs_dict['verbose']: print '['+source_dict['name']+'] Fitted aperture is smaller than minimum permitted aperture size; reverting to minimum permitted aperture size.'\r\n        cont_semimaj_arcsec = source_dict['fitting_min_semimaj_arcsec']\r\n        cont_axial_ratio = 1.0\r\n        cont_angle = 0.0\r\n\r\n    # Clean garbage and return results\r\n    if kwargs_dict['verbose']: print '['+source_dict['name']+'] Final ellipse semi-major axis: '+str(ChrisFuncs.FromGitHub.randlet.ToPrecision(cont_semimaj_arcsec,4))+' arcsec; final ellipse angle: '+str(ChrisFuncs.FromGitHub.randlet.ToPrecision(cont_angle,4))+' '+' degrees; final ellipse axial ratio: '+str(ChrisFuncs.FromGitHub.randlet.ToPrecision(cont_axial_ratio,4))+'.'\r\n    gc.collect()\r\n    return [cont_semimaj_arcsec, cont_axial_ratio, cont_angle, ap_array]\r\n\r\n\r\n\r\n\r\n# Define function to check that all bands which were supposed to undergo photometry have done so\r\ndef ApertureCheck(aperture_attempts, aperture_output_list, source_dict, bands_dict, kwargs_dict):\r\n\r\n\r\n\r\n    # Compare number of bands with photometry returned to number of bands for which photometry was requested\r\n    aperture_limit = 5\r\n    if len(aperture_output_list)==len(bands_dict.keys()):\r\n        aperture_attempts = 'Success'\r\n        return aperture_attempts\r\n\r\n    # Check how many attempts have been made so far, and proceed accordingly\r\n    else:\r\n        aperture_attempts += 1\r\n        time.sleep(30.0)\r\n        if aperture_attempts>=aperture_limit:\r\n            print '['+source_dict['name']+'] Aperture fitting failed '+str(aperture_limit)+' times in succession; suggest debugging.'\r\n            pdb.set_trace()\r\n            raise Exception('Aperture fitting failed '+str(aperture_limit)+' times in succession; suggest debugging.')\r\n        else:\r\n            return aperture_attempts\r\n\r\n\r\n\r\n\r\n\r\n# Define function that check is present band is to be excluded from aperture-fitting\r\ndef ExcludeAperture(pod, source_dict, band_dict, kwargs_dict):\r\n\r\n\r\n\r\n    # Check if the aperture exclusion field actually contains characters; if so, make list of entries, and if not, record an empty list\r\n    if isinstance(source_dict['aperture_bands_exclude'], basestring):\r\n        aperture_bands_exclude = source_dict['aperture_bands_exclude'].split(';')\r\n    elif source_dict['aperture_bands_exclude']==False:\r\n        aperture_bands_exclude = []\r\n\r\n    # If present band is to be excluded, note this fact in pod\r\n    if (band_dict['consider_aperture']==False) or (band_dict['band_name'] in aperture_bands_exclude):\r\n        pod['band_exclude'] = True\r\n\r\n    # If exclusion not required, record and return\r\n    else:\r\n        pod['band_exclude'] = False\r\n        return pod\r\n\r\n    # Set generic null aperture properties\r\n    pod['opt_axial_ratio'] = 1.0\r\n    pod['opt_angle'] = 0.0\r\n    pod['opt_semimaj_arcsec'] = 0.0#( (2.0*band_dict['beam_arcsec'])**2.0 - band_dict['beam_arcsec']**2.0 )**0.5\r\n    pod['opt_semimaj_pix'] = 0.0#pod['opt_semimaj_arcsec'] / pod['pix_arcsec']\r\n    pod['semimaj_initial_pix'] = 0.0#pod['opt_semimaj_arcsec'] / pod['pix_arcsec']\r\n\r\n    # Create aperture output dictionry containing null values\r\n    output_dict = {'band_name':band_dict['band_name'],\r\n                   'opt_semimaj_arcsec':pod['opt_semimaj_arcsec'],\r\n                   'opt_axial_ratio':pod['opt_axial_ratio'],\r\n                   'opt_angle':pod['opt_angle']}\r\n    pod['null_output_dict'] = output_dict\r\n\r\n    # Return pod\r\n    if pod['verbose']: print '['+pod['id']+'] No aperture fitting required from this source in this band.'\r\n    return pod\r\n\r\n\r\n\r\n\r\n\r\n# Define function that handles bands excluded from aperture fitting, so that they appear in thumbnail grid\r\ndef ExcludedThumb(source_dict, bands_dict, kwargs_dict, aperture_list, aperture_combined):\r\n\r\n\r\n\r\n    # If thumbnails not required, end immediately\r\n    if kwargs_dict['thumbnails']==False:\r\n        return\r\n\r\n    # Check if the aperture exclusion field for this source actually contains characters; if so make list of entries, else produce empty list\r\n    if isinstance(source_dict['aperture_bands_exclude'], basestring):\r\n        aperture_bands_exclude = source_dict['aperture_bands_exclude'].split(';')\r\n    else:\r\n        aperture_bands_exclude = []\r\n\r\n    # Now consider bands which have been assigned a blancket aperture exclusion\r\n    [ aperture_bands_exclude.append(band) for band in bands_dict.keys() if bands_dict[band]['consider_aperture']==False ]\r\n    aperture_bands_exclude = list( set( aperture_bands_exclude ) )\r\n    aperture_bands_exclude = np.array(aperture_bands_exclude)[ np.in1d( aperture_bands_exclude, bands_dict.keys() ) ]\r\n\r\n    # If no bands require processing here, end immediately; else prepare to loop over bands that do require processing\r\n    if len(aperture_bands_exclude)==0:\r\n        return\r\n    else:\r\n        if kwargs_dict['verbose']: print '['+source_dict['name']+'] Preparing thumbnail data for bands excluded from aperture-fitting.'\r\n        random.shuffle(aperture_bands_exclude)\r\n\r\n    # Find largest beam size and outer annulus size, and hence work out thumbnail size that will contain the largest beam-convolved aperture\r\n    beam_arcsec_max = 0.0\r\n    outer_annulus_max = 0.0\r\n    pix_arcsec_max = 0.0\r\n    for band_name in bands_dict:\r\n        in_fitspath, file_found = CAAPR.CAAPR_Pipeline.FilePrelim(source_dict, bands_dict[band_name], kwargs_dict)\r\n        if file_found!=True:\r\n            continue\r\n        band_pix_matrix = astropy.wcs.WCS(astropy.io.fits.getheader(in_fitspath)).pixel_scale_matrix\r\n        band_pix_arcsec = 3600.0 * np.sqrt( np.min(np.abs(band_pix_matrix))**2.0 + np.max(np.abs(band_pix_matrix))**2.0 )\r\n        if band_pix_arcsec>pix_arcsec_max:\r\n            pix_arcsec_max = band_pix_arcsec\r\n        if bands_dict[band_name]['beam_arcsec']>beam_arcsec_max:\r\n            beam_arcsec_max = bands_dict[band_name]['beam_arcsec']\r\n        if bands_dict[band_name]['annulus_outer']>outer_annulus_max:\r\n            outer_annulus_max = bands_dict[band_name]['annulus_outer']\r\n    thumb_rad_arcsec = np.ceil( 1.0 * pix_arcsec_max ) + np.ceil( 1.75 * 0.5 * np.sqrt( (outer_annulus_max*2.0*aperture_combined[0])**2.0 + (beam_arcsec_max)**2.0 ) )\r\n    source_dict['thumb_rad_arcsec'] = thumb_rad_arcsec\r\n\r\n    # In standard operation, process multiple sources in parallel\r\n    if kwargs_dict['parallel']==True:\r\n        ex_ap_pool = mp.Pool(processes=kwargs_dict['n_proc'])\r\n        for band in aperture_bands_exclude:\r\n            ex_ap_pool.apply_async( ExcludedSubpipelineAperture, args=(aperture_combined, source_dict, bands_dict[band], kwargs_dict,) )\r\n        ex_ap_pool.close()\r\n        ex_ap_pool.join()\r\n        del(ex_ap_pool)\r\n\r\n    # If parallelisation is disabled, process sources one-at-a-time\r\n    elif kwargs_dict['parallel']==False:\r\n        for band in aperture_bands_exclude:\r\n            ExcludedSubpipelineAperture(aperture_combined, source_dict, bands_dict[band], kwargs_dict)\r\n\r\n\r\n\r\n\r\n\r\n# Define 'pseudo-dummy' version of the aperture sub-pipeline, to run excluded bands through\r\ndef ExcludedSubpipelineAperture(aperture_combined, source_dict, band_dict, kwargs_dict_inviolate):\r\n    source_id = source_dict['name']+'_'+band_dict['band_name']\r\n\r\n    # Make deep copy of kwargs dict, to disable verbosity\r\n    kwargs_dict = copy.deepcopy(kwargs_dict_inviolate)\r\n    kwargs_dict['verbose'] = False\r\n\r\n    # Run through initial stages of aperture sub-pipeline, as would occur usually\r\n    in_fitspath_prelim, file_found = CAAPR.CAAPR_Pipeline.FilePrelim(source_dict, band_dict, kwargs_dict)\r\n    if file_found == False:\r\n        return\r\n    pod = CAAPR.CAAPR_Pipeline.PodInitiate(in_fitspath_prelim, source_dict, band_dict, kwargs_dict)\r\n    pod = CAAPR.CAAPR_Pipeline.MapPrelim(pod, source_dict, band_dict)\r\n    if pod['within_bounds']==False:\r\n        return\r\n    CAAPR.CAAPR_IO.MemCheck(pod)\r\n\r\n    # Use thumbnail cutout function to create a cutout that's only as large as it needs to be for the thumbnail grid\r\n    CAAPR.CAAPR_IO.ThumbCutout(source_dict, band_dict, kwargs_dict, pod['in_fitspath'], source_dict['thumb_rad_arcsec'])\r\n\r\n    # Rename thumbnail cutout, and make it the 'active' map by repeating necessary processing\r\n    thumb_output = os.path.join( kwargs_dict['temp_dir_path'], 'Processed_Maps', source_id+'_Thumbnail.fits' )\r\n    pod['in_fitspath'] = thumb_output\r\n    in_fitsdata = astropy.io.fits.open(pod['in_fitspath'])\r\n    pod['in_image'] = in_fitsdata[0].data\r\n    pod['in_header'] = in_fitsdata[0].header\r\n    in_fitsdata.close()\r\n    pod['in_wcs'] = astropy.wcs.WCS(pod['in_header'])\r\n    pod['in_fitspath_size'] = float(os.stat(pod['in_fitspath']).st_size)\r\n    thumb_centre_xy = pod['in_wcs'].wcs_world2pix( np.array([[ source_dict['ra'], source_dict['dec'] ]]), 0 )\r\n    pod['centre_i'], pod['centre_j'] = float(thumb_centre_xy[0][1]), float(thumb_centre_xy[0][0])\r\n\r\n    # Run thumbnail cutout thorugh AstroMagic, save result, and delete temporary files\r\n    if kwargs_dict['starsub']==True:\r\n        pod['cutout'] = pod['in_image'].copy()\r\n        pod['starsub_thumbnail'] = True\r\n        pod = CAAPR.CAAPR_AstroMagic.Magic(pod, source_dict, band_dict, kwargs_dict)\r\n        os.remove(thumb_output)\r\n        magic_output = os.path.join(kwargs_dict['temp_dir_path'], 'AstroMagic', band_dict['band_name'], source_dict['name']+'_'+band_dict['band_name']+'_StarSub.fits')\r\n        if os.path.exists(magic_output):\r\n            os.remove(magic_output)\r\n    else:\r\n        pod['cutout'] = pod['in_image'].copy()\r\n        os.remove(thumb_output)\r\n\r\n    # Save resulting cutout\r\n    astropy.io.fits.writeto(os.path.join(kwargs_dict['temp_dir_path'],'Processed_Maps',source_id+'.fits'), pod['cutout'], header=pod['in_header'], overwrite=True)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "f9d29a5c5f6d70185a28b3db22aec177fece6a7c", "size": 30546, "ext": "py", "lang": "Python", "max_stars_repo_path": "CAAPR/CAAPR_Aperture/CAAPR_Aperture.py", "max_stars_repo_name": "wdobbels/CAAPR", "max_stars_repo_head_hexsha": "50d0b32642a61af614c22f1c6dc3c4a00a1e71a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2016-05-20T21:56:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T21:09:48.000Z", "max_issues_repo_path": "CAAPR/CAAPR_Aperture/CAAPR_Aperture.py", "max_issues_repo_name": "wdobbels/CAAPR", "max_issues_repo_head_hexsha": "50d0b32642a61af614c22f1c6dc3c4a00a1e71a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-03-21T16:10:04.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-22T17:21:56.000Z", "max_forks_repo_path": "CAAPR/CAAPR_Aperture/CAAPR_Aperture.py", "max_forks_repo_name": "wdobbels/CAAPR", "max_forks_repo_head_hexsha": "50d0b32642a61af614c22f1c6dc3c4a00a1e71a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-19T16:17:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-19T16:17:17.000Z", "avg_line_length": 50.4059405941, "max_line_length": 376, "alphanum_fraction": 0.6904668369, "include": true, "reason": "import numpy,import scipy,import astropy", "num_tokens": 8044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.16917437297694204}}
{"text": "from __future__ import annotations\n# dh import\ntry:\n    from dh.udfdh import UDFDH\n    from dh.dhutil import calc_batch_size, gen_batch, gen_shl_batch, tot_size, timing\n    from dh.grad.rdfdh import get_H_1_ao, get_S_1_ao, generator_L_1\n    from dh.grad.rdfdh import Gradients as RGradients\nexcept ImportError:\n    from pyscf.dh.udfdh import UDFDH\n    from pyscf.dh.dhutil import calc_batch_size, gen_batch, gen_shl_batch, tot_size, timing\n    from pyscf.dh.grad.rdfdh import get_H_1_ao, get_S_1_ao, generator_L_1\n    from pyscf.dh.grad.rdfdh import Gradients as RGradients\n# pyscf import\nfrom pyscf import gto, lib, df\nfrom pyscf.df.grad.rhf import _int3c_wrapper as int3c_wrapper\ntry:\n    from pyscf.dftd3 import itrf\nexcept ImportError:\n    print('''Warning: dftd3 not found. You cannot using functionals with \"-D3\" suffix \n             before installing pyscf-dftd3. See https://github.com/pyscf/dftd3 and\n             https://github.com/ajz34/dh#dftd3-extension ''') \n# other import\nimport numpy as np\nimport itertools\nimport ctypes\n\neinsum = lib.einsum\nα, β = 0, 1\nαα, αβ, ββ = 0, 1, 2\n\n\n@timing\ndef get_gradient_jk(dfobj: df.DF, C, D, D_r, Y_mo, cx, cx_n, max_memory=2000):\n    mol, aux = dfobj.mol, dfobj.auxmol\n    natm, nao, nmo, nocc = mol.natm, mol.nao, C.shape[-1], mol.nelec\n    mocc = max(nocc)\n    naux = Y_mo[0].shape[0]\n    # this algorithm asserts naux = aux.nao, i.e. no linear dependency in auxiliary basis\n    assert naux == aux.nao\n    so = slice(0, nocc[α]), slice(0, nocc[β])\n\n    D_r_symm = (D_r + D_r.swapaxes(-1, -2)) / 2\n    D_r_ao = einsum(\"sup, spq, svq -> suv\", C, D_r_symm, C)\n    D_mo = np.zeros((2, nmo, nmo))\n    for σ in (α, β):\n        for i in range(nocc[σ]):\n            D_mo[σ, i, i] = 1\n\n    Y_dot_D, Y_dot_D_r = np.zeros((2, naux)), np.zeros((2, naux))\n    nbatch = calc_batch_size(nmo**2, max_memory)\n    for σ in (α, β):\n        for i in range(nocc[σ]):\n            Y_dot_D[σ] += Y_mo[σ][:, i, i]\n        for saux in gen_batch(0, naux, nbatch):\n            Y_dot_D_r[σ][saux] = einsum(\"Ppq, pq -> P\", Y_mo[σ][saux], D_r_symm[σ])\n\n    Y_ip = [np.asarray(Y_mo[σ][:, so[σ]]) for σ in (α, β)]\n    L_inv, L_1_gen = generator_L_1(aux)\n    int3c2e_ip1_gen = int3c_wrapper(mol, aux, \"int3c2e_ip1\", \"s1\")\n    int3c2e_ip2_gen = int3c_wrapper(mol, aux, \"int3c2e_ip2\", \"s1\")\n    C0 = [C[σ][:, so[σ]] for σ in (α, β)]\n    D1 = [cx * D_r_symm[σ] + 0.5 * cx_n * D_mo[σ] for σ in (α, β)]\n    C1 = [C[σ] @ D1[σ] for σ in (α, β)]\n\n    grad_contrib = np.zeros((natm, 3))\n    for A in range(natm):\n        shA0, shA1, _, _ = mol.aoslice_by_atom()[A]\n        shA0a, shA1a, _, _ = aux.aoslice_by_atom()[A]\n\n        Y_1_mo_D_r = [np.zeros((3, naux, nocc[σ], nmo)) for σ in (α, β)]\n        Y_1_dot_D, Y_1_dot_D_r = np.zeros((2, 3, naux)), np.zeros((2, 3, naux))\n\n        pre_flop = tot_size(Y_1_mo_D_r, Y_ip, Y_1_dot_D, Y_1_dot_D_r)\n        nbatch = calc_batch_size(3*(nao+mocc)*naux, max_memory, pre_flop)\n        for shU0, shU1, U0, U1 in gen_shl_batch(mol, nbatch, shA0, shA1):\n            su = slice(U0, U1)\n            int3c2e_ip1 = int3c2e_ip1_gen((shU0, shU1, 0, mol.nbas, 0, aux.nbas))\n            for σ in (α, β):\n                Y_1_mo_D_r[σ] -= einsum(\"tuvQ, PQ, ui, vp -> tPip\", int3c2e_ip1, L_inv, C0[σ][su], C1[σ])\n                Y_1_mo_D_r[σ] -= einsum(\"tuvQ, PQ, up, vi -> tPip\", int3c2e_ip1, L_inv, C1[σ][su], C0[σ])\n                Y_1_dot_D[σ] -= 2 * einsum(\"tuvQ, PQ, uv -> tP\", int3c2e_ip1, L_inv, D[σ][su])\n                Y_1_dot_D_r[σ] -= 2 * einsum(\"tuvQ, PQ, uv -> tP\", int3c2e_ip1, L_inv, D_r_ao[σ][su])\n\n        nbatch = calc_batch_size(3*nao*(nao+mocc), max_memory, pre_flop)\n        for shP0, shP1, P0, P1 in gen_shl_batch(aux, nbatch, shA0a, shA1a):\n            sp = slice(P0, P1)\n            int3c2e_ip2 = int3c2e_ip2_gen((0, mol.nbas, 0, mol.nbas, shP0, shP1))\n            for σ in (α, β):\n                Y_1_mo_D_r[σ] -= einsum(\"tuvQ, PQ, ui, vp -> tPip\", int3c2e_ip2, L_inv[:, sp], C0[σ], C1[σ])\n                Y_1_dot_D[σ] -= einsum(\"tuvQ, PQ, uv -> tP\", int3c2e_ip2, L_inv[:, sp], D[σ])\n                Y_1_dot_D_r[σ] -= einsum(\"tuvQ, PQ, uv -> tP\", int3c2e_ip2, L_inv[:, sp], D_r_ao[σ])\n\n        L_1 = L_1_gen(A)\n        L_1_dot_inv = einsum(\"tRQ, PR -> tPQ\", L_1, L_inv)\n        for σ in (α, β):\n            Y_1_mo_D_r[σ] -= einsum(\"Qiq, qp, tPQ -> tPip\", Y_ip[σ], D1[σ], L_1_dot_inv)\n            Y_1_dot_D[σ] -= einsum(\"Q, tPQ -> tP\", Y_dot_D[σ], L_1_dot_inv)\n            Y_1_dot_D_r[σ] -= einsum(\"Q, tPQ -> tP\", Y_dot_D_r[σ], L_1_dot_inv)\n            # RI-K contribution\n            grad_contrib[A] += - 2 * einsum(\"Pip, tPip -> t\", Y_ip[σ], Y_1_mo_D_r[σ])\n\n        # RI-J contribution\n        for σ, ς in itertools.product((α, β), (α, β)):\n            grad_contrib[A] += (\n                + einsum(\"P, tP -> t\", Y_dot_D[σ], Y_1_dot_D_r[ς])\n                + einsum(\"P, tP -> t\", Y_dot_D_r[σ], Y_1_dot_D[ς])\n                + einsum(\"P, tP -> t\", Y_dot_D[σ], Y_1_dot_D[ς]))\n    return grad_contrib\n\n\nclass Gradients(UDFDH, RGradients):\n\n    def __init__(self, mol: gto.Mole, *args, skip_construct=False, **kwargs):\n        if not skip_construct:\n            super(Gradients, self).__init__(mol, *args, **kwargs)\n        # results\n        self.grad_jk = NotImplemented\n        self.grad_gga = NotImplemented\n        self.grad_pt2 = NotImplemented\n        self.grad_enfunc = NotImplemented\n        self.grad_tot = NotImplemented\n        self.de = NotImplemented\n\n    @timing\n    def prepare_H_1(self):\n        H_1_ao = get_H_1_ao(self.mol)\n        H_1_mo = np.array([einsum(\"up, Auv, vq -> Apq\", self.C[σ], H_1_ao, self.C[σ]) for σ in (α, β)])\n        self.tensors.create(\"H_1_ao\", H_1_ao)\n        self.tensors.create(\"H_1_mo\", H_1_mo)\n\n    @timing\n    def prepare_S_1(self):\n        S_1_ao = get_S_1_ao(self.mol)\n        S_1_mo = np.array([einsum(\"up, Auv, vq -> Apq\", self.C[σ], S_1_ao, self.C[σ]) for σ in (α, β)])\n        self.tensors.create(\"S_1_ao\", S_1_ao)\n        self.tensors.create(\"S_1_mo\", S_1_mo)\n\n    def prepare_gradient_jk(self):\n        D_r = self.tensors.load(\"D_r\")\n        Y_mo = [self.tensors[\"Y_mo_jk\" + str(σ)] for σ in (α, β)]\n        # a special treatment\n        cx_n = self.cx_n if self.xc_n else self.cx\n        self.grad_jk = get_gradient_jk(self.df_jk, self.C, self.D, D_r, Y_mo, self.cx, cx_n, self.get_memory())\n\n    @timing\n    def prepare_gradient_gga(self):\n        tensors = self.tensors\n        if \"rho\" not in tensors:\n            self.grad_gga = 0\n            return self\n        # --- LAZY CODE ---\n        from pyscf import grad, hessian\n        ni, mol, grids = self.ni, self.mol, self.grids\n        natm = mol.natm\n        C, D = self.C, self.D\n        grad_contrib = np.zeros((natm, 3))\n\n        xc = self.xc_n if self.xc_n else self.xc\n        if self.ni._xc_type(xc) == \"GGA\":  # energy functional contribution\n            veff_1_gga = grad.uks.get_vxc(ni, mol, grids, xc, D)[1]\n            for A, (_, _, A0, A1) in enumerate(mol.aoslice_by_atom()):\n                grad_contrib[A] += 2 * einsum(\"stuv, suv -> t\", veff_1_gga[:, :, A0:A1], D[:, A0:A1])\n\n        if self.ni._xc_type(self.xc) == \"GGA\":  # reference functional skeleton fock derivative contribution\n            D_r = tensors.load(\"D_r\")\n            D_r_symm = (D_r + D_r.swapaxes(-1, -2)) / 2\n            D_r_ao = einsum(\"sup, spq, svq -> suv\", C, D_r_symm, C)\n\n            F_1_ao_dfa = np.array(hessian.uks._get_vxc_deriv1(self.mf_s.Hessian(), C, self.mo_occ, 2000))\n            grad_contrib += einsum(\"suv, sAtuv -> At\", D_r_ao, F_1_ao_dfa)\n\n        self.grad_gga = grad_contrib\n        return self\n\n    @timing\n    def prepare_gradient_pt2(self):\n        tensors = self.tensors\n        C, D, e = self.C, self.D, self.e\n        mol, aux_ri = self.mol, self.aux_ri\n        natm, nao, nmo, nocc, nvir, naux = mol.natm, self.nao, self.nmo, self.nocc, self.nvir, self.df_ri.get_naoaux()\n        mocc, mvir = max(nocc), max(nvir)\n        # this algorithm asserts naux = aux.nao, i.e. no linear dependency in auxiliary basis\n        assert naux == aux_ri.nao\n        so, sv, sa = self.so, self.sv, self.sa\n\n        D_r = tensors.load(\"D_r\")\n        H_1_mo = tensors.load(\"H_1_mo\")\n        grad_corr = einsum(\"spq, sApq -> A\", D_r, H_1_mo)\n        if not self.eval_pt2:\n            grad_corr.shape = (natm, 3)\n            self.grad_pt2 = grad_corr\n            return\n\n        W_I = tensors.load(\"W_I\")\n        W_II = - einsum(\"spq, sq -> spq\", D_r, e)\n        W_III_tmp = self.Ax0_Core(so, so, sa, sa)(D_r)\n        W = W_I + W_II\n        for σ in (α, β):\n            W[σ][so[σ], so[σ]] += - 0.5 * W_III_tmp[σ]\n        W_ao = einsum(\"sup, spq, svq -> suv\", C, W, C)\n        S_1_ao = tensors.load(\"S_1_ao\")\n        grad_corr += np.einsum(\"suv, Auv -> A\", W_ao, S_1_ao)\n        grad_corr.shape = (natm, 3)\n\n        L_inv, L_1_gen = generator_L_1(aux_ri)\n        int3c2e_ip1_gen = int3c_wrapper(mol, aux_ri, \"int3c2e_ip1\", \"s1\")\n        int3c2e_ip2_gen = int3c_wrapper(mol, aux_ri, \"int3c2e_ip2\", \"s1\")\n        Y_ia_ri = [np.asarray(tensors[\"Y_mo_ri\" + str(σ)][:, so[σ], sv[σ]]) for σ in (α, β)]\n        G_ia_ri = [tensors.load(\"G_ia_ri\" + str(σ)) for σ in (α, β)]\n\n        for A in range(natm):\n            L_1_ri = L_1_gen(A)\n            Y_1_ia_ri = [np.zeros((3, naux, nocc[σ], nvir[σ])) for σ in (α, β)]\n            shA0, shA1, _, _ = mol.aoslice_by_atom()[A]\n            shA0a, shA1a, _, _ = aux_ri.aoslice_by_atom()[A]\n\n            nbatch = calc_batch_size(3*(nao+mocc)*naux, self.get_memory(), tot_size(Y_1_ia_ri))\n            for shU0, shU1, U0, U1 in gen_shl_batch(mol, nbatch, shA0, shA1):\n                su = slice(U0, U1)\n                int3c2e_ip1 = int3c2e_ip1_gen((shU0, shU1, 0, mol.nbas, 0, aux_ri.nbas))\n                for σ in (α, β):\n                    Y_1_ia_ri[σ] -= einsum(\"tuvQ, PQ, ui, va -> tPia\", int3c2e_ip1, L_inv, C[σ][su, so[σ]], C[σ][:, sv[σ]])\n                    Y_1_ia_ri[σ] -= einsum(\"tuvQ, PQ, ua, vi -> tPia\", int3c2e_ip1, L_inv, C[σ][su, sv[σ]], C[σ][:, so[σ]])\n\n            nbatch = calc_batch_size(3*nao*(nao+mocc), self.get_memory(), tot_size(Y_1_ia_ri))\n            for shP0, shP1, P0, P1 in gen_shl_batch(aux_ri, nbatch, shA0a, shA1a):\n                sp = slice(P0, P1)\n                int3c2e_ip2 = int3c2e_ip2_gen((0, mol.nbas, 0, mol.nbas, shP0, shP1))\n                for σ in (α, β):\n                    Y_1_ia_ri[σ] -= einsum(\"tuvQ, PQ, ui, va -> tPia\", int3c2e_ip2, L_inv[:, sp], C[σ][:, so[σ]], C[σ][:, sv[σ]])\n\n            for σ in (α, β):\n                Y_1_ia_ri[σ] -= einsum(\"Qia, tRQ, PR -> tPia\", Y_ia_ri[σ], L_1_ri, L_inv)\n                grad_corr[A] += einsum(\"Pia, tPia -> t\", G_ia_ri[σ], Y_1_ia_ri[σ])\n        self.grad_pt2 = grad_corr\n\n    @timing\n    def prepare_gradient_enfunc(self):\n        tensors = self.tensors\n        natm = self.mol.natm\n        Co, eo, D = self.Co, self.eo, self.D\n        so = self.so\n\n        grad_contrib = self.mf_s.Gradients().grad_nuc()\n        grad_contrib.shape = (natm * 3,)\n\n        H_1_ao = tensors.load(\"H_1_ao\")\n        S_1_mo = tensors.load(\"S_1_mo\")\n\n        grad_contrib += np.einsum(\"Auv, suv -> A\", H_1_ao, D, optimize=True)  # TODO check PySCF lib.einsum why fails\n        if self.xc_n is None:\n            for σ in (α, β):\n                grad_contrib -= np.einsum(\"Ai, i -> A\", S_1_mo[σ][:, so[σ], so[σ]].diagonal(0, -1, -2), eo[σ])\n        else:\n            # TODO see whether get_fock could use mo_coeff to accelearate RI-K\n            F_0_ao_n = self.mf_n.get_fock(dm=D)\n            nc_F_0_ij = [(Co[σ].T @ F_0_ao_n[σ] @ Co[σ]) for σ in (α, β)]\n            for σ in (α, β):\n                grad_contrib -= einsum(\"Aij, ij -> A\", S_1_mo[σ][:, so[σ], so[σ]], nc_F_0_ij[σ])\n        grad_contrib.shape = (natm, 3)\n\n        # handle dftd3 situation\n        mol = self.mol\n        if \"D3\" in self.xc_add:\n            drv = itrf.libdftd3.wrapper_params\n            params = np.asarray(self.xc_add[\"D3\"][0], order=\"F\")\n            version = self.xc_add[\"D3\"][1]\n            coords = np.asarray(mol.atom_coords(), order=\"F\")\n            itype = np.asarray(mol.atom_charges(), order=\"F\")\n            edisp = np.zeros(1)\n            grad = np.zeros((mol.natm, 3))\n            drv(\n                ctypes.c_int(mol.natm),  # natoms\n                coords.ctypes.data_as(ctypes.c_void_p),  # coords\n                itype.ctypes.data_as(ctypes.c_void_p),  # itype\n                params.ctypes.data_as(ctypes.c_void_p),  # params\n                ctypes.c_int(version),  # version\n                edisp.ctypes.data_as(ctypes.c_void_p),  # edisp\n                grad.ctypes.data_as(ctypes.c_void_p))  # grads)\n            grad_contrib += grad\n\n        self.grad_enfunc = grad_contrib\n\n    def base_method(self) -> UDFDH:\n        self.__class__ = UDFDH\n        return self\n\n", "meta": {"hexsha": "f7f78778ecf8bfb23c7ad8a6d0ed31a85fa31bae", "size": 12741, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/dh/grad/udfdh.py", "max_stars_repo_name": "hebrewsnabla/dh", "max_stars_repo_head_hexsha": "222e3d4d8d4d04cd63074327ebb5fb39ea4441b7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-05T08:58:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T08:58:13.000Z", "max_issues_repo_path": "pyscf/dh/grad/udfdh.py", "max_issues_repo_name": "hebrewsnabla/dh", "max_issues_repo_head_hexsha": "222e3d4d8d4d04cd63074327ebb5fb39ea4441b7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscf/dh/grad/udfdh.py", "max_forks_repo_name": "hebrewsnabla/dh", "max_forks_repo_head_hexsha": "222e3d4d8d4d04cd63074327ebb5fb39ea4441b7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2395833333, "max_line_length": 129, "alphanum_fraction": 0.5676948434, "include": true, "reason": "import numpy", "num_tokens": 4663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.2568319970758679, "lm_q1q2_score": 0.16910268502187267}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n# coding=utf-8\n\nimport subprocess\nimport warnings\n\nimport numpy as np\nfrom skimage.transform import rotate as imrotate\n\nimport astropy.units as u\nfrom astropy.io import ascii\nfrom astropy.table import Table\nfrom astropy import visualization\n\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport matplotlib.colors as col\n\nfrom .config import recursive_subclasses, merge_config, mmtwfs_config\nfrom .custom_exceptions import WFSConfigException\nfrom .secondary import SecondaryFactory\nfrom .zernike import ZernikeVector\n\nimport logging\nimport logging.handlers\n\n# we need to wrap the poppy import in a context manager to trap its whinging about missing pysynphot stuff that we don't use.\nwith warnings.catch_warnings():\n    warnings.simplefilter(\"ignore\")\n    import poppy\n\nlog = logging.getLogger(\"Telescope\")\nlog.setLevel(logging.INFO)\n\n\n__all__ = ['TelescopeFactory', 'MMT', 'FLWO12']\n\n\ndef TelescopeFactory(telescope=\"mmt\", secondary=\"f5\", config={}, **kwargs):\n    \"\"\"\n    Build and return proper Telescope sub-class instance based on the value of 'telescope' and 'secondary'.\n    \"\"\"\n    config = merge_config(config, dict(**kwargs))\n    secondary = secondary.lower()\n    telescope = telescope.lower()\n\n    types = recursive_subclasses(Telescope)\n    telescopes = [t.__name__.lower() for t in types]\n    tel_map = dict(list(zip(telescopes, types)))\n\n    if telescope not in telescopes:\n        raise WFSConfigException(value=f\"Specified telescope, {telescope}, not valid or not implemented.\")\n\n    tel_cls = tel_map[telescope](secondary=secondary, config=config)\n    return tel_cls\n\n\nclass Telescope(object):\n    \"\"\"\n    Defines generic configuration and methods that pertain to telescope and primary mirror systems\n    \"\"\"\n    def __init__(self, telescope=\"mmt\", secondary=\"f5\", config={}, **kwargs):\n        config = merge_config(config, dict(**kwargs))\n        if telescope not in mmtwfs_config['telescope']:\n            msg = f\"Invalid telescope specified, {telescope}.\"\n            raise WFSConfigException(value=msg)\n        if secondary not in mmtwfs_config['secondary']:\n            msg = f\"Invalid secondary specified, {secondary}.\"\n            raise WFSConfigException(value=msg)\n        if mmtwfs_config['secondary'][secondary]['telescope'] != telescope:\n            msg = f\"Invalid secondary, {secondary}, for telescope, {telescope}.\"\n            raise WFSConfigException(value=msg)\n\n        self.__dict__.update(merge_config(mmtwfs_config['telescope'][telescope], config))\n\n        self.secondary = SecondaryFactory(secondary=secondary)\n\n        self.radius = self.diameter / 2.\n        self.nmperrad = self.radius.to(u.nm).value\n        self.nmperasec = self.nmperrad / 206265.\n\n        # ratio of the size of the central obstruction of the secondary to the size of the primary\n        self.obscuration = self.secondary.diameter / self.diameter\n\n        # create model of MMTO pupil including secondary and secondary support obstructions\n        self.pupil = self._pupil_model()\n\n        # initialize poppy optical system used for calculating the PSFs\n        self.osys = poppy.OpticalSystem()\n        self.osys.add_pupil(self.pupil)\n        self.osys.add_pupil(poppy.ZernikeWFE(radius=self.radius.to(u.m).value, coefficients=[0.0, 0.0, 0.0, 0.0]))\n        self.osys.add_detector(pixelscale=self.psf_pixel_scale, fov_arcsec=self.psf_fov)\n\n    def _pupil_model(self):\n        \"\"\"\n        Use poppy to create a model of the pupil given the configured primary and secondary mirrors.\n        \"\"\"\n        primary = poppy.CircularAperture(radius=self.radius.to(u.m).value)\n        secondary = poppy.SecondaryObscuration(\n            secondary_radius=self.secondary.diameter.to(u.m).value / 2,\n            n_supports=self.n_supports,\n            support_width=self.support_width.to(u.m).value,\n            support_angle_offset=self.support_offset.to(u.deg).value\n        )\n        pup_model = poppy.CompoundAnalyticOptic(opticslist=[primary, secondary], name=\"MMTO\")\n        return pup_model\n\n    def pupil_mask(self, rotation=0.0, size=512):\n        \"\"\"\n        Use the pupil model to make a pupil mask that can be used as a kernel for finding pupil-like things in images\n        \"\"\"\n        if size >= 700:\n            msg = \"WFS pupil sizes are currently restricted to 700 pixels in diameter or less.\"\n            raise WFSConfigException(value=msg)\n\n        rotation = u.Quantity(rotation, u.deg)\n\n        # not sure how to get the image data out directly, but the to_fits() method gives me a path...\n        pup_im = imrotate(self.pupil.to_fits(npix=size)[0].data.astype(float), rotation.value)\n        pup_im = pup_im / pup_im.max()\n        return pup_im\n\n    def psf(self, zv=ZernikeVector(), wavelength=550.*u.nm, plot=True):\n        \"\"\"\n        Take a ZernikeVector and calculate resulting PSF at given wavelength.\n        \"\"\"\n        # poppy wants the wavelength in meters\n        try:\n            w = wavelength.to(u.m).value\n        except AttributeError:\n            w = wavelength  # if no unit provided, assumed meters\n\n        # poppy wants the piston term so whack it in there if modestart isn't already 1\n        if zv.modestart != 1:\n            zv.modestart = 1\n            zv['Z01'] = 0.0\n\n        # poppy wants coeffs in meters\n        zv.units = u.m\n\n        # poppy wants Noll normalized coefficients\n        coeffs = zv.norm_array\n\n        # pop detector out to reuse, pop old wavefront error out to make way for new\n        det = self.osys.planes.pop()\n        fov = det.fov_arcsec.value\n\n        # add new wavefront error and put detector back in place\n        wfe = poppy.ZernikeWFE(radius=self.radius.to(u.m).value, coefficients=coeffs)\n        self.osys.add_pupil(wfe)\n        self.osys.planes.append(det)\n\n        psf = self.osys.calc_psf(w)\n\n        psf_fig = None\n        if plot:\n            psf_fig, ax = plt.subplots()\n            psf_fig.set_label(\"PSF at {0:0.0f}\".format(wavelength))\n            norm = visualization.mpl_normalize.ImageNormalize(stretch=visualization.LinearStretch())\n            ims = ax.imshow(psf[0].data, extent=[-fov/2, fov/2, -fov/2, fov/2], cmap=cm.magma, norm=norm)\n            ax.set_xlabel(\"arcsec\")\n            ax.set_ylabel(\"arcsec\")\n            cb = psf_fig.colorbar(ims)\n            cb.set_label(\"Fraction of Total Flux\")\n        return psf, psf_fig\n\n\nclass FLWO12(Telescope):\n    \"\"\"\n    Defines configuration and methods for the FLWO 1.2-meter\n    \"\"\"\n    def __init__(self, config={}, **kwargs):\n        config = merge_config(config, dict(**kwargs))\n        super(FLWO12, self).__init__(telescope=\"flwo12\", secondary=\"flwo12\", config=config)\n\n\nclass FLWO15(Telescope):\n    \"\"\"\n    Defines configuration and methods for the FLWO 1.5-meter\n    \"\"\"\n    def __init__(self, config={}, **kwargs):\n        config = merge_config(config, dict(**kwargs))\n        super(FLWO15, self).__init__(telescope=\"flwo15\", secondary=\"flwo15\", config=config)\n\n\nclass MMT(Telescope):\n    \"\"\"\n    Defines configuration and methods that pertain to the MMT's telescope and primary mirror systems\n    \"\"\"\n    def __init__(self, secondary=\"f5\", config={}, **kwargs):\n        config = merge_config(config, dict(**kwargs))\n        super(MMT, self).__init__(telescope=\"mmt\", secondary=secondary, config=config)\n\n        # load table of finite element coordinates\n        self.nodecoor = self.load_bcv_coordinates()\n        self.n_node = len(self.nodecoor)\n\n        # load table of actuator coordinates\n        self.actcoor = self.load_actuator_coordinates()\n        self.n_act = len(self.actcoor)\n\n        # load actuator influence matrix that provides the surface displacement caused by 1 N of force by\n        # each actuator at each of self.node finite element node positions.\n        self.surf2act = self.load_influence_matrix()\n\n        # use this boolean to determine if corrections are actually to be sent\n        self.connected = False\n\n        # keep track of last and total forces. a blank ZernikeVector will generate the appropriate format\n        # table with all forces set to 0.\n        self.last_forces = self.bending_forces(zv=ZernikeVector())\n        self.total_forces = self.bending_forces(zv=ZernikeVector())\n        self.last_m1focus = 0.0 * u.um\n        self.total_m1focus = 0.0 * u.um\n\n    def connect(self):\n        \"\"\"\n        Set state to connected so that calculated corrections will be sent to the relevant systems\n        \"\"\"\n        self.connected = True\n\n    def disconnect(self):\n        \"\"\"\n        Set state to disconnected so that corrections will be calculated, but not sent\n        \"\"\"\n        self.connected = False\n\n    def bending_forces(self, zv=ZernikeVector(), gain=0.5):\n        \"\"\"\n        Given a ZernikeVector (or similar object describing a 2D polynomial surface), calculate the actuator forces required\n        to correct for the surface displacement it describes.\n        \"\"\"\n        # we don't want to bend any tilts...\n        if 'Z02' in zv:\n            zv['Z02'] = 0.0\n        if 'Z03' in zv:\n            zv['Z03'] = 0.0\n\n        # convert to nm...\n        zv.units = u.nm\n\n        # make sure we're not Noll normalized...\n        zv.denormalize()\n\n        # need to rotate the wavefront -90 degrees to match the BCV angle convention of +Y being 0 deg.\n        zv.rotate(-90*u.deg)\n\n        # get surface displacements at the BCV node positions. multiply the wavefront amplitude by 0.5 to account for\n        # reflection off the surface.\n        surf_corr = -0.5 * gain * zv.total_phase(self.nodecoor['bcv_rho'], self.nodecoor['bcv_phi'])\n        if isinstance(surf_corr, float):  # means we got 0.0 from zv.total_phase()\n            force_vec = np.zeros(self.n_act)\n        else:\n            force_vec = np.dot(surf_corr, self.surf2act).value  # remove the units that got passed through\n\n        # return an astropy.table.Table so we can easily package actuator ID along with the force. its write() method\n        # also provides a lot of flexibility in providing outputs that match the old system.\n        t = Table([self.actcoor['act_id'], force_vec], names=['actuator', 'force'])\n        return t\n\n    def to_rcell(self, t, filename=\"zfile\", overwrite=True):\n        \"\"\"\n        Take table generated by bending_forces() and write it to a file of a format that matches the old SHWFS system\n        \"\"\"\n        t.write(filename, format=\"ascii.no_header\", delimiter=\"\\t\", formats={'force': \".1f\"}, overwrite=overwrite)\n\n    def calculate_primary_corrections(self, zv, mask=[], gain=0.5):\n        \"\"\"\n        Take ZernikeVector as input and determine corrections to apply to primary/secondary\n        \"\"\"\n        # leave out tilts, focus, and coma from force calcs to start with\n        def_mask = ['Z02', 'Z03', 'Z04', 'Z07', 'Z08']\n        def_mask.extend(mask)\n\n        # mask out all high order terms beyond 2nd order spherical\n        for i in range(23, 99):\n            def_mask.append(\"Z{0:02d}\".format(i))\n\n        mask = list(set(def_mask))\n        zv_masked = zv.copy()\n        zv_masked.denormalize()\n        for k in mask:\n            zv_masked.ignore(k)\n\n        # to reduce the amount of force required to remove spherical aberration, we offset the r**2 part of that term by\n        # bending focus into the primary and then offsetting that by adjusting the secondary.  this has the effect of\n        # reducing by ~1/4 to 1/3 the total force required to correct a given amount of spherical aberration.\n        #\n        # this same scheme can also be extended to the higher order spherical terms as well, Z22 and Z37.\n        #\n        # for reference:\n        #   Z04 ~ 2r**2 - 1\n        #   Z11 ~ 6r**4 - 6r**2 + 1\n        #   Z22 ~ 20r**6 - 30r**4 + 12r**2 - 1\n        #   Z37 ~ 70r**8 - 140r**6 + 90r**4 - 20r**2 + 1\n        #\n        zv_masked['Z04'] = -6.0 * zv_masked['Z11'] - 12.0 * zv_masked['Z22'] - 20.0 * zv_masked['Z37']\n\n        m1focus_corr = gain * zv_masked['Z04'] / self.secondary.focus_trans\n\n        t = self.bending_forces(zv=zv_masked, gain=gain)\n\n        return t, m1focus_corr, zv_masked\n\n    def bend_mirror(self, filename=\"zfile\"):\n        \"\"\"\n        Take a force file and send it to the cell to apply bending forces. Return fraction of requested\n        forces that the cell reports were applied.\n        \"\"\"\n        frac = 1.0\n        log.info(f\"Using command, /mmt/scripts/cell_send_forces {filename}, to apply forces...\")\n        pipe = subprocess.Popen(\n            ['/mmt/scripts/cell_send_forces', f\"{filename}\"],\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE\n        )\n\n        try:\n            (stdout, stderr) = pipe.communicate(timeout=10)\n        except subprocess.TimeoutExpired:\n            pipe.kill()\n            (stdout, stderr) = pipe.communicate()\n\n        outstr = stdout.decode('utf8')\n        outerr = stderr.decode('utf8')\n\n        # had to dig into the cell code at /mmt/vxsource/mmt/cell/src/cell_inf.c to get the messages that are produces\n        if \"Able to Apply\" in outstr:\n            log.info(\"...forces successfully applied in full.\")\n\n        elif \"Forces Rejected\" in outstr:\n            log.error(\"...forces rejected!\")\n            frac = 0.0\n\n        elif \"Unable to apply forces\" in outstr:\n            log.error(\"...unable to apply forces!\")\n            frac = 0.0\n\n        elif \"Applying partial forces\" in outstr:\n            percent = float(outstr.split()[3])\n            frac = percent / 100.0\n            log.warn(f\"...applied {percent}% of requested forces.\")\n\n        else:\n            log.error(f\"...got unexpected reply from cell command: {outstr}\")\n            log.error(f\"\\t stderr: {outerr}\")\n\n        return frac\n\n    def correct_primary(self, t, m1focus_corr, filename=\"zfile\"):\n        \"\"\"\n        Take force table and focus offset calculated by self.calculate_primary_corrections() and apply them, if connected.\n        \"\"\"\n        frac = 1.0\n        if self.connected:\n            self.to_rcell(t, filename=filename)\n            log.info(f\"Sending forces from {filename}...\")\n            frac = self.bend_mirror(filename=filename)\n            self.secondary.m1spherical(frac * m1focus_corr)\n        else:\n            log.info(\"Not connected; no commands sent to cell or hexapod.\")\n\n        self.last_forces = t.copy(copy_data=True)\n        self.last_forces['force'] *= frac\n        self.last_m1focus = frac * m1focus_corr.copy()\n        self.total_forces['force'] += frac * t['force']\n        self.total_m1focus += frac * m1focus_corr\n        return t, m1focus_corr\n\n    def undo_last(self, zfilename=\"zfile_undo\"):\n        \"\"\"\n        Undo the last set of corrections.\n        \"\"\"\n        self.last_forces['force'] *= -1\n        self.last_m1focus *= -1\n        frac = 1.0\n        if self.connected:\n            log.info(\"Undoing last set of primary mirror corrections...\")\n            self.to_rcell(self.last_forces, filename=zfilename)\n            frac = self.bend_mirror(filename=zfilename)\n            self.secondary.m1spherical(frac * self.last_m1focus)\n        else:\n            log.info(\"Not connected; no undo commands sent.\")\n\n        self.total_m1focus += frac * self.last_m1focus\n        self.total_forces['force'] += frac * self.last_forces['force']\n        return self.last_forces.copy(), self.last_m1focus.copy()\n\n    def clear_forces(self):\n        \"\"\"\n        Clear applied forces from primary mirror and clear any m1spherical offsets from secondary hexapod\n        \"\"\"\n        if self.connected:\n            log.info(\"Clearing forces and spherical aberration focus offsets...\")\n            self.secondary.clear_m1spherical()\n            pipe = subprocess.Popen(['/mmt/scripts/cell_clear_forces'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n            try:\n                (stdout, stderr) = pipe.communicate(timeout=20)\n            except subprocess.TimeoutExpired:\n                pipe.kill()\n                (stdout, stderr) = pipe.communicate()\n\n            outstr = stdout.decode('utf8')\n            outerr = stderr.decode('utf8')\n            log.info(f\"...{outstr.strip()}\")\n            if len(outerr) > 0:\n                log.warn(f\"Got error from cell_clear_forces: {outerr}\")\n        else:\n            log.info(\"Not connected; no clearing commands sent.\")\n\n        # the 'last' corrections are negations of the current total. reset the totals to 0.\n        self.last_forces = self.total_forces.copy(copy_data=True)\n        self.last_forces['force'] *= -1\n        self.last_m1focus = -self.total_m1focus\n        self.total_forces = self.bending_forces(zv=ZernikeVector())\n        self.total_m1focus = 0.0\n\n        return self.last_forces, self.last_m1focus\n\n    def load_influence_matrix(self):\n        \"\"\"\n        The influence of each actuator on the mirror surface has been modeled via finite element analysis.\n        This method loads the influence matrix that resulted from this analysis and maps for each actuator\n        the influence of 1 lb of force on the mirror surface at each finite element node.  This matrix is\n        stored in a binary file for compactness and speed of loading.\n        \"\"\"\n        surf2act = np.fromfile(self.surf2act_file, dtype=np.float32).reshape(self.n_act, self.n_node).transpose()\n        return surf2act\n\n    def load_actuator_coordinates(self):\n        \"\"\"\n        The actuator IDs and X/Y positions in mm are stored in a simple ASCII table.  Load it using\n        astropy.io.ascii, convert to units of mirror radius, and add polar coordinates.\n        \"\"\"\n        coord = ascii.read(self.actuator_file, names=[\"act_id\", \"act_x\", \"act_y\", \"act_type\"])\n        for ax in [\"act_x\", \"act_y\"]:\n            coord[ax] /= self.bcv_radius.to(u.mm).value\n        coord['act_rho'] = np.sqrt(coord['act_x']**2 + coord['act_y']**2)\n        coord['act_phi'] = np.arctan2(coord['act_y'], coord['act_x'])\n        coord['act_phi'].unit = u.radian\n\n        return coord\n\n    def load_bcv_coordinates(self):\n        \"\"\"\n        The BCV finite element nodes IDs and X/Y/Z positions in mm are stored in a simple ASCII table.  Load it\n        using astropy.io.ascii, convert to units of mirror radius, and add polar coordinates.\n        \"\"\"\n        coord = ascii.read(self.nodecoor_file, names=[\"bcv_id\", \"bcv_x\", \"bcv_y\", \"bcv_z\"])\n        for ax in [\"bcv_x\", \"bcv_y\"]:\n            coord[ax] /= self.bcv_radius.to(u.mm).value\n        coord['bcv_rho'] = np.sqrt(coord['bcv_x']**2 + coord['bcv_y']**2)\n        coord['bcv_phi'] = np.arctan2(coord['bcv_y'], coord['bcv_x'])\n        coord['bcv_phi'].unit = u.radian\n\n        return coord\n\n    def plot_forces(self, t, m1focus=None, limit=100.):\n        \"\"\"\n        Plot actuator forces given force table as output from self.bending_forces()\n        \"\"\"\n        coords = self.actcoor\n        r_fac = 0.5 * self.diameter / self.bcv_radius  # adjust for slight difference\n        cmap = cm.ScalarMappable(col.Normalize(-1*limit, limit), cm.bwr)\n        cmap._A = []  # grr stupid matplotlib\n        fig, ax = plt.subplots()\n        fig.set_label(\"M1 Actuator Forces\")\n        xcor, ycor = coords['act_x']/r_fac, coords['act_y']/r_fac\n        ax.scatter(xcor, ycor, color=cmap.to_rgba(t['force']))\n        for i, (x, y) in enumerate(zip(xcor, ycor)):\n            ax.text(x, y+0.02, t['actuator'][i],  horizontalalignment='center', verticalalignment='bottom', size='xx-small')\n\n        ax.set_aspect(1.0)\n        circle1 = plt.Circle((0, 0), 1.0, fill=False, color='black', alpha=0.2)\n        circle2 = plt.Circle((0, 0), 0.9/6.5, fill=False, color='black', alpha=0.2)\n        ax.add_artist(circle1)\n        ax.add_artist(circle2)\n        if m1focus is not None:\n            ax.set_title(\"M1 Focus Offset: {0:0.1f}\".format(m1focus))\n        ax.set_axis_off()\n        cb = fig.colorbar(cmap)\n        cb.set_label(\"Actuator Force (N)\")\n        return fig\n", "meta": {"hexsha": "097f5c26cdbde80a6f33a9abe6d3db775954bebd", "size": 19852, "ext": "py", "lang": "Python", "max_stars_repo_path": "mmtwfs/telescope.py", "max_stars_repo_name": "tepickering/mmtwfs", "max_stars_repo_head_hexsha": "c38616951057290f85f4c7a6af5f0b3d23f87b8f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-11T08:54:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T22:08:48.000Z", "max_issues_repo_path": "mmtwfs/telescope.py", "max_issues_repo_name": "tepickering/mmtwfs", "max_issues_repo_head_hexsha": "c38616951057290f85f4c7a6af5f0b3d23f87b8f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 43, "max_issues_repo_issues_event_min_datetime": "2017-04-17T20:11:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T22:57:27.000Z", "max_forks_repo_path": "mmtwfs/telescope.py", "max_forks_repo_name": "tepickering/mmtwfs", "max_forks_repo_head_hexsha": "c38616951057290f85f4c7a6af5f0b3d23f87b8f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-16T00:36:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-16T00:36:29.000Z", "avg_line_length": 40.9319587629, "max_line_length": 125, "alphanum_fraction": 0.6341426557, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 4912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.2782567996876011, "lm_q1q2_score": 0.16908640892572363}}
{"text": "#!/usr/bin/env python\nimport os\nimport numpy as np\nimport time\nimport copy\nimport sys\n\nimport argparse\n\nang_2_bohr = 1.0/0.52917721067\nhart_2_ev = 27.21138602\n\nimport cp2k_spm_tools.cp2k_grid_orbitals as cgo\nimport cp2k_spm_tools.cp2k_stm_sts as css\nfrom cp2k_spm_tools import common, cube_utils\nfrom cp2k_spm_tools.cube import Cube\n\nfrom mpi4py import MPI\n\ncomm = MPI.COMM_WORLD\nmpi_rank = comm.Get_rank()\nmpi_size = comm.Get_size()\n\nparser = argparse.ArgumentParser(\n    description='Puts the CP2K orbitals on grid and calculates STM.')\n\n### ----------------------------------------------------------------------\n### Input and output files\nparser.add_argument(\n    '--cp2k_input_file',\n    metavar='FILENAME',\n    required=True,\n    help='CP2K input of the SCF calculation.')\nparser.add_argument(\n    '--basis_set_file',\n    metavar='FILENAME',\n    required=True,\n    help='File containing the used basis sets.')\nparser.add_argument(\n    '--xyz_file',\n    metavar='FILENAME',\n    required=True,\n    help='.xyz file containing the geometry.')\nparser.add_argument(\n    '--wfn_file',\n    metavar='FILENAME',\n    required=True,\n    help='Restart file containing the final wavefunction.')\nparser.add_argument(\n    '--hartree_file',\n    metavar='FILENAME',\n    required=True,\n    help='Cube file containing the hartree potential.')\nparser.add_argument(\n    '--output_file',\n    metavar='FILENAME',\n    default=\"./stm.npz\",\n    help='File, where to save the STM/STS output')\nparser.add_argument(\n    '--orb_output_file',\n    metavar='FILENAME',\n    default=\"./orb.npz\",\n    help='File, where to save the orbital output')\n### ----------------------------------------------------------------------\n### Parameters for putting orbitals on grid\nparser.add_argument(\n    '--eval_region',\n    type=str,\n    nargs=6,\n    metavar='X',\n    required=True,\n    help=common.eval_region_description\n)\nparser.add_argument(\n    '--dx',\n    type=float,\n    metavar='DX',\n    required=True,\n    help='Spatial step for the grid (angstroms).')\nparser.add_argument(\n    '--eval_cutoff',\n    type=float,\n    metavar='D',\n    default=16.0,\n    help=(\"Size of the region around the atom where each\"\n          \" orbital is evaluated (only used for 'G' region).\")\n)\nparser.add_argument(\n    '--extrap_extent',\n    type=float,\n    metavar='H',\n    default=4.0,\n    required=True,\n    help=\"The extent of the extrapolation region. (angstrom)\"\n)\n### ----------------------------------------------------------------------\n### Gas phase analysis parameters - image at orbital energies\nparser.add_argument(\n    '--n_homo',\n    type=int,\n    metavar='N',\n    default=0,\n    help=\"Number of HOMO orbitals to analyse.\")\nparser.add_argument(\n    '--n_lumo',\n    type=int,\n    metavar='N',\n    default=0,\n    help=\"Number of LUMO orbitals to analyse.\")\nparser.add_argument(\n    '--orb_heights',\n    nargs='*',\n    type=float,\n    metavar='H',\n    help=\"List of heights for constant height orbital pictures (wrt topmost atom).\")\nparser.add_argument(\n    '--orb_isovalues',\n    nargs='*',\n    type=float,\n    metavar='C',\n    help=\"List of charge density isovalues for constant current orbital pictures\")\nparser.add_argument(\n    '--orb_fwhms',\n    nargs='*',\n    type=float,\n    default=[0.02],\n    help=\"Full width at half maximum for orbital STS gaussian broadening. (eV)\")\n### ----------------------------------------------------------------------\n### Slab system analysis parameters - images at specified energies\n###\n### Option 1: continuous selection\nparser.add_argument(\n    '--energy_range',\n    nargs=3,\n    type=float,\n    metavar='E',\n    help='Selection of STM/STS energy values based on a range: min, max and differential.')\n###\n### Option 2: discrete selection\nparser.add_argument(\n    '--energies',\n    nargs='*',\n    type=float,\n    metavar='E',\n    help='Discrete energies where to run the STM/STS.')\n### ----------------------------------------------------------------------\n### Parameters for STM/STS series\nparser.add_argument(\n    '--heights',\n    nargs='*',\n    type=float,\n    metavar='H',\n    help=\"List of heights for constant height STM pictures (wrt topmost atom).\")\nparser.add_argument(\n    '--isovalues',\n    nargs='*',\n    type=float,\n    metavar='C',\n    help=\"List of charge density isovalues for constant current STM pictures.\")\nparser.add_argument(\n    '--fwhms',\n    nargs='*',\n    type=float,\n    default=[0.1],\n    help=\"Full width at half maximum for STS gaussian broadening. (eV)\")\n### ----------------------------------------------------------------------\n### P - tip ratio list\nparser.add_argument(\n    '--p_tip_ratios',\n    nargs='+',\n    type=float,\n    metavar='P',\n    default=[0.0],\n    help=(\"List of p character of the STM tip: 0.0 corresponds\"\n          \"to fully s-type and 1.0 to fully p-type tip\")\n)\n### ----------------------------------------------------------------------\n\n\ntime0 = time.time()\n\n### ------------------------------------------------------\n### Parse args for only one rank to suppress duplicate stdio\n### ------------------------------------------------------\n\nargs = None\nargs_success = False\ntry:\n    if mpi_rank == 0:\n        args = parser.parse_args()\n        args_success = True\nfinally:\n    args_success = comm.bcast(args_success, root=0)\n\nif not args_success:\n    print(mpi_rank, \"exiting\")\n    exit(0)\n\nargs = comm.bcast(args, root=0)\n\n### ------------------------------------------------------\n### Energy values for STM/STS\n### ------------------------------------------------------\n\nif args.energies is not None:\n    e_arr = np.array(args.energies)\nelif args.energy_range is not None:\n    emin, emax, de = args.energy_range\n    e_arr = np.arange(emin, emax+de/2, de)\nelse:\n    e_arr = None\n\nmax_fwhm = np.max(args.fwhms)\nif e_arr is not None:\n    sel_emin = np.min(e_arr) - 2.0*max_fwhm\n    sel_emax = np.max(e_arr) + 2.0*max_fwhm\nelse:\n    sel_emin = None\n    sel_emax = None\n\n### ------------------------------------------------------\n### Evaluate orbitals on the real-space grid\n### ------------------------------------------------------\n\ncp2k_grid_orb = cgo.Cp2kGridOrbitals(mpi_rank, mpi_size, mpi_comm=comm, single_precision=True)\ncp2k_grid_orb.read_cp2k_input(args.cp2k_input_file)\ncp2k_grid_orb.read_xyz(args.xyz_file)\ncp2k_grid_orb.center_atoms_to_cell()\ncp2k_grid_orb.read_basis_functions(args.basis_set_file)\ncp2k_grid_orb.load_restart_wfn_file(args.wfn_file,\n                                    emin=sel_emin, emax=sel_emax,\n                                    n_occ=args.n_homo, n_virt=args.n_lumo\n)\n\n\n\nprint(\"R%d/%d: loaded wfn, %.2fs\"%(mpi_rank, mpi_size, (time.time() - time0)))\nsys.stdout.flush()\ntime1 = time.time()\n\neval_reg = common.parse_eval_region_input(args.eval_region, cp2k_grid_orb.ase_atoms, cp2k_grid_orb.cell)\n\n# --------\n# Make sure extrap extent is compatible with heights\natoms_max_z = np.max(cp2k_grid_orb.ase_atoms.positions[:, 2])\neval_z_above_atoms = eval_reg[2][1] - atoms_max_z\nextrap_extent = args.extrap_extent\nfor hs in [args.orb_heights, args.heights]:\n    if hs is not None:\n        if np.max(hs) - eval_z_above_atoms > extrap_extent:\n            print(\"Increasing extrap. extent to be compatible with heights.\")\n            extrap_extent = np.max(hs)- eval_z_above_atoms\n# --------\n\ncp2k_grid_orb.calc_morbs_in_region(args.dx,\n                                x_eval_region = eval_reg[0],\n                                y_eval_region = eval_reg[1],\n                                z_eval_region = eval_reg[2],\n                                pbc = (True, True, False),\n                                reserve_extrap = extrap_extent,\n                                eval_cutoff = args.eval_cutoff)\n\nprint(\"R%d/%d: evaluated wfn, %.2fs\"%(mpi_rank, mpi_size, (time.time() - time1)))\nsys.stdout.flush()\ntime1 = time.time()\n\n### ------------------------------------------------------\n### Extrapolate orbitals\n### ------------------------------------------------------\n\nhart_cube = Cube()\nhart_cube.read_cube_file(args.hartree_file)\nextrap_plane_z = eval_reg[2][1] / ang_2_bohr - np.max(cp2k_grid_orb.ase_atoms.positions[:, 2])\nhart_plane = hart_cube.get_plane_above_topmost_atom(extrap_plane_z) - cp2k_grid_orb.ref_energy/hart_2_ev\n\ncp2k_grid_orb.extrapolate_morbs(hart_plane=hart_plane)\n\nprint(\"R%d/%d: extrapolated wfn, %.2fs\"%(mpi_rank, mpi_size, (time.time() - time1)))\nsys.stdout.flush()\ntime1 = time.time()\n\n\n### ------------------------------------------------------\n### Calculate the ionization potential (just for output)\n### ------------------------------------------------------\n\nif mpi_rank == 0:\n    # NB: currently only accurate for isolated molecules\n    if cp2k_grid_orb.nspin == 1:\n        homo_en = cp2k_grid_orb.global_morb_energies[0][cp2k_grid_orb.i_homo_glob[0]]\n    else:\n        homo_en = np.max([\n            cp2k_grid_orb.global_morb_energies[0][cp2k_grid_orb.i_homo_glob[0]],\n            cp2k_grid_orb.global_morb_energies[1][cp2k_grid_orb.i_homo_glob[1]]\n        ])\n    ion_pot = cube_utils.find_vacuum_level_naive(hart_cube) - (homo_en + cp2k_grid_orb.ref_energy)\n    print(\"IONIZATION POTENIAL (eV): %.6f (accurate only for isolated molecules)\" % ion_pot)\n\n### ------------------------------------------------------\n### Set up STM object\n### ------------------------------------------------------\n\nstm = css.STM(mpi_comm = comm, cp2k_grid_orb = cp2k_grid_orb, p_tip_ratios = args.p_tip_ratios)\nstm.gather_global_energies()\nstm.divide_by_space()\n\n### ------------------------------------------------------\n### Run STM-STS analysis for orbitals\n### ------------------------------------------------------\n\norb_heights = args.orb_heights if args.orb_heights is not None else []\norb_isovalues = args.orb_isovalues if args.orb_isovalues is not None else []\norb_fwhms = args.orb_fwhms if args.orb_fwhms is not None else []\n\nif len(orb_fwhms) != 0 and (len(orb_heights) != 0 or len(orb_isovalues) != 0):\n\n    orbital_list = list(range(-args.n_homo + 1, args.n_lumo + 1))\n\n    stm.create_orb_series(orbital_list, orb_heights, orb_isovalues, orb_fwhms)\n\n    stm.collect_and_save_orb_maps(path=args.orb_output_file)\n\n### ------------------------------------------------------\n### Run STM-STS analysis for general energies\n### ------------------------------------------------------\n\nheights = args.heights if args.heights is not None else []\nisovalues = args.isovalues if args.isovalues is not None else []\nfwhms = args.fwhms if args.fwhms is not None else []\n\nif e_arr is not None and len(fwhms) != 0 and (len(heights) != 0 or len(isovalues) != 0):\n\n    stm.calculate_stm_maps(fwhms, isovalues, heights, e_arr)\n\n    stm.collect_and_save_stm_maps(path=args.output_file)\n\nprint(\"R%d/%d: finished, total time: %.2fs\"%(mpi_rank, mpi_size, (time.time() - time0)))\n\n\n", "meta": {"hexsha": "c5121e8131536588a0ce3e0d822d685fe8e28236", "size": 10756, "ext": "py", "lang": "Python", "max_stars_repo_path": "stm_sts_from_wfn.py", "max_stars_repo_name": "eimrek/cp2k-spm-tools", "max_stars_repo_head_hexsha": "94b158e7e93bc4cb76e88d59d31347fafdda5e64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-10-11T15:24:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T16:05:24.000Z", "max_issues_repo_path": "stm_sts_from_wfn.py", "max_issues_repo_name": "eimrek/cp2k-spm-tools", "max_issues_repo_head_hexsha": "94b158e7e93bc4cb76e88d59d31347fafdda5e64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stm_sts_from_wfn.py", "max_forks_repo_name": "eimrek/cp2k-spm-tools", "max_forks_repo_head_hexsha": "94b158e7e93bc4cb76e88d59d31347fafdda5e64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-09-27T06:09:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-23T15:21:11.000Z", "avg_line_length": 31.6352941176, "max_line_length": 104, "alphanum_fraction": 0.587671997, "include": true, "reason": "import numpy", "num_tokens": 2601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.16907210074942275}}
{"text": "#!/usr/bin/env python3\nimport argparse\nimport numpy\nfrom astropy.io import fits as pyfits\nimport PyParadise\n\n__author__ = \"Bernd Husemann\"\n__contributor__ = ['Bernd Husemann', 'Omar Choudhury']\n__credit__ = ['Bernd Husemann', 'Omar Choudhury','Jakbo Walcher','Tanya Urrutia','Anika Beer']\n__copyright__ = \"Copyright 2020, Bernd Husemann\"\n__license__ = \"MIT\"\n__maintainer__ = \"Bernd Husemann\"\n__email__ = \"berndhusemann@gmx.de\"\n__status__ = \"Development\"\n__version__ = \"0.2\"\n\n\nclass ParadiseApp(object):\n    \"\"\"The class `ParadiseApp` handles the fitting of the spectrum with\n    a linear combination of template spectra and/or emission lines. For the\n    the fitting of the template spectra, velocity and the velocity\n    dispersion are obtained by Monte Carlo Markov Chains and the linear\n    combination of template spectra with a non-negative least-squares\n    algorithm.\n\n    The emission line fitting is a separate function, and fits a provided\n    set of emission lines.\n\n    The bootstrapping fitting function can be used to obtain errors on the\n    parameters for the template spectral fitting and errors on the\n    parameters of the emission lines.\n    \"\"\"\n    def __init__(self, input_file, outprefix, instrFWHM):\n        \"\"\"\n        Parameters\n        ----------\n        input_file : str\n            The fits file containing the spectrum for which the fitting will be\n            performed\n        outprefix : str\n            The prefix that will be prepended to the files that are written by\n            the fitting routines.\n        instrFWHM : float\n            The instrumental resolution of the data in `input_file`.\n        \"\"\"\n\n        self.__inputData = PyParadise.spectrum1d.loadSpectrum(input_file)\n        if self.__inputData._datatype == 'CUBE':\n            self.__inputData = PyParadise.cube.loadCube(input_file)\n            self.__inputData.correctError()\n            self.__datatype = 'CUBE'\n        elif self.__inputData._datatype == 'RSS':\n            self.__inputData = PyParadise.rss.loadRSS(input_file)\n            self.__inputData.correctError()\n            self.__datatype = 'RSS'\n        elif self.__inputData._datatype == 'Spectrum1D':\n            data = PyParadise.spectrum1D.loadSpectrum(input_file)\n            data.correctError()\n            self.__datatype = 'RSS'\n            if data._error is not None:\n                err = numpy.array([data._error])\n            else:\n                err = None\n            if data._mask is not None:\n                m = numpy.array([data._mask])\n            else:\n                m = None\n            self.__inputData = PyParadise.rss.RSS(wave=data._wave, data=numpy.array([data._data]), error=err, mask=m)\n        self.__outPrefix = outprefix\n        try:\n            self.__instrFWHM = PyParadise.spectrum1d.SpectralResolution(res=float(instrFWHM))\n        except ValueError:\n            try:\n                self.__instrFWHM = PyParadise.spectrum1d.SpectralResolution()\n                self.__instrFWHM.readFile(instrFWHM)\n            except IOError:\n                print(\"Wrong input for spectral resolution. Specify either a float number or the path to an ASCII file with columns wavelengt and spectral resolution as content.\")\n                \n           \n            \n\n    def run_SSP_fit(self, parfile, parallel, verbose):\n        \"\"\"This functions fits a linear combination of template spectra to the\n        input spectra to obtain the best fit.\n\n        Parameters\n        ----------\n        parfile : str\n            The parameter file containing the constraints under which the input\n            spectra will be fitted.\n        parallel : {'auto', int}, optional\n            If parallel is not equal to one, the python multiprocessing routine\n            shall be used to run parts of the code in parallel. With the option\n            `auto`, it adjusts the number of parallel processes to the number\n            of cpu-cores/threads that are available.\n        verbose : bool, optional\n            Produces screen output, such that the user can follow which spectrum\n            is currently fitted and what the results are for each spectrum.\n\n        Notes\n        -----\n        The function does not return anything, but writes the results of the fit\n        to disk. There are three files written to disk, all prepended by the\n        `outprefix` supplied to this class at creation. The three files are:\n        - `outprefix`.cont_model.fits which contains the spectra corresponding\n          to the best linear combination of spectra.\n        - `outprefix`.cont_res.fits contains the residual between the input fits\n          file and the best fitted model spectra.\n        - `outprefix`.stellar_table.fits contains the parameters of the best\n          fit, like velocity, velocity dispersion, the luminosity-weighted and\n          mass-weighted parameters.\n        \"\"\"\n        ## Read in parameter file and get values\n        parList = PyParadise.parameters.ParameterList(parfile)\n        nlib_guess = int(parList['tmplinitspec'].getValue())\n        vel_guess = float(parList['vel_guess'].getValue())\n        vel_min = float(parList['vel_min'].getValue())\n        vel_max = float(parList['vel_max'].getValue())\n        disp_min = float(parList['disp_min'].getValue())\n        disp_max = float(parList['disp_max'].getValue())\n        kin_fix = bool(int(parList['kin_fix'].getValue()))\n        mcmc_code = parList['mcmc_code'].getValue()\n        nwidth_norm = int(parList['nwidth_norm'].getValue())\n        iterations = int(parList['iterations'].getValue())\n        samples = int(parList['samples'].getValue())\n        walkers = int(parList['walkers'].getValue())\n        burn = int(parList['burn'].getValue())\n        thin = int(parList['thin'].getValue())\n        store_chain = bool(int(parList['store_chain'].getValue()))\n        start_wave = float(parList['start_wave'].getValue())\n        end_wave = float(parList['end_wave'].getValue())\n        excl_fit = PyParadise.parameters.CustomMasks(parList['excl_fit'].getValue())\n        excl_cont = PyParadise.parameters.CustomMasks(parList['excl_cont'].getValue())\n        min_x = int(parList['min_x'].getValue())\n        max_x = int(parList['max_x'].getValue())\n        min_y = int(parList['min_y'].getValue())\n        max_y = int(parList['max_y'].getValue())\n        bins = [[None, None]]\n        \n        try:\n            f = open(parList['agebinfile'].getValue())\n            try:\n                for l in f.readlines():\n                    bins.append([float(l.split()[0]), float(l.split()[1])])\n            finally:\n                f.close()\n        except (IOError, ValueError):\n            if verbose:\n                print('agebinfile is non-existent or ignored.')\n                print('Optional stellar population binning will not occur.')\n\n        if verbose:\n            print(\"The stellar population library is being prepared.\")\n        lib = PyParadise.ssplibrary.SSPlibrary(filename=parList['tmpldir'].getValue() + '/' + parList['tmplfile'].getValue())\n        if kin_fix is True:\n            hdu = pyfits.open(self.__outPrefix + '.kin_table.fits')\n            tab = hdu[1].data\n            vel_fit = tab.field('vel_fit')\n            disp_fit = tab.field('disp_fit')\n            vel_fit_err = tab.field('vel_fit_err')\n            disp_fit_err = tab.field('disp_fit_err')\n            Rvel = -numpy.ones(vel_fit.shape)\n            Rdisp = -numpy.ones(disp_fit.shape)\n            if self.__datatype == 'CUBE':\n                x_pixels = tab.field('x_cor')\n                y_pixels = tab.field('y_cor')\n            elif self.__datatype == 'RSS':\n                fibers = tab.field('fiber')\n            vel_min = numpy.min(vel_fit)\n            vel_max = numpy.max(vel_fit)\n            \n        min_wave = (start_wave / (1 + (vel_max + 2000) / 300000.0))\n        max_wave = (end_wave / (1 + (vel_min - 2000) / 300000.0))\n        if nlib_guess < 0:\n            select = numpy.arange(lib.getBaseNumber()) == nlib_guess * -1 - 1\n            lib = lib.subLibrary(select)\n        lib = lib.subWaveLibrary(min_wave=min_wave, max_wave=max_wave)\n        lib = lib.matchInstFWHM(self.__instrFWHM, vel_guess)\n        lib = lib.resampleWaveStepLinear(self.__inputData.getWaveStep(), vel_guess / 300000.0)\n        lib_norm = lib.normalizeBase(nwidth_norm, excl_cont, vel_guess / 300000.0)\n        lib_rebin = lib_norm.rebinLogarithmic()\n\n        if verbose:\n            print(\"The input cube is being normalized.\")\n\n        normData = self.__inputData.normalizeSpec(nwidth_norm, excl_cont.maskPixelsObserved(self.__inputData.getWave(),\n             vel_guess / 300000.0))\n        normDataSub = normData.subWaveLimits(start_wave, end_wave)\n        \n        #pylab.plot(self.__inputData._data[0,:],'-k')\n        #pylab.plot(normData._normalization[0,:],'-g')\n        #pylab.plot(normData._data[0,:],'-r')\n        #pylab.show()\n        if verbose:\n            print(\"The stellar population modelling has been started.\")\n        if self.__datatype == 'CUBE':\n            if kin_fix:\n                (fitted, coeff, chi2, x_pix, y_pix, cube_model, mask) = normDataSub.fit_Lib_fixed_kin(lib_rebin, nlib_guess,\n                vel_fit, disp_fit, x_pixels, y_pixels, min_x, max_x, min_y, max_y,\n                excl_fit, verbose, parallel)\n            else:\n                (vel_fit, vel_fit_err, Rvel, disp_fit, disp_fit_err, Rdisp, fitted, coeff, chi2, x_pix, y_pix,\n                cube_model, mask) = normDataSub.fit_Kin_Lib_simple(lib_rebin, nlib_guess, vel_min, vel_max, disp_min, disp_max,\n                min_x, max_x, min_y, max_y, excl_fit, iterations, mcmc_code,\n                walkers, burn, samples, thin, verbose, parallel)\n        elif self.__datatype == 'RSS':\n            if kin_fix:\n                (fitted, coeff, chi2, fiber, rss_model, mask) = normDataSub.fit_Lib_fixed_kin(lib_rebin, nlib_guess, vel_fit, disp_fit, fibers, min_y, max_y, excl_fit, verbose, parallel)\n            else:\n                \n                (vel_fit, vel_fit_err, Rvel, disp_fit, disp_fit_err, Rdisp, fitted, coeff, chi2, fiber, rss_model, mask, vel_trace, disp_trace) = normDataSub.fit_Kin_Lib_simple(lib_rebin, nlib_guess,vel_min, vel_max, disp_min, disp_max, min_y, max_y, excl_fit, iterations, mcmc_code, walkers, burn, samples, thin, verbose, store_chain, parallel)\n        if verbose:\n                print(\"Storing the results to %s (model), %s (residual) and %s (parameters).\" % (\n                    self.__outPrefix + '.cont_model.fits', self.__outPrefix + '.cont_res.fits',\n                    self.__outPrefix + '.stellar_table.fits'))\n        # pylab.plot(rss_model[0,:],'-g')\n        # pylab.show()\n        if self.__datatype == 'RSS':\n            model_out = PyParadise.rss.RSS(wave=normDataSub.getWave(), data=rss_model, error=normDataSub.unnormalizedSpec()._error, mask=mask,\n                header=self.__inputData.getHeader(), normalization=normDataSub.getNormalization())\n            res_out = PyParadise.rss.RSS(wave=normDataSub.getWave(),\n                data=self.__inputData.subWaveLimits(start_wave, end_wave).getData() - rss_model,\n                header=self.__inputData.getHeader())\n        elif self.__datatype == 'CUBE':\n            model_out = PyParadise.cube.Cube(wave=normDataSub.getWave(), data=cube_model, error=normDataSub.unnormalizedSpec()._error, mask=mask,\n                header=self.__inputData.getHeader(), normalization=normDataSub.getNormalization())\n            res_out = PyParadise.cube.Cube(wave=normDataSub.getWave(),\n                data=self.__inputData.subWaveLimits(start_wave, end_wave).getData() - cube_model,\n                header=self.__inputData.getHeader())\n        if numpy.max(self.__inputData.getWave()[1:] - self.__inputData.getWave()[:-1]) - numpy.min(\n            self.__inputData.getWave()[1:] - self.__inputData.getWave()[:-1]) < 0.01:\n            model_out.writeFitsData(self.__outPrefix + '.cont_model.fits')\n            res_out.writeFitsData(self.__outPrefix + '.cont_res.fits')\n        else:\n            model_out.writeFitsData(self.__outPrefix + '.cont_model.fits', store_wave=True)\n            res_out.writeFitsData(self.__outPrefix + '.cont_res.fits', store_wave=True)\n\n        mass_weighted_pars = numpy.zeros((len(fitted), 5, len(bins) + 1), dtype=numpy.float32)\n        lum_weighted_pars = numpy.zeros((len(fitted), 5, len(bins) + 1), dtype=numpy.float32)\n        for i in range(len(fitted)):\n            if fitted[i]:\n                for j in range(len(bins)):\n                    try:\n                        mass_weighted_pars[i, :, j] = lib_norm.massWeightedPars(coeff[i, :], bins[j][0], bins[j][1])\n                    except:\n                        mass_weighted_pars[i, :, j] = numpy.array([numpy.nan, numpy.nan, numpy.nan, numpy.nan, numpy.nan])\n                    try:\n                        lum_weighted_pars[i, :, j] = lib_norm.lumWeightedPars(coeff[i, :], bins[j][0], bins[j][1])\n                    except:\n                        lum_weighted_pars[i, :, j] = numpy.array([numpy.nan, numpy.nan, numpy.nan, numpy.nan, numpy.nan])\n\n        columns = []\n        if self.__datatype == 'CUBE':\n            columns.append(pyfits.Column(name='x_cor', format='J', array=x_pix[fitted]))\n            columns.append(pyfits.Column(name='y_cor', format='J', array=y_pix[fitted]))\n        elif self.__datatype == 'RSS':\n            columns.append(pyfits.Column(name='fiber', format='J', array=fiber[fitted]))\n        columns.append(pyfits.Column(name='vel_fit', format='E', unit='km/s', array=vel_fit[fitted]))\n        columns.append(pyfits.Column(name='vel_fit_err', format='E', unit='km/s', array=vel_fit_err[fitted]))\n        if store_chain and self.__datatype == 'RSS':\n            columns.append(pyfits.Column(name='vel_trace', format='%dE'%(vel_trace.shape[1]), unit='km/s', array=vel_trace[fitted,:]))\n        columns.append(pyfits.Column(name='Rvel', format='E', unit='km/s', array=Rvel[fitted]))\n        columns.append(pyfits.Column(name='disp_fit', format='E', unit='km/s', array=disp_fit[fitted]))\n        columns.append(pyfits.Column(name='disp_fit_err', format='E', unit='km/s', array=disp_fit_err[fitted]))\n        if store_chain and self.__datatype == 'RSS':\n            columns.append(pyfits.Column(name='disp_trace', format='%dE'%(disp_trace.shape[1]), unit='km/s', array=disp_trace[fitted,:]))\n        columns.append(pyfits.Column(name='Rdisp', format='E', unit='km/s', array=Rdisp[fitted]))\n        columns.append(pyfits.Column(name='chi2', format='E', array=chi2[fitted]))\n        if lib.getBaseNumber() > 1:\n            columns.append(pyfits.Column(name='base_coeff', format='%dE' % (lib.getBaseNumber()), array=coeff[fitted, :]))\n        else:\n            columns.append(pyfits.Column(name='base_coeff', format='E', array=coeff[fitted].flatten()))\n        for i, postfix in enumerate(['total'] + ['bin{}'.format(i) for i in range(1, len(bins))]):\n            columns.append(pyfits.Column(name='lum_coeff_frac_' + postfix, format='E', array=lum_weighted_pars[fitted, 0, i]))\n            columns.append(pyfits.Column(name='lum_age_' + postfix, format='E', array=lum_weighted_pars[fitted, 1, i]))\n            columns.append(pyfits.Column(name='lum_M/L_' + postfix, format='E', array=lum_weighted_pars[fitted, 2, i]))\n            columns.append(pyfits.Column(name='lum_[Fe/H]_' + postfix, format='E', array=lum_weighted_pars[fitted, 3, i]))\n            columns.append(pyfits.Column(name='lum_[A/Fe]_' + postfix, format='E', array=lum_weighted_pars[fitted, 4, i]))\n            columns.append(pyfits.Column(name='mass_coeff_frac_' + postfix, format='E', array=mass_weighted_pars[fitted, 0, i]))\n            columns.append(pyfits.Column(name='mass_age_' + postfix, format='E', array=mass_weighted_pars[fitted, 1, i]))\n            columns.append(pyfits.Column(name='mass_M/L_' + postfix, format='E', array=mass_weighted_pars[fitted, 2, i]))\n            columns.append(pyfits.Column(name='mass_[Fe/H]_' + postfix, format='E', array=mass_weighted_pars[fitted, 3, i]))\n            columns.append(pyfits.Column(name='mass_[A/Fe]_' + postfix, format='E', array=mass_weighted_pars[fitted, 4, i]))\n\n        try:\n            table_out = pyfits.BinTableHDU.from_columns(columns)\n        except:\n            table_out = pyfits.new_table(columns)\n        table_out.writeto(self.__outPrefix + '.stellar_table.fits', overwrite=True)\n\n    def run_eline_fit(self, parfile, parallel, verbose):\n        \"\"\"This functions fits a a set of emission lines to the spectra.\n\n        Parameters\n        ----------\n        parfile : str\n            The parameter file containing the constraints under which the\n            emission lines will be fitted to the input spectra.\n        parallel : {'auto', int}, optional\n            If parallel is not equal to one, the python multiprocessing routine\n            shall be used to run parts of the code in parallel. With the option\n            `auto`, it adjusts the number of parallel processes to the number\n            of cpu-cores/threads that are available.\n        verbose : bool, optional\n            Produces screen output, such that the user can follow which spectrum\n            is currently fitted and what the results are for each spectrum.\n\n        Notes\n        -----\n        The function does not return anything, but writes the results of the fit\n        to disk. There are three files written to disk, all prepended by the\n        `outprefix` supplied to this class at creation. The three files are:\n        - `outprefix`.eline_model.fits which contains the best fitted emission\n          line spectra.\n        - `outprefix`.eline_res.fits contains the residual between the input\n          fits file and the best fitted emission line model spectra.\n        - `outprefix`.eline_table.fits contains the parameters of the best\n          fit, like flux, velocity and the FWHM.\n        \"\"\"\n        parList = PyParadise.parameters.ParameterList(parfile)\n        eCompFile = parList['eCompFile'].getValue()\n        vel_guess = float(parList['vel_guess'].getValue())\n        line_fit = PyParadise.parameters.CustomMasks(parList['line_fit_region'].getValue())\n        efit_method = parList['efit_method'].getValue()\n        efit_ftol = float(parList['efit_ftol'].getValue())\n        efit_xtol = float(parList['efit_xtol'].getValue())\n        guess_window = int(parList['eguess_window'].getValue())\n        min_x = float(parList['min_x'].getValue())\n        max_x = float(parList['max_x'].getValue())\n        min_y = float(parList['min_y'].getValue())\n        max_y = float(parList['max_y'].getValue())\n\n        hdu = pyfits.open(self.__outPrefix + '.stellar_table.fits')\n        stellar_table = hdu[1].data\n        if self.__datatype == 'CUBE':\n            x_cor = stellar_table.field('x_cor')\n            y_cor = stellar_table.field('y_cor')\n        elif self.__datatype == 'RSS':\n            fiber = stellar_table.field('fiber')\n\n        line_par = PyParadise.fit_profile.parFile(eCompFile, self.__instrFWHM)\n        if self.__datatype == 'CUBE':\n            res_out = PyParadise.cube.loadCube(self.__outPrefix + '.cont_res.fits')\n        elif self.__datatype == 'RSS':\n            res_out = PyParadise.rss.loadRSS(self.__outPrefix + '.cont_res.fits')\n        disp1 = res_out._wave[1]-res_out._wave[0]\n        res_wave_start = res_out._wave[0]-disp1/2.0\n        disp2 = res_out._wave[-1]-res_out._wave[-2]\n        res_wave_end = res_out._wave[-1]+disp2/2.0\n        res_out._error = self.__inputData.subWaveLimits(res_wave_start, res_wave_end)._error\n        res_out._mask = self.__inputData.subWaveLimits(res_wave_start, res_wave_end)._mask\n        if self.__datatype == 'CUBE':\n            out_lines = res_out.fitELines(line_par, line_fit.maskPixelsObserved(res_out.getWave(),\n                vel_guess / 300000.0), min_x, max_x, min_y, max_y, method=efit_method, guess_window=guess_window,\n                spectral_res=self.__instrFWHM, ftol=efit_ftol, xtol=efit_xtol, verbose=verbose, parallel=parallel)\n            model_line = PyParadise.cube.Cube(wave=res_out.getWave(), data=out_lines[4], header=self.__inputData.getHeader())\n            line_res = PyParadise.cube.Cube(wave=res_out.getWave(), data=res_out.getData() - model_line.getData(),\n                header=self.__inputData.getHeader())\n        elif self.__datatype == 'RSS':\n            out_lines = res_out.fitELines(line_par, line_fit.maskPixelsObserved(res_out.getWave(),\n                vel_guess / 300000.0), min_y, max_y, method=efit_method, guess_window=guess_window,\n                spectral_res=self.__instrFWHM, ftol=efit_ftol, xtol=efit_xtol, verbose=verbose, parallel=parallel)\n            model_line = PyParadise.rss.RSS(wave=res_out.getWave(), data=out_lines[3], header=self.__inputData.getHeader())\n            line_res = PyParadise.rss.RSS(wave=res_out.getWave(), data=res_out.getData() - model_line.getData(),\n                header=self.__inputData.getHeader())\n        if numpy.max(self.__inputData.getWave()[1:] - self.__inputData.getWave()[:-1]) - numpy.min(\n                     self.__inputData.getWave()[1:] - self.__inputData.getWave()[:-1]) < 0.01:\n            model_line.writeFitsData(self.__outPrefix + '.eline_model.fits')\n            line_res.writeFitsData(self.__outPrefix + '.eline_res.fits')\n        else:\n            model_line.writeFitsData(self.__outPrefix + '.eline_model.fits',store_wave=True)\n            line_res.writeFitsData(self.__outPrefix + '.eline_res.fits',store_wave=True)\n        indices = numpy.arange(len(out_lines[2]))\n        valid = numpy.zeros(len(out_lines[2]),dtype=\"bool\")\n        for i in range(len(out_lines[2])):\n            if self.__datatype == 'CUBE':\n                select_pos = (x_cor==out_lines[2][i]) & (y_cor==out_lines[3][i])\n            elif self.__datatype == 'RSS':\n                select_pos= fiber == out_lines[2][i]\n\n            if numpy.sum(select_pos)>0:\n                valid[i]=True\n        columns = []\n        if self.__datatype == 'CUBE':\n            columns.append(pyfits.Column(name='x_cor', format='J', array=out_lines[2][valid]))\n            columns.append(pyfits.Column(name='y_cor', format='J', array=out_lines[3][valid]))\n        elif self.__datatype == 'RSS':\n            columns.append(pyfits.Column(name='fiber', format='J', array=out_lines[2][valid]))\n        for n in line_par._names:\n            if line_par._profile_type[n] == 'Gauss':\n                columns.append(pyfits.Column(name='%s_flux' % (n), format='E', array=out_lines[0][n]['flux'][valid]))\n                columns.append(pyfits.Column(name='%s_vel' % (n), format='E', unit='km/s',\n                    array=out_lines[0][n]['vel'][valid]))\n                columns.append(pyfits.Column(name='%s_fwhm' % (n), format='E', unit='km/s',\n                        array=out_lines[0][n]['fwhm'][valid]))\n\n        try:\n            table_out = pyfits.BinTableHDU.from_columns(columns)\n        except:\n            table_out = pyfits.new_table(columns)\n        table_out.writeto(self.__outPrefix + '.eline_table.fits', overwrite=True)\n\n    def run_bootstrap(self, stellar_parfile, eline_parfile, bootstraps, modkeep, parallel, verbose):\n        \"\"\"The bootstrap functions performs a bootstrap on the data in order to\n        obtain errors. The errors for the template fitting are determined by\n        refitting with a subset of the templates (with fixed velocity and\n        velocity dispersion) and looking at the spread of the determined\n        parameters to obtain a bootstrapped error estimate. Each time the\n        templates are fitted, the emission lines are also fitted and this then\n        gives an estimate of the error in the emission line parameters.\n\n        Parameters\n        ----------\n        stellar_parfile : str\n            The parameter file containing the constraints under which the input\n            template spectra are fitted.\n        eline_par_file : str\n            The parameter file containing the constraints under which the\n            emission lines are fitted to the input spectra.\n        bootstraps : int\n            The number of bootstraps run to each spectra.\n        modkeep : float\n            The percentage of template spectra that will be keeped under each\n            bootstrap run.\n        parallel : {'auto', int}, optional\n            If parallel is not equal to one, the python multiprocessing routine\n            shall be used to run parts of the code in parallel. With the option\n            `auto`, it adjusts the number of parallel processes to the number\n            of cpu-cores/threads that are available.\n        verbose : bool, optional\n            Produces screen output, such that the user can follow which spectrum\n            is currently fitted and what the results are for each spectrum.\n\n        Notes\n        -----\n        The function does not return anything, but overwrites the stellar table\n        and emission-line table fits files created by the fitting functions\n        `run_SSP_fit` and `run_eline_fit`. The files\n        `outprefix`.stellar_table.fits and `outprefix`.eline_table.fits are\n        appended with information on the errors on the fitted parameters.\n        \"\"\"\n        ## Read in parameter file and get values\n        parList = PyParadise.parameters.ParameterList(stellar_parfile)\n        tmpldir = parList['tmpldir'].getValue()\n        tmplfile = parList['tmplfile'].getValue()\n        vel_guess = float(parList['vel_guess'].getValue())\n        vel_min = float(parList['vel_min'].getValue())\n        vel_max = float(parList['vel_max'].getValue())\n        nwidth_norm = int(parList['nwidth_norm'].getValue())\n        start_wave = float(parList['start_wave'].getValue())\n        end_wave = float(parList['end_wave'].getValue())\n        excl_fit = PyParadise.parameters.CustomMasks(parList['excl_fit'].getValue())\n        excl_cont = PyParadise.parameters.CustomMasks(parList['excl_cont'].getValue())\n        nlib_guess = int(parList['tmplinitspec'].getValue())\n        kin_bootstrap = bool(int(parList['kin_bootstrap'].getValue()))\n\n        bins = [[None, None]]\n        try:\n            f = open(parList['agebinfile'].getValue())\n            try:\n                for l in f.readlines():\n                    bins.append([float(l.split()[0]), float(l.split()[1])])\n            finally:\n                f.close()\n        except (IOError, ValueError):\n            if verbose:\n                print('agebinfile is non-existent or ignored.')\n                print('Optional stellar population binning will not occur.')\n\n        if nlib_guess < 0:\n            modkeep = 100.0\n\n        hdu = pyfits.open(self.__outPrefix + '.stellar_table.fits')\n        stellar_table = hdu[1].data\n        if self.__datatype == 'CUBE':\n            x_cor = stellar_table.field('x_cor')\n            y_cor = stellar_table.field('y_cor')\n        elif self.__datatype == 'RSS':\n            fiber = stellar_table.field('fiber')\n        vel = stellar_table.field('vel_fit')\n        disp = stellar_table.field('disp_fit')\n        if kin_bootstrap:\n            vel_err = stellar_table.field('vel_fit_err')\n            disp_err = stellar_table.field('disp_fit_err')\n        else:\n            vel_err = None\n            disp_err = None\n\n        if eline_parfile is not None:\n            parList = PyParadise.parameters.ParameterList(eline_parfile)\n            eCompFile = parList['eCompFile'].getValue()\n            vel_guess = float(parList['vel_guess'].getValue())\n            line_fit = PyParadise.parameters.CustomMasks(parList['line_fit_region'].getValue())\n            efit_method = parList['efit_method'].getValue()\n            efit_ftol = float(parList['efit_ftol'].getValue())\n            efit_xtol = float(parList['efit_xtol'].getValue())\n            guess_window = int(parList['eguess_window'].getValue())\n\n            line_par = PyParadise.fit_profile.parFile(eCompFile, self.__instrFWHM)\n\n            hdu = pyfits.open(self.__outPrefix + '.eline_table.fits')\n            eline_table = hdu[1].data\n            if self.__datatype == 'CUBE':\n                x_eline = eline_table.field('x_cor')\n                y_eline = eline_table.field('y_cor')\n            if self.__datatype == 'RSS':\n                fiber_eline = eline_table.field('fiber')\n\n        if verbose:\n            print(\"The stellar population library is being prepared.\")\n        lib = PyParadise.ssplibrary.SSPlibrary(filename=tmpldir + '/' + tmplfile)\n        min_wave = (start_wave / (1 + (vel_max + 2000) / 300000.0))\n        max_wave = (end_wave / (1 + (vel_min - 2000) / 300000.0))\n\n\n        if nlib_guess < 0:\n            select = numpy.arange(lib.getBaseNumber()) == nlib_guess * -1 - 1\n            lib = lib.subLibrary(select)\n        lib = lib.subWaveLibrary(min_wave=min_wave, max_wave=max_wave)\n        lib = lib.matchInstFWHM(self.__instrFWHM, vel_guess)\n        lib = lib.resampleWaveStepLinear(self.__inputData.getWaveStep(), vel_guess / 300000.0)\n        lib_norm = lib.normalizeBase(nwidth_norm, excl_cont, vel_guess / 300000.0)\n        lib_rebin = lib_norm.rebinLogarithmic()\n\n        if verbose:\n            print(\"The input data is being normalized.\")\n        normData = self.__inputData.normalizeSpec(nwidth_norm, excl_cont.maskPixelsObserved(self.__inputData.getWave(),\n             vel_guess / 300000.0))\n        #normData.writeFitsData('test.fits')\n        normDataSub = normData.subWaveLimits(start_wave, end_wave)\n        excl_fit = excl_fit.maskPixelsObserved(normDataSub.getWave(), vel_guess / 300000.0)\n        if eline_parfile is None:\n            if self.__datatype == 'CUBE':\n                (coeffs, maps, x_line, y_line) = normDataSub.fit_Lib_Boots(\n                    lib_rebin, x_cor, y_cor, vel, disp, vel_err, disp_err,\n                    mask_fit=excl_fit, bootstraps=bootstraps, modkeep=modkeep,\n                    parallel=parallel, verbose=verbose)\n            elif self.__datatype == 'RSS':\n                (coeffs, maps) = normDataSub.fit_Lib_Boots(\n                    lib_rebin, fiber, vel, disp, vel_err, disp_err,\n                    mask_fit=excl_fit, bootstraps=bootstraps, modkeep=modkeep,\n                    parallel=parallel, verbose=verbose)\n        else:\n            select_wave_eline = line_fit.maskPixelsObserved(normDataSub.getWave(), vel_guess / 300000.0)\n            if self.__datatype == 'CUBE':\n                (coeffs, maps, x_line, y_line) = normDataSub.fit_Lib_Boots(\n                    lib_rebin, x_cor, y_cor, vel, disp, vel_err, disp_err,\n                    line_par, select_wave_eline, excl_fit, efit_method,\n                    guess_window, self.__instrFWHM, efit_ftol, efit_xtol,\n                    bootstraps, modkeep, parallel, verbose)\n            elif self.__datatype == 'RSS':\n                (coeffs, maps) = \\\n                    normDataSub.fit_Lib_Boots(lib_rebin, fiber, vel, disp, vel_err, disp_err, bootstraps=bootstraps, par_eline=line_par,\n                    select_wave_eline=select_wave_eline, mask_fit=excl_fit, method_eline=efit_method,\n                    guess_window=guess_window, spectral_res=self.__instrFWHM, ftol=efit_ftol, xtol=efit_xtol,\n                    modkeep=modkeep, parallel=parallel, verbose=verbose)\n        mass_weighted_pars_full = numpy.zeros((len(vel), bootstraps, 5, len(bins) + 1), dtype=numpy.float32)\n        lum_weighted_pars_full = numpy.zeros((len(vel), bootstraps, 5, len(bins) + 1), dtype=numpy.float32)\n        for i in range(len(vel)):\n            for j in range(len(bins)):\n                for m in range(bootstraps):\n                    try:\n                        mass_weighted_pars_full[i, m, :, j] = lib_norm.massWeightedPars(coeffs[i, m, :], min_age=bins[j][0], max_age=bins[j][1])\n                    except:\n                        mass_weighted_pars_full[i, m, :, j] = numpy.array([numpy.nan, numpy.nan, numpy.nan, numpy.nan, numpy.nan])\n                    try:\n                        lum_weighted_pars_full[i, m, :, j] = lib_norm.lumWeightedPars(coeffs[i, m, :], min_age=bins[j][0], max_age=bins[j][1])\n                    except:\n                        lum_weighted_pars_full[i, m, :, j] = numpy.array([numpy.nan, numpy.nan, numpy.nan, numpy.nan, numpy.nan])\n        mass_weighted_pars_mean = numpy.nanmean(mass_weighted_pars_full, axis=1)\n        mass_weighted_pars_err = numpy.nanstd(mass_weighted_pars_full, axis=1)\n        lum_weighted_pars_mean = numpy.nanmean(lum_weighted_pars_full, axis=1)\n        lum_weighted_pars_err = numpy.nanstd(lum_weighted_pars_full, axis=1)\n        columns_stellar = []\n        for i, postfix in enumerate(['total'] + ['bin{}'.format(i) for i in range(1, len(bins))]):\n            columns_stellar.append(pyfits.Column(name='lum_coeff_frac_' + postfix + '_btmean', format='E', array=lum_weighted_pars_mean[:, 0, i]))\n            columns_stellar.append(pyfits.Column(name='lum_coeff_frac_' + postfix + '_err', format='E', array=lum_weighted_pars_err[:, 0, i]))\n            columns_stellar.append(pyfits.Column(name='lum_age_' + postfix + '_btmean', format='E', array=lum_weighted_pars_mean[:, 1, i]))\n            columns_stellar.append(pyfits.Column(name='lum_age_' + postfix + '_err', format='E', array=lum_weighted_pars_err[:, 1, i]))\n            columns_stellar.append(pyfits.Column(name='lum_M/L_' + postfix + '_btmean', format='E', array=lum_weighted_pars_mean[:, 2, i]))\n            columns_stellar.append(pyfits.Column(name='lum_M/L_' + postfix + '_err', format='E', array=lum_weighted_pars_err[:, 2, i]))\n            columns_stellar.append(pyfits.Column(name='lum_[Fe/H]_' + postfix + '_btmean', format='E', array=lum_weighted_pars_mean[:, 3, i]))\n            columns_stellar.append(pyfits.Column(name='lum_[Fe/H]_' + postfix + '_err', format='E', array=lum_weighted_pars_err[:, 3, i]))\n            columns_stellar.append(pyfits.Column(name='lum_[A/Fe]_' + postfix + '_btmean', format='E', array=lum_weighted_pars_mean[:, 4, i]))\n            columns_stellar.append(pyfits.Column(name='lum_[A/Fe]_' + postfix + '_err', format='E', array=lum_weighted_pars_err[:, 4, i]))\n            columns_stellar.append(pyfits.Column(name='mass_coeff_frac_' + postfix + '_btmean', format='E', array=mass_weighted_pars_mean[:, 0, i]))\n            columns_stellar.append(pyfits.Column(name='mass_coeff_frac_' + postfix + '_err', format='E', array=mass_weighted_pars_err[:, 0, i]))\n            columns_stellar.append(pyfits.Column(name='mass_age_' + postfix + '_btmean', format='E', array=mass_weighted_pars_mean[:, 1, i]))\n            columns_stellar.append(pyfits.Column(name='mass_age_' + postfix + '_err', format='E', array=mass_weighted_pars_err[:, 1, i]))\n            columns_stellar.append(pyfits.Column(name='mass_M/L_' + postfix + '_btmean', format='E', array=mass_weighted_pars_mean[:, 2, i]))\n            columns_stellar.append(pyfits.Column(name='mass_M/L_' + postfix + '_err', format='E', array=mass_weighted_pars_err[:, 2, i]))\n            columns_stellar.append(pyfits.Column(name='mass_[Fe/H]_' + postfix + '_btmean', format='E', array=mass_weighted_pars_mean[:, 3, i]))\n            columns_stellar.append(pyfits.Column(name='mass_[Fe/H]_' + postfix + '_err', format='E', array=mass_weighted_pars_err[:, 3, i]))\n            columns_stellar.append(pyfits.Column(name='mass_[A/Fe]_' + postfix + '_btmean', format='E', array=mass_weighted_pars_mean[:, 4, i]))\n            columns_stellar.append(pyfits.Column(name='mass_[A/Fe]_' + postfix + '_err', format='E', array=mass_weighted_pars_err[:, 4, i]))\n\n        columns_bootstrap = None\n        try:\n            if bool(int(parList['bootstrap_verb'].getValue())) != 0:\n                columns_bootstrap = []\n                for m in range(bootstraps):\n                    if lib.getBaseNumber() > 1:\n                        columns_bootstrap.append(pyfits.Column(\n                            name='bootstrap_coeff_{}'.format(m),\n                            format='%dE' % (lib.getBaseNumber()),\n                            array=coeffs[:, m]))\n                    else:\n                        columns_bootstrap.append(pyfits.Column(\n                            name='bootstrap_coeff_{}'.format(m),\n                            format='E', array=coeffs[:, m].flatten()))\n        except KeyError:  # in case bootstrap_verb is not in the parameters-file\n            pass\n\n        tbl_size = 8 + 2 if self.__datatype == 'CUBE' else 8 + 1\n        tbl_size += 10 * len(bins)\n        try:\n            hdu = pyfits.BinTableHDU.from_columns(stellar_table.columns[:tbl_size] + pyfits.ColDefs(columns_stellar))\n            if columns_bootstrap is not None:\n                btunit = pyfits.BinTableHDU.from_columns(pyfits.ColDefs(columns_bootstrap))\n        except:\n            hdu = pyfits.new_table(stellar_table.columns[:tbl_size] + pyfits.new_table(columns_stellar).columns)\n            if columns_bootstrap is not None:\n                btunit = pyfits.new_table(columns_bootstrap)\n        if columns_bootstrap is None:\n            hdu = pyfits.HDUList([pyfits.PrimaryHDU([]), hdu])\n        else:\n            hdu = pyfits.HDUList([pyfits.PrimaryHDU([]), hdu, btunit])\n        hdu.writeto(self.__outPrefix + '.stellar_table.fits', overwrite=True)\n\n        if self.__datatype == 'CUBE' and eline_parfile is not None:\n            mapping=numpy.zeros(len(x_eline),dtype=numpy.int32)\n            indices = numpy.arange(len(x_line))\n            for i in range(len(x_eline)):\n                select_pos = (x_line==x_eline[i]) & (y_line==y_eline[i])\n                if numpy.sum(select_pos)==1:\n                    mapping[i]=indices[select_pos]\n                else:\n                    mapping[i]=-1\n        elif self.__datatype == 'RSS' and eline_parfile is not None:\n            mapping=numpy.zeros(len(fiber_eline),dtype=numpy.int16)\n            indices = numpy.arange(len(fiber))\n            for i in range(len(fiber_eline)):\n                select_pos = fiber==fiber_eline[i]\n                if numpy.sum(select_pos)==1:\n                    mapping[i]=indices[select_pos]\n                else:\n                    mapping[i]=-1\n\t\n        if maps is not None:\n            columns_eline = []\n            for n in line_par._names:\n                if line_par._profile_type[n] == 'Gauss':\n                    columns_eline.append(pyfits.Column(name='%s_flux_err' % (n), format='E', array=maps[n]['flux_err'][mapping]))\n                    columns_eline.append(pyfits.Column(name='%s_vel_err' % (n), format='E', unit='km/s',\n                        array=maps[n]['vel_err'][mapping]))\n                    columns_eline.append(pyfits.Column(name='%s_fwhm_err' % (n), format='E', unit='km/s',\n                            array=maps[n]['fwhm_err'][mapping]))\n\n            \n            if self.__datatype == 'CUBE':\n                add_column=2\n            else:\n                add_column=1\n            try:\n                hdu = pyfits.BinTableHDU.from_columns(eline_table.columns[:len(columns_eline) + add_column] + pyfits.ColDefs(columns_eline))\n            except:\n                hdu = pyfits.new_table(eline_table.columns[:len(columns_eline) + 2] + pyfits.new_table(columns_eline).columns)\n            hdu.writeto(self.__outPrefix + '.eline_table.fits', overwrite=True)\n\n\nif __name__ == \"__main__\":\n\n    parser = argparse.ArgumentParser(description=\"\"\"\nProgram to model the stellar population model from spectrosopic data stored either in RSS or datacube format.\nEstimated parameters are velocity, velocity disperion, the best fit continuum model, and the star formation history.\nAdditionally the program allows to model emission lines in the residual spectra and infer the errors using a bootstrap\nMonte Carlo simulation taking systematic uncertainties of the continuum model estimation into account.\"\"\",\nformatter_class=argparse.ArgumentDefaultsHelpFormatter, prog='Paradise')\n    parser.add_argument('--version', action='version', version='Paradise version %s' % (__version__))\n\n    parser.add_argument(\"input\", type=str, help=\"\"\"File name of the input datacube or RSS file. Please have a look at the\n        documentation for the correct format of each file.\"\"\")\n    parser.add_argument(\"outprefix\", type=str, help=\"\"\"Prefix used for nameing all the output file names.\"\"\")\n    parser.add_argument(\"instrFWHM\", type=str, help=\"\"\"Instrumental spectral resolution of the input spectra.\"\"\")\n    parser.add_argument(\"--SSP_par\", type=str, default=None, help=\"\"\"File name of the parameter file that controls the fitting procedure\"\"\")\n    parser.add_argument(\"--line_par\", type=str, default=None, help=\"\"\"File name of the parameter file that controls the fitting procedure\"\"\")\n    parser.add_argument(\"--bootstraps\", type=int, default=None, help=\"\"\"Number of bootstraps iterations per spectrum\"\"\")\n    parser.add_argument(\"--modkeep\", type=float, default=80, help=\"\"\"Fraction of random SSP models used for each bootstrap.\"\"\")\n    parser.add_argument(\"--parallel\", type=str, default=\"auto\", help=\"\"\"Options are: 'auto' - using all CPUs available on the\n    machine, an integer number specifying in the number of CPUs. An integer of 1 means no parrell processing.\"\"\")\n    parser.add_argument(\"--verbose\", action=\"store_true\", default=False, help=\"\"\"Flag to print some progress information on\n    the screen. The default is False.\"\"\")\n\n    args = parser.parse_args()\n    app = ParadiseApp(args.input, args.outprefix, args.instrFWHM)\n    if args.SSP_par is not None and args.bootstraps is None:\n        app.run_SSP_fit(args.SSP_par, args.parallel, args.verbose)\n    if args.line_par is not None and args.bootstraps is None:\n        app.run_eline_fit(args.line_par, args.parallel, args.verbose)\n    if args.bootstraps is not None:\n        app.run_bootstrap(args.SSP_par, args.line_par, args.bootstraps, args.modkeep, args.parallel, args.verbose)\n", "meta": {"hexsha": "cef10479d4839e2c70f12fbe0634701b1c086914", "size": 41664, "ext": "py", "lang": "Python", "max_stars_repo_path": "bin/ParadiseApp.py", "max_stars_repo_name": "brandherd/PyParadise", "max_stars_repo_head_hexsha": "1c65bf634e17931f165fd88b9938f604b9371e2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-01T13:07:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-01T13:07:54.000Z", "max_issues_repo_path": "bin/ParadiseApp.py", "max_issues_repo_name": "brandherd/PyParadise", "max_issues_repo_head_hexsha": "1c65bf634e17931f165fd88b9938f604b9371e2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-11-03T02:07:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T20:35:04.000Z", "max_forks_repo_path": "bin/ParadiseApp.py", "max_forks_repo_name": "brandherd/PyParadise", "max_forks_repo_head_hexsha": "1c65bf634e17931f165fd88b9938f604b9371e2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.3504273504, "max_line_length": 345, "alphanum_fraction": 0.6302563364, "include": true, "reason": "import numpy,from astropy", "num_tokens": 9963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096344, "lm_q2_score": 0.3276683139517237, "lm_q1q2_score": 0.16895231330276367}}
{"text": "import numpy as np\nimport gc\n\nfrom multiprocessing.pool import ThreadPool\n\nfrom scipy.linalg import pinv\nfrom scipy.sparse import csr_matrix\nfrom scipy.sparse import lil_matrix\n\nfrom .util import _checkState, _thresholding, _save, _load\nfrom .distributed import *\n\nfrom pyspark import keyword_only, SparkContext\nfrom pyspark.ml import Estimator, Model\nfrom pyspark.ml.evaluation import Evaluator\nfrom pyspark.ml.param import *\nfrom pyspark.ml.param.shared import HasMaxIter, HasStandardization, HasTol\nfrom pyspark.ml.tuning import CrossValidator, CrossValidatorModel\n\n\nclass CCA(Estimator, HasMaxIter, HasStandardization, HasTol):\n    verbose = Param(Params._dummy(), \"verbose\", \"if True, print progress to STDOUT\")\n    k = Param(Params._dummy(), \"k\", \"the number of canonical vectors\",\n              typeConverter=TypeConverters.toInt)\n\n    rhos = Param(Params._dummy(), \"rhos\", \"the sparsity parameters in [0,1]\",\n                 typeConverter=TypeConverters.toList)\n\n    colsPerBlock = Param(Params._dummy(), \"colsPerBlock\",\n                         \"Number of columns in the blocks of the two input \"\n                         \"matrices when they are distributed\",\n                         typeConverter=TypeConverters.toList)\n\n    broadcast = Param(Params._dummy(), \"broadcast\",\n                      \"whether or not to broadcast during distributed matrix \"\n                      \"multiplication\",\n                      typeConverter=TypeConverters.toBoolean)\n\n    caching = Param(Params._dummy(), \"caching\",\n                      \"whether or not to cache underlying RDDs of ColBlockMatrices\",\n                      typeConverter=TypeConverters.toBoolean)\n\n    @keyword_only\n    def __init__(self, k=1, maxIter=1000, rhos=[0.1], colsPerBlock=[1024],\n                 broadcast=True, caching=True, standardization=True, tol=1e-4,\n                 verbose=False):\n        super(CCA, self).__init__()\n        self._setDefault(\n            k=1, maxIter=1000, rhos=[0.1], colsPerBlock=[1024], broadcast=True,\n            caching=True, standardization=True, tol=1e-4, verbose=False\n        )\n        kwargs = self._input_kwargs\n        self.setParams(**kwargs)\n\n    def setVerbose(self, verbose):\n        \"\"\"\n        Sets the value of :py:attr:`verbose`.\n        \"\"\"\n        return self._set(verbose=verbose)\n\n    def getVerbose(self):\n        \"\"\"\n        Gets the value of verbose or its default value.\n        \"\"\"\n        return self.getOrDefault(self.verbose)\n\n    @keyword_only\n    def setParams(self, k=1, maxIter=1000, rhos=[0.1],\n                  colsPerBlock=[1024], broadcast=True, caching=True,\n                  standardization=True, tol=1e-4, verbose=False):\n        self.setK(k)\n        self.setMaxIter(maxIter)\n        self.setRhos(rhos)\n        self.setColsPerBlock(colsPerBlock)\n        self.setBroadcast(broadcast)\n        self.setCaching(caching)\n        self.setStandardization(standardization)\n        self.setTol(tol)\n        self.setVerbose(verbose)\n\n    def setRhos(self, value):\n        \"\"\"\n        Sets the value of :py:attr:`rhos`.\n        \"\"\"\n        assert min(value) >= 0 and max(value) <= 1, \\\n            \"all rhos must be in [0, 1]\"\n        return self._set(rhos=value)\n\n    def getRhos(self):\n        \"\"\"\n        Gets the value of :py:attr:`rhos` or its default value.\n        \"\"\"\n        return self.getOrDefault(self.rhos)\n\n    def setColsPerBlock(self, value):\n        \"\"\"\n        Sets the value of :py:attr:`colsPerBlock`.\n        \"\"\"\n        # assert len(value) == 2, \"colsPerBlock must be a two-tuple\"\n        assert min(value) > 0, \"colsPerBlock must be positive\"\n        return self._set(colsPerBlock=value)\n\n    def getColsPerBlock(self):\n        \"\"\"\n        Gets the value of :py:attr:`colsPerBlock`. or its default value.\n        \"\"\"\n        return self.getOrDefault(self.colsPerBlock)\n\n    def setBroadcast(self, value):\n        \"\"\"\n        Sets the value of :py:attr:`broadcast`.\n        \"\"\"\n        return self._set(broadcast=value)\n\n    def getBroadcast(self):\n        \"\"\"\n        Gets the value of :py:attr:`broadcast` or its default value.\n        \"\"\"\n        return self.getOrDefault(self.broadcast)\n\n    def setCaching(self, value):\n        \"\"\"\n        Sets the value of :py:attr:`caching`.\n        \"\"\"\n        return self._set(caching=value)\n\n    def getCaching(self):\n        \"\"\"\n        Gets the value of :py:attr:`caching` or its default value.\n        \"\"\"\n        return self.getOrDefault(self.caching)\n\n    def setK(self, value):\n        \"\"\"\n        Sets the value of :py:attr:`k`.\n        \"\"\"\n        assert value > 0, \"k must be greater than 0\"\n        return self._set(k=value)\n\n    def getK(self):\n        \"\"\"\n        Gets the value of k or its default value.\n        \"\"\"\n        return self.getOrDefault(self.k)\n\n    def _fit(self, datasets):\n        \"\"\"\n        Computes multiple CCs using a deflation scheme.\n        :param datasets: A list of numpy.arrays.\n        \"\"\"\n        standardization = self.getStandardization()\n        n_ccs = self.getK()\n        maxIter = self.getMaxIter()\n        rhos = self.getRhos()\n        tol = self.getTol()\n        colsPerBlock = self.getColsPerBlock()\n        broadcast = self.getBroadcast()\n        caching = self.getCaching()\n        verbose = self.getVerbose()\n\n        if standardization:\n            datasets = [X - np.mean(X, axis=0) for X in datasets]\n\n        d = len(datasets)\n\n        if len(rhos) == 1:\n            rhos = rhos * d\n        else:\n            assert len(rhos) == d,\\\n                \"Please provide one regularization parameter per dataset.\"\n        if len(colsPerBlock) == 1:\n            colsPerBlock = colsPerBlock * d\n        else:\n            assert len(colsPerBlock) == d,\\\n                \"Please provide one colsPerBlock value per dataset.\"\n\n        # cross covariance matrices\n        CC = [\n            makeColBlockMatrix(datasets[i], colsPerBlock[i], caching)\n            .leftMultiply(datasets[j].T, broadcast)\n            for i in range(d)\n            for j in (x for y in (range(i), range(i+1, d))\n                      for x in y)  # all indices other than i\n        ]\n\n        # matrices of sparse loadings\n        ZZ = [lil_matrix((n_ccs, X.shape[1])) for X in datasets]\n        Sigma = []\n\n        for k in range(n_ccs):\n\n            z_init = []  # initial estimates of sparse canonical loadings\n            pattern = []  # sparsity patterns\n\n            for i in range(d):\n\n                # 1. Get the cov matrices involving dataset i. For any\n                #    covariance matrix involving a dataset that was\n                #    already processed, reduce the rows using the sparsity\n                #    pattern that was computed.\n                # 2. Call singleL1 one time for all of those cov matrices,\n                #    returning a z for each one.\n                # 3. Add the z's up from step 2 and threshold and standardize\n                #    the resulting vector. This is z initial for dataset i.\n\n                z = np.zeros(datasets[i].shape[1])\n                max_rho = 0\n\n                # indices of datasets other than i\n                not_i = [x for y in (range(i), range(i+1, d)) for x in y]\n\n                # indices of covariance matrices we'll need for this iteration\n                for j in range(i*(d - 1), (i + 1)*(d - 1)):\n\n                    # get the index of the left dataset in CC[j]\n                    left_idx = not_i[j % (d - 1)]\n\n                    if left_idx < i:\n                        p = pattern[left_idx]\n                        if np.size(p) == 0:\n                            print(\"Canonical loading vector \" + str(k) +\n                                  \" of dataset \" + str(left_idx) +\n                                  \" is all zeros. Moving on to next dataset.\")\n                            # move on to next not_i dataset\n                            import pdb; pdb.set_trace()\n                            continue\n                    else:\n                        p = None  # keep all columns of left dataset\n\n                    if k == 0:\n                        lZ = None\n                        rZ = None\n                    else:\n                        lZ = (ZZ[left_idx][0:k, p] if p is not None\n                              else ZZ[left_idx][0:k, :]).tocsr()\n                        sigma_ij = np.diag(\n                            [Sigma[cc][i, left_idx] for cc in range(k)]\n                        )\n                        rZ = csr_matrix.dot(\n                            sigma_ij,\n                            ZZ[i][0:k, :].tocsr()\n                        ) ## TODO: check\n\n                    z_term, this_rho = CCA._singleL1(\n                        CC[j], datasets[left_idx][:, p] if p is not None\n                        else datasets[left_idx], datasets[i],\n                        rhos[i], tol, maxIter, lZ, rZ, p, verbose\n                    )\n                    z += z_term\n                    if this_rho > max_rho:\n                        max_rho = this_rho\n\n                z = _thresholding(z, max_rho)\n                norm_z = np.linalg.norm(z)\n                if norm_z > 0:\n                    z = z / norm_z\n\n                pattern.append(z.nonzero()[0])\n                z_init.append(z)\n\n            zz, sigma = CCA._coeffEstSingleComp(\n                datasets, z_init, pattern, k, maxIter, tol, ZZ, Sigma, verbose\n            )\n            for i in range(d):\n                ZZ[i][k, pattern[i]] = zz[i]\n            Sigma.append(sigma)\n            Sigma[k] += np.tril(Sigma[k]).T\n\n            for i in range(d):\n                for j in (x for y in (range(i), range(i+1, d)) for x in y):\n                    # C_ij - z_i.T C_ij z_j * z_i z_j.T\n                    # subtractOuter mutates its object, so no need to reassign to CC\n                    CC[i*(d - 1) + (j if j < i else j - 1)].subtractOuter(\n                        Sigma[k][i, j] * ZZ[j][k, :].todense().getA1(),\n                        ZZ[i][k, :].todense().getA1()\n                    )\n        ## done, unpersist the ColBlockMatrices\n        if caching:\n            for cbm in CC:\n                cbm.unpersist()\n        del CC\n        gc.collect()\n        return CCAModel(k=n_ccs, ZZ=[Z.tocsr() for Z in ZZ], Sigma=Sigma,\n                        standardization=standardization, rhos=rhos)\n\n    def fit(self, datasets, params=None):\n        \"\"\"\n        Overrides pyspark.ml.Estimator's fit method.\n        \"\"\"\n        # TODO: assert all datasets are np.array\n        assert len(datasets) > 1, \"need at least 2 datasets\"\n        assert np.all(\n            np.array([X.shape[0] for X in datasets]) == datasets[0].shape[0]),\\\n            \"all datasets must have same number of observations\"\n        if params is None:\n            params = dict()\n        if isinstance(params, (list, tuple)):\n            models = [None] * len(params)\n            for index, model in self.fitMultiple(datasets, params):\n                models[index] = model\n            return models\n        elif isinstance(params, dict):\n            if params:\n                return self.copy(params)._fit(datasets)\n            else:\n                return self._fit(datasets)\n        else:\n            raise ValueError(\"Params must be either a param map or a list/\"\n                             \"tuple of param maps, but got %s.\" % type(params))\n\n    @staticmethod\n    def _coeffEstSingleComp(datasets, z_init, pattern, k, maxIter, tol,\n                            ZZ=None, Sigma=None, verbose=False):\n        \"\"\"\n        \"\"\"\n        d = len(datasets)\n        z_final = []\n\n        for i in range(d):\n\n            # get reduced versions of the ith dataset and initial loadings\n            # vector using the ith sparsity pattern\n            p_i = pattern[i]\n            if p_i.size == 0:\n                continue\n            X_i = datasets[i][:, p_i]\n            z_i = z_init[i][p_i]\n\n            nIter = 1\n            f = []\n\n            while not _checkState(f, nIter, maxIter, tol, verbose) in (-1, 1, 2):\n\n                tmp = np.zeros(p_i.size)\n\n                # all indices other than i\n                for j in (x for y in (range(i), range(i+1, d)) for x in y):\n\n                    p_j = pattern[j]\n                    if np.size(p_j) == 0:\n                        continue\n                    X_j = datasets[j][:, p_j]\n                    if j < i:\n                        z_j = z_final[j]  # already shrunken\n                        tmp += np.matmul(  # X_i.T @ X_j @ z_j\n                            X_i.T, np.matmul(\n                                X_j, z_j\n                            )\n                        )\n                        if k > 0:\n                            tmp -= Sigma[k-1][i, j] * csr_matrix.dot(\n                                ZZ[j][k-1, p_j].tocsr(), z_j\n                            ) * ZZ[i][k-1, p_i].tocsr().transpose().\\\n                                todense().getA1()\n                    else:\n                        tmp += np.matmul(  # X_i.T @ X_j @ X_j.T @ X_i @ z_i\n                            X_i.T, np.matmul(\n                                X_j, np.matmul(\n                                    X_j.T, np.matmul(X_i, z_i)\n                                )\n                            )\n                        )\n                        if k > 0:\n                            sig = Sigma[k-1][i, j]\n                            zz_i = ZZ[i][k-1, p_i].tocsr()  # row vector\n                            zz_j = ZZ[j][k-1, p_j].tocsr()  # row vector\n                            tmp -= sig * np.dot(\n                                csr_matrix.dot(\n                                    zz_j, X_j.T\n                                ),\n                                np.matmul(X_i, z_i)\n                            ) * zz_i.transpose().todense().getA1() +\\\n                                sig * csr_matrix.dot(zz_i, z_i) *\\\n                                np.matmul(\n                                    X_i.T, csr_matrix.dot(\n                                        X_j, zz_j.transpose()\n                                    )\n                                ).ravel() - sig**2 * csr_matrix.dot(\n                                    zz_j, zz_j.transpose()\n                                ).todense().getA1() * csr_matrix.dot(\n                                    zz_i, z_i\n                                ) * zz_i.transpose().todense().getA1()\n\n                norm_tmp = np.linalg.norm(tmp)\n                f.append(-2*norm_tmp)\n                if norm_tmp > 0:\n                    z_i = tmp / norm_tmp\n                else:\n                    z_i = tmp\n                nIter += 1\n\n            z_final.append(z_i.ravel())\n\n        sigma = np.zeros((d, d))\n        for i in range(d):\n            p_i = pattern[i]\n            X_i = datasets[i][:, p_i]\n            z_i = z_final[i]\n            if k > 0:\n                z_i_prev = ZZ[i][k-1, p_i].todense().getA1()  # row vector\n            for j in range(i):\n                p_j = pattern[j]\n                if p_i.size == 0 or p_j.size == 0:\n                    sigma[i, j] = 0\n                    continue\n                X_j = datasets[j][:, p_j]\n                z_j = z_final[j]\n                if k == 0:\n                    # z_i.T @ X_i.T X_j z_j for j < i\n                    sigma[i, j] = np.dot(\n                        np.matmul(X_i, z_i),\n                        np.matmul(X_j, z_j)\n                    )\n                else:\n                    z_j_prev = ZZ[j][k-1, p_j].todense().getA1()\n                    # z_i.T @ (X_i.T @ X_j - Sigma[k-1][i, j] *\n                    #     ZZ[i][k-1,p_i] @ ZZ[j][k-1,p_j].T) @ z_j\n                    sigma[i, j] = np.dot(\n                        np.matmul(X_i, z_i),\n                        np.matmul(X_j, z_j)\n                    ) - Sigma[k-1][i, j] *\\\n                        np.dot(z_i, z_i_prev) * np.dot(z_j, z_j_prev)\n\n        return (z_final, sigma)\n\n    @staticmethod\n    def _singleL1(covBlock, lX, rX, rho, tol, maxIter,\n                  lZ=None, rZ=None, p=None, verbose=False):\n        \"\"\"\n        Using an off-diagonal block of the sample covariance matrix,\n        `covBlock`, return an initial estimate of the canonical loading\n        vector corresponding to the `right` matrix of `covBlock`.\n\n        :param covBlock: A sparkle.distributed.ColBlockMatrix formed by\n                       multiplying the transpose of the `lX` matrix by\n                       the `rX` matrix.\n        :param lX: The left matrix in the sample covariance block.\n        :param rX: The right matrix in the sample covariance block.\n        :param lZ: A scipy.sparse.csr_matrix which contains the loadings\n                   corresponding to the left matrix (optional).\n        :param rZ: A scipy.sparse.csr_matrix which contains the loadings\n                   corresponding to the right matrix (optional).\n        :param rho: Sparsity parameter.\n        :param tol: Convergence tolerance.\n        :param maxIter: Maxiumum number of iterations.\n        :param p: Optional sparsity pattern.\n        \"\"\"\n        rho_max, x = covBlock.maxL2NormCol(p)\n        x = x / rho_max\n        rho = rho * rho_max\n\n        f = []\n        nIter = 1\n\n        while not _checkState(f, nIter, maxIter, tol, verbose):\n\n            z = np.matmul(rX.T, np.matmul(lX, x))\n            if lZ is not None:\n                z = z - rZ.transpose().dot(lZ.dot(x))\n            z = _thresholding(z, rho)\n\n            f.append(np.sum(z**2))\n\n            x = np.matmul(lX.T, np.matmul(rX, z))\n            if lZ is not None:\n                x = x - lZ.transpose().dot(rZ.dot(z))\n            norm_x = np.linalg.norm(x)\n            if norm_x > 0:\n                x = x / norm_x\n\n            nIter += 1\n\n        z = np.matmul(rX.T, np.matmul(lX, x))\n        if lZ is not None:\n            z = z - rZ.transpose().dot(lZ.dot(x))\n        return z, rho\n\n    def suggest_colsPerBlock(datasets, n_cores=4, partitions_per_core=3):\n        \"\"\"\n        :param partitions_per_core: Spark recommends 2-4 partitions per CPU.\n          See https://spark.apache.org/docs/latest/rdd-programming-guide.html\n        \"\"\"\n        nCols = np.array([X.shape[1] for X in datasets])\n        nPartitions = n_cores * partitions_per_core\n        return (nCols / nPartitions).astype(int)\n\n\nclass CCAModel(Model, HasStandardization):\n\n    k = Param(Params._dummy(), \"k\", \"the number of canonical vectors\",\n              typeConverter=TypeConverters.toInt)\n\n    rhos = Param(Params._dummy(), \"rhos\", \"the sparsity parameters in [0,1]\",\n                 typeConverter=TypeConverters.toList)\n\n    @keyword_only\n    def __init__(self, k=1, ZZ=None, Sigma=None, standardization=True,\n                 rhos=[0.1]):\n        super(CCAModel, self).__init__()\n        self._setDefault(k=1, standardization=True, rhos=[0.1])\n        kwargs = self._input_kwargs\n        self.setParams(**kwargs)\n\n    @keyword_only\n    def setParams(self, k=1, ZZ=None, Sigma=None, standardization=True,\n                  rhos=[0.1]):\n        self.setK(k)\n        self.setStandardization(standardization)\n        self.setRhos(rhos)\n        self.__ZZ = ZZ\n        self.__Sigma = Sigma\n\n    def setK(self, value):\n        \"\"\"\n        Sets the value of :py:attr:`k`.\n        \"\"\"\n        assert value > 0, \"k must be greater than 0\"\n        return self._set(k=value)\n\n    def getK(self):\n        \"\"\"\n        Gets the value of k or its default value.\n        \"\"\"\n        return self.getOrDefault(self.k)\n\n    def setRhos(self, value):\n        \"\"\"\n        Sets the value of :py:attr:`rhos`.\n        \"\"\"\n        assert min(value) >= 0 and max(value) <= 1,\\\n            \"all rhos must be in [0, 1]\"\n        return self._set(rhos=value)\n\n    def getRhos(self):\n        \"\"\"\n        Gets the value of :py:attr:`rhos` or its default value.\n        \"\"\"\n        return self.getOrDefault(self.rhos)\n\n    @property\n    def ZZ(self):\n        \"\"\"\n        A np.array of scipy.sparse.csr_matrix with first :py:attr:`k` canonical\n        weight vectors.\n        \"\"\"\n        return self.__ZZ\n\n    @property\n    def Sigma(self):\n        \"\"\"\n        A np.array of scipy.sparse.csr_matrix with first :py:attr:`k` canonical\n        weights on the diagonal.\n        \"\"\"\n        return self.__Sigma\n\n    def canonicalCorrelations(self, datasets = None):\n        \"\"\"\n        Take :py:attr:`k` datasets and return the :py:attr:`k` canonical correlations.\n        :param datasets: A list of numpy.arrays.\n        \"\"\"\n        if datasets is not None:\n            XZ = [csr_matrix.dot(X, Z.transpose()) for X, Z in\n                  zip(datasets, self.ZZ)]\n            k = self.getK()\n            corrs = np.zeros((k, len(XZ), len(XZ)))\n            for i in range(len(XZ)):\n                corrs[:, i, i] = np.ones(k)\n                for j in range(i + 1, len(XZ)):\n                    for cc in range(k):\n                        corrs[cc, j, i] = np.corrcoef(\n                            XZ[i][:, cc], XZ[j][:, cc], rowvar=False)[0, 1]\n            for cc in range(k):\n                # fill in the upper triangles with the transpose of the lower\n                corrs[cc, :, :] = corrs[cc, :, :] + np.tril(\n                    corrs[cc, :, :], -1).T\n        else:\n            corrs = None  # TODO: save canonical correlations during CCA.fit\n        return np.nan_to_num(corrs)\n\n    def _transform(self, datasets, outcome_index=None):\n        # TODO: use 'outcome_index' to allow user to use d - 1 datasets to predict the\n        # remaining one\n        ZZ = self.ZZ\n        d = len(ZZ)\n        assert len(datasets) == d,\\\n            \"number of datasets should be len(self.ZZ)\"\n        standardization = self.getStandardization()\n        if standardization:\n            datasets = [X - np.mean(X, axis=0) for X in datasets]\n\n        if outcome_index is not None:\n            assert outcome_index >= 0 and outcome_index < d,\\\n                \"outcome_index is not a valid index for datasets\"\n            XZ = [csr_matrix.dot(datasets[j], ZZ[j].transpose()) for j in\n                  [x for x in range(d) if x != outcome_index]]\n            XZ_sums = np.sum(XZ, axis=0)\n            prediction = np.dot(XZ_sums, pinv(ZZ[outcome_index].todense()).transpose())\n        else:\n            XZ = [csr_matrix.dot(X, Z.transpose()) for X, Z in zip(datasets, ZZ)]\n            XZ_sums = []\n            for i in range(d):\n                for j in range(d):\n                    if j != i:\n                        if len(XZ_sums) == i:\n                            XZ_sums.append(XZ[j])\n                        else:\n                            XZ_sums[i] += XZ[j]\n            prediction = [np.dot(XZ_sums[i], pinv(ZZ[i].todense()).transpose())\n                          for i in range(d)]\n        return prediction\n\n    def transform(self, datasets, params=None, outcome_index=None):\n        \"\"\"\n        Overrides pyspark.ml.Transformer's transform method.\n        :param datasets: A list of np.arrays corresponding to self.ZZ\n        :param params: an optional param map that overrides embedded params.\n        :returns: predictions\n        \"\"\"\n        if params is None:\n            params = dict()\n        if isinstance(params, dict):\n            if params:\n                return self.copy(params)._transform(datasets, outcome_index)\n            else:\n                return self._transform(datasets, outcome_index)\n        else:\n            raise ValueError(\"Params must be a param map but got %s.\" % type(params))\n\n    def save(self, path):\n        \"\"\"Save this CCAModel instance to the given path\"\"\"\n        _save(self, path)\n\n    def load(path):\n        \"\"\"Load a CCAModel instance from the given path\"\"\"\n        return _load(path)\n\n\nclass CCACanonicalCorrelationEvaluator(Evaluator):\n\n    def _evaluate(self, canCorrs):\n        # TODO: extract upper triangles\n        return np.mean(canCorrs)\n\n    def evaluate(self, model, datasets, params=None):\n        \"\"\"\n        Overrides pyspark.ml.evaluation.Evaluator's evaluate method.\n        :param canCorrs: the result of a call to CCAModel.canonicalCorrelations\n        :returns: average correlation between the canonical variables\n        \"\"\"\n        if params is None:\n            params = dict()\n        if isinstance(params, dict):\n            if params:\n                return self.copy(params)._evaluate(\n                    model.canonicalCorrelations(datasets)\n                )\n            else:\n                return self._evaluate(\n                    model.canonicalCorrelations(datasets)\n                )\n        else:\n            raise ValueError(\"Params must be a param map but got %s.\"\n                             % type(params))\n\n\nclass CCAPredictionEvaluator(Evaluator):\n\n    outcome_index = Param(Params._dummy(), \"outcome_index\",\n                          \"the index of the outcome dataset\",\n                          typeConverter=TypeConverters.toInt)\n\n    @keyword_only\n    def __init__(self, outcome_index=0):\n        super(Evaluator, self).__init__()\n        self._setDefault(outcome_index=0)\n        kwargs = self._input_kwargs\n        self.setParams(**kwargs)\n\n    @keyword_only\n    def setParams(self, outcome_index=0):\n        self.setOutcomeIndex(outcome_index)\n\n    def setOutcomeIndex(self, value):\n        \"\"\"\n        Sets the value of :py:attr:`outcome_index`.\n        \"\"\"\n        return self._set(outcome_index=value)\n\n    def getOutcomeIndex(self):\n        \"\"\"\n        Gets the value of :py:attr:`outcome_index`.\n        \"\"\"\n        return self.getOrDefault(self.outcome_index)\n\n    def _evaluate(self, prediction, dataset):\n        corrs = np.zeros(prediction.shape[1])\n        for i in range(prediction.shape[1]):\n            corrs[i] = np.corrcoef(prediction[:, i], dataset[:, i])[0, 1]\n        return np.mean(np.nan_to_num(corrs))\n\n    def evaluate(self, model, datasets, params=None):\n        \"\"\"\n        Overrides pyspark.ml.evaluation.Evaluator's evaluate method.\n        :param canCorrs: the result of a call to CCAModel.canonicalCorrelations\n        :returns: average correlation between the canonical variables\n        \"\"\"\n        if params is None:\n            params = dict()\n        if isinstance(params, dict):\n            if params:\n                return self.copy(params)._evaluate(\n                    model.transform(datasets, outcome_index=self.getOutcomeIndex()),\n                    datasets[self.getOutcomeIndex()]\n                )\n            else:\n                return self._evaluate(\n                    model.transform(datasets, outcome_index=self.getOutcomeIndex()),\n                    datasets[self.getOutcomeIndex()]\n                )\n        else:\n            raise ValueError(\"Params must be a param map but got %s.\"\n                             % type(params))\n\n\nclass CCACrossValidator(CrossValidator):\n    \"\"\"\n    Borrows heavily from pyspark.ml.tuning.CrossValidator.\n    \"\"\"\n    verbose = Param(Params._dummy(), \"verbose\", \"if True, print progress to STDOUT\")\n\n    @keyword_only\n    def __init__(self, estimator=None, estimatorParamMaps=None, evaluator=None,\n                 numFolds=3, seed=None, parallelism=1, verbose=False):\n        super(CCACrossValidator, self).__init__(\n            estimator=estimator,\n            estimatorParamMaps=estimatorParamMaps,\n            evaluator=evaluator,\n            numFolds=numFolds, seed=seed,\n            parallelism=parallelism\n        )\n        self._setDefault(verbose=False)\n        kwargs = self._input_kwargs\n        self.setParams(**kwargs)\n\n    @keyword_only\n    def setParams(self, estimator=None, estimatorParamMaps=None, evaluator=None,\n                  numFolds=3, seed=None, parallelism=1, verbose=False):\n        self.setEstimator(estimator)\n        self.setEstimatorParamMaps(estimatorParamMaps)\n        self.setEvaluator(evaluator)\n        self.setNumFolds(numFolds)\n        self.setSeed(seed)\n        self.setParallelism(parallelism)\n        self.setVerbose(verbose)\n\n    def setVerbose(self, verbose):\n        \"\"\"\n        Sets the value of :py:attr:`verbose`.\n        \"\"\"\n        return self._set(verbose=verbose)\n\n    def getVerbose(self):\n        \"\"\"\n        Gets the value of verbose or its default value.\n        \"\"\"\n        return self.getOrDefault(self.verbose)\n\n    def _fit(self, datasets):\n        \"\"\"\n        Overrides pyspark.ml.tuning.Crossvalidator's _fit method.\n        \"\"\"\n        verbose = self.getVerbose()\n        est = self.getOrDefault(self.estimator)\n        epm = self.getOrDefault(self.estimatorParamMaps)\n        numModels = len(epm)\n        eva = self.getOrDefault(self.evaluator)\n        nFolds = self.getOrDefault(self.numFolds)\n        h = 1.0 / nFolds\n        randUnif = np.random.uniform(size = datasets[0].shape[0])\n        metrics = np.zeros(numModels)\n\n        pool = ThreadPool(processes=min(self.getParallelism(), numModels))\n\n        for i in range(nFolds):\n            if verbose:\n                print(\"Fold \" + str(i + 1) + \" of \" + str(nFolds))\n            validateLB = i * h\n            validateUB = (i + 1) * h\n            condition = (randUnif >= validateLB) & (randUnif < validateUB)\n            validate = [X[condition,:] for X in datasets]\n            train = [X[~condition,:] for X in datasets]\n\n            tasks = self._parallelFitTasks(est, train, eva, validate, epm, verbose)\n            for j, metric in pool.imap_unordered(lambda f: f(), tasks):\n                metrics[j] += (metric / nFolds)\n\n        if eva.isLargerBetter():\n            bestIndex = np.argmax(metrics)\n        else:\n            bestIndex = np.argmin(metrics)\n        bestModel = est.fit(datasets, epm[bestIndex])\n        if verbose:\n            print(\"Best model: \" + str(i + 1) + \" of \" + str(nFolds))\n            print(\"k: {0}\".format(bestModel.getK()))\n            print(\"rhos: {0}\".format(bestModel.getRhos()))\n            print(\"Avg. correlation across \" + str(nFolds) + \" folds: \" +\n                  str(metrics[bestIndex]))\n        return CCACrossValidatorModel(bestModel)\n\n\n    def fit(self, datasets, params=None):\n        \"\"\"\n        Overrides pyspark.ml.Estimator's fit method, which is inherited from\n        pyspark.ml.tuning.CrossValidator.\n        \"\"\"\n        if params is None:\n            params = dict()\n        if isinstance(params, (list, tuple)):\n            models = [None] * len(params)\n            for index, model in self.fitMultiple(datasets, params):\n                models[index] = model\n            return models\n        elif isinstance(params, dict):\n            if params:\n                return self.copy(params)._fit(datasets)\n            else:\n                return self._fit(datasets)\n        else:\n            raise ValueError(\"Params must be either a param map or a list/tuple of\"\n                             \"param maps, but got %s.\" % type(params))\n\n    @staticmethod\n    def _parallelFitTasks(est, train, eva, validation, epm, verbose=False):\n        \"\"\"\n        Creates a list of callables which can be called from different threads to fit and evaluate\n        an estimator in parallel. Each callable returns an `(index, metric)` pair. Borrows heavily\n        from pyspark.ml.tuning._parallelFitTasks.\n\n        :param est: Estimator, the estimator to be fit.\n        :param train: DataFrame, training data set, used for fitting.\n        :param eva: Evaluator, used to compute `metric`\n        :param validation: DataFrame, validation data set, used for evaluation.\n        :param epm: Sequence of ParamMap, params maps to be used during fitting & evaluation.\n        :return: (int, float), an index into `epm` and the associated metric value.\n        \"\"\"\n        modelIter = est.fitMultiple(train, epm)\n\n        def singleTask():\n            index, model = next(modelIter)\n            metric = eva.evaluate(model, validation)\n            if verbose:\n                print(\"k: {0}\".format(model.getK()))\n                print(\"rhos: {0}\".format(model.getRhos()))\n                print(\"Avg. correlation: \" + str(metric))\n            return index, metric\n\n        return [singleTask] * len(epm)\n\n\nclass CCACrossValidatorModel(CrossValidatorModel):\n    \"\"\"\n    Borrows heavily from pyspark.ml.tuning.CrossValidatorModel.\n    \"\"\"\n    def __init__(self, bestModel):\n        super(CCACrossValidatorModel, self).__init__(bestModel)\n\n    def _transform(self, datasets):\n        return self.bestModel.transform(datasets)\n\n    def transform(self, datasets, params=None):\n        \"\"\"\n        Overrides pyspark.ml.Transformer's transform method.\n        \"\"\"\n        if params is None:\n            params = dict()\n        if isinstance(params, dict):\n            if params:\n                return self.copy(params)._transform(datasets)\n            else:\n                return self._transform(datasets)\n        else:\n            raise ValueError(\"Params must be a param map but got %s.\" % type(params))\n        \n    def save(self, path):\n        \"\"\"Save this CCACrossValidatorModel instance to the given path\"\"\"\n        _save(self, path)\n\n    def load(path):\n        \"\"\"Load a CCACrossValidatorModel instance from the given path\"\"\"\n        return _load(path)\n", "meta": {"hexsha": "f8edfe6e47821d125c8398809882834d12453f64", "size": 32983, "ext": "py", "lang": "Python", "max_stars_repo_path": "sparkle/cca.py", "max_stars_repo_name": "jpdunc23/sparkle", "max_stars_repo_head_hexsha": "623813ed18a58929f5885fa6954045e3f5d9915f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-16T20:20:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-16T20:20:52.000Z", "max_issues_repo_path": "sparkle/cca.py", "max_issues_repo_name": "jpdunc23/sparkle", "max_issues_repo_head_hexsha": "623813ed18a58929f5885fa6954045e3f5d9915f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sparkle/cca.py", "max_forks_repo_name": "jpdunc23/sparkle", "max_forks_repo_head_hexsha": "623813ed18a58929f5885fa6954045e3f5d9915f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0179573513, "max_line_length": 98, "alphanum_fraction": 0.5206318406, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.2814056014026228, "lm_q1q2_score": 0.1688963661924714}}
{"text": "#!/usr/bin/env python\n\nimport os,sys,re\nfrom ase import Atom, Atoms\nimport io2\nimport io2.data as data\nfrom io2.gaussian_reader import GaussianReader as GR0\nimport ase.data as ad\nimport numpy as np\nimport multiprocessing\n\nglobal dic_sm, atom_symbs, prop_names\ndic_sm = {'H':2,'B':2,'C':3,'N':4,'O':3,'F':2, \\\n          'Si':3,'P':4,'S':3,'Cl':2,'Ge':3,'As':4,\\\n          'Se':3,'Br':2,'I':2}\natom_symbs = ['C', 'B', 'F', 'I', 'H', 'O', 'N', 'P', \\\n                  'S', 'Se', 'As', 'Cl', 'Si', 'Ge', 'Br']\nprop_names = ['NMR', 'ALPHA', 'MU', 'AE', 'G','U0','U','H', \\\n              'HOMO','LUMO','GAP', 'IP','EA', 'OMEGA1', \\\n              'MP','BP']\n\ndef is_job_done(f):\n    el = file(f).readlines()[-1] # end line\n    return 'Normal termination' in el\n\n\nclass GR(object):\n\n    def __init__(self, f, properties=['AE'], unit='kcal', istart=0):\n\n        self.f = f\n        self.unit = unit\n\n        assert is_job_done(f), '#ERROR: Gaussian calculation was terminated abnormally?'\n\n        dic = GR0(f, istart=istart)[-1]\n        self.coords = dic['Positions']\n        self.zs = dic['Atomic_numbers']\n        self.atoms = Atoms(self.zs, self.coords)\n        self.na = len(self.zs)\n        self.sm = dic['Multiplicity']\n        self.charge = dic['Charge']\n        self.dic = dic\n\n        uo = io2.Units()\n        self.uo = uo\n        self.const = {'kcal': uo.h2kc, 'kj': uo.h2kj, 'h': 1.0, \\\n                 'ev': uo.h2e, }[unit.lower()]\n\n        if type(properties) is str: properties = [ properties.upper(), ]\n\n        # visited or not?\n        imo, ie, ithermo, imu, ipolar, inmr, iforce, ipop = 0, 0, 0, 0, 0, 0, 0, 0\n        ys = []\n        visited = []\n        for property_i in properties:\n            pname = property_i.upper()\n            if pname in ['HOMO','LUMO','GAP']:\n                if not imo:\n                    imo = 1\n                    self.get_mo_energy()\n            elif pname in ['E', 'AE', 'EE', 'EN' ]:\n                if not ie:\n                    ie = 1\n                    self.get_energy(etype=pname)\n            elif pname in ['HF', 'MP2', 'CCSD(T)', ]:\n                if pname not in visited:\n                    self.get_ei(pname)\n                    visited.append( pname )\n            elif pname in ['U0', 'U', 'H', 'G', 'ZPE', 'ZPVE']:\n                if not ithermo:\n                    ithermo = 1\n                    self.get_thermo()\n            elif pname in ['MU',]:\n                if not imu:\n                    imu = 1\n                    self.get_dipole_moment()\n            elif pname in ['ALPHA',]:\n                if not ipolar:\n                    ipolar = 1\n                    self.get_polarizability()\n            elif pname in ['NMR',]:\n                if not inmr:\n                    inmr = 1\n                    self.get_nmr()\n            elif pname in ['FORCE',]:\n                if not iforce:\n                    iforce = 1\n                    self.get_force()\n            elif pname in ['POPULATION',]:\n                if not ipop:\n                    ipop = 1\n                    self.get_mulliken_population()\n            else:\n                raise '#ERROR:'\n            ys.append( self.dic[ property_i ] )\n\t    self.properties = ys\n\n    def update_dic(self, ss1, ss2):\n        for i, s1 in enumerate(ss1):\n            self.dic[s1] = ss2[i]\n\n    def get_ei(self, ein): # `ein -- energy_i name, i.e., HF, MP2, CCSD(T)\n        self.update_dic([ein, ], [ self.dic[ein]*self.const, ])\n\n    def get_energy(self,etype='E'):\n        f = self.f\n        # first read method\n        cmd1 = \"grep -n ' # ' %s | head -n 1\"%f\n        s0 = os.popen(cmd1).read().strip().split(':')\n        #print 'f,s0 = ',f,s0;\n        n0 = int(s0[0]); s0_1 = s0[1]\n\n        # in case the command line has two many user-specified keywords\n        # so that it spans more than 1 line\n        s0u = s0_1\n        while True:\n            cmd1_i = \"sed -n '%sp' %s\"%(n0+1,f)\n            s0_i = os.popen(cmd1_i).read().strip()\n            if set([ si for si in s0_i ]) != set(['-',]):\n                s0u += s0_i; n0 += 1\n            else:\n                break\n\n        s1 = s0u.split()\n        #print s1\n        ns1 = len(s1)\n        method1 = None\n        isGn = False\n        basis = ''\n        # for MY calculation, the command line always goes like \"# G4MP2\"\n        if ns1 == 2 and (s1[1][0].upper() == 'G'):\n            isGn = True\n            method1 = s1[1]\n        else:\n            # assume this is a normal method with \"/\" seperating `qcl and\n            # `basis, e.g., B3LYP/6-31G(d,p)'\n            for sj in s1:\n                if '/' in sj:\n                    #print 'Yeah, sj = ',sj\n                    cont1 = sj.split('/')\n                    method1 = cont1[0]\n                    basis1 = cont1[1]\n                    ss0 = ['-','+','+','(',')',',']\n                    ss1 = ['\\-','\\+','\\+','(',')',',']\n                    ss2 = ['','j','j','','','']\n                    for js,sj in enumerate(ss1):\n                        if ss0[js] in basis1:\n                            cmd = \"echo '%s' | sed -n 's/%s/%s/p'\"%(basis1, sj, ss2[js])\n                            basis1 = os.popen(cmd).read().strip()\n                    break\n\n        if method1 is None:\n            print ' #ERROR: method cannot be retrieved??'\n            sys.exit(3)\n        #else:\n        #    if 'maxcyc' in method1:\n        #        # e.g.,  \"# uqcisd(t)(maxcyc=100)/6-311++g(d,p)\"\n        #        idx0 = method1.index('(max')\n        #        method1 = method1[:idx0]\n\n        # now read energy\n        m1U = method1.upper(); #print ' ** meth = ', m1U\n        if m1U in ['B3LYP', 'RB3LYP', 'UB3LYP']:\n            cmd2 = \"grep 'E([RU]B3LYP) =' %s | tail -n 1 | awk '{print $5}'\"%f #out\n            # e.g.,\n            #  SCF Done:  E(RB3LYP) =  -40.5236797399     A.U. after   10 cycles\n            #print cmd2\n            E_str = os.popen(cmd2).read().strip()\n        elif m1U in ['CCSD(T)', 'QCISD(T)', 'UCCSD(T)', 'UQCISD(T)']:\n            m1Uu = {'UQCISD(T)':'QCISD(T)', 'QCISD(T)':'QCISD(T)', 'UCCSD(T)':'CCSD(T)', 'CCSD(T)':'CCSD(T)'}[m1U]\n            cmd2 = \"grep '^ %s=' %s\"%(m1Uu,f); #print cmd2\n            # e.g.,\n            #  QCISD(T)= -0.11358793642D+03\n            E_str = os.popen(cmd2).read().strip().split('\\n')[0].split()[-1]\n        elif m1U in ['HF','RHF','UHF',]:\n            cmd2 = \"grep 'E([RU]HF) =' %s | tail -n 1\"%f\n            E_str = os.popen(cmd2).read().strip().split('=')[1].split()[0]\n        elif m1U in ['MP2','RMP2','UMP2',]:\n            cmd2 = \"grep 'EUMP2 = ' %s | tail -n 1\"%f\n            E_str = os.popen(cmd2).read().strip().split()[-1]\n        else:\n            print '#ERROR: not implemented yet'; sys.exit(3)\n\n        if 'D' in E_str:\n            E = eval( 'E'.join( E_str.split('D') ) )\n        else:\n            E = eval( E_str )\n\n        self.E = E*self.const\n\n\n        atoms = self.atoms\n        qcl = method1 + basis1\n        self.qcl = qcl\n        #print '  -- qcl = ', qcl\n        if etype == 'AE':\n            ea_refs = data.retrieve_esref( qcl.lower() )\n            E0 = 0.\n            symbs = [ ai.symbol for ai in atoms ]\n            for si in symbs: E0 += ea_refs[si][0]\n            self.AE = (E - E0)*self.const\n            self.update_dic( ['qcl','AE'], [self.qcl, self.AE] )\n        elif etype == 'EE': # electronic energy\n            cmd1 = \"awk '/nuclear repulsion energy/{print NR}' %s | tail -n 1\"%f\n            En = eval( io2.cmdout2(cmd1) ) * self.const\n            Ee = E - En\n            self.En = En\n            self.Ee = Ee\n            self.update_dic( ['qcl','E','EN','EE'], [self.qcl,self.E,En,Ee] )\n        else:\n            self.update_dic( ['qcl','E',], [self.qcl, self.E] )\n\n\n    def get_mo_energy(self):\n        \"\"\"\n        get HOMO, LUMO and their gap\n        \"\"\"\n        f = self.f\n        cmd1 = \"awk '/^ The electronic state is/{print NR}' %s | tail -n 1\"%f\n        Ln1 = int(io2.cmdout2(cmd1)) + 1\n        cmd2 = \"awk '/^          Condensed to atoms \\(all electrons\\)/{print NR}' %s | tail -n 1\"%f\n        Ln2 = int(io2.cmdout2(cmd2)) - 1\n        cmd = \"sed -n '%d,%dp' %s | grep Beta\"%(Ln1,Ln2,f)\n        cont0 = io2.cmdout2(cmd)\n        if cont0 != '':\n            print ' Alpha & Beta spins are both involved, spin polarized??'\n            sys.exit(2)\n        else:\n            cmd = \"sed -n '%d,%dp' %s | grep ' Alpha virt. eigenvalues --' | head -n 1\"%(Ln1,Ln2,f)\n            ct = io2.cmdout2(cmd);\n            self.lumo = eval( ct.split()[-5] ) * self.uo.h2e\n            cmd = \"sed -n '%d,%dp' %s | grep ' Alpha  occ. eigenvalues --' | tail -1\"%(Ln1,Ln2,f)\n            ct = io2.cmdout2(cmd)\n            self.homo = eval( ct.split()[-1] ) * self.uo.h2e\n            #iseed = debug(iseed)\n            self.gap = self.lumo - self.homo\n\n            self.update_dic(['homo','lumo','gap'], [self.homo, self.lumo, self.gap])\n            self.update_dic(['HOMO','LUMO','GAP'], [self.homo, self.lumo, self.gap])\n\n    def get_thermo(self, scale_factor=0.965):\n        \"\"\"\n        for DFT, the `scale_factor is 0.965\n        \"\"\"\n        f = self.f\n        cmd = \"grep '^ Freq' %s\"%f\n        # data in lines below could be retrieved together\n        #\n        # Sum of electronic and zero-point Energies=           -174.095490\n        # Sum of electronic and thermal Energies=              -174.091365\n        # Sum of electronic and thermal Enthalpies=            -174.090421\n        # Sum of electronic and thermal Free Energies=         -174.122620\n        conts = io2.cmdout(cmd)\n        assert conts != [], '#ERROR: no thermochem was done!'\n        if not isGn:\n            cmd = \"awk '/^ Sum of electronic and/{print $NF}' %s\"%f\n            U0, U, H, G = np.array( io2.cmdout(cmd) ).astype(np.float) * self.const\n            self.U0, self.U, self.H, self.G  = U0, U, H, G\n\n            cmd = \"awk '/^ Zero-point correction=/{print $3}' %s\"%f\n            zpe = eval(io.cmdout(cmd)[0]) * self.const # the last two entries are \"0.81475823 Hartree/atom\"\n            self.zpe = self.zpve = zpe\n        else:\n            print '#ERROR: cannot handle output of Compositional method like G4MP2 yet!'\n            sys.exit(2)\n        E_ = U0 - zpe\n        #assert abs(E_ - E) < 0.0001, '#ERROR: '\n\n        # people usually scale ZPE by a factor, for B3LYP, it's 0.965??\n        U0c = E_ + scale_factor*zpe\n        self.U0c = U0c\n        self.update_dic(['U0', 'U0c', 'U', 'H', 'G'], [U0, U0c, U, H, G])\n\n    def get_dipole_moment(self):\n        cmd = \"grep -A1 ' Dipole moment (field-independent basis, Debye):' %s | tail -1 | awk '{print $NF}'\"%self.f\n        self.mu = eval( io2.cmdout2(cmd) )\n        self.update_dic(['MU', 'DIPOLE'], [self.mu, self.mu])\n\n    def get_polarizability(self):\n        cmd = \"awk '/Isotropic polarizability/{print $6}' %s\"%self.f\n        #print cmd\n        try:\n            self.alpha = eval( io2.cmdout2(cmd) )\n            self.update_dic(['ALPHA',], [self.alpha,])\n        except:\n            print ' * WARNING: no Isotropic polarizability found'\n\n    def get_nmr(self):\n        cmd = \"awk '/  Isotropic =  /{print $5}' %s\"%self.f\n        vals = io2.cmdout(cmd)\n        self.nmr = [ eval(val) for val in vals ]\n        self.update_dic(['NMR',], [self.nmr,])\n\n    def get_mulliken_population(self):\n        # note that the output Mulliken charge starting line may be different\n        # for different versions of Gaussian, i.e., with or without `atomic` in between\n        # \"Mullike\" and \"charges:\", so a regular expression is used\n        cmd1 = \"awk '/^ Mulliken [a-zA-Z]*\\s?charges:/{print NR}' %s | tail -1\"%self.f\n        #print cmd1\n        Ln1 = int(io2.cmdout2(cmd1)) + 2\n        cmd2 = \"awk '/^ Sum of Mulliken [a-zA-Z]*\\s?charges =/{print NR}' %s | tail -1\"%self.f\n        Ln2 = int(io2.cmdout2(cmd2)) - 1\n        cmd = \"sed -n '%d,%dp' %s\"%(Ln1,Ln2,self.f)\n        cs = io2.cmdout2(cmd).split('\\n')\n        pops = [ eval(ci.split()[2]) for ci in cs ]\n        #pops = np.array(vals)\n        self.populations = pops\n        self.update_dic(['POPULATION',], [self.populations,])\n\n    def get_force(self):\n        iou = io2.Units()\n        const = iou.h2e / iou.b2a # from hartree/bohr to eV/A\n        #cmd = \"grep '^\\s*[XYZ][0-9]*   ' %s | awk '{print $3}'\"%self.f #\n        cmd1 = \"awk '/^ Variable       Old X    -DE/{print NR}' %s | tail -1\"%self.f\n        Ln1 = int(io2.cmdout2(cmd1)) + 2\n        cmd2 = \"awk '/^         Item               Value     Threshold  Converged/{print NR}' %s | tail -1\"%self.f\n        Ln2 = int(io2.cmdout2(cmd2)) - 1\n        cmd = \"sed -n '%d,%dp' %s\"%(Ln1,Ln2,self.f)\n        #print cmd\n        cs = io2.cmdout2(cmd).split('\\n')\n        vals = [ eval(ci.split()[2]) for ci in cs ]\n        #print vals\n        #print len(vals)\n        forces = np.array(vals).reshape((self.na, 3)) * const\n        #abs_forces = np.linalg.norm( forces, axis=1 )\n        #self.forces = abs_forces[:, np.newaxis]\n        self.forces = forces\n        self.update_dic(['FORCE',], [self.forces,])\n\n\nclass GRs(object):\n\n    def __init__(self, fs, properties=['AE'], unit='kcal', write_Y=False, nproc=1, istart=0):\n\n        self.n = len(fs)\n        typeP = type(properties)\n        if typeP is str:\n            properties = [ properties.upper(), ]\n        elif typeP is list:\n            properties = [ prop.upper() for prop in properties ]\n        else:\n            raise '#ERROR,'\n        npr = len(properties)\n        istats = [] # is_local_property = False\n        for propi in properties:\n            istat = False # assume global property\n            if propi in ['POPULATION','NMR']:\n                istat = True\n            istats.append( istat )\n\n        if nproc == 1:\n            self.objs = []\n            for i,f in enumerate(fs):\n                #print i+1, f\n                ipt = [ f, properties, unit, istart ]\n                self.objs.append( self.processInput(ipt) )\n        else:\n            pool = multiprocessing.Pool(processes=nproc)\n            ipts = [ [ fi, properties, unit ] for fi in fs ]\n            self.objs = pool.map(self.processInput, ipts)\n\n        ys = []\n        #print ' - npr = ', npr\n        for ipr in range(npr):\n            ysi = []\n            for obj in self.objs:\n                #print ' - obj.properties = ', obj.properties\n                yi = obj.properties[ipr]; #print ' ysi = ', ysi\n                if istats[ipr]: # atomic property, e.g., NMR shifts\n                    ysi += yi\n                else:\n                    ysi.append( yi )\n            ys.append( ysi )\n        #print ys\n        self.dic = dict( zip(properties, ys) )\n        if write_Y:\n            for ipr in range(npr):\n                np.savetxt('%s.dat'%properties[ipr], ys[ipr], fmt='%.2f')\n\n    def processInput(self, ipt):\n        f, properties, unit, istart = ipt\n        obj = GR(f, properties=properties, unit=unit, istart=istart)\n        return obj\n\n    def get_statistics(self):\n        \"\"\"\n        `zs, `nas, `nhass, `coords, etc\n        \"\"\"\n        zs = []\n        zsr = []\n        nas = []\n        nhass = []\n        zsu = set([])\n        coords = []\n        for i in range(self.n):\n            obj_i = self.objs[i]\n            coords.append( obj_i.coords )\n            zsi = obj_i.zs\n            nhass.append( (np.array(zsi)>1).sum() )\n            nas.append( len(zsi) )\n            zsu.update( zsi )\n            zsr += list(zsi)\n            zs.append( zsi )\n        zsu = list(zsu)\n        nzu = len(zsu)\n        zsu.sort()\n        nzs = np.zeros((self.n, nzu), np.int32)\n        for i in range(self.n):\n            for iz in range(nzu):\n                istats = np.array(zs[i]) == zsu[iz]\n                nzs[i,iz] = np.sum(istats)\n        self.nzs = nzs\n        self.zsu = zsu\n        self.zs = zs\n        self.zsr = np.array(zsr,np.int32)\n        self.nas = np.array(nas,np.int32)\n        self.nhass = np.array(nhass,np.int32)\n        self.coords = coords\n\n\ndef get_line_number(cmd):\n    return int(io2.cmdout2(cmd).split(':')[0])\n\ndef read_coords(f):\n    lines = file(f).readlines()\n    cmd0 = \"grep -n ' Input orientation:' %s | tail -1\"%f\n    #cmd0 = \"grep -n ' Standard orientation:' %s | tail -1\"%f\n    #print cmd0\n    ln = get_line_number(cmd0) + 5\n    zs = []; coords = []\n    while 1:\n        l = lines[ln-1].strip()\n        if l[:10] == '-'*10: break\n        ia,zi,_,x,y,z = l.split()\n        zs.append(int(zi))\n        coords.append([eval(xi) for xi in [x,y,z]])\n        ln += 1\n    return zs,coords\n\n    obsolete=\"\"\"#cmd1 = \"grep -n '    Distance matrix (angstroms):' %s | tail -1\"%f\n    cmd1 = \"grep -n ' Rotational constants (GHZ):' %s\"%f\n    #print cmd1\n    ln1s = get_line_number(cmd1);\n    if type(ln1s) is int: ln1s = [ln1s,]\n    nnl = len(ln1s)\n    fconts = file(f).readlines()\n    ln1_found = False\n    for jn in range(1,nnl+1):\n        if fconts[ ln1s[-jn]-2 ].strip() == '-'*69:\n            ln1 = ln1s[-jn] - 2\n            ln1_found = True\n            break\n\n    if not ln1_found:\n        print ' #ERROR: `ln1 not assigned!!'\"\"\"\n\ndef get_cf_and_chg(f):\n    \"\"\" cf: chemical formula\n        chg: charge \"\"\"\n    cmdi = \"grep Stoichiometry %s | tail -1\"%f\n    ct = io2.cmdout2(cmdi)\n    info = ct.split()[-1]\n    if ('(' in info) and (info[-1] == ')'):\n        # charged mol\n        cf, c0_ = info.split('(') # cf: chemical formula;\n        if c0_[-2] == '-':\n            chg = -int(c0_[:-2]) # negatively charged\n        elif c0_[-2] == '+':\n            chg = int(c0_[:-2]) # positively charged\n        else:\n            #print 'c0_ = ', c0_, ', ct = ', ct\n            #sys.exit(2)\n            chg = 0 # spin-polarized case, e.g., C4H9O(2)\n    else:\n        chg = 0\n        cf = info\n    return cf, chg\n\ndef get_spin(f):\n    cmdi = \"grep 'Multiplicity =' %s | tail -1\"%f\n    ct = cmdout2(cmdi).split()\n    chg = int(ct[2]); sm = int(ct[-1])\n    return sm, chg\n\n\nif __name__ == \"__main__\":\n    import sys\n    import stropr as so\n\n    args = sys.argv[1:]\n\n    idx = 0\n    keys=['-p','-properties']; hask,s,idx = so.parser(args,keys,'E',idx)\n    assert hask\n    props = s.split(',')\n\n    fs = args[idx:]\n\n    #test\n    obj = GRs(fs, properties=props)\n    for propi in props:\n        for (f,p) in zip(fs,obj.dic[propi]):\n            print f,p\n\n\n", "meta": {"hexsha": "5141d545da41a00c7f638b90a73d853db34bbac0", "size": 18154, "ext": "py", "lang": "Python", "max_stars_repo_path": "io2/PY27_BAK_2019.2.28/gaussian.py", "max_stars_repo_name": "binghuang2018/aqml", "max_stars_repo_head_hexsha": "4901f3bd85db968fb3fc7ab97fd443421909d89d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2020-02-17T11:15:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T18:03:15.000Z", "max_issues_repo_path": "io2/PY27_BAK_2019.2.28/gaussian.py", "max_issues_repo_name": "binghuang2018/aqml", "max_issues_repo_head_hexsha": "4901f3bd85db968fb3fc7ab97fd443421909d89d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-11T06:49:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-21T07:30:53.000Z", "max_forks_repo_path": "io2/PY27_BAK_2019.2.28/gaussian.py", "max_forks_repo_name": "binghuang2018/aqml", "max_forks_repo_head_hexsha": "4901f3bd85db968fb3fc7ab97fd443421909d89d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-09T01:37:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-19T13:13:34.000Z", "avg_line_length": 35.8067061144, "max_line_length": 115, "alphanum_fraction": 0.4784069627, "include": true, "reason": "import numpy", "num_tokens": 5513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.16866457639997012}}
{"text": "import numpy as onp\nfrom scipy.stats import t as student_t\nfrom simtk import unit\n\nfrom bayes_implicit_solvent.constants import min_r, max_r, min_scale, max_scale\nfrom bayes_implicit_solvent.solvation_free_energy import predict_solvation_free_energy, \\\n    get_vacuum_samples, create_implicit_sim, beta\nfrom bayes_implicit_solvent.freesolv import db, smiles_list, mol_top_sys_pos_list\n\nuse_jax = False\nif use_jax:\n    import jax.numpy as jnp\n    import jax\n    from bayes_implicit_solvent.gb_models.jax_gb_models import compute_OBC_energy_vectorized as jax_compute_OBC_energy\nimport autograd.numpy as np\nfrom bayes_implicit_solvent.gb_models.numpy_gb_models import compute_OBC_energy_vectorized\n\n\nfrom bayes_implicit_solvent.solvation_free_energy import kj_mol_to_kT, one_sided_exp\n\nfrom scipy.spatial.distance import pdist, squareform\nfrom bayes_implicit_solvent.utils import get_charges\n\n# TODO: Maybe resurrect this...\n# from functools import lru_cache\n\nclass Molecule():\n    def __init__(self, smiles, verbose=False, vacuum_samples=None,\n                 n_samples=50, thinning=50000, ll='gaussian'):\n        \"\"\"Create an object that supports prediction of solvation free energy given radii and scaling factors\n\n        # TODO: remove ll\n        # TODO: add backend attribute\n\n        Parameters\n        ----------\n        smiles : string\n            SMILES representation of molecule\n\n        verbose : boolean\n            whether to print updates\n\n        vacuum_samples : list of unit'd snapshots\n\n        n_samples : int\n            if vacuum_samples not provided, how many samples to collect?\n\n        thinning : int\n            if vacuum samples not provided, how many steps to take between samples?\n\n        ll : string in {'gaussian', 'student-t'}\n            is each log-likelihood term Gaussian or heavy-tailed?\n\n        Attributes\n        ----------\n        mol_index_in_smiles_list : int\n            where in the sorted smiles list are we\n            TODO: Replace with less janky indexing\n        mol_index_in_freesolv : int\n            where in freesolv are we\n            TODO: Replace with less janky indexing\n        mol_name : string\n            iupac name (or alternative if IUPAC is unavailable or not parseable by OEChem\n        mol : OEMol object\n            OEMol object with explicit hydrogens, partial charges, etc. assigned\n        top : OpenMM Topology\n        sys : OpenMM System\n        pos : [n_atoms x 3] array\n            initial atomic positions\n        atom_names : list of strings\n            element symbol + occurrence number, e.g. ['C1', 'F1', 'F2', 'F3', 'Br1']\n        n_atoms : int\n            number of atoms\n        vacuum_sim : OpenMM Simulation\n            simulation object at vacuum using Smirnoff parameters, Reference platform, BAOAB Langevin integrator\n        vacuum_traj : [n_snapshots x n_atoms x 3] array\n            collection of atom positions sampled by vacuum_sim\n        experimental_value : float\n            experimental value of solvation free energy for this molecule, converted from kcal/mol to unitless (in kT)\n        experimental_uncertainty\n            uncertainty in experimental_value, converted from kcal.mol to unitless (in kT)\n        implicit_sim : OpenMM Simulation\n            same as vacuum_sim, but with a GBSAOBCForce added\n\n        \"\"\"\n\n        assert (ll in {'gaussian', 'student-t'})\n        self.smiles = smiles\n        self.verbose = verbose\n        self.ll = ll\n\n        # find the index of this molecule in our smiles list\n        mol_index_in_smiles_list = -1\n        for i in range(len(smiles_list)):\n            if smiles_list[i] == smiles:\n                mol_index_in_smiles_list = i\n        self.mol_index_in_smiles_list = mol_index_in_smiles_list\n        if self.mol_index_in_smiles_list == -1:\n            raise (ValueError(\n                \"the smiles string queried ({}) doesn't appear to be in FreeSolv's SMILES list...\".format(smiles)))\n\n        # find the index of this molecule in Freesolv\n        mol_index_in_freesolv = -1\n        for i in range(len(db)):\n            if db[i][1] == smiles:\n                mol_index_in_freesolv = i\n        self.mol_index_in_freesolv = mol_index_in_freesolv\n        if self.mol_index_in_freesolv == -1:\n            raise (ValueError(\"the smiles string queried ({}) doesn't appear to be in FreeSolv...\".format(smiles)))\n\n        self.mol_name = db[mol_index_in_freesolv][2]\n\n        self.mol, self.top, self.sys, self.pos = mol_top_sys_pos_list[self.mol_index_in_smiles_list]\n        self.atom_names = [a.name for a in self.top.atoms()]\n        self.n_atoms = len(self.pos)\n\n        self._n_samples = n_samples\n        self._thinning = thinning\n        self.charges = get_charges(self.sys)\n\n        if type(vacuum_samples) == type(None):\n            if verbose: print('collecting vacuum samples...')\n            self.vacuum_sim, self.vacuum_traj = get_vacuum_samples(self.top, self.sys, self.pos,\n                                                                   n_samples=self._n_samples,\n                                                                   thinning=self._thinning)\n        else:\n            self.vacuum_traj = vacuum_samples\n            self._n_samples = len(vacuum_samples)\n\n        self.configurations = np.array([snapshot / unit.nanometer for snapshot in self.vacuum_traj])\n        self.distance_matrices = np.array([squareform(pdist(snapshot / unit.nanometer)) for snapshot in self.vacuum_traj])\n\n        # both in reduced units\n        self.experimental_value = beta * (float(db[mol_index_in_freesolv][3]) * unit.kilocalorie_per_mole)\n        self.experimental_uncertainty = beta * (float(db[mol_index_in_freesolv][4]) * unit.kilocalorie_per_mole)\n\n        if verbose:\n            print('creating implicit-solvent simulation...')\n        self.implicit_sim = create_implicit_sim(self.top, self.sys)\n\n        if verbose:\n            print('successfully initialized {}'.format(self.mol_name))\n\n    def predict_solvation_free_energy(self, radii, scaling_factors):\n        \"\"\"Use one-sided EXP to predict the solvation free energy using this set of radii\n\n        Parameters\n        ----------\n        scaling_factors\n        radii : array of floats, either unit'd or assumed to be in nanometers\n            radius parameters for each atom\n        scaling_factors : array of floats\n            scalingFactors for each atom\n\n        Returns\n        -------\n        mean : float\n        uncertainty : float\n        \"\"\"\n        assert (len(radii) == self.n_atoms)\n        assert (len(scaling_factors) == self.n_atoms)\n        return predict_solvation_free_energy(self.implicit_sim, self.vacuum_traj, radii, scaling_factors)\n\n\n\n    def predict_solvation_free_energy_autograd(self, radii, scaling_factors):\n        W_F = np.array([compute_OBC_energy_vectorized(distance_matrix, radii, scaling_factors, self.charges) for\n                    distance_matrix in\n                    self.distance_matrices])\n        w_F = W_F * kj_mol_to_kT\n        return one_sided_exp(w_F)\n\n    #@jit\n    def predict_solvation_free_energy_jax(self, radii, scaling_factors):\n        @jax.jit\n        def compute_component(distance_matrix):\n            return jax_compute_OBC_energy(distance_matrix, radii, scaling_factors, self.charges)\n\n        W_F = jax.vmap(compute_component)(self.distance_matrices)\n\n        w_F = W_F * kj_mol_to_kT\n        return one_sided_exp(w_F)\n\n    def gaussian_log_likelihood(self, radii, scaling_factors):\n        \"\"\"Un-normalized log-likelihood using Gaussian located at experimentally measured value, with\n        scale set by the estimated experimental error.\n\n        This will be sensitive to the stated experimental uncertainty, which we are somewhat skeptical of,\n        since for many (most?) entries in FreeSolv this just a default value.\n\n\n        N(mean_sim | mu = mean_expt,\n                     sigma^2 = sigma_expt * max(sigma_expt, sigma_sim)\n        \"\"\"\n        simulation_mean, simulation_uncertainty = self.predict_solvation_free_energy(radii, scaling_factors)\n\n        mu = self.experimental_value\n        sigma2 = self.experimental_uncertainty * max([self.experimental_uncertainty, simulation_uncertainty])\n\n        return - (simulation_mean - mu) ** 2 / sigma2\n\n    def log_likelihood(self, radii, scaling_factors):\n        \"\"\"To be more robust to inaccurate statement of `experimental_uncertainty`, favor a Student-t likelihood\n        over a Gaussian likelihood. This also corresponds to using a nuisance parameter for the experimental uncertainty (with\n        an inverse-Gamma prior?) and marginalizing it out.\n\n        TODO: Gelman reference\n        \"\"\"\n        simulation_mean, simulation_uncertainty = self.predict_solvation_free_energy(radii, scaling_factors)\n\n        mu = self.experimental_value\n        sigma = np.sqrt(self.experimental_uncertainty * max([self.experimental_uncertainty, simulation_uncertainty]))\n\n        return student_t.logpdf(simulation_mean, loc=mu,\n                                scale=sigma,  # TODO: Look up how best to put scale information here\n                                df=7)  # TODO: Decide what to use for the degrees of freedom parameter\n\n    def bounds_check(self, radii, scale_factors):\n        \"\"\"Check whether parameters are in bounds (radii in (max_r, min_r),\n        scale_factors in (min_scale, max_scale)\n        \"\"\"\n        # TODO: refactor to have a parameter object that knows how to check its own bounds\n        if (np.min(radii) < min_r) or (np.max(radii) > max_r) or \\\n                (np.min(scale_factors) < min_scale) or (np.max(scale_factors) > max_scale):\n            return False\n        else:\n            return True\n\n    def log_prob_uncached(self, radii, scale_factors):\n        \"\"\"Un-normalized log-probability : log-likelihood, if log-prior > -infty\n        \"\"\"\n        if self.bounds_check(radii, scale_factors):\n            if self.ll == 'student-t':\n                ll = self.log_likelihood(radii, scale_factors)\n            elif self.ll == 'gaussian':\n                ll = self.gaussian_log_likelihood(radii, scale_factors)\n            return ll\n        else:\n            return - np.inf\n\n\n    # TODO: Return also a list of all the predictions\n\n    # @lru_cache(maxsize=4)\n    # TODO: Maybe use lru_cache again\n    def log_prob(self, radii, scale_factors):\n        return self.log_prob_uncached(radii, scale_factors)\n\n\nif __name__ == '__main__':\n    from bayes_implicit_solvent.samplers import random_walk_mh\n\n    np.random.seed(0)\n\n    smiles = 'C'\n    mol = Molecule(smiles, n_samples=10, thinning=1000)\n    n = 2\n    radii0 = np.ones(n)\n    scaling_factors0 = np.ones(n)\n    theta0 = np.hstack([radii0, scaling_factors0])\n    assert (len(theta0) == 2 * n)\n\n\n    def unpack(theta):\n        _radii = theta[:n]\n        radii = np.zeros(mol.n_atoms)\n        radii[0] = _radii[0]\n        radii[1:] = _radii[1]\n\n        _scaling_factors = theta[n:]\n        scaling_factors = np.zeros(mol.n_atoms)\n        scaling_factors[0] = _scaling_factors[0]\n        scaling_factors[1:] = _scaling_factors[1]\n\n        return radii, scaling_factors\n\n\n    def L(theta):\n        radii, scaling_factors = unpack(theta)\n        return mol.log_prob(radii, scaling_factors)\n\n\n    traj, log_probs, acceptance_fraction = random_walk_mh(theta0, L,\n                                                          n_steps=1000000, stepsize=0.02)\n    import os.path\n\n    data_path = 'data/'\n    onp.save(os.path.join(data_path, 'radii_samples_{}.npy'.format(smiles)), traj[:, :n])\n    onp.save(os.path.join(data_path, 'scale_samples_{}.npy'.format(smiles)), traj[:, n:])\n    onp.save(os.path.join(data_path, 'theta_samples_{}.npy'.format(smiles)), traj)\n    onp.save(os.path.join(data_path, 'log_probs_{}.npy'.format(smiles)), log_probs)\n\n    print(acceptance_fraction)\n    print('atom_names: ', mol.atom_names)\n\n    posterior_predictions = [mol.predict_solvation_free_energy(*unpack(theta))[0] for theta in traj[::100]]\n\n    onp.save(os.path.join(data_path, 'posterior_predictions_{}.npy'.format(smiles)), posterior_predictions)\n", "meta": {"hexsha": "97161d9fc5c360f665219520ecbf3c255cf9ab8a", "size": 12056, "ext": "py", "lang": "Python", "max_stars_repo_path": "bayes_implicit_solvent/molecule.py", "max_stars_repo_name": "openforcefield/bayes-implicit-solvent", "max_stars_repo_head_hexsha": "067239fcbb8af28eb6310d702804887662692ec2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-11-12T16:23:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:37:37.000Z", "max_issues_repo_path": "bayes_implicit_solvent/molecule.py", "max_issues_repo_name": "openforcefield/bayes-implicit-solvent", "max_issues_repo_head_hexsha": "067239fcbb8af28eb6310d702804887662692ec2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-01-18T22:05:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-12T18:37:31.000Z", "max_forks_repo_path": "bayes_implicit_solvent/molecule.py", "max_forks_repo_name": "openforcefield/bayes-implicit-solvent", "max_forks_repo_head_hexsha": "067239fcbb8af28eb6310d702804887662692ec2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-12-02T20:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-25T23:28:36.000Z", "avg_line_length": 40.3210702341, "max_line_length": 126, "alphanum_fraction": 0.6563536828, "include": true, "reason": "import numpy,from scipy,import jax", "num_tokens": 2795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.16866456947024844}}
{"text": "\"\"\"Module for handling Gaussian/CP2K style density files.\n\"\"\"\nimport os\nfrom time import time\n\nimport numpy as np\n\nfrom ..utils import fortran_format, python_format, tqdm_wrap\n\n__extensions__ = ['.cube']\n__args__ = ['orbitals']\n\n# Unit conversions\nbohr_to_ang = .52917721067\nang_to_bohr = 1 / bohr_to_ang\n\n\ndef read(fn, orbitals=0):\n    \"\"\"Read the charge density from a cube file.\n\n    Splits the density into blocks of buffer_size and parses it in chunks.\n    Buffer_size must be positive and an integer. If decomposed to orbitals can\n    either sum all for total charge density, sum a selection of orbitals or\n    return all for user processing. Units are converted to VASP chgcar units.\n\n    args:\n        fn: name of the file to open.\n        orbitals: how to deal with nval > 1, often associated with molecular\n                  orbitals. Passing an iterator returns the sum of the passed\n                  orbitals, passing an int > 0 returns just that orbital,\n                  passing an int < 0 return the whole charge array in the order\n                  density['charge'][nval,nx,ny,nz], the default value, 0,\n                  returns a sum of all nvals unless atom number indicator is\n                  positive,vin which case it returns just the first nval.\n    return:\n        density: dict containing 3d-arrays for charge and spin densities.\n        lattice: 3x3 array with lattice vectors as rows.\n        atoms: atomic positions in Cartesian basis.\n        file_info: information about the file type and the write function.\n    \"\"\"\n    t0 = time()\n    density = dict()\n    prefix, filename = os.path.split(fn)\n    prefix = os.path.join(prefix, '')\n    with open(fn, 'r') as f:\n        print(f\"  Reading {f.name} as cube format.\")\n        # first two lines are comments.\n        _ = f.readline()\n        _ = f.readline()\n        line = f.readline().strip().split()\n        atom_sum = int(line[0])\n        origin = np.array(line[1:4], dtype=np.float64)\n        if len(line) > 4:\n            nval = int(line[5])\n        else:\n            nval = 1\n        grid = np.zeros(3, dtype=np.int64)\n        lattice = np.zeros((3, 3), dtype=np.float64)\n        for i in range(3):\n            line = f.readline().strip().split()\n            grid[i] = line[0]\n            lattice[i] = line[1:]\n            lattice[i] *= grid[i]\n        print(f\"  {' x '.join(grid.astype(str))} grid size.\")\n        # read atomic positions and the blank line after\n        atom_types = np.zeros(abs(atom_sum), dtype=np.int64)\n        atoms = np.zeros((abs(atom_sum), 3), dtype=np.float64)\n        for i in range(abs(atom_sum)):\n            line = f.readline().strip().split()\n            atom_types[i] = line[0]\n            atoms[i] = line[-3:]\n        # convert to fractional coordinates and then wrap in cell\n        atoms = np.dot(atoms, np.linalg.inv(lattice))\n        atoms %= 1\n        # convert back\n        atoms = np.dot(atoms, lattice)\n        if atom_sum < 0:\n            line = f.readline().strip().split()\n            dset_ids = np.zeros(int(line.pop(0)), dtype=np.int64)\n            nval = dset_ids.shape[0]\n            count = 0\n            while count < nval:\n                for m in line:\n                    dset_ids[count] = m\n                    count += 1\n                line = f.readline().strip().split()\n        grid_pts = np.prod(grid)\n        nx, ny, nz = grid\n        record_pts = nz * nval\n        grid_lines = record_pts // 6\n        grid_mod = record_pts % 6\n        # save the current file position and get the line length.\n        charge_pos = f.tell()\n        line_len = len(f.readline())\n        f.seek(charge_pos)\n        # set up buffer numbers.\n        buffer_size = grid_lines\n        buffer_range = [buffer_size]\n        charge = np.zeros((nx, ny, nz * nval), dtype=np.float64)\n        for x in tqdm_wrap(range(nx), desc=\"Charge density:\"):\n            for y in range(ny):\n                idx = 0\n                for buff in buffer_range:\n                    # cube has 6 voxels per line.\n                    idx_inc = buff * 6\n                    buff_b = buff * line_len\n                    line = f.read(buff_b).strip().split()\n                    charge[x, y, idx:idx + idx_inc] = line\n                    idx += idx_inc\n                # get the last non-complete line.\n                if grid_mod != 0:\n                    line = f.readline().strip().split()\n                    charge[x, y, -grid_mod:] = line\n        print(f\"  File {f.name} closed. \", end='')\n    if nval > 1:\n        # how are we handling nval > 1\n        if hasattr(orbitals, '__iter__'):\n            # sum all given orbitals\n            charge = charge.reshape(nx, ny, nz, nval)\n            charge = np.swapaxes(charge, 0, -1)\n            density['charge'] = np.sum([charge[dset_ids.index(int(m))]\n                                        for m in orbitals], axis=0)\n        elif orbitals < 0:\n            # return the entire file\n            charge = charge.reshape(nx, ny, nz, nval)\n            density['charge'] = np.swapaxes(charge, 0, -1)\n        elif orbitals > 0:\n            # return specific orbital\n            charge = charge.reshape(nx, ny, nz, nval)\n            charge = np.swapaxes(charge, 0, -1)\n            density['charge'] = charge[dset_ids.index(int(orbitals))].copy()\n        elif atom_sum > 0:\n            # return just first value (useful for gradient cubes)\n            charge = charge.reshape(nx, ny, nz, nval)\n            density['charge'] = np.swapaxes(charge, 0, -1)[0].copy()\n        else:\n            # sum all nvals\n            charge = charge.reshape(nx, ny, nz, nval)\n            charge = np.swapaxes(charge, 0, -1)\n            density['charge'] = np.sum(charge, axis=0)\n        del charge\n    else:\n        density['charge'] = charge\n    print(f\"Time taken: {time() - t0:0.3f}s\", end='\\n\\n')\n    lattice *= bohr_to_ang\n    atoms *= bohr_to_ang\n    density['charge'] *= ang_to_bohr**3\n    file_info = {\n        'filename': fn,\n        'prefix': prefix,\n        'file_type': 'cube',\n        'write_function': write,\n        'elements': atom_types,\n        'voxel_offset': np.array([.5, .5, .5])\n    }\n    return density, lattice, atoms, file_info\n\n\ndef write(fn, atoms, lattice, density, file_info, prefix=None, suffix='.cube'):\n    \"\"\"Write a cube style charge density\n\n    args:\n        fn: filename\n        atoms: the atoms for the structure\n        lattice: lattice defining cell\n        file_info: dictionary containing everything from file_info exported by\n                   read function plus optional fortran_format flag\n        prefix: string to be placed infront of filename\n        suffix: string to be placed at end of filename\n    \"\"\"\n    if prefix is not None:\n        fn = prefix + fn\n    fn += suffix\n    if file_info.get('fortran_format', 0) == 2:\n        output_format = fortran_format\n    elif file_info.get('fortran_format', 0) == 1:\n        def output_format(a, p):\n            return python_format(a, p, ' ')\n    else:\n        output_format = python_format\n    charge = density['charge']\n    # convert to bohr\n    atoms *= ang_to_bohr\n    charge *= bohr_to_ang**3\n    lattice *= ang_to_bohr\n    lattice /= charge.shape\n\n    buffer_size = charge.shape[2] // 6\n    buffer_rem = charge.shape[2] % 6\n    buffer_flag = buffer_rem != 0\n\n    lattice_width = np.max(np.log10(np.abs(lattice[lattice != 0]))) + 9\n    lattice_width = max([int(lattice_width), 9]) + 1\n    lattice_prec = 17 - lattice_width\n    atoms_width = np.max(np.log10(np.abs(atoms[atoms != 0]))) + 9\n    atoms_width = max([int(atoms_width), 9]) + 1\n    atoms_prec = 17 - atoms_width\n    with open(fn, 'w') as f:\n        f.write(\"Cube File writen in pybader\\n\")\n        f.write(file_info['comment'])\n        f.write(f\"{atoms.shape[0]:>5}{'  0.0000000'*3}\\n\")\n        for i, lat in enumerate(lattice):\n            x, y, z = lat\n            f.write(f\"{charge.shape[i]:>5}\")\n            f.write(f\" {x:> {10}.{lattice_prec}f}\")\n            f.write(f\" {y:> {10}.{lattice_prec}f}\")\n            f.write(f\" {z:> {10}.{lattice_prec}f}\\n\")\n        for i, atom in enumerate(atoms):\n            x, y, z = atom\n            f.write(f\"{file_info['elements'][i]:>5}\")\n            f.write('  0.0000000')\n            f.write(f\" {x:> {10}.{atoms_prec}f}\")\n            f.write(f\" {y:> {10}.{atoms_prec}f}\")\n            f.write(f\" {z:> {10}.{atoms_prec}f}\\n\")\n        for i in tqdm_wrap(range(charge.shape[0]), desc=f\"{fn}:\"):\n            for j in range(charge.shape[1]):\n                r = charge[i, j][:buffer_size * 6].reshape((buffer_size, 6))\n                out = output_format(r, 5)\n                if buffer_flag:\n                    out += output_format(np.array([charge[i, j]\n                                                   [-buffer_rem:]]), 5)\n                f.write(out)\n", "meta": {"hexsha": "7dc379b6ec78b751fc6dc3e10955e7ce2e375360", "size": 8785, "ext": "py", "lang": "Python", "max_stars_repo_path": "pybader/io/cube.py", "max_stars_repo_name": "adam-kerrigan/pybader", "max_stars_repo_head_hexsha": "1d675ae69ab64fe336b936b00990681e01258031", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-30T20:15:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-20T18:24:23.000Z", "max_issues_repo_path": "pybader/io/cube.py", "max_issues_repo_name": "kerrigoon/pybader", "max_issues_repo_head_hexsha": "1d675ae69ab64fe336b936b00990681e01258031", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pybader/io/cube.py", "max_forks_repo_name": "kerrigoon/pybader", "max_forks_repo_head_hexsha": "1d675ae69ab64fe336b936b00990681e01258031", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-18T13:39:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-18T13:39:53.000Z", "avg_line_length": 39.3946188341, "max_line_length": 79, "alphanum_fraction": 0.5503699488, "include": true, "reason": "import numpy", "num_tokens": 2246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.16865869694238197}}
{"text": "import matplotlib as mpl\nmpl.use('agg')\nimport numpy as np, matplotlib.pyplot as plt, os, sys\nimport tools21cm as t2c, py21cmfast as p21\nimport matplotlib.gridspec as gridspec\nimport random, json\n\nfrom datetime import datetime, date\nfrom glob import glob\nfrom tqdm import tqdm\nfrom mpi4py import MPI\n\npath_out = sys.argv[1]\narr_idx = int(sys.argv[2])\npath_out += '/' if path_out[-1]!='/' else ''\n\npath_chache = '/gpfs/scratch/userexternal/mbianco0/21cmFAST-cache/'\np21.config['direc'] = path_chache\n\ncomm = MPI.COMM_WORLD\nrank = comm.Get_rank()\nnprocs = comm.Get_size()\n\n#loop_start, loop_end = 6999, 7000\nloop_start, loop_end = np.loadtxt('parameters/todo_r%d.txt' %arr_idx, dtype=int)\nperrank = (loop_end-loop_start)//nprocs\n\ndef get_dir_size(dir):\n    \"\"\"Returns the \"dir\" size in bytes.\"\"\"\n    total = 0\n    try:\n        for entry in os.scandir(dir):\n            if entry.is_file():\n                total += entry.stat().st_size\n            elif entry.is_dir():\n                total += get_dir_size(entry.path)\n    except NotAdirError:\n        return os.path.getsize(dir)\n    except PermissionError:\n        return 0\n    return total\n\n\ndef GenerateSeed():\n    # create seed for 21cmFast\n    seed = [var for var in datetime.now().strftime('%d%H%M%S')]\n    np.random.shuffle(seed)\n    return int(''.join(seed))\n\n\nparams = {'HII_DIM':128, 'DIM':384, 'BOX_LEN':256}\nc_params = {'OMm':0.27, 'OMb':0.046, 'SIGMA_8':0.82, 'POWER_INDEX':0.96}\nmy_ext = [0, params['BOX_LEN'], 0, params['BOX_LEN']]\ntobs = 1000\n\n\nif not (os.path.exists('%sastro_params_rank%d.txt' %(path_out+'parameters/', rank))):\n    loop_resume = 0\n    \n    with open(path_out+'parameters/user_params.txt', 'w') as file:\n        file.write(json.dumps(params))\n\n    with open(path_out+'parameters/cosm_params.txt', 'w') as file:\n        file.write(json.dumps(c_params))\nelse:\n    loop_resume = int(np.loadtxt('%sastro_params_rank%d.txt' %(path_out+'parameters/', rank))[:,0].max())\n\n\nif(loop_resume == 0):\n    i = int(loop_start+rank*perrank)\nelif(loop_resume != 0):\n    print(' Rank=%d resumes itration from i=%d.' %(rank, loop_resume))\n    i = int(loop_resume + 1)\n\nif(rank == nprocs-1):\n    i_end = int(loop_start+(rank+1)*perrank)\nelse:\n    i_end = int(loop_start+(rank+1)*perrank)\n    if(i_end != loop_end):\n        i_end = loop_end\n\nwhile i < i_end:\n    # astronomical & cosmological parameters\n    z = np.random.uniform(7, 9)         # z = [7, 9]\n    eff_fact = random.gauss(52.5, 20.)  # eff_fact = [5, 100]\n    Rmfp = random.gauss(12.5, 5.)       # Rmfp = [5, 20]\n    Tvir = random.gauss(4.65, 0.5)      # Tvir = [log10(1e4), log10(2e5)]\n    \n    # Define astronomical parameters\n    a_params = {'HII_EFF_FACTOR':eff_fact, 'R_BUBBLE_MAX':Rmfp, 'ION_Tvir_MIN':Tvir}\n\n    # Create 21cmFast cube\n    if(i%1 == 0):\n        try:\n            os.system('rm %s*h5' %path_chache)\n        except:\n            pass\n        comm.Barrier()\n        \n        ic = p21.initial_conditions(user_params=params, cosmo_params=c_params, random_seed=GenerateSeed())\n\n    cube = p21.run_coeval(redshift=z, init_box=ic, astro_params=a_params, zprime_step_factor=1.05)\n\n    # Mean neutral fraction\n    xn = np.mean(cube.xH_box)\n\n    if(xn > 0.1 and xn <= 0.8):\n        print('processor: %d/%d   idx=%d\\n z=%.3f, xn=%.3f, eff_fact=%.3f, Rmfp=%.3f, Tvir=%.3f' %(rank, nprocs, i, z, xn, eff_fact, Rmfp, Tvir))\n\n        dT = cube.brightness_temp\n        dT1 = t2c.subtract_mean_signal(signal=dT, los_axis=2)\n        \n        \"\"\"\n        # calculate uv-coverage \n        file_uv, file_Nant = 'uv_coverage_%d/uvmap_z%.3f.npy' %(params['HII_DIM'], z), 'uv_coverage_%d/Nantmap_z%.3f.npy' %(params['HII_DIM'], z)\n\n        if(os.path.exists(file_uv) and os.path.exists(file_Nant)):\n            uv = np.load(file_uv)\n            Nant = np.load(file_Nant)\n        else:\n            uv, Nant = t2c.get_uv_daily_observation(params['HII_DIM'], z, filename=None, total_int_time=6.0, int_time=10.0, boxsize=params['BOX_LEN'], declination=-30.0, verbose=True)\n            \n            np.save(file_uv, uv)\n            np.save(file_Nant, Nant)\n        \n                \n        # Noise cube\n        np.random.seed(GenerateSeed())\n        noise_cube = t2c.noise_cube_coeval(params['HII_DIM'], z, depth_mhz=None, obs_time=tobs, filename=None, boxsize=params['BOX_LEN'], total_int_time=6.0, int_time=10.0, declination=-30.0, uv_map=uv, N_ant=Nant, fft_wrap=False, verbose=False)\n        \n        dT2 = dT1 + noise_cube\n\n        # Smooth the data to resolution corresponding to maximum baseline of 2 km\n        dT3 = t2c.smooth_coeval(dT2, cube.redshift, box_size_mpc=cube.user_params.HII_DIM, max_baseline=2.0, ratio=1.0, nu_axis=2)\n\n        smt_xn = t2c.smooth_coeval(cube.xH_box, cube.redshift, box_size_mpc=cube.user_params.HII_DIM, max_baseline=2.0, ratio=1.0, nu_axis=2)\n        mask_xn = smt_xn>0.5\n        \"\"\"\n        # mask are saved such that 1 in neutral region and 0 in ionized region\n        t2c.save_cbin(path_out+'data/xH_21cm_i%d.bin' %i, cube.xH_box)\n        t2c.save_cbin(path_out+'data/dT1_21cm_i%d.bin' %i, dT1)\n        \n        if(i%50):\n            ps, ks, n_modes = t2c.power_spectrum_1d(dT, kbins=20, box_dims=cube.user_params.BOX_LEN,return_n_modes=True, binning='log')\n            idx=params['HII_DIM']//2\n\n            fig = plt.figure(figsize=(11, 4))\n            fig.suptitle('z=%.3f   $x_n$=%.2f   $\\zeta$=%.3f   $R_{mfp}$=%.3f   $T_{vir}^{min}$=%.3f' %(z, xn, eff_fact, Rmfp, Tvir), fontsize=15)\n            gs = gridspec.GridSpec(nrows=1, ncols=2, width_ratios=[1.5, 1])\n            ax0 = fig.add_subplot(gs[0,0])\n            ax0.loglog(ks, ps*ks**3/2/np.pi**2)\n            ax0.set_xlabel('k (Mpc$^{-1}$)', fontsize=12), ax0.set_ylabel('$\\Delta^2_\\mathrm{21}$', fontsize=12)\n            ax1 = fig.add_subplot(gs[0,1])\n            ax1.imshow(dT[:,:,idx], origin='lower', cmap='jet')\n            plt.savefig(path_out+'images/test_i%d.png' %i, bbox_inches='tight'), plt.close()\n        \n            # Plot outputs comparisons\n            fig, axs = plt.subplots(1, 2, figsize=(12,7))\n            fig.suptitle('z=%.3f\\t\\t$x_n$=%.2f\\n$\\zeta$=%.3f\\t\\t$R_{mfp}$=%.3f\\t\\t$T_{vir}^{min}$=%.3f' %(z, xn, eff_fact, Rmfp, Tvir), fontsize=18)\n            axs[0].set_title('$x_{HII}$', size=16)\n            axs[0].imshow(1-cube.xH_box[:,:,idx], origin='lower', cmap='jet', extent=my_ext)\n            axs[0].set_xlabel('[Mpc]'), axs[0].set_ylabel('[Mpc]');\n\n            axs[1].set_title('$\\delta T_b$', size=16)\n            axs[1].imshow(dT1[:,:,idx], origin='lower', cmap='jet', extent=my_ext)\n            axs[1].set_xlabel('[Mpc]'), axs[1].set_ylabel('[Mpc]');\n            plt.savefig(path_out+'images/slice_i%d.png' %i, bbox_inches='tight'), plt.close()\n        \n        # save parameters values\n        with open('%sastro_params_rank%d.txt' %(path_out+'parameters/', rank), 'a') as f:\n            if(i == 0 and rank == 0):\n                f.write('# HII_EFF_FACTOR: The ionizing efficiency of high-z galaxies\\n')\n                f.write('# R_BUBBLE_MAX: Mean free path in Mpc of ionizing photons within ionizing regions\\n')\n                f.write('# ION_Tvir_MIN: Minimum virial Temperature of star-forming haloes in log10 units\\n')\n                f.write('#i\\tz\\teff_f\\tRmfp\\tTvir\\tx_n\\n')\n\n            f.write('%d\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\n' %(i, z, eff_fact, Rmfp, Tvir, np.mean(xn)))\n        \n        # if output dir is more than 15 GB of size, compress and remove files in data/\n        if(get_dir_size(path_out) / 1e9 >= 15):\n            if(rank == 0):\n                try:\n                    strd = np.loadtxt(path_out+'written.txt', dtype=str, delimiter='\\n')\n                except:\n                    strd = np.array([])\n\n                os.system('tar -czvf %s_part%d.tar.gz %s' %(path_out[path_out[:-1].rfind('/')+1:-1], strd.size+1, path_out[path_out[:-1].rfind('/')+1:-1]))\n                os.system('rm %sdata/*.bin' %path_out)\n\n                np.savetxt(path_out+'written.txt', np.append(strd, ['%s written %s_part%d.tar.gz' %(datetime.now().strftime('%d/%m/%Y %H:%M:%S'), path_out[path_out[:-1].rfind('/')+1:-1], strd.size+1)]), delimiter='\\n', fmt='%s')\n            print(' \\n Data created exeed 15GB. Compression completed...')\n            comm.Barrier()\n\n        # update while loop index\n        i += 1\n    else:\n        continue\ncomm.Barrier() \nprint('... rank=%d finished' %rank)\n", "meta": {"hexsha": "f1e83f40846a99b42d697aaebabb4a06c71da46b", "size": 8357, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/create_data_21cmfast_mpi.py", "max_stars_repo_name": "micbia/SegU-Net", "max_stars_repo_head_hexsha": "69c3e3596d32d93b62d3636317e1dbf531f5862e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-05-13T22:45:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T10:13:21.000Z", "max_issues_repo_path": "utils/create_data_21cmfast_mpi.py", "max_issues_repo_name": "micbia/SegU-Net", "max_issues_repo_head_hexsha": "69c3e3596d32d93b62d3636317e1dbf531f5862e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/create_data_21cmfast_mpi.py", "max_forks_repo_name": "micbia/SegU-Net", "max_forks_repo_head_hexsha": "69c3e3596d32d93b62d3636317e1dbf531f5862e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.785, "max_line_length": 245, "alphanum_fraction": 0.5993777671, "include": true, "reason": "import numpy", "num_tokens": 2564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.28457601028405616, "lm_q1q2_score": 0.16865869644354595}}
{"text": "#   Copyright 2020 The PyMC Developers\n#\n#   Licensed under the Apache License, Version 2.0 (the \"License\");\n#   you may not use this file except in compliance with the License.\n#   You may obtain a copy of the License at\n#\n#       http://www.apache.org/licenses/LICENSE-2.0\n#\n#   Unless required by applicable law or agreed to in writing, software\n#   distributed under the License is distributed on an \"AS IS\" BASIS,\n#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#   See the License for the specific language governing permissions and\n#   limitations under the License.\nimport contextvars\nimport functools\nimport sys\nimport types\nimport warnings\n\nfrom abc import ABCMeta\nfrom functools import singledispatch\nfrom typing import Callable, Iterable, Optional, Sequence, Tuple, Union, cast\n\nimport aesara\nimport numpy as np\n\nfrom aeppl.logprob import _logcdf, _logprob\nfrom aesara import tensor as at\nfrom aesara.graph.basic import Variable\nfrom aesara.tensor.basic import as_tensor_variable\nfrom aesara.tensor.elemwise import Elemwise\nfrom aesara.tensor.random.op import RandomVariable\nfrom aesara.tensor.var import TensorVariable\nfrom typing_extensions import TypeAlias\n\nfrom pymc.aesaraf import change_rv_size\nfrom pymc.distributions.shape_utils import (\n    Dims,\n    Shape,\n    Size,\n    StrongShape,\n    WeakDims,\n    convert_dims,\n    convert_shape,\n    convert_size,\n    find_size,\n    resize_from_dims,\n    resize_from_observed,\n)\nfrom pymc.printing import str_for_dist\nfrom pymc.util import UNSET\nfrom pymc.vartypes import string_types\n\n__all__ = [\n    \"DensityDistRV\",\n    \"DensityDist\",\n    \"Distribution\",\n    \"SymbolicDistribution\",\n    \"Continuous\",\n    \"Discrete\",\n    \"NoDistribution\",\n]\n\nDIST_PARAMETER_TYPES: TypeAlias = Union[np.ndarray, int, float, TensorVariable]\n\nvectorized_ppc = contextvars.ContextVar(\n    \"vectorized_ppc\", default=None\n)  # type: contextvars.ContextVar[Optional[Callable]]\n\nPLATFORM = sys.platform\n\n\nclass _Unpickling:\n    pass\n\n\nclass DistributionMeta(ABCMeta):\n    \"\"\"\n    DistributionMeta class\n\n\n    Notes\n    -----\n    DistributionMeta currently performs many functions, and will likely be refactored soon.\n    See issue below for more details\n    https://github.com/pymc-devs/pymc/issues/5308\n    \"\"\"\n\n    def __new__(cls, name, bases, clsdict):\n\n        # Forcefully deprecate old v3 `Distribution`s\n        if \"random\" in clsdict:\n\n            def _random(*args, **kwargs):\n                warnings.warn(\n                    \"The old `Distribution.random` interface is deprecated.\",\n                    FutureWarning,\n                    stacklevel=2,\n                )\n                return clsdict[\"random\"](*args, **kwargs)\n\n            clsdict[\"random\"] = _random\n\n        rv_op = clsdict.setdefault(\"rv_op\", None)\n        rv_type = None\n\n        if isinstance(rv_op, RandomVariable):\n            rv_type = type(rv_op)\n\n        new_cls = super().__new__(cls, name, bases, clsdict)\n\n        if rv_type is not None:\n            # Create dispatch functions\n\n            class_logp = clsdict.get(\"logp\")\n            if class_logp:\n\n                @_logprob.register(rv_type)\n                def logp(op, values, *dist_params, **kwargs):\n                    dist_params = dist_params[3:]\n                    (value,) = values\n                    return class_logp(value, *dist_params)\n\n            class_logcdf = clsdict.get(\"logcdf\")\n            if class_logcdf:\n\n                @_logcdf.register(rv_type)\n                def logcdf(op, value, *dist_params, **kwargs):\n                    dist_params = dist_params[3:]\n                    return class_logcdf(value, *dist_params)\n\n            class_moment = clsdict.get(\"moment\")\n            if class_moment:\n\n                @_moment.register(rv_type)\n                def moment(op, rv, rng, size, dtype, *dist_params):\n                    return class_moment(rv, size, *dist_params)\n\n            # Register the Aesara `RandomVariable` type as a subclass of this\n            # `Distribution` type.\n            new_cls.register(rv_type)\n\n        return new_cls\n\n\ndef _make_nice_attr_error(oldcode: str, newcode: str):\n    def fn(*args, **kwargs):\n        raise AttributeError(f\"The `{oldcode}` method was removed. Instead use `{newcode}`.`\")\n\n    return fn\n\n\ndef _make_rv_and_resize_shape(\n    *,\n    cls,\n    dims: Optional[Dims],\n    model,\n    observed,\n    args,\n    **kwargs,\n) -> Tuple[Variable, Optional[WeakDims], Optional[Union[np.ndarray, Variable]], StrongShape]:\n    \"\"\"Creates the RV and processes dims or observed to determine a resize shape.\"\"\"\n    # Create the RV without dims information, because that's not something tracked at the Aesara level.\n    # If necessary we'll later replicate to a different size implied by already known dims.\n    rv_out = cls.dist(*args, **kwargs)\n    ndim_actual = rv_out.ndim\n    resize_shape = None\n\n    # # `dims` are only available with this API, because `.dist()` can be used\n    # # without a modelcontext and dims are not tracked at the Aesara level.\n    dims = convert_dims(dims)\n    dims_can_resize = kwargs.get(\"shape\", None) is None and kwargs.get(\"size\", None) is None\n    if dims is not None:\n        if dims_can_resize:\n            resize_shape, dims = resize_from_dims(dims, ndim_actual, model)\n        elif Ellipsis in dims:\n            # Replace ... with None entries to match the actual dimensionality.\n            dims = (*dims[:-1], *[None] * ndim_actual)[:ndim_actual]\n    elif observed is not None:\n        resize_shape, observed = resize_from_observed(observed, ndim_actual)\n    return rv_out, dims, observed, resize_shape\n\n\nclass Distribution(metaclass=DistributionMeta):\n    \"\"\"Statistical distribution\"\"\"\n\n    rv_class = None\n    rv_op: RandomVariable = None\n\n    def __new__(\n        cls,\n        name: str,\n        *args,\n        rng=None,\n        dims: Optional[Dims] = None,\n        initval=None,\n        observed=None,\n        total_size=None,\n        transform=UNSET,\n        **kwargs,\n    ) -> RandomVariable:\n        \"\"\"Adds a RandomVariable corresponding to a PyMC distribution to the current model.\n\n        Note that all remaining kwargs must be compatible with ``.dist()``\n\n        Parameters\n        ----------\n        cls : type\n            A PyMC distribution.\n        name : str\n            Name for the new model variable.\n        rng : optional\n            Random number generator to use with the RandomVariable.\n        dims : tuple, optional\n            A tuple of dimension names known to the model.\n        initval : optional\n            Numeric or symbolic untransformed initial value of matching shape,\n            or one of the following initial value strategies: \"moment\", \"prior\".\n            Depending on the sampler's settings, a random jitter may be added to numeric, symbolic\n            or moment-based initial values in the transformed space.\n        observed : optional\n            Observed data to be passed when registering the random variable in the model.\n            See ``Model.register_rv``.\n        total_size : float, optional\n            See ``Model.register_rv``.\n        transform : optional\n            See ``Model.register_rv``.\n        **kwargs\n            Keyword arguments that will be forwarded to ``.dist()``.\n            Most prominently: ``shape`` and ``size``\n\n        Returns\n        -------\n        rv : RandomVariable\n            The created RV, registered in the Model.\n        \"\"\"\n\n        try:\n            from pymc.model import Model\n\n            model = Model.get_context()\n        except TypeError:\n            raise TypeError(\n                \"No model on context stack, which is needed to \"\n                \"instantiate distributions. Add variable inside \"\n                \"a 'with model:' block, or use the '.dist' syntax \"\n                \"for a standalone distribution.\"\n            )\n\n        if \"testval\" in kwargs:\n            initval = kwargs.pop(\"testval\")\n            warnings.warn(\n                \"The `testval` argument is deprecated; use `initval`.\",\n                FutureWarning,\n                stacklevel=2,\n            )\n\n        if not isinstance(name, string_types):\n            raise TypeError(f\"Name needs to be a string but got: {name}\")\n\n        if rng is None:\n            rng = model.next_rng()\n\n        # Create the RV and process dims and observed to determine\n        # a shape by which the created RV may need to be resized.\n        rv_out, dims, observed, resize_shape = _make_rv_and_resize_shape(\n            cls=cls, dims=dims, model=model, observed=observed, args=args, rng=rng, **kwargs\n        )\n\n        if resize_shape:\n            # A batch size was specified through `dims`, or implied by `observed`.\n            rv_out = change_rv_size(rv=rv_out, new_size=resize_shape, expand=True)\n\n        rv_out = model.register_rv(\n            rv_out,\n            name,\n            observed,\n            total_size,\n            dims=dims,\n            transform=transform,\n            initval=initval,\n        )\n\n        # add in pretty-printing support\n        rv_out.str_repr = types.MethodType(str_for_dist, rv_out)\n        rv_out._repr_latex_ = types.MethodType(\n            functools.partial(str_for_dist, formatting=\"latex\"), rv_out\n        )\n\n        rv_out.logp = _make_nice_attr_error(\"rv.logp(x)\", \"pm.logp(rv, x)\")\n        rv_out.logcdf = _make_nice_attr_error(\"rv.logcdf(x)\", \"pm.logcdf(rv, x)\")\n        rv_out.random = _make_nice_attr_error(\"rv.random()\", \"rv.eval()\")\n        return rv_out\n\n    @classmethod\n    def dist(\n        cls,\n        dist_params,\n        *,\n        shape: Optional[Shape] = None,\n        size: Optional[Size] = None,\n        **kwargs,\n    ) -> RandomVariable:\n        \"\"\"Creates a RandomVariable corresponding to the `cls` distribution.\n\n        Parameters\n        ----------\n        dist_params : array-like\n            The inputs to the `RandomVariable` `Op`.\n        shape : int, tuple, Variable, optional\n            A tuple of sizes for each dimension of the new RV.\n\n            An Ellipsis (...) may be inserted in the last position to short-hand refer to\n            all the dimensions that the RV would get if no shape/size/dims were passed at all.\n        size : int, tuple, Variable, optional\n            For creating the RV like in Aesara/NumPy.\n\n        Returns\n        -------\n        rv : RandomVariable\n            The created RV.\n        \"\"\"\n        if \"testval\" in kwargs:\n            kwargs.pop(\"testval\")\n            warnings.warn(\n                \"The `.dist(testval=...)` argument is deprecated and has no effect. \"\n                \"Initial values for sampling/optimization can be specified with `initval` in a modelcontext. \"\n                \"For using Aesara's test value features, you must assign the `.tag.test_value` yourself.\",\n                FutureWarning,\n                stacklevel=2,\n            )\n        if \"initval\" in kwargs:\n            raise TypeError(\n                \"Unexpected keyword argument `initval`. \"\n                \"This argument is not available for the `.dist()` API.\"\n            )\n\n        if \"dims\" in kwargs:\n            raise NotImplementedError(\"The use of a `.dist(dims=...)` API is not supported.\")\n        if shape is not None and size is not None:\n            raise ValueError(\n                f\"Passing both `shape` ({shape}) and `size` ({size}) is not supported!\"\n            )\n\n        shape = convert_shape(shape)\n        size = convert_size(size)\n\n        create_size, ndim_expected, ndim_batch, ndim_supp = find_size(\n            shape=shape, size=size, ndim_supp=cls.rv_op.ndim_supp\n        )\n        # Create the RV with a `size` right away.\n        # This is not necessarily the final result.\n        rv_out = cls.rv_op(*dist_params, size=create_size, **kwargs)\n\n        # Replicate dimensions may be prepended via a shape with Ellipsis as the last element:\n        if shape is not None and Ellipsis in shape:\n            replicate_shape = cast(StrongShape, shape[:-1])\n            rv_out = change_rv_size(rv=rv_out, new_size=replicate_shape, expand=True)\n\n        rv_out.logp = _make_nice_attr_error(\"rv.logp(x)\", \"pm.logp(rv, x)\")\n        rv_out.logcdf = _make_nice_attr_error(\"rv.logcdf(x)\", \"pm.logcdf(rv, x)\")\n        rv_out.random = _make_nice_attr_error(\"rv.random()\", \"rv.eval()\")\n        return rv_out\n\n\nclass SymbolicDistribution:\n    \"\"\"Symbolic statistical distribution\n\n    While traditional PyMC distributions are represented by a single RandomVariable\n    graph, Symbolic distributions correspond to a larger graph that contains one or\n    more RandomVariables and an arbitrary number of deterministic operations, which\n    represent their own kind of distribution.\n\n    The graphs returned by symbolic distributions can be evaluated directly to\n    obtain valid draws and can further be parsed by Aeppl to derive the\n    corresponding logp at runtime.\n\n    Check pymc.distributions.Censored for an example of a symbolic distribution.\n\n    Symbolic distributions must implement the following classmethods:\n    cls.dist\n        Performs input validation and converts optional alternative parametrizations\n        to a canonical parametrization. It should call `super().dist()`, passing a\n        list with the default parameters as the first and only non keyword argument,\n        followed by other keyword arguments like size and rngs, and return the result\n    cls.num_rngs\n        Returns the number of rngs given the same arguments passed by the user when\n        calling the distribution\n    cls.ndim_supp\n        Returns the support of the symbolic distribution, given the default set of\n        parameters. This may not always be constant, for instance if the symbolic\n        distribution can be defined based on an arbitrary base distribution.\n    cls.rv_op\n        Returns a TensorVariable that represents the symbolic distribution\n        parametrized by a default set of parameters and a size and rngs arguments\n    cls.change_size\n        Returns an equivalent symbolic distribution with a different size. This is\n        analogous to `pymc.aesaraf.change_rv_size` for `RandomVariable`s.\n    \"\"\"\n\n    def __new__(\n        cls,\n        name: str,\n        *args,\n        rngs: Optional[Iterable] = None,\n        dims: Optional[Dims] = None,\n        initval=None,\n        observed=None,\n        total_size=None,\n        transform=UNSET,\n        **kwargs,\n    ) -> TensorVariable:\n        \"\"\"Adds a TensorVariable corresponding to a PyMC symbolic distribution to the\n        current model.\n\n        Parameters\n        ----------\n        cls : type\n            A distribution class that inherits from SymbolicDistribution.\n        name : str\n            Name for the new model variable.\n        rngs : optional\n            Random number generator to use for the RandomVariable(s) in the graph.\n        dims : tuple, optional\n            A tuple of dimension names known to the model.\n        initval : optional\n            Numeric or symbolic untransformed initial value of matching shape,\n            or one of the following initial value strategies: \"moment\", \"prior\".\n            Depending on the sampler's settings, a random jitter may be added to numeric,\n            symbolic or moment-based initial values in the transformed space.\n        observed : optional\n            Observed data to be passed when registering the random variable in the model.\n            See ``Model.register_rv``.\n        total_size : float, optional\n            See ``Model.register_rv``.\n        transform : optional\n            See ``Model.register_rv``.\n        **kwargs\n            Keyword arguments that will be forwarded to ``.dist()``.\n            Most prominently: ``shape`` and ``size``\n\n        Returns\n        -------\n        var : TensorVariable\n            The created variable, registered in the Model.\n        \"\"\"\n\n        try:\n            from pymc.model import Model\n\n            model = Model.get_context()\n        except TypeError:\n            raise TypeError(\n                \"No model on context stack, which is needed to \"\n                \"instantiate distributions. Add variable inside \"\n                \"a 'with model:' block, or use the '.dist' syntax \"\n                \"for a standalone distribution.\"\n            )\n\n        if \"testval\" in kwargs:\n            initval = kwargs.pop(\"testval\")\n            warnings.warn(\n                \"The `testval` argument is deprecated; use `initval`.\",\n                FutureWarning,\n                stacklevel=2,\n            )\n\n        if not isinstance(name, string_types):\n            raise TypeError(f\"Name needs to be a string but got: {name}\")\n\n        if rngs is None:\n            # Instead of passing individual RNG variables we could pass a RandomStream\n            # and let the classes create as many RNGs as they need\n            rngs = [model.next_rng() for _ in range(cls.num_rngs(*args, **kwargs))]\n        elif not isinstance(rngs, (list, tuple)):\n            rngs = [rngs]\n\n        # Create the RV and process dims and observed to determine\n        # a shape by which the created RV may need to be resized.\n        rv_out, dims, observed, resize_shape = _make_rv_and_resize_shape(\n            cls=cls, dims=dims, model=model, observed=observed, args=args, rngs=rngs, **kwargs\n        )\n\n        if resize_shape:\n            # A batch size was specified through `dims`, or implied by `observed`.\n            rv_out = cls.change_size(\n                rv=rv_out,\n                new_size=resize_shape,\n                expand=True,\n            )\n\n        rv_out = model.register_rv(\n            rv_out,\n            name,\n            observed,\n            total_size,\n            dims=dims,\n            transform=transform,\n            initval=initval,\n        )\n\n        # TODO: Refactor this\n        # add in pretty-printing support\n        rv_out.str_repr = lambda *args, **kwargs: name\n        rv_out._repr_latex_ = f\"\\\\text{name}\"\n        # rv_out.str_repr = types.MethodType(str_for_dist, rv_out)\n        # rv_out._repr_latex_ = types.MethodType(\n        #     functools.partial(str_for_dist, formatting=\"latex\"), rv_out\n        # )\n\n        return rv_out\n\n    @classmethod\n    def dist(\n        cls,\n        dist_params,\n        *,\n        shape: Optional[Shape] = None,\n        size: Optional[Size] = None,\n        **kwargs,\n    ) -> TensorVariable:\n        \"\"\"Creates a TensorVariable corresponding to the `cls` symbolic distribution.\n\n        Parameters\n        ----------\n        dist_params : array-like\n            The inputs to the `RandomVariable` `Op`.\n        shape : int, tuple, Variable, optional\n            A tuple of sizes for each dimension of the new RV.\n            An Ellipsis (...) may be inserted in the last position to short-hand refer to\n            all the dimensions that the RV would get if no shape/size/dims were passed at all.\n        size : int, tuple, Variable, optional\n            For creating the RV like in Aesara/NumPy.\n\n        Returns\n        -------\n        var : TensorVariable\n        \"\"\"\n\n        if \"testval\" in kwargs:\n            kwargs.pop(\"testval\")\n            warnings.warn(\n                \"The `.dist(testval=...)` argument is deprecated and has no effect. \"\n                \"Initial values for sampling/optimization can be specified with `initval` in a modelcontext. \"\n                \"For using Aesara's test value features, you must assign the `.tag.test_value` yourself.\",\n                FutureWarning,\n                stacklevel=2,\n            )\n        if \"initval\" in kwargs:\n            raise TypeError(\n                \"Unexpected keyword argument `initval`. \"\n                \"This argument is not available for the `.dist()` API.\"\n            )\n\n        if \"dims\" in kwargs:\n            raise NotImplementedError(\"The use of a `.dist(dims=...)` API is not supported.\")\n        if shape is not None and size is not None:\n            raise ValueError(\n                f\"Passing both `shape` ({shape}) and `size` ({size}) is not supported!\"\n            )\n\n        shape = convert_shape(shape)\n        size = convert_size(size)\n\n        create_size, ndim_expected, ndim_batch, ndim_supp = find_size(\n            shape=shape, size=size, ndim_supp=cls.ndim_supp(*dist_params)\n        )\n        # Create the RV with a `size` right away.\n        # This is not necessarily the final result.\n        graph = cls.rv_op(*dist_params, size=create_size, **kwargs)\n\n        # Replicate dimensions may be prepended via a shape with Ellipsis as the last element:\n        if shape is not None and Ellipsis in shape:\n            replicate_shape = cast(StrongShape, shape[:-1])\n            graph = cls.change_size(rv=graph, new_size=replicate_shape, expand=True)\n\n        # TODO: Create new attr error stating that these are not available for DerivedDistribution\n        # rv_out.logp = _make_nice_attr_error(\"rv.logp(x)\", \"pm.logp(rv, x)\")\n        # rv_out.logcdf = _make_nice_attr_error(\"rv.logcdf(x)\", \"pm.logcdf(rv, x)\")\n        # rv_out.random = _make_nice_attr_error(\"rv.random()\", \"rv.eval()\")\n        return graph\n\n\n@singledispatch\ndef _moment(op, rv, *rv_inputs) -> TensorVariable:\n    raise NotImplementedError(f\"Variable {rv} of type {op} has no moment implementation.\")\n\n\ndef moment(rv: TensorVariable) -> TensorVariable:\n    \"\"\"Method for choosing a representative point/value\n    that can be used to start optimization or MCMC sampling.\n\n    The only parameter to this function is the RandomVariable\n    for which the value is to be derived.\n    \"\"\"\n    return _moment(rv.owner.op, rv, *rv.owner.inputs).astype(rv.dtype)\n\n\n@_moment.register(Elemwise)\ndef moment_elemwise(op, rv, *dist_params):\n    \"\"\"For Elemwise Ops, dispatch on respective scalar_op\"\"\"\n    return _moment(op.scalar_op, rv, *dist_params)\n\n\nclass Discrete(Distribution):\n    \"\"\"Base class for discrete distributions\"\"\"\n\n    def __new__(cls, name, *args, **kwargs):\n\n        if kwargs.get(\"transform\", None):\n            raise ValueError(\"Transformations for discrete distributions\")\n\n        return super().__new__(cls, name, *args, **kwargs)\n\n\nclass Continuous(Distribution):\n    \"\"\"Base class for continuous distributions\"\"\"\n\n\nclass NoDistribution(Distribution):\n    \"\"\"Base class for artifical distributions\n\n    RandomVariables that share this type are allowed in logprob graphs\n    \"\"\"\n\n\nclass DensityDistRV(RandomVariable):\n    \"\"\"\n    Base class for DensityDistRV\n\n    This should be subclassed when defining custom DensityDist objects.\n    \"\"\"\n\n    name = \"DensityDistRV\"\n    _print_name = (\"DensityDist\", \"\\\\operatorname{DensityDist}\")\n\n    @classmethod\n    def rng_fn(cls, rng, *args):\n        args = list(args)\n        size = args.pop(-1)\n        return cls._random_fn(*args, rng=rng, size=size)\n\n\nclass DensityDist(NoDistribution):\n    \"\"\"A distribution that can be used to wrap black-box log density functions.\n\n    Creates a Distribution and registers the supplied log density function to be used\n    for inference. It is also possible to supply a `random` method in order to be able\n    to sample from the prior or posterior predictive distributions.\n    \"\"\"\n\n    def __new__(\n        cls,\n        name: str,\n        *dist_params,\n        logp: Optional[Callable] = None,\n        logcdf: Optional[Callable] = None,\n        random: Optional[Callable] = None,\n        moment: Optional[Callable] = None,\n        ndim_supp: int = 0,\n        ndims_params: Optional[Sequence[int]] = None,\n        dtype: str = \"floatX\",\n        **kwargs,\n    ):\n        \"\"\"\n        Parameters\n        ----------\n        name : str\n        dist_params : Tuple\n            A sequence of the distribution's parameter. These will be converted into\n            Aesara tensors internally. These parameters could be other ``RandomVariable``\n            instances.\n        logp : Optional[Callable]\n            A callable that calculates the log density of some given observed ``value``\n            conditioned on certain distribution parameter values. It must have the\n            following signature: ``logp(value, *dist_params)``, where ``value`` is\n            an Aesara tensor that represents the observed value, and ``dist_params``\n            are the tensors that hold the values of the distribution parameters.\n            This function must return an Aesara tensor. If ``None``, a ``NotImplemented``\n            error will be raised when trying to compute the distribution's logp.\n        logcdf : Optional[Callable]\n            A callable that calculates the log cummulative probability of some given observed\n            ``value`` conditioned on certain distribution parameter values. It must have the\n            following signature: ``logcdf(value, *dist_params)``, where ``value`` is\n            an Aesara tensor that represents the observed value, and ``dist_params``\n            are the tensors that hold the values of the distribution parameters.\n            This function must return an Aesara tensor. If ``None``, a ``NotImplemented``\n            error will be raised when trying to compute the distribution's logcdf.\n        random : Optional[Callable]\n            A callable that can be used to generate random draws from the distribution.\n            It must have the following signature: ``random(*dist_params, rng=None, size=None)``.\n            The distribution parameters are passed as positional arguments in the\n            same order as they are supplied when the ``DensityDist`` is constructed.\n            The keyword arguments are ``rnd``, which will provide the random variable's\n            associated :py:class:`~numpy.random.Generator`, and ``size``, that will represent\n            the desired size of the random draw. If ``None``, a ``NotImplemented``\n            error will be raised when trying to draw random samples from the distribution's\n            prior or posterior predictive.\n        moment : Optional[Callable]\n            A callable that can be used to compute the moments of the distribution.\n            It must have the following signature: ``moment(rv, size, *rv_inputs)``.\n            The distribution's :class:`~aesara.tensor.random.op.RandomVariable` is passed\n            as the first argument ``rv``. ``size`` is the random variable's size implied\n            by the ``dims``, ``size`` and parameters supplied to the distribution. Finally,\n            ``rv_inputs`` is the sequence of the distribution parameters, in the same order\n            as they were supplied when the DensityDist was created. If ``None``, a default\n            ``moment`` function will be assigned that will always return 0, or an array\n            of zeros.\n        ndim_supp : int\n            The number of dimensions in the support of the distribution. Defaults to assuming\n            a scalar distribution, i.e. ``ndim_supp = 0``.\n        ndims_params : Optional[Sequence[int]]\n            The list of number of dimensions in the support of each of the distribution's\n            parameters. If ``None``, it is assumed that all parameters are scalars, hence\n            the number of dimensions of their support will be 0.\n        dtype : str\n            The dtype of the distribution. All draws and observations passed into the distribution\n            will be casted onto this dtype.\n        kwargs :\n            Extra keyword arguments are passed to the parent's class ``__new__`` method.\n\n        Examples\n        --------\n            .. code-block:: python\n\n                def logp(value, mu):\n                    return -(value - mu)**2\n\n                with pm.Model():\n                    mu = pm.Normal('mu',0,1)\n                    pm.DensityDist(\n                        'density_dist',\n                        mu,\n                        logp=logp,\n                        observed=np.random.randn(100),\n                    )\n                    idata = pm.sample(100)\n\n            .. code-block:: python\n\n                def logp(value, mu):\n                    return -(value - mu)**2\n\n                def random(mu, rng=None, size=None):\n                    return rng.normal(loc=mu, scale=1, size=size)\n\n                with pm.Model():\n                    mu = pm.Normal('mu', 0 , 1)\n                    dens = pm.DensityDist(\n                        'density_dist',\n                        mu,\n                        logp=logp,\n                        random=random,\n                        observed=np.random.randn(100, 3),\n                        size=(100, 3),\n                    )\n                    prior = pm.sample_prior_predictive(10).prior_predictive['density_dist']\n                assert prior.shape == (1, 10, 100, 3)\n\n        \"\"\"\n\n        if dist_params is None:\n            dist_params = []\n        elif len(dist_params) > 0 and callable(dist_params[0]):\n            raise TypeError(\n                \"The DensityDist API has changed, you are using the old API \"\n                \"where logp was the first positional argument. In the current API, \"\n                \"the logp is a keyword argument, amongst other changes. Please refer \"\n                \"to the API documentation for more information on how to use the \"\n                \"new DensityDist API.\"\n            )\n        dist_params = [as_tensor_variable(param) for param in dist_params]\n\n        # Assume scalar ndims_params\n        if ndims_params is None:\n            ndims_params = [0] * len(dist_params)\n\n        if logp is None:\n            logp = default_not_implemented(name, \"logp\")\n\n        if logcdf is None:\n            logcdf = default_not_implemented(name, \"logcdf\")\n\n        if moment is None:\n            moment = functools.partial(\n                default_moment,\n                rv_name=name,\n                has_fallback=random is not None,\n                ndim_supp=ndim_supp,\n            )\n\n        if random is None:\n            random = default_not_implemented(name, \"random\")\n\n        rv_op = type(\n            f\"DensityDist_{name}\",\n            (DensityDistRV,),\n            dict(\n                name=f\"DensityDist_{name}\",\n                inplace=False,\n                ndim_supp=ndim_supp,\n                ndims_params=ndims_params,\n                dtype=dtype,\n                # Specifc to DensityDist\n                _random_fn=random,\n            ),\n        )()\n\n        # Register custom logp\n        rv_type = type(rv_op)\n\n        @_logprob.register(rv_type)\n        def density_dist_logp(op, value_var_list, *dist_params, **kwargs):\n            _dist_params = dist_params[3:]\n            value_var = value_var_list[0]\n            return logp(value_var, *_dist_params)\n\n        @_logcdf.register(rv_type)\n        def density_dist_logcdf(op, var, rvs_to_values, *dist_params, **kwargs):\n            value_var = rvs_to_values.get(var, var)\n            return logcdf(value_var, *dist_params, **kwargs)\n\n        @_moment.register(rv_type)\n        def density_dist_get_moment(op, rv, rng, size, dtype, *dist_params):\n            return moment(rv, size, *dist_params)\n\n        cls.rv_op = rv_op\n        return super().__new__(cls, name, *dist_params, **kwargs)\n\n    @classmethod\n    def dist(cls, *args, **kwargs):\n        output = super().dist(args, **kwargs)\n        if cls.rv_op.dtype == \"floatX\":\n            dtype = aesara.config.floatX\n        else:\n            dtype = cls.rv_op.dtype\n        ndim_supp = cls.rv_op.ndim_supp\n        return output\n\n\ndef default_not_implemented(rv_name, method_name):\n    message = (\n        f\"Attempted to run {method_name} on the DensityDist '{rv_name}', \"\n        f\"but this method had not been provided when the distribution was \"\n        f\"constructed. Please re-build your model and provide a callable \"\n        f\"to '{rv_name}'s {method_name} keyword argument.\\n\"\n    )\n\n    def func(*args, **kwargs):\n        raise NotImplementedError(message)\n\n    return func\n\n\ndef default_moment(rv, size, *rv_inputs, rv_name=None, has_fallback=False, ndim_supp=0):\n    if ndim_supp == 0:\n        return at.zeros(size, dtype=rv.dtype)\n    elif has_fallback:\n        return at.zeros_like(rv)\n    else:\n        raise TypeError(\n            \"Cannot safely infer the size of a multivariate random variable's moment. \"\n            f\"Please provide a moment function when instantiating the {rv_name} \"\n            \"random variable.\"\n        )\n", "meta": {"hexsha": "138b3cd2532183577514c390c0c57ff11688c2e3", "size": 32242, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymc/distributions/distribution.py", "max_stars_repo_name": "larryshamalama/pymc", "max_stars_repo_head_hexsha": "ce2e8910abcab91eb326d31554eb7d1265b2d55a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pymc/distributions/distribution.py", "max_issues_repo_name": "larryshamalama/pymc", "max_issues_repo_head_hexsha": "ce2e8910abcab91eb326d31554eb7d1265b2d55a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pymc/distributions/distribution.py", "max_forks_repo_name": "larryshamalama/pymc", "max_forks_repo_head_hexsha": "ce2e8910abcab91eb326d31554eb7d1265b2d55a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2309468822, "max_line_length": 110, "alphanum_fraction": 0.6092053843, "include": true, "reason": "import numpy", "num_tokens": 6948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.3174262720448507, "lm_q1q2_score": 0.1686198110653126}}
{"text": "# -*-coding:utf-8 -*-\n\n'''\n@File       : beam_search.py\n@Author     : HW Shen\n@Date       : 2020/8/12\n@Desc       :\n'''\n\nimport numpy as np\nimport tensorflow as tf\n\nBATCH_SIZE = 1  # 每个batch数据量\nBEAM_SIZE = 2  # beam_search的尺度\nEMB_DIM = 10  # 词向量维度\nENCODER_UNITS = 20  # encoder层的单位数\nDECODER_UNITS = 20  # decoder层的单位数\nATTENTION_UNITS = 20  # attention层的单位数\nMAX_LEN = 10  # Decoding输出的最大长度\nMIN_LEN = 1   # Decoding输出的最小长度\nSTART_TOKEN = 'START'  # Decoder过程的开始标识符\nEND_TOKEN = 'END'  # Deocder过程的结束标识符\nUNK_TOKEN = 'UNK'  # OOV\n\nword2id = {'START': 0, 'END': 1, 'PAD': 2, '我': 3, '你': 4, '洗澡': 5, '吃饭': 6, 'UNK': 7}\nid2word = ['START', 'END', 'PAD', '我', '你', '洗澡', '吃饭', 'UNK']\n\n\nclass Encoder(tf.keras.layers.Layer):\n    \"\"\"编码器 : 双层GRU \"\"\"\n\n    def __init__(self, vocab_size, embedding_dim, encoder_units, batch_size):\n\n        super(Encoder, self).__init__()\n        self.batch_size = batch_size\n        self.encoder_units = encoder_units // 2  # 因为是双向的，所以每一层均分encoder_units\n        self.embedding = tf.keras.layers.Embedding(input_dim=vocab_size, output_dim=embedding_dim)\n        self.gru = tf.keras.layers.GRU(units=self.encoder_units,\n                                       return_sequences=True,\n                                       return_state=True,\n                                       recurrent_initializer='glorot_uniform')\n        self.bi_gru = tf.keras.layers.Bidirectional(layer=self.gru, merge_mode='concat')\n\n    def call(self, x, hidden):\n        x = self.embedding(x)\n        hidden = tf.split(value=hidden, num_or_size_splits=2, axis=1)\n        output, forward_state, backward_state = self.bi_gru(x, initial_state=hidden)\n        state = tf.concat([forward_state, backward_state], axis=1)\n\n        return output, state\n\n    def initialize_hidden_state(self):\n        # encoder隐层初始化参数\n        return tf.zeros((self.batch_size, self.encoder_units * 2))  # shape:(batch_size, encoder_units)\n\n\nclass Attention(tf.keras.layers.Layer):\n    \"\"\"attention 类\"\"\"\n\n    def __init__(self, units):\n        super(Attention, self).__init__()\n        self.W_s = tf.keras.layers.Dense(units)\n        self.W_h = tf.keras.layers.Dense(units)\n        self.V = tf.keras.layers.Dense(1)\n\n    def call(self, decoder_hidden, encoder_output):\n\n        hidden_with_time_axis = tf.expand_dims(decoder_hidden, 1)  # 给dec_hidden增加一个时间维度\n        score = self.V(tf.nn.tanh(self.W_s(encoder_output) + self.W_h(hidden_with_time_axis)))  # 注意力得分\n        attn_dist = tf.nn.softmax(score, axis=1)  # 注意力得分归一化\n        context_vector = attn_dist * encoder_output  # 输入词向量的上下文向量\n        context_vector = tf.reduce_sum(context_vector, axis=1)  # 上下文向量的求和，降维\n\n        return context_vector, tf.squeeze(attn_dist, -1)\n\n\nclass Decoder(tf.keras.layers.Layer):\n    \"\"\" 解码层 ： 单层 GRU + Dense\"\"\"\n\n    def __init__(self, vocab_size, embedding_dim, decoder_units, batch_size):\n        super(Decoder, self).__init__()\n        self.batch_size = batch_size\n        self.decoder_units = decoder_units  # Decoder是单层GRU\n        self.embedding = tf.keras.layers.Embedding(input_dim=vocab_size, output_dim=embedding_dim)\n        self.gru = tf.keras.layers.GRU(units=self.decoder_units,\n                                       return_sequences=True,\n                                       return_state=True,\n                                       recurrent_initializer='glorot_uniform')\n        self.fc = tf.keras.layers.Dense(units=vocab_size, activation=tf.keras.activations.softmax)\n\n    def call(self, x, hidden, enc_output, context_vector):\n        x = self.embedding(x)\n        x = tf.concat([tf.expand_dims(context_vector, 1), x], axis=-1)\n        output, state = self.gru(x)\n        output = tf.reshape(output, (-1, output.shape[2]))\n        out = self.fc(output)\n        return x, out, state\n\n\nclass Seq2SeqModel(object):\n    \"\"\"seq2seq 类\"\"\"\n\n    def __init__(self, encoder, decoder, attention):\n\n        self.encoder = encoder\n        self.decoder = decoder\n        self.attention = attention\n\n    def call_encoder(self, encoder_input):\n\n        encoder_hidden = self.encoder.initialize_hidden_state()  # 初始化隐层参数矩阵\n        encoder_output, encoder_hidden = self.encoder(encoder_input, encoder_hidden)  # 编码器的 output 和 hidden_state\n\n        return encoder_output, encoder_hidden\n\n    def decode_one_step(self, latest_tokens, encoder_states, decoder_in_states):\n        \"\"\"\n        Decoder层的每一步解码\n        Args:\n            latest_tokens: 当前时间步, 解码器输入的 token\n            encoder_states: 编码器输出的 output\n            decoder_in_states: 解码器上一时间步传来的隐层向量\n        Returns:\n            top_k_ids: [beam, beam * 2], 解码结果中 top 2 * beam 的 token id\n            top_k_log_probs: [beam, beam * 2], 解码过程中 top 2 * beam 的 log 概率得分\n            new_states: list, 每个 item 是每个 beam 中的隐层向量\n        \"\"\"\n        # latest_tokens = np.transpose(np.array([latest_tokens]))\n        # decoder_in_states = np.concatenate(arrays=decoder_in_states, axis=0)\n        latest_tokens = tf.transpose([latest_tokens])\n        decoder_in_states = tf.concat(values=decoder_in_states, axis=0)\n        context_vector, attn_dists = self.attention(decoder_in_states, encoder_states)\n        _, prediction, decoder_hidden = self.decoder(latest_tokens, decoder_in_states, encoder_states, context_vector)\n        # 把上一步预测的结果prediction作为topK的选依据\n        top_k_log_probs, top_k_ids = tf.nn.top_k(input=prediction, k=BEAM_SIZE * 2, sorted=True)\n        top_k_log_probs = tf.math.log(x=top_k_log_probs)\n        new_states = [np.expand_dims(decoder_hidden[i, :], axis=0) for i in range(BEAM_SIZE)]\n\n        return top_k_ids.numpy(), top_k_log_probs, new_states, attn_dists\n\n\nclass BeamHypotheses(object):\n    \"\"\" BeamSearch的假设 \"\"\"\n\n    def __init__(self, token_list, log_prob_list, state, attn_dist_list):\n\n        self.token_list = token_list  # list of all the tokens from time 0 to the current time step t\n        self.log_prob_list = log_prob_list  # list of the log probabilities of the tokens\n        self.state = state  # decoder state after the last token decoding\n        self.attn_dist_list = attn_dist_list  # attention dists of all the tokens\n\n    def extend(self, token, log_prob, state, attn_dist):\n        \"\"\"\n        Method to extend the current hypothesis by adding the next decoded token\n        Args:\n            token: the next decoded token\n            log_prob: the log prob of the next decoded token\n            state: next hidden state\n            attn_dist: # the attention dist of the next decoded toke\n        Returns: next hypothesis\n        \"\"\"\n        return BeamHypotheses(\n            token_list=self.token_list + [token],\n            log_prob_list=self.log_prob_list + [log_prob],\n            state=state,\n            attn_dist_list=self.attn_dist_list + [attn_dist]\n        )\n\n    @property\n    def latest_token(self):\n        return self.token_list[-1]\n\n    @property\n    def log_prob(self):\n        return sum(self.log_prob_list)\n\n    @property\n    def avg_log_prob(self):\n        return self.log_prob / len(self.token_list)\n\n\nclass Generation(object):\n    \"\"\" 按照beam_search的方式 生成Decode的相应结果 \"\"\"\n\n    def __init__(self):\n        pass\n\n    @staticmethod\n    def sort_hyp(hyp_list):\n        # 对所有假设从大到小排序（按照平均概率值）\n        return sorted(hyp_list, key=lambda h: h.avg_log_prob, reverse=True)\n\n    def generate_beam_search(self, model, model_input):\n\n        # encoder states bi-gru 的 output; decoder in state 是拼接的隐层向量\n        encoder_states, decoder_in_state = model.call_encoder(model_input)\n        hyp_list = [\n            BeamHypotheses(token_list=[word2id[START_TOKEN]],\n                           log_prob_list=[0.0],\n                           state=decoder_in_state,\n                           attn_dist_list=[],\n                           ) for _ in range(BEAM_SIZE)\n        ]\n        result = []\n        step = 0\n\n        while step < MAX_LEN and len(result) < BEAM_SIZE:\n            # 容器里每个 hpy 的最后一个 token 的列表\n            latest_tokens = [hyp.latest_token for hyp in hyp_list]\n            # 处理异常, 搞成 unk 的 id\n            latest_tokens = [token if token in range(len(id2word)) else word2id[UNK_TOKEN] for token in latest_tokens]\n            # 容器里的 hpy 在解码器得到 state 的列表\n            states = [hyp.state for hyp in hyp_list]\n\n            top_k_ids, top_k_log_probs, new_states, attn_dists = model.decode_one_step(latest_tokens=latest_tokens,\n                                                                                       encoder_states=encoder_states,\n                                                                                       decoder_in_states=states)\n            # extend 操作后, 都收集在 all_hyp_list 中\n            all_hyp_list = []\n            # 初始状态开始 beam search 时, 实际只有一种状态; 但在后面的 step 时, 每次都有 beam 个状态\n            num_ori_hyp = 1 if step == 0 else len(hyp_list)\n\n            for i in range(num_ori_hyp):\n                hyp = hyp_list[i]\n                new_state = new_states[i]\n                attn_dist = attn_dists[i]\n\n                for j in range(BEAM_SIZE * 2):\n                    new_hpy = hyp.extend(token=top_k_ids[i, j],\n                                         log_prob=top_k_log_probs[i, j],\n                                         state=new_state,\n                                         attn_dist=attn_dist)\n                    all_hyp_list.append(new_hpy)\n\n            # 对 hpy 进行排序, 只有满足了 END TOKEN 和 MIN LEN 才会加入result\n            hyp_list = []\n            for hyp in self.sort_hyp(all_hyp_list):\n                # 出现终止符号\n                if hyp.latest_token == word2id[END_TOKEN]:\n                    if step >= MIN_LEN:\n                        result.append(hyp)\n                else:\n                    hyp_list.append(hyp)\n                if len(hyp_list) == BEAM_SIZE or len(result) == BEAM_SIZE:\n                    break\n\n            step += 1\n\n        # 如果循环都结束了, 但都仍然没有 END 出现, result 就是一个空 hyp_list, 此时要把此时的 hyp list 进行排序取最大的输出\n        if len(result) == 0:\n            result = hyp_list\n        hyp_sorted = self.sort_hyp(result)\n\n        return ' '.join(id2word[index] for index in hyp_sorted[0].token_list)\n\n\nif __name__ == '__main__':\n    model_obj = Seq2SeqModel(encoder=Encoder(vocab_size=len(word2id),\n                                             embedding_dim=EMB_DIM,\n                                             encoder_units=ENCODER_UNITS,\n                                             batch_size=BATCH_SIZE),\n                             decoder=Decoder(vocab_size=len(word2id),\n                                             embedding_dim=EMB_DIM,\n                                             decoder_units=DECODER_UNITS,\n                                             batch_size=BATCH_SIZE),\n                             attention=Attention(units=ATTENTION_UNITS))\n    generator_obj = Generation()\n    res = generator_obj.generate_beam_search(model_obj, np.array([[0, 3, 5, 5, 5]]))\n    print(res)", "meta": {"hexsha": "1d9f68d08e97812dcc427ac09c7073614f6c77ba", "size": 10809, "ext": "py", "lang": "Python", "max_stars_repo_path": "PythonSmallTools/beam_search.py", "max_stars_repo_name": "xiaobuguilaile/python-small-tools", "max_stars_repo_head_hexsha": "50fb3f1fc0bd0a7e1e2817d11383ac20fbd514fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PythonSmallTools/beam_search.py", "max_issues_repo_name": "xiaobuguilaile/python-small-tools", "max_issues_repo_head_hexsha": "50fb3f1fc0bd0a7e1e2817d11383ac20fbd514fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PythonSmallTools/beam_search.py", "max_forks_repo_name": "xiaobuguilaile/python-small-tools", "max_forks_repo_head_hexsha": "50fb3f1fc0bd0a7e1e2817d11383ac20fbd514fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1821561338, "max_line_length": 118, "alphanum_fraction": 0.595337219, "include": true, "reason": "import numpy", "num_tokens": 2788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.16861980763520082}}
{"text": "#!/usr/bin/env python\n#\n# Copyright 2019 DFKI GmbH.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the\n# following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n# USE OR OTHER DEALINGS IN THE SOFTWARE.\nimport numpy as np\nfrom .fabrik_chain import FABRIKChain, to_local_cos, quaternion_from_vector_to_vector, FABRIKBone, ROOT_OFFSET\n\n\ndef get_child_offset(skeleton, node, child_node):\n    actual_offset = np.array([0, 0, 0], np.float)\n    while node is not None and skeleton.nodes[node].children[0].node_name != child_node:\n        local_offset = np.array(skeleton.nodes[node].children[0].offset)\n        local_offset_len = np.linalg.norm(local_offset)\n        if local_offset_len > 0:\n            local_offset /= local_offset_len\n            actual_offset = actual_offset + local_offset\n            node = skeleton.nodes[node].children[0].node_name\n            if len(skeleton.nodes[node].children) < 1:\n                node = None\n        else:\n            node = None\n    return actual_offset\n\n\ndef get_global_joint_parameters_from_positions(skeleton, positions, next_nodes):\n    n_parameters = len(skeleton.animated_joints)*4+3\n    frame = np.zeros(n_parameters)\n    frame[:3] = positions[skeleton.root]\n    o = 3\n    print(skeleton.animated_joints)\n    print(next_nodes.keys())\n    print(positions.keys())\n    for node in skeleton.animated_joints:\n        next_node = next_nodes[node]\n        if next_node in positions:\n            next_offset = np.array(skeleton.nodes[next_node].offset)\n            next_offset /= np.linalg.norm(next_offset)\n\n            # 1. sum over offsets of static nodes\n            local_offset = get_child_offset(skeleton, node, next_node)\n            #print(node, local_offset)\n            actual_offset = next_offset + local_offset\n            actual_offset /= np.linalg.norm(actual_offset)  # actual_offset = [0.5, 0.5,0]\n\n\n            dir_to_child = positions[next_node] - positions[node]\n            dir_to_child /= np.linalg.norm(dir_to_child)\n\n            # 2. get global rotation\n            global_q = quaternion_from_vector_to_vector(actual_offset, dir_to_child)\n            frame[o:o + 4] = global_q\n        else:\n            #print(\"ignore\", node, next_node)\n            frame[o:o + 4] = [1,0,0,0]\n        o += 4\n    return frame\n\n\ndef global_to_local_frame(skeleton, global_frame):\n    n_parameters = len(skeleton.animated_joints)*4+3\n    frame = np.zeros(n_parameters)\n    o = 3\n    for node in skeleton.animated_joints:\n        frame[o:o + 4] = to_local_cos(skeleton, node, frame, global_frame[o:o + 4])\n\n        o += 4\n\n    return frame\n\n\nclass FABRIKNode(object):\n    def __init__(self, skeleton, root, parent_chain=None, tolerance=0.01, max_iter=100, root_offset=ROOT_OFFSET):\n        self.root_pos = np.array([0,0,0], dtype=np.float)\n        self.skeleton = skeleton\n        self.n_parameters = len(self.skeleton.animated_joints)*4+3\n        self.tolerance = tolerance\n        self.max_iter = max_iter\n        self.parent_chain = parent_chain\n        self.root = root\n        self.root_offset = root_offset\n        self.child_nodes = list()\n        # self.target = None\n        # self.position = None\n        self.is_leaf = True\n        self.construct_from_skeleton(skeleton, root, tolerance, max_iter)\n\n    def construct_from_skeleton(self, skeleton, root, tolerance, max_iter):\n        \"\"\" there need to be two end effectors\"\"\"\n        children = [c.node_name for c in skeleton.nodes[root].children]\n        for c in children:\n            self.is_leaf = False\n            current_node = c\n            node_order = [self.root]\n            while current_node is not None:\n                n_children = len(skeleton.nodes[current_node].children)\n                if n_children == 1:  # append to chain\n                    child_node = skeleton.nodes[current_node].children[0].node_name\n                    # only add list to joints\n                    if not skeleton.nodes[current_node].fixed:\n                        node_order.append(current_node)# skip fixed nodes\n                    current_node = child_node\n                else:  # stop chain # split up by adding child nodes\n                    if n_children > 0:\n                        node_order.append(current_node)\n                    bones = dict()\n                    for idx, node in enumerate(node_order):\n                        child_node = None\n                        if idx+1 < len(node_order):\n                            child_node = node_order[idx + 1]\n                        bones[node] = FABRIKBone(node, child_node)\n                        if idx == 0 and self.parent_chain is None :\n                            bones[node].is_root = True\n                        else:\n                            bones[node].is_root = False\n                    parent_chain = FABRIKChain(skeleton, bones, node_order)\n                    print(\"construct node at\",self.root , current_node, node_order)\n                    node = FABRIKNode(skeleton, current_node, parent_chain, tolerance, max_iter)\n                    self.child_nodes.append(node)\n                    current_node = None\n\n    def backward_stage(self):\n        for c in self.child_nodes:\n            c.backward_stage()  # calculate backward update of children of child to start at the end effectors\n\n        if not self.is_leaf:\n            positions = [c.get_chain_root_position() for c in self.child_nodes]\n            t = np.mean(positions, axis=0)\n            #print(\"centroid\",t)\n            #print(\"no leaf\")\n        else:\n            t = self.parent_chain.target\n            #print(\"leaf\")\n\n        if self.parent_chain is not None:\n            self.parent_chain.target = t\n            if self.target_is_reachable():\n               self.parent_chain.backward()\n            else:\n                print(\"unreachable\")\n                # if unreachable orient joints to target\n                self.parent_chain.orient_to_target()\n\n    def target_is_reachable(self):\n        return self.parent_chain.target_is_reachable()\n\n    def forward_stage(self):\n        # calculate forward update of parent chain\n        if self.parent_chain is not None:\n            #if self.parent_chain.target_is_reachable():\n            self.parent_chain.forward()\n            #else:\n            #    self.parent_chain.orient_to_target()\n\n        # calculate forward update of children of child\n        for c in self.child_nodes:\n            if self.parent_chain is not None:\n                c.parent_chain.root_pos = self.parent_chain.get_end_effector_position()\n            else:\n                c.parent_chain.root_pos = self.root_pos\n            c.forward_stage()\n\n    def get_chain_root_position(self):\n        root_node = self.parent_chain.node_order[0]\n        return self.parent_chain.bones[root_node].position\n\n\n    def set_positions_from_frame(self, frame, parent_length):\n        if self.parent_chain is not None:\n            self.parent_chain.set_positions_from_frame(frame, parent_length)\n            parent_length += self.parent_chain.chain_length\n        for c in self.child_nodes:\n            c.set_positions_from_frame(frame, parent_length)\n\n    def get_error(self):\n        error = 0\n        for c in self.child_nodes:\n            error += c.get_error()\n        if self.is_leaf:\n            if self.parent_chain.target_is_reachable():\n                error += self.parent_chain.get_error()\n            else:\n                error += 0\n        return error\n\n    def solve(self):\n        iter = 0\n        distance = self.get_error()\n        while distance > self.tolerance and iter < self.max_iter:\n            self.backward_stage()\n            self.forward_stage()\n            distance = self.get_error()\n            iter += 1\n        n_out_of_reach = self.targets_out_of_reach()\n        if n_out_of_reach > 0:\n            self.orient_to_targets()\n        print(\"solved\", distance, n_out_of_reach)\n        self.print_end_effectors()\n\n    def print_end_effectors(self):\n        n_targets = 0\n        for c in self.child_nodes:\n            if c.is_leaf:\n                print(c.root, c.parent_chain.target, c.parent_chain.get_end_effector_position())\n            else:\n                c.print_end_effectors()\n        return n_targets\n\n    def targets_out_of_reach(self):\n        n_targets = 0\n        for c in self.child_nodes:\n            if c.is_leaf and not c.parent_chain.target_is_reachable():\n                n_targets+=1\n            else:\n                n_targets += c.targets_out_of_reach()\n        return n_targets\n\n    def orient_to_targets(self):\n        for c in self.child_nodes:\n            if c.is_leaf and not c.parent_chain.target_is_reachable():\n                c.parent_chain.orient_to_target()\n            else:\n                c.orient_to_targets()\n\n    def get_joint_parameters(self, frame):\n        #print(\"get joint parameters\")\n        for c in self.child_nodes:\n            print(\"from\", c.parent_chain.node_order[0], \"to\", c.parent_chain.node_order[-1])\n            global_frame = c.parent_chain.get_joint_parameters_global()\n            src = 3\n            if self.parent_chain is None:\n                animated_joints = c.parent_chain.node_order\n            else:\n                animated_joints = c.parent_chain.node_order[1:]\n            for j in animated_joints: #ignore root rotation\n                dest = self.skeleton.animated_joints.index(j)*4 +3\n                frame[dest:dest+4] = to_local_cos(self.skeleton, j, frame, global_frame[src:src+4])\n                src += 4\n            c.get_joint_parameters(frame)\n        return frame\n\n    def set_targets(self, targets):\n        #print(\"set targets\",targets)\n        if self.is_leaf:\n            if self.root in targets:\n                self.target = targets[self.root]\n                self.parent_chain.target = self.target\n                #print(\"set target\",self.root)\n            else:\n                self.target = self.parent_chain.get_end_effector_position() # keep the initial position as target for unconstrained leafs\n                self.parent_chain.target = self.target\n                print(\"set end effector position\")\n        else:\n            for c in self.child_nodes:\n                c.set_targets(targets)\n\n    def run(self, orig_frame, targets):\n        self.set_positions_from_frame(orig_frame, 0)\n        self.set_targets(targets)\n        self.solve()\n        if False:\n            frame = np.zeros(self.n_parameters)\n            self.get_joint_parameters(frame)\n        else:\n            joint_pos = dict()\n            self.get_global_positions(joint_pos)\n            next_nodes = dict()\n            self.get_next_nodes(next_nodes)\n            frame = get_global_joint_parameters_from_positions(self.skeleton, joint_pos, next_nodes)\n            frame = global_to_local_frame(self.skeleton, frame)\n            #print(\"done\")\n            #self.print_frame_parameters(frame)\n        return frame\n\n    def get_next_nodes(self, next_nodes):\n        if self.parent_chain is not None:\n            self.parent_chain.get_next_nodes(next_nodes)\n        for c in self.child_nodes:\n            c.get_next_nodes(next_nodes)\n\n    def print_frame_parameters(self, frame):\n        idx = 3\n        for n in self.skeleton.nodes:\n            if len(self.skeleton.nodes[n].children) > 0:\n                print(n, frame[idx: idx+4])\n                idx +=4\n        return\n\n    def draw(self, m,v,p, l):\n        if self.parent_chain is not None:\n            self.parent_chain.draw(m,v,p,l)\n        for c in self.child_nodes:\n            c.draw(m, v, p, l)\n\n    def get_global_positions(self, positions):\n        if self.parent_chain is not None:\n            positions.update(self.parent_chain.get_global_positions())\n        for c in self.child_nodes:\n            c.get_global_positions(positions)", "meta": {"hexsha": "b8aea92e7e47f25545e956f86a2757f59fc1867e", "size": 12667, "ext": "py", "lang": "Python", "max_stars_repo_path": "anim_utils/motion_editing/fabrik_node.py", "max_stars_repo_name": "jsprenger2/anim_utils", "max_stars_repo_head_hexsha": "d28d4384cf16af5a8c1ec482e3c7d597286933e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-02-24T06:32:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T07:36:04.000Z", "max_issues_repo_path": "anim_utils/motion_editing/fabrik_node.py", "max_issues_repo_name": "jsprenger2/anim_utils", "max_issues_repo_head_hexsha": "d28d4384cf16af5a8c1ec482e3c7d597286933e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-03-19T12:11:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T15:44:30.000Z", "max_forks_repo_path": "anim_utils/motion_editing/fabrik_node.py", "max_forks_repo_name": "jsprenger2/anim_utils", "max_forks_repo_head_hexsha": "d28d4384cf16af5a8c1ec482e3c7d597286933e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-02-24T06:35:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-28T14:26:05.000Z", "avg_line_length": 40.085443038, "max_line_length": 137, "alphanum_fraction": 0.6130891292, "include": true, "reason": "import numpy", "num_tokens": 2700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.16861980420508907}}
{"text": "#!/usr/bin/env python\n\n# Copyright (c) 2007 Carnegie Mellon University\n#\n# You may copy and modify this freely under the same terms as\n# Sphinx-III\n\n\"\"\"\nWord lattices for speech recognition.\n\nIncludes routines for loading lattices in Sphinx3 and HTK format,\nsearching them, and calculating word posterior probabilities.\n\"\"\"\n\n__author__ = \"David Huggins-Daines <dhuggins@cs.cmu.edu>\"\n__version__ = \"$Revision: 12380 $\"\n\nimport sphinxbase\nimport gzip\nimport re\nimport math\nimport os\ntry:\n    import numpy\nexcept:\n    pass\n\nLOGZERO = -10000000\n\ndef logadd(x,y):\n    \"\"\"\n    For M{x=log(a)} and M{y=log(b)}, return M{z=log(a+b)}.\n\n    @param x: M{log(a)}\n    @type x: float\n    @param y: M{log(b)}\n    @type y: float\n    @return: M{log(a+b)}\n    @rtype: float\n    \"\"\"\n    if x < y:\n        return logadd(y,x)\n    if y == LOGZERO:\n        return x\n    else:\n        return x + math.log(1 + math.exp(y-x))\n\ndef is_filler(sym):\n    \"\"\"\n    Returns true if C{sym} is a filler word.\n    @param sym: Word string to test\n    @type sym: string\n    @return: True if C{sym} is a filler word (but not <s> or </s>)\n    @rtype: boolean\n    \"\"\"\n    if sym == '<s>' or sym == '</s>': return False\n    return ((sym[0] == '<' and sym[-1] == '>') or\n            (sym[0] == '+' and sym[-1] == '+'))\n\nbasere = re.compile(r\"(?::.*)?(?:\\(\\d+\\))?$\")\ndef baseword_noclass(sym):\n    \"\"\"\n    Returns base word (no pronunciation variant or class tag) for sym.\n    \"\"\"\n    return basere.sub(\"\", sym)\n\nbasere2 = re.compile(r\"(?:\\(\\d+\\))?$\")\ndef baseword(sym):\n    \"\"\"\n    Returns base word (no pronunciation variant) for sym.\n    \"\"\"\n    return basere2.sub(\"\", sym)\n\nclass Dag(object):\n    \"\"\"\n    Directed acyclic graph representation of a phone/word lattice.\n    \"\"\"\n    class Node(object):\n        \"\"\"\n        Node in a DAG representation of a phone/word lattice.\n\n        @ivar sym: Word corresponding to this node.  All arcs out of\n                   this node represent hypothesized instances of this\n                   word starting at frame C{entry}.\n        @type sym: string\n        @ivar entry: Entry frame for this node.\n        @type entry: int\n        @ivar exits: List of arcs out of this node.\n        @type exits: list of Dag.Link\n        @ivar entries: List of arcs into this node\n        @type entries: list of Dag.Link\n        @ivar score: Viterbi (or other) score for this node, used in\n                     bestpath calculation.\n        @type score: float\n        @ivar post: Posterior probability of this node.\n        @type post: float\n        @ivar prev: Backtrace pointer for this node, used in bestpath\n                    calculation.\n        @type prev: object\n        @ivar fan: Temporary fan-in or fan-out counter used in edge traversal\n        @type fan: int\n        \"\"\"\n        __slots__ = 'sym', 'entry', 'exits', 'entries', 'score', 'post', 'prev', 'fan'\n        def __init__(self, sym, entry):\n            self.sym = sym\n            self.entry = entry\n            self.exits = []\n            self.entries = []\n            self.score = LOGZERO\n            self.post = LOGZERO\n            self.prev = None\n            self.fan = 0\n\n        def __str__(self):\n            return \"<Node: %s/%d>\" % (self.sym, self.entry)\n\n    class Link(object):\n        \"\"\"\n        Link in DAG representation of a phone/word lattice.\n\n        @ivar src: Start node for this link.\n        @type src: Dag.Node\n        @ivar dest: End node for this link.\n        @type dst: Dag.Node\n        @ivar ascr: Acoustic score for this link.\n        @type ascr: float\n        @ivar lscr: Best language model score for this link\n        @type lscr: float\n        @type lback: Best language model backoff mode for this link\n        @type lback: int\n        @ivar pscr: Dijkstra path score for this link\n        @type pscr: float\n        @ivar alpha: Joint log-probability of all paths ending in this link\n        @type alpha: float\n        @ivar beta: Conditional log-probability of all paths following this link\n        @type beta: float\n        @ivar post: Posterior log-probability of this link\n        @type post: float\n        @ivar prev: Previous link in best path\n        @type prev: Dag.Link\n        \"\"\"\n        __slots__ = ('src', 'dest', 'ascr', 'lscr', 'pscr', 'alpha', 'beta',\n                     'post', 'lback', 'prev')\n        def __init__(self, src, dest, ascr,\n                     lscr=LOGZERO, pscr=LOGZERO,\n                     alpha=LOGZERO, beta=LOGZERO,\n                     post=LOGZERO, lback=0):\n            self.src = src\n            self.dest = dest\n            self.ascr = ascr\n            self.lscr = lscr\n            self.pscr = pscr\n            self.alpha = alpha\n            self.beta = beta\n            self.post = post\n            self.lback = lback\n            self.prev = None\n\n        def __str__(self):\n            return \"<Link: %s/%d => %s/%d P = %f>\" % (self.src.sym, self.src.entry,\n                                                     self.dest.sym, self.dest.entry,\n                                                     self.post)\n\n    def __init__(self, sphinx_file=None, htk_file=None, frate=100):\n        \"\"\"\n        Construct a DAG, optionally loading contents from a file.\n\n        @param frate: Number of frames per second.  This is important\n                      when loading HTK word graphs since times in them\n                      are specified in decimal.  The default is\n                      probably okay.\n        @type frate: int\n        @param sphinx_file: Sphinx-III format word lattice file to\n                            load (optionally).\n        @type sphinx_file: string\n        @param htk_file: HTK SLF format word lattice file to\n                         load (optionally).\n        @type htk_file: string\n        \"\"\"\n        self.frate = frate\n        if sphinx_file != None:\n            self.sphinx2dag(sphinx_file)\n        elif htk_file != None:\n            self.htk2dag(htk_file)\n\n    fieldre = re.compile(r'(\\S+)=(?:\"((?:[^\\\\\"]+|\\\\.)*)\"|(\\S+))')\n    def htk2dag(self, htkfile):\n        \"\"\"Read an HTK-format lattice file to populate a DAG.\"\"\"\n        if htkfile.endswith('.gz'): # DUMB\n            fh = gzip.open(htkfile)\n        else:\n            fh = open(htkfile)\n        self.header = {}\n        self.n_frames = 0\n        state='header'\n        # Read everything\n        for spam in fh:\n            if spam.startswith('#'):\n                continue\n            fields = dict(map(lambda (x,y,z): (x, y or z),\n                              self.fieldre.findall(spam.rstrip())))\n            # Number of nodes and links\n            if 'N' in fields:\n                nnodes = int(fields['N'])\n                self.nodes = [None] * nnodes\n                nlinks = int(fields['L'])\n                self.links = [None] * nlinks\n                state = 'items'\n            elif 'NODES' in fields:\n                nnodes = int(fields['NODES'])\n                self.nodes = [None] * nnodes\n                nlinks = int(fields['LINKS'])\n                self.links = [None] * nlinks\n                state = 'items'\n            if state == 'header':\n                self.header.update(fields)\n            else:\n                # This is a node\n                if 'I' in fields:\n                    frame = int(float(fields['t']) * self.frate)\n                    node = self.Node(fields['W'], frame)\n                    self.nodes[int(fields['I'])] = node\n                    if 'p' in fields and float(fields['p']) != 0:\n                        node.post = math.log(float(fields['p']))\n                    if frame > self.n_frames:\n                        self.n_frames = frame\n                # This is a link\n                elif 'J' in fields:\n                    # Link up existing nodes\n                    fromnode = int(fields['S'])\n                    tonode = int(fields['E'])\n                    ascr = float(fields.get('a', 0))\n                    lscr = float(fields.get('n', fields.get('l', 1.0)))\n                    link = self.Link(fromnode, tonode, ascr, lscr)\n                    if 'p' in fields and float(fields['p']) != 0:\n                        link.post = math.log(float(fields['p']))\n                    self.nodes[int(fromnode)].exits.append(link)\n                        \n        # FIXME: Not sure if the first and last nodes are always the start and end?\n        if 'start' in self.header:\n            self.start = self.nodes[int(self.header['start'])]\n        else:\n            self.start = self.nodes[0]\n        if 'end' in self.header:\n            self.end = self.nodes[int(self.header['end'])]\n        else:\n            self.end = self.nodes[-1]\n        # Snap links to nodes to point to the objects themselves\n        self.snap_links()\n        # Sort nodes to be in time order\n        self.sort_nodes_forward()\n\n    def dag2htk(self, htkfile, lm=None):\n        if htkfile.endswith('.gz'): # DUMB\n            fh = gzip.open(htkfile, 'w')\n        else:\n            fh = open(htkfile, 'w')\n        # Ensure some header fields are there\n        if 'VERSION' not in self.header:\n            self.header['VERSION'] = '1.0'\n        for k,v in self.header.iteritems():\n            # Skip Sphinx stuff\n            if k[0] == '-':\n                continue\n            fh.write(\"%s=%s\\n\" % (k,v))\n        fh.write(\"N=%d\\tL=%d\\n\" % (self.n_nodes(), self.n_edges()))\n        idmap = {}\n        i = 0\n        for n in self.nodes:\n            fh.write(\"I=%d\\tt=%.2f\\tW=%s\\n\" % (i, float(n.entry) / 100, n.sym))\n            idmap[n] = i\n            i += 1\n        j = 0\n        for l in self.edges():\n            if l.lscr != LOGZERO:\n                fh.write(\"J=%d\\tS=%d\\tE=%d\\ta=%f\\tl=%f\\n\" %\n                              (j, idmap[l.src], idmap[l.dest], l.ascr, l.lscr))\n            else:\n                fh.write(\"J=%d\\tS=%d\\tE=%d\\ta=%f\\n\" %\n                              (j, idmap[l.src], idmap[l.dest], l.ascr))\n            j += 1\n\n    def dag2fst(self, fstfile, symfile=None, altpron=False):\n        fh = open(fstfile, \"w\")\n        if symfile:\n            sfh = open(symfile, \"w\")\n        idmap = {}\n        symmap = { \"<eps>\" : 0 }\n        j = 0\n        for i, n in enumerate(self.nodes):\n            idmap[n] = i\n            if altpron: sym = n.sym\n            else: sym = baseword(n.sym)\n            if n.sym not in symmap:\n                j += 1\n                symmap[n.sym] = j\n        for x in self.start.exits:\n            if altpron: sym = x.src.sym\n            else: sym = baseword(x.src.sym)\n            fh.write(\"%d %d %s %s %f\\n\" % (idmap[x.src], idmap[x.dest],\n                                        sym, sym, -x.ascr))\n        for x in self.edges():\n            if x.src == self.start:\n                continue\n            if altpron: sym = x.src.sym\n            else: sym = baseword(x.src.sym)\n            fh.write(\"%d %d %s %s %f\\n\" % (idmap[x.src], idmap[x.dest],\n                                        sym, sym, -x.ascr))\n        fh.write(\"%d 0\" % idmap[self.end])\n        fh.close()\n        if symfile:\n            for k, v in symmap.iteritems():\n                sfh.write(\"%s %d\\n\" % (k, v))\n            sfh.close()\n\n    def snap_links(self):\n        for n in self.nodes:\n            for x in n.exits:\n                x.src = self.nodes[int(x.src)]\n                x.dest = self.nodes[int(x.dest)]\n                x.dest.entries.append(x)\n\n    def sort_nodes_forward(self):\n        # Sort nodes by starting point\n        self.nodes.sort(lambda x,y: cmp(x.entry, y.entry))\n        # Sort edges by ending point\n        for n in self.nodes:\n            n.exits.sort(lambda x,y: cmp(x.dest.entry, y.dest.entry))\n\n    headre = re.compile(r'# (-\\S+) (\\S+)')\n    def sphinx2dag(self, s3file):\n        \"\"\"Read a Sphinx-III format lattice file to populate a DAG.\"\"\"\n        if s3file.endswith('.gz'): # DUMB\n            fh = gzip.open(s3file)\n        else:\n            fh = open(s3file)\n        self.header = {}\n        self.getcwd = None\n        state = 'header'\n        logbase = math.log(1.0003)\n        for spam in fh:\n            spam = spam.rstrip()\n            m = self.headre.match(spam)\n            if m:\n                arg, val = m.groups()\n                self.header[arg] = val\n                if arg == '-logbase':\n                    logbase = math.log(float(val))\n            if spam.startswith('# getcwd:'):\n                self.getcwd = spam[len('# getcwd:'):].strip()\n            if spam.startswith('#'):\n                continue\n            else:\n                fields = spam.split()\n                if fields[0] == 'Frames':\n                    self.n_frames = int(fields[1])\n                elif fields[0] == 'Nodes':\n                    state='nodes'\n                    nnodes = int(fields[1])\n                    self.nodes = [None] * nnodes\n                elif fields[0] == 'Initial':\n                    state = 'crud'\n                    self.start = self.nodes[int(fields[1])]\n                elif fields[0] == 'Final':\n                    self.end = self.nodes[int(fields[1])]\n                elif fields[0] == 'Edges':\n                    state='edges'\n                elif fields[0] == 'End':\n                    state='done'\n                else:\n                    if state == 'nodes':\n                        nodeid, word, sf, fef, lef = fields\n                        node = self.Node(word, int(sf))\n                        self.nodes[int(nodeid)] = node\n                    elif state == 'edges':\n                        fromnode, tonode, ascr = fields\n                        ascr = float(ascr) * logbase\n                        self.nodes[int(fromnode)].exits.append(\n                            self.Link(fromnode, tonode, ascr))\n        if self.getcwd == None:\n            self.getcwd = os.getcwd()\n        # Snap links to nodes to point to the objects themselves\n        self.snap_links()\n        # Sort nodes to be in time order\n        self.sort_nodes_forward()\n\n    def dag2sphinx(self, outfile, logbase=1.0003):\n        if isinstance(outfile, file):\n            fh = outfile\n        else:\n            if outfile.endswith('.gz'): # DUMB\n                fh = gzip.open(outfile, \"w\")\n            else:\n                fh = open(outfile, \"w\")\n        fh.write(\"# getcwd: %s\\n\" % self.getcwd)\n        fh.write(\"# -logbase %e\\n\" % logbase)\n        for arg, val in self.header.iteritems():\n            if arg != '-logbase':\n                fh.write(\"# %s %s\\n\" % (arg,val))\n        fh.write(\"#\\n\")\n        fh.write(\"Frames %d\\n\" % self.n_frames)\n        fh.write(\"#\\n\")\n        fh.write(\"Nodes %d (NODEID WORD STARTFRAME FIRST-ENDFRAME LAST-ENDFRAME)\\n\"\n                 % self.n_nodes())\n        links = []\n        idmap = {}\n        for i,n in enumerate(self.nodes):\n            fef = self.n_frames\n            lef = 0\n            for x in n.exits:\n                fr = x.dest.entry - 1\n                if fr > lef: lef = fr\n                if fr < fef: fef = fr\n            if fef == self.n_frames: lef = fef = self.n_frames\n            idmap[n] = i\n            fh.write(\"%d %s %d %d %d\\n\" % (i, n.sym, n.entry, fef, lef))\n        fh.write(\"#\\n\")\n        fh.write(\"Initial %d\\n\" % idmap[self.start])\n        fh.write(\"Final %d\\n\" % idmap[self.end])\n        fh.write(\"BestSegAscr 0 (NODEID ENDFRAME ASCORE)\\n#\\n\")\n        fh.write(\"Edges (FROM-NODEID TO-NODEID ASCORE)\\n\")\n        logfactor = 1./math.log(logbase)\n        for u in self.nodes:\n            for x in u.exits:\n                fh.write(\"%d %d %d\\n\" % (idmap[u], idmap[x.dest],\n                                         int(x.ascr * logfactor)))\n        fh.write(\"End\\n\")\n        fh.close()\n\n    def dag2dot(self, outfile):\n        fh = open(outfile, \"w\")\n        fh.write(\"digraph lattice {\\n\\trankdir=LR;\\n\\t\")\n        nodeid = {}\n        fh.write(\"\\tnode [shape=circle];\")\n        for i,u in enumerate(self.nodes):\n            nodeid[u] = '\"%s/%d\"' % (u.sym, u.entry)\n            if u != self.end:\n                fh.write(\" %s\" % nodeid[u])\n        fh.write(\";\\n\\tnode [shape=doublecircle]; %s;\\n\\n\" % nodeid[self.end])\n        for x in self.edges():\n            fh.write(\"\\t%s -> %s [label=\\\"%.2f\\\"];\\n\"\n                     % (nodeid[x.src], nodeid[x.dest], x.post))\n        fh.write(\"}\\n\")\n        fh.close()\n\n    def n_nodes(self):\n        \"\"\"\n        Return the number of nodes in the DAG\n        @return: Number of nodes in the DAG\n        @rtype: int\n        \"\"\"\n        return len(self.nodes)\n\n    def n_edges(self):\n        \"\"\"\n        Return the number of edges in the DAG\n        @return: Number of edges in the DAG\n        @rtype: int\n        \"\"\"\n        return sum([len(n.exits) for n in self.nodes])\n\n    def edges(self):\n        \"\"\"\n        Return an iterator over all edges in the DAG\n        \"\"\"\n        for n in self.nodes:\n            for x in n.exits:\n                yield x\n\n    def bestpath_edges(self, lm=None, start=None, end=None):\n        \"\"\"\n        Find best path through lattice over edges.\n\n        It is assumed that filler words have been bypassed before this\n        function is called.  You may also want to remove unreachable\n        nodes, as it will run faster.\n\n        This function does shortest-path search over edges rather than\n        nodes, which makes it possible to do full trigram expansion.\n        \"\"\"\n        if start == None:\n            start = self.start\n        if end == None:\n            end = self.end\n        # Find number of links into each node\n        for w in self.nodes:\n            w.fan = 0\n        for w in self.nodes:\n            if is_filler(w.sym) and w != end:\n                continue\n            for x in w.exits:\n                x.dest.fan += 1\n        # Agenda of optimally scored paths\n        Q = []\n        # Initialize agenda with path scores for all links exiting start\n        for e in start.exits:\n            if is_filler(e.dest.sym) and e.dest != end:\n                continue\n            e.lscr, e.lback = lm.score(baseword(e.dest.sym),\n                                       baseword(e.src.sym))\n            e.pscr = e.ascr + e.lscr\n            Q.append(e)\n        # Track the best link entering the end node\n        bestend = None\n        bestescr = LOGZERO\n        # Now go to work\n        nlinks = 0\n        while Q:\n            # Remove the first path in the queue\n            e = Q[0]\n            del Q[0]\n            nlinks += 1\n            # Update scores for all paths exiting e.dest\n            for f in e.dest.exits:\n                if is_filler(f.dest.sym) and f.dest != end:\n                    continue\n                lscr, lback = lm.score(baseword(f.dest.sym),\n                                       baseword(e.dest.sym),\n                                       baseword(e.src.sym))\n                pscr = e.pscr + f.ascr + lscr\n                # Update its score\n                if pscr > f.pscr:\n                    f.pscr = pscr\n                    f.lscr = lscr\n                    f.lback = lback\n                    f.prev = e\n                    if f.dest == end and f.pscr > bestescr:\n                        bestend = f\n                        bestescr = f.pscr\n            # Decrease fan-in count for destination node\n            e.dest.fan -= 1\n            if e.dest.fan == 0:\n                # If we have searched all links entering the end node,\n                # return the best one.\n                if e.dest == end:\n                    break\n                # All incoming links to e have been evaluated, so its\n                # outgoing links all have the best scores.  Insert\n                # them in the queue.\n                for f in e.dest.exits:\n                    if is_filler(f.dest.sym) and f.dest != end:\n                        continue\n                    Q.append(f)\n        #print \"Searched %d links of %d\" % (nlinks, sum([len(x.exits) for x in self.nodes]))\n        return bestend\n\n    def backtrace_edges(self, end):\n        \"\"\"\n        Return a backtrace from an end link after bestpath.\n\n        @param end: End link\n        @type end: Dag.Link\n        @return: Best path through lattice from start to end.\n        @rtype: list of Dag.Node\n        \"\"\"\n        backtrace = [end.dest]\n        while end:\n            backtrace.append(end.src)\n            end = end.prev\n        backtrace.reverse()\n        return backtrace\n\n    def bestpath(self, lm=None, start=None, end=None):\n        \"\"\"\n        Find best path through lattice using Dijkstra's algorithm.\n\n        It is assumed that filler words have been bypassed before this\n        function is called.\n\n        @param lm: Language model to use in search\n        @type lm: sphinxbase.ngram_model (or equivalent)\n        @param start: Node to start search from\n        @type start: Dag.Node\n        @param end: Node to end search at\n        @type end: Dag.Node\n        @return: Final node in search (same as C{end})\n        @rtype: Dag.Node\n        \"\"\"\n        # Reset all path scores and backpointers\n        Q = self.nodes[:]\n        for u in Q:\n            u.score = LOGZERO\n            u.prev = None\n        if start == None:\n            start = self.start\n        if end == None:\n            end = self.end\n        start.score = 0\n        while Q:\n            bestscore = LOGZERO\n            bestidx = 0\n            for i,u in enumerate(Q):\n                if is_filler(u.sym) and u != end:\n                    continue\n                if u.score > bestscore:\n                    bestidx = i\n                    bestscore = u.score\n            u = Q[bestidx]\n            del Q[bestidx]\n            #print \"Looking at %s/%d\" % (u.sym, u.entry)\n            if u == end:\n                return u\n            for x in u.exits:\n                v = x.dest\n                # Recaculate the language model score based on the\n                # best history (FIXME: This is an approximation, since\n                # there might be a higher scoring trigram?)\n                syms = [baseword(v.sym), baseword(u.sym)]\n                if u.prev:\n                    syms.append(baseword(u.prev.sym))\n                x.lscr, x.lback = lm.score(*syms)\n                x.pscr = u.score + x.ascr + x.lscr\n                #print \"Looking at link to %s/%d (%d <=> %d)\" % (v.sym, v.entry, x.pscr, v.score)\n                if x.pscr > v.score:\n                    v.score = x.pscr\n                    #print \"Prev of %s/%d now %s/%d\" % (v.sym, v.entry, u.sym, u.entry)\n                    v.prev = u\n\n    def backtrace(self, end=None):\n        \"\"\"\n        Return a backtrace from an optional end node after bestpath.\n\n        @param end: End node to backtrace from (default is final node in DAG)\n        @type end: Dag.Node\n        @return: Best path through lattice from start to end.\n        @rtype: list of Dag.Node\n        \"\"\"\n        if end == None:\n            end = self.end\n        backtrace = []\n        while end:\n            backtrace.append(end)\n            end = end.prev\n        backtrace.reverse()\n        return backtrace\n\n    def node_range(self, start, end):\n        \"\"\"Return all nodes starting in a certain time range.\"\"\"\n        return [n for n in self.nodes\n                if n.entry >= start\n                and n.entry < end]\n\n    def edge_slice(self, time):\n        \"\"\"Return all edges active at a certain time point.\"\"\"\n        return self.edge_range(time, time)\n\n    def edge_range(self, start, end):\n        \"\"\"Return all edges active in a certain time range.\"\"\"\n        return [e for e in self.edges()\n                if e.src.entry <= end\n                and e.dest.entry > start]\n\n    def traverse_depth(self, start=None):\n        \"\"\"Depth-first traversal of DAG nodes\"\"\"\n        if start == None:\n            start = self.start\n        # Initialize the agenda (set of root nodes)\n        roots = [start]\n        # Keep a table of already seen nodes\n        seen = {start:1}\n        # Repeatedly pop the first one off of the agenda and push\n        # all of its successors\n        while roots:\n            r = roots.pop()\n            for x in r.exits:\n                if x.dest not in seen:\n                    roots.append(x.dest)\n                    seen[x.dest] = 1\n            yield r\n\n    def traverse_breadth(self, start=None):\n        \"\"\"Breadth-first traversal of DAG nodes\"\"\"\n        if start == None:\n            start = self.start\n        # Initialize the agenda (set of active nodes)\n        roots = [start]\n        # Keep a table of already seen nodes\n        seen = {start:1}\n        # Repeatedly pop the first one off of the agenda and shift\n        # all of its successors\n        while roots:\n            r = roots.pop()\n            for x in r.exits:\n                if x.dest not in seen:\n                    roots.insert(0, x.dest)\n                    seen[x.dest] = 1\n            yield r\n\n    def reverse_breadth(self, end=None):\n        \"\"\"Breadth-first reverse traversal of DAG nodes\"\"\"\n        if end == None:\n            end = self.end\n        # Initialize the agenda (set of active nodes)\n        roots = [end]\n        # Keep a table of already seen nodes\n        seen = {end:1}\n        # Repeatedly pop the first one off of the agenda and shift\n        # all of its successors\n        while roots:\n            r = roots.pop()\n            for v in r.entries:\n                if v.src not in seen:\n                    roots.insert(0, v.src)\n                seen[v.src] = 1\n            yield r\n\n    def update_link(self, src, dest, ascr):\n        \"\"\"Add a link from src to dest if none exists, or update the\n        acoustic score if one does and ascr is better.\"\"\"\n        for x in src.exits:\n            if x.dest == dest:\n                if ascr > x.ascr:\n                    x.ascr = ascr\n                # Found a link, return\n                return x.ascr\n        link = self.Link(src, dest, ascr)\n        src.exits.append(link)\n        dest.entries.append(link)\n\n    def bypass_fillers(self, lm=None, silprob=0.1, fillprob=0.1, remove=False):\n        \"\"\"Add links to bypass filler nodes.\"\"\"\n        if lm:\n            silpen = math.log(silprob) * lm.lw + math.log(lm.wip)\n            fillpen = math.log(fillprob) * lm.lw + math.log(lm.wip)\n        else:\n            silpen = math.log(silprob)\n            fillpen = math.log(fillprob)\n        def fill_score(link):\n            if link.dest.sym == '<sil>':\n                return link.ascr + silpen\n            else:\n                return link.ascr + fillpen\n        # Do transitive closure on filler nodes\n        for n in self.nodes:\n            if is_filler(n.sym):\n                continue\n            # Traverse the outgoing filler links until all non-fillers\n            # are reached.\n            agenda = []\n            leaves = []\n            for nx in n.exits:\n                if is_filler(nx.dest.sym) and nx.dest != self.end:\n                    fscr = fill_score(nx)\n                    agenda.append((nx, fscr))\n            while len(agenda):\n                link, fscr = agenda.pop()\n                for nx in link.dest.exits:\n                    if is_filler(nx.dest.sym) and nx.dest != self.end:\n                        fscr2 = fill_score(nx)\n                        agenda.append((nx, fscr + fscr2))\n                    else:\n                        self.update_link(n, nx.dest, fscr + nx.ascr)\n        # Remove filler nodes if requested\n        if remove:\n            for n in self.nodes:\n                if is_filler(n.sym):\n                    for x in n.entries:\n                        x.src.exits.remove(x)\n                    for x in n.exits:\n                        x.dest.entries.remove(x)\n            self.remove_unreachable()\n\n    def remove_unreachable(self):\n        \"\"\"Remove unreachable nodes and dangling edges.\"\"\"\n        # It is supposed to be the case that all nodes are reachable\n        # from the start, but this is not true!\n        for w in self.nodes:\n            w.score = 0\n        for w in self.traverse_breadth():\n            w.score = 42\n        # Mark reachable nodes from the end\n        for w in self.reverse_breadth():\n            w.score += 27\n        # Mark deleted nodes and start, end node\n        for w in self.nodes:\n            if w == self.start or w == self.end:\n                w.score = 69\n            elif w.entries == [] and w.exits == []:\n                w.score = 0\n        # Find and remove unreachable ones\n        begone = {}\n        for i, w in enumerate(self.nodes):\n            if w.score != 69:\n                begone[w] = 1\n                #print \"Removing node %s\" % w\n                self.nodes[i] = None\n        self.nodes = [w for w in self.nodes if w != None]\n        # Remove links to unreachable nodes\n        for w in self.nodes:\n            newexits = []\n            for x in w.exits:\n                if x.dest in begone:\n                    pass\n                else:\n                    newexits.append(x)\n            w.exits = newexits\n            newentries = []\n            for x in w.entries:\n                if x.src in begone:\n                    pass\n                else:\n                    newentries.append(x)\n            w.entries = newentries\n\n    def traverse_edges_topo(self, start=None, end=None):\n        \"\"\"\n        Traverse edges in topological order (ensuring that all\n        predecessors to a given edge have been traversed before that\n        edge).\n        \"\"\"\n        for w in self.nodes:\n            w.fan = 0\n        for x in self.edges():\n            x.dest.fan += 1\n        if start == None: start = self.start\n        if end == None: end = self.end\n        # Agenda of closed edges\n        Q = start.exits[:]\n        while Q:\n            e = Q[0]\n            del Q[0]\n            yield e\n            e.dest.fan -= 1\n            if e.dest.fan == 0:\n                if e.dest == end:\n                    break\n                Q.extend(e.dest.exits)\n            \n    def reverse_edges_topo(self, start=None, end=None):\n        \"\"\"\n        Traverse edges in reverse topological order (ensuring that all\n        successors to a given edge have been traversed before that\n        edge).\n        \"\"\"\n        for w in self.nodes:\n            w.fan = 0\n        for x in self.edges():\n            x.src.fan += 1\n        if start == None: start = self.start\n        if end == None: end = self.end\n        # Agenda of closed edges\n        Q = end.entries[:]\n        while Q:\n            e = Q[0]\n            del Q[0]\n            yield e\n            e.src.fan -= 1\n            if e.src.fan == 0:\n                if e.src == start:\n                    break\n                Q.extend(e.src.entries)\n            \n    def forward(self, lm=None, lw=1.0, aw=1.0):\n        \"\"\"\n        Compute forward variable for all arcs in the lattice.\n\n        @param lm: Language model to use in computation\n        @type lm: sphinxbase.ngram_model (or equivalent)\n        \"\"\"\n        for wx in self.traverse_edges_topo():\n            # This is alpha_t(w)\n            wx.alpha = LOGZERO\n            # If wx.src has no predecessors the previous alpha is 1.0\n            if len(wx.src.entries) == 0:\n                wx.alpha = wx.ascr * aw\n            # For each predecessor node to wx.src\n            for vx in wx.src.entries:\n                # Get unscaled language model score P(w|v) (bigrams only for now...)\n                if lm:\n                    lscr = lm.prob([baseword(wx.src.sym),\n                                    baseword(vx.src.sym)]) * lw\n                else:\n                    lscr = 0\n                # Accumulate alpha for this arc\n                wx.alpha = logadd(wx.alpha, vx.alpha + lscr + wx.ascr * aw)\n\n    def backward(self, lm=None, lw=1.0, aw=1.0):\n        \"\"\"\n        Compute backward variable for all arcs in the lattice.\n\n        @param lm: Language model to use in computation\n        @type lm: sphinxbase.ngram_model.NGramModel (or equivalent)\n        \"\"\"\n        for vx in self.reverse_edges_topo():\n            # Beta for arcs into </s> = 1.0\n            if vx.dest == self.end:\n                beta = 0\n            else:\n                beta = LOGZERO\n                # Get unscaled language model probability P(w|v) (bigrams only for now...)\n                if lm:\n                    lscr = lm.prob([baseword(vx.dest.sym),\n                                    baseword(vx.src.sym)]) * lw\n                else:\n                    lscr = 0\n                # For each outgoing arc from vx.dest\n                for wx in vx.dest.exits:\n                    # Accumulate beta for this arc\n                    beta = logadd(beta, wx.beta + lscr + wx.ascr * aw)\n            # Update beta for this arc\n            vx.beta = logadd(vx.beta, beta)\n\n    def posterior(self, lm=None, lw=1.0, aw=1.0):\n        \"\"\"\n        Compute arc posterior probabilities.\n\n        @param lm: Language model to use in computation\n        @type lm: sphinxbase.ngram_model.NGramModel (or equivalent)\n        \"\"\"\n        # Clear alphas, betas, and posteriors\n        for w in self.nodes:\n            for wx in w.exits:\n                wx.alpha = wx.beta = wx.post = LOGZERO\n        # Run forward and backward\n        self.forward(lm, lw, aw)\n        self.backward(lm, lw, aw)\n        # Sum over alpha for arcs entering the end node to get normalizer\n        norm = LOGZERO\n        for vx in self.end.entries:\n            norm = logadd(norm, vx.alpha)\n        # Iterate over all arcs and normalize\n        for w in self.nodes:\n            w.post = LOGZERO\n            for wx in w.exits:\n                wx.post = wx.alpha + wx.beta - norm\n                w.post = logadd(w.post, wx.post)\n\n    def posterior_prune(self, threshold=-10.):\n        \"\"\"\n        Prune arcs (and resulting unreachable nodes) based on\n        posterior probability.\n        \"\"\"\n        for x in self.traverse_edges_topo():\n            if x.post < threshold:\n                #print \"Removing link %s\" % x\n                x.src.exits.remove(x)\n                x.dest.entries.remove(x)\n        self.remove_unreachable()\n\n    def minimum_error(self, ref):\n        \"\"\"\n        Find the minimum word error rate path through lattice,\n        returning the number of errors and an alignment.\n        @return: Tuple of (error-count, alignment of (hyp, ref) pairs)\n        @rtype: (int, list(string, string))\n        \"\"\"\n        # Initialize the alignment matrix\n        align_matrix = numpy.ones((len(ref),len(self.nodes)), 'i') * 999999999\n        # And the backpointer matrix\n        bp_matrix = numpy.zeros((len(ref),len(self.nodes)), 'O')\n        # Remove filler nodes from the reference\n        ref = filter(lambda x: not is_filler(x), ref)\n        # Remove unreachable nodes\n        self.remove_unreachable()\n        # Figure out the minimum distance to each node from the start\n        # of the lattice, and construct a node to ID mapping\n        nodeid = {}\n        for i,u in enumerate(self.nodes):\n            u.score = 999999999\n            nodeid[u] = i\n        self.start.score = 1\n        for u in self.nodes:\n            if is_filler(u.sym):\n                continue\n            for x in u.exits:\n                dist = u.score + 1\n                if dist < x.dest.score:\n                    x.dest.score = dist\n        def find_pred(ii, jj):\n            bestscore = 999999999\n            bestp = -1\n            if len(self.nodes[jj].entries) == 0:\n                return bestp, bestscore\n            for e in self.nodes[jj].entries:\n                k = nodeid[e.src]\n                if align_matrix[ii,k] < bestscore:\n                    bestp = k\n                    bestscore = align_matrix[ii,k]\n            return bestp, bestscore\n        # Now fill in the alignment matrix\n        for i, w in enumerate(ref):\n            for j, u in enumerate(self.nodes):\n                # Insertion = cost(w, prev(u)) + 1\n                if u == self.start: # start node\n                    bestp = -1\n                    inscost = i + 2 # Distance from start of ref\n                else:\n                    # Find best predecessor in the same reference position\n                    bestp, bestscore = find_pred(i, j)\n                    inscost = align_matrix[i,bestp] + 1\n                # Deletion  = cost(prev(w), u) + 1\n                if i == 0: # start symbol\n                    delcost = u.score + 1 # Distance from start of hyp\n                else:\n                    delcost = align_matrix[i-1,j] + 1\n                # Substitution = cost(prev(w), prev(u)) + (w != u)\n                if i == 0 and bestp == -1: # Start node, start of ref\n                    subcost = int(baseword_noclass(w) != baseword_noclass(u.sym))\n                elif i == 0: # Start of ref\n                    subcost = (self.nodes[bestp].score\n                               + int(baseword_noclass(w) != baseword_noclass(u.sym)))\n                elif bestp == -1: # Start node\n                    subcost = i - 1 + int(baseword_noclass(w) != baseword_noclass(u.sym))\n                else:\n                    # Find best predecessor in the previous reference position\n                    bestp, bestscore = find_pred(i-1, j)\n                    subcost = (align_matrix[i-1,bestp]\n                               + int(baseword_noclass(w) != baseword_noclass(u.sym)))\n                align_matrix[i,j] = min(subcost, inscost, delcost)\n                # Now find the argmin\n                if align_matrix[i,j] == subcost:\n                    bp_matrix[i,j] = (i-1, bestp)\n                elif align_matrix[i,j] == inscost:\n                    bp_matrix[i,j] = (i, bestp)\n                else:\n                    bp_matrix[i,j] = (i-1, j)\n        # Find last node's index\n        last = nodeid[self.end]\n        # Backtrace to get an alignment\n        i = len(ref)-1\n        j = last\n        bt = []\n        while True:\n            ip,jp = bp_matrix[i,j]\n            if ip == i: # Insertion\n                bt.append(('**INS**', '*%s*' % baseword_noclass(self.nodes[j].sym)))\n            elif jp == j: # Deletion\n                bt.append(('*%s' % ref[i], '**DEL**'))\n            else:\n                if ref[i] == baseword_noclass(self.nodes[j].sym):\n                    bt.append((ref[i], baseword_noclass(self.nodes[j].sym)))\n                else:\n                    bt.append((ref[i], '*%s*' % baseword_noclass(self.nodes[j].sym)))\n            # If we consume both ref and hyp, we are done\n            if ip == -1 and jp == -1:\n                break\n            # If we hit the beginning of the ref, fill with insertions\n            if ip == -1:\n                while True:\n                    bt.append(('**INS**', baseword_noclass(self.nodes[jp].sym)))\n                    bestp, bestscore = find_pred(i,jp)\n                    if bestp == -1:\n                        break\n                    jp = bestp\n                break\n            # If we hit the beginning of the hyp, fill with deletions\n            if jp == -1:\n                while ip >= 0:\n                    bt.append((ref[ip], '**DEL**'))\n                    ip = ip - 1\n                break\n            # Follow the pointer\n            i,j = ip,jp\n        bt.reverse()\n        return align_matrix[len(ref)-1,last], bt\n\n    def dt_forward(self, aw=1.0):\n        \"\"\"\n        Compute forward variable for all arcs in the lattice.\n        @param lm: Language model to use in computation\n        @type lm: sphinxbase.ngram_model (or equivalent)\n        \"\"\"\n        for wx in self.traverse_edges_topo():\n            # This is alpha_t(w)\n            wx.alpha = LOGZERO\n            # If wx.src has no predecessors the previous alpha is 1.0\n            if len(wx.src.entries) == 0:\n                wx.alpha = wx.ascr * aw\n            # use unigram lm score from each edge\n            lscr = wx.lscr\n            # For each predecessor node to wx.src\n            for vx in wx.src.entries:\n                # Accumulate alpha for this arc\n                wx.alpha = logadd(wx.alpha, vx.alpha + lscr + wx.ascr * aw)\n    \n    def dt_backward(self, aw=1.0):\n        \"\"\"\n        Compute backward variable for all arcs in the lattice.\n        @param lm: Language model to use in computation\n        @type lm: sphinxbase.ngram_model.NGramModel (or equivalent)\n        \"\"\"\n        for vx in self.reverse_edges_topo():\n            # Beta for arcs into </s> = 1.0\n            if vx.dest == self.end:\n                beta = 0\n            else:\n                beta = LOGZERO\n                # For each outgoing arc from vx.dest\n                for wx in vx.dest.exits:\n                    # use unigram lm score from each edge\n                    lscr = wx.lscr\n                    # Accumulate beta for this arc\n                    beta = logadd(beta, wx.beta + lscr + wx.ascr * aw)\n            # Update beta for this arc\n            vx.beta = logadd(vx.beta, beta)\n\n    def dt_posterior(self, aw=1.0):\n        \"\"\"\n        Compute arc posterior probabilities.\n        @param lm: Language model to use in computation\n        @type lm: sphinxbase.ngram_model.NGramModel (or equivalent)\n        \"\"\"\n        # Clear alphas, betas, and posteriors\n        for w in self.nodes:\n            for wx in w.exits:\n                wx.alpha = wx.beta = wx.post = LOGZERO\n        # Run forward and backward\n        self.dt_forward(aw)\n        self.dt_backward(aw)\n        # Sum over alpha for arcs entering the end node to get normalizer\n        norm = LOGZERO\n        for vx in self.end.entries:\n            norm = logadd(norm, vx.alpha)\n        # Iterate over all arcs and normalize\n        for w in self.nodes:\n            w.post = LOGZERO\n            for wx in w.exits:\n                wx.post = wx.alpha + wx.beta - norm\n                w.post = logadd(w.post, wx.post)\n\n    def forward_edge_prune(self, beam=1.0e-50):\n        # prune exist edges which has very small posterior probability\n        logbeam = math.log(beam)\n\tfor n in self.nodes:\n            if n != self.start and n != self.end:\n                newexits =[]\n                bestpost = LOGZERO\n                for e in n.exits:\n                    if e.post > bestpost:\n                        bestpost = e.post\n                for e in n.exits:\n                    if e.post > bestpost + logbeam:\n                        newexits.append(e)\n                    elif e.dest == self.end:\n                        newexits.append(e)\n                n.exits = newexits\n\n    def backward_edge_prune(self, beam=1.0e-50):\n        # prune entry edges which has very small posterior probability\n        logbeam = math.log(beam)\n\tfor n in self.nodes:\n            if n != self.start and n != self.end:\n                newentries = []\n                bestpost = LOGZERO\n                for e in n.entries:\n                    if e.post > bestpost:\n                        bestpost = e.post\n                for e in n.entries:\n                    if e.post > bestpost + logbeam:\n                        newentries.append(e)\n                    elif e.src == self.start:\n                        newentries.append(e)\n                n.entries = newentries\n\n    def post_node_prune(self, beam=1.0e-10):\n        # prune nodes which has the same word and similar entry and exist points\n        #  but with very small posterior probability\n        seen = {}\n        win = 10\n\tlogbeam = math.log(beam)\n        for n in self.nodes:\n            if n != self.start and n != self.end and n not in seen:\n                seen[n] = 1\n                start = n.entry - win\n                end = n.entry + win\n                if start < 1:\n                    start = 1\n                if end > self.end.entry - 1:\n                    end  = self.end.entry - 1\n                align = self.node_range(start, end)\n\n                similar = []\n                for m in align:\n                    if m.sym == n.sym:\n                        seen[m] = 1\n                        if m != self.start and m != self.end:\n                            similar.append(m)\n\n                bestpost = LOGZERO\n                for m in similar:\n                    if m.post > bestpost:\n                        bestpost = m.post\n                for m in similar:\n                    if m.post < bestpost + logbeam:\n                        m.entries = []\n                        m.exits = []\n\n    def edges_unigram_score(self, lm, lw=1.0):\n        # assign unigram lm score to edge\n        for n in self.nodes:\n            for e in n.exits:\n                e.lscr = lm.prob([baseword(e.src.sym)]) * lw\n\n", "meta": {"hexsha": "1ed921e0abd297f79a72eacdef3138ae71402907", "size": 44284, "ext": "py", "lang": "Python", "max_stars_repo_path": "speech_recognition/cmusphinx-code/sphinxtrain/python/cmusphinx/lattice.py", "max_stars_repo_name": "Ohara124c41/TUB-MSc_Thesis", "max_stars_repo_head_hexsha": "b1a2d5dc9c0c589a39019126cf7a5cc775baa288", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-12-05T01:29:52.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-05T01:29:52.000Z", "max_issues_repo_path": "speech_recognition/cmusphinx-code/sphinxtrain/python/cmusphinx/lattice.py", "max_issues_repo_name": "Ohara124c41/TUB-MSc_Thesis", "max_issues_repo_head_hexsha": "b1a2d5dc9c0c589a39019126cf7a5cc775baa288", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "speech_recognition/cmusphinx-code/sphinxtrain/python/cmusphinx/lattice.py", "max_forks_repo_name": "Ohara124c41/TUB-MSc_Thesis", "max_forks_repo_head_hexsha": "b1a2d5dc9c0c589a39019126cf7a5cc775baa288", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-24T17:26:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-24T17:26:59.000Z", "avg_line_length": 37.0887772194, "max_line_length": 97, "alphanum_fraction": 0.4850961973, "include": true, "reason": "import numpy", "num_tokens": 10485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.16861980077497737}}
{"text": "\"\"\"\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nimport argparse\nimport cPickle as pickle\nimport json\nfrom numpy import array, random\nimport numpy as np\nfrom scipy import stats\nimport aggregate, crystal, rotator, generator\n\n\ndef generate_aggregate(monomer_generator,N=5,align=True):\n\n    align_rot = rotator.PartialAligningRotator(exp_sig_deg=40)\n    uniform_rot = rotator.UniformRotator()\n\n    agg = [monomer_generator() for i in xrange(N)]\n\n    while len(agg) > 1:\n        r = array([((a.extent[0][1]-a.extent[0][0])+(a.extent[1][1]-a.extent[1][0]))/4.0 for a in agg])\n        m_r = np.sqrt(array([a.X.shape[0] for a in agg])/r)\n        r_mat = (np.tile(r,(len(agg),1)).T+r)**2\n        mr_mat = abs(np.tile(m_r,(len(agg),1)).T - m_r)\n        p_mat = r_mat * mr_mat\n        p_mat /= p_mat.max()\n        collision = False\n        while not collision:\n            \n            i = random.randint(len(agg))\n            j = random.randint(len(agg))\n            rnd = random.rand()\n            if rnd < p_mat[i][j]:\n                print i, j\n                agg_top = agg[i] if (m_r[i] > m_r[j]) else agg[j]\n                agg_btm = agg[i] if (m_r[i] <= m_r[j]) else agg[j]\n                agg_btm.rotate(uniform_rot)\n                collision = agg_top.add_particle(particle=agg_btm.X,required=True,pen_depth=80e-6)\n                if collision:\n                    if align:\n                        agg_top.align()\n                        agg_top.rotate(align_rot)\n                    else:\n                        agg_top.rotate(uniform_rot)\n                    agg.pop(i if (m_r[i] <= m_r[j]) else j)\n        \n            \n\n    if align:\n        agg[0].align()\n        agg[0].rotate(align_rot)\n    agg[0].rotate(rotator.HorizontalRotator())\n\n    return agg[0]\n\n\ndef gen_monomer(psd=\"monodisperse\", size=1.0, min_size=1e-3, max_size=10,\n    mono_type=\"dendrite\", grid_res=0.02e-3, rimed=False):\n        \n    def make_cry(D):\n        if mono_type==\"dendrite\":\n            grid = pickle.load(file(\"dendrite_grid.dat\"))\n            cry = crystal.Dendrite(D, hex_grid=grid)\n        elif mono_type==\"plate\":\n            cry = crystal.Plate(D)            \n        elif mono_type==\"needle\":\n            cry = crystal.Needle(D)\n        elif mono_type==\"rosette\":\n            cry = crystal.Rosette(D)\n        elif mono_type==\"bullet\":\n            cry = crystal.Bullet(D)\n        elif mono_type==\"spheroid\":\n            cry = crystal.Spheroid(D,0.6)\n        return cry\n                \n    rot = rotator.UniformRotator()            \n    \n    def gen():\n        if psd==\"monodisperse\":\n            D = size\n        elif psd==\"exponential\":\n            psd_f = stats.expon(scale=size)\n            D=max_size+1\n            while (D<min_size) or (D>max_size):\n                D = psd_f.rvs()\n        \n        cry = make_cry(D)\n        \n        gen = generator.MonodisperseGenerator(cry, rot, grid_res)\n        if rimed:\n            agg = aggregate.RimedAggregate(gen)\n        else:\n            agg = aggregate.Aggregate(gen)\n        return agg\n    \n    return gen\n\n\ndef visualize_crystal(mono_type):\n    gen = gen_monomer(mono_type=mono_type, size=2e-3, grid_res=40e-6)\n    cry = gen()\n    cry.align()\n    cry.visualize(bgcolor=(1,1,1))\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--psd', required=True)\n    parser.add_argument('--mono_type', required=True)\n    parser.add_argument('--mono_size', type=float, required=True)\n    parser.add_argument('--mono_min_size', type=float, default=None)\n    parser.add_argument('--mono_max_size', type=float, default=None)\n    parser.add_argument('--num_monos', type=int, required=True)\n    parser.add_argument('--output', type=argparse.FileType('w'), required=True)\n    parser.add_argument('--grid_res', type=float, required=True)\n    args = parser.parse_args()\n\n    mono_generator = gen_monomer(psd=args.psd, size=args.mono_size, \n        min_size=args.mono_min_size, max_size=args.mono_max_size,\n        mono_type=args.mono_type, grid_res=args.grid_res)\n        \n    agg = generate_aggregate(mono_generator,N=args.num_monos,align=True)\n\n    meta = {\"psd\": args.psd, \"mono_type\": args.mono_type, \n        \"mono_size\": args.mono_size, \"mono_min_size\": args.mono_min_size,\n        \"mono_max_size\": args.mono_max_size, \"num_monos\": args.num_monos,\n        \"grid_res\": args.grid_res, \"file_name\": args.output.name,\n        \"extent\": agg.extent}\n    np.savetxt(args.output, agg.grid(), fmt=\"%d\")\n    json.dump(meta, file(args.output.name+\".meta\", 'w'))\n", "meta": {"hexsha": "96ca8d4645f3440843b27065078184286caa481a", "size": 5507, "ext": "py", "lang": "Python", "max_stars_repo_path": "aggregation/tripfreq_runs.py", "max_stars_repo_name": "ChristophSiewert/aggregation", "max_stars_repo_head_hexsha": "f0c538024208fb86d7c1171825e31f43dd56416a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aggregation/tripfreq_runs.py", "max_issues_repo_name": "ChristophSiewert/aggregation", "max_issues_repo_head_hexsha": "f0c538024208fb86d7c1171825e31f43dd56416a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aggregation/tripfreq_runs.py", "max_forks_repo_name": "ChristophSiewert/aggregation", "max_forks_repo_head_hexsha": "f0c538024208fb86d7c1171825e31f43dd56416a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.462585034, "max_line_length": 103, "alphanum_fraction": 0.6232068277, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 1373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3345894478883556, "lm_q1q2_score": 0.16860168738486064}}
{"text": "#! /usr/bin/env python\n#adam: this is an older version of cosmos_sim.py from ~/wtgpipeline, which probably won't be needed anymore, but should be saved anyway (just in case)\n# I've incorporated two of the changes cause I basically knew they were right:\n#\t(1) ID/id is an input for more functions now\n#\t(2) we don't append redshifts to a list anymore (since it was leading to inconsistent lengths) \n# I kept cosmos_sim.py.svn_diff in case it's needed for reference later on.\nimport re, cPickle\nimport numpy as np\nimport numpy\nimport ldac, astropy, astropy.io.fits as pyfits\nimport shearprofile as sp\nimport nfwmodel_sim as nfwsim, matching\nimport scipy.stats as stats\nimport nfwutils\n#adam-old# import voigt_tools\nimport pickle\nfl=open('/u/ki/awright/COSMOS_2017/bad_ids.pkl','rb')\nbad_ids=pickle.load(fl)\nfl.close()\nfl=open('/u/ki/awright/COSMOS_2017/gone_ids.pkl','rb')\ngone_ids=pickle.load(fl)\nfl.close()\n\n\n\n############################################\n\npixscale = 0.2\n\ndef __DEFAULT_SHAPE_DISTRO__(g, binvals, sigma):\n    size = len(binvals)\n    return g + sigma*np.random.standard_normal(size)\n\n\n###########################################\n\ndef voigtdistro(g, binvals, sigma, gamma):\n\n    size = len(binvals)\n\n    return g + voigt_tools.voigtSamples(sigma, gamma, size)\n\n#########\n\ndef voigtDistro2(g, binvals, alpha, sigma1, gamma1, sigma2, gamma2):\n    size = len(binvals)\n    distro1 = np.random.uniform(size=size) < alpha\n    distro2 = np.logical_not(distro1)\n\n    gs = np.zeros(size)\n    gs[distro1] = g[distro1]+voigt_tools.voigtSamples(sigma1, gamma1, len(gs[distro1]))\n    gs[distro2] = g[distro2]+voigt_tools.voigtSamples(sigma2, gamma2, len(gs[distro2]))\n\n    return gs\n\n\n############################################\n\ndef matchById(smallcat, bigcat, smallid='SeqNr', bigid=None):\n    if bigid is None:\n        bigid = smallid\n\n    seqnr = {}\n    for i, x in enumerate(bigcat[bigid]):\n        seqnr[x] = i\n        \n    keep = []\n    for x in smallcat[smallid]:\n        keep.append(seqnr[x])\n            \n    keep = np.array(keep)\n    matched = bigcat.filter(keep)\n    return matched\n\n#############################################\n\ndef commonSubset(cat1, cat2, id1 = 'SeqNr', id2 = 'SeqNr'):\n\n    ids1 = {}\n    for i, x in enumerate(cat1[id1]):\n        ids1[x] = i\n\n    ids2 = {}\n    for i, x in enumerate(cat2[id2]):\n        ids2[x] = i\n\n    keep1 = []\n    keep2 = []\n\n    for id, index in ids1.iteritems():\n        if id in ids2:\n            keep1.append(index)\n            keep2.append(ids2[id])\n\n    keep1 = np.array(keep1)\n    keep2 = np.array(keep2)\n\n    return cat1.filter(keep1), cat2.filter(keep2)\n    \n\n\n#############################################\n\ndef SphereDist(p1, p2):\n    '''assumes already in radians, first coord is RA, second is dec'''\n    dTheta = p1 - p2\n    dLat = dTheta[:,1] #dec\n    dLong = dTheta[:,0] #ra\n\n    dist = 2*np.arcsin(np.sqrt(np.sin(dLat/2)**2 + np.cos(p1[:,1])*np.cos(p2[1])*np.sin(dLong/2)**2))\n\n    return dist\n\n\ndef extractField(cat, size, snratio, maxradii = 4000, center = None, ra='ra', dec = 'dec', id = 'id', pixscale = pixscale):\n    # extracts objects directly from bpz catalog w/ respect to position, from a random center position\n    # uses periodic boundary conditions\n    # fieldsize is (x,y) with units of pixels. Why? Cause I'm evil -- and lazy\n\n\n\n    min_ra = np.min(cat[ra])\n    max_ra = np.max(cat[ra])\n    delta_ra = max_ra - min_ra\n    min_dec = np.min(cat[dec])\n    max_dec = np.max(cat[dec])\n    delta_dec = max_dec - min_dec\n    \n    if center is None:\n        center_x = np.random.uniform(min_ra, max_ra)\n        center_y = np.random.uniform(min_dec, max_dec)\n        center = [center_x, center_y]\n        center = np.array(center)*(np.pi / 180.)\n\n\n    ids = []\n    ras = []\n    decs = []\n    sizes = []\n    snratios = []\n    for i in [-1, 0, 1]:\n        for j in [ -1, 0, 1]:\n            ids.extend(cat[id])\n            ras.extend(cat[ra] + (i * delta_ra))\n            decs.extend(cat[dec] + (j * delta_dec))\n            sizes.extend(size)\n            snratios.extend(snratio)\n\n    ids = np.array(ids)\n    points = np.pi * np.column_stack([ras, decs]) / 180.\n    sizes = np.array(sizes)\n    snratios = np.array(snratios)\n\n    dr_rad = SphereDist(points, center)\n    dr_pix = 3600.*180. * dr_rad / (np.pi * pixscale)\n\n    inField = dr_pix < maxradii\n\n    cols = [pyfits.Column(name = 'SeqNr', format = 'J', array = ids[inField]),\n            pyfits.Column(name = 'r_pix', format = 'E', array = dr_pix[inField]),\n            pyfits.Column(name = 'size', format = 'E', array = sizes[inField]),\n            pyfits.Column(name = 'snratio', format = 'E', array = snratios[inField])]\n    cols = ldac.LDACCat(pyfits.BinTableHDU.from_columns(pyfits.ColDefs(cols)))\n    cols.hdu.header['EXTNAME']= 'OBJECTS'\n    cols.hdu.header['CENTERX']= center[0]\n    cols.hdu.header['CENTERY']= center[1]\n\n    return cols\n\n##########################\n\ndef bootstrapField(cat, size, snratio, galdensity = 150, maxradii = 4000, id = 'id', pixscale = pixscale, ngals = None):\n    #creates bootstrap realizations with galaxies randomly distributed throughout the field.\n    #galdensity is numbers / square arcmin\n    #adam-new# maybe default id should be 'SeqNr' or 'id' instead of 'ID'?\n    maxRdist = maxradii / np.sqrt(2.)\n    area = 4*(maxRdist * pixscale / 60)**2\n\n    if ngals is None and galdensity is not None:\n\n\n        ngals = galdensity * area\n\n    else:\n\n        galdensity = float(ngals) / area\n\n\n    xs = np.random.uniform(0, maxRdist, ngals)\n    ys = np.random.uniform(0, maxRdist, ngals)\n    dr_pix = np.sqrt(xs**2 + ys**2)\n\n    bootstrap = np.random.randint(0, len(cat), ngals)\n\n    ids = cat[id][bootstrap]\n    sizes = size[bootstrap]\n    snratios = snratio[bootstrap]\n\n\n    cols = [pyfits.Column(name = 'SeqNr', format = 'J', array = ids),\n            pyfits.Column(name = 'r_pix', format = 'E', array = dr_pix),\n            pyfits.Column(name = 'size', format = 'E', array = sizes),\n            pyfits.Column(name = 'snratio', format = 'E', array = snratios)]\n    cols = ldac.LDACCat(pyfits.BinTableHDU.from_columns(pyfits.ColDefs(cols)))\n    cols.hdu.header['EXTNAME']= 'OBJECTS'\n    cols.hdu.header['GDENSITY']= galdensity\n    cols.hdu.header['CENTERX']= 0.\n    cols.hdu.header['CENTERY']= 0.\n\n    return cols\n\n    \n\n##########################\n\ndef pick_snratio(sizes, size_distro, sn_distro, size_bin = 0.2):\n\n    size_cat = matching.Catalog(sizes, np.zeros(len(sizes)), np.arange(len(sizes)))\n    size_distro_cat = matching.Catalog(size_distro, \n                                       np.zeros(len(size_distro)), \n                                       np.arange(len(size_distro)))\n                                                  \n    trie = matching.buildTrie(size_distro_cat)\n\n    snratios = np.zeros_like(sizes)\n\n    for i in np.arange(len(sizes)):\n\n        matches = np.array(trie.findNeighbors(np.array((0, sizes[i])), size_bin), dtype=np.int32)\n\n        available_sns = sn_distro[matches]\n        navailable = len(available_sns)\n\n        if navailable == 0:\n            deltaSize = np.abs(size_distro - sizes[i])\n            available_sns = sn_distro[deltaSize == min(deltaSize)]\n            navailable = len(available_sns)\n\n        snratios[i] = available_sns[np.random.randint(0, navailable, 1)]\n\n    return snratios\n\n\n####################################            \n    \n\ndef createCutoutSuite(zs, \n                      massrange, \n                      goodbpz, \n                      sizes, \n                      snratios,\n                      outputdir, \n                      simcats = None,\n                      sourcecat = None,\n                      shape_distro = __DEFAULT_SHAPE_DISTRO__,\n                      shape_distro_kw_sets = 100*[{'sigma' : 0.25}],\n                      idcol = 'ID'):\n\n    if simcats is None:\n        simcats = []\n        for i in range(len(shape_distro_kw_sets)):\n            simsource = extractField(sourcecat, sizes, snratios)\n            simcats.append(simsource)\n\n\n    for curz in zs:\n        print 'z = %2.2f' % curz\n        for cur_mass in massrange:\n            print '\\tmass = %2.2f' % (cur_mass / 1e14)\n\t    print 'adam-look: range(len(simcats)), simcats, shape_distro_kw_sets=',range(len(simcats)), simcats, shape_distro_kw_sets\n            for i, simsource, kw_set in zip(range(len(simcats)), simcats, shape_distro_kw_sets):\n\n                print '\\t\\t%d' % i\n\n\t\t#adam-old# base = '%s/cutout_z=%1.2f_mass=%2.2f_%d' % (outputdir, curz, cur_mass / 1e14, i)\n                base = '%s/cutout_z_drawn_z=%1.2f_mass=%2.2f_%d' % (outputdir, curz, cur_mass / 1e14, i)\n\n                #cur_rs = nfwutils.rscaleConstM(cur_mass, 4.0, curz, 500)\n                cur_rs = nfwutils.RsMassInsideR(cur_mass, 4.0, curz, 1.5)\n\n\n\t\t#adam-old# simsource, simbpz = commonSubset(simsource, goodbpz,id2=\"ID\")\n\t\tsimbpz=goodbpz\n\n                simcat, momento = createCatalog(simbpz,\n                                                simsource['size'],\n                                                simsource['snratio'],\n                                                4.0, \n                                                cur_rs,\n                                                curz,\n                                                ngals = None,\n                                                shape_distro = shape_distro,\n                                                shape_distro_kw = kw_set, \n                                                radii_pix = simsource['r_pix'])\n\n    \n\n                simcat.saveas('%s.cat' % base, overwrite=True)\n                output = open('%s.momento' % base, 'wb')\n                cPickle.dump(momento, output, -1)\n                output.close()\n\n\n#########################\n\n\n\n        \n        \n\n\n\n##########################\n### cs.createCutoutSuite(zs, rsrange, mcosmos30, bpz, ones(len(bpz)), ones(len(bpz)), pdzrange, pdzs, '/u/ki/dapple/nfs12/cosmos/simulations/2010-11-16/extended', cs.__DEFAULT_SHAPE_DISTRO__, 100*[{'sigma' : 0.25}])\n\n###cs.createCutoutSuite(zs, rsrange, mcosmos30, bpz, ones(len(bpz)), ones(len(bpz)), pdzrange, pdzs, '/u/ki/dapple/nfs12/cosmos/simulations/2010-11-16/extended', shape_distro_kw_sets = 100*[{'sigma' : 0.25}])\n\n#def createSimSuite(zs, rsrange, goodbpz, pdzrange, pdzs, outputdir):\n#\n#\n#    for curz in zs:\n#        print 'z = %2.2f' % curz\n#        for cur_rs in rsrange:\n#            print '\\trs = %2.2f' % cur_rs\n#            for i in np.arange(15):\n#                print '\\t\\t%d' % i\n#                simcat, momento = createCatalog(goodbpz, \n#                                                4.0, \n#                                                cur_rs,\n#                                                curz, \n#                                                21300, \n#                                                shape_distro_args = [0.25],\n#                                                maxpix = 4000)\n#                \n#                base = '%s/sim_z=%1.2f_rs=%1.2f_%d' % (outputdir, curz, cur_rs, i)\n#                simpdz = pdzfile_utils.associatePDZ(pdzs, simcat['z_id'])\n#                simcat.saveas('%s.cat' % base, overwrite=True)\n#                output = open('%s.momento' % base, 'wb')\n#                cPickle.dump(momento, output)\n#                output.close()\n#                output = open('%s.pdz' % base, 'wb')\n#                cPickle.dump((pdzrange, simpdz), output)\n#                output.close()\n#\n#\n#\n###########################    \n\n\ndef createCatalog(bpz,\n                  bpz_sizes,\n                  bpz_snratios,\n                  concentration, \n                  scale_radius, \n                  zcluster, \n                  ngals,\n                  shape_distro = __DEFAULT_SHAPE_DISTRO__, \n                  shape_distro_args = [], \n                  shape_distro_kw = {}, \n                  maxpix=5000, \n                  radii_pix = None,\n                  contam = None,\n                  contam_args = [],\n                  contam_kw = {},\n                  idcol = 'ID'):\n\n    # ngals == None -> no bootstrapping\n    # bpz is ldac bpz output\n\n    momento = {'concentration'   : concentration,   \n               'scale_radius'    : scale_radius,    \n               'zcluster'        : zcluster,        \n               'ngals'           : ngals,          \n               'shape_distro'    : shape_distro.func_name,\n               'shape_distro_args' : shape_distro_args,\n               'shape_distro_kw' : shape_distro_kw,\n               'maxpix'          : maxpix,\n               'radii_pix'        : radii_pix\n               }\n\n    bootstrap = True\n    if ngals == None:\n        bootstrap = False\n        ngals = len(bpz)\n\n    if radii_pix is None:\n        x_pix = np.random.uniform(0, maxpix, ngals)\n        y_pix = np.random.uniform(0, maxpix, ngals)\n        radii_pix = np.sqrt(x_pix**2 + y_pix**2)\n    \n    radii_mpc = radii_pix * pixscale * (1./3600.) * (np.pi / 180. ) * sp.angulardist(zcluster)\n\n    chosenZs = bpz\n    chosenSizes = bpz_sizes\n    chosenSNratios = bpz_snratios\n    if bootstrap:\n        indices = np.random.randint(0, len(bpz), ngals)\n        chosenZs = bpz.filter(indices)\n        chosenSizes = bpz_sizes[indices]\n        chosenSNratios = bpz_snratios[indices]\n\n    print \"adam-look: running createCatalog in cosmos_sim.py\"\n    z_id=chosenZs['SeqNr']\n    z_drawn=-1*np.ones(len(chosenZs))\n\n    #adam: toggle from using single point zp_best to drawing a random sample from the p(z) dist'n\n    zchoice='dist'\n    zchoice='point'\n    if zchoice=='point':\n\t    zkey = 'zp_best'\n\t    if zkey not in chosenZs:\n\t\tzkey = 'BPZ_Z_S'\n    \n    #adam-old# change from `true_z = chosenZs[zkey]` to z_drawn from p(z)\n    fl=open('/nfs/slac/kipac/fs1/u/awright/COSMOS_2017/id2pz_cdf.pkl','rb')\n    id2pz_cdf=pickle.load(fl)\n    fl.close()\n    zbins=numpy.arange(0,6.01,.01)\n    print '!!!', len(z_drawn)\n    for id_indx, id in enumerate(z_id):\n\t    try:\n\t    \t    cdf=id2pz_cdf[id]\n\t    except:\n\t\t    if id in gone_ids:\n\t\t\t    print \"adam-look: gone id \",id\n\t\t\t    continue\n\t\t    else:\n\t\t\t    raise\n\t    x=numpy.random.rand()\n\t    try:\n\t    \tzval=(zbins[cdf<=x])[-1]\n\t    except:\n\t\t    if id in bad_ids:\n\t\t\t    print \"adam-look: bad id \",id\n\t\t    \t    continue\n\t\t    else:\n\t\t\t    raise\n            z_drawn[id_indx] = zval\n    \n    good_draws = z_drawn > -1\n    z_drawn = z_drawn[good_draws]\n    radii_pix = radii_pix[good_draws]\n    radii_mpc = radii_mpc[good_draws]\n    chosenZs = chosenZs.filter(good_draws)\n    chosenSizes = chosenSizes[good_draws]\n    chosenSNratios = chosenSNratios[good_draws]\n    ngals = len(z_drawn)\n    \n    true_shears, true_gamma, true_kappa = nfwsim.create_nfwmodel_shapedata(concentration, scale_radius,\n                                                   zcluster, ngals, \n                                                   z_drawn, \n                                                   radii_mpc)\n\n    true_beta = nfwutils.beta_s(z_drawn, zcluster)\n\n\n\n    ghats = shape_distro(true_shears, np.column_stack([chosenSizes, chosenSNratios]), \n                         *shape_distro_args, **shape_distro_kw)\n\n\n    \n    cols = [ pyfits.Column(name = 'Seqnr', format = 'J', array = np.arange(ngals)), \n             pyfits.Column(name = 'r_pix', format = 'E', array = radii_pix), \n             pyfits.Column(name = 'r_mpc', format = 'E', array = radii_mpc),\n             pyfits.Column(name = 'z', format = 'E', array = z_drawn),\n             pyfits.Column(name = 'z_id', format = 'J', array = chosenZs[idcol]),\n             pyfits.Column(name = 'ghats', format = 'E', array = ghats),\n             pyfits.Column(name = 'true_shear', format = 'E', array = true_shears),\n             pyfits.Column(name = 'true_z', format = 'E', array = z_drawn),\n             pyfits.Column(name = 'true_beta', format = 'E', array = true_beta),\n             pyfits.Column(name = 'true_gamma', format = 'E', array = true_gamma),\n             pyfits.Column(name = 'true_kappa', format = 'E', array = true_kappa)]\n\n\n    \n    simcat = pyfits.BinTableHDU.from_columns(pyfits.ColDefs(cols))\n    simcat.header['EXTNAME']= 'OBJECTS'\n    simcat.header['concen']= concentration\n    simcat.header['r_s']= scale_radius\n    simcat.header['z']= zcluster\n\n\n    return ldac.LDACCat(simcat), momento\n\n\n################################\n\ndef addPDZNoise(actualZs, zsigma, pdf_range = np.arange(0, 5.0, 0.01)):\n\n    ngals = len(actualZs)\n\n    baseZs = actualZs  + zsigma*np.random.standard_normal(size=ngals)\n    baseZs[baseZs < 0] = 0.\n\n    probs = []\n    for z in pdf_range:\n        probs.append( stats.norm.pdf( z, baseZs, zsigma) )\n\n    pdz = np.column_stack(probs)\n\n    extended_pdf_range = np.arange(-2, 0, 0.01)\n    probs = []\n    for z in extended_pdf_range:\n        probs.append( stats.norm.pdf( z, baseZs, zsigma) )\n\n    extended_pdz = np.column_stack(probs)\n    out_of_bounds_prob = extended_pdz.sum(axis=-1)\n    \n    pdz[:,0] = pdz[:,0] + out_of_bounds_prob\n\n\n    return pdz\n    \n\n\n#################################################\n\n\ndef addContamination(sourcebpz, source_snratio, source_size, simcat, simpdz, r500, zcluster, f500 = 0.04, pixscale = pixscale, refcat = '/u/ki/dapple/nfs12/cosmos/cosmos2.cat',\n                     shape_distro = __DEFAULT_SHAPE_DISTRO__, \n                     shape_distro_args = [], \n                     shape_distro_kw = {}):\n\n    refcat = ldac.openObjectFile(refcat).matchById(sourcebpz, selfid = 'id')\n\n    r_max = max(simcat['r_pix'])\n    area = np.pi*(r_max*pixscale / 60.)**2\n    n_back = float(len(simcat)) / area\n\n    x,y = nfwsim.stdcontamination((0,0), pixscale, f500, n_back, r500, zcluster)\n\n    r_pix = np.sqrt(x**2 + y**2)\n\n    r_mpc = r_pix * pixscale * (1./3600.) * (np.pi / 180. ) * sp.angulardist(zcluster)\n\n    z = zcluster*np.ones(len(r_pix))\n\n    toKeepAvailable = {}\n    for id in sourcebpz['SeqNr']:\n        toKeepAvailable[id] = True\n    for id in simcat['z_id']:\n        toKeepAvailable[id] = False\n\n\n    zkey = 'zp_best'\n    if zkey not in sourcebpz:\n        zkey = 'BPZ_Z_S'\n    \n\n    toKeep = np.logical_and(np.logical_and(np.array([toKeepAvailable[id] for id in sourcebpz['SeqNr']]),\n                                           refcat['mod_gal'] > 8),\n                            np.logical_and(sourcebpz[zkey] > (zcluster - 0.05),\n                                           sourcebpz[zkey] < (zcluster + 0.05)))\n\n\n    #toKeep = np.logical_and(np.array([toKeepAvailable[id] for id in sourcebpz['SeqNr']]),\n    #                        np.logical_and(sourcebpz[zkey] > (zcluster - 0.05),\n    #                                       sourcebpz[zkey] < (zcluster + 0.05)))\n    #\n    #\n    \n    availablebpz = sourcebpz.filter(toKeep)\n    available_snratio = source_snratio[toKeep]\n    available_size = source_size[toKeep]\n\n    selected = np.random.randint(0, len(availablebpz), len(r_pix))\n    selectedbpz = availablebpz.filter(selected)\n    selected_snratio = available_snratio[selected]\n    selected_size = available_size[selected]\n    \n    \n    col_collection = {'Seqnr' : -selectedbpz['SeqNr'],\n            'r_pix' : r_pix,\n            'r_mpc' : r_mpc,\n            'z' : z,\n            'z_id' : selectedbpz['SeqNr'],\n            'ghats' : shape_distro(np.zeros(len(selectedbpz)), \n                                   np.column_stack([selected_size, selected_snratio]), \n                                   *shape_distro_args, **shape_distro_kw),\n            'true_shear' : np.zeros_like(r_pix),\n            'true_z' : zcluster*np.ones_like(r_pix),\n            'true_beta' : np.zeros_like(r_pix),\n            'true_gamma' : np.zeros_like(r_pix),\n            'true_kappa' : np.zeros_like(r_pix)\n            }\n            \n\n\n    cols = []\n    for name, arr in col_collection.iteritems():\n        if name == 'SeqNr':\n            col = pyfits.Column(name = name, format = 'J', array = arr)\n        else:\n            col = pyfits.Column(name = name, format = 'E', array = arr)\n        cols.append(col)\n\n\n    contamcat = ldac.LDACCat(pyfits.BinTableHDU.from_columns(pyfits.ColDefs(cols)))\n\n\n    finalcat = simcat.append(contamcat)\n\n\n    return finalcat\n    \n", "meta": {"hexsha": "be96b264d594b7fbd42a34b1f2260719861ff884", "size": 20068, "ext": "py", "lang": "Python", "max_stars_repo_path": "non_essentials/cosmos_sim_old.py", "max_stars_repo_name": "deapplegate/wtgpipeline", "max_stars_repo_head_hexsha": "9693e8562022cc97bf5a96427e22965e1a5e8497", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-15T04:01:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-15T04:01:19.000Z", "max_issues_repo_path": "non_essentials/cosmos_sim_old.py", "max_issues_repo_name": "deapplegate/wtgpipeline", "max_issues_repo_head_hexsha": "9693e8562022cc97bf5a96427e22965e1a5e8497", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2017-12-11T00:11:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-09T17:05:16.000Z", "max_forks_repo_path": "non_essentials/cosmos_sim_old.py", "max_forks_repo_name": "deapplegate/wtgpipeline", "max_forks_repo_head_hexsha": "9693e8562022cc97bf5a96427e22965e1a5e8497", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-08-15T21:19:11.000Z", "max_forks_repo_forks_event_max_datetime": "2017-10-12T00:36:35.000Z", "avg_line_length": 33.0609555189, "max_line_length": 215, "alphanum_fraction": 0.5449471796, "include": true, "reason": "import numpy,import scipy", "num_tokens": 5440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.168601677354352}}
{"text": "\"\"\"\n \" License:\n \" -----------------------------------------------------------------------------\n \" Copyright (c) 2018, Ratnajit Mukherjee.\n \" All rights reserved.\n \"\n \" Redistribution and use in source and binary forms, with or without\n \" modification, are permitted provided that the following conditions are met:\n \"\n \" 1. Redistributions of source code must retain the above copyright notice,\n \"    this list of conditions and the following disclaimer.\n \"\n \" 2. Redistributions in binary form must reproduce the above copyright notice,\n \"    this list of conditions and the following disclaimer in the documentation\n \"    and/or other materials provided with the distribution.\n \"\n \" 3. Neither the name of the copyright holder nor the names of its contributors\n \"    may be used to endorse or promote products derived from this software\n \"    without specific prior written permission.\n \"\n \" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n \" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n \" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n \" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n \" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n \" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n \" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n \" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n \" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n \" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n \" POSSIBILITY OF SUCH DAMAGE.\n \" -----------------------------------------------------------------------------\n \"\n \" Description: A VGG like network to extract facial expressions from the FER 2013 dataset and learn\n                6 primary emotions (NOTE: we are merging 'anger' and 'disgust' into a single dataset\n                due to lack of examples\n\n                ====================================================================================\n                Network Description:\n                1) 8 Convolution layers (grouped as 2 x 4)\n                2) 4 Maxpool layers\n                3) 2 Densely connected layers\n                4) 1 output layer with 6 classes\n                ====================================================================================\n \" Author: Ratnajit Mukherjee, ratnajitmukherjee@gmail.com\n \" Date: July 2018\n\"\"\"\n# various imports to build the Neural Net\nfrom keras.layers import Conv2D, Dense, Flatten, Dropout, BatchNormalization, MaxPooling2D\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.utils import plot_model\nfrom keras.models import Sequential\nfrom keras import backend as K\nimport argparse\nimport numpy as np\n\n\ndef Emonet(num_classes):\n    # use sequential model to build a VGG like network\n    emonet = Sequential()\n\n    \"\"\"\n    Convolution and Maxpool layers: Block 1\n    \"\"\"\n    # Conv Layer 1:48x48x32\n    emonet.add(Conv2D(filters=32, kernel_size=3, padding='same', activation='linear', input_shape=(48, 48, 1)))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n\n    # Conv Layer 2:48x48x32\n    emonet.add(Conv2D(filters=32, kernel_size=3, padding='same', activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n\n    # MaxPool layer: 1\n    emonet.add(MaxPooling2D(pool_size=(2, 2), padding='same'))\n    emonet.add(Dropout(0.3))\n\n    \"\"\"\n    Convolution and Maxpool layers: Block 2\n    \"\"\"\n    # Conv Layer 3:24x24x64\n    emonet.add(Conv2D(filters=64, kernel_size=3, padding='same', activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n\n    # Conv Layer 4:24x24x64\n    emonet.add(Conv2D(filters=64, kernel_size=3, padding='same', activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n\n    # MaxPool layer: 2\n    emonet.add(MaxPooling2D(pool_size=(2, 2), padding='same'))\n    emonet.add(Dropout(0.3))\n\n    \"\"\"\n    Convolution and Maxpool layers: Block 3\n    \"\"\"\n    # Conv Layer 5:12x12x128\n    emonet.add(Conv2D(filters=128, kernel_size=3, padding='same', activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n\n    # Conv Layer 6:12x12x128\n    emonet.add(Conv2D(filters=128, kernel_size=3, padding='same', activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n\n    # MaxPool layer: 3\n    emonet.add(MaxPooling2D(pool_size=(2, 2), padding='same'))\n    emonet.add(Dropout(0.25))\n\n    \"\"\"\n    Convolution and Maxpool layers: Block 4\n    \"\"\"\n    # Conv Layer 7:6x6x256\n    emonet.add(Conv2D(filters=256, kernel_size=3, padding='same', activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n\n    # Conv Layer 8:6x6x256\n    emonet.add(Conv2D(filters=256, kernel_size=3, padding='same', activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n\n    # MaxPool layer: 4\n    emonet.add(MaxPooling2D(pool_size=(2, 2), padding='same'))\n    emonet.add(Dropout(0.25))\n\n    # Flatten\n    emonet.add(Flatten())\n\n    # Dense layer 1:\n    emonet.add(Dense(256, activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n    emonet.add(Dropout(0.5))\n\n    # Dense layer 2:\n    emonet.add(Dense(256, activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n    emonet.add(Dropout(0.5))\n\n    # Output layer\n    emonet.add(Dense(num_classes, activation='softmax'))\n\n    trainable_count = int(\n        np.sum([K.count_params(p) for p in set(emonet.trainable_weights)]))\n    non_trainable_count = int(\n        np.sum([K.count_params(p) for p in set(emonet.non_trainable_weights)]))\n\n    # network summary\n    print('\\n\\n---<summary>---')\n    print('\\n Layers: \\n\\tConvolution2D: {0}\\n\\tMaxPooling2D: {1}\\n\\tFully Connected Layers: {2}'.format(8, 4, 2))\n    print('\\n Total params: {:,}'.format(trainable_count + non_trainable_count))\n    print('\\n Trainable params: {:,}'.format(trainable_count))\n    print('\\n Non-trainable params: {:,}'.format(non_trainable_count))\n    print('\\n\\n---</summary>---')\n    return emonet\n\n\ndef Emonet_extend(num_classes):\n    \"\"\"\n    This model is optional and bigger than the previous one. Practically, this model is less useful than the first one\n    therefore is not called by the application. Use only for experimental purposes\n    \"\"\"\n    emonet = Sequential()\n\n    \"\"\"\n    Convolution and Maxpool layers: Block 1\n    \"\"\"\n    # Conv Layer 1:48x48x32\n    emonet.add(Conv2D(filters=64, kernel_size=3, padding='same', activation='linear', input_shape=(48, 48, 1)))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n\n    # Conv Layer 2:48x48x32\n    emonet.add(Conv2D(filters=64, kernel_size=3, padding='same', activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n\n    # MaxPool layer: 1\n    emonet.add(MaxPooling2D(pool_size=(2, 2), padding='same'))\n    emonet.add(Dropout(0.2))\n\n    \"\"\"\n    Convolution and Maxpool layers: Block 2\n    \"\"\"\n    # Conv Layer 3:24x24x64\n    emonet.add(Conv2D(filters=128, kernel_size=3, padding='same', activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n\n    # Conv Layer 4:24x24x64\n    emonet.add(Conv2D(filters=128, kernel_size=3, padding='same', activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n\n    # Conv Layer 5:24x24x64\n    emonet.add(Conv2D(filters=128, kernel_size=3, padding='same', activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n\n    # MaxPool layer: 2\n    emonet.add(MaxPooling2D(pool_size=(2, 2), padding='same'))\n    emonet.add(Dropout(0.2))\n\n    \"\"\"\n    Convolution and Maxpool layers: Block 3\n    \"\"\"\n    # Conv Layer 6:12x12x256\n    emonet.add(Conv2D(filters=256, kernel_size=3, padding='same', activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n\n    # Conv Layer 7:12x12x256\n    emonet.add(Conv2D(filters=256, kernel_size=3, padding='same', activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n\n    # Conv Layer 8:12x12x256\n    emonet.add(Conv2D(filters=256, kernel_size=3, padding='same', activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n\n    # Conv Layer 9:12x12x256\n    emonet.add(Conv2D(filters=256, kernel_size=3, padding='same', activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n\n    # MaxPool layer: 3\n    emonet.add(MaxPooling2D(pool_size=(2, 2), padding='same'))\n    emonet.add(Dropout(0.3))\n\n    \"\"\"\n    Convolution and Maxpool layers: Block 4\n    \"\"\"\n    # Conv Layer 9:6x6x256\n    emonet.add(Conv2D(filters=512, kernel_size=3, padding='same', activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n\n    # Conv Layer 10:6x6x256\n    emonet.add(Conv2D(filters=512, kernel_size=3, padding='same', activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n\n    # Conv Layer 11:6x6x256\n    emonet.add(Conv2D(filters=512, kernel_size=3, padding='same', activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n\n    # Conv Layer 12:6x6x256\n    emonet.add(Conv2D(filters=512, kernel_size=3, padding='same', activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n\n    # MaxPool layer: 4\n    emonet.add(MaxPooling2D(pool_size=(2, 2), padding='same'))\n    emonet.add(Dropout(0.2))\n\n    # Flatten\n    emonet.add(Flatten())\n\n    # Dense layer 1:\n    emonet.add(Dense(2048, activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n    emonet.add(Dropout(0.5))\n\n    # Dense layer 2:\n    emonet.add(Dense(2048, activation='linear'))\n    emonet.add(LeakyReLU(alpha=0.3))\n    emonet.add(BatchNormalization(axis=-1))\n    emonet.add(Dropout(0.5))\n\n    # Output layer\n    emonet.add(Dense(num_classes, activation='softmax'))\n\n    trainable_count = int(\n        np.sum([K.count_params(p) for p in set(emonet.trainable_weights)]))\n    non_trainable_count = int(\n        np.sum([K.count_params(p) for p in set(emonet.non_trainable_weights)]))\n\n    # network summary\n    print('\\n\\n---<summary>---')\n    print('\\n Layers: \\n\\tConvolution2D: {0}\\n\\tMaxPooling2D: {1}\\n\\tFully Connected Layers: {2}'.format(8, 4, 2))\n    print('\\n Total params: {:,}'.format(trainable_count + non_trainable_count))\n    print('\\n Trainable params: {:,}'.format(trainable_count))\n    print('\\n Non-trainable params: {:,}'.format(non_trainable_count))\n    print('\\n\\n---</summary>---')\n    return emonet\n\n\n\"\"\"\nUsing a main function for testing individual modules\nUncomment for testing purposes\nComment when testing is successful \n\"\"\"\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"-n\", \"--num_emotions\", help=\"Number of emotions in the output layer of the VGG like NN\",\n                        type=int, default=7, required=True)\n    parser.add_argument(\"-o\", \"--out_img\", type=str, help=\"Output path to dump the Network Architecture\")\n    args = parser.parse_args()\n\n    num_emotions = args.num_emotions\n    out_img_path = args.out_img\n\n    if num_emotions is not 6 and num_emotions is not 7:\n        print(\"\\n Number of emotions options are: \\n 6 (for merging anger and disgust) \"\n              \"OR \\n 7 (for all the emotions in the dataset\")\n        exit(0)\n    else:\n        emonet = Emonet(num_classes=num_emotions)\n        emonet.summary()\n\n    if out_img_path is not None:\n        plot_model(model=emonet, to_file=out_img_path, show_shapes=True, show_layer_names=True)\n", "meta": {"hexsha": "5dab1a725f0a2a4a8424f97e1c6a53e424f0c6b4", "size": 12127, "ext": "py", "lang": "Python", "max_stars_repo_path": "VGGNet.py", "max_stars_repo_name": "ratnajitmukherjee/EmotionClassification_FER2013", "max_stars_repo_head_hexsha": "29bda4caaea26b40f75aae253ec292eb846a93df", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2018-10-25T09:53:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T02:55:36.000Z", "max_issues_repo_path": "VGGNet.py", "max_issues_repo_name": "ratnajitmukherjee/EmotionClassification_FER2013", "max_issues_repo_head_hexsha": "29bda4caaea26b40f75aae253ec292eb846a93df", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VGGNet.py", "max_forks_repo_name": "ratnajitmukherjee/EmotionClassification_FER2013", "max_forks_repo_head_hexsha": "29bda4caaea26b40f75aae253ec292eb846a93df", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-08-23T14:09:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-12T04:09:47.000Z", "avg_line_length": 37.6614906832, "max_line_length": 118, "alphanum_fraction": 0.6668590748, "include": true, "reason": "import numpy", "num_tokens": 3314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604272, "lm_q2_score": 0.3040416623541847, "lm_q1q2_score": 0.168582121892866}}
{"text": "# This software is open source software available under the BSD-3 license.\n#\n# Copyright (c) 2020 Triad National Security, LLC. All rights reserved.\n# Copyright (c) 2020 Lawrence Livermore National Security, LLC. All rights\n# reserved.\n# Copyright (c) 2020 UT-Battelle, LLC. All rights reserved.\n#\n# Additional copyright and license information can be found in the LICENSE file\n# distributed with this code, or at\n# https://raw.githubusercontent.com/MPAS-Dev/MPAS-Analysis/master/LICENSE\n\"\"\"\nFunctions for creating climatologies from monthly time series data\n\"\"\"\n# Authors\n# -------\n# Xylar Asay-Davis\n\nfrom __future__ import absolute_import, division, print_function, \\\n    unicode_literals\n\nimport xarray as xr\nimport os\nimport numpy\nfrom tempfile import TemporaryDirectory\n\nfrom pyremap import Remapper, LatLonGridDescriptor, ProjectionGridDescriptor\n\nfrom mpas_analysis.shared.constants import constants\n\nfrom mpas_analysis.shared.timekeeping.utility import days_to_datetime\n\nfrom mpas_analysis.shared.io.utility import build_config_full_path, \\\n    make_directories, fingerprint_generator\nfrom mpas_analysis.shared.io import write_netcdf\n\nfrom mpas_analysis.shared.climatology.comparison_descriptors import \\\n    get_comparison_descriptor\n\n\ndef get_remapper(config, sourceDescriptor, comparisonDescriptor,\n                 mappingFilePrefix, method, logger=None):  # {{{\n    \"\"\"\n    Given config options and descriptions of the source and comparison grids,\n    returns a ``pyremap.Remapper`` object that can be used to remap from source\n    files or data sets to corresponding data sets on the comparison grid.\n\n    If necessary, creates the mapping file containing weights and indices\n    needed to perform remapping.\n\n    Parameters\n    ----------\n    config :  instance of ``MpasAnalysisConfigParser``\n        Contains configuration options\n\n    sourceDescriptor : ``MeshDescriptor`` subclass object\n        A description of the source mesh or grid\n\n    comparisonDescriptor : ``MeshDescriptor`` subclass object\n        A description of the comparison grid\n\n    mappingFilePrefix : str\n        A prefix to be prepended to the mapping file name\n\n    method : {'bilinear', 'neareststod', 'conserve'}\n        The method of interpolation used.\n\n    logger : ``logging.Logger``, optional\n        A logger to which ncclimo output should be redirected\n\n    Returns\n    -------\n    remapper : ``pyremap.Remapper`` object\n        A remapper that can be used to remap files or data sets from the source\n        grid or mesh to the comparison grid.\n    \"\"\"\n    # Authors\n    # -------\n    # Xylar Asay-Davis\n\n    mappingFileName = None\n\n    if not _matches_comparison(sourceDescriptor, comparisonDescriptor):\n        # we need to remap because the grids don't match\n\n        mappingBaseName = '{}_{}_to_{}_{}.nc'.format(\n            mappingFilePrefix,\n            sourceDescriptor.meshName,\n            comparisonDescriptor.meshName,\n            method)\n\n        tryCustom = config.get('diagnostics', 'customDirectory') != 'none'\n        if tryCustom:\n            # first see if mapping files are in the custom directory\n            mappingSubdirectory = build_config_full_path(\n                config, 'diagnostics', 'mappingSubdirectory',\n                baseDirectoryOption='customDirectory')\n\n            mappingFileName = '{}/{}'.format(mappingSubdirectory,\n                                         mappingBaseName)\n        if not tryCustom or not os.path.exists(mappingFileName):\n            # second see if mapping files are in the base directory\n\n            mappingSubdirectory = build_config_full_path(\n                config, 'diagnostics', 'mappingSubdirectory',\n                baseDirectoryOption='base_path')\n\n            mappingFileName = '{}/{}'.format(mappingSubdirectory,\n                                             mappingBaseName)\n\n        if not os.path.exists(mappingFileName):\n            # we don't have a mapping file yet, so get ready to create one\n            # in the output subfolder if needed\n            mappingSubdirectory = \\\n                build_config_full_path(config, 'output',\n                                       'mappingSubdirectory')\n            make_directories(mappingSubdirectory)\n            mappingFileName = '{}/{}'.format(mappingSubdirectory,\n                                             mappingBaseName)\n\n    remapper = Remapper(sourceDescriptor, comparisonDescriptor,\n                        mappingFileName)\n\n    mpiTasks = config.getWithDefault('execute', 'mapMpiTasks', 1)\n    esmf_parallel_exec = config.get('execute', 'mapParallelExec')\n    if esmf_parallel_exec == 'None':\n        esmf_parallel_exec = None\n\n    mappingSubdirectory = \\\n        build_config_full_path(config, 'output',\n                               'mappingSubdirectory')\n    make_directories(mappingSubdirectory)\n    with TemporaryDirectory(dir=mappingSubdirectory) as tempdir:\n        remapper.build_mapping_file(method=method, logger=logger,\n                                    mpiTasks=mpiTasks, tempdir=tempdir,\n                                    esmf_parallel_exec=esmf_parallel_exec)\n\n    return remapper  # }}}\n\n\ndef compute_monthly_climatology(ds, calendar=None, maskVaries=True):  # {{{\n    \"\"\"\n    Compute monthly climatologies from a data set.  The mean is weighted but\n    the number of days in each month of the data set, ignoring values masked\n    out with NaNs.  If the month coordinate is not present, a data array\n    ``month`` will be added based on ``Time`` and the provided calendar.\n\n    Parameters\n    ----------\n    ds : xarray.Dataset or xarray.DataArray\n        A data set with a ``Time`` coordinate expressed as days since\n        0001-01-01 or ``month`` coordinate\n\n    calendar : {'gregorian', 'gregorian_noleap'}, optional\n        The name of one of the calendars supported by MPAS cores, used to\n        determine ``month`` from ``Time`` coordinate, so must be supplied if\n        ``ds`` does not already have a ``month`` coordinate or data array\n\n    maskVaries : bool, optional\n        If the mask (where variables in ``ds`` are ``NaN``) varies with time.\n        If not, the weighted average does not need make extra effort to account\n        for the mask.  Most MPAS fields will have masks that don't vary in\n        time, whereas observations may sometimes be present only at some\n        times and not at others, requiring ``maskVaries = True``.\n\n    Returns\n    -------\n    climatology : object of same type as ``ds``\n        A data set without the ``'Time'`` coordinate containing the mean\n        of ds over all months in monthValues, weighted by the number of days\n        in each month.\n    \"\"\"\n    # Authors\n    # -------\n    # Xylar Asay-Davis\n\n    def compute_one_month_climatology(ds):\n        monthValues = list(ds.month.values)\n        return compute_climatology(ds, monthValues, calendar, maskVaries)\n\n    ds = add_years_months_days_in_month(ds, calendar)\n\n    monthlyClimatology = \\\n        ds.groupby('month').map(compute_one_month_climatology)\n\n    return monthlyClimatology  # }}}\n\n\ndef compute_climatology(ds, monthValues, calendar=None,\n                        maskVaries=True):  # {{{\n    \"\"\"\n    Compute a monthly, seasonal or annual climatology data set from a data\n    set.  The mean is weighted but the number of days in each month of\n    the data set, ignoring values masked out with NaNs.  If the month\n    coordinate is not present, a data array ``month`` will be added based\n    on ``Time`` and the provided calendar.\n\n    Parameters\n    ----------\n    ds : xarray.Dataset or xarray.DataArray\n        A data set with a ``Time`` coordinate expressed as days since\n        0001-01-01 or ``month`` coordinate\n\n    monthValues : int or array-like of ints\n        A single month or an array of months to be averaged together\n\n    calendar : {'gregorian', 'gregorian_noleap'}, optional\n        The name of one of the calendars supported by MPAS cores, used to\n        determine ``month`` from ``Time`` coordinate, so must be supplied if\n        ``ds`` does not already have a ``month`` coordinate or data array\n\n    maskVaries : bool, optional\n        If the mask (where variables in ``ds`` are ``NaN``) varies with time.\n        If not, the weighted average does not need make extra effort to account\n        for the mask.  Most MPAS fields will have masks that don't vary in\n        time, whereas observations may sometimes be present only at some\n        times and not at others, requiring ``maskVaries = True``.\n\n    Returns\n    -------\n    climatology : object of same type as ``ds``\n        A data set without the ``'Time'`` coordinate containing the mean\n        of ds over all months in monthValues, weighted by the number of days\n        in each month.\n    \"\"\"\n    # Authors\n    # -------\n    # Xylar Asay-Davis\n\n    ds = add_years_months_days_in_month(ds, calendar)\n\n    mask = xr.zeros_like(ds.month, bool)\n\n    for month in monthValues:\n        mask = numpy.logical_or(mask, ds.month == month)\n\n    climatologyMonths = ds.where(mask, drop=True)\n\n    climatology = _compute_masked_mean(climatologyMonths, maskVaries)\n\n    return climatology  # }}}\n\n\ndef add_years_months_days_in_month(ds, calendar=None):  # {{{\n    '''\n    Add ``year``, ``month`` and ``daysInMonth`` as data arrays in ``ds``.\n    The number of days in each month of ``ds`` is computed either using the\n    ``startTime`` and ``endTime`` if available or assuming ``gregorian_noleap``\n    calendar and ignoring leap years.  ``year`` and ``month`` are computed\n    accounting correctly for the the calendar.\n\n    Parameters\n    ----------\n    ds : ``xarray.Dataset`` or ``xarray.DataArray`` object\n        A data set with a ``Time`` coordinate expressed as days since\n        0001-01-01\n\n    calendar : {'gregorian', 'gregorian_noleap'}, optional\n        The name of one of the calendars supported by MPAS cores, used to\n        determine ``year`` and ``month`` from ``Time`` coordinate\n\n    Returns\n    -------\n    ds : object of same type as ``ds``\n        The data set with ``year``, ``month`` and ``daysInMonth`` data arrays\n        added (if not already present)\n    '''\n    # Authors\n    # -------\n    # Xylar Asay-Davis\n\n    if ('year' in ds.coords and 'month' in ds.coords and\n            'daysInMonth' in ds.coords):\n        return ds\n\n    ds = ds.copy()\n\n    if 'year' not in ds.coords or 'month' not in ds.coords:\n        if calendar is None:\n            raise ValueError('calendar must be provided if month and year '\n                             'coordinate is not in ds.')\n        datetimes = days_to_datetime(ds.Time, calendar=calendar)\n\n    if 'year' not in ds.coords:\n        ds.coords['year'] = ('Time', [date.year for date in datetimes])\n\n    if 'month' not in ds.coords:\n        ds.coords['month'] = ('Time', [date.month for date in datetimes])\n\n    if 'daysInMonth' not in ds.coords:\n        if 'startTime' in ds.coords and 'endTime' in ds.coords:\n            ds.coords['daysInMonth'] = ds.endTime - ds.startTime\n        else:\n            if calendar == 'gregorian':\n                print('Warning: The MPAS run used the Gregorian calendar '\n                      'but does not appear to have\\n'\n                      'supplied start and end times.  Climatologies '\n                      'will be computed with\\n'\n                      'month durations ignoring leap years.')\n\n            daysInMonth = numpy.array(\n                [constants.daysInMonth[int(month) - 1] for\n                 month in ds.month.values], float)\n            ds.coords['daysInMonth'] = ('Time', daysInMonth)\n\n    return ds  # }}}\n\n\ndef remap_and_write_climatology(config, climatologyDataSet,\n                                climatologyFileName, remappedFileName,\n                                remapper, logger=None):  # {{{\n    \"\"\"\n    Given a field in a climatology data set, use the ``remapper`` to remap\n    horizontal dimensions of all fields, write the results to an output file,\n    and return the remapped data set.\n\n    Note that ``climatologyFileName`` and ``remappedFileName`` will be\n    overwritten if they exist, so if this behavior is not desired, the calling\n    code should skip this call if the files exist and simply load the contents\n    of ``remappedFileName``.\n\n    Parameters\n    ----------\n    config :  instance of ``MpasAnalysisConfigParser``\n        Contains configuration options\n\n    climatologyDataSet : ``xarray.DataSet`` or ``xarray.DataArray`` object\n        A data set containing a climatology\n\n    fieldName : str\n        A field within the climatology to be remapped\n\n    climatologyFileName : str\n        The name of the output file to which the data set should be written\n        before remapping (if using ncremap).\n\n    remappedFileName : str\n        The name of the output file to which the remapped data set should\n        be written.\n\n    remapper : ``pyremap.Remapper`` object\n        A remapper that can be used to remap files or data sets to a\n        comparison grid.\n\n    logger : ``logging.Logger``, optional\n        A logger to which ncclimo output should be redirected\n\n    Returns\n    -------\n    remappedClimatology : ``xarray.DataSet`` or ``xarray.DataArray`` object\n        A data set containing the remapped climatology\n    \"\"\"\n    # Authors\n    # -------\n    # Xylar Asay-Davis\n\n    useNcremap = config.getboolean('climatology', 'useNcremap')\n\n    if remapper.mappingFileName is None:\n        # no remapping is needed\n        remappedClimatology = climatologyDataSet\n    else:\n        renormalizationThreshold = config.getfloat(\n            'climatology', 'renormalizationThreshold')\n        parallel_exec = config.get(\n            'execute', 'ncremapParallelExec')\n        if parallel_exec == 'None':\n            parallel_exec = None\n\n        if useNcremap:\n            if not os.path.exists(climatologyFileName):\n                write_netcdf(climatologyDataSet, climatologyFileName)\n            remapper.remap_file(inFileName=climatologyFileName,\n                                outFileName=remappedFileName,\n                                overwrite=True,\n                                renormalize=renormalizationThreshold,\n                                logger=logger,\n                                parallel_exec=parallel_exec)\n            remappedClimatology = xr.open_dataset(remappedFileName)\n        else:\n\n            remappedClimatology = remapper.remap(climatologyDataSet,\n                                                 renormalizationThreshold)\n            write_netcdf(remappedClimatology, remappedFileName)\n    return remappedClimatology  # }}}\n\n\ndef get_unmasked_mpas_climatology_directory(config, op='avg'):  # {{{\n    \"\"\"\n    Get the directory for an unmasked MPAS climatology produced by ncclimo,\n    making the directory if it doesn't already exist\n\n    Parameters\n    ----------\n    config :  ``MpasAnalysisConfigParser``\n        configuration options\n\n    op : {'avg', 'min', 'max'}\n         operator for monthly stats\n    \"\"\"\n    # Authors\n    # -------\n    # Xylar Asay-Davis\n\n    climatologyOpDirectory = get_climatology_op_directory(config, op)\n\n    mpasMeshName = config.get('input', 'mpasMeshName')\n\n    directory = '{}/unmasked_{}'.format(climatologyOpDirectory,\n                                        mpasMeshName)\n\n    make_directories(directory)\n    return directory  # }}}\n\n\ndef get_unmasked_mpas_climatology_file_name(config, season, componentName,\n                                            op='avg'):\n    # {{{\n    \"\"\"\n    Get the file name for an unmasked MPAS climatology produced by ncclimo\n\n    Parameters\n    ----------\n    config :  ``MpasAnalysisConfigParser``\n        configuration options\n\n    season : str\n        One of the seasons in ``constants.monthDictionary``\n\n    componentName : {'ocean', 'seaIce'}\n        The MPAS component for which the climatology is being computed\n\n    op : {'avg', 'min', 'max'}\n         operator for monthly stats\n    \"\"\"\n    # Authors\n    # -------\n    # Xylar Asay-Davis\n\n    startYear = config.getint('climatology', 'startYear')\n    endYear = config.getint('climatology', 'endYear')\n\n    if componentName == 'ocean':\n        ncclimoModel = 'mpaso'\n    elif componentName == 'seaIce':\n        ncclimoModel = 'mpascice'\n    else:\n        raise ValueError('component {} is not supported by ncclimo.\\n'\n                         'Check with Charlie Zender and Xylar Asay-Davis\\n'\n                         'about getting it added'.format(componentName))\n\n    directory = get_unmasked_mpas_climatology_directory(config, op)\n\n    make_directories(directory)\n    monthValues = sorted(constants.monthDictionary[season])\n    startMonth = monthValues[0]\n    endMonth = monthValues[-1]\n\n    suffix = '{:04d}{:02d}_{:04d}{:02d}_climo'.format(\n        startYear, startMonth, endYear, endMonth)\n\n    if season in constants.abrevMonthNames:\n        season = '{:02d}'.format(monthValues[0])\n    fileName = '{}/{}_{}_{}.nc'.format(directory, ncclimoModel,\n                                       season, suffix)\n    return fileName  # }}}\n\n\ndef get_masked_mpas_climatology_file_name(config, season, componentName,\n                                          climatologyName, op='avg'):  # {{{\n    \"\"\"\n    Get the file name for a masked MPAS climatology\n\n    Parameters\n    ----------\n    config :  ``MpasAnalysisConfigParser``\n        Configuration options\n\n    season : str\n        One of the seasons in ``constants.monthDictionary``\n\n    componentName : {'ocean', 'seaIce'}\n        The MPAS component for which the climatology is being computed\n\n    climatologyName : str\n        The name of the climatology (typically the name of a field to mask\n        and later remap)\n\n    op : {'avg', 'min', 'max'}\n         operator for monthly stats\n    \"\"\"\n    # Authors\n    # -------\n    # Xylar Asay-Davis\n\n    startYear = config.getint('climatology', 'startYear')\n    endYear = config.getint('climatology', 'endYear')\n    mpasMeshName = config.get('input', 'mpasMeshName')\n\n    if componentName == 'ocean':\n        ncclimoModel = 'mpaso'\n    elif componentName == 'seaIce':\n        ncclimoModel = 'mpascice'\n    else:\n        raise ValueError('component {} is not supported by ncclimo.\\n'\n                         'Check with Charlie Zender and Xylar Asay-Davis\\n'\n                         'about getting it added'.format(componentName))\n\n    climatologyOpDirectory = get_climatology_op_directory(config, op)\n\n    stageDirectory = '{}/masked'.format(climatologyOpDirectory)\n\n    directory = '{}/{}_{}'.format(\n        stageDirectory, climatologyName,\n        mpasMeshName)\n\n    make_directories(directory)\n\n    monthValues = sorted(constants.monthDictionary[season])\n    startMonth = monthValues[0]\n    endMonth = monthValues[-1]\n\n    suffix = '{:04d}{:02d}_{:04d}{:02d}_climo'.format(\n        startYear, startMonth, endYear, endMonth)\n\n    if season in constants.abrevMonthNames:\n        season = '{:02d}'.format(monthValues[0])\n    fileName = '{}/{}_{}_{}.nc'.format(\n        directory, ncclimoModel, season, suffix)\n\n    return fileName  # }}}\n\n\ndef get_remapped_mpas_climatology_file_name(config, season, componentName,\n                                            climatologyName,\n                                            comparisonGridName,\n                                            op='avg'):  # {{{\n    \"\"\"\n    Get the file name for a masked MPAS climatology\n\n    Parameters\n    ----------\n    config :  ``MpasAnalysisConfigParser``\n        Configuration options\n\n    season : str\n        One of the seasons in ``constants.monthDictionary``\n\n    componentName : {'ocean', 'seaIce'}\n        The MPAS component for which the climatology is being computed\n\n    climatologyName : str\n        The name of the climatology (typically the name of a field to mask\n        and later remap)\n\n    comparisonGridName : str\n        The name of the comparison grid to use for remapping.  If it is one\n        of the default comparison grid names ``{'latlon', 'antarctic',\n        'arctic'}``, the full grid name is looked up via\n        get_comparison_descriptor\n\n    op : {'avg', 'min', 'max'}\n         operator for monthly stats\n    \"\"\"\n    # Authors\n    # -------\n    # Xylar Asay-Davis\n\n    startYear = config.getint('climatology', 'startYear')\n    endYear = config.getint('climatology', 'endYear')\n    mpasMeshName = config.get('input', 'mpasMeshName')\n\n    if componentName == 'ocean':\n        ncclimoModel = 'mpaso'\n    elif componentName == 'seaIce':\n        ncclimoModel = 'mpascice'\n    else:\n        raise ValueError('component {} is not supported by ncclimo.\\n'\n                         'Check with Charlie Zender and Xylar Asay-Davis\\n'\n                         'about getting it added'.format(componentName))\n\n    climatologyOpDirectory = get_climatology_op_directory(config, op)\n\n    if comparisonGridName in ['latlon', 'antarctic', 'arctic']:\n        comparisonDescriptor = get_comparison_descriptor(config,\n                                                         comparisonGridName)\n        comparisonFullMeshName = comparisonDescriptor.meshName\n    else:\n        comparisonFullMeshName = comparisonGridName\n\n    stageDirectory = '{}/remapped'.format(climatologyOpDirectory)\n\n    directory = '{}/{}_{}_to_{}'.format(stageDirectory, climatologyName,\n                                        mpasMeshName, comparisonFullMeshName)\n\n    make_directories(directory)\n\n    monthValues = sorted(constants.monthDictionary[season])\n    startMonth = monthValues[0]\n    endMonth = monthValues[-1]\n\n    suffix = '{:04d}{:02d}_{:04d}{:02d}_climo'.format(\n        startYear, startMonth, endYear, endMonth)\n\n    if season in constants.abrevMonthNames:\n        season = '{:02d}'.format(monthValues[0])\n    fileName = '{}/{}_{}_{}.nc'.format(\n        directory, ncclimoModel, season, suffix)\n\n    return fileName  # }}}\n\n\ndef get_climatology_op_directory(config, op='avg'):\n    '''\n    Get the output directory for MPAS climatologies from output with the given\n    monthly operator: avg, min or max\n    '''\n    climatologyBaseDirectory = build_config_full_path(\n        config, 'output', 'mpasClimatologySubdirectory')\n\n    return '{}/{}'.format(climatologyBaseDirectory, op)\n\n\ndef _compute_masked_mean(ds, maskVaries):  # {{{\n    '''\n    Compute the time average of data set, masked out where the variables in ds\n    are NaN and, if ``maskVaries == True``, weighting by the number of days\n    used to compute each monthly mean time in ds.\n    '''\n    # Authors\n    # -------\n    # Xylar Asay-Davis\n\n    def ds_to_weights(ds):\n        # make an identical data set to ds but replacing all data arrays with\n        # nonnull applied to that data array\n        weights = ds.copy(deep=True)\n        if isinstance(ds, xr.core.dataarray.DataArray):\n            weights = ds.notnull()\n        elif isinstance(ds, xr.core.dataset.Dataset):\n            for var in ds.data_vars:\n                weights[var] = ds[var].notnull()\n        else:\n            raise TypeError('ds must be an instance of either xarray.Dataset '\n                            'or xarray.DataArray.')\n\n        return weights\n\n    if maskVaries:\n        dsWeightedSum = (ds * ds.daysInMonth).sum(dim='Time', keep_attrs=True)\n\n        weights = ds_to_weights(ds)\n\n        weightSum = (weights * ds.daysInMonth).sum(dim='Time')\n\n        timeMean = dsWeightedSum / weightSum.where(weightSum > 0.)\n    else:\n        days = ds.daysInMonth.sum(dim='Time')\n\n        dsWeightedSum = (ds * ds.daysInMonth).sum(dim='Time', keep_attrs=True)\n\n        timeMean = dsWeightedSum / days.where(days > 0.)\n\n    return timeMean  # }}}\n\n\ndef _matches_comparison(obsDescriptor, comparisonDescriptor):  # {{{\n    '''\n    Determine if the two meshes are the same\n    '''\n    # Authors\n    # -------\n    # Xylar Asay-Davis\n\n    if isinstance(obsDescriptor, ProjectionGridDescriptor) and \\\n            isinstance(comparisonDescriptor, ProjectionGridDescriptor):\n        # pretty hard to determine if projections are the same, so we'll rely\n        # on the grid names\n        match = obsDescriptor.meshName == comparisonDescriptor.meshName and \\\n            len(obsDescriptor.x) == len(comparisonDescriptor.x) and \\\n            len(obsDescriptor.y) == len(comparisonDescriptor.y) and \\\n            numpy.all(numpy.isclose(obsDescriptor.x,\n                                    comparisonDescriptor.x)) and \\\n            numpy.all(numpy.isclose(obsDescriptor.y,\n                                    comparisonDescriptor.y))\n    elif isinstance(obsDescriptor, LatLonGridDescriptor) and \\\n            isinstance(comparisonDescriptor, LatLonGridDescriptor):\n        match = ((('degree' in obsDescriptor.units and\n                   'degree' in comparisonDescriptor.units) or\n                  ('radian' in obsDescriptor.units and\n                   'radian' in comparisonDescriptor.units)) and\n                 len(obsDescriptor.lat) == len(comparisonDescriptor.lat) and\n                 len(obsDescriptor.lon) == len(comparisonDescriptor.lon) and\n                 numpy.all(numpy.isclose(obsDescriptor.lat,\n                                         comparisonDescriptor.lat)) and\n                 numpy.all(numpy.isclose(obsDescriptor.lon,\n                                         comparisonDescriptor.lon)))\n    else:\n        match = False\n\n    return match  # }}}\n\n\ndef _setup_climatology_caching(ds, startYearClimo, endYearClimo,\n                               yearsPerCacheFile, cachePrefix,\n                               monthValues):  # {{{\n    '''\n    Determine which cache files already exist, which are incomplete and which\n    years are present in each cache file (whether existing or to be created).\n    '''\n    # Authors\n    # -------\n    # Xylar Asay-Davis\n\n    cacheInfo = []\n\n    cacheIndices = -1 * numpy.ones(ds.dims['Time'], int)\n    monthsInDs = ds.month.values\n    yearsInDs = ds.year.values\n\n    # figure out which files to load and which years go in each file\n    for firstYear in range(startYearClimo, endYearClimo + 1,\n                           yearsPerCacheFile):\n        years = range(firstYear, firstYear + yearsPerCacheFile)\n\n        yearString, fileSuffix = _get_year_string(years[0], years[-1])\n        outputFileClimo = '{}_{}.nc'.format(cachePrefix, fileSuffix)\n\n        done = False\n        if os.path.exists(outputFileClimo):\n            # already cached\n            dsCached = None\n            try:\n                dsCached = xr.open_dataset(outputFileClimo)\n            except IOError:\n                # assuming the cache file is corrupt, so deleting it.\n                print('Warning: Deleting cache file {}, which appears to '\n                      'have been corrupted.'.format(outputFileClimo))\n\n                os.remove(outputFileClimo)\n\n            monthsIfDone = len(monthValues) * len(years)\n            if ((dsCached is not None) and\n                    (dsCached.attrs['totalMonths'] == monthsIfDone)):\n                # also complete, so we can move on\n                done = True\n            if dsCached is not None:\n                dsCached.close()\n\n        cacheIndex = len(cacheInfo)\n        for year in years:\n            for month in monthValues:\n                mask = numpy.logical_and(yearsInDs == year,\n                                         monthsInDs == month)\n                cacheIndices[mask] = cacheIndex\n\n        if numpy.count_nonzero(cacheIndices == cacheIndex) == 0:\n            continue\n\n        cacheInfo.append((outputFileClimo, done, yearString))\n\n    ds = ds.copy()\n    ds.coords['cacheIndices'] = ('Time', cacheIndices)\n\n    return cacheInfo, cacheIndices  # }}}\n\n\ndef _cache_individual_climatologies(ds, cacheInfo, printProgress,\n                                    yearsPerCacheFile, monthValues,\n                                    calendar):  # {{{\n    '''\n    Cache individual climatologies for later aggregation.\n    '''\n    # Authors\n    # -------\n    # Xylar Asay-Davis\n\n    for cacheIndex, info in enumerate(cacheInfo):\n        outputFileClimo, done, yearString = info\n        if done:\n            continue\n        dsYear = ds.where(ds.cacheIndices == cacheIndex, drop=True)\n\n        if printProgress:\n            print('     {}'.format(yearString))\n\n        totalDays = dsYear.daysInMonth.sum(dim='Time').values\n\n        monthCount = dsYear.dims['Time']\n\n        climatology = compute_climatology(dsYear, monthValues, calendar,\n                                          maskVaries=False)\n\n        climatology.attrs['totalDays'] = totalDays\n        climatology.attrs['totalMonths'] = monthCount\n        climatology.attrs['fingerprintClimo'] = fingerprint_generator()\n\n        write_netcdf(climatology, outputFileClimo)\n        climatology.close()\n\n    # }}}\n\n\ndef _cache_aggregated_climatology(startYearClimo, endYearClimo, cachePrefix,\n                                  printProgress, monthValues,\n                                  cacheInfo):  # {{{\n    '''\n    Cache aggregated climatology from individual climatologies.\n    '''\n    # Authors\n    # -------\n    # Xylar Asay-Davis\n\n    yearString, fileSuffix = _get_year_string(startYearClimo, endYearClimo)\n    outputFileClimo = '{}_{}.nc'.format(cachePrefix, fileSuffix)\n\n    done = False\n    if len(cacheInfo) == 0:\n        climatology = None\n        done = True\n\n    if os.path.exists(outputFileClimo):\n        # already cached\n        climatology = None\n        try:\n            climatology = xr.open_dataset(outputFileClimo)\n\n        except IOError:\n            # assuming the cache file is corrupt, so deleting it.\n            print('Warning: Deleting cache file {}, which appears to have '\n                  'been corrupted.'.format(outputFileClimo))\n            os.remove(outputFileClimo)\n\n        if len(cacheInfo) == 1 and outputFileClimo == cacheInfo[0][0]:\n            # theres only one cache file and it already has the same name\n            # as the aggregated file so no need to aggregate\n            done = True\n\n        elif climatology is not None:\n            monthsIfDone = (\n                endYearClimo - startYearClimo + 1) * len(monthValues)\n            if climatology.attrs['totalMonths'] == monthsIfDone:\n                # also complete, so we can move on\n                done = True\n            else:\n                climatology.close()\n\n    if not done:\n        if printProgress:\n            print('   Computing aggregated climatology '\n                  '{}...'.format(yearString))\n\n        first = True\n        for cacheIndex, info in enumerate(cacheInfo):\n            inFileClimo = info[0]\n            ds = xr.open_dataset(inFileClimo)\n            days = ds.attrs['totalDays']\n            months = ds.attrs['totalMonths']\n            if first:\n                totalDays = days\n                totalMonths = months\n                climatology = ds * days\n                first = False\n            else:\n                totalDays += days\n                totalMonths += months\n                climatology = climatology + ds * days\n\n            ds.close()\n        climatology = climatology / totalDays\n\n        climatology.attrs['totalDays'] = totalDays\n        climatology.attrs['totalMonths'] = totalMonths\n        climatology.attrs['fingerprintClimo'] = fingerprint_generator()\n\n        write_netcdf(climatology, outputFileClimo)\n\n    return climatology  # }}}\n\n\ndef _get_year_string(startYear, endYear):\n    if startYear == endYear:\n        yearString = '{:04d}'.format(startYear)\n        fileSuffix = 'year{}'.format(yearString)\n    else:\n        yearString = '{:04d}-{:04d}'.format(startYear, endYear)\n        fileSuffix = 'years{}'.format(yearString)\n\n    return yearString, fileSuffix\n\n\n# vim: foldmethod=marker ai ts=4 sts=4 et sw=4 ft=python\n", "meta": {"hexsha": "fab6fd57ab09d476681601186bb640ae30f4619e", "size": 31626, "ext": "py", "lang": "Python", "max_stars_repo_path": "mpas_analysis/shared/climatology/climatology.py", "max_stars_repo_name": "sbrus89/MPAS-Analysis", "max_stars_repo_head_hexsha": "5e151c3377d26d25f0249dcf47a6598304d5d2aa", "max_stars_repo_licenses": ["MIT", "Apache-2.0", "BSD-3-Clause"], "max_stars_count": 43, "max_stars_repo_stars_event_min_datetime": "2016-08-31T22:59:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T06:46:04.000Z", "max_issues_repo_path": "mpas_analysis/shared/climatology/climatology.py", "max_issues_repo_name": "sbrus89/MPAS-Analysis", "max_issues_repo_head_hexsha": "5e151c3377d26d25f0249dcf47a6598304d5d2aa", "max_issues_repo_licenses": ["MIT", "Apache-2.0", "BSD-3-Clause"], "max_issues_count": 764, "max_issues_repo_issues_event_min_datetime": "2016-07-01T20:15:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T19:03:17.000Z", "max_forks_repo_path": "mpas_analysis/shared/climatology/climatology.py", "max_forks_repo_name": "sbrus89/MPAS-Analysis", "max_forks_repo_head_hexsha": "5e151c3377d26d25f0249dcf47a6598304d5d2aa", "max_forks_repo_licenses": ["MIT", "Apache-2.0", "BSD-3-Clause"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2016-06-22T20:36:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T15:25:15.000Z", "avg_line_length": 35.4551569507, "max_line_length": 79, "alphanum_fraction": 0.6174034023, "include": true, "reason": "import numpy", "num_tokens": 7033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.16844720649466668}}
{"text": "\"\"\"\nReference: https://github.com/openai/imitation\nI follow the architecture from the official repository\n\"\"\"\nimport gym\nimport tensorflow as tf\nimport numpy as np\n\nfrom stable_baselines.common.mpi_running_mean_std import RunningMeanStd as MpiRunningMeanStd\n\nfrom stable_baselines.common.running_mean_std import RunningMeanStd, RunningMinMax\nfrom stable_baselines.common import tf_util as tf_util\nfrom stable_baselines.common import zipsame\n\n\n\ndef logsigmoid(input_tensor):\n    \"\"\"\n    Equivalent to tf.log(tf.sigmoid(a))\n\n    :param input_tensor: (tf.Tensor)\n    :return: (tf.Tensor)\n    \"\"\"\n    return -tf.nn.softplus(-input_tensor)\n\n\ndef logit_bernoulli_entropy(logits):\n    \"\"\"\n    Reference:\n    https://github.com/openai/imitation/blob/99fbccf3e060b6e6c739bdf209758620fcdefd3c/policyopt/thutil.py#L48-L51\n\n    :param logits: (tf.Tensor) the logits\n    :return: (tf.Tensor) the Bernoulli entropy\n    \"\"\"\n    ent = (1. - tf.nn.sigmoid(logits)) * logits - logsigmoid(logits)\n    return ent\n#\nclass TabularAdversary(object):\n    def __init__(self, observation_space, action_space, hidden_size,\n                 entcoeff=0.00, scope=\"adversary\", normalize=True, expert_features=None,\n                 exploration_bonus=False, bonus_coef=0.01, t_c=0.1):\n        \"\"\"\n        Reward regression from observations and transitions\n\n        :param observation_space: (gym.spaces)\n        :param action_space: (gym.spaces)\n        :param hidden_size: ([int]) the hidden dimension for the MLP\n        :param entcoeff: (float) the entropy loss weight\n        :param scope: (str) tensorflow variable scope\n        :param normalize: (bool) Whether to normalize the reward or not\n        \"\"\"\n        # TODO: support images properly (using a CNN)\n        self.scope = scope\n        self.observation_shape = observation_space.shape\n        self.actions_shape = action_space.shape\n        if isinstance(action_space, gym.spaces.Box):\n            # Continuous action space\n            self.discrete_actions = False\n            self.n_actions = action_space.shape[0]\n        elif isinstance(action_space, gym.spaces.Discrete):\n            self.n_actions = action_space.n\n            self.discrete_actions = True\n        else:\n            raise ValueError('Action space not supported: {}'.format(action_space))\n\n        self.hidden_size = hidden_size\n        self.normalize = normalize\n        self.obs_rms = None\n        self.expert_features = expert_features\n        self.reward = expert_features\n        normalization = np.linalg.norm(self.reward)\n        self.norm_factor = np.sqrt(float(self.observation_shape[0]))\n        if normalization > 1:\n            self.reward = self.reward / (self.norm_factor * normalization)\n        self.exploration_bonus = exploration_bonus\n        self.t_c = t_c\n\n        self.bonus_coef = bonus_coef\n        if self.exploration_bonus:\n            self.covariance_lambda = np.identity(self.observation_shape[0])\n        else:\n            self.covariance_lambda = None\n\n\n    def update_reward(self, features):\n\n        t_c = self.t_c\n        # self.reward = (1-t_c) * self.reward + t_c * (self.expert_features - features)\n        self.reward = self.reward + t_c * (self.expert_features - features) / self.norm_factor\n        normalization = np.linalg.norm(self.reward)\n\n        if normalization > 1:\n            self.reward = self.reward / normalization\n\n    def get_reward(self, observation):\n        \"\"\"\n        Predict the reward using the observation and action\n\n        :param obs: (tf.Tensor or np.ndarray) the observation\n        :param actions: (tf.Tensor or np.ndarray) the action\n        :return: (np.ndarray) the reward\n        \"\"\"\n        if self.exploration_bonus:\n            self.covariance_lambda = self.covariance_lambda \\\n                                + np.matmul(np.expand_dims(observation, axis=1), np.expand_dims(observation, axis=0))\n            inverse_covariance = np.linalg.inv(self.covariance_lambda)\n            reward = np.matmul(observation, np.reshape(self.reward, (self.reward.shape[0], 1))).squeeze()\n            bonus = np.sqrt(np.matmul(np.matmul(observation,inverse_covariance), observation))\n            return reward + self.bonus_coef * bonus\n        else:\n            reward = np.matmul(observation, np.reshape(self.reward, (self.reward.shape[0], 1))).squeeze()\n            return reward\n\n\n\nclass TabularAdversaryTF(object):\n    def __init__(self, sess, observation_space, action_space, hidden_size,\n                 entcoeff=0.00, scope=\"adversary\", normalize=True, expert_features=None,\n                 exploration_bonus=False, is_action_features=True, bonus_coef=0.01, t_c=0.1):\n        \"\"\"\n        Reward regression from observations and transitions\n\n        :param observation_space: (gym.spaces)\n        :param action_space: (gym.spaces)\n        :param hidden_size: ([int]) the hidden dimension for the MLP\n        :param entcoeff: (float) the entropy loss weight\n        :param scope: (str) tensorflow variable scope\n        :param normalize: (bool) Whether to normalize the reward or not\n        \"\"\"\n        # TODO: support images properly (using a CNN)\n        self.scope = scope\n        self.sess = sess\n        self.observation_shape = observation_space.shape\n        self.actions_shape = action_space.shape\n        self.is_action_features = is_action_features\n\n        if isinstance(action_space, gym.spaces.Box):\n            # Continuous action space\n            self.discrete_actions = False\n            self.n_actions = action_space.shape[0]\n        elif isinstance(action_space, gym.spaces.Discrete):\n            self.n_actions = action_space.n\n            self.discrete_actions = True\n        else:\n            raise ValueError('Action space not supported: {}'.format(action_space))\n\n        if self.is_action_features:\n            self.n_features = self.observation_shape[0] + self.n_actions\n        else:\n            self.n_features = self.observation_shape[0]\n        expert_features = expert_features[:self.n_features]\n\n\n        self.hidden_size = hidden_size\n        self.normalize = normalize\n        self.obs_rms = None\n\n        self.expert_features = tf.constant(expert_features, dtype=tf.float32)\n        self.norm_factor = tf.sqrt(float(self.n_features))\n\n\n        # self.normalization = tf.square(float(np.linalg.norm(expert_features)))\n        self.normalization = np.linalg.norm(expert_features)\n\n        expert_normalization = np.linalg.norm(expert_features)\n\n\n        # if expert_normalization > 1:\n        # self.reward_vec = tf.Variable(expert_features / (self.norm_factor * expert_normalization), dtype=tf.float32)\n        self.reward_vec = tf.Variable(expert_features, dtype=tf.float32)\n\n        # else:\n        #     self.reward_vec = tf.Variable(expert_features / self.norm_factor)\n            # self.reward_vec = tf.Variable(expert_features, dtype=tf.float32)\n\n        # self.reward_vec = tf.Variable(expert_features / self.normalization, dtype=tf.float32)\n\n        # if normalization > 1:\n        #     self.reward_vec = tf.Variable(expert_features / normalization, dtype=tf.float32)\n        # else:\n        #     self.reward_vec = tf.Variable(expert_features, dtype=tf.float32)\n        #\n\n        self.exploration_bonus = exploration_bonus\n        self.t_c = t_c\n\n        self.bonus_coef = bonus_coef\n        if self.exploration_bonus:\n            self.covariance_lambda = tf.Variable(tf.eye(self.n_features), dtype=tf.float32)\n            self.inverse_covariance = tf.eye(self.n_features)\n        else:\n            self.covariance_lambda = None\n            self.inverse_covariance = None\n        # Placeholders\n        self.features_ph = tf.placeholder(tf.float32, (None,) + (self.n_features, ),\n                                               name=\"observations_ph\")\n        self.successor_features_ph = tf.placeholder(tf.float32, (self.n_features, ),\n                                               name=\"successor_features_ph\")\n        # Build graph\n        with tf.variable_scope(self.scope, reuse=False):\n            if self.normalize:\n                with tf.variable_scope(\"obfilter\"):\n                    self.obs_rms = RunningMeanStd(shape=self.n_features)\n                    # self.obs_rms = RunningMinMax(shape=self.observation_shape)\n                obs_scaled = (tf.cast(self.features_ph, tf.float32) - self.obs_rms.mean)\\\n                      / tf.cast(tf.sqrt(self.obs_rms.var), tf.float32)\n                reward_vec_scaled = (tf.cast(self.reward_vec, tf.float32) - self.obs_rms.mean)\\\n                             / (tf.cast(tf.sqrt(self.obs_rms.var), tf.float32))\n                # obs_scaled = (tf.cast(self.features_ph, tf.float32)) / tf.cast(self.obs_rms.scale, tf.float32)\n                obs = obs_scaled\n\n\n                # reward_vec_scaled = (tf.cast(self.reward_vec, tf.float32)) / tf.cast(self.obs_rms.scale,\n                #                                                                              tf.float32)\n                reward_vec = reward_vec_scaled / tf.norm(reward_vec_scaled)\n\n            else:\n                obs = self.features_ph\n                reward_vec = self.reward_vec\n\n            if self.exploration_bonus:\n                self.new_covariance_lambda = self.covariance_lambda \\\n                                         + tf.reduce_sum(\n                                            tf.matmul(tf.expand_dims(tf.cast(self.features_ph, tf.float32), axis=2),\n                                                         tf.expand_dims(tf.cast(self.features_ph, tf.float32), axis=1)), axis=0)\n                self.update_covariance_op = tf.assign(self.covariance_lambda, self.new_covariance_lambda)\n\n                bonus = tf.squeeze(tf.sqrt(tf.matmul(tf.matmul(tf.expand_dims(obs, axis=1), self.inverse_covariance),\n                                          tf.expand_dims(obs, axis=2))))\n\n                reward = tf.squeeze(tf.matmul(obs, tf.expand_dims(reward_vec, 1)))\n                self.reward_op = reward + self.bonus_coef * bonus\n            else:\n                self.reward_op = tf.squeeze(tf.matmul(obs, tf.expand_dims(reward_vec, 1)))\n\n            # Update reward\n            self.new_reward_vec = self.reward_vec + self.t_c * (self.expert_features - self.successor_features_ph)\n            # self.new_reward_vec = self.reward_vec\\\n            #                       + self.t_c * (self.expert_features - self.successor_features_ph)\\\n            #                       / (self.normalization * self.norm_factor)\n            # normalization = tf.norm(self.new_reward_vec) * self.normalization\n            # normalization = tf.norm(self.new_reward_vec)\n            # self.new_reward_vec = tf.cond(normalization > 1.0,\n            #                                 true_fn=lambda: self.new_reward_vec / normalization,\n            #                                 false_fn=lambda: self.new_reward_vec)\n            # self.new_reward_vec = self.new_reward_vec / normalization\n\n            # reward_vec_unnormalized = self.reward_vec + self.t_c * (self.expert_features - self.successor_features_ph)\n            # reward_vec_scaled = (tf.cast(reward_vec_unnormalized, tf.float32)) / tf.cast(self.obs_rms.scale, tf.float32)\n            # self.new_reward_vec = reward_vec_scaled / tf.norm(reward_vec_scaled)\n            self.update_reward_op = tf.assign(self.reward_vec, self.new_reward_vec)\n\n\n\n    def update_reward(self, successor_features):\n        #\n        # sess = tf.get_default_session()\n        # if len(features.shape) == 1:\n            # features = np.expand_dims(features, 0)\n        if not self.is_action_features:\n            successor_features = successor_features[:self.observation_shape[0]]\n\n        feed_dict = {self.successor_features_ph: successor_features}\n\n        if self.exploration_bonus:\n            self.inverse_covariance = tf.linalg.inv(self.covariance_lambda)\n\n        self.sess.run(self.update_reward_op, feed_dict)\n\n\n\n\n    def get_reward(self, obs, action=None):\n        \"\"\"\n        Predict the reward using the observation and action\n\n        :param obs: (tf.Tensor or np.ndarray) the observation\n        :param actions: (tf.Tensor or np.ndarray) the action\n        :return: (np.ndarray) the reward\n        \"\"\"\n        # sess = tf.get_default_session()\n        if len(obs.shape) == 1:\n            obs = np.expand_dims(obs, 0)\n        if len(action.shape) == 1:\n            action = np.expand_dims(action, 0)\n\n        if self.is_action_features:\n            features = np.concatenate((obs, action), axis=1)\n        else:\n            features = obs\n\n        feed_dict = {self.features_ph: features}\n\n        if self.exploration_bonus:\n            reward, _ = self.sess.run([self.reward_op, self.update_covariance_op], feed_dict)\n        else:\n            reward = self.sess.run(self.reward_op, feed_dict)\n        return reward\n\n\n\nclass NeuralAdversary(object):\n    def __init__(self, sess, observation_space, action_space, hidden_size=64, lipschitz_reg_coef=1.0, scope=\"adversary\", normalize=True):\n        \"\"\"\n        Reward regression from observations and transitions\n\n        :param observation_space: (gym.spaces)\n        :param action_space: (gym.spaces)\n        :param hidden_size: ([int]) the hidden dimension for the MLP\n        :param entcoeff: (float) the entropy loss weight\n        :param scope: (str) tensorflow variable scope\n        :param normalize: (bool) Whether to normalize the reward or not\n        \"\"\"\n        # TODO: support images properly (using a CNN)\n        self.sess = sess\n        self.scope = scope\n        self.observation_shape = observation_space.shape\n        self.actions_shape = action_space.shape\n\n        if isinstance(action_space, gym.spaces.Box):\n            # Continuous action space\n            self.discrete_actions = False\n            self.n_actions = action_space.shape[0]\n        elif isinstance(action_space, gym.spaces.Discrete):\n            self.n_actions = action_space.n\n            self.discrete_actions = True\n        else:\n            raise ValueError('Action space not supported: {}'.format(action_space))\n\n        self.hidden_size = hidden_size\n        self.normalize = normalize\n        self.obs_rms = None\n\n        # Placeholders\n        self.policy_obs_ph = tf.placeholder(observation_space.dtype, (None,) + self.observation_shape,\n                                               name=\"observations_ph\")\n        self.policy_acs_ph = tf.placeholder(action_space.dtype, (None,) + self.actions_shape,\n                                               name=\"actions_ph\")\n        self.policy_gammas_ph = tf.placeholder(tf.float32, (None, 1), name=\"gammas_ph\")\n        self.expert_obs_ph = tf.placeholder(observation_space.dtype, (None,) + self.observation_shape,\n                                            name=\"expert_observations_ph\")\n        self.expert_acs_ph = tf.placeholder(action_space.dtype, (None,) + self.actions_shape,\n                                            name=\"expert_actions_ph\")\n        self.expert_gammas_ph = tf.placeholder(tf.float32, (None, 1), name=\"gammas_ph\")\n        self.mix_obs_ph = tf.placeholder(observation_space.dtype, (None,) + self.observation_shape,\n                                            name=\"expert_observations_ph\")\n        self.mix_acs_ph = tf.placeholder(action_space.dtype, (None,) + self.actions_shape,\n                                            name=\"expert_actions_ph\")\n\n\n        # Build graph\n        policy_rewards = self.build_graph(self.policy_obs_ph, self.policy_acs_ph, reuse=False)\n        expert_rewards = self.build_graph(self.expert_obs_ph, self.expert_acs_ph, reuse=True)\n        # generator_rewards = tf.math.sigmoid(generator_logits)\n        # expert_rewards = tf.math.sigmoid(expert_logits)\n        # policy_scaled_rewards = tf.multiply(policy_rewards, self.policy_gammas_ph)\n        policy_scaled_rewards = policy_rewards\n        # policy_value = (1-0.99) * tf.reduce_sum(policy_scaled_rewards)\n        policy_value = tf.reduce_mean(policy_scaled_rewards)\n        # expert_scaled_rewards = tf.multiply(expert_rewards, self.expert_gammas_ph)\n        expert_scaled_rewards = expert_rewards\n        # expert_value = (1-0.99) * tf.reduce_sum(expert_scaled_rewards)\n        expert_value = tf.reduce_mean(expert_scaled_rewards)\n\n        # alpha = tf.random.uniform([], 0.0, 1.0, observation_space.dtype)\n        # generator_obs_mix = tf.reduce_mean(self.generator_obs_ph, axis=0, keepdims=True)\n        # generator_acs_mix = tf.reduce_mean(self.generator_acs_ph, axis=0, keepdims=True)\n        # expert_obs_mix = tf.reduce_mean(self.expert_obs_ph, axis=0, keepdims=True)\n        # expert_acs_mix = tf.reduce_mean(self.expert_acs_ph, axis=0, keepdims=True)\n        # generator_obs_mix = (1-0.99) * tf.reduce_sum(tf.cast(self.generator_gammas_ph, observation_space.dtype) * self.generator_obs_ph, axis=0, keepdims=True)\n        # generator_acs_mix = (1-0.99) * tf.reduce_sum(tf.cast(self.generator_gammas_ph, action_space.dtype) * self.generator_acs_ph, axis=0, keepdims=True)\n        # expert_obs_mix = (1-0.99) * tf.reduce_sum(tf.cast(self.expert_gammas_ph, observation_space.dtype) * self.expert_obs_ph, axis=0, keepdims=True)\n        # expert_acs_mix = (1-0.99) * tf.reduce_sum(tf.cast(self.expert_gammas_ph, action_space.dtype) * self.expert_acs_ph, axis=0, keepdims=True)\n        # mixture_obs = alpha * generator_obs_mix + (1 - alpha) * tf.reduce_mean(expert_obs_mix)\n        # mixture_acs = tf.cast(alpha, action_space.dtype) * generator_acs_mix\\\n        #               + tf.cast((1 - alpha), action_space.dtype) * expert_acs_mix\n        mixture_rewards = self.build_graph(self.mix_obs_ph, self.mix_acs_ph, reuse=True)\n        grads = tf.gradients(mixture_rewards, [self.mix_obs_ph, self.mix_acs_ph])[0]\n        norm = tf.cast(tf.sqrt(tf.reduce_sum(tf.square(grads), axis=1)), tf.float32)\n        lipschitz_reg = tf.reduce_mean(tf.square(norm - 1.0))\n        lipschitz_reg_loss = lipschitz_reg_coef * lipschitz_reg\n\n        rewards = tf.concat([policy_rewards, expert_rewards], 0)\n\n        rewards_reg = - tf.reduce_mean(logit_bernoulli_entropy(rewards))\n        rewards_reg_coef = 0.001\n\n        # rewards_reg = tf.reduce_sum(tf.square(rewards))\n        # rewards_reg_coef = 0.01\n\n        rewards_reg_loss = rewards_reg_coef * rewards_reg\n        policy_loss = policy_value - expert_value\n        loss = policy_loss + lipschitz_reg_loss + rewards_reg_loss\n\n        # Loss + Accuracy terms\n        self.losses = [loss]\n        self.loss_name = [\"generator_loss\", \"expert_loss\", \"entropy\", \"entropy_loss\", \"generator_acc\", \"expert_acc\"]\n        # self.total_loss = loss\n        # Build Reward for policy\n        self.reward_op = tf.clip_by_value(policy_rewards, -10.0, 10.0)\n        # self.reward_op = tf.stop_gradient(policy_rewards)\n        # self.reward_op = generator_rewards\n\n\n        var_list = self.get_trainable_variables()\n        rewards_optimizer = tf.train.AdamOptimizer(learning_rate=3e-4)\n        # rewards_optimizer = tf.train.AdamOptimizer(learning_rate=1e-5)\n\n        # rewards_optimizer = tf.train.AdamOptimizer(learning_rate=3e-4, beta1=0)\n        # rewards_optimizer = tf.train.AdamOptimizer(learning_rate=1e-3, beta1=0.5)\n\n        # rewards_optimizer = tf.train.AdamOptimizer(learning_rate=1e-2)\n\n        # grads, vars = zip(*rewards_optimizer.compute_gradients(loss, var_list=var_list))\n        # accum_vars = [tf.Variable(tf.zeros_like(var.initialized_value()), trainable=False) for var in var_list]\n        # accumulation_counter = tf.Variable(0.0, trainable=False)\n\n        # zero_ops = [var.assign(tf.zeros_like(var)) for var in accum_vars]\n        # zero_ops.append(accumulation_counter.assign(0.0))\n\n        # gvs = rewards_optimizer.compute_gradients(loss, var_list)\n        # accumulate_ops = [accum_vars[i].assign_add(gv[0]) for i, gv in enumerate(gvs)]\n        # accumulate_ops.append(accumulation_counter.assign_add(1.0))\n\n        # train_step = rewards_optimizer.apply_gradients([(accum_vars[i] / accumulation_counter, gv[1]) for i, gv in enumerate(gvs)])\n\n        # grads, vars = list(zip(*grads_and_vars))\n        # grads, norm = tf.clip_by_global_norm(grads, 300.0)\n        # rewards_train_op = rewards_optimizer.apply_gradients(zip(grads, vars))\n        # norm = tf.constant(0.)\n        rewards_train_op = rewards_optimizer.minimize(loss, var_list=var_list)\n\n        # rewards_train_op = [rewards_train_op, norm]\n\n        # self.zero_grad = tf_util.function([], zero_ops)\n        # self.compute_grads = tf_util.function(\n        #     [self.generator_obs_ph, self.generator_acs_ph, self.generator_gammas_ph,\n        #      self.expert_obs_ph, self.expert_acs_ph, self.expert_gammas_ph], accumulate_ops)\n        # self.train = tf_util.function([], train_step)\n        # print_op = tf.print(\"Value diff:\", policy_value - expert_value, \"Grad Regularizer:\", lipschitz_reg)\n        print_op = tf.no_op()\n        self.train = tf_util.function(\n            [self.policy_obs_ph, self.policy_acs_ph, self.policy_gammas_ph,\n             self.expert_obs_ph, self.expert_acs_ph, self.expert_gammas_ph,\n             self.mix_obs_ph, self.mix_acs_ph], [rewards_train_op, print_op])\n\n\n    def build_graph(self, obs_ph, acs_ph, reuse=False):\n        \"\"\"\n        build the graph\n\n        :param obs_ph: (tf.Tensor) the observation placeholder\n        :param acs_ph: (tf.Tensor) the action placeholder\n        :param reuse: (bool)\n        :return: (tf.Tensor) the graph output\n        \"\"\"\n        with tf.variable_scope(self.scope):\n            if reuse:\n                tf.get_variable_scope().reuse_variables()\n\n            if self.normalize:\n                with tf.variable_scope(\"obfilter\"):\n                    self.obs_rms = RunningMeanStd(shape=self.observation_shape)\n                obs = (tf.cast(obs_ph, tf.float32) - self.obs_rms.mean) / tf.cast(tf.sqrt(self.obs_rms.var), tf.float32)\n            else:\n                obs = tf.cast(obs_ph, tf.float32)\n\n            if self.discrete_actions:\n                one_hot_actions = tf.one_hot(acs_ph, self.n_actions)\n                actions_ph = tf.cast(one_hot_actions, tf.float32)\n            else:\n                actions_ph = acs_ph\n\n            _input = tf.concat([obs, actions_ph], axis=1)  # concatenate the two input -> form a transition\n            p_h1 = tf.contrib.layers.fully_connected(_input, self.hidden_size, activation_fn=tf.nn.tanh)\n            p_h2 = tf.contrib.layers.fully_connected(p_h1, self.hidden_size, activation_fn=tf.nn.tanh)\n            # rewards = tf.contrib.layers.fully_connected(p_h2, 1, activation_fn=tf.nn.tanh)\n            # rewards = tf.contrib.layers.fully_connected(p_h2, 1, activation_fn=tf.math.sigmoid)\n            rewards = tf.contrib.layers.fully_connected(p_h2, 1, activation_fn=tf.identity)\n        return rewards\n\n    def get_trainable_variables(self):\n        \"\"\"\n        Get all the trainable variables from the graph\n\n        :return: ([tf.Tensor]) the variables\n        \"\"\"\n        return tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, self.scope)\n\n    def get_reward(self, obs, actions):\n        \"\"\"\n        Predict the reward using the observation and action\n\n        :param obs: (tf.Tensor or np.ndarray) the observation\n        :param actions: (tf.Tensor or np.ndarray) the action\n        :return: (np.ndarray) the reward\n        \"\"\"\n        # sess = tf.get_default_session()\n        if len(obs.shape) == 1:\n            obs = np.expand_dims(obs, 0)\n        if len(actions.shape) == 1:\n            actions = np.expand_dims(actions, 0)\n        elif len(actions.shape) == 0:\n            # one discrete action\n            actions = np.expand_dims(actions, 0)\n\n        feed_dict = {self.policy_obs_ph: obs, self.policy_acs_ph: actions}\n        reward = self.sess.run(self.reward_op, feed_dict)\n        return reward\n\nclass NeuralAdversaryTRPO(object):\n    def __init__(self, sess, observation_space, action_space, hidden_size=64, entcoeff=0.001,\n                 scope=\"adversary\", normalize=True):\n        \"\"\"\n        Reward regression from observations and transitions\n\n        :param observation_space: (gym.spaces)\n        :param action_space: (gym.spaces)\n        :param hidden_size: ([int]) the hidden dimension for the MLP\n        :param entcoeff: (float) the entropy loss weight\n        :param scope: (str) tensorflow variable scope\n        :param normalize: (bool) Whether to normalize the reward or not\n        \"\"\"\n        # TODO: support images properly (using a CNN)\n        self.sess = sess\n        self.scope = scope\n        self.observation_shape = observation_space.shape\n        self.actions_shape = action_space.shape\n\n        if isinstance(action_space, gym.spaces.Box):\n            # Continuous action space\n            self.discrete_actions = False\n            self.n_actions = action_space.shape[0]\n        elif isinstance(action_space, gym.spaces.Discrete):\n            self.n_actions = action_space.n\n            self.discrete_actions = True\n        else:\n            raise ValueError('Action space not supported: {}'.format(action_space))\n\n        self.hidden_size = hidden_size\n        self.normalize = normalize\n        self.obs_rms = None\n\n        # Placeholders\n        self.policy_obs_ph = tf.placeholder(observation_space.dtype, (None,) + self.observation_shape,\n                                               name=\"observations_ph\")\n        self.policy_acs_ph = tf.placeholder(action_space.dtype, (None,) + self.actions_shape,\n                                               name=\"actions_ph\")\n        self.policy_gammas_ph = tf.placeholder(tf.float32, (None, 1), name=\"gammas_ph\")\n        self.expert_obs_ph = tf.placeholder(observation_space.dtype, (None,) + self.observation_shape,\n                                            name=\"expert_observations_ph\")\n        self.expert_acs_ph = tf.placeholder(action_space.dtype, (None,) + self.actions_shape,\n                                            name=\"expert_actions_ph\")\n        self.expert_gammas_ph = tf.placeholder(tf.float32, (None, 1), name=\"gammas_ph\")\n        self.mix_obs_ph = tf.placeholder(observation_space.dtype, (None,) + self.observation_shape,\n                                            name=\"expert_observations_ph\")\n        self.mix_acs_ph = tf.placeholder(action_space.dtype, (None,) + self.actions_shape,\n                                            name=\"expert_actions_ph\")\n\n\n        # Build graph\n        policy_rewards = self.build_graph(self.policy_obs_ph, self.policy_acs_ph, reuse=False)\n        expert_rewards = self.build_graph(self.expert_obs_ph, self.expert_acs_ph, reuse=True)\n        # policy_rewards = tf.math.sigmoid(policy_logits)\n        # expert_rewards = tf.math.sigmoid(expert_logits)\n        # policy_scaled_rewards = tf.multiply(policy_rewards, self.policy_gammas_ph)\n        policy_scaled_rewards = policy_rewards\n        # policy_value = tf.reduce_sum(policy_scaled_rewards)\n        policy_value = tf.reduce_mean(policy_scaled_rewards)\n        # expert_scaled_rewards = tf.multiply(expert_rewards, self.expert_gammas_ph)\n        expert_scaled_rewards = expert_rewards\n        # expert_value = tf.reduce_sum(expert_scaled_rewards)\n        expert_value = tf.reduce_mean(expert_scaled_rewards)\n\n        # alpha = tf.random.uniform([], 0.0, 1.0, observation_space.dtype)\n        # generator_obs_mix = tf.reduce_mean(self.generator_obs_ph, axis=0, keepdims=True)\n        # generator_acs_mix = tf.reduce_mean(self.generator_acs_ph, axis=0, keepdims=True)\n        # expert_obs_mix = tf.reduce_mean(self.expert_obs_ph, axis=0, keepdims=True)\n        # expert_acs_mix = tf.reduce_mean(self.expert_acs_ph, axis=0, keepdims=True)\n        # generator_obs_mix = (1-0.99) * tf.reduce_sum(tf.cast(self.generator_gammas_ph, observation_space.dtype) * self.generator_obs_ph, axis=0, keepdims=True)\n        # generator_acs_mix = (1-0.99) * tf.reduce_sum(tf.cast(self.generator_gammas_ph, action_space.dtype) * self.generator_acs_ph, axis=0, keepdims=True)\n        # expert_obs_mix = (1-0.99) * tf.reduce_sum(tf.cast(self.expert_gammas_ph, observation_space.dtype) * self.expert_obs_ph, axis=0, keepdims=True)\n        # expert_acs_mix = (1-0.99) * tf.reduce_sum(tf.cast(self.expert_gammas_ph, action_space.dtype) * self.expert_acs_ph, axis=0, keepdims=True)\n        # mixture_obs = alpha * generator_obs_mix + (1 - alpha) * tf.reduce_mean(expert_obs_mix)\n        # mixture_acs = tf.cast(alpha, action_space.dtype) * generator_acs_mix\\\n        #               + tf.cast((1 - alpha), action_space.dtype) * expert_acs_mix\n        mixture_rewards = self.build_graph(self.mix_obs_ph, self.mix_acs_ph, reuse=True)\n        grads = tf.gradients(mixture_rewards, [self.mix_obs_ph, self.mix_acs_ph])[0]\n        norm = tf.cast(tf.sqrt(tf.reduce_sum(tf.square(grads), axis=1)), tf.float32)\n        lipschitz_reg = tf.reduce_mean(tf.square(norm - 1.0))\n        lipschitz_reg_coef = 0.0\n        lipschitz_reg_loss = lipschitz_reg_coef * lipschitz_reg\n\n        rewards = tf.concat([policy_rewards, expert_rewards], 0)\n\n        rewards_reg = - tf.reduce_mean(logit_bernoulli_entropy(rewards))\n        # rewards_reg = tf.reduce_sum(tf.square(rewards))\n\n        rewards_reg_coef = 0.0\n\n        rewards_reg_loss = rewards_reg_coef * rewards_reg\n\n        policy_loss = policy_value - expert_value\n        self.total_loss = policy_loss + lipschitz_reg_loss + rewards_reg_loss\n\n        # Loss + Accuracy terms\n        self.losses = []\n        self.loss_name = [\"generator_loss\", \"expert_loss\", \"entropy\", \"entropy_loss\", \"generator_acc\", \"expert_acc\"]\n        # self.total_loss = loss\n        # Build Reward for policy\n        # self.reward_op = tf.stop_gradient(policy_rewards)\n        self.reward_op = tf.stop_gradient(tf.clip_by_value(policy_rewards, -1.0, 1.0))\n        # self.reward_op = generator_rewards\n\n        print_op = tf.print(\"Policy loss:\", policy_loss,\n                            \"GradReg\", lipschitz_reg,\n                            \"rewards_abs_mean\", tf.reduce_mean(tf.abs(rewards)), \"rewards_std\", tf.math.reduce_std(rewards),\n                            \"abs_max\", tf.math.reduce_max(tf.abs(rewards)))\n        var_list = self.get_trainable_variables()\n        self.lossandgrad = tf_util.function(\n            [self.policy_obs_ph, self.policy_acs_ph, self.policy_gammas_ph,\n             self.expert_obs_ph, self.expert_acs_ph, self.expert_gammas_ph,\n             self.mix_obs_ph, self.mix_acs_ph],\n            self.losses + [print_op] + [tf_util.flatgrad(self.total_loss, var_list)])\n\n        # print_op = tf.print(\"Value diff:\", policy_value - expert_value, \"Grad Regularizer:\", lipschitz_reg)\n        # print_op = tf.no_op()\n        # self.train = tf_util.function(\n        #     [self.policy_obs_ph, self.policy_acs_ph, self.policy_gammas_ph,\n        #      self.expert_obs_ph, self.expert_acs_ph, self.expert_gammas_ph,\n        #      self.mix_obs_ph, self.mix_acs_ph], [rewards_train_op, print_op])\n\n\n    def build_graph(self, obs_ph, acs_ph, reuse=False):\n        \"\"\"\n        build the graph\n\n        :param obs_ph: (tf.Tensor) the observation placeholder\n        :param acs_ph: (tf.Tensor) the action placeholder\n        :param reuse: (bool)\n        :return: (tf.Tensor) the graph output\n        \"\"\"\n        with tf.variable_scope(self.scope):\n            if reuse:\n                tf.get_variable_scope().reuse_variables()\n\n            if self.normalize:\n                with tf.variable_scope(\"obfilter\"):\n                    self.obs_rms = MpiRunningMeanStd(shape=self.observation_shape)\n                obs = (tf.cast(obs_ph, tf.float32) - self.obs_rms.mean) / tf.cast(self.obs_rms.std, tf.float32)\n            else:\n                obs = tf.cast(obs_ph, tf.float32)\n\n            if self.discrete_actions:\n                one_hot_actions = tf.one_hot(acs_ph, self.n_actions)\n                actions_ph = tf.cast(one_hot_actions, tf.float32)\n            else:\n                actions_ph = acs_ph\n\n            _input = tf.concat([obs, actions_ph], axis=1)  # concatenate the two input -> form a transition\n            p_h1 = tf.contrib.layers.fully_connected(_input, self.hidden_size, activation_fn=tf.nn.tanh)\n            p_h2 = tf.contrib.layers.fully_connected(p_h1, self.hidden_size, activation_fn=tf.nn.tanh)\n            # rewards = tf.contrib.layers.fully_connected(p_h2, 1, activation_fn=tf.nn.tanh)\n            # rewards = tf.contrib.layers.fully_connected(p_h2, 1, activation_fn=tf.math.sigmoid)\n            rewards = tf.contrib.layers.fully_connected(p_h2, 1, activation_fn=tf.identity)\n            # last_layer_init = tf.contrib.layers.variance_scaling_initializer(factor=0.1, mode='FAN_AVG', uniform=True)\n            # rewards = tf.contrib.layers.fully_connected(p_h2, 1, activation_fn=tf.identity, weights_initializer=last_layer_init)\n\n        return rewards\n\n    def get_trainable_variables(self):\n        \"\"\"\n        Get all the trainable variables from the graph\n\n        :return: ([tf.Tensor]) the variables\n        \"\"\"\n        return tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, self.scope)\n\n    def get_reward(self, obs, actions):\n        \"\"\"\n        Predict the reward using the observation and action\n\n        :param obs: (tf.Tensor or np.ndarray) the observation\n        :param actions: (tf.Tensor or np.ndarray) the action\n        :return: (np.ndarray) the reward\n        \"\"\"\n        # sess = tf.get_default_session()\n        if len(obs.shape) == 1:\n            obs = np.expand_dims(obs, 0)\n        if len(actions.shape) == 1:\n            actions = np.expand_dims(actions, 0)\n        elif len(actions.shape) == 0:\n            # one discrete action\n            actions = np.expand_dims(actions, 0)\n\n        feed_dict = {self.policy_obs_ph: obs, self.policy_acs_ph: actions}\n        reward = self.sess.run(self.reward_op, feed_dict)\n        return reward\n\n\nclass NeuralAdversaryMDPO(object):\n    def __init__(self, sess, observation_space, action_space, hidden_size=64, scope=\"adversary\", normalize=True):\n        \"\"\"\n        Reward regression from observations and transitions\n\n        :param observation_space: (gym.spaces)\n        :param action_space: (gym.spaces)\n        :param hidden_size: ([int]) the hidden dimension for the MLP\n        :param entcoeff: (float) the entropy loss weight\n        :param scope: (str) tensorflow variable scope\n        :param normalize: (bool) Whether to normalize the reward or not\n        \"\"\"\n        # TODO: support images properly (using a CNN)\n        self.sess = sess\n        self.scope = scope\n        self.observation_shape = observation_space.shape\n        self.actions_shape = action_space.shape\n\n        if isinstance(action_space, gym.spaces.Box):\n            # Continuous action space\n            self.discrete_actions = False\n            self.n_actions = action_space.shape[0]\n        elif isinstance(action_space, gym.spaces.Discrete):\n            self.n_actions = action_space.n\n            self.discrete_actions = True\n        else:\n            raise ValueError('Action space not supported: {}'.format(action_space))\n\n        self.hidden_size = hidden_size\n        self.normalize = normalize\n        self.obs_rms = None\n\n        # Placeholders\n        self.policy_obs_ph = tf.placeholder(observation_space.dtype, (None,) + self.observation_shape,\n                                               name=\"observations_ph\")\n        self.policy_acs_ph = tf.placeholder(action_space.dtype, (None,) + self.actions_shape,\n                                               name=\"actions_ph\")\n        self.policy_gammas_ph = tf.placeholder(tf.float32, (None, 1), name=\"gammas_ph\")\n        self.expert_obs_ph = tf.placeholder(observation_space.dtype, (None,) + self.observation_shape,\n                                            name=\"expert_observations_ph\")\n        self.expert_acs_ph = tf.placeholder(action_space.dtype, (None,) + self.actions_shape,\n                                            name=\"expert_actions_ph\")\n        self.expert_gammas_ph = tf.placeholder(tf.float32, (None, 1), name=\"gammas_ph\")\n        self.mix_obs_ph = tf.placeholder(observation_space.dtype, (None,) + self.observation_shape,\n                                            name=\"expert_observations_ph\")\n        self.mix_acs_ph = tf.placeholder(action_space.dtype, (None,) + self.actions_shape,\n                                            name=\"expert_actions_ph\")\n\n\n        # Build graph\n        policy_rewards = self.build_graph(self.policy_obs_ph, self.policy_acs_ph, reuse=False, scope=self.scope)\n        expert_rewards = self.build_graph(self.expert_obs_ph, self.expert_acs_ph, reuse=True, scope=self.scope)\n        old_policy_rewards = self.build_graph(self.policy_obs_ph, self.policy_acs_ph, reuse=False, scope=\"oldreward\")\n        old_expert_rewards = self.build_graph(self.expert_obs_ph, self.expert_acs_ph, reuse=True, scope=\"oldreward\")\n\n        # generator_rewards = tf.math.sigmoid(generator_logits)\n        # expert_rewards = tf.math.sigmoid(expert_logits)\n        # policy_scaled_rewards = tf.multiply(policy_rewards, self.policy_gammas_ph)\n        policy_scaled_rewards = policy_rewards\n        # policy_value = (1-0.99) * tf.reduce_sum(policy_scaled_rewards)\n        policy_value = tf.reduce_mean(policy_scaled_rewards)\n        # expert_scaled_rewards = tf.multiply(expert_rewards, self.expert_gammas_ph)\n        expert_scaled_rewards = expert_rewards\n        # expert_value = (1-0.99) * tf.reduce_sum(expert_scaled_rewards)\n        expert_value = tf.reduce_mean(expert_scaled_rewards)\n\n        # alpha = tf.random.uniform([], 0.0, 1.0, observation_space.dtype)\n        # generator_obs_mix = tf.reduce_mean(self.generator_obs_ph, axis=0, keepdims=True)\n        # generator_acs_mix = tf.reduce_mean(self.generator_acs_ph, axis=0, keepdims=True)\n        # expert_obs_mix = tf.reduce_mean(self.expert_obs_ph, axis=0, keepdims=True)\n        # expert_acs_mix = tf.reduce_mean(self.expert_acs_ph, axis=0, keepdims=True)\n        # generator_obs_mix = (1-0.99) * tf.reduce_sum(tf.cast(self.generator_gammas_ph, observation_space.dtype) * self.generator_obs_ph, axis=0, keepdims=True)\n        # generator_acs_mix = (1-0.99) * tf.reduce_sum(tf.cast(self.generator_gammas_ph, action_space.dtype) * self.generator_acs_ph, axis=0, keepdims=True)\n        # expert_obs_mix = (1-0.99) * tf.reduce_sum(tf.cast(self.expert_gammas_ph, observation_space.dtype) * self.expert_obs_ph, axis=0, keepdims=True)\n        # expert_acs_mix = (1-0.99) * tf.reduce_sum(tf.cast(self.expert_gammas_ph, action_space.dtype) * self.expert_acs_ph, axis=0, keepdims=True)\n        # mixture_obs = alpha * generator_obs_mix + (1 - alpha) * tf.reduce_mean(expert_obs_mix)\n        # mixture_acs = tf.cast(alpha, action_space.dtype) * generator_acs_mix\\\n        #               + tf.cast((1 - alpha), action_space.dtype) * expert_acs_mix\n        mixture_rewards = self.build_graph(self.mix_obs_ph, self.mix_acs_ph, reuse=True, scope=self.scope)\n        grads = tf.gradients(mixture_rewards, [self.mix_obs_ph, self.mix_acs_ph])[0]\n        norm = tf.cast(tf.sqrt(tf.reduce_sum(tf.square(grads), axis=1)), tf.float32)\n        lipschitz_reg = tf.reduce_mean(tf.square(norm - 1.0))\n        lipschitz_reg_coef = 10\n        lipschitz_reg_loss = lipschitz_reg_coef * lipschitz_reg\n        #\n        # rewards = tf.concat([policy_rewards, expert_rewards], 0)\n        #\n        # rewards_reg = - tf.reduce_mean(logit_bernoulli_entropy(rewards))\n        # rewards_reg_coef = 0.001\n        #\n\n\n        rewards = tf.concat([policy_rewards, expert_rewards], 0)\n\n        policy_clipped_rewards = tf.clip_by_value(policy_rewards, -10.0, 10.0)\n        expert_clipped_rewards = tf.clip_by_value(expert_rewards, -10.0, 10.0)\n        clipped_rewards = tf.concat([policy_clipped_rewards, expert_clipped_rewards], 0)\n\n        # rewards_reg_loss = rewards_reg_coef * rewards_reg\n        old_rewards = tf.concat([old_policy_rewards, old_expert_rewards], 0)\n\n        old_policy_clipped_rewards = tf.clip_by_value(old_policy_rewards, -10.0, 10.0)\n        old_expert_clipped_rewards = tf.clip_by_value(old_expert_rewards, -10.0, 10.0)\n        old_clipped_rewards = tf.concat([old_policy_clipped_rewards, old_expert_clipped_rewards], 0)\n\n\n\n\n        # rewards_reg_coef = 0.01\n        # bregman = tf.reduce_mean(tf_util.huber_loss(old_rewards - rewards))\n        bregman = tf.reduce_mean(tf.square(tf.stop_gradient(old_clipped_rewards) - rewards))\n\n        bregman_coeff = 100\n        bregman_loss = bregman_coeff * bregman\n        #\n        # stepsize = 0.001\n\n        rewards_reg = - tf.reduce_mean(logit_bernoulli_entropy(rewards))\n        rewards_reg_coeff = 0.00\n        # rewards_reg = tf.reduce_mean(tf.square(rewards))\n        # rewards_reg_coeff = 1\n        rewards_reg_loss = rewards_reg_coeff * rewards_reg\n\n        # rewards_reg_loss = rewards_reg_coef * rewards_reg\n\n        # policy_loss = policy_value - expert_value\n        # rewards_gradient = (tf.gradients(tf.reduce_mean(old_policy_clipped_rewards), [old_policy_rewards])[0]\n        #                - tf.gradients(tf.reduce_mean(old_expert_clipped_rewards), [old_expert_rewards])[0])\n        old_policy_loss = tf.reduce_mean(old_policy_rewards) - tf.reduce_mean(old_expert_rewards)\n        old_rewards_gradient = tf.concat(tf.gradients(old_policy_loss, [old_policy_rewards, old_expert_rewards]), axis=0)\n\n        policy_loss = tf.reduce_sum(tf.multiply(tf.stop_gradient(old_rewards_gradient), clipped_rewards))\n\n        loss = policy_loss + bregman_loss + rewards_reg_loss + lipschitz_reg_loss\n\n        # Loss + Accuracy terms\n        self.losses = [loss]\n        self.loss_name = [\"generator_loss\", \"expert_loss\", \"entropy\", \"entropy_loss\", \"generator_acc\", \"expert_acc\"]\n        # self.total_loss = loss\n        # Build Reward for policy\n        self.reward_op = old_policy_clipped_rewards\n        # self.reward_op = tf.stop_gradient(tf.clip_by_value(policy_rewards, -1.0, 1.0))\n        # self.reward_op = generator_rewards\n\n        self.update_old_rewards = \\\n            tf_util.function([], [], updates=[tf.assign(oldv, newv) for (oldv, newv) in\n                                              zipsame(tf_util.get_globals_vars(\"oldreward\"),\n                                                      tf_util.get_globals_vars(self.scope))])\n\n        var_list = self.get_trainable_variables()\n        # rewards_optimizer = tf.train.AdamOptimizer(learning_rate=1e-5, epsilon=1e-5)\n        # rewards_optimizer = tf.train.AdamOptimizer(learning_rate=3e-4, beta1=0.9895193, beta2=0.9999, epsilon=1e-5)\n\n        # rewards_optimizer = tf.train.AdamOptimizer(learning_rate=3e-4, beta1=0, beta2=0.9)\n        rewards_optimizer = tf.train.AdamOptimizer(learning_rate=3e-4)\n\n        # rewards_optimizer = tf.train.AdamOptimizer(learning_rate=1e-3, beta1=0.5)\n\n        # rewards_optimizer = tf.train.AdamOptimizer(learning_rate=1e-2)\n\n        # accum_vars = [tf.Variable(tf.zeros_like(var.initialized_value()), trainable=False) for var in var_list]\n        # accumulation_counter = tf.Variable(0.0, trainable=False)\n\n        # zero_ops = [var.assign(tf.zeros_like(var)) for var in accum_vars]\n        # zero_ops.append(accumulation_counter.assign(0.0))\n\n        # gvs = rewards_optimizer.compute_gradients(loss, var_list)\n        # accumulate_ops = [accum_vars[i].assign_add(gv[0]) for i, gv in enumerate(gvs)]\n        # accumulate_ops.append(accumulation_counter.assign_add(1.0))\n\n        # train_step = rewards_optimizer.apply_gradients([(accum_vars[i] / accumulation_counter, gv[1]) for i, gv in enumerate(gvs)])\n        grads, vars = zip(*rewards_optimizer.compute_gradients(loss, var_list=var_list))\n        grads, norm = tf.clip_by_global_norm(grads, 1e7)\n        # grads, norm = tf.clip_by_global_norm(grads, 5.0)\n\n        rewards_train_op = rewards_optimizer.apply_gradients(zip(grads, vars))\n        # norm = tf.constant(0.)\n        # rewards_train_op = rewards_optimizer.minimize(loss, var_list=var_list)\n\n        # rewards_train_op = [rewards_train_op, norm]\n\n        # self.zero_grad = tf_util.function([], zero_ops)\n        # self.compute_grads = tf_util.function(\n        #     [self.generator_obs_ph, self.generator_acs_ph, self.generator_gammas_ph,\n        #      self.expert_obs_ph, self.expert_acs_ph, self.expert_gammas_ph], accumulate_ops)\n        # self.train = tf_util.function([], train_step)\n        linear_approximation = tf.stop_gradient(tf.reduce_sum(tf.multiply(old_rewards_gradient, rewards - old_rewards)))\n        # print_op = tf.print(\"Value diff:\", linear_approximation, \"Bregman:\", bregman_loss,\n        #                     \"MD objective\",  linear_approximation + bregman_loss,\n        #                     \"Weight GradNorm:\", norm, \"Loss norm\", tf.norm(old_rewards_gradient),\n        #                     \"rewards_mean\", tf.reduce_mean(rewards), \"rewards_std\", tf.math.reduce_std(rewards),\n        #                     \"rewards_abs_max\", tf.math.reduce_max(rewards))\n        # print_op = tf.print(\"old_rewards_gradient\", tf.shape(old_rewards_gradient), \"rewards\",tf.shape(rewards))\n        print_op = tf.no_op()\n\n\n\n\n        # var_list = self.get_trainable_variables()\n\n        # grads, vars = zip(*rewards_optimizer.compute_gradients(loss, var_list=var_list))\n        # grads, norm = tf.clip_by_global_norm(grads, 300.0)\n        # rewards_train_op = rewards_optimizer.apply_gradients(zip(grads, vars))\n\n\n        self.train = tf_util.function(\n            [self.policy_obs_ph, self.policy_acs_ph, self.policy_gammas_ph,\n             self.expert_obs_ph, self.expert_acs_ph, self.expert_gammas_ph,\n             self.mix_obs_ph, self.mix_acs_ph], [rewards_train_op, print_op])\n\n\n    def build_graph(self, obs_ph, acs_ph, reuse=False, scope=None):\n        \"\"\"\n        build the graph\n\n        :param obs_ph: (tf.Tensor) the observation placeholder\n        :param acs_ph: (tf.Tensor) the action placeholder\n        :param reuse: (bool)\n        :return: (tf.Tensor) the graph output\n        \"\"\"\n        with tf.variable_scope(scope):\n            if reuse:\n                tf.get_variable_scope().reuse_variables()\n\n            if self.normalize:\n                with tf.variable_scope(\"obfilter\"):\n                    self.obs_rms = RunningMeanStd(shape=self.observation_shape)\n                obs = (tf.cast(obs_ph, tf.float32) - self.obs_rms.mean) / tf.cast(tf.sqrt(self.obs_rms.var), tf.float32)\n            else:\n                obs = tf.cast(obs_ph, tf.float32)\n\n            if self.discrete_actions:\n                one_hot_actions = tf.one_hot(acs_ph, self.n_actions)\n                actions_ph = tf.cast(one_hot_actions, tf.float32)\n            else:\n                actions_ph = acs_ph\n\n                _input = tf.concat([obs, actions_ph], axis=1)  # concatenate the two input -> form a transition\n                p_h1 = tf.contrib.layers.fully_connected(_input, self.hidden_size, activation_fn=tf.nn.tanh)\n                p_h2 = tf.contrib.layers.fully_connected(p_h1, self.hidden_size, activation_fn=tf.nn.tanh)\n                rewards = tf.contrib.layers.fully_connected(p_h2, 1, activation_fn=tf.identity)\n\n\n        return rewards\n\n    def get_trainable_variables(self):\n        \"\"\"\n        Get all the trainable variables from the graph\n\n        :return: ([tf.Tensor]) the variables\n        \"\"\"\n        return tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, self.scope)\n\n    def get_reward(self, obs, actions):\n        \"\"\"\n        Predict the reward using the observation and action\n\n        :param obs: (tf.Tensor or np.ndarray) the observation\n        :param actions: (tf.Tensor or np.ndarray) the action\n        :return: (np.ndarray) the reward\n        \"\"\"\n        # sess = tf.get_default_session()\n        if len(obs.shape) == 1:\n            obs = np.expand_dims(obs, 0)\n        if len(actions.shape) == 1:\n            actions = np.expand_dims(actions, 0)\n        elif len(actions.shape) == 0:\n            # one discrete action\n            actions = np.expand_dims(actions, 0)\n\n        feed_dict = {self.policy_obs_ph: obs, self.policy_acs_ph: actions}\n        reward = self.sess.run(self.reward_op, feed_dict)\n        return reward\n\nclass NeuralAdversaryMD(object):\n    def __init__(self, sess, observation_space, action_space, hidden_size=64, entcoeff=0.001, lipschitz_reg_coef=0.0,\n                 scope=\"adversary\", normalize=True):\n        \"\"\"\n        Reward regression from observations and transitions\n\n        :param observation_space: (gym.spaces)\n        :param action_space: (gym.spaces)\n        :param hidden_size: ([int]) the hidden dimension for the MLP\n        :param entcoeff: (float) the entropy loss weight\n        :param scope: (str) tensorflow variable scope\n        :param normalize: (bool) Whether to normalize the reward or not\n        \"\"\"\n        # TODO: support images properly (using a CNN)\n        self.sess = sess\n        self.scope = scope\n        self.observation_shape = observation_space.shape\n        self.actions_shape = action_space.shape\n\n        if isinstance(action_space, gym.spaces.Box):\n            # Continuous action space\n            self.discrete_actions = False\n            self.n_actions = action_space.shape[0]\n        elif isinstance(action_space, gym.spaces.Discrete):\n            self.n_actions = action_space.n\n            self.discrete_actions = True\n        else:\n            raise ValueError('Action space not supported: {}'.format(action_space))\n\n        self.hidden_size = hidden_size\n        self.normalize = normalize\n        self.obs_rms = None\n\n        # Placeholders\n        self.policy_obs_ph = tf.placeholder(observation_space.dtype, (None,) + self.observation_shape,\n                                               name=\"observations_ph\")\n        self.policy_acs_ph = tf.placeholder(action_space.dtype, (None,) + self.actions_shape,\n                                               name=\"actions_ph\")\n        self.policy_gammas_ph = tf.placeholder(tf.float32, (None, 1), name=\"gammas_ph\")\n        self.expert_obs_ph = tf.placeholder(observation_space.dtype, (None,) + self.observation_shape,\n                                            name=\"expert_observations_ph\")\n        self.expert_acs_ph = tf.placeholder(action_space.dtype, (None,) + self.actions_shape,\n                                            name=\"expert_actions_ph\")\n        self.expert_gammas_ph = tf.placeholder(tf.float32, (None, 1), name=\"expert_gammas_ph\")\n        self.mix_obs_ph = tf.placeholder(observation_space.dtype, (None,) + self.observation_shape,\n                                            name=\"expert_observations_ph\")\n        self.mix_acs_ph = tf.placeholder(action_space.dtype, (None,) + self.actions_shape,\n                                            name=\"expert_actions_ph\")\n\n        if self.normalize:\n            with tf.variable_scope(\"obfilter\"):\n                self.obs_rms = MpiRunningMeanStd(shape=self.observation_shape)\n\n        # Build graph\n        policy_rewards = self.build_graph(self.policy_obs_ph, self.policy_acs_ph, reuse=False, scope=self.scope)\n        expert_rewards = self.build_graph(self.expert_obs_ph, self.expert_acs_ph, reuse=True, scope=self.scope)\n        old_policy_rewards = self.build_graph(self.policy_obs_ph, self.policy_acs_ph, reuse=False, scope=\"oldreward\")\n        old_expert_rewards = self.build_graph(self.expert_obs_ph, self.expert_acs_ph, reuse=True, scope=\"oldreward\")\n\n\n        # policy_scaled_rewards = tf.multiply(policy_rewards, self.policy_gammas_ph)\n        policy_scaled_rewards = policy_rewards\n        # policy_value = tf.reduce_sum(policy_scaled_rewards)\n        policy_value = tf.reduce_mean(policy_scaled_rewards)\n        # expert_scaled_rewards = tf.multiply(expert_rewards, self.expert_gammas_ph)\n        expert_scaled_rewards = expert_rewards\n        # expert_value = tf.reduce_sum(expert_scaled_rewards)\n        expert_value = tf.reduce_mean(expert_scaled_rewards)\n\n\n        mixture_rewards = self.build_graph(self.mix_obs_ph, self.mix_acs_ph, reuse=True, scope=self.scope)\n        grads = tf.gradients(mixture_rewards, [self.mix_obs_ph, self.mix_acs_ph])[0]\n        norm = tf.cast(tf.sqrt(tf.reduce_sum(tf.square(grads), axis=1)), tf.float32)\n        lipschitz_reg = tf.reduce_mean(tf.square(norm - 1.0))\n        lipschitz_loss = lipschitz_reg_coef * lipschitz_reg\n        #\n\n        rewards = tf.concat([policy_rewards, expert_rewards], 0)\n\n        policy_clipped_rewards = tf.clip_by_value(policy_rewards, -10.0, 10.0)\n        expert_clipped_rewards = tf.clip_by_value(expert_rewards, -10.0, 10.0)\n        clipped_rewards = tf.concat([policy_clipped_rewards, expert_clipped_rewards], 0)\n\n        #\n        # rewards_reg = - tf.reduce_mean(logit_bernoulli_entropy(rewards))\n        # rewards_reg_coef = 0.001\n        #\n        # rewards_reg = tf.reduce_sum(tf.square(rewards))\n\n        # rewards_reg_coef = 0.01\n\n        old_rewards = tf.concat([old_policy_rewards, old_expert_rewards], 0)\n\n        old_policy_clipped_rewards = tf.clip_by_value(old_policy_rewards, -10.0, 10.0)\n        old_expert_clipped_rewards = tf.clip_by_value(old_expert_rewards, -10.0, 10.0)\n        old_clipped_rewards = tf.concat([old_policy_clipped_rewards, old_expert_clipped_rewards], 0)\n\n        # bregman = tf.reduce_mean(tf_util.huber_loss(old_clipped_rewards - rewards))\n        bregman = tf.reduce_mean(tf.square(tf.stop_gradient(old_clipped_rewards) - rewards))\n\n        bregman_coeff = 100\n        bregman_loss = bregman_coeff * bregman\n\n        #\n        # stepsize = 0.001\n\n\n        # old_policy_loss = tf.reduce_mean(tf.multiply(old_policy_rewards, self.policy_gammas_ph))\\\n        #                   - tf.reduce_mean(tf.multiply(old_expert_rewards, self.expert_gammas_ph))\n\n        new_policy_loss = tf.reduce_mean(tf.multiply(policy_rewards, self.policy_gammas_ph))\\\n                          - tf.reduce_mean(tf.multiply(expert_rewards, self.expert_gammas_ph))\n\n        old_policy_loss = tf.reduce_mean(old_policy_rewards) - tf.reduce_mean(old_expert_rewards)\n        old_rewards_gradient = tf.concat(tf.gradients(old_policy_loss, [old_policy_rewards, old_expert_rewards]), axis=0)\n\n        policy_loss = tf.reduce_sum(tf.multiply(tf.stop_gradient(old_rewards_gradient), clipped_rewards))\n\n        rewards_reg = - tf.reduce_mean(logit_bernoulli_entropy(rewards))\n        rewards_reg_coeff = 0.001\n        # rewards_reg = tf.reduce_mean(tf.square(rewards))\n        # rewards_reg = tf.reduce_mean(tf_util.huber_loss(rewards))\n        # rewards_reg_coeff = 0\n        rewards_reg_loss = rewards_reg_coeff * rewards_reg\n\n        # rewards_reg_loss = rewards_reg_coef * rewards_reg\n        # policy_loss = policy_value - exp  ert_value\n        self.total_loss = policy_loss + bregman_loss + rewards_reg_loss + lipschitz_loss\n\n        # Loss + Accuracy terms\n        self.losses = []\n        self.loss_name = [\"generator_loss\", \"expert_loss\", \"entropy\", \"entropy_loss\", \"generator_acc\", \"expert_acc\"]\n        # Build Reward for policy\n        self.reward_op = tf.stop_gradient(old_policy_clipped_rewards)\n        # self.reward_op = old_policy_rewards\n\n        # self.reward_op = tf.clip_by_value(policy_rewards, -1.0, 1.0)\n        # self.reward_op = generator_rewards\n\n\n\n\n        self.update_old_rewards = \\\n            tf_util.function([], [], updates=[tf.assign(oldv, newv) for (oldv, newv) in\n                                              zipsame(tf_util.get_globals_vars(\"oldreward\"),\n                                                      tf_util.get_globals_vars(self.scope))])\n\n        var_list = self.get_trainable_variables()\n\n        # clip_weights = [tf.assign(var, tf.clip_by_value(var,  -0.5, 0.5)) for var in var_list]\n        clip_weights = tf.no_op()\n        self.clip_weights = tf_util.function([], [clip_weights])\n\n        # rewards_optimizer = tf.train.AdamOptimizer(learning_rate=3e-5)\n        # grads, vars = zip(*rewards_optimizer.compute_gradients(self.total_loss, var_list=var_list))\n        # rewards_train_op = rewards_optimizer.apply_gradients(zip(grads, vars))\n\n        linear_approximation = tf.stop_gradient(tf.reduce_sum(tf.multiply(old_rewards_gradient, rewards - old_rewards)))\n\n\n        grads = tf.gradients(self.total_loss, var_list)\n        grads, norm = tf.clip_by_global_norm(grads, 1e7)\n\n\n        # self.train = tf_util.function(\n        #     [self.policy_obs_ph, self.policy_acs_ph, self.policy_gammas_ph,\n        #      self.expert_obs_ph, self.expert_acs_ph, self.expert_gammas_ph,\n        #      self.mix_obs_ph, self.mix_acs_ph], [rewards_train_op, print_op])\n\n        loss_op = tf.concat(axis=0, values=[tf.reshape(grad if grad is not None else tf.zeros_like(v), [tf_util.numel(v)])\n                                            for (v, grad) in zip(var_list, grads)])\n\n        print_op = tf.print(\"Policy Loss:\", new_policy_loss, \"Bregman:\", bregman_loss,\n                            \"MD objective\",  linear_approximation + bregman_loss,\n                            \"GradNorm\", norm,\n                            \"Loss norm\", tf.norm(old_rewards_gradient),\n                            \"averageEnt\", rewards_reg_loss,\n                            \"mean\", tf.reduce_mean(tf.abs(rewards)), \"std\", tf.math.reduce_std(rewards),\n                            \"max\", tf.math.reduce_max(tf.abs(rewards)))\n\n        self.lossandgrad = tf_util.function(\n            [self.policy_obs_ph, self.policy_acs_ph, self.policy_gammas_ph,\n             self.expert_obs_ph, self.expert_acs_ph, self.expert_gammas_ph,\n             self.mix_obs_ph, self.mix_acs_ph],\n             # self.losses + [tf_util.flatgrad(self.total_loss, var_list)]) #, clip_norm=0.5, clip_by_global_norm=True)])\n             self.losses + [print_op] + [loss_op])\n\n\n\n\n        # print_op = tf.print(\"Value diff:\", policy_value - expert_value, \"Grad Regularizer:\", lipschitz_reg)\n        # print_op = tf.no_op()\n        # self.train = tf_util.function(\n        #     [self.policy_obs_ph, self.policy_acs_ph, self.policy_gammas_ph,\n        #      self.expert_obs_ph, self.expert_acs_ph, self.expert_gammas_ph,\n        #      s, [rewards_train_op, print_op])\n\n\n    def build_graph(self, obs_ph, acs_ph, reuse=False, scope=None):\n        \"\"\"\n        build the graph\n\n        :param obs_ph: (tf.Tensor) the observation placeholder\n        :param acs_ph: (tf.Tensor) the action placeholder\n        :param reuse: (bool)\n        :return: (tf.Tensor) the graph output\n        \"\"\"\n        with tf.variable_scope(scope):\n            if reuse:\n                tf.get_variable_scope().reuse_variables()\n\n            if self.normalize:\n                obs = (tf.cast(obs_ph, tf.float32) - self.obs_rms.mean) / tf.cast(self.obs_rms.std, tf.float32)\n            else:\n                obs = tf.cast(obs_ph, tf.float32)\n\n            if self.discrete_actions:\n                one_hot_actions = tf.one_hot(acs_ph, self.n_actions)\n                actions_ph = tf.cast(one_hot_actions, tf.float32)\n            else:\n                actions_ph = acs_ph\n\n                _input = tf.concat([obs, actions_ph], axis=1)  # concatenate the two input -> form a transition\n                p_h1 = tf.contrib.layers.fully_connected(_input, self.hidden_size, activation_fn=tf.nn.tanh)\n                p_h2 = tf.contrib.layers.fully_connected(p_h1, self.hidden_size, activation_fn=tf.nn.tanh)\n                # rewards = tf.contrib.layers.fully_connected(p_h2, 1, activation_fn=tf.nn.tanh)\n                # rewards = tf.contrib.layers.fully_connected(p_h2, 1, activation_fn=tf.math.sigmoid)\n                rewards = tf.contrib.layers.fully_connected(p_h2, 1, activation_fn=tf.identity)\n                # last_layer_init = tf.contrib.layers.variance_scaling_initializer(factor=0.01, mode='FAN_AVG', uniform=True)\n                # rewards = tf.contrib.layers.fully_connected(p_h2, 1, activation_fn=tf.identity, weights_initializer=last_layer_init)\n\n        return rewards\n\n    def get_trainable_variables(self):\n        \"\"\"\n        Get all the trainable variables from the graph\n\n        :return: ([tf.Tensor]) the variables\n        \"\"\"\n        return tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, self.scope)# + tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, \"oldreward\")\n\n    def get_reward(self, obs, actions):\n        \"\"\"\n        Predict the reward using the observation and action\n\n        :param obs: (tf.Tensor or np.ndarray) the observation\n        :param actions: (tf.Tensor or np.ndarray) the action\n        :return: (np.ndarray) the reward\n        \"\"\"\n        # sess = tf.get_default_session()\n        if len(obs.shape) == 1:\n            obs = np.expand_dims(obs, 0)\n        if len(actions.shape) == 1:\n            actions = np.expand_dims(actions, 0)\n        elif len(actions.shape) == 0:\n            # one discrete action\n            actions = np.expand_dims(actions, 0)\n\n        feed_dict = {self.policy_obs_ph: obs, self.policy_acs_ph: actions}\n        reward = self.sess.run(self.reward_op, feed_dict)\n        return reward\n", "meta": {"hexsha": "193ccce92a9589bf0c167414dc73fdd932ed83f4", "size": 60764, "ext": "py", "lang": "Python", "max_stars_repo_path": "stable_baselines/mdal/adversary.py", "max_stars_repo_name": "shanlior/OAL", "max_stars_repo_head_hexsha": "39c9eb24f64a27d3da09e92b6da9bf60326baabe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-04-08T12:49:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T00:53:47.000Z", "max_issues_repo_path": "stable_baselines/mdal/adversary.py", "max_issues_repo_name": "shanlior/OAL", "max_issues_repo_head_hexsha": "39c9eb24f64a27d3da09e92b6da9bf60326baabe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stable_baselines/mdal/adversary.py", "max_forks_repo_name": "shanlior/OAL", "max_forks_repo_head_hexsha": "39c9eb24f64a27d3da09e92b6da9bf60326baabe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.1618122977, "max_line_length": 161, "alphanum_fraction": 0.6444605358, "include": true, "reason": "import numpy", "num_tokens": 13848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.16844720649466663}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport logging\nimport numpy as np\nimport astropy.units as u\nfrom astropy.io import fits\nfrom astropy.nddata.utils import NoOverlapError\nfrom astropy.table import Table\nfrom astropy.utils import lazyproperty\nfrom regions import CircleSkyRegion\nfrom gammapy.cube.edisp_map import EDispMap\nfrom gammapy.cube.psf_kernel import PSFKernel\nfrom gammapy.cube.psf_map import PSFMap\nfrom gammapy.data import GTI\nfrom gammapy.irf import EffectiveAreaTable, EDispKernel\nfrom gammapy.maps import Map, MapAxis\nfrom gammapy.modeling import Dataset, Parameters\nfrom gammapy.modeling.models import BackgroundModel, SkyModel, SkyModels\nfrom gammapy.modeling.parameter import _get_parameters_str\nfrom gammapy.spectrum import SpectrumDataset, SpectrumDatasetOnOff\nfrom gammapy.stats import cash, cash_sum_cython, wstat\nfrom gammapy.utils.random import get_random_state\nfrom gammapy.utils.scripts import make_path\nfrom .exposure import _map_spectrum_weight\n\n__all__ = [\"MapDataset\", \"MapDatasetOnOff\"]\n\nlog = logging.getLogger(__name__)\n\nCUTOUT_MARGIN = 0.1 * u.deg\nRAD_MAX = 0.66\nRAD_AXIS_DEFAULT = MapAxis.from_bounds(\n    0, RAD_MAX, nbin=66, node_type=\"edges\", name=\"theta\", unit=\"deg\"\n)\nMIGRA_AXIS_DEFAULT = MapAxis.from_bounds(\n    0.2, 5, nbin=48, node_type=\"edges\", name=\"migra\"\n)\n\nBINSZ_IRF_DEFAULT = 0.2\n\n\nclass MapDataset(Dataset):\n    \"\"\"Perform sky model likelihood fit on maps.\n\n    Parameters\n    ----------\n    models : `~gammapy.modeling.models.SkyModels`\n        Source sky models.\n    counts : `~gammapy.maps.WcsNDMap`\n        Counts cube\n    exposure : `~gammapy.maps.WcsNDMap`\n        Exposure cube\n    mask_fit : `~gammapy.maps.WcsNDMap`\n        Mask to apply to the likelihood for fitting.\n    psf : `~gammapy.cube.PSFKernel` or `~gammapy.cube.PSFMap`\n        PSF kernel\n    edisp : `~gammapy.irf.EDispKernel` or `~gammapy.cube.EDispMap`\n        Energy dispersion kernel\n    background_model : `~gammapy.modeling.models.BackgroundModel`\n        Background model to use for the fit.\n    evaluation_mode : {\"local\", \"global\"}\n        Model evaluation mode.\n        The \"local\" mode evaluates the model components on smaller grids to save computation time.\n        This mode is recommended for local optimization algorithms.\n        The \"global\" evaluation mode evaluates the model components on the full map.\n        This mode is recommended for global optimization algorithms.\n    mask_safe : `~gammapy.maps.WcsNDMap`\n        Mask defining the safe data range.\n    gti : `~gammapy.data.GTI`\n        GTI of the observation or union of GTI if it is a stacked observation\n    \"\"\"\n\n    likelihood_type = \"cash\"\n    tag = \"MapDataset\"\n\n    def __init__(\n        self,\n        models=None,\n        counts=None,\n        exposure=None,\n        mask_fit=None,\n        psf=None,\n        edisp=None,\n        background_model=None,\n        name=\"\",\n        evaluation_mode=\"local\",\n        mask_safe=None,\n        gti=None,\n    ):\n        if mask_fit is not None and mask_fit.data.dtype != np.dtype(\"bool\"):\n            raise ValueError(\"mask data must have dtype bool\")\n        if mask_safe is not None and mask_safe.data.dtype != np.dtype(\"bool\"):\n            raise ValueError(\"mask data must have dtype bool\")\n\n        self.evaluation_mode = evaluation_mode\n        self.counts = counts\n        self.exposure = exposure\n        self.mask_fit = mask_fit\n        self.psf = psf\n        self.edisp = edisp\n        self.background_model = background_model\n        self.models = models\n        self.name = name\n        self.mask_safe = mask_safe\n        self.gti = gti\n\n    def __str__(self):\n        str_ = f\"{self.__class__.__name__}\\n\"\n        str_ += \"\\n\"\n\n        str_ += \"\\t{:32}: {} \\n\\n\".format(\"Name\", self.name)\n\n        counts = np.nan\n        if self.counts is not None:\n            counts = np.sum(self.counts.data)\n        str_ += \"\\t{:32}: {:.0f} \\n\".format(\"Total counts\", counts)\n\n        npred = np.nan\n        if self.models is not None or self.background_model is not None:\n            npred = np.sum(self.npred().data)\n        str_ += \"\\t{:32}: {:.2f}\\n\".format(\"Total predicted counts\", npred)\n\n        background = np.nan\n        if self.background_model is not None:\n            background = np.sum(self.background_model.evaluate().data)\n        str_ += \"\\t{:32}: {:.2f}\\n\\n\".format(\"Total background counts\", background)\n\n        exposure_min, exposure_max, exposure_unit = np.nan, np.nan, \"\"\n        if self.exposure is not None:\n            mask = self.mask_safe.reduce_over_axes(np.logical_or).data\n            if not mask.any():\n                mask = None\n            exposure_min = np.min(self.exposure.data[..., mask])\n            exposure_max = np.max(self.exposure.data[..., mask])\n            exposure_unit = self.exposure.unit\n\n        str_ += \"\\t{:32}: {:.2e} {}\\n\".format(\n            \"Exposure min\", exposure_min, exposure_unit\n        )\n        str_ += \"\\t{:32}: {:.2e} {}\\n\\n\".format(\n            \"Exposure max\", exposure_max, exposure_unit\n        )\n\n        # data section\n        n_bins = 0\n        if self.counts is not None:\n            n_bins = self.counts.data.size\n        str_ += \"\\t{:32}: {} \\n\".format(\"Number of total bins\", n_bins)\n\n        n_fit_bins = 0\n        if self.mask is not None:\n            n_fit_bins = np.sum(self.mask.data)\n        str_ += \"\\t{:32}: {} \\n\\n\".format(\"Number of fit bins\", n_fit_bins)\n\n        # likelihood section\n        str_ += \"\\t{:32}: {}\\n\".format(\"Fit statistic type\", self.likelihood_type)\n\n        stat = np.nan\n        if self.counts is not None and (\n            self.models is not None or self.background_model is not None\n        ):\n            stat = self.stat_sum()\n        str_ += \"\\t{:32}: {:.2f}\\n\\n\".format(\"Fit statistic value (-2 log(L))\", stat)\n\n        # model section\n        n_models = 0\n        if self.models is not None:\n            n_models = len(self.models)\n\n        if self.background_model is not None:\n            n_models += 1\n\n        str_ += \"\\t{:32}: {} \\n\".format(\"Number of models\", n_models)\n\n        str_ += \"\\t{:32}: {}\\n\".format(\"Number of parameters\", len(self.parameters))\n        str_ += \"\\t{:32}: {}\\n\\n\".format(\n            \"Number of free parameters\", len(self.parameters.free_parameters)\n        )\n\n        components = []\n\n        if self.models is not None:\n            components += self.models\n\n        if self.background_model is not None:\n            components += [self.background_model]\n\n        for idx, model in enumerate(components):\n            str_ += f\"\\tComponent {idx}: \\n\"\n            str_ += \"\\t\\t{:28}: {}\\n\".format(\"Name\", model.name)\n            str_ += \"\\t\\t{:28}: {}\\n\".format(\"Type\", model.__class__.__name__)\n\n            if isinstance(model, SkyModel):\n                str_ += \"\\t\\t{:28}: {}\\n\".format(\n                    \"Spatial  model type\", model.spatial_model.__class__.__name__\n                )\n                str_ += \"\\t\\t{:28}: {}\\n\".format(\n                    \"Spectral model type\", model.spectral_model.__class__.__name__\n                )\n\n            str_ += \"\\t\\tParameters:\\n\"\n            info = _get_parameters_str(model.parameters)\n            lines = info.split(\"\\n\")\n            str_ += \"\\t\\t\" + \"\\n\\t\\t\".join(lines[:-1])\n\n            str_ += \"\\n\\n\"\n\n        return str_.expandtabs(tabsize=4)\n\n    @property\n    def models(self):\n        \"\"\"Models (`~gammapy.modeling.models.SkyModels`).\"\"\"\n        return self._models\n\n    @models.setter\n    def models(self, value):\n        if value is None or isinstance(value, SkyModels):\n            models = value\n        elif isinstance(value, SkyModel):\n            models = SkyModels([value])\n        else:\n            raise TypeError(f\"Invalid: {value!r}\")\n\n        self._models = models\n\n        self._make_evaluators()\n\n    def _make_evaluators(self):\n        if self.models is None:\n            self._evaluators = []\n            return\n\n        evaluators = []\n        for model in self.models:\n            evaluator = MapEvaluator(model, evaluation_mode=self.evaluation_mode)\n            evaluator.update(self.exposure, self.psf, self.edisp, self._geom)\n            evaluators.append(evaluator)\n\n        self._evaluators = evaluators\n\n    @property\n    def parameters(self):\n        \"\"\"List of parameters (`~gammapy.modeling.Parameters`)\"\"\"\n        parameters_list = []\n\n        if self.models:\n            parameters_list.append(self.models.parameters)\n\n        if self.background_model:\n            parameters_list.append(self.background_model.parameters)\n\n        return Parameters.from_stack(parameters_list)\n\n    @property\n    def _geom(self):\n        if self.counts is not None:\n            return self.counts.geom\n        elif self.background_model is not None:\n            return self.background_model.map.geom\n        elif self.exposure:\n            return self.exposure.geom\n        else:\n            raise ValueError(\"No map available to extract shape\")\n\n    @property\n    def _energy_axis(self):\n        return self._geom.get_axis_by_name(\"energy\")\n\n    @property\n    def data_shape(self):\n        \"\"\"Shape of the counts or background data (tuple)\"\"\"\n        return self._geom.data_shape\n\n    def npred(self):\n        \"\"\"Predicted source and background counts (`~gammapy.maps.Map`).\"\"\"\n        npred_total = Map.from_geom(self._geom, dtype=float)\n\n        if self.background_model:\n            npred_total += self.background_model.evaluate()\n\n        if self.models:\n            for evaluator in self._evaluators:\n                # if the model component drifts out of its support the evaluator has\n                # has to be updated\n                if evaluator.needs_update:\n                    evaluator.update(self.exposure, self.psf, self.edisp, self._geom)\n\n                if evaluator.contributes:\n                    npred = evaluator.compute_npred()\n                    npred_total.stack(npred)\n\n        return npred_total\n\n    @classmethod\n    def from_geoms(\n        cls,\n        geom,\n        geom_exposure,\n        geom_psf,\n        geom_edisp,\n        reference_time=\"2000-01-01\",\n        name=\"\",\n        **kwargs,\n    ):\n        \"\"\"\n        Create a MapDataset object with zero filled maps according to the specified geometries\n\n        Parameters\n        ----------\n        geom : `Geom`\n            geometry for the counts and background maps\n        geom_exposure : `Geom`\n            geometry for the exposure map\n        geom_psf : `Geom`\n            geometry for the psf map\n        geom_edisp : `Geom`\n            geometry for the energy dispersion map\n        reference_time : `~astropy.time.Time`\n            the reference time to use in GTI definition\n        name : str\n            Name of the dataset.\n\n        Returns\n        -------\n        empty_maps : `MapDataset`\n            A MapDataset containing zero filled maps\n        \"\"\"\n        counts = Map.from_geom(geom, unit=\"\")\n\n        background = Map.from_geom(geom, unit=\"\")\n        background_model = BackgroundModel(background)\n\n        exposure = Map.from_geom(geom_exposure, unit=\"m2 s\")\n        edisp = EDispMap.from_geom(geom_edisp)\n        psf = PSFMap.from_geom(geom_psf)\n\n        gti = GTI.create([] * u.s, [] * u.s, reference_time=reference_time)\n\n        mask_safe = Map.from_geom(geom, unit=\"\", dtype=bool)\n\n        return cls(\n            counts=counts,\n            exposure=exposure,\n            psf=psf,\n            edisp=edisp,\n            background_model=background_model,\n            gti=gti,\n            mask_safe=mask_safe,\n            name=name,\n            **kwargs,\n        )\n\n    @classmethod\n    def create(\n        cls,\n        geom,\n        energy_axis_true=None,\n        migra_axis=None,\n        rad_axis=None,\n        binsz_irf=None,\n        reference_time=\"2000-01-01\",\n        name=\"\",\n        **kwargs,\n    ):\n        \"\"\"Create a MapDataset object with zero filled maps.\n\n        Parameters\n        ----------\n        geom : `~gammapy.maps.WcsGeom`\n            Reference target geometry in reco energy, used for counts and background maps\n        energy_axis_true : `~gammapy.maps.MapAxis`\n            True energy axis used for IRF maps\n        migra_axis : `~gammapy.maps.MapAxis`\n            Migration axis for the energy dispersion map\n        rad_axis : `~gammapy.maps.MapAxis`\n            Rad axis for the psf map\n        binsz_irf : float\n            IRF Map pixel size in degrees.\n        reference_time : `~astropy.time.Time`\n            the reference time to use in GTI definition\n        name : str\n            Name of the dataset.\n\n        Returns\n        -------\n        empty_maps : `MapDataset`\n            A MapDataset containing zero filled maps\n        \"\"\"\n        migra_axis = migra_axis or MIGRA_AXIS_DEFAULT\n        rad_axis = rad_axis or RAD_AXIS_DEFAULT\n        energy_axis_true = energy_axis_true or geom.get_axis_by_name(\"energy\")\n        binsz_irf = binsz_irf or BINSZ_IRF_DEFAULT\n\n        geom_image = geom.to_image()\n        geom_exposure = geom_image.to_cube([energy_axis_true])\n        geom_irf = geom_image.to_binsz(binsz=binsz_irf)\n        geom_psf = geom_irf.to_cube([rad_axis, energy_axis_true])\n        geom_edisp = geom_irf.to_cube([migra_axis, energy_axis_true])\n\n        return cls.from_geoms(\n            geom,\n            geom_exposure,\n            geom_psf,\n            geom_edisp,\n            reference_time=reference_time,\n            name=name,\n            **kwargs,\n        )\n\n    def stack(self, other):\n        \"\"\"Stack another dataset in place.\n\n        Parameters\n        ----------\n        other: `~gammapy.cube.MapDataset`\n            Map dataset to be stacked with this one.\n        \"\"\"\n\n        if self.counts and other.counts:\n            self.counts *= self.mask_safe\n            self.counts.stack(other.counts, weights=other.mask_safe)\n\n        if self.exposure and other.exposure:\n            mask_image = self.mask_safe.reduce_over_axes(func=np.logical_or)\n            self.exposure *= mask_image.data\n            # TODO: apply energy dependent mask to exposure. Does this require\n            #  a mask_safe in true energy?\n            mask_image_other = other.mask_safe.reduce_over_axes(func=np.logical_or)\n            self.exposure.stack(other.exposure, weights=mask_image_other)\n\n        if self.background_model and other.background_model:\n            bkg = self.background_model.evaluate()\n            bkg *= self.mask_safe\n            other_bkg = other.background_model.evaluate()\n            bkg.stack(other_bkg, weights=other.mask_safe)\n\n            self.background_model = BackgroundModel(\n                bkg, name=self.background_model.name\n            )\n\n        if self.mask_safe is not None and other.mask_safe is not None:\n            self.mask_safe.stack(other.mask_safe)\n\n        if self.psf and other.psf:\n            if isinstance(self.psf, PSFMap) and isinstance(other.psf, PSFMap):\n                mask_irf = self._mask_safe_irf(self.psf.psf_map, mask_image)\n                self.psf.psf_map *= mask_irf.data\n                self.psf.exposure_map *= mask_irf.data\n\n                mask_image_other = other.mask_safe.reduce_over_axes(func=np.logical_or)\n                mask_irf_other = self._mask_safe_irf(\n                    other.psf.psf_map, mask_image_other\n                )\n                self.psf.stack(other.psf, weights=mask_irf_other)\n            else:\n                raise ValueError(\"Stacking of PSF kernels not supported\")\n\n        if self.edisp and other.edisp:\n            if isinstance(self.edisp, EDispMap) and isinstance(other.edisp, EDispMap):\n                mask_irf = self._mask_safe_irf(self.edisp.edisp_map, mask_image)\n                self.edisp.edisp_map *= mask_irf.data\n                self.edisp.exposure_map *= mask_irf.data\n\n                mask_image_other = other.mask_safe.reduce_over_axes(func=np.logical_or)\n                mask_irf_other = self._mask_safe_irf(\n                    other.edisp.edisp_map, mask_image_other\n                )\n                self.edisp.stack(other.edisp, weights=mask_irf_other)\n            else:\n                raise ValueError(\"Stacking of edisp kernels not supported\")\n\n        if self.gti and other.gti:\n            self.gti = self.gti.stack(other.gti).union()\n\n    @staticmethod\n    def _mask_safe_irf(irf_map, mask):\n        geom = irf_map.geom.to_image()\n        coords = geom.get_coord()\n        data = mask.get_by_coord(coords).astype(bool)\n        return Map.from_geom(geom=geom, data=data)\n\n    def stat_array(self):\n        \"\"\"Likelihood per bin given the current model parameters\"\"\"\n        return cash(n_on=self.counts.data, mu_on=self.npred().data)\n\n    def residuals(self, method=\"diff\"):\n        \"\"\"Compute residuals map.\n\n        Parameters\n        ----------\n        method: {\"diff\", \"diff/model\", \"diff/sqrt(model)\"}\n            Method used to compute the residuals. Available options are:\n                - \"diff\" (default): data - model\n                - \"diff/model\": (data - model) / model\n                - \"diff/sqrt(model)\": (data - model) / sqrt(model)\n\n        Returns\n        -------\n        residuals : `gammapy.maps.WcsNDMap`\n            Residual map.\n        \"\"\"\n        return self._compute_residuals(self.counts, self.npred(), method=method)\n\n    def plot_residuals(\n        self,\n        method=\"diff\",\n        smooth_kernel=\"gauss\",\n        smooth_radius=\"0.1 deg\",\n        region=None,\n        figsize=(12, 4),\n        **kwargs,\n    ):\n        \"\"\"\n        Plot spatial and spectral residuals.\n\n        The spectral residuals are extracted from the provided region, and the\n        normalization used for the residuals computation can be controlled using\n        the method parameter. If no region is passed, only the spatial\n        residuals are shown.\n\n        Parameters\n        ----------\n        method : {\"diff\", \"diff/model\", \"diff/sqrt(model)\"}\n            Method used to compute the residuals, see `MapDataset.residuals()`\n        smooth_kernel : {'gauss', 'box'}\n            Kernel shape.\n        smooth_radius: `~astropy.units.Quantity`, str or float\n            Smoothing width given as quantity or float. If a float is given it\n            is interpreted as smoothing width in pixels.\n        region: `~regions.Region`\n            Region (pixel or sky regions accepted)\n        figsize : tuple\n            Figure size used for the plotting.\n        **kwargs : dict\n            Keyword arguments passed to `~matplotlib.pyplot.imshow`.\n\n        Returns\n        -------\n        ax_image, ax_spec : `~matplotlib.pyplot.Axes`,\n            Image and spectrum axes.\n        \"\"\"\n        import matplotlib.pyplot as plt\n\n        fig = plt.figure(figsize=figsize)\n\n        counts, npred = self.counts, self.npred()\n\n        if self.mask is not None:\n            counts = counts * self.mask\n            npred = npred * self.mask\n\n        counts_spatial = counts.sum_over_axes().smooth(\n            width=smooth_radius, kernel=smooth_kernel\n        )\n        npred_spatial = npred.sum_over_axes().smooth(\n            width=smooth_radius, kernel=smooth_kernel\n        )\n        spatial_residuals = self._compute_residuals(\n            counts_spatial, npred_spatial, method\n        )\n\n        if self.mask_safe is not None:\n            mask = self.mask_safe.reduce_over_axes(func=np.logical_or)\n            spatial_residuals.data[~mask.data] = np.nan\n\n        # If no region is provided, skip spectral residuals\n        ncols = 2 if region is not None else 1\n        ax_image = fig.add_subplot(1, ncols, 1, projection=spatial_residuals.geom.wcs)\n        ax_spec = None\n\n        kwargs.setdefault(\"cmap\", \"coolwarm\")\n        kwargs.setdefault(\"stretch\", \"linear\")\n        kwargs.setdefault(\"vmin\", -5)\n        kwargs.setdefault(\"vmax\", 5)\n        spatial_residuals.plot(ax=ax_image, add_cbar=True, **kwargs)\n\n        # Spectral residuals\n        if region:\n            ax_spec = fig.add_subplot(1, 2, 2)\n            counts_spec = counts.get_spectrum(region=region)\n            npred_spec = npred.get_spectrum(region=region)\n            residuals = self._compute_residuals(counts_spec, npred_spec, method)\n            ax = residuals.plot()\n            ax.axhline(0, color=\"black\", lw=0.5)\n\n            y_max = 2 * np.nanmax(residuals.data)\n            plt.ylim(-y_max, y_max)\n            label = self._residuals_labels[method]\n            plt.ylabel(f\"Residuals ({label})\")\n\n            # Overlay spectral extraction region on the spatial residuals\n            pix_region = region.to_pixel(wcs=spatial_residuals.geom.wcs)\n            pix_region.plot(ax=ax_image)\n\n        return ax_image, ax_spec\n\n    @lazyproperty\n    def _counts_data(self):\n        return self.counts.data.astype(float)\n\n    def stat_sum(self):\n        \"\"\"Total likelihood given the current model parameters.\"\"\"\n        counts, npred = self._counts_data, self.npred().data\n\n        if self.mask is not None:\n            return cash_sum_cython(counts[self.mask.data], npred[self.mask.data])\n        else:\n            return cash_sum_cython(counts.ravel(), npred.ravel())\n\n    def fake(self, random_state=\"random-seed\"):\n        \"\"\"Simulate fake counts for the current model and reduced IRFs.\n\n        This method overwrites the counts defined on the dataset object.\n\n        Parameters\n        ----------\n        random_state : {int, 'random-seed', 'global-rng', `~numpy.random.RandomState`}\n                Defines random number generator initialisation.\n                Passed to `~gammapy.utils.random.get_random_state`.\n        \"\"\"\n        random_state = get_random_state(random_state)\n        npred = self.npred()\n        npred.data = random_state.poisson(npred.data)\n        self.counts = npred\n\n    def to_hdulist(self):\n        \"\"\"Convert map dataset to list of HDUs.\n\n        Returns\n        -------\n        hdulist : `~astropy.io.fits.HDUList`\n            Map dataset list of HDUs.\n        \"\"\"\n        # TODO: what todo about the model and background model parameters?\n        exclude_primary = slice(1, None)\n\n        hdu_primary = fits.PrimaryHDU()\n        hdulist = fits.HDUList([hdu_primary])\n        if self.counts is not None:\n            hdulist += self.counts.to_hdulist(hdu=\"counts\")[exclude_primary]\n\n        if self.exposure is not None:\n            hdulist += self.exposure.to_hdulist(hdu=\"exposure\")[exclude_primary]\n\n        if self.background_model is not None:\n            hdulist += self.background_model.map.to_hdulist(hdu=\"background\")[\n                exclude_primary\n            ]\n\n        if self.edisp is not None:\n            if isinstance(self.edisp, EDispKernel):\n                hdus = self.edisp.to_hdulist()\n                hdus[\"MATRIX\"].name = \"edisp_matrix\"\n                hdus[\"EBOUNDS\"].name = \"edisp_matrix_ebounds\"\n                hdulist.append(hdus[\"EDISP_MATRIX\"])\n                hdulist.append(hdus[\"EDISP_MATRIX_EBOUNDS\"])\n            else:\n                hdulist += self.edisp.edisp_map.to_hdulist(hdu=\"EDISP\")[exclude_primary]\n                hdulist += self.edisp.exposure_map.to_hdulist(hdu=\"edisp_exposure\")[\n                    exclude_primary\n                ]\n\n        if self.psf is not None:\n            if isinstance(self.psf, PSFKernel):\n                hdulist += self.psf.psf_kernel_map.to_hdulist(hdu=\"psf_kernel\")[\n                    exclude_primary\n                ]\n            else:\n                hdulist += self.psf.psf_map.to_hdulist(hdu=\"psf\")[exclude_primary]\n                hdulist += self.psf.exposure_map.to_hdulist(hdu=\"psf_exposure\")[\n                    exclude_primary\n                ]\n\n        if self.mask_safe is not None:\n            mask_safe_int = self.mask_safe.copy()\n            mask_safe_int.data = mask_safe_int.data.astype(int)\n            hdulist += mask_safe_int.to_hdulist(hdu=\"mask_safe\")[exclude_primary]\n\n        if self.mask_fit is not None:\n            mask_fit_int = self.mask_fit.copy()\n            mask_fit_int.data = mask_fit_int.data.astype(int)\n            hdulist += mask_fit_int.to_hdulist(hdu=\"mask_fit\")[exclude_primary]\n\n        if self.gti is not None:\n            hdulist.append(fits.BinTableHDU(self.gti.table, name=\"GTI\"))\n\n        return hdulist\n\n    @classmethod\n    def from_hdulist(cls, hdulist, name=\"\"):\n        \"\"\"Create map dataset from list of HDUs.\n\n        Parameters\n        ----------\n        hdulist : `~astropy.io.fits.HDUList`\n            List of HDUs.\n\n        Returns\n        -------\n        dataset : `MapDataset`\n            Map dataset.\n        \"\"\"\n        kwargs = {\"name\": name}\n\n        if \"COUNTS\" in hdulist:\n            kwargs[\"counts\"] = Map.from_hdulist(hdulist, hdu=\"counts\")\n\n        if \"EXPOSURE\" in hdulist:\n            kwargs[\"exposure\"] = Map.from_hdulist(hdulist, hdu=\"exposure\")\n\n        if \"BACKGROUND\" in hdulist:\n            background_map = Map.from_hdulist(hdulist, hdu=\"background\")\n            kwargs[\"background_model\"] = BackgroundModel(background_map)\n\n        if \"EDISP_MATRIX\" in hdulist:\n            kwargs[\"edisp\"] = EDispKernel.from_hdulist(\n                hdulist, hdu1=\"EDISP_MATRIX\", hdu2=\"EDISP_MATRIX_EBOUNDS\"\n            )\n        if \"EDISP\" in hdulist:\n            edisp_map = Map.from_hdulist(hdulist, hdu=\"edisp\")\n            exposure_map = Map.from_hdulist(hdulist, hdu=\"edisp_exposure\")\n            kwargs[\"edisp\"] = EDispMap(edisp_map, exposure_map)\n\n        if \"PSF_KERNEL\" in hdulist:\n            psf_map = Map.from_hdulist(hdulist, hdu=\"psf_kernel\")\n            kwargs[\"psf\"] = PSFKernel(psf_map)\n        if \"PSF\" in hdulist:\n            psf_map = Map.from_hdulist(hdulist, hdu=\"psf\")\n            exposure_map = Map.from_hdulist(hdulist, hdu=\"psf_exposure\")\n            kwargs[\"psf\"] = PSFMap(psf_map, exposure_map)\n\n        if \"MASK_SAFE\" in hdulist:\n            mask_safe = Map.from_hdulist(hdulist, hdu=\"mask_safe\")\n            mask_safe.data = mask_safe.data.astype(bool)\n            kwargs[\"mask_safe\"] = mask_safe\n\n        if \"MASK_FIT\" in hdulist:\n            mask_fit = Map.from_hdulist(hdulist, hdu=\"mask_fit\")\n            mask_fit.data = mask_fit.data.astype(bool)\n            kwargs[\"mask_fit\"] = mask_fit\n\n        if \"GTI\" in hdulist:\n            gti = GTI(Table.read(hdulist, hdu=\"GTI\"))\n            kwargs[\"gti\"] = gti\n\n        return cls(**kwargs)\n\n    def write(self, filename, overwrite=False):\n        \"\"\"Write map dataset to file.\n\n        Parameters\n        ----------\n        filename : str\n            Filename to write to.\n        overwrite : bool\n            Overwrite file if it exists.\n        \"\"\"\n        self.to_hdulist().writeto(make_path(filename), overwrite=overwrite)\n\n    @classmethod\n    def read(cls, filename, name=\"\"):\n        \"\"\"Read map dataset from file.\n\n        Parameters\n        ----------\n        filename : str\n            Filename to read from.\n\n        Returns\n        -------\n        dataset : `MapDataset`\n            Map dataset.\n        \"\"\"\n        with fits.open(make_path(filename), memmap=False) as hdulist:\n            return cls.from_hdulist(hdulist, name=name)\n\n    @classmethod\n    def from_dict(cls, data, components, models):\n        \"\"\"Create from dicts and models list generated from YAML serialization.\"\"\"\n        dataset = cls.read(data[\"filename\"], name=data[\"name\"])\n        bkg_name = data[\"background\"]\n        model_names = data[\"models\"]\n        for component in components[\"components\"]:\n            if component[\"type\"] == \"BackgroundModel\":\n                if component[\"name\"] == bkg_name:\n                    if \"filename\" not in component:\n                        component[\"map\"] = dataset.background_model.map\n                    background_model = BackgroundModel.from_dict(component)\n                    dataset.background_model = background_model\n\n        models_list = [model for model in models if model.name in model_names]\n        dataset.models = SkyModels(models_list)\n        if \"likelihood\" in data:\n            dataset.likelihood_type = data[\"likelihood\"]\n\n        return dataset\n\n    def to_dict(self, filename=\"\"):\n        \"\"\"Convert to dict for YAML serialization.\"\"\"\n        if self.models is None:\n            models = []\n        else:\n            models = [_.name for _ in self.models]\n\n        return {\n            \"name\": self.name,\n            \"type\": self.tag,\n            \"likelihood\": self.likelihood_type,\n            \"models\": models,\n            \"background\": self.background_model.name,\n            \"filename\": str(filename),\n        }\n\n    def to_spectrum_dataset(self, on_region, containment_correction=False):\n        \"\"\"Return a ~gammapy.spectrum.SpectrumDataset from on_region.\n\n        Counts and background are summed in the on_region.\n\n        Effective area is taken from the average exposure divided by the livetime.\n        Here we assume it is the sum of the GTIs.\n\n        The energy dispersion kernel is obtained at the on_region center.\n        Only regions with centers are supported.\n\n        The model is not exported to the ~gammapy.spectrum.SpectrumDataset.\n        It must be set after the dataset extraction.\n        \n        Parameters\n        ----------\n        on_region : `~regions.SkyRegion`\n            the input ON region on which to extract the spectrum\n        containment_correction : bool\n            Apply containment correction for point sources and circular on regions\n\n        Returns\n        -------\n        dataset : `~gammapy.spectrum.SpectrumDataset`\n            the resulting reduced dataset\n        \"\"\"\n        if self.gti is not None:\n            livetime = self.gti.time_sum\n        else:\n            raise ValueError(\"No GTI in `MapDataset`, cannot compute livetime\")\n\n        if self.counts is not None:\n            counts = self.counts.get_spectrum(on_region, np.sum)\n        else:\n            counts = None\n\n        if self.background_model is not None:\n            background = self.background_model.evaluate().get_spectrum(\n                on_region, np.sum\n            )\n        else:\n            background = None\n\n        if self.exposure is not None:\n            exposure = self.exposure.get_spectrum(on_region, np.mean)\n            aeff = EffectiveAreaTable(\n                energy_lo=exposure.energy.edges[:-1],\n                energy_hi=exposure.energy.edges[1:],\n                data=exposure.quantity / livetime,\n            )\n        else:\n            aeff = None\n\n        if containment_correction:\n            if not isinstance(on_region, CircleSkyRegion):\n                raise TypeError(\n                    \"Containement correction is only supported for\"\n                    \" `CircleSkyRegion`.\"\n                )\n            elif self.psf is None or isinstance(self.psf, PSFKernel):\n                raise ValueError(\"No PSFMap set. Containement correction impossible\")\n            else:\n                psf = self.psf.get_energy_dependent_table_psf(on_region.center)\n                containment = psf.containment(aeff.energy.center, self.region.radius)\n                aeff.data.data *= containment.squeeze()\n\n        if self.edisp is not None:\n            if isinstance(self.edisp, EDispKernel):\n                edisp = self.edisp\n            else:\n                edisp = self.edisp.get_edisp_kernel(\n                    on_region.center, self._energy_axis.edges\n                )\n        else:\n            edisp = None\n\n        return SpectrumDataset(\n            counts=counts,\n            background=background,\n            aeff=aeff,\n            edisp=edisp,\n            livetime=livetime,\n            gti=self.gti,\n            name=self.name,\n        )\n\n    def to_image(self, spectrum=None):\n        \"\"\"Create images by summing over the energy axis.\n\n        Exposure is weighted with an assumed spectrum,\n        resulting in a weighted mean exposure image.\n\n        Currently the PSFMap and EdispMap are dropped from the\n        resulting image dataset.\n\n        Parameters\n        ----------\n        spectrum : `~gammapy.modeling.models.SpectralModel`\n            Spectral model to compute the weights.\n            Default is power-law with spectral index of 2.\n\n        Returns\n        -------\n        dataset : `MapDataset`\n            Map dataset containing images.\n        \"\"\"\n        counts = self.counts * self.mask_safe\n        background = self.background_model.evaluate() * self.mask_safe\n\n        counts = counts.sum_over_axes(keepdims=True)\n        exposure = _map_spectrum_weight(self.exposure, spectrum)\n        exposure = exposure.sum_over_axes(keepdims=True)\n        background = background.sum_over_axes(keepdims=True)\n\n        mask_image = self.mask_safe.reduce_over_axes(func=np.logical_or, keepdims=True)\n\n        # TODO: add edisp and psf\n        edisp = None\n\n        if self.psf is not None:\n            psf = self.psf.to_image()\n        else:\n            psf = None\n\n        return self.__class__(\n            counts=counts,\n            exposure=exposure,\n            background_model=BackgroundModel(background),\n            mask_safe=mask_image,\n            edisp=edisp,\n            psf=psf,\n            gti=self.gti,\n            name=self.name,\n        )\n\n    def cutout(self, position, width, mode=\"trim\"):\n        \"\"\"Cutout map dataset.\n\n        Parameters\n        ----------\n        position : `~astropy.coordinates.SkyCoord`\n            Center position of the cutout region.\n        width : tuple of `~astropy.coordinates.Angle`\n            Angular sizes of the region in (lon, lat) in that specific order.\n            If only one value is passed, a square region is extracted.\n        mode : {'trim', 'partial', 'strict'}\n            Mode option for Cutout2D, for details see `~astropy.nddata.utils.Cutout2D`.\n\n        Returns\n        -------\n        cutout : `MapDataset`\n            Cutout map dataset.\n        \"\"\"\n        kwargs = {\"gti\": self.gti}\n        cutout_kwargs = {\"position\": position, \"width\": width, \"mode\": mode}\n\n        if self.counts is not None:\n            kwargs[\"counts\"] = self.counts.cutout(**cutout_kwargs)\n\n        if self.exposure is not None:\n            kwargs[\"exposure\"] = self.exposure.cutout(**cutout_kwargs)\n\n        if self.background_model is not None:\n            bkg_map = self.background_model.map.cutout(**cutout_kwargs)\n            bkg_model = BackgroundModel(bkg_map)\n            factors = [par.factor for par in self.background_model.parameters]\n            bkg_model.parameters.set_parameter_factors(factors)\n            kwargs[\"background_model\"] = bkg_model\n\n        if self.edisp is not None:\n            kwargs[\"edisp\"] = self.edisp.cutout(**cutout_kwargs)\n\n        if self.psf is not None:\n            kwargs[\"psf\"] = self.psf.cutout(**cutout_kwargs)\n\n        if self.mask_safe is not None:\n            kwargs[\"mask_safe\"] = self.mask_safe.cutout(**cutout_kwargs)\n\n        if self.mask_fit is not None:\n            kwargs[\"mask_fit\"] = self.mask_fit.cutout(**cutout_kwargs)\n\n        return self.__class__(**kwargs)\n\n\nclass MapDatasetOnOff(MapDataset):\n    \"\"\"Map dataset for on-off likelihood fitting.\n\n    Parameters\n    ----------\n    models : `~gammapy.modeling.models.SkyModels`\n        Source sky models.\n    counts : `~gammapy.maps.WcsNDMap`\n        Counts cube\n    counts_off : `~gammapy.maps.WcsNDMap`\n        Ring-convolved counts cube\n    acceptance : `~gammapy.maps.WcsNDMap`\n        Acceptance from the IRFs\n    acceptance_off : `~gammapy.maps.WcsNDMap`\n        Acceptance off\n    exposure : `~gammapy.maps.WcsNDMap`\n        Exposure cube\n    mask_fit : `~numpy.ndarray`\n        Mask to apply to the likelihood for fitting.\n    psf : `~gammapy.cube.PSFKernel`\n        PSF kernel\n    edisp : `~gammapy.irf.EDispKernel`\n        Energy dispersion\n    background_model : `~gammapy.modeling.models.BackgroundModel`\n        Background model to use for the fit.\n    evaluation_mode : {\"local\", \"global\"}\n        Model evaluation mode.\n        The \"local\" mode evaluates the model components on smaller grids to save computation time.\n        This mode is recommended for local optimization algorithms.\n        The \"global\" evaluation mode evaluates the model components on the full map.\n        This mode is recommended for global optimization algorithms.\n    mask_safe : `~numpy.ndarray`\n        Mask defining the safe data range.\n    gti : `~gammapy.data.GTI`\n        GTI of the observation or union of GTI if it is a stacked observation\n    \"\"\"\n\n    likelihood_type = \"wstat\"\n    tag = \"MapDatasetOnOff\"\n\n    def __init__(\n        self,\n        models=None,\n        counts=None,\n        counts_off=None,\n        acceptance=None,\n        acceptance_off=None,\n        exposure=None,\n        mask_fit=None,\n        psf=None,\n        edisp=None,\n        background_model=None,\n        name=\"\",\n        evaluation_mode=\"local\",\n        mask_safe=None,\n        gti=None,\n    ):\n        if mask_fit is not None and mask_fit.dtype != np.dtype(\"bool\"):\n            raise ValueError(\"mask data must have dtype bool\")\n\n        self.evaluation_mode = evaluation_mode\n        self.counts = counts\n        self.counts_off = counts_off\n\n        if np.isscalar(acceptance):\n            acceptance = np.ones(self.data_shape) * acceptance\n\n        if np.isscalar(acceptance_off):\n            acceptance_off = np.ones(self.data_shape) * acceptance_off\n\n        self.acceptance = acceptance\n        self.acceptance_off = acceptance_off\n        self.exposure = exposure\n        self.background_model = None\n        self.mask_fit = mask_fit\n        self.psf = psf\n        self.edisp = edisp\n        self.models = models\n        self.name = name\n        self.mask_safe = mask_safe\n        self.gti = gti\n\n    def __str__(self):\n        str_ = super().__str__()\n\n        counts_off = np.nan\n        if self.counts_off is not None:\n            counts_off = np.sum(self.counts_off.data)\n        str_ += \"\\t{:32}: {:.0f} \\n\".format(\"Total counts_off\", counts_off)\n\n        acceptance = np.nan\n        if self.acceptance is not None:\n            acceptance = np.sum(self.acceptance.data)\n        str_ += \"\\t{:32}: {:.0f} \\n\".format(\"Acceptance\", acceptance)\n\n        acceptance_off = np.nan\n        if self.acceptance_off is not None:\n            acceptance_off = np.sum(self.acceptance_off.data)\n        str_ += \"\\t{:32}: {:.0f} \\n\".format(\"Acceptance off\", acceptance_off)\n\n        return str_.expandtabs(tabsize=4)\n\n    @property\n    def parameters(self):\n        \"\"\"List of parameters (`~gammapy.modeling.Parameters`)\"\"\"\n        parameters = []\n\n        if self.models:\n            parameters += self.models.parameters\n\n        return Parameters(parameters)\n\n    @property\n    def alpha(self):\n        \"\"\"Exposure ratio between signal and background regions\"\"\"\n        alpha = self.acceptance / self.acceptance_off\n        alpha.data = np.nan_to_num(alpha.data)\n        return alpha\n\n    @property\n    def background(self):\n        \"\"\"Predicted background in the on region.\n\n        Notice that this definition is valid under the assumption of cash statistic.\n        \"\"\"\n        return self.alpha * self.counts_off\n\n    @property\n    def excess(self):\n        \"\"\"Excess (counts - alpha * counts_off)\"\"\"\n        return self.counts.data - self.background.data\n\n    def stat_array(self):\n        \"\"\"Likelihood per bin given the current model parameters\"\"\"\n        mu_sig = self.npred().data\n        on_stat_ = wstat(\n            n_on=self.counts.data,\n            n_off=self.counts_off.data,\n            alpha=list(self.alpha.data),\n            mu_sig=mu_sig,\n        )\n        return np.nan_to_num(on_stat_)\n\n    @classmethod\n    def from_geoms(\n        cls,\n        geom,\n        geom_exposure,\n        geom_psf,\n        geom_edisp,\n        reference_time=\"2000-01-01\",\n        name=\"\",\n        **kwargs,\n    ):\n        \"\"\"\n        Create a MapDatasetOnOff object with zero filled maps according to the specified geometries\n\n        Parameters\n        ----------\n        geom : `gammapy.maps.WcsGeom`\n            geometry for the counts, counts_off, acceptance and acceptance_off maps\n        geom_exposure : `gammapy.maps.WcsGeom`\n            geometry for the exposure map\n        geom_psf : `gammapy.maps.WcsGeom`\n            geometry for the psf map\n        geom_edisp : `gammapy.maps.WcsGeom`\n            geometry for the energy dispersion map\n        reference_time : `~astropy.time.Time`\n            the reference time to use in GTI definition\n        name : str\n            Name of the dataset.\n\n        Returns\n        -------\n        empty_maps : `MapDatasetOnOff`\n            A MapDatasetOnOff containing zero filled maps\n        \"\"\"\n        maps = {}\n        for aname in [\"counts\", \"counts_off\", \"acceptance\", \"acceptance_off\"]:\n            maps[aname] = Map.from_geom(geom, unit=\"\")\n\n        exposure = Map.from_geom(geom_exposure, unit=\"m2 s\")\n        edisp = EDispMap.from_geom(geom_edisp)\n        psf = PSFMap.from_geom(geom_psf)\n\n        gti = GTI.create([] * u.s, [] * u.s, reference_time=reference_time)\n\n        mask_safe = Map.from_geom(geom, dtype=bool)\n\n        return cls(\n            counts=maps[\"counts\"],\n            counts_off=maps[\"counts_off\"],\n            acceptance=maps[\"acceptance\"],\n            acceptance_off=maps[\"acceptance_off\"],\n            exposure=exposure,\n            psf=psf,\n            edisp=edisp,\n            gti=gti,\n            mask_safe=mask_safe,\n            name=name,\n            **kwargs,\n        )\n\n    def _is_stackable(self):\n        \"\"\"Check if the Dataset contains enough information to be stacked\"\"\"\n        if (\n            self.acceptance_off is None\n            or self.acceptance is None\n            or self.counts_off is None\n        ):\n            return False\n        else:\n            return True\n\n    def stack(self, other):\n        r\"\"\"Stack another dataset in place.\n\n        The ``acceptance`` of the stacked dataset is normalized to 1,\n        and the stacked ``acceptance_off`` is scaled so that:\n\n        .. math::\n            \\alpha_\\text{stacked} =\n            \\frac{1}{a_\\text{off}} =\n            \\frac{\\alpha_1\\text{OFF}_1 + \\alpha_2\\text{OFF}_2}{\\text{OFF}_1 + OFF_2}\n\n        Parameters\n        ----------\n        other : `MapDatasetOnOff`\n            Other dataset\n        \"\"\"\n        if not isinstance(other, MapDatasetOnOff):\n            raise TypeError(\"Incompatible types for MapDatasetOnOff stacking\")\n\n        if not self._is_stackable() or not other._is_stackable():\n            raise ValueError(\"Cannot stack incomplete MapDatsetOnOff.\")\n\n        # Factor containing: self.alpha * self.counts_off + other.alpha * other.counts_off\n        tmp_factor = (self.alpha * self.counts_off).copy()\n        tmp_factor.data[~self.mask_safe.data] = 0\n        tmp_factor.stack(other.alpha * other.counts_off, weights=other.mask_safe.data)\n\n        # Stack the off counts (in place)\n        self.counts_off.data[~self.mask_safe.data] = 0\n        self.counts_off.stack(other.counts_off, weights=other.mask_safe.data)\n\n        self.acceptance_off = self.counts_off / tmp_factor\n        self.acceptance.data = np.ones(self.data_shape)\n\n        super().stack(other)\n\n    def stat_sum(self):\n        \"\"\"Total likelihood given the current model parameters.\"\"\"\n        return Dataset.stat_sum(self)\n\n    def fake(self, background_model, random_state=\"random-seed\"):\n        \"\"\"Simulate fake counts (on and off) for the current model and reduced IRFs.\n\n        This method overwrites the counts defined on the dataset object.\n\n        Parameters\n        ----------\n        random_state : {int, 'random-seed', 'global-rng', `~numpy.random.RandomState`}\n                Defines random number generator initialisation.\n                Passed to `~gammapy.utils.random.get_random_state`.\n        \"\"\"\n        random_state = get_random_state(random_state)\n        npred = self.npred()\n        npred.data = random_state.poisson(npred.data)\n\n        npred_bkg = background_model.copy()\n        npred_bkg.data = random_state.poisson(npred_bkg.data)\n\n        self.counts = npred + npred_bkg\n\n        npred_off = background_model / self.alpha\n        npred_off.data = random_state.poisson(npred_off.data)\n        self.counts_off = npred_off\n\n    def to_hdulist(self):\n        \"\"\"Convert map dataset to list of HDUs.\n\n        Returns\n        -------\n        hdulist : `~astropy.io.fits.HDUList`\n            Map dataset list of HDUs.\n        \"\"\"\n        hdulist = super().to_hdulist()\n        exclude_primary = slice(1, None)\n\n        if self.counts_off is not None:\n            hdulist += self.counts_off.to_hdulist(hdu=\"counts_off\")[exclude_primary]\n\n        if self.acceptance is not None:\n            hdulist += self.acceptance.to_hdulist(hdu=\"acceptance\")[exclude_primary]\n\n        if self.acceptance_off is not None:\n            hdulist += self.acceptance_off.to_hdulist(hdu=\"acceptance_off\")[\n                exclude_primary\n            ]\n\n        return hdulist\n\n    @classmethod\n    def from_hdulist(cls, hdulist, name=\"\"):\n        \"\"\"Create map dataset from list of HDUs.\n\n        Parameters\n        ----------\n        hdulist : `~astropy.io.fits.HDUList`\n            List of HDUs.\n\n        Returns\n        -------\n        dataset : `MapDataset`\n            Map dataset.\n        \"\"\"\n        init_kwargs = {}\n        init_kwargs[\"name\"] = name\n        if \"COUNTS\" in hdulist:\n            init_kwargs[\"counts\"] = Map.from_hdulist(hdulist, hdu=\"counts\")\n\n        if \"COUNTS_OFF\" in hdulist:\n            init_kwargs[\"counts_off\"] = Map.from_hdulist(hdulist, hdu=\"counts_off\")\n\n        if \"ACCEPTANCE\" in hdulist:\n            init_kwargs[\"acceptance\"] = Map.from_hdulist(hdulist, hdu=\"acceptance\")\n\n        if \"ACCEPTANCE_OFF\" in hdulist:\n            init_kwargs[\"acceptance_off\"] = Map.from_hdulist(\n                hdulist, hdu=\"acceptance_off\"\n            )\n\n        if \"EXPOSURE\" in hdulist:\n            init_kwargs[\"exposure\"] = Map.from_hdulist(hdulist, hdu=\"exposure\")\n\n        if \"EDISP_MATRIX\" in hdulist:\n            init_kwargs[\"edisp\"] = EDispKernel.from_hdulist(\n                hdulist, hdu1=\"EDISP_MATRIX\", hdu2=\"EDISP_MATRIX_EBOUNDS\"\n            )\n\n        if \"PSF_KERNEL\" in hdulist:\n            psf_map = Map.from_hdulist(hdulist, hdu=\"psf_kernel\")\n            init_kwargs[\"psf\"] = PSFKernel(psf_map)\n\n        if \"MASK_SAFE\" in hdulist:\n            mask_safe_map = Map.from_hdulist(hdulist, hdu=\"mask_safe\")\n            init_kwargs[\"mask_safe\"] = mask_safe_map.data.astype(bool)\n\n        if \"MASK_FIT\" in hdulist:\n            mask_fit_map = Map.from_hdulist(hdulist, hdu=\"mask_fit\")\n            init_kwargs[\"mask_fit\"] = mask_fit_map.data.astype(bool)\n\n        if \"GTI\" in hdulist:\n            gti = GTI(Table.read(hdulist, hdu=\"GTI\"))\n            init_kwargs[\"gti\"] = gti\n        return cls(**init_kwargs)\n\n    def to_spectrum_dataset(self, on_region, containment_correction=False):\n        \"\"\"Return a ~gammapy.spectrum.SpectrumDatasetOnOff from on_region.\n\n        Counts and OFF counts are summed in the on_region.\n\n        Acceptance is the average of all acceptances while acceptance OFF\n        is taken such that number of excess is preserved in the on_region.\n\n        Effective area is taken from the average exposure divided by the livetime.\n        Here we assume it is the sum of the GTIs.\n\n        The energy dispersion kernel is obtained at the on_region center.\n        Only regions with centers are supported.\n\n        The model is not exported to the ~gammapy.spectrum.SpectrumDataset.\n        It must be set after the dataset extraction.\n\n        Parameters\n        ----------\n        on_region : `~regions.SkyRegion`\n            the input ON region on which to extract the spectrum\n        containment_correction : bool\n            Apply containment correction for point sources and circular on regions\n\n        Returns\n        -------\n        dataset : `~gammapy.spectrum.SpectrumDatasetOnOff`\n            the resulting reduced dataset\n        \"\"\"\n        dataset = super().to_spectrum_dataset(on_region, containment_correction)\n\n        if self.counts_off is not None:\n            counts_off = self.counts_off.get_spectrum(on_region, np.sum)\n        else:\n            counts_off = None\n\n        if self.acceptance is not None:\n            acceptance = self.acceptance.get_spectrum(on_region, np.mean)\n            background = self.background.get_spectrum(on_region, np.sum)\n            acceptance_off = acceptance * counts_off / background\n        else:\n            acceptance = None\n            acceptance_off = None\n\n        return SpectrumDatasetOnOff(\n            counts=dataset.counts,\n            counts_off=counts_off,\n            acceptance=acceptance,\n            acceptance_off=acceptance_off,\n            name=dataset.name,\n            aeff=dataset.aeff,\n            edisp=dataset.edisp,\n            livetime=dataset.livetime,\n            gti=dataset.gti,\n        )\n\n    def cutout(self, position, width, mode=\"trim\"):\n        \"\"\"Cutout map dataset.\n\n        Parameters\n        ----------\n        position : `~astropy.coordinates.SkyCoord`\n            Center position of the cutout region.\n        width : tuple of `~astropy.coordinates.Angle`\n            Angular sizes of the region in (lon, lat) in that specific order.\n            If only one value is passed, a square region is extracted.\n        mode : {'trim', 'partial', 'strict'}\n            Mode option for Cutout2D, for details see `~astropy.nddata.utils.Cutout2D`.\n\n        Returns\n        -------\n        cutout : `MapDatasetOnOff`\n            Cutout map dataset.\n        \"\"\"\n        cutout_kwargs = {\"position\": position, \"width\": width, \"mode\": mode}\n\n        cutout_dataset = super().cutout(**cutout_kwargs)\n\n        if self.counts_off is not None:\n            cutout_dataset.counts_off = self.counts_off.cutout(**cutout_kwargs)\n\n        if self.acceptance is not None:\n            cutout_dataset.acceptance = self.acceptance.cutout(**cutout_kwargs)\n\n        if self.acceptance_off is not None:\n            cutout_dataset.acceptance_off = self.acceptance_off.cutout(**cutout_kwargs)\n\n        return cutout_dataset\n\n\nclass MapEvaluator:\n    \"\"\"Sky model evaluation on maps.\n\n    This evaluates a sky model on a 3D map and convolves with the IRFs,\n    and returns a map of the predicted counts.\n    Note that background counts are not added.\n\n    For now, we only make it work for 3D WCS maps with an energy axis.\n    No HPX, no other axes, those can be added later here or via new\n    separate model evaluator classes.\n\n    Parameters\n    ----------\n    model : `~gammapy.modeling.models.SkyModel`\n        Sky model\n    exposure : `~gammapy.maps.Map`\n        Exposure map\n    psf : `~gammapy.cube.PSFKernel`\n        PSF kernel\n    edisp : `~gammapy.irf.EDispKernel`\n        Energy dispersion\n    evaluation_mode : {\"local\", \"global\"}\n        Model evaluation mode.\n    \"\"\"\n\n    def __init__(\n        self, model=None, exposure=None, psf=None, edisp=None, evaluation_mode=\"local\"\n    ):\n        self.model = model\n        self.exposure = exposure\n        self.psf = psf\n        self.edisp = edisp\n        self.contributes = True\n\n        if evaluation_mode not in {\"local\", \"global\"}:\n            raise ValueError(f\"Invalid evaluation_mode: {evaluation_mode!r}\")\n\n        self.evaluation_mode = evaluation_mode\n\n    @property\n    def geom(self):\n        \"\"\"True energy map geometry (`~gammapy.maps.Geom`)\"\"\"\n        return self.exposure.geom\n\n    @property\n    def needs_update(self):\n        \"\"\"Check whether the model component has drifted away from its support.\"\"\"\n        if self.evaluation_mode == \"global\" or self.model.evaluation_radius is None:\n            return False\n        else:\n            position = self.model.position\n            separation = self._init_position.separation(position)\n            update = separation > (self.model.evaluation_radius + CUTOUT_MARGIN)\n        return update\n\n    def update(self, exposure, psf, edisp, geom):\n        \"\"\"Update MapEvaluator, based on the current position of the model component.\n\n        Parameters\n        ----------\n        exposure : `~gammapy.maps.Map`\n            Exposure map.\n        psf : `gammapy.cube.PSFMap`\n            PSF map.\n        edisp : `gammapy.cube.EDispMap`\n            Edisp map.\n        geom : `WcsGeom`\n            Counts geom\n        \"\"\"\n        log.debug(\"Updating model evaluator\")\n        # cache current position of the model component\n\n        if isinstance(edisp, EDispMap):\n            e_reco = geom.get_axis_by_name(\"energy\").edges\n            self.edisp = edisp.get_edisp_kernel(self.model.position, e_reco=e_reco)\n        else:\n            self.edisp = edisp\n\n        if isinstance(psf, PSFMap):\n            self.psf = psf.get_psf_kernel(self.model.position, geom=exposure.geom)\n        else:\n            self.psf = psf\n\n        if self.evaluation_mode == \"local\" and self.model.evaluation_radius is not None:\n            self._init_position = self.model.position\n            if self.psf is not None:\n                psf_width = np.max(self.psf.psf_kernel_map.geom.width)\n            else:\n                psf_width = 0 * u.deg\n\n            width = psf_width + 2 * (self.model.evaluation_radius + CUTOUT_MARGIN)\n            try:\n                self.exposure = exposure.cutout(\n                    position=self.model.position, width=width\n                )\n                self.contributes = True\n            except (NoOverlapError, ValueError):\n                self.contributes = False\n        else:\n            self.exposure = exposure\n\n    def compute_dnde(self):\n        \"\"\"Compute model differential flux at map pixel centers.\n\n        Returns\n        -------\n        model_map : `~gammapy.maps.Map`\n            Sky cube with data filled with evaluated model values.\n            Units: ``cm-2 s-1 TeV-1 deg-2``\n        \"\"\"\n        return self.model.evaluate_geom(self.geom)\n\n    def compute_flux(self):\n        \"\"\"Compute model integral flux over map pixel volumes.\n\n        For now, we simply multiply dnde with bin volume.\n        \"\"\"\n        dnde = self.compute_dnde()\n        volume = self.geom.bin_volume()\n        return dnde * volume\n\n    def apply_exposure(self, flux):\n        \"\"\"Compute npred cube\n\n        For now just divide flux cube by exposure\n        \"\"\"\n        npred = (flux * self.exposure.quantity).to_value(\"\")\n        return Map.from_geom(self.geom, data=npred, unit=\"\")\n\n    def apply_psf(self, npred):\n        \"\"\"Convolve npred cube with PSF\"\"\"\n        tmp = npred.convolve(self.psf)\n        tmp.data[tmp.data < 0.0] = 0\n        return tmp\n\n    def apply_edisp(self, npred):\n        \"\"\"Convolve map data with energy dispersion.\n\n        Parameters\n        ----------\n        npred : `~gammapy.maps.Map`\n            Predicted counts in true energy bins\n\n        Returns\n        -------\n        npred_reco : `~gammapy.maps.Map`\n            Predicted counts in reco energy bins\n        \"\"\"\n        return npred.apply_edisp(self.edisp)\n\n    def compute_npred(self):\n        \"\"\"\n        Evaluate model predicted counts.\n\n        Returns\n        -------\n        npred : `~gammapy.maps.Map`\n            Predicted counts on the map (in reco energy bins)\n        \"\"\"\n        flux = self.compute_flux()\n        npred = self.apply_exposure(flux)\n        if self.psf is not None:\n            npred = self.apply_psf(npred)\n        if self.edisp is not None:\n            npred = self.apply_edisp(npred)\n\n        return npred\n", "meta": {"hexsha": "3c2ad2a2fe95f3f735e8569815d7cffc8d0ab275", "size": 55222, "ext": "py", "lang": "Python", "max_stars_repo_path": "gammapy/cube/fit.py", "max_stars_repo_name": "QRemy/gammapy", "max_stars_repo_head_hexsha": "fe799e8a8e792d216fdb11fb7abcb64d58f273dd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gammapy/cube/fit.py", "max_issues_repo_name": "QRemy/gammapy", "max_issues_repo_head_hexsha": "fe799e8a8e792d216fdb11fb7abcb64d58f273dd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gammapy/cube/fit.py", "max_forks_repo_name": "QRemy/gammapy", "max_forks_repo_head_hexsha": "fe799e8a8e792d216fdb11fb7abcb64d58f273dd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.278088144, "max_line_length": 99, "alphanum_fraction": 0.5951975662, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 12503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.1684471997098308}}
{"text": "#!/usr/bin/env python\nimport os\nimport numpy as np\nimport time\nimport copy\nimport sys\n\nimport argparse\n\nang_2_bohr = 1.0/0.52917721067\nhart_2_ev = 27.21138602\n\nimport cp2k_spm_tools.cp2k_grid_orbitals as cgo\nfrom cp2k_spm_tools import common, cube\n\nfrom mpi4py import MPI\n\ncomm = MPI.COMM_WORLD\nmpi_rank = comm.Get_rank()\nmpi_size = comm.Get_size()\n\nparser = argparse.ArgumentParser(\n    description='Runs bond order analysis based on Bader basins.')\n\nparser.add_argument(\n    '--cp2k_input_file',\n    metavar='FILENAME',\n    required=True,\n    help='CP2K input of the SCF calculation.')\nparser.add_argument(\n    '--basis_set_file',\n    metavar='FILENAME',\n    required=True,\n    help='File containing the used basis sets.')\nparser.add_argument(\n    '--xyz_file',\n    metavar='FILENAME',\n    required=True,\n    help='.xyz file containing the geometry.')\nparser.add_argument(\n    '--wfn_file',\n    metavar='FILENAME',\n    required=True,\n    help='cp2k restart file containing the wavefunction.')\n### -----------------------------------------------------------\nparser.add_argument(\n    '--output_file',\n    metavar='FILENAME',\n    required=True,\n    help='Output file containing the bond orders.')\nparser.add_argument(\n    '--bader_basins_dir',\n    metavar='DIR',\n    required=True,\n    help='directory containing the Bader basin .cube files.')\n### -----------------------------------------------------------\nparser.add_argument(\n    '--dx',\n    type=float,\n    metavar='DX',\n    default=0.2,\n    help='Spatial step for the grid (angstroms).')\nparser.add_argument(\n    '--eval_cutoff',\n    type=float,\n    metavar='D',\n    default=14.0,\n    help=(\"Size of the region around the atom where each\"\n          \" orbital is evaluated (only used for 'G' region).\")\n)\nparser.add_argument(\n    '--eval_region',\n    type=str,\n    nargs=6,\n    metavar='X',\n    required=False,\n    default = ['G', 'G', 'G', 'G', 'G', 'G'],\n    help=common.eval_region_description\n)\n### -----------------------------------------------------------\n\n\ntime0 = time.time()\n\n### ------------------------------------------------------\n### Parse args for only one rank to suppress duplicate stdio\n### ------------------------------------------------------\n\nargs = None\nargs_success = False\ntry:\n    if mpi_rank == 0:\n        args = parser.parse_args()\n        args_success = True\nfinally:\n    args_success = comm.bcast(args_success, root=0)\n\nif not args_success:\n    print(mpi_rank, \"exiting\")\n    exit(0)\n\nargs = comm.bcast(args, root=0)\n\n### ------------------------------------------------------\n### Load the Bader basins\n### ------------------------------------------------------\n\nbader_atoms = []\nbader_masks = []\n\nfor f in sorted(os.listdir(args.bader_basins_dir)):\n    if f.startswith(\"BvAt\"):\n        num = int(f.split(\".\")[0][4:]) - 1\n        bader_atoms.append(num)\n        c = cube.Cube()\n        c.read_cube_file(args.bader_basins_dir+\"/\"+f)\n        if np.abs(c.dv[0, 0] - args.dx) > 1e-3:\n            print(\"ERROR: Basin cube dx doesn't match specified dx!\")\n            print(c.dv[0, 0], args.dx)\n            exit(0)\n        bader_masks.append(c.data > 1e-10)\n\n\nprint(\"R%d/%d: loaded Bader basins, time: %.2fs\"%(mpi_rank, mpi_size, (time.time() - time0)))\nsys.stdout.flush()\ntime1 = time.time()\n\n### ------------------------------------------------------\n### Evaluate orbitals on the real-space grid\n### ------------------------------------------------------\n\nmol_grid_orb = cgo.Cp2kGridOrbitals(mpi_rank, mpi_size, comm, single_precision=False)\nmol_grid_orb.read_cp2k_input(args.cp2k_input_file)\nmol_grid_orb.read_xyz(args.xyz_file)\nmol_grid_orb.center_atoms_to_cell()\nmol_grid_orb.read_basis_functions(args.basis_set_file)\nmol_grid_orb.load_restart_wfn_file(args.wfn_file, n_occ=None, n_virt=0)\n\nprint(\"R%d/%d: loaded eval files, time: %.2fs\"%(mpi_rank, mpi_size, (time.time() - time1)))\nsys.stdout.flush()\ntime1 = time.time()\n\neval_reg = common.parse_eval_region_input(args.eval_region, mol_grid_orb.ase_atoms, mol_grid_orb.cell)\n\nmol_grid_orb.calc_morbs_in_region(args.dx,\n                                x_eval_region = eval_reg[0],\n                                y_eval_region = eval_reg[1],\n                                z_eval_region = eval_reg[2],\n                                reserve_extrap = 0.0,\n                                eval_cutoff = args.eval_cutoff)\n\nprint(\"R%d/%d: evaluated grids, time: %.2fs\"%(mpi_rank, mpi_size, (time.time() - time1)))\nsys.stdout.flush()\ntime1 = time.time()\n\n### ------------------------------------------------------\n### Calculate Bond orders\n### ------------------------------------------------------\n\nbond_order_matrix = np.zeros((len(bader_atoms), len(bader_atoms)))\n\nn_orb_per_rank = []\nfor i_spin in range(mol_grid_orb.nspin):\n    n_orb_per_rank.append(comm.allgather(len(mol_grid_orb.morb_energies[i_spin])))\n\ncell_n = mol_grid_orb.eval_cell_n\nvol_elem = np.prod(mol_grid_orb.dv)\n\nif any(cell_n != bader_masks[0].shape):\n    print(\"Error: Basin and evaluation size mismatch.\")\n    exit(0)\n\nfor i_rank in range(mpi_size):\n\n    if mpi_rank == i_rank:\n        print(\"R%d/%d: distributing grids and evaluating products...\"%(mpi_rank, mpi_size))\n        sys.stdout.flush()\n        time1 = time.time()\n\n\n    for i_spin in range(mol_grid_orb.nspin):\n\n        bcast_buffer = np.empty(np.prod(cell_n)*n_orb_per_rank[i_spin][i_rank])\n\n        if mpi_rank == i_rank:\n            bcast_buffer = mol_grid_orb.morb_grids[i_spin].flatten()\n\n        # Broadcast the current rank grids to all\n        comm.Bcast([bcast_buffer, MPI.DOUBLE], root=i_rank)\n\n        received_grids = np.reshape(bcast_buffer,\n            (n_orb_per_rank[i_spin][i_rank], cell_n[0], cell_n[1], cell_n[2])\n        )\n        \n#        for i_mo in range(received_grids.shape[0]):\n#            \n#            i_grid = received_grids[i_mo]\n#\n#            for j_mo in range(mol_grid_orb.morb_grids[i_spin].shape[0]):\n#                \n#                j_grid = mol_grid_orb.morb_grids[i_spin][j_mo]\n#\n#                for at_a in range(len(bader_atoms)):\n#                    for at_b in range(at_a):\n#\n#                        i_grid_a = i_grid*bader_masks[at_a]\n#                        i_grid_b = i_grid*bader_masks[at_b]\n#\n#                        scalar_a = np.dot(i_grid_a.flatten(), j_grid.flatten())*vol_elem\n#                        scalar_b = np.dot(i_grid_b.flatten(), j_grid.flatten())*vol_elem\n#\n#                        bond_order_matrix[at_a, at_b] += 4*scalar_a*scalar_b\n#                        bond_order_matrix[at_b, at_a] += 4*scalar_a*scalar_b\n\n        n_i = received_grids.shape[0]\n        n_j = mol_grid_orb.morb_grids[i_spin].shape[0]\n\n        for at_a in range(len(bader_atoms)):\n            for at_b in range(at_a):\n                \n                i_grid_a = received_grids[:, bader_masks[at_a]].reshape(n_i, -1)\n                i_grid_b = received_grids[:, bader_masks[at_b]].reshape(n_i, -1)\n\n                j_grid_a = mol_grid_orb.morb_grids[i_spin][:, bader_masks[at_a]].reshape(n_j, -1)\n                j_grid_b = mol_grid_orb.morb_grids[i_spin][:, bader_masks[at_b]].reshape(n_j, -1)\n\n                bo = np.sum(np.einsum(\"ij,kj\", i_grid_a, j_grid_a) * np.einsum(\"ij,kj\", i_grid_b, j_grid_b))\n\n                bond_order_matrix[at_a, at_b] += 4 * bo * vol_elem**2\n                bond_order_matrix[at_b, at_a] += 4 * bo * vol_elem**2\n\n    \n    if mpi_rank == i_rank:\n        print(\"R%d/%d: ... time: %.2fs\"%((mpi_rank, mpi_size, time.time()-time1)))\n        sys.stdout.flush()\n\n# collect all contributions\nfinal_bond_order_mat = np.zeros((len(bader_atoms), len(bader_atoms)))\ncomm.Reduce(bond_order_matrix, final_bond_order_mat, op=MPI.SUM)\n\nif mpi_rank == 0:\n    header = \"\"\n    for b_at in bader_atoms:\n        header += \"%10d\" % b_at\n    header = header[3:]\n    np.savetxt(args.output_file, final_bond_order_mat, fmt=\"%9.6f\", header=header)\n\nprint(\"R%d/%d finished, total time: %.2fs\"%(mpi_rank, mpi_size, (time.time() - time0)))\n", "meta": {"hexsha": "67dd99e24a32b56051bbb6cc4a2b6b276e28e468", "size": 7954, "ext": "py", "lang": "Python", "max_stars_repo_path": "bader_bond_order.py", "max_stars_repo_name": "eimrek/cp2k-spm-tools", "max_stars_repo_head_hexsha": "94b158e7e93bc4cb76e88d59d31347fafdda5e64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-10-11T15:24:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T16:05:24.000Z", "max_issues_repo_path": "bader_bond_order.py", "max_issues_repo_name": "eimrek/cp2k-spm-tools", "max_issues_repo_head_hexsha": "94b158e7e93bc4cb76e88d59d31347fafdda5e64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bader_bond_order.py", "max_forks_repo_name": "eimrek/cp2k-spm-tools", "max_forks_repo_head_hexsha": "94b158e7e93bc4cb76e88d59d31347fafdda5e64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-09-27T06:09:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-23T15:21:11.000Z", "avg_line_length": 31.9437751004, "max_line_length": 108, "alphanum_fraction": 0.5817198894, "include": true, "reason": "import numpy", "num_tokens": 2000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.2974699363766585, "lm_q1q2_score": 0.16837349765279372}}
{"text": "﻿#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#-------------------------------------------------------------------------------\n# Name:        carbonsource.py\n# Purpose:     CarbonSource class in mfapy\n#\n# Author:      Fumio_Matsuda\n#\n# Created:     12/06/2018\n# Copyright:   (c) Fumio_Matsuda 2018\n# Licence:     MIT license\n#-------------------------------------------------------------------------------\n\"\"\"carbonsource.py:CarbonSource class in mfapy\n\nThe module includes::\n\n    CarbonSource class\n\nTodo:\n    * Subtraction of natural isotope\n\n\"\"\"\n\nimport numpy as numpy\nimport itertools\n\nclass CarbonSource:\n    \"\"\"Class for carbon source information.\n\n    Instance of this class is generated in the MetabolicModel instance\n\n    \"\"\"\n    def __init__(self, carbon_sources):\n        \"\"\"Constructer of CarbonSource instance from target_fragments information of the metabolic model\n\n        Args:\n            carbon_sources (dict): dictionary of carbon sources information in model.carbon_sources.\n\n        Returns:\n            instance : CarbonSource instance\n\n        Examples:\n            >>> cs = CarbonSource(arbon_sources)\n            CarbonSource data can be accessed by:\n            cs.cs['fragment_name']['IDV']\n\n\n        \"\"\"\n        self.cs = {}\n        #for each line in mass data\n        for compound in carbon_sources:\n            self.cs[compound] = {\n            'IDV': carbon_sources[compound]['IDV'][:],\n            'size': carbon_sources[compound]['size']\n            }\n        self.mdv_carbon_sources = {}\n        #Set MDVs of EMUs of each carbon sources\n        self.generate_carbonsource_MDV()\n\n    def show(self):\n        \"\"\"Method to display contents of CarbonSource instance\n\n        Args:\n            Not required.\n\n        Returns:\n            Nothing.\n\n        Examples:\n\n            >>> cs.show()\n            Name: Asp\n            Carbon number: 4\n            #0000\t1.0\n            Name: AcCoA\n            Carbon number: 2\n            #00\t0.5\n            #10\t0.25\n            #11\t0.25\n\n\n        \"\"\"\n        for compound in self.cs:\n            IDV = self.cs[compound]['IDV'][:]\n            size = self.cs[compound]['size']\n            print('Name: ' +  compound)\n            print('Carbon number: ' +  str(size))\n            for i in range(0, 2**size):\n                if IDV[i] > 0.0:\n                    strbin = format(i, 'b')# strbin = format(10,'b') #'1010'\n                    strbin =\"0\" * (size - len(strbin)) + strbin# strbin = \"0\" * (6-4) + '1010' = '001010'\n                    print(\"#\"+strbin[::-1]+\"\\t\", IDV[i])# #010100 reverse 0/1\n            for emu in sorted(self.mdv_carbon_sources.keys()):\n                if compound in emu:\n                    print(emu+\"\\t\", self.mdv_carbon_sources[emu], \"sum \"+str(sum(self.mdv_carbon_sources[emu])))\n\n    def generate_dict(self):\n        \"\"\"Generator of a dictionary of MDVs of all EMUs of carbon sources\n\n        Args:\n            Not required.\n\n        Returns:\n            dict : Dictionary of MDVs of all EMUs of carbon sources\n\n        Examples:\n            >>> mdvs = cs.generate_dict()\n\n\n\n        \"\"\"\n        mdv_cs = {}\n        #for each line in mass data\n        for label in self.mdv_carbon_sources:\n            mdv_cs[label] = self.mdv_carbon_sources[label][:]\n        return mdv_cs\n\n    def set_all_isotopomers(self, compound, list, correction = 'no'):\n        \"\"\"Setter of IDV data by list of all mass isotopomer distribution\n\n        Args:\n            compound (str): Name of carbon source.\n\n            list (array): list of mass isotopomer distribution (from 000, 001, 010, to 111)\n\n            correction (str): (yes/no) Correction of isotopomer distribution considering natural 13C occurence\n\n        Returns:\n            Booleans: True/False\n\n\n        Examples:\n            >>> cs.set_all_isotopomers('AcCoA', [0.3, 0.3, 0.3, 0.1])\n\n\n\n        \"\"\"\n        if compound not in self.cs:\n            print(\"False compound name\")\n            return False\n        if len(list) != 2**self.cs[compound]['size']:\n            print(\"False list length\")\n            return False\n        if abs(1.0-sum(list)) > 0.00001:\n            print(\"Sum of list is not 1.0\")\n            return False\n        self.cs[compound]['IDV'] = list[:]\n        self.generate_carbonsource_MDV(carbonsource = [compound], correction = correction)\n        return True\n\n    def set_carbonsources(self, filename, correction = 'no', format = 'text',output = \"normal\"):\n        \"\"\"Setter of isotopomer data of multiple carbon sourses from text file.\n\n        Args:\n            filename (str): filename of MDV data with following format::\n\n                Name\tIsotopomer\tRatio\n                Asp\t#0000\t0.5\n                Asp\t#1111\t0.5\n                AcCoA\t#00\t0.5\n                AcCoA\t#11\t0.5\n\n            correction (str) : (yes/no) Correction of isotopomer distribution considering natural 13C occurence\n\n            format (str) : \"text\" (defalut) or \"csv\"\n\n            output (str) : \"normal\" (defalut) or \"debug\"\n\n        Returns:\n            Boolean: True/False\n\n        Examples:\n            >>> cs2.set_isotopomers_from_file('Example_1_carbonsource2.txt', correction = \"yes\")\n\n\n\n        \"\"\"\n        #\n        #\n        observed_fragments_set = set()\n        with open(filename, 'r') as f:\n            import csv\n            if format == \"text\":\n                reader = csv.reader(f, delimiter='\\t')\n            elif format == \"csv\":\n                reader = csv.reader(f, dialect='excel')\n            else:\n                print(\"Unknown format!\")\n                return False\n            dict = {}\n\n            for i, row in enumerate(reader):\n                if output == \"debug\":\n                    print(row)\n                if i == 0: continue\n                if len(row) != 3:\n                    continue\n                fragment, isotopomer, ratio, *over = row\n                if ratio == \"\":\n                    ratio = 0\n\n                if fragment not in self.cs:\n                    continue\n                if fragment not in dict:\n                    dict[fragment] = {}\n                dict[fragment][isotopomer] = float(ratio)\n        for fragment in dict:\n            self.set_each_isotopomer(fragment, dict[fragment], correction = correction)\n        return True\n\n    def set_each_isotopomer(self, compound, dict, correction = 'no'):\n        \"\"\"Setter of IDV data of selected mass isotopomers\n\n        Args:\n            compound (str): Name of carbon source\n\n            dict (dict): Dictionary of mass isotopomer and its relative abundance::\n\n                {'#111': 0.5, '#001': 0.5}\n\n            correction (str): (yes/no) Correction of isotopomer distribution considering natural 13C occurence\n\n        Returns:\n            Boolean: True/False\n\n        Examples:\n            >>> cs.set_each_isotopomers('AcCoA', {'#11':0.5, '#10':0.25}, correction = 'yes')\n\n\n\n        \"\"\"\n\n        #check compound name\n        #\n        if compound not in self.cs:\n            print(\"False compound name\")\n            return False\n\n        size = self.cs[compound]['size']\n        #\n        #check compound name\n        #\n        sum = 0.0\n        for isotopomer in dict:\n            sum = sum + dict[isotopomer]\n        if sum > 1.0:\n            print(\"Sum isctopomers is over 1.0\")\n            return False\n\n        for isotopomer in dict:\n            sum = 0\n            for letter in isotopomer:\n                if letter == \"0\": sum = sum + 1\n                if letter == \"1\": sum = sum + 1\n            if sum != size:\n                print(\"False isotopomer\" + isotopomer)\n                return False\n\n        #\n        # generate IDV\n        #\n        self.cs[compound]['IDV'] = [0] * 2**size\n\n        for isotopomer in dict:\n            str_bin = \"\"\n            for letter in isotopomer[::-1]:\n                if letter == \"0\": str_bin = str_bin + \"0\"\n                if letter == \"1\": str_bin = str_bin + \"1\"\n\n            self.cs[compound]['IDV'][int(str_bin, 2)] = dict[isotopomer]\n        self.generate_carbonsource_MDV(carbonsource = [compound], correction = correction)\n        return True\n\n    def set_labeled_compounds(self, compound, dict, correction = 'no'):\n        \"\"\"Setter of IDV data by distribution of selected mass isotopomers\n\n        Following symbols are available::\n\n            \"[13C]CO2\": \"#1\",\n            \"[12C]CO2\": \"#0\",\n            \"[13C]THF\": \"#1\",\n            \"[12C]THF\": \"#0\",\n            \"[1-13C]glucose\": \"#100000\",\n            \"[2-13C]glucose\": \"#010000\",\n            \"[1,2-13C]glucose\": \"#110000\",\n            \"[U-13C]glucose\": \"#111111\",\n            \"[1-13C]glutamine\": \"#10000\",\n            \"[2-13C]glutamine\": \"#01000\",\n            \"[5-13C]glutamine\": \"#00001\",\n            \"[U-13C]glutamine\": \"#11111\",\n\n        Args:\n            compound (str): Name of carbon source.\n\n            dict (dict): Dictionary of mass isotopomer and its relative abundance {'#111': 0.5, '#001': 0.5}\n\n            correction (str): (yes/no) Correction of isotopomer distribution considering natural 13C occurence\n\n        Returns:\n            Boolean: True/False\n\n        Examples:\n            >>> cs.set_labeled_compounds('Glc',{'[1_13C]glucose': 0.5, '[U_13C]glucose':0.5}, correction = 'yes')\n\n\n        \"\"\"\n        #\n        # please enrich this list\n        #\n        labeledcompound_dict = {\n        \"[13C]CO2\": \"#1\",\n        \"[12C]CO2\": \"#0\",\n        \"[13C]THF\": \"#1\",\n        \"[12C]THF\": \"#0\",\n        \"[1-13C]glucose\": \"#100000\",\n        \"[2-13C]glucose\": \"#010000\",\n        \"[1,2-13C]glucose\": \"#110000\",\n        \"[U-13C]glucose\": \"#111111\",\n        \"[1-13C]glutamine\": \"#10000\",\n        \"[2-13C]glutamine\": \"#01000\",\n        \"[5-13C]glutamine\": \"#00001\",\n        \"[U-13C]glutamine\": \"#11111\",\n        }\n\n\n        #check compound name\n        #\n        if compound not in self.cs:\n            print(\"False compound name\")\n            return False\n\n        size = self.cs[compound]['size']\n        #\n        #check compound name\n        #\n        sum = 0.0\n        for isotopomer in dict:\n            sum = sum + dict[isotopomer]\n        if sum > 1.0:\n            print(\"Sum isotopomers is over 1.0\")\n            return False\n\n        for labeledcompound in dict:\n            if labeledcompound not in labeledcompound_dict:\n                print(\"False lableled compound name \"+labeledcompound)\n                return False\n        for labeledcompound in dict:\n            sum = 0\n            for letter in labeledcompound_dict[labeledcompound]:\n                if letter == \"0\": sum = sum + 1\n                if letter == \"1\": sum = sum + 1\n            if sum != size:\n                print(\"False isotopomer\" + isotopomer)\n                return False\n\n        #\n        # IDV????\n        #\n        self.cs[compound]['IDV'] = [0] * 2**size\n\n        for labeledcompound in dict:\n            str_bin = \"\"\n            for letter in labeledcompound_dict[labeledcompound]:\n                if letter == \"0\": str_bin = str_bin + \"0\"\n                if letter == \"1\": str_bin = str_bin + \"1\"\n\n            self.cs[compound]['IDV'][int(str_bin, 2)] = dict[isotopomer]\n        self.generate_carbonsource_MDV(carbonsource = [compound], correction = correction)\n        return True\n\n\n    def generate_carbonsource_MDV(self, carbonsource = [], correction = 'no'):\n        \"\"\"Generator of MDVs of all EMUs of each carbon source.\n\n        This function is called in the mfapy.metabolicmodel.MetabolicModel\n\n        Args:\n            carbonsource (array): List of carbon source metabolite (optional)\n\n            correction (str): (yes/no) Correction of isotopomer distribution considering natural 13C occurence\n\n        Returns:\n            dict: Dictionary of mdv data of carbon source.\n\n        Examples:\n\n            >>> cs.generate_carbonsource_MDV()\n\n        History:\n\n            Correcton of IDV by natural 13C method was improved.\n\n            labeled by 2 13C and 3 13C was taken into consideration.\n\n        \"\"\"\n\n        #\n        # Initialization\n        #\n        stable_isotope_ratio = 0.0107\n        if len(carbonsource)==0:\n            carbonsource = self.cs.keys()\n        #\n        # For each carbon source\n        #\n        for compound in carbonsource:\n            if compound not in self.cs:\n                continue\n            #\n            #  correction by natural isotope abundance\n            #\n            size = self.cs[compound][\"size\"]\n            if correction != 'no':\n                #\n                # Preparation of IDV array for the natural isotope correaction.\n                # Asp, {'IDV': [1.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'size': 4}\n                #\n                IDV_array = numpy.zeros((2 ** int(size)))\n                #\n                # For each idv..\n                #\n                for t in range((2 ** int(size))):\n                    #\n                    # Ignore when carbon source does not contain the IDV\n                    #  'IDV': [1.0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n                    if self.cs[compound][\"IDV\"][t] == 0:\n                        continue\n                    #\n                    # Generate label patterns of IDV\n                    #\n                    # ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0']\n                    #['0', '0', '0', '0']\n                    bin = list('{0:010b}'.format(t))[10-size:10]# Max 10\n                    bin.reverse()\n                    #\n                    #['0', '0', '0', '0'] <= Label pattern = #0000\n                    #\n                    # Count nonlabled carbon (0)\n                    #\n                    zero_count = float(sum([1 for x in bin if x == '0']))\n                    # zero_count = 4\n                    for i in range(0, len(bin)):\n                        # scan ['0', '0', '0', '0']\n                        #\n                        # If there is one natural 13C among 12C\n                        #\n                        isotope = bin[i]\n                        if isotope == \"0\":\n                            bin_temp = list(bin) #copy\n                            bin_temp[i] = '1' # Change to 13C ['1', '0', '0', '0']\n                            bin_temp.reverse()  # reverse ['0', '0', '0', '1']\n                            number_temp = int(\"\".join(bin_temp),2) # convert to number of natural isotope 3\n                            IDV_array[number_temp] = IDV_array[number_temp] + \\\n                            self.cs[compound][\"IDV\"][t] * stable_isotope_ratio * ((1.0- stable_isotope_ratio) ** (zero_count-1.0))\n                            # 0 + 1 * 0.0107 + (1- 0.0107) ** (1-1)\n                            for i2 in range(len(bin_temp)):\n                                # scan ['0', '0', '0', '1']\n                                # If there are two natural 13C among 12C\n                                #\n                                isotope2 = bin_temp[i2]\n                                if isotope2 == \"0\":\n                                    bin_temp2 = list(bin_temp)\n                                    bin_temp2[i2] = '1'\n                                    bin_temp2.reverse()\n                                    number_temp2 = int(\"\".join(bin_temp2),2)\n                                    IDV_array[number_temp2] = IDV_array[number_temp2] + \\\n                                    0.5 * self.cs[compound][\"IDV\"][t] * (stable_isotope_ratio ** 2.0) * ((1.0- stable_isotope_ratio) ** (zero_count-2.0))\n                                    for i3 in range(len(bin_temp2)):\n                                        #\n                                        # If there are three natural 13C among 12C\n                                        #\n                                        isotope3 = bin_temp2[i3]\n                                        if isotope3 == \"0\":\n                                            bin_temp3 = list(bin_temp2)\n                                            bin_temp3[i3] = '1'\n                                            bin_temp3.reverse()\n                                            number_temp3 = int(\"\".join(bin_temp3),2)\n                                            IDV_array[number_temp3] = IDV_array[number_temp3] +  self.cs[compound][\"IDV\"][t] / 6.0 * (stable_isotope_ratio ** 3.0) * ((1.0- stable_isotope_ratio) ** (zero_count-3.0))\n                    IDV_array[t] = IDV_array[t] + self.cs[compound][\"IDV\"][t] * ((1.0- stable_isotope_ratio) ** zero_count)\n            else:\n                IDV_array = list(self.cs[compound][\"IDV\"])\n\n            #\n            # EMU generation\n            #\n            for emu_size in range(1, size+1):\n                #\n                # Generate all EMUs by itertools.combinations\n                #\n                for c in itertools.combinations(range(1,size+1),emu_size):\n                    MID = [0] * (int(emu_size) + 1)#Mass isotopomer distribution\n                    filter = [0]  * int(size);# Carbons for EMU\n                    #\n                    # Name of EMUs.\n                    #\n                    numbers =  \":\".join(map(str,c))\n                    emu = compound + \"_\" + numbers\n                    #\n                    # Set carbon positions\n                    #\n                    for i in c:\n                        filter[int(i)-1] = 1\n                    for t in range((2 ** int(size))):\n                        bin = list(format (t, '09b'))#for all isotopomers\n                        bin.reverse()\n                        #Cals number of 13C in EMU\n                        #print(bin, filter)\n                        number = sum([int(bin[x]) for x in range(len(filter)) if filter[x] == 1])\n                        #Integraton。\n                        MID[number] += IDV_array[t]\n                    #Normalised to 1.0\n                    sum_MID = sum(MID)\n                    self.mdv_carbon_sources[emu] = [x/sum_MID for x in MID]\n        return(self.mdv_carbon_sources)\n\ndef main():\n    pass\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "dd0f9b067cda1ccfa15aff605f08a7e05f32a2ee", "size": 17921, "ext": "py", "lang": "Python", "max_stars_repo_path": "mfapy/carbonsource.py", "max_stars_repo_name": "kskmaeda/mfapy", "max_stars_repo_head_hexsha": "f7d621fe412f0f04219189db5d1bb956cdee4e9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-02-24T07:48:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T01:11:36.000Z", "max_issues_repo_path": "mfapy/carbonsource.py", "max_issues_repo_name": "fumiomatsuda/mfapy", "max_issues_repo_head_hexsha": "0d22cfe3f7fe690565d039b7bda4fb80e2bb0eb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-09-05T15:48:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T05:21:22.000Z", "max_forks_repo_path": "mfapy/carbonsource.py", "max_forks_repo_name": "kskmaeda/mfapy", "max_forks_repo_head_hexsha": "f7d621fe412f0f04219189db5d1bb956cdee4e9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-04-11T12:49:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T14:03:10.000Z", "avg_line_length": 34.3973128599, "max_line_length": 214, "alphanum_fraction": 0.4677752358, "include": true, "reason": "import numpy", "num_tokens": 4300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3311197462295937, "lm_q1q2_score": 0.16814653563250706}}
{"text": "# -*- coding: utf-8 -*-\n#\n# ke_model.py\n#\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\"\"\"\nKnowledge Graph Embedding Model\n1. TransE_1\n2. TransE_2\n3. TransR\n4. RESCAL\n5. DistMult\n6. ComplEx\n7. RotatE\n\"\"\"\nimport os\nfrom abc import abstractmethod, ABCMeta\nimport numpy as np\nimport dgl\nimport torch as th\n\nfrom .pytorch.tensor_models import logsigmoid\nfrom .pytorch.tensor_models import none\nfrom .pytorch.tensor_models import get_device\nfrom .pytorch.tensor_models import norm\nfrom .pytorch.tensor_models import get_scalar\nfrom .pytorch.tensor_models import reshape\nfrom .pytorch.tensor_models import cuda\nfrom .pytorch.tensor_models import ExternalEmbedding\nfrom .pytorch.score_fun import *\nfrom .pytorch.ke_tensor import KGEmbedding\nfrom .pytorch.tensor_models import cosine_dist\nfrom .pytorch.tensor_models import l2_dist\nfrom .pytorch.tensor_models import l1_dist\nfrom .pytorch.tensor_models import dot_dist\nfrom .pytorch.tensor_models import extended_jaccard_dist\nfrom .pytorch.tensor_models import floor_divide\n\nEMB_INIT_EPS = 2.0\nDEFAULT_INFER_BATCHSIZE = 1024\n\nclass BasicGEModel(object):\n    \"\"\" Basic Graph Embeding Model\n    \"\"\"\n    def __init__(self, device, model_name, score_func):\n        self._g = None\n        self._model_name = model_name\n        self._device = device\n        self._entity_emb = KGEmbedding(device)\n        self._relation_emb = KGEmbedding(device)\n        self._score_func = score_func\n\n    def attach_graph(self, g, etid_field='tid', ntid_filed='ntid'):\n        \"\"\" Attach dataset into Graph Embedding Model\n\n        Parameter\n        ----------\n        g: DGLGraph\n            Input data for knowledge graph\n        etid_field: str\n            Edge feature name storing the edge type id\n        ntid_filed: str\n            Node feature name storing the node type id\n\n        Note\n        ----\n        If the input graph is DGLGraph, we assume that it uses a homogeneous graph\n        to represent the heterogeneous graph. The edge type id is stored in etid_field\n        and the node type id is stored in ntid_filed.\n        \"\"\"\n        self._etid_field = etid_field\n        self._ntid_filed = ntid_filed\n        assert isinstance(g, dgl.DGLGraph)\n        self._g = g\n\n    def load(self, model_path):\n        \"\"\" Load Graph Embedding Model from model_path.\n\n        The default entity embeding file is entity.npy.\n        The default relation embedding file is relation.npy.\n\n        Parameter\n        ---------\n        model_path : str\n            Path to store the model information\n        \"\"\"\n        pass\n\n    def save(self, model_path):\n        \"\"\" Save Graph Embedding Model into model_path.\n\n        All model related data are saved under model_path.\n        The default entity embeding file is entity.npy.\n        The default relation embedding file is relation.npy.\n\n        Parameter\n        ---------\n        model_path : str\n            Path to store the model information\n        \"\"\"\n        assert False, 'Not support training now'\n\n    def fit(self):\n        \"\"\" Start training\n        \"\"\"\n        assert False, 'Not support training now'\n\n    def eval(self):\n        \"\"\" Start evaluation\n        \"\"\"\n        assert False, 'Not support evaluation now'\n\n    def _infer_score_func(self, head, rel, tail, triplet_wise=False, batch_size=DEFAULT_INFER_BATCHSIZE):\n        head_emb = self.entity_embed[head]\n        rel_emb = self.relation_embed[rel]\n        tail_emb = self.entity_embed[tail]\n\n        num_head = head.shape[0]\n        num_rel = rel.shape[0]\n        num_tail = tail.shape[0]\n\n        score = []\n        if triplet_wise:\n            # triplet wise score: head, relation and tail tensor have the same length N,\n            # for i in range(N):\n            #     result.append(score(head[i],rel[i],tail[i]))\n            class FakeEdge(object):\n                def __init__(self, head_emb, rel_emb, tail_emb, device=-1):\n                    self._hobj = {}\n                    self._robj = {}\n                    self._tobj = {}\n                    self._hobj['emb'] = head_emb.to(device)\n                    self._robj['emb'] = rel_emb.to(device)\n                    self._tobj['emb'] = tail_emb.to(device)\n\n                @property\n                def src(self):\n                    return self._hobj\n\n                @property\n                def dst(self):\n                    return self._tobj\n\n                @property\n                def data(self):\n                    return self._robj\n\n            # calculate scores in mini-batches\n            # so we can use GPU to accelerate the speed with avoiding GPU OOM\n            for i in range((num_head + batch_size - 1) // batch_size):\n                sh_emb = head_emb[i * batch_size : (i + 1) * batch_size \\\n                                                   if (i + 1) * batch_size < num_head \\\n                                                   else num_head]\n                sr_emb = rel_emb[i * batch_size : (i + 1) * batch_size \\\n                                                  if (i + 1) * batch_size < num_head \\\n                                                  else num_head]\n                st_emb = tail_emb[i * batch_size : (i + 1) * batch_size \\\n                                                   if (i + 1) * batch_size < num_head \\\n                                                   else num_head]\n                edata = FakeEdge(sh_emb, sr_emb, st_emb, self._device)\n                score.append(self._score_func.edge_func(edata)['score'].to(th.device('cpu')))\n            score = th.cat(score, dim=0)\n            return score\n        else:\n            # head, relation and tail tensors has different size\n            # for h_i in range(head):\n            #     for r_j in range(relation):\n            #         for t_k in range(tail):\n            #             result.append(score(h_i, r_j, t_k))\n            # The result will have shape (len(head), len(relation), len(tail))\n            rel_emb = rel_emb.to(self._device)\n\n            # calculating scores using mini-batch, the default batchsize if 1024\n            # This can avoid OOM when using GPU\n            for i in range((num_head + batch_size - 1) // batch_size):\n                sh_emb = head_emb[i * batch_size : (i + 1) * batch_size \\\n                                                   if (i + 1) * batch_size < num_head \\\n                                                   else num_head]\n                s_score = []\n                sh_emb = sh_emb.to(self._device)\n                for j in range((num_tail + batch_size - 1) // batch_size):\n                    st_emb = tail_emb[j * batch_size : (j + 1) * batch_size \\\n                                                       if (j + 1) * batch_size < num_tail \\\n                                                       else num_tail]\n                    st_emb = st_emb.to(self._device)\n                    s_score.append(self._score_func.infer(sh_emb, rel_emb, st_emb).to(th.device('cpu')))\n                score.append(th.cat(s_score, dim=2))\n            score = th.cat(score, dim=0)\n            return th.reshape(score, (num_head, num_rel, num_tail))\n\n    def _exclude_pos(self, sidx, score, idx, head, rel, tail, topk, exec_mode, exclude_mode):\n        g = self.graph\n        num_triples = idx.shape[0]\n        num_head = 1 if exec_mode == 'batch_head' else head.shape[0]\n        num_rel = 1 if exec_mode == 'batch_rel' else rel.shape[0]\n        num_tail = 1 if exec_mode == 'batch_tail' else tail.shape[0]\n\n        res_head = []\n        res_rel = []\n        res_tail = []\n        res_score = []\n        result = []\n        if exclude_mode == 'exclude':\n            # exclude existing edges\n            cur_k = 0\n            batch_size = topk\n            while (cur_k < num_triples):\n                cur_sidx = sidx[cur_k:cur_k + batch_size if cur_k + batch_size < num_triples else num_triples]\n                cur_score = score[cur_k:cur_k + batch_size if cur_k + batch_size < num_triples else num_triples]\n                cur_idx = idx[cur_sidx]\n\n                if exec_mode == 'triplet_wise':\n                    cur_head = head[cur_idx]\n                    cur_rel = rel[cur_idx]\n                    cur_tail = tail[cur_idx]\n                elif exec_mode == 'all':\n                    tail_idx = cur_idx % num_tail\n                    cur_idx = floor_divide(cur_idx, num_tail)\n                    rel_idx = cur_idx % num_rel\n                    cur_idx = floor_divide(cur_idx, num_rel)\n                    head_idx = cur_idx % num_head\n\n                    cur_head = head[head_idx]\n                    cur_rel = rel[rel_idx]\n                    cur_tail = tail[tail_idx]\n                elif exec_mode == 'batch_head':\n                    tail_idx = cur_idx % num_tail\n                    cur_idx = floor_divide(cur_idx, num_tail)\n                    rel_idx = cur_idx % num_rel\n\n                    cur_head = th.full((cur_sidx.shape[0],), head, dtype=head.dtype)\n                    cur_rel = rel[rel_idx]\n                    cur_tail = tail[tail_idx]\n                elif exec_mode == 'batch_rel':\n                    tail_idx = cur_idx % num_tail\n                    cur_idx = floor_divide(cur_idx, num_tail)\n                    head_idx = cur_idx % num_head\n\n                    cur_head = head[head_idx]\n                    cur_rel = th.full((cur_sidx.shape[0],), rel, dtype=rel.dtype)\n                    cur_tail = tail[tail_idx]\n                elif exec_mode == 'batch_tail':\n                    rel_idx = cur_idx % num_rel\n                    cur_idx = floor_divide(cur_idx, num_rel)\n                    head_idx = cur_idx % num_head\n\n                    cur_head = head[head_idx]\n                    cur_rel = rel[rel_idx]\n                    cur_tail = th.full((cur_sidx.shape[0],), tail, dtype=tail.dtype)\n\n                # Find exising edges\n                # It is expacted that the existing edges are much less than triples\n                # The idea is: 1) we get existing edges using g.edge_ids\n                #              2) sort edges according to source node id (O(nlog(n)), n is number of edges)\n                #              3) sort candidate triples according to cur_head (O(mlog(m)), m is number of cur_head nodes)\n                #              4) go over all candidate triples and compare with existing edges,\n                #                 as both edges and candidate triples are sorted. filtering edges out\n                #                 will take only O(n+m)\n                #              5) sort the score again it taks O(klog(k))\n                uid, vid, eid = g.edge_ids(cur_head, cur_tail, return_uv=True)\n                rid = g.edata[self._etid_field][eid]\n\n                for i in range(cur_head.shape[0]):\n                    h = cur_head[i]\n                    r = cur_rel[i]\n                    t = cur_tail[i]\n\n                    h_where = uid == h\n                    t_where = vid[h_where] == t\n                    r_where = rid[h_where][t_where]\n                    edge_exist = False\n                    if r_where.shape[0] > 0:\n                        for c_r in r_where:\n                            if c_r == r:\n                                edge_exist = True\n                                break\n\n                    if edge_exist is False:\n                        res_head.append(h)\n                        res_rel.append(r)\n                        res_tail.append(t)\n                        res_score.append(cur_score[i])\n\n                if len(res_head) >= topk:\n                    break\n\n                cur_k += batch_size\n                batch_size = topk - len(res_head) # check more edges\n                batch_size = 16 if batch_size < 16 else batch_size # avoid tailing issue\n            res_head = th.tensor(res_head)\n            res_rel = th.tensor(res_rel)\n            res_tail = th.tensor(res_tail)\n            res_score = th.tensor(res_score)\n            sidx = th.argsort(res_score, dim=0, descending=True)\n            sidx = sidx[:topk] if topk < sidx.shape[0] else sidx\n            result.append((res_head[sidx],\n                           res_rel[sidx],\n                           res_tail[sidx],\n                           res_score[sidx],\n                           None))\n        else:\n            # including the existing edges in the result\n            topk = topk if topk < num_triples else num_triples\n            sidx = sidx[:topk]\n            idx = idx[sidx]\n\n            if exec_mode == 'triplet_wise':\n                head = head[idx]\n                rel = rel[idx]\n                tail = tail[idx]\n            elif exec_mode == 'all':\n                tail_idx = idx % num_tail\n                idx = floor_divide(idx, num_tail)\n                rel_idx = idx % num_rel\n                idx = floor_divide(idx, num_rel)\n                head_idx = idx % num_head\n\n                head = head[head_idx]\n                rel = rel[rel_idx]\n                tail = tail[tail_idx]\n            elif exec_mode == 'batch_head':\n                tail_idx = idx % num_tail\n                idx = floor_divide(idx, num_tail)\n                rel_idx = idx % num_rel\n\n                head = th.full((topk,), head, dtype=head.dtype)\n                rel = rel[rel_idx]\n                tail = tail[tail_idx]\n            elif exec_mode == 'batch_rel':\n                tail_idx = idx % num_tail\n                idx = floor_divide(idx, num_tail)\n                head_idx = idx % num_head\n\n                head = head[head_idx]\n                rel = th.full((topk,), rel, dtype=rel.dtype)\n                tail = tail[tail_idx]\n            elif exec_mode == 'batch_tail':\n                rel_idx = idx % num_rel\n                idx = floor_divide(idx, num_rel)\n                head_idx = idx % num_head\n\n                head = head[head_idx]\n                rel = rel[rel_idx]\n                tail = th.full((topk,), tail, dtype=tail.dtype)\n\n            if exclude_mode == 'mask':\n                # Find exising edges\n                # It is expacted that the existing edges are much less than triples\n                # The idea is: 1) we get existing edges using g.edge_ids\n                #              2) sort edges according to source node id (O(nlog(n)), n is number of edges)\n                #              3) sort candidate triples according to cur_head (O(mlog(m)), m is number of cur_head nodes)\n                #              4) go over all candidate triples and compare with existing edges and mask them,\n                #                 as both edges and candidate triples are sorted. filtering edges out\n                #                 will take only O(n+m)\n                uid, vid, eid = g.edge_ids(head, tail, return_uv=True)\n                rid = g.edata[self._etid_field][eid]\n                mask = th.full((head.shape[0],), False, dtype=th.bool)\n\n                if len(uid) > 0:\n                    for i in range(head.shape[0]):\n                        h = head[i]\n                        r = rel[i]\n                        t = tail[i]\n\n                        h_where = uid == h\n                        t_where = vid[h_where] == t\n                        r_where = rid[h_where][t_where]\n                        if r_where.shape[0] > 0:\n                            for c_r in r_where:\n                                if c_r == r:\n                                    mask[i] = True\n                                    break\n\n                result.append((head, rel, tail, score, mask))\n            else:\n                result.append((head, rel, tail, score, None))\n\n        return result\n\n    def _topk_exclude_pos(self, score, idx, head, rel, tail, topk, exec_mode, exclude_mode):\n        \"\"\" Generate topk most relevent triplets and corresponding scores.\n\n            It takes following steps:\n\n              1) find topk elements\n              2) sort topk elements in descending order\n              3) call _exclude_pos if figure out existing edges\n        \"\"\"\n        if exclude_mode == 'exclude':\n            if idx.shape[0] < topk * 4: # TODO(xiangsx): Find a better value of topk * n\n                topk_score, topk_sidx = th.topk(score, k=idx.shape[0], dim=0)\n                sidx = th.argsort(topk_score, dim=0, descending=True)\n                sidx = topk_sidx[sidx]\n                result = self._exclude_pos(sidx=sidx,\n                                           score=topk_score,\n                                           idx=idx,\n                                           head=head,\n                                           rel=rel,\n                                           tail=tail,\n                                           topk=topk,\n                                           exec_mode=exec_mode,\n                                           exclude_mode=exclude_mode)\n            else:\n                topk_score, topk_sidx = th.topk(score, k= topk * 4, dim=0)\n                sidx = th.argsort(topk_score, dim=0, descending=True)\n                sidx = topk_sidx[sidx]\n                result = self._exclude_pos(sidx=sidx,\n                                           score=topk_score,\n                                           idx=idx,\n                                           head=head,\n                                           rel=rel,\n                                           tail=tail,\n                                           topk=topk,\n                                           exec_mode=exec_mode,\n                                           exclude_mode=exclude_mode)\n                if len(result) < topk:\n                    sidx = th.argsort(score, dim=0, descending=True)\n                    result = self._exclude_pos(sidx=sidx,\n                                               score=score[sidx],\n                                               idx=idx,\n                                               head=head,\n                                               rel=rel,\n                                               tail=tail,\n                                               topk=topk,\n                                               exec_mode=exec_mode,\n                                               exclude_mode=exclude_mode)\n        else:\n            topk = idx.shape[0] if idx.shape[0] < topk else topk\n            topk_score, topk_sidx = th.topk(score, k=topk, dim=0)\n            sidx = th.argsort(topk_score, dim=0, descending=True)\n            sidx = topk_sidx[sidx]\n            result = self._exclude_pos(sidx=sidx,\n                                       score=topk_score,\n                                       idx=idx,\n                                       head=head,\n                                       rel=rel,\n                                       tail=tail,\n                                       topk=topk,\n                                       exec_mode=exec_mode,\n                                       exclude_mode=exclude_mode)\n        return result\n\n    def link_predict(self, head=None, rel=None, tail=None, exec_mode='all', sfunc='none', topk=10, exclude_mode=None, batch_size=DEFAULT_INFER_BATCHSIZE):\n        \"\"\" Predicts missing entities or relations in a triplet.\n\n        Given head_id, relation_id and tail_id, return topk most relevent triplet.\n\n        Parameters\n        ----------\n        head: th.Tensor\n            A tensor of head entity id.\n\n        rel: th.Tensor\n            A tensor of relation id.\n\n        tail: th.Tensor\n            A tensor of tail entity id.\n\n        exec_mode: str\n            How to calculate scores for triplets and calculate topK:\n\n              * triplet_wise: head, relation and tail lists have the same length N,\n                and we calculate the similarity triplet by triplet:\n                ``result = topK([score(h_i, r_i, t_i) for i in N])``,\n                the result shape will be (K,)\n\n              * all: three lists of head, relation and tail ids are provided as H, R and T,\n                and we calculate all possible combinations of all triplets (h_i, r_j, t_k):\n                ``result = topK([[[score(h_i, r_j, t_k) for each h_i in H] for each r_j in R] for each t_k in T])``,\n                the result shape will be (K,)\n\n              * batch_head: three lists of head, relation and tail ids are provided as H, R and T\n                and we calculate topK for each element in head:\n                ``result = topK([[score(h_i, r_j, t_k) for each r_j in R] for each t_k in T]) for each h_i in H``\n                the result shape will be (sizeof(H), K)\n\n              * batch_rel: three lists of head, relation and tail ids are provided as H, R and T,\n                and we calculate topK for each element in relation:\n                ``result = topK([[score(h_i, r_j, t_k) for each h_i in H] for each t_k in T]) for each r_j in R``,\n                the result shape will be (sizeof(R), K)\n\n              * batch_tail: three lists of head, relation and tail ids are provided as H, R and T,\n                and we calculate topK for each element in tail:\n                ``result = topK([[score(h_i, r_j, t_k) for each h_i in H] for each r_j in R]) for each t_k in T``,\n                the result shape will be (sizeof(T), K)\n\n        sfunc: str\n            What kind of score is used in ranking and will be output:\n\n              * none: $score = x$\n              * logsigmoid: $score = log(sigmoid(x))\n\n        topk: int\n            Return top k results\n\n        exclude_mode: str\n            Whether to exclude positive edges:\n\n            * None: Do not exclude positive edges.\n\n            * 'mask': Return topk edges and a mask indicating which one is positive edge.\n\n            * 'exclude': Exclude positive edges, the returned k edges will be missing edges in the graph.\n\n        Return\n        ------\n        A list of (head_idx, rel_idx, tail_idx, score)\n        \"\"\"\n        if head is None:\n            head = th.arange(0, self.num_entity)\n        else:\n            head = th.tensor(head)\n        if rel is None:\n            rel = th.arange(0, self.num_rel)\n        else:\n            rel = th.tensor(rel)\n        if tail is None:\n            tail = th.arange(0, self.num_entity)\n        else:\n            tail = th.tensor(tail)\n\n        num_head = head.shape[0]\n        num_rel = rel.shape[0]\n        num_tail = tail.shape[0]\n\n        if sfunc == 'none':\n            sfunc = none\n        else:\n            sfunc = logsigmoid\n\n        # if exclude_mode is not None, we need a graph to do the edge filtering\n        assert (self._g is not None) or (exclude_mode is None), \\\n            'If exclude_mode is not None, please use load_graph() to initialize ' \\\n            'a graph for edge filtering.'\n        if exec_mode == 'triplet_wise':\n            assert num_head == num_rel, \\\n                'For triplet wise exection mode, head, relation and tail lists should have same length'\n            assert num_head == num_tail, \\\n                'For triplet wise exection mode, head, relation and tail lists should have same length'\n\n            with th.no_grad():\n                raw_score = self._infer_score_func(head, rel, tail, triplet_wise=True, batch_size=batch_size)\n                score = sfunc(raw_score)\n                idx = th.arange(0, num_head)\n\n            result = self._topk_exclude_pos(score=score,\n                                            idx=idx,\n                                            head=head,\n                                            rel=rel,\n                                            tail=tail,\n                                            topk=topk,\n                                            exec_mode=exec_mode,\n                                            exclude_mode=exclude_mode)\n        elif exec_mode == 'all':\n            result = []\n            with th.no_grad():\n                raw_score = self._infer_score_func(head, rel, tail)\n                raw_score = th.reshape(raw_score, (head.shape[0]*rel.shape[0]*tail.shape[0],))\n                score = sfunc(raw_score)\n            idx = th.arange(0, num_head * num_rel * num_tail)\n\n            result = self._topk_exclude_pos(score=score,\n                                            idx=idx,\n                                            head=head,\n                                            rel=rel,\n                                            tail=tail,\n                                            topk=topk,\n                                            exec_mode=exec_mode,\n                                            exclude_mode=exclude_mode)\n        elif exec_mode == 'batch_head':\n            result = []\n            with th.no_grad():\n                raw_score = self._infer_score_func(head, rel, tail)\n            for i in range(num_head):\n                score = sfunc(th.reshape(raw_score[i,:,:], (rel.shape[0]*tail.shape[0],)))\n                idx = th.arange(0, num_rel * num_tail)\n\n                res = self._topk_exclude_pos(score=score,\n                                             idx=idx,\n                                             head=head[i],\n                                             rel=rel,\n                                             tail=tail,\n                                             topk=topk,\n                                             exec_mode=exec_mode,\n                                             exclude_mode=exclude_mode)\n\n                result.append(res[0])\n        elif exec_mode == 'batch_rel':\n            result = []\n            with th.no_grad():\n                raw_score = self._infer_score_func(head, rel, tail)\n            for i in range(num_rel):\n                score = sfunc(th.reshape(raw_score[:,i,:], (head.shape[0]*tail.shape[0],)))\n                idx = th.arange(0, num_head * num_tail)\n\n                res = self._topk_exclude_pos(score=score,\n                                             idx=idx,\n                                             head=head,\n                                             rel=rel[i],\n                                             tail=tail,\n                                             topk=topk,\n                                             exec_mode=exec_mode,\n                                             exclude_mode=exclude_mode)\n\n                result.append(res[0])\n        elif exec_mode == 'batch_tail':\n            result = []\n            with th.no_grad():\n                raw_score = self._infer_score_func(head, rel, tail)\n            for i in range(num_tail):\n                score = sfunc(th.reshape(raw_score[:,:,i], (head.shape[0]*rel.shape[0],)))\n                idx = th.arange(0, num_head * num_rel)\n\n                res = self._topk_exclude_pos(score=score,\n                                             idx=idx,\n                                             head=head,\n                                             rel=rel,\n                                             tail=tail[i],\n                                             topk=topk,\n                                             exec_mode=exec_mode,\n                                             exclude_mode=exclude_mode)\n\n                result.append(res[0])\n        else:\n            assert False, 'unknow execution mode type {}'.format(exec_mode)\n\n        return result\n\n    def _embed_sim(self, head, tail, emb, sfunc='cosine', bcast=False, pair_ws=False, topk=10):\n        batch_size=DEFAULT_INFER_BATCHSIZE\n        if head is None:\n            head = th.arange(0, emb.shape[0])\n        else:\n            head = th.tensor(head)\n        if tail is None:\n            tail = th.arange(0, emb.shape[0])\n        else:\n            tail = th.tensor(tail)\n        head_emb = emb[head]\n        tail_emb = emb[tail]\n\n        if sfunc == 'cosine':\n            sim_func = cosine_dist\n        elif sfunc == 'l2':\n            sim_func = l2_dist\n        elif sfunc == 'l1':\n            sim_func = l1_dist\n        elif sfunc == 'dot':\n            sim_func = dot_dist\n        elif sfunc == 'ext_jaccard':\n            sim_func = extended_jaccard_dist\n\n        if pair_ws is True:\n            result = []\n            # chunked cal score\n            score = []\n            num_head = head.shape[0]\n            num_tail = tail.shape[0]\n\n            # calculating scores using mini-batch, the default batchsize if 1024\n            # This can avoid OOM when using GPU\n            for i in range((num_head + batch_size - 1) // batch_size):\n                sh_emb = head_emb[i * batch_size : (i + 1) * batch_size \\\n                                                   if (i + 1) * batch_size < num_head \\\n                                                   else num_head]\n                sh_emb = sh_emb.to(self._device)\n                st_emb = tail_emb[i * batch_size : (i + 1) * batch_size \\\n                                                   if (i + 1) * batch_size < num_head \\\n                                                   else num_head]\n                st_emb = st_emb.to(self._device)\n                score.append(sim_func(sh_emb, st_emb, pw=True).to(th.device('cpu')))\n            score = th.cat(score, dim=0)\n\n            topk_score, topk_sidx = th.topk(score,\n                                            k=topk if score.shape[0] > topk else score.shape[0],\n                                            dim=0)\n            sidx = th.argsort(topk_score, dim=0, descending=True)\n            sidx = topk_sidx[sidx]\n            score = score[sidx]\n            result.append((head[sidx],\n                           tail[sidx],\n                           score))\n        else:\n            num_head = head.shape[0]\n            num_tail = tail.shape[0]\n\n            # calculating scores using mini-batch, the default batchsize if 1024\n            # This can avoid OOM when using GPU\n            score = []\n            for i in range((num_head + batch_size - 1) // batch_size):\n                sh_emb = head_emb[i * batch_size : (i + 1) * batch_size \\\n                                            if (i + 1) * batch_size < num_head \\\n                                            else num_head]\n                sh_emb = sh_emb.to(self._device)\n                s_score = []\n                for j in range((num_tail + batch_size - 1) // batch_size):\n                    st_emb = tail_emb[j * batch_size : (j + 1) * batch_size \\\n                                                    if (j + 1) * batch_size < num_tail \\\n                                                    else num_tail]\n                    st_emb = st_emb.to(self._device)\n                    s_score.append(sim_func(sh_emb, st_emb).to(th.device('cpu')))\n                score.append(th.cat(s_score, dim=1))\n            score = th.cat(score, dim=0)\n\n            if bcast is False:\n                result = []\n                idx = th.arange(0, num_head * num_tail)\n                score = th.reshape(score, (num_head * num_tail, ))\n\n                topk_score, topk_sidx = th.topk(score,\n                                                k=topk if score.shape[0] > topk else score.shape[0],\n                                                dim=0)\n                sidx = th.argsort(topk_score, dim=0, descending=True)\n                score = topk_score[sidx]\n                sidx = topk_sidx[sidx]\n                idx = idx[sidx]\n                tail_idx = idx % num_tail\n                idx = floor_divide(idx, num_tail)\n                head_idx = idx % num_head\n\n                result.append((head[head_idx],\n                               tail[tail_idx],\n                               score))\n\n            else: # bcast at head\n                result = []\n                for i in range(num_head):\n                    i_score = score[i]\n\n                    topk_score, topk_sidx = th.topk(i_score,\n                                                    k=topk if i_score.shape[0] > topk else i_score.shape[0],\n                                                    dim=0)\n                    sidx = th.argsort(topk_score, dim=0, descending=True)\n                    i_score = topk_score[sidx]\n                    idx = topk_sidx[sidx]\n\n                    result.append((th.full((topk,), head[i], dtype=head[i].dtype),\n                                  tail[idx],\n                                  i_score))\n\n        return result\n\n    def embed_sim(self, left=None, right=None, embed_type='entity', sfunc='cosine', bcast=False, pair_ws=False, topk=10):\n        \"\"\" Finds the most similar entity/relation embeddings for\n        some pre-defined similarity functions given a set of\n        entities or relations.\n\n        Parameters\n        ----------\n        left: th.Tensor\n            A tensor of left object id.\n\n        right: th.Tensor\n            A tensor of right object id.\n\n        embed_type: str\n            Whether it is using entity embedding or relation embedding.\n            If `entity`, it is entity embedding.\n            If 'relation', it is relation embedding.\n\n        sfunc: str\n            What kind of similarity function is used in ranking and will be output:\n\n              * cosine: use cosine similarity, score = $\\frac{x \\cdot y}{||x||_2||y||_2}$'\n\n              * l2: use l2 similarity, score = -$||x - y||_2$\n\n              * l1: use l1 similarity, score = -$||x - y||_1$\n\n              * dot: use dot product similarity, score = $x \\cdot y$\n\n              * ext_jaccard: use extended jaccard similarity, score = $\\frac{x \\cdot y}{||x||_{2}^{2} + ||y||_{2}^{2} - x \\cdot y}$\n\n        bcast: bool\n            If True, both left and right objects are provided as L and R,, and we calculate topK for each element in L:\n\n                * 'result = topK([score(l_i, r_j) for r_j in R]) for l_j in L, the result shape will be (sizeof(L), K)\n\n            Default: False\n\n        pair_ws: bool\n            If True, both left and right objects are provided with the same length N, and we will calculate the similarity pair by pair:\n\n              * result = topK([score(l_i, r_i)]) for i in N, the result shape will be (K,)\n\n            Default: False\n\n        topk: int\n            Return top k results\n\n        Note\n        ----\n        If both bcast and pair_ws is False, both left and right objects are provided as L and R,\n        and we calculate all possible combinations of (l_i, r_j):\n        ``result = topK([[score(l_i, rj) for l_i in L] for r_j in R])``,\n        the result shape will be (K,)\n\n        Return\n        ------\n        A list of (left_idx, right_idx, sim_score)\n        \"\"\"\n        if embed_type == 'entity':\n            emb = self.entity_embed\n        elif embed_type == 'relation':\n            emb = self.relation_embed\n        else:\n            assert False, 'emb should entity or relation'\n\n        return self._embed_sim(head=left,\n                               tail=right,\n                               emb=emb,\n                               sfunc=sfunc,\n                               bcast=bcast,\n                               pair_ws=pair_ws,\n                               topk=topk)\n\n    @property\n    def model_name(self):\n        return self._model_name\n\n    @property\n    def entity_embed(self):\n        return self._entity_emb.emb\n\n    @property\n    def relation_embed(self):\n        return self._relation_emb.emb\n\n    @property\n    def num_entity(self):\n        return -1 if self.entity_embed is None else self.entity_embed.shape[0]\n\n    @property\n    def num_rel(self):\n        return -1 if self.relation_embed is None else self.relation_embed.shape[0]\n\n    @property\n    def graph(self):\n        return self._g\n\nclass KGEModel(BasicGEModel):\n    \"\"\" Basic Knowledge Graph Embedding Model\n    \"\"\"\n    def __init__(self, device, model_name, score_func):\n        super(KGEModel, self).__init__(device, model_name, score_func)\n\n    def load(self, model_path):\n        entity_emb_file = 'entity.npy'\n        relation_emb_file = 'relation.npy'\n        self._entity_emb.load(model_path, entity_emb_file)\n        self._relation_emb.load(model_path, relation_emb_file)\n        self._score_func.load(model_path, self.model_name)\n\nclass TransEModel(KGEModel):\n    \"\"\" TransE Model\n    \"\"\"\n    def __init__(self, device, gamma):\n        model_name = 'TransE'\n        score_func = TransEScore(gamma, 'l2')\n        self._gamma = gamma\n        super(TransEModel, self).__init__(device, model_name, score_func)\n\nclass TransE_l2Model(KGEModel):\n    \"\"\" TransE_l2 Model\n    \"\"\"\n    def __init__(self, device, gamma):\n        model_name = 'TransE_l2'\n        score_func = TransEScore(gamma, 'l2')\n        self._gamma = gamma\n        super(TransE_l2Model, self).__init__(device, model_name, score_func)\n\nclass TransE_l1Model(KGEModel):\n    \"\"\" TransE_l1 Model\n    \"\"\"\n    def __init__(self, device, gamma):\n        model_name = 'TransE_l1'\n        score_func = TransEScore(gamma, 'l1')\n        self._gamma = gamma\n        super(TransE_l1Model, self).__init__(device, model_name, score_func)\n\nclass TransRModel(KGEModel):\n    \"\"\" TransR Model\n    \"\"\"\n    def __init__(self, device, gamma):\n        model_name = 'TransR'\n        # TransR score initialization is done at fit or load model\n        projection_emb = KGEmbedding(device)\n        score_func = TransRScore(gamma, projection_emb, -1, -1)\n        self._gamma = gamma\n        super(TransRModel, self).__init__(device, model_name, score_func)\n\n    def load(self, model_path):\n        super(TransRModel, self).load(model_path)\n        self._score_func.relation_dim = self._relation_emb.emb.shape[1]\n        self._score_func.entity_dim = self._entity_emb.emb.shape[1]\n\nclass DistMultModel(KGEModel):\n    \"\"\" DistMult Model\n    \"\"\"\n    def __init__(self, device):\n        model_name = 'DistMult'\n        score_func = DistMultScore()\n        super(DistMultModel, self).__init__(device, model_name, score_func)\n\nclass ComplExModel(KGEModel):\n    \"\"\" ComplEx Model\n    \"\"\"\n    def __init__(self, device):\n        model_name = 'ComplEx'\n        score_func = ComplExScore()\n        super(ComplExModel, self).__init__(device, model_name, score_func)\n\nclass RESCALModel(KGEModel):\n    \"\"\" RESCAL Model\n    \"\"\"\n    def __init__(self, device):\n        model_name = 'RESCAL'\n        score_func = RESCALScore(-1, -1)\n        super(RESCALModel, self).__init__(device, model_name, score_func)\n\n    def load(self, model_path):\n        super(RESCALModel, self).load(model_path)\n        self._score_func.entity_dim = self._entity_emb.emb.shape[1]\n        self._score_func.relation_dim = self._relation_emb.emb.shape[1] // self._score_func.entity_dim\n\nclass RotatEModel(KGEModel):\n    \"\"\" RotatE Model\n    \"\"\"\n    def __init__(self, device, gamma):\n        model_name = 'RotatE'\n        self._gamma = gamma\n        score_func = RotatEScore(gamma, 0)\n        super(RotatEModel, self).__init__(device, model_name, score_func)\n\n    def load(self, model_path):\n        super(RotatEModel, self).load(model_path)\n        # retrive emb_init, which is used in scoring func\n        entity_dim = self._entity_emb.emb.shape[1]\n        hidden_dim = entity_dim // 2\n        emb_init = (self._gamma + EMB_INIT_EPS) / hidden_dim\n        self._score_func.emb_init = emb_init\n\nclass GNNModel(BasicGEModel):\n    \"\"\" Basic GNN Model\n    \"\"\"\n    def __init__(self, device, model_name, gamma=0):\n        if model_name == 'TransE' or model_name == 'TransE_l2':\n            score_func = TransEScore(gamma, 'l2')\n        elif model_name == 'TransE_l1':\n            score_func = TransEScore(gamma, 'l1')\n        elif model_name == 'DistMult':\n            score_func = DistMultScore()\n        else:\n            assert model_name in ['TransE', 'TransE_l2', 'TransE_l1', 'DistMult'], \\\n                \"For general purpose Scoring function for GNN, we only support TransE_l1, TransE_l2\" \\\n                \"DistMult, but {} is given.\".format(model_name)\n\n        super(GNNModel, self).__init__(device, model_name, score_func)\n\n    def load(self, model_path):\n        entity_emb_file = 'entity.npy'\n        relation_emb_file = 'relation.npy'\n        self._entity_emb.load(model_path, entity_emb_file)\n        self._relation_emb.load(model_path, relation_emb_file)\n", "meta": {"hexsha": "12da92292a440cd5039bbbd4dd802cd229fce2b5", "size": 40513, "ext": "py", "lang": "Python", "max_stars_repo_path": "dgl-ke-ogb-lsc/python/dglke/models/ke_model.py", "max_stars_repo_name": "hhr114/Hetero-Reasoner", "max_stars_repo_head_hexsha": "2a95aa5398a4318a20cfb3a69bb887e9d9d88bd4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-06-15T12:18:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:33:22.000Z", "max_issues_repo_path": "dgl-ke-ogb-lsc/python/dglke/models/ke_model.py", "max_issues_repo_name": "MIRALab-USTC/KDDCup2021_WikiKG90M_GraphMIRAcles", "max_issues_repo_head_hexsha": "c4341ddceb6e9d85adc7a8357cfe738bc59443f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dgl-ke-ogb-lsc/python/dglke/models/ke_model.py", "max_forks_repo_name": "MIRALab-USTC/KDDCup2021_WikiKG90M_GraphMIRAcles", "max_forks_repo_head_hexsha": "c4341ddceb6e9d85adc7a8357cfe738bc59443f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-10-24T00:58:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T06:30:31.000Z", "avg_line_length": 41.4243353783, "max_line_length": 154, "alphanum_fraction": 0.5009996791, "include": true, "reason": "import numpy", "num_tokens": 8737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.33111972642778714, "lm_q1q2_score": 0.16814652557691476}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nColour Models Plotting\n======================\n\nDefines the colour models plotting objects:\n\n-   :func:`colourspaces_CIE_1931_chromaticity_diagram_plot`\n-   :func:`single_transfer_function_plot`\n-   :func:`multi_transfer_function_plot`\n\"\"\"\n\nfrom __future__ import division\n\nimport random\nimport numpy as np\nimport pylab\n\nfrom colour.models import POINTER_GAMUT_DATA, RGB_COLOURSPACES\nfrom colour.plotting import (\n    CIE_1931_chromaticity_diagram_plot,\n    aspect,\n    bounding_box,\n    display,\n    figure_size,\n    get_cmfs)\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013 - 2014 - Colour Developers'\n__license__ = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-science@googlegroups.com'\n__status__ = 'Production'\n\n__all__ = ['get_RGB_colourspace',\n           'colourspaces_CIE_1931_chromaticity_diagram_plot',\n           'single_transfer_function_plot',\n           'multi_transfer_function_plot']\n\n\ndef get_RGB_colourspace(colourspace):\n    \"\"\"\n    Returns the *RGB* colourspace with given name.\n\n    Parameters\n    ----------\n    colourspace : Unicode\n        *RGB* Colourspace name.\n\n    Returns\n    -------\n    RGB_Colourspace\n        *RGB* Colourspace.\n\n    Raises\n    ------\n    KeyError\n        If the given colourspace is not found in the factory colourspaces.\n    \"\"\"\n\n    colourspace, name = RGB_COLOURSPACES.get(colourspace), colourspace\n    if colourspace is None:\n        raise KeyError(\n            ('\"{0}\" colourspace not found in factory colourspaces: '\n             '\"{1}\".').format(name, sorted(RGB_COLOURSPACES.keys())))\n\n    return colourspace\n\n\n@figure_size((8, 8))\ndef colourspaces_CIE_1931_chromaticity_diagram_plot(\n        colourspaces=None,\n        cmfs='CIE 1931 2 Degree Standard Observer',\n        **kwargs):\n    \"\"\"\n    Plots given colourspaces in *CIE 1931 Chromaticity Diagram*.\n\n    Parameters\n    ----------\n    colourspaces : list, optional\n        Colourspaces to plot.\n    cmfs : unicode, optional\n        Standard observer colour matching functions used for diagram bounds.\n    \\*\\*kwargs : \\*\\*\n        Keywords arguments.\n\n    Returns\n    -------\n    bool\n        Definition success.\n\n    Examples\n    --------\n    >>> csps = ['sRGB', 'ACES RGB']\n    >>> colourspaces_CIE_1931_chromaticity_diagram_plot(csps)  # doctest: +SKIP\n    True\n    \"\"\"\n\n    if colourspaces is None:\n        colourspaces = ('sRGB', 'ACES RGB', 'Pointer Gamut')\n\n    cmfs, name = get_cmfs(cmfs), cmfs\n\n    settings = {'title': '{0} - {1}'.format(', '.join(colourspaces), name),\n                'standalone': False}\n    settings.update(kwargs)\n\n    if not CIE_1931_chromaticity_diagram_plot(**settings):\n        return\n\n    x_limit_min, x_limit_max = [-0.1], [0.9]\n    y_limit_min, y_limit_max = [-0.1], [0.9]\n    for colourspace in colourspaces:\n        if colourspace == 'Pointer Gamut':\n            x, y = tuple(zip(*POINTER_GAMUT_DATA))\n            pylab.plot(x,\n                       y,\n                       label='Pointer Gamut',\n                       color='0.95',\n                       linewidth=2)\n            pylab.plot([x[-1],\n                        x[0]],\n                       [y[-1],\n                        y[0]],\n                       color='0.95',\n                       linewidth=2)\n        else:\n            colourspace, name = get_RGB_colourspace(\n                colourspace), colourspace\n\n            random_colour = lambda: float(random.randint(64, 224)) / 255\n            r, g, b = random_colour(), random_colour(), random_colour()\n\n            primaries = colourspace.primaries\n            whitepoint = colourspace.whitepoint\n\n            pylab.plot([whitepoint[0], whitepoint[0]],\n                       [whitepoint[1], whitepoint[1]],\n                       color=(r, g, b),\n                       label=colourspace.name,\n                       linewidth=2)\n            pylab.plot([whitepoint[0], whitepoint[0]],\n                       [whitepoint[1], whitepoint[1]],\n                       'o',\n                       color=(r, g, b),\n                       linewidth=2)\n            pylab.plot([primaries[0, 0], primaries[1, 0]],\n                       [primaries[0, 1], primaries[1, 1]],\n                       'o-',\n                       color=(r, g, b),\n                       linewidth=2)\n            pylab.plot([primaries[1, 0], primaries[2, 0]],\n                       [primaries[1, 1], primaries[2, 1]],\n                       'o-',\n                       color=(r, g, b),\n                       linewidth=2)\n            pylab.plot([primaries[2, 0], primaries[0, 0]],\n                       [primaries[2, 1], primaries[0, 1]],\n                       'o-',\n                       color=(r, g, b),\n                       linewidth=2)\n\n            x_limit_min.append(np.amin(primaries[:, 0]))\n            y_limit_min.append(np.amin(primaries[:, 1]))\n            x_limit_max.append(np.amax(primaries[:, 0]))\n            y_limit_max.append(np.amax(primaries[:, 1]))\n\n    settings.update({'legend': True,\n                     'legend_location': 'upper right',\n                     'x_tighten': True,\n                     'y_tighten': True,\n                     'limits': [min(x_limit_min), max(x_limit_max),\n                                min(y_limit_min), max(y_limit_max)],\n                     'margins': [-0.05, 0.05, -0.05, 0.05],\n                     'standalone': True})\n\n    bounding_box(**settings)\n    aspect(**settings)\n\n    return display(**settings)\n\n\ndef single_transfer_function_plot(colourspace='sRGB', **kwargs):\n    \"\"\"\n    Plots given colourspace transfer function.\n\n    Parameters\n    ----------\n    colourspace : unicode, optional\n        *RGB* Colourspace transfer function to plot.\n    \\*\\*kwargs : \\*\\*\n        Keywords arguments.\n\n    Returns\n    -------\n    bool\n        Definition success.\n\n    Examples\n    --------\n    >>> single_transfer_function_plot()  # doctest: +SKIP\n    True\n    \"\"\"\n\n    settings = {'title': '{0} - Transfer Function'.format(colourspace)}\n    settings.update(kwargs)\n\n    return multi_transfer_function_plot([colourspace], **settings)\n\n\n@figure_size((8, 8))\ndef multi_transfer_function_plot(colourspaces=None,\n                                 inverse=False, **kwargs):\n    \"\"\"\n    Plots given colourspaces transfer functions.\n\n    Parameters\n    ----------\n    colourspaces : list, optional\n        Colourspaces transfer functions to plot.\n    inverse : bool\n        Plot inverse transfer functions.\n    \\*\\*kwargs : \\*\\*\n        Keywords arguments.\n\n    Returns\n    -------\n    bool\n        Definition success.\n\n    Examples\n    --------\n    >>> multi_transfer_function_plot(['sRGB', 'Rec. 709'])  # doctest: +SKIP\n    True\n    \"\"\"\n\n    if colourspaces is None:\n        colourspaces = ['sRGB', 'Rec. 709']\n\n    samples = np.linspace(0, 1, 1000)\n    for i, colourspace in enumerate(colourspaces):\n        colourspace, name = get_RGB_colourspace(colourspace), colourspace\n\n        RGBs = np.array([colourspace.inverse_transfer_function(x)\n                         if inverse else\n                         colourspace.transfer_function(x)\n                         for x in samples])\n        pylab.plot(samples,\n                   RGBs,\n                   label=u'{0}'.format(colourspace.name),\n                   linewidth=2)\n\n    settings = {\n        'title': '{0} - Transfer Functions'.format(\n            ', '.join(colourspaces)),\n        'x_tighten': True,\n        'legend': True,\n        'legend_location': 'upper left',\n        'x_ticker': True,\n        'y_ticker': True,\n        'grid': True,\n        'limits': [0, 1, 0, 1]}\n\n    settings.update(kwargs)\n\n    bounding_box(**settings)\n    aspect(**settings)\n\n    return display(**settings)\n", "meta": {"hexsha": "ff702e377b858377a1d9ffc02916830b0abaa47e", "size": 7797, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/plotting/models.py", "max_stars_repo_name": "canavandl/colour", "max_stars_repo_head_hexsha": "a453cd37b6135a9092d5ea5b2aafb8d19134bdff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-27T11:32:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-27T11:32:48.000Z", "max_issues_repo_path": "colour/plotting/models.py", "max_issues_repo_name": "canavandl/colour", "max_issues_repo_head_hexsha": "a453cd37b6135a9092d5ea5b2aafb8d19134bdff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/plotting/models.py", "max_forks_repo_name": "canavandl/colour", "max_forks_repo_head_hexsha": "a453cd37b6135a9092d5ea5b2aafb8d19134bdff", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6654411765, "max_line_length": 79, "alphanum_fraction": 0.5435423881, "include": true, "reason": "import numpy", "num_tokens": 1832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.3140505514119072, "lm_q1q2_score": 0.16804796122649052}}
{"text": "#!/usr/bin/env python\n# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 ai :\n\"\"\"\nA set of routines used in matching sources by offset histograms\n\nPath\n----\nHLApipeline/regression_testing/starmatch_hist.py\n\nDependencies\n------------\n* HLApipeline/regression_testing/infrot.py\n\nInputs\n------\nNone.\n\nClasses and Functions\n---------------------\n\"\"\"\n\nimport os,sys,numpy\nimport scipy.special, scipy.signal\nfrom scipy.ndimage.filters import maximum_filter\nfrom scipy.ndimage.morphology import generate_binary_structure\nimport astropy.io.fits as pyfits\nfrom astropy.table import Table\n\nfrom drizzlepac import util\nfrom drizzlepac.haputils import infrot\nfrom stsci.tools import logutil\n\n__taskname__ = 'starmatch_hist'\n\nMSG_DATEFMT = '%Y%j%H%M%S'\nSPLUNK_MSG_FORMAT = '%(asctime)s %(levelname)s src=%(name)s- %(message)s'\nlog = logutil.create_logger(__name__, level=logutil.logging.NOTSET, stream=sys.stdout,\n                            format=SPLUNK_MSG_FORMAT, datefmt=MSG_DATEFMT)\n\nmsgunit = sys.stdout\n\ndef run(source_list_dict, log_level,minimum_match=10, xref=0.0, yref=0.0, postarg=None):\n    \"\"\"\n    Match source lists in x,y coordinates allowing for possible shift & rotation\n\n    :param source_list_dict: dictionary indexed by coo filename with number of sources in each file as value\n    :param log_level: the desired level of verboseness in the log statements displayed on the screen and written to the .log file.\n    :param minimum_match: minimum number of matches in peak. Default value = '10'.\n    :param xref: X reference pixel in image (default 0, which is a very bad value if image rotates) \n    :param yref: Y reference pixel in image (default 0, which is a very bad value if image rotates) \n    :param postarg: dictionary indexed by coo filename with (dx, dy) in pixels for postarg (default is to read FITS headers)\n    :type source_list_dict: dictionary\n    :type log_level: integer\n    :type minimum_match: integer\n    :type xref: float\n    :type yref: float\n    :type postarg: dictionary\n    :returns: dictionary of lists of matching sourcelist indicies indexed by coo filename.\n    \"\"\"\n    log.setLevel(log_level)\n    out_dict={}\n    ### assumes list with greatest number of sources should be the reference file\n    (coo_ref,number)=max(iter(source_list_dict.items()), key=lambda x:x[1])\n    if postarg is None:\n        postarg = getpostarg(source_list_dict)\n    for coo_img in list(source_list_dict.keys()):\n        matched_flag=True\n        if coo_img == coo_ref:\n            matched_list=['#This is reference']\n        else:\n            matched_list,matching_lines_ref,matching_lines_img=match_cat_histogram(coo_ref,coo_img,maxdiff=50, step=1, verbose=True, extra_verbose=True,\n                    minimum_match=minimum_match, xref=xref, yref=yref,postarg_ref=postarg[coo_ref], postarg_img=postarg[coo_img])\n            if not matched_list:\n                matched_list=['#Not a thing found']\n            out_dict[coo_ref] = matching_lines_ref\n            out_dict[coo_img] = matching_lines_img\n        if len(matched_list) < minimum_match:\n            matched_flag = False\n            if coo_img == coo_ref:\n                log.info(\"\\n %s is reference image, starmatch_hist leaving WCS alone\\n\" %(os.path.basename(coo_img),))\n            else:\n                log.info(\"\\n %s -> %s starmatch_hist failed! Leaving WCS alone\\n\" %(os.path.basename(coo_img),coo_ref))\n    return(out_dict)\n\n\ndef read_cat_file(catfile):\n    \"\"\"\n    read in specified catalog file or daophot output file and force result to be a 2-D array if it is not empty\n    \n    :param catfile: catalog file to read in\n    :type catfile: string\n    :returns: Catalog file information (reshaped if need be)\n    \"\"\"\n    if catfile.endswith(\"point-cat.ecsv\"):\n        ecsvData = Table.read(catfile, format='ascii.ecsv') #now will read in and process HAP catalog data\n        data = numpy.stack((ecsvData[\"X-Center\"].data, ecsvData[\"Y-Center\"].data), axis=-1)\n    elif catfile.endswith(\"segment-cat.ecsv\"):\n        ecsvData = Table.read(catfile, format='ascii.ecsv') #now will read in and process HAP catalog data\n        data = numpy.stack((ecsvData[\"X-Centroid\"].data, ecsvData[\"Y-Centroid\"].data), axis=-1)\n    elif catfile.endswith(\"point-cat-fxm.ecsv\"):\n        ecsvData = Table.read(catfile, format='ascii.ecsv') #now will read in and process HAP catalog data\n        data = numpy.stack((ecsvData[\"xcentroid_ref\"].data, ecsvData[\"ycentroid_ref\"].data), axis=-1)\n    else:\n        try:\n            daoData = Table.read(catfile, format='ascii.daophot') #now will read in and process daophot data\n            data = numpy.stack((daoData[\"XCENTER\"].data, daoData[\"YCENTER\"].data), axis=-1)\n        except:\n            try:\n                data = numpy.loadtxt(catfile, comments='#', skiprows=0,usecols=(0,1)) #orig. loadtxt call for .coo files\n            except:\n                data = numpy.loadtxt(catfile, comments='#', usecols=(0, 1), delimiter=',', skiprows=1) #new loadtxt call for daophot.txt, sexphot.txt sourcelists\n    # force result to be 2-D if it is not empty\n    if data.size == 2:\n        data = data.reshape(1, data.size)\n    return data\n\n\ndef getpostarg(source_list_dict):\n    \"\"\"\n    Read FITS files used for the source list to get POSTARG info\n\n    :param source_list_dict: dictionary\n    :returns: dictionary of POSTARG info, keyed by image name\n    \"\"\"\n    rv = {}\n    for coo_img in source_list_dict:\n        fitsfile = coo_img.replace(coo_img.split(\"_\")[-1],\"drz.fits\")\n        if not os.path.exists(fitsfile):\n            fitsfile.replace(\"drz.fits\",\"drc.fits\")\n        if (os.path.exists(fitsfile) and fitsfile.endswith(\".fits\")):\n            try:\n                fh = pyfits.open(fitsfile)\n                hdr = fh[0].header\n                # assume image has north up (which is true for HLA images)\n                pixsize = abs(hdr['cd1_1'])*3600.0 #TODO: figure out how to get \"cd1_1\" (or eqivlent) value from final drizzle-combined (e.g. hst_10265_01_acs_wfc_f606w_drz.fits or hst_10265_01_acs_wfc_total_drz.fits) images\n                postarg1 = hdr['postarg1']/pixsize\n                postarg2 = hdr['postarg2']/pixsize\n                pa_aper = hdr['pa_aper']*numpy.pi/180 #TODO: figure out how to get \"pa_aper\" (or eqivlent) value from final drizzle-combined (e.g. hst_10265_01_acs_wfc_f606w_drz.fits or hst_10265_01_acs_wfc_total_drz.fits) images\n                fh.close()\n                cospa = numpy.cos(pa_aper)\n                sinpa = numpy.sin(pa_aper)\n                dx = cospa*postarg1-sinpa*postarg2\n                dy = sinpa*postarg1+cospa*postarg2\n                rv[coo_img] = (dx, dy)\n            except:\n                log.info(\"Warning: unable to fetch POSTARG info for image {}. Using POSTARG=0\".format(os.path.basename(fitsfile)))\n                rv[coo_img] = (0.0, 0.0)\n        else:\n            log.info('FITS file %s not found, using POSTARG=0' % os.path.basename(fitsfile))\n            rv[coo_img] = (0.0,0.0)\n    return rv\n\n\ndef match_cat_histogram(catHH, catWW, maxdiff=50, step=1, verbose = False, extra_verbose = True, minimum_match=10, xref=0.0, yref=0.0,\n        postarg_ref=(0.0,0.0), postarg_img=(0.0,0.0)):\n    \"\"\"\n    Procedure to find a coordinate match between two images\n    in the presence of substantial CR contamination\n    \n    Modified to work on pixel coordinates rather than RA, dec.\n    Assumes rectified tangent plane projection.  Note that\n    the step and tolerance (maxdiff) need to be in pixels.\n    \n    Default operation assumes that there is not a large rotation\n    (a small rotation is acceptable and is included in the matching)\n    and the shift is limited to less than maxdiff pixels in each\n    direction.\n    \n    Procedure includes the following steps:\n    \n    #. Compute two-dimensional histogram of source-to-source distances\n    #. Find best peak in histogram, determine significance\n    #. Match sources on basis of peak\n    #. Refine relative offset\n    #. Return matched column list of coordinates in the sense: ``X_ref Y_ref    X_transform Y_transform`` (ref and transform can be switched, in this order just to be consistent with XYXYMATCH output, hence right input for GEOTRAN) \n    \n    Tested.\n    \n    :param catHH: reference catalog name\n    :param catWW: coordinate catalog name\n    :param maxdiff: maximum difference value to use when computing histograms in *findOffset()*. Default value = 50.\n    :param step: max separation used by *catMatch()* (in pixels) to match sources in the catalogs. Default value = 1.\n    :param verbose: Verbose output (True/False)? Default value = False\n    :param extra_verbose: Even more verbose output (True/False)? Default value = False\n    :param minimum_match: Minimum number of matches. Default value = 10.\n    :param xref: x-axis pixel offset to place reference pixel at zero. Default value = 0.0\n    :param yref: y-axis pixel offset to place reference pixel at zero. Default value = 0.0\n    :param postarg_ref: tuple (dx,dy) with postarg pixel offsets for reference image\n    :param postarg_img: tuple (dx,dy) with postarg pixel offsets for coordinate image\n    :type catHH: string\n    :type catWW: string\n    :type maxdiff: integer\n    :type step: integer\n    :type verbose: Boolean\n    :type extra_verbose: Boolean\n    :type minimum_match: integer\n    :type xref: float\n    :type yref: float\n    :type postarg_ref: tuple (float, float)\n    :type postarg_img: tuple (float, float)\n    :returns: matched column list of coordinates, list of catHH lines that match catWW lines, and list of catWW lines that match catHH lines\n    \"\"\"\n    if extra_verbose:\n        log.info(\"Matching %s --> %s using the Stefano method.\"%(catWW.split(\"/\")[-1], catHH.split(\"/\")[-1]))\n    # Read the catalogs - Column 0 and 1 are the X and Y respectively\n    chh = read_cat_file(catHH)\n    if chh.size == 0:\n        log.info(\"Empty reference file {}\".format(catHH))\n        return []\n    x1 = chh[:,0]\n    y1 = chh[:,1]\n    cww = read_cat_file(catWW)\n    if cww.size == 0:\n        log.info(\"Empty coordinate file {}\".format(catWW))\n        return []\n    x2 = cww[:,0]\n    y2 = cww[:,1]\n\n    # offset to put reference pixel at zero\n    # this is what makes geomap work when there is rotation\n    x1 -= xref\n    y1 -= yref\n    x2 -= xref\n    y2 -= yref\n\n    # pdb.set_trace() #- for de-bugging\n    rv = findOffsetAndRotation(x1,y1, x2,y2, maxdiff, postarg_ref, postarg_img, verbose = verbose)\n    if rv is None:\n        if verbose: log.info(\"No significant peak found, skipping fine match\")\n        return [\"#No significant peak found\"],[],[]\n    base_offset, rotangle = rv\n\n    if verbose:\n        log.info(\"base_offset, rotangle {} {}\".format(base_offset, rotangle))\n    # Now match sources within bin; use radius = twice the bin size\n    index = catMatch(x1,y1, x2,y2, 2.*step, base_offset, rotangle)\n    # index is an array of length = n(cat1) with is -1 if the ith source\n    # has no match, and points to the matching source in cat2 if there\n    # is a match.  Thus the matched positions are:\n    ww = numpy.where(index > -1)[0]\n    nsub = numpy.size(ww)\n    subx1 = x1[ww]\n    suby1 = y1[ww]\n    subx2 = x2[index[ww]]\n    suby2 = y2[index[ww]]\n    if verbose: log.info(\"{}\".format(nsub))\n\n    # iterate to tighten up match if there is a tight cluster\n    # this is not useful if there is a rotation, so skip it \n    wsub = numpy.arange(nsub)\n    if rotangle == 0:\n        for iter in range(0,5):\n            dx = subx1-subx2\n            dy = suby1-suby2\n            meandx = numpy.mean(dx[wsub])\n            meandy = numpy.mean(dy[wsub])\n            dist = numpy.sqrt((dx-meandx)**2+(dy-meandy)**2)\n            rmsdist = numpy.sqrt(numpy.mean(dist[wsub]**2))\n            wsub = numpy.where(dist <= 2.*rmsdist)[0]\n            if verbose: log.info(\"{} {} {} {}\".format(meandx, meandy, rmsdist, wsub.size))\n\n    nsub = wsub.size\n    output_array = numpy.empty((nsub,4), dtype=float)\n    output_array[:,0] = subx1[wsub]\n    output_array[:,1] = suby1[wsub]\n    output_array[:,2] = subx2[wsub]\n    output_array[:,3] = suby2[wsub]\n\n    matching_lines_HH = ww[wsub]\n    matching_lines_WW = index[ww][wsub]\n    # print \"Sourcelist Matching Results\"\n    # print \"Reference sourcelist:  {} of {} total sources matched ({} %)\".format(len(matching_lines_HH),len(x1),100.0*(float(len(matching_lines_HH))/float(len(x1))))\n    # print \"Comparison sourcelist: {} of {} total sources matched ({} %)\".format(len(matching_lines_WW),len(x2),100.0*(float(len(matching_lines_WW))/float(len(x2))))\n    if nsub >= minimum_match:\n        # compute the shift and rotation\n        xshift, yshift, rotation = infrot.getxyshiftrot(output_array[:, 0], output_array[:, 1], output_array[:, 2], output_array[:, 3], xref=0.0, yref=0.0)\n        log.info(\"infrot xshift yshift rotation {} {} {}\".format(xshift, yshift, rotation))\n\n    output_array = output_array.astype(str)\n    column_list = [None]*nsub\n    for i, v in enumerate(output_array):\n        column_list[i] = ' '.join(v)\n    return column_list,matching_lines_HH,matching_lines_WW\n\n\ndef findOffsetAndRotation(x1,y1, x2, y2, maxdiff, postarg1, postarg2, verbose = False, oversample=5):\n    \"\"\"\n    Determine the offset of the positions in x1,y1 and x2,y2 using the\n    histogram method\n\n    This version uses an algorithm based on my xymatch function\n    (as in catMatch).  This uses a binning size of 1 pixel oversampled by a factor\n    oversample (default 5).  The oversample value is forced to be odd.\n\n    The approach is:\n    \n    #. Construct a 2D histogram count_diff in delta_x and delta_y from -maxdiff to maxdiff with a resolution 1/oversample pixels.  The position differences are computed for each source pair from the x1,y1 and x2,y2 lists.\n    #. Smooth the histogram with a boxcar of size oversample, giving a bin resolution of 1 pixel\n    #. Compute Hanning-filter smoothed version of the histogram.\n    #. Find all significant peaks in the histogram.\n    #. Filter out peaks near postarg offset (unless offset is near zero)\n    #. Return the position of the best peak x, y and rotation angle. This returns zeros if the peak is judged not to be significant.\n        \n    :param x1: X coordinates to match (list 1) \n    :param y1: Y coordinates to match (list 1)\n    :param x2: X coordinates to match (list 2) \n    :param y2: Y coordinates to match (list 2)\n    :param maxdiff: Max x,y difference value that will be used to generate histogram\n    :param postarg1: (dx,dy) for image 1\n    :param postarg2: (dx,dy) for image 2\n    :param verbose: Verbose output (True/False)? Default value = False\n    :param oversample: oversampling factor (NOTE: should be odd value). Default value = 5\n    :type x1: numpy.ndarray\n    :type y1: numpy.ndarray\n    :type x2: numpy.ndarray\n    :type y2: numpy.ndarray\n    :type maxdiff: Integer\n    :type postarg1: (float, float)\n    :type postarg2: (float, float)\n    :type verbose: Boolean\n    :type oversample: integer\n    :returns: (numpy.ndarray, float) x, y position of the peak and rotation angle.\n    \"\"\"\n    if x1.ndim != 1 or y1.ndim != 1 or x2.ndim != 1 or y2.ndim != 1:\n        raise ValueError(\"x and y parameters must be 1-D arrays\")\n    n1 = len(x1)\n    n2 = len(x2)\n    if n1 != len(y1) or n2 != len(y2):\n        raise ValueError(\"x and y arrays must be of equal length\")\n\n    # force oversample to be odd\n    oversample = oversample + (1 - (oversample % 2))\n    halfsample = (oversample-1)/2\n    foversample = float(oversample)\n\n    # add padding around edges so smoothing works better\n    # midpoint of array\n    xmid = maxdiff*oversample + halfsample\n    # size of array\n    nx = 2*xmid + 1\n    ny = nx\n    # trimmed size\n    nxtrim = nx - 2*halfsample\n    nytrim = ny - 2*halfsample\n\n    # get all pairs that match in box\n    p1, p2 = boxMatch(x1,y1,x2,y2,maxdiff)\n\n    # make histograms for a range of rotations\n    # rotation increment is determined by image size\n    rotinc = 1.0/max(abs(x1).max(), abs(x2).max())\n    # nrot = 51\n\n    #XXX RLW, 2017 October 17\n    #XXX this version has reverted to just doing rotation 0\n    #XXX keeping the rest of the code for the future though\n    nrot = 1\n    #XXX RLW, 2017 October 17\n\n    rotangle = (numpy.arange(nrot,dtype=float) - (nrot-1)/2) * rotinc\n    crot = numpy.cos(rotangle)\n    srot = numpy.sin(rotangle)\n    count_diff = numpy.zeros((nrot,int(nytrim),int(nxtrim)), dtype=numpy.int64)\n    for k in range(nrot):\n        cx2 = x2*crot[k] - y2*srot[k]\n        cy2 = y2*crot[k] + x2*srot[k]\n        delta_x = x1[p1] - cx2[p2]\n        delta_y = y1[p1] - cy2[p2]\n        ii = (delta_x*oversample + xmid).astype(int)\n        jj = (delta_y*oversample + xmid).astype(int)\n        count_diff[k,:,:] = fast_boxsum(bincount2d(jj,ii,ny,nx,clipped=False), oversample)\n    xmid = xmid - halfsample\n\n    irot0 = (nrot-1)/2\n    smax0 = count_diff[int(irot0)].max()\n    smax = count_diff.max()\n    # use zero-rotation histogram unless a rotated version is at least 1-sigma better\n    sthresh = (smax+smax0)/2.0 + numpy.sqrt((smax+smax0)/2.0)\n    if smax <= sthresh:\n        if verbose and smax > smax0:\n            log.info(\"Choosing zero-rot histogram peak {} over rotated max {} threshold={}\".format(smax0,smax,sthresh))\n        count_diff = count_diff[int(irot0)]\n        rotfactor = 1\n        rotangle = 0.0\n    else:\n        # pull out best slice of the histogram array\n        irot, jmax, imax = numpy.unravel_index(numpy.argmax(count_diff), count_diff.shape)\n        count_diff = count_diff[irot]\n        rotfactor = 2*numpy.abs(irot-irot0) + 1\n        rotangle = rotangle[irot]\n        if verbose:\n            log.info(\"Best histogram has rotation {} degrees\".format(rotangle*180/numpy.pi))\n            log.info(\"Rotated peak {} unrotated peak {}\".format(smax,smax0))\n\n    # find the best peak\n    jmax, imax, npred = findbestpeak(count_diff, oversample, postarg1, postarg2, verbose=verbose)\n    npred = npred*rotfactor\n    maxcount = count_diff[jmax,imax]\n    if verbose:\n        log.info(\"{} {} {}\".format(maxcount, imax, jmax))\n        log.info('number of predicted peaks of this size = {}'.format(npred))\n    # Is it significant?\n    # Require probability > 1-e3 that one of the pixels iin the histogram has this max or bigger\n    if npred >= 0.001:\n        if verbose: log.info('Maximum not very significant: predicted {} peaks'.format(npred))\n        return None\n    x_base_offset = (imax-xmid)/foversample\n    y_base_offset = (jmax-xmid)/foversample\n    return (numpy.array((x_base_offset, y_base_offset)), rotangle)\n\n\ndef fast_boxsum(a, size):\n    \"\"\"\n    Return box sum over region size**2 pixels while trimming off the (size-1)/2 pixels on each edge\n    \n    :param a: array of values to compute sums over\n    :param size: size of sampling box used to compute sums\n    :type a: numpy.ndarray\n    :type size: integer\n    :returns: numpy.ndarray (2-D) of sums\n    \"\"\"\n    b = numpy.insert(a,0,0,axis=1).cumsum(axis=1)\n    b = b[:,size:] - b[:,:-size]\n    b = numpy.insert(b,0,0,axis=0).cumsum(axis=0)\n    b = b[size:] - b[:-size]\n    return b\n\n\ndef findbestpeak(h, size, postarg1, postarg2, minthresh=1.e-3, verbose=False):\n    \"\"\"\n    Return the x,y location of the best histogram peak along with the number of predicted peaks of that amplitude\n    \n    :param h: 2-D histogram of counts\n    :param size: number of samples per pixel (used in smoothing)\n    :param postarg1: (dx,dy) for image 1\n    :param postarg2: (dx,dy) for image 2\n    :param minthresh: minimum probability threshold for peaks to consider. Default value = '1.0e-3'.\n    :param verbose: if true, prints info\n    :type h: numpy.ndarray\n    :type size: integer\n    :type postarg1: (float, float)\n    :type postarg2: (float, float)\n    :type minthresh: float\n    :type verbose: boolean\n    :returns: tuple (jmax, imax, npred)\n    \"\"\"\n\n    # Find maximum value\n    jmax, imax = numpy.unravel_index(numpy.argmax(h), h.shape)\n    maxcount = h[jmax,imax]\n    if maxcount == 0:\n        if verbose:\n            log.info(\"No matches in histogram\")\n        return (jmax, imax, 1.0)\n    hmean = numpy.mean(h)\n\n    # determine peak amplitude to get below minthresh random probability\n    # The gammainc function gives the Poisson cumulative probability that N >= maxcount\n    prob = scipy.special.gammainc(numpy.arange(maxcount)+1, hmean)\n    # get slope to empirically improve probability estimate\n    power = getprobcorr(prob, h, jmax, imax, size, verbose=verbose)\n    if verbose:\n        log.info(\"False-peak probability parameter {}\".format(power))\n    prob = prob**power\n    w = numpy.where(prob <= minthresh)[0]\n    if w.size == 0:\n        # no significant peaks\n        # just return the highest\n        return (jmax, imax, prob.min()*h.size)\n    thresh = w[0]+1\n    # locate all peaks above threshold in Hanning-smoothed version of image\n    sh = hanning_smooth(h, size)\n\n    jj, ii = findpeaks(sh, thresh)\n\n    # weed out peaks near postarg offset\n    xmid = (h.shape[1]-1)/2\n    ymid = (h.shape[0]-1)/2\n    dx = size*(postarg2[0] - postarg1[0])\n    dy = size*(postarg2[1] - postarg1[1])\n    # do not apply postarg filtering if zero shift is included\n    if dx**2+dy**2 > size**2:\n        w = numpy.where((ii-dx-xmid)**2+(jj-dy-ymid)**2 > size**2)\n        ss = ii.size\n        ii = ii[w]\n        jj = jj[w]\n        if ss != ii.size and verbose:\n            log.info(\"Filtered out {} peak near POSTARG position\".format(ss-ii.size))\n    else:\n        if verbose:\n            log.info(\"POSTARG near zero, no peaks excluded\")\n\n    if jj.size == 0:\n        # no peaks found\n        return (jmax, imax, 1.0)\n    # sort by increasing distance\n    distance = numpy.sqrt((jj-h.shape[0]/2)**2 + (ii-h.shape[1]/2)**2)\n    index = numpy.argsort(distance)\n    distance = distance[index]\n    ii = ii[index]\n    jj = jj[index]\n    # compute local mean of h at each peak using annulus\n    shalf = (size-1)/2\n    r1 = 4*shalf\n    r2 = 6*shalf\n    ky, kx = numpy.ogrid[-r2:r2+1,-r2:r2+1]\n    kr = kx*kx+ky*ky\n    kernel = ((kr >= r1**2) & (kr <= r2**2)).astype(float)\n    lmean = scipy.signal.convolve2d(h.astype(float), kernel, mode='same', boundary='fill', fillvalue=0)\n    norm = scipy.signal.convolve2d(h*0+1.0, kernel, mode='same', boundary='fill', fillvalue=0)\n    # use the global mean if it is higher than the local value\n    numpy.clip(lmean/norm, hmean, None, out=lmean)\n    hpeak = h[jj,ii]\n    bmean = lmean[jj,ii]\n    npred = numpy.pi*(distance+1)**2 * scipy.special.gammainc(hpeak, bmean)**power\n    # sort by expected chance count, then by decreasing peak amplitude, then by increasing background\n    # this handles the case where the predicted number is zero\n    index = numpy.lexsort((bmean,-hpeak,npred))\n    ii = ii[index]\n    jj = jj[index]\n    hpeak = hpeak[index]\n    bmean = bmean[index]\n    npred = npred[index]\n    keep = (ii-ii[0])^2+(jj-jj[0])^2 > size^2\n    keep[0] = True\n    ii = ii[keep]\n    jj = jj[keep]\n    hpeak = hpeak[keep]\n    bmean = bmean[keep]\n    npred = npred[keep]\n    if len(ii) == 1:\n        if verbose:\n            log.info(\"Only 1 peak left after weeding out nearby peaks\")\n        npbest = npred[0]\n    else:\n        if len(npred) > 1 and npred[1] < minthresh and hpeak[1] >= hpeak[0]-3*numpy.sqrt(hpeak[0]):\n            # if second-highest peak is also significant, this peak is not reliable\n            # return highest peak but with low significance\n            npbest = 1.0\n            if verbose:\n                log.info(\"More than 1 significant peak, not reliable (top 2 npred = %e %e hpeak = %d %d)\" % (npred[0], npred[1], hpeak[0], hpeak[1]))\n        else:\n            if len(npred) > 1 and npred[1] < minthresh and verbose:\n                log.info(\"2nd peak judged not significant (top 2 npred = %e %e hpeak = %d %d)\" % (npred[0], npred[1], hpeak[0], hpeak[1]))\n            npbest = npred[0]\n    return (jj[0], ii[0], npbest)\n\n\ndef findpeaks(image, thresh):\n    \"\"\"\n    Return positions of all peaks in image above threshold thresh\n    Based on `\"detect_peaks\" Stack Overflow discussion <https://stackoverflow.com/questions/3684484/peak-detection-in-a-2d-array/3689710#3689710>`_\n    \n    :param image: array of values to search\n    :param thresh: threshold for peaks\n    :type image: numpy.ndarray\n    :type thresh: float\n    :returns: index array (equivalent of where output)\n    \"\"\"\n    # define an 8-connected neighborhood\n    neighborhood = generate_binary_structure(2,2)\n    # find local maximum for each pixel\n    amax = maximum_filter(image, footprint=neighborhood)\n    w = numpy.where((image == amax) & (image >= thresh))\n    return w\n\n\ndef hanning_smooth(a, size):\n    \"\"\"\n    Return Hanning-smoothed version of histogram\n    \n    :param a: array of values to smooth\n    :param size: size of sampling box used to compute sums\n    :type a: numpy.ndarray\n    :type size: integer\n    :returns: numpy.ndarray (2-D) with smoothed array\n    \"\"\"\n    # create normalized 2-D Hanning filter\n    hfilter = numpy.hanning(size+3)[1:-1]\n    hfilter = numpy.outer(hfilter, hfilter)\n    hfilter = hfilter/hfilter.sum()\n    cim = scipy.signal.convolve2d(a, hfilter, mode='same', boundary='fill', fillvalue=0)\n    # normalize for pixels off edge\n    norm = scipy.signal.convolve2d(a*0+1.0, hfilter, mode='same', boundary='fill', fillvalue=0)\n    return cim/norm\n\ndef getprobcorr(prob, h, jmax, imax, size, verbose=False):\n    \"\"\"Use measured distribution of histogram values to improve probability estimate\n\n    Returns power <= 1 to raise original probability to get better value\n\n    :param prob: array of probability estimates for counts from 1 to max(h)\n    :param h: 2-D histogram of bin counts\n    :param jmax: location of maximum value in h\n    :param imax: location of maximum value in h\n    :param size: number of samples per pixel\n    :param verbose: if true, print info\n    :type prob: array\n    :type h: array\n    :type jmax: int\n    :type imax: int\n    :type size: int\n    :type verbose: boolean\n    :returns: float power to improve probability\n    \"\"\"\n    # remove points from histogram around peak\n    keep = numpy.ones(h.shape, dtype=bool)\n    shalf = int((size-1)/2)\n    j1 = max(jmax-shalf,0)\n    j2 = min(jmax+shalf, h.shape[0]-1)\n    i1 = max(imax-shalf,0)\n    i2 = min(imax+shalf, h.shape[1]-1)\n    keep[j1:j2,i1:i2] = False\n    hsub = h[numpy.where(keep)]\n    # distribution of counts excluding the peak\n    chist = numpy.bincount(hsub)\n    # trim leading zeros (and always remove zero counts)\n    hmin = max(numpy.argmax(chist != 0), 1)\n    chist = chist[hmin:]\n    # calculate reverse cumulative distribution\n    csum = chist[::-1].cumsum()[::-1] / float(hsub.size)\n    # note first element of prob is for 1 count, not zero\n    xx = prob[hmin-1:hmin-1+csum.size]\n    # avoid zero division (note these have zero weight too so they don't affect the weighted median)\n    # also drop log(0) values\n    w = numpy.where((xx != 1) & (xx != 0))[0]\n    if w.size == 0:\n        if verbose:\n            log.info(\"No points to fit after removing zero weights\")\n        return 1.0\n    xx = numpy.log(xx[w])\n    csum = csum[w]\n    # weighted median gives robust fit to power\n    power = wtmedian(numpy.log(csum)/xx, -xx) \n    if power > 1:\n        power = 1.0\n    return power\n\n\ndef wtmedian(a, wt):\n    \"\"\"Computed weighted median of array a\n    Use wt=1/sigma to get maximum likelihood estimator for\n    Laplacian noise distribution with amplitude sigma.\n\n    :param a: array with values\n    :param wt: array with weights (non-negative with size as a)\n    :type a: array_like\n    :type wt: array_like\n    :returns: a floating point weighted median value.\n    \"\"\"\n\n    a = numpy.ravel(a)\n    wt = numpy.ravel(wt).clip(min=0)\n    if a.size != wt.size:\n        raise ValueError(\"a and wt must be the same size\")\n    # ignore weights if all zero\n    if wt.max() == 0:\n        return numpy.median(a)\n\n    index = numpy.argsort(a)\n    wts = wt[index]\n    wsum = wts.cumsum()\n\n    # find first element in cumulative weight array >= sum/2\n    wthresh = 0.5*wsum[-1]\n    i = numpy.searchsorted(wsum, wthresh, side='left')\n    if wsum[i] == wthresh:\n        # Special case if sum is exactly half of total\n        # Average with next non-zero weight (equivalent to median with\n        # even number of points.)\n        ihi = numpy.searchsorted(wsum, wthresh, side='right')\n        return 0.5*(a[index[i]]+a[index[ihi]])\n    else:\n        return a[index[i]]\n\n\ndef bincount2d(jj, ii, ny, nx, clipped=False):\n\n    \"\"\"\n    Fast 2-D histogram using numpy.bincount\n\n    :param jj: 1-d array of y values\n    :param ii: 1-d array of x values \n    :param ny: X size of output 2-d histogram\n    :param nx: Y size of output 2-d histogram\n    :param clipped: Clip output histogram (True/False)? Note: if clipped is True, ii/jj values are already clipped to range 0..nx-1,0..ny-1. Default value = False\n    :type jj: numpy.ndarray\n    :type ii: numpy.ndarray\n    :type ny: integer \n    :type nx: integer\n    :type clipped: Boolean\n    :returns: (ny,nx) integer histogram with counts.\n    \"\"\"\n\n    if clipped:\n        index = ii + jj*nx\n    else:\n        ww = numpy.where((ii>=0) & (ii<nx) & (jj>=0) & (jj<ny))[0]\n        index = ii[ww] + jj[ww]*nx\n    return numpy.bincount(index.astype('int'), minlength=int(nx*ny)).reshape(int(ny),int(nx))\n\n\ndef catMatch(x1,y1, x2,y2, sep, offset=None, rotangle=None):\n\n    \"\"\"\n    Routine to match two lists of objects by position using 2-D Cartesian distances\n\n    Matches positions x1,y1 with positions in x2,y2, for matches within separation (sep).\n    If more than one match is found, the nearest is returned.  Input catalogs need not be sorted.\n\n    2017 June 15, Rick White\n    Based loosely on Marcel Haas's translation of my IDL routine xymatch.pro\n    \n    :param x1: X components of catalog 1\n    :param y1: Y components of catalog 1\n    :param x2: X components of catalog 2\n    :param y2: Y components of catalog 2\n    :param sep: Maximum allowed separation (in pixels) between sources for said sources to be considered 'matching'\n    :param offset: a 2-element array that (if specified) gets subtracted from the x1,y1 values\n    :param rotangle: rotation in degrees applied to x1,y1 values\n    :type x1: numpy.ndarray\n    :type y1: numpy.ndarray\n    :type x2: numpy.ndarray\n    :type y2: numpy.ndarray\n    :type sep: integer\n    :type offset: numpy.ndarray\n    :returns: an array of indices for 2nd list that correspond to the closest match (within sep) in cat2 for each object in cat1, so x1[i] matches x2[return_value[i]]. Note that objects in cat1 with no match within sep have indices -N-1 with N the length of cat2, so that IndexErrors will be raised if trying to assign these indices.\n    \"\"\"\n\n    if x1.ndim != 1 or y1.ndim != 1 or x2.ndim != 1 or y2.ndim != 1:\n        raise ValueError(\"x and y parameters must be 1-D arrays\")\n    if len(x1) != len(y1) or len(x2) != len(y2):\n        raise ValueError(\"x and y arrays must be of equal length\")\n\n    # apply offset and rotation\n    if rotangle is not None or offset is not None:\n        if rotangle is None:\n            rotangle = 0.0\n        if offset is None:\n            offset = (0.0, 0.0)\n        elif len(offset) != 2:\n            raise ValueError(\"offset must be a 2-element array\")\n        crot = numpy.cos(rotangle)\n        srot = numpy.sin(rotangle)\n        x1 = x1*crot + y1*srot - offset[0]\n        y1 = y1*crot - x1*srot - offset[1]\n\n    # Sort the arrays by increasing y-coordinate\n    is1 = y1.argsort()\n    x1 = x1[is1]\n    y1 = y1[is1]\n    is2 = y2.argsort()\n    x2 = x2[is2]\n    y2 = y2[is2]\n    # find search limits in y2 for each object in y1\n    # note this is designed to include the points that are exactly equal to maxdiff\n    kvlo = y2.searchsorted(y1-sep,'left').clip(0, len(y2))\n    kvhi = y2.searchsorted(y1+sep,'right').clip(kvlo, len(y2))\n\n    nnomatch = 0\n    n1 = len(x1)\n    p2 = numpy.zeros(n1, dtype='int') - len(x2) - 1\n    sepsq = sep**2\n    for i in range(n1):\n        y = y1[i]\n        x = x1[i]\n        klo = kvlo[i]\n        khi = kvhi[i]\n        dx = numpy.abs(x2[klo:khi] - x)\n        w = (dx <= sep).nonzero()[0]\n        if len(w) == 0:\n            # Nothing matched\n            nnomatch += 1\n        else:\n            distsq = (x - x2[klo+w])**2 + (y - y2[klo+w])**2\n            if distsq.min() <= sepsq:\n                p2[is1[i]] = is2[klo+w[distsq.argmin()]]\n            else:\n                nnomatch += 1\n    return p2\n\n\ndef boxMatch(x1,y1, x2,y2, sep):\n\n    \"\"\"\n    Routine to match two lists of objects by position using 2-D Cartesian distances\n\n    Matches positions x1,y1 with positions in x2,y2, for matches within a box of size +- sep.\n    *All* matches within the box are returned.  Input catalogs need not be sorted.\n\n    2017 October 14, Rick White\n    \n    :param x1: X components of catalog 1\n    :param y1: Y components of catalog 1\n    :param x2: X components of catalog 2\n    :param y2: Y components of catalog 2\n    :param sep: Half-size of xy box in pixels between sources for said sources to be considered 'matching'\n    :type x1: numpy.ndarray\n    :type y1: numpy.ndarray\n    :type x2: numpy.ndarray\n    :type y2: numpy.ndarray\n    :type sep: integer\n    :returns: (p1, p2) index arrays into source lists with matching pairs\n    \"\"\"\n\n    if x1.ndim != 1 or y1.ndim != 1 or x2.ndim != 1 or y2.ndim != 1:\n        raise ValueError(\"x and y parameters must be 1-D arrays\")\n    if len(x1) != len(y1) or len(x2) != len(y2):\n        raise ValueError(\"x and y arrays must be of equal length\")\n\n    # Sort the arrays by increasing y-coordinate\n    is1 = y1.argsort()\n    x1 = x1[is1]\n    y1 = y1[is1]\n    is2 = y2.argsort()\n    x2 = x2[is2]\n    y2 = y2[is2]\n    # find search limits in y2 for each object in y1\n    # note this is designed to include the points that are exactly equal to maxdiff\n    kvlo = y2.searchsorted(y1-sep,'left').clip(0, len(y2))\n    kvhi = y2.searchsorted(y1+sep,'right').clip(kvlo, len(y2))\n\n    p1 = []\n    p2 = []\n    n1 = len(x1)\n    for i in range(n1):\n        y = y1[i]\n        x = x1[i]\n        klo = kvlo[i]\n        khi = kvhi[i]\n        dx = numpy.abs(x2[klo:khi] - x)\n        w = (dx <= sep).nonzero()[0]\n        if w.size > 0:\n            p1.append(numpy.zeros(w.size,dtype=int)+is1[i])\n            p2.append(is2[klo+w])\n    if p1:\n        return (numpy.hstack(p1), numpy.hstack(p2))\n    else:\n        return (numpy.array([],dtype=int), numpy.array([],dtype=int))\n\n\nif __name__ == '__main__':\n    import getopt\n\n    def usage(msg=None):\n        log.info(\"Usage: %s [-r xref,yref] coo1 coo2...\" % sys.argv[0])\n        if msg: log.info(\"{}\".format(msg))\n        sys.exit(1)\n\n    try:\n        opts, args = getopt.getopt(sys.argv[1:], \"r:h\")\n    except getopt.error as e:\n        usage(str(e))\n    xref = 0.0\n    yref = 0.0\n    for opt, value in opts:\n        if opt == \"-r\":\n            try:\n                xref, yref = list(map(float, value.split(',')))\n            except ValueError as e:\n                usage(\"Argument for -r must be comma-separated pair of floats\")\n        elif opt == \"-h\":\n            usage()\n        else:\n            usage(\"Unknown option '%s'\" % opt)\n    msgunit = sys.stderr\n    source_list_dict = {}\n    for cooname in args:\n        source_list_dict[cooname] = len(open(cooname).readlines())\n    matched=run(source_list_dict, xref=xref, yref=yref)\n    # print >> msgunit, 'matched keys'\n    # print >> msgunit, matched.keys()\n    # print \"x1 y1 x2 y2\"\n    # print '\\n'.join(matched[list2]['matchlist'])\n", "meta": {"hexsha": "22ede9041087116a1ae436cf03a1ca255c08f8c7", "size": 35384, "ext": "py", "lang": "Python", "max_stars_repo_path": "drizzlepac/haputils/starmatch_hist.py", "max_stars_repo_name": "check-spelling/drizzlepac", "max_stars_repo_head_hexsha": "19baaf5a416c72f272889800b13d251f33f76d2c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2016-08-16T04:16:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:39:29.000Z", "max_issues_repo_path": "drizzlepac/haputils/starmatch_hist.py", "max_issues_repo_name": "check-spelling/drizzlepac", "max_issues_repo_head_hexsha": "19baaf5a416c72f272889800b13d251f33f76d2c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 822, "max_issues_repo_issues_event_min_datetime": "2016-03-10T01:19:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:25:34.000Z", "max_forks_repo_path": "drizzlepac/haputils/starmatch_hist.py", "max_forks_repo_name": "check-spelling/drizzlepac", "max_forks_repo_head_hexsha": "19baaf5a416c72f272889800b13d251f33f76d2c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2016-03-16T19:18:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-27T04:20:44.000Z", "avg_line_length": 40.4388571429, "max_line_length": 333, "alphanum_fraction": 0.6416459417, "include": true, "reason": "import scipy,from scipy,import astropy,from astropy", "num_tokens": 10079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3140505578320071, "lm_q1q2_score": 0.16804796000521777}}
{"text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nReddening laws.\n\"\"\"\nimport pylab as py\nimport numpy as np\nfrom scipy import interpolate\nimport pysynphot\nfrom scipy.linalg import solve_banded\nimport pdb\n\n\ndef get_red_law(str):\n    \"\"\"\n    Given a reddening law name, return the reddening\n    law object.\n\n    Parameters:\n    ----------\n    str: str\n        Reddening law name and additional params (comma-separated).\n        Name must match \n    \"\"\"\n    # Parse the string, extracting redlaw name and other params\n    tmp = str.split(',')\n    name = tmp[0]\n    params = ()\n    if len(tmp) > 1:\n        for ii in range(len(tmp) - 1):\n            params = params + (float(tmp[ii+1]),)\n\n    # Define dictionary connecting redlaw names to the redlaw classes\n    name_dict = {'N09':RedLawNishiyama09,\n                     'C89': RedLawCardelli,\n                     'RZ07': RedLawRomanZuniga07,\n                     'RL85': RedLawRiekeLebofsky,\n                     'D16': RedLawDamineli16,\n                     'DM16': RedLawDeMarchi16,\n                     'F09': RedLawFitzpatrick09,\n                     'S16': RedLawSchlafly16,\n                     'pl': RedLawPowerLaw,\n                     'F11': RedLawFritz11,\n                     'H18': RedLawHosek18,\n                     'H18b': RedLawHosek18b,\n                     'NL18': RedLawNoguerasLara18}\n\n    # Make reddening law object, including params if necessary.\n    # This is not great coding, but I really strugged to generalize this...\n    if len(params) == 0:\n        red_law = name_dict[name]()\n    elif len(params) == 1:\n        red_law = name_dict[name](params[0])\n    elif len(params) == 2:\n        red_law = name_dict[name](params[0], params[1])\n    elif len(params) == 3:\n        red_law = name_dict[name](params[0], params[1], params[2])\n    elif len(params) == 4:\n        red_law = name_dict[name](params[0], params[1], params[2], params[3])\n    else:\n        mes = 'Redlaw contains more params than reddening.get_red_law currently supports'\n        raise ValueError(mes)\n\n    return red_law\n\nclass RedLawNishiyama09(pysynphot.reddening.CustomRedLaw):\n    \"\"\"\n    Defines extinction law from `Nishiyama et al. 2009 \n    <https://ui.adsabs.harvard.edu/abs/2009ApJ...696.1407N/abstract>`_\n    toward the Galactic Center. This is the default extinction law. \n    The law is defined between 0.5 -- 8 microns.\n    \"\"\"\n    def __init__(self):\n        # Fetch the extinction curve, pre-interpolate across 3-8 microns\n        wave = np.arange(0.5, 8.0, 0.001)\n        \n        # This will eventually be scaled by AKs when you\n        # call reddening(). Right now, calc for AKs=1\n        wave_vals, Alambda_scaled = RedLawNishiyama09._derive_nishiyama09(wave)\n\n        # Convert wavelength to angstrom\n        wave_vals *= 10 ** 4\n\n        pysynphot.reddening.CustomRedLaw.__init__(self, wave=wave_vals, \n                                                  waveunits='angstrom',\n                                                  Avscaled=Alambda_scaled,\n                                                  name='Nishiyama09',\n                                                  litref='Nishiyama+ 2009')\n\n        # Set the upper/lower wavelength limits of law (in angstroms)\n        self.low_lim = min(wave_vals)\n        self.high_lim = max(wave_vals)\n        self.name = 'N09'\n    \n    @staticmethod\n    def _derive_nishiyama09(wavelength):\n        \"\"\" \n        Calculate the N09 extinction law as defined in the paper:\n        a A_lambda/AKs = power law of exponent -2.0 between JHK. Then\n        use a *linear* interpolation in 1/lambda space to go from J to the V-band observation,\n        in order to avoid imposing more structure. A cublic spline interpolation\n        across the wavelength points is used longward of K-band\n\n        Parameters\n        ----------\n        wavelength : float\n            in microns\n        AKs : float\n            in magnitudes\n        \"\"\"\n        #-----Define power law extinction law between JHK----#\n        jhk_idx = np.where( (wavelength >= 1.25) & (wavelength <= 2.14) )\n        \n        alpha = 2.0\n        wave_jhk = wavelength[jhk_idx]\n\n        A_jhk = wave_jhk**(-1.0*alpha)\n        A_Ks_jhk = A_jhk / A_jhk[-1]\n\n        #----Now do a linear interpolation (in log(1/lambda) vs log(A/AKs) space) between 1.25 microns and 0.551 microns---#\n        jv_idx = np.where( (wavelength < 1.25) & (wavelength > 0.551) )\n        Av = 16.13\n        func = interpolate.interp1d(np.log10(np.array([1.0/1.25, 1.0/0.551])), np.log10(np.array([A_Ks_jhk[0], Av])),\n                                        kind='linear')\n        A_Ks_jv = func(np.log10(1.0 / wavelength[jv_idx]))\n\n        # Convert back to linear space\n        A_Ks_jv = 10**A_Ks_jv\n\n        #---Do a spline interpolation for the rest of the (long-wavelength) law---#\n        # We do this since no other function form is given\n        long_idx = np.where(wavelength > 2.14)\n        wave = np.array([0.551, 1.25, 1.63, 2.14, 3.545, 4.442, 5.675, 7.760])\n        A_AKs = np.array([16.13, 3.02, 1.73, 1.00, 0.500, 0.390, 0.360, 0.430])\n        \n        spline_interp = interpolate.splrep(wave, A_AKs, k=3, s=0)\n        A_AKs_long = interpolate.splev(wavelength[long_idx], spline_interp)\n        \n        # Stitch together sections for the final law\n        wave_vals = np.concatenate((wavelength[jv_idx[0]], wavelength[jhk_idx[0]]))\n        A_AKs_vjhk = np.concatenate((A_Ks_jv, A_Ks_jhk))\n\n        # Now add the long-wavelength law\n        wave_vals = np.concatenate((wave_vals, wavelength[long_idx[0]]))\n        A_AKs_final = np.concatenate((A_AKs_vjhk, A_AKs_long))\n\n        return wave_vals, A_AKs_final\n\n    def Nishiyama09(self, wavelength, AKs):\n        \"\"\" \n        Return the extinction at a given wavelength assuming the \n        extinction law and an overall `AKs` value.\n\n        Parameters\n        ----------\n        wavelength : float or array\n            Wavelength to return extinction for, in microns\n        AKs : float\n            Total extinction in AKs, in mags\n        \"\"\"\n        # If input entry is a single float, turn it into an array\n        try:\n            len(wavelength)\n        except:\n            wavelength = [wavelength]\n\n        # Return error if any wavelength is beyond interpolation range of\n        # extinction law\n        if ((min(wavelength) < (self.low_lim*10**-4)) | (max(wavelength) > (self.high_lim*10**-4))):\n            return ValueError('{0}: wavelength values beyond interpolation range'.format(self))\n            \n        # Extract wave and A/AKs from law, turning wave into micron units\n        wave = self.wave * (10**-4)\n        law = self.obscuration\n\n        # Find the value of the law at the closest points\n        # to wavelength\n        A_AKs_at_wave = []\n        for ii in wavelength:\n            idx = np.where( abs(wave - ii) == min(abs(wave - ii)) )\n            A_AKs_at_wave.append(law[idx][0])\n\n        # Now multiply by AKs (since law assumes AKs = 1)\n        A_at_wave = np.array(A_AKs_at_wave) * AKs\n\n        return A_at_wave\n        \nclass RedLawCardelli(pysynphot.reddening.CustomRedLaw):\n    \"\"\"\n    Defines the extinction law from  \n    `Cardelli et al. 1989 <https://ui.adsabs.harvard.edu/abs/1989ApJ...345..245C/abstract>`_. \n    The law is defined from 0.3 - 3 microns, and in terms\n    of :math:`A_{\\lambda} / A_{Ks}`, where Ks is 2.174 microns.\n\n    Parameters\n    ----------\n    Rv : float\n        Ratio of absolute to selective extinction, :math:`A(V) / E(B-V)`. \n        The standard value for the diffuse ISM is 3.1.\n    \"\"\"\n    def __init__(self, Rv):\n        # Fetch the extinction curve, pre-interpolate across 0.3-3 microns\n        wave = np.arange(0.3, 3.0, 0.001)\n        \n        # This will eventually be scaled by AKs when you\n        # call reddening(). Produces A_lambda for AKs = 1, which will be \n        # scaled later. Expects wavelength in microns\n        Alambda_scaled = RedLawCardelli._derive_cardelli(wave, Rv)\n\n        # Convert wavelength to angstrom\n        wave *= 10 ** 4\n\n        pysynphot.reddening.CustomRedLaw.__init__(self, wave=wave, \n                                                  waveunits='angstrom',\n                                                  Avscaled=Alambda_scaled,\n                                                  name='Cardelli89',\n                                                  litref='Cardelli+ 2009')\n\n        # Set the upper/lower wavelength limits of law (in angstroms)\n        self.low_lim = min(wave)\n        self.high_lim = max(wave)\n        self.name = 'C89,{0}'.format(Rv)\n\n    @staticmethod\n    def _derive_cardelli(wavelength, Rv):\n        \"\"\"\n        Cardelli extinction law. This produces extinction values expected\n        for AKs = 1\n        \"\"\"\n        x = 1.0 / np.array(wavelength)\n\n        # check for applicability\n        if (np.min(x) < 0.3):\n            print( 'wavelength is longer than applicable range for Cardelli law')\n            return None\n\n        if (np.max(x) > 8.0):\n            print( 'wavelength is shorter than applicable range for Cardelli law')\n            return None\n        \n        # Set up some arrays for coefficients that we will need\n        a = np.zeros(len(x), dtype=float)\n        b = np.zeros(len(x), dtype=float)\n\n        y = x - 1.82\n\n        # Calculate coefficients for long wavelengths (low wavenumber)\n        # Wavenumger <= 1.1 (Eq. 2a, 2b)\n        idx = np.where(x <= 1.1)[0]\n        a[idx] =  0.574 * x[idx] ** 1.61\n        b[idx] = -0.527 * x[idx] ** 1.61\n\n        # Calculate coefficients for intermediate wavelengths\n        # 1.1 < wavenumber <= 3.3 (Eq. 3a, 3b)\n        idx = np.where((x > 1.1) & (x <= 3.3))[0]\n        yy = y[idx]\n        a[idx] = 1 + (0.17699 * yy) - (0.50447 * yy ** 2) - \\\n            (0.02427 * yy ** 3) + (0.72085 * yy ** 4) + \\\n            (0.01979 * yy ** 5) - (0.77530 * yy ** 6) + \\\n            (0.32999 * yy ** 7)\n        b[idx] = (1.41338 * yy) + (2.28305 * yy ** 2) + \\\n            (1.07233 * yy ** 3) - (5.38434 * yy ** 4) - \\\n            (0.62251 * yy ** 5) + (5.30260 * yy ** 6) - \\\n            (2.09002 * yy ** 7)\n\n        # Calculate the long wavelength\n        # 3.3 < wavenumber < 5.9 (Eq. 4a, 4b)\n        idx = np.where((x > 3.3) & (x < 5.9))[0]\n        xx = x[idx]\n        a[idx] = 1.752 - (0.316 * xx) - (0.104/((xx - 4.67) ** 2 + 0.341))\n        b[idx] = -3.090 + (1.825 * xx) + (1.206/((xx - 4.62) ** 2 + 0.263))\n\n        # Calculate the longest wavelength\n        # 5.9 <= wavenumber (Eq. 4a, 4b)\n        idx = np.where(x >= 5.9)[0]\n        xx = x[idx]\n        a[idx] = 1.752 - (0.316 * xx) - (0.104/((xx - 4.67) ** 2 + 0.341)) + \\\n            (-0.04473 * (xx - 5.9) ** 2) - (0.009779 * (xx - 5.9) ** 3)\n        b[idx] = -3.090 + (1.825 * xx) + (1.206/((xx - 4.62) ** 2 + 0.263)) + \\\n            (0.2130 * (xx - 5.9) ** 2) + (0.1207 * (xx - 5.9) ** 3)\n\n        # A(lam) / A(V), from Eq. 1\n        extinction = a + b/Rv\n\n        # Now, want to produce A_lambda / AKs, to match other laws\n        k_ind = np.where(abs(x-0.46) == min(abs(x-0.46)))\n        Aks_Av = a[k_ind] + b[k_ind]/Rv # Aks / Av\n        Av_Aks = 1.0 / Aks_Av # Av / Aks\n        \n        output = extinction * Av_Aks # (A(lamb) / Av) * (Av / Aks) = (A(lamb) / Aks)\n\n        return output\n\n    def Cardelli89(self, wavelength, AKs):\n        \"\"\" \n        Return the extinction at a given wavelength assuming the \n        extinction law and an overall `AKs` value.\n\n        Parameters\n        ----------\n        wavelength : float or array\n            Wavelength to return extinction for, in microns\n        AKs : float\n            Total extinction in AKs, in mags\n        \"\"\"\n        # If input entry is a single float, turn it into an array\n        try:\n            len(wavelength)\n        except:\n            wavelength = [wavelength]\n\n        # Return error if any wavelength is beyond interpolation range of\n        # extinction law\n        if ((min(wavelength) < (self.low_lim*10**-4)) | (max(wavelength) > (self.high_lim*10**-4))):\n            return ValueError('{0}: wavelength values beyond interpolation range'.format(self))\n            \n        # Extract wave and A/AKs from law, turning wave into micron units\n        wave = self.wave * (10**-4)\n        law = self.obscuration\n\n        # Find the value of the law at the closest points\n        # to wavelength\n        A_AKs_at_wave = []\n        for ii in wavelength:\n            idx = np.where( abs(wave - ii) == min(abs(wave - ii)) )\n            A_AKs_at_wave.append(law[idx][0])\n\n        # Now multiply by AKs (since law assumes AKs = 1)\n        A_at_wave = np.array(A_AKs_at_wave) * AKs\n\n        return A_at_wave\n    \nclass RedLawRomanZuniga07(pysynphot.reddening.CustomRedLaw):\n    \"\"\"\n    Defines extinction law from `Roman-Zuniga et al. 2007\n    <https://ui.adsabs.harvard.edu/abs/2007ApJ...664..357R/abstract>`_\n    for the dense cloud core Barnard 59. It is defined between 1.0 - 8.0\n    microns.\n    \"\"\"\n    def __init__(self):\n        # Fetch the extinction curve, pre-interpolate across 1-8 microns\n        wave = np.arange(1.0, 8.0, 0.01)\n        \n        # This will eventually be scaled by AKs when you\n        # call reddening(). Right now, calc for AKs=1\n        Alambda_scaled = RedLawRomanZuniga07._derive_romanzuniga07(wave)\n\n        # Convert wavelength to angstrom\n        wave *= 10**4\n\n        pysynphot.reddening.CustomRedLaw.__init__(self, wave=wave, \n                                                  waveunits='angstrom',\n                                                  Avscaled=Alambda_scaled,\n                                                  name='RomanZuniga07',\n                                                  litref='Roman-Zuniga+ 2007')\n\n        # Set the upper/lower wavelength limits of law (in angstroms)\n        self.low_lim = min(wave)\n        self.high_lim = max(wave)\n        self.name = 'RZ07'\n\n    @staticmethod\n    def _derive_romanzuniga07(wavelength):\n        filters = ['J', 'H', 'Ks', '[3.6]', '[4.5]', '[5.8]', '[8.0]']\n        wave =      np.array([1.240, 1.664, 2.164, 3.545, 4.442, 5.675, 7.760])\n        A_AKs =     np.array([2.299, 1.550, 1.000, 0.618, 0.525, 0.462, 0.455])\n        A_AKs_err = np.array([0.530, 0.080, 0.000, 0.077, 0.063, 0.055, 0.059])\n        \n        # Interpolate over the curve\n        spline_interp = interpolate.splrep(wave, A_AKs, k=3, s=0)\n        A_AKs_at_wave = interpolate.splev(wavelength, spline_interp)\n\n        return A_AKs_at_wave\n\n    def RomanZuniga07(self, wavelength, AKs):\n        \"\"\" \n        Return the extinction at a given wavelength assuming the \n        extinction law and an overall `AKs` value.\n\n        Parameters\n        ----------\n        wavelength : float or array\n            Wavelength to return extinction for, in microns\n        AKs : float\n            Total extinction in AKs, in mags\n        \"\"\"\n        # If input entry is a single float, turn it into an array\n        try:\n            len(wavelength)\n        except:\n            wavelength = [wavelength]\n\n        # Return error if any wavelength is beyond interpolation range of\n        # extinction law\n        if ((min(wavelength) < (self.low_lim*10**-4)) | (max(wavelength) > (self.high_lim*10**-4))):\n            return ValueError('{0}: wavelength values beyond interpolation range'.format(self))\n            \n        # Extract wave and A/AKs from law, turning wave into micron units\n        wave = self.wave * (10**-4)\n        law = self.obscuration\n\n        # Find the value of the law at the closest points\n        # to wavelength\n        A_AKs_at_wave = []\n        for ii in wavelength:\n            idx = np.where( abs(wave - ii) == min(abs(wave - ii)) )\n            A_AKs_at_wave.append(law[idx][0])\n\n        # Now multiply by AKs (since law assumes AKs = 1)\n        A_at_wave = np.array(A_AKs_at_wave) * AKs\n\n        return A_at_wave\n    \nclass RedLawRiekeLebofsky(pysynphot.reddening.CustomRedLaw):\n    \"\"\"\n    Defines the extinction law from `Rieke & Lebofsky 1985\n    <https://ui.adsabs.harvard.edu/abs/1985ApJ...288..618R/abstract>`_\n    for the Galactic Center. The law is defined between 1.0 - 13 microns.\n    \"\"\"\n    def __init__(self):\n        # Fetch the extinction curve, pre-interpolate across 0.365-13 microns\n        wave = np.arange(0.365, 13.0, 0.001)\n        \n        # This will eventually be scaled by AKs when you\n        # call reddening(). Right now, calc for AKs=1\n        Alambda_scaled = RedLawRiekeLebofsky._derive_RiekeLebofsky(wave)\n\n        # Convert wavelength to angstrom\n        wave *= 10 ** 4\n\n        pysynphot.reddening.CustomRedLaw.__init__(self, wave=wave, \n                                                  waveunits='angstrom',\n                                                  Avscaled=Alambda_scaled,\n                                                  name='RiekeLebofsky',\n                                                  litref='Rieke+Lebovsky 1985')\n\n        # Set the upper/lower wavelength limits of law (in angstroms)\n        self.low_lim = min(wave)\n        self.high_lim = max(wave)\n        self.name = 'RL85'\n\n    @staticmethod\n    def _derive_RiekeLebofsky(wavelength):\n        \"\"\"\n        Calculate the resulting extinction for an array of wavelengths.\n        The extinction is normalized with A_Ks.\n\n        Data pulled from Rieke+Lebofsky 1985, Table 3\n        \"\"\"\n        filters = ['U', 'B', 'V', 'R', 'I', 'J', 'H', 'K', 'L', 'M', \n                   '[8.0]', '[8.5]', '[9.0]', '[9.5]', '[10.0]', '[10.5]', \n                   '[11.0]', '[11.5]', '[12.0]', '[12.5]', '[13.0]']\n        #wave = np.array([0.365, 0.445, 0.551, 0.658, 0.806, 1.25, 1.635, 2.2, \n        #                 3.77, 4.68, 4.75, 8.0, 8.5, 9.0, 9.5, 10.0, 10.5, 11.0,\n        #                11.5, 12.0, 12.5, 13.0])\n        \n        # Wavelengths from Nishiyama+09 plot of RL+85 law...slightly different than standard, \n        # drop N filter\n        wave = np.array([0.365, 0.445, 0.551, 0.658, 0.806, 1.17, 1.57, 2.12, \n                         3.40, 4.75, 8.0, 8.5, 9.0, 9.5, 10.0, 10.5, 11.0,\n                        11.5, 12.0, 12.5, 13.0])\n        A_Av = np.array([1.531, 1.324, 1.00, 0.748, 0.482, 0.282, 0.175, 0.112,\n                         0.058, 0.023, 0.02, 0.043, 0.074, 0.087, 0.083,\n                         0.074, 0.060, 0.047, 0.037, 0.030, 0.027])\n        # Want to change this from A/Av to A/AK\n        k_ind = np.where(np.array(filters) == 'K')\n        Ak_Av = A_Av[k_ind]\n        Av_Ak = 1.0 / Ak_Av\n\n        A_Ak = A_Av * Av_Ak\n        \n        # Interpolate over the curve\n        spline_interp = interpolate.splrep(wave, A_Ak, k=3, s=0)\n        A_Ak_at_wave = interpolate.splev(wavelength, spline_interp)\n\n        return A_Ak_at_wave\n\n    def RiekeLebofsky85(self, wavelength, AKs):\n        \"\"\" \n        Return the extinction at a given wavelength assuming the \n        extinction law and an overall `AKs` value.\n\n        Parameters\n        ----------\n        wavelength : float or array\n            Wavelength to return extinction for, in microns\n        AKs : float\n            Total extinction in AKs, in mags\n        \"\"\"\n        # If input entry is a single float, turn it into an array\n        try:\n            len(wavelength)\n        except:\n            wavelength = [wavelength]\n\n        # Return error if any wavelength is beyond interpolation range of\n        # extinction law\n        if ((min(wavelength) < (self.low_lim*10**-4)) | (max(wavelength) > (self.high_lim*10**-4))):\n            return ValueError('{0}: wavelength values beyond interpolation range'.format(self))\n            \n        # Extract wave and A/AKs from law, turning wave into micron units\n        wave = self.wave * (10**-4)\n        law = self.obscuration\n\n        # Find the value of the law at the closest points\n        # to wavelength\n        A_AKs_at_wave = []\n        for ii in wavelength:\n            idx = np.where( abs(wave - ii) == min(abs(wave - ii)) )\n            A_AKs_at_wave.append(law[idx][0])\n\n        # Now multiply by AKs (since law assumes AKs = 1)\n        A_at_wave = np.array(A_AKs_at_wave) * AKs\n\n        return A_at_wave\n\nclass RedLawDamineli16(pysynphot.reddening.CustomRedLaw):\n    \"\"\"\n    Defines the extinction law of `Damineli et al. 2016\n    <https://ui.adsabs.harvard.edu/abs/2016MNRAS.463.2653D/abstract>`_,\n    derived for the Wd1 cluster. The law is derived between\n    0.5 - 8.0 microns.\n    \"\"\"\n    def __init__(self):\n        # Fetch the extinction curve, pre-interpolate across 1-8 microns\n        wave = np.arange(0.3, 8.0, 0.001)\n        \n        # This will eventually be scaled by AKs when you\n        # call reddening(). Right now, calc for AKs=1\n        Alambda_scaled = RedLawDamineli16._derive_Damineli16(wave)\n        #Alambda_scaled = RedLawDamineli16.derive_Damineli16_old(wave, 1.0)\n\n        # Convert wavelength to angstrom\n        wave *= 10 ** 4\n\n        pysynphot.reddening.CustomRedLaw.__init__(self, wave=wave, \n                                                  waveunits='angstrom',\n                                                  Avscaled=Alambda_scaled,\n                                                  name='Damineli16',\n                                                  litref='Damineli+ 2016')\n\n        # Set the upper/lower wavelength limits of law (in angstroms)\n        self.low_lim = min(wave)\n        self.high_lim = max(wave)\n        self.name = 'D16'\n    \n\n    @staticmethod\n    def _derive_Damineli16(wavelength):\n        \"\"\"\n        Calculate the Damineli+16 extinction law using their equation 19\n\n        Parameters\n        ----------\n        wavelength : float\n            in microns\n        AKs : float\n            in magnitudes\n        \"\"\"\n        # From their eq 19\n        x = np.log10(2.159 / wavelength)\n        log_A_AKs = -0.015 + 2.33*x + 0.522*x**2. - 3.001*x**3. + 2.034*x**4.\n\n        # Now to convert this back to linear space\n        A_AKs_at_wave = 10**log_A_AKs \n\n        return A_AKs_at_wave\n\n    def Damineli16(self, wavelength, AKs):\n        \"\"\" \n        Return the extinction at a given wavelength assuming the \n        extinction law and an overall `AKs` value.\n\n        Parameters\n        ----------\n        wavelength : float or array\n            Wavelength to return extinction for, in microns\n        AKs : float\n            Total extinction in AKs, in mags\n        \"\"\"\n        # If input entry is a single float, turn it into an array\n        try:\n            len(wavelength)\n        except:\n            wavelength = [wavelength]\n\n        # Return error if any wavelength is beyond interpolation range of\n        # extinction law\n        if ((min(wavelength) < (self.low_lim*10**-4)) | (max(wavelength) > (self.high_lim*10**-4))):\n            return ValueError('{0}: wavelength values beyond interpolation range'.format(self))\n            \n        # Extract wave and A/AKs from law, turning wave into micron units\n        wave = self.wave * (10**-4)\n        law = self.obscuration\n\n        # Find the value of the law at the closest points\n        # to wavelength\n        A_AKs_at_wave = []\n        for ii in wavelength:\n            idx = np.where( abs(wave - ii) == min(abs(wave - ii)) )\n            A_AKs_at_wave.append(law[idx][0])\n\n        # Now multiply by AKs (since law assumes AKs = 1)\n        A_at_wave = np.array(A_AKs_at_wave) * AKs\n\n        return A_at_wave\n\nclass RedLawDeMarchi16(pysynphot.reddening.CustomRedLaw):\n    \"\"\"\n    Defines extinction law from `De Marchi et al. 2016\n    <https://ui.adsabs.harvard.edu/abs/2016MNRAS.455.4373D/abstract>`_\n    derived for 30 Dorodus. The law is defined between 0.3 - 8.0 microns.\n    \"\"\"\n    def __init__(self):\n        # Fetch the extinction curve, pre-interpolate across 1-8 microns\n        wave = np.arange(0.3, 8.0, 0.001)\n        \n        # This will eventually be scaled by AK when you\n        # call reddening(). Right now, calc for AKs=1\n        Alambda_scaled = RedLawDeMarchi16._derive_DeMarchi16(wave)\n\n        # Convert wavelength to angstrom\n        wave *= 10 ** 4\n\n        pysynphot.reddening.CustomRedLaw.__init__(self, wave=wave, \n                                                  waveunits='angstrom',\n                                                  Avscaled=Alambda_scaled,\n                                                  name='DeMarchi16',\n                                                  litref='DeMarchi+ 2016')\n\n        # Set the upper/lower wavelength limits of law (in angstroms)\n        self.low_lim = min(wave)\n        self.high_lim = max(wave)\n        self.name = 'DM16'\n\n    @staticmethod\n    def _derive_DeMarchi16(wavelength):\n        \"\"\"\n        Calculate the resulting extinction for an array of wavelengths.\n        The extinction is normalized with A_Ks.\n\n        Data pulled from DeMarchi+16, Table 3\n\n        Note: Authors measure R_VI (V) = 3.09 +/- 0.15,\n        so we use this to calculate the absolute extinctions in all\n        of the other bands. This corresponds to A_I/ A_V = 0.676\n\n        Note that they extrapolate their curve to get to K-band\n\n        Parameters\n        ----------\n        wavelength : float\n            in microns\n        AKs : float\n            in magnitudes\n        \"\"\"\n        AI_AV = 0.676\n\n        # Extracting the values from the paper\n        filters = ['U', 'B', 'V', 'R', 'I', 'J', 'H', 'K']\n        wave = np.array([0.365, 0.445, 0.551, 0.658, 0.806, 1.22, 1.63, 2.19])\n        R_VI = np.array([4.41, 3.78, 3.09, 2.58, 2.09, 1.26, 0.84, 0.52])\n        R_VI_err = np.array([0.18, 0.15, 0.15, 0.13, 0.17, 0.18, 0.12, 0.08])\n\n        # We'll calculate A_AKs from R_VI\n        A_Av = R_VI * (1. - AI_AV)\n        AK_Av = A_Av[-1]\n        A_AK = A_Av / AK_Av\n\n        # Interpolate over the curve\n        spline_interp = interpolate.splrep(wave, A_AK, k=3, s=0)\n        A_AK_at_wave = interpolate.splev(wavelength, spline_interp)\n\n        return A_AK_at_wave\n\n    def DeMarchi16(self, wavelength, AK):\n        \"\"\" \n        Return the extinction at a given wavelength assuming the \n        extinction law and an overall `AKs` value.\n\n        Parameters\n        ----------\n        wavelength : float or array\n            Wavelength to return extinction for, in microns\n        AKs : float\n            Total extinction in AKs, in mags\n        \"\"\"\n        # If input entry is a single float, turn it into an array\n        try:\n            len(wavelength)\n        except:\n            wavelength = [wavelength]\n\n        # Return error if any wavelength is beyond interpolation range of\n        # extinction law\n        if ((min(wavelength) < (self.low_lim*10**-4)) | (max(wavelength) > (self.high_lim*10**-4))):\n            return ValueError('{0}: wavelength values beyond interpolation range'.format(self))\n            \n        # Extract wave and A/AKs from law, turning wave into micron units\n        wave = self.wave * (10**-4)\n        law = self.obscuration\n\n        # Find the value of the law at the closest points\n        # to wavelength\n        A_AKs_at_wave = []\n        for ii in wavelength:\n            idx = np.where( abs(wave - ii) == min(abs(wave - ii)) )\n            A_AKs_at_wave.append(law[idx][0])\n\n        # Now multiply by AK (since law assumes AK = 1)\n        A_at_wave = np.array(A_AKs_at_wave) * AK\n\n        return A_at_wave\n    \nclass RedLawFitzpatrick09(pysynphot.reddening.CustomRedLaw):\n    \"\"\"\n    Defines the extinction law from \n    `Fitzpatrick et al. 2009 <https://ui.adsabs.harvard.edu/abs/2009ApJ...699.1209F/abstract>`_.\n    The law is defined between 0.3 -- 3 microns.\n\n    The extinction law is as defined in their equation 5, and has two\n    free parameters: :math:`\\alpha` and R(V). Averaged over 14 sight-lines,\n    the authors generally find either :math:`alpha` ~ 2.5, R(V) ~ 3, or \n    :math:`alpha` ~ 1.8, R(V) ~ 5 (their Figure 6). \n\n    Parameters\n    ----------\n    alpha : float\n         alpha parameter for extinction law. \n\n    RV : float\n        R(V) parameter for extinction law. \n    \"\"\"\n    def __init__(self, alpha, RV):\n        # Fetch the extinction curve, pre-interpolate across 1-8 microns\n        wave = np.arange(0.7, 3.0, 0.001)\n        \n        # This will eventually be scaled by AK when you\n        # call reddening(). Right now, calc for AKs=1\n        Alambda_scaled = RedLawFitzpatrick09._derive_Fitzpatrick09(wave, alpha, RV)\n\n        # Convert wavelength to angstrom\n        wave *= 10 ** 4\n\n        pysynphot.reddening.CustomRedLaw.__init__(self, wave=wave, \n                                                  waveunits='angstrom',\n                                                  Avscaled=Alambda_scaled,\n                                                  name='Fitzpatrick09',\n                                                  litref='Fitzpatrick+ 2009')\n\n        # Set the upper/lower wavelength limits of law (in angstroms)\n        self.low_lim = min(wave)\n        self.high_lim = max(wave)\n        self.name = 'F09,{0},{1}'.format(alpha, RV)\n\n    @staticmethod\n    def _derive_Fitzpatrick09(wavelength, alpha, RV):\n        \"\"\"\n        Calculate the resulting extinction for an array of wavelengths.\n        The extinction is normalized with A_Ks.\n\n        Data pulled from Fitzpactrick09, equation 5\n\n        Parameters\n        ----------\n        wavelength : float\n            in microns\n\n        alpha: float\n            Free parameter alpha\n\n        RV: float\n            Free parameter RV\n        \"\"\"\n        alpha = float(alpha)\n        RV = float(RV)\n        \n        # First we'll calculate k(lambda - V) = E(lambda - V) / E(B - V),\n        # directly from equation 5\n        k = (0.349 + 2.087*RV) * (1.0 / (1.0 + (wavelength / 0.507)**alpha)) - RV\n\n        # We'll calculate Alam/Av from K + Rv\n        Alam_Av = (k / RV) + 1. \n        \n        # Finally, to get A_lambda/Aks we need to divide Alam_Av by AKs_Av.\n        # We'll assume central wavelength of 2.14 for Ks\n        idx = np.where(abs(wavelength - 2.14) == min(abs(wavelength - 2.14)))\n\n        A_AKs_at_wave = Alam_Av / Alam_Av[idx]\n\n        return A_AKs_at_wave\n\n    def Fitzpatrick09(self, wavelength, AKs):\n        \"\"\" \n        Return the extinction at a given wavelength assuming the \n        extinction law and an overall `AKs` value.\n\n        Parameters\n        ----------\n        wavelength : float or array\n            Wavelength to return extinction for, in microns\n        AKs : float\n            Total extinction in AKs, in mags\n        \"\"\"\n        # If input entry is a single float, turn it into an array\n        try:\n            len(wavelength)\n        except:\n            wavelength = [wavelength]\n\n        # Return error if any wavelength is beyond interpolation range of\n        # extinction law\n        if ((min(wavelength) < (self.low_lim*10**-4)) | (max(wavelength) > (self.high_lim*10**-4))):\n            return ValueError('{0}: wavelength values beyond interpolation range'.format(self))\n            \n        # Extract wave and A/AKs from law, turning wave into micron units\n        wave = self.wave * (10**-4)\n        law = self.obscuration\n\n        # Find the value of the law at the closest points\n        # to wavelength\n        A_AKs_at_wave = []\n        for ii in wavelength:\n            idx = np.where( abs(wave - ii) == min(abs(wave - ii)) )\n            A_AKs_at_wave.append(law[idx][0])\n\n        # Now multiply by AKs (since law assumes AKs = 1)\n        A_at_wave = np.array(A_AKs_at_wave) * AKs\n\n        return A_at_wave\n\nclass RedLawSchlafly16(pysynphot.reddening.CustomRedLaw):\n    \"\"\"\n    Defines the extinction law from `Schlafly et al. 2016 \n    <https://ui.adsabs.harvard.edu/abs/2016ApJ...821...78S/abstract>`_.\n    The law is defined between 0.5 - 8 microns.\n\n    Parameters\n    ----------\n    AH_AKs : float\n        Ratio of A_H / A_Ks, which sets the normalization of the law (see Schlafly+16)\n    x : float\n        Free parameter in extinction law (see Schlafly+16, Eqn 6)\n    \"\"\"\n    def __init__(self, AH_AKs, x):\n        # Fetch the extinction curve, pre-interpolate across 1-8 microns\n        wave = np.arange(0.5, 4.8, 0.001)\n        \n        # This will eventually be scaled by AK when you\n        # call reddening(). Right now, calc for AKs=1\n        Alambda_scaled = RedLawSchlafly16._derive_Schlafly16(wave, AH_AKs, x)\n\n        # Convert wavelength to angstrom\n        wave *= 10 ** 4\n\n        pysynphot.reddening.CustomRedLaw.__init__(self, wave=wave, \n                                                  waveunits='angstrom',\n                                                  Avscaled=Alambda_scaled,\n                                                  name='Schlafly16',\n                                                  litref='Schlafly+ 2016')\n\n        # Set the upper/lower wavelength limits of law (in angstroms)\n        self.low_lim = min(wave)\n        self.high_lim = max(wave)\n        self.name = 'S16,{0},{1}'.format(AH_AKs,x)\n\n    @staticmethod\n    def _derive_Schlafly16(wavelength, AH_AKs, x):\n        \"\"\"\n        Calculate Schalfly+16 extinction law according to \n        code provided in appendix of the paper. AH_AKs sets the\n        gray component while x sets the shape of the law in an\n        Rv-like way\n        \"\"\"\n        # Use the function from the Schlafly+16 appendix to get the extinciton law\n        # for given AH_AKs and x value. This is given in terms of A_lambda / A(5420)\n        law_func = RedLawSchlafly16._Schlafly_appendix(x, AH_AKs)\n\n        # Evaluate function for desired wavelengths (in angstroms)\n        law = law_func(wavelength*10**4)\n        \n        # Now normalize to A_lambda/AKs, rather than A_lambda/A(5420)\n        idx = np.where( abs(wavelength - 2.14) == min(abs(wavelength - 2.14)) )\n        law_out = law / law[idx]\n        \n        return law_out\n\n    @staticmethod\n    def _Schlafly_appendix(x, rhk):\n        \"\"\" \n        Schlafly+16 extinction law as defined in paper appendix. We've modified\n        the wrapper slightly so that the user has control of rhk and x. Here is \n        the comments from that code:\n         \n        Returns the extinction curve, A(lambda)/A(5420 A), according to\n        Schlafly+2016, for the parameter \"x,\" which controls the overall shape of\n        the extinction curve in an R(V)-like way.  The extinction curve returned\n        is a callable function, which is then invoked with the wavelength, in\n        angstroms, of interest.\n\n        The extinction curve is based on broad band photometry between the PS1 g\n        band and the WISE W2 band, which have effective wavelengths between 5000\n        and 45000 A.  The extinction curve is blindly extrapolated outside that\n        range.  The gray component of the extinction curve is fixed by enforcing\n        A(H)/A(K) = 1.55 (Indebetouw+2005).  The gray component is relatively\n        uncertain, and its variation with x is largely made up.\n\n        Args:\n            x: some number controlling the shape of the extinction curve\n            ra: extinction vector at anchor wavelengths, default to Schlafly+2016\n            dra: derivative of extinction vector at anchor wavelengths, default to\n             Schlafly+2016\n            lam: anchor wavelengths (angstroms), default to Schlafly+2016\n\n        Returns: the extinction curve E, so the extinction alam = A(lam)/A(5420 A)\n        is given by: \n            A = extcurve(x)\n            alam = A(lam)\n        \"\"\"\n        # Schlafly+2016\n        ra = np.array([ 0.65373283,  0.39063843,  0.20197893,  0.07871701, -0.00476316,\n                   -0.14213929, -0.23660605, -0.28522577, -0.321301  , -0.33503192])\n        dra = np.array([-0.54278669,  0.03404903,  0.36841725,  0.42265873,  0.38247769,\n                     0.14148814, -0.04020524, -0.13457319, -0.26883343, -0.36269229])\n\n        # \"isoreddening wavelengths\" for extinction curve, at E(g-r) = 0.65 reddening\n        # T_eff = 4500, Fe/H = 0, log g = 2.5\n        lam = np.array([  5032.36441067,   6280.53335141,   7571.85928312,   8690.89321059,\n                      9635.52560909,  12377.04268274,  16381.78146718,  21510.20523237,\n                     32949.54009328,  44809.4919175 ])\n\n\n        anchors = ra + x*dra\n        # fix gray component so that A(H)/A(K) = 1.55\n        anchors += (-anchors[6] + rhk*anchors[7])/(1 - rhk)\n        cs0 = CubicSpline(lam, anchors, yp='3d=0')\n        # normalize at 5420 angstroms\n        return CubicSpline(lam, anchors/cs0(5420.), yp='3d=0')\n\n    def Schlafly16(self, wavelength, AKs):\n        \"\"\" \n        Return the extinction at a given wavelength assuming the \n        extinction law and an overall `AKs` value.\n\n        Parameters\n        ----------\n        wavelength : float or array\n            Wavelength to return extinction for, in microns\n        AKs : float\n            Total extinction in AKs, in mags\n        \"\"\"\n        # If input entry is a single float, turn it into an array\n        try:\n            len(wavelength)\n        except:\n            wavelength = [wavelength]\n\n        # Return error if any wavelength is beyond interpolation range of\n        # extinction law\n        if ((min(wavelength) < (self.low_lim*10**-4)) | (max(wavelength) > (self.high_lim*10**-4))):\n            return ValueError('{0}: wavelength values beyond interpolation range'.format(self))\n            \n        # Extract wave and A/AKs from law, turning wave into micron units\n        wave = self.wave * (10**-4)\n        law = self.obscuration\n\n        # Find the value of the law at the closest points\n        # to wavelength\n        A_AKs_at_wave = []\n        for ii in wavelength:\n            idx = np.where( abs(wave - ii) == min(abs(wave - ii)) )\n            A_AKs_at_wave.append(law[idx][0])\n\n        # Now multiply by AKs (since law assumes AKs = 1)\n        A_at_wave = np.array(A_AKs_at_wave) * AKs\n\n        return A_at_wave\n        \nclass RedLawPowerLaw(pysynphot.reddening.CustomRedLaw):\n    \"\"\"\n    Extinction object that is a power-law extinction law: \n    :math:`A_{\\lambda} \\propto \\lambda^{\\alpha}`.\n\n    For example, to create an extinction law between \n    0.8 and 3 microns where :math:`\\alpha = 2.21`, \n    where :math:`A_{\\lambda} / A_{Ks} = 1` at 2.12 microns:\n\n    >>> red_law = reddening.RedLawPowerLaw(2.21, 2.12, wave_min=0.8, wave_max=3.0)\n\n    Parameters\n    ----------\n    alpha : float\n        Exponent of the extinction power-law.\n\n    K_wave : float\n        Extinction law is normalized such that AKs = 1 at `K_wave`.\n\n    wave_min : float; optional\n        Minimum wavelength of the extinction law, in microns.\n        Default is 0.5 microns.\n\n    wave_max : float; optional\n        Maximum wavelength of the extinction law, in microns.\n        Default is 5.0 microns\n    \"\"\"\n    def __init__(self, alpha, K_wave, wave_min=0.5, wave_max=5.0):\n        # Fetch the extinction curve, pre-interpolate across wave_min to wave_max\n        wave = np.arange(wave_min, wave_max, 0.001)\n        \n        # This will eventually be scaled by AK when you\n        # call reddening(). Right now, calc for AKs=1\n        Alambda_scaled = RedLawPowerLaw._derive_powerlaw(wave, alpha, K_wave)\n\n        # Convert wavelength to angstrom\n        wave *= 10 ** 4\n\n        pysynphot.reddening.CustomRedLaw.__init__(self, wave=wave, \n                                                  waveunits='angstrom',\n                                                  Avscaled=Alambda_scaled,\n                                                  name='Power law')\n\n        # Set the upper/lower wavelength limits of law (in angstroms)\n        self.low_lim = min(wave)\n        self.high_lim = max(wave)\n        self.name = 'pl,{0},{1},{2},{3}'.format(alpha,K_wave,wave_min,wave_max)\n\n    @staticmethod\n    def _derive_powerlaw(wavelength, alpha, K_wave):\n        \"\"\"\n        Calculate the resulting extinction for an array of wavelengths.\n        The extinction is normalized with A_Ks.\n\n        Parameters\n        ----------\n        wavelength : float\n            in microns\n\n        alpha: float\n            -1.0 * (power law exponent) \n             \n        K_wave: float\n            Desired K-band wavelength, in microns\n        \"\"\"\n        # Create extinction law\n        law = wavelength**(-1.0 * alpha)\n\n        # We'll identify K-band as 2.14 microns\n        idx = np.where(abs(wavelength - K_wave) == min(abs(wavelength - K_wave)))\n        A_AKs_at_wave = law / law[idx]\n\n        return A_AKs_at_wave\n\n    def powerlaw(self, wavelength, AKs):\n        \"\"\" \n        Return the extinction at a given wavelength assuming the \n        extinction law and an overall `AKs` value.\n\n        Parameters\n        ----------\n        wavelength : float or array\n            Wavelength to return extinction for, in microns\n        AKs : float\n            Total extinction in AKs, in mags\n        \"\"\"\n        # If input entry is a single float, turn it into an array\n        try:\n            len(wavelength)\n        except:\n            wavelength = [wavelength]\n\n        # Return error if any wavelength is beyond interpolation range of\n        # extinction law\n        if ((min(wavelength) < (self.low_lim*10**-4)) | (max(wavelength) > (self.high_lim*10**-4))):\n            return ValueError('{0}: wavelength values beyond interpolation range'.format(self))\n            \n        # Extract wave and A/AKs from law, turning wave into micron units\n        wave = self.wave * (10**-4)\n        law = self.obscuration\n\n        # Find the value of the law at the closest points\n        # to wavelength\n        A_AKs_at_wave = []\n        for ii in wavelength:\n            idx = np.where( abs(wave - ii) == min(abs(wave - ii)) )\n            A_AKs_at_wave.append(law[idx][0])\n\n        # Now multiply by AKs (since law assumes AKs = 1)\n        A_at_wave = np.array(A_AKs_at_wave) * AKs\n\n        return A_at_wave\n\nclass RedLawFritz11(pysynphot.reddening.CustomRedLaw):\n    \"\"\"\n    Defines extinction law from `Fritz et al. 2011 \n    <https://ui.adsabs.harvard.edu/abs/2011ApJ...737...73F/abstract>`_\n    for the Galactic Center. The law is defined from 1.0 -- 19 microns.\n    \"\"\"\n    def __init__(self):\n        # Fetch the extinction curve, pre-interpolate across 3-8 microns\n        wave = np.arange(1.0, 19, 0.001)\n        \n        # This will eventually be scaled by AKs when you\n        # call reddening(). Right now, calc for AKs=1\n        Alambda_scaled = RedLawFritz11._derive_Fritz11(wave)\n\n        # Convert wavelength to angstrom\n        wave *= 10 ** 4\n\n        pysynphot.reddening.CustomRedLaw.__init__(self, wave=wave, \n                                                  waveunits='angstrom',\n                                                  Avscaled=Alambda_scaled,\n                                                  name='Fritz09',\n                                                  litref='Fritz+2011')\n        \n        # Set the upper/lower wavelength limits of law (in angstroms)\n        self.low_lim = min(wave)\n        self.high_lim = max(wave)\n        self.name = 'F11'\n        \n    @staticmethod\n    def _derive_Fritz11(wavelength):\n        \"\"\"\n        Calculate the resulting extinction for an array of wavelengths.\n        The extinction is normalized to A_Ks = 1\n\n        Data pulled from Fritz+11, Table 2\n\n        Parameters\n        ----------\n        wavelength : float\n            Wavelength range to derive extinction law over, in microns\n        \"\"\"\n        # Extinction law definition\n        wave = np.array([1.282, 1.736, 2.166, 2.625, 2.758, 2.873, 3.039, 3.297, 3.74, 3.819, 3.907, 4.052,\n                             4.376, 5.128, 5.908, 6.772, 7.459, 7.502, 8.76, 12.371, 19.062])\n        A_AKs = np.array([7.91, 4.30, 2.49, 1.83, 1.51, 1.84, 2.07, 1.66, 1.19, 1.19, 1.09, 1.01, 1.09, 0.99,\n                              1.04, 0.84, 0.81, 0.79, 2.04, 1.34, 1.34])\n\n\n        # Interpolate over the curve\n        spline_interp = interpolate.splrep(wave, A_AKs, k=3, s=0)\n        A_at_wave = interpolate.splev(wavelength, spline_interp)\n\n        # We'll call 2.14 microns the K-band\n        idx = np.where( abs(wavelength - 2.14) == min(abs(wavelength - 2.14)) )\n        A_AKs_at_wave = A_at_wave / A_at_wave[idx] \n\n        return A_AKs_at_wave\n\n    def Fritz11(self, wavelength, AKs):\n        \"\"\" \n        Return the extinction at a given wavelength assuming the \n        extinction law and an overall `AKs` value.\n\n        Parameters\n        ----------\n        wavelength : float or array\n            Wavelength to return extinction for, in microns\n        AKs : float\n            Total extinction in AKs, in mags\n        \"\"\"\n        # If input entry is a single float, turn it into an array\n        try:\n            len(wavelength)\n        except:\n            wavelength = [wavelength]\n\n        # Return error if any wavelength is beyond interpolation range of\n        # extinction law\n        if ((min(wavelength) < (self.low_lim*10**-4)) | (max(wavelength) > (self.high_lim*10**-4))):\n            return ValueError('{0}: wavelength values beyond interpolation range'.format(self))\n            \n        # Extract wave and A/AKs from law, turning wave into micron units\n        wave = self.wave * (10**-4)\n        law = self.obscuration\n\n        # Find the value of the law at the closest points\n        # to wavelength\n        A_AKs_at_wave = []\n        for ii in wavelength:\n            idx = np.where( abs(wave - ii) == min(abs(wave - ii)) )\n            A_AKs_at_wave.append(law[idx][0])\n\n        # Now multiply by AKs (since law assumes AKs = 1)\n        A_at_wave = np.array(A_AKs_at_wave) * AKs\n\n        return A_at_wave\n        \nclass RedLawHosek18(pysynphot.reddening.CustomRedLaw):\n    \"\"\"\n    Defines extinction law from `Hosek et al. 2018 \n    <https://ui.adsabs.harvard.edu/abs/2018ApJ...855...13H/abstract>`_\n    for the Arches Cluster and Wd1. The law is defined between \n    0.7 - 3.54 microns.\n\n    WARNING: DEPRECATED! This law has revised to RedLawHosek18b, which \n    should be used instead\n    \"\"\"\n    def __init__(self):\n        # Fetch the extinction curve, pre-interpolate across 3-8 microns\n        wave = np.arange(0.7, 3.545, 0.001)\n        \n        # This will eventually be scaled by AKs when you\n        # call reddening(). Right now, calc for AKs=1\n        Alambda_scaled = RedLawHosek18._derive_Hosek18(wave)\n\n        # Convert wavelength to angstrom\n        wave *= 10 ** 4\n\n        pysynphot.reddening.CustomRedLaw.__init__(self, wave=wave, \n                                                  waveunits='angstrom',\n                                                  Avscaled=Alambda_scaled,\n                                                  name='Hosek+18',\n                                                  litref='Hosek+ 2018')\n\n        # Set the upper/lower wavelength limits of law (in angstroms)\n        self.low_lim = min(wave)\n        self.high_lim = max(wave)\n        self.name = 'H18'\n        \n    @staticmethod\n    def _derive_Hosek18(wavelength):\n        \"\"\" \n        Derive the Hosek+18 extinction law, using the data from Table 4. \n        \n        Calculate the resulting extinction for an array of wavelengths.\n        The extinction is normalized with A_Ks.\n\n        Data pulled from Hosek+18, Table 4\n\n        Parameters\n        ----------\n        wavelength : float\n            Wavelength range to define extinction law over, in microns\n        \"\"\"\n        # Extinction law definition\n        wave = np.array([0.8059, 0.962, 1.25, 1.53, 2.14, 3.545])\n        A_AKs = np.array([9.66, 6.29, 3.56, 2.33, 1.0, 0.50])\n        \n\n        # Following Hosek+18, Interpolate over the curve with cubic spline interpolation\n        spline_interp = interpolate.splrep(wave, A_AKs, k=3, s=0)\n        A_AKs_at_wave = interpolate.splev(wavelength, spline_interp)\n\n        # This curve already assumes A_Ks = 1.0, so we can go straight to\n        # output        \n        return A_AKs_at_wave\n\n    def Hosek18(self, wavelength, AKs):\n        \"\"\" \n        Return the extinction at a given wavelength assuming the \n        extinction law and an overall `AKs` value.\n\n        Parameters\n        ----------\n        wavelength : float or array\n            Wavelength to return extinction for, in microns\n        AKs : float\n            Total extinction in AKs, in mags\n        \"\"\"\n        # If input entry is a single float, turn it into an array\n        try:\n            len(wavelength)\n        except:\n            wavelength = [wavelength]\n\n        # Return error if any wavelength is beyond interpolation range of\n        # extinction law\n        if ((min(wavelength) < (self.low_lim*10**-4)) | (max(wavelength) > (self.high_lim*10**-4))):\n            return ValueError('{0}: wavelength values beyond interpolation range'.format(self))\n            \n        # Extract wave and A/AKs from law, turning wave into micron units\n        wave = self.wave * (10**-4)\n        law = self.obscuration\n\n        # Find the value of the law at the closest points\n        # to wavelength\n        A_AKs_at_wave = []\n        for ii in wavelength:\n            idx = np.where( abs(wave - ii) == min(abs(wave - ii)) )\n            A_AKs_at_wave.append(law[idx][0])\n\n        # Now multiply by AKs (since law assumes AKs = 1)\n        A_at_wave = np.array(A_AKs_at_wave) * AKs\n\n        return A_at_wave\n\nclass RedLawHosek18b(pysynphot.reddening.CustomRedLaw):\n    \"\"\"\n    Defines extinction law from `Hosek et al. 2019 \n    <https://ui.adsabs.harvard.edu/abs/2019ApJ...870...44H/abstract>`_\n    for the Arches cluster and Wd1. This should be used over RedLawHosek18b.\n    The law is derived between 0.7 - 3.54 microns\n    \"\"\"\n    def __init__(self):\n        # Fetch the extinction curve, pre-interpolate across 3-8 microns\n        wave = np.arange(0.7, 3.545, 0.001)\n        \n        # This will eventually be scaled by AKs when you\n        # call reddening(). Right now, calc for AKs=1\n        Alambda_scaled = RedLawHosek18b._derive_Hosek18b(wave)\n\n        # Convert wavelength to angstrom\n        wave *= 10 ** 4\n\n        pysynphot.reddening.CustomRedLaw.__init__(self, wave=wave, \n                                                  waveunits='angstrom',\n                                                  Avscaled=Alambda_scaled,\n                                                  name='Hosek+18b',\n                                                  litref='Hosek+ 2018b')\n\n        # Set the upper/lower wavelength limits of law (in angstroms)\n        self.low_lim = min(wave)\n        self.high_lim = max(wave)\n        self.name = 'H18b'\n        \n    @staticmethod\n    def _derive_Hosek18b(wavelength):\n        \"\"\" \n        Derive the Hosek+18 extinction law, using the data from Table 4. \n        \n        Calculate the resulting extinction for an array of wavelengths.\n        The extinction is normalized with A_Ks.\n\n        Data pulled from Hosek+18, Table 4\n\n        Parameters\n        ----------\n        wavelength : float\n            Wavelength range to define extinction law over, in microns\n        \"\"\"\n        # Extinction law definition\n        wave = np.array([0.8059, 0.962, 1.25, 1.53, 2.14, 3.545])\n        A_AKs = np.array([7.943, 5.715, 3.142, 2.04, 1.0, 0.50])\n        \n        # Following Hosek+18, Interpolate over the curve with cubic spline interpolation\n        spline_interp = interpolate.splrep(wave, A_AKs, k=3, s=0)\n        A_AKs_at_wave = interpolate.splev(wavelength, spline_interp)\n\n        # This curve already assumes A_Ks = 1.0, so we can go straight to\n        # output        \n        return A_AKs_at_wave\n\n    def Hosek18b(self, wavelength, AKs):\n        \"\"\" \n        Return the extinction at a given wavelength assuming the \n        extinction law and an overall `AKs` value.\n\n        Parameters\n        ----------\n        wavelength : float or array\n            Wavelength to return extinction for, in microns\n        AKs : float\n            Total extinction in AKs, in mags\n        \"\"\"\n        # If input entry is a single float, turn it into an array\n        try:\n            len(wavelength)\n        except:\n            wavelength = [wavelength]\n\n        # Return error if any wavelength is beyond interpolation range of\n        # extinction law\n        if ((min(wavelength) < (self.low_lim*10**-4)) | (max(wavelength) > (self.high_lim*10**-4))):\n            return ValueError('{0}: wavelength values beyond interpolation range'.format(self))\n            \n        # Extract wave and A/AKs from law, turning wave into micron units\n        wave = self.wave * (10**-4)\n        law = self.obscuration\n\n        # Find the value of the law at the closest points\n        # to wavelength\n        A_AKs_at_wave = []\n        for ii in wavelength:\n            idx = np.where( abs(wave - ii) == min(abs(wave - ii)) )\n            A_AKs_at_wave.append(law[idx][0])\n\n        # Now multiply by AKs (since law assumes AKs = 1)\n        A_at_wave = np.array(A_AKs_at_wave) * AKs\n\n        return A_at_wave\n\nclass RedLawNoguerasLara18(RedLawPowerLaw):\n    \"\"\"\n    Defines extinction law from `Nogueras-Lara et al. 2018 \n    <https://ui.adsabs.harvard.edu/abs/2018A%26A...610A..83N/abstract>`_\n    for the Galactic Center. It is defined between 0.8 - 2.5 microns.\n    \"\"\"\n    def __init__(self):\n        wave_min = 0.8\n        wave_max = 2.8\n        RedLawPowerLaw.__init__(self, 2.30, 2.15, wave_min=wave_min, wave_max=wave_max)\n        \n        # Set the upper/lower wavelength limits of law (in angstroms)\n        self.low_lim = wave_min*10**4\n        self.high_lim = wave_max*10**4\n        self.name = 'NL18'\n\n    def NoguerasLara18(self, wavelength, AKs):\n        \"\"\" \n        Return the extinction at a given wavelength assuming the \n        extinction law and an overall `AKs` value.\n\n        Parameters\n        ----------\n        wavelength : float or array\n            Wavelength to return extinction for, in microns\n        AKs : float\n            Total extinction in AKs, in mags\n        \"\"\"\n        # If input entry is a single float, turn it into an array\n        try:\n            len(wavelength)\n        except:\n            wavelength = [wavelength]\n\n        # Return error if any wavelength is beyond interpolation range of\n        # extinction law\n        if ((min(wavelength) < (self.low_lim*10**-4)) | (max(wavelength) > (self.high_lim*10**-4))):\n            return ValueError('{0}: wavelength values beyond interpolation range'.format(self))    \n\n        # Extract wave and A/AKs from law, turning wave into micron units\n        wave = self.wave * (10**-4)\n        law = self.obscuration\n\n        # Find the value of the law at the closest points\n        # to wavelength\n        A_AKs_at_wave = []\n        for ii in wavelength:\n            idx = np.where( abs(wave - ii) == min(abs(wave - ii)) )\n            A_AKs_at_wave.append(law[idx][0])\n\n        # Now multiply by AKs (since law assumes AKs = 1)\n        A_at_wave = np.array(A_AKs_at_wave) * AKs\n\n        return A_at_wave    \n\n#---------------------------#\n# Cubic spline function from Schalfly+16 appendix\n#---------------------------#\ndef splint(spl, x):\n    npts = len(spl.x)\n    lo = np.searchsorted(spl.x, x)-1\n    lo = np.clip(lo, 0, npts-2)\n    hi = lo + 1\n    dx = spl.x[hi] - spl.x[lo]\n    a = (spl.x[hi] - x)/dx\n    b = (x-spl.x[lo])/dx\n    y = (a*spl.y[lo]+b*spl.y[hi]+\n         ((a**3-a)*spl.y2[lo]+(b**3-b)*spl.y2[hi])*dx**2./6.)\n    return y\n\nclass CubicSpline:\n    def __init__(self, x, y, yp=None):\n        npts = len(x)\n        mat = np.zeros((3, npts))\n        # enforce continuity of 1st derivatives\n        mat[1,1:-1] = (x[2:  ]-x[0:-2])/3.\n        mat[2,0:-2] = (x[1:-1]-x[0:-2])/6.\n        mat[0,2:  ] = (x[2:  ]-x[1:-1])/6.\n        bb = np.zeros(npts)\n        bb[1:-1] = ((y[2:  ]-y[1:-1])/(x[2:  ]-x[1:-1]) -\n                    (y[1:-1]-y[0:-2])/(x[1:-1]-x[0:-2]))\n        if yp is None: # natural cubic spline\n            mat[1,0] = 1.\n            mat[1,-1] = 1.\n            bb[0] = 0.\n            bb[-1] = 0.\n        elif yp == '3d=0':\n            mat[1, 0] = -1./(x[1]-x[0])\n            mat[0, 1] =  1./(x[1]-x[0])\n            mat[1,-1] =  1./(x[-2]-x[-1])\n            mat[2,-2] = -1./(x[-2]-x[-1])\n            bb[ 0] = 0.\n            bb[-1] = 0.\n        else:\n            mat[1, 0] = -1./3.*(x[1]-x[0])\n            mat[0, 1] = -1./6.*(x[1]-x[0])\n            mat[2,-2] =  1./6.*(x[-1]-x[-2])\n            mat[1,-1] =  1./3.*(x[-1]-x[-2])\n            bb[ 0] = yp[0]-1.*(y[ 1]-y[ 0])/(x[ 1]-x[ 0])\n            bb[-1] = yp[1]-1.*(y[-1]-y[-2])/(x[-1]-x[-2])\n        y2 = solve_banded((1,1), mat, bb)\n        self.x, self.y, self.y2 = (x, y, y2)\n    def __call__(self, x):\n        return splint(self, x)\n", "meta": {"hexsha": "b60022705171d8224e4467be3c13b81b475e8611", "size": 56401, "ext": "py", "lang": "Python", "max_stars_repo_path": "popstar/reddening.py", "max_stars_repo_name": "samrose30/PyPopStar", "max_stars_repo_head_hexsha": "de32db0662c61dbb1141d3acedb7cc2be06bb1dd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "popstar/reddening.py", "max_issues_repo_name": "samrose30/PyPopStar", "max_issues_repo_head_hexsha": "de32db0662c61dbb1141d3acedb7cc2be06bb1dd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "popstar/reddening.py", "max_forks_repo_name": "samrose30/PyPopStar", "max_forks_repo_head_hexsha": "de32db0662c61dbb1141d3acedb7cc2be06bb1dd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9038978495, "max_line_length": 124, "alphanum_fraction": 0.5577560682, "include": true, "reason": "import numpy,from scipy", "num_tokens": 15701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.16804795656983243}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#\n\n'''\nJ-metric density fitting\n'''\n\nimport time\nimport tempfile\nimport numpy\nimport h5py\nfrom pyscf import lib\nfrom pyscf import ao2mo\nfrom pyscf.lib import logger\nfrom pyscf.df import incore\nfrom pyscf.df import outcore\nfrom pyscf.df import r_incore\nfrom pyscf.df import addons\nfrom pyscf.df import df_jk\nfrom pyscf.ao2mo import _ao2mo\nfrom pyscf.ao2mo.incore import _conc_mos, iden_coeffs\nfrom pyscf import __config__\n\nclass DF(lib.StreamObject):\n    r'''\n    Object to hold 3-index tensor\n\n    Attributes:\n        auxbasis : str or dict\n            Same input format as :attr:`Mole.basis`\n\n        auxmol : Mole object\n            Read only Mole object to hold the auxiliary basis.  auxmol is\n            generated automatically in the initialization step based on the\n            given auxbasis.  It is used in the rest part of the code to\n            determine the problem size, the integral batches etc.  This object\n            should NOT be modified.\n        _cderi_to_save : str\n            If _cderi_to_save is specified, the DF integral tensor will be\n            saved in this file.\n        _cderi : str or numpy array\n            If _cderi is specified, the DF integral tensor will be read from\n            this HDF5 file (or numpy array). When the DF integral tensor is\n            provided from the HDF5 file, it has to be stored under the dataset\n            'j3c'.\n            The DF integral tensor :math:`V_{x,ij}` should be a 2D array in C\n            (row-major) convention, where x corresponds to index of auxiliary\n            basis, and the combined index ij is the orbital pair index. The\n            hermitian symmetry is assumed for the combined ij index, ie\n            the elements of :math:`V_{x,i,j}` with :math:`i\\geq j` are existed\n            in the DF integral tensor.  Thus the shape of DF integral tensor\n            is (M,N*(N+1)/2), where M is the number of auxbasis functions and\n            N is the number of basis functions of the orbital basis.\n        blockdim : int\n            When reading DF integrals from disk the chunk size to load.  It is\n            used to improve the IO performance.\n    '''\n    def __init__(self, mol):\n        self.mol = mol\n        self.stdout = mol.stdout\n        self.verbose = mol.verbose\n        self.max_memory = mol.max_memory\n        self._auxbasis = None\n\n##################################################\n# Following are not input options\n        self.auxmol = None\n# If _cderi_to_save is specified, the 3C-integral tensor will be saved in this file.\n        self._cderi_to_save = tempfile.NamedTemporaryFile(dir=lib.param.TMPDIR)\n# If _cderi is specified, the 3C-integral tensor will be read from this file\n        self._cderi = None\n        self._call_count = getattr(__config__, 'df_df_DF_call_count', None)\n        self.blockdim = getattr(__config__, 'df_df_DF_blockdim', 240)\n        self._keys = set(self.__dict__.keys())\n\n    @property\n    def auxbasis(self):\n        return self._auxbasis\n    @auxbasis.setter\n    def auxbasis(self, x):\n        if self._auxbasis != x:\n            self._auxbasis = x\n            self.auxmol = None\n            self._cderi = None\n\n    def dump_flags(self):\n        log = logger.Logger(self.stdout, self.verbose)\n        log.info('******** %s flags ********', self.__class__)\n        if self.auxmol is None:\n            log.info('auxbasis = %s', self.auxbasis)\n        else:\n            log.info('auxbasis = auxmol.basis = %s', self.auxmol.basis)\n        log.info('max_memory = %s', self.max_memory)\n        if isinstance(self._cderi, str):\n            log.info('_cderi = %s  where DF integrals are loaded (readonly).',\n                     self._cderi)\n        if isinstance(self._cderi_to_save, str):\n            log.info('_cderi_to_save = %s', self._cderi_to_save)\n        else:\n            log.info('_cderi_to_save = %s', self._cderi_to_save.name)\n        return self\n\n    def build(self):\n        t0 = (time.clock(), time.time())\n        log = logger.Logger(self.stdout, self.verbose)\n\n        self.check_sanity()\n        self.dump_flags()\n\n        mol = self.mol\n        auxmol = self.auxmol = addons.make_auxmol(self.mol, self.auxbasis)\n        nao = mol.nao_nr()\n        naux = auxmol.nao_nr()\n        nao_pair = nao*(nao+1)//2\n\n        max_memory = (self.max_memory - lib.current_memory()[0]) * .8\n        int3c = mol._add_suffix('int3c2e')\n        int2c = mol._add_suffix('int2c2e')\n        if (nao_pair*naux*3*8/1e6 < max_memory and\n            not isinstance(self._cderi_to_save, str)):\n            self._cderi = incore.cholesky_eri(mol, int3c=int3c, int2c=int2c,\n                                              auxmol=auxmol, verbose=log)\n        else:\n            if isinstance(self._cderi_to_save, str):\n                cderi = self._cderi_to_save\n            else:\n                cderi = self._cderi_to_save.name\n            if isinstance(self._cderi, str):\n                log.warn('Value of _cderi is ignored. DF integrals will be '\n                         'saved in file %s .', cderi)\n            outcore.cholesky_eri(mol, cderi, dataname='j3c',\n                                 int3c=int3c, int2c=int2c, auxmol=auxmol,\n                                 max_memory=max_memory, verbose=log)\n            if nao_pair*naux*8/1e6 < max_memory:\n                with addons.load(cderi, 'j3c') as feri:\n                    cderi = numpy.asarray(feri)\n            self._cderi = cderi\n            log.timer_debug1('Generate density fitting integrals', *t0)\n        return self\n\n    def kernel(self, *args, **kwargs):\n        return self.build(*args, **kwargs)\n\n    def loop(self, blksize=None):\n        if self._cderi is None:\n            self.build()\n        if blksize is None:\n            blksize = self.blockdim\n        with addons.load(self._cderi, 'j3c') as feri:\n            naoaux = feri.shape[0]\n            for b0, b1 in self.prange(0, naoaux, blksize):\n                eri1 = numpy.asarray(feri[b0:b1], order='C')\n                yield eri1\n\n    def prange(self, start, end, step):\n        if isinstance(self._call_count, int):\n            self._call_count += 1\n            if self._call_count % 2 == 1:\n                for i in reversed(range(start, end, step)):\n                    yield i, min(i+step, end)\n            else:\n                for i in range(start, end, step):\n                    yield i, min(i+step, end)\n\n        else:\n            for i in range(start, end, step):\n                yield i, min(i+step, end)\n\n    def get_naoaux(self):\n# determine naoaux with self._cderi, because DF object may be used as CD\n# object when self._cderi is provided.\n        if self._cderi is None:\n            self.build()\n        with addons.load(self._cderi, 'j3c') as feri:\n            return feri.shape[0]\n\n    def get_jk(self, dm, hermi=1, vhfopt=None, with_j=True, with_k=True):\n        return df_jk.get_jk(self, dm, hermi, vhfopt, with_j, with_k)\n\n    def get_eri(self):\n        nao = self.mol.nao_nr()\n        nao_pair = nao * (nao+1) // 2\n        ao_eri = numpy.zeros((nao_pair,nao_pair))\n        for eri1 in self.loop():\n            lib.dot(eri1.T, eri1, 1, ao_eri, 1)\n        return ao2mo.restore(8, ao_eri, nao)\n    get_ao_eri = get_eri\n\n    def ao2mo(self, mo_coeffs,\n              compact=getattr(__config__, 'df_df_DF_ao2mo_compact', True)):\n        if isinstance(mo_coeffs, numpy.ndarray) and mo_coeffs.ndim == 2:\n            mo_coeffs = (mo_coeffs,) * 4\n        ijmosym, nij_pair, moij, ijslice = _conc_mos(mo_coeffs[0], mo_coeffs[1], compact)\n        klmosym, nkl_pair, mokl, klslice = _conc_mos(mo_coeffs[2], mo_coeffs[3], compact)\n        mo_eri = numpy.zeros((nij_pair,nkl_pair))\n        sym = (iden_coeffs(mo_coeffs[0], mo_coeffs[2]) and\n               iden_coeffs(mo_coeffs[1], mo_coeffs[3]))\n        Lij = Lkl = None\n        for eri1 in self.loop():\n            Lij = _ao2mo.nr_e2(eri1, moij, ijslice, aosym='s2', mosym=ijmosym, out=Lij)\n            if sym:\n                Lkl = Lij\n            else:\n                Lkl = _ao2mo.nr_e2(eri1, mokl, klslice, aosym='s2', mosym=klmosym, out=Lkl)\n            lib.dot(Lij.T, Lkl, 1, mo_eri, 1)\n        return mo_eri\n    get_mo_eri = ao2mo\n\n\nclass DF4C(DF):\n    '''Relativistic 4-component'''\n    def build(self):\n        log = logger.Logger(self.stdout, self.verbose)\n        mol = self.mol\n        auxmol = self.auxmol = addons.make_auxmol(self.mol, self.auxbasis)\n        n2c = mol.nao_2c()\n        naux = auxmol.nao_nr()\n        nao_pair = n2c*(n2c+1)//2\n\n        max_memory = (self.max_memory - lib.current_memory()[0]) * .8\n        if nao_pair*naux*3*16/1e6*2 < max_memory:\n            self._cderi =(r_incore.cholesky_eri(mol, auxmol=auxmol, aosym='s2',\n                                                int3c='int3c2e_spinor', verbose=log),\n                          r_incore.cholesky_eri(mol, auxmol=auxmol, aosym='s2',\n                                                int3c='int3c2e_spsp1_spinor', verbose=log))\n        else:\n            raise NotImplementedError\n        return self\n\n    def loop(self):\n        if self._cderi is None:\n            self.build()\n        with addons.load(self._cderi[0], 'j3c') as ferill:\n            naoaux = ferill.shape[0]\n            with addons.load(self._cderi[1], 'j3c') as feriss: # python2.6 not support multiple with\n                for b0, b1 in self.prange(0, naoaux, self.blockdim):\n                    erill = numpy.asarray(ferill[b0:b1], order='C')\n                    eriss = numpy.asarray(feriss[b0:b1], order='C')\n                    yield erill, eriss\n\n    def get_jk(self, dm, hermi=1, vhfopt=None, with_j=True, with_k=True):\n        return df_jk.r_get_jk(self, dm, hermi)\n\n    def ao2mo(self, mo_coeffs):\n        raise NotImplementedError\n\n", "meta": {"hexsha": "f45ef2cd00923102356548454e2043661840de6b", "size": 10391, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/df/df.py", "max_stars_repo_name": "fdmalone/pyscf", "max_stars_repo_head_hexsha": "021b17ac721e292b277d2b740e2ff8ab38bb6a4a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-01T12:39:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-01T12:39:45.000Z", "max_issues_repo_path": "pyscf/df/df.py", "max_issues_repo_name": "fdmalone/pyscf", "max_issues_repo_head_hexsha": "021b17ac721e292b277d2b740e2ff8ab38bb6a4a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscf/df/df.py", "max_forks_repo_name": "fdmalone/pyscf", "max_forks_repo_head_hexsha": "021b17ac721e292b277d2b740e2ff8ab38bb6a4a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6603053435, "max_line_length": 100, "alphanum_fraction": 0.5945529785, "include": true, "reason": "import numpy", "num_tokens": 2838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.3140505385717078, "lm_q1q2_score": 0.16804795435571981}}
{"text": "\"\"\"Simplified retina model.\"\"\"\n\nimport logging\nimport numpy as np\nimport cv2\nimport cv2.cv as cv\nfrom collections import OrderedDict\n\nfrom lumos.context import Context\nfrom lumos.input import Projector, run\n\nfrom ..photoreceptor import Rod, Cone\n\n\nclass Retina(object):\n  \"\"\"\n  A multi-layered surface for hosting different types of neurons that make up a retina, simplified version.\n  \n  [Deprecated] Use VisualSystem instead.\n  \n  \"\"\"\n  \n  default_image_size = (480, 480)\n  \n  def __init__(self, imageSize=default_image_size, timeNow=0.0):\n    # * Initialize members, parameters\n    self.context = Context.getInstance()\n    self.logger = logging.getLogger(__name__)\n    self.logger.debug(\"Creating simplified Retina\")  # to distinguish from other Retina versions\n    self.imageSize = imageSize\n    self.imageCenter = (self.imageSize[1] / 2, self.imageSize[0] / 2)\n    self.timeNow = timeNow\n    self.bounds = np.float32([[0.0, 0.0, 2.0], [self.imageSize[0] - 1, self.imageSize[1] - 1, 4.0]])\n    self.center = (self.bounds[0] + self.bounds[1]) / 2\n    self.logger.debug(\"Retina center: {}, image size: {}\".format(self.center, self.imageSize))\n    \n    self.bipolarBlurSize = (5, 5)  # size of blurring kernel used when computing Bipolar cell response\n    self.ganglionCenterSurroundKernel = np.float32(\n      [ [ -1, -1, -1, -1, -1, -1, -1 ],\n        [ -1, -1, -1, -1, -1, -1, -1 ],\n        [ -1, -1,  7,  7,  7, -1, -1 ],\n        [ -1, -1,  7,  9,  7, -1, -1 ],\n        [ -1, -1,  7,  7,  7, -1, -1 ],\n        [ -1, -1, -1, -1, -1, -1, -1 ],\n        [ -1, -1, -1, -1, -1, -1, -1 ] ])\n    self.ganglionCenterSurroundKernel /= np.sum(self.ganglionCenterSurroundKernel)  # normalize\n    #self.logger.info(\"Ganglion center-surround kernel:\\n{}\".format(self.ganglionCenterSurroundKernel))  # [debug]\n    self.ganglionKernelLevels = 4\n    self.ganglionKernels = [None] * self.ganglionKernelLevels\n    self.ganglionKernels[0] = self.ganglionCenterSurroundKernel\n    for i in xrange(1, self.ganglionKernelLevels):\n      self.ganglionKernels[i] = cv2.resize(self.ganglionKernels[i - 1], dsize=None, fx=2, fy=2)\n      self.ganglionKernels[i] /= np.sum(self.ganglionKernels[i])  # normalize\n    #self.logger.info(\"Ganglion center-surround kernel sizes ({} levels): {}\".format(self.ganglionKernelLevels, \", \".join(\"{}\".format(k.shape) for k in self.ganglionKernels)))  # [debug]\n    \n    # * Image and related members\n    self.imageCenter = (self.imageSize[1] / 2, self.imageSize[0] / 2)\n    self.imageShapeC3 = (self.imageSize[1], self.imageSize[0], 3)  # numpy shape for 3 channel images\n    self.imageShapeC1 = (self.imageSize[1], self.imageSize[0])  # numpy shape for single channel images\n    # NOTE Image shapes (h, w, 1) and (h, w) are not compatible unless we use keepdims=True for numpy operations\n    self.imageTypeInt = np.uint8  # numpy dtype for integer-valued images\n    self.imageTypeFloat = np.float32  # numpy dtype for real-valued images\n    self.images = OrderedDict()\n    \n    # ** RGB and HSV images\n    self.images['BGR'] = np.zeros(self.imageShapeC3, dtype=self.imageTypeInt)\n    self.images['HSV'] = np.zeros(self.imageShapeC3, dtype=self.imageTypeInt)\n    self.images['H'] = np.zeros(self.imageShapeC1, dtype=self.imageTypeInt)\n    self.images['S'] = np.zeros(self.imageShapeC1, dtype=self.imageTypeInt)\n    self.images['V'] = np.zeros(self.imageShapeC1, dtype=self.imageTypeInt)\n    \n    # ** Freq/hue-dependent response images for rods and different cone types\n    self.imageRod = np.zeros(self.imageShapeC1, dtype=self.imageTypeFloat)\n    self.imagesCone = dict()  # NOTE dict keys must match names of Cone.cone_types\n    self.imagesCone['S'] = np.zeros(self.imageShapeC1, dtype=self.imageTypeFloat)\n    self.imagesCone['M'] = np.zeros(self.imageShapeC1, dtype=self.imageTypeFloat)\n    self.imagesCone['L'] = np.zeros(self.imageShapeC1, dtype=self.imageTypeFloat)\n    \n    # ** Bipolar and Ganglion cell response images\n    # TODO Add more Ganglion cell types with different receptive field properties (color-opponent cells)\n    #   'RG' +Red    -Green\n    #   'GR' +Green  -Red\n    #   'RB' +Red    -Blue\n    #   'BR' +Blue   -Red\n    #   'BY' +Blue   -Yellow\n    #   'YB' +Yellow -Blue\n    #   'WK' +White  -Black (currently 'ON')\n    #   'KW' +Black  -White (currently 'OFF')\n    # NOTE: R = L cones, G = M cones, B = S cones\n    self.imagesBipolar = dict()\n    self.imagesBipolar['ON'] = np.zeros(self.imageShapeC1, dtype=self.imageTypeFloat)\n    self.imagesBipolar['OFF'] = np.zeros(self.imageShapeC1, dtype=self.imageTypeFloat)\n    self.imagesGanglion = dict()\n    self.imagesGanglion['ON'] = np.zeros(self.imageShapeC1, dtype=self.imageTypeFloat)\n    self.imagesGanglion['OFF'] = np.zeros(self.imageShapeC1, dtype=self.imageTypeFloat)\n    # TODO Verify why image shapes (h, w, 1) and (h, w) are not compatible (use keepdims=True for numpy operations)\n    self.imagesGanglion['RG'] = np.zeros(self.imageShapeC1, dtype=self.imageTypeFloat)\n    self.imagesGanglion['GR'] = np.zeros(self.imageShapeC1, dtype=self.imageTypeFloat)\n    self.imagesGanglion['RB'] = np.zeros(self.imageShapeC1, dtype=self.imageTypeFloat)\n    self.imagesGanglion['BR'] = np.zeros(self.imageShapeC1, dtype=self.imageTypeFloat)\n    self.imagesGanglion['BY'] = np.zeros(self.imageShapeC1, dtype=self.imageTypeFloat)\n    self.imagesGanglion['YB'] = np.zeros(self.imageShapeC1, dtype=self.imageTypeFloat)\n    \n    # ** Combined response (salience) image\n    self.imageSalience = np.zeros(self.imageShapeC1, dtype=self.imageTypeFloat)\n    \n    # ** Spatial attention map with a central (covert) spotlight (currently unused; TODO move to VisualCortex? also, use np.ogrid?)\n    self.imageAttention = np.zeros(self.imageShapeC1, dtype=self.imageTypeFloat)\n    cv2.circle(self.imageAttention, (self.imageSize[1] / 2, self.imageSize[0] / 2), self.imageSize[0] / 3, 1.0, cv.CV_FILLED)\n    self.imageAttention = cv2.blur(self.imageAttention, (self.imageSize[0] / 4, self.imageSize[0] / 4))  # coarse blur\n    \n    # ** Output image(s)\n    if self.context.options.gui:\n      self.imageOut = np.zeros(self.imageShapeC3, dtype=self.imageTypeInt)\n  \n  def initialize(self, imageIn, timeNow):\n    pass  # to emulate FrameProcessor-like interface\n  \n  def process(self, imageIn, timeNow):\n    self.timeNow = timeNow\n    self.logger.debug(\"Retina update @ {}\".format(self.timeNow))\n    \n    # * Get HSV\n    self.images['BGR'][:] = imageIn\n    self.images['HSV'] = cv2.cvtColor(self.images['BGR'], cv2.COLOR_BGR2HSV)\n    self.images['H'], self.images['S'], self.images['V'] = cv2.split(self.images['HSV'])\n    \n    # * Compute Rod and Cone responses\n    # TODO Need non-linear response to hue, sat, val (less dependent on sat, val for cones)\n    self.imageRod = np.float32(180 - cv2.absdiff(self.images['H'], Rod.rod_type.hue) % 180) * 255 * self.images['V'] * Rod.rod_type.responseFactor  # hack: use constant sat = 200 to make response independent of saturation\n    self.imagesCone['S'] = np.float32(180 - cv2.absdiff(self.images['H'], Cone.cone_types[0].hue) % 180) * self.images['S'] * self.images['V'] * Cone.cone_types[0].responseFactor\n    self.imagesCone['M'] = np.float32(180 - cv2.absdiff(self.images['H'], Cone.cone_types[1].hue) % 180) * self.images['S'] * self.images['V'] * Cone.cone_types[1].responseFactor\n    self.imagesCone['L'] = np.float32(180 - cv2.absdiff(self.images['H'], Cone.cone_types[2].hue) % 180) * self.images['S'] * self.images['V'] * Cone.cone_types[2].responseFactor\n    \n    # * Compute Bipolar and Ganglion cell responses\n    # ** Blurring is a step that is effectively achieved in biology by horizontal cells\n    imageRodBlurred = cv2.blur(self.imageRod, self.bipolarBlurSize)\n    self.imagesBipolar['ON'] = np.clip(self.imageRod - 0.75 * imageRodBlurred, 0.0, 1.0)\n    self.imagesBipolar['OFF'] = np.clip((1.0 - self.imageRod) - 0.75 * (1.0 - imageRodBlurred), 0.0, 1.0)  # same as (1 - ON response)?\n    #imagesConeSBlurred = cv2.blur(self.imagesCone['S'], self.bipolarBlurSize)\n    #imagesConeMBlurred = cv2.blur(self.imagesCone['M'], self.bipolarBlurSize)\n    #imagesConeLBlurred = cv2.blur(self.imagesCone['L'], self.bipolarBlurSize)\n    # ** Ganglion cells simply add up responses from a (bunch of) central bipolar cell(s) (ON/OFF) and surrounding antagonistic bipolar cells (OFF/ON)\n    # *** Method 1: Center - Surround\n    #imageGanglionCenterON = cv2.filter2D(self.imagesBipolar['ON'], -1, self.ganglionCenterKernel)\n    #imageGanglionSurroundOFF = cv2.filter2D(self.imagesBipolar['OFF'], -1, self.ganglionSurroundKernel)\n    #self.imagesGanglion['ON'] = 0.75 * imageGanglionCenterON + 0.25 * imageGanglionSurroundOFF\n    # *** Method 2: Center-Surround kernel\n    #self.imagesGanglion['ON'] = np.clip(cv2.filter2D(self.imagesBipolar['ON'], -1, self.ganglionCenterSurroundKernel), 0.0, 1.0)\n    #self.imagesGanglion['OFF'] = np.clip(cv2.filter2D(self.imagesBipolar['OFF'], -1, self.ganglionCenterSurroundKernel), 0.0, 1.0)\n    # *** Method 3: Multi-level Center-Surround kernels, taking maximum\n    self.imagesGanglion['ON'].fill(0.0)\n    self.imagesGanglion['OFF'].fill(0.0)\n    self.imagesGanglion['RG'].fill(0.0)\n    self.imagesGanglion['GR'].fill(0.0)\n    self.imagesGanglion['RB'].fill(0.0)\n    self.imagesGanglion['BR'].fill(0.0)\n    self.imagesGanglion['BY'].fill(0.0)\n    self.imagesGanglion['YB'].fill(0.0)\n    \n    for k in self.ganglionKernels:\n      # Rod pathway\n      self.imagesGanglion['ON'] = np.maximum(self.imagesGanglion['ON'], np.clip(cv2.filter2D(self.imagesBipolar['ON'], -1, k), 0.0, 1.0))\n      self.imagesGanglion['OFF'] = np.maximum(self.imagesGanglion['OFF'], np.clip(cv2.filter2D(self.imagesBipolar['OFF'], -1, k), 0.0, 1.0))\n      # Cone pathway\n      imageRG = self.imagesCone['L'] - self.imagesCone['M']\n      imageRB = self.imagesCone['L'] - self.imagesCone['S']\n      imageBY = self.imagesCone['S'] - (self.imagesCone['L'] + self.imagesCone['M']) / 2\n      self.imagesGanglion['RG'] = np.maximum(self.imagesGanglion['RG'], np.clip(cv2.filter2D(imageRG, -1, k), 0.0, 1.0))\n      self.imagesGanglion['GR'] = np.maximum(self.imagesGanglion['GR'], np.clip(cv2.filter2D(-imageRG, -1, k), 0.0, 1.0))\n      self.imagesGanglion['RB'] = np.maximum(self.imagesGanglion['RB'], np.clip(cv2.filter2D(imageRB, -1, k), 0.0, 1.0))\n      self.imagesGanglion['BR'] = np.maximum(self.imagesGanglion['BR'], np.clip(cv2.filter2D(-imageRB, -1, k), 0.0, 1.0))\n      self.imagesGanglion['BY'] = np.maximum(self.imagesGanglion['BY'], np.clip(cv2.filter2D(imageBY, -1, k), 0.0, 1.0))\n      self.imagesGanglion['YB'] = np.maximum(self.imagesGanglion['YB'], np.clip(cv2.filter2D(-imageBY, -1, k), 0.0, 1.0))\n    \n    # * Compute combined (salience) image; TODO incorporate attention weighting (spatial, as well as by visual feature)\n    # ** Method 1: Max of all Ganglion cell images\n    self.imageSalience.fill(0.0)\n    for ganglionType, ganglionImage in self.imagesGanglion.iteritems():\n      self.imageSalience = np.maximum(self.imageSalience, ganglionImage)\n    \n    #self.imageSalience *= self.imageAttention  # TODO evaluate if this is necessary\n    \n    # * TODO Compute feature vector of attended region\n    \n    # * Show output images if in GUI mode\n    if self.context.options.gui:\n      #cv2.imshow(\"Hue\", self.images['H'])\n      #cv2.imshow(\"Saturation\", self.images['S'])\n      #cv2.imshow(\"Value\", self.images['V'])\n      cv2.imshow(\"Rod response\", self.imageRod)\n      cv2.imshow(\"S-cone response\", self.imagesCone['S'])\n      cv2.imshow(\"M-cone response\", self.imagesCone['M'])\n      cv2.imshow(\"L-cone response\", self.imagesCone['L'])\n      cv2.imshow(\"ON Bipolar cells\", self.imagesBipolar['ON'])\n      cv2.imshow(\"OFF Bipolar cells\", self.imagesBipolar['OFF'])\n      #cv2.imshow(\"ON Ganglion cells\", self.imagesGanglion['ON'])\n      #cv2.imshow(\"OFF Ganglion cells\", self.imagesGanglion['OFF'])\n      for ganglionType, ganglionImage in self.imagesGanglion.iteritems():\n        cv2.imshow(\"{} Ganglion cells\".format(ganglionType), ganglionImage)\n      cv2.imshow(\"Salience\", self.imageSalience)\n      \n      # Designate a representative output image\n      self.imageOut = self.imageSalience\n      #_, self.imageOut = cv2.threshold(self.imageOut, 0.15, 1.0, cv2.THRESH_TOZERO)  # apply threshold to remove low-response regions\n    \n    return True, self.imageOut\n\n\nif __name__ == \"__main__\":\n  Context.createInstance(description=\"Test application that uses a SimplifiedProjector to run image input through a (simplified) Retina.\")\n  run(Projector(Retina()))\n", "meta": {"hexsha": "ddfe11625002632ec3b7906b4d7754b7a341a27e", "size": 12506, "ext": "py", "lang": "Python", "max_stars_repo_path": "nap/vision/simplified/retina.py", "max_stars_repo_name": "napratin/nap", "max_stars_repo_head_hexsha": "a5735a2a2a0ad9a4da2d48671f3072ad60173b0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-02-19T21:56:23.000Z", "max_stars_repo_stars_event_max_datetime": "2016-02-19T21:56:23.000Z", "max_issues_repo_path": "nap/vision/simplified/retina.py", "max_issues_repo_name": "napratin/nap", "max_issues_repo_head_hexsha": "a5735a2a2a0ad9a4da2d48671f3072ad60173b0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-06-05T17:34:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-13T00:40:43.000Z", "max_forks_repo_path": "nap/vision/simplified/retina.py", "max_forks_repo_name": "napratin/nap", "max_forks_repo_head_hexsha": "a5735a2a2a0ad9a4da2d48671f3072ad60173b0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.7136150235, "max_line_length": 221, "alphanum_fraction": 0.6810331041, "include": true, "reason": "import numpy", "num_tokens": 3786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.16804795313444715}}
{"text": "import time\nimport multiprocessing as mp\nfrom typing import Tuple, Dict, Optional\n\nimport numpy as np\nimport pandas as pd\nfrom scipy.interpolate.interpolate import interp1d\n\nimport sha_calc as sha_calc\nfrom gmhazard_calc import site\nfrom gmhazard_calc import utils\nfrom gmhazard_calc import shared\nfrom gmhazard_calc import gm_data\nfrom gmhazard_calc import site_source\nfrom gmhazard_calc import constants as const\nfrom gmhazard_calc.im import IM\nfrom .HazardResult import BranchHazardResult, EnsembleHazardResult\n\n\nDEFAULT_N_IM_VALUES = 200\n\n\ndef run_ensemble_hazard(\n    ensemble: gm_data.Ensemble,\n    site_info: site.SiteInfo,\n    im: IM,\n    branch_hazard: Optional[Dict[str, BranchHazardResult]] = None,\n    im_values: Optional[np.ndarray] = None,\n    calc_percentiles: bool = True,\n) -> EnsembleHazardResult:\n    \"\"\"Computes the weighted hazard curve for all branches in\n    the specified ensemble.\n\n    Parameters\n    ----------\n    ensemble: Ensemble\n        ensemble to use for calculation\n    site_info: SiteInfo\n        The site at which to calculate the hazard curve\n    im: IM\n        IM object for specifying the IM to use for calculations\n    branch_hazard: Dictionary of str: HazardResult, optional\n        Where the key is the branch name the hazard result is for.\n        If specified then this saves re-computing the hazard\n        results for the branches.\n    im_values: np.ndarray, optional\n        The range of IM values for which to calculate the\n        hazard, not used if branches_hazard is passed in\n    calc_percentiles: bool, optional\n        True or False to calculate the 16th and 84th percentiles\n\n    Returns\n    -------\n    HazardResult\n    \"\"\"\n\n    def get_weighted_branch_hazard(hazard: BranchHazardResult):\n        return (\n            hazard.branch.weight * hazard.fault_hazard,\n            hazard.branch.weight * hazard.ds_hazard,\n        )\n\n    ensemble.check_im(im)\n\n    # Get the hazard per branch\n    if branch_hazard is None:\n        branch_hazard = run_branches_hazard(\n            ensemble,\n            site_info,\n            im,\n            im_values=im_values,\n        )\n\n    # Combine the branches according to their weights\n    fault_hazard, ds_hazard = None, None\n    for branch_name, cur_hazard in branch_hazard.items():\n        cur_fault_h, cur_ds_h = get_weighted_branch_hazard(cur_hazard)\n        if fault_hazard is None:\n            fault_hazard, ds_hazard = cur_fault_h, cur_ds_h\n        else:\n            fault_hazard += cur_fault_h\n            ds_hazard += cur_ds_h\n\n    # Compute 16th and 84th percentile if flag enabled\n    percentiles = None\n    if calc_percentiles:\n        # Retrieving data\n        im_values = fault_hazard.index.values\n        excd_values, weights = [], []\n        for cur_branch in branch_hazard.values():\n            assert np.all(cur_branch.fault_hazard.index.values == im_values)\n            excd_values.append(cur_branch.total_hazard.values)\n            weights.append(cur_branch.branch.weight)\n        excd_values, weights = np.asarray(excd_values).T, np.asarray(weights)\n        weights = np.repeat(weights[None, ...], im_values.size, 0)\n\n        # Sorting\n        sort_ind = np.argsort(excd_values, axis=1)\n        excd_values = np.take_along_axis(excd_values, sort_ind, 1)\n        weights = np.take_along_axis(weights, sort_ind, 1)\n\n        # Inverse CDF lookup\n        cdf_x, cdf_y = excd_values, np.cumsum(weights, axis=1)\n        x_values = sha_calc.shared.query_non_parametric_multi_cdf_invs(\n            [0.16, 0.84], cdf_x, cdf_y\n        )\n        x_values = np.stack(x_values, axis=1)\n        percentiles = pd.DataFrame(\n            data=x_values, columns=[\"16th\", \"84th\"], index=fault_hazard.index.values\n        )\n\n    return EnsembleHazardResult(\n        im,\n        site_info,\n        fault_hazard,\n        ds_hazard,\n        ensemble,\n        list(branch_hazard.values()),\n        percentiles=percentiles,\n    )\n\n\ndef run_branches_hazard(\n    ensemble: gm_data.Ensemble,\n    site_info: site.SiteInfo,\n    im: IM,\n    im_values: Optional[np.ndarray] = None,\n) -> Dict[str, BranchHazardResult]:\n    \"\"\"Runs computation of the hazard curve for each of the branches in\n    the specified IM-ensemble.\n\n    Parameters\n    ----------\n    ensemble : Ensemble\n        Ensemble to use for calculation\n    site_info : SiteInfo\n        The site at which to calculate the hazard curve\n    im : IM\n        IM Object to use for calculations\n    im_values: array of floats, optional\n        The IM values for which to calculate the hazard for.\n\n    Returns\n    -------\n    Dict of str : HazardResult, where the key is the branch name\n    \"\"\"\n    ensemble.check_im(im)\n    im_ensemble = ensemble.get_im_ensemble(im.im_type)\n\n    hazards = {}\n    for branch_name, branch in im_ensemble.branches_dict.items():\n        hazards[branch_name] = run_branch_hazard(\n            branch, site_info, im, im_values=im_values\n        )\n\n    return hazards\n\n\ndef run_branch_hazard(\n    branch: gm_data.Branch,\n    site_info: site.SiteInfo,\n    im: IM,\n    im_values: Optional[np.ndarray] = None,\n) -> BranchHazardResult:\n    \"\"\"Computes the hazard for a single branch\n\n    Parameters\n    ----------\n    branch: Branch\n        The branch for which to calculate the hazard curve\n    site_info: SiteInfo\n        The site at which to calculate the hazard curve\n    im: IM\n        IM Object used for calculations\n    im_values: np.ndarray, optional\n        The IM values for which to calculate the hazard for.\n\n    Returns\n    -------\n    HazardResult\n    \"\"\"\n    im_values = (\n        utils.get_im_values(im, n_values=DEFAULT_N_IM_VALUES)\n        if im_values is None\n        else im_values\n    )\n\n    # Fault Hazard\n    fault_gm_prob_df = shared.get_gm_prob_df(\n        branch,\n        site_info,\n        im,\n        im_values,\n        const.SourceType.fault,\n        ensemble=branch.im_ensemble.ensemble,\n    )\n    if fault_gm_prob_df is not None:\n        fault_hazard = sha_calc.hazard_curve(\n            fault_gm_prob_df, branch.rupture_df_id_ix[\"annual_rec_prob\"]\n        )\n    else:\n        fault_hazard = pd.Series(data=np.zeros(im_values.shape), index=im_values)\n\n    # DS Hazard\n    ds_gm_prob_df = shared.get_gm_prob_df(\n        branch,\n        site_info,\n        im,\n        im_values,\n        const.SourceType.distributed,\n        ensemble=branch.im_ensemble.ensemble,\n    )\n    if ds_gm_prob_df is not None:\n        ds_hazard = sha_calc.hazard_curve(\n            ds_gm_prob_df, branch.rupture_df_id_ix[\"annual_rec_prob\"]\n        )\n    else:\n        ds_hazard = pd.Series(data=np.zeros(im_values.shape), index=im_values)\n\n    return BranchHazardResult(im, site_info, fault_hazard, ds_hazard, branch)\n\n\ndef run_full_hazard(\n    ensemble: gm_data.Ensemble,\n    site_info: site.SiteInfo,\n    im: IM,\n    calc_percentiles: bool = False,\n    im_values: Optional[np.ndarray] = None,\n) -> Tuple[EnsembleHazardResult, Dict[str, BranchHazardResult]]:\n    \"\"\"Convenience function, computes the ensemble\n     and hazard for all branches.\n\n    Parameters\n    ----------\n    branch: Branch\n        The branch for which to calculate the hazard curve\n    site_info: SiteInfo\n        The site at which to calculate the hazard curve\n    im: IM\n        IM Object to use for calculations\n    calc_percentiles: bool, optional\n        True or false for calculating 16th and 84th percentiles\n    im_values: np.ndarray, optional\n        The IM values for which to calculate the hazard for.\n\n    Returns\n    -------\n    HazardResult:\n        The ensemble hazard\n    dict:\n        The hazard for each branch, key is the branch name\n    \"\"\"\n    branch_hazard = run_branches_hazard(ensemble, site_info, im, im_values=im_values)\n    ens_hazard = run_ensemble_hazard(\n        ensemble,\n        site_info,\n        im,\n        calc_percentiles=calc_percentiles,\n        branch_hazard=branch_hazard,\n        im_values=im_values,\n    )\n\n    return ens_hazard, branch_hazard\n\n\ndef run_hazard_map(\n    ensemble: gm_data.Ensemble, im: IM, exceedance: float, n_procs: Optional[int] = 4\n) -> pd.DataFrame:\n    \"\"\"\n    Computes the hazard at each station in the ensemble for the\n    specified exceedance.\n\n    Parameters\n    ----------\n    ensemble: Ensemble\n    im: IM\n        IM Object used for calculations\n    exceedance: float\n        The exceedance value\n    n_procs:\n        Number of processes to use\n\n    Returns\n    -------\n    pd.Series\n        format: index = station_name, values: exceedance probability\n    \"\"\"\n    # Drop duplicate location stations\n    stations_df = ensemble.stations.drop_duplicates(subset=[\"lon\", \"lat\"])\n\n    n_stations = stations_df.shape[0]\n    if n_procs == 1:\n        excd_probs = []\n        for ix, station_name in enumerate(stations_df.index.values):\n            excd_probs.append(\n                _get_hazard(ensemble, station_name, im, exceedance, ix, n_stations)\n            )\n    else:\n        with mp.Pool(n_procs) as p:\n            excd_probs = p.starmap(\n                _get_hazard,\n                [\n                    (ensemble, station_name, im, exceedance, ix, n_stations)\n                    for ix, station_name in enumerate(stations_df.index.values)\n                ],\n            )\n\n    result_df = stations_df.copy()\n    result_df[\"value\"] = excd_probs\n    return result_df\n\n\ndef get_exceedance_rate(probability: float, years: int):\n    \"\"\"Gets the exceedance rate for the specified probability\n    in number of specified years\n\n    Parameters\n    ----------\n    probability: float\n        The probability of interest (e.g. 50 for 50%)\n    years: int\n        The number of years\n\n    Returns\n    -------\n    float\n        The exceedance rate\n    \"\"\"\n    return -1.0 / years * np.log(1 - (probability / 100))\n\n\ndef exceedance_to_im(\n    exceedance: float, im_values: np.ndarray, hazard_values: np.ndarray\n):\n    \"\"\"Converts the given exceedance rate to an IM value, based on the\n    provided im and hazard values\n\n    Parameters\n    ----------\n    exceedance: float\n        The exceedance value of interest\n    im_values: numpy array\n        The IM values corresponding to the hazard values\n        Has to be the same shape as hazard_values\n    hazard_values: numpy array\n        The hazard values corresponding to the IM values\n        Has to be the same shape as im_values\n\n    Returns\n    -------\n    float\n        The IM value corresponding to the provided exceedance\n    \"\"\"\n    return np.exp(\n        interp1d(\n            np.log(hazard_values) * -1,\n            np.log(im_values),\n            kind=\"linear\",\n            bounds_error=True,\n        )(np.log(exceedance) * -1)\n    )\n\n\ndef im_to_exceedance(im_value: float, im_values: np.ndarray, hazard_values: np.ndarray):\n    \"\"\"Inverse to exceedance_to_im\"\"\"\n    return np.exp(\n        interp1d(\n            np.log(im_values), np.log(hazard_values), kind=\"linear\", bounds_error=True\n        )(np.log(im_value))\n    )\n\n\ndef _get_hazard(\n    ensemble: gm_data.Ensemble,\n    station_name: str,\n    im: IM,\n    exceedance: float,\n    ix: int,\n    n_stations: int,\n):\n    \"\"\"Computes the ensemble hazard curve for the specific station\"\"\"\n    start_time = time.time()\n    site_info = site.get_site_from_name(ensemble, station_name)\n    im_value = run_ensemble_hazard(ensemble, site_info, im).exceedance_to_im(exceedance)\n\n    print(\n        f\"Progress {ix}/{n_stations} - station {station_name} \"\n        f\"- {time.time() - start_time}\"\n    )\n    return im_value\n\n\ndef vs30_update(site_info: site.SiteInfo, hazard_result: BranchHazardResult):\n    \"\"\"Computes the updated hazard for the user specified vs30 value\n\n    Parameters\n    ----------\n    site_info: SiteInfo\n        Site of interest\n    hazard_result: HazardResult\n        The hazard result for the db vs30 value\n\n    Returns\n    -------\n    flt_upd_hazard: pd.Series\n        The fault based updated hazard\n        format: index = IM values, values = exceedance probability\n    ds_upd_hazard: pd.DataFrame\n        The distributed seismicity based updated hazard\n        format: index = IM values, values = exceedance probability\n    \"\"\"\n    import empirical.util.classdef as classdef\n    import empirical.util.empirical_factory as emp_factory\n\n    branch, ensemble = hazard_result.branch, hazard_result.im_ensemble.ensemble\n    im_ensemble = hazard_result.im_ensemble\n\n    # Get IM of interest and the IM values of interest\n    im = hazard_result.im\n    im_values = hazard_result.im_values\n\n    # Get the recurrance & gm prob dfs\n    rec_prob = branch.rupture_df_id[\"annual_rec_prob\"]\n    flt_gm_prob_df = shared.get_gm_prob_df(\n        branch, site_info, im, im_values, const.SourceType.fault, ensemble=ensemble\n    )\n    ds_gm_prob_df = shared.get_gm_prob_df(\n        branch,\n        site_info,\n        im,\n        im_values,\n        const.SourceType.distributed,\n        ensemble=ensemble,\n    )\n\n    # Get the fault and distributed disagg and combine to get the full disagg\n    flt_disagg = sha_calc.disagg_exceedance_multi(\n        flt_gm_prob_df, rec_prob, hazard_result.total_hazard\n    )\n    ds_disagg = sha_calc.disagg_exceedance_multi(\n        ds_gm_prob_df, rec_prob, hazard_result.total_hazard\n    )\n    full_disagg = pd.concat([flt_disagg, ds_disagg])\n\n    # Create distance lookup\n    flt_distance_df = site_source.get_distance_df(ensemble.flt_ssddb_ffp, site_info)\n    ds_distance_df = site_source.get_distance_df(ensemble.ds_ssddb_ffp, site_info)\n    distance_lookup_df = pd.concat([flt_distance_df, ds_distance_df])\n\n    # Create a rupture_id to location name lookup, since the data from the\n    # the site-source db uses location names and not rupture ids\n    flt_loc_names = site_source.rupture_id_to_loc_name(\n        flt_disagg.index.values, const.SourceType.fault\n    )\n    ds_loc_names = site_source.rupture_id_to_loc_name(\n        ds_disagg.index.values, const.SourceType.distributed\n    )\n    loc_names_lookup = pd.concat([flt_loc_names, ds_loc_names])\n\n    # Compute the mean magnitude\n    ruptures = full_disagg.index.values\n    flt_ruptures = flt_disagg.index.values\n    ds_ruptures = ds_disagg.index.values\n    flt_mag_mean_df = shared.compute_contr_mean(\n        im_ensemble.rupture_df_id.magnitude.loc[flt_ruptures], full_disagg.loc[flt_ruptures]\n    )\n    ds_mag_mean_df = shared.compute_contr_mean(\n        im_ensemble.rupture_df_id.magnitude.loc[ds_ruptures], full_disagg.loc[ds_ruptures]\n    )\n\n    # Create a distance dataframe for the ruptures of interest\n    # Note: Have to use reindex since there might be ruptures for which\n    # there is no site-source data for the current station (reindex just sets those to nan)\n    distance_df = distance_lookup_df.reindex(loc_names_lookup.loc[ruptures].values)\n    distance_df = distance_df.set_index(ruptures)\n\n    # Compute the mean rrup & rjb\n    flt_rrup_mean_df = shared.compute_contr_mean(\n        distance_df.rrup.loc[flt_ruptures], full_disagg.loc[flt_ruptures]\n    )\n    ds_rrup_mean_df = shared.compute_contr_mean(\n        distance_df.rrup.loc[ds_ruptures], full_disagg.loc[ds_ruptures]\n    )\n\n    flt_rjb_mean_df = shared.compute_contr_mean(\n        distance_df.rjb.loc[flt_ruptures], full_disagg.loc[flt_ruptures]\n    )\n    ds_rjb_mean_df = shared.compute_contr_mean(\n        distance_df.rjb.loc[ds_ruptures], full_disagg.loc[ds_ruptures]\n    )\n\n    # Sanity check (can probably remove these at some point)\n    assert np.all(np.isclose(flt_mag_mean_df.index.values, im_values))\n    assert np.all(np.isclose(ds_mag_mean_df.index.values, im_values))\n    assert np.all(np.isclose(flt_rrup_mean_df.index.values, im_values))\n    assert np.all(np.isclose(ds_rrup_mean_df.index.values, im_values))\n    assert np.all(np.isclose(flt_rjb_mean_df.index.values, im_values))\n    assert np.all(np.isclose(ds_rjb_mean_df.index.values, im_values))\n\n    # Compute the vs30 ratios for each IM value of the hazard data\n    vs30_ratio, flt_vs30_ratio, ds_vs30_ratio = [], [], []\n    for ix, im_value in enumerate(im_values):\n        # Create the fault and site objects\n        cur_flt_fault = classdef.Fault(\n            Mw=flt_mag_mean_df.iloc[ix], rake=-90.0, dip=45.0, zbot=15.0, hdepth=5.0\n        )\n        cur_ds_fault = classdef.Fault(\n            Mw=ds_mag_mean_df.iloc[ix], rake=-90.0, dip=45.0, zbot=15.0, hdepth=5.0\n        )\n\n        cur_flt_site_db = classdef.Site(\n            rrup=float(flt_rrup_mean_df.iloc[ix]),\n            rjb=float(flt_rjb_mean_df.iloc[ix]),\n            rx=0,\n            vs30=site_info.vs30,\n        )\n        cur_flt_site_user = classdef.Site(\n            rrup=float(flt_rrup_mean_df.iloc[ix]),\n            rjb=float(flt_rjb_mean_df.iloc[ix]),\n            rx=0,\n            vs30=site_info.user_vs30,\n        )\n\n        cur_ds_site_db = classdef.Site(\n            rrup=float(ds_rrup_mean_df.iloc[ix]),\n            rjb=float(ds_rjb_mean_df.iloc[ix]),\n            rx=0,\n            vs30=site_info.vs30,\n        )\n        cur_ds_site_user = classdef.Site(\n            rrup=float(ds_rrup_mean_df.iloc[ix]),\n            rjb=float(ds_rjb_mean_df.iloc[ix]),\n            rx=0,\n            vs30=site_info.user_vs30,\n        )\n\n        # Run the empirical model for using the db and user specified vs30\n        flt_im_db, _ = emp_factory.compute_gmm(\n            cur_flt_fault,\n            cur_flt_site_db,\n            classdef.GMM.CB_14,\n            str(im),\n            period=im.period,\n        )\n        flt_im_user, _ = emp_factory.compute_gmm(\n            cur_flt_fault,\n            cur_flt_site_user,\n            classdef.GMM.CB_14,\n            str(im),\n            period=im.period,\n        )\n\n        ds_im_db, _ = emp_factory.compute_gmm(\n            cur_ds_fault, cur_ds_site_db, classdef.GMM.CB_14, str(im), period=im.period\n        )\n        ds_im_user, _ = emp_factory.compute_gmm(\n            cur_ds_fault,\n            cur_ds_site_user,\n            classdef.GMM.CB_14,\n            str(im),\n            period=im.period,\n        )\n\n        # Compute the vs30 ratio\n        flt_vs30_ratio.append(flt_im_user / flt_im_db)\n        ds_vs30_ratio.append(ds_im_user / ds_im_db)\n\n    # Compute the updated IM values\n    flt_vs30_updated = im_values * np.asarray(flt_vs30_ratio)\n    ds_vs30_updated = im_values * np.asarray(ds_vs30_ratio)\n\n    # Interpolate to return data at the same IM levels\n    flt_mask = ~np.isnan(flt_vs30_updated)\n    flt_vs30_updated_excd = np.interp(\n        im_values,\n        flt_vs30_updated[flt_mask],\n        hazard_result.fault_hazard.values[flt_mask],\n        right=0.0,\n    )\n    flt_upd_hazard = pd.Series(index=im_values, data=flt_vs30_updated_excd)\n\n    ds_mask = ~np.isnan(ds_vs30_updated)\n    ds_vs30_updated_excd = np.interp(\n        im_values,\n        ds_vs30_updated[ds_mask],\n        hazard_result.ds_hazard.values[ds_mask],\n        right=0.0,\n    )\n    ds_upd_hazard = pd.Series(index=im_values, data=ds_vs30_updated_excd)\n\n    return flt_upd_hazard, ds_upd_hazard\n", "meta": {"hexsha": "7dd25b8867ce2068c030a80ae70b170d2d6bf691", "size": 18826, "ext": "py", "lang": "Python", "max_stars_repo_path": "calculation/gmhazard_calc/gmhazard_calc/hazard/hazard.py", "max_stars_repo_name": "ucgmsim/seistech", "max_stars_repo_head_hexsha": "e66b89327e096fdd5bfc575c474d9f19b5d4ce29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "calculation/gmhazard_calc/gmhazard_calc/hazard/hazard.py", "max_issues_repo_name": "ucgmsim/seistech", "max_issues_repo_head_hexsha": "e66b89327e096fdd5bfc575c474d9f19b5d4ce29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-08-31T03:36:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-13T01:51:19.000Z", "max_forks_repo_path": "calculation/gmhazard_calc/gmhazard_calc/hazard/hazard.py", "max_forks_repo_name": "ucgmsim/seistech", "max_forks_repo_head_hexsha": "e66b89327e096fdd5bfc575c474d9f19b5d4ce29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8006756757, "max_line_length": 92, "alphanum_fraction": 0.6604164453, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.16804795313444712}}
{"text": "\"\"\"This module defines class Energy.\"\"\"\n\nimport numpy as np\n\nimport brave.common as common\nfrom brave.kpoint import Kpoint\n\nclass Energy(Kpoint):\n    \"\"\"Class for representing the energy bands.\n\n    Class Energy defines the electron or phonon energy bands. It is used for\n    plotting the energy band diagrams in class Diagram and for generating the\n    input files for calculating the electronic transport coefficients.\n    \"\"\"\n\n    @property\n    def eunit(self):\n        \"\"\"A string holding the units of energy. Possible values are 'ev',\n        'rydberg', 'hartree', 'thz' and 'cm-1'.\n        \"\"\"\n        return self._eunit\n\n    @eunit.setter\n    def eunit(self, value):\n        if not isinstance(value, str):\n            raise TypeError('eunit {0!r}'.format(value))\n        if value not in common._escale.keys():\n            raise ValueError('eunit {0!r}'.format(value))\n        self._eunit = value\n\n    @eunit.deleter\n    def eunit(self):\n        del self._eunit\n\n    @property\n    def nkpoint(self):\n        \"\"\"An integer holding the number of k-points.\"\"\"\n        _list = []\n        if hasattr(self, 'energy'):\n            _list.append(self._energy.shape[0])\n        if hasattr(self, 'kpoint') or hasattr(self, 'kline') or hasattr(\n                self, 'kweight'):\n            _list.append(super().nkpoint)\n\n        if _list[1:] == _list[:-1] and len(_list) > 0:\n            return _list[0]\n        else:\n            raise AttributeError('nkpoint')\n\n    @property\n    def nband(self):\n        \"\"\"An integer holding the number of electron energy bands or phonon\n    modes.\n        \"\"\"\n        return self._energy.shape[1]\n\n    @property\n    def nspin(self):\n        \"\"\"An integer holding the number of spin components for electrons or 1\n    for phonons.\n        \"\"\"\n        return self._energy.shape[2]\n\n    @property\n    def energy(self):\n        \"\"\"A nkpoint by nband by nspin ndarray of floats holding the electron\n    or phonon energies, in units of eunit.\n        \"\"\"\n        return self._energy\n\n    @energy.setter\n    def energy(self, value):\n        if not isinstance(value, np.ndarray):\n            raise TypeError('energy {0!r}'.format(value))\n        if value.dtype != np.dtype('float') or len(value.shape) != 3:\n            raise ValueError('energy {0!r}'.format(value))\n        self._energy = value\n\n    @energy.deleter\n    def energy(self):\n        del self._energy\n\n    @property\n    def efermi(self):\n        \"\"\"A float holding the chemical potential of electrons or the Fermi\n    level, in units of eunit.\n        \"\"\"\n        return self._efermi\n\n    @efermi.setter\n    def efermi(self, value):\n        if not isinstance(value, float):\n            raise TypeError('efermi {0!r}'.format(value))\n        self._efermi = value\n\n    @efermi.deleter\n    def efermi(self):\n        del self._efermi\n\n    @property\n    def vref(self):\n        \"\"\"A float holding the reference potential, in units of eunit.\"\"\"\n        return self._vref\n\n    @vref.setter\n    def vref(self, value):\n        if not isinstance(value, float):\n            raise TypeError('vref {0!r}'.format(value))\n        self._vref = value\n\n    @vref.deleter\n    def vref(self):\n        del self._vref\n\n    def set_eunit(self, eunit):\n        \"\"\"Sets the new value of eunit and converts energy, efermi and vref.\n\n    Args:\n        eunit (str): New value of eunit. Possible values are 'ev', 'rydberg',\n            'hartree', 'thz' and 'cm-1'.\n        \"\"\"\n        if eunit != self.eunit:\n            if hasattr(self, 'energy'):\n                self.energy *= common._escale[eunit] / common._escale[\n                        self.eunit]\n            if hasattr(self, 'efermi'):\n                self.efermi *= common._escale[eunit] / common._escale[\n                        self.eunit]\n            if hasattr(self, 'vref'):\n                self.vref *= common._escale[eunit] / common._escale[self.eunit]\n            self.eunit = eunit\n\n    def calc_efermi(self, soc = None):\n        \"\"\"Sets the new value of efermi calculated from nelec for insulators.\n    Does not work for metals.\n\n    Args:\n        soc (bool): Set to True if the calculation includes the spin-orbit\n            coupling.\n\n    Returns:\n        evbm (float): VBM energy in units of eunit.\n        ecbm (float): CBM energy in units of eunit.\n        kvbm (ndarray): VBM k-point in units of kunit.\n        kcbm (ndarray): CBM k-point in units of kunit.\n\n    Sets efermi in the middle of the band gap between the VBM (valence band\n    maximum) and the CBM (conduction band minimum).\n        \"\"\"\n        if soc is None:\n            soc = False\n\n        if soc:\n            spin_degeneracy = 1\n        else:\n            spin_degeneracy = 2\n\n        nval = self.nelec / spin_degeneracy\n\n        if nval.is_integer():\n            nval = int(nval)\n        else:\n            raise ValueError(nval)\n\n        nkpoint = self.nkpoint\n        nband = self.nband\n        nspin = self.nspin\n        energy = self.energy\n        kpoint = self.kpoint\n        ivbm = np.unravel_index(energy[:, :nval, :].argmax(), (\n                nkpoint, nval, nspin))\n        icbm = np.unravel_index(energy[:, nval:, :].argmin(), (\n                nkpoint, nband - nval, nspin))\n        evbm = energy[ivbm[0], ivbm[1], ivbm[2]]\n        ecbm = energy[icbm[0], icbm[1] + nval, icbm[2]]\n        kvbm = kpoint[ivbm[0], :]\n        kcbm = kpoint[icbm[0], :]\n\n        self.efermi = (evbm + ecbm) / 2.0\n        return evbm, ecbm, kvbm, kcbm\n\n    def sort_energy(self):\n        \"\"\"Sorts energy in ascending order by band.\n\n    This fixes discontinuities in the band structure.\n        \"\"\"\n        _energy = np.copy(self.energy)\n\n        slice = np.zeros(self.nband, float)\n        for ikpoint in range(1, self.nkpoint):\n            for ispin in range(self.nspin):\n                slice = _energy[ikpoint, :, ispin]\n                dummy = np.sort(slice)\n                _energy[ikpoint, :, ispin] = dummy\n\n        self.energy = _energy\n\n    def read(self, fileformat, filenames, etype = None, lapwkunit = None):\n        \"\"\"Reads properties from files.\n\n    Args:\n        fileformat (str): File format. Possible values are below.\n        filenames (list): File names. Possible values are below.\n        etype (str): Energy type. Possible values are below.\n        lapwkunit (str): WIEN2k workaround. WIEN2k requires k-points in crystal\n            coordinates with respect to conventional reciprocal lattice vectors\n            (see xcrysden/tests/supportInfo.kpath). Possible values are below.\n\n    fileformat       filenames\n    ----------       ---------\n    'internal'       ['prefix.brave']\n    'pw-out'         ['prefix.out']\n    'bands-out'      ['prefix.out', 'bands.out'] or ['prefix.out',\n                         'bands.outup', 'bands.outdn']\n    'matdyn-out'     ['prefix.out', 'matdyn.modes']\n    'inteqp-out'     ['prefix.out', 'bandstructure.dat']\n    'sigma-out'      ['prefix.out', 'sigma_hp.log']\n    'wannier-out'    ['seedname.win', 'seedname_band.dat'] or ['seedname.win',\n                         'seedname_band.datup', 'seedname_band.datdn']\n    'vasp-out'       ['OUTCAR']\n    'lapw-out'       ['case.output1'] or ['case.output1up', 'case.output1dn']\n\n    fileformat       etype\n    ----------       -----\n    'inteqp-out'     'emf' or 'eqp'\n    'sigma-out'      'edft', 'ecor', 'eqp0', 'eqp1', 'eqp0p' or 'eqp1p'\n\n    fileformat       lapwkunit\n    ----------       ---------\n    'lapw-out'       'cartesian' (for fcc or bcc) or 'crystal' (for hcp)\n        \"\"\"\n        if lapwkunit is None:\n            lapwkunit = 'cartesian'\n\n        if fileformat == 'internal':\n            self._read_file_internal(3, filenames)\n        elif fileformat == 'pw-out':\n            self._read_file_pw_out(3, filenames)\n        elif fileformat == 'bands-out':\n            self._read_file_pw_out(1, [filenames[0]])\n            self._read_file_bands_out(3, filenames[1:])\n        elif fileformat == 'matdyn-out':\n            self._read_file_pw_out(1, [filenames[0]])\n            self._read_file_matdyn_out(3, [filenames[1]])\n        elif fileformat == 'inteqp-out':\n            self._read_file_pw_out(1, [filenames[0]])\n            self._read_file_inteqp_out(3, [filenames[1]], etype)\n        elif fileformat == 'sigma-out':\n            self._read_file_pw_out(1, [filenames[0]])\n            self._read_file_sigma_out(3, [filenames[1]], etype)\n        elif fileformat == 'wannier-out':\n            self._read_file_wannier_in(1, [filenames[0]])\n            self._read_file_wannier_out(3, filenames[1:])\n        elif fileformat == 'vasp-out':\n            self._read_file_vasp_out(3, filenames)\n        elif fileformat == 'lapw-out':\n            self._read_file_lapw_out(3, filenames, lapwkunit)\n        else:\n            raise ValueError(fileformat)\n\n    def write(self, fileformat, filenames, lapwkunit = None, boltzparam = None):\n        \"\"\"Writes properties to files.\n\n    Args:\n        fileformat (str): File format. Possible values are below.\n        filenames (list): File names. Possible values are below.\n        lapwkunit (str): WIEN2k workaround. WIEN2k requires k-points in crystal\n            coordinates with respect to conventional reciprocal lattice vectors\n            (see xcrysden/tests/supportInfo.kpath). Possible values are below.\n        boltzparam (list): BoltzTraP parameters. Possible values are below.\n\n    fileformat       filenames\n    ----------       ---------\n    'internal'       ['prefix.brave']\n    'pw-in'          ['prefix.in']\n    'wannier-in'     ['seedname.win']\n    'vasp-kpt'       ['KPOINTS']\n    'lapw-kpt'       ['case.klist_band']\n    'boltztrap-in'   ['case.def', 'case.intrans', 'case.struct', 'case.energy']\n                         (for spin-unpolarized case) or ['case.def',\n                         'case.intrans', 'case.struct', 'case.energyso'] (for\n                         spin-polarized case)\n\n    fileformat       lapwkunit\n    ----------       ---------\n    'lapw-kpt'       'cartesian' (for fcc or bcc) or 'crystal' (for hcp)\n\n    fileformat       boltzparam\n    ----------       ----------\n    'boltztrap-in'   [0.0005, 0.6, 5, 0.3, 1200.0, 10.0, -1.0, 'TETRA', 0]\n        \"\"\"\n        if lapwkunit is None:\n            lapwkunit = 'cartesian'\n        if boltzparam is None:\n            boltzparam = [0.0005, 0.6, 5, 0.3, 1200.0, 10.0, -1.0, 'TETRA', 0]\n\n        if fileformat == 'internal':\n            self._write_file_internal(3, filenames)\n        elif fileformat == 'pw-in':\n            self._write_file_pw_in(2, filenames)\n        elif fileformat == 'wannier-in':\n            self._write_file_wannier_in(2, filenames)\n        elif fileformat == 'vasp-kpt':\n            self._write_file_vasp_kpt(2, filenames)\n        elif fileformat == 'lapw-kpt':\n            self._write_file_lapw_kpt(2, filenames, lapwkunit) \n        elif fileformat == 'boltztrap-in':\n            self._write_file_boltztrap_in(3, filenames, boltzparam)\n        else:\n            raise ValueError(fileformat)\n\n    def __init__(\n            self, eunit = None, energy = None, efermi = None, vref = None,\n            **kwargs):\n        super().__init__(**kwargs)\n\n        if eunit is not None:\n            self.eunit = eunit\n        if energy is not None:\n            self.energy = energy\n        if efermi is not None:\n            self.efermi = efermi\n        if vref is not None:\n            self.vref = vref\n\n", "meta": {"hexsha": "79d838e00c1657f1c7c665fe3e1766d4da576d86", "size": 11345, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/brave/energy.py", "max_stars_repo_name": "mir-group/BRAVE", "max_stars_repo_head_hexsha": "45a870946661d7d76fcca273036b3004f21a49bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-11-03T03:28:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T21:22:03.000Z", "max_issues_repo_path": "src/brave/energy.py", "max_issues_repo_name": "mir-group/BRAVE", "max_issues_repo_head_hexsha": "45a870946661d7d76fcca273036b3004f21a49bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-28T08:41:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-28T08:41:21.000Z", "max_forks_repo_path": "src/brave/energy.py", "max_forks_repo_name": "mir-group/BRAVE", "max_forks_repo_head_hexsha": "45a870946661d7d76fcca273036b3004f21a49bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-20T19:27:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T19:27:33.000Z", "avg_line_length": 34.8006134969, "max_line_length": 80, "alphanum_fraction": 0.5676509476, "include": true, "reason": "import numpy", "num_tokens": 2996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.3140505449918074, "lm_q1q2_score": 0.16804794847778906}}
{"text": "'''\nA variety of useful functions that don't belong anywhere else.\n'''\nimport numpy as np\nimport astropy\nimport astropy.coordinates as coord\nimport pandas as pd\nfrom scipy.special import gamma, gammaincinv\n\n\ndef matchTables(table1, table2,\n                table1Ra = 'ra', table1Dec = 'dec', table1Unit = 'deg',\n                table2Ra = 'ra', table2Dec = 'dec', table2Unit = 'deg',\n                maxSep = None):\n    '''\n    Matches and joins two tables.  Modification of a code originally\n    written by Lee Kelvin.\n        Parameters\n        ----------\n        table1 : `astropy.table.table.Table` OR `pandas.core.frame.DataFrame`\n            First input table\n        table2 : `astropy.table.table.Table` OR `pandas.core.frame.DataFrame`\n        table1Ra : `string`\n            Right ascension key name in table1\n        table1Dec : `string`\n            Declination key name in table1\n        table1Unit : `string`\n            Unit of RA and Dec in table1 (for astropy.coordinates.coord.SkyCoord)\n        table2Ra : `string`\n            Right ascension key name in table2\n        table2Dec : `string`\n            Declination key name in table2\n        table2Unit : `string`\n            Unit of RA and Dec in table2 (for astropy.coordinates.coord.SkyCoord)   \n        maxSep : `float`\n            Maximum allowable separation for coordinate matches, in arcsec\n            To not cull selection based on this, set to None\n            \n        Yields\n        -------\n        res : `pandas.core.frame.DataFrame`\n            Concatenated, matched table combining table1 and table2\n    '''\n    if type(table1) is astropy.table.table.Table:\n        table1 = table1.to_pandas()\n    if type(table2) is astropy.table.table.Table:\n        table2 = table2.to_pandas()\n    table1 = pd.DataFrame(table1)\n    table2 = pd.DataFrame(table2)\n    \n    # Matching coordinates between tables\n    c1 = coord.SkyCoord(ra=table1[table1Ra], dec=table1[table1Dec], unit=table1Unit)\n    c2 = coord.SkyCoord(ra=table2[table2Ra], dec=table2[table2Dec], unit=table2Unit)\n    idx1, sep2d1, dist3d1 = coord.match_coordinates_sky(c1, c2)\n    table21 = table2.iloc[idx1,:]\n    \n    # Combining the matched tables\n    res = pd.concat([table1, table21.reset_index(drop=True)], axis=1, ignore_index=True, sort=False)\n    res.columns = table1.columns.to_list() + table21.columns.to_list()\n    res['sep2d'] = sep2d1.arcsec\n    res['idx'] = idx1\n    if maxSep is not None:\n        good = sep2d1.arcsec <= maxSep\n        res = res[good]\n        \n    return res\n\n\ndef findNearest(arr, val, tol):\n    '''\n    Finds the index in an array where the array value\n    matches the input value to some tolerance\n        Parameters\n        ----------\n        arr : `numpy.array`\n            Array in which to search for the value\n        val : `float`\n            Value to search for in the array\n        tol : `float`\n            Tolerance on success at finding the value\n            \n        Yields\n        -------\n        i : `int`\n            Index in arr where arr[i] is closest to val,\n            within linear tolerance tol\n    '''\n    i = -1\n    arr2 = -99\n    while (i < len(arr)-1) & (arr2 < (val-tol)):\n        i += 1\n        if arr[i] == -99:\n            arr2 = -99\n        else:\n            arr2 = arr[i]\n            \n    return i\n\n\ndef mkLogIm(image):\n    '''\n    Creates a logarithmically scaled version of an image\n    in the manner of DS9, showing also negative flux.\n    DO NOT USE FOR ANALYSIS!\n        Parameters\n        ----------\n        image : `numpy.array`\n            Image array (2D)\n            \n        Yields\n        -------\n        lgim : `numpy.array`\n            Log-scaled version of image, with negative values\n            replaced by positive ones\n    '''\n    lgim = np.log10(image)\n    lg2 = np.log10(-image)\n    lgim[np.isnan(lgim)] = lg2[np.isnan(lgim)]\n    \n    return lgim\n\n\n# =============================================================================\n# Sersic Profile Functions\n# =============================================================================\ndef bnn(n, frac):\n    '''\n    Derives Sersic bn parameter for given light fraction\n        Parameters\n        ----------\n        n : `float`\n            Sersic index\n        frac : `float`\n            Light fraction, e.g. 0.5\n        \n        Yields\n        -------\n        gammaincinv(2*n, frac) : `float`\n            Value of bn for given n and light fraction\n    '''\n    return gammaincinv(2*n, frac)\n\n\ndef getMuEff(mag, rEff, n):\n    '''\n    Derives effective surface brightnesses for a given\n    set of model parameters\n        Parameters\n        ----------\n        mag : `float`\n            Model magnitude\n        rEff : `float`\n            Model effective radius in arcsec\n        n : `float`\n            Model Sersic index\n            \n        Yields\n        -------\n        muEff : `float`\n            Surface brightness at the effective radius\n        muEffAv : `float`\n            Mean surface brightness within 1Reff\n    '''\n    fn = (n*np.exp(bnn(n, 0.5))*gamma(2*n))/(bnn(n, 0.5)**(2*n))\n    muEffAv = mag + 2.5*np.log10(2*np.pi*rEff**2)\n    muEff = muEffAv + 2.5*np.log10(fn)\n    \n    return muEff, muEffAv\n\n\ndef getSersicRadProf(mag, rEff, n, maxR, pxScale):\n    '''\n    Derives surface brightness profile for given parameters\n        Parameters\n        ----------\n        mag : `float`\n            Model magnitude\n        rEff : `float`\n            Model effective radius in arcsec\n        n : `float`\n            Model Sersic index\n        maxR : `float`\n            Maximum radius of model profile, in pixels\n        pxScale : `float`\n            Pixel scale to convert to arcseconds\n            \n        Yields\n        -------\n        rad : `numpy.array`\n            Radius array in arcseconds\n        muR : `numpy.array`\n            Surface brightness array out to maxR\n    '''\n    muEff, __ = getMuEff(mag, rEff, n)\n    bn = bnn(n, 0.5)\n    \n    rad = np.arange(0, maxR+1, 1)*pxScale\n    radPart = (rad/rEff)**(1/n) - 1\n    muR = muEff + ((2.5*bn)/np.log(10))*radPart\n    \n    return rad, muR\n", "meta": {"hexsha": "197f488159378f8d05f649149b0758ee96c49dee", "size": 6075, "ext": "py", "lang": "Python", "max_stars_repo_path": "measureMetrics/utility.py", "max_stars_repo_name": "lsst-uk/sky-estimation-WP3.7", "max_stars_repo_head_hexsha": "220da04556656497a50f5a6dd663f99fb374a917", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-15T02:20:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-31T23:57:41.000Z", "max_issues_repo_path": "measureMetrics/utility.py", "max_issues_repo_name": "lsst-uk/sky-estimation-WP3.7", "max_issues_repo_head_hexsha": "220da04556656497a50f5a6dd663f99fb374a917", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2020-06-19T14:20:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T11:30:56.000Z", "max_forks_repo_path": "measureMetrics/utility.py", "max_forks_repo_name": "lsst-uk/sky-estimation-WP3.7", "max_forks_repo_head_hexsha": "220da04556656497a50f5a6dd663f99fb374a917", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-29T00:15:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-29T00:15:57.000Z", "avg_line_length": 30.0742574257, "max_line_length": 100, "alphanum_fraction": 0.5450205761, "include": true, "reason": "import numpy,from scipy,import astropy", "num_tokens": 1525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.16804435520971364}}
{"text": "#!/usr/bin/env python\n\n\"\"\"\nMIT License\n\nCopyright (c) 2020-2021 Max Hallgarten La Casta\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nimport multiprocessing\nimport yaml\n\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom .astro_target import AstroTarget, AstroSubtarget\n\n\ndef load(spacecraft_frame, num_workers=None):\n    \"\"\"\n    Function to import targets and their subtargets.\n\n    Parameters\n    ----------\n    spacecraft_frame : astropy.coordinates.builtin_frames.gcrs.GCRS\n        Spacecraft reference frame relative to the Earth's geocentre\n        with the same orientation as BCRS/ICRS.\n    num_workers : int, optional\n        Number of workers for multiprocessing.\n\n    Raises\n    ------\n    ValueError\n        Error if targets file is empty, or if subtarget shape is invalid.\n\n    Returns\n    -------\n    targets : list\n        Targets and their properties.\n\n    \"\"\"\n\n    # Load targets from config file\n    # TODO: implement default and optional paths\n    with open(\"data/targets.yml\", \"r\") as targets_file:\n        targets_dump = yaml.safe_load(targets_file)\n\n    # Check for empty targets file\n    if targets_dump is None:\n        raise ValueError(\"Empty target file\")\n\n    # Create list of worker parameters\n    worker_params = [(target_dump, spacecraft_frame)\n                     for target_dump in targets_dump.items()]\n\n    # Generate target objects\n    # TODO: value checking\n    targets = []\n    # Create worker pool\n    with multiprocessing.Pool(num_workers) as p:\n        # Create progress bar\n        with tqdm(total=len(targets_dump), desc=\"Target Generation\") as pbar:\n            # Iterate through targets\n            for target in p.imap(load_worker, worker_params):\n                # Store in target list\n                targets.append(target)\n\n                # Update progress bar\n                pbar.update()\n    \n    # Return imported targets\n    return targets\n\n\ndef load_worker(worker_params):\n    \"\"\"\n    Worker function for loading targets.\n\n    Parameters\n    ----------\n    worker_params : tuple\n        Parameters for the worker including target information and the\n        spacecraft frame.\n\n    Raises\n    ------\n    ValueError\n        Error if the subtarget shape is invalid.\n\n    Returns\n    -------\n    target : AstroTarget\n        Target object containing its properties.\n\n    \"\"\"\n\n    # Extract worker params\n    target_dump, spacecraft_frame = worker_params\n\n    # Extract target name and info\n    target_name, target_info = target_dump\n\n    # Extract general properties\n    target_priority = target_info[\"priority\"]\n    target_category = target_info[\"category\"]\n\n    # Create empty target with general properties\n    target = AstroTarget(target_name, target_priority, target_category)\n\n    # Generate subtargets and add to target object\n    for subtarget_name, subtarget_info in target_info[\"subtargets\"].items():\n        # Import frame and coordinates\n        frame = subtarget_info[\"frame\"]\n        centre = subtarget_info[\"centre\"] * u.deg\n        original_coordinates = SkyCoord(centre[0], centre[1], frame=frame)\n\n        # Convert into ICRF and satellite frame\n        icrs_coordinates = original_coordinates.transform_to(\"icrs\")\n        coordinates = original_coordinates.transform_to(spacecraft_frame)\n\n        # Calculate subtarget geometry\n        shape = subtarget_info[\"shape\"]\n        if shape == \"rectangular\":\n            # Assign width and height\n            width = subtarget_info[\"width\"] * u.deg\n            height = subtarget_info[\"height\"] * u.deg\n            # Calculate bounding circle angular radius\n            angular_radius = 0.5*np.sqrt(width**2 + height**2)\n        elif shape == \"circular\":\n            # Assign nan width and height\n            width = np.nan\n            height = np.nan\n            # Assign angular\n            angular_radius = subtarget_info[\"angular_radius\"] * u.deg\n        else:\n            raise ValueError(f\"Invalid subtarget shape: {target_name}, {subtarget_name}\")\n\n        # Create subtarget object\n        subtarget = AstroSubtarget(subtarget_name,\n                                   frame,\n                                   centre,\n                                   shape,\n                                   width, height,\n                                   angular_radius,\n                                   coordinates,\n                                   icrs_coordinates)\n\n        # Add subtarget to target object\n        target.add_subtarget(subtarget)\n    \n    # Return imported target\n    return target\n\n\ndef save():\n    # TODO: implement method to save targets to file\n    pass\n", "meta": {"hexsha": "604a6465b663c8ddfd3b8f497c1d5b86bf32f2d6", "size": 5646, "ext": "py", "lang": "Python", "max_stars_repo_path": "assam/visibility/astro_target_interface.py", "max_stars_repo_name": "ykawashima/assam", "max_stars_repo_head_hexsha": "a2b0d315fd8b2ede392cdfcd372ff856fccdfde8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-10T10:02:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-26T00:48:33.000Z", "max_issues_repo_path": "assam/visibility/astro_target_interface.py", "max_issues_repo_name": "ykawashima/assam", "max_issues_repo_head_hexsha": "a2b0d315fd8b2ede392cdfcd372ff856fccdfde8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-25T03:35:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-26T09:09:39.000Z", "max_forks_repo_path": "assam/visibility/astro_target_interface.py", "max_forks_repo_name": "ykawashima/assam", "max_forks_repo_head_hexsha": "a2b0d315fd8b2ede392cdfcd372ff856fccdfde8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-25T23:50:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-29T06:18:25.000Z", "avg_line_length": 31.8983050847, "max_line_length": 89, "alphanum_fraction": 0.6544456252, "include": true, "reason": "import numpy,from astropy", "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.1679243972238212}}
{"text": "\"\"\".. copyright:: CERN\"\"\"\n\nimport numpy as np\nfrom scipy.constants import c\nfrom scipy.optimize import newton\nfrom scipy.integrate import dblquad\nfrom functools import partial, wraps\n\nfrom .curve_tools import zero_crossings as cvt_zero_crossings\n\nfrom functools import reduce\n\n\ndef attach_clean_buckets(rf_parameter_changing_method, rfsystems_instance):\n    '''Wrap an rf_parameter_changing_method (that changes relevant RF\n    parameters, i.e. Kick attributes). Needs to be an instance method,\n    presumably an RFSystems instance (hence the self argument in\n    cleaned_rf_parameter_changing_method).\n    In detail, attaches a call to the rfsystems_instance.clean_buckets\n    method after calling the wrapped function.\n    '''\n    @wraps(rf_parameter_changing_method)\n    def cleaned_rf_parameter_changing_method(self, *args, **kwargs):\n        res = rf_parameter_changing_method(*args, **kwargs)\n        rfsystems_instance.clean_buckets()\n        return res\n    return cleaned_rf_parameter_changing_method\n\n\nclass RFBucket:\n    \"\"\"Holds a blueprint of the current RF bucket configuration.\n    Should be requested via RFSystems.get_bucket(gamma).\n\n    Contains all information and all physical parameters of the\n    current longitudinal RF configuration for a (real, not macro-)\n    particle.\n\n    Use for plotting or obtaining the Hamiltonian etc.\n\n    Warning: zmin and zmax do not (yet) account for phi_offset of\n    Kick objects, i.e. the left and right side of the bucket are not\n    accordingly moved w.r.t. the harmonic phase offset.\n    \"\"\"\n\n    \"\"\"Sampling points to find zero crossings.\"\"\"\n    sampling_points = 1000\n\n    def __init__(self, circumference, gamma, mass_kg,\n                 charge_coulomb, alpha_array, p_increment,\n                 harmonic_list, voltage_list, phi_offset_list,\n                 z_offset=None, *args, **kwargs):\n        '''Implements only the leading order momentum compaction factor.\n\n        Arguments:\n        - mass_kg is the mass of the particle type in the beam\n        - charge_coulomb is the charge of the particle type in the beam\n        - z_offset determines the centre for the bucket interval\n        over which the root finding (of the electric force field to\n        calibrate the separatrix Hamiltonian value to zero) is done.\n        z_offset is per default determined by the zero crossing located\n        closest to z == 0.\n        '''\n\n        self.charge_coulomb = charge_coulomb\n        self.mass_kg = mass_kg\n\n        self._gamma = gamma\n        self._beta = np.sqrt(1 - gamma**-2)\n        self._p0 = np.sqrt(gamma**2 - 1) * mass_kg * c\n\n        self.alpha0 = alpha_array[0]\n        self.p_increment = p_increment\n\n        self.circumference = circumference\n        self.h = harmonic_list\n        self.V = voltage_list\n        self.dphi = phi_offset_list\n\n        \"\"\"Additional electric force fields to be added on top of the\n        RF electric force field.\n        \"\"\"\n        self._add_forces = []\n        \"\"\"Additional electric potential energies to be added on top\n        of the RF electric potential energy.\n        \"\"\"\n        self._add_potentials = []\n\n        zmax = self.circumference / (2*np.amin(self.h))\n\n        if z_offset is None:\n            # i_fund = np.argmin(self.h) # index of fundamental RF element\n            # phi_offset = self.dphi[i_fund]\n            # # account for bucket size between -pi and pi.\n            # # below transition there should be no relocation of the\n            # # bucket interval by an offset of pi! we only need relative\n            # # offset w.r.t. normal phi setting at given gamma (0 resp. pi)\n            # if self.eta0 < 0:\n            #     phi_offset -= np.pi\n            # z_offset = -phi_offset * self.R / self.h[i_fund]\n            ### the above approach does not take into account higher harmonics!\n            ### Within a 2 bucket length interval we find all zero crossings\n            ### of the non-accelerated total_force and identify the outermost\n            ### separatrix UFPs via their minimal (convexified) potential value\n            domain_to_find_bucket_centre = np.linspace(-1.999*zmax, 1.999*zmax,\n                                                       self.sampling_points)\n            z0 = self.zero_crossings(\n                partial(self.total_force, acceleration=False),\n                domain_to_find_bucket_centre)\n            convex_pot0 = (\n                np.array(self.total_potential(z0, acceleration=False)) *\n                np.sign(self.eta0) / self.charge_coulomb)  # charge for numerical reasons\n            outer_separatrix_pot0 = np.min(convex_pot0)\n            outer_separatrix_z0 = z0[np.isclose(convex_pot0,\n                                                outer_separatrix_pot0)]\n            # outer_separatrix_z0 should contain exactly 2 entries\n            z_offset = np.mean(outer_separatrix_z0)\n        self.z_offset = z_offset\n\n        \"\"\"Minimum and maximum z values on either side of the\n        stationary bucket to cover the maximally possible bucket area,\n        defined by the fundamental harmonic.\n        (This range is always larger than the outmost unstable fix\n        points of the real bucket including self.p_increment .)\n        \"\"\"\n        self.interval = (z_offset - 1.01*zmax, z_offset + 1.01*zmax)\n\n    @property\n    def gamma(self):\n        return self._gamma\n\n    @property\n    def beta(self):\n        return self._beta\n\n    @property\n    def p0(self):\n        return self._p0\n\n    @property\n    def deltaE(self):\n        return self.p_increment * self.beta * c\n\n    @property\n    def harmonic_list(self):\n        return self.h\n    @harmonic_list.setter\n    def harmonic_list(self, value):\n        self.h = value\n\n    @property\n    def voltage_list(self):\n        return self.V\n    @voltage_list.setter\n    def voltage_list(self, value):\n        self.V = value\n\n    @property\n    def phi_offset_list(self):\n        return self.dphi\n    @phi_offset_list.setter\n    def phi_offset_list(self, value):\n        self.dphi = value\n\n    @property\n    def z_ufp(self):\n        '''Return the (left-most) unstable fix point on the z axis\n        within self.interval .\n        '''\n        try:\n            return self._z_ufp\n        except AttributeError:\n            self._z_sfp, self._z_ufp = self._get_zsfp_and_zufp()\n            return self._z_ufp\n\n    @property\n    def z_sfp(self):\n        '''Return the (left-most) stable fix point on the z axis.\n        within self.interval .\n        '''\n        try:\n            return self._z_sfp\n        except AttributeError:\n            self._z_sfp, self._z_ufp = self._get_zsfp_and_zufp()\n            return self._z_sfp\n\n    @property\n    def z_ufp_separatrix(self):\n        '''Return the (left-most) unstable fix point at the outermost\n        separatrix of the bucket.\n        (i.e. a bucket boundary defining unstable fix point)\n        '''\n        if self.eta0 * self.p_increment > 0:\n            # separatrix ufp right of sfp\n            return self.z_ufp[-1]\n        else:\n            # separatrix ufp left of sfp\n            return self.z_ufp[0]\n\n    @property\n    def z_sfp_extr(self):\n        '''Return the (left-most) absolute extremal stable fix point\n        within the bucket.\n        '''\n        sfp_extr_index = np.argmax(self.hamiltonian(self.z_sfp, 0,\n                                                    make_convex=True))\n        return self.z_sfp[sfp_extr_index]\n\n    @property\n    def z_left(self):\n        '''Return the left bucket boundary within self.interval .'''\n        try:\n            return self._z_left\n        except AttributeError:\n            self._z_left, self._z_right, _ = self._get_bucket_boundaries()\n            return self._z_left\n\n    @property\n    def z_right(self):\n        '''Return the right bucket boundary within self.interval .'''\n        try:\n            return self._z_right\n        except AttributeError:\n            self._z_left, self._z_right, _ = self._get_bucket_boundaries()\n            return self._z_right\n\n    #@property\n    #@deprecated(\"--> Will become z_left.\\n\")\n    #def zleft(self):\n    #    '''Return the left bucket boundary within self.interval .'''\n    #    try:\n    #        return self._z_left\n    #    except AttributeError:\n    #        self._z_left, self._z_right, _ = self._get_bucket_boundaries()\n    #        return self._z_left\n\n    #@property\n    #@deprecated(\"--> Will become z_right.\\n\")\n    #def zright(self):\n    #    '''Return the right bucket boundary within self.interval .'''\n    #    try:\n    #        return self._z_right\n    #    except AttributeError:\n    #        self._z_left, self._z_right, _ = self._get_bucket_boundaries()\n    #        return self._z_right\n\n    @property\n    def R(self):\n        return self.circumference/(2*np.pi)\n\n    # should make use of eta functionality of LongitudinalMap at some point\n    @property\n    def eta0(self):\n        return self.alpha0 - self.gamma**-2\n\n    @property\n    def beta_z(self):\n        return np.abs(self.eta0 * self.R / self.Q_s)\n\n    #@property\n    #@deprecated('--> Use Q_s instead!')\n    #def Qs(self):\n    #    return self.Q_s\n\n    @property\n    def Q_s(self):\n        \"\"\"Linear synchrotron tune for small amplitudes i.e., in the\n        center of the bucket. Analytical formula neglects any\n        added forces / potentials via add_fields.\n        \"\"\"\n        hV = sum([h * self.V[i] for i, h in enumerate(self.h)])\n        # if hV == 0:\n        #     ix = np.argmax(self.V)\n        #     hV = self.h[ix] * self.V[ix]\n        return np.sqrt(self.charge_coulomb*np.abs(self.eta0)*hV /\n                       (2*np.pi*self.p0*self.beta*c))\n\n    def add_fields(self, add_forces, add_potentials):\n        '''Include additional (e.g. non-RF) effects to this RFBucket.\n        Use this interface for adding space charge influence etc.\n        to the bucket parameters and shape.\n\n        Arguments:\n        - add_forces are additional electric force fields to be added\n        on top of the RF electric force field.\n        add_forces is expected to be an iterable of functions of z,\n        in units of Coul*Volt/metre.\n        - add_potentials are additional electric potential energies\n        to be added on top of the RF electric potential energy.\n        add_potentials is expected to be an iterable of functions of z,\n        in units of Coul*Volt.\n\n        Bucket shape parameters z_ufp, z_sfp, z_left and z_right are\n        recalculated.\n        '''\n        self._add_forces += add_forces\n        self._add_potentials += add_potentials\n        try:\n            delattr(self, \"_z_ufp\")\n            delattr(self, \"_z_sfp\")\n        except AttributeError:\n            pass\n        try:\n            delattr(self, \"_z_left\")\n            delattr(self, \"_z_right\")\n        except AttributeError:\n            pass\n\n    # FORCE FIELDS AND POTENTIALS OF MULTI-HARMONIC ACCELERATING BUCKET\n    # =================================================================\n    def rf_force(self, V, h, dphi, p_increment, acceleration=True):\n        def f(z):\n            coefficient = np.abs(self.charge_coulomb)/self.circumference\n            focusing_field = reduce(lambda x, y: x+y, [\n                V_i * np.sin(h_i*z/self.R + dphi_i)\n                for V_i, h_i, dphi_i in zip(V, h, dphi)])\n            if not acceleration:\n                accelerating_field = 0\n            else:\n                accelerating_field = -(\n                    p_increment*self.beta*c/self.circumference)\n            return coefficient * focusing_field + accelerating_field\n        return f\n\n    def total_force(self, z, ignore_add_forces=False, acceleration=True):\n        '''Return the total electric force field including\n        - the acceleration offset and\n        - the additional electric force fields (provided via\n        self.add_nonRF_influences),\n        evaluated at position z in units of Coul*Volt/metre.\n        '''\n        f = (self.rf_force(self.V, self.h, self.dphi,\n                           self.p_increment, acceleration)(z) +\n             sum(f(z) for f in self._add_forces\n                 if not ignore_add_forces))\n        return f\n\n\n    #@deprecated('--> Replace with \"rf_force(acceleration=False)\" ' +\n    #            'as soon as possible.\\n')\n    #def make_singleharmonic_force(self, V, h, dphi):\n    #    '''Return the electric force field of a single harmonic\n    #    RF element as a function of z in units of Coul*Volt/metre.\n    #    '''\n    #    def force(z):\n    #        return (np.abs(self.charge_coulomb) * V / self.circumference *\n    #                np.sin(h * z / self.R + dphi))\n    #    return force\n\n    #@deprecated('--> Replace with \"total_force(acceleration=False)\" ' +\n    #            'as soon as possible.\\n')\n    #def make_total_force(self, ignore_add_forces=False):\n    #    '''Return the stationary total electric force field of\n    #    superimposed RF elements (multi-harmonics) as a function of z.\n    #    Parameters are taken from RF parameters of this\n    #    RFBucket instance.\n\n    #    Adds the additional electric force fields (provided via\n    #    self.add_nonRF_influences) on top.\n    #    Uses units of Coul*Volt/metre.\n    #    '''\n    #    def total_force(z):\n    #        '''Return stationary total electric force field of\n    #        superimposed RF elements (multi-harmonics) and additional\n    #        force fields as a function of z in units of Coul*Volt/metre.\n    #        '''\n    #        harmonics = (self.make_singleharmonic_force(V, h, dphi)(z)\n    #                     for V, h, dphi in zip(self.V, self.h, self.dphi))\n    #        return (sum(harmonics) + sum(f(z) for f in self._add_forces\n    #                                     if not ignore_add_forces))\n    #    return total_force\n\n    #@deprecated('--> Replace with \"total_force\" as soon as possible.\\n')\n    #def acc_force(self, z, ignore_add_forces=False):\n    #    '''Return the total electric force field including\n    #    - the acceleration offset and\n    #    - the additional electric force fields (provided via\n    #    self.add_nonRF_influences),\n    #    evaluated at position z in units of Coul*Volt/metre.\n    #    '''\n    #    total_force = self.make_total_force(\n    #        ignore_add_forces=ignore_add_forces)\n    #    return total_force(z) - self.deltaE / self.circumference\n\n\n    def rf_potential(self, V, h, dphi, p_increment,\n                     acceleration=True, offset=True):\n        '''Return the RF electric potential energy including the linear\n        acceleration slope (if acceleration == True).\n\n        Arguments:\n            - V: list of voltages for each harmonic\n            - h: list of harmonics\n            - dphi: list of phase offsets for each harmonic\n            - p_increment: momentum increase per turn\n            - acceleration: whether to superimpose the linear\n              acceleration slope (induced by p_increment, default=True)\n            - offset: boolean whether the potential energy should be\n              shifted to zero at the unstable fix point enclosing\n              the separatrix of the RF bucket (default=True).\n        '''\n        def vf(z):\n            coefficient = np.abs(self.charge_coulomb)/self.circumference\n            focusing_potential = reduce(lambda x, y: x+y, [\n                self.R/h[i] * V[i] * np.cos(h[i]*z/self.R + dphi[i])\n                for i in range(len(V))])\n            return coefficient * focusing_potential\n\n        if not acceleration:\n            return vf\n        else:\n            v_norm = 0 # normalisation shift\n            if offset:\n                zmax = self.z_ufp_separatrix\n                v_norm = (vf(zmax) +\n                          p_increment*self.beta*c/self.circumference * zmax)\n\n            def f(z):\n                return (vf(z) + p_increment*self.beta*c/self.circumference * z\n                        - v_norm)\n            return f\n\n    def total_potential(self, z, ignore_add_potentials=False,\n                        make_convex=False, acceleration=True, offset=True):\n        '''Return the total electric potential energy including\n        - the linear acceleration slope and\n        - the additional electric potential energies (provided via\n        self.add_nonRF_influences),\n        evaluated at position z in units of Coul*Volt.\n\n        Note:\n        Adds a potential energy offset: this relocates the extremum\n        (defining the unstable fix point UFP of the bucket)\n        to obtain zero potential energy at the UFP.\n        Thus the Hamiltonian value of the separatrix is calibrated\n        to zero.\n\n        Arguments:\n            - make_convex: multiplies by sign(eta) for plotting etc.\n              To see a literal 'bucket structure' in the sense of\n              always having a local maximum in the Hamiltonian topology\n              where the stable fix points are located, set\n              make_convex=True in order to return\n              sign(eta)*hamiltonian(z, dp).\n            - offset: boolean whether the potential energy should be\n              shifted to zero at the unstable fix point enclosing\n              the separatrix of the RF bucket (default=True).\n        '''\n        v = (self.rf_potential(self.V, self.h, self.dphi,\n                               self.p_increment, acceleration, offset)(z) +\n             sum(pot(z) for pot in self._add_potentials\n                 if not ignore_add_potentials))\n        if make_convex:\n            v *= np.sign(self.eta0)\n        return v\n\n    #@deprecated('--> Replace with \"rf_potential(acceleration=False)\" ' +\n    #            'as soon as possible.\\n')\n    #def make_singleharmonic_potential(self, V, h, dphi):\n    #    '''Return the electric potential energy of a single harmonic\n    #    RF element as a function of z in units of Coul*Volt.\n    #    '''\n    #    def potential(z):\n    #        return (np.abs(self.charge_coulomb) * V / (2 * np.pi * h) *\n    #                np.cos(h * z / self.R + dphi))\n    #    return potential\n\n    #@deprecated('--> Replace with ' +\n    #            '\"total_potential(acceleration=False)\" ' +\n    #            'as soon as possible.\\n')\n    #def make_total_potential(self, ignore_add_potentials=False):\n    #    '''Return the stationary total electric potential energy of\n    #    superimposed RF elements (multi-harmonics) as a function of z.\n    #    Parameters are taken from RF parameters of this\n    #    RFBucket instance.\n\n    #    Adds the additional electric potential energies\n    #    (provided via self.add_nonRF_influences) on top.\n    #    Uses units of Coul*Volt.\n    #    '''\n    #    def total_potential(z):\n    #        '''Return stationary total electric potential energy of\n    #        superimposed RF elements (multi-harmonics) and additional\n    #        electric potentials as a function of z\n    #        in units of Coul*Volt.\n    #        '''\n    #        harmonics = (self.make_singleharmonic_potential(V, h, dphi)(z)\n    #                     for V, h, dphi in zip(self.V, self.h, self.dphi))\n    #        return (sum(harmonics) + sum(pot(z) for pot in self._add_potentials\n    #                                     if not ignore_add_potentials))\n    #    return total_potential\n\n    #@deprecated('--> Replace with \"total_potential as soon as possible.\\n')\n    #def acc_potential(self, z, ignore_add_potentials=False,\n    #                  make_convex=False):\n    #    '''Return the total electric potential energy including\n    #    - the linear acceleration slope and\n    #    - the additional electric potential energies (provided via\n    #    self.add_nonRF_influences),\n    #    evaluated at position z in units of Coul*Volt.\n\n    #    Note:\n    #    Adds a potential energy offset: this relocates the extremum\n    #    (defining the unstable fix point UFP of the bucket)\n    #    to obtain zero potential energy at the UFP.\n    #    Thus the Hamiltonian value of the separatrix is calibrated\n    #    to zero.\n\n    #    Arguments:\n    #        - make_convex: multiplies by sign(eta) for plotting etc.\n    #          To see a literal 'bucket structure' in the sense of\n    #          always having a local maximum in the Hamiltonian topology\n    #          where the stable fix points are located, set\n    #          make_convex=True in order to return\n    #          sign(eta)*hamiltonian(z, dp).\n    #    '''\n    #    pot_tot = self.make_total_potential(\n    #        ignore_add_potentials=ignore_add_potentials)\n    #    z_boundary = self.z_ufp_separatrix\n    #    v_acc = (pot_tot(z) - pot_tot(z_boundary) +\n    #             self.deltaE / self.circumference * (z - z_boundary))\n    #    if make_convex:\n    #        v_acc *= np.sign(self.eta0)\n    #    return v_acc\n\n\n    # ROOT AND BOUNDARY FINDING ROUTINES\n    # ==================================\n    def zero_crossings(self, f, x=None, subintervals=None):\n        '''Determine roots of f along x.\n        If x is not explicitely given, take stationary bucket interval.\n        '''\n        if x is None:\n            if subintervals is None:\n                subintervals = self.sampling_points\n            x = np.linspace(*self.interval, num=subintervals)\n\n        return cvt_zero_crossings(f, x)\n\n    def _get_bucket_boundaries(self):\n        '''Return the bucket boundaries as well as the whole list\n        of acceleration voltage roots, (z_left, z_right, z_roots).\n        '''\n        z0 = np.atleast_1d(self.zero_crossings(self.total_potential))\n        z0 = np.append(z0, self.z_ufp)\n        return np.min(z0), np.max(z0), z0\n\n    def _get_zsfp_and_zufp(self):\n        '''Return (z_sfp, z_ufp),\n        where z_sfp is the z location of the stable fix points,\n        and z_ufp is the z location of the unstable fix points\n        belonging to this RF bucket.\n\n        A stationary RF bucket has the right-most UFP overlapping\n        with the adjacent RF bucket's separatrix, while for an\n        ac-/decelerating RF bucket one of the two out-most UFP always\n        belongs to the separatrix of the adjacent RF bucket. This UFP\n        will be discarded (although you find it with the zero crossing\n        of the total_force) by comparing the voltages between the\n        out-most UFP.\n        '''\n        z0 = np.atleast_1d(self.zero_crossings(self.total_force))\n\n        if not z0.size:\n            # no bucket (i.e. bucket area 'negative')\n            raise ValueError('With an electric force field this weak ' +\n                             'there is no bucket for such strong ' +\n                             'momentum increase -- ' +\n                             'why do you ask me for bucket boundaries ' +\n                             'in this hyperbolic phase space structure?!')\n\n        if len(z0) == 1:  # exactly zero bucket area\n            return z0, z0\n\n        V_left = self.total_potential(z0[0], make_convex=True, offset=False)\n        V_right = self.total_potential(z0[-1], make_convex=True, offset=False)\n\n        if self.eta0 * self.p_increment > 0:\n            # separatrix ufp right of sfp AND we are ac-/decelerating\n            if V_left < V_right:\n                # --> need to remove first ufp (belongs to bucket to the left)\n                z0 = z0[1:]\n            z_sfp, z_ufp = z0[::2], z0[1::2]\n        elif self.eta0 * self.p_increment == 0:\n            # stationary bucket, need both left and right UFP (overlapping!)\n            z_sfp, z_ufp = z0[1::2], z0[::2]\n        else:\n            # separatrix ufp left of sfp AND we are ac-/decelerating\n            if V_right < V_left:\n                # --> need to remove last ufp (belongs to bucket to the right)\n                z0 = z0[:-1]\n            z_sfp, z_ufp = z0[1::2], z0[::2]\n\n        return z_sfp, z_ufp\n\n    # HAMILTONIANS, SEPARATRICES AND RELATED FUNCTIONS\n    # ================================================\n    def hamiltonian(self, z, dp, make_convex=False):\n        '''Return the Hamiltonian at position z and dp in units of\n        Coul*Volt/p0.\n\n        Arguments:\n            - make_convex: multiplies by sign(eta) for plotting etc.\n              To see a literal 'bucket structure' in the sense of\n              always having a local maximum in the Hamiltonian topology\n              where the stable fix points are located, set\n              make_convex=True in order to return\n              sign(eta)*hamiltonian(z, dp).\n        '''\n        h = (-0.5 * self.eta0 * self.beta * c * dp**2 +\n             self.total_potential(z) / self.p0)\n        if make_convex:\n            h *= np.sign(self.eta0)\n        return h\n\n    def equihamiltonian(self, zcut):\n        '''Return a function dp_at that encodes the equi-Hamiltonian\n        contour line that cuts the z axis at (zcut, 0).\n        In more detail, dp_at(z) returns the (positive) dp value at\n        its given z argument such that\n        self.hamiltonian(z, dp_at(z)) == self.hamiltonian(zcut, 0) .\n        '''\n        def dp_at(z):\n            hcut = self.hamiltonian(zcut, 0)\n            r = np.abs(2./(self.eta0*self.beta*c) *\n                       (self.total_potential(z)/self.p0 - hcut))\n            return np.sqrt(r.clip(min=0))\n        return dp_at\n\n    def separatrix(self, z):\n        '''Return the positive dp value corresponding to the separatrix\n        Hamiltonian contour line at the given z.\n        '''\n        dp_separatrix_at = self.equihamiltonian(self.z_ufp_separatrix)\n        return dp_separatrix_at(z)\n\n    def h_sfp(self, make_convex=False):\n        '''Return the extremal Hamiltonian value at the corresponding\n        stable fix point (self.z_sfp_extr, 0) of the bucket.\n        '''\n        return self.hamiltonian(self.z_sfp_extr, 0, make_convex)\n\n    def dp_max(self, zcut):\n        '''Return the maximal dp value along the equihamiltonian which\n        is located at (one of the) self.z_sfp .\n        '''\n        dp_at = self.equihamiltonian(zcut)\n        return np.amax(dp_at(self.z_sfp))\n\n    def is_in_separatrix(self, z, dp, margin=0):\n        \"\"\"Return boolean whether the coordinate (z, dp) is located\n        strictly inside the separatrix of this bucket\n        (i.e. excluding neighbouring buckets).\n\n        If margin is different from 0, use the equihamiltonian\n        defined by margin*self.h_sfp instead of the separatrix.\n        (Use margin as a weighting factor in units of the Hamiltonian\n        value at the stable fix point to move from the separatrix\n        toward the extremal Hamiltonian value at self.z_sfp .)\n        \"\"\"\n        within_interval = np.logical_and(self.z_left < z, z < self.z_right)\n        within_separatrix = (self.hamiltonian(z, dp, make_convex=True) >\n                             margin * self.h_sfp(make_convex=True))\n        return np.logical_and(within_interval, within_separatrix)\n\n    def make_is_accepted(self, margin=0):\n        \"\"\"Return the function is_accepted(z, dp) definining the\n        equihamiltonian with a value of margin*self.h_sfp .\n        For margin 0, the returned is_accepted(z, dp) function is\n        identical to self.is_in_separatrix(z, dp).\n        \"\"\"\n        return partial(self.is_in_separatrix, margin=margin)\n\n    def emittance_single_particle(self, z=None, sigma=2):\n        \"\"\"The single particle emittance computed along a given\n        equihamiltonian line.\n        \"\"\"\n        if z is not None:\n            zl = -sigma * z\n            zr = +sigma * z\n            f = self.equihamiltonian(sigma * z)\n        else:\n            zl = self.z_left\n            zr = self.z_right\n            f = self.separatrix\n\n        Q, error = dblquad(lambda y, x: 1, zl, zr,\n                           lambda x: 0, f)\n\n        return Q * 2*self.p0/np.abs(self.charge_coulomb)\n\n    def bunchlength_single_particle(self, epsn_z, verbose=False):\n        \"\"\"The corresponding RMS bunch length computed from the single\n        particle emittance.\n        \"\"\"\n        def emittance_from_zcut(zcut):\n            emittance = self.emittance_single_particle(zcut)\n            if np.isnan(emittance):\n                raise ValueError\n\n            if verbose:\n                self.prints('... distance to target emittance: ' +\n                            '{:.4e}'.format(emittance-epsn_z))\n            return emittance - epsn_z\n\n        sigma = newton(emittance_from_zcut, 1)\n\n        return sigma\n\n    def guess_H0(self, var, from_variable='epsn', make_convex=True):\n        \"\"\"Pure estimate value of H_0 starting from a bi-Gaussian bunch\n        in a linear \"RF bucket\". Intended for use by iterative matching\n        algorithms in the generators module.\n        \"\"\"\n        # If Qs = 0, get the fundamental harmonic\n        hV = sum([h * V for h, V in zip(self.h, self.V)])\n        if hV == 0:\n            ix = np.argmax(self.V)\n            hV = self.h[ix] * self.V[ix]\n        Qs = np.sqrt(np.abs(self.charge_coulomb)*np.abs(self.eta0)*hV /\n                     (2*np.pi*self.p0*self.beta*c))\n        beta_z = np.abs(self.eta0 * self.R / Qs)\n\n        # to be replaced with something more flexible (add_forces etc.)\n        if from_variable == 'epsn':\n            epsn = var\n            z0 = np.sqrt(epsn/(4.*np.pi) * beta_z *\n                         np.abs(self.charge_coulomb)/self.p0)  # gauss approx.\n        elif from_variable == 'sigma':\n            z0 = var\n\n        h0 = self.beta*c * (z0/beta_z)**2\n        if make_convex:\n            h0 *= np.abs(self.eta0)\n        return h0\n", "meta": {"hexsha": "892c324a1200af25ed926d565207c89a06b479fe", "size": 29283, "ext": "py", "lang": "Python", "max_stars_repo_path": "xpart/longitudinal/rf_bucket.py", "max_stars_repo_name": "rdemaria/xpart", "max_stars_repo_head_hexsha": "35fe06eeb508991dfe1dd23685331f8347d0b603", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "xpart/longitudinal/rf_bucket.py", "max_issues_repo_name": "rdemaria/xpart", "max_issues_repo_head_hexsha": "35fe06eeb508991dfe1dd23685331f8347d0b603", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xpart/longitudinal/rf_bucket.py", "max_forks_repo_name": "rdemaria/xpart", "max_forks_repo_head_hexsha": "35fe06eeb508991dfe1dd23685331f8347d0b603", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8408163265, "max_line_length": 89, "alphanum_fraction": 0.5990847932, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.16792439245370017}}
{"text": "\"\"\"\n\"\"\"\nfrom jax import vmap as jvmap, jit as jjit\nfrom .photometry_kernels import _obs_flux_ssp, _calc_obs_mag_no_dimming, _calc_obs_mag\n\n_a = [None, 0, None, None, None]\n_b = [None, None, None, None, 0]\n_obs_flux_ssp_vmap = jjit(\n    jvmap(jvmap(jvmap(_obs_flux_ssp, in_axes=_b), in_axes=_a), in_axes=_a)\n)\n_calc_obs_mag_no_dimming_vmap = jjit(\n    jvmap(jvmap(jvmap(_calc_obs_mag_no_dimming, in_axes=_b), in_axes=_a), in_axes=_a)\n)\n\n_calc_obs_mag_no_dimming_vmap_singlemet = jjit(\n    jvmap(jvmap(_calc_obs_mag_no_dimming, in_axes=_b), in_axes=_a)\n)\n\n_c = [None, 0, None, None, None, None, None]\n_d = [None, None, None, None, 0, None, None]\n_e = [None, None, 0, 0, None, None, None]\n\n_calc_obs_mag_vmap = jjit(\n    jvmap(jvmap(jvmap(_calc_obs_mag, in_axes=_d), in_axes=_c), in_axes=_c)\n)\n\n_a = (*[None] * 4, 0, *[None] * 5)\n_calc_obs_mag_vmap_z = jjit(jvmap(_calc_obs_mag, in_axes=_a))\n\n_b = (None, 0, *[None] * 8)\n_calc_obs_mag_vmap_spec = jjit(jvmap(_calc_obs_mag, in_axes=_b))\n\n\n@jjit\ndef calc_obs_mag_history_singlegal(\n    wave_spec, lum_spec, wave_filter, trans_filter, z_obs, Om0, Ode0, w0, wa, h\n):\n    \"\"\"Calculate the history of the observed flux of a single galaxy\n    through a particular filter.\n\n    Parameters\n    ----------\n    wave_spec_rest : ndarray of shape (n_wave_spec, )\n        Rest-frame wavelengths of the spectrum\n\n    lum_spec : ndarray of shape (n_wave_spec, )\n        Spectrum of each galaxy in Lsun/Hz\n\n    wave_filter : ndarray of shape (n_wave_filter, )\n        Wave length of the filter transmission curve\n\n    trans_filter : ndarray of shape (n_wave_filter, )\n        Fraction of the incident flux transmitted through the filter\n\n    z_obs : ndarray of shape (n_obs, )\n        Array of redshifts of the observed galaxies\n\n    Om0: float\n        Omega matter at z=0\n\n    Ode0: float\n        Omega DE at z=0\n\n    w0 : float\n        DE eqn of state today\n\n    wa : float\n        DE eqn of state deriv\n\n    h : float\n        Little h\n\n    Returns\n    -------\n    obs_mags : ndarray of shape (n_obs, )\n\n    \"\"\"\n    obs_mags = _calc_obs_mag_vmap_z(\n        wave_spec, lum_spec, wave_filter, trans_filter, z_obs, Om0, Ode0, w0, wa, h\n    )\n    return obs_mags\n\n\n@jjit\ndef calc_obs_mags_galpop(\n    wave_spec, lum_spec, wave_filter, trans_filter, z_obs, Om0, Ode0, w0, wa, h\n):\n    \"\"\"Calculate the history of the observed flux of a galaxy population\n    at a single redshift observed through a particular filter.\n\n    Parameters\n    ----------\n    wave_spec_rest : ndarray of shape (n_wave_spec, )\n        Rest-frame wavelengths of the spectrum\n\n    lum_spec : ndarray of shape (n_gals, n_wave_spec)\n        Spectrum of each galaxy in Lsun/Hz\n\n    wave_filter : ndarray of shape (n_wave_filter, )\n        Wave length of the filter transmission curve\n\n    trans_filter : ndarray of shape (n_wave_filter, )\n        Fraction of the incident flux transmitted through the filter\n\n    z_obs : float\n        Redshift of the observed galaxies\n\n    Om0: float\n        Omega matter at z=0\n\n    Ode0: float\n        Omega DE at z=0\n\n    w0 : float\n        DE eqn of state today\n\n    wa : float\n        DE eqn of state deriv\n\n    h : float\n        Little h\n\n    Returns\n    -------\n    obs_mags : ndarray of shape (n_gals, )\n\n    \"\"\"\n    obs_mags = _calc_obs_mag_vmap_spec(\n        wave_spec, lum_spec, wave_filter, trans_filter, z_obs, Om0, Ode0, w0, wa, h\n    )\n    return obs_mags\n", "meta": {"hexsha": "63c3cb24261210c147c85a6f54d4884e23f1e09e", "size": 3402, "ext": "py", "lang": "Python", "max_stars_repo_path": "dsps/photometry.py", "max_stars_repo_name": "ArgonneCPAC/dsps", "max_stars_repo_head_hexsha": "a08da74cf9df4b12197805531d0b273d98ed5da6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2021-12-13T20:10:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T17:58:06.000Z", "max_issues_repo_path": "dsps/photometry.py", "max_issues_repo_name": "ArgonneCPAC/dsps", "max_issues_repo_head_hexsha": "a08da74cf9df4b12197805531d0b273d98ed5da6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dsps/photometry.py", "max_forks_repo_name": "ArgonneCPAC/dsps", "max_forks_repo_head_hexsha": "a08da74cf9df4b12197805531d0b273d98ed5da6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-14T08:04:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T08:04:42.000Z", "avg_line_length": 25.7727272727, "max_line_length": 86, "alphanum_fraction": 0.6660787772, "include": true, "reason": "from jax", "num_tokens": 1015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3208212878370535, "lm_q1q2_score": 0.1679243904258714}}
{"text": "from __future__ import print_function, division\n\n# Still to implement:\n# - Performance monitoring\n# - Remove resolved models\n# - Optional FITS input/output\n# - Output convolved fluxes\n\nimport numpy as np\nfrom astropy import units as u\n\nfrom . import timer\n\nfrom .models import Models\nfrom .source import Source\nfrom .utils import io\nfrom .utils.validator import validate_array\nfrom . import six\nfrom .fit_info import FitInfoFile\n\n\nclass Fitter(object):\n    \"\"\"\n    A fitter class that can be used to fit sources.\n\n    This class is initialized using a particular set of models, and with\n    specific fit parameters. It can then be used to fit data given by Source\n    instances, and returns a FitInfo instance. Once initialized, the fit\n    parameters cannot be changed, because changing most of them would require\n    re-reading the models from disk.\n\n    Parameters\n    ----------\n    filter_names : tuple or list\n        List of filter names (given as individual strings) for which the data\n        is defined. The filter names should be the name of the files in the\n        ``convolved`` directory for the models, without the extensions. This is\n        typically ``2J``, ``I1``, ``M1``, etc. You can also specify the\n        wavelength as a :class:`~astropy.units.quantity.Quantity` instance\n        instead of a filter name, and this will indicate that the SED fluxes\n        closest to the requested wavelength should be used in the fitting.\n    apertures : :class:`~astropy.units.quantity.Quantity` array instance\n        The aperture radii that the data is specified in (as an angle). The\n        fluxes may not be measured from aperture photometry, but this is meant\n        to give an indication of the sizescale of the emission, and can be used\n        to reject models that would have been clearly resolved at the distance\n        specified.\n    models_dir : str\n        Name of the directory containing the models to use.\n    extinction_law : :class:`~sedfitter.extinction.Extinction` instance\n        The extinction law to use.\n    av_range : tuple\n        Minimum and maximum Av to allow in the fitting.\n    distance_range : :class:`~astropy.units.quantity.Quantity` array instance\n        Minimum and maximum distance to allow in the fitting in units of length.\n    remove_resolved : bool, optional\n        If set, then models larger than the aperture are removed. See\n        Robitaille et al. (2007) for a discussion of this criterion.\n    \"\"\"\n\n    def __init__(self, filter_names, apertures, model_dir,\n                 extinction_law=None, av_range=None, distance_range=None,\n                 remove_resolved=False):\n\n        validate_array('apertures', apertures, domain='positive', ndim=1, physical_type='angle')\n        validate_array('distance_range', distance_range, domain='positive', ndim=1, shape=(2,), physical_type='length')\n\n        if len(apertures) != len(filter_names):\n            raise ValueError(\"length of apertures list should match length of filter names list\")\n\n        # Construct filters dictionary\n        self.filters = []\n        for i in range(len(apertures)):\n            filt = {'aperture_arcsec': apertures[i].to(u.arcsec).value}\n            if isinstance(filter_names[i], six.string_types):\n                filt['name'] = filter_names[i]\n            elif isinstance(filter_names[i], u.Quantity):\n                filt['wav'] = filter_names[i]\n            else:\n                raise ValueError(\"filter should be a string or a Quantity\")\n\n            self.filters.append(filt)\n\n        # Read in models\n        self.models = Models.read(model_dir, self.filters, distance_range=distance_range, remove_resolved=remove_resolved)\n\n        # Add wavelength to filters\n        for i, f in enumerate(self.filters):\n            if 'wav' not in f:\n                f['wav'] = self.models.wavelengths[i]\n\n        # Set Av law\n        self.av_law = extinction_law.get_av(self.models.wavelengths)\n\n        # Set scale model - make this a scalar\n        self.sc_law = -2. * np.ones(self.av_law.shape)\n\n        self.model_dir = model_dir\n        self.av_range = av_range\n        self.extinction_law = extinction_law\n\n    def fit(self, source):\n        \"\"\"\n        Fit the specified source.\n\n        Parameters\n        ----------\n        source : `~sedfitter.source.Source`\n            The source to fit.\n\n        Returns\n        -------\n        fit_info : `sedfitter.fit_info.FitInfo`\n            The results of the fit.\n        \"\"\"\n\n        info = self.models.fit(source, self.av_law, self.sc_law,\n                               self.av_range[0], self.av_range[1])\n\n        info.meta.model_dir = self.model_dir\n        info.meta.filters = self.filters\n        info.meta.extinction_law = self.extinction_law\n\n        return info\n\n\ndef fit(data, filter_names, apertures, model_dir, output, n_data_min=3,\n        extinction_law=None, av_range=None, distance_range=None,\n        output_format=('F', 6.), output_convolved=False,\n        remove_resolved=False):\n    \"\"\"\n    Fit a set of sources with models.\n\n    Parameters\n    ----------\n    data : str\n        Filename of the file containing the data, one source per line (see\n        documentation for a description of the required format).\n    filter_names : tuple or list\n        List of filter names (given as individual strings) for which the data\n        is defined. The filter names should be the name of the files in the\n        ``convolved`` directory for the models, without the extensions. This is\n        typically ``2J``, ``I1``, ``M1``, etc. You can also specify the\n        wavelength as a :class:`~astropy.units.quantity.Quantity` instance\n        instead of a filter name, and this will indicate that the SED fluxes\n        closest to the requested wavelength should be used in the fitting.\n    apertures : :class:`~astropy.units.quantity.Quantity` array instance\n        The aperture radii that the data is specified in (as an angle). The\n        fluxes may not be measured from aperture photometry, but this is meant\n        to give an indication of the sizescale of the emission, and can be used\n        to reject models that would have been clearly resolved at the distance\n        specified.\n    models_dir : str\n        Name of the directory containing the models to use.\n    output : str\n        Name of the file to output the fit information to (in binary format).\n    extinction_law : :class:`~sedfitter.extinction.Extinction` instance\n        The extinction law to use.\n    av_range : tuple\n        Minimum and maximum Av to allow in the fitting.\n    distance_range : :class:`~astropy.units.quantity.Quantity` array instance\n        Minimum and maximum distance to allow in the fitting in units of length.\n    n_data_min : int, optional\n        The minimum number of points a source needs to be fit.\n    output_format : tuple, optional\n        Tuple specifying which fits should be output. See the documentation\n        for a description of the tuple syntax.\n    output_convolved : bool, optional\n        Whether to output the convolved fluxes (necessary if the convolved\n        model fluxes are needed for the SED plot).\n    remove_resolved : bool, optional\n        If set, then models larger than the aperture are removed. See\n        Robitaille et al. (2007) for a discussion of this criterion.\n    \"\"\"\n\n    fitter = Fitter(filter_names, apertures, model_dir,\n                    extinction_law=extinction_law, av_range=av_range,\n                    distance_range=distance_range,\n                    remove_resolved=remove_resolved)\n\n    print(\" ------------------------------------------------------------\")\n    print(\"  => Fitting parameters\")\n    print(\" ------------------------------------------------------------\")\n    print(\"\")\n    print(\"   Minimum A_V      : %9.3f mag\" % av_range[0])\n    print(\"   Maximum A_V      : %9.3f mag\" % av_range[1])\n    print(\"   Minimum distance : %9.3f %s\" % (distance_range[0].value, distance_range.unit))\n    print(\"   Maximum distance : %9.3f %s\" % (distance_range[1].value, distance_range.unit))\n    print(\"\")\n    print(\" ------------------------------------------------------------\")\n    print(\"  => Output parameters\")\n    print(\" ------------------------------------------------------------\")\n    print(\"\")\n    print(\"   File   : %s\" % output)\n    print(\"   Format : %s\" % output_format[0])\n    print(\"   Number : %g\" % output_format[1])\n    print(\"\")\n    print(\" ------------------------------------------------------------\")\n    print(\"  => Data format parameters\")\n    print(\" ------------------------------------------------------------\")\n    print(\"\")\n    print(\"   Number of filters :  %i\" % len(filter_names))\n    print(\"\")\n\n    # Open datafile\n    if isinstance(data, six.string_types):\n        data_file = open(data, 'r')\n    else:\n        data_file = data\n\n    print('')\n    print('     Filter    Wavelength    Aperture (\")   ')\n    print('    ----------------------------------------')\n    for f in fitter.filters:\n        print('       %5s   %9.2f  %9.2f        ' % (f.get('name', ''), f['wav'].to(u.micron).value, f['aperture_arcsec']))\n    print('')\n\n    # Cycle through sources\n\n    io.delete_file(output)\n\n    fout = FitInfoFile(output, 'w')\n\n    s = Source()\n\n    t = timer.Timer()\n\n    while True:\n\n        try:\n            s = Source.from_ascii(data_file.readline())\n        except EOFError:\n            break\n\n        if s.n_data >= n_data_min:\n\n            info = fitter.fit(s)\n\n            if not output_convolved:\n                info.model_fluxes = None\n\n            info.keep(output_format)\n\n            fout.write(info)\n\n            t.display()\n\n    t.display(force=True)\n\n    fout.close()\n", "meta": {"hexsha": "9ff5c30eaeb746ae33deb28f9a6afbbc7cf803de", "size": 9676, "ext": "py", "lang": "Python", "max_stars_repo_path": "sedfitter/fit.py", "max_stars_repo_name": "KainRasleafar/sedfitter", "max_stars_repo_head_hexsha": "4f0e9e46f7903a853166835bb74857cc15eef219", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2015-07-04T02:00:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T09:03:10.000Z", "max_issues_repo_path": "sedfitter/fit.py", "max_issues_repo_name": "KainRasleafar/sedfitter", "max_issues_repo_head_hexsha": "4f0e9e46f7903a853166835bb74857cc15eef219", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 45, "max_issues_repo_issues_event_min_datetime": "2015-04-27T20:19:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T06:24:31.000Z", "max_forks_repo_path": "sedfitter/fit.py", "max_forks_repo_name": "KainRasleafar/sedfitter", "max_forks_repo_head_hexsha": "4f0e9e46f7903a853166835bb74857cc15eef219", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2015-04-21T15:32:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T21:53:46.000Z", "avg_line_length": 38.5498007968, "max_line_length": 123, "alphanum_fraction": 0.6140967342, "include": true, "reason": "import numpy,from astropy", "num_tokens": 2131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.16791437864915124}}
{"text": "# -*- coding:utf-8 -*-\n\"\"\"\"\n生成整个模型回归目标的真实答案用来参与损失函数的计算来迭代模型\n    1. 采用facal loss，所有的anchor都参与到分类中，但是会考虑到正负样本的不均衡和难易样本的不均衡\n    2. 实验facal loss的效果：\n\"\"\"\nimport numpy as np\nimport numpy.random as npr\nimport tensorflow as tf\nfrom lib.rpn_msr.generate_anchors import generate_anchors\nfrom lib.utils.bbox import bbox_overlaps, bbox_intersections\nfrom lib.fast_rcnn.config import cfg\nfrom lib.fast_rcnn.bbox_transform import bbox_transform\nimport math\n\nDEBUG = False\nSHOW_SOME = False\n\n\ndef split_frame(gt_boxes):\n    gt_boxes = gt_boxes.astype(np.int32)\n    list_box = list()\n    for i in range(gt_boxes.shape[0]):\n        list_box.append(gt_boxes[i][:])\n    list_fine_box = list()\n    for box in list_box:\n        xmin, ymin, xmax, ymax = box[0], box[1], box[2], box[3]\n        width = xmax - xmin\n        height = ymax - ymin\n\n        # reimplement\n        step = 16.0\n        x_left = []\n        x_right = []\n        x_left.append(xmin)\n        x_left_start = int(math.ceil(xmin / 16.0) * 16.0)\n        if x_left_start == xmin:\n            x_left_start = xmin + 16\n        for i in np.arange(x_left_start, xmax, 16):\n            x_left.append(i)\n        x_left = np.array(x_left)\n\n        x_right.append(x_left_start - 1)\n        for i in range(1, len(x_left) - 1):\n            x_right.append(x_left[i] + 15)\n        x_right.append(xmax)\n        x_right = np.array(x_right)\n\n        idx = np.where(x_left == x_right)\n        x_left = np.delete(x_left, idx, axis=0)\n        x_right = np.delete(x_right, idx, axis=0)\n\n        for i in range(len(x_left)):\n            list_fine_box.append([x_left[i], ymin, x_right[i], ymax, 1])\n\n    gt_boxes = np.array(list_fine_box).astype(np.float32)\n    return gt_boxes\n\n\ndef anchor_target_layer(rpn_cls_score, rpn_cls_prob, im_name, gt_boxes_large, gt_ishard, dontcare_areas, im_info, _feat_stride = [16,], anchor_scales = [16,]):\n    \"\"\"\n    将gt_box划分为细框\n    实现论文中的side-refinement\n    arameters\n    ----------\n    rpn_cls_score: (1, H, W, Ax2) bg/fg scores of previous conv layer\n    gt_boxes: (G, 5) vstack of [x1, y1, x2, y2, class]\n    gt_ishard: (G, 1), 1 or 0 indicates difficult or not\n    dontcare_areas: (D, 4), some areas may contains small objs but no labelling. D may be 0\n    im_info: a list of [image_height, image_width, scale_ratios]\n    _feat_stride: the downsampling ratio of feature map to the original input image\n    anchor_scales: the scales to the basic_anchor (basic anchor is [16, 16])\n    ----------\n    :return:\n    \"\"\"\n    gt_boxes = split_frame(gt_boxes_large)\n    _anchors = generate_anchors(scales=np.array(anchor_scales))  # 生成基本的anchor,一共9个\n    _num_anchors = _anchors.shape[0]  # 9个anchor\n\n    if DEBUG:\n        print('anchors:')\n        print(_anchors)\n        print('anchor shapes:')\n        print(np.hstack((\n            _anchors[:, 2::4] - _anchors[:, 0::4],\n            _anchors[:, 3::4] - _anchors[:, 1::4],\n        )))\n        _counts = cfg.EPS\n        _sums = np.zeros((1, 4))\n        _squared_sums = np.zeros((1, 4))\n        _fg_sum = 0\n        _bg_sum = 0\n        _count = 0\n\n    # allow boxes to sit over the edge by a small amount\n    _allowed_border = 0\n\n    im_info = im_info[0]  # 图像的高宽及通道数\n\n    assert rpn_cls_score.shape[0] == 1, \\\n        'Only single item batches are supported'\n\n    # map of shape (..., H, W)\n    height, width = rpn_cls_score.shape[1:3]  # feature-map的高宽\n\n    if DEBUG:\n        print('AnchorTargetLayer: height', height, 'width', width)\n        print('')\n        print('im_size: ({}, {})'.format(im_info[0], im_info[1]))\n        print('scale: {}'.format(im_info[2]))\n        print('height, width: ({}, {})'.format(height, width))\n        print('rpn: gt_boxes.shape', gt_boxes.shape)\n\n    # 1. Generate proposals from bbox deltas and shifted anchors\n    shift_x = np.arange(0, width) * _feat_stride  # (W)\n    shift_y = np.arange(0, height) * _feat_stride  # (H)\n    shift_x, shift_y = np.meshgrid(shift_x, shift_y)  # in W H order   # shift_x (H, W)  shift_y (H, W)\n\n    # K is H x W\n    shifts = np.vstack((shift_x.ravel(), shift_y.ravel(),\n                        shift_x.ravel(),\n                        shift_y.ravel())).transpose()  # 生成feature-map和真实image上anchor之间的偏移量     #(H*W, 4)\n    # add A anchors (1, A, 4) to\n    # cell K shifts (K, 1, 4) to get\n    # shift anchors (K, A, 4)\n    # reshape to (K*A, 4) shifted anchors\n    A = _num_anchors  # 9个anchor\n    K = shifts.shape[0]  # 50*37，feature-map的宽乘高的大小\n    all_anchors = (_anchors.reshape((1, A, 4)) +\n                   shifts.reshape((1, K, 4)).transpose((1, 0, 2)))  # 相当于复制宽高的维度，然后相加\n    all_anchors = all_anchors.reshape((K * A, 4))\n    total_anchors = int(K * A)\n\n    # only keep anchors inside the image\n    # 仅保留那些还在图像内部的anchor，超出图像的都删掉\n    inds_inside = np.where(\n        (all_anchors[:, 0] >= -_allowed_border) &\n        (all_anchors[:, 1] >= -_allowed_border) &\n        (all_anchors[:, 2] < im_info[1] + _allowed_border) &  # width\n        (all_anchors[:, 3] < im_info[0] + _allowed_border)  # height\n    )[0]\n\n    if DEBUG:\n        print('total_anchors', total_anchors)\n        print('inds_inside', len(inds_inside))\n\n    # keep only inside anchors\n    anchors = all_anchors[inds_inside, :]  # 保留那些在图像内的anchor   (In, 4)\n    if DEBUG:\n        print('anchors.shape', anchors.shape)\n\n    # 至此，anchor准备好了\n    # --------------------------------------------------------------\n    # label: 1 is positive, 0 is negative, -1 is dont care\n    # (A)\n    labels = np.empty((len(inds_inside),), dtype=np.float32)\n    labels.fill(-1)  # 初始化label，均为-1\n\n    # overlaps between the anchors and the gt boxes\n    # overlaps (ex, gt), shape is A x G\n    # 计算anchor和gt-box的overlap，用来给anchor上标签\n    overlaps = bbox_overlaps(\n        np.ascontiguousarray(anchors, dtype=np.float),\n        np.ascontiguousarray(gt_boxes, dtype=np.float))  # 假设anchors有x个，gt_boxes有y个，返回的是一个（x,y）的数组\n    # 存放每一个anchor和每一个gtbox之间的overlap\n    argmax_overlaps = overlaps.argmax(axis=1)  # (A)#找到和每一个anchor，overlap最大的那个gt\n    max_overlaps = overlaps[\n        np.arange(len(inds_inside)), argmax_overlaps]  # 假如在内部的anchor有900个 ，(900,), 表示的是每一个anchor最大的overlaps值\n    gt_argmax_overlaps = overlaps.argmax(axis=0)  # G#找到所有anchor中与gtbox，overlap最大的那个anchor  # (3)\n\n    gt_max_overlaps = overlaps[gt_argmax_overlaps,\n                               np.arange(\n                                   overlaps.shape[\n                                       1])]  # 比如有3个gt 那么就得到(3,),表示的是上一步找到的与gt的overlap最大的3个anchor的overlap值\n    gt_argmax_overlaps = np.where(overlaps == gt_max_overlaps)[0]  # (3, ) 表示的是哪几个与gt有最大overlap的anchor的索引\n\n    # fg label: for each gt, anchor with highest overlap\n    labels[gt_argmax_overlaps] = 1  # 每个位置上的9个anchor中overlap最大的认为是前景\n\n    # 是将iou小于0.5的样本标记为负样本，\n    if cfg.TRAIN.RPN_CLOBBER_POSITIVES:\n        # assign bg labels last so that negative labels can clobber positives\n        labels[max_overlaps < cfg.TRAIN.RPN_NEGATIVE_OVERLAP] = 0\n\n    # fg label: above threshold IOU\n    labels[max_overlaps >= cfg.TRAIN.RPN_POSITIVE_OVERLAP] = 1  # overlap大于0.7的认为是前景\n\n    # 增加的修复，负样本包含了最上方最下方有字的部分，这些样本会干扰样本，因此可以去掉这些负样本中，处在最上方的和左下方的样本\n    bg_anchor_index = labels == 0\n\n    y_anchor = anchors[:, 3]\n    top_anchor_index = y_anchor < min(anchors[:, 1]) + 50\n    bottom_anchor_index = y_anchor > max(anchors[:, 3]) - 50\n    assert  top_anchor_index.shape == bottom_anchor_index.shape\n    top_bottom_anchor_index = top_anchor_index + bottom_anchor_index\n    bg_topbottom_anchor_index = bg_anchor_index * top_bottom_anchor_index\n\n    labels[bg_topbottom_anchor_index] = -1\n\n    # 可视化这时候的正样本，看一下是怎样的\n    # vis_labels = _unmap(labels, total_anchors, inds_inside, fill=-1)  # 这些anchor的label是-1，也即dontcare\n    # vis_training_sample(vis_labels, all_anchors, im_name, gt_boxes)\n\n    if DEBUG:\n        print('在过滤数量之前：')\n        print('正样本：' + str(len(np.where(labels == 1)[0])))\n        print('负样本：' + str(len(np.where(labels == 0)[0])))\n        print('忽略样本：' + str(len(np.where(labels == -1)[0])))\n\n    # 至此，第一次生成好了这个图片的labels，\n    # 生成其他部分的标签\n    v_target, o_target = _compute_targets(anchors,\n                                          gt_boxes[argmax_overlaps, :])  # 根据anchor和gtbox计算得真值（anchor和gtbox之间的偏差）\n\n    # 但是计算损失函数的时候，其实是需要j索引和k索引，所以计算好这两个索引，一并返回，帮助计算损失函数\n    # j索引，有效索引：正锚点或者与gt的overlap大于0.5以上的锚点的索引\n    # 正锚点\n    positive_index = np.where(labels == 1)[0]  # 应该是一个（p,）p应该不大于128\n\n    #\n    # ignore_index = np.where(labels==-1)[0]  # 应该是一个（n,）n应该很大，因为忽略的anchor很多\n    keep_index = np.where(labels != -1)[0]\n    _ = np.where(max_overlaps > 0.5)[0]  # 应该是一个（c,）,表示overlap大于0.5的anchor的索引\n\n    remove_ignore = list()\n    for i in range(_.shape[0]):\n        if i in keep_index:\n            remove_ignore.append(_[i])\n    remove_ignore = np.array(remove_ignore)\n    effect_index = np.append(positive_index, remove_ignore)\n\n    remove_repeat = np.array(list(set(list(effect_index))))\n\n    j_index = remove_repeat.astype(np.int32)\n\n    j_index1 = np.zeros((len(inds_inside)), dtype=np.int32)\n    j_index1[j_index] = 1\n\n    # k 索引 , 边缘索引\n\n    # 先找到所有的可以认为是边缘的gt框,这里简单的认为是边缘框和左右各自一个。\n    # ori_gt_box = (gt_boxes/im_info[2]).astype(np.int32, copy=False)\n    ori_gt_box = gt_boxes.astype(np.float32, copy=False)\n    # 找到左右边界框，矩阵操作实现  todo\n    list_left_index = list()\n    list_right_index = list()\n    for i in range(ori_gt_box.shape[0]):\n        if ori_gt_box[i][2] - ori_gt_box[i][0] != 15:\n            list_left_index.append(i)\n            if ori_gt_box[i][0]%16 != 0:  # 看做是左边边界框\n                list_left_index.append(i+1)\n            if (ori_gt_box[i][2]+1)%16 != 0:  # 看做是右边边界框\n                list_left_index.append(i - 1)\n        else:\n            continue\n    list_index1 = list_left_index + list_right_index\n    # 去除不属于gt中的索引和重复的索引\n    list_index2 = list(set(list_index1))\n    list_index3 = sorted(list_index2)\n    list_index4 = list()\n    for index in list_index3:\n        if index in range(ori_gt_box.shape[0]):\n            list_index4.append(index)\n\n    gt_side_index = np.array(list_index4).astype(np.int32)  # 得到了边界gt框的索引\n\n    # 要得到与这些gt框有最大的overlap的anchors的索引，这些anchor是我们关心的\n    gt_argmax_overlaps = overlaps.argmax(axis=0)\n    anchor_side_index = gt_argmax_overlaps[gt_side_index]  # 得到143个与gt具有最大的overlaps的anchor的索引\n    # 还要去掉与边界框overlap为0的anchor，因为这些anhcor不是真的我们关心的anchor，如果不去除，还会造成o_loss异常大\n    # anchor_side_list = list()\n    anchor_fg_side_list = list()\n    anchor_nocare_side_list = list()\n    for i in range(anchor_side_index.shape[0]):\n        anchor_index = anchor_side_index[i]\n        gt_index = gt_side_index[i]\n        overlap = overlaps[anchor_index, gt_index]\n        if overlap > 0.05:\n            anchor_fg_side_list.append(anchor_index)\n        elif overlap>0:\n            anchor_nocare_side_list.append(anchor_index)\n        else:\n            pass\n    # 找到了与所有边界框有最大交集的anchor，这些anchor中有的与gt的iou只有很小（因为gt特别窄，不够16像素），所以这些anchor我们标记为-1，意思是模型将之识别为什么我们都不关心了，但是iou大于0.4的，我们都将之标记为正样本，另模型能够正确学习正负样本\n    anchor_fg_side_index = np.array(anchor_fg_side_list, dtype=np.int32)\n    anchor_nocare_side_index = np.array(anchor_nocare_side_list, dtype=np.int32)\n    anchor_fg_side_index = np.array(sorted(list(set(list(anchor_fg_side_index))))).astype(np.int32)\n    anchor_nocare_side_index = np.array(sorted(list(set(list(anchor_nocare_side_index))))).astype(np.int32)\n    labels[anchor_fg_side_index] = 1\n    labels[anchor_nocare_side_index] = -1\n\n    k_index = anchor_fg_side_index.copy()\n    k_index1 = np.zeros((len(inds_inside)), dtype=np.int32)\n    k_index1[k_index] = 1\n\n    # map up to original set of anchors\n    # 一开始是将超出图像范围的anchor直接丢掉的，现在在加回来\n    labels = _unmap(labels, total_anchors, inds_inside, fill=-1)  # 这些anchor的label是-1，也即dontcare\n    v_target = _unmap(v_target, total_anchors, inds_inside, fill=0)  # 这些anchor的真值是0，也即没有值\n    o_target = _unmap(o_target, total_anchors, inds_inside, fill=0)\n    j_index2 = _unmap(j_index1, total_anchors, inds_inside, fill=0).astype(np.int32)\n    k_index2 = _unmap(k_index1, total_anchors, inds_inside, fill=0).astype(np.int32)\n\n    # real_j_index = np.where(j_index2==1)[0]\n    # real_k_index = np.where(k_index2==1)[0]\n\n    if DEBUG:\n        # 可视化出我们最终选出来的正样本，确定是否合理\n        vis_training_sample(labels, all_anchors, im_name, gt_boxes)\n    if DEBUG or SHOW_SOME:\n        print('正样本：' + str(len(np.where(labels == 1)[0])))\n        print('负样本：' + str(len(np.where(labels == 0)[0])))\n        print('忽略样本：' + str(len(np.where(labels == -1)[0])))\n        # print('保存的tmp_labels')\n        # print('正样本：' + str(len(np.where(tmp_labels == 1)[0])))\n        # print('负样本：' + str(len(np.where(tmp_labels == 0)[0])))\n        # print('忽略样本：' + str(len(np.where(tmp_labels == -1)[0])))\n    return labels, v_target, o_target, j_index2, k_index2\n\n\ndef _unmap(data, count, inds, fill=0):\n    \"\"\" Unmap a subset of item (data) back to the original set of items (of\n    size count) \"\"\"\n    if len(data.shape) == 1:\n        ret = np.empty((count, ), dtype=np.float32)\n        ret.fill(fill)\n        ret[inds] = data\n    else:\n        ret = np.empty((count, ) + data.shape[1:], dtype=np.float32)\n        ret.fill(fill)\n        ret[inds, :] = data\n    return ret\n\n\ndef _compute_targets(ex_rois, gt_rois):\n    \"\"\"Compute bounding-box regression targets for an image.\"\"\"\n\n    assert ex_rois.shape[0] == gt_rois.shape[0]\n    assert ex_rois.shape[1] == 4\n    assert gt_rois.shape[1] == 5\n\n    target_v, target_o = v_compute(ex_rois, gt_rois[:, :4])\n    return target_v.astype(np.float32, copy=False), target_o.astype(np.float32, copy=False)\n\n\ndef v_compute(ex_rois, gt_rois):\n    \"\"\"\n    计算竖直方向坐标的回归目标\n    :param ex_rois:\n    :param gt_rois:\n    :return: target_d (n*2)  v_c, v_h\n    \"\"\"\n    ex_widths = ex_rois[:, 2] - ex_rois[:, 0] + 1.0\n    ex_heights = ex_rois[:, 3] - ex_rois[:, 1] + 1.0\n    ex_ctr_x = ex_rois[:, 0] + 0.5 * ex_widths\n    ex_ctr_y = ex_rois[:, 1] + 0.5 * ex_heights\n\n    assert np.min(ex_widths) > 0.1 and np.min(ex_heights) > 0.1, \\\n        'Invalid boxes found: {} {}'. \\\n            format(ex_rois[np.argmin(ex_widths), :], ex_rois[np.argmin(ex_heights), :])\n\n    gt_widths = gt_rois[:, 2] - gt_rois[:, 0] + 1.0\n    # 得到的gt_width怎么会有17\n    gt_heights = gt_rois[:, 3] - gt_rois[:, 1] + 1.0\n    gt_ctr_x = gt_rois[:, 0] + 0.5 * gt_widths\n    gt_ctr_y = gt_rois[:, 1] + 0.5 * gt_heights\n\n    target_dvc = (gt_ctr_y - ex_ctr_y) / ex_heights\n    target_dvh = np.log(gt_heights / ex_heights)\n\n    # 由于上一行报错，\n    if not (target_dvh==target_dvh).all(): # 判断是否是nan\n        print('gt_heights:', gt_heights, '\\nex_heights:', ex_heights)\n    target_v= np.vstack(\n        (target_dvc, target_dvh)).transpose()\n\n    target_do = (gt_ctr_x - ex_ctr_x) / ex_widths\n    target_o = target_do\n\n    return target_v, target_o\n\n\ndef vis_training_sample(labels, all_anchors, img_name, gt_boxes):\n    import matplotlib.pyplot as plt\n    import os, cv2\n    img_path = os.path.join(cfg.ROOT_DIR, 'data/VOC2007', 'JPEGImages', img_name)\n    img = cv2.imread(img_path)\n    img = cv2.resize(img, (1000, 495))\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    fg_index = np.where(labels==-2)[0]  # 可视化出忽略样本\n    fg_anchors = all_anchors[fg_index, :]\n    list_fg_anchors = list(fg_anchors)\n    list_gt_boxes = list(gt_boxes)\n    # draw gt boxes\n    for box in list_gt_boxes:\n        cv2.rectangle(img, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (0, 0, 0), 1)\n    plt.imshow(img)\n    plt.show()\n    # draw fg boxes\n    height = []\n    color = [(0, 255, 0), (0, 0, 255), (255, 0, 0), (125, 125, 125), (125, 0, 200)]\n    list_img = []\n    for box in list_fg_anchors:\n        hei = (box[1], box[3])\n        if hei in height:\n            _ = height.index(hei)\n            choose_color = color[_%5]\n            choose_img = list_img[_]\n        else:\n            height.append(hei)\n            list_img.append(img.copy())\n            _ = height.index(hei)\n            choose_color = color[_ % 5]\n            choose_img = list_img[_]\n        cv2.rectangle(choose_img, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), choose_color, 1)\n    for a in list_img:\n        plt.imshow(a)\n        plt.show()\n\nif __name__ == '__main__':\n    from lib.fast_rcnn.train import get_data_layer, get_training_roidb\n    from lib.datasets.factory import get_imdb\n\n    imdb = get_imdb('voc_2007_trainval')\n    roidb = get_training_roidb(imdb)\n    data_layer = get_data_layer(roidb, 2)\n\n    DEBUG = True\n    while True:\n        db_inds, blobs = data_layer.forward()\n\n        if blobs['im_name']!='auto_50_5768038962_20180628224921_20180629100000_161.jpg':\n            continue\n\n        im_name = blobs['im_name']\n        data = blobs['data']\n        im_info = blobs['im_info']\n        gt_boxes = blobs['gt_boxes']\n        gt_ishard = blobs['gt_ishard']\n        dontcare_areas = blobs['dontcare_areas']\n        rpn_cls_score = np.ones((1, 30, 62, 20))\n        rpn_cls_prob = np.ones((18600, 2))\n\n        a, b, c, d, e = anchor_target_layer(rpn_cls_score, rpn_cls_prob, im_name, gt_boxes, gt_ishard,\n                                            dontcare_areas, im_info)\n\n\n\n\n", "meta": {"hexsha": "8e0cf27e8a17418cc505dc7dfdb3a4b29fea44ef", "size": 16933, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib_bak/rpn_msr/anchor_target_layer_hx3.py", "max_stars_repo_name": "hx123123/express-order-detection", "max_stars_repo_head_hexsha": "a1fa92a6bb02b5c47ad4b36e6f01602660527ac7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-02-23T04:58:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-27T16:48:27.000Z", "max_issues_repo_path": "lib_bak/rpn_msr/anchor_target_layer_hx3.py", "max_issues_repo_name": "hx123123/express-order-detection", "max_issues_repo_head_hexsha": "a1fa92a6bb02b5c47ad4b36e6f01602660527ac7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib_bak/rpn_msr/anchor_target_layer_hx3.py", "max_forks_repo_name": "hx123123/express-order-detection", "max_forks_repo_head_hexsha": "a1fa92a6bb02b5c47ad4b36e6f01602660527ac7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6288888889, "max_line_length": 159, "alphanum_fraction": 0.6340872852, "include": true, "reason": "import numpy", "num_tokens": 5802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.32766831395172374, "lm_q1q2_score": 0.16767331708451458}}
{"text": "import numpy as np\r\nimport nltk\r\nimport pandas as pd\r\nfrom ast import literal_eval\r\nfrom collections import Counter\r\n\r\n\r\ndef sampleFromDirichlet(alpha):\r\n    return np.random.dirichlet(alpha)\r\n\r\n\r\ndef sampleFromCategorical(theta):\r\n    # theta = theta / np.sum(theta)\r\n    return np.random.multinomial(1, theta).argmax()\r\n\r\n\r\ndef word_indices(doc_sent_word_dict, sent_index):\r\n    \"\"\"\r\n    :param doc_sent_word_dict:\r\n    :param sent_index:\r\n    :return:\r\n    \"\"\"\r\n    sentence = doc_sent_word_dict[sent_index]\r\n    for idx in sentence:\r\n        yield idx\r\n\r\n\r\nclass STMD_Gibbs_Sampler:\r\n    def __init__(self, numTopics, alpha, beta, gamma, max_vocab_size=10000, max_sentence=50, numSentiments=2):\r\n        self.alpha = alpha\r\n        self.beta = beta\r\n        self.gamma = gamma\r\n        self.numTopics = numTopics\r\n        self.numSentiments = numSentiments\r\n        self.MAX_VOCAB_SIZE = max_vocab_size\r\n        self.maxSentence = max_sentence\r\n\r\n    def build_dataset(self, reviews):\r\n        \"\"\"\r\n        :param reviews: 리뷰 데이터 [ [[문서1의 문장1],[문서1의 문장2]], [[문서2의 문장1],[문서2의 문장2]], ...]]\r\n        :return:\r\n        \"\"\"\r\n        corpus = [word for review in reviews for sentence in review for word in sentence]\r\n        text = nltk.Text(corpus)\r\n        freq = nltk.FreqDist(text)\r\n        keywords = [tup[0] for tup in freq.most_common(self.MAX_VOCAB_SIZE)]  # 많이 등장한 단어 선택\r\n\r\n        word2idx = {}  # key : 단어, value : index\r\n        for index, key in enumerate(keywords):\r\n            word2idx[key] = index\r\n\r\n        idx2word = dict(zip(word2idx.values(), word2idx.keys()))  # key : index, value : 단어\r\n        doc_sent_word_dict = {}  # key: 문서 index, value : [[list of sent1 단어의 index], [list of sent2 단어의 index]...]\r\n        numSentence = {}  # key : 문서 index, value : 해당 문서의 문장수\r\n        wordCountSentence = {}  # key : 문서 index, value : 해당 문서의 각 문장별 word count\r\n        for index, review in enumerate(reviews):\r\n            doc_sent_lst = []\r\n            doc_sent_count = []\r\n            for sent in review:\r\n                word_indices = [word2idx[word] for word in sent if word in word2idx]\r\n                doc_sent_lst.append(word_indices)\r\n                counts = Counter(word_indices)\r\n                doc_sent_count.append(counts)\r\n            numSentence[index] = len(doc_sent_lst)\r\n            doc_sent_word_dict[index] = doc_sent_lst\r\n            wordCountSentence[index] = doc_sent_count\r\n\r\n        return word2idx, idx2word, doc_sent_word_dict, wordCountSentence, numSentence\r\n\r\n    def _initialize_(self, reviews):\r\n        self.word2idx, self.idx2word, self.doc_sent_word_dict, self.wordCountSentence, self.numSentence = self.build_dataset(\r\n            reviews)\r\n        numDocs = len(self.doc_sent_word_dict.keys())\r\n        vocabSize = len(self.word2idx.keys())\r\n\r\n        # Pseudocounts\r\n        self.n_wkl = np.zeros((vocabSize, self.numTopics, self.numSentiments))  # 단어 i가 topic k, senti l로 할당된 수\r\n        self.n_kl = np.zeros((self.numTopics, self.numSentiments))  # topic k, senti l로 할당된 단어 수\r\n        self.ns_d = np.zeros((numDocs))  # 문서 d의 문장 수\r\n        self.ns_dkl = np.zeros((numDocs, self.numTopics, self.numSentiments))  # 문서 d에서 topic k, sentiment l로 할당된 문장 수\r\n        self.ns_dk = np.zeros((numDocs, self.numTopics))  # 문서 d에서 topic k로 할당된 문장 수\r\n        self.topics = {}\r\n        self.sentiments = {}\r\n        # self.priorSentiment = {}\r\n\r\n        alphaVec = self.alpha * np.ones(self.numTopics)\r\n        gammaVec = self.gamma * np.ones(self.numSentiments)\r\n        # 기존 sentiment-lda에서는 sentiment wordnet을 이용해서 priorsentiment를 줬는데,\r\n        # word2vec은 classvector와 유사성을 이용해서 해도 괜찮을듯\r\n        #         for i, word in enumerate(self.vectorizer.get_feature_names()):\r\n        #             synsets = swn.senti_synsets(word)\r\n        #             posScore = np.mean([s.pos_score() for s in synsets])\r\n        #             negScore = np.mean([s.neg_score() for s in synsets])\r\n        #             if posScore >= 0.1 and posScore > negScore:\r\n        #                 self.priorSentiment[i] = 1\r\n        #             elif negScore >= 0.1 and negScore > posScore:\r\n        #                 self.priorSentiment[i] = 0\r\n\r\n        for d in range(numDocs):\r\n            topicDistribution = sampleFromDirichlet(alphaVec)\r\n            sentimentDistribution = np.zeros((self.numTopics, self.numSentiments))\r\n\r\n            for t in range(self.numTopics):\r\n                sentimentDistribution[t, :] = sampleFromDirichlet(gammaVec)\r\n\r\n            for m in range(self.numSentence[d]):\r\n                t = sampleFromCategorical(topicDistribution)\r\n                s = sampleFromCategorical(sentimentDistribution[t, :])\r\n                self.topics[(d, m)] = t  # d 문서의 m번째 문장의 topic\r\n                self.sentiments[(d, m)] = s  # d 문서의 m 번째 문장의 sentiment\r\n                self.ns_d[d] += 1\r\n                self.ns_dkl[d, t, s] += 1\r\n                self.ns_dk[d, t] += 1\r\n                for i, w in enumerate(word_indices(self.doc_sent_word_dict[d], m)):  # d번째 문서의 m번째 문장의 단어를 돌면서\r\n                    self.n_wkl[w, t, s] += 1  # w번째 단어가 topic은 t, sentiment s로 할당된 개수\r\n                    self.n_kl[t, s] += 1  # topic k, senti l로 할당된 단어 수\r\n\r\n    def conditionalDistribution(self, d, m, w):\r\n        \"\"\"\r\n        Calculates the (topic, sentiment) probability for sentence m in document d\r\n        Returns:    a matrix (numTopics x numSentiments) storing the probabilities\r\n        \"\"\"\r\n        probabilities_ts = np.ones((self.numTopics, self.numSentiments))\r\n\r\n        # firstfactor 수정\r\n        firstFactor = (self.n_wkl[w, :, :] + self.beta) / \\\r\n                      (self.n_kl + self.n_wkl.shape[0] * self.beta)  # dim(K x L)\r\n\r\n        secondFactor = (self.ns_dk[d, :] + self.alpha) / \\\r\n                       (self.ns_d[d] + self.numTopics * self.alpha)  # dim(K x 1)\r\n\r\n        thirdFactor = (self.ns_dkl[d, :, :] + self.gamma) / \\\r\n                      (self.ns_dk[d] + self.numSentiments * self.gamma)[:, np.newaxis]  # dim (K x L)\r\n\r\n        probabilities_ts *= firstFactor * thirdFactor\r\n        probabilities_ts *= secondFactor[:, np.newaxis]\r\n        probabilities_ts /= np.sum(probabilities_ts)\r\n        return probabilities_ts\r\n\r\n    def run(self, reviews, maxIters=10):\r\n        self._initialize_(reviews)\r\n        numDocs = len(self.doc_sent_word_dict.keys())\r\n\r\n        for iteration in range(maxIters):\r\n            if (iteration + 1) % 10 == 0:\r\n                print(\"Starting iteration %d of %d\" % (iteration + 1, maxIters))\r\n            for d in range(numDocs):\r\n                for m in range(self.numSentence[d]):\r\n                    t = self.topics[(d, m)]\r\n                    s = self.sentiments[(d, m)]\r\n                    self.ns_d[d] -= 1\r\n                    self.ns_dkl[d, t, s] -= 1\r\n                    self.ns_dk[d, t] -= 1\r\n                    for i, w in enumerate(word_indices(self.doc_sent_word_dict[d], m)):\r\n                        self.n_wkl[w, t, s] -= 1  # w번째 단어가 topic은 t, sentiment s로 할당된 개수\r\n                        self.n_kl[t, s] -= 1  # topic k, senti l로 할당된 단어 수\r\n\r\n                    probabilities_ts = self.conditionalDistribution(d, m, w)\r\n                    ind = sampleFromCategorical(probabilities_ts.flatten())\r\n                    t, s = np.unravel_index(ind, probabilities_ts.shape)\r\n                    self.topics[(d, m)] = t\r\n                    self.sentiments[(d, m)] = s\r\n                    self.ns_d[d] += 1\r\n                    self.ns_dkl[d, t, s] += 1\r\n                    self.ns_dk[d, t] += 1\r\n                    for i, w in enumerate(word_indices(self.doc_sent_word_dict[d], m)):\r\n                        self.n_wkl[w, t, s] += 1  # w번째 단어가 topic은 t, sentiment s로 할당된 개수\r\n                        self.n_kl[t, s] += 1  # topic k, senti l로 할당된 단어 수\r\n\r\n\r\ndata = pd.read_csv(\"E:/dataset/MasterThesis/elec_df_brand2vec.csv\",nrows =1000)\r\ndata['reviewSentence'] = data.reviewSentence.apply(lambda row: literal_eval(row))\r\ndata['reviewSentence_tagged'] = data.reviewSentence_tagged.apply(lambda row: literal_eval(row))\r\ntagged_text_list = list(data['reviewSentence_tagged'])\r\nsampler = STMD_Gibbs_Sampler(numTopics=5, alpha=0.1, beta=0.1, gamma=0.5, numSentiments=2)\r\nsampler._initialize_(tagged_text_list)\r\nsampler.run(tagged_text_list)\r\nprint(\"end\")", "meta": {"hexsha": "6cd4456b5b179c47022299336306a8ce21a85df5", "size": 8271, "ext": "py", "lang": "Python", "max_stars_repo_path": "STMD-hs.py", "max_stars_repo_name": "dedert/python_lda", "max_stars_repo_head_hexsha": "7ffb792ccee468c0d6afc41f38efd63c33fa59fe", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "STMD-hs.py", "max_issues_repo_name": "dedert/python_lda", "max_issues_repo_head_hexsha": "7ffb792ccee468c0d6afc41f38efd63c33fa59fe", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "STMD-hs.py", "max_forks_repo_name": "dedert/python_lda", "max_forks_repo_head_hexsha": "7ffb792ccee468c0d6afc41f38efd63c33fa59fe", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.4662921348, "max_line_length": 126, "alphanum_fraction": 0.5745375408, "include": true, "reason": "import numpy", "num_tokens": 2221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.2942149659744614, "lm_q1q2_score": 0.1676591827448496}}
{"text": "# param_sweep.py\n#\n# This file is part of scqubits: a Python package for superconducting qubits,\n# arXiv:2107.08552 (2021). https://arxiv.org/abs/2107.08552\n#\n#    Copyright (c) 2019 and later, Jens Koch and Peter Groszkowski\n#    All rights reserved.\n#\n#    This source code is licensed under the BSD-style license found in the\n#    LICENSE file in the root directory of this source tree.\n############################################################################\n\n\nimport functools\nimport weakref\n\nfrom abc import ABC\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union\n\nimport numpy as np\n\nfrom numpy import ndarray\nfrom qutip.qobj import Qobj\n\nimport scqubits.core.central_dispatch as dispatch\nimport scqubits.core.descriptors as descriptors\nimport scqubits.core.hilbert_space as hspace\nimport scqubits.core.spec_lookup as spec_lookup\nimport scqubits.core.storage as storage\nimport scqubits.io_utils.fileio_qutip as qutip_serializer\nimport scqubits.io_utils.fileio_serializers as serializers\nimport scqubits.settings as settings\nimport scqubits.utils.cpu_switch as cpu_switch\nimport scqubits.utils.misc as utils\n\nfrom scqubits.core.hilbert_space import HilbertSpace\nfrom scqubits.core.oscillator import Oscillator\nfrom scqubits.core.qubit_base import QubitBaseClass\nfrom scqubits.core.spec_lookup import SpectrumLookup\nfrom scqubits.core.storage import DataStore, SpectrumData\nfrom scqubits.io_utils.fileio_qutip import QutipEigenstates\n\nif TYPE_CHECKING:\n    from scqubits.io_utils.fileio import IOData\n\nif settings.IN_IPYTHON:\n    from tqdm.notebook import tqdm\nelse:\n    from tqdm import tqdm\n\nfrom scqubits.utils.typedefs import QuantumSys\n\n\nclass _ParameterSweepBase(ABC):\n    \"\"\"\n    The _ParameterSweepBase class is an abstract base class for ParameterSweep and\n    StoredSweep\n    \"\"\"\n\n    param_name = descriptors.WatchedProperty(str, \"PARAMETERSWEEP_UPDATE\")\n    param_vals = descriptors.WatchedProperty(ndarray, \"PARAMETERSWEEP_UPDATE\")\n    param_count = descriptors.WatchedProperty(int, \"PARAMETERSWEEP_UPDATE\")\n    evals_count = descriptors.WatchedProperty(int, \"PARAMETERSWEEP_UPDATE\")\n    lookup = descriptors.ReadOnlyProperty(SpectrumLookup)\n    _hilbertspace: hspace.HilbertSpace\n\n    def get_subsys(self, index: int) -> QuantumSys:\n        return self._hilbertspace[index]\n\n    def get_subsys_index(self, subsys: QuantumSys) -> int:\n        return self._hilbertspace.get_subsys_index(subsys)\n\n    @property\n    def osc_subsys_list(self) -> List[Oscillator]:\n        return self._hilbertspace.osc_subsys_list\n\n    @property\n    def qbt_subsys_list(self) -> List[QubitBaseClass]:\n        return self._hilbertspace.qbt_subsys_list\n\n    @property\n    def subsystem_count(self) -> int:\n        return self._hilbertspace.subsystem_count\n\n    @property\n    def bare_specdata_list(self) -> List[SpectrumData]:\n        return self.lookup._bare_specdata_list\n\n    @property\n    def dressed_specdata(self) -> SpectrumData:\n        return self.lookup._dressed_specdata\n\n    def _lookup_bare_eigenstates(\n        self,\n        param_index: int,\n        subsys: QuantumSys,\n        bare_specdata_list: List[SpectrumData],\n    ) -> Union[ndarray, List[QutipEigenstates]]:\n        \"\"\"\n        Parameters\n        ----------\n        param_index:\n            position index of parameter value in question\n        subsys:\n            Hilbert space subsystem for which bare eigendata is to be looked up\n        bare_specdata_list:\n            may be provided during partial generation of the lookup\n\n        Returns\n        -------\n            bare eigenvectors for the specified subsystem and the external parameter\n            fixed to the value indicated by its index\n        \"\"\"\n        subsys_index = self.get_subsys_index(subsys)\n        return bare_specdata_list[subsys_index].state_table[param_index]  # type: ignore\n\n    @property\n    def system_params(self) -> Dict[str, Any]:\n        return self._hilbertspace.get_initdata()\n\n    def new_datastore(self, **kwargs) -> DataStore:\n        \"\"\"Return DataStore object with system/sweep information obtained from self.\"\"\"\n        return storage.DataStore(\n            self.system_params, self.param_name, self.param_vals, **kwargs\n        )\n\n\nclass _ParameterSweep(\n    _ParameterSweepBase, dispatch.DispatchClient, serializers.Serializable\n):\n    \"\"\"\n    The ParameterSweep class helps generate spectral and associated data for a\n    composite quantum system, as an externa, parameter, such as flux, is swept over\n    some given interval of values. Upon initialization, these data are calculated and\n    stored internally, so that plots can be generated efficiently. This is of\n    particular use for interactive displays used in the Explorer_ class.\n\n    Parameters\n    ----------\n    param_name:\n        name of external parameter to be varied\n    param_vals:\n        array of parameter values\n    evals_count:\n        number of eigenvalues and eigenstates to be calculated for the composite\n        Hilbert space\n    hilbertspace:\n        collects all data specifying the Hilbert space of interest\n    subsys_update_list:\n        list of subsys_list in the Hilbert space which get modified when the external\n        parameter changes\n    update_hilbertspace:\n        update_hilbertspace(param_val) specifies how a change in the external\n        parameter affects the Hilbert space components\n    num_cpus:\n        number of CPUS requested for computing the sweep (default: settings.NUM_CPUS)\n    \"\"\"\n\n    param_name = descriptors.WatchedProperty(str, \"PARAMETERSWEEP_UPDATE\")\n    param_vals = descriptors.WatchedProperty(ndarray, \"PARAMETERSWEEP_UPDATE\")\n    param_count = descriptors.WatchedProperty(int, \"PARAMETERSWEEP_UPDATE\")\n    evals_count = descriptors.WatchedProperty(int, \"PARAMETERSWEEP_UPDATE\")\n    subsys_update_list = descriptors.WatchedProperty(\n        List[QuantumSys], \"PARAMETERSWEEP_UPDATE\"\n    )\n    update_hilbertspace = descriptors.WatchedProperty(Callable, \"PARAMETERSWEEP_UPDATE\")\n    lookup = descriptors.ReadOnlyProperty(SpectrumLookup)\n\n    def __init__(\n        self,\n        param_name: str,\n        param_vals: ndarray,\n        evals_count: int,\n        hilbertspace: HilbertSpace,\n        subsys_update_list: List[QuantumSys],\n        update_hilbertspace: Callable,\n        num_cpus: Optional[int] = None,\n    ) -> None:\n        num_cpus = num_cpus or settings.NUM_CPUS\n        self.param_name = param_name\n        self.param_vals = param_vals\n        self.param_count = len(param_vals)\n        self.evals_count = evals_count\n        self._hilbertspace = hilbertspace\n        self.subsys_update_list = tuple(subsys_update_list)\n        self.update_hilbertspace = update_hilbertspace\n        self.num_cpus = num_cpus\n        self._lookup: Union[SpectrumLookup, None] = None\n        self._bare_hamiltonian_constant: Qobj\n\n        self.tqdm_disabled = settings.PROGRESSBAR_DISABLED or (num_cpus > 1)\n\n        dispatch.CENTRAL_DISPATCH.register(\"PARAMETERSWEEP_UPDATE\", self)\n        dispatch.CENTRAL_DISPATCH.register(\"HILBERTSPACE_UPDATE\", self)\n\n        # generate the spectral data sweep\n        if settings.AUTORUN_SWEEP:\n            self.run()\n\n    def run(self) -> None:\n        \"\"\"Top-level method for generating all parameter sweep data\"\"\"\n        self.cause_dispatch()  # one dispatch before temp. disabling CENTRAL_DISPATCH\n        settings.DISPATCH_ENABLED = False\n        bare_specdata_list = self._compute_bare_specdata_sweep()\n        dressed_specdata = self._compute_dressed_specdata_sweep(bare_specdata_list)\n        self._lookup = spec_lookup.SpectrumLookup(\n            self, dressed_specdata, bare_specdata_list\n        )\n        settings.DISPATCH_ENABLED = True\n\n    # HilbertSpace: methods for CentralDispatch ---------------------------------------\n    def cause_dispatch(self) -> None:\n        self.update_hilbertspace(self.param_vals[0])\n\n    def receive(self, event: str, sender: object, **kwargs) -> None:\n        \"\"\"Hook to CENTRAL_DISPATCH. This method is accessed by the global\n        CentralDispatch instance whenever an event occurs that ParameterSweep is\n        registered for. In reaction to update events, the lookup table is marked as\n        out of sync.\n\n        Parameters\n        ----------\n        event:\n            type of event being received\n        sender:\n            identity of sender announcing the event\n        **kwargs\n        \"\"\"\n        if self._lookup is not None:\n            if event == \"HILBERTSPACE_UPDATE\" and sender is self._hilbertspace:\n                self._lookup._out_of_sync = True\n                # print('Lookup table now out of sync')\n            elif event == \"PARAMETERSWEEP_UPDATE\" and sender is self:\n                self._lookup._out_of_sync = True\n                # print('Lookup table now out of sync')\n\n    # ParameterSweep: file IO methods -------------------------------------------------\n    @classmethod\n    def deserialize(cls, iodata: \"IOData\") -> \"_StoredSweep\":\n        \"\"\"\n        Take the given IOData and return an instance of the described class,\n        initialized with the data stored in io_data.\n\n        Parameters\n        ----------\n        iodata: IOData\n\n        Returns\n        -------\n        _StoredSweep\n        \"\"\"\n        data_dict = iodata.as_kwargs()\n        lookup = data_dict.pop(\"_lookup\")\n        data_dict[\"dressed_specdata\"] = lookup._dressed_specdata\n        data_dict[\"bare_specdata_list\"] = lookup._bare_specdata_list\n        new_storedsweep = _StoredSweep(**data_dict)\n        new_storedsweep._lookup = lookup\n        return new_storedsweep\n\n    def serialize(self) -> \"IOData\":\n        \"\"\"\n        Convert the content of the current class instance into IOData format.\n\n        Returns\n        -------\n        IOData\n        \"\"\"\n        if self._lookup is None:\n            raise ValueError(\"Nothing to save - no lookup data has been generated yet.\")\n\n        initdata = {\n            \"param_name\": self.param_name,\n            \"param_vals\": self.param_vals,\n            \"evals_count\": self.evals_count,\n            \"hilbertspace\": self._hilbertspace,\n            \"_lookup\": self._lookup,\n        }\n        iodata = serializers.dict_serialize(initdata)\n        iodata.typename = \"_StoredSweep\"\n        return iodata\n\n    # ParameterSweep: private methods for generating the sweep ------------------------\n    def _compute_bare_specdata_sweep(self) -> List[SpectrumData]:\n        \"\"\"\n        Pre-calculates all bare spectral data needed for the interactive explorer\n        display.\n        \"\"\"\n        bare_eigendata_constant = [\n            self._compute_bare_spectrum_constant()\n        ] * self.param_count\n        target_map = cpu_switch.get_map_method(self.num_cpus)\n        with utils.InfoBar(\n            \"Parallel compute bare eigensys [num_cpus={}]\".format(self.num_cpus),\n            self.num_cpus,\n        ):\n            bare_eigendata_varying = list(\n                target_map(\n                    self._compute_bare_spectrum_varying,\n                    tqdm(\n                        self.param_vals,\n                        desc=\"Bare spectra\",\n                        leave=False,\n                        disable=self.tqdm_disabled,\n                    ),\n                )\n            )\n        bare_specdata_list = self._recast_bare_eigendata(\n            bare_eigendata_constant, bare_eigendata_varying\n        )\n        del bare_eigendata_constant\n        del bare_eigendata_varying\n        return bare_specdata_list\n\n    def _compute_dressed_specdata_sweep(\n        self, bare_specdata_list: List[SpectrumData]\n    ) -> SpectrumData:\n        \"\"\"\n        Calculates and returns all dressed spectral data.\n        \"\"\"\n        self._bare_hamiltonian_constant = self._compute_bare_hamiltonian_constant(\n            bare_specdata_list\n        )\n        param_indices = range(self.param_count)\n        func = functools.partial(\n            self._compute_dressed_eigensystem, bare_specdata_list=bare_specdata_list\n        )\n        target_map = cpu_switch.get_map_method(self.num_cpus)\n\n        with utils.InfoBar(\n            \"Parallel compute dressed eigensys [num_cpus={}]\".format(self.num_cpus),\n            self.num_cpus,\n        ):\n            dressed_eigendata = list(\n                target_map(\n                    func,\n                    tqdm(\n                        param_indices,\n                        desc=\"Dressed spectrum\",\n                        leave=False,\n                        disable=self.tqdm_disabled,\n                    ),\n                )\n            )\n        dressed_specdata = self._recast_dressed_eigendata(dressed_eigendata)\n        del dressed_eigendata\n        return dressed_specdata\n\n    def _recast_bare_eigendata(\n        self,\n        static_eigendata: List[List[Tuple[ndarray, ndarray]]],\n        bare_eigendata: List[List[Tuple[ndarray, ndarray]]],\n    ) -> List[SpectrumData]:\n        specdata_list = []\n        for index, subsys in enumerate(self._hilbertspace):\n            if subsys in self.subsys_update_list:\n                eigendata = bare_eigendata\n            else:\n                eigendata = static_eigendata\n            evals_count = subsys.truncated_dim\n            dim = subsys.hilbertdim()\n            esys_dtype = subsys._evec_dtype\n\n            energy_table = np.empty(\n                shape=(self.param_count, evals_count), dtype=np.float_\n            )\n            state_table = np.empty(\n                shape=(self.param_count, dim, evals_count), dtype=esys_dtype\n            )\n            for j in range(self.param_count):\n                energy_table[j] = eigendata[j][index][0]\n                state_table[j] = eigendata[j][index][1]\n            specdata_list.append(\n                storage.SpectrumData(\n                    energy_table,\n                    system_params={},\n                    param_name=self.param_name,\n                    param_vals=self.param_vals,\n                    state_table=state_table,\n                )\n            )\n        return specdata_list\n\n    def _recast_dressed_eigendata(\n        self, dressed_eigendata: List[Tuple[ndarray, QutipEigenstates]]\n    ) -> SpectrumData:\n        evals_count = self.evals_count\n        energy_table = np.empty(shape=(self.param_count, evals_count), dtype=np.float_)\n        state_table = []  # for dressed states, entries are Qobj\n        for j in range(self.param_count):\n            energy_table[j] = np.real_if_close(dressed_eigendata[j][0])\n            state_table.append(dressed_eigendata[j][1])\n        specdata = storage.SpectrumData(\n            energy_table,\n            system_params={},\n            param_name=self.param_name,\n            param_vals=self.param_vals,\n            state_table=state_table,\n        )\n        return specdata\n\n    def _compute_bare_hamiltonian_constant(\n        self, bare_specdata_list: List[SpectrumData]\n    ) -> Qobj:\n        \"\"\"\n        Returns\n        -------\n            composite Hamiltonian composed of bare Hamiltonians of subsys_list\n            independent of the external parameter\n        \"\"\"\n        static_hamiltonian = 0\n        for index, subsys in enumerate(self._hilbertspace):\n            if subsys not in self.subsys_update_list:\n                evals = bare_specdata_list[index].energy_table[0]\n                static_hamiltonian += self._hilbertspace.diag_hamiltonian(subsys, evals)\n        return static_hamiltonian\n\n    def _compute_bare_hamiltonian_varying(\n        self, bare_specdata_list: List[SpectrumData], param_index: int\n    ) -> Qobj:\n        \"\"\"\n        Parameters\n        ----------\n        param_index:\n            position index of current value of the external parameter\n\n        Returns\n        -------\n            composite Hamiltonian consisting of all bare Hamiltonians which depend on\n            the external parameter\n        \"\"\"\n        hamiltonian = 0\n        for index, subsys in enumerate(self._hilbertspace):\n            if subsys in self.subsys_update_list:\n                evals = bare_specdata_list[index].energy_table[param_index]\n                hamiltonian += self._hilbertspace.diag_hamiltonian(subsys, evals)\n        return hamiltonian\n\n    def _compute_bare_spectrum_constant(self) -> List[Tuple[ndarray, ndarray]]:\n        \"\"\"\n        Returns\n        -------\n            eigensystem data for each subsystem that is not affected by a change of the\n            external parameter\n        \"\"\"\n        eigendata = []\n        for subsys in self._hilbertspace:\n            if subsys not in self.subsys_update_list:\n                evals_count = subsys.truncated_dim\n                eigendata.append(subsys.eigensys(evals_count=evals_count))\n            else:\n                eigendata.append(None)  # type: ignore\n        return eigendata\n\n    def _compute_bare_spectrum_varying(\n        self, param_val: float\n    ) -> List[Tuple[ndarray, ndarray]]:\n        \"\"\"\n        For given external parameter value obtain the bare eigenspectra of each bare\n        subsystem that is affected by changes in the external parameter. Formulated\n        to be used with Pool.map()\n\n        Returns\n        -------\n            (evals, evecs) bare eigendata for each subsystem that is parameter-dependent\n        \"\"\"\n        eigendata = []\n        self.update_hilbertspace(param_val)\n        for subsys in self._hilbertspace:\n            if subsys in self.subsys_update_list:\n                evals_count = subsys.truncated_dim\n                subsys_index = self._hilbertspace.get_subsys_index(subsys)\n                eigendata.append(\n                    self._hilbertspace[subsys_index].eigensys(evals_count=evals_count)\n                )\n            else:\n                eigendata.append(None)  # type: ignore\n        return eigendata\n\n    def _compute_dressed_eigensystem(\n        self, param_index: int, bare_specdata_list: List[SpectrumData]\n    ) -> Tuple[ndarray, QutipEigenstates]:\n        hamiltonian = (\n            self._bare_hamiltonian_constant\n            + self._compute_bare_hamiltonian_varying(bare_specdata_list, param_index)\n        )\n\n        for interaction_term in self._hilbertspace.interaction_list:\n            evecs1 = self._lookup_bare_eigenstates(\n                param_index, interaction_term.subsys1, bare_specdata_list\n            )\n            evecs2 = self._lookup_bare_eigenstates(\n                param_index, interaction_term.subsys2, bare_specdata_list\n            )\n            hamiltonian += self._hilbertspace.interactionterm_hamiltonian(\n                interaction_term, evecs1=evecs1, evecs2=evecs2\n            )\n        evals, evecs = hamiltonian.eigenstates(eigvals=self.evals_count)\n        evecs = evecs.view(qutip_serializer.QutipEigenstates)\n        return evals, evecs\n\n    def _lookup_bare_eigenstates(\n        self,\n        param_index: int,\n        subsys: QuantumSys,\n        bare_specdata_list: List[SpectrumData],\n    ) -> ndarray:\n        \"\"\"\n        Parameters\n        ----------\n        param_index:\n            position index of parameter value in question\n        subsys:\n            Hilbert space subsystem for which bare eigendata is to be looked up\n        bare_specdata_list:\n            may be provided during partial generation of the lookup\n\n        Returns\n        -------\n            bare eigenvectors for the specified subsystem and the external parameter\n            fixed to the value indicated by its index\n        \"\"\"\n        subsys_index = self.get_subsys_index(subsys)\n        return bare_specdata_list[subsys_index].state_table[param_index]  # type: ignore\n\n\nclass _StoredSweep(\n    _ParameterSweepBase, dispatch.DispatchClient, serializers.Serializable\n):\n    param_name = descriptors.WatchedProperty(str, \"PARAMETERSWEEP_UPDATE\")\n    param_vals = descriptors.WatchedProperty(ndarray, \"PARAMETERSWEEP_UPDATE\")\n    param_count = descriptors.WatchedProperty(int, \"PARAMETERSWEEP_UPDATE\")\n    evals_count = descriptors.WatchedProperty(int, \"PARAMETERSWEEP_UPDATE\")\n    lookup = descriptors.ReadOnlyProperty(SpectrumLookup)\n\n    def __init__(\n        self,\n        param_name: str,\n        param_vals: ndarray,\n        evals_count: int,\n        hilbertspace: HilbertSpace,\n        dressed_specdata: SpectrumData,\n        bare_specdata_list: List[SpectrumData],\n    ) -> None:\n        self.param_name = param_name\n        self.param_vals = param_vals\n        self.param_count = len(param_vals)\n        self.evals_count = evals_count\n        self._hilbertspace = hilbertspace\n        self._lookup = spec_lookup.SpectrumLookup(\n            hilbertspace, dressed_specdata, bare_specdata_list, auto_run=False\n        )\n\n    # StoredSweep: file IO methods -----------------------------------------------------\n    @classmethod\n    def deserialize(cls, iodata: \"IOData\") -> \"_StoredSweep\":\n        \"\"\"\n        Take the given IOData and return an instance of the described class,\n        initialized with the data stored in io_data.\n\n        Parameters\n        ----------\n        iodata: IOData\n\n        Returns\n        -------\n        _StoredSweep\n        \"\"\"\n        data_dict = iodata.as_kwargs()\n        lookup = data_dict.pop(\"_lookup\")\n        data_dict[\"dressed_specdata\"] = lookup._dressed_specdata\n        data_dict[\"bare_specdata_list\"] = lookup._bare_specdata_list\n        new_storedsweep = _StoredSweep(**data_dict)\n        new_storedsweep._lookup = lookup\n        new_storedsweep._lookup._hilbertspace = weakref.proxy(\n            new_storedsweep._hilbertspace\n        )\n        return new_storedsweep\n\n    # _StoredSweep: other methods\n    def get_hilbertspace(self) -> HilbertSpace:\n        return self._hilbertspace\n\n    def new_sweep(\n        self,\n        subsys_update_list: List[QuantumSys],\n        update_hilbertspace: Callable,\n        num_cpus: Optional[int] = None,\n    ) -> _ParameterSweep:\n        num_cpus = num_cpus or settings.NUM_CPUS\n        return _ParameterSweep(\n            self.param_name,\n            self.param_vals,\n            self.evals_count,\n            hilbertspace=self._hilbertspace,\n            subsys_update_list=subsys_update_list,\n            update_hilbertspace=update_hilbertspace,\n            num_cpus=num_cpus,\n        )\n", "meta": {"hexsha": "9be2a905fd3aaf73f07837af2269c160f0f9837c", "size": 22127, "ext": "py", "lang": "Python", "max_stars_repo_path": "scqubits/legacy/_param_sweep.py", "max_stars_repo_name": "scqubits/scqubits", "max_stars_repo_head_hexsha": "d8532a3b614e37b1e65b75000493ea2c25c05682", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 108, "max_stars_repo_stars_event_min_datetime": "2019-12-14T16:08:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T03:48:33.000Z", "max_issues_repo_path": "scqubits/legacy/_param_sweep.py", "max_issues_repo_name": "scqubits/scqubits", "max_issues_repo_head_hexsha": "d8532a3b614e37b1e65b75000493ea2c25c05682", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 62, "max_issues_repo_issues_event_min_datetime": "2019-12-14T02:41:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-06T07:32:42.000Z", "max_forks_repo_path": "scqubits/legacy/_param_sweep.py", "max_forks_repo_name": "scqubits/scqubits", "max_forks_repo_head_hexsha": "d8532a3b614e37b1e65b75000493ea2c25c05682", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 46, "max_forks_repo_forks_event_min_datetime": "2019-12-21T12:13:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T17:09:53.000Z", "avg_line_length": 36.9398998331, "max_line_length": 88, "alphanum_fraction": 0.6405296696, "include": true, "reason": "import numpy,from numpy", "num_tokens": 4914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.16758371576045333}}
{"text": "#coding:utf-8\nimport numpy as np\nimport tensorflow as tf\nfrom .Model import Model\n\nif tf.__version__ > '0.12.1':\n\tmatmul_func = tf.matmul\nelse:\n\tmatmul_func = tf.batch_matmul\n\nclass TransNB(Model):\n\tr'''\n\tTransE is the first model to introduce translation-based embedding,\n\twhich interprets relations as the translations operating on entities.\n\t'''\n\tdef _transfer(self, transfer_matrix, embeddings):\n\t\treturn matmul_func(embeddings, transfer_matrix)\n\n\tdef _calc(self, h, t, r):\n\t\th = tf.nn.l2_normalize(h, -1)\n\t\tt = tf.nn.l2_normalize(t, -1)\n\t\tr = tf.nn.l2_normalize(r, -1)\n\t\treturn abs(h + r - t)\n\n\tdef embedding_def(self):\n\t\t#Obtaining the initial configuration of the model\n\t\tconfig = self.get_config()\n\t\t#Defining required parameters of the model, including embeddings of entities and relations\n\t\tself.ent_embeddings = tf.get_variable(name = \"ent_embeddings\", shape = [config.entTotal, config.hidden_size], initializer = tf.contrib.layers.xavier_initializer(uniform = False))\n\t\tself.rel_embeddings = tf.get_variable(name = \"rel_embeddings\", shape = [config.relTotal, config.hidden_size], initializer = tf.contrib.layers.xavier_initializer(uniform = False))\n        self.type_transfer_matrix = tf.get_variable(name = \"type_transfer_matrix\", shape = [config.rel_type, config.ent_size * config.rel_size], initializer = tf.contrib.layers.xavier_initializer(uniform = False))\n        self.parameter_lists = {\"ent_embeddings\":self.ent_embeddings, \\\n\t\t\t\t\t\t\t\t\"rel_embeddings\":self.rel_embeddings,\n                                \"type_transfer_matrix\":self.type_transfer_matrix}\n\n\tdef loss_def(self):\n\t\t#Obtaining the initial configuration of the model\n\t\tconfig = self.get_config()\n\t\t#To get positive triples and negative triples for training\n\t\t#The shapes of pos_h, pos_t, pos_r are (batch_size, 1)\n\t\t#The shapes of neg_h, neg_t, neg_r are (batch_size, negative_ent + negative_rel)\n\t\tpos_h, pos_t, pos_r, pos_type_r = self.get_positive_instance(in_batch = True)\n\t\tneg_h, neg_t, neg_r, neg_type_r = self.get_negative_instance(in_batch = True)\n\t\t#Embedding entities and relations of triples, e.g. p_h, p_t and p_r are embeddings for positive triples\n\t\tself.p_h = tf.nn.embedding_lookup(self.ent_embeddings, pos_h)\n\t\tself.p_t = tf.nn.embedding_lookup(self.ent_embeddings, pos_t)\n\t\tself.p_r = tf.nn.embedding_lookup(self.rel_embeddings, pos_r)\n        self.p_type_r = tf.reshape(tf.nn.embedding_lookup(self.type_transfer_matrix, pos_type_r), [-1, config.ent_size, config.rel_size])\n\n\t\tself.n_h = tf.nn.embedding_lookup(self.ent_embeddings, neg_h)\n\t\tself.n_t = tf.nn.embedding_lookup(self.ent_embeddings, neg_t)\n\t\tself.n_r = tf.nn.embedding_lookup(self.rel_embeddings, neg_r)\n        self.n_type_r = tf.reshape(tf.nn.embedding_lookup(self.type_transfer_matrix, neg_type_r), [-1, config.ent_size, config.rel_size])\n\n        self.p_h_ = self._transfer(self.p_type_r, self.p_h)\n        self.p_t_ = self._transfer(self.p_type_r, self.p_t)\n        self.n_h_ = self._transfer(self.n_type_r, self.n_h)\n        self.n_t_ = self._transfer(self.n_type_r, self.n_t)\n\t\t#Calculating score functions for all positive triples and negative triples\n\t\t#The shape of _p_score is (batch_size, 1, hidden_size)\n\t\t#The shape of _n_score is (batch_size, negative_ent + negative_rel, hidden_size)\n\t\tself._p_score = self._calc(self.p_h_, self.p_t_, self.p_r)\n\t\tself._n_score = self._calc(self.n_h_, self.n_t_, self.n_r)\n\t\t#The shape of p_score is (batch_size, 1, 1)\n\t\t#The shape of n_score is (batch_size, negative_ent + negative_rel, 1)\n\t\tself.p_score =  tf.reduce_sum(self._p_score, -1, keep_dims = True)\n\t\tself.n_score =  tf.reduce_sum(self._n_score, -1, keep_dims = True)\n\t\t#Calculating loss to get what the framework will optimize\n\t\tself.loss = tf.reduce_mean(tf.maximum(self.p_score - self.n_score + config.margin, 0))\n\n\tdef predict_def(self):\n\t\tpredict_h, predict_t, predict_r = self.get_predict_instance()\n\t\tpredict_h_e = tf.nn.embedding_lookup(self.ent_embeddings, predict_h)\n\t\tpredict_t_e = tf.nn.embedding_lookup(self.ent_embeddings, predict_t)\n\t\tpredict_r_e = tf.nn.embedding_lookup(self.rel_embeddings, predict_r)\n\t\tself.predict = tf.reduce_mean(self._calc(predict_h_e, predict_t_e, predict_r_e), 1, keep_dims = False)\n", "meta": {"hexsha": "82e534b68b42f0fe4567fe039d392aeed0c4e20d", "size": 4198, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/TransNB.py", "max_stars_repo_name": "DavidHeSkr/Knowledge_Graph-in-Item2Item", "max_stars_repo_head_hexsha": "966e752c021056f6caae182dbab00e3d5f3d9525", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/TransNB.py", "max_issues_repo_name": "DavidHeSkr/Knowledge_Graph-in-Item2Item", "max_issues_repo_head_hexsha": "966e752c021056f6caae182dbab00e3d5f3d9525", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/TransNB.py", "max_forks_repo_name": "DavidHeSkr/Knowledge_Graph-in-Item2Item", "max_forks_repo_head_hexsha": "966e752c021056f6caae182dbab00e3d5f3d9525", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-11T06:27:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T08:00:34.000Z", "avg_line_length": 54.5194805195, "max_line_length": 213, "alphanum_fraction": 0.7508337303, "include": true, "reason": "import numpy", "num_tokens": 1081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.2845759920814681, "lm_q1q2_score": 0.1675837086142492}}
{"text": "#! /usr/bin/env python\n\"\"\"\nThis module takes a table of exposures, finds all exposures tagged as planetary nebula \nexposures, and:\n\n- For each grism\n    - For each spectral order\n        - For each file\n            - Determines which emission lines fall in that order of that file\n            - Attempts to automatically fit the line location\n            - Allows the user to override the result of the automatic fit\n            - Records the resulting fit location and status (good/bad/custom/etc.)\n\nThe module then saves a table of the results.\n\nIn addition, the module can take the result table above and use it to derive an overall \nwavelength fit for each grism/order value of the inputs, and produce yet another output \ntable given the results of that fit.\n\nAuthors\n-------\n- Brian York (all python code)\n- Ralph Bohlin (original IDL code)\n\nUse\n---\nThis module can be run from the command line (although one of the `abscal.commands` or \n`abscal.idl_commands` scripts would be preferred for that), but is mostly intended to be \nimported, either by binary scripts or for use from within python::\n\n    from abscal.wfc3.reduce_grism_wavelength import wlmeas, wlmake\n    \n    interim_table = wlmeas(input_table, command_line_arg_namespace, override_dict)\n    final_table = wlmake(input_table, interim_table, command_line_arg_namespace, override_dict)\n\nThe override dict allows for many of the default input parameters to be overriden (as \ndefaults -- individual per-exposure overrides defined in the data files will still take \npriority). There are currently no default parameters that can be overriden in this module.\n\"\"\"\n\n# *****TODO*****\n#   The following things could potentially be overridable parameters:\n#       - wlmeas\n#           - search region size around emission line\n#           - order wavelength search ranges (wrang)\n\nimport datetime\nimport glob\nimport json\nimport os\nimport yaml\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom astropy import constants as consts\nfrom astropy.io import ascii, fits\nfrom astropy.table import Table, Column, unique\nfrom astropy.time import Time\nfrom copy import deepcopy\nfrom matplotlib.widgets import TextBox\nfrom pathlib import Path\nfrom photutils.detection import DAOStarFinder\nfrom scipy.linalg import lstsq\nfrom scipy.stats import mode\n\nfrom abscal.common.args import parse\nfrom abscal.common.standard_stars import find_star_by_name\nfrom abscal.common.utils import air2vac, get_data_file, get_defaults, linecen\nfrom abscal.common.utils import smooth_model, tabinv\nfrom abscal.common.exposure_data_table import AbscalDataTable\nfrom abscal.wfc3.reduce_grism_extract import reduce\n\ndef wlimaz(root, y_arr, wave_arr, directory, verbose):\n    \"\"\"\n    Find a line from the IMA zero-read.\n    \n    If the very bright 10380A line falls in the first order, you can end up\n    trying to centre a saturated line. In this case, use the _ima.fits file,\n    which holds all of the individual reads, and measure the line centre from\n    the zero-read ima file in the first order.\n\n    Parameters\n    ----------\n    root : str\n        The file name to be checked\n    y_arr : np.ndarray\n        The y-values (flux values) from the flt file\n    wave_arr : np.ndarray\n        The approximate wavelength values from the flt file\n    directory : str\n        The directory where the flt file is located (and where the ima file\n        should be located)\n\n    Returns\n    -------\n    star_x : float\n        The x centre of the line\n    star_y : float\n        The y centre of the line\n    \"\"\"\n    file_name = os.path.join(directory, root+\"_ima.fits\")\n    with fits.open(file_name) as in_file:\n        hd = in_file[0].header\n        nexten = hd['NEXTEND']\n        ima = in_file[nexten-4].data    # zero read\n        ima = ima[5:1019,5:1019]        # trim to match flt\n        dq = in_file[nexten-2].data     # DQ=8 is unstable in Zread\n        dq = dq[5:1019,5:1019]          # trim to match flt\n\n        # Get approximate position from preliminary extraction\n        xlin = tabinv(wave_arr, np.array((10830.,)))\n        xapprox = np.floor(xlin + .5).astype(np.int32)\n        if isinstance(xapprox, np.ndarray):\n            xapprox = xapprox[0]\n        yapprox = np.floor(y_arr[xapprox] + .5).astype(np.int32)\n        if isinstance(yapprox, np.ndarray):\n            yapprox = yapprox[0]\n        if verbose:\n            print(type(xapprox), type(yapprox))\n            msg = \"WLIMAZ: 10830 line at approx ({},{})\"\n            print(msg.format(xapprox, yapprox))\n\n        # Fix any DQ=8 pixels\n        ns = 11 # for an 11x11 search area\n        sbimg = ima[yapprox-ns//2:yapprox+ns//2+1,xapprox-ns//2:xapprox+ns//2+1]\n        sbdq = dq[yapprox-ns//2:yapprox+ns//2+1,xapprox-ns//2:xapprox+ns//2+1]\n        bad = np.where((sbdq & 8) != 0)\n        if len(bad) > 0:\n            nbad = len(bad[0])\n        # from wlimaz.pro comment:\n        # ; I see up to nbad=5 in later data, eg ic6906bzq, but ima NOT zeroed & looks OK\n        # ; no response from SED abt re-fetching new OTF processings\n        totbad = np.sum(sbimg[bad])\n\n        # If all bad pixels have been zeroed, interpolate them.\n        if totbad == 0:\n            if verbose:\n                print(\"WLIMAZ: {} bad pixels repaired\".format(nbad))\n            for i in range(nbad):\n                xbad = bad[0][i] % ns\n                ybad = bad[0][i] / ns\n                if xbad != 0 and xbad != ns-1 and ybad != 0 and ybad != ns-1:\n                    bad_val = (sbimg[ybad,xbad-1] + sbimg[ybad,xbad+1] +\n                               sbimg[ybad-1,xbad] + sbimg[ybad+1,sbad])/4\n                    sbimg[ybad,xbad] = bad_val\n\n        indmx = np.unravel_index(np.argmax(sbimg, axis=None), sbimg.shape)\n        xmx, ymx = indmx[1], indmx[0]\n        xpos = xmx % ns\n        ypos = ymx / ns\n\n        # Threshold of 10 counts, FWHM of 2. Only return brightest result.\n        star_finder = DAOStarFinder(10., 2., brightest=1)\n        star_table = star_finder.find_stars(sbimg)\n        star_x = star_table['xcentroid'][0]\n        star_y = star_table['ycentroid'][0]\n        if star_x < 0 or star_y < 0:\n            print(\"WLIMAZ: Peak too close to edge: using approximate position.\")\n            star_x = xpos\n            star_y = ypos\n\n        star_x = star_x + xapprox - ns//2\n        star_y = star_y + yapprox - ns//2\n        if verbose:\n            print(\"\\tDAOFind: xc={}, yc={}\".format(star_x, star_y))\n\n        if nbad > 0:\n            print(\"WLIMAZ: nbad={}, total bad counts={}\".format(nbad, totbad))\n        return star_x, star_y\n\n\ndef wlmeas(input_table, **kwargs):\n    \"\"\"\n    Measure planetary nebula emission line locations.\n    \n    There are six planetary nebula emission lines that fall neatly into the WFC3 grism \n    spectral orders, and this function uses the approximate wavelength solution to find \n    the rough location of these lines, and then uses flux-weighting to determine the line \n    centre. The user is able to override a given fit if the script is run with the \n    show_plots flag.\n    \n    Parameters\n    ----------\n    input_table : abscal.common.exposure_data_table.AbscalDataTable\n        Table of exposures with emission lines to fit.\n    kwargs : dict\n        Dictionary of overrides to the default reduction parameters, and command-line \n        option selections.\n    \n    Returns\n    -------\n    output_table : astropy.table.Table\n        Table of emission line locations\n    \"\"\"\n    task = \"wfc3: grism: wlmeas\"\n    default_values = get_defaults('abscal.common.args')\n    base_defaults = default_values | get_defaults(kwargs.get('module_name', __name__))\n    verbose = kwargs.get('verbose', base_defaults['verbose'])\n    show_plots = kwargs.get('plots', base_defaults['plots'])\n    if 'out_file' in kwargs:\n        out_file = kwargs['out_file']\n        out_dir, out_table = os.path.split(out_file)\n        if out_dir == '':\n            out_dir = os.getcwd()\n    elif 'out_dir' in kwargs:\n        out_dir = kwargs['out_dir']\n    else:\n        out_dir = os.getcwd()\n    spec_name = kwargs.get('spec_dir', base_defaults['spec_dir'])\n    spec_dir = os.path.join(out_dir, spec_name)\n    in_notebook = kwargs.get('notebook', False)\n\n    issues = {}\n    exposure_parameter_file = get_data_file(\"abscal.wfc3\", os.path.basename(__file__))\n    if exposure_parameter_file is not None:\n        with open(exposure_parameter_file, 'r') as inf:\n            issues = yaml.safe_load(inf)\n    \n    fwhm = {\n                'G102': {\n                            -1: 80.,\n                            1: 80.,\n                            2: 40.\n                        },\n                'G141': {\n                            -1: 120.,\n                            1: 120.,\n                            2: 60\n                        }\n            }\n\n    # lab reference line wavelengths\n    wl_air = np.array([9068.6, 9532.5, 10830., 12818.1, 16109.3, 16407.2])\n    wl_vac = air2vac(wl_air)\n\n    # Get wavelength reference file\n    cal_data = get_data_file(\"abscal.wfc3\", \"calibration_files.yaml\")\n    with open(cal_data, 'r') as inf:\n        cal_files = yaml.safe_load(inf)\n    pn_ref_name = cal_files[\"ic5117_data\"]\n    pn_ref = get_data_file(\"abscal.wfc3\", pn_ref_name)\n\n    # Columns are 'wavelength' and 'flux'\n    pn_ref_table = Table.read(pn_ref, format=\"ascii.basic\")\n    \n    input_table = deepcopy(input_table)\n    input_table = input_table[input_table[\"planetary_nebula\"] == True]\n\n    xpx = np.arange(1014, dtype=np.float64)\n\n    if verbose:\n        msg = \"{}: Starting WFC3 wavelength measurement for GRISM data.\"\n        print(msg.format(task))\n\n    roots = []\n    stars = []\n    gratings = []\n    x_ords = []\n    y_ords = []\n    orders = []\n    lines = []\n    notes = []\n\n    for row in input_table:\n        root = row[\"root\"]\n        path = row[\"path\"]\n        root_filter = input_table[\"root\"]==row[\"root\"]\n        # Imaging files shouldn't be processed\n        if row[\"filter\"][0] == 'F':\n            continue\n        # Files without spectra (i.e. have no \"extracted\" entry) shouldn't be processed.\n        if hasattr(row[\"extracted\"], \"mask\") and row[\"extracted\"].mask:\n            continue\n\n        spec_file = os.path.join(row['path'], row['extracted'])\n        if not os.path.isfile(spec_file):\n            # look for default extracted file\n            extracted_name = \"{}_{}_x1d.fits\".format(row['root'], row['target'])\n            print(\"Extracted Name: {}\".format(extracted_name))\n            extracted_dest = os.path.join(spec_dir, extracted_name)\n            print(\"Extracted File: {}\".format(extracted_dest))\n            \n            if os.path.isfile(extracted_dest):\n                spec_file = extracted_dest\n                extracted_value = os.path.join(spec_name, extracted_name)\n                input_table['extracted'][root_filter] = extracted_value\n                row['extracted'] = extracted_value\n            else:\n                msg = \"{}: Unable to find extracted spectrum '{}'. Extracting.\"\n                print(msg.format(task, row['extracted']))\n                extract_table = input_table[input_table['root']==row['root']]\n                output_row = reduce(extract_table, **kwargs)\n                for item in ['path', 'extracted', 'xc', 'yc', 'xerr', 'yerr']:\n                    input_table[item][root_filter] = output_row[item][0]\n                    row[item] = output_row[item][0]\n                spec_file = os.path.join(output_row['path'][0], \n                                         output_row['extracted'][0])\n                if not os.path.isfile(spec_file):\n                    msg = \"{}: {}: ERROR: EXTRACTION FAILED. SKIPPING ROW\"\n                    print(msg.format(task, row['root']))\n                    continue\n        # END search for the 1d extracted spectrum.\n\n        if verbose:\n            print(\"{}: reducing {}\".format(task, root))\n            print(\"\\tpath is {}\".format(path))\n            print(\"\\textracted is {}\".format(row[\"extracted\"]))\n            print(\"\\tfile is {}\".format(spec_file))\n            print(\"\\trow: \")\n            print(row)\n        star = row[\"target\"]\n        grat = row[\"filter\"]\n        preamble = \"wlmeas: {} ({}) ({})\".format(root, grat, star)\n        with fits.open(spec_file) as inf:\n            wl = inf[1].data['wavelength']\n            net = inf[1].data['net']\n            dq = inf[1].data['eps'].astype(np.uint32)\n            y_fit = inf[1].data['y_fit']\n            if \"xzorder\" in inf[0].header:\n                zxpos = inf[0].header['xzorder']\n            else:\n                zxpos = inf[0].header['xactual']\n            if \"yzorder\" in inf[0].header:\n                zypos = inf[0].header['yzorder']\n            else:\n                zypos = inf[0].header['yactual']\n\n        # Bad DQ values are 256 (saturated), 516 (FF glitches),\n        # and 32 (CTE tail) as per Table 2.5\n        bad_dq = np.where((dq & (32|256|512)) != 0)\n        good_dq = np.where((dq & (32|256|512)) == 0)\n\n        name = row['root'][5:9]\n\n        if grat == 'G102':\n            wrang = [8900., 11100.]\n        elif grat == 'G141':\n            wrang = [10800., 17500.]\n        else:\n            raise ValueError(\"Unknown Grating/Filter {}\".format(grat))\n\n        pnvel = 0. # radial velocity            \n        target_star = find_star_by_name(row['target'])\n        if target_star is not None:\n            pnvel = target_star['radial_velocity']\n\n        wrud = pn_ref_table['wavelength'] * (1. + pnvel/consts.c.to('km/s').value)\n        wlref = wl_vac * (1. + pnvel/consts.c.to('km/s').value)\n\n        for iord in [-1, 1, 2]:\n\n            dlam = fwhm[grat][iord]\n\n            # 3rd order 10830 at 32490 dominates 2nd order beyond ~16245\n            # (32490/2)\n            if iord == 2 and grat == 'G141':\n                wrang[1] = 13000.\n\n            xline = wlref * 0.\n\n            line_dict = {}\n            note_dict = {}\n\n            for ilin in range(len(wlref)):\n                wv = wl_vac[ilin]\n                wl_line = wl/iord\n                wlr = wlref[ilin]\n\n                # All of these indicate that the line we're looking for isn't\n                # in the order we're looking at.\n                if wrang[1] > max(wl_line) or wv < wrang[0] or wv > wrang[1]:\n                    continue\n\n                # smoothed lines\n                smorud = smooth_model(wrud, pn_ref_table['flux'], dlam)\n                if grat == 'G102':\n                    dw = 150/abs(iord)\n                else:\n                    dw = 250/abs(iord)\n\n                xgdrud = np.where((wrud > wlr - dw) & (wrud < wlr + dw))\n\n                xgood = np.where((wl/iord > wlr - dw) & (wl/iord < wlr + dw))\n\n                min_x = wl[np.min(xgood)] - 50\n                net_min = np.min(net[xgood])\n                max_x = wl[np.max(xgood)] + 50\n                net_max = np.min(net[xgood])\n\n                if show_plots:\n                    wl_good = np.where((wl > min_x-1000.) & (wl < max_x+1000.))\n\n                    fig = plt.figure()\n                    ax = fig.add_subplot(111)\n                    title_str = \"{} {} order={} line={} Search Range\"\n                    ax.set_title(title_str.format(grat, root, iord, wlr))\n                    plt.plot(wl[wl_good], net[wl_good])\n                    plt.plot([min_x, min_x], [net_min*0.5, net_max*1.5])\n                    plt.plot([max_x, max_x], [net_min*0.5, net_max*1.5])\n                    plt.show()\n\n                fit_status = \"auto\"\n                cmd = \"unknown\"\n                maxpos = np.argmax(net[xgood])\n                bad = np.where(dq[maxpos-1:maxpos+2] & (32|256|512) != 0)\n                if len(bad) > 0:\n                    nbad = len(bad[0])\n\n                # This case handles the very bright 10830A line falling in\n                #   the first order\n                if ilin == 2 and iord == 1:\n                    xcentr, ycentr = wlimaz(root, y_fit, wl, path, verbose)\n                    xline[2] = xcentr\n                    fit_status = \"ima\"\n\n                if nbad > 0 and xline[ilin] == 0.:\n                    print(\"WARNING: Centred using bad DQ\")\n\n                if root in issues:\n                    siord = str(iord)\n                    silin = str(ilin)\n                    if siord in issues[root]:\n                        if silin in issues[root][siord]:\n                            xline[ilin] = float(issues[root][siord][silin][\"xcentr\"])\n                            fit_status = \"hardcoded\"\n\n                # Only do the centroiding if the line hasn't been set\n                #   to a value yet.\n                if xline[ilin] == 0 or fit_status == \"ima\":\n                    xmin = np.min(xgood)\n                    xmax = np.max(xgood)\n                    search_range = (np.max(xgood) - np.min(xgood))/5\n                    cont_low = np.where((xpx >= xmin) & (xpx <= xmin + search_range))\n                    cont_hi = np.where((xpx >= xmax - search_range) & (xpx <= xmax))\n                    cont = (np.mean(net[cont_low]) + np.mean(net[cont_hi]))/2\n                    xcentr, fit = linecen(xgood[0], net[xgood], cont)\n                    if fit == \"good\" or xline[ilin] == 0:\n                        xline[ilin] = xcentr\n                        if fit_status == \"ima\":\n                            fit_status = \"good (ima)\"\n                        else:\n                            fit_status = fit\n\n\n                cmd = {\"choice\": \"unknown\", \"fit_status\": fit_status, \"msg\": \"\",\n                       \"finished\": False, \"submitted\": False}\n\n                if show_plots or ((\"good\" not in cmd[\"fit_status\"]) and \\\n                                  (\"hardcoded\" not in cmd[\"fit_status\"])):\n                \n                    while not cmd[\"finished\"]:\n    \n                        cmd[\"submitted\"] = False\n    \n                        fig, ax = plt.subplots()\n                        fig.subplots_adjust(bottom=0.2)\n    \n                        title_str = \"{} {} order={} line={}\"\n                        ax.set_title(title_str.format(grat, root, iord, wlr))\n                        xrud = tabinv((wl/iord), wrud[xgdrud])\n                        min_y = 0.\n                        max_y = np.max(net[xgood])*1.1\n#                         plt.plot(xrud, smorud[xgdrud], linestyle='--', label='WFC3 FWHM')\n                        plt.scatter(wl[good_dq], net[good_dq], label='Good DQ')\n                        plt.scatter(wl[bad_dq], net[bad_dq], label='Bad DQ')\n                        if cmd[\"fit_status\"] in [\"custom\", \"rejected\"]:\n                            x_int = np.floor(cmd[\"choice\"]).astype(np.int32)\n                            xwl = wl[x_int] + (cmd[\"choice\"]-x_int)*(wl[x_int+1]-wl[x_int])\n                        else:\n                            x_int = np.floor(xcentr).astype(np.int32)\n                            xwl = wl[x_int] + (xcentr-x_int)*(wl[x_int+1]-wl[x_int])\n                        if cmd[\"fit_status\"] == \"good\" or cmd[\"fit_status\"] == \"good (ima)\":\n                            plt.plot([xwl, xwl], [0., 1.e10], color='green', label='Fit')\n                        elif cmd[\"fit_status\"] == \"bad\" or cmd[\"fit_status\"] == \"rejected\":\n                            plt.plot([xwl, xwl], [0., 1.e10], color='red',\n                                     label='Bad Fit, Rejected Fit, or Not Found')\n                        elif cmd[\"fit_status\"] == \"ima\":\n                            plt.plot([xwl, xwl], [0., 1.e10], color='blue',\n                                     label='IMA zeroth read.')\n                        elif cmd[\"fit_status\"] == \"hardcoded\":\n                            plt.plot([xwl, xwl], [0., 1.e10], color='grey',\n                                     label='Hardcoded from Known Issues.')\n                        elif cmd[\"fit_status\"] == \"custom\":\n                            plt.plot([xwl, xwl], [0., 1.e10], color='grey',\n                                     label='User Custom')\n                        else:\n                            plt.plot([xwl, xwl], [0., 1.e10], color='red',\n                                     label='UNKNOWN FIT')\n                        plt.xlim(min_x, max_x)\n                        plt.ylim(min_y, max_y)\n                        plt.legend()\n\n                        text_axes = fig.add_axes([0.75, 0.05, 0.15, 0.075])\n                        msg = \"Empty to accept fit, X to reject all fits, Wavelength \"\n                        msg += \"for custom fit:\"\n                        text_box = TextBox(text_axes, msg, initial=cmd[\"msg\"])\n\n                        def submit(choice):\n                            if choice == \"\":\n                                cmd[\"finished\"] = True\n                                cmd[\"submitted\"] = True\n                            elif choice in ['x', 'X']:\n                                wl_choice = wl[xgood][(len(xgood[0])-1)//2]\n                                pix = np.searchsorted(wl, wl_choice)\n                                cmd[\"choice\"] = pix\n                                cmd[\"fit_status\"] = \"rejected\"\n                                cmd[\"submitted\"] = True\n                            else:\n                                try:\n                                    custom_wl = float(choice)\n                                    pix = np.searchsorted(wl, custom_wl)\n                                    remainder = (custom_wl - wl[pix])/(wl[pix+1]-wl[pix])\n                                    cmd[\"choice\"] = pix + remainder\n                                    cmd[\"fit_status\"] = \"custom\"\n                                    cmd[\"msg\"] = \"\"\n                                    cmd[\"submitted\"] = True\n                                except Exception as e:\n                                    msg = \"Enter nothing to accept fit, a floating point \"\n                                    msg += \"value to choose a custom fit, or 'X' to reject\"\n                                    msg += \"any fit.\"\n                                    cmd[\"msg\"] = msg\n                                    cmd[\"fit_status\"] = fit_status\n                                    cmd[\"submitted\"] = True\n                            plt.close(\"all\")\n\n                        text_box.on_submit(submit)\n\n                        def handle_close(evt):\n                            if not cmd[\"submitted\"]:\n                                submit(text_box.text)\n\n                        fig.canvas.mpl_connect('close_event', handle_close)\n                        if in_notebook:\n                            cmd[\"finished\"] = True\n                        plt.show()\n                # end if showing the plot.\n\n                if cmd[\"fit_status\"] == \"custom\":\n                    fit_status = \"custom\"\n                    xcentr = cmd[\"choice\"]\n                elif cmd[\"fit_status\"] == \"rejected\":\n                    fit_status = \"rejected\"\n                    xcentr = cmd[\"choice\"]\n\n                xline[ilin] = xcentr\n\n                line_dict[int(wv)] = xcentr\n                note_dict[int(wv)] = fit_status\n\n                if verbose:\n                    print(\"{}: Finished line {}\".format(preamble, wv))\n\n            roots.append(root)\n            stars.append(star)\n            gratings.append(grat)\n            x_ords.append(zxpos)\n            y_ords.append(zypos)\n            orders.append(iord)\n            lines.append(line_dict)\n            notes.append(note_dict)\n\n            if verbose:\n                print(\"{}: Finished order {}.\".format(preamble, iord))\n        if verbose:\n            print(\"{}: Finished obs {}\".format(preamble, root))\n    if verbose:\n        print(\"{}: finished wavelength measurement.\".format(preamble))\n\n    output_table = Table()\n    output_table['root'] = Column(data=roots)\n    output_table['star'] = Column(data=stars)\n    output_table['grism'] = Column(data=gratings)\n    output_table['X_0_ORD'] = Column(data=x_ords)\n    output_table['Y_0_ORD'] = Column(data=y_ords)\n    output_table['order'] = Column(data=orders)\n    for float_key in wl_vac:\n        key = int(float_key)\n        key_data = []\n        for line_dict in lines:\n            if key in line_dict:\n                key_data.append(line_dict[key])\n            else:\n                key_data.append(-1.)\n        note_data = []\n        for note_dict in notes:\n            if key in note_dict:\n                note_data.append(note_dict[key])\n            else:\n                note_data.append(\"\")\n        output_table[\"{}_pos\".format(key)] = Column(data=key_data, format='.3f')\n        output_table[\"{}_notes\".format(key)] = Column(data=note_data)\n\n    return output_table\n\n\ndef wlmake(input_table, wl_table, **kwargs):\n    \"\"\"\n    Derives a grism wavelength fit.\n    \n    Once planetary nebula emission lines have been located and fit, it is possible to use\n    them as input in creating a full wavelength fit for the grism detector. ABSCAL fits \n    the wavelength set with a linear slope and intercept, where both the slope and the \n    intercept have constant terms, linear terms in X, and linear terms in y.\n    \n    Once the fit has been calculated, the script prints out fit errors based on the input \n    exposures, and creates an output table with all of the fit terms. A separate fit is \n    derived for each order of each grism.\n\n    Parameters\n    ----------\n    input_table : abscal.common.exposure_data_table.AbscalDataTable\n        Table of exposures to be fit.\n    wl_table : astropy.table.Table\n        Output of wlmeas.\n    kwargs : dict\n        Dictionary of overrides to the default reduction parameters, and command-line \n        option selections.\n    \n    Returns\n    -------\n    output_table : astropy.table.Table\n        Table of wavelength fit values\n    \"\"\"\n    task = \"wfc3: grism: wlmake\"\n    default_values = get_defaults('abscal.common.args')\n    base_defaults = default_values | get_defaults(kwargs.get('module_name', __name__))\n    verbose = kwargs.get('verbose', base_defaults['verbose'])\n    show_plots = kwargs.get('plots', base_defaults['plots'])\n    if 'out_file' in kwargs:\n        out_file = kwargs['out_file']\n        out_dir, out_table = os.path.split(out_file)\n        if out_dir == '':\n            out_dir = os.getcwd()\n    elif 'out_dir' in kwargs:\n        out_dir = kwargs['out_dir']\n    else:\n        out_dir = os.getcwd()\n    spec_name = kwargs.get('spec_dir', base_defaults['spec_dir'])\n    spec_dir = os.path.join(out_dir, spec_name)\n    \n    if verbose:\n        print(\"Starting {}\\nInput data:\\n{}\".format(task, wl_table))\n\n    line_array = [9071, 9535, 10832, 12821, 16411] #16113, 16411]\n    visible_lines = {\n                        'G102': [9071, 9535, 10832],\n                        'G141': [10832, 12821, 16411] #16113, 16411]\n                    }\n    wl_vac = np.array([[ 9070.0,  9070.0,  9071.4,  9070.5],\n                       [ 9535.1,  9535.1,  9535.1,  9535.2],\n                       [10833.5, 10834.6, 10833.4, 10833.4],\n                       [12820.8, 12820.8, 12821.6, 12821.0],\n                       # WHERE IS 16113?\n#                       [],\n                       [16413.2, 16414.0, 16412.1, 16412.7]])\n\n    bad = np.where(wl_table['X_0_ORD'] == 0.)\n    if len(bad) > 0:\n        nbad = len(bad[0])\n    \n    results = {\n                'grism': [],\n                'order': [],\n                'b_constant': [],\n                'b_x': [],\n                'b_y': [],\n                'm_constant': [],\n                'm_x': [],\n                'm_y': []\n              }\n\n    for grism_index,grism in enumerate(['G102', 'G141']):\n        if verbose:\n            print(\"{}: starting grism {}\".format(task, grism))\n\n        mask = [g == grism for g in wl_table['grism']]\n        grism_table = wl_table[mask]\n\n        for iord in [-1, 1, 2]:\n            if verbose:\n                print(\"{}: {}: starting order {}\".format(task, grism, iord))\n            ord_mask = [o == iord for o in grism_table['order']]\n            current_table = grism_table[ord_mask]\n            xord_mask = [x > 0 for x in current_table['X_0_ORD']]\n            current_table = current_table[xord_mask]\n            emline_mask = []\n            for row in current_table:\n                is_any_valid = False\n                for col in [\"{}_pos\".format(l) for l in line_array]:\n                    if row[col] > 0:\n                        is_any_valid = True\n                emline_mask.append(is_any_valid)\n            current_table = current_table[emline_mask]\n            ngood = len(current_table)\n            if ngood <= 0:\n                continue\n            if verbose:\n                print(\"{}: {}: {}: Found {} good rows\".format(task, grism, iord, ngood))\n            dofil = current_table['root']\n            dostr = current_table['star']\n            doord = current_table['order'].data\n            dozx = current_table['X_0_ORD'].data\n            dozy = current_table['Y_0_ORD'].data\n            wl_index = grism_index + 2*(abs(iord) - 1)\n            results['grism'].append(grism)\n            results['order'].append(iord)\n\n            # Set up line offsets due to standard star radial velocity\n            radial_velocity = np.zeros((ngood,), dtype=np.float64)\n            rvc_p1 = np.zeros((ngood,), dtype=np.float64)\n            for i,row in enumerate(current_table):\n                star = find_star_by_name(row['star'])\n                radial_velocity[i] = star['radial_velocity']\n                rvc_p1[i] = 1 + star['radial_velocity']/consts.c.to('km/s').value\n            \n            good_fits = {}\n            good_lines = []\n            print(current_table)\n            for line in visible_lines[grism]:\n                print(\"Checking line {}\".format(line),end='')\n                good_fits[line] = 0\n                for row in current_table:\n                    notes_col = '{}_notes'.format(line)\n                    if ('good' in row[notes_col]) or ('custom' in row[notes_col]):\n                        good_fits[line] += 1\n                        print(\" good \",end='')\n                    else:\n                        print(\" bad \",end='')\n                print(\"{} good of {} \".format(good_fits[line], ngood),end='')\n                if good_fits[line] > 0.5*ngood:\n                    print(\"adding line {}.\".format(line))\n                    good_lines.append(line)\n                else:\n                    print(\"rejected.\")\n            nline = len(good_lines)\n            low_line, high_line = min(good_lines), max(good_lines)\n            low_idx, high_idx = line_array.index(low_line), line_array.index(high_line)\n            doxi = np.zeros((ngood, nline), dtype=np.float64)\n            for i,line in enumerate(good_lines):\n                doxi[:,i] = current_table['{}_pos'.format(line)].data\n            dox1 = current_table['{}_pos'.format(low_line)].data\n            dox2 = current_table['{}_pos'.format(high_line)].data\n            ref_line = np.full((ngood,), wl_vac[low_idx, wl_index])\n            disp = (wl_vac[high_idx, wl_index] - wl_vac[low_idx, wl_index]) * doord\n            disp *= rvc_p1/(dox2 - dox1)\n            ref_line *= rvc_p1\n\n            # Make polynomial fit to WL = b + m*delpx, spit out coefficient, and\n            #   iterate to check results. Where delpx = x - x0, b = b1 + b2*x + b3*y,\n            #   m = m1 + m2*x + m3*y, x0 is the z-order reference pixel location.\n            xpx = np.arange(1014, dtype=np.float64)\n            fit_good = np.where(((dox1 > 0.) & (dox2 > 0.)))\n            n_fit_good = len(fit_good[0])\n\n            #b3rd is 3rd element of b array. First 2 are X,Y of z-order.\n            b3rd = ref_line[fit_good]*iord\n            b3rd -= disp[fit_good]*(dox1[fit_good] - dozx[fit_good])\n            b = np.zeros((n_fit_good,3), dtype=np.float64)\n            b[:,0] = dozx[fit_good]\n            b[:,1] = dozy[fit_good]            \n            m = deepcopy(b)\n            b[:,2] = b3rd[:]\n            if verbose:\n                print(\"b matrix is {}\".format(b))\n            b_fit,_,_,_ = lstsq(np.c_[b[:,0], b[:,1], np.ones(b.shape[0])], b[:,2])\n            b_x, b_y, b_const = b_fit\n            bfit = [b_const + b_x*x + b_y*y for x,y in zip(b[:,0], b[:,1])]\n            results['b_constant'].append(b_const)\n            results['b_x'].append(b_x)\n            results['b_y'].append(b_y)\n            bval = b_const + b_x*506 + b_y*506 # b at (x,y) = (506,506)\n            xr = [np.min(dozx[fit_good]), np.max(dozx[fit_good])] # range of 0-order points\n            if verbose:\n                print(\"{}: {}: {}: Z0 x-range is {}\".format(task, grism, iord, xr))\n                print(\"\\t b1={}, b2={}, b3={}\".format(b_const, b_x, b_y))\n            m[:,2] = disp[fit_good]\n            if verbose:\n                print(\"m matrix is {}\".format(m))\n            m_fit,_,_,_ = lstsq(np.c_[m[:,0], m[:,1], np.ones(m.shape[0])], m[:,2])\n            m_x, m_y, m_const = m_fit\n            mfit = [m_const + m_x*x + m_y*y for x,y in zip(m[:,0], m[:,1])]\n            results['m_constant'].append(m_const)\n            results['m_x'].append(m_x)\n            results['m_y'].append(m_y)\n            mval = m_const + m_x*xpx * m_y*506\n            mval = m_const + m_x*xpx * m_y*106\n            mval = m_const + m_x*xpx * m_y*906\n            if verbose:\n                print(\"\\t m1={}, m2={}, m3={}\".format(m_const, m_x, m_y))\n            \n            line = []\n            for em_line in visible_lines[grism]:\n                line.append(wl_vac[line_array.index(em_line), wl_index])\n\n            for ilin in range(nline):\n                line_good = np.where((doord == iord) & (dox1 > 0.) & (dox2 > 0) & \\\n                                     (doxi[:,ilin] > 0))\n                n_line_good = len(line_good[0])\n                if n_line_good <= 0:\n                    break # in theory break from the entire order, but we do what we can.\n                wlerr = np.zeros((n_line_good,), np.float64)\n                if verbose:\n                    msg = \"{}: {}: {}: File      Xmeas (px)  Xfit   err (A)\"\n                    print(msg.format(task, grism, iord))\n                for igd in range(n_line_good):\n                    indx = line_good[0][igd]\n                    row = current_table[indx]\n                    bval = b_const + b_x*dozx[indx] + b_y*dozy[indx]\n                    mval = m_const + m_x*dozx[indx] + m_y*dozy[indx]\n                    wnew = bval + mval*(xpx - dozx[indx])\n                    xfit = tabinv(wnew, line[ilin]*iord*rvc_p1[indx])\n                    wlerr[igd] = (doxi[indx,ilin] - xfit)*mval\n                    if verbose:\n                        msg = \"                 {} {:8.2f} {:8.2f} {:8.2f} YZO={:8.2f}\"\n                        print(msg.format(row['root'], doxi[indx,ilin], xfit[0], \n                                         wlerr[igd], dozy[indx]))\n                if verbose:\n                    msg = \"Line, rms (A) and avg={}, {}, {}, #Obs={}\"\n                    print(msg.format(line[ilin], np.std(wlerr), np.mean(wlerr), \n                                     n_line_good))\n            \n            dmeas = m[:,2]\n            bmeas = b[:,2]\n            xpos, ypos = dozx, dozy\n            berr = bmeas - bfit\n            merr = dmeas - mfit\n            if verbose:\n                msg = \"{}: {}: {}: File     ZX (px)    ZY    b fit (A)     bmeas     berr\"\n                print(msg.format(task, grism, iord))\n                for i in range(ngood):\n                    row = current_table[i]\n                    msg = \"               {} {:8.2f} {:8.2f} {:8.2f} {:8.2f}  {:8.2f}\"\n                    print(msg.format(row['root'], xpos[i], ypos[i], bfit[i], bmeas[i], \n                                     berr[i]))\n                print(\"b rms={}\".format(np.std(bmeas-bfit)))\n                print(\"m rms={}\".format(np.std(dmeas-mfit)))\n            \n            if show_plots:\n                for igd in range(ngood):\n                    row = current_table[igd]\n                    full_row = input_table[input_table['root']==row['root']]\n                    full_file = os.path.join(full_row[\"path\"].data[0], \n                                             full_row[\"extracted\"].data[0])\n                    if not os.path.isfile(full_file):\n                        full_name = \"{}_{}_x1d.fits\".format(row['root'], \n                                                            full_row['target'].data[0])\n                        full_file = os.path.join(spec_dir, full_name)\n                    if os.path.isfile(full_file):\n                        star = find_star_by_name(row['star'])\n                        rvc = star['radial_velocity']/consts.c.to('km/s').value\n                        with fits.open(full_file) as inf:\n                            wl = inf[1].data['wavelength']\n                            net = inf[1].data['net']\n                            angle = inf[0].header[\"angle\"]\n                \n                        fig, ax = plt.subplots()\n                        title_str = \"{} {} order={} Fitted vs. Measured Line Positions\"\n                        ax.set_title(title_str.format(row['root'], grism, iord))\n\n                        bval = b_const + b_x*dozx[igd] + b_y*dozy[igd]\n                        mval = m_const + m_x*dozx[igd] + m_y*dozy[igd]\n                        wnew = bval + mval*(xpx - dozx[igd])\n                        plt.plot(wl/iord, net, 'b', label='Initial Wavelength Estimate')\n                        plt.plot(wnew/iord, net, 'g', label='Fitted Wavelength')\n                        for i in range(len(wl_vac[:,wl_index])):\n                            plt.plot([wl_vac[i,wl_index], wl_vac[i,wl_index]*(1+rvc)],\n                                     [0., 1.e5], 'r', linestyle='dashed')\n                        msg = \"Zero-order at ({:.2f},{:.2f})\"\n                        plt.figtext(0.2,0.2,msg.format(dozx[igd], dozy[igd]))\n                        plt.legend()\n                        # Figure out X and Y limits\n                        if grism == \"G102\":\n                            wave_low, wave_high = 9000, 11000\n                        elif grism == \"G141\":\n                            wave_low, wave_high = 10500, 17500\n                        plt.xlim(wave_low, wave_high)\n                        ind_low = np.searchsorted(wnew/iord, wave_low, side='left')\n                        ind_high = np.searchsorted(wnew/iord, wave_high, side='right')\n                        net_region = net[ind_low:ind_high]\n                        plt.ylim(0, np.max(net_region)*1.1)\n                        plt.show()\n                \n                        if verbose:\n                            print(\"{}: {}: {}: {}\".format(task, grism, iord, row['root']))\n                            print(\"b={}, m={}\".format(bval, mval))\n                            print(\"Measured Dispersion = {}\".format(dmeas[igd]))\n                            print(\"Measured b={}\".format(bmeas[igd]))\n                            print(\"b,m errors={}, {}\".format(bval-bmeas[igd], mval-dmeas[igd]))\n                            print(\"Angle={}\".format(angle))\n            # done interactive plot\n        # DONE ORDER LOOP\n    # DONE GRISM LOOP\n\n    output_table = Table()\n    output_table['grism'] = Column(data=results['grism'])\n    output_table['order'] = Column(data=results['order'])\n    output_table['b_constant'] = Column(data=results['b_constant'])\n    output_table['b_x'] = Column(data=results['b_x'])\n    output_table['b_y'] = Column(data=results['b_y'])\n    output_table['m_constant'] = Column(data=results['m_constant'])\n    output_table['m_x'] = Column(data=results['m_x'])\n    output_table['m_y'] = Column(data=results['m_y'])\n\n    return output_table\n\n\ndef wl_offset(input_table, **kwargs):\n    \"\"\"\n    Derives wavelength offsets for white dwarf exposures.\n    \n    Cross-correlates flux and net from white dwarf exposures against one another to derive \n    offsets\n\n    Parameters\n    ----------\n    input_table : abscal.common.exposure_data_table.AbscalDataTable\n        Table of exposures to have offsets generated.\n    kwargs : dict\n        Dictionary of overrides to the default reduction parameters, and command-line \n        option selections.\n    \n    Returns\n    -------\n    output_table : astropy.table.Table\n        Updated table\n    \"\"\"\n    task = \"wfc3: grism: wloffset\"\n    default_values = get_defaults('abscal.common.args')\n    base_defaults = default_values | get_defaults(kwargs.get('module_name', __name__))\n    verbose = kwargs.get('verbose', base_defaults['verbose'])\n    show_plots = kwargs.get('plots', base_defaults['plots'])\n    if 'out_file' in kwargs:\n        out_file = kwargs['out_file']\n        out_dir, out_table = os.path.split(out_file)\n        if out_dir == '':\n            out_dir = os.getcwd()\n    elif 'out_dir' in kwargs:\n        out_dir = kwargs['out_dir']\n    else:\n        out_dir = os.getcwd()\n    spec_name = kwargs.get('spec_dir', base_defaults['spec_dir'])\n    spec_dir = os.path.join(out_dir, spec_name)\n    \n    return input_table\n\n\ndef additional_args(**kwargs):\n    \"\"\"\n    Additional command-line arguments. \n    \n    Provides additional command-line arguments that are unique to the wavelength fitting \n    process.\n    \n    Returns\n    -------\n    additional_args : dict\n        Dictionary of tuples in the form (fixed,keyword) that can be passed to an argument \n        parser to create a new command-line option\n    \"\"\"\n    module_name = kwargs.get('module_name', __name__)\n    base_defaults = get_defaults(module_name)\n\n    additional_args = {}\n\n    table_help = \"The input metadata table to use.\"\n    table_args = ['table']\n    table_kwargs = {'help': table_help}\n    additional_args['table'] = (table_args, table_kwargs)\n\n    plots_help = \"Include result plots while running.\"\n    plots_args = [\"-p\", \"--plots\"]\n    plots_kwargs = {'dest': 'plots', 'action': 'store_true', \n                    'default': base_defaults['plots'], 'help': plots_help}\n    additional_args['plots'] = (plots_args, plots_kwargs)\n\n    return additional_args\n\n\ndef parse_args(**kwargs):\n    \"\"\"\n    Parse command-line arguments.\n    \n    Gets the custom arguments from wavelength fitting, and passes them to the common \n    command-line option function.\n    \n    Returns\n    -------\n    res : namespace\n        parsed argument namespace\n    \"\"\"\n    description_str = 'Process files from metadata table.'\n    default_out_file = kwargs.get('default_input_file', 'dirirstare.log')\n    default_in_file = kwargs.get('default_input_file', 'dirirstare.log')\n\n    args = additional_args(**kwargs)\n\n    res = parse(description_str, default_out_file, args, **kwargs)\n\n    if res.paths is not None:\n        if \",\" in res.paths:\n            res.paths = res.paths.split(\",\")\n        else:\n            res.paths = [res.paths]\n    else:\n        res.paths = []\n\n    if res.table is None:\n        res.table = \"dirtemp.log\"\n\n    if len(res.paths) == 0:\n        res.paths.append(os.getcwd())\n\n    return res\n\n\ndef main(do_measure=True, do_make=True, **kwargs):\n    \"\"\"\n    Run the wavelength fitting function(s).\n    \n    Runs the wavelength fitting function(s) if called from the command line, with \n    command-line arguments added in. Can run wlmeas, wlmake, or both.\n    \n    Parameters\n    ----------\n    do_measure : bool, default True\n        Run wlmeas function\n    do_make : bool, default, True\n        Run wlmake function\n    kwargs : dict\n        Dictionary of parameters to override when running.\n    \"\"\"\n    kwargs['default_output_file'] = 'wlmeastmp.log'\n    parsed = parse_args(**kwargs)\n\n    for key in kwargs:\n        if hasattr(parsed, key):\n            setattr(parsed, key, kwargs[key])\n\n    input_table = AbscalDataTable(table=parsed.table,\n                                  duplicates='both',\n                                  search_str='',\n                                  search_dirs=parsed.paths)\n\n    measure_fname = parsed.out_file\n    if do_measure:\n        wl_calib_table = wlmeas(input_table, **vars(parsed), **kwargs)\n        wl_calib_table.write(measure_fname, format='ascii.ipac', overwrite=True)\n    else:\n        wl_calib_table = Table.read(measure_fname, format='ascii.ipac')\n    \n    if do_make:\n        final_wave_table = wlmake(input_table, wl_calib_table, **vars(parsed), **kwargs)\n        (table_file, table_ext) = os.path.splitext(parsed.out_file)\n        final_fname = table_file + \"_final\" + table_ext\n        final_wave_table.write(final_fname, format='ascii.ipac', overwrite=True)\n    # Done.\n\n\nif __name__ == \"__main__\":\n    main(module_name='abscal.wfc3.reduce_grism_wavelength')\n", "meta": {"hexsha": "c3895c63c652416b7812f55eb8c677ac8ca195bb", "size": 44364, "ext": "py", "lang": "Python", "max_stars_repo_path": "abscal/wfc3/reduce_grism_wavelength.py", "max_stars_repo_name": "york-stsci/ABSCAL", "max_stars_repo_head_hexsha": "89b43bf5a02c56936e562287db27bf49a69ae406", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "abscal/wfc3/reduce_grism_wavelength.py", "max_issues_repo_name": "york-stsci/ABSCAL", "max_issues_repo_head_hexsha": "89b43bf5a02c56936e562287db27bf49a69ae406", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "abscal/wfc3/reduce_grism_wavelength.py", "max_forks_repo_name": "york-stsci/ABSCAL", "max_forks_repo_head_hexsha": "89b43bf5a02c56936e562287db27bf49a69ae406", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-06T14:38:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T14:38:38.000Z", "avg_line_length": 41.7740112994, "max_line_length": 95, "alphanum_fraction": 0.5170183031, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 10659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.30404168757891037, "lm_q1q2_score": 0.16740759261071245}}
{"text": "import numpy as np\nfrom .load_sed import *\n\nclass Simplemock():\n    \"\"\"\n    Calculate flux through a filter for all stellar particle.\n\n    Example\n    >>> from general import defaults\n    >>> import quick_mock\n    >>> import galaxymodule\n    >>> dfl = defaults.Default()\n    >>> nout = 312#782 # 312\n    >>> s = load.sim.Sim(nout=nout)\n    >>> gcat = tree.halomodule.Halo(nout=nout, is_gal=True)\n    >>> gg = galaxymodule.rd_GM.Gal(nout, catalog=gcat.data[21].copy(), info=s.info)\n    >>> gg.debug=False\n    >>> make_gal.mk_gal(gg)\n    >>> from galaxymodule import quick_mock as qmc\n    >>> MockSED = qmc.Simplemock(repo=dfl.dir_repo+'sed/')\n    >>> gg.star.Flux_u= MockSED.get_flux(star=gg.star, filter_name='u')\n    >>> gg.star.Flux_g= MockSED.get_flux(star=gg.star, filter_name='g')\n    >>> gg.star.Flux_r= MockSED.get_flux(star=gg.star, filter_name='r')\n    >>> gg.star.Flux_i= MockSED.get_flux(star=gg.star, filter_name='i')\n    >>> gg.star.Flux_z= MockSED.get_flux(star=gg.star, filter_name='z')\n    >>> Fluxs = [gg.star.Flux_u,\n                 gg.star.Flux_g,\n                 gg.star.Flux_r,\n                 gg.star.Flux_i,\n                 gg.star.Flux_z]\n    >>> quick_mock.draw(Fluxs, gg.star[\"x\"], gg.star[\"y\"], suffix=\"face\")\n    >>> quick_mock.draw(Fluxs, gg.star[\"x\"], gg.star[\"z\"], suffix=\"edge\")\n\n    TODO\n\n    t_univ\n\n    interpolation outside range. (metallcity < 0.0004)\n\n    \"\"\"\n    def __init__(self, repo=\"/home/hoseung/Work/pyclusterevol/repo/sed/\",\n                 filter_system=\"SDSS\",\n                 sed_model=\"bc03yy\",\n                 info=None,\n                 load=True,\n                 imf = \"Salpeter\"):\n        self.filter_system = filter_system\n        self.repo = repo\n        self.sed_model = sed_model\n        self.IMF = imf\n        self.info = info\n        if load is True:\n            self.load_filters()\n            self.load_SED_wavelength()\n            self.load_SED_all()\n\n    def load_filters(self):\n        if self.filter_system == \"SDSS\":\n            filter_lambda, filter_u, filter_g, filter_r, filter_i, filter_z = \\\n                np.genfromtxt(self.repo + \"filter_sdss.dat\",\n                                skip_header=1, unpack=True)\n\n            self.filters = {\"lambda\":filter_lambda,\n                            \"u\":filter_u,\n                            \"g\":filter_g,\n                            \"r\":filter_r,\n                            \"i\":filter_i,\n                            \"z\":filter_z}\n\n    def load_SED_wavelength(self):\n        if self.sed_model == \"bc03yy\":\n            self.sed_wavelength = np.genfromtxt(self.repo + \"lambda.dat\")\n\n    def load_SED_all(self):\n        \"\"\"\n        Full SEDs are just a few tens of MB.\n        \"\"\"\n        if self.sed_model == \"bc03yy\":\n            self.metal_points = np.array([0.0004, 0.001, 0.004, 0.01, 0.02, 0.04])\n            # age points in tables.\n            self.age_points = np.genfromtxt(self.repo+\"ages_yybc.dat\") # in Gry unit\n            self.SEDs = np.zeros((6, 221, 1221))\n\n            for i, metal in enumerate(self.metal_points):\n                self.SEDs[i,:,:] = np.genfromtxt(self.repo +\n                                            \"bc03_yy_{:.4f}\".format(metal)).reshape(221, 1221)\n        elif self.sed_model == \"bc\":\n            all_sed=[]\n            for fn in glob(\"./BC03_v03/bc03/models/Padova2000/salpeter/*lr*.ised*.gz\"):\n                bc03 = Sed_block(fn)\n                all_sed.append(bc03)\n                print(bc03.isochrone)\n                print(bc03.X, bc03.Y, bc03.Z)\n\n            SED = Sed(all_sed)\n            self.SEDs\n\n        else:\n            print(\"Sorry, Only bc03 is implemented.\")\n\n    def get_flux(self, star,\n                 cell=None,\n                 simple=False,\n                 metal_lower_cut = True,\n                 filter_name='r',\n                 quick=False,\n                 speed_check=False):\n        \"\"\"\n        calculate SED of each particle.\n        If cell is not None, attenuate flux accordingly.\n\n        parameters\n        ----------\n        quick : False\n            If True, reduce wavelength point of sed and filter significantly.\n            This still gives reasonable value.\n\n        speed_check : False\n            If True, measure the time taken. Only for optimizing purpose.\n        \"\"\"\n        if speed_check:\n            from time import time\n            t0 = time()\n\n        Lum_sun = 3.826e33\n        # BC2003 is in unit of L_sun Ang-1, where L_sun = Lum_sun.\n\n        starmetal = star[\"metal\"].copy() # Is the original array modified?\n        starmetal[starmetal > 0.04] = 0.0399999 # a few stars have higher metallicity\n        if metal_lower_cut:\n            # No star with metallicity lower than the lowest table.\n            starmetal[starmetal < min(self.metal_points)] = min(self.metal_points) * 1.0001\n\n        locate_metal = np.digitize(starmetal, self.metal_points)-1 # GOOD\n        relevant_metals = self.metal_points[:max(locate_metal)+2]\n        nmetals = len(relevant_metals)\n\n        # Star Age\n        starage = star[\"age\"] # the field name \"time\" should have been changed to \"age\"\n\n        locate_age = np.digitize(starage, self.age_points)-1 # GOOD\n        relevant_ages = self.age_points[:max(locate_age)+2]\n        nages = len(relevant_ages)\n        if speed_check: t1 = time() #\n\n        ### Filter optimization. #################################################\n        # Pick one\n        this_filter = self.filters[filter_name]\n\n        # band range\n        i_filter_pos = this_filter > 0\n        if quick:\n            this_filter = this_filter[i_filter_pos][::10]\n            filter_lambda_this_band = self.filters[\"lambda\"][i_filter_pos][::10]\n        else:\n            this_filter = this_filter[i_filter_pos]\n            filter_lambda_this_band = self.filters[\"lambda\"][i_filter_pos]\n\n        lambda_min_this_band = min(filter_lambda_this_band)\n        lambda_max_this_band = max(filter_lambda_this_band)\n\n        if quick:\n            n_compress = 20\n            sed_org = self.sed_wavelength\n            sed_wavelength = self.sed_wavelength[::n_compress]\n        else:\n            sed_wavelength = self.sed_wavelength\n\n        i_lambda_min = np.argmax(sed_wavelength > lambda_min_this_band) -1\n        i_lambda_max = np.argmax(sed_wavelength > lambda_max_this_band)\n\n        # Only a small part of SED is needed.\n        # To compute d_lambda, one additional lambda point is desired.\n        # Could be forward / backward / midpoint and so on.\n        # let me take backward as fractional chnge in d_lambda is less in longer wavelength\n        # Well.. actually I don't care..\n        # d_lambda = wavelength[:-1] - wavelength[1:]\n        wavelength = sed_wavelength[i_lambda_min:i_lambda_max+2] # why +2?\n        n_wavelength = len(wavelength)-1#i_lambda_max - i_lambda_min + 1\n\n        ##### Caclulate band flux #################\n        # Load only necessary data\n        # Load all once, keep under the class and copy a part of it when needed here.\n        seds = np.zeros((nmetals, nages, n_wavelength)) # metal age lambda\n        if self.sed_model == \"bc03yy\":\n            for i, metal in enumerate(relevant_metals):\n                if quick:\n                    for j in range(seds.shape[1]):\n                        seds[i,j,:] = np.interp(wavelength[:-1],\n                                            sed_org,\n                                            self.SEDs[i,j,:])\n                else:\n                    seds[i,:,:] = self.SEDs[i,:nages, i_lambda_min:i_lambda_max+1]\n\n        if speed_check: t2 = time() # all set up\n\n        # All are array calculations.\n        # interpolation weight\n        dl_m = (starmetal - relevant_metals[locate_metal] ) / \\\n                                     (relevant_metals[locate_metal+1] - relevant_metals[locate_metal])\n        dr_m = (relevant_metals[locate_metal+1] - starmetal) / \\\n                                     (relevant_metals[locate_metal+1] - relevant_metals[locate_metal])\n        dl_a = (starage - relevant_ages[locate_age] )   / \\\n                                     (relevant_ages[locate_age+1] - relevant_ages[locate_age])\n        dr_a = (relevant_ages[locate_age+1] - starage ) / \\\n                                     (relevant_ages[locate_age+1] - relevant_ages[locate_age])\n\n        if speed_check: t3 = time() # done first easy calculation\n\n        # 2D linear interpolation\n        # weight * SED.\n        Flux =  np.multiply( (dr_m * dr_a), seds[locate_metal, locate_age,:].T).T +\\\n                np.multiply( (dl_m * dr_a), seds[locate_metal + 1, locate_age,:].T).T +\\\n                np.multiply( (dr_m * dl_a), seds[locate_metal, locate_age + 1, :].T).T +\\\n                np.multiply( (dl_m * dl_a), seds[locate_metal + 1, locate_age + 1,:].T).T\n\n        if speed_check: t4 = time()\n        # Convolve filter\n        # Wavelengths at which filter function are defined are different from the SED wavelength points.\n        # Interpolate filter function on SED points.\n        filter_in_sed_wavelengths = np.interp(wavelength, filter_lambda_this_band, this_filter)\n        Flux = np.multiply(filter_in_sed_wavelengths[:-1] * wavelength[-1], Flux)#\\\n        div = np.multiply(filter_in_sed_wavelengths[:-1], wavelength[-1])\n\n        if speed_check: t5 = time()\n        # Need to multiply stellar mass\n\n        if cell is None or self.info is None or len(cell) == 0:\n            return np.sum(Flux, axis=1) / np.sum(div) * Lum_sun * star[\"m\"]\n        else:\n            #print(len(cell))\n            colden = get_star_colden(star, cell) *self.info.unit_nH *self.info.unit_l / self.info.boxtokpc #* 1e3\n            try:\n                if colden == -1:\n                    return np.sum(Flux, axis=1) / np.sum(div) * Lum_sun * star[\"m\"]\n            except:\n                pass\n            #lams = np.linspace(1e3,1e4,1e3) # in Angstrom\n            waven = wavelength[:-1] * 1e-4 # in 1e-6 m\n\n            Es = 0.44#*EBV\n            # Hydrogen column number density\n            colden = colden/5.8e21  # -1mag per 5.8e21 Hydrogen.\n            tau = 0.4 * Es * np.outer(ext_curve_k(waven), colden)\n            # colden = N_star array.\n            # waven = N_wavelengths array\n            # tau = N_wave X N_star\n            # Flux = N_star X N_wave  ... (may be the other way around.)\n            #print(\"tau\", tau)\n            F_ext= [ff*np.power(10,(-1*tt)) for ff, tt in zip(Flux, tau.T)]\n\n            #print(\"before ext\", np.sum(Flux, axis=1))\n            #print(\"After ext\", np.sum(F_ext, axis=1))\n            if speed_check: \n                t6 = time()\n                print(\"age metal digitize {:.3f}\".format(t1-t0))\n                print(\"setup done {:.3f}\".format(t2-t0))\n                print(\"interpolation coefficient {:.3f}\".format(t3-t0))\n                print(\"flux {:.3f}\".format(t4-t0))\n                print(\"filter, flux, div {:.3f}\".format(t5-t0))\n                print(\"After dust attanuation {:.3f}\".format(t6-t0))\n            return np.sum(F_ext, axis=1) / np.sum(div) * Lum_sun * star[\"m\"]\n\n##################################################################\ndef flux2mag(flux,\n             gal,\n             x1=\"x\",\n             x2=\"y\",\n             filter_name = 'r',\n             gal_range=None,\n             Lum_dist = 400,\n             plate_scale = 0.24,\n             npixmax = 1200):\n    # Observation conndition\n    # in Mpc.\n    if gal_range is None:\n        gal_range = [[-gal.meta.rgal,gal.meta.rgal]]*2\n\n    npixx, npixy = get_npix(plate_scale, gal_range, Lum_dist, npixmax)\n\n    # Calculate Unit.\n    d_lum_10p = 3.0857e19 # lumminonsity distance of 10pc in cm\n    speed_of_light = 3e18 # angstrom / sec\n    kpc_to_cm = 3.0857e21\n    ldcm = Lum_dist * kpc_to_cm\n    inv_distance = 1/(4*np.pi * ldcm * ldcm)\n\n    band=BandSDSS()\n    # Additional factors to derive realistic flux values.\n\n    print(npixx, npixy)\n    Flux_map = np.histogram2d(gal.star[x1], gal.star[x2],\n               weights=flux,\n               bins=[npixx,npixy],\n               range=gal_range)[0]\n\n    Flux_map *= Lum_sun * 1e-2 * inv_distance\n    return - 2.5 * np.log10(Flux_map) \\\n           - 5. * np.log10(getattr(band, filter_name)[\"pivot_lambda\"]) \\\n           + 2.5 * np.log10(speed_of_light) -48.6\n\n\ndef get_npix(plate_scale, gal_range, Lum_dist, npixmax):\n    FOVx = (gal_range[0][1] - gal_range[0][0]) / (Lum_dist*1e3) * 180. / np.pi * 3600. # in arcsec\n    FOVy = (gal_range[1][1] - gal_range[1][0]) / (Lum_dist*1e3) * 180. / np.pi * 3600.\n    npixx= int(np.ceil(FOVx/plate_scale))\n    npixy= int(np.ceil(FOVy/plate_scale))\n\n    npixx = min([npixmax, npixx])\n    npixy = min([npixmax, npixy])\n\n    return (npixx, npixy)\n\nclass BandSDSS():\n    def __init__(self):\n        self.u = dict(pivot_lambda = 3557.0, name=\"u\")\n        self.g = dict(pivot_lambda = 4702.0, name=\"g\")\n        self.r = dict(pivot_lambda = 6175.0, name=\"r\")\n        self.i = dict(pivot_lambda = 7491.0, name=\"i\")\n        self.z = dict(pivot_lambda = 8946.0, name=\"z\")\n\ndef composite_rgb(x,y, weight_r, weight_g, weight_b,\n                  npix=100,\n                  multiply_r=1.3,\n                  multiply_g=1.1,\n                  multiply_b=1.0,\n                  log_scale = True,\n                  range=None):\n    import numpy as np\n    from PIL import Image\n\n    rgbArray = np.zeros((npix,npix,3))\n    rgbArray[..., 0] = np.histogram2d(x, y,\n               weights=weight_r, bins=npix, range=range)[0] * multiply_r\n    rgbArray[..., 1] = np.histogram2d(x,y,\n               weights=weight_g, bins=npix, range=range)[0] * multiply_g\n    rgbArray[..., 2] = np.histogram2d(x,y,\n               weights=weight_b, bins=npix, range=range)[0] * multiply_b\n\n    if log_scale:\n        rgbArray = np.log10(rgbArray+1)\n    rgbArray = rgbArray/rgbArray.max() * 255\n    #return rgbArray\n\n    img = Image.fromarray(rgbArray.astype('uint8'))\n\n    return img.rotate(90)\n    #img.save('myimg.jpeg')\n\ndef draw(gal,\n         x1=\"x\",\n         x2=\"y\",\n         suffix=\"edge\",\n         npix=200,\n         gal_range=None,\n         R=\"Flux_g\",\n         G=\"Flux_r\",\n         B=\"Flux_i\",\n         cr=1.0, cg=1.0, cb=3.0):\n    \"\"\"\n    Parameers\n    ---------\n    gal:\n\n    suffix:\n\n    npix:\n        default = 200\n    gal_range:\n        image 2d span in kpc.\n    \"\"\"\n\n    import numpy as np\n    import matplotlib.pyplot as plt\n    from matplotlib.colors import LogNorm\n\n    channel_r = getattr(gal.star, R)\n    channel_g = getattr(gal.star, G)\n    channel_b = getattr(gal.star, B)\n\n    if gal_range is None:\n        gal_range = [[-gal.meta.rgal,gal.meta.rgal]]*2\n\n    fig, axs = plt.subplots(2,3)\n    fig.set_size_inches(8,6)\n\n    titles=[\"u\",\"g\",\"r\",\"i\",\"z\",\"composite\"]\n    for i, ax in enumerate(axs.ravel()[:5]):\n        ax.hist2d(gal.star[x1], gal.star[x2],\n               weights=np.log10(getattr(gal.star, \"Flux_\"+titles[i])+1),\n               bins=npix,\n               cmap=plt.cm.binary_r,\n               norm=LogNorm(),\n               range=gal_range)\n        ax.set_aspect(\"equal\")\n        ax.set_title(titles[i])\n\n    # Try scaling Flux_x arrays to make a better composite image\n    comp_img = composite_rgb(gal.star[x1], gal.star[x2],\n                             channel_r,\n                             channel_g,\n                             channel_b,\n                             npix=npix,\n                             multiply_r = cr,\n                             multiply_g = cg,\n                             multiply_b = cb,\n                             log_scale=True,\n                             range=gal_range)\n    ax = axs[-1][-1]\n    ax.imshow(comp_img)\n    ax.set_title(\"composite\")\n    labels = [item.get_text() for item in ax.get_xticklabels()]\n    empty_string_labels = ['']*len(labels)\n    ax.set_aspect(\"equal\")\n    ax.set_xticklabels(empty_string_labels)\n    ax.set_yticklabels(empty_string_labels)\n\n    plt.savefig(str(gal.meta.id).zfill(5) + suffix + \".png\", dpi=200)\n\n\ndef get_absolute_mag(flux, band=None, bandname=\"r\"):\n    \"\"\"\n    Don't forget to pass band.\n    Initializing a new band class is expensive.\n\n    Todo\n    ----\n    Figure out, why 1e-2??\n    \"\"\"\n    if band is None:\n        band = BandSDSS()\n\n    speed_of_light = 3e18 # angstrom / sec\n    d_lum_10p = 3.0857e19 # lumminonsity distance of 10pc in cm\n    return - 2.5 * np.log10(np.sum(flux)/(4.*np.pi*d_lum_10p*d_lum_10p)*1e-2) \\\n            - 5. * np.log10(getattr(band, bandname)[\"pivot_lambda\"]) \\\n           + 2.5 * np.log10(speed_of_light) - 48.6\n\n\ndef get_star_colden(star, cell):\n    nstar = len(star)\n    # no need to perform calculations on irrelevant cells\n    # cut cells behind the further\n    # This shrinks the cell length significantly.\n\n    cell_dx_min = np.min(cell[\"dx\"])\n\n    ddx_h = cell[\"dx\"] * 0.5\n\n    sub_cell = cell[((cell[\"x\"]+ddx_h) > star[\"x\"].min()) * (cell[\"x\"]-ddx_h < star[\"x\"].max()) *\\\n                    ((cell[\"y\"]+ddx_h) > star[\"y\"].min()) * (cell[\"y\"]-ddx_h < star[\"y\"].max()) *\\\n                    ((cell[\"z\"]+ddx_h) < star[\"z\"].max())]\n\n    #print(\"len subcell\", len(sub_cell))\n    if len(sub_cell) < 1:\n        return -1\n\n    ddx_h = sub_cell[\"dx\"] * 0.5\n    xl = sub_cell[\"x\"] - ddx_h\n    xr = sub_cell[\"x\"] + ddx_h\n    yl = sub_cell[\"y\"] - ddx_h\n    yr = sub_cell[\"y\"] + ddx_h\n\n    xrange = (xl.min(),xr.max())\n    yrange = (yl.min(),yr.max())\n    xspan = xrange[1]-xrange[0]\n    yspan = yrange[1]-yrange[0]\n    npixx = np.int(np.ceil(xspan/cell_dx_min))\n    npixy = np.int(np.ceil(yspan/cell_dx_min))\n\n    h = np.histogram2d(star[\"x\"], star[\"y\"],\n                       bins=[npixx,npixy],\n                       range=[xrange, yrange])\n\n    dxmap = dymap = cell_dx_min\n\n    # Sort cells\n    i_relev = np.where(h[0].ravel() > 0)[0]\n\n    # Sort stars\n    ix=np.searchsorted(h[1], star[\"x\"]) - 1\n    iy=np.searchsorted(h[2], star[\"y\"]) - 1\n\n    ixy = iy + npixx*ix\n    #print(\"histogram indicies and ixy are equivalent:\", np.all(np.unique(ixy) == i_relev))\n\n    i_star_sort = np.argsort(ixy)\n    i_star = np.concatenate((np.searchsorted(ixy[i_star_sort], np.unique(ixy)),\n                             [nstar]))\n\n    # stars grouped in each lum map.\n    sorted_star = star[i_star_sort]\n    #sorted_flux = sorted_star[\"Flux_r\"]#[i_star_sort]\n    colden_star = np.zeros(nstar)\n\n    #print('len star', len(i_star))\n    #print(\"len cell\", len(sub_cell))\n    #print(\"minx cell\", min(xl))\n    #print(\"maxx cell\", max(xr))\n    #print(\"miny cell\", min(yl))\n    #print(\"maxy cell\", max(yr))\n\n    for i in range(len(i_star)-1):\n        stars_here = sorted_star[i_star[i]:i_star[i+1]]\n        jx, jy = ix[i_star_sort[i_star[i]]], iy[i_star_sort[i_star[i]]]\n   #     print(jx, jy)\n   #     print(h[1][jx], h[2][jy])\n        cells_here = sub_cell[ (xr >= h[1][jx]) * (xl <= h[1][jx]) *\\\n                               (yr >= h[2][jy]) * (yl <= h[2][jy]) ]\n   #     print(len(cells_here), \"cells here\")\n        if len(cells_here) == 0:\n            # at the edge\n            colden_star[i_star[i]:i_star[i+1]] = 0\n        else:\n            # column density for each star.\n            i_star_z = np.searchsorted(cells_here[\"z\"]+cells_here[\"dx\"], stars_here[\"z\"])\n            i_star_z[i_star_z >= len(cells_here)] = len(cells_here)-1\n            colden_star[i_star[i]:i_star[i+1]] = np.cumsum(cells_here[\"var0\"]*cells_here[\"dx\"])[i_star_z]\n\n    return colden_star\n\n\ndef ext_curve_k(lam, Rv=4.05):\n    H_frac = 0.76\n\n    lambda1 = 0.48613 # 1e-6 m\n    lambda2 = 0.65628 # 1e-6 m\n\n    # Why use only lambda 2\n    inv_lambda1 = 1./lam[lam < lambda2]\n    inv_lambda2 = 1./lam[lam > lambda2]\n\n    k = np.zeros(len(lam))\n    # lambda : 0.09 ~ 0.63 1e-6m\n    k1 = 2.659 * (-2.156 + (1.509 * inv_lambda1)\n                      - (0.198*inv_lambda1**2)\n                  + (0.011*inv_lambda1**3)) + Rv\n    # lambda : 0.63 ~ 5.08 1e-6m\n    k2 = 2.659 * (-1.857 + (1.040*inv_lambda2)) + Rv\n\n    k[lam < lambda2] = k1\n    k[lam > lambda2] = k2\n    return k\n", "meta": {"hexsha": "9344d7ecc07365b0a60ba5b58004a19e111dc3de", "size": 19851, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyram/galaxymodule/quick_mock.py", "max_stars_repo_name": "Hoseung/pyRamAn", "max_stars_repo_head_hexsha": "f9386fa5a9f045f98590039988d3cd50bc488dc2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-25T16:11:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T16:11:56.000Z", "max_issues_repo_path": "pyram/galaxymodule/quick_mock.py", "max_issues_repo_name": "Hoseung/pyRamAn", "max_issues_repo_head_hexsha": "f9386fa5a9f045f98590039988d3cd50bc488dc2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-02-17T13:44:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-25T15:35:05.000Z", "max_forks_repo_path": "pyram/galaxymodule/quick_mock.py", "max_forks_repo_name": "Hoseung/pyRamAn", "max_forks_repo_head_hexsha": "f9386fa5a9f045f98590039988d3cd50bc488dc2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-25T16:11:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T16:11:56.000Z", "avg_line_length": 36.4908088235, "max_line_length": 113, "alphanum_fraction": 0.5476298423, "include": true, "reason": "import numpy", "num_tokens": 5578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3040416812727289, "lm_q1q2_score": 0.1674075891384825}}
{"text": "import os\nimport copy\nimport pickle\nimport numpy as np\nfrom types import FunctionType\nfrom ..static import Fluctuations\nfrom .Global21cm import Global21cm\nfrom ..physics.HaloModel import HaloModel\nfrom ..util import ParameterFile, ProgressBar\n#from ..analysis.BlobFactory import BlobFactory\nfrom ..analysis.PowerSpectrum import PowerSpectrum as AnalyzePS\nfrom ..physics.Constants import cm_per_mpc, c, s_per_yr, erg_per_ev, \\\n    erg_per_s_per_nW, h_p, cm_per_m\n\nclass Simulation(AnalyzePS): # pragma: no cover\n    def __init__(self, pf=None, **kwargs):\n        \"\"\" Set up a power spectrum calculation. \"\"\"\n\n        # See if this is a tanh model calculation\n        if 'problem_type' not in kwargs:\n            kwargs['problem_type'] = 102\n\n        self.tab_kwargs = kwargs\n\n        if pf is None:\n            self.pf = ParameterFile(**self.tab_kwargs)\n        else:\n            self.pf = pf\n\n    @property\n    def gs(self):\n        if not hasattr(self, '_gs'):\n            self._gs = Global21cm(**self.tab_kwargs)\n        return self._gs\n\n    @gs.setter\n    def gs(self, value):\n        \"\"\" Set global 21cm instance by hand. \"\"\"\n        self._gs = value\n\n    @property\n    def history(self):\n        if not hasattr(self, '_history'):\n            self._history = {}\n        return self._history\n\n    @property\n    def mean_intensity(self):\n        if not hasattr(self, '_mean_intensity'):\n            self._mean_intensity = self.gs.medium.field\n        return self._mean_intensity\n\n    def _cache_ebl(self, waves=None, wave_units='mic', flux_units='SI',\n        pops=None):\n        if not hasattr(self, '_cache_ebl_'):\n            self._cache_ebl_ = {}\n\n        # Could be clever and convert units here.\n        if (wave_units, flux_units, pops) in self._cache_ebl_:\n            _waves, _fluxes = self._cache_ebl_[(wave_units, flux_units, pops)]\n            if waves is None:\n                return _waves, _fluxes\n            elif _waves.size == waves.size:\n                if np.all(_waves == waves):\n                    return _waves, _fluxes\n\n        return None\n\n    def get_ebl(self, waves=None, wave_units='mic', flux_units='SI',\n        pops=None):\n        \"\"\"\n        Return the extragalactic background light (EBL) over all wavelengths.\n\n        Parameters\n        ----------\n        waves : np.ndarray\n            If provided, will interpolate fluxes from each source population\n            onto common grid.\n        wave_units : str\n            Current options: 'eV', 'microns', 'Ang'\n        flux_units : str\n            Current options: 'cgs', 'SI'\n\n        .. note :: 'SI' units means nW / m^2 / sr, 'cgs' means erg/s/Hz/sr.\n\n        Returns\n        -------\n        Tuple containing (observed wavelength, observed flux). Note that if\n        `waves` is not None, the returned flux array will have shape\n        (num source populations, num waves). If not, it will be 1-D with\n        the same length as output observed wavelengths.\n\n        \"\"\"\n\n        cached_result = self._cache_ebl(waves, wave_units, flux_units,\n            pops)\n        if cached_result is not None:\n            return cached_result\n\n        if not self.mean_intensity._run_complete:\n            self.mean_intensity.run()\n\n        if waves is not None:\n            all_x = waves\n            all_y = np.zeros((len(self.pops), len(waves)))\n        else:\n            all_x = []\n            all_y = []\n\n        for i in range(len(self.pops)):\n            if pops is not None:\n                if i not in pops:\n                    continue\n\n            zf = self.pops[i].zdead\n            E, flux = self.mean_intensity.flux_today(zf=None, popids=i,\n                units=flux_units)\n\n            if wave_units.lower() == 'ev':\n                x = E\n            elif wave_units.lower().startswith('mic'):\n                x = 1e4 * c / (E * erg_per_ev / h_p)\n            elif wave_units.lower().startswith('ang'):\n                x = 1e8 * c / (E * erg_per_ev / h_p)\n            else:\n                raise NotImplemented('Unrecognized `wave_units`={}'.format(\n                    wave_units\n                ))\n\n            lo, hi = x.min(), x.max()\n\n            # Check for overlap, warn user if they should use `waves`\n            if i > 0:\n                lo_all, hi_all = np.min(all_x), np.max(all_x)\n\n                is_overlap = (lo_all <= lo <= hi_all) or (lo_all <= hi <= hi_all)\n                if waves is None and is_overlap:\n                    print(\"# WARNING: Overlap in spectral coverage of population #{}. Consider using `waves` keyword argument.\".format(i))\n\n            #\n\n            # Either save EBL as potentially-disjointed array of energies\n            # OR interpolate to common wavelength grid if `waves` is not None.\n            if waves is not None:\n                if not np.all(np.diff(x) > 0):\n                    all_y[i,:] = np.exp(np.interp(np.log(waves[-1::-1]),\n                        np.log(x[-1::-1]), np.log(flux[-1::-1])))[-1::-1]\n                else:\n                    all_y[i,:] = np.exp(np.interp(np.log(waves), np.log(x),\n                        np.log(flux)))\n            else:\n                all_x.extend(E)\n                all_y.extend(flux)\n\n                # Put a gap between chunks to avoid weird plotting artifacts\n                all_x.append(-np.inf)\n                all_y.append(-np.inf)\n\n        x = np.array(all_x)\n        y = np.array(all_y)\n\n        if pops is None:\n            hist = self.history # poke\n            self._history['ebl'] = x, y\n\n        return x, y\n\n    def get_ps_galaxies(self, scales, waves, wave_units='mic',\n        scale_units='arcmin', flux_units='SI', dimensionless=False, pops=None,\n        **kwargs):\n        \"\"\"\n        Compute power spectrum at some observed wavelength.\n\n        Parameters\n        ----------\n        scales : int, float, np.ndarray\n\n        waves : int, float, np.ndarray\n            Wavelengths at which to compute power spectra in `wave_units`.\n            Note that if 2-D, must have shape (number of bins, 2), in which\n            case the power spectra will be computed in series of bandpasses.\n\n        wave_units : str\n            Current options: 'eV', 'microns', 'Ang'\n        flux_units : str\n            Current options: 'cgs', 'SI'\n        scale_units : str\n            Current options: 'arcmin', 'arcsec', 'degrees', 'ell'\n\n        Returns\n        -------\n        Tuple containing (scales, 2 pi / scales or l*l(+z),\n            waves, power spectra).\n\n        Note that the power spectra are return as 2-D arrays with shape\n        (len(scales), len(waves))\n\n        \"\"\"\n\n        # Make sure we do mean background first in case LW feedback is on.\n        if not self.mean_intensity._run_complete:\n            self.mean_intensity.run()\n\n        # Make sure things are arrays\n        if type(scales) != np.ndarray:\n            scales = np.array([scales])\n        if type(waves) != np.ndarray:\n            waves = np.array([waves])\n\n        if waves.ndim == 2:\n            assert waves.shape[1] == 2, \\\n                \"If `waves` is 2-D, must have shape (num waves, 2).\"\n\n        # Prep scales\n        if scale_units.lower() in ['l', 'ell']:\n            scales_inv = np.sqrt(scales * (scales + 1))\n        else:\n            if scale_units.lower().startswith('deg'):\n                scale_rad = scales * (np.pi / 180.)\n            elif scale_units.lower() == 'arcmin':\n                scale_rad = (scales / 60.) * (np.pi / 180.)\n            elif scale_units.lower() == 'arcsec':\n                scale_rad = (scales / 3600.) * (np.pi / 180.)\n            else:\n                raise NotImplemented('help')\n\n            scales_inv = np.pi / scale_rad\n\n        if wave_units.lower().startswith('mic'):\n            pass\n        else:\n            raise NotImplemented('help')\n\n        # Do some error-handling if waves is 2-D: means the user provided\n        # bandpasses instead of a set of wavelengths.\n\n        ps = np.zeros((len(self.pops), len(scales), len(waves)))\n\n        for i, pop in enumerate(self.pops):\n\n            if pops is not None:\n                if i not in pops:\n                    continue\n\n            for j, wave in enumerate(waves):\n                ps[i,:,j] = pop.get_ps_obs(scales, wave_obs=wave,\n                    scale_units=scale_units, **kwargs)\n\n\n        # Modify PS units before return\n        if flux_units.lower() == 'si':\n            ps *= cm_per_m**4 / erg_per_s_per_nW**2\n\n        if pops is None:\n            hist = self.history # poke\n            self._history['ps_nirb'] = scales, scales_inv, waves, ps\n\n        if dimensionless:\n            ps *= scales_inv[:,None]**2 / 2. / np.pi**2\n\n        return scales, scales_inv, waves, ps\n\n    @property\n    def pops(self):\n        return self.gs.medium.field.pops\n\n    @property\n    def grid(self):\n        return self.gs.medium.field.grid\n\n    @property\n    def hydr(self):\n        return self.grid.hydr\n\n    @property\n    def field(self):\n        if not hasattr(self, '_field'):\n            self._field = Fluctuations(**self.tab_kwargs)\n        return self._field\n\n    @property\n    def halos(self):\n        if not hasattr(self, '_halos'):\n            self._halos = self.pops[0].halos\n        return self._halos\n\n    @property\n    def tab_z(self):\n        if not hasattr(self, '_tab_z'):\n            self._tab_z = np.array(np.sort(self.pf['ps_output_z'])[-1::-1],\n                dtype=np.float64)\n        return self._tab_z\n\n    def run(self):\n        \"\"\"\n        Run everything we can.\n        \"\"\"\n        pass\n\n    def run_ebl(self):\n        pass\n\n    def run_nirb_ps(self):\n        pass\n\n    def get_ps_21cm(self):\n        if 'ps_21cm' not in self.history:\n            self.run_ps_21cm()\n\n        return self.history['ps_21cm']\n\n    def get_gs_21cm(self):\n        if 'gs_21cm' not in self.history:\n            self.gs.run()\n\n        return self.history['gs_21cm']\n\n    def run_gs_21cm(self):\n        self.gs.run()\n        self.history['gs_21cm'] = self.gs.history\n\n    def run_ps_21cm(self, z=None, k=None):\n        \"\"\"\n        Run a simulation, compute power spectrum at each redshift.\n\n        Returns\n        -------\n        Nothing: sets `history` attribute.\n\n        \"\"\"\n\n        if z is None:\n            z = self.tab_z\n        if k is None:\n            k = self.tab_k\n\n        # First, run global signal.\n        self.run_gs_21cm()\n\n        N = z.size\n        pb = self.pb = ProgressBar(N, use=self.pf['progress_bar'],\n            name='ps-21cm')\n\n        all_ps = []\n        for i, (z, data) in enumerate(self._step_ps_21cm()):\n\n            # Do stuff\n            all_ps.append(data.copy())\n\n            if i == 0:\n                keys = data.keys()\n\n            if not pb.has_pb:\n                pb.start()\n\n            pb.update(i)\n\n        pb.finish()\n\n        self.all_ps = all_ps\n\n        hist = {}\n        for key in keys:\n\n            is2d_k = key.startswith('ps')\n            is2d_R = key.startswith('jp') or key.startswith('ev') \\\n                  or key.startswith('cf')\n            is2d_B = (key in ['n_i', 'm_i', 'r_i', 'delta_B', 'bsd'])\n\n            if is2d_k:\n                tmp = np.zeros((len(self.tab_z), len(self.tab_k)))\n            elif is2d_R:\n                tmp = np.zeros((len(self.tab_z), len(self.tab_R)))\n            elif is2d_B:\n                tmp = np.zeros((len(self.tab_z), len(all_ps[0]['r_i'])))\n            else:\n                tmp = np.zeros_like(self.tab_z)\n\n            for i, z in enumerate(self.tab_z):\n                if key not in all_ps[i].keys():\n                    continue\n\n                tmp[i] = all_ps[i][key]\n\n            hist[key] = tmp.copy()\n\n        poke = self.history\n\n        self.history['ps_21cm'] = hist\n        self.history['ps_21cm']['z'] = self.tab_z\n        self.history['ps_21cm']['k'] = self.tab_k\n        self.history['ps_21cm']['R'] = self.tab_R\n\n    @property\n    def tab_k(self):\n        \"\"\"\n        Wavenumbers to output power spectra.\n\n        .. note :: Can be far more crude than native resolution of\n            matter power spectrum.\n\n        \"\"\"\n\n        if not hasattr(self, '_k'):\n            if self.pf['ps_output_k'] is not None:\n                self._k = self.pf['ps_output_k']\n            else:\n                lnk1 = self.pf['ps_output_lnkmin']\n                lnk2 = self.pf['ps_output_lnkmax']\n                dlnk = self.pf['ps_output_dlnk']\n                self._k = np.exp(np.arange(lnk1, lnk2+dlnk, dlnk))\n\n        return self._k\n\n    @property\n    def tab_R(self):\n        \"\"\"\n        Scales on which to compute correlation functions.\n\n        .. note :: Can be more crude than native resolution of matter\n            power spectrum, however, unlike `self.tab_k`, the resolution of\n            this quantity matters when converting back to power spectra,\n            since that operation requires an integral over R.\n\n        \"\"\"\n        if not hasattr(self, '_R'):\n            if self.pf['ps_output_R'] is not None:\n                self._R = self.pf['ps_output_R']\n            else:\n                lnR1 = self.pf['ps_output_lnRmin']\n                lnR2 = self.pf['ps_output_lnRmax']\n                dlnR = self.pf['ps_output_dlnR']\n                #lnR = np.log(self.halos.tab_R)\n\n                self._R = np.exp(np.arange(lnR1, lnR2+dlnR, dlnR))\n\n        return self._R\n\n    @property\n    def tab_Mmin(self):\n        if not hasattr(self, '_tab_Mmin'):\n            self._tab_Mmin = np.ones_like(self.halos.tab_z) * np.inf\n            for j, pop in enumerate(self.pops):\n                self._tab_Mmin = np.minimum(self._tab_Mmin, pop._tab_Mmin)\n\n        return self._tab_Mmin\n\n\n    @property\n    def tab_zeta(self):\n        return self._tab_zeta\n\n    @tab_zeta.setter\n    def tab_zeta(self, value):\n        self._tab_zeta = value\n\n    def _step_ps_21cm(self):\n        \"\"\"\n        Generator for the power spectrum.\n        \"\"\"\n\n        # Set a few things before we get moving.\n        self.field.tab_Mmin = self.tab_Mmin\n\n        for i, z in enumerate(self.tab_z):\n\n            data = {}\n\n            ##\n            # First, loop over populations and determine total\n            # UV and X-ray outputs.\n            ##\n\n            # Prepare for the general case of Mh-dependent things\n            Nion = np.zeros_like(self.halos.tab_M)\n            Nlya = np.zeros_like(self.halos.tab_M)\n            fXcX = np.zeros_like(self.halos.tab_M)\n            zeta_ion = zeta = np.zeros_like(self.halos.tab_M)\n            zeta_lya = np.zeros_like(self.halos.tab_M)\n            zeta_X = np.zeros_like(self.halos.tab_M)\n            #Tpro = None\n            for j, pop in enumerate(self.pops):\n                pop_zeta = pop.IonizingEfficiency(z=z)\n\n                if pop.is_src_ion:\n\n                    if type(pop_zeta) is tuple:\n                        _Mh, _zeta = pop_zeta\n                        zeta += np.interp(self.halos.tab_M, _Mh, _zeta)\n                        Nion += pop.src.Nion\n                    else:\n                        zeta += pop_zeta\n                        Nion += pop.pf['pop_Nion']\n                        Nlya += pop.pf['pop_Nlw']\n\n                    zeta = np.maximum(zeta, 1.) # why?\n\n                if pop.is_src_heat:\n                    pop_zeta_X = pop.HeatingEfficiency(z=z)\n                    zeta_X += pop_zeta_X\n\n                if pop.is_src_lya:\n                    Nlya += pop.pf['pop_Nlw']\n                    #Nlya += pop.src.Nlw\n\n            # Only used if...ps_lya_method==0?\n            zeta_lya += zeta * (Nlya / Nion)\n\n            ##\n            # Make scalar if it's a simple model\n            ##\n            if np.all(np.diff(zeta) == 0):\n                zeta = zeta[0]\n            if np.all(np.diff(zeta_X) == 0):\n                zeta_X = zeta_X[0]\n            if np.all(np.diff(zeta_lya) == 0):\n                zeta_lya = zeta_lya[0]\n\n            self.field.zeta = zeta\n            self.field.zeta_X = zeta_X\n\n            self.tab_zeta = zeta\n\n            ##\n            # Figure out scaling from ionized regions to heated regions.\n            # Right now, only constant (relative) scaling is allowed.\n            ##\n            asize = self.pf['bubble_shell_asize_zone_0']\n            if self.pf['ps_include_temp'] and asize is not None:\n\n                self.field.is_Rs_const = False\n\n                if type(asize) is FunctionType:\n                    R_s = lambda R, z: R + asize(z)\n                else:\n                    R_s = lambda R, z: R + asize\n\n            elif self.pf['ps_include_temp'] and self.pf['ps_include_ion']:\n                fvol = self.pf[\"bubble_shell_rvol_zone_0\"]\n                frad = self.pf['bubble_shell_rsize_zone_0']\n\n                assert (fvol is not None) + (frad is not None) <= 1\n\n                if fvol is not None:\n                    assert frad is None\n\n                    # Assume independent variable is redshift for now.\n                    if type(fvol) is FunctionType:\n                        frad = lambda z: (1. + fvol(z))**(1./3.) - 1.\n                        self.field.is_Rs_const = False\n                    else:\n                        frad = lambda z: (1. + fvol)**(1./3.) - 1.\n\n                elif frad is not None:\n                    if type(frad) is FunctionType:\n                        self.field.is_Rs_const = False\n                    else:\n                        frad = lambda z: frad\n                else:\n                    # If R_s = R_s(z), must re-compute overlap volumes on each\n                    # step. Should set attribute if this is the case.\n                    raise NotImplemented('help')\n\n                R_s = lambda R, z: R * (1. + frad(z))\n\n\n            else:\n                R_s = lambda R, z: None\n                Th = None\n\n            # Must be constant, for now.\n            Th = self.pf[\"bubble_shell_ktemp_zone_0\"]\n\n            self.tab_R_s = R_s\n            self.Th = Th\n\n\n            ##\n            # First: some global quantities we'll need\n            ##\n            Tcmb = self.cosm.TCMB(z)\n            hist = self.gs.history\n\n            Tk = np.interp(z, hist['z'][-1::-1], hist['igm_Tk'][-1::-1])\n            Ts = np.interp(z, hist['z'][-1::-1], hist['igm_Ts'][-1::-1])\n            Ja = np.interp(z, hist['z'][-1::-1], hist['Ja'][-1::-1])\n            xHII, ne = [0] * 2\n\n            xa = self.hydr.RadiativeCouplingCoefficient(z, Ja, Tk)\n            xc = self.hydr.CollisionalCouplingCoefficient(z, Tk)\n            xt = xa + xc\n\n            # Won't be terribly meaningful if temp fluctuations are off.\n            C = self.field.TempToContrast(z, Th=Th, Tk=Tk, Ts=Ts, Ja=Ja)\n            data['c'] = C\n            data['Ts'] = Ts\n            data['Tk'] = Tk\n            data['xa'] = xa\n            data['Ja'] = Ja\n\n\n\n            # Assumes strong coupling. Mapping between temperature\n            # fluctuations and contrast fluctuations.\n            #Ts = Tk\n\n\n            # Add beta factors to dictionary\n            for f1 in ['x', 'd', 'a']:\n                func = self.hydr.__getattribute__('beta_%s' % f1)\n                data['beta_%s' % f1] = func(z, Tk, xHII, ne, Ja)\n\n            Qi_gs = np.interp(z, self.gs.history['z'][-1::-1],\n                self.gs.history['cgm_h_2'][-1::-1])\n\n            # Ionization fluctuations\n            if self.pf['ps_include_ion']:\n\n                Ri, Mi, Ni = self.field.BubbleSizeDistribution(z, ion=True)\n\n                data['n_i'] = Ni\n                data['m_i'] = Mi\n                data['r_i'] = Ri\n                data['delta_B'] = self.field._B(z, ion=True)\n            else:\n                Ri = Mi = Ni = None\n\n            Qi = self.field.MeanIonizedFraction(z)\n\n            Qi_bff = self.field.BubbleFillingFactor(z)\n\n            xibar = Qi_gs\n\n\n            # Save normalized copy of BSD for easy plotting in post\n            dvdr = 4. * np.pi * Ri**2\n            dmdr = self.cosm.mean_density0 * (1. + data['delta_B']) * dvdr\n            dmdlnr = dmdr * Ri\n            dndlnR = Ni * dmdlnr\n            V = 4. * np.pi * Ri**3 / 3.\n            data['bsd'] = V * dndlnR / Qi\n\n            if self.pf['ps_include_temp']:\n                # R_s=R_s(Ri,z)\n                Qh = self.field.MeanIonizedFraction(z, ion=False)\n                data['Qh'] = Qh\n            else:\n                data['Qh'] = Qh = 0.0\n\n            # Interpolate global signal onto new (coarser) redshift grid.\n            dTb_ps = np.interp(z, self.gs.history['z'][-1::-1],\n                self.gs.history['dTb'][-1::-1])\n\n            xavg_gs = np.interp(z, self.gs.history['z'][-1::-1],\n                self.gs.history['xavg'][-1::-1])\n\n            data['dTb'] = dTb_ps\n\n            #data['dTb_bulk'] = np.interp(z, self.gs.history['z'][-1::-1],\n            #    self.gs.history['dTb_bulk'][-1::-1])\n\n\n            ##\n            # Correct for fraction of ionized and heated volumes\n            # and densities!\n            ##\n            if self.pf['ps_include_temp']:\n                data['dTb_vcorr'] = None#(1 - Qh - Qi) * data['dTb_bulk'] \\\n                    #+ Qh * self.hydr.dTb(z, 0.0, Th)\n            else:\n                data['dTb_vcorr'] = None#data['dTb_bulk'] * (1. - Qi)\n\n            if self.pf['ps_include_xcorr_ion_rho']:\n                pass\n            if self.pf['ps_include_xcorr_ion_hot']:\n                pass\n\n            # Just for now\n            data['dTb0'] = data['dTb']\n            data['dTb0_2'] = data['dTb0_1'] = data['dTb_vcorr']\n\n            #if self.pf['include_ion_fl']:\n            #    if self.pf['ps_rescale_Qion']:\n            #        xibar = min(np.interp(z, self.pops[0].halos.z,\n            #            self.pops[0].halos.fcoll_Tmin) * zeta, 1.)\n            #        Qi = xibar\n            #\n            #        xibar = np.interp(z, self.mean_history['z'][-1::-1],\n            #            self.mean_history['cgm_h_2'][-1::-1])\n            #\n            #    else:\n            #        Qi = self.field.BubbleFillingFactor(z, zeta)\n            #        xibar = 1. - np.exp(-Qi)\n            #else:\n            #    Qi = 0.\n\n\n\n            #if self.pf['ps_force_QHII_gs'] or self.pf['ps_force_QHII_fcoll']:\n            #    rescale_Q = True\n            #else:\n            #    rescale_Q = False\n\n            #Qi = np.mean([QHII_gs, self.field.BubbleFillingFactor(z, zeta)])\n\n            #xibar = np.interp(z, self.mean_history['z'][-1::-1],\n            #    self.mean_history['cgm_h_2'][-1::-1])\n\n            # Avoid divide by zeros when reionization is over\n            if Qi == 1:\n                Tbar = 0.0\n            else:\n                Tbar = data['dTb0_2']\n\n            xbar = 1. - xibar\n            data['Qi'] = Qi\n            data['xibar'] = xibar\n            data['dTb0'] = Tbar\n            #data['dTb_bulk'] = dTb_ps / (1. - xavg_gs)\n\n            ##\n            # 21-cm fluctuations\n            ##\n            if self.pf['ps_include_21cm']:\n\n                data['cf_21'] = self.field.CorrelationFunction(z,\n                    R=self.tab_R, term='21', R_s=R_s(Ri,z), Ts=Ts, Th=Th,\n                    Tk=Tk, Ja=Ja, k=self.tab_k)\n\n                # Always compute the 21-cm power spectrum. Individual power\n                # spectra can be saved by setting ps_save_components=True.\n                data['ps_21'] = self.field.PowerSpectrumFromCF(self.tab_k,\n                    data['cf_21'], self.tab_R,\n                    split_by_scale=self.pf['ps_split_transform'],\n                    epsrel=self.pf['ps_fht_rtol'],\n                    epsabs=self.pf['ps_fht_atol'])\n\n            # Should just do the above, and then loop over whatever is in\n            # the cache and save also. If ps_save_components is True, then\n            # FT everything we haven't already.\n            for term in ['dd', 'ii', 'id', 'psi', 'phi']:\n                # Should change suffix to _ev\n                jp_1 = self.field._cache_jp(z, term)\n                cf_1 = self.field._cache_cf(z, term)\n\n                if (jp_1 is None and cf_1 is None) and (term not in ['psi', 'phi', 'oo']):\n                    continue\n\n                _cf = self.field.CorrelationFunction(z,\n                    R=self.tab_R, term=term, R_s=R_s(Ri,z), Ts=Ts, Th=Th,\n                    Tk=Tk, Ja=Ja, k=self.tab_k)\n\n                data['cf_{}'.format(term)] = _cf.copy()\n\n                if not self.pf['ps_output_components']:\n                    continue\n\n                data['ps_{}'.format(term)] = \\\n                    self.field.PowerSpectrumFromCF(self.tab_k,\n                    data['cf_{}'.format(term)], self.tab_R,\n                    split_by_scale=self.pf['ps_split_transform'],\n                    epsrel=self.pf['ps_fht_rtol'],\n                    epsabs=self.pf['ps_fht_atol'])\n\n            # Always save the matter correlation function.\n            data['cf_dd'] = self.field.CorrelationFunction(z,\n                term='dd', R=self.tab_R)\n\n            yield z, data\n\n    def save(self, prefix, suffix='pkl', clobber=False, fields=None):\n        \"\"\"\n        Save results of calculation. Pickle parameter file dict.\n\n        Notes\n        -----\n        1) will save files as prefix.history.suffix and prefix.parameters.pkl.\n        2) ASCII files will fail if simulation had multiple populations.\n\n        Parameters\n        ----------\n        prefix : str\n            Prefix of save filename\n        suffix : str\n            Suffix of save filename. Can be hdf5 (or h5) or pkl.\n            Anything else will be assumed to be ASCII format (e.g., .txt).\n        clobber : bool\n            Overwrite pre-existing files of same name?\n\n        \"\"\"\n\n        self.gs.save(prefix, clobber=clobber, fields=fields)\n\n        fn = '%s.fluctuations.%s' % (prefix, suffix)\n\n        if os.path.exists(fn):\n            if clobber:\n                os.remove(fn)\n            else:\n                raise IOError('%s exists! Set clobber=True to overwrite.' % fn)\n\n        if suffix == 'pkl':\n            f = open(fn, 'wb')\n            pickle.dump(self.history._data, f)\n            f.close()\n\n            try:\n                f = open('%s.blobs.%s' % (prefix, suffix), 'wb')\n                pickle.dump(self.blobs, f)\n                f.close()\n\n                if self.pf['verbose']:\n                    print('Wrote {}.blobs.{}'.format(prefix, suffix))\n            except AttributeError:\n                print('Error writing {}.blobs.{}'.format(prefix, suffix))\n\n        elif suffix in ['hdf5', 'h5']:\n            import h5py\n\n            f = h5py.File(fn, 'w')\n            for key in self.history:\n                if fields is not None:\n                    if key not in fields:\n                        continue\n                f.create_dataset(key, data=np.array(self.history[key]))\n            f.close()\n\n        # ASCII format\n        else:\n            f = open(fn, 'w')\n            print >> f, \"#\",\n\n            for key in self.history:\n                if fields is not None:\n                    if key not in fields:\n                        continue\n                print >> f, '%-18s' % key,\n\n            print >> f, ''\n\n            # Now, the data\n            for i in range(len(self.history[key])):\n                s = ''\n\n                for key in self.history:\n                    if fields is not None:\n                        if key not in fields:\n                            continue\n\n                    s += '%-20.8e' % (self.history[key][i])\n\n                if not s.strip():\n                    continue\n\n                print >> f, s\n\n            f.close()\n\n        if self.pf['verbose']:\n            print('Wrote {}.fluctuations.{}'.format(prefix, suffix))\n\n        #write_pf = True\n        #if os.path.exists('%s.parameters.pkl' % prefix):\n        #    if clobber:\n        #        os.remove('%s.parameters.pkl' % prefix)\n        #    else:\n        #        write_pf = False\n        #        print 'WARNING: %s.parameters.pkl exists! Set clobber=True to overwrite.' % prefix\n\n        #if write_pf:\n        #\n        #    #pf = {}\n        #    #for key in self.pf:\n        #    #    if key in self.carryover_kwargs():\n        #    #        continue\n        #    #    pf[key] = self.pf[key]\n        #\n        #    if 'revision' not in self.pf:\n        #        self.pf['revision'] = get_hg_rev()\n        #\n        #    # Save parameter file\n        #    f = open('%s.parameters.pkl' % prefix, 'wb')\n        #    pickle.dump(self.pf, f, -1)\n        #    f.close()\n        #\n        #    if self.pf['verbose']:\n        #        print 'Wrote %s.parameters.pkl' % prefix\n        #\n", "meta": {"hexsha": "03ef387709e9e85eb33366f6fc1b7201450aacda", "size": 28404, "ext": "py", "lang": "Python", "max_stars_repo_path": "ares/simulations/Simulation.py", "max_stars_repo_name": "mirochaj/ares", "max_stars_repo_head_hexsha": "b3335ad30435ee0d7f17d0110aa164a35f252d78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-03-26T01:08:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T13:02:10.000Z", "max_issues_repo_path": "ares/simulations/Simulation.py", "max_issues_repo_name": "mirochaj/ares", "max_issues_repo_head_hexsha": "b3335ad30435ee0d7f17d0110aa164a35f252d78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2020-06-08T14:52:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T02:30:54.000Z", "max_forks_repo_path": "ares/simulations/Simulation.py", "max_forks_repo_name": "mirochaj/ares", "max_forks_repo_head_hexsha": "b3335ad30435ee0d7f17d0110aa164a35f252d78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-03-24T14:11:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-06T06:32:59.000Z", "avg_line_length": 31.9505061867, "max_line_length": 138, "alphanum_fraction": 0.4951767357, "include": true, "reason": "import numpy", "num_tokens": 7016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863698, "lm_q2_score": 0.25982564369245537, "lm_q1q2_score": 0.16738620297566162}}
{"text": "# Dopri ODE system\nfrom __future__ import division, absolute_import, print_function\n\nimport imp\n\nfrom .allimports import *\nfrom PyDSTool.Generator import ODEsystem as ODEsystem\nfrom .baseclasses import theGenSpecHelper, genDB, _pollInputs\nfrom .mixins import CompiledMixin\nfrom PyDSTool.utils import *\nfrom PyDSTool.common import *\n# for future cleanup of * imports\nfrom PyDSTool import utils\nfrom PyDSTool import common\nfrom PyDSTool.integrator import integrator\nimport numpy as npy\n\n# Other imports\nfrom numpy import Inf, NaN, isfinite, int, int32, float, float64, \\\n     sometrue, alltrue, any, all, concatenate, transpose, array, zeros\nimport math, random\nimport operator\nfrom copy import copy, deepcopy\nimport sys, gc\n#import distutils\nfrom distutils.sysconfig import get_python_inc\nfrom time import clock, sleep\n\n\nclass dopri(integrator):\n    \"\"\"Dopri 853 specialization of the basic integrator class.\"\"\"\n\n    def __init__(self, modname, rhs='default_name', phaseDim=0, paramDim=0,\n                 nAux=0, nEvents=0, nExtInputs=0,\n                 hasJac=0, hasJacP=0, hasMass=0, extraSpace=0,\n                 defaultBound=1e8):\n\n        integrator.__init__(self, rhs=rhs, phaseDim=phaseDim, paramDim=paramDim,\n                            nAux=nAux, nEvents=nEvents, nExtInputs=nExtInputs,\n                            hasJac=hasJac, hasJacP=hasJacP, hasMass=hasMass,\n                            extraSpace=extraSpace, defaultBound=defaultBound)\n        self.modname = modname\n        try:\n            self._integMod = imp.load_module(\n                modname, *imp.find_module(modname, [\"dop853_temp\"]))\n        except:\n            print(\"Error in importing compiled vector field and integrator.\")\n            print(\"Did you compile the RHS C code?\")\n            raise\n        # check module's directory\n        assert 'Integrate' in dir(self._integMod), \\\n               \"dop853 library does not contain Integrate()\"\n\n        self.fac1 = []\n        self.fac2 = []\n        self.safety = []\n        self.beta = []\n        self.checkBounds = 0\n        self.boundsCheckMaxSteps = 1000\n        self.magBound = 1000000\n\n        retval = self._integMod.InitBasic(self.phaseDim, self.paramDim, self.nAux,\n                                          self.nEvents, self.nExtInputs, self.hasJac,\n                                          self.hasJacP, self.hasMass, self.extraSpace)\n\n        if retval[0] != 1:\n            raise PyDSTool_InitError('Call to InitBasic failed! (dopri)')\n\n        self.initBasic = True\n\n\n    def Run(self, hinit=0, hmax=1.0, checkAux=0, calcSpecTimes=0, verbose=0,\n            fac1=0.2, fac2=10.0, safety=0.9, beta=0.04, checkBounds=0,\n            boundsCheckMaxSteps=1000, magBound=1000000):\n        if not self.initBasic:\n            raise PyDSTool_InitError('initBasic is False (dopri)')\n        if not self.initEvents:\n            raise PyDSTool_InitError('initEvents is False (dopri)')\n        if not self.initIntegrate:\n            raise PyDSTool_InitError('initInteg is False (dopri)')\n        if not self.setParams:\n            raise PyDSTool_InitError('setParams is False (dopri)')\n        if self.nExtInputs > 0 and not self.initExtInputs:\n            raise PyDSTool_InitError('initExtInputs is False (dopri)')\n\n        self.setDopriParams(hinit=hinit, hmax=hmax, checkAux=checkAux,\n                            calcSpecTimes=calcSpecTimes,\n                            verbose=verbose, fac1=fac1,\n                            fac2=fac2, safety=safety, beta=beta,\n                            checkBounds=checkBounds,\n                            boundsCheckMaxSteps=boundsCheckMaxSteps,\n                            magBound=magBound)\n\n        # For a run, we want to ensure indices are set to 0\n        self.Reset()\n        T, P, A, Stats, H, Err, EvtT, EvtP = self._integMod.Integrate(self.ic,\n                                                          self.t0,\n                                                          self.hinit,\n                                                          self.hmax,\n                                                          self.safety,\n                                                          self.fac1,\n                                                          self.fac2,\n                                                          self.beta,\n                                                          self.verbose,\n                                                          self.checkAux,\n                                                          self.calcSpecTimes,\n                                                          self.checkBounds,\n                                                          self.boundsCheckMaxSteps,\n                                                          self.magBound)\n        self.points = P\n        self.times = T\n        self.auxPoints = A\n        self.eventTimes = EvtT\n        self.eventPoints = EvtP\n        self.errors = Err\n        self.stats = Stats\n        self.step = H\n\n        try:\n            self.lastTime = self.times[-1]\n            self.lastPoint = [self.points[i][-1] for i in range(self.phaseDim)]\n            self.lastStep = self.step\n        except IndexError:\n            self.lastTime = self.t0\n            self.lastPoint = self.ic\n            self.lastStep = self.hinit\n        self.numRuns += 1\n        self.canContinue = True\n\n        return T, P, A, Stats, H, Err, EvtT, EvtP\n\n\n    def Continue(self, tend, params=[], calcSpecTimes=0, verbose=0, extInputChanged=False,\n                 extInputVals=[], extInputTimes=[], bounds=[]):\n        if not self.initBasic:\n            raise PyDSTool_InitError('initBasic is False (dopri)')\n        if not self.initEvents:\n            raise PyDSTool_InitError('initEvents is False (dopri)')\n        if not self.initIntegrate:\n            raise PyDSTool_InitError('initInteg is False (dopri)')\n        if not self.setParams:\n            raise PyDSTool_InitError('setParams is False (dopri)')\n        if self.nExtInputs > 0 and not self.initExtInputs:\n            raise PyDSTool_InitError('initExtInputs is False (dopri)')\n\n        if not self.canContinue:\n            raise PyDSTool_ContError('Unable to continue trajectory -- '\n                    'have you run the integrator and reset events, etc?')\n\n        self.setContParams(tend=tend, params=copy(params),\n                           calcSpecTimes=calcSpecTimes, verbose=verbose,\n                           extInputChanged=extInputChanged,\n                           extInputVals=copy(extInputVals),\n                           extInputTimes=copy(extInputTimes),\n                           bounds=copy(bounds))\n\n        # For a continue, we do not set indices to 0\n        T, P, A, Stats, H, Err, EvtT, EvtP = self._integMod.Integrate(self.lastPoint,\n                                                          self.lastTime,\n                                                          self.lastStep,\n                                                          self.hmax,\n                                                          self.safety,\n                                                          self.fac1,\n                                                          self.fac2,\n                                                          self.beta,\n                                                          self.verbose,\n                                                          self.checkAux,\n                                                          self.calcSpecTimes,\n                                                          self.checkBounds,\n                                                          self.boundsCheckMaxSteps,\n                                                          self.magBound)\n        self.points = P\n        self.times = T\n        self.auxPoints = A\n        self.eventTimes = EvtT\n        self.eventPoints = EvtP\n        self.errors = Err\n        self.stats = Stats\n        self.step = H\n\n        try:\n            self.lastTime = self.times[-1]\n            self.lastPoint = [self.points[i][-1] for i in range(self.phaseDim)]\n            self.lastStep = self.step\n        except IndexError:\n            self.lastTime = self.t0\n            self.lastPoint = self.ic\n            self.lastStep = self.hinit\n        self.numRuns += 1\n        self.numContinues += 1\n        self.canContinue = True\n\n        return T, P, A, Stats, H, Err, EvtT, EvtP\n\n\n    def setDopriParams(self,hinit,hmax,checkAux,calcSpecTimes,verbose,\n                       fac1,fac2,safety,beta,checkBounds,boundsCheckMaxSteps,\n                       magBound):\n        checkAux = int(checkAux)\n        calcSpecTimes = int(calcSpecTimes)\n\n        if not isinstance(hinit, _num_types):\n            raise TypeError(\"hinit must be int, float\")\n\n        if not isinstance(hmax, _num_types):\n            raise TypeError(\"hmax must be int, float\")\n\n        if abs(hinit) > abs(hmax):\n            raise ValueError(\"Abs value of hinit (%g) must be less than hmax (%g)\"%(hinit,hmax))\n\n        if not isinstance(checkAux, _int_types):\n            raise TypeError(\"checkAux must be int\")\n        if checkAux not in (0,1):\n            raise TypeError(\"checkAux must be 0 or 1\")\n        if checkAux == 1 and self.nAux <= 0:\n            raise ValueError(\"checkAux cannot be 1 if nAux is 0\")\n\n        if not isinstance(verbose, _int_types):\n            raise TypeError(\"verbose must be int\")\n        if verbose not in (0,1):\n            if verbose >= 2:\n                # interpret all greater values as 1\n                verbose = 1\n            else:\n                raise TypeError(\"verbose must be 0 or 1\")\n\n        if not isinstance(calcSpecTimes, _int_types):\n            raise TypeError(\"calcSpecTimes must be int\")\n        if calcSpecTimes not in (0,1):\n            raise TypeError(\"calcSpecTimes must be 0 or 1\")\n        if calcSpecTimes == 1 and len(self.specTimes) <= 0:\n            raise ValueError(\"calcSpecTimes cannot be 1 if specTimes is empty\")\n\n        if fac1 < 0:\n            raise ValueError(\"fac1 must be non-negative\")\n        if fac2 < 0:\n            raise ValueError(\"fac2 must be non-negative\")\n        if beta < 0:\n            raise ValueError(\"beta must be non-negative\")\n        if safety < 0:\n            raise ValueError(\"safety must be non-negative\")\n\n        if not isinstance(checkBounds, _int_types):\n            raise TypeError(\"checkBounds must be int\")\n        if checkBounds not in (0,1,2):\n            raise ValueError(\"checkBounds must be 0, 1, or 2\")\n\n        if not isinstance(boundsCheckMaxSteps, _int_types):\n            raise TypeError(\"boundsCheckMaxSteps must be int\")\n        if boundsCheckMaxSteps < 0:\n            raise ValueError(\"boundsCheckMaxSteps must be non-negative\")\n\n        if isinstance(magBound, _num_types):\n            if magBound <= 0:\n                raise ValueError(\"magBound must be positive\")\n            mbound = [float(magBound) for x in range(self.phaseDim)]\n            self.magBound = mbound\n        else:\n            for x in magBound:\n                if x <= 0:\n                    raise ValueError(\"All magBound components must be positive\")\n            self.magBound = magBound\n\n        self.boundsCheckMaxSteps = boundsCheckMaxSteps\n        self.checkBounds = checkBounds\n        self.hinit = hinit\n        self.hmax = hmax\n        self.checkAux = checkAux\n        self.verbose = verbose\n        self.calcSpecTimes = calcSpecTimes\n        self.fac1 = fac1\n        self.fac2 = fac2\n        self.beta = beta\n        self.safety = safety\n\n\nclass Dopri_ODEsystem(ODEsystem, CompiledMixin):\n    \"\"\"Wrapper for Dopri853 integrator.\n\n    Uses C target language only for functional specifications.\"\"\"\n    _paraminfo = {'rtol': 'Relative error tolerance.',\n                  'atol': 'Absolute error tolerance.',\n                  'safety': 'Safety factor in the step size prediction, default 0.9.',\n                  'fac1': 'Parameter for step size selection; the new step size is chosen subject to the restriction  fac1 <= new_step/old_step <= fac2. Default value is 0.333.',\n                  'fac2': 'Parameter for step size selection; the new step size is chosen subject to the restriction  fac1 <= new_step/old_step <= fac2. Default value is 6.0.',\n                  'beta': 'The \"beta\" for stabilized step size control. Larger values for beta ( <= 0.1 ) make the step size control more stable. Negative initial value provoke beta=0; default beta=0.04',\n                  'max_step': 'Maximal step size, default tend-tstart.',\n                  'init_step': 'Initial step size, default is a guess computed by the function init_step.',\n                  'refine': 'Refine output by adding points interpolated using the RK4 polynomial (0, 1 or 2).',\n                  'use_special': \"Switch for using special times\",\n                  'specialtimes': \"List of special times to use during integration\",\n                  'check_aux': \"Switch\",\n                  'extraspace': \"\",\n                  'magBound': \"The largest variable magnitude before a bounds error flags (if checkBound > 0). Defaults to 1e7\",\n                  'checkBounds': \"Switch to check variable bounds: 0 = no check, 1 = check up to 'boundsCheckMaxSteps', 2 = check for every point\",\n                  'boundsCheckMaxSteps': \"Last step to bounds check if checkBound==1. Defaults to 1000.\"\n                  }\n\n    def __init__(self, kw):\n        \"\"\"Use the nobuild key to postpone building of the library, e.g. in\n        order to provide additional build options to makeLibSource and\n        compileLib methods or to make changes to the C code by hand.\n        No build options can be specified otherwise.\"\"\"\n\n        # delete because not covered in ODEsystem\n        nobuild = kw.pop('nobuild', False)\n        ODEsystem.__init__(self, kw)\n        self.diagnostics.outputStatsInfo = {\n            'last_step': 'Predicted step size of the last accepted step (useful for a subsequent call to dop853).',\n            'num_steps': 'Number of used steps.',\n            'num_accept': 'Number of accepted steps.',\n            'num_reject': 'Number of rejected steps.',\n            'num_fcns': 'Number of function calls.',\n            'errorStatus': 'Error status on completion.'\n                        }\n        self.diagnostics._errorcodes = {\n             0 : 'Unrecognized error code returned (see stderr output)',\n            -1 : 'input is not consistent',\n            -2 : 'larger nmax is needed',\n            2 : 'larger nmax or maxevtpts is probably needed (error raised by solout)',\n            -3 : 'step size becomes too small',\n            -4 : 'the problem is probably stiff (interrupted)',\n            -8 : 'The solution exceeded a magbound (poor choice of initial step)'}\n        self._solver = None\n        algparams_def = {'poly_interp': False,\n                        'init_step': 0,\n                        'max_step': 0,\n                        'rtol': [1e-9 for i in range(self.dimension)],\n                        'atol': [1e-12 for i in range(self.dimension)],\n                        'fac1': 0.2,\n                        'fac2': 10.0,\n                        'safety': 0.9,\n                        'beta': 0.04,\n                        'max_pts': 10000,\n                        'refine': 0,\n                        'maxbisect': [], # for events\n                        'maxevtpts': 1000, # for events\n                        'eventInt': [],  # set using setEventInterval only\n                        'eventDelay': [], # set using setEventDelay only\n                        'eventTol': [], # set using setEventTol only\n                        'use_special': 0,\n                        'specialtimes': [],\n                        'check_aux': 1,\n                        'extraspace': 100,\n                        'verbose': 0,\n                        'hasJac': 0,\n                        'hasJacP': 0,\n                        'magBound': 1e7,\n                        'boundsCheckMaxSteps': 1000,\n                        'checkBounds': self.checklevel\n                        }\n        for k, v in algparams_def.items():\n            if k not in self.algparams:\n                self.algparams[k] = v\n        # verify that no additional keys are present in algparams, after\n        # defaults are added above\n        if len(self.algparams) != len(algparams_def):\n            raise ValueError(\"Invalid keys present in algparams argument: \" \\\n                     + str(remain(self.algparams.keys(),algparams_def.keys())))\n\n        if self.haveMass():\n            raise ValueError(\"Mass matrix declaration is incompatible \"\n                             \"with Dopri853 integrator system specification\")\n\n        self._prepareEventSpecs()\n        self._inputVarList = []\n        self._inputTimeList = []\n\n        if nobuild:\n            print(\"Build the library using the makeLib method, or in \")\n            print(\"stages using the makeLibSource and compileLib methods.\")\n        else:\n            self.makeLib()\n\n    @property\n    def integrator(self):\n        return {\n            'name': ('dop853', 'Dopri853'),\n            'description': \"Dopri 853 integrator\",\n            'src': [\"dop853mod.c\", \"dop853.c\"],\n            'cflags': [\"-D__DOPRI__\"],\n        }\n\n    def _prepareEventSpecs(self):\n        eventActive = []\n        eventTerm = []\n        eventDir = []\n        eventDelay = []\n        eventTol = []\n        maxbisect = []\n        eventInt = []\n        # convert event specs (term, active, etc.) into integparam specs\n        self._eventNames = self.eventstruct.sortedEventNames()\n        for evname in self._eventNames:\n            ev = self.eventstruct.events[evname]\n            assert isinstance(ev, LowLevelEvent), (\"Dopri can only \"\n                                                \"accept low level events\")\n        # if event 'precise' flags set to False then set their tolerances\n        # to be > max_step\n        maxstep = self.algparams['max_step']\n        for evname in self._eventNames:\n            ev = self.eventstruct.events[evname]\n            eventActive.append(int(ev.activeFlag))\n            eventTerm.append(int(ev.termFlag))\n            eventDir.append(ev.dircode)\n            eventInt.append(ev.eventinterval)\n            eventDelay.append(ev.eventdelay)\n            if ev.preciseFlag:\n                eventTol.append(ev.eventtol)\n                maxbisect.append(ev.bisectlimit)\n            else:\n                eventTol.append(maxstep*1.5)\n                maxbisect.append(1)\n        self.algparams['eventTol'] = eventTol\n        self.algparams['eventDelay'] = eventDelay\n        self.algparams['eventInt'] = eventInt\n        self.algparams['maxbisect'] = maxbisect\n        self.algparams['eventActive'] = eventActive\n        self.algparams['eventTerm'] = eventTerm\n        self.algparams['eventDir'] = eventDir\n\n\n    def compute(self, trajname, dirn='f', ics=None):\n        continue_integ = ODEsystem.prepDirection(self, dirn)\n        if ics is not None:\n            self.set(ics=ics)\n        self.validateICs()\n        self.diagnostics.clearWarnings()\n        self.diagnostics.clearErrors()\n        if isinstance(self.algparams['rtol'], list):\n            if len(self.algparams['rtol']) != self.dimension:\n                raise ValueError('rtol list must have same length as phase dimension')\n        else:\n            rtol = self.algparams['rtol']\n            self.algparams['rtol'] = [rtol for dimix in range(self.dimension)]\n        if isinstance(self.algparams['atol'], list):\n            if len(self.algparams['atol']) != self.dimension:\n                raise ValueError('atol list must have same length as phase dimension')\n        else:\n            atol = self.algparams['atol']\n            self.algparams['atol'] = [atol for dimix in range(self.dimension)]\n        anames = self.funcspec.auxvars\n        # Check i.c.'s are well defined (finite)\n        self.checkInitialConditions()\n        self.setEventICs(self.initialconditions, self.globalt0)\n        # update event params in case changed since last run\n        self._prepareEventSpecs()\n        # Main integration\n        t0 = self.indepvariable.depdomain[0]\n        t1 = self.indepvariable.depdomain[1]\n        plist = sortedDictValues(self.pars)\n        self.algparams['hasJac'] = self.haveJacobian()\n        self.algparams['hasJacP'] = self.haveJacobian_pars()\n        if self._solver is None:\n            self._solver = dopri(self.modname,\n                                 rhs=self.name, phaseDim=self.dimension,\n                                 paramDim=len(plist), nAux=len(anames),\n                                 nEvents=len(self._eventNames),\n                                 nExtInputs=len(self.inputs),\n                                 hasJac=self.algparams['hasJac'],\n                                 hasJacP=self.algparams['hasJacP'],\n                                 hasMass=self.haveMass(),\n                                 extraSpace=self.algparams['extraspace'],\n                                 )\n            try:\n                genDB.register(self)\n            except PyDSTool_KeyError:\n                errstr = \"Generator \" + self.name + \": this vector field's \" +\\\n                         \"DLL is already in use\"\n                raise RuntimeError(errstr)\n        if self._dircode == 1:\n            tbegin = t0\n            tend = t1\n        elif self._dircode == -1:\n            # dopri does reverse time integration simply by switching t0 and t1\n            # and using negative steps\n            tbegin = t1\n            tend = t0\n        if len(self.algparams['specialtimes'])>0:\n            use_special = self.algparams['use_special']\n        else:\n            use_special = 0\n        bounds = [[],[]]  # lower, then upper\n        for v in self.funcspec.vars:\n            bds = self.xdomain[v]\n            bounds[0].append(bds[0])\n            bounds[1].append(bds[1])\n        for p in self.funcspec.pars:\n            bds = self.pdomain[p]\n            bounds[0].append(bds[0])\n            bounds[1].append(bds[1])\n        if continue_integ:\n            x0 = self._solver.lastPoint\n            # overwrite t0 from self.indepvariable.domain, but use its t1\n            tbegin = self._solver.lastTime\n            if abs(self._solver.lastStep) < abs(self.algparams['init_step']):\n                self.algparams['init_step'] = self._solver.lastStep\n            if abs(t1-tbegin) < abs(self.algparams['init_step']):\n                raise ValueError(\"Integration end point too close to initial \"\n                                 \"point\")\n#            if self.inputs and self._extInputsChanged:\n#                self._extInputsChanged = False\n#                self._solver.setContParams(tend, plist,\n#                                           use_special,\n#                                           self.algparams['verbose'],\n#                                           True, deepcopy(self._inputVarList),\n#                                           deepcopy(self._inputTimeList))\n        else:\n            if self._solver.numRuns > 0:\n                self._solver.clearAll()\n            x0 = sortedDictValues(self.initialconditions, self.funcspec.vars)\n            self._solver.setInteg(maxpts=self.algparams['max_pts'],\n                rtol=self.algparams['rtol'], atol=self.algparams['atol'])\n            self._solver.setRunParams(ic=x0, params=plist,\n                                  t0=tbegin, tend=tend, gt0=self.globalt0,\n                                  refine=self.algparams['refine'],\n                                  specTimes=self.algparams['specialtimes'],\n                                  bounds=bounds)\n        if self.inputs:\n            # self._extInputsChanged if global t0 changed so that can\n            # adjust times given to the integrator (it is blind to global t0\n            # when accesses input variable times)\n            self._ensure_inputs(self._extInputsChanged)\n        # hinit only set if not continue_integ\n        if len(anames)>0:\n            check_aux = self.algparams['check_aux']\n        else:\n            check_aux = 0\n        if self.algparams['max_step'] == 0:\n            max_step = tend-tbegin\n        else:\n            max_step = self.algparams['max_step']\n        init_step = self.algparams['init_step']\n        if self._dircode == 1:\n            if init_step < 0:\n                init_step = -init_step\n            if max_step < 0:\n                max_step = -max_step\n        else:\n            if init_step > 0:\n                init_step = -init_step\n            if max_step > 0:\n                max_step = -max_step\n        if continue_integ:\n            # record needed for bounds checking and truncation\n            old_highest_ix = self._solver.points.shape[1]\n            alltData, X, A, Stats, H, Err, Evtimes, \\\n                 Evpoints = self._solver.Continue(tend, plist,\n                                  use_special, self.algparams['verbose'],\n                                  self._extInputsChanged,\n                                  deepcopy(self._inputVarList),\n                                  deepcopy(self._inputTimeList),\n                                  bounds)\n        else:\n            old_highest_ix = 0\n            self._solver.setEvents(eventActive=self.algparams['eventActive'],\n                eventTerm=self.algparams['eventTerm'],\n                eventDir=self.algparams['eventDir'],\n                eventDelay=self.algparams['eventDelay'],\n                eventInt=self.algparams['eventInt'],\n                eventTol=self.algparams['eventTol'],\n                maxevtpts=self.algparams['maxevtpts'],\n                maxbisect=self.algparams['maxbisect'])\n            alltData, X, A, Stats, H, Err, Evtimes, \\\n                 Evpoints = self._solver.Run(init_step,\n                                    max_step,\n                                    check_aux,\n                                    use_special,\n                                    self.algparams['verbose'],\n                                    self.algparams['fac1'],\n                                    self.algparams['fac2'],\n                                    self.algparams['safety'],\n                                    self.algparams['beta'],\n                                    self.algparams['checkBounds'],\n                                    self.algparams['boundsCheckMaxSteps'],\n                                    self.algparams['magBound'])\n        self._extInputsChanged = False    # reset this now\n        self.diagnostics.outputStats = {'last_step': H,\n                            'last_time': self._solver.lastTime,\n                            'last_point': self._solver.lastPoint,\n                            'num_fcns': Stats[0],\n                            'num_steps': Stats[1],\n                            'num_accept': Stats[2],\n                            'num_reject': Stats[3],\n                            'errorStatus': Err\n                            }\n        if self._dircode == -1:\n            # reverse the array object (no reverse method!)\n            alltData = alltData[::-1]\n            X = X[:,::-1]\n            if anames != []:\n                A = A[:,::-1]\n        xnames = self._var_ixmap\n        # Package up computed trajectory in Variable variables\n        # Add external inputs warnings to self.diagnostics.warnings, if any\n        # (not presently supported)\n##        for f in inputVarList:\n##            for winfo in f.diagnostics.warnings:\n##                self.diagnostics.warnings.append((W_NONTERMSTATEBD,\n##                                     (winfo[0], f.name, winfo[1],\n##                                      f.depdomain)))\n        eventslist = self.eventstruct.query(['lowlevel', 'active'])\n        termevents = self.eventstruct.query(['term'], eventslist)\n        if self._eventNames != []:\n            # build self.diagnostics.warnings because events happened --\n            # and keep a record of which times terminal events happened because\n            # Model.py's event handling procedure assumes multiple events\n            # happening at one time are listed in one warning\n            termevtimes = {}\n            nontermevtimes = {}\n            try:\n                for evix in range(len(self._eventNames)):\n                    if Evpoints[evix] is None:\n                        continue\n                    evname = self._eventNames[evix]\n                    numevs = len(Evtimes[evix])\n                    if self.algparams['eventTerm'][evix]:\n                        if numevs > 1:\n                            print(\"Event info:%r, %r\" % (Evpoints, Evtimes))\n                        assert numevs <= 1, (\"Internal error: more than one \"\n                                         \"terminal event of same type found\")\n                        # For safety, we should assert that this event\n                        # also appears in termevents, but we don't\n                        if Evtimes[evix][0] in termevtimes.keys():\n                            # append event name to this warning\n                            warning_ix = termevtimes[Evtimes[evix][0]]\n                            self.diagnostics.warnings[warning_ix][1][1].append(evname)\n                        else:\n                            # make new termevtime entry for the new warning\n                            termevtimes[Evtimes[evix][0]] = len(self.diagnostics.warnings)\n                            self.diagnostics.warnings.append((W_TERMEVENT,\n                                             (Evtimes[evix][0],\n                                             [self._eventNames[evix]])))\n                    else:\n                        for ev in range(numevs):\n                            if Evtimes[evix][ev] in nontermevtimes.keys():\n                                # append event name to this warning\n                                warning_ix = nontermevtimes[Evtimes[evix][ev]]\n                                self.diagnostics.warnings[warning_ix][1][1].append(evname)\n                            else:\n                                # make new nontermevtime entry for the new warning\n                                nontermevtimes[Evtimes[evix][ev]] = \\\n                                                            len(self.diagnostics.warnings)\n                                self.diagnostics.warnings.append((W_NONTERMEVENT,\n                                                 (Evtimes[evix][ev],\n                                                  [evname])))\n            except IndexError:\n                print(\"Events returned from integrator are the wrong size.\")\n                print(\"  Did you change the system and not refresh the C \" \\\n                      + \"library using the forcelibrefresh() method?\")\n                raise\n        termcount = 0\n        for (w,i) in self.diagnostics.warnings:\n            if w == W_TERMEVENT or w == W_TERMSTATEBD:\n                if termcount > 0:\n                    raise ValueError(\"Internal error: more than one terminal \"\n                                     \"event found\")\n                termcount += 1\n        # post-process check of variable bounds (if defined and algparams['checkBounds'] True)\n        if self._dircode > 0:\n            compare = operator.lt\n            last_ix = Inf\n        else:\n            compare = operator.gt\n            last_ix = -Inf\n        highest_ix = X.shape[1]-1\n        last_t = Inf\n        if self.algparams['checkBounds'] > 0:\n            # temp storage for repeatedly used object attributes (for lookup efficiency)\n            depdomains = dict(zip(range(self.dimension),\n                                  [self.variables[xn].depdomain for xn in xnames]))\n            offender_ix = None\n            for xi in range(self.dimension):\n                if not any(depdomains[xi].isfinite()):\n                    # no point in checking when the bounds are +/- infinity\n                    continue\n                next_last_ix = array_bounds_check(X[xi][old_highest_ix:],\n                                    depdomains[xi], self._dircode) + old_highest_ix\n                if compare(next_last_ix, last_ix):\n                    # won't count as truncating unless the following checks\n                    # hold\n                    last_ix = next_last_ix\n                    offender_ix = xi\n            if not isfinite(last_ix) and last_ix < 0:\n                # only use +Inf hereon to flag no truncation needed\n                last_ix = Inf\n            elif last_ix >= 0 and last_ix < highest_ix:\n                # truncate data\n                last_t = alltData[last_ix]\n                print(\"Warning; domain bound reached (because algparams['checkBounds'] > 0)\")\n                self.diagnostics.warnings.append((W_TERMSTATEBD,\n                                    (last_t, xnames[offender_ix],\n                                     X[offender_ix, last_ix],\n                                     depdomains[offender_ix].get())))\n        # Create variables (self.variables contains no actual data)\n        variables = copyVarDict(self.variables)\n        # build event pointset information (reset previous trajectory's)\n        # don't include events after any truncation due to state bound violation\n        self.trajevents = {}\n        for evix in range(len(self._eventNames)):\n            evname = self._eventNames[evix]\n            if Evpoints[evix] is None:\n                self.trajevents[evname] = None\n            else:\n                try:\n                    ev_a_list = []\n                    for t in Evtimes[evix]:\n                        tix = find(alltData, t)\n                        ev_a_list.append(A[:,tix])\n                    ev_array = concatenate((Evpoints[evix],\n                                         transpose(array(ev_a_list, 'd'))))\n                    del ev_a_list, tix\n                except TypeError:\n                    # A is empty\n                    ev_array = Evpoints[evix]\n                if last_ix >= 0 and last_ix < highest_ix:\n                    # don't count last_ix = -1 which is the same as highest_ix\n                    last_ev_tix = npy.argmax(Evtimes[evix] >= alltData[last_ix])\n                    if last_ev_tix == 0 and Evtimes[evix][0] >= last_t:\n                        # checks that there was actually a violation\n                        # - so no events to record\n                        self.trajevents[evname] = None\n                    else:\n                        # truncation needed\n                        ev_array = ev_array[:, :last_ev_tix+1]\n                        ev_times = Evtimes[evix][:last_ev_tix+1]\n                        self.trajevents[evname] = Pointset({'coordnames': xnames+anames,\n                                               'indepvarname': 't',\n                                               'coordarray': ev_array,\n                                               'indepvararray': ev_times})\n                else:\n                    # no truncation needed\n                    self.trajevents[evname] = Pointset({'coordnames': xnames+anames,\n                                               'indepvarname': 't',\n                                               'coordarray': ev_array,\n                                               'indepvararray': Evtimes[evix]})\n        if last_ix >= 0 and last_ix < highest_ix:\n            # truncate\n            X = X[:, :last_ix]\n            alltData = alltData[:last_ix]\n        try:\n            allxDataDict = dict(zip(xnames,X))\n        except IndexError:\n            print(\"Integration returned variable values of unexpected dimensions.\")\n            print(\"  Did you change the system and not refresh the C library\" \\\n                  + \" using the forcelibrefresh() method?\")\n            raise\n        # storage of all auxiliary variable data\n        try:\n            if anames != []:\n                if last_ix < highest_ix:\n                    A = A[:, :last_ix]\n                try:\n                    allaDataDict = dict(zip(anames,A))\n                except TypeError:\n                    print(\"Internal error!  Type of A: %s\" % type(A))\n                    raise\n        except IndexError:\n            print(\"Integration returned auxiliary values of unexpected dimensions.\")\n            print(\"  Did you change the system and not refresh the C library\" \\\n                  + \" using the forcelibrefresh() method?\")\n            raise\n        if int(Err) == 1 or (int(Err) == 2 and termcount == 1):\n            # output OK\n            if self.algparams['poly_interp']:\n                rhsfn = self._solver.Rhs\n                # when Dopri can output the Rhs values alongside variable\n                # values then this won't be necessary\n                dxvals = zeros((len(alltData),self.dimension),float)\n                for tix, tval in enumerate(alltData):\n                    # solver's Rhs function already contains the inputs so no\n                    # need to recompute and provide here.\n                    #i = _pollInputs(sortedDictValues(self.inputs), tval,\n                    #                        self.checklevel)\n                    # X is the output variable array, but rhsfn demands a list\n                    dxvals[tix] = rhsfn(tval, list(X[:,tix]), plist)[0]\n            for xi, x in enumerate(xnames):\n                if len(alltData) > 1:\n                    if self.algparams['poly_interp']:\n                        interp = PiecewisePolynomial(alltData,\n                                    array([allxDataDict[x], dxvals[:,xi]]).T, 2)\n                    else:\n                        interp = interp1d(alltData, allxDataDict[x])\n                    variables[x] = Variable(interp, 't', x, x)\n                else:\n                    raise PyDSTool_ValueError(\"Fewer than 2 data points \"\n                                              \"computed\")\n            for a in anames:\n                if len(alltData) > 1:\n                    variables[a] = Variable(interp1d(alltData,allaDataDict[a]),\n                                             't', a, a)\n                else:\n                    raise PyDSTool_ValueError(\"Fewer than 2 data points \"\n                                              \"computed\")\n            # final checks\n            #self.validateSpec()\n            self.defined = True\n            return Trajectory(trajname, list(variables.values()),\n                              abseps=self._abseps, globalt0=self.globalt0,\n                              checklevel=self.checklevel,\n                              FScompatibleNames=self._FScompatibleNames,\n                              FScompatibleNamesInv=self._FScompatibleNamesInv,\n                              modelNames=self.name, events=self.trajevents,\n                              modelEventStructs=self.eventstruct)\n        else:\n            try:\n                diagnost_info = self.diagnostics._errorcodes[int(Err)]\n            except TypeError:\n                # errcode messed up from Dopri\n                print(\"Error code: %d\" % Err)\n                diagnost_info = self.diagnostics._errorcodes[0]\n            if self._solver.verbose:\n                info(self.diagnostics.outputStats, \"Output statistics\")\n            self.defined = False\n            # Did the solver run out of memory?\n            if (len(alltData) == self.algparams['max_pts'] or \\\n                self.diagnostics.outputStats['num_steps'] >= self.algparams['max_pts']) \\\n                   and alltData[-1] < tend:\n                print(\"max_pts algorithmic parameter too small: current \" + \\\n                      \"value is %i\"%self.algparams['max_pts'])\n#                avstep = (self.algparams['init_step']+self.diagnostics.outputStats['last_step'])/2.\n                if self.diagnostics.outputStats['last_time']-tbegin > 0:\n                    ms = str(int(round(self.algparams['max_pts'] / \\\n                              (self.diagnostics.outputStats['last_time'] - \\\n                               tbegin)*(tend-tbegin))))\n                else:\n                    ms = 'Inf'\n                print(\"(recommended value for this trajectory segment is \" + \\\n                      \"estimated to be %s (saved in diagnostics.errors attribute))\"%str(ms))\n                diagnost_info += \" -- recommended value is \" + ms\n            self.diagnostics.errors.append((E_COMPUTFAIL,\n                                    (self._solver.lastTime, diagnost_info)))\n            raise PyDSTool_ExistError(\"No trajectory created\")\n\n\n    def Rhs(self, t, xdict, pdict=None, asarray=True):\n        \"\"\"asarray is an unused, dummy argument for compatibility with Model.Rhs\"\"\"\n        # must convert names to FS-compatible as '.' sorts before letters\n        # while '_' sorts after!\n        x = sortedDictValues(filteredDict(self._FScompatibleNames(xdict),\n                                          self.funcspec.vars))\n        if pdict is None:\n            pdict = self.pars\n            # internal self.pars already is FS-compatible\n            p = sortedDictValues(pdict)\n        else:\n            p = sortedDictValues(self._FScompatibleNames(pdict))\n        i = _pollInputs(sortedDictValues(self.inputs),\n                        t, self.checklevel)\n        self._ensure_solver({'params': p, 't0': 0, 'tend': 1})\n        self._ensure_inputs()\n        return self._solver.Rhs(t, x, p+i)[0]\n\n\n    def Jacobian(self, t, xdict, pdict=None, asarray=True):\n        \"\"\"asarray is an unused, dummy argument for compatibility with\n        Model.Jacobian\"\"\"\n        if self.haveJacobian():\n            x = sortedDictValues(filteredDict(self._FScompatibleNames(xdict),\n                                              self.funcspec.vars))\n            if pdict is None:\n                pdict = self.pars\n                # internal self.pars already is FS-compatible\n                p = sortedDictValues(pdict)\n            else:\n                p = sortedDictValues(self._FScompatibleNames(pdict))\n            i = _pollInputs(sortedDictValues(self.inputs),\n                            t, self.checklevel)\n            self._ensure_solver({'params': p, 't0': 0, 'tend': 1})\n            self._ensure_inputs()\n            return self._solver.Jacobian(t, x, p+i)[0]\n        else:\n            raise PyDSTool_ExistError(\"Jacobian not defined\")\n\n\n    def JacobianP(self, t, xdict, pdict=None, asarray=True):\n        \"\"\"asarray is an unused, dummy argument for compatibility with\n        Model.JacobianP\"\"\"\n        if self.haveJacobian_pars():\n            x = sortedDictValues(filteredDict(self._FScompatibleNames(xdict),\n                                              self.funcspec.vars))\n            if pdict is None:\n                pdict = self.pars\n                # internal self.pars already is FS-compatible\n                p = sortedDictValues(pdict)\n            else:\n                p = sortedDictValues(self._FScompatibleNames(pdict))\n            i = _pollInputs(sortedDictValues(self.inputs),\n                            t, self.checklevel)\n            self._ensure_solver({'params': p, 't0': 0, 'tend': 1})\n            self._ensure_inputs()\n            return self._solver.JacobianP(t, x, p+i)[0]\n        else:\n            raise PyDSTool_ExistError(\"Jacobian w.r.t. parameters not defined\")\n\n\n    def AuxVars(self, t, xdict, pdict=None, asarray=True):\n        \"\"\"asarray is an unused, dummy argument for compatibility with\n        Model.AuxVars\"\"\"\n        x = sortedDictValues(filteredDict(self._FScompatibleNames(xdict),\n                                          self.funcspec.vars))\n        if pdict is None:\n            pdict = self.pars\n            # internal self.pars already is FS-compatible\n            p = sortedDictValues(pdict)\n        else:\n            p = sortedDictValues(self._FScompatibleNames(pdict))\n        i = _pollInputs(sortedDictValues(self.inputs),\n                        t, self.checklevel)\n        self._ensure_solver({'params': p, 't0': 0, 'tend': 1})\n        self._ensure_inputs()\n        return self._solver.AuxFunc(t, x, p+i)[0]\n\n\n    def _ensure_solver(self, pars=None):\n        if self._solver is None:\n            sortedDictValues(filteredDict(self.initialconditions, self.funcspec.vars))\n#            _integMod = self._ensureLoaded(self.modname)\n            self._solver = dopri(self.modname,\n                                 rhs=self.name, phaseDim=self.dimension,\n                                 paramDim=self.numpars,\n                                 nAux=len(self.funcspec.auxvars),\n                                 nEvents=len(self._eventNames),\n                                 nExtInputs=len(self.inputs),\n                                 hasJac=self.haveJacobian(),\n                                 hasJacP=self.haveJacobian_pars(),\n                                 hasMass=self.haveMass(),\n                                 extraSpace=self.algparams['extraspace'])\n            try:\n                genDB.register(self)\n            except PyDSTool_KeyError:\n                errstr = \"Generator \" + self.name + \": this vector field's \" +\\\n                         \"DLL is already in use\"\n                raise RuntimeError(errstr)\n            if pars is not None:\n                # tend value doesn't matter\n                self._solver.setRunParams(\n                              ic=sortedDictValues(filteredDict(self.initialconditions,\n                                                               self.funcspec.vars)),\n                              params=pars['params'],\n                              t0=pars['t0'], tend=pars['tend'],\n                              gt0=self.globalt0,\n                              refine=0, specTimes=[])\n\n    def _ensure_inputs(self, force=False):\n        if not self.inputs:\n            return\n        if force:\n            listOK = False\n        else:\n            try:\n                listOK = self._inputTimest0 == self.globalt0\n            except AttributeError:\n                # not yet defined, so proceed\n                listOK = False\n        if not listOK:\n            self._inputVarList = []\n            self._inputTimeList = []\n            self._inputTimest0 = self.globalt0\n            # inputVarList is a list of Variables or Pointsets\n            for inp in sortedDictValues(self.inputs):\n                if isinstance(inp, Variable):\n                    pts = inp.getDataPoints()\n                    if pts is None:\n                        raise TypeError(\"Can only pass external input Variable objects if based on\"\n                                        \" an underlying mesh\")\n                    else:\n                        tvals = copy(pts[inp.indepvarname])\n                        tvals -= self.globalt0\n                    self._inputVarList.append(pts[inp.coordname].tolist())\n                    self._inputTimeList.append(tvals.tolist())\n                elif isinstance(inp, Pointset):\n                    tvals = copy(inp.indepvararray)\n                    tvals -= self.globalt0\n                    self._inputVarList.append(inp[inp.coordname].tolist())\n                    self._inputTimeList.append(tvals.tolist())\n                else:\n                    raise TypeError(\"Invalid type of input\")\n        if not self._solver.initExtInputs:\n            self._solver.setExtInputs(True, deepcopy(self._inputVarList),\n                                        deepcopy(self._inputTimeList))\n        elif not listOK:\n            self._solver.clearExtInputs()\n            self._solver.setExtInputs(True, deepcopy(self._inputVarList),\n                                    deepcopy(self._inputTimeList))\n            self._solver.canContinue=True\n\n\n    def __del__(self):\n        genDB.unregister(self)\n        ODEsystem.__del__(self)\n\n\n\n# Register this Generator with the database\n\nsymbolMapDict = {'abs': 'fabs', 'sign': 'signum', 'mod': 'fmod'}\n# in future, provide appropriate mappings for libraries math,\n# random, etc. (for now it's left to FuncSpec)\ntheGenSpecHelper.add(Dopri_ODEsystem, symbolMapDict, 'c')\n", "meta": {"hexsha": "833cbe0c40668df09c7554c73546a51d348c35f6", "size": 47864, "ext": "py", "lang": "Python", "max_stars_repo_path": "PyDSTool/Generator/Dopri_ODEsystem.py", "max_stars_repo_name": "mdlama/pydstool", "max_stars_repo_head_hexsha": "3d298e908ff55340cd3612078508be0c791f63a8", "max_stars_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-04T15:01:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-25T16:08:43.000Z", "max_issues_repo_path": "PyDSTool/Generator/Dopri_ODEsystem.py", "max_issues_repo_name": "mdlama/pydstool", "max_issues_repo_head_hexsha": "3d298e908ff55340cd3612078508be0c791f63a8", "max_issues_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PyDSTool/Generator/Dopri_ODEsystem.py", "max_forks_repo_name": "mdlama/pydstool", "max_forks_repo_head_hexsha": "3d298e908ff55340cd3612078508be0c791f63a8", "max_forks_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-25T14:43:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-25T14:43:36.000Z", "avg_line_length": 47.8161838162, "max_line_length": 204, "alphanum_fraction": 0.5106342972, "include": true, "reason": "import numpy,from numpy", "num_tokens": 10033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3174262785020255, "lm_q1q2_score": 0.16738412160900232}}
{"text": "from __future__ import division, print_function\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Aug 22 13:56:32 2016\r\n\r\n@author: Trent\r\n\"\"\"\r\n\r\nfrom random import choice\r\nfrom subprocess import Popen\r\nimport numpy\r\nimport random\r\nimport time\r\nfrom sys import stdout\r\n\r\nclass SGD_Static:\r\n    \"\"\"\r\n    Test header\r\n\r\n    Attributes:\r\n        scored (bool): test score arg\r\n\r\n    Returns:\r\n        list: test list return\r\n\r\n    Example:\r\n        >>> data = SGD_Static()\r\n        >>> output = data.do_something()\r\n    \"\"\"\r\n\r\n    \r\n    def __init__(self,pdbfile,sequence_energy_file,wt_seq,sequence_alignment_file=False,reduce_alignment=1,pair_select_list=False,pair_dist=4,gamma_multiplier=2,regular_linear_regression=True,lasso=False,lambda_lasso_coef=.01,ridge=False,ridge_coef=.01,custom_tag=False):\r\n        self.pdbfile = pdbfile\r\n        self.sequence_energy_file = sequence_energy_file\r\n        self.sequence_alignment_file = sequence_alignment_file\r\n        self.pair_select_list = pair_select_list\r\n        self.gamma_multiplier = gamma_multiplier\r\n        self.wt_seq = wt_seq\r\n        self.regular_linear_regression = regular_linear_regression\r\n        self.lasso = lasso\r\n        self.ridge = ridge\r\n        self.lambda_lasso_coef = lambda_lasso_coef\r\n        self.ridge_coef = ridge_coef\r\n        self.custom_tag = custom_tag\r\n        self.overall_solution_space=None\r\n        self.energies=None\r\n        self.sequences=None\r\n        self.CC=None\r\n        self.MAD=None\r\n        self.model_parameters=None\r\n        self.pair_dist=pair_dist\r\n        self.reduce_alignment=reduce_alignment\r\n\t\r\n\r\n\r\n    def static_model(self,mad_thresh=.01,model_output_text_file=False,display_plots=True):\r\n        if not self.regular_linear_regression and not self.lasso and not self.ridge:\r\n            raise ValueError('No model type selected, one of regular_linear_regression, lasso, or ridge must be true')\r\n        if self.regular_linear_regression and self.lasso:\r\n            raise ValueError('Cannot use both regular and lasso regression, select one or the other')\r\n        if self.regular_linear_regression and self.ridge:\r\n            raise ValueError('Cannot use both regular and ridge regression, select one or the other')\r\n        if self.ridge and self.lasso:\r\n            raise ValueError('Cannot use both ridge and lasso regression, select one or the other')\r\n        if self.regular_linear_regression and self.lasso and self.ridge:\r\n            raise ValueError('Cannot use regular, ridge, and lasso regression at the same time, select one or the other')\r\n        \r\n        \r\n\r\n        starttime = time.time()\r\n\r\n        \r\n        #max_time = 252000\r\n        max_time = 5000000\r\n        start_time = time.time()\r\n        \r\n        \r\n        if not self.custom_tag:\r\n            if '/' in self.pdbfile:\r\n                pdbtag = self.pdbfile.split('/')[-1].split('.')[0]\r\n            else:\r\n                pdbtag = self.pdbfile\r\n            if '\\\\' in self.pdbfile:\r\n                pdbtag = self.pdbfile.split('\\\\')[-1].split('.')[0]        \r\n        else: \r\n            pdbtag = self.pdbfile\r\n        if self.custom_tag:\r\n             pdbtag = self.custom_tag\r\n             \r\n        print('Filename Tag will be = '+str(pdbtag))\r\n            \r\n        \r\n        L = len(self.wt_seq) # the length of the protein\r\n        \r\n        \r\n        overall_solution_space = import_sequence_alignment(self.sequence_alignment_file,self.reduce_alignment,L)\r\n        print(overall_solution_space)\r\n        \r\n        #wildtype = 'MQIFVKTLTGKTITLEVEPSDTIENVKAKIQDKEGIPPDQQRLIFAGKQLEDGRTLSDYNIQKESTLHLVLRLRGG'\r\n        wildtype = self.wt_seq\r\n        wtlist = [wildtype[i] for i in range(len(wildtype))]\r\n        reference_seq = wtlist\r\n        print(reference_seq)\r\n        \r\n        \r\n        h = open(self.sequence_energy_file,'r+')\r\n        text = h.read()\r\n        text = text.split('\\n')\r\n        del text[-1]\r\n        sequences = [t.split(',')[0] for t in text]\r\n        Energies = [float(t.split(',')[1]) for t in text]\r\n        \r\n        self.sequences=sequences\r\n        self.energies=Energies\r\n        \r\n\r\n        if self.pair_select_list:\r\n            position_pairs = pair_select(self.pdbfile,self.pair_dist,self.wt_seq)\r\n        else:\r\n            position_pairs = []\r\n        \r\n\r\n        \r\n            \r\n        \r\n        \r\n        \r\n        # Sample a random sequence, evaluate its energy according to our energy fucntion, and store the sequence and energy data\r\n        trainingsets = len(Energies)\r\n        print('Number of training sets = '+str(len(Energies)))\r\n        \r\n        E_list = []\r\n        random_Seq_list = []\r\n        CC = []\r\n        MAD = []\r\n        #w = []\r\n        Philist = []\r\n        trainE = []\r\n        trainPhi = []\r\n        print('Stochastic Gradient Descent Multivariate Linear Regression')\r\n        print('# of pair interactions = %s, gamma = %s/((i+1)**0.5)' % (len(position_pairs), self.gamma_multiplier))\r\n        print('\\n')\r\n        \r\n        \r\n        \r\n        for n in range(trainingsets):\r\n            if time.time()-start_time<max_time:\r\n                random_Seq_list.append(sequences[n])\r\n                E_list.append(Energies[n])\r\n\r\n                #Convert Seq to Phi Here\r\n                seq_Phi = [1] \r\n                for i in range(L):\r\n                    Phi_i = sigma2Phi(random_Seq_list[n][i],i,overall_solution_space,reference_seq)\r\n                    seq_Phi.extend(Phi_i)\r\n                if self.pair_select_list:\r\n                    for pair in position_pairs:\r\n                        firstpos = pair[0]\r\n                        secondpos = pair[1]\r\n                        pairs_j = pairs(random_Seq_list[n][firstpos],random_Seq_list[n][secondpos],firstpos,secondpos,overall_solution_space,reference_seq)\r\n                        seq_Phi.extend(pairs_j)\r\n                else:\r\n                    pass\r\n                if n<100:\r\n                    Philist.append(seq_Phi)\r\n                    if n==0:\r\n                        d = len(seq_Phi)\r\n                        w = numpy.zeros(shape=(d,1)) #Starting vector for regular regression not L1\r\n                        if self.lasso:\r\n                            for f in range(1,len(Phi_i*L)):\r\n                                w[f][0] = .01\r\n                        print('Number of Variables in Model = '+str(d))\r\n                if n>=100:\r\n                    Philist.append(seq_Phi)\r\n                    trainPhi = Philist[0]\r\n                    del Philist[0]\r\n                    E_testinglist = [E_list[-xx] for xx in range(1,101)]\r\n                    E_testinglist.reverse()\r\n                    trainE = E_list[n-100]\r\n                    weight = 1\r\n                    \r\n                    gamma = self.gamma_multiplier/((n-100+1)**0.5)\r\n\r\n                        \r\n                    x = numpy.array([trainPhi]).T # column vector\r\n                    if self.regular_linear_regression:\r\n                        w = w-gamma*x*weight*(numpy.dot(x.T,w)*weight - trainE*weight)\r\n                    #Ridge\r\n                    if self.ridge:\r\n                        w = w-gamma*(x*weight*(numpy.dot(x.T,w)*weight - trainE) + self.ridge_coef*w)\r\n                    #Lasso\r\n                    if self.lasso:\r\n                        w = w-gamma*x*weight*(numpy.dot(x.T,w)*weight - trainE*weight)\r\n                        for j in range(d):\r\n                            w[j][0]=STF(w[j][0],gamma*self.lambda_lasso_coef)\r\n            \r\n                    # analyze the fit of the current model w\r\n                    #Regular Matrix Multiplication\r\n                    E_estimate=numpy.empty([len(Philist),1])\r\n                    for s in range(len(Philist)):\r\n                        E_estimate[s]=numpy.dot(Philist[s],w[:,0])\r\n                    E_estimate = E_estimate[:,0]\r\n                    cc=numpy.corrcoef(E_testinglist,E_estimate)[0,1]\r\n                    mad=numpy.mean(abs(E_estimate-E_testinglist))\r\n                    CC.append(cc) # calculate the correlation coeffcient, append into list\r\n                    MAD.append(float(mad))# calculate the mean absolute deviation, append into list\r\n                    stdout.write('\\rTraining set = %s' % str(n+1)) #This prints the current training set index on same line as an update\r\n                    stdout.flush()\r\n                    madlist100 = []\r\n                    if len(MAD)>=100:\r\n                        for g in range(1,101):\r\n                            madlist100.append(MAD[-g])\r\n                        if all(mm<float(mad_thresh) for mm in madlist100):\r\n                            break\r\n           \r\n        if model_output_text_file:\r\n            open('w'+str(pdbtag)+'.txt','w')\r\n            for vv in range(len(w)):\r\n                open('w'+str(pdbtag)+'.txt','a').write(str(w[vv][0])+'\\n')             \r\n                  \r\n                  \r\n        self.CC=CC\r\n        self.MAD=MAD\r\n        self.model_parameters=w\r\n        if display_plots:  \r\n            import matplotlib.pyplot as plt\r\n            plt.plot(range(len(MAD)),MAD)\r\n            plt.show()\r\n            \r\n            plt.plot(range(len(CC)),CC)\r\n            plt.show()\r\n            \r\n            \r\n            \r\n            plt.scatter(E_testinglist,E_estimate)\r\n            plt.show()\r\n        \r\n        print('energy function fit:')\r\n        print('\\tCC = %0.2f' % CC[(len(MAD))-1])\r\n        print('\\tMAD = %0.2f' % MAD[(len(MAD))-1])\r\n        \r\n        #Test to see how many features are zero...\r\n        zerolist = []\r\n        for z in range(len(w)):\r\n            if w[z][0]==0:\r\n                zerolist.append(z)\r\n        print('Number of Features Equal to Zero in the Model = %s' % len(zerolist))\r\n        \r\n        sumlist = []\r\n        for i in range(1000):\r\n            sumlist.append(MAD[-i])\r\n        print('Avg MAD of last 1000 terms = '+str(sum(sumlist)/1000))\r\n        \r\n        elapsedtime = time.time() - starttime \r\n        print('time = %0.2f' % elapsedtime)\r\n        return w\r\n\r\n\r\n\r\nclass SGD_Online:\r\n    \r\n    def __init__(self,wt_seq,pdbfile,sequence_alignment_file=False,reduce_alignment=2,output_energy_file=False,\r\n                 custom_tag=False,pair_select_list=False,pair_dist=4,gamma_multiplier=2,\r\n                 regular_linear_regression=True,lasso=False,lambda_lasso_coef=.01,ridge=False,\r\n                 ridge_coef=.01,output_cc=True,output_mad=True,\r\n                 rosetta_score_path='/home/romeroroot/code/rosetta_src_2016.17.58663_bundle/main/source/bin/',\r\n                 rosetta_database_path='/home/romeroroot/code/rosetta_src_2016.17.58663_bundle/main/database'):\r\n                     \r\n                     \r\n        'Takes in a pdb file, sequence alignment file, wild type sequence, and energy scoring script'\r\n        'We provide two scoring scripts score_sequence_amber.py and score_sequence_rosetta.py'\r\n        'The rosetta script requires rosetta protein structure software'\r\n        'The amber script requires openmm molecular modeling software as well as rosetta for energy minimization'\r\n        'this class must run in command line to make use of energy scoring scripts which output energies to command line'        \r\n        self.pdbfile = pdbfile\r\n        self.pair_select_list = pair_select_list\r\n        self.gamma_multiplier = gamma_multiplier\r\n        self.wt_seq = wt_seq\r\n        self.regular_linear_regression = regular_linear_regression\r\n        self.lasso = lasso\r\n        self.ridge = ridge\r\n        self.lambda_lasso_coef = lambda_lasso_coef\r\n        self.ridge_coef = ridge_coef\r\n        self.output_energy_file = output_energy_file\r\n        self.output_cc = output_cc\r\n        self.output_mad = output_mad\r\n        self.custom_tag = custom_tag\r\n        self.overall_solution_space=None\r\n        self.CC=None\r\n        self.MAD=None\r\n        self.model_parameters=None\r\n        self.reduce_alignment = reduce_alignment\r\n        self.pair_dist=pair_dist\r\n        self.sequence_alignment_file=sequence_alignment_file\r\n        self.rosetta_score_path = rosetta_score_path\r\n        self.rosetta_database_path = rosetta_database_path\r\n\r\n\r\n    def online_model(self,energy_scoring_function='rosetta',num_mutations=4,max_computation_time=252000,max_training_sets=50000,mad_cutoff=1,w_start_file=False):\r\n        #Scoring function is either 'rosetta' or 'amber'\r\n        \r\n        if not self.regular_linear_regression and not self.lasso and not self.ridge:\r\n            raise ValueError('No model type selected, one of regular_linear_regression, lasso, or ridge must be true')\r\n        if self.regular_linear_regression and self.lasso:\r\n            raise ValueError('Cannot use both regular and lasso regression, select one or the other')\r\n        if self.regular_linear_regression and self.ridge:\r\n            raise ValueError('Cannot use both regular and ridge regression, select one or the other')\r\n        if self.ridge and self.lasso:\r\n            raise ValueError('Cannot use both ridge and lasso regression, select one or the other')\r\n        if self.regular_linear_regression and self.lasso and self.ridge:\r\n            raise ValueError('Cannot use regular, ridge, and lasso regression at the same time, select one or the other')\r\n        \r\n        \r\n\r\n        starttime = time.time()\r\n        \r\n        \r\n        \r\n        max_time = max_computation_time\r\n        \r\n        if w_start_file:\r\n            hh = open(w_start_file,'r+')\r\n            newtext = hh.read()\r\n            newtext = newtext.split('\\n')\r\n            del newtext[-1]\r\n            w = []\r\n            for numbers in newtext:\r\n                w.append(float(numbers))\r\n\r\n\r\n        wildtype = self.wt_seq\r\n        wtlist = [wildtype[i] for i in range(len(wildtype))]\r\n        \r\n        L = len(wildtype)\r\n        \r\n        overall_solution_space = import_sequence_alignment(self.sequence_alignment_file,self.reduce_alignment,L)\r\n        print(overall_solution_space)\r\n\r\n        trainingsets = max_training_sets\r\n        madcutoff = mad_cutoff\r\n        \r\n        \r\n        #Here Creating the tag that follows to output files...\r\n        #This is skipped if a custom_tag variable is defined\r\n        if not self.custom_tag:\r\n            if '/' in self.pdbfile:\r\n                pdbtag = self.pdbfile.split('/')[-1].split('.')[0]\r\n            else:\r\n                pdbtag = self.pdbfile\r\n            if '\\\\' in self.pdbfile:\r\n                pdbtag = self.pdbfile.split('\\\\')[-1].split('.')[0]        \r\n        else: \r\n            pdbtag = self.pdbfile\r\n        if self.custom_tag:\r\n             pdbtag = self.custom_tag\r\n             \r\n        print('Filename Tag will be = '+str(pdbtag))\r\n            \r\n        if self.output_energy_file:\r\n            seqEfilename = 'ubiquitin_energies_'+str(pdbtag)+'.txt'\r\n\r\n        \r\n        \r\n        \r\n        \r\n         # the length of the protein\r\n        \r\n\r\n\r\n        \r\n        reference_seq = wtlist\r\n        print(reference_seq)\r\n        \r\n\r\n        \r\n        if self.pair_select_list:\r\n            position_pairs = pair_select(self.pdbfile,self.pair_dist,self.wt_seq)\r\n        else:\r\n            position_pairs = []\r\n        \r\n        #Definitions\r\n        \r\n        # Sample a random sequence, evaluate its energy according to our energy fucntion, and store the sequence and energy data\r\n        \r\n        \r\n        E_list = []\r\n        CC = []\r\n        MAD = []\r\n        Philist = []\r\n        print('Stochastic Gradient Descent')\r\n        print('# of pair interactions = %s, %s maximum training sequences, gamma = %s/((i+1)**0.5)' % (len(position_pairs),trainingsets, self.gamma_multiplier))\r\n        \r\n        if self.output_energy_file:    \r\n            open(seqEfilename,'w')\r\n        if self.output_cc:\r\n            open('CC'+str(pdbtag)+'.txt','w')\r\n        if self.output_mad:\r\n            open('MAD'+str(pdbtag)+'.txt','w')\r\n            \r\n            \r\n        for n in range(trainingsets):\r\n            if time.time()-starttime<max_time:\r\n                wildtype = self.wt_seq\r\n                wtlist = [wildtype[i] for i in range(len(wildtype))]\r\n                randAAlist = []\r\n                for i in range(num_mutations):\r\n                    randAAlist.append(random.randint(0,L-1))\r\n                for mutantpositions in randAAlist:\r\n                    wtlist[mutantpositions] = choice(overall_solution_space[mutantpositions])\r\n                random_seq = ''.join(wtlist)\r\n                \r\n                #cmd = 'python '+str(self.energy_scoring_script)+' %s' % random_seq #1. generate a terminal command as a string\r\n                #output = Popen(cmd,shell=True,stdout=PIPE).communicate() #2. send the command to the terminal shell\r\n                #seq_E = float(output[0]) #3. read the result and convert to a float\r\n                \r\n                'Add a new energy scoring function here if wanted'\r\n                'Input should be random_seq and an associated pdbfile'\r\n                'Should create a definition similar to the two energy function definitions provided'\r\n                'if there is a need or want for a different energy function' \r\n                if energy_scoring_function=='amber':\r\n                    seq_E = score_sequence_amber(random_seq,pdbfile=self.pdbfile,\r\n                                                   rosetta_path = self.rosetta_score_path,\r\n                                                   rosetta_db = self.rosetta_database_path)          \r\n                \r\n                if energy_scoring_function=='rosetta':\r\n                    seq_E = score_sequence_rosetta(random_seq,pdbfile=self.pdbfile,\r\n                                                   rosetta_path = self.rosetta_score_path,\r\n                                                   rosetta_db = self.rosetta_database_path)          \r\n                \r\n                \r\n                #This bypasses Amber not returning scores for certain sequences\r\n                if seq_E=='Nan':\r\n                    print('Sequence did not generate a score')\r\n                    pass                \r\n                \r\n                if seq_E!='Nan':\r\n                    #print(seq_E)\r\n                    seq_E = float(seq_E) #3. read the result and convert to a float\r\n                \r\n                \r\n    \r\n    \r\n                    print(random_seq, seq_E)\r\n                    if self.output_energy_file:\r\n                        open(seqEfilename,'a').write(random_seq+','+str(seq_E)+'\\n')\r\n                    E_list.append(seq_E)\r\n                    #Convert Seq to Phi Here\r\n                    seq_Phi = [1] \r\n                    for i in range(L):\r\n                        Phi_i = sigma2Phi(random_seq[i],i,overall_solution_space,reference_seq)\r\n                        seq_Phi.extend(Phi_i)\r\n                    if self.pair_select_list:\r\n                        for pair in position_pairs:\r\n                            firstpos = pair[0]\r\n                            secondpos = pair[1]\r\n                            pairs_j = pairs(random_seq[firstpos],random_seq[secondpos],firstpos,secondpos,overall_solution_space,reference_seq)\r\n                            seq_Phi.extend(pairs_j)\r\n                    else:\r\n                        pass\r\n                    if len(E_list)-1<100:\r\n                        Philist.append(seq_Phi)\r\n                        if n==0:\r\n                            d = len(seq_Phi)\r\n                            if not w_start_file:\r\n                                w = numpy.zeros(shape=(d,1)) #Starting vector for regular regression not L1\r\n                                if self.lasso:\r\n                                    for f in range(1,len(Phi_i*L)):\r\n                                        w[f][0] = .01\r\n                            print('Number of Variables in Model = '+str(d))\r\n                    if len(E_list)-1>=100:\r\n                        Philist.append(seq_Phi)\r\n                        trainPhi = Philist[0]\r\n                        del Philist[0]\r\n                        E_testinglist = [E_list[-xx] for xx in range(1,101)]\r\n                        E_testinglist.reverse()\r\n                        trainE = E_list[len(E_list)-1-100]\r\n                        weight = 1\r\n                        \r\n                        gamma = self.gamma_multiplier/((n+1)**0.5) # have to do plus one cause first round i = 0\r\n                        \r\n                        x = numpy.array([trainPhi]).T # column vector\r\n                        if self.regular_linear_regression:\r\n                            w = w-gamma*x*weight*(numpy.dot(x.T,w)*weight - trainE*weight)\r\n                        #Ridge\r\n                        if self.ridge:\r\n                            w = w-gamma*(x*weight*(numpy.dot(x.T,w)*weight - trainE) + self.ridge_coef*w)\r\n                        #Lasso\r\n                        if self.lasso:\r\n                            w = w-gamma*x*weight*(numpy.dot(x.T,w)*weight - trainE*weight)\r\n                            for j in range(d):\r\n                                w[j][0]=STF(w[j][0],gamma*self.lambda_lasso_coef)\r\n                \r\n        \r\n                        E_estimate=numpy.empty([len(Philist),1])\r\n                        for s in range(len(Philist)):\r\n                            E_estimate[s]=numpy.dot(Philist[s],w[:,0])\r\n                        E_estimate = E_estimate[:,0]\r\n                        cc=numpy.corrcoef(E_testinglist,E_estimate)[0,1]\r\n                        mad=numpy.mean(abs(E_estimate-E_testinglist))\r\n                        print('cc = '+str(cc))\r\n                        print('mad = '+str(mad))\r\n                        CC.append(cc) # calculate the correlation coeffcient, append into list\r\n                        MAD.append(mad)# calculate the mean absolute deviation, append into list\r\n                        if self.output_cc:\r\n                            open('CC'+str(pdbtag)+'.txt','a').write(str(cc)+'\\n')\r\n                        if self.output_mad:\r\n                            open('MAD'+str(pdbtag)+'.txt','a').write(str(mad)+'\\n')\r\n                        madlist100 = []\r\n                        if len(MAD)>=100:\r\n                            for g in range(1,101):\r\n                                madlist100.append(MAD[-g])\r\n                            if all(mm<float(madcutoff) for mm in madlist100):\r\n                                break\r\n        \r\n        open('w'+str(pdbtag)+'.txt','w')\r\n        #open('wState0.txt','w')\r\n        for vv in range(len(w)):\r\n            open('w'+str(pdbtag)+'.txt','a').write(str(w[vv][0])+'\\n')\r\n        \r\n        self.CC=CC\r\n        self.MAD=MAD\r\n        self.model_parameters=w\r\n        \r\n        print('energy function fit:')\r\n        print('\\tCC = %0.2f' % CC[(len(MAD))-1])\r\n        print('\\tMAD = %0.2f' % MAD[(len(MAD))-1])\r\n        \r\n        #plt.scatter(E_testinglist,E_estimate)\r\n        #plt.show()\r\n        \r\n        \r\n        \r\n        \r\n        #Test to see how many features are zero...\r\n        zerolist = []\r\n        for z in range(len(w)):\r\n            if w[z][0]==0:\r\n                zerolist.append(z)\r\n        print('Number of Features Equal to Zero in the Model = %s' % len(zerolist))\r\n        \r\n        elapsedtime = time.time() - starttime \r\n        print('time = %0.2f' % elapsedtime)\r\n        return w\r\n        \r\n        \r\n    \r\n    \r\n    \r\ndef score_sequence_amber(newseq=None,pdbfile=None,rosetta_path = '/home/romeroroot/code/rosetta_src_2016.17.58663_bundle/main/source/bin/',rosetta_db = '/home/romeroroot/code/rosetta_src_2016.17.58663_bundle/main/database'):   \r\n    'Provide rosetta path to fixbb.linuxgccrelease'\r\n    from random import choice\r\n    from os import remove\r\n    import simtk.openmm.app as app\r\n    import simtk.openmm as op\r\n    import simtk.unit as unit\r\n\r\n    def rand_tag():\r\n        '''creates a unique tag that can be used to identify the current files a script is working with.  necessary for running the same program multiple times in the same directory'''\r\n        alpha = 'abcdefghijklmnopqrstuvwxyz0123456789'\r\n        tag = ''.join([choice(alpha) for i in range(15)])\r\n        return tag\r\n    \r\n    \r\n    \r\n    def thread_repack_score_amber(pdbfile,newseq):\r\n    \r\n        tag = rand_tag() # generate a random tag to associate with this run\r\n    \r\n        # generate a resfile to mutate the pdb\r\n        resfile = \"\"\"\r\n        #header\r\n        NATAA # keep this so all sites aren't designed\r\n        USE_INPUT_SC # this to also consider the WT rotamer, if we're mutating WT to WT\r\n    \r\n        start\r\n    \r\n        #body\\n\"\"\"\r\n    \r\n        for i in range(len(newseq)):\r\n            resfile += '%i    A    PIKAA %s \\n'%(i+1,newseq[i])\r\n    \r\n        open('resfile_'+tag+'.res','w').write(resfile)\r\n    \r\n    \r\n        # the options for the run\r\n        options = ['nice',\r\n                   rosetta_path+'fixbb.linuxgccrelease', # fixbb is the program used for threading a repacking\r\n                   '-s '+pdbfile, \r\n                   '-database '+rosetta_db, # good to explicitly define location of rosetta DB\r\n                   '-resfile resfile_'+tag+'.res', # a resfile to specify mutations\r\n                   '-out:suffix _'+tag] # this adds a suffix to the score output file: score_[RNDTAG].sc\r\n    \r\n        # run fixbb\r\n        Popen(options,stdout=open('/dev/null','w')).wait() # send stdout to the trash, report stderr\r\n    \r\n    \r\n        # read the output\r\n        scorefile = open('score_%s.sc'%tag).read().split('\\n')\r\n        names = scorefile[1].split(':')[1].split()\r\n        values = scorefile[2].split(':')[1].split()\r\n        score = dict((names[i],float(values[i])) for i in range(len(names)-1)) # use i-1 because the last entry is the filename\r\n        pdbname = (pdbfile[:-4]+'_'+tag+'_0001.pdb').split('/')[-1]\r\n    \r\n    \r\n        # now load into openMM and score with amber\r\n        pdb = app.PDBFile(pdbname)\r\n        forcefield = app.ForceField('amber03.xml','amber03_obc.xml')\r\n        system = forcefield.createSystem(pdb.topology, nonbondedMethod=app.NoCutoff, constraints=None)\r\n        integrator = op.LangevinIntegrator(300*unit.kelvin, 1/unit.picosecond, 1e-9*unit.picoseconds)\r\n        simulation = app.Simulation(pdb.topology, system, integrator)\r\n        simulation.context.setPositions(pdb.positions)\r\n    \r\n    \r\n        #Must do try/except here because Amber occasionally throws an Exception error and does not return a score\r\n        try:\r\n            simulation.minimizeEnergy()\r\n            state = simulation.context.getState(getPositions=True, getEnergy=True)\r\n            score = state.getPotentialEnergy()/unit.kilojoule_per_mole\r\n    \r\n        except Exception:\r\n            score = 'Nan'\r\n            pass\r\n    \r\n    \r\n        #delete the evidence\r\n        remove('score_%s.sc'%tag)\r\n        remove('resfile_'+tag+'.res')\r\n        remove(pdbname)\r\n    \r\n        return score\r\n    \r\n    \r\n    score = thread_repack_score_amber(pdbfile,newseq)\r\n    return score\r\n    \r\n    \r\n    \r\ndef score_sequence_rosetta(newseq,pdbfile,rosetta_path = '/home/romeroroot/code/rosetta_src_2016.17.58663_bundle/main/source/bin/',rosetta_db = '/home/romeroroot/code/rosetta_src_2016.17.58663_bundle/main/database'):\r\n    from random import choice\r\n    from subprocess import Popen\r\n    from os import remove\r\n\r\n    def rand_tag():\r\n        '''creates a unique tag that can be used to identify the current files a script is working with.  necessary for running the same program multiple times in the same directory'''\r\n        alpha = 'abcdefghijklmnopqrstuvwxyz0123456789'\r\n        tag = ''.join([choice(alpha) for i in range(15)])\r\n        return tag\r\n    \r\n    \r\n    \r\n    def fast_thread_repack_score(pdbfile,newseq,savepdb=False):\r\n        \"\"\"this function inputs a pdbfile name and a sequence, mutates the pdb file, repacks, and returns the scores as a dict\r\n        REQUIRES: pdbfile to be consecutivly numbered from 1 to N, and len(newseq) = N. Used when we want to score seqence variants many times\r\n        \"\"\"\r\n    \r\n        tag = rand_tag() # generate a random tag to associate with this run\r\n    \r\n    \r\n        # generate a resfile to mutate the pdb\r\n        resfile = \"\"\"\r\n        #header\r\n        NATAA # keep this so all sites aren't designed\r\n        USE_INPUT_SC # this to also consider the WT rotamer, if we're mutating WT to WT\r\n    \r\n        start\r\n    \r\n        #body\\n\"\"\"\r\n    \r\n        for i in range(len(newseq)):\r\n            resfile += '%i    A    PIKAA %s \\n'%(i+1,newseq[i])\r\n    \r\n        open('resfile_'+tag+'.res','w').write(resfile)\r\n    \r\n    \r\n        # the options for the run\r\n        options = ['nice',\r\n                   rosetta_path+'fixbb.linuxgccrelease', # fixbb is the program used for threading a repacking\r\n                   '-s '+pdbfile, \r\n                   '-database '+rosetta_db, # good to explicitly define location of rosetta DB\r\n                   '-resfile resfile_'+tag+'.res', # a resfile to specify mutations\r\n                   '-out:suffix _'+tag] # this adds a suffix to the score output file: score_[RNDTAG].sc\r\n    \r\n        # run fixbb\r\n        Popen(options,stdout=open('/dev/null','w')).wait() # send stdout to the trash, report stderr\r\n    \r\n    \r\n        # read the output\r\n        scorefile = open('score_%s.sc'%tag).read().split('\\n')\r\n        names = scorefile[1].split(':')[1].split()\r\n        values = scorefile[2].split(':')[1].split()\r\n        score = dict((names[i],float(values[i])) for i in range(len(names)-1)) # use i-1 because the last entry is the filename\r\n    \r\n    \r\n        #delete the evidence\r\n        remove('score_%s.sc'%tag)\r\n        remove('resfile_'+tag+'.res')\r\n    \r\n        pdbname = (pdbfile[:-4]+'_'+tag+'_0001.pdb').split('/')[-1]\r\n        if savepdb:\r\n            return score,pdbname\r\n        else:\r\n            remove(pdbname)\r\n            return score\r\n\r\n    score = fast_thread_repack_score(pdbfile,newseq)\r\n    return score['total_score']\r\n\r\n\r\ndef pair_select(pdbfile,dist,wt_seq):\r\n    \"Here we select the maximum distance for a pair of AAs to be considered important\"\r\n    angstrom_distance = dist\r\n    #########################################################################\r\n    #this should really use the 'state' pdb files....\r\n    L = len(wt_seq)\r\n    \r\n    \r\n    \r\n    \r\n    \r\n    #AAs = ['A', 'C', 'D', 'E', 'F', 'G', 'H','I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W','Y'] #all 20 amino acids\r\n    \r\n    \r\n\r\n    pdbdata = open(pdbfile).read()\r\n    \r\n    pdblines = pdbdata.split('\\n')\r\n    \r\n    coordinates = []\r\n    for line in pdblines:\r\n        if line[:4]=='ATOM':\r\n            coordinates.append(line)\r\n    \r\n    #\"Why is there a lot of extra sequences in the pdb file\"\r\n    #for i in range(4123):\r\n    #    coordinates.pop()\r\n    \r\n    \"Here we make lists of all atoms x,y,z coordinates and pair them by which AA they are in into lists, each list corresponds to the atoms in each AA\"\r\n    xcoors = {}\r\n    for q in range(1,L+1):\r\n        xcoors['AAxcoor'+str(q)] = []\r\n    \r\n    for j in range(L+1):\r\n        for line in coordinates:\r\n            if int(line[22:26])==j:\r\n                x = line[30:38]\r\n                xnum = float(x)\r\n                xcoors['AAxcoor'+str(j)].append(xnum)\r\n    \r\n    ycoors = {}\r\n    for q in range(1,L+1):\r\n        ycoors['AAycoor'+str(q)] = []\r\n    \r\n    for k in range(L+1):\r\n        for line in coordinates:\r\n            if int(line[22:26])==k:\r\n                y = line[38:46]\r\n                ynum = float(y)\r\n                ycoors['AAycoor'+str(k)].append(ynum)\r\n    \r\n    zcoors = {}\r\n    for q in range(1,L+1):\r\n        zcoors['AAzcoor'+str(q)] = []\r\n    \r\n    for s in range(L+1):\r\n        for line in coordinates:\r\n            if int(line[22:26])==s:\r\n                z = line[46:54]\r\n                znum = float(z)\r\n                zcoors['AAzcoor'+str(s)].append(znum)\r\n                \r\n    \r\n    \"Pair all xyz together\"\r\n    listofxyz = {}\r\n    for q in range(1,L+1):\r\n        listofxyz['listofxyz'+str(q)] = []\r\n    \r\n    \"XYZ points of all atoms sorted into lists of corresponding AAs\"\r\n    for q in range(1,L+1):\r\n        for j in range(len(xcoors['AAxcoor'+str(q)])):\r\n            listofxyz['listofxyz'+str(q)].append((xcoors['AAxcoor'+str(q)][j],ycoors['AAycoor'+str(q)][j],zcoors['AAzcoor'+str(q)][j]))\r\n        \r\n    \"Here we find the distance between every atom in the protein separated by the atoms that belong to specific AAs\"\r\n    atomtoatom = {}\r\n    for i in range(1,L+1):\r\n        for j in range(1,L+1):\r\n            if i<j:\r\n                atomtoatom['atomtoatom'+str(i)+'-'+str(j)] = []\r\n                for k in range(len(listofxyz['listofxyz'+str(i)])):\r\n                    for f in range(len(listofxyz['listofxyz'+str(j)])):\r\n                        atomtoatom['atomtoatom'+str(i)+'-'+str(j)].append(numpy.linalg.norm(numpy.array(listofxyz['listofxyz'+str(i)])[k]-numpy.array(listofxyz['listofxyz'+str(j)])[f]))\r\n    \r\n    \"Here we take the minimum distance between atoms between all AAs\"\r\n    minimumdistances = {}\r\n    for i in range(1,L+1):\r\n        for j in range(1,L+1):\r\n            if i<j and atomtoatom['atomtoatom'+str(i)+'-'+str(j)] != []: #New shit here...\r\n                minimumdistances['minimumdistances'+str(i)+'-'+str(j)] = []\r\n                minimumdistances['minimumdistances'+str(i)+'-'+str(j)] = min(atomtoatom['atomtoatom'+str(i)+'-'+str(j)])\r\n    \r\n    \"Here we determine which pairs are close enough by setting an angstrom_distance constraint\"\r\n    closeatoms = []\r\n    for i in range(1,L+1):\r\n        for j in range(1,L+1):\r\n            if all([i<j and minimumdistances['minimumdistances'+str(i)+'-'+str(j)]<float(angstrom_distance)]):\r\n            #if all([i<j and minimumdistances['minimumdistances'+str(i)+'-'+str(j)]<float(angstrom_distance) and abs(i-j)!=1]):\r\n                closeatoms.append((i,j))\r\n    \r\n    \"Here we subtract of (1,1) from each pair to match the indecies of the regression format\"  \r\n    \r\n\r\n              \r\n    newcloseatoms = numpy.array(closeatoms) - (1,1)\r\n    newcloseatoms = map(tuple, newcloseatoms)\r\n    \r\n    print(len(newcloseatoms))\r\n    return newcloseatoms\r\n\r\n\r\ndef import_sequence_alignment(seq_align_file,reduce_alignment,seq_len):\r\n    if seq_align_file:\r\n        h = open(seq_align_file,'r+')\r\n        text = h.read()\r\n        text = text.split('\\n')\r\n        del text[-1]\r\n        \r\n        overall_solution_space = []\r\n        for topaminoacids in text:\r\n            tempsolspace = []\r\n            for i in range(len(topaminoacids)):\r\n                tempsolspace.append(topaminoacids[i])\r\n            overall_solution_space.append(tempsolspace)\r\n            \r\n        #This part deletes the last AA at each position to have one less AA per position\r\n        #Take this out Eventually\r\n        if reduce_alignment:\r\n            for i in range(reduce_alignment):\r\n                 for top5 in overall_solution_space:\r\n                     del top5[-1]  \r\n            return overall_solution_space\r\n        else:\r\n            return overall_solution_space\r\n    else:\r\n        AAs = ['A', 'C', 'D', 'E', 'F', 'G', 'H','I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W','Y'] #all 20 amino acids\r\n        overall_solution_space = []\r\n        for i in range(len(seq_len)):\r\n            overall_solution_space.append(AAs)\r\n        return overall_solution_space\r\n        \r\n#Definitions\r\ndef sigma2Phi(sigma,i,overall_solution_space,reference_seq):\r\n    \"\"\"This takes in an amino acid and a position and returns the 1x19 binary indicator vector Phi\"\"\"\r\n    AAchanges = [aa for aa in overall_solution_space[i] if aa!=reference_seq[i]] # these are all 19 possible AA changes (i.e. AAs that are not the reference sequence AA)\r\n    #AAchanges = [aa for aa in AAs if aa!=reference_seq[i]]\r\n    Phi = []\r\n    for aa in AAchanges:\r\n        if sigma==aa:\r\n            Phi.append(1)\r\n        else:\r\n            Phi.append(0)\r\n    return Phi\r\n\r\ndef pairs(aa1,aa2,i,h,overall_solution_space,reference_seq):\r\n    #This generates the pairs associated with currently solution space \r\n    #Similar to sigma2Phi but for the pairs\r\n    AAchanges1 = [aa for aa in overall_solution_space[i] if aa!=reference_seq[i]]\r\n    AAchanges2 = [bb for bb in overall_solution_space[h] if bb!=reference_seq[h]]\r\n    Phi = []\r\n    for aa in AAchanges1:\r\n        for bb in AAchanges2:\r\n            if (aa1==aa and aa2==bb):\r\n                Phi.append(1)\r\n            else:\r\n                Phi.append(0)\r\n    return Phi\r\n    \r\n\r\n\r\n#Used in the lasso function\r\ndef STF(a,z):\r\n    if a>z:\r\n        return a-z\r\n    if a<-z:\r\n        return a+z\r\n    if -z<=a<=z:\r\n        return 0\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "38421275272f563b6eeca52431b2e257aaa2888a", "size": 36544, "ext": "py", "lang": "Python", "max_stars_repo_path": "msm_design/msm_model.py", "max_stars_repo_name": "trenth12/MSM-Design", "max_stars_repo_head_hexsha": "b78b0c69f612b8451b0f9d15b99a3b68f817ec4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-10-05T06:50:48.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-05T06:50:48.000Z", "max_issues_repo_path": "msm_design/msm_model.py", "max_issues_repo_name": "trenth12/MSM-Design", "max_issues_repo_head_hexsha": "b78b0c69f612b8451b0f9d15b99a3b68f817ec4e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "msm_design/msm_model.py", "max_forks_repo_name": "trenth12/MSM-Design", "max_forks_repo_head_hexsha": "b78b0c69f612b8451b0f9d15b99a3b68f817ec4e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0606741573, "max_line_length": 272, "alphanum_fraction": 0.5336306918, "include": true, "reason": "import numpy", "num_tokens": 8219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.16738411820402732}}
{"text": "#!/usr/bin/env python3\n\nimport argparse\nfrom collections import Counter\nimport pdb\nimport pickle\nimport re\nimport sys\nimport time\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch import optim\nimport torch.nn.functional as F\nimport torch.multiprocessing as mp\n\nimport data_producer\n\nfrom multiprocessing import set_start_method\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--train\", type=str, default=\"\", help=\"training file\")\nparser.add_argument(\"--vocab\", type=str, default=\"\", help=\"vocab pickle file\")\nparser.add_argument(\"--save\", type=str, default=\"csv.pth.tar\", help=\"saved model filename\")\nparser.add_argument(\"--size\", type=int, default=300, help=\"word embedding dimension\")\nparser.add_argument(\"--window\", type=int, default=5, help=\"context window size\")\nparser.add_argument(\"--sample\", type=float, default=1e-5, help=\"subsample threshold\")\nparser.add_argument(\"--negative\", type=int, default=10, help=\"number of negative samples\")\nparser.add_argument(\"--delta\", type=float, default=0.15, help=\"create new sense for a type if similarity lower than this value.\")\nparser.add_argument(\"--min_count\", type=int, default=5, help=\"minimum frequency of a word\")\nparser.add_argument(\"--processes\", type=int, default=4, help=\"number of processes\")\nparser.add_argument(\"--num_workers\", type=int, default=6, help=\"number of workers for data processsing\")\nparser.add_argument(\"--iter\", type=int, default=3, help=\"number of iterations\")\nparser.add_argument(\"--lr\", type=float, default=-1.0, help=\"initial learning rate\")\nparser.add_argument(\"--batch_size\", type=int, default=100, help=\"(max) batch size\")\nparser.add_argument(\"--cuda\", action='store_true', default=False, help=\"enable cuda\")\nparser.add_argument(\"--multi_proto\", action='store_true', default=False, help=\"True: multi-prototype, False:single-prototype\")\n\nMAX_SENT_LEN = 1000\n\n# Build the vocabulary.\ndef file_split(f, delim=' \\t\\n', bufsize=1024):\n    prev = ''\n    while True:\n        s = f.read(bufsize)\n        if not s:\n            break\n        tokens = re.split('['+delim+']{1,}', s)\n        if len(tokens) > 1:\n            yield prev + tokens[0]\n            prev = tokens[-1]\n            for x in tokens[1:-1]:\n                yield x\n        else:\n            prev += s\n    if prev:\n        yield prev\n\ndef build_vocab(args):\n    vocab = Counter()\n    word_count = 0\n    for word in file_split(open(args.train)):\n        vocab[word] += 1\n        word_count += 1\n        if word_count % 10000 == 0:\n            sys.stdout.write('%d\\r' % len(vocab))\n    freq = {k:v for k,v in vocab.items() if v >= args.min_count}\n    word_count = sum([freq[k] for k in freq])\n    word_list = sorted(freq, key=freq.get, reverse=True)\n    word2idx = {}\n    for i,w in enumerate(word_list):\n        word2idx[w] = i\n\n    print(\"Vocab size: %ld\" % len(word2idx))\n    print(\"Words in train file: %ld\" % word_count)\n    vars(args)['vocab_size'] = len(word2idx)\n    vars(args)['train_words'] = word_count\n\n    return word2idx, word_list, freq\n\n\nclass CSV(nn.Module):\n    def __init__(self, args):\n        super(CSV, self).__init__()\n        self.global_embs = nn.Embedding(args.vocab_size+1, args.size, padding_idx=args.vocab_size, sparse=True)\n        self.sense_embs = nn.Embedding(args.vocab_size*5, args.size, sparse=True)\n        self.ctx_weight = torch.nn.Parameter(torch.ones(2*args.window, args.size))\n        self.word2sense = [ [i] for i in range(args.vocab_size) ]\n        '''\n        word2sense = np.zeros((args.vocab_size, 5), dtype='int32')                                                                                      \n        for i in range(args.vocab_size):                                              \n            word2sense[i, 0] = i\n        self.word2sense = torch.nn.Parameter(torch.from_numpy(word2sense).int())\n        self.word_sense_cnts = torch.nn.Parameter(torch.ones((args.vocab_size,)).int())\n        '''\n\n        self.global_embs.weight.data.uniform_(-0.5/args.size, 0.5/args.size)\n        self.sense_embs.weight.data.uniform_(-0.5/args.size, 0.5/args.size)\n\n        self.n_senses = args.vocab_size\n        self.sense_capacity = args.vocab_size*5\n        self.batch_size = args.batch_size\n        self.size = args.size\n        self.window = args.window\n        self.negative = args.negative\n        self.pad_idx = args.vocab_size\n\n    def get_context_feats(self, ctx_type_indices):\n        ctx_type_embs = self.global_embs(ctx_type_indices)\n        return torch.sum(ctx_type_embs * self.ctx_weight, 1).cpu().data.numpy()\n\n    def get_possible_sense_embs(self, type_indices, cuda=True):\n        sense_indices = []\n        sense2idx = {}\n        for type_id in type_indices:\n            for s_id in self.word2sense[type_id]:\n                if s_id not in sense2idx:\n                    sense2idx[s_id] = len(sense_indices)\n                    sense_indices.append( s_id )\n        sense_indices = np.array(sense_indices)\n\n        if cuda:\n            sense_embs = self.sense_embs(Variable(torch.LongTensor(sense_indices).cuda()))\n            return sense2idx, sense_embs.cpu().data.numpy()\n        else:\n            sense_embs = self.sense_embs(Variable(torch.LongTensor(sense_indices)))\n            return sense2idx, sense_embs.data.numpy()\n\n    def forward(self, data):\n        ctx_type_indices = data[:, 0:2*self.window]\n        pos_sense_idx = data[:, 2*self.window+1]\n        neg_sense_indices = data[:, 2*self.window+2:2*self.window+2+self.negative]\n        neg_mask = data[:, 2*self.window+2+self.negative:].float()\n\n        ctx_type_embs = self.global_embs(ctx_type_indices)\n        pos_sense_embs = self.sense_embs(pos_sense_idx)\n        neg_sense_embs = self.sense_embs(neg_sense_indices)\n\n        ctx_feats = torch.sum(ctx_type_embs * self.ctx_weight, 1, keepdim=True)\n\n        # Neg Log Likelihood\n        pos_ips = torch.sum(ctx_feats[:,0,:] * pos_sense_embs, 1)\n        pos_loss = torch.sum( -F.logsigmoid(torch.clamp(pos_ips,max=10,min=-10)))\n        neg_ips = torch.bmm(neg_sense_embs, ctx_feats.permute(0,2,1))[:,:,0]\n        neg_loss = torch.sum( -F.logsigmoid(torch.clamp(-neg_ips,max=10,min=-10)) * neg_mask )\n\n        return pos_loss + neg_loss\n\n\n# Initialize model.\ndef init_net(args):\n    if args.lr == -1.0:\n        vars(args)['lr'] = 0.05\n    return CSV(args)\n\ndef save_model(filename, model, args, word2idx):\n    torch.save({\n        'word2idx':word2idx,\n        'args':args,\n        #'word2sense': model.word2sense,\n        'n_senses': model.n_senses,\n        'params': model.state_dict()\n    }, filename)\n\ndef load_model(filename):\n    checkpoint = torch.load(filename)\n    word2idx = checkpoint['word2idx']\n    args = checkpoint['args']\n    model = CSV(args)\n    if args.cuda:\n        model.cuda()\n\n    model.global_embs.weight.data = checkpoint['params']['global_embs.weight']\n    model.sense_embs.weight.data = checkpoint['params']['sense_embs.weight']\n    model.ctx_weight.data = checkpoint['params']['ctx_weight']\n    model.word2sense = checkpoint['word2sense']\n    #model.word2sense.data = checkpoint['params']['word2sense']                                                                                          \n    #model.word_sense_cnts.data = checkpoint['params']['word_sense_cnts'] \n    model.n_senses = checkpoint['n_senses']\n\n    return model, word2idx\n\n# Training\ndef train_process_sent_producer(p_id, data_queue, word_count_actual, word_list, word2idx, freq, args):\n    n_proc = 1 if args.stage == 2 else args.processes\n    N = 1 if args.stage == 2 else args.iter\n    neg = 0 if args.stage == 2 else args.negative\n\n    if args.negative > 0:\n        table_ptr_val = data_producer.init_unigram_table(word_list, freq, args.train_words)\n\n    train_file = open(args.train)\n    file_pos = args.file_size * p_id // n_proc\n    train_file.seek(file_pos, 0)\n    while True:\n        try:\n            train_file.read(1)\n        except UnicodeDecodeError:\n            file_pos -= 1\n            train_file.seek(file_pos, 0)\n        else:\n            train_file.seek(file_pos, 0)\n            break\n\n    batch_count = 0\n    batch_placeholder = np.zeros((args.batch_size, 2*args.window+2+2*neg), 'int64')\n\n    for it in range(N):\n        train_file.seek(file_pos, 0)\n\n        last_word_cnt = 0\n        word_cnt = 0\n        sentence = []\n        prev = ''\n        eof = False\n        while True:\n            if eof or train_file.tell() > file_pos + args.file_size / n_proc:\n                break\n\n            while True:\n                s = train_file.read(1)\n                if not s:\n                    eof = True\n                    break\n                elif s == ' ' or s == '\\t':\n                    if prev in word2idx:\n                        sentence.append(prev)\n                    prev = ''\n                    if len(sentence) >= MAX_SENT_LEN:\n                        break\n                elif s == '\\n':\n                    if prev in word2idx:\n                        sentence.append(prev)\n                    prev = ''\n                    break\n                else:\n                    prev += s\n\n            if len(sentence) > 0:\n                # subsampling\n                sent_id = []\n                if args.sample != 0:\n                    sent_len = len(sentence)\n                    i = 0\n                    while i < sent_len:\n                        word = sentence[i]\n                        f = freq[word] / args.train_words\n                        pb = (np.sqrt(f / args.sample) + 1) * args.sample / f;\n\n                        if pb > np.random.random_sample():\n                            sent_id.append( word2idx[word] )\n                        i += 1\n\n                if len(sent_id) < 2:\n                    word_cnt += len(sentence)\n                    sentence.clear()\n                    continue\n\n                next_random = (2**24) * np.random.randint(0, 2**24) + np.random.randint(0, 2**24)\n                chunk = data_producer.cbow_producer(sent_id, len(sent_id), table_ptr_val, args.window,\n                            neg, args.vocab_size, args.batch_size, next_random)\n\n                chunk_pos = 0\n                while chunk_pos < chunk.shape[0]:\n                    remain_space = args.batch_size - batch_count\n                    remain_chunk = chunk.shape[0] - chunk_pos\n\n                    if remain_chunk < remain_space:\n                        take_from_chunk = remain_chunk\n                    else:\n                        take_from_chunk = remain_space\n\n                    batch_placeholder[batch_count:batch_count+take_from_chunk, :] = chunk[chunk_pos:chunk_pos+take_from_chunk, :]\n                    batch_count += take_from_chunk\n\n                    if batch_count == args.batch_size:\n                        data_queue.put(batch_placeholder)\n                        batch_count = 0\n\n                    chunk_pos += take_from_chunk\n\n                word_cnt += len(sentence)\n                if word_cnt - last_word_cnt > 10000:\n                    with word_count_actual.get_lock():\n                        word_count_actual.value += word_cnt - last_word_cnt\n                    last_word_cnt = word_cnt\n                sentence.clear()\n\n        with word_count_actual.get_lock():\n            word_count_actual.value += word_cnt - last_word_cnt\n        print(p_id, it, file_pos, train_file.tell(), args.file_size)\n    if batch_count > 0:\n        data_queue.put(batch_placeholder[:batch_count,:])\n    data_queue.put(None)\n    print(p_id, file_pos, train_file.tell(), args.file_size)\n\ndef train_process(p_id, word_count_actual, word2idx, word_list, freq, args, model):\n    data_queue = mp.SimpleQueue()\n\n    lr = args.lr\n    #optimizer = optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), lr=lr)\n    optimizer = optim.Adagrad(filter(lambda p: p.requires_grad, model.parameters()), lr=lr)\n\n    t = mp.Process(target=train_process_sent_producer, args=(p_id, data_queue, word_count_actual, word_list, word2idx, freq, args))\n    t.start()\n\n    #n_iter = 1 if args.stage == 2 else args.iter\n    n_iter = args.iter\n    # get from data_queue and feed to model\n    prev_word_cnt = 0\n    while True:\n        chunk = data_queue.get()\n        if chunk is None:\n            break\n        else:\n            # lr anneal & output\n            if word_count_actual.value - prev_word_cnt > 10000:\n                #if args.lr_anneal:\n                #    lr = args.lr * (1 - word_count_actual.value / (n_iter * args.train_words))\n                #    if lr < 0.0001 * args.lr:\n                #        lr = 0.0001 * args.lr\n                #    for param_group in optimizer.param_groups:\n                #        param_group['lr'] = lr\n\n                #sys.stdout.write(\"\\rAlpha: %0.8f, Progess: %0.2f, Words/sec: %f, word_cnt: %d\" % (lr, word_count_actual.value / (n_iter * args.train_words) * 100, word_count_actual.value / (time.monotonic() - args.t_start), word_count_actual.value))\n                sys.stdout.write(\"\\rProgess: %0.2f, Words/sec: %f, word_cnt: %d\" % (word_count_actual.value / (n_iter * args.train_words) * 100, word_count_actual.value / (time.monotonic() - args.t_start), word_count_actual.value))\n                sys.stdout.flush()\n                prev_word_cnt = word_count_actual.value\n\n            if args.stage == 1:\n                if args.cuda:\n                    data = Variable(torch.LongTensor(chunk).cuda(), requires_grad=False)\n                else:\n                    data = Variable(torch.LongTensor(chunk), requires_grad=False)\n\n                optimizer.zero_grad()\n                loss = model(data)\n                loss.backward()\n                optimizer.step()\n                model.global_embs.weight.data[args.vocab_size].fill_(0)\n\n            elif args.stage == 3:\n                if args.cuda:\n                    data = Variable(torch.LongTensor(chunk).cuda(), requires_grad=False)\n                else:\n                    data = Variable(torch.LongTensor(chunk), requires_grad=False)\n\n                #type_ids = chunk[:, 2*args.window+1:2*args.window+2+2*args.negative]\n                type_ids = chunk[:, 2*args.window+1:2*args.window+2+args.negative]\n                type_ids = np.reshape(type_ids, (type_ids.shape[0] * type_ids.shape[1]))\n                sense2idx, sense_embs = model.get_possible_sense_embs(type_ids.tolist())\n\n                # get type_idx from chunk, and do sense selection here.\n                context_feats = model.get_context_feats(data[:, :2*args.window])\n\n                chunk = data_producer.select_sense(chunk, context_feats, sense2idx, sense_embs,\n                            model.word2sense, chunk.shape[0], args.size, args.window, args.negative)\n\n                if args.cuda:\n                    data = Variable(torch.LongTensor(chunk).cuda(), requires_grad=False)\n                else:\n                    data = Variable(torch.LongTensor(chunk), requires_grad=False)\n\n                optimizer.zero_grad()\n                loss = model(data)\n                loss.backward()\n                optimizer.step()\n                model.global_embs.weight.data[args.vocab_size].fill_(0)\n    t.join()\n\ndef train_process_stage2(p_id, word_count_actual, word2idx, word_list, freq, args, model):\n    data_queue = mp.SimpleQueue()\n\n    sense_embs = model.sense_embs.weight.data.numpy()\n    counter_list = np.zeros((model.sense_capacity), dtype='float32')\n\n    t = mp.Process(target=train_process_sent_producer, args=(p_id, data_queue, word_count_actual, word_list, word2idx, freq, args))\n    t.start()\n\n    n_iter = 1\n    # get from data_queue and feed to model\n    prev_word_cnt = 0\n    while True:\n        chunk = data_queue.get()\n        if chunk is None:\n            break\n        else:\n            if word_count_actual.value - prev_word_cnt > 10000:\n                sys.stdout.write(\"\\rProgess: %0.2f, Words/sec: %f, word_cnt: %d\" % (word_count_actual.value / (n_iter * args.train_words) * 100, word_count_actual.value / (time.monotonic() - args.t_start), word_count_actual.value))\n                sys.stdout.flush()\n                prev_word_cnt = word_count_actual.value\n\n            if args.cuda:\n                data = Variable(torch.LongTensor(chunk).cuda(), requires_grad=False)\n            else:\n                data = Variable(torch.LongTensor(chunk), requires_grad=False)\n\n            context_feats = model.get_context_feats(data[:, :2*args.window])\n\n            # update sense_embs\n            create_cnt = data_producer.create_n_update_sense(chunk[:, 2*args.window+1], context_feats, sense_embs, model.word2sense, counter_list, chunk.shape[0], args.size, args.delta, model.n_senses)\n            model.n_senses += create_cnt\n\n            #if model.n_senses + args.batch_size > model.sense_capacity:\n            #    new_capacity = model.sense_capacity * 3 // 2\n            #    counter_list = np.concatenate( (counter_list, np.ones((new_capacity - model.sense_capacity),dtype='float32')), axis=0)\n            #    zero = np.zeros((new_capacity - model.sense_capacity, args.size), 'float32')\n            #    sense_embs = np.concatenate((sense_embs, zero), 0)\n            #    model.sense_capacity = new_capacity\n            #    print(\"\\nexapnded sense_embs: %d\" % model.n_senses)\n    t.join()\n\n    sense_embs[:model.n_senses, :] = sense_embs[:model.n_senses, :] / counter_list[:model.n_senses, None]\n\n\nif __name__ == '__main__':\n    set_start_method('forkserver')\n\n    args = parser.parse_args()\n    print(\"Starting training using file %s\" % args.train)\n    train_file = open(args.train)\n    train_file.seek(0, 2)\n    vars(args)['file_size'] = train_file.tell()\n\n    word_count_actual = mp.Value('L', 0)\n\n    if args.vocab == '':\n        word2idx, word_list, freq = build_vocab(args)   \n    else:\n        with open(args.vocab, 'rb') as f:                                                               \n            word2idx, word_list, freq, pos2idx, dep2id = pickle.load(f)\n            word_count = sum([freq[k] for k in freq])\n            vars(args)['vocab_size'] = len(word2idx)\n            vars(args)['train_words'] = word_count\n            print(\"Vocab size: %ld\" % len(word2idx))\n            print(\"Words in train file: %ld\" % word_count)\n\n    model = init_net(args)\n    model.share_memory()\n    if args.cuda:\n        model.cuda()\n\n    # stage 1, learn robust context representation.\n    vars(args)['stage'] = 1\n    print(\"Stage 1\")\n    vars(args)['lr_anneal'] = True\n    vars(args)['t_start'] = time.monotonic()\n    processes = []\n    for p_id in range(args.processes):\n        p = mp.Process(target=train_process, args=(p_id, word_count_actual, word2idx, word_list, freq, args, model))\n        p.start()\n        processes.append(p)\n\n    for p in processes:\n        p.join()\n    del processes\n    print(\"\\nStage 1, \", time.monotonic() - args.t_start, \" secs \", word_count_actual.value)\n    filename = args.save\n    if not filename.endswith('.pth.tar'):\n        filename += '.stage1.pth.tar'\n    save_model(filename, model, args, word2idx)\n\n    if args.multi_proto:\n        # stage 2, create new sense in a non-parametric way.\n        # Freeze model paramters except sense_embs, and use only 1 process to prevent race condition\n        old_batch_size = vars(args)['batch_size']\n        model.global_embs.requires_grad = False\n        model.ctx_weight.requires_grad = False\n        model.sense_embs = model.sense_embs.cpu()\n        vars(args)['stage'] = 2\n        vars(args)['batch_size'] = 5000\n        print(\"\\nStage 2\")\n        word_count_actual.value = 0\n        vars(args)['t_start'] = time.monotonic()\n        train_process_stage2(0, word_count_actual, word2idx, word_list, freq, args, model)\n\n        if args.cuda:\n            model.cuda()\n        print(\"\\nStage 2, \", time.monotonic() - args.t_start, \" secs\")\n        print(\"Current # of senses: %d\" % model.n_senses)\n        pdb.set_trace()\n        filename = args.save\n        if not filename.endswith('.pth.tar'):\n            filename += '.stage2.pth.tar'\n        save_model(filename, model, args, word2idx)\n\n        # stage 3, no more sense creation.\n        vars(args)['lr'] = args.lr * 0.01\n        vars(args)['batch_size'] = old_batch_size\n        model.global_embs.requires_grad = True\n        model.ctx_weight.requires_grad = True\n        vars(args)['stage'] = 3\n        print(\"\\nBegin stage 3\")\n        word_count_actual.value = 0\n        vars(args)['t_start'] = time.monotonic()\n        processes = []\n        for p_id in range(args.processes):\n            p = mp.Process(target=train_process, args=(p_id, word_count_actual, word2idx, word_list, freq, args, model))\n            p.start()\n            processes.append(p)\n\n        for p in processes:\n            p.join()\n\n        print(\"\\nStage 3, \", time.monotonic() - args.t_start, \" secs\")\n\n    # save model\n    filename = args.save\n    if not filename.endswith('.pth.tar'):\n        filename += '.stage3.pth.tar'\n    save_model(filename, model, args, word2idx)\n    print(\"\")\n\n\n", "meta": {"hexsha": "a3c78b4ed55d10de069695bce6f3d899ee02cc99", "size": 20932, "ext": "py", "lang": "Python", "max_stars_repo_path": "pytorch-word2vec-master/csv.py", "max_stars_repo_name": "arjun-sai-krishnan/tamil-morpho-embeddings", "max_stars_repo_head_hexsha": "a33bcb427d635dba3b1857f26ea7ab287e1a44c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-11T18:25:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T03:48:52.000Z", "max_issues_repo_path": "pytorch-word2vec-master/csv.py", "max_issues_repo_name": "arjun-sai-krishnan/tamil-morpho-embeddings", "max_issues_repo_head_hexsha": "a33bcb427d635dba3b1857f26ea7ab287e1a44c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pytorch-word2vec-master/csv.py", "max_forks_repo_name": "arjun-sai-krishnan/tamil-morpho-embeddings", "max_forks_repo_head_hexsha": "a33bcb427d635dba3b1857f26ea7ab287e1a44c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4874274662, "max_line_length": 250, "alphanum_fraction": 0.5918211351, "include": true, "reason": "import numpy", "num_tokens": 4952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.16738411820402732}}
{"text": "# -*- coding: utf-8 -*-\r\nimport numpy as np\r\nimport astropy.units as u\r\nimport astropy.constants as const\r\nfrom astropy.time import Time\r\nimport os,inspect\r\nfrom EXOSIMS.util.eccanom import eccanom\r\n\r\nclass Observatory(object):\r\n    \"\"\"Observatory class template\r\n    \r\n    This class contains all variables and methods necessary to perform\r\n    Observatory Definition Module calculations in exoplanet mission simulation.\r\n    \r\n    Args:\r\n        \\*\\*specs: \r\n            user specified values\r\n        forceStaticEphem (bool):\r\n            If True, forces use of stored ephemerides for solar system objects\r\n            and uses eccanom utility to propagate.  Defaults to False.\r\n        spkpath (str):\r\n            Path to SPK file on disk (Defaults to de432s.bsp). \r\n    \r\n    Attributes:\r\n        settlingTime (Quantity): \r\n            instrument settling time after repoint (default with units of day)\r\n        thrust (Quantity): \r\n            occulter slew thrust (default with units of mN)\r\n        slewIsp (Quantity): \r\n            occulter slew specific impulse (default with units of s)\r\n        scMass (Quantity): \r\n            occulter (maneuvering sc) wet mass (default with units of kg)\r\n        dryMass (Quantity): \r\n            occulter (maneuvering sc) dry mass (default with units of kg)\r\n        coMass (Quantity): \r\n            telescope (or non-maneuvering sc) mass (default with units of kg)\r\n        occulterSep (Quantity): \r\n            occulter-telescope distance (default with units of km)\r\n        skIsp (Quantity): \r\n            station-keeping specific impulse (default with units of s)\r\n        kogood (ndarray): \r\n            1D numpy ndarray of booleans where True is observable target star \r\n            in the target list\r\n        r_sc (Quantity): \r\n            1D numpy ndarray of observatory postion vector (default with units \r\n            of km)\r\n        currentSep (Quantity): \r\n            current occulter separation (default with units of km)\r\n        flowRate (Quantity): \r\n            slew flow rate (default with units of kg/day)\r\n    \r\n    Notes:\r\n        For finding positions of solar system bodies, this routine will attempt to \r\n        use the jplephem module and a local SPK file on disk.  The module can be \r\n        installed via pip or from source.  The default SPK file can be downloaded from\r\n        here: http://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/de430.bsp\r\n        and should be placed in the Observatory subdirectory of EXOSIMS.\r\n    \r\n    \"\"\"\r\n\r\n    _modtype = 'Observatory'\r\n    _outspec = {}\r\n\r\n    def __init__(self, settlingTime=1., thrust=450., slewIsp=4160.,\\\r\n                 scMass=6000., dryMass=3400., coMass=5800., skIsp=220.,\\\r\n                 defburnPortion=0.05, spkpath=None, forceStaticEphem=False,\\\r\n                 **specs):\r\n        \r\n        # default Observatory values\r\n        # instrument settling time after repoint (days)\r\n        self.settlingTime = float(settlingTime)*u.day \r\n        # occulter slew thrust (mN)\r\n        self.thrust = float(thrust)*u.mN \r\n        # occulter slew specific impulse (s)\r\n        self.slewIsp = float(slewIsp)*u.s \r\n        # occulter (maneuvering sc) initial (wet) mass (kg)\r\n        self.scMass = float(scMass)*u.kg \r\n        # occulter (maneuvering sc) dry mass (kg)\r\n        self.dryMass = float(dryMass)*u.kg \r\n        # telescope (or non-maneuvering sc) mass (kg)\r\n        self.coMass = float(coMass)*u.kg \r\n        # station-keeping Isp (s)\r\n        self.skIsp = float(skIsp)*u.s \r\n        # default burn portion\r\n        self.defburnPortion = float(defburnPortion)\r\n        \r\n        # occulter-telescope distance (km)\r\n        self.occulterSep = 55000.*u.km\r\n        \r\n        #if jplephem is available, we'll use that for propagating solar system bodies\r\n        #otherwise, use static ephemeris\r\n        if not forceStaticEphem:\r\n            try:\r\n                from jplephem.spk import SPK\r\n                self.havejplephem = True\r\n            except ImportError:\r\n                print \"WARNING: Module jplephem not found, using static solar system ephemeris.\"\r\n                self.havejplephem = False\r\n        else:\r\n            self.havejplephem = False\r\n            print \"Using static solar system ephemeris.\"\r\n        \r\n        # populate outspec\r\n        for att in self.__dict__.keys():\r\n            dat = self.__dict__[att]\r\n            self._outspec[att] = dat.value if isinstance(dat,u.Quantity) else dat\r\n        \r\n        # initialize values updated by functions\r\n        # observatory keepout booleans\r\n        self.kogood = np.array([]) \r\n        # observatory orbit position vector (km)\r\n        self.r_sc = np.zeros(3)*u.km \r\n        # current occulter separation\r\n        self.currentSep = self.occulterSep \r\n        \r\n        # set values derived from quantities above\r\n        # slew flow rate (kg/day)\r\n        self.flowRate = (self.thrust/const.g0/self.slewIsp).to('kg/day')\r\n        \r\n        #define function for calculating obliquity of the ecliptic \r\n        #(arg Julian centuries from J2000)\r\n        self.obe = lambda TDB: 23.439279 - 0.0130102*TDB - 5.086e-8*(TDB**2) + \\\r\n                5.565e-7*(TDB**3) + 1.6e-10*(TDB**4) + 1.21e-11*(TDB**5) \r\n        \r\n        # if you have jplephem, load spice file. otherwise, load static ephem.\r\n        if self.havejplephem:\r\n            if (spkpath is None) or not(os.path.exists(spkpath)):\r\n                # if the path does not exist, load the default de432s.bsp\r\n                    classpath = os.path.split(inspect.getfile(self.__class__))[0]\r\n                    classpath = os.path.normpath(os.path.join(classpath,'..','Observatory'))\r\n                    filename = 'de432s.bsp'\r\n                    spkpath = os.path.join(classpath, filename)\r\n            self.kernel = SPK.open(spkpath)\r\n        else:\r\n            \"\"\"All ephemeride data from Vallado Appendix D.4\r\n            Values are:\r\n            a     e             i               O                       w                   lM\r\n            sma   eccentricity  inclination     long. ascending node    long. perihelion    mean longitude\r\n            AU    N/A           deg             deg                     deg                 deg\r\n            \"\"\"\r\n\r\n            # Store Mercury ephemerides data (ecliptic)\r\n            Mercurya = 0.387098310\r\n            Mercurye = [0.20563175, 0.000020406, -0.0000000284, -0.00000000017]\r\n            Mercuryi = [7.004986, -0.0059516, 0.00000081, 0.000000041]\r\n            MercuryO = [48.330893, -0.1254229, -0.00008833, -0.000000196]\r\n            Mercuryw = [77.456119, 0.1588643, -0.00001343, 0.000000039]\r\n            MercurylM = [252.250906, 149472.6746358, -0.00000535, 0.000000002]\r\n            Mercury = self.SolarEph(Mercurya, Mercurye, Mercuryi, MercuryO, Mercuryw, MercurylM)\r\n            \r\n            # Store Venus epemerides data (ecliptic)\r\n            Venusa = 0.723329820\r\n            Venuse = [0.00677188, -0.000047766, 0.0000000975, 0.00000000044]\r\n            Venusi = [3.394662, -0.0008568, -0.00003244, 0.000000010]\r\n            VenusO = [76.679920, -0.2780080, -0.00014256, -0.000000198]\r\n            Venusw = [131.563707, 0.0048646, -0.00138232, -0.000005332]\r\n            VenuslM = [181.979801, 58517.8156760, 0.00000165, -0.000000002]\r\n            Venus = self.SolarEph(Venusa, Venuse, Venusi, VenusO, Venusw, VenuslM)\r\n            \r\n            # Store Earth ephemerides data (ecliptic)\r\n            Eartha = 1.000001018\r\n            Earthe = [0.01670862, -0.000042037, -0.0000001236, 0.00000000004]\r\n            Earthi = [0., 0.0130546, -0.00000931, -0.000000034]\r\n            EarthO = [174.873174, -0.2410908, 0.00004067, -0.000001327]\r\n            Earthw = [102.937348, 0.3225557, 0.00015026, 0.000000478]\r\n            EarthlM = [100.466449, 35999.3728519, -0.00000568, 0.]\r\n            Earth = self.SolarEph(Eartha, Earthe, Earthi, EarthO, Earthw, EarthlM)\r\n            \r\n            # Store Mars ephemerides data (ecliptic)\r\n            Marsa = 1.523679342\r\n            Marse = [0.09340062, 0.000090483, -0.0000000806, -0.00000000035]\r\n            Marsi = [1.849726, -0.0081479, -0.00002255, -0.000000027]\r\n            MarsO = [49.558093, -0.2949846, -0.00063993, -0.000002143]\r\n            Marsw = [336.060234, 0.4438898, -0.00017321, 0.000000300]\r\n            MarslM = [355.433275, 19140.2993313, 0.00000261, -0.000000003]\r\n            Mars = self.SolarEph(Marsa, Marse, Marsi, MarsO, Marsw, MarslM)\r\n            \r\n            # Store Jupiter ephemerides data (ecliptic)\r\n            Jupitera = [5.202603191, 0.0000001913]\r\n            Jupitere = [0.04849485, 0.000163244, -0.0000004719, -0.00000000197]\r\n            Jupiteri = [1.303270, -0.0019872, 0.00003318, 0.000000092]\r\n            JupiterO = [100.464441, 0.1766828, 0.00090387, -0.000007032]\r\n            Jupiterw = [14.331309, 0.2155525, 0.00072252, -0.000004590]\r\n            JupiterlM = [34.351484, 3034.9056746, -0.00008501, 0.000000004]\r\n            Jupiter = self.SolarEph(Jupitera, Jupitere, Jupiteri, JupiterO, Jupiterw, JupiterlM)\r\n            \r\n            # Store Saturn ephemerides data (ecliptic)\r\n            Saturna = [9.554909596, -0.0000021389]\r\n            Saturne = [0.05550862, -0.000346818, -0.0000006456, 0.00000000338]\r\n            Saturni = [2.488878, 0.0025515, -0.00004903, 0.000000018]\r\n            SaturnO = [113.665524, -0.2566649, -0.00018345, 0.000000357]\r\n            Saturnw = [93.056787, 0.5665496, 0.00052809, 0.000004882]\r\n            SaturnlM = [50.077471, 1222.1137943, 0.00021004, -0.000000019]\r\n            Saturn = self.SolarEph(Saturna, Saturne, Saturni, SaturnO, Saturnw, SaturnlM)\r\n            \r\n            # Store Uranus ephemerides data (ecliptic)\r\n            Uranusa = [19.218446062, -0.0000000372, 0.00000000098]\r\n            Uranuse = [0.04629590, -0.000027337, 0.0000000790, 0.00000000025]\r\n            Uranusi = [0.773196, -0.0016869, 0.00000349, 0.000000016]\r\n            UranusO = [74.005947, 0.0741461, 0.00040540, 0.000000104]\r\n            Uranusw = [173.005159, 0.0893206, -0.00009470, 0.000000413]\r\n            UranuslM = [314.055005, 428.4669983, -0.00000486, 0.000000006]\r\n            Uranus = self.SolarEph(Uranusa, Uranuse, Uranusi, UranusO, Uranusw, UranuslM)\r\n            \r\n            # Store Neptune ephemerides data (ecliptic)\r\n            Neptunea = [30.110386869, -0.0000001663, 0.00000000069]\r\n            Neptunee = [0.00898809, 0.000006408, -0.0000000008]\r\n            Neptunei = [1.769952, 0.0002257, 0.00000023, -0.000000000]\r\n            NeptuneO = [131.784057, -0.0061651, -0.00000219, -0.000000078]\r\n            Neptunew = [48.123691, 0.0291587, 0.00007051, 0.]\r\n            NeptunelM = [304.348665, 218.4862002, 0.00000059, -0.000000002]\r\n            Neptune = self.SolarEph(Neptunea, Neptunee, Neptunei, NeptuneO, Neptunew, NeptunelM)\r\n            \r\n            # Store Pluto ephemerides data (ecliptic)\r\n            Plutoa = [39.48168677, -0.00076912]\r\n            Plutoe = [0.24880766, 0.00006465]\r\n            Plutoi = [17.14175, 0.003075]\r\n            PlutoO = [110.30347, -0.01036944]\r\n            Plutow = [224.06676, -0.03673611]\r\n            PlutolM = [238.92881, 145.2078]\r\n            Pluto = self.SolarEph(Plutoa, Plutoe, Plutoi, PlutoO, Plutow, PlutolM)\r\n            \r\n            #store all as dictionary:\r\n            self.planets = {'Mercury': Mercury,\r\n                            'Venus': Venus,\r\n                            'Earth': Earth,\r\n                            'Mars': Mars,\r\n                            'Jupiter': Jupiter,\r\n                            'Saturn': Saturn,\r\n                            'Uranus': Uranus,\r\n                            'Neptune': Neptune,\r\n                            'Pluto': Pluto}\r\n\r\n    def __str__(self):\r\n        \"\"\"String representation of the Observatory object\r\n        \r\n        When the command 'print' is used on the Observatory object, this method\r\n        will print the attribute values contained in the object\"\"\"\r\n        \r\n        for att in self.__dict__.keys():\r\n            print '%s: %r' % (att, getattr(self, att))\r\n        \r\n        return 'Observatory class object attributes'\r\n\r\n    def orbit(self, time):\r\n        \"\"\"Finds observatory orbit position vector, returns True if successful\r\n        \r\n        This method finds the observatory position vector (heliocentric \r\n        equatorial frame) as a 1D numpy array with astropy Quantity units of km \r\n        and stores it in self.r_sc.\r\n        \r\n        This defines the data type expected, orbits are determined by specific\r\n        instances of Observatory classes.\r\n        \r\n        Args:\r\n            time (Time):\r\n                absolute time\r\n        \r\n        Returns:\r\n            success (bool):\r\n                True if successful, False if not\r\n        \r\n        \"\"\"\r\n        \r\n        self.r_sc = np.array([float(time.mjd),float(time.mjd),float(time.mjd)])*u.km\r\n        b = np.isfinite(self.r_sc) # finds if all values are finite \r\n        success = all(b) # returns True if all values of self.r_sc are finite\r\n        \r\n        return success\r\n\r\n    def keepout(self, currentTime, TL, koangle):\r\n        \"\"\"Finds keepout Boolean values, returns True if successful\r\n        \r\n        This method finds the keepout Boolean values for each target star where\r\n        True is an observable star and stores the 1D numpy array in self.kogood.\r\n        \r\n        Args:\r\n            currentTime (Time):\r\n                absolute time\r\n            TL (TargetList or StarCatalog):\r\n                TargetList or StarCatalog class object\r\n            koangle (float):\r\n                telescope keepout angle in degrees\r\n                \r\n        Returns:\r\n            success (bool):\r\n                True if successful, False if not\r\n        \r\n        \"\"\"\r\n        \r\n        # update spacecraft orbital position\r\n        a = self.orbit(currentTime) \r\n        \r\n        self.kogood = np.array([True for row in TL.Name])\r\n        \r\n        # check to make sure all elements in self.kogood are Boolean\r\n        b = [isinstance(element, np.bool_) for element in self.kogood]\r\n        c = [a, b]\r\n        # return True if orbital position is successful and all elements of \r\n        # self.kogood are Boolean\r\n        success = all(c) \r\n        \r\n        return success\r\n\r\n    def solarSystem_body_position(self, time, bodyname):\r\n        \"\"\"Finds position vector for solar system objects\r\n        \r\n        This passes all arguments to one of spk_body or keplerplanet, depending\r\n        on the value of self.havejplephem.\r\n        \r\n        Args:\r\n            time (Time):\r\n                absolute time\r\n            bodyname (str):\r\n                solar system object name\r\n        \r\n        Returns:\r\n            r_body (Quantity):\r\n                heliocentric equatorial position vector in 1D numpy ndarray\r\n                (units of km)\r\n        \r\n        \"\"\"\r\n        \r\n        if self.havejplephem:\r\n            return self.spk_body(time,bodyname)\r\n        else:\r\n            return self.keplerplanet(time,bodyname)\r\n\r\n    def spk_body(self, time, bodyname):\r\n        \"\"\"Finds position vector for solar system objects\r\n        \r\n        This method uses spice kernel from NAIF to find heliocentric\r\n        equatorial position vectors (astropy Quantity in km) for solar system\r\n        objects.\r\n        \r\n        Args:\r\n            time (Time):\r\n                absolute time\r\n            bodyname (str):\r\n                solar system object name\r\n        \r\n        Returns:\r\n            r_body (Quantity):\r\n                heliocentric equatorial position vector in 1D numpy ndarray\r\n                (units of km)\r\n        \r\n        \"\"\"\r\n        \r\n        # dictionary of solar system bodies available in spice kernel\r\n        bodies = {'Mercury':199,\r\n                  'Venus':299,\r\n                  'Earth':399,\r\n                  'Mars':4,\r\n                  'Jupiter':5,\r\n                  'Saturn':6,\r\n                  'Uranus':7,\r\n                  'Neptune':8,\r\n                  'Pluto':9,\r\n                  'Sun':10,\r\n                  'Moon':301}\r\n        \r\n        assert bodies.has_key(bodyname),\\\r\n                 \"%s is not a recognized body name.\"%(bodyname)\r\n        \r\n        if bodies[bodyname] == 199:\r\n            r_body = (self.kernel[0,1].compute(time.jd) + \\\r\n                    self.kernel[1,199].compute(time.jd) - \\\r\n                    self.kernel[0,10].compute(time.jd))*u.km\r\n        elif bodies[bodyname] == 299:\r\n            r_body = (self.kernel[0,2].compute(time.jd) + \\\r\n                    self.kernel[2,299].compute(time.jd) - \\\r\n                    self.kernel[0,10].compute(time.jd))*u.km\r\n        elif bodies[bodyname] == 399:\r\n            r_body = (self.kernel[0,3].compute(time.jd) + \\\r\n                    self.kernel[3,399].compute(time.jd) - \\\r\n                    self.kernel[0,10].compute(time.jd))*u.km\r\n        elif bodies[bodyname] == 301:\r\n            r_body = (self.kernel[0,3].compute(time.jd) + \\\r\n                    self.kernel[3,301].compute(time.jd) - \\\r\n                    self.kernel[0,10].compute(time.jd))*u.km\r\n        else:\r\n            r_body = (self.kernel[0,bodies[bodyname]].compute(time.jd) - \\\r\n                    self.kernel[0,10].compute(time.jd))*u.km\r\n        \r\n        return r_body\r\n\r\n    def keplerplanet(self, time, bodyname):\r\n        \"\"\"Finds position vector for solar system objects\r\n        \r\n        This method uses algorithms 2 and 10 from Vallado 2013 to find \r\n        heliocentric equatorial position vectors (astropy Quantity in km) for \r\n        solar system objects.\r\n        \r\n        Args:\r\n            time (Time):\r\n                absolute time\r\n            bodyname (str):\r\n                solar system object name\r\n                \r\n        Returns:\r\n            r_body (Quantity):\r\n                heliocentric equatorial position vector in 1D numpy ndarray \r\n                (units of km)\r\n        \r\n        \"\"\"\r\n        \r\n        if bodyname == 'Moon':\r\n            r_Earth = self.keplerplanet(time, 'Earth')\r\n            return r_Earth + self.moon_earth(time)\r\n        \r\n        assert self.planets.has_key(bodyname),\\\r\n                \"%s is not a recognized body name.\"%(bodyname)\r\n        \r\n        planet = self.planets[bodyname] \r\n        # find Julian centuries from J2000\r\n        TDB = self.cent(time)\r\n        # update ephemeride data\r\n        a = self.propeph(planet.a, TDB)\r\n        e = self.propeph(planet.e, TDB)\r\n        i = np.radians(self.propeph(planet.i, TDB))\r\n        O = np.radians(self.propeph(planet.O, TDB))\r\n        w = np.radians(self.propeph(planet.w, TDB))\r\n        lM = np.radians(self.propeph(planet.lM, TDB))\r\n        # Find mean anomaly and argument of perigee\r\n        M = np.mod(lM - w,2*np.pi)\r\n        wp = np.mod(w - O,2*np.pi)\r\n        # Find eccentric anomaly\r\n        E = eccanom(M,e)[0]\r\n        # Find true anomaly\r\n        nu = np.arctan2(np.sin(E) * np.sqrt(1 - e**2), np.cos(E) - e)\r\n        # Find semiparameter\r\n        p = a*(1 - e**2)\r\n        # position vector (km) in orbital plane\r\n        r_planet = np.array([(p*np.cos(nu)/(1 + e*np.cos(nu))), (p*np.sin(nu))/(1 + e*np.cos(nu)), 0.])\r\n        # position vector (km) in ecliptic plane\r\n        r_planet = np.dot(np.dot(self.rot(-O,3),self.rot(-i,1)),np.dot(self.rot(-wp,3),r_planet))\r\n        # find obliquity of the ecliptic\r\n        obe = self.obe(TDB)\r\n        # position vector (km) in heliocentric equatorial frame\r\n        r_planet = np.dot(self.rot(np.radians(-obe),1),r_planet)*u.km\r\n        \r\n        return r_planet\r\n\r\n    def moon_earth(self, time):\r\n        \"\"\"Finds geocentric equatorial position vector (km) for Earth's moon\r\n        \r\n        This method uses Algorithm 31 from Vallado 2013 to find the geocentric\r\n        equatorial position vector for Earth's moon.\r\n        \r\n        Args:\r\n            time (Time):\r\n                absolute time \r\n        \r\n        Returns:\r\n            r_moon (Quantity):\r\n                geocentric equatorial position vector in 1D numpy array (units \r\n                of km) \r\n        \r\n        \"\"\"\r\n        \r\n        TDB = self.cent(time)\r\n        la = np.radians(218.32 + 481267.8813*TDB + \\\r\n            6.29*np.sin(np.radians(134.9 + 477198.85*TDB)) - \r\n            1.27*np.sin(np.radians(259.2 - 413335.38*TDB)) + \r\n            0.66*np.sin(np.radians(235.7 + 890534.23*TDB)) + \r\n            0.21*np.sin(np.radians(269.9 + 954397.70*TDB)) - \r\n            0.19*np.sin(np.radians(357.5 + 35999.05*TDB)) - \r\n            0.11*np.sin(np.radians(186.6 + 966404.05*TDB)))\r\n        \r\n        phi = np.radians(5.13*np.sin(np.radians(93.3 + 483202.03*TDB)) + \r\n            0.28*np.sin(np.radians(228.2 + 960400.87*TDB)) - \r\n            0.28*np.sin(np.radians(318.3 + 6003.18*TDB)) - \r\n            0.17*np.sin(np.radians(217.6 - 407332.20*TDB)))\r\n        \r\n        P = np.radians(0.9508 + 0.0518*np.cos(np.radians(134.9 + 477198.85*TDB)) + \r\n            0.0095*np.cos(np.radians(259.2 - 413335.38*TDB)) + \r\n            0.0078*np.cos(np.radians(235.7 + 890534.23*TDB)) + \r\n            0.0028*np.cos(np.radians(269.9 + 954397.70*TDB)))\r\n        \r\n        e = np.radians(23.439291 - 0.0130042*TDB - 1.64e-7*TDB**2 + 5.04e-7*TDB**3)\r\n        \r\n        r = 1./np.sin(P)*6378.137 # km\r\n        \r\n        r_moon = r*np.array([np.cos(phi)*np.cos(la),\r\n            np.cos(e)*np.cos(phi)*np.sin(la) - np.sin(e)*np.sin(phi),\r\n            np.sin(e)*np.cos(phi)*np.sin(la) + np.cos(e)*np.sin(phi)])*u.km\r\n        \r\n        return r_moon\r\n\r\n    def starprop(self, currentTime, TL, sInd):\r\n        \"\"\"Finds target star position vector (km) for current time (MJD)\r\n        \r\n        Args:\r\n            currentTime (Time): \r\n                absolute time\r\n            TL (TargetList or StarCatalog): \r\n                TargetList or StarCatalog class object\r\n            sInd (int): \r\n                index for star catalog information\r\n        \r\n        Returns:\r\n            r_star (Quantity): star position vector in heliocentric equatorial \r\n                frame in 1D numpy ndarray (units of km)\r\n            \r\n        \"\"\"\r\n\r\n        # right ascension and declination\r\n        ra = TL.coords.ra[sInd]\r\n        dec = TL.coords.dec[sInd]\r\n        \r\n        # set J2000 epoch\r\n        j2000 = Time(2000., format='jyear')\r\n        \r\n        # directions\r\n        p0 = np.array([-np.sin(ra), np.cos(ra), 0.])\r\n        q0 = np.array([-np.sin(dec)*np.cos(ra), -np.sin(dec)*np.sin(ra), np.cos(dec)])\r\n        r0 = TL.coords[sInd].cartesian.xyz/TL.coords[sInd].distance\r\n        \r\n        # proper motion vector\r\n        mu0 = p0*TL.pmra[sInd] + q0*TL.pmdec[sInd]\r\n        \r\n        # space velocity vector\r\n        v = mu0/TL.parx[sInd]*u.AU + r0*TL.rv[0]\r\n        \r\n        # stellar position vector\r\n        r_star = TL.coords[sInd].cartesian.xyz + v*(currentTime.mjd - j2000.mjd)*u.day\r\n        \r\n        return r_star.to('km')\r\n\r\n    def cent(self, currentTime):\r\n        \"\"\"Finds time in Julian centuries since J2000 epoch\r\n        \r\n        This quantity is needed for many algorithms from Vallado 2013.\r\n        \r\n        Args:\r\n            currentTime (Time):\r\n                absolute time\r\n            \r\n        Returns:\r\n            TDB (float):\r\n                time in Julian centuries since the J2000 epoch \r\n        \r\n        \"\"\"\r\n        \r\n        j2000 = Time(2000., format='jyear')\r\n        TDB = (currentTime.jd - j2000.jd)/36525.\r\n        \r\n        return TDB\r\n\r\n    def propeph(self, x, TDB):\r\n        \"\"\"Propagates ephemeride to current time and returns this value\r\n        \r\n        This method propagates the ephemerides from Vallado 2013 to the current\r\n        time.\r\n        \r\n        Args:\r\n            x (list):\r\n                ephemeride list (maximum of 4 elements)\r\n            TDB (float):\r\n                time in Julian centuries since the J2000 epoch\r\n        \r\n        Returns:\r\n            y (float):\r\n                ephemeride value at current time\r\n        \r\n        \"\"\"\r\n        \r\n        if isinstance(x, list):\r\n            if len(x) < 4:\r\n                q = 4 - len(x)\r\n                i = 0\r\n                while i < q:\r\n                    x.append(0.)\r\n                    i += 1\r\n        elif (isinstance(x, float) or isinstance(x, int)):\r\n            x = [float(x)]\r\n            i = 0\r\n            while i < 3:\r\n                x.append(0.)\r\n                i += 1\r\n        \r\n        y = x[0] + x[1]*TDB + x[2]*(TDB**2) + x[3]*(TDB**3)\r\n        \r\n        return y\r\n\r\n    def rot(self, th, axis):\r\n        \"\"\"Finds the rotation matrix of angle th about the axis value\r\n        \r\n        Args:\r\n            th (float):\r\n                rotation angle in radians\r\n            axis (int): \r\n                integer value denoting rotation axis (1,2, or 3)\r\n        \r\n        Returns:\r\n            matrix (ndarray):\r\n                rotation matrix defined as numpy ndarray\r\n        \r\n        \"\"\"\r\n        \r\n        if axis == 1:\r\n            return np.array([[1., 0., 0.], \r\n                       [0., np.cos(th), np.sin(th)], \r\n                       [0., -np.sin(th), np.cos(th)]])\r\n        elif axis == 2:\r\n            return np.array([[np.cos(th), 0., -np.sin(th)],\r\n                       [0., 1., 0.],\r\n                       [np.sin(th), 0., np.cos(th)]])\r\n        elif axis == 3:\r\n            return np.array([[np.cos(th), np.sin(th), 0.],\r\n                       [-np.sin(th), np.cos(th), 0.],\r\n                       [0., 0., 1.]])\r\n\r\n    def distForces(self, TK, TL, sInd):\r\n        \"\"\"Finds lateral and axial disturbance forces on an occulter \r\n        \r\n        Args:\r\n            TK (TimeKeeping):\r\n                TimeKeeping class object\r\n            TL (TargetList):\r\n                TargetList class object\r\n            sInd (int):\r\n                index of target star\r\n                \r\n        Returns:\r\n            dF_lateral, dF_axial (Quantity, Quantity):\r\n                lateral and axial disturbance forces (units of N)\r\n        \r\n        \"\"\"\r\n        \r\n        # occulter separation distance\r\n        occulterSep = self.occulterSep\r\n        \r\n        # get spacecraft position vector\r\n        self.orbit(TK.currentTimeAbs)\r\n        r_Ts = self.r_sc\r\n        # sun -> earth position vector\r\n        r_Es = self.solarSystem_body_position(TK.currentTimeAbs, 'Earth')\r\n        # sun -> target star vector\r\n        r_ts = self.starprop(TK.currentTimeAbs, TL, sInd)\r\n        # Telescope -> target vector and unit vector\r\n        r_tT = r_ts - r_Ts\r\n        u_tT = r_tT/np.sqrt(np.sum(r_tT**2))\r\n        # sun -> occulter vector\r\n        r_Os = r_Ts + occulterSep*u_tT\r\n        # Earth-Moon barycenter -> spacecraft vectors\r\n        r_TE = r_Ts - r_Es\r\n        r_OE = r_Os - r_Es\r\n        \r\n        # force on occulter\r\n        F_sO = (-const.G*const.M_sun*self.scMass*r_Os/np.sqrt(np.sum(r_Os**2)**3)).to('N')\r\n        mEMB = const.M_sun/328900.56\r\n        F_EO = (-const.G*mEMB*self.scMass*r_OE/np.sqrt(np.sum(r_OE**2)**3)).to('N')\r\n        \r\n        F_O = F_sO + F_EO\r\n        \r\n        # force on telescope\r\n        F_sT = (-const.G*const.M_sun*self.coMass*r_Ts/np.sqrt(np.sum(r_Ts**2))**3).to('N')\r\n        F_ET = (-const.G*mEMB*self.coMass*r_TE/np.sqrt(np.sum(r_TE**2))**3).to('N')\r\n        F_T = F_sT + F_ET\r\n        \r\n        # differential force\r\n        dF = ((F_O/self.scMass - F_T/self.coMass)*self.scMass).to('N')\r\n        \r\n        dF_axial = np.dot(dF.to('N'), u_tT)*u.N\r\n        dF_lateral = np.sqrt(np.sum((dF - dF_axial*u_tT)**2))\r\n        dF_axial = np.abs(dF_axial)\r\n        \r\n        return dF_lateral, dF_axial\r\n\r\n    def mass_dec(self, dF_lateral, t_int):\r\n        \"\"\"Returns mass_used and deltaV \r\n        \r\n        The values returned by this method are used to decrement spacecraft \r\n        mass for station-keeping.\r\n        \r\n        Args:\r\n            dF_lateral (Quantity):\r\n                lateral force on occulter (units of force)\r\n            t_int (Quantity):\r\n                integration time (units of time)\r\n                \r\n        Returns:\r\n            intMdot, mass_used, deltaV (Quantity, Quantity, Quantity):\r\n                mass flow rate (units like kg/day), \r\n                mass used in station-keeping (units of mass), \r\n                change in velocity required for station-keeping (velocity units \r\n                like km/s)\r\n                \r\n        \"\"\"\r\n        \r\n        intMdot = (1./np.cos(np.radians(45.))*np.cos(np.radians(5.))*dF_lateral/const.g0/self.skIsp).to('kg/s')\r\n        mass_used = (intMdot*t_int).to('kg')\r\n        deltaV = (dF_lateral/self.scMass*t_int).to('km/s')\r\n        \r\n        return intMdot, mass_used, deltaV\r\n\r\n    class SolarEph:\r\n        \"\"\"Solar system ephemerides class \r\n        \r\n        This class takes the constants in Appendix D.4 of Vallado as inputs\r\n        and stores them for use in defining solar system ephemerides at a \r\n        given time.\r\n        \r\n        Args:\r\n            a (list):\r\n                semimajor axis list (in AU)\r\n            e (list):\r\n                eccentricity list\r\n            i (list):\r\n                inclination list\r\n            O (list):\r\n                right ascension of the ascending node list\r\n            w (list):\r\n                longitude of periapsis list\r\n            lM (list):\r\n                mean longitude list\r\n                \r\n        Each of these lists has a maximum of 4 elements. The values in \r\n        these lists are used to propagate the solar system planetary \r\n        ephemerides for a specific solar system planet.\r\n        \r\n        Attributes:\r\n            a (list):\r\n                list of semimajor axis (in AU)\r\n            e (list):\r\n                list of eccentricity\r\n            i (list):\r\n                list of inclination\r\n            O (list):\r\n                list of right ascension of the ascending node\r\n            w (list):\r\n                list of longitude of periapsis\r\n            lM (list):\r\n                list of mean longitude values\r\n            \r\n        Each of these lists has a maximum of 4 elements. The values in \r\n        these lists are used to propagate the solar system planetary \r\n        ephemerides for a specific solar system planet.\"\"\"\r\n\r\n        def __init__(self, a, e, i, O, w, lM):\r\n            \r\n            # attach units of AU\r\n            self.a = a*u.AU \r\n            # change to km\r\n            self.a = self.a.to('km') \r\n            # strip dimensions\r\n            self.a = self.a.value \r\n            if not isinstance(self.a, float):\r\n                self.a = self.a.tolist()\r\n            # store list of dimensionless eccentricity values\r\n            self.e = e \r\n            # store list of inclination values (degrees)\r\n            self.i = i \r\n            # store list of right ascension of ascending node values (degrees)\r\n            self.O = O \r\n            # store list of longitude of periapsis values (degrees)\r\n            self.w = w \r\n            # store list of mean longitude values (degrees)\r\n            self.lM = lM\r\n\r\n        def __str__(self):\r\n            \"\"\"String representation of the SolarEph object\r\n            \r\n            When the command 'print' is used on the SolarEph object, this \r\n            method will print the attribute values contained in the object\"\"\"\r\n            \r\n            for att in self.__dict__.keys():\r\n                print '%s: %r' % (att, getattr(self, att))\r\n            \r\n            return 'SolarEph class object attributes'\r\n", "meta": {"hexsha": "86a028675a140aa218694d42b6a9048f8fbed8a4", "size": 31484, "ext": "py", "lang": "Python", "max_stars_repo_path": "EXOSIMS/Prototypes/Observatory.py", "max_stars_repo_name": "dgarrett622/EXOSIMS", "max_stars_repo_head_hexsha": "ce41adc8c162b6330eb9cefee83f3a395bcff614", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EXOSIMS/Prototypes/Observatory.py", "max_issues_repo_name": "dgarrett622/EXOSIMS", "max_issues_repo_head_hexsha": "ce41adc8c162b6330eb9cefee83f3a395bcff614", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-08-13T18:39:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-26T00:18:37.000Z", "max_forks_repo_path": "EXOSIMS/Prototypes/Observatory.py", "max_forks_repo_name": "douglase/EXOSIMS", "max_forks_repo_head_hexsha": "ce41adc8c162b6330eb9cefee83f3a395bcff614", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.7823834197, "max_line_length": 112, "alphanum_fraction": 0.5254414941, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 8227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.3174262655876759, "lm_q1q2_score": 0.1673841147990524}}
{"text": "\"\"\"\nFunctions for Imaging Pipeline\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Ellipse\nfrom astropy.io import fits\nfrom astropy.modeling import models, fitting\nfrom astropy.table import Table\nfrom scipy.optimize import curve_fit\nimport os\n\nfrom astropy.coordinates import SkyCoord\nimport astropy.units as u\nfrom astroquery.sdss import SDSS\n\nimport astroalign as aa\nimport sep\n\nfrom pynot import alfosc\nfrom pynot.functions import get_version_number, mad\nfrom pynot.data.organizer import get_filter\n\n__version__ = get_version_number()\n\n\ndef source_detection(fname, zeropoint=0., threshold=5.0, aperture=10.0, kwargs_bg={}, kwargs_ext={}):\n    \"\"\"\n    Run source detection in the input image using the python package SEP, based on the SExtractor algorithm.\n\n    Parameters\n    ----------\n    fname : str\n        Filename of the FITS image to be analyzed. The image must have at least two extensions:\n        the first should be the image in counts, and one should be named ERR holding the associated error image\n\n    zeropoint : float  [default=0.]\n        Magnitude zero-point for the given photometric filter used for the observations.\n        By defualt instrument magnitudes will be returned if no zero-point is given.\n\n    threshold : float  [default=5.0]\n        Detection threshold in 'sigmas'.\n\n    aperture : float  [default=10.]\n        Circular aperture radius in pixels.\n\n    kwargs_bg : dict\n        Parameters to pass to background subtraction (sep.Background()).\n        See defition in `default_options_img.yml`\n\n    kwargs_ext : dict\n        Parameters to pass to source extraction (sep.extract()).\n        See defition in `default_options_img.yml`\n\n    Returns\n    -------\n    table_fname : str\n        The autogenerated filename of the source catalog. The format is: file-base of the input filename + '_phot.fits'.\n        Ex.: fname='alfosc_rband.fits' -> table_fname='alfosc_rband_phot.fits'\n\n    segmap_fname : str\n        The autogenerated filename of the segmentation map. This image holds the regions associated to each source\n        in the source catalog. The format is: file-base of the input filename + '_sep.fits'\n\n    output_msg : str\n        Log of messages from the function call.\n    \"\"\"\n    msg = list()\n    # get GAIN from header\n    data = fits.getdata(fname)\n    error_image = fits.getdata(fname, 'ERR')\n    hdr = fits.getheader(fname)\n    msg.append(\"          - Loaded input image: %s\" % fname)\n\n    if 'EXPTIME' in hdr:\n        exptime = hdr['EXPTIME']\n        msg.append(\"          - Loaded exposure time from image header: %.1f\" % exptime)\n    else:\n        exptime = 1.\n        msg.append(\"[WARNING] - No exposure time found in image header! Assuming image in counts.\")\n\n    data = data * 1.\n    error_image = error_image * 1.\n    if 'threshold' in kwargs_ext:\n        threshold = kwargs_ext.pop('threshold')\n    if 'aperture' in kwargs_ext:\n        aperture = kwargs_ext.pop('aperture')\n\n    bkg = sep.Background(data, **kwargs_bg)\n    data_sub = data - bkg\n    msg.append(\"          - Subtracted sky background\")\n    msg.append(\"          - Background RMS: %.2e\" % bkg.globalrms)\n    data_sub = data_sub.byteswap().newbyteorder()\n    error_image = error_image.byteswap().newbyteorder()\n    if data_sub.dtype.byteorder != '<':\n        data_sub = data_sub.byteswap().newbyteorder()\n        error_image = error_image.byteswap().newbyteorder()\n    extract_output = sep.extract(data_sub, threshold, err=bkg.globalrms, **kwargs_ext)\n    if len(extract_output) == 2:\n        objects, segmap = extract_output\n    else:\n        objects = extract_output\n        segmap = None\n    N_obj = len(objects)\n    msg.append(\"          - Detected %i objects\" % N_obj)\n\n    # Calculate fixed aperture magnitudes:\n    aper_results = sep.sum_circle(data_sub, objects['x'], objects['y'], aperture, err=error_image)\n    aper_flux, aper_fluxerr, aper_flag = aper_results\n    msg.append(\"          - Calculating fluxes within circular aperture of: %i pixels\" % aperture)\n\n    # Calculate Kron radius:\n    x = objects['x']\n    y = objects['y']\n    a = objects['a']\n    b = objects['b']\n    theta = objects['theta']\n    kronrad, krflag = sep.kron_radius(data_sub, x, y, a, b, theta, 6.0)\n    kronrad[kronrad < 1.] = 1.\n    # Sum fluxes in ellipse apertures:\n    flux, fluxerr, flag = sep.sum_ellipse(data_sub, x, y, a, b, theta, 2.5*kronrad, subpix=1)\n    msg.append(\"          - Calculating Kron radii and fluxes within elliptical apertures\")\n    # combine flags:\n    flag |= krflag\n\n    # If the Kron radius is less than r_min (aperture), use aperture fluxes:\n    r_min = aperture\n    use_circle = kronrad * np.sqrt(b * a) < r_min\n    flux[use_circle] = aper_flux[use_circle]\n    fluxerr[use_circle] = aper_fluxerr[use_circle]\n    flag[use_circle] = aper_flag[use_circle]\n    msg.append(\"          - Targets with Kron radii below R_min (%.2f) are ignored\" % r_min)\n    msg.append(\"          - Circular aperture fluxes used instead where R_kron < R_min\")\n    if np.sum(use_circle) == 1:\n        msg.append(\"          - %i source identified with R_kron < R_min\" % np.sum(use_circle))\n    else:\n        msg.append(\"          - %i sources identified with R_kron < R_min\" % np.sum(use_circle))\n\n    # Save output table:\n    base, ext = os.path.splitext(fname)\n    table_fname = base + '_phot.fits'\n    object_table = Table(objects)\n    object_table['flux_auto'] = flux\n    object_table['flux_err_auto'] = fluxerr\n    object_table['flux_aper'] = aper_flux\n    object_table['flux_err_aper'] = aper_fluxerr\n    object_table['R_kron'] = kronrad\n    flux[flux <= 0] = 1.\n    object_table['mag_auto'] = zeropoint - 2.5*np.log10(flux)\n    object_table.write(table_fname, format='fits', overwrite=True)\n    msg.append(\" [OUTPUT] - Saved extraction table: %s\" % table_fname)\n\n    # Save segmentation map:\n    if segmap is not None:\n        segmap_fname = base + '_seg.fits'\n        seg_hdr = fits.Header()\n        seg_hdr['AUTHOR'] = 'PyNOT version %s' % __version__\n        seg_hdr['IMAGE'] = fname\n        seg_hdr['FILTER'] = get_filter(hdr)\n        seg_hdr.add_comment(\"Segmentation map from SEP (SExtractor)\")\n        fits.writeto(segmap_fname, segmap, header=seg_hdr, overwrite=True)\n        msg.append(\" [OUTPUT] - Saved source segmentation map: %s\" % segmap_fname)\n    else:\n        segmap_fname = ''\n\n    # Plot source identifications:\n    fig_fname = base + '_sources.pdf'\n    plot_objects(fig_fname, data_sub, objects, threshold=threshold)\n    msg.append(\" [OUTPUT] - Saved source identification overview: %s\" % fig_fname)\n    msg.append(\"\")\n    output_msg = \"\\n\".join(msg)\n\n    return table_fname, segmap_fname, output_msg\n\n\ndef plot_objects(fig_fname, data, objects, threshold=5.):\n    \"\"\"\n    Create a plot of the image and the detected sources from SEP.\n\n    Parameters\n    ----------\n    fig_fname : str\n        Filename of the resulting figure\n\n    data : np.array, shape (N, M)\n        Numpy array of the image data, must be a 2D array.\n\n    objects : astropy.table.Table or List[dict]\n        List of dictionaries or astropy table holding the object information:\n        x, y : x, y positions\n        a, b : aperture minor and major axes in pixels\n        theta : aperture orientation in radians\n\n    threshold : float  [default=5.]\n        Constract threshold for the image. The color-scale is normalized based on the image\n        statistics (median and MAD). The min and max values are -1*MAD and +`threshold`*MAD\n        around the median value of the image counts, where MAD is the median absolute deviation.\n\n    Returns\n    -------\n    None\n    \"\"\"\n    # plot background-subtracted image\n    fig, ax = plt.subplots()\n    m, s = np.median(data), 1.5*mad(data)\n    ax.imshow(data, interpolation='nearest', cmap='gray_r',\n              vmin=m-1*s, vmax=m+threshold*s, origin='lower')\n\n    # plot an ellipse for each object\n    for item in objects:\n        e = Ellipse(xy=(item['x'], item['y']),\n                    width=10*item['a'],\n                    height=10*item['b'],\n                    angle=item['theta'] * 180. / np.pi)\n        e.set_facecolor('none')\n        e.set_edgecolor('red')\n        e.set_linewidth(0.8)\n        ax.add_artist(e)\n    fig.tight_layout()\n    fig.savefig(fig_fname)\n\n\ndef load_fits_image(fname):\n    \"\"\"Load a FITS image with an associated error extension and an optional data quality MASK.\"\"\"\n    with fits.open(fname) as hdu_list:\n        image = hdu_list[0].data\n        hdr = hdu_list[0].header\n        if 'ERR' in hdu_list:\n            error = hdu_list['ERR'].data\n        else:\n            raise TypeError(\"No error image detected\")\n\n        if 'MASK' in hdu_list:\n            mask = hdu_list['MASK'].data\n        else:\n            mask = np.zeros_like(image, dtype=bool)\n    return image, error, mask, hdr\n\n\ndef measure_seeing(img, centers, size=20, max_obj=10):\n    \"\"\"\n    Measure the average seeing in an image by fitting a 2D Gaussian to pre-defined point sources.\n\n    Parameters\n    ----------\n    img : np.array, shape(N, M)\n        Numpy array of the image to analyze.\n\n    centers : list[number, number]\n        List of positions of point sources (x, y) in pixels\n\n    size : int  [default=20]\n        Image cutout size. The Gaussian PSF is fitted in a box of size 2*size by 2*size pixels.\n\n    max_obj : int  [default=10]\n        Maximum number of sources to include in the fitting.\n\n    Returns\n    -------\n    fwhm : float\n        The average seeing FWHM in pixels.\n\n    ratio : float\n        The average axis ratio (ellipticity) of the Gaussian PSF.\n\n    msg : str\n        Output message of the function call.\n        If no warnings occurred, this is an emptry string.\n    \"\"\"\n    X = np.arange(img.shape[1])\n    Y = np.arange(img.shape[0])\n    sigmas = list()\n    ratios = list()\n    good_x = (centers[:, 0] > size) & (centers[:, 0] < X.max()-size)\n    good_y = (centers[:, 1] > size) & (centers[:, 1] < Y.max()-size)\n    if np.sum(good_x & good_y) < 2:\n        msg = \"[WARNING] - Not enough sources to measure seeing.\"\n        return (-1, -1, msg)\n    max_obj = min(max_obj, np.sum(good_x & good_y))\n    idx = np.random.choice(np.arange(len(centers))[good_x & good_y], max_obj, replace=False)\n    for x_cen, y_cen in centers[idx]:\n        x1, x2 = int(x_cen)-size, int(x_cen)+size\n        y1, y2 = int(y_cen)-size, int(y_cen)+size\n        cutout = img[y1:y2, x1:x2]\n        x, y = np.meshgrid(X[x1:x2], Y[y1:y2])\n        A = img[int(y_cen), int(x_cen)]\n        p_init = models.Gaussian2D(amplitude=A, x_mean=x_cen, y_mean=y_cen, x_stddev=5, y_stddev=5, theta=0)\n        try:\n            fitter = fitting.LevMarLSQFitter()\n        except TypeError:\n            continue\n        p_opt = fitter(p_init, x, y, cutout-np.median(cutout))\n        sigma_x = p_opt.x_stddev\n        sigma_y = p_opt.y_stddev\n        sig = np.sqrt(sigma_x**2 + sigma_y**2)\n        ba = min(sigma_x, sigma_y) / max(sigma_x, sigma_y)\n        sigmas.append(sig)\n        ratios.append(ba)\n\n    if len(sigmas) < 2:\n        msg = \"[WARNING] - Not enough sources to measure seeing.\"\n        return (-1, -1, msg)\n\n    fwhm = np.median(sigmas) * 2.35\n    ratio = np.median(ratios)\n    msg = \"\"\n    return (fwhm, ratio, msg)\n\n\ndef save_file_log(log_name, image_log, target_hdr):\n    with open(log_name, 'w') as out:\n        out.write(\"# PyNOT Combination Log of Target: %s\\n\" % target_hdr['OBJECT'])\n        out.write(\"# Filter: %s\\n\" % get_filter(target_hdr))\n        out.write(\"# Col 1: Filename\\n\")\n        out.write(\"# Col 2: FWHM / pixels  (seeing)\\n\")\n        out.write(\"# Col 3: PSF axis ratio  (minor/major)\\n\")\n        out.write(\"# Col 4: Exp. Time / seconds\\n\")\n        out.write(\"# \" + 40*\"-\" + \"\\n\")\n        for line in image_log:\n            out.write(\" %s   %.1f  %5.2f  %6.1f\\n\" % tuple(line))\n\n\ndef image_combine(corrected_images, output='', log_name='', fringe_image='', method='weighted', max_control_points=50, detection_sigma=5, min_area=9):\n    \"\"\"\n    Register and combine a list of FITS images using affine transformation.\n\n    Parameters\n    ----------\n    corrected_images : List[str]\n        List of input filenames of `corrected` images, i.e., bias, flat corrected\n        and trimmed for filter/aperture vignetting.\n\n    output : str  [default='']\n        Output filename of the combined image. If not given, it is generated from the OBJECT keyword of the FITS header.\n\n    log_name : str  [default='']\n        Filename of the combination log. This table holds the average seeing FWHM, PSF ellipticity, and exposure time\n        for each image in the input list.\n\n    fringe_image : str  [default='']\n        Filename of the fringe image (FITS format) from `pynot.create_fringe_image`.\n        If given, this image will be subtracted from each input image before combination.\n\n    method : str  [default='weighted']\n        Method for image combination: mean, median or weighted.\n        By default an inverse-variance weighting is used.\n\n    max_control_points : int  [default=50]\n        Maximum number of control point-sources to find the transformation.\n        A lower number will converge faster but may result in a less robust image registration.\n\n    detection_sigma : float  [default=5.]\n        Detection threshold for control points in units of standard deviations of the sky background.\n\n    min_area : int  [default=9]\n        Minimum number of connected pixels to be considered a source\n\n    Returns\n    -------\n    output_msg : str\n        Log of messages from the function call.\n    \"\"\"\n    msg = list()\n    if fringe_image != '':\n        norm_sky = fits.getdata(fringe_image)\n        msg.append(\"          - Loaded normalized fringe image: %s\" % fringe_image)\n    else:\n        norm_sky = 1.\n    target_fname = corrected_images[0]\n    target, target_err, target_mask, target_hdr = load_fits_image(target_fname)\n    target = target - norm_sky*np.median(target)\n    exptime = target_hdr['EXPTIME']\n    target /= exptime\n    target_err /= exptime\n    target_hdr['BUNIT'] = 'count / s'\n    msg.append(\"          - Aligning all images to reference: %s\" % target_fname)\n\n    msg.append(\"          - Registering input images:\")\n    shifted_images = [target]\n    shifted_vars = [target_err**2]\n    target = target.byteswap().newbyteorder()\n    if target.dtype.byteorder != '<':\n        target = target.byteswap().newbyteorder()\n    final_exptime = exptime\n    image_log = list()\n    if len(corrected_images) > 1:\n        for fname in corrected_images[1:]:\n            msg.append(\"          - Input image: %s\" % fname)\n            source, source_err, source_mask, hdr_i = load_fits_image(fname)\n            source = source - norm_sky*np.median(source)\n            source /= hdr_i['EXPTIME']\n            source_err /= hdr_i['EXPTIME']\n            final_exptime += hdr_i['EXPTIME']\n            try:\n                transf, (coords) = aa.find_transform(source, target,\n                                                     max_control_points=max_control_points,\n                                                     detection_sigma=detection_sigma,\n                                                     min_area=min_area)\n            except:\n                msg.append(\" [ERROR]  - Failed to find image transformation!\")\n                msg.append(\"          - Skipping image\")\n                continue\n\n            source = source.byteswap().newbyteorder()\n            source_err = source_err.byteswap().newbyteorder()\n            source_mask = source_mask.byteswap().newbyteorder()\n            if source.dtype.byteorder != '<':\n                source = source.byteswap().newbyteorder()\n            if source_err.dtype.byteorder != '<':\n                source_err = source_err.byteswap().newbyteorder()\n            if source_mask.dtype.byteorder != '<':\n                source_mask = source_mask.byteswap().newbyteorder()\n\n            registered_image, _ = aa.apply_transform(transf, source, target, fill_value=0)\n            registered_error, _ = aa.apply_transform(transf, source_err, target, fill_value=0)\n            registered_mask, _ = aa.apply_transform(transf, source_mask, target, fill_value=0)\n            target_mask += 1 * (registered_mask > 0)\n            registered_error[registered_error == 0] = np.mean(registered_error)*10\n            shifted_images.append(registered_image)\n            shifted_vars.append(registered_error**2)\n            source_list, target_list = coords\n            if len(image_log) == 0:\n                fwhm, ratio, seeing_msg = measure_seeing(target, target_list)\n                image_log.append([os.path.basename(target_fname), fwhm, ratio, exptime])\n                if seeing_msg:\n                    msg.append(seeing_msg)\n            fwhm, ratio, seeing_msg = measure_seeing(source, source_list)\n            if seeing_msg:\n                msg.append(seeing_msg)\n            image_log.append([os.path.basename(fname), fwhm, ratio, hdr_i['EXPTIME']])\n\n        if log_name == '':\n            filter_name = alfosc.filter_translate[get_filter(target_hdr)]\n            log_name = 'filelist_%s_%s.txt' % (target_hdr['OBJECT'], filter_name)\n        save_file_log(log_name, image_log, target_hdr)\n        msg.append(\" [OUTPUT] - Saved file log and image stats: %s\" % log_name)\n\n        if method == 'median':\n            final_image = np.nanmedian(shifted_images, axis=0)\n            final_error = np.sqrt(np.nanmean(shifted_vars, axis=0))\n            target_hdr['COMBINE'] = \"Median\"\n        elif method == 'mean':\n            final_image = np.nanmean(shifted_images, axis=0)\n            final_error = np.sqrt(np.nanmean(shifted_vars, axis=0))\n            target_hdr['COMBINE'] = \"Mean\"\n        else:\n            w = 1./np.array(shifted_vars)\n            shifted_images = np.array(shifted_images)\n            final_image = np.nansum(w*shifted_images, axis=0) / np.sum(w, axis=0)\n            final_error = np.sqrt(1. / np.nansum(w, axis=0))\n            target_hdr['COMBINE'] = \"Inverse Variance Weighted\"\n        final_mask = 1 * (target_mask > 0)\n    else:\n        final_image = target\n        final_error = target_err\n        final_mask = target_mask\n        target_hdr['COMBINE'] = \"None\"\n\n    target_hdr['NCOMBINE'] = len(shifted_images)\n    target_hdr['EXPTIME'] = final_exptime / len(shifted_images)\n    # Fix NaN values from negative pixel values:\n    err_NaN = np.isnan(final_error)\n    final_error[err_NaN] = np.nanmean(final_error)*100\n    msg.append(\"          - Correcting NaNs in noise image: %i pixel(s)\" % np.sum(err_NaN))\n    target_hdr['DATAMIN'] = np.nanmin(final_image)\n    target_hdr['DATAMAX'] = np.nanmax(final_image)\n    target_hdr['EXTNAME'] = 'DATA'\n    target_hdr['AUTHOR'] = 'PyNOT version %s' % __version__\n\n    mask_hdr = fits.Header()\n    mask_hdr.add_comment(\"0 = Good Pixels\")\n    mask_hdr.add_comment(\"1 = Cosmic Ray Hits\")\n\n    if output == '':\n        output = \"combined_%s.fits\" % target_hdr['OBJECT']\n\n    sci_ext = fits.PrimaryHDU(final_image, header=target_hdr)\n    err_ext = fits.ImageHDU(final_error, header=target_hdr, name='ERR')\n    mask_ext = fits.ImageHDU(final_mask, header=mask_hdr, name='MASK')\n    output_HDU = fits.HDUList([sci_ext, err_ext, mask_ext])\n    output_HDU.writeto(output, overwrite=True)\n    msg.append(\"          - Successfully combined the images\")\n    msg.append(\" [OUTPUT] - Saving output: %s\" % output)\n    msg.append(\"\")\n    output_msg = \"\\n\".join(msg)\n    return output_msg\n\n\ndef plot_image2D(fname, image, vmin=-2, vmax=2):\n    fig = plt.figure()\n    ax = fig.add_subplot(111)\n    med = np.median(image)\n    s = mad(image)\n    im = ax.imshow(image, origin='lower', vmin=med+vmin*s, vmax=med+vmax*s)\n    fig.colorbar(im)\n    fig.tight_layout()\n    fig.savefig(fname)\n\n\ndef create_fringe_image(input_filenames, output='', fig_fname='', threshold=3.0):\n    \"\"\"\n    Create a normalized average fringe image for a list of images taken with the same filter.\n\n    Parameters\n    ----------\n    input_filenames : str\n        List of FITS filenames of images taken in the same photometric band.\n\n    output : str  [default='']\n        Output filename of the fringe image.\n\n    fig_fname : str  [default='']\n        Output filename of the diagnostic figure showing the normalized fringe image.\n\n    threshold : float  [default=3.]\n        Threshold for source rejection in the image stacking in units of the standard deviation\n        of the sky background (estimated via median absolute deviation).\n\n    Returns\n    -------\n    output_msg : str\n        Log of messages from the function call.\n    \"\"\"\n    msg = list()\n    hdr = fits.getheader(input_filenames[0])\n    img_list = [fits.getdata(fname) for fname in input_filenames]\n    exptimes = [fits.getheader(fname)['EXPTIME'] for fname in input_filenames]\n    msg.append(\"          - Loaded input images\")\n    mask = [np.fabs(im-np.median(im)) < threshold*mad(im) for im in img_list]\n    msg.append(\"          - Created image mask using threshold: %.2f\" % threshold)\n\n    N = np.sum(mask, 0)\n    skysum = np.sum([im*m/t for im, m, t in zip(img_list, mask, exptimes)], axis=0)\n    skysum[N == 0] = np.median(skysum)\n    N[N == 0] = 1\n    sky = skysum / N\n    norm_sky = sky / np.median(sky)\n    msg.append(\"          - Created normalized fringe image\")\n\n    if fig_fname:\n        plot_image2D(fig_fname, norm_sky, vmin=-2, vmax=2)\n        msg.append(\" [OUTPUT] - Saving figure: %s\" % fig_fname)\n\n    if output == '':\n        output = \"fringe_%s.fits\" % hdr['OBJECT']\n    hdr['OBJECT'] = 'Fringe Image'\n    hdr['EXTNAME'] = 'MODEL'\n    hdr.add_comment('Average Fringe image, median normalized')\n    fits.writeto(output, norm_sky, header=hdr, overwrite=True)\n    msg.append(\" [OUTPUT] - Saving output: %s\" % output)\n    msg.append(\"\")\n    output_msg = \"\\n\".join(msg)\n    return output_msg\n\n\n\ndef match_phot_catalogs(sep, phot, match_radius=1.):\n    \"\"\"\n    Match a source catalog from SEP to a photometric catalog `phot`.\n    Both catalogs must include columns 'ra' and 'dec'.\n\n    Parameters\n    ----------\n    match_radius : float  [default=1.0]\n        Matching radius in arcseconds\n\n    Returns\n    -------\n    matched_sep : astropy.table.Table\n        An astropy table of sources in the SEP source catalog that have matches\n        in the reference `phot` catalog.\n\n    matched_phot : astropy.table.Table\n        An astropy table of sources in the reference `phot` catalog that have matches\n        in the SEP source catalog.\n    \"\"\"\n    matched_sep = list()\n    matched_phot = list()\n    refs = np.array([phot['ra'], phot['dec']]).T\n    for row in sep:\n        xy = np.array([row['ra'], row['dec']])\n        dist = np.sqrt(np.sum((refs - xy)**2, axis=1))\n        index = np.argmin(dist)\n        if np.min(dist) < match_radius/3600.:\n            matched_phot.append(np.array(phot[index]))\n            matched_sep.append(np.array(row))\n    matched_sep = np.array(matched_sep)\n    matched_phot = np.array(matched_phot)\n    return Table(matched_sep), Table(matched_phot)\n\n\ndef get_sdss_catalog(ra, dec, radius=4.):\n    \"\"\"Download the SDSS photometry using astroquery for a circular region of radius in deg.\"\"\"\n    catalog_fname = 'sdss_phot_%.2f%+.2f.csv' % (ra, dec)\n    fields = ['ra', 'dec', 'psfMag_u', 'psfMag_g', 'psfMag_r', 'psfMag_i', 'psfMag_z',\n              'psfMagErr_u', 'psfMagErr_g', 'psfMagErr_r', 'psfMagErr_i', 'psfMagErr_z']\n    field_center = SkyCoord(ra, dec, frame='icrs', unit='deg')\n    sdss_result = SDSS.query_region(field_center, radius*u.arcmin, photoobj_fields=fields)\n    if sdss_result is not None:\n        sdss_result.write(catalog_fname, format='ascii.csv', overwrite=True)\n    return sdss_result\n\n\n\next_coeffs = {'u': 0.517,\n              'g': 0.165,\n              'r': 0.0754,\n              'i': 0.0257,\n              'z': 0.0114}\n\ndef flux_calibration_sdss(img_fname, sep_fname, fig_fname='', q_lim=0.8, kappa=3, match_radius=1.):\n    \"\"\"\n    Self-calibration of magnitude zero point using SDSS photometry as reference\n\n    Parameters\n    ----------\n    img_fname : string\n        Filename of WCS calibrated image (_wcs.fits)\n\n    sep_fname : string\n        Filename of the source extraction table (_phot.fits)\n\n    fig_fname : string\n        Filename of the diagnostic figure. Autogenerated by default.\n\n    q_lim : float  [default=0.8]\n        Reject elliptical sources with axis ratio < `q_lim`.\n        Axis ratio is defined as minor/major.\n\n    kappa : float  [default=3]\n        Threshold for projected distance filtering. Sources are rejected if the distance differs\n        more then `kappa` times the median absolute deviation from the median of all distances.\n\n    match_radius : float  [default=1]\n        Matching radius between SDSS sources and image sources\n\n    Returns\n    -------\n    output_msg : string\n        Log of messages from the function call.\n    \"\"\"\n    # -- Get SDSS catalog\n    msg = list()\n\n    hdr = fits.getheader(img_fname)\n    msg.append(\"          - Loaded image: %s\" % img_fname)\n    radius = np.sqrt(hdr['CD1_1']**2 + hdr['CD1_2']**2)*60 * hdr['NAXIS1'] / np.sqrt(2)\n    msg.append(\"          - Downloading SDSS photometric catalog...\")\n    try:\n        sdss_cat = get_sdss_catalog(hdr['CRVAL1'], hdr['CRVAL2'], radius)\n    except:\n        msg.append(\" [ERROR]  - Could not connect to SDSS server. Check your internet connection.\")\n        msg.append(\"\")\n        return \"\\n\".join(msg)\n\n    def line(x, zp):\n        return zp + x\n\n    if sdss_cat is None:\n        msg.append(\" [ERROR]  - No data found in SDSS. No zero point calculated\")\n        msg.append(\"\")\n        return \"\\n\".join(msg)\n\n    airmass = hdr['AIRMASS']\n    filter = alfosc.filter_translate[alfosc.get_filter(hdr)]\n    if 'SDSS' in filter:\n        band = filter.split('_')[0]\n    else:\n        msg.append(\" [ERROR]  - The image was not taken with an SDSS filter. No zero point calculated\")\n        msg.append(\"\")\n        return \"\\n\".join(msg)\n\n\n    # For r-band: (measured from La Palma extinction curve)\n    mag_key = 'psfMag_%s' % band\n    mag_err_key = 'psfMagErr_%s' % band\n    good = (sdss_cat[mag_key] > 0) & (sdss_cat[mag_key] < 30)\n    sdss_cat = sdss_cat[good]\n\n    # Load SEP filename:\n    try:\n        sep_cat = Table.read(sep_fname)\n        sep_hdr = fits.getheader(sep_fname)\n        msg.append(\"          - Loaded SEP source table: %s\" % sep_fname)\n    except (FileNotFoundError, OSError):\n        msg.append(\" [ERROR]  - Could not load SEP source table: %s\" % sep_fname)\n        msg.append(\"\")\n        return \"\\n\".join(msg)\n\n    if 'MAG_ZP' in sep_hdr:\n        msg.append(\"[WARNING] - The source table has already been flux calibrated by PyNOT\")\n        msg.append(\"          - Terminating task...\")\n        msg.append(\"\")\n        return \"\\n\".join(msg)\n\n    axis_ratio = sep_cat['b']/sep_cat['a']\n    # Select only 'round' sources:\n    sep_points = sep_cat[axis_ratio > q_lim]\n\n    # Match catalogs:\n    match_sep, match_sdss = match_phot_catalogs(sep_points, sdss_cat)\n    msg.append(\"          - Cross matched source catalog\")\n\n    mag = match_sdss[mag_key]\n    mag_err = match_sdss[mag_err_key]\n    m_inst = match_sep['mag_auto']\n    k = ext_coeffs[band]\n\n    # Get first estimate using the median:\n    zp0, _ = curve_fit(line, m_inst+k*airmass, mag, p0=[27], sigma=mag_err)\n\n    # Filter outliers:\n    cut = np.abs(zp0 + m_inst + k*airmass - mag) < kappa*mad(zp0 + m_inst + k*airmass - mag)\n    cut &= (mag < 20.1) & (mag > 15)\n\n    # Get weighted average zero point:\n    w = 1./mag_err[cut]**2\n    zp = np.sum((mag[cut] - m_inst[cut] - k*airmass) * w) / np.sum(w)\n    msg.append(\"          - Calculating zero point in SDSS %s band using %i sources\" % (band, len(w)))\n\n    # Zero point dispersion:\n    zp_err = np.std(mag[cut] - zp - m_inst[cut] - k*airmass)\n    msg.append(\"          - Zero Point = %.3f ± %.3f mag\" % (zp, zp_err))\n\n    sep_cat['mag_auto'] += zp\n    sep_cat.write(sep_fname, overwrite=True)\n    with fits.open(sep_fname, 'update') as sep_file:\n        sep_file[0].header.add_comment(\"Self-calibration of mag. zero point using SDSS\")\n        sep_file[0].header['MAG_ZP'] = (np.round(zp, 3), \"Magnitude zero point (AB mag)\")\n        sep_file[0].header['ZP_ERR'] = (np.round(zp_err, 3), \"Uncertainty on magnitude zero point (AB mag)\")\n    msg.append(\" [OUTPUT] - Updating magnitudes in source table: %s\" % sep_fname)\n\n    # -- Plot the zero point for visual aid:\n    base, _ = os.path.splitext(os.path.basename(img_fname))\n    dirname = os.path.dirname(img_fname)\n    if fig_fname == '':\n        fig_fname = 'zero_point_' + base + '.pdf'\n        fig_fname = os.path.join(dirname, fig_fname)\n    fig = plt.figure()\n    ax = fig.add_subplot(111)\n    ax.errorbar(m_inst, mag, 3*mag_err, ls='', marker='.', color='k', alpha=0.8)\n    ax.plot(m_inst[cut], mag[cut], ls='', marker='o', color='b', alpha=0.7)\n    ax.plot(np.sort(m_inst), zp + np.sort(m_inst) + k*airmass, ls='--', color='crimson',\n            label='ZP = %.2f ± %.2f' % (zp, zp_err))\n    ax.set_ylim(np.min(mag)-0.2, np.max(mag)+0.5)\n    ax.set_xlabel(\"Instrument Magnitude\")\n    ax.set_ylabel(\"Reference SDSS Magnitude (r-band)\")\n    ax.legend()\n    ax.tick_params(which='both', top=False, right=False)\n    fig.tight_layout()\n    fig.savefig(fig_fname)\n    msg.append(\" [OUTPUT] - Saving diagnostic figure: %s\" % fig_fname)\n\n    # -- Update header in FITS image:\n    with fits.open(img_fname) as hdu_list:\n        hdu_list['DATA'].header.add_comment(\"Self-calibration of mag. zero point using SDSS\")\n        hdu_list['DATA'].header['MAG_ZP'] = (np.round(zp, 3), \"Magnitude zero point (AB mag)\")\n        hdu_list['DATA'].header['ZP_ERR'] = (np.round(zp_err, 3), \"Uncertainty on magnitude zero point (AB mag)\")\n        hdu_list.writeto(img_fname, overwrite=True)\n\n    msg.append(\" [OUTPUT] - Updating header of input image: %s\" % img_fname)\n    msg.append(\"          - MAG_ZP  = %10.3f / %s\" % (zp, \"Magnitude zero point (AB mag)\"))\n    msg.append(\"          - ZP_ERR  = %10.3f / %s\" % (zp_err, \"Uncertainty on magnitude zero point (AB mag)\"))\n    msg.append(\"\")\n    return \"\\n\".join(msg)\n", "meta": {"hexsha": "f713967d33b8d32a374b78f34d77db9b0b616d88", "size": 29988, "ext": "py", "lang": "Python", "max_stars_repo_path": "pynot/phot.py", "max_stars_repo_name": "jkrogager/PyNOT", "max_stars_repo_head_hexsha": "2514a443079e50c12a13ebbd89a48f91a8d20626", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-09T11:54:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T07:47:05.000Z", "max_issues_repo_path": "pynot/phot.py", "max_issues_repo_name": "jkrogager/PyNOT", "max_issues_repo_head_hexsha": "2514a443079e50c12a13ebbd89a48f91a8d20626", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-06-21T09:44:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T11:13:32.000Z", "max_forks_repo_path": "pynot/phot.py", "max_forks_repo_name": "jkrogager/PyNOT", "max_forks_repo_head_hexsha": "2514a443079e50c12a13ebbd89a48f91a8d20626", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-01T07:42:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-01T07:42:24.000Z", "avg_line_length": 39.0977835724, "max_line_length": 150, "alphanum_fraction": 0.6273175937, "include": true, "reason": "import numpy,from scipy,import astropy,from astropy", "num_tokens": 7764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.3174262655876759, "lm_q1q2_score": 0.1673841147990524}}
{"text": "# Copyright (c) 2018, Xilinx\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n#    1. Redistributions of source code must retain the above copyright\n#       notice, this list of conditions and the following disclaimer.\n#    2. Redistributions in binary form must reproduce the above copyright\n#       notice, this list of conditions and the following disclaimer in the\n#       documentation and/or other materials provided with the distribution.\n#    3. Neither the name of the <organization> nor the\n#       names of its contributors may be used to endorse or promote products\n#       derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nimport os\n# remove Caffe chatter on terminal\nos.environ['GLOG_minloglevel'] = '2'\n\nimport caffe\nimport numpy as np\nimport FINN.core.layers as lb\nimport logging\nfrom google.protobuf.text_format import Merge\n\n# frontend for importing Caffe HWGQ networks\n\n\ndef importCaffeNetwork(modeldef, params):\n    \"\"\"\n    Imports a trained HWGQ Caffe model and returns FINN representation. At the\n    moment, data source layers are not supported, so the deploy.prototxt variant\n   \n    \"\"\"\n    if params is None:\n        net = caffe.Net(modeldef, caffe.TEST)\n    else:\n        net = caffe.Net(modeldef, params, caffe.TEST)\n    model = caffe.proto.caffe_pb2.NetParameter()\n    Merge(open(modeldef, \"rb\").read(), model)\n    numLayers = len(model.layer)\n    outLayerStr = []\n    outParams = []\n    ret = []\n    # TODO check that net is linear (no branching)\n    dataLayerName = net.inputs[0] # any better way to get this?\n    dataShape = net.blobs[dataLayerName].data.shape\n    if dataShape[2] != dataShape[3]:\n        raise Exception(\"Only square images supported for now\")\n    inDim = dataShape[2]\n    inChans = dataShape[1]\n    for i in range(numLayers):\n        layerModel = model.layer[i]\n        layerType = layerModel.type\n        layerName = layerModel.name\n        logging.info(\"Processing layer: %s (type %s). input (chans,dim)=(%d,%d)\" % (layerName, layerType, inChans, inDim))\n        if net.params.has_key(layerName):\n            layerParams = net.params[layerName]\n        if layerType == \"Input\":\n            # TODO we should support some of the transformations that Caffe\n            # supports on the input\n            raise Exception(\"Input layer is not yet convertable, need input data shape instead\")\n        elif layerType == \"Scale\":\n            A = layerParams[0].data\n            if layerModel.scale_param.bias_term:\n                B = layerParams[1].data\n            else:\n                B = np.zeros(shape=A.shape)\n            ret += [lb.LinearLayer(A, B)]\n        elif layerType == \"BatchNorm\":\n            # epsilon to ensure non-zero operand to square root\n            eps = layerModel.batch_norm_param.eps\n            # batchnorm layer has the following data blobs:\n            # [mean, variance, moving average factor]\n            # BUG: mavf can be zero, causing invalid divide below\n            mavf = layerParams[2].data[0]\n            if mavf == 0:\n                mavf = 1\n            m = layerParams[0].data / mavf\n            i = 1 / (np.sqrt( (layerParams[1].data / mavf) + eps ))\n            numBatchNormChans = m.shape[0]\n            # Caffe BN layers do not have b and g\n            b = np.zeros((numBatchNormChans), dtype=np.float32)\n            g = np.ones((numBatchNormChans), dtype=np.float32)\n            # we want to implement batchnorm as a linear operation Mx+N\n            # where Mx+N = g*i*(x-m)+b = g*i*x - g*i*m + b\n            # so M = g*i and N = b - g*i*m\n            M = g*i\n            N = b - g*i*m\n            #outLayerStr += [\"linear\"]\n            #outParams += [M, N]\n            ret += [lb.LinearLayer(M, N)]\n        elif layerType == \"Quant\":\n            # quantization layer\n            # get quantization type and levels\n            qfxn = layerModel.quant_param.forward_func\n            qlevels = np.asarray(layerModel.quant_param.centers, dtype=np.float32)\n            if qfxn == \"hwgq\":\n                # add zero as an explicit level for HWGQ\n                qlevels = np.concatenate((np.asarray([0.0], dtype=np.float32), qlevels))\n                # check for uniform quantization -- all levels equally spaced\n                isUniform = np.all(np.isclose(np.diff(qlevels, 2), 0))\n                if not isUniform:\n                    # TODO add a LookupTableLayer for nonlinear quantization support\n                    raise Exception(\"Nonuniform quantization not yet supported\")\n                else:\n                    # uniform quantization = threshold followed by linear transform\n                    # compute thresholds as HWGQ does\n                    qlevels_t = qlevels[1:] # exclude the zero level for thres. comp\n                    thr = (qlevels_t[:-1] + qlevels_t[1:]) / 2.0\n                    # add explicit zero threshold\n                    thr = np.concatenate((np.asarray([0.0], dtype=np.float32), thr))\n                    # emit threshold layer\n                    #outLayerStr += [\"thres\"]\n                    #outParams += [thr]\n                    ret += [lb.ThresholdingLayer(thr)]\n                    # TODO this should be ideally propagated (similar to bitwidths)\n                    # using a transform\n                    ret[-1].insize = inChans\n                    ret[-1].outsize = inChans\n                    # find the coefficients for the linear transform Fx + G\n                    G = np.asarray([qlevels[0]])\n                    F = np.asarray([qlevels[1] - qlevels[0]])\n                    # emit linear layer with scalars\n                    #outLayerStr += [\"linear\"]\n                    #outParams += [F, G]\n                    ret += [lb.LinearLayer(F, G)]\n            elif qfxn == \"sign\":\n                # sign quantization has its own layer type, but the core logic\n                # still uses 0 as a threshold.\n                thr = np.asarray([[0.0]], dtype=np.float32)\n                ret += [lb.BipolarThresholdingLayer(thr)]\n            else:\n                raise Exception(\"Unsupported quantization function\")\n\n        elif layerType == \"BinaryInnerProduct\":\n            # binary inner product layer may or may not have bias field\n            # additionally, it may use the l1-norm as a scaling factor\n            # need access to prototxt to find out whether to use alpha\n            if not layerModel.binary_inner_product_param.use_binarization:\n                raise Exception(\"use_binarization not set in BinaryInnerProduct layer\")\n            useBias = layerModel.inner_product_param.bias_term\n            W = layerParams[0].data\n            (rows, cols) = W.shape\n            useAlpha = layerModel.binary_inner_product_param.use_alpha\n            # the weights here are not yet binarized - need to do that\n            # access and binarize the weights as done by the bnfc layer impl\n            # binarize the weight matrix:\n            Wbin = np.sign(W)\n            # generate fully connected layer output\n\n            # TODO indicate 1 bit signed (bipolar)\n            ret += [lb.FullyConnectedLayer(Wbin, 1, 32, 32)]\n            ret[-1].in_dim = inDim\n            ret[-1].kernel = 1\n            # treat the produced data as \"rows\"-channel, 1px images\n            inChans = rows\n            inDim = 1\n            if useAlpha:\n                # add a linear layer with A=alpha B=0 after the FC layer\n                alpha = np.zeros(rows, dtype=np.float32)\n                beta = np.zeros(rows, dtype=np.float32)\n                Wabs = np.abs(W)\n                for i in range(rows):\n                    alpha[i] = Wabs[i].sum() / cols\n                ret += [lb.LinearLayer(alpha, beta)]\n            if useBias:\n                # add bias as additive linear layer\n                b = layerParams[1].data\n                ret += [lb.LinearLayer(np.ones((rows), dtype=np.float32), b)]\n        elif layerType == \"BinaryConvolution\":\n            if not layerModel.binary_convolution_param.use_binarization:\n                raise Exception(\"use_binarization not set in BinaryInnerProduct layer\")\n            useAlpha = layerModel.binary_convolution_param.use_alpha\n            useBias = layerModel.convolution_param.bias_term\n            ofm = layerModel.convolution_param.num_output\n            # TODO warn about non-uniform stride/pad/kernelsize\n            # kernel size\n            if len(layerModel.convolution_param.kernel_size) == 0:\n                raise Exception(\"Unknown kernel size\")\n            else:\n                k = layerModel.convolution_param.kernel_size[0]\n            # stride options\n            if len(layerModel.convolution_param.stride) == 0:\n                s = 1\n            else:\n                s = layerModel.convolution_param.stride[0]\n            # padding options\n            if len(layerModel.convolution_param.pad) == 0:\n                pad = 0\n            else:\n                pad = layerModel.convolution_param.pad[0]\n            # size of each output feature map\n            outDim = ((inDim + 2*pad - k) / s) + 1\n            W = layerParams[0].data\n            # binarize kernel weights and output conv layer\n            orig_shape = W.shape\n            Wbin = np.sign(W)\n\n            # TODO indicate 1 bit signed (bipolar)\n            ret += [lb.ConvolutionLayer(Wbin, inDim, pad, s, 1, 1, 1)]\n            ret[-1].kernel = k\n            ret[-1].k = k\n            ret[-1].stride = s\n            ret[-1].parallel = layerModel.convolution_param.group\n            # compute alphas, if needed\n            if useAlpha:\n                Wa = W.reshape((ofm, k*k*inChans))\n                (rows, cols) = Wa.shape\n                # add a linear layer with A=alpha B=0 after the conv layer\n                alpha = np.zeros(rows, dtype=np.float32)\n                Wabs = np.abs(Wa)\n                for i in range(rows):\n                    alpha[i] = Wabs[i].sum() / cols\n                beta = np.zeros(rows, dtype=np.float32)\n                #outLayerStr += [\"linear\"]\n                #outParams += [alpha, beta]\n                ret += [lb.LinearLayer(alpha, beta)]\n            # TODO support conv bias\n            if useBias:\n                raise Exception(\"BinaryConvolution bias not yet supported\")\n            # update data shape passed to next layer\n            inChans = ofm\n            inDim = outDim\n        elif layerType == \"Convolution\":\n            useBias = layerModel.convolution_param.bias_term\n            ofm = layerModel.convolution_param.num_output\n            # TODO warn about non-uniform stride/pad/kernelsize\n            # kernel size\n            if len(layerModel.convolution_param.kernel_size) == 0:\n                raise Exception(\"Unknown kernel size\")\n            else:\n                k = layerModel.convolution_param.kernel_size[0]\n            # stride options\n            if len(layerModel.convolution_param.stride) == 0:\n                s = 1\n            else:\n                s = layerModel.convolution_param.stride[0]\n            # padding options\n            if len(layerModel.convolution_param.pad) == 0:\n                pad = 0\n            else:\n                pad = layerModel.convolution_param.pad[0]\n            # size of each output feature map\n            outDim = ((inDim + 2*pad - k) / s) + 1\n            W = layerParams[0].data\n            #outParams += [W]\n            #outLayerStr += [\"conv:%d:%d:%d:32:32:32\" % (inDim, pad, s)]\n            ret += [lb.ConvolutionLayer(W, inDim, pad, s, 32, 32, 32)]\n            ret[-1].kernel = k\n            ret[-1].stride = s\n            ret[-1].parallel = layerModel.convolution_param.group\n             # TODO support conv bias\n            if useBias:\n                rows = ofm    \n                b = layerParams[1].data\n                ret += [lb.LinearLayer(np.ones((rows), dtype=np.float32), b)]\n                raise Exception(\"Convolution bias not yet supported\")\n            # update data shape passed to next layer\n            inChans = ofm\n            inDim = outDim\n        elif layerType == \"InnerProduct\":\n            useBias = layerModel.inner_product_param.bias_term\n            W = layerParams[0].data\n            (rows, cols) = W.shape\n            # if the previous layer was a conv layer, interleave the columns\n            # to match the interleaved channel data layout\n            # generate fully connected layer output\n            #outLayerStr += [\"fc:32:32:32\"]\n            #outParams += [W]\n            ret += [lb.FullyConnectedLayer(W, 32, 32, 32)]\n            # treat the produced data as \"rows\"-channel, 1px images\n            ret[-1].kernel =1\n            inChans = rows\n            inDim = 1\n            if useBias:\n                # add bias as additive linear layer\n                b = layerParams[1].data\n                #outLayerStr += [\"linear\"]\n                #outParams += [np.ones((rows), dtype=np.float32), b]\n                ret += [lb.LinearLayer(np.ones((rows), dtype=np.float32), b)]\n        elif layerType == \"Pooling\":\n            if inDim == 1:\n                continue\n            if layerModel.pooling_param.pool == 0:  # max pooling\n                poolFxn = \"MAX\"\n            elif layerModel.pooling_param.pool == 1:  # average pooling\n                poolFxn = \"AVE\"\n            else:\n                raise Exception(\"Only max and average pooling supported for now\")\n            k = layerModel.pooling_param.kernel_size\n            s = layerModel.pooling_param.stride\n            #outLayerStr += [\"maxpool:%d:%d:%d:%d\" % (inDim, inChans, k, s)]\n            ret += [lb.PoolingLayer(inDim, inChans, k, s, poolFxn)]\n            # update data shape passed to next layer\n            inChans = ofm\n            inDim = ((inDim - k) / s) + 1\n        elif layerType == \"Softmax\":\n            ret += [lb.SoftmaxLayer()]\n            ret[-1].outsize = inChans\n            ret[-1].insize = inChans\n        elif layerType == \"ReLU\":\n            ret += [lb.ReLULayer()]\n        elif layerType == \"LRN\":\n            pass\n        elif layerType == \"Dropout\":\n            pass\n        else:\n            raise Exception(\"Unrecognized or unsupported layer: %s\" % layerType)\n\n    return ret\n", "meta": {"hexsha": "c9c79b2e606a243ebac60ae774020fbab1b6550d", "size": 14997, "ext": "py", "lang": "Python", "max_stars_repo_path": "FINN/frontend/frontend_hwgq.py", "max_stars_repo_name": "HyunwooKim2/FINN", "max_stars_repo_head_hexsha": "fac4ff40aaba1c14aa416738e3d22802649a94f8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FINN/frontend/frontend_hwgq.py", "max_issues_repo_name": "HyunwooKim2/FINN", "max_issues_repo_head_hexsha": "fac4ff40aaba1c14aa416738e3d22802649a94f8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FINN/frontend/frontend_hwgq.py", "max_forks_repo_name": "HyunwooKim2/FINN", "max_forks_repo_head_hexsha": "fac4ff40aaba1c14aa416738e3d22802649a94f8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-27T07:01:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-27T07:01:13.000Z", "avg_line_length": 46.5745341615, "max_line_length": 122, "alphanum_fraction": 0.5657131426, "include": true, "reason": "import numpy", "num_tokens": 3479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.16738411479905235}}
{"text": "from collections import OrderedDict\n\nimport astropy.units as u\nimport numpy as np\n\nfrom exorad.models.foregrounds.skyForegrounds import SkyForeground\nfrom exorad.models.foregrounds.zodiacalForeground import ZodiacalFrg\nfrom .task import Task\n\n\nclass EstimateZodi(Task):\n    \"\"\"\n    It estimate the zodiacal radiance in the target direction for a specific wl range\n\n    Parameters\n    -----------\n    zodi: dict\n        zodiacal foreground description\n    target: Target\n        target class\n    wl_range: (float, float)\n        wavelength range to investigate. (wl_min, wl_max)\n\n    Returns\n    -------\n    Target:\n        updated target class\n    \"\"\"\n\n    def __init__(self):\n        self.addTaskParam('zodi', 'zodiacal foreground description')\n        self.addTaskParam('target', 'target class')\n        self.addTaskParam('wl_range', 'wavelength range to investigate')\n\n    def execute(self):\n        self.info('estimating zodiacal foreground')\n        zodi_dict = self.get_task_param('zodi')\n        target = self.get_task_param('target')\n        wl_min, wl_max = self.get_task_param('wl_range')\n\n        wl = np.logspace(np.log10((wl_min.to(u.um)).value),\n                         np.log10((wl_max.to(u.um)).value), 6000) * u.um\n        zodi = ZodiacalFrg(wl=wl, description=zodi_dict)\n\n        if not hasattr(target, 'foreground'):\n            setattr(target, 'foreground', OrderedDict())\n        target.foreground['zodi'] = zodi.radiance\n        self.set_output(target)\n\n\nclass EstimateForeground(Task):\n    \"\"\"\n    It estimate the foreground radiance in the target direction for a specific wl range\n\n    Parameters\n    -----------\n    foreground: dict\n        foreground description\n    target: Target\n        target class\n    wl_range: (float, float)\n        wavelength range to investigate. (wl_min, wl_max)\n\n    Returns\n    -------\n    Target:\n        updated target class\n    \"\"\"\n\n    def __init__(self):\n        self.addTaskParam('foreground', 'foreground description')\n        self.addTaskParam('target', 'target class')\n        self.addTaskParam('wl_range', 'wavelength range to investigate')\n\n    def execute(self):\n        self.info('estimating custom foreground')\n        foreground_dict = self.get_task_param('foreground')\n        target = self.get_task_param('target')\n        wl_min, wl_max = self.get_task_param('wl_range')\n\n        wl = np.logspace(np.log10((wl_min.to(u.um)).value),\n                         np.log10((wl_max.to(u.um)).value), 6000) * u.um\n        foreground_name = foreground_dict['value']\n        foreground = SkyForeground(wl, foreground_dict)\n        if not hasattr(target, 'foreground'):\n            setattr(target, 'foreground', OrderedDict())\n        target.foreground[foreground_name] = foreground.skyFilter\n        if not hasattr(target, 'skyTransmission'):\n            from exorad.models.signal import Signal\n            setattr(target, 'skyTransmission', Signal(wl, foreground.skyFilter.transmission))\n        else:\n            target.skyTransmission.data *= foreground.skyFilter.transmission\n        self.set_output(target)\n\n\nclass EstimateForegrounds(Task):\n    \"\"\"\n    It estimate the foreground radiance in the target direction for a specific wl range\n\n    Parameters\n    -----------\n    foregrounds: dict\n        foregrounds description\n    target: Target\n        target class\n    wl_range: (float, float)\n        wavelength range to investigate. (wl_min, wl_max)\n\n    Returns\n    -------\n    Target:\n        updated target class\n    \"\"\"\n\n    def __init__(self):\n        self.addTaskParam('foregrounds', 'foregrounds description')\n        self.addTaskParam('target', 'target class')\n        self.addTaskParam('wl_range', 'wavelength range to investigate')\n\n    def execute(self):\n        self.info('estimating foregrounds')\n        target = self.get_task_param('target')\n        foregrounds = self.get_task_param('foregrounds')\n        wl_min, wl_max = self.get_task_param('wl_range')\n\n        estimateZodi = EstimateZodi()\n        estimateForeground = EstimateForeground()\n\n        if isinstance(foregrounds, OrderedDict):\n            for foreground in foregrounds:\n                if foreground == 'zodiacal':\n                    target = estimateZodi(zodi=foregrounds['zodiacal'],\n                                          target=target,\n                                          wl_range=(wl_min, wl_max))\n                else:\n                    target = estimateForeground(foreground=foregrounds[foreground],\n                                                target=target,\n                                                wl_range=(wl_min, wl_max))\n        else:\n            if foregrounds['value'] == 'zodiacal':\n                target = estimateZodi(zodi=foregrounds,\n                                      target=target,\n                                      wl_range=(wl_min, wl_max))\n            else:\n                target = estimateForeground(foreground=foregrounds,\n                                            target=target,\n                                            wl_range=(wl_min, wl_max))\n        self.set_output(target)\n", "meta": {"hexsha": "cb79c9b7acd92c4a4a9a3d6bd39dbbe226d7c643", "size": 5096, "ext": "py", "lang": "Python", "max_stars_repo_path": "exorad/tasks/foregroundHandler.py", "max_stars_repo_name": "derikk/ExoRad2-public", "max_stars_repo_head_hexsha": "034406bfd8237670f0796f9c95ab2fa5d609bc95", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-14T20:32:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-23T11:41:04.000Z", "max_issues_repo_path": "exorad/tasks/foregroundHandler.py", "max_issues_repo_name": "derikk/ExoRad2-public", "max_issues_repo_head_hexsha": "034406bfd8237670f0796f9c95ab2fa5d609bc95", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exorad/tasks/foregroundHandler.py", "max_forks_repo_name": "derikk/ExoRad2-public", "max_forks_repo_head_hexsha": "034406bfd8237670f0796f9c95ab2fa5d609bc95", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-17T19:55:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-17T19:55:34.000Z", "avg_line_length": 34.2013422819, "max_line_length": 93, "alphanum_fraction": 0.5994897959, "include": true, "reason": "import numpy,import astropy", "num_tokens": 1045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.16738411139407747}}
{"text": "import logging\n\nimport numpy as np \nfrom astropy import units as u \nfrom astropy.table import Table, vstack\nfrom astropy.coordinates import SkyCoord, LSR\nfrom astropy.table.column import (BaseColumn, Column, MaskedColumn, _auto_names, FalseArray,\n                     col_copy, _convert_sequence_data_to_array)\n\nfrom astropy.constants import c as speed_of_light\n\nfrom .uvDataMixin import UVSpectraMixin, UVSpectraRawMixin, CloudyModelMixin\n\nimport os\n\nimport glob\nimport io\nimport pandas as pd\nimport sys\n\nfrom astroquery.simbad import Simbad\n\nimport VoigtFit\nimport pickle\n\nfrom .JBH_IonizationModel import get_input_spectra\n\nfrom VoigtFit.output import rebin_spectrum, rebin_bool_array\n\nfrom matplotlib.widgets import Slider, Button, RadioButtons\nimport matplotlib.pyplot as plt\n\nfrom matplotlib.colors import Normalize\nfrom matplotlib import cm as cmapper\nfrom matplotlib import cm\n\nimport warnings\n\ndirectory = os.path.dirname(__file__)\n\ncite_these = {\n    \"pymccorrelation\":\"https://github.com/privong/pymccorrelation\",\n    \"Kendall's Tau with censoring\": \"https://ui.adsabs.harvard.edu/abs/1986ApJ...306..490I/abstract\",\n    \"pyKrige\":\"DOI:10.5281/zenodo.3991907\",\n    \"sbi_python\":\"DOI:10.21105/joss.02505\",\n    \"Simulation Based Inference Review\":\"https://doi.org/10.1073/pnas.1912789117\"\n}\n\ndef prepare_night_only_data(directory, output_filename = None):\n    \"\"\"\n    Prepares night only data for OI using G130_M COS data\n\n    Parameters\n    ----------\n    directory: `str`\n        directory of data\n    output_filename: `str`, optional, must be keyword\n        name of spectra file to save\n    \"\"\"\n\n    # get source name from directory\n    source_name = directory.split(\"/\")[-1]\n\n\n    # default output file\n    if output_filename == None:\n        output_filename = f\"{source_name}_spec-G130M-N-DK\"\n\n    from scipy.interpolate import interp1d\n\n    from calcos import calcos\n    from costools import timefilter\n\n    from astroquery.mast import Observations\n\n    from astropy.io import fits\n\n    # Download data\n    print(f\"Downloading corrtag data for {source_name} from MAST...\")\n    obs_table = Observations.query_object(source_name, radius = \"2 arcmin\")\n    mask = obs_table[\"obs_collection\"] == \"HST\"\n    mask &= obs_table[\"instrument_name\"] == \"COS/FUV\"\n    mask &= obs_table[\"filters\"] == \"G130M\"\n    target_table = obs_table[mask]\n    product_list = Observations.get_product_list(target_table)\n    corrtag_mask = [\"corrtag\" in entry for entry in product_list[\"dataURI\"]]\n    products = product_list[corrtag_mask]\n    manifest = Observations.download_products(products, download_dir=directory)\n\n    # Get reference files if needed\n    print(\"Checking for reference files...\")\n    os.system(\"crds bestrefs --update-bestrefs --sync-references=1 --files {}/mastDownload/HST/*/*.fits\".format(directory))\n\n    print(\"Filtering and processing night only observations...\")\n    for dataset in glob.glob(f'{directory}/mastDownload/HST/*/*corrtag*.fits'):\n        filepath, filename = os.path.split(dataset)\n        print (\"Filtering \", filename)\n        timefilter.TimelineFilter(input=dataset, filter='SUN_ALT > 0')\n    for dataset in glob.glob(f'{directory}/mastDownload/HST/*/*corrtag_a*.fits'):\n        calcos(dataset, outdir=f'{directory}/nightOnly/')\n\n    def avg_spectra(path):\n        wls = []\n        fluxs = []\n        errs = []\n        for dataset in glob.glob(f'{path}/nightOnly/*x1d.fits'):\n            with fits.open(dataset) as hdu:\n                f = hdu[1].data['flux'].ravel()\n                if not np.all(f == 0.):\n                    w = hdu[1].data['wavelength'].ravel()\n                    wargs = np.argsort(w)\n                    wls.append(w[wargs])\n                    fluxs.append(f[wargs])\n                    errs.append(hdu[1].data['error'].ravel()[wargs])\n                \n        if len(wls) > 1:\n            wl_master = wls[0]\n            fs = [fluxs[0]]\n            es = [errs[0]]\n            \n            for wl, f, e in zip(wls[1:], fluxs[1:], errs[1:]):\n                interper_f = interp1d(wl, f, bounds_error = False)\n                interper_e = interp1d(wl, e, bounds_error = False)\n                fs.append(interper_f(wl_master))\n                es.append(interper_e(wl_master))\n                \n            fs = np.vstack(fs)\n            es = np.vstack(es)\n            \n            f_sum = np.nansum(fs, axis = 0)\n            e_sum = np.nansum(es, axis = 0)\n        elif len(wls) == 1:\n            return wls[0], fluxs[0], errs[0]\n        else:\n            return [0,],[0,],[0,]\n            \n        return wl_master, f_sum, e_sum\n\n    # Averaging all observations\n    print(\"Averaging all observations if needed...\")\n    w,f,e = avg_spectra(directory)\n\n    # write to file\n    print(f\"Saving spectra to file {output_filename}\")\n    np.savetxt(f\"{directory}/{output_filename}\", np.stack([w,f,e]).T)\n\n\n\nclass UVSpectra(UVSpectraMixin, Table):\n    \"\"\"\n    Core UV Spectra class\n\n    Load, view, manipulate, and plot basic results from Bart's analysis files\n\n    Parameters\n    ----------\n\n    directory: `str`, optional \n        Directory where data is stored, \n        organized as one folder per source/direction\n    bart: `bool`, optional, must be keyword\n        if True (default) assumes reading in Bart Wakker's data analysis products\n    query: `bool`, optional must be keyword\n        if True (default) will Simbad query the source names and store their information\n\n    \"\"\"\n\n    def __init__(self, path = None, bart = True, query = True,\n                 source_dirs = None, source_names = None, source_info = None, \n                 LMC_info = None, LMC_coords = None, source_coords = None,\n                 coords_dict = None, abund_files = None, \n                 SMC_info = None, SMC_coords = None,\n                 raw_df = None, \n                 raw_table = None,\n                 voigtfit_files = None,\n                 voigtfit = None,\n                 voigtfit_flags = None,\n                 **kwargs):\n\n        # Read in paths for data\n\n        self.path = path\n        if source_dirs is None:\n            self.source_dirs = glob.glob(os.path.join(path,\"*\"))\n        else:\n            self.source_dirs = source_dirs\n\n        # Get source names:\n        if source_names is None:\n            self.source_names = [path.split(\"/\")[-1] for path in self.source_dirs]\n        else:\n            self.source_names = source_names\n\n        # Query basic info to store\n        if query:\n            if source_info is None:\n                with warnings.catch_warnings():\n                    warnings.simplefilter(\"ignore\")\n                    self.source_info = vstack([Simbad.query_objects([sn]) for sn in self.source_names])\n                self.source_info[\"SOURCE\"] = self.source_names\n            else:\n                self.source_info = source_info\n\n            if LMC_info is None:\n                self.LMC_info = Simbad.query_object(\"LMC\")\n            else:\n                self.LMC_info = LMC_info\n\n            if SMC_info is None:\n                self.SMC_info = Simbad.query_object(\"SMC\")\n            else:\n                self.SMC_info = SMC_info\n        \n\n            # Set SkyCoord objects for sources\n            if LMC_coords is None:\n                self.LMC_coords = SkyCoord(ra = self.LMC_info[\"RA\"], \n                    dec = self.LMC_info[\"DEC\"], \n                    unit = (u.hourangle, u.deg), \n                    frame = \"icrs\")\n            else:\n                self.LMC_coords = LMC_coords\n\n            if SMC_coords is None:\n                self.SMC_coords = SkyCoord(ra = self.SMC_info[\"RA\"], \n                    dec = self.SMC_info[\"DEC\"], \n                    unit = (u.hourangle, u.deg), \n                    frame = \"icrs\")\n            else:\n                self.SMC_coords = SMC_coords\n\n\n            if source_coords is None:\n                self.source_coords = SkyCoord(ra = self.source_info[\"RA\"], \n                    dec = self.source_info[\"DEC\"], \n                    unit = (u.hourangle, u.deg),\n                    frame = \"icrs\")\n            else:\n                self.source_coords = source_coords\n\n            if coords_dict is None:\n                self.coords_dict = {}\n                for key,value in zip(self.source_names,self.source_coords):\n                    self.coords_dict[key] = value\n            else:\n                self.coords_dict = coords_dict\n\n        if abund_files is None:\n            self.abund_files = glob.glob(os.path.join(self.path,\"*/*ABUND.txt\"))\n        else:\n            self.abund_files = abund_files\n\n\n        # Read in abundance measurements\n        names = [\n            \"SOURCE\", \n            \"CLASS_FLAG\", \n            \"NAME\", \n            \"VELOCITY\", \n            \"VMIN\", \n            \"VMAX\", \n            \"MEAN_VEL\", \n            \"VEL_GALDEV\", \n            \"MEASURE_FLAG\",\n            \"N_HI\",\n            \"N_CII\", \n            \"N_OI\", \n            \"N_NI\", \n            \"N_AlII\", \n            \"N_SiII\", \n            \"N_SiIII\", \n            \"N_SII\", \n            \"N_PII\", \n            \"N_FeII\", \n            \"N_OVI\",\n            \"N_CIV\", \n            \"N_NV\", \n            \"N_SiIV\", \n            \"LOG_OVI/CIV\", \n            \"LOG_CIV/NV\", \n            \"LOG_CIV/SiIV\", \n            \"LOG_CIV/II\", \n            \"LOG_SiIII/II\"\n        ]\n\n        def read_abund_file(filename, names = names):\n            stream = os.popen('cat {} | grep \" m \"'.format(filename))\n            output = stream.read()\n            data = io.StringIO(output)\n            return  pd.read_csv(data, delim_whitespace=True, names = names, na_values = \".\")\n\n        \n\n\n        if raw_df is None:\n            frames = [read_abund_file(abund_file) for abund_file in self.abund_files]\n            self.raw_df = pd.concat(frames)\n        else:\n            self.raw_df = raw_df\n        if raw_table is None:\n            self.raw_table = Table.from_pandas(self.raw_df)\n        \n\n\n            # Assign Units and convert data when necessary\n            vel_cols = [\"VELOCITY\", \"VMIN\", \"VMAX\", \"MEAN_VEL\", \"VEL_GALDEV\"]\n            for key in vel_cols:\n                new_col = self.raw_table[key] * u.km/u.s\n\n                self.raw_table[key] = new_col\n\n            N_cols = [\n                \"N_HI\",\n                \"N_CII\", \n                \"N_OI\", \n                \"N_NI\", \n                \"N_AlII\", \n                \"N_SiII\", \n                \"N_SiIII\", \n                \"N_SII\", \n                \"N_PII\", \n                \"N_FeII\", \n                \"N_OVI\",\n                \"N_CIV\", \n                \"N_NV\", \n                \"N_SiIV\", \n            ]\n\n            for species in N_cols:\n                upper_limit_mask = [str(val)[0] == \"<\" for val in self.raw_table[species]]\n                lower_limit_mask = [str(val)[0] == \">\" for val in self.raw_table[species]]\n                new_col = []\n                for val in self.raw_table[species]:\n                    try:\n                        new_col.append(float(str(val).split(\"<\")[-1].split(\">\")[-1]))\n                    except ValueError:\n                        new_col.append(np.nan)\n                new_col = np.array(new_col)\n\n                self.raw_table[species] = 10**new_col * u.cm**-2\n                self.raw_table[\"{}_UPPERLIMIT\".format(species)] = upper_limit_mask\n                self.raw_table[\"{}_LOWERLIMIT\".format(species)] = lower_limit_mask\n\n\n\n            ratio_cols = [\n                \"LOG_OVI/CIV\", \n                \"LOG_CIV/NV\", \n                \"LOG_CIV/SiIV\", \n                \"LOG_CIV/II\", \n                \"LOG_SiIII/II\"\n            ]\n\n            for ratio in ratio_cols:\n                num_species, denom_species = ratio.split(\"/\")\n                num_species = num_species.split(\"_\")[-1]\n                if denom_species == \"II\":\n                    denom_species = \"{}II\".format(num_species.split(\"I\")[0])\n                self.raw_table[ratio] = np.log10(self.raw_table[\"N_{}\".format(num_species)] / self.raw_table[\"N_{}\".format(denom_species)])\n                self.raw_table[\"{}_UPPERLIMIT\".format(ratio)] = self.raw_table[\"N_{}_UPPERLIMIT\".format(num_species)]\n                self.raw_table[\"{}_LOWERLIMIT\".format(ratio)] = self.raw_table[\"N_{}_UPPERLIMIT\".format(denom_species)]\n                self.raw_table[ratio][self.raw_table[\"{}_UPPERLIMIT\".format(ratio)] & self.raw_table[\"{}_LOWERLIMIT\".format(ratio)]] = np.nan\n                self.raw_table[\"{}_UPPERLIMIT\".format(ratio)] |= self.raw_table[\"N_{}_LOWERLIMIT\".format(denom_species)]\n                self.raw_table[\"{}_LOWERLIMIT\".format(ratio)] |= self.raw_table[\"N_{}_LOWERLIMIT\".format(num_species)]\n\n                self.raw_table[ratio].unit = None\n\n        else:\n            self.raw_table = raw_table\n\n\n\n        super().__init__(data = self.raw_table, **kwargs)\n\n        # Add in coordinate information \n        self.SkyCoords = self.get_SkyCoords()\n        self.SkyCoords_gal = self.SkyCoords.transform_to(\"galactic\")\n\n        # Add to table\n        self[\"RA\"] = self.SkyCoords.ra\n        self[\"DEC\"] = self.SkyCoords.dec\n        self[\"GAL-LON\"] = self.SkyCoords_gal.l \n        self[\"GAL-LAT\"] = self.SkyCoords_gal.b \n\n        # Add impact parameters\n        self[\"LMC_ANG_B\"] = self.get_angular_impact_parameter(self.LMC_coords, self.SkyCoords)\n        self[\"LMC_B\"] = self.get_LMC_impact_parameter(self.SkyCoords)\n\n        # Simple Velocity cut flagging\n        self[\"250_PM_30KMS_FLAG\"] = self[\"MEAN_VEL\"] < 280*u.km/u.s\n        self[\"250_PM_30KMS_FLAG\"] &= self[\"MEAN_VEL\"] > 220*u.km/u.s\n\n        # check for voigtfit data\n\n        if voigtfit_files == None:\n            self.voigtfit_files = {\"LOW\":glob.glob(os.path.join(self.path,\"*\",\"*_VoigtFit_DK_vSeparate2_Low.hdf5\")),\n                                   \"HIGH\":glob.glob(os.path.join(self.path,\"*\",\"*_VoigtFit_DK_vSeparate2_High.hdf5\")),\n                                   \"FUSE\":glob.glob(os.path.join(self.path,\"*\",\"*_VoigtFit_DK_FUSE_OVI_v2.hdf5\"))}\n        else:\n            self.voigtfit_files = voigtfit_files\n\n        if voigtfit == None:\n            self.voigtfit = {}\n            if len(self.voigtfit_files[\"LOW\"]) > 0:\n                for fl in self.voigtfit_files[\"LOW\"]:\n                    sn = fl.split(\"/\")[-1].split(\"_Voigt\")[0]\n                    self.voigtfit[sn] = {\"LOW\":UVSpectraRaw(fl, from_dataset = True)}\n                for fh in self.voigtfit_files[\"HIGH\"]:\n                    sn = fh.split(\"/\")[-1].split(\"_Voigt\")[0]\n                    self.voigtfit[sn][\"HIGH\"]=UVSpectraRaw(fh, from_dataset = True)\n                for ff in self.voigtfit_files[\"FUSE\"]:\n                    sn = ff.split(\"/\")[-1].split(\"_Voigt\")[0]\n                    self.voigtfit[sn][\"FUSE\"]=UVSpectraRaw(ff, from_dataset = True)\n\n\n        if voigtfit_flags == None:\n            self.voigtfit_flags = {}\n            if len(self.voigtfit_files[\"LOW\"]) > 0:\n                for f in self.voigtfit_files[\"LOW\"]:\n                    sn = f.split(\"/\")[-1].split(\"_Voigt\")[0]\n                    fn = f.split(\"/\")[:-1]\n                    with open(\"/{}/{}_VoigtFit_Flags_DK_vSeparate2_LowHigh.pkl\".format(os.path.join(*fn), sn), \"rb\") as file:\n                        self.voigtfit_flags[sn] = pickle.load(file)\n\n\n\n\n    def _new_from_slice(self, slice_):\n        \"\"\"Create a new table as a referenced slice from self.\"\"\"\n\n        table = self.__class__(masked=self.masked, \n                               path = self.path,\n                               source_dirs = self.source_dirs, \n                               source_names = self.source_names, \n                               source_info = self.source_info, \n                               LMC_info = self.LMC_info, \n                               LMC_coords = self.LMC_coords, \n                               source_coords = self.source_coords,\n                               coords_dict = self.coords_dict,\n                               abund_files = self.abund_files, \n                               raw_df = self.raw_df, \n                               raw_table = self.raw_table, \n                               SMC_info = self.SMC_info, \n                               SMC_coords = self.SMC_coords, \n                               voigtfit_files = self.voigtfit_files,\n                               voigtfit = self.voigtfit)\n        if self.meta:\n            table.meta = self.meta.copy()  # Shallow copy for slice\n        table.primary_key = self.primary_key\n\n        newcols = []\n        for col in self.columns.values():\n            newcol = col[slice_]\n\n            # Note in line below, use direct attribute access to col.indices for Column\n            # instances instead of the generic col.info.indices.  This saves about 4 usec\n            # per column.\n            if (col if isinstance(col, Column) else col.info).indices:\n                # TODO : as far as I can tell the only purpose of setting _copy_indices\n                # here is to communicate that to the initial test in `slice_indices`.\n                # Why isn't that just sent as an arg to the function?\n                col.info._copy_indices = self._copy_indices\n                newcol = col.info.slice_indices(newcol, slice_, len(col))\n\n                # Don't understand why this is forcing a value on the original column.\n                # Normally col.info does not even have a _copy_indices attribute.  Tests\n                # still pass if this line is deleted.  (Each col.info attribute access\n                # is expensive).\n                col.info._copy_indices = True\n            else:\n                newcol.info.indices = []\n\n            newcols.append(newcol)\n\n        self._make_table_from_cols(table, newcols, verify=False, names=self.columns.keys())\n        return table\n\n    def _cite(self):\n        return cite_these\n\n\n\nclass UVSpectraRaw(UVSpectraRawMixin, object):\n    \"\"\"\n    Raw UV data reader and wrapper to go through voigt fitting process\n\n    Parameters\n    ----------\n    filename: `str`, `list-like`\n        filename of spectra text file with columns of wavelength, flux, error\n        if list, can be multiple filenames of data to load in\n    from_dataset: `bool`, optional, must be keyword\n        if True, loads from existing saved dataset\n    redshift: `number`, optional, must be keyword - defaults to 0\n        redshift\n    name: `str`, optional, must be keyword\n        name to set dataset to, defaults to folder name\n    resolution: `number`, optional, must be keyword\n        spectral resolution in km/s\n    lines: `list-like`, optional, must be keyword\n        list of strings of lines to add to dataset\n    velspan: `number`, optional, must be keyword\n        velocity span for lines, default to 1000\n    rebin_n: `number`, optional, must be keyword\n        number of elements to rebin by\n    rebin_method: `str`, optional, must be keyword\n            rebinning method to use, either \"mean\" or \"median\"\n    \"\"\"\n    \n    def __init__(self, filename,\n                 from_dataset = False, \n                 redshift = None, \n                 name = None, \n                 resolution = None, \n                 lines = None, \n                 velspan = None, \n                 rebin_n = None,\n                 rebin_method = None, \n                 query = True,\n                 filter_regions = True, \n                 auto_resolution = True,\n                 pre_rebin = True, \n                 manual_night_only_error = None, \n                 use_DK_N = True, \n                 shift_night_only_at_OI = None,\n                 shift_g160_at_1526 = None, \n                 fuse_only = False):\n\n        if not from_dataset:\n            if filename.__class__ is str:\n                self.data_files = [filename]\n            else:\n                self.data_files = filename\n\n            self.pre_rebin = pre_rebin\n            \n\n            if resolution == None:\n                self.resolution = 20. # COS\n            else:\n                self.resolution = resolution\n\n            if name == None:\n                self.name = self.data_files[0].split(\"/\")[-2]\n            else:\n                self.name = name\n\n            if lines == None:\n                # set default set of lines\n                self.lines = lines = [\"CII_1334\", \n                         \"CIV_1548\", \"CIV_1550\",\n                         \"SiII_1190\", \"SiII_1193\", \"SiII_1260\", \n                         \"SiIII_1206\", \n                         \"SiIV_1393\", \"SiIV_1402\",]\n                         # \"OI_1302\",\n                         # \"OVI_1031\", \"OVI_1037\",\n                         # \"NV_1238\", \"NV_1242\",\n                         # \"SII_1250\", \"SII_1253\"]#, \"SII_1259\"]\n            else:\n                self.lines = lines\n\n            if velspan == None:\n                self.velspan = 500.\n            else:\n                self.velspan = velspan\n\n            if rebin_n == None:\n                self.rebin_n = 5\n            else:\n                self.rebin_n = rebin_n\n\n            if pre_rebin:\n                self.rebin_n = 1\n\n            if rebin_method == None:\n                self.rebin_method = \"mean\"\n            else:\n                self.rebin_method = rebin_method\n\n            self.auto_resolution = auto_resolution\n\n            customSimbad = Simbad()\n            customSimbad.add_votable_fields(\"rvz_radvel\", \"rvz_type\")\n\n            self.source_info = customSimbad.query_object(self.name)\n\n            self.SkyCoord_at_LMC = SkyCoord(ra = self.source_info[\"RA\"][0], \n                        dec = self.source_info[\"DEC\"][0], \n                        distance = 50*u.kpc,\n                        pm_ra_cosdec = 0*u.mas/u.s,\n                        pm_dec = 0*u.mas/u.s,\n                        radial_velocity = 0*u.km/u.s,\n                        unit = (u.hourangle, u.deg), \n                        frame = \"icrs\")\n\n\n            self.redshift_from_rv =self.SkyCoord_at_LMC.transform_to(LSR()).radial_velocity/speed_of_light\n            self.redshift_from_rv = -1*self.redshift_from_rv.decompose().value\n\n            if redshift == None:\n                self.redshift = self.redshift_from_rv\n            else:\n                self.redshift = redshift\n\n            # open Dataset\n            self.dataset = VoigtFit.DataSet(self.redshift)\n            self.dataset.set_name(self.name)\n\n\n            \n            self.file_suffix = np.array([f.split(\"_spec-\")[-1] for f in self.data_files])\n            if filter_regions:\n            \n                \n\n\n                if use_DK_N:\n\n                    self.filter_dict = {\"G160M\":np.where(self.file_suffix == \"G160M\")[0][0], \n                             \"G130M\":np.where(self.file_suffix == \"G130M\")[0][0], \n                             \"G130M-N-DK\":np.where(self.file_suffix == \"G130M-N-DK\")[0][0]}\n                    try:\n                        self.filter_dict[\"LIF1\"] = np.where(self.file_suffix == \"LIF1\")[0][0]\n                    except IndexError:\n                        pass\n\n                    self.tag_file_pairs = {\"OI_1302\":\"G130M-N-DK\", \n                                      \"OI_1039\":\"LIF1\", \n                                      \"SiII_1304\":\"G130M-N-DK\",\n                                      \"SiIV_1402\":\"G130M\",\n                                      \"SiIV_1393\":\"G130M\",\n                                      \"SiIII_1206\":\"G130M\",\n                                      \"SiII_1260\":\"G130M\",\n                                      \"SiII_1193\":\"G130M\",\n                                      \"SiII_1190\":\"G130M\",\n                                      \"CII_1334\":\"G130M\",\n                                      \"CIIa_1335.7\":\"G130M\",\n                                      \"CIIa_1335.71\":\"G130M\",\n                                      \"FeII_1144\":\"G130M\",\n                                      \"SII_1250\":\"G130M\",\n                                      \"SII_1253\":\"G130M\",\n                                      \"SII_1259\":\"G130M\",\n                                      \"NI_1200.7\":\"G130M\",\n                                      \"NI_1200\":\"G130M\",\n                                      \"NI_1199\":\"G130M\"}\n\n                else:\n\n                    self.filter_dict = {\"G160M\":np.where(self.file_suffix == \"G160M\")[0][0], \n                             \"G130M\":np.where(self.file_suffix == \"G130M\")[0][0], \n                             \"G130M-N\":np.where(self.file_suffix == \"G130M-N\")[0][0]}\n                    try:\n                        self.filter_dict[\"LIF1\"] = np.where(self.file_suffix == \"LIF1\")[0][0]\n                    except IndexError:\n                        pass\n\n                    self.tag_file_pairs = {\"OI_1302\":\"G130M-N\",  \n                                      \"OI_1039\":\"LIF1\", \n                                      \"SiII_1304\":\"G130M-N\",\n                                      \"SiIV_1402\":\"G130M\",\n                                      \"SiIV_1393\":\"G130M\",\n                                      \"SiIII_1206\":\"G130M\",\n                                      \"SiII_1260\":\"G130M\",\n                                      \"SiII_1193\":\"G130M\",\n                                      \"SiII_1190\":\"G130M\",\n                                      \"CII_1334\":\"G130M\",\n                                      \"CIIa_1335.7\":\"G130M\",\n                                      \"CIIa_1335.71\":\"G130M\",\n                                      \"FeII_1144\":\"G130M\",\n                                      \"SII_1250\":\"G130M\",\n                                      \"SII_1253\":\"G130M\",\n                                      \"SII_1259\":\"G130M\",\n                                      \"NI_1200.7\":\"G130M\",\n                                      \"NI_1200\":\"G130M\",\n                                      \"NI_1199\":\"G130M\"}\n\n\n\n            # read in data from text file\n            for suffix,file in zip(self.file_suffix, self.data_files):\n                print(\"Loading data from file, {}\".format(file.split(\"/\")[-1]))\n                if auto_resolution:\n                    if suffix == \"G160M\":\n                        self.resolution = 15.\n                        print(\"Setting G160M resolution to 15 km/s\")\n                    else:\n                        self.resolution = 20.\n                try:\n                    wav, flux, err, _,_, _,_, _,_ = np.loadtxt(file, unpack = True)\n                except ValueError:\n                    wav, flux, err = np.loadtxt(file, unpack = True)\n                mask = flux < 0\n                mask |= np.isnan(flux)\n                mask |= np.isinf(flux)\n                if (suffix == \"G130M-N-DK\") & (manual_night_only_error != None):\n                    err = manual_night_only_error * flux\n                if ((suffix == \"G130M-N\")|(suffix == \"G130M-N-DK\")) & (shift_night_only_at_OI != None):\n                    l0_ref = 1302.1680\n                    l_ref = l0_ref*(self.redshift+1)\n                    wav_shift = shift_night_only_at_OI / speed_of_light.to(u.km/u.s).value * l_ref\n                    wav += wav_shift\n                    print(\"shifting Night Only data by {}\".format(wav_shift))\n                if (suffix == \"G160M\") & (shift_g160_at_1526 != None):\n                    l0_ref = 1526.7066\n                    l_ref = l0_ref*(self.redshift+1)\n                    wav_shift = shift_g160_at_1526 / speed_of_light.to(u.km/u.s).value * l_ref\n                    wav += wav_shift\n                    print(\"shifting G160M data by {}\".format(wav_shift))\n                if pre_rebin:\n                    if suffix == \"G160M\":\n                        rebin_n = 3\n                    else:\n                        rebin_n = 5\n                    wl_r, spec_r, err_r = rebin_spectrum(wav[~mask], flux[~mask], err[~mask], \n                                                         rebin_n, method = self.rebin_method)\n                    self.dataset.add_data(wl_r, spec_r, self.resolution, \n                                      err = err_r, \n                                      normalized = False)\n                else:\n                    self.dataset.add_data(wav[~mask], flux[~mask], self.resolution, \n                                      err = err[~mask], \n                                      normalized = False)\n\n\n            # Add relevent lines to dataset\n            for line in self.lines:\n                print(line)\n                self.dataset.add_line(line, velspan = self.velspan)\n\n\n            if filter_regions:\n                self.filter_regions()\n\n        else:\n\n            self.pre_rebin = pre_rebin\n            #loading from existing dataset\n            self.data_files = [filename]\n\n            if resolution == None:\n                self.resolution = 20.\n            else:\n                self.resolution = resolution\n\n            # load dataset\n            self.dataset = VoigtFit.load_dataset(filename)\n\n            if name == None:\n                self.name = self.dataset.name\n            else:\n                self.name = name\n\n            regions = self.dataset.regions\n            self.lines = []\n            for region in regions:\n                self.lines = np.concatenate([self.lines, [line.tag for line in region.lines]])\n\n            self.velspan = self.dataset.velspan\n\n            if rebin_n == None:\n                self.rebin_n = 5\n            else:\n                self.rebin_n = rebin_n\n\n            if self.pre_rebin:\n                self.rebin_n = 1\n                rebin_n = 1\n\n            if rebin_method == None:\n                self.rebin_method = \"mean\"\n            else:\n                self.rebin_method = rebin_method\n\n            customSimbad = Simbad()\n            # customSimbad.add_votable_fields(\"rvz_radvel\", \"rvz_type\")\n\n            # print(f\"getting Simbad Query for {self.name}\")\n            self.source_info = customSimbad.query_object(self.name)\n\n            self.SkyCoord_at_LMC = SkyCoord(ra = self.source_info[\"RA\"][0], \n                        dec = self.source_info[\"DEC\"][0], \n                        distance = 50*u.kpc,\n                        pm_ra_cosdec = 0*u.mas/u.s,\n                        pm_dec = 0*u.mas/u.s,\n                        radial_velocity = 0*u.km/u.s,\n                        unit = (u.hourangle, u.deg), \n                        frame = \"icrs\")\n\n\n            self.redshift_from_rv =self.SkyCoord_at_LMC.transform_to(LSR()).radial_velocity/speed_of_light\n            self.redshift_from_rv = -1*self.redshift_from_rv.decompose().value\n\n            self.redshift = self.dataset.redshift\n\n\n    def save_dataset(self, filename, in_same_folder = False):\n        if not in_same_folder:\n            self.dataset.save(filename)\n        else:\n            path = os.path.join(\"/\",*self.data_files[0].split(\"/\")[:-1], filename)\n            self.dataset.save(path)\n\n\n\n\nclass CloudyModel(CloudyModelMixin, object):\n    \"\"\"\n    Raw UV data reader and wrapper to go through voigt fitting process\n\n    Parameters\n    ----------\n    source_name: `str`\n        Name of source\n    source_info: `astropy.table.Table`, optional, must be keyword\n        table of source info from Simbad query\n    source_coord: `astropy.coordinates.SkyCoord`, optional, must be keyword\n        Coordinate of source\n        if not provided, will query Simbad to get it\n    distance_grid_command: `list-like`, optional, must be keyword\n        [min,max,step] of distances to grid in Cloudy in log10 space and units of cm\n    hden_grid_command: `list-like`, optional, must be keyword\n        [min,max,step] of distances to grid in Cloudy of hydrogen column density in\n        log10 space and units of cm^-3\n    neutral_column_density_grid: `list-like`, optional, must be keyword\n        log10 neutral column densities grid\n    spectra_template_filename: `str`, optional, must be keyword\n        template tabulated spectrum, defaults to that from Fox et al. 2005 (Figure 8)\n    egb: `str`, optional, must be keyword\n        extragalactic background spectra to use, default to KS18 \n    ebg_redshift: `number`, optional, must be keyword\n        redshift to use for extragalactic background, default to 0\n    metalicity: `number`, optional, must be keyword\n        metalicity to use in log space relative to solar, default to -0.3\n    \"\"\"\n    \n    def __init__(self, source_name, source_coord = None, \n                 source_info = None, \n                 distance_grid_command = None, \n                 neutral_column_density_grid = None, \n                 stop_OI_column = None,\n                 spectra_template_filename = None, \n                 egb = None, \n                 egb_redshift = None, \n                 cosmic_rays_background = True,\n                 species = None,\n                 metalicity_grid_command = None,\n                 hden_grid_command = None,):\n\n        self.source_name = source_name\n\n        if source_info == None:\n            self.source_info = Simbad.query_object(self.source_name)\n\n        if source_coord is None:\n            self.source_coord = SkyCoord(ra = self.source_info[\"RA\"], \n                    dec = self.source_info[\"DEC\"], \n                    unit = (u.hourangle, u.deg), \n                    frame = \"icrs\").transform_to('galactic')\n        else:\n            self.source_coord = source_coord.transform_to('galactic')\n\n        if distance_grid_command == None:\n            self.distance_grid_command = [22.9,23.55,0.05]\n        else:\n            self.distance_grid_command = distance_grid_command\n\n        self.distance_grid = 10**np.arange(*self.distance_grid_command) * u.cm\n        self.distnace_grid = self.distance_grid.to(u.kpc)\n\n\n        self.neutral_column_density_grid = neutral_column_density_grid\n\n        self.stop_OI_column = stop_OI_column\n\n        if spectra_template_filename != None:\n            self.spectra_template_filename = spectra_template_filename\n        else:\n            self.spectra_template_filename = os.path.join(directory,\"data/JBH_RadiationField/Fox+2005_MW.sed\")\n\n\n        if egb == None:\n            self.egb = \"KS18\"\n        else:\n            self.egb = egb\n\n        if egb_redshift == None:\n            self.egb_redshift = 0.\n        else:\n            self.egb_redshift = egb_redshift\n\n        self.cosmic_rays_background = cosmic_rays_background\n\n        if species == None:\n            self.species = [\"H\", \"H+\", \"Si+\", \"Si+2\", \"Si+3\", \"C+\", \"C+3\", \"Fe+\", \"Al+\", \"O\"]\n        else:\n            self.species = species\n\n\n        if metalicity_grid_command == None:\n            self.metalicity_grid_command = [-0.7,-0.1,0.2]\n        else:\n            self.metalicity_grid_command = metalicity\n\n        if hden_grid_command == None:\n            self.hden_grid_command = [-3,0,0.5]\n        else:\n            self.hden_grid_command = hden_grid_command\n\n        self.hden_grid = 10**np.arange(*self.hden_grid_command) * u.cm**-3\n\n        self.input_filename = None\n\n\n        \n\n\n    def get_input_file(self, stop_neutral_column_density = None, distance = None, save = False, \n                        grid_colden = False, grid_metals = True, stop_OI_column = None):\n        \"\"\"\n        Returns string of input file as list for each line of file\n        \"\"\" \n\n        if distance == None:\n            distance = 50*u.kpc\n\n        coord_3d = SkyCoord(l = self.source_coord.l, \n                            b = self.source_coord.b, \n                            distance = distance, \n                            frame = \"galactic\")\n\n        rad, norms = get_input_spectra(coord_3d)\n\n        input_spectra_filename = self.spectra_template_filename.split(\"/\")[-1]\n        #see if file is available in local directory\n        if not len(glob.glob(input_spectra_filename))>0:\n            import shutil\n            shutil.copy(self.spectra_template_filename, \"./\")\n\n        if stop_OI_column == None:\n            stop_OI_column = self.stop_OI_column\n\n\n\n        file_lines = []\n\n\n        file_lines.append(f'title {self.source_name}')\n        file_lines.append('# Input Spectrum File')\n        file_lines.append(f'table SED \"{input_spectra_filename}\"')\n        file_lines.append('# Normalization')\n        file_lines.append(f'phi(H) = {np.log10(norms[\"TOTAL\"].value[0])}')\n        file_lines.append('# Extragalactic Background')\n        file_lines.append(f'Table {self.egb} redshift {self.egb_redshift}')\n        file_lines.append('# hden')\n        file_lines.append('hden -3.0 vary')\n        file_lines.append('grid {} {} {}'.format(*self.hden_grid_command))\n\n        if self.cosmic_rays_background:\n            file_lines.append('cosmic rays background')\n\n        file_lines.append('constant density')\n        file_lines.append('# Metalcity')\n        if grid_metals:\n            file_lines.append('metals -0.3 log vary')\n            file_lines.append('grid {} {} {}'.format(*self.metalicity_grid_command))\n        else:\n            file_lines.append(f'metals {self.metalicity_grid_command} log')\n        file_lines.append('# Stop condition')\n        if stop_OI_column == None:\n            file_lines.append(f'stop neutral column density {stop_neutral_column_density}')\n            stop_val = stop_neutral_column_density\n        else:\n            file_lines.append(f'stop column density \"O\" {stop_OI_column}')\n            stop_val = stop_OI_column\n        \n\n        file_lines.append('double optical depths')\n        file_lines.append('iterate to convergence')\n        file_lines.append('save grid separate \"distance_kpc_{0:.1f}_stop_{1:.2f}_gridrun.grd\"'.format(distance.value, stop_val))\n        file_lines.append('save species column densities last separate \"distance_kpc_{0:.1f}_stop_{1:.2f}_colden.col\" no hash'.format(distance.value, stop_val))\n        for species in self.species:\n            file_lines.append(f'\"{species}\"')\n\n        file_lines.append('end of species')\n        file_lines.append('print last')\n        file_lines.append('plot continuum')\n\n        if save:\n\n            with open('distance_kpc_{0:.1f}_stop_{1:.2f}_input.in'.format(distance.value, stop_val), 'w') as f:\n                for line in file_lines:\n                    print(line, file = f)\n\n            self.input_filename = 'distance_kpc_{0:.1f}_stop_{1:.2f}_input.in'.format(distance.value, stop_val)\n\n        return file_lines\n\n    def print_input_file(self, file_lines):\n        for line in file_lines:\n            print(line)\n\n\n\n\n    def grid_viewer(self, data, meas = None,\n                    figsize = None, \n                    cloudy_results = None,\n                    ions = None, \n                    cmap = None, \n                    vel_range = None,\n                    ):\n        return CloudyGridViewer(cloudy = self, data = data, \n                                figsize = figsize, \n                                cloudy_results = cloudy_results, \n                                ions = ions, \n                                cmap = cmap, \n                                vel_range = vel_range, \n                                meas = meas)\n\n\n\n\n\n\nclass CloudyGridViewer(object):\n    \n    def __init__(self, cloudy = None,\n                       data = None, \n                       figsize = None, \n                       cloudy_results = None, \n                       ions = None,  \n                       cmap = None, \n                 vel_range = None,\n                 meas = None):\n        \"\"\"\n        Interactive plot of cloudy results with slides to control the plotted distances, stop_colN, or METALS\n        \"\"\"\n\n        if ions == None:\n            self.ions = [\"HI\", \"HII\", \"OI\", \"FeII\", \"AlII\", \"SiII\", \"SiIII\", \"SiIV\", \"CII\", \"CIV\"]\n        else:\n            self.ions = ions\n\n        if figsize == None:\n            figsize = (8.5,11)\n\n        if cloudy_results == None:\n            assert cloudy.cloudy_results != None\n            self.cloudy_results = cloudy.cloudy_results\n        else:\n            self.cloudy_results = cloudy_results\n\n        if cmap == None:\n            self.cmap = \"plasma\"\n        else:\n            self.cmap = cmap\n            \n        if vel_range == None:\n            self.vel_min = -200\n            self.vel_max = 600\n        else:\n            self.vel_min = vel_range[0]\n            self.vel_max = vel_range[1]\n            \n        if meas == None:\n            self.meas = cloudy.meas  \n        else:\n            self.meas = meas  \n        self.data = data\n        self.cloudy = cloudy\n\n\n        # set default values\n        self.distance_0 = np.sort(self.cloudy_results[\"DISTANCE\"])[(int(len(self.cloudy_results)/2))]\n        self.stop_coln_0 = np.sort(self.cloudy_results[\"STOP_COLN\"])[(int(len(self.cloudy_results)/2))]\n        self.metals_0 = np.sort(self.cloudy_results[\"METALS\"])[(int(len(self.cloudy_results)/2))]\n\n        self.delta_distance = np.diff(np.unique(self.cloudy_results[\"DISTANCE\"]))[0]\n        self.delta_stop_coln = np.diff(np.unique(self.cloudy_results[\"STOP_COLN\"]))[0]\n        self.delta_metals = np.diff(np.unique(self.cloudy_results[\"METALS\"]))[0]\n\n\n\n        self.fig, self.axs = plt.subplots(5,2, figsize = figsize)\n\n        plt.subplots_adjust(left = 0.25, top = 0.94, bottom = 0.2, right = .94,\n                            hspace = 0.5, wspace = .12)\n\n        \n\n        self.grid_data = {\"DISTANCE\":np.unique(self.cloudy_results[\"DISTANCE\"]),\n                     \"STOP_COLN\":np.unique(self.cloudy_results[\"STOP_COLN\"]),\n                     \"METALS\":np.unique(self.cloudy_results[\"METALS\"])}\n        \n        self.as_cmap = \"DISTANCE\"\n        self.norm = {\"DISTANCE\":Normalize(vmin = np.min(self.grid_data[\"DISTANCE\"])-5., \n                                          vmax = np.max(self.grid_data[\"DISTANCE\"])+5.),\n                \"STOP_COLN\":Normalize(vmin = np.min(self.grid_data[\"STOP_COLN\"])-.5, \n                                          vmax = np.max(self.grid_data[\"STOP_COLN\"])+.5),\n                \"METALS\":Normalize(vmin = np.min(self.grid_data[\"METALS\"])-.2, \n                                          vmax = np.max(self.grid_data[\"METALS\"])+.2)}\n\n        self.sm = cm.ScalarMappable(cmap = self.cmap, norm = self.norm[self.as_cmap])\n\n        self.xlim = (np.min(self.cloudy_results[\"HDEN\"]), np.max(self.cloudy_results[\"HDEN\"]))\n\n        self.max_lines = np.max([len(self.grid_data[\"DISTANCE\"]),\n                            len(self.grid_data[\"STOP_COLN\"]),\n                            len(self.grid_data[\"METALS\"])])\n\n        #initial lines\n        self.lines_list = []\n        for ax,ion in zip(self.axs.flatten(), self.ions):\n            lines = []\n            nlines = 0\n            for val in self.grid_data[self.as_cmap]:\n                nlines +=1\n                color = self.sm.to_rgba(val)\n                mask = self.cloudy_results[self.as_cmap] == val\n                if self.as_cmap == \"DISTANCE\":\n                    mask &= self.cloudy_results[\"STOP_COLN\"] == self.stop_coln_0\n                    mask &= self.cloudy_results[\"METALS\"] == self.metals_0\n                elif self.as_cmap == \"STOP_COLN\":\n                    mask &= self.cloudy_results[\"DISTANCE\"] == self.distance_0\n                    mask &= self.cloudy_results[\"METALS\"] == self.metals_0\n                else:\n                    mask &= self.cloudy_results[\"DISTANCE\"] == self.distance_0\n                    mask &= self.cloudy_results[\"STOP_COLN\"] == self.stop_coln_0\n\n                yy = np.ma.masked_array(data = self.cloudy_results[f\"N_{ion}\"][mask].value, \n                                        mask = self.cloudy_results[f\"N_{ion}\"][mask].value <= 0.)\n                yy = np.ma.log10(yy)\n                l, = ax.plot(self.cloudy_results[\"HDEN\"][mask], \n                                yy, \n                                color = self.sm.to_rgba(val), lw = 2, alpha = 0.8,\n                             label = val)\n                ax.set_xlim(self.xlim)\n                ax.set_title(ion, fontsize = 12)\n                lines.append(l)\n\n            while nlines < self.max_lines:\n                l, = ax.plot(self.cloudy_results[\"HDEN\"][mask], yy, lw = 2, alpha = 0.0)\n                lines.append(l)\n                nlines+=1\n\n            self.lines_list.append(lines)\n        \n        handles, labels = self.axs.flatten()[0].get_legend_handles_labels()\n        self.lg = self.fig.legend(handles, labels, loc='upper center', ncol = 8)\n        \n        self.title = self.fig.suptitle(self.cloudy.source_name, x = 0.1, y = 0.83, fontweight = \"bold\")\n        \n        self.axs[-1][0].set_xlabel(r\"$\\log_{10}(n_H)$\", fontsize = 12)\n        self.axs[-1][1].set_xlabel(r\"$\\log_{10}(n_H)$\", fontsize = 12)\n        for ax in self.axs[:,0]:\n            ax.set_ylabel(r\"$\\log_{10}(N)$\", fontsize = 12)\n        for ax in self.axs[:,1]:\n            ax.yaxis.tick_right()\n\n        def plot_result(as_cmap, distance = self.distance_0, stop_coln = self.stop_coln_0, metals = self.metals_0):\n            for lines,ion in zip(self.lines_list, self.ions):\n\n                for val,l in zip(self.grid_data[self.as_cmap],lines[:len(self.grid_data[self.as_cmap])]):\n                    color = self.sm.to_rgba(val)\n                    mask = self.cloudy_results[self.as_cmap] == val\n                    if as_cmap == \"DISTANCE\":\n                        mask &= self.cloudy_results[\"STOP_COLN\"] < stop_coln + self.delta_stop_coln/2\n                        mask &= self.cloudy_results[\"STOP_COLN\"] > stop_coln - self.delta_stop_coln/2\n                        mask &= self.cloudy_results[\"METALS\"] < metals + self.delta_metals/2\n                        mask &= self.cloudy_results[\"METALS\"] > metals - self.delta_metals/2\n                    elif as_cmap == \"STOP_COLN\":\n                        mask &= self.cloudy_results[\"DISTANCE\"] < distance + self.delta_distance/2\n                        mask &= self.cloudy_results[\"DISTANCE\"] > distance - self.delta_distance/2\n                        mask &= self.cloudy_results[\"METALS\"] < metals + self.delta_metals/2\n                        mask &= self.cloudy_results[\"METALS\"] > metals - self.delta_metals/2\n                    else:\n                        mask &= self.cloudy_results[\"DISTANCE\"] < distance + self.delta_distance/2\n                        mask &= self.cloudy_results[\"DISTANCE\"] > distance - self.delta_distance/2\n                        mask &= self.cloudy_results[\"STOP_COLN\"] < stop_coln + self.delta_stop_coln/2\n                        mask &= self.cloudy_results[\"STOP_COLN\"] > stop_coln - self.delta_stop_coln/2\n\n                    yy = np.ma.masked_array(data = self.cloudy_results[f\"N_{ion}\"][mask].value, \n                                        mask = self.cloudy_results[f\"N_{ion}\"][mask].value <= 0.)\n                    yy = np.ma.log10(yy)\n                    self.yy = yy\n                    l.set_ydata(yy)\n                    l.set_alpha(0.8)\n                    l.set_color(color)\n                    l.set_label(val)\n\n                for l in lines[len(self.grid_data[self.as_cmap]):]:\n                    l.set_alpha(0.0)\n                    l.set_label(None)\n                    \n                    \n            for ax in self.axs.flatten():\n                ax.relim()\n                ax.autoscale_view()\n                ax.set_xlim(self.xlim)\n            self.lg.remove()\n            handles, labels = self.axs.flatten()[0].get_legend_handles_labels()\n            self.lg = self.fig.legend(handles, labels, loc='upper center', ncol = 8)\n\n\n        self.axcolor = 'lightgoldenrodyellow'\n        self.axdist = plt.axes([0.02, 0.2, 0.02, 0.57], facecolor=self.axcolor)\n        self.axcoln = plt.axes([0.08, 0.2, 0.02, 0.57], facecolor=self.axcolor)\n        self.axmetal = plt.axes([0.14, 0.2, 0.02, 0.57], facecolor=self.axcolor)\n\n        self.sdist = Slider(self.axdist, 'D', \n                       np.min(self.grid_data[\"DISTANCE\"]), \n                       np.max(self.grid_data[\"DISTANCE\"]), \n                       valinit=self.distance_0, \n                       valstep=self.delta_distance, \n                       orientation = \"vertical\")\n\n        self.smetal = Slider(self.axmetal, 'Z', \n                       np.min(self.grid_data[\"METALS\"]), \n                       np.max(self.grid_data[\"METALS\"]), \n                       valinit=self.metals_0, \n                       valstep=self.delta_metals, \n                       orientation = \"vertical\")\n\n        self.scoln = Slider(self.axcoln, 'N', \n                       np.min(self.grid_data[\"STOP_COLN\"]), \n                       np.max(self.grid_data[\"STOP_COLN\"]), \n                       valinit=self.stop_coln_0, \n                       valstep=self.delta_stop_coln, \n                       orientation = \"vertical\")\n\n        self.rax = plt.axes([0.015, 0.85, 0.14, 0.1], facecolor=self.axcolor)\n        self.radio = RadioButtons(self.rax, ('DISTANCE', 'STOP_COLN', 'METALS'), active=0)\n\n        \n        \n        self.axvw = plt.axes([.18, .02, .02, .13], facecolor = self.axcolor)\n        self.svw = Slider(self.axvw, r\"$\\Delta v$\", \n                          5., 40., valinit = 15., orientation = \"vertical\", valstep = 0.25)\n        \n        self.rabs_ax = plt.axes([0.02,0.02, .15, .13], facecolor = self.axcolor)\n        self.radio_abs = RadioButtons(self.rabs_ax, (r\"OI $\\lambda$1302\", \n                                                     r\"AlII $\\lambda$1670\",\n                                                     r\"SiII $\\lambda$1190\", \n                                                     r\"SiIII $\\lambda$1206\",\n                                                     r\"SiIV $\\lambda$1393\",\n                                                     r\"CIV $\\lambda$1548\"), active = 0)\n        \n        self.axvcen = plt.axes([.25, .01, .69, .015], facecolor = self.axcolor)\n        self.svcen = Slider(self.axvcen, r\"$v$\",\n                            self.vel_min, self.vel_max, valinit = 250., valstep = 1.)\n        \n        self.axabs = plt.axes([.25, .05, .69, .1])\n        self.axabs.set_xlim(self.vel_min,self.vel_max)\n        self.axabs.yaxis.set_label_position(\"right\")\n        \n        #init spectra\n        self.line_to_tag = {r\"OI $\\lambda$1302\":\"OI_1302\", \n                            r\"AlII $\\lambda$1670\":\"AlII_1670\",\n                            r\"SiII $\\lambda$1190\":\"SiII_1190\",\n                            r\"SiIII $\\lambda$1206\":\"SiIII_1206\",\n                            r\"SiIV $\\lambda$1393\":\"SiIV_1393\",\n                            r\"CIV $\\lambda$1548\":\"CIV_1548\"}\n                \n        \n        def plot_spec(line_label = self.radio_abs.value_selected):\n            # Find the right region\n            self.axabs.clear()\n            line_label = self.radio_abs.value_selected\n            for ell,region in enumerate(self.data.voigtfit[self.cloudy.source_name][\"LOW\"].dataset.regions):\n                for sub_ind,line in enumerate(region.lines):\n                    if self.line_to_tag[line_label] == line.tag:\n                        self.data.voigtfit[self.cloudy.source_name][\"LOW\"].plot_region_fit(ell, \n                                                                                    sub_region_ind = sub_ind, \n                                                                                    vel_range = [self.vel_min, \n                                                                                                 self.vel_max],\n                                                                                    ax = self.axabs, \n                                                                                    labelx = False, \n                                                                                    labely = False, \n                                                                                    lw = 1, \n                                                                                    alpha = 0.8, \n                                                                                    fit_kwargs = {\"lw\":1, \n                                                                                                  \"alpha\":0.8},\n                                                                                    comp_kwargs = {\"lw\":2},\n                                                                                    comp_scale = 0.2, \n                                                                                    plot_indiv_comps = True,\n                                                                                           ylabel_as_ion = True)\n            for ell,region in enumerate(self.data.voigtfit[self.cloudy.source_name][\"HIGH\"].dataset.regions):\n                for sub_ind,line in enumerate(region.lines):\n                    if self.line_to_tag[line_label] == line.tag:\n                        self.data.voigtfit[self.cloudy.source_name][\"HIGH\"].plot_region_fit(ell, \n                                                                                    sub_region_ind = sub_ind, \n                                                                                    vel_range = [self.vel_min, \n                                                                                                 self.vel_max],\n                                                                                    ax = self.axabs, \n                                                                                    labelx = False, \n                                                                                    labely = False, \n                                                                                    lw = 1, \n                                                                                    alpha = 0.8, \n                                                                                    fit_kwargs = {\"lw\":1, \n                                                                                                  \"alpha\":0.8},\n                                                                                    comp_kwargs = {\"lw\":2},\n                                                                                    comp_scale = 0.3, \n                                                                                    plot_indiv_comps = True, \n                                                                                            ylabel_as_ion = True)\n                        \n            self.axabs.set_ylabel(\"Normalized\\nFlux\", fontsize = 12)\n            # add vel markers\n            ylim = self.axabs.get_ylim()\n            self.axabs.plot([self.svcen.val, self.svcen.val], ylim, color = \"k\", ls = \":\", \n                            lw = 2, alpha = 0.5, zorder = -1)\n            self.axabs.fill_between([self.svcen.val - self.svw.val, self.svcen.val + self.svw.val], \n                                    [ylim[0], ylim[0]], \n                                    [ylim[1], ylim[1]], color = \"k\", alpha = 0.04, zorder = -1)\n            \n        \n                        \n        plot_spec(self.radio_abs.value_selected)\n        \n        \n        \n        #init lines\n        self.meas_lines = []\n        for ion,ax in zip(self.ions, self.axs.flatten()):\n            l0, = ax.plot(self.xlim,[12,12],lw = 2, color = \"k\", ls = \"--\", alpha = 0., zorder = -1)\n            \n            l1, = ax.plot(self.xlim,[12,12],lw = 2, color = \"k\", ls = \":\", alpha = 0., zorder = -1)\n            \n            l2, = ax.plot(self.xlim,[12,12],lw = 2, color = \"k\", ls = \":\", alpha = 0., zorder = -1)\n            \n            self.meas_lines.append([l0,l1,l2])\n        \n        def add_obs_lines():\n            for ion,lines in zip(self.ions, self.meas_lines):\n                #check for matching component\n                vel_mask = self.meas[\"V\"].value <= (self.svcen.val + self.svw.val)\n                vel_mask &= self.meas[\"V\"].value >= (self.svcen.val - self.svw.val)\n                ion_mask = [comp.split(\"_\")[-1] == ion for comp in self.meas[\"COMP\"]]\n                mask = vel_mask & ion_mask\n                if np.sum(mask)>0:\n                    res_N = np.log10(self.meas[\"N\"].value)[mask]\n                    res_err_N = np.log10(self.meas[\"ERR_N\"].value)[mask]\n\n                    res_v = self.meas[\"V\"].value[mask]\n\n                    # check for multiple\n                    if len(res_v) > 1:\n                        use_ind = np.argmin(np.abs(res_v - self.svcen.val))\n                        res_v = res_v[use_ind]\n                        res_N = res_N[use_ind]\n                        res_err_N = res_err_N[use_ind]\n                    if np.isinf(res_err_N):\n                        res_err_N = 0.\n                    \n                    lines[0].set_ydata([res_N, res_N])\n                    lines[1].set_ydata([res_N-res_err_N, res_N-res_err_N])\n                    lines[2].set_ydata([res_N+res_err_N, res_N+res_err_N])\n                    \n                    lines[0].set_alpha(0.7)\n                    lines[1].set_alpha(0.7)\n                    lines[2].set_alpha(0.7)\n                else:\n                    lines[0].set_alpha(0.)\n                    lines[1].set_alpha(0.)\n                    lines[2].set_alpha(0.)\n                    \n        def update_cmap_parameter(label):\n            self.as_cmap = label\n            self.sm = cm.ScalarMappable(cmap = self.cmap, norm = self.norm[self.as_cmap])\n            plot_result(self.as_cmap, distance = self.sdist.val, stop_coln = self.scoln.val, metals = self.smetal.val)\n            add_obs_lines()\n            plot_spec()\n            self.fig.canvas.draw_idle()\n        self.radio.on_clicked(update_cmap_parameter)\n\n        def update(val):\n            plot_result(self.as_cmap, distance = self.sdist.val, stop_coln = self.scoln.val, metals = self.smetal.val)\n            add_obs_lines()\n            plot_spec()\n            self.fig.canvas.draw_idle()\n        self.sdist.on_changed(update)\n        self.smetal.on_changed(update)\n        self.scoln.on_changed(update)\n        \n        self.radio_abs.on_clicked(update)\n        self.svw.on_changed(update)\n        self.svcen.on_changed(update)\n                \n    \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "fbe057c4a539f568987b7264b0ffa110552303d2", "size": 57637, "ext": "py", "lang": "Python", "max_stars_repo_path": "dk_hst_tools/UVSpectra.py", "max_stars_repo_name": "Deech08/DK_HST_Tools", "max_stars_repo_head_hexsha": "0c38ac72171c6610fbba7b6f7a135dac309fe91a", "max_stars_repo_licenses": ["BSD-3-Clause-Clear", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dk_hst_tools/UVSpectra.py", "max_issues_repo_name": "Deech08/DK_HST_Tools", "max_issues_repo_head_hexsha": "0c38ac72171c6610fbba7b6f7a135dac309fe91a", "max_issues_repo_licenses": ["BSD-3-Clause-Clear", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dk_hst_tools/UVSpectra.py", "max_forks_repo_name": "Deech08/DK_HST_Tools", "max_forks_repo_head_hexsha": "0c38ac72171c6610fbba7b6f7a135dac309fe91a", "max_forks_repo_licenses": ["BSD-3-Clause-Clear", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.993598862, "max_line_length": 160, "alphanum_fraction": 0.49230529, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 12897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.16738410667817558}}
{"text": "import os\nimport sys\nfrom functools import lru_cache, wraps\n\nimport astropy.units as astropy_units\nimport numpy as np\nimport six\nfrom astropy.io import fits\n\nfrom astromodels.functions.function import Function1D, FunctionMeta\nfrom astromodels.utils import configuration\nfrom astromodels.utils.data_files import _get_data_file_path\n\n\ndef cache_array_method(*args, **kwargs):\n    \"\"\"\n    LRU cache implementation for methods whose FIRST parameter is a numpy array\n    modified from: https://gist.github.com/Susensio/61f4fee01150caaac1e10fc5f005eb75\n    \"\"\"\n\n    def decorator(function):\n        @wraps(function)\n        def wrapper(s, np_array, *args, **kwargs):\n            hashable_array = tuple(np_array)\n            return cached_wrapper(s, hashable_array, *args, **kwargs)\n\n        @lru_cache(*args, **kwargs)\n        def cached_wrapper(s, hashable_array, *args, **kwargs):\n            array = np.array(hashable_array)\n            return function(s, array, *args, **kwargs)\n\n        # copy lru_cache attributes over too\n        wrapper.cache_info = cached_wrapper.cache_info\n        wrapper.cache_clear = cached_wrapper.cache_clear\n        return wrapper\n\n    return decorator\n\n\ntry:\n\n    import pyatomdb\n\n    has_atomdb = True\n\nexcept:\n\n    has_atomdb = False\n\n\nif has_atomdb:\n    # APEC class\n    @six.add_metaclass(FunctionMeta)\n    class APEC(Function1D):\n        r\"\"\"\n        description :\n            The Astrophysical Plasma Emission Code (APEC, Smith et al. 2001)\n            contributed by Dominique Eckert\n        parameters :\n            K :\n                desc : Normalization in units of 1e-14/(4*pi*(1+z)^2*dA*2)*EM\n                initial value : 1.0\n                is_normalization : True\n                transformation : log10\n                min : 1e-30\n                max : 1e3\n                delta : 0.1\n            kT :\n                desc : Plasma temperature\n                initial value : 1.0\n                min : 0.08\n                max : 64\n                delta : 0.1\n            abund :\n                desc : Metal abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            redshift :\n                desc : Source redshift\n                initial value : 0.1\n                min : 0.0\n                max : 10.0\n                delta : 1e-3\n                fix : yes\n\n        \"\"\"\n\n        def _set_units(self, x_unit, y_unit):\n            self.kT.unit = astropy_units.keV\n\n            self.abund.unit = astropy_units.dimensionless_unscaled\n\n            self.redshift.unit = astropy_units.dimensionless_unscaled\n\n            self.K.unit = y_unit\n\n        def init_session(self, abund_table=\"AG89\"):\n            # initialize PyAtomDB session\n            self.session = pyatomdb.spectrum.CIESession(abundset=abund_table)\n\n        def evaluate(self, x, K, kT, abund, redshift):\n            assert self.session is not None, \"please run init_session(abund)\"\n\n            sess = self.session\n\n            nval = len(x)\n\n            xz = x * (1.0 + redshift)\n\n            ebplus = (np.roll(xz, -1) + xz)[: nval - 1] / 2.0\n\n            ebounds = np.empty(nval + 1)\n\n            ebounds[1:nval] = ebplus\n\n            ebounds[0] = xz[0] - (ebplus[0] - xz[0])\n\n            ebounds[nval] = xz[nval - 1] + (xz[nval - 1] - ebplus[nval - 2])\n\n            binsize = (np.roll(ebounds, -1) - ebounds)[:nval]\n\n            sess.set_response(ebounds, raw=True)\n\n            sess.set_abund(\n                [\n                    6,\n                    7,\n                    8,\n                    9,\n                    10,\n                    11,\n                    12,\n                    13,\n                    14,\n                    16,\n                    17,\n                    18,\n                    19,\n                    20,\n                    21,\n                    22,\n                    23,\n                    24,\n                    25,\n                    26,\n                    27,\n                    28,\n                    29,\n                    30,\n                ],\n                abund,\n            )\n\n            spec = sess.return_spectrum(kT) / binsize / 1e-14\n\n            return K * spec\n\n    # VAPEC class\n    @six.add_metaclass(FunctionMeta)\n    class VAPEC(Function1D):\n        r\"\"\"\n        description :\n            The Astrophysical Plasma Emission Code (APEC, Smith et al. 2001), variable abundances for individual elements\n            contributed by Dominique Eckert\n        parameters :\n            K :\n                desc : Normalization in units of 1e-14/(4*pi*(1+z)^2*dA*2)*EM\n                initial value : 1.0\n                is_normalization : True\n                transformation : log10\n                min : 1e-30\n                max : 1e3\n                delta : 0.1\n            kT :\n                desc : Plasma temperature\n                initial value : 1.0\n                min : 0.08\n                max : 64\n                delta : 0.1\n            Fe :\n                desc : Fe abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            C :\n                desc : C abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            N :\n                desc : N abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            O :\n                desc : O abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            Ne :\n                desc : Ne abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            Mg :\n                desc : Mg abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            Al :\n                desc : Al abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            Si :\n                desc : Si abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            S :\n                desc : S abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            Ar :\n                desc : Ar abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            Ca :\n                desc : Ca abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            Ni :\n                desc : Ni abundance\n                initial value : 1\n                min : 0.0\n                max : 5.0\n                delta : 0.01\n                fix : yes\n            redshift :\n                desc : Source redshift\n                initial value : 0.1\n                min : 0.0\n                max : 10.0\n                delta : 1e-3\n                fix : yes\n\n        \"\"\"\n\n        def _set_units(self, x_unit, y_unit):\n            self.kT.unit = astropy_units.keV\n\n            self.Fe.unit = astropy_units.dimensionless_unscaled\n\n            self.C.unit = astropy_units.dimensionless_unscaled\n\n            self.N.unit = astropy_units.dimensionless_unscaled\n\n            self.O.unit = astropy_units.dimensionless_unscaled\n\n            self.Ne.unit = astropy_units.dimensionless_unscaled\n\n            self.Mg.unit = astropy_units.dimensionless_unscaled\n\n            self.Al.unit = astropy_units.dimensionless_unscaled\n\n            self.Si.unit = astropy_units.dimensionless_unscaled\n\n            self.Ar.unit = astropy_units.dimensionless_unscaled\n\n            self.Ca.unit = astropy_units.dimensionless_unscaled\n\n            self.Ni.unit = astropy_units.dimensionless_unscaled\n\n            self.redshift.unit = astropy_units.dimensionless_unscaled\n\n            self.K.unit = y_unit\n\n        def init_session(self, abund_table=\"AG89\"):\n            # initialize PyAtomDB session\n            self.session = pyatomdb.spectrum.CIESession(abundset=abund_table)\n\n        def evaluate(\n            self, x, K, kT, Fe, C, N, O, Ne, Mg, Al, Si, S, Ar, Ca, Ni, redshift\n        ):\n            assert self.session is not None, \"please run init_session(abund)\"\n\n            sess = self.session\n\n            nval = len(x)\n\n            xz = x * (1.0 + redshift)\n\n            ebplus = (np.roll(xz, -1) + xz)[: nval - 1] / 2.0\n\n            ebounds = np.empty(nval + 1)\n\n            ebounds[1:nval] = ebplus\n\n            ebounds[0] = xz[0] - (ebplus[0] - xz[0])\n\n            ebounds[nval] = xz[nval - 1] + (xz[nval - 1] - ebplus[nval - 2])\n\n            binsize = (np.roll(ebounds, -1) - ebounds)[:nval]\n\n            sess.set_response(ebounds, raw=True)\n\n            sess.set_abund(\n                [6, ], C,\n            )\n\n            sess.set_abund(\n                [7, ], N,\n            )\n\n            sess.set_abund(\n                [8, ], O,\n            )\n\n            sess.set_abund(\n                [10, ], Ne,\n            )\n\n            sess.set_abund(\n                [12, ], Mg,\n            )\n\n            sess.set_abund(\n                [13, ], Al,\n            )\n\n            sess.set_abund(\n                [14, ], Si,\n            )\n\n            sess.set_abund(\n                [16, ], S,\n            )\n\n            sess.set_abund(\n                [18, ], Ar,\n            )\n\n            sess.set_abund(\n                [20, ], Ca,\n            )\n\n            sess.set_abund(\n                [26, ], Fe,\n            )\n\n            sess.set_abund(\n                [28, ], Ni,\n            )\n\n            sess.set_abund(\n                [9, 11, 15, 17, 19, 21, 22, 23, 24, 25, 27, 29, 30], Fe\n            )  # Remaining elements are set to Fe\n\n            spec = sess.return_spectrum(kT) / binsize / 1e-14\n\n            return K * spec\n\n\n_abs_tables = {\n    \"phabs\": {\"AG89\": \"angr\", \"ASPL\": \"aspl\"},\n    \"tbabs\": {\"AG89\": \"angr\", \"ASPL\": \"aspl\", \"WILM\": \"wilm\"},\n    \"wabs\": {\"AG89\": \"angr\"},\n}\n_abund_info = {}\n_abund_info[\n    \"WILM\"\n] = \"wilms\\nfrom Wilms, Allen & McCray (2000), ApJ 542, 914 \\n except for elements not listed which are given zero abundance)\\n https://heasarc.nasa.gov/xanadu/xspec/manual/XSabund.html \"\n_abund_info[\n    \"AG89\"\n] = \"angr\\nfrom Anders E. & Grevesse N. (1989, Geochimica et Cosmochimica Acta 53, 197)\\n https://heasarc.nasa.gov/xanadu/xspec/manual/XSabund.html\"\n_abund_info[\n    \"ASPL\"\n] = \"aspl\\nfrom Asplund M., Grevesse N., Sauval A.J. & Scott P. (2009, ARAA, 47, 481)\\nhttps://heasarc.nasa.gov/xanadu/xspec/manual/XSabund.html\"\n\n\ndef _get_xsect_table(model, abund_table):\n    \"\"\"\n    contructs the abundance table from the values given\n    \"\"\"\n\n    assert model in _abs_tables, \"the model %s does not exist\" % model\n    assert abund_table in _abs_tables[model], (\n        \"the table %s does not exist\" % abund_table\n    )\n\n    path_to_xsect = _get_data_file_path(\n        os.path.join(\n            \"xsect\", \"xsect_%s_%s.fits\" % (\n                model, _abs_tables[model][abund_table])\n        )\n    )\n\n    fxs = fits.open(path_to_xsect)\n    dxs = fxs[1].data\n    xsect_ene = dxs[\"ENERGY\"]\n    xsect_val = dxs[\"SIGMA\"]\n\n    return np.array(xsect_ene), np.array(xsect_val)\n\n# PhAbs class\n\n\n@six.add_metaclass(FunctionMeta)\nclass PhAbs(Function1D):\n    r\"\"\"\n    description :\n        Photometric absorption (phabs implementation), f(E) = exp(- NH * sigma(E))\n        contributed by Dominique Eckert\n    parameters :\n        NH :\n            desc : absorbing column density in units of 1e22 particles per cm^2\n            initial value : 1.0\n            is_normalization : False\n            transformation : log10\n            min : 1e-4\n            max : 1e4\n            delta : 0.1\n\n        redshift :\n            desc : the redshift of the source\n            initial value : 0.\n            is_normalization : False\n            min : 0\n            max : 15\n            delta : 0.1\n            fix: True\n\n\n    \"\"\"\n\n    def _setup(self):\n        self._fixed_units = (\n            astropy_units.keV, astropy_units.dimensionless_unscaled)\n        self.init_xsect()\n\n    def _set_units(self, x_unit, y_unit):\n        self.NH.unit = astropy_units.cm ** (-2)\n        self.redshift.unit = astropy_units.dimensionless_unscaled\n\n    def init_xsect(self, abund_table=\"AG89\"):\n        \"\"\"\n        Set the abundance table\n\n        :param abund_table: \"ASPL\", \"AG89\" \n        :returns: \n        :rtype: \n\n        \"\"\"\n\n        # load cross section data\n\n        try:\n            self.xsect_ene, self.xsect_val = _get_xsect_table(\n                \"phabs\", abund_table)\n            self._abund_table = abund_table\n\n        except:\n\n            print(\"defaulting to AG89\")\n            self.xsect_ene, self.xsect_val = _get_xsect_table(\n                \"phabs\", abund_table)\n\n            self._abund_table = \"AG89\"\n\n    @cache_array_method()\n    def _cached_interp(self, x):\n\n        return np.interp(x, self.xsect_ene, self.xsect_val)\n\n    def evaluate(self, x, NH, redshift):\n\n        if isinstance(x, astropy_units.Quantity):\n\n            _unit = astropy_units.cm ** 2\n            _y_unit = astropy_units.dimensionless_unscaled\n            _x = x.value\n\n        else:\n\n            _unit = 1.0\n            _y_unit = 1.0\n\n            _x = x\n\n        xsect_interp = self._cached_interp(_x * (1 + redshift))\n\n        spec = np.exp(-NH * xsect_interp * _unit) * _y_unit\n\n        return spec\n\n# TbAbs class\n\n\n@six.add_metaclass(FunctionMeta)\nclass TbAbs(Function1D):\n    r\"\"\"\n    description :\n        Photometric absorption (Tbabs implementation), f(E) = exp(- NH * sigma(E))\n        contributed by Dominique Eckert\n    parameters :\n        NH :\n            desc : absorbing column density in units of 1e22 particles per cm^2\n            initial value : 1.0\n            is_normalization : True\n            transformation : log10\n            min : 1e-4\n            max : 1e4\n            delta : 0.1\n\n        redshift :\n            desc : the redshift of the source\n            initial value : 0.\n            is_normalization : False\n            min : 0\n            max : 15\n            delta : 0.1\n            fix: True\n\n\n    \"\"\"\n\n    def _setup(self):\n\n        self.init_xsect()\n\n        self._fixed_units = (\n            astropy_units.keV, astropy_units.dimensionless_unscaled)\n\n    def _set_units(self, x_unit, y_unit):\n        self.NH.unit = astropy_units.cm ** (-2)\n        self.redshift.unit = astropy_units.dimensionless_unscaled\n\n    def init_xsect(self, abund_table=\"WILM\"):\n        \"\"\"\n        Set the abundance table\n\n        :param abund_table: \"WILM\", \"ASPL\", \"AG89\" \n        :returns: \n        :rtype: \n\n        \"\"\"\n\n        try:\n            self.xsect_ene, self.xsect_val = _get_xsect_table(\n                \"tbabs\", abund_table)\n            self._abund_table = abund_table\n\n        except:\n\n            print(\"defaulting to WILM\")\n            self.xsect_ene, self.xsect_val = _get_xsect_table(\n                \"tbabs\", abund_table)\n\n            self._abund_table = \"WILM\"\n\n    @property\n    def abundance_table(self):\n        print(_abund_info[self._abund_table])\n\n    @cache_array_method()\n    def _cached_interp(self, x):\n\n        return np.interp(x, self.xsect_ene, self.xsect_val)\n\n    def evaluate(self, x, NH, redshift):\n\n        if isinstance(x, astropy_units.Quantity):\n\n            _unit = astropy_units.cm ** 2\n            _y_unit = astropy_units.dimensionless_unscaled\n            _x = x.value\n\n        else:\n\n            _unit = 1.0\n            _y_unit = 1.0\n\n            _x = x\n\n        xsect_interp = self._cached_interp(_x * (1 + redshift))\n\n        spec = np.exp(-NH * xsect_interp * _unit) * _y_unit\n\n        return spec\n\n# WAbs class\n\n\n@six.add_metaclass(FunctionMeta)\nclass WAbs(Function1D):\n    r\"\"\"\n    description :\n        Photometric absorption (Wabs implementation), f(E) = exp(- NH * sigma(E))\n        contributed by Dominique Eckert\n    parameters :\n        NH :\n            desc : absorbing column density in units of 1e22 particles per cm^2\n            initial value : 1.0\n            is_normalization : True\n            transformation : log10\n            min : 1e-4\n            max : 1e4\n            delta : 0.1\n        redshift :\n            desc : the redshift of the source\n            initial value : 0.\n            is_normalization : False\n            min : 0\n            max : 15\n            delta : 0.1\n            fix: True\n\n\n    \"\"\"\n\n    def _setup(self):\n        self._fixed_units = (\n            astropy_units.keV, astropy_units.dimensionless_unscaled)\n        self.init_xsect()\n\n    def _set_units(self, x_unit, y_unit):\n        self.NH.unit = astropy_units.cm ** (-2)\n        self.redshift.unit = astropy_units.dimensionless_unscaled\n\n    def init_xsect(self):\n        \"\"\"\n        Set the abundance table\n\n        :returns:\n        :rtype:\n\n        \"\"\"\n\n        self.xsect_ene, self.xsect_val = _get_xsect_table(\"wabs\", \"AG89\")\n\n        self._abund_table = \"AG89\"\n\n    @property\n    def abundance_table(self):\n        print(_abund_info[self._abund_table])\n\n    @cache_array_method()\n    def _cached_interp(self, x):\n\n        return np.interp(x, self.xsect_ene, self.xsect_val)\n\n    def evaluate(self, x, NH, redshift):\n\n        if isinstance(x, astropy_units.Quantity):\n\n            _unit = astropy_units.cm ** 2\n            _y_unit = astropy_units.dimensionless_unscaled\n            _x = x.value\n\n        else:\n\n            _unit = 1.0\n            _y_unit = 1.0\n\n            _x = x\n\n        xsect_interp = self._cached_interp(_x * (1 + redshift))\n\n        spec = np.exp(-NH * xsect_interp * _unit) * _y_unit\n\n        return spec\n", "meta": {"hexsha": "5cf68d9e7fcff4950b445a1978f9209caa49c2d4", "size": 18182, "ext": "py", "lang": "Python", "max_stars_repo_path": "astromodels/functions/apec.py", "max_stars_repo_name": "henrikef/astromodels", "max_stars_repo_head_hexsha": "03b972d9678648ed970e77bd989df0040a43ea1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-15T21:13:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-15T21:13:55.000Z", "max_issues_repo_path": "astromodels/functions/apec.py", "max_issues_repo_name": "henrikef/astromodels", "max_issues_repo_head_hexsha": "03b972d9678648ed970e77bd989df0040a43ea1a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "astromodels/functions/apec.py", "max_forks_repo_name": "henrikef/astromodels", "max_forks_repo_head_hexsha": "03b972d9678648ed970e77bd989df0040a43ea1a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9742857143, "max_line_length": 187, "alphanum_fraction": 0.4886151138, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 4617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.29098086006635976, "lm_q1q2_score": 0.1669294364020308}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 08 9:02 2021\n\n@author: MCR\n\nAll functions associated with the determining the centroid positions of the\norder 1 and 2 SOSS spectra trace.\n\"\"\"\n\nimport numpy as np\nimport emcee\nimport warnings\nfrom SOSS.trace import tracepol as tp\nfrom SOSS.extract.empirical_trace import plotting as plotting\n\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\n# hack to get around the fact that relative paths are constantly messing up atm\npath = '/Users/michaelradica/Documents/GitHub/jwst-mtl/SOSS/'\n\n\ndef determine_stack_dimensions(stack, header=None, verbose=False):\n    ''' Determine the size of the stack array. Will be called by\n    get_uncontam_centroids and make_trace_mask.\n\n    Parameters\n    ----------\n    stack : array of floats (2D)\n        Data frame. Assumes DMS orientation.\n        This array could be a native pixel size SOSS subarray or FF.\n        It could also be a 2D trace reference file in which case padding exists\n        around the edges, and the pixels may be oversampled by some integer factor.\n    header : fits header\n        Header associated to the stack array.\n        If the header is None then some assumptions will be made regarding the stack array.\n        If the header is passed, then specific keywords will be read in it to assess what\n        the stack array is. This ensures that a 2D Trace Reference file will be digested\n        properly.\n\n    Returns\n    -------\n    dimx, dimy : The dimensions of the stack array.\n    xos, yos : The oversampling factor (integer) of the stack array.\n    xnative, ynative : The dimensions of the stack image, expressed in native pixels.\n    padding : the size of padding all around the image, in units of native pixels.\n    working_pixel_bool : a 2D array of the same size as stack with boolean values of\n        False where pixels are not light sensitive (the reference pixels). True elsewhere.\n    '''\n\n    # Dimensions of the subarray.\n    dimy, dimx = np.shape(stack)\n\n    # Determine what is the input stack based either on its dimensions or on\n    # the header if passed. Construct a mask of working pixels in case the\n    # stack contains reference pixels.\n    if header is None:\n        # No header passed - Assume stack is valid SOSS subarray or FF, i.e.\n        # 2048x256 or 2040x252 (working pixels) or multiple of if oversampled\n        # 2048x96 or 2040x96 (working pixels) or multiple of\n        # 2048x2048 or 2040x2040 (working pixels) or multiple of\n        if (dimx % 2048) == 0:\n            # stack is a multiple of native pixels.\n            xnative = 2048\n            # The x-axis oversampling is:\n            xos = int(dimx / 2048)\n        elif (dimx % 2040) == 0:\n            # stack is a multiple of native *** working *** pixels.\n            xnative = 2040\n            # The y-axis oversampling is:\n            xos = int(dimx / 2040)\n        else:\n            # stack x dimension has unrecognized size.\n            print('Stack X dimension has unrecognized size of {:}. Accepts 2048, 2040 or multiple of.'.format(dimx))\n            sys.exit()\n        # Check if the Y axis is consistent with the X axis.\n        acceptable_ydim = [96, 256, 252, 2040, 2048]\n        yaxis_consistent = False\n        for accdim in acceptable_ydim:\n            if dimy / (accdim*xos) == 1:\n                # Found the acceptable dimension\n                yos = np.copy(xos)\n                ynative = np.copy(accdim)\n                yaxis_consistent = True\n        if yaxis_consistent is False:\n            # stack y dimension is inconsistent with the x dimension.\n            print('Stack Y dimension ({:}) is inconsistent with X dimension ({:}) for acceptable SOSS arrays'.format(dimy,dimx))\n            sys.exit()\n        # Construct a boolean mask (true or false) of working pixels\n        working_pixel_bool = np.full((dimy, dimx), True)\n\n        # For dimensions where reference pixels would have been included in\n        # stack, mask those reference pixels out.\n        # Sizes 96, 252 and 2040 should not contain any reference pixel.\n        if xnative == 2048:\n            # Mask out the left and right columns of reference pixels\n            working_pixel_bool[:, 0:xos * 4] = False\n            working_pixel_bool[:, -xos * 4:] = False\n        if ynative == 2048:\n            # Mask out the top and bottom rows of reference pixels\n            working_pixel_bool[0:yos * 4, :] = False\n            working_pixel_bool[-yos * 4:, :] = False\n        if ynative == 256:\n            # Mask the top rows of reference pixels\n            working_pixel_bool[-yos * 4:, :] = False\n\n        # Initialize padding to zero in this case because it is not a 2D Trace ref file\n        padding = int(0)\n\n    else:\n        # header was passed\n        # Read in the relevant keywords\n        xos, yos = int(header['OVERSAMP']), int(header['OVERSAMP'])\n        padding = int(header['PADDING'])\n        # The 2D Trace profile is for FULL FRAME so 2048x2048\n        xnative, ynative = int(2048), int(2048)\n        # Check that the stack respects its intended format\n        if dimx != ((xnative+2*padding)*xos):\n            # Problem\n            print('The header passed is inconsistent with the X dimension of the stack.')\n            sys.exit()\n        if dimy != ((ynative+2*padding)*yos):\n            # Problem\n            print('The header passed is inconsistent with the Y dimension of the stack.')\n            sys.exit()\n        # Construct a mask of working pixels. The 2D Trace REFERENCE file does\n        # not contain any reference pixel. So all are True.\n        working_pixel_bool = np.full((dimy, dimx), True)\n\n    # For debugging purposes...\n    if verbose is True:\n        print('dimx={:}, dimy={:}, xos={:}, yos={:}, xnative={:}, ynative={:}'.format(dimx, dimy, xos, yos, xnative, ynative))\n\n    return(dimx, dimy, xos, yos, xnative, ynative, padding, working_pixel_bool)\n\n\ndef _do_emcee(xref, yref, xdat, ydat, showprogress=False):\n    '''Calls the emcee package to preform an MCMC determination of the best\n    fitting rotation angle and offsets to map the reference centroids onto the\n    data for the first order.\n\n    Parameters\n    ----------\n    xref, yref : array of float\n        X and Y trace centroids respectively to be used as a reference point,\n        for example: as returned by get_om_centroids.\n    xdat, ydat : array of float\n        X and Y trace centroids determined from the data, for example: as\n        returned by get_uncontam_centroids.\n    showprogress: bool\n        If True, show the emcee progress bar.\n\n    Returns\n    -------\n    sampler : emcee EnsembleSampler object\n        MCMC fitting results.\n    '''\n\n    # Set up the MCMC run.\n    initial = np.array([0, 0, 0])  # Initial guess parameters\n    pos = initial + 0.5*np.random.randn(32, 3)\n    nwalkers, ndim = pos.shape\n\n    sampler = emcee.EnsembleSampler(nwalkers, ndim, _log_probability,\n                                    args=[xref, yref, xdat, ydat])\n    # Run the MCMC for 5000 steps - it has generally converged\n    # within ~3000 steps in trial runs.\n    sampler.run_mcmc(pos, 5000, progress=showprogress)\n\n    return sampler\n\n\ndef get_centerofmass_centroids(stack, header=None, badpix=None, tracemask=None,\n                               verbose=False):\n    '''Determine the x, y positions of the trace centroids from an\n    exposure using a center-of-mass analysis. Works for either order if there\n    is no contamination, or for order 1 on a detector where the two orders\n    are overlapping.\n    This is an adaptation of Loïc's get_order1_centroids which can better\n    deal with a bright second order.\n\n    Parameters\n    ----------\n    stack : array of floats (2D)\n        Data frame. Assumes DMS orientation.\n        This array could be a native pixel size SOSS subarray or FF.\n        It could also be a 2D trace reference file in which case padding exists\n        around the edges, and the pixels may be oversampled by some integer factor.\n    header : fits header\n        Header associated to the stack array.\n        If the header is None then some assumptions will be made regarding the stack array.\n        If the header is passed, then specific keywords will be read in it to assess what\n        the stack array is. This ensures that a 2D Trace Reference file will be digested\n        properly.\n    badpix : array of floats (2D) with anything different than zero meaning a bad pixel\n        Optional input bad pixel mask to apply to the stack. Should be of\n        the same dimensions as the stack.\n    tracemask : array of floats (2D) with anything different than zero meaning a\n        masked out pixel. The spirit is to have zeros along one spectral order with\n        a certain width.\n    specpix_bounds : native spectral pixel bounds to consider in fitting the trace. Most\n        likely used for the 2nd and 3rd orders, not for the 1st order.\n\n    Returns\n    -------\n    tracexbest : np.array\n        Best estimate data x centroid.\n    traceybest : np.array\n        Best estimate data y centroids.\n    '''\n\n    # Call the script that determines the dimensions of the stack. It handles\n    # regular science images of various subaaray sizes, with or without the\n    # reference pixels, oversampled or not. It also handles the 2D Trace\n    # Reference File.\n    dimx, dimy, xos, yos, xnative, ynative, padding, working_pixel_bool = \\\n        determine_stack_dimensions(stack, header=header)\n\n    # Make a numpy mask array of the working pixels\n    working_pixel_mask = np.ma.array(np.ones((dimy, dimx)), mask=np.invert(working_pixel_bool))\n    # Fill the working pixel mask with NaN\n    working_pixel_mask = np.ma.filled(working_pixel_mask, np.nan)\n\n    # Check for the optional input badpix and create a bad pixel numpy mask\n    if badpix is not None:\n        # 1) Check the dimension is the same as stack\n        # TODO:\n        # 2) Create the numpy.ma array with it\n        # The bad pixel mask has values of 'one' for valid pixels.\n        badpix_mask = np.ma.array(np.ones((dimy, dimx)), mask=(badpix != 0))\n    else:\n        # Create a mask with all valid pixels (all ones)\n        badpix_mask = np.ma.array(np.ones((dimy, dimx)))\n    # Fill the bad pixels with NaN\n    badpix_mask = np.ma.filled(badpix_mask, np.nan)\n\n    # Check for the optional input tracemask and create a trace numpy mask\n    if tracemask is not None:\n        # 1) Check the dimension is the same as stack\n        # TODO:\n        # 2) Create the numpy.ma array with it\n        # The trace mask has values of 'one' for valid pixels.\n        trace_mask = np.ma.array(np.ones((dimy, dimx)), mask=(tracemask == 0))\n    else:\n        # Create a mask with all pixels in the trace (all ones)\n        trace_mask = np.ma.array(np.ones((dimy, dimx)))\n    # Fill the trace mask with NaN\n    trace_mask = np.ma.filled(trace_mask, np.nan)\n\n    # Multiply working pixel mask, bad pixel mask and trace mask\n    # The stack image with embedded numpy mask is stackm\n    stackm = stack * badpix_mask * working_pixel_mask * trace_mask\n\n    # Identify the floor level of all 2040 working cols to subtract it first.\n    floorlevel = np.nanpercentile(stackm, 10, axis=0)\n    backsub = stackm - floorlevel\n    # Find centroid - first pass, use all pixels in the column.\n    # Normalize each column\n    norm = backsub / np.nanmax(backsub, axis=0)\n    # Create 2D Array of pixel positions\n    rows = (np.ones((dimx, dimy)) * np.arange(dimy)).T\n    # CoM analysis to find centroid\n    com = (np.nansum(norm * rows, axis=0) / np.nansum(norm, axis=0)).data\n    # Adopt these trace values as best\n    tracex_best = np.arange(dimx)\n    tracey_best = np.copy(com)\n    # Second pass, find centroid on a subset of pixels\n    # from an area around the centroid determined earlier.\n    tracex = np.arange(dimx)\n    tracey = np.zeros(dimx)*np.nan\n    row = np.arange(dimy)\n    w = 30 * yos\n    for i in range(dimx):\n        miny = np.int(np.nanmax([np.around(tracey_best[i] - w), 0]))\n        maxy = np.int(np.nanmax([np.around(tracey_best[i] + w), dimy - 1]))\n        val = backsub[miny:maxy, i] / np.nanmax(backsub[:, i])\n        ind = np.where(np.isfinite(val))\n        thisrow = (row[miny:maxy])[ind]\n        thisval = val[ind]\n        com = np.sum(thisrow * thisval) / np.sum(thisval)\n        # Ensure that the centroid position is not getting too close to an edge\n        # such that it is biased.\n        if (not np.isfinite(com)) or (com <= 5*yos) or (com >= (ynative-6)*yos):\n            continue\n        # For a bright second order, it is likely that the centroid at this\n        # point will be somewhere in between the first and second order.\n        # If this is the case (i.e. the pixel value of the centroid is very low\n        # compared to the column average), restrict the range of pixels\n        # considered to be above the current centroid.\n        if backsub[int(com)][i] < np.nanmean(backsub[(int(com) - w):(int(com) + w), i]):\n            miny = np.int(np.nanmax([np.around(com), 0]))\n            maxy = np.int(np.nanmin([np.around(com + 2*w), dimy - 1]))\n            val = backsub[miny:maxy, i] / np.nanmax(backsub[:, i])\n            ind = np.where(np.isfinite(val))\n            thisrow = (row[miny:maxy])[ind]\n            thisval = val[ind]\n            com = np.sum(thisrow * thisval) / np.sum(thisval)\n        tracey[i] = com\n    # Adopt these trace values as best.\n    tracex_best = np.copy(tracex)\n    tracey_best = np.copy(tracey)\n\n    # Third pass - fine tuning.\n    tracex = np.arange(dimx)\n    tracey = np.zeros(dimx) * np.nan\n    row = np.arange(dimy)\n    w = 16 * yos\n    for i in range(len(tracex_best)):\n        miny = np.int(np.nanmax([np.around(tracey_best[i] - w), 0]))\n        maxy = np.int(np.nanmax([np.around(tracey_best[i] + w), dimy - 1]))\n        val = backsub[miny:maxy, i] / np.nanmax(backsub[:, i])\n        ind = np.where(np.isfinite(val))\n        thisrow = (row[miny:maxy])[ind]\n        thisval = val[ind]\n        com = np.sum(thisrow * thisval) / np.sum(thisval)\n        tracex[i] = np.copy(tracex_best[i])\n        tracey[i] = np.copy(com)\n    # Update with the best estimates\n    tracex_best = np.copy(tracex)\n    tracey_best = np.copy(tracey)\n\n    if verbose is True:\n        plt.figure()\n        plt.plot(tracex_best, tracey_best)\n\n    # Final pass : Fitting a polynomial to the measured (noisy) positions\n    if padding == 0:\n        # Only use the non NaN pixels.\n        induse = np.isfinite(tracex_best) & np.isfinite(tracey_best)\n    else:\n        # Important steps in the case of the 2D Trace reference file.\n        # Mask out the padded pixels from the fit so it is rigorously the\n        # same as for regular science images.\n        induse = np.isfinite(tracex_best) & np.isfinite(tracey_best) & \\\n                 (tracex_best >= xos*padding) & (tracex_best < (dimx-xos*padding))\n\n    # Use a *** fixed *** polynomial order of 11 to keep results consistent\n    # from data set to data set. Any systematics would remain fixed.\n    polyorder = 11\n    param = np.polyfit(tracex_best[induse], tracey_best[induse], polyorder)\n    tracey_best = np.polyval(param, tracex_best)\n\n    if verbose is True:\n        plt.plot(tracex_best, tracey_best, color='r')\n        plt.show()\n\n    return tracex_best, tracey_best\n\n\ndef get_contam_centroids(clear, ref_centroids=None, doplot=False,\n                         return_orders=[1, 2, 3], bound=True,\n                         showprogress=False):\n    '''Get the trace centroids for all orders when there is contamination on\n    the detector. Fits the first order centroids using the uncontaminated\n    method, and determines the second/third order centroids via the\n    well-calibrated relationship between all orders.\n\n    Parameters\n    ----------\n    clear : np.ndarray (2D)\n        CLEAR SOSS exposure data frame.\n    ref_centroids : np.ndarray (2D)\n        Centroids relative to which to determine rotations parameters.\n        Must contain lists of x and y centroids for each order to be returned.\n        If None, uses the trace table centroids as a reference.\n    doplot : bool\n        Whether to plot the results of the reference centroids fit to the\n        first order.\n    return_orders : list\n        Orders for which centroid x and y positions will be returned.\n    bound : bool\n        If True, only returns centroids that fall on the detector after\n        polynomial fitting.\n    showprogress : bool\n        If True, show the emcee progress bar.\n\n    Returns\n    -------\n    trans_cen : dict\n        Dictionary containing x and y trace centroids for each order in\n        return_orders.\n    rot_pars : tuple\n        Tuple containing the required parameters to transform the reference\n        centroids to match the dataL: rotation angle, x offset and y offset.\n\n    Raises\n    ------\n    ValueError\n        If ref_centroids does not match return_orders.\n    '''\n\n    # Determine reference centroids for all orders.\n    ref_cen = {}\n    trans_cen = {}\n    # If provided as input.\n    if ref_centroids is not None:\n        # Ensure length is correct.\n        if len(ref_centroids) != 2*len(return_orders):\n            raise ValueError('Insufficient reference centroids provided.')\n        # Repackage into a dictionary\n        for i, order in enumerate(return_orders):\n            ref_cen['order '+str(order)] = [ref_centroids[2*i], ref_centroids[2*i+1]]\n    # Or from the trace table (currently the optics model).\n    else:\n        for order in return_orders:\n            # Extend centroids off of the detector to compensate for shifts.\n            xom, yom, tp = get_om_centroids(np.arange(2148)-50, order=order)\n            ref_cen['order '+str(order)] = [xom, yom]\n\n    # Get the order 1 centroids from the data.\n    xdat_o1, ydat_o1 = get_uncontam_centroids(clear, np.arange(2048), fit=True)\n    trans_cen['order 1'] = [xdat_o1, ydat_o1]\n\n    # Fit the reference centroids to the data for order 1.\n    fit = _do_emcee(ref_cen['order 1'][0], ref_cen['order 1'][1], xdat_o1,\n                    ydat_o1, showprogress=showprogress)\n    # Plot MCMC results if requested.\n    if doplot is True:\n        plotting._plot_corner(fit)\n    # Get fitted rotation parameters.\n    flat_samples = fit.get_chain(discard=500, thin=15, flat=True)\n    ang = np.percentile(flat_samples[:, 0], 50)\n    xshift = np.percentile(flat_samples[:, 1], 50)\n    yshift = np.percentile(flat_samples[:, 2], 50)\n    rot_params = (ang, xshift, yshift)\n\n    # Get rotated centroids for all other orders.\n    for order in return_orders:\n        if order == 1:\n            continue\n        xtrans, ytrans = rot_centroids(ang, xshift, yshift,\n                                       ref_cen['order '+str(order)][0],\n                                       ref_cen['order '+str(order)][1])\n        # Ensure that the centroids cover the whole detector.\n        pp = np.polyfit(xtrans, ytrans, 5)\n        ytrans = np.polyval(pp, np.arange(2048))\n        if bound is True:\n            inds = np.where((ytrans >= 0) & (ytrans < 256))[0]\n            trans_cen['order '+str(order)] = [np.arange(2048)[inds], ytrans[inds]]\n        else:\n            trans_cen['order '+str(order)] = [np.arange(2048), ytrans]\n\n    return trans_cen, rot_params\n\n\n# Needs to be updated whenever we decide on how we will interact with\n# new reference files\ndef get_om_centroids(atthesex=None, order=1):\n    '''Get trace profile centroids from the NIRISS SOSS optics model.\n    These centroids include the standard rotation of 1.489 deg about\n    (1514, 486) to transform from the optics model into the CV3 coordinate\n    system.\n\n    Parameters\n    ----------\n    atthesex : list of floats\n        Pixel x values at which to evaluate the centroid position.\n    order : int\n        Diffraction order for which to return the optics model solution.\n\n    Returns\n    -------\n    xOM : list of floats\n        Optics model x centroids.\n    yOM : list of floats\n        Optics model y centroids.\n    tp2 : list of floats\n        trace polynomial coefficients.\n    '''\n\n    if atthesex is None:\n        atthesex = np.linspace(0, 2047, 2048)\n\n    # Derive the trace polynomials.\n    tp2 = tp.get_tracepars(filename=path+'/trace/NIRISS_GR700_trace.csv')\n\n    # Evaluate the trace polynomials at the desired coordinates.\n    w = tp.specpix_to_wavelength(atthesex, tp2, order, frame='dms', oversample=2)[0]\n    xOM, yOM, mas = tp.wavelength_to_pix(w, tp2, order, frame='dms', oversample=2)\n\n    return xOM, yOM[::-1], tp2\n\n\ndef get_uncontam_centroids(stack, atthesex=np.arange(2048), fit=True):\n    '''Determine the x, y positions of the trace centroids from an\n    exposure using a center-of-mass analysis. Works for either order if there\n    is no contamination, or for order 1 on a detector where the two orders\n    are overlapping.\n    This is an adaptation of Loïc's get_order1_centroids which can better\n    deal with a bright second order.\n\n    Parameters\n    ----------\n    stack : array of floats (2D)\n        Data frame.\n    atthesex : list of floats\n        Pixel x values at which to extract the trace centroids.\n    fit : bool\n        If True, fits a 5th order polynomial to the extracted y-centroids,\n        and returns the evaluation of this polynomial at atthesex. If False,\n        a y-centroid may not be located for each x-pixel in atthesex.\n\n    Returns\n    -------\n    tracexbest : np.array\n        Best estimate data x centroid.\n    traceybest : np.array\n        Best estimate data y centroids.\n    '''\n\n    # Dimensions of the subarray.\n    dimx = len(atthesex)\n    dimy = np.shape(stack)[0]\n\n    # Identify the floor level of all 2040 working cols to subtract it first.\n    floorlevel = np.nanpercentile(stack, 10, axis=0)\n    backsub = stack - floorlevel\n\n    # Find centroid - first pass, use all pixels in the column.\n    # Normalize each column\n    norm = backsub[:, 4:2044] / np.nanmax(backsub[:, 4:2044], axis=0)\n    # Create 2D Array of pixel positions\n    rows = (np.ones((2040, 256)) * np.arange(256)).T\n    # Mask any nan values\n    norm_mask = np.ma.masked_invalid(norm)\n    # CoM analysis to find centroid\n    cx = (np.nansum(norm_mask * rows, axis=0) / np.nansum(norm, axis=0)).data\n\n    # Adopt these trace values as best\n    tracex_best = np.arange(2040)+4\n    tracey_best = cx\n\n    # Second pass, find centroid on a subset of pixels\n    # from an area around the centroid determined earlier.\n    tracex = []\n    tracey = []\n    row = np.arange(dimy)\n    w = 30\n    for i in range(dimx - 8):\n        miny = np.int(np.nanmax([np.around(tracey_best[i] - w), 0]))\n        maxy = np.int(np.nanmax([np.around(tracey_best[i] + w), dimy - 1]))\n        val = backsub[miny:maxy, i + 4] / np.nanmax(backsub[:, i + 4])\n        ind = np.where(np.isfinite(val))\n        thisrow = (row[miny:maxy])[ind]\n        thisval = val[ind]\n        cx = np.sum(thisrow * thisval) / np.sum(thisval)\n        # Ensure that the centroid position is not getting too close to an edge\n        # such that it is biased.\n        if not np.isfinite(cx) or cx <= 5 or cx >= 250:\n            continue\n        # For a bright second order, it is likely that the centroid at this\n        # point will be somewhere in between the first and second order.\n        # If this is the case (i.e. the pixel value of the centroid is very low\n        # compared to the column average), restrict the range of pixels\n        # considered to be above the current centroid.\n        if backsub[int(cx)][i+4] < np.nanmean(backsub[(int(cx) - w):(int(cx)+w), i+4]):\n            miny = np.int(np.nanmax([np.around(cx), 0]))\n            maxy = np.int(np.nanmin([np.around(cx + 2*w), dimy - 1]))\n            val = backsub[miny:maxy, i + 4] / np.nanmax(backsub[:, i + 4])\n            ind = np.where(np.isfinite(val))\n            thisrow = (row[miny:maxy])[ind]\n            thisval = val[ind]\n            cx = np.sum(thisrow * thisval) / np.sum(thisval)\n\n        tracex.append(i + 4)\n        tracey.append(cx)\n\n    # Adopt these trace values as best.\n    tracex_best = np.array(tracex) * 1\n    tracey_best = np.array(tracey) * 1\n\n    # Third pass - fine tuning.\n    tracex = []\n    tracey = []\n    row = np.arange(dimy)\n    w = 16\n    for i in range(len(tracex_best)):\n        miny = np.int(np.nanmax([np.around(tracey_best[i] - w), 0]))\n        maxy = np.int(np.nanmax([np.around(tracey_best[i] + w), dimy - 1]))\n        val = backsub[miny:maxy, i + 4] / np.nanmax(backsub[:, i + 4])\n        ind = np.where(np.isfinite(val))\n        thisrow = (row[miny:maxy])[ind]\n        thisval = val[ind]\n        cx = np.sum(thisrow * thisval) / np.sum(thisval)\n\n        tracex.append(tracex_best[i])\n        tracey.append(cx)\n\n    tracex_best = np.array(tracex)\n    tracey_best = np.array(tracey)\n\n    if fit is True:\n        # Fit a polynomial to centroids to ensure there is a centroid at each x\n        p_o1 = np.polyfit(tracex_best, tracey_best, 5)\n        tracey_best = np.polyval(p_o1, atthesex)\n        tracex_best = atthesex\n\n    return tracex_best, tracey_best\n\n\ndef _log_likelihood(theta, xmod, ymod, xdat, ydat):\n    '''Definition of the log likelihood. Called by _do_emcee.\n    xmod/ymod should extend past the edges of the SUBSTRIP256 detector.\n    '''\n    ang, xshift, yshift = theta\n    # Calculate rotated model\n    modelx, modely = rot_centroids(ang, xshift, yshift,\n                                   xmod, ymod, bound=True)\n    # Interpolate rotated model onto same x scale as data\n    modely = np.interp(xdat, modelx, modely)\n\n    return -0.5 * np.sum((ydat - modely)**2 - 0.5 * np.log(2 * np.pi * 1))\n\n\ndef _log_prior(theta):\n    '''Definition of the priors. Called by _do_emcee.\n    Angle within +/- 5 deg (one motor step is 0.15deg).\n    X-shift within +/- 100 pixels, TA shoukd be accurate to within 1 pixel.\n    Y-shift to within +/- 50 pixels.\n    '''\n    ang, xshift, yshift = theta\n\n    if -5 <= ang < 5 and -100 <= xshift < 100 and -50 <= yshift < 50:\n        return -1\n    else:\n        return -np.inf\n\n\ndef _log_probability(theta, xmod, ymod, xdat, ydat):\n    '''Definition of the final probability. Called by _do_emcee.\n    '''\n    lp = _log_prior(theta)\n    if not np.isfinite(lp):\n        return -np.inf\n\n    return lp + _log_likelihood(theta, xmod, ymod, xdat, ydat)\n\n\ndef rot_centroids(ang, xshift, yshift, xpix, ypix, bound=True, atthesex=None,\n                  cenx=1024, ceny=50):\n    '''Apply a rotation and shift to the trace centroids positions. This\n    assumes that the trace centroids are already in the CV3 coordinate system.\n\n    Parameters\n    ----------\n    ang : float\n        The rotation angle in degrees CCW.\n    xshift : float\n        Offset in the X direction to be rigidly applied after rotation.\n    yshift : float\n        Offset in the Y direction to be rigidly applied after rotation.\n    xpix : float or np.array of float\n        Centroid pixel X values.\n    ypix : float or np.array of float]\n        Centroid pixel Y values.\n    bound : bool\n        Whether to trim rotated solutions to fit within the subarray256.\n    atthesex : list of float\n        Pixel values at which to calculate rotated centroids.\n\n    Returns\n    -------\n    rot_xpix : np.array of float\n        xval after the application of the rotation and translation\n        transformations.\n    rot_ypix : np.array of float\n        yval after the application of the rotation and translation\n        transformations.\n    '''\n\n    # Convert to numpy arrays\n    xpix = np.atleast_1d(xpix)\n    ypix = np.atleast_1d(ypix)\n    # Required rotation in the detector frame to match the data.\n    t = np.deg2rad(ang)\n    R = np.array([[np.cos(t), -np.sin(t)], [np.sin(t), np.cos(t)]])\n\n    # Rotation center set to o1 trace centroid halfway along spectral axis.\n    points1 = np.array([xpix - cenx, ypix - ceny])\n    rot_pix = R @ points1\n\n    rot_pix[0] += cenx\n    rot_pix[1] += ceny\n\n    # Apply the offsets\n    rot_pix[0] += xshift\n    rot_pix[1] += yshift\n\n    if xpix.size >= 10:\n        if atthesex is None:\n            # Ensure that there are no jumps of >1 pixel.\n            min = int(round(np.min(rot_pix[0]), 0))\n            max = int(round(np.max(rot_pix[0]), 0))\n            # Same range as rotated pixels but with step of 1 pixel.\n            atthesex = np.linspace(min, max, max-min+1)\n        # Polynomial fit to ensure a centroid at each pixel in atthesex\n        pp = np.polyfit(rot_pix[0], rot_pix[1], 5)\n        # Warn user if atthesex extends beyond polynomial domain.\n        if np.max(atthesex) > np.max(rot_pix[0])+25 or np.min(atthesex) < np.min(rot_pix[0])-25:\n            warnings.warn('atthesex extends beyond rot_xpix. Use results with caution.')\n        rot_xpix = atthesex\n        rot_ypix = np.polyval(pp, rot_xpix)\n    else:\n        # If too few pixels for fitting, keep rot_pix.\n        if atthesex is not None:\n            print('Too few pixels for polynomial fitting. Ignoring atthesex.')\n        rot_xpix = rot_pix[0]\n        rot_ypix = rot_pix[1]\n\n    # Check to ensure all points are on the subarray.\n    if bound is True:\n        inds = [(rot_ypix >= 0) & (rot_ypix < 256) & (rot_xpix >= 0) &\n                (rot_xpix < 2048)]\n        rot_xpix = rot_xpix[inds]\n        rot_ypix = rot_ypix[inds]\n\n    return rot_xpix, rot_ypix\n", "meta": {"hexsha": "90136641b31c3891bfc77d53a6358ad4a8fc94b1", "size": 29203, "ext": "py", "lang": "Python", "max_stars_repo_path": "SOSS/extract/Empirical_Trace/centroid.py", "max_stars_repo_name": "njcuk9999/jwst-mtl", "max_stars_repo_head_hexsha": "81d3e7ec6adc5dae180cd9d3bff8e4a2a7292596", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-04T13:59:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T13:59:18.000Z", "max_issues_repo_path": "SOSS/extract/Empirical_Trace/centroid.py", "max_issues_repo_name": "njcuk9999/jwst-mtl", "max_issues_repo_head_hexsha": "81d3e7ec6adc5dae180cd9d3bff8e4a2a7292596", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-09-17T20:14:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T21:16:43.000Z", "max_forks_repo_path": "SOSS/extract/Empirical_Trace/centroid.py", "max_forks_repo_name": "njcuk9999/jwst-mtl", "max_forks_repo_head_hexsha": "81d3e7ec6adc5dae180cd9d3bff8e4a2a7292596", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-18T15:25:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-18T15:25:52.000Z", "avg_line_length": 40.6161335188, "max_line_length": 128, "alphanum_fraction": 0.6366126768, "include": true, "reason": "import numpy", "num_tokens": 7653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.290980853917813, "lm_q1q2_score": 0.1669294328747423}}
{"text": "import math\nimport numpy as np\nfrom tinygrad.tensor import Tensor\nfrom tinygrad.utils import fetch\nfrom tinygrad.nn import BatchNorm2D\n\nUSE_TORCH = False\n\ndef fake_torch_load(b0):\n  import io\n  import pickle\n  import struct\n\n  # convert it to a file\n  fb0 = io.BytesIO(b0)\n\n  # skip three junk pickles\n  pickle.load(fb0)\n  pickle.load(fb0)\n  pickle.load(fb0)\n\n  key_prelookup = {}\n\n  class HackTensor:\n    def __new__(cls, *args):\n      #print(args)\n      ident, storage_type, obj_key, location, obj_size, view_metadata = args[0]\n      assert ident == 'storage'\n\n      ret = np.zeros(obj_size, dtype=storage_type)\n      key_prelookup[obj_key] = (storage_type, obj_size, ret, args[2], args[3])\n      return ret\n\n  class MyPickle(pickle.Unpickler):\n    def find_class(self, module, name):\n      #print(module, name)\n      if name == 'FloatStorage':\n        return np.float32\n      if name == 'LongStorage':\n        return np.int64\n      if module == \"torch._utils\" or module == \"torch\":\n        return HackTensor\n      else:\n        return pickle.Unpickler.find_class(self, module, name)\n\n    def persistent_load(self, pid):\n      return pid\n\n  ret = MyPickle(fb0).load()\n\n  # create key_lookup\n  key_lookup = pickle.load(fb0)\n  key_real = [None] * len(key_lookup)\n  for k,v in key_prelookup.items():\n    key_real[key_lookup.index(k)] = v\n\n  # read in the actual data\n  for storage_type, obj_size, np_array, np_shape, np_strides in key_real:\n    ll = struct.unpack(\"Q\", fb0.read(8))[0]\n    assert ll == obj_size\n    bytes_size = {np.float32: 4, np.int64: 8}[storage_type]\n    mydat = fb0.read(ll * bytes_size)\n    np_array[:] = np.frombuffer(mydat, storage_type)\n    np_array.shape = np_shape\n\n    # numpy stores its strides in bytes\n    real_strides = tuple([x*bytes_size for x in np_strides])\n    np_array.strides = real_strides\n\n  return ret\n\nclass MBConvBlock:\n  def __init__(self, kernel_size, strides, expand_ratio, input_filters, output_filters, se_ratio):\n    oup = expand_ratio * input_filters\n    if expand_ratio != 1:\n      self._expand_conv = Tensor.zeros(oup, input_filters, 1, 1)\n      self._bn0 = BatchNorm2D(oup)\n    else:\n      self._expand_conv = None\n\n    self.strides = strides\n    if strides == (2,2):\n      self.pad = [(kernel_size-1)//2-1, (kernel_size-1)//2]*2\n    else:\n      self.pad = [(kernel_size-1)//2]*4\n\n    self._depthwise_conv = Tensor.zeros(oup, 1, kernel_size, kernel_size)\n    self._bn1 = BatchNorm2D(oup)\n\n    num_squeezed_channels = max(1, int(input_filters * se_ratio))\n    self._se_reduce = Tensor.zeros(num_squeezed_channels, oup, 1, 1)\n    self._se_reduce_bias = Tensor.zeros(num_squeezed_channels)\n    self._se_expand = Tensor.zeros(oup, num_squeezed_channels, 1, 1)\n    self._se_expand_bias = Tensor.zeros(oup)\n\n    self._project_conv = Tensor.zeros(output_filters, oup, 1, 1)\n    self._bn2 = BatchNorm2D(output_filters)\n\n  def __call__(self, inputs):\n    x = inputs\n    if self._expand_conv:\n      x = self._bn0(x.conv2d(self._expand_conv)).swish()\n    x = x.pad2d(padding=self.pad)\n    x = x.conv2d(self._depthwise_conv, stride=self.strides, groups=self._depthwise_conv.shape[0])\n    x = self._bn1(x).swish()\n\n    # has_se\n    x_squeezed = x.avg_pool2d(kernel_size=x.shape[2:4])\n    x_squeezed = x_squeezed.conv2d(self._se_reduce).add(self._se_reduce_bias.reshape(shape=[1, -1, 1, 1])).swish()\n    x_squeezed = x_squeezed.conv2d(self._se_expand).add(self._se_expand_bias.reshape(shape=[1, -1, 1, 1]))\n    x = x.mul(x_squeezed.sigmoid())\n\n    x = self._bn2(x.conv2d(self._project_conv))\n    if x.shape == inputs.shape:\n      x = x.add(inputs)\n    return x\n\nclass EfficientNet:\n  def __init__(self, number=0):\n    self.number = number\n    global_params = [\n      # width, depth\n      (1.0, 1.0), # b0\n      (1.0, 1.1), # b1\n      (1.1, 1.2), # b2\n      (1.2, 1.4), # b3\n      (1.4, 1.8), # b4\n      (1.6, 2.2), # b5\n      (1.8, 2.6), # b6\n      (2.0, 3.1), # b7\n      (2.2, 3.6), # b8\n      (4.3, 5.3), # l2\n    ][number]\n\n    def round_filters(filters):\n      multiplier = global_params[0]\n      divisor = 8\n      filters *= multiplier\n      new_filters = max(divisor, int(filters + divisor / 2) // divisor * divisor)\n      if new_filters < 0.9 * filters: # prevent rounding by more than 10%\n        new_filters += divisor\n      return int(new_filters)\n\n    def round_repeats(repeats):\n      return int(math.ceil(global_params[1] * repeats))\n\n    out_channels = round_filters(32)\n    self._conv_stem = Tensor.zeros(out_channels, 3, 3, 3)\n    self._bn0 = BatchNorm2D(out_channels)\n    blocks_args = [\n      [1, 3, (1,1), 1, 32, 16, 0.25],\n      [2, 3, (2,2), 6, 16, 24, 0.25],\n      [2, 5, (2,2), 6, 24, 40, 0.25],\n      [3, 3, (2,2), 6, 40, 80, 0.25],\n      [3, 5, (1,1), 6, 80, 112, 0.25],\n      [4, 5, (2,2), 6, 112, 192, 0.25],\n      [1, 3, (1,1), 6, 192, 320, 0.25],\n    ]\n    self._blocks = []\n    # num_repeats, kernel_size, strides, expand_ratio, input_filters, output_filters, se_ratio\n    for b in blocks_args:\n      args = b[1:]\n      args[3] = round_filters(args[3])\n      args[4] = round_filters(args[4])\n      for n in range(round_repeats(b[0])):\n        self._blocks.append(MBConvBlock(*args))\n        args[3] = args[4]\n        args[1] = (1,1)\n\n    in_channels = round_filters(320)\n    out_channels = round_filters(1280)\n    self._conv_head = Tensor.zeros(out_channels, in_channels, 1, 1)\n    self._bn1 = BatchNorm2D(out_channels)\n    self._fc = Tensor.zeros(out_channels, 1000)\n    self._fc_bias = Tensor.zeros(1000)\n\n  def forward(self, x):\n    x = x.pad2d(padding=(0,1,0,1))\n    x = self._bn0(x.conv2d(self._conv_stem, stride=2)).swish()\n    for block in self._blocks:\n      #print(x.shape)\n      x = block(x)\n    x = self._bn1(x.conv2d(self._conv_head)).swish()\n    x = x.avg_pool2d(kernel_size=x.shape[2:4])\n    x = x.reshape(shape=(-1, x.shape[1]))\n    #x = x.dropout(0.2)\n    return x.dot(self._fc).add(self._fc_bias.reshape(shape=[1,-1]))\n\n  def load_weights_from_torch(self, gpu):\n    # load b0\n    # https://github.com/lukemelas/EfficientNet-PyTorch/blob/master/efficientnet_pytorch/utils.py#L551\n    if self.number == 0:\n      b0 = fetch(\"https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b0-355c32eb.pth\")\n    elif self.number == 2:\n      b0 = fetch(\"https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b2-8bb594d6.pth\")\n    elif self.number == 4:\n      b0 = fetch(\"https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b4-6ed6700e.pth\")\n    elif self.number == 7:\n      b0 = fetch(\"https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b7-dcc49843.pth\")\n    else:\n      raise Exception(\"no pretrained weights\")\n\n    if USE_TORCH:\n      import io\n      import torch\n      b0 = torch.load(io.BytesIO(b0))\n    else:\n      b0 = fake_torch_load(b0)\n\n    for k,v in b0.items():\n      if '_blocks.' in k:\n        k = \"%s[%s].%s\" % tuple(k.split(\".\", 2))\n      mk = \"self.\"+k\n      #print(k, v.shape)\n      try:\n        mv = eval(mk)\n      except AttributeError:\n        try:\n          mv = eval(mk.replace(\".weight\", \"\"))\n        except AttributeError:\n          mv = eval(mk.replace(\".bias\", \"_bias\"))\n      vnp = v.numpy().astype(np.float32) if USE_TORCH else v\n      mv.data[:] = vnp if k != '_fc.weight' else vnp.T\n      if gpu:\n        mv.cuda_()\n\n", "meta": {"hexsha": "5dafa19678bc98ebbd11451e58b8eb10ada3baa0", "size": 7347, "ext": "py", "lang": "Python", "max_stars_repo_path": "extra/efficientnet.py", "max_stars_repo_name": "dwburer/tinygrad", "max_stars_repo_head_hexsha": "b8deb36e56b4eebb48cb0533e814397b1fcc7694", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-08T22:08:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-08T22:08:01.000Z", "max_issues_repo_path": "extra/efficientnet.py", "max_issues_repo_name": "Vinci0007/tinygrad", "max_issues_repo_head_hexsha": "541330c42a107d97fa8808ab882fb75de7c0d240", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extra/efficientnet.py", "max_forks_repo_name": "Vinci0007/tinygrad", "max_forks_repo_head_hexsha": "541330c42a107d97fa8808ab882fb75de7c0d240", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-27T09:50:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T09:50:36.000Z", "avg_line_length": 32.3656387665, "max_line_length": 120, "alphanum_fraction": 0.6327752824, "include": true, "reason": "import numpy", "num_tokens": 2364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.16685338558911159}}
{"text": "#-------------------------------------------------------------------------------\n#\n#  Swarm MIO_SHA_2* coefficients loaders\n#\n# Author: Martin Paces <martin.paces@eox.at>\n#\n#-------------------------------------------------------------------------------\n# Copyright (C) 2018 EOX IT Services GmbH\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies of this Software or works derived from this Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#-------------------------------------------------------------------------------\n\nfrom io import open\nfrom numpy import arange\nfrom .model_mio import (\n    DipoleMIOPrimaryGeomagneticModel, DipoleMIOGeomagneticModel,\n    MIO_EARTH_RADIUS,\n)\nfrom .coefficients_mio import SparseSHCoefficientsMIO\nfrom .parser_mio import parse_swarm_mio_file\n\n\ndef load_model_swarm_mio_internal(path):\n    \"\"\" Load internal (secondary field) model from a Swarm MIO_SHA_2* product.\n    \"\"\"\n    coefficients, params = load_coeff_swarm_mio_internal(path)\n    return _create_mio_model(coefficients, params)\n\n\ndef load_model_swarm_mio_external(path, above_ionosphere=None):\n    \"\"\" Load external (primary field) model from a Swarm MIO_SHA_2* product.\n    \"\"\"\n    with open(path, encoding=\"ascii\") as file_in:\n        params = parse_swarm_mio_file(file_in)\n\n    if above_ionosphere is None:\n        return _create_composed_mio_model(\n            _get_coeff_swarm_mio_external(params, False),\n            _get_coeff_swarm_mio_external(params, True),\n            params\n        )\n    else:\n        return _create_mio_model(\n            _get_coeff_swarm_mio_external(params, above_ionosphere), params\n        )\n\n\ndef _create_composed_mio_model(coefficients_below_ionosphere,\n                               coefficients_above_ionosphere, params):\n    return DipoleMIOPrimaryGeomagneticModel(\n        _create_mio_model(coefficients_below_ionosphere, params),\n        _create_mio_model(coefficients_above_ionosphere, params),\n        height=params[\"height\"],\n    )\n\n\ndef _create_mio_model(coefficients, params):\n    return DipoleMIOGeomagneticModel(\n        coefficients, north_pole=(params[\"lat_NGP\"], params[\"lon_NGP\"]),\n        wolf_ratio=params[\"wolf_ratio\"], height=params[\"height\"],\n    )\n\n\ndef load_coeff_swarm_mio_internal(path):\n    \"\"\" Load internal model coefficients and other parameters\n    from a Swarm MIO_SHA_2* product file.\n    \"\"\"\n    with open(path, encoding=\"ascii\") as file_in:\n        data = parse_swarm_mio_file(file_in)\n\n    return SparseSHCoefficientsMIO(\n        data[\"nm\"], data[\"gh\"],\n        ps_extent=(data[\"pmin\"], data[\"pmax\"], data[\"smin\"], data[\"smax\"]),\n        is_internal=True,\n    ), data\n\n\ndef load_coeff_swarm_mio_external(path, above_ionosphere=True):\n    \"\"\" Load external model coefficients from a Swarm MIO_SHA_2* product file.\n    Use the `above_ionosphere` to pick the right model variant.\n    \"\"\"\n    with open(path, encoding=\"ascii\") as file_in:\n        data = parse_swarm_mio_file(file_in)\n\n    return _get_coeff_swarm_mio_external(data, above_ionosphere), data\n\n\ndef _get_coeff_swarm_mio_external(data, above_ionosphere):\n    \"\"\" Create coefficient object for the given source data. \"\"\"\n    indices = data[\"nm\"]\n    coefficients = data[\"qs\"]\n    if above_ionosphere:\n        is_internal = True\n        coefficients = convert_external_mio_coeff(\n            data[\"degree_max\"], indices, coefficients, data[\"height\"]\n        )\n    else:\n        is_internal = False\n\n    return SparseSHCoefficientsMIO(\n        indices, coefficients,\n        ps_extent=(data[\"pmin\"], data[\"pmax\"], data[\"smin\"], data[\"smax\"]),\n        is_internal=is_internal,\n    )\n\n\ndef convert_external_mio_coeff(degree, indices, coefficients, height):\n    \"\"\" Convert external coefficients to internal ones. \"\"\"\n    nrrad = -(1.0 + height/MIO_EARTH_RADIUS)\n    order = arange(degree + 1, dtype='float')\n    scale = (order/(order + 1)) * nrrad**(2*order + 1)\n    return (scale[indices[:, 0]] * coefficients.transpose()).transpose()\n", "meta": {"hexsha": "9a3bfb542708857010d558ce45303e87007ea3fb", "size": 4884, "ext": "py", "lang": "Python", "max_stars_repo_path": "geoist/magmod/magnetic_model/loader_mio.py", "max_stars_repo_name": "CHEN-Zhaohui/geoist", "max_stars_repo_head_hexsha": "06a00db3e0ed3d92abf3e45b7b3bfbef6a858a5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 53, "max_stars_repo_stars_event_min_datetime": "2018-11-17T03:29:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T02:36:25.000Z", "max_issues_repo_path": "geoist/magmod/magnetic_model/loader_mio.py", "max_issues_repo_name": "CHEN-Zhaohui/geoist", "max_issues_repo_head_hexsha": "06a00db3e0ed3d92abf3e45b7b3bfbef6a858a5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-11-28T11:37:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-30T01:52:45.000Z", "max_forks_repo_path": "geoist/magmod/magnetic_model/loader_mio.py", "max_forks_repo_name": "CHEN-Zhaohui/geoist", "max_forks_repo_head_hexsha": "06a00db3e0ed3d92abf3e45b7b3bfbef6a858a5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2018-11-17T03:29:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T17:57:06.000Z", "avg_line_length": 37.8604651163, "max_line_length": 80, "alphanum_fraction": 0.680999181, "include": true, "reason": "from numpy", "num_tokens": 1115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.1668533741542905}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author  : Dengpan Fu (fdpan@mail.ustc.edu.cn)\n\nimport os, sys\nimport numpy as np\nimport time, pickle\nimport scipy.io as sio\nimport torch\nfrom torch.nn import functional as F\n\ndef load_data(path, dtype='torch', mat_type=False):\n    if not mat_type:\n        with open(path, 'rb') as f:\n            data = pickle.load(f)\n    else:\n        data = sio.loadmat(path)\n    q_feat, q_pid, q_cam = data['q_feat'], data['q_id'], data['q_cam']\n    g_feat, g_pid, g_cam = data['g_feat'], data['g_id'], data['g_cam']\n    if dtype == 'torch':\n        q_feat, g_feat = torch.from_numpy(q_feat), torch.from_numpy(g_feat)\n    out = [q_feat, q_pid, q_cam, g_feat, g_pid, g_cam]\n    return out\n\ndef pairwise_distance(x, y, dist_type='cosine'):\n    \"\"\" Calculate pairwise distance \"\"\"\n    if dist_type == 'euclidean':\n        m, n = x.size(0), y.size(0)\n        x = x.view(m, -1)\n        y = y.view(n, -1)\n        dist = torch.pow(x, 2).sum(1).unsqueeze(1).expand(m, n) + \\\n               torch.pow(y, 2).sum(1).unsqueeze(1).expand(n, m).t()\n        dist.addmm_(1, -2, x, y.t())\n    elif dist_type == 'cosine':\n        x = F.normalize(x)\n        y = F.normalize(y)\n        dist = torch.mm(x, y.t()).mul_(-1).add(1)\n    else:\n        raise TypeError(\"Unknown dist_type={}.\".format(dist_type))\n    return dist\n\ndef mah_dist(x, y, M=None):\n    \"\"\" Calculate Mahalanobis Distance if Matrix `M` provided, \n        Or calculate pairwise Euclidean distance\n    \"\"\"\n    if M is None:\n        return pairwise_distance(x, y, 'euclidean')\n    u = (x.matmul(M)*x).sum(1)\n    v = (y.matmul(M)*y).sum(1)\n    uv = x.matmul(M).matmul(y.t())\n    return u.view(-1, 1) + v.view(1, -1) - 2 * uv\n\ndef tensor2numpy(x):\n    if isinstance(x, torch.Tensor):\n        x = x.cpu().numpy()\n    if not isinstance(x, np.ndarray):\n        x = np.array(x)\n    return x\n\ndef numpy2tensor(x):\n    if isinstance(x, np.ndarray):\n        x = torch.from_numpy(x)\n    if not isinstance(x, torch.Tensor):\n        x = torch.Tensor(x)\n    return x\n\ndef print_scores(mAP, cmc_scores, p_str=''):\n    if p_str:\n        print('{:<15}:'.format(p_str), end='')\n    print(('[mAP: {:5.2%}], [cmc1: {:5.2%}], [cmc5: {:5.2%}],' \n        ' [cmc10: {:5.2%}]').format(mAP, *cmc_scores[[0, 4, 9]]))\n\ndef compute_mAP(index, good_index, junk_index):\n    ap = 0\n    cmc = torch.IntTensor(len(index)).zero_()\n    if good_index.size==0:   # if empty\n        cmc[0] = -1\n        return ap,cmc\n\n    # remove junk_index\n    mask = np.in1d(index, junk_index, invert=True)\n    index = index[mask]\n\n    # find good_index index\n    ngood = len(good_index)\n    mask = np.in1d(index, good_index)\n    rows_good = np.where(mask)[0]\n\n    cmc[rows_good[0]:] = 1\n    d_recall = 1.0/ngood\n    precision = (np.arange(len(rows_good), dtype=np.float) + 1) / (rows_good + 1)\n    if rows_good[0] == 0:\n        old_precision = np.ones(len(rows_good))\n        old_precision[1:] = np.arange(1, len(rows_good), dtype=np.float) / rows_good[1:]\n    else:\n        old_precision = np.arange(len(rows_good), dtype=np.float) / rows_good\n    ap = np.sum((precision + old_precision) / 2. * d_recall)\n\n    return ap, cmc\n\ndef compute_score(dist, q_id, q_cam, g_id, g_cam, verbose=True, out_aps=False):\n    dist = tensor2numpy(dist)\n    q_id, q_cam = tensor2numpy(q_id), tensor2numpy(q_cam)\n    g_id, g_cam = tensor2numpy(g_id), tensor2numpy(g_cam)\n    t1 = time.time()\n    cmc = torch.IntTensor(len(g_id)).zero_()\n    ap = 0.0\n    aps = []\n    for i in range(len(q_id)):\n        index = dist[i].argsort()\n        ql, qc, gl, gc = q_id[i], q_cam[i], g_id, g_cam\n\n        good_index = np.where((gl==ql) & (gc!=qc))[0]\n        junk_index = np.where(((gl==ql) & (gc==qc)) | (gl==-1))[0]\n\n        ap_tmp, cmc_tmp = compute_mAP(index, good_index, junk_index)\n        aps.append(ap_tmp)\n        if cmc_tmp[0]==-1:\n            continue\n        cmc = cmc + cmc_tmp\n        ap += ap_tmp\n        if verbose and i % 500 == 0:\n            print(\"Precessing [{:d}/{:d}], Using: {:.3f}s ...\".format(\n                i+1, len(q_id), time.time() - t1))\n\n    cmc = cmc.float()\n    cmc = cmc/len(q_id) #average cmc\n    ap = ap/len(q_id)\n    if not out_aps:\n        return ap, cmc\n    else:\n        return ap, cmc, aps\n\n", "meta": {"hexsha": "7445a88080a079423576f71885616dd066405372", "size": 4233, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils.py", "max_stars_repo_name": "DengpanFu/IIA", "max_stars_repo_head_hexsha": "07c9e23f2b60cdd84b041d5fc11d20c9a9439465", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-22T16:21:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-19T02:43:12.000Z", "max_issues_repo_path": "utils.py", "max_issues_repo_name": "DengpanFu/IIA", "max_issues_repo_head_hexsha": "07c9e23f2b60cdd84b041d5fc11d20c9a9439465", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils.py", "max_forks_repo_name": "DengpanFu/IIA", "max_forks_repo_head_hexsha": "07c9e23f2b60cdd84b041d5fc11d20c9a9439465", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5895522388, "max_line_length": 88, "alphanum_fraction": 0.5747696669, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.331119752830196, "lm_q1q2_score": 0.16685328663519974}}
{"text": "# Authors: Sai Nudurupati & Erkan Istanbulluoglu, 21May15\n# Edited: 15Jul16 - to conform to Landlab version 1.\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nfrom landlab import load_params\nfrom landlab.plot import imshow_grid\nfrom landlab.components import (PrecipitationDistribution, Radiation,\n                                PotentialEvapotranspiration, SoilMoisture,\n                                Vegetation, VegCA)\n\nGRASS = 0\nSHRUB = 1\nTREE = 2\nBARE = 3\nSHRUBSEEDLING = 4\nTREESEEDLING = 5\n\n\ndef compose_veg_grid(grid, percent_bare=0.4, percent_grass=0.2,\n                     percent_shrub=0.2, percent_tree=0.2):\n    \"\"\"Compose spatially distribute PFT.\"\"\"\n    no_cells = grid.number_of_cells\n    shrub_point = int(percent_bare * no_cells)\n    tree_point = int((percent_bare + percent_shrub) * no_cells)\n    grass_point = int((1 - percent_grass) * no_cells)\n\n    veg_grid = np.full(grid.number_of_cells, BARE, dtype=int)\n    veg_grid[shrub_point:tree_point] = SHRUB\n    veg_grid[tree_point:grass_point] = TREE\n    veg_grid[grass_point:] = GRASS\n\n    np.random.shuffle(veg_grid)\n    return veg_grid\n\n\ndef initialize(data, grid, grid1):\n    \"\"\"Initialize random plant type field.\n\n    Plant types are defined as the following:\n\n    *  GRASS = 0\n    *  SHRUB = 1\n    *  TREE = 2\n    *  BARE = 3\n    *  SHRUBSEEDLING = 4\n    *  TREESEEDLING = 5\n    \"\"\"\n    grid1.at_cell['vegetation__plant_functional_type'] = compose_veg_grid(\n        grid1, percent_bare=data['percent_bare_initial'],\n        percent_grass=data['percent_grass_initial'],\n        percent_shrub=data['percent_shrub_initial'],\n        percent_tree=data['percent_tree_initial'])\n\n    # Assign plant type for representative ecohydrologic simulations\n    grid.at_cell['vegetation__plant_functional_type'] = np.arange(6)\n    grid1.at_node['topographic__elevation'] = np.full(grid1.number_of_nodes,\n                                                      1700.)\n    grid.at_node['topographic__elevation'] = np.full(grid.number_of_nodes,\n                                                     1700.)\n    precip_dry = PrecipitationDistribution(\n        mean_storm_duration=data['mean_storm_dry'],\n        mean_interstorm_duration=data['mean_interstorm_dry'],\n        mean_storm_depth=data['mean_storm_depth_dry'])\n    precip_wet = PrecipitationDistribution(\n        mean_storm_duration=data['mean_storm_wet'],\n        mean_interstorm_duration=data['mean_interstorm_wet'],\n        mean_storm_depth=data['mean_storm_depth_wet'])\n\n    radiation = Radiation(grid)\n    pet_tree = PotentialEvapotranspiration(grid, method=data['PET_method'],\n                                           MeanTmaxF=data['MeanTmaxF_tree'],\n                                           delta_d=data['DeltaD'])\n    pet_shrub = PotentialEvapotranspiration(grid, method=data['PET_method'],\n                                            MeanTmaxF=data['MeanTmaxF_shrub'],\n                                            delta_d=data['DeltaD'])\n    pet_grass = PotentialEvapotranspiration(grid, method=data['PET_method'],\n                                            MeanTmaxF=data['MeanTmaxF_grass'],\n                                            delta_d=data['DeltaD'])\n    soil_moisture = SoilMoisture(grid, **data) # Soil Moisture object\n    vegetation = Vegetation(grid, **data) # Vegetation object\n    vegca = VegCA(grid1, **data) # Cellular automaton object\n\n    # Initializing inputs for Soil Moisture object\n    grid.at_cell['vegetation__live_leaf_area_index'] = (\n        1.6 * np.ones(grid.number_of_cells))\n    grid.at_cell['soil_moisture__initial_saturation_fraction'] = (\n        0.59 * np.ones(grid.number_of_cells))\n\n    return (precip_dry, precip_wet, radiation, pet_tree, pet_shrub,\n            pet_grass, soil_moisture, vegetation, vegca)\n\n\ndef empty_arrays(n, grid, grid1):\n    precip = np.empty(n) # Record precipitation\n    inter_storm_dt = np.empty(n) # Record inter storm duration\n    storm_dt = np.empty(n) # Record storm duration\n    time_elapsed = np.empty(n) # To record time elapsed from the start of simulation\n\n    # Cumulative Water Stress\n    veg_type = np.empty([n / 55, grid1.number_of_cells], dtype=int)\n    daily_pet = np.zeros([365, grid.number_of_cells])\n    rad_factor = np.empty([365, grid.number_of_cells])\n    EP30 = np.empty([365, grid.number_of_cells])\n\n    # 30 day average PET to determine season\n    pet_threshold = 0  # Initializing pet_threshold to ETThresholddown\n    return (precip, inter_storm_dt, storm_dt, time_elapsed, veg_type,\n            daily_pet, rad_factor, EP30, pet_threshold)\n\n\ndef create_pet_lookup(radiation, pet_tree, pet_shrub, pet_grass, daily_pet,\n                      rad_factor, EP30, grid):\n    for i in range(0, 365):\n        pet_tree.update(float(i) / 365.25)\n        pet_shrub.update(float(i) / 365.25)\n        pet_grass.update(float(i) / 365.25)\n        daily_pet[i] = [pet_grass._PET_value, pet_shrub._PET_value,\n                   pet_tree._PET_value, 0., pet_shrub._PET_value,\n                   pet_tree._PET_value]\n        radiation.update(float(i) / 365.25)\n        rad_factor[i] = grid.at_cell['radiation__ratio_to_flat_surface']\n\n        if i < 30:\n            if i == 0:\n                EP30[0] = daily_pet[0]\n            else:\n                EP30[i] = np.mean(daily_pet[:i], axis=0)\n        else:\n            EP30[i] = np.mean(daily_pet[i - 30:i], axis=0)\n\n\ndef save(sim, inter_storm_dt, storm_dt, precip, veg_type, yrs,\n         walltime, time_elapsed):\n    np.save(sim + '_Tb', inter_storm_dt)\n    np.save(sim + '_Tr', storm_dt)\n    np.save(sim + '_P', precip)\n    np.save(sim + '_VegType', veg_type)\n    np.save(sim + '_Years', yrs)\n    np.save(sim + '_Time_Consumed_minutes', walltime)\n    np.save(sim + '_CurrentTime', time_elapsed)\n\n\ndef plot(sim, grid, veg_type, yrs, yr_step=10):\n    pic = 0\n    years = range(0, yrs)\n    cmap = mpl.colors.ListedColormap(\n        ['green', 'red', 'black', 'white', 'red', 'black'])\n    bounds = [-0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5]\n    norm = mpl.colors.BoundaryNorm(bounds, cmap.N)\n    print 'Plotting cellular field of Plant Functional Type'\n    print 'Green - Grass; Red - Shrubs; Black - Trees; White - Bare'\n\n    # Plot images to make gif.\n    for year in range(0, yrs, yr_step):\n        filename = 'year_' + \"%05d\" % year\n        pic += 1\n        plt.figure(pic, figsize=(10, 8))\n        imshow_grid(grid, veg_type[year], values_at='cell', cmap=cmap,\n                    grid_units=('m', 'm'), norm=norm, limits=[0, 5],\n                    allow_colorbar=False)\n        plt.title(filename, weight='bold', fontsize=22)\n        plt.xlabel('X (m)', weight='bold', fontsize=18)\n        plt.ylabel('Y (m)', weight='bold', fontsize=18)\n        plt.xticks(fontsize=14, weight='bold')\n        plt.yticks(fontsize=14, weight='bold')\n        plt.savefig(sim + '_' + filename)\n\n    grass_cov = np.empty(yrs)\n    shrub_cov = np.empty(yrs)\n    tree_cov = np.empty(yrs)\n    grid_size = float(veg_type.shape[1])\n\n    for x in range(0, yrs):\n        grass_cov[x] = (veg_type[x][veg_type[x] == GRASS].size / grid_size) * 100\n        shrub_cov[x] = ((veg_type[x][veg_type[x] == SHRUB].size / grid_size) *\n                        100 + (veg_type[x][veg_type[x] == SHRUBSEEDLING].size /\n                        grid_size) * 100)\n        tree_cov[x] = ((veg_type[x][veg_type[x] == TREE].size / grid_size) *\n                       100 + (veg_type[x][veg_type[x] == TREESEEDLING].size /\n                       grid_size) * 100)\n\n    pic += 1\n    plt.figure(pic, figsize=(10, 8))\n    plt.plot(years, grass_cov, '-g', label='Grass', linewidth=4)\n    plt.hold(True)\n    plt.plot(years, shrub_cov, '-r', label='Shrub', linewidth=4)\n    plt.hold(True)\n    plt.plot(years, tree_cov, '-k', label='Tree', linewidth=4)\n    plt.ylabel('% Area Covered by Plant Type', weight='bold', fontsize=18)\n    plt.xlabel('Time in years', weight='bold', fontsize=18)\n    plt.xticks(fontsize=12, weight='bold')\n    plt.yticks(fontsize=12, weight='bold')\n    plt.legend(loc=0, prop={'size': 16, 'weight': 'bold'})\n    plt.savefig(sim + '_percent_cover')\n", "meta": {"hexsha": "8bfa387650c69b7fe65565f7e4d4d9fa2490cece", "size": 8090, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/ecohydrology_flat_surface/ecohyd_functions_flat.py", "max_stars_repo_name": "sainjacobs/drivers", "max_stars_repo_head_hexsha": "7f28944e5b30204572cdcfef00d32d9bb1b68b37", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2015-08-20T18:56:23.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-25T13:41:41.000Z", "max_issues_repo_path": "scripts/ecohydrology_flat_surface/ecohyd_functions_flat.py", "max_issues_repo_name": "sainjacobs/drivers", "max_issues_repo_head_hexsha": "7f28944e5b30204572cdcfef00d32d9bb1b68b37", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/ecohydrology_flat_surface/ecohyd_functions_flat.py", "max_forks_repo_name": "sainjacobs/drivers", "max_forks_repo_head_hexsha": "7f28944e5b30204572cdcfef00d32d9bb1b68b37", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-05-24T03:18:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-07T20:39:19.000Z", "avg_line_length": 41.0659898477, "max_line_length": 84, "alphanum_fraction": 0.6224969098, "include": true, "reason": "import numpy", "num_tokens": 2176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.331119752830196, "lm_q1q2_score": 0.16685328663519974}}
{"text": "\"\"\"Data input for A.S.A.P model.\"\"\"\nfrom __future__ import print_function, division, unicode_literals\n\nimport os\nimport pickle\n\nimport numpy as np\n\nimport emcee\n\nfrom astropy.table import Table, Column\nfrom astropy.cosmology import FlatLambdaCDM\n\nfrom . import ensemble\n\n\n__all__ = [\"load_obs\", \"load_um\", \"save_pickle\", \"load_pickle\", \"load_npz_results\", \n           \"save_results_to_npz\"]\n\n\ndef load_dsigma(cfg, verbose=False):\n    \"\"\"Read in the observed weak lensing sigma profiles.\n\n    Parameters\n    ----------\n    cfg : dict\n        Configuration parameters for the observations.\n    verbose : boolen\n        Blah, blah, blah\n\n    Return\n    ------\n    \"\"\"\n    # Now the DeltaSigma data are stored in a numpy array\n    # Mass bin is defined by: min_logm1, min_logm2, max_logm1, and max_logm2\n    wl_dsigma = np.load(cfg['dsigma'])\n\n    cfg['wl_n_bin'] = len(wl_dsigma)\n    if verbose:\n        if cfg['wl_n_bin'] > 1:\n            print(\"# There are %d DSigma profiles in this sample\" %\n                  cfg['wl_n_bin'])\n        else:\n            print(\"# There is 1 DSigma profile in this sample\")\n\n    return wl_dsigma\n\n\ndef load_obs(cfg, verbose=True):\n    \"\"\"Load the observed data.\n\n    Parameters\n    ----------\n    cfg : dict\n        Configuration parameters for the observations.\n    verbose : boolen\n        Blah, blah, blah\n\n    Return\n    ------\n        Dictionary that contains all the observations.\n\n    \"\"\"\n    # Galaxy catalog.\n    mass = Table.read(cfg['galaxy'])\n    minn = np.array(mass[cfg['minn_col']])\n    mtot = np.array(mass[cfg['mtot_col']])\n\n    # Observed DeltaSigma profiles\n    wl_dsigma = load_dsigma(cfg, verbose=verbose)\n    cfg['dsigma_n_data'] = len(wl_dsigma[0]['dsigma']) * cfg['wl_n_bin']\n\n    # Stellar mass functions\n    if os.path.splitext(cfg['smf_inn'])[-1] == '.npy':\n        smf_inn = np.load(cfg['smf_inn'])\n    else:\n        smf_inn = Table.read(cfg['smf_inn'])\n\n    if os.path.splitext(cfg['smf_tot'])[-1] == '.npy':\n        smf_tot = np.load(cfg['smf_tot'])\n    else:\n        smf_tot = Table.read(cfg['smf_tot'])\n\n    # This is for a specific format of SMF\n    cfg['smf_inn_min'] = np.min(smf_inn['logm_0'])\n    cfg['smf_inn_max'] = np.max(smf_inn['logm_1'])\n    cfg['smf_inn_nbin'] = len(smf_inn)\n\n    cfg['smf_tot_min'] = np.min(smf_tot['logm_0'])\n    cfg['smf_tot_max'] = np.max(smf_tot['logm_1'])\n    cfg['smf_tot_nbin'] = len(smf_tot)\n\n    cfg['ngal_use'] = ((mtot >= cfg['smf_tot_min']) &\n                       (minn >= cfg['smf_inn_min'])).sum()\n\n    cfg['min_mtot'] = cfg['smf_tot_min'] - 0.1\n\n    cfg['smf_n_data'] = cfg['smf_tot_nbin'] + cfg['smf_inn_nbin']\n\n    # Covariance of the SMF\n    if cfg['smf_cov'] is not None:\n        smf_cov = np.load(cfg['smf_cov'])\n        assert cfg['smf_n_data'] == len(smf_cov)\n    else:\n        smf_cov = None\n\n    if verbose:\n        print(\"# SMF for total stellar mass: \")\n        print(\"  %7.4f -- %7.4f in %d bins\" % (cfg['smf_tot_min'],\n                                               cfg['smf_tot_max'],\n                                               cfg['smf_tot_nbin']))\n        print(\"# SMF for inner stellar mass: \")\n        print(\"  %7.4f -- %7.4f in %d bins\" % (cfg['smf_inn_min'],\n                                               cfg['smf_inn_max'],\n                                               cfg['smf_inn_nbin']))\n\n    logms_inn = minn[mtot >= cfg['smf_tot_min']]\n    logms_tot = mtot[mtot >= cfg['smf_tot_min']]\n\n    if os.path.isfile(cfg['smf_full']):\n        smf_full = Table.read(cfg['smf_full'])\n        smf_full[smf_full['smf'] <= 0]['smf'] = 1E-8\n        smf_full[smf_full['smf_low'] <= 0]['smf_low'] = 1E-9\n        smf_full[smf_full['smf_upp'] <= 0]['smf_upp'] = 1E-7\n        smf_full = smf_full\n    else:\n        smf_full = None\n\n    if verbose:\n        print(\"# For inner stellar mass: \")\n        print(\"    %d bins at %5.2f < logMinn < %5.2f\" %\n              (cfg['smf_inn_nbin'], cfg['smf_inn_min'],\n               cfg['smf_inn_max']))\n        print(\"# For total stellar mass: \")\n        print(\"    %d bins at %5.2f < logMtot < %5.2f\" %\n              (cfg['smf_tot_nbin'], cfg['smf_tot_min'],\n               cfg['smf_tot_max']))\n\n    # Redshift range and observed volume\n    cosmo = FlatLambdaCDM(H0=cfg['h0'] * 100, Om0=cfg['omega_m'])\n    cfg['volume'] = (\n        (cosmo.comoving_volume(np.nanmax(mass[cfg['z_col']])) - \n         cosmo.comoving_volume(np.nanmin(mass[cfg['z_col']]))) *\n        (cfg['area'] / 41254.0)).value\n\n    if verbose:\n        print(\"# The volume of the HSC data is %15.2f Mpc^3\" % cfg['volume'])\n\n    return {'mass': mass, 'minn': minn, 'mtot': mtot,\n            'logms_inn': logms_inn, 'logms_tot': logms_tot,\n            'wl_dsigma': wl_dsigma,\n            'smf_inn': smf_inn, 'smf_tot': smf_tot,\n            'smf_full': smf_full, 'smf_cov': smf_cov}, cfg\n\n\ndef load_um(cfg, verbose=True):\n    \"\"\"Load the UniverseMachine data.\n\n    Parameters\n    ----------\n    cfg : dict\n        Configuration parameters for the UniverseMachine model.\n    verbose : boolen\n        Blah, blah, blah\n\n    Return\n    ------\n        Dictionary that contains all the UniverseMachine data.\n\n    \"\"\"\n    # Mock galaxy catalog\n    um_mock = Table(np.load(cfg['galaxy']))\n\n    # Only select the useful columns\n    cols_use = ['halo_id', 'upid', 'sm', 'icl', 'x', 'y', 'z',\n                'mtot_galaxy', 'mstar_mhalo', 'logms_gal',\n                'logms_icl', 'logms_tot', 'logms_halo',\n                'logmh_vir', 'logmh_peak', 'logmh_host']\n    um_mock_use = um_mock[cols_use]\n\n    # Value added a few useful columns\n    um_mock_use.add_column(Column(data=(um_mock_use['mtot_galaxy'] /\n                                        um_mock_use['mstar_mhalo']),\n                                  name='frac_cen_tot'))\n    um_mock_use.add_column(Column(data=(um_mock_use['sm'] /\n                                        um_mock_use['mtot_galaxy']),\n                                  name='frac_ins_cen'))\n    um_mock_use.add_column(Column(data=(um_mock_use['icl'] /\n                                        um_mock_use['mtot_galaxy']),\n                                  name='frac_exs_cen'))\n    um_mock_use = um_mock_use.as_array()\n\n    # Load the pre-compute lensing pairs\n    um_mass_encl = np.load(cfg['dsigma'])\n    assert len(um_mock_use) == len(um_mass_encl)\n\n    # Mask for central galaxies\n    mask_central = (um_mock_use['upid'] == -1)\n    if verbose:\n        print(\"# %d out of %d galaxies are central\" % (\n            mask_central.sum(), len(um_mock_use)))\n\n    # Mask for massive enough halo\n    mask_mass = (um_mock_use[cfg['halo_col']] >= cfg['min_mvir'])\n\n    return {'um_mock': um_mock_use[mask_mass],\n            'um_mass_encl': um_mass_encl[mask_mass, :],\n            'mask_central': mask_central[mask_mass]}\n\n\ndef save_pickle(pickle_file, data):\n    \"\"\"Save some data in pickle format.\n\n    Parameters\n    ----------\n    pickle_file : string\n        Name of the output Pickle file.\n    data : array or dict\n        Some data\n    \"\"\"\n    pickle.dump(data, open(pickle_file, 'wb'))\n    pickle_file.close()\n\n    return\n\n\ndef load_pickle(pickle_file):\n    \"\"\"Load the pickled pickle.\n\n    Parameters\n    ----------\n    pickle_file : string\n        Name of the output Pickle file.\n    \"\"\"\n    data = pickle.load(open(pickle_file, 'rb'))\n    pickle_file.close()\n\n    return data\n\n\ndef load_npz_results(mcmc_file):\n    \"\"\"Retrieve the MCMC results from .npz file.\"\"\"\n    mcmc_data = np.load(mcmc_file)\n\n    return (mcmc_data['samples'], mcmc_data['chains'],\n            mcmc_data['lnprob'], mcmc_data['best'],\n            mcmc_data['position'], mcmc_data['acceptance'])\n\n\ndef save_results_to_npz(mcmc_results, mcmc_sampler, mcmc_file,\n                        mcmc_ndims, verbose=True, frac=0.1, tol=20, c=5):\n    \"\"\"Save the MCMC run results.\"\"\"\n    mcmc_position, mcmc_lnprob, _ = mcmc_results\n\n    mcmc_samples = mcmc_sampler.chain[:, :, :].reshape((-1, mcmc_ndims))\n    mcmc_chains = mcmc_sampler.chain\n    mcmc_lnprob = mcmc_sampler.lnprobability\n\n    mcmc_params_stats = ensemble.mcmc_samples_stats(mcmc_samples)\n\n    # Best parameter using the best log(prob)\n    mcmc_best = mcmc_sampler.flatchain[mcmc_sampler.flatlnprobability.argmax()]\n\n    # Best parameters using the mean of the last few samples\n    _, n_step, n_dim = mcmc_chains.shape\n    mcmc_mean = np.nanmean(\n        mcmc_chains[:, -int(n_step * frac):, :].reshape([-1, n_dim]), axis=0)\n\n    # Auto-correlation time\n    try:\n        tau = mcmc_sampler.get_autocorr_time(quiet=False, tol=tol, c=c)\n        print(\"# Current autocorrelation time is\", tau)\n    except emcee.autocorr.AutocorrError:\n        print(\"# The chain is shorter than {} x tau right now...\".format(tol))\n        tau = None\n\n    np.savez(mcmc_file,\n             samples=mcmc_samples, lnprob=np.array(mcmc_lnprob),\n             best=np.array(mcmc_best), mean=np.asarray(mcmc_mean),\n             chains=mcmc_chains, tau=tau,\n             position=np.asarray(mcmc_position),\n             acceptance=np.array(mcmc_sampler.acceptance_fraction))\n\n    if verbose:\n        print(\"#------------------------------------------------------\")\n        print(\"#  Mean acceptance fraction\",\n              np.mean(mcmc_sampler.acceptance_fraction))\n        print(\"#------------------------------------------------------\")\n        print(\"#  Best ln(Probability): %11.5f\" % np.max(mcmc_lnprob))\n        print(mcmc_best)\n        print(\"#------------------------------------------------------\")\n        print(\"#  Best parameters (mean):\")\n        print(mcmc_mean)\n        print(\"#------------------------------------------------------\")\n        for param_stats in mcmc_params_stats:\n            print(param_stats)\n        print(\"#------------------------------------------------------\")\n", "meta": {"hexsha": "5cdb7b752ba5e7032b5851b27fc5d3e5d47c82a2", "size": 9742, "ext": "py", "lang": "Python", "max_stars_repo_path": "asap/io.py", "max_stars_repo_name": "dr-guangtou/asap", "max_stars_repo_head_hexsha": "4b796b9708ee1a1d854d4ddf6d5c6e811941f55e", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-11-06T06:50:35.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-06T14:24:05.000Z", "max_issues_repo_path": "asap/io.py", "max_issues_repo_name": "dr-guangtou/asap", "max_issues_repo_head_hexsha": "4b796b9708ee1a1d854d4ddf6d5c6e811941f55e", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-11-02T17:55:32.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-02T17:55:32.000Z", "max_forks_repo_path": "asap/io.py", "max_forks_repo_name": "dr-guangtou/asap", "max_forks_repo_head_hexsha": "4b796b9708ee1a1d854d4ddf6d5c6e811941f55e", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6912751678, "max_line_length": 84, "alphanum_fraction": 0.5653869842, "include": true, "reason": "import numpy,from astropy", "num_tokens": 2629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.16685327665694716}}
{"text": "\"\"\"\n  Module for parsing intermediate data from Hipparcos and Gaia.\n  For Hipparcos (both reductions) and Gaia, the scan angle theta is the angle between the north\n  equitorial pole (declination) and the along-scan axis, defined as positive if east of the north pole\n  (positive for increasing RA).\n\n  Author:\n    G. Mirek Brandt\n    Daniel Michalik\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats, special\nimport warnings\nfrom ast import literal_eval\nimport os\nimport re\nimport glob\nimport itertools\nfrom math import ceil, floor\nimport pkg_resources\n\nfrom astropy.time import Time\nfrom astropy.table import QTable, Column, Table\n\nfrom htof import settings as st\nfrom htof.utils.data_utils import merge_consortia, safe_concatenate\nfrom htof.utils.parse_utils import gaia_obmt_to_tcb_julian_year\n\nimport abc\n\n\nclass DataParser(object):\n    \"\"\"\n    Base class for parsing Hip1, Hip2 and Gaia data. self.epoch, self.covariance_matrix and self.scan_angle are saved\n    as pandas.DataFrame. use .values (e.g. self.epoch.values) to call the ndarray version.\n    \"\"\"\n    def __init__(self, scan_angle=None, epoch=None, residuals=None, inverse_covariance_matrix=None,\n                 along_scan_errs=None, parallax_factors=None, meta=None):\n        if meta is None:\n            meta = {}\n        self.scan_angle = pd.Series(scan_angle, dtype=np.float64)\n        self._epoch = pd.DataFrame(epoch, dtype=np.float64)\n        self.residuals = pd.Series(residuals, dtype=np.float64)\n        self.parallax_factors = pd.Series(parallax_factors, dtype=np.float64)\n        self.along_scan_errs = pd.Series(along_scan_errs, dtype=np.float64)\n        self.inverse_covariance_matrix = inverse_covariance_matrix\n        self.meta = meta\n\n    @staticmethod\n    def get_intermediate_data_file_path(star_id: str, intermediate_data_directory: str):\n        star_id = str(star_id)\n        filepath = os.path.join(os.path.join(intermediate_data_directory, '**/'), '*' + star_id + '*')\n        filepath_list = glob.glob(filepath, recursive=True)\n        if len(filepath_list) != 1:\n            # search for the star id with leading zeros stripped\n            filepath = os.path.join(os.path.join(intermediate_data_directory, '**/'), '*' + star_id.lstrip('0') + '*')\n            filepath_list = glob.glob(filepath, recursive=True)\n        if len(filepath_list) != 1:\n            # search for files with the full 6 digit hipparcos string\n            filepath = os.path.join(os.path.join(intermediate_data_directory, '**/'), '*' + star_id.zfill(6) + '*')\n            filepath_list = glob.glob(filepath, recursive=True)\n        if len(filepath_list) != 1:\n            # take the file with which contains only the hip id if there are multiple matches\n            filepath = os.path.join(os.path.join(intermediate_data_directory, '**/'), '*' + star_id.lstrip('0') + '*')\n            filepath_list = match_filename(glob.glob(filepath, recursive=True), star_id)\n        if len(filepath_list) == 0:\n            raise FileNotFoundError('No file with name containing {0} or {1} or {2} found in {3}'\n                                    ''.format(star_id, star_id.lstrip('0'), star_id.zfill(6), intermediate_data_directory))\n        if len(filepath_list) > 1:\n            raise FileNotFoundError('Unable to find the correct file among the {0} files containing {1}'\n                                    'found in {2}'.format(len(filepath_list), star_id, intermediate_data_directory))\n        return filepath_list[0]\n\n    @staticmethod\n    def read_intermediate_data_file(star_id: str, intermediate_data_directory: str, skiprows, header, sep):\n        iad_filepath = DataParser.get_intermediate_data_file_path(star_id, intermediate_data_directory)\n        data = pd.read_csv(iad_filepath, sep=sep, skiprows=skiprows, header=header, engine='python')\n        return data\n\n    @abc.abstractmethod\n    def parse(self, star_id: str, intermediate_data_parent_directory: str, **kwargs):\n        pass    # pragma: no cover\n\n    def julian_day_epoch(self):\n        return self._epoch.values.flatten()\n\n    @property\n    def epoch(self):\n        return self._epoch.values.flatten()\n\n    def calculate_inverse_covariance_matrices(self, cross_scan_along_scan_var_ratio=np.inf):\n        self.inverse_covariance_matrix = calc_inverse_covariance_matrices(self.scan_angle,\n                                                                          cross_scan_along_scan_var_ratio=cross_scan_along_scan_var_ratio,\n                                                                          along_scan_errs=self.along_scan_errs,\n                                                                          star_id=self.meta.get('star_id', None))\n\n    def write(self, path: str, *args, **kwargs):\n        \"\"\"\n        :param path: str. filepath to write out the processed data.\n        :param args: arguments for astropy.table.Table.write()\n        :param kwargs: keyword arguments for astropy.table.Table.write()\n        :return: None\n\n        Note: The IntermediateDataParser.inverse_covariance_matrix are added to the table as strings\n        so that they are easily writable. The icov matrix is saved a string.\n        Each element of t['icov'] can be recovered with ast.literal_eval(t['icov'][i])\n        where i is the index. ast.literal_eval(t['icov'][i]) will return a 2x2 list.\n        \"\"\"\n        t = self.as_table()\n        # transform icov matrices as writable strings.\n        t['icov'] = [str(icov.tolist()) for icov in t['icov']]\n        t.write(path, fast_writer=False, *args, **kwargs)\n\n    def as_table(self):\n        \"\"\"\n        :return: astropy.table.QTable\n                 The IntermediateDataParser object tabulated.\n                 This table has as columns all of the attributes of IntermediateDataParser.\n\n                 For any attribute which is empty or None, the column will contain zeros.\n        \"\"\"\n        cols = [self.scan_angle, self.julian_day_epoch(), self.residuals, self.along_scan_errs, self.inverse_covariance_matrix]\n        cols = [Column(col) for col in cols]\n        # replacing incorrect length columns with empties.\n        cols = [col if len(col) == len(self) else Column(None, length=len(self)) for col in cols]\n\n        t = QTable(cols, names=['scan_angle', 'julian_day_epoch', 'residuals', 'along_scan_errs', 'icov'])\n        return t\n\n    def __add__(self, other):\n        all_scan_angles = pd.concat([self.scan_angle, other.scan_angle])\n        all_epoch = pd.concat([pd.DataFrame(self.julian_day_epoch()), pd.DataFrame(other.julian_day_epoch())])\n        all_residuals = pd.concat([self.residuals, other.residuals])\n        all_along_scan_errs = pd.concat([self.along_scan_errs, other.along_scan_errs])\n        # TODO: add parallax factors. Tricky because gaia missions do not have them.\n        all_inverse_covariance_matrix = safe_concatenate(self.inverse_covariance_matrix,\n                                                         other.inverse_covariance_matrix)\n\n        return DataParser(scan_angle=all_scan_angles, epoch=all_epoch, residuals=all_residuals,\n                          inverse_covariance_matrix=all_inverse_covariance_matrix,\n                          along_scan_errs=all_along_scan_errs)\n\n    def __radd__(self, other):\n        if other == 0:\n            return self\n        return self.__add__(other)\n\n    def __len__(self):\n        return len(self._epoch)\n\n\nclass GaiaData(DataParser):\n    DEAD_TIME_TABLE_NAME = None\n\n    def __init__(self, scan_angle=None, epoch=None, residuals=None, inverse_covariance_matrix=None,\n                 min_epoch=-np.inf, max_epoch=np.inf, along_scan_errs=None, meta=None):\n        super(GaiaData, self).__init__(scan_angle=scan_angle, along_scan_errs=along_scan_errs,\n                                       epoch=epoch, residuals=residuals, meta=meta,\n                                       inverse_covariance_matrix=inverse_covariance_matrix)\n        self.min_epoch = min_epoch\n        self.max_epoch = max_epoch\n\n    def parse(self, star_id, intermediate_data_directory, **kwargs):\n        self.meta['star_id'] = star_id\n        data = self.read_intermediate_data_file(star_id, intermediate_data_directory,\n                                                skiprows=0, header='infer', sep=r'\\s*,\\s*')\n        data = self.trim_data(data['ObservationTimeAtBarycentre[BarycentricJulianDateInTCB]'],\n                              data, self.min_epoch, self.max_epoch)\n        data = self.reject_dead_times(data['ObservationTimeAtBarycentre[BarycentricJulianDateInTCB]'], data)\n        self._epoch = data['ObservationTimeAtBarycentre[BarycentricJulianDateInTCB]']\n        self.scan_angle = data['scanAngle[rad]']\n\n    def trim_data(self, epochs, data, min_mjd, max_mjd):\n        valid = np.logical_and(epochs >= min_mjd, epochs <= max_mjd)\n        return data[valid].dropna()\n\n    def reject_dead_times(self, epochs, data):\n        # there will be different astrometric gaps for gaia DR2 and DR3 because rejection criteria may change.\n        # hence we have the appropriate parsers have different values for DEAD_TIME_TABLE_NAME.\n        if self.DEAD_TIME_TABLE_NAME is None:\n            # return the data if there is no dead time table specified.\n            return data\n        dead_time_table = Table.read(self.DEAD_TIME_TABLE_NAME)\n        # convert on board mission time (OBMT) to julian day\n        for col, newcol in zip(['start', 'end'], ['start_tcb_jd', 'end_tcb_jd']):\n            dead_time_table[newcol] = gaia_obmt_to_tcb_julian_year(dead_time_table[col]).jd\n        # make a mask of the epochs. Those that are within a dead time window have a value of 0 (masked)\n        valid = np.ones(len(data), dtype=bool)\n        for entry in dead_time_table:\n            valid[np.logical_and(epochs >= entry['start_tcb_jd'], epochs <= entry['end_tcb_jd'])] = 0\n        # reject the epochs which fall within a dead time window\n        data = data[valid].dropna()\n        return data\n\n\nclass DecimalYearData(DataParser):\n    def __init__(self, scan_angle=None, epoch=None, residuals=None, inverse_covariance_matrix=None,\n                 along_scan_errs=None, meta=None):\n        super(DecimalYearData, self).__init__(scan_angle=scan_angle, along_scan_errs=along_scan_errs,\n                                              epoch=epoch, residuals=residuals, meta=meta,\n                                              inverse_covariance_matrix=inverse_covariance_matrix)\n\n    def parse(self, star_id, intermediate_data_parent_directory, **kwargs):\n        pass  # pragma: no cover\n\n    def julian_day_epoch(self):\n        return Time(self._epoch.values.flatten(), format='decimalyear').jd\n\n\ndef calc_inverse_covariance_matrices(scan_angles, cross_scan_along_scan_var_ratio=np.inf,\n                                     along_scan_errs=None, star_id=None):\n    \"\"\"\n    :param scan_angles: pandas.DataFrame.\n            data frame with scan angles, e.g. as-is from IntermediateDataParser.read_intermediate_data_file.\n            scan_angles.values is a numpy array with the scan angles\n    :param cross_scan_along_scan_var_ratio: var_cross_scan / var_along_scan\n    :param along_scan_errs: array. array of len(scan_angles), the errors in the along scan direction, one for each\n    scan in scan_angles.\n    :return An ndarray with shape (len(scan_angles), 2, 2), e.g. an array of covariance matrices in the same order\n    as the scan angles\n    \"\"\"\n    if along_scan_errs is None or len(along_scan_errs) == 0:\n        along_scan_errs = np.ones_like(scan_angles.values.flatten())\n    if np.any(np.isclose(along_scan_errs, 0)):\n        warnings.warn(f'The IAD of {star_id} contained an along scan error that '\n                      'is zero. This is unphysical, the observation should '\n                      'probably have been marked as rejected. '\n                      'In order to compute the inverse covariance matrices for '\n                      'this source we are setting this AL error to a large '\n                      'number (1 arcsec) and continue. ', RuntimeWarning)\n        along_scan_errs[np.isclose(along_scan_errs, 0)] = 1000\n    icovariance_matrices = []\n    icov_matrix_in_scan_basis = np.array([[1, 0],\n                                         [0, 1/cross_scan_along_scan_var_ratio]])\n    for theta, err in zip(scan_angles.values.flatten(), along_scan_errs):\n        c, s = np.cos(theta), np.sin(theta)\n        Rot = np.array([[s, -c], [c, s]])\n        icov_matrix_in_ra_dec_basis = np.matmul(np.matmul(1/(err ** 2) * Rot, icov_matrix_in_scan_basis), Rot.T)\n        icovariance_matrices.append(icov_matrix_in_ra_dec_basis)\n    return np.array(icovariance_matrices)\n\n\nclass HipparcosOriginalData(DecimalYearData):\n    def __init__(self, scan_angle=None, epoch=None, residuals=None, inverse_covariance_matrix=None,\n                 along_scan_errs=None):\n        super(HipparcosOriginalData, self).__init__(scan_angle=scan_angle, along_scan_errs=along_scan_errs,\n                                                    epoch=epoch, residuals=residuals,\n                                                    inverse_covariance_matrix=inverse_covariance_matrix)\n\n    def parse(self, star_id, intermediate_data_directory, data_choice='MERGED'):\n        \"\"\"\n        :param star_id: a string which is just the number for the HIP ID.\n        :param intermediate_data_directory: the path (string) to the place where the intermediate data is stored, e.g.\n                Hip2/IntermediateData/resrec\n                note you have to specify the file resrec or absrec. We use the residual records, so specify resrec.\n        :param data_choice: 'FAST' or 'NDAC', 'BOTH', or 'MERGED. The standard is 'MERGED' which does a merger\n        of the 'NDAC' and 'FAST' data reductions in the same way as the hipparcos 1991.25 catalog. 'BOTH' keeps\n        both consortia's data in the IAD, which would be unphysical and is just for debugging. 'FAST' would keep\n        only the FAST consortia data, likewise only NDAC would be kept if you selected 'NDAC'.\n        \"\"\"\n        if (data_choice != 'NDAC') and (data_choice != 'FAST') and (data_choice != 'MERGED')\\\n                and (data_choice != 'BOTH'):\n            raise ValueError('data choice has to be either NDAC or FAST or MERGED or BOTH.')\n        self.meta['star_id'] = star_id\n        data = self.read_intermediate_data_file(star_id, intermediate_data_directory,\n                                                skiprows=10, header='infer', sep=r'\\s*\\|\\s*')\n        data = self._fix_unnamed_column(data)\n        data = self._select_data(data, data_choice)\n        # compute scan angles and observations epochs according to van Leeuwen & Evans 1998\n        #  10.1051/aas:1998218, eq. 11 & 12.\n        self.scan_angle = np.arctan2(data['IA3'], data['IA4'])  # unit radians, arctan2(sin, cos)\n        # Use the larger denominator when computing the epoch offset. \n        # This increases numerical precision and avoids NaNs if one of the two fields (IA3, IA4) is exactly zero.\n        self._epoch = 1991.25 + (data['IA6'] / data['IA3']).where(abs(data['IA3']) > abs(data['IA4']), (data['IA7'] / data['IA4']))\n        self.residuals = data['IA8']  # unit milli-arcseconds (mas)\n        self.along_scan_errs = data['IA9']  # unit milli-arcseconds\n        self.parallax_factors = data['IA5']\n\n    @staticmethod\n    def _select_data(data, data_choice):\n        # restrict intermediate data to either NDAC, FAST, or merge the NDAC and FAST results.\n        if data_choice == 'MERGED':\n            data = merge_consortia(data)\n        elif data_choice != 'BOTH':\n            data = data[data['IA2'].str.upper() == {'NDAC': 'N', 'FAST': 'F'}[data_choice]]\n        return data\n\n    @staticmethod\n    def _fix_unnamed_column(data, correct_key='IA2', col_idx=1):\n        data.rename(columns={data.columns[col_idx]: correct_key}, inplace=True)\n        return data\n\n\nclass HipparcosRereductionDVDBook(DecimalYearData):\n    def __init__(self, scan_angle=None, epoch=None, residuals=None, inverse_covariance_matrix=None,\n                 along_scan_errs=None, meta=None):\n        super(HipparcosRereductionDVDBook, self).__init__(scan_angle=scan_angle, along_scan_errs=along_scan_errs,\n                                                          epoch=epoch, residuals=residuals, meta=meta,\n                                                          inverse_covariance_matrix=inverse_covariance_matrix)\n        self._additional_rejected_epochs = {}  # epochs that need to be rejected due to the write out bug.\n        self._rejected_epochs = {}  # epochs that are known rejects, e.g.,\n        # those that have negative AL errors in the java tool\n\n    def read_header(self, star_id, intermediate_data_directory):\n        header = self.read_intermediate_data_file(star_id, intermediate_data_directory,\n                                                  skiprows=0, header=None, sep=r'\\s+')\n        return header\n\n    def parse(self, star_id, intermediate_data_directory, error_inflate=True, header_rows=1,\n              attempt_adhoc_rejection=True, **kwargs):\n        \"\"\"\n        :param: star_id:\n        :param: intermediate_data_directory:\n        :param: error_inflate: True if the along-scan errors are to be corrected by the inflation factor\n        according to Appendix B of D. Michalik et al. 2014. Only turn this off for tests, or if the parameters\n        required to compute the error inflation are unavailable.\n        :param: header_rows: int.\n        :return:\n\n        Compute scan angles and observations epochs from van Leeuwen 2007, table G.8\n        see also Figure 2.1, section 2.5.1, and section 4.1.2\n        NOTE: that the Hipparcos re-reduction book and the figures therein describe the\n        scan angle against the north ecliptic pole.\n        NOTE: In the actual intermediate astrometry data on the DVD the scan angle psi\n        is given in the equatorial system. This is similar to the original\n        Hipparcos and Gaia (Source: private communication between Daniel\n        Michalik and Floor van Leeuwen, April 2019), which define the scan angle theta\n        as East of the North equatorial pole. theta = pi / 2 - psi, \n        see Brandt et al. (2021), Section 2.2.2.\"\n        \"\"\"\n        self.meta['star_id'] = star_id\n        header = self.read_header(star_id, intermediate_data_directory)\n        data = self.read_intermediate_data_file(star_id, intermediate_data_directory,\n                                                skiprows=header_rows, header=None, sep=r'\\s+')\n        self.scan_angle = np.arctan2(data[3], data[4])  # data[3] = sin(theta) = cos(psi), data[4] = cos(theta) = sin(psi)\n        self._epoch = data[1] + 1991.25\n        self.residuals = data[5]  # unit milli-arcseconds (mas)\n        self.along_scan_errs = data[6]  # unit milli-arcseconds (mas)\n        self.parallax_factors = data[2]\n        self.meta['catalog_f2'] = header.iloc[0][6]\n        self.meta['catalog_soltype'] = header.iloc[0][4]\n        # TODO need to calculate f2 newly using htof. Like we do in the java tool.\n        n_transits, nparam, percent_rejected = header.iloc[0][2], get_nparam(header.iloc[0][4]), header.iloc[0][7]\n        if attempt_adhoc_rejection:\n            warnings.warn(f\"For source {self.meta['star_id']}. The DVD IAD does not indicate which observation epochs were \"\n                           \"rejected for the final solution. htof will attempt to find which epochs to \"\n                           \"reject in order to reproduce the catalog parameters. However, if this source \"\n                           \"also has some corrupted residuals (see Brandt et al. 2021, Section 4), then \"\n                           \"this will fail. We recommend you switch to using the IAD from the Java tool, \"\n                           \"since that version of the IAD indicates rejected epochs with negative \"\n                           \"uncertainties.\", UserWarning)\n            self.rejected_epochs = find_epochs_to_reject_DVD(self, n_transits, percent_rejected, nparam, self.meta['catalog_f2'])\n        if error_inflate:\n            # adjust the along scan errors so that the errors on the best fit parameters match the catalog.\n            self.along_scan_errs *= self.error_inflation_factor(n_transits, nparam, self.meta['catalog_f2'])\n        return header, data\n\n    @staticmethod\n    def error_inflation_factor(ntr, nparam, f2):\n        \"\"\"\n        :param ntr: int. Number of transits used in the catalog solution. I.e. this should be\n        N_transit_total - N_reject. So if N_reject is unknown, then the error inflation factor will be slightly wrong.\n        :param nparam: int. Number of parameters used in the solution (e.g. 5, 7, 9..)\n        :param f2: float. Goodness of fit metric. field F2 in the Hipparcos Re-reduction catalog.\n        :return: u. float.\n        The errors are to be scaled by u = Sqrt(Q/v) in equation B.4 of D. Michalik et al. 2014.\n        (Title: Joint astrometric solution of Hipparcos and Gaia)\n        NOTE: ntr (the number of transits) given in the header of the Hip2 IAD, is not necessarily\n        the number of transits used in the actual solution.\n        \"\"\"\n        num_transits_used = ntr\n        nu = num_transits_used - nparam  # equation B.1 of D. Michalik et al. 2014\n        Q = nu * (np.sqrt(2/(9*nu))*f2 + 1 - 2/(9*nu))**3  # equation B.3\n        u = np.sqrt(Q/nu)  # equation B.4. This is the chi squared statistic of the fit.\n        return u\n\n    def _reject_epochs(self, attr_to_set, value):\n        residuals_to_reject, orbits_to_reject = value['residual/along_scan_error'], value['orbit/scan_angle/time']\n        not_outlier = np.ones(len(self), dtype=bool)\n        np.put(not_outlier, residuals_to_reject, False)\n        self.residuals, self.along_scan_errs = self.residuals[not_outlier], self.along_scan_errs[not_outlier]\n        not_outlier = np.ones(len(self), dtype=bool)\n        np.put(not_outlier, orbits_to_reject, False)\n        self._epoch, self.scan_angle = self._epoch[not_outlier], self.scan_angle[not_outlier]\n        self.parallax_factors = self.parallax_factors[not_outlier]\n        setattr(self, attr_to_set, value)\n\n    @property\n    def additional_rejected_epochs(self):\n        return self._additional_rejected_epochs\n\n    @additional_rejected_epochs.setter\n    def additional_rejected_epochs(self, value):\n        self._reject_epochs('_additional_rejected_epochs', value)\n\n    @property\n    def rejected_epochs(self):\n        return self._rejected_epochs\n\n    @rejected_epochs.setter\n    def rejected_epochs(self, value):\n        self._reject_epochs('_rejected_epochs', value)\n\n\nclass HipparcosRereductionJavaTool(HipparcosRereductionDVDBook):\n    EPOCHREJECTLIST = Table.read(pkg_resources.resource_filename('htof',\n                                                                 'data/epoch_reject_shortlist.csv'), format='ascii')\n\n    def __init__(self, scan_angle=None, epoch=None, residuals=None, inverse_covariance_matrix=None,\n                 along_scan_errs=None, meta=None):\n        super(HipparcosRereductionJavaTool, self).__init__(scan_angle=scan_angle, along_scan_errs=along_scan_errs,\n                                                           epoch=epoch, residuals=residuals,\n                                                           inverse_covariance_matrix=inverse_covariance_matrix,\n                                                           meta=meta)\n\n    def read_header(self, star_id, intermediate_data_directory):\n        fpath = self.get_intermediate_data_file_path(star_id, intermediate_data_directory)\n        with open(fpath) as f:\n            lines = f.readlines()\n            hline_fst = [float(i) for i in lines[6].split('#')[1].split()]\n            hline_scd = [float(i) for i in lines[8].split('#')[1].split()]\n            hline_trd = [float(i) if not ('---' in i) else np.nan for i in lines[10].split('#')[1].split()]\n        hline_fst = {key: val for key, val in zip(['HIP', 'MCE', 'NRES', 'NC',\n                                                'isol_n', 'SCE', 'F2', 'F1'], hline_fst)}\n        hline_scd = {key: val for key, val in zip(['Hp','B-V','VarAnn','NOB','NR'], hline_scd)}\n        hline_trd = {key: val for key, val in zip(['RAdeg', 'DEdeg', 'Plx', 'pm_RA', 'pm_DE',\n                                                'e_RA', 'e_DE', 'e_Plx', 'e_pmRA', 'e_pmDE', 'dpmRA',\n                                                'dpmDE', 'e_dpmRA', 'e_dpmDE', 'ddpmRA', 'ddpmDE',\n                                                'e_ddpmRA', 'e_ddpmDE', 'upsRA', 'upsDE', 'e_upsRA',\n                                                'e_upsDE', 'var'], hline_trd)}\n        return {'first': hline_fst, 'second': hline_scd, 'third': hline_trd}\n\n    def parse(self, star_id, intermediate_data_directory, error_inflate=True, attempt_adhoc_rejection=True,\n              reject_known=True, **kwargs):\n        self.meta['star_id'] = star_id\n        header = self.read_header(star_id, intermediate_data_directory)\n        raw_data = self.read_intermediate_data_file(star_id, intermediate_data_directory,\n                                                    skiprows=13, header=None, sep=r'\\s+')\n        self.scan_angle = np.arctan2(raw_data[3], raw_data[4])  # data[3] = sin(theta) = cos(psi), data[4] = cos(theta) = sin(psi)\n        self._epoch = raw_data[1] + 1991.25\n        self.residuals = raw_data[5]  # unit milli-arcseconds (mas)\n        self.along_scan_errs = raw_data[6]  # unit milli-arcseconds (mas)\n        self.parallax_factors = raw_data[2]\n        self.meta['catalog_f2'] = header['first']['F2']\n        self.meta['catalog_soltype'] = header['first']['isol_n']\n        n_transits, n_expected_transits = header['first']['NRES'], header['second']['NOB']\n        n_additional_reject = int(n_transits) - int(n_expected_transits)\n        # self.meta['catalog_f2'] = header.iloc[0][6]  # this is already set in HipparcosRereductionDVDBook.parse()\n        # self.meta['catalog_soltype'] = header.iloc[0][4]  # this is already set in HipparcosRereductionDVDBook.parse()\n        max_n_auto_reject = 4\n        if attempt_adhoc_rejection:\n            if 3 >= n_additional_reject > 0:\n                self.additional_rejected_epochs = find_epochs_to_reject_java(self, n_additional_reject)\n            if max_n_auto_reject >= n_additional_reject > 3:\n                orbit_number = raw_data[0].values\n                self.additional_rejected_epochs = find_epochs_to_reject_java_large(self, n_additional_reject, orbit_number)\n            if n_additional_reject > max_n_auto_reject:\n                # These take too long to do automatically, pull the epochs to reject from the file that we computed\n                correct_id = header['first']['HIP']\n                t = self.EPOCHREJECTLIST[self.EPOCHREJECTLIST['hip_id'] == int(correct_id)]\n                if len(t) == 1:\n                    self.additional_rejected_epochs = {'residual/along_scan_error': literal_eval(t['residual/along_scan_error'][0]),\n                                                       'orbit/scan_angle/time': literal_eval(t['orbit/scan_angle/time'][0])}\n                else:\n                    warnings.warn(f'Cannot fix {star_id}. It has more than {max_n_auto_reject} corrupted epochs than can be '\n                                  f'corrected on-the-fly. The correct epochs to reject are not in our precomputed list '\n                                  f'(epoch_reject_shortlist.csv). This happens for sources where it is computationally '\n                                  f'infeasible to find an ad-hoc correction.', UserWarning)    # pragma: no cover\n        if not attempt_adhoc_rejection and n_additional_reject > 0:\n            warnings.warn(f\"attempt_adhoc_rejection = False and {star_id} has {n_additional_reject} \"\n                          \"discrepant observations. You have disabled the ad-hoc \"\n                          \"correction for this Java tool source. The IAD do not correspond \"\n                          \"to the best fit catalog solution. \", UserWarning)\n        epochs_to_reject = np.where(self.along_scan_errs <= 0)[0] # note that we have to reject\n        # the epochs with negative along scan errors (the formally known epochs that need to be rejected)\n        # AFTER we have done the bug correction (rejected the epochs from the write out bug). This order\n        # is important because the ad-hoc correction shuffles the orbits.\n        if len(epochs_to_reject) > 0 and reject_known:\n            # setting self.rejected_epochs also rejects the epochs (see the @setter)\n            self.rejected_epochs = {'residual/along_scan_error': list(epochs_to_reject),\n                                    'orbit/scan_angle/time': list(epochs_to_reject)}\n        # compute f2 of the residuals (with ad-hoc correction where applicable)\n        nparam = get_nparam(str(int(header['first']['isol_n'])))\n        Q = np.sum((self.residuals/self.along_scan_errs)**2)\n        n_transits_final = len(self)\n        # note that n_transits_final = n_expected_transits - number of indicated rejects (By negative AL errors)\n        self.meta['calculated_f2'] = special.erfcinv(stats.chi2.sf(Q, n_transits_final - nparam)*2)*np.sqrt(2)\n        if error_inflate:\n            # WARNING: we use the catalog (Van Leeuwen 2014 Java tool F2) f2 value here to calculate the error inflation\n            # factor. this is because for some sources, the calculated f2 value is much larger than the\n            # catalog value. E.g., HIP 87275 has a catalog f2 of 65.29, and a newly calculated f2 is using\n            # chi2.sf is infinity.\n            # Therefore the error inflation in the catalog is ~7, while the error inflation assuming\n            # the new f2 is infinity. We adopt the catalog f2 so as to reproduce the catalog solution and errors.\n            # The developers have not yet found this f2 discrepency to be an issue, but any source with it\n            # should still be treated with caution.\n            self.along_scan_errs *= self.error_inflation_factor(n_transits_final, nparam, self.meta['catalog_f2'])\n        return header, raw_data\n\n\n\nclass GaiaDR2(GaiaData):\n    DEAD_TIME_TABLE_NAME = pkg_resources.resource_filename('htof', 'data/astrometric_gaps_gaiadr2_08252020.csv')\n\n    def __init__(self, scan_angle=None, epoch=None, residuals=None, inverse_covariance_matrix=None, meta=None,\n                 min_epoch=st.GaiaDR2_min_epoch, max_epoch=st.GaiaDR2_max_epoch, along_scan_errs=None):\n        super(GaiaDR2, self).__init__(scan_angle=scan_angle, along_scan_errs=along_scan_errs,\n                                      epoch=epoch, residuals=residuals,\n                                      inverse_covariance_matrix=inverse_covariance_matrix,\n                                      min_epoch=min_epoch, max_epoch=max_epoch, meta=meta)\n\n\nclass GaiaeDR3(GaiaData):\n    DEAD_TIME_TABLE_NAME = pkg_resources.resource_filename('htof', 'data/astrometric_gaps_gaiaedr3_12232020.csv')\n\n    def __init__(self, scan_angle=None, epoch=None, residuals=None, inverse_covariance_matrix=None, meta=None,\n                 min_epoch=st.GaiaeDR3_min_epoch, max_epoch=st.GaiaeDR3_max_epoch, along_scan_errs=None):\n        super(GaiaeDR3, self).__init__(scan_angle=scan_angle, along_scan_errs=along_scan_errs,\n                                      epoch=epoch, residuals=residuals,\n                                      inverse_covariance_matrix=inverse_covariance_matrix,\n                                      min_epoch=min_epoch, max_epoch=max_epoch, meta=meta)\n\n\ndef digits_only(x: str):\n    return re.sub(\"[^0-9]\", \"\", x)\n\n\ndef match_filename(paths, star_id):\n    return [f for f in paths if digits_only(os.path.basename(f).split('.')[0]).zfill(6) == star_id.zfill(6)]\n\n\ndef find_epochs_to_reject_DVD(data: DataParser, n_transits, percent_rejected, nparam, catalog_f2):\n    # just looks for combinations of orbits within the dvd IAD that yield a stationary point of chisquared.\n    # Note that this does not work for sources with the data corruption.\n    chi2_thresh = 1\n    possible_rejects = np.arange(len(data))\n    min_n_reject = max(floor((percent_rejected - 1) / 100 * n_transits), 0)\n    max_n_reject = max(ceil((percent_rejected + 1) / 100 * n_transits), 1)\n    max_n_reject = min(max_n_reject, 3)  # limit to three rejected sources so that combinatorics dont blow up.\n    # calculate the chisquared partials\n    sin_scan = np.sin(data.scan_angle.values)\n    cos_scan = np.cos(data.scan_angle.values)\n    dt = data.epoch - 1991.25\n    rows_to_keep = np.ones(len(data), dtype=bool)\n    orbit_factors = np.array([data.parallax_factors.values, sin_scan, cos_scan, dt * sin_scan, dt * cos_scan])\n    residual_factors = (data.residuals.values / data.along_scan_errs.values ** 2)\n    chi2_vector = (2 * residual_factors * orbit_factors).T\n    sum_chisquared_partials_norejects = np.sqrt(np.sum(np.sum(chi2_vector, axis=0) ** 2))\n    # we should be able to do the orbit reject calculation fairly easily in memory.\n    # for 100 choose 3 we have like 250,000 combinations of orbits -- we should be able to\n    # do those in 10,000 orbit chunks in memory and gain a factor of 10,000 speed up.\n    candidate_row_rejects_pern = [[]]\n    candidate_row_chisquared_partials_pern = [sum_chisquared_partials_norejects]\n    n_reject = max(min_n_reject, 1)\n    while n_reject < max_n_reject:\n        candidate_row_rejects = []\n        candidate_row_chisquared_partials = []\n        combinations = list(set(itertools.combinations(possible_rejects, int(n_reject))))\n        for rows_to_reject in combinations:\n            rows_to_keep[list(rows_to_reject)] = False\n            # sum the square of the chi2 partials to decide for whether or not it is a stationary point.\n            sum_chisquared_partials = np.sqrt(np.sum(np.sum(chi2_vector[rows_to_keep], axis=0) ** 2))\n            candidate_row_rejects.append(rows_to_reject)\n            candidate_row_chisquared_partials.append(sum_chisquared_partials)\n            # reset for the next loop:\n            rows_to_keep[list(rows_to_reject)] = True\n        n_reject += 1\n        candidate_row_rejects_pern.append(np.array(candidate_row_rejects)[np.argmin(candidate_row_chisquared_partials)])\n        candidate_row_chisquared_partials_pern.append(np.min(candidate_row_chisquared_partials))\n    # see if any of the rejections are viable (i.e., check if this IAD is messed up in an unrepairable way)\n    if np.min(candidate_row_chisquared_partials_pern) > chi2_thresh:\n        warnings.warn(f\"Failed to find which observations of this DVD source {data.meta['star_id']} \"\n                      f\"that should have been marked as rejected. \"\n                      f\"The chi squared partials were larger than {chi2_thresh}. \"\n                      f\"DVD source {data.meta['star_id']} is likely a source with corrupted data. \"\n                      f\"Aborting rejection routine and using IAD as was \"\n                      f\"read from the DVD data. \", UserWarning)    # pragma: no cover\n        return {'residual/along_scan_error': [], 'orbit/scan_angle/time': []}\n    # exclude any rejections that do not yield stationary points.\n    viable_rejections = np.where(np.array(candidate_row_chisquared_partials_pern) < chi2_thresh)[0]\n    candidate_row_rejects_pern = [candidate_row_rejects_pern[v] for v in viable_rejections]\n    candidate_row_chisquared_partials_pern = [candidate_row_chisquared_partials_pern[v] for v in viable_rejections]\n    # calculate f2 values for all the viable rejections\n    candidate_row_f2_vals_pern = []\n    data_minus_model_squared = ((data.residuals.values / data.along_scan_errs.values) ** 2)\n    for r in candidate_row_rejects_pern:\n        rows_to_keep[list(r)] = False\n        chisquared = np.sum(data_minus_model_squared[rows_to_keep])\n        candidate_row_f2_vals_pern.append(compute_f2(n_transits - nparam, chisquared))\n        rows_to_keep[list(r)] = True\n    # restrict viable choices to the one that best matches f2\n    reject_idx = candidate_row_rejects_pern[np.argmin(np.abs(np.array(candidate_row_f2_vals_pern) - catalog_f2))]\n    return {'residual/along_scan_error': list(reject_idx), 'orbit/scan_angle/time': list(reject_idx)}\n\n\ndef find_epochs_to_reject_java(data: DataParser, n_additional_reject):\n    # Note there are degeneracies in the best epochs to reject. E.g. for hip 39, as long as the last\n    #  residual is rejected, basically any of the 1426 orbits (Because they are all similar)\n    #  can be rejected and they result in a very similar chisquared.\n    possible_rejects = np.arange(len(data))\n    # calculate the chisquared partials\n    sin_scan = np.sin(data.scan_angle.values)\n    cos_scan = np.cos(data.scan_angle.values)\n    dt = data.epoch - 1991.25\n    resid_reject_idx = [len(data) - 1 - i for i in range(int(n_additional_reject))]  # always reject the repeated observations.\n    # need to iterate over popping orbit combinations\n    orbits_to_keep = np.ones(len(data), dtype=bool)\n    residuals_to_keep = np.ones(len(data), dtype=bool)\n    residuals_to_keep[resid_reject_idx] = False\n\n    residual_factors = (data.residuals.values / data.along_scan_errs.values ** 2)[residuals_to_keep]\n    mask_rejected_resid = (data.along_scan_errs.values > 0).astype(bool)[residuals_to_keep]\n    _orbit_factors = np.array([data.parallax_factors.values, sin_scan, cos_scan, dt * sin_scan, dt * cos_scan]).T\n    # we should be able to do the orbit reject calculation fairly easily in memory.\n    # for 100 choose 3 we have like 250,000 combinations of orbits -- we sghould be able to\n    # do those in 10,000 orbit chunks in memory and gain a factor of 10,000 speed up.\n    candidate_orbit_rejects = []\n    candidate_orbit_chisquared_partials = []\n    for orbit_to_reject in itertools.combinations(possible_rejects, int(n_additional_reject)):\n        orbits_to_keep[list(orbit_to_reject)] = False\n        # now we want to try a variety of deleting orbits and sliding the other orbits\n        # upward to fill the vacancy.\n        # this pops the orbits out and shifts all the orbits after:\n        orbit_factors = _orbit_factors[orbits_to_keep].T\n        # this simultaneously deletes one of the residuals, assigns the remaining residuals to the\n        # shifted orbits, and calculates the chi2 partials vector per orbit:\n        chi2_vector = (2 * residual_factors * orbit_factors).T\n        # sum the square of the chi2 partials to decide for whether or not it is a stationary point.\n        sum_chisquared_partials = np.sqrt(np.sum(np.sum(chi2_vector[mask_rejected_resid], axis=0) ** 2))\n        candidate_orbit_rejects.append(orbit_to_reject)\n        candidate_orbit_chisquared_partials.append(sum_chisquared_partials)\n        # reset for the next loop:\n        orbits_to_keep[list(orbit_to_reject)] = True\n    orbit_reject_idx = np.array(candidate_orbit_rejects)[np.argmin(candidate_orbit_chisquared_partials)]\n    if np.min(candidate_orbit_chisquared_partials) > 0.5:\n        warnings.warn(f\"Completed the ad-hoc correction for java tool source {data.meta['star_id']}, \"\n                      f\"but the chisquared partials are \"\n                      \"still larger than 0.5. Treat the results of this \"\n                      \"source with caution.\", UserWarning)    # pragma: no cover\n\n    return {'residual/along_scan_error': list(resid_reject_idx),\n            'orbit/scan_angle/time': list(orbit_reject_idx)}\n\n\ndef find_epochs_to_reject_java_large(data: DataParser, n_additional_reject, orbit_number):\n    # this is for any java tool object where n_additional_reject is greater than 3.\n    # we assume the scan angles and times of rows in the same orbit are similar, therefore we only have\n    # to try all combinations of distributing n_additional_reject rejected epochs among N orbits\n    # calculate the chisquared partials\n    orbit_prototypes, orbit_index, orbit_multiplicity = np.unique(orbit_number, return_index=True, return_counts=True)\n    num_unique_orbits = len(orbit_prototypes)\n    sin_scan = np.sin(data.scan_angle.values)\n    cos_scan = np.cos(data.scan_angle.values)\n    dt = data.epoch - 1991.25\n    resid_reject_idx = [len(data) - 1 - i for i in range(int(n_additional_reject))]  # always reject the repeated observations.\n    # need to iterate over popping orbit combinations\n    orbits_to_keep = np.zeros(len(data), dtype=bool)\n    residuals_to_keep = np.ones(len(data), dtype=bool)\n    residuals_to_keep[resid_reject_idx] = False\n\n    residual_factors = (data.residuals.values / data.along_scan_errs.values ** 2)[residuals_to_keep]\n    mask_rejected_resid = (data.along_scan_errs.values > 0).astype(bool)[residuals_to_keep]\n    _orbit_factors = np.array([sin_scan, cos_scan, dt * sin_scan, dt * cos_scan]).T\n    # we should be able to do the orbit reject calculation fairly easily in memory.\n    # for 100 choose 3 we have like 250,000 combinations of orbits -- we sghould be able to\n    # do those in 10,000 orbit chunks in memory and gain a factor of 10,000 speed up.\n    candidate_orbit_rejects = []\n    candidate_orbit_chisquared_partials = []\n    for rejects_from_each_orbit in partitions(n_additional_reject, num_unique_orbits):\n        if np.any(rejects_from_each_orbit > orbit_multiplicity):\n            # ignore any trials of rejects that put e.g. 10 rejects into an orbit with only 4 observations.\n            continue\n        end_index = orbit_index + orbit_multiplicity - np.array(rejects_from_each_orbit)\n        for s, e in zip(orbit_index, end_index):\n            orbits_to_keep[s:e] = True\n        # now we want to try a variety of deleting orbits and sliding the other orbits\n        # upward to fill the vacancy.\n        # this pops the orbits out and shifts all the orbits after:\n        orbit_factors = _orbit_factors[orbits_to_keep].T\n        # this simultaneously deletes one of the residuals, assigns the remaining residuals to the\n        # shifted orbits, and calculates the chi2 partials vector per orbit:\n        chi2_vector = (2 * residual_factors * orbit_factors).T\n        # sum the square of the chi2 partials to decide for whether or not it is a stationary point.\n        sum_chisquared_partials = np.sqrt(np.sum(np.sum(chi2_vector[mask_rejected_resid], axis=0) ** 2))\n        candidate_orbit_rejects.append(rejects_from_each_orbit)\n        candidate_orbit_chisquared_partials.append(sum_chisquared_partials)\n        # reset for the next loop:\n        orbits_to_keep[:] = False\n    rejects_from_each_orbit = np.array(candidate_orbit_rejects)[np.argmin(candidate_orbit_chisquared_partials)]\n    # now transform rejects_from_each_orbit into actual orbit indices that we are going to reject.\n    end_index = orbit_index + orbit_multiplicity - np.array(rejects_from_each_orbit)\n    for s, e in zip(orbit_index, end_index):\n        orbits_to_keep[s:e] = True\n    orbit_reject_idx = np.where(~orbits_to_keep)[0]\n    if np.min(candidate_orbit_chisquared_partials) > 0.5:\n        warnings.warn(f\"Completed the ad-hoc correction for java tool source {data.meta['star_id']}, \"\n                      f\"but the chisquared partials are \"\n                      \"still larger than 0.5. Treat the results of this \"\n                      \"source with caution.\", UserWarning)    # pragma: no cover\n\n    return {'residual/along_scan_error': list(resid_reject_idx),\n            'orbit/scan_angle/time': list(orbit_reject_idx)}\n\n\ndef partitions(n, k):\n    \"\"\"\n    yield all possible weighs to distribute n rejected rows among k orbits.\n    This is just the solution to the \"stars and bars\" problem.\n    Theorem 2: https://en.wikipedia.org/wiki/Stars_and_bars_%28combinatorics%29\n\n    From https://stackoverflow.com/questions/28965734/general-bars-and-stars\n    \"\"\"\n    for c in itertools.combinations(range(n+k-1), k-1):\n        yield [b-a-1 for a, b in zip((-1,)+c, c+(n+k-1,))]\n\n\ndef get_nparam(nparam_header_val):\n    # strip the solution type (5, 7, or 9) from the solution type, which is a number 10xd+s consisting of\n    # two parts: d and s. see Note 1 on Vizier for the Hipparcos re-reduction.\n    return int(str(int(nparam_header_val))[-1])\n\n\ndef compute_f2(nu, chisquared):\n    # equation B.2 of D. Michalik et al. 2014. Joint astrometric solution of Hipparcos and Gaia\n    return (9*nu/2)**(1/2)*((chisquared/nu)**(1/3) + 2/(9*nu) - 1)\n", "meta": {"hexsha": "819cfa7af883aad8cb6c31b296877d57f5d1182a", "size": 44186, "ext": "py", "lang": "Python", "max_stars_repo_path": "htof/parse.py", "max_stars_repo_name": "gmbrandt/HTOF", "max_stars_repo_head_hexsha": "e01f21cccb788fa685b167888153ac3a7befda1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-06-14T19:23:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T20:09:09.000Z", "max_issues_repo_path": "htof/parse.py", "max_issues_repo_name": "gmbrandt/HTOF", "max_issues_repo_head_hexsha": "e01f21cccb788fa685b167888153ac3a7befda1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2019-11-06T18:31:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-16T18:28:46.000Z", "max_forks_repo_path": "htof/parse.py", "max_forks_repo_name": "gmbrandt/HTOF", "max_forks_repo_head_hexsha": "e01f21cccb788fa685b167888153ac3a7befda1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-04-09T19:59:41.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-09T19:59:41.000Z", "avg_line_length": 60.6950549451, "max_line_length": 138, "alphanum_fraction": 0.6652107002, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 10617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.16685327665694716}}
{"text": "\"\"\"\nModule implements X-learner from Kuenzel et al (2019) using NNs\n\"\"\"\n# Author: Alicia Curth\nfrom typing import Callable, Optional, Tuple\n\nimport jax.numpy as jnp\n\nimport catenets.logger as log\nfrom catenets.models.constants import (\n    DEFAULT_AVG_OBJECTIVE,\n    DEFAULT_BATCH_SIZE,\n    DEFAULT_LAYERS_OUT,\n    DEFAULT_LAYERS_OUT_T,\n    DEFAULT_LAYERS_R,\n    DEFAULT_LAYERS_R_T,\n    DEFAULT_N_ITER,\n    DEFAULT_N_ITER_MIN,\n    DEFAULT_N_ITER_PRINT,\n    DEFAULT_NONLIN,\n    DEFAULT_PATIENCE,\n    DEFAULT_PENALTY_L2,\n    DEFAULT_SEED,\n    DEFAULT_STEP_SIZE,\n    DEFAULT_STEP_SIZE_T,\n    DEFAULT_UNITS_OUT,\n    DEFAULT_UNITS_OUT_T,\n    DEFAULT_UNITS_R,\n    DEFAULT_UNITS_R_T,\n    DEFAULT_VAL_SPLIT,\n)\nfrom catenets.models.jax.base import BaseCATENet, train_output_net_only\nfrom catenets.models.jax.model_utils import check_shape_1d_data, check_X_is_np\nfrom catenets.models.jax.pseudo_outcome_nets import (  # same strategies as other nets\n    ALL_STRATEGIES,\n    FLEX_STRATEGY,\n    OFFSET_STRATEGY,\n    S1_STRATEGY,\n    S2_STRATEGY,\n    S3_STRATEGY,\n    S_STRATEGY,\n    T_STRATEGY,\n    predict_flextenet,\n    predict_offsetnet,\n    predict_snet,\n    predict_snet1,\n    predict_snet2,\n    predict_snet3,\n    predict_t_net,\n    train_flextenet,\n    train_offsetnet,\n    train_snet,\n    train_snet1,\n    train_snet2,\n    train_snet3,\n    train_tnet,\n)\n\n\nclass XNet(BaseCATENet):\n    \"\"\"\n    Class implements X-learner using NNs.\n\n    Parameters\n    ----------\n    weight_strategy: int, default None\n        Which strategy to use to weight the two CATE estimators in the second stage. weight_strategy\n        is coded as follows: for tau(x)=g(x)tau_0(x) + (1-g(x))tau_1(x) [eq 9, kuenzel et al (2019)]\n        weight_strategy=0 sets g(x)=0, weight_strategy=1 sets g(x)=1,\n        weight_strategy=None sets g(x)=pi(x) [propensity score],\n         weight_strategy=-1 sets g(x)=(1-pi(x))\n    binary_y: bool, default False\n        Whether the outcome is binary\n    n_layers_out: int\n        First stage Number of hypothesis layers (n_layers_out x n_units_out + 1 x Dense layer)\n    n_units_out: int\n        First stage Number of hidden units in each hypothesis layer\n    n_layers_r: int\n        First stage Number of representation layers before hypothesis layers (distinction between\n        hypothesis layers and representation layers is made to match TARNet & SNets)\n    n_units_r: int\n        First stage Number of hidden units in each representation layer\n    n_layers_out_t: int\n        Second stage Number of hypothesis layers (n_layers_out x n_units_out + 1 x Dense layer)\n    n_units_out_t: int\n        Second stage Number of hidden units in each hypothesis layer\n    n_layers_r_t: int\n        Second stage Number of representation layers before hypothesis layers (distinction between\n        hypothesis layers and representation layers is made to match TARNet & SNets)\n    n_units_r_t: int\n        Second stage Number of hidden units in each representation layer\n    penalty_l2: float\n        First stage l2 (ridge) penalty\n    penalty_l2_t: float\n        Second stage l2 (ridge) penalty\n    step_size: float\n        First stage learning rate for optimizer\n    step_size_t: float\n        Second stage learning rate for optimizer\n    n_iter: int\n        Maximum number of iterations\n    batch_size: int\n        Batch size\n    val_split_prop: float\n        Proportion of samples used for validation split (can be 0)\n    early_stopping: bool, default True\n        Whether to use early stopping\n    patience: int\n        Number of iterations to wait before early stopping after decrease in validation loss\n    n_iter_min: int\n        Minimum number of iterations to go through before starting early stopping\n    n_iter_print: int\n        Number of iterations after which to print updates\n    seed: int\n        Seed used\n    nonlin: string, default 'elu'\n        Nonlinearity to use in NN\n    \"\"\"\n\n    def __init__(\n        self,\n        weight_strategy: Optional[int] = None,\n        first_stage_strategy: str = T_STRATEGY,\n        first_stage_args: Optional[dict] = None,\n        binary_y: bool = False,\n        n_layers_out: int = DEFAULT_LAYERS_OUT,\n        n_layers_r: int = DEFAULT_LAYERS_R,\n        n_layers_out_t: int = DEFAULT_LAYERS_OUT_T,\n        n_layers_r_t: int = DEFAULT_LAYERS_R_T,\n        n_units_out: int = DEFAULT_UNITS_OUT,\n        n_units_r: int = DEFAULT_UNITS_R,\n        n_units_out_t: int = DEFAULT_UNITS_OUT_T,\n        n_units_r_t: int = DEFAULT_UNITS_R_T,\n        penalty_l2: float = DEFAULT_PENALTY_L2,\n        penalty_l2_t: float = DEFAULT_PENALTY_L2,\n        step_size: float = DEFAULT_STEP_SIZE,\n        step_size_t: float = DEFAULT_STEP_SIZE_T,\n        n_iter: int = DEFAULT_N_ITER,\n        batch_size: int = DEFAULT_BATCH_SIZE,\n        n_iter_min: int = DEFAULT_N_ITER_MIN,\n        val_split_prop: float = DEFAULT_VAL_SPLIT,\n        early_stopping: bool = True,\n        patience: int = DEFAULT_PATIENCE,\n        n_iter_print: int = DEFAULT_N_ITER_PRINT,\n        seed: int = DEFAULT_SEED,\n        nonlin: str = DEFAULT_NONLIN,\n    ):\n        # settings\n        self.weight_strategy = weight_strategy\n        self.first_stage_strategy = first_stage_strategy\n        self.first_stage_args = first_stage_args\n        self.binary_y = binary_y\n\n        # model architecture hyperparams\n        self.n_layers_out = n_layers_out\n        self.n_layers_out_t = n_layers_out_t\n        self.n_layers_r = n_layers_r\n        self.n_layers_r_t = n_layers_r_t\n        self.n_units_out = n_units_out\n        self.n_units_out_t = n_units_out_t\n        self.n_units_r = n_units_r\n        self.n_units_r_t = n_units_r_t\n        self.nonlin = nonlin\n\n        # other hyperparameters\n        self.penalty_l2 = penalty_l2\n        self.penalty_l2_t = penalty_l2_t\n        self.step_size = step_size\n        self.step_size_t = step_size_t\n        self.n_iter = n_iter\n        self.batch_size = batch_size\n        self.n_iter_print = n_iter_print\n        self.seed = seed\n        self.val_split_prop = val_split_prop\n        self.early_stopping = early_stopping\n        self.patience = patience\n        self.n_iter_min = n_iter_min\n\n    def _get_train_function(self) -> Callable:\n        return train_x_net\n\n    def _get_predict_function(self) -> Callable:\n        # Two step nets do not need this\n        return predict_x_net\n\n    def predict(\n        self, X: jnp.ndarray, return_po: bool = False, return_prop: bool = False\n    ) -> jnp.ndarray:\n        \"\"\"\n        Predict treatment effect estimates using a CATENet. Depending on method, can also return\n        potential outcome estimate and propensity score estimate.\n\n        Parameters\n        ----------\n        X: pd.DataFrame or np.array\n            Covariate matrix\n        return_po: bool, default False\n            Whether to return potential outcome estimate\n        return_prop: bool, default False\n            Whether to return propensity estimate\n\n        Returns\n        -------\n        array of CATE estimates, optionally also potential outcomes and propensity\n        \"\"\"\n        X = check_X_is_np(X)\n        predict_func = self._get_predict_function()\n        return predict_func(\n            X,\n            trained_params=self._params,\n            predict_funs=self._predict_funs,\n            return_po=return_po,\n            return_prop=return_prop,\n            weight_strategy=self.weight_strategy,\n        )\n\n\ndef train_x_net(\n    X: jnp.ndarray,\n    y: jnp.ndarray,\n    w: jnp.ndarray,\n    weight_strategy: Optional[int] = None,\n    first_stage_strategy: str = T_STRATEGY,\n    first_stage_args: Optional[dict] = None,\n    binary_y: bool = False,\n    n_layers_out: int = DEFAULT_LAYERS_OUT,\n    n_layers_r: int = DEFAULT_LAYERS_R,\n    n_layers_out_t: int = DEFAULT_LAYERS_OUT_T,\n    n_layers_r_t: int = DEFAULT_LAYERS_R_T,\n    n_units_out: int = DEFAULT_UNITS_OUT,\n    n_units_r: int = DEFAULT_UNITS_R,\n    n_units_out_t: int = DEFAULT_UNITS_OUT_T,\n    n_units_r_t: int = DEFAULT_UNITS_R_T,\n    penalty_l2: float = DEFAULT_PENALTY_L2,\n    penalty_l2_t: float = DEFAULT_PENALTY_L2,\n    step_size: float = DEFAULT_STEP_SIZE,\n    step_size_t: float = DEFAULT_STEP_SIZE_T,\n    n_iter: int = DEFAULT_N_ITER,\n    batch_size: int = DEFAULT_BATCH_SIZE,\n    n_iter_min: int = DEFAULT_N_ITER_MIN,\n    val_split_prop: float = DEFAULT_VAL_SPLIT,\n    early_stopping: bool = True,\n    patience: int = DEFAULT_PATIENCE,\n    n_iter_print: int = DEFAULT_N_ITER_PRINT,\n    seed: int = DEFAULT_SEED,\n    nonlin: str = DEFAULT_NONLIN,\n    return_val_loss: bool = False,\n    avg_objective: bool = DEFAULT_AVG_OBJECTIVE,\n) -> Tuple:\n    y = check_shape_1d_data(y)\n    if len(w.shape) > 1:\n        w = w.reshape((len(w),))\n\n    if weight_strategy not in [0, 1, -1, None]:\n        # weight_strategy is coded as follows:\n        # for tau(x)=g(x)tau_0(x) + (1-g(x))tau_1(x) [eq 9, kuenzel et al (2019)]\n        # weight_strategy=0 sets g(x)=0, weight_strategy=1 sets g(x)=1,\n        # weight_strategy=None sets g(x)=pi(x) [propensity score],\n        # weight_strategy=-1 sets g(x)=(1-pi(x))\n        raise ValueError(\"XNet only implements weight_strategy in [0, 1, -1, None]\")\n\n    if first_stage_strategy not in ALL_STRATEGIES:\n        raise ValueError(\n            \"Parameter first stage should be in \"\n            \"catenets.models.twostep_nets.ALL_STRATEGIES. \"\n            \"You passed {}\".format(first_stage_strategy)\n        )\n\n    # first stage: get estimates of PO regression\n    log.debug(\"Training first stage\")\n\n    mu_hat_0, mu_hat_1 = _get_first_stage_pos(\n        X,\n        y,\n        w,\n        binary_y=binary_y,\n        n_layers_out=n_layers_out,\n        n_units_out=n_units_out,\n        n_layers_r=n_layers_r,\n        n_units_r=n_units_r,\n        penalty_l2=penalty_l2,\n        step_size=step_size,\n        n_iter=n_iter,\n        batch_size=batch_size,\n        val_split_prop=val_split_prop,\n        early_stopping=early_stopping,\n        patience=patience,\n        n_iter_min=n_iter_min,\n        n_iter_print=n_iter_print,\n        seed=seed,\n        nonlin=nonlin,\n        avg_objective=avg_objective,\n        first_stage_strategy=first_stage_strategy,\n        first_stage_args=first_stage_args,\n    )\n\n    if weight_strategy is None or weight_strategy == -1:\n        # also fit propensity estimator\n        log.debug(\"Training propensity net\")\n        params_prop, predict_fun_prop = train_output_net_only(\n            X,\n            w,\n            binary_y=True,\n            n_layers_out=n_layers_out,\n            n_units_out=n_units_out,\n            n_layers_r=n_layers_r,\n            n_units_r=n_units_r,\n            penalty_l2=penalty_l2,\n            step_size=step_size,\n            n_iter=n_iter,\n            batch_size=batch_size,\n            val_split_prop=val_split_prop,\n            early_stopping=early_stopping,\n            patience=patience,\n            n_iter_min=n_iter_min,\n            n_iter_print=n_iter_print,\n            seed=seed,\n            nonlin=nonlin,\n            avg_objective=avg_objective,\n        )\n\n    else:\n        params_prop, predict_fun_prop = None, None\n\n    # second stage\n    log.debug(\"Training second stage\")\n    if not weight_strategy == 0:\n        # fit tau_0\n        log.debug(\"Fitting tau_0\")\n        pseudo_outcome0 = mu_hat_1 - y[w == 0]\n        params_tau0, predict_fun_tau0 = train_output_net_only(\n            X[w == 0],\n            pseudo_outcome0,\n            binary_y=False,\n            n_layers_out=n_layers_out_t,\n            n_units_out=n_units_out_t,\n            n_layers_r=n_layers_r_t,\n            n_units_r=n_units_r_t,\n            penalty_l2=penalty_l2_t,\n            step_size=step_size_t,\n            n_iter=n_iter,\n            batch_size=batch_size,\n            val_split_prop=val_split_prop,\n            early_stopping=early_stopping,\n            patience=patience,\n            n_iter_min=n_iter_min,\n            n_iter_print=n_iter_print,\n            seed=seed,\n            return_val_loss=return_val_loss,\n            nonlin=nonlin,\n            avg_objective=avg_objective,\n        )\n    else:\n        params_tau0, predict_fun_tau0 = None, None\n\n    if not weight_strategy == 1:\n        # fit tau_1\n        log.debug(\"Fitting tau_1\")\n        pseudo_outcome1 = y[w == 1] - mu_hat_0\n        params_tau1, predict_fun_tau1 = train_output_net_only(\n            X[w == 1],\n            pseudo_outcome1,\n            binary_y=False,\n            n_layers_out=n_layers_out_t,\n            n_units_out=n_units_out_t,\n            n_layers_r=n_layers_r_t,\n            n_units_r=n_units_r_t,\n            penalty_l2=penalty_l2_t,\n            step_size=step_size_t,\n            n_iter=n_iter,\n            batch_size=batch_size,\n            val_split_prop=val_split_prop,\n            early_stopping=early_stopping,\n            patience=patience,\n            n_iter_min=n_iter_min,\n            n_iter_print=n_iter_print,\n            seed=seed,\n            return_val_loss=return_val_loss,\n            nonlin=nonlin,\n            avg_objective=avg_objective,\n        )\n\n    else:\n        params_tau1, predict_fun_tau1 = None, None\n\n    params = params_tau0, params_tau1, params_prop\n    predict_funs = predict_fun_tau0, predict_fun_tau1, predict_fun_prop\n\n    return params, predict_funs\n\n\ndef _get_first_stage_pos(\n    X: jnp.ndarray,\n    y: jnp.ndarray,\n    w: jnp.ndarray,\n    first_stage_strategy: str = T_STRATEGY,\n    first_stage_args: Optional[dict] = None,\n    binary_y: bool = False,\n    n_layers_out: int = DEFAULT_LAYERS_OUT,\n    n_layers_r: int = DEFAULT_LAYERS_R,\n    n_units_out: int = DEFAULT_UNITS_OUT,\n    n_units_r: int = DEFAULT_UNITS_R,\n    penalty_l2: float = DEFAULT_PENALTY_L2,\n    step_size: float = DEFAULT_STEP_SIZE,\n    n_iter: int = DEFAULT_N_ITER,\n    batch_size: int = DEFAULT_BATCH_SIZE,\n    n_iter_min: int = DEFAULT_N_ITER_MIN,\n    val_split_prop: float = DEFAULT_VAL_SPLIT,\n    early_stopping: bool = True,\n    patience: int = DEFAULT_PATIENCE,\n    n_iter_print: int = DEFAULT_N_ITER_PRINT,\n    seed: int = DEFAULT_SEED,\n    nonlin: str = DEFAULT_NONLIN,\n    avg_objective: bool = DEFAULT_AVG_OBJECTIVE,\n) -> Tuple[jnp.ndarray, jnp.ndarray]:\n    if first_stage_args is None:\n        first_stage_args = {}\n\n    train_fun: Callable\n    predict_fun: Callable\n\n    if first_stage_strategy == T_STRATEGY:\n        train_fun, predict_fun = train_tnet, predict_t_net\n    elif first_stage_strategy == S_STRATEGY:\n        train_fun, predict_fun = train_snet, predict_snet\n    elif first_stage_strategy == S1_STRATEGY:\n        train_fun, predict_fun = train_snet1, predict_snet1\n    elif first_stage_strategy == S2_STRATEGY:\n        train_fun, predict_fun = train_snet2, predict_snet2\n    elif first_stage_strategy == S3_STRATEGY:\n        train_fun, predict_fun = train_snet3, predict_snet3\n    elif first_stage_strategy == OFFSET_STRATEGY:\n        train_fun, predict_fun = train_offsetnet, predict_offsetnet\n    elif first_stage_strategy == FLEX_STRATEGY:\n        train_fun, predict_fun = train_flextenet, predict_flextenet\n\n    trained_params, pred_fun = train_fun(\n        X,\n        y,\n        w,\n        binary_y=binary_y,\n        n_layers_r=n_layers_r,\n        n_units_r=n_units_r,\n        n_layers_out=n_layers_out,\n        n_units_out=n_units_out,\n        penalty_l2=penalty_l2,\n        step_size=step_size,\n        n_iter=n_iter,\n        batch_size=batch_size,\n        val_split_prop=val_split_prop,\n        early_stopping=early_stopping,\n        patience=patience,\n        n_iter_min=n_iter_min,\n        n_iter_print=n_iter_print,\n        seed=seed,\n        nonlin=nonlin,\n        avg_objective=avg_objective,\n        **first_stage_args\n    )\n\n    _, mu_0, mu_1 = predict_fun(X, trained_params, pred_fun, return_po=True)\n\n    return mu_0[w == 1], mu_1[w == 0]\n\n\ndef predict_x_net(\n    X: jnp.ndarray,\n    trained_params: dict,\n    predict_funs: list,\n    return_po: bool = False,\n    return_prop: bool = False,\n    weight_strategy: Optional[int] = None,\n) -> jnp.ndarray:\n    if return_po:\n        raise NotImplementedError(\"TwoStepNets have no Potential outcome predictors.\")\n\n    if return_prop:\n        raise NotImplementedError(\"TwoStepNets have no Propensity predictors.\")\n\n    params_tau0, params_tau1, params_prop = trained_params\n    predict_fun_tau0, predict_fun_tau1, predict_fun_prop = predict_funs\n\n    tau0_pred: jnp.ndarray\n    tau1_pred: jnp.ndarray\n\n    if not weight_strategy == 0:\n        tau0_pred = predict_fun_tau0(params_tau0, X)\n    else:\n        tau0_pred = 0\n\n    if not weight_strategy == 1:\n        tau1_pred = predict_fun_tau1(params_tau1, X)\n    else:\n        tau1_pred = 0\n\n    if weight_strategy is None or weight_strategy == -1:\n        prop_pred = predict_fun_prop(params_prop, X)\n\n    if weight_strategy is None:\n        weight = prop_pred\n    elif weight_strategy == -1:\n        weight = 1 - prop_pred\n    elif weight_strategy == 0:\n        weight = 0\n    elif weight_strategy == 1:\n        weight = 1\n\n    return weight * tau0_pred + (1 - weight) * tau1_pred\n", "meta": {"hexsha": "0a11152be99f8c6622c22268e717e31dff6461ce", "size": 16947, "ext": "py", "lang": "Python", "max_stars_repo_path": "catenets/models/jax/xnet.py", "max_stars_repo_name": "AliciaCurth/CATENets", "max_stars_repo_head_hexsha": "aeeae7625e454e97adff37b66ba2acb527dbd275", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2021-02-25T13:50:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T14:31:40.000Z", "max_issues_repo_path": "catenets/models/jax/xnet.py", "max_issues_repo_name": "vanderschaarlab/CATENets", "max_issues_repo_head_hexsha": "d0bc5316fa784fad78d8801367ed57c37193d2c5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-02-21T16:16:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T17:56:29.000Z", "max_forks_repo_path": "catenets/models/jax/xnet.py", "max_forks_repo_name": "vanderschaarlab/CATENets", "max_forks_repo_head_hexsha": "d0bc5316fa784fad78d8801367ed57c37193d2c5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-02-26T10:20:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-03T16:34:23.000Z", "avg_line_length": 33.2946954813, "max_line_length": 100, "alphanum_fraction": 0.6605888948, "include": true, "reason": "import jax", "num_tokens": 4224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.16685327665694713}}
{"text": "# 目标-老网络，用R和下一步Q最大值作为Q_目标\n# 预测-新网络，直接输出Q_预测\n\nimport tensorflow as tf\nimport numpy as np\nimport cv2.cv2 as cv2\n\n\nclass DQN:\n    # 所有初始化\n    def __init__(\n        self,\n        n_actions,\n        n_features,\n        learning_rate=0.01,\n        reward_decay=0.9,\n        e_greedy=0.9,\n        replace_target_iter=300,\n        memory_size=500,\n        batch_size=32,\n        e_greedy_increment=None,\n        output_graph=False\n    ):\n        self.n_actions = n_actions      # 可能操作总数\n        self.n_features = n_features    # 状态特征的维数\n        self.lr = learning_rate         # 学习率\n        self.gamma = reward_decay       # 下步q和奖励在目标q中的比值\n        self.epsilon_max = e_greedy     # epsilon 的最大值\n        self.replace_target_iter = replace_target_iter  # target_net 更新 的步数\n        self.memory_size = memory_size  # 记忆池的上限\n        self.batch_size = batch_size    # 每步训练抽取的记录条数\n        self.epsilon_increment = e_greedy_increment  # epsilon 的增量\n        # 是否开启探索模式, 并逐步减少探索次数\n        self.epsilon = 0 if e_greedy_increment is not None else self.epsilon_max\n\n        # 记录学习次数 (用于判断是否更换 target_net 参数)\n        self.learn_step_counter = 0\n\n        # 初始化全 0 记忆 [s, a, r, s_]\n        # 和视频中不同, 因为 pandas 运算比较慢, 这里改为直接用 numpy\n        self.memory = np.zeros((self.memory_size, n_features*2+2))\n\n        # 创建 [target_net, evaluate_net]\n        self._build_net()\n\n        # replace_target_op节点：用预测网络的参数更新目标网络的参数\n        t_params = tf.get_collection(\n            'target_net_params')  # 提取 target_net 的参数\n        e_params = tf.get_collection(\n            'pred_net_params')   # 提取  pred_net 的参数\n        self.replace_target_op = [tf.assign(\n            t, e) for t, e in zip(t_params, e_params)]  # 更新 target_net 参数\n\n        # 建立tf会话\n        self.sess = tf.Session()\n\n        # 输出 tensorboard 文件\n        if output_graph:\n            # $ tensorboard --logdir=logs\n            tf.summary.FileWriter(\"logs/\", self.sess.graph)\n\n        # 进行所有全局变量的初始化\n        self.sess.run(tf.global_variables_initializer())\n\n        # 记录所有 cost 变化, 用于最后 plot 出来观看\n        self.cost_his = []\n\n    # 构建网络计算图\n    def _build_net(self):\n        # -------------- 创建prediction网络，用于输出预测，参数实时学习 --------------\n        # s:输入节点，即环境的当前状态。行数不定，列数为n_features(一个状态特征向量的维数)\n        self.s = tf.placeholder(\n            tf.float32, [None, self.n_features], name='s')\n\n        # q_target节点:用公式算出的q目标值\n        self.q_target = tf.placeholder(\n            tf.float32, [None, self.n_actions], name='Q_target')\n\n        # q_pred节点：prediction网络输出的q值\n        with tf.variable_scope('pred_net'):\n            # c_names?\n            c_names, n_l1, w_initializer, b_initializer = \\\n                ['pred_net_params', tf.GraphKeys.GLOBAL_VARIABLES], 10, \\\n                tf.random_normal_initializer(\n                    0., 0.3), tf.constant_initializer(0.1)\n\n            # 第一层，输入维数（矩阵行数）为n_features\n            with tf.variable_scope('l1'):\n                w1 = tf.get_variable(\n                    'w1', [self.n_features, n_l1], initializer=w_initializer, collections=c_names)\n                b1 = tf.get_variable(\n                    'b1', [1, n_l1], initializer=b_initializer, collections=c_names)\n                l1 = tf.nn.relu(tf.matmul(self.s, w1) + b1)\n\n            # 第二层，输出q的预测值，节点数为所有action的总数\n            with tf.variable_scope('l2'):\n                w2 = tf.get_variable(\n                    'w2', [n_l1, self.n_actions], initializer=w_initializer, collections=c_names)\n                b2 = tf.get_variable(\n                    'b2', [1, self.n_actions], initializer=b_initializer, collections=c_names)\n                self.q_pred = tf.matmul(l1, w2) + b2\n\n        # loss节点：用q_target和q_pred计算的损失函数\n        with tf.variable_scope('loss'):\n            self.loss = tf.reduce_mean(\n                tf.squared_difference(self.q_target, self.q_pred))\n\n        # _train_op节点：使用RMSprop优化器更新参数？\n        with tf.variable_scope('train'):\n            self._train_op = tf.train.RMSPropOptimizer(\n                self.lr).minimize(self.loss)\n\n        # -------------- 创建target网络，给出计算q_target所需的下一步的q值，参数滞后更新 --------------\n        # s_节点：环境的下一状态，行数不定，列数为n_features(一个状态特征向量的维数)\n        self.s_ = tf.placeholder(\n            tf.float32, [None, self.n_features], name='s_')\n\n        # q_pred节点：target（滞后）网络输出的下步的q值\n        with tf.variable_scope('target_net'):\n            c_names = ['target_net_params',\n                       tf.GraphKeys.GLOBAL_VARIABLES]\n\n            # 第一层，输入维数（矩阵行数）为n_features\n            with tf.variable_scope('l1'):\n                w1 = tf.get_variable(\n                    'w1', [self.n_features, n_l1], initializer=w_initializer, collections=c_names)\n                b1 = tf.get_variable(\n                    'b1', [1, n_l1], initializer=b_initializer, collections=c_names)\n                l1 = tf.nn.relu(\n                    tf.matmul(self.s_, w1) + b1)\n\n            # 第二层，输出q的预测值，节点数为所有action的总数\n            with tf.variable_scope('l2'):\n                w2 = tf.get_variable(\n                    'w2', [n_l1, self.n_actions], initializer=w_initializer, collections=c_names)\n                b2 = tf.get_variable(\n                    'b2', [1, self.n_actions], initializer=b_initializer, collections=c_names)\n                self.q_next = tf.matmul(l1, w2) + b2\n\n    # 将记录更新到memory中\n    def store_transition(self, s, a, r, s_):\n        # 创建记录计数器\n        if not hasattr(self, 'memory_counter'):\n            self.memory_counter = 0\n\n        # 将本步状态s, 选择动作a, 奖励r, 下一步状态s_拼接为一条记录\n        transition = np.hstack((s, [a, r], s_))\n\n        # 在0-memory_size范围内循环更新memory\n        index = self.memory_counter % self.memory_size\n        self.memory[index, :] = transition\n        self.memory_counter += 1\n\n    # 做出决策\n    def choose_action(self, observation):\n        # 增加一个维度\n        observation = observation[np.newaxis, :]\n\n        # 以一定概率让网络做决定，一定概率随机决定\n        if np.random.uniform() < self.epsilon:\n            # 将当前状态送入pred网络，得到每种action的推荐度，选出最大的\n            actions_value = self.sess.run(\n                self.q_pred, feed_dict={self.s: observation})\n            action = np.argmax(actions_value)\n        else:\n            action = np.random.randint(0, self.n_actions)\n        return action\n\n    # 学习过程，核心算法\n    def learn(self):\n        # 每replace_target_iter步将target网络的参数更新\n        if self.learn_step_counter % self.replace_target_iter == 0:\n            self.sess.run(self.replace_target_op)\n            print(\"\\ntarget_params_replaced\")\n\n        # 从记忆池中抽取batch_size条记录\n        if self.memory_counter > self.memory_size:\n            sample_index = np.random.choice(\n                self.memory_size, size=self.batch_size)\n        else:\n            sample_index = np.random.choice(\n                self.memory_counter, size=self.batch_size)\n        batch_memory = self.memory[sample_index, :]\n\n        # 对这批记录中的每一条，用滞后更新参数的target网络得到下一步的q，用实时更新参数的prediction网络得到s的q\n        q_next, q_pred = self.sess.run(\n            [self.q_next, self.q_pred],\n            feed_dict={\n                self.s_: batch_memory[:, -self.n_features:],\n                self.s: batch_memory[:, :self.n_features]\n            }\n        )\n\n        # 对这一批记录中的每一条，计算其目标q\n\n        # 先把q目标值统一设置为预测值。\n        # 由于仅需（也仅能）更新q的{记录中选择了的那个action}的分量，\n        # 因此其他分量不需更新，保持其与预测q相同即可\n        q_target = q_pred.copy()\n        # 生成一个0-batch_size - 1的数列备用\n        batch_index = np.arange(self.batch_size, dtype=np.int32)\n        # 找到每条记录中选择了的那个action的编号\n        pred_act_index = batch_memory[:, self.n_features].astype(int)\n        # 找到每条记录中该action产生的reward\n        reward = batch_memory[:, self.n_features + 1]\n\n        # 核心公式，对于一批样本中的每一个记录中的s和选择了的a，其目标q值就是：\n        # 选择这个a产生的reward，加上系数gamma乘以{这个a到达的下一个状态s_的所有可能动作的q}中的最大值\n        q_target[batch_index, pred_act_index] = reward + \\\n            self.gamma * np.max(q_next, axis=1)\n\n        # 将s传入预测网络得到q_pred，将q_target和q_pred传入loss节点计算损失，用损失训练预测网络\n        _, self.cost = self.sess.run([self._train_op, self.loss],\n                                     feed_dict={self.s: batch_memory[:, :self.n_features],\n                                                self.q_target: q_target})\n\n        # 记录每一步的误差\n        self.cost_his.append(self.cost)\n\n        # 逐渐增加epsilon，直到给出的epsilon最大值\n        self.epsilon = self.epsilon + \\\n            self.epsilon_increment if self.epsilon_max else self.epsilon_max\n        # 学习步数加一\n        self.learn_step_counter += 1\n\n\n# 主函数\nif __name__ == '__main__':\n    DeepQNetwork = DQN(3, 4, output_graph=True)\n", "meta": {"hexsha": "cd05c8abf4f4f90a5a8f775c27103db4ad091302", "size": 8396, "ext": "py", "lang": "Python", "max_stars_repo_path": "reference/DQN.py", "max_stars_repo_name": "weixr18/DQNFlappy", "max_stars_repo_head_hexsha": "46e68200a6b8ad791bf825d90f99da81c3677831", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reference/DQN.py", "max_issues_repo_name": "weixr18/DQNFlappy", "max_issues_repo_head_hexsha": "46e68200a6b8ad791bf825d90f99da81c3677831", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reference/DQN.py", "max_forks_repo_name": "weixr18/DQNFlappy", "max_forks_repo_head_hexsha": "46e68200a6b8ad791bf825d90f99da81c3677831", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5043478261, "max_line_length": 98, "alphanum_fraction": 0.5846831825, "include": true, "reason": "import numpy", "num_tokens": 2647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.1668266012846871}}
{"text": "''' A package for implementing Caffe-like network structure using Owl APIs.\n\nThe package implements Caffe-like network structure with some minor differences. It uses Caffe-defined \nprotobuf as core data structure so Caffe users could easily adapt to this. The package serves the purpose\nof:\n\n1. Quick deployment of neural network training using configure file.\n2. Demonstrate the power of ``owl`` package (it takes only several hundreds LOC to implement Caffe and run it on dataflow engine).\n'''\n\nimport numpy as np\nimport math\nimport Queue\n\nimport owl\nimport owl.elewise as ele\nimport owl.conv as co\nfrom caffe import *\n\nfrom netio import LMDBDataProvider\nfrom netio import ImageListDataProvider\nfrom netio import ImageWindowDataProvider\n\nclass ComputeUnit(object):\n    ''' Interface for each compute unit.\n\n    In ``owl.net``, the network is graph (in fact a DAG) that is composed of ``ComputeUnit`` s.\n    ``ComputeUnit`` is a wrap-up of Caffe's ``layer`` abstraction, but is more\n    general and flexible in its function sigature.\n\n    :ivar caffe.LayerParameter params: layer parameter in Caffe's proto structure\n    :ivar str name: name of the unit; the name must be unique\n    :ivar btm_names: names of the bottom units\n    :vartype btm_names: list str\n    :ivar top_names: names of the top units\n    :vartype top_names: list str\n    :ivar list int out_shape:\n\n    .. note::\n        ``params``, ``name``, ``btm_names`` and ``top_names`` will be parsed from Caffe's network\n        description file. ``out_shape`` should be set in :py:meth:`compute_size`\n\n    '''\n    def __init__(self, params):\n        self.params = params\n        self.name = params.name\n        self.btm_names = []\n        self.top_names = []\n        self.out = None\n        self.out_shape = None\n        self.rec_on_ori = None\n        self.stride_on_ori = None\n        self.start_on_ori = None\n    def __str__(self):\n        return 'N/A unit'\n    def compute_size(self, from_btm, to_top):\n        ''' Calculate the output size of this unit\n\n        This function will be called before training during the ``compute_size`` phase.\n        The ``compute_size`` phase is a feed-forward-like phase, during which each ``ComputeUnit``, rather than\n        calculating the output tensor but calculating the output size (list int) for the top units. The\n        size is usually used to calculate the weight and bias size for initialization.\n\n        :param dict from_btm: input size from bottom units\n        :param dict to_top: output size to top units\n\n        .. seealso::\n            :py:meth:`FullyConnection.compute_size`\n            :py:meth:`ConvConnection.compute_size`\n            :py:meth:`Net.compute_size`\n        '''\n        pass\n    def forward(self, from_btm, to_top, phase):\n        ''' Function for forward propagation\n\n        This function will be called during forward-propagation. The function\n        should take input in ``from_btm``, perform customized computation, and then\n        put the result in ``to_top``. Both ``from_btm`` and ``to_top`` are ``dict`` type \n        where key is a ``str`` of name of the bottom/top units and value is an ``owl.NArray``\n        served as input or output of the function.\n\n        :param dict from_btm: input from bottom units\n        :param dict to_top: output for top units\n        :param str phase: name of the phase of the running. Currently either ``\"TRAIN\"`` or ``\"TEST\"``\n        '''\n        pass\n    def backward(self, from_top, to_btm, phase):\n        ''' Function for backward propagation\n\n        This function will be called during backward-propagation. Similar to :py:meth:`forward`,\n        The function should take input in ``from_top``, perform customized computation, and then\n        put the result in ``to_btm``. The function also need to calculate the gradient (if any) and\n        save them to the ``weightgrad`` field (see :py:meth:WeightedComputeUnit.weight_update).\n\n        :param dict from_top: input from top units\n        :param dict to_btm: output for top units\n        :param str phase: name of the phase of the running. Currently either ``\"TRAIN\"`` or ``\"TEST\"``\n        '''\n        pass\n    def weight_update(self, base_lr, base_weight_decay, momentum, batch_size):\n        ''' Function for weight update\n\n        This function will be called during weight update. \n\n        :param float base_lr: base learning rate\n        :param float base_weight_decay: base weight decay\n        :param float momentum: momentum value\n        :param int batch_size: the size of the current minibatch\n        '''\n        pass\n\nclass ComputeUnitSimple(ComputeUnit):\n    ''' An auxiliary class for :py:class:`ComputeUnit` that will only have one input unit and one output unit.\n    '''\n    def __init__(self, params):\n        super(ComputeUnitSimple, self).__init__(params)\n    def compute_size(self, from_btm, to_top):\n        ''' Set the ``out_shape`` as the same shape of the input. Inherited classes could override this function.\n        '''\n        to_top[self.top_names[0]] = dict()\n        to_top[self.top_names[0]]['out_shape'] = from_btm[self.btm_names[0]]['out_shape'][:]\n        to_top[self.top_names[0]]['rec_on_ori'] = from_btm[self.btm_names[0]]['rec_on_ori']\n        to_top[self.top_names[0]]['stride_on_ori'] = from_btm[self.btm_names[0]]['stride_on_ori']\n        to_top[self.top_names[0]]['start_on_ori'] = from_btm[self.btm_names[0]]['start_on_ori']\n        self.out_shape = to_top[self.top_names[0]]['out_shape'][:]\n        self.rec_on_ori = to_top[self.top_names[0]]['rec_on_ori']\n        self.stride_on_ori = to_top[self.top_names[0]]['stride_on_ori']\n        self.start_on_ori = to_top[self.top_names[0]]['start_on_ori']\n    def forward(self, from_btm, to_top, phase):\n        ''' Transform the interface from multiple input/output to only one input/output function :py:meth:`ff`.\n        '''\n        to_top[self.top_names[0]] = self.ff(from_btm[self.btm_names[0]], phase)\n        self.out = to_top[self.top_names[0]]\n    def ff(self, act, phase):\n        ''' Function for forward-propagation\n\n        :param owl.NArray act: the activation from the bottom unit\n        :param str phase: name of the phase of the running. Currently either ``\"TRAIN\"`` or ``\"TEST\"``\n        :return: the activation of this unit\n        :rtype: owl.NArray\n        '''\n        pass\n    def backward(self, from_top, to_btm, phase):\n        ''' Transform the interface from multiple input/output to only one input/output function :py:meth:`bp`.\n        '''\n        to_btm[self.btm_names[0]] = self.bp(from_top[self.top_names[0]], phase)\n    def bp(self, sen, phase):\n        ''' Function for backward-propagation\n\n        :param owl.NArray sen: the sensitivity (or error derivative to the input) from the top unit\n        :return: the sensitivity of this unit\n        :rtype: owl.NArray\n        '''\n        pass\n\nclass WeightedComputeUnit(ComputeUnitSimple):\n    ''' An auxiliary class for :py:class:`ComputeUnit` with weights\n\n    :ivar owl.NArray weight: weight tensor\n    :ivar owl.NArray weightdelta: momentum of weight\n    :ivar owl.NArray weightgrad: gradient of weight\n    :ivar owl.NArray bias: bias tensor\n    :ivar owl.NArray biasdelta: momentum of bias\n    :ivar owl.NArray biasgrad: gradient of bias\n    :ivar float lr_mult_w: learning rate multiplier for the weight of this unit\n    :ivar float lr_mult_b: bias learning rate multiplier for the bias of this unit\n    :ivar float decay_mult_w: decay multiplier for the weight of this unit\n    :ivar float decay_mult_b: decay multiplier for the bias of this unit\n    '''\n    def __init__(self, params):\n        super(WeightedComputeUnit, self).__init__(params)\n        # weights and bias\n        self.weight = None\n        self.weightdelta = None\n        self.weightgrad = None\n        self.bias = None\n        self.biasdelta = None\n        self.biasgrad = None\n      \n        self.in_shape = None\n        self.fan_in = None\n        self.fan_out = None\n\n        # blob learning rate and weight decay\n        if len(params.param) >= 1:\n            self.lr_mult_w = params.param[0].lr_mult\n            self.decay_mult_w = params.param[0].decay_mult\n        else:\n            self.lr_mult_w = 1\n            self.decay_mult_w = 1\n\n        if len(params.param) >= 2:\n            self.lr_mult_b = params.param[1].lr_mult\n            self.decay_mult_b = params.param[1].decay_mult\n        else:\n            self.lr_mult_b = 1\n            self.decay_mult_b = 0\n\n        #self.blobs_lr = params.blobs_lr\n        #self.weight_decay = params.weight_decay\n        #if len(self.blobs_lr) == 0:\n            #self.blobs_lr = [1,1]\n        #if len(self.weight_decay) == 0:\n            #self.weight_decay = [1, 0]\n    \n    def compute_size(self, from_btm, to_top):\n        pass \n   \n    def init_weights_with_filler(self):\n        ''' Init weights & bias. The function will be called during weight initialization.\n\n        Currently, four types of initializers are supported: ``\"constant\", \"gaussian\", \"uniform\", \"xavier\"``.\n        '''\n        #init weight\n        npweights = None\n        if self.weight_filler.type == \"constant\":\n            npweights = np.ones(self.wshape, dtype = np.float32) * self.weight_filler.value\n        elif self.weight_filler.type == \"gaussian\":\n            npweights = np.random.normal(self.weight_filler.mean, self.weight_filler.std, self.wshape)\n        elif self.weight_filler.type == \"uniform\":\n            npweights = np.random.uniform(self.weight_filler.min, self.weight_filler.max, self.wshape)\n        elif self.weight_filler.type == \"xavier\":\n            scale = np.sqrt(float(3)/self.fan_in)\n            npweights = np.random.uniform(-scale, scale, self.wshape)\n        self.weight = owl.from_numpy(npweights.astype(np.float32)).reshape(self.wshape)\n      \n        #init bias\n        npwbias = None\n        if self.bias_filler.type == \"constant\":\n            npbias = np.ones(self.bshape, dtype = np.float32) * self.bias_filler.value\n        elif self.bias_filler.type == \"gaussian\":\n            npbias = np.random.normal(self.bias_filler.mean, self.bias_filler.std, self.bshape)\n        elif self.bias_filler.type == \"uniform\":\n            npbias = np.random.uniform(self.bias_filler.min, self.bias_filler.max, self.bshape)\n        elif self.bias_filler.type == \"xavier\":\n            scale = np.sqrt(float(3)/self.fan_in)\n            npbias = np.random.uniform(-scale, scale, self.bshape)\n        self.bias = owl.from_numpy(npbias.astype(np.float32)).reshape(self.bshape)\n        \n    def weight_update(self, base_lr, base_weight_decay, momentum, batch_size):\n        ''' Update the weight & bias\n\n        Using following formula:\n\n        ``$_delta = momentum * $_delta - (base_lr * $_lr / batch_size) * $_grad - (base_lr * $_lr * base_wd * $_wd) * $``\n        \n        , where ``$`` could be either ``weight`` or ``bias``.\n        '''\n        if self.weightdelta == None:\n            self.weightdelta = owl.zeros(self.weightgrad.shape)\n\n        self.weightdelta = momentum * self.weightdelta \\\n                        - (base_lr * self.lr_mult_w / batch_size) * self.weightgrad \\\n                        - (base_lr * self.lr_mult_w * base_weight_decay * self.decay_mult_w) * self.weight\n        \n        self.weight = self.weight + self.weightdelta\n        self.weightgrad = None\n\n        if self.biasdelta == None:\n            self.biasdelta = owl.zeros(self.biasgrad.shape)\n\n        self.biasdelta = momentum * self.biasdelta \\\n                        - (base_lr * self.lr_mult_b / batch_size) * self.biasgrad \\\n                        - (base_lr * self.lr_mult_b * base_weight_decay * self.decay_mult_b) * self.bias\n        self.bias = self.bias + self.biasdelta\n        self.biasgrad = None\n\nclass LinearUnit(ComputeUnitSimple):\n    ''' Compute unit for linear transformation\n    '''\n    def ff(self, x, phase):\n        return x\n    def bp(self, y, phase):\n        return y\n    def __str__(self):\n        return 'linear'\n\nclass SigmoidUnit(ComputeUnitSimple):\n    ''' Compute unit for Sigmoid non-linearity\n    '''\n    def ff(self, x, phase):\n        return ele.sigm(x)\n    def bp(self, y, phase):\n        return ele.sigm_back(y)\n    def __str__(self):\n        return 'sigmoid'\n\nclass ReluUnit(ComputeUnitSimple):\n    ''' Compute unit for RELU non-linearity\n    '''\n    def ff(self, x, phase):\n        self.ff_x = x\n        return ele.relu(x)\n    def bp(self, y, phase):\n        return ele.relu_back(y, self.ff_x)\n    def __str__(self):\n        return 'relu'\n\nclass TanhUnit(ComputeUnitSimple):\n    ''' Compute unit for Hyperbolic Tangine non-linearity\n    '''\n    def ff(self, x, phase):\n        return ele.tanh(x)\n    def bp(self, y, phase):\n        return ele.tanh_back(y)\n    def __str__(self):\n        return 'tanh'\n\nclass PoolingUnit(ComputeUnitSimple):\n    ''' Compute unit for Pooling\n\n    .. note::\n        The input and output is of size ``[HWCN]``:\n\n        - ``H``: image height\n        - ``W``: image width\n        - ``C``: number of image channels (feature maps)\n        - ``N``: size of minibatch\n    '''\n    def __init__(self, params):\n        super(PoolingUnit, self).__init__(params)\n        self.ppa = params.pooling_param\n        if self.ppa.pool == PoolingParameter.PoolMethod.Value('MAX'):\n            pool_ty = co.pool_op.max\n        elif self.ppa.pool == PoolingParameter.PoolMethod.Value('AVE'):\n            pool_ty = co.pool_op.average\n        self.pooler = co.Pooler(self.ppa.kernel_size, self.ppa.kernel_size,\n                                self.ppa.stride, self.ppa.stride,\n                                self.ppa.pad, self.ppa.pad,\n                                pool_ty)\n        \n    def compute_size(self, from_btm, to_top):\n        self.out_shape = from_btm[self.btm_names[0]]['out_shape'][:]\n        ori_height = self.out_shape[0]\n        ori_width = self.out_shape[1]\n        self.out_shape[0] = int(np.ceil(float(self.out_shape[0] + 2 * self.ppa.pad - self.ppa.kernel_size) / self.ppa.stride)) + 1\n        self.out_shape[1] = int(np.ceil(float(self.out_shape[1] + 2 * self.ppa.pad - self.ppa.kernel_size) / self.ppa.stride)) + 1\n        if self.ppa.pad:\n            if (self.out_shape[0] - 1) * self.ppa.stride >= ori_height + self.ppa.pad:\n                self.out_shape[0] = self.out_shape[0] - 1\n                self.out_shape[1] = self.out_shape[1] - 1\n        to_top[self.top_names[0]] = dict()\n        to_top[self.top_names[0]]['out_shape'] = self.out_shape[:]\n        to_top[self.top_names[0]]['stride_on_ori'] = from_btm[self.btm_names[0]]['stride_on_ori'] * self.ppa.stride\n        to_top[self.top_names[0]]['rec_on_ori'] = from_btm[self.btm_names[0]]['rec_on_ori'] + (self.ppa.kernel_size - 1) * from_btm[self.btm_names[0]]['stride_on_ori']\n        to_top[self.top_names[0]]['start_on_ori'] = from_btm[self.btm_names[0]]['start_on_ori'] - self.ppa.pad * from_btm[self.btm_names[0]]['stride_on_ori']\n        self.rec_on_ori = to_top[self.top_names[0]]['rec_on_ori']\n        self.stride_on_ori = to_top[self.top_names[0]]['stride_on_ori']\n        self.start_on_ori = to_top[self.top_names[0]]['start_on_ori']\n\n    def ff(self, x, phase):\n        self.ff_x = x\n        self.ff_y = self.pooler.ff(x)\n        return self.ff_y\n    def bp(self, y, phase):\n        return self.pooler.bp(y, self.ff_y, self.ff_x)\n    def __str__(self):\n        return 'pooling'\n\nclass DropoutUnit(ComputeUnitSimple):\n    ''' Compute unit for dropout\n    '''\n    def __init__(self, params):\n        super(DropoutUnit, self).__init__(params)\n        self.scale = 1.0 / (1.0 - self.params.dropout_param.dropout_ratio)\n        self.keep_ratio = 1 - self.params.dropout_param.dropout_ratio\n    def ff(self, x, phase):\n        ''' Foward function of dropout\n        \n        The dropout mask will not be multiplied if under ``\"TEST\"`` mode.\n        '''\n        if phase == \"TRAIN\":\n            self.dropmask = owl.randb(x.shape, self.keep_ratio)\n            return ele.mult(x, self.dropmask)*self.scale\n        else:\n            return x\n        #for gradient test\n        #return x\n    def bp(self, y, phase):\n        if phase == \"TRAIN\":\n            return ele.mult(y, self.dropmask)*self.scale\n        else:\n            return y\n    def __str__(self):\n        return 'dropout'\n\nclass SoftmaxUnit(ComputeUnit):\n    ''' Compute unit for softmax\n    '''\n    def __init__(self, params):\n        super(SoftmaxUnit, self).__init__(params)\n        self.loss_weight = params.loss_weight\n    \n    def compute_size(self, from_btm, to_top):\n        to_top[self.top_names[0]] = dict()\n        to_top[self.top_names[0]]['out_shape'] = from_btm[self.btm_names[0]]['out_shape'][:]\n        to_top[self.top_names[0]]['rec_on_ori'] = from_btm[self.btm_names[0]]['rec_on_ori']\n        to_top[self.top_names[0]]['stride_on_ori'] = from_btm[self.btm_names[0]]['stride_on_ori']       \n        to_top[self.top_names[0]]['start_on_ori'] = from_btm[self.btm_names[0]]['start_on_ori']       \n        \n        self.out_shape = to_top[self.top_names[0]]['out_shape'][:]\n        self.stride_on_ori = to_top[self.top_names[0]]['stride_on_ori']\n        self.start_on_ori = to_top[self.top_names[0]]['start_on_ori']\n        self.rec_on_ori = to_top[self.top_names[0]]['rec_on_ori']\n    \n    def forward(self, from_btm, to_top, phase):\n        to_top[self.top_names[0]] = co.softmax(from_btm[self.btm_names[0]], co.soft_op.instance)\n        self.ff_y = to_top[self.top_names[0]]\n        #turn label into matrix form\n        nplabel = np.zeros([self.ff_y.shape[1], self.ff_y.shape[0]], dtype=np.float32)\n        self.strlabel = from_btm[self.btm_names[1]]\n        \n        for i in range(len(self.strlabel)):\n            nplabel[i, self.strlabel[i]] = 1\n        self.y = owl.from_numpy(nplabel)\n        self.out = self.ff_y\n\n\n        \n    def backward(self, from_top, to_btm, phase):\n        if len(self.loss_weight) == 1:\n            to_btm[self.btm_names[0]] = (self.ff_y - self.y)*self.loss_weight[0]\n        else:\n            to_btm[self.btm_names[0]] = (self.ff_y - self.y)\n\n    def getloss(self):\n        ''' Get the loss of the softmax (cross entropy)\n        '''\n        lossmat = ele.mult(ele.ln(self.ff_y), self.y)\n        res = lossmat.sum(0).sum(1).to_numpy()\n        return -res[0][0] / lossmat.shape[1]\n\n    def __str__(self):\n        return 'softmax'\n\nclass AccuracyUnit(ComputeUnit):\n    ''' Compute unit for calculating accuracy\n\n    .. note::\n        In terms of Minerva's lazy evaluation, the unit is a **non-lazy** one since it gets the actual\n        contents (accuracy) out of an ``owl.NArray``.\n    '''\n    def __init__(self, params):\n        super(AccuracyUnit, self).__init__(params)\n        self.acc = 0\n        self.batch_size = 0\n        self.top_k = params.accuracy_param.top_k\n\n    def compute_size(self, from_btm, to_top):\n        to_top[self.top_names[0]] = dict()\n        to_top[self.top_names[0]]['out_shape'] = from_btm[self.btm_names[0]]['out_shape'][:]\n        to_top[self.top_names[0]]['rec_on_ori'] = from_btm[self.btm_names[0]]['rec_on_ori']\n        to_top[self.top_names[0]]['stride_on_ori'] = from_btm[self.btm_names[0]]['stride_on_ori']             \n        to_top[self.top_names[0]]['start_on_ori'] = from_btm[self.btm_names[0]]['start_on_ori']             \n        \n        self.out_shape = to_top[self.top_names[0]]['out_shape'][:]\n        self.stride_on_ori = to_top[self.top_names[0]]['stride_on_ori']\n        self.start_on_ori = to_top[self.top_names[0]]['start_on_ori']\n        self.rec_on_ori = to_top[self.top_names[0]]['rec_on_ori']\n    \n    def forward(self, from_btm, to_top, phase):\n        if self.top_k == 1:\n            predict = from_btm[self.btm_names[0]].max_index(0)\n            ground_truth = owl.from_numpy(from_btm[self.btm_names[1]]).reshape(predict.shape)\n            self.batch_size = from_btm[self.btm_names[0]].shape[1]\n            correct = (predict - ground_truth).count_zero()\n            self.acc = correct * 1.0 / self.batch_size\n        elif self.top_k == 5:\n            predict = from_btm[self.btm_names[0]].to_numpy()\n            top_5 = np.argsort(predict, axis=1)[:,::-1]\n            ground_truth = from_btm[self.btm_names[1]]\n            self.batch_size = np.shape(ground_truth)[0]\n            correct = 0\n            for i in range(self.batch_size):\n                for t in range(5):\n                    if ground_truth[i] == top_5[i,t]:\n                        correct += 1\n                        break\n            self.acc = correct * 1.0 / self.batch_size\n        else:\n            assert(FALSE)\n\n    def backward(self, from_top, to_btm, phase):\n        pass\n\n    def __str__(self):\n        return 'accuracy'\n\nclass LRNUnit(ComputeUnitSimple):\n    ''' Compute unit for LRN\n    '''\n    def __init__(self, params):\n        super(LRNUnit, self).__init__(params)\n        self.lrner = co.Lrner(params.lrn_param.local_size, params.lrn_param.alpha, params.lrn_param.beta)\n        self.scale = None\n    def ff(self, x, phase):\n        self.ff_x = x\n        self.scale = owl.zeros(x.shape)\n        self.ff_y = self.lrner.ff(x, self.scale)\n        return self.ff_y\n    def bp(self, y, phase):\n        return self.lrner.bp(self.ff_x, self.ff_y, self.scale, y)\n    def __str__(self):\n        return 'lrn'\n\nclass ConcatUnit(ComputeUnit):\n    ''' Compute unit for concatenation\n\n    Concatenate input arrays along the dimension specified by Caffe's ``concat_dim_caffe``\n    '''\n    def __init__(self, params):\n        super(ConcatUnit, self).__init__(params)\n        self.concat_dim_caffe = params.concat_param.concat_dim\n        self.slice_count = []\n\n    def compute_size(self, from_btm, to_top):\n        to_top[self.top_names[0]] = dict()\n        to_top[self.top_names[0]]['out_shape'] = from_btm[self.btm_names[0]]['out_shape'][:]\n        to_top[self.top_names[0]]['rec_on_ori'] = from_btm[self.btm_names[0]]['rec_on_ori']\n        to_top[self.top_names[0]]['stride_on_ori'] = from_btm[self.btm_names[0]]['stride_on_ori'] \n        to_top[self.top_names[0]]['start_on_ori'] = from_btm[self.btm_names[0]]['start_on_ori'] \n        \n        self.concat_dim = len(from_btm[self.btm_names[0]]['out_shape']) - 1 - self.concat_dim_caffe\n        for i in range(1, len(self.btm_names)):\n            to_top[self.top_names[0]]['out_shape'][self.concat_dim] = to_top[self.top_names[0]]['out_shape'][self.concat_dim] + from_btm[self.btm_names[i]]['out_shape'][self.concat_dim]\n        self.out_shape = to_top[self.top_names[0]]['out_shape'][:]\n        self.stride_on_ori = to_top[self.top_names[0]]['stride_on_ori']\n        self.start_on_ori = to_top[self.top_names[0]]['start_on_ori']\n        self.rec_on_ori = to_top[self.top_names[0]]['rec_on_ori']\n\n    def forward(self, from_btm, to_top, phase):\n        narrays = []\n        self.concat_dim = len(from_btm[self.btm_names[0]].shape) - 1 - self.concat_dim_caffe\n        for i in range(len(self.btm_names)):\n            narrays.append(from_btm[self.btm_names[i]])\n            self.slice_count.append(from_btm[self.btm_names[i]].shape[self.concat_dim])\n        to_top[self.top_names[0]] = owl.concat(narrays, self.concat_dim)\n        self.out = to_top[self.top_names[0]] \n    \n    def backward(self, from_top, to_btm, phase):\n        st_off = 0\n        for i in range(len(self.btm_names)):\n            to_btm[self.btm_names[i]] = owl.slice(from_top[self.top_names[0]],\n                                                  self.concat_dim,\n                                                  st_off,\n                                                  self.slice_count[i])\n            st_off += self.slice_count[i]\n    def __str__(self):\n        return 'concat'\n\nclass FullyConnection(WeightedComputeUnit):\n    ''' Compute unit for traditional fully connected layer\n    '''\n    def __init__(self, params):\n        super(FullyConnection, self).__init__(params)\n        self.inner_product_param = params.inner_product_param\n        self.weight_filler = params.inner_product_param.weight_filler\n        self.bias_filler = params.inner_product_param.bias_filler\n    \n    def compute_size(self, from_btm, to_top):\n        ''' Compute the output size and also weight and bias size\n        The weight size is ``[top_shape[0], btm_shape[0]]``; the bias size is ``[top_shape[0], 1]``\n        (assume both ``top`` and ``btm`` are 2-dimensional array)\n        '''\n        shp = from_btm[self.btm_names[0]]['out_shape'][:]\n        if len(shp) > 2:\n            self.in_shape = [np.prod(shp[0:-1], dtype=np.int32), shp[-1]]\n        else:\n            self.in_shape = shp\n        to_top[self.top_names[0]] = dict() \n        to_top[self.top_names[0]]['out_shape'] = self.in_shape[:]\n        to_top[self.top_names[0]]['out_shape'][0] = self.inner_product_param.num_output\n        to_top[self.top_names[0]]['out_shape'][1] = 1 \n        self.out_shape = to_top[self.top_names[0]]['out_shape'][:]\n        self.wshape = [self.out_shape[0], self.in_shape[0]]\n        self.bshape = [self.out_shape[0], 1]\n\n        if len(shp) > 2:\n            #last layer is conv layer\n            self.rec_on_ori = from_btm[self.btm_names[0]]['rec_on_ori'] + (shp[0] - 1) * from_btm[self.btm_names[0]]['stride_on_ori']\n            self.stride_on_ori = self.rec_on_ori\n        else:\n            self.rec_on_ori = from_btm[self.btm_names[0]]['rec_on_ori']\n            self.stride_on_ori = from_btm[self.btm_names[0]]['stride_on_ori']\n\n        to_top[self.top_names[0]]['rec_on_ori'] = self.rec_on_ori\n        to_top[self.top_names[0]]['stride_on_ori'] = self.stride_on_ori\n        to_top[self.top_names[0]]['start_on_ori'] = from_btm[self.btm_names[0]]['start_on_ori']\n        self.start_on_ori = to_top[self.top_names[0]]['start_on_ori']\n        #set fan_in fan_out\n        self.fan_out = self.inner_product_param.num_output\n        self.fan_in = np.prod(from_btm[self.btm_names[0]]['out_shape'][0:len(from_btm[self.btm_names[0]]['out_shape'])])\n\n\n    def ff(self, act, phase):\n        shp = act.shape\n        if len(shp) > 2:\n            a = act.reshape([np.prod(shp[0:-1], dtype=np.int32), shp[-1]])\n        else:\n            a = act\n        self.ff_act = act # save ff value\n        if self.weight == None:\n            self.init_weights_with_filler()\n        return self.weight * a + self.bias\n\n    def bp(self, sen, phase):\n        shp = self.ff_act.shape\n        if len(shp) > 2:\n            a = self.ff_act.reshape([np.prod(shp[0:-1], dtype=np.int32), shp[-1]])\n        else:\n            a = self.ff_act\n        self.weightgrad = sen * a.trans()\n        self.biasgrad = sen.sum(1)\n        s = self.weight.trans() * sen\n        if len(shp) > 2:\n            s = s.reshape(shp)\n        return s\n    def __str__(self):\n        return 'fc'\n\nclass ConvConnection(WeightedComputeUnit):\n    ''' Convolution operation\n\n    .. note::\n        The input and output is of size ``[HWCN]``:\n\n        - ``H``: image height\n        - ``W``: image width\n        - ``C``: number of image channels (feature maps)\n        - ``N``: size of minibatch\n\n    '''\n    def __init__(self, params):\n        super(ConvConnection, self).__init__(params)\n        self.conv_params = params.convolution_param\n        self.convolver = co.Convolver(self.conv_params.pad,\n                self.conv_params.pad, self.conv_params.stride, self.conv_params.stride)\n        self.num_output = params.convolution_param.num_output\n        self.group = params.convolution_param.group\n        \n\n        #TODO: hack, we don't want to slice agian to use it into bp as a parameter\n        self.group_data = []\n        self.group_filter = []\n        self.group_bias = []\n        self.weight_filler = params.convolution_param.weight_filler\n        self.bias_filler = params.convolution_param.bias_filler\n    \n    def compute_size(self, from_btm, to_top):\n        ''' Compute the output size and also weight and bias size\n\n        .. note::\n            The weight(kernel) size is ``[HWCiCo]``; bias shape is ``[Co]``:\n\n            - ``H``: kernel_height\n            - ``W``: kernel_width\n            - ``Ci``: number of input channels\n            - ``Co``: number of output channels\n        '''\n        self.in_shape = from_btm[self.btm_names[0]]['out_shape'][:]\n        to_top[self.top_names[0]] = dict()\n        to_top[self.top_names[0]]['out_shape'] = from_btm[self.btm_names[0]]['out_shape'][:]\n        to_top[self.top_names[0]]['out_shape'][0] = (to_top[self.top_names[0]]['out_shape'][0] + 2 * self.conv_params.pad - self.conv_params.kernel_size) / self.conv_params.stride + 1\n        to_top[self.top_names[0]]['out_shape'][1] = (to_top[self.top_names[0]]['out_shape'][1] + 2 * self.conv_params.pad - self.conv_params.kernel_size) / self.conv_params.stride + 1\n        to_top[self.top_names[0]]['out_shape'][2] = self.num_output\n        self.out_shape = to_top[self.top_names[0]]['out_shape'][:]\n        self.wshape = [self.conv_params.kernel_size,\n                       self.conv_params.kernel_size,\n                       self.in_shape[2],\n                       self.num_output]\n        self.bshape = [self.out_shape[2]]\n        \n        to_top[self.top_names[0]]['stride_on_ori'] = from_btm[self.btm_names[0]]['stride_on_ori'] * self.conv_params.stride\n        to_top[self.top_names[0]]['rec_on_ori'] = from_btm[self.btm_names[0]]['rec_on_ori'] + (self.conv_params.kernel_size - 1) * from_btm[self.btm_names[0]]['stride_on_ori']\n        to_top[self.top_names[0]]['start_on_ori'] = from_btm[self.btm_names[0]]['start_on_ori'] - self.conv_params.pad * from_btm[self.btm_names[0]]['stride_on_ori']\n        self.stride_on_ori = to_top[self.top_names[0]]['stride_on_ori']\n        self.start_on_ori = to_top[self.top_names[0]]['start_on_ori']\n        self.rec_on_ori = to_top[self.top_names[0]]['rec_on_ori']\n        #set fan_in fan_out\n        self.fan_out = self.conv_params.kernel_size * self.conv_params.kernel_size * self.conv_params.num_output\n        self.fan_in = self.conv_params.kernel_size * self.conv_params.kernel_size * from_btm[self.btm_names[0]]['out_shape'][2]\n\n    def ff(self, act, phase):\n        ''' Feed-forward of convolution\n\n        .. warning::\n            Currently multi-group convolution (as in AlexNet paper) is not supported. One could walk around it by\n            using a bigger convolution with number of feature maps doubled.\n        '''\n        if self.group == 1:\n            self.ff_act = act\n            if self.weight == None:\n                self.init_weights_with_filler()\n            return self.convolver.ff(act, self.weight, self.bias)\n        else:\n            #currently doesn't support multi-group\n            assert(False)\n        \n    def bp(self, sen, phase):\n        ''' Backward propagation of convolution\n\n        .. warning::\n            Currently multi-group convolution (as in AlexNet paper) is not supported. One could walk around it by\n            using a bigger convolution with number of feature maps doubled.\n        '''\n        if self.group == 1:\n            self.weightgrad = self.convolver.weight_grad(sen, self.ff_act, self.weight)\n            self.biasgrad = self.convolver.bias_grad(sen)\n            return self.convolver.bp(sen, self.ff_act, self.weight)\n        else:\n            #currently doesn't support multi-group\n            assert(False)\n            \n    def __str__(self):\n        return 'conv'\n\nclass DataUnit(ComputeUnit):\n    ''' The base class of dataunit.\n    \n    :ivar dp: dataprovider, different kind of dp load data from different formats\n    :ivar generator: the iterator produced by dataprovider\n    '''\n\n    def __init__(self, params, num_gpu):\n        super(DataUnit, self).__init__(params)\n\n    def compute_size(self, from_btm, to_top):\n        pass\n\n    def forward(self, from_btm, to_top, phase):\n        ''' Feed-forward of data unit will get a batch of a fixed batch_size from data provider. \n\n        .. note::\n            \n            Phase indicates whether it's training or testing. Usualy, the data augmentation operation for training involves some randomness, while testing doesn't\n        \n        '''\n        \n        if self.generator == None:\n            self.generator = self.dp.get_mb(phase)\n\n        while True:\n            try:\n                (samples, labels) = next(self.generator)\n                if len(labels) == 0:\n                    (samples, labels) = next(self.generator)\n            except StopIteration:\n                print 'Have scanned the whole dataset; start from the begginning agin'\n                self.generator = self.dp.get_mb(phase)\n                continue\n            break\n\n        to_top[self.top_names[0]] = owl.from_numpy(samples).reshape(\n                [self.crop_size, self.crop_size, 3, samples.shape[0]])\n        #may have multiplier labels\n        for i in range (1, len(self.top_names)):\n            to_top[self.top_names[i]] = labels[:,i - 1]\n\n        #the output of datalayer is the data not label\n        self.out = to_top[self.top_names[0]]\n\n    def backward(self, from_top, to_btm, phase):\n        # no bp pass\n        pass\n    def __str__(self):\n        return 'data'\n\nclass LMDBDataUnit(DataUnit):\n    ''' DataUnit load from LMDB.\n\n    :ivar caffe.LayerParameter params: lmdb data layer param defined by Caffe, params.data_param contains information about data source, parmas.transform_param mainly defines data augmentation operations\n    \n    '''\n    \n    \n    def __init__(self, params, num_gpu):\n        super(LMDBDataUnit, self).__init__(params, num_gpu)\n        if params.include[0].phase == Phase.Value('TRAIN'):\n            self.dp = LMDBDataProvider(params.data_param, params.transform_param, num_gpu)\n        else:\n            self.dp = LMDBDataProvider(params.data_param, params.transform_param, 1)\n        self.params = params\n        self.crop_size = params.transform_param.crop_size\n        self.generator = None\n        self.out = None\n        self.multiview = False\n\n    def compute_size(self, from_btm, to_top):\n        self.out_shape = [self.params.transform_param.crop_size,\n                          self.params.transform_param.crop_size,\n                          3, 1]\n        to_top[self.top_names[0]] = dict()\n        to_top[self.top_names[0]]['out_shape'] = self.out_shape[:]\n        to_top[self.top_names[0]]['rec_on_ori'] = 1\n        to_top[self.top_names[0]]['stride_on_ori'] = 1 \n        to_top[self.top_names[0]]['start_on_ori'] = 0\n        self.rec_on_ori = 1\n        self.stride_on_ori = 1\n        self.start_on_ori = 0\n\n   \n    def forward(self, from_btm, to_top, phase):\n        ''' Feed-forward operation may vary according to phase. \n\n        .. note::\n\n            LMDB data provider now support multi-view testing, if multiview == True, it will produce concequtive 10 batches of different views of the same original image     \n        '''\n        if self.generator == None:\n            if self.multiview == False:\n                self.generator = self.dp.get_mb(phase)\n            #multiview test\n            else:\n                self.generator = self.dp.get_multiview_mb()\n        while True:\n            try:\n                (samples, labels) = next(self.generator)\n                if len(labels) == 0:\n                    (samples, labels) = next(self.generator)\n            except StopIteration:\n                print 'Have scanned the whole dataset; start from the begginning agin'\n                if self.multiview == False:\n                    self.generator = self.dp.get_mb(phase)\n                #multiview test\n                else:\n                    self.generator = self.dp.get_multiview_mb()\n                continue\n            break\n        to_top[self.top_names[0]] = owl.from_numpy(samples).reshape(\n                [self.crop_size, self.crop_size, 3, samples.shape[0]])\n        for i in range (1, len(self.top_names)):\n            to_top[self.top_names[i]] = labels[:,i - 1]\n        #to_top[self.top_names[0]] = owl.zeros([self.crop_size, self.crop_size, 3, 256])\n        #for i in range (1, len(self.top_names)):\n            #to_top[self.top_names[i]] = np.ones(256)\n        self.out = to_top[self.top_names[0]]\n\n    def __str__(self):\n        return 'lmdb_data'\n\nclass ImageDataUnit(DataUnit):\n    ''' DataUnit load from raw images.\n    :ivar caffe.LayerParameter params: image data layer param defined by Caffe, this is often used when data is limited. Loading from original image will be slower than loading from LMDB\n    '''\n    \n    def __init__(self, params, num_gpu):\n        super(ImageDataUnit, self).__init__(params, num_gpu)\n        if params.include[0].phase == Phase.Value('TRAIN'):\n            self.dp = ImageListDataProvider(params.image_data_param, params.transform_param, num_gpu)\n        else:\n            self.dp = ImageListDataProvider(params.image_data_param, params.transform_param, 1)\n        self.params = params\n        self.crop_size = params.transform_param.crop_size\n        self.generator = None\n\n    def compute_size(self, from_btm, to_top):\n        self.out_shape = [self.params.transform_param.crop_size,\n                          self.params.transform_param.crop_size,\n                          3, 1]\n        to_top[self.top_names[0]] = dict()\n        to_top[self.top_names[0]]['out_shape'] = self.out_shape[:]\n        to_top[self.top_names[0]]['rec_on_ori'] = 1\n        to_top[self.top_names[0]]['stride_on_ori'] = 1 \n        to_top[self.top_names[0]]['start_on_ori'] = 0\n        self.rec_on_ori = 1\n        self.stride_on_ori = 1\n        self.start_on_ori = 0\n\n    def __str__(self):\n        return 'image_data'\n\nclass ImageWindowDataUnit(DataUnit):\n    ''' DataUnit load from image window patches. \n    :ivar caffe.LayerParameter params: image window data layer param defined by Caffe, this is often used when data is limited and object bounding box is given\n\n    '''\n    \n    def __init__(self, params, num_gpu):\n        super(ImageWindowDataUnit, self).__init__(params, num_gpu)\n        if params.include[0].phase == Phase.Value('TRAIN'):\n            self.dp = ImageWindowDataProvider(params.window_data_param, num_gpu)\n        else:\n            self.dp = ImageWindowDataProvider(params.window_data_param, 1)\n        self.params = params\n        self.crop_size = params.window_data_param.crop_size\n        self.generator = None\n    \n    #reset generator\n    def reset_generator(self):\n        if self.params.include[0].phase == Phase.Value('TRAIN'):\n            self.generator = self.dp.get_mb('TRAIN')\n        else:\n            self.generator = self.dp.get_mb('TEST')\n\n    def compute_size(self, from_btm, to_top):\n        self.out_shape = [self.params.window_data_param.crop_size,\n                          self.params.window_data_param.crop_size,\n                          3, 1]\n        to_top[self.top_names[0]] = dict()\n        to_top[self.top_names[0]]['out_shape'] = self.out_shape[:]\n        to_top[self.top_names[0]]['rec_on_ori'] = 1\n        to_top[self.top_names[0]]['stride_on_ori'] = 1 \n        to_top[self.top_names[0]]['start_on_ori'] = 0 \n        self.rec_on_ori = 1\n        self.stride_on_ori = 1\n        self.start_on_ori = 0\n    \n    def __str__(self):\n        return 'window_data'\n\nclass Net:\n    ''' The class for neural network structure\n\n    The Net is basically a graph (DAG), of which each node is a :py:class:`ComputeUnit`.\n\n    :ivar units: all the ``ComputeUnit`` s.\n    :vartype units: list owl.net.ComputeUnit\n    :ivar adjacent: the adjacent list (units are represented by their name)\n    :vartype adjacent: list list str\n    :ivar reverse_adjacent: the reverse adjacent list (units are represented by their name)\n    :vartype reverse_adjacent: list list str\n    :ivar dict name_to_uid: a map from units' name to the unit object\n    :ivar loss_uids: all the units for computing loss\n    :vartype loss_uids: list int\n    :ivar accuracy_uids: all the units for calculating accuracy\n    :vartype accuracy_uids: list int\n    '''\n    def __init__(self):\n        self.units = []\n        self.adjacent = []\n        self.reverse_adjacent = []\n        self.base_lr = 0\n        self.base_weight_decay = 0\n        self.momentum = 0\n        self.name_to_uid = {}\n        self.loss_uids = []\n        self.accuracy_uids = []\n\n    def add_unit(self, unit):\n        ''' Method for adding units into the graph\n\n        :param owl.net.ComputeUnit unit: the unit to add\n        '''\n        uid = len(self.units)\n        self.units.append(unit)\n        self.adjacent.append([])\n        self.reverse_adjacent.append([])\n        if not unit.name in self.name_to_uid:\n            self.name_to_uid[unit.name] = []\n        self.name_to_uid[unit.name].append(uid)\n        return uid\n\n    def connect(self, u1, u2):\n        ''' Method for connecting two units\n\n        :param str u1: name of the bottom unit\n        :param str u2: name of the top unit\n        '''\n        self.adjacent[u1].append(u2)\n        self.reverse_adjacent[u2].append(u1)\n\n    def get_units_by_name(self, name):\n        ''' Get ``ComputeUnit`` object by its name\n\n        :param str name: unit name\n        :return: the compute unit object of that name\n        :rtype: owl.net.ComputeUnit\n        '''\n        return [self.units[uid] for uid in self.name_to_uid[name]]\n\n    def get_loss_units(self):\n        ''' Get all ``ComputeUnit`` object for loss\n\n        :return: all compute unit object for computing loss\n        :rtype: list owl.net.ComputeUnit\n        '''\n        return [self.units[uid] for uid in self.loss_uids]\n\n    def get_accuracy_units(self):\n        ''' Get all ``ComputeUnit`` object for accuracy\n\n        :return: all compute unit object for computing accuracy\n        :rtype: list owl.net.ComputeUnit\n        '''\n        return [self.units[uid] for uid in self.accuracy_uids]\n\n    def get_data_unit(self, phase = 'TRAIN'):\n        ''' Get the ``ComputeUnit`` object for data loading\n\n        :param str phase: phase name of the run\n        :return: the compute unit object for loading data\n        :rtype: owl.net.ComputeUnit\n        '''\n        data_units = self.name_to_uid['data']\n        for du in data_units:\n            if not self._is_excluded(du, phase):\n                return self.units[du]\n\n    def get_weighted_unit_ids(self):\n        ''' Get ids for all :py:class:owl.net.WeightedComputeUnit\n\n        :return: ids of all weighted compute unit\n        :rtype: list int\n        '''\n        weights_id = []\n        for i in xrange(len(self.units)):\n            if isinstance(self.units[i], WeightedComputeUnit):\n                weights_id.append(i)\n        return weights_id\n\n    def _is_excluded(self, unit, phase):\n        p = self.units[unit].params\n        return phase != None and len(p.include) != 0 and p.include[0].phase != Phase.Value(phase)\n\n    def _toporder(self, phase = None):\n        depcount = [len(inunits) for inunits in self.reverse_adjacent]\n        queue = Queue.Queue()\n        # remove dep from excluded units\n        for unit in range(len(depcount)):\n            if self._is_excluded(unit, phase):\n                for l in self.adjacent[unit]:\n                    depcount[l] -= 1\n        # find start units\n        for unit in range(len(depcount)):\n            count = depcount[unit]\n            if count == 0:\n                queue.put(unit)\n        # run\n        while not queue.empty():\n            unit = queue.get()\n            if self._is_excluded(unit, phase):\n                continue\n            yield unit\n            for l in self.adjacent[unit]:\n                depcount[l] -= 1\n                if depcount[l] == 0:\n                    queue.put(l)\n\n    def _reverse_toporder(self, phase = None):\n        depcount = [len(outunits) for outunits in self.adjacent]\n        queue = Queue.Queue()\n        # remove dep from excluded units\n        for unit in range(len(depcount)):\n            if self._is_excluded(unit, phase):\n                for l in self.reverse_adjacent[unit]:\n                    depcount[l] -= 1\n        # find start units\n        for unit in range(len(depcount)):\n            count = depcount[unit]\n            if count == 0:\n                queue.put(unit)\n        # run\n        while not queue.empty():\n            unit = queue.get()\n            if self._is_excluded(unit, phase):\n                continue\n            yield unit\n            for l in self.reverse_adjacent[unit]:\n                depcount[l] -= 1\n                if depcount[l] == 0:\n                    queue.put(l)\n\n    def compute_size(self, phase = 'TRAIN'):\n        ''' Perform the compute_size phase before running\n        '''\n        unit_to_tops = [{} for name in self.units]\n        for u in self._toporder(phase):\n            from_btm = {}\n            for btm in self.reverse_adjacent[u]:\n                from_btm.update(unit_to_tops[btm])\n            self.units[u].compute_size(from_btm, unit_to_tops[u])\n        '''\n        for u in self._toporder(phase):\n            print self.units[u].name\n            print self.units[u].out_shape\n            print self.units[u].rec_on_ori\n            print self.units[u].stride_on_ori\n            print self.units[u].start_on_ori\n        exit(0)\n        '''\n\n    def forward(self, phase = 'TRAIN'):\n        ''' Perform the forward pass\n        '''\n        unit_to_tops = [{} for name in self.units]\n        for u in self._toporder(phase):\n            from_btm = {}\n            for btm in self.reverse_adjacent[u]:\n                from_btm.update(unit_to_tops[btm])\n            self.units[u].forward(from_btm, unit_to_tops[u], phase)\n\n    def forward_check(self):\n        ''' Check forward function, use the same batch of data, remove random\n        '''\n        unit_to_tops = [{} for name in self.units]\n        for u in self._toporder('TEST'):\n            from_btm = {}\n            for btm in self.reverse_adjacent[u]:\n                from_btm.update(unit_to_tops[btm])\n            self.units[u].forward(from_btm, unit_to_tops[u], 'CHECK')\n    \n    def backward(self, phase = 'TRAIN'):\n        ''' Perform the backward pass\n        '''\n        unit_to_btms = [{} for name in self.units]\n        for u in self._reverse_toporder(phase):\n            from_top = {}\n            for top in self.adjacent[u]:\n                for keys in unit_to_btms[top]:\n                    if keys in from_top:\n                        from_top[keys] += unit_to_btms[top][keys]\n                    else:\n                        from_top[keys] = unit_to_btms[top][keys]\n            self.units[u].backward(from_top, unit_to_btms[u], phase)\n\n    def update(self, uid):\n        ''' Update weights of one compute unit of the given uid\n\n        :param int uid: id of the compute unit to update\n        '''\n        self.units[uid].weight_update(self.current_lr,\n                                      self.base_weight_decay,\n                                      self.momentum,\n                                      self.batch_size)\n\n    def weight_update(self):\n        ''' Update weights for all units\n        '''\n        for i in range(len(self.units)):\n            self.update(i)\n\n    def __str__(self):\n        ret = 'digraph G {\\n'\n        for uid in range(len(self.units)):\n            ret += 'n' + str(uid) + ' [label=\"' + self.units[uid].name + '\"]\\n'\n        for uid in range(len(self.units)):\n            for nuid in self.adjacent[uid]:\n                ret += 'n' + str(uid) + ' -> n' + str(nuid) + '\\n'\n        return ret + '}\\n'\n", "meta": {"hexsha": "ebb066627618b3be37fa0ab0be1987897ae22058", "size": 47194, "ext": "py", "lang": "Python", "max_stars_repo_path": "owl/owl/net/net.py", "max_stars_repo_name": "jjzhang166/minerva", "max_stars_repo_head_hexsha": "7d21ed2bdca3de9fbb6e5e2e277fd9956b81a04f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 561, "max_stars_repo_stars_event_min_datetime": "2015-04-05T02:50:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T09:05:16.000Z", "max_issues_repo_path": "owl/owl/net/net.py", "max_issues_repo_name": "jjzhang166/minerva", "max_issues_repo_head_hexsha": "7d21ed2bdca3de9fbb6e5e2e277fd9956b81a04f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 35, "max_issues_repo_issues_event_min_datetime": "2015-04-05T12:46:45.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-14T00:58:17.000Z", "max_forks_repo_path": "owl/owl/net/net.py", "max_forks_repo_name": "jjzhang166/minerva", "max_forks_repo_head_hexsha": "7d21ed2bdca3de9fbb6e5e2e277fd9956b81a04f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 161, "max_forks_repo_forks_event_min_datetime": "2015-04-15T05:47:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T16:01:20.000Z", "avg_line_length": 41.398245614, "max_line_length": 203, "alphanum_fraction": 0.6087214476, "include": true, "reason": "import numpy", "num_tokens": 11580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.31405053215160816, "lm_q1q2_score": 0.16682658639195047}}
{"text": "#!/usr/bin/env python\nfrom astropy.io import ascii\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport util\nimport os\nimport EDGE as edge\nimport starparam\n\n#Set up path to where EDGE/MODULES resides\nmodulespath = os.path.dirname(os.path.realpath(util.__file__)) + '/'\n#Set up path to where EDGE/COMMON resides\ncommonpath = os.path.realpath(modulespath + '../COMMON') + '/'\n#Set up path to where you'd like to put your output files\noutpath = './'\n\n# interactive Av determination? if False, it just uses input Av\ninter = True\n\n# object name for labeling output file\nobj='gmaur'\n\n#spectral type; should be a whole number\nsptin='K5'\n\n# uncomment extinction law to use, default is mcclure\n#law='mathis'\n#law='HD29647'\n#law='CCM89'\nlaw='mcclure'\n\n# uncomment which color table to use\ntable='kh95'\n#table='pm13'\n\n# uncomment which isochrones to use\n#isochrone = 'baraffe'\nisochrone = 'siess'\n\n# uncomment to turn on/off HR diagram display\nHR = True\n\n# uncomment Rv to use\nr=3.1\n#r=5.0\n\n# Av\navin=0.8\n\n# distance in pc\ndistance=160\n\n# If you have an obs fits file created with EDGE, you can\n# input the photometry using it. You might need to change\n# some code below to select the correct photometry with\n# the names you gave them\ninput_obs = True\nif input_obs:\n    c = 2.99793e10\n    source_obs = edge.loadObs(obj,outpath)\n    xu = util.convertJy_to_Mag(source_obs.photometry['UBVRI']['lFl'][0]*\n    source_obs.photometry['UBVRI']['wl'][0]*1e-4/c*1e23,'U')\n    xb = util.convertJy_to_Mag(source_obs.photometry['UBVRI']['lFl'][1]*\n    source_obs.photometry['UBVRI']['wl'][1]*1e-4/c*1e23,'B')\n    xv = util.convertJy_to_Mag(source_obs.photometry['UBVRI']['lFl'][2]*\n    source_obs.photometry['UBVRI']['wl'][2]*1e-4/c*1e23,'V')\n    xr = util.convertJy_to_Mag(source_obs.photometry['UBVRI']['lFl'][3]*\n    source_obs.photometry['UBVRI']['wl'][3]*1e-4/c*1e23,'R')\n    xi = util.convertJy_to_Mag(source_obs.photometry['UBVRI']['lFl'][4]*\n    source_obs.photometry['UBVRI']['wl'][4]*1e-4/c*1e23,'I')\n    xj = util.convertJy_to_Mag(source_obs.photometry['2MASS']['lFl'][0]*\n    source_obs.photometry['2MASS']['wl'][0]*1e-4/c*1e23,'J')\n    xh = util.convertJy_to_Mag(source_obs.photometry['2MASS']['lFl'][1]*\n    source_obs.photometry['2MASS']['wl'][1]*1e-4/c*1e23,'H')\n    xk = util.convertJy_to_Mag(source_obs.photometry['2MASS']['lFl'][2]*\n    source_obs.photometry['2MASS']['wl'][2]*1e-4/c*1e23,'K')\n    xl = np.nan\n    xm = np.nan\n    irac1 = util.convertJy_to_Mag(source_obs.photometry['IRAC']['lFl'][0]*\n    source_obs.photometry['IRAC']['wl'][0]*1e-4/c*1e23,'IRAC3.6')\n    irac2 = util.convertJy_to_Mag(source_obs.photometry['IRAC']['lFl'][1]*\n    source_obs.photometry['IRAC']['wl'][1]*1e-4/c*1e23,'IRAC4.5')\n    irac3 = util.convertJy_to_Mag(source_obs.photometry['IRAC']['lFl'][2]*\n    source_obs.photometry['IRAC']['wl'][2]*1e-4/c*1e23,'IRAC5.8')\n    irac4 = util.convertJy_to_Mag(source_obs.photometry['IRAC']['lFl'][3]*\n    source_obs.photometry['IRAC']['wl'][3]*1e-4/c*1e23,'IRAC8.0')\n    mips1 = util.convertJy_to_Mag(source_obs.photometry['MIPS']['lFl'][0]*\n    source_obs.photometry['MIPS']['wl'][0]*1e-4/c*1e23,'MIPS24')\n\nelse: #If not, input it by hand\n    # input photometry in magnitudes, when missing a value np.nan\n    # need to list at least J-band ('xj') for SpT less than ~G\n    # for earlier type stars need to list at least V-band ('xv')\n    # to get Mdot need U-band ('xu') in addition to above\n    # put 99.00 for magnitudes with no value\n    xu=13.6\n    xb=12.5\n    xv=11.4\n    xr=10.4\n    xi=9.74\n    xj=8.90\n    xh=8.47\n    xk=8.58\n    xl=np.nan\n    xm=np.nan\n    irac1=8.04\n    irac2=7.88\n    irac3=7.68\n    irac4=7.07\n    mips1=2.48\n\n# what to call output file\noutputfile=outpath+'starparam.'+obj+'.'+law+'.rv'+str(r)+'.av'+str(avin)+'.'+table\n\n# FOR TEMPLATE PHOTOSPHERE\n\n# do you want an output template photosphere (useful when fitting for Av)\ncalcphot = True\n\n# what to call output photosphere file\nphotfile=outpath+'photosphere.'+obj+'.'+law+'.rv'+str(r)+'.av'+str(avin)+'.'+table\n\n# wavelengths over which to interpolate template photosphere\n# use 'wlfile_standard.ent' if you're using the photosphere in SED models\nphotfilewl=commonpath+'wavelengths/'+'wlfile_standard.ent'\n\n#\nstarparam.starparam(obj, sptin, avin, distance, law, table, isochrone, HR,\ncalcphot, inter, r,\nxu, xb, xv, xr, xi, xj, xh, xk, xl, xm, irac1, irac2, irac3, irac4, mips1,\noutpath, outputfile, photfile, commonpath, photfilewl)\n", "meta": {"hexsha": "23ebed4c3911908724a8e1ef80bc10d84631340c", "size": 4435, "ext": "py", "lang": "Python", "max_stars_repo_path": "SCRIPTS/jobstarparam.py", "max_stars_repo_name": "zihuaxin/EDGE", "max_stars_repo_head_hexsha": "3b0146950c856e288059b470373d0e4f259c6064", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-06-27T22:09:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-05T19:19:32.000Z", "max_issues_repo_path": "SCRIPTS/jobstarparam.py", "max_issues_repo_name": "zihuaxin/EDGE", "max_issues_repo_head_hexsha": "3b0146950c856e288059b470373d0e4f259c6064", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2017-07-11T17:51:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-19T17:07:06.000Z", "max_forks_repo_path": "SCRIPTS/jobstarparam.py", "max_forks_repo_name": "zihuaxin/EDGE", "max_forks_repo_head_hexsha": "3b0146950c856e288059b470373d0e4f259c6064", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-18T20:25:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-18T20:25:35.000Z", "avg_line_length": 33.5984848485, "max_line_length": 82, "alphanum_fraction": 0.6863585118, "include": true, "reason": "import numpy,from astropy", "num_tokens": 1558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.28140560140262283, "lm_q1q2_score": 0.16677970504056075}}
{"text": "\"\"\"\nAuthor: Hans Pinckaers\nMIT License\n\"\"\"\nimport copy\nimport math\nimport os\nfrom dataclasses import dataclass\nfrom itertools import repeat\nfrom typing import NamedTuple, Union, List\n\nimport numpy as np\nimport torch\nimport torch.autograd\nimport torch.backends\nimport torch.nn.functional\n\nfrom torch._six import container_abcs\nfrom torch.nn.modules.conv import _ConvNd\nfrom torch.nn.modules.utils import _pair\nfrom torch.utils.cpp_extension import load\n\nfrom tqdm import tqdm\n\n\n# from torch.nn.grad import _grad_input_padding\n\nif '1.6' in torch.__version__: # type:ignore\n    def forward_amp_decorator(func): \n        return torch.cuda.amp.custom_fwd(func)  # type:ignore\n    def backward_amp_decorator(func): \n        return torch.cuda.amp.custom_bwd(func)  # type:ignore\n    from torch.cuda.amp import autocast\nelse:\n    def forward_amp_decorator(func): \n        return func\n    def backward_amp_decorator(func):\n        return func\n\n# Load and compile cpp code to call cudnn conv2d backward function\ndirname = os.path.dirname(__file__)\nfilename = os.path.join(dirname, \"cpp_functions.cpp\")\ncpp_functions = load(name=\"cpp_functions\", sources=[filename], verbose=False)\n\n# inspired by torch/nn/modules/utils.py\ndef _ntuple(n):\n    def parse(x, default=0):\n        if isinstance(x, container_abcs.Iterable):\n            if len(x) == n: \n                return x\n            elif len(x) == n-1: \n                return tuple([default, *x])\n            else: \n                return tuple(repeat(x[0], n))\n        return tuple(repeat(x, n))\n    return parse\n\n_triple = _ntuple(3)\n\n# Utility named tuples, makes code more readable\nclass Sides(NamedTuple):\n    left: int\n    top: int\n    right: int\n    bottom: int\n\n@dataclass\nclass Box:\n    y: int\n    height: int\n    x: int\n    width: int\n    sides: Union[Sides, None]\n\nclass IOShape(NamedTuple):\n    batch: int\n    channels: int\n    height: int\n    width: int\n\n@dataclass\nclass Lost:\n    top: int\n    left: int\n    bottom: int\n    right: int\n\n    def __str__(self):\n        return 'Lost(top:%2.1f, left:%2.1f, bottom:%2.1f, right:%2.1f)' \\\n            % (self.top, self.left, self.bottom, self.right)\n\nclass StreamingConv2dF(torch.autograd.Function):\n    @staticmethod\n    @forward_amp_decorator\n    def forward(ctx, inpt, weight, bias, stride, padding, dilation, groups, grad_lost, seen_indices, output_stride, input_loc):\n        ctx.save_for_backward(inpt, weight, bias)\n        ctx.stride = stride\n        ctx.padding = padding\n        ctx.dilation = dilation\n        ctx.groups = groups\n        ctx.grad_lost = grad_lost\n        ctx.seen_indices = seen_indices\n        ctx.output_stride = output_stride\n        ctx.input_loc = input_loc\n        return torch.nn.functional.conv2d(inpt, weight, bias, stride, padding, dilation, groups)\n\n    @staticmethod\n    @backward_amp_decorator\n    def backward(ctx, grad_output):\n        inpt, weight, bias = ctx.saved_variables\n        grad = grad_weight = grad_bias = None\n\n        stride = ctx.stride\n        padding = ctx.padding \n        dilation = ctx.dilation \n        groups = ctx.groups \n        sides = ctx.input_loc.sides  # Type: Sides\n        seen_indices = ctx.seen_indices\n        grad_lost = ctx.grad_lost  # Type: Lost\n        output_stride = ctx.output_stride\n        grad_bias = None\n        kernel_size = weight.shape[-1]\n\n        if ctx.needs_input_grad[0]:\n            # TODO: performance improvements possible by only backpropping valid input\n            # grad_input_padding = _grad_input_padding(grad_output, inpt.shape, stride, padding, (weight.shape[2], weight.shape[3]))  \n            # TODO: use this!?\n            grad_in = cpp_functions.backward_input(inpt.shape, grad_output, weight.to(inpt.dtype), padding, \n                                                   stride, dilation, groups, \n                                                   torch.backends.cudnn.benchmark, torch.backends.cudnn.deterministic)\n        else:\n            grad_in = None\n\n        grad = grad_output\n\n        lost_top = grad_lost.top if not sides.top else 0\n        lost_bottom = grad_lost.bottom if not sides.bottom else 0\n        lost_left = grad_lost.left if not sides.left else 0\n        lost_right = grad_lost.right if not sides.right else 0\n\n        valid_grad = grad[:, :, lost_top:grad.shape[H_DIM] - lost_bottom,\n                          lost_left:grad.shape[W_DIM] - lost_right]\n\n        stride, kernel_size, padding = _triple(stride), _triple(kernel_size), _triple(padding)\n\n        output_stride = output_stride * torch.tensor(stride)\n        input_loc = ctx.input_loc\n\n        # Move the location according to how many pixels have been trimmed\n        # this will be the location of the valid gradient of this layer in relation\n        # to the actual gradient in a normal backpass\n        data_loc_y = int(input_loc.y // output_stride[1]) + lost_top\n        data_loc_x = int(input_loc.x // output_stride[2]) + lost_left\n\n        data_loc = Box(data_loc_y, 0,\n                       data_loc_x, 0,\n                       input_loc.sides)\n\n        # Calculate which part of the gradient is 'new'\n        old_value_indices = seen_indices\n        new_output_box, updated_total_indices = StreamingCNN._new_value_indices(valid_grad.shape,\n                                                                                data_loc,\n                                                                                old_value_indices)\n\n        # Update inplace\n        seen_indices.y = updated_total_indices.y\n        seen_indices.height = updated_total_indices.height\n        seen_indices.x = updated_total_indices.x\n        seen_indices.width = updated_total_indices.width\n        seen_indices.sides = updated_total_indices.sides\n\n        if new_output_box.height > 0 and new_output_box.width > 0:\n            relevant_grad = valid_grad[:, :,\n                                       new_output_box.y:new_output_box.y + new_output_box.height,\n                                       new_output_box.x:new_output_box.x + new_output_box.width]\n\n            input_y = (new_output_box.y + lost_top) * stride[1]\n            input_x = (new_output_box.x + lost_left) * stride[2]\n\n            # Accounting for padding:\n            # the kernel locations are relative to the padded input, inpt[0] is not padded\n            # this means that the corresponding input of the grad_loc is module.padding shifted to the left\n            # we account for this:\n            input_y -= padding[1]\n            input_x -= padding[2]\n            input_x = max(0, input_x)\n            input_y = max(0, input_y)\n\n            relevant_input_height = relevant_grad.shape[H_DIM] * stride[1] + (kernel_size[1] - 1)\n            relevant_input_width = relevant_grad.shape[W_DIM] * stride[2] + (kernel_size[2] - 1)\n\n            relevant_input = inpt[:, :,\n                                  input_y:input_y + relevant_input_height,\n                                  input_x:input_x + relevant_input_width]\n\n            # If layer has padding we need to pad based on if the current tile\n            # is at the sides of the input.\n            if (padding[0] > 0 or padding[1] > 0 or padding[2] > 0) and \\\n                    (sides.top or sides.left or sides.right or sides.bottom):\n                # The size of the tile should remain equal.\n                crop_bottom = padding[1] if sides.top else 0\n                crop_right = padding[2] if sides.left else 0\n                relevant_input = inpt[:, :,\n                                      input_y:input_y + relevant_input_height - crop_bottom,\n                                      input_x:input_x + relevant_input_width - crop_right]\n\n                relevant_input = torch.nn.functional.pad(relevant_input, [padding[2] if sides.left else 0,\n                                                                          padding[2] if sides.right else 0,\n                                                                          padding[1] if sides.top else 0,\n                                                                          padding[1] if sides.bottom else 0])\n\n            # Calculate the kernel gradients with the new unseen gradient values\n            relevant_grad = relevant_grad.contiguous()\n\n            grad_weight = cpp_functions.backward(weight.shape,\n                                                 relevant_grad.to(weight.dtype),\n                                                 relevant_input.to(weight.dtype),\n                                                 (0, 0),  # padding\n                                                 stride[1:3], dilation, groups,\n                                                 torch.backends.cudnn.benchmark,  # benchmark\n                                                 torch.backends.cudnn.deterministic)  # deterministic\n\n            if bias is not None:\n                grad_bias = relevant_grad[0].sum((1, 2))\n\n            del relevant_input\n            del relevant_grad\n        else:\n            # if self.verbose and not hasattr(self, '_inefficient_tile_shape_warning'):\n            # print(\"Warning: no new gradient values found. Tile size could be too small.\")\n            # self._inefficient_tile_shape_warning = True\n            grad_weight = torch.zeros_like(weight)\n            if bias is None: grad_bias = None\n            else: grad_bias = torch.zeros_like(bias)\n\n        if bias is not None:\n            return grad_in, grad_weight, grad_bias, None, None, None, None, None, None, None, None, \n        else:\n            return grad_in, grad_weight, None, None, None, None, None, None, None, None, None, \n\nconv2d = StreamingConv2dF.apply  # type:ignore\n\nclass StreamingConv2d(_ConvNd):\n    def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros'):\n        kernel_size = _pair(kernel_size)\n        stride = _pair(stride)\n        padding = _pair(padding)\n        dilation = _pair(dilation)\n        super(StreamingConv2d, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilation, False, _pair(0), groups, bias, padding_mode)\n        self.grad_lost = Lost(0, 0, 0, 0)\n        self.tile_output_box = Box(0, 0, 0, 0, None)\n        self.reset()\n\n    def reset(self):\n        self.seen_indices = Box(0, 0, 0, 0, None)\n        self.input_loc = Box(0, 0, 0, 0, None)\n\n    def forward(self, input):       \n        return conv2d(input, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups,\n                      self.grad_lost, self.seen_indices, self.output_stride, self.input_loc)\n\nB_DIM = 0\nC_DIM = 1\nH_DIM = 2\nW_DIM = 3\n\nclass StreamingCNN(object):\n    '''Initialize Streaming CNN helper class. After initialization use the\n    forward() and backward() function of this class to stream.\n    Pseudocode example:\n\n    ```python\n    sCNN = StreamingCNN(stream_layers, tile_shape=(1, 3, 600, 600))\n    str_output = sCNN.forward(image)\n    final_output = final_layers(str_output)\n    loss = criterion(final_output, labels)\n    loss.backward()\n    sCNN.backward(image, str_output.grad)\n    ```\n\n    Hooks are used to perform streaming, to use the stream_layers without\n    streaming you can disable StreamingCNN with the disable() function.\n    Subsequently, enable() enables it again. Streaming gets enabled by default\n    after initialization.\n    '''\n    def __init__(self, stream_module, tile_shape, verbose=False, deterministic=False,\n                 saliency=False, gather_gradients=False, replace_non_linearity=True, \n                 eps=1e-5, copy_to_gpu=True, dtype=None, statistics_on_cpu=False,\n                 normalize_on_gpu=False, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225],\n                 state_dict=None):\n        '''\n        Parameters:\n            stream_module (torch.nn.Module): module containing the to be streamed layers\n            tile_shape (tuple, NCHW): size of the to be streamed tiles\n            verbose (bool): will log various debugging relevant information (default is False)\n            deterministic (bool): whether to use the deterministic algorithms for cudnn\n            saliency (bool): will gather the gradients of the input image (saliency map)\n            gather_gradients (bool): will gather the gradients of the feature maps\n            eps (float): epsilon error to compare floating values\n        '''\n        global H_DIM, W_DIM\n        self.stream_module = stream_module\n        self.verbose = verbose\n        self.deterministic = deterministic\n        self.eps = eps\n        self.device = next(stream_module.parameters()).device\n        self.dtype = next(stream_module.parameters()).dtype\n        if dtype is not None: self.dtype = dtype\n        self.tile_shape = tile_shape\n        self.gather_input_gradient = saliency\n        self.gather_gradient = gather_gradients\n        self.replace_non_linearity = replace_non_linearity\n        self.copy_to_gpu = copy_to_gpu\n        self.statistics_on_cpu = statistics_on_cpu\n\n        self.mean = torch.tensor(mean).cuda()[:, None, None]\n        self.std = torch.tensor(std).cuda()[:, None, None]\n        self.should_normalize = normalize_on_gpu\n\n        self._tile_output_shape = None\n        self._module_stats = {}\n        self._backward_seen_indices = {}\n        self._saved_tensors = {}\n        self._current_tile_input_loc = None\n        self._hooks = []\n\n        if state_dict is None:\n            self._configure()\n        else:\n            self.load_state_dict(state_dict)\n\n    def _configure(self):\n        if self.replace_non_linearity: self.convert_modules_model(self.stream_module)\n        self.convert_modules_model(self.stream_module, from_mod=torch.nn.BatchNorm2d, to_mod=torch.nn.Sequential)\n\n        # Save current model and cudnn flags, since we need to change them and restore later\n        state_dict = self._save_parameters()\n        old_deterministic_flag, old_benchmark_flag = self._set_cudnn_flags_to_determistic()\n        self._reset_parameters_to_constant()\n\n        # Add hooks to each layer to gather statistics\n        self._add_hooks_for_statistics()\n\n        # We need to temporary store statistics per layer to keep track of the\n        # total output stride at each layer\n        self._stats_per_grad_fn = {}\n\n        # TODO; temp hack for tile sizes too big on gpu, \n        # we need float32 precision\n        if self.statistics_on_cpu:\n            self.stream_module = self.stream_module.cpu()\n            self.device = torch.device('cpu')  # type:ignore\n\n        # Create all-ones tile\n        tile = torch.ones(self.tile_shape, dtype=self.dtype, requires_grad=True, device=self.device)\n\n        self._gather_forward_statistics(tile)\n        if self.verbose: print('')\n        self._gather_backward_statistics(tile)\n\n        # TODO; temp hack for tile sizes too big on gpu, \n        if self.statistics_on_cpu:\n            self.stream_module = self.stream_module.cuda()\n            self.device = torch.device('cuda')  # type:ignore\n\n        # Remove all hooks and add hooks for correcting gradients\n        # during streaming\n        self._remove_hooks()\n        self._add_hooks_for_streaming()\n        self._restore_parameters(state_dict)\n        self._convert_modules_for_streaming(self.stream_module)\n        if self.replace_non_linearity: self.convert_modules_model(self.stream_module, back=True)\n\n        # Remove temporary data\n        self._saved_tensors = {}\n        del self._stats_per_grad_fn\n\n        # Zero the gradients\n        for param in self.stream_module.parameters():\n            if param.grad is not None: param.grad.data.zero_()\n\n        self._set_cudnn_flags(old_deterministic_flag, old_benchmark_flag)\n        del state_dict\n\n\n    def _gather_backward_statistics(self, tile):\n        # Forward pass with grads enabled\n        torch.set_grad_enabled(True)\n        output = self.stream_module(tile)\n\n        # Gather backward statistics\n        self._tile_output_shape = output.shape\n\n        gradient = torch.zeros(*output.shape, dtype=self.dtype, device=self.device)\n        gradient[:, :,\n                 self.tile_output_lost.top:output.shape[H_DIM] - self.tile_output_lost.bottom,\n                 self.tile_output_lost.left:output.shape[W_DIM] - self.tile_output_lost.right] = 1\n        output.backward(gradient=gradient)\n\n        # Calculate the output stride of the whole stream_module\n        p_stats = self._prev_stats(output)\n        if p_stats: self.output_stride = p_stats['output_stride'] * torch.tensor(p_stats['stride'])\n        else: self.output_stride = torch.tensor([1, 1, 1])\n\n        self.tile_gradient_lost = self._non_max_border_amount(tile.grad)\n\n        if self.verbose: \n            print('\\n', 'Input gradient lost', self.tile_gradient_lost)\n\n    def _gather_forward_statistics(self, tile):\n        torch.set_grad_enabled(False)\n        output = self.stream_module(tile)\n        self.tile_output_lost = self._non_max_border_amount(output)\n        if self.verbose: print('\\n', 'Output lost', self.tile_output_lost)\n\n    def convert_modules_model(self, module, from_mod=torch.nn.ReLU6, to_mod=torch.nn.ReLU, back=False):\n        mod = module\n        if not back and isinstance(module, from_mod):\n            mod = to_mod()\n            # mod.previous_mod = module\n        if back and isinstance(module, to_mod):\n            mod = module.previous_mod\n        for name, child in module.named_children():\n            mod.add_module(name, self.convert_modules_model(child, from_mod, to_mod))\n        del module\n        return mod\n\n    def _convert_modules_for_streaming(self, module):\n        mod = module\n        if isinstance(module, torch.nn.Conv2d):\n            if module in self._module_stats:\n                mod = StreamingConv2d(module.in_channels, module.out_channels, module.kernel_size, module.stride, module.padding, module.dilation, module.groups, module.bias is not None)\n                mod = mod.to(module.weight.device)\n                mod = mod.to(module.weight.dtype)\n\n                mod.weight.requires_grad = module.weight.requires_grad\n                if module.bias is not None:\n                    mod.bias.requires_grad = module.bias.requires_grad\n\n                mod.load_state_dict(module.state_dict())  # copy params\n                mod.grad_lost = self._module_stats[module]['grad_lost']\n                mod.output_stride = self._module_stats[module]['output_stride']\n                self._module_stats[mod] = self._module_stats[module]\n                del self._module_stats[module]\n        for name, child in module.named_children():\n            mod.add_module(name, self._convert_modules_for_streaming(child))\n        del module\n        return mod\n\n    def _reset_converted_modules(self, module):\n        mod = module\n        if isinstance(module, StreamingConv2d):\n            mod = torch.nn.Conv2d(module.in_channels, module.out_channels, module.kernel_size, module.stride, module.padding, module.dilation, module.groups, module.bias is not None)\n            mod = mod.to(module.weight.device)\n            mod = mod.to(module.weight.dtype)\n\n            mod.weight.requires_grad = module.weight.requires_grad\n            if module.bias is not None:\n                mod.bias.requires_grad = module.bias.requires_grad\n\n            mod.load_state_dict(module.state_dict())  # copy params\n            self._module_stats[mod] = self._module_stats[module]\n            del self._module_stats[module]\n        for name, child in module.named_children():\n            mod.add_module(name, self._reset_converted_modules(child))\n        del module\n        return mod\n\n    def _reset_parameters_to_constant(self):\n        for mod in self.stream_module.modules():\n            if isinstance(mod, (torch.nn.Conv2d)):\n                # to counter loating precision errors, we assign 1 to the weights and\n                # normalize the output after the conv.\n                torch.nn.init.constant_(mod.weight, 1)\n                if mod.bias is not None:\n                    torch.nn.init.constant_(mod.bias, 0)\n\n        for m in self.stream_module.modules():\n            if isinstance(m, torch.nn.BatchNorm2d):\n                m.weight.data.fill_(1)\n                m.bias.data.zero_()\n                m.eval()\n\n    def _set_cudnn_flags(self, deterministic_flag, benchmark_flag):\n        torch.backends.cudnn.deterministic = deterministic_flag\n        torch.backends.cudnn.benchmark = benchmark_flag\n\n    def _set_cudnn_flags_to_determistic(self):\n        deterministic_flag = torch.backends.cudnn.deterministic\n        benchmark_flag = torch.backends.cudnn.benchmark\n        self._set_cudnn_flags(True, False)\n        return deterministic_flag, benchmark_flag\n\n    def _save_parameters(self):\n        state_dict = self.stream_module.state_dict()\n        state_dict = copy.deepcopy(state_dict)\n        return state_dict\n\n    def _restore_parameters(self, state_dict):\n        self.stream_module.load_state_dict(state_dict)\n\n    def _non_max_border_amount(self, tensor):\n        # Sum over the channels, useful for networks that treat certain channels\n        # different (e.g., DenseNet)\n        if tensor.dim() > 3: tensor = torch.sum(tensor, dim=1)[0]\n        tensor = tensor / tensor.max()  # normalize\n        tensor = (tensor > tensor.max() * (1-self.eps))\n        non_zero = tensor.nonzero()\n        top, left = non_zero.min(dim=0)[0]\n        # for bottom and right we need to substract -1: correct index 3 is actually the 4th pixel\n        bottom, right = torch.tensor([*tensor.size()], dtype=torch.long, device=self.device) - non_zero.max(dim=0)[0] - 1\n        return Lost(int(top), int(left), int(bottom), int(right))\n\n    def forward(self, image, result_on_cpu=False):\n        \"\"\"Perform forward pass with streaming.\n\n        Parameters:\n            image (torch.Tensor): CHW the image to stream\n        \"\"\"\n        # The input image is likely quite small in terms of channels, for\n        # performance reasons it is beneficial to copy to the GPU as a whole\n        # instead of tile-by-tile.\n        image = image\n        if self.copy_to_gpu:\n            image = image.to(self.device, non_blocking=True)\n\n        tile_width, tile_height = self.tile_shape[W_DIM], self.tile_shape[H_DIM]\n\n        # Size of valid output of a tile\n        valid_output_height = (self._tile_output_shape[H_DIM] - self.tile_output_lost.top - self.tile_output_lost.bottom)\n        valid_output_width = (self._tile_output_shape[W_DIM] - self.tile_output_lost.left - self.tile_output_lost.right)\n\n        # We will keep track which part of the output of the whole image we\n        # already filled with valid values from tile output.\n        already_filled = Box(0, 0, 0, 0, None)\n\n        # Calculate size of output that we would get by inferencing the\n        # whole image.\n        output_height = (image.shape[H_DIM] - self.tile_shape[H_DIM]) // self.output_stride[1] + self._tile_output_shape[H_DIM]\n        output_width = (image.shape[W_DIM] - self.tile_shape[W_DIM]) // self.output_stride[2] + self._tile_output_shape[W_DIM]\n\n        if result_on_cpu:\n            device = torch.device('cpu')\n        else:\n            device = self.device\n        output = torch.empty((image.shape[0], self._tile_output_shape[1], output_height, output_width), dtype=self.dtype, device=device).fill_(999)\n\n        n_rows = math.ceil(float(output_height) / float(valid_output_height))\n        n_cols = math.ceil(float(output_width) / float(valid_output_width))\n        \n        if image.shape[W_DIM] <= tile_width: n_cols = 1\n        if image.shape[H_DIM] <= tile_height: n_rows = 1\n\n        if self.gather_input_gradient:\n            self.saliency_map = torch.zeros(image.shape, dtype=self.dtype, device=self.device)\n\n        if self.verbose: print('Number of tiles in forward:', n_rows * n_cols)\n        if self.verbose: iterator = tqdm(range(n_rows))\n        else: iterator = range(n_rows)\n\n        with torch.no_grad():\n            for row in iterator:\n                for col in range(n_cols):\n                    # Coordinates of the output w.r.t. the output of full image\n                    output_y = row * valid_output_height\n                    output_x = col * valid_output_width\n\n                    # Check if we are at borders, since we can not create\n                    # overlap here and should not crop values.\n                    sides_top = True if row == 0 else False\n                    sides_left = True if col == 0 else False\n\n                    sides_bottom = True if output_y * self.output_stride[1] + self.tile_shape[H_DIM] >= image.shape[H_DIM] else False\n                    sides_right = True if output_x * self.output_stride[2] + self.tile_shape[W_DIM] >= image.shape[W_DIM] else False\n                    sides = Sides(sides_left, sides_top, sides_right, sides_bottom)\n\n                    # These values are used to crop invalid output values\n                    lost = self._get_tile_lost_for_sides(sides)\n\n                    # Since we need to stay at multiples of output stride we\n                    # need to keep that into account when we are at the bottom\n                    # and right side of the output.\n                    if sides_bottom: output_y = (image.shape[H_DIM] - self.tile_shape[H_DIM]) // self.output_stride[1]\n                    if sides_right:  output_x = (image.shape[W_DIM] - self.tile_shape[W_DIM]) // self.output_stride[2]\n\n                    output_y = output_y if not sides.top else 0\n                    output_x = output_x if not sides.left else 0\n                    output_loc = Box(output_y + lost.top, -1, output_x + lost.left, -1, sides)\n\n                    # Coordinates of the input w.r.t. the output of full image\n                    tile_y = output_y * self.output_stride[1]\n                    tile_x = output_x * self.output_stride[2]\n\n                    # Extract tile and perform forward pass\n                    tile = image[:, :,\n                                 tile_y:tile_y + tile_height,\n                                 tile_x:tile_x + tile_width]\n\n                    # normalize on gpu for speed in dataloader\n                    # does this reduce speed significantly?\n                    if not self.copy_to_gpu:\n                        tile = tile.to(self.device, non_blocking=True)\n\n                    if self.should_normalize: tile = self._normalize_on_gpu(tile)\n                    tile_output = self.stream_module(tile)\n\n                    trimmed_output = tile_output[:, :,\n                                                 lost.top:tile_output.shape[H_DIM] - lost.bottom,\n                                                 lost.left:tile_output.shape[W_DIM] - lost.right]\n\n                    new_output_box, updated_total_indices = self._new_value_indices(trimmed_output.shape, output_loc, already_filled)\n                    already_filled = updated_total_indices\n\n                    relevant_output = trimmed_output[:, :,\n                                                     new_output_box.y:updated_total_indices.y + new_output_box.height,\n                                                     new_output_box.x:new_output_box.x + new_output_box.width]\n\n                    output[:, :, int(updated_total_indices.y):int(updated_total_indices.height), int(updated_total_indices.x - new_output_box.width):int(updated_total_indices.x)] = relevant_output\n\n                    del tile\n\n            assert sides_bottom and sides_right, \"It seems like we could not reconstruct all output\"  #type:ignore\n\n        # mem management\n        del relevant_output  # type:ignore\n        del image\n        self._saved_tensors = {}\n\n        return output\n\n    def backward(self, image, grad):\n        \"\"\"Perform backward pass with streaming.\n\n        Parameters:\n            image (torch.Tensor): the image (expects NCHW) that was used in the forward pass\n            grad (torch.Tensor): this should be the gradient of the output of\n                the stream_layers.\n        \"\"\"\n        # The input image is likely quite small in terms of channels, for\n        # performance reasons it is beneficial to copy to the GPU as a whole\n        # instead of tile-by-tile.\n        image = image\n        if self.copy_to_gpu:\n            image = image.to(self.device, non_blocking=True)\n        grad = grad\n\n        height = image.shape[H_DIM]\n        width = image.shape[W_DIM]\n\n        tile_height = self.tile_shape[H_DIM]\n        tile_width = self.tile_shape[W_DIM]\n        grad_lost = self.tile_gradient_lost\n\n        output_height = self._tile_output_shape[H_DIM]\n        output_width = self._tile_output_shape[W_DIM]\n\n        valid_grad_height = (tile_height - grad_lost.top - grad_lost.bottom) // self.output_stride[1]\n        valid_grad_height *= self.output_stride[1]\n        valid_grad_width = (tile_width - grad_lost.left - grad_lost.right) // self.output_stride[2]\n        valid_grad_width *= self.output_stride[2]\n\n        n_rows = math.ceil(float(height - grad_lost.top - grad_lost.bottom) / float(valid_grad_height))\n        n_cols = math.ceil(float(width - grad_lost.left - grad_lost.right) / float(valid_grad_width))\n\n        if self.verbose:\n            ideal_tile_size = height / float(n_rows) + grad_lost.top + grad_lost.bottom        \n            next_ideal_tile_size = height / float(n_rows - 1) + grad_lost.top + grad_lost.bottom        \n            print(ideal_tile_size, n_rows*n_cols, next_ideal_tile_size) \n\n        if image.shape[W_DIM] <= tile_width: n_cols = 1\n        if image.shape[H_DIM] <= tile_height: n_rows = 1\n\n        if self.gather_gradient:\n            self.gradients = {}\n        self._inputs = {}\n        self._backward_seen_indices = {}\n\n        if self.verbose: print('Number of tiles in backprop:', n_rows * n_cols)\n        if self.verbose: iterator = tqdm(range(n_rows))\n        else: iterator = range(n_rows)\n\n        for row in iterator:\n            for col in range(n_cols):\n                # Since we determine output (gradient) coordinates based on input\n                # coordinates. We need to divide by output stride.\n                output_y = row * valid_grad_height // self.output_stride[1]\n                output_x = col * valid_grad_width // self.output_stride[2]\n\n                sides_top = True if row == 0 else False\n                sides_left = True if col == 0 else False\n\n                sides_bottom = True if output_y + output_height >= grad.shape[H_DIM] else False\n                sides_right = True if output_x + output_width >= grad.shape[W_DIM] else False\n                sides = Sides(sides_left, sides_top, sides_right, sides_bottom)\n\n                # We are doing a forward pass\n                lost = self._get_tile_lost_for_sides(sides)\n\n                # If the tile is at the bottom or right side of the input image\n                # than we need to shift back so that the tile fits (does not go\n                # over the border)\n                if sides_bottom: output_y = max(grad.shape[H_DIM] - output_height, 0)\n                if sides_right: output_x = max(grad.shape[W_DIM] - output_width, 0)\n\n                input_y = output_y * self.output_stride[1]\n                input_x = output_x * self.output_stride[2]\n\n                input_loc = Box(input_y, tile_height, input_x, tile_width, sides)\n\n                tile = image[:, :,\n                             input_y:input_y + tile_height,\n                             input_x:input_x + tile_width]\n\n                gradient = grad[:, :,\n                                output_y:output_y + output_height,\n                                output_x:output_x + output_width]\n\n                self._saved_tensors = {}\n\n                # Trim output and gradient\n                trimmed_grad = gradient[:, :,\n                                        lost.top:gradient.shape[H_DIM] - lost.bottom,\n                                        lost.left:gradient.shape[W_DIM] - lost.right]\n\n                if not self.copy_to_gpu:\n                    tile = tile.to(self.device, non_blocking=True)\n\n                for mod in self.stream_module.modules():\n                    if isinstance(mod, StreamingConv2d):\n                        mod.input_loc = input_loc\n\n                # normalize on gpu for speed in dataloader\n                # does this reduce speed significantly?\n                if self.should_normalize: tile = self._normalize_on_gpu(tile)\n\n                if self.dtype == torch.float16:\n                    with autocast(): \n                        tile_output = self.stream_module(tile)\n                else: \n                    tile_output = self.stream_module(tile)\n\n                del tile # memory management\n\n                trimmed_output = tile_output[:, :,\n                         lost.top:tile_output.shape[H_DIM] - lost.bottom,\n                         lost.left:tile_output.shape[W_DIM] - lost.right]\n\n                # Do backward pass, fix gradient in hooks\n                trimmed_output = trimmed_output.to(self.device, non_blocking=True)\n\n                # Sometimes when training with variable input shapes,\n                # the gradient size is a bit too big\n                if trimmed_grad.shape[H_DIM] != trimmed_output.shape[H_DIM] or \\\n                   trimmed_grad.shape[W_DIM] != trimmed_output.shape[W_DIM]:\n                    assert image.shape[H_DIM] < self.tile_shape[H_DIM] or \\\n                        image.shape[W_DIM] < self.tile_shape[W_DIM]\n                    trimmed_grad = trimmed_grad[:, :,\n                                                0:trimmed_output.shape[H_DIM],\n                                                0:trimmed_output.shape[W_DIM]]\n\n                trimmed_output.backward(trimmed_grad)\n\n                # Memory management\n                del tile_output\n                del trimmed_grad\n                del trimmed_output\n\n        # Memory management\n        self._saved_tensors = {}\n        self._current_tile_input_loc = None\n\n        for mod in self.stream_module.modules():\n            if isinstance(mod, StreamingConv2d):\n                mod.input_loc = None\n                mod.reset()\n\n        assert sides_right and sides_bottom, \"It seems like we could not reconstruct all output\"  # type:ignore\n\n    def _get_tile_lost_for_sides(self, sides):\n        lost_top = self.tile_output_lost.top if not sides.top else 0\n        lost_bottom = self.tile_output_lost.bottom if not sides.bottom else 0\n        lost_left = self.tile_output_lost.left if not sides.left else 0\n        lost_right = self.tile_output_lost.right if not sides.right else 0\n        lost = Lost(lost_top, lost_left, lost_bottom, lost_right)\n        return lost\n\n    def _normalize_on_gpu(self, tile):\n        tile_norm = tile.to(self.dtype)\n        del tile\n        tile_norm.div_(255)\n        tile_norm.sub_(self.mean)\n        tile_norm.div_(self.std)\n        tile = tile_norm\n        return tile\n\n    def disable(self):\n        \"\"\"Disable the streaming hooks\"\"\"\n        self._remove_hooks()\n        self._reset_converted_modules(self.stream_module)\n\n    def enable(self):\n        \"\"\"Enable the streaming hooks\"\"\"\n        self._remove_hooks()\n        self._add_hooks_for_streaming()\n        self._convert_modules_for_streaming(self.stream_module)\n\n    def _add_hooks_for_statistics(self):\n        def forw_lambda(module, inpt, outpt):\n            self._forward_gather_statistics_hook(module, inpt, outpt)\n\n        def back_lambda(module, grad_in, grad_out):\n            return self._backward_gather_statistics_hook(module, grad_in, grad_out)\n\n        self._add_hooks(forward_hook=forw_lambda, backward_hook=back_lambda)\n\n    def _add_hooks_for_streaming(self):\n        if self.gather_input_gradient:\n            def back_lambda(module, grad_in, grad_out):\n                return self._backward_saliency_hook(module, grad_in, grad_out)\n\n            for mod in self.stream_module.modules():\n                if isinstance(mod, (torch.nn.Conv2d)):\n                    if mod.in_channels == 3:\n                        back_handle = mod.register_backward_hook(back_lambda)\n                        self._hooks.append(back_handle)\n\n    def _add_hooks(self, forward_hook, backward_hook,\n                   forward_modules=(torch.nn.Conv2d, torch.nn.MaxPool2d, torch.nn.AvgPool2d),\n                   back_modules=(torch.nn.Conv2d, torch.nn.MaxPool2d)):\n        for mod in self.stream_module.modules():\n            if isinstance(mod, forward_modules):\n                forw_handle = mod.register_forward_hook(forward_hook)\n                self._hooks.append(forw_handle)\n                if back_modules and isinstance(mod, back_modules):\n                    back_handle = mod.register_backward_hook(backward_hook)\n                    self._hooks.append(back_handle)\n\n    def _remove_hooks(self):\n        for hook in self._hooks:\n            hook.remove()\n\n    def _forward_gather_statistics_hook(self, module, inpt, output):\n        stride, kernel_size, _ = _triple(module.stride), _triple(module.kernel_size), _triple(module.padding)\n\n        if not torch.is_grad_enabled():  # type:ignore\n            # Convert strided convolutions/pooling to average pool\n            if isinstance(module, (torch.nn.MaxPool2d)) or \\\n                    (stride[0] > 1 and stride[0] > kernel_size[0]) or \\\n                    (stride[1] > 1 and stride[1] > kernel_size[1]) or \\\n                    (stride[2] > 1 and stride[2] > kernel_size[2]):\n                # Pytorch documentation is explicitely against changing output in a forward hook\n                # However, since we do not really need the graph or gradients to be correct\n                # it shouldn't harm.\n                if module.padding != 0:\n                    padding = module.padding\n                    if not isinstance(module.padding, tuple):\n                        padding = [module.padding, module.padding]\n                    padded_input = torch.nn.functional.pad(inpt[0], [padding[1], padding[1], padding[0], padding[0]])\n                else:\n                    padded_input = inpt[0]\n\n                new_output = torch.nn.functional.avg_pool2d(padded_input, kernel_size[1:], stride[1:])\n                new_output = torch.sum(new_output, dim=1)[0]\n                new_output = (new_output > (1-self.eps) * new_output.max())\n                new_output = new_output.expand_as(output[0])\n                output[0] = new_output.type(self.dtype)\n\n            # Sum all dimensions (useful for DenseNet like networks)\n            lost = self._non_max_border_amount(output)\n\n            # Make output between 0-1 again, so the values do not explode\n            output.fill_(0)\n            output[:,:,lost.top:output[0, 0].shape[0] - lost.bottom,\n                     lost.left:output[0, 0].shape[1] - lost.right] = 1\n\n            module_stats = {'lost': lost, 'stride': stride, 'module': module}\n            if self.verbose: print(module, \"\\n\", module_stats['lost'])\n\n            self._saved_tensors[module] = inpt\n            self._module_stats[module] = module_stats\n        else:\n            module_stats = self._module_stats[module]\n\n            p_stats = self._prev_stats(output)\n            if p_stats: output_stride = p_stats['output_stride'] * torch.tensor(p_stats['stride'])\n            else: output_stride = torch.tensor([1, 1, 1])\n\n            module_stats['output_stride'] = output_stride.clone().detach()\n\n            self._stats_per_grad_fn[output.grad_fn] = module_stats\n            self._module_stats[module] = module_stats\n\n    def _backward_gather_statistics_hook(self, module, grad_in, grad_out):\n        stride, kernel_size, _ = _triple(module.stride), _triple(module.kernel_size), _triple(module.padding)\n\n        if grad_in[0] is not None:\n            # We sum over the channels to deal with networks that do different operations\n            # on groups of channels\n            f_grad = torch.sum(grad_in[0], dim=1)[0]\n\n            if isinstance(module, (torch.nn.MaxPool2d)):\n                # MaxPool shifts indices around, which break the calculation to\n                # find valid gradient values. To fix this we do an average pool\n                # with the same kernel-size and stride and repeat using the stride.\n                inpt = self._saved_tensors[module]\n                padded_inpt = inpt[0]\n                if module.padding != 0:\n                    padded_inpt = torch.nn.functional.pad(inpt[0], [module.padding, module.padding,\n                                                                    module.padding, module.padding], value=-1)\n\n                new_outpt = torch.nn.functional.avg_pool2d(padded_inpt, kernel_size[1:], stride[1:])[0]\n                new_outpt = torch.sum(new_outpt, dim=0)\n\n                f_grad = torch.sum(grad_out[0], dim=1)[0]\n                f_grad = f_grad * new_outpt\n                f_grad = f_grad.cpu()\n                f_grad = np.repeat(f_grad, stride[0], axis=0)\n                f_grad = np.repeat(f_grad, stride[1], axis=1)\n                grad = np.zeros(grad_in[0].shape[2:])\n                grad[:f_grad.shape[0], :f_grad.shape[1]] = f_grad\n                f_grad = torch.from_numpy(grad)\n                f_grad = f_grad.to(self.device)\n\n            grad_lost = self._non_max_border_amount(grad_out[0])\n\n            if self.verbose: print(module, \"\\n\", grad_lost)\n            self._module_stats[module]['grad_lost'] = grad_lost\n\n            valid_grad = (f_grad > (1-self.eps) * f_grad.max())\n\n            # When kernel_size > stride we have some _overlap_ of gradients,\n            # this overlap makes extra positions in the input gradient invalid\n            if (stride[0] > 1 and kernel_size[0] > stride[0]) or \\\n                    (stride[1] > 1 and kernel_size[1] > stride[1]) or \\\n                    (stride[2] > 1 and kernel_size[2] > stride[2]):\n                valid_lost = self._non_max_border_amount(f_grad)\n                valid_grad.fill_(0)\n                overlap_rows = kernel_size[1] - stride[1]\n                overlap_cols = kernel_size[2] - stride[2]\n                valid_grad[valid_lost.top + overlap_rows:\n                           valid_grad.shape[0] - valid_lost.bottom - overlap_rows,\n                           valid_lost.left + overlap_cols:\n                           valid_grad.shape[1] - valid_lost.right - overlap_cols] = 1\n\n            new_grad_in = valid_grad[None].expand(grad_in[0].shape[1], *valid_grad.shape)[None]\n            new_grad_in = (new_grad_in.type(self.dtype) * 10 - 1)\n            new_grad_in_lost = self._non_max_border_amount(new_grad_in)\n            return (new_grad_in, *grad_in[1:])\n\n    def _backward_saliency_hook(self, module: StreamingConv2d, grad_in, grad_out, is_bias=False, change_grad=True):\n        stride: List[int] = _triple(module.stride)  # type:ignore\n\n        # Trim gradient of invalid values\n        sides = module.input_loc.sides\n        grad_lost = module.grad_lost  # type: Lost\n\n        lost_top = grad_lost.top if not sides.top else 0\n        lost_bottom = grad_lost.bottom if not sides.bottom else 0\n        lost_left = grad_lost.left if not sides.left else 0\n        lost_right = grad_lost.right if not sides.right else 0\n        lost = Lost(lost_top, lost_left, lost_bottom, lost_right)\n\n        # Calculate which part of the gradient is 'new'\n        new_output_box = module.tile_output_box\n        updated_total_indices = module.seen_indices\n\n        if module.in_channels == 3:\n            valid_grad_in = grad_in[0][:, :,\n                                       lost.top*stride[0]:grad_in[0].shape[2] - lost.bottom*stride[0],\n                                       lost.left*stride[1]:grad_in[0].shape[3] - lost.right*stride[1]]\n\n            relevant_input_grad = valid_grad_in[:, :,\n                                                new_output_box.y*stride[0]:\n                                                new_output_box.y*stride[0] + new_output_box.height*stride[0],\n                                                new_output_box.x*stride[1]:\n                                                new_output_box.x*stride[1] + new_output_box.width*stride[1]]\n\n            self.saliency_map[:, :,\n                              updated_total_indices.y * stride[0]:\n                              updated_total_indices.height * stride[0],\n                              updated_total_indices.x * stride[1] - relevant_input_grad.shape[3]:\n                              updated_total_indices.x * stride[1]] = relevant_input_grad.detach().cpu()\n\n            del relevant_input_grad\n            del valid_grad_in\n\n    @staticmethod\n    def _new_value_indices(data_shape, data_indices, old_value_indices):\n        \"\"\"\n        This helper functions assumes we reconstruct feature maps and\n        gradients in tiles from top-left to bottom-right. Using current tile\n        index and old_value_indices it finds the relative indices of `data`\n        which are unique for this tile (not earlier seen in other tiles).\n        \"\"\"\n        rel_top, rel_bottom, rel_left, rel_right = 0, 0, 0, 0\n\n        old_values_y = old_value_indices.y\n        old_values_x = old_value_indices.x\n        old_values_height = old_value_indices.height\n\n        # Check if new row\n        if data_indices.x == 0:\n            old_values_y = old_values_height\n            old_values_height = data_indices.y + data_shape[H_DIM]\n            old_values_x = 0\n\n        # Check x-axis:\n        # If this gradient is exactly on the border of old_value_indices\n        # everything is new.\n        if data_indices.x == old_values_x:\n            rel_left = 0\n            rel_right = data_shape[W_DIM]\n\n        # If data_indices has some overlap with old_value_indices, trim unique\n        # indices.\n        else:\n            assert old_values_x - data_indices.x >= 0, \"Misses data in x-axis!\"\n            rel_left = old_values_x - data_indices.x\n            rel_right = data_shape[W_DIM]\n\n        # Check y-axis:\n        # Equal to column logic (see above)\n        if data_indices.y == old_values_y:\n            rel_top = 0\n            rel_bottom = data_shape[H_DIM]\n        else:\n            assert old_values_y - data_indices.y >= 0, \"We miss data in y-axis\"\n            rel_top = old_values_y - data_indices.y\n            rel_bottom = data_shape[H_DIM]\n\n        # Update old-value-indices\n        old_values_x += (rel_right - rel_left)\n\n        assert rel_top >= 0, f\"We miss data in y-axis before: {data_indices}\"\n        assert rel_left >= 0, f\"We miss data in x-axis before: {data_indices}\"\n\n        new_value_indices = Box(rel_top, rel_bottom - rel_top, rel_left, rel_right - rel_left, None)\n        old_value_indices = Box(int(old_values_y), int(old_values_height), int(old_values_x), 0, None)\n\n        return new_value_indices, old_value_indices\n\n    def _prev_stats(self, tensor):\n        prev = tensor.grad_fn\n        prev_stats = None\n        while True:\n            if prev in self._stats_per_grad_fn:\n                prev_stats = self._stats_per_grad_fn[prev]\n                break\n            if hasattr(prev, 'next_functions') and len(prev.next_functions) > 0:\n                prev = prev.next_functions[0][0]\n            else:\n                break\n        return prev_stats\n\n    def state_dict(self):\n        named_stats = {\n            'net_stats': {}\n        }\n        for name, module in self.stream_module.named_modules():\n            if module in self._module_stats:\n                named_stats['net_stats'][name] = self._module_stats[module]\n        named_stats['output_stride'] = self.output_stride\n        named_stats['tile_output_lost'] = self.tile_output_lost  # type:ignore\n        named_stats['tile_gradient_lost'] = self.tile_gradient_lost  # type:ignore\n        named_stats['tile_output_shape'] = self._tile_output_shape  # type:ignore\n        return named_stats\n\n    def load_state_dict(self, state):\n        self.disable()\n\n        self.output_stride = state['output_stride']\n        self.tile_output_lost = state['tile_output_lost']\n        self.tile_gradient_lost = state['tile_gradient_lost']\n        self._tile_output_shape = state['tile_output_shape']\n\n        for name, module in self.stream_module.named_modules():\n            if name in state['net_stats']:\n                self._module_stats[module] = state['net_stats'][name] \n\n        self.enable()\n", "meta": {"hexsha": "8ab8b17078e21a2b7a6bf341b24c2401b9f443d0", "size": 48223, "ext": "py", "lang": "Python", "max_stars_repo_path": "scnn.py", "max_stars_repo_name": "DIAGNijmegen/StreamingSGD", "max_stars_repo_head_hexsha": "95f95e1240dadf5ebc6e39eb6eb5c0a22b64dd76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2018-04-17T11:04:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-17T01:05:58.000Z", "max_issues_repo_path": "scnn.py", "max_issues_repo_name": "DIAGNijmegen/StreamingSGD", "max_issues_repo_head_hexsha": "95f95e1240dadf5ebc6e39eb6eb5c0a22b64dd76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-19T03:42:20.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-29T09:37:23.000Z", "max_forks_repo_path": "scnn.py", "max_forks_repo_name": "DIAGNijmegen/StreamingSGD", "max_forks_repo_head_hexsha": "95f95e1240dadf5ebc6e39eb6eb5c0a22b64dd76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-04-17T14:28:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-18T09:11:29.000Z", "avg_line_length": 44.6096207216, "max_line_length": 196, "alphanum_fraction": 0.6059141903, "include": true, "reason": "import numpy", "num_tokens": 10345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.2814056074291439, "lm_q1q2_score": 0.1667797005138022}}
{"text": "# -*- coding: future_fstrings -*-\n\nimport numpy as np\nimport torch\nfrom torch.distributions import Normal, kl_divergence, Bernoulli, RelaxedBernoulli\nfrom torch import nn\nimport torch.nn.functional as F\nfrom .utils import spatial_transform, calc_kl_z_pres_bernoulli\nfrom .common import *\nfrom .modules import NumericalRelaxedBernoulli\n\n\nclass TrackerRNN(nn.Module):\n\n    def __init__(self, hid_dim):\n        super(TrackerRNN, self).__init__()\n\n        self.cell = nn.GRUCell(temporal_rnn_inp_dim, hid_dim)\n\n    def forward(self, h_pre, c_pre, temporal_rnn_inp):\n        h = self.cell(temporal_rnn_inp, c_pre)\n\n        # output and hidden, for vanilla rnn, output == hidden\n        return h, h\n\n\nclass AttEncoder(nn.Module):\n\n    def __init__(self, args):\n        self.args = args\n        super(AttEncoder, self).__init__()\n\n        self.temporal_img_conv_net = nn.Sequential(\n            nn.Conv2d(img_encode_dim, temporal_img_enc_hid_dim, 1),\n            nn.ELU(),\n            nn.GroupNorm(8, temporal_img_enc_hid_dim)\n        )\n\n        self.temporal_img_enc_net = nn.Linear(\n            temporal_img_enc_hid_dim * self.args.num_cell_h // 2 * self.args.num_cell_w // 2, temporal_img_enc_dim)\n\n    def forward(self, img_enc):\n        \"\"\"\n\n        :param x: (bs, dim, img_h, img_w)\n        \"\"\"\n        bs = img_enc.size(0)\n        x = self.temporal_img_enc_net(self.temporal_img_conv_net(img_enc).view(bs, -1))\n\n        # bs, dim\n        return x\n\n\nclass PropagationCell(nn.Module):\n\n    def __init__(self, args, z_what_net, glimpse_dec_net):\n        super(PropagationCell, self).__init__()\n        self.args = args\n\n        self.z_pres_logits_bias = 2.\n        self.where_update_scale = where_update_scale\n        self.z_where_std_bias = -2\n\n        # self.z_what_gate_bias = 2\n        self.register_buffer('z_pres_stop_threshold', torch.tensor(0.6))\n\n        z_where_transit_bias_net_input_dim = temporal_rnn_out_dim + z_what_dim + z_where_scale_dim + \\\n                                             z_where_shift_dim + z_where_bias_dim + temporal_img_enc_dim\n\n        self.z_where_transit_bias_net = nn.Sequential(\n            nn.Linear(z_where_transit_bias_net_input_dim, z_where_transit_bias_net_hid_dim),\n            nn.ELU(),\n            nn.Linear(z_where_transit_bias_net_hid_dim, (z_where_scale_dim + z_where_shift_dim) * 2)\n        )\n\n        z_depth_transit_net_input_dim = temporal_rnn_out_dim + z_what_dim + temporal_img_enc_dim\n\n        self.z_depth_transit_net = nn.Sequential(\n            nn.Linear(z_depth_transit_net_input_dim, z_depth_transit_net_hid_dim),\n            nn.ELU(),\n            nn.Linear(z_depth_transit_net_hid_dim, z_depth_dim * 2)\n        )\n\n        self.z_what_from_temporal_net = nn.Sequential(\n            nn.Linear(temporal_rnn_out_dim, z_what_from_temporal_hid_dim),\n            nn.ELU(),\n            nn.Linear(z_what_from_temporal_hid_dim, z_what_dim * 2)\n        )\n\n        z_what_gate_net_inp_dim = temporal_rnn_out_dim + temporal_img_enc_dim\n\n        self.z_what_gate_net = nn.Sequential(\n            nn.Linear(z_what_gate_net_inp_dim, 64),\n            nn.ELU(),\n            nn.Linear(64, 2),\n            nn.Sigmoid(),\n        )\n\n        z_pres_transit_input_dim = temporal_rnn_out_dim + z_where_scale_dim + \\\n                                   z_where_shift_dim + z_where_bias_dim + z_what_dim\n\n        self.z_pres_transit = nn.Sequential(\n            nn.Linear(z_pres_transit_input_dim, z_pres_hid_dim),\n            nn.ELU(),\n            nn.Linear(z_pres_hid_dim, z_pres_dim),\n        )\n\n        temporal_rnn_inp_net_inp_dim = z_where_scale_dim + z_where_shift_dim + z_pres_dim + \\\n                                       z_what_dim + z_where_bias_dim + temporal_img_enc_dim\n\n        self.temporal_rnn_inp_net = nn.Linear(temporal_rnn_inp_net_inp_dim, temporal_rnn_inp_dim)\n\n        self.temporal_rnn = TrackerRNN(temporal_rnn_hid_dim)\n        self.attention_encoding = AttEncoder(self.args)\n\n        self.glimpse_dec_net = glimpse_dec_net\n        self.z_what_net = z_what_net\n        self.prior_cell = PropagatePrior()\n\n    def update_z_where(self, z_where_pre, z_where_bias):\n        z_where_shift = z_where_pre[:, 2:] + self.where_update_scale * z_where_bias[:, 2:].tanh()\n\n        scale, ratio = z_where_bias[:, :2].tanh().chunk(2, 1)\n        scale = self.args.size_anc + self.args.var_s * scale  # add bias to let masking do its job\n        ratio = self.args.ratio_anc + self.args.var_anc * ratio\n        ratio_sqrt = ratio.sqrt()\n\n        z_where = torch.cat((scale / ratio_sqrt, scale * ratio_sqrt, z_where_shift), dim=1)\n        # # always within the image\n        z_where = torch.cat((z_where[:, :2], z_where[:, 2:].clamp(-1.05, 1.05)), dim=1)\n        return z_where\n\n    def forward(self, x, img_enc, temporal_rnn_out_pre, temporal_rnn_hid_pre, prior_rnn_out_pre,\n                prior_rnn_hid_pre, z_what_pre, z_where_pre, z_where_bias_pre, z_depth_pre, z_pres_pre,\n                cumsum_one_minus_z_pres, ids_pre, lengths, max_length, t, no_disc=False, eps=1e-15):\n        \"\"\"\n\n        :param x: input image (bs, c, h, w)\n        :param img_enc: input image encode (bs, c, num_cell_h, num_cell_w)\n        :param temporal_rnn_out_pre: (bs, max_num_obj, dim)\n        :param temporal_rnn_hid_pre: (bs, max_num_obj, dim)\n        :param z_what_pre: (bs, max_num_obj, dim)\n        :param z_where_pre: (bs, max_num_obj, dim)\n        :param z_depth_pre: (bs, max_num_obj, dim)\n        :param z_pres_pre: (bs, max_num_obj, dim)\n        :param cumsum_one_minus_z_pres: (bs, max_num_obj, dim)\n        :param lengths: (bs)\n        :return:\n        \"\"\"\n        bs = x.size(0)\n        device = x.device\n        max_num_obj = max_length\n        bns = bs * max_num_obj\n        obj_mask = (z_pres_pre.view(bs, max_num_obj) != 0).float()\n        temporal_rnn_out_pre, temporal_rnn_hid_pre, prior_rnn_out_pre, \\\n        prior_rnn_hid_pre, z_what_pre, z_where_pre, z_where_bias_pre, z_depth_pre, \\\n        z_pres_pre, cumsum_one_minus_z_pres = \\\n            temporal_rnn_out_pre.view(bns, -1), temporal_rnn_hid_pre.view(bns, -1), \\\n            prior_rnn_out_pre.view(bns, -1), prior_rnn_hid_pre.view(bns, -1), \\\n            z_what_pre.view(bns, -1), z_where_pre.view(bns, -1), z_where_bias_pre.view(bns, -1), \\\n            z_depth_pre.view(bns, -1), z_pres_pre.view(bns, -1), \\\n            cumsum_one_minus_z_pres.view(bns, -1)\n\n        prior_rnn_out, prior_rnn_hid, prior_what_mean, prior_what_std, prior_where_bias_mean, \\\n        prior_where_bias_std, prior_depth_mean, prior_depth_std, prior_pres_prob = \\\n            self.prior_cell(prior_rnn_out_pre, prior_rnn_hid_pre, z_what_pre,\n                            z_where_pre, z_where_bias_pre, z_depth_pre, z_pres_pre)\n\n        z_where_att = x.new_ones(z_where_pre.size()) * .5\n        z_where_att[:, 2:] = z_where_pre[:, 2:].detach()\n        img_enc_att = spatial_transform(\n            img_enc.unsqueeze(1).expand(-1, max_num_obj, -1, -1, -1).contiguous().\n                view(bns, img_encode_dim, self.args.num_cell_h, self.args.num_cell_w), z_where_att,\n            (bns, img_encode_dim, self.args.num_cell_h // 2, self.args.num_cell_w // 2), inverse=False\n        )\n        # bns, dim\n        temporal_img_enc = self.attention_encoding(img_enc_att).view(-1, temporal_img_enc_dim)\n        temporal_img_enc = \\\n            temporal_img_enc.view(bs, -1, temporal_img_enc_dim).contiguous().view(-1, temporal_img_enc_dim)\n\n        temporal_rnn_inp_net_inp = torch.cat(\n            [z_where_pre, z_pres_pre, z_what_pre, z_where_bias_pre, temporal_img_enc],\n            dim=1\n        )\n        temporal_rnn_inp = self.temporal_rnn_inp_net(temporal_rnn_inp_net_inp)\n        # bns, dim\n        temporal_rnn_out, temporal_rnn_hid = self.temporal_rnn(\n            temporal_rnn_out_pre, temporal_rnn_hid_pre, temporal_rnn_inp\n        )\n\n        # z_where transition\n        z_where_transit_bias_net_inp = torch.cat(\n            [temporal_rnn_out, z_what_pre, z_where_pre, z_where_bias_pre, temporal_img_enc], dim=1\n        )\n        z_where_bias_mean, z_where_bias_std = \\\n            self.z_where_transit_bias_net(z_where_transit_bias_net_inp).chunk(2, -1)\n        z_where_bias_std = F.softplus(z_where_bias_std + self.z_where_std_bias)\n        if self.args.phase_generate and t >= self.args.observe_frames:\n            z_where_bias_dist = Normal(prior_where_bias_mean, prior_where_bias_std)\n        else:\n            z_where_bias_dist = Normal(z_where_bias_mean, z_where_bias_std)\n\n        z_where_bias = z_where_bias_dist.rsample()\n        z_where = self.update_z_where(z_where_pre, z_where_bias)\n        z_where_mean = self.update_z_where(z_where_pre, z_where_bias_mean)\n\n        # get glimpse encode\n        x_att = \\\n            spatial_transform(\n                x.unsqueeze(1).expand(-1, max_num_obj, -1, -1, -1).contiguous().view(bns, 3, img_h, img_w), z_where,\n                (bns, 3, glimpse_size, glimpse_size), inverse=False\n            )\n\n        z_what_from_enc_mean, z_what_from_enc_std = self.z_what_net(\n            x_att\n        )\n        z_what_from_enc_std = F.softplus(z_what_from_enc_std)\n\n        # z_what transit\n        z_what_from_temporal_mean, z_what_from_temporal_std = \\\n            self.z_what_from_temporal_net(temporal_rnn_out).chunk(2, -1)\n\n        z_what_from_temporal_std = F.softplus(z_what_from_temporal_std)\n\n        z_what_gate_net_inp = torch.cat((temporal_rnn_out, temporal_img_enc), dim=1)\n        forget_gate, input_gate = self.z_what_gate_net(z_what_gate_net_inp).chunk(2, -1)\n\n        z_what_mean = input_gate * z_what_from_enc_mean + \\\n                      forget_gate * z_what_from_temporal_mean\n\n        z_what_std = F.softplus(input_gate * z_what_from_enc_std + \\\n                                forget_gate * z_what_from_temporal_std)\n\n        if self.args.phase_generate and t >= self.args.observe_frames:\n            z_what_dist = Normal(prior_what_mean, prior_what_std)\n        else:\n            z_what_dist = Normal(z_what_mean, z_what_std)\n\n        z_what = z_what_dist.rsample()\n\n        z_depth_transit_net_inp = torch.cat(\n            [temporal_rnn_out, z_what, temporal_img_enc],\n            dim=1\n        )\n        z_depth_mean, z_depth_std = self.z_depth_transit_net(z_depth_transit_net_inp).chunk(2, -1)\n        z_depth_std = F.softplus(z_depth_std)\n\n        if self.args.phase_generate and t >= self.args.observe_frames:\n            z_depth_dist = Normal(prior_depth_mean, prior_depth_std)\n        else:\n            z_depth_dist = Normal(z_depth_mean, z_depth_std)\n\n        z_depth = z_depth_dist.rsample()\n\n        # z_pres bns, dim\n        z_pres_transit_inp = torch.cat(\n            [temporal_rnn_out, z_where, z_where_bias, z_what],\n            dim=1\n        )\n        z_pres_logits = pres_logit_factor * torch.tanh(self.z_pres_transit(z_pres_transit_inp) +\n                                                       self.z_pres_logits_bias)\n        if self.args.phase_generate and t >= self.args.observe_frames:\n            q_z_pres = NumericalRelaxedBernoulli(probs=prior_pres_prob, temperature=self.args.tau)\n        else:\n            q_z_pres = NumericalRelaxedBernoulli(logits=z_pres_logits, temperature=self.args.tau)\n\n        # for z_pres, we end up setting this to one during generation\n        z_pres_y = q_z_pres.rsample()\n        z_pres = torch.sigmoid(z_pres_y)\n        if no_disc:\n            z_pres = torch.ones_like(z_pres)\n        cumsum_one_minus_z_pres += (1 - z_pres) * obj_mask.view(bns, 1)\n        z_pres = z_pres * (cumsum_one_minus_z_pres < self.z_pres_stop_threshold).float()\n\n        # (bs, dim, glimpse_size, glimpse_size)\n        o_att, alpha_att = self.glimpse_dec_net(z_what)\n\n        alpha_att_hat = alpha_att * z_pres.view(-1, 1, 1, 1)\n        y_att = alpha_att_hat * o_att\n\n        # (bs, 3, img_h, img_w)\n        y_each_obj = spatial_transform(y_att, z_where, (bns, 3, img_h, img_w), inverse=True)\n\n        # (batch_size_t, 1, glimpse_size, glimpse_size)\n        importance_map = alpha_att_hat * torch.sigmoid(-z_depth).view(-1, 1, 1, 1)\n\n        # (batch_size_t, 1, img_h, img_w)\n        importance_map_full_res = spatial_transform(importance_map, z_where, (bns, 1, img_h, img_w),\n                                                    inverse=True)\n\n        # (batch_size_t, 1, img_h, img_w)\n        alpha_map = spatial_transform(alpha_att_hat, z_where, (bns, 1, img_h, img_w), inverse=True)\n\n        kl_z_pres = \\\n            (calc_kl_z_pres_bernoulli(z_pres_logits, prior_pres_prob) *\n             obj_mask.view(bns)).view(bs, max_num_obj).sum(1)\n\n        prior_what_dist = Normal(prior_what_mean, prior_what_std)\n        prior_where_bias_dist = Normal(prior_where_bias_mean, prior_where_bias_std)\n        prior_depth_dist = Normal(prior_depth_mean, prior_depth_std)\n\n        kl_z_what = \\\n            (kl_divergence(z_what_dist, prior_what_dist).sum(1) * \\\n             z_pres.squeeze() * obj_mask.view(bns)).view(bs, max_num_obj).sum(1)\n        kl_z_where = \\\n            (kl_divergence(z_where_bias_dist, prior_where_bias_dist).sum(1) * \\\n             z_pres.squeeze() * obj_mask.view(bns)).view(bs, max_num_obj).sum(1)\n        kl_z_depth = \\\n            (kl_divergence(z_depth_dist, prior_depth_dist).sum(1) * \\\n             z_pres.squeeze() * obj_mask.view(bns)).view(bs, max_num_obj).sum(1)\n\n        ########################################### Compute log importance ############################################\n        log_imp = x.new_zeros(bs, 1)\n        if not self.training and self.args.phase_nll:\n            z_pres_binary = (z_pres > 0.5).float()\n            # (bns, dim)\n            log_imp_what = (prior_what_dist.log_prob(z_what) - z_what_dist.log_prob(z_what)) * \\\n                           z_pres_binary * obj_mask.view(bns, 1)\n            log_imp_depth = (prior_depth_dist.log_prob(z_depth) - z_depth_dist.log_prob(z_depth)) * \\\n                            z_pres_binary * obj_mask.view(bns, 1)\n            log_imp_where = (prior_where_bias_dist.log_prob(z_where_bias) - z_where_bias_dist.log_prob(z_where_bias)) * \\\n                            z_pres_binary * obj_mask.view(bns, 1)\n\n            log_pres_prior = z_pres_binary * torch.log(prior_pres_prob + eps) + \\\n                             (1 - z_pres_binary) * torch.log(1 - prior_pres_prob + eps)\n\n            log_pres_pos = z_pres_binary * torch.log(torch.sigmoid(z_pres_logits) + eps) + \\\n                           (1 - z_pres_binary) * torch.log(1 - torch.sigmoid(z_pres_logits) + eps)\n\n            log_imp_pres = (log_pres_prior - log_pres_pos) * obj_mask.view(bns, 1)\n\n            log_imp = log_imp_what.view(bs, -1).sum(1) + log_imp_depth.view(bs, -1).sum(1) + \\\n                      log_imp_where.view(bs, -1).sum(1) + log_imp_pres.view(bs, -1).sum(1)\n\n        ######################################## End of Compute log importance #########################################\n        z_what_all = z_what.view(bs, max_num_obj, -1) * obj_mask.view(bs, max_num_obj, 1)\n        z_where_dummy = x.new_ones(bs, max_num_obj, (z_where_scale_dim + z_where_shift_dim)) * .5\n        z_where_dummy[:, :, z_where_scale_dim:] = 2\n        z_where_all = z_where.view(bs, max_num_obj, -1) * obj_mask.view(bs, max_num_obj, 1) + \\\n                      z_where_dummy * (1 - obj_mask.view(bs, max_num_obj, 1))\n        z_where_bias_all = z_where_bias.view(bs, max_num_obj, -1) * obj_mask.view(bs, max_num_obj, 1)\n        z_pres_all = z_pres.view(bs, max_num_obj, -1) * obj_mask.view(bs, max_num_obj, 1)\n        temporal_rnn_hid_all = \\\n            temporal_rnn_hid.view(bs, max_num_obj, -1) * obj_mask.view(bs, max_num_obj, 1)\n        temporal_rnn_out_all = \\\n            temporal_rnn_out.view(bs, max_num_obj, -1) * obj_mask.view(bs, max_num_obj, 1)\n        z_depth_all = z_depth.view(bs, max_num_obj, -1) * obj_mask.view(bs, max_num_obj, 1)\n        y_each_obj_all = \\\n            y_each_obj.view(bs, max_num_obj, 3, img_h, img_w) * obj_mask.view(bs, max_num_obj, 1, 1, 1)\n        alpha_map_all = \\\n            alpha_map.view(bs, max_num_obj, 1, img_h, img_w) * obj_mask.view(bs, max_num_obj, 1, 1, 1)\n        importance_map_all = \\\n            importance_map_full_res.view(bs, max_num_obj, 1, img_h, img_w) * \\\n            obj_mask.view(bs, max_num_obj, 1, 1, 1)\n\n        cumsum_one_minus_z_pres = cumsum_one_minus_z_pres.view(bs, max_num_obj, -1)\n        prior_rnn_out = prior_rnn_out.view(bs, max_num_obj, -1)\n        prior_rnn_hid = prior_rnn_hid.view(bs, max_num_obj, -1)\n\n        if self.args.log_phase:\n            self.log = {\n                'z_what': z_what_all,\n                'z_where': z_where_all,\n                'z_pres': z_pres_all,\n                'z_what_std': z_what_std.view(bs, max_num_obj, -1),\n                'z_what_mean': z_what_mean.view(bs, max_num_obj, -1),\n                'z_where_bias_std': z_where_bias_std.view(bs, max_num_obj, -1),\n                'z_where_bias_mean': z_where_bias_mean.view(bs, max_num_obj, -1),\n                'glimpse': x_att.view(bs, max_num_obj, 3, glimpse_size, glimpse_size),\n                'glimpse_recon': y_att.view(bs, max_num_obj, 3, glimpse_size, glimpse_size),\n                'prior_z_pres_prob': prior_pres_prob.view(bs, max_num_obj, -1),\n                'prior_where_bias_std': prior_where_bias_std.view(bs, max_num_obj, -1),\n                'prior_where_bias_mean': prior_where_bias_mean.view(bs, max_num_obj, -1),\n                'prior_what_mean': prior_what_mean.view(bs, max_num_obj, -1),\n                'prior_what_std': prior_what_std.view(bs, max_num_obj, -1),\n                'lengths': lengths,\n                'z_depth': z_depth_all,\n                'z_depth_std': z_depth_std.view(bs, max_num_obj, -1),\n                'z_depth_mean': z_depth_mean.view(bs, max_num_obj, -1),\n                'y_each_obj': y_each_obj_all.view(bs, max_num_obj, 3, img_h, img_w),\n                'alpha_map': alpha_map_all.view(bs, max_num_obj, 1, img_h, img_w),\n                'importance_map': importance_map_all.view(bs, max_num_obj, 1, img_h, img_w),\n                'z_pres_logits': z_pres_logits.view(bs, max_num_obj, -1),\n                'z_pres_y': z_pres_y.view(bs, max_num_obj, -1),\n                'o_att': o_att.view(bs, max_num_obj, 3, glimpse_size, glimpse_size),\n                'z_where_bias': z_where_bias_all,\n                'ids': ids_pre\n            }\n        else:\n            self.log = {}\n        representation = {\"z_where\": z_where_mean.view(bs, max_num_obj, -1) * obj_mask.view(bs, max_num_obj, 1)+z_where_dummy * (1 - obj_mask.view(bs, max_num_obj, 1)), \n                          \"z_what\": z_what_mean.view(bs, max_num_obj, -1) * obj_mask.view(bs, max_num_obj, 1), \n                          \"z_depth\": z_depth_mean.view(bs, max_num_obj, -1) * obj_mask.view(bs, max_num_obj, 1)\n                          }\n        only_prop_representation = {\"z_where\": z_where_mean, \n                          \"z_what\": z_what_mean, \n                          \"z_depth\": z_depth_mean\n                          }\n        return y_each_obj_all, alpha_map_all, importance_map_all, z_what_all, z_where_all, \\\n               z_where_bias_all, z_depth_all, z_pres_all, ids_pre, kl_z_what, kl_z_where, kl_z_depth, \\\n               kl_z_pres, temporal_rnn_out_all, temporal_rnn_hid_all, prior_rnn_out, \\\n               prior_rnn_hid, cumsum_one_minus_z_pres, log_imp, self.log, representation, only_prop_representation\n\n\nclass PropagatePrior(nn.Module):\n    \"\"\"Attention, initial state of rnn is learnable\"\"\"\n\n    def __init__(self):\n        super(PropagatePrior, self).__init__()\n\n        prior_rnn_inp_net_inp_dim = z_what_dim + z_where_scale_dim + z_where_shift_dim + \\\n                                    z_where_bias_dim + z_depth_dim + z_pres_dim\n\n        self.prior_rnn_inp_net = nn.Linear(prior_rnn_inp_net_inp_dim, prior_rnn_inp_dim)\n\n        self.prior_rnn = nn.LSTMCell(prior_rnn_inp_dim, prior_rnn_hid_dim)\n\n        self.prior_what_net = nn.Linear(prior_rnn_out_dim, z_what_dim * 2)\n        self.prior_where_bias_net = nn.Linear(\n            prior_rnn_out_dim, (z_where_scale_dim + z_where_shift_dim) * 2)\n\n        self.prior_depth_net = nn.Linear(prior_rnn_out_dim, z_depth_dim * 2)\n        self.prior_pres_net = nn.Linear(prior_rnn_out_dim, z_pres_dim)\n        self.prior_z_pres_logits_bias = 5.\n        self.where_update_scale = where_update_scale\n\n    def forward(self, prior_rnn_out_pre, prior_rnn_hid_pre, z_what_pre,\n                z_where_pre, z_where_bias_pre, z_depth_pre, z_pres_pre, eps=1e-15):\n        bns = z_what_pre.size(0)\n\n        z_what_pre_flat = z_what_pre.view(-1, z_what_dim)\n        z_where_pre_flat = z_where_pre.view(-1, z_where_scale_dim + z_where_shift_dim)\n        z_where_bias_pre_flat = z_where_bias_pre.view(-1, z_where_bias_dim)\n        z_depth_pre_flat = z_depth_pre.view(-1, z_depth_dim)\n        z_pres_pre_flat = z_pres_pre.view(-1, z_pres_dim)\n\n        prior_rnn_out_pre_flat = prior_rnn_out_pre.view(bns, -1)\n        prior_rnn_hid_pre_flat = prior_rnn_hid_pre.view(bns, -1)\n\n        # prior_rnn\n        prior_rnn_inp_net_inp = torch.cat((z_what_pre_flat, z_where_pre_flat, z_where_bias_pre_flat,\n                                           z_depth_pre_flat, z_pres_pre_flat), dim=1)\n        prior_rnn_inp = self.prior_rnn_inp_net(prior_rnn_inp_net_inp)\n\n        prior_rnn_out, prior_rnn_hid = self.prior_rnn(prior_rnn_inp, (prior_rnn_out_pre_flat,\n                                                                      prior_rnn_hid_pre_flat))\n\n        prior_what_mean, prior_what_std = self.prior_what_net(prior_rnn_out).chunk(2, -1)\n        prior_depth_mean, prior_depth_std = self.prior_depth_net(prior_rnn_out).chunk(2, -1)\n        prior_where_bias_mean, prior_where_bias_std = self.prior_where_bias_net(prior_rnn_out).chunk(2, -1)\n\n        prior_pres_probs = torch.sigmoid(self.prior_pres_net(prior_rnn_out) + \\\n                                         self.prior_z_pres_logits_bias)\n\n        prior_rnn_out = prior_rnn_out.view(bns, -1)\n        prior_rnn_hid = prior_rnn_hid.view(bns, -1)\n        prior_what_mean = prior_what_mean.view(bns, -1)\n        prior_what_std = prior_what_std.view(bns, -1)\n        prior_where_bias_mean = prior_where_bias_mean.view(bns, -1)\n        prior_where_bias_std = prior_where_bias_std.view(bns, -1)\n        prior_depth_mean = prior_depth_mean.view(bns, -1)\n        prior_depth_std = prior_depth_std.view(bns, -1)\n        prior_pres_probs = prior_pres_probs.view(bns, -1)\n\n        return prior_rnn_out, prior_rnn_hid, prior_what_mean, F.softplus(prior_what_std), \\\n               prior_where_bias_mean, F.softplus(prior_where_bias_std), prior_depth_mean, \\\n               F.softplus(prior_depth_std), prior_pres_probs\n", "meta": {"hexsha": "180ddae104f29b00ae8c92d45fba86e68018ae76", "size": 22626, "ext": "py", "lang": "Python", "max_stars_repo_path": "rlkit/rlkit/torch/scalor/propagation.py", "max_stars_repo_name": "martius-lab/SMORL", "max_stars_repo_head_hexsha": "d23eda9d6a72baa3ab1f4d729b2e4f742e4dd9db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-06-16T11:15:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T04:42:07.000Z", "max_issues_repo_path": "rlkit/rlkit/torch/scalor/propagation.py", "max_issues_repo_name": "martius-lab/SMORL", "max_issues_repo_head_hexsha": "d23eda9d6a72baa3ab1f4d729b2e4f742e4dd9db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-08-17T08:07:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T10:48:38.000Z", "max_forks_repo_path": "rlkit/rlkit/torch/scalor/propagation.py", "max_forks_repo_name": "martius-lab/SMORL", "max_forks_repo_head_hexsha": "d23eda9d6a72baa3ab1f4d729b2e4f742e4dd9db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-12-09T06:48:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T07:38:36.000Z", "avg_line_length": 48.3461538462, "max_line_length": 169, "alphanum_fraction": 0.6379828516, "include": true, "reason": "import numpy", "num_tokens": 5899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.16675454446540863}}
{"text": "# Copyright 2016-2020 The GPflow Contributors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport enum\nfrom abc import ABC, abstractmethod\nfrom typing import Optional, Tuple, Union, cast\n\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_probability as tfp\n\nfrom . import covariances, kernels, mean_functions\nfrom .base import Module, Parameter, TensorType\nfrom .conditionals.util import (\n    base_conditional,\n    base_conditional_with_lm,\n    expand_independent_outputs,\n    fully_correlated_conditional,\n    independent_interdomain_conditional,\n    mix_latent_gp,\n    separate_independent_conditional_implementation,\n)\nfrom .config import default_float, default_jitter\nfrom .inducing_variables import (\n    FallbackSeparateIndependentInducingVariables,\n    FallbackSharedIndependentInducingVariables,\n    InducingPoints,\n    InducingVariables,\n    SeparateIndependentInducingVariables,\n    SharedIndependentInducingVariables,\n)\nfrom .types import MeanAndVariance\nfrom .utilities import Dispatcher, add_noise_cov\n\n\nclass _QDistribution(Module):\n    \"\"\"\n    Base class for our parametrization of q(u) in the `AbstractPosterior`.\n    Internal - do not rely on this outside of GPflow.\n    \"\"\"\n\n\nclass _DeltaDist(_QDistribution):\n    def __init__(self, q_mu):\n        self.q_mu = q_mu  # [M, L]\n\n    @property\n    def q_sqrt(self):\n        return None\n\n\nclass _DiagNormal(_QDistribution):\n    def __init__(self, q_mu, q_sqrt):\n        self.q_mu = q_mu  # [M, L]\n        self.q_sqrt = q_sqrt  # [M, L]\n\n\nclass _MvNormal(_QDistribution):\n    def __init__(self, q_mu, q_sqrt):\n        self.q_mu = q_mu  # [M, L]\n        self.q_sqrt = q_sqrt  # [L, M, M], lower-triangular\n\n\nclass PrecomputeCacheType(enum.Enum):\n    \"\"\"\n    - `PrecomputeCacheType.TENSOR` (or `\"tensor\"`): Precomputes the cached\n      quantities and stores them as tensors (which allows differentiating\n      through the prediction). This is the default.\n    - `PrecomputeCacheType.VARIABLE` (or `\"variable\"`): Precomputes the cached\n      quantities and stores them as variables, which allows for updating\n      their values without changing the compute graph (relevant for AOT\n      compilation).\n    - `PrecomputeCacheType.NOCACHE` (or `\"nocache\"` or `None`): Avoids\n      immediate cache computation. This is useful for avoiding extraneous\n      computations when you only want to call the posterior's\n      `fused_predict_f` method.\n    \"\"\"\n\n    TENSOR = \"tensor\"\n    VARIABLE = \"variable\"\n    NOCACHE = \"nocache\"\n\n\ndef _validate_precompute_cache_type(value) -> PrecomputeCacheType:\n    if value is None:\n        return PrecomputeCacheType.NOCACHE\n    elif isinstance(value, PrecomputeCacheType):\n        return value\n    elif isinstance(value, str):\n        return PrecomputeCacheType(value.lower())\n    else:\n        raise ValueError(\n            f\"{value} is not a valid PrecomputeCacheType. Valid options: 'tensor', 'variable', 'nocache' (or None).\"\n        )\n\n\nclass AbstractPosterior(Module, ABC):\n    def __init__(\n        self,\n        kernel,\n        X_data: Union[tf.Tensor, InducingVariables],\n        alpha: Optional[TensorType] = None,\n        Qinv: Optional[TensorType] = None,\n        mean_function: Optional[mean_functions.MeanFunction] = None,\n    ):\n        \"\"\"\n        Users should use `create_posterior` to create instances of concrete\n        subclasses of this AbstractPosterior class instead of calling this\n        constructor directly. For `create_posterior` to be able to correctly\n        instantiate subclasses, developers need to ensure their subclasses\n        don't change the constructor signature.\n        \"\"\"\n        super().__init__()\n\n        self.kernel = kernel\n        self.X_data = X_data\n        self.alpha = alpha\n        self.Qinv = Qinv\n        self.mean_function = mean_function\n\n    def _add_mean_function(self, Xnew, mean):\n        if self.mean_function is None:\n            return mean\n        else:\n            return mean + self.mean_function(Xnew)\n\n    def fused_predict_f(\n        self, Xnew, full_cov: bool = False, full_output_cov: bool = False\n    ) -> MeanAndVariance:\n        \"\"\"\n        Computes predictive mean and (co)variance at Xnew, including mean_function\n        Does not make use of caching\n        \"\"\"\n        mean, cov = self._conditional_fused(\n            Xnew, full_cov=full_cov, full_output_cov=full_output_cov\n        )\n        return self._add_mean_function(Xnew, mean), cov\n\n    @abstractmethod\n    def _conditional_fused(\n        self, Xnew, full_cov: bool = False, full_output_cov: bool = False\n    ) -> MeanAndVariance:\n        \"\"\"\n        Computes predictive mean and (co)variance at Xnew, *excluding* mean_function\n        Does not make use of caching\n        \"\"\"\n\n    def predict_f(\n        self, Xnew, full_cov: bool = False, full_output_cov: bool = False\n    ) -> MeanAndVariance:\n        \"\"\"\n        Computes predictive mean and (co)variance at Xnew, including mean_function.\n        Relies on precomputed alpha and Qinv (see _precompute method)\n        \"\"\"\n        if self.alpha is None or self.Qinv is None:\n            raise ValueError(\n                \"Cache has not been precomputed yet. Call update_cache first or use fused_predict_f\"\n            )\n        mean, cov = self._conditional_with_precompute(\n            Xnew, full_cov=full_cov, full_output_cov=full_output_cov\n        )\n        return self._add_mean_function(Xnew, mean), cov\n\n    @abstractmethod\n    def _conditional_with_precompute(\n        self, Xnew, full_cov: bool = False, full_output_cov: bool = False\n    ) -> MeanAndVariance:\n        \"\"\"\n        Computes predictive mean and (co)variance at Xnew, *excluding* mean_function.\n        Relies on cached alpha and Qinv.\n        \"\"\"\n\n    def update_cache(self, precompute_cache: Optional[PrecomputeCacheType] = None) -> None:\n        \"\"\"\n        Sets the cache depending on the value of `precompute_cache` to a\n        `tf.Tensor`, `tf.Variable`, or clears the cache. If `precompute_cache`\n        is not given, the setting defaults to the most-recently-used one.\n        \"\"\"\n        if precompute_cache is None:\n            try:\n                precompute_cache = cast(\n                    PrecomputeCacheType,\n                    self._precompute_cache,  # type: ignore\n                )\n            except AttributeError:\n                raise ValueError(\n                    \"You must pass precompute_cache explicitly (the cache had not been updated before).\"\n                )\n        else:\n            self._precompute_cache = precompute_cache\n\n        if precompute_cache is PrecomputeCacheType.NOCACHE:\n            self.alpha = self.Qinv = None\n\n        elif precompute_cache is PrecomputeCacheType.TENSOR:\n            self.alpha, self.Qinv = self._precompute()\n\n        elif precompute_cache is PrecomputeCacheType.VARIABLE:\n            alpha, Qinv = self._precompute()\n            if isinstance(self.alpha, tf.Variable) and isinstance(self.Qinv, tf.Variable):\n                # re-use existing variables\n                self.alpha.assign(alpha)\n                self.Qinv.assign(Qinv)\n            else:  # create variables\n                self.alpha = tf.Variable(alpha, trainable=False)\n                self.Qinv = tf.Variable(Qinv, trainable=False)\n\n\nclass GPRPosterior(AbstractPosterior):\n    def __init__(\n        self,\n        kernel,\n        X_data: tf.Tensor,\n        Y_data: tf.Tensor,\n        likelihood_variance: Parameter,\n        mean_function: Optional[mean_functions.MeanFunction] = None,\n        *,\n        precompute_cache: Optional[PrecomputeCacheType],\n    ):\n\n        super().__init__(kernel, X_data, mean_function=mean_function)\n        self.mean_function = mean_function\n        self.Y_data = Y_data\n        self.likelihood_variance = likelihood_variance\n\n        if precompute_cache is not None:\n            self.update_cache(precompute_cache)\n\n    def _conditional_with_precompute(\n        self, Xnew, full_cov: bool = False, full_output_cov: bool = False\n    ) -> MeanAndVariance:\n        \"\"\"\n        Computes predictive mean and (co)variance at Xnew, *excluding* mean_function.\n        Relies on cached alpha and Qinv.\n        \"\"\"\n        Kmn = self.kernel(self.X_data, Xnew)\n        Knn = self.kernel(Xnew, full_cov=full_cov)\n\n        return base_conditional_with_lm(Kmn, self.Qinv, Knn, self.alpha, full_cov=full_cov)\n\n    def _precompute(self) -> Tuple[tf.Tensor, tf.Tensor]:\n\n        \"\"\"\n        Precomputes the cholesky decomposition of Kmm_plus_s for later reuse we will call\n        base_conditional_with_lm implementation ('Qinv' in the Abstract Posterior class). We also\n        precompute the less compute intensive error term ('alpha' in the Abstract Posterior class)\n        \"\"\"\n\n        Kmm = self.kernel(self.X_data)\n        Kmm_plus_s = add_noise_cov(Kmm, self.likelihood_variance)\n\n        # obtain the cholesky decomposition of Kmm_plus_s\n        Lm = tf.linalg.cholesky(Kmm_plus_s)\n\n        alpha = self.Y_data - self.mean_function(self.X_data)  # type: ignore\n        tf.debugging.assert_shapes(\n            [\n                (Lm, [\"M\", \"M\"]),\n                (Kmm, [\"M\", \"M\"]),\n            ]\n        )\n        return alpha, Lm\n\n    def _conditional_fused(\n        self, Xnew, full_cov: bool = False, full_output_cov: bool = False\n    ) -> MeanAndVariance:\n        \"\"\"\n        Computes predictive mean and (co)variance at Xnew, *excluding* mean_function\n        Does not make use of caching\n        \"\"\"\n\n        # taken directly from the deprecated GPR implementation\n        err = self.Y_data - self.mean_function(self.X_data)  # type: ignore\n\n        Kmm = self.kernel(self.X_data)\n        Knn = self.kernel(Xnew, full_cov=full_cov)\n        Kmn = self.kernel(self.X_data, Xnew)\n        Kmm_plus_s = add_noise_cov(Kmm, self.likelihood_variance)\n\n        return base_conditional(\n            Kmn, Kmm_plus_s, Knn, err, full_cov=full_cov, white=False\n        )  # [N, P], [N, P] or [P, N, N]\n\n\nclass BasePosterior(AbstractPosterior):\n    def __init__(\n        self,\n        kernel,\n        inducing_variable,\n        q_mu: tf.Tensor,\n        q_sqrt: tf.Tensor,\n        whiten: bool = True,\n        mean_function: Optional[mean_functions.MeanFunction] = None,\n        *,\n        precompute_cache: Optional[PrecomputeCacheType],\n    ):\n\n        super().__init__(kernel, inducing_variable, mean_function=mean_function)\n        self.whiten = whiten\n        self._set_qdist(q_mu, q_sqrt)\n\n        if precompute_cache is not None:\n            self.update_cache(precompute_cache)\n\n    @property\n    def q_mu(self):\n        return self._q_dist.q_mu\n\n    @property\n    def q_sqrt(self):\n        return self._q_dist.q_sqrt\n\n    def _set_qdist(self, q_mu, q_sqrt):\n        if q_sqrt is None:\n            self._q_dist = _DeltaDist(q_mu)\n        elif len(q_sqrt.shape) == 2:  # q_diag\n            self._q_dist = _DiagNormal(q_mu, q_sqrt)\n        else:\n            self._q_dist = _MvNormal(q_mu, q_sqrt)\n\n    def _precompute(self):\n        Kuu = covariances.Kuu(self.X_data, self.kernel, jitter=default_jitter())  # [(R), M, M]\n        q_mu = self._q_dist.q_mu\n\n        if Kuu.shape.ndims == 4:\n            ML = tf.reduce_prod(tf.shape(Kuu)[:2])\n            Kuu = tf.reshape(Kuu, [ML, ML])\n        if Kuu.shape.ndims == 3:\n            q_mu = tf.linalg.adjoint(self._q_dist.q_mu)[..., None]  # [..., R, M, 1]\n        L = tf.linalg.cholesky(Kuu)\n\n        if not self.whiten:\n            # alpha = Kuu⁻¹ q_mu\n            alpha = tf.linalg.cholesky_solve(L, q_mu)\n        else:\n            # alpha = L⁻ᵀ q_mu\n            alpha = tf.linalg.triangular_solve(L, q_mu, adjoint=True)\n        # predictive mean = Kfu alpha\n        # predictive variance = Kff - Kfu Qinv Kuf\n        # S = q_sqrt q_sqrtᵀ\n        I = tf.eye(tf.shape(L)[-1], dtype=L.dtype)\n        if isinstance(self._q_dist, _DeltaDist):\n            B = I\n        else:\n            if not self.whiten:\n                # Qinv = Kuu⁻¹ - Kuu⁻¹ S Kuu⁻¹\n                #      = Kuu⁻¹ - L⁻ᵀ L⁻¹ S L⁻ᵀ L⁻¹\n                #      = L⁻ᵀ (I - L⁻¹ S L⁻ᵀ) L⁻¹\n                #      = L⁻ᵀ B L⁻¹\n                if isinstance(self._q_dist, _DiagNormal):\n                    q_sqrt = tf.linalg.diag(tf.linalg.adjoint(self._q_dist.q_sqrt))\n                elif isinstance(self._q_dist, _MvNormal):\n                    q_sqrt = self._q_dist.q_sqrt\n                Linv_qsqrt = tf.linalg.triangular_solve(L, q_sqrt)\n                Linv_cov_u_LinvT = tf.matmul(Linv_qsqrt, Linv_qsqrt, transpose_b=True)\n            else:\n                if isinstance(self._q_dist, _DiagNormal):\n                    Linv_cov_u_LinvT = tf.linalg.diag(tf.linalg.adjoint(self._q_dist.q_sqrt ** 2))\n                elif isinstance(self._q_dist, _MvNormal):\n                    q_sqrt = self._q_dist.q_sqrt\n                    Linv_cov_u_LinvT = tf.matmul(q_sqrt, q_sqrt, transpose_b=True)\n                # Qinv = Kuu⁻¹ - L⁻ᵀ S L⁻¹\n                # Linv = (L⁻¹ I) = solve(L, I)\n                # Kinv = Linvᵀ @ Linv\n            B = I - Linv_cov_u_LinvT\n        LinvT_B = tf.linalg.triangular_solve(L, B, adjoint=True)\n        B_Linv = tf.linalg.adjoint(LinvT_B)\n        Qinv = tf.linalg.triangular_solve(L, B_Linv, adjoint=True)\n\n        M, L = tf.unstack(tf.shape(self._q_dist.q_mu), num=2)\n        Qinv = tf.broadcast_to(Qinv, [L, M, M])\n\n        tf.debugging.assert_shapes(\n            [\n                (Qinv, [\"L\", \"M\", \"M\"]),\n            ]\n        )\n\n        return alpha, Qinv\n\n\nclass IndependentPosterior(BasePosterior):\n    def _post_process_mean_and_cov(self, mean, cov, full_cov, full_output_cov):\n        return mean, expand_independent_outputs(cov, full_cov, full_output_cov)\n\n    def _get_Kff(self, Xnew, full_cov):\n\n        # TODO: this assumes that Xnew has shape [N, D] and no leading dims\n\n        if isinstance(self.kernel, (kernels.SeparateIndependent, kernels.IndependentLatent)):\n            # NOTE calling kernel(Xnew, full_cov=full_cov, full_output_cov=False) directly would return\n            # if full_cov: [P, N, N] -- this is what we want\n            # else: [N, P] instead of [P, N] as we get from the explicit stack below\n            Kff = tf.stack([k(Xnew, full_cov=full_cov) for k in self.kernel.kernels], axis=0)\n        elif isinstance(self.kernel, kernels.MultioutputKernel):\n            # effectively, SharedIndependent path\n            Kff = self.kernel.kernel(Xnew, full_cov=full_cov)\n            # NOTE calling kernel(Xnew, full_cov=full_cov, full_output_cov=False) directly would return\n            # if full_cov: [P, N, N] instead of [N, N]\n            # else: [N, P] instead of [N]\n        else:\n            # standard (\"single-output\") kernels\n            Kff = self.kernel(Xnew, full_cov=full_cov)  # [N, N] if full_cov else [N]\n\n        return Kff\n\n    def _conditional_with_precompute(\n        self, Xnew, full_cov: bool = False, full_output_cov: bool = False\n    ) -> MeanAndVariance:\n        # Qinv: [L, M, M]\n        # alpha: [M, L]\n\n        Kuf = covariances.Kuf(self.X_data, self.kernel, Xnew)  # [(R), M, N]\n        Kff = self._get_Kff(Xnew, full_cov)\n\n        mean = tf.matmul(Kuf, self.alpha, transpose_a=True)\n        if Kuf.shape.ndims == 3:\n            mean = tf.linalg.adjoint(tf.squeeze(mean, axis=-1))\n\n        if full_cov:\n            Kfu_Qinv_Kuf = tf.matmul(Kuf, self.Qinv @ Kuf, transpose_a=True)\n            cov = Kff - Kfu_Qinv_Kuf\n        else:\n            # [Aᵀ B]_ij = Aᵀ_ik B_kj = A_ki B_kj\n            # TODO check whether einsum is faster now?\n            Kfu_Qinv_Kuf = tf.reduce_sum(Kuf * tf.matmul(self.Qinv, Kuf), axis=-2)\n            cov = Kff - Kfu_Qinv_Kuf\n            cov = tf.linalg.adjoint(cov)\n\n        return self._post_process_mean_and_cov(mean, cov, full_cov, full_output_cov)\n\n\nclass IndependentPosteriorSingleOutput(IndependentPosterior):\n    # could almost be the same as IndependentPosteriorMultiOutput ...\n    def _conditional_fused(\n        self, Xnew, full_cov: bool = False, full_output_cov: bool = False\n    ) -> MeanAndVariance:\n        # same as IndependentPosteriorMultiOutput, Shared~/Shared~ branch, except for following line:\n        Knn = self.kernel(Xnew, full_cov=full_cov)\n\n        Kmm = covariances.Kuu(self.X_data, self.kernel, jitter=default_jitter())  # [M, M]\n        Kmn = covariances.Kuf(self.X_data, self.kernel, Xnew)  # [M, N]\n\n        fmean, fvar = base_conditional(\n            Kmn, Kmm, Knn, self.q_mu, full_cov=full_cov, q_sqrt=self.q_sqrt, white=self.whiten\n        )  # [N, P],  [P, N, N] or [N, P]\n        return self._post_process_mean_and_cov(fmean, fvar, full_cov, full_output_cov)\n\n\nclass IndependentPosteriorMultiOutput(IndependentPosterior):\n    def _conditional_fused(\n        self, Xnew, full_cov: bool = False, full_output_cov: bool = False\n    ) -> MeanAndVariance:\n        if isinstance(self.X_data, SharedIndependentInducingVariables) and isinstance(\n            self.kernel, kernels.SharedIndependent\n        ):\n            # same as IndependentPosteriorSingleOutput except for following line\n            Knn = self.kernel.kernel(Xnew, full_cov=full_cov)\n            # we don't call self.kernel() directly as that would do unnecessary tiling\n\n            Kmm = covariances.Kuu(self.X_data, self.kernel, jitter=default_jitter())  # [M, M]\n            Kmn = covariances.Kuf(self.X_data, self.kernel, Xnew)  # [M, N]\n\n            fmean, fvar = base_conditional(\n                Kmn, Kmm, Knn, self.q_mu, full_cov=full_cov, q_sqrt=self.q_sqrt, white=self.whiten\n            )  # [N, P],  [P, N, N] or [N, P]\n        else:\n            # this is the messy thing with tf.map_fn, cleaned up by the st/clean_up_broadcasting_conditionals branch\n\n            # Following are: [P, M, M]  -  [P, M, N]  -  [P, N](x N)\n            Kmms = covariances.Kuu(self.X_data, self.kernel, jitter=default_jitter())  # [P, M, M]\n            Kmns = covariances.Kuf(self.X_data, self.kernel, Xnew)  # [P, M, N]\n            if isinstance(self.kernel, kernels.Combination):\n                kernel_list = self.kernel.kernels\n            else:\n                kernel_list = [self.kernel.kernel] * len(self.X_data.inducing_variable_list)\n            Knns = tf.stack(\n                [k.K(Xnew) if full_cov else k.K_diag(Xnew) for k in kernel_list], axis=0\n            )\n\n            fmean, fvar = separate_independent_conditional_implementation(\n                Kmns,\n                Kmms,\n                Knns,\n                self.q_mu,\n                q_sqrt=self.q_sqrt,\n                full_cov=full_cov,\n                white=self.whiten,\n            )\n\n        return self._post_process_mean_and_cov(fmean, fvar, full_cov, full_output_cov)\n\n\nclass LinearCoregionalizationPosterior(IndependentPosteriorMultiOutput):\n    def _post_process_mean_and_cov(self, mean, cov, full_cov, full_output_cov):\n        \"\"\"\n        mean: [N, L]\n        cov: [L, N, N] or [N, L]\n        \"\"\"\n        cov = expand_independent_outputs(cov, full_cov, full_output_cov=False)\n        mean, cov = mix_latent_gp(self.kernel.W, mean, cov, full_cov, full_output_cov)\n        return mean, cov\n\n\nclass FullyCorrelatedPosterior(BasePosterior):\n    def _conditional_with_precompute(\n        self, Xnew, full_cov: bool = False, full_output_cov: bool = False\n    ) -> MeanAndVariance:\n        # TODO: this assumes that Xnew has shape [N, D] and no leading dims\n\n        # Qinv: [L, M, M]\n        # alpha: [M, L]\n\n        Kuf = covariances.Kuf(self.X_data, self.kernel, Xnew)\n        assert Kuf.shape.ndims == 4\n        M, L, N, K = tf.unstack(tf.shape(Kuf), num=Kuf.shape.ndims, axis=0)\n        Kuf = tf.reshape(Kuf, (M * L, N * K))\n\n        Kff = self.kernel(Xnew, full_cov=full_cov, full_output_cov=full_output_cov)\n        # full_cov=True and full_output_cov=True: [N, P, N, P]\n        # full_cov=True and full_output_cov=False: [P, N, N]\n        # full_cov=False and full_output_cov=True: [N, P, P]\n        # full_cov=False and full_output_cov=False: [N, P]\n        if full_cov == full_output_cov:\n            new_shape = (N * K, N * K) if full_cov else (N * K,)\n            Kff = tf.reshape(Kff, new_shape)\n\n        N = tf.shape(Xnew)[0]\n        K = tf.shape(Kuf)[-1] // N\n\n        mean = tf.matmul(Kuf, self.alpha, transpose_a=True)\n        if Kuf.shape.ndims == 3:\n            mean = tf.linalg.adjoint(tf.squeeze(mean, axis=-1))\n\n        if not full_cov and not full_output_cov:\n            # fully diagonal case in both inputs and outputs\n            # [Aᵀ B]_ij = Aᵀ_ik B_kj = A_ki B_kj\n            # TODO check whether einsum is faster now?\n            Kfu_Qinv_Kuf = tf.reduce_sum(Kuf * tf.matmul(self.Qinv, Kuf), axis=-2)\n        else:\n            Kfu_Qinv_Kuf = tf.matmul(Kuf, self.Qinv @ Kuf, transpose_a=True)\n            if not (full_cov and full_output_cov):\n                # diagonal in either inputs or outputs\n                new_shape = tf.concat([tf.shape(Kfu_Qinv_Kuf)[:-2], (N, K, N, K)], axis=0)\n                Kfu_Qinv_Kuf = tf.reshape(Kfu_Qinv_Kuf, new_shape)\n                if full_cov:\n                    # diagonal in outputs: move outputs to end\n                    tmp = tf.linalg.diag_part(tf.einsum(\"...ijkl->...ikjl\", Kfu_Qinv_Kuf))\n                elif full_output_cov:\n                    # diagonal in inputs: move inputs to end\n                    tmp = tf.linalg.diag_part(tf.einsum(\"...ijkl->...jlik\", Kfu_Qinv_Kuf))\n                Kfu_Qinv_Kuf = tf.einsum(\"...ijk->...kij\", tmp)  # move diagonal dim to [-3]\n        cov = Kff - Kfu_Qinv_Kuf\n\n        if not full_cov and not full_output_cov:\n            cov = tf.linalg.adjoint(cov)\n\n        mean = tf.reshape(mean, (N, K))\n        if full_cov == full_output_cov:\n            cov_shape = (N, K, N, K) if full_cov else (N, K)\n        else:\n            cov_shape = (K, N, N) if full_cov else (N, K, K)\n        cov = tf.reshape(cov, cov_shape)\n\n        return mean, cov\n\n    def _conditional_fused(\n        self, Xnew, full_cov: bool = False, full_output_cov: bool = False\n    ) -> MeanAndVariance:\n        Kmm = covariances.Kuu(self.X_data, self.kernel, jitter=default_jitter())  # [M, L, M, L]\n        Kmn = covariances.Kuf(self.X_data, self.kernel, Xnew)  # [M, L, N, P]\n        Knn = self.kernel(\n            Xnew, full_cov=full_cov, full_output_cov=full_output_cov\n        )  # [N, P](x N)x P  or  [N, P](x P)\n\n        M, L, N, K = tf.unstack(tf.shape(Kmn), num=Kmn.shape.ndims, axis=0)\n        Kmm = tf.reshape(Kmm, (M * L, M * L))\n\n        if full_cov == full_output_cov:\n            Kmn = tf.reshape(Kmn, (M * L, N * K))\n            Knn = tf.reshape(Knn, (N * K, N * K)) if full_cov else tf.reshape(Knn, (N * K,))\n            mean, cov = base_conditional(\n                Kmn, Kmm, Knn, self.q_mu, full_cov=full_cov, q_sqrt=self.q_sqrt, white=self.whiten\n            )  # [K, 1], [1, K](x NK)\n            mean = tf.reshape(mean, (N, K))\n            cov = tf.reshape(cov, (N, K, N, K) if full_cov else (N, K))\n        else:\n            Kmn = tf.reshape(Kmn, (M * L, N, K))\n            mean, cov = fully_correlated_conditional(\n                Kmn,\n                Kmm,\n                Knn,\n                self.q_mu,\n                full_cov=full_cov,\n                full_output_cov=full_output_cov,\n                q_sqrt=self.q_sqrt,\n                white=self.whiten,\n            )\n        return mean, cov\n\n\nclass FallbackIndependentLatentPosterior(FullyCorrelatedPosterior):  # XXX\n    def _conditional_fused(\n        self, Xnew, full_cov: bool = False, full_output_cov: bool = False\n    ) -> MeanAndVariance:\n        Kmm = covariances.Kuu(self.X_data, self.kernel, jitter=default_jitter())  # [L, M, M]\n        Kmn = covariances.Kuf(self.X_data, self.kernel, Xnew)  # [M, L, N, P]\n        Knn = self.kernel(\n            Xnew, full_cov=full_cov, full_output_cov=full_output_cov\n        )  # [N, P](x N)x P  or  [N, P](x P)\n\n        return independent_interdomain_conditional(\n            Kmn,\n            Kmm,\n            Knn,\n            self.q_mu,\n            full_cov=full_cov,\n            full_output_cov=full_output_cov,\n            q_sqrt=self.q_sqrt,\n            white=self.whiten,\n        )\n\n\nget_posterior_class = Dispatcher(\"get_posterior_class\")\n\n\n@get_posterior_class.register(kernels.Kernel, InducingVariables)\ndef _get_posterior_base_case(kernel, inducing_variable):\n    # independent single output\n    return IndependentPosteriorSingleOutput\n\n\n@get_posterior_class.register(kernels.MultioutputKernel, InducingPoints)\ndef _get_posterior_fully_correlated_mo(kernel, inducing_variable):\n    return FullyCorrelatedPosterior\n\n\n@get_posterior_class.register(\n    (kernels.SharedIndependent, kernels.SeparateIndependent),\n    (SeparateIndependentInducingVariables, SharedIndependentInducingVariables),\n)\ndef _get_posterior_independent_mo(kernel, inducing_variable):\n    # independent multi-output\n    return IndependentPosteriorMultiOutput\n\n\n@get_posterior_class.register(\n    kernels.IndependentLatent,\n    (FallbackSeparateIndependentInducingVariables, FallbackSharedIndependentInducingVariables),\n)\ndef _get_posterior_independentlatent_mo_fallback(kernel, inducing_variable):\n    return FallbackIndependentLatentPosterior\n\n\n@get_posterior_class.register(\n    kernels.LinearCoregionalization,\n    (SeparateIndependentInducingVariables, SharedIndependentInducingVariables),\n)\ndef _get_posterior_linearcoregionalization_mo_efficient(kernel, inducing_variable):\n    # Linear mixing---efficient multi-output\n    return LinearCoregionalizationPosterior\n\n\ndef create_posterior(\n    kernel,\n    inducing_variable,\n    q_mu,\n    q_sqrt,\n    whiten,\n    mean_function=None,\n    precompute_cache: Union[PrecomputeCacheType, str, None] = PrecomputeCacheType.TENSOR,\n):\n    posterior_class = get_posterior_class(kernel, inducing_variable)\n    precompute_cache = _validate_precompute_cache_type(precompute_cache)\n    return posterior_class(\n        kernel,\n        inducing_variable,\n        q_mu,\n        q_sqrt,\n        whiten,\n        mean_function,\n        precompute_cache=precompute_cache,\n    )\n", "meta": {"hexsha": "0ecf38f201b3a8b51ea851c5ecb5c5bae74582b5", "size": 26442, "ext": "py", "lang": "Python", "max_stars_repo_path": "gpflow/posteriors.py", "max_stars_repo_name": "HarrySpearing/GPflow", "max_stars_repo_head_hexsha": "02cd9000f72f4302f24a9fa1b28237f86140e04e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gpflow/posteriors.py", "max_issues_repo_name": "HarrySpearing/GPflow", "max_issues_repo_head_hexsha": "02cd9000f72f4302f24a9fa1b28237f86140e04e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gpflow/posteriors.py", "max_forks_repo_name": "HarrySpearing/GPflow", "max_forks_repo_head_hexsha": "02cd9000f72f4302f24a9fa1b28237f86140e04e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0460431655, "max_line_length": 116, "alphanum_fraction": 0.6252174571, "include": true, "reason": "import numpy", "num_tokens": 6781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3007455789412415, "lm_q1q2_score": 0.16675454099034306}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"This file is used for generator training under reinforcement learning framework.\n\nIt is implemented by integrating exploration strategy into REINFORCE algorithm.\nThe deep learning code is implemented by PyTorch ( >= version 1.0)\n\"\"\"\n\nimport os\n\nimport click\nimport numpy as np\nimport torch\nfrom rdkit import rdBase\nfrom torch.utils.data import DataLoader, TensorDataset\nfrom tqdm import trange\n\nfrom drugex import model, util\n\n\ndef policy_gradient(agent, environ, explore=None, *, batch_size, mc, epsilon, baseline):\n    \"\"\"Training generator under reinforcement learning framework,\n    The rewoard is only the final reward given by environment (predictor).\n\n    agent (model.Generator): the exploitation network for SMILES string generation\n    environ (util.Activity): the environment provide the final reward for each SMILES\n    explore (model.Generator): the exploration network for SMILES string generation,\n        it has the same architecture with the agent.\n    \"\"\"\n    seqs = []\n\n    # repeated sampling with MC times\n    for _ in range(mc):\n        seq = agent.sample(batch_size, explore=explore, epsilon=epsilon)\n        seqs.append(seq)\n    seqs = torch.cat(seqs, dim=0)\n    ix = util.unique(seqs)\n    seqs = seqs[ix]\n    smiles, valids = util.check_smiles(seqs, agent.voc)\n\n    # obtaining the reward\n    preds = environ(smiles)\n    preds[valids == False] = 0\n    preds -= baseline\n    preds = torch.Tensor(preds.reshape(-1, 1)).to(util.dev)\n\n    ds = TensorDataset(seqs, preds)\n    loader = DataLoader(ds, batch_size=batch_size)\n\n    # Training Loop\n    for seq, pred in loader:\n        score = agent.likelihood(seq)\n        agent.optim.zero_grad()\n        loss = agent.PGLoss(score, pred)\n        loss.backward()\n        agent.optim.step()\n\n\ndef rollout_pg(agent, environ, explore=None, *, batch_size, baseline, mc, epsilon):\n    \"\"\"Training generator under reinforcement learning framework.\n\n    The reward is given for each token in the SMILES, which is generated by\n    Monte Carlo Tree Search based on final reward given by the environment.\n\n    Arguments:\n\n        agent (model.Generator): the exploitation network for SMILES string generation\n        environ (util.Activity): the environment provide the final reward for each SMILES\n        explore (model.Generator): the exploration network for SMILES string generation,\n            it has the same architecture with the agent.\n    \"\"\"\n\n    agent.optim.zero_grad()\n    seqs = agent.sample(batch_size, explore=explore, epsilon=epsilon)\n    batch_size = seqs.size(0)\n    seq_len = seqs.size(1)\n    rewards = np.zeros((batch_size, seq_len))\n    smiles, valids = util.check_smiles(seqs, agent.voc)\n    preds = environ(smiles) - baseline\n    preds[valids == False] = - baseline\n    scores, hiddens = agent.likelihood(seqs)\n\n    # Monte Carlo Tree Search for step rewards generation\n    for _ in trange(mc):\n        for i in range(seq_len):\n            if (seqs[:, i] != 0).any():\n                h = hiddens[:, :, i, :]\n                subseqs = agent.sample(batch_size, inits=(seqs[:, i], h, i + 1, None))\n                subseqs = torch.cat([seqs[:, :i+1], subseqs], dim=1)\n                subsmile, subvalid = util.check_smiles(subseqs, voc=agent.voc)\n                subpred = environ(subsmile) - baseline\n                subpred[1 - subvalid] = -baseline\n            else:\n                subpred = preds\n            rewards[:, i] += subpred\n    loss = agent.PGLoss(scores, seqs, torch.FloatTensor(rewards / mc))\n    loss.backward()\n    agent.optim.step()\n    return 0, valids.mean(), smiles, preds\n\n\ndef _main_helper(*, epsilon, baseline, batch_size, mc, vocabulary_path, output_dir):\n    #: Vocabulary containing all of the tokens for SMILES construction\n    voc = util.Voc(vocabulary_path)\n    #: File path of predictor in the environment\n    environ_path = os.path.join(output_dir, 'RF_cls_ecfp6.pkg')\n    #: file path of hidden states in RNN for initialization\n    initial_path = os.path.join(output_dir, 'net_p.pkg')\n    #: file path of hidden states of optimal exploitation network\n    agent_path = os.path.join(output_dir, 'net_e_%.2f_%.1f_%dx%d' % (epsilon, baseline, batch_size, mc))\n    #: file path of hidden states of exploration network\n    explore_path = os.path.join(output_dir, 'net_p.pkg')\n\n    # Environment (predictor)\n    environ = util.Environment(environ_path)\n    # Agent (generator, exploitation network)\n    agent = model.Generator(voc)\n    agent.load_state_dict(torch.load(initial_path))\n\n    # exploration network\n    explore = model.Generator(voc)\n    explore.load_state_dict(torch.load(explore_path))\n\n    best_score = 0\n    log_file = open(agent_path + '.log', 'w')\n\n    it = trange(1000)\n    for epoch in it:\n        it.write('\\n--------\\nEPOCH %d\\n--------' % (epoch + 1))\n        it.write('\\nForward Policy Gradient Training Generator : ')\n        policy_gradient(agent, environ, explore=explore,\n                        baseline=baseline, batch_size=batch_size, mc=mc, epsilon=epsilon)\n        seqs = agent.sample(1000)\n        ix = util.unique(seqs)\n        smiles, valids = util.check_smiles(seqs[ix], agent.voc)\n        scores = environ(smiles)\n        scores[valids == False] = 0\n        unique = (scores >= 0.5).sum() / 1000\n        # The model with best percentage of unique desired SMILES will be persisted on the hard drive.\n        if best_score < unique:\n            torch.save(agent.state_dict(), agent_path + '.pkg')\n            best_score = unique\n        print(\"Epoch+: %d average: %.4f valid: %.4f unique: %.4f\" % (epoch, scores.mean(), valids.mean(), unique), file=log_file)\n        for i, smile in enumerate(smiles):\n            print('%f\\t%s' % (scores[i], smile), file=log_file)\n\n        # Learing rate exponential decay\n        for param_group in agent.optim.param_groups:\n            param_group['lr'] *= (1 - 0.01)\n    log_file.close()\n\n\n@click.command()\n@click.option('-d', '--input-directory', type=click.Path(file_okay=False, dir_okay=True), show_default=True)\n@click.option('-o', '--output-directory', type=click.Path(file_okay=False, dir_okay=True), show_default=True)\n@click.option('--mc', type=int, default=10, show_default=True)\n@click.option('--batch-size', type=int, default=500, show_default=True)\n@click.option('--num-threads', type=int, default=1, show_default=True)\n@click.option('-e', '--epsilon', type=float, default=0.1, show_default=True)\n@click.option('-b', '--baseline', type=float, default=0.1, show_default=True)\n@click.option('-g', '--cuda-visible-devices')\ndef main(input_directory, output_directory, mc, batch_size, num_threads, epsilon, baseline, cuda_visible_devices):\n    rdBase.DisableLog('rdApp.error')\n    torch.set_num_threads(num_threads)\n    if cuda_visible_devices:\n        os.environ[\"CUDA_VISIBLE_DEVICES\"] = cuda_visible_devices\n    _main_helper(\n        baseline=baseline,\n        batch_size=batch_size,\n        mc=mc,\n        epsilon=epsilon,\n        vocabulary_path=os.path.join(input_directory, \"voc.txt\"),\n        output_dir=output_directory,\n    )\n\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "aee5ba2a06b406057f1641b19625ffea21260180", "size": 7111, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/drugex/agent.py", "max_stars_repo_name": "cthoyt/DrugEx", "max_stars_repo_head_hexsha": "9e4d31adb2c65d0afc852948f502c79dcf8308a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/drugex/agent.py", "max_issues_repo_name": "cthoyt/DrugEx", "max_issues_repo_head_hexsha": "9e4d31adb2c65d0afc852948f502c79dcf8308a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/drugex/agent.py", "max_forks_repo_name": "cthoyt/DrugEx", "max_forks_repo_head_hexsha": "9e4d31adb2c65d0afc852948f502c79dcf8308a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5055555556, "max_line_length": 129, "alphanum_fraction": 0.6681198144, "include": true, "reason": "import numpy", "num_tokens": 1709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.32082131381216084, "lm_q1q2_score": 0.16667351306210107}}
{"text": "# Derive optimal tolerance by ESM-SSP and  well-characterized errors\n# for an audience seeking to emulate from the full CMIP6 archive,\n# for a selection of ESMs.\n\n# For each ESM, loop over various tolerances and generate Ndraws = 500\n# GSAT trajectories. Archives with and without each target to characterize\n# error. (Reproducible mode off so draws are different).\n# Compare to the target ensemble via 4 metrics (E1, E2 on both Tgavs and\n# jumps) to select the optimal tol for each ESM-SSP-archive combo.\n# Use the resultant optimal tol for a final, reproducible mode set of recipes,\n# Tgavs, and gridded data sets of monthly + daily for ??? variables.\n# Start with tas, pr, psl - must subset archive up front to only include\n# ensemble members that have all of these files available.\n# look at CanESM5, MIROC6 and ACCESS-ESM1-5\n\n## TODO functionalize at least some part of the analysis or at least use a for-loop\n## over the different SSP targets so that the code isn't so long and repetitive\n# making a table of avail runs X planned archives and for looping over that would\n# trim things down (see approach for max tol runs). And rewrite the tolerance\n# iteration to be a while loop, comparing current to prev instead of calculating\n# and saving it all? Update writes and reads to be subdir so things are tidier\n\n# would be better to functionalize this script with ESM, tol and Ndraws as arguments\n# and then have the .sh just call the function and dispatch to diff nodes for each run I guess.\n\n# #############################################################################\n# General setup\n# #############################################################################\n# Import packages\nimport pandas as pd\nimport numpy as np\nimport stitches as stitches\nimport pkg_resources\nimport os\nfrom  pathlib import Path\n\npd.set_option('display.max_columns', None)\n\nOUTPUT_DIR = pkg_resources.resource_filename('stitches', 'data/created_data')\n# OUTPUT_DIR = '/pic/projects/GCAM/stitches_pic/paper1_outputs'\n\n# #############################################################################\n# Experiment  setup\n# #############################################################################\n# experiment parameters\ntolerances = np.round(np.arange(0.07, 0.225, 0.005), 3)\nNdraws = 10\nerror_threshold = 0.1\n\n# pangeo table of ESMs for reference\npangeo_path = pkg_resources.resource_filename('stitches', 'data/pangeo_table.csv')\npangeo_data = pd.read_csv(pangeo_path)\npangeo_data = pangeo_data[((pangeo_data['variable'] == 'tas') | (pangeo_data['variable'] == 'pr') | (pangeo_data['variable'] == 'psl'))\n                          & ((pangeo_data['domain'] == 'Amon') | (pangeo_data['domain'] == 'day')) ].copy()\n\n# Keep only the runs that have data for all vars X all timesteps:\npangeo_good_ensembles =[]\nfor name, group in pangeo_data.groupby(['model', 'experiment', 'ensemble']):\n    df = group.drop_duplicates().copy()\n    if len(df) == 6:\n        pangeo_good_ensembles.append(df)\n    del(df)\npangeo_good_ensembles = pd.concat(pangeo_good_ensembles)\npangeo_good_ensembles  = pangeo_good_ensembles[['model', 'experiment', 'ensemble']].drop_duplicates().copy()\npangeo_good_ensembles = pangeo_good_ensembles.reset_index(drop=True).copy()\n\n# won't use idealized runs\npangeo_good_ensembles = pangeo_good_ensembles[~((pangeo_good_ensembles['experiment'] == '1pctCO2') |\n                                                (pangeo_good_ensembles['experiment'] == 'abrupt-4xCO2')) ].reset_index(drop=True).copy()\n\nesms = ['ACCESS-ESM1-5', 'CanESM5', 'MIROC6']\n# ['ACCESS-CM2', 'ACCESS-ESM1-5', 'AWI-CM-1-1-MR', 'BCC-CSM2-MR',\n#        'BCC-ESM1', 'CESM2', 'CESM2-FV2', 'CESM2-WACCM', 'CMCC-CM2-HR4',\n#        'CMCC-CM2-SR5', 'CMCC-ESM2', 'CanESM5', 'HadGEM3-GC31-LL',\n#        'HadGEM3-GC31-MM', 'IITM-ESM', 'MIROC-ES2L', 'MIROC6',\n#        'MPI-ESM-1-2-HAM', 'MPI-ESM1-2-HR', 'MPI-ESM1-2-LR', 'MRI-ESM2-0',\n#        'NorESM2-LM', 'NorESM2-MM', 'SAM0-UNICON', 'TaiESM1',\n#        'UKESM1-0-LL']\n\n\n# #############################################################################\n# Load full archive and target data\n# #############################################################################\n\n# Load the full archive of all staggered windows, which we will be matching on\nfull_archive_path = pkg_resources.resource_filename('stitches', 'data/matching_archive.csv')\nfull_archive_data = pd.read_csv(full_archive_path)\n\n# Keep only the entries that appeared in pangeo_good_ensembles:\nkeys =['model', 'experiment', 'ensemble']\ni1 = full_archive_data.set_index(keys).index\ni2 = pangeo_good_ensembles.set_index(keys).index\nfull_archive_data= full_archive_data[i1.isin(i2)].copy()\ndel(i1)\ndel(i2)\n\n# Load the original archive without staggered windows, which we will draw\n# the target trajectories from for matching\nfull_target_path = pkg_resources.resource_filename('stitches', 'data/matching_archive.csv')\nfull_target_data = pd.read_csv(full_target_path)\n\n# Keep only the entries that appeared in pangeo_good_ensembles:\nkeys =['model', 'experiment', 'ensemble']\ni1 = full_target_data.set_index(keys).index\ni2 = pangeo_good_ensembles.set_index(keys).index\nfull_target_data = full_target_data[i1.isin(i2)].copy()\ndel(i1)\ndel(i2)\ndel(keys)\n\n# #############################################################################\n# Some helper functions\n# #############################################################################\ndef prep_target_data(target_df):\n    if not target_df.empty:\n        grped = target_df.groupby(['experiment', 'variable', 'ensemble', 'model'])\n        for name, group in grped:\n            df1 = group.copy()\n            # if it isn't a complete time series (defined as going to 2099 or 2100),\n            # remove it from the target data frame:\n            if max(df1.end_yr) < 2099:\n                target_df = target_df.loc[(target_df['ensemble'] != df1.ensemble.unique()[0])].copy().reset_index(\n                    drop=True)\n            del (df1)\n        del (grped)\n\n        target_df = target_df.reset_index(drop=True).copy()\n        return(target_df)\n\n\ndef get_orig_data(target_df):\n    if not target_df.empty:\n        esm_name = target_df.model.unique()[0]\n        scn_name = target_df.experiment.unique()[0]\n\n        full_rawtarget_path = pkg_resources.resource_filename('stitches', ('data/tas-data/' + esm_name + '_tas.csv'))\n        full_rawtarget_data = pd.read_csv(full_rawtarget_path)\n\n        orig_data = full_rawtarget_data[(full_rawtarget_data['experiment'] == scn_name)].copy()\n        keys = ['experiment', 'ensemble', 'model']\n        i1 = orig_data.set_index(keys).index\n        i2 = target_df.set_index(keys).index\n        orig_data = orig_data[i1.isin(i2)].copy()\n        del (i1)\n        del (i2)\n        del (keys)\n        del (full_rawtarget_data)\n        del (full_rawtarget_path)\n\n        orig_data = orig_data.reset_index(drop=True).copy()\n        return (orig_data)\n\n\ndef match_draw_stitchTgav(target_df, archive_df, toler, num_draws, TGAV_OUTPUT_DIR, reproducible):\n\n    esm_name = archive_df.model.unique()[0]\n\n    if not target_df.empty:\n        # Use the match_neighborhood function to generate all of the matches between the target and\n        # archive data points.\n        match_df = stitches.match_neighborhood(target_df, archive_df, tol=toler)\n\n\n        if target_df.experiment.unique() in archive_df.experiment.unique():\n            archive_id = 'w_target'\n        else:\n            archive_id = 'wo_target'\n\n        scn_name = target_df.experiment.unique()[0]\n\n\n        for draw in range(0, num_draws):\n            # Do the random draw of recipes\n            if reproducible:\n                unformatted_recipe = stitches.permute_stitching_recipes(N_matches=10000,\n                                                                        matched_data=match_df,\n                                                                        archive=archive_df,\n                                                                        testing=True)\n            else:\n                unformatted_recipe = stitches.permute_stitching_recipes(N_matches=10000,\n                                                                        matched_data=match_df,\n                                                                        archive=archive_df,\n                                                                        testing=False)\n\n\n            new_ids = ('tol' + str(toler) + '~draw' + str(draw) + '~' + archive_id + '~'+\n                       unformatted_recipe['stitching_id'].astype(str)).copy()\n            unformatted_recipe = unformatted_recipe.drop(columns=['stitching_id']).copy()\n            unformatted_recipe['stitching_id'] = new_ids\n            del (new_ids)\n\n            # format the recipe\n            recipe = stitches.generate_gridded_recipe(unformatted_recipe)\n            recipe.columns = ['target_start_yr', 'target_end_yr', 'archive_experiment', 'archive_variable',\n                              'archive_model', 'archive_ensemble', 'stitching_id', 'archive_start_yr',\n                              'archive_end_yr', 'tas_file']\n            recipe['tolerance'] = toler\n            recipe['draw'] = draw\n            recipe['archive'] = archive_id\n            recipe.to_csv((OUTPUT_DIR + '/' + esm_name + '/experiment_CMIP6/' +\n                           'gridded_recipes_' + esm_name + '_target_' + scn_name +\n                           '_tol' + str(toler) +\n                           '_draw' + str(draw) +\n                           '_archive_' + archive_id + '.csv'), index=False)\n            del (unformatted_recipe)\n\n            # stitch the GSAT values and save as csv\n            try:\n\n                gsat = stitches.gmat_stitching(recipe)\n                gsat['tolerance'] = toler\n                gsat['draw'] = draw\n                gsat['archive'] = archive_id\n                for id in gsat.stitching_id.unique():\n                    ds = gsat[gsat['stitching_id'] == id].copy()\n                    fname = (TGAV_OUTPUT_DIR +\n                             'stitched_' + esm_name + '_GSAT_' + id + '.csv')\n                    ds.to_csv(fname, index=False)\n                    del (ds)\n\n                del (gsat)\n\n            except:\n                print((\"Some issue stitching GMAT for \" + esm_name + \". Skipping and moving on\"))\n\n    else:\n        recipe = []\n        print('Some missing target data for ' + esm_name + '. Analysis will be skipped')\n\n    return(recipe)\n\n\ndef get_jumps(tgav_df):\n    tgav_jump = []\n    for name, group in tgav_df.groupby(['variable', 'experiment', 'ensemble', 'model']):\n        ds = group.copy()\n        ds['jump'] = ds.value.diff().copy()\n        ds = ds.dropna().copy()\n        tgav_jump.append(ds)\n        del (ds)\n    tgav_jump = pd.concat(tgav_jump)\n    tgav_jump = tgav_jump.drop(columns=['value']).copy()\n    tgav_jump = tgav_jump.drop_duplicates().reset_index(drop=True).copy()\n    return(tgav_jump)\n\ndef four_errors(gen_data, orig_data):\n    gen_data_jump = get_jumps(gen_data)\n    orig_data_jump = get_jumps(orig_data)\n\n    orig_stats = []\n    for name, group in orig_data.groupby(['model', 'variable', 'experiment']):\n        ds = group.copy()\n        ds1 = ds[['model', 'variable', 'experiment']].drop_duplicates().copy()\n        ds1['mean_orig_tgav'] = np.mean(ds.value.values)\n        ds1['sd_orig_tgav'] = np.std(ds.value.values)\n        orig_stats.append(ds1)\n        del (ds)\n        del (ds1)\n    orig_stats = pd.concat(orig_stats).reset_index(drop=True).copy()\n\n    orig_stats_jump = []\n    for name, group in orig_data_jump.groupby(['model', 'variable', 'experiment']):\n        ds = group.copy()\n        ds1 = ds[['model', 'variable', 'experiment']].drop_duplicates().copy()\n        ds1['mean_orig_jump'] = np.mean(ds.jump.values)\n        ds1['sd_orig_jump'] = np.std(ds.jump.values)\n        orig_stats_jump.append(ds1)\n        del (ds)\n        del (ds1)\n    orig_stats_jump = pd.concat(orig_stats_jump).reset_index(drop=True).copy()\n\n    orig_stats = orig_stats.merge(orig_stats_jump, how='left', on=['model', 'variable', 'experiment']).copy()\n    del (orig_stats_jump)\n\n    gen_stats = []\n    for name, group in gen_data.groupby(['model', 'variable', 'experiment', 'tolerance', 'draw', 'archive']):\n        ds = group.copy()\n        ds1 = ds[['model', 'variable', 'experiment', 'tolerance', 'draw', 'archive']].drop_duplicates().copy()\n        ds1['mean_gen_tgav'] = np.mean(ds.value.values)\n        ds1['sd_gen_tgav'] = np.std(ds.value.values)\n        gen_stats.append(ds1)\n        del (ds)\n        del (ds1)\n    gen_stats = pd.concat(gen_stats).reset_index(drop=True).copy()\n\n    gen_stats_jump = []\n    for name, group in gen_data_jump.groupby(['model', 'variable', 'experiment', 'tolerance', 'draw', 'archive']):\n        ds = group.copy()\n        ds1 = ds[['model', 'variable', 'experiment', 'tolerance', 'draw', 'archive']].drop_duplicates().copy()\n        ds1['mean_gen_jump'] = np.mean(ds.jump.values)\n        ds1['sd_gen_jump'] = np.std(ds.jump.values)\n        gen_stats_jump.append(ds1)\n        del (ds)\n        del (ds1)\n    gen_stats_jump = pd.concat(gen_stats_jump).reset_index(drop=True).copy()\n\n    gen_stats = gen_stats.merge(gen_stats_jump, how='left',\n                                on=['model', 'variable', 'experiment', 'tolerance', 'draw', 'archive']).copy()\n    del (gen_stats_jump)\n\n    compare = gen_stats.merge(orig_stats, how='left', on=['model', 'variable', 'experiment']).copy()\n    del (gen_stats)\n    del (orig_stats)\n\n    compare['E1_tgav'] = abs(compare.mean_orig_tgav - compare.mean_gen_tgav) / compare.sd_orig_tgav\n    compare['E2_tgav'] = compare.sd_gen_tgav / compare.sd_orig_tgav\n\n    compare['E1_jump'] = abs(compare.mean_orig_jump - compare.mean_gen_jump) / compare.sd_orig_jump\n    compare['E2_jump'] = compare.sd_gen_jump / compare.sd_orig_jump\n\n    compare = compare[['model', 'variable', 'experiment', 'tolerance', 'draw', 'archive',\n                       'E1_tgav', 'E2_tgav', 'E1_jump', 'E2_jump']].copy()\n\n    four_values = []\n    for name, group in compare.groupby(['model', 'variable', 'experiment', 'tolerance', 'draw', 'archive']):\n        ds = group.copy()\n        ds['max_metric'] = np.max(\n            [ds.E1_tgav.values, abs(1 - ds.E2_tgav.values), ds.E1_jump.values, abs(1 - ds.E2_jump.values)])\n        four_values.append(ds)\n        del (ds)\n    four_values = pd.concat(four_values).reset_index(drop=True).copy()\n    del (compare)\n\n    return(four_values)\n\n\n# #############################################################################\n# The experiment\n# #############################################################################\n\n# for each of the esms in the experiment, subset to what we want\n# to work with and run the experiment.\nfor esm in esms:\n    print(esm)\n\n    # subset the archive and the targets to this ESM\n    archive_w_all = full_archive_data[(full_archive_data['model'] == esm)].copy()\n\n    archive_wo245 = full_archive_data[(full_archive_data['model'] == esm) &\n                                      (full_archive_data['experiment'] != 'ssp245')].copy()\n\n    archive_wo370 = full_archive_data[(full_archive_data['model'] == esm) &\n                                      (full_archive_data['experiment'] != 'ssp370')].copy()\n\n\n    target_245 = full_target_data[(full_target_data['model'] == esm) &\n                                  (full_target_data['experiment'] == 'ssp245')].copy()\n\n    target_370 = full_target_data[(full_target_data['model'] == esm) &\n                                  (full_target_data['experiment'] == 'ssp370')].copy()\n\n\n    # Clean up target data and pull corresponding original/raw data\n    if not target_245.empty:\n        # clean up\n        target_245 = prep_target_data(target_245).copy()\n\n        # and pull corresponding original/raw data for later comparison\n        orig_245 = get_orig_data(target_245).copy()\n\n\n    if not target_370.empty:\n        # clean up\n        target_370 = prep_target_data(target_370).copy()\n\n        # and pull corresponding original/raw data for later comparison\n        orig_370 = get_orig_data(target_370).copy()\n\n\n\n    # loop over tolerances:\n    for tolerance in tolerances:\n\n        rp_245_w = match_draw_stitchTgav(target_245, archive_w_all,\n                                         toler=tolerance, num_draws=Ndraws,\n                                         TGAV_OUTPUT_DIR=(OUTPUT_DIR + '/' + esm + '/experiment_CMIP6/tolerance-generated-tgavs/' ),\n                                         reproducible=False)\n        rp_245_wo = match_draw_stitchTgav(target_245, archive_wo245,\n                                         toler=tolerance, num_draws=Ndraws,\n                                         TGAV_OUTPUT_DIR=(OUTPUT_DIR + '/' + esm + '/experiment_CMIP6/tolerance-generated-tgavs/' ),\n                                         reproducible=False)\n        rp_370_w = match_draw_stitchTgav(target_370, archive_w_all,\n                                         toler=tolerance, num_draws=Ndraws,\n                                         TGAV_OUTPUT_DIR=(OUTPUT_DIR + '/' + esm + '/experiment_CMIP6/tolerance-generated-tgavs/' ),\n                                         reproducible=False)\n        rp_370_wo = match_draw_stitchTgav(target_370, archive_wo370,\n                                         toler=tolerance, num_draws=Ndraws,\n                                         TGAV_OUTPUT_DIR=(OUTPUT_DIR + '/' + esm + '/experiment_CMIP6/tolerance-generated-tgavs/' ),\n                                         reproducible=False)\n\n\n    #########################################################\n    # Now we've generated all the GSAT files we're going to for each target.\n    # It's time to compare to the raw ensemble statistics for both Tgav and jumps.\n\n    if (((not orig_245.empty) & (not target_245.empty)) |\n            ((not orig_370.empty) & (not target_370.empty))):\n\n        # form the raw ensemble data frame\n        if orig_245.empty:\n            orig = orig_370.reset_index(drop=True).copy()\n        elif orig_370.empty:\n            orig = orig_245.reset_index(drop=True).copy()\n        else:\n            orig = orig_245.append(orig_370).reset_index(drop=True).copy()\n\n        # Read in all generated GSAT files and format so error metrics can\n        # be calculated.\n        gen = []\n        entries = Path((OUTPUT_DIR + '/' + esm + '/experiment_CMIP6/tolerance-generated-tgavs/'))\n        for entry in entries.iterdir():\n            if (('stitched' in entry.name) & ('GSAT' in entry.name)):\n                data = pd.read_csv((OUTPUT_DIR + '/' + esm + '/experiment_CMIP6/tolerance-generated-tgavs/') + entry.name)\n                data['model'] = esm\n\n                if ('ssp245' in entry.name):\n                    data['experiment'] = 'ssp245'\n\n                if ('ssp370' in entry.name):\n                    data['experiment'] = 'ssp370'\n\n                gen.append(data)\n                del (data)\n        gen = pd.concat(gen).reset_index(drop=True).copy()\n        gen = gen.rename(columns={\"stitching_id\": \"ensemble\"}).copy()\n\n        compared_data = four_errors(gen_data=gen, orig_data=orig)\n        compared_data.to_csv((OUTPUT_DIR + '/' + esm + '/experiment_CMIP6/all_metrics.csv'), index=False)\n\n        # average over draws\n        aggregate_metrics = []\n        for name, group in compared_data.groupby(['model', 'variable', 'experiment', 'tolerance', 'archive']):\n            ds = group.copy()\n            ds1 = ds[['model', 'variable', 'experiment', 'tolerance', 'archive']].drop_duplicates().copy()\n            ds1['aggregate_E1_tgav'] = np.mean(ds.E1_tgav.values)\n            ds1['aggregate_E2_tgav'] = np.mean(ds.E2_tgav.values)\n            ds1['aggregate_E1_jump'] = np.mean(ds.E1_jump.values)\n            ds1['aggregate_E2_jump'] = np.mean(ds.E2_jump.values)\n            ds1['max_metric'] = np.max([ds1.aggregrate_E1_tgav.values,\n                                        abs(1 - ds1.aggregate_E2_tgav.values),\n                                        ds1.aggregate_E1_jump.values,\n                                        abs(1 - ds1.aggregate_E2_jump.values)])\n            aggregate_metrics.append(ds1)\n            del (ds)\n            del (ds1)\n        aggregate_metrics = pd.concat(aggregate_metrics).reset_index(drop=True).copy()\n\n        # filter to the largest tolerance that keeps max_metric<error_threshold\n        # for each model, variable, experiment, archive.\n        max_tol = []\n        for name, group in aggregate_metrics.groupby(['model', 'variable', 'experiment', 'archive']):\n            ds = group.copy()\n            ds = ds[ds[\"max_metric\"] < error_threshold].copy()\n            ds = ds[ds['tolerance'] == ds.tolerance.max()].copy()\n            ds = ds.rename(columns={\"tolerance\": \"max_tol\"}).copy()\n            ds = ds[['model', 'variable', 'experiment', 'archive', 'max_tol']].copy()\n            max_tol.append(ds)\n            del (ds)\n        max_tol = pd.concat(max_tol).reset_index(drop=True).copy()\n        max_tol.to_csv((OUTPUT_DIR + '/' + esm + '/experiment_CMIP6/max_tol_by_ESM_SSP.csv'), index=False)\n\n\n    if not max_tol.empty:\n        # now that we have max tolerances, we will use those to do a final,\n        # reproducible draw and construction of gridded data\n        for name, group in max_tol.groupby(['model', 'variable', 'experiment', 'archive']):\n            tolerance = group.max_tol.unique()[0]\n            arch_id = group.archive.unique()[0]\n            targ_id = group.experiment.unique()[0]\n\n            if targ_id == 'ssp245':\n                target = target_245.copy()\n                if group.archive.unique == 'wo_target':\n                    archive = archive_wo245.copy()\n                else:\n                    archive = archive_w_all.copy()\n\n            if targ_id == 'ssp370':\n                target = target_370.copy()\n                if group.archive.unique == 'wo_target':\n                    archive = archive_wo370.copy()\n                else:\n                    archive = archive_w_all.copy()\n\n            match_df = stitches.match_neighborhood(target, archive,\n                                                   tol=tolerance)\n\n            unformatted_recipe = stitches.permute_stitching_recipes(N_matches=10000,\n                                                                    matched_data=match_df,\n                                                                    archive=archive, testing=True)\n            new_ids = ('~tol' + str(tolerance) + '~archive_' + arch_id + '~' +\n                       unformatted_recipe['stitching_id'].astype(str)).copy()\n            unformatted_recipe = unformatted_recipe.drop(columns=['stitching_id']).copy()\n            unformatted_recipe['stitching_id'] = new_ids\n            del (new_ids)\n\n            recipe = stitches.generate_gridded_recipe(unformatted_recipe)\n            recipe.columns = ['target_start_yr', 'target_end_yr', 'archive_experiment', 'archive_variable',\n                              'archive_model', 'archive_ensemble', 'stitching_id', 'archive_start_yr',\n                              'archive_end_yr', 'tas_file']\n            recipe.to_csv((OUTPUT_DIR + '/' + esm + '/experiment_CMIP6/max-tol-runs/' +\n                               'gridded_recipes_' + esm + '_target'+\n                           targ_id +'_archive_' + arch_id +'.csv'), index=False)\n\n\n            gsat = stitches.gmat_stitching(recipe)\n            gsat['tolerance'] = tolerance\n            gsat['archive'] = arch_id\n            for id in gsat.stitching_id.unique():\n                ds = gsat[gsat['stitching_id'] == id].copy()\n                fname = (OUTPUT_DIR + '/' + esm + '/experiment_CMIP6/max-tol-runs/' +\n                         'stitched_' + esm + '_GSAT_' + id + '.csv')\n                ds.to_csv(fname, index=False)\n\n\n                # for single_id in recipe['stitching_id'].unique():\n                #     single_rp = recipe.loc[recipe['stitching_id'] == single_id].copy()\n                #     outputs = stitches.gridded_stitching((OUTPUT_DIR + '/' + esm + '/experiment_CMIP6'),\n                #                                          single_rp)\n                #     del (single_rp)\n                #     del(outputs)\n\n\n\n\n# end for loop over ESMs\n", "meta": {"hexsha": "6292e7633a78d5a2088c2a36ac20458795b27040", "size": 24162, "ext": "py", "lang": "Python", "max_stars_repo_path": "modules/paper_experiment_CMIP6.py", "max_stars_repo_name": "JGCRI/stitches", "max_stars_repo_head_hexsha": "a55e5801279bd153bb7bcc247422e29eecbbc209", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/paper_experiment_CMIP6.py", "max_issues_repo_name": "JGCRI/stitches", "max_issues_repo_head_hexsha": "a55e5801279bd153bb7bcc247422e29eecbbc209", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 37, "max_issues_repo_issues_event_min_datetime": "2021-01-26T21:31:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:26:36.000Z", "max_forks_repo_path": "modules/paper_experiment_CMIP6.py", "max_forks_repo_name": "JGCRI/stitches", "max_forks_repo_head_hexsha": "a55e5801279bd153bb7bcc247422e29eecbbc209", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.8481973435, "max_line_length": 136, "alphanum_fraction": 0.5737107855, "include": true, "reason": "import numpy", "num_tokens": 5642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.32082128783705344, "lm_q1q2_score": 0.16667349956747893}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"\nssobj --- Solar System objects.\n===============================\n\n   Classes\n   -------\n   SolarSysObject\n\n   Functions\n   ---------\n   getgeom\n   getspiceobj\n   getxyz\n   summarizegeom\n\n\"\"\"\n\nimport numpy as np\nimport astropy.units as u\nfrom astropy.time import Time\n\nfrom . import core\n\n__all__ = [\n    'SolarSysObject',\n    'getgeom',\n    'getspiceobj',\n    'getxyz',\n    'summarizegeom',\n]\n\nclass SolarSysObject:\n    \"\"\"A star, planet, comet, etc. in the Solar System.\n\n    Parameters\n    ----------\n    state : State\n      The object from which to retrieve positions and velocities.\n    M : float or Quantity, optional\n      Mass of the object.  [float: kg]\n    GM : float or Quantity, optional\n      Gravitational constant times the mass of the object. [float:\n      km**3/s**2]\n    name : string, optional\n      The name of the object.\n\n    Methods\n    -------\n    ephemeris : Ephemeris for an observer.\n    fluxd : Total flux density as seen by an observer.\n    lightcurve : An ephemeris table with fluxes.\n    observe : Distance, phase angle, etc. to another object.\n    orbit : Osculating orbital parameters at date.\n    r : Position vector\n    v : Velocity vector\n    h : Angular momentum integral, `r × v`\n\n    Notes\n    -----\n    Inheriting classes should override `fluxd`.\n\n    \"\"\"\n\n    def __init__(self, state, M=None, GM=None, name=None):\n        from .state import State\n        assert isinstance(state, State)\n        self.state = state\n        self.name = name\n\n        if M is None and GM is None:\n            self.M = 0\n        elif M is not None:\n            self.M = M\n        else:\n            self.GM = GM\n\n    @property\n    def M(self):\n        \"\"\"Mass.  [kg]\"\"\"\n        return self._GM / 6.67384e-20\n\n    @M.setter\n    def M(self, m):\n        m = u.Quantity(m, u.kg)\n        self._GM = 6.67384e-20 * m.value\n\n    @property\n    def GM(self):\n        \"\"\"Gravitational constant times mass. [kg**3 / s**2]\"\"\"\n        return self._GM\n\n    @GM.setter\n    def GM(self, gm):\n        gm = u.Quantity(gm, u.km**3 / u.s**2)\n        self._GM = gm.value\n\n    def __repr__(self):\n        return '<SolarSysObject name=\"{}\" M=\"{:.3g} kg\">'.format(\n            self.name, self.M)\n\n    def r(self, date):\n        \"\"\"Position vector.\n\n        Parameters\n        ----------\n        date : string, float, astropy Time, datetime, or array\n          Processed via `util.date2time`.\n\n        Returns\n        -------\n        r : ndarray\n          Position vector (3-element or Nx3 element array). [km]\n       \n        \"\"\"\n        return self.state.r(date)\n\n    def v(self, date):\n        \"\"\"Velocity vector.\n\n        Parameters\n        ----------\n        date : string, float, astropy Time, datetime, or array\n          Processed via `util.date2time`.\n\n        Returns\n        -------\n        v : ndarray\n          Velocity vector (3-element or Nx3 element array). [km/s]\n       \n        \"\"\"\n        return self.state.v(date)\n\n    def rv(self, date):\n        \"\"\"Position and velocity vectors.\n\n        Parameters\n        ----------\n        date : string, float, astropy Time, datetime, or array\n          Processed via `util.date2time`.\n\n        Returns\n        -------\n        r : ndarray\n          Position vector (3-element or Nx3 element array). [km]\n        v : ndarray\n          Velocity vector (3-element or Nx3 element array). [km/s]\n\n        \"\"\"\n        return self.state.rv(date)\n\n    def h(self, date):\n        \"\"\"Angular momentum integral, `r × v`.\n\n        Parameters\n        ----------\n        date : string, float, astropy Time, datetime, or array\n          Processed via `util.date2time`.\n\n        Returns\n        -------\n        h : ndarray\n          3-element or Nx3 element array.  [km2/s]\n\n        \"\"\"\n        return self.state.h(date)\n\n    def ephemeris(self, observer, dates, num=None, columns=None,\n                  cformats=None, ra_unit='hourangle', date_format=None,\n                  ltt=False, **kwargs):\n        \"\"\"Ephemeris for an observer.\n\n        Parameters\n        ----------\n        observer : SolarSysObject\n          The observer.\n        dates : array\n          If `num` is `None`, set `dates` to a list of exact times for\n          the ephemeris, otherwise, let `dates` be a start and stop\n          time, and `num` be the number of dates to generate.  `dates`\n          may be in any format that `observe` accepts.\n        num : int, optional\n          If not `None`, generate this many time steps between\n          `min(dates)` and `max(dates)`.\n        columns : array, optional\n          A list of `Geom` keywords to use as table columns, or `None`\n          for the default list.\n        cformats : dict or list, optional\n          A dictionary of formats with keys corresponding to\n          `columns`.\n        ra_unit : str or astropy Unit, optional\n          The unit of Right Ascention output, e.g., hourangle or deg.\n        date_format : function\n          A function to format the `date` column before creating the\n          table.\n        ltt : bool, optional\n          Set to `True` to account for light travel time.\n\n        Returns\n        -------\n        eph : astropy Table\n\n        Notes\n        -----\n        `date_format` should be removed when astropy `Table` can\n        handle Time objects.\n\n        Override `_add_lc_columns` to add additional columns to\n        lightcurve output.\n\n        \"\"\"\n\n        from astropy.table import Table, Column\n        from astropy.units import Quantity\n        from ..util import date2time, dh2hms\n\n        dates = date2time(dates)\n        if num is not None:\n            if num <= 0:\n                time = []\n            elif num == 1:\n                time = [dates[0], dates[-1]]\n            else:\n                step = (dates[-1] - dates[0]) / float(num - 1)\n                time = []\n                for i in range(num):\n                    time += [dates[0] + step * i]\n        else:\n            time = dates\n\n        g = observer.observe(self, time, ltt=ltt)\n\n        if columns is None:\n            columns = ['date', 'ra', 'dec', 'rh', 'delta', 'phase', 'selong']\n\n        if cformats is None:\n            cformats = dict()\n\n        _cformats = dict(\n            date = '{:s}',\n            ra = lambda x: dh2hms(x, \"{:2d}:{:02d}\"),\n            dec = lambda x: dh2hms(x, \"{:2d}:{:02d}\"),\n            lam = '{:.0f}',\n            bet = '{:+.0f}',\n            rh = '{:.3f}',\n            delta = '{:.3f}',\n            phase = '{:.0f}',\n            selong = '{:.0f}',\n            lelong = '{:.0f}')\n\n        for k, v in cformats:\n            _cformats[k] = v\n\n        if date_format is None:\n            date_format = lambda d: d.iso[:-7]\n\n        eph = Table()\n        eph.meta['ltt'] = ltt\n        #eph.meta['observer'] = str(self)\n        #eph.meta['target'] = str(target)\n\n        for c in columns:\n            if c == 'date':\n                data = [date_format(d) for d in g[c]]\n            elif c == 'ra':\n                data = g[c].to(ra_unit)\n            else:\n                data = g[c]\n\n            if c in _cformats:\n                cf = _cformats[c]\n            else:\n                cf = None\n\n            eph.add_column(Column(data=data, name=c, format=cf))\n\n        return eph\n\n    def fluxd(self, observer, date, wave, ltt=False,\n              unit=u.Unit('W / (m2 um)'), **kwargs):\n        \"\"\"Total flux density as seen by an observer.\n\n        Parameters\n        ----------\n        observer : SolarSysObject\n          The observer.\n        date : string, float, astropy Time, datetime\n          The time of the observation in any format acceptable to\n          `observer`.\n        wave : Quantity\n          The wavelengths at which to compute `fluxd`.\n        ltt : bool, optional\n          Set to `True` to correct the object's position for light\n          travel time.\n        unit : astropy Unit\n          The return unit, must be flux density.\n        \n        Returns\n        -------\n        fluxd : Quantity\n\n        \"\"\"\n        raise NotImplemented('This class has not implemented fluxd.')\n\n    def lightcurve(self, observer, dates, wave, wformat='f{:.1f}',\n                   verbose=True, **kwargs):\n        \"\"\"An ephemeris table with fluxes.\n\n        Parameters\n        ----------\n        observer : SolarSysObject\n          The observer.\n        dates : string, float, astropy Time, datetime\n          The dates of the observation in any format acceptable to\n          `SolarSysObservable.ephemeris`.\n        wave : Quantity\n          The wavelengths at which to compute `fluxd`.\n        wformat : string, optional\n          The flux density columns will are labed with their\n          wavelengths using this format string.\n        verbose : bool, optional\n          If `True`, give some visual feedback.\n        **kwargs\n          Additional `fluxd` and `ephemeris` keywords.\n\n        Returns\n        -------\n        lc : astropy Table\n\n        Notes\n        -----\n        `date` must be in the table returned by `ephemeris`.\n\n        The `cformat` keyword `fluxd` will be used to format all flux\n        density columns.\n\n        \"\"\"\n\n        from astropy.table import Column\n\n        lc = self.ephemeris(observer, dates, **kwargs)\n        if 'date' not in lc.columns:\n            raise KeyError(\"Ephemeris must return a date column.\"\n                           \"  Update columns.\")\n\n        if not np.iterable(wave):\n            wave = [wave.value] * wave.unit\n\n        if verbose:\n            print('Computing date:')\n\n        fluxd = np.zeros((len(lc), len(wave)))\n        for i, d in enumerate(lc['date']):\n            if verbose:\n                print(d)\n            f = self.fluxd(observer, d, wave, **kwargs)\n            fluxd[i] = f.value\n            unit = f.unit\n\n        if verbose:\n            print()\n\n        lc = self._add_lc_columns(lc)\n\n        cf = kwargs.get('cformat', dict()).get('fluxd', '{:9.3g}')\n        unit = str(unit)\n        for i in range(fluxd.shape[1]):\n            lc.add_column(Column(data=fluxd[:, i],\n                                 name=wformat.format(wave.value[i]),\n                                 format=cf, unit=unit))\n        return lc\n\n    def _add_lc_columns(self, lc):\n        \"\"\"Add additional columns to a lightcurve table.\n\n        Parameters\n        ----------\n        lc : Table\n          The current lightcurve table.\n\n        \"\"\"\n        return lc\n\n    def observe(self, target, date, ltt=False):\n        \"\"\"Distance, phase angle, etc. to another object.\n\n        Parameters\n        ----------\n        target : SolarSysObject\n          The target to observe.\n        date : string, float, astropy Time, datetime, or array\n          Processed via `util.date2time`.\n        ltt : bool, optional\n          Account for light travel time when `True`.\n\n        Returns\n        -------\n        geom : Geom\n          The geometric parameters of the observation.\n\n        \"\"\"\n\n        from astropy.time import TimeDelta\n        import astropy.constants as const\n        from . import Geom\n        from ..util import date2time\n\n        date = date2time(date)\n\n        rt = target.r(date) # target postion\n        ro = self.r(date)   # observer position\n        vt = target.v(date) # target velocity\n        vo = self.v(date)   # observer velocity\n\n        g = Geom(ro * u.km, rt * u.km,\n                 vo=vo * u.km / u.s, vt=vt * u.km / u.s,\n                 date=date)\n\n        if ltt:\n            dt = (g['delta'] / const.c.si).decompose().value\n            date -= TimeDelta(dt, format='sec')\n            g = self.observe(target, date, ltt=False)\n\n        return g\n\n    def orbit(self, date):\n        \"\"\"Osculating orbital elements.\n\n        Parameters\n        ----------\n        date : string, float, astropy Time, datetime, or array\n          Processed via `util.date2time`.\n\n        Returns\n        -------\n        orbit : dict\n          See `util.state2orbit`.\n\n        \"\"\"\n\n        from ..util import state2orbit, date2time\n        r = self.r(date)\n        v = self.v(date)\n        jd = date2time(date).jd\n        return state2orbit(r, v)\n\ndef getgeom(target, observer, date=None, ltt=False, kernel=None):\n    \"\"\"Moving target geometry parameters for an observer and date.\n\n    Parameters\n    ----------\n    target : string, SolarSysObject\n      The object's name or NAIF ID, as found in the relevant SPICE\n      kernel, or a `SolarSysObject`.\n    observer : string, array, SolarSysObject\n      A valid built-in observer name, set of heliocentric rectangular\n      ecliptic J2000 coordinates, or a `SolarSysObject`.  See the\n      `ephem` package documentation for built-in moving objects that\n      can be used as observers.\n    date : string, float or array, optional\n      The date(s) for which to compute the target's geometry.\n    ltt : bool, optional\n      Set to true to correct parameters for light travel time\n      (currently, only one ltt iteration is implemented).\n    kernel : string, optional\n      If the target or observer is a string, use this kernel.\n\n    Returns\n    -------\n    geom : Geom\n      The geometric parameters of the observation.\n\n    Raises\n    ------\n    ValueError on invalid input.\n\n    \"\"\"\n\n    from . import _loaded_objects\n    from .state import SpiceState\n\n    if isinstance(target, str):\n        target = SolarSysObject(SpiceState(target, kernel=kernel))\n    elif not isinstance(target, SolarSysObject):\n        raise ValueError(\"target must be a string or SolarSysObject.\")\n\n    if isinstance(observer, str):\n        if observer.lower() in _loaded_objects:\n            observer = _loaded_objects[observer.lower()]\n        else:\n            observer = SolarSysObject(SpiceState(target, kernel=kernel))\n    elif np.iterable(observer):\n        observer = FixedObject(observer)\n    elif not isinstance(observer, SolarSysObject):\n        raise ValueError(\"observer must be a string, array, or SolarSysObject\")\n\n    return observer.observe(target, date, ltt=ltt)\n\ndef getspiceobj(obj, kernel=None, name=None, **kwarg):\n    \"\"\"Create a new SolarSysObject with a SPICE kernel, for your convenience.\n\n    Parameters\n    ----------\n    obj : string or int\n      The object's name or NAIF ID, as found in the relevant SPICE\n      kernel.\n    kernel : string, optional\n      The name of a specific SPICE planetary ephemeris kernel (SPK) to\n      use for this object, or `None` to automatically search for a\n      kernel through `find_kernel`.\n    name : string\n      The name of the object, or `None` to use `obj`.\n    **kwarg\n      Any other `SolarSysObject` keyword argument.\n\n    Returns\n    -------\n    ssobj : SolarSysObject\n      A `SolarSysObject` loaded with the requested SPICE ephemeris\n      file.\n\n    \"\"\"\n\n    from .state import SpiceState\n    name = str(obj) if name is None else name\n    return SolarSysObject(SpiceState(obj, kernel=kernel), name=name, **kwarg)\n\ndef getxyz(obj, date=None, kernel=None):\n    \"\"\"Coordinates and velocity from an ephemeris kernel.\n\n    Coordinates are heliocentric rectangular ecliptic J2000.\n\n    Parameters\n    ----------\n    obj : string or int\n      The object's name or NAIF ID, as found in the relevant SPICE\n      kernel.\n    date : string, float, astropy Time, datetime, or array, optional\n      Processed via `util.date2time`.\n    kernel : string, optional\n      The name of a specific SPICE planetary ephemeris kernel (SPK) to\n      use for this object, or `None` to automatically search for a\n      kernel through `find_kernel`.\n\n    Returns\n    -------\n    r, v: array\n      The position and veloctiy vectors as 3-element arrays, or, if\n      multiple dates are requested, Nx3-element arrays. [km and km/s]\n\n    Raises\n    ------\n    ValueError for invalid `date`.\n    ObjectError for `obj` not in `kernel`.\n\n    \"\"\"\n\n    from .state import SpiceState\n    obj = SpiceState(obj, kernel=kernel)\n    return obj.r(date), obj.v(date)\n\ndef summarizegeom(*args, **kwargs):\n    \"\"\"Pretty print a summary of the observing geometry.\n\n    See `getgeom` for a description of the parameters.\n\n    \"\"\"\n\n    getgeom(*args, **kwargs).summary()\n\n# update module docstring\nfrom ..util import autodoc\nautodoc(globals())\ndel autodoc\n", "meta": {"hexsha": "d32ebd416889104b2607555a9ca522cc5e13c78d", "size": 16160, "ext": "py", "lang": "Python", "max_stars_repo_path": "mskpy/ephem/ssobj.py", "max_stars_repo_name": "mkelley/mskpy", "max_stars_repo_head_hexsha": "41f41fd69bae71853abdfd2afbd535cd0b79c530", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-03-27T09:52:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-07T22:29:51.000Z", "max_issues_repo_path": "mskpy/ephem/ssobj.py", "max_issues_repo_name": "mkelley/mskpy", "max_issues_repo_head_hexsha": "41f41fd69bae71853abdfd2afbd535cd0b79c530", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2015-11-29T22:20:57.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-01T21:15:07.000Z", "max_forks_repo_path": "mskpy/ephem/ssobj.py", "max_forks_repo_name": "mkelley/mskpy", "max_forks_repo_head_hexsha": "41f41fd69bae71853abdfd2afbd535cd0b79c530", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-11-29T21:26:09.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-24T08:53:43.000Z", "avg_line_length": 28.1043478261, "max_line_length": 79, "alphanum_fraction": 0.5563118812, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 3860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.16653113107927792}}
{"text": "import logging\nimport multiprocessing\nimport warnings\nfrom itertools import repeat\nfrom pathlib import Path\n\nimport astropy.units as u\nimport click\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom astropy.coordinates import SkyCoord\nfrom astropy.table import Table\nfrom regions import CircleSkyRegion\nfrom scipy.stats import norm\n\nfrom gammapy.data import GTI, EventList, Observation\nfrom gammapy.datasets import MapDataset, MapDatasetEventSampler\nfrom gammapy.estimators import ExcessMapEstimator\nfrom gammapy.irf import EnergyDispersion2D, load_cta_irfs\nfrom gammapy.makers import MapDatasetMaker\nfrom gammapy.maps import Map, MapAxis, WcsGeom\nfrom gammapy.modeling import Fit\nfrom gammapy.modeling.models import Models\nfrom gammapy.utils.table import table_from_row_data\n\nlog = logging.getLogger(__name__)\n\n# path config\nBASE_PATH = Path(__file__).parent\n\nAVAILABLE_MODELS = [\n    \"point-pwl\",\n    \"point-ecpl\",\n    \"point-log-parabola\",\n    \"point-pwl2\",\n    \"point-ecpl-3fgl\",\n    \"point-ecpl-4fgl\",\n    \"point-template\",\n    \"diffuse-cube\",\n    \"disk-pwl\",\n    \"gauss-pwl\",\n]\n\nDPI = 120\n\n# observation config\nIRF_FILE = \"$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits\"\n# IRF_FILE = \"$GAMMAPY_DATA/cta-prod3b/caldb/data/cta/prod3b-v2/bcf/South_z20_50h/irf_file.fits\"\n\nPOINTING = SkyCoord(0.0, 0.5, frame=\"galactic\", unit=\"deg\")\nLIVETIME = 1 * u.hr\nGTI_TABLE = GTI.create(start=0 * u.s, stop=LIVETIME.to(u.s))\n\n# dataset config\nENERGY_AXIS = MapAxis.from_energy_bounds(\"0.1 TeV\", \"100 TeV\", nbin=10, per_decade=True)\nENERGY_AXIS_TRUE = MapAxis.from_energy_bounds(\n    \"0.03 TeV\", \"300 TeV\", nbin=20, per_decade=True, name=\"energy_true\"\n)\nMIGRA_AXIS = MapAxis.from_bounds(0.5, 2, nbin=150, node_type=\"edges\", name=\"migra\")\n\nWCS_GEOM = WcsGeom.create(\n    skydir=POINTING, width=(8, 8), binsz=0.02, frame=\"galactic\", axes=[ENERGY_AXIS]\n)\n\n\ndef get_filename_dataset(livetime):\n    filename = f\"data/dataset_{livetime.value:.0f}{livetime.unit}.fits.gz\"\n    return BASE_PATH / filename\n\n\ndef get_filename_events(filename_dataset, filename_model, obs_id):\n    obs_id = int(obs_id)\n    model_str = filename_model.name.replace(filename_model.suffix, \"\")\n    filename_events = filename_dataset.name.replace(\"dataset\", \"events\")\n    filename_events = BASE_PATH / f\"data/models/{model_str}/\" / filename_events\n    filename_events = filename_events.name.replace(\".fits.gz\", f\"_{obs_id:04d}.fits.gz\")\n    return BASE_PATH / f\"data/models/{model_str}/\" / filename_events\n\n\ndef get_filename_best_fit_model(filename_model, obs_id, livetime):\n    obs_id = int(obs_id)\n    model_str = filename_model.name.replace(filename_model.suffix, \"\")\n\n    path = (\n        BASE_PATH\n        / f\"results/models/{model_str}/fit_{livetime.value:.0f}{livetime.unit}/covariance\"\n    )\n    path.mkdir(exist_ok=True, parents=True)\n    path = (\n        BASE_PATH\n        / f\"results/models/{model_str}/plots_{livetime.value:.0f}{livetime.unit}\"\n    )\n    path.mkdir(exist_ok=True, parents=True)\n\n    filename = f\"results/models/{model_str}/fit_{livetime.value:.0f}{livetime.unit}/best-fit-model_{obs_id:04d}.yaml\"\n    return BASE_PATH / filename\n\n\ndef get_filename_covariance(filename_best_fit_model):\n    filename = filename_best_fit_model.name\n    # filename = filename.replace(\"best-fit-model\", \"covariance\")\n    filename = filename.replace(\".yaml\", \"_covariance.dat\")\n    # return filename_best_fit_model.parent / \"covariance\" / filename\n    return filename_best_fit_model.parent / filename\n\n\n@click.group()\n@click.option(\n    \"--log-level\", default=\"INFO\", type=click.Choice([\"DEBUG\", \"INFO\", \"WARNING\"])\n)\n@click.option(\"--show-warnings\", is_flag=True, help=\"Show warnings?\")\ndef cli(log_level, show_warnings):\n    logging.basicConfig(level=log_level)\n    if not show_warnings:\n        warnings.simplefilter(\"ignore\")\n\n\n@cli.command(\"all\", help=\"Run all steps\")\n@click.argument(\"model\", type=click.Choice(list(AVAILABLE_MODELS) + [\"all-models\"]))\n@click.option(\n    \"--obs_ids\", default=1, nargs=1, help=\"Select a single observation\", type=int\n)\n@click.option(\n    \"--obs_all\",\n    default=False,\n    nargs=1,\n    help=\"Iterate over all observations\",\n    is_flag=True,\n)\n@click.option(\n    \"--simple\",\n    default=False,\n    nargs=1,\n    help=\"Simplify the dataset preparation\",\n    type=str,\n)\n@click.option(\"--core\", default=4, nargs=1, help=\"Number of cores to be used\", type=int)\ndef all_cmd(model, obs_ids, obs_all, simple, core):\n    models = AVAILABLE_MODELS if model == \"all-models\" else [model]\n    log.info(models)\n    binned = False\n    filename_dataset = get_filename_dataset(LIVETIME)\n\n    log.info(f\"Preparing datasets\")\n    if simple:\n        filename_dataset = Path(\n            str(filename_dataset).replace(\"dataset\", \"dataset_simple\")\n        )\n        prepare_dataset_simple(filename_dataset)\n    else:\n        prepare_dataset(filename_dataset)\n\n    for model in models:\n        log.info(f\"Simulating events with model {model}\")\n        filename_model = BASE_PATH / f\"models/{model}.yaml\"\n        simulate_events(\n            filename_model=filename_model,\n            filename_dataset=filename_dataset,\n            nobs=obs_ids,\n        )\n        if obs_all:\n            obs_ids = f\"0:{obs_ids}\"\n            obs_ids = parse_obs_ids(obs_ids, model)\n            with multiprocessing.Pool(processes=core) as pool:\n                args = zip(\n                    repeat(filename_model),\n                    repeat(filename_dataset),\n                    obs_ids,\n                    repeat(binned),\n                    repeat(simple),\n                )\n                pool.starmap(fit_model, args)\n\n            fit_gather(model, LIVETIME)\n            plot_pull_distribution(model, LIVETIME)\n        else:\n            fit_model(\n                filename_model=filename_model,\n                filename_dataset=filename_dataset,\n                obs_id=obs_ids - 1,\n                binned=binned,\n                simple=simple,\n            )\n            plot_results(\n                filename_model=filename_model,\n                filename_dataset=filename_dataset,\n                obs_id=obs_ids - 1,\n            )\n\n\n@cli.command(\"prepare-dataset\", help=\"Prepare map dataset used for event simulation\")\ndef prepare_dataset_cmd():\n    filename_dataset = get_filename_dataset(LIVETIME)\n    prepare_dataset(filename_dataset)\n\n\ndef prepare_dataset(filename_dataset):\n    \"\"\"Prepare dataset for a given skymodel.\"\"\"\n    log.info(f\"Reading {IRF_FILE}\")\n    irfs = load_cta_irfs(IRF_FILE)\n    observation = Observation.create(\n        obs_id=1001, pointing=POINTING, livetime=LIVETIME, irfs=irfs\n    )\n\n    empty = MapDataset.create(\n        WCS_GEOM, energy_axis_true=ENERGY_AXIS_TRUE, migra_axis=MIGRA_AXIS\n    )\n    maker = MapDatasetMaker(selection=[\"exposure\", \"background\", \"psf\", \"edisp\"])\n    dataset = maker.run(empty, observation)\n\n    filename_dataset.parent.mkdir(exist_ok=True, parents=True)\n    log.info(f\"Writing {filename_dataset}\")\n    dataset.write(filename_dataset, overwrite=True)\n\n\ndef prepare_dataset_simple(filename_dataset):\n    \"\"\"Prepare dataset for a given skymodel.\"\"\"\n    log.info(f\"Reading {IRF_FILE}\")\n\n    irfs = load_cta_irfs(IRF_FILE)\n\n    edisp_gauss = EnergyDispersion2D.from_gauss(\n        e_true=ENERGY_AXIS_TRUE.edges,\n        migra=MIGRA_AXIS.edges,\n        sigma=0.1,\n        bias=0,\n        offset=[0, 2, 4, 6, 8] * u.deg,\n    )\n\n    irfs[\"edisp\"] = edisp_gauss\n    # irfs[\"aeff\"].data.data = np.ones_like(irfs[\"aeff\"].data.data) * 1e6\n\n    observation = Observation.create(\n        obs_id=1001, pointing=POINTING, livetime=LIVETIME, irfs=irfs\n    )\n\n    empty = MapDataset.create(\n        WCS_GEOM, energy_axis_true=ENERGY_AXIS_TRUE, migra_axis=MIGRA_AXIS\n    )\n    # maker = MapDatasetMaker(selection=[\"exposure\", \"edisp\"])\n    # maker = MapDatasetMaker(selection=[\"exposure\", \"edisp\", \"background\"])\n    maker = MapDatasetMaker(selection=[\"exposure\", \"edisp\", \"psf\", \"background\"])\n    dataset = maker.run(empty, observation)\n\n    filename_dataset.parent.mkdir(exist_ok=True, parents=True)\n    log.info(f\"Writing {filename_dataset}\")\n    dataset.write(filename_dataset, overwrite=True)\n\n\n@cli.command(\"simulate-events\", help=\"Simulate events for given model and livetime\")\n@click.argument(\"model\", type=click.Choice(list(AVAILABLE_MODELS) + [\"all-models\"]))\n@click.option(\"--nobs\", default=1, nargs=1, help=\"How many observations to simulate\")\ndef simulate_events_cmd(model, nobs):\n    models = AVAILABLE_MODELS if model == \"all-models\" else [model]\n    filename_dataset = get_filename_dataset(LIVETIME)\n\n    for model in models:\n        filename_model = BASE_PATH / f\"models/{model}.yaml\"\n        simulate_events(\n            filename_model=filename_model, filename_dataset=filename_dataset, nobs=nobs\n        )\n\n\ndef simulate_events(filename_model, filename_dataset, nobs):\n    \"\"\"Simulate events for a given model and dataset.\n\n    Parameters\n    ----------\n    filename_model : str\n        Filename of the model definition.\n    filename_dataset : str\n        Filename of the dataset to use for simulation.\n    nobs : int\n        Number of obervations to simulate.\n    \"\"\"\n    log.info(f\"Reading {IRF_FILE}\")\n    irfs = load_cta_irfs(IRF_FILE)\n\n    log.info(f\"Reading {filename_dataset}\")\n    dataset = MapDataset.read(filename_dataset)\n\n    log.info(f\"Reading {filename_model}\")\n    models = Models.read(filename_model)\n    # dataset.models = models\n    dataset.models.extend(models)\n\n    sampler = MapDatasetEventSampler(random_state=0)\n\n    for obs_id in np.arange(nobs):\n        observation = Observation.create(\n            obs_id=obs_id, pointing=POINTING, livetime=LIVETIME, irfs=irfs\n        )\n\n        events = sampler.run(dataset, observation)\n\n        path = get_filename_events(filename_dataset, filename_model, obs_id)\n        log.info(f\"Writing {path}\")\n        path.parent.mkdir(exist_ok=True, parents=True)\n        events.table.write(str(path), overwrite=True)\n\n\ndef parse_obs_ids(obs_ids_str, model):\n    if \":\" in obs_ids_str:\n        start, stop = obs_ids_str.split(\":\")\n        obs_ids = np.arange(int(start), int(stop))\n    elif \",\" in obs_ids_str:\n        obs_ids = [int(_) for _ in obs_ids_str.split(\",\")]\n    elif obs_ids_str == \"all\":\n        n_obs = len(list(BASE_PATH.glob(f\"data/models/{model}/events_*.fits.gz\")))\n        obs_ids = np.arange(n_obs)\n    else:\n        obs_ids = [int(obs_ids_str)]\n    return obs_ids\n\n\n@cli.command(\"fit-model\", help=\"Fit given model\")\n@click.argument(\"model\", type=click.Choice(list(AVAILABLE_MODELS) + [\"all-models\"]))\n@click.option(\n    \"--obs_ids\", default=\"all\", nargs=1, help=\"Which observation to choose.\", type=str\n)\n@click.option(\n    \"--binned\", default=False, nargs=1, help=\"Which observation to choose.\", type=str\n)\n@click.option(\n    \"--simple\", default=False, nargs=1, help=\"Select a single observation\", type=str\n)\n@click.option(\"--core\", default=4, nargs=1, help=\"Number of cores to be used\", type=int)\ndef fit_model_cmd(model, obs_ids, binned, simple, core):\n    models = AVAILABLE_MODELS if model == \"all-models\" else [model]\n    filename_dataset = get_filename_dataset(LIVETIME)\n\n    for model in models:\n        obs_ids = parse_obs_ids(obs_ids, model)\n        filename_model = BASE_PATH / f\"models/{model}.yaml\"\n        with multiprocessing.Pool(processes=core) as pool:\n            args = zip(\n                repeat(filename_model),\n                repeat(filename_dataset),\n                obs_ids,\n                repeat(binned),\n                repeat(simple),\n            )\n            pool.starmap(fit_model, args)\n\n\ndef read_dataset(filename_dataset, filename_model, obs_id):\n    log.info(f\"Reading {filename_dataset}\")\n    dataset = MapDataset.read(filename_dataset)\n\n    filename_events = get_filename_events(filename_dataset, filename_model, obs_id)\n    log.info(f\"Reading {filename_events}\")\n    events = EventList.read(filename_events)\n\n    counts = Map.from_geom(WCS_GEOM)\n    counts.fill_events(events)\n    dataset.counts = counts\n    return dataset\n\n\ndef fit_model(filename_model, filename_dataset, obs_id, binned=False, simple=False):\n    \"\"\"Fit the events using a model.\n\n    Parameters\n    ----------\n    filename_model : str\n        Filename of the model definition.\n    filename_dataset : str\n        Filename of the dataset to use for simulation.\n    obs_id : int\n        Observation ID.\n    \"\"\"\n    dataset = read_dataset(filename_dataset, filename_model, obs_id)\n\n    log.info(f\"Reading {filename_model}\")\n    models = Models.read(filename_model)\n\n    # dataset.models = models\n    dataset.models.extend(models)\n    if binned:\n        dataset.fake()\n\n    if dataset.background_model:\n        dataset.background_model.parameters[\"norm\"].frozen = True\n\n    fit = Fit([dataset])\n\n    result = fit.run(optimize_opts={\"print_level\": 1})\n\n    log.info(f\"Fit info: {result}\")\n\n    # write best fit model\n    path = get_filename_best_fit_model(filename_model, obs_id, LIVETIME)\n    path = path.absolute()\n    if binned:\n        path = Path(str(path).replace(\"/fit\", \"/fit_fake\"))\n    log.info(f\"Writing {path}\")\n    # write best-fit model and covariance\n    dataset.models.write(str(path), overwrite=True)\n\n    # write covariance\n    # path = get_filename_covariance(path)\n    # if binned:\n    #    path = Path(str(path).replace(\"/fit\",\"/fit_fake\"))\n    # log.info(f\"Writing {path}\")\n\n    # TODO: exclude background parameters for now, as they are fixed anyway\n    # covariance = result.parameters.get_subcovariance(models.parameters)\n    # np.savetxt(path, covariance)\n\n\n@cli.command(\"fit-gather\", help=\"Gather fit results from the given model\")\n@click.argument(\"model\", type=click.Choice(list(AVAILABLE_MODELS) + [\"all-models\"]))\n@click.option(\n    \"--binned\", default=False, nargs=1, help=\"Which observation to choose.\", type=str\n)\ndef fit_gather_cmd(model, binned):\n    models = AVAILABLE_MODELS if model == \"all-models\" else [model]\n    for model in models:\n        fit_gather(model, LIVETIME, binned)\n\n\ndef fit_gather(model_name, livetime, binned=False):\n    rows = []\n\n    path = (\n        BASE_PATH\n        / f\"results/models/{model_name}/fit_{livetime.value:.0f}{livetime.unit}\"\n    )\n    if binned:\n        path = Path(str(path).replace(\"/fit\", \"/fit_fake\"))\n\n    for filename in path.glob(\"*.yaml\"):\n        # model_best_fit = read_best_fit_model(filename)\n        model_best_fit = Models.read(filename)\n        model_best_fit = model_best_fit[model_name]\n        row = {}\n\n        for par in model_best_fit.parameters:\n            row[par.name] = par.value\n            row[par.name + \"_err\"] = par.error\n\n        rows.append(row)\n\n    table = table_from_row_data(rows)\n    name = f\"fit-results-all_{livetime.value:.0f}{livetime.unit}\"\n    if binned:\n        name = \"fit_binned-results-all\"\n    filename = f\"results/models/{model_name}/{name}.fits.gz\"\n    log.info(f\"Writing {filename}\")\n    table.write(str(filename), overwrite=True)\n\n\n@cli.command(\"plot-results\", help=\"Plot results for given model\")\n@click.argument(\"model\", type=click.Choice(list(AVAILABLE_MODELS) + [\"all-models\"]))\n@click.option(\n    \"--obs_ids\", default=\"0\", nargs=1, help=\"Which observation to choose.\", type=str\n)\ndef plot_results_cmd(model, obs_ids):\n    models = AVAILABLE_MODELS if model == \"all-models\" else [model]\n    filename_dataset = get_filename_dataset(LIVETIME)\n    for model in models:\n        for obs_id in parse_obs_ids(obs_ids, model):\n            filename_model = BASE_PATH / f\"models/{model}.yaml\"\n            plot_results(\n                filename_model=filename_model,\n                filename_dataset=filename_dataset,\n                obs_id=obs_id,\n            )\n\n\ndef save_figure(filename):\n    path = BASE_PATH / filename\n    path.parent.mkdir(parents=True, exist_ok=True)\n    log.info(f\"Writing {path}\")\n    plt.savefig(path, dpi=DPI)\n    plt.clf()\n    plt.close()\n\n\ndef plot_spectra(model, model_best_fit, obs_id, livetime):\n    \"\"\"Plot spectral models\"\"\"\n\n    if model.tag == \"SkyDiffuseCube\":\n        log.info(f\"SkyDiffuseCube: no spectral model to plot\")\n    else:\n        ax = model.spectral_model.plot(\n            energy_range=(0.1, 300) * u.TeV, label=\"Sim. model\"\n        )\n        model_best_fit.spectral_model.plot(\n            energy_range=(0.1, 300) * u.TeV, label=\"Best-fit model\", ax=ax,\n        )\n        model_best_fit.spectral_model.plot_error(energy_range=(0.1, 300) * u.TeV, ax=ax)\n\n        ax.legend()\n        obs_id = int(obs_id)\n        filename = f\"results/models/{model.name}/plots_{livetime.value:.0f}{livetime.unit}/spectra/spectra_{obs_id:04d}.png\"\n        save_figure(filename)\n\n\ndef plot_residuals(dataset, obs_id, livetime, model_name):\n    \"\"\"Plot residuals\"\"\"\n\n    model = dataset.models[model_name]\n    if model.tag == \"SkyDiffuseCube\":\n        log.info(f\"SkyDiffuseCube: no spectral model to plot\")\n    else:\n        spatial_model = model.spatial_model\n        if spatial_model.__class__.__name__ == \"PointSpatialModel\":\n            region = CircleSkyRegion(center=spatial_model.position, radius=0.1 * u.deg)\n        else:\n            region = spatial_model.to_region()\n\n        dataset.plot_residuals(\n            method=\"diff/sqrt(model)\",\n            vmin=-0.5,\n            vmax=0.5,\n            region=region,\n            figsize=(10, 4),\n        )\n        obs_id = int(obs_id)\n        filename = f\"results/models/{model.name}/plots_{livetime.value:.0f}{livetime.unit}/residuals/residuals_{obs_id:04d}.png\"\n        save_figure(filename)\n\n\ndef plot_residual_distribution(dataset, obs_id, livetime):\n    \"\"\"Plot residual significance distribution\"\"\"\n    model = dataset.models[1]\n\n    estimator = ExcessMapEstimator(\n        correlation_radius=\"0.1 deg\"\n    )\n\n    maps = estimator.run(dataset)\n    valid = np.isfinite(maps[\"sqrt_ts\"].data)\n    sig_resid = maps[\"sqrt_ts\"].data[valid]\n\n    plt.hist(\n        sig_resid, density=True, alpha=0.5, color=\"red\", bins=100,\n    )\n\n    mu, std = norm.fit(sig_resid)\n    # replace with log.info()\n    log.info(\"Fit results: mu = {:.2f}, std = {:.2f}\".format(mu, std))\n    x = np.linspace(-8, 8, 50)\n    p = norm.pdf(x, mu, std)\n    plt.plot(\n        x,\n        p,\n        lw=2,\n        color=\"black\",\n        label=\"Fit results: mu = {:.2f}, std = {:.2f}\".format(mu, std),\n    )\n    plt.legend()\n    plt.xlabel(\"Significance\")\n    plt.yscale(\"log\")\n    plt.ylim(1e-5, 1)\n    xmin, xmax = np.min(sig_resid), np.max(sig_resid)\n    plt.xlim(xmin, xmax)\n\n    obs_id = int(obs_id)\n    filename = f\"residuals-distribution_{obs_id:04d}.png\"\n    filepath = f\"results/models/{model.name}/plots_{livetime.value:.0f}{livetime.unit}/residuals-distribution/{filename}\"\n    save_figure(filepath)\n\n\n# OBSOLETE...\n# def read_best_fit_model(filename):\n#    log.info(f\"Reading {filename}\")\n#    model_best_fit = Models.read(filename)\n#\n#    path = get_filename_covariance(filename)\n#    log.info(f\"Reading {path}\")\n#    pars = model_best_fit.parameters\n#    pars.covariance = np.loadtxt(str(path))\n#\n#    if model_best_fit[1].tag  == 'SkyDiffuseCube':\n#        spectral_model_best_fit = model_best_fit[1]\n#        covar = pars.get_subcovariance(spectral_model_best_fit.parameters)\n#        spectral_model_best_fit.parameters.covariance = covar\n#\n#       # spatial_model_best_fit = model_best_fit[0].spatial_model\n#       # covar = pars.get_subcovariance(spatial_model_best_fit.parameters)\n#       # spatial_model_best_fit.parameters.covariance = covar\n#\n#    else:\n#        spectral_model_best_fit = model_best_fit[1].spectral_model\n#        covar = pars.get_subcovariance(spectral_model_best_fit.parameters)\n#        spectral_model_best_fit.parameters.covariance = covar\n#\n#        spatial_model_best_fit = model_best_fit[1].spatial_model\n#        covar = pars.get_subcovariance(spatial_model_best_fit.parameters)\n#        spatial_model_best_fit.parameters.covariance = covar\n#\n#    return model_best_fit\n#\n\n\ndef plot_results(filename_model, obs_id, filename_dataset=None):\n    \"\"\"Plot the best-fit spectrum, the residual map and the residual significance distribution.\n\n    Parameters\n    ----------\n    filename_model : str\n        Filename of the model definition.\n    filename_dataset : str\n        Filename of the dataset.\n    obs_id : int\n        Observation ID.\n    \"\"\"\n    log.info(f\"Reading {filename_model}\")\n    model = Models.read(filename_model)\n\n    path = get_filename_best_fit_model(filename_model, obs_id, LIVETIME)\n    # model_best_fit = read_best_fit_model(path)\n    model_best_fit = Models.read(path)\n\n    plot_spectra(\n        model[model.names[0]], model_best_fit[model.names[0]], obs_id, LIVETIME\n    )\n\n    dataset = read_dataset(filename_dataset, filename_model, obs_id)\n    mod = Models(model_best_fit[model.names[0]])\n    dataset.models.extend(mod)\n    plot_residuals(dataset, obs_id, LIVETIME, model.names[0])\n    plot_residual_distribution(dataset, obs_id, LIVETIME)\n\n\n@cli.command(\n    \"plot-pull-distributions\", help=\"Plot pull distributions for the given model\"\n)\n@click.argument(\"model\", type=click.Choice(list(AVAILABLE_MODELS) + [\"all-models\"]))\n@click.option(\n    \"--binned\", default=False, nargs=1, help=\"Which observation to choose.\", type=str\n)\ndef plot_pull_distribution_cmd(model, binned):\n    models = AVAILABLE_MODELS if model == \"all-models\" else [model]\n    for model in models:\n        plot_pull_distribution(model_name=model, livetime=LIVETIME, binned=binned)\n\n\ndef plot_pull_distribution(model_name, livetime, binned=False):\n    name = f\"fit-results-all_{livetime.value:.0f}{livetime.unit}\"\n    if binned:\n        name = \"fit_binned-results-all\"\n    filename = BASE_PATH / f\"results/models/{model_name}/{name}.fits.gz\"\n    results = Table.read(str(filename))\n\n    filename_ref = BASE_PATH / f\"models/{model_name}.yaml\"\n    model_ref = Models.read(filename_ref)[0]\n    names = [name for name in results.colnames if \"err\" not in name]\n\n    plots = f\"plots_{livetime.value:.0f}{livetime.unit}\"\n    if binned:\n        plots = \"plots_fake\"\n    for name in names:\n        # TODO: report mean and stdev here as well\n        values = results[name]\n        values_err = results[name + \"_err\"]\n        par = model_ref.parameters[name]\n\n        if par.frozen:\n            log.info(f\"Skipping frozen parameter: {name}\")\n            continue\n\n        pull = (values - par.value) / values_err\n\n        # print(\"Number of fits beyond 5 sigmas: \",(np.where( (pull<-5) )))\n        plt.hist(pull, bins=21, normed=True, range=(-5, 5))\n        plt.xlim(-5, 5)\n        plt.xlabel(\"(value - value_true) / error\")\n        plt.ylabel(\"PDF\")\n        plt.title(f\"Pull distribution for {model_name}: {name} \")\n        filename = f\"results/models/{model_name}/{plots}/pull-distribution-{name}.png\"\n        save_figure(filename)\n\n\nif __name__ == \"__main__\":\n    cli()\n", "meta": {"hexsha": "e6d60cd9bedde03c070d0fd24b6f57a28b924f79", "size": 22718, "ext": "py", "lang": "Python", "max_stars_repo_path": "validation/event-sampling/make.py", "max_stars_repo_name": "AtreyeeS/gammapy-benchmarks", "max_stars_repo_head_hexsha": "b4b4ec998f0675b944c40fae4fce4692448d2237", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "validation/event-sampling/make.py", "max_issues_repo_name": "AtreyeeS/gammapy-benchmarks", "max_issues_repo_head_hexsha": "b4b4ec998f0675b944c40fae4fce4692448d2237", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "validation/event-sampling/make.py", "max_forks_repo_name": "AtreyeeS/gammapy-benchmarks", "max_forks_repo_head_hexsha": "b4b4ec998f0675b944c40fae4fce4692448d2237", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4580265096, "max_line_length": 128, "alphanum_fraction": 0.6689409279, "include": true, "reason": "import numpy,from scipy,import astropy,from astropy", "num_tokens": 5615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.16625207282592097}}
{"text": "#!/usr/bin/env python\n#\n# Copyright 2019 DFKI GmbH.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the\n# following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n# USE OR OTHER DEALINGS IN THE SOFTWARE.\nfrom copy import copy\nimport numpy as np\nimport collections\nfrom transformations import quaternion_matrix, euler_from_matrix, quaternion_multiply, quaternion_matrix, quaternion_from_matrix\nfrom .numerical_ik_quat import NumericalInverseKinematicsQuat\nfrom .numerical_ik_exp import NumericalInverseKinematicsExp\nfrom .skeleton_pose_model import SkeletonPoseModel\nfrom .cubic_motion_spline import CubicMotionSpline, get_quaternion_delta\nfrom ..animation_data.motion_blending import smooth_joints_around_transition_using_slerp, create_transition_using_slerp, smooth_quaternion_frames\nfrom ..utilities.log import write_message_to_log, LOG_MODE_DEBUG\nfrom .utils import convert_exp_frame_to_quat_frame\nfrom .fabrik_chain import FABRIKChain, FABRIKBone\nfrom ..animation_data.joint_constraints import JointConstraint, HingeConstraint2, BallSocketConstraint, ConeConstraint, ShoulderConstraint, HeadConstraint, SpineConstraint\nfrom ..animation_data.skeleton import LOOK_AT_DIR, SPINE_LOOK_AT_DIR\n\nSPATIAL_CONSTRAINT_TYPE_KEYFRAME_POSITION = \"keyframe_position\"\nSPATIAL_CONSTRAINT_TYPE_KEYFRAME_RELATIVE_POSITION = \"keyframe_relative_position\"\nSUPPORTED_CONSTRAINT_TYPES = [SPATIAL_CONSTRAINT_TYPE_KEYFRAME_POSITION, SPATIAL_CONSTRAINT_TYPE_KEYFRAME_RELATIVE_POSITION]\n\n\n\ndef create_fabrik_chain(skeleton, frame, node_order, activate_constraints=False):\n    bones = dict()\n    root = node_order[0]\n    root_offset = skeleton.nodes[root].get_global_position(frame)\n    frame_offset = skeleton.animated_joints.index(root)*4 + 3\n    for idx, j in enumerate(node_order[:-1]):\n        bones[j] = FABRIKBone(j, node_order[idx + 1])\n        if idx == 0:\n            bones[j].is_root = True\n        else:\n            bones[j].is_root = False\n\n    bones[node_order[-1]] = FABRIKBone(node_order[-1], None)\n    max_iter = 50\n    chain = FABRIKChain(skeleton, bones, node_order, max_iter=max_iter, frame_offset=frame_offset, root_offset=root_offset,\n                                                activate_constraints=activate_constraints)\n    return chain\n\ndef add_frames(skeleton, a, b):\n    \"\"\" returns c = a + b\"\"\"\n    c = np.zeros(len(a))\n    c[:3] = a[:3] + b[:3]\n    for idx, j in enumerate(skeleton.animated_joints):\n        o = idx * 4 + 3\n        q_a = a[o:o + 4]\n        q_b = b[o:o + 4]\n        q_prod = quaternion_multiply(q_a, q_b)\n        c[o:o + 4] = q_prod / np.linalg.norm(q_prod)\n    return c\n\ndef add_reduced_frames(skeleton, a, delta, joints):\n    \"\"\" returns c = a + delta where delta are the parameters of the joints list\"\"\"\n    c = np.array(a)\n    o = 0\n    for idx, j in enumerate(skeleton.animated_joints):\n        if j not in joints:\n            continue\n        if j == skeleton.root:\n            dest = 0\n            c[:3] = a[dest:dest+3] + delta[o:o+3]\n            q_dest = dest+3\n            q_o = o+3\n            q_a = a[q_dest:q_dest + 4]\n            q_delta = delta[q_o:q_o + 4]\n\n            q_prod = quaternion_multiply(q_a, q_delta)\n            c[q_dest:q_dest + 4] = q_prod / np.linalg.norm(q_prod)\n            o += 7\n        else:\n            dest = idx* 4 + 3\n\n            q_a = a[dest:dest + 4]\n            q_delta = delta[o:o + 4]\n\n            q_prod = quaternion_multiply(q_a, q_delta)\n            c[dest:dest + 4] = q_prod / np.linalg.norm(q_prod)\n            o += 4\n    return c\n\ndef substract_frames(skeleton, a, b):\n    \"\"\" returns c = a - b\"\"\"\n    c = np.zeros(len(a))\n    c[:3] = a[:3] - b[:3]\n    for idx, j in enumerate(skeleton.animated_joints):\n        o = idx*4 + 3\n        q_a = a[o:o+4]\n        q_b = b[o:o+4]\n        if np.dot(q_a, q_b) < 0:\n            q_a *= -1\n        q_delta = get_quaternion_delta(q_a, q_b)\n        q_delta = q_delta / np.linalg.norm(q_delta)\n        #dot = np.sum(q_delta)\n        #if dot < 0:\n        #    q_delta = -q_delta\n        c[o:o+4] = q_delta\n    return c\n\n\nclass KeyframeConstraint(object):\n    def __init__(self, frame_idx, joint_name, position, orientation=None, look_at=False, offset=None, look_at_pos=None):\n        self.frame_idx = frame_idx\n        self.joint_name = joint_name\n        self.position = position\n        self.orientation = orientation\n        self.look_at = look_at\n        self.look_at_pos = look_at_pos\n        self.offset = offset # tool offset\n        self.inside_region_position = False\n        self.end_of_region = False\n        self.inside_region_orientation = False\n        self.keep_orientation = False\n\n        # set in case it is a has a relative constraint\n        self.relative_parent_joint_name = None # joint the offsets points from to the target\n        self.relative_offset = None        \n        \n        # tool orientation constraint\n        self.src_tool_cos = None # tool coordinate system\n        self.dest_tool_cos = None # target direction\n        \n        # set a fk chain root to reduce the degrees of freedom \n        self.fk_chain_root = None\n\n    def instantiate_relative_constraint(self, skeleton, frame):\n        \"\"\" turn relative constraint into a normal constraint\"\"\"\n        ppos = skeleton.nodes[self.relative_parent_joint_name].get_global_position(frame)\n        pos = ppos + self.relative_offset\n        return KeyframeConstraint(self.frame_idx, self.joint_name, pos, orientation=self.orientation)\n\n    def evaluate(self, skeleton, frame):\n        if self.orientation is not None:\n            parent_joint = skeleton.nodes[self.joint_name].parent\n            if parent_joint is not None:\n                m = quaternion_matrix(self.orientation)\n                parent_m = parent_joint.get_global_matrix(frame, use_cache=False)\n                local_m = np.dot(np.linalg.inv(parent_m), m)\n                q = quaternion_from_matrix(local_m)\n                idx = skeleton.animated_joints.index(parent_joint.node_name)\n                # idx = skeleton.nodes[c.joint_name].quaternion_frame_index * 4\n                frame[idx:idx + 4] = q\n        if self.offset is not None:\n            m = skeleton.nodes[self.joint_name].get_global_matrix(frame)\n            p = np.dot(m, self.offset)[:3]\n            d = self.position - p\n        else:\n            d = self.position - skeleton.nodes[self.joint_name].get_global_position(frame)\n        return np.dot(d, d)\n\n\nclass MotionEditing(object):\n    def __init__(self, skeleton, ik_settings):\n        self.skeleton = skeleton\n        self._ik_settings = ik_settings\n        self.window = int(self._ik_settings[\"interpolation_window\"])\n        self.transition_window = int(self._ik_settings[\"transition_window\"])\n        self.verbose = False\n        self.use_euler = self._ik_settings[\"use_euler_representation\"]\n        self.solving_method = self._ik_settings[\"solving_method\"]\n        self.success_threshold = self._ik_settings[\"success_threshold\"]\n        self.max_retries = int(self._ik_settings[\"max_retries\"])\n        self.activate_look_at = self._ik_settings[\"activate_look_at\"]\n        self.optimize_orientation = self._ik_settings[\"optimize_orientation\"]\n        self.elementary_action_max_iterations = int(self._ik_settings[\"elementary_action_max_iterations\"])\n        self.elementary_action_epsilon = self._ik_settings[\"elementary_action_optimization_eps\"]\n        self.adapt_hands_during_both_hand_carry = self._ik_settings[\"adapt_hands_during_carry_both\"]\n        self.pose = SkeletonPoseModel(self.skeleton, self.use_euler)\n        self._ik = NumericalInverseKinematicsQuat(self.pose, self._ik_settings)\n        self._ik_exp = NumericalInverseKinematicsExp(self.skeleton, self._ik_settings)\n        self._fabrik_chains = dict()\n\n    def add_fabrik_chain(self, joint_name, node_order, activate_constraints=False):\n        self._fabrik_chains[joint_name] = create_fabrik_chain(self.skeleton, self.skeleton.reference_frame, node_order, activate_constraints)\n        \n    def add_constraints_to_skeleton(self, joint_constraints):\n        joint_map = self.skeleton.skeleton_model[\"joints\"]\n        for j in joint_constraints:\n            if j in joint_map:\n                skel_j = joint_map[j]\n            else:\n                continue\n            if skel_j not in self.skeleton.nodes:\n                continue\n            c = joint_constraints[j]\n            if \"stiffness\" in c:\n                self.skeleton.nodes[skel_j].stiffness = c[\"stiffness\"]\n\n            if c[\"type\"] == \"static\":\n                h = JointConstraint()\n                h.is_static = True\n                self.skeleton.nodes[skel_j].joint_constraint = h\n                print(\"add static constraint to\", skel_j)\n            elif c[\"type\"] == \"hinge\":\n                swing_axis = np.array(c[\"swing_axis\"])\n                twist_axis = np.array(c[\"twist_axis\"])\n                deg_angle_range = None\n                if \"k1\" in c and \"k2\" in c:\n                    deg_angle_range = [c[\"k1\"], c[\"k2\"]]\n                print(\"add hinge constraint to\", skel_j)\n                h = HingeConstraint2(swing_axis, twist_axis, deg_angle_range)\n                self.skeleton.nodes[skel_j].joint_constraint = h\n            elif c[\"type\"] == \"ball\":\n                axis = np.array(c[\"axis\"])\n                k = c[\"k\"]\n                print(\"add ball socket constraint to\", skel_j)\n                h = BallSocketConstraint(axis, k)\n                self.skeleton.nodes[skel_j].joint_constraint = h\n            elif c[\"type\"] == \"cone\":\n                axis = np.array(c[\"axis\"])\n                k = c[\"k\"]\n                print(\"add cone constraint to\", skel_j)\n                h = ConeConstraint(axis, k)\n                self.skeleton.nodes[skel_j].joint_constraint = h\n            elif c[\"type\"] == \"shoulder\":\n                axis = np.array(c[\"axis\"])\n                k = c[\"k\"]\n                k1 = c[\"k1\"]\n                k2 = c[\"k2\"]\n                print(\"add shoulder socket constraint to\", skel_j)\n                h = ShoulderConstraint(axis, k, k1, k2)\n                self.skeleton.nodes[skel_j].joint_constraint = h\n            elif c[\"type\"] == \"head\":\n                skel_j = self.skeleton.nodes[skel_j].parent.node_name\n                axis = np.array(c[\"axis\"])\n                tk1 = c[\"tk1\"]\n                tk2 = c[\"tk2\"]\n                sk1 = c[\"sk1\"]\n                sk2 = c[\"sk2\"]\n                print(\"add head constraint to\", skel_j)\n                ref_q = [1,0,0,0] #  TODO get reference and axis from skeleton\n                h = HeadConstraint(ref_q, axis, tk1, tk2, sk1, sk2)\n                h.joint_name = skel_j\n                self.skeleton.nodes[skel_j].joint_constraint = h\n            elif c[\"type\"] == \"spine\":\n                skel_j = self.skeleton.nodes[skel_j].parent.node_name\n                axis = np.array(c[\"axis\"])\n                tk1 = c[\"tk1\"]\n                tk2 = c[\"tk2\"]\n                sk1 = c[\"sk1\"]\n                sk2 = c[\"sk2\"]\n                print(\"add spine constraint to\", skel_j)\n                ref_q = [1,0,0,0] #  TODO get reference and axis from skeleton\n                h = SpineConstraint(ref_q, axis, tk1, tk2, sk1, sk2)\n                h.joint_name = skel_j\n                self.skeleton.nodes[skel_j].joint_constraint = h\n\n    def modify_motion_vector(self, motion_vector):\n        for idx, action_ik_constraints in enumerate(motion_vector.ik_constraints):\n            write_message_to_log(\"Apply IK to elementary action \" + str(idx), LOG_MODE_DEBUG)\n            self._optimize_action_ik_constraints(motion_vector, action_ik_constraints)\n\n    def _optimize_action_ik_constraints(self, motion_vector, action_ik_constraints):\n        i = 0\n        last_error = None\n        keep_running = True\n        trajectory_weights = 1.0\n        # modify individual keyframes based on constraints\n        while keep_running:\n            error = 0.0\n            if \"trajectories\" in list(action_ik_constraints.keys()):\n                constraints = action_ik_constraints[\"trajectories\"]\n                c_error = self._modify_motion_vector_using_trajectory_constraint_list(motion_vector, constraints)\n                error += c_error * trajectory_weights\n            if \"keyframes\" in list(action_ik_constraints.keys()):\n                constraints = action_ik_constraints[\"keyframes\"]\n                error += self._modify_motion_vector_using_keyframe_constraint_list(motion_vector, constraints)\n            if last_error is not None:\n                delta = abs(last_error - error)\n            else:\n                delta = np.inf\n            last_error = error\n            i += 1\n            keep_running = i < self.elementary_action_max_iterations and delta > self.elementary_action_epsilon\n            write_message_to_log(\"IK iteration \" + str(i) + \" \" + str(error) + \" \" + str(delta) + \" \" + str(\n                self.elementary_action_epsilon), LOG_MODE_DEBUG)\n\n    def _modify_motion_vector_using_keyframe_constraint_list(self, motion_vector, constraints):\n        error = 0.0\n        for keyframe, keyframe_constraints in list(constraints.items()):\n            keyframe = int(keyframe)\n            if \"single\" in list(keyframe_constraints.keys()):\n                for c in keyframe_constraints[\"single\"]:\n                    if c.optimize:\n                        if c.frame_range is not None:\n                            error += self._modify_motion_vector_using_keyframe_constraint_range(motion_vector, c,\n                                                                                                c.frame_range)\n                        else:\n                            error += self._modify_frame_using_keyframe_constraint(motion_vector, c, keyframe)\n                    start = keyframe\n                    end = keyframe + 1\n                    if self.activate_look_at and c.look_at:\n                        self._look_at_in_range(motion_vector.frames, c.position, start, end)\n                    print(\"set hand orientation\", c.orientation)\n                    if c.orientation is not None and self.optimize_orientation:\n                        self._set_hand_orientation(motion_vector.frames, c.orientation, c.joint_name, keyframe, start, end)\n        return error\n\n    def _modify_frame_using_keyframe_constraint(self, motion_vector, constraint, keyframe):\n        self.set_pose_from_frame(motion_vector.frames[keyframe])\n        error = self._ik.modify_pose_general(constraint)\n        motion_vector.frames[keyframe] = self.pose.get_vector()\n        if self.window > 0:\n            self.interpolate_around_keyframe(motion_vector.frames, constraint.get_joint_names(), keyframe, self.window)\n        return error\n\n    def _modify_motion_vector_using_keyframe_constraint_range(self, motion_vector, constraint, frame_range):\n        error = 0.0\n        for frame in range(frame_range[0], frame_range[1] + 1):\n            self.set_pose_from_frame(motion_vector.frames[frame])\n            error += self._ik.modify_pose_general(constraint)\n            motion_vector.frames[frame] = self.pose.get_vector()\n\n        self._create_transition_for_frame_range(motion_vector.frames, frame_range[0], frame_range[1],\n                                                self.pose.free_joints_map[constraint.joint_name])\n        return error\n\n    def interpolate_around_keyframe(self, frames, joint_names, keyframe, window):\n        write_message_to_log(\"Smooth and interpolate\" + str(joint_names), LOG_MODE_DEBUG)\n        for target_joint_name in joint_names:\n            joint_parameter_indices = self._extract_free_parameter_indices(self.pose.free_joints_map[target_joint_name])\n            for joint_name in self.pose.free_joints_map[target_joint_name]:\n                smooth_joints_around_transition_using_slerp(frames, joint_parameter_indices[joint_name], keyframe, window)\n\n    def _look_at_in_range(self, frames, position, start, end):\n        start = max(0, start)\n        end = min(frames.shape[0], end)\n        for idx in range(start, end):\n            self.set_pose_from_frame(frames[idx])\n            self.pose.lookat(position)\n            frames[idx] = self.pose.get_vector()\n        self._create_transition_for_frame_range(frames, start, end - 1, [self.pose.head_joint])\n\n    def _create_transition_for_frame_range(self, frames, start, end, target_joints):\n        for target_joint in target_joints:\n            joint_parameter_indices = list(range(*self.pose.extract_parameters_indices(target_joint)))\n            transition_start = max(start - self.transition_window, 0)\n            transition_end = min(end + self.transition_window, frames.shape[0]) - 1\n            create_transition_using_slerp(frames, transition_start, start, joint_parameter_indices)\n            create_transition_using_slerp(frames, end, transition_end, joint_parameter_indices)\n\n    def _set_hand_orientation(self, frames, orientation, joint_name, keyframe, start, end):\n        parent_joint_name = self.pose.get_parent_joint(joint_name)\n        self.set_pose_from_frame(frames[keyframe])\n        self.pose.set_hand_orientation(parent_joint_name, orientation)\n        start = max(0, start)\n        end = min(frames.shape[0], end)\n        self._create_transition_for_frame_range(frames, start, end - 1, [parent_joint_name])\n\n    def set_pose_from_frame(self, reference_frame):\n        self.pose.set_pose_parameters(reference_frame)\n        self.pose.clear_cache()\n\n    def _extract_free_parameter_indices(self, free_joints):\n        \"\"\"get parameter indices of joints from reference frame\n        \"\"\"\n        indices = {}\n        for joint_name in free_joints:\n            indices[joint_name] = list(range(*self.pose.extract_parameters_indices(joint_name)))\n        return indices\n\n    def _modify_motion_vector_using_trajectory_constraint_list(self, motion_vector, constraints):\n        error = 0.0\n        for c in constraints:\n            if c[\"fixed_range\"]:\n                error += self._modify_motion_vector_using_trajectory_constraint(motion_vector, c)\n            else:\n                error += self._modify_motion_vector_using_trajectory_constraint_search_start(motion_vector, c)\n        return error\n\n    def _modify_motion_vector_using_trajectory_constraint(self, motion_vector, traj_constraint):\n        error_sum = 0.0\n        d = traj_constraint[\"delta\"]\n        trajectory = traj_constraint[\"trajectory\"]\n        start_idx = traj_constraint[\"start_frame\"]\n        end_idx = traj_constraint[\"end_frame\"] - 1\n        end_idx = min(len(motion_vector.frames) - 1, end_idx)\n        n_frames = end_idx - start_idx + 1\n        target_direction = None\n        if traj_constraint[\"constrain_orientation\"]:\n            target_direction = trajectory.get_direction()\n            if np.linalg.norm(target_direction) == 0:\n                target_direction = None\n\n        full_length = n_frames * d\n        for idx in range(n_frames):\n            t = (idx * d) / full_length\n            target_position = trajectory.query_point_by_parameter(t)\n            keyframe = start_idx + idx\n            self.set_pose_from_frame(motion_vector.frames[keyframe])\n            error = np.inf\n            iter_counter = 0\n            while error > self.success_threshold and iter_counter < self.max_retries:\n                error = self._ik.modify_pose(traj_constraint[\"joint_name\"], target_position, target_direction)\n                iter_counter += 1\n            error_sum += error\n            motion_vector.frames[keyframe] = self.pose.get_vector()\n        parent_joint = self.pose.get_parent_joint(traj_constraint[\"joint_name\"])\n\n        if traj_constraint[\"joint_name\"] in list(self.pose.free_joints_map.keys()):\n            free_joints = self.pose.free_joints_map[traj_constraint[\"joint_name\"]]\n            free_joints = list(set(free_joints + [parent_joint]))\n        else:\n            free_joints = [parent_joint]\n        self._create_transition_for_frame_range(motion_vector.frames, start_idx, end_idx, free_joints)\n        return error_sum\n\n    def _modify_motion_vector_using_trajectory_constraint_search_start(self, motion_vector, traj_constraint):\n        error_sum = 0.0\n        trajectory = traj_constraint[\"trajectory\"]\n        start_target = trajectory.query_point_by_parameter(0.0)\n        start_idx = self._find_corresponding_frame(motion_vector,\n                                                   traj_constraint[\"start_frame\"],\n                                                   traj_constraint[\"end_frame\"],\n                                                   traj_constraint[\"joint_name\"],\n                                                   start_target)\n        n_frames = traj_constraint[\"end_frame\"]-start_idx + 1\n        arc_length = 0.0\n        self.set_pose_from_frame(motion_vector.frames[start_idx])\n        prev_position = self.pose.evaluate_position(traj_constraint[\"joint_name\"])\n        for idx in range(n_frames):\n            keyframe = start_idx+idx\n            self.set_pose_from_frame(motion_vector.frames[keyframe])\n            current_position = self.pose.evaluate_position(traj_constraint[\"joint_name\"])\n            arc_length += np.linalg.norm(prev_position-current_position)\n            prev_position = current_position\n            if arc_length >= trajectory.full_arc_length:\n                break\n            target = trajectory.query_point_by_absolute_arc_length(arc_length)\n\n            error = np.inf\n            iter_counter = 0\n            while error > self.success_threshold and iter_counter < self.max_retries:\n                error = self._ik.modify_pose(traj_constraint[\"joint_name\"], target)\n                iter_counter += 1\n            error_sum += error\n            motion_vector.frames[keyframe] = self.pose.get_vector()\n\n        self._create_transition_for_frame_range(motion_vector.frames, start_idx, keyframe-1, self.pose.free_joints_map[traj_constraint[\"joint_name\"]])\n        return error_sum\n\n    def _find_corresponding_frame(self, motion_vector, start_idx, end_idx, target_joint, target_position):\n        closest_start_frame = copy(start_idx)\n        min_error = np.inf\n        n_frames = end_idx - start_idx\n        for idx in range(n_frames):\n            keyframe = start_idx + idx\n            self.set_pose_from_frame(motion_vector.frames[keyframe])\n            position = self.pose.evaluate_position(target_joint)\n            error = np.linalg.norm(position - target_position)\n            if error <= min_error:\n                min_error = error\n                closest_start_frame = keyframe\n        return closest_start_frame\n\n    def fill_rotate_events(self, motion_vector):\n        for keyframe in list(motion_vector.keyframe_event_list.keyframe_events_dict[\"events\"].keys()):\n            keyframe = int(keyframe)\n            for event in motion_vector.keyframe_event_list.keyframe_events_dict[\"events\"][keyframe]:\n                if event[\"event\"] == \"rotate\":\n                    self.fill_rotate_event(motion_vector, event)\n\n    def fill_rotate_event(self, motion_vector, event):\n        joint_name = event[\"parameters\"][\"joint\"]\n        orientation = event[\"parameters\"][\"globalOrientation\"]\n        place_keyframe = event[\"parameters\"][\"referenceKeyframe\"]\n        frames = motion_vector.frames[place_keyframe]\n        # compare delta with global hand orientation\n        joint_orientation = motion_vector.skeleton.nodes[joint_name].get_global_matrix(frames)\n        joint_orientation[:3, 3] = [0, 0, 0]\n        orientation_constraint = quaternion_matrix(orientation)\n        delta_orientation = np.dot(np.linalg.inv(joint_orientation), orientation_constraint)\n        euler = np.degrees(euler_from_matrix(delta_orientation))\n        # convert to CAD coordinate system\n        event[\"parameters\"][\"relativeOrientation\"] = [euler[0], -euler[2], euler[1]]\n\n    def generate_zero_frame(self):\n        n_dims = len(self.skeleton.animated_joints) * 4 + 3\n        zero_frame = np.zeros(n_dims)\n        for j in range(len(self.skeleton.animated_joints)):\n            o = j * 4 + 3\n            zero_frame[o:o + 4] = [1, 0, 0, 0]\n        return zero_frame\n\n    def generate_delta_frames(self, frames, constraints, influence_range=40):\n        n_frames = frames.shape[0]\n        zero_frame = self.generate_zero_frame()\n        constrained_frames = list(constraints.keys())\n        delta_frames = collections.OrderedDict()\n        delta_frames[0] = zero_frame\n        delta_frames[1] = zero_frame\n        for f in range(0, n_frames, influence_range):\n            delta_frames[f] = zero_frame\n            delta_frames[f+1] = zero_frame\n        delta_frames[n_frames - 2] = zero_frame\n        delta_frames[n_frames - 1] = zero_frame\n        for frame_idx, frame_constraints in constraints.items():\n            # delete zero frames in range around constraint\n            start = max(frame_idx - influence_range, min(frame_idx, 2))\n            end = min(frame_idx + influence_range, max(frame_idx, n_frames - 2))\n            for i in range(start, end):\n                if i in delta_frames and i not in constrained_frames:\n                    del delta_frames[i]\n\n            frame_constraints = list(frame_constraints.values())\n            exp_frame = self._ik_exp.run(frames[frame_idx], frame_constraints)\n\n            n_dims = len(self.skeleton.animated_joints) * 4 + 3\n            delta_frames[frame_idx] = np.zeros(n_dims)\n            delta_frames[frame_idx][3:] = convert_exp_frame_to_quat_frame(self.skeleton, exp_frame)\n        delta_frames = collections.OrderedDict(sorted(delta_frames.items(), key=lambda x: x[0]))\n        return list(delta_frames.keys()), np.array(list(delta_frames.values()))\n\n    def modify_motion_vector2(self, motion_vector, plot=False):\n        motion_vector.frames = self.edit_motion_using_displacement_map(motion_vector.frames, motion_vector.ik_constraints, plot=plot)\n        self.apply_orientation_constraints(motion_vector.frames, motion_vector.ik_constraints)\n\n    def edit_motion_using_displacement_map(self, frames, constraints, influence_range=40, plot=False):\n        \"\"\" References\n                Witkin and Popovic: Motion Warping, 1995.\n                Bruderlin and Williams: Motion Signal Processing, 1995.\n                Lee and Shin: A Hierarchical Approach to Interactive Motion Editing for Human-like Figures, 1999.\n        \"\"\"\n        d_times, delta_frames = self.generate_delta_frames(frames, constraints, influence_range)\n        return self.add_delta_curve(frames, d_times, delta_frames, plot=plot)\n\n    def get_reduced_frame(self, frame, joint_list):\n        n_dims = len(joint_list)*4\n        if self.skeleton.root in joint_list:\n            n_dims += 3\n        rf = np.zeros(n_dims)\n        o = 0\n        for idx, j in enumerate(self.skeleton.animated_joints):\n            if j not in joint_list:\n                continue\n            if j == self.skeleton.root:\n                src = 0\n                rf[o:o+7] = frame[src:src+7]\n                o+=7\n            else:\n                src = idx * 4 + 3\n                rf[o:o+4] = frame[src:src+4]\n                o+=4\n        return rf\n    \n    def add_delta_curve(self, frames, d_times, delta_frames, plot=False):\n        #print(\"dtimes\", d_times)\n        #print(\"d frames\", delta_frames.tolist())\n        n_frames = len(frames)\n        times = list(range(n_frames))\n        d_curve = CubicMotionSpline.fit_frames(self.skeleton, d_times, delta_frames)\n        new_frames = []\n        for t in times:\n            d_frame = d_curve.evaluate(t)\n            f = add_frames(self.skeleton, frames[t], d_frame)\n            new_frames.append(f)\n        if plot:\n            t = np.linspace(0, n_frames - 1, num=100, endpoint=True)\n            d_curve.plot(t)\n        return np.array(new_frames)\n\n    def add_reduced_delta_curve(self, frames, d_times, delta_frames, joint_list=None, plot=False):\n        #print(\"dtimes\", d_times)\n        #print(\"d frames\", delta_frames.tolist())\n        n_frames = len(frames)\n        times = list(range(n_frames))\n        if joint_list is not None:\n            reduced_delta_frames = []\n            for f in delta_frames:\n                rf = self.get_reduced_frame(f, joint_list)\n                reduced_delta_frames.append(rf)\n            reduced_delta_frames = np.array(reduced_delta_frames)\n        else:\n            reduced_delta_frames = delta_frames\n        d_curve = CubicMotionSpline.fit_frames(self.skeleton, d_times, reduced_delta_frames)\n        new_frames = []\n        if joint_list is None:\n            joint_list = self.skeleton.animated_joints\n        for t in times:\n            d_frame = d_curve.evaluate(t)\n            f = add_reduced_frames(self.skeleton, frames[t], d_frame, joint_list)\n            new_frames.append(f)\n        \n        if plot:\n            t = np.linspace(0, n_frames - 1, num=100, endpoint=True)\n            d_curve.plot(t)\n        return np.array(new_frames)\n\n    def generate_delta_frames_using_ccd(self, frames, constraints, n_max_iter=25, root_joint=None, influence_range=40):\n        n_frames = frames.shape[0]\n        zero_frame = self.generate_zero_frame()\n        constrained_frames = list(constraints.keys())\n        delta_frames = collections.OrderedDict()\n        delta_frames[0] = zero_frame\n        delta_frames[1] = zero_frame\n        joint_list = set()\n        chain_end_joints = dict()\n        for frame_idx, frame_constraints in constraints.items():\n            for joint_name in frame_constraints:\n                if joint_name not in chain_end_joints:\n                    chain_end_joints[joint_name] = root_joint\n                    for j in self.get_fk_chain(joint_name, root_joint):\n                        joint_list.add(j)\n        for f in range(0, n_frames, influence_range):\n            delta_frames[f] = zero_frame\n            delta_frames[f+1] = zero_frame\n        delta_frames[n_frames - 2] = zero_frame\n        delta_frames[n_frames - 1] = zero_frame\n\n\n        for frame_idx, frame_constraints in constraints.items():\n            # delete zero frames in range around constraint\n            start = max(frame_idx - influence_range, min(frame_idx, 2))\n            end = min(frame_idx + influence_range, max(frame_idx, n_frames - 2))\n            for i in range(start, end):\n                if i in delta_frames and i not in constrained_frames:\n                    del delta_frames[i]\n\n            frame_constraints = list(frame_constraints.values())\n            frame_copy = np.array(frames[frame_idx])\n            new_frame = self.skeleton.reach_target_positions(frame_copy, frame_constraints, chain_end_joints, n_max_iter=n_max_iter, verbose=False)\n            delta_frames[frame_idx] = substract_frames(self.skeleton, new_frame, frames[frame_idx])\n        delta_frames = collections.OrderedDict(sorted(delta_frames.items(), key=lambda x: x[0]))\n        return list(delta_frames.keys()), np.array(list(delta_frames.values())), list(joint_list)\n\n    def edit_motion_using_displacement_map_and_ccd(self, frames, constraints, n_max_iter=100, root_joint=None, transition_window=None, plot=False):\n        \"\"\" Apply IK and create a transition using a displacement map\n            References:\n                Witkin and Popovic: Motion Warping, 1995.\n                Bruderlin and Williams: Motion Signal Processing, 1995.\n                Lee and Shin: A Hierarchical Approach to Interactive Motion Editing for Human-like Figures, 1999.\n            Args:\n                frames(np.array): input frames to be modified\n                constraints(list<KeyframeConstraint>): list of constraints\n                n_max_iter(int): optional maximum ik iterations\n                root_joint(str): optional root joint of ik chain\n                transition_window(int): optional blending window size\n                plot(bool): optional plot delta curve\n            Returns:\n                frames(np.array): modifed frames\n        \"\"\"\n        if transition_window is None:\n            transition_window = self.transition_window\n        d_times, delta_frames, joint_list = self.generate_delta_frames_using_ccd(frames, constraints, n_max_iter, root_joint, transition_window)\n        if self.skeleton.skeleton_model is not None and \"joints\" in self.skeleton.skeleton_model and \"neck\" in self.skeleton.skeleton_model[\"joints\"]:\n            joint_name = self.skeleton.skeleton_model[\"joints\"][\"neck\"]\n            if joint_name is not None:\n                joint_list.append(joint_name)\n        return self.add_reduced_delta_curve(frames, d_times, delta_frames, joint_list, plot=plot)\n\n    def apply_orientation_constraints(self, frames, constraints):\n        for frame_idx, frame_constraints in constraints.items():\n            for joint_name, c in frame_constraints.items():\n                if c.orientation is not None and self.optimize_orientation:\n                    start = c.frame_idx\n                    end = c.frame_idx + 1\n                    if self.activate_look_at and c.look_at:\n                        self._look_at_in_range(frames, c.position, start, end)\n                    print(\"set hand orientation\", c.orientation)\n                    self._set_hand_orientation(frames, c.orientation, c.joint_name, c.frame_idx, start, end)\n\n    def edit_motion_using_fabrik(self, frames, constraints):\n        new_frames = np.array(frames)\n        for frame_idx, frame_constraints in constraints.items():\n            joint_names = []\n            fk_nodes = set()\n            for joint_name, c in frame_constraints.items():\n                print(\"use fabrik on\", joint_name, \"at\", frame_idx)\n                if joint_name in self._fabrik_chains:\n                    joint_names += self._fabrik_chains[joint_name].node_order[:1]\n                    new_frame = self._fabrik_chains[joint_name].run_partial_with_constraints(frames[frame_idx], c.position)\n                    new_frames[frame_idx] = new_frame\n                    joint_fk_nodes = self.skeleton.nodes[joint_name].get_fk_chain_list()\n                    fk_nodes.update(joint_fk_nodes)\n\n            if self.window > 0:\n                self.interpolate_around_frame(fk_nodes, new_frames, frame_idx, self.window)\n        return new_frames\n\n    def edit_motion_to_look_at_target(self, frames, look_at_target, spine_target, start_idx, end_idx, orient_spine=False, look_at_dir=LOOK_AT_DIR, spine_look_at_dir=SPINE_LOOK_AT_DIR):\n        if look_at_target is None:\n            return frames\n        spine_joint_name = self.skeleton.skeleton_model[\"joints\"][\"spine_1\"]\n        head_joint_name = self.skeleton.skeleton_model[\"joints\"][\"head\"]\n        self.skeleton.clear_cached_global_matrices()\n        fk_nodes = None\n        for frame_idx in range(start_idx, end_idx):\n            if orient_spine and spine_target is not None:\n                frames[frame_idx] = self.skeleton.look_at_projected(frames[frame_idx], spine_joint_name, spine_target, local_dir=spine_look_at_dir)\n            frames[frame_idx] = self.skeleton.look_at(frames[frame_idx], head_joint_name, look_at_target, n_max_iter=2, local_dir=look_at_dir, chain_end_joint=spine_joint_name)\n            n_joints = len(self.skeleton.animated_joints)\n            fk_nodes = self.skeleton.nodes[head_joint_name].get_fk_chain_list()\n        if fk_nodes is not None:\n            self.interpolate_around_frame(fk_nodes, frames, start_idx, self.window)\n            if end_idx < len(frames):\n                self.interpolate_around_frame(fk_nodes, frames, end_idx, self.window)\n        return frames\n\n    def get_static_joints(self, frame_constraints):\n        static_joints = set()\n        for joint_name, c in frame_constraints.items():\n            if c.inside_region_position:\n                static_joints.add(joint_name)\n        return static_joints\n\n    def find_free_root_joints(self, constraints, joint_chains):\n        \"\"\" check for each joint in the constraints if it is free\"\"\"\n        root_joints = dict()\n        for c in constraints:\n            root_joints[c.joint_name] = None\n            for free_joint in joint_chains[c.joint_name]:\n                is_free = True\n                for joint_name in joint_chains:\n                    if joint_name == c.joint_name:\n                        continue\n                    if free_joint in joint_chains[joint_name]:\n                        is_free = False\n                if not is_free:\n                    root_joints[c.joint_name] = free_joint\n                    print(\"set root joint for \", c.joint_name, \"to\", free_joint)\n                    break\n        return root_joints\n\n    def get_fk_chain(self, joint_name, root_joint):\n        joint_chain = []\n        joint_fk_nodes = self.skeleton.nodes[joint_name].get_fk_chain_list()\n        abort = False\n        if root_joint is not None: # remove root joint\n            for j in joint_fk_nodes:\n                joint_chain.append(j)\n                if abort:\n                    break\n                if j == root_joint:\n                    abort = True\n        else:\n            joint_chain = joint_fk_nodes\n        print(\"copy fk chain\", joint_name, joint_chain)\n        return joint_chain\n\n    def get_active_constraints(self, new_frames, frame_idx, frame_constraints, joint_chain_buffer, prev_static_joints, root_joint):\n        \n        keep_static_joints = True\n        static_joints = self.get_static_joints(frame_constraints)\n        active_constraints = []\n        region_overlaps = []\n        fk_nodes = set()\n        for joint_name, c in frame_constraints.items():\n            copied_joints = False\n            if joint_name not in joint_chain_buffer:\n                j_root_joint = root_joint\n                if c.fk_chain_root is not None:\n                    j_root_joint = c.fk_chain_root\n                joint_chain_buffer[joint_name] = self.get_fk_chain(joint_name, None) # copy entire chain \n            if c.inside_region_position and prev_static_joints == static_joints:\n                #print(\"copy parameters for\", joint_name, len(joint_chain_buffer[joint_name]))\n                #copy guess from previous frame if it is part of a region\n                #print(\"copy parameters\", frame_idx)\n                self.copy_joint_parameters(joint_chain_buffer[joint_name], new_frames, frame_idx - 1, frame_idx)\n                copied_joints = True\n            if not copied_joints or not keep_static_joints:\n                #if c.orientation is not None:\n                #    print(\"use ccd on\", joint_name, \"at\", frame_idx, \" with orientation\")\n                #else:\n                #    print(\"use ccd on\", joint_name, \"at\", frame_idx)\n                active_constraints.append(c)\n                fk_nodes.update(joint_chain_buffer[joint_name])\n                if c.inside_region_position and prev_static_joints != static_joints:\n                    region_overlaps.append(frame_idx)\n        return active_constraints, fk_nodes, region_overlaps, joint_chain_buffer, static_joints\n\n    def edit_motion_using_ccd(self, frames, constraints, n_max_iter=100, root_joint=None, activate_smoothing=True):\n        \"\"\" edit frame parameters using ccd and applying blending\"\"\"\n        \n        new_frames = np.array(frames)\n        joint_chain_buffer = dict()\n        delta_frames = dict()\n        n_frames = len(frames)\n        prev_static_joints = set()\n\n        region_overlaps = []\n        for frame_idx, frame_constraints in constraints.items():\n            active_constraints, fk_nodes, _region_overlaps, joint_chain_buffer, static_joints = self.get_active_constraints(new_frames, frame_idx, frame_constraints, joint_chain_buffer, prev_static_joints, root_joint)\n            region_overlaps += _region_overlaps\n            if len(active_constraints) > 0:\n                #print(\"find free joints at\", frame_idx)\n                if len(static_joints) > 0:\n                    chain_end_joints = self.find_free_root_joints(active_constraints, joint_chain_buffer)\n                elif root_joint is not None:\n                    chain_end_joints = dict()\n                    for c in active_constraints:\n                        chain_end_joints[c.joint_name] = root_joint\n                else:\n                    chain_end_joints = None\n                \n                # init frame with changes from prev frame if it was edited\n                prev_frame_idx = frame_idx-1\n                if prev_frame_idx in delta_frames:\n                    new_frames[frame_idx] = add_frames(self.skeleton, frames[frame_idx], delta_frames[prev_frame_idx])\n                    #print(\"apply delta\",delta_frames[prev_frame_idx])\n\n                new_frame = self.skeleton.reach_target_positions(new_frames[frame_idx], active_constraints, chain_end_joints, n_max_iter=n_max_iter, verbose=False)\n                delta_frames[frame_idx] = substract_frames(self.skeleton,new_frame, frames[frame_idx])\n\n            #  interpolate outside of region constraints\n            is_at_border = self.is_at_constrain_region_border(frame_idx, constraints)\n            if is_at_border and self.window > 0 and len(active_constraints) > 0 and len(fk_nodes) > 0 and activate_smoothing:\n                #print(\"outside of region\", list(prev_static_joints), list(static_joints))\n                fk_nodes = list(fk_nodes)\n                #fk_nodes = self.skeleton.animated_joints\n                self.interpolate_around_frame(fk_nodes, new_frames, frame_idx, self.window)\n                #new_frames = smooth_quaternion_frames(new_frames, frame_idx, self.window, False)\n            prev_static_joints = static_joints\n        if activate_smoothing:\n            for frame_idx in region_overlaps:\n                #print(\"apply transition smoothing\", frame_idx)\n                new_frames = smooth_quaternion_frames(new_frames, frame_idx, self.window, False)\n        return new_frames\n\n    def is_at_constrain_region_border(self, frame_idx, constraints):\n        \"\"\"check if the frame index is at the border of a constrained region \"\"\"\n        prev_frame_unconstrained = True\n        if frame_idx + 1 in constraints:\n            prev_frame_unconstrained = len(constraints[frame_idx+1]) == 0\n        next_frame_unconstrained = True\n        if frame_idx-1 in constraints:\n            next_frame_unconstrained = len(constraints[frame_idx-1]) == 0            \n        return next_frame_unconstrained or prev_frame_unconstrained\n\n    def apply_carry_constraints(self, frames, constraints):\n        print(\"generate carry constraints\")\n        n_frames = frames.shape[0]\n        active_orientations = dict()\n        for frame_idx in range(0, n_frames):\n            # update active orientations\n            if frame_idx in constraints:\n                for joint_name, c in constraints[frame_idx].items():\n                    if c.keep_orientation and c.orientation is not None:\n                        active_orientations[c.joint_name] = c.orientation\n                    elif c.joint_name in active_orientations:\n                        active_orientations[c.joint_name] = None\n                    #else:\n                    #    print(\"no constraint on frame\", frame_idx, c.keep_orientation)\n            # apply active orientations\n            for joint_name in active_orientations:\n                if active_orientations[joint_name] is not None:\n                    #print(\"set orientation for\", joint_name, \"at\", frame_idx)\n                    frames[frame_idx] = self.skeleton.set_joint_orientation(frames[frame_idx], joint_name, active_orientations[joint_name] )\n        return frames\n\n    def set_global_joint_orientations(self, frames, constraints,  frame_offset=0, time_function=None):\n         for c in constraints:\n            if c.constraint_type not in SUPPORTED_CONSTRAINT_TYPES or \"generated\" in c.semantic_annotation.keys():\n                #print(\"skip unsupported constraint\")\n                continue\n            joint_name = c.joint_name\n            start_frame_idx = self.get_global_frame_idx(c.canonical_keyframe, frame_offset, time_function)\n            if c.constrain_orientation_in_region and c.canonical_end_keyframe is not None:\n                end_frame_idx = self.get_global_frame_idx(c.canonical_end_keyframe, frame_offset, time_function)\n                #print(\"apply ik constraint on region\", start_frame_idx, end_frame_idx)\n                for frame_idx in range(start_frame_idx, end_frame_idx):\n                    #print(\"set orientation for\", joint_name, \"at\", frame_idx)\n                    frames[frame_idx] = self.skeleton.set_joint_orientation(frames[frame_idx], joint_name, c.orientation)\n         return frames\n    \n    def get_global_frame_idx(self, mp_frame_idx, frame_offset, time_function):\n        if time_function is not None:\n            frame_idx = frame_offset + int(time_function[mp_frame_idx]) + 1\n        else:\n            frame_idx = frame_offset + int(mp_frame_idx)\n        return frame_idx\n    \n    def set_joint_orientation(self, joint_name, frames, start_idx, end_idx, target_orientation):\n        for frame_idx in range(start_idx, end_idx):\n            frames[frame_idx] = self.skeleton.set_joint_orientation(frames[frame_idx], joint_name, target_orientation)\n\n\n    def copy_joint_parameters(self, nodes, frames, src_idx, dst_idx):\n        for node in nodes:\n            if self.skeleton.nodes[node].quaternion_frame_index == 0:\n                frames[dst_idx][:7] = frames[src_idx][:7]\n            else:\n                o = self.skeleton.nodes[node].quaternion_frame_index * 4 + 3\n                frames[dst_idx][o:o+4] = frames[src_idx][o:o+4]\n\n    def interpolate_around_frame(self, fk_nodes, frames, keyframe, window):\n        print(\"interpolate around frame\", keyframe)\n        for node in fk_nodes:\n            o = self.skeleton.nodes[node].quaternion_frame_index * 4 + 3\n            indices = list(range(o,o+4))\n            smooth_joints_around_transition_using_slerp(frames, indices, keyframe, window)\n\n        #window = 1000\n        #h_window = int(window / 2)\n        #start_idx = max(keyframe - h_window, 0)\n        #end_idx = min(keyframe + h_window, len(frames))\n        #self.apply_joint_constraints(frames, start_idx, end_idx)\n\n    def apply_joint_constraints(self, frames, start_idx, end_idx):\n        return frames\n        #print(\"apply joint constraints in range\", start_idx, end_idx)\n        for frame_idx in range(start_idx, end_idx):\n            frames[frame_idx] = self.skeleton.apply_joint_constraints(frames[frame_idx])\n        return frames\n\n    def resample_motion(self, frames, resample_factor):\n        n_frames = len(frames)\n        times = list(range(0, n_frames))\n        spline = CubicMotionSpline.fit_frames(self.skeleton, times, frames)\n        n_dest_frames = n_frames*resample_factor\n        step_size = (n_frames-1)/n_dest_frames\n        streched_times = np.arange(0,n_frames-1,step_size)\n        #print(streched_times)\n        new_frames = []\n        for t in streched_times:\n            f = spline.evaluate(t)\n            new_frames.append(f)\n        return np.array(new_frames)\n    \n    def copy_joint_values_from_src(self, left_frames, right_frames, joint_list, joint_index_list, src_start, src_end, dest_start, dest_end):\n        n_copied_frames = src_end - src_start\n        n_dest_frames = dest_end - dest_start\n        modified_frames = np.array(right_frames)\n        if n_copied_frames > 1:\n            src_frames = self.stretch_motion(left_frames[src_start:src_end], n_dest_frames)\n        else:\n            src_frames = []\n            for i in range(n_dest_frames):\n                src_frames.append(left_frames[src_start])\n            src_frames = np.array(src_frames)\n        #print(\"copy \", n_copied_frames, n_dest_frames)\n        for frame_idx in range(n_dest_frames):\n            modified_frames[dest_start+frame_idx][joint_index_list] = src_frames[frame_idx][joint_index_list]\n        return modified_frames\n\n    def apply_blending(self, frames, joint_list, joint_index_list, dest_start, dest_end, n_blend_range):\n        n_frames = len(frames)\n        blend_start = max(dest_start- n_blend_range, 0)\n        start_window = dest_start -blend_start\n        blend_end =  min(dest_end +n_blend_range, n_frames-1)\n        end_window = blend_end- dest_end\n         #remove root indices\n        print(\"blend \", dest_start, dest_end, n_blend_range, start_window, end_window)\n        quat_joint_index_list = list(joint_index_list)\n        if self.skeleton.root in joint_list:\n            # apply root smnoothing and remove from index list\n            if start_window > 0:\n                frames = smooth_translation_in_quat_frames(frames, dest_start, start_window)\n            if end_window > 0:\n                frames = smooth_translation_in_quat_frames(frames, dest_end, end_window)\n            for i in range(3):\n                quat_joint_index_list.remove(i)\n        \n        if len(quat_joint_index_list) > 0:\n            o = 0\n            for j in joint_list:\n                q_indices = quat_joint_index_list[o:o+4]\n                if start_window > 0:\n                    frames = create_transition_for_joints_using_slerp(frames, q_indices, blend_start, dest_start, start_window, BLEND_DIRECTION_FORWARD)\n                if end_window > 0:\n                    print(j, q_indices)\n                    frames = create_transition_for_joints_using_slerp(frames, q_indices, dest_end, blend_end, end_window, BLEND_DIRECTION_BACKWARD)\n                o += 4\n        \n        return frames\n\n    def stretch_motion(self, frames, n_dest_frames):\n        n_frames = len(frames)\n        times = list(range(0, n_frames))\n        spline = CubicMotionSpline.fit_frames(self.skeleton, times, frames)\n        step_size = (n_frames-1)/n_dest_frames\n        streched_times = np.arange(0,n_frames-1,step_size)\n        #print(streched_times)\n        new_frames = []\n        for t in streched_times:\n            f = spline.evaluate(t)\n            new_frames.append(f)\n        print(\"new frames\", len(new_frames))\n        return new_frames\n        ", "meta": {"hexsha": "330f2b5ee40fe987ec26e9a98f089df15ad98519", "size": 50682, "ext": "py", "lang": "Python", "max_stars_repo_path": "motion_editing/motion_editing.py", "max_stars_repo_name": "gemlongman/anim_utils", "max_stars_repo_head_hexsha": "8903220fa4fefa17adf608435313f054f8cec08f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-01T01:55:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T01:55:02.000Z", "max_issues_repo_path": "motion_editing/motion_editing.py", "max_issues_repo_name": "gemlongman/anim_utils", "max_issues_repo_head_hexsha": "8903220fa4fefa17adf608435313f054f8cec08f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "motion_editing/motion_editing.py", "max_forks_repo_name": "gemlongman/anim_utils", "max_forks_repo_head_hexsha": "8903220fa4fefa17adf608435313f054f8cec08f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.682, "max_line_length": 217, "alphanum_fraction": 0.6414506136, "include": true, "reason": "import numpy", "num_tokens": 10961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.31069437044942166, "lm_q1q2_score": 0.16625206941061985}}
{"text": "import os\nimport pickle\nimport pandas as pd\nimport numpy as np\n\nimport srpp\n\nfrom CPR import life\nfrom CPR import tools\n\nimport sys\nsys.path.insert(1, 'C:/Users/pyann/Dropbox (CEDIA)/srd/Model')\nimport srd\n\nmodule_dir = os.path.dirname(os.path.dirname(__file__))\npath_params = '/CPR/data/params/'\npath_factors = '/CPR/data/precomputed/'\n\n\nclass CommonParameters:\n    \"\"\"\n    This class sets and contains the parameters common to all households.\n    \n    Parameters\n    ----------\n    nsim: int\n        number of simulations\n    non_stochastic: bool\n        True if non stochastic simulation, False otherwise\n    extra_params: dict\n        dictionary of extra parameters\n    \"\"\"\n    def __init__(self, nsim, non_stochastic, extra_params):\n\n        self.nsim = nsim\n        self.non_stochastic = non_stochastic\n        for file in ['common_params.csv', 'user_options.csv']:\n            tools.add_params_as_attr(self, module_dir + path_params + file)\n        tools.change_params(self, extra_params)\n\n        self.tax = srd.tax(year=self.base_year)\n\n        self.rules_cpp = srpp.rules()\n        self.rules_qpp = srpp.rules(qpp=True)\n\n        for name in ['rrsp', 'tfsa']:\n            self.set_limits(name)\n\n        self.d_ympe = self.prepare_ympe()\n        self.d_perc_cpp = self.prepare_cpp()\n        self.d_perc_rrif = tools.get_params(\n            module_dir + path_params + 'rrif_rates.csv', numerical_key=True)\n\n    def set_limits(self, name):\n        \"\"\"\n        Set contributions limits for RRSP and TFSA.\n\n        Parameters\n        ----------\n        name: str\n            RRSP or TFSA\n        \"\"\"\n        d = {}\n        for year in range(self.base_year, self.base_year + self.future_years):\n            try:\n                d[year] = getattr(self, f'{name}_limit_{year}')\n            except:\n                d[year] = round(d[year-1]\n                                * (1+getattr(self, f'gr_{name}_limit')))\n        setattr(self, f'd_{name}_limit', d)\n\n    def prepare_ympe(self):\n        \"\"\"\"\n        Pre-reform ympe used to adjust DB benefits for CPP\n        \"\"\"\n        d_ympe = tools.get_params(module_dir + path_params + 'ympe.csv',\n                                  numerical_key=True)\n        for year in range(max(d_ympe.keys()) + 1,\n                          self.base_year + self.future_years):\n            d_ympe[year] = round(d_ympe[year-1] * (1 + self.gr_ympe))\n        return d_ympe\n\n    def prepare_cpp(self):\n        \"\"\"\n        Set percentages for cpp/qpp benefits.\n        \"\"\"\n        d_perc_cpp = {year: getattr(self, f'perc_cpp_{year}')\n                      for year in range(2018, 2023)}\n        d_perc_cpp.update(\n            {year: self.perc_cpp_2023\n             for year in range(2023, self.base_year + self.future_years)})\n        return d_perc_cpp\n\n\nclass Prices:\n    \"\"\"\n    This class computes the times series for asset returns,\n    interest rates on debt, deterministic wage profiles,\n    housing price growth rate and price/rent ratio.\n    \n    Parameters\n    ----------\n    common: Common\n        instance of the class Common\n    extra_params: dict\n        dictionary of extra parameters\n    \"\"\"\n    def __init__(self, common, extra_params):\n        tools.add_params_as_attr(self, module_dir + path_params + 'prices.csv')\n        tools.change_params(self, extra_params)\n        np.random.seed(self.seed)\n\n        for asset in ['bills', 'bonds', 'equity', 'business']:\n            ret = self.simulate_ret(asset, common)\n            setattr(self, f'ret_{asset}', ret)\n\n        self.ret_housing, self.price_rent_ratio = self.simulate_housing(common)\n\n        self.d_infl_factors = self.prepare_inflation_factors(common)\n        self.d_interest_debt = self.simulate_interest_debt()\n        self.d_diff_log_wages = self.attach_diff_log_wages()\n\n        if common.recompute_factors:\n            self.d_factors = self.initialize_factors()\n        else:\n            with open(module_dir + path_factors + 'd_factors.pickle', 'rb') as file:\n                self.d_factors = pickle.load(file)\n\n    def simulate_ret(self, asset, common):\n        \"\"\"\n        Simulate N series of length T nominal returns distributed lognormally\n        with autocorrelation rho.\n\n        Parameters\n        ----------\n        asset: str\n            type of asset\n        common: Common\n            instance of the class Common\n\n        Returns\n        -------\n        numpy.array:\n            Array of nominal returns\n        \"\"\"\n        r = np.empty((common.future_years, common.nsim))\n        r[0, :] = getattr(self, f'ret_{asset}_2018')\n        mu = getattr(self, f'mu_{asset}')\n        rho = getattr(self, f'rho_{asset}')\n        sigma = getattr(self, f'sig_{asset}')\n\n        alpha, sig_eps = self.compute_params_process(mu, rho, sigma)\n\n        if common.non_stochastic:\n            for t in range(1, common.future_years):\n                r[t, :] = np.exp(alpha) * (1+r[t-1, :])**rho \\\n                    * np.exp(sig_eps**2/2) - 1\n        else:\n            eps = np.random.normal(loc=0, scale=sig_eps,\n                                   size=(common.future_years, common.nsim))\n            for t in range(1, common.future_years):\n                r[t, :] = np.exp(alpha) * (1+r[t-1, :])**rho \\\n                    * np.exp(eps[t, :]) - 1\n        return (1+r) * (1 + self.inflation_rate) - 1\n\n    def compute_params_process(self, mu, rho, sigma):\n        \"\"\"        \n        Convert arithmetic mean mu and volatility sigma of the returns\n        and autocorrelation rho of the log returns into\n        :math:`\\\\alpha`, :math:`\\\\rho` and :math:`\\\\sigma_{\\\\epsilon}` of the process:\n        \n        :math:`\\\\ln(1+r_t) = \\\\alpha + \\\\rho * \\\\ln(1+r_{t-1}) + \\\\epsilon`,\n        where :math:`\\\\epsilon \\\\sim N(0, \\\\sigma_{\\\\epsilon})`.\n\n        Parameters\n        ----------\n        mu: float\n            arithmetic mean\n        rho: float\n            autocorrelation :math:\n        sigma: float\n            standard deviation\n\n        Returns\n        -------\n        float:\n            AR(1) coefficient (:math:`\\\\alpha`)\n        float:\n            Standard deviation of error term (:math:`\\\\sigma_{\\\\epsilon}`)\n        \"\"\"\n        m, v = (1+mu), sigma**2\n        sig_lognorm = np.sqrt(np.log(1 + v / m**2))\n        mu_lognorm = np.log(m / np.sqrt(1 + v / m**2))\n        alpha = (1-rho) * mu_lognorm\n        sig_eps = np.sqrt(1 - rho**2) * sig_lognorm\n        return alpha, sig_eps\n\n    def simulate_housing(self, common):\n        \"\"\"\n        Simulate series of nominal housing price growth (in :math:`\\\\ln(1+r)` form)\n        and price-rent ratio.\n\n        Parameters\n        ----------\n        common: Common\n            instance of the class Common\n\n        Returns\n        -------\n        numpy.array:\n            Array of nominal housing price growth\n        numpy.array:\n            Array of price-rent ratios\n        \"\"\"\n        r = np.empty((common.future_years, common.nsim))\n        r[0, :] = self.ret_housing_2018\n        rho_r = self.rho_housing\n        alpha_r, sig_eps_r = self.compute_params_process(\n            self.mu_housing, rho_r, self.sig_housing)\n\n        ratio = np.empty_like(r)\n        ratio[0, :] = self.price_rent_2018\n        rho_ratio = self.rho_price_rent\n        alpha_ratio = self.mu_price_rent * (1 - rho_ratio)\n        sig_eps_ratio = np.sqrt(1 - rho_ratio**2) * self.sig_price_rent\n\n        if common.non_stochastic:\n            for t in range(1, common.future_years):\n                r[t, :] = np.exp(alpha_r) * (1 + r[t-1, :])**rho_r \\\n                    * np.exp(sig_eps_r**2/2) - 1\n                ratio[t, :] = alpha_ratio + rho_ratio * ratio[t-1, :]\n        else:\n            cov = sig_eps_r * sig_eps_ratio * self.corr_housing_price_rent\n            m_cov = np.array([[sig_eps_r**2, cov],\n                              [cov, sig_eps_ratio**2]])\n            eps = np.random.multivariate_normal(\n                [0, 0], m_cov, size=(common.future_years, common.nsim))\n            eps_r, eps_ratio = eps[:, :, 0], eps[:, :, 1]\n\n            for t in range(1, common.future_years):\n                r[t, :] = np.exp(alpha_r) * (1+r[t-1, :])**rho_r \\\n                    * np.exp(eps_r[t, :]) - 1\n                ratio[t, :] = alpha_ratio + rho_ratio * ratio[t-1, :] \\\n                    + eps_ratio[t, :]\n        return (1+r) * (1 + self.inflation_rate) - 1, ratio\n\n    def prepare_inflation_factors(self, common):\n        \"\"\"\n        Compute inflation factors with base year 2018.\n\n        Parameters\n        ----------\n        common: Common\n            instance of the class Common\n\n        Returns\n        -------\n        dict:\n            Dictionary of inflation factors for each year\n        \"\"\"\n        start_year = common.base_year - common.past_years\n        end_year = common.base_year + common.future_years\n        # future inflation\n        d_infl_factors = {\n            year: (1 + self.inflation_rate)**(year-common.base_year)\n            for year in range(common.base_year, end_year)}\n        # past inflation\n        d_inflation = tools.get_params(\n            module_dir + path_params + 'inflation.csv', numerical_key=True)\n        for year in reversed(range(start_year, common.base_year)):\n            d_infl_factors[year] = (d_infl_factors[year + 1]\n                                    / (1 + d_inflation[year]))\n        return d_infl_factors\n\n    def simulate_interest_debt(self):\n        \"\"\"\n        Creates N series of yearly nominal interest rate of length T\n        for each type of debt\n\n        Returns\n        -------\n        dict:\n            Dictionary of interest rates by type of debt and year\n        \"\"\"\n        mix_fee_debts = pd.read_csv(\n            module_dir + path_params + \"mix_fee_debt.csv\",\n            usecols=list(range(5)), index_col=0).to_dict('index')\n        # monthly rates:\n        d_interest = {}\n        for debt in mix_fee_debts:\n            d_interest[debt] = (mix_fee_debts[debt]['bills']*self.ret_bills\n                                + mix_fee_debts[debt]['bonds']*self.ret_bonds\n                                + mix_fee_debts[debt]['fee'])\n            d_interest[debt][0] = mix_fee_debts[debt]['value_2018']\n\n        return d_interest\n\n    def attach_diff_log_wages(self):\n        \"\"\"\n        Creates a dictionary of differences in log wages by education and age.\n\n        Returns\n        -------\n        dict:\n            Dictionary of difference in log wages by education and age\n        \"\"\"\n        diff_log_wages = pd.read_csv(\n            module_dir + path_params + 'diff_log_wage.csv', index_col=0)\n        d_diff_log_wages = {}\n        for degree in diff_log_wages.columns:\n            d_diff_log_wages[degree] = np.cumsum(\n                diff_log_wages[degree].values + np.log(1 + self.gr_rate_wage))\n        return d_diff_log_wages\n\n    def initialize_factors(self):\n        \"\"\"\n        This function creates an instance of life.table\n        by gender and province.\n\n        Returns\n        -------\n        dict:\n            dictionary of annuity factors by gender and provinces\n        \"\"\"\n        l_sex = ['male', 'female']\n        l_prov = ['qc', 'on', 'ab', 'bc', 'sk', 'ns', 'nb', 'mb', 'pe', 'nl']\n        d_factors = {}\n        for s in l_sex:\n            d_factors[s] = {}\n            for p in l_prov:\n                d_factors[s][p] = life.table(prov=p, scenario='M',\n                                             gender=s+'s')\n        with open(module_dir + path_factors + 'd_factors.pickle', 'wb') as file:\n            pickle.dump(d_factors, file)\n        return d_factors\n", "meta": {"hexsha": "5f1ee1bde0577b2f8d13bd2a7a267748d3a8a8ba", "size": 11506, "ext": "py", "lang": "Python", "max_stars_repo_path": "CPR/macro.py", "max_stars_repo_name": "rsi-models/CPR", "max_stars_repo_head_hexsha": "2c9e2eb36499e65facd2303f1189101cfd18b267", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CPR/macro.py", "max_issues_repo_name": "rsi-models/CPR", "max_issues_repo_head_hexsha": "2c9e2eb36499e65facd2303f1189101cfd18b267", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CPR/macro.py", "max_forks_repo_name": "rsi-models/CPR", "max_forks_repo_head_hexsha": "2c9e2eb36499e65facd2303f1189101cfd18b267", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.244047619, "max_line_length": 86, "alphanum_fraction": 0.5537980184, "include": true, "reason": "import numpy", "num_tokens": 2745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.30404168127272885, "lm_q1q2_score": 0.16623118694534675}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nschedmaster.py: This code identifies candidates for followup with 12 hours of\nfurther VLA time on FERMI sources, then helps to create a schedule, testing\nthat it's possible. If everything looks good, we send the schedule to the\nto be converted to OPT format and write it to disk. Note that this code serves\nalso as a prototype for the pythonic OPT project. \n\"\"\"\n\n__author__ = \"Seth Bruzewski\"\n__email__ = \"bruzewskis@unm.edu\"\n__license__ = \"GPL\"\n\n# Third Party Modules\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom astropy.coordinates import SkyCoord,Angle,EarthLocation\nfrom astropy.table import Table\nimport astropy.units as u\nfrom scipy.optimize import brentq\n\n# Custom Modules\nfrom SimEVLA import EquitorialToHorizontal as E2H, MotionSimulator\nfrom SimEVLA import PointToPointTime as P2P\nfrom optscheduler import write_OPT\n\ndef block_argsort(ra, dec):\n    '''\n    Sort the sources into blocks of RA, moving up and down in declination. \n    With the name 'argsort' borrowed from numpy, this function returns the\n    indices in the sorted order, allowing for arrays or tables to be resorted\n    easily. \n    \n    Args\n    =======\n    ra (array) - The RA of the sources to be sorted\n    dec (array) - The dec of the sources to be sorted\n    \n    Returns\n    =======\n    new_order (array) - The sorted indices, to be used in sorting objects\n    \n    Raises\n    =======\n    None\n    '''\n    \n    # Divide into hours\n    min_block = min(ra)//30*30\n    max_block = max(ra)//30*30+30\n    num_hours = (max_block - min_block) / 30 # 30 = 2 hr blocks\n    div = np.linspace(min_block, max_block, num_hours+1)\n    \n    # Generate index\n    index = np.arange(len(dec))\n    \n    new_order = np.array([], dtype=int)\n    for i in range(len(div)-1):\n        # Find indices inside RA range\n        inrange = np.logical_and(ra>div[i], ra<=div[i+1])\n        ind = index[inrange]\n        \n        # Sort RA filtered indices by DEC\n        inorder = ind[np.argsort(dec[ind])]\n        \n        # Flip every other one\n        if i%2!=0:\n            inorder = np.flip(inorder)\n        \n        # Append\n        new_order = np.append(new_order, inorder)\n    \n    return new_order\n\ndef plot_sky(sky, show_tour=False):\n    '''\n    From input coordinate pairs expressed in degrees, convert to the\n    appropriate system and plot in a Mollweide projection friendly way.\n    \n    Args\n    =======\n    sky (array) - A (2,N) array of points in RA and DEC to be plotted.\n    show_tour (bool) - If True, plot lines connecting points in order.\n    \n    Returns\n    =======\n    None\n    \n    Raises\n    =======\n    None\n    '''\n    \n    ra = Angle(sky[:,0], unit='deg').wrap_at('180d').rad\n    dec = np.deg2rad(sky[:,1])\n    \n    plt.scatter(ra,dec,s=10)\n    \n    if show_tour:\n        for i in range(len(sky)-1):\n            plt.plot([ra[i],ra[i+1]], [dec[i], dec[i+1]])\n            \n    return None\n    \ndef make_block(data, ramin=None, ramax=None, dcmin=None, dcmax=None):\n    '''\n    Returns a subset of `data` fitting just inside the bounds provided as\n    inputs. Note that because ra is a wrapping coordinate system, some \n    considerations must be made. Namely when we say \"angle a is between amin\n    and amax,\" we mean more specifically \"angle a is counterclockwise of amin\n    and clockwise of amax.\" The sources are downselected using this method,\n    then sorted by their RA and DEC into convenient blocks\n    \n    Args\n    =======\n    data (Table) - The data to be filtered down.\n    ramin (float) - The minimum RA, specified in degrees.\n    ramax (float) - The maximum RA, specified in degrees.\n    dcmin (float) - The minimum Dec, specified in degrees.\n    dcmax (float) - The maximum Dec, specified in degrees.\n    \n    Returns\n    =======\n    outdata (Table) - The input `data` table, filtered and sorted\n    \n    Raises\n    =======\n    None\n    '''\n    \n    # Filter for Valid RA\n    ra = data['RAJ2000']\n    ra_minus = (ra-ramin)%360\n    ra_max_minus = (ramax-ramin)%360\n    ra_inbounds = np.logical_and(ra_minus>0, ra_minus<ra_max_minus)\n    \n    # Filter for Valid Dec\n    dec = data['DEJ2000']\n    dec_inbounds = np.logical_and(dec>dcmin, dec<dcmax)\n    \n    # All sources in bounds\n    inblock = np.logical_and(ra_inbounds, dec_inbounds)\n    \n    # Find coordinates inside requested area\n    inblock_ind = np.nonzero(inblock)[0]\n    ra_inblock = data['RAJ2000'][inblock_ind]\n    dec_inblock = data['DEJ2000'][inblock_ind]\n    \n    # Figure out best place to wrap\n    radmin = np.deg2rad(ramin)\n    radmax = np.deg2rad(ramax)\n    dist = np.arctan2(np.sin(radmax-radmin), np.cos(radmax-radmin))\n    wrap = radmin + dist%(2*np.pi)/2 + np.pi\n    \n    # Wrap at best spot then sort into RA-DEC blocks\n    ra_wrapped = Angle(ra_inblock).wrap_at(wrap*u.rad).deg\n    blocksort_ind = block_argsort(ra_wrapped, dec_inblock)\n    master_ind = inblock_ind[blocksort_ind]\n    \n    # Generate data subset\n    outdata = data[master_ind]\n    \n    return outdata\n\ndef find_nearest_cal(sc, calibrators, config):\n    '''\n    For an input coordinate, returns the nearest high quality VLA calibrator\n    for the specified band and array configuration. \n    \n    Args\n    =======\n    sc (SkyCoord) - The sky coordinate to search around for a calibrator.\n    band (string) - The observational band.\n    config (string) - The observational array configuration.\n    \n    Returns\n    =======\n    best_sc (SkyCoord) - The skycoordinate of the nearest calibrator.\n    name (string) - The J2000 epoch name for the returned calibrator.\n    \n    Raises\n    =======\n    None\n    '''\n    \n    # Narrow down to good quality\n    config_qual = calibrators[config+'_qual']\n    good_qual = np.logical_or(config_qual=='P', config_qual=='S')\n    cals = calibrators[good_qual]\n    \n    # Convert to SkyCoords\n    sc_cals = SkyCoord(cals['ra'], cals['dec'])\n    \n    # Find minimum distance calibrator\n    seps = sc.separation(sc_cals).deg\n    near = np.argmin(seps)\n    best_sc = sc_cals[near]\n    name = cals['name'][near]\n    \n    return best_sc, name\n\ndef worst_setup_slew(az, el):\n    '''\n    This function finds the worst possible setup slew, assuming the telescope\n    begins the observation at the worst possible wrap end. \n    \n    Args\n    =======\n    az (Angle) - The target azimuth of the first source\n    el (Angle) - The target elevation of the first source\n    \n    Returns\n    =======\n    worst_time (Quantity) - The time the worst possible slew will take\n    \n    Raises\n    =======\n    None\n    '''\n    \n    # HARD CODING SLEW SPEEDS\n    vel_az = 40/60 * u.Unit('deg/s')\n    vel_el = 20/60 * u.Unit('deg/s')\n    \n    # HARD CODING WRAP LIMITS\n    az_ends = np.array([-85, 445])\n    el_ends = np.array([0,90])\n    \n    # Figure out max in each direction\n    az_dist = max(abs(az_ends-az.deg)) * u.deg\n    el_dist = max(abs(el_ends-el.deg)) * u.deg\n    \n    time = max([ az_dist/vel_az, el_dist/vel_el])\n    \n    return time\n\ndef to_dur_fmt(t):\n    '''\n    Convert to format duration likes, input is time object\n    '''\n    time_hour = t.to('hour').value\n    time_str = Angle(time_hour, unit=u.hourangle).to_string('h', pad=True)\n    \n    return time_str\n\ndef skyAz(lst, ra, dec):\n    '''\n    Helper function to predict_target. Extrapolates the azimuthal position for\n    a source as a function of LST\n    '''\n    \n    # Let's just assume we're at the VLA\n    vla = EarthLocation.of_site('VLA')\n    ha = Angle(lst*u.hourangle).rad - np.deg2rad(ra)\n    lat = vla.lat.rad\n    dec = np.deg2rad(dec)\n    \n    # Do Trigonometry\n    cosAlt_sinAz = -np.cos(dec)*np.sin(ha)\n    cosAlt_cosAz = np.sin(dec)*np.cos(lat) - np.cos(dec)*np.cos(ha)*np.sin(lat)\n    \n    Az = np.rad2deg(np.arctan2(cosAlt_sinAz,cosAlt_cosAz))%360\n    \n    return Az    \n\ndef skyEl(lst, ra, dec):\n    '''\n    Helper function to predict_target. Extrapolates the elevation position for\n    a source as a function of LST\n    '''\n    \n    # Let's just assume we're at the VLA\n    vla = EarthLocation.of_site('VLA')\n    ha = Angle(lst*u.hourangle).rad - np.deg2rad(ra)\n    lat = vla.lat.rad\n    dec = np.deg2rad(dec)\n    \n    # Do Trigonometry\n    sinAlt = np.sin(dec)*np.sin(lat) + np.cos(dec)*np.cos(ha)*np.cos(lat)\n    \n    Alt = np.rad2deg(np.arcsin(sinAlt))\n    \n    return Alt\n\ndef predict_target(tgt_ra, tgt_dec, tel_az, tel_el, lst0):\n    '''\n    Predict the location of the target after the slew, such that we intersect\n    the objects path of motion. This effect will be most severe near zenith.\n    '''\n    # Convert to floats\n    ra = tgt_ra.deg\n    dec = tgt_dec.deg\n    tel_az = tel_az.deg\n    tel_el = tel_el.deg\n    lst0 = lst0.hourangle\n    \n    # Current telescope position and capabilities\n    vel_az = 40/60 * u.Unit('deg/s').to('deg/hour')\n    vel_el = 20/60 * u.Unit('deg/s').to('deg/hour')\n    \n    # Azimuth calculations for intercept time\n    az_dir = np.sign( skyAz(lst0, ra, dec) - tel_az)\n    azt = lambda lst_t : tel_az + az_dir * vel_az * (lst_t-lst0)\n    az_func = lambda lst, rr, dd : azt(lst) - skyAz(lst, rr, dd)\n    az_time = brentq(az_func, lst0, lst0+0.5, args=(ra, dec))\n    \n    # Elevation calculations for intercept time\n    el_dir = np.sign( skyEl(lst0, ra, dec) - tel_el)\n    elt = lambda lst_t : tel_el + el_dir * vel_el * (lst_t-lst0)\n    el_func = lambda lst, rr, dd : elt(lst) - skyEl(lst, rr, dd)\n    el_time = brentq(el_func, lst0, lst0+0.5, args=(ra, dec))\n    \n    # Final coordinates\n    worst_time = max([az_time, el_time])\n    azf = skyAz(worst_time, ra, dec)\n    elf = skyEl(worst_time, ra, dec)\n    azf_ang = Angle(azf*u.deg)\n    elf_ang = Angle(elf*u.deg)\n    \n    return azf_ang, elf_ang\n\ndef schedule_block(block, mosaics, source_scan=280, cal_scan=300, \n                   ha_offset=0, verbose=True, config='A', wrap_pref=None):\n    '''\n    For input points and start LST, run a simulated observation to see if \n    the particular schedule is possible. This will produce some figures\n    displaying the hour angle and elevation of the telescope over time, \n    highlighting in particular any areas where the telescope would go beyond\n    certian limits. The function returns the total time the observation would\n    take\n    \n    Args\n    =======\n    block (Table) - Target list in the FERMI format. The needed columns are \n        essentially just RAJ2000, DEJ2000, and Source_Name.\n    mosaics (dict) - The mosaic dictionary maping each source name to its\n        mosaic coordinates\n    source_scan (float/Quantity) - The amount of time to spend on each \n        pointing. Default value is 30 and default units are seconds.\n    cal_scan (float/Quantity) - The amount of time to spend on phase\n        calibrators. Default value is 60 and default units are seconds.\n    ha_offset (Quantity) - The hour angle of the first source when the\n        observation will begin. For instance, if RA[0]=1h and ha_offset=-1h,\n        then the observation will start at LST=0h. Defaults to 0h, such that\n        things start when the first source is on the meridian. Default units\n        are hourangle\n    verbose (bool) - Whether to generate HA and El plots of the projected\n        schedule and produce explanatory text.\n    band (string) - The band which the observation will be performed in. This\n        is used to search for calibrators.\n    config (string) - The array configuration when the observation will be\n        performed. This is used to search for calibrators.\n    \n    Returns\n    =======\n    sched_table (Table) - A table summarizing the observation. If the user\n        likes how it went, this table can be passed to OPTSCHEDULER for\n        formatting.\n    \n    Raises\n    =======\n    None\n    '''\n    \n    ############### SET UP STUFF ###############\n    # Check units\n    if not isinstance(source_scan, u.Quantity):\n        source_scan *= u.s\n    if not isinstance(cal_scan, u.Quantity):\n        cal_scan *= u.s\n    if not isinstance(ha_offset, u.Quantity):\n        ha_offset *= u.hourangle\n        \n    if wrap_pref is None:\n        wrap_pref = ''\n    \n    # Define the coherence time manually\n    \n    # Convenience function for sc->str\n    sc_to_ra = lambda sc:sc.ra.to_string('h', sep=':', pad=True)\n    sc_to_dc = lambda sc:sc.dec.to_string('deg', sep=':', pad=True, \n                                          alwayssign=True)\n    \n    # Convenience function for time->ang\n    time_to_ang = lambda t : Angle(t.to('s').value/3600, unit=u.hourangle)\n    \n    # Convenience function for formatting LST angle\n    lst_to_str = lambda lsti : lsti.to_string('h',sep=':',pad=True)[:8]\n    \n    \n    ############### INITIALIZE TIMEKEEPING ###############\n    # Figure out when to start\n    tgt0 = SkyCoord(block['RAJ2000'][0]*u.deg, block['DEJ2000'][0]*u.deg)\n    lst0 = tgt0.ra + ha_offset\n    lst0_str = lst0.wrap_at('360d').to_string(u.hourangle, sep=':') #for print\n    \n    # This will keep a running track of time\n    lst = lst0.wrap_at('360d') # initialize\n    total_time = 0*u.s\n    \n    ############### DETERMINE BEST CALIBRATOR ###############\n    # Values for best flux cal\n    best_flux_name = 'Cygnus A'\n    best_flux_sc = SkyCoord('19h59m28.34s', '40d44\\'02.12\"')\n    best_flux_az, best_flux_el = E2H(best_flux_sc.ra, best_flux_sc.dec, lst)\n    \n    # What is the worst possible slew we might have to do\n    worst_slew = worst_setup_slew(best_flux_az, best_flux_el)\n    setup_atten = 1*u.min\n    setup_req = 30*u.s\n    slew_target = P2P(best_flux_sc, tgt0, lst0)\n    scan_tgt = 10*u.min\n    \n    # Calculate length of setup slew\n    setup_slew = worst_slew - setup_atten - setup_req\n    \n    # Figure out delays to apply to lst0 for flux cal\n    delay_slew = worst_slew + scan_tgt + slew_target\n    delay_atten = setup_atten + setup_req + scan_tgt + slew_target\n    delay_req = setup_req + scan_tgt + slew_target\n    delay_tgt = scan_tgt + slew_target\n    \n    ############### SETUP SCANS ###############\n    # Define scheduler keeper\n    sched = []\n    \n    # Slew scan\n    start_lst = lst0 - time_to_ang(delay_slew)\n    end_lst = lst0 - time_to_ang(delay_atten)\n    start_az, start_el = E2H(best_flux_sc.ra, best_flux_sc.dec, start_lst)\n    end_az, end_el = E2H(best_flux_sc.ra, best_flux_sc.dec, end_lst)\n    start_ha = (start_lst-best_flux_sc.ra).wrap_at('180d')\n    end_ha = (end_lst-best_flux_sc.ra).wrap_at('180d')\n    slew_line = {'scanName': 'slew',\n                 'sourceName': best_flux_name,\n                 'resourceName': 'X band pointing',\n                 'timeType': 'DUR',\n                 'time': to_dur_fmt(setup_slew),\n                 'antennaWrap': wrap_pref,\n                 'applyRefPtg': 'N',\n                 'applyPhase': 'N',\n                 'recordOnMark5': 'N',\n                 'allowOverTop': 'N',\n                 'use10HzNoise': 'Y',\n                 'scanIntents': 'SetAtnGain,',\n                 'comments': '',\n                 'ra': sc_to_ra(best_flux_sc),\n                 'dec': sc_to_dc(best_flux_sc),\n                 'start_lst': lst_to_str(start_lst.wrap_at('360d')),\n                 'end_lst': lst_to_str(end_lst.wrap_at('360d')),\n                 'start_az': start_az.deg,\n                 'end_az': end_az.deg,\n                 'start_el': start_el.deg,\n                 'end_el': end_el.deg,\n                 'start_ha': start_ha.hourangle,\n                 'end_ha': end_ha.hourangle,\n                 'errors': 0}\n    sched.append(slew_line)\n    \n    # Atten scan\n    start_lst = end_lst\n    end_lst = lst0 - time_to_ang(delay_req)\n    start_az, start_el = end_az, end_el\n    end_az, end_el = E2H(best_flux_sc.ra, best_flux_sc.dec, end_lst)\n    start_ha = (start_lst-best_flux_sc.ra).wrap_at('180d')\n    end_ha = (end_lst-best_flux_sc.ra).wrap_at('180d')\n    atten_line = {'scanName': 'atten',\n                  'sourceName': best_flux_name,\n                  'resourceName': 'L16f3B',\n                  'timeType': 'DUR',\n                  'time': to_dur_fmt(setup_atten),\n                  'antennaWrap': wrap_pref,\n                  'applyRefPtg': 'N',\n                  'applyPhase': 'N',\n                  'recordOnMark5': 'N',\n                  'allowOverTop': 'N',\n                  'use10HzNoise': 'Y',\n                  'scanIntents': 'SetAtnGain,',\n                  'comments': '',\n                  'ra': sc_to_ra(best_flux_sc),\n                  'dec': sc_to_dc(best_flux_sc),\n                  'start_lst': lst_to_str(start_lst.wrap_at('360d')),\n                  'end_lst': lst_to_str(end_lst.wrap_at('360d')),\n                  'start_az': start_az.deg,\n                  'end_az': end_az.deg,\n                  'start_el': start_el.deg,\n                  'end_el': end_el.deg,\n                  'start_ha': start_ha.hourangle,\n                  'end_ha': end_ha.hourangle,\n                  'errors': 0}\n    sched.append(atten_line)\n    \n    # Req scan\n    start_lst = end_lst\n    end_lst = lst0 - time_to_ang(delay_tgt)\n    start_az, start_el = end_az, end_el\n    end_az, end_el = E2H(best_flux_sc.ra, best_flux_sc.dec, end_lst)\n    start_ha = (start_lst-best_flux_sc.ra).wrap_at('180d')\n    end_ha = (end_lst-best_flux_sc.ra).wrap_at('180d')\n    req_line = {'scanName': 'req',\n                'sourceName': best_flux_name,\n                'resourceName': 'L16f3B',\n                'timeType': 'DUR',\n                'time': to_dur_fmt(setup_req),\n                'antennaWrap': wrap_pref,\n                'applyRefPtg': 'N',\n                'applyPhase': 'N',\n                'recordOnMark5': 'N',\n                'allowOverTop': 'N',\n                'use10HzNoise': 'Y',\n                'scanIntents': 'SetAtnGain,',\n                'comments': '',\n                'ra': sc_to_ra(best_flux_sc),\n                'dec': sc_to_dc(best_flux_sc),\n                'start_lst': lst_to_str(start_lst.wrap_at('360d')),\n                'end_lst': lst_to_str(end_lst.wrap_at('360d')),\n                'start_az': start_az.deg,\n                'end_az': end_az.deg,\n                'start_el': start_el.deg,\n                'end_el': end_el.deg,\n                'start_ha': start_ha.hourangle,\n                'end_ha': end_ha.hourangle,\n                'errors': 0}\n    sched.append(req_line)\n    \n    # Flux target scan\n    start_lst = end_lst\n    end_lst = lst0 - time_to_ang(slew_target)\n    start_az, start_el = end_az, end_el\n    end_az, end_el = E2H(best_flux_sc.ra, best_flux_sc.dec, end_lst)\n    start_ha = (start_lst-best_flux_sc.ra).wrap_at('180d')\n    end_ha = (end_lst-best_flux_sc.ra).wrap_at('180d')\n    flux_tgt_line = {'scanName': '',\n                     'sourceName': best_flux_name,\n                     'resourceName': 'L16f3B',\n                     'timeType': 'DUR',\n                     'time': to_dur_fmt(scan_tgt),\n                     'antennaWrap': wrap_pref,\n                     'applyRefPtg': 'N',\n                     'applyPhase': 'N',\n                     'recordOnMark5': 'N',\n                     'allowOverTop': 'N',\n                     'use10HzNoise': 'Y',\n                     'scanIntents': 'CalBP,CalFlux,',\n                     'comments': '',\n                     'ra': sc_to_ra(best_flux_sc),\n                     'dec': sc_to_dc(best_flux_sc),\n                     'start_lst': lst_to_str(start_lst.wrap_at('360d')),\n                     'end_lst': lst_to_str(end_lst.wrap_at('360d')),\n                     'start_az': start_az.deg,\n                     'end_az': end_az.deg,\n                     'start_el': start_el.deg,\n                     'end_el': end_el.deg,\n                     'start_ha': start_ha.hourangle,\n                     'end_ha': end_ha.hourangle,\n                     'errors': 0}\n    sched.append(flux_tgt_line)\n    \n    \n    ############### RUN SIMULATION ###############\n    # Initialize at defaults\n    if wrap_pref == 'CCW':\n        w = 'COUNTERCLOCKWISE'\n    elif wrap_pref == 'CW':\n        w = 'CLOCKWISE'\n    else:\n        w = None\n    sim = MotionSimulator(end_az, end_el, wrap=w)\n    \n    # Run Simulation\n    for i in range(len(block)):\n        # Grab mosaic coordinates\n        fname = block['Source_Name'][i]\n        mosi = mosaics[fname]\n        \n        # Generate some names and notes\n        b26 = lambda n : chr(97+n//26) + chr(97+n%26)\n        names = [ fname+b26(n) for n in range(len(mosi)) ]\n        intents = ['ObsTgt']*len(mosi)\n        dur = [source_scan]*len(mosi)\n            \n        # Prepend a calibrator\n        csc = SkyCoord('21h04m06.937s', '+76d33\\'10.41\"')\n        cname = '3C427.1'\n        cal_arr = np.array([[csc.ra.deg, csc.dec.deg]])\n        \n        # Prepend calibrator\n        mosi = np.concatenate((cal_arr, mosi), axis=0)\n        names.insert(0, cname)\n        intents.insert(0, 'CalGain')\n        dur.insert(0, cal_scan)\n            \n        if i==len(block)-1:\n            mosi = np.concatenate((mosi, cal_arr), axis=0)\n            names.append(cname)\n            intents.append('CalGain')\n            dur.append(cal_scan)\n        \n        for j in range(len(mosi)):\n            # Move to a new spot on sky\n            scj = SkyCoord(mosi[j][0]*u.deg, mosi[j][1]*u.deg)\n            \n            # Trying something new\n            current_az = sim.getCurrentAntennaAzimuth()\n            current_el = sim.getCurrentAntennaElevation()\n            azj, elj = predict_target(scj.ra, scj.dec, current_az, \n                                        current_el, lst)\n            \n            # Move to predicted position\n            slew = sim.moveTo(azj, elj, wrap=w)\n            \n            # Convert slew time to an angle\n            slew_ang = time_to_ang(slew)\n            scan = dur[j] + 1*u.s\n            scan_ang = time_to_ang(scan)\n            \n            # Record new time\n            start_lst = lst\n            lst += slew_ang + scan_ang\n            total_time += slew + scan\n            \n            # Telescope tracked to new AltAz\n            azj_new, elj_new = E2H(scj.ra, scj.dec, lst)\n            sim.moveTo(azj_new, elj_new, wrap=w)\n            \n            # Num errors\n            num_errors = len(sim.getErrors())\n            \n            # Calculate hour angles for recording\n            start_ha = (start_lst - scj.ra).wrap_at('180d')\n            end_ha = (lst - scj.ra).wrap_at('180d')\n            \n            # Keep track of scan\n            source_line = {'scanName': '',\n                           'sourceName': names[j],\n                           'resourceName': 'L16f3B',\n                           'timeType': 'DUR',\n                           'time': to_dur_fmt(slew+scan),\n                           'antennaWrap': wrap_pref,\n                           'applyRefPtg': 'N',\n                           'applyPhase': 'N',\n                           'recordOnMark5': 'N',\n                           'allowOverTop': 'N',\n                           'use10HzNoise': 'Y',\n                           'scanIntents': intents[j],\n                           'comments': '',\n                           'ra': sc_to_ra(scj),\n                           'dec': sc_to_dc(scj),\n                           'start_lst': lst_to_str(start_lst.wrap_at('360d')),\n                           'end_lst': lst_to_str(lst.wrap_at('360d')),\n                           'start_az': azj.deg,\n                           'end_az': azj_new.deg,\n                           'start_el': elj.deg,\n                           'end_el': elj_new.deg,\n                           'start_ha': start_ha.hourangle,\n                           'end_ha': end_ha.hourangle,\n                           'errors': num_errors}\n            sched.append(source_line)\n            \n    sched_tab = Table(sched)\n        \n    # Display how run went\n    if verbose:\n        # Skip setup scans\n        plot_tab = sched_tab[3:]\n        \n        # Some nice text\n        print('\\n'+'='*25, 'SCHEDULING BLOCK', '='*25+'\\n')\n        verb_str = 'Observing {} sources, starting at LST {}'\n        print(verb_str.format(len(block), lst0_str))\n        print('Flux cal:', best_flux_name)\n        \n        #DELETE ME\n        print('worst slew', worst_slew)\n        \n        times = Angle(plot_tab['time'], unit=u.hourangle).hourangle\n        start_times = np.cumsum(times)\n        \n        # Get errors and calibrators\n        cc = ['C0' if e==0 else 'C3' for e in plot_tab['errors']]\n        calind = ['CalGain' in intn for intn in plot_tab['scanIntents']]\n        cal_times = start_times[calind]\n        \n        # Plot sky\n        plt.figure(figsize=(8,8))\n        ax1 = plt.subplot2grid((5,5), (0,0), rowspan=3, colspan=5, \n                               projection='mollweide')\n        ra = Angle(block['RAJ2000']).wrap_at('180d').rad\n        dec = Angle(block['DEJ2000']).rad\n        ax1.scatter(ra, dec, s=10)\n        for i in range(len(ra)-1):\n            p1 = [ra[i], dec[i]]\n            p2 = [ra[i+1], dec[i+1]]\n            plt.plot([p1[0], p2[0]], [p1[1], p2[1]])\n        ax1.grid(True)\n        \n        # Plot az vs time\n        ax2 = plt.subplot2grid((5,5), (3,0), colspan=3)\n        ax2.scatter(start_times, plot_tab['start_az'], c=cc, s=5)\n        ax2.axhline(85, ls='--', c='g')\n        ax2.axhline(275, ls='--', c='r')\n        for ct in cal_times:\n            ax2.axvline(ct, c='C2', ls='--')\n        ax2.set_ylabel('Hour Angle [hr]')\n        ax2.set_xticklabels([])\n        ax2.set_ylim(-85,445)\n        ax2.grid(True)\n        \n        # Plot El vs time\n        ax3 = plt.subplot2grid((5,5), (4,0), colspan=3)\n        ax3.scatter(start_times, plot_tab['start_el'], c=cc, s=5)\n        ax3.axhline(8, ls='--', c='k')\n        for ct in cal_times:\n            ax3.axvline(ct, c='C2', ls='--')\n        ax3.set_xlabel('Time [hr]')\n        ax3.set_ylabel('Elevation [deg]')\n        ax3.set_ylim(0,90)\n        ax3.grid(True)\n        \n        # Alt-Az map stuff\n        a_az = np.deg2rad(plot_tab['start_az'])\n        r_el = np.cos(np.deg2rad(plot_tab['start_el']))\n        circle = np.linspace(0, 2*np.pi, len(r_el))\n        r_min = np.full_like(r_el, np.cos(np.deg2rad(8)))\n        \n        # Plot alt-az map\n        ax4 = plt.subplot2grid((5,5), (3,3), colspan=2, rowspan=2, polar=True)\n        ax4.scatter(a_az, r_el, s=2)\n        ax4.plot(circle, r_min, 'k--')\n        ax4.plot(np.deg2rad([85,85]), [0,1], ls='--', c='g')\n        ax4.plot(np.deg2rad([-85,-85]), [0,1], ls='--', c='r')\n        ax4.set_ylim(0,1)\n        ax4.set_xticklabels(['N', '', 'E', '', 'S', '', 'W'])\n        ax4.set_yticklabels([])\n        ax4.set_theta_direction(-1)\n        ax4.set_theta_zero_location('N')\n        ax4.grid(True)\n        plt.show()\n        \n    # Just to be safe, clear the sim from memory\n    del sim\n    \n    # Return scheduler\n    return sched_tab\n\ndef time_block(block):\n    tangs = Angle(block['time'], unit=u.hourangle).hourangle\n    diff = sum(tangs)\n    return diff\n    \ndef make_best_block(block, mosaics, haoff, wrap, verbose, \n                    doplots=True):\n    \n    dummy = schedule_block(block, mosaics, ha_offset=haoff, \n                           wrap_pref=wrap, verbose=True)\n    \n    # Figure out what schedules to test\n    width = -1\n    steps = 10\n    ha_range = np.linspace(haoff-width, haoff+width, steps)\n    \n    # Generate schedules\n    sub_blocks = []\n    for ha in ha_range:\n        sblock = schedule_block(block, mosaics, ha_offset=ha, \n                                wrap_pref=wrap, verbose=verbose)\n        sub_blocks.append(sblock)\n        \n    # Some helpful plots, for now\n    if doplots:\n        el_min = [ min(sb['end_el']) for sb in sub_blocks]\n        az_min = [ min(sb['end_az']) for sb in sub_blocks]\n        az_max = [ max(sb['end_az']) for sb in sub_blocks]\n        bl_tme = [ time_block(sb) for sb in sub_blocks]\n        \n        ax1 = plt.subplot2grid((2,2), (0,0))\n        ax1.plot(ha_range, el_min)\n        ax1.axhline(8)\n        ax1.set_ylabel('Min El')\n        \n        ax2 = plt.subplot2grid((2,2), (0,1))\n        ax2.plot(ha_range, az_max)\n        ax2.set_ylabel('Max Az')\n        \n        ax3 = plt.subplot2grid((2,2), (1,1))\n        ax3.plot(ha_range, az_min)\n        ax3.set_ylabel('Min Az')\n        \n        ax4 = plt.subplot2grid((2,2), (1,0))\n        ax4.plot(ha_range, bl_tme)\n        ax4.set_ylabel('Run Time')\n        plt.tight_layout()\n        plt.show()\n    \n    # Copy middle block\n    mid_ind = len(sub_blocks)//2\n    master_block = sub_blocks[mid_ind].copy()\n    \n    # Check that all schedules are similar\n    same_lengths = np.all([ len(s)==len(sub_blocks[0]) for s in sub_blocks])\n    if same_lengths:\n        # Extract max times\n        print('Building out worst time scenario')\n        tangs = Angle( [ sb['time'] for sb in sub_blocks ], unit=u.hourangle)\n        tmaxs = np.max(tangs, axis=0).to_string('h', pad=True)\n        master_block['time'] = tmaxs\n    else:\n        # Warn user if schedules are dissimilar\n        print('ERROR: Could not build worst time scenario')\n    \n    # Time and print for user\n    master_time = time_block(master_block)\n    print('Master block time:', master_time)\n    \n    return master_block\n    \ndef mosaic_new(radius, beamsize=0.0585):\n    '''\n    From input parameters of a FERMI positional uncertianty ellipse, generate\n    a mosaic of beams to completely cover it. The coordinates of the mosaic\n    pointing centers are returned.\n    \n    Args\n    =======\n    ra (float) - The right ascension of the FERMI source\n    dec (float) - The declination of the FERMI source\n    semimaj (float) - The semimajor axis of the FERMI source\n    semimin (float) - The semiminor axis of the FERMI source\n    angle (float) - The angle of the FERMI source, note that by default this\n        is measured clockwise of North, and for our purposes we need it\n        counterclockwise of East.\n    \n    Returns\n    =======\n    mosaic_coords (array) - An numpy array of coordinate points with shape\n        (n,2). Note that the order of these points should amount to a fairly\n        optimized slew path, alternating up and down rows.\n        \n    Raises\n    =======\n    None\n    '''\n    \n    # Figure out how many rows/columns we need\n    ver_bm = np.sqrt(3)/2 * beamsize # scaled to spacing\n    nh = np.ceil(radius/beamsize)\n    nv = np.ceil(radius/ver_bm)//2*2+1 # oddify\n    \n    # Build ranges\n    rangev = np.linspace(-(nv-1)/2, (nv-1)/2, int(nv))\n    \n    coords = []\n    for i in range(int(nv)):\n        # For any row the y will be the same\n        y = np.sqrt(3) * beamsize * rangev[i]\n        \n        # Flips center-like rows\n        # Non-center-like rows shift left, add point on right\n        tnh = nh\n        if i%2==((nv-1)/2)%2:\n            tnh = 1-nh\n        rangeh = np.linspace(-tnh/2, tnh/2, int(abs(tnh)+1))\n            \n        # Loop through points in row\n        for j in range(len(rangeh)):\n            # Calculated x for each point\n            x = 2 * beamsize * rangeh[j]\n            \n            # Record coordinate pair\n            coords.append([x,y])\n            \n    # Arrayify\n    coords = np.array(coords)\n            \n    # Remove any points not inside ellipse + fraction of beam radius\n    fr = 0.8 # Derived -> (arccos(fr) - fr*sqrt(1-fr**2)) = 0.05*pi\n    ewp = radius + fr*beamsize\n    ehp = radius + fr*beamsize\n    inside = (coords[:,0]/ewp)**2+(coords[:,1]/ehp)**2 <= 1\n    coords_in = coords[inside]\n    \n    return coords_in\n\ndef rotate(sc_pnt, sc_shift):\n    if sc_pnt.ndim == 0:\n        sc_pnt = SkyCoord([sc_pnt.ra], [sc_pnt.dec])\n    \n    new_ra = np.zeros(len(sc_pnt))\n    new_dec = np.zeros(len(sc_pnt))\n    for i in range(len(sc_pnt)):\n        pnt_ra = sc_pnt[i].ra\n        pnt_dec = sc_pnt[i].dec\n        \n        ra_shift = sc_shift.ra\n        dec_shift = sc_shift.dec\n        \n        v = np.array([[np.cos(pnt_dec)*np.cos(pnt_ra+ra_shift)],\n                      [np.cos(pnt_dec)*np.sin(pnt_ra+ra_shift)],\n                      [np.sin(pnt_dec)]])\n        \n        uv = np.array([[-np.sin(ra_shift)],\n                      [np.cos(ra_shift)],\n                      [0]])\n        \n        cross_u = np.array([[0, -uv[2][0], uv[1][0]],\n                            [uv[2][0], 0, -uv[0][0]],\n                            [-uv[1][0], uv[0][0], 0]])\n        \n        t1 = np.cos(dec_shift)*np.identity(3)\n        t2 = -np.sin(dec_shift)*cross_u\n        t3 = (1-np.cos(dec_shift))*np.outer(uv,uv)\n        R = t1+t2+t3\n        \n        v_pr = R.dot(v)\n        \n        nra = np.arctan2(v_pr[1][0], v_pr[0][0])\n        ndc = np.arcsin(v_pr[2][0])\n        \n        new_ra[i] = nra.to('deg').value\n        new_dec[i] = ndc.to('deg').value\n    \n    new_sc = SkyCoord(new_ra*u.deg, new_dec*u.deg)\n    \n    if len(new_sc)==1:\n        return new_sc[0]\n    else:\n        return new_sc\n\ndef main():\n    beamsize = 1.1\n    moc = mosaic_new(6, beamsize)\n    scm = SkyCoord(moc[:,0]*u.deg, moc[:,1]*u.deg)\n    scmr = rotate(scm, SkyCoord('0d', '90d'))\n    moc = {'NCP': np.array([scmr.ra.deg, scmr.dec.deg]).T}\n    \n    tgt = Table({'Source_Name': ['NCP']*2, 'RAJ2000':[0]*2 *u.deg, \n                 'DEJ2000':[89.99]*2 *u.deg})\n    \n    \n    plt.scatter(scmr.ra.deg, scmr.dec.deg)\n    plt.xlabel('RA [deg]')\n    plt.ylabel('DEC [deg]')\n    plt.grid()\n    plt.show()\n    \n    \n    # Block list\n    blocks = []\n    has = []\n    \n    # Make block\n    ha1 = -2\n    bestblock1 = make_best_block(tgt, moc, haoff=ha1, wrap='CCW', verbose=False)\n    blocks.append(bestblock1)\n    has.append(ha1)\n    \n    # Write\n    write_OPT(blocks, has)\n    \nmain()", "meta": {"hexsha": "170105d56d324734a3c9ca076f4c69b8c1c4a563", "size": 33271, "ext": "py", "lang": "Python", "max_stars_repo_path": "beta/schedmaster.py", "max_stars_repo_name": "bruzewskis/grote", "max_stars_repo_head_hexsha": "80b2e150f8e2d0027397732369c3cfeadfb742e5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "beta/schedmaster.py", "max_issues_repo_name": "bruzewskis/grote", "max_issues_repo_head_hexsha": "80b2e150f8e2d0027397732369c3cfeadfb742e5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "beta/schedmaster.py", "max_forks_repo_name": "bruzewskis/grote", "max_forks_repo_head_hexsha": "80b2e150f8e2d0027397732369c3cfeadfb742e5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6212278876, "max_line_length": 80, "alphanum_fraction": 0.5615701362, "include": true, "reason": "import numpy,from numpy,from scipy,import astropy,from astropy", "num_tokens": 8952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.3040416686603661, "lm_q1q2_score": 0.16623117555870023}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\" Functions for dealing with the Stagger model photospheres. \"\"\"\n\nfrom __future__ import division, absolute_import, print_function\n\n__author__ = \"Andy Casey <arc@ast.cam.ac.uk>\"\n\nimport logging\nimport numpy as np\n\nfrom .interpolator import BaseInterpolator\n\nlogger = logging.getLogger(__name__)\n\n\nclass Interpolator(BaseInterpolator):\n\n    opacity_scale = \"logtau\"\n\n    def __init__(self, filename, **kwargs):\n        return super(self.__class__, self).__init__(filename, **kwargs)\n\n\ndef pickle_from_tsv_file(filename, depth_scale=\"optical\", skiprows=72,\n    delimiter=\";\"):\n    \"\"\"\n    Pickle the Stagger-grid models from TSV-formatted filename.\n\n    :param filename:\n        The path of the TSV-formatted file.\n\n    :type filename:\n        str\n\n    :param depth_scale: [optional, optical assumed]\n        Which horizontal averaging method to use. Available options are:\n        optical, mass density, Rosseland, or geometric height\n\n    :type depth_scale:\n        str\n\n    :param skiprows: [optional]\n        The number of rows at the top of the file before the header information.\n\n    :type skiprows:\n        int\n\n    :param delimiter: [optional]\n        The delimiting character between columns.\n\n    :type delimiter:\n        str\n    \"\"\"\n\n    depth_scale_hint = depth_scale.lower()[0] # work it out from first letter\n    if depth_scale_hint not in (\"o\", \"m\", \"r\", \"z\", \"g\", \"h\"): # zgh are same \n        raise ValueError(\n            \"depth scale expected to be 'optical', 'mass density', \"\n            \"Rosseland, or geometric height\")\n    if depth_scale_hint in (\"g\", \"h\"):\n        depth_scale_hint = \"z\"\n    elif depth_scale_hint == \"r\":\n        depth_scale_hint = \"R\"\n\n    depth_scale = {\n        \"o\": \"optical\",\n        \"m\": \"mass density\",\n        \"R\": \"Rossland opacity\",\n        \"z\": \"geometric height\",\n    }[depth_scale_hint]\n\n    with open(filename, \"r\") as fp:\n        contents = fp.readlines()[skiprows + 1:]\n    if contents[-1] == \"\\n\": contents.pop(-1)\n\n    # Number of extra columns in each row.\n    n = 4\n\n    # First three lines are for headers\n    names = contents[0].strip().split(delimiter)\n    units = contents[1].strip().split(delimiter)\n    contents = contents[3:]\n\n    num_models = len(set([row.split(delimiter)[n - 1] for row in contents]))\n    parameters = np.nan * np.ones((num_models, n - 1))\n\n    # Assume they all have the same number of depth points.\n    assert (len(contents) % num_models) == 0\n    num_depth_points = int(len(contents) / num_models)\n    num_photospheric_quantitites = len(names) - n\n    photospheres = np.nan * np.ones(\n        (num_models, num_depth_points, num_photospheric_quantitites))\n\n    for i in range(num_models):\n        # The '4:' arises from the first four columns being the model parameters\n        parameters[i, :] = \\\n            map(float, contents[i*num_depth_points].split(delimiter)[:n-1])\n        photospheres[i, :, :] = np.array(\n            [map(float, map(str.strip, _.split(delimiter)[n:])) \\\n                for _ in contents[i*num_depth_points:(i + 1)*num_depth_points]])\n\n    names, units = names[n:], units[n:]\n    # Replace dimensionless columns with \"\" for astropy.\n    \n    # Which depth scale do we want?\n    indices = np.array([0] + [i for i, name in enumerate(names) \\\n        if name.endswith(\"({})\".format(depth_scale_hint))])\n    names = [names[0]] + [names[i][:-3] for i in indices[1:]]\n\n    units = [units[i].replace(\"[-]\", \"\") for i in indices]\n    photospheres = photospheres[:, :, indices]\n\n    meta = {\n        \"kind\": \"Stagger\",\n        \"source_path\": filename,\n        \"horizontal_averaging\": depth_scale,\n        \"photospheric_units\": units\n    }\n    assert np.all(np.isfinite(parameters))\n    assert np.all(np.isfinite(photospheres))\n\n    parameters = np.core.records.fromarrays(parameters.T,\n        names=(\"effective_temperature\", \"surface_gravity\", \"metallicity\"))\n\n    return (parameters, photospheres, names, meta)\n\n\n", "meta": {"hexsha": "b894c8bedad4391965af3a55d32c8dd6012fea09", "size": 3973, "ext": "py", "lang": "Python", "max_stars_repo_path": "smhr_session/photospheres/stagger.py", "max_stars_repo_name": "alexji/smhr-session", "max_stars_repo_head_hexsha": "98cf3dd5da737752e704cffb005f729dfc2711dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-02T09:47:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-02T09:47:31.000Z", "max_issues_repo_path": "smhr_session/photospheres/stagger.py", "max_issues_repo_name": "alexji/smhr-session", "max_issues_repo_head_hexsha": "98cf3dd5da737752e704cffb005f729dfc2711dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-08-24T07:41:22.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-29T15:54:17.000Z", "max_forks_repo_path": "alexmods/smhr/photospheres/stagger.py", "max_forks_repo_name": "alexji/alexmods", "max_forks_repo_head_hexsha": "702f933e717256c0f055288f5f7c7341ac19b126", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5615384615, "max_line_length": 80, "alphanum_fraction": 0.6357915933, "include": true, "reason": "import numpy", "num_tokens": 983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.16618458050925594}}
{"text": "\"\"\"\nAuthor: Joseph(Junzhe) Zhu, 2021/5. Email: josefzhu@stanford.edu / junzhe.joseph.zhu@gmail.com\nFor the original code for the paper[1], please refer to https://github.com/JunzheJosephZhu/MultiDecoder-DPRNN\nDemo Page: https://junzhejosephzhu.github.io/Multi-Decoder-DPRNN/\nMulti-Decoder DPRNN is a method for source separation when the number of speakers is unknown. \nOur contribution is using multiple output heads, with each head modelling a distinct number of source outputs. \nIn addition, we design a selector network which determines which output head to use, i.e. estimates the number of sources. \nThe \"DPRNN\" part of the architecture is orthogonal to our contribution, and can be replaced with any other separator, e.g. Conv/LSTM-TasNet. \nReferences:\n    [1] \"Multi-Decoder DPRNN: High Accuracy Source Counting and Separation\",\n        Junzhe Zhu, Raymond Yeh, Mark Hasegawa-Johnson. https://arxiv.org/abs/2011.12022\n\"\"\"\nimport json\nimport os\nimport numpy as np\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torch.nn.functional import fold, unfold\n\nfrom asteroid import torch_utils\nfrom asteroid.models import BaseModel\nfrom asteroid_filterbanks import make_enc_dec\nfrom asteroid.engine.optimizers import make_optimizer\nfrom asteroid.masknn import activations, norms\nfrom asteroid.masknn.recurrent import DPRNNBlock\nfrom asteroid.models.base_models import _shape_reconstructed, _unsqueeze_to_3d\nfrom asteroid.utils.generic_utils import has_arg\nfrom asteroid.utils.torch_utils import pad_x_to_y, script_if_tracing, jitable_shape\nfrom asteroid.losses import PITLossWrapper, pairwise_neg_sisdr\n\n\ndef make_model_and_optimizer(conf, sample_rate):\n    \"\"\"Function to define the model and optimizer for a config dictionary.\n    Args:\n        conf: Dictionary containing the output of hierachical argparse.\n    Returns:\n        model, optimizer.\n    The main goal of this function is to make reloading for resuming\n    and evaluation very simple.\n    \"\"\"\n    model = MultiDecoderDPRNN(**conf[\"masknet\"], **conf[\"filterbank\"], sample_rate=sample_rate)\n    optimizer = make_optimizer(model.parameters(), **conf[\"optim\"])\n    return model, optimizer\n\n\nclass MultiDecoderDPRNN(BaseModel):\n    \"\"\"Multi-Decoder Dual-Path RNN as proposed in [1].\n\n    Args:\n        n_srcs (list of int): range of possible number of sources\n        bn_chan (int): Number of channels after the bottleneck.\n            Defaults to 128.\n        hid_size (int): Number of neurons in the RNNs cell state.\n            Defaults to 128.\n        chunk_size (int): window size of overlap and add processing.\n            Defaults to 100.\n        hop_size (int or None): hop size (stride) of overlap and add processing.\n            Default to `chunk_size // 2` (50% overlap).\n        n_repeats (int): Number of repeats. Defaults to 6.\n        norm_type (str, optional): Type of normalization to use. To choose from\n            - ``'gLN'``: global Layernorm\n            - ``'cLN'``: channelwise Layernorm\n        mask_act (str, optional): Which non-linear function to generate mask.\n        bidirectional (bool, optional): True for bidirectional Inter-Chunk RNN\n            (Intra-Chunk is always bidirectional).\n        rnn_type (str, optional): Type of RNN used. Choose between ``'RNN'``,\n            ``'LSTM'`` and ``'GRU'``.\n        num_layers (int, optional): Number of layers in each RNN.\n        dropout (float, optional): Dropout ratio, must be in [0,1].\n        kernel_size (int): Length of the filters.\n        n_filters (int): Number of filters / Input dimension of the masker net.\n        stride (int, optional): Stride of the convolution.\n            If None (default), set to ``kernel_size // 2``.\n\n    References\n        [1] \"Multi-Decoder DPRNN: High Accuracy Source Counting and Separation\",\n            Junzhe Zhu, Raymond Yeh, Mark Hasegawa-Johnson. https://arxiv.org/abs/2011.12022\n    \"\"\"\n\n    def __init__(\n        self,\n        n_srcs,\n        bn_chan=128,\n        hid_size=128,\n        chunk_size=100,\n        hop_size=None,\n        n_repeats=6,\n        norm_type=\"gLN\",\n        mask_act=\"sigmoid\",\n        bidirectional=True,\n        rnn_type=\"LSTM\",\n        num_layers=1,\n        dropout=0,\n        kernel_size=16,\n        n_filters=64,\n        stride=8,\n        encoder_activation=None,\n        use_mulcat=False,\n        sample_rate=8000,\n    ):\n        super().__init__(sample_rate=sample_rate)\n        self.encoder_activation = encoder_activation\n        self.enc_activation = activations.get(encoder_activation or \"linear\")()\n        hop_size = hop_size if hop_size is not None else chunk_size // 2\n        self.encoder, _ = make_enc_dec(\n            \"free\",\n            kernel_size=kernel_size,\n            n_filters=n_filters,\n            stride=stride,\n        )\n        # Update in_chan\n        self.masker = DPRNN_MultiStage(\n            in_chan=n_filters,\n            bn_chan=bn_chan,\n            hid_size=hid_size,\n            chunk_size=chunk_size,\n            hop_size=hop_size,\n            n_repeats=n_repeats,\n            norm_type=norm_type,\n            bidirectional=bidirectional,\n            rnn_type=rnn_type,\n            use_mulcat=use_mulcat,\n            num_layers=num_layers,\n            dropout=dropout,\n        )\n        self.decoder_select = Decoder_Select(\n            kernel_size=kernel_size,\n            stride=stride,\n            in_chan=n_filters,\n            n_srcs=n_srcs,\n            bn_chan=bn_chan,\n            chunk_size=chunk_size,\n            hop_size=hop_size,\n            mask_act=mask_act,\n        )\n\n        \"\"\"\n        Args:\n            wav: 2D or 3D Tensor, Tensor of shape $(batch, T)$\n            ground_truth: oracle number of speakers, None or list of $(batch)$ ints \n        Return:\n            reconstructed: torch.Tensor, $(batch, num_stages, max_spks, T)$\n                where max_spks is the maximum possible number of speakers.\n                if training, num_stages=n_repeats; otherwise num_stages=0\n            Speaker dimension is zero-padded for examples with num_spks < max_spks\n        \"\"\"\n\n    def forward(self, wav, ground_truth=None):\n        shape = jitable_shape(wav)\n        # [batch, 1, T]\n        wav = _unsqueeze_to_3d(wav)\n        tf_rep = self.enc_activation(self.encoder(wav))\n        est_masks_list = self.masker(tf_rep)\n        decoded, selector_output = self.decoder_select(\n            est_masks_list, tf_rep, ground_truth=ground_truth\n        )\n        reconstructed = pad_x_to_y(decoded, wav)\n        return _shape_reconstructed(reconstructed, shape), _shape_reconstructed(\n            selector_output, shape\n        )\n\n    def forward_wav(self, wav, slice_size=32000, *args, **kwargs):\n        \"\"\"Separation method for waveforms.\n        Unfolds a full audio into slices, estimate\n        Args:\n            wav (torch.Tensor): waveform array/tensor.\n                Shape: 1D, 2D or 3D tensor, time last.\n        Return:\n            output_cat (torch.Tensor): concatenated output tensor.\n                [num_spks, T]\n        \"\"\"\n        assert not self.training, \"forward_wav is only used for test mode\"\n        T = wav.size(-1)\n        if wav.ndim == 1:\n            wav = wav.reshape(1, wav.size(0))\n        assert wav.ndim == 2  # [1, T]\n        slice_stride = slice_size // 2\n        # pad wav to integer multiple of slice_stride\n        T_padded = max(int(np.ceil(T / slice_stride)), 2) * slice_stride\n        wav = F.pad(wav, (0, T_padded - T))\n        slices = wav.unfold(\n            dimension=-1, size=slice_size, step=slice_stride\n        )  # [1, slice_nb, slice_size]\n        slice_nb = slices.size(1)\n        slices = slices.squeeze(0).unsqueeze(1)\n        tf_rep = self.enc_activation(self.encoder(slices))\n        est_masks_list = self.masker(tf_rep)\n        selector_input = est_masks_list[-1]  # [slice_nb, bn_chan, chunk_size, n_chunks]\n        selector_output = self.decoder_select.selector(selector_input).reshape(\n            slice_nb, -1\n        )  # [slice_nb, num_decs]\n        est_idx, _ = selector_output.argmax(-1).mode()\n        est_spks = self.decoder_select.n_srcs[est_idx]\n        output_wavs, _ = self.decoder_select(\n            est_masks_list, tf_rep, ground_truth=[est_spks] * slice_nb\n        )  # [slice_nb, 1, n_spks, slice_size]\n        output_wavs = output_wavs.squeeze(1)[:, :est_spks, :]\n        # TODO: overlap and add (with division)\n        output_cat = output_wavs.new_zeros(est_spks, slice_nb * slice_size)\n        output_cat[:, :slice_size] = output_wavs[0]\n        start = slice_stride\n        for i in range(1, slice_nb):\n            end = start + slice_size\n            overlap_prev = output_cat[:, start : start + slice_stride].unsqueeze(0)\n            overlap_next = output_wavs[i : i + 1, :, :slice_stride]\n            pw_losses = pairwise_neg_sisdr(overlap_next, overlap_prev)\n            _, best_indices = PITLossWrapper.find_best_perm(pw_losses)\n            reordered = PITLossWrapper.reorder_source(output_wavs[i : i + 1, :, :], best_indices)\n            output_cat[:, start : start + slice_size] += reordered.squeeze(0)\n            output_cat[:, start : start + slice_stride] /= 2\n            start += slice_stride\n        return output_cat[:, :T]\n\n\nclass DPRNN_MultiStage(nn.Module):\n    \"\"\"Implementation of the Dual-Path-RNN model,\n    with multi-stage output, without Conv2D projection\n    \"\"\"\n\n    def __init__(\n        self,\n        in_chan,\n        bn_chan,\n        hid_size,\n        chunk_size,\n        hop_size,\n        n_repeats,\n        norm_type,\n        bidirectional,\n        rnn_type,\n        use_mulcat,\n        num_layers,\n        dropout,\n    ):\n        super(DPRNN_MultiStage, self).__init__()\n        self.in_chan = in_chan\n        self.bn_chan = bn_chan\n        self.hid_size = hid_size\n        self.chunk_size = chunk_size\n        self.hop_size = hop_size\n        self.n_repeats = n_repeats\n        self.norm_type = norm_type\n        self.bidirectional = bidirectional\n        self.rnn_type = rnn_type\n        self.num_layers = num_layers\n        self.dropout = dropout\n        self.use_mulcat = use_mulcat\n\n        layer_norm = norms.get(norm_type)(in_chan)\n        bottleneck_conv = nn.Conv1d(in_chan, bn_chan, 1)\n        self.bottleneck = nn.Sequential(layer_norm, bottleneck_conv)\n\n        # Succession of DPRNNBlocks.\n        self.net = nn.ModuleList([])\n        for i in range(self.n_repeats):\n            self.net.append(\n                DPRNNBlock(\n                    bn_chan,\n                    hid_size,\n                    norm_type=norm_type,\n                    bidirectional=bidirectional,\n                    rnn_type=rnn_type,\n                    use_mulcat=use_mulcat,\n                    num_layers=num_layers,\n                    dropout=dropout,\n                )\n            )\n\n    def forward(self, mixture_w):\n        \"\"\"Forward.\n        Args:\n            mixture_w (:class:`torch.Tensor`): Tensor of shape $(batch, nfilters, nframes)$\n        Returns:\n            list of (:class:`torch.Tensor`): Tensor of shape $(batch, bn_chan, chunk_size, n_chunks)\n        \"\"\"\n        batch, n_filters, n_frames = mixture_w.size()\n        output = self.bottleneck(mixture_w)  # [batch, bn_chan, n_frames]\n        output = unfold(\n            output.unsqueeze(-1),\n            kernel_size=(self.chunk_size, 1),\n            padding=(self.chunk_size, 0),\n            stride=(self.hop_size, 1),\n        )\n        n_chunks = output.shape[-1]\n        output = output.reshape(batch, self.bn_chan, self.chunk_size, n_chunks)\n        # Apply stacked DPRNN Blocks sequentially\n        output_list = []\n        for i in range(self.n_repeats):\n            output = self.net[i](output)\n            output_list.append(output)\n        return output_list\n\n\nclass SingleDecoder(nn.Module):\n    \"\"\"\n    Base decoder module, including the projection layer from (bn_chan) to (n_src * bn_chan).\n    Takes a single example mask and encoding, outputs waveform\n    \"\"\"\n\n    def __init__(\n        self, kernel_size, stride, in_chan, n_src, bn_chan, chunk_size, hop_size, mask_act\n    ):\n        super(SingleDecoder, self).__init__()\n        self.kernel_size = kernel_size\n        self.stride = stride\n        self.in_chan = in_chan\n        self.bn_chan = bn_chan\n        self.chunk_size = chunk_size\n        self.hop_size = hop_size\n        self.n_src = n_src\n        self.mask_act = mask_act\n\n        # Masking in 3D space\n        net_out_conv = nn.Conv2d(bn_chan, n_src * bn_chan, 1)\n        self.first_out = nn.Sequential(nn.PReLU(), net_out_conv)\n        # Gating and masking in 2D space (after fold)\n        self.net_out = nn.Sequential(nn.Conv1d(bn_chan, bn_chan, 1), nn.Tanh())\n        self.net_gate = nn.Sequential(nn.Conv1d(bn_chan, bn_chan, 1), nn.Sigmoid())\n        self.mask_net = nn.Conv1d(bn_chan, in_chan, 1, bias=False)\n\n        # Get activation function.\n        mask_nl_class = activations.get(mask_act)\n        # For softmax, feed the source dimension.\n        if has_arg(mask_nl_class, \"dim\"):\n            self.output_act = mask_nl_class(dim=1)\n        else:\n            self.output_act = mask_nl_class()\n\n        _, self.trans_conv = make_enc_dec(\n            \"free\", kernel_size=kernel_size, stride=stride, n_filters=in_chan\n        )\n\n    def forward(self, output, mixture_w):\n        \"\"\"\n        Args:\n            output: LSTM output, Tensor of shape $(num_stages, bn_chan, chunk_size, n_chunks)$\n            mixture_w: Encoder output, Tensor of shape $(num_stages, in_chan, nframes)\n        outputs:\n            est_wavs: Signal, Tensor of shape $(num_stages, n_src, T)\n        \"\"\"\n        batch, bn_chan, chunk_size, n_chunks = output.size()\n        _, in_chan, n_frames = mixture_w.size()\n        assert self.bn_chan == bn_chan\n        assert self.in_chan == in_chan\n        assert self.chunk_size == chunk_size\n        output = self.first_out(output)\n        output = output.reshape(batch * self.n_src, self.bn_chan, self.chunk_size, n_chunks)\n        # Overlap and add:\n        # [batch, out_chan, chunk_size, n_chunks] -> [batch, out_chan, n_frames]\n        to_unfold = self.bn_chan * self.chunk_size\n        output = fold(\n            output.reshape(batch * self.n_src, to_unfold, n_chunks),\n            (n_frames, 1),\n            kernel_size=(self.chunk_size, 1),\n            padding=(self.chunk_size, 0),\n            stride=(self.hop_size, 1),\n        )\n        # Apply gating\n        output = output.reshape(batch * self.n_src, self.bn_chan, -1)\n        output = self.net_out(output) * self.net_gate(output)\n        # Compute mask\n        score = self.mask_net(output)\n        est_mask = self.output_act(score)\n        est_mask = est_mask.reshape(batch, self.n_src, self.in_chan, n_frames)\n        mixture_w = mixture_w.unsqueeze(1)\n        source_w = est_mask * mixture_w\n        source_w = source_w.reshape(batch * self.n_src, self.in_chan, n_frames)\n        est_wavs = self.trans_conv(source_w)\n        est_wavs = est_wavs.reshape(batch, self.n_src, -1)\n        return est_wavs\n\n\nclass Decoder_Select(nn.Module):\n    \"\"\"Selects which SingleDecoder to use, as well as whether to use multiloss, as proposed in [1]\n    References\n        [1] \"Multi-Decoder DPRNN: High Accuracy Source Counting and Separation\",\n            Junzhe Zhu, Raymond Yeh, Mark Hasegawa-Johnson. https://arxiv.org/abs/2011.12022\n    \"\"\"\n\n    def __init__(\n        self, kernel_size, stride, in_chan, n_srcs, bn_chan, chunk_size, hop_size, mask_act\n    ):\n        super().__init__()\n        self.kernel_size = kernel_size\n        self.stride = stride\n        self.in_chan = in_chan\n        self.n_srcs = n_srcs\n        self.bn_chan = bn_chan\n        self.chunk_size = chunk_size\n        self.hop_size = hop_size\n        self.mask_act = mask_act\n\n        self.n_src2idx = {n_src: i for i, n_src in enumerate(n_srcs)}\n        self.decoders = torch.nn.ModuleList()\n        for n_src in n_srcs:\n            self.decoders.append(\n                SingleDecoder(\n                    kernel_size=kernel_size,\n                    stride=stride,\n                    in_chan=in_chan,\n                    n_src=n_src,\n                    bn_chan=bn_chan,\n                    chunk_size=chunk_size,\n                    hop_size=hop_size,\n                    mask_act=mask_act,\n                )\n            )\n        self.selector = nn.Sequential(\n            nn.Conv2d(bn_chan, in_chan, 1),\n            nn.AdaptiveAvgPool2d(1),\n            nn.ReLU(),\n            nn.Conv2d(in_chan, len(n_srcs), 1),\n        )\n\n    def forward(self, output_list, mixture_w, ground_truth):\n        \"\"\"Forward\n        Args:\n            output_list: list of $(batch, bn_chan, chunk_size, n_chunks)$\n            mixture_w: torch.Tensor, $(batch, in_chan, n_frames)$\n            ground_truth: None, or list of [B] ints, or Long Tensor of $(B)\n                if None, use inferred number of speakers to determine output shape\n        Output:\n            output_wavs: torch.Tensor, $(batch, num_stages, max_spks, T)$\n                where the speaker dimension is padded for examples with num_spks < max_spks\n                if training, num_stages=n_repeats; otherwise, num_stages=1\n            selector_output: output logits from selector module. torch.Tensor, $(batch, num_stages, num_decoders)$\n        \"\"\"\n        batch, bn_chan, chunk_size, n_chunks = output_list[0].size()\n        _, in_chan, n_frames = mixture_w.size()\n        assert self.chunk_size == chunk_size\n        if not self.training:\n            output_list = output_list[-1:]\n        num_stages = len(output_list)\n        # [batch, num_stages, bn_chan, chunk_size, n_chunks]\n        output = torch.stack(output_list, 1).reshape(\n            batch * num_stages, bn_chan, chunk_size, n_chunks\n        )\n        selector_output = self.selector(output).reshape(batch, num_stages, -1)\n        output = output.reshape(batch, num_stages, bn_chan, chunk_size, n_chunks)\n        # [batch, num_stages, in_chan, n_frames]\n        mixture_w = mixture_w.unsqueeze(1).repeat(1, num_stages, 1, 1)\n        if ground_truth is not None:  # oracle\n            decoder_selected = torch.LongTensor([self.n_src2idx[truth] for truth in ground_truth])\n        else:\n            assert num_stages == 1  # can't use select with multistage\n            decoder_selected = selector_output.reshape(batch, -1).argmax(1)\n        T = self.kernel_size + self.stride * (n_frames - 1)\n        output_wavs = torch.zeros(batch, num_stages, max(self.n_srcs), T).to(output.device)\n        for i in range(batch):\n            output_wavs[i, :, : self.n_srcs[decoder_selected[i]], :] = self.decoders[\n                decoder_selected[i]\n            ](output[i], mixture_w[i])\n        return output_wavs, selector_output\n\n\ndef load_best_model(train_conf, exp_dir, sample_rate):\n    \"\"\"Load best model after training.\n\n    Args:\n        train_conf (dict): dictionary as expected by `make_model_and_optimizer`\n        exp_dir(str): Experiment directory. Expects to find\n            `'best_k_models.json'` of `checkpoints` directory in it.\n\n    Returns:\n        nn.Module the best (or last) pretrained model according to the val_loss.\n    \"\"\"\n    # Create the model from recipe-local function\n    model, _ = make_model_and_optimizer(train_conf, sample_rate=sample_rate)\n    try:\n        # Last best model summary\n        with open(os.path.join(exp_dir, \"best_k_models.json\"), \"r\") as f:\n            best_k = json.load(f)\n        best_model_path = min(best_k, key=best_k.get)\n    except FileNotFoundError:\n        # Get last checkpoint\n        all_ckpt = os.listdir(os.path.join(exp_dir, \"checkpoints/\"))\n        all_ckpt = [\n            (ckpt, int(\"\".join(filter(str.isdigit, os.path.basename(ckpt)))))\n            for ckpt in all_ckpt\n            if ckpt.find(\"ckpt\") >= 0\n        ]\n        all_ckpt.sort(key=lambda x: x[1])\n        best_model_path = os.path.join(exp_dir, \"checkpoints\", all_ckpt[-1][0])\n    # Load checkpoint\n    checkpoint = torch.load(best_model_path, map_location=\"cpu\")\n    # Load state_dict into model.\n    model = torch_utils.load_state_dict_in(checkpoint[\"state_dict\"], model)\n    model.eval()\n    return model\n\n\n# Training notes:\n# Weight different stages in accordance with facebook code\nif __name__ == \"__main__\":\n    network = MultiDecoderDPRNN(n_srcs=[2, 3], bn_chan=32, hid_size=32, n_filters=16)\n    # training\n    input = torch.rand(2, 3200)\n    wavs, selector_output = network(input, [3, 2])\n    print(wavs.shape)\n    assert (wavs[1, :, 2] == 0).all()\n    # validation\n    network.eval()\n    wavs, selector_output = network(input)\n    print(wavs.shape)\n    # test\n    input_wav = torch.rand(64351)\n    output_wavs = network.forward_wav(input_wav)\n    print(output_wavs.shape)\n", "meta": {"hexsha": "ae30e99b2ad4b62c956fee9b9f3e872ec1384c3d", "size": 20674, "ext": "py", "lang": "Python", "max_stars_repo_path": "egs/wsj0-mix-var/Multi-Decoder-DPRNN/model.py", "max_stars_repo_name": "ccan1995/asteroid", "max_stars_repo_head_hexsha": "782e95be17b6c16ed2b292d11b9063bf274ca346", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 722, "max_stars_repo_stars_event_min_datetime": "2020-12-01T06:49:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:44:53.000Z", "max_issues_repo_path": "egs/wsj0-mix-var/Multi-Decoder-DPRNN/model.py", "max_issues_repo_name": "ccan1995/asteroid", "max_issues_repo_head_hexsha": "782e95be17b6c16ed2b292d11b9063bf274ca346", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 235, "max_issues_repo_issues_event_min_datetime": "2020-03-02T12:57:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-30T20:11:18.000Z", "max_forks_repo_path": "egs/wsj0-mix-var/Multi-Decoder-DPRNN/model.py", "max_forks_repo_name": "ccan1995/asteroid", "max_forks_repo_head_hexsha": "782e95be17b6c16ed2b292d11b9063bf274ca346", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 176, "max_forks_repo_forks_event_min_datetime": "2020-12-01T00:10:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T10:38:19.000Z", "avg_line_length": 40.537254902, "max_line_length": 141, "alphanum_fraction": 0.6235851795, "include": true, "reason": "import numpy", "num_tokens": 4992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.16614736669545557}}
{"text": "from numba import prange, njit, jit, objmode\nimport logging\nimport numpy as np\n\nfrom tardis.montecarlo.montecarlo_numba.r_packet import (\n    RPacket,\n    PacketStatus,\n)\nfrom tardis.montecarlo.montecarlo_numba.utils import MonteCarloException\n\nfrom tardis.montecarlo.montecarlo_numba.numba_interface import (\n    PacketCollection,\n    VPacketCollection,\n    NumbaModel,\n    numba_plasma_initialize,\n    Estimators,\n    configuration_initialize,\n)\n\nfrom tardis.montecarlo import (\n    montecarlo_configuration as montecarlo_configuration,\n)\n\nfrom tardis.montecarlo.montecarlo_numba.single_packet_loop import (\n    single_packet_loop,\n)\nfrom tardis.montecarlo.montecarlo_numba import njit_dict\nfrom numba.typed import List\nfrom tardis.util.base import update_iterations_pbar, update_packet_pbar\n\n\ndef montecarlo_radial1d(\n    model,\n    plasma,\n    iteration,\n    no_of_packets,\n    total_iterations,\n    show_progress_bars,\n    runner,\n):\n    packet_collection = PacketCollection(\n        runner.input_r,\n        runner.input_nu,\n        runner.input_mu,\n        runner.input_energy,\n        runner._output_nu,\n        runner._output_energy,\n    )\n\n    numba_model = NumbaModel(\n        runner.r_inner_cgs,\n        runner.r_outer_cgs,\n        model.time_explosion.to(\"s\").value,\n    )\n    numba_plasma = numba_plasma_initialize(plasma, runner.line_interaction_type)\n    estimators = Estimators(\n        runner.j_estimator,\n        runner.nu_bar_estimator,\n        runner.j_blue_estimator,\n        runner.Edotlu_estimator,\n    )\n    packet_seeds = montecarlo_configuration.packet_seeds\n\n    number_of_vpackets = montecarlo_configuration.number_of_vpackets\n\n    (\n        v_packets_energy_hist,\n        last_interaction_type,\n        last_interaction_in_nu,\n        last_line_interaction_in_id,\n        last_line_interaction_out_id,\n        virt_packet_nus,\n        virt_packet_energies,\n        virt_packet_initial_mus,\n        virt_packet_initial_rs,\n        virt_packet_last_interaction_in_nu,\n        virt_packet_last_interaction_type,\n        virt_packet_last_line_interaction_in_id,\n        virt_packet_last_line_interaction_out_id,\n    ) = montecarlo_main_loop(\n        packet_collection,\n        numba_model,\n        numba_plasma,\n        estimators,\n        runner.spectrum_frequency.value,\n        number_of_vpackets,\n        packet_seeds,\n        iteration=iteration,\n        show_progress_bars=show_progress_bars,\n        no_of_packets=no_of_packets,\n        total_iterations=total_iterations,\n    )\n\n    runner._montecarlo_virtual_luminosity.value[:] = v_packets_energy_hist\n    runner.last_interaction_type = last_interaction_type\n    runner.last_interaction_in_nu = last_interaction_in_nu\n    runner.last_line_interaction_in_id = last_line_interaction_in_id\n    runner.last_line_interaction_out_id = last_line_interaction_out_id\n\n    if montecarlo_configuration.VPACKET_LOGGING and number_of_vpackets > 0:\n        runner.virt_packet_nus = np.concatenate(\n            np.array(virt_packet_nus)\n        ).ravel()\n        runner.virt_packet_energies = np.concatenate(\n            np.array(virt_packet_energies)\n        ).ravel()\n        runner.virt_packet_initial_mus = np.concatenate(\n            np.array(virt_packet_initial_mus)\n        ).ravel()\n        runner.virt_packet_initial_rs = np.concatenate(\n            np.array(virt_packet_initial_rs)\n        ).ravel()\n        runner.virt_packet_last_interaction_in_nu = np.concatenate(\n            np.array(virt_packet_last_interaction_in_nu)\n        ).ravel()\n        runner.virt_packet_last_interaction_type = np.concatenate(\n            np.array(virt_packet_last_interaction_type)\n        ).ravel()\n        runner.virt_packet_last_line_interaction_in_id = np.concatenate(\n            np.array(virt_packet_last_line_interaction_in_id)\n        ).ravel()\n        runner.virt_packet_last_line_interaction_out_id = np.concatenate(\n            np.array(virt_packet_last_line_interaction_out_id)\n        ).ravel()\n    update_iterations_pbar(1)\n\n\n@njit(**njit_dict)\ndef montecarlo_main_loop(\n    packet_collection,\n    numba_model,\n    numba_plasma,\n    estimators,\n    spectrum_frequency,\n    number_of_vpackets,\n    packet_seeds,\n    iteration,\n    show_progress_bars,\n    no_of_packets,\n    total_iterations,\n):\n    \"\"\"\n    This is the main loop of the MonteCarlo routine that generates packets\n    and sends them through the ejecta.\n\n    Parameters\n    ----------\n    packet_collection : PacketCollection\n    numba_model : NumbaModel\n    estimators : NumbaEstimators\n    spectrum_frequency : astropy.units.Quantity\n        frequency bins\n    number_of_vpackets : int\n        VPackets released per interaction\n    packet_seeds : numpy.array\n    \"\"\"\n    output_nus = np.empty_like(packet_collection.packets_output_nu)\n    last_interaction_types = (\n        np.ones_like(packet_collection.packets_output_nu, dtype=np.int64) * -1\n    )\n    output_energies = np.empty_like(packet_collection.packets_output_nu)\n\n    last_interaction_in_nus = np.empty_like(packet_collection.packets_output_nu)\n    last_line_interaction_in_ids = (\n        np.ones_like(packet_collection.packets_output_nu, dtype=np.int64) * -1\n    )\n    last_line_interaction_out_ids = (\n        np.ones_like(packet_collection.packets_output_nu, dtype=np.int64) * -1\n    )\n\n    v_packets_energy_hist = np.zeros_like(spectrum_frequency)\n    delta_nu = spectrum_frequency[1] - spectrum_frequency[0]\n\n    # Pre-allocate a list of vpacket collections for later storage\n    vpacket_collections = List()\n    for i in range(len(output_nus)):\n        vpacket_collections.append(\n            VPacketCollection(\n                i,\n                spectrum_frequency,\n                montecarlo_configuration.v_packet_spawn_start_frequency,\n                montecarlo_configuration.v_packet_spawn_end_frequency,\n                number_of_vpackets,\n                montecarlo_configuration.temporary_v_packet_bins,\n            )\n        )\n\n    # Arrays for vpacket logging\n    virt_packet_nus = []\n    virt_packet_energies = []\n    virt_packet_initial_mus = []\n    virt_packet_initial_rs = []\n    virt_packet_last_interaction_in_nu = []\n    virt_packet_last_interaction_type = []\n    virt_packet_last_line_interaction_in_id = []\n    virt_packet_last_line_interaction_out_id = []\n\n    for i in prange(len(output_nus)):\n        if show_progress_bars:\n            with objmode:\n                update_amount  = 1\n                update_packet_pbar(\n                    update_amount,\n                    current_iteration=iteration,\n                    no_of_packets=no_of_packets,\n                    total_iterations=total_iterations,\n                )\n\n        if montecarlo_configuration.single_packet_seed != -1:\n            seed = packet_seeds[montecarlo_configuration.single_packet_seed]\n            np.random.seed(seed)\n        else:\n            seed = packet_seeds[i]\n            np.random.seed(seed)\n        r_packet = RPacket(\n            numba_model.r_inner[0],\n            packet_collection.packets_input_mu[i],\n            packet_collection.packets_input_nu[i],\n            packet_collection.packets_input_energy[i],\n            seed,\n            i,\n        )\n        vpacket_collection = vpacket_collections[i]\n\n        loop = single_packet_loop(\n            r_packet, numba_model, numba_plasma, estimators, vpacket_collection\n        )\n        # if loop and 'stop' in loop:\n        #     raise MonteCarloException\n\n        output_nus[i] = r_packet.nu\n        last_interaction_in_nus[i] = r_packet.last_interaction_in_nu\n        last_line_interaction_in_ids[i] = r_packet.last_line_interaction_in_id\n        last_line_interaction_out_ids[i] = r_packet.last_line_interaction_out_id\n\n        if r_packet.status == PacketStatus.REABSORBED:\n            output_energies[i] = -r_packet.energy\n            last_interaction_types[i] = r_packet.last_interaction_type\n        elif r_packet.status == PacketStatus.EMITTED:\n            output_energies[i] = r_packet.energy\n            last_interaction_types[i] = r_packet.last_interaction_type\n\n        vpackets_nu = vpacket_collection.nus[: vpacket_collection.idx]\n        vpackets_energy = vpacket_collection.energies[: vpacket_collection.idx]\n        vpackets_initial_mu = vpacket_collection.initial_mus[\n            : vpacket_collection.idx\n        ]\n        vpackets_initial_r = vpacket_collection.initial_rs[\n            : vpacket_collection.idx\n        ]\n\n        v_packets_idx = np.floor(\n            (vpackets_nu - spectrum_frequency[0]) / delta_nu\n        ).astype(np.int64)\n        # if we're only in a single-packet mode\n        # if montecarlo_configuration.single_packet_seed == -1:\n        #    break\n        for j, idx in enumerate(v_packets_idx):\n            if (vpackets_nu[j] < spectrum_frequency[0]) or (\n                vpackets_nu[j] > spectrum_frequency[-1]\n            ):\n                continue\n            v_packets_energy_hist[idx] += vpackets_energy[j]\n\n    if montecarlo_configuration.VPACKET_LOGGING:\n        for vpacket_collection in vpacket_collections:\n            vpackets_nu = vpacket_collection.nus[: vpacket_collection.idx]\n            vpackets_energy = vpacket_collection.energies[\n                : vpacket_collection.idx\n            ]\n            vpackets_initial_mu = vpacket_collection.initial_mus[\n                : vpacket_collection.idx\n            ]\n            vpackets_initial_r = vpacket_collection.initial_rs[\n                : vpacket_collection.idx\n            ]\n            virt_packet_nus.append(np.ascontiguousarray(vpackets_nu))\n            virt_packet_energies.append(np.ascontiguousarray(vpackets_energy))\n            virt_packet_initial_mus.append(\n                np.ascontiguousarray(vpackets_initial_mu)\n            )\n            virt_packet_initial_rs.append(\n                np.ascontiguousarray(vpackets_initial_r)\n            )\n            virt_packet_last_interaction_in_nu.append(\n                np.ascontiguousarray(\n                    vpacket_collection.last_interaction_in_nu[\n                        : vpacket_collection.idx\n                    ]\n                )\n            )\n            virt_packet_last_interaction_type.append(\n                np.ascontiguousarray(\n                    vpacket_collection.last_interaction_type[\n                        : vpacket_collection.idx\n                    ]\n                )\n            )\n            virt_packet_last_line_interaction_in_id.append(\n                np.ascontiguousarray(\n                    vpacket_collection.last_interaction_in_id[\n                        : vpacket_collection.idx\n                    ]\n                )\n            )\n            virt_packet_last_line_interaction_out_id.append(\n                np.ascontiguousarray(\n                    vpacket_collection.last_interaction_out_id[\n                        : vpacket_collection.idx\n                    ]\n                )\n            )\n\n    packet_collection.packets_output_energy[:] = output_energies[:]\n    packet_collection.packets_output_nu[:] = output_nus[:]\n\n    return (\n        v_packets_energy_hist,\n        last_interaction_types,\n        last_interaction_in_nus,\n        last_line_interaction_in_ids,\n        last_line_interaction_out_ids,\n        virt_packet_nus,\n        virt_packet_energies,\n        virt_packet_initial_mus,\n        virt_packet_initial_rs,\n        virt_packet_last_interaction_in_nu,\n        virt_packet_last_interaction_type,\n        virt_packet_last_line_interaction_in_id,\n        virt_packet_last_line_interaction_out_id,\n    )\n", "meta": {"hexsha": "dbac64d17e190c8874ff05cbacdabc7376899dc8", "size": 11525, "ext": "py", "lang": "Python", "max_stars_repo_path": "tardis/montecarlo/montecarlo_numba/base.py", "max_stars_repo_name": "chirag224/tardis", "max_stars_repo_head_hexsha": "0ed1cb0954dd4dce43fa670f7d6519f0d99650fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tardis/montecarlo/montecarlo_numba/base.py", "max_issues_repo_name": "chirag224/tardis", "max_issues_repo_head_hexsha": "0ed1cb0954dd4dce43fa670f7d6519f0d99650fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2021-03-24T07:53:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-23T15:59:47.000Z", "max_forks_repo_path": "tardis/montecarlo/montecarlo_numba/base.py", "max_forks_repo_name": "chirag224/tardis", "max_forks_repo_head_hexsha": "0ed1cb0954dd4dce43fa670f7d6519f0d99650fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7138554217, "max_line_length": 80, "alphanum_fraction": 0.6636008677, "include": true, "reason": "import numpy,from numba", "num_tokens": 2444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.16614736465546415}}
{"text": "\"\"\"\nWrapper for openquake models.\nCan import without openquake but using openquake models will raise ImportError.\n\"\"\"\nfrom math import exp\n\nimport numpy as np\n\nfrom empirical.util.classdef import TectType, GMM\n\ntry:\n    # openquake constants and models\n    from openquake.hazardlib import const, imt, gsim\n    from openquake.hazardlib.site import Site, SiteCollection\n    from openquake.hazardlib.geo import Point\n\n    OQ = True\nexcept ImportError:\n    # fail silently, only an issue if openquake models wanted\n    OQ = False\n\nSITE_PROPERTIES = [\n    (\"vs30\", \"vs30\"),\n    (\"vs30measured\", \"vs30measured\"),\n    (\"z1pt0\", \"z1p0\"),\n    (\"z2pt5\", \"z2p5\"),\n    (\"fpeak\", \"fpeak\"),\n]\nRUPTURE_PROPERTIES = [\n    (\"mag\", \"Mw\"),\n    (\"rake\", \"rake\"),\n    (\"width\", \"width\"),\n    (\"ztor\", \"ztor\"),\n    (\"hypo_depth\", \"hdepth\"),\n]\nDISTANCE_PROPERTIES = [\n    (\"rrup\", \"Rrup\"),\n    (\"rjb\", \"Rjb\"),\n    (\"rx\", \"Rx\"),\n    (\"ry0\", \"Ry\"),\n    (\"rvolc\", \"Rtvz\"),\n]\n\nOQ_GMM_LIST = [\n    GMM.P_20,\n    GMM.HA_20,\n    GMM.G_17,\n    GMM.BC_16,\n    GMM.S_16,\n    GMM.Ph_20,\n    GMM.Ch_20,\n    GMM.AG_20,\n    GMM.AG_20_NZ,\n    GMM.K_20,\n    GMM.K_20_NZ,\n    GMM.Si_20,\n    GMM.Z_16,\n]\nif OQ:\n    oq_models = {\n        GMM.P_20: {\n            TectType.SUBDUCTION_SLAB: gsim.parker_2020.ParkerEtAl2020SSlab,\n            TectType.SUBDUCTION_INTERFACE: gsim.parker_2020.ParkerEtAl2020SInter,\n        },\n        GMM.HA_20: {\n            TectType.ACTIVE_SHALLOW: gsim.hassani_atkinson_2020.HassaniAtkinson2020Asc,\n            TectType.SUBDUCTION_SLAB: gsim.hassani_atkinson_2020.HassaniAtkinson2020SSlab,\n            TectType.SUBDUCTION_INTERFACE: gsim.hassani_atkinson_2020.HassaniAtkinson2020SInter,\n        },\n        GMM.G_17: {TectType.ACTIVE_SHALLOW: gsim.gulerce_2017.GulerceEtAl2017},\n        GMM.BC_16: {\n            TectType.ACTIVE_SHALLOW: gsim.bozorgnia_campbell_2016.BozorgniaCampbell2016\n        },\n        GMM.S_16: {TectType.ACTIVE_SHALLOW: gsim.stewart_2016_vh.StewartEtAl2016VH},\n        GMM.Ph_20: {\n            TectType.ACTIVE_SHALLOW: gsim.phung_2020.PhungEtAl2020Asc,\n            TectType.SUBDUCTION_SLAB: gsim.phung_2020.PhungEtAl2020SSlab,\n            TectType.SUBDUCTION_INTERFACE: gsim.phung_2020.PhungEtAl2020SInter,\n        },\n        GMM.Ch_20: {\n            TectType.ACTIVE_SHALLOW: gsim.chao_2020.ChaoEtAl2020Asc,\n            TectType.SUBDUCTION_SLAB: gsim.chao_2020.ChaoEtAl2020SSlab,\n            TectType.SUBDUCTION_INTERFACE: gsim.chao_2020.ChaoEtAl2020SInter,\n        },\n        GMM.AG_20: {\n            TectType.SUBDUCTION_SLAB: gsim.abrahamson_gulerce_2020.AbrahamsonGulerce2020SSlab,\n            TectType.SUBDUCTION_INTERFACE: gsim.abrahamson_gulerce_2020.AbrahamsonGulerce2020SInter,\n        },\n        GMM.AG_20_NZ: {\n            TectType.SUBDUCTION_SLAB: gsim.abrahamson_gulerce_2020.AbrahamsonGulerce2020SSlab,\n            TectType.SUBDUCTION_INTERFACE: gsim.abrahamson_gulerce_2020.AbrahamsonGulerce2020SInter,\n        },\n        GMM.K_20: {\n            TectType.SUBDUCTION_SLAB: gsim.kuehn_2020.KuehnEtAl2020SSlab,\n            TectType.SUBDUCTION_INTERFACE: gsim.kuehn_2020.KuehnEtAl2020SInter,\n        },\n        GMM.K_20_NZ: {\n            TectType.SUBDUCTION_SLAB: gsim.kuehn_2020.KuehnEtAl2020SSlab,\n            TectType.SUBDUCTION_INTERFACE: gsim.kuehn_2020.KuehnEtAl2020SInter,\n        },\n        GMM.Si_20: {\n            TectType.SUBDUCTION_SLAB: gsim.si_2020.SiEtAl2020SSlab,\n            TectType.SUBDUCTION_INTERFACE: gsim.si_2020.SiEtAl2020SInter,\n        },\n        GMM.Z_16: {\n            TectType.ACTIVE_SHALLOW: gsim.zhao_2016.ZhaoEtAl2016Asc,\n            TectType.SUBDUCTION_SLAB: gsim.zhao_2016.ZhaoEtAl2016SSlab,\n            TectType.SUBDUCTION_INTERFACE: gsim.zhao_2016.ZhaoEtAl2016SInter,\n        },\n    }\n\n\nclass Properties(object):\n    \"\"\"\n    Stores values for sites, rup and dists.\n    \"\"\"\n\n    def __init__(self):\n        # this allows attaching arbitrary attributes to self later\n        pass\n\n\ndef oq_mean_stddevs(model, sites, rup, dists, imr, stddev_types):\n    \"\"\"\n    Calculate mean and standard deviations given openquake input structures.\n    \"\"\"\n    mean, stddevs = model.get_mean_and_stddevs(sites, rup, dists, imr, stddev_types)\n    mean = exp(mean[0]) if hasattr(mean, \"__len__\") else exp(mean)\n    stddevs = [s[0] if hasattr(s, \"__len__\") else s for s in stddevs]\n\n    return mean, stddevs\n\n\ndef oq_run(model, site, fault, im, period=None, **kwargs):\n    \"\"\"\n    Run an openquake model using Empirical_Engine input structures.\n    model: model or value from empirical.util.classdef.GMM or openquake class:\n           GMM.P_20 gsim.parker_2020.ParkerEtAl2020SInter\n    site / fault: instances from empirical.classdef -- A tect_type must be able to be set to retrieve the correct model\n    im: intensity measure name\n    period: for spectral acceleration, openquake tables automatically\n            interpolate values between specified values, fails if outside range\n    kwargs: pass extra (model specific) parameters to models\n    \"\"\"\n    if not OQ:\n        raise ImportError(\"openquake is not installed, models not available\")\n\n    # model can be given multiple ways\n    if type(model).__name__ == \"GMM\":\n        model = oq_models[model][fault.tect_type](**kwargs)\n    elif type(model).__name__ == \"MetaGSIM\":\n        model = model(**kwargs)\n\n    trt = model.DEFINED_FOR_TECTONIC_REGION_TYPE\n    if trt == const.TRT.SUBDUCTION_INTERFACE:\n        assert fault.tect_type == TectType.SUBDUCTION_INTERFACE\n    elif trt == const.TRT.SUBDUCTION_INTRASLAB:\n        assert fault.tect_type == TectType.SUBDUCTION_SLAB\n    elif trt == const.TRT.ACTIVE_SHALLOW_CRUST:\n        assert fault.tect_type == TectType.ACTIVE_SHALLOW\n    else:\n        raise ValueError(\"unknown tectonic region: \" + trt)\n\n    stddev_types = []\n    for st in [const.StdDev.TOTAL, const.StdDev.INTER_EVENT, const.StdDev.INTRA_EVENT]:\n        if st in model.DEFINED_FOR_STANDARD_DEVIATION_TYPES:\n            stddev_types.append(st)\n\n    location = Point(\n        0.0, 0.0, 0.0\n    )  # Create a dummy location as OQ calculation doesn't use a location\n    oq_site = Site(location)\n    extra_site_parameters = set(model.REQUIRES_SITES_PARAMETERS).difference(\n        list(zip(*SITE_PROPERTIES))[0]\n    )\n    if len(extra_site_parameters) > 0:\n        raise ValueError(\"unknown site property: \" + extra_site_parameters)\n    oq_site = check_properties(site, model, SITE_PROPERTIES, oq_site, np_array=True)\n\n    sites = SiteCollection([oq_site])\n\n    extra_rup_properties = set(model.REQUIRES_RUPTURE_PARAMETERS).difference(\n        list(zip(*RUPTURE_PROPERTIES))[0]\n    )\n    if len(extra_rup_properties) > 0:\n        raise ValueError(\"unknown rupture property: \" + \" \".join(extra_rup_properties))\n    rupture = check_properties(fault, model, RUPTURE_PROPERTIES, Properties())\n\n    extra_dist_properties = set(model.REQUIRES_DISTANCES).difference(\n        list(zip(*DISTANCE_PROPERTIES))[0]\n    )\n    if len(extra_dist_properties) > 0:\n        raise ValueError(\n            \"unknown distance property: \" + \" \".join(extra_dist_properties)\n        )\n    dists = check_properties(\n        site, model, DISTANCE_PROPERTIES, Properties(), np_array=True\n    )\n\n    if period is not None:\n        assert imt.SA in model.DEFINED_FOR_INTENSITY_MEASURE_TYPES\n        # use sorted instead of max for full list\n        max_period = max([i.period for i in model.COEFFS.sa_coeffs.keys()])\n        single = False\n        if not hasattr(period, \"__len__\"):\n            single = True\n            period = [period]\n        results = []\n        for p in period:\n            imr = imt.SA(period=min(p, max_period))\n            m, s = oq_mean_stddevs(model, sites, rupture, dists, imr, stddev_types)\n            # interpolate pSA value up based on maximum available period\n            if p > max_period:\n                m = m * (max_period / p) ** 2\n            results.append((m, s))\n        if single:\n            return results[0]\n        return results\n    else:\n        imc = getattr(imt, im)\n        assert imc in model.DEFINED_FOR_INTENSITY_MEASURE_TYPES\n        return oq_mean_stddevs(model, sites, rupture, dists, imc(), stddev_types)\n\n\ndef check_properties(ee_object, model, properties, properties_obj, np_array=False):\n    for oq_property_name, ee_property_name in properties:\n        ee_property = getattr(ee_object, ee_property_name)\n        if ee_property:\n            setattr(\n                properties_obj,\n                oq_property_name,\n                np.array([ee_property]) if np_array else ee_property,\n            )\n        else:\n            check_param(model, oq_property_name)\n    return properties_obj\n\n\ndef check_param(model, rp):\n    if rp in model.REQUIRES_RUPTURE_PARAMETERS:\n        raise ValueError(f\"{rp} is a required parameter for {model}\")\n", "meta": {"hexsha": "a1e223f9429afae51bb51369340d4eca580dffae", "size": 8767, "ext": "py", "lang": "Python", "max_stars_repo_path": "empirical/util/openquake_wrapper.py", "max_stars_repo_name": "ucgmsim/Empirical_Engine", "max_stars_repo_head_hexsha": "fa990da352c5615bcaf300142fad6907024e917b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "empirical/util/openquake_wrapper.py", "max_issues_repo_name": "ucgmsim/Empirical_Engine", "max_issues_repo_head_hexsha": "fa990da352c5615bcaf300142fad6907024e917b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2019-04-01T04:58:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T10:33:42.000Z", "max_forks_repo_path": "empirical/util/openquake_wrapper.py", "max_forks_repo_name": "ucgmsim/Empirical_Engine", "max_forks_repo_head_hexsha": "fa990da352c5615bcaf300142fad6907024e917b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2272727273, "max_line_length": 119, "alphanum_fraction": 0.6660203034, "include": true, "reason": "import numpy", "num_tokens": 2475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.1661473633156389}}
{"text": "\"\"\"\nThe classes in this file do preprocessing on data and monte carlo to be used\nto do a point source analysis.\n\"\"\"\n\n__author__ = 'John Evans'\n__copyright__ = 'Copyright 2020 John Evans'\n__credits__ = ['John Evans', 'Jason Fan', 'Michael Larson']\n__license__ = 'Apache License 2.0'\n__version__ = '0.0.1'\n__maintainer__ = 'John Evans'\n__email__ = 'john.evans@icecube.wisc.edu'\n__status__ = 'Development'\n\nfrom typing import List, Optional, Tuple, Union\n\nimport numpy as np\nfrom scipy.interpolate import UnivariateSpline as Spline\n\nfrom dataclasses import dataclass\nfrom dataclasses import field\nfrom dataclasses import InitVar\n\nfrom . import sources\nfrom . import _models\n\n\n@dataclass\nclass _I3EventModelBase(_models.EventModelBase):\n    \"\"\"Docstring\n\n    Attributes:\n        sin_dec_bins (np.array): An array of sin(dec) bin edges for the energy\n            maps.\n        log_energy_bins (np.array): An array of log(energy) bin edges for the\n            energy maps.\n        log_sob_gamma_splines (List[List[scipy.interpolate.UnivariateSpline]]):\n            A 2D list of spline fits of the log(signal-over-background) vs.\n            gamma at a binned energy and sin(dec).\n        \"\"\"\n    _sin_dec_bins: np.array = field(init=False)\n    _log_energy_bins: np.array = field(init=False)\n    _log_sob_gamma_splines: List[List[Spline]] = field(init=False)\n\n\n@dataclass\nclass _I3EventModelDefaultsBase(_models.TdEventModelDefaultsBase):\n    \"\"\"Docstring\"\"\"\n    signal_sin_dec_bins: InitVar[Union[np.array, int]] = field(default=50)\n    log_energy_bins: InitVar[Union[np.array, int]] = field(default=50)\n    gamma_bins: InitVar[Union[np.array, int]] = field(default=50)\n    verbose: InitVar[bool] = field(default=False)\n\n\n@dataclass\nclass I3EventModel(\n    _models.TdEventModel,\n    _I3EventModelDefaultsBase,\n    _I3EventModelBase,\n):\n    \"\"\"Docstring\"\"\"\n    def __post_init__(\n        self,\n        source: sources.Source,\n        data: np.ndarray,\n        sim: np.ndarray,\n        grl: np.ndarray,\n        gamma: float,\n        sampling_width: Optional[float],\n        background_sin_dec_bins: Union[np.array, int],\n        background_window: float,\n        withinwindow: bool,\n        signal_sin_dec_bins: Union[np.array, int],\n        log_energy_bins: Union[np.array, int],\n        gamma_bins: Union[np.array, int],\n        verbose: bool,\n    ) -> None:\n        \"\"\"Docstring\"\"\"\n        super().__post_init__(\n            source,\n            data,\n            sim,\n            grl,\n            gamma,\n            sampling_width,\n            background_sin_dec_bins,\n            background_window,\n            withinwindow,\n        )\n\n        if isinstance(signal_sin_dec_bins, int):\n            signal_sin_dec_bins = np.linspace(-1, 1, 1 + signal_sin_dec_bins)\n        self._sin_dec_bins = signal_sin_dec_bins\n\n        if isinstance(log_energy_bins, int):\n            log_energy_bins = np.linspace(1, 8, 1 + log_energy_bins)\n        self._log_energy_bins = log_energy_bins\n\n        if isinstance(gamma_bins, int):\n            gamma_bins = np.linspace(-4.25, -0.5, 1 + gamma_bins)\n\n        self._log_sob_gamma_splines = self._init_log_sob_gamma_splines(\n            gamma_bins, verbose=verbose)\n\n    def _init_sob_map(self, gamma: float, *args, verbose: bool = False,\n                      **kwargs) -> np.array:\n        \"\"\"Creates sob histogram for a given spectral index (gamma).\n\n        The UnivariateSpline function call uses these default arguments:\n        k=1, s=0, ext=3. To replace any of these defaults, or to pass any other\n        args/kwargs to UnivariateSpline, just pass them to this function.\n        Spline is used here to smooth over the energies to get the values for\n        each bin.\n\n        Args:\n            gamma: The gamma value to use to weight the signal.\n            verbose: A flag to print progress.\n\n        Returns:\n            An array of signal-over-background values binned in sin(dec) and\n            log(energy) for a given gamma.\n        \"\"\"\n        if verbose:\n            print(f'Building map for gamma = {gamma}...', end='')\n        bins = np.array([self._sin_dec_bins, self._log_energy_bins])\n        bin_centers = bins[1, :-1] + np.diff(bins[1]) / 2\n\n        # background\n        bg_h, _, _ = np.histogram2d(self._data['sindec'], self._data['logE'],\n                                    bins=bins, density=True)\n\n        # signal\n        sig_w = self._sim['ow'] * self._sim['trueE']**gamma\n        sig_h, _, _ = np.histogram2d(self._sim['sindec'], self._sim['logE'],\n                                     bins=bins, weights=sig_w, density=True)\n\n        # Normalize histograms by dec band\n        bg_h /= np.sum(bg_h, axis=1)[:, None]\n        sig_h /= np.sum(sig_h, axis=1)[:, None]\n\n        # div-0 okay here\n        with np.errstate(divide='ignore', invalid='ignore'):\n            ratio = sig_h / bg_h\n\n        if 'k' not in kwargs:\n            kwargs['k'] = 1\n        if 's' not in kwargs:\n            kwargs['s'] = 0\n        if 'ext' not in kwargs:\n            kwargs['ext'] = 3\n\n        for i in range(ratio.shape[0]):\n            # Pick out the values we want to use.\n            # We explicitly want to avoid NaNs and infinities\n            good = np.isfinite(ratio[i]) & (ratio[i] > 0)\n            good_bins, good_vals = bin_centers[good], ratio[i][good]\n\n            # Do a linear interpolation across the energy range\n            spline = Spline(good_bins, good_vals, *args, **kwargs)\n\n            # And store the interpolated values\n            ratio[i] = spline(bin_centers)\n        if verbose:\n            print('done')\n        return ratio\n\n    def _init_log_sob_gamma_splines(self, gamma_bins: np.array, *args,\n                                    verbose: bool = False,\n                                    **kwargs) -> List[List[Spline]]:\n        \"\"\"Builds a 3D hist of sob vs. sin(dec), log(energy), and gamma, then\n            returns splines of sob vs. gamma.\n\n        The UnivariateSpline function call uses these default arguments:\n        k=3, s=0, ext='raise'. To replace any of these defaults, or to pass any\n        other args/kwargs to UnivariateSpline, just pass them to this function.\n        Spline is used here to smooth over the energies to get the values for\n        each bin.\n\n        Args:\n            gamma_bins: The spectral indicies at which to build the histograms.\n            verbose: A flag to print progress.\n\n        Returns: A Nested spline list of shape (sin_dec_bins, log_energy_bins).\n        \"\"\"\n        if verbose:\n            print('Building signal-over-background maps...')\n        sob_maps = np.array([self._init_sob_map(gamma, verbose=verbose)\n                             for gamma in gamma_bins])\n        if verbose:\n            print('done.')\n\n        if 'k' not in kwargs:\n            kwargs['k'] = 3\n        if 's' not in kwargs:\n            kwargs['s'] = 0\n        if 'ext' not in kwargs:\n            kwargs['ext'] = 'raise'\n\n        transposed_log_sob_maps = np.log(sob_maps.transpose(1, 2, 0))\n\n        if verbose:\n            print('Fitting log(signal-over-background vs. gamma splines)...',\n                  end='')\n\n        splines = [[\n            Spline(gamma_bins, log_ratios, *args, **kwargs)\n            for log_ratios in dec_bin\n        ] for dec_bin in transposed_log_sob_maps]\n\n        if verbose:\n            print('done')\n\n        return splines\n\n    def log_sob_spline_prepro(\n        self,\n        events: np.ndarray,\n    ) -> Tuple[np.ndarray, List]:\n        \"\"\"Docstring\"\"\"\n        # Get the bin that each event belongs to\n        sin_dec_idx = np.searchsorted(self._sin_dec_bins[:-1],\n                                      events['sindec'])\n\n        log_energy_idx = np.searchsorted(self._log_energy_bins[:-1],\n                                         events['logE'])\n\n        spline_idxs, event_spline_idxs = np.unique(\n            [sin_dec_idx - 1, log_energy_idx - 1],\n            return_inverse=True,\n            axis=1\n        )\n\n        splines = [\n            self._log_sob_gamma_splines[i][j]\n            for i, j in spline_idxs.T\n        ]\n\n        return np.array(event_spline_idxs, dtype=int), splines\n\n    def get_sob_energy(\n        self,\n        gamma: float,\n        splines: List[Spline],\n        event_spline_idxs: np.ndarray,\n    ) -> np.array:\n        \"\"\"Docstring\"\"\"\n        spline_evals = np.exp([spline(gamma) for spline in splines])\n        return spline_evals[event_spline_idxs]\n", "meta": {"hexsha": "75d196ff8751003901098822c54b0fac68900f91", "size": 8422, "ext": "py", "lang": "Python", "max_stars_repo_path": "mla/models.py", "max_stars_repo_name": "thejevans/mla", "max_stars_repo_head_hexsha": "0c583741cfc7626b0653bf58f4efaa1e7681424c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-20T15:47:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-20T15:47:00.000Z", "max_issues_repo_path": "mla/models.py", "max_issues_repo_name": "thejevans/mla", "max_issues_repo_head_hexsha": "0c583741cfc7626b0653bf58f4efaa1e7681424c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-27T02:23:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T20:14:24.000Z", "max_forks_repo_path": "mla/models.py", "max_forks_repo_name": "thejevans/mla", "max_forks_repo_head_hexsha": "0c583741cfc7626b0653bf58f4efaa1e7681424c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8232931727, "max_line_length": 79, "alphanum_fraction": 0.5932082641, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.2974699363766585, "lm_q1q2_score": 0.1660854954823148}}
{"text": "\"\"\"Kernels for scikit-image label.\n\nThese are copied from CuPy, with modification to add a greyscale_mode\nparameter as needed for scikit-image.\n\n\"\"\"\nimport cupy\nimport numpy\n\n\ndef _label(x, structure, y, greyscale_mode=False):\n    elems = numpy.where(structure != 0)\n    vecs = [elems[dm] - 1 for dm in range(x.ndim)]\n    offset = vecs[0]\n    for dm in range(1, x.ndim):\n        offset = offset * 3 + vecs[dm]\n    indxs = numpy.where(offset < 0)[0]\n    dirs = [[vecs[dm][dr] for dm in range(x.ndim)] for dr in indxs]\n    dirs = cupy.array(dirs, dtype=numpy.int32)\n    ndirs = indxs.shape[0]\n    y_shape = cupy.array(y.shape, dtype=numpy.int32)\n    count = cupy.zeros(2, dtype=numpy.int32)\n    _kernel_init()(x, y)\n    try:\n        int_t = int_types[y.dtype.char]\n    except KeyError:\n        raise ValueError(\"y must have int32, uint16, uint32 or uint64 dtype\")\n    if int_t != \"int\":\n        raise NotImplementedError(\n            \"Currently only 32-bit integer case is implemented\"\n        )\n    if greyscale_mode:\n        _kernel_connect(True, int_t)(\n            x, y_shape, dirs, ndirs, x.ndim, y, size=y.size\n        )\n    else:\n        _kernel_connect(False, int_t)(\n            y_shape, dirs, ndirs, x.ndim, y, size=y.size\n        )\n    _kernel_count()(y, count, size=y.size)\n    maxlabel = int(count[0])  # synchronize\n    labels = cupy.empty(maxlabel, dtype=numpy.int32)\n    _kernel_labels()(y, count, labels, size=y.size)\n    _kernel_finalize()(maxlabel, cupy.sort(labels), y, size=y.size)\n    return maxlabel\n\n\n\"\"\"\nElementwise kernels for use by label\n\"\"\"\n\n\ndef _kernel_init():\n    return cupy.ElementwiseKernel(\n        \"X x\",\n        \"Y y\",\n        \"if (x == 0) { y = -1; } else { y = i; }\",\n        \"cucim_nd_label_init\",\n    )\n\n\ndef _kernel_connect(greyscale_mode=False, int_t=\"int\"):\n    \"\"\"\n    Notes\n    -----\n    dirs is a (n_neig//2, ndim) of relative offsets to the neighboring voxels.\n    For example, for structure = np.ones((3, 3)):\n        dirs = array([[-1, -1],\n                      [-1,  0],\n                      [-1,  1],\n                      [ 0, -1]], dtype=int32)\n    (Implementation assumes a centro-symmetric structure)\n    ndirs = dirs.shape[0]\n\n    In the dirs loop below, there is a loop over the ndim neighbors:\n        Here, index j corresponds to the current pixel and k is the current\n        neighbor location.\n    \"\"\"\n    in_params = \"raw int32 shape, raw int32 dirs, int32 ndirs, int32 ndim\"\n    if greyscale_mode:\n        # greyscale mode -> different values receive different labels\n        x_condition = \"if (x[k] != x[j]) continue;\"\n        in_params = \"raw X x, \" + in_params\n    else:\n        # binary mode -> all non-background voxels treated the same\n        x_condition = \"\"\n\n    # Note: atomicCAS is implemented for int, unsigned short, unsigned int, and\n    # unsigned long long\n\n    code = \"\"\"\n        if (y[i] < 0) continue;\n        for (int dr = 0; dr < ndirs; dr++) {{\n            {int_t} j = i;\n            {int_t} rest = j;\n            {int_t} stride = 1;\n            {int_t} k = 0;\n            for (int dm = ndim-1; dm >= 0; dm--) {{\n                int pos = rest % shape[dm] + dirs[dm + dr * ndim];\n                if (pos < 0 || pos >= shape[dm]) {{\n                    k = -1;\n                    break;\n                }}\n                k += pos * stride;\n                rest /= shape[dm];\n                stride *= shape[dm];\n            }}\n            if (k < 0) continue;\n            if (y[k] < 0) continue;\n            {x_condition}\n            while (1) {{\n                while (j != y[j]) {{ j = y[j]; }}\n                while (k != y[k]) {{ k = y[k]; }}\n                if (j == k) break;\n                if (j < k) {{\n                    {int_t} old = atomicCAS( &y[k], (Y)k, (Y)j );\n                    if (old == k) break;\n                    k = old;\n                }}\n                else {{\n                    {int_t} old = atomicCAS( &y[j], (Y)j, (Y)k );\n                    if (old == j) break;\n                    j = old;\n                }}\n            }}\n        }}\n        \"\"\".format(\n        x_condition=x_condition, int_t=int_t\n    )\n\n    return cupy.ElementwiseKernel(\n        in_params, \"raw Y y\", code, \"cucim_nd_label_connect\",\n    )\n\n\ndef _kernel_count():\n    return cupy.ElementwiseKernel(\n        \"\",\n        \"raw Y y, raw int32 count\",\n        \"\"\"\n        if (y[i] < 0) continue;\n        int j = i;\n        while (j != y[j]) { j = y[j]; }\n        if (j != i) y[i] = j;\n        else atomicAdd(&count[0], 1);\n        \"\"\",\n        \"cucim_nd_label_count\",\n    )\n\n\ndef _kernel_labels():\n    return cupy.ElementwiseKernel(\n        \"\",\n        \"raw Y y, raw int32 count, raw int32 labels\",\n        \"\"\"\n        if (y[i] != i) continue;\n        int j = atomicAdd(&count[1], 1);\n        labels[j] = i;\n        \"\"\",\n        \"cucim_nd_label_labels\",\n    )\n\n\ndef _kernel_finalize():\n    return cupy.ElementwiseKernel(\n        \"int32 maxlabel\",\n        \"raw int32 labels, raw Y y\",\n        \"\"\"\n        if (y[i] < 0) {\n            y[i] = 0;\n            continue;\n        }\n        int yi = y[i];\n        int j_min = 0;\n        int j_max = maxlabel - 1;\n        int j = (j_min + j_max) / 2;\n        while (j_min < j_max) {\n            if (yi == labels[j]) break;\n            if (yi < labels[j]) j_max = j - 1;\n            else j_min = j + 1;\n            j = (j_min + j_max) / 2;\n        }\n        y[i] = j + 1;\n        \"\"\",\n        \"cucim_nd_label_finalize\",\n    )\n\n\nint_types = {\n    \"i\": \"int\",\n    \"H\": \"unsigned short\",\n    \"I\": \"unsigned int\",\n    \"L\": \"unsigned long long\",\n}\n", "meta": {"hexsha": "ce4199e8fdfb7355b6f23248244e795dc765d8e6", "size": 5571, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/cucim/src/cucim/skimage/measure/_label_kernels.py", "max_stars_repo_name": "quasiben/cucim", "max_stars_repo_head_hexsha": "048d53e6f99c2129b9febd08e0ae6d1b37d74451", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/cucim/src/cucim/skimage/measure/_label_kernels.py", "max_issues_repo_name": "quasiben/cucim", "max_issues_repo_head_hexsha": "048d53e6f99c2129b9febd08e0ae6d1b37d74451", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/cucim/src/cucim/skimage/measure/_label_kernels.py", "max_forks_repo_name": "quasiben/cucim", "max_forks_repo_head_hexsha": "048d53e6f99c2129b9febd08e0ae6d1b37d74451", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5692307692, "max_line_length": 79, "alphanum_fraction": 0.4898581942, "include": true, "reason": "import numpy,import cupy", "num_tokens": 1547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3242353989809524, "lm_q1q2_score": 0.16591663749143334}}
{"text": "# pylint: disable=too-many-lines\n\"\"\"Nuclear potential module.\n\nModule containing representations of 3D potentials for use in nuclear theory.\nAlso contains logic to read them from and save them to files with a standard\nnaming convention.\n\nclass Channel\n-------------\nA container for the channel information for a potential. It has the following\nmethod::\n\n    channel = Channel(spin, orb_ang_mom_1, orb_ang_mom_2, tot_ang_mom, isospin)\n\nThese are also commonly read as S, L, L, J, and T.\n\nclass CoupledChannel\n--------------------\nA container to handle coupled channels. It has the following method::\n\n    channel = CoupledChannel(list_of_channels)\n\nAll channels in coupled channel should have same S, J, and T.\n\nclass PotentialType\n-------------------\nA container class to hold all the physical information about the potential. It\nhas the following method::\n\n    potential_type = PotentialType(n_body, order, name, channel, particles)\n\nclass Potential\n---------------\nAbstraction for the representation of a potential. Handles the logic of adding\nand removing weights. Can generate corresponding kinetic energy. It has the\nfollowing methods::\n\n    potential = Potential(potential_type, nodes, weights, potential, lam=50.0,\n                          has_weights=False)\n    kinetic_energy = potential.kinetic_energy()\n    potential_data_wo_weights = potential.without_weights()\n    potential_data_w_weights = potential.with_weights()\n    new_potential = potential.copy(potential_data, lam)\n    reduced_potential = potential.reduce_dim(dim)\n\nclass CoupledPotential\n----------------------\nAbstraction for representation for potential of coupled channel. Handles logic\nof adding and removing weights. Can generate kinetic energy. It has the\nfollowing methods::\n\n    potential = CoupledPotential([potential1, potential2, potential3,\n                                  potential4])\n    kinetic_energy = potential.kinetic_energy()\n    potential_data_wo_weights = potential.without_weights()\n    potential_data_w_weights = potential.with_weights()\n    new_potential = potential.copy(potential_data, lam)\n    reduced_potential = potential.reduce_dim(dim)\n    channel_potential = potential.extract_channel_potential(\n        potential1.potential_type.channel\n    )\n\nMethods\n-------\npotential = load_from_file(file_str)\n\nMethod to load a potential from a file. Requires that standard file-naming\nconventions have been followed.\n\npotential = load(n_body, order, name, channel, lambda, particles,\n                 num_points='*')\n\nMethod to load potential from a standard directory. Requires that potential was\nsaved there earlier.\n\nsave(potential, directory=None)\n\nMethod to save potential with correct naming convention either to a standard\nfolder or to a user-specified directory.\n\nChangelog:\n\n2018.11.14\n    Added:\n        CoupledChannel for coupled channels\n        CoupledPotential for potentials in coupled channels\n\n2018.11.09\n    Added:\n        load_from_file method\n    Changed:\n        Make load take parameters and use load_from_file for loading from a\n        specific file\n        Save now has different parameter ordering with the dir_str param being\n        optional\n\n2018.11.06\n    Added:\n        Initial creation of module\n\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport glob\nfrom math import pi\nfrom math import sqrt\nimport os\nimport re\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nNBODY_DICT = {\n    'NN': 2,\n    '3N': 3,\n}\n\nSTANDARD_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),\n                             'potentials')\n\nINV_NBODY_DICT = {v: k for k, v in NBODY_DICT.items()}\n\nORDER_DICT = {\n    'LO': 0,\n    'NLO': 1,\n    'N2LO': 2,\n    'N3LO': 3,\n}\n\nINV_ORDER_DICT = {v: k for k, v in ORDER_DICT.items()}\n\n\nclass Channel:\n    \"\"\"Container for information on channel for potential.\"\"\"\n\n    # pylint: disable=too-many-arguments\n    def __init__(self, spin, orb_ang_mom_1, orb_ang_mom_2, tot_ang_mom,\n                 isospin):\n        \"\"\"Create Channel object.\n\n        Parameters\n        ----------\n        spin : int\n            Spin quantum number.\n        orb_ang_mom_1 : int\n            First angular momentum quantum number.\n        orb_ang_mom_2 : int\n            Second angular momentum quantum number.\n        tot_ang_mom : int\n            Total angular momentum.\n        isospin : int\n            2-body isospin quantum number.\n\n        \"\"\"\n        self._spin = spin\n        self._l1 = orb_ang_mom_1\n        self._l2 = orb_ang_mom_2\n        self._j = tot_ang_mom\n        self._isospin = isospin\n\n    def as_5tuple(self):\n        \"\"\"Return 5-tuple representation of channel.\n\n        Returns\n        -------\n        (int, int, int, int, int)\n            5-tuple with channel quantum numbers.\n\n        \"\"\"\n        return (self._spin, self._l1, self._l2, self._j, self._isospin)\n\n    def __str__(self):\n        \"\"\"Return string representation of channel.\n\n        Returns\n        -------\n        str\n            String of 5 integers with channel information which are SLLJT.\n\n        \"\"\"\n        return '{}{}{}{}{}'.format(self._spin, self._l1, self._l2, self._j,\n                                   self._isospin)\n\n    def __eq__(self, other):\n        \"\"\"Return whether channel is same as another channel object.\n\n        Returns\n        -------\n        bool\n            True if self and other are the same, False otherwise.\n\n        \"\"\"\n        return self.as_5tuple() == other.as_5tuple()\n\n    def __ne__(self, other):\n        \"\"\"Return whether channel is different from another channel object.\n\n        Returns\n        -------\n        bool\n            False if self and other are the same, False otherwise.\n\n        \"\"\"\n        return self.as_5tuple() != other.as_5tuple()\n\n\nclass CoupledChannel(Channel):\n    \"\"\"Container for information about coupled channel.\"\"\"\n\n    def __init__(self, list_of_channels):\n        \"\"\"Create coupled channel container.\n\n        Parameters\n        ----------\n        list_of_channels : list of Channel objects\n            List of channels in coupled channel.\n\n        \"\"\"\n        spins = {x.as_5tuple()[0] for x in list_of_channels}\n        tot_ang_moms = {x.as_5tuple()[3] for x in list_of_channels}\n        isospins = {x.as_5tuple()[4] for x in list_of_channels}\n        if len(spins) * len(isospins) * len(tot_ang_moms) != 1:\n            raise ValueError('Given channels cannot be coupled.')\n        super(CoupledChannel, self).__init__(spins.pop(), '*', '*',\n                                             tot_ang_moms.pop(),\n                                             isospins.pop())\n        self._channels = list_of_channels\n\n    @property\n    def channels(self):\n        \"\"\"Return list of channels in coupled channel.\n\n        Returns\n        -------\n        list of Channel objects\n\n        \"\"\"\n        return self._channels\n\n    def __eq__(self, other):\n        \"\"\"Return whether coupled channel object is same as another.\n\n        Returns\n        -------\n        bool\n            True if coupled channels are equal, False otherwise.\n\n        \"\"\"\n        return False not in {x == y for x, y in zip(self.channels,\n                                                    other.channels)}\n\n    def __ne__(self, other):\n        \"\"\"Return whether coupled channel object is not same as another.\n\n        Returns\n        -------\n        bool\n            True if coupled channels are not equal, False otherwise.\n\n        \"\"\"\n        return False in {x == y for x, y in zip(self.channels,\n                                                other.channels)}\n\n\nclass PotentialType:\n    \"\"\"Container for information related to potential.\"\"\"\n\n    # pylint: disable=too-many-arguments\n    def __init__(self, n_body, order, name, channel, particles):\n        \"\"\"Construct potential type.\n\n        Parameters\n        ----------\n        n_body : int\n            Number of particles interacting in potential.\n        order : int\n            Order to which potential was calculated.\n        name : str\n            Name for potential, may reflect something about origin.\n        channel: Channel\n            Object representing the partial wave channel for the potential.\n        particles: str\n            String representing constituent particles in the interaction.\n\n        \"\"\"\n        self._n_body = n_body\n        self._order = order\n        self._name = name\n        self._channel = channel\n        self._particles = particles\n\n    @property\n    def n_body(self):\n        \"\"\"Return number of particles in potential.\n\n        Returns\n        -------\n        int\n            Number of particles.\n\n        \"\"\"\n        return self._n_body\n\n    @property\n    def order(self):\n        \"\"\"Return order to which potential was calculated.\n\n        Returns\n        -------\n        int\n            Order of potential.\n\n        \"\"\"\n        return self._order\n\n    @property\n    def name(self):\n        \"\"\"Return name of potential.\n\n        Returns\n        -------\n        str\n            Name of potential.\n\n        \"\"\"\n        return self._name\n\n    @property\n    def channel(self):\n        \"\"\"Return partial wave channel of potential.\n\n        Returns\n        -------\n        Channel\n            Channel object representing partial wave channel.\n\n        \"\"\"\n        return self._channel\n\n    @property\n    def particles(self):\n        \"\"\"Return particles in interaction to which potential applies.\n\n        Returns\n        -------\n        str\n            String with particles in interaction.\n\n        \"\"\"\n        return self._particles\n\n    def __eq__(self, other):\n        \"\"\"Return whether potential type is same as other potential type.\n\n        Returns\n        -------\n        bool\n            True if same, False otherwise.\n\n        \"\"\"\n        return ((self.n_body == other.n_body)\n                and (self.order == other.order)\n                and (self.name == other.name)\n                and (self.channel == other.channel)\n                and (self.particles == other.particles))\n\n    def __ne__(self, other):\n        \"\"\"Return whether potential type is not same as other potential type.\n\n        Returns\n        -------\n        bool\n            False if same, True otherwise.\n\n        \"\"\"\n        return not ((self.n_body == other.n_body)\n                    and (self.order == other.order)\n                    and (self.name == other.name)\n                    and (self.channel == other.channel)\n                    and (self.particles == other.particles))\n\n\nclass Potential:\n    \"\"\"Class encapsulating all relevant information about a potential.\"\"\"\n\n    # pylint: disable=too-many-arguments\n    def __init__(self, potential_type, nodes, weights, potential, lam=50.0,\n                 has_weights=False):\n        \"\"\"Create potential from parameters.\n\n        Parameters\n        ----------\n        potential_type : PotentialType\n            PotentialType instance with information about the potential.\n        nodes : list of floats\n            List of momenta at which the potential is defined.\n        weights : list of floats\n            List of integration weights corresponding to nodes.\n        potential : matrix of floats\n            Value of potential at incoming and outgoing momenta in nodes.\n        lam : float, optional\n            Value of lambda (SRG flow parameter) for potential. For unevolved\n            potentials, a value of 50 is the default.\n        has_weights : bool, optional\n            Specifies whether potential given has weights factored in already.\n\n        \"\"\"\n        self._potential_type = potential_type\n        self._nodes = nodes\n        self._weights = weights\n        self._lam = lam\n        if has_weights:\n            potential = _rem_w(potential, self._weights, self._nodes)\n        self._potential = potential\n\n    def copy(self, potential, lam):\n        \"\"\"Create potential from current potential with new data and lam.\n\n        Parameters\n        ----------\n        potential : matrix of floats\n            Potential data.\n        lam : float\n            Value of lambda\n\n        Returns\n        -------\n        Potential\n            New potential with new data.\n\n        \"\"\"\n        return Potential(self._potential_type, self._nodes, self._weights,\n                         potential, lam)\n\n    def with_weights(self):\n        \"\"\"Return potential with weights factored in (for calculations).\n\n        Returns\n        -------\n        matrix of floats\n            Potential with integration weights.\n\n        \"\"\"\n        return _add_w(self._potential, self._weights, self._nodes)\n\n    def without_weights(self):\n        \"\"\"Return potential without weights (for visualization).\n\n        Returns\n        -------\n        matrix of floats\n            Potential without integration weights.\n\n        \"\"\"\n        return np.array(self._potential)\n\n    def reduce_dim(self, dim):\n        \"\"\"Return new potential with only `dim` lowest energy states.\n\n        Parameters\n        ----------\n        dim : int\n            Dimension to which potential is to be reduced.\n\n        Returns\n        -------\n        Potential\n            New reduced dimension potential.\n\n        Raises\n        ------\n        ValueError\n            When value for new dim is too small or too large.\n\n        \"\"\"\n        if dim >= len(self.nodes):\n            raise ValueError('Value of dim is not smaller than current dim.')\n        if dim <= 0:\n            raise ValueError('Zero or negative dim is not allowed.')\n\n        new_data = self._potential[np.ix_(list(range(dim)), list(range(dim)))]\n        new_nodes = self._nodes[:dim]\n        new_weights = self._weights[:dim]\n\n        return Potential(self._potential_type, new_nodes, new_weights,\n                         new_data, self._lam)\n\n    def kinetic_energy(self):\n        \"\"\"Return kinetic energy for potential (for calculations).\n\n        Returns\n        -------\n        matrix of floats\n            Kinetic energy matrix.\n\n        \"\"\"\n        return np.diag(np.array([p**2 for p in self._nodes]))\n\n    def __eq__(self, other):\n        \"\"\"Return whether two potentials are equal to with numerical error.\n\n        Returns\n        -------\n        bool\n            True when potential type, nodes, weights, potential, and lam are\n            all equal within epsilon, False otherwise.\n\n        \"\"\"\n        # Numerical errors smaller than this are acceptable\n        # If there is something wrong with the physics, it should produce\n        # errors larger than this.\n        eps = 10**(-4)\n\n        if self.potential_type != other.potential_type:\n            return False\n        if self.dim != other.dim:\n            return False\n        if abs(self.lam - other.lam) > eps:\n            return False\n        for p_self, p_other, w_self, w_other in zip(self.nodes, other.nodes,\n                                                    self.weights,\n                                                    other.weights):\n            if abs(p_self - p_other) > eps or abs(w_self - w_other) > eps:\n                return False\n        for i in range(self.dim):\n            for j in range(self.dim):\n                diff = abs(self.without_weights()[i][j] -\n                           other.without_weights()[i][j])\n                if diff > eps:\n                    return False\n        return True\n\n    def __ne__(self, other):\n        \"\"\"Return whether two potentials are not equal to with numerical error.\n\n        Returns\n        -------\n        bool\n            False when potential type, nodes, weights, potential, and lam are\n            all equal within epsilon, True otherwise.\n\n        \"\"\"\n        # Numerical errors smaller than this are acceptable\n        # If there is something wrong with the physics, it should produce\n        # errors larger than this.\n        eps = 10**(-4)\n\n        if self.potential_type != other.potential_type:\n            return True\n        if self.dim != other.dim:\n            return True\n        if abs(self.lam - other.lam) > eps:\n            return True\n        for p_self, p_other, w_self, w_other in zip(self.nodes, other.nodes,\n                                                    self.weights,\n                                                    other.weights):\n            if abs(p_self - p_other) > eps or abs(w_self - w_other) > eps:\n                return True\n        for i in range(self.dim):\n            for j in range(self.dim):\n                diff = abs(self.without_weights()[i][j] -\n                           other.without_weights()[i][j])\n                if diff > eps:\n                    return True\n        return False\n\n    @property\n    def dim(self):\n        \"\"\"Return the dimension of the potential matrix.\n\n        Returns\n        -------\n        int\n            The dimension of the (square) potential matrix.\n\n        \"\"\"\n        return len(self._nodes)\n\n    @property\n    def potential_type(self):\n        \"\"\"Return `PotentialType` object for potential.\n\n        Returns\n        -------\n        PotentialType\n            Object with all physics related information for the potential.\n\n        \"\"\"\n        return self._potential_type\n\n    @property\n    def nodes(self):\n        \"\"\"Return the nodes for the potential.\n\n        Returns\n        -------\n        list of floats\n            List of momenta at which potential is defined.\n\n        \"\"\"\n        return self._nodes\n\n    @property\n    def weights(self):\n        \"\"\"Return weights for the potential.\n\n        Returns\n        -------\n        list of floats\n            Integration weights corresponding to nodes for potential.\n\n        \"\"\"\n        return self._weights\n\n    @property\n    def lam(self):\n        \"\"\"Return lambda for potential.\n\n        Returns\n        -------\n        float\n            Value of lambda, the SRG flow parameter, for potential.\n\n        \"\"\"\n        return self._lam\n\n\nclass CoupledPotential(Potential):\n    \"\"\"Representation of potential of coupled channel.\"\"\"\n\n    def __init__(self, list_of_potentials):  # pylint: disable=too-many-locals\n        \"\"\"Create potential from list of potentials in a coupled channel.\n\n        Parameters\n        ----------\n        list_of_potentials : list of Potential objects\n            List of potentials to form coupled channel.\n\n        Returns\n        -------\n        Potential\n            New potential with full coupled channel.\n\n        \"\"\"\n        self._construction = list_of_potentials\n        channels = [x.potential_type.channel for x in list_of_potentials]\n        n_body = {x.potential_type.n_body for x in list_of_potentials}\n        order = {x.potential_type.order for x in list_of_potentials}\n        name = {x.potential_type.name for x in list_of_potentials}\n        particles = {x.potential_type.particles for x in list_of_potentials}\n        if len(n_body) * len(order) * len(name) * len(particles) != 1:\n            raise ValueError('Given potentials cannot be coupled.')\n        coupled_channel = CoupledChannel(channels)\n        potential_type = PotentialType(n_body.pop(), order.pop(), name.pop(),\n                                       coupled_channel, particles.pop())\n        lam = {x.lam for x in list_of_potentials}\n        if len(lam) != 1:\n            raise ValueError('Not all given potentials are at the same lam.')\n        lam = lam.pop()\n        dim = {x.dim for x in list_of_potentials}\n        if len(dim) != 1:\n            raise ValueError('Not all given potentials have same dim.')\n        dim = dim.pop()\n        c_dim = int(sqrt(len(list_of_potentials)))\n        if c_dim**2 != len(list_of_potentials):\n            raise ValueError('Non-square number of potentials given.')\n        nodes = []\n        weights = []\n        for pot in list_of_potentials[:c_dim]:\n            nodes += pot.nodes\n            weights += pot.weights\n        nodes = np.array(nodes)\n        weights = np.array(weights)\n        potential_data = np.zeros((c_dim * dim, c_dim * dim))\n        self._channel_indexes = []\n        for i in range(c_dim):\n            for j in range(c_dim):\n                r_s = i * dim\n                r_e = (i + 1) * dim\n                c_s = j * dim\n                c_e = (j + 1) * dim\n                data = list_of_potentials[i * c_dim + j].without_weights()\n                potential_data[r_s:r_e, c_s:c_e] = data\n                self._channel_indexes.append((r_s, r_e, c_s, c_e))\n        super(CoupledPotential, self).__init__(potential_type, nodes, weights,\n                                               potential_data, lam)\n        self._c_dim = c_dim\n        self._w_dim = dim\n        self._channels = channels\n\n    def copy(self, potential, lam):\n        \"\"\"Create potential from current potential with new data and lam.\n\n        Parameters\n        ----------\n        potential : matrix of floats\n            Potential data.\n        lam : float\n            Value of lambda\n\n        Returns\n        -------\n        Potential\n            New potential with new data.\n\n        \"\"\"\n        new_potentials = []\n        for pot, ranges in zip(self._construction, self._channel_indexes):\n            sub_matrix = _submatrix(potential, ranges)\n            new_potentials.append(pot.copy(sub_matrix, lam))\n        return CoupledPotential(new_potentials)\n\n    def reduce_dim(self, dim):\n        \"\"\"Return new potential with only `dim` lowest energy states.\n\n        Parameters\n        ----------\n        dim : int\n            Dimension to which potential is to be reduced.\n\n        Returns\n        -------\n        Potential\n            New reduced dimension potential.\n\n        Raises\n        ------\n        ValueError\n            When value for new dim is too small or too large.\n\n        \"\"\"\n        if dim >= self._w_dim:\n            raise ValueError('Value of dim is not smaller than current dim.')\n        if dim <= 0:\n            raise ValueError('Zero or negative dim is not allowed.')\n        new_potentials = []\n        for pot, ranges in zip(self._construction, self._channel_indexes):\n            sub_matrix = _submatrix(self._potential, ranges)\n            new_potentials.append(pot.copy(sub_matrix,\n                                           self._lam).reduce_dim(dim))\n        return CoupledPotential(new_potentials)\n\n    def extract_channel_potential(self, channel):\n        \"\"\"Return potential corresponding to channel.\n\n        Parameters\n        ----------\n        channel : Channel\n            Channel to extract.\n\n        Returns\n        -------\n        Potential\n            Potential corresponding to channel.\n\n        \"\"\"\n        for chan, potential, ranges in zip(self._channels, self._construction,\n                                           self._channel_indexes):\n            if channel == chan:\n                sub_matrix = _submatrix(self._potential, ranges)\n                return potential.copy(sub_matrix, self._lam)\n        raise ValueError('Channel not found.')\n\n    @property\n    def dim(self):\n        \"\"\"Return the dimension of single channel in the potential matrix.\n\n        Returns\n        -------\n        int\n            The dimension of a single channel in the (square) potential matrix.\n\n        \"\"\"\n        return self._w_dim\n\n\n# pylint: disable=too-many-locals\ndef load_from_file(file_str):\n    \"\"\"Load potential from file.\n\n    Parameters\n    ----------\n    file_str : str\n        String path to file with potential data.\n\n    Returns\n    -------\n    Potential\n        Potential created from extracted information and data from file.\n\n    \"\"\"\n    # Parse info about potential from filename\n    # Strip directory structure\n    end = file_str.split('/')[-1]\n\n    # Match regular expression\n    regex_str = r'V(.*)_(.*)_(.*)_SLLJT_(.*)_lambda_(.*)_Np_(.*)_(.*)\\.dat'\n    result = re.search(regex_str, end)\n\n    # Extract values from matches\n    n_body_str = result.group(1)\n    order_str = result.group(2)\n    name = result.group(3)\n    channel_str = result.group(4)\n    lam = float(result.group(5))\n    particles = result.group(7)\n\n    # Convert string values to integer values\n    n_body = NBODY_DICT[n_body_str]\n    order = ORDER_DICT[order_str]\n\n    # Convert channel to 5-tuple, then Channel object\n    channel = Channel(*tuple([int(n) for n in channel_str]))\n\n    # Get number of points\n    num_points = int(result.group(6))\n\n    # Read potential\n    with open(file_str) as file:\n        nodes = []\n        weights = []\n        for _ in range(num_points):\n            vals = file.readline().split()\n            weights.append(float(vals[0]))\n            nodes.append(float(vals[1]))\n        potential = np.array([[float(file.readline().split()[-1]) for _ in\n                               range(num_points)] for _ in range(num_points)])\n\n    # Create potential_type\n    potential_type = PotentialType(n_body, order, name, channel, particles)\n\n    # Return potential\n    return Potential(potential_type, nodes, weights, potential, lam)\n\n\n# pylint: disable=too-many-arguments\ndef load(n_body, order, name, channel, lam, particles, num_points='*'):\n    \"\"\"Load potential based on parameters.\n\n    Parameters\n    ----------\n     n_body : int\n        Number of particles interacting in potential.\n    order : int\n        Order to which potential was calculated.\n    name : str\n        Name for potential, may reflect something about origin.\n    channel: Channel or (int, int, int, int, int) or str\n        Object representing the partial wave channel for the potential.\n    lam : float\n        Value of SRG flow parameter for potential.\n    particles: str\n        String representing constituent particles in the interaction.\n    num_points : int, optional\n        Number of points in potential. Should only be specified if multiple\n        versions of same potential are saved and you need a specific one.\n        Otherwise, will match the first one in lexicographical ordering.\n\n    Returns\n    -------\n    Potential\n        Potential created from extracted information and data from file.\n\n    Raises\n    ------\n    FileNotFoundError\n        If globbing doesn't match any files.\n\n    \"\"\"\n    # Set up format string\n    file_format_str = '{}/V{}_{}_{}_SLLJT_{}_lambda_{:.2f}_Np_{}_{}.dat'\n\n    # Get values for format string\n    n_body_str = INV_NBODY_DICT[n_body]\n    order_str = INV_ORDER_DICT[order]\n\n    # Handle non-string formats\n    if isinstance(channel, Channel):\n        channel = str(channel)\n    elif isinstance(channel, tuple):\n        channel = ''.join(channel)\n\n    dir_str = os.path.join(STANDARD_PATH, n_body_str,\n                           'SLLJT_{}'.format(channel))\n\n    # Create full file path string\n    file_path = file_format_str.format(dir_str, n_body_str, order_str, name,\n                                       channel, lam, num_points, particles)\n\n    # Handle globbing\n    if num_points == '*':\n        try:\n            file_path = glob.glob(file_path)[0]\n        except IndexError:\n            raise FileNotFoundError('No potential with those params found.')\n\n    return load_from_file(file_path)\n\n\ndef save(potential, dir_str=None):\n    \"\"\"Save potential with correct file-naming.\n\n    Parameters\n    ----------\n    potential : Potential\n        Potential to be saved.\n    dir_str : str, optional\n        String corresponding to directory where file should be saved. May have\n        trailing `/`.\n\n    \"\"\"\n    # Set up format strings\n    file_format_str = '{}/V{}_{}_{}_SLLJT_{}_lambda_{:.2f}_Np_{}_{}.dat'\n    nodes_format_str = '{:.5e} {:.5e}\\n'\n    potential_format_str = '{:.5e} {:.5e} {:.5e}\\n'\n\n    # Get values for format string\n    potential_type = potential.potential_type\n    n_body = potential_type.n_body\n    n_body_str = INV_NBODY_DICT[n_body]\n    order = potential_type.order\n    order_str = INV_ORDER_DICT[order]\n    name = potential_type.name\n    channel_str = str(potential_type.channel)\n    lam = potential.lam\n    num_points = len(potential.nodes)\n    particles = potential_type.particles\n\n    # Handle optional argument\n    if dir_str is None:\n        dir_str = os.path.join(STANDARD_PATH, n_body_str,\n                               'SLLJT_{}'.format(channel_str))\n\n    # Strip potential trailing '/'\n    if dir_str[-1] == '/':\n        dir_str = dir_str[:-1]\n\n    # Create full file path string\n    file_path = file_format_str.format(dir_str, n_body_str, order_str, name,\n                                       channel_str, lam, num_points, particles)\n\n    # Create directory if it doesnt exist\n    _ensure_dir_for_file(file_path)\n\n    # Output potential\n    with open(file_path, 'w+') as file:\n        for weight, node in zip(potential.weights, potential.nodes):\n            file.write(nodes_format_str.format(weight, node))\n        for i in range(num_points):\n            for j in range(num_points):\n                file.write(potential_format_str.format(\n                    potential.nodes[i], potential.nodes[j],\n                    potential.without_weights()[i][j]))\n\n\ndef plot(potential, v_min=None, v_max=None):\n    \"\"\"Plot potential with colorbar.\n\n    Parameters\n    ----------\n    potential : Potential\n        Potential to be plotted.\n    v_min : int, optional\n        Minimum value to be reflected on the colorbar scale.\n    v_max : int, optional\n        Maximum value to be reflected on the colorbar scale.\n\n    \"\"\"\n    if v_min is None or v_max is None:\n        plt.matshow(potential.without_weights())\n    else:\n        plt.matshow(potential.without_weights(), vmin=v_min, vmax=v_max)\n    plt.colorbar()\n    plt.show()\n    plt.close()\n\n\n# ------------------- Internal Methods ------------------------------------- #\n\n\ndef _add_w(matrix, weights, nodes):\n    factor_vector = [sqrt(w) * p for w, p in zip(weights, nodes)]\n    weighted_matrix = np.dot(np.dot(np.diag(factor_vector), matrix),\n                             np.diag(factor_vector))\n    return 2 / pi * weighted_matrix\n\n\ndef _rem_w(matrix, weights, nodes):\n    factor_vector = [1/(sqrt(w) * p) for w, p in zip(weights, nodes)]\n    unweighted_matrix = np.dot(np.dot(np.diag(factor_vector), pi / 2 * matrix),\n                               np.diag(factor_vector))\n    return unweighted_matrix\n\n\ndef _ensure_dir_for_file(file):\n    directory = os.path.dirname(file)\n    if not os.path.exists(directory):\n        os.makedirs(directory)\n\n\ndef _submatrix(potential, ranges):\n    return potential[np.ix_(list(range(ranges[0], ranges[1])),\n                            list(range(ranges[2], ranges[3])))]\n", "meta": {"hexsha": "458d5ce62a9e9557847f69a30f64f71be1f7f272", "size": 30348, "ext": "py", "lang": "Python", "max_stars_repo_path": "srg3d/potential.py", "max_stars_repo_name": "cheshyre/srg3d-py", "max_stars_repo_head_hexsha": "a62592c0d9bcb62d6a54d13827882cdfe46fa706", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "srg3d/potential.py", "max_issues_repo_name": "cheshyre/srg3d-py", "max_issues_repo_head_hexsha": "a62592c0d9bcb62d6a54d13827882cdfe46fa706", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "srg3d/potential.py", "max_forks_repo_name": "cheshyre/srg3d-py", "max_forks_repo_head_hexsha": "a62592c0d9bcb62d6a54d13827882cdfe46fa706", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-25T14:47:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-25T14:47:54.000Z", "avg_line_length": 30.137040715, "max_line_length": 79, "alphanum_fraction": 0.588473705, "include": true, "reason": "import numpy", "num_tokens": 6361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3242353989809524, "lm_q1q2_score": 0.16591663749143332}}
{"text": "\"\"\"\nSet of programs and tools to read the outputs from RH (Han's version)\n\"\"\"\nimport os\nimport sys\nimport io\nimport xdrlib\nimport numpy as np\n\n\nclass Rhout:\n    \"\"\"\n    Reads outputs from RH.\n\n    Currently the reading the following output files is supported:\n     - input.out\n     - geometry.out\n     - atmos.out\n     - spectrum.out (no Stokes)\n     - spectrum_XX (no Stokes, from solveray)\n     - brs.out\n     - J.dat\n     - opacity.out (no Stokes)\n\n    These output files are NOT supported:\n      - Atom (atom, collrate, damping, pops, radrate)\n      - Flux\n      - metals\n      - molecule\n\n    Parameters\n    ----------\n    fdir : str, optional\n        Directory with output files.\n    verbose : str, optional\n        If True, will print more details.\n\n    Notes\n    -----\n    In general,  the way to read all the XDR files should be:\n\n     Modify read_xdr_file so that it returns only xdata.\n     Then, on each read_xxx, read the necessary header variables,\n     rewind (xdata.set_position(0)), then read the variables in order.\n     This allows the flexibility of derived datatypes, and appending to dictionary\n     (e.g. as in readatmos for all the elements and etc.). It also allows one to\n     read directly into attribute of the class (with setattr(self,'aa',<data>))\n    \"\"\"\n    def __init__(self, fdir='.', verbose=True):\n        ''' Reads all the output data from a RH run.'''\n        self.verbose = verbose\n        self.fdir = fdir\n        self.read_input('{0}/input.out'.format(fdir))\n        self.read_geometry('{0}/geometry.out'.format(fdir))\n        self.read_atmosphere('{0}/atmos.out'.format(fdir))\n        self.read_spectrum('{0}/spectrum.out'.format(fdir))\n        if os.path.isfile('{0}/spectrum_1.00'.format(fdir)):\n            self.read_ray('{0}/spectrum_1.00'.format(fdir))\n\n    def read_input(self, infile='input.out'):\n        ''' Reads RH input.out file. '''\n        data = read_xdr_file(infile)\n        self.input = {}\n        input_vars = [('magneto_optical', 'i'), ('PRD_angle_dep', 'i'),\n                      ('XRD', 'i'), ('start_solution', 'i'),\n                      ('stokes_mode', 'i'), ('metallicity', 'd'),\n                      ('backgr_pol', 'i'), ('big_endian', 'i')]\n        for v in input_vars:\n            self.input[v[0]] = read_xdr_var(data, v[1:])\n        close_xdr(data, infile, verbose=self.verbose)\n\n    def read_geometry(self, infile='geometry.out'):\n        ''' Reads RH geometry.out file. '''\n        data = read_xdr_file(infile)\n        self.geometry = {}\n        geom_type = ['ONE_D_PLANE', 'TWO_D_PLANE',\n                     'SPHERICAL_SYMMETRIC', 'THREE_D_PLANE']\n        type = read_xdr_var(data, ('i',))\n        if type not in list(range(4)):\n            raise ValueError('read_geometry: invalid geometry type {0} in {1}'.\n                             format(type, infile))\n        nrays = read_xdr_var(data, ('i',))\n        self.nrays = nrays\n        self.geometry_type = geom_type[type]\n        # read some parameters and define structure to be read\n        if self.geometry_type == 'ONE_D_PLANE':\n            ndep = read_xdr_var(data, ('i',))\n            self.ndep = ndep\n            geom_vars = [('xmu', 'd', (nrays,)), ('wmu', 'd', (nrays,)),\n                         ('height', 'd', (ndep,)), ('cmass', 'd', (ndep,)),\n                         ('tau500', 'd', (ndep,)), ('vz', 'd', (ndep,))]\n        elif self.geometry_type == 'TWO_D_PLANE':\n            nx = read_xdr_var(data, ('i',))\n            nz = read_xdr_var(data, ('i',))\n            self.nx = nx\n            self.nz = nz\n            geom_vars = [('angleSet', 'i'), ('xmu', 'd', (nrays,)),\n                         ('ymu', 'd', (nrays,)), ('wmu', 'd', (nrays,)),\n                         ('x', 'd', (nx,)), ('z', 'd', (nz,)),\n                         ('vx', 'd', (nx, nz)), ('vz', 'd', (nx, nz))]\n        elif self.geometry_type == 'THREE_D_PLANE':\n            nx = read_xdr_var(data, ('i',))\n            ny = read_xdr_var(data, ('i',))\n            nz = read_xdr_var(data, ('i',))\n            self.nx = nx\n            self.ny = ny\n            self.nz = nz\n            geom_vars = [('angleSet', 'i'), ('xmu', 'd', (nrays,)),\n                         ('ymu', 'd', (nrays,)), ('wmu', 'd', (nrays,)),\n                         ('dx', 'd'), ('dy', 'd'),\n                         ('z', 'd', (nz,)), ('vx', 'd', (nx, ny, nz)),\n                         ('vy', 'd', (nx, ny, nz)), ('vz', 'd', (nx, ny, nz))]\n        elif self.geometry_type == 'SPHERICAL_SYMMETRIC':\n            nradius = read_xdr_var(data, ('i',))\n            ncore = read_xdr_var(data, ('i',))\n            self.nradius = nradius\n            self.ncore = ncore\n            geom_vars = [('radius', 'd'), ('xmu', 'd', (nrays,)),\n                         ('wmu', 'd', (nrays,)), ('r', 'd', (nradius,)),\n                         ('cmass', 'd', (nradius,)), ('tau500', 'd', (nradius,)),\n                         ('vr', 'd', (nradius,))]\n        # read data\n        for v in geom_vars:\n            self.geometry[v[0]] = read_xdr_var(data, v[1:])\n        close_xdr(data, infile, verbose=self.verbose)\n\n    def read_atmosphere(self, infile='atmos.out'):\n        ''' Reads RH atmos.out file '''\n        if not hasattr(self, 'geometry'):\n            em = ('read_atmosphere: geometry data not loaded, '\n                  'call read_geometry() first!')\n            raise ValueError(em)\n        data = read_xdr_file(infile)\n        self.atmos = {}\n        nhydr = read_xdr_var(data, ('i',))\n        nelem = read_xdr_var(data, ('i',))\n        self.atmos['nhydr'] = nhydr\n        self.atmos['nelem'] = nelem\n        # read some parameters and define structure to be read\n        if self.geometry_type == 'ONE_D_PLANE':\n            ndep = self.ndep\n            atmos_vars = [('moving', 'i'), ('T', 'd', (ndep,)),\n                          ('n_elec', 'd', (ndep,)), ('vturb', 'd', (ndep,)),\n                          ('nh', 'd', (ndep, nhydr)), ('id', 's')]\n        elif self.geometry_type == 'TWO_D_PLANE':\n            nx, nz = self.nx, self.nz\n            atmos_vars = [('moving', 'i'), ('T', 'd', (nx, nz)),\n                          ('n_elec', 'd', (nx, nz)), ('vturb', 'd', (nx, nz)),\n                          ('nh', 'd', (nx, nz, nhydr)), ('id', 's')]\n        elif self.geometry_type == 'THREE_D_PLANE':\n            nx, ny, nz = self.nx, self.ny, self.nz\n            atmos_vars = [('moving', 'i'), ('T', 'd', (nx, ny, nz)),\n                          ('n_elec', 'd', (nx, ny, nz)\n                           ), ('vturb', 'd', (nx, ny, nz)),\n                          ('nh', 'd', (nx, ny, nz, nhydr)), ('id', 's')]\n        elif self.geometry_type == 'SPHERICAL_SYMMETRIC':\n            nradius = self.nradius\n            atmos_vars = [('moving', 'i'), ('T', 'd', (nradius,)),\n                          ('n_elec', 'd', (nradius,)), ('vturb', 'd', (nradius,)),\n                          ('nh', 'd', (nradius, nhydr)), ('id', 's')]\n        # read data\n        for v in atmos_vars:\n            self.atmos[v[0]] = read_xdr_var(data, v[1:])\n        # read elements into nested dictionaries\n        self.elements = {}\n        for v in range(nelem):\n            el = read_xdr_var(data, ('s',)).strip()\n            weight = read_xdr_var(data, ('d',))\n            abund = read_xdr_var(data, ('d',))\n            self.elements[el] = {'weight': weight, 'abund': abund}\n        # read stokes data, if present\n        self.stokes = False\n        if self.geometry_type != 'SPHERICAL_SYMMETRIC':\n            try:\n                stokes = read_xdr_var(data, ('i',))\n            except EOFError or IOError:\n                if self.verbose:\n                    print('(WWW) read_atmos: no Stokes data in atmos.out,'\n                          ' skipping.')\n                return\n            self.stokes = True\n            ss = self.atmos['T'].shape\n            stokes_vars = [('B', 'd', ss), ('gamma_B', 'd', ss),\n                           ('chi_B', 'd', ss)]\n            for v in stokes_vars:\n                self.atmos[v[0]] = read_xdr_var(data, v[1:])\n        close_xdr(data, infile, verbose=self.verbose)\n\n    def read_spectrum(self, infile='spectrum.out'):\n        ''' Reads RH spectrum.out file '''\n        if not hasattr(self, 'geometry'):\n            em = ('read_spectrum: geometry data not loaded, '\n                  'call read_geometry() first!')\n            raise ValueError(em)\n        if not hasattr(self, 'atmos'):\n            em = ('read_spectrum: atmos data not loaded, '\n                  'call read_atmos() first!')\n            raise ValueError(em)\n        data = read_xdr_file(infile)\n        profs = {}\n        self.spec = {}\n        nspect = read_xdr_var(data, ('i',))\n        self.spec['nspect'] = nspect\n        nrays = self.nrays\n        self.wave = read_xdr_var(data, ('d', (nspect,)))\n        if self.geometry_type == 'ONE_D_PLANE':\n            ishape = (nrays, nspect)\n        elif self.geometry_type == 'TWO_D_PLANE':\n            ishape = (self.nx, nrays, nspect)\n        elif self.geometry_type == 'THREE_D_PLANE':\n            ishape = (self.nx, self.ny, nrays, nspect)\n        elif self.geometry_type == 'SPHERICAL_SYMMETRIC':\n            ishape = (nrays, nspect)\n        self.imu = read_xdr_var(data, ('d', ishape))\n        self.spec['vacuum_to_air'] = read_xdr_var(data, ('i',))\n        self.spec['air_limit'] = read_xdr_var(data, ('d',))\n        if self.stokes:\n            self.stokes_Q = read_xdr_var(data, ('d', ishape))\n            self.stokes_U = read_xdr_var(data, ('d', ishape))\n            self.stokes_V = read_xdr_var(data, ('d', ishape))\n        close_xdr(data, infile, verbose=self.verbose)\n        # read as_rn, if it exists\n        if os.path.isfile('asrs.out'):\n            data = read_xdr_file('asrs.out')\n            if self.atmos['moving'] or self.stokes or self.input['PRD_angle_dep']:\n                self.spec['as_rn'] = read_xdr_var(data, ('i', (nrays, nspect)))\n            else:\n                self.spec['as_rn'] = read_xdr_var(data, ('i', (nspect,)))\n            close_xdr(data, 'asrs.out', verbose=self.verbose)\n\n    def read_ray(self, infile='spectrum_1.00'):\n        ''' Reads spectra for single ray files (e.g. mu=1). '''\n        if not hasattr(self, 'geometry'):\n            em = ('read_spectrum: geometry data not loaded,'\n                  ' call read_geometry() first!')\n            raise ValueError(em)\n        if not hasattr(self, 'spec'):\n            em = ('read_spectrum: spectral data not loaded, '\n                  'call read_spectrum() first!')\n            raise ValueError(em)\n        data = read_xdr_file(infile)\n        nspect = self.spec['nspect']\n        self.ray = {}\n        if self.geometry_type == 'ONE_D_PLANE':\n            self.muz = read_xdr_var(data, ('d',))\n            ishape = (nspect,)\n            sshape = (self.ndep,)\n        elif self.geometry_type == 'TWO_D_PLANE':\n            self.mux = read_xdr_var(data, ('d',))\n            self.muz = read_xdr_var(data, ('d',))\n            ishape = (self.nx, nspect)\n            sshape = (self.nx, self.nz)\n        elif self.geometry_type == 'THREE_D_PLANE':\n            self.mux = read_xdr_var(data, ('d',))\n            self.muy = read_xdr_var(data, ('d',))\n            ishape = (self.nx, self.ny, nspect)\n            sshape = (self.nx, self.ny, self.nz)\n        elif self.geometry_type == 'SPHERICAL_SYMMETRIC':\n            self.muz = read_xdr_var(data, ('d',))\n            ishape = (nspect,)\n            sshape = (self.nradius,)\n        # read intensity\n        self.int = read_xdr_var(data, ('d', ishape))\n        # read absorption and source function if written\n        ns = read_xdr_var(data, ('i',))\n        if ns > 0:\n            nshape = (ns,) + sshape\n            self.ray['chi'] = np.zeros(nshape, dtype='d')\n            self.ray['S'] = np.zeros(nshape, dtype='d')\n            self.ray['wave_idx'] = np.zeros(ns, dtype='l')\n            for i in range(ns):\n                self.ray['wave_idx'][i] = read_xdr_var(data, ('i',))\n                self.ray['chi'][i] = read_xdr_var(data, ('d', sshape))\n                self.ray['S'][i] = read_xdr_var(data, ('d', sshape))\n        if self.stokes:\n            self.ray_stokes_Q = read_xdr_var(data, ('d', ishape))\n            self.ray_stokes_U = read_xdr_var(data, ('d', ishape))\n            self.ray_stokes_V = read_xdr_var(data, ('d', ishape))\n        close_xdr(data, infile, verbose=self.verbose)\n\n    def read_brs(self, infile='brs.out'):\n        ''' Reads the file with the background opacity record settings,\n            in the old (xdr) format. '''\n        if not hasattr(self, 'geometry'):\n            em = ('read_brs: geometry data not loaded, call read_geometry()'\n                  ' first!')\n            raise ValueError(em)\n        if not hasattr(self, 'spec'):\n            em = ('read_brs: spectrum data not loaded, call read_spectrum()'\n                  ' first!')\n            raise ValueError(em)\n        data = read_xdr_file(infile)\n        atmosID = read_xdr_var(data, ('s',)).strip()\n        nspace = read_xdr_var(data, ('i',))\n        nspect = read_xdr_var(data, ('i',))\n        if nspect != self.spec['nspect']:\n            em = ('(EEE) read_brs: nspect in file different from atmos. '\n                  'Aborting.')\n            raise ValueError(em)\n        self.brs = {}\n        if self.atmos['moving'] or self.stokes:\n            ishape = (2, self.nrays, nspect)\n        else:\n            ishape = (nspect,)\n        self.brs['hasline'] = read_xdr_var(\n            data, ('i', (nspect,))).astype('Bool')\n        self.brs['ispolarized'] = read_xdr_var(\n            data, ('i', (nspect,))).astype('Bool')\n        self.brs['backgrrecno'] = read_xdr_var(data, ('i', ishape))\n        close_xdr(data, infile, verbose=self.verbose)\n\n    def read_j(self, infile='J.dat'):\n        ''' Reads the mean radiation field, for all wavelengths. '''\n        if not hasattr(self, 'geometry'):\n            em = 'read_j: geometry data not loaded, call read_geometry() first!'\n            raise ValueError(em)\n        if not hasattr(self, 'spec'):\n            em = 'read_j: spectrum data not loaded, call read_spec() first!'\n            raise ValueError(em)\n        data_file = open(infile, 'r')\n        nspect = self.spec['nspect']\n        if self.geometry_type == 'ONE_D_PLANE':\n            rec_len = self.ndep * 8\n            ishape = (nspect, self.ndep)\n        elif self.geometry_type == 'TWO_D_PLANE':\n            rec_len = (self.nx * self.nz) * 8\n            ishape = (nspect, self.nx, self.nz)\n        elif self.geometry_type == 'THREE_D_PLANE':\n            rec_len = (self.nx * self.ny * self.nz) * 8\n            ishape = (nspect, self.nx, self.ny, self.nz)\n        elif self.geometry_type == 'SPHERICAL_SYMMETRIC':\n            rec_len = self.nradius * 8\n            ishape = (nspect, self.nradius)\n        self.J = np.zeros(ishape)\n        for i in range(nspect):\n            # point background file to position and read\n            data_file.seek(i * rec_len)\n            self.J[i] = read_file_var(data_file, ('d', ishape[1:]))\n        data_file.close()\n\n    def read_opacity(self, infile_line='opacity.out', infile_bg='background.dat',\n                     imu=0):\n        ''' Reads RH atmos.out file '''\n        if not hasattr(self, 'geometry'):\n            em = ('read_opacity: geometry data not loaded,'\n                  ' call read_geometry() first!')\n            raise ValueError(em)\n        if not hasattr(self, 'spec'):\n            em = ('read_opacity: spectrum data not loaded,'\n                  ' call read_spec() first!')\n            raise ValueError(em)\n        if not hasattr(self.atmos, 'brs'):\n            self.read_brs()\n        data_line = read_xdr_file(infile_line)\n        file_bg = open(infile_bg, 'r')\n        nspect = self.spec['nspect']\n        if self.geometry_type == 'ONE_D_PLANE':\n            as_rec_len = 2 * self.ndep * 8\n            bg_rec_len = self.ndep * 8\n            ishape = (nspect, self.ndep)\n        elif self.geometry_type == 'TWO_D_PLANE':\n            as_rec_len = 2 * (self.nx * self.nz) * 8\n            bg_rec_len = (self.nx * self.nz) * 8\n            ishape = (nspect, self.nx, self.nz)\n        elif self.geometry_type == 'THREE_D_PLANE':\n            as_rec_len = 2 * (self.nx * self.ny * self.nz) * 8\n            bg_rec_len = (self.nx * self.ny * self.nz) * 8\n            ishape = (nspect, self.nx, self.ny, self.nz)\n        elif self.geometry_type == 'SPHERICAL_SYMMETRIC':\n            as_rec_len = 2 * self.nradius * 8\n            bg_rec_len = self.nradius * 8\n            ishape = (nspect, self.nradius)\n        # create arrays\n        chi_as = np.zeros(ishape)\n        eta_as = np.zeros(ishape)\n        chi_c = np.zeros(ishape)\n        eta_c = np.zeros(ishape)\n        scatt = np.zeros(ishape)\n        # NOTE: this will not work when a line is polarised.\n        #       For those cases these arrays must be read per wavelength, and will\n        #       have different sizes for different wavelengths.\n        if np.sum(self.brs['ispolarized']):\n            em = ('read_opacity: Polarized line(s) detected, cannot continue'\n                  ' with opacity extraction')\n            raise ValueError(em)\n        # get record numbers\n        if self.atmos['moving'] or self.stokes or self.input['PRD_angle_dep']:\n            as_index = self.spec['as_rn'][imu] * as_rec_len\n            bg_index = self.brs['backgrrecno'][1, imu] * bg_rec_len\n        else:\n            as_index = self.spec['as_rn'] * as_rec_len\n            bg_index = self.brs['backgrrecno'] * bg_rec_len\n        # Read arrays\n        for i in range(nspect):\n            if as_index[i] >= 0:  # avoid non-active set lines\n                # point xdr buffer to position and read\n                data_line.set_position(as_index[i])\n                chi_as[i] = read_xdr_var(data_line, ('d', ishape[1:]))\n                eta_as[i] = read_xdr_var(data_line, ('d', ishape[1:]))\n            # point background file to position and read\n            file_bg.seek(bg_index[i])\n            chi_c[i] = read_file_var(file_bg, ('d', ishape[1:]))\n            eta_c[i] = read_file_var(file_bg, ('d', ishape[1:]))\n            scatt[i] = read_file_var(file_bg, ('d', ishape[1:]))\n        self.chi_as = chi_as\n        self.eta_as = eta_as\n        self.chi_c = chi_c\n        self.eta_c = eta_c\n        self.scatt = scatt\n        close_xdr(data_line, infile_line, verbose=False)\n        file_bg.close()\n\n    def get_contrib_imu(self, imu, type='total', op_file='opacity.out',\n                        bg_file='background.dat', j_file='J.dat'):\n        ''' Calculates the contribution function for intensity, for a\n            particular ray, defined by imu.\n\n            type can be: \\'total\\', \\'line, or \\'continuum\\'\n\n            The units of self.contribi are J m^-2 s^-1 Hz^-1 sr^-1 km^-1\n\n            NOTE: This only calculates the contribution function for\n                  the quadrature rays (ie, often not for disk-centre)\n                  For rays calculated with solve ray, one must use\n                  get_contrib_ray\n\n        '''\n        type = type.lower()\n        if not hasattr(self, 'geometry'):\n            em = ('get_contrib_imu: geometry data not loaded,'\n                  ' call read_geometry() first!')\n            raise ValueError(em)\n        if not hasattr(self, 'spec'):\n            em = ('get_contrib_imu: spectrum data not loaded,'\n                  ' call read_spec() first!')\n            raise ValueError(em)\n        self.read_opacity(infile_line=op_file, infile_bg=bg_file, imu=imu)\n        self.read_j(infile=j_file)\n        mu = self.geometry['xmu'][imu]\n        # Calculate optical depth\n        ab = (self.chi_c + self.chi_as)\n        self.tau = get_tau(self.geometry['height'], mu, ab)\n        # Calculate source function\n        if type == 'total':\n            self.S = (self.eta_as + self.eta_c + self.J * self.scatt) / ab\n        elif type == 'line':\n            self.S = self.eta_as / ab\n        elif type == 'continuum':\n            self.S = (self.eta_c + self.J * self.scatt) / ab\n        else:\n            raise ValueError('get_contrib_imu: invalid type!')\n        # Calculate contribution function\n        self.contribi = get_contrib(\n            self.geometry['height'], mu, self.tau, self.S)\n        return\n\n    def get_contrib_ray(self, inray='ray.input', rayfile='spectrum_1.00'):\n        ''' Calculates the contribution function for intensity, for a\n            particular ray\n\n            The units of self.contrib are J m^-2 s^-1 Hz^-1 sr^-1 km^-1\n        '''\n        inray = self.fdir + '/' + inray\n        rayfile = self.fdir + '/' + rayfile\n        if not hasattr(self, 'ray'):\n            self.read_ray(infile=rayfile)\n        if 'wave_idx' not in list(self.ray.keys()):\n            em = ('get_contrib_ray: no chi/source function written to '\n                  'ray file, aborting.')\n            raise ValueError(em)\n        # read mu from ray.input file\n        mu = np.loadtxt(inray, dtype='f')[0]\n        if not (0 <= mu <= 1.):\n            em = 'get_contrib_ray: invalid mu read: %f' % mu\n            raise ValueError(em)\n        idx = self.ray['wave_idx']\n        # Calculate optical depth\n        self.tau = get_tau(self.geometry['height'], mu, self.ray['chi'])\n        # Calculate contribution function\n        self.contrib = get_contrib(self.geometry['height'], mu, self.tau,\n                                   self.ray['S'])\n        return\n\n\nclass RhAtmos:\n    \"\"\"\n    Reads input atmosphere from RH. Currently only 2D format supported.\n\n    Parameters\n    ----------\n    format : str, optional\n        Atmosphere format. Currently only '2D' (default) supported.\n    filename : str, optional\n        File to read.\n    verbose : str, optional\n        If True, will print more details.\n    \"\"\"\n    def __init__(self, format=\"2D\", filename=None, verbose=True):\n        ''' Reads RH input atmospheres. '''\n        self.verbose = verbose\n        if format.lower() == \"2d\":\n            if filename is not None:\n                self.read_atmos2d(filename)\n        else:\n            raise NotImplementedError(\"Format %s not yet supported\" % format)\n\n    def read_atmos2d(self, filename):\n        \"\"\"\n        Reads input 2D atmosphere\n        \"\"\"\n        data = read_xdr_file(filename)\n        self.nx = read_xdr_var(data, ('i',))\n        self.nz = read_xdr_var(data, ('i',))\n        self.nhydr = read_xdr_var(data, ('i',))\n        self.hboundary = read_xdr_var(data, ('i',))\n        self.bvalue = read_xdr_var(data, ('i', (2, )))\n        nx, nz, nhydr = self.nx, self.nz, self.nhydr\n        atmos_vars = [('dx', 'd', (nx,)), ('z', 'd', (nz,)),\n                      ('T', 'd', (nx, nz)), ('ne', 'd', (nx, nz)),\n                      ('vturb', 'd', (nx, nz)), ('vx', 'd', (nx, nz)),\n                      ('vz', 'd', (nx, nz)), ('nh', 'd', (nx, nz, nhydr))\n                      ]\n        for v in atmos_vars:\n            setattr(self, v[0], read_xdr_var(data, v[1:]))\n\n    def write_atmos2d(self, filename, dx, z, T, ne, vturb, vx, vz, nh,\n                      hboundary, bvalue):\n        nx, nz = T.shape\n        nhydr = nh.shape[-1]\n        assert T.shape == ne.shape\n        assert ne.shape == vturb.shape\n        assert vturb.shape == nh.shape[:-1]\n        assert dx.shape[0] == nx\n        assert z.shape[0] == nz\n        # Pack as double\n        p = xdrlib.Packer()\n        p.pack_int(nx)\n        p.pack_int(nz)\n        p.pack_int(nhydr)\n        p.pack_int(hboundary)\n        p.pack_int(bvalue[0])\n        p.pack_int(bvalue[1])\n        p.pack_farray(nx, dx.ravel().astype('d'), p.pack_double)\n        p.pack_farray(nz, z.ravel().astype('d'), p.pack_double)\n        p.pack_farray(nx * nz, T.ravel().astype('d'), p.pack_double)\n        p.pack_farray(nx * nz, ne.ravel().astype('d'), p.pack_double)\n        p.pack_farray(nx * nz, vturb.ravel().astype('d'), p.pack_double)\n        p.pack_farray(nx * nz, vx.ravel().astype('d'), p.pack_double)\n        p.pack_farray(nx * nz, vz.ravel().astype('d'), p.pack_double)\n        p.pack_farray(nx * nz * nhydr, nh.T.ravel().astype('d'), p.pack_double)\n        # Write to file\n        f = open(filename, 'wb')\n        f.write(p.get_buffer())\n        f.close()\n\n\n#############################################################################\n# TOOLS\n#############################################################################\nclass EmptyData:\n    def __init__(self):\n        pass\n\n\ndef read_xdr_file(filename):  # ,var,cl=None,verbose=False):\n    \"\"\"\n    Reads data from XDR file.\n\n    Because of the way xdrlib works, this reads the whole file to\n    memory at once. Avoid with very large files.\n\n    Parameters\n    ----------\n    filename : string\n        File to read.\n\n    Returns\n    -------\n    result   : xdrlib.Unpacker object\n    \"\"\"\n    try:\n        f = io.open(filename, 'rb')\n        data = f.read()\n        f.close()\n    except IOError as e:\n        raise IOError(\n            'read_xdr_file: problem reading {0}: {1}'.format(filename, e))\n    # return XDR data\n    return xdrlib.Unpacker(data)\n\n\ndef close_xdr(buf, ofile='', verbose=False):\n    \"\"\"\n    Closes the xdrlib.Unpacker object, gives warning if not all data read.\n\n    Parameters\n    ----------\n    buf : xdrlib.Unpacker object\n        data object.\n    ofile : string, optional\n        Original file from which data was read.\n    verbose : bool, optional\n        Whether to print warning or not.\n    \"\"\"\n    try:\n        buf.done()\n    except:  # .done() will raise error if data remaining\n        if verbose:\n            print(('(WWW) close_xdr: {0} not all data read!'.format(ofile)))\n\n\ndef read_xdr_var(buf, var):\n    \"\"\"\n    Reads a single variable/array from a xdrlib.Unpack buffer.\n\n    Parameters\n    ----------\n\n    buf:  xdrlib.Unpack object\n        Data buffer.\n    var: tuple with (type[,shape]), where type is 'f', 'd', 'i', 'ui',\n             or 's'. Shape is optional, and if true is shape of array.\n        Type and shape of variable to read\n\n    Returns\n    -------\n    out :  int/float or array\n        Resulting variable.\n    \"\"\"\n    assert len(var) > 0\n    if var[0] not in ['f', 'd', 'i', 'ui', 's']:\n        raise ValueError('read_xdr_var: data type'\n                         ' {0} not currently supported'.format(var[0]))\n    fdict = {'f': buf.unpack_float,\n             'd': buf.unpack_double,\n             'i': buf.unpack_int,\n             'ui': buf.unpack_uint,\n             's': buf.unpack_string}\n    func = fdict[var[0]]\n    # Single or array?\n    if len(var) == 1:\n        # this is because RH seems to write the size of the string twice\n        if var[0] == 's':\n            buf.unpack_int()\n        out = func()\n    else:\n        nitems = np.prod(var[1])\n        out = np.array(buf.unpack_farray(nitems, func)).reshape(var[1][::-1])\n        # invert order of indices, to match IDL's\n        out = np.transpose(out, list(range(len(var[1])))[::-1])\n    return out\n\n\ndef read_file_var(buf, var):\n    ''' Reads a single variable/array from a file buffer.\n\n    IN:\n       buf:  open file object\n       var:  tuple with (type[,shape]), where type is 'f', 'd', 'i', 'ui',\n             or 's'. Shape is optional, and if true is shape of array.\n    OUT:\n       variable/array\n\n    '''\n    assert len(var) > 0\n    if len(var) == 1:\n        out = np.fromfile(buf, dtype=var, count=1)\n    elif len(var) == 2:\n        out = np.fromfile(buf, dtype=var[0], count=var[1][0])\n    else:\n        nitems = np.prod(var[1])\n        out = np.array(np.fromfile(buf, dtype=var[0], count=nitems)).\\\n            reshape(var[1][::-1])\n        out = np.transpose(out, list(range(len(var[1])))[::-1])\n    return out\n\n\ndef get_tau(x, mu, chi):\n    ''' Calculates the optical depth, given x (height), mu (cos[theta]) and\n        chi, absorption coefficient. Chi can be n-dimensional, as long as\n        last index is depth.\n    '''\n    # With scipy, this could be done in one line with\n    # scipy.integrate.quadrature.cumtrapz, but we are avoiding scipy to keep\n    # these tools more independent\n    if len(x) != chi.shape[-1]:\n        raise ValueError('get_tau: x and chi have different sizes!')\n    path = x / mu\n    npts = len(x)\n    # bring depth to first index, to allow n-d algebra\n    chi_t = np.transpose(chi)\n    tau = np.zeros(chi_t.shape)\n    for i in range(1, npts):\n        tau[i] = tau[i - 1] + 0.5 * \\\n            (chi_t[i - 1] + chi_t[i]) * (path[i - 1] - path[i])\n    return tau.T\n\n\ndef get_contrib(z, mu, tau_in, S):\n    ''' Calculates contribution function using x, mu, tau, and the source\n        function. '''\n    # Tau truncated at 100 (large enough to be useless)\n    tau = tau_in.copy()\n    tau[tau_in > 100.] = 100.\n    # Calculate dtau (transpose to keep n-D generic form), and dx\n    dtau = np.zeros(tau_in.shape[::-1])\n    tt = np.transpose(tau_in)\n    dtau[1:] = tt[1:] - tt[:-1]\n    dtau = np.transpose(dtau)\n    dx = np.zeros(z.shape)\n    dx[1:] = (z[1:] - z[:-1]) / mu\n    dx[0] = dx[1]\n    # Calculate contribution function\n    contrib = S * np.exp(-tau) * (- dtau / dx) / mu\n    # convert from m^-1 to km^-1, units are now: J m^-2 s^-1 Hz^-1 sr^-1 km^-1\n    contrib *= 1.e3\n    return contrib\n\n\ndef write_B(outfile, Bx, By, Bz):\n    ''' Writes a RH magnetic field file. Input B arrays can be any rank, as\n        they will be flattened before write. Bx, By, Bz units should be T.'''\n    if (Bx.shape != By.shape) or (By.shape != Bz.shape):\n        raise TypeError('writeB: B arrays have different shapes!')\n    n = np.prod(Bx.shape)\n    # Convert into spherical coordinates\n    B = np.sqrt(Bx**2 + By**2 + Bz**2)\n    gamma_B = np.arccos(Bz / B)\n    chi_B = np.arctan(By / Bx)\n    # Pack as double\n    p = xdrlib.Packer()\n    p.pack_farray(n, B.ravel().astype('d'), p.pack_double)\n    p.pack_farray(n, gamma_B.ravel().astype('d'), p.pack_double)\n    p.pack_farray(n, chi_B.ravel().astype('d'), p.pack_double)\n    # Write to file\n    f = open(outfile, 'wb')\n    f.write(p.get_buffer())\n    f.close()\n    return\n", "meta": {"hexsha": "ec9fbc1d2609eacbe802da9a1a1f249f370cdb29", "size": 29862, "ext": "py", "lang": "Python", "max_stars_repo_path": "helita/sim/rh.py", "max_stars_repo_name": "temcomp/helita", "max_stars_repo_head_hexsha": "33c71837f79cb2acb89144fcfb59a7ae84fe6db0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-06-14T14:43:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-14T15:34:32.000Z", "max_issues_repo_path": "helita/sim/rh.py", "max_issues_repo_name": "temcomp/helita", "max_issues_repo_head_hexsha": "33c71837f79cb2acb89144fcfb59a7ae84fe6db0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2017-06-29T18:32:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-29T13:18:34.000Z", "max_forks_repo_path": "helita/sim/rh.py", "max_forks_repo_name": "temcomp/helita", "max_forks_repo_head_hexsha": "33c71837f79cb2acb89144fcfb59a7ae84fe6db0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2017-05-23T15:36:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T06:51:44.000Z", "avg_line_length": 40.3540540541, "max_line_length": 82, "alphanum_fraction": 0.5293014534, "include": true, "reason": "import numpy", "num_tokens": 7920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.16591663414997937}}
{"text": "#!/usr/bin/env python\n#\n#  A Python package for temporal consistency and scheduling.\n#\n#  Copyright (c) 2015 MIT. All rights reserved.\n#\n#   author: Pedro Santana\n#   e-mail: psantana@mit.edu\n#   website: people.csail.mit.edu/psantana\n#\n#  Redistribution and use in source and binary forms, with or without\n#  modification, are permitted provided that the following conditions\n#  are met:\n#\n#  1. Redistributions of source code must retain the above copyright\n#     notice, this list of conditions and the following disclaimer.\n#  2. Redistributions in binary form must reproduce the above copyright\n#     notice, this list of conditions and the following disclaimer in\n#     the documentation and/or other materials provided with the\n#     distribution.\n#  3. Neither the name(s) of the copyright holders nor the names of its\n#     contributors or of the Massachusetts Institute of Technology may be\n#     used to endorse or promote products derived from this software\n#     without specific prior written permission.\n#\n#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n#  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n#  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n#  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n#  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n#  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n#  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n#  AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n#  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n#  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n#  POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\npytemporal: A Python package for temporal consistency and scheduling.\n\nChance-constrained, strong controllability checker implemented using Gurobi\n\n@author: Pedro Santana (psantana@mit.edu).\n\"\"\"\nfrom gurobipy import *\nimport numpy as np\nimport scipy.stats as st\nfrom .gaussian_piecewise import get_gaussian_partition\n\nclass PARIS(object):\n    \"\"\"\n    Class encapsulating the different functionality of PARIS, the Polynomial-time,\n    RIsk-sensitive Scheduler.\n    \"\"\"\n    def __init__(self,gaussian_div=5,gaussian_optimize_partition=False,\n                 gaussian_lr=0.05,gaussian_tol=1e-5,gaussian_max_iter=10000,\n                 gaussian_lb_sigma=None,gaussian_ub_sigma=None,\n                 random_part_init=False,verbose=False):\n        self.gaussian_div = gaussian_div\n        self.gaussian_optimize_partition = gaussian_optimize_partition\n        self.gaussian_lr = gaussian_lr\n        self.gaussian_tol = gaussian_tol\n        self.gaussian_max_iter = gaussian_max_iter\n        self.gaussian_lb_sigma = gaussian_lb_sigma\n        self.gaussian_ub_sigma = gaussian_ub_sigma\n        self.random_part_init = random_part_init\n        self.verbose = verbose\n\n    def init_model(self,):\n        \"\"\"\n        Initializes an empty optimization model\n        \"\"\"\n        self.model = Model('paris_model')\n        self.model.setParam('OutputFlag',1 if self.verbose else 0)\n        self.modelSense = GRB.MINIMIZE #Minimize risk of STNU reformulation\n\n    def schedule(self,tcs,makespan=False,cc=-1.0,lin_sched_obj=None,reset=True):\n        \"\"\"\n        Automates the process of calling the different forms of the PARIS module.\n        \"\"\"\n        if reset:\n            self.init_model()\n\n        if self.set_minimum_risk_strong_controllability(tcs):\n            #Objective function is makespan\n            if makespan:\n                self.set_makespan_optimization()\n            else:\n                #Objective function has been specified by the user\n                if lin_sched_obj != None:\n                    self.set_linear_schedule_objective(lin_sched_obj)\n            #Add a chance constraint\n            if cc>=0.0:\n                self.set_chance_constraint(cc)\n            return self.solve()\n        else:\n            None,None,None\n\n    def stnu_reformulation(self,pstnu_or_prog=None,makespan=False,cc=-1.0,digits=3):\n        \"\"\"\n        Takes a PSTNU or RMPyL program and performs the appropriate STNU reformulation.\n        It modifies the original object!\n        \"\"\"\n        #The input is a list of temporal constraints (PSTNU)\n        if isinstance(pstnu_or_prog,list):\n            tcs = pstnu_or_prog\n        #The input is an RMPyL program\n        else:\n            if len(pstnu_or_prog.choices)>0:\n                print('\\nWARNING: PARIS should not be used for conditional scheduling!')\n            tcs = pstnu_or_prog.temporal_constraints\n\n        squeeze_dict,risk_bound,sc_schedule = self.schedule(tcs,makespan,cc)\n        if squeeze_dict != None:\n            for tc,tc_dict in squeeze_dict.items():\n                tc.set_stcu(round(tc_dict['lb'],digits),round(tc_dict['ub'],digits))\n            return risk_bound,sc_schedule\n        else:\n            print('The %s is not strongly controllable'%('PSTNU' if isinstance(pstnu_or_prog,list) else 'RMPyL program'))\n            return None,None\n\n    def set_minimum_risk_strong_controllability(self,tcs):\n        \"\"\"\n        Sets up the strong controllability problem for risk minimization.\n        \"\"\"\n        #Extracts the temporal reference structure from the pSTPN, while adding\n        #the required squeezing variables for probabilistic durations.\n        self.sc_reform={'_baseline_risk_':0.0}\n        self.tc_squeeze_var_dict={}\n        requirements=[]\n        for tc in tcs:\n            if tc.type in ['uncontrollable_probabilistic','uncontrollable_bounded']:\n                if tc.end.name in self.sc_reform:\n                    #NOTE:some Zipcar tests had uncontrollable durations sharing\n                    #end points, so I had to convert the exception into a failure in\n                    #order to be able to run all the tests.\n                    print('An event cannot be the end point of two uncontrollable durations.')\n                    return False\n                else:\n                    self.sc_reform[tc.end.name]={'ref':tc.start.name,'lb':tc.lb,'ub':tc.ub}\n\n                if tc.type=='uncontrollable_probabilistic':\n                    dist_type=tc.distribution['type']\n                    if dist_type=='uniform':\n                        lb,ub=tc.distribution['lb'],tc.distribution['ub']\n                        uniform_sc_reformulation(tc,lb,ub,self.model,self.sc_reform,\n                                                 self.tc_squeeze_var_dict)\n                    elif dist_type=='gaussian':\n                        #FIXME:some Zipcar tests had distributions with variance equal to 0.0,\n                        #which cause errors in the piecewise approximation. This is clearly\n                        #inconsistent.\n                        if tc.distribution['variance']>0.0:\n                            smart_piecewise_gaussian_sc_reformulation(tc,self.model,self.sc_reform,\n                                                                      self.tc_squeeze_var_dict,\n                                                                      num_div=self.gaussian_div,\n                                                                      optimize_partition=self.gaussian_optimize_partition,\n                                                                      lr=self.gaussian_lr,\n                                                                      tol=self.gaussian_tol,\n                                                                      max_iter=self.gaussian_max_iter,\n                                                                      gaussian_lb_sigma=self.gaussian_lb_sigma,\n                                                                      gaussian_ub_sigma=self.gaussian_ub_sigma,\n                                                                      random_part_init=self.random_part_init)\n                    else:\n                        raise TypeError('Gurobi only supports uniform and Gaussian distributions at the moment.')\n\n            else:#Controllable duration\n                requirements.append(tc)\n\n        #Adds baseline risk as a constant to the objective (allows correct chance constraints)\n        self.model.setObjective(self.model.getObjective()+self.sc_reform['_baseline_risk_'],GRB.MINIMIZE)\n        self.model.update() # Integrate new variables\n\n        #For strong controllability, only controllable temporal events are variables\n        #in the optimization model. All uncontrollable time points should be replaced\n        #by their maximum and minimum values.\n        self.var_map={}; path_cache={}\n        for tc in requirements:\n            #Minimal and maximal values of temporal distances\n            dv1 = ctg_path(tc.start.name,self.sc_reform,path_cache,self.var_map,\n                           self.model,set())\n            dv2 = ctg_path(tc.end.name,self.sc_reform,path_cache,self.var_map,\n                           self.model,set())\n            df_min,df_max = diff_min_max(dv2,dv1,self.sc_reform,self.var_map)\n\n            #Strongly controllable reformulation\n            self.model.addConstr(df_min>=tc.lb)\n            self.model.addConstr(df_max<=tc.ub)\n\n        self.risk_bound = self.model.getObjective() #Gets the risk bound expression\n        self.model.update()\n\n        return True\n\n    def set_makespan_optimization(self,tight_risk=True,mult=1000.0):\n        \"\"\"\n        Adds makespan to the objective and constraints.\n        \"\"\"\n        #Surrogate objective that ensures a tight risk bound with approximate\n        #makespan\n        if tight_risk:\n            M = len(self.sc_reform)*mult\n            t = self.model.addVar(vtype=GRB.CONTINUOUS,lb=0.0,obj=M) #Makespan\n            self.model.update()\n        else: #Optimizes makespan directly\n            t = self.model.addVar(vtype=GRB.CONTINUOUS,lb=0.0) #Makespan\n            self.model.update()\n            self.model.setObjective(t,GRB.MINIMIZE)\n\n        for ec in self.var_map.values():\n            self.model.addConstr(t-ec>=0.0) #All controllable events should be less\n\n        self.model.update()\n        return t\n\n    def set_linear_schedule_objective(self,lin_sched_obj):\n        \"\"\"\n        Sets a generic linear objective over the controllable schedule variables.\n        \"\"\"\n        valid_objective=True\n        if isinstance(lin_sched_obj,dict):\n            for field in ['events','coefficients','maximize']:\n                if not field in lin_sched_obj:\n                    valid_objective=False\n                    print('\\nERROR: missing field '+field+'\\n')\n                    break\n        else:\n            valid_objective=False\n\n        if valid_objective:\n            #Extracts the names of the events, whether they are given as event\n            #objects or their names directly.\n            ec_names = [e if isinstance(e,str) else e.name for e in lin_sched_obj['events']]\n\n            #Constructs the objective\n            obj = quicksum([lin_sched_obj['coefficients'][i]*self.var_map[n] for i,n in enumerate(ec_names)])\n\n            #Updates the model\n            self.model.setObjective(obj,GRB.MAXIMIZE if lin_sched_obj['maximize'] else GRB.MINIMIZE)\n            self.model.update()\n        else:\n            print('\\nERROR: Invalid specification of linear schedule objective as dictionary.')\n            print('\\t\"events\": list of event objects or names involved in the objective')\n            print('\\t\"coefficients\": list of corresponding coefficients for the events in the objective.')\n            print('\\t\"maximize\": whether to maximize (TRUE) or minimize (FALSE).')\n            obj = None\n\n        return obj\n\n    def set_chance_constraint(self,theta):\n        \"\"\"\n        Adds a chance constraint to the model.\n        \"\"\"\n        cc = self.model.addConstr(self.risk_bound<=theta)\n        return cc\n\n    def solve(self):\n        \"\"\"\n        Solves the internal optimization problem and returns the solution.\n        \"\"\"\n        self.model.optimize()#Solves LP with SC constraints\n\n        if self.model.status == GRB.status.OPTIMAL: #Found optimal squeezing\n            #Returns amount by which temporal constraints should be squeezed,\n            #but only for the ones with non-zero (or very close to zero)\n            #squeezing\n            squeeze_dict={}\n            for tc,tc_dict in self.tc_squeeze_var_dict.items():\n                new_lb_ub_bounds=[]\n                for bound in [tc_dict['lb'],tc_dict['ub']]:\n                    if isinstance(bound,gurobipy.LinExpr):\n                        new_lb_ub_bounds.append(bound.getValue())\n                    elif isinstance(bound,gurobipy.Var):\n                        new_lb_ub_bounds.append(bound.X)\n                    else:\n                        new_lb_ub_bounds.append(bound)\n                risk= tc_dict['risk_function'](tc,new_lb_ub_bounds[0],new_lb_ub_bounds[1])\n                squeeze_dict[tc]={'lb':new_lb_ub_bounds[0],'ub':new_lb_ub_bounds[1],'risk':risk}\n\n            #One possible strongly controllable schedule\n            sc_schedule={event_id:var.X for event_id,var in self.var_map.items()}\n\n            # Returns the objective with the constant _baseline_risk_ added to it already\n            return squeeze_dict,self.risk_bound.getValue(),sc_schedule\n            # return squeeze_dict,sc_model.ObjVal+sc_reform['_baseline_risk_'],sc_schedule\n\n        else: #No relaxation found\n            return None,None,None\n\n\n\ndef ctg_path(event_name,sc_reform,path_cache,var_map,model,prev_events):\n    \"\"\"\n    Recursively computes the controllable and contigent events that influence\n    the schedule of a given event.\n    \"\"\"\n    if event_name in path_cache:#If solution has been already computed, use it\n        return path_cache[event_name]\n    else:\n        if event_name in sc_reform: #End point of uncontrollable duration\n            if event_name in prev_events:\n                raise RuntimeError('Contigent duration loop detected!')\n            else:\n                prev_events.add(event_name)\n            path_ref = ctg_path(sc_reform[event_name]['ref'],sc_reform,path_cache,var_map,model,prev_events)\n            path = [event_name]+path_ref\n        else: #Controllable event\n            if not event_name in var_map:#1-to-1 mapping between events and variables\n                var_map[event_name]=model.addVar(vtype=GRB.CONTINUOUS,lb=0.0)\n                model.update()\n            path = [event_name]\n\n        path_cache[event_name]=path #Caches solution for future use\n        return path\n\ndef diff_min_max(dv2,dv1,sc_reform,var_map):\n    \"\"\"\n    Computes the maximum and the minimum differences between two sequences of events.\n    \"\"\"\n    dvs = [dv1[:-1],dv2[:-1]] #All contingent durations\n    mins = [0.0,0.0]\n    maxs = [0.0,0.0]\n    for i in range(2):\n        for ev in [e for e in dvs[i] if not e in dvs[1-i]]:\n            mins[i] += sc_reform[ev]['lb']\n            maxs[i] += sc_reform[ev]['ub']\n    ec1 = var_map[dv1[-1]]; ec2 = var_map[dv2[-1]]\n    diff_min = ec2-ec1+mins[1]-maxs[0]\n    diff_max = ec2-ec1+maxs[1]-mins[0]\n    return diff_min, diff_max\n\ndef uniform_sc_reformulation(tc,lb,ub,model,sc_reform,tc_squeeze_var_dict):\n    \"\"\"\n    Creates the necessary variables and constraints to treat strong controllability\n    of probabilistic durations with uniform distribution.\n    \"\"\"\n    pdf = 1.0/(ub-lb) #PDF associated with squeezing this variable\n    lb_var = model.addVar(vtype=GRB.CONTINUOUS,lb=0.0,ub=ub-lb,obj=pdf)\n    ub_var = model.addVar(vtype=GRB.CONTINUOUS,lb=0.0,ub=ub-lb,obj=pdf)\n    model.update()\n    #The relaxation cannot make the upper bound bigger than the\n    #lower bound.\n    model.addConstr(lb_var+ub_var<=ub-lb)\n    #Updates the strong controllability reformulation dictionary\n    sc_reform[tc.end.name]['lb']+=lb_var\n    sc_reform[tc.end.name]['ub']+=-ub_var\n    #Updates the correspondence between uncontrollable temporal constraints\n    #and squeezing variables\n    tc_squeeze_var_dict[tc]={'lb':sc_reform[tc.end.name]['lb'],\n                             'ub':sc_reform[tc.end.name]['ub'],\n                             'risk_function':uniform_squeeze_risk}\n\ndef smart_piecewise_gaussian_sc_reformulation(tc,model,sc_reform,tc_squeeze_var_dict,\n                                               num_div=5,optimize_partition=False,\n                                               lr=0.05,tol=1e-5,max_iter=10000,\n                                               gaussian_lb_sigma=None,\n                                               gaussian_ub_sigma=None,\n                                               random_part_init=False):\n    \"\"\"\n    Generates an upper bound for a Gaussian CDF by performing a piecewise constraint\n    approximation of its PDF (therefore approximating the CDF by straight line\n    segments).\n    \"\"\"\n    mean,var = tc.distribution['mean'],tc.distribution['variance']\n    stdev = np.sqrt(var)\n    lb_breaks, ub_breaks = get_gaussian_partition(mean=mean,var=var,num_div=num_div,\n                                                  lb_sigma=gaussian_lb_sigma,\n                                                  ub_sigma=gaussian_ub_sigma,\n                                                  optimize_partition=optimize_partition,\n                                                  random_part_init=random_part_init,\n                                                  lr=lr,tol=tol,max_iter=max_iter)\n\n    lb_vars=[]\n    for i in range(1,len(lb_breaks)):\n        lb_vars.append(model.addVar(vtype=GRB.CONTINUOUS,lb=0.0,ub=lb_breaks[i]-lb_breaks[i-1],\n                                    obj=st.norm.pdf(lb_breaks[i],loc=mean,scale=stdev)))\n    ub_vars=[]\n    for i in range(1,len(ub_breaks)):\n        ub_vars.append(model.addVar(vtype=GRB.CONTINUOUS,lb=0.0,ub=ub_breaks[i]-ub_breaks[i-1],\n                                    obj=st.norm.pdf(ub_breaks[i-1],loc=mean,scale=stdev)))\n\n    #Adds the variables to the model\n    model.update()\n\n    lower_bound = lb_breaks[0]+quicksum(lb_vars) #Total lower bound\n    upper_bound = ub_breaks[-1]-quicksum(ub_vars)#Total upper bound\n\n    #model.addConstr(lower_bound-upper_bound<=0.0)#Lower bound cannot be bigger than upper bound\n\n    #Updates the strong controllability reformulation dictionary\n    sc_reform[tc.end.name]['lb']=lower_bound\n    sc_reform[tc.end.name]['ub']=upper_bound\n\n    #Baseline risk of cutting a Gaussian\n    sc_reform['_baseline_risk_']+=st.norm.cdf(lb_breaks[0],loc=mean,scale=stdev)+1.0-st.norm.cdf(ub_breaks[-1],loc=mean,scale=stdev)\n\n    #Updates the correspondence between uncontrollable temporal constraints\n    #and squeezing variables\n    tc_squeeze_var_dict[tc]={'lb':sc_reform[tc.end.name]['lb'],\n                             'ub':sc_reform[tc.end.name]['ub'],\n                             'risk_function':gaussian_squeeze_risk}\n\n\ndef uniform_squeeze_risk(tc,new_lb,new_ub):\n    \"\"\"\n    Risk for squeezing uniform distributions.\n    \"\"\"\n    ub_squeeze=tc.ub-new_ub; lb_squeeze=new_lb-tc.lb\n    if ub_squeeze>=0.0 and lb_squeeze>=0.0:\n        return (1.0/(tc.ub-tc.lb))*(ub_squeeze+lb_squeeze)\n    else:\n        raise ValueError('Invalid squeezing of uniform distribution:[%f,%f]'%(lb_squeeze,ub_squeeze))\n\ndef gaussian_squeeze_risk(tc,new_lb,new_ub):\n    \"\"\"\n    Risk for squeezing Gaussian distributions.\n    \"\"\"\n    mean = tc.distribution['mean']; stdev=np.sqrt(tc.distribution['variance'])\n    return st.norm.cdf(new_lb,loc=mean,scale=stdev)+1.0-st.norm.cdf(new_ub,loc=mean,scale=stdev)\n", "meta": {"hexsha": "bb1073359654b921aef6ee9c5e3975fb3e663522", "size": 19476, "ext": "py", "lang": "Python", "max_stars_repo_path": "paris.py", "max_stars_repo_name": "phrqas/pytemporal", "max_stars_repo_head_hexsha": "6ec466b83531a8dff41b7c5b87728374d0ba56ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paris.py", "max_issues_repo_name": "phrqas/pytemporal", "max_issues_repo_head_hexsha": "6ec466b83531a8dff41b7c5b87728374d0ba56ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paris.py", "max_forks_repo_name": "phrqas/pytemporal", "max_forks_repo_head_hexsha": "6ec466b83531a8dff41b7c5b87728374d0ba56ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.4821002387, "max_line_length": 132, "alphanum_fraction": 0.6182481002, "include": true, "reason": "import numpy,import scipy", "num_tokens": 4276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.16581621036826152}}
{"text": "# -*- coding: utf-8 -*-\n\n\nfrom collections import namedtuple\n\nfrom numba import types\nimport numpy as np\n\nfrom africanus.averaging.time_and_channel_mapping import (row_mapper,\n                                                          channel_mapper)\nfrom africanus.averaging.shared import (chan_corrs,\n                                        merge_flags,\n                                        vis_output_arrays)\n\nfrom africanus.util.docs import DocstringTemplate\nfrom africanus.util.numba import (is_numba_type_none, generated_jit,\n                                  njit, overload, intrinsic)\n\nTUPLE_TYPE = 0\nARRAY_TYPE = 1\nNONE_TYPE = 2\n\n\ndef matching_flag_factory(present):\n    if present:\n        def impl(flag_row, ri, out_flag_row, ro):\n            return flag_row[ri] == out_flag_row[ro]\n    else:\n        def impl(flag_row, ri, out_flag_row, ro):\n            return True\n\n    return njit(nogil=True, cache=True, inline='always')(impl)\n\n\ndef is_chan_flagged(flag, r, f, c):\n    pass\n\n\n@overload(is_chan_flagged, inline='always')\ndef _is_chan_flagged(flag, r, f, c):\n    if is_numba_type_none(flag):\n        def impl(flag, r, f, c):\n            return True\n    else:\n        def impl(flag, r, f, c):\n            return flag[r, f, c]\n\n    return impl\n\n\n@njit(nogil=True, inline='always')\ndef chan_add(output, input, orow, ochan, irow, ichan, corr):\n    if input is not None:\n        output[orow, ochan, corr] += input[irow, ichan, corr]\n\n\n_row_output_fields = [\"antenna1\", \"antenna2\", \"time_centroid\", \"exposure\",\n                      \"uvw\", \"weight\", \"sigma\"]\nRowAverageOutput = namedtuple(\"RowAverageOutput\", _row_output_fields)\n\n\n@generated_jit(nopython=True, nogil=True, cache=True)\ndef row_average(meta, ant1, ant2, flag_row=None,\n                time_centroid=None, exposure=None, uvw=None,\n                weight=None, sigma=None):\n\n    have_flag_row = not is_numba_type_none(flag_row)\n    flags_match = matching_flag_factory(have_flag_row)\n\n    def impl(meta, ant1, ant2, flag_row=None,\n             time_centroid=None, exposure=None, uvw=None,\n             weight=None, sigma=None):\n\n        out_rows = meta.time.shape[0]\n\n        counts = np.zeros(out_rows, dtype=np.uint32)\n\n        # These outputs are always present\n        ant1_avg = np.empty(out_rows, ant1.dtype)\n        ant2_avg = np.empty(out_rows, ant2.dtype)\n\n        # Possibly present outputs for possibly present inputs\n        uvw_avg = (\n            None if uvw is None else\n            np.zeros((out_rows,) + uvw.shape[1:],\n                     dtype=uvw.dtype))\n\n        time_centroid_avg = (\n            None if time_centroid is None else\n            np.zeros((out_rows,) + time_centroid.shape[1:],\n                     dtype=time_centroid.dtype))\n\n        exposure_avg = (\n            None if exposure is None else\n            np.zeros((out_rows,) + exposure.shape[1:],\n                     dtype=exposure.dtype))\n\n        weight_avg = (\n            None if weight is None else\n            np.zeros((out_rows,) + weight.shape[1:],\n                     dtype=weight.dtype))\n\n        sigma_avg = (\n            None if sigma is None else\n            np.zeros((out_rows,) + sigma.shape[1:],\n                     dtype=sigma.dtype))\n\n        sigma_weight_sum = (\n            None if sigma is None else\n            np.zeros((out_rows,) + sigma.shape[1:],\n                     dtype=sigma.dtype))\n\n        # Iterate over input rows, accumulating into output rows\n        for in_row, out_row in enumerate(meta.map):\n            # Input and output flags must match in order for the\n            # current row to contribute to these columns\n            if flags_match(flag_row, in_row, meta.flag_row, out_row):\n                if uvw is not None:\n                    uvw_avg[out_row, 0] += uvw[in_row, 0]\n                    uvw_avg[out_row, 1] += uvw[in_row, 1]\n                    uvw_avg[out_row, 2] += uvw[in_row, 2]\n\n                if time_centroid is not None:\n                    time_centroid_avg[out_row] += time_centroid[in_row]\n\n                if exposure is not None:\n                    exposure_avg[out_row] += exposure[in_row]\n\n                if weight is not None:\n                    for co in range(weight.shape[1]):\n                        weight_avg[out_row, co] += weight[in_row, co]\n\n                if sigma is not None:\n                    for co in range(sigma.shape[1]):\n                        sva = sigma[in_row, co]**2\n\n                        # Use provided weights\n                        if weight is not None:\n                            wt = weight[in_row, co]\n                            sva *= wt ** 2\n                            sigma_weight_sum[out_row, co] += wt\n                        # Natural weights\n                        else:\n                            sigma_weight_sum[out_row, co] += 1.0\n\n                        # Assign\n                        sigma_avg[out_row, co] += sva\n\n                counts[out_row] += 1\n\n            # Here we can simply assign because input_row baselines\n            # should always match output row baselines\n            ant1_avg[out_row] = ant1[in_row]\n            ant2_avg[out_row] = ant2[in_row]\n\n        # Normalise\n        for out_row in range(out_rows):\n            count = counts[out_row]\n\n            if count > 0:\n                # Normalise uvw\n                if uvw is not None:\n                    uvw_avg[out_row, 0] /= count\n                    uvw_avg[out_row, 1] /= count\n                    uvw_avg[out_row, 2] /= count\n\n                # Normalise time centroid\n                if time_centroid is not None:\n                    time_centroid_avg[out_row] /= count\n\n                # Normalise sigma\n                if sigma is not None:\n                    for co in range(sigma.shape[1]):\n                        ssva = sigma_avg[out_row, co]\n                        wt = sigma_weight_sum[out_row, co]\n\n                        if wt != 0.0:\n                            ssva /= (wt**2)\n\n                        sigma_avg[out_row, co] = np.sqrt(ssva)\n\n        return RowAverageOutput(ant1_avg, ant2_avg,\n                                time_centroid_avg,\n                                exposure_avg, uvw_avg,\n                                weight_avg, sigma_avg)\n\n    return impl\n\n\n_rowchan_output_fields = [\n    \"visibilities\",\n    \"flag\",\n    \"weight_spectrum\",\n    \"sigma_spectrum\"]\nRowChanAverageOutput = namedtuple(\"RowChanAverageOutput\",\n                                  _rowchan_output_fields)\n\n\nclass RowChannelAverageException(Exception):\n    pass\n\n\n@intrinsic\ndef average_visibilities(typingctx, vis, vis_avg, vis_weight_sum,\n                         weight, ri, fi, ro, fo, co):\n\n    import numba.core.types as nbtypes\n\n    have_array = isinstance(vis, nbtypes.Array)\n    have_tuple = isinstance(vis, (nbtypes.Tuple, nbtypes.UniTuple))\n\n    def avg_fn(vis, vis_avg, vis_ws, wt, ri, fi, ro, fo, co):\n        vis_avg[ro, fo, co] += vis[ri, fi, co] * wt\n        vis_ws[ro, fo, co] += wt\n\n    return_type = nbtypes.NoneType(\"none\")\n\n    sig = return_type(vis, vis_avg, vis_weight_sum,\n                      weight, ri, fi, ro, fo, co)\n\n    def codegen(context, builder, signature, args):\n        vis, vis_type = args[0], signature.args[0]\n        vis_avg, vis_avg_type = args[1], signature.args[1]\n        vis_weight_sum, vis_weight_sum_type = args[2], signature.args[2]\n        weight, weight_type = args[3], signature.args[3]\n        ri, ri_type = args[4], signature.args[4]\n        fi, fi_type = args[5], signature.args[5]\n        ro, ro_type = args[6], signature.args[6]\n        fo, fo_type = args[7], signature.args[7]\n        co, co_type = args[8], signature.args[8]\n        return_type = signature.return_type\n\n        if have_array:\n            avg_sig = return_type(vis_type,\n                                  vis_avg_type,\n                                  vis_weight_sum_type,\n                                  weight_type,\n                                  ri_type, fi_type,\n                                  ro_type, fo_type, co_type)\n            avg_args = [vis, vis_avg, vis_weight_sum,\n                        weight, ri, fi, ro, fo, co]\n\n            # Compile function and get handle to output\n            context.compile_internal(builder, avg_fn,\n                                     avg_sig, avg_args)\n        elif have_tuple:\n            for i in range(len(vis_type)):\n                avg_sig = return_type(vis_type.types[i],\n                                      vis_avg_type.types[i],\n                                      vis_weight_sum_type.types[i],\n                                      weight_type,\n                                      ri_type, fi_type,\n                                      ro_type, fo_type, co_type)\n                avg_args = [builder.extract_value(vis, i),\n                            builder.extract_value(vis_avg, i),\n                            builder.extract_value(vis_weight_sum, i),\n                            weight, ri, fi, ro, fo, co]\n\n                # Compile function and get handle to output\n                context.compile_internal(builder, avg_fn,\n                                         avg_sig, avg_args)\n        else:\n            raise TypeError(\"Unhandled visibility array type\")\n\n    return sig, codegen\n\n\n@intrinsic\ndef normalise_visibilities(typingctx, vis_avg, vis_weight_sum, ro, fo, co):\n    import numba.core.types as nbtypes\n\n    have_array = isinstance(vis_avg, nbtypes.Array)\n    have_tuple = isinstance(vis_avg, (nbtypes.Tuple, nbtypes.UniTuple))\n\n    def normalise_fn(vis_avg, vis_ws, ro, fo, co):\n        weight_sum = vis_ws[ro, fo, co]\n\n        if weight_sum != 0.0:\n            vis_avg[ro, fo, co] /= weight_sum\n\n    return_type = nbtypes.NoneType(\"none\")\n    sig = return_type(vis_avg, vis_weight_sum, ro, fo, co)\n\n    def codegen(context, builder, signature, args):\n        vis_avg, vis_avg_type = args[0], signature.args[0]\n        vis_weight_sum, vis_weight_sum_type = args[1], signature.args[1]\n        ro, ro_type = args[2], signature.args[2]\n        fo, fo_type = args[3], signature.args[3]\n        co, co_type = args[4], signature.args[4]\n        return_type = signature.return_type\n\n        if have_array:\n            # Normalise single array\n            norm_sig = return_type(vis_avg_type,\n                                   vis_weight_sum_type,\n                                   ro_type, fo_type, co_type)\n            norm_args = [vis_avg, vis_weight_sum, ro, fo, co]\n\n            context.compile_internal(builder, normalise_fn,\n                                     norm_sig, norm_args)\n        elif have_tuple:\n            # Normalise each array in the tuple\n            for i in range(len(vis_avg_type)):\n                norm_sig = return_type(vis_avg_type.types[i],\n                                       vis_weight_sum_type.types[i],\n                                       ro_type, fo_type, co_type)\n                norm_args = [builder.extract_value(vis_avg, i),\n                             builder.extract_value(vis_weight_sum, i),\n                             ro, fo, co]\n\n                # Compile function and get handle to output\n                context.compile_internal(builder, normalise_fn,\n                                         norm_sig, norm_args)\n        else:\n            raise TypeError(\"Unhandled visibility array type\")\n\n    return sig, codegen\n\n\n@generated_jit(nopython=True, nogil=True, cache=True)\ndef row_chan_average(row_meta, chan_meta,\n                     flag_row=None, weight=None,\n                     visibilities=None, flag=None,\n                     weight_spectrum=None, sigma_spectrum=None):\n\n    dummy_chan_freq = None\n    dummy_chan_width = None\n\n    have_vis = not is_numba_type_none(visibilities)\n    have_flag = not is_numba_type_none(flag)\n    have_flag_row = not is_numba_type_none(flag_row)\n    have_flags = have_flag_row or have_flag\n\n    have_weight = not is_numba_type_none(weight)\n    have_weight_spectrum = not is_numba_type_none(weight_spectrum)\n    have_sigma_spectrum = not is_numba_type_none(sigma_spectrum)\n\n    def impl(row_meta, chan_meta, flag_row=None, weight=None,\n             visibilities=None, flag=None,\n             weight_spectrum=None, sigma_spectrum=None):\n\n        out_rows = row_meta.time.shape[0]\n        nchan, ncorrs = chan_corrs(visibilities, flag,\n                                   weight_spectrum, sigma_spectrum,\n                                   dummy_chan_freq, dummy_chan_width,\n                                   dummy_chan_width, dummy_chan_width)\n\n        chan_map, out_chans = chan_meta\n\n        in_shape = (row_meta.map.shape[0], nchan, ncorrs)\n        out_shape = (out_rows, out_chans, ncorrs)\n\n        if not have_flag:\n            flag_avg = None\n        else:\n            flag_avg = np.full(out_shape, False, dtype=np.bool_)\n\n        # If either flag_row or flag is present, we need to ensure that\n        # effective averaging takes place.\n        if have_flags:\n            flags_match = np.full(in_shape, False, dtype=np.bool_)\n            flag_counts = np.zeros(out_shape, dtype=np.uint32)\n        else:\n            flags_match = None\n            flag_counts = None\n\n        counts = np.zeros(out_shape, dtype=np.uint32)\n\n        # Determine output bin counts both unflagged and flagged\n        for ri, ro in enumerate(row_meta.map):\n            row_flagged = have_flag_row and flag_row[ri] != 0\n            for fi, fo in enumerate(chan_map):\n                for co in range(ncorrs):\n                    flagged = (row_flagged or\n                               (have_flag and flag[ri, fi, co] != 0))\n\n                    if have_flags and flagged:\n                        flag_counts[ro, fo, co] += 1\n                    else:\n                        counts[ro, fo, co] += 1\n\n        # ------\n        # Flags\n        # ------\n\n        # Determine whether input samples should contribute to an output bin\n        # and, if flags are parent, whether the output bin is flagged\n\n        # This follows from the definition of an effective average:\n        #\n        # * bad or flagged values should be excluded\n        #   when calculating the average\n        #\n        # Note that if a bin is completely flagged we still compute an average,\n        # to which all relevant input samples contribute.\n        for ri, ro in enumerate(row_meta.map):\n            row_flagged = have_flag_row and flag_row[ri] != 0\n            for fi, fo in enumerate(chan_map):\n                for co in range(ncorrs):\n                    if counts[ro, fo, co] > 0:\n                        # Output bin should only contain unflagged samples\n                        out_flag = False\n\n                        if have_flag:\n                            # Set output flags\n                            flag_avg[ro, fo, co] = False\n\n                    elif have_flags and flag_counts[ro, fo, co] > 0:\n                        # Output bin is completely flagged\n                        out_flag = True\n\n                        if have_flag:\n                            # Set output flags\n                            flag_avg[ro, fo, co] = True\n                    else:\n                        raise RowChannelAverageException(\"Zero-filled bin\")\n\n                    # We should only add a sample to an output bin\n                    # if the input flag matches the output flag.\n                    # This is because flagged samples don't contribute\n                    # to a bin with some unflagged samples while\n                    # unflagged samples never contribute to a\n                    # completely flagged bin\n                    if have_flags:\n                        in_flag = (row_flagged or\n                                   (have_flag and flag[ri, fi, co] != 0))\n                        flags_match[ri, fi, co] = in_flag == out_flag\n\n        # -------------\n        # Visibilities\n        # -------------\n        if not have_vis:\n            vis_avg = None\n        else:\n            vis_avg, vis_weight_sum = vis_output_arrays(\n                visibilities, out_shape)\n\n            # # Aggregate\n            for ri, ro in enumerate(row_meta.map):\n                for fi, fo in enumerate(chan_map):\n                    for co in range(ncorrs):\n                        if have_flags and not flags_match[ri, fi, co]:\n                            continue\n\n                        wt = (weight_spectrum[ri, fi, co]\n                              if have_weight_spectrum else\n                              weight[ri, co] if have_weight else 1.0)\n\n                        average_visibilities(visibilities,\n                                             vis_avg,\n                                             vis_weight_sum,\n                                             wt, ri, fi, ro, fo, co)\n\n            # Normalise\n            for ro in range(out_rows):\n                for fo in range(out_chans):\n                    for co in range(ncorrs):\n                        normalise_visibilities(\n                            vis_avg, vis_weight_sum, ro, fo, co)\n\n        # ----------------\n        # Weight Spectrum\n        # ----------------\n\n        if not have_weight_spectrum:\n            weight_spectrum_avg = None\n        else:\n            weight_spectrum_avg = np.zeros(out_shape, weight_spectrum.dtype)\n\n            # Aggregate\n            for ri, ro in enumerate(row_meta.map):\n                for fi, fo in enumerate(chan_map):\n                    for co in range(ncorrs):\n                        if have_flags and not flags_match[ri, fi, co]:\n                            continue\n\n                        weight_spectrum_avg[ro, fo, co] += (\n                            weight_spectrum[ri, fi, co])\n\n        # ---------------\n        # Sigma Spectrum\n        # ---------------\n        if not have_sigma_spectrum:\n            sigma_spectrum_avg = None\n        else:\n            sigma_spectrum_avg = np.zeros(out_shape, sigma_spectrum.dtype)\n            sigma_spectrum_weight_sum = np.zeros_like(sigma_spectrum_avg)\n\n            # Aggregate\n            for ri, ro in enumerate(row_meta.map):\n                for fi, fo in enumerate(chan_map):\n                    for co in range(ncorrs):\n                        if have_flags and not flags_match[ri, fi, co]:\n                            continue\n\n                        wt = (weight_spectrum[ri, fi, co]\n                              if have_weight_spectrum else\n                              weight[ri, co] if have_weight else 1.0)\n\n                        ssv = sigma_spectrum[ri, fi, co]**2 * wt**2\n                        sigma_spectrum_avg[ro, fo, co] += ssv\n                        sigma_spectrum_weight_sum[ro, fo, co] += wt\n\n            # Normalise\n            for ro in range(out_rows):\n                for fo in range(out_chans):\n                    for co in range(ncorrs):\n                        sswsum = sigma_spectrum_weight_sum[ro, fo, co]\n                        if sswsum != 0.0:\n                            ssv = sigma_spectrum_avg[ro, fo, co]\n                            sigma_spectrum_avg[ro, fo, co] = np.sqrt(\n                                ssv / sswsum**2)\n\n        return RowChanAverageOutput(vis_avg, flag_avg,\n                                    weight_spectrum_avg,\n                                    sigma_spectrum_avg)\n\n    return impl\n\n\n_chan_output_fields = [\"chan_freq\", \"chan_width\", \"effective_bw\", \"resolution\"]\nChannelAverageOutput = namedtuple(\"ChannelAverageOutput\", _chan_output_fields)\n\n\n@generated_jit(nopython=True, nogil=True, cache=True)\ndef chan_average(chan_meta, chan_freq=None, chan_width=None,\n                 effective_bw=None, resolution=None):\n\n    def impl(chan_meta, chan_freq=None, chan_width=None,\n             effective_bw=None, resolution=None):\n        chan_map, out_chans = chan_meta\n\n        chan_freq_avg = (\n            None if chan_freq is None else\n            np.zeros(out_chans, dtype=chan_freq.dtype))\n\n        chan_width_avg = (\n            None if chan_width is None else\n            np.zeros(out_chans, dtype=chan_width.dtype))\n\n        effective_bw_avg = (\n            None if effective_bw is None else\n            np.zeros(out_chans, dtype=effective_bw.dtype))\n\n        resolution_avg = (\n            None if resolution is None else\n            np.zeros(out_chans, dtype=resolution.dtype))\n\n        counts = np.zeros(out_chans, dtype=np.uint32)\n\n        for in_chan, out_chan in enumerate(chan_map):\n            counts[out_chan] += 1\n\n            if chan_freq is not None:\n                chan_freq_avg[out_chan] += chan_freq[in_chan]\n\n            if chan_width is not None:\n                chan_width_avg[out_chan] += chan_width[in_chan]\n\n            if effective_bw is not None:\n                effective_bw_avg[out_chan] += effective_bw[in_chan]\n\n            if resolution is not None:\n                resolution_avg[out_chan] += resolution[in_chan]\n\n        for out_chan in range(out_chans):\n            if chan_freq is not None:\n                chan_freq_avg[out_chan] /= counts[out_chan]\n\n        return ChannelAverageOutput(chan_freq_avg, chan_width_avg,\n                                    effective_bw_avg, resolution_avg)\n\n    return impl\n\n\nAverageOutput = namedtuple(\"AverageOutput\",\n                           [\"time\", \"interval\", \"flag_row\"] +\n                           _row_output_fields +\n                           _chan_output_fields +\n                           _rowchan_output_fields)\n\n\n@generated_jit(nopython=True, nogil=True, cache=True)\ndef time_and_channel(time, interval, antenna1, antenna2,\n                     time_centroid=None, exposure=None, flag_row=None,\n                     uvw=None, weight=None, sigma=None,\n                     chan_freq=None, chan_width=None,\n                     effective_bw=None, resolution=None,\n                     visibilities=None, flag=None,\n                     weight_spectrum=None, sigma_spectrum=None,\n                     time_bin_secs=1.0, chan_bin_size=1):\n\n    valid_types = (types.misc.Omitted, types.scalars.Float,\n                   types.scalars.Integer)\n\n    if not isinstance(time_bin_secs, valid_types):\n        raise TypeError(\"time_bin_secs must be a scalar float\")\n\n    valid_types = (types.misc.Omitted, types.scalars.Integer)\n\n    if not isinstance(chan_bin_size, valid_types):\n        raise TypeError(\"chan_bin_size must be a scalar integer\")\n\n    def impl(time, interval, antenna1, antenna2,\n             time_centroid=None, exposure=None, flag_row=None,\n             uvw=None, weight=None, sigma=None,\n             chan_freq=None, chan_width=None,\n             effective_bw=None, resolution=None,\n             visibilities=None, flag=None,\n             weight_spectrum=None, sigma_spectrum=None,\n             time_bin_secs=1.0, chan_bin_size=1):\n\n        nchan, ncorrs = chan_corrs(visibilities, flag,\n                                   weight_spectrum, sigma_spectrum,\n                                   chan_freq, chan_width,\n                                   effective_bw, resolution)\n\n        # Merge flag_row and flag arrays\n        flag_row = merge_flags(flag_row, flag)\n\n        # Generate row mapping metadata\n        row_meta = row_mapper(time, interval, antenna1, antenna2,\n                              flag_row=flag_row, time_bin_secs=time_bin_secs)\n\n        # Generate channel mapping metadata\n        chan_meta = channel_mapper(nchan, chan_bin_size)\n\n        # Average row data\n        row_data = row_average(row_meta, antenna1, antenna2, flag_row=flag_row,\n                               time_centroid=time_centroid, exposure=exposure,\n                               uvw=uvw, weight=weight, sigma=sigma)\n\n        # Average channel data\n        chan_data = chan_average(chan_meta, chan_freq=chan_freq,\n                                 chan_width=chan_width,\n                                 effective_bw=effective_bw,\n                                 resolution=resolution)\n\n        # Average row and channel data\n        row_chan_data = row_chan_average(row_meta, chan_meta,\n                                         flag_row=flag_row, weight=weight,\n                                         visibilities=visibilities, flag=flag,\n                                         weight_spectrum=weight_spectrum,\n                                         sigma_spectrum=sigma_spectrum)\n\n        # Have to explicitly write it out because numba tuples\n        # are highly constrained types\n        return AverageOutput(row_meta.time,\n                             row_meta.interval,\n                             row_meta.flag_row,\n                             row_data.antenna1,\n                             row_data.antenna2,\n                             row_data.time_centroid,\n                             row_data.exposure,\n                             row_data.uvw,\n                             row_data.weight,\n                             row_data.sigma,\n                             chan_data.chan_freq,\n                             chan_data.chan_width,\n                             chan_data.effective_bw,\n                             chan_data.resolution,\n                             row_chan_data.visibilities,\n                             row_chan_data.flag,\n                             row_chan_data.weight_spectrum,\n                             row_chan_data.sigma_spectrum)\n\n    return impl\n\n\nAVERAGING_DOCS = DocstringTemplate(\"\"\"\nAverages in time and channel.\n\nParameters\n----------\ntime : $(array_type)\n    Time values of shape :code:`(row,)`.\ninterval : $(array_type)\n    Interval values of shape :code:`(row,)`.\nantenna1 : $(array_type)\n    First antenna indices of shape :code:`(row,)`\nantenna2 : $(array_type)\n    Second antenna indices of shape :code:`(row,)`\ntime_centroid : $(array_type), optional\n    Time centroid values of shape :code:`(row,)`\nexposure : $(array_type), optional\n    Exposure values of shape :code:`(row,)`\nflag_row : $(array_type), optional\n    Flagged rows of shape :code:`(row,)`.\nuvw : $(array_type), optional\n    UVW coordinates of shape :code:`(row, 3)`.\nweight : $(array_type), optional\n    Weight values of shape :code:`(row, corr)`.\nsigma : $(array_type), optional\n    Sigma values of shape :code:`(row, corr)`.\nchan_freq : $(array_type), optional\n    Channel frequencies of shape :code:`(chan,)`.\nchan_width : $(array_type), optional\n    Channel widths of shape :code:`(chan,)`.\neffective_bw : $(array_type), optional\n    Effective channel bandwidth of shape :code:`(chan,)`.\nresolution : $(array_type), optional\n    Effective channel resolution of shape :code:`(chan,)`.\nvisibilities : $(array_type) or tuple of $(array_type), optional\n    Visibility data of shape :code:`(row, chan, corr)`.\n    Tuples of visibilities arrays may be supplied,\n    in which case tuples will be output.\nflag : $(array_type), optional\n    Flag data of shape :code:`(row, chan, corr)`.\nweight_spectrum : $(array_type), optional\n    Weight spectrum of shape :code:`(row, chan, corr)`.\nsigma_spectrum : $(array_type), optional\n    Sigma spectrum of shape :code:`(row, chan, corr)`.\ntime_bin_secs : float, optional\n    Maximum summed interval in seconds to include within a bin.\n    Defaults to 1.0.\nchan_bin_size : int, optional\n    Number of bins to average together.\n    Defaults to 1.\n\nNotes\n-----\n\nThe implementation currently requires unique lexicographical\ncombinations of (TIME, ANTENNA1, ANTENNA2). This can usually\nbe achieved by suitably partitioning input data on indexing rows,\nDATA_DESC_ID and SCAN_NUMBER in particular.\n\nReturns\n-------\nnamedtuple\n    A namedtuple whose entries correspond to the input arrays.\n    Output arrays will be ``None`` if the inputs were ``None``.\n\"\"\")\n\n\ntry:\n    time_and_channel.__doc__ = AVERAGING_DOCS.substitute(\n                                    array_type=\":class:`numpy.ndarray`\")\nexcept AttributeError:\n    pass\n", "meta": {"hexsha": "a1c4aeb877718e1d32ff339375fa4f74828df672", "size": 27780, "ext": "py", "lang": "Python", "max_stars_repo_path": "africanus/averaging/time_and_channel_avg.py", "max_stars_repo_name": "ratt-ru/codex-africanus", "max_stars_repo_head_hexsha": "29c463c7e79eb8d2a2703d3381448d96c6840eb3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2018-04-06T09:36:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-13T13:11:00.000Z", "max_issues_repo_path": "africanus/averaging/time_and_channel_avg.py", "max_issues_repo_name": "ratt-ru/codex-africanus", "max_issues_repo_head_hexsha": "29c463c7e79eb8d2a2703d3381448d96c6840eb3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 153, "max_issues_repo_issues_event_min_datetime": "2018-03-28T14:13:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T07:49:17.000Z", "max_forks_repo_path": "africanus/averaging/time_and_channel_avg.py", "max_forks_repo_name": "ska-sa/codex-africanus", "max_forks_repo_head_hexsha": "f1523ad5923932c02fb8718a841067ba7a4ac6e8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2018-03-29T13:30:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T02:56:55.000Z", "avg_line_length": 37.4898785425, "max_line_length": 79, "alphanum_fraction": 0.5409287257, "include": true, "reason": "import numpy,import numba,from numba", "num_tokens": 5769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.16566081725384624}}
{"text": "from genericpath import getsize\n#from statistics import covariance\nimport sys\nfrom turtle import setundobuffer\nimport numpy as np\n#sys.path=[\"/home/creichardt/.local/lib/python3.7/site-packages/\",\"/home/creichardt/spt3g_software/build\",\"/home/creichardt/.local/lib/python3.7/site-packages/healpy-1.15.0-py3.7-linux-x86_64.egg\"]+sys.path\nimport healpy\n\nimport os\nfrom spt3g import core,maps, calibration\nfrom spectra_port import utils\nimport pickle as pkl\nimport pdb\nimport time\nAlmType = np.dtype(np.complex64)\n\n\ndef name_tempdir(basedir):\n    while True:\n        rand = np.random.randint(0,999999)\n        path = \"{}/workdir_{:6d}\".format(basedir, rand)\n        if not os.path.exists(path):\n            return path\n\ndef printinplace(myString):\n    digits = len(myString)\n    delete = \"\\b\" * (digits)\n    print(\"{0}{1:{2}}\".format(delete, myString, digits), end=\"\")\n    sys.stdout.flush()\n\n\ndef load_spt3g_healpix_ring_map(file,require_order = 'Ring',require_nside=8192,map_key='T'):\n    # only taking 1st map \n    frames = core.G3File(file)\n    for frame in frames:\n        if frame.type == core.G3FrameType.Map:\n            if require_nside is not None:\n                assert(require_nside == frame[map_key].nside)\n            if require_order is not None:\n                assert(frame[map_key].nested == (require_order == 'Nest'))\n            if type(frame[map_key]) is np.ndarray:\n                ind = frame[map_key].nonzero()\n                map = frame[map_key][frame[map_key] != 0]\n            else:\n                ind, map = frame[map_key].nonzero_pixels()\n            return( np.asarray(ind).astype(np.int64,casting='same_kind'), np.asarray(map).astype(np.float32,casting='same_kind') )\n    raise Exception(\"No Map found in file: {}\".format(file))\n\n\n\n\ndef reformat_shts(shtfilelist, processedshtfile,\n                           lmax,\n                           cmbweighting = True, \n                           mask  = None,\n                           kmask = None,\n                           ell_reordering=None,\n                           no_reorder=False,\n                           ram_limit = None,\n                          ) -> 'May be done in Fortran - output is a file':\n    ''' \n    Output is expected to be CL (Dl if cmbweighting=Trure) * mask normalization factor * kweights\n    Output ordering is expected to \n    '''\n    if ram_limit is None:\n        ram_limit = 16 * 2**30 # 16 GB\n\n    # number of bytes in a Dcomplex: 16\n    # number of arrays we need to make to do this efficiently: 6 or less\n    # number of pixels in an fft: winsize^2\n    ram_required=16*6*lmax**2\n    parallelism = int(np.ceil(ram_limit/ram_required))\n\n    inv_mask_factor = 1.\n    if mask is not None:\n        inv_mask_factor = np.sqrt(1./np.mean(mask**2))\n\n    #ie do parallelism SHTs at once...\n    size = healpy.sphtfunc.Alm.getsize(lmax)\n    if kmask is not None:\n        if kmask.shape[0] != size:\n            raise Exception(\"kmask provided is wrong size ({} vs {}), exiting\".format(size,kmask.shape[0]))\n        local_kmask = kmask.astype(np.float32)\n    else:\n        local_kmask = np.ones(size,dtype=np.float32)\n\n        \n    if cmbweighting:\n        dummy_vec = np.arange(lmax+1,dtype=np.float32)\n        dummy_vec = np.sqrt((dummy_vec*(dummy_vec+1.))/(2*np.pi)) # This will be squared since Cl =a*a\n        j=0\n        for i in range(lmax+1):\n            nm = lmax+1-i\n            local_kmask[j:j+nm]=dummy_vec[i:]\n            j=j+nm\n\n\n    if ell_reordering is None:  # need to make it\n        #have lmax+1 m=0's, followed by lmax m=1's.... (if does do l=0,m=0)\n        # healpy has indexing routines, but they only take 1 at a time...\n        #make dummy vec for use\n        dummy_vec = np.zeros(lmax+1,dtype=np.int)\n        k=0\n        for i in np.arange(lmax+1):\n            dummy_vec[i] = k\n            k=k+lmax-i\n        ell_reordering = np.zeros(size,dtype=np.int)\n        k=0\n        for i in range(lmax+1):\n            ell_reordering[k:k+i+1] = dummy_vec[0:i+1] + i\n            k += i+1\n\n\n\n    print('Warning: not using pixel weights in SHT')\n    with open(processedshtfile,'wb') as fp:\n\n        oldtime = time.time()\n        count = 0 \n        for file in shtfilelist:\n            newtime=time.time()\n            timeinminutes = (newtime - oldtime)/60.0\n            oldtime=newtime\n            printinplace('SHT map: {}  Last one took: {:.1f} minutes'.format(count,timeinminutes))\n            count += 1\n\n            #TBD get SHT\n            with np.load(file) as obs_alms:\n                alms = obs_alms['alm']\n            assert lmax ==  healpy.sphtfunc.Alm.getlmax(alms.shape[0])\n\n            #possibly downsample alms to save later CPU cycles\n            # TBD if worthwhile\n\n            #apply weighting (ie cl-dl) and kmask \n            alms *= local_kmask\n\n            #TBD, possibly adjust for mask factor here\n            alms *= inv_mask_factor\n\n            # Get reindexing\n\n            #reorder and write to disk\n            #need to check sizing\n            #32 bit floats/64b complex should be fine for this. will need to bump up by one for aggregation\n            if no_reorder:\n                (alms.astype(AlmType)).tofile(fp)\n            else:\n                (alms[ell_reordering].astype(AlmType)).tofile(fp)\n\ndef take_and_reformat_shts(mapfilelist, processedshtfile,\n                           nside,lmax,\n                           cmbweighting = True, \n                           mask  = None,\n                           kmask = None,\n                           ell_reordering=None,\n                           no_reorder=False,\n                           ram_limit = None,\n                           npmapformat=False, \n                           map_key='T'\n                          ) -> 'May be done in Fortran - output is a file':\n    ''' \n    Output is expected to be CL (Dl if cmbweighting=Trure) * mask normalization factor * kweights\n    Output ordering is expected to \n    '''\n    if ram_limit is None:\n        ram_limit = 16 * 2**30 # 16 GB\n\n    # number of bytes in a Dcomplex: 16\n    # number of arrays we need to make to do this efficiently: 6 or less\n    # number of pixels in an fft: winsize^2\n    ram_required=16*6*lmax**2\n    parallelism = int(np.ceil(ram_limit/ram_required))\n\n    map_scratch = np.zeros(12*nside**2,dtype=np.float32)\n\n    inv_mask_factor = 1.\n    if mask is not None:\n        inv_mask_factor = np.sqrt(1./np.mean(mask**2))\n\n    if mask is not None:\n        if type(mask) is np.ndarray:\n            map_inds = mask.nonzero()\n            cut_mask = mask[mask != 0]\n        else:\n            map_inds, cut_mask = mask.nonzero_pixels()\n        npix = len(map_inds)\n        \n    #ie do parallelism SHTs at once...\n    size = healpy.sphtfunc.Alm.getsize(lmax)\n    if kmask is not None:\n        if kmask.shape[0] != size:\n            raise Exception(\"kmask provided is wrong size ({} vs {}), exiting\".format(size,kmask.shape[0]))\n        local_kmask = kmask.astype(np.float32)\n    else:\n        local_kmask = np.ones(size,dtype=np.float32)\n\n        \n    if cmbweighting:\n        dummy_vec = np.arange(lmax+1,dtype=np.float32)\n        dummy_vec = np.sqrt((dummy_vec*(dummy_vec+1.))/(2*np.pi)) #this will be squared later as Cl=a*a\n        j=0\n        for i in range(lmax+1):\n            nm = lmax+1-i\n            local_kmask[j:j+nm]=dummy_vec[i:]\n            j=j+nm\n\n\n    if ell_reordering is None:  # need to make it\n        #have lmax+1 m=0's, followed by lmax m=1's.... (if does do l=0,m=0)\n        # healpy has indexing routines, but they only take 1 at a time...\n        #make dummy vec for use\n        dummy_vec = np.zeros(lmax+1,dtype=np.int)\n        k=0\n        for i in np.arange(lmax+1):\n            dummy_vec[i] = k\n            k=k+lmax-i\n        ell_reordering = np.zeros(size,dtype=np.int)\n        k=0\n        for i in range(lmax+1):\n            ell_reordering[k:k+i+1] = dummy_vec[0:i+1] + i\n            k += i+1\n\n\n\n    print('Warning: not using pixel weights in SHT')\n    with open(processedshtfile,'wb') as fp:\n\n        oldtime = time.time()\n        count = 0 \n        for file in mapfilelist:\n            newtime=time.time()\n            timeinminutes = (newtime - oldtime)/60.0\n            oldtime=newtime\n            printinplace('SHT map: {}  Last one took: {:.1f} minutes'.format(count,timeinminutes))\n            count += 1\n\n            #TBD get a map\n            if not npmapformat:\n                ring_indices, map_tmp = load_spt3g_healpix_ring_map(file,map_key=map_key)\n\n                map_scratch[:]=0 #reset\n                map_scratch[ring_indices]=map_tmp #fill in the temperature map\n\n                # if not already masked, apply mask\n                #may need to change the next line based on formatting\n                if mask is not None:\n                    map_scratch  = mask*map_scratch\n            else:\n                map_tmp = utils.load_spt3g_cutsky_healpix_ring_map(file,npix)\n                map_scratch[map_inds]=map_tmp * cut_mask\n                    \n            #gets alms\n            alms = healpy.sphtfunc.map2alm(map_scratch,lmax = lmax, pol=False, use_pixel_weights=False, iter = 1,datapath='/sptlocal/user/creichardt/healpy-data/')\n\n            #possibly downsample alms to save later CPU cycles\n            # TBD if worthwhile\n\n            #apply weighting (ie cl-dl) and kmask \n            alms *= local_kmask\n\n            #TBD, possibly adjust for mask factor here\n            alms *= inv_mask_factor\n\n            # Get reindexing\n\n            #reorder and write to disk\n            #need to check sizing\n            #32 bit floats/64b complex should be fine for this. will need to bump up by one for aggregation\n            if no_reorder:\n                (alms.astype(AlmType)).tofile(fp)\n            else:\n                (alms[ell_reordering].astype(AlmType)).tofile(fp)\n\ndef get_first_index_ell(l):\n    # l=0 - 0\n    # l = 1 -> 1 (0+1)\n    # l = 2 ->  3 (1+2)\n    # l = 3 -> 6 (3+3)\n    if type(l) is int:\n        return int(l*(l+1)/2)\n    elif type(l) is np.ndarray:\n        return (l*(l+1)/2).astype(np.int)\n    else:\n        pdb.set_trace()\n        return -1\n\ndef generate_jackknife_shts( processed_shtfile, jackknife_shtfile,  lmax,\n                             setdef) -> 'Does differencing to make SHT equiv file for nulls, returns new setdef':\n    buffer_size = healpy.sphtfunc.Alm.getsize(lmax)\n    buffer_bytes= buffer_size * np.zeros(1,dtype=AlmType).nbytes\n    buffera = np.zeros(buffer_size,dtype=AlmType)\n    bufferb = np.zeros(buffer_size,dtype=AlmType)\n    setsize = setdef.shape[0]\n    nsets   = setdef.shape[1]\n\n    oldtime=time.time()\n    with open(processed_shtfile,'rb') as fin, open(jackknife_shtfile,'wb') as fout:\n        for i in range(setsize):\n            newtime=time.time()\n            timeinminutes = (newtime - oldtime)/60.0\n            oldtime=newtime\n            printinplace('Creating null SHT : {} of {}  Last one took: {:.1f} minutes'.format(i,setsize,timeinminutes))\n            #need to do stuff here\n\n            fin.seek( setdef[i,0] * buffer_bytes )\n            buffera  = np.fromfile(fin,dtype=AlmType,count=buffer_size)\n            fin.seek( setdef[i,1] * buffer_bytes )\n            bufferb  = np.fromfile(fin,dtype=AlmType,count=buffer_size)\n\n            buffera -= bufferb\n            buffera *= 0.5\n            #fout.seek( i * buffer_bytes )\n            (buffera.astype(AlmType)).tofile(fout)\n\n\n    return(np.reshape(np.arange(setsize,dtype=np.int32),[setsize,1]))\n\ndef generate_coadd_shts( processed_shtfile, coadd_shtfile,  lmax,\n                             setdef) -> 'Does differencing to make SHT equiv file for nulls, returns new setdef':\n    '''\n    Setdef in: Nbundles_out (dim0) x Nmaps_to_coadd (dim1)\n    Setdef out: Nbundles_out (same as input dim0)\n    '''\n    \n    buffer_size = healpy.sphtfunc.Alm.getsize(lmax)\n    buffer_bytes= buffer_size * np.zeros(1,dtype=AlmType).nbytes\n    buffera = np.zeros(buffer_size,dtype=AlmType)\n    bufferb = np.zeros(buffer_size,dtype=AlmType)\n    setsize = setdef.shape[0]\n    nsets   = setdef.shape[1]\n\n    with open(processed_shtfile,'rb') as fin, open(coadd_shtfile,'wb') as fout:\n        for i in range(setsize):\n            #need to do stuff here\n\n            fin.seek( setdef[i,0] * buffer_bytes )\n            buffera  = np.fromfile(fin,dtype=AlmType,count=buffer_size)\n            for j in range(1,nsets):\n                fin.seek( setdef[i,1] * buffer_bytes )\n                bufferb  = np.fromfile(fin,dtype=AlmType,count=buffer_size)\n                buffera += bufferb\n            buffera *= (1./nsets)\n            fout.seek( i * buffer_bytes )\n            buffera.tofile(fout)\n\n    return(np.reshape(np.arange(setsize,dtype=np.int32),[setsize,1]))\n\n\ndef load_cross_spectra_data_from_disk(shtfile, nshts, npersht, start, stop):\n    nelems = stop - start + 1\n    buffer_bytes = np.zeros(1,dtype=AlmType).nbytes\n    data = np.zeros([nshts,nelems],dtype=AlmType)\n    print(nshts,nelems)\n    with open(shtfile,'r') as fp:\n        for i in range(nshts):\n            fp.seek((i*npersht+start) * buffer_bytes)\n            data[i,:] = np.fromfile(fp,count=nelems,dtype=AlmType)\n    return data\n\n\ndef take_all_cross_spectra( processedshtfile, lmax,\n                            setdef, banddef, ram_limit=None, auto = False,nshts=None) -> 'Returns set of all x-spectra, binned':\n    '''\n    ;; Step 1, copy all of the fft files and apply scalings masks etc\n\n\n    ;; Step 2 (this function):  average all the bands to create binned x-spectra\n    '''\n    if ram_limit is None:\n        ram_limit = 64 * 2**30 # default limit is 64 GB\n\n\n    # Simplifying assumption axb == (a^c b + b^c a)\n    # assume do *not* do x-spectra between same observation\n    nsets   = setdef.shape[1] #nfreq\n    setsize = setdef.shape[0] #nbundles\n    nspectra=np.int((nsets*(nsets+1))/2 + 0.001)\n    print(nsets,setsize,nspectra)\n    if auto:\n        nrealizations=setsize\n    else:\n        nrealizations=np.int( (setsize*(setsize-1))/2 + 0.001)\n\n    nbands = banddef.shape[0]-1\n    if nshts is  None:\n        nshts  = np.int(np.max(setdef)+1.001)\n\n    npersht = healpy.sphtfunc.Alm.getsize(lmax)\n    #pdb.set_trace()\n    allspectra_out = np.zeros([nbands,nspectra,nrealizations],dtype=np.float32)\n    nmodes_out     = np.zeros(nbands, dtype = np.int32)\n\n    tmpresult = np.zeros([setsize,setsize],dtype=np.float64)\n\n    # number of bytes in a Dcomplex: 16\n    # number of arrays we need to make to do this efficiently: 6 or less\n    # number of pixels in an fft: winsize^2\n    ram_required=16*6*lmax**2\n    max_nmodes=ram_limit/nshts/32 #64 b complex \n\n    assert(banddef[0] == 0 and banddef[-1] < lmax)\n    #assumes banddef[0]=0\n    #so first bin goes 1 - banddef[1]\n    # second bin goes banddef[1]+1 - banddef[2], etc\n    band_start_idx = get_first_index_ell(banddef+1)\n\n    #code=reverse_linefeed_code()\n\n    i=0 # i is the last bin to have finished. initially 0\n    while (i < nbands):\n        istop = np.where((band_start_idx - band_start_idx[i]) < max_nmodes)[0][-1] # get out of tuple, then take last elem of array\n\n        if istop <= i:\n            raise Exception(\"Insufficient ram for processing even a single bin\")\n\n        print('take_all_cross_spectra: loading bands {} {}'.format(i,istop-1))\n        # technical: delete the last iteration of banddata_big first\n        banddata_big=0\n        # get data for as many bins as will fit in our ramlimit\n\n        banddata_big=load_cross_spectra_data_from_disk(processedshtfile, \n                                                       nshts, npersht,   \n                                                       band_start_idx[i],\n                                                       band_start_idx[istop]-1 )\n        #process this data\n        for iprime in range(i, istop):\n            printinplace('processing band {}    '.format(iprime))\n                \n            nmodes=(band_start_idx[iprime+1]-band_start_idx[iprime])\n            nmodes_out[iprime]=nmodes\n            aidx=band_start_idx[iprime]-band_start_idx[i]\n            banddata=banddata_big[:,aidx:(aidx+nmodes-1)] # first index SHT; second index alm\n\n\n            spectrum_idx=0\n            for j in range(nsets):\n                for k in range(j, nsets):\n                    if not auto:\n\n                        tmpresult  = np.real(np.matmul(banddata[setdef[:,j],:],np.conj(banddata[setdef[:,k],:]).T)) #need to check dims -- intended to end up for 3 freqs with 3x3 matrix\n\n                        tmpresult += tmpresult.T # imposing the ab + ba condition\n                        tmpresult /= (2*nmodes)\n                        #it had a factor of 1/(reso**2 winsize**2) \n                        # leaving this out for curved sky\n                        a=0\n                        for l in range(setsize-1):\n                            rowlength=setsize-l-1\n                            allspectra_out[iprime, spectrum_idx, a:(a+rowlength)]=tmpresult[l, l+1:setsize]\n                            a+=rowlength\n                    else:\n                        idx=np.arange(setsize,dtype=np.int)\n                        tmpresult=np.sum(np.real(banddata[setdef[:, j],:]*np.conj(banddata[setdef[:, k],:])), 1,dtype=np.float64) / (nmodes) # had been in flatsky: *reso^2*winsize^2)\n                        allspectra_out[iprime, spectrum_idx, :]=tmpresult.astype(np.float32)\n                    spectrum_idx+=1\n                    #           pdb.set_trace()\n        i=istop\n    return(allspectra_out, nmodes_out)\n\n\ndef take_all_sim_cross_spectra( processedshtfile, lmax,\n                            setdef1,  banddef, setdef2=None, ram_limit=None, auto=False) -> 'Returns set of all x-spectra, binned':\n    '''\n    ;; Step 1, copy all of the fft files and apply scalings masks etc\n\n\n    ;; Step 2 (this function):  average all the bands to create binned x-spectra\n    ;; this assumes sims are created with two bundles\n    '''\n    if ram_limit is None:\n        ram_limit = 32 * 2**30 # default limit is 32 GB\n\n\n    # Simplifying assumption axb == (a^c b + b^c a)\n    # assume do *not* do x-spectra between same observation\n    nsets   = setdef1.shape[1]\n    setsize = setdef1.shape[0]\n    nspectra=np.int((nsets*(nsets+1))/2 + 0.001)\n    print(nsets,setsize,nspectra)\n    \n    if auto is False:\n        assert setdef2 is not None\n    \n    nrealizations=setsize\n\n    nbands = banddef.shape[0]-1\n\n    nshts  = np.int(np.max([setdef1,setdef2])+1.001)\n    npersht = healpy.sphtfunc.Alm.getsize(lmax)\n    #pdb.set_trace()\n    allspectra_out = np.zeros([nbands,nspectra,nrealizations],dtype=np.float32)\n    nmodes_out     = np.zeros(nbands, dtype = np.int32)\n\n    tmpresult = np.zeros([setsize,setsize],dtype=np.float64)\n\n    # number of bytes in a Dcomplex: 16\n    # number of arrays we need to make to do this efficiently: 6 or less\n    # number of pixels in an fft: winsize^2\n    ram_required=16*6*lmax**2\n    max_nmodes=ram_limit/nshts/32 #64 b complex \n\n\n    assert(banddef[0] == 0 and banddef[-1] <= lmax)\n    #assumes banddef[0]=0\n    #so first bin goes 1 - banddef[1]\n    # second bin goes banddef[1]+1 - banddef[2], etc\n    band_start_idx = get_first_index_ell(banddef+1)\n\n    #code=reverse_linefeed_code()\n\n    i=0 # i is the last bin to have finished. initially 0\n    while (i < nbands):\n        istop = np.where((band_start_idx - band_start_idx[i]) < max_nmodes)[0][-1] # get out of tuple, then take last elem of array\n\n        if istop <= i:\n            print('ram hit:',max_modes, band_start_idx[i],band_start_idx[i+1])\n            raise Exception(\"Insufficient ram for processing even a single bin\")\n\n        print('take_all_cross_spectra: loading bands {} {}'.format(i,istop-1))\n        # technical: delete the last iteration of banddata_big first\n        banddata_big=0\n        # get data for as many bins as will fit in our ramlimit\n\n        banddata_big=load_cross_spectra_data_from_disk(processedshtfile, \n                                                       nshts, npersht,   \n                                                       band_start_idx[i],\n                                                       band_start_idx[istop]-1 )\n        #process this data\n        for iprime in range(i, istop):\n            printinplace('processing band {}    '.format(iprime))\n                \n            nmodes=(band_start_idx[iprime+1]-band_start_idx[iprime])\n            nmodes_out[iprime]=nmodes\n            aidx=band_start_idx[iprime]-band_start_idx[i]\n            banddata=banddata_big[:,aidx:(aidx+nmodes-1)] # first index SHT; second index alm\n\n\n            spectrum_idx=0\n            for j in range(nsets):\n                for k in range(j, nsets):\n                    if not auto:\n\n                        #hypothetically, have 150a, 150b, 220a,220b \n                        #want to end with:\n                        # 150a * 220b + 150b * 220a\n                        #iew 1j* 2k + 2j* 1k\n                        tmpresult  =np.sum(np.real(banddata[setdef1[:, j],:]*np.conj(banddata[setdef2[:, k],:])), 1,dtype=np.float64)\n                        tmpresult +=np.sum(np.real(banddata[setdef2[:, j],:]*np.conj(banddata[setdef1[:, k],:])), 1,dtype=np.float64)\n                        tmpresult /= (2*nmodes)\n                        \n                        allspectra_out[iprime, spectrum_idx, :]=tmpresult.astype(np.float32)\n\n                    else:\n                        #j/k are freqs\n                        #first index is nrealizations\n                        tmpresult=np.sum(np.real(banddata[setdef1[:, j],:]*np.conj(banddata[setdef1[:, k],:])), 1,dtype=np.float64) / (nmodes) # had been in flatsky: *reso^2*winsize^2)\n                        #tmpresult is nrealizations long\n                        allspectra_out[iprime, spectrum_idx, :]=tmpresult.astype(np.float32)\n                    spectrum_idx+=1\n                    #           pdb.set_trace()\n        i=istop\n    return(allspectra_out, nmodes_out)\n\n\n\ndef process_all_cross_spectra(allspectra, nbands, nsets,setsize, \n                              auto=False,\n                              skipcov=False ) -> 'Returns mean and covarariance estimates':\n\n    print(\"Correlating Cross Spectra\")\n    nspectra = int( (nsets * (nsets+1))/2 + 0.001)\n\n\n\n\n    if auto:\n        nrealizations = setsize\n    else:\n        nrealizations=int( (setsize*(setsize-1))/2 + 0.001)\n\n    allspectra = np.reshape(allspectra, [nbands*nspectra, nrealizations])\n    #cov  = np.zeros([nbands*nspectra, nbands*nspectra],dtype=np.float64)\n\n    spectrum = np.sum(allspectra,-1,dtype=np.float64)/nrealizations\n\n    spectrum = np.reshape(spectrum,[nbands,nspectra])\n    if skipcov:\n        return spectrum,None,None,None\n    # [nbands*nspectra, nrealizations])\n    spectrum_2d = np.tile(np.reshape(spectrum,[nbands*nspectra,1]), [1,nrealizations])\n\n    cov1 = np.matmul((allspectra-spectrum_2d) , (allspectra-spectrum_2d).T)\n    cov1/= (nrealizations*(nrealizations-1))\n\n    cov2 = None\n    if not auto:\n        realization_to_complement=np.zeros([nrealizations, setsize],dtype=np.float64)\n\n        for i in range(setsize):\n            realization_idx = 0\n            for j in range(setsize):\n                for k in range(j+1,setsize):\n                    if (i == j) or (i == k):\n                        realization_to_complement[realization_idx, i]=1./(setsize-1)\n                    realization_idx += 1\n\n        allcomplementspectra=np.matmul(allspectra,realization_to_complement)\n        #nbands*nspectra, setsize)\n        spectrum_2d=np.tile(np.reshape(spectrum,[nbands*nspectra,1]), [1,setsize])\n\n        cov2=np.matmul( (allcomplementspectra-spectrum_2d), (allcomplementspectra-spectrum_2d).T )\n        cov2/=(setsize**2 / 2)\n        cov=2*cov2-cov1\n\n    else:\n        cov=cov1*(nrealizations) \n\n    return spectrum,cov,cov1,cov2\n\n'''\nCreate a class instance to simplify storing all the arguments along with the output\n'''\nclass unbiased_multispec:\n    def __init__(self,\n                 # Maps/SHT flags ################################################\n                 mapfile, #required -array of map filenames, g3 format\n                 window, # required -- mask to apply for SHT\n                 banddef, # required. [0,lmax_bin1, lmax_bin2, ...]\n                 nside, #required. eg 8192\n                 lmax=None, #optional, but should be set. Defaults to 2*nside      \n                 cmbweighting=True, # True ==> return Dl. False ==> Return Cl\n                 kmask = None, #If not none, must be the right size for the Alms. A numpy array/vector\n                 setdef=None, # optional -- will take from mapfile array dimensions if not provided\n                 setdef2 = None, #optional -- if provided will assume doing sim cross-spectra\n                 jackknife = False, #If true, will difference SHTs to do null spectrum\n                 auto=False, #If true will do autospectra instead of cross-spectra\n                 apply_windowfactor = True, #if true, calculate and apply normalization correction for partial sky mask. \n                 map_key = 'T', #where to fetch maps from\n                 skipcov=False, #don't calculate covariances\n                 # Run time processing flags ################################################\n                 ramlimit=64 * 2**30, # optional -- set to change default RAM limit from 64gb\n                 resume=True, #optional -- will use existing files if true    \n                 basedir=None, # strongly suggested. defaults to current directory and can use a lot of disk space\n                 persistdir=None, # optional - can be unset. will create a temp directory within basedir\n                 remove_temporary_files= False, # optional. Defaults to off (user has to do cleanup, but can restart runs later)\n                 verbose = False ): #extra print statements\n                #maybe sometime I'll put in more input file arguments...                  \n        '''\n                 # Outputs ################################################\n                 allspectra -- array of all cross-spectra (binned according to banddef)\n                 cov -- array estimated covariance\n                 est1_cov -- array estimated covariance from estimator 1\n                 est2_cov -- array estimated covariance from estimator 2\n                 nmodes -- array of number of alms per bandpower bin (form banddef)\n                 windowfactor -- value used to normalize spectrum for apodization window. May be 1 (ie not corrected)\n        '''\n        self.mapfile = mapfile\n        self.window = window\n        self.banddef = banddef\n        self.nside = nside\n        self.lmax = lmax\n        if self.lmax is None: \n            self.lmax = 2*self.nside\n        self.cmbweighting = cmbweighting\n        self.kmask = kmask\n        self.setdef = setdef\n        self.jackknife = jackknife\n        self.auto = auto\n        self.apply_windowfactor = apply_windowfactor\n        self.ramlimit = ramlimit\n        self.resume = resume\n        self.basedir = basedir\n        self.persistdir = persistdir\n        self.remove_temporary_files = remove_temporary_files\n        self.verbose = verbose\n        self.allspectra = None\n        self.spectrum = None\n        self.cov = None\n        self.est1_cov = None\n        self.est2_cov = None\n        self.nmodes = None\n        self.windowfactor = 1.0\n                \n                \n        #################\n        # figure out scratch directories\n        #################\n        try:\n            if not os.path.isdir(self.basedir):\n                raise TypeError  # to be caught below\n        except TypeError:            \n            self.basedir = os.getcwd()\n        try:     \n            if os.path.exists(self.persistdir) and not os.path.isdir(self.persistdir):\n                print(\"WARNING -- Requested scratch exists, but is not a directory: {}\".format(self.persistdir))\n                raise TypeError\n        except TypeError:\n            self.persistdir = name_tempdir(self.basedir)\n            print(\"WARNING -- using {} for scratch\".format(self.persistdir))\n            if not os.path.isdir(self.persistdir):\n                os.makedirs(self.persistdir)\n\n        #maybe at some point, we'll use status. right now nothing is done. Resume will only affect the full step level - no partial steps yet.\n        status_file = self.persistdir + '/status.pkl'\n        \n        processed_sht_file = self.persistdir + '/shts_processed.bin'\n        if not self.resume:\n            try: \n                os.remove(processed_sht_file)\n            except FileNotFoundError:\n                pass\n        \n        \n        #################\n        # Figure out set def based on structure of map file names, if not provided\n        #################\n        if self.setdef is None:\n            #may need to change this -- unsure if it's right or transpose\n            #may also need to make it 2d\n            #remove warning printout when checked\n            self.setdef = self.mapfile.shape\n            print('Warning - check set def: inferred {}'.format(self.setdef))\n        \n        #get SHTs done\n        sht_size = os.path.getsize(processed_sht_file)\n        desired_size = healpy.sphtfunc.Alm.getsize(lmax) * np.zeros(1,dtype=AlmType).nbytes\n        if (sht_size < desired_size):  #this will be false if resume==False since deleted file above.\n            print(\"Dont expect to be here\")\n            pdb.set_trace()\n            take_and_reformat_shts(self.fuile, processed_sht_file,\n                   self.nside,self.lmax,\n                   cmbweighting = self.cmbweighting, \n                   mask  = self.window,\n                   kmask = self.kmask,\n                   ell_reordering=None,\n                   no_reorder=False,\n                   ram_limit = self.ramlimit, \n                   map_key=map_key\n                  )\n        \n        use_setdef  = setdef\n        use_shtfile = processed_sht_file\n        if self.jackknife:\n            jackknife_sht_file = self.persistdir + '/null_shts_processed.bin'\n            use_setdef = generate_jackknife_shts( processed_sht_file, jackknife_sht_file,  self.lmax, self.setdef)\n            use_shtfile = jackknife_sht_file\n\n        self.use_setdef = use_setdef\n        \n        #figure out cross-spectra (or autospectra)\n        if setdef2 is None:\n            allspectra, nmodes= take_all_cross_spectra( use_shtfile, self.lmax,\n                                                        self.use_setdef, self.banddef,  ram_limit=self.ramlimit, auto = self.auto) #-> 'Returns set of all x-spectra, binned':\n        else:\n            allspectra, nmodes= take_all_sim_cross_spectra( use_shtfile, self.lmax,\n                                                        self.use_setdef,self.banddef, setdef2=setdef2, ram_limit=self.ramlimit, auto = self.auto) #-> 'Returns set of all x-spectra, binned':\n                        \n        self.allspectra = allspectra\n        self.nmodes = nmodes\n        \n        \n        #bring it all together\n        nbands = banddef.shape[0]-1\n        nsets   = use_setdef.shape[1]\n        setsize = use_setdef.shape[0]\n\n        process_auto = self.auto or (setdef2 is not None) # only get 1 per set for the sim crosses too\n        spectrum,cov,cov1,cov2 = process_all_cross_spectra(self.allspectra, nbands, nsets,setsize, \n                                                            auto=process_auto)\n        self.spectrum = spectrum\n        self.cov      = cov\n        self.est1_cov = cov1\n        self.est2_cov = cov2\n                                 \n", "meta": {"hexsha": "fe44d64210e045f9ae151fcb78cf8530e99d8332", "size": 31455, "ext": "py", "lang": "Python", "max_stars_repo_path": "unbiased_multispec.py", "max_stars_repo_name": "clreichardt/spectra_port", "max_stars_repo_head_hexsha": "75d27d7f24a57b148616bd09597e78b4766378fd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unbiased_multispec.py", "max_issues_repo_name": "clreichardt/spectra_port", "max_issues_repo_head_hexsha": "75d27d7f24a57b148616bd09597e78b4766378fd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unbiased_multispec.py", "max_forks_repo_name": "clreichardt/spectra_port", "max_forks_repo_head_hexsha": "75d27d7f24a57b148616bd09597e78b4766378fd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-13T07:55:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T07:55:48.000Z", "avg_line_length": 40.5347938144, "max_line_length": 206, "alphanum_fraction": 0.573962804, "include": true, "reason": "import numpy", "num_tokens": 8149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.16560404155053823}}
{"text": "\"\"\"\nThe ExpErrorgenOp class and supporting functionality.\n\"\"\"\n#***************************************************************************************************\n# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).\n# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights\n# in this software.\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n# in compliance with the License.  You may obtain a copy of the License at\n# http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory.\n#***************************************************************************************************\n\nimport warnings as _warnings\n\nimport numpy as _np\nimport scipy.linalg as _spl\nimport scipy.sparse as _sps\nimport scipy.sparse.linalg as _spsl\n\nfrom pygsti.modelmembers.operations.linearop import LinearOperator as _LinearOperator\nfrom pygsti.modelmembers.operations.lindbladerrorgen import LindbladParameterization as _LindbladParameterization\nfrom pygsti.modelmembers import modelmember as _modelmember, term as _term\nfrom pygsti.modelmembers.errorgencontainer import ErrorGeneratorContainer as _ErrorGeneratorContainer\nfrom pygsti.baseobjs.polynomial import Polynomial as _Polynomial\nfrom pygsti.tools import matrixtools as _mt\n\nIMAG_TOL = 1e-7  # tolerance for imaginary part being considered zero\nMAX_EXPONENT = _np.log(_np.finfo('d').max) - 10.0  # so that exp(.) doesn't overflow\nTODENSE_TRUNCATE = 1e-11\n\n\nclass ExpErrorgenOp(_LinearOperator, _ErrorGeneratorContainer):\n    \"\"\"\n    An operation parameterized by the coefficients of an exponentiated sum of Lindblad-like terms.\n    TODO: update docstring!\n\n    The exponentiated terms give the operation's action.\n\n    Parameters\n    ----------\n    errorgen : LinearOperator\n        The error generator for this operator.  That is, the `L` if this\n        operator is `exp(L)`.\n    \"\"\"\n\n    def __init__(self, errorgen):\n        # Extract superop dimension from 'errorgen'\n        state_space = errorgen.state_space\n        self.errorgen = errorgen  # don't copy (allow object reuse)\n\n        evotype = self.errorgen._evotype\n\n        #Create representation object\n        rep_type_order = ('dense', 'experrgen') if evotype.prefer_dense_reps else ('experrgen', 'dense')\n        rep = None\n        for rep_type in rep_type_order:\n            try:\n                if rep_type == 'experrgen':\n                    # \"sparse mode\" => don't ever compute matrix-exponential explicitly\n                    rep = evotype.create_experrorgen_rep(self.errorgen._rep)\n                elif rep_type == 'dense':\n                    rep = evotype.create_dense_superop_rep(None, state_space)\n\n                    # Cache values - for later work with dense rep\n                    self.exp_err_gen = None   # used for dense_rep=True mode to cache qty needed in deriv_wrt_params\n                    self.base_deriv = None\n                    self.base_hessian = None\n                else:\n                    assert(False), \"Logic error!\"\n\n                self._rep_type = rep_type\n                break\n\n            except AttributeError:\n                pass  # just go to the next rep_type\n\n        if rep is None:\n            raise ValueError(\"Unable to construct representation with evotype: %s\" % str(evotype))\n\n        # Caches in case terms are used\n        self.terms = {}\n        self.exp_terms_cache = {}  # used for repeated calls to the exponentiate_terms function\n        self.local_term_poly_coeffs = {}\n\n        _LinearOperator.__init__(self, rep, evotype)\n        _ErrorGeneratorContainer.__init__(self, self.errorgen)\n        self.init_gpindices()  # initialize our gpindices based on sub-members\n        self._update_rep()  # updates self._rep\n        #Done with __init__(...)\n\n    #Note: no to_memoized_dict needed, as ModelMember version does all we need.\n\n    @classmethod\n    def _from_memoized_dict(cls, mm_dict, serial_memo):\n        errorgen = serial_memo[mm_dict['submembers'][0]]\n        return cls(errorgen)\n\n    def submembers(self):\n        \"\"\"\n        Get the ModelMember-derived objects contained in this one.\n\n        Returns\n        -------\n        list\n        \"\"\"\n        return [self.errorgen]\n\n    def _update_rep(self, close=False):\n        \"\"\"\n        Updates self._rep as needed after parameters have changed.\n        \"\"\"\n        if self._rep_type == 'dense':\n            # compute matrix-exponential explicitly\n            self.exp_err_gen = _spl.expm(self.errorgen.to_dense(on_space='HilbertSchmidt'))  # used in deriv_wrt_params\n\n            dense = self.exp_err_gen\n            self._rep.base.flags.writeable = True\n            self._rep.base[:, :] = dense\n            self._rep.base.flags.writeable = False\n            self.base_deriv = None\n            self.base_hessian = None\n        else:  # if not close:\n            self._rep.errgenrep_has_changed(self.errorgen.onenorm_upperbound())\n\n            #CHECK that sparsemx action is correct (DEBUG CHECK)\n            #from pygsti.modelmembers.states import StaticState\n            #Mdense = _spl.expm(self.errorgen.to_dense())\n            #if Mdense.shape == (4,4):\n            #    for i in range(4):\n            #        v = _np.zeros(4); v[i] = 1.0\n            #\n            #        staterep = StaticState(v)._rep\n            #        check_acton = self._rep.acton(staterep).data\n            #\n            #        #check_sparse_scipy = _spsl.expm_multiply(self.errorgen.to_sparse(), v.copy())\n            #        prep = _mt.expm_multiply_prep(self.errorgen.to_sparse())\n            #        check_sparse = _mt.expm_multiply_fast(prep, v)\n            #        check_dense = _np.dot(Mdense, v)\n            #\n            #        diff = _np.linalg.norm(check_dense - check_acton)\n            #        #diff2 = _np.linalg.norm(check_sparse_scipy - check_sparse)\n            #        if diff > 1e-6: # or diff2 > 1e-3:\n            #            print(\"PROBLEM (%d)!!\" % i, \" Expop diff = \", diff)\n\n    def set_gpindices(self, gpindices, parent, memo=None):\n        \"\"\"\n        Set the parent and indices into the parent's parameter vector that are used by this ModelMember object.\n\n        Parameters\n        ----------\n        gpindices : slice or integer ndarray\n            The indices of this objects parameters in its parent's array.\n\n        parent : Model or ModelMember\n            The parent whose parameter array gpindices references.\n\n        memo : dict, optional\n            A memo dict used to avoid circular references.\n\n        Returns\n        -------\n        None\n        \"\"\"\n        _modelmember.ModelMember.set_gpindices(self, gpindices, parent, memo)\n        self.terms = {}  # clear terms cache since param indices have changed now\n        self.exp_terms_cache = {}\n        self.local_term_poly_coeffs = {}\n\n    def to_dense(self, on_space='minimal'):\n        \"\"\"\n        Return this operation as a dense matrix.\n\n        Returns\n        -------\n        numpy.ndarray\n        \"\"\"\n        if self._rep_type == 'dense':\n            # Then self._rep contains a dense version already\n            return self._rep.base  # copy() unnecessary since we set to readonly\n\n        else:\n            # Construct a dense version from scratch (more time consuming)\n            return _spl.expm(self.errorgen.to_dense(on_space))\n\n    #FUTURE: maybe remove this function altogether, as it really shouldn't be called\n    def to_sparse(self, on_space='minimal'):\n        \"\"\"\n        Return the operation as a sparse matrix.\n\n        Parameters\n        ----------\n        on_space : {'minimal', 'Hilbert', 'HilbertSchmidt'}\n            The space that the returned dense operation acts upon.  For unitary matrices and bra/ket vectors,\n            use `'Hilbert'`.  For superoperator matrices and super-bra/super-ket vectors use `'HilbertSchmidt'`.\n            `'minimal'` means that `'Hilbert'` is used if possible given this operator's evolution type, and\n            otherwise `'HilbertSchmidt'` is used.\n\n        Returns\n        -------\n        scipy.sparse.csr_matrix\n        \"\"\"\n        if self._rep_type == 'dense':\n            return _sps.csr_matrix(self.to_dense(on_space))\n        else:\n            return _spsl.expm(self.errorgen.to_sparse(on_space).tocsc()).tocsr()\n\n    def deriv_wrt_params(self, wrt_filter=None):\n        \"\"\"\n        The element-wise derivative this operation.\n\n        Construct a matrix whose columns are the vectorized\n        derivatives of the flattened operation matrix with respect to a\n        single operation parameter.  Thus, each column is of length\n        op_dim^2 and there is one column per operation parameter.\n\n        Parameters\n        ----------\n        wrt_filter : list or numpy.ndarray\n            List of parameter indices to take derivative with respect to.\n            (None means to use all the this operation's parameters.)\n\n        Returns\n        -------\n        numpy array\n            Array of derivatives, shape == (dimension^2, num_params)\n        \"\"\"\n        if not self._rep_type == 'dense':\n            #raise NotImplementedError(\"deriv_wrt_params(...) can only be used when a dense representation is used!\")\n            #_warnings.warn(\"Using finite differencing to compute ExpErrogenOp derivative!\")\n            return super(ExpErrorgenOp, self).deriv_wrt_params(wrt_filter)\n\n        if self.base_deriv is None:\n            d2 = self.dim\n\n            #Deriv wrt hamiltonian params\n            derrgen = self.errorgen.deriv_wrt_params(None)  # apply filter below; cache *full* deriv\n            derrgen.shape = (d2, d2, -1)  # separate 1st d2**2 dim to (d2,d2)\n            dexpL = _d_exp_x(self.errorgen.to_dense(on_space='minimal'), derrgen, self.exp_err_gen)\n            derivMx = dexpL.reshape(d2**2, self.num_params)  # [iFlattenedOp,iParam]\n\n            assert(_np.linalg.norm(_np.imag(derivMx)) < IMAG_TOL), \\\n                (\"Deriv matrix has imaginary part = %s.  This can result from \"\n                 \"evaluating a Model derivative at a 'bad' point where the \"\n                 \"error generator is large.  This often occurs when GST's \"\n                 \"starting Model has *no* stochastic error and all such \"\n                 \"parameters affect error rates at 2nd order.  Try \"\n                 \"depolarizing the seed Model.\") % str(_np.linalg.norm(_np.imag(derivMx)))\n            # if this fails, uncomment around \"DB COMMUTANT NORM\" for further debugging.\n            derivMx = _np.real(derivMx)\n            self.base_deriv = derivMx\n\n            #check_deriv_wrt_params(self, derivMx, eps=1e-7)\n            #fd_deriv = finite_difference_deriv_wrt_params(self, wrt_filter, eps=1e-7)\n            #derivMx = fd_deriv\n\n        if wrt_filter is None:\n            return self.base_deriv.view()\n            #view because later setting of .shape by caller can mess with self.base_deriv!\n        else:\n            return _np.take(self.base_deriv, wrt_filter, axis=1)\n\n    def has_nonzero_hessian(self):\n        \"\"\"\n        Whether this operation has a non-zero Hessian with respect to its parameters.\n\n        (i.e. whether it only depends linearly on its parameters or not)\n\n        Returns\n        -------\n        bool\n        \"\"\"\n        return True\n\n    def hessian_wrt_params(self, wrt_filter1=None, wrt_filter2=None):\n        \"\"\"\n        Construct the Hessian of this operation with respect to its parameters.\n\n        This function returns a tensor whose first axis corresponds to the\n        flattened operation matrix and whose 2nd and 3rd axes correspond to the\n        parameters that are differentiated with respect to.\n\n        Parameters\n        ----------\n        wrt_filter1 : list or numpy.ndarray\n            List of parameter indices to take 1st derivatives with respect to.\n            (None means to use all the this operation's parameters.)\n\n        wrt_filter2 : list or numpy.ndarray\n            List of parameter indices to take 2nd derivatives with respect to.\n            (None means to use all the this operation's parameters.)\n\n        Returns\n        -------\n        numpy array\n            Hessian with shape (dimension^2, num_params1, num_params2)\n        \"\"\"\n        if not self._rep_type == 'dense':\n            #raise NotImplementedError(\"hessian_wrt_params is only implemented for *dense-rep* LindbladOps\")\n            #_warnings.warn(\"Using finite differencing to compute ExpErrogenOp Hessian!\")\n            return super(ExpErrorgenOp, self).hessian_wrt_params(wrt_filter1, wrt_filter2)\n\n        if self.base_hessian is None:\n            d2 = self.dim\n            nP = self.num_params\n            hessianMx = _np.zeros((d2**2, nP, nP), 'd')\n\n            #Deriv wrt other params\n            dEdp = self.errorgen.deriv_wrt_params(None)  # filter later, cache *full*\n            d2Edp2 = self.errorgen.hessian_wrt_params(None, None)  # hessian\n            dEdp.shape = (d2, d2, nP)  # separate 1st d2**2 dim to (d2,d2)\n            d2Edp2.shape = (d2, d2, nP, nP)  # ditto\n\n            series, series2 = _d2_exp_series(self.errorgen.to_dense(on_space='minimal'), dEdp, d2Edp2)\n            term1 = series2\n            term2 = _np.einsum(\"ija,jkq->ikaq\", series, series)\n            d2expL = _np.einsum(\"ikaq,kj->ijaq\", term1 + term2,\n                                self.exp_err_gen)\n            hessianMx = d2expL.reshape((d2**2, nP, nP))\n\n            #hessian has been made so index as [iFlattenedOp,iDeriv1,iDeriv2]\n            assert(_np.linalg.norm(_np.imag(hessianMx)) < IMAG_TOL)\n            hessianMx = _np.real(hessianMx)  # d2O block of hessian\n\n            self.base_hessian = hessianMx\n\n            #TODO: check hessian with finite difference here?\n\n        if wrt_filter1 is None:\n            if wrt_filter2 is None:\n                return self.base_hessian.view()\n                #view because later setting of .shape by caller can mess with self.base_hessian!\n            else:\n                return _np.take(self.base_hessian, wrt_filter2, axis=2)\n        else:\n            if wrt_filter2 is None:\n                return _np.take(self.base_hessian, wrt_filter1, axis=1)\n            else:\n                return _np.take(_np.take(self.base_hessian, wrt_filter1, axis=1),\n                                wrt_filter2, axis=2)\n\n    @property\n    def parameter_labels(self):\n        \"\"\"\n        An array of labels (usually strings) describing this model member's parameters.\n        \"\"\"\n        return self.errorgen.parameter_labels\n\n    @property\n    def num_params(self):\n        \"\"\"\n        Get the number of independent parameters which specify this operation.\n\n        Returns\n        -------\n        int\n            the number of independent parameters.\n        \"\"\"\n        return self.errorgen.num_params\n\n    def to_vector(self):\n        \"\"\"\n        Extract a vector of the underlying operation parameters from this operation.\n\n        Returns\n        -------\n        numpy array\n            a 1D numpy array with length == num_params().\n        \"\"\"\n        return self.errorgen.to_vector()\n\n    def from_vector(self, v, close=False, dirty_value=True):\n        \"\"\"\n        Initialize the operation using a vector of parameters.\n\n        Parameters\n        ----------\n        v : numpy array\n            The 1D vector of operation parameters.  Length\n            must == num_params()\n\n        close : bool, optional\n            Whether `v` is close to this operation's current\n            set of parameters.  Under some circumstances, when this\n            is true this call can be completed more quickly.\n\n        dirty_value : bool, optional\n            The value to set this object's \"dirty flag\" to before exiting this\n            call.  This is passed as an argument so it can be updated *recursively*.\n            Leave this set to `True` unless you know what you're doing.\n\n        Returns\n        -------\n        None\n        \"\"\"\n        self.errorgen.from_vector(v, close, dirty_value)\n        self._update_rep(close)\n        self.dirty = dirty_value\n\n    def taylor_order_terms(self, order, max_polynomial_vars=100, return_coeff_polys=False):\n        \"\"\"\n        Get the `order`-th order Taylor-expansion terms of this operation.\n\n        This function either constructs or returns a cached list of the terms at\n        the given order.  Each term is \"rank-1\", meaning that its action on a\n        density matrix `rho` can be written:\n\n        `rho -> A rho B`\n\n        The coefficients of these terms are typically polynomials of the operation's\n        parameters, where the polynomial's variable indices index the *global*\n        parameters of the operation's parent (usually a :class:`Model`), not the\n        operation's local parameter array (i.e. that returned from `to_vector`).\n\n        Parameters\n        ----------\n        order : int\n            Which order terms (in a Taylor expansion of this :class:`LindbladOp`)\n            to retrieve.\n\n        max_polynomial_vars : int, optional\n            maximum number of variables the created polynomials can have.\n\n        return_coeff_polys : bool\n            Whether a parallel list of locally-indexed (using variable indices\n            corresponding to *this* object's parameters rather than its parent's)\n            polynomial coefficients should be returned as well.\n\n        Returns\n        -------\n        terms : list\n            A list of :class:`RankOneTerm` objects.\n        coefficients : list\n            Only present when `return_coeff_polys == True`.\n            A list of *compact* polynomial objects, meaning that each element\n            is a `(vtape,ctape)` 2-tuple formed by concatenating together the\n            output of :method:`Polynomial.compact`.\n        \"\"\"\n        if order not in self.terms:\n            self._compute_taylor_order_terms(order, max_polynomial_vars)\n\n        if return_coeff_polys:\n            return self.terms[order], self.local_term_poly_coeffs[order]\n        else:\n            return self.terms[order]\n\n    def _compute_taylor_order_terms(self, order, max_polynomial_vars):  # separated for profiling\n\n        mapvec = _np.ascontiguousarray(_np.zeros(max_polynomial_vars, _np.int64))\n        for ii, i in enumerate(self.gpindices_as_array()):\n            mapvec[ii] = i\n\n        def _compose_poly_indices(terms):\n            for term in terms:\n                #term.map_indices_inplace(lambda x: tuple(_modelmember._compose_gpindices(\n                #    self.gpindices, _np.array(x, _np.int64))))\n                term.mapvec_indices_inplace(mapvec)\n            return terms\n\n        assert(self.gpindices is not None), \"LindbladOp must be added to a Model before use!\"\n        mpv = max_polynomial_vars\n\n        #Note: for now, *all* of an error generator's terms are considered 0-th order,\n        # so the below call to taylor_order_terms just gets all of them.  In the FUTURE\n        # we might want to allow a distinction among the error generator terms, in which\n        # case this term-exponentiation step will need to become more complicated...\n        postTerm = _term.RankOnePolynomialOpTerm.create_from(_Polynomial({(): 1.0}, mpv),\n                                                             None, None, self._evotype, self.state_space)  # identity\n        loc_terms = _term.exponentiate_terms(self.errorgen.taylor_order_terms(0, max_polynomial_vars),\n                                             order, postTerm, self.exp_terms_cache)\n        #OLD: loc_terms = [ t.collapse() for t in loc_terms ] # collapse terms for speed\n\n        poly_coeffs = [t.coeff for t in loc_terms]\n        tapes = [poly.compact(complex_coeff_tape=True) for poly in poly_coeffs]\n        if len(tapes) > 0:\n            vtape = _np.concatenate([t[0] for t in tapes])\n            ctape = _np.concatenate([t[1] for t in tapes])\n        else:\n            vtape = _np.empty(0, _np.int64)\n            ctape = _np.empty(0, complex)\n        coeffs_as_compact_polys = (vtape, ctape)\n        self.local_term_poly_coeffs[order] = coeffs_as_compact_polys\n\n        # only cache terms with *global* indices to avoid confusion...\n        self.terms[order] = _compose_poly_indices(loc_terms)\n\n    def taylor_order_terms_above_mag(self, order, max_polynomial_vars, min_term_mag):\n        \"\"\"\n        Get the `order`-th order Taylor-expansion terms of this operation that have magnitude above `min_term_mag`.\n\n        This function constructs the terms at the given order which have a magnitude (given by\n        the absolute value of their coefficient) that is greater than or equal to `min_term_mag`.\n        It calls :method:`taylor_order_terms` internally, so that all the terms at order `order`\n        are typically cached for future calls.\n\n        The coefficients of these terms are typically polynomials of the operation's\n        parameters, where the polynomial's variable indices index the *global*\n        parameters of the operation's parent (usually a :class:`Model`), not the\n        operation's local parameter array (i.e. that returned from `to_vector`).\n\n        Parameters\n        ----------\n        order : int\n            The order of terms to get (and filter).\n\n        max_polynomial_vars : int, optional\n            maximum number of variables the created polynomials can have.\n\n        min_term_mag : float\n            the minimum term magnitude.\n\n        Returns\n        -------\n        list\n            A list of :class:`Rank1Term` objects.\n        \"\"\"\n        mapvec = _np.ascontiguousarray(_np.zeros(max_polynomial_vars, _np.int64))\n        for ii, i in enumerate(self.gpindices_as_array()):\n            mapvec[ii] = i\n\n        assert(self.gpindices is not None), \"LindbladOp must be added to a Model before use!\"\n        mpv = max_polynomial_vars\n\n        postTerm = _term.RankOnePolynomialOpTerm.create_from(_Polynomial({(): 1.0}, mpv), None, None,\n                                                             self._evotype, self.state_space)  # identity term\n        postTerm = postTerm.copy_with_magnitude(1.0)\n        #Note: for now, *all* of an error generator's terms are considered 0-th order,\n        # so the below call to taylor_order_terms just gets all of them.  In the FUTURE\n        # we might want to allow a distinction among the error generator terms, in which\n        # case this term-exponentiation step will need to become more complicated...\n        errgen_terms = self.errorgen.taylor_order_terms(0, max_polynomial_vars)\n\n        #DEBUG CHECK MAGS OF ERRGEN COEFFS\n        #poly_coeffs = [t.coeff for t in errgen_terms]\n        #tapes = [poly.compact(complex_coeff_tape=True) for poly in poly_coeffs]\n        #if len(tapes) > 0:\n        #    vtape = _np.concatenate([t[0] for t in tapes])\n        #    ctape = _np.concatenate([t[1] for t in tapes])\n        #else:\n        #    vtape = _np.empty(0, _np.int64)\n        #    ctape = _np.empty(0, complex)\n        #v = self.to_vector()\n        #errgen_coeffs = _bulk_eval_compact_polynomials_complex(\n        #    vtape, ctape, v, (len(errgen_terms),))  # an array of coeffs\n        #for coeff, t in zip(errgen_coeffs, errgen_terms):\n        #    coeff2 = t.coeff.evaluate(v)\n        #    if not _np.isclose(coeff,coeff2):\n        #        assert(False), \"STOP\"\n        #    t.set_magnitude(abs(coeff))\n\n        #evaluate errgen_terms' coefficients using their local vector of parameters\n        # (which happends to be the same as our paramvec in this case)\n        egvec = self.errorgen.to_vector()   # we need errorgen's vector (usually not in rep) to perform evaluation\n        errgen_terms = [egt.copy_with_magnitude(abs(egt.coeff.evaluate(egvec))) for egt in errgen_terms]\n\n        terms = []\n        for term in _term.exponentiate_terms_above_mag(errgen_terms, order,\n                                                       postTerm, min_term_mag=min_term_mag):\n            #poly_coeff = term.coeff\n            #compact_poly_coeff = poly_coeff.compact(complex_coeff_tape=True)\n            term.mapvec_indices_inplace(mapvec)  # local -> global indices\n\n            # DEBUG CHECK - to ensure term magnitudes are being set correctly (i.e. are in sync with evaluated coeffs)\n            # t = term\n            # vt, ct = t._rep.coeff.compact_complex()\n            # coeff_array = _bulk_eval_compact_polynomials_complex(vt, ct, self.parent.to_vector(), (1,))\n            # if not _np.isclose(abs(coeff_array[0]), t._rep.magnitude):  # DEBUG!!!\n            #     print(coeff_array[0], \"vs.\", t._rep.magnitude)\n            #     import bpdb; bpdb.set_trace()\n            #     c1 = _Polynomial.from_rep(t._rep.coeff)\n\n            terms.append(term)\n        return terms\n\n    @property\n    def total_term_magnitude(self):\n        \"\"\"\n        Get the total (sum) of the magnitudes of all this operator's terms.\n\n        The magnitude of a term is the absolute value of its coefficient, so\n        this function returns the number you'd get from summing up the\n        absolute-coefficients of all the Taylor terms (at all orders!) you\n        get from expanding this operator in a Taylor series.\n\n        Returns\n        -------\n        float\n        \"\"\"\n        # return exp( mag of errorgen ) = exp( sum of absvals of errgen term coeffs )\n        # (unitary postfactor has weight == 1.0 so doesn't enter)\n        return _np.exp(min(self.errorgen.total_term_magnitude, MAX_EXPONENT))\n        #return _np.exp(self.errorgen.total_term_magnitude)  # overflows sometimes\n\n    @property\n    def total_term_magnitude_deriv(self):\n        \"\"\"\n        The derivative of the sum of *all* this operator's terms.\n\n        Computes the derivative of the total (sum) of the magnitudes of all this\n        operator's terms with respect to the operators (local) parameters.\n\n        Returns\n        -------\n        numpy array\n            An array of length self.num_params\n        \"\"\"\n        return _np.exp(self.errorgen.total_term_magnitude) * self.errorgen.total_term_magnitude_deriv\n\n    def set_dense(self, m):\n        \"\"\"\n        Set the dense-matrix value of this operation.\n\n        Attempts to modify operation parameters so that the specified raw\n        operation matrix becomes mx.  Will raise ValueError if this operation\n        is not possible.\n\n        Parameters\n        ----------\n        m : array_like or LinearOperator\n            An array of shape (dim, dim) or LinearOperator representing the operation action.\n\n        Returns\n        -------\n        None\n        \"\"\"\n        mx = _LinearOperator.convert_to_matrix(m)\n        errgen_cls = self.errorgen.__class__\n\n        #Note: this only really works for LindbladErrorGen objects now... make more general in FUTURE?\n        truncate = TODENSE_TRUNCATE  # can't just be 'True' since we need to throw errors when appropriate\n        new_errgen = errgen_cls.from_operation_matrix_and_blocks(\n            mx, self.errorgen.coefficient_blocks, 'auto', self.errorgen.matrix_basis,\n            truncate, self.errorgen.evotype, self.errorgen.state_space)\n        self.errorgen.from_vector(new_errgen.to_vector())\n        self._update_rep()  # needed to rebuild exponentiated error gen\n        self.dirty = True\n\n    def transform_inplace(self, s):\n        \"\"\"\n        Update operation matrix `O` with `inv(s) * O * s`.\n\n        Generally, the transform function updates the *parameters* of\n        the operation such that the resulting operation matrix is altered as\n        described above.  If such an update cannot be done (because\n        the operation parameters do not allow for it), ValueError is raised.\n\n        Parameters\n        ----------\n        s : GaugeGroupElement\n            A gauge group element which specifies the \"s\" matrix\n            (and it's inverse) used in the above similarity transform.\n\n        Returns\n        -------\n        None\n        \"\"\"\n        #assert(_np.allclose(U, _np.linalg.inv(Uinv)))\n        #just conjugate postfactor and Lindbladian exponent by U:\n        self.errorgen.transform_inplace(s)\n        self._update_rep()  # needed to rebuild exponentiated error gen\n        self.dirty = True\n\n    def spam_transform_inplace(self, s, typ):\n        \"\"\"\n        Update operation matrix `O` with `inv(s) * O` OR `O * s`, depending on the value of `typ`.\n\n        This functions as `transform_inplace(...)` but is used when this\n        operation is used as a part of a SPAM vector.  When `typ == \"prep\"`,\n        the spam vector is assumed to be `rho = dot(self, <spamvec>)`,\n        which transforms as `rho -> inv(s) * rho`, so `self -> inv(s) * self`.\n        When `typ == \"effect\"`, `e.dag = dot(e.dag, self)` (note that\n        `self` is NOT `self.dag` here), and `e.dag -> e.dag * s`\n        so that `self -> self * s`.\n\n        Parameters\n        ----------\n        s : GaugeGroupElement\n            A gauge group element which specifies the \"s\" matrix\n            (and it's inverse) used in the above similarity transform.\n\n        typ : { 'prep', 'effect' }\n            Which type of SPAM vector is being transformed (see above).\n\n        Returns\n        -------\n        None\n        \"\"\"\n        assert(typ in ('prep', 'effect')), \"Invalid `typ` argument: %s\" % typ\n        from pygsti.models import gaugegroup as _gaugegroup\n\n        if isinstance(s, _gaugegroup.UnitaryGaugeGroupElement) \\\n           or isinstance(s, _gaugegroup.TPSpamGaugeGroupElement):\n            U = s.transform_matrix\n            Uinv = s.transform_matrix_inverse\n            mx = self.to_dense(on_space='minimal') if self._rep_type == 'dense' else self.to_sparse(on_space='minimal')\n\n            #just act on postfactor and Lindbladian exponent:\n            if typ == \"prep\":\n                mx = _mt.safe_dot(Uinv, mx)\n            else:\n                mx = _mt.safe_dot(mx, U)\n            self.set_dense(mx)  # calls _update_rep() and sets dirty flag\n\n    def __str__(self):\n        s = \"Exponentiated operation map with dim = %d, num params = %d\\n\" % \\\n            (self.dim, self.num_params)\n        return s\n\n    def _oneline_contents(self):\n        \"\"\" Summarizes the contents of this object in a single line.  Does not summarize submembers. \"\"\"\n        return \"exponentiates\"\n\n\ndef _d_exp_series(x, dx):\n    TERM_TOL = 1e-12\n    tr = len(dx.shape)  # tensor rank of dx; tr-2 == # of derivative dimensions\n    assert((tr - 2) in (1, 2)), \"Currently, dx can only have 1 or 2 derivative dimensions\"\n    #assert( len( (_np.isnan(dx)).nonzero()[0] ) == 0 ) # NaN debugging\n    #assert( len( (_np.isnan(x)).nonzero()[0] ) == 0 ) # NaN debugging\n    series = dx.copy()  # accumulates results, so *need* a separate copy\n    last_commutant = term = dx; i = 2\n\n    #take d(matrix-exp) using series approximation\n    while _np.amax(_np.abs(term)) > TERM_TOL:  # _np.linalg.norm(term)\n        if tr == 3:\n            #commutant = _np.einsum(\"ik,kja->ija\",x,last_commutant) - \\\n            #            _np.einsum(\"ika,kj->ija\",last_commutant,x)\n            commutant = _np.tensordot(x, last_commutant, (1, 0)) - \\\n                _np.transpose(_np.tensordot(last_commutant, x, (1, 0)), (0, 2, 1))\n        elif tr == 4:\n            #commutant = _np.einsum(\"ik,kjab->ijab\",x,last_commutant) - \\\n            #        _np.einsum(\"ikab,kj->ijab\",last_commutant,x)\n            commutant = _np.tensordot(x, last_commutant, (1, 0)) - \\\n                _np.transpose(_np.tensordot(last_commutant, x, (1, 0)), (0, 3, 1, 2))\n\n        term = 1 / _np.math.factorial(i) * commutant\n\n        #Uncomment some/all of this when you suspect an overflow due to x having large norm.\n        #print(\"DB COMMUTANT NORM = \",_np.linalg.norm(commutant)) # sometimes this increases w/iter -> divergence => NaN\n        #assert(not _np.isnan(_np.linalg.norm(term))), \\\n        #    (\"Haddamard series = NaN! Probably due to trying to differentiate \"\n        #     \"exp(x) where x has a large norm!\")\n\n        #DEBUG\n        #if not _np.isfinite(_np.linalg.norm(term)): break # DEBUG high values -> overflow for nqubit operations\n        #if len( (_np.isnan(term)).nonzero()[0] ) > 0: # NaN debugging\n        #    #WARNING: stopping early b/c of NaNs!!! - usually caused by infs\n        #    break\n\n        series += term  # 1/_np.math.factorial(i) * commutant\n        last_commutant = commutant; i += 1\n    return series\n\n\ndef _d2_exp_series(x, dx, d2x):\n    TERM_TOL = 1e-12\n    tr = len(dx.shape)  # tensor rank of dx; tr-2 == # of derivative dimensions\n    tr2 = len(d2x.shape)  # tensor rank of dx; tr-2 == # of derivative dimensions\n    assert((tr - 2, tr2 - 2) in [(1, 2), (2, 4)]), \"Current support for only 1 or 2 derivative dimensions\"\n\n    series = dx.copy()  # accumulates results, so *need* a separate copy\n    series2 = d2x.copy()  # accumulates results, so *need* a separate copy\n    term = last_commutant = dx\n    last_commutant2 = term2 = d2x\n    i = 2\n\n    #take d(matrix-exp) using series approximation\n    while _np.amax(_np.abs(term)) > TERM_TOL or _np.amax(_np.abs(term2)) > TERM_TOL:\n        if tr == 3:\n            commutant = _np.einsum(\"ik,kja->ija\", x, last_commutant) - \\\n                _np.einsum(\"ika,kj->ija\", last_commutant, x)\n            commutant2A = _np.einsum(\"ikq,kja->ijaq\", dx, last_commutant) - \\\n                _np.einsum(\"ika,kjq->ijaq\", last_commutant, dx)\n            commutant2B = _np.einsum(\"ik,kjaq->ijaq\", x, last_commutant2) - \\\n                _np.einsum(\"ikaq,kj->ijaq\", last_commutant2, x)\n\n        elif tr == 4:\n            commutant = _np.einsum(\"ik,kjab->ijab\", x, last_commutant) - \\\n                _np.einsum(\"ikab,kj->ijab\", last_commutant, x)\n            commutant2A = _np.einsum(\"ikqr,kjab->ijabqr\", dx, last_commutant) - \\\n                _np.einsum(\"ikab,kjqr->ijabqr\", last_commutant, dx)\n            commutant2B = _np.einsum(\"ik,kjabqr->ijabqr\", x, last_commutant2) - \\\n                _np.einsum(\"ikabqr,kj->ijabqr\", last_commutant2, x)\n\n        term = 1 / _np.math.factorial(i) * commutant\n        term2 = 1 / _np.math.factorial(i) * (commutant2A + commutant2B)\n        series += term\n        series2 += term2\n        last_commutant = commutant\n        last_commutant2 = (commutant2A + commutant2B)\n        i += 1\n    return series, series2\n\n\ndef _d_exp_x(x, dx, exp_x=None):\n    \"\"\"\n    Computes the derivative of the exponential of x(t) using\n    the Haddamard lemma series expansion.\n\n    Parameters\n    ----------\n    x : ndarray\n        The 2-tensor being exponentiated\n\n    dx : ndarray\n        The derivative of x; can be either a 3- or 4-tensor where the\n        3rd+ dimensions are for (multi-)indexing the parameters which\n        are differentiated w.r.t.  For example, in the simplest case\n        dx is a 3-tensor s.t. dx[i,j,p] == d(x[i,j])/dp.\n\n    exp_x : ndarray, optional\n        The value of `exp(x)`, which can be specified in order to save\n        a call to `scipy.linalg.expm`.  If None, then the value is\n        computed internally.\n\n    Returns\n    -------\n    ndarray\n        The derivative of `exp(x)` given as a tensor with the\n        same shape and axes as `dx`.\n    \"\"\"\n    tr = len(dx.shape)  # tensor rank of dx; tr-2 == # of derivative dimensions\n    assert((tr - 2) in (1, 2)), \"Currently, dx can only have 1 or 2 derivative dimensions\"\n\n    series = _d_exp_series(x, dx)\n    if exp_x is None: exp_x = _spl.expm(x)\n\n    if tr == 3:\n        #dExpX = _np.einsum('ika,kj->ija', series, exp_x)\n        dExpX = _np.transpose(_np.tensordot(series, exp_x, (1, 0)), (0, 2, 1))\n    elif tr == 4:\n        #dExpX = _np.einsum('ikab,kj->ijab', series, exp_x)\n        dExpX = _np.transpose(_np.tensordot(series, exp_x, (1, 0)), (0, 3, 1, 2))\n\n    return dExpX\n", "meta": {"hexsha": "161300564cb8f853961cf0ddb4d2aef07657f486", "size": 35597, "ext": "py", "lang": "Python", "max_stars_repo_path": "pygsti/modelmembers/operations/experrorgenop.py", "max_stars_repo_name": "pyGSTi-Developers/pyGSTi", "max_stars_repo_head_hexsha": "bfedc1de4d604f14b0f958615776fb80ddb59e33", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pygsti/modelmembers/operations/experrorgenop.py", "max_issues_repo_name": "pyGSTi-Developers/pyGSTi", "max_issues_repo_head_hexsha": "bfedc1de4d604f14b0f958615776fb80ddb59e33", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pygsti/modelmembers/operations/experrorgenop.py", "max_forks_repo_name": "pyGSTi-Developers/pyGSTi", "max_forks_repo_head_hexsha": "bfedc1de4d604f14b0f958615776fb80ddb59e33", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.6311377246, "max_line_length": 120, "alphanum_fraction": 0.6129449111, "include": true, "reason": "import numpy,import scipy", "num_tokens": 8660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.30074557894124154, "lm_q1q2_score": 0.16559273091720766}}
{"text": "from numpy import exp\n\nfrom . helpers import lbm_dubois, ffm_alsallami\nfrom . model import Model\n\n\"\"\"\nopentiva.propofol\n=================\n\nThis module contains the classes for propofol models.\n\nAll Classes have the same following parameters and attributes.\n\nParameters\n----------\nsex\n    0 for male or 1 for female\nage\n    in years\nweight\n    in kg\nheight\n   in cm\n\nAdditional\n~~~~~~~~~~\nopiates_coadministered\n   bool; true if opiates co-administered, Eleveld model only\nbolus_data\n   bool; true for bolus data, Schuttler model only\nvenous_data\n   bool; true for venous data, Schuttler model only\n\nAttributes\n----------\ncompartments : int\n    number of compartments to model; 1, 2 or 3\nconcentration_unit : str\n    drug concentration unit\ntarget_unit : str\n    target concentration unit\nage_lower : float\n    lower age limit of model; -1 if no limit\nage_upper : float\n    upper age limit of model; -1 if no limit\nweight_lower : float\n    lower weight limit of model; -1 if no limit\nweight_upper : float\n    upper weight limit of model; -1 if no limit\npmid : str\n    Pubmed ID of model's reference\ndoi : str\n    Digital Object Identifier (DOI) of model's reference\nwarning : str\n    Warnings relating to non-validated anthropometric values\nv1 : float\n    volume of central compartment\nk10 : float\n    equilibrium rate constant from compartment 1 to 0\nk12 : float\n    equilibrium rate constant from compartment 1 to 2\nk13 : float\n    equilibrium rate constant from compartment 1 to 3\nk21 : float\n    equilibrium rate constant from compartment 2 to 1\nk31 : float\n    equilibrium rate constant from compartment 3 to 1\nke0 : float\n    effect compartment equilibrium rate constant\n\"\"\"\n\n\nclass MarshDiprifusor(Model):\n    \"\"\"MarshDiprifusor class holds pharmacokinetic parameters for the\n       Diprifusor Marsh propofol model with Keo 0.26.\n\n       Reference: PMID: 1859758 DOI: 10.1093/bja/67.1.41\n    \"\"\"\n\n    def __init__(self, sex: int, age: float, weight: float, height: float):\n        super().__init__(sex, age, weight, height)\n\n        self.compartments = 3\n        self.concentration_unit = \"mg/ml\"\n        self.target_unit = \"ug/ml\"\n        self.age_lower = 16\n        self.age_upper = -1\n        self.weight_lower = -1\n        self.weight_upper = 150\n        self.pmid = \"1859758\"\n        self.doi = \"10.1093/bja/67.1.41\"\n        self.validate_anthropometric_values()\n\n        self.v1 = 0.228 * weight\n        self.v2 = 0.463 * weight\n        self.v3 = 2.893 * weight\n\n        self.k10 = 0.119\n        self.k12 = 0.112\n        self.k13 = 0.0419\n        self.k21 = 0.055\n        self.k31 = 0.0033\n        self.ke0 = 0.26\n\n\nclass MarshModified(Model):\n    \"\"\"MarshModified class holds pharmacokinetic parameters for the Modified\n       Marsh propofol model with  Keo 1.2.\n\n       Reference: PMID: 1859758 DOI: 10.1093/bja/67.1.41\n    \"\"\"\n\n    def __init__(self, sex: int, age: float, weight: float, height: float):\n        super().__init__(sex, age, weight, height)\n\n        self.compartments = 3\n        self.concentration_unit = \"mg/ml\"\n        self.target_unit = \"ug/ml\"\n        self.age_lower = 16\n        self.age_upper = -1\n        self.weight_lower = -1\n        self.weight_upper = 150\n        self.pmid = \"1859758\"\n        self.doi = \"10.1093/bja/67.1.41\"\n        self.validate_anthropometric_values()\n\n        self.v1 = 0.228 * weight\n        self.v2 = 0.463 * weight\n        self.v3 = 2.893 * weight\n\n        self.k10 = 0.119\n        self.k12 = 0.112\n        self.k13 = 0.0419\n        self.k21 = 0.055\n        self.k31 = 0.0033\n        self.ke0 = 1.2\n\n\nclass Schnider(Model):\n    \"\"\"Schnider class holds pharmacokinetic parameters for the Schnider propofol\n    model.\n\n    Reference: PMID: 9605675 DOI: 10.1097/00000542-199805000-00006\n    \"\"\"\n\n    def __init__(self, sex: int, age: float, weight: float, height: float):\n        super().__init__(sex, age, weight, height)\n\n        self.compartments = 3\n        self.concentration_unit = \"mg/ml\"\n        self.target_unit = \"ug/ml\"\n        self.age_lower = -1\n        self.age_upper = -1\n        self.weight_lower = -1\n        self.weight_upper = -1\n        if sex == 0:\n            self.bmi_upper = 42\n        elif sex == 1:\n            self.bmi_upper = 35\n        self.pmid = \"9605675\"\n        self.doi = \"10.1097/00000542-199805000-00006\"\n        self.validate_anthropometric_values()\n\n        lbm = lbm_dubois(sex, weight, height)\n\n        self.v1 = 4.27\n        self.v2 = 18.9 - 0.391 * (age - 52)\n        self.v3 = 238\n\n        self.cl1 = 1.89 + 0.0456 * (weight - 77) - 0.0681 * (lbm - 59) \\\n                   + 0.0264 * (height - 177)\n        self.cl2 = 1.29 - 0.024 * (age - 53)\n        self.cl3 = 0.836\n\n        self.k10 = self.cl1 / self.v1\n        self.k12 = self.cl2 / self.v1\n        self.k13 = self.cl3 / self.v1\n        self.k21 = self.cl2 / self.v2\n        self.k31 = self.cl3 / self.v3\n        self.ke0 = 0.456  # TTPE 1.6 minutes is used in original model\n\n\nclass Paedfusor(Model):\n    \"\"\"Paedfusor class holds pharmacokinetic parameters for the Paedfusor propofol\n    model.\n\n    Reference: PMID: 15941735 DOI: 10.1093/bja/aei567\n    \"\"\"\n\n    def __init__(self, sex: int, age: float, weight: float, height: float):\n        super().__init__(sex, age, weight, height)\n\n        self.compartments = 3\n        self.concentration_unit = \"mg/ml\"\n        self.target_unit = \"ug/ml\"\n        self.age_lower = 1\n        self.age_upper = 16\n        self.weight_lower = 5\n        self.weight_upper = 61\n        self.pmid = \"15941735\"\n        self.doi = \"10.1093/bja/aei567\"\n        self.validate_anthropometric_values()\n\n        self.k12 = 0.114\n        self.k13 = 0.0419\n        self.k21 = 0.055\n        self.k31 = 0.0033\n        self.ke0 = 0.26\n\n        if age <= 12:\n            self.v1 = 458.4 * weight / 1000\n            self.k10 = 0.1527 * (weight ** -0.3)\n        elif age >= 13:\n            self.v1 = 400 * weight / 1000\n            self.k10 = 0.0678\n        elif age >= 14:\n            self.v1 = 342 * weight / 1000\n            self.k10 = 0.0792\n        elif age >= 15:\n            self.v1 = 284 * weight / 1000\n            self.k10 = 0.0954\n        elif age >= 16:\n            self.v1 = 228.57 * weight / 1000\n            self.k10 = 0.119\n\n        self.v2 = self.v1 * self.k12 / self.k21 / 1000\n        self.v3 = self.v1 * self.k13 / self.k31 / 1000\n\n\nclass Kataria(Model):\n    \"\"\"Kataria class holds pharmacokinetic parameters for the Kataria propofol\n    model.\n\n    Reference: PMID: 8291699 DOI: 10.1097/00000542-199401000-00018\n    \"\"\"\n\n    def __init__(self, sex: int, age: float, weight: float, height: float):\n        super().__init__(sex, age, weight, height)\n\n        self.compartments = 3\n        self.concentration_unit = \"mg/ml\"\n        self.target_unit = \"ug/ml\"\n        self.age_lower = 3\n        self.age_upper = 11\n        self.weight_lower = 15\n        self.weight_upper = 61\n        self.pmid = \"8291699\"\n        self.doi = \"10.1097/00000542-199401000-00018\"\n        self.validate_anthropometric_values()\n\n        self.v1 = weight * 0.41\n        self.v2 = weight * 0.78 + 3.1 * age - 16\n        self.v3 = weight * 6.9\n        self.cl1 = weight * 0.035\n        self.cl2 = weight * 0.077\n        self.cl3 = weight * 0.026\n\n        self.k10 = self.cl1 / self.v1\n        self.k12 = self.cl2 / self.v1\n        self.k13 = self.cl3 / self.v1\n        self.k21 = self.cl2 / self.v2\n        self.k31 = self.cl3 / self.v3\n        self.ke0 = 0.41\n\n\nclass Eleveld(Model):\n    \"\"\"Eleveld class holds pharmacokinetic parameters for the Eleveld propofol\n    model.\n\n    Reference: PMID: 29661412 DOI: 10.1016/j.bja.2018.01.018\n    \"\"\"\n\n    def __init__(self, sex: int, age: float, weight: float, height: float,\n                 opiates_coadministered: bool):\n        super().__init__(sex, age, weight, height)\n\n        self.compartments = 3\n        self.concentration_unit = \"mg/ml\"\n        self.target_unit = \"ug/ml\"\n        self.age_lower = -1\n        self.age_upper = -1\n        self.weight_lower = -1\n        self.weight_upper = -1\n        self.pmid = \"29661412\"\n        self.doi = \"10.1016/j.bja.2018.01.018\"\n        self.validate_anthropometric_values()\n\n        # Reference\n        sex_ref = 0\n        age_ref = 35\n        weight_ref = 70\n        height_ref = 170\n\n        # Theta constants\n        theta_1 = 6.28  # V1ref L\n        theta_2 = 25.5  # V2ref L\n        theta_3 = 273  # V3ref L\n        theta_4 = 1.79  # CLref (male) L/min\n        theta_5 = 1.83  # Q2ref L/min\n        theta_6 = 1.11  # Q3ref L/min\n        theta_7 = 0.191  # Typical residual error\n        theta_8 = 42.3  # CL maturation E50 weeks\n        theta_9 = 9.06  # CL maturation slope\n        theta_10 = -0.0156  # Smaller V2 with age\n        theta_11 = -0.00286  # Lower CL with age\n        theta_12 = 33.6  # Weight for 50% of maximal V1 Kg\n        theta_13 = -0.0138  # Smaller V3 with age\n        theta_14 = 68.3  # Maturation of Q3 weeks\n        theta_15 = 2.1  # CLref (female) L$min\u00011\n        theta_16 = 1.3  # Higher Q2 for maturation of Q3\n        theta_17 = 1.42  # V1 venous samples (children)\n        theta_18 = 0.68  # Higher Q2 venous samples\n\n        # Post menstrual age\n        pma = age * 52 + 40\n        pma_ref = age_ref * 52 + 40\n\n        def ageing(x, age):\n            return exp(x * (age - age_ref))\n\n        def sigmoid(x, e50, y):\n            return (x ** y) / ((x ** y) + (e50 ** y))\n\n        def central(x):\n            return sigmoid(x, theta_12, 1)\n\n        def opiates(x, present):\n            if present:\n                return exp(x * age)\n            else:\n                return 1\n\n        # cl1 maturation\n        cl1_mat = sigmoid(pma, theta_8, theta_9)\n        cl1_mat_ref = sigmoid(pma_ref, theta_8, theta_9)\n\n        # cl3 maturation\n        cl3_mat = sigmoid(pma, theta_14, 1)\n        cl3_mat_ref = sigmoid(pma_ref, theta_14, 1)\n\n        # fat free mass\n        ffm = ffm_alsallami(sex, age, weight, height)\n        ffm_ref = ffm_alsallami(sex_ref, age_ref, weight_ref, height_ref)\n\n        self.v1 = theta_1 * (central(weight) / central(weight_ref))\n        self.v2 = theta_2 * (weight / weight_ref) * ageing(theta_10, age)\n        self.v3 = theta_3 * (ffm / ffm_ref) * opiates(theta_13,\n                                                      opiates_coadministered)\n\n        if sex == 0:\n            self.cl1 = theta_4 * ((weight / weight_ref) ** 0.75) * \\\n                       (cl1_mat / cl1_mat_ref) * \\\n                       opiates(theta_11, opiates_coadministered)\n        elif sex == 1:\n            self.cl1 = theta_15 * (weight / weight_ref) ** 0.75 * \\\n                       (cl1_mat / cl1_mat_ref) * \\\n                       opiates(theta_11, opiates_coadministered)\n\n        self.cl2 = theta_5 * (self.v2 / theta_2) ** 0.75 * \\\n                    (1 + theta_16 * (1 - cl3_mat))\n\n        self.cl3 = theta_6 * (self.v3 / theta_3) ** 0.75 * \\\n                   (cl3_mat / cl3_mat_ref)\n\n        self.k10 = self.cl1 / self.v1\n        self.k12 = self.cl2 / self.v1\n        self.k13 = self.cl3 / self.v1\n        self.k21 = self.cl2 / self.v2\n        self.k31 = self.cl3 / self.v3\n        self.ke0 = 0.146 * ((weight / weight_ref) ** -0.25)\n\n        self.ce50 = 3.08 * ageing(-0.00635, age)\n\n\nclass Short(Model):\n    \"\"\"Short class holds pharmacokinetic parameters for the Short\n    propofol model; uses Keo from Eleveld\n\n    Reference: PMID: 8130049 DOI: 10.1093/bja/72.3.302\n    \"\"\"\n\n    def __init__(self, sex: int, age: float, weight: float, height: float):\n        super().__init__(sex, age, weight, height)\n\n        self.compartments = 3\n        self.concentration_unit = \"mg/ml\"\n        self.target_unit = \"ug/ml\"\n        self.age_lower = 4\n        self.age_upper = 7\n        self.weight_lower = 15\n        self.weight_upper = 22\n        self.pmid = \"8130049\"\n        self.doi = \"10.1093/bja/72.3.302\"\n        self.validate_anthropometric_values()\n\n        self.v1 = 0.432 * weight\n\n        self.k10 = 0.0967\n        self.k12 = 0.1413\n        self.k13 = 0.1092\n        self.k21 = 0.0392\n        self.k31 = 0.0049\n        self.ke0 = 0.146 * ((weight / 70) ** -0.25)\n\n\nclass Schuttler(Model):\n    \"\"\"Schuttler class holds pharmacokinetic parameters for the Schuttler\n       propofol model; uses Keo from Eleveld\n\n    Reference: PMID:  DOI: 10.1097/00000542-200003000-00017\n    \"\"\"\n\n    def __init__(self, sex: int, age: float, weight: float, height: float,\n                 bolus_data: bool = False, venous_data: bool = False):\n        super().__init__(sex, age, weight, height)\n\n        self.compartments = 3\n        self.concentration_unit = \"mg/ml\"\n        self.target_unit = \"ug/ml\"\n        self.age_lower = 2\n        self.age_upper = 88\n        self.weight_lower = 2\n        self.weight_upper = 88\n        self.pmid = \"10719952\"\n        self.doi = \"10.1097/00000542-200003000-00017\"\n        self.validate_anthropometric_values()\n\n        # Theta constants\n        theta_1 = 1.44\n        theta_2 = 9.3\n        theta_3 = 2.25\n        theta_4 = 44.2\n        theta_5 = 0.92\n        theta_6 = 266\n        theta_7 = 0.75\n        theta_8 = 0.62\n        theta_9 = 0.61\n        theta_10 = 0.045\n        theta_11 = 0.55\n        theta_12 = 0.71\n        theta_13 = 20.39\n        theta_14 = 20.40\n        theta_15 = 1.61\n        theta_16 = 2.02\n        theta_17 = 0.73\n        theta_18 = 20.48\n\n        if bolus_data:\n            bol = 1\n        else:\n            bol = 0\n\n        if venous_data:\n            ven = 1\n        else:\n            ven = 0\n\n        self.v1 = theta_2 * (weight / 70) ** theta_12 * \\\n                  (age / 30) ** theta_13 * (1 + bol * theta_15)\n        self.v2 = theta_4 * (weight / 70) ** theta_9 * \\\n                  (1 + bol * theta_17)\n        self.v3 = theta_6\n\n        if age <= 60:\n            self.cl1 = theta_1 * (weight / 70) ** theta_7\n        else:\n            self.cl1 = theta_1 * (weight / 70) ** theta_7 - \\\n                       (age - 60) * theta_10\n        self.cl2 = theta_3 * (weight / 70) ** theta_8 * \\\n                   (1 + ven * theta_14) * (1 + bol * theta_16)\n        self.cl3 = theta_5 * (weight / 70) ** theta_11 * \\\n                   (1 + bol * theta_18)\n\n        self.k10 = self.cl1 / self.v1\n        self.k12 = self.cl2 / self.v1\n        self.k13 = self.cl3 / self.v1\n        self.k21 = self.cl2 / self.v2\n        self.k31 = self.cl3 / self.v3\n        self.ke0 = 0.146 * ((weight / 70) ** -0.25)\n", "meta": {"hexsha": "edc243c44e3fa380965be9df98a369d2389d8cb2", "size": 14371, "ext": "py", "lang": "Python", "max_stars_repo_path": "opentiva/propofol.py", "max_stars_repo_name": "opentiva/opentiva", "max_stars_repo_head_hexsha": "ba969d7fb651cf5961620dea571911ccd7dbe365", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "opentiva/propofol.py", "max_issues_repo_name": "opentiva/opentiva", "max_issues_repo_head_hexsha": "ba969d7fb651cf5961620dea571911ccd7dbe365", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "opentiva/propofol.py", "max_forks_repo_name": "opentiva/opentiva", "max_forks_repo_head_hexsha": "ba969d7fb651cf5961620dea571911ccd7dbe365", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9395833333, "max_line_length": 82, "alphanum_fraction": 0.565374713, "include": true, "reason": "from numpy", "num_tokens": 4495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.28457601028405616, "lm_q1q2_score": 0.16542491430134973}}
{"text": "\"\"\"\n对transformer encoder的paddle实现。\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom functools import partial\nimport numpy as np\nimport paddle.fluid as fluid\nimport paddle.fluid.layers as layers\n\n\n# transformer_encoder结构的实现\n# transformer_encoder的主题为依次连接的多层encoder层\ndef transformer_encoder(inputs,\n                        attention_bias,\n                        num_attention_layers,\n                        num_attention_heads,\n                        hidden_state_size,\n                        key_size,\n                        value_size,\n                        inner_hidden_size,\n                        attention_dropout,\n                        activate_dropout,\n                        post_and_pre_process_dropout,\n                        hidden_act,\n                        preprocess_cmd=\"n\",\n                        postprocess_cmd=\"da\",\n                        param_initializer=None,\n                        name='',\n                        is_test=False):\n\n    enc_input = inputs\n    enc_output_list = []\n    # 多层encoder依次相连\n    for i in range(num_attention_layers):\n        enc_output = encoder_layer(\n            enc_input,\n            attention_bias,\n            num_attention_heads,\n            hidden_state_size,\n            key_size,\n            value_size,\n            inner_hidden_size,\n            attention_dropout,\n            activate_dropout,\n            post_and_pre_process_dropout,\n            hidden_act,\n            preprocess_cmd,\n            postprocess_cmd,\n            param_initializer=param_initializer,\n            name=name + '_layer_' + str(i),\n            is_test=is_test)\n        enc_output_list.append(enc_output)\n        enc_input = enc_output\n\n    enc_output = pre_process_layer(\n        enc_output, preprocess_cmd, post_and_pre_process_dropout, name=\"post_encoder\", is_test=is_test)\n\n    return enc_output, enc_output_list\n\n\n# encoder层的实现\n# encoder层的主体为multi_head_attention和前馈神经网络\ndef encoder_layer(inputs,\n                  attention_bias,\n                  num_attention_heads,\n                  hidden_state_size,\n                  key_size,\n                  value_size,\n                  inner_hidden_size,\n                  attention_dropout,\n                  activate_dropout,\n                  post_and_pre_process_dropout,\n                  hidden_act,\n                  preprocess_cmd=\"n\",\n                  postprocess_cmd=\"da\",\n                  param_initializer=None,\n                  name='',\n                  is_test=False\n                  ):\n    # multi_head_attention\n    attn_output = multi_head_attention(\n        pre_process_layer(\n            inputs,\n            preprocess_cmd,\n            post_and_pre_process_dropout,\n            name=name + '_pre_att', is_test=is_test),\n        None,\n        None,\n        attention_bias,\n        key_size,\n        value_size,\n        hidden_state_size,\n        num_attention_heads,\n        attention_dropout,\n        param_initializer=param_initializer,\n        name=name + '_multi_head_att', is_test=is_test)\n    attn_output = post_process_layer(\n        inputs,\n        attn_output,\n        postprocess_cmd,\n        post_and_pre_process_dropout,\n        name=name + '_post_att', is_test=is_test)\n\n    # 前馈神经网络层\n    ffd_output = feed_forward_layer(\n        pre_process_layer(\n            attn_output,\n            preprocess_cmd,\n            post_and_pre_process_dropout,\n            name=name + '_pre_ffn',\n            is_test=is_test),\n        hidden_state_size,\n        inner_hidden_size,\n        activate_dropout,\n        hidden_act,\n        param_initializer=param_initializer,\n        name=name + '_ffn',\n        is_test=is_test)\n\n    return post_process_layer(\n        attn_output,\n        ffd_output,\n        postprocess_cmd,\n        post_and_pre_process_dropout,\n        name=name + '_post_ffn',\n        is_test=is_test)\n\n\n# 对encoder_layer中前馈层的实现\n# 其主体为两个全连接层，一层实现hidden_size到inner_hidden_size的转化，另一层实现inner_hidden_size到hidden_size的转化\ndef feed_forward_layer(x,\n                       hidden_size,\n                       inner_hidden_size,\n                       dropout_rate,\n                       hidden_act,\n                       param_initializer=None,\n                       name='ffn',\n                       is_test=False):\n\n    # 将维数为hidden_size的向量转化为inner_hidden_size\n    hidden = layers.fc(input=x,\n                       size=inner_hidden_size,\n                       num_flatten_dims=2,\n                       act=hidden_act,\n                       param_attr=fluid.ParamAttr(\n                           name=name + '_fc_0.w_0',\n                           initializer=param_initializer),\n                       bias_attr=name + '_fc_0.b_0')\n    if dropout_rate:\n        hidden = layers.dropout(\n            hidden,\n            dropout_prob=dropout_rate,\n            dropout_implementation=\"upscale_in_train\",\n            is_test=is_test)\n    # 将维数为inner_hidden_size的向量转化为hidden_size\n    out = layers.fc(input=hidden,\n                    size=hidden_size,\n                    num_flatten_dims=2,\n                    param_attr=fluid.ParamAttr(\n                        name=name + '_fc_1.w_0', initializer=param_initializer),\n                    bias_attr=name + '_fc_1.b_0')\n    return out\n\n\n# 实现dropout、输入相加、normalization的前处理、后处理层\n# 一般接在其他层之前或之后，对输入输出进行处理\ndef pre_post_process_layer(prev_out, out, process_cmd, dropout_rate=0.,\n                           name='', is_test=False):\n\n    for cmd in process_cmd:\n        if cmd == \"a\":  # 两个输入相加\n            out = out + prev_out if prev_out else out\n        elif cmd == \"n\":  # 进行normalization\n            out_type = out.dtype\n            if out_type == fluid.core.VarDesc.VarType.FP16:\n                out = layers.cast(x=out, dtype=\"float32\")\n            out = layers.layer_norm(\n                out,\n                begin_norm_axis=len(out.shape) - 1,\n                param_attr=fluid.ParamAttr(\n                    name=name + '_layer_norm_scale',\n                    initializer=fluid.initializer.Constant(1.)),\n                bias_attr=fluid.ParamAttr(\n                    name=name + '_layer_norm_bias',\n                    initializer=fluid.initializer.Constant(0.)))\n            if out_type == fluid.core.VarDesc.VarType.FP16:\n                out = layers.cast(x=out, dtype=\"float16\")\n        elif cmd == \"d\":  # 进行dropout\n            if dropout_rate:\n                out = layers.dropout(\n                    out,\n                    dropout_prob=dropout_rate,\n                    dropout_implementation=\"upscale_in_train\",\n                    is_test=is_test)\n    return out\n\n\n# 对多头attention计算的实现\n# 通过queries和keys计算attention值，并依此对values进行加权求和\n# attention_bias可实现对某些位置的mask作用\ndef multi_head_attention(queries,\n                         keys,\n                         values,\n                         attention_bias,\n                         key_size,\n                         value_size,\n                         hidden_size,\n                         n_head=1,\n                         dropout_rate=0.,\n                         cache=None,\n                         param_initializer=None,\n                         name='multi_head_att',\n                         is_test=False):\n\n    keys = queries if keys is None else keys\n    values = keys if values is None else values\n\n    if not (len(queries.shape) == len(keys.shape) == len(values.shape) == 3):\n        raise ValueError(\n            \"Inputs: quries, keys and values should all be 3-D tensors.\")\n\n    # 以下为函数定义部分\n    # 定义了一系列计算attention所需的函数\n\n    # 定义q、k、v三个矩阵，将输入的queries、keys、values与三个矩阵相乘得到用于计算的q、k、v\n    def __compute_qkv(queries, keys, values, n_head, key_size, value_size):\n        q = layers.fc(input=queries,\n                      size=key_size * n_head,\n                      num_flatten_dims=2,\n                      param_attr=fluid.ParamAttr(\n                          name=name + '_query_fc.w_0',\n                          initializer=param_initializer),\n                      bias_attr=name + '_query_fc.b_0')\n        k = layers.fc(input=keys,\n                      size=key_size * n_head,\n                      num_flatten_dims=2,\n                      param_attr=fluid.ParamAttr(\n                          name=name + '_key_fc.w_0',\n                          initializer=param_initializer),\n                      bias_attr=name + '_key_fc.b_0')\n        v = layers.fc(input=values,\n                      size=value_size * n_head,\n                      num_flatten_dims=2,\n                      param_attr=fluid.ParamAttr(\n                          name=name + '_value_fc.w_0',\n                          initializer=param_initializer),\n                      bias_attr=name + '_value_fc.b_0')\n        return q, k, v\n\n    # 将输入的[batch_size, max_sequence_length, n_head * hidden_dim]维度的向量转换为[batch_size, n_head, max_sequence_length,\n    # hidden_dim]维度，以便后续的多头attention计算\n    def __split_heads(x, num_head):\n        hidden_size = x.shape[-1]\n        reshaped = layers.reshape(\n            x=x, shape=[0, 0, num_head, hidden_size // num_head], inplace=True)\n        return layers.transpose(x=reshaped, perm=[0, 2, 1, 3])\n\n    # 对_split_heads的逆操作，将[batch_size, n_head, max_sequence_length,hidden_dim]维的向量转化回[batch_size,\n    # max_sequence_length, n_head * hidden_dim]维度\n    def __combine_heads(x):\n\n        if len(x.shape) == 3: return x\n        if len(x.shape) != 4:\n            raise ValueError(\"Input(x) should be a 4-D Tensor.\")\n\n        trans_x = layers.transpose(x, perm=[0, 2, 1, 3])\n        return layers.reshape(\n            x=trans_x,\n            shape=[0, 0, trans_x.shape[2] * trans_x.shape[3]],\n            inplace=True)\n\n    # 计算q与k的点积，并凭此对v加权求和\n    def scaled_dot_product_attention(q, k, v, attn_bias, d_key, dropout_rate, is_test=False):\n        scaled_q = layers.scale(x=q, scale=d_key**-0.5)\n        product = layers.matmul(x=scaled_q, y=k, transpose_y=True)\n        if attn_bias:\n            product += attn_bias\n        weights = layers.softmax(product)\n        if dropout_rate:\n            weights = layers.dropout(\n                weights,\n                dropout_prob=dropout_rate,\n                dropout_implementation=\"upscale_in_train\",\n                is_test=is_test)\n        out = layers.matmul(weights, v)\n        return out\n\n    # 函数定义部分结束\n    # 开始计算attention\n    q, k, v = __compute_qkv(queries, keys, values, n_head, key_size, value_size)\n\n    if cache is not None:  # use cache and concat time steps\n        # Since the inplace reshape in __split_heads changes the shape of k and\n        # v, which is the cache input for next time step, reshape the cache\n        # input from the previous time step first.\n        k = cache[\"k\"] = layers.concat(\n            [layers.reshape(\n                cache[\"k\"], shape=[0, 0, hidden_size]), k], axis=1)\n        v = cache[\"v\"] = layers.concat(\n            [layers.reshape(\n                cache[\"v\"], shape=[0, 0, hidden_size]), v], axis=1)\n\n    # 转化向量维度\n    q = __split_heads(q, n_head)\n    k = __split_heads(k, n_head)\n    v = __split_heads(v, n_head)\n\n    ctx_multiheads = scaled_dot_product_attention(q, k, v, attention_bias, key_size,\n                                                  dropout_rate, is_test=is_test)\n\n    out = __combine_heads(ctx_multiheads)\n\n    # 投影回模型所需的hidden_size，本模型中out的维度与hidden_size相同\n    proj_out = layers.fc(input=out,\n                         size=hidden_size,\n                         num_flatten_dims=2,\n                         param_attr=fluid.ParamAttr(\n                             name=name + '_output_fc.w_0',\n                             initializer=param_initializer),\n                         bias_attr=name + '_output_fc.b_0')\n    return proj_out\n\n\n# 定义用于预处理和后处理的层\npre_process_layer = partial(pre_post_process_layer, None)\npost_process_layer = pre_post_process_layer\n", "meta": {"hexsha": "5e6091f9fb1de96191403c6442fb6b32e3fab027", "size": 11810, "ext": "py", "lang": "Python", "max_stars_repo_path": "model/layer/transformer.py", "max_stars_repo_name": "mottled233/MRC_FastFrame", "max_stars_repo_head_hexsha": "48b63556b2d12526f82f2b307f15cd4d640a6520", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-03-13T05:32:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-27T17:59:10.000Z", "max_issues_repo_path": "model/layer/transformer.py", "max_issues_repo_name": "mottled233/MRC_FastFrame", "max_issues_repo_head_hexsha": "48b63556b2d12526f82f2b307f15cd4d640a6520", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-06-12T07:23:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T22:02:45.000Z", "max_forks_repo_path": "model/layer/transformer.py", "max_forks_repo_name": "mottled233/MRC_FastFrame", "max_forks_repo_head_hexsha": "48b63556b2d12526f82f2b307f15cd4d640a6520", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-14T06:32:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T06:32:34.000Z", "avg_line_length": 35.896656535, "max_line_length": 113, "alphanum_fraction": 0.550635055, "include": true, "reason": "import numpy", "num_tokens": 2660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.16542491077427612}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n\"\"\"\nfrom __future__ import division, print_function, unicode_literals\nimport numpy as np\nimport declarative\n\n#import phasor.numerics.dispatched as dmath\n#import sympy\n\n\nfrom ..utilities.future_from_2 import super\nfrom ..base.autograft import invalidate_auto\nfrom ..base.bases import Element\n\nfrom ..base.multi_unit_args import (\n    unitless_refval_attribute,\n)\n\nfrom .utils import (\n    TargetLeft,\n    TargetRight,\n    TargetIdx,\n    matrix_focus,\n    np_check_sorted,\n    str_m,\n)\n\nfrom .substrates import (\n    substrate_environment,\n)\n\nfrom . import standard_attrs as attrs\n\n\nclass MatrixAtsBase(Element):\n    #TODO report in ctree\n\n    @declarative.dproperty\n    def plotname(self, arg = declarative.NOARG):\n        if arg is declarative.NOARG:\n            arg = self.name\n        return arg\n\n    @declarative.dproperty\n    def reversed(self, arg = declarative.NOARG):\n        elname = \"reversed\"\n        if arg is declarative.NOARG:\n            arg = False\n\n        ooa = self.ctree\n        if self.inst_prototype_t in [\"full\"]:\n            #TODO make this do the correct thing\n            arg = getattr(self.inst_prototype, elname)\n        else:\n            ooa = self.ctree.useidx('immediate')\n\n        ooa[elname] = arg\n        #arg = ooa.setdefault(elname, arg)\n        return ooa[elname]\n\n    @declarative.mproperty\n    def env_reversed(self):\n        #TODO put this into the environment_query\n        #print(\"PREV: \", self.parent.env_reversed, \" ME: \", self.reversed)\n        p_env_reversed = self.parent.environment_query((MatrixAtsBase, \"reversed\"))\n        arg = bool(p_env_reversed) ^ bool(self.reversed)\n        #arg = self.ctree.setdefault(\"env_reversed\", arg)\n        self.ctree.env_reversed = arg\n        return self.ctree.env_reversed\n\n    @declarative.mproperty(simple_delete = True)\n    @invalidate_auto\n    def matrix_inv(self):\n        #print(self.__class__)\n        #print(self.matrix)\n        return self.matrix**(-1)\n\n    def matrix_between(self, tidx1, tidx2):\n        if tidx1 == TargetLeft:\n            if tidx2 == TargetLeft:\n                return np.eye(2)\n            elif tidx2 == TargetRight:\n                return self.matrix\n            else:\n                raise RuntimeError(\"Unknown Target {0}\".format(tidx1))\n        elif tidx1 == TargetRight:\n            if tidx2 == TargetLeft:\n                return self.matrix_inv\n            elif tidx2 == TargetRight:\n                return np.eye(2)\n            else:\n                raise RuntimeError(\"Unknown Target {0}\".format(tidx1))\n        else:\n            print(self.__class__)\n            raise RuntimeError(\"Unknown Target {0}\".format(tidx1))\n\n    def matrix_target_to_z_single(self, tidx1, z_m, invert = False):\n        raise NotImplementedError()\n\n    def matrix_target_to_z(self, tidx1, z_m, fill, invert = False):\n        z_m = np.asarray(z_m)\n        if len(z_m.shape) > 0:\n            if len(z_m.shape) == 1 and np_check_sorted(z_m):\n                return self.matrix_target_to_z_linsorted(tidx1, z_m, fill, invert = invert)\n\n            fill_reshape = fill.reshape(2, 2, -1)\n            idx_remux = np.indices(z_m.shape)\n            idx_remux = idx_remux.reshape(len(z_m.shape), -1)\n            z_m = z_m.reshape(-1)\n            sidx = np.argsort(z_m)\n            z_m = z_m[sidx]\n            idx_remux = idx_remux[:, sidx]\n            self.matrix_target_to_z_linsorted(tidx1, z_m, fill_reshape, invert = invert)\n            fill = fill_reshape[(slice(None), slice(None)) + tuple(idx_remux[i] for i in range(idx_remux.shape[0]))]\n            return\n        else:\n            return self.matrix_target_to_z_single(z_m)\n\n    def matrix_target_to_z_linsorted(self, tidx1, z_m, fill, invert = False):\n        it = np.nditer(z_m, flags = ['multi_index'])\n        while not it.finished:\n            fill[(slice(None), slice(None)) + it.multi_index] = self.matrix_target_to_z_single(tidx1, it.value)\n            it.iternext()\n        return fill\n\n    @declarative.mproperty\n    def constraints(self):\n        return []\n\n    def as_target(self, direction = 'left'):\n        sub_target = self.parent._target_to_child(self)\n        if direction == 'left':\n            return TargetIdx(TargetLeft + sub_target)\n        elif direction == 'right':\n            return TargetIdx(TargetRight + sub_target)\n        else:\n            return None\n\n    def environment_query_local(self, query):\n        if query == (MatrixAtsBase, \"reversed\"):\n            return self.env_reversed\n        return super().environment_query_local(query)\n\n    @declarative.dproperty\n    def root(self):\n        return self.environment_query((MatrixAtsBase, \"root\"))\n\n\nclass MatrixAtsCompositeBase(MatrixAtsBase):\n    pass\n\n\nclass ThinBase(MatrixAtsBase, declarative.OverridableObject):\n    width_m      = 0\n\n    _loc_default = ('loc_m', None)\n    loc_m = attrs.generate_loc_m()\n\n    def matrix_target_to_z_single(self, tidx1, z_m, invert = False):\n        if z_m != 0:\n            raise RuntimeError(\"Only located at 0\")\n\n        #invert if viewing from the right\n        if tidx1 == TargetRight:\n            invert = not invert\n\n        if not invert:\n            return self.matrix\n        else:\n            return self.matrix_inv\n\n    def matrix_target_to_z(self, tidx1, z_m, fill, invert = False):\n        return self.matrix_target_to_z_linsorted(self, z_m, fill, invert = invert)\n\n    def matrix_target_to_z_linsorted(self, tidx1, z_m, fill, invert = False):\n        if not all(z_m == 0):\n            raise RuntimeError(\"Only located at 0\")\n\n        #invert if viewing from the right\n        if tidx1 == TargetRight:\n            invert = not invert\n\n        if not invert:\n            fill[:, :, ...] = self.matrix\n        else:\n            fill[:, :, ...] = self.matrix_inv\n        return\n\n    def target_pos(self, target):\n        return 0\n\n    def system_data_targets(self, typename):\n        dmap = {}\n        return dmap\n\n\nclass NoP(ThinBase):\n    @declarative.mproperty\n    def matrix(self):\n        return np.matrix([[1, 0], [0, 1]])\n\n    @declarative.mproperty(simple_delete = True)\n    def matrix_inv(self):\n        return np.matrix([[1, 0], [0, 1]])\n\n\nclass ThinLens(ThinBase):\n\n    f_m = attrs.generate_f_m()\n\n    @declarative.mproperty\n    def matrix(self):\n        mat = matrix_focus(f_m = self.f_m.val)\n        return mat\n\n    @declarative.mproperty\n    def matrix_inv(self):\n        mat = matrix_focus(f_m = -self.f_m.val)\n        return mat\n\n    def lens_description(self, z, from_target):\n        return declarative.Bunch(\n            f_m = self.f_m.val,\n            z = z,\n            type = 'lens',\n            name = self.plotname,\n            str = 'thin lens f_m = {f_m}'.format(f_m = str_m(self.f_m.val)),\n        )\n\n    def detune_description(self, z, q_left):\n        q_right = q_left.propagate_matrix(self.matrix)\n        cplg02 = q_right.cplg02 - q_left.cplg02\n        return declarative.Bunch(\n            cplg02   = cplg02,\n            type    = 'lens',\n            q       = q_left,\n            obj     = self,\n        )\n\n    def system_data_targets(self, typename):\n        dmap = {}\n        if typename == 'lens_description':\n            dmap[TargetIdx()] = self.lens_description\n        elif typename == 'detune_description':\n            dmap[TargetIdx()] = self.detune_description\n        return dmap\n\n\nclass LensInterface(ThinBase):\n    substrate_from = substrate_environment\n    substrate_to   = substrate_environment\n\n    R_m = attrs.generate_R_m()\n\n    @declarative.mproperty\n    def matrix(self):\n        n_from = self.substrate_from.n(self)\n        n_to   = self.substrate_to.n(self)\n        if self.R_m.val is not None:\n            if not self.env_reversed:\n                mat = np.matrix([\n                    [1, 0],\n                    [(n_from/n_to - 1)/self.R_m.val, n_from / n_to],\n                ])\n            else:\n                mat = np.matrix([\n                    [1, 0],\n                    [(n_to/n_from - 1)/-self.R_m.val, n_to / n_from],\n                ])\n        else:\n            if not self.env_reversed:\n                mat = np.matrix([\n                    [1 , 0],\n                    [0 , n_from / n_to],\n                ])\n            else:\n                mat = np.matrix([\n                    [1 , 0],\n                    [0 , n_to / n_from],\n                ])\n        return mat\n\n    @declarative.mproperty\n    def matrix_inv(self):\n        n_to = self.substrate_from.n(self)\n        n_from = self.substrate_to.n(self)\n        if self.R_m.val is not None:\n            if not self.env_reversed:\n                mat = np.matrix([\n                    [1, 0],\n                    [(n_from/n_to - 1)/self.R_m.val, n_from / n_to],\n                ])\n            else:\n                mat = np.matrix([\n                    [1, 0],\n                    [(n_to/n_from - 1)/-self.R_m.val, n_to / n_from],\n                ])\n        else:\n            if not self.env_reversed:\n                mat = np.matrix([\n                    [1 , 0],\n                    [0 , n_from / n_to],\n                ])\n            else:\n                mat = np.matrix([\n                    [1 , 0],\n                    [0 , n_to / n_from],\n                ])\n        return mat\n\n\nclass Mirror(ThinBase):\n    R_m = attrs.generate_R_m()\n\n    @declarative.mproperty\n    def matrix(self):\n        if self.R_m.val is not None:\n            mat = np.matrix([\n                [1,      0],\n                [-2/self.R_m.val, 1],\n            ])\n        else:\n            mat = np.matrix([\n                [1 , 0],\n                [0 , 1],\n            ])\n        return mat\n\n    def mirror_description(self, z, from_target):\n        if self.R_m.val is not None:\n            f_m = -1/self.matrix[1, 0]\n            return declarative.Bunch(\n                R_m = self.R_m.val,\n                f_m = f_m,\n                z = z,\n                name = self.plotname,\n                type = 'mirror',\n                str = 'Mirror, R_m = {R_m}, f_m = {f_m}'.format(R_m = str_m(self.R_m.val), f_m = str_m(f_m)),\n            )\n        else:\n            return declarative.Bunch(\n                R_m = self.R_m.val,\n                z = z,\n                type = 'mirror',\n                name = self.plotname,\n                str = 'Mirror, flat',\n            )\n\n    def detune_description(self, z, q_left):\n        q_right = q_left.propagate_matrix(self.matrix)\n        cplg02 = q_right.cplg02 + q_left.cplg02\n        return declarative.Bunch(\n            cplg02   = cplg02,\n            type    = 'mirror',\n            q       = q_left,\n            obj     = self,\n        )\n\n    def system_data_targets(self, typename):\n        dmap = {}\n        if typename == 'mirror_description':\n            dmap[TargetIdx()] = self.mirror_description\n        elif typename == 'detune_description':\n            dmap[TargetIdx()] = self.detune_description\n        return dmap\n\n\nclass ABCDGeneric(ThinBase):\n    _A_default = 1\n    @declarative.dproperty_adv\n    def A(desc):\n        return unitless_refval_attribute(\n            desc,\n            prototypes    = ['full', 'base'],\n            default_attr  = '_A_default',\n            allow_fitting = True,\n        )\n\n    _B_default = 0\n    @declarative.dproperty_adv\n    def B(desc):\n        return unitless_refval_attribute(\n            desc,\n            prototypes    = ['full', 'base'],\n            default_attr  = '_B_default',\n            allow_fitting = True,\n        )\n\n    _C_default = 0\n    @declarative.dproperty_adv\n    def C(desc):\n        return unitless_refval_attribute(\n            desc,\n            prototypes    = ['full', 'base'],\n            default_attr  = '_C_default',\n            allow_fitting = True,\n        )\n\n    @declarative.dproperty\n    def D(self):\n        return (self.C.val * self.B.val + 1)/self.A.val\n\n    @declarative.mproperty\n    def matrix(self):\n        return np.matrix([[self.A.val, self.B.val], [self.C.val, self.D]])\n\n", "meta": {"hexsha": "6406e6e5485206b28ff1560cbb2ca2432aca0d5a", "size": 11923, "ext": "py", "lang": "Python", "max_stars_repo_path": "phasor/alm/bases.py", "max_stars_repo_name": "mccullerlp/OpenLoop", "max_stars_repo_head_hexsha": "fe86dc6dec3740d4b6be6b88d8eef8566e2aa78d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-02-28T00:43:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-21T11:39:15.000Z", "max_issues_repo_path": "phasor/alm/bases.py", "max_issues_repo_name": "mccullerlp/OpenLoop", "max_issues_repo_head_hexsha": "fe86dc6dec3740d4b6be6b88d8eef8566e2aa78d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-09-07T23:15:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-07T23:15:43.000Z", "max_forks_repo_path": "phasor/alm/bases.py", "max_forks_repo_name": "mccullerlp/OpenLoop", "max_forks_repo_head_hexsha": "fe86dc6dec3740d4b6be6b88d8eef8566e2aa78d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-21T04:42:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-21T04:42:09.000Z", "avg_line_length": 29.2230392157, "max_line_length": 116, "alphanum_fraction": 0.5431518913, "include": true, "reason": "import numpy,import sympy", "num_tokens": 2883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.16542491077427612}}
{"text": "import numpy as np\nimport warnings\nimport nestpy\n\nprint(f'Using nestpy version {nestpy.__version__}')\n\n@np.vectorize\ndef quanta_from_NEST(en, model, e_field, A, Z, create_s2, **kwargs):\n    \"\"\"\n    Function which uses NEST to yield photons and electrons\n    for a given set of parameters.\n\n    Note:\n        In case the energy deposit is outside of the range of NEST a -1\n        is returned.\n\n    Args:\n        en (numpy.array): Energy deposit of the interaction [keV]\n        model (numpy.array): Nest Id for qunata generation (integers)\n        e_field (numpy.array): Field value in the interaction site [V/cm]\n        A (numpy.array): Atomic mass number\n        Z (numpy.array): Atomic number\n        create_s2 (bool): Specifies if S2 can be produced by interaction,\n            in this case electrons are generated.\n        kwargs: Additional keyword arguments which can be taken by\n            GetYields e.g. density.\n\n    Returns:\n        photons (numpy.array): Number of generated photons\n        electrons (numpy.array): Number of generated electrons\n        excitons (numpy.array): Number of generated excitons\n    \"\"\"\n    nc = nestpy.NESTcalc(nestpy.VDetector())\n    density = 2.862  # g/cm^3\n\n    # Fix for Kr83m events.\n    # Energies have to be very close to 32.1 keV or 9.4 keV\n    # See: https://github.com/NESTCollaboration/nest/blob/master/src/NEST.cpp#L567\n    # and: https://github.com/NESTCollaboration/nest/blob/master/src/NEST.cpp#L585\n    max_allowed_energy_difference = 1  # keV\n    if model == 11:\n        if abs(en - 32.1) > max_allowed_energy_difference:\n            en = 32.1\n        if abs(en - 9.4) > max_allowed_energy_difference:\n            en = 9.4\n\n    # Some addition taken from\n    # https://github.com/NESTCollaboration/nestpy/blob/e82c71f864d7362fee87989ed642cd875845ae3e/src/nestpy/helpers.py#L94-L100\n    if model == 0 and en > 2e2:\n        warnings.warn(f\"Energy deposition of {en} keV beyond NEST validity for NR model of 200 keV - Remove Interaction\")\n        return -1, -1, -1\n    if model == 7 and en > 3e3:\n        warnings.warn(f\"Energy deposition of {en} keV beyond NEST validity for gamma model of 3 MeV - Remove Interaction\")\n        return -1, -1, -1\n    if model == 8 and en > 3e3:\n        warnings.warn(f\"Energy deposition of {en} keV beyond NEST validity for beta model of 3 MeV - Remove Interaction\")\n        return -1, -1, -1\n\n    y = nc.GetYields(interaction=nestpy.INTERACTION_TYPE(model),\n                     energy=en,\n                     drift_field=e_field,\n                     A=A,\n                     Z=Z,\n                     **kwargs\n                     )\n\n    event_quanta = nc.GetQuanta(y)  # Density argument is not use in function...\n\n    photons = event_quanta.photons\n    excitons = event_quanta.excitons\n    electrons = 0\n    if create_s2:\n        electrons = event_quanta.electrons\n\n    return photons, electrons, excitons\n", "meta": {"hexsha": "2f115f6b0f9bf747b37a263fcfebe27b32d6268f", "size": 2904, "ext": "py", "lang": "Python", "max_stars_repo_path": "epix/quanta_generation.py", "max_stars_repo_name": "XENONnT/epix", "max_stars_repo_head_hexsha": "d315551cdcf6b98898c6682952eb0def10646dc3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "epix/quanta_generation.py", "max_issues_repo_name": "XENONnT/epix", "max_issues_repo_head_hexsha": "d315551cdcf6b98898c6682952eb0def10646dc3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 39, "max_issues_repo_issues_event_min_datetime": "2021-01-13T13:18:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T15:29:37.000Z", "max_forks_repo_path": "epix/quanta_generation.py", "max_forks_repo_name": "XENONnT/epix", "max_forks_repo_head_hexsha": "d315551cdcf6b98898c6682952eb0def10646dc3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2105263158, "max_line_length": 126, "alphanum_fraction": 0.641184573, "include": true, "reason": "import numpy", "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.28457601028405616, "lm_q1q2_score": 0.16542491017295916}}
{"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# load a bunch of stuff\nfrom __future__ import division\n# load\nimport cantera as ct\nimport numpy as np\nimport scipy\nimport pylab\nimport matplotlib\nimport matplotlib.pyplot  as plt\nimport matplotlib.gridspec as gridspec\nfrom matplotlib.pyplot import cm\nfrom matplotlib.ticker import NullFormatter, MaxNLocator, LogLocator\nplt.switch_backend('agg')  # needed for saving figures\nimport csv\nfrom pydas.dassl import DASSL\nimport os\nimport rmgpy\nimport rmg\nimport re\nimport operator\nimport pandas as pd\nimport pylab\nfrom cycler import cycler\nimport seaborn as sns\nimport os\nimport multiprocessing\n\n# this chemkin file is from the cti generated by rmg\ngas = ct.Solution('./rh/cantera/chem_annotated.cti', 'gas')\nsurf = ct.Interface('./rh/cantera/chem_annotated.cti', 'surface1', [gas])\n# gas = ct.Solution('chem_vlachos_bidentate.cti', 'gas')\n# surf = ct.Interface('chem_vlachos_bidentate.cti', 'surface1', [gas])\n\nprint(\"This mechanism contains {} gas reactions and {} surface reactions\".format(gas.n_reactions, surf.n_reactions))\n\ni_ar = gas.species_index('Ar')\ni_ch4 = gas.species_index('CH4(2)')\ni_o2 = gas.species_index('O2(3)')\ni_co2 = gas.species_index('CO2(4)')\ni_h2o = gas.species_index('H2O(5)')\ni_h2 = gas.species_index('H2(6)')\ni_co = gas.species_index('CO(7)')\n\n# unit conversion factors to SI\nmm = 0.001\ncm = 0.01\nms = mm\nminute = 60.0\n\n#######################################################################\n# Input Parameters\n#######################################################################\nt_in = 700  # K - in the paper, it was ~698.15K at the start of the cat surface and ~373.15 for the gas inlet temp\nt_cat = t_in\nlength = 70 * mm  # Reactor length- m\ndiam = 16.5*mm  # Reactor diameter - in m\narea = (diam/2.0)**2*np.pi  # Reactor cross section area (area of tube) in m^2\nporosity = 0.81  # Monolith channel porosity, from Horn ref 17 sec 2.2.2\ncat_area_per_vol = 16000  # I made this up, in m-1. 4500 is lowest that \"work\" for all base\nflow_rate = 4.7  # slpm\nflow_rate = flow_rate*.001/60  # m^3/s\ntot_flow = 0.208  # from Horn 2007, constant inlet flow rate in mol/min, equivalent to 4.7 slpm\nvelocity = flow_rate/area  # m/s\n# The PFR will be simulated by a chain of 'NReactors' stirred reactors.\nNReactors = 7001\n\non_catalyst = 1000  # catalyst length 10mm, but it doesn't say where.  let's guess at 1 cm?\noff_catalyst = 2000\ndt = 1.0\n\nreactor_len = length/(NReactors-1)\nrvol = area * reactor_len * porosity\n# catalyst area in one reactor\ncat_area = cat_area_per_vol * rvol\n\n\ndef plotZoom(a):\n    gas_out, surf_out, gas_names, surf_names, dist_array, T_array = a\n\n    fig, axs = plt.subplots(1, 2)\n    axs[0].set_prop_cycle(cycler('color', ['m', 'g', 'b', 'y', 'c', 'r', 'k', 'g']))\n\n    for i in range(len(gas_out[0, :])):\n        if i != i_ar:\n            if gas_out[:, i].max() > 5.e-3:\n                #             print(gas_names[i])\n                axs[0].plot(dist_array, gas_out[:, i], label=gas_names[i])\n                species_name = gas_names[i]\n                if species_name.endswith(')'):\n                    if species_name[-3] == '(':\n                        species_name = species_name[0:-3]\n                    else:\n                        species_name = species_name[0:-4]\n                if species_name == \"O2\":\n                    axs[0].annotate(\"O$_2$\", fontsize=18, color='y',\n                                    xy=(dist_array[1100], gas_out[:, i][1100] + gas_out[:, i][1100] / 100.0),\n                                    va='bottom', ha='center')\n                elif species_name == \"CO2\":\n                    axs[0].annotate(\"CO$_2$\", fontsize=18, color='c',\n                                    xy=(dist_array[2400], gas_out[:, i][2400] + gas_out[:, i][2400] / 10.0), va='bottom',\n                                    ha='center')\n                elif species_name == \"CO\":\n                    axs[0].annotate(\"CO\", fontsize=18, color='g', xy=(dist_array[2100], gas_out[:, i][2100] + 0.001),\n                                    va='bottom', ha='center')\n                elif species_name == \"H2\":\n                    axs[0].annotate(\"H$_2$\", fontsize=18, color='k', xy=(dist_array[2200], gas_out[:, i][2200] - 0.001),\n                                    va='top', ha='center')\n                elif species_name == \"CH4\":\n                    axs[0].annotate(\"CH$_4$\", fontsize=18, color='b',\n                                    xy=(dist_array[1100], gas_out[:, i][1100] + gas_out[:, i][1100] / 100.0),\n                                    va='bottom', ha='center')\n                elif species_name == \"H2O\":\n                    axs[0].annotate(\"H$_2$O\", fontsize=18, color='r',\n                                    xy=(dist_array[2100], gas_out[:, i][2100] + gas_out[:, i][2100] / 40.0 + 0.001), va='bottom',\n                                    ha='center')\n                else:\n                    axs[0].annotate(species_name, fontsize=18,\n                                    xy=(dist_array[-1], gas_out[:, i][-1] + gas_out[:, i][-1] / 10.0), va='top',\n                                    ha='center')\n            else:\n                axs[0].plot(0, 0)\n\n    axs[1].set_prop_cycle(cycler('color', ['m', 'g', 'b', 'y', 'c', 'r', 'k', 'g']))\n    ax2 = axs[0].twinx()\n    ax2.plot(dist_array, T_array, label='temperature', color='r', linestyle=':')\n    axs[0].set_prop_cycle(cycler('color', ['m', 'g', 'b', 'y', 'c', 'r', 'k', 'g']))\n\n    axs[0].plot([dist_array[on_catalyst], dist_array[on_catalyst]], [0, 0.2], linestyle='--', color='xkcd:grey')\n    axs[0].plot([dist_array[off_catalyst], dist_array[off_catalyst]], [0, 0.2], linestyle='--', color='xkcd:grey')\n    axs[0].annotate(\"catalyst\", fontsize=18, xy=(dist_array[on_catalyst], 0.175), va='bottom', ha='left')\n    axs[1].plot([dist_array[on_catalyst], dist_array[on_catalyst]], [600.0, 2000], linestyle='--', color='xkcd:grey')\n    axs[1].plot([dist_array[off_catalyst], dist_array[off_catalyst]], [600.0, 2000], linestyle='--', color='xkcd:grey')\n    axs[1].annotate(\"catalyst\", fontsize=18, xy=(dist_array[on_catalyst], 1800), va='bottom', ha='left')\n\n    for item in (\n            axs[0].get_xticklabels() + axs[0].get_yticklabels() + ax2.get_xticklabels() + ax2.get_yticklabels()):\n        item.set_fontsize(18)\n\n    axs[0].legend(loc='upper center', bbox_to_anchor=(0.5, -0.2), fancybox=False, shadow=False, ncol=4)\n    axs[0].set_ylim(0., 0.1)\n    axs[1].set_ylim(600.0, 2000)\n    axs[0].set_xlim(8, 25)\n    axs[1].set_xlim(8, 25)\n    axs[0].set_xlabel('Distance (mm)', fontsize=22)\n    axs[1].set_xlabel('Distance (mm)', fontsize=22)  # axs[0,1].set_xlabel('time (s)'); axs[1,1].set_xlabel('time (s)')\n    axs[0].set_ylabel('flow/ mol/min', fontsize=22)\n    ax2.set_ylabel('Temperature (K)', fontsize=22)\n    ax2.set_ylim(600, 2000)\n    ax2.set_xlim(8, 25)\n    fig.delaxes(axs[1])  # THIS DELETES THE EXTRA SUBPLOT!\n    fig.set_figheight(6)\n    fig.set_figwidth(24)\n\n    for n in range(len(gas_names)):\n        if gas_names[n] == 'CH4(2)':\n            c_in = gas_out[0][n]\n        if gas_names[n] == 'O2(3)':\n            o_in = gas_out[0][n]\n    ratio = c_in / (o_in * 2)\n    ratio = round(ratio, 1)\n\n    out_dir = 'figures'\n    os.path.exists(out_dir) or os.makedirs(out_dir)\n\n\ndef plotSurf(a):\n    gas_out, surf_out, gas_names, surf_names, dist_array, T_array = a\n\n    fig, axs = plt.subplots(1, 2)\n    axs[0].set_prop_cycle(cycler('color', ['m', 'g', 'b', 'y', 'c', 'r', 'k', 'g']))\n\n    for i in range(len(gas_out[0, :])):\n        if i != i_ar:\n            if gas_out[:, i].max() > 5.e-3:\n                axs[0].plot(dist_array, gas_out[:, i], label=gas_names[i])\n                species_name = gas_names[i]\n                if species_name.endswith(')'):\n                    if species_name[-3] == '(':\n                        species_name = species_name[0:-3]\n                    else:\n                        species_name = species_name[0:-4]\n                if species_name == \"O2\":\n                    axs[0].annotate(\"O$_2$\", fontsize=18,\n                                    xy=(dist_array[2200], gas_out[:, i][2200] + gas_out[:, i][2200] / 100.0),\n                                    va='bottom', ha='center')\n                elif species_name == \"CO2\":\n                    axs[0].annotate(\"CO$_2$\", fontsize=18,\n                                    xy=(dist_array[2200], gas_out[:, i][2200] + gas_out[:, i][2200] / 10.0), va='top',\n                                    ha='center')\n                elif species_name == \"CO\":\n                    axs[0].annotate(\"CO\", fontsize=18, xy=(dist_array[2200], gas_out[:, i][2200] + 0.001),\n                                    va='bottom', ha='center')\n                elif species_name == \"CH2O\":\n                    axs[0].annotate(\"CH$_2$O\", fontsize=18, xy=(dist_array[2200], gas_out[:, i][2200] + 0.001),\n                                    va='bottom', ha='center')\n                elif species_name == \"CH4\":\n                    axs[0].annotate(\"CH$_4$\", fontsize=18,\n                                    xy=(dist_array[2200], gas_out[:, i][2200] + gas_out[:, i][2200] / 100.0),\n                                    va='bottom', ha='center')\n                elif species_name == \"H2O\":\n                    axs[0].annotate(\"H$_2$O\", fontsize=18,\n                                    xy=(dist_array[2200], gas_out[:, i][2200] + gas_out[:, i][2200] / 40.0), va='top',\n                                    ha='center')\n                else:\n                    axs[0].annotate(species_name, fontsize=18,\n                                    xy=(dist_array[-1], gas_out[:, i][-1] + gas_out[:, i][-1] / 10.0), va='top',\n                                    ha='center')\n            else:\n                axs[0].plot(0, 0)\n\n    axs[1].set_prop_cycle(cycler('color', ['m', 'g', 'b', 'y', 'c', 'r', 'k', 'g']))\n    # Plot two temperatures (of gas-phase and surface vs only surface.)\n    for i in range(len(surf_out[0, :])):\n        if surf_out[:, i].max() > 5.e-3:\n            axs[1].semilogy(dist_array, surf_out[:, i], label=surf_names[i])\n    axs[0].set_prop_cycle(cycler('color', ['m', 'g', 'b', 'y', 'c', 'r', 'k', 'g']))\n\n    axs[0].plot([dist_array[on_catalyst], dist_array[on_catalyst]], [0, 0.2], linestyle='--', color='xkcd:grey')\n    axs[0].plot([dist_array[off_catalyst], dist_array[off_catalyst]], [0, 0.2], linestyle='--', color='xkcd:grey')\n    axs[0].annotate(\"catalyst\", fontsize=18, xy=(dist_array[on_catalyst], 0.175), va='bottom', ha='left')\n    axs[1].plot([dist_array[on_catalyst], dist_array[on_catalyst]], [0, 1.2], linestyle='--', color='xkcd:grey')\n    axs[1].plot([dist_array[off_catalyst], dist_array[off_catalyst]], [0, 1.2], linestyle='--', color='xkcd:grey')\n    axs[1].annotate(\"catalyst\", fontsize=18, xy=(dist_array[on_catalyst], 1.1), va='bottom', ha='left')\n\n    for item in (\n            axs[0].get_xticklabels() + axs[0].get_yticklabels() + axs[1].get_xticklabels() + axs[1].get_yticklabels()):\n        item.set_fontsize(18)\n\n    axs[1].legend(loc='upper center', bbox_to_anchor=(0.5, -0.2), fancybox=False, shadow=False, ncol=2)\n    axs[0].legend(loc='upper center', bbox_to_anchor=(0.5, -0.2), fancybox=False, shadow=False, ncol=4)\n    axs[0].set_ylim(0., 0.1)\n    axs[1].set_ylim(1e-10, 1.2)\n    axs[0].set_xlim(5, 25)\n    axs[1].set_xlim(9, 21)\n    axs[0].set_xlabel('Distance (mm)', fontsize=22)\n    axs[1].set_xlabel('Distance (mm)', fontsize=22)\n    axs[0].set_ylabel('flow/ mol/min', fontsize=22)\n    axs[1].set_ylabel('Site fraction', fontsize=22)\n    fig.delaxes(axs[0])  # THIS DELETES THE EXTRA SUBPLOT!\n\n    fig.set_figheight(6)\n    fig.set_figwidth(18)\n\n    for n in range(len(gas_names)):\n        if gas_names[n] == 'CH4(2)':\n            c_in = gas_out[0][n]\n        if gas_names[n] == 'O2(3)':\n            o_in = gas_out[0][n]\n    ratio = c_in / (o_in * 2)\n    ratio = round(ratio, 1)\n\n    out_dir = 'figures'\n    os.path.exists(out_dir) or os.makedirs(out_dir)\n    fig.clf()\n\n\ndef monolithFull(gas, surf, temp, mol_in, verbose=False, sens=False):\n    \"\"\"\n    Verbose prints out values as you go along\n    Sens is for sensitivity, in the form [perturbation, reaction #]\n    \"\"\"\n    ch4, o2, ar = mol_in\n    ratio = ch4/(2*o2)\n    ratio = round(ratio, 1)\n    ch4 = str(ch4)\n    o2 = str(o2)\n    ar = str(ar)\n    X = str('CH4(2):' + ch4 + ', O2(3):' + o2 + ', Ar:' + ar)\n    gas.TPX = 273.15, ct.one_atm, X  # need to initialize mass flow rate at STP\n    mass_flow_rate = flow_rate * gas.density_mass\n    gas.TPX = temp, ct.one_atm, X\n    temp_cat = temp\n    surf.TP = temp_cat, ct.one_atm\n    surf.coverages = 'X(1):1.0'\n    gas.set_multiplier(1.0)\n\n    TDY = gas.TDY\n    cov = surf.coverages\n\n    if verbose is True:\n        print('  distance(mm)   X_CH4        X_O2        X_H2       X_CO       X_H2O       X_CO2')\n\n    # create a new reactor\n    gas.TDY = TDY\n    r = ct.IdealGasReactor(gas)\n    r.volume = rvol\n\n    # create a reservoir to represent the reactor immediately upstream. Note\n    # that the gas object is set already to the state of the upstream reactor\n    upstream = ct.Reservoir(gas, name='upstream')\n\n    # create a reservoir for the reactor to exhaust into. The composition of\n    # this reservoir is irrelevant.\n    downstream = ct.Reservoir(gas, name='downstream')\n\n    # Add the reacting surface to the reactor. The area is set to the desired\n    # catalyst area in the reactor.\n    rsurf = ct.ReactorSurface(surf, r, A=cat_area)\n\n    # The mass flow rate into the reactor will be fixed by using a\n    # MassFlowController object.\n    # mass_flow_rate = velocity * gas.density_mass * area  # kg/s\n    # mass_flow_rate = flow_rate * gas.density_mass\n    m = ct.MassFlowController(upstream, r, mdot=mass_flow_rate)\n\n    # We need an outlet to the downstream reservoir. This will determine the\n    # pressure in the reactor. The value of K will only affect the transient\n    # pressure difference.\n    v = ct.PressureController(r, downstream, master=m, K=1e-5)\n\n    sim = ct.ReactorNet([r])\n    sim.max_err_test_fails = 12\n\n    # set relative and absolute tolerances on the simulation\n    sim.rtol = 1.0e-10\n    sim.atol = 1.0e-20\n\n    gas_names = gas.species_names\n    surf_names = surf.species_names\n    gas_out = []\n    surf_out = []\n    dist_array = []\n    T_array = []\n\n    surf.set_multiplier(0.0)  # no surface reactions until the gauze\n    for n in range(NReactors):\n        # Set the state of the reservoir to match that of the previous reactor\n        gas.TDY = r.thermo.TDY\n        upstream.syncState()\n        if n == on_catalyst:\n            surf.set_multiplier(1.0)\n            if sens is not False:\n                surf.set_multiplier(1.0 + sens[0], sens[1])\n        if n == off_catalyst:\n            surf.set_multiplier(0.0)\n        sim.reinitialize()\n        sim.advance_to_steady_state()\n        dist = n * reactor_len * 1.0e3  # distance in mm\n        dist_array.append(dist)\n        T_array.append(surf.T)\n        # print \"mass_flow_rate\", mass_flow_rate,  v.mdot(sim.time), \"kg/s\"\n        kmole_flow_rate = mass_flow_rate / gas.mean_molecular_weight  # kmol/s\n        gas_out.append(1000 * 60 * kmole_flow_rate * gas.X.copy())  # molar flow rate in moles/minute\n        surf_out.append(surf.X.copy())\n\n        # make reaction diagrams\n        out_dir = 'rxnpath'\n        os.path.exists(out_dir) or os.makedirs(out_dir)\n        elements = ['H', 'O']\n        locations_of_interest = [1000, 1150, 1160, 1183, 1196, 1999]\n        if sens is False:\n            for l in locations_of_interest:\n                if n == l:\n                    location = str(n / 100)\n\n                    diagram = ct.ReactionPathDiagram(surf, 'X')\n                    diagram.title = 'rxn path'\n                    diagram.label_threshold = 1e-9\n                    dot_file = out_dir + '/rxnpath-' + str(ratio) + '-x-' + location + 'mm.dot'\n                    img_file = out_dir + '/rxnpath-' + str(ratio) + '-x-' + location + 'mm.png'\n                    img_path = os.path.join(out_dir, img_file)\n                    diagram.write_dot(dot_file)\n                    os.system('dot {0} -Tpng -o{1} -Gdpi=200'.format(dot_file, img_file))\n\n                    for element in elements:\n                        diagram = ct.ReactionPathDiagram(surf, element)\n                        diagram.title = element + 'rxn path'\n                        diagram.label_threshold = 1e-9\n                        dot_file = out_dir + '/rxnpath-' + str(ratio) + '-surf-' + location + 'mm-' + element + '.dot'\n                        img_file = out_dir + '/rxnpath-' + str(ratio) + '-surf-' + location + 'mm-' + element + '.png'\n                        img_path = os.path.join(out_dir, img_file)\n                        diagram.write_dot(dot_file)\n                        os.system('dot {0} -Tpng -o{1} -Gdpi=200'.format(dot_file, img_file))\n        else:\n            pass\n\n        if verbose is True:\n            if not n % 100:\n                print('  {0:10f}  {1:10f}  {2:10f}  {3:10f} {4:10f} {5:10f} {6:10f}'.format(dist, *gas[\n                    'CH4(2)', 'O2(3)', 'H2(6)', 'CO(7)', 'H2O(5)', 'CO2(4)'].X * 1000 * 60 * kmole_flow_rate))\n\n    gas_out = np.array(gas_out)\n    surf_out = np.array(surf_out)\n    gas_names = np.array(gas_names)\n    surf_names = np.array(surf_names)\n    data_out = gas_out, surf_out, gas_names, surf_names, dist_array, T_array\n    return data_out\n\n\nratio = 1.0\nfo2 = 1 / (2. * ratio + 1 + 79 / 21)\nfch4 = 2 * fo2 * ratio\nfar = 79 * fo2 / 21\nratio_in = [fch4, fo2, far]\n\na = monolithFull(gas, surf, t_in, ratio_in)\ngas_out, surf_out, gas_names, surf_names, dist_array, T_array = a\n\ndef deriv(p):\n    deriv = []\n    for x in range(7000):\n        deriv.append((p[x+1] - p[x])/.01)\n    deriv.append(0.)\n    return deriv\n\nmethane = gas_out[:,3]\noxygen = gas_out[:,4]\nhydrogen = gas_out[:,7]\nco2 = gas_out[:,5]\nco = gas_out[:,8]\nh2o = gas_out[:,6]\n\nd_ch4 = deriv(methane)\nd_o2 = deriv(oxygen)\nd_h2 = deriv(hydrogen)\nd_co2 = deriv(co2)\nd_co = deriv(co)\nd_h2o = deriv(h2o)\n\n\nplt.figure(figsize=(6,5))\nplt.plot(dist_array,d_ch4,color='green')\nplt.plot(dist_array,d_o2,color='orange')\nplt.plot(dist_array,d_h2,color='k')\nplt.plot(dist_array,d_co2,color='blue')\nplt.plot(dist_array,d_co,color='limegreen')\nplt.plot(dist_array,d_h2o,color='dodgerblue')\n\nplt.annotate(\"CH$_4$\", fontsize=18, color='g',\n            xy=(dist_array[1140], -.15),\n            va='bottom', ha='center')\nplt.annotate(\"O$_2$\", fontsize=18, color='orange',\n            xy=(dist_array[1113], -.17),\n            va='bottom', ha='center')\nplt.annotate(\"H$_2$\", fontsize=18, color='k',\n            xy=(dist_array[1144], .15),\n            va='bottom', ha='center')\nplt.annotate(\"CO\", fontsize=18, color='limegreen',\n            xy=(dist_array[1137], .03),\n            va='bottom', ha='center')\nplt.annotate(\"CO$_2$\", fontsize=18, color='blue',\n            xy=(dist_array[1125], -0.03),\n            va='bottom', ha='center')\nplt.annotate(\"H$_2$O\", fontsize=18, color='dodgerblue',\n            xy=(dist_array[1105], .1),\n            va='bottom', ha='center')\n\nplt.xlabel('Position (mm)', fontsize=22)\nplt.ylabel('d Flow/dx', fontsize=22)\nplt.xticks(fontsize=18)\nplt.yticks(fontsize=18)\nplt.xticks(np.arange(10.5,12.5,0.5))\nplt.yticks(np.arange(-.2,.25, .1))\nplt.xlim(10.5,12.)\nplt.savefig('./paperplots/deriv.pdf',bbox_inches='tight',dpi=300)\nplt.clf()\n\ntemp_profile = np.array([\n        [0.,373.15],\n        [1.,373.15],\n        [2.,373.15],\n        [3.,373.15],\n        [4.,373.15],\n        [5.,373.15],\n        [6.,413.15],\n        [7.,448.15],\n        [8.,473.15],\n        [9.,548.15],\n        [10.,648.15],\n        [11.,963.15],\n        [12.,1133.15],\n        [13.,1173.15],\n        [14.,1163.15],\n        [15.,1123.15],\n        [16.,1098.15],\n        [17.,1073.15],\n        [18.,1068.15],\n        [19.,1063.15],\n        [20.,1048.15],\n        [21.,1033.15],\n        [22.,1028.15],\n        [23.,1023.15],\n        [24.,1023.15],\n        [25.,1023.15],])\n\nch4_in = 21/71*.208\nch4_profile = np.array([\n        [0.,ch4_in],\n        [1.,ch4_in],\n        [2.,ch4_in],\n        [3.,ch4_in],\n        [4.,ch4_in],\n        [5.,ch4_in],\n        [6.,ch4_in],\n        [7.,ch4_in],\n        [8.,ch4_in],\n        [9.,ch4_in],\n        [10.,ch4_in],\n        [10.25,0.059],\n        [10.5,0.048],\n        [10.75,0.041],\n        [11.,0.036],\n        [11.5,0.028],\n        [12.,0.0225],\n        [12.25,0.022],\n        [12.5,0.021],\n        [13.,0.021],\n        [13.5,0.022],\n        [14.,0.022],\n        [14.5,0.021],\n        [15.,0.019],\n        [15.5,0.017],\n        [16.,0.016],\n        [17.,0.016],\n        [18.,0.015],\n        [19.,0.015],\n        [20.,0.015],\n        [21.,0.014],\n        [22.,0.014],\n        [23.,0.014],\n        [24.,0.014],\n        [25.,0.014],])\n\no2_in = (1 / (2. + 1 + 79 / 21)) * .208\no2_profile = np.array([\n        [0.,o2_in],\n        [1.,o2_in],\n        [2.,o2_in],\n        [3.,o2_in],\n        [4.,o2_in],\n        [5.,o2_in],\n        [6.,o2_in],\n        [7.,o2_in],\n        [8.,o2_in],\n        [9.,o2_in],\n        [9.5,o2_in],\n        [9.75,o2_in],\n        [10.,o2_in],\n        [10.1,0.028],\n        [10.25,0.022],\n        [10.5,0.013],\n        [10.75,0.008],\n        [11.,0.004],\n        [11.25,0.001],\n        [11.5,0.],\n        [12.,0.],\n        [13.,0.],\n        [14.,0.],\n        [15.,0.],\n        [16.,0.],\n        [17.,0.],\n        [18.,0.],\n        [19.,0.],\n        [20.,0.],\n        [21.,0.],\n        [22.,0.],\n        [23.,0.],\n        [24.,0.],\n        [25.,0.],])\n\nh2_profile = np.array([\n        [0.,0],\n        [1.,0],\n        [2.,0],\n        [3.,0],\n        [4.,0],\n        [5.,0],\n        [6.,0],\n        [7.,0],\n        [8.,0],\n        [9.,0],\n        [10.,0],\n        [10.5,0.015],\n        [11.,0.034],\n        [12.,0.051],\n        [13.,0.065],\n        [14.,0.071],\n        [15.,0.083],\n        [16.,0.089],\n        [17.,0.0895],\n        [18.,0.09],\n        [19.,0.0905],\n        [20.,0.091],\n        [21.,0.092],\n        [22.,0.092],\n        [23.,0.092],\n        [24.,0.092],\n        [25.,0.092],])\n\nco_profile = np.array([\n        [0.,0],\n        [1.,0],\n        [2.,0],\n        [3.,0],\n        [4.,0],\n        [5.,0],\n        [6.,0],\n        [7.,0],\n        [8.,0],\n        [9.,0],\n        [10.,0],\n        [10.5,0.015],\n        [11.,0.026],\n        [12.,0.035],\n        [13.,0.04],\n        [14.,0.036],\n        [15.,0.04],\n        [16.,0.044],\n        [17.,0.045],\n        [18.,0.045],\n        [19.,0.045],\n        [20.,0.045],\n        [21.,0.045],\n        [22.,0.045],\n        [23.,0.045],\n        [24.,0.045],\n        [25.,0.045],])\n\nh2o_profile = np.array([\n        [0.,0],\n        [1.,0],\n        [2.,0],\n        [3.,0],\n        [4.,0],\n        [5.,0],\n        [6.,0],\n        [7.,0],\n        [8.,0],\n        [9.,0],\n        [10.,0],\n        [10.5,0.015],\n        [11.,0.025],\n        [11.5,0.026],\n        [12.,0.025],\n        [12.5,0.022],\n        [13.,0.019],\n        [14.,0.011],\n        [15.,0.009],\n        [16.,0.009],\n        [17.,0.009],\n        [18.,0.008],\n        [19.,0.008],\n        [20.,0.008],\n        [21.,0.008],\n        [22.,0.008],\n        [23.,0.008],\n        [24.,0.008],\n        [25.,0.008],])\n\nco2_profile = np.array([\n        [0.,0],\n        [1.,0],\n        [2.,0],\n        [3.,0],\n        [4.,0],\n        [5.,0],\n        [6.,0],\n        [7.,0],\n        [8.,0],\n        [9.,0],\n        [10.,0],\n        [11.,0.002],\n        [12.,0.002],\n        [12.5,0.002],\n        [13.,0.002],\n        [14.,0.002],\n        [15.,0.002],\n        [16.,0.002],\n        [17.,0.002],\n        [18.,0.002],\n        [19.,0.002],\n        [20.,0.002],\n        [21.,0.002],\n        [22.,0.002],\n        [23.,0.002],\n        [24.,0.002],\n        [25.,0.002],])\n\n\nfrom scipy.interpolate import interp1d\n\ndist = np.linspace(0,25,2501)\nch4 = interp1d(ch4_profile[:,0],ch4_profile[:,1],kind='cubic')\no2 = interp1d(o2_profile[:,0],o2_profile[:,1],kind='cubic')\nh2 = interp1d(h2_profile[:,0],h2_profile[:,1],kind='cubic')\nco = interp1d(co_profile[:,0],co_profile[:,1],kind='cubic')\nh2o = interp1d(h2o_profile[:,0],h2o_profile[:,1],kind='cubic')\nco2 = interp1d(co2_profile[:,0],co2_profile[:,1],kind='cubic')\ntemp = interp1d(temp_profile[:,0],temp_profile[:,1],kind='cubic')\n\nplt.plot(dist,ch4(dist),color='g')\nplt.annotate(\"CH$_4$\", fontsize=18, color='g',\n            xy=(dist_array[700], .062),\n            va='bottom', ha='center')\nplt.plot(dist,o2(dist),color='orange')\nplt.annotate(\"O$_2$\", fontsize=18, color='orange',\n            xy=(dist_array[700], .032),\n            va='bottom', ha='center')\nplt.plot(dist,h2(dist),color='k')\nplt.annotate(\"H$_2$\", fontsize=18, color='k',\n            xy=(dist_array[2300], .072),\n            va='bottom', ha='center')\nplt.plot(dist,co(dist),color='limegreen')\nplt.annotate(\"CO\", fontsize=18, color='limegreen',\n            xy=(dist_array[2300], .03),\n            va='bottom', ha='center')\nplt.plot(dist,co2(dist),color='blue')\nplt.annotate(\"CO$_2$\", fontsize=18, color='blue',\n            xy=(dist_array[2200], .002),\n            va='bottom', ha='center')\nplt.plot(dist,h2o(dist),color='dodgerblue')\nplt.annotate(\"H$_2$O\", fontsize=18, color='dodgerblue',\n            xy=(dist_array[1600], .01),\n            va='bottom', ha='center')\nplt.plot([dist_array[on_catalyst], dist_array[on_catalyst]], [0, 0.1], linestyle='--', color='xkcd:grey')\nplt.plot([dist_array[off_catalyst], dist_array[off_catalyst]], [0, 0.1], linestyle='--', color='xkcd:grey')\nplt.annotate(\"catalyst\", fontsize=18, xy=(dist_array[1500], 0.095), va='center', ha='center')\n\nplt.ylabel('Flow (mol/min)', fontsize=22)\nplt.xlabel('Position (mm)', fontsize=22)\nplt.ylim((0,0.1))\nplt.xlim((5,25))\nplt.xticks(fontsize=18)\nplt.yticks(fontsize=18)\nplt.xticks(np.arange(6,26,2))\n\nax2 = plt.twinx()\nax2.plot(dist,temp(dist), ':', color='r')\nax2.set_ylim(300, 2000)\nax2.annotate(\"T\",fontsize=18, color='r',\n             xy=(dist_array[2300], 1310),\n             va='top', ha='center')\nax2.set_ylabel('Temperature (K)', fontsize=22)\nfor item in (ax2.get_yticklabels()):\n             item.set_fontsize(18)\nplt.savefig('./paperplots/horn_data.pdf',bbox_inches='tight',dpi=300)\nplt.clf()\n\n\n# plotting ch4\nplt.plot(dist_array,gas_out[:,3], label=gas_names[3],color='g')\nplt.annotate(\"CH$_4$\", fontsize=18, color='g',\n            xy=(dist_array[700], gas_out[:, 3][500] + gas_out[:, 3][500] / 100.0),\n            va='bottom', ha='center')\nplt.plot(dist,ch4(dist),'--',color='g')\n# plotting o2\nplt.plot(dist_array,gas_out[:,4], label=gas_names[4],color='orange')\nplt.annotate(\"O$_2$\", fontsize=18, color='orange',\n            xy=(dist_array[700], gas_out[:, 4][500] + gas_out[:, 4][500] / 100.0),\n            va='bottom', ha='center')\nplt.plot(dist,o2(dist),'--',color='orange')\n\nplt.plot([dist_array[on_catalyst], dist_array[on_catalyst]], [0, 0.1], linestyle=':', color='xkcd:grey')\nplt.plot([dist_array[off_catalyst], dist_array[off_catalyst]], [0, 0.1], linestyle=':', color='xkcd:grey')\nplt.annotate(\"catalyst\", fontsize=18, xy=(dist_array[1500], 0.095), va='center', ha='center')\n\nplt.ylabel('Flow (mol/min)', fontsize=22)\nplt.xlabel('Position (mm)', fontsize=22)\nplt.ylim((0,0.1))\nplt.xticks(fontsize=18)\nplt.yticks(fontsize=18)\nplt.xticks(np.arange(6,26,2))\n\nax2 = plt.twinx()\nax2.plot(dist,temp(dist), '--', color='r')\nax2.plot(dist_array,T_array,color='r')\nax2.annotate(\"T\",fontsize=18, color='r',\n             xy=(dist_array[2300], T_array[2300] -150),\n             va='top', ha='center')\nax2.set_ylim(300, 2000)\nax2.set_ylabel('Temperature (K)', fontsize=22)\nfor item in (ax2.get_yticklabels()):\n             item.set_fontsize(18)\n\nplt.xlim((5,25))  # cutting off where the horn paper cuts off the plots\nplt.savefig('./paperplots/compare_ch4_o2_temp.pdf',bbox_inches='tight',dpi=300)\nplt.clf()\n\n\n# plotting h2\nplt.plot(dist_array,gas_out[:,7], label=gas_names[7],color='k')\nplt.annotate(\"H$_2$\", fontsize=18, color='k',\n            xy=(dist_array[2200], gas_out[:, 7][2200] + gas_out[:, 7][2200] / 100.0),\n            va='bottom', ha='center')\nplt.plot(dist,h2(dist),'--',color='k')\n# plotting co\nplt.plot(dist_array,gas_out[:,8], label=gas_names[8],color='limegreen')\nplt.annotate(\"CO\", fontsize=18, color='limegreen',\n            xy=(dist_array[1800], gas_out[:, 8][1800] + gas_out[:, 8][1800] / 100.0),\n            va='bottom', ha='center')\nplt.plot(dist,co(dist),'--',color='limegreen')\n\nplt.plot([dist_array[on_catalyst], dist_array[on_catalyst]], [0, 0.1], linestyle=':', color='xkcd:grey')\nplt.plot([dist_array[off_catalyst], dist_array[off_catalyst]], [0, 0.1], linestyle=':', color='xkcd:grey')\nplt.annotate(\"catalyst\", fontsize=18, xy=(dist_array[1500], 0.095), va='center', ha='center')\n\nplt.ylabel('Flow (mol/min)', fontsize=22)\nplt.xlabel('Position (mm)', fontsize=22)\nplt.ylim((0,0.1))\nplt.xticks(fontsize=18)\nplt.yticks(fontsize=18)\nplt.xticks(np.arange(6,26,2))\n\nplt.xlim((5,25))  # cutting off where the horn paper cuts off the plots\nplt.savefig('./paperplots/compare_h2_co.pdf',bbox_inches='tight',dpi=300)\nplt.clf()\n\n\n# plotting h2o\nplt.plot(dist_array,gas_out[:,6], label=gas_names[6],color='dodgerblue')\nplt.annotate(\"H$_2$O\", fontsize=18, color='dodgerblue',\n            xy=(dist_array[2200], gas_out[:, 6][2200] -.01),\n            va='bottom', ha='center')\nplt.plot(dist,h2o(dist),'--',color='dodgerblue')\n# plotting co2\nplt.plot(dist_array,gas_out[:,5], label=gas_names[5],color='blue')\nplt.annotate(\"CO$_2$\", fontsize=18, color='blue',\n            xy=(dist_array[1400], .009),\n            va='bottom', ha='center')\nplt.plot(dist,co2(dist),'--',color='blue')\n\nplt.plot([dist_array[on_catalyst], dist_array[on_catalyst]], [0, 0.1], linestyle=':', color='xkcd:grey')\nplt.plot([dist_array[off_catalyst], dist_array[off_catalyst]], [0, 0.1], linestyle=':', color='xkcd:grey')\nplt.annotate(\"catalyst\", fontsize=18, xy=(dist_array[1500], 0.095), va='center', ha='center')\n\nplt.ylabel('Flow (mol/min)', fontsize=22)\nplt.xlabel('Position (mm)', fontsize=22)\nplt.ylim((0,0.1))\nplt.xticks(fontsize=18)\nplt.yticks(fontsize=18)\nplt.xticks(np.arange(6,26,2))\n\nplt.xlim((5,25))  # cutting off where the horn paper cuts off the plots\nplt.savefig('./paperplots/compare_h2o_co2.pdf',bbox_inches='tight',dpi=300)\nplt.clf()\n\n\n# plotting ch4\nplt.plot(dist_array,gas_out[:,3], label=gas_names[3],color='g')\nplt.annotate(\"CH$_4$\", fontsize=18, color='g',\n            xy=(dist_array[700], gas_out[:, 3][500] + gas_out[:, 3][500] / 100.0),\n            va='bottom', ha='center')\nplt.plot(dist,ch4(dist),'--',color='g')\n# plotting o2\nplt.plot(dist_array,gas_out[:,4], label=gas_names[4],color='orange')\nplt.annotate(\"O$_2$\", fontsize=18, color='orange',\n            xy=(dist_array[700], gas_out[:, 4][500] + gas_out[:, 4][500] / 100.0),\n            va='bottom', ha='center')\nplt.plot(dist,o2(dist),'--',color='orange')\n# plotting h2\nplt.plot(dist_array,gas_out[:,7], label=gas_names[7],color='k')\nplt.annotate(\"H$_2$\", fontsize=18, color='k',\n            xy=(dist_array[2200], gas_out[:, 7][2200] + gas_out[:, 7][2200] / 100.0),\n            va='bottom', ha='center')\nplt.plot(dist,h2(dist),'--',color='k')\n# plotting co\nplt.plot(dist_array,gas_out[:,8], label=gas_names[8],color='limegreen')\nplt.annotate(\"CO\", fontsize=18, color='limegreen',\n            xy=(dist_array[1800], gas_out[:, 8][1800] + gas_out[:, 8][1800] / 100.0),\n            va='bottom', ha='center')\nplt.plot(dist,co(dist),'--',color='limegreen')\n# plotting h2o\nplt.plot(dist_array,gas_out[:,6], label=gas_names[6],color='dodgerblue')\nplt.annotate(\"H$_2$O\", fontsize=18, color='dodgerblue',\n            xy=(dist_array[2200], gas_out[:, 6][2200] -.01),\n            va='bottom', ha='center')\nplt.plot(dist,h2o(dist),'--',color='dodgerblue')\n# plotting co2\nplt.plot(dist_array,gas_out[:,5], label=gas_names[5],color='blue')\nplt.annotate(\"CO$_2$\", fontsize=18, color='blue',\n            xy=(dist_array[1400], .009),\n            va='bottom', ha='center')\nplt.plot(dist,co2(dist),'--',color='blue')\n\nplt.plot([dist_array[on_catalyst], dist_array[on_catalyst]], [0, 0.1], linestyle=':', color='xkcd:grey')\nplt.plot([dist_array[off_catalyst], dist_array[off_catalyst]], [0, 0.1], linestyle=':', color='xkcd:grey')\nplt.annotate(\"catalyst\", fontsize=18, xy=(dist_array[1500], 0.095), va='center', ha='center')\n\nplt.ylabel('Flow (mol/min)', fontsize=22)\nplt.xlabel('Position (mm)', fontsize=22)\nplt.ylim((0,0.1))\nplt.xticks(fontsize=18)\nplt.yticks(fontsize=18)\nplt.xticks(np.arange(6,26,2))\n\nplt.xlim((5,25))  # cutting off where the horn paper cuts off the plots\nplt.savefig('./paperplots/all_compare.pdf',bbox_inches='tight',dpi=300)\n\nplt.clf()\n\n\nfig, axs = plt.subplots(3, 1)\n\n# plotting ch4\naxs[0].plot(dist_array,gas_out[:,3], label=gas_names[3],color='g')\naxs[0].annotate(\"CH$_4$\", fontsize=18, color='g',\n            xy=(dist_array[700], gas_out[:, 3][500] + gas_out[:, 3][500] / 100.0),\n            va='bottom', ha='center')\naxs[0].plot(dist,ch4(dist),'--',color='g')\n# plotting o2\naxs[0].plot(dist_array,gas_out[:,4], label=gas_names[4],color='orange')\naxs[0].annotate(\"O$_2$\", fontsize=18, color='orange',\n            xy=(dist_array[700], gas_out[:, 4][500] + gas_out[:, 4][500] / 100.0),\n            va='bottom', ha='center')\naxs[0].plot(dist,o2(dist),'--',color='orange')\n\naxs[0].plot([dist_array[on_catalyst], dist_array[on_catalyst]], [0, 0.1], linestyle=':', color='xkcd:grey')\naxs[0].plot([dist_array[off_catalyst], dist_array[off_catalyst]], [0, 0.1], linestyle=':', color='xkcd:grey')\naxs[0].annotate(\"catalyst\", fontsize=18, xy=(dist_array[1500], 0.095), va='center', ha='center')\n\naxs[0].set_ylabel('Flow (mol/min)', fontsize=22)\naxs[0].set_ylim((0,0.1))\nfor item in (axs[0].get_xticklabels()):\n             item.set_fontsize(18)\nfor item in (axs[0].get_yticklabels()):\n             item.set_fontsize(18)\naxs[0].set_xticks(np.arange(6,26,2))\n\nax2 = axs[0].twinx()\nax2.plot(dist,temp(dist), '--', color='r')\nax2.plot(dist_array,T_array,color='r')\nax2.annotate(\"T (K)\",fontsize=18, color='r',\n             xy=(dist_array[2300], T_array[2300] -150),\n             va='top', ha='center')\nax2.set_ylim(300, 2000)\nfor item in (ax2.get_yticklabels()):\n             item.set_fontsize(18)\naxs[0].set_xlim((5,25))\n\n# plotting h2\naxs[1].plot(dist_array,gas_out[:,7], label=gas_names[7],color='k')\naxs[1].annotate(\"H$_2$\", fontsize=18, color='k',\n            xy=(dist_array[2200], 0.0575),\n            va='bottom', ha='center')\naxs[1].plot(dist,h2(dist),'--',color='k')\n# plotting co\naxs[1].plot(dist_array,gas_out[:,8], label=gas_names[8],color='limegreen')\naxs[1].annotate(\"CO\", fontsize=18, color='limegreen',\n            xy=(dist_array[1800], gas_out[:, 8][1800] + gas_out[:, 8][1800] / 100.0 + 0.005),\n            va='bottom', ha='center')\naxs[1].plot(dist,co(dist),'--',color='limegreen')\n\naxs[1].plot([dist_array[on_catalyst], dist_array[on_catalyst]], [0, 0.1], linestyle=':', color='xkcd:grey')\naxs[1].plot([dist_array[off_catalyst], dist_array[off_catalyst]], [0, 0.1], linestyle=':', color='xkcd:grey')\n\naxs[1].set_ylabel('Flow (mol/min)', fontsize=22)\naxs[1].set_ylim((0,0.1))\nfor item in (axs[1].get_xticklabels()):\n             item.set_fontsize(18)\nfor item in (axs[1].get_yticklabels()):\n             item.set_fontsize(18)\naxs[1].set_xticks(np.arange(6,26,2))\n\naxs[1].set_xlim((5,25))  # cutting off where the horn paper cuts off the plots\n\n# plotting h2o\naxs[2].plot(dist_array,gas_out[:,6], label=gas_names[6],color='dodgerblue')\naxs[2].annotate(\"H$_2$O\", fontsize=18, color='dodgerblue',\n            xy=(dist_array[2200], 0.02),\n            va='bottom', ha='center')\naxs[2].plot(dist,h2o(dist),'--',color='dodgerblue')\n# plotting co2\naxs[2].plot(dist_array,gas_out[:,5], label=gas_names[5],color='blue')\naxs[2].annotate(\"CO$_2$\", fontsize=18, color='blue',\n            xy=(dist_array[1225], .005),\n            va='bottom', ha='center')\naxs[2].plot(dist,co2(dist),'--',color='blue')\n\naxs[2].plot([dist_array[on_catalyst], dist_array[on_catalyst]], [0, 0.1], linestyle=':', color='xkcd:grey')\naxs[2].plot([dist_array[off_catalyst], dist_array[off_catalyst]], [0, 0.1], linestyle=':', color='xkcd:grey')\n\naxs[2].set_ylabel('Flow (mol/min)', fontsize=22)\naxs[2].set_ylim((0,0.1))\nfor item in (axs[2].get_xticklabels()):\n             item.set_fontsize(18)\nfor item in (axs[2].get_yticklabels()):\n             item.set_fontsize(18)\naxs[2].set_xticks(np.arange(6,26,2))\n\naxs[2].set_xlim((5,25))  # cutting off where the horn paper cuts off the plots\n\naxs[2].set_xlabel('Position (mm)', fontsize=22)\nfig.set_figheight(10)\nfig.set_figwidth(7)\nplt.savefig('./paperplots/all_compare_subplots.pdf',bbox_inches='tight',dpi=300)\nplt.clf()\n\n\ndef simulationWorker(ratio):\n    fo2 = 1 / (2. * ratio + 1 + 79 / 21)\n    fch4 = 2 * fo2 * ratio\n    far = 79 * fo2 / 21\n    ratio_in = [fch4, fo2, far]  # mol fractions\n\n    a = monolithFull(gas, surf, t_in, ratio_in)\n    print(\"Finished simulation at a C/O ratio of {:.1f}\".format(ratio))\n    gas_out, surf_out, gas_names, surf_names, dist_array, T_array = a\n    return [ratio, [gas_out, gas_names, dist_array, T_array]]\n\n\nratios = [.6, .7, .8, .9, 1., 1.1, 1.2, 1.3, 1.4, 1.6, 1.8, 2., 2.2, 2.4, 2.6]  # 15 items\ndata = []\nnum_threads = len(ratios)\npool = multiprocessing.Pool(processes=num_threads)\ndata = pool.map(simulationWorker, ratios, 1)\npool.close()\npool.join()\n\nend_temp = []\nmax_temp = []\ndist_max_temp = []\nch4_in = []\nch4_out = []\nch4_conv = []\no2_conv = []\nco_sel = []\nco_out = []\nh2_sel = []\nh2_out = []\nh2o_sel = []\nh2o_out = []\nco2_sel = []\nco2_out = []\nratios_real = []\nfor r in data:\n    for x in range(len(r[1][1])):\n        if r[1][1][x] == 'CH4(2)':\n            ch4_i = r[1][0][0][x]\n            ch4_in.append(ch4_i)\n            ch4_o = r[1][0][-1][x]\n            ch4_out.append(ch4_o)\n            ch4_depletion = ch4_i - ch4_o\n            ch4_conv.append(ch4_depletion / ch4_i)\n        if r[1][1][x] == 'O2(3)':\n            o2_in = r[1][0][0][x]\n            o2_out = r[1][0][-1][x]\n            o2_conv.append((o2_in - o2_out) / o2_in)\n    ratios_real.append(ch4_i / (2 * o2_in))\n    end_temp.append(r[1][3][-1])\n    max_temp.append(max(r[1][3]))\n    dist_max_temp.append(r[1][2][r[1][3].index(max(r[1][3]))])\n\n    for x in range(len(r[1][1])):\n        if r[1][1][x] == 'Ar':\n            ar = r[1][0][-1][x]\n        if r[1][1][x] == 'CO(7)':\n            co_o = r[1][0][-1][x]\n            co_out.append(co_o)\n            co_sel.append(co_o / ch4_depletion)\n        if r[1][1][x] == 'H2O(5)':\n            h2o_o = r[1][0][-1][x]\n            h2o_out.append(h2o_o)\n            h2o_sel.append(h2o_o / (ch4_depletion * 2))\n        if r[1][1][x] == 'H2(6)':\n            h2_o = r[1][0][-1][x]\n            h2_out.append(h2_o)\n            h2_sel.append(h2_o / (ch4_depletion * 2))\n        if r[1][1][x] == 'CO2(4)':\n            co2_o = r[1][0][-1][x]\n            co2_out.append(co2_o)\n            co2_sel.append(co2_o / ch4_depletion)\n\npch4_conv = [x *100 for x in ch4_conv]\npo2_conv = [x * 100 for x in o2_conv]\n# #horn data\no2_horn = [100] * 15\nch4_horn = [100,99,95,88,78,69,62,57,50,44,37,32,27,24,21]\nt_horn_c = [1175,1000,820,790,780,775,770,768,765,760,755,750,740,730,725] #celcius\nt_horn = [x + 275.13 for x in t_horn_c]\n\n\nplt.figure(figsize=(6,5))\nplt.plot(ratios_real, pch4_conv, 'bo-', label='CH4', color='g')\nplt.annotate(\"CH$_4$\", fontsize=18, color='g',xy=(1.6,60), va='top', ha='center')\nplt.plot(ratios_real,ch4_horn, '--', color='g')\nplt.plot(ratios_real, po2_conv, 'bo-', label='O2', color='orange')\nplt.annotate(\"O$_2$\", fontsize=18, color='orange',xy=(1.8,95), va='top', ha='center')\nplt.plot(ratios_real,o2_horn, '--', color='orange')\nplt.yticks(np.arange(0,106,10))\nplt.ylabel('Exit conversion (%)', fontsize=22)\nplt.xlabel('C/O Ratio', fontsize=22)\nplt.xticks(np.arange(.6,2.7,0.4))\nplt.xticks(fontsize=18)\nplt.yticks(fontsize=18)\n\nax2 = plt.twinx()\nax2.plot(ratios_real, end_temp, 'bo-', color='r')\nax2.set_ylim(900, 1900)\nax2.set_yticks(np.arange(900,2200,100))\nfor item in (ax2.get_yticklabels()):\n             item.set_fontsize(13)\nax2.annotate(\"T\",fontsize=18, color='r',\n             xy=(1.3, 1150),\n             va='top', ha='center')\nax2.set_ylabel('Temperature (K)', fontsize=22)\nfor item in (ax2.get_yticklabels()):\n             item.set_fontsize(18)\nax2.plot(ratios_real,t_horn,'--',color='r')\nplt.tight_layout()\nplt.savefig('./paperplots/conversion.pdf', bbox_inches='tight', dpi=300)\nplt.clf()\n\npco_sel = [x *100 for x in co_sel]\nph2_sel = [x * 100 for x in h2_sel]\npco2_sel = [x * 100 for x in co2_sel]\nph2o_sel = [x * 100 for x in h2o_sel]\n\n# horn data\nhorn_co = [88,90,93,94,95,95,94,94,93,92,91,90,89,88,87]\nhorn_h2 = [79,88,95,94,93,92,91,90,89,88,85,84,80,78,76]\nhorn_h2o = [21,12,5,6,7,8,9,10,11,12,15,16,20,22,24]\nhorn_co2 = [12,10,7,6,5,5,6,6,7,8,9,10,11,12,13]\n\nplt.figure(figsize=(6,5))\nplt.plot(ratios_real, pco_sel, 'bo-', label='CO', color='limegreen')\nplt.annotate(\"CO\", fontsize=18, color='limegreen',xy=(1.8,98), va='top', ha='center')\nplt.plot(ratios_real,horn_co,'--',color='limegreen')\nplt.plot(ratios_real, ph2_sel, 'bo-', label='H2', color='k')\nplt.annotate(\"H$_2$\", fontsize=18, color='k',xy=(0.8,75), va='top', ha='center')\nplt.plot(ratios_real, pco2_sel, 'bo-', label='CO2', color='blue')\nplt.plot(ratios_real,horn_h2,'--',color='k')\nplt.annotate(\"CO$_2$\", fontsize=18, color='blue',xy=(1.8,8), va='top', ha='center')\nplt.plot(ratios_real,horn_co2,'--',color='blue')\nplt.plot(ratios_real, ph2o_sel, 'bo-', label='H2O', color='dodgerblue')\nplt.annotate(\"H$_2$O\", fontsize=18, color='dodgerblue',xy=(1.,25), va='top', ha='center')\nplt.ylabel('Exit Selectivity (%)', fontsize=18)\nplt.plot(ratios_real,horn_h2o,'--',color='dodgerblue')\nplt.xlabel('C/O Ratio', fontsize=22)\nplt.xticks(np.arange(.6,2.7,0.4))\nplt.xticks(fontsize=18)\nplt.yticks(fontsize=18)\nplt.yticks(np.arange(0,110,10))\nplt.tight_layout()\nplt.savefig('./paperplots/selectivity_comparison.pdf', bbox_inches='tight', dpi=300)\nplt.clf()\n\n\nplt.figure(figsize=(6,5))\nplt.plot(ratios_real, pco_sel, 'bo-', label='CO', color='limegreen')\nplt.annotate(\"CO\", fontsize=18, color='limegreen',xy=(1.8,98), va='top', ha='center')\nplt.plot(ratios_real,horn_co,'--',color='limegreen')\nplt.plot(ratios_real, ph2_sel, 'bo-', label='H2', color='k')\nplt.annotate(\"H$_2$\", fontsize=18, color='k',xy=(0.8,75), va='top', ha='center')\nplt.plot(ratios_real,horn_h2,'--',color='k')\nplt.ylabel('Exit Selectivity (%)', fontsize=22)\nplt.xlabel('C/O Ratio', fontsize=22)\nplt.xticks(np.arange(.6,2.7,0.2))\nplt.xticks(fontsize=18)\nplt.yticks(fontsize=18)\nplt.yticks(np.arange(10,100,10))\nplt.tight_layout()\nplt.savefig('./paperplots/selectivity_syngas.pdf', bbox_inches='tight', dpi=300)\nplt.clf()\n\n\nplt.figure(figsize=(6,5))\nplt.plot(ratios_real, pco2_sel, 'bo-', label='CO2', color='blue')\nplt.annotate(\"CO$_2$\", fontsize=18, color='blue',xy=(1.8,8), va='top', ha='center')\nplt.plot(ratios_real,horn_co2,'--',color='blue')\nplt.plot(ratios_real, ph2o_sel, 'bo-', label='H2O', color='dodgerblue')\nplt.annotate(\"H$_2$O\", fontsize=18, color='dodgerblue',xy=(1.,25), va='top', ha='center')\nplt.plot(ratios_real,horn_h2o,'--',color='dodgerblue')\nplt.ylabel('Exit Selectivity (%)', fontsize=22)\nplt.xlabel('C/O Ratio', fontsize=22)\nplt.xticks(np.arange(.6,2.7,0.2))\nplt.xticks(fontsize=18)\nplt.yticks(fontsize=18)\nplt.yticks(np.arange(10,100,10))\nplt.tight_layout()\nplt.savefig('./paperplots/selectivity_full.pdf', bbox_inches='tight', dpi=300)\nplt.clf()\n", "meta": {"hexsha": "0eeb991f6752805066de7a1e0b4e56440b817a70", "size": 43253, "ext": "py", "lang": "Python", "max_stars_repo_path": "paperplots.py", "max_stars_repo_name": "mazeau/cov-dep", "max_stars_repo_head_hexsha": "af448268a8dc08a4539dda2eb0dfba96e2f6da03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paperplots.py", "max_issues_repo_name": "mazeau/cov-dep", "max_issues_repo_head_hexsha": "af448268a8dc08a4539dda2eb0dfba96e2f6da03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paperplots.py", "max_forks_repo_name": "mazeau/cov-dep", "max_forks_repo_head_hexsha": "af448268a8dc08a4539dda2eb0dfba96e2f6da03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8110638298, "max_line_length": 129, "alphanum_fraction": 0.5677987654, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 14166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.26894141551050293, "lm_q1q2_score": 0.16542259852581062}}
{"text": "\"\"\"\nThis file provides simple functions to calculate wavelength dependent effects.\n\nThe functions can also be used to estimate the Weak Lensing Channel ghosts as a function\nof spectral type.\n\n:requires: NumPy\n:requires: matplotlib\n:requires: pysynphot\n\n:version: 0.1\n\n:author: Sami-Matias Niemi\n:contact: s.niemi@ucl.ac.uk\n\"\"\"\nimport matplotlib\nmatplotlib.rc('text', usetex=True)\nmatplotlib.rcParams['font.size'] = 17\nmatplotlib.rc('xtick', labelsize=14)\nmatplotlib.rc('axes', linewidth=1.1)\nmatplotlib.rcParams['legend.fontsize'] = 11\nmatplotlib.rcParams['legend.handlelength'] = 3\nmatplotlib.rcParams['xtick.major.size'] = 5\nmatplotlib.rcParams['ytick.major.size'] = 5\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pysynphot as S\n\n\ndef _VISbandpass(scale=0.8, area=10000.):\n    \"\"\"\n    Returns Weak Lensing Channel bandpass objects.\n\n    Sets the primary mirror collecting area to 1m**2. This affects the count rate calcuations.\n\n    :param scale: scale the throughput to EoL situation [default=0.8]\n    :type scale: float\n    :param area: collecting area of the primary mirror [default=10000.]\n    :type area: float\n\n    :return: BoL and EoL bandpass objects\n    \"\"\"\n    data = np.loadtxt('/Users/sammy/EUCLID/throughputs/VIS.txt')\n\n    bp = S.ArrayBandpass(wave=data[:, 0], throughput=data[:, 1], waveunits='angstrom', name='VIS')\n\n    bpEoL = S.ArrayBandpass(wave=data[:, 0].copy(), throughput=data[:, 1].copy()*scale,\n                            waveunits='angstrom', name='VIS EoL')\n\n    #set the primary mirror collecting area to 1m**2, effects the count rate estimates\n    bp.primary_area = area\n    bpEoL.primary_area = area\n\n    return bp, bpEoL\n\n\ndef _VISbandpassGhost(scale=0.8, area=10000.):\n    \"\"\"\n    Returns Weak Lensing Channel ghost objects.\n\n    Sets the primary mirror collecting area to 1m**2. This affects the count rate calcuations.\n\n    :param scale: scale the throughput to EoL situation [default=0.8]\n    :type scale: float\n    :param area: collecting area of the primary mirror [default=10000.]\n    :type area: float\n\n    :return: BoL and EoL bandpass objects\n    \"\"\"\n    data = np.loadtxt('/Users/sammy/EUCLID/throughputs/ghost.txt')\n\n    bp = S.ArrayBandpass(wave=data[:, 0], throughput=data[:, 1], waveunits='angstrom', name='VIS')\n\n    bpEoL = S.ArrayBandpass(wave=data[:, 0].copy(), throughput=data[:, 1].copy()*scale,\n                            waveunits='angstrom', name='VIS EoL')\n\n    #set the primary mirror collecting area to 1m**2, effects the count rate estimates\n    bp.primary_area = area\n    bpEoL.primary_area = area\n\n    return bp, bpEoL\n\n\ndef throughputs(output='throughputs.pdf'):\n    \"\"\"\n    Plot throughputs, compares to HST WFC3 UVIS F600LP\n\n    :param output: name of the output file\n    :type output: str\n\n    :return: None\n    \"\"\"\n    #comparison\n    bp1 = S.ObsBandpass('wfc3,uvis2,f600lp')\n\n    #VIS\n    bp, bpEoL = _VISbandpass()\n\n    #ghost\n    bpG, bpEoLG = _VISbandpassGhost()\n\n    #plot\n    plt.semilogy(bp1.wave/10., bp1.throughput, 'r-', label='WFC3 F600LP')\n    plt.semilogy(bp.wave/10., bp.throughput, 'b-', label='VIS Best Estimate')\n    plt.semilogy(bpEoL.wave/10., bpEoL.throughput, 'g--', label='VIS EoL Req.')\n    plt.semilogy(bpG.wave/10., bpG.throughput, 'm-', label='VIS Ghost')\n    plt.semilogy(bpEoLG.wave/10., bpEoLG.throughput, 'y-.', label='VIS Ghost EoL')\n    plt.xlim(230, 1100)\n    plt.xlabel(r'Wavelength [nm]')\n    plt.ylabel(r'Total System Throughput')\n    plt.legend(shadow=True, fancybox=True, loc='best')\n    plt.savefig(output)\n    plt.close()\n\n\ndef testFlatSpectrum(mag=18):\n    \"\"\"\n    Test the pysynphot flat spectra, how to make flat in lambda and nu.\n\n    :param mag:\n    :return:\n    \"\"\"\n    unitflux1 = S.FlatSpectrum(mag, fluxunits='abmag')                 #F_lam\n    unitflux2 = S.FlatSpectrum(mag, fluxunits='abmag', waveunits='Hz') #F_nu\n\n    #unitflux2.convert(S.units.Angstrom)\n\n    plt.plot(unitflux1.wave, unitflux1.flux, 'r-')\n    plt.plot(unitflux2.waveunits.ToAngstrom(unitflux2.wave), unitflux2.flux, 'b--')\n    #plt.plot(unitflux2.wave, unitflux2.flux, 'b--')\n\n    plt.xlim(3000, 11000)\n    #plt.ylim(17.5, 18.5)\n    plt.savefig('flatSpectra.pdf')\n    plt.close()\n\n\ndef flatSpectrum(mag=18):\n    unitflux = S.FlatSpectrum(mag, fluxunits='abmag')\n\n    #observing bandpass\n    bp1 = S.ObsBandpass('wfc3,uvis2,f600lp')\n    #VIS\n    bp, bpEoL = _VISbandpass()\n\n    #observations\n    obs1 = S.Observation(unitflux, bp1)\n    obs2 = S.Observation(unitflux, bp)\n    obsEoL = S.Observation(unitflux, bpEoL)\n\n    #converts\n    obs1.convert('counts')\n    obs2.convert('counts')\n    obsEoL.convert('counts')\n\n    print 'Count rates in e/s (WFC3 vs VIS):'\n    print obs1.countrate(range=[3500, 11000]) #source countrate e/s (all counts, no aperture assumed)\n    print obs2.countrate(range=[3500, 11000]) #source countrate e/s (all counts, no aperture assumed)\n    print obsEoL.countrate(range=[3500, 11000]) #source countrate e/s (all counts, no aperture assumed)\n\n    print 'Count rate VIS in-band / total:'\n    print obs2.countrate(range=[5500, 9000]) / obs2.countrate()\n\n    #print 'integrated ?'\n    #print obs1.integrate() #\n    #print obs2.integrate() #\n\n    #bin widths\n    bw1 = np.diff(obs1.binwave)\n    bw2 = np.diff(obs2.binwave)\n\n    #plot\n    plt.title(r'Flat Spectrum $F_{\\lambda}$ 18 mag$_{AB}$ [photons cm$^{-2}$ s$^{-1}$ \\AA$^{-1}$]')\n    plt.plot(obs1.binwave[1:], obs1.binflux[1:]/bw1, 'r-', label='WFC3 F600LP')\n    plt.plot(obs2.binwave[1:], obs2.binflux[1:]/bw2, 'b-', label='VIS Best Estimate')\n    plt.plot(obsEoL.binwave[1:], obsEoL.binflux[1:]/bw2, 'g--', label='VIS EoL Req.')\n    plt.xlim(3000, 11000)\n    plt.xlabel(r'Wavelength [\\AA]')\n    plt.ylabel(r'Counts per Wavelength Unit')\n    plt.legend(shadow=True, fancybox=True)\n    plt.savefig('comparisonFlatspectrum.pdf')\n    plt.close()\n\n\ndef G2star():\n    #object flux\n    G2 = S.FileSpectrum('/Users/sammy/synphot/pickles/dat_uvk/pickles_uk_26.fits')\n\n    #observing bandpass\n    bp1 = S.ObsBandpass('wfc3,uvis2,f600lp')\n    #VIS\n    bp, bpEoL = _VISbandpass()\n\n    #observations\n    obs1 = S.Observation(G2, bp1)\n    obs2 = S.Observation(G2, bp)\n    obsEoL = S.Observation(G2, bpEoL)\n    obs1.convert('counts')\n    obs2.convert('counts')\n    obsEoL.convert('counts')\n\n    print 'effective wavelength [AA]'\n    print obs2.efflam()  #effective wavelength\n\n    print 'Countrate in e/s:'\n    #source countrate e/s (all counts, no aperture assumed)\n    print obs2.countrate(range=[3500, 11000])\n    print obsEoL.countrate(range=[3500, 11000])\n    print obs2.countrate(range=[5500, 9000])\n    print obsEoL.countrate(range=[5500, 9000])\n\n    print 'Count rate VIS in-band / total:'\n    print obs2.countrate(range=[5500, 9000]) / obs2.countrate()\n\n    #bin widths\n    bw1 = np.diff(obs1.binwave)\n    bw2 = np.diff(obs2.binwave)\n\n    #plot\n    plt.title('G2 Star (Pickles\\_uk\\_26)')\n    plt.plot(obs1.binwave[1:], obs1.binflux[1:]/bw1, 'r-', label='WFC3 F600LP')\n    plt.plot(obs2.binwave[1:], obs2.binflux[1:]/bw2, 'b-', label='VIS Best Estimate')\n    plt.plot(obsEoL.binwave[1:], obsEoL.binflux[1:]/bw2, 'g--', label='VIS EoL Req.')\n    plt.xlim(3000, 11000)\n    plt.xlabel(r'Wavelength [\\AA]')\n    plt.ylabel(r'Counts per Wavelength Unit')\n    plt.legend(shadow=True, fancybox=True)\n    plt.savefig('comparisonG2.pdf')\n\n\ndef ghostCalculations(sourceSpectrum, title, output):\n    \"\"\"\n    Weak Lensing Channel Ghost calculations.\n\n    :param sourceSpectrum: pysynphot spectrum object\n    :type sourceSpectrum: object\n    :param title: title of the plot\n    :type title: str\n    :param output: name of the output file\n    :type output: str\n\n    :return: pysynphot observation object for VIS and Ghost\n    :rtype: list of objects\n    \"\"\"\n    bp, bpEoL = _VISbandpass()\n    bpG, bpEoLG = _VISbandpassGhost()\n\n    #BoL, the best estimate\n    obs = S.Observation(sourceSpectrum, bp)\n    obsG = S.Observation(sourceSpectrum, bpG)\n\n    #convert to counts and derive the count rate in e/s\n    obs.convert('counts')\n    obsG.convert('counts')\n    c = obs.countrate(range=[3200, 11500])\n    cG = obsG.countrate(range=[3200, 11500])\n    #c = obs.countrate(binned=False)\n    #cG = obsG.countrate(binned=False)\n\n    print 'effective stimulation in magnitude (AB)'\n    print obs.effstim('abmag'), obsG.effstim('abmag')\n\n    print 'effective wavelength'\n    print obs.efflam(), obs.efflam()\n\n    print 'source vs. ghost count rates [e/s]'\n    print c, cG\n\n    print 'ghost count rate / total count rate = %e' % (cG / c)\n    print 'ghost count rate / total count rate [1750 dilution] = %e' % (cG / c / 1750.)\n\n    #binflux is wavelength bin dependent...\n    bw1 = np.diff(obs.binwave)\n    bw2 = np.diff(obsG.binwave)\n\n    #for a, b in zip(obsG.binwave[1:], bw2):\n    #    print a, b\n\n    y1 = obs.binflux[1:]/bw1\n    y2 = obsG.binflux[1:]/bw2\n\n    scale = np.max(y1)\n\n    #make a plot\n    plt.title(title)\n    plt.semilogy(obs.binwave[1:], y1/scale, 'b-', label='Source')\n    plt.semilogy(obsG.binwave[1:], y2/scale, 'r--', label='Ghost')\n    plt.xlim(3000, 11000)\n    plt.ylim(1e-7, 2.)\n    plt.xlabel(r'Wavelength [\\AA]')\n    plt.ylabel(r'Normalised Counts per Wavelength Unit')\n    plt.legend(shadow=True, fancybox=True, loc='best')\n    plt.savefig(output)\n    plt.close()\n\n    return obs, obsG\n\n\ndef ghostResults():\n    \"\"\"\n    Calculate the VIS channel ghost contribution.\n\n    Synphot table for the Pickles stellar library:\n    http://www.stsci.edu/hst/HST_overview/documents/synphot/AppA_Catalogs5.html\n\n    :return:\n    \"\"\"\n    #G2V\n    print '\\n\\n\\nG2V:'\n    G2 = S.FileSpectrum('/Users/sammy/synphot/pickles/dat_uvk/pickles_uk_26.fits')\n    obsBoL2, obsBoLG2 = ghostCalculations(G2, 'G2V Star (Pickles\\_uk\\_26)', 'G2Ghost.pdf')\n\n    #Flat\n    print '\\n\\n\\nFlat F_lam:'\n    unitflux = S.FlatSpectrum(18.)\n    obsBoL, obsBoLG = ghostCalculations(unitflux,\n                                        r'Flat Spectrum $F_{\\lambda}$ [photons cm$^{-2}$ s$^{-1}$ \\AA$^{-1}$]',\n                                        'FlatGhost.pdf')\n\n    #O5V\n    print '\\n\\n\\nO5V:'\n    O5V = S.FileSpectrum('/Users/sammy/synphot/pickles/dat_uvk/pickles_uk_1.fits')\n    obsBoL2, obsBoLG2 = ghostCalculations(O5V, 'O5V Star (Pickles\\_uk\\_1)', 'O5Ghost.pdf')\n\n    #G2IV\n    print '\\n\\n\\nG2IV:'\n    sp = S.FileSpectrum('/Users/sammy/synphot/pickles/dat_uvk/pickles_uk_54.fits')\n    obsBoL2, obsBoLG2 = ghostCalculations(sp, 'G2IV Star (Pickles\\_uk\\_54)', 'G2IVGhost.pdf')\n\n    #G5III\n    print '\\n\\n\\nG5III:'\n    sp = S.FileSpectrum('/Users/sammy/synphot/pickles/dat_uvk/pickles_uk_73.fits')\n    obsBoL2, obsBoLG2 = ghostCalculations(sp, 'G5III Star (Pickles\\_uk\\_73)', 'G5IIIGhost.pdf')\n\n    #K2I\n    print '\\n\\n\\nK2I:'\n    sp = S.FileSpectrum('/Users/sammy/synphot/pickles/dat_uvk/pickles_uk_128.fits')\n    obsBoL2, obsBoLG2 = ghostCalculations(sp, 'K2I Star (Pickles\\_uk\\_128)', 'K2IGhost.pdf')\n\n\nif __name__ == '__main__':\n    #testFlatSpectrum()\n    #throughputs()\n    #flatSpectrum()\n    #G2star()\n\n    ghostResults()", "meta": {"hexsha": "e02ef0072900dce4955c2829f0bf2990fd44a1a6", "size": 10971, "ext": "py", "lang": "Python", "max_stars_repo_path": "ETC/fluxEstimates.py", "max_stars_repo_name": "Borlaff/EuclidVisibleInstrument", "max_stars_repo_head_hexsha": "73a64ad275054d7b1a26f0fe556eae222b65f613", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2016-12-13T16:58:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-29T05:29:00.000Z", "max_issues_repo_path": "ETC/fluxEstimates.py", "max_issues_repo_name": "Borlaff/EuclidVisibleInstrument", "max_issues_repo_head_hexsha": "73a64ad275054d7b1a26f0fe556eae222b65f613", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ETC/fluxEstimates.py", "max_forks_repo_name": "Borlaff/EuclidVisibleInstrument", "max_forks_repo_head_hexsha": "73a64ad275054d7b1a26f0fe556eae222b65f613", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-07-13T10:01:41.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-28T13:41:47.000Z", "avg_line_length": 31.6167146974, "max_line_length": 111, "alphanum_fraction": 0.6584632212, "include": true, "reason": "import numpy", "num_tokens": 3490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.3208213138121609, "lm_q1q2_score": 0.16542185401402895}}
{"text": "\"\"\"\nItem-based k-NN collaborative filtering.\n\"\"\"\n\nfrom sys import intern\nimport logging\nimport warnings\n\nimport pandas as pd\nimport numpy as np\nimport scipy.sparse as sps\nimport scipy.sparse.linalg as spla\nfrom numba import jit, njit, prange\nfrom numba.typed import List\n\nfrom lenskit import util, matrix, DataWarning\nfrom lenskit.sharing import in_share_context\nfrom lenskit.util.parallel import is_mp_worker\nfrom lenskit.util.accum import kvp_minheap_insert, kvp_minheap_sort\nfrom . import Predictor\n\n_logger = logging.getLogger(__name__)\n_mkl_ops = matrix.mkl_ops()\n_empty_csr = matrix._impl_mod()._empty_csr\n_subset_rows = matrix._impl_mod()._subset_rows\n\nif _mkl_ops is not None:\n    # we have to import LK CFFI utils into this module\n    for lkv in dir(_mkl_ops):\n        if lkv.startswith('_lk_mkl'):\n            globals()[lkv] = getattr(_mkl_ops, lkv)\n\n\ndef _make_blocks(n, size):\n    \"Create blocks for the range 0..n.\"\n    return [(s, min(s + size, n)) for s in range(0, n, size)]\n\n\n@njit(nogil=True)\ndef _count_nbrs(mat: matrix._CSR, thresh: float):\n    \"Count the number of neighbors passing the threshold for each row.\"\n    counts = np.zeros(mat.nrows, dtype=np.int32)\n    cs = mat.colinds\n    vs = mat.values\n    for i in range(mat.nrows):\n        sp, ep = mat.row_extent(i)\n        for j in range(sp, ep):\n            c = cs[j]\n            v = vs[j]\n            if c != i and v >= thresh:\n                counts[i] += 1\n\n    return counts\n\n\n@njit\ndef _insert(dst, used, limits, i, c, v):\n    \"Insert one item into a heap\"\n    sp = dst.rowptrs[i]\n    ep = sp + used[i]\n    ep = kvp_minheap_insert(sp, ep, limits[i], c, v, dst.colinds, dst.values)\n    used[i] = ep - sp\n\n\n@njit(nogil=True)\ndef _copy_nbrs(src: matrix._CSR, dst: matrix._CSR, limits, thresh: float):\n    \"Copy neighbors into the output matrix.\"\n    used = np.zeros(dst.nrows, dtype=np.int32)\n\n    for i in range(src.nrows):\n        sp, ep = src.row_extent(i)\n\n        for j in range(sp, ep):\n            c = src.colinds[j]\n            v = src.values[j]\n            if c != i and v >= thresh:\n                _insert(dst, used, limits, i, c, v)\n\n    return used\n\n\n@njit(nogil=True, parallel=not is_mp_worker())\ndef _sort_nbrs(smat):\n    for i in prange(smat.nrows):\n        sp, ep = smat.row_extent(i)\n        kvp_minheap_sort(sp, ep, smat.colinds, smat.values)\n\n\n@njit(nogil=True)\ndef _make_sim_block(nitems, bsp, bitems, r_sp, r_ep, r_cs, r_vs, min_sim, max_nbrs):\n    # pass 1: compute the size of each row\n    sizes = np.zeros(bitems, np.int32)\n    for i in range(nitems):\n        for j in range(r_sp[i], r_ep[i]):\n            # we accept the neighbor if it passes threshold and isn't a self-similarity\n            r = r_cs[j]\n            if i != bsp + r and r_vs[j] >= min_sim:\n                sizes[r] += 1\n\n    if max_nbrs > 0:\n        for i in range(bitems):\n            if sizes[i] > max_nbrs:\n                sizes[i] = max_nbrs\n\n    # if bnc == 0:\n    #     # empty resulting matrix, oops\n    #     return _empty_csr(bitems, nitems, np.zeros(bitems, np.int32))\n\n    # allocate a matrix\n    block_csr = _empty_csr(bitems, nitems, sizes)\n\n    # pass 2: truncate each row into the matrix\n    eps = block_csr.rowptrs[:-1].copy()\n    for c in range(nitems):\n        for j in range(r_sp[c], r_ep[c]):\n            v = r_vs[j]\n            r = r_cs[j]\n            sp, lep = block_csr.row_extent(r)\n            lim = lep - sp\n            if c != bsp + r and v >= min_sim:\n                eps[r] = kvp_minheap_insert(sp, eps[r], lim, c, v,\n                                            block_csr.colinds, block_csr.values)\n        # we're done!\n    return block_csr\n\n\n@njit(nogil=True)\ndef _mkl_sim_block(block, bsp, bep, rmh, min_sim, max_nbrs, nitems):\n    \"Compute a single block of the similarity matrix\"\n    # assert block.nrows == bep - bsp\n\n    bitems = block.nrows\n    if block.nnz == 0:\n        return _empty_csr(bitems, nitems, np.zeros(bitems, np.int32))\n\n    # create a matrix handle for the subset matrix\n    amh = _mkl_ops._from_csr(block)\n    _lk_mkl_spopt(amh)\n\n    smh = _lk_mkl_spmabt(rmh, amh)\n\n    _lk_mkl_spfree(amh)\n\n    _lk_mkl_sporder(smh)  # for reproducibility\n\n    block = _lk_mkl_spexport_p(smh)\n    bnr = _lk_mkl_spe_nrows(block)\n    bnc = _lk_mkl_spe_ncols(block)\n    # bnr and bnc should be right\n    # assert bnc == bep - bsp\n    # assert bnr == nitems\n\n    r_sp = _lk_mkl_spe_row_sp(block)\n    r_ep = _lk_mkl_spe_row_ep(block)\n    r_cs = _lk_mkl_spe_colinds(block)\n    r_vs = _lk_mkl_spe_values(block)\n\n    block_csr = _make_sim_block(nitems, bsp, bitems, r_sp, r_ep, r_cs, r_vs, min_sim, max_nbrs)\n\n    _lk_mkl_spe_free(block)\n    _lk_mkl_spfree(smh)\n    return block_csr\n\n\n@njit(nogil=True, parallel=not is_mp_worker())\ndef _mkl_sim_blocks(trmat, blocks, ptrs, min_sim, max_nbrs):\n    \"Compute the similarity matrix with blocked MKL calls\"\n    nitems = trmat.nrows\n    nblocks = len(blocks)\n\n    null = _empty_csr(1, 1, np.zeros(1, dtype=np.int32))\n    res = [null for i in range(nblocks)]\n\n    rmat_h = _mkl_ops._from_csr(trmat)\n    _lk_mkl_sporder(rmat_h)\n    _lk_mkl_spopt(rmat_h)\n\n    for bi in prange(nblocks):\n        b = blocks[bi]\n        p = ptrs[bi]\n        bs, be = p\n        bres = _mkl_sim_block(b, bs, be, rmat_h, min_sim, max_nbrs, nitems)\n        res[bi] = bres\n\n    _lk_mkl_spfree(rmat_h)\n\n    return res\n\n\ndef _scipy_sim_block(block, bsp, bep, rmat, min_sim, max_nbrs, nitems):\n    \"Compute a single block of the similarity matrix\"\n    assert block.nrows == bep - bsp\n\n    _logger.debug('processing block %d:%d (%d nnz)', bsp, bep, block.nnz)\n\n    if rmat.nnz == 0:\n        return _empty_csr(block.nrows, nitems, np.zeros(block.nrows, np.int32))\n\n    sims = rmat @ block.to_scipy().transpose()\n    sims = matrix.CSR.from_scipy(sims)\n\n    r_sp = sims.rowptrs[:-1]\n    r_ep = sims.rowptrs[1:]\n    r_cs = sims.colinds\n    r_vs = sims.values\n\n    block_csr = _make_sim_block(nitems, bsp, block.nrows, r_sp, r_ep, r_cs, r_vs, min_sim, max_nbrs)\n    _logger.debug('umm %d %d', block_csr.nrows, block.nrows)\n    assert block_csr.nrows == block.nrows\n    assert block_csr.ncols == nitems\n    _logger.debug('block %d:%d has %d similarities', bsp, bep, block_csr.nnz)\n    _logger.debug('block: %s', matrix.CSR(N=block_csr))\n\n    return block_csr\n\n\n# we compile this in object mode so we can use numba's thread pool with scipy\n@jit(parallel=not is_mp_worker(), forceobj=True)\ndef _scipy_sim_blocks(trmat, blocks, ptrs, min_sim, max_nbrs):\n    \"Compute the similarity matrix with blocked SciPy calls\"\n    nitems, nusers = trmat.shape\n    nblocks = len(blocks)\n\n    null = _empty_csr(1, 1, np.zeros(1, dtype=np.int32))\n    res = [null for i in range(nblocks)]\n\n    for bi in prange(nblocks):\n        b = blocks[bi]\n        bs, be = ptrs[bi]\n        bres = _scipy_sim_block(b, bs, be, trmat, min_sim, max_nbrs, nitems)\n        res[bi] = bres\n        assert bres.nrows == be - bs\n\n    return res\n\n\n@njit(nogil=True)\ndef _predict_weighted_average(model, nitems, nrange, ratings, rated, targets):\n    \"Weighted average prediction function\"\n    min_nbrs, max_nbrs = nrange\n    scores = np.full(nitems, np.nan, dtype=np.float_)\n\n    for i in prange(targets.shape[0]):\n        iidx = targets[i]\n        rptr = model.rowptrs[iidx]\n        rend = model.rowptrs[iidx + 1]\n\n        num = 0\n        denom = 0\n        nnbrs = 0\n\n        for j in range(rptr, rend):\n            nidx = model.colinds[j]\n            if not rated[nidx]:\n                continue\n\n            nnbrs = nnbrs + 1\n            num = num + ratings[nidx] * model.values[j]\n            denom = denom + np.abs(model.values[j])\n\n            if max_nbrs > 0 and nnbrs >= max_nbrs:\n                break\n\n        if nnbrs < min_nbrs:\n            continue\n\n        scores[iidx] = num / denom\n\n    return scores\n\n\n@njit(nogil=True)\ndef _predict_sum(model, nitems, nrange, ratings, rated, targets):\n    \"Sum-of-similarities prediction function\"\n    min_nbrs, max_nbrs = nrange\n    scores = np.full(nitems, np.nan, dtype=np.float_)\n\n    for i in prange(targets.shape[0]):\n        iidx = targets[i]\n        rptr = model.rowptrs[iidx]\n        rend = model.rowptrs[iidx + 1]\n\n        score = 0\n        nnbrs = 0\n\n        for j in range(rptr, rend):\n            nidx = model.colinds[j]\n            if not rated[nidx]:\n                continue\n\n            nnbrs = nnbrs + 1\n            score = score + model.values[j]\n\n            if max_nbrs > 0 and nnbrs >= max_nbrs:\n                break\n\n        if nnbrs < min_nbrs:\n            continue\n\n        scores[iidx] = score\n\n    return scores\n\n\n_predictors = {\n    'weighted-average': _predict_weighted_average,\n    'sum': _predict_sum\n}\n\n\nclass ItemItem(Predictor):\n    \"\"\"\n    Item-item nearest-neighbor collaborative filtering with ratings. This item-item implementation\n    is not terribly configurable; it hard-codes design decisions found to work well in the previous\n    Java-based LensKit code.\n\n    Args:\n        nnbrs(int):\n            the maximum number of neighbors for scoring each item (``None`` for unlimited)\n        min_nbrs(int): the minimum number of neighbors for scoring each item\n        min_sim(double): minimum similarity threshold for considering a neighbor\n        save_nbrs(double):\n            the number of neighbors to save per item in the trained model\n            (``None`` for unlimited)\n        center(bool):\n            whether to normalize (mean-center) rating vectors.  Turn this off when working\n            with unary data and other data types that don't respond well to centering.\n        aggregate:\n            the type of aggregation to do. Can be ``weighted-average`` or ``sum``.\n\n    Attributes:\n        item_index_(pandas.Index): the index of item IDs.\n        item_means_(numpy.ndarray): the mean rating for each known item.\n        item_counts_(numpy.ndarray): the number of saved neighbors for each item.\n        sim_matrix_(matrix.CSR): the similarity matrix.\n        user_index_(pandas.Index): the index of known user IDs for the rating matrix.\n        rating_matrix_(matrix.CSR): the user-item rating matrix for looking up users' ratings.\n    \"\"\"\n    AGG_SUM = intern('sum')\n    AGG_WA = intern('weighted-average')\n    _use_mkl = True\n\n    def __init__(self, nnbrs, min_nbrs=1, min_sim=1.0e-6, save_nbrs=None,\n                 center=True, aggregate='weighted-average'):\n        self.nnbrs = nnbrs\n        if self.nnbrs is not None and self.nnbrs < 1:\n            self.nnbrs = -1\n        self.min_nbrs = min_nbrs\n        if self.min_nbrs is not None and self.min_nbrs < 1:\n            self.min_nbrs = 1\n        self.min_sim = min_sim\n        self.save_nbrs = save_nbrs\n        self.center = center\n        self.aggregate = aggregate\n\n    def fit(self, ratings, **kwargs):\n        \"\"\"\n        Train a model.\n\n        The model-training process depends on ``save_nbrs`` and ``min_sim``, but *not* on other\n        algorithm parameters.\n\n        Args:\n            ratings(pandas.DataFrame):\n                (user,item,rating) data for computing item similarities.\n        \"\"\"\n        # Training proceeds in 2 steps:\n        # 1. Normalize item vectors to be mean-centered and unit-normalized\n        # 2. Compute similarities with pairwise dot products\n        self._timer = util.Stopwatch()\n\n        _logger.debug('[%s] beginning fit, memory use %s', self._timer, util.max_memory())\n\n        init_rmat, users, items = matrix.sparse_ratings(ratings)\n        n_items = len(items)\n        _logger.info('[%s] made sparse matrix for %d items (%d ratings from %d users)',\n                     self._timer, len(items), init_rmat.nnz, len(users))\n        _logger.debug('[%s] made matrix, memory use %s', self._timer, util.max_memory())\n\n        rmat, item_means = self._mean_center(ratings, init_rmat, items)\n        _logger.debug('[%s] centered, memory use %s', self._timer, util.max_memory())\n\n        rmat = self._normalize(rmat)\n        _logger.debug('[%s] normalized, memory use %s', self._timer, util.max_memory())\n\n        _logger.info('[%s] computing similarity matrix', self._timer)\n        smat = self._compute_similarities(rmat)\n        _logger.debug('[%s] computed, memory use %s', self._timer, util.max_memory())\n\n        _logger.info('[%s] got neighborhoods for %d of %d items',\n                     self._timer, np.sum(np.diff(smat.rowptrs) > 0), n_items)\n\n        _logger.info('[%s] computed %d neighbor pairs', self._timer, smat.nnz)\n\n        self.item_index_ = items\n        self.item_means_ = item_means\n        self.item_counts_ = np.diff(smat.rowptrs)\n        self.sim_matrix_ = smat\n        self.user_index_ = users\n        self.rating_matrix_ = init_rmat\n        # create an inverted similarity matrix for efficient scanning\n        self._sim_inv_ = smat.transpose()\n        _logger.info('[%s] transposed matrix for optimization', self._timer)\n        _logger.debug('[%s] done, memory use %s', self._timer, util.max_memory())\n\n        return self\n\n    def _mean_center(self, ratings, rmat, items):\n        if not self.center:\n            return rmat, None\n\n        item_means = ratings.groupby('item').rating.mean()\n        item_means = item_means.reindex(items).values\n        mcvals = rmat.values - item_means[rmat.colinds]\n        nmat = matrix.CSR(rmat.nrows, rmat.ncols, rmat.nnz,\n                          rmat.rowptrs.copy(), rmat.colinds.copy(), mcvals)\n        _logger.info('[%s] computed means for %d items', self._timer, len(item_means))\n        return nmat, item_means\n\n    def _normalize(self, rmat):\n        rmat = rmat.to_scipy()\n        # compute column norms\n        norms = spla.norm(rmat, 2, axis=0)\n        # and multiply by a diagonal to normalize columns\n        recip_norms = norms.copy()\n        is_nz = recip_norms > 0\n        recip_norms[is_nz] = np.reciprocal(recip_norms[is_nz])\n        norm_mat = rmat @ sps.diags(recip_norms)\n        assert norm_mat.shape[1] == rmat.shape[1]\n        # and reset NaN\n        norm_mat.data[np.isnan(norm_mat.data)] = 0\n        _logger.info('[%s] normalized rating matrix columns', self._timer)\n        return matrix.CSR.from_scipy(norm_mat, False)\n\n    def _compute_similarities(self, rmat):\n        trmat = rmat.transpose()\n        nitems = trmat.nrows\n        m_nbrs = self.save_nbrs\n        if m_nbrs is None or m_nbrs < 0:\n            m_nbrs = 0\n\n        bounds = _make_blocks(nitems, 1000)\n        _logger.info('[%s] splitting %d items (%d ratings) into %d blocks',\n                     self._timer, nitems, trmat.nnz, len(bounds))\n        blocks = [trmat.subset_rows(sp, ep) for (sp, ep) in bounds]\n\n        if self._use_mkl and _mkl_ops is not None:\n            _logger.info('[%s] computing similarities with MKL', self._timer)\n            ptrs = List(bounds)\n            nbs = List(b.N for b in blocks)\n            if not nbs:\n                # oops, this is the bad place\n                # in non-JIT node, List doesn't actually make the list\n                nbs = [b.N for b in blocks]\n                ptrs = bounds\n            s_blocks = _mkl_sim_blocks(trmat.N, nbs, ptrs, self.min_sim, m_nbrs)\n        else:\n            s_blocks = _scipy_sim_blocks(trmat.to_scipy(), blocks, bounds, self.min_sim, m_nbrs)\n\n        s_blocks = [matrix.CSR(N=b) for b in s_blocks]\n        nnz = sum(b.nnz for b in s_blocks)\n        tot_rows = sum(b.nrows for b in s_blocks)\n        _logger.info('[%s] computed %d similarities for %d items in %d blocks',\n                     self._timer, nnz, tot_rows, len(s_blocks))\n        row_nnzs = np.concatenate([b.row_nnzs() for b in s_blocks])\n        assert len(row_nnzs) == nitems, \\\n            'only have {} rows for {} items'.format(len(row_nnzs), nitems)\n\n        smat = matrix.CSR.empty((nitems, nitems), row_nnzs, rpdtype=np.int64)\n        start = 0\n        for bi, b in enumerate(s_blocks):\n            bnr = b.nrows\n            end = start + bnr\n            v_sp = smat.rowptrs[start]\n            v_ep = smat.rowptrs[end]\n            _logger.debug('block %d (%d:%d) has %d entries, storing in %d:%d',\n                          bi, start, end, b.nnz, v_sp, v_ep)\n            smat.colinds[v_sp:v_ep] = b.colinds\n            smat.values[v_sp:v_ep] = b.values\n            start = end\n\n        _logger.info('[%s] sorting similarity matrix with %d entries', self._timer, smat.nnz)\n        _sort_nbrs(smat.N)\n\n        return smat\n\n    def predict_for_user(self, user, items, ratings=None):\n        _logger.debug('predicting %d items for user %s', len(items), user)\n        if ratings is None:\n            if user not in self.user_index_:\n                _logger.debug('user %s missing, returning empty predictions', user)\n                return pd.Series(np.nan, index=items)\n            upos = self.user_index_.get_loc(user)\n            ratings = pd.Series(self.rating_matrix_.row_vs(upos),\n                                index=pd.Index(self.item_index_[self.rating_matrix_.row_cs(upos)]))\n\n        if not ratings.index.is_unique:\n            wmsg = 'user {} has duplicate ratings, this is likely to cause problems'.format(user)\n            warnings.warn(wmsg, DataWarning)\n\n        # set up rating array\n        # get rated item positions & limit to in-model items\n        n_items = len(self.item_index_)\n        ri_pos = self.item_index_.get_indexer(ratings.index)\n        m_rates = ratings[ri_pos >= 0]\n        ri_pos = ri_pos[ri_pos >= 0]\n        rate_v = np.full(n_items, np.nan, dtype=np.float_)\n        rated = np.zeros(n_items, dtype='bool')\n        # mean-center the rating array\n        if self.center:\n            rate_v[ri_pos] = m_rates.values - self.item_means_[ri_pos]\n        else:\n            rate_v[ri_pos] = m_rates.values\n        rated[ri_pos] = True\n\n        _logger.debug('user %s: %d of %d rated items in model', user, len(ri_pos), len(ratings))\n        assert np.sum(np.logical_not(np.isnan(rate_v))) == len(ri_pos)\n        assert np.all(np.isnan(rate_v) == np.logical_not(rated))\n\n        # set up item result vector\n        # ipos will be an array of item indices\n        i_pos = self.item_index_.get_indexer(items)\n        i_pos = i_pos[i_pos >= 0]\n        _logger.debug('user %s: %d of %d requested items in model', user, len(i_pos), len(items))\n\n        # now we take a first pass through the data to count _viable_ targets\n        # This computes the number of neighbors (and their weight sum) for\n        # each target item based on the user's ratings, allowing us to fast-path\n        # other computations and avoid as many neighbor truncations as possible\n        i_cts, i_sums, i_nbrs = self._count_viable_targets(i_pos, ri_pos)\n        viable = i_cts >= self.min_nbrs\n        i_pos = i_pos[viable]\n        i_cts = i_cts[viable]\n        i_sums = i_sums[viable]\n        i_nbrs = i_nbrs[viable]\n        _logger.debug('user %s: %d of %d requested items possibly reachable',\n                      user, len(i_pos), len(items))\n\n        # look for some fast paths\n        if self.aggregate == self.AGG_SUM and self.min_sim >= 0:\n            # similarity sums are all we need\n            if self.nnbrs >= 0:\n                fast_mask = i_cts <= self.nnbrs\n                fast_items = i_pos[fast_mask]\n                fast_scores = i_sums[fast_mask]\n                slow_items = i_pos[~fast_mask]\n            else:\n                fast_items = i_pos\n                fast_scores = i_sums\n                slow_items = np.array([], dtype='i4')\n\n            _logger.debug('user %s: using fast-path similarity sum for %d items',\n                          user, len(fast_items))\n\n            if len(slow_items):\n                iscores = _predict_sum(self.sim_matrix_.N, len(self.item_index_),\n                                       (self.min_nbrs, self.nnbrs),\n                                       rate_v, rated, slow_items)\n            else:\n                iscores = np.full(len(self.item_index_), np.nan)\n            iscores[fast_items] = fast_scores\n\n        elif self.aggregate == self.AGG_WA and self.min_nbrs == 1:\n            # fast-path single-neighbor targets - common in sparse data\n            fast_mask = i_cts == 1\n            fast_items = i_pos[fast_mask]\n            fast_scores = rate_v[i_nbrs[fast_mask]]\n            if self.min_sim < 0:\n                fast_scores *= np.sign(i_sums[fast_mask])\n            _logger.debug('user %s: fast-pathed %d scores', user, len(fast_scores))\n\n            slow_items = i_pos[i_cts > 1]\n            iscores = _predict_weighted_average(self.sim_matrix_.N, len(self.item_index_),\n                                                (self.min_nbrs, self.nnbrs),\n                                                rate_v, rated, slow_items)\n            iscores[fast_items] = fast_scores\n        else:\n            # now compute the predictions\n            _logger.debug('user %s: taking the slow path', user)\n            agg = _predictors[self.aggregate]\n            iscores = agg(self.sim_matrix_.N, len(self.item_index_), (self.min_nbrs, self.nnbrs),\n                          rate_v, rated, i_pos)\n\n        if self.center:\n            iscores += self.item_means_\n\n        results = pd.Series(iscores, index=self.item_index_)\n        results = results.reindex(items, fill_value=np.nan)\n\n        _logger.debug('user %s: predicted for %d of %d items',\n                      user, results.notna().sum(), len(items))\n\n        return results\n\n    def _count_viable_targets(self, targets, rated):\n        \"Count upper-bound on possible neighbors for target items and rated items.\"\n        # initialize counts to zero\n        counts = np.zeros(len(self.item_index_), dtype=np.int32)\n        sums = np.zeros(len(self.item_index_))\n        last_nbrs = np.full(len(self.item_index_), -1, 'i4')\n        # count the number of times each item is reachable from the neighborhood\n        for ri in rated:\n            nbrs = self._sim_inv_.row_cs(ri)\n            counts[nbrs] += 1\n            sums[nbrs] += self._sim_inv_.row_vs(ri)\n            last_nbrs[nbrs] = ri\n\n        # we want the reachability counts for the target items\n        return counts[targets], sums[targets], last_nbrs[targets]\n\n    def __getstate__(self):\n        state = dict(self.__dict__)\n        if '_sim_inv_' in state and not in_share_context():\n            del state['_sim_inv_']\n        return state\n\n    def __setstate__(self, state):\n        self.__dict__.update(state)\n        if hasattr(self, 'sim_matrix_') and not hasattr(self, '_sim_inv_'):\n            self._sim_inv_ = self.sim_matrix_.transpose()\n\n    def __str__(self):\n        return 'ItemItem(nnbrs={}, msize={})'.format(self.nnbrs, self.save_nbrs)\n", "meta": {"hexsha": "8a40547d8bb181d41a6c330eaa041385f2bad108", "size": 22517, "ext": "py", "lang": "Python", "max_stars_repo_path": "lenskit/algorithms/item_knn.py", "max_stars_repo_name": "ShwetanshuSingh/lkpy", "max_stars_repo_head_hexsha": "5dbc6e8cedfdaf0e54b4744ba6cd0224cfad07fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lenskit/algorithms/item_knn.py", "max_issues_repo_name": "ShwetanshuSingh/lkpy", "max_issues_repo_head_hexsha": "5dbc6e8cedfdaf0e54b4744ba6cd0224cfad07fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lenskit/algorithms/item_knn.py", "max_forks_repo_name": "ShwetanshuSingh/lkpy", "max_forks_repo_head_hexsha": "5dbc6e8cedfdaf0e54b4744ba6cd0224cfad07fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0849358974, "max_line_length": 100, "alphanum_fraction": 0.6077630235, "include": true, "reason": "import numpy,import scipy,from numba", "num_tokens": 6027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.1654218487450115}}
{"text": "#!/usr/bin/env python\n#    Under the terms of the GNU General Public License as published by\n#    the Free Software Foundation, either version 3 of the License, or\n#    (at your option) any later version.\n# \n#    This program is distributed in the hope that it will be useful,\n#    but WITHOUT ANY WARRANTY; without even the implied warranty of\n#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n#    GNU General Public License for more details.\n#\n#    You should have received a copy of the GNU General Public License\n#    along with this program.  If not, see http://www.gnu.org/licenses/.\n#\n# Renamed to svt to keep separate from the wav2png.py script\n# \n# Based on wav2png.py by Bram de Jong <bram.dejong at domain.com where domain in gmail>\n# From http://freesound.iua.upf.edu/blog/?p=10\n#\n\"\"\"\nsvt.py [options] filename.wav\nThe options the script takes are:\n<ul>\n <li>-a = output waveform image (default input filename + _w.png)</li>\n <li>-s = output spectrogram image (default input filename + _s.png)</li>\n <li>-w = image width in pixels (default 500)</li>\n <li>-h = image height in pixels (default 170)</li>\n <li>-f = fft size, power of 2 (default 2048)</li>\n <li>-m = maximum frequency to draw, in Hz (default 22050)</li>\n <li>-o = 1 if you want to draw the waveform too\n</ul>\n\"\"\"\n \nimport optparse, math, sys\nimport scikits.audiolab as audiolab\nimport ImageFilter, ImageChops, Image, ImageDraw, ImageColor\nimport numpy\n\n#For music visualization, this class is more or less irrelevant.\nclass TestAudioFile(object):\n    \"\"\"A class that mimics audiolab.sndfile but generates noise instead of reading\n    a wave file. Additionally it can be told to have a \"broken\" header and thus crashing\n    in the middle of the file. Also useful for testing ultra-short files of 20 samples.\"\"\"\n\n    def __init__(self, num_frames, has_broken_header=False):\n        self.seekpoint = 0\n        self.num_frames = num_frames\n        self.has_broken_header = has_broken_header\n \n    def seek(self, seekpoint):\n        self.seekpoint = seekpoint\n \n    def get_nframes(self):\n        return self.num_frames\n \n    def get_samplerate(self):\n        return 44100\n \n    def get_channels(self):\n        return 1\n \n    def read_frames(self, frames_to_read):\n        if self.has_broken_header and self.seekpoint + frames_to_read > self.num_frames / 2:\n            raise IOError()\n \n        num_frames_left = self.num_frames - self.seekpoint\n        will_read = num_frames_left if num_frames_left < frames_to_read else frames_to_read\n        self.seekpoint += will_read\n        return numpy.random.random(will_read)*2 - 1 \n \n \nclass AudioProcessor(object):\n    def __init__(self, audio_file, fft_size, channel, window_function=numpy.ones):\n        self.fft_size = fft_size \n        self.window = window_function(self.fft_size)\n        self.audio_file = audio_file\n        self.frames = audio_file.get_nframes()\n        self.samplerate = audio_file.get_samplerate()\n        self.channels = audio_file.get_channels()\n        self.spectrum_range = None\n        self.lower = 100\n        self.higher = 22050\n        self.lower_log = math.log10(self.lower)\n        self.higher_log = math.log10(self.higher)\n        self.clip = lambda val, low, high: min(high, max(low, val))\n        self.channel = channel\n    \n    #returns a number of samples from the audio file. \n    def read(self, start, size, resize_if_less=False):\n        \"\"\" read size samples starting at start, if resize_if_less is True and less than size\n        samples are read, resize the array to size and fill with zeros \"\"\"\n \n        # number of zeros to add to start and end of the buffer\n        add_to_start = 0\n        add_to_end = 0\n \n        if start < 0:\n            # the first FFT window starts centered around zero\n            if size + start <= 0:\n                return numpy.zeros(size) if resize_if_less else numpy.array([])\n            else:\n                self.audio_file.seek(0)\n \n                add_to_start = -start # remember: start is negative!\n                to_read = size + start\n \n                if to_read > self.frames:\n                    add_to_end = to_read - self.frames\n                    to_read = self.frames\n        else:\n            self.audio_file.seek(start)\n \n            to_read = size\n            if start + to_read >= self.frames:\n                to_read = self.frames - start\n                add_to_end = size - to_read\n \n        try:\n            samples = self.audio_file.read_frames(to_read)\n        except IOError:\n            # this can happen for wave files with broken headers...\n            return numpy.zeros(size) if resize_if_less else numpy.zeros(2)\n \n        # select which channel to draw\n        if self.channels > 1:\n            if self.channel==1:\n                samples = samples[:,0]\n            if self.channel==2:\n                samples = samples[:,1]\n \n        if resize_if_less and (add_to_start > 0 or add_to_end > 0):\n            if add_to_start > 0:\n                samples = numpy.concatenate((numpy.zeros(add_to_start), samples), axis=1)\n \n            if add_to_end > 0:\n                samples = numpy.resize(samples, size)\n                samples[size - add_to_end:] = 0\n \n        return samples\n \n    \"\"\"\n    The spectral centroid is a measure used in digital signal processing to characterise\n    a spectrum. It indicates where the \"center of mass\" of the spectrum is. Perceptually,\n    it has a robust connection with the impression of \"brightness\" of a sound. It is calculated\n    as the weighted mean of the frequencies present in the signal, determined using a Fourier\n    transform, with their magnitudes as the wiehgts.\n    The spectral centroid is widely used in digital audio and music processing as an automatic\n    measure of musical timbre. -Wikipedia\n    \n    Probably extremely useful for visualization.\n    \"\"\"\n    def spectral_centroid(self, seek_point, spec_range=120.0):\n        \"\"\" starting at seek_point read fft_size samples, and calculate the spectral centroid \"\"\"\n        \n        samples = self.read(seek_point - self.fft_size/2, self.fft_size, True)\n \n        samples *= self.window\n        fft = numpy.fft.fft(samples)\n        spectrum = numpy.abs(fft[:fft.shape[0] / 2 + 1]) / float(self.fft_size) # normalized abs(FFT) between 0 and 1\n        length = numpy.float64(spectrum.shape[0])\n \n        # scale the db spectrum from [- spec_range db ... 0 db] > [0..1]\n        db_spectrum = ((20*(numpy.log10(spectrum + 1e-30))).clip(-spec_range, 0.0) + spec_range)/spec_range\n \n        energy = spectrum.sum()\n        spectral_centroid = 0\n \n        if energy > 1e-20:\n            # calculate the spectral centroid\n \n            if self.spectrum_range == None:\n                self.spectrum_range = numpy.arange(length)\n \n            spectral_centroid = (spectrum * self.spectrum_range).sum() / (energy * (length - 1)) * self.samplerate * 0.5\n \n            # clip > log10 > scale between 0 and 1\n            spectral_centroid = (math.log10(self.clip(spectral_centroid, self.lower, self.higher)) - self.lower_log) / (self.higher_log - self.lower_log)\n \n        return (spectral_centroid, db_spectrum)\n \n    #Goes through the samples and finds the min and max amplitudes; used to draw the waveform.\n    #This function is probably what I need to use to output amplitudes to a visualizer..\n    def peaks(self, start_seek, end_seek):\n        \"\"\" read all samples between start_seek and end_seek, then find the minimum and maximum peak\n        in that range. Returns that pair in the order they were found. So if min was found first,\n        it returns (min, max) else the other way around. \"\"\"\n \n        # larger blocksizes are faster but take more mem...\n        # Aha, Watson, a clue, a tradeof!\n        block_size = 4096\n \n        max_index = -1\n        max_value = -1\n        min_index = -1\n        min_value = 1\n \n        if end_seek > self.frames:\n            end_seek = self.frames\n \n        if block_size > end_seek - start_seek:\n            block_size = end_seek - start_seek\n \n        if block_size <= 1:\n            samples = self.read(start_seek, 1)\n            return samples[0], samples[0]\n        elif block_size == 2:\n            samples = self.read(start_seek, True)\n            return samples[0], samples[1]\n \n        for i in range(start_seek, end_seek, block_size):\n            samples = self.read(i, block_size)\n \n            local_max_index = numpy.argmax(samples)\n            local_max_value = samples[local_max_index]\n \n            if local_max_value > max_value:\n                max_value = local_max_value\n                max_index = local_max_index\n \n            local_min_index = numpy.argmin(samples)\n            local_min_value = samples[local_min_index]\n \n            if local_min_value < min_value:\n                min_value = local_min_value\n                min_index = local_min_index\n \n        return (min_value, max_value) if min_index < max_index else (max_value, min_value)\n \n#not relevant to visualization\ndef interpolate_colors(colors, flat=False, num_colors=256):\n    \"\"\" given a list of colors, create a larger list of colors interpolating\n    the first one. If flatten is True a list of numers will be returned. If\n    False, a list of (r,g,b) tuples. num_colors is the number of colors wanted\n    in the final list \"\"\"\n \n    palette = []\n \n    for i in range(num_colors):\n        index = (i * (len(colors) - 1))/(num_colors - 1.0)\n        index_int = int(index)\n        alpha = index - float(index_int)\n \n        if alpha > 0:\n            r = (1.0 - alpha) * colors[index_int][0] + alpha * colors[index_int + 1][0]\n            g = (1.0 - alpha) * colors[index_int][1] + alpha * colors[index_int + 1][1]\n            b = (1.0 - alpha) * colors[index_int][2] + alpha * colors[index_int + 1][2]\n        else:\n            r = (1.0 - alpha) * colors[index_int][0]\n            g = (1.0 - alpha) * colors[index_int][1]\n            b = (1.0 - alpha) * colors[index_int][2]\n \n        if flat:\n            palette.extend((int(r), int(g), int(b)))\n        else:\n            palette.append((int(r), int(g), int(b)))\n \n    return palette\n \nclass WaveformImage(object):\n    def __init__(self, image_width, image_height, palette):\n        self.image = Image.new(\"RGB\", (image_width, image_height))\n \n        self.image_width = image_width\n        self.image_height = image_height\n \n        self.draw = ImageDraw.Draw(self.image)\n        self.previous_x, self.previous_y = None, None\n \n        if palette==2:\n\t        colors = [\n\t                    (255,255,255),\n\t                    (255,255,255),\n\t                    (255,255,255),\n\t                    (225,248,255),\n\t                    (210,241,255),\n\t                    (195,232,255),\n\t                    (180,221,255),\n\t                    (165,208,255),\n\t                    (150,193,255),\n\t                    (135,175,255),\n\t                    (120,156,255),\n\t                    (105,134,255),\n\t                    (90,110,255),\n\t                    (75,85,255),\n\t                    (63,60,255),\n\t                    (64,45,255),\n\t                    (66,30,255),\n\t                    (76,0,255),\n\t                    (0,128,13),\n\t                    (8,138,0),\n\t                    (20,143,0),\n\t                    (33,148,0),\n\t                    (46,153,0),\n\t                    (60,158,0),\n\t                    (91,168,0),\n\t                    (108,173,0),\n\t                    (125,179,0),\n\t                    (143,184,0),\n\t                    (162,189,0),\n\t                    (182,194,0),\n\t                    (199,195,0),\n\t                    (204,184,0),\n\t                    (255,230,128),\n\t                    (255,221,119),\n\t                    (255,213,111),\n\t                    (255,203,102),\n\t                    (255,193,94),\n\t                    (255,181,85),\n\t                    (255,169,77),\n\t                    (255,157,68),\n\t                    (255,143,60),\n\t                    (255,129,51),\n\t                    (255,113,43),\n\t                    (255,97,34),\n\t                    (255,81,25),\n\t                    (255,63,17),\n\t                    (255,45,8),\n\t                    (255,26,0)\n\t                 ]\n        elif palette==1:\n\t        colors = [\n\t                    (0, 0, 0),\n\t                    (58/4,68/4,65/4),\n\t                    (80/2,100/2,153/2),\n\t                    (90,180,100),\n\t                    (224,224,44),\n\t                    (255,60,30),\n\t                    (255,255,255)\n\t                 ]\n \n        # this line gets the old \"screaming\" colors back...\n        # colors = [self.color_from_value(value/29.0) for value in range(0,30)]\n \n        self.color_lookup = interpolate_colors(colors)\n        self.pix = self.image.load()\n \n    def color_from_value(self, value):\n        \"\"\" given a value between 0 and 1, return an (r,g,b) tuple \"\"\"\n \n        return ImageColor.getrgb(\"hsl(%d,%d%%,%d%%)\" % (int( (1.0 - value) * 360 ), 80, 50))\n \n    def draw_peaks(self, x, peaks, spectral_centroid):\n        \"\"\" draw 2 peaks at x using the spectral_centroid for color \"\"\"\n \n        y1 = self.image_height * 0.5 - peaks[0] * (self.image_height - 4) * 0.5\n        y2 = self.image_height * 0.5 - peaks[1] * (self.image_height - 4) * 0.5\n \n        line_color = self.color_lookup[int(spectral_centroid*255.0)]\n \n        if self.previous_y != None:\n            self.draw.line([self.previous_x, self.previous_y, x, y1, x, y2], line_color)\n        else:\n            self.draw.line([x, y1, x, y2], line_color)\n \n        self.previous_x, self.previous_y = x, y2\n \n        self.draw_anti_aliased_pixels(x, y1, y2, line_color)\n \n    def draw_anti_aliased_pixels(self, x, y1, y2, color):\n        \"\"\" vertical anti-aliasing at y1 and y2 \"\"\"\n \n        y_max = max(y1, y2)\n        y_max_int = int(y_max)\n        alpha = y_max - y_max_int\n \n        if alpha > 0.0 and alpha < 1.0 and y_max_int + 1 < self.image_height:\n            current_pix = self.pix[x, y_max_int + 1]\n \n            r = int((1-alpha)*current_pix[0] + alpha*color[0])\n            g = int((1-alpha)*current_pix[1] + alpha*color[1])\n            b = int((1-alpha)*current_pix[2] + alpha*color[2])\n \n            self.pix[x, y_max_int + 1] = (r,g,b)\n \n        y_min = min(y1, y2)\n        y_min_int = int(y_min)\n        alpha = 1.0 - (y_min - y_min_int)\n \n        if alpha > 0.0 and alpha < 1.0 and y_min_int - 1 >= 0:\n            current_pix = self.pix[x, y_min_int - 1]\n \n            r = int((1-alpha)*current_pix[0] + alpha*color[0])\n            g = int((1-alpha)*current_pix[1] + alpha*color[1])\n            b = int((1-alpha)*current_pix[2] + alpha*color[2])\n \n            self.pix[x, y_min_int - 1] = (r,g,b)\n \n    def save(self, filename):\n        # draw a zero \"zero\" line\n        a = 25\n        for x in range(self.image_width):\n            self.pix[x, self.image_height/2] = tuple(map(lambda p: p+a, self.pix[x, self.image_height/2]))\n \n        self.image.save(filename)\n \n \nclass SpectrogramImage(object):\n    def __init__(self, image_width, image_height, fft_size, f_max, f_min, nyquist_freq, palette):\n        self.image = Image.new(\"P\", (image_height, image_width))\n \n        self.image_width = image_width\n        self.image_height = image_height\n        self.fft_size = fft_size\n        self.f_max = f_max\n        self.f_min = f_min\n        self.nyquist_freq = nyquist_freq\n        self.palette = palette\n \n        if nyquist_freq<f_max:\n            print \"\\nWarning: The specified maximum frequency to draw (%d Hz) is higher that what the digital file allows, which is %d Hz. The image file will have black areas on top that correspond to empty data.\\n\" % (f_max,nyquist_freq)\n\n        if palette==2:\n\t        colors = [\n\t                    (255,255,255),\n\t                    (255,255,255),\n\t                    (255,255,255),\n\t                    (225,248,255),\n\t                    (210,241,255),\n\t                    (195,232,255),\n\t                    (180,221,255),\n\t                    (165,208,255),\n\t                    (150,193,255),\n\t                    (135,175,255),\n\t                    (120,156,255),\n\t                    (105,134,255),\n\t                    (90,110,255),\n\t                    (75,85,255),\n\t                    (63,60,255),\n\t                    (64,45,255),\n\t                    (66,30,255),\n\t                    (76,0,255),\n\t                    (0,128,13),\n\t                    (8,138,0),\n\t                    (20,143,0),\n\t                    (33,148,0),\n\t                    (46,153,0),\n\t                    (60,158,0),\n\t                    (91,168,0),\n\t                    (108,173,0),\n\t                    (125,179,0),\n\t                    (143,184,0),\n\t                    (162,189,0),\n\t                    (182,194,0),\n\t                    (199,195,0),\n\t                    (204,184,0),\n\t                    (255,230,128),\n\t                    (255,221,119),\n\t                    (255,213,111),\n\t                    (255,203,102),\n\t                    (255,193,94),\n\t                    (255,181,85),\n\t                    (255,169,77),\n\t                    (255,157,68),\n\t                    (255,143,60),\n\t                    (255,129,51),\n\t                    (255,113,43),\n\t                    (255,97,34),\n\t                    (255,81,25),\n\t                    (255,63,17),\n\t                    (255,45,8),\n\t                    (255,26,0)\n\t                 ]\n        elif palette==1:\n\t        colors = [\n\t                    (0, 0, 0),\n\t                    (58/4,68/4,65/4),\n\t                    (80/2,100/2,153/2),\n\t                    (90,180,100),\n\t                    (224,224,44),\n\t                    (255,60,30),\n\t                    (255,255,255)\n\t                 ]\n \n        self.image.putpalette(interpolate_colors(colors, True))\n \n        # generate the lookup which translates y-coordinate to fft-bin\n        self.y_to_bin = []\n        y_min = math.log10(f_min)\n        y_max = math.log10(f_max)\n        for y in range(self.image_height):\n#            log scale\n#            freq = math.pow(10.0, y_min + y / (image_height - 1.0) *(y_max - y_min))\n#            arithmetic scale\n            freq = f_min + y / (image_height - 1.0) *(f_max - f_min)\n#            uses the nyquist frequency to allow files of different sampling rate\n            bin = freq / nyquist_freq * (self.fft_size/2 + 1)\n#            bin = freq / 22050.0 * (self.fft_size/2 + 1)\n \n            if bin < self.fft_size/2:\n                alpha = bin - int(bin)\n \n                self.y_to_bin.append((int(bin), alpha * 255))\n \n        # this is a bit strange, but using image.load()[x,y] = ... is\n        # a lot slower than using image.putadata and then rotating the image\n        # so we store all the pixels in an array and then create the image when saving\n        self.pixels = []\n \n    def draw_spectrum(self, x, spectrum):\n        for (index, alpha) in self.y_to_bin:\n            self.pixels.append( int( ((255.0-alpha) * spectrum[index] + alpha * spectrum[index + 1] )) )\n \n        for y in range(len(self.y_to_bin), self.image_height):\n            self.pixels.append(0)\n \n    def save(self, filename):\n        self.image.putdata(self.pixels)\n        self.image.transpose(Image.ROTATE_90).save(filename)\n \n \ndef create_png(input_filename, output_filename_w, output_filename_s, image_width, image_height, fft_size, f_max, f_min, wavefile, palette, channel):\n    \"\"\"\n    Given command line arguments this basically does everything.\n\n    WHAT I HAVE GATHERED:\n    db_spectrum has the frequencies of the sound file.\n    spectral_centroid tells us what the color of the sound is.\n    peaks tell us what the amplitude of the sound is.\n\n    Should be trivial to adapt this from image output to output\n    to our JavaScript visualizer now.\n    \"\"\"\n    \n    print \"processing file %s:\\n\\t\" % input_file,\n \n    audio_file = audiolab.sndfile(input_filename, 'read')  #opens the wavfile; audio_file is an object now\n \n    samples_per_pixel = audio_file.get_nframes() / float(image_width)\n    nyquist_freq = (audio_file.get_samplerate() / 2) + 0.0\n    \"\"\"\n    Initializes AudioProcessor class, which does FFT analysis and spits \n    out amplitudes and frequencies to the SpectrogramImage and WaveformImage \n    classes below later. For a stereo wav file, this selects a single channel \n    to analyze. We might want to analyze both channels to give more input to\n    the visualizer,though.\n    \"\"\"\n    processor = AudioProcessor(audio_file, fft_size, channel, numpy.hanning)\n \n    if wavefile==1:\n        waveform = WaveformImage(image_width, image_height, palette)\n    spectrogram = SpectrogramImage(image_width, image_height, fft_size, f_max, f_min, nyquist_freq, palette)\n \n    for x in range(image_width):\n        #shows progress\n        if x % (image_width/10) == 0:\n            sys.stdout.write('.')\n            sys.stdout.flush()\n \n        seek_point = int(x * samples_per_pixel)\n        next_seek_point = int((x + 1) * samples_per_pixel)\n        \n        (spectral_centroid, db_spectrum) = processor.spectral_centroid(seek_point)\n        \n        #let's have a look at the spectral centroid and the db_spectrum\n        #print \"Spectral Centroid:\" + str(spectral_centroid)\n        #print \"DB Spectrum:\" + str(db_spectrum)\n        \n        if wavefile==1:\n            #aha! The peaks and spectral centroid make up the waveform.\n            #Since the spectral centroid indicates timbre (often referred to as color),\n            #it's probably what colors the waveform.\n            peaks = processor.peaks(seek_point, next_seek_point)\n            #let's have a look at these peaks\n            #print \"Peaks:\" + str(peaks)\n            waveform.draw_peaks(x, peaks, spectral_centroid)\n \n        spectrogram.draw_spectrum(x, db_spectrum)\n \n    if wavefile==1:\n        waveform.save(output_filename_w)\n    spectrogram.save(output_filename_s)\n \n    print \" done\"\n\n\ndef processWav(filename, channel):\n    \"\"\"\n    filename: path to a wav file\n    Channel: 1 for left, 2 for right\n    Returns centroids, frequencies, volumes\n    \"\"\"\n    #open file\n    audio_file = audiolab.sndfile(filename, 'read')\n    #should be length of audiofile in seconds * 60. will fix this later\n    \n    import contextlib\n    import wave\n    with contextlib.closing(wave.open(filename, 'r')) as f:\n        frames = f.getnframes()\n        rate = f.getframerate()\n        duration = frames / float(rate)\n    duration *= 30 #30 data points for every second of audio yay\n    duration = int(duration) #can only return an integer number of frames so yeah\n    #print duration\n    #Not really samples per pixel but I'll let that slide\n    samples_per_pixel = audio_file.get_nframes() / float(duration)\n    #some rule says this frequency has to be half of the sample rate\n    nyquist_freq = (audio_file.get_samplerate() / 2) + 0.0\n    #fft_size stays 2048; smaller size == more efficient, fewer frequency samples\n    processor = AudioProcessor(audio_file, 2048, channel, numpy.hanning)\n    \n    centroids = []\n    frequencies = []\n    volumes = []\n\n    for x in range(duration):\n        seek_point = int(x * samples_per_pixel)\n        next_seek_point = int((x + 1) * samples_per_pixel)\n        (spectral_centroid, db_spectrum) = processor.spectral_centroid(seek_point)\n        peaks = processor.peaks(seek_point, next_seek_point)\n        \n        centroids.append(spectral_centroid)\n        frequencies.append(db_spectrum)\n        volumes.append(peaks)\n    #print \"Centroids:\" + str(centroids)\n    #print \"Frequencies:\" + str(frequencies)\n    #print \"Volumes:\" + str(volumes)\n    \n    #convert volumes[] from peaks to actual volumes\n    for i in range(len(volumes)):\n        volumes[i] = abs(volumes[i][0]) + abs(volumes[i][1])\n    #round frequencies to save resources\n    for i in range(len(frequencies)):\n        for j in range(len(frequencies[i])):\n            frequencies[i][j] = round(frequencies[i][j], 4)\n    return centroids, frequencies, volumes\n", "meta": {"hexsha": "a480da5ede330e4c5ffa4fa567c728e4ac607d87", "size": 23899, "ext": "py", "lang": "Python", "max_stars_repo_path": "speech/svt.py", "max_stars_repo_name": "darylsew/audiolearn", "max_stars_repo_head_hexsha": "5994f5df14285f03059614b6fead7234ea46f613", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2015-08-03T18:34:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-18T02:00:58.000Z", "max_issues_repo_path": "speech/svt.py", "max_issues_repo_name": "darylsew/audiolearn", "max_issues_repo_head_hexsha": "5994f5df14285f03059614b6fead7234ea46f613", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "speech/svt.py", "max_forks_repo_name": "darylsew/audiolearn", "max_forks_repo_head_hexsha": "5994f5df14285f03059614b6fead7234ea46f613", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2016-09-17T13:57:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-01T02:14:06.000Z", "avg_line_length": 38.1773162939, "max_line_length": 239, "alphanum_fraction": 0.5619063559, "include": true, "reason": "import numpy", "num_tokens": 5906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.1654218487450115}}
{"text": "\"\"\"\nDraft of a force-field.\nAt this point only a Lennard Jones and a solvation term are implemented.\n\nFunctions assign_atom_types(), assign_params(), get_neighbors() and, \nget_sasa() adapted from\nhttps://github.com/BIOS-IMASL/Azahar/blob/master/Azahar/energy.py\n\"\"\"\n\nimport openbabel as ob\nimport numpy as np\nfrom scipy.spatial.distance import cdist\nfrom scipy.spatial import cKDTree\nfrom numba import jit\nfrom ..utils.geometry import dist\nfrom ..utils.constants import par_s_ij, par_eps_ij\n\n\ndef assign_atom_types(selection='all'):\n    \"\"\"\n    Assign properties at each atom in the selection.\n    \n    Using openbabel-2.4.1\n    read http://openbabel.org/dev-api/classOpenBabel_1_1OBAtom.shtml#ae09ed28481ac044dab3f31c8605b44a9\n    for available functions provided by openbabel to extract atom properties.\n    There is a GetType() function but is more limited.\n    \n    Parameters\n    -----------\n    selection: str\n        Atoms selection\n    \n    Returns\n    --------\n    atom_types: list of tuples, a tuple for each description of an atom\n        [(at_index, elem, heavy_nb, in_ring, is_arom,\n          ring_membership, neighbors)]\n    \"\"\"\n    atom_types = []\n    pdb_string = selection.dump_pdb(filename=False, b_factors=None, to_file=False)\n    mol = ob.OBMol()\n    obconversion = ob.OBConversion()\n    obconversion.SetInAndOutFormats('pdb', 'pdb')\n    obconversion.ReadString(mol, pdb_string)\n    rings = mol.GetSSSR()\n    for at in ob.OBMolAtomIter(mol):\n        ring_member = [ring.IsMember(at) for ring in rings]\n        neighbors = [neighbor.GetAtomicNum()\n                     for neighbor in ob.OBAtomAtomIter(at)]\n        atom_types.append(\n            (at.GetIndex(),\n             at.GetAtomicNum(),\n             at.GetHvyValence(),\n             any(ring_member),\n                at.IsAromatic(),\n                at.MemberOfRingCount(),\n                (neighbors)))\n    return atom_types\n\n\ndef assign_params(atom_types):\n    \"\"\"\n    Assign solvation parameters for each atom.\n    For now, simplified from: DOI: 10.1002/prot.340140112\n    \n    SRA_model = {'atom_types': (Radius, theta)}\n    Radius: Hydrated radius in Angstroms\n    theta: Atomic solvatation parameter (kcal/mol/A²)\n    \n    Parameters\n    ----------\n    atom_types: list of tuples, a tuple for each description of atoms\n        [(at_index, elem, heavy_nb, in_ring, is_arom,\n          ring_membership, neighbors)]\n    \n    Result\n    --------\n    params: Dictionary of atoms index with the corresponding Radius and theta\n        {'atom_index': (Radius, theta)}\n    \"\"\"\n    SRA_model = {'hydroxyl_carboxyl H': (2.85, -0.0487),\n                 'amine_amide H': (2.85, -0.0487),\n                 'thiol H': (2.85, -0.0487),\n                 \n                 'aliphatic CH3': (0.946, 0.0676),\n                 'aliphatic CH2': (0.946, 0.0676),\n                 'aliphatic CH': (0.946, 0.0676),\n                 'aliphatic_alicyclic C': (0.946, 0.0676),\n                 'alicyclic CH2': (0.946, 0.0676),\n                 'alicyclic CH': (0.946, 0.0676),\n                 'aromatic CH': (0.946, 0.0676),\n                 'aromatic C': (0.946, 0.0676),\n                 'aromatic C of fused ring': (0.946, 0.0676),\n                 'aromatic CH of fused ring': (0.946, 0.0676),\n                 'carbonyl_carboxylic C': (0.946, 0.0676),\n                 \n                 'N primary amine': (4.10, -0.0225),\n                 'N secondary amine': (4.10, -0.0225),\n                 'N cyclic amine': (4.10, -0.0225),\n                 'aromatic N': (4.10, -0.0225),\n                 'N amide': (4.10, -0.0225),\n                 \n                 'ether_hydroxyl O': (2.83, -0.0282),\n                 'carboxylic O': (2.83, -0.0282),\n                 'carbonyl O': (2.83, -0.0282),\n                 'amide carbonyl O': (2.83, -0.0282),\n                 \n                 'thiol or sulfide S': (7.37, -0.0020)}\n    params = {}\n    for atom in atom_types:\n        at_index, elem, heavy_nb, in_ring, is_arom, ring_membership, neighbors = atom\n        if elem == 1:\n            if (neighbors[0] == 6 or neighbors[0] == 8):\n                params[at_index] = SRA_model['hydroxyl_carboxyl H']\n            elif neighbors[0] == 7:\n                params[at_index] = SRA_model['amine_amide H']\n            elif neighbors[0] == 16:\n                params[at_index] = SRA_model['thiol H']\n        elif elem == 6:\n            if neighbors.count(1) == 3:\n                params[at_index] = SRA_model['aliphatic CH3']\n            elif neighbors.count(1) == 2:\n                if in_ring:\n                    params[at_index] = SRA_model['alicyclic CH2']\n                else:\n                    params[at_index] = SRA_model['aliphatic CH2']\n            elif neighbors.count(1) == 1:\n                if in_ring:\n                    params[at_index] = SRA_model['alicyclic CH']\n                else:\n                    params[at_index] = SRA_model['aliphatic CH']\n                if is_arom:\n                    if ring_membership > 1:\n                        params[at_index] = SRA_model['aromatic CH of fused ring']\n                    else:\n                        params[at_index] = SRA_model['aromatic CH']\n            elif neighbors.count(1) == 0:\n                if is_arom:\n                    if ring_membership > 1:\n                        params[at_index] = SRA_model['aromatic C of fused ring']\n                    else:\n                        params[at_index] = SRA_model['aromatic C']\n                else:\n                    params[at_index] = SRA_model['aliphatic_alicyclic C']\n            elif neighbors.count(8) > 1:\n                params[at_index] = SRA_model['carbonyl_carboxylic C']\n        elif elem == 7:\n            if neighbors.count(1) == 2:\n                if is_arom:\n                    params[at_index] = SRA_model['N cyclic amine']\n                else:\n                    params[at_index] = SRA_model['N primary amine']\n            elif neighbors.count(1) == 1:\n                params[at_index] = SRA_model['N secondary amine']\n            elif is_arom:\n                params[at_index] = SRA_model['aromatic N']\n            # elif # N de laamide\n                #params.append(SRA_model['aromatic N'])\n        elif elem == 8:\n            if len(neighbors) == 2:\n                params[at_index] = SRA_model['ether_hydroxyl O']\n            else:\n                params[at_index] = SRA_model['carboxylic O']\n            # C=O\n            # C=O of ester\n            # O of amide\n        if elem == 16:\n            params[at_index] = SRA_model['thiol or sulfide S']\n    return params\n\n\ndef get_neighbors(coord, probe, k, params):\n    \"\"\"\n    Returns list of index of neighbors.\n    \n    TODO: Combine with compute_neighbors()\n    \n    Parameters\n    ----------\n    coord : Array (n,3)\n        Cartesian coordinates\n    probe : float\n        Radius of the solvent\n    k: int\n        Atoms index from which to compute neighbors\n    \"\"\"\n    dist = cdist(coord, coord, metric='euclidean')\n    neighbor_indices = []\n    radius = params[k][0] + probe * 2\n    for key, values in params.items():\n        if dist[key, k] < radius + values[0]:\n            neighbor_indices.append(key)\n    return neighbor_indices\n\n\ndef get_sasa(params, points, selection='all', probe=1.4):\n    \"\"\"\n    Returns the solvent-accessible-surface area and empirical solvation term.\n    \n    Parameters\n    ----------\n    params: dictionary\n        {atom: [atom's radius, atom's energy solvatation]}\n    points: interger\n        Number of points per sphere\n    selection: str\n        Atoms selection\n    probe : float\n        The radius of the solvent\n    \n    Return\n    ------\n    energy: float\n        The energy of solvation from the atoms selection\n    areas: float\n        The total solvent-accessible-surface area from the atoms selection\n    \"\"\"\n    # compute the area each point represents\n    areas = []\n    energies = []\n    coord = selection.coords\n    const = 4.0 *(np.pi/points)\n    for key, values in params.items():\n        # scale the points to the correct radius\n        radius = values[0] + probe\n        points_scaled = (coord[key] + points * radius).reshape(1,-1)\n        # get all the indices of neighbors of the i residue\n        neighbors = get_neighbors(coord, probe, key, params)\n        # compute the distance between points and neighbors\n        d_matrix = cdist(points_scaled, coord[neighbors],\n                         metric='euclidean')\n        # create a matrix and store the vdW radii for each neighbor\n        nb_matrix = np.zeros((len(points_scaled), len(neighbors)))\n        for nb_i, nb in enumerate(neighbors):\n            nb_matrix[:, nb_i] = values[0]\n        # compute the number of buried points, we have to be carefull\n        # because we have counted how many times a point is buried\n        # and we only need how many points are buried\n        buried = np.sum(np.sum(d_matrix < nb_matrix + probe, axis=1) > 0)\n        exposed = len(points_scaled) - buried\n        area_per_atom = const * exposed * radius**2\n        energy_per_atom = area_per_atom * values[1]\n        areas.append(area_per_atom)\n        energies.append(energy_per_atom)\n    return sum(energies), sum(areas)\n\n\ndef compute_neighbors(coords, exclusions, cut_off):\n    \"\"\"\n    Use a KD-tree (from scipy) to compute the neighbors atoms for each atom.\n\n    Parameters\n    ----------\n    coords : array (m, 3)\n        Cartesian coordinates of a molecule\n    exclusions : set of tuples\n        Pairs of atoms excluded from the computation of the neighbors\n    cut_off : float\n        Only pairs of atoms closer than cut_off will be used to compute the\n        neighbors.\n\n    Results\n    -------\n    neighbors: set of tuples\n        Pairs of neighbors atoms within a given \"cut_off\" and excluding\n        \"exclusions\"\n    \"\"\"\n    tree_c = cKDTree(coords)\n    all_pairs = tree_c.query_pairs(cut_off)\n    return all_pairs - exclusions\n\n\ndef LJ(neighbors, xyz, elements):\n    \"\"\"\n    Lennard Jones energy term\n\n    .. math::\n\n    LJ_{ij} = \\\\epsilon \\\\left [ \\\\left (\\\\frac{\\\\sigma_{ij}}{r_{ij}} \\\\right)^{12}\n     - 2 \\\\left (\\\\frac{\\\\sigma_{ij}}{r_{ij}} \\\\right)^{6} \\\\right]\n\n    \\\\sigma_{ij} is the distance at which the potential reaches its minimum\n    \\\\epsilon_{ij} is the depth of the potential well\n    r_{ij} is the distance between the particles\n\n    Parameters\n    ----------\n    neighbors : set of tuples\n        Pairs of neighbors atoms\n    xyz : array (m, 3)\n        Cartesian coordinates of a molecule\n    elements : list of strings\n        list of atoms in the molecule, used has key dictionary in\n        par_s_ij and par_eps_ij\n\n    Results\n    -------\n    E_LJ: float\n        Lennard Jones energy contribution\n    \"\"\"\n\n    E_vdw = 0.\n    for i, j in neighbors:\n        key_ij = elements[i] + elements[j]\n        # use par_vdw without precomputing values\n        #sigma_ij = par_vdw[key_i][0] + par_vdw[key_j][0]\n        #epsilon_ij = (par_vdw[key_i][1] * par_vdw[key_j][1])**0.5\n        # or use precomputed values\n        sigma_ij = par_s_ij[key_ij]\n        epsilon_ij = par_eps_ij[key_ij]\n\n        E_vdw += _LJ(xyz, i, j, sigma_ij, epsilon_ij)\n    return E_vdw\n\n\n# convenient function just to speed up computation by 3x\n@jit\ndef _LJ(xyz, i, j, sigma_ij, epsilon_ij):\n\n    r_ij = dist(xyz[i], xyz[j])\n    C6 = (sigma_ij / r_ij) ** 6\n\n    return epsilon_ij * (C6 * C6 - 2 * C6)\n\n", "meta": {"hexsha": "e7d62532d5cec4193ca5e613e7bfbf7c40cd891f", "size": 11362, "ext": "py", "lang": "Python", "max_stars_repo_path": "bomeba0/energy/ff.py", "max_stars_repo_name": "aloctavodia/bomeba0", "max_stars_repo_head_hexsha": "e212986d8ee60be1da91d63a7a889db14ec851c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bomeba0/energy/ff.py", "max_issues_repo_name": "aloctavodia/bomeba0", "max_issues_repo_head_hexsha": "e212986d8ee60be1da91d63a7a889db14ec851c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2017-06-01T15:46:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T18:28:36.000Z", "max_forks_repo_path": "bomeba0/energy/ff.py", "max_forks_repo_name": "aloctavodia/bomeba0", "max_forks_repo_head_hexsha": "e212986d8ee60be1da91d63a7a889db14ec851c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-09-30T13:26:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:01:18.000Z", "avg_line_length": 34.96, "max_line_length": 102, "alphanum_fraction": 0.5702341137, "include": true, "reason": "import numpy,from scipy,from numba", "num_tokens": 2933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565327, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.1654007513541961}}
{"text": "'''\nLEAKY INTEGRATE AND FIRE NETWORK W. STIMULATION\n----------------------\nRuns a simulation (from 0s to 9s), with a stimulation period from\n3s to 6s. During this period, the current slowly ramps up, mimicking\nthe optogenetic stimulation (or silencing) implemented experimentally\n----------------------\n'''\n\nfrom brian import *\nimport numpy as np\nimport numpy.matlib as ml\nfrom numpy.random import rand as rand\nfrom numpy.random import randn as randn\nimport h5py\nimport os.path\nfrom subprocess import call\nfrom sys import platform\nimport elephant\nfrom neo.core import SpikeTrain\nfrom elephant.conversion import BinnedSpikeTrain\nimport quantities as pq\nfrom scipy import signal\n\nroot_dir = '/home/tpfeffer/neonates/'\n\nfrom make_circuit import make_circuit\n\n\nif __name__ == '__main__':\n\n    #------------------------------------------------------------------------------ \n    # Simulation parameters \n    #------------------------------------------------------------------------------ \n    # Timing \n    runtime  = 9000.0 * ms \n    stim_on  = 3000.0 * ms\n    stim_off = 6000.0 * ms\n    #------------------------------------------------------------------------------ \n    # VERSION 1: Parameters from run_network.py\n    #------------------------------------------------------------------------------ \n    v = 1\n    # Inputs: stimululus, AMPA, NMDA, GABA\n    inputs      = np.array([0.9])\n    AMPA_mods   = np.array([5.1]) \n    NMDA_mods   = np.array([1])\n    GABA_mods   = np.linspace(0.7,6.2,56)\n    ntrls       = 1\n    stim_curr   = 0.2 # max stimulation current\n    stim_frac   = 0.2 # fraciton of stimulated /inhibited neurons \n    #------------------------------------------------------------------------------ \n    # preallocate\n    #resp = np.zeros([len(AMPA_mods), len(NMDA_mods), len(GABA_mods), len(inputs)])\n    #mean_corr = np.zeros([len(AMPA_mods), len(NMDA_mods), len(GABA_mods), len(inputs)])\n    myclock = EventClock(dt=1.0*ms,t=0.0*ms,order=1,makedefaultclock=False)\n    voltage_clock = EventClock(dt=5.0*ms,t=0.0*ms,order=2,makedefaultclock=False)\n    #------------------------------------------------------------------------------ \n    # Run simulation\n    #------------------------------------------------------------------------------ \n\n    if not(os.path.exists('/home/tpfeffer/neonates/proc/v%d' %v)):\n      os.makedirs('/home/tpfeffer/neonates/proc/v%d' %v)\n\n    for itr in range(ntrls):\n      # Loop through exp parameters\n      for igaba in range(0,GABA_mods.size): \n          for iinp in range(0,inputs.size):\n              for iampa in range(0,AMPA_mods.size):\n                  for inmda in range(0,NMDA_mods.size):\n                      for stim_protocol in range(1,3): # 1 = inhibit IN / 2 = excite IN\n\n                        fn = os.path.expanduser(root_dir + 'proc/opto/v%d/neonates_network_opto_iampa%d_inmda%d_gaba%d_inp%d_stim%d_tr%d_v%d_processing.txt') % (v,iampa, inmda, igaba, iinp,stim_protocol,itr,v)\n                        if os.path.isfile(fn)==False:\n                            call(['touch', fn])\n                        else:\n                            continue\n\n                        #  initialize  \n                        defaultclock.reinit(t=0.0*ms)\n                        myclock.reinit(t=0.0*ms)\n\n                        clear(True) \n\n                        print(\"Computing INPUT%d, GABA%d, AMPA%d, trial%d ...\") % (iinp, igaba,iampa,itr)\n\n                        inp = inputs[0]\n                        AMPA_mod = AMPA_mods[iampa]\n                        NMDA_mod = NMDA_mods[inmda]\n                        GABA_mod = GABA_mods[igaba]\n\n                        Dgroups, Dconnections, Dnetfunctions, subgroups = make_circuit(inp,GABA_mod,AMPA_mod,NMDA_mod)\n\n                        # get populations from the integrations circuit\n                        popE = Dgroups['DE']\n                        popI = Dgroups['DI']\n\n                        #------------------------------------------------------------------------------\n                        # Set up external stimulation (optogenetics protocol)\n                        #------------------------------------------------------------------------------\n\n                        if stim_protocol == 1: # inhibit inhibitory cells\n                          stim = np.zeros([len(popI),1000 * int(stim_off-stim_on)])\n                          rand_idx = np.random.choice(np.linspace(0,len(popI)-1,len(popI)),np.int(stim_frac*len(popI)),replace=False)\n                          f = np.vectorize(np.int); rand_idx = f(rand_idx)\n                          stim[rand_idx,:] = np.matlib.repmat(np.linspace(0,-stim_curr,1000 * int(stim_off-stim_on)),np.int(stim_frac*len(popI)),1)\n                        elif stim_protocol == 2: # excite inhibitory cells\n                          stim = np.zeros([len(popI),1000 * int(stim_off-stim_on)])\n                          rand_idx = np.random.choice(np.linspace(0,len(popI)-1,len(popI)),np.int(stim_frac*len(popI)),replace=False)\n                          f = np.vectorize(np.int); rand_idx = f(rand_idx)\n                          stim[rand_idx,:] = np.matlib.repmat(np.linspace(0,stim_curr,1000 * int(stim_off-stim_on)),np.int(stim_frac*len(popI)),1)\n\n                        @network_operation(myclock,stim_protocol)\n\n                        def update_input():\n                          if myclock.t >= stim_on and myclock.t < stim_off:\n                            if stim_protocol == 1: # inhibit inhibitory cells\n                              popI.I = stim[: ,int( (myclock.t - stim_on) / (1 * ms))] * nA\n                            else: # excite inhibitory cells\n                              popI.I = stim[: ,int( (myclock.t - stim_on) / (1 * ms))] * nA\n                          else:\n                            popI.I = 0.0 * nA\n                            popE.I = 0.0 * nA\n\n                        #------------------------------------------------------------------------------\n                        # ---- set initial conditions (random)\n                        popE.gen = popE.gen * (1 + 0.2 * rand(popE.__len__()))\n                        popI.gen = popI.gen * (1 + 0.2 * rand(popI.__len__()))\n                        popE.V = popE.V + rand(popE.__len__()) * 2 * mV\n                        popI.V = popI.V + rand(popI.__len__()) * 2 * mV\n                        #popE.I = 0.0 * nA\n                        #popI.I = 0.0 * nA\n\n                        # record spikes of excitatory/inhibitory neurons\n                        Sp_E = SpikeMonitor(popE, record=True)           \n                        Sp_I = SpikeMonitor(popI, record=True)\n\n                        # record instantaneous excitatory/inhibitory population activity\n                        R_E = PopulationRateMonitor(popE, bin=5*ms)\n                        R_I = PopulationRateMonitor(popI, bin=5*ms)\n\n                        # record voltage\n                        Vm_E = StateMonitor(popE, 'V', record=True, clock=voltage_clock)\n                        Vm_I = StateMonitor(popI, 'V', record=True, clock=voltage_clock)\n\n                        gE = StateMonitor(popE, 'gea', record=True, clock=voltage_clock)\n                        gI = StateMonitor(popE, 'gi', record=True, clock=voltage_clock)\n                        \n                        # record current\n                        I_E = StateMonitor(popE, 'I', record=True, clock=myclock)\n                        I_I = StateMonitor(popI, 'I', record=True, clock=myclock)\n\n                        #------------------------------------------------------------------------------\n                        # Run the simulation\n                        #------------------------------------------------------------------------------\n                        print(\"Running simulation...\")\n                        net = Network(Dgroups.values(),  Dconnections.values(), Dnetfunctions, update_input, Sp_E, Sp_I, R_E, R_I, Vm_E, Vm_I, gE, gI, I_E, I_I)\n                        net.prepare()\n                        net.run(runtime) \n\n                        print(\"Computing power spectra ...\")\n                        LFP = np.abs(np.concatenate([gE.values,gI.values])).sum(axis=0)\n                        \n                        fxx, pxx = signal.welch(LFP,200,window='hann')\n\n                        # convert to array and save output has .h5            \n                        spt_E = []; spt_E_idx = []\n                        spt_I = []; spt_I_idx = []\n\n                        for ineuron in range(0,len(Sp_E.spiketimes)):\n                            spt_E = np.append(spt_E,Sp_E.spiketimes.values()[ineuron], axis=None)\n                            spt_E_idx = np.append(spt_E_idx,ml.repmat(ineuron,1,len(Sp_E.spiketimes.values()[ineuron])), axis=None)\n\n                        for ineuron in range(0,len(Sp_I.spiketimes)):\n                            spt_I = np.append(spt_I,Sp_I.spiketimes.values()[ineuron], axis=None)\n                            spt_I_idx = np.append(spt_I_idx,ml.repmat(ineuron,1,len(Sp_I.spiketimes.values()[ineuron])), axis=None)\n\n                        spt_E = np.vstack((spt_E,spt_E_idx))\n                        spt_I = np.vstack((spt_I,spt_I_idx))\n\n                        # -------------------------------------------\n                        # COMPUTE SPIKE COUNT CORRELATIONS\n                        # -------------------------------------------\n                        print(\"Computing spike count correlations...\")\n                        spikes = dict(); frE = np.zeros([320,3]); frI = np.zeros([80,3])\n\n                        first_spike = 0 # start analysis at t = 0\n                        for ineuron in range(0,320):\n                            spikes[ineuron] = SpikeTrain(spt_E[0][(spt_E[1]==ineuron) & ((spt_E[0]>0) & (spt_E[0]<runtime))]*pq.s, t_start = 0, t_stop = runtime)\n                            frE[ineuron,0] = np.sum((spikes[ineuron]>0) & (spikes[ineuron]<3))\n                            frE[ineuron,1] = np.sum((spikes[ineuron]>3) & (spikes[ineuron]<6))\n                            frE[ineuron,2] = np.sum((spikes[ineuron]>6) & (spikes[ineuron]<9))\n                        for ineuron in range(0,80):\n                            spikes[ineuron+320] = SpikeTrain(spt_I[0][(spt_I[1]==ineuron) & ((spt_I[0]>0) & (spt_I[0]<runtime))]*pq.s, t_start = 0, t_stop = runtime)\n                            frI[ineuron,0] = np.sum((spikes[ineuron+320]>0) & (spikes[ineuron+320]<3))\n                            frI[ineuron,1] = np.sum((spikes[ineuron+320]>3) & (spikes[ineuron+320]<6))\n                            frI[ineuron,2] = np.sum((spikes[ineuron+320]>6) & (spikes[ineuron+320]<9))\n\n                        frE=np.mean(frE,axis=0)/int(runtime)\n                        frI=np.mean(frI,axis=0)/int(runtime)\n\n                        st_baseline = []; st_stim = []; st_post = []\n                        subsamp = 1\n                        matidx = np.triu_indices(len(range(0,len(spikes),subsamp)),1)\n                        for isp in range(0,len(spikes),subsamp):\n                            st_baseline.append(spikes[isp][(spikes[isp]>0) & (spikes[isp]<=3)])\n                            st_stim.append(spikes[isp][(spikes[isp]>3) & (spikes[isp]<=6)])\n                            st_post.append(spikes[isp][(spikes[isp]>6) & (spikes[isp]<=9)])\n\n                        stc=np.zeros([3,1])\n                        sts_corr_baseline=BinnedSpikeTrain(st_baseline, binsize=100*pq.ms)\n                        tmp1=elephant.spike_train_correlation.corrcoef(sts_corr_baseline)\n                        sts_corr_stim=BinnedSpikeTrain(st_stim, binsize=100*pq.ms)\n                        tmp2=elephant.spike_train_correlation.corrcoef(sts_corr_stim)\n                        sts_corr_post=BinnedSpikeTrain(st_post, binsize=100*pq.ms)\n                        tmp3=elephant.spike_train_correlation.corrcoef(sts_corr_post)\n                        \n                        # average correlations across upper triangular part\n                        stc[0] = np.triu(tmp1,1).sum()/((tmp1.shape[0]**2-tmp1.shape[0])/2)\n                        stc[1] = np.triu(tmp2,1).sum()/((tmp2.shape[0]**2-tmp2.shape[0])/2)\n                        stc[2] = np.triu(tmp3,1).sum()/((tmp3.shape[0]**2-tmp3.shape[0])/2)\n\n                        spike_array = np.zeros([400,9000])\n                        if itr==0:\n                          sts_corr_baseline=BinnedSpikeTrain(st_baseline, binsize=1*pq.ms)\n                          spike_array[:,0:3000]=sts_corr_baseline.to_array()[:,0:3000]     \n                          sts_corr_stim=BinnedSpikeTrain(st_stim, binsize=1*pq.ms)\n                          spike_array[:,3000:6000]=sts_corr_stim.to_array()[:,3000:6000]\n                          sts_corr_post=BinnedSpikeTrain(st_post, binsize=1*pq.ms)\n                          spike_array[:,6000:9000]=sts_corr_post.to_array()[:,6000:9000]\n\n                          hf = h5py.File(os.path.expanduser(root_dir + 'proc/opto/v%d/neonates_opto_spikes_iampa%d_inmda%d_gaba%d_inp%d_prot%d_tr%d_v%d.h5') % (v,iampa, inmda, igaba, iinp,stim_protocol,itr,v), 'w')\n                          hf.create_dataset('spike_array', data=spike_array)\n                          hf.close() \n                          \n                        # stE = []; stI = []\n                        # subsamp = 1\n                        # matidx = np.triu_indices(len(range(0,len(spikesE),subsamp)),1)\n                        # for isp in range(0,len(spikesE),subsamp):\n                        #     stE.append(spikesE[isp])\n                        #     stI.append(spikesI[isp])\n\n                        # stsE=BinnedSpikeTrain(stE, binsize=1*pq.ms)\n                        # stsI=BinnedSpikeTrain(stI, binsize=1*pq.ms)\n\n                        # stsE_corr=BinnedSpikeTrain(stE, binsize=10*pq.ms)\n                        # corr=elephant.spike_train_correlation.corrcoef(stsE_corr)\n\n                        # hf = h5py.File(os.path.expanduser(root_dir + 'proc/opto/v%d/neonates_network_opto_spiketrain_iampa%d_inmda%d_gaba%d_inp%d_stim%d_tr%d_v%d.h5') % (v,iampa, inmda, igaba, iinp,stim_protocol,itr,v), 'w')\n                        # hf.create_dataset('spike_train_E', data= stsE.to_array())\n                        # hf.create_dataset('spike_train_I', data= stsI.to_array())\n                        # hf.close() \n\n                        # mean_corr = corr[matidx].mean()\n                        curr = I_I.values\n                        hf = h5py.File(os.path.expanduser(root_dir + 'proc/opto/v%d/neonates_opto_iampa%d_inmda%d_gaba%d_inp%d_prot%d_tr%d_v%d.h5') % (v,iampa, inmda, igaba, iinp,stim_protocol,itr,v), 'w')\n                        # hf.create_dataset('sttc_all', data=sttc_all)\n                        hf.create_dataset('stc', data=stc)\n                        # hf.create_dataset('sttcE', data=sttcE)\n                        # hf.create_dataset('sttcI', data=sttcI)\n                        hf.create_dataset('frE', data=frE)\n                        hf.create_dataset('frI', data=frI)  \n                        hf.create_dataset('pxx', data=pxx)    \n                        hf.create_dataset('fxx', data=fxx) \n                        hf.create_dataset('LFP', data=LFP)   \n                        hf.create_dataset('curr',data=curr)                \n                        hf.close() \n\n\n", "meta": {"hexsha": "4000da78e18d8049935bead8ad8b5256dfd73055", "size": 15262, "ext": "py", "lang": "Python", "max_stars_repo_path": "run_network_opto.py", "max_stars_repo_name": "thmspfffr/neonates", "max_stars_repo_head_hexsha": "0dbe1d11c87e9acceec17f9e745d4c67c1f3c106", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "run_network_opto.py", "max_issues_repo_name": "thmspfffr/neonates", "max_issues_repo_head_hexsha": "0dbe1d11c87e9acceec17f9e745d4c67c1f3c106", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "run_network_opto.py", "max_forks_repo_name": "thmspfffr/neonates", "max_forks_repo_head_hexsha": "0dbe1d11c87e9acceec17f9e745d4c67c1f3c106", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.7360594796, "max_line_length": 226, "alphanum_fraction": 0.4685493382, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 3634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.2942149597859341, "lm_q1q2_score": 0.16540074091706178}}
{"text": "\"\"\"Classes for odorants, mixtures, chemical orders, etc.\"\"\"\n\nimport base64\nimport io\nimport json\nimport re\nimport time\nimport warnings\nfrom collections import OrderedDict\nfrom datetime import datetime\nfrom urllib.parse import quote\n\n\nimport numpy as np\nimport pandas as pd\nimport pubchempy as pcp\nimport requests\nfrom IPython.display import display\nfrom PIL import Image\n\nimport quantities as pq\nfrom pyrfume import load_data, logger, tqdm, trange\nfrom pyrfume.physics import mackay\nfrom quantities.constants.statisticalmechanics import R\nfrom typing import Dict\ntry:\n    from rdkit import Chem\n    from rdkit.Chem import Draw, AllChem, SaltRemover\n    from rdkit import RDLogger\n    rdkit_logger = RDLogger.logger()\n    RDKIT = True\nexcept ImportError:\n    warnings.warn(\n        \"Parts of mordred and/or rdkit could not be imported; try installing rdkit via conda\",\n        UserWarning,\n    )\n    RDKIT = False\n\nROOM_TEMP = (22 + 273.15) * pq.Kelvin\nROOM_PRESSURE = 1 * pq.atm\nGAS_MOLAR_DENSITY = ROOM_PRESSURE / (R * ROOM_TEMP)\n\nODORANTS_BASIC_INFO_PATH = \"molecules/all-cids-properties.csv\"\nODORANT_SOURCES_PATH = \"molecules/all-cids.csv\"\n\nPUBCHEM_KINDS = ['name', 'smiles', 'inchi', 'inchikey', 'formula', 'sdf', None]\n\n\nclass Solution:\n    components: Dict[\"Compound\", pq.quantity.Quantity] = None\n    date_created: datetime = None\n\n    def __init__(self, components: dict, date_created: datetime=None):\n        self.total_volume = 0 * pq.mL\n        assert isinstance(components, dict), \"Components must be a dict\"\n        for component, volume in components.items():\n            assert isinstance(\n                component, (Compound, Solution)\n            ), \"Each component must be a Compound or a Solution\"\n            try:\n                volume = volume.rescale(pq.mL)\n            except ValueError:\n                raise ValueError(\"Components must be provided with volumes\")\n            self.total_volume += volume  # Assume that volume is conserved\n        self.components = components\n        if not date_created:\n            date_created = str(datetime.now())[:-7]\n        self.date_created = date_created if date_created else datetime.now()\n\n    @property\n    def compounds(self):\n        return self._compounds()\n\n    def _compounds(self, result: dict = None):\n        if result is None:\n            result = {}\n        for component, volume in self.components.items():\n            if isinstance(component, Compound):\n                if component in result:\n                    result[component] += volume\n                else:\n                    result[component] = volume\n            else:  # If it is a Solution\n                component._compounds(result=result)\n        return result\n\n    @property\n    def molecules(self):\n        \"\"\"Returns a dictionary with the moles of each Molecule\"\"\"\n        compounds = self.compounds\n        assert all([c.density for c, v in compounds.items() if v and not c.is_solvent]), (\n            \"All non-solvent compounds must have a known density \" \"in order to compute moles\"\n        )\n        assert all([c.molecular_weight for c, v in compounds.items() if v and not c.is_solvent]), (\n            \"All non-solvent compounds must have a known molecular weight \"\n            \"in order to compute moles\"\n        )\n        return {\n            c.molecule: (v * c.molarity).rescale(pq.mol) for c, v in self.compounds.items() if v\n        }\n\n    @property\n    def molarities(self):\n        \"\"\"Returns a dictionary with the molarity of each Molecule\"\"\"\n        return {m: mol / self.total_volume for m, mol in self.molecules.items() if mol}\n\n    @property\n    def mole_fractions(self):\n        \"\"\"Returns a dictionary with the mole fraction of each Molecule\"\"\"\n        molecules = self.molecules\n        assert [moles for molecule, moles in molecules.items()], (\n            \"All compounds must have a known number of moles \" \"in order to compute mole fraction\"\n        )\n        # A Quantities bug prevents me from simply summing molecules.values()\n        total_moles = 0 * pq.mol\n        for moles in molecules.values():\n            total_moles += moles\n        return {molecule: moles / total_moles for molecule, moles in molecules.items()}\n\n    def mole_fraction(self, molecule):\n        return self.mole_fractions[molecule] if molecule in self.mole_fractions else 0\n\n    @property\n    def dilutions(self):\n        return {\n            c.molecule: self.total_volume / c.volume for c in self.compounds if not c.is_solvent\n        }\n\n    @property\n    def partial_pressures(self):\n        \"\"\"Computes partial pressures for each odorant\n        in the mixture using Raoult's law\"\"\"\n        return {\n            m: self.mole_fraction(m) * m.vapor_pressure for m in self.molecules if m.vapor_pressure\n        }\n\n    def partial_pressure(self, molecule):\n        return self.partial_pressures[molecule]\n\n    @property\n    def total_pressure(self):\n        \"\"\"Computes total pressure of the vapor using Dalton's law\"\"\"\n        preferred_units = pq.Pa\n        partial_pressures = [pressure.rescale(preferred_units) for pressure in self.partial_pressures.values()]\n        return preferred_units * np.sum(partial_pressures)\n\n    @property\n    def vapor_concentrations(self):\n        \"\"\"Concentrations of each component in the vapor phase at steady state.\n        Units are fraction of volume. Air is assumed to make up the balance\"\"\"\n        pp = self.partial_pressures\n        result = {}\n        for m, p in pp.items():\n            ratio = (p / pq.atm).simplified\n            assert ratio.units == pq.dimensionless\n            result[m] = float(ratio)\n        return result\n\n    def vapor_concentration(self, molecule):\n        return self.vapor_concentrations[molecule]\n\n    @property\n    def molar_evaporation_rates(self):\n        mf = self.mole_fractions\n        result = {\n            molecule: mole_fraction * molecule.molar_evaporation_rate\n            for molecule, mole_fraction in mf.items()\n        }\n        return result\n\n    def molar_evaporation_rate(self, molecule):\n        return self.molar_evaporation_rates[molecule]\n\n\nclass Molecule:\n    def __init__(self, cid: int, name: str=None, fill: bool=False):\n        self.cid = cid\n\n        if fill:\n            self.fill_details()\n        if name:\n            self.name = name\n\n    # Integer Chemical ID number (CID) from PubChem\n    cid: int = 0\n    # Chemical Abstract Service (CAS) number\n    cas: str = \"\"\n    # Principal name\n    name: str = \"\"\n    # Synonyms\n    synonyms: str = \"\"\n    # IUPAC name (long, unique name)\n    iupac: str = \"\"\n    # Density (pq.g / pq.ml)\n    density: float = None\n    # Vapor pressure (pq.Pa)\n    vapor_pressure: float = None\n    # Molecular weight (pq.g / pq.mol)\n    molecular_weight: float = None\n\n    @property\n    def molarity(self):\n        if not (self.molecular_weight and self.density):\n            result = None\n        else:\n            result = self.density / self.molecular_weight\n            result = result.rescale(pq.mol / pq.L)\n        return result\n\n    @property\n    def molar_evaporation_rate(self):\n        return mackay(self.vapor_pressure)\n\n    def fill_details(self):\n        assert self.cid is not None\n        url_template = (\n            \"https://pubchem.ncbi.nlm.nih.gov/\" \"rest/pug/compound/cid/%d/property/\" \"%s/JSON\"\n        )\n        property_list = [\"MolecularWeight\", \"IsomericSMILES\"]\n        url = url_template % (self.cid, \",\".join(property_list))\n        json_data = url_to_json(url)\n        details = json_data[\"PropertyTable\"][\"Properties\"][0]\n\n        def convert(name):\n            s1 = re.sub(\"(.)([A-Z][a-z]+)\", r\"\\1_\\2\", name)\n            return re.sub(\"([a-z0-9])([A-Z])\", r\"\\1_\\2\", s1).lower()\n\n        for key, value in details.items():\n            if key == \"CID\":\n                assert value == self.cid, \"REST API CID does not match provided CID\"\n            key = convert(key)\n            if key == \"molecular_weight\":\n                value = float(value) * pq.g / pq.mol\n            setattr(self, key, value)\n\n        if not self.name:\n            self.name = self.get_name_from_api()\n\n    def get_name_from_api(self):\n        url_template = \"https://pubchem.ncbi.nlm.nih.gov/\" \"rest/pug/compound/cid/%d/synonyms/JSON\"\n        url = url_template % (self.cid)\n        json_data = url_to_json(url)\n        name = None\n        if json_data:\n            information = json_data[\"InformationList\"][\"Information\"][0]\n            synonyms = information[\"Synonym\"]\n            name = synonyms[0].lower()\n        return name\n\n    def get_cid_from_api(self):\n        url_template = \"https://pubchem.ncbi.nlm.nih.gov/\" \"rest/pug/compound/%s/%s/cids/JSON\"\n        options = [getattr(self, x) for x in (\"cas\", \"name\") if len(getattr(self, x))]\n        cid = None\n        query = self.name\n        for option in options:\n            url = url_template % (option, query)\n            json_data = url_to_json(url)\n        cid = json_data[\"IdentifierList\"][\"CID\"][0]\n        return cid\n\n    def __eq__(self, other):\n        if self.cid:\n            return self.cid == other.cid\n        else:\n            return self.name == self.name\n\n    def __lt__(self, other):\n        if self.cid:\n            return self.cid < other.cid\n        else:\n            return self.name < self.name\n\n    def __hash__(self):\n        return id(self)\n\n    def __repr__(self):\n        if self.cid and self.name:\n            result = \"%d (%s)\" % (self.cid, self.name)\n        elif self.cid:\n            result = \"%d\" % self.cid\n        elif self.name:\n            result = \"%s\" % self.name\n        else:\n            result = \"Unknown\"\n        return result\n\n\nclass Vendor:\n    def __init__(self, name: str, url: str):\n        self.name = name\n        self.url = url\n\n    name: str = \"\"\n    url: str = \"\"\n\n\nclass ChemicalOrder:\n    def __init__(self, molecule: \"Molecule\", vendor: \"Vendor\", part_id: str, purity: float=1, known_impurities: list=None):\n        self.molecule = molecule\n        self.vendor = vendor\n        self.part_id = part_id\n        self.purity = purity\n        self.known_impurities = known_impurities\n\n    # Molecule\n    molecule: Molecule = None\n    # Vendor, e.g. Sigma-Aldrich\n    vendor: Vendor = None\n    # ID number of compound at vendor\n    part_id: str = \"\"\n    # Reported purity as a fraction\n    purity: float = 1\n    # List of known impurities (Molecules)\n    known_impurities: list = None\n\n\nclass Compound:\n    def __init__(\n        self, chemical_order: ChemicalOrder, stock: str=\"\", date_arrived: datetime=None, \n        date_opened: datetime=None, is_solvent: bool=False\n    ):\n\n        self.chemical_order = chemical_order\n        self.stock = stock\n        self.date_arrived = date_arrived if date_arrived else datetime.now\n        self.date_opened = date_opened\n        self.is_solvent = is_solvent\n\n    # ChemicalOrder\n    chemical_order: ChemicalOrder = None\n    # Stock number (supplied by vendor, usually on bottle)\n    stock: str = \"\"\n    # Date arrived at the lab/clinic\n    date_arrived: datetime = None\n    # Date opened\n    date_opened: datetime = None\n    # Is it a solvent?\n    is_solvent: bool = False\n\n    def __getattr__(self, attr):\n        \"\"\"If no attribute is found, try looking up on the\n        ChemicalOrder or the Molecule\"\"\"\n        try:\n            return getattr(self.chemical_order, attr)\n        except AttributeError:\n            return getattr(self.chemical_order.molecule, attr)\n\n\ndef url_to_json(url, verbose=True) -> str:\n    json_data = None\n    response = requests.get(url)\n    if response.status_code == 200:\n        string = response.content.decode(\"utf-8\")\n        json_data = json.loads(string)\n    else:\n        msg = \"HTTP Status Code %d for %s\" % (response.status_code, url)\n        print(msg)\n        if verbose:\n            logger.error(msg)\n    return json_data\n\n\ndef is_kind(identifier: str, kind: str) -> bool:\n    if kind == 'smiles':\n        if RDKIT:\n            rdkit_logger.setLevel(RDLogger.CRITICAL)\n            result = Chem.MolFromSmiles(identifier) is not None\n            rdkit_logger.setLevel(RDLogger.WARNING)\n        else:\n            result = None\n    elif kind == 'inchikey':\n        result = len(identifier) == 27 and identifier[14]=='-' and identifier[25]=='-'\n    elif kind == 'inchi':\n        if RDKIT:\n            result = Chem.inchi.MolFromInchi(identifier, logLevel=None) is not None\n        else:\n            result = None\n    elif kind == 'name':\n        result = True\n    else:\n        result = False\n    return result\n\n    \ndef get_kind(identifier: str):\n    kinds = [kind for kind in PUBCHEM_KINDS if is_kind(identifier, kind)]\n    return kinds[-1]  # Return most sophisticated kind ('name' will always be in the list)\n        \n\ndef deisomerize_smiles(smiles: str) -> str:\n    mol = Chem.MolFromSmiles(smiles)\n    if mol:  # If a mol object was successfully create (i.e. not `None`)\n        smiles = Chem.MolToSmiles(mol, isomericSmiles=False)\n    else:\n        smiles = smiles.replace('@','').replace('@@','').replace('/','').replace('\\\\','')\n    return smiles\n\n\ndef canonical_smiles(smiles: str, kekulize: bool = False) -> str:\n    \"\"\"Use rdkit to convert the `smiles` string to canonical form\"\"\"\n    mol = Chem.MolFromSmiles(smiles)\n    if mol:  # If a mol object was successfully create (i.e. not `None`)\n        if kekulize:\n            Chem.Kekulize(mol)\n        smiles = Chem.MolToSmiles(mol, isomericSmiles=True)\n    else:  # No mol object means the `smiles` string was invalid\n        smiles = \"\"\n    return smiles\n\n\ndef get_cids(\n    identifiers: list,\n    kind: str = None,\n    verbose: bool = True,\n    wait: float = 0,\n    results: dict = None,\n) -> dict:\n    \"\"\"Return CIDs for molecule based on any synonym,\n    including a chemical name or a CAS\"\"\"\n    if isinstance(kind, str):\n        kind = kind.lower()\n    assert kind in PUBCHEM_KINDS\n    if results is None:\n        results = {}\n    p = tqdm(identifiers)\n    for identifier in p:\n        #if not isinstance(identifier, str):\n        #    logger.warning(\"%s is not a string\" % identifier)\n        #    continue\n        p.set_description(str(identifier))\n        cid = get_cid(identifier, kind=kind, verbose=verbose)\n        if not cid:\n            logger.warning(\"Could not find %s\" % identifier)\n        results[identifier] = cid\n        if wait:\n            time.sleep(wait)\n    return results\n\n\ndef get_cid(\n    identifier: str, kind: str = None, verbose: bool = True, fix_smiles_on_error: bool = True, attempt=0\n) -> int:\n    \"\"\"\n    Return data about a molecule from any synonym,\n    including a chemical name or a CAS.\n    \"\"\"\n    if isinstance(identifier, float) and np.isnan(identifier):\n        return 0\n    replace = [('α', 'alpha'), ('β', 'beta'), ('γ', 'gamma'), ('δ', 'delta')]\n    for a, b in replace:\n        identifier = identifier.replace(a, b)\n    if kind is None:\n        kind = get_kind(identifier)\n    else:\n        kind = kind.lower()\n    try:\n        result = pcp.get_cids(identifier, namespace=kind)\n    except pcp.BadRequestError:\n        logger.warning('Request Error for \"%s\"' % identifier)\n        result = []\n    except pcp.PubChemHTTPError as e:\n        if attempt == 0:\n            import time\n            time.sleep(10)\n            return get_cid(identifier,kind,verbose, fix_smiles_on_error, 1)\n        else:\n            raise e\n    if not len(result):\n        cid = 0\n    else:\n        if (len(result) > 1) and verbose:\n            logger.warning(\"Multiple CIDs for %s: %s\" % (identifier, result))\n        cid = result[0]\n    if not cid and kind == \"smiles\" and fix_smiles_on_error:\n        # Retry with canonical SMILES\n        identifier = canonical_smiles(identifier)\n        if identifier:\n            cid = get_cid(identifier, kind=kind, verbose=verbose, fix_smiles_on_error=False)\n    return cid\n\n\ndef from_cids(cids: list, property_list: bool = None) -> list:\n    if property_list is None:\n        property_list = [\"MolecularWeight\", \"IsomericSMILES\", \"IUPACName\"]\n    result = []\n    chunk_size = 100\n    for start in trange(0, len(cids), chunk_size):\n        stop = min(start + chunk_size, len(cids))\n        logger.info(\"Retrieving %d through %d\" % (start, stop - 1))\n        cid_subset = [\n            str(x) for x in [cid for cid in cids[start:stop] if int(cid) > 0 and cid is not None]\n        ]\n        cid_subset = \",\".join(cid_subset)\n        properties_template = (\n            \"https://pubchem.ncbi.nlm.nih.gov/\" \"rest/pug/compound/cid/%s/property/\" \"%s/JSON\"\n        )\n        url = properties_template % (cid_subset, \",\".join(property_list))\n        json_data = url_to_json(url)\n        data = json_data[\"PropertyTable\"][\"Properties\"]\n\n        synonyms_template = (\n            \"https://pubchem.ncbi.nlm.nih.gov/\" \"rest/pug/compound/cid/%s/synonyms/JSON\"\n        )\n        url = synonyms_template % (cid_subset)\n        json_data = url_to_json(url)\n        information = json_data[\"InformationList\"][\"Information\"]\n        for i, d in enumerate(data):\n            try:\n                synonyms = information[i][\"Synonym\"]\n            except KeyError:\n                try:\n                    d[\"name\"] = d[\"IUPACName\"]\n                except KeyError:\n                    d[\"name\"] = \"\"\n            else:\n                d[\"name\"] = synonyms[0].lower()\n        result += data\n    return result\n\n\ndef cids_to_smiles(cids: list) -> dict:\n    \"\"\"Returns an ordered dictionary of SMILES strings with CIDs as keys\"\"\"\n    info = from_cids(cids, property_list=[\"IsomericSMILES\"])\n    smiles = {item[\"CID\"]: item[\"IsomericSMILES\"] for item in info}\n    return smiles\n\n\ndef cids_to_cas(cids: list) -> OrderedDict:\n    result = OrderedDict()\n    chunk_size = 100\n    for start in trange(0, len(cids), chunk_size):\n        stop = min(start + chunk_size, len(cids))\n        # msg = \"Retrieving %d through %d\" % (start, stop-1)\n        cid_subset = [str(x) for x in cids[start:stop]]\n        cid_subset = \",\".join(cid_subset)\n        synonyms_template = (\n            \"https://pubchem.ncbi.nlm.nih.gov/\" \"rest/pug/compound/cid/%s/synonyms/JSON\"\n        )\n        url = synonyms_template % (cid_subset)\n        json_data = url_to_json(url)\n        information = json_data[\"InformationList\"][\"Information\"]\n        for i, info in enumerate(information):\n            cid = info[\"CID\"]\n            try:\n                synonyms = info[\"Synonym\"]\n            except KeyError:\n                result[cid] = []\n            else:\n                result[cid] = cas_from_synonyms(synonyms)\n        result\n    return result\n\n\ndef cas_from_synonyms(synonyms: list) -> list:\n    result = []\n    for s in synonyms:\n        if re.match(r\"^[0-9]+\\-[0-9]+\\-[0-9]+$\", s):\n            result.append(s)\n    return result\n\n\ndef cactus(identifier: str, output: str = \"cas\") -> str:\n    url_template = \"https://cactus.nci.nih.gov/chemical/structure/%s/%s\"\n    identifier = identifier.replace(' ', '%20')\n    url = url_template % (identifier, output)\n    response = requests.get(url)\n    if response.status_code == 200:\n        result = response.content.decode(\"utf-8\")\n    else:\n        logger.error(\"HTTP Status Code %d for %s\" % (response.status_code, url))\n        result = None\n    return result\n\n\ndef cactus_image(smiles: str) -> None:\n    url_template = \"https://cactus.nci.nih.gov/chemical/structure/%s/image\"\n    smiles = smiles.replace(' ', '%20')\n    url = url_template % smiles\n    response = requests.get(url)\n    if response.status_code == 200:\n        image_data = response.content.decode(\"utf-8\")\n        image = Image(image_data)\n        display(image)\n    else:\n        logger.error(\"HTTP Status Code %d for %s\" % (response.status_code, url))\n\n\ndef get_compound_summary(cid: int, heading: str):\n    \"\"\"Get summary info about `heading` from PubChem for the compound\n    given by `cid`.  Example heading: 'Physical Description'\"\"\"\n    url_template = (\n        \"https://pubchem.ncbi.nlm.nih.gov/\" \"rest/pug_view/data/compound/%d/JSON?heading=%s\"\n    )\n    escaped_heading = quote(heading)  # Escape the string\n    url = url_template % (cid, escaped_heading)\n    json_data = url_to_json(url, verbose=False)\n    return json_data\n\n\ndef get_compound_odor(cid, raw=False):\n    info = []\n    for heading in [\"Odor\", \"Physical Description\"]:\n        json_data = get_compound_summary(cid, heading)\n        if raw:\n            info += [] if json_data is None else [json_data]\n        else:\n            info += _parse_odor_info(json_data)\n    return info\n\n\ndef _parse_odor_info(info, odors=None, any_string=False):\n    if odors is None:\n        odors = []\n    if isinstance(info, dict):\n        for key, value in info.items():\n            if key == \"TOCHeading\" and value == \"Odor\":\n                any_string = True\n            if key == \"String\" and (any_string or \"odor\" in value.lower()):\n                odors.append(value)\n            else:\n                _parse_odor_info(value, odors=odors, any_string=any_string)\n    elif isinstance(info, list):\n        for value in info:\n            _parse_odor_info(value, odors=odors, any_string=any_string)\n    return odors\n\n\ndef _parse_other_info(info, records=None):\n    if records is None:\n        records = []\n    if isinstance(info, dict):\n        for key, value in info.items():\n            if key == \"String\":\n                records.append(value)\n            elif key == \"Value\" and \"Number\" in value:\n                records.append(value)\n            else:\n                _parse_other_info(value, records=records)\n    elif isinstance(info, list):\n        for value in info:\n            _parse_other_info(value, records=records)\n    return records\n\n\ndef display_molecules(molecules: pd.DataFrame, no_of_columns=5, figsize=(15, 15)):\n    import matplotlib.pyplot as plt\n    from IPython.display import display\n    fig = plt.figure(figsize=figsize)\n    column = 0\n    for i, (cid, info) in enumerate(molecules.iterrows()):\n        column += 1\n        #  check for end of column and create a new figure\n        if column == no_of_columns+1:\n            fig = plt.figure(figsize=figsize)\n            column = 1\n        fig.add_subplot(1, no_of_columns, column)\n        image = smiles_to_image(info['IsomericSMILES'], png=False)\n        plt.imshow(image)\n        plt.axis('off')\n        plt.title(\"%d: %s\" % (cid, info['name']))\n        \n        \ndef embed_molecules(molecules: pd.DataFrame):\n    import matplotlib.pyplot as plt\n    plt.figure(figsize=(6, 6))\n    ax = plt.gca()\n    embedding = load_data('embedding/pf_umap.pkl')\n    ax = embedding.plot.scatter(x=0, y=1, alpha=0.05, c='k', ax=ax)\n    smiles = molecules['IsomericSMILES']\n    embedding_ = embedding.loc[smiles]\n    embedding_.plot.scatter(x=0, y=1, alpha=1, c='r', s=100, ax=ax)\n    ax.set_xlabel('Dimension 1')\n    ax.set_ylabel('Dimension 2')\n    \n\n\ndef smiles_to_image(smiles, png=True, b64=False, crop=True, padding=10, size=300):\n    \"\"\"\n    png: Whether to convert to .png data (or to leave as a PIL image)\n    b64: Whether to base64 encode (only possible for .png data)\n    \"\"\"\n    buffer = io.BytesIO()\n    mol = Chem.MolFromSmiles(smiles)\n    image = Draw.MolToImage(mol, fitImage=True, size=(size, size))\n    if crop:\n        image = crop_image(image, padding=padding)\n    if png:\n        image.save(buffer, format=\"PNG\")\n        image = buffer.getvalue()\n    if b64:\n        assert png, \"Can only base64 encode PNG data, not a PIL image\"\n        image = base64.b64encode(image).decode(\"utf8\")\n    return image\n\n\ndef smiles_to_mol(smiles: list, max_attempts: int=10, use_random_coords: bool=False, deisomerize=False) -> dict:\n    if deisomerize:\n        f = deisomerize_smiles\n    else:\n        f = lambda x: x\n    mols_raw = [Chem.MolFromSmiles(f(smi)) for smi in smiles]\n    logger.info(\"Computing 3D coordinates...\")\n    s = SaltRemover.SaltRemover()\n    mols = {}\n    n = len(mols_raw)\n    pbar = tqdm(total=n)\n    for i, mol in enumerate(mols_raw):\n        pbar.update()\n        logger.debug(\"Embedding %s\" % smiles[i])\n        try:\n            mol = s.StripMol(mol, dontRemoveEverything=True)\n            mol = Chem.AddHs(mol)\n            AllChem.Compute2DCoords(mol)\n            AllChem.EmbedMolecule(mol, maxAttempts=max_attempts, useRandomCoords=use_random_coords)\n            AllChem.UFFOptimizeMolecule(mol)  # Is this deterministic?\n        except Exception as e:\n            logger.warning(\"Exception for %s: %s\" % (smiles[i], str(e)))\n        else:\n            mols[smiles[i]] = mol\n    logger.info(\"Finished embedding all molecules\")\n    return mols\n\n\ndef crop_image(img, padding=0):\n    \"\"\"Crop white out of a PIL image.\"\"\"\n    as_array = np.array(img)  # N x N x (r,g,b,a)\n    if as_array.shape[2] == 4:\n        as_array[as_array[:, :, 3] == 0] = [255, 255, 255, 255]\n    has_content = np.sum(as_array, axis=2, dtype=np.uint32) != 255 * 4\n    xs, ys = np.nonzero(has_content)\n    x_range = max([min(xs) - padding, 0]), min([max(xs) + padding, as_array.shape[0]])\n    y_range = max([min(ys) - padding, 0]), min([max(ys) + padding, as_array.shape[1]])\n    as_array_cropped = as_array[x_range[0] : x_range[1], y_range[0] : y_range[1], 0:3]\n    img = Image.fromarray(as_array_cropped, mode=\"RGB\")\n    return img\n\n\ndef all_odorants():\n    \"\"\"All CIDs, SMILES, Names, and Molecular Weights found in the\n    file at ODORANTS_BASIC_INFO_PATH\"\"\"\n    df = load_data(ODORANTS_BASIC_INFO_PATH)\n    df = df.sort_index()\n    return df\n\n\ndef all_sources():\n    \"\"\"Whether or not each odorant (by CID) is in each of the data sources\"\"\"\n    df = load_data(ODORANT_SOURCES_PATH)\n    df = df.sort_index()\n    return df\n\n\ndef all_cids():\n    \"\"\"All CIDs found in the file at ODORANTS_BASIC_INFO_PATH\"\"\"\n    df = all_odorants()\n    return list(df.index)\n\n\ndef all_smiles():\n    \"\"\"All SMILES found in the file at ODORANTS_BASIC_INFO_PATH.\n    May contain duplicates (if two CIDs give the same SMILES)\"\"\"\n    df = all_odorants()\n    return list(df[\"SMILES\"])\n\n\nif __name__ == \"__main__\":\n    x = Molecule(325, fill=True)\n    print(x.__dict__)\n", "meta": {"hexsha": "7ce61de2614187ac3e02c462d80f1c2f85f0b7ec", "size": 25939, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyrfume/odorants.py", "max_stars_repo_name": "brilee/pyrfume", "max_stars_repo_head_hexsha": "ae93d320793914c39315dc4f94384f6184254af5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyrfume/odorants.py", "max_issues_repo_name": "brilee/pyrfume", "max_issues_repo_head_hexsha": "ae93d320793914c39315dc4f94384f6184254af5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyrfume/odorants.py", "max_forks_repo_name": "brilee/pyrfume", "max_forks_repo_head_hexsha": "ae93d320793914c39315dc4f94384f6184254af5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7308192458, "max_line_length": 123, "alphanum_fraction": 0.6123983191, "include": true, "reason": "import numpy", "num_tokens": 6489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.1651140786703367}}
{"text": "#  Copyright (C) 2014-2021 Syntrogi Inc dba Intheon. All rights reserved.\n\nfrom pathlib import Path\nimport numpy as np\nimport os\nimport warnings\n\n\ndef parse_headmodel_file(filename):\n    from scipy.io.matlab import loadmat\n    from scipy.sparse import csc_matrix\n    filepath = Path(filename)\n    if not filepath.exists():\n        filepath = Path(os.path.expanduser('~')) / '.stream_viewer' / 'headmodel' / filepath.name\n    HM = loadmat(filepath, squeeze_me=True)\n    leadfield = HM['leadfield']['matrix'][()]\n    sensors = dict()\n    sensors['labels'] = HM['sensors']['labels'][()]\n    sensors['coordinates'] = HM['sensors']['coordinates'][()]\n    laplacian = csc_matrix(HM['laplacian']['matrix'][()])\n\n    meshes = [{'name': _, 'vertices': HM['meshes']['vertices'][ix], 'faces': HM['meshes']['faces'][ix] - 1}\n              for ix, _ in enumerate(HM['meshes']['name'])]\n\n    if HM['atlases'].size == 1:\n        atlases = [{_: HM['atlases'][_][()] for _ in HM['atlases'].dtype.names}]\n        atlases[0]['labeling'] -= 1\n    else:\n        atlases = [{'name': _, 'labeling': HM['atlases']['labeling'][ix] - 1, 'labels': HM['atlases']['labels'][ix]}\n                   for ix, _ in enumerate(HM['atlases']['name'])]\n\n    for atl in atlases:\n        if atl['name'] == 'Desikan–Killiany' and len(atl['labeling']) == 4495:\n            _labels = atl['labels'].tolist()\n\n            atl['labeling'][202] = _labels.index('lingual L.1')  # From 'lingual R.2'\n            switch_lr = [248, 334, 343, 1415, 1503, 1568, 1607, 1657, 1820, 1848, 2520, 2605, 3145, 3189, 3429, 3465,\n                         3499, 3531, 3639, 3689, 3788, 3796, 3870, 3914, 3957, 4029, 4109, 4173, 4333]\n            for v_id in switch_lr:\n                old_roi_spl = _labels[atl['labeling'][v_id]].split(' ')\n                new_roi = old_roi_spl[0] + ' ' + ('L' if old_roi_spl[1][0] == 'R' else 'R') + old_roi_spl[1][1:]\n                atl['labeling'][v_id] = _labels.index(new_roi)\n\n            # Previously known mislabels\n            atl['labeling'][1038] = _labels.index('superiortemporal L.3')  # From middletemporal L.4\n            atl['labeling'][985] = _labels.index('superiortemporal L.3')  # From supramarginal L.10\n            atl['labeling'][1161] = _labels.index('superiortemporal L.4')  # From middletemporal L.6\n            atl['labeling'][1509] = _labels.index('superiortemporal L.6')  # From precentral L.9\n            atl['labeling'][1361] = _labels.index('superiortemporal L.5')  # From precentral L.9\n\n    coords = HM['meta']['coordinates'][()]\n    meta = {'coordinates': {_: coords[_][()] for _ in coords.dtype.names},\n            'system': 'MNI'}\n    del HM\n    return {'leadfield': leadfield, 'sensors': sensors, 'laplacian': laplacian,\n            'meshes': meshes, 'atlases': atlases, 'meta': meta}\n\n\ndef internalize_coordinates(coords, unit, x, y, z):\n    \"\"\"Convert the given coordinates (Nx3 array) into a unified\n    internal coordinate system.\n\n    The internal system is as follows:\n    * unit=meters\n    * x=right\n    * y=front\n    * z=up\n\n    Args:\n        coords: Nx3 array of coordinates to convert\n        unit: the unit of the coordinates, e.g., 'meters', 'millimeters',\n          can also be 'guess'\n        x: orientation of the X axis relative to the head, e.g., 'front'\n        y: orientation of the Y axis relative to the head, e.g., 'left'\n        z: orientation of the Z axis relative to the head, e.g., 'up'\n\n    Returns:\n        coords: the transformed coordinates\n    \"\"\"\n\n    # unit conversion\n    if unit.lower() == 'guess':\n        with warnings.catch_warnings():\n            warnings.simplefilter('ignore')\n            max_coord = np.nanmax(np.abs(coords[:, :2]))\n        if not np.isnan(max_coord):\n            if max_coord < 0.1:\n                unit = 'meters'\n            elif max_coord < 1:\n                unit = 'centimeters'\n            elif max_coord < 10:\n                unit = 'millimeters'\n\n    if unit.lower() in ['millimeters', 'mm']:\n        coords /= 1000.0\n    elif unit.lower() in ['centimeters', 'cm']:\n        coords /= 100.0\n    elif not unit.lower() in ['meters', 'guess']:\n        raise RuntimeError(\"Unsupported unit: %s\" % unit)\n\n    # rotations, etc\n    if x == 'front' and y == 'left' and z == 'up':\n        # +X nose direction\n        # rotate 90 degrees clockwise (looking down on head)\n        coords = np.dot(coords, np.array([[0, 1, 0],\n                                          [-1, 0, 0],\n                                          [0, 0, 1]]))\n    elif x == 'back' and y == 'right' and z == 'up':\n        # -X nose direction\n        coords = np.dot(coords, np.array([[0, -1, 0],\n                                          [1, 0, 0],\n                                          [0, 0, 1]]))\n    elif not (x == 'right' and y == 'front' and z == 'up'):\n        # not +Y nose direction\n        raise RuntimeError(\"Unsupported coordinate system (%s,%s,%s)\" % (x, y,\n                                                                         z))\n    return coords", "meta": {"hexsha": "b462b3f61bdda2a9fbb175d31d8fb9b23a8626d8", "size": 5011, "ext": "py", "lang": "Python", "max_stars_repo_path": "stream_viewer/utils/headmodel.py", "max_stars_repo_name": "intheon/stream_viewer", "max_stars_repo_head_hexsha": "386b9e27d5cd7e66eece0dc2e4977e917ef94877", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-07T11:38:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T09:07:58.000Z", "max_issues_repo_path": "stream_viewer/utils/headmodel.py", "max_issues_repo_name": "intheon/stream_viewer", "max_issues_repo_head_hexsha": "386b9e27d5cd7e66eece0dc2e4977e917ef94877", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stream_viewer/utils/headmodel.py", "max_forks_repo_name": "intheon/stream_viewer", "max_forks_repo_head_hexsha": "386b9e27d5cd7e66eece0dc2e4977e917ef94877", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-23T09:08:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T09:08:06.000Z", "avg_line_length": 42.8290598291, "max_line_length": 117, "alphanum_fraction": 0.5455996807, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.1651140753619383}}
{"text": "\"\"\"\nProcessing of GINI formatted data found on NOAAPORT\n\"\"\"\nimport struct\nimport math\nimport zlib\nfrom datetime import timezone, datetime\nimport os\n\nimport pyproj\nimport numpy as np\nfrom pyiem.util import LOG\n\nDATADIR = os.sep.join([os.path.dirname(__file__), \"../data\"])\nM_PI_2 = 1.57079632679489661923\nM_PI = 3.14159265358979323846\nRE_METERS = 6371200.0\nENTITIES = [\n    \"UNK\",\n    \"UNK\",\n    \"MISC\",\n    \"JERS\",\n    \"ERS\",\n    \"POES\",\n    \"COMP\",\n    \"DMSP\",\n    \"GMS\",\n    \"METEOSAT\",\n    \"GOES7\",\n    \"GOES8\",\n    \"GOES9\",\n    \"GOES10\",\n    \"GOES11\",\n    \"GOES12\",\n    \"GOES13\",\n    \"GOES14\",\n    \"GOES15\",\n]\nLABELS = [\n    \"UNK\",\n    \"UNK\",\n    \"MISC\",\n    \"JERS\",\n    \"ERS\",\n    \"POES\",\n    \"COMP\",\n    \"DMSP\",\n    \"GMS\",\n    \"METEOSAT\",\n    \"GOES\",\n    \"GOES\",\n    \"GOES\",\n    \"GOES\",\n    \"GOES\",\n    \"GOES\",\n    \"GOES\",\n    \"GOES\",\n    \"GOES\",\n]\nCHANNELS = [\n    \"\",\n    \"VIS\",\n    \"3.9\",\n    \"WV\",\n    \"IR\",\n    \"12\",\n    \"13.3\",\n    \"1.3\",\n    \"U8\",\n    \"U9\",\n    \"U10\",\n    \"U11\",\n    \"U12\",\n    \"LI\",\n    \"PW\",\n    \"SKIN\",\n    \"CAPE\",\n    \"TSURF\",\n    \"WINDEX\",\n]\nfor _u in range(22, 100):\n    CHANNELS.append(f\"U{_u}\")\nSECTORS = [\n    \"NHCOMP\",\n    \"EAST\",\n    \"WEST\",\n    \"AK\",\n    \"AKNAT\",\n    \"HI\",\n    \"HINAT\",\n    \"PR\",\n    \"PRNAT\",\n    \"SUPER\",\n    \"NHCOMP\",\n    \"CCONUS\",\n    \"EFLOAT\",\n    \"WFLOAT\",\n    \"CFLOAT\",\n    \"PFLOAT\",\n]\n\nAWIPS_GRID_GUESS = {\n    \"A\": 207,\n    \"B\": 203,\n    \"E\": 211,\n    \"F\": 0,\n    \"H\": 208,\n    \"I\": 204,\n    \"N\": 0,\n    \"P\": 210,\n    \"Q\": 205,\n    \"W\": 211,\n}\n\nAWIPS_GRID = {\n    \"TIGB\": 203,\n    \"TIGE\": 211,\n    \"TIGW\": 211,\n    \"TIGH\": 208,\n    \"TIGP\": 210,\n    \"TIGA\": 207,\n    \"TIGI\": 204,\n    \"TIGQ\": 205,\n    \"TICF\": 201,\n}\n\n\ndef uint24(data):\n    \"\"\"convert three byte data that represents an unsigned int\"\"\"\n    u = int(struct.unpack(\">B\", data[0:1])[0]) << 16\n    u += int(struct.unpack(\">B\", data[1:2])[0]) << 8\n    u += int(struct.unpack(\">B\", data[2:3])[0])\n    return u\n\n\ndef int24(data):\n    \"\"\"Convert to int.\"\"\"\n    u = int(struct.unpack(\">B\", data[0:1])[0] & 127) << 16\n    u += int(struct.unpack(\">B\", data[1:2])[0]) << 8\n    u += int(struct.unpack(\">B\", data[2:3])[0])\n    if (struct.unpack(\">B\", data[0:1])[0] & 128) != 0:\n        u *= -1\n    return u\n\n\ndef get_ir_ramp():\n    \"\"\"Return a np 256x3 array of colors to use for IR\"\"\"\n    fn = \"%s/gini_ir_ramp.txt\" % (DATADIR,)\n    data = np.zeros((256, 3), np.uint8)\n    for i, line in enumerate(open(fn)):\n        tokens = line.split()\n        data[i, :] = [int(tokens[0]), int(tokens[1]), int(tokens[2])]\n    return data\n\n\nclass GINIZFile:\n    \"\"\"\n    Deal with compressed GINI files, which are the standard on NOAAPORT\n    \"\"\"\n\n    def __init__(self, fobj):\n        \"\"\"Create a GNIFile instance with a compressed file object\n\n        Args:\n          fobj (file): A fileobject\n        \"\"\"\n        fobj.seek(0)\n        # WMO HEADER\n        self.wmo = (fobj.read(21)).strip().decode(\"utf-8\")\n        d = zlib.decompressobj()\n        hdata = d.decompress(fobj.read())\n        self.metadata = self.read_header(hdata[21:])\n        self.init_projection()\n        totsz = len(d.unused_data)\n        # 5120 value chunks, so we need to be careful!\n        sdata = b\"\"\n        chunk = b\"x\\xda\"\n        i = 0\n        for part in d.unused_data.split(b\"x\\xda\"):\n            if part == b\"\" and i == 0:\n                continue\n            chunk += part\n            try:\n                sdata += zlib.decompress(chunk)\n                i += 1\n                totsz -= len(chunk)\n                chunk = b\"x\\xda\"\n            except Exception:\n                chunk += b\"x\\xda\"\n        if totsz != 0:\n            LOG.info(\"Totalsize left: %s\", totsz)\n\n        self.data = np.reshape(\n            np.fromstring(sdata, np.int8),\n            (self.metadata[\"numlines\"] + 1, self.metadata[\"linesize\"]),\n        )\n\n    def __str__(self):\n        \"\"\"return a string representation\"\"\"\n        text = \"%s Line Size: %s Num Lines: %s\" % (\n            self.wmo,\n            self.metadata[\"linesize\"],\n            self.metadata[\"numlines\"],\n        )\n        return text\n\n    def awips_grid(self):\n        \"\"\"\n        Return the awips grid number based on the WMO header\n        \"\"\"\n        try1 = AWIPS_GRID.get(self.wmo[:4], None)\n        if try1:\n            return try1\n        return AWIPS_GRID_GUESS.get(self.wmo[3], None)\n\n    def current_filename(self):\n        \"\"\"\n        Return a filename for this product, we'll use the format\n        {SOURCE}_{SECTOR}_{CHANNEL}_{VALID}.png\n        \"\"\"\n        return \"%s_%s_%s.png\" % (\n            LABELS[self.metadata[\"creating_entity\"]],\n            SECTORS[self.metadata[\"sector\"]],\n            CHANNELS[self.metadata[\"channel\"]],\n        )\n\n    def get_bird(self):\n        \"\"\"\n        Return a string label for this satellite\n        \"\"\"\n        return ENTITIES[self.metadata[\"creating_entity\"]]\n\n    def get_sector(self):\n        \"\"\"Return the sector.\"\"\"\n        return SECTORS[self.metadata[\"sector\"]]\n\n    def get_channel(self):\n        \"\"\"Return the channel.\"\"\"\n        return CHANNELS[self.metadata[\"channel\"]]\n\n    def archive_filename(self):\n        \"\"\"\n        Return a filename for this product, we'll use the format\n        {SOURCE}_{SECTOR}_{CHANNEL}_{VALID}.png\n        \"\"\"\n        return (\"%s_%s_%s_%s.png\") % (\n            LABELS[self.metadata[\"creating_entity\"]],\n            SECTORS[self.metadata[\"sector\"]],\n            CHANNELS[self.metadata[\"channel\"]],\n            self.metadata[\"valid\"].strftime(\"%Y%m%d%H%M\"),\n        )\n\n    def init_llc(self):\n        \"\"\"\n        Initialize Lambert Conic Comformal\n        \"\"\"\n        self.metadata[\"proj\"] = pyproj.Proj(\n            proj=\"lcc\",\n            lat_0=self.metadata[\"latin\"],\n            lat_1=self.metadata[\"latin\"],\n            lat_2=self.metadata[\"latin\"],\n            lon_0=self.metadata[\"lov\"],\n            a=6371200.0,\n            b=6371200.0,\n        )\n\n        # s = 1.0\n        # if self.metadata['proj_center_flag'] != 0:\n        #    s = -1.0\n        psi = M_PI_2 - abs(math.radians(self.metadata[\"latin\"]))\n        cos_psi = math.cos(psi)\n        # r_E = RE_METERS / cos_psi\n        alpha = math.pow(math.tan(psi / 2.0), cos_psi) / math.sin(psi)\n\n        x0, y0 = self.metadata[\"proj\"](\n            self.metadata[\"lon1\"], self.metadata[\"lat1\"]\n        )\n        self.metadata[\"x0\"] = x0\n        self.metadata[\"y0\"] = y0\n        # self.metadata['dx'] *= alpha\n        # self.metadata['dy'] *= alpha\n        self.metadata[\"y1\"] = y0 + (self.metadata[\"dy\"] * self.metadata[\"ny\"])\n\n        (self.metadata[\"lon_ul\"], self.metadata[\"lat_ul\"]) = self.metadata[\n            \"proj\"\n        ](self.metadata[\"x0\"], self.metadata[\"y1\"], inverse=True)\n        LOG.info(\n            (\n                \"lat1: %.5f y0: %5.f y1: %.5f lat_ul: %.3f \"\n                \"lat_ur: %.3f lon_ur: %.3f alpha: %.5f dy: %.3f\"\n            ),\n            self.metadata[\"lat1\"],\n            y0,\n            self.metadata[\"y1\"],\n            self.metadata[\"lat_ul\"],\n            self.metadata[\"lat_ur\"],\n            self.metadata[\"lon_ur\"],\n            alpha,\n            self.metadata[\"dy\"],\n        )\n\n    def init_mercator(self):\n        \"\"\"\n        Compute mercator projection stuff\n        \"\"\"\n        self.metadata[\"proj\"] = pyproj.Proj(\n            proj=\"merc\",\n            lat_ts=self.metadata[\"latin\"],\n            x_0=0,\n            y_0=0,\n            a=6371200.0,\n            b=6371200.0,\n        )\n        x0, y0 = self.metadata[\"proj\"](\n            self.metadata[\"lon1\"], self.metadata[\"lat1\"]\n        )\n        self.metadata[\"x0\"] = x0\n        self.metadata[\"y0\"] = y0\n\n        x1, y1 = self.metadata[\"proj\"](\n            self.metadata[\"lon2\"], self.metadata[\"lat2\"]\n        )\n        self.metadata[\"x1\"] = x1\n        self.metadata[\"y1\"] = y1\n\n        self.metadata[\"dx\"] = (x1 - x0) / self.metadata[\"nx\"]\n        self.metadata[\"dy\"] = (y1 - y0) / self.metadata[\"ny\"]\n\n        (self.metadata[\"lon_ul\"], self.metadata[\"lat_ul\"]) = self.metadata[\n            \"proj\"\n        ](self.metadata[\"x0\"], self.metadata[\"y1\"], inverse=True)\n\n        LOG.info(\n            (\n                \"latin: %.2f lat_ul: %.3f lon_ul: %.3f \"\n                \"y0: %5.f y1: %.5f dx: %.3f dy: %.3f\"\n            ),\n            self.metadata[\"latin\"],\n            self.metadata[\"lat_ul\"],\n            self.metadata[\"lon_ul\"],\n            y0,\n            y1,\n            self.metadata[\"dx\"],\n            self.metadata[\"dy\"],\n        )\n\n    def init_stereo(self):\n        \"\"\"\n        Compute Polar Stereographic\n        \"\"\"\n        self.metadata[\"proj\"] = pyproj.Proj(\n            proj=\"stere\",\n            lat_ts=60,\n            lat_0=90,\n            lon_0=self.metadata[\"lov\"],\n            x_0=0,\n            y_0=0,\n            a=6371200.0,\n            b=6371200.0,\n        )\n        # First point!\n        x0, y0 = self.metadata[\"proj\"](\n            self.metadata[\"lon1\"], self.metadata[\"lat1\"]\n        )\n        self.metadata[\"x0\"] = x0\n        self.metadata[\"y0\"] = y0\n\n        self.metadata[\"y1\"] = y0 + (self.metadata[\"dy\"] * self.metadata[\"ny\"])\n        (self.metadata[\"lon_ul\"], self.metadata[\"lat_ul\"]) = self.metadata[\n            \"proj\"\n        ](x0, self.metadata[\"y1\"], inverse=True)\n\n        LOG.info(\n            (\n                \"lon_ul: %.2f lat_ul: %.2f \"\n                \"lon_ll: %.2f lat_ll: %.2f \"\n                \" lov: %.2f latin: %.2f lat1: %.2f lat2: %.2f \"\n                \"y0: %5.f y1: %.5f dx: %.3f dy: %.3f\"\n            ),\n            self.metadata[\"lon_ul\"],\n            self.metadata[\"lat_ul\"],\n            self.metadata[\"lon1\"],\n            self.metadata[\"lat1\"],\n            self.metadata[\"lov\"],\n            self.metadata[\"latin\"],\n            self.metadata[\"lat1\"],\n            self.metadata[\"lat2\"],\n            y0,\n            self.metadata[\"y1\"],\n            self.metadata[\"dx\"],\n            self.metadata[\"dy\"],\n        )\n\n    def init_projection(self):\n        \"\"\"\n        Setup Grid and projection details\n        \"\"\"\n        if self.metadata[\"map_projection\"] == 3:\n            self.init_llc()\n        elif self.metadata[\"map_projection\"] == 1:\n            self.init_mercator()\n        elif self.metadata[\"map_projection\"] == 5:\n            self.init_stereo()\n        else:\n            LOG.info(\"Unknown Projection: %s\", self.metadata[\"map_projection\"])\n\n    def read_header(self, hdata):\n        \"\"\"read the header!\"\"\"\n        meta = {}\n        meta[\"source\"] = struct.unpack(\"> B\", hdata[0:1])[0]\n        meta[\"creating_entity\"] = struct.unpack(\"> B\", hdata[1:2])[0]\n        meta[\"sector\"] = struct.unpack(\"> B\", hdata[2:3])[0]\n        meta[\"channel\"] = struct.unpack(\"> B\", hdata[3:4])[0]\n\n        meta[\"numlines\"] = struct.unpack(\">H\", hdata[4:6])[0]\n        meta[\"linesize\"] = struct.unpack(\">H\", hdata[6:8])[0]\n\n        yr = 1900 + struct.unpack(\"> B\", hdata[8:9])[0]\n        mo = struct.unpack(\"> B\", hdata[9:10])[0]\n        dy = struct.unpack(\"> B\", hdata[10:11])[0]\n        hh = struct.unpack(\"> B\", hdata[11:12])[0]\n        mi = struct.unpack(\"> B\", hdata[12:13])[0]\n        ss = struct.unpack(\"> B\", hdata[13:14])[0]\n        # hs = struct.unpack(\"> B\", hdata[14:15] )[0]\n        meta[\"valid\"] = datetime(yr, mo, dy, hh, mi, ss).replace(\n            tzinfo=timezone.utc\n        )\n        meta[\"map_projection\"] = struct.unpack(\"> B\", hdata[15:16])[0]\n        meta[\"proj_center_flag\"] = struct.unpack(\"> B\", hdata[36:37])[0] >> 7\n        meta[\"scan_mode\"] = struct.unpack(\"> B\", hdata[37:38])[0]\n\n        meta[\"nx\"] = struct.unpack(\">H\", hdata[16:18])[0]\n        meta[\"ny\"] = struct.unpack(\">H\", hdata[18:20])[0]\n        meta[\"res\"] = struct.unpack(\">B\", hdata[41:42])[0]\n        # Is Calibration Info included?\n        # http://www.nws.noaa.gov/noaaport/document/ICD%20CH5-2005-1.pdf\n        # page24\n        # Mercator\n        if meta[\"map_projection\"] == 1:\n            meta[\"lat1\"] = int24(hdata[20:23])\n            meta[\"lon1\"] = int24(hdata[23:26])\n            meta[\"lov\"] = 0\n            meta[\"dx\"] = struct.unpack(\">H\", hdata[33:35])[0]\n            meta[\"dy\"] = struct.unpack(\">H\", hdata[35:37])[0]\n            meta[\"latin\"] = int24(hdata[38:41])\n            meta[\"lat2\"] = int24(hdata[27:30])\n            meta[\"lon2\"] = int24(hdata[30:33])\n            meta[\"lat_ur\"] = int24(hdata[55:58])\n            meta[\"lon_ur\"] = int24(hdata[58:61])\n        # lambert == 3, polar == 5\n        else:\n            meta[\"lat1\"] = int24(hdata[20:23])\n            meta[\"lon1\"] = int24(hdata[23:26])\n            meta[\"lov\"] = int24(hdata[27:30])\n            meta[\"dx\"] = uint24(hdata[30:33])\n            meta[\"dy\"] = uint24(hdata[33:36])\n            meta[\"latin\"] = int24(hdata[38:41])\n            meta[\"lat2\"] = 0\n            meta[\"lon2\"] = 0\n            meta[\"lat_ur\"] = int24(hdata[55:58])\n            meta[\"lon_ur\"] = int24(hdata[58:61])\n\n        meta[\"dx\"] = meta[\"dx\"] / 10.0\n        meta[\"dy\"] = meta[\"dy\"] / 10.0\n        meta[\"lat1\"] = meta[\"lat1\"] / 10000.0\n        meta[\"lon1\"] = meta[\"lon1\"] / 10000.0\n        meta[\"lov\"] = meta[\"lov\"] / 10000.0\n        meta[\"latin\"] = meta[\"latin\"] / 10000.0\n        meta[\"lat2\"] = meta[\"lat2\"] / 10000.0\n        meta[\"lon2\"] = meta[\"lon2\"] / 10000.0\n        meta[\"lat_ur\"] = meta[\"lat_ur\"] / 10000.0\n        meta[\"lon_ur\"] = meta[\"lon_ur\"] / 10000.0\n\n        return meta\n", "meta": {"hexsha": "c3a1a03c6bc0c3a4d73dab6a332c782b1657089b", "size": 13237, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/pyiem/nws/gini.py", "max_stars_repo_name": "akrherz/pyIEM", "max_stars_repo_head_hexsha": "ec0acdc4c6b507b0d558ce216d4bbdbcb9b2f364", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2015-09-02T15:53:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T19:47:49.000Z", "max_issues_repo_path": "src/pyiem/nws/gini.py", "max_issues_repo_name": "akrherz/pyIEM", "max_issues_repo_head_hexsha": "ec0acdc4c6b507b0d558ce216d4bbdbcb9b2f364", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 531, "max_issues_repo_issues_event_min_datetime": "2015-01-13T20:58:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T13:59:14.000Z", "max_forks_repo_path": "src/pyiem/nws/gini.py", "max_forks_repo_name": "akrherz/pyIEM", "max_forks_repo_head_hexsha": "ec0acdc4c6b507b0d558ce216d4bbdbcb9b2f364", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2015-02-28T22:34:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T05:16:13.000Z", "avg_line_length": 27.8673684211, "max_line_length": 79, "alphanum_fraction": 0.4837954219, "include": true, "reason": "import numpy", "num_tokens": 3893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.16508618295270341}}
{"text": "''' Compared with model_v1 use deeper network for 3D box regression. use BN for all FC layers\ncompared with model_v1_deeper, added more layers for 3D regression. added dropout for segmentation\ncompared with model_v1_deeper_0913, added visu for mean iou3d, added balanced loss.\ncompared with model_v1_deeper_0914, use two stage center regression..\n'''\nimport tensorflow as tf\nimport numpy as np\nimport math\nimport sys\nimport os\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(BASE_DIR)\nsys.path.append(os.path.join(BASE_DIR, '../utils'))\nimport tf_util\nfrom roi_seg_box3d_dataset import NUM_HEADING_BIN, NUM_SIZE_CLUSTER, NUM_CLASS, compute_box3d_iou, class2type, type_mean_size\nfrom model_v1_deeper_0914_corners_balanced import get_box3d_corners, get_box3d_corners_helper # TODO move elsewhere\nmean_size_arr = np.zeros((NUM_SIZE_CLUSTER, 3))\nfor i in range(NUM_SIZE_CLUSTER):\n    mean_size_arr[i,:] = type_mean_size[class2type[i]]\n\ndef placeholder_inputs(batch_size, num_point):\n    pointclouds_pl = tf.placeholder(tf.float32,\n                                     shape=(batch_size, num_point, 6))\n    one_hot_vec_pl = tf.placeholder(tf.float32, shape=(batch_size, NUM_CLASS))\n    labels_pl = tf.placeholder(tf.int32,\n                                shape=(batch_size, num_point))\n    centers_pl = tf.placeholder(tf.float32,\n                                shape=(batch_size, 3))\n    heading_class_label_pl = tf.placeholder(tf.int32, shape=(batch_size,))\n    heading_residual_label_pl = tf.placeholder(tf.float32, shape=(batch_size,))\n    size_class_label_pl = tf.placeholder(tf.int32, shape=(batch_size,))\n    size_residual_label_pl = tf.placeholder(tf.float32, shape=(batch_size,3))\n    return pointclouds_pl, one_hot_vec_pl, labels_pl, centers_pl, heading_class_label_pl, heading_residual_label_pl, size_class_label_pl, size_residual_label_pl\n\n\ndef get_model(point_cloud, one_hot_vec, is_training, bn_decay=None):\n    \"\"\" Classification PointNet, input is BxNx4, onehotvec is Bx3, output BxNx2 \"\"\"\n    batch_size = point_cloud.get_shape()[0].value\n    num_point = point_cloud.get_shape()[1].value\n    end_points = {}\n\n    input_image = tf.expand_dims(point_cloud, -1)\n\n    net = tf_util.conv2d(input_image, 64, [1,6],\n                         padding='VALID', stride=[1,1],\n                         bn=True, is_training=is_training,\n                         scope='conv1', bn_decay=bn_decay)\n    net = tf_util.conv2d(net, 64, [1,1],\n                         padding='VALID', stride=[1,1],\n                         bn=True, is_training=is_training,\n                         scope='conv2', bn_decay=bn_decay)\n    point_feat = tf_util.conv2d(net, 64, [1,1],\n                         padding='VALID', stride=[1,1],\n                         bn=True, is_training=is_training,\n                         scope='conv3', bn_decay=bn_decay)\n    net = tf_util.conv2d(point_feat, 128, [1,1],\n                         padding='VALID', stride=[1,1],\n                         bn=True, is_training=is_training,\n                         scope='conv4', bn_decay=bn_decay)\n    net = tf_util.conv2d(net, 1024, [1,1],\n                         padding='VALID', stride=[1,1],\n                         bn=True, is_training=is_training,\n                         scope='conv5', bn_decay=bn_decay)\n    global_feat = tf_util.max_pool2d(net, [num_point,1],\n                                     padding='VALID', scope='maxpool')\n    print global_feat\n\n    global_feat = tf.concat([global_feat, tf.expand_dims(tf.expand_dims(one_hot_vec, 1), 1)], axis=3)\n    print 'Global Feat: ', global_feat\n    global_feat_expand = tf.tile(global_feat, [1, num_point, 1, 1])\n    print point_feat, global_feat_expand\n    concat_feat = tf.concat(axis=3, values=[point_feat, global_feat_expand])\n    print concat_feat\n\n    net = tf_util.conv2d(concat_feat, 512, [1,1],\n                         padding='VALID', stride=[1,1],\n                         bn=True, is_training=is_training,\n                         scope='conv6', bn_decay=bn_decay)\n    net = tf_util.conv2d(net, 256, [1,1],\n                         padding='VALID', stride=[1,1],\n                         bn=True, is_training=is_training,\n                         scope='conv7', bn_decay=bn_decay)\n    net = tf_util.conv2d(net, 128, [1,1],\n                         padding='VALID', stride=[1,1],\n                         bn=True, is_training=is_training,\n                         scope='conv8', bn_decay=bn_decay)\n    net = tf_util.conv2d(net, 128, [1,1],\n                         padding='VALID', stride=[1,1],\n                         bn=True, is_training=is_training,\n                         scope='conv9', bn_decay=bn_decay)\n    net = tf_util.dropout(net, is_training, 'dp1', keep_prob=0.5)\n\n    logits = tf_util.conv2d(net, 2, [1,1],\n                         padding='VALID', stride=[1,1], activation_fn=None,\n                         scope='conv10')\n    logits = tf.squeeze(logits, [2]) # BxNxC\n    print logits\n    \n    print '-----------'\n    #net = tf.concat(axis=3, values=[net, tf.expand_dims(tf.slice(point_cloud, [0,0,0], [-1,-1,3]), 2)])\n    mask = tf.slice(logits,[0,0,0],[-1,-1,1]) < tf.slice(logits,[0,0,1],[-1,-1,1])\n    mask = tf.to_float(mask) # BxNx1\n    mask_count = tf.tile(tf.reduce_sum(mask,axis=1,keep_dims=True), [1,1,3]) # Bx1x3\n    print mask\n    point_cloud_xyz = tf.slice(point_cloud, [0,0,0], [-1,-1,3]) # BxNx3\n\n    # ---- Subtract points mean ----\n    mask_xyz_mean = tf.reduce_sum(tf.tile(mask, [1,1,3])*point_cloud_xyz, axis=1, keep_dims=True) # Bx1x3\n    mask_xyz_mean = mask_xyz_mean/tf.maximum(mask_count,1) # Bx1x3\n    point_cloud_xyz_stage1 = point_cloud_xyz - tf.tile(mask_xyz_mean, [1,num_point,1])\n    print 'Point cloud xyz stage1: ', point_cloud_xyz_stage1\n\n    # ---- Regress 1st stage center ----\n    net = tf.expand_dims(point_cloud_xyz_stage1, 2)\n    print net\n    net = tf_util.conv2d(net, 128, [1,1],\n                         padding='VALID', stride=[1,1],\n                         bn=True, is_training=is_training,\n                         scope='conv-reg1-stage1', bn_decay=bn_decay)\n    net = tf_util.conv2d(net, 128, [1,1],\n                         padding='VALID', stride=[1,1],\n                         bn=True, is_training=is_training,\n                         scope='conv-reg2-stage1', bn_decay=bn_decay)\n    net = tf_util.conv2d(net, 256, [1,1],\n                         padding='VALID', stride=[1,1],\n                         bn=True, is_training=is_training,\n                         scope='conv-reg3-stage1', bn_decay=bn_decay)\n    mask_expand = tf.tile(tf.expand_dims(mask,-1), [1,1,1,256])\n    masked_net = net*mask_expand\n    print masked_net\n    net = tf_util.max_pool2d(masked_net, [num_point,1], padding='VALID', scope='maxpool-stage1')\n    net = tf.squeeze(net, axis=[1,2])\n    print net\n    net = tf.concat([net, one_hot_vec], axis=1)\n    net = tf_util.fully_connected(net, 256, scope='fc1-stage1', bn=True, is_training=is_training, bn_decay=bn_decay)\n    net = tf_util.fully_connected(net, 128, scope='fc2-stage1', bn=True, is_training=is_training, bn_decay=bn_decay)\n    stage1_center = tf_util.fully_connected(net, 3, activation_fn=None, scope='fc3-stage1')\n    stage1_center = stage1_center + tf.squeeze(mask_xyz_mean, axis=1) # Bx3\n    end_points['stage1_center'] = stage1_center\n\n    # ---- Subtract stage1 center ----\n    point_cloud_xyz_submean = point_cloud_xyz - tf.expand_dims(stage1_center, 1)\n    print 'Point cloud xyz submean: ', point_cloud_xyz_submean\n\n    net = tf.expand_dims(point_cloud_xyz_submean, 2)\n    print net\n    net = tf_util.conv2d(net, 128, [1,1],\n                         padding='VALID', stride=[1,1],\n                         bn=True, is_training=is_training,\n                         scope='conv-reg1', bn_decay=bn_decay)\n    net = tf_util.conv2d(net, 128, [1,1],\n                         padding='VALID', stride=[1,1],\n                         bn=True, is_training=is_training,\n                         scope='conv-reg2', bn_decay=bn_decay)\n    net = tf_util.conv2d(net, 256, [1,1],\n                         padding='VALID', stride=[1,1],\n                         bn=True, is_training=is_training,\n                         scope='conv-reg3', bn_decay=bn_decay)\n    net = tf_util.conv2d(net, 512, [1,1],\n                         padding='VALID', stride=[1,1],\n                         bn=True, is_training=is_training,\n                         scope='conv-reg4', bn_decay=bn_decay)\n    mask_expand = tf.tile(tf.expand_dims(mask,-1), [1,1,1,512])\n    masked_net = net*mask_expand\n    print masked_net\n    net = tf_util.max_pool2d(masked_net, [num_point,1], padding='VALID', scope='maxpool2')\n    net = tf.squeeze(net, axis=[1,2])\n    print net\n    net = tf.concat([net, one_hot_vec], axis=1)\n    net = tf_util.fully_connected(net, 512, scope='fc1', bn=True, is_training=is_training, bn_decay=bn_decay)\n    net = tf_util.fully_connected(net, 256, scope='fc2', bn=True, is_training=is_training, bn_decay=bn_decay)\n\n    # First 3 are cx,cy,cz, next NUM_HEADING_BIN*2 are for heading\n    # next NUM_SIZE_CLUSTER*4 are for dimension\n    output = tf_util.fully_connected(net, 3+NUM_HEADING_BIN*2+NUM_SIZE_CLUSTER*4, activation_fn=None, scope='fc3')\n    print output\n\n    center = tf.slice(output, [0,0], [-1,3])\n    center = center + stage1_center # Bx3\n    end_points['center'] = center\n\n    heading_scores = tf.slice(output, [0,3], [-1,NUM_HEADING_BIN])\n    heading_residuals_normalized = tf.slice(output, [0,3+NUM_HEADING_BIN], [-1,NUM_HEADING_BIN])\n    end_points['heading_scores'] = heading_scores # BxNUM_HEADING_BIN\n    end_points['heading_residuals_normalized'] = heading_residuals_normalized # BxNUM_HEADING_BIN (should be -1 to 1)\n    end_points['heading_residuals'] = heading_residuals_normalized * (np.pi/NUM_HEADING_BIN) # BxNUM_HEADING_BIN\n    \n    size_scores = tf.slice(output, [0,3+NUM_HEADING_BIN*2], [-1,NUM_SIZE_CLUSTER]) # BxNUM_SIZE_CLUSTER\n    size_residuals_normalized = tf.slice(output, [0,3+NUM_HEADING_BIN*2+NUM_SIZE_CLUSTER], [-1,NUM_SIZE_CLUSTER*3])\n    size_residuals_normalized = tf.reshape(size_residuals_normalized, [batch_size, NUM_SIZE_CLUSTER, 3]) # BxNUM_SIZE_CLUSTERx3\n    end_points['size_scores'] = size_scores\n    end_points['size_residuals_normalized'] = size_residuals_normalized\n    end_points['size_residuals'] = size_residuals_normalized * tf.expand_dims(tf.constant(mean_size_arr, dtype=tf.float32), 0)\n\n    return logits, end_points\n\n\ndef huber_loss(error, delta):\n    abs_error = tf.abs(error)\n    quadratic = tf.minimum(abs_error, delta)\n    linear = (abs_error - quadratic)\n    losses = 0.5 * quadratic**2 + delta * linear\n    return tf.reduce_mean(losses)\n\n# TODO: Test correctness of the loss...\ndef get_loss(logits, \\\n             mask_label, center_label, \\\n             heading_class_label, heading_residual_label, \\\n             size_class_label, size_residual_label, \\\n             end_points, reg_weight=0.001):\n    \"\"\" logits: BxNxC,\n        mask_label: BxN, \"\"\"\n    batch_size = logits.get_shape()[0].value\n    mask_loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=mask_label))\n    tf.summary.scalar('3d mask loss', mask_loss)\n\n    center_dist = tf.norm(center_label - end_points['center'], axis=-1)\n    center_loss = huber_loss(center_dist, delta=2.0)\n    tf.summary.scalar('center loss', center_loss)\n\n    stage1_center_dist = tf.norm(center_label - end_points['stage1_center'], axis=-1)\n    stage1_center_loss = huber_loss(stage1_center_dist, delta=1.0)\n    tf.summary.scalar('stage1 center loss', stage1_center_loss)\n\n    heading_class_loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=end_points['heading_scores'], labels=heading_class_label))\n    tf.summary.scalar('heading class loss', heading_class_loss)\n\n    tmp = tf.one_hot(heading_class_label, depth=NUM_HEADING_BIN, on_value=1, off_value=0, axis=-1) # BxNUM_HEADING_BIN\n    print tmp\n    heading_residual_normalized_label = heading_residual_label / (np.pi/NUM_HEADING_BIN)\n    heading_residual_normalized_loss = huber_loss(tf.reduce_sum(end_points['heading_residuals_normalized']*tf.to_float(tmp), axis=1) - heading_residual_normalized_label, delta=1.0)\n    print heading_residual_normalized_loss\n    tf.summary.scalar('heading residual normalized loss', heading_residual_normalized_loss)\n\n    size_class_loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=end_points['size_scores'], labels=size_class_label))\n    tf.summary.scalar('size class loss', size_class_loss)\n\n    tmp2 = tf.one_hot(size_class_label, depth=NUM_SIZE_CLUSTER, on_value=1, off_value=0, axis=-1) # BxNUM_SIZE_CLUSTER\n    tmp2_tiled = tf.tile(tf.expand_dims(tf.to_float(tmp2), -1), [1,1,3]) # BxNUM_SIZE_CLUSTERx3\n    predicted_size_residual_normalized = tf.reduce_sum(end_points['size_residuals_normalized']*tmp2_tiled, axis=[1]) # Bx3\n\n    tmp3 = tf.expand_dims(tf.constant(mean_size_arr, dtype=tf.float32),0) # 1xNUM_SIZE_CLUSTERx3\n    mean_size_label = tf.reduce_sum(tmp2_tiled * tmp3, axis=[1]) # Bx3\n    size_residual_label_normalized = size_residual_label / mean_size_label\n \n    size_normalized_dist = tf.norm(size_residual_label_normalized - predicted_size_residual_normalized, axis=-1)\n    size_residual_normalized_loss = huber_loss(size_normalized_dist, delta=1.0)\n    print size_residual_normalized_loss\n    tf.summary.scalar('size residual normalized loss', size_residual_normalized_loss)\n\n    # Compute IOU 3D\n    iou2ds, iou3ds = tf.py_func(compute_box3d_iou, [end_points['center'], end_points['heading_scores'], end_points['heading_residuals'], end_points['size_scores'], end_points['size_residuals'], center_label, heading_class_label, heading_residual_label, size_class_label, size_residual_label], [tf.float32, tf.float32])\n    tf.summary.scalar('iou_2d', tf.reduce_mean(iou2ds))\n    tf.summary.scalar('iou_3d', tf.reduce_mean(iou3ds))\n \n    end_points['iou2ds'] = iou2ds \n    end_points['iou3ds'] = iou3ds \n\n    # Compute BOX3D corners\n    corners_3d = get_box3d_corners(end_points['center'], end_points['heading_residuals'], end_points['size_residuals']) # (B,NH,NS,8,3)\n    gt_mask = tf.tile(tf.expand_dims(tmp, 2), [1,1,NUM_SIZE_CLUSTER]) * tf.tile(tf.expand_dims(tmp2,1), [1,NUM_HEADING_BIN,1]) # (B,NH,NS)\n    corners_3d_pred = tf.reduce_sum(tf.to_float(tf.expand_dims(tf.expand_dims(gt_mask,-1),-1))*corners_3d, axis=[1,2]) # (B,8,3)\n\n    heading_bin_centers = tf.constant(np.arange(0,2*np.pi,2*np.pi/NUM_HEADING_BIN), dtype=tf.float32) # (NH,)\n    heading_label = tf.expand_dims(heading_residual_label,1) + tf.expand_dims(heading_bin_centers, 0) # (B,NH)\n    heading_label = tf.reduce_sum(tf.to_float(tmp)*heading_label, 1)\n    mean_sizes = tf.expand_dims(tf.constant(mean_size_arr, dtype=tf.float32), 0) # (1,NS,3)\n    size_label = mean_sizes + tf.expand_dims(size_residual_label, 1) # (1,NS,3) + (B,1,3) = (B,NS,3)\n    size_label = tf.reduce_sum(tf.expand_dims(tf.to_float(tmp2),-1)*size_label, axis=[1]) # (B,3)\n    corners_3d_gt = get_box3d_corners_helper(center_label, heading_label, size_label) # (B,8,3)\n    corners_3d_gt_flip = get_box3d_corners_helper(center_label, heading_label+np.pi, size_label) # (B,8,3)\n\n    corners_dist = tf.minimum(tf.norm(corners_3d_pred - corners_3d_gt, axis=-1), tf.norm(corners_3d_pred - corners_3d_gt_flip, axis=-1))\n    print \"Corners dist: \", corners_dist\n    corners_loss = huber_loss(corners_dist, delta=1.0) \n    tf.summary.scalar('corners loss', corners_loss)\n\n    return mask_loss + (center_loss + heading_class_loss + size_class_loss + heading_residual_normalized_loss*20 + size_residual_normalized_loss*20 + stage1_center_loss)*0.1 + corners_loss\n\n\nif __name__=='__main__':\n    with tf.Graph().as_default():\n        inputs = tf.zeros((32,1024,4))\n        outputs = get_model(inputs, tf.ones((32,3)), tf.constant(True))\n        print outputs\n        loss = get_loss(outputs[0], tf.zeros((32,1024),dtype=tf.int32), tf.zeros((32,3)), tf.zeros((32,),dtype=tf.int32), tf.zeros((32,)), tf.zeros((32,),dtype=tf.int32), tf.zeros((32,3)), outputs[1])\n        print loss\n", "meta": {"hexsha": "b10b1b29815cb77e4529c8a3a01306ac069ede2b", "size": 16060, "ext": "py", "lang": "Python", "max_stars_repo_path": "sunrgbd/sunrgbd_detection/frustum_pointnets_v1_sunrgbd.py", "max_stars_repo_name": "JenningsL/frustum-pointnets", "max_stars_repo_head_hexsha": "989e7cc2a6e6899dd30792344bd5a5e457d6fc8d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-12-01T02:56:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-01T02:56:57.000Z", "max_issues_repo_path": "sunrgbd/sunrgbd_detection/frustum_pointnets_v1_sunrgbd.py", "max_issues_repo_name": "JenningsL/frustum-pointnets", "max_issues_repo_head_hexsha": "989e7cc2a6e6899dd30792344bd5a5e457d6fc8d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sunrgbd/sunrgbd_detection/frustum_pointnets_v1_sunrgbd.py", "max_forks_repo_name": "JenningsL/frustum-pointnets", "max_forks_repo_head_hexsha": "989e7cc2a6e6899dd30792344bd5a5e457d6fc8d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-02-14T05:55:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-18T02:42:21.000Z", "avg_line_length": 55.7638888889, "max_line_length": 318, "alphanum_fraction": 0.6673723537, "include": true, "reason": "import numpy", "num_tokens": 4257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.28776782186926264, "lm_q1q2_score": 0.16508618157107277}}
{"text": "\"\"\"\ndevice.py - A module for defining attributes in the device..\n\"\"\"\n\n#from fqc.util import get_unitary\nimport numpy as np\nimport scipy.linalg as la\nfrom scipy.special import factorial\nimport os,sys,inspect\n# import h5py\nimport matplotlib.pyplot as plt\nimport random as rd\nimport time\nimport re, math\nfrom datetime import datetime\nfrom ..util import get_grid_coupling_list, get_connectivity_graph, get_crosstalk_graph\n\n\nGATETIMES = {'unitary': 55,'rz': 30, 'z':30, 'u1': 30, 's': 30, 't': 30, 'rx': 30, 'x': 30, 'u2': 30, 'ry': 30, 'y': 30, 'u3': 30, 'h': 30, 'measure': 0.0, 'barrier': 0.0} # all in ns\n\nclass Device(object):\n    \"\"\"\n    Fields:\n    \"\"\"\n    def __init__(self, topology, qubits, omega_max, delta_int, delta_ext, delta_park, cqq=0.019, alpha=-0.2, EJS=8, EJL=20, EC=0.5, flux_sigma=0.0, error_1q_gate=0.001, d=1):\n        if (topology == None):\n            self.topology = 'grid'\n        else:\n            self.topology = topology\n        self.qubits = qubits\n        self.side_length = int(np.sqrt(qubits)) # only for square grid\n        self.omega_max = omega_max\n        self.delta_int = delta_int\n        self.delta_ext = delta_ext\n        self.delta_park = delta_park\n        self.omega_min = omega_max - delta_int - delta_ext - delta_park\n        self.cqq = cqq\n        self.alpha = alpha\n        self.ejs = EJS\n        self.ejl = EJL\n        self.ec = EC\n        self.flux_sigma = flux_sigma\n        self.g_connect = None\n        self.coupling = None\n        self.g_xtalk = None\n        self.d_xtalk = d\n        self.gate_times = GATETIMES\n        self.error_1q_gate = error_1q_gate\n\n    def build_graph(self, param=None):\n        if self.topology=='grid':\n            self.g_connect = get_connectivity_graph(self.qubits, self.topology)\n            self.coupling = get_grid_coupling_list(self.side_length, self.side_length)\n            self.g_xtalk = get_crosstalk_graph(self.g_connect, self.topology, self.d_xtalk)\n        else:\n            self.g_connect = get_connectivity_graph(self.qubits, self.topology, param)\n            self.coupling = self.g_connect.edges()\n            self.g_xtalk = get_crosstalk_graph(self.g_connect, self.topology, self.d_xtalk)\n\nclass Sycamore_device(object):\n    def __init__(self, device, size, res_coupling=0.0):\n        if size != device.qubits:\n            print(\"Warning: device size inconsistent. Device: \" + str(device.qubits) + \", Sycamore_device: \" + str(size))\n        if size not in [4,9,16,25]:\n            raise Exception(\"Wrong device size\")\n        if size == 4:\n            self.int_freqs = {(0,1):6.619, (0,2):6.65, (1,3):6.657, (2,3):6.677}\n            self.park_freqs = {0:6.605,1:6.638,2:6.694,3:6.681}\n        elif size == 9:\n            self.park_freqs = {0:6.605,1:6.638,2:6.565,3:6.694,4:6.681,5:6.601,6:6.643,7:6.621,8:6.646}\n            self.int_freqs = {(0,1):6.619, (1,2):6.601, (3,4):6.677, (4,5):6.635, (6,7):6.631, (7,8):6.646, (0,3):6.65, (1,4):6.657, (2,5):6.585, (3,6):6.667, (4,7):6.645,(5,8):6.646}\n        elif size == 16:\n            self.park_freqs = {0:6.605,1:6.638,2:6.565,3:6.555,4:6.694,5:6.681,6:6.601,7:6.626,8:6.643,9:6.621,10:6.646,11:6.657,12:6.712,13:6.671,14:6.586,15:6.623}\n            self.int_freqs = {(0,1):6.619,(1,2):6.601,(2,3):6.565,(4,5):6.677,(5,6):6.635,(6,7):6.595}\n            self.int_freqs[(8,9)] = 6.631\n            self.int_freqs[(9,10)] = 6.646\n            self.int_freqs[(10,11)] = 6.646\n            self.int_freqs[(12,13)] = 6.69\n            self.int_freqs[(13,14)] = 6.631\n            self.int_freqs[(14,15)] = 6.623\n            self.int_freqs[(0,4)] = 6.65\n            self.int_freqs[(1,5)] = 6.657\n            self.int_freqs[(2,6)] = 6.585\n            self.int_freqs[(3,7)] = 6.592\n            self.int_freqs[(4,8)] = 6.667\n            self.int_freqs[(5,9)] = 6.645\n            self.int_freqs[(6,10)] = 6.646\n            self.int_freqs[(7,11)] = 6.642\n            self.int_freqs[(8,12)] = 6.68\n            self.int_freqs[(9,13)] = 6.645\n            self.int_freqs[(10,14)] = 6.646\n            self.int_freqs[(11,15)] = 6.633\n        else: # size == 25\n            self.park_freqs = {0:6.612,1:6.571,2:6.605,3:6.638,4:6.565,5:6.687,6:6.661,7:6.694,8:6.681,9:6.601,10:6.634,11:6.628,12:6.643,13:6.621,14:6.646,15:6.707,16:6.665,17:6.712,18:6.671,19:6.586,20:6.775,21:6.734,22:6.766,23:6.729,24:6.594}\n            self.int_freqs = {(0,1):6.592,(1,2):6.589,(2,3):6.619,(3,4):6.601}\n            self.int_freqs[(5,6)] = 6.675\n            self.int_freqs[(6,7)] = 6.678\n            self.int_freqs[(7,8)] = 6.677\n            self.int_freqs[(8,9)] = 6.635\n            self.int_freqs[(10,11)] = 6.628\n            self.int_freqs[(11,12)] = 6.632\n            self.int_freqs[(12,13)] = 6.631\n            self.int_freqs[(13,14)] = 6.646\n            self.int_freqs[(15,16)] = 6.693\n            self.int_freqs[(16,17)] = 6.690\n            self.int_freqs[(17,18)] = 6.690\n            self.int_freqs[(18,19)] = 6.631\n            self.int_freqs[(20,21)] = 6.753\n            self.int_freqs[(21,22)] = 6.766\n            self.int_freqs[(22,23)] = 6.743\n            self.int_freqs[(23,24)] = 6.594\n\n            self.int_freqs[(0,5)] = 6.648\n            self.int_freqs[(1,6)] = 6.617\n            self.int_freqs[(2,7)] = 6.650\n            self.int_freqs[(3,8)] = 6.657\n            self.int_freqs[(4,9)] = 6.585\n            self.int_freqs[(5,10)] = 6.660\n            self.int_freqs[(6,11)] = 6.640\n            self.int_freqs[(7,12)] = 6.667\n            self.int_freqs[(8,13)] = 6.645\n            self.int_freqs[(9,14)] = 6.646\n            self.int_freqs[(10,15)] = 6.670\n            self.int_freqs[(11,16)] = 6.646\n            self.int_freqs[(12,17)] = 6.680\n            self.int_freqs[(13,18)] = 6.645\n            self.int_freqs[(14,19)] = 6.646\n            self.int_freqs[(15,20)] = 6.741\n            self.int_freqs[(16,21)] = 6.704\n            self.int_freqs[(17,22)] = 6.712\n            self.int_freqs[(18,23)] = 6.703\n            self.int_freqs[(19,24)] = 6.594\n\n        self.res_coupling = res_coupling\n        omega_max = max(self.int_freqs.values())\n        omega_min = min(self.int_freqs.values())\n        if omega_max > device.omega_max:\n            print(\"Warning: max freq inconsistent. Device: \" + str(device.omega_max) + \", Sycamore_device: \" + str(omega_max))\n            self.omega_max = omega_max\n        if omega_min < device.omega_min:\n            print(\"Warning: min freq inconsistent. Device: \" + str(device.omega_min) + \", Sycamore_device: \" + str(omega_min))\n            self.omega_min = omega_min\n\n    def get_park_freq(self,q):\n        if q not in self.park_freqs:\n            raise Exception(\"Wrong qubit number\")\n        return self.park_freqs[q]\n\n    def get_itr_freq(self,q1,q2):\n        if (q1,q2) in self.int_freqs:\n            return self.int_freqs[(q1,q2)]\n        elif (q2,q1) in self.int_freqs:\n            return self.int_freqs[(q1,q2)]\n        else:\n            raise Exception(\"Coupling not found\")\n", "meta": {"hexsha": "daa76581eaa3dc6c0a83a20abdbc10ac86db9001", "size": 6940, "ext": "py", "lang": "Python", "max_stars_repo_path": "fastsc/models/device.py", "max_stars_repo_name": "yongshanding/FastSC", "max_stars_repo_head_hexsha": "c08bf17f30fdc5f8f2906600c632f8131745c69d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-08-24T19:23:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T18:21:51.000Z", "max_issues_repo_path": "fastsc/models/device.py", "max_issues_repo_name": "yongshanding/FastSC", "max_issues_repo_head_hexsha": "c08bf17f30fdc5f8f2906600c632f8131745c69d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fastsc/models/device.py", "max_forks_repo_name": "yongshanding/FastSC", "max_forks_repo_head_hexsha": "c08bf17f30fdc5f8f2906600c632f8131745c69d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-19T16:14:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-09T10:42:11.000Z", "avg_line_length": 44.4871794872, "max_line_length": 246, "alphanum_fraction": 0.5597982709, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 2473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.1650861787577403}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"Interface to the Fermi and HESS catalogs.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport logging\nimport numpy as np\nfrom astropy.table import Table\nfrom astropy.units import Unit, Quantity\nfrom ..spectrum import compute_differential_flux_points\n\n__all__ = [\n    'SEDComponent',\n    'SED',\n    'cube_sed',\n    'add_spec',\n]\n\nlog = logging.getLogger(__name__)\n\nMeV_to_GeV = Unit('MeV').to(Unit('GeV'))\nMeV_to_erg = Unit('MeV').to(Unit('erg'))\n\n\nclass SEDComponent(object):\n    \"\"\"Uniform interface to SED components for the SED class\n    \"\"\"\n\n    def __init__(self, name='', model=None, points=None):\n        \"\"\"\n        @param name: str\n        @type model: spec.spectrum.Spectrum\n        @type points: spec.data.FluxPoints\"\"\"\n        self.name = name\n        self.model = model\n        self.points = points\n\n    def plot(self, model=True, points=True, butterfly=True):\n        if butterfly:\n            self.plot_butterfly()\n        if model:\n            self.plot_model()\n        if points:\n            self.plot_points()\n\n    def plot_model(self):\n        import matplotlib.pyplot as plt\n        if self.model is None:\n            log.warning('{0}: No model available.'.format(self.name))\n            return\n        x, y = self.model.points(power=2)\n        plt.plot(x * MeV_to_GeV, y * MeV_to_erg, label=self.name)\n\n    def plot_points(self, color='black', markerfacecolor='black'):\n        import matplotlib.pyplot as plt\n        if self.points is None:\n            log.warning('{0}: No points available.'.format(self.name))\n            return\n        # Note: We plot each point individually because anyway\n        # upper limits have to be plotted differently which I\n        # think is not possible because the marker argument doesn't\n        # take arrays.\n        for ii in range(len(self.points)):\n            x, exl, exh, y, eyl, eyh, ul = self.points[ii]\n            if ul:\n                marker = ' '\n                lolims = True\n                eyl, eyh = 5 / 10. * y, 0\n            else:\n                marker = 'o'\n                lolims = False\n            plt.plot(MeV_to_GeV * x, y)\n            plt.errorbar(x, y, [eyl, eyh], [exl, exh], lolims=lolims,\n                         marker=marker, color=color,\n                         markerfacecolor=markerfacecolor,\n                         label=self.name)\n\n    def plot_butterfly(self):\n        pass\n\n\nclass SED(list):\n    \"\"\"Class to plot GeV -- TeV SEDs\n\n    Internally the same units as in the Fermi catalog are used:\n    - Energies in MeV\n    - Flux densities in cm^-2 s^-2 MeV^-1\n    - Fluxes in cm^-2 s^-1\n    - Energy fluxes in erg cm^-2 s^-1\"\"\"\n    \"\"\"\n    def add_Fermi(self, name):\n        try:\n            self._fermi\n            self.append(self._fermi.sed_component(name))\n        except\n        component = catalog.sed_component(name)\n        self.append(component)\n    \"\"\"\n\n    def add(self, names, catalogs):\n        for name in names:\n            for catalog in catalogs:\n                try:\n                    component = catalog.sed_component(name)\n                    self.append(component)\n                    log.info('%s found in %s',\n                             name, catalog.table.table_name)\n                except ValueError as e:\n                    log.warning(e)\n                    log.warning('%s not found in %s',\n                                name, catalog.table.table_name)\n                    pass\n\n    def plot(self, filename='sed.png', xlim=(8e-2, 2e5), ylim=(1e-14, 1e-8)):\n        import matplotlib.pyplot as plt\n        plt.figure()\n        plt.ylabel(r'E$^2$ dF/DE (erg cm$^{-2}$ s$^{-1}$)')\n        plt.xlabel('Energy (GeV)')\n        plt.loglog()\n        log.info('Plotting {0} components in SED'.format(len(self)))\n        for component in self:\n            component.plot()\n        plt.xlim(xlim)\n        plt.ylim(ylim)\n        plt.legend()\n        log.info('Writing {0}'.format(filename))\n        plt.savefig(filename)\n\n    def add_component(self, catalog_format, catalog_name,\n                      object_name, plot_pivot=False, **ecpl_params):\n        \"\"\" Read necessary parameters from FITS file and plot butterfly\n\n        Parameters:\n        catalog_format = 'hess', 'fermi'\n        catalog_name = FITS file name\n        object_name  = object name string in 'name' column\n\n        Note: Since every catalog has columns with different\n        names and units, a general SED plotting is not possible.\n        Instead for each catalog type a handler function that\n        deals converts to a standard format is called.\n\n        @todo: Possibly pass plotting parameters along here by\n        appending them to the ecpl_params dictionary\n        -> I don't think this works at the moment!!!\"\"\"\n        from atpy import Table\n        # Get the catalog from file and initialize some things\n        self.catalog_format = catalog_format\n        self.catalog_name = catalog_name\n        self.object_name = object_name\n        self.catalog = Table(catalog_name).data\n        # Build a dictionary of parameters needed for the plot\n        self.ecpl_params = ecpl_params\n        self.get_ecpl_params()\n        # Plot curve\n        self.plot_ecpl(plot_pivot=plot_pivot, **ecpl_params)\n        # Plot points if present\n        if self.plot_points is not None:\n            # Get the values needed for plotting\n            e = self.plot_points[0]\n            f = self.plot_points[1]\n            f_err = self.plot_points[2]\n            e_err = self.plot_points[3]\n            is_ul = self.plot_points[4]\n            for ii in range(e.size):\n                self.plot_point(e[ii], f[ii],\n                                f_err=f_err[ii],\n                                e_err=[[e_err[0][ii]], [e_err[1][ii]]],\n                                ul=is_ul[ii])\n            # Remove so that it doesn't get plotted again.\n            self.plot_points = None\n\n    def get_ecpl_params(self):\n        \"\"\"Build self.ecpl_params dictionary\n        by parsing one of the supported catalogs\"\"\"\n        if self.catalog_format == 'hess':\n            self.get_ecpl_params_hess_cat()\n        elif self.catalog_format == 'fermi':\n            self.get_ecpl_params_fermi_cat()\n        # Change numpy types to regular types\n        # and replace nan values with 0\n        for key, value in self.ecpl_params.items():\n            if isinstance(value, np.float32):\n                value = float(value)\n            if isinstance(value, np.int16):\n                value = int(value)\n\n    def get_ecpl_params_fermi_cat(self):\n        \"\"\" Build self.ecpl_params dictionary from Fermi catalog fields \"\"\"\n        i = self.find_object_index('source_name')\n        # Set all plot parameters:\n        self.ecpl_params['e_pivot'] = self.catalog.field('Pivot_Energy')[i]\n        self.ecpl_params['e_min'] = 1e2\n        self.ecpl_params['e_max'] = 1e5\n        self.ecpl_params['e_cut'] = 0.0\n        self.ecpl_params['e_cut_err'] = 0.0\n        self.ecpl_params['e_scale'] = 1\n        self.ecpl_params['norm'] = self.catalog.field('Flux_Density')[i]\n        self.ecpl_params['norm_err'] = self.catalog.field('Unc_Flux_Density')[i]\n        self.ecpl_params['norm_scale'] = 1\n        self.ecpl_params['index'] = self.catalog.field('Spectral_Index')[i]\n        self.ecpl_params['index_err'] = self.catalog.field('Unc_Spectral_Index')[i]\n        self.ecpl_params['color'] = 'green'\n        self.ecpl_params['butterfly'] = True\n        # Set flux point data\n        self.plot_points = self.get_flux_points_fermi(i)\n        # Add text label\n        fmt = '%s\\n%s, %s\\n' + \\\n              r'S = %3.1f, C = %3.1f, $\\Gamma = %1.2f \\pm %1.2f$'\n        values = (self.object_name,\n                  self.catalog.field('class1')[i],\n                  self.catalog.field('assoc1')[i],\n                  self.catalog.field('signif_avg')[i],\n                  self.catalog.field('curvature_index')[i],\n                  self.catalog.field('spectral_index')[i],\n                  self.catalog.field('unc_spectral_index')[i]\n                  )\n        self.ax.text(0.05, 0.95, fmt % values,\n                     horizontalalignment='left',\n                     verticalalignment='top',\n                     transform=self.ax.transAxes)\n\n\ndef add_spec(frame, model, xlim, npoints=100, **plot_params):\n    \"\"\"Add a spectral component to a frame.\n\n    frame = matplotlib.Axes object\n    model = [function, parameters, constants]\n    xlim  = [xmin, xmax]\"\"\"\n    # Unpack model\n    f, p, c = model\n    # Compute x and y values\n    logx = np.linspace(np.log10(xlim[0]), np.log10(xlim[1]), npoints)\n    x = 10 ** logx\n    y = f(p, c, x)\n    frame.plot(x, y, **plot_params)\n\n\ndef add_crab(ax):\n    \"\"\"Add the Fermi and HESS Crab SED to test scaling.\"\"\"\n    pass\n    # The HESS butterfly\n    # Note: The HESS catalog contains energies in TeV and flux norm in 1e-12 cm^-2 s^-1 TeV^-1\n    \"\"\"\n    add_sed_component(ax, e0 = 1, e1 = 1e-2, e2 = 1e2,\n                      norm = 10, norm_err = 0, index = 2., index_err = 0.0,\n                      e_scale = 1e12, norm_scale = 1e-12 * 1e-12, e_cut = 10, e_cut_err = 3,\n                      color='b', butterfly = True)\n    # The Fermi butterfly\n    add__sed_component(ax, e0 = 494, e1 = 1e2, e2 = 1e6,\n                       norm = 1e-9, norm_err = 6.7e-11, index = 2.3, index_err = 0.1,\n                       e_scale = 1e6, norm_scale = 1e-6, color='g', butterfly = True)\n    # Add published fermi result\n    \"\"\"\n\n\ndef cube_sed(cube, mask=None, flux_type='differential', counts=None,\n             errors=False, standard_error=0.1, spectral_index=2.3):\n    \"\"\"Creates SED from SkyCube within given lat and lon range.\n\n    Parameters\n    ----------\n    cube : `~gammapy.data.SkyCube`\n        Spectral cube of either differential or integral fluxes (specified\n        with flux_type)\n    mask : array_like, optional\n        2D mask array, matching spatial dimensions of input cube.\n        A mask value of True indicates a value that should be ignored,\n        while a mask value of False indicates a valid value.\n    flux_type : {'differential', 'integral'}\n        Specify whether input cube includes differential or integral fluxes.\n    counts :  `~gammapy.data.SkyCube`, optional\n        Counts cube to allow Poisson errors to be calculated. If not provided,\n        a standard_error should be provided, or zero errors will be returned.\n    errors : bool\n        If True, computes errors, if possible, according to provided inputs.\n        If False (default), returns all errors as zero.\n    standard_error : float\n        If counts cube not provided, but error values required, this specifies\n        a standard fractional error to be applied to values. Default = 0.1.\n    spectral_index : float\n        If integral flux is provided, this is used to calculate differential\n        fluxes and energies (according to the Lafferty & Wyatt model-based\n        method, assuming a power-law model).\n\n    Returns\n    -------\n    table : `~astropy.table.Table`\n        A spectral energy table of energies, differential fluxes and\n        differential flux errors. Units as those input.\n    \"\"\"\n\n    values = []\n    for i in np.arange(cube.data.shape[0]):\n        if mask is None:\n            bin = cube.data[i].sum()\n        else:\n            bin = cube.data[i][mask].sum()\n        values.append(bin.value)\n    values = np.array(values)\n\n    if errors:\n        if counts is None:\n            # Counts cube required to calculate poisson errors\n            errors = np.ones_like(values) * standard_error\n        else:\n            errors = []\n            for i in np.arange(counts.data.shape[0]):\n                if mask is None:\n                    bin = counts.data[i].sum()\n                else:\n                    bin = counts.data[i][mask].sum()\n                r_error = 1. / (np.sqrt(bin.value))\n                errors.append(r_error)\n            errors = np.array(errors)\n    else:\n        errors = np.zeros_like(values)\n\n    if flux_type == 'differential':\n        energy = cube.energy\n        table = Table()\n        table['ENERGY'] = energy\n        table['DIFF_FLUX'] = Quantity(values, cube.data.unit)\n        table['DIFF_FLUX_ERR_HI'] = Quantity(errors * values, cube.data.unit)\n        table['DIFF_FLUX_ERR_LO'] = Quantity(-errors * values, cube.data.unit)\n\n    elif flux_type == 'integral':\n\n        emins = cube.energy[:-1]\n        emaxs = cube.energy[1:]\n        table = compute_differential_flux_points(x_method='lafferty',\n                                                 y_method='power_law',\n                                                 spectral_index=spectral_index,\n                                                 energy_min=emins, energy_max=emaxs,\n                                                 int_flux=values,\n                                                 int_flux_err_hi=errors * values,\n                                                 int_flux_err_lo=-errors * values)\n\n    else:\n        raise ValueError('Unknown flux_type: {0}'.format(flux_type))\n\n    return table\n", "meta": {"hexsha": "8f693887706aa89db4f573df020114e9863412d4", "size": 13107, "ext": "py", "lang": "Python", "max_stars_repo_path": "gammapy/spectrum/sed.py", "max_stars_repo_name": "grburgess/gammapy", "max_stars_repo_head_hexsha": "609e460698caca7223afeef5e71826c7b32728d1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-01-28T12:21:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-10T19:58:07.000Z", "max_issues_repo_path": "gammapy/spectrum/sed.py", "max_issues_repo_name": "grburgess/gammapy", "max_issues_repo_head_hexsha": "609e460698caca7223afeef5e71826c7b32728d1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gammapy/spectrum/sed.py", "max_forks_repo_name": "grburgess/gammapy", "max_forks_repo_head_hexsha": "609e460698caca7223afeef5e71826c7b32728d1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3245614035, "max_line_length": 94, "alphanum_fraction": 0.5720607309, "include": true, "reason": "import numpy,from astropy", "num_tokens": 3097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.3040416623541848, "lm_q1q2_score": 0.16505305954409746}}
{"text": "import numpy as np\nfrom KiMonETSim.conversion_functions import from_ev_to_au, from_ns_to_au\n\n\n\"\"\"\nCOMENTARI INICIAL: Els estats (fonamental i excitats) s'indicaran per mitjà d'etiquetes tipus string. Els estats possibles \ni les seves respectives referències hauran de venir indicades a l'inici del programa, e.g, quan s'inicialitzi la \nmolècula genèrica. Aquestes referències s'usaran per caracteritzar la variable estat i per simplicitat i eficiència\ns'usaran com a claus dels diccionaris que contenguin informació sobre els excitons. A saber: state_energies, \nrelaxation_energies, exciton_energies, (REFERENTS A RATES...).\n\nINICIALITZACIÓ DE LA MOLÈCULA GENÈRICA:\n    -state_energies: diccionari amb les energies d'excitació de cada estat de la molècula:\n                :key: energia de l'estat excitat\n                :argument:  energia de l'estat\n    -relaxation_energies: diccionari amb les energies de relaxació de cada estat. Per ara en prenem una fitxa i què depèn\n    sols de cada estat.\n                :key: energia de l'estat excitat\n                :argument:  energia de relaxació de l'estat\n    -transition_moment: moment de transició dipolar de la molècula. Donat com un vector (llista de 3 elements) en el \n    sistema de referència de la molècula.\n    \nPer defecte venen donats:\n    -characteristic_length: defineix les dimensions finites de la molècula. Aquesta s'aproxima com una línia, quadrat o \n    cub i aquest paràmetre en defineix el costat. Alternativament podriem fer una aproximació esfèrica i que en sigui \n    el radi.\n    -coordinates. D'entrada la suposam en l'origen. \n    -orientation. D'entrada la suposam orientada segons [1, 0, 0]. Aquest vector ve donat en un SR extern que \n    anomenarem global.\n    Aquests dos darrers paràmetres no són estrictament necessaris per estudiar la naturalesa del tipus de molècula.\n    La classe inclou 2 mètodes per cada un d'aquests 2 darrers paràmetres. Un per inicialitzar-los (defineix de manera\n    la posició/orientació com un 3-array) i un per cridar-los alhora d'operar (per assegurar que no s'alteren en el procés).\n    Noms:\n    initialize_coordinates(coordinates)                  initialize_orientation(orientation)\n    molecular_coordinates()                              molecular_orientation()\n\nMètodes de la molècula:\nApart dels 4 ja comentats la classe molècula inclou:\n    - electronic_state. Mètode que retorna l'estat electrònic de la molecula\n    - get_relaxation_state_energy. Mètode que dóna l'energia de relaxació de l'estat en què es troba la molècula\n    - change_state(new_state): Canvia l'estat de la molècula pel nou donat.\n    - decay_rates: mètode que retorna un diccionari amb els possibles rates de decaïment {'decay process': rate}\n    - get_transition_moment(reference_orientation). Necessita com argument un vector de referència. L'orientació de la\n        molècula en la qual el moment de transició en el SR de la molècula i en el SR global coindideixen. \n        Aleshores, donada aquesta referència i l'orientació de la molècula, aquest mètode fa un canvi de base i retorna\n        el moment de transició dipolar en el SR global.\n\"\"\"\n\n\nclass Molecule:\n\n    def __init__(self,\n                 state_energies,\n                 reorganization_energies,\n                 transition_moment,\n                 dipole_moment_direction=[1, 0, 0],                 # unity vector\n                 state='gs',\n                 characteristic_length=10**(-8),\n                 coordinates=[0, 0, 0],\n                 orientation=[1, 0, 0]):                            # unity vector\n        \"\"\"\n        :param states_energies: dictionary {'state': energy}\n        :param state: sting of the name of the state\n        The name of the state should coincide with some key of the dictionary in order to identify the state with\n        its energy.\n        :param reorganization_energies: dictionary {'state': relaxation energy of the state}\n        Names of 'state' would be: g_s (ground state), s_1 (first singlet), t_1 (first triplet), etc.\n        Energies should be given with eV.\n\n\n        :param transition_moment: Dipole transition moment vector (3d). The vector is given in respect to the RS\n        of the molecule. So for all molecules of a same type if will be equal.\n        This dipole moment is given in atomic units.\n\n        :param dipole_moment_direction: Gives a referene direction This reference direction is the molecular orientation\n        in which the transition dipole moment in the molecular reference system coincides with the itself in the\n        global reference system. Given by default as [1,0,0]\n\n        :param characteristic_length: We consider a finite size molecule. The simplified shape of the molecule\n        is longitudinal, squared or cubic and is defined with this characteristic length. Units: nm\n\n        :param coordinates: 3d vector. Gives the position of the molecule in the system (in general the 0 position\n        will coincide with the center of the distribution). Units: nm. If the system has less than 3 dimensions,\n        the extra coordinates will be taken as 0.\n        :param orientation: 3d unit vector. Gives the orientation of the molecule in the global reference system.\n        \"\"\"\n\n        self.state_energies = state_energies\n        self.state = state\n        self.reorganization_energies = reorganization_energies\n        self.transition_moment = np.array(transition_moment)\n        self.dipole_moment_direction = np.array(dipole_moment_direction)        # unity vector\n        self.characteristic_length = characteristic_length\n        self.coordinates = np.array(coordinates)\n        self.orientation = np.array(orientation)                                # unity vector\n\n    def initialize_coordinates(self, coordinate_list):\n        \"\"\"\n        :param coordinate_list: List [x, y, z] with the coordinates of the molecule. Units: nm\n        Changes self.coordinates to this new position. Format: numpy array.\n        \"\"\"\n        self.coordinates = np.array(coordinate_list)\n\n    def molecular_coordinates(self):\n        \"\"\"\n        :return: Array with the molecular coordinates.\n        \"\"\"\n        return self.coordinates\n\n    def initialize_orientation(self, orientation):\n        \"\"\"\n        :param orientation: list with the coordinates of the orientation vector\n        Changes self.orientation to this new orientation. Format: numpy array\n        \"\"\"\n        self.orientation = np.array(orientation)\n\n    def molecular_orientation(self):\n        \"\"\"\n        :return: Array with the molecular orientation\n        \"\"\"\n        return self.orientation\n\n    def get_reorganization_state_energy(self):\n        return self.reorganization_energies[self.state]\n\n    def electronic_state(self):\n        \"\"\"\n        :return: the electronic state of the molecule\n        \"\"\"\n        return self.state\n\n    def set_state(self, new_state):\n        \"\"\"\n        :param new_state:\n        No return method. Only changes the molecular state when the exciton is transferred.\n        \"\"\"\n        self.state = new_state\n\n    def desexcitation_energies(self):\n        \"\"\"\n        IS NOT USED (19/08/2019).\n        Given an electronic state, calculates the possible desexcitation energy. Generates and sorts\n        a list with the energies, then calculates the possible desexcitation energies (the energy difference\n        between the given state and the less energetic states).\n        :return: Dictionary with the decay processes as key, e.g. 'State1_to_State0', and the energy as argument\n        \"\"\"\n        desexcitations = {}\n\n        for state_key in self.state_energies:\n            if self.state_energies[self.state] > self.state_energies[state_key]:\n                decay_process = 'from_'+self.state+'_to_'+state_key\n                energy_gap = self.state_energies[self.state] - self.state_energies[state_key]\n                desexcitations[decay_process] = energy_gap\n\n        return desexcitations\n\n    def decay_rates(self):\n        \"\"\"\n        :return: A list of two elements: list of the possible decay processes and another with the respective rates\n        for a given electronic state.\n\n        More if(s) entrances shall be added if more electronic states are considered.\n        \"\"\"\n\n        decay_rates = {}\n\n        if self.state == 'gs':\n            process = 'No decay for a molecule at the ground state.'\n            print(process)\n            decay_rates[process] = 0\n\n        elif self.state == 's1':\n\n            desexcitation_energy = self.state_energies[self.state] - self.state_energies['gs']      # energy in eV\n            desexcitation_energy = from_ev_to_au(desexcitation_energy, 'direct')                    # energy in a.u.\n\n            u = np.linalg.norm(self.transition_moment)              # transition moment norm.\n            c = 137                                                 # light speed in atomic units\n\n            rate = 4 * desexcitation_energy**3 * u**2 / (3 * c**3)\n            decay_process = 'Singlet_radiative_decay'\n            # for a first singlet state only radiative decay is considered.\n\n            decay_rates[decay_process] = from_ns_to_au(rate, 'direct')\n\n        return decay_rates\n\n    def get_transition_moment(self):\n        \"\"\"\n        This method computes a basis transformation in order to get the transition dipole moment in a global\n        reference coordinate system. This system is described by the dipole_moment_direction\n        When the molecule is orientated in this way the transition_moment in the RS system of the molecule\n        and in the global RS coincides. Else, we can say that the molecule is rotated and the rotation angle\n        is given by the inner product between the reference_orientation and molecule_orientation vectors\n        :return: The t.d.m in the global reference system\n        \"\"\"\n\n        # compute the director cosinus of the rotation (inner product)\n        cos_director = np.dot(self.dipole_moment_direction, self.orientation)\n\n        # construct the rotation matrix\n        sin_director = np.sqrt(1-cos_director**2)\n\n        rotation_matrix = np.array([[cos_director, -sin_director, 0],\n                                    [sin_director, cos_director, 0],\n                                    [0,                 0,       0]])\n\n        # basis transform (matrix product)\n        return np.dot(rotation_matrix, self.transition_moment)\n\n\n", "meta": {"hexsha": "3f90490f49bced60218654b406d02ec78471d228", "size": 10408, "ext": "py", "lang": "Python", "max_stars_repo_path": "KiMonETSim/molecules.py", "max_stars_repo_name": "MaciaMutSbert/General_KMC", "max_stars_repo_head_hexsha": "570e62c622d9e32c4e89d1688549946549b1af8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-30T07:44:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T07:44:15.000Z", "max_issues_repo_path": "KiMonETSim/molecules.py", "max_issues_repo_name": "MaciaMutSbert/General_KMC", "max_issues_repo_head_hexsha": "570e62c622d9e32c4e89d1688549946549b1af8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "KiMonETSim/molecules.py", "max_forks_repo_name": "MaciaMutSbert/General_KMC", "max_forks_repo_head_hexsha": "570e62c622d9e32c4e89d1688549946549b1af8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-10-08T10:45:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-22T08:00:28.000Z", "avg_line_length": 49.0943396226, "max_line_length": 124, "alphanum_fraction": 0.6729438893, "include": true, "reason": "import numpy", "num_tokens": 2445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.16504377539910695}}
{"text": "license=\"\"\"\n   Copyright (C) 2015 James Annis\n\n   This program is free software; you can redistribute it and/or modify it\n   under the terms of version 3 of the GNU General Public License as\n   published by the Free Software Foundation.\n\n   More to the points- this code is science code: buggy, barely working,\n   with little or no documentation. Science code in the the alpine fast \n   & light style. (Note the rate at which people who stand on the\n   summit of K2 to successfully make it down.)\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\"\"\"\n\nimport numpy as np\nimport decam2hp\n\n#\n# Example usage\n#\n#    obs.resetTime(mjd+time)\n#    obs.limitMag(\"i\", exposure=90)\n#\n#    sm=sourceProb.map(obs);\n#    models_at_t = modelsAtTimeT (models, time)\n#    abs_mag = models_at_t[0]\n#    sm.modelAbsoluteMagnitude = abs_mag\n#    sm.searchDistance = np.array([distance,])\n#    sm.calculateProb()\n#\n#    raHex, decHex, idHex, hexVals, rank = cutAndHexalate (obs, sm, raHexen, decHexen)\n\n#\n# Given an obs object and a sm object, along with a map of hex centers,\n# this routine returns the sum of the probability inside of DECam camera outlines\n# for all hexes in the map, along with a rank of the hexes sorted from large to small.\n#\n# domain knowlege- the blanco cuts keep everything inside an hour angle range\ndef hexalateNHexes (obs, sm, nHexes, allskyDesHexes) :\n    raHexen, decHexen, idHexen, hexVals, rank = cutAndHexalate(obs, sm, allskyDesHexes)\n    raHexen = raHexen[0:nHexes]\n    decHexen = decHexen[0:nHexes]\n    idHexen = idHexen[0:nHexes]\n    hexVals = hexVals[0:nHexes]\n    rank = rank[0:nHexes]\n    return raHexen, decHexen, idHexen, hexVals, rank\n\n# be aware that while most of my ra,dec are in degrees,\n# those in obs and sm are in radians\ndef cutAndHexalate (obs, sm, camera, hexFile) :\n    #allskyDesHexes=\"../data/all-sky-hexCenters-\"+camera+\".txt\"\n    raHexen, decHexen, idHexen = getHexCenters(hexFile)\n    raHexen, decHexen, idHexen, hexVals, rank = cutAndHexalateOnRaDec(\n        obs, sm, raHexen, decHexen, idHexen, camera)\n    return raHexen, decHexen, idHexen, hexVals, rank\n\n\ndef cutAndHexalateOnRaDec (obs, sm, raHexen, decHexen, idHexen, tree, camera, cutProbs=False) :\n    #cutProbs calls without Overlap\n    verbose = False\n    obsHourAngle = obs.ha*360./(2*np.pi)\n    obsRa        = obs.ra*360./(2*np.pi)\n    obsDec       = obs.dec*360./(2*np.pi)\n    # based on blanco horizen limits  (may not be needed with tree)                                                                                                                          \n    ix = (abs(obsHourAngle) <= 83. ) & (obsDec < 43.)\n    ix2 = decHexen < 43.\n\n    probabilities = obs.map*sm.probMap\n    if verbose  :\n        print \"\\t cutAndHexalate probabilities sum\",probabilities.sum()\n\n    hexVals = np.zeros(raHexen.size)\n    if not cutProbs:\n        hexVals[ix2] = decam2hp.hexalateMap(obsRa,obsDec, probabilities, tree,\n                                            raHexen[ix2], decHexen[ix2], camera, verbose=False)\n    else:\n        hexVals[ix2] = decam2hp.hexalateMapWithoutOverlap(obsRa,obsDec, probabilities, tree,\n                                            raHexen[ix2], decHexen[ix2], camera, verbose=False)\n    if verbose  :\n        print \"hexVals max\", hexVals.max()\n    rank=np.argsort(hexVals);\n    rank = rank[::-1];# sort from large to small by flipping natural argsort order                                                                                                   \n \n    return raHexen, decHexen, idHexen, hexVals, rank\n\n\ndef getHexCenters (hexFile) :\n    #allskyDesHexes=\"../data/all-sky-hexCenters-\"+camera+\".txt\"\n    ra,dec = np.genfromtxt(hexFile, unpack=True, \\\n        usecols=(0,1),comments=\"#\")\n    hex_id = getHexId(ra,dec)\n    return ra,dec,hex_id\n\n#\n# a modified DES convention: just rounded ra,dec with + or - sign\n# of type \"24-31\", \"179+10\"\ndef getHexId(ra, dec) :\n    intra = np.round(ra)\n    intdec = np.abs(np.round(dec));\n    sign=np.full(ra.size, \"+\",dtype=\"str\");\n    ix = dec < 0; sign[ix]=\"-\";\n    id = np.array([],dtype=\"str\")\n    for i in range(0,ra.size) :\n        name = str(np.int(intra[i])) + sign[i] + str(np.int(intdec[i]))\n        id = np.append(id, name)\n    return id\n\n\n", "meta": {"hexsha": "7a82b5c31a54c745cea96d978d9cd55776fa93fe", "size": 4627, "ext": "py", "lang": "Python", "max_stars_repo_path": "gwtarget/DESI_mainInjector/Main-Injector-master/python/hexalate.py", "max_stars_repo_name": "rknop/timedomain", "max_stars_repo_head_hexsha": "d3e3c43dfbb9cadc150ea04024d9b4132cb9ca17", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-18T05:25:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-18T05:25:27.000Z", "max_issues_repo_path": "gwtarget/DESI_mainInjector/Main-Injector-master/python/hexalate.py", "max_issues_repo_name": "MatthewPortman/timedomain", "max_issues_repo_head_hexsha": "b9c6c2e6804d7dde56311d9402769be545d505d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gwtarget/DESI_mainInjector/Main-Injector-master/python/hexalate.py", "max_forks_repo_name": "MatthewPortman/timedomain", "max_forks_repo_head_hexsha": "b9c6c2e6804d7dde56311d9402769be545d505d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.547008547, "max_line_length": 189, "alphanum_fraction": 0.6416684677, "include": true, "reason": "import numpy", "num_tokens": 1290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.16504377200862788}}
{"text": "#!/usr/bin/env python\n\"\"\"\nfeffdat  provides the following function related to\nreading and dealing with Feff.data files in larch:\n\n  path1 = read_feffdat('feffNNNN.dat')\n\nreturns a Feff Group -- a special variation of a Group -- for\nthe path represented by the feffNNNN.dat\n\n  group  = ff2chi(paths)\n\ncreates a group that contains the chi(k) for the sum of paths.\n\"\"\"\nimport numpy as np\nfrom copy import deepcopy\nfrom scipy.interpolate import UnivariateSpline\nfrom lmfit import Parameters, Parameter\nfrom lmfit.printfuncs import gformat\n\nfrom xraydb import atomic_mass, atomic_symbol\n\nfrom larch import Group, isNamedClass\nfrom larch.utils.strutils import fix_varname, b32hash\nfrom larch.fitting import group2params, isParameter, param_value\n\nfrom .xafsutils import ETOK, set_xafsGroup\nfrom .sigma2_models import add_sigma2funcs\n\nSMALL_ENERGY = 1.e-6\n\nclass FeffDatFile(Group):\n    def __init__(self, filename,  **kws):\n        kwargs = dict(name='feff.dat: %s' % filename)\n        kwargs.update(kws)\n        Group.__init__(self,  **kwargs)\n        self._read(filename)\n\n    def __repr__(self):\n        if self.filename is not None:\n            return '<Feff.dat File Group: %s>' % self.filename\n        return '<Feff.dat File Group (empty)>'\n\n    def __copy__(self):\n        return FeffDatFile(filename=self.filename)\n\n    def __deepcopy__(self, memo):\n        return FeffDatFile(filename=self.filename)\n\n    @property\n    def reff(self): return self.__reff__\n\n    @reff.setter\n    def reff(self, val):     pass\n\n    @property\n    def nleg(self): return self.__nleg__\n\n    @nleg.setter\n    def nleg(self, val):     pass\n\n    @property\n    def rmass(self):\n        \"\"\"reduced mass for a path\"\"\"\n        if self.__rmass is None:\n            rmass = 0\n            for atsym, iz, ipot, amass, x, y, z in self.geom:\n                rmass += 1.0/max(1., amass)\n            self.__rmass = 1./rmass\n        return self.__rmass\n\n    @rmass.setter\n    def rmass(self, val):     pass\n\n    def _read(self, filename):\n        try:\n            with open(filename, 'r') as fh:\n                lines = fh.readlines()\n        except:\n            print( 'Error reading file %s ' % filename)\n            return\n        self.filename = filename\n        mode = 'header'\n        self.potentials, self.geom = [], []\n        data = []\n        pcounter = 0\n        iline = 0\n        for line in lines:\n            iline += 1\n            line = line[:-1]\n            if line.startswith('#'): line = line[1:]\n            line = line.strip()\n            if iline == 1:\n                self.title = line[:64].strip()\n                self.version = line[64:].strip()\n                continue\n            if line.startswith('k') and line.endswith('real[p]@#'):\n                mode = 'arrays'\n                continue\n            elif '----' in line[2:10]:\n                mode = 'path'\n                continue\n            #\n            if (mode == 'header' and\n                line.startswith('Abs') or line.startswith('Pot')):\n                words = line.replace('=', ' ').split()\n                ipot, z, rmt, rnm = (0, 0, 0, 0)\n                words.pop(0)\n                if line.startswith('Pot'):\n                    ipot = int(words.pop(0))\n                iz = int(words[1])\n                rmt = float(words[3])\n                rnm = float(words[5])\n                self.potentials.append((ipot, iz, rmt, rnm))\n            elif mode == 'header' and line.startswith('Gam_ch'):\n                words  = line.replace('=', ' ').split(' ', 2)\n                self.gam_ch = float(words[1])\n                self.exch   = words[2]\n            elif mode == 'header' and line.startswith('Mu'):\n                words  = line.replace('=', ' ').split()\n                self.mu = float(words[1])\n                self.kf = float(words[3])\n                self.vint = float(words[5])\n                self.rs_int= float(words[7])\n            elif mode == 'path':\n                pcounter += 1\n                if pcounter == 1:\n                    w = [float(x) for x in line.split()[:5]]\n                    self.__nleg__ = int(w.pop(0))\n                    self.degen, self.__reff__, self.rnorman, self.edge = w\n                elif pcounter > 2:\n                    words = line.split()\n                    xyz = [float(x) for x in words[:3]]\n                    ipot = int(words[3])\n                    iz   = int(words[4])\n                    if len(words) > 5:\n                        lab = words[5]\n                    else:\n                        lab = atomic_symbol(iz)\n                    amass = atomic_mass(iz)\n                    geom = [lab, iz, ipot, amass] + xyz\n                    self.geom.append(tuple(geom))\n            elif mode == 'arrays':\n                d = np.array([float(x) for x in line.split()])\n                if len(d) == 7:\n                    data.append(d)\n        data = np.array(data).transpose()\n        self.k        = data[0]\n        self.real_phc = data[1]\n        self.mag_feff = data[2]\n        self.pha_feff = data[3]\n        self.red_fact = data[4]\n        self.lam = data[5]\n        self.rep = data[6]\n        self.pha = data[1] + data[3]\n        self.amp = data[2] * data[4]\n        self.__rmass = None  # reduced mass of path\n\n\nPATH_PARS = ('degen', 's02', 'e0', 'ei', 'deltar', 'sigma2', 'third', 'fourth')\n\nclass FeffPathGroup(Group):\n    def __init__(self, filename, label=None, s02=None, degen=None,\n                 e0=None, ei=None, deltar=None, sigma2=None, third=None,\n                 fourth=None, _larch=None, **kws):\n\n        kwargs = dict(name='FeffPath: %s' % filename)\n        kwargs.update(kws)\n        Group.__init__(self, **kwargs)\n        self.filename = filename\n        self.params = None\n        self.label = label\n        self.spline_coefs = None\n\n        self._feffdat = FeffDatFile(filename=filename)\n        self.geom  = self._feffdat.geom\n        def_degen  = self._feffdat.degen\n\n        self.hashkey = self.__geom2label()\n        self.label = label if label is not None else self.hashkey\n\n        self.degen = def_degen if degen  is None else degen\n        self.s02    = 1.0      if s02    is None else s02\n        self.e0     = 0.0      if e0     is None else e0\n        self.ei     = 0.0      if ei     is None else ei\n        self.deltar = 0.0      if deltar is None else deltar\n        self.sigma2 = 0.0      if sigma2 is None else sigma2\n        self.third  = 0.0      if third  is None else third\n        self.fourth = 0.0      if fourth is None else fourth\n\n        self.k = None\n        self.chi = None\n        if self._feffdat is not None:\n            self.create_spline_coefs()\n\n    def __geom2label(self):\n        \"\"\"generate label by hashing path geometry\"\"\"\n        rep = [self._feffdat.degen, self._feffdat.reff]\n        for atom in self.geom:\n            rep.extend(atom)\n\n        for attr in ('s02', 'e0', 'ei', 'deltar', 'sigma2', 'third', 'fourth'):\n            rep.append(getattr(self, attr, '_'))\n        s = \"|\".join([str(i) for i in rep])\n        return \"p%s\" % (b32hash(s)[:10].lower())\n\n    def pathpar_name(self, parname):\n        \"\"\"\n        get internal name of lmfit Parameter for a path paramter, using Path's hashkey\n        \"\"\"\n        return f'{parname}_{self.hashkey}'\n\n    def __copy__(self):\n        return FeffPathGroup(filename=self.filename, label=self.label,\n                             s02=self.s02, degen=self.degen, e0=self.e0,\n                             ei=self.ei, deltar=self.deltar, sigma2=self.sigma2,\n                             third=self.third, fourth=self.fourth)\n\n    def __deepcopy__(self, memo):\n        return FeffPathGroup(filename=self.filename, label=self.label,\n                             s02=self.s02, degen=self.degen, e0=self.e0,\n                             ei=self.ei, deltar=self.deltar, sigma2=self.sigma2,\n                             third=self.third, fourth=self.fourth)\n\n    @property\n    def reff(self): return self._feffdat.reff\n\n    @reff.setter\n    def reff(self, val):  pass\n\n    @property\n    def nleg(self): return self._feffdat.nleg\n\n    @nleg.setter\n    def nleg(self, val):     pass\n\n    @property\n    def rmass(self): return self._feffdat.rmass\n\n    @rmass.setter\n    def rmass(self, val):  pass\n\n    def __repr__(self):\n        return f'<FeffPath Group label={self.label:s}, filename={self.filename:s}>'\n\n    def create_path_params(self, params=None):\n        \"\"\"\n        create Path Parameters within the current lmfit.Parameters namespace\n        \"\"\"\n        if params is not None:\n           self.params = params\n        if self.params is None:\n            self.params = Parameters()\n        if self.params._asteval.symtable.get('sigma2_debye', None) is None:\n            add_sigma2funcs(self.params)\n        if self.label is None:\n            self.label = self.__geom2label()\n        self.store_feffdat()\n        for pname in PATH_PARS:\n            val =  getattr(self, pname)\n            attr = 'value'\n            if isinstance(val, str):\n                attr = 'expr'\n            kws =  {'vary': False, attr: val}\n            parname = self.pathpar_name(pname)\n            self.params.add(parname, **kws)\n            self.params[parname].is_pathparam = True\n\n    def create_spline_coefs(self):\n        \"\"\"pre-calculate spline coefficients for feff data\"\"\"\n        self.spline_coefs = {}\n        fdat = self._feffdat\n        self.spline_coefs['pha'] = UnivariateSpline(fdat.k, fdat.pha, s=0)\n        self.spline_coefs['amp'] = UnivariateSpline(fdat.k, fdat.amp, s=0)\n        self.spline_coefs['rep'] = UnivariateSpline(fdat.k, fdat.rep, s=0)\n        self.spline_coefs['lam'] = UnivariateSpline(fdat.k, fdat.lam, s=0)\n\n    def store_feffdat(self):\n        \"\"\"stores data about this Feff path in the Parameters\n        symbol table for use as `reff` and in sigma2 calcs\n        \"\"\"\n        symtab = self.params._asteval.symtable\n        symtab['feffpath'] = self._feffdat\n        symtab['reff']  = self._feffdat.reff\n\n    def __path_params(self, **kws):\n        \"\"\"evaluate path parameter value.  Returns\n        (degen, s02, e0, ei, deltar, sigma2, third, fourth)\n        \"\"\"\n        # put 'reff' and '_feffdat' into the symboltable so that\n        # they can be used in constraint expressions\n        self.store_feffdat()\n        if self.params is None:\n            self.create_path_params()\n        out = []\n        for pname in PATH_PARS:\n            val = kws.get(pname, None)\n            parname = self.pathpar_name(pname)\n            if val is None:\n                val = self.params[parname]._getval()\n            out.append(val)\n        return out\n\n    def path_paramvals(self, **kws):\n        (deg, s02, e0, ei, delr, ss2, c3, c4) = self.__path_params()\n        return dict(degen=deg, s02=s02, e0=e0, ei=ei, deltar=delr,\n                    sigma2=ss2, third=c3, fourth=c4)\n\n    def report(self):\n        \"return  text report of parameters\"\n        tmpvals = self.__path_params()\n        pathpars = {}\n        for pname in ('degen', 's02', 'e0', 'deltar',\n                      'sigma2', 'third', 'fourth', 'ei'):\n            parname = self.pathpar_name(pname)\n            if parname in self.params:\n                pathpars[pname] = (self.params[parname].value, self.params[parname].stderr)\n\n        out = [f\" = Path '{self.label}' = \",\n               f'    feffdat file = {self.filename}']\n        geomlabel  = '    geometry  atom      x        y        z      ipot'\n        geomformat = '            %4s      % .4f, % .4f, % .4f  %i'\n        out.append(geomlabel)\n\n        for atsym, iz, ipot, amass, x, y, z in self.geom:\n            s = geomformat % (atsym, x, y, z, ipot)\n            if ipot == 0: s = \"%s (absorber)\" % s\n            out.append(s)\n\n        stderrs = {}\n        out.append('     {:7s}= {:s}'.format('reff',\n                                              gformat(self._feffdat.reff)))\n\n        for pname in ('degen', 's02', 'e0', 'r',\n                      'deltar', 'sigma2', 'third', 'fourth', 'ei'):\n            val = strval = getattr(self, pname, 0)\n            parname = self.pathpar_name(pname)\n            std = None\n            if pname == 'r':\n                parname = self.pathpar_name('deltar')\n                par = self.params.get(parname, None)\n                val = par.value + self._feffdat.reff\n                strval = 'reff + ' + getattr(self, 'deltar', 0)\n                std = par.stderr\n            else:\n                if pname in pathpars:\n                    val, std = pathpars[pname]\n                else:\n                    par = self.params.get(parname, None)\n                    if par is not None:\n                        val = par.value\n                        std = par.stderr\n\n            if std is None  or std <= 0:\n                svalue = gformat(val)\n            else:\n                svalue = \"{:s} +/-{:s}\".format(gformat(val), gformat(std))\n            if pname == 's02':\n                pname = 'n*s02'\n\n            svalue = \"     {:7s}= {:s}\".format(pname, svalue)\n            if isinstance(strval, str):\n                svalue = \"{:s}  := '{:s}'\".format(svalue, strval)\n\n            if val == 0 and pname in ('third', 'fourth', 'ei'):\n                continue\n            out.append(svalue)\n        return '\\n'.join(out)\n\n    def calc_chi_from_params(self, params, **kws):\n        \"calculate chi(k) from Parameters, ParameterGroup, and/or kws for path parameters\"\n        if isinstance(params, Parameters):\n            self.create_path_params(params=params)\n        else:\n            self.create_path_params(params=group2params(params))\n        self._calc_chi(**kws)\n\n    def _calc_chi(self, k=None, kmax=None, kstep=None, degen=None, s02=None,\n                 e0=None, ei=None, deltar=None, sigma2=None,\n                 third=None, fourth=None, debug=False, interp='cubic', **kws):\n        \"\"\"calculate chi(k) with the provided parameters\"\"\"\n        fdat = self._feffdat\n        if fdat.reff < 0.05:\n            print('reff is too small to calculate chi(k)')\n            return\n        # make sure we have a k array\n        if k is None:\n            if kmax is None:\n                kmax = 30.0\n            kmax = min(max(fdat.k), kmax)\n            if kstep is None: kstep = 0.05\n            k = kstep * np.arange(int(1.01 + kmax/kstep), dtype='float64')\n\n        reff = fdat.reff\n        # get values for all the path parameters\n        (degen, s02, e0, ei, deltar, sigma2, third, fourth)  = \\\n                self.__path_params(degen=degen, s02=s02, e0=e0, ei=ei,\n                                 deltar=deltar, sigma2=sigma2,\n                                 third=third, fourth=fourth)\n\n        # create e0-shifted energy and k, careful to look for |e0| ~= 0.\n        en = k*k - e0*ETOK\n        if min(abs(en)) < SMALL_ENERGY:\n            try:\n                en[np.where(abs(en) < 1.5*SMALL_ENERGY)] = SMALL_ENERGY\n            except ValueError:\n                pass\n        # q is the e0-shifted wavenumber\n        q = np.sign(en)*np.sqrt(abs(en))\n\n        # lookup Feff.dat values (pha, amp, rep, lam)\n        if interp.startswith('lin'):\n            pha = np.interp(q, fdat.k, fdat.pha)\n            amp = np.interp(q, fdat.k, fdat.amp)\n            rep = np.interp(q, fdat.k, fdat.rep)\n            lam = np.interp(q, fdat.k, fdat.lam)\n        else:\n            pha = self.spline_coefs['pha'](q)\n            amp = self.spline_coefs['amp'](q)\n            rep = self.spline_coefs['rep'](q)\n            lam = self.spline_coefs['lam'](q)\n\n        if debug:\n            self.debug_k   = q\n            self.debug_pha = pha\n            self.debug_amp = amp\n            self.debug_rep = rep\n            self.debug_lam = lam\n\n        # p = complex wavenumber, and its square:\n        pp   = (rep + 1j/lam)**2 + 1j * ei * ETOK\n        p    = np.sqrt(pp)\n\n        # the xafs equation:\n        cchi = np.exp(-2*reff*p.imag - 2*pp*(sigma2 - pp*fourth/3) +\n                      1j*(2*q*reff + pha +\n                          2*p*(deltar - 2*sigma2/reff - 2*pp*third/3) ))\n\n        cchi = degen * s02 * amp * cchi / (q*(reff + deltar)**2)\n        cchi[0] = 2*cchi[1] - cchi[2]\n        # outputs:\n        self.k = k\n        self.p = p\n        self.chi = cchi.imag\n        self.chi_imag = -cchi.real\n\ndef path2chi(path, paramgroup=None, **kws):\n    \"\"\"calculate chi(k) for a Feff Path,\n    optionally setting path parameter values\n    output chi array will be written to path group\n\n    Parameters:\n    ------------\n      path:        a FeffPath Group\n      params:      lmfit Parameters or larch ParameterGroup\n      kmax:        maximum k value for chi calculation [20].\n      kstep:       step in k value for chi calculation [0.05].\n      k:           explicit array of k values to calculate chi.\n\n    Returns:\n    ---------\n      None - outputs are written to path group\n\n    \"\"\"\n    if not isNamedClass(path, FeffPathGroup):\n        msg('%s is not a valid Feff Path' % path)\n        return\n    path.calc_chi_from_params(paramgroup, **kws)\n\n\ndef ff2chi(paths, group=None, paramgroup=None, k=None, kmax=None,\n            kstep=0.05, _larch=None, **kws):\n    \"\"\"sum chi(k) for a list of FeffPath Groups.\n\n    Parameters:\n    ------------\n      paths:       a list of FeffPath Groups or dict of {label: FeffPathGroups}\n      paramgroup:  a Parameter Group for calculating Path Parameters [None]\n      kmax:        maximum k value for chi calculation [20].\n      kstep:       step in k value for chi calculation [0.05].\n      k:           explicit array of k values to calculate chi.\n    Returns:\n    ---------\n       group contain arrays for k and chi\n\n    This essentially calls path2chi() for each of the paths in the\n    `paths` and writes the resulting arrays to group.k and group.chi.\n\n    \"\"\"\n    params = group2params(paramgroup)\n\n    if isinstance(paths, (list, tuple)):\n        pathlist = paths\n    elif isinstance(paths, dict):\n        pathlist = list(paths.values())\n    else:\n        raise ValueErrror('paths must be list, tuple, or dict')\n\n    for path in pathlist:\n        if not isNamedClass(path, FeffPathGroup):\n            print('%s is not a valid Feff Path' % path)\n            return\n        path.create_path_params(params=params)\n        path._calc_chi(k=k, kstep=kstep, kmax=kmax)\n    k = pathlist[0].k[:]\n    out = np.zeros_like(k)\n    for path in pathlist:\n        out += path.chi\n\n    if group is None:\n        group = Group()\n    else:\n        group = set_xafsGroup(group, _larch=_larch)\n    group.k = k\n    group.chi = out\n    return group\n\ndef feffpath(filename=None, label=None, s02=None, degen=None,\n             e0=None,ei=None, deltar=None, sigma2=None, third=None,\n             fourth=None, _larch=None, **kws):\n    \"\"\"create a Feff Path Group from a *feffNNNN.dat* file.\n\n    Parameters:\n    -----------\n      filename:  name (full path of) *feffNNNN.dat* file\n      label:     label for path   [file name]\n      degen:     path degeneracy, N [taken from file]\n      s02:       S_0^2    value or parameter [1.0]\n      e0:        E_0      value or parameter [0.0]\n      deltar:    delta_R  value or parameter [0.0]\n      sigma2:    sigma^2  value or parameter [0.0]\n      third:     c_3      value or parameter [0.0]\n      fourth:    c_4      value or parameter [0.0]\n      ei:        E_i      value or parameter [0.0]\n\n    For all the options described as **value or parameter** either a\n    numerical value or a Parameter (as created by param()) can be given.\n\n    Returns:\n    ---------\n        a FeffPath Group.\n\n    \"\"\"\n    return FeffPathGroup(filename=filename, label=label, s02=s02,\n                         degen=degen, e0=e0, ei=ei, deltar=deltar,\n                         sigma2=sigma2, third=third, fourth=fourth)\n", "meta": {"hexsha": "3f4df7a50c074a69bccdde3d9e0779e0c9bd1331", "size": 19665, "ext": "py", "lang": "Python", "max_stars_repo_path": "larch/xafs/feffdat.py", "max_stars_repo_name": "kbuc/xraylarch", "max_stars_repo_head_hexsha": "3abb0d6bdc65cf2747a03dd114d98df317c0ac9f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 90, "max_stars_repo_stars_event_min_datetime": "2015-01-10T21:57:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T15:21:52.000Z", "max_issues_repo_path": "larch/xafs/feffdat.py", "max_issues_repo_name": "kbuc/xraylarch", "max_issues_repo_head_hexsha": "3abb0d6bdc65cf2747a03dd114d98df317c0ac9f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 225, "max_issues_repo_issues_event_min_datetime": "2015-01-09T19:08:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:55:54.000Z", "max_forks_repo_path": "larch/xafs/feffdat.py", "max_forks_repo_name": "kbuc/xraylarch", "max_forks_repo_head_hexsha": "3abb0d6bdc65cf2747a03dd114d98df317c0ac9f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 51, "max_forks_repo_forks_event_min_datetime": "2015-03-13T10:03:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T07:54:38.000Z", "avg_line_length": 35.9506398537, "max_line_length": 91, "alphanum_fraction": 0.5345537757, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.1650437686181489}}
{"text": "import numpy as np\nimport tensorflow as tf\nfrom parameters import par\nfrom itertools import product\n\nclass AdamOpt:\n\n    \"\"\"\n    Example of use:\n\n    optimizer = AdamOpt.AdamOpt(variables, learning_rate=self.lr)\n    self.train = optimizer.compute_gradients(self.loss, gate=0)\n    gvs = optimizer.return_gradients()\n    self.g = gvs[0][0]\n    self.v = gvs[0][1]\n    \"\"\"\n\n    def __init__(self, variables, learning_rate = 0.001):\n\n        self.beta1 = 0.9\n        self.beta2 = 0.999\n        self.epsilon = 1e-08\n        self.t = 0\n        self.variables = variables\n        self.learning_rate = learning_rate\n\n        self.m = {}\n        self.v = {}\n        self.delta_grads = {}\n        for var in self.variables:\n            self.m[var.op.name]  = tf.Variable(tf.zeros(var.get_shape()), trainable=False)\n            self.v[var.op.name]  = tf.Variable(tf.zeros(var.get_shape()), trainable=False)\n            self.delta_grads[var.op.name]  = tf.Variable(tf.zeros(var.get_shape()), trainable=False)\n\n        self.grad_descent = tf.train.GradientDescentOptimizer(learning_rate = 1.0)\n\n\n    def reset_params(self):\n\n        self.t = 0\n        reset_op = []\n        for var in self.variables:\n            reset_op.append(tf.assign(self.m[var.op.name], tf.zeros(var.get_shape())))\n            reset_op.append(tf.assign(self.v[var.op.name], tf.zeros(var.get_shape())))\n            reset_op.append(tf.assign(self.delta_grads[var.op.name], tf.zeros(var.get_shape())))\n\n        return tf.group(*reset_op)\n\n\n    def optimize(self, loss):\n\n        grads_and_vars = self.compute_gradients(loss)\n        train_op = self.apply_gradients(grads_and_vars)\n\n        return train_op\n\n\n    def compute_gradients(self, loss):\n\n        self.gradients = self.grad_descent.compute_gradients(loss, var_list = self.variables)\n\n        self.t += 1\n        lr = self.learning_rate*np.sqrt(1-self.beta2**self.t)/(1-self.beta1**self.t)\n        self.update_var_op = []\n\n        #grads_and_vars = []\n        for (grads, _), var in zip(self.gradients, self.variables):\n            new_m = self.beta1*self.m[var.op.name] + (1-self.beta1)*grads\n            new_v = self.beta2*self.v[var.op.name] + (1-self.beta2)*grads*grads\n\n            delta_grad = - lr*new_m/(tf.sqrt(new_v) + self.epsilon)\n            delta_grad = tf.clip_by_norm(delta_grad, 1)\n\n            self.update_var_op.append(tf.assign(self.m[var.op.name], new_m))\n            self.update_var_op.append(tf.assign(self.v[var.op.name], new_v))\n\n            if 'W_rnn' in var.op.name:\n                print('Applied W_rnn mask.')\n                delta_grad *= par['W_rnn_mask']\n            elif 'W_in' in var.op.name:\n                print('Applied W_in mask.')\n                delta_grad *= par['W_in_mask']\n            elif 'W_d_rnn' in var.op.name:\n                print('Applied W_d_rnn mask.')\n                delta_grad *= par['W_d_rnn_mask']\n            elif 'W_out' in var.op.name:\n                print('Applied W_out mask.')\n                delta_grad *= par['W_out_mask']\n\n            self.update_var_op.append(tf.assign(self.delta_grads[var.op.name], delta_grad))\n            self.update_var_op.append(tf.assign_add(var, delta_grad))\n\n        return tf.group(*self.update_var_op)\n\n\n    def apply_gradients(self, grads_and_vars):\n        # currently not in use\n        for (grad, var) in grads_and_vars:\n            if 'W_rnn' in var.op.name:\n                print('Applied W_rnn mask.')\n                grad *= par['W_rnn_mask']\n            elif 'W_in' in var.op.name:\n                print('Applied W_in mask.')\n                grad *= par['W_in_mask']\n            elif 'W_out' in var.op.name:\n                print('Applied W_out mask.')\n                grad *= par['W_out_mask']\n            self.update_var_op.append(tf.assign_add(var, grad))\n\n        return tf.group(*self.update_var_op)\n\n\n    def return_delta_grads(self):\n        return self.delta_grads\n\n    def return_means(self):\n        return self.m\n\n    def return_grads_and_vars(self):\n        return self.gradients\n", "meta": {"hexsha": "d9f4036720a4e56f8bd00350e203ef491948df43", "size": 4014, "ext": "py", "lang": "Python", "max_stars_repo_path": "AdamOpt.py", "max_stars_repo_name": "xqding/Context-Dependent-Gating-RNN", "max_stars_repo_head_hexsha": "e37ff80a5f5c07a89c80ea7b8aedb54fa0cdfdda", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AdamOpt.py", "max_issues_repo_name": "xqding/Context-Dependent-Gating-RNN", "max_issues_repo_head_hexsha": "e37ff80a5f5c07a89c80ea7b8aedb54fa0cdfdda", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AdamOpt.py", "max_forks_repo_name": "xqding/Context-Dependent-Gating-RNN", "max_forks_repo_head_hexsha": "e37ff80a5f5c07a89c80ea7b8aedb54fa0cdfdda", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-11-06T21:41:41.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-20T20:14:31.000Z", "avg_line_length": 33.173553719, "max_line_length": 100, "alphanum_fraction": 0.5946686597, "include": true, "reason": "import numpy", "num_tokens": 938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3106943704494217, "lm_q1q2_score": 0.16504376183719102}}
{"text": "import numpy as np\nimport psr_utils as pu\nimport matplotlib.pyplot as plt\nimport pyslalib.slalib as slalib\nfrom argparse import ArgumentParser\nfrom frequencyoptimizer import PulsarNoise,TelescopeNoise,GalacticNoise\nfrom frequencyoptimizer import FrequencyOptimizer\n\nNCHAN = 16\nNSTEPS = 16\n\nTcmb = 3.0\n\nusage = \"\"\"%(prog)s [options]\n\nReceiver/telescope parameters can be specified via a text file using\nthe -r/--rx-specs argument.  The text file should have\nspace-delineated columns of\n\nFrequency(GHz) Trx(K) Gain(K/Jy) FractionalGainError\n\nfrequencyoptimizer.py will interpolate over these values at the\nfrequencies of interest.  If nothing is specified for -r/--rx-specs,\nthen frequency-independent receiver/telescope parameters will be taken\nfrom command line arguments with defaults as specified below.\n\nPulsar parameters can be specified from a python dictionary or from\ncommand line options with defaults as specified below.  If using a\npython dictionary, then the dictionary file should contain one and\nonly one dictionary of dictionaries, with the top-level keys being\npulsar names, and the second-level keys/values being\n\nname - Pulsar name\nperiod - Pulsar period (ms)\nDM - Dispersion measure (pc/cc)\nflux_1GHz - Pulsar flux at 1 GHz (mJy)\nspec_index - Pulsar spectral index (S_nu \\propto nu^\\alpha)\nW50 - Pulse profile FWHM (us)\nWeff - Effective pulsar profile width (us)\nUscale - Pulse profile scaling parameter\nrms_J1 - Single pulse RMS due to jitter (us)\nscat_ts - Scattering timescale at 1 GHz (us)\nscat_ts_var - Scattering timescale variability at 1 GHz (us)\ndiss_ts - Diffractive interstellar scintillation timescale (s)\n\nThe script make_dict.py can be used to convert a space-delineated text\nfile with the above columns into a suitable dictionary.  See\npsr_info.py and psr_info.txt for examples.\"\"\"\n\nparser = ArgumentParser(description=\"Predict pulsar TOA precision\", usage=usage)\nrx_group = parser.add_argument_group(title=\"Receiver specs\")\npulsar_group = parser.add_argument_group(title=\"Pulsar parameters\")\nrx_group.add_argument(\"-r\", \"--rx-specs\", \n                      help=\"File containing receiver performance specs\")\nrx_group.add_argument(\"-L\", \"--low-freq\", type=float, default=1.0,\n                      help=\"Low frequency (GHz; default=%(default)s)\")\nrx_group.add_argument(\"-H\", \"--high-freq\", type=float, default=2.0,\n                      help=\"High frequency (GHz; default=%(default)s)\")\nrx_group.add_argument(\"-T\", \"--trx\", dest=\"Trx\", type=float, default=20, \n                      help=\"Receiver temperature (K; default=%(default)s)\")\nrx_group.add_argument(\"-G\", \"--gain\", type=float, default=2.0, \n                      help=\"Telescope gain (K/Jy; default=%(default)s)\")\nrx_group.add_argument(\"-e\", \"--epsilon\", type=float, default=0.01,\n                      help=\"Fractional gain instability (default=%(default)s)\")\nparser.add_argument(\"-t\", \"--tobs\", type=float, default=1800.0, \n                    help=\"Observing time (s; default=%(default)s)\")\n\npulsar_group.add_argument(\"-d\", \"--psr-dict\", \n                          help=\"Python dictionary containing pulsar parameters\")\n\npulsar_group.add_argument(\"-n\", \"--name\", default=\"Fake\",\n                          help=\"Pulsar name (default=%(default)s)\")\npulsar_group.add_argument(\"-P\", \"--period\", type=float, default=3.0,\n                          help=\"Pulsar period (ms; default=%(default)s)\")\npulsar_group.add_argument(\"-D\", \"--dm\", type=float, default=30.0,\n                          help=\"Pulsar DM (pc/cc; default=%(default)s)\")\npulsar_group.add_argument(\"-F\", \"--flux\", dest=\"flux_1GHz\", type=float,\n                          default=10.0,\n                          help=(\"Pulsar flux density at 1 GHz (mJy; \"\n                                \"default=%(default)s)\"))\npulsar_group.add_argument(\"-a\", \"--alpha\", dest=\"spec_index\", type=float,\n                          default=-1.7,\n                          help=\"Pulsar spectral index (default=%(default)s)\")\npulsar_group.add_argument(\"-w\", \"--width\", dest=\"W50\", type=float,\n                          default=300.0,\n                          help=\"Pulsar FWHM (us; default=%(default)s)\")\npulsar_group.add_argument(\"--weff\", dest=\"Weff\", type=float,\n                          help=\"Pulsar effective width (us; default=1.2 x W50)\")\npulsar_group.add_argument(\"-U\", \"--uscale\", type=float, default=10.0, \n                          help=(\"Pulsar profile scaling factor\"))\npulsar_group.add_argument(\"-j\", \"--jitter\", dest=\"rms_J1\", type=float,\n                          default=100.0, \n                          help=(\"Pulsar single-pulse jitter RMS (us; \"\n                                \"default=%(default)s)\"))\npulsar_group.add_argument(\"-s\", \"--scat-ts\", type=float, default=0.01, \n                          help=(\"Pulsar scattering timescale at 1 GHz \"\n                                \"(us; default=%(default)s)\"))\npulsar_group.add_argument(\"-S\", \"--scat-ts-var\", type=float, default=0.05, \n                          help=(\"Pulsar scattering timescale variability at \"\n                                \"1 GHz (us; default=%(default)s)\"))\npulsar_group.add_argument(\"-i\", \"--diss-ts\", type=float, default=1000.0, \n                          help=(\"Pulsar diffractive ISS timescale at 1 GHz (s; \"\n                                \"default=%(default)s\"))\nargs = parser.parse_args()\n\nif args.rx_specs is not None:\n    interpolate = True\n    rx_freq,Trx,gain,epsilon = np.loadtxt(args.rx_specs,unpack=True)\n    low_freq = np.min(rx_freq)\n    high_freq = np.max(rx_freq)\n    freqs = np.logspace(np.log10(low_freq),np.log10(high_freq),NCHAN)\nelse:\n    interpolate = False\n    Trx = args.Trx\n    gain = args.gain\n    epsilon = args.epsilon\n    low_freq = args.low_freq\n    high_freq = args.high_freq\n    freqs = np.logspace(np.log10(low_freq),np.log10(high_freq),NCHAN)\n    rx_freq = freqs.copy()\n\nif args.psr_dict is not None:\n    import importlib\n    psr_dict = importlib.import_module(args.psr_dict.rstrip(\".py\"))\n    for a in dir(psr_dict):\n        if not a.startswith(\"__\"):\n            psrs = psr_dict.__getattribute__(a)\n            break\nelse:\n    psrs = {args.name: {\n        \"name\": args.name,\n        \"period\": args.period,\n        \"DM\": args.dm,\n        \"flux_1GHz\": args.flux_1GHz,\n        \"spec_index\": args.spec_index,\n        \"W50\": args.W50,\n        \"Weff\": 1.2*args.W50 if args.Weff is None else args.Weff,\n        \"uscale\": args.uscale,\n        \"rms_J1\": args.rms_J1,\n        \"scat_ts\": args.scat_ts,\n        \"scat_ts_var\": args.scat_ts_var,\n        \"diss_ts\": args.diss_ts }}\nsigmas = []\ntelescope_noise = TelescopeNoise(gain=gain,T_const=Trx+Tcmb,epsilon=epsilon,\n                                 T=args.tobs,rx_nu=rx_freq,\n                                 interpolate=interpolate)\ngalactic_noise = GalacticNoise()\nfor name,psr in psrs.items():\n    if psr[\"W50\"] is None and psr[\"Weff\"] is not None: \n        psr[\"W50\"] = 0.66*psr[\"Weff\"]\n    if psr[\"scat_ts\"] is None and psr[\"DM\"] is not None:\n        psr[\"scat_ts\"] = 1000*pu.pulse_broadening(psr[\"DM\"],1000.0)\n    if None not in psr.values():\n        pulsar_noise = PulsarNoise(\n            name,alpha=-psr[\"spec_index\"],I_0=psr[\"flux_1GHz\"],DM=psr[\"DM\"],\n            taud=psr[\"scat_ts\"]*1.5**4.4,tauvar=psr[\"scat_ts_var\"]*1.5**4.4*0.5,\n            dtd=psr[\"diss_ts\"],P=psr[\"period\"],Uscale=psr[\"uscale\"],\n            sigma_Js=np.zeros(NCHAN)+psr[\"rms_J1\"] / \\\n            np.sqrt(1000*args.tobs/psr[\"period\"]),\n            Weffs=np.zeros(NCHAN)+psr[\"Weff\"],W50s=np.zeros(NCHAN)+psr[\"W50\"])\n        frequency_optimizer = FrequencyOptimizer(\n            pulsar_noise,galactic_noise,telescope_noise,\n            numin=low_freq,numax=high_freq,nchan=NCHAN,log=True,nsteps=NSTEPS,\n            frac_bw=False,full_bandwidth=False,masks=None)\n        sigma = frequency_optimizer.calc_single(freqs)\n        sigmas.append(sigma)\n        print(\"%-10s   %.3f\"%(name,sigma))\n\nsigma_mean = np.mean(sigmas)\nsigma_median = np.median(sigmas)\nsigma_std = np.std(sigmas)\n\nprint(\"Mean sigma = %.3f\"%sigma_mean)\nprint(\"Median sigma = %.3f\"%sigma_median)\nprint(\"STD sigma = %.3f\"%sigma_std)\n", "meta": {"hexsha": "3e18b751cc4f806862a00b66f76e2287334cb85d", "size": 8080, "ext": "py", "lang": "Python", "max_stars_repo_path": "predict_toas.py", "max_stars_repo_name": "tycohen/FrequencyOptimizer", "max_stars_repo_head_hexsha": "3ad0cf244c558a063c58ec739e6ae91e565a34a4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "predict_toas.py", "max_issues_repo_name": "tycohen/FrequencyOptimizer", "max_issues_repo_head_hexsha": "3ad0cf244c558a063c58ec739e6ae91e565a34a4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "predict_toas.py", "max_forks_repo_name": "tycohen/FrequencyOptimizer", "max_forks_repo_head_hexsha": "3ad0cf244c558a063c58ec739e6ae91e565a34a4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-23T02:15:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-23T02:15:33.000Z", "avg_line_length": 45.9090909091, "max_line_length": 80, "alphanum_fraction": 0.6330445545, "include": true, "reason": "import numpy", "num_tokens": 2135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.27825679968760103, "lm_q1q2_score": 0.16491351138495114}}
{"text": "from __future__ import print_function\nfrom astropy.io import fits, ascii as asc\nfrom astropy.convolution import Gaussian2DKernel\nfrom scipy.interpolate import interp1d\n\nimport numpy as np\nimport os\nimport glob\nimport sys\n#import fsps\n\nfrom ..utils.smoothing import smooth\nfrom ..filters import get_filter\n\n#import some bits for the instruments\nfrom ..detectors import CCD250\nfrom ..telescopes import VLT\n\n__all__ = [\"MAVIS_Imager\"]\n\n\nclass ImagingInstrument:\n    \"\"\"\n    Generic instrument class with some generic instrument routines.  \n    \"\"\"\n    def __init__(self):\n        self.small_num = 1e-70\n        self.source_obs = None\n        self.sky_obs = None\n   \n        self.transmission = None\n        self.wavelength = None\n        self.pivot = None\n\n    def _EE_gaussian(self, seeing, binning=1, **kwargs):\n        sigma_pix = seeing / self.pix_scale / 2.355 #relies on the v-band seeing here\n\n        wave_temp = np.linspace(self.inst_wavelength.min(), self.inst_wavelength.max(), 50)\n        sig_temp = sigma_pix * (wave_temp/.500)**(-1./5.)\n        ee_temp = np.zeros_like(wave_temp)\n        for ii, tsig in enumerate(sig_temp):\n            ee_temp[ii] = Gaussian2DKernel(tsig, x_size=binning, y_size=binning,\n                                            mode='oversample', factor=100).array.sum()\n\n        ee_array = interp1d(wave_temp, ee_temp, kind='quadratic')(self.inst_wavelength)\n\n        return ee_array, binning**2    \n\n    def _set_filter(self, filt):\n        #fetch filter transmission curve from FSPS\n        #this sets the wavelength grid, so no rebinning needed\n\n        #pull information for this filter\n        fobj = get_filter(filt)\n        fwl, ftrans = fobj.transmission\n\n        ftrans = np.maximum(ftrans, 0.)\n        trans_interp = np.asarray(np.interp(self.inst_wavelength, fwl/1e4, \n                                  ftrans, left=0., right=0.), dtype=np.float)\n\n        #normalize transmission\n        ttrans = np.trapz(np.copy(trans_interp), self.inst_wavelength)\n        if ttrans < self.small_num: ttrans = 1.\n        ntrans = np.maximum(trans_interp / ttrans, 0.0)\n        \n        #stupid, but re-normalize to peak of 1 (since all other throughput terms \n        #are included in the instrument throughput\n        self.trans_norm = np.copy(ntrans)/ntrans.max()\n        self.transmission = ntrans\n        self.pivot = fobj.lambda_eff\n        return \n\n    def _patch_nan(self, signal):\n        nans = np.isnan(signal)\n        interpolator = interp1d(self.inst_wavelength[~nans], signal[~nans], bounds_error='extrapolate')\n        signal[nans] = interpolator(self.inst_wavelength[nans])\n        return signal\n\n\n    def make_sky_spectrum(self, sky, source, source_wave):\n        sky_wave, sky_emm, sky_trans = sky()\n       \n        match_res_sky = np.interp(sky_wave, source_wave, source.res_pix,\n                                 left=source.res_pix[0], right=source.res_pix[-1])\n        offset_res_sky = np.sqrt(np.clip((match_res_sky*source.step/sky.step)**2 - \n                                         sky.res_pix**2, 1e-10, None))\n        conv_emm = smooth(sky_emm, offset_res_sky)\n        conv_trans = smooth(sky_trans, offset_res_sky)\n                    \n        #resample onto output grid\n        sky_emm_resampled = np.interp(self.inst_wavelength, sky_wave, conv_emm)\n        sky_trans_resampled = np.clip(np.interp(self.inst_wavelength, \n                                                     sky_wave, conv_trans),0,1)\n\n        return sky_emm_resampled, sky_trans_resampled\n\n\n    def calc_sn(self, source, sky=None, dit=3600., \n                ndit=None, sn=None, seeing=1., binning=1, band='johnson_v', strehl=None):\n    \n        #generate source spectrum\n        source_wave, source_phot = source()\n        \n        #resample onto outputpixel grid\n        source_resampled = np.interp(self.inst_wavelength, source_wave, source_phot)\n \n        #if a sky object is also supplied, convolve it to match the instrument properties\n        if sky is not None:\n            sky_emm_resampled, sky_trans_resampled = self.make_sky_spectrum(sky, source, source_wave)\n        else:\n            sky_trans_resampled = np.ones(len(self.inst_wavelength))\n            sky_emm_resampled = np.zeros(len(self.inst_wavelength))\n\n        #store transmission spectrum\n        self.sky_trans = np.copy(sky_trans_resampled)\n        \n        #estimate the ensquared energy and pixel area\n        self.obs_ee, self.obs_area = self._ee(seeing, binning=binning, strehl=strehl)\n       \n        #total source spectrum\n        if source.norm_sb:\n            self.cfact = sky_trans_resampled*dit*self.total_throughput*self.step*\\\n                         self.telescope.area*self.pix_scale**2 * self.obs_area\n        else:\n            #get ensquared energy and area in pixels\n            self.cfact = sky_trans_resampled*dit*self.total_throughput*\\\n                         self.step*self.telescope.area*self.obs_ee\n\n        source_obs = np.copy(source_resampled)*self.cfact #photons\n\n        #sky is always done correctly-ish.\n        sky_obs = np.copy(sky_emm_resampled)*dit*self.total_throughput*self.step*\\\n                  self.telescope.area*self.pix_scale**2 * self.obs_area #total area, photons#/um\n\n\n        ##set filter\n        for iband in band:\n            self._set_filter(iband)\n         \n            #integrate transmission for total counts\n            self.source_obs = self._patch_nan(source_obs)*self.trans_norm\n            self.sky_obs = self._patch_nan(sky_obs)*self.trans_norm\n        \n            #total noise calculation\n            self.dark_noise = self.obs_area*self.detector.dark*dit\n            self.read_noise = self.obs_area*self.detector.rn**2\n            self.sky_noise = np.nansum(self.sky_obs)\n            self.obj_noise = np.nansum(self.source_obs)\n            self.noise = self.obj_noise + self.sky_noise + self.read_noise + self.dark_noise #per dit\n        \n            if sn is not None and ndit is None: #provided S/N, work out ndit to reach target S/N\n                indit = np.int(np.ceil(np.sqrt(self.noise)*sn/self.source_obs.sum()))\n                print(\"NDIT={2} to reach S/N={0} with DIT={1} in {3}\".format(sn, dit, indit, iband))\n            elif sn is None and ndit is not None:\n                isn = np.sqrt(ndit)*self.source_obs.sum() / np.sqrt(self.noise)\n                print(\"S/N={0:4.2f} at with NDIT={1} and DIT={2} in {3}\".format(isn, ndit, dit, iband))\n\n        return \n\n\n    def get_mag_limit(self, sn=None, sky=None, dit=3600., \n                      ndit=None, seeing=1., binning=1, band='johnson_v', strehl=None,\n                      norm='point'):\n    \n\n        #if a sky object is also supplied, convolve it to match the instrument properties\n        if sky is not None:\n            sky_wave, sky_emm, sky_trans = sky()\n            \n            #resample onto output grid\n            sky_emm_resampled = np.interp(self.inst_wavelength, sky_wave, sky_emm)\n            sky_trans_resampled = np.clip(np.interp(self.inst_wavelength, \n                                                         sky_wave, sky_trans),0,1)\n        else:\n            sky_trans_resampled = np.ones(len(self.inst_wavelength))\n            sky_emm_resampled = np.zeros(len(self.inst_wavelength))\n\n        #store transmission spectrum\n        self.sky_trans = np.copy(sky_trans_resampled)\n        \n        #estimate the ensquared energy and pixel area\n        self.obs_ee, self.obs_area = self._ee(seeing, binning=binning, strehl=strehl)\n\n        #total source spectrum\n        if norm == 'point':\n            #get ensquared energy and area in pixels\n            self.cfact = sky_trans_resampled*dit*self.total_throughput*\\\n                         self.step*self.telescope.area*self.obs_ee\n        else:\n            self.cfact = sky_trans_resampled*dit*self.total_throughput*self.step*\\\n                         self.telescope.area*self.pix_scale**2 * self.obs_area\n\n        #sky is always done correctly-ish.\n        sky_obs = np.copy(sky_emm_resampled)*dit*self.total_throughput*self.step*\\\n                  self.telescope.area*self.pix_scale**2 * self.obs_area #total area, photons#/um\n\n        ##set filter\n        store_limit = []\n        store_pivot = []\n        for iband in band:\n            self._set_filter(iband)\n         \n            #integrate transmission for total counts\n            self.sky_obs = self._patch_nan(sky_obs)*self.trans_norm\n        \n            #total noise calculation\n            self.dark_noise = self.obs_area*self.detector.dark*dit\n            self.read_noise = self.obs_area*self.detector.rn**2\n            self.sky_noise = np.nansum(self.sky_obs)\n            self.noise = self.sky_noise + self.read_noise + self.dark_noise #per dit\n       \n            #quadratic terms for solution\n            a = ndit / sn**2\n            c = self.noise\n\n            source_obs = 0.5*(1. + np.sqrt(1. + 4*a*c)) * sn**2 / ndit #total counts\n\n            #print(source_obs, self.pivot)\n            store_limit.append(-2.5*np.log10(source_obs * self.pivot * 6.626196e-27 / 100**2 / np.nansum(self.cfact*self.trans_norm) / 1e4)-48.6)\n            store_pivot.append(self.pivot/1e4)\n\n        return store_pivot, store_limit\n\n\n\nclass MAVIS_Imager(ImagingInstrument):\n    \"\"\"\n    A MAVIS-like instrument.\n\n    Assumes that the general properties of the MAVIS spectrograph\n    are MUSE-like, but with an added throughput hit from the AO system\n    and more elaborate PSF model.\n    \"\"\"\n\n    def __init__(self, pix_scale=0.00736, jitter=5, detector=None, telescope=None):\n        #check for reasonable jitter values\n        if jitter not in [5,10,20,30,40]:\n            raise ValueError('Input jitter must be one of 5, 10, 20, 30, or 40 (mas)')\n\n        #initialize the model base\n        ImagingInstrument.__init__(self)\n\n        #set the pixel scale\n        self.pix_scale = pix_scale\n       \n        #wavelength business\n        self.step = 1. / 1e4 #microns\n        self.wmin, self.wmax = 3700./1e4, 10100./1e4\n        self.inst_wavelength = np.arange(self.wmin, self.wmax, self.step)\n\n        #initialize the provided detector object\n        if detector is None:\n            self.detector = CCD250()\n        else:\n            self.detector = detector()\n\n        #get detector QE\n        self.qe = self.detector.qe_interp(self.inst_wavelength)\n        \n        #initialize the telescope\n        if telescope is None:\n            self.telescope = VLT()\n        else:\n            self.telescope = telescope()\n\n        #if the instrument throughput curves are already included, this should be set to 1\n        self.telescope_throughput = np.interp(self.inst_wavelength, self.telescope.telescope_wave, self.telescope.telescope_eff)\n\n        #compute the combined throughput - including filter transmission\n        self.total_throughput = self.telescope_throughput * self.qe * 0.98**2\n\n        #patch in low throughput at the notch\n        self.notch = (self.inst_wavelength > 0.580) & (self.inst_wavelength < 0.597)\n\n        #get path for bundled package files\n        bfile_dir = os.path.join(os.path.dirname(sys.modules['mavisetc'].__file__), 'data')\n\n        #fold in AOM throughput\n        data = np.array(asc.read(os.path.join(bfile_dir, 'mavis/mavis_AOM_throughput.csv')))\n        twave = np.array(data['col1'])\n        ttpt = np.array(data['col2'])\n\n        self.ao_throughput = np.interp(self.inst_wavelength, np.array(twave), np.array(ttpt),\n                                left=ttpt[0], right=ttpt[-1])\n        self.total_throughput *= self.ao_throughput\n\n        #pre-load EE profiles\n        ee_files = glob.glob(os.path.join(bfile_dir, 'mavis/PSF_{0}mas*EEProfile.dat'.format(jitter)))\n        wave = []\n        ee_interp = []\n        for ii, ee_file in enumerate(ee_files):\n            twave = os.path.split(ee_file)[1].split('_')[2][:-2]\n            wave.append(float(twave)/1e3)\n            with open(ee_file, 'r') as file:\n                tr, tee = [], []\n                for line in file:\n                    temp = line.strip().split(',')\n                    tr.append(float(temp[0])/self.pix_scale) #in pixels\n                    tee.append(float(temp[1]))\n                ee_interp.append(interp1d(tr, tee, bounds_error=False, fill_value='extrapolate'))\n        self._ee_profile_wave = np.array(wave)\n        self._ee_profile_interp = ee_interp\n        \n        self._ee = self._EE_lookup\n       \n\n    def _EE_lookup(self, seeing, binning=1, **kwargs):\n        \"\"\"\n        A quick and dirty lookup/interpolation function to generate ensquared \n        energy profiles based on simulations of the MAVIS PSF.\n        \"\"\"\n        #Seeing isn't relevant for MAVIS at the moment, so it only depends on the binning\n        iwave = np.argsort(self._ee_profile_wave)\n        \n        wave_out = np.zeros(len(iwave), dtype=np.float)\n        ee_out = np.zeros(len(iwave), dtype=np.float)\n        for ii, idx in enumerate(iwave): #sorted arguments?\n            wave_out[ii] = self._ee_profile_wave[idx]\n            ee_out[ii] = self._ee_profile_interp[idx](binning/2.)\n   \n        ee_interped = interp1d(wave_out, ee_out, fill_value='extrapolate')(self.inst_wavelength)\n        return ee_interped, binning**2\n \n", "meta": {"hexsha": "0bc9b3b5d358b656107bec4eaca848b0d9cc3214", "size": 13179, "ext": "py", "lang": "Python", "max_stars_repo_path": "mavisetc/instruments/imager.py", "max_stars_repo_name": "jtmendel/mavisetc", "max_stars_repo_head_hexsha": "4cd6800a7c4462f9a8063060c41e19719d35c5ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mavisetc/instruments/imager.py", "max_issues_repo_name": "jtmendel/mavisetc", "max_issues_repo_head_hexsha": "4cd6800a7c4462f9a8063060c41e19719d35c5ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mavisetc/instruments/imager.py", "max_forks_repo_name": "jtmendel/mavisetc", "max_forks_repo_head_hexsha": "4cd6800a7c4462f9a8063060c41e19719d35c5ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6759259259, "max_line_length": 145, "alphanum_fraction": 0.6172698991, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 3199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.27825678173200435, "lm_q1q2_score": 0.16491350074326871}}
{"text": "\"\"\" Defines the OplessModel class\"\"\"\n#***************************************************************************************************\n# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).\n# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights\n# in this software.\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n# in compliance with the License.  You may obtain a copy of the License at\n# http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory.\n#***************************************************************************************************\n\nimport numpy as _np\nimport collections as _collections\n\nfrom .model import Model as _Model\nfrom .evaltree import EvalTree as _EvalTree\nfrom .labeldicts import OutcomeLabelDict as _OutcomeLabelDict\nfrom .circuit import Circuit as _Circuit\nfrom .polynomial import Polynomial as _Polynomial\nfrom ..tools import slicetools as _slct\n\nfrom .opcalc import compact_deriv as _compact_deriv, float_product as prod, \\\n    safe_bulk_eval_compact_polys as _safe_bulk_eval_compact_polys\n\n\nclass OplessModelTree(_EvalTree):\n    def __init__(self, circuit_list, lookup, outcome_lookup, cache=None):\n        _EvalTree.__init__(self, circuit_list)\n        self.element_indices = lookup\n        self.outcomes = outcome_lookup\n        self.num_final_strs = len(circuit_list)  # circuits\n        max_el_index = -1\n        for elIndices in lookup.values():\n            max_i = elIndices.stop - 1 if isinstance(elIndices, slice) else max(elIndices)\n            max_el_index = max(max_el_index, max_i)\n        self.num_final_els = max_el_index + 1\n        self.cache = cache\n\n\nclass OplessModel(_Model):\n    \"\"\"\n    TODO docstring\n    \"\"\"\n\n    def __init__(self, state_space_labels):\n        \"\"\"\n        Creates a new Model.  Rarely used except from derived classes\n        `__init__` functions.\n\n        Parameters\n        ----------\n        state_space_labels : StateSpaceLabels or list or tuple\n            The decomposition (with labels) of (pure) state-space this model\n            acts upon.  Regardless of whether the model contains operators or\n            superoperators, this argument describes the Hilbert space dimension\n            and imposed structure.  If a list or tuple is given, it must be\n            of a from that can be passed to `StateSpaceLabels.__init__`.\n        \"\"\"\n        _Model.__init__(self, state_space_labels)\n\n        #Setting things the rest of pyGSTi expects but probably shouldn't...\n        self.simtype = \"opless\"\n        self.basis = None\n        self.dim = 0\n\n    def get_dimension(self):\n        return self.dim\n\n    def get_num_outcomes(self, circuit):  # needed for sparse data detection\n        raise NotImplementedError(\"Derived classes should implement this!\")\n\n    def probs(self, circuit, clipTo=None, cache=None):\n        \"\"\"\n        Construct a dictionary containing the probabilities of every spam label\n        given a operation sequence.\n\n        Parameters\n        ----------\n        circuit : Circuit or tuple of operation labels\n          The sequence of operation labels specifying the operation sequence.\n\n        clipTo : 2-tuple, optional\n           (min,max) to clip probabilities to if not None.\n\n        Returns\n        -------\n        probs : dictionary\n            A dictionary such that\n            probs[SL] = pr(SL,circuit,clipTo)\n            for each spam label (string) SL.\n        \"\"\"\n        raise NotImplementedError(\"Derived classes should implement this!\")\n\n    def dprobs(self, circuit, returnPr=False, clipTo=None):\n        \"\"\"\n        Construct a dictionary containing the probability derivatives of every\n        spam label for a given operation sequence.\n\n        Parameters\n        ----------\n        circuit : Circuit or tuple of operation labels\n          The sequence of operation labels specifying the operation sequence.\n\n        returnPr : bool, optional\n          when set to True, additionally return the probabilities.\n\n        clipTo : 2-tuple, optional\n           (min,max) to clip returned probability to if not None.\n           Only relevant when returnPr == True.\n\n        Returns\n        -------\n        dprobs : dictionary\n            A dictionary such that\n            dprobs[SL] = dpr(SL,circuit,gates,G0,SPAM,SP0,returnPr,clipTo)\n            for each spam label (string) SL.\n        \"\"\"\n        eps = 1e-7\n        orig_pvec = self.to_vector()\n        Np = self.num_params()\n        probs0 = self.probs(circuit, clipTo, None)\n\n        deriv = {k: _np.empty(Np, 'd') for k in probs0.keys()}\n        for i in range(Np):\n            p_plus_dp = orig_pvec.copy()\n            p_plus_dp[i] += eps\n            self.from_vector(p_plus_dp)\n            probs1 = self.probs(circuit, clipTo, None)\n            for k, p0 in probs0.items():\n                deriv[k][i] = (probs1[k] - p0) / eps\n        self.from_vector(orig_pvec)\n\n        if returnPr:\n            return {k: (p0, deriv[k]) for k in probs0.keys()}\n        else:\n            return deriv\n\n    def bulk_evaltree_from_resources(self, circuit_list, comm=None, memLimit=None,\n                                     distributeMethod=\"default\", subcalls=[],\n                                     dataset=None, verbosity=0):\n        #TODO: choose these based on resources, and enable split trees\n        minSubtrees = 0\n        numSubtreeComms = 1\n        maxTreeSize = None\n        evTree = self.bulk_evaltree(circuit_list, minSubtrees, maxTreeSize,\n                                    numSubtreeComms, dataset, verbosity)\n        return evTree, 0, 0, evTree.element_indices, evTree.outcomes\n\n    def bulk_evaltree(self, circuit_list, minSubtrees=None, maxTreeSize=None,\n                      numSubtreeComms=1, dataset=None, verbosity=0):\n        raise NotImplementedError(\"Derived classes should implement this!\")\n\n    def bulk_probs(self, circuit_list, clipTo=None, check=False,\n                   comm=None, memLimit=None, dataset=None, smartc=None):\n        evalTree, _, _, elIndices, outcomes = self.bulk_evaltree_from_resources(circuit_list, comm, memLimit, \"default\",\n                                                                                [], dataset)\n        vp = _np.empty(evalTree.num_final_elements(), 'd')\n        self.bulk_fill_probs(vp, evalTree, clipTo, check, comm)\n\n        ret = _collections.OrderedDict()\n        for i, opstr in enumerate(evalTree):\n            elInds = _slct.indices(elIndices[i]) \\\n                if isinstance(elIndices[i], slice) else elIndices[i]\n            ret[opstr] = _OutcomeLabelDict(\n                [(outLbl, vp[ei]) for ei, outLbl in zip(elInds, outcomes[i])])\n        return ret\n\n    def bulk_dprobs(self, circuit_list, returnPr=False, clipTo=None,\n                    check=False, comm=None, wrtBlockSize=None, dataset=None):\n        memLimit = None\n        evalTree, _, _, elIndices, outcomes = self.bulk_evaltree_from_resources(circuit_list, comm, memLimit,\n                                                                                \"default\", [], dataset)\n        nElements = evalTree.num_final_elements()\n        nDerivCols = self.num_params()\n\n        vdp = _np.empty((nElements, nDerivCols), 'd')\n        vp = _np.empty(nElements, 'd') if returnPr else None\n\n        self.bulk_fill_dprobs(vdp, evalTree,\n                              vp, clipTo, check, comm,\n                              None, wrtBlockSize)\n\n        ret = _collections.OrderedDict()\n        for i, opstr in enumerate(evalTree):\n            elInds = _slct.indices(elIndices[i]) \\\n                if isinstance(elIndices[i], slice) else elIndices[i]\n            if returnPr:\n                ret[opstr] = _OutcomeLabelDict(\n                    [(outLbl, (vdp[ei], vp[ei])) for ei, outLbl in zip(elInds, outcomes[i])])\n            else:\n                ret[opstr] = _OutcomeLabelDict(\n                    [(outLbl, vdp[ei]) for ei, outLbl in zip(elInds, outcomes[i])])\n        return ret\n\n    def bulk_fill_probs(self, mxToFill, evalTree, clipTo=None, check=False, comm=None):\n        if False and evalTree.cache:  # TEST (disabled)\n            cpolys = evalTree.cache\n            ps = _safe_bulk_eval_compact_polys(cpolys[0], cpolys[1], self._paramvec, (evalTree.num_final_elements(),))\n            assert(_np.linalg.norm(_np.imag(ps)) < 1e-6)\n            ps = _np.real(ps)\n            if clipTo is not None: ps = _np.clip(ps, clipTo[0], clipTo[1])\n            mxToFill[:] = ps\n        else:\n            for i, c in enumerate(evalTree):\n                cache = evalTree.cache[i] if evalTree.cache else None\n                probs = self.probs(c, clipTo, cache)\n                elInds = _slct.indices(evalTree.element_indices[i]) \\\n                    if isinstance(evalTree.element_indices[i], slice) else evalTree.element_indices[i]\n                for k, outcome in zip(elInds, evalTree.outcomes[i]):\n                    mxToFill[k] = probs[outcome]\n\n    def bulk_fill_dprobs(self, mxToFill, evalTree, prMxToFill=None, clipTo=None,\n                         check=False, comm=None, wrtBlockSize=None,\n                         profiler=None, gatherMemLimit=None):\n\n        Np = self.num_params()\n        p = self.to_vector()\n\n        if False and evalTree.cache:  # TEST (disabled)\n            cpolys = evalTree.cache\n            if prMxToFill is not None:\n                ps = _safe_bulk_eval_compact_polys(cpolys[0], cpolys[1], p, (evalTree.num_final_elements(),))\n                assert(_np.linalg.norm(_np.imag(ps)) < 1e-6)\n                ps = _np.real(ps)\n                if clipTo is not None: ps = _np.clip(ps, clipTo[0], clipTo[1])\n                prMxToFill[:] = ps\n            dpolys = _compact_deriv(cpolys[0], cpolys[1], list(range(Np)))\n            dps = _safe_bulk_eval_compact_polys(dpolys[0], dpolys[1], p, (evalTree.num_final_elements(), Np))\n            mxToFill[:, :] = dps\n        else:\n            # eps = 1e-6\n            for i, c in enumerate(evalTree):\n                cache = evalTree.cache[i] if evalTree.cache else None\n                probs0 = self.probs(c, clipTo, cache)\n                dprobs0 = self.dprobs(c, False, clipTo, cache)\n                elInds = _slct.indices(evalTree.element_indices[i]) \\\n                    if isinstance(evalTree.element_indices[i], slice) else evalTree.element_indices[i]\n                for k, outcome in zip(elInds, evalTree.outcomes[i]):\n                    if prMxToFill is not None:\n                        prMxToFill[k] = probs0[outcome]\n                    mxToFill[k, :] = dprobs0[outcome]\n\n                    #Do this to fill mxToFill instead of calling dprobs above as it's a little faster for finite diff?\n                    #for j in range(Np):\n                    #    p_plus_dp = p.copy()\n                    #    p_plus_dp[j] += eps\n                    #    self.from_vector(p_plus_dp)\n                    #    probs1 = self.probs(c,clipTo,cache)\n                    #    mxToFill[k,j] = (probs1[outcome]-probs0[outcome]) / eps\n                    #self.from_vector(p)\n\n    def __str__(self):\n        raise \"Derived classes should implement OplessModel.__str__ !!\"\n\n\nclass SuccessFailModel(OplessModel):\n    def __init__(self, state_space_labels, use_cache=False):\n        OplessModel.__init__(self, state_space_labels)\n        self.use_cache = use_cache\n\n    def get_num_outcomes(self, circuit):  # needed for sparse data detection\n        return 2\n\n    def _success_prob(self, circuit, cache):\n        raise NotImplementedError(\"Derived classes should implement this!\")\n\n    def _success_dprob(self, circuit, cache):\n        raise NotImplementedError(\"Derived classes should implement this!\")\n\n    #FUTURE?: def _fill_circuit_probs(self, array_to_fill, outcomes, circuit, clipTo):\n    def probs(self, circuit, clipTo=None, cache=None):\n        \"\"\"\n        Construct a dictionary containing the probabilities of every spam label\n        given a operation sequence.\n\n        Parameters\n        ----------\n        circuit : Circuit or tuple of operation labels\n          The sequence of operation labels specifying the operation sequence.\n\n        clipTo : 2-tuple, optional\n           (min,max) to clip probabilities to if not None.\n\n        Returns\n        -------\n        probs : dictionary\n            A dictionary such that\n            probs[outcome] = pr(outcome,circuit,clipTo).\n        \"\"\"\n        sp = self._success_prob(circuit, cache)\n        if clipTo is not None: sp = _np.clip(sp, clipTo[0], clipTo[1])\n        return _OutcomeLabelDict([('success', sp), ('fail', 1 - sp)])\n\n    def dprobs(self, circuit, returnPr=False, clipTo=None, cache=None):\n        \"\"\"\n        Construct a dictionary containing the probability derivatives of every\n        spam label for a given operation sequence.\n\n        Parameters\n        ----------\n        circuit : Circuit or tuple of operation labels\n          The sequence of operation labels specifying the operation sequence.\n\n        returnPr : bool, optional\n          when set to True, additionally return the probabilities.\n\n        clipTo : 2-tuple, optional\n           (min,max) to clip returned probability to if not None.\n           Only relevant when returnPr == True.\n\n        Returns\n        -------\n        dprobs : dictionary\n            A dictionary such that\n            dprobs[SL] = dpr(SL,circuit,gates,G0,SPAM,SP0,returnPr,clipTo)\n            for each spam label (string) SL.\n        \"\"\"\n        try:\n            dsp = self._success_dprob(circuit, cache)\n        except NotImplementedError:\n            return OplessModel.dprobs(self, circuit, returnPr, clipTo)\n\n        if returnPr:\n            sp = self._success_prob(circuit, cache)\n            if clipTo is not None: sp = _np.clip(sp, clipTo[0], clipTo[1])\n            return {('success',): (sp, dsp), ('fail',): (1 - sp, -dsp)}\n        else:\n            return {('success',): dsp, ('fail',): -dsp}\n\n    def poly_probs(self, circuit):\n        \"\"\"\n        Same as probs(...) but return polynomials.\n        \"\"\"\n        sp = self._success_prob_poly(circuit)\n        return _OutcomeLabelDict([('success', sp), ('fail', _Polynomial({(): 1.0}) - sp)])\n\n    def simplify_circuits(self, circuits, dataset=None):\n        rawdict = None  # TODO - is this needed?\n        lookup = {i: slice(2 * i, 2 * i + 2, 1) for i in range(len(circuits))}\n        outcome_lookup = {i: (('success',), ('fail',)) for i in range(len(circuits))}\n\n        return rawdict, lookup, outcome_lookup, 2 * len(circuits)\n\n    def bulk_evaltree(self, circuit_list, minSubtrees=None, maxTreeSize=None,\n                      numSubtreeComms=1, dataset=None, verbosity=0):\n        lookup = {i: slice(2 * i, 2 * i + 2, 1) for i in range(len(circuit_list))}\n        outcome_lookup = {i: (('success',), ('fail',)) for i in range(len(circuit_list))}\n\n        if self.use_cache == \"poly\":\n            #Do precomputation here\n            polys = []\n            for i, circuit in enumerate(circuit_list):\n                print(\"Generating probs for circuit %d of %d\" % (i + 1, len(circuit_list)))\n                probs = self.poly_probs(circuit)\n                polys.append(probs['success'])\n                polys.append(probs['fail'])\n            compact_polys = compact_poly_list(polys)\n            cache = compact_polys\n        elif self.use_cache is True:\n            cache = [self._circuit_cache(circuit) for circuit in circuit_list]\n        else:\n            cache = None\n\n        return OplessModelTree(circuit_list, lookup, outcome_lookup, cache)\n\n#TODO: move this to polynomial.py??\n\n\ndef compact_poly_list(list_of_polys):\n    \"\"\"Create a single vtape,ctape pair from a list of normal Polynomals \"\"\"\n    tapes = [p.compact() for p in list_of_polys]\n    vtape = _np.concatenate([t[0] for t in tapes])\n    ctape = _np.concatenate([t[1] for t in tapes])\n    return vtape, ctape\n\n\nclass ErrorRatesModel(SuccessFailModel):\n\n    def __init__(self, error_rates, nQubits, state_space_labels=None, alias_dict={}, idlename='Gi'):\n        \"\"\"\n        todo\n        \"\"\"\n        if state_space_labels is None:\n            state_space_labels = ['Q%d' % i for i in range(nQubits)]\n        else:\n            assert(len(state_space_labels) == nQubits)\n\n        SuccessFailModel.__init__(self, state_space_labels, use_cache=True)\n\n        gate_error_rate_keys = (list(error_rates['gates'].keys()))\n        readout_error_rate_keys = (list(error_rates['readout'].keys()))\n\n        # if gate_error_rate_keys[0] in state_space_labels:\n        #     self._gateind = True\n        # else:\n        #     self._gateind = False\n\n        self._idlename = idlename\n        self._alias_dict = alias_dict.copy()\n        self._gate_error_rate_indices = {k: i for i, k in enumerate(gate_error_rate_keys)}\n        self._readout_error_rate_indices = {k: i + len(gate_error_rate_keys)\n                                            for i, k in enumerate(readout_error_rate_keys)}\n        self._paramvec = _np.concatenate(\n            (_np.array([_np.sqrt(error_rates['gates'][k]) for k in gate_error_rate_keys], 'd'),\n             _np.array([_np.sqrt(error_rates['readout'][k]) for k in readout_error_rate_keys], 'd'))\n        )\n\n    def __str__(self):\n        s = \"Error Rates model with error rates: \\n\" + \\\n            \"\\n\".join([\"%s = %g\" % (k, self._paramvec[i]**2) for k, i in self._gate_error_rate_indices.items()]) + \\\n            \"\\n\" + \\\n            \"\\n\".join([\"%s = %g\" % (k, self._paramvec[i]**2) for k, i in self._readout_error_rate_indices.items()])\n        return s\n\n    def to_dict(self):\n        error_rate_dict = {'gates': {}, 'readout': {}}\n        error_rate_dict['gates'] = {k: self._paramvec[i]**2 for k, i in self._gate_error_rate_indices.items()}\n        error_rate_dict['readout'] = {k: self._paramvec[i]**2 for k, i in self._readout_error_rate_indices.items()}\n        asdict = {'error_rates': error_rate_dict, 'alias_dict': self._alias_dict.copy()}\n        return asdict\n\n    def _circuit_cache(self, circuit):\n        if not isinstance(circuit, _Circuit):\n            circuit = _Circuit.fromtup(circuit)\n\n        depth = circuit.depth()\n        width = circuit.width()\n        g_inds = self._gate_error_rate_indices\n        r_inds = self._readout_error_rate_indices\n\n        # if self._gateind:\n        #     inds_to_mult_by_layer = []\n        #     for i in range(depth):\n\n        #         layer = circuit.get_layer(i)\n        #         inds_to_mult = []\n        #         usedQs = []\n\n        #         for gate in layer:\n        #             if len(gate.qubits) > 1:\n        #                 usedQs += list(gate.qubits)\n        #                 inds_to_mult.append(g_inds[frozenset(gate.qubits)])\n\n        #         for q in circuit.line_labels:\n        #             if q not in usedQs:\n        #                 inds_to_mult.append(g_inds[q])\n\n        #         inds_to_mult_by_layer.append(_np.array(inds_to_mult, int))\n\n        # else:\n        layers_with_idles = [circuit.get_layer_with_idles(i, idleGateName=self._idlename) for i in range(depth)]\n        inds_to_mult_by_layer = [_np.array([g_inds[self._alias_dict.get(str(gate), str(gate))] for gate in layer], int)\n                                 for layer in layers_with_idles]\n\n        # Bit-flip readout error as a pre-measurement depolarizing channel.\n        inds_to_mult = [r_inds[q] for q in circuit.line_labels]\n        inds_to_mult_by_layer.append(_np.array(inds_to_mult, int))\n\n        # The scaling constant such that lambda = 1 - alpha * epsilon where lambda is the diagonal of a depolarizing\n        # channel with entanglement infidelity of epsilon.\n        alpha = 4**width / (4**width - 1)\n\n        return (width, depth, alpha, 1 / 2**width, inds_to_mult_by_layer)\n\n\nclass TwirledLayersModel(ErrorRatesModel):\n\n    def __init__(self, error_rates, nQubits, state_space_labels=None, alias_dict={}, idlename='Gi'):\n        \"\"\"\n        todo\n        \"\"\"\n        ErrorRatesModel.__init__(self, error_rates, nQubits, state_space_labels=state_space_labels,\n                                 alias_dict=alias_dict, idlename=idlename)\n\n    def _success_prob(self, circuit, cache):\n        \"\"\"\n        todo\n        \"\"\"\n        pvec = self._paramvec**2\n        if cache is None:\n            cache = self._circuit_cache(circuit)\n\n        width, depth, alpha, one_over_2_width, inds_to_mult_by_layer = cache\n        # The success probability for all the operations (the entanglment fidelity for the gates)\n        sp = 1.0 - pvec\n\n        # The depolarizing constant for the full sequence of twirled layers.\n        lambda_all_layers = 1.0\n        for inds_to_mult in inds_to_mult_by_layer[:-1]:\n            lambda_all_layers *= 1 - alpha * (1 - prod(sp[inds_to_mult]))\n        # lambda_all_layers = prod([(1 - alpha * (1 - prod(sp[inds_to_mult])))\n        #                           for inds_to_mult in inds_to_mult_by_layer[:-1]])\n\n        # The readout success probability.\n        successprob_readout = prod(sp[inds_to_mult_by_layer[-1]])\n        # THe success probability of the circuit.\n        successprob_circuit = lambda_all_layers * (successprob_readout - one_over_2_width) + one_over_2_width\n\n        return successprob_circuit\n\n    def _success_dprob(self, circuit, cache):\n        pvec = self._paramvec**2\n        dpvec_dparams = 2 * self._paramvec\n\n        if cache is None:\n            cache = self._circuit_cache(circuit)\n\n        # p = product_layers(1 - alpha * (1 - prod_[inds4layer](1 - param))) * \\\n        #     (prod_[inds4LASTlayer](1 - param) - 1 / 2**width)\n        # Note: indices cannot be repeated in a layer, i.e. either a given index appears one or zero times in inds4layer\n\n        width, depth, alpha, one_over_2_width, inds_to_mult_by_layer = cache\n        sp = 1.0 - pvec\n        deriv = _np.zeros(len(pvec), 'd')\n\n        nLayers = len(inds_to_mult_by_layer)\n        lambda_per_layer = _np.empty(nLayers, 'd')\n        for i, inds_to_mult in enumerate(inds_to_mult_by_layer[:-1]):\n            lambda_per_layer[i] = 1 - alpha * (1 - prod(sp[inds_to_mult]))\n\n        successprob_readout = prod(sp[inds_to_mult_by_layer[-1]])\n        lambda_per_layer[nLayers - 1] = successprob_readout - one_over_2_width\n        lambda_all_layers = prod(lambda_per_layer)  # includes readout factor as last layer\n\n        #All layers except last\n        for i, inds_to_mult in enumerate(inds_to_mult_by_layer[:-1]):\n            lambda_all_but_current_layer = lambda_all_layers / lambda_per_layer[i]\n            # for each such ind, when we take deriv wrt this index, we need to differentiate this layer, etc.\n            for ind in inds_to_mult:\n                deriv[ind] += lambda_all_but_current_layer * alpha * \\\n                    (prod(sp[inds_to_mult]) / sp[ind]) * -1.0  # what if sp[ind] == 0?\n\n        #Last layer\n        lambda_all_but_current_layer = lambda_all_layers / lambda_per_layer[-1]\n        for ind in inds_to_mult_by_layer[-1]:\n            deriv[ind] += lambda_all_but_current_layer * (successprob_readout / sp[ind]) * -1.0  # what if sp[ind] == 0?\n\n        return deriv * dpvec_dparams\n\n\nclass TwirledGatesModel(ErrorRatesModel):\n\n    def __init__(self, error_rates, nQubits, state_space_labels=None, alias_dict={}, idlename='Gi'):\n        \"\"\"\n        todo\n        \"\"\"\n        ErrorRatesModel.__init__(self, error_rates, nQubits, state_space_labels=state_space_labels,\n                                 alias_dict=alias_dict, idlename=idlename)\n\n    def _circuit_cache(self, circuit):\n        width, depth, alpha, one_over_2_width, inds_to_mult_by_layer = super()._circuit_cache(circuit)\n        all_inds_to_mult = _np.concatenate(inds_to_mult_by_layer[:-1])\n        readout_inds_to_mult = inds_to_mult_by_layer[-1]\n        all_inds_to_mult_cnt = _np.zeros(self.num_params(), int)\n        for i in all_inds_to_mult:\n            all_inds_to_mult_cnt[i] += 1\n        return width, depth, alpha, one_over_2_width, all_inds_to_mult, readout_inds_to_mult, all_inds_to_mult_cnt\n\n    def _success_prob(self, circuit, cache):\n        \"\"\"\n        todo\n        \"\"\"\n        pvec = self._paramvec**2\n        if cache is None:\n            cache = self._circuit_cache(circuit)\n\n        width, depth, alpha, one_over_2_width, all_inds_to_mult, readout_inds_to_mult, all_inds_to_mult_cnt = cache\n        # The success probability for all the operations (the entanglment fidelity for the gates)\n        sp = 1.0 - pvec\n\n        # The 'lambda' for all gates (+ readout, which isn't used).\n        lambda_ops = 1.0 - alpha * pvec\n\n        # The depolarizing constant for the full sequence of twirled gates.\n        lambda_all_layers = prod(lambda_ops[all_inds_to_mult])\n        # The readout success probability.\n        successprob_readout = prod(sp[readout_inds_to_mult])\n        # THe success probability of the circuit.\n        successprob_circuit = lambda_all_layers * (successprob_readout - one_over_2_width) + one_over_2_width\n\n        return successprob_circuit\n\n    def _success_dprob(self, circuit, cache):\n        \"\"\"\n        todo\n        \"\"\"\n        pvec = self._paramvec**2\n        dpvec_dparams = 2 * self._paramvec\n\n        if cache is None:\n            cache = self._circuit_cache(circuit)\n\n        width, depth, alpha, one_over_2_width, all_inds_to_mult, readout_inds_to_mult, all_inds_to_mult_cnt = cache\n        sp = 1.0 - pvec\n        lambda_ops = 1.0 - alpha * pvec\n        deriv = _np.zeros(len(pvec), 'd')\n\n        # The depolarizing constant for the full sequence of twirled gates.\n        lambda_all_layers = prod(lambda_ops[all_inds_to_mult])\n        for i, n in enumerate(all_inds_to_mult_cnt):\n            deriv[i] = n * lambda_all_layers / lambda_ops[i] * -alpha  # -alpha = d(lambda_ops/dparam)\n\n        # The readout success probability.\n        readout_deriv = _np.zeros(len(pvec), 'd')\n        successprob_readout = prod(sp[readout_inds_to_mult])\n        for ind in readout_inds_to_mult:\n            readout_deriv[ind] = (successprob_readout / sp[ind]) * -1.0  # what if sp[ind] == 0?\n\n        # The success probability of the circuit.\n        #successprob_circuit = lambda_all_layers * (successprob_readout - one_over_2_width) + one_over_2_width\n\n        # product rule\n        return (deriv * (successprob_readout - one_over_2_width) + lambda_all_layers * readout_deriv) * dpvec_dparams\n\n\nclass AnyErrorCausesFailureModel(ErrorRatesModel):\n\n    def __init__(self, error_rates, nQubits, state_space_labels=None, alias_dict={}, idlename='Gi'):\n        \"\"\"\n        todo\n        \"\"\"\n        ErrorRatesModel.__init__(self, error_rates, nQubits, state_space_labels=state_space_labels,\n                                 alias_dict=alias_dict, idlename=idlename)\n\n    def _circuit_cache(self, circuit):\n        width, depth, alpha, one_over_2_width, inds_to_mult_by_layer = super()._circuit_cache(circuit)\n        all_inds_to_mult = _np.concatenate(inds_to_mult_by_layer)\n        all_inds_to_mult_cnt = _np.zeros(self.num_params(), int)\n        for i in all_inds_to_mult:\n            all_inds_to_mult_cnt[i] += 1\n        return all_inds_to_mult, all_inds_to_mult_cnt\n\n    def _success_prob(self, circuit, cache):\n        \"\"\"\n        todo\n        \"\"\"\n        pvec = self._paramvec**2\n\n        if cache is None:\n            cache = self._circuit_cache(circuit)\n\n        all_inds_to_mult, all_inds_to_mult_cnt = cache\n        # The success probability for all the operations (the entanglment fidelity for the gates)\n        sp = 1.0 - pvec\n\n        # The probability that every operation succeeds.\n        successprob_circuit = prod(sp[all_inds_to_mult])\n\n        return successprob_circuit\n\n    def _success_dprob(self, circuit, cache):\n        \"\"\"\n        todo\n        \"\"\"\n        pvec = self._paramvec**2\n        dpvec_dparams = 2 * self._paramvec\n\n        if cache is None:\n            cache = self._circuit_cache(circuit)\n\n        all_inds_to_mult, all_inds_to_mult_cnt = cache\n        sp = 1.0 - pvec\n        successprob_circuit = prod(sp[all_inds_to_mult])\n        deriv = _np.zeros(len(pvec), 'd')\n        for i, n in enumerate(all_inds_to_mult_cnt):\n            deriv[i] = n * successprob_circuit / sp[i] * -1.0\n\n        return deriv * dpvec_dparams\n\n\nclass AnyErrorCausesRandomOutputModel(ErrorRatesModel):\n\n    def __init__(self, error_rates, nQubits, state_space_labels=None, alias_dict={}, idlename='Gi'):\n        \"\"\"\n        todo\n        \"\"\"\n        ErrorRatesModel.__init__(self, error_rates, nQubits, state_space_labels=state_space_labels,\n                                 alias_dict=alias_dict, idlename=idlename)\n\n    def _circuit_cache(self, circuit):\n        width, depth, alpha, one_over_2_width, inds_to_mult_by_layer = super()._circuit_cache(circuit)\n        all_inds_to_mult = _np.concatenate(inds_to_mult_by_layer)\n        all_inds_to_mult_cnt = _np.zeros(self.num_params(), int)\n        for i in all_inds_to_mult:\n            all_inds_to_mult_cnt[i] += 1\n        return one_over_2_width, all_inds_to_mult, all_inds_to_mult_cnt\n\n    def _success_prob(self, circuit, cache):\n        \"\"\"\n        todo\n        \"\"\"\n        pvec = self._paramvec**2\n        if cache is None:\n            cache = self._circuit_cache(circuit)\n\n        one_over_2_width, all_inds_to_mult, all_inds_to_mult_cnt = cache\n        # The success probability for all the operations (the entanglment fidelity for the gates)\n        sp = 1.0 - pvec\n\n        # The probability that every operation succeeds.\n        successprob_all_ops = prod(sp[all_inds_to_mult])\n        # The circuit succeeds if all ops succeed, and has a random outcome otherwise.\n        successprob_circuit = successprob_all_ops + (1 - successprob_all_ops) * one_over_2_width\n\n        return successprob_circuit\n\n    def _success_dprob(self, circuit, cache):\n        \"\"\"\n        todo\n        \"\"\"\n        pvec = self._paramvec**2\n        dpvec_dparams = 2 * self._paramvec\n\n        if cache is None:\n            cache = self._circuit_cache(circuit)\n\n        one_over_2_width, all_inds_to_mult, all_inds_to_mult_cnt = cache\n        sp = 1.0 - pvec\n\n        successprob_all_ops = prod(sp[all_inds_to_mult])\n        deriv = _np.zeros(len(pvec), 'd')\n        for i, n in enumerate(all_inds_to_mult_cnt):\n            deriv[i] = n * successprob_all_ops / sp[i] * -1.0\n\n        # The circuit succeeds if all ops succeed, and has a random outcome otherwise.\n        # successprob_circuit = successprob_all_ops + (1 - successprob_all_ops) / 2**width\n        # = const + (1-1/2**width)*successprobs_all_ops\n        deriv *= (1.0 - one_over_2_width)\n        return deriv * dpvec_dparams\n\n    # def ORIGINAL_success_prob(self, circuit, cache):\n    #     \"\"\"\n    #     todo\n    #     \"\"\"\n    #     if not isinstance(circuit, _Circuit):\n    #         circuit = _Circuit.fromtup(circuit)\n\n    #     depth = circuit.depth()\n    #     width = circuit.width()\n    #     pvec = self._paramvec\n    #     g_inds = self._gate_error_rate_indices\n    #     r_inds = self._readout_error_rate_indices\n\n    #     if self.model_type in ('FE', 'FiE+U'):\n\n    #         twoQgates = []\n    #         for i in range(depth):\n    #             layer = circuit.get_layer(i)\n    #             twoQgates += [q.qubits for q in layer if len(q.qubits) > 1]\n\n    #         sp = 1\n    #         oneqs = {q: depth for q in circuit.line_labels}\n\n    #         for qs in twoQgates:\n    #             sp = sp * (1 - pvec[g_inds[frozenset(qs)]])\n    #             oneqs[qs[0]] += -1\n    #             oneqs[qs[1]] += -1\n\n    #         sp = sp * _np.prod([(1 - pvec[g_inds[q]])**oneqs[q]\n    #                             * (1 - pvec[r_inds[q]]) for q in circuit.line_labels])\n\n    #         if self.model_type == 'FiE+U':\n    #             sp = sp + (1 - sp) * (1 / 2**width)\n\n    #         return sp\n\n    #     if self.model_type == 'GlobalDep':\n\n    #         p = 1\n    #         for i in range(depth):\n\n    #             layer = circuit.get_layer(i)\n    #             sp_layer = 1\n    #             usedQs = []\n\n    #             for gate in layer:\n    #                 if len(gate.qubits) > 1:\n    #                     usedQs += list(gate.qubits)\n    #                     sp_layer = sp_layer * (1 - pvec[g_inds[frozenset(gate.qubits)]])\n\n    #             for q in circuit.line_labels:\n    #                 if q not in usedQs:\n    #                     sp_layer = sp_layer * (1 - pvec[g_inds[q]])\n\n    #             p_layer = 1 - 4**width * (1 - sp_layer) / (4**width - 1)\n    #             p = p * p_layer\n\n    #         # Bit-flip readout error as a pre-measurement depolarizing channel.\n    #         sp_layer = _np.prod([(1 - 3 * pvec[r_inds[q]] / 2) for q in circuit.line_labels])\n    #         p_layer = 1 - 4**width * (1 - sp_layer) / (4**width - 1)\n    #         p = p * p_layer\n    #         sp = p + (1 - p) * (1 / 2**width)\n\n    #         return sp\n", "meta": {"hexsha": "cb045db171e60e3803aa6595c6a7df56ccfa3376", "size": 32825, "ext": "py", "lang": "Python", "max_stars_repo_path": "pygsti/objects/oplessmodel.py", "max_stars_repo_name": "drewrisinger/pyGSTi", "max_stars_repo_head_hexsha": "dd4ad669931c7f75e026456470cf33ac5b682d0d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-19T15:11:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T15:11:09.000Z", "max_issues_repo_path": "pygsti/objects/oplessmodel.py", "max_issues_repo_name": "drewrisinger/pyGSTi", "max_issues_repo_head_hexsha": "dd4ad669931c7f75e026456470cf33ac5b682d0d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pygsti/objects/oplessmodel.py", "max_forks_repo_name": "drewrisinger/pyGSTi", "max_forks_repo_head_hexsha": "dd4ad669931c7f75e026456470cf33ac5b682d0d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3413098237, "max_line_length": 120, "alphanum_fraction": 0.6008530084, "include": true, "reason": "import numpy", "num_tokens": 8074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.31742625913050115, "lm_q1q2_score": 0.16490971448859534}}
{"text": "import pdb\nimport os\nimport pandas as pd\nimport dymos as dm\nimport numpy as np\nimport datetime as dt\nfrom typing import Union\nimport openmdao.api as om\nfrom pyNA.src.settings import Settings\nfrom pyNA.src.aircraft import Aircraft\nfrom pyNA.src.trajectory_src.atmosphere import Atmosphere\nfrom pyNA.src.engine import Engine\nfrom scipy.interpolate import RegularGridInterpolator\nfrom pyNA.src.trajectory_src.trajectory_ode import TrajectoryODE\nfrom pyNA.src.trajectory_src.mux import Mux\nfrom pyNA.src.trajectory_src.surrogate_noise import SurrogateNoise\n\n\nclass Trajectory:\n    \"\"\"\n    The trajectory module contains the methods to compute the take-off trajectory used by pyNA.\n    \"\"\"\n\n    def __init__(self, n_order):\n\n        # Initialize path\n        self.path = pd.DataFrame\n        self.n_t = np.int\n\n        # Initialize phases\n        # self.phase_name_lst = ['groundroll', 'rotation', 'liftoff', 'vnrs', 'cutback']\n        self.phase_name_lst = ['groundroll', 'rotation', 'liftoff', 'vnrs', 'cutback']\n        self.phases = dict()\n\n        # Compute transcription for the phases\n        self.num_segments = []\n        self.transcription_order = []\n        self.transcription_phases = []\n        self.phase_size = []\n        for i, phase in enumerate(self.phase_name_lst):\n            if phase == 'groundroll':\n                self.num_segments.append(3)\n                self.transcription_order.append(3)\n            elif phase == 'rotation':\n                self.num_segments.append(3)\n                self.transcription_order.append(3)\n            elif phase == 'liftoff':\n                self.num_segments.append(4)\n                self.transcription_order.append(3)\n            elif phase == 'vnrs':\n                self.num_segments.append(7)\n                self.transcription_order.append(3)\n            elif phase == 'cutback':\n                self.num_segments.append(12)\n                self.transcription_order.append(3)\n            \n            self.transcription_phases.append(dm.GaussLobatto(num_segments=self.num_segments[i], order=self.transcription_order[i], compressed=True, solve_segments=False))\n            self.transcription_phases[i].init_grid()\n            self.phase_size.append(self.num_segments[i] * self.transcription_order[i]+1)\n\n        # Compute size of the muxed trajectory\n        self.trajectory_size = Trajectory.compute_size_output_mux(size_inputs=self.phase_size)\n\n        return\n\n    @staticmethod\n    def get_engine_variables(settings: Settings) -> Union[list, list]:\n        \"\"\"\n        Get the engine parameters to compute during the trajectory computations.\n\n        :param settings: pyna settings\n        :type settings: Settings\n\n        :return: (engine_var, engine_var_units)\n        :rtype: (list, list)\n        \"\"\"\n        # Engine variables\n        engine_var = ['W_f', 'Tti_c', 'Pti_c']\n        engine_var_units = ['kg/s', 'K', 'Pa']\n\n        # Jet parameters\n        engine_var.extend(['V_j', 'rho_j', 'A_j', 'Tt_j', 'M_j'])\n        engine_var_units.extend(['m/s', 'kg/m**3', 'm**2', 'K', None])\n\n        # Core parameters\n        if settings.method_core_turb == 'GE':\n            engine_var.extend(['mdoti_c', 'Ttj_c', 'DTt_des_c'])\n            engine_var_units.extend(['kg/s', 'K', 'K'])\n        elif settings.method_core_turb == 'PW':\n            engine_var.extend(['mdoti_c', 'Ttj_c', 'DTt_des_c', 'rho_te_c', 'c_te_c', 'rho_ti_c', 'c_ti_c'])\n            engine_var_units.extend(['kg/s', 'K', 'K', 'kg/m**3', 'm/s', 'kg/m**3', 'm/s'])\n        \n        # Fan parameters\n        engine_var.extend(['DTt_f', 'mdot_f', 'N_f', 'A_f', 'd_f'])\n        engine_var_units.extend(['K', 'kg/s', 'rpm', 'm**2', 'm'])\n\n        return engine_var, engine_var_units\n\n    def compute_size_output_mux(size_inputs: np.ndarray):\n        \"\"\"\n        Compute vector size of the muxed trajectory.\n\n        :param size_inputs: \n        :type size_inputs: np.ndarray \n\n        \"\"\"\n\n        mux_num = len(size_inputs)\n        \n        size_output = 0\n        for i in range(mux_num):\n            \n            # Add input size to output vector\n            if i < mux_num-1:\n                size_output = size_output + (size_inputs[i]-1)\n            else:\n                size_output = size_output + (size_inputs[i])\n  \n        return size_output\n\n    @staticmethod\n    def compute_minimum_TS(settings: Settings, ac: Aircraft, engine: Engine) -> np.float64:\n        \"\"\"\n        Compute minimum cutback thrust-setting meeting the 4%CG and one-engine-inoperative (OEI) airworthiness requirements.\n        \n        :param settings: pyNA settings\n        :type settings: Settings\n        :param ac: aircraft parameters\n        :type ac: Aircraft\n        :param engine: engine parameters\n        :param engine: Engine\n        :return: TS_max\n        :rtype: np.float64\n\n        \"\"\"\n\n        # Initialize limiting cases\n        gamma_lst = np.array([0, 2.7])\n        nr_engine_lst = np.array([ac.n_eng - 1, ac.n_eng])\n        \n        alpha = np.zeros(2)\n        TS_lst = np.zeros(2)\n\n        for cc, case in enumerate(['OEI', '4%CG']):\n            # Compute atmospheric properties at ac.z_max\n            prob_atm = om.Problem()\n            prob_atm.model.add_subsystem(\"atm\", Atmosphere(num_nodes=1, settings=settings))\n            prob_atm.setup(force_alloc_complex=True)\n            prob_atm.set_val('atm.z', ac.z_max)\n            prob_atm.run_model()\n            rho_0 = prob_atm.get_val('atm.rho_0')\n            c_0 = prob_atm.get_val('atm.c_0')\n\n            # Lift requirement for horizontal, steady climbing flight\n            L = 9.80665 * ac.mtow * np.cos(gamma_lst[cc] * np.pi / 180.)\n            c_l = L / (0.5* rho_0 * ac.v_max ** 2 * ac.af_S_w)\n\n            # Compute required angle of attack to meet lift coefficient\n            c_l_interp = RegularGridInterpolator((ac.aero['alpha'], ac.aero['theta_flaps'], ac.aero['theta_slats']), ac.aero['c_l'])\n            c_l_data = c_l_interp((ac.aero['alpha'], settings.theta_flaps, settings.theta_slats))\n            alpha[cc] = np.interp(c_l, c_l_data, ac.aero['alpha'])\n\n            # Compute corresponding drag coefficient\n            c_d_interp = RegularGridInterpolator((ac.aero['alpha'], ac.aero['theta_flaps'], ac.aero['theta_slats']), ac.aero['c_d'])\n            c_d_data = c_d_interp((ac.aero['alpha'], settings.theta_flaps, settings.theta_slats))\n            c_d = np.interp(alpha[cc], ac.aero['alpha'], c_d_data)\n            \n            # Compute thrust requirement\n            D = (c_d * 0.5 * rho_0 * ac.v_max ** 2 * ac.af_S_w) + ac.mtow * 9.80065 * np.sin(gamma_lst[cc] * np.pi / 180.)\n            F_req = D / nr_engine_lst[cc]\n\n            # Compute thrust available\n            F_n_interp = RegularGridInterpolator((engine.deck['z'], engine.deck['M_0'], engine.deck['TS']), engine.deck['F_n'])\n            F_avl = F_n_interp([ac.z_max, ac.v_max / c_0, 1.])[0]\n\n            # Compute minimum thrust setting\n            TS_lst[cc] = F_req / F_avl\n            # Print results\n            print(case, 'engine thrust-setting requirement: ', np.round(TS_lst[cc], 3))\n\n        # Compute TS_max\n        TS_max = max(TS_lst)\n\n        return TS_max\n\n    def load_time_series(self, settings: Settings) -> None:\n        \"\"\"\n        Loads predefined trajectory timeseries.\n\n        :param settings: pyna settings\n        :type settings: Settings\n\n        :return: None\n\n        \"\"\"\n\n        # Load trajectory data for the specific observer\n        # Source: validation noise assessment data set of NASA STCA (Berton et al., 2019)\n        self.path = pd.read_csv(settings.pyNA_directory + '/cases/' + settings.case_name + '/trajectory/' + settings.output_directory_name + '/' + settings.trajectory_file_name)\n        self.n_t = np.size(self.path['t_source [s]'])\n\n        return None\n\n    def load_operating_point(self, settings:Settings, time_step: int) -> None:\n        \"\"\"\n        Loads predefined trajectory timeseries.\n\n        :param settings: pyna settings\n        :type settings: Settings\n        :param time_step: time step of the operating point in the trajectory time series\n        :type time_step: int\n\n        :return: None\n\n        \"\"\"\n\n        # Load trajectory data for the specific observer\n        # Source: validation noise assessment data set of NASA STCA (Berton et al., 2019)\n        self.path = pd.read_csv(settings.pyNA_directory + '/cases/' + settings.case_name + '/trajectory/' + settings.output_directory_name + '/' + settings.trajectory_file_name)\n        \n        # Select operating point\n        cols = self.path.columns\n        op_point = pd.DataFrame(np.reshape(self.path.values[time_step, :], (1, len(cols))))\n        op_point.columns = cols\n\n        # Duplicate operating for theta range (np.linspace(0, 180, 19))\n        self.path = pd.DataFrame()\n        for i in np.arange(19):\n            self.path = self.path.append(op_point)\n\n        self.n_t = 19\n\n        return None  \n\n    def setup(self, problem: om.Problem, settings: Settings, ac: Aircraft, engine: Engine, trajectory_mode: str, objective: str) -> None:\n        \"\"\"\n        Setup take-off trajectory module using the following phases:\n\n        * ``Ground roll``:  acceleration from V=0\n        * ``Flaps down``:   accelerate further to V=kVstall while deploying flaps during x seconds\n        * ``Rotation``:     rotate at dalpha/dt = cnst until load factor n=1;\n        * ``Lift off``:     climb until obstacle is cleared (35ft).\n        * ``VNRS``:         any VNRS can be applied in this phase, e.g. PTCB or PHLD\n        * ``cutback``:      a pilot-initiated thrust cut-back to a constant thrust-setting is applied\n\n        :param problem: openmdao problem\n        :type problem: om.Problem\n        :param settings: pyna settings\n        :type settings: Settings\n        :param ac: aircraft parameters\n        :type ac: Aircraft\n        :param engine: engine parameters\n        :param engine: Engine\n        :param objective: optimization objective\n        :type objective: str\n\n        :return: None\n\n        \"\"\"\n\n        # Set solver settings for the problem\n        problem.driver = om.pyOptSparseDriver(optimizer='IPOPT')\n        problem.driver.opt_settings['print_level'] = 5\n        problem.driver.opt_settings['nlp_scaling_method'] = 'gradient-based'\n\n        problem.driver.declare_coloring(tol=1e-12)\n        problem.model.linear_solver = om.LinearRunOnce()\n        problem.driver.opt_settings['output_file'] = settings.pyNA_directory + '/cases/' + settings.case_name + '/output/' + settings.output_directory_name + '/IPOPT_trajectory_convergence.out'\n\n        if objective == 'noise':\n            problem.driver.opt_settings['tol'] = 1e-2\n            problem.driver.opt_settings['acceptable_tol'] = 1e-1\n        else:\n            problem.driver.opt_settings['tol'] = settings.tol\n            problem.driver.opt_settings['acceptable_tol'] = 1e-3\n\n        problem.driver.opt_settings['max_iter'] = settings.max_iter\n        problem.driver.opt_settings['mu_strategy'] = 'adaptive'\n        problem.driver.opt_settings['bound_mult_init_method'] = 'mu-based'\n        problem.driver.opt_settings['mu_init'] = 0.01\n        problem.driver.opt_settings['constr_viol_tol'] = 1e-3\n        problem.driver.opt_settings['compl_inf_tol'] = 1e-3\n        problem.driver.opt_settings['acceptable_iter'] = 0\n        problem.driver.opt_settings['acceptable_constr_viol_tol'] = 1e-1\n        problem.driver.opt_settings['acceptable_compl_inf_tol'] = 1e-1\n        problem.driver.opt_settings['acceptable_obj_change_tol'] = 1e-1\n\n        # Setup trajectory and initialize trajectory transcription and compute number of points per phase\n        traj = dm.Trajectory()\n        problem.model.add_subsystem('phases', traj)\n\n        # Get engine variables\n        engine_var, engine_var_units = Trajectory.get_engine_variables(settings)\n\n        # Compute the minimum thrust-setting based on 4% climb gradient and OEI requirement\n        if settings.TS_cutback:\n            TS_min = settings.TS_cutback\n        else:\n            TS_min = Trajectory.compute_minimum_TS(settings=settings, ac=ac, engine=engine)\n        \n        # Phase 1: ground roll\n        if 'groundroll' in self.phase_name_lst:\n            opts = {'phase': 'groundroll', 'ac': ac, 'engine': engine, 'settings': settings, 'objective': objective}\n            self.phases['groundroll'] = dm.Phase(ode_class=TrajectoryODE, ode_init_kwargs=opts, transcription=self.transcription_phases[0])\n            self.phases['groundroll'].set_time_options(fix_initial=True, duration_bounds=(0, 60), duration_ref=100.)\n            self.phases['groundroll'].add_state('x', rate_source='flight_dynamics.x_dot', units='m', fix_initial=True, fix_final=False, ref=1000.)\n            self.phases['groundroll'].add_state('v', targets='v', rate_source='flight_dynamics.v_dot', units='m/s', fix_initial=True, fix_final=False, ref=100.)\n            self.phases['groundroll'].add_state('alpha', targets='alpha', rate_source='flight_dynamics.alpha_dot', units='deg', fix_initial=True, fix_final=False, lower=ac.aero['alpha'][0], upper=ac.aero['alpha'][-1], ref=1.)\n            self.phases['groundroll'].add_parameter('z', targets='z', units='m', val=0., dynamic=True,include_timeseries=True)\n            self.phases['groundroll'].add_parameter('gamma', targets='gamma', units='deg', val=0., dynamic=True, include_timeseries=True)\n            self.phases['groundroll'].add_parameter('TS', targets='propulsion.TS', units=None, val=settings.TS_to, dynamic=True, include_timeseries=True)\n            self.phases['groundroll'].add_parameter('TS_min', units=None, val=1, dynamic=True, include_timeseries=True)\n            if settings.PKROT:\n                self.phases['groundroll'].add_parameter('k_rot', targets='flight_dynamics.k_rot', units=None, lower=1.1, upper=1.6, dynamic=False, val=ac.k_rot, opt=True)\n            else:\n                self.phases['groundroll'].add_parameter('k_rot', targets='flight_dynamics.k_rot', units=None, dynamic=False, val=ac.k_rot, opt=False)\n            # PHLD\n            # if objective == 'noise' and settings.PHLD:\n                # self.phases['groundroll'].add_parameter('theta_flaps', targets='theta_flaps', units='deg', val=ac.aero['theta_flaps_c_d_min_gr'], dynamic=True, include_timeseries=True, opt=False)\n            # else:\n            self.phases['groundroll'].add_parameter('theta_flaps', targets='theta_flaps', units='deg', val=settings.theta_flaps, dynamic=True, include_timeseries=True)\n            self.phases['groundroll'].add_parameter('theta_slats', targets='theta_slats', units='deg', val=settings.theta_slats, dynamic=True, include_timeseries=True)\n            self.phases['groundroll'].add_timeseries('interpolated', transcription=dm.GaussLobatto(num_segments=self.phase_size[0]-1,order=3, solve_segments=False, compressed=True), subset='state_input')\n            self.phases['groundroll'].add_boundary_constraint('flight_dynamics.v_rot_residual', equals=0., loc='final', ref=100, units='m/s')\n\n        # Phase 2: rotation phase\n        if 'rotation' in self.phase_name_lst:\n            opts = {'phase': 'rotation', 'ac': ac, 'engine': engine, 'settings': settings, 'objective': objective}\n            self.phases['rotation'] = dm.Phase(ode_class=TrajectoryODE, transcription=self.transcription_phases[1], ode_init_kwargs=opts)\n            self.phases['rotation'].set_time_options(initial_bounds=(20, 60), duration_bounds=(0, 60), initial_ref=100., duration_ref=100.)\n            self.phases['rotation'].add_state('x', rate_source='flight_dynamics.x_dot', units='m', fix_initial=False, fix_final=False, ref=1000.)\n            self.phases['rotation'].add_state('v', targets='v', rate_source='flight_dynamics.v_dot', units='m/s', fix_initial=False, fix_final=False, ref=100.)\n            self.phases['rotation'].add_state('alpha', targets='alpha', rate_source='flight_dynamics.alpha_dot', units='deg', fix_initial=False, fix_final=False, lower=ac.aero['alpha'][0], upper=ac.aero['alpha'][-1], ref=10.)\n            self.phases['rotation'].add_parameter('z', targets='z', units='m', val=0., dynamic=True,include_timeseries=True)\n            self.phases['rotation'].add_parameter('gamma', targets='gamma', units='deg', val=0., dynamic=True, include_timeseries=True)\n            self.phases['rotation'].add_parameter('TS', targets='propulsion.TS', units=None, val=settings.TS_to, dynamic=True, include_timeseries=True)\n            self.phases['rotation'].add_parameter('TS_min', units=None, val=1, dynamic=True, include_timeseries=True)\n            # PHLD\n            # if objective == 'noise' and settings.PHLD:\n                # self.phases['rotation'].add_parameter('theta_flaps', targets='theta_flaps', units='deg', val=settings.theta_flaps, lower=ac.aero['theta_flaps'][0], upper=ac.aero['theta_flaps'][-1], dynamic=True, include_timeseries=True, opt=True, ref=10.)\n                # self.phases['rotation'].add_parameter('theta_flaps', targets='theta_flaps', units='deg', val=15., dynamic=True, include_timeseries=True)\n            # else:\n            self.phases['rotation'].add_parameter('theta_flaps', targets='theta_flaps', units='deg', val=settings.theta_flaps, dynamic=True, include_timeseries=True)\n            self.phases['rotation'].add_parameter('theta_slats', targets='theta_slats', units='deg', val=settings.theta_slats, dynamic=True, include_timeseries=True)\n            self.phases['rotation'].add_timeseries('interpolated', transcription=dm.GaussLobatto(num_segments=self.phase_size[1]-1, order=3, solve_segments=False, compressed=True), subset='state_input')\n            self.phases['rotation'].add_boundary_constraint('flight_dynamics.n', equals=1., loc='final', ref=1, units=None)\n\n        # Phase 3: lift-off phase\n        if 'liftoff' in self.phase_name_lst:\n            opts = {'phase': 'liftoff', 'ac': ac, 'engine': engine, 'settings': settings, 'objective': objective}\n            self.phases['liftoff'] = dm.Phase(ode_class=TrajectoryODE, transcription=self.transcription_phases[2], ode_init_kwargs=opts)\n            self.phases['liftoff'].set_time_options(initial_bounds=(20, 150), duration_bounds=(0, 500), initial_ref=100., duration_ref=100., fix_duration=False)\n            self.phases['liftoff'].add_state('x', rate_source='flight_dynamics.x_dot', units='m', fix_initial=False, fix_final=False, ref=10000.)\n            self.phases['liftoff'].add_state('z', rate_source='flight_dynamics.z_dot', units='m', fix_initial=False, fix_final=True, ref=10.)\n            self.phases['liftoff'].add_state('v', targets='v', rate_source='flight_dynamics.v_dot', units='m/s', fix_initial=False, fix_final=False, ref=100.)\n            self.phases['liftoff'].add_state('gamma', rate_source='flight_dynamics.gamma_dot', units='deg', fix_initial=False, fix_final=False, ref=10.)\n            self.phases['liftoff'].add_control('alpha', targets='alpha', units='deg', lower=ac.aero['alpha'][0], upper=ac.aero['alpha'][-1], rate_continuity=True, rate_continuity_scaler=1.0, rate2_continuity=False, opt=True, ref=10.)\n            self.phases['liftoff'].add_timeseries('interpolated', transcription=dm.GaussLobatto(num_segments=self.phase_size[2]-1, order=3, solve_segments=False, compressed=True), subset='state_input')\n            self.phases['liftoff'].add_path_constraint(name='flight_dynamics.gamma_dot', lower=0., units='deg/s')\n            self.phases['liftoff'].add_path_constraint(name='flight_dynamics.eas_dot', lower=0., units='m/s**2')\n            self.phases['liftoff'].add_parameter('TS', targets='propulsion.TS', units=None, val=settings.TS_to, dynamic=True, include_timeseries=True)\n            self.phases['liftoff'].add_parameter('TS_min', units=None, val=1, dynamic=True, include_timeseries=True)\n            # PHLD\n            # if objective == 'noise' and settings.PHLD:\n                # self.phases['liftoff'].add_parameter('theta_flaps', targets='theta_flaps', units='deg', val=settings.theta_flaps, lower=ac.aero['theta_flaps'][0], upper=ac.aero['theta_flaps'][-1], dynamic=True, include_timeseries=True, opt=True, ref=10.)                \n                # self.phases['liftoff'].add_parameter('theta_flaps', targets='theta_flaps', units='deg', val=15, dynamic=True, include_timeseries=True, opt=True)\n            # else:\n            self.phases['liftoff'].add_parameter('theta_flaps', targets='theta_flaps', units='deg', val=settings.theta_flaps, dynamic=True, include_timeseries=True)\n            self.phases['liftoff'].add_parameter('theta_slats', targets='theta_slats', units='deg', val=settings.theta_slats, dynamic=True, include_timeseries=True)\n\n        # Phase 4: vnrs phase\n        if 'vnrs' in self.phase_name_lst:\n            opts = {'phase': 'vnrs', 'ac': ac, 'engine': engine, 'settings': settings, 'objective': objective}\n            self.phases['vnrs'] = dm.Phase(ode_class=TrajectoryODE, transcription=self.transcription_phases[3], ode_init_kwargs=opts)\n            self.phases['vnrs'].set_time_options(initial_bounds=(20, 150), duration_bounds=(0, 500), initial_ref=100., duration_ref=100.)            \n            if trajectory_mode == 'flyover':\n                self.phases['vnrs'].add_state('x', rate_source='flight_dynamics.x_dot', units='m', fix_initial=False, fix_final=True, ref=10000.)\n                self.phases['vnrs'].add_state('z', rate_source='flight_dynamics.z_dot', units='m', fix_initial=True, fix_final=False, ref=1000.)\n            elif trajectory_mode == 'cutback':\n                self.phases['vnrs'].add_state('x', rate_source='flight_dynamics.x_dot', units='m', fix_initial=False, fix_final=False, ref=10000.)\n                self.phases['vnrs'].add_state('z', rate_source='flight_dynamics.z_dot', units='m', fix_initial=True, fix_final=True, ref=1000.)\n            self.phases['vnrs'].add_state('v', targets='v', rate_source='flight_dynamics.v_dot', units='m/s', fix_initial=False, fix_final=False, ref=100.)\n            self.phases['vnrs'].add_state('gamma', rate_source='flight_dynamics.gamma_dot', units='deg', fix_initial=False, fix_final=False, ref=10.)\n            self.phases['vnrs'].add_control('alpha', targets='alpha', units='deg', lower=5., upper=ac.aero['alpha'][-1], rate_continuity=True, rate_continuity_scaler=1.0, rate2_continuity=False, opt=True, ref=10.)\n            self.phases['vnrs'].add_timeseries('interpolated', transcription=dm.GaussLobatto(num_segments=self.phase_size[3]-1, order=3, solve_segments=False, compressed=True), subset='state_input')\n            self.phases['vnrs'].add_path_constraint(name='flight_dynamics.eas_dot', lower=0., units='m/s**2')\n            self.phases['vnrs'].add_path_constraint(name='gamma', lower=0., units='deg', ref=10.)\n            # PTCB\n            if objective == 'noise' and settings.PTCB:\n                self.phases['vnrs'].add_control('TS', targets='propulsion.TS', units=None, upper=settings.TS_to, lower=TS_min, val=TS_min, opt=True, rate_continuity=True, rate2_continuity=False, ref=1.)\n                self.phases['vnrs'].add_path_constraint(name='TS', lower=TS_min, upper=1, units=None, ref=1.)\n            else:\n                self.phases['vnrs'].add_parameter('TS', targets='propulsion.TS', units=None, val=settings.TS_vnrs, dynamic=True, include_timeseries=True)\n            # PHLD\n            if objective == 'noise' and settings.PHLD:\n                self.phases['vnrs'].add_control('theta_flaps', targets='theta_flaps', units='deg', val=0., lower=ac.aero['theta_flaps'][0], upper=ac.aero['theta_flaps'][-1], opt=True, rate_continuity=True, rate2_continuity=False, ref=1.)\n                # self.phases['vnrs'].add_parameter('theta_flaps', targets='theta_flaps', units='deg', val=0., lower=ac.aero['theta_flaps'][0], upper=ac.aero['theta_flaps'][-1], dynamic=True, include_timeseries=True, opt=True)\n            else:\n                self.phases['vnrs'].add_parameter('theta_flaps', targets='theta_flaps', units='deg', val=settings.theta_flaps, dynamic=True, include_timeseries=True)\n            self.phases['vnrs'].add_parameter('theta_slats', targets='theta_slats', units='deg', val=settings.theta_slats, dynamic=True, include_timeseries=True)\n\n        # Phase 5: cutback phase\n        if 'cutback' in self.phase_name_lst:\n            opts = {'phase': 'cutback', 'ac': ac, 'engine': engine, 'settings': settings, 'objective': objective}\n            self.phases['cutback'] = dm.Phase(ode_class=TrajectoryODE, transcription=self.transcription_phases[4], ode_init_kwargs=opts)\n            self.phases['cutback'].set_time_options(initial_bounds=(20, 150), duration_bounds=(0, 500), initial_ref=100., duration_ref=100.)\n            if trajectory_mode == 'flyover':\n                self.phases['cutback'].add_state('x', rate_source='flight_dynamics.x_dot', units='m', fix_initial=True, fix_final=False, ref=10000.)\n                self.phases['cutback'].add_state('z', rate_source='flight_dynamics.z_dot', units='m', fix_initial=False, fix_final=True, ref=1000.)\n            elif trajectory_mode == 'cutback':\n                self.phases['cutback'].add_state('x', rate_source='flight_dynamics.x_dot', units='m', fix_initial=False, fix_final=False, ref=10000.)\n                self.phases['cutback'].add_state('z', rate_source='flight_dynamics.z_dot', units='m', fix_initial=True, fix_final=True, ref=1000.)\n            self.phases['cutback'].add_state('v', targets='v', rate_source='flight_dynamics.v_dot', units='m/s', fix_initial=False, fix_final=False, ref=100.)\n            self.phases['cutback'].add_state('gamma', rate_source='flight_dynamics.gamma_dot', units='deg', fix_initial=False, fix_final=False, ref=10.)\n            self.phases['cutback'].add_control('alpha', targets='alpha', units='deg', lower=ac.aero['alpha'][0], upper=ac.aero['alpha'][-1], rate_continuity=True, rate_continuity_scaler=1.0, rate2_continuity=False, opt=True, ref=10.)\n            self.phases['cutback'].add_path_constraint(name='flight_dynamics.eas_dot', lower=0., units='m/s**2')\n            self.phases['cutback'].add_path_constraint(name='flight_dynamics.gamma_dot', upper=0., units='deg/s')\n            self.phases['cutback'].add_boundary_constraint('v', loc='final', upper=ac.v_max, ref=100., units='m/s')\n            self.phases['cutback'].add_timeseries('interpolated', transcription=dm.GaussLobatto(num_segments=self.phase_size[4]-1, order=3, solve_segments=False, compressed=True), subset='state_input')\n            # PTCB\n            self.phases['cutback'].add_parameter('TS', targets='propulsion.TS', units=None, val=TS_min, dynamic=True, include_timeseries=True)\n            # PHLD\n            if objective == 'noise' and settings.PHLD:\n                self.phases['cutback'].add_parameter('theta_flaps', targets='theta_flaps', units='deg', val=0., lower=ac.aero['theta_flaps'][0], upper=ac.aero['theta_flaps'][-1], dynamic=True, include_timeseries=True, opt=True, ref=10.)\n            else:\n                self.phases['cutback'].add_parameter('theta_flaps', targets='theta_flaps', units='deg', val=settings.theta_flaps, dynamic=True, include_timeseries=True)\n            self.phases['cutback'].add_parameter('theta_slats', targets='theta_slats', units='deg', val=settings.theta_slats, dynamic=True, include_timeseries=True)\n\n        # Add outputs to timeseries for each phase\n        for j, phase_name in enumerate(self.phase_name_lst):\n            for i in np.arange(len(engine_var)):\n                self.phases[phase_name].add_timeseries_output('propulsion.'+ engine_var[i], timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('aerodynamics.M_0', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('p_0', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('rho_0', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('I_0', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('drho_0_dz', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('T_0', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('c_0', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('mu_0', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('propulsion.W_f', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('emissions.mdot_NOx', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('emissions.EINOx', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('flight_dynamics.y', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('flight_dynamics.n', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('flight_dynamics.I_landing_gear', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('flight_dynamics.eas', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('flight_dynamics.n', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('aerodynamics.L', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('aerodynamics.D', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('propulsion.F_n', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('propulsion.W_f', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('clcd.c_l', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('clcd.c_l_max', timeseries='interpolated')\n            self.phases[phase_name].add_timeseries_output('clcd.c_d', timeseries='interpolated')\n\n        # Add phases to the trajectory\n        for phase_name in self.phase_name_lst:\n            traj.add_phase(phase_name, self.phases[phase_name])\n\n        # Link phases\n        if 'rotation' in self.phase_name_lst:\n            traj.link_phases(phases=['groundroll', 'rotation'], vars=['time', 'x', 'v', 'alpha'])\n            # if objective == 'noise' and settings.PHLD:\n                # traj.add_linkage_constraint(phase_a='groundroll', phase_b='rotation', var_a='theta_flaps', var_b='theta_flaps', loc_a='final', loc_b='initial')\n\n        if 'liftoff' in self.phase_name_lst:\n            traj.link_phases(phases=['rotation', 'liftoff'], vars=['time', 'x', 'z', 'v', 'alpha', 'gamma'])\n            # if objective == 'noise' and settings.PHLD:\n                # traj.add_linkage_constraint(phase_a='rotation', phase_b='liftoff', var_a='theta_flaps', var_b='theta_flaps', loc_a='final', loc_b='initial')\n        \n        if 'vnrs' in self.phase_name_lst:\n            traj.link_phases(phases=['liftoff', 'vnrs'],  vars=['time', 'x', 'v', 'alpha', 'gamma'])\n            if objective == 'noise' and settings.PTCB:\n                traj.add_linkage_constraint(phase_a='liftoff', phase_b='vnrs', var_a='TS', var_b='TS', loc_a='final', loc_b='initial')\n            if objective == 'noise' and settings.PHLD:\n                traj.add_linkage_constraint(phase_a='liftoff', phase_b='vnrs', var_a='theta_flaps', var_b='theta_flaps', loc_a='final', loc_b='initial')\n\n        if 'cutback' in self.phase_name_lst:\n            if trajectory_mode == 'flyover':\n                traj.link_phases(phases=['vnrs', 'cutback'], vars=['time', 'z', 'v', 'alpha', 'gamma'])\n            elif trajectory_mode == 'cutback':\n                traj.link_phases(phases=['vnrs', 'cutback'], vars=['time', 'x', 'v', 'alpha', 'gamma'])\n            # if objective == 'noise' and settings.PTCB:\n                # traj.add_linkage_constraint(phase_a='vnrs', phase_b='cutback', var_a='TS', var_b='TS', loc_a='final', loc_b='initial')\n            if objective == 'noise' and settings.PHLD:\n                traj.add_linkage_constraint(phase_a='vnrs', phase_b='cutback', var_a='theta_flaps', var_b='theta_flaps', loc_a='final', loc_b='initial')\n\n        # Mux trajectory variables\n        mux_t = problem.model.add_subsystem(name='trajectory', subsys=Mux(size_inputs=np.array(self.phase_size), size_output=self.trajectory_size))\n        var   = ['time', 'x', 'y', 'z', 'v', 'M_0', 'alpha', 'gamma', 'TS', 'I_landing_gear', 'theta_flaps', 'theta_slats','F_n', 'L', 'D', 'eas', 'n', 'p_0','rho_0','drho_0_dz','T_0','c_0','mu_0', 'I_0', 'W_f', 'mdot_NOx', 'EINOx', 'c_l', 'c_d', 'c_l_max']\n        units = ['s', 'm', 'm', 'm', 'm/s', None, 'deg', 'deg', None, None, 'deg', 'deg', 'N', 'N', 'N', 'm/s', None, 'Pa', 'kg/m**3', 'kg/m**4', 'K', 'm/s', 'kg/m/s', 'kg/m**2/s', 'kg/s', 'kg/s', None, None, None, None]\n        for i in np.arange(len(var)):\n            # Add the variables to the trajectory mux\n            if var[i] == 'time':\n                mux_t.add_var('t_s', units=units[i])\n            else:\n                mux_t.add_var(var[i], units=units[i])\n\n            # Connect phase variables to trajectory mux\n            if var[i] == 'time':\n                for j, phase_name in enumerate(self.phase_name_lst):\n                    problem.model.connect('phases.' + phase_name + '.interpolated.' + var[i], 'trajectory.t_s_' + str(j))\n\n            elif var[i] in ['x', 'v']:\n                for j, phase_name in enumerate(self.phase_name_lst):\n                    problem.model.connect('phases.' + phase_name + '.interpolated.states:' + var[i], 'trajectory.' + var[i] + '_' + str(j))\n\n            elif var[i] in ['z', 'gamma']:\n                for j, phase_name in enumerate(self.phase_name_lst):\n                    if phase_name in {'groundroll','rotation'}:\n                        problem.model.connect('phases.' + phase_name + '.interpolated.parameters:' + var[i], 'trajectory.' + var[i] + '_' + str(j))\n                    else:\n                        problem.model.connect('phases.' + phase_name + '.interpolated.states:' + var[i], 'trajectory.' + var[i] + '_' + str(j))\n\n            elif var[i] in ['alpha']:\n                for j, phase_name in enumerate(self.phase_name_lst):\n                    if phase_name in {'groundroll', 'rotation'}:\n                        problem.model.connect('phases.' + phase_name + '.interpolated.states:' + var[i],'trajectory.' + var[i] + '_' + str(j))\n                    else:\n                        problem.model.connect('phases.' + phase_name + '.interpolated.controls:' + var[i], 'trajectory.' + var[i] + '_' + str(j))\n\n            elif var[i] in ['TS']:\n                if objective == 'noise' and settings.PTCB:\n                    for j, phase_name in enumerate(self.phase_name_lst):\n                        if phase_name in ['groundroll', 'rotation', 'liftoff']:\n                            problem.model.connect('phases.' + phase_name + '.interpolated.parameters:' + var[i], 'trajectory.' + var[i] + '_' + str(j))\n                        elif phase_name == 'vnrs':\n                            problem.model.connect('phases.' + phase_name + '.interpolated.controls:' + var[i], 'trajectory.' + var[i] + '_' + str(j))\n                        elif phase_name == 'cutback':\n                            problem.model.connect('phases.' + phase_name + '.interpolated.parameters:' + var[i], 'trajectory.' + var[i] + '_' + str(j))\n                else:\n                    for j, phase_name in enumerate(self.phase_name_lst):\n                        if phase_name in ['groundroll', 'rotation', 'liftoff', 'vnrs']:\n                            problem.model.connect('phases.' + phase_name + '.interpolated.parameters:' + var[i], 'trajectory.' + var[i] + '_' + str(j))\n                        elif phase_name == 'cutback':\n                            problem.model.connect('phases.' + phase_name + '.interpolated.parameters:' + var[i], 'trajectory.' + var[i] + '_' + str(j))\n\n            elif var[i] in ['theta_slats']:\n                for j, phase_name in enumerate(self.phase_name_lst):\n                    problem.model.connect('phases.' + phase_name + '.interpolated.parameters:' + var[i], 'trajectory.' + var[i] + '_' + str(j))\n\n            elif var[i] in ['theta_flaps']:\n                if objective == 'noise' and settings.PHLD:\n                    for j, phase_name in enumerate(self.phase_name_lst):\n                        if phase_name == 'vnrs':\n                            problem.model.connect('phases.' + phase_name + '.interpolated.controls:' + var[i], 'trajectory.' + var[i] + '_' + str(j))\n                        else:\n                            problem.model.connect('phases.' + phase_name + '.interpolated.parameters:' + var[i], 'trajectory.' + var[i] + '_' + str(j))\n                else:\n                    for j, phase_name in enumerate(self.phase_name_lst):\n                        problem.model.connect('phases.' + phase_name + '.interpolated.parameters:' + var[i], 'trajectory.' + var[i] + '_' + str(j))\n\n            elif var[i] in ['y', 'F_n', 'L', 'D', 'eas', 'n', 'I_landing_gear','M_0', 'p_0','rho_0','drho_0_dz','T_0','c_0','c_bar','mu_0', 'I_0', 'W_f', 'mdot_NOx', 'EINOx', 'c_l', 'c_d', 'c_l_max']:\n                for j, phase_name in enumerate(self.phase_name_lst):\n                    problem.model.connect('phases.' + phase_name + '.interpolated.' + var[i], 'trajectory.' + var[i] + '_' + str(j))\n\n        # Mux engine variables\n        mux_e = problem.model.add_subsystem(name='engine', subsys=Mux(size_inputs=np.array(self.phase_size), size_output=self.trajectory_size))\n        for i in np.arange(len(engine_var)):\n            mux_e.add_var(engine_var[i], units=engine_var_units[i])\n            for j, phase_name in enumerate(self.phase_name_lst):\n                problem.model.connect('phases.' + phase_name + '.interpolated.' + engine_var[i], 'engine.' + engine_var[i] + '_' + str(j))\n\n        return None\n\n    def compute(self, problem: om.Problem, settings: Settings, ac: Aircraft, run_driver: bool, init_trajectory: om.Problem, trajectory_mode: str, objective: str) -> None:\n        \"\"\"\n        Run trajectory initial guess with minimal time to climb.\n\n        :param problem: openmdao problem\n        :type problem: om.Problem\n        :param settings: pyna settings\n        :type settings: Settings\n        :param ac: aircraft parameters\n        :type ac: Aircraft\n        :param run_driver: flag to enable run_driver setting for dymos run_model function\n        :type run_driver: bool\n        :param init_trajectory: initialization trajectory\n        :type init_trajectory: om.Problem\n        :param objective: optimization objective\n        :type objective: str\n\n        :return: None\n        \"\"\"\n\n        # Add objective for trajectory model\n        if objective == None:\n            # No optimization objective required; problem is run with run_driver = False\n            pass\n\n        elif objective == 'x_end':\n            problem.model.add_objective('trajectory.x', index=-1, ref=1000.)\n        \n        elif objective == 't_end':\n            problem.model.add_objective('trajectory.t_s', index=-1, ref=1000.)\n        \n        elif objective == 'noise':\n            # Optimization bjective is set in the noise.setup_trajectory_noise() method\n            pass\n\n        elif objective == 'x_takeoff_x_end':\n            problem.model.add_subsystem('combined', om.ExecComp('objective = x_to/2000 + x_end/7000', \n                                                                x_to={'val': 0., 'units': 'm'},\n                                                                x_end={'val': 0., 'units': 'm'}), \n                                                                promotes=['objective'])\n            problem.model.connect('phases.liftoff.timeseries.states:x' , 'combined.x_to', src_indices=[-1])\n            problem.model.connect('trajectory.x', 'combined.x_end', src_indices=[-1])\n            problem.model.add_objective('objective', scaler=10.)\n\n        elif objective == 'noise_surrogate':\n            x_observer = np.array([6500., 0., 0.3048*4.])\n            problem.model.add_subsystem('noise', SurrogateNoise(num_nodes=self.trajectory_size, x_observer=x_observer), promotes_outputs=['noise'])\n            problem.model.connect('trajectory.x', 'noise.x')\n            problem.model.connect('trajectory.y', 'noise.y')\n            problem.model.connect('trajectory.z', 'noise.z')\n            problem.model.connect('trajectory.t_s', 'noise.t_s')\n            problem.model.add_objective('noise', scaler=1)\n\n        else: \n            raise ValueError('Invalid control objective specified.')\n\n        # Run the openMDAO problem setup\n        problem.setup(force_alloc_complex=True)\n\n        # Attach a recorder to the problem to save model data\n        if settings.save_results:\n            problem.add_recorder(om.SqliteRecorder(settings.pyNA_directory + '/cases/' + settings.case_name + '/output/' + settings.output_directory_name + '/' + settings.output_file_name))\n\n        # Set initial guess for the trajectory problem\n        if init_trajectory is None:\n\n            # Phase 1: groundroll\n            if 'groundroll' in self.phase_name_lst:\n                problem['phases.groundroll.t_initial'] = 0.0\n                problem['phases.groundroll.t_duration'] = 30.0\n                problem['phases.groundroll.states:x'] = self.phases['groundroll'].interp(ys=[0, 1000], nodes='state_input')\n                problem['phases.groundroll.states:v'] = self.phases['groundroll'].interp(ys=[0.0, 60], nodes='state_input')\n                problem['phases.groundroll.states:alpha'] = self.phases['groundroll'].interp(ys=[ac.alpha_0, ac.alpha_0], nodes='state_input')\n\n            # Phase 2: rotation\n            if 'rotation' in self.phase_name_lst:\n                problem['phases.rotation.t_initial'] = 30.0\n                problem['phases.rotation.t_duration'] = 10.0\n                problem['phases.rotation.states:x'] = self.phases['rotation'].interp(ys=[1500, 2000], nodes='state_input')\n                problem['phases.rotation.states:v'] = self.phases['rotation'].interp(ys=[100, 110.], nodes='state_input')\n                problem['phases.rotation.states:alpha'] = self.phases['rotation'].interp(ys=[ac.alpha_0, 15*np.pi/180.], nodes='state_input')\n\n            # Phase 3: lift-off\n            if 'liftoff' in self.phase_name_lst:\n                if trajectory_mode == 'flyover':\n                    z_cutback_guess = 500.\n                elif trajectory_mode == 'cutback':\n                    z_cutback_guess = settings.z_cutback\n                problem['phases.liftoff.t_initial'] = 40.0\n                problem['phases.liftoff.t_duration'] = 2.\n                problem['phases.liftoff.states:x'] = self.phases['liftoff'].interp(ys=[2000., 3500.], nodes='state_input')\n                problem['phases.liftoff.states:z'] = self.phases['liftoff'].interp(ys=[0., 35*0.3048], nodes='state_input')\n                problem['phases.liftoff.states:v'] = self.phases['liftoff'].interp(ys=[110., 110.], nodes='state_input')\n                problem['phases.liftoff.states:gamma'] = self.phases['liftoff'].interp(ys=[0, 4.], nodes='state_input')\n                problem['phases.liftoff.controls:alpha'] = self.phases['liftoff'].interp(ys=[15., 15.], nodes='control_input')\n\n            # # Phase 4: vnrs \n            if 'vnrs' in self.phase_name_lst:\n                problem['phases.vnrs.t_initial'] = 50.0\n                problem['phases.vnrs.t_duration'] = 50.0\n                problem['phases.vnrs.states:x'] = self.phases['vnrs'].interp(ys=[3500., 6501.], nodes='state_input')\n                problem['phases.vnrs.states:z'] = self.phases['vnrs'].interp(ys=[35*0.3048, z_cutback_guess], nodes='state_input')\n                problem['phases.vnrs.states:v'] = self.phases['vnrs'].interp(ys=[110., 110.], nodes='state_input')\n                problem['phases.vnrs.states:gamma'] = self.phases['vnrs'].interp(ys=[4., 15.], nodes='state_input')\n                problem['phases.vnrs.controls:alpha'] = self.phases['vnrs'].interp(ys=[15., 15.], nodes='control_input')\n                \n            # Phase 5: cutback\n            if 'cutback' in self.phase_name_lst:\n                problem['phases.cutback.t_initial'] = 100.0\n                problem['phases.cutback.t_duration'] = 50.0\n                problem['phases.cutback.states:x'] = self.phases['cutback'].interp(ys=[6501., 20000.], nodes='state_input')\n                problem['phases.cutback.states:z'] = self.phases['cutback'].interp(ys=[z_cutback_guess, ac.z_max], nodes='state_input')\n                problem['phases.cutback.states:v'] = self.phases['cutback'].interp(ys=[110., 110.], nodes='state_input')\n                problem['phases.cutback.states:gamma'] = self.phases['cutback'].interp(ys=[15, 15.], nodes='state_input')\n                problem['phases.cutback.controls:alpha'] = self.phases['cutback'].interp(ys=[15., 15.], nodes='control_input')\n                \n        else:\n            # Phase 1: groundroll \n            if 'groundroll' in self.phase_name_lst:\n                problem['phases.groundroll.t_initial'] = init_trajectory.get_val('phases.groundroll.t_initial')\n                problem['phases.groundroll.t_duration'] = init_trajectory.get_val('phases.groundroll.t_duration')\n                problem['phases.groundroll.timeseries.time'] = init_trajectory.get_val('phases.groundroll.timeseries.time')\n                problem['phases.groundroll.states:x'] = init_trajectory.get_val('phases.groundroll.states:x')\n                problem['phases.groundroll.states:v'] = init_trajectory.get_val('phases.groundroll.states:v')\n                problem['phases.groundroll.states:alpha'] = init_trajectory.get_val('phases.groundroll.states:alpha')\n\n            # Phase 2: rotation\n            if 'rotation' in self.phase_name_lst:\n                problem['phases.rotation.t_initial'] = init_trajectory.get_val('phases.rotation.t_initial')\n                problem['phases.rotation.t_duration'] = init_trajectory.get_val('phases.rotation.t_duration')\n                problem['phases.rotation.timeseries.time'] = init_trajectory.get_val('phases.rotation.timeseries.time')\n                problem['phases.rotation.states:x'] = init_trajectory.get_val('phases.rotation.states:x')\n                problem['phases.rotation.states:v'] = init_trajectory.get_val('phases.rotation.states:v')\n                problem['phases.rotation.states:alpha'] = init_trajectory.get_val('phases.rotation.states:alpha')\n\n            # Phase 3-5: liftoff-cutback\n            for j, phase_name in enumerate(self.phase_name_lst[3:]):\n                problem['phases.' + phase_name + '.t_initial'] = init_trajectory.get_val('phases.' + phase_name + '.t_initial')\n                problem['phases.' + phase_name + '.t_duration'] = init_trajectory.get_val('phases.' + phase_name + '.t_duration')\n                problem['phases.' + phase_name + '.timeseries.time'] = init_trajectory.get_val('phases.' + phase_name + '.timeseries.time')\n                problem['phases.' + phase_name + '.states:x'] = init_trajectory.get_val('phases.' + phase_name + '.states:x')\n                problem['phases.' + phase_name + '.states:z'] = init_trajectory.get_val('phases.' + phase_name + '.states:z')\n                problem['phases.' + phase_name + '.states:v'] = init_trajectory.get_val('phases.' + phase_name + '.states:v')\n                problem['phases.' + phase_name + '.states:gamma'] = init_trajectory.get_val('phases.' + phase_name + '.states:gamma')\n                problem['phases.' + phase_name + '.controls:alpha'] = init_trajectory.get_val('phases.' + phase_name + '.controls:alpha')\n                # if phase_name == 'vnrs' and settings.PTCB:\n                    # problem['phases.' + phase_name + '.controls:TS'] = init_trajectory.get_val('phases.' + phase_name + '.controls:TS')\n\n        # Run problem\n        dm.run_problem(problem, run_driver=run_driver)\n\n        # Save the results\n        if settings.save_results:\n            problem.record(case_name=settings.ac_name)\n\n        # Write output\n        return None\n\n    @staticmethod\n    def check_convergence(settings: Settings, filename: str) -> bool:\n        \"\"\"\n        Checks convergence of case using optimizer output file.\n\n        :param settings: pyna settings\n        :type settings: Settings\n        :param filename: file name of IPOPT output\n        :type filename: str\n\n        :return: converged\n        :rtype: bool\n        \"\"\"\n\n        # Save convergence info for trajectory\n        # Read IPOPT file\n        file_ipopt = open(settings.pyNA_directory + '/cases/' + settings.case_name + '/output/' + settings.output_directory_name + '/' + filename, 'r')\n        ipopt = file_ipopt.readlines()\n        file_ipopt.close()\n\n        # Check if convergence summary excel file exists\n        cnvg_file_name = settings.pyNA_directory + '/cases/' + settings.case_name + '/output/' + settings.output_directory_name + '/' + 'Convergence.csv'\n        if not os.path.isfile(cnvg_file_name):\n            file_cvg = open(cnvg_file_name, 'w')\n            file_cvg.writelines(\"Trajectory name , Execution date/time,  Converged\")\n        else:\n            file_cvg = open(cnvg_file_name, 'a')\n\n        # Write convergence output to file\n        # file = open(cnvg_file_name, 'a')\n        if ipopt[-1] in {'EXIT: Optimal Solution Found.\\n', 'EXIT: Solved To Acceptable Level.\\n'}:\n            file_cvg.writelines(\"\\n\" + settings.output_file_name + \", \" + str(dt.datetime.now()) + \", Converged\")\n            converged = True\n        else:\n            file_cvg.writelines(\"\\n\" + settings.output_file_name + \", \" + str(dt.datetime.now()) + \", Not converged\")\n            converged = False\n        file_cvg.close()\n\n        return converged\n\n", "meta": {"hexsha": "aa8742bd9409978f982044cbeca0272f9abceaf1", "size": 49531, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyNA/src/trajectory.py", "max_stars_repo_name": "MIT-LAE/pyNA", "max_stars_repo_head_hexsha": "651189596094ec3d26929330fa68f9122f6b3526", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyNA/src/trajectory.py", "max_issues_repo_name": "MIT-LAE/pyNA", "max_issues_repo_head_hexsha": "651189596094ec3d26929330fa68f9122f6b3526", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyNA/src/trajectory.py", "max_forks_repo_name": "MIT-LAE/pyNA", "max_forks_repo_head_hexsha": "651189596094ec3d26929330fa68f9122f6b3526", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.7464052288, "max_line_length": 272, "alphanum_fraction": 0.6308776322, "include": true, "reason": "import numpy,from scipy", "num_tokens": 12328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.1649097131204255}}
{"text": "# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n#    Project: Azimuthal integration\n#             https://github.com/silx-kit/pyFAI\n#\n#    Copyright (C) 2015-2018 European Synchrotron Radiation Facility, Grenoble, France\n#\n#    Principal author:       Jérôme Kieffer (Jerome.Kieffer@ESRF.eu)\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n__author__ = \"Jerome Kieffer\"\n__contact__ = \"Jerome.Kieffer@ESRF.eu\"\n__license__ = \"MIT\"\n__copyright__ = \"European Synchrotron Radiation Facility, Grenoble, France\"\n__date__ = \"10/01/2018\"\n__status__ = \"development\"\n__docformat__ = 'restructuredtext'\n\nimport logging\nimport numpy\n\nfrom . import detectors\nimport fabio\nlogger = logging.getLogger(__name__)\n\n\nclass Grid(object):\n    \"\"\"\n    This class handles a regular grid in front of a detector to calibrate the\n    geometrical distortion of the detector\n    \"\"\"\n    def __init__(self, detector, image, mask=None, pitch=None, invert=False):\n        \"\"\"\n        :param detector: instance of Detector or its name\n        :param image: 2d array representing the image\n        :param mask:\n        :param pitch: 2-tuple representing the grid spacing in (y, x) coordinates, in meter\n        :param invert: set to true if the image of the grid has regular dark spots (instead of bright points)\n        \"\"\"\n        if isinstance(detector, detectors.Detector):\n            self.detector = detectors.detector_factory(detector)\n        else:\n            self.detector = detector\n\n        if isinstance(image, numpy.ndarray):\n            self.image = image\n        else:\n            self.image = fabio.open(image).data\n\n        if mask is not None:\n            if isinstance(mask, numpy.ndarray):\n                self.mask = mask\n            else:\n                self.mask = fabio.open(mask).data.astype(bool)\n            if self.detector.mask is not None:\n                self.mask = numpy.logical_or(self.detector.mask, self.mask)\n        else:\n            self.mask = numpy.zeros_like(self.image, bool)\n        if invert:\n            self.image = self.image.max() - self.image\n        self.pitch = tuple(pitch[0], pitch[-1])\n\n    def threshold(self, level=None, percentile=None):\n        \"\"\"\n        Segment the image with a single threshold\n        \"\"\"\n        if percentile and not level:\n            data = self.image[self.mask]\n            data.sort()\n            level = data[int(len(data) * percentile / 100.)]\n        raise NotImplementedError(\"TODO\")\n", "meta": {"hexsha": "ba5bf41ded22b49bfe4805d6ae7007b9ee6d3f2b", "size": 3454, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyFAI/grid.py", "max_stars_repo_name": "yugangzhang/pyFAI", "max_stars_repo_head_hexsha": "e0453b279dac1f165f637e2a2ed1d4ddf57d31ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45, "max_stars_repo_stars_event_min_datetime": "2016-07-16T19:43:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T16:53:47.000Z", "max_issues_repo_path": "pyFAI/grid.py", "max_issues_repo_name": "yugangzhang/pyFAI", "max_issues_repo_head_hexsha": "e0453b279dac1f165f637e2a2ed1d4ddf57d31ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1125, "max_issues_repo_issues_event_min_datetime": "2016-06-09T07:47:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:34:00.000Z", "max_forks_repo_path": "pyFAI/grid.py", "max_forks_repo_name": "yugangzhang/pyFAI", "max_forks_repo_head_hexsha": "e0453b279dac1f165f637e2a2ed1d4ddf57d31ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 52, "max_forks_repo_forks_event_min_datetime": "2016-06-09T07:30:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T08:25:11.000Z", "avg_line_length": 38.3777777778, "max_line_length": 109, "alphanum_fraction": 0.6748697163, "include": true, "reason": "import numpy", "num_tokens": 779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.16490970976578553}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nrefer: rlpack\n\nActor Critic 框架\n\nProximal Policy Optimization.\n目标loss由三部分组成：1. clipped policy loss；2. value loss；3. entropy。\npolicy loss需要计算当前policy和old policy在当前state上的ratio。\n需要注意的是，state分布依赖于old policy。因此，更新中的old policy是一样的。\n\"\"\"\n\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom .base import Base\n\n\nclass PPO(Base):\n    def __init__(self,\n                 rnd=0,\n                 dim_obs=None, dim_act=None,\n                 policy_fn=None, value_fn=None,\n                 discount=0.99, gae=0.95, clip_ratio=0.2,\n                 train_epoch=40, policy_lr=1e-3, value_lr=1e-3,\n                 save_path=\"./log\", log_freq=10, save_model_freq=100):\n        self._dim_obs = dim_obs\n        self._dim_act = dim_act\n        self._policy_fn = policy_fn\n        self._value_fn = value_fn\n\n        self._clip_ratio = clip_ratio\n        self._discount = discount\n        self._gae = gae\n        self._train_epoch = train_epoch\n        self._policy_lr = policy_lr\n        self._value_lr = value_lr\n\n        self._log_freq = log_freq\n        self._save_model_freq = save_model_freq\n\n        super().__init__(save_path=save_path, rnd=rnd)\n\n    def _build_network(self):\n        \"\"\"Build tensorflow operations for algorithms.\"\"\"\n        self._obs = tf.placeholder(tf.float32, [None, *self._dim_obs])\n        self._act = tf.placeholder(tf.int32, [None, self._dim_act])\n\n        self._adv = tf.placeholder(tf.float32, [None])\n        self._ret = tf.placeholder(tf.float32, [None])\n        self._logp_old = tf.placeholder(tf.float32, [None])\n        self.all_phs = [self._obs, self._act, self._adv, self._ret, self._logp_old]\n\n        self.pi, self.logp_list = self._policy_fn(self._obs)\n        self.logp = tf.gather_nd(self.logp_list, self._act)\n        self.v = self._value_fn(self._obs)\n\n    def _build_algorithm(self):\n        \"\"\"Build algorithms using prebuilt networks.\"\"\"\n\n        ratio = tf.exp(self.logp - self._logp_old)\n        surr1 = ratio * self._adv\n        surr2 = tf.clip_by_value(ratio, 1.0 - self._clip_ratio, 1.0 + self._clip_ratio) * self._adv\n        self.policy_loss = -tf.reduce_mean(tf.minimum(surr1, surr2))\n        self.value_loss = tf.reduce_mean((self.v - self._ret)**2)\n\n        self._train_policy_op = tf.train.AdamOptimizer(self._policy_lr).minimize(self.policy_loss)\n        self._train_value_op = tf.train.AdamOptimizer(self._value_lr).minimize(self.value_loss)\n\n    def get_action(self, obs) -> np.ndarray:\n        \"\"\"Return action according to the observations.\n        :param obs: the observation that could be image or real-number features\n        :return: actions\n        \"\"\"\n        a_prob = self.sess.run(self.pi, feed_dict={self._obs: obs})\n\n        return a_prob\n\n    def update(self, databatch):\n        \"\"\"\n        参数:\n            databatch：一个列表，分别是state, action, reward, done, early_stop, next_state。每个是矩阵或向量。\n            state是状态，action是动作，reward是奖励，done是是否完结，early_stop是是否提前结束，next_state是下一个状态。\n        \"\"\"\n        preprocess_databatch = self._parse_databatch(*databatch)\n\n        inputs = {k: v for k, v in zip(self.all_phs, preprocess_databatch)}\n        pi_l_old, v_l_old = self.sess.run([self.policy_loss, self.value_loss], feed_dict=inputs)\n\n        # Training\n        for i in range(self._train_epoch):\n            self.sess.run(self._train_policy_op, feed_dict=inputs)\n        for i in range(self._train_epoch):\n            self.sess.run(self._train_value_op, feed_dict=inputs)\n\n        pi_l_new, v_l_new = self.sess.run([self.policy_loss, self.value_loss], feed_dict=inputs)\n\n        global_step, _ = self.sess.run([tf.train.get_global_step(), self.increment_global_step])\n        if global_step % self._save_model_freq == 0:\n            self.save_model()\n\n    def _parse_databatch(self, states, actions, rewards, dones, earlystops, nextstates):\n\n        batch_size = len(dones)\n        oldlogproba, values = self.sess.run([self.logp, self.v], feed_dict={self._obs: states, self._act: actions})\n        nextvalues = self.sess.run(self.v, feed_dict={self._obs: nextstates})\n\n        returns = np.zeros(batch_size)\n        deltas = np.zeros(batch_size)\n        advantages = np.zeros(batch_size)\n\n        for i in reversed(range(batch_size)):\n\n            if dones[i]:\n                prev_return = 0\n                prev_value = 0\n                prev_advantage = 0\n            elif earlystops[i]:\n                prev_return = nextvalues[i] \n                prev_value = prev_return\n                prev_advantage = 0\n\n            returns[i] = rewards[i] + self._discount * prev_return * (1 - dones[i])\n            deltas[i] = rewards[i] + self._discount * prev_value * (1 - dones[i]) - values[i]\n            # ref: https://arxiv.org/pdf/1506.02438.pdf (generalization advantage estimate)\n            advantages[i] = deltas[i] + self._discount * self._gae * prev_advantage * (1 - dones[i])\n\n            prev_return = returns[i]\n            prev_value = values[i]\n            prev_advantage = advantages[i]\n\n        advantages = (advantages - advantages.mean()) / advantages.std()\n\n        return [states, actions, advantages, returns, oldlogproba]", "meta": {"hexsha": "315e3fb2c6161ec4d7c616c6f3ea1c0ce867961a", "size": 5119, "ext": "py", "lang": "Python", "max_stars_repo_path": "policy/algo/ppo.py", "max_stars_repo_name": "yangmuzhi/wuziqi", "max_stars_repo_head_hexsha": "7bdee51ef2a37373b0823b00c4536138560ec3bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "policy/algo/ppo.py", "max_issues_repo_name": "yangmuzhi/wuziqi", "max_issues_repo_head_hexsha": "7bdee51ef2a37373b0823b00c4536138560ec3bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "policy/algo/ppo.py", "max_forks_repo_name": "yangmuzhi/wuziqi", "max_forks_repo_head_hexsha": "7bdee51ef2a37373b0823b00c4536138560ec3bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9185185185, "max_line_length": 115, "alphanum_fraction": 0.6341082243, "include": true, "reason": "import numpy", "num_tokens": 1343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.16490970976578553}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom dropblock import DropBlock2D\n\n\nclass BEV_Unet(nn.Module):\n\n    def __init__(self,n_class,n_height,dilation = 1,group_conv=False,input_batch_norm = False,dropout = 0.,circular_padding = False, dropblock = True, use_vis_fea=False):\n        super(BEV_Unet, self).__init__()\n        self.n_class = n_class\n        self.n_height = n_height\n        if use_vis_fea:\n            self.network = UNet(n_class*n_height,2*n_height,dilation,group_conv,input_batch_norm,dropout,circular_padding,dropblock)\n        else:\n            self.network = UNet(n_class*n_height,n_height,dilation,group_conv,input_batch_norm,dropout,circular_padding,dropblock)\n\n    def forward(self, x):\n        x,center,offset = self.network(x)\n        \n        x = x.permute(0,2,3,1)\n        new_shape = list(x.size())[:3] + [self.n_height,self.n_class]\n        x = x.view(new_shape)\n        x = x.permute(0,4,1,2,3)\n\n        return x,center,offset\n    \nclass UNet(nn.Module):\n    def __init__(self, n_class,n_height,dilation,group_conv,input_batch_norm, dropout,circular_padding,dropblock):\n        super(UNet, self).__init__()\n        # encoder\n        self.inc = inconv(n_height, 64, dilation, input_batch_norm, circular_padding)\n        self.down1 = down(64, 128, dilation, group_conv, circular_padding)\n        self.down2 = down(128, 256, dilation, group_conv, circular_padding)\n        self.down3 = down(256, 512, dilation, group_conv, circular_padding)\n        self.down4 = down(512, 512, dilation, group_conv, circular_padding)\n\n        # semantic decoder\n        self.up1 = up(1024, 256, circular_padding, group_conv = group_conv, use_dropblock=dropblock, drop_p=dropout)\n        self.up2 = up(512, 128, circular_padding, group_conv = group_conv, use_dropblock=dropblock, drop_p=dropout)\n        self.up3 = up(256, 64, circular_padding, group_conv = group_conv, use_dropblock=dropblock, drop_p=dropout)\n        self.up4 = up(128, 64, circular_padding, group_conv = group_conv, use_dropblock=dropblock, drop_p=dropout)\n        self.dropout = nn.Dropout(p=0. if dropblock else dropout)\n        # semantic head\n        self.outc = outconv(64, n_class)\n\n        # instance decoder\n        # self.i_up1 = up(1024, 256, circular_padding, group_conv = group_conv, use_dropblock=dropblock, drop_p=dropout)\n        # self.i_up2 = up(512, 128, circular_padding, group_conv = group_conv, use_dropblock=dropblock, drop_p=dropout)\n        # self.i_up3 = up(256, 64, circular_padding, group_conv = group_conv, use_dropblock=dropblock, drop_p=dropout)\n        # self.i_up4 = up(128, 32, circular_padding, group_conv = group_conv, use_dropblock=dropblock, drop_p=dropout)\n        self.i_up4_center = up(128, 32, circular_padding, group_conv = group_conv, use_dropblock=dropblock, drop_p=dropout)\n        self.i_up4_offset = up(128, 32, circular_padding, group_conv = group_conv, use_dropblock=dropblock, drop_p=dropout)\n        # instance head\n        self.i_outc_center = outconv(32, 1)\n        self.i_outc_offset = outconv(32, 2)\n\n    def forward(self, x):\n        x1 = self.inc(x)\n        x2 = self.down1(x1)\n        x3 = self.down2(x2)\n        x4 = self.down3(x3)\n        x5 = self.down4(x4)\n        # semantic\n        x = self.up1(x5, x4)\n        x = self.up2(x, x3)\n        x = self.up3(x, x2)\n        s_x = self.up4(x, x1)\n        s_x = self.outc(self.dropout(s_x))\n        # instance\n        # i_x = self.i_up1(x5, x4)\n        # i_x = self.i_up2(i_x, x3)\n        # i_x = self.i_up3(i_x, x2)x\n\n        # i_x = self.i_up4(i_x, x1)\n        i_x_center = self.i_up4_center(x, x1)\n        i_x_center = self.i_outc_center(self.dropout(i_x_center))\n\n        i_x_offset = self.i_up4_offset(x, x1)\n        i_x_offset = self.i_outc_offset(self.dropout(i_x_offset))\n\n        return s_x, i_x_center, i_x_offset\n\nclass double_conv(nn.Module):\n    '''(conv => BN => ReLU) * 2'''\n    def __init__(self, in_ch, out_ch,group_conv,dilation=1):\n        super(double_conv, self).__init__()\n        if group_conv:\n            self.conv = nn.Sequential(\n                nn.Conv2d(in_ch, out_ch, 3, padding=1,groups = min(out_ch,in_ch)),\n                nn.BatchNorm2d(out_ch),\n                nn.LeakyReLU(inplace=True),\n                nn.Conv2d(out_ch, out_ch, 3, padding=1,groups = out_ch),\n                nn.BatchNorm2d(out_ch),\n                nn.LeakyReLU(inplace=True)\n            )\n        else:\n            self.conv = nn.Sequential(\n                nn.Conv2d(in_ch, out_ch, 3, padding=1),\n                nn.BatchNorm2d(out_ch),\n                nn.LeakyReLU(inplace=True),\n                nn.Conv2d(out_ch, out_ch, 3, padding=1),\n                nn.BatchNorm2d(out_ch),\n                nn.LeakyReLU(inplace=True)\n            )\n\n    def forward(self, x):\n        x = self.conv(x)\n        return x\n\nclass double_conv_circular(nn.Module):\n    '''(conv => BN => ReLU) * 2'''\n    def __init__(self, in_ch, out_ch,group_conv,dilation=1):\n        super(double_conv_circular, self).__init__()\n        if group_conv:\n            self.conv1 = nn.Sequential(\n                nn.Conv2d(in_ch, out_ch, 3, padding=(1,0),groups = min(out_ch,in_ch)),\n                nn.BatchNorm2d(out_ch),\n                nn.LeakyReLU(inplace=True)\n            )\n            self.conv2 = nn.Sequential(\n                nn.Conv2d(out_ch, out_ch, 3, padding=(1,0),groups = out_ch),\n                nn.BatchNorm2d(out_ch),\n                nn.LeakyReLU(inplace=True)\n            )\n        else:\n            self.conv1 = nn.Sequential(\n                nn.Conv2d(in_ch, out_ch, 3, padding=(1,0)),\n                nn.BatchNorm2d(out_ch),\n                nn.LeakyReLU(inplace=True)\n            )\n            self.conv2 = nn.Sequential(\n                nn.Conv2d(out_ch, out_ch, 3, padding=(1,0)),\n                nn.BatchNorm2d(out_ch),\n                nn.LeakyReLU(inplace=True)\n            )\n\n    def forward(self, x):\n        #add circular padding\n        x = F.pad(x,(1,1,0,0),mode = 'circular')\n        x = self.conv1(x)\n        x = F.pad(x,(1,1,0,0),mode = 'circular')\n        x = self.conv2(x)\n        return x\n\n\nclass inconv(nn.Module):\n    def __init__(self, in_ch, out_ch, dilation, input_batch_norm, circular_padding):\n        super(inconv, self).__init__()\n        if input_batch_norm:\n            if circular_padding:\n                self.conv = nn.Sequential(\n                    nn.BatchNorm2d(in_ch),\n                    double_conv_circular(in_ch, out_ch,group_conv = False,dilation = dilation)\n                )\n            else:\n                self.conv = nn.Sequential(\n                    nn.BatchNorm2d(in_ch),\n                    double_conv(in_ch, out_ch,group_conv = False,dilation = dilation)\n                )\n        else:\n            if circular_padding:\n                self.conv = double_conv_circular(in_ch, out_ch,group_conv = False,dilation = dilation)\n            else:\n                self.conv = double_conv(in_ch, out_ch,group_conv = False,dilation = dilation)\n\n    def forward(self, x):\n        x = self.conv(x)\n        return x\n\n\nclass down(nn.Module):\n    def __init__(self, in_ch, out_ch, dilation, group_conv, circular_padding):\n        super(down, self).__init__()\n        if circular_padding:\n            self.mpconv = nn.Sequential(\n                nn.MaxPool2d(2),\n                double_conv_circular(in_ch, out_ch,group_conv = group_conv,dilation = dilation)\n            )\n        else:\n            self.mpconv = nn.Sequential(\n                nn.MaxPool2d(2),\n                double_conv(in_ch, out_ch,group_conv = group_conv,dilation = dilation)\n            )                \n\n    def forward(self, x):\n        x = self.mpconv(x)\n        return x\n\n\nclass up(nn.Module):\n    def __init__(self, in_ch, out_ch, circular_padding, bilinear=True, group_conv=False, use_dropblock = False, drop_p = 0.5):\n        super(up, self).__init__()\n\n        #  would be a nice idea if the upsampling could be learned too,\n        #  but my machine do not have enough memory to handle all those weights\n        if bilinear:\n            self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n        elif group_conv:\n            self.up = nn.ConvTranspose2d(in_ch//2, in_ch//2, 2, stride=2,groups = in_ch//2)\n        else:\n            self.up = nn.ConvTranspose2d(in_ch//2, in_ch//2, 2, stride=2)\n\n        if circular_padding:\n            self.conv = double_conv_circular(in_ch, out_ch,group_conv = group_conv)\n        else:\n            self.conv = double_conv(in_ch, out_ch,group_conv = group_conv)\n\n        self.use_dropblock = use_dropblock\n        if self.use_dropblock:\n            self.dropblock = DropBlock2D(block_size=7, drop_prob=drop_p)\n\n    def forward(self, x1, x2):\n        x1 = self.up(x1)\n        \n        # input is CHW\n        diffY = x2.size()[2] - x1.size()[2]\n        diffX = x2.size()[3] - x1.size()[3]\n\n        x1 = F.pad(x1, (diffX // 2, diffX - diffX//2,\n                        diffY // 2, diffY - diffY//2))\n        \n        # for padding issues, see \n        # https://github.com/HaiyongJiang/U-Net-Pytorch-Unstructured-Buggy/commit/0e854509c2cea854e247a9c615f175f76fbb2e3a\n        # https://github.com/xiaopeng-liao/Pytorch-UNet/commit/8ebac70e633bac59fc22bb5195e513d5832fb3bd\n\n        x = torch.cat([x2, x1], dim=1)\n        x = self.conv(x)\n        if self.use_dropblock:\n            x = self.dropblock(x)\n        return x\n\n\nclass outconv(nn.Module):\n    def __init__(self, in_ch, out_ch):\n        super(outconv, self).__init__()\n        self.conv = nn.Conv2d(in_ch, out_ch, 1)\n\n    def forward(self, x):\n        x = self.conv(x)\n        return x", "meta": {"hexsha": "680546ea3f8fcd0fe13c14d0c6d955ddf492c057", "size": 9680, "ext": "py", "lang": "Python", "max_stars_repo_path": "network/BEV_Unet.py", "max_stars_repo_name": "xizaoqu/Panoptic-PolarNet", "max_stars_repo_head_hexsha": "8ce05f437f54e030eac7de150f43caab2810cfbb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 90, "max_stars_repo_stars_event_min_datetime": "2021-03-30T08:02:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:29:56.000Z", "max_issues_repo_path": "network/BEV_Unet.py", "max_issues_repo_name": "xizaoqu/Panoptic-PolarNet", "max_issues_repo_head_hexsha": "8ce05f437f54e030eac7de150f43caab2810cfbb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2021-04-01T02:29:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T07:30:50.000Z", "max_forks_repo_path": "network/BEV_Unet.py", "max_forks_repo_name": "xizaoqu/Panoptic-PolarNet", "max_forks_repo_head_hexsha": "8ce05f437f54e030eac7de150f43caab2810cfbb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2021-04-01T09:29:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T01:36:02.000Z", "avg_line_length": 39.5102040816, "max_line_length": 170, "alphanum_fraction": 0.5983471074, "include": true, "reason": "import numpy", "num_tokens": 2593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.28140560140262283, "lm_q1q2_score": 0.16465074217992903}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nThis module contains the functions necessary to correct atom probe datasets\nfor systematic energy deficits.  Details on the algorithm are given in a\nmanuscript titled:\n    ``An Algorithm for Correcting Systematic Energy Deficits in the Atom Probe\n    Mass Spectra of Insulating Samples''\n\nCreated on Mon Nov 25 14:02:12 2019\n\n@author: bwc\n\n>  NIST Public License - 2019\n\n>  This software was developed by employees of the National Institute of\n>  Standards and Technology (NIST), an agency of the Federal Government\n>  and is being made available as a public service. Pursuant to title 17\n>  United States Code Section 105, works of NIST employees are not subject\n>  to copyright protection in the United States.  This software may be\n>  subject to foreign copyright.  Permission in the United States and in\n>  foreign countries, to the extent that NIST may hold copyright, to use,\n>  copy, modify, create derivative works, and distribute this software and\n>  its documentation without fee is hereby granted on a non-exclusive basis,\n>  provided that this notice and disclaimer of warranty appears in all copies.\n\n>  THE SOFTWARE IS PROVIDED 'AS IS' WITHOUT ANY WARRANTY OF ANY KIND,\n>  EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED\n>  TO, ANY WARRANTY THAT THE SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY\n>  IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,\n>  AND FREEDOM FROM INFRINGEMENT, AND ANY WARRANTY THAT THE DOCUMENTATION\n>  WILL CONFORM TO THE SOFTWARE, OR ANY WARRANTY THAT THE SOFTWARE WILL BE\n>  ERROR FREE.  IN NO EVENT SHALL NIST BE LIABLE FOR ANY DAMAGES, INCLUDING,\n>  BUT NOT LIMITED TO, DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES,\n>  ARISING OUT OF, RESULTING FROM, OR IN ANY WAY CONNECTED WITH THIS SOFTWARE,\n>  WHETHER OR NOT BASED UPON WARRANTY, CONTRACT, TORT, OR OTHERWISE, WHETHER\n>  OR NOT INJURY WAS SUSTAINED BY PERSONS OR PROPERTY OR OTHERWISE, AND\n>  WHETHER OR NOT LOSS WAS SUSTAINED FROM, OR AROSE OUT OF THE RESULTS OF,\n>  OR USE OF, THE SOFTWARE OR SERVICES PROVIDED HEREUNDER.\n\n\"\"\"\n\n\nimport numpy as np\nimport histo_funcs as hf\nfrom scipy.interpolate import interp1d\n\n\ndef get_shifts(ref, N, max_shift=150, global_shift_fun=None):\n    \"\"\"\n    This computes the optimal shift between a 1d reference array and the\n    columns of a 2d data array using an fft based cross correlation.  The\n    optimal shift is assumed to be where the cross correlation is maximal.\n    Because no padding or normalization is applied, this works best for\n    relatively small shifts.  This is explicitly enforced by the ``max_shift``\n    parameter.\n\n    Parameters\n    ----------\n    ref : real numeric 1d array (shape is nx1)\n        The reference array.  Should be in a nx1 column array.\n    N : real numeric 2d array (shape is nxm)\n        The data array.  Each column of this array will be cross-correlated to\n        the reference array using an fft.\n    max_shift : int (default is 150)\n        The maximum number of bins that are searched for the cross-correlation.\n        The cross correlation is set to zero for lags less than -max_shift and\n        greater than +max_shift.\n    global_shift_fun : function handle (default is None)\n        This function applies an additional subtractive shift to the returned\n        shift array.  I generally set this to numpy.mean or numpy.median, but\n        more complex shift functions could be used (including lambdas).\n\n    Returns\n    -------\n    shifts : numeric 1d array\n        The shift (in units of bin index) that was required to align each\n        column of data to the reference spectrum.\n\n    \"\"\"\n    # Note: Use real valued fft to improve speed/memory\n\n    # FFT the ref and data arrays\n    rfft_ref = np.fft.rfft(ref, axis=1)\n    rfft_N = np.fft.rfft(N, axis=1)\n\n    # Compute the cross-correlation and take the inverse fft\n    xc = np.fft.irfft(rfft_N*np.conj(rfft_ref), axis=1)\n\n    # Set the cross correlation to zero for lags greater than max_shift\n    xc[:, max_shift:xc.shape[1]-max_shift] = 0\n\n    # Find the lags corresponding to the maximum of the cross correlation and\n    # then shift them to correspond to the appropriate origin.\n    max_idxs = np.argmax(xc, axis=1)\n    max_idxs[max_idxs > xc.shape[1]//2] = \\\n        max_idxs[max_idxs > xc.shape[1]//2] - xc.shape[1]\n\n    # Apply a global_shift_fun shift if specified\n    if global_shift_fun is not None:\n        shifts = max_idxs - global_shift_fun(max_idxs)\n    else:\n        shifts = max_idxs\n\n    return shifts\n\n\ndef get_all_scale_coeffs(event_dat,\n                         max_scale=1.1,\n                         roi=None,\n                         cts_per_chunk=2**10,\n                         delta_logdat=5e-4):\n    \"\"\"\n    This attempts to best align event data.  The basic assumption is that if\n    the ``event_dat`` is binned into a 2d history (histogram) then there are\n    clearly defined features (i.e. peaks) that will shift around in a\n    systematic manner.  When this data is projected onto a single dimension\n    then any features (peaks) will be broader than they really should be.  This\n    algorithm discretizes the event_dat into `chunks' and attempts to align\n    each chunk to a reference dataset using a scalar multiplicative\n    coefficient.  The reference dataset is the middle 50% of the ``event_dat``.\n    The alignment is performed using a logarithm based cross correlation\n    approach.  Two iterations of this algorithm are performed before the result\n    is returned.  In all tests performed thus far a single iteration was\n    sufficient however we used two iterations in an abundance of caution.\n\n    Parameters\n    ----------\n    event_dat : real float 1d array\n        Event data.  Typically the data is either the mass-to-charge or\n        time-of-flight of each event.  The ordering of the data is assumed to\n        be chronological (i.e. the order in which they were detected).\n    max_scale : real float (default is 1.1)\n        The maximum possible scale factor allowed (relative to the reference\n        data)\n    roi : real numeric list or array (default is [0.5,200])\n        The domain that the data should be evaluated over.\n        Specified as [min, max] values.\n    cts_per_chunk : int (default is 1024)\n        The number of events to be collected into a single `chunk' of data.\n    delta_logdat : real float (default is 5e-4)\n        The discretization of the log(data) over the roi specified.  Smaller\n        deltas are more time/memory intensive.  For deltas much less than one,\n        this effectively gives a discretization/resolution of the\n        multiplicative factor of 1+delta_logdat.  For the atom probe data I\n        have worked with, the noise on the shift is on the order of 1e-3 and\n        so setting the delta to be smaller than this, ensures that the\n        discretization error is not a significant problem.\n\n    Returns\n    -------\n    eventwise_scales : real float array\n        An array that contains the computed scale factor for each event that\n        best aligns the data.  To correct the data, just divide the event_dat\n        array by the eventwise_scales array.\n\n    \"\"\"\n    if roi is None:\n        roi = [0.5, 200]\n    log_roi = np.log(roi)\n\n    # Take the log of data\n    logdat = np.log(event_dat)\n\n    # Create the histogram.  Compute centers and delta y\n    N, seq_edges, logdat_edges = \\\n        hf.create_histogram(logdat,\n                            roi=log_roi,\n                            cts_per_chunk=cts_per_chunk,\n                            delta_dat=delta_logdat)\n    seq_centers, logdat_centers = hf.edges_to_centers(seq_edges, logdat_edges)\n#    print('specified delta_logdat = '+str(delta_logdat))\n    delta_logdat = logdat_edges[1]-logdat_edges[0]\n#    print('actual delta_logdat = '+str(delta_logdat))\n\n    # Initialize the total eventwise log(dat) shift\n    eventwise_logdat_shifts = np.zeros(event_dat.size)\n\n    # Do one iteration with the center 50% of the data as a reference\n    # Note: Make it is 2d (even though it is just a single column array)\n    ref = np.mean(N[N.shape[0]//4:3*N.shape[0]//4, :], axis=0)[None, :]\n\n    # Get the maximum possible shift in bins.\n    max_pixel_shift = int(np.ceil(np.log(max_scale)/delta_logdat))\n\n    # Determine the chunkwise shifts\n    chunkwise_shifts0 = delta_logdat*get_shifts(ref,\n                                                N,\n                                                max_shift=max_pixel_shift,\n                                                global_shift_fun=np.mean)\n\n    # Interpolate (linear) from chunkwise to eventwise shifts\n    f = interp1d(seq_centers, chunkwise_shifts0, fill_value='extrapolate')\n\n    # Accumulate the shift for the first iteration.\n    eventwise_logdat_shifts += f(np.arange(event_dat.size))\n\n    # Correct the log(data)\n    logdat_corr = logdat - eventwise_logdat_shifts\n\n    # Recompute the histogram with newly corrected log(data)\n    N, seq_edges, logdat_edges = \\\n        hf.create_histogram(logdat_corr,\n                            roi=log_roi,\n                            cts_per_chunk=cts_per_chunk,\n                            delta_dat=delta_logdat)\n    seq_centers, logdat_centers = hf.edges_to_centers(seq_edges, logdat_edges)\n    delta_logdat = logdat_edges[1]-logdat_edges[0]\n\n    # Use the center 50% of the data as a reference\n    # Note: Make it is 2d (even though it is just a single column array)\n    ref = np.mean(N[N.shape[0]//4:3*N.shape[0]//4, :], axis=0)[None, :]\n\n    # Get the maximum possible shift in bins.\n    max_pixel_shift = int(np.ceil(np.log(max_scale)/delta_logdat))\n\n    # Determine the chunkwise shifts\n    chunkwise_shifts1 = delta_logdat*get_shifts(ref,\n                                                N,\n                                                max_shift=max_pixel_shift,\n                                                global_shift_fun=np.mean)\n\n    # Interpolate to get eventwise shifts\n    f = interp1d(seq_centers, chunkwise_shifts1, fill_value='extrapolate')\n\n    # Accumulate the shift for the second iteration.\n    eventwise_logdat_shifts += f(np.arange(event_dat.size))\n\n    # Compute total eventwise shifts for output\n    eventwise_scales = np.exp(eventwise_logdat_shifts)\n\n#    # Uncomment this to see the relative importance of the two iterations\n#    import matplotlib.pyplot as plt\n#    plt.figure()\n#    plt.plot(np.exp(chunkwise_shifts0), label='iter 0')\n#    plt.plot(np.exp(chunkwise_shifts1), label='iter 1')\n#    plt.legend()\n\n    return eventwise_scales\n", "meta": {"hexsha": "f9310ad9d4c11fdc982763eeffd6bfc3e37f18cc", "size": 10543, "ext": "py", "lang": "Python", "max_stars_repo_path": "SiO2/SEDcorr/sed_corr.py", "max_stars_repo_name": "bcaplins/NIST_APT_TOOLS", "max_stars_repo_head_hexsha": "80c25498e8b069b8ee289a2d09c76c932c054cea", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SiO2/SEDcorr/sed_corr.py", "max_issues_repo_name": "bcaplins/NIST_APT_TOOLS", "max_issues_repo_head_hexsha": "80c25498e8b069b8ee289a2d09c76c932c054cea", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SiO2/SEDcorr/sed_corr.py", "max_forks_repo_name": "bcaplins/NIST_APT_TOOLS", "max_forks_repo_head_hexsha": "80c25498e8b069b8ee289a2d09c76c932c054cea", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.1129707113, "max_line_length": 79, "alphanum_fraction": 0.6820639287, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.32423540551084407, "lm_q1q2_score": 0.16465058573778557}}
{"text": "\"\"\"\nGaugeGroup and derived objects, used primarily in gauge optimization\n\"\"\"\n#***************************************************************************************************\n# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).\n# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights\n# in this software.\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n# in compliance with the License.  You may obtain a copy of the License at\n# http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory.\n#***************************************************************************************************\n\nimport numpy as _np\n\nfrom pygsti.modelmembers import operations as _op\n\n\nclass GaugeGroup(object):\n    \"\"\"\n    A parameterized set (ideally a group) of gauge transformations.\n\n    Specifies the \"optimization space\" explored by gauge optimization\n    algorithms.  This base class is used to define the common interface of all\n    types of gauge \"groups\" (even though they need not be groups in the\n    mathematical sense).\n\n    Parameters\n    ----------\n    name : str\n        A name for this group - used for reporting what type of\n        gauge optimization was performed.\n    \"\"\"\n\n    def __init__(self, name):\n        \"\"\"\n        Creates a new gauge group object\n\n        Parameters\n        ----------\n        name : str\n            A name for this group - used for reporting what type of\n            gauge optimization was performed.\n        \"\"\"\n        self.name = name\n\n    @property\n    def num_params(self):\n        \"\"\"\n        Return the number of parameters (degrees of freedom) of this gauge group..\n\n        Returns\n        -------\n        int\n        \"\"\"\n        return 0\n\n    def compute_element(self, param_vec):\n        \"\"\"\n        Retrieve the element of this group corresponding to `param_vec`\n\n        Parameters\n        ----------\n        param_vec : numpy.ndarray\n            A 1D array of length :method:`num_params`.\n\n        Returns\n        -------\n        GaugeGroupElement\n        \"\"\"\n        return GaugeGroupElement()\n\n    @property\n    def initial_params(self):\n        \"\"\"\n        Return a good (or standard) starting parameter vector, used to initialize a gauge optimization.\n\n        Returns\n        -------\n        numpy.ndarray\n            A 1D array of length :method:`num_params`.\n        \"\"\"\n        return _np.array([], 'd')\n\n\nclass GaugeGroupElement(object):\n    \"\"\"\n    The element of a :class:`GaugeGroup`, which represents a single gauge transformation.\n    \"\"\"\n\n    def __init__(self):\n        \"\"\"Creates a new GaugeGroupElement\"\"\"\n        pass\n\n    @property\n    def transform_matrix(self):\n        \"\"\"\n        The gauge-transform matrix.\n\n        Returns\n        -------\n        numpy.ndarray\n        \"\"\"\n        return None\n\n    @property\n    def transform_matrix_inverse(self):\n        \"\"\"\n        The inverse of the gauge-transform matrix.\n\n        Returns\n        -------\n        numpy.ndarray\n        \"\"\"\n        return None\n\n    def deriv_wrt_params(self, wrt_filter=None):\n        \"\"\"\n        Computes the derivative of the gauge group at this element.\n\n        That is, the derivative of a general element with respect to the gauge\n        group's parameters, evaluated at this element.\n\n        Parameters\n        ----------\n        wrt_filter : list or numpy.ndarray, optional\n            Indices of the gauge group parameters to differentiate with respect to.\n            If None, differentiation is performed with respect to all the group's parameters.\n\n        Returns\n        -------\n        numpy.ndarray\n        \"\"\"\n        return None\n\n    def to_vector(self):\n        \"\"\"\n        Get the parameter vector corresponding to this transform.\n\n        Returns\n        -------\n        numpy.ndarray\n        \"\"\"\n        return _np.array([], 'd')\n\n    def from_vector(self, v):\n        \"\"\"\n        Reinitialize this `GaugeGroupElement` using the the parameter vector `v`.\n\n        Parameters\n        ----------\n        v : numpy.ndarray\n            A 1D array of length :method:`num_params`\n\n        Returns\n        -------\n        None\n        \"\"\"\n        pass\n\n    @property\n    def num_params(self):\n        \"\"\"\n        Return the number of parameters of this gauge group element.\n\n        (This is equivalent to the number of parameters of the parent gauge group.)\n\n        Returns\n        -------\n        int\n        \"\"\"\n        return 0\n\n    def inverse(self):\n        \"\"\"\n        Creates a gauge group element that performs the inverse of this element.\n\n        Returns\n        -------\n        InverseGaugeGroupElement\n        \"\"\"\n        return InverseGaugeGroupElement(self)\n\n\nclass InverseGaugeGroupElement(GaugeGroupElement):\n    \"\"\"\n    A gauge group element that represents the inverse action of another element.\n\n    Parameters\n    ----------\n    gauge_group_el : GaugeGroupElement\n        The element to invert.\n    \"\"\"\n\n    def __init__(self, gauge_group_el):\n        self.inverse_element = gauge_group_el\n\n    @property\n    def transform_matrix(self):\n        \"\"\"\n        The gauge-transform matrix.\n\n        Returns\n        -------\n        numpy.ndarray\n        \"\"\"\n        return self.inverse_element.transform_matrix_inverse\n\n    @property\n    def transform_matrix_inverse(self):\n        \"\"\"\n        The inverse of the gauge-transform matrix.\n\n        Returns\n        -------\n        numpy.ndarray\n        \"\"\"\n        return self.inverse_element.transform_matrix\n\n    def deriv_wrt_params(self, wrt_filter=None):\n        \"\"\"\n        Computes the derivative of the gauge group at this element.\n\n        That is, the derivative of a general element with respect to the gauge\n        group's parameters, evaluated at this element.\n\n        Parameters\n        ----------\n        wrt_filter : list or numpy.ndarray, optional\n            Indices of the gauge group parameters to differentiate with respect to.\n            If None, differentiation is performed with respect to all the group's parameters.\n\n        Returns\n        -------\n        numpy.ndarray\n        \"\"\"\n        #Derivative of inv(M): d(inv_M) = inv_M * dM * inv_M\n        Tinv = self.transform_matrix  # inverse of *original* transform\n        dT = self.inverse_element.deriv_wrt_params(wrt_filter)  # shape (d*d, n)\n        d, n = int(round(_np.sqrt(dT.shape[0]))), dT.shape[1]\n\n        dT.shape = (d, d, n)  # call it (d1,d2,n)\n        dT = _np.rollaxis(dT, 2)  # shape (n, d1, d2)\n        deriv = -_np.dot(Tinv, _np.dot(dT, Tinv))  # d,d * (n,d,d * d,d) => d,d * n,d,d => d,n,d\n        return _np.swapaxes(deriv, 1, 2).reshape(d * d, n)  # d,n,d => d,d,n => (d*d, n)\n\n    def to_vector(self):\n        \"\"\"\n        Get the parameter vector corresponding to this transform.\n\n        Returns\n        -------\n        numpy.ndarray\n        \"\"\"\n        return self.inverse_element.to_vector()\n\n    def from_vector(self, v):\n        \"\"\"\n        Reinitialize this `GaugeGroupElement` using the the parameter vector `v`.\n\n        Parameters\n        ----------\n        v : numpy.ndarray\n            A 1D array of length :method:`num_params`\n\n        Returns\n        -------\n        None\n        \"\"\"\n        return self.inverse_element.from_vector()\n\n    @property\n    def num_params(self):\n        \"\"\"\n        Return the number of parameters of this gauge group element.\n\n        (This is equivalent to the number of parameters of the parent gauge group.)\n\n        Returns\n        -------\n        int\n        \"\"\"\n        return self.inverse_element.num_params\n\n    def inverse(self):\n        \"\"\"\n        Creates a gauge group element that performs the inverse of this element.\n\n        Returns\n        -------\n        GaugeGroupElement\n        \"\"\"\n        return self.inverse_element  # inverting an inverse => back to original\n\n\nclass OpGaugeGroup(GaugeGroup):\n    \"\"\"\n    A gauge group based on the parameterization of a single `LinearOperator`.\n\n    The parameterization of this linear operator is used to parameterize the\n    gauge-transform matrix.  This class is used as the base class for sevearl\n    other of gauge group classes.\n\n    Parameters\n    ----------\n    operation : LinearOperator\n        The LinearOperator to base this Gauge group on.\n\n    elementcls : class\n        The element class to use when implementing the `element` method.\n\n    name : str\n        A name for this group - used for reporting what type of\n        gauge optimization was performed.\n    \"\"\"\n\n    def __init__(self, operation, elementcls, name):\n        \"\"\"\n        Create a new `OpGaugeGroup`.\n\n        Parameters\n        ----------\n        operation : LinearOperator\n            The LinearOperator to base this Gauge group on.\n\n        elementcls : class\n            The element class to use when implementing the `compute_element` method.\n\n        name : str\n            A name for this group - used for reporting what type of\n            gauge optimization was performed.\n        \"\"\"\n        if not isinstance(operation, _op.LinearOperator):\n            operation = _op.StaticArbitraryOp(operation, evotype='default', state_space=None)\n        self._operation = operation\n        self.element = elementcls\n        GaugeGroup.__init__(self, name)\n\n    @property\n    def num_params(self):\n        \"\"\"\n        Return the number of parameters (degrees of freedom) of this gauge group.\n\n        Returns\n        -------\n        int\n        \"\"\"\n        return self._operation.num_params\n\n    def compute_element(self, param_vec):\n        \"\"\"\n        Retrieve the element of this group corresponding to `param_vec`\n\n        Parameters\n        ----------\n        param_vec : numpy.ndarray\n            A 1D array of length :method:`num_params`.\n\n        Returns\n        -------\n        GaugeGroupElement\n        \"\"\"\n        elgate = self._operation.copy()\n        elgate.from_vector(param_vec)\n        return self.element(elgate)\n\n    @property\n    def initial_params(self):\n        \"\"\"\n        Return a good (or standard) starting parameter vector, used to initialize a gauge optimization.\n\n        Returns\n        -------\n        numpy.ndarray\n            A 1D array of length :method:`num_params`.\n        \"\"\"\n        return self._operation.to_vector()\n\n\nclass OpGaugeGroupElement(GaugeGroupElement):\n    \"\"\"\n    The element type for `OpGaugeGroup`-derived gauge groups\n\n    Parameters\n    ----------\n    operation : LinearOperator\n        The operation to base this element on. It provides both parameterization\n        information and the gauge transformation matrix itself.\n    \"\"\"\n\n    def __init__(self, operation):\n        \"\"\"\n        Create a new element based on `operation`\n\n        Parameters\n        ----------\n        operation : LinearOperator\n            The operation to base this element on. It provides both parameterization\n            information and the gauge transformation matrix itself.\n        \"\"\"\n        if not isinstance(operation, _op.LinearOperator):\n            operation = _op.StaticArbitraryOp(operation, evotype='default', state_space=None)\n        self._operation = operation\n        self._inv_matrix = None\n        GaugeGroupElement.__init__(self)\n\n    @property\n    def transform_matrix(self):\n        \"\"\"\n        The gauge-transform matrix.\n\n        Returns\n        -------\n        numpy.ndarray\n        \"\"\"\n        return self._operation.to_dense(on_space='minimal')\n\n    @property\n    def transform_matrix_inverse(self):\n        \"\"\"\n        The inverse of the gauge-transform matrix.\n\n        Returns\n        -------\n        numpy.ndarray\n        \"\"\"\n        if self._inv_matrix is None:\n            self._inv_matrix = _np.linalg.inv(self._operation.to_dense(on_space='minimal'))\n        return self._inv_matrix\n\n    def deriv_wrt_params(self, wrt_filter=None):\n        \"\"\"\n        Computes the derivative of the gauge group at this element.\n\n        That is, the derivative of a general element with respect to the gauge\n        group's parameters, evaluated at this element.\n\n        Parameters\n        ----------\n        wrt_filter : list or numpy.ndarray, optional\n            Indices of the gauge group parameters to differentiate with respect to.\n            If None, differentiation is performed with respect to all the group's parameters.\n\n        Returns\n        -------\n        numpy.ndarray\n        \"\"\"\n        return self._operation.deriv_wrt_params(wrt_filter)\n\n    def to_vector(self):\n        \"\"\"\n        Get the parameter vector corresponding to this transform.\n\n        Returns\n        -------\n        numpy.ndarray\n        \"\"\"\n        return self._operation.to_vector()\n\n    def from_vector(self, v):\n        \"\"\"\n        Reinitialize this `GaugeGroupElement` using the the parameter vector `v`.\n\n        Parameters\n        ----------\n        v : numpy.ndarray\n            A 1D array of length :method:`num_params`\n\n        Returns\n        -------\n        None\n        \"\"\"\n        self._operation.from_vector(v)\n        self._inv_matrix = None\n\n    @property\n    def num_params(self):\n        \"\"\"\n        Return the number of parameters (degrees of freedom) of this element.\n\n        Returns\n        -------\n        int\n        \"\"\"\n        return self._operation.num_params\n\n\nclass FullGaugeGroup(OpGaugeGroup):\n    \"\"\"\n    A fully-parameterized gauge group.\n\n    Every element of the gauge transformation matrix is an independent parameter.\n\n    Parameters\n    ----------\n    state_space : StateSpace\n        The state space for this gauge group.  This is the state space that\n        elements of the gauge group act on.  This should be the same as `mdl.state_space`\n        where `mdl` is a :class:`Model` you want to gauge-transform.\n\n    evotype : Evotype or str, optional\n        The evolution type.  The special value `\"default\"` is equivalent\n        to specifying the value of `pygsti.evotypes.Evotype.default_evotype`.\n    \"\"\"\n\n    def __init__(self, state_space, evotype='default'):\n        operation = _op.FullArbitraryOp(_np.identity(state_space.dim, 'd'), evotype, state_space)\n        OpGaugeGroup.__init__(self, operation, FullGaugeGroupElement, \"Full\")\n\n\nclass FullGaugeGroupElement(OpGaugeGroupElement):\n    \"\"\"\n    Element of a :class:`FullGaugeGroup`\n\n    Parameters\n    ----------\n    operation : LinearOperator\n        The operation to base this element on. It provides both parameterization\n        information and the gauge transformation matrix itself.\n    \"\"\"\n\n    def __init__(self, operation):\n        \"\"\"\n        Creates a new gauge group element based on `operation`, which\n        is assumed to have the correct parameterization.\n        \"\"\"\n        OpGaugeGroupElement.__init__(self, operation)\n\n\nclass TPGaugeGroup(OpGaugeGroup):\n    \"\"\"\n    A gauge group spanning all trace-preserving (TP) gauge transformations.\n\n    Implemented as a gauge transformation matrix whose first row is locked\n    as `[1,0,0...0]` and where every other element is an independent parameter.\n\n    Parameters\n    ----------\n    state_space : StateSpace\n        The state space for this gauge group.  This is the state space that\n        elements of the gauge group act on.  This should be the same as `mdl.state_space`\n        where `mdl` is a :class:`Model` you want to gauge-transform.\n\n    evotype : Evotype or str, optional\n        The evolution type.  The special value `\"default\"` is equivalent\n        to specifying the value of `pygsti.evotypes.Evotype.default_evotype`.\n    \"\"\"\n\n    def __init__(self, state_space, evotype='default'):\n        operation = _op.FullTPOp(_np.identity(state_space.dim, 'd'), evotype, state_space)\n        OpGaugeGroup.__init__(self, operation, TPGaugeGroupElement, \"TP\")\n\n\nclass TPGaugeGroupElement(OpGaugeGroupElement):\n    \"\"\"\n    Element of a :class:`TPGaugeGroup`\n\n    Parameters\n    ----------\n    operation : LinearOperator\n        The operation to base this element on. It provides both parameterization\n        information and the gauge transformation matrix itself.\n    \"\"\"\n\n    def __init__(self, operation):\n        \"\"\"\n        Creates a new gauge group element based on `operation`, which\n        is assumed to have the correct parameterization.\n        \"\"\"\n        OpGaugeGroupElement.__init__(self, operation)\n\n    @property\n    def transform_matrix_inverse(self):\n        \"\"\"\n        The inverse of the gauge-transform matrix.\n\n        Returns\n        -------\n        numpy.ndarray\n        \"\"\"\n        if self._inv_matrix is None:\n            self._inv_matrix = _np.linalg.inv(self._operation.to_dense())\n            self._inv_matrix[0, :] = 0.0  # ensure invers is *exactly* TP\n            self._inv_matrix[0, 0] = 1.0  # as otherwise small variations can get amplified\n        return self._inv_matrix\n\n\nclass DiagGaugeGroup(OpGaugeGroup):\n    \"\"\"\n    A gauge group consisting of just diagonal gauge-transform matrices.\n\n    (Each diagonal element is a separate parameter.)\n\n    Parameters\n    ----------\n    state_space : StateSpace\n        The state space for this gauge group.  This is the state space that\n        elements of the gauge group act on.  This should be the same as `mdl.state_space`\n        where `mdl` is a :class:`Model` you want to gauge-transform.\n\n    evotype : Evotype or str, optional\n        The evolution type.  The special value `\"default\"` is equivalent\n        to specifying the value of `pygsti.evotypes.Evotype.default_evotype`.\n    \"\"\"\n\n    def __init__(self, state_space, evotype='default'):\n        dim = state_space.dim\n        ltrans = _np.identity(dim, 'd')\n        rtrans = _np.identity(dim, 'd')\n        baseMx = _np.identity(dim, 'd')\n        parameterArray = _np.zeros(dim, 'd')\n        parameterToBaseIndicesMap = {i: [(i, i)] for i in range(dim)}\n        operation = _op.LinearlyParamArbitraryOp(baseMx, parameterArray,\n                                                 parameterToBaseIndicesMap,\n                                                 ltrans, rtrans, real=True,\n                                                 evotype=evotype, state_space=state_space)\n        OpGaugeGroup.__init__(self, operation, DiagGaugeGroupElement, \"Diagonal\")\n\n\nclass DiagGaugeGroupElement(OpGaugeGroupElement):\n    \"\"\"\n    Element of a :class:`DiagGaugeGroup`\n\n    Parameters\n    ----------\n    operation : LinearOperator\n        The operation to base this element on. It provides both parameterization\n        information and the gauge transformation matrix itself.\n    \"\"\"\n\n    def __init__(self, operation):\n        \"\"\"\n        Creates a new gauge group element based on `operation`, which\n        is assumed to have the correct parameterization.\n        \"\"\"\n        OpGaugeGroupElement.__init__(self, operation)\n\n\nclass TPDiagGaugeGroup(TPGaugeGroup):\n    \"\"\"\n    A gauge group consisting of just trace-preserving (TP) diagonal gauge-transform matrices.\n\n    That is, where the first (`[0,0]`) element is fixed at 1.0,\n    and each subsequent diagonal element is a separate parameter.\n\n    Parameters\n    ----------\n    state_space : StateSpace\n        The state space for this gauge group.  This is the state space that\n        elements of the gauge group act on.  This should be the same as `mdl.state_space`\n        where `mdl` is a :class:`Model` you want to gauge-transform.\n\n    evotype : Evotype or str, optional\n        The evolution type.  The special value `\"default\"` is equivalent\n        to specifying the value of `pygsti.evotypes.Evotype.default_evotype`.\n    \"\"\"\n\n    def __init__(self, state_space, evotype='default'):\n        \"\"\"\n        Create a new gauge group with gauge-transform dimension `dim`, which\n        should be the same as `mdl.dim` where `mdl` is a :class:`Model` you\n        might gauge-transform.\n        \"\"\"\n        dim = state_space.dim\n        ltrans = _np.identity(dim, 'd')\n        rtrans = _np.identity(dim, 'd')\n        baseMx = _np.identity(dim, 'd')\n        parameterArray = _np.zeros(dim - 1, 'd')\n        parameterToBaseIndicesMap = {i: [(i + 1, i + 1)] for i in range(dim - 1)}\n        operation = _op.LinearlyParamArbitraryOp(baseMx, parameterArray,\n                                                 parameterToBaseIndicesMap,\n                                                 ltrans, rtrans, real=True,\n                                                 evotype=evotype, state_space=state_space)\n        OpGaugeGroup.__init__(self, operation, TPDiagGaugeGroupElement, \"TP Diagonal\")\n\n\nclass TPDiagGaugeGroupElement(TPGaugeGroupElement):\n    \"\"\"\n    Element of a :class:`TPDiagGaugeGroup`\n\n    Parameters\n    ----------\n    operation : LinearOperator\n        The operation to base this element on. It provides both parameterization\n        information and the gauge transformation matrix itself.\n    \"\"\"\n\n    def __init__(self, operation):\n        \"\"\"\n        Creates a new gauge group element based on `operation`, which\n        is assumed to have the correct parameterization.\n        \"\"\"\n        TPGaugeGroupElement.__init__(self, operation)\n\n\nclass UnitaryGaugeGroup(OpGaugeGroup):\n    \"\"\"\n    A gauge group consisting of unitary gauge-transform matrices.\n\n    This group includes those (superoperator) transformation matrices that\n    correspond to unitary evolution.  Parameterization is performed via a\n    Lindblad parametrizaton with only Hamiltonian terms.\n\n    Parameters\n    ----------\n    state_space : StateSpace\n        The state space for this gauge group.  This is the state space that\n        elements of the gauge group act on.  This should be the same as `mdl.state_space`\n        where `mdl` is a :class:`Model` you want to gauge-transform.\n\n    basis : Basis or {\"pp\", \"gm\", \"std\"}\n        The basis to use when parameterizing the Hamiltonian Lindblad terms.\n\n    evotype : Evotype or str, optional\n        The evolution type.  The special value `\"default\"` is equivalent\n        to specifying the value of `pygsti.evotypes.Evotype.default_evotype`.\n    \"\"\"\n\n    def __init__(self, state_space, basis, evotype='default'):\n        errgen = _op.LindbladErrorgen.from_operation_matrix(\n            _np.identity(state_space.dim, 'd'), \"H\", basis, mx_basis=basis, evotype=evotype)\n        operation = _op.ExpErrorgenOp(errgen)\n        OpGaugeGroup.__init__(self, operation, UnitaryGaugeGroupElement, \"Unitary\")\n\n\nclass UnitaryGaugeGroupElement(OpGaugeGroupElement):\n    \"\"\"\n    Element of a :class:`UnitaryGaugeGroup`\n\n    Parameters\n    ----------\n    operation : LinearOperator\n        The operation to base this element on. It provides both parameterization\n        information and the gauge transformation matrix itself.\n    \"\"\"\n\n    def __init__(self, operation):\n        \"\"\"\n        Creates a new gauge group element based on `operation`, which\n        is assumed to have the correct parameterization.\n        \"\"\"\n        OpGaugeGroupElement.__init__(self, operation)\n\n\nclass SpamGaugeGroup(OpGaugeGroup):\n    \"\"\"\n    Gauge transformations which scale the SPAM and non-unital portions of the gates in a gate set.\n\n    A 2-dimensional gauge group spanning transform matrices of the form:\n    [ [ a 0 ... 0]   where a and b are the 2 parameters.  These diagonal\n      [ 0 b ... 0]   transform matrices do not affect the SPAM operations\n      [ . . ... .]   much more than typical near-unital and TP operations, and\n      [ 0 0 ... b] ] so we call this group of transformations the \"SPAM gauge\".\n\n    Parameters\n    ----------\n    state_space : StateSpace\n        The state space for this gauge group.  This is the state space that\n        elements of the gauge group act on.  This should be the same as `mdl.state_space`\n        where `mdl` is a :class:`Model` you want to gauge-transform.\n\n    evotype : Evotype or str, optional\n        The evolution type.  The special value `\"default\"` is equivalent\n        to specifying the value of `pygsti.evotypes.Evotype.default_evotype`.\n    \"\"\"\n\n    def __init__(self, state_space, evotype='default'):\n        \"\"\"\n        Create a new gauge group with gauge-transform dimension `dim`, which\n        should be the same as `mdl.dim` where `mdl` is a :class:`Model` you\n        might gauge-transform.\n        \"\"\"\n        dim = state_space.dim\n        ltrans = _np.identity(dim, 'd')\n        rtrans = _np.identity(dim, 'd')\n        baseMx = _np.identity(dim, 'd')\n        parameterArray = _np.zeros(2, 'd')\n        parameterToBaseIndicesMap = {0: [(0, 0)],\n                                     1: [(i, i) for i in range(1, dim)]}\n        operation = _op.LinearlyParamArbitraryOp(baseMx, parameterArray,\n                                                 parameterToBaseIndicesMap,\n                                                 ltrans, rtrans, real=True,\n                                                 evotype=evotype, state_space=state_space)\n        OpGaugeGroup.__init__(self, operation, SpamGaugeGroupElement, \"Spam\")\n\n\nclass SpamGaugeGroupElement(OpGaugeGroupElement):\n    \"\"\"\n    Element of a :class:`SpamGaugeGroup`\n\n    Parameters\n    ----------\n    operation : LinearOperator\n        The operation to base this element on. It provides both parameterization\n        information and the gauge transformation matrix itself.\n    \"\"\"\n\n    def __init__(self, operation):\n        \"\"\"\n        Creates a new gauge group element based on `operation`, which\n        is assumed to have the correct parameterization.\n        \"\"\"\n        OpGaugeGroupElement.__init__(self, operation)\n\n\nclass TPSpamGaugeGroup(OpGaugeGroup):\n    \"\"\"\n    Similar to :class:`SpamGaugeGroup` except with TP constrains.\n\n    This means the `[0,0]` element of each transform matrix is fixed at 1.0\n    (so all gauge transforms are trace preserving), leaving just a single degree\n    of freedom.\n\n    Parameters\n    ----------\n    state_space : StateSpace\n        The state space for this gauge group.  This is the state space that\n        elements of the gauge group act on.  This should be the same as `mdl.state_space`\n        where `mdl` is a :class:`Model` you want to gauge-transform.\n\n    evotype : Evotype or str, optional\n        The evolution type.  The special value `\"default\"` is equivalent\n        to specifying the value of `pygsti.evotypes.Evotype.default_evotype`.\n    \"\"\"\n\n    def __init__(self, state_space, evotype='default'):\n        \"\"\"\n        Create a new gauge group with gauge-transform dimension `dim`, which\n        should be the same as `mdl.dim` where `mdl` is a :class:`Model` you\n        might gauge-transform.\n        \"\"\"\n        dim = state_space.dim\n        ltrans = _np.identity(dim, 'd')\n        rtrans = _np.identity(dim, 'd')\n        baseMx = _np.identity(dim, 'd')\n        parameterArray = _np.zeros(1, 'd')\n        parameterToBaseIndicesMap = {0: [(i, i) for i in range(1, dim)]}\n        operation = _op.LinearlyParamArbitraryOp(baseMx, parameterArray,\n                                                 parameterToBaseIndicesMap,\n                                                 ltrans, rtrans, real=True,\n                                                 evotype=evotype, state_space=state_space)\n        OpGaugeGroup.__init__(self, operation, TPSpamGaugeGroupElement, \"TP Spam\")\n\n\nclass TPSpamGaugeGroupElement(OpGaugeGroupElement):\n    \"\"\"\n    Element of :class:`TPSpamGaugeGroup`\n\n    Parameters\n    ----------\n    operation : LinearOperator\n        The operation to base this element on. It provides both parameterization\n        information and the gauge transformation matrix itself.\n    \"\"\"\n\n    def __init__(self, operation):\n        \"\"\"\n        Creates a new gauge group element based on `operation`, which\n        is assumed to have the correct parameterization.\n        \"\"\"\n        OpGaugeGroupElement.__init__(self, operation)\n\n\nclass TrivialGaugeGroup(GaugeGroup):\n    \"\"\"\n    A trivial gauge group with no degrees of freedom.\n\n    Useful for telling pyGSTi that you don't want to do any gauge optimization\n    within the framework common to the other gauge groups. Using a\n    `TrivialGaugeGroup` instead of `None` in gauge optimization will prevent\n    pyGSTi from wondering if you meant to not-gauge-optimize and displaying\n    warning messages.\n\n    Parameters\n    ----------\n    state_space : StateSpace\n        The state space for this gauge group.  This is the state space that\n        elements of the gauge group act on.  This should be the same as `mdl.state_space`\n        where `mdl` is a :class:`Model` you want to gauge-transform.\n    \"\"\"\n\n    def __init__(self, state_space):\n        self.state_space = state_space\n        GaugeGroup.__init__(self, \"Trivial\")\n\n    @property\n    def num_params(self):\n        \"\"\"\n        Return the number of parameters (degrees of freedom) of this gauge group.\n\n        Returns\n        -------\n        int\n        \"\"\"\n        return 0\n\n    def compute_element(self, param_vec):\n        \"\"\"\n        Retrieve the element of this group corresponding to `param_vec`\n\n        Parameters\n        ----------\n        param_vec : numpy.ndarray\n            A 1D array of length :method:`num_params`.\n\n        Returns\n        -------\n        TrivialGaugeGroupElement\n        \"\"\"\n        assert(len(param_vec) == 0)\n        return TrivialGaugeGroupElement(self.state_space.dim)\n\n    @property\n    def initial_params(self):\n        \"\"\"\n        Return a good (or standard) starting parameter vector, used to initialize a gauge optimization.\n\n        Returns\n        -------\n        numpy.ndarray\n            A 1D array of length :method:`num_params`.\n        \"\"\"\n        return _np.empty(0, 'd')\n\n\nclass TrivialGaugeGroupElement(GaugeGroupElement):\n    \"\"\"\n    Element of :class:`TrivialGaugeGroup`\n\n    Parameters\n    ----------\n    dim : int\n        The Hilbert-Schmidt space dimension of the gauge group.\n    \"\"\"\n\n    def __init__(self, dim):\n        \"\"\"\n        Creates a new trivial gauge group element of dimension `dim`.\n        (so transform matirx is a `dim` by `dim` identity matrix).\n        \"\"\"\n        self._matrix = _np.identity(dim, 'd')\n        GaugeGroupElement.__init__(self)\n\n    @property\n    def transform_matrix(self):\n        \"\"\"\n        The gauge-transform matrix.\n\n        Returns\n        -------\n        numpy.ndarray\n        \"\"\"\n        return self._matrix\n\n    @property\n    def transform_matrix_inverse(self):\n        \"\"\"\n        The inverse of the gauge-transform matrix.\n\n        Returns\n        -------\n        numpy.ndarray\n        \"\"\"\n        return self._matrix  # inverse of identity is itself!\n\n    def deriv_wrt_params(self, wrt_filter=None):\n        \"\"\"\n        Computes the derivative of the gauge group at this element.\n\n        That is, the derivative of a general element with respect to the gauge\n        group's parameters, evaluated at this element.\n\n        Parameters\n        ----------\n        wrt_filter : list or numpy.ndarray, optional\n            Indices of the gauge group parameters to differentiate with respect to.\n            If None, differentiation is performed with respect to all the group's parameters.\n\n        Returns\n        -------\n        numpy.ndarray\n        \"\"\"\n        return _np.empty(0, 'd')\n\n    def to_vector(self):\n        \"\"\"\n        Get the parameter vector corresponding to this transform.\n\n        Returns\n        -------\n        numpy.ndarray\n        \"\"\"\n        return _np.empty(0, 'd')\n\n    def from_vector(self, v):\n        \"\"\"\n        Reinitialize this `GaugeGroupElement` using the the parameter vector `v`.\n\n        Parameters\n        ----------\n        v : numpy.ndarray\n            A 1D array of length :method:`num_params`\n\n        Returns\n        -------\n        None\n        \"\"\"\n        assert(len(v) == 0)\n\n    @property\n    def num_params(self):\n        \"\"\"\n        Return the number of parameters (degrees of freedom) of this element.\n\n        Returns\n        -------\n        int\n        \"\"\"\n        return 0\n", "meta": {"hexsha": "0bb3819d1a315dfe47b0f9761a411cd3b2c919d9", "size": 31800, "ext": "py", "lang": "Python", "max_stars_repo_path": "pygsti/models/gaugegroup.py", "max_stars_repo_name": "colibri-coruscans/pyGSTi", "max_stars_repo_head_hexsha": "da54f4abf668a28476030528f81afa46a1fbba33", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pygsti/models/gaugegroup.py", "max_issues_repo_name": "colibri-coruscans/pyGSTi", "max_issues_repo_head_hexsha": "da54f4abf668a28476030528f81afa46a1fbba33", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pygsti/models/gaugegroup.py", "max_forks_repo_name": "colibri-coruscans/pyGSTi", "max_forks_repo_head_hexsha": "da54f4abf668a28476030528f81afa46a1fbba33", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2070657507, "max_line_length": 103, "alphanum_fraction": 0.6074213836, "include": true, "reason": "import numpy", "num_tokens": 6833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792046, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.16465058242182914}}
{"text": "from __future__ import annotations\n\nimport json\nimport warnings\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Tuple, Union\n\nimport emcee\nimport h5py\nimport numpy as np\nimport pandas as pd\nfrom scipy.special import factorial as fact\n\nimport lymph\n\n\ndef lyprox_to_lymph(\n    data: pd.DataFrame,\n    method: str = \"unilateral\",\n    modalities: List[str] = [\"MRI\", \"PET\"],\n    convert_t_stage: Optional[Dict[int, Any]] = None\n) -> pd.DataFrame:\n    \"\"\"Convert LyProX output into pandas :class:`DataFrame` that the lymph\n    package can use for sampling.\n\n    `LyProX <https://lyprox.org>`_ is our online interface where we make\n    detailed patterns of involvement on a per-patient basis available and\n    visualize it in useful ways.\n\n    Args:\n        data: Patient data exported from the LyProX interface.\n        method: Can be ``\"unilateral\"``, ``\"bilateral\"`` or ``\"midline\"``. It\n            corresponds to the three lymphatic network classes that are\n            implemented in the lymph package.\n        modalities: List of diagnostic modalities that should be extracted from\n            the exported data.\n        convert_t_stage: For each of the possible T-categories (0, 1, 2, 3, 4)\n            this dictionary holds a key where the corresponding value is the\n            'converted' T-category. For example, if one only wants to\n            differentiate between 'early' and 'late', then that dictionary\n            would look like this:\n\n            .. code-block:: python\n\n                convert_t_stage = {\n                    0: 'early',\n                    1: 'early',\n                    2: 'early',\n                    3: 'late',\n                    4: 'late'\n                }\n    Returns:\n        A converted pandas :class:`DataFrame` that can then be used with the\n        lymph package.\n    \"\"\"\n    t_stage_data = data[(\"tumor\", \"1\", \"t_stage\")]\n    midline_extension_data = data[(\"tumor\", \"1\", \"extension\")]\n    diagnostic_data = data[modalities].drop(columns=[\"date\"], level=2)\n\n    if convert_t_stage is not None:\n        diagnostic_data[(\"info\", \"tumor\", \"t_stage\")] = [\n            convert_t_stage[t] for t in t_stage_data.values\n        ]\n    else:\n        diagnostic_data[(\"info\", \"tumor\", \"t_stage\")] = t_stage_data\n\n    if method == \"midline\":\n        diagnostic_data[(\"info\", \"tumor\", \"midline_extension\")] = midline_extension_data\n    elif method == \"unilateral\":\n        diagnostic_data = diagnostic_data.drop(columns=[\"contra\"], level=1)\n        diagnostic_data.columns = diagnostic_data.columns.droplevel(1)\n\n    return diagnostic_data\n\n\nclass EnsembleSampler(emcee.EnsembleSampler):\n    \"\"\"A custom wrapper of emcee's ``EnsembleSampler`` that adds a sampling\n    method that automatically tracks convergence.\n    \"\"\"\n    def __init__(\n        self,\n        nwalkers,\n        ndim,\n        log_prob_fn,\n        pool=None,\n        moves=None,\n        args=None,\n        kwargs=None,\n        backend=None,\n        vectorize=False,\n        blobs_dtype=None,\n        parameter_names: Optional[Union[Dict[str, int], List[str]]] = None\n    ):\n        \"\"\"Just define a default mixture of moves.\n        \"\"\"\n        if moves is None:\n            moves = [\n                (emcee.moves.DEMove(),        0.8),\n                (emcee.moves.DESnookerMove(), 0.2)\n            ]\n\n        super().__init__(\n            nwalkers,\n            ndim,\n            log_prob_fn,\n            pool,\n            moves,\n            args,\n            kwargs,\n            backend,\n            vectorize,\n            blobs_dtype,\n            parameter_names\n        )\n\n    def run_sampling(\n        self,\n        max_steps: int = 10000,\n        check_interval: int = 100,\n        trust_threshold: float = 50.,\n        rel_acor_threshold: float = 0.05,\n        verbose: bool = True,\n        **kwargs\n    ) -> np.ndarray:\n        \"\"\"Extract ``start`` from settings of the sampler and perform sampling\n        while monitoring the convergence.\n\n        Args:\n            max_steps: Maximum number of sampling steps to perform.\n            check_interval: Number of sampling steps after which to check for\n                convergence.\n            trust_threshold: The autocorrelation estimate is only trusted when\n                it is smaller than the number of samples drawn divided by this\n                parameter.\n            rel_acor_threshold: The relative change of two consequtive trusted\n                autocorrelation estimates must fall below.\n            verbose: Show progress during sampling and success at the end.\n            **kwargs: Any other ``kwargs`` are directly passed to the ``sample``\n                method.\n\n        Returns:\n            A list of mean autocorrelation times, computed every\n            ``check_interval`` samples.\n        \"\"\"\n        if verbose:\n            print(\"Starting sampling\")\n\n        start = np.random.uniform(\n            low=0., high=1.,\n            size=(self.nwalkers, self.ndim)\n        )\n\n        acor_list = []\n        old_acor = np.inf\n        idx = 0\n        is_converged = False\n\n        for sample in self.sample(start, iterations=max_steps, progress=verbose, **kwargs):\n            # after `check_interval` number of samples...\n            if self.iteration % check_interval:\n                continue\n\n            # ...compute the autocorrelation time and store it in an array.\n            new_acor = self.get_autocorr_time(tol=0)\n            acor_list.append(np.mean(new_acor))\n            idx += 1\n\n            # check convergence based on two criterions:\n            # - has the acor time crossed the N / `trust_theshold` line?\n            # - did the acor time stay stable?\n            is_converged = np.all(new_acor * trust_threshold < self.iteration)\n            rel_acor_diff = np.abs(old_acor - new_acor) / new_acor\n            is_converged &= np.all(rel_acor_diff < rel_acor_threshold)\n\n            # if it has converged, stop\n            if is_converged:\n                break\n\n            old_acor = new_acor\n\n        if verbose:\n            if is_converged:\n                print(f\"Sampler converged after {self.iteration} steps\")\n            else:\n                print(\"Max. number of steps reached\")\n\n            acc_frac = 100 * np.mean(self.acceptance_fraction)\n            print(f\"Acceptance fraction = {acc_frac:.2f}%\")\n            print(f\"Mean autocorrelation time = {np.mean(old_acor):.2f}\")\n\n        return acor_list\n\n\ndef tupledict_to_jsondict(dict: Dict[Tuple[str], List[str]]) -> Dict[str, List[str]]:\n    \"\"\"Take a dictionary that has tuples as keys and stringify those keys so\n    that it can be serialized to JSON.\n    \"\"\"\n    jsondict = {}\n    for k, v in dict.items():\n        if np.any([',' in s for s in k]):\n            raise ValueError(\"Strings in in key tuple must not contain commas\")\n\n        jsondict[\",\".join(k)] = v\n    return jsondict\n\ndef jsondict_to_tupledict(dict: Dict[str, List[str]]) -> Dict[Tuple[str], List[str]]:\n    \"\"\"Take a serialized JSON dictionary where the keys are strings of\n    comma-separated names and convert them into keys of tuples.\n    \"\"\"\n    tupledict = {}\n    for k, v in dict.items():\n        tupledict[tuple(n for n in k.split(\",\"))] = v\n    return tupledict\n\n\nclass HDFMixin(object):\n    \"\"\"Mixin for the :class:`Unilateral`, :class:`Bilateral` and\n    :class:`MidlineBilateral` classes to provide the ability to store and load\n    settings to and from an HDF5 file.\n    \"\"\"\n    graph: Dict[Tuple[str], List[str]]\n    patient_data: pd.DataFrame\n    modalities: Dict[str, List[float]]\n\n    def to_hdf(\n        self,\n        filename: str,\n        name: str = \"\",\n    ):\n        \"\"\"Store some important settings as well as the loaded data in the\n        specified HDF5 file.\n\n        Args:\n            filename: Name of or path to HDF5 file.\n            name: Name of the group where the info is supposed to be\n                stored.\n        \"\"\"\n        filename = Path(filename).resolve()\n\n        with h5py.File(filename, 'a') as file:\n            group = file.require_group(f\"{name}\")\n            group.attrs[\"class\"] = self.__class__.__name__\n            group.attrs[\"graph\"] = json.dumps(tupledict_to_jsondict(self.graph))\n            group.attrs[\"modalities\"] = json.dumps(self.modalities)\n            group.attrs[\"base_symmetric\"] = getattr(\n                self, \"base_symmetric\", \"None\"\n            )\n            group.attrs[\"trans_symmetric\"] = getattr(\n                self, \"trans_symmetric\", \"None\"\n            )\n\n        with pd.HDFStore(filename, 'a') as store:\n            store.put(\n                key=f\"{name}/patient_data\",\n                value=self.patient_data,\n                format=\"fixed\",     # due to MultiIndex this needs to be fixed\n                data_columns=None\n            )\n\ndef system_from_hdf(\n    filename: str,\n    name: str = \"\",\n    **kwargs\n):\n    \"\"\"Create a lymph system instance from the information saved in an HDF5\n    file.\n\n    Args:\n        filename: Name of the HDF5 file where the info is stored.\n        name: Subgroup where to look for the stored settings and data.\n\n    Any other keyword arguments are passed directly to the constructor of the\n    respective class.\n\n    Returns:\n        An instance of :class:`lymph.Unilateral`, :class:`lymph.Bilateral` or\n        :class:`lymph.MidlineBilateral`.\n    \"\"\"\n    filename = Path(filename).resolve()\n    recover_None = lambda val: val if val != \"None\" else None\n\n    with h5py.File(filename, 'a') as file:\n        group = file.require_group(f\"{name}\")\n        classname = group.attrs[\"class\"]\n        graph = jsondict_to_tupledict(json.loads(group.attrs[\"graph\"]))\n        modalities = json.loads(group.attrs[\"modalities\"])\n        base_symmetric = recover_None(group.attrs[\"base_symmetric\"])\n        trans_symmetric = recover_None(group.attrs[\"trans_symmetric\"])\n\n    with pd.HDFStore(filename, 'a') as store:\n        patient_data = store.get(f\"{name}/patient_data\")\n\n    if classname == \"Unilateral\":\n        new_cls = lymph.Unilateral\n    elif classname == \"Bilateral\":\n        new_cls = lymph.Bilateral\n    elif classname == \"MidlineBilateral\":\n        new_cls = lymph.MidlineBilateral\n    else:\n        raise RuntimeError(\n            \"The classname loaded from the file does not correspond to an \"\n            \"implemented class in the `lymph` package.\"\n        )\n\n    new_sys = new_cls(\n        graph=graph,\n        base_symmetric=base_symmetric,\n        trans_symmetric=trans_symmetric,\n        **kwargs\n    )\n    new_sys.modalities = modalities\n    new_sys.patient_data = patient_data\n    return new_sys\n\n\ndef fast_binomial_pmf(k: int, n: int, p: float):\n    \"\"\"Compute the probability mass function of the binomial distribution.\n    \"\"\"\n    q = (1. - p)\n    binom_coeff = fact(n) / (fact(k) * fact(n - k))\n    return binom_coeff * p**k * q**(n - k)\n\n\ndef change_base(\n    number: int,\n    base: int,\n    reverse: bool = False,\n    length: Optional[int] = None\n) -> str:\n    \"\"\"Convert an integer into another base.\n\n    Args:\n        number: Number to convert\n        base: Base of the resulting converted number\n        reverse: If true, the converted number will be printed in reverse order.\n        length: Length of the returned string. If longer than would be\n            necessary, the output will be padded.\n\n    Returns:\n        The (padded) string of the converted number.\n    \"\"\"\n    if number < 0:\n        raise ValueError(\"Cannot convert negative numbers\")\n    if base > 16:\n        raise ValueError(\"Base must be 16 or smaller!\")\n    elif base < 2:\n        raise ValueError(\"There is no unary number system, base must be > 2\")\n\n    convertString = \"0123456789ABCDEF\"\n    result = ''\n\n    if number == 0:\n        result += '0'\n    else:\n        while number >= base:\n            result += convertString[number % base]\n            number = number//base\n        if number > 0:\n            result += convertString[number]\n\n    if length is None:\n        length = len(result)\n    elif length < len(result):\n        length = len(result)\n        warnings.warn(\"Length cannot be shorter than converted number.\")\n\n    pad = '0' * (length - len(result))\n\n    if reverse:\n        return result + pad\n    else:\n        return pad + result[::-1]\n\n\ndef comp_state_dist(table: np.ndarray) -> Tuple[np.ndarray, List[str]]:\n    \"\"\"Compute the distribution of distinct states/diagnoses from a table of\n    individual diagnoses detailing the patterns of lymphatic progression per\n    patient.\n\n    Args:\n        table: Rows of patients and columns of LNLs, reporting which LNL was\n            involved for which patient.\n\n    Returns:\n        A histogram of unique states and a list of the corresponding state\n        labels.\n\n    Note:\n        This function cannot deal with parts of the diagnose being unknown. So\n        if, e.g., one level isn't reported for a patient, that row will just be\n        ignored.\n    \"\"\"\n    _, num_cols = table.shape\n    table = table.astype(float)\n    state_dist = np.zeros(shape=2**num_cols, dtype=int)\n    for row in table:\n        if not np.any(np.isnan(row)):\n            idx = int(np.sum([n * 2**i for i,n in enumerate(row[::-1])]))\n            state_dist[idx] += 1\n\n    state_labels = []\n    for i in range(2**num_cols):\n        state_labels.append(change_base(i, 2, length=num_cols))\n\n    return state_dist, state_labels\n\n\ndef draw_diagnose_times(\n    num_patients: int,\n    stage_dist: Dict[Any, float],\n    diag_times: Optional[Dict[Any, int]] = None,\n    time_dists: Optional[Dict[Any, List[float]]] = None,\n) -> Tuple[List[int], List[Any]]:\n    \"\"\"Draw T-stages from a distribution over them and determine the\n    corresponding diagnose time or draw a one from a distribution over diagnose\n    times defined for the respective T-stage.\n\n    Args:\n        num_patients: Number of patients to draw diagnose times for.\n        stage_dist: Distribution over T-stages.\n        diag_times: Fixed diagnose time for a given T-stage.\n        time_dists: Holds a distribution over diagnose times for each T-stage\n            from which the diagnose times will be drawn if it is given. If this\n            is ``None``, ``diag_times`` must be provided.\n\n    Returns:\n        The drawn T-stages as well as the drawn diagnose times.\n    \"\"\"\n    if num_patients < 1:\n        raise ValueError(\"Number of patients to draw must be 1 or larger\")\n    if not np.isclose(np.sum(stage_dist), 1.):\n        raise ValueError(\"Distribution over T-stages must sum to 1.\")\n\n    # draw the diagnose times for each patient\n    if diag_times is not None:\n        t_stages = list(diag_times.keys())\n        drawn_t_stages = np.random.choice(\n            t_stages,\n            p=stage_dist,\n            size=num_patients\n        )\n        drawn_diag_times = [diag_times[t] for t in drawn_t_stages]\n\n    elif time_dists is not None:\n        t_stages = list(time_dists.keys())\n        max_t = len(time_dists[t_stages[0]]) - 1\n        time_steps = np.arange(max_t + 1)\n\n        drawn_t_stages = np.random.choice(\n            t_stages,\n            p=stage_dist,\n            size=num_patients\n        )\n        drawn_diag_times = [\n            np.random.choice(time_steps, p=time_dists[t])\n            for t in drawn_t_stages\n        ]\n\n    else:\n        raise ValueError(\n            \"Either `diag_times`or `time_dists` must be provided\"\n        )\n\n    return drawn_t_stages, drawn_diag_times\n\n\ndef draw_from_simplex(ndim: int, nsample: int = 1) -> np.ndarray:\n    \"\"\"Draw uniformly from an n-dimensional simplex.\n\n    Args:\n        ndim: Dimensionality of simplex to draw from.\n        nsample: Number of samples to draw from the simplex.\n\n    Returns:\n        A matrix of shape (nsample, ndim) that sums to one along axis 1.\n    \"\"\"\n    if ndim < 1:\n        raise ValueError(\"Cannot generate less than 1D samples\")\n    if nsample < 1:\n        raise ValueError(\"Generating less than one sample doesn't make sense\")\n\n    rand = np.random.uniform(size=(nsample, ndim-1))\n    unsorted = np.concatenate(\n        [np.zeros(shape=(nsample,1)), rand, np.ones(shape=(nsample,1))],\n        axis=1\n    )\n    sorted = np.sort(unsorted, axis=1)\n\n    diff_arr = np.concatenate([[-1., 1.], np.zeros(ndim-1)])\n    diff_mat = np.array([np.roll(diff_arr, i) for i in range(ndim)]).T\n    res = sorted @ diff_mat\n\n    return res", "meta": {"hexsha": "ffbe4a9c5e5b392a9b7c672fec7115ce60cf8a14", "size": 16294, "ext": "py", "lang": "Python", "max_stars_repo_path": "lymph/utils.py", "max_stars_repo_name": "lfranceschetti/lymph", "max_stars_repo_head_hexsha": "d7fc8c0709316fb1b055487f6c3c2165d889974a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lymph/utils.py", "max_issues_repo_name": "lfranceschetti/lymph", "max_issues_repo_head_hexsha": "d7fc8c0709316fb1b055487f6c3c2165d889974a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lymph/utils.py", "max_forks_repo_name": "lfranceschetti/lymph", "max_forks_repo_head_hexsha": "d7fc8c0709316fb1b055487f6c3c2165d889974a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0507099391, "max_line_length": 91, "alphanum_fraction": 0.6050079784, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.16465058242182912}}
{"text": "\"\"\"多维多时间序列神经网络滚动训练的数据工具.\n\nversion: 0.0.19\n\nauthor: Congyu Wang\n\ndate: 2021-08-26\n\"\"\"\nimport numpy as np\nimport tensorflow as _tf\nimport numpy as _np\nfrom numba import njit\nfrom typing import List as _List\n\n__all__ = [\"TimeSeriesData\", \"TrainValData\"]\n\n\nclass TimeSeriesData:\n    \"\"\"单个时间序列信息.\n\n    Notes:\n        用于储存个股的数据信息及预测label，全部使用numpy，日期格式为整数: ``YYYYMMDD``。\n        数据分三个部分：时间，数据，标签，第一个维度都是时间，数据的第二个维度为特征。\n\n    \"\"\"\n\n    def __init__(self,\n                 dates: _np.ndarray,\n                 data: _np.ndarray,\n                 labels: _np.ndarray):\n        \"\"\"储存个股的数据信息及预测目标，全部使用numpy，日期格式为整数: ``YYYYMMDD``.\n\n        Args:\n            dates: 日期列, 1D ``numpy.ndarray``, 整数\n            data: 训练输入的X，2D ``numpy.ndarray``, (日期长度 x 特征数量)\n            labels: 训练标签Y, 1D ``numpy.ndarray``, 长度与dates相同。\n                如果为分类问题则是2D, (日期长度 x 类别数量)\n\n        \"\"\"\n        # 检查参数类型\n        if (not type(dates) is _np.ndarray or\n                not type(data) is _np.ndarray or\n                not type(labels) is _np.ndarray):\n            raise ValueError(\"Data should be numpy arrays\")\n        # 检查日期、数据、标签长度是否一致\n        if len(dates) != len(data) or len(dates) != len(labels):\n            raise ValueError(\"Bad data shape\")\n        # 检查维度是否正确\n        if dates.ndim != 1 or data.ndim != 2 or not 1 <= labels.ndim <= 2:\n            raise ValueError(\"Wrong dimensions\")\n        self.dates = dates.astype(_np.int32)\n        self.data = data\n        self.labels = labels\n\n\nclass TrainValData:\n    \"\"\"根据训练天数、验证天数、样本历史长度、训练起点生成不同训练阶段的数据.\"\"\"\n\n    def __init__(self,\n                 time_series_list: _List[TimeSeriesData],\n                 train_length: int = 1200,\n                 validate_length: int = 300,\n                 history_length: int = 30,\n                 train_val_gap: int = 10,\n                 sample_step: int = 2,\n                 fill_na: _np.float = _np.NaN,\n                 normalize: bool = False):\n        \"\"\"用于获取不同阶段的训练集和验证集.\n\n        Notes:\n            ``time_series_list``储存全部的时间序列信息，\n            其中每支股票序列为一个单独``TimeSeriesData``，\n            完整数据为``List[TimeSeriesData]``类型。\n\n            此外需要提供训练集总交易天数(``train_length``)、\n            验证集总交易天数(``validate_length``)、\n            单个样本用到的历史长度(``history_length``)、\n            采样步进大小(``sample_step``)。\n\n            使用方法为：通过get(start_date)方法获取从start_date\n            开始的训练机和验证集。通过逐渐增大start_date训练多个模型回测。\n\n            ``train_val_gap``参数为验证集第一天与训练集最后一天中间间隔的天数，\n            如果是相临，则train_val_gap = 0。设置该参数的目的如下：\n\n            如果希望预测未来十天的累计收益，则预测时用到的输入数据为最近的历史数据来预测\n            未来十天的累计收益，即用t(-history)到t(0)的数据来预测t(1)到t(11)的累计收益\n            而训练时因为要用到十天累计收益做标签，最近的一个十天累计收益是从t(-10)到t(0)，\n            用到的历史数据则必须是t(-history-11)到t(-11)的数据。\n            而validation时，如果第一个预测点是t(1)(明天收盘价)至t(11)的累计收益，\n            则与最后一个训练的数据即：t(-10)至t(0)之间间隔了10天，\n            使用``train_val_gap=10``。\n\n            可选项为fill_na，缺失数据填充值，默认为np.Na\n            训练时跳过所有有缺失数据的样本。\n\n        Args:\n            time_series_list: TimeSeriesData 列表\n            train_length: 训练集天数\n            validate_length: 验证集天数\n            history_length: 每个样本的历史天数\n            train_val_gap: 训练集与验证集的间隔\n            sample_step: 采样sample时步进的天数\n            fill_na: 默认填充为np.NaN，训练时会跳过有确实数据的样本\n            normalize: 是否对非率值做每个历史片段的max/min标准化\n\n        \"\"\"\n        # 检查参数类型\n        if type(time_series_list) is not list:\n            raise ValueError(\"time_series_list should be a list\")\n        # 不允许空列表\n        if len(time_series_list) == 0:\n            raise ValueError(\"Empty time_series_list\")\n        # 检查列表元素类型\n        for t in time_series_list:\n            if type(t) is not TimeSeriesData:\n                raise ValueError(\"time_series_data should be a list \"\n                                 \"of TimeSeriesData objects\")\n        # 检查参数数值\n        if (type(history_length) is not int or\n                type(validate_length) is not int or\n                type(sample_step) is not int or\n                type(train_length) is not int or\n                type(train_val_gap) is not int or\n                history_length < 1 or\n                validate_length < 1 or\n                sample_step < 1 or\n                train_val_gap < 0 or\n                train_length < history_length):\n            raise ValueError(\"bad arguments\")\n\n        if type(fill_na) is not _np.float:\n            raise ValueError(\"fill_na should be numpy float\")\n\n        # 确保数据特征数量一致\n        self.__feature_counts = time_series_list[0].data.shape[1]\n        for series in time_series_list:\n            if series.data.shape[1] != self.__feature_counts:\n                raise ValueError(\"time series do not have \"\n                                 \"the same number of features\")\n\n        # 确保标签维度一致\n        label_dims = time_series_list[0].labels.ndim\n        for series in time_series_list:\n            if series.labels.ndim != label_dims:\n                raise ValueError(\"time labels do not have \"\n                                 \"the same number of dimensions\")\n\n        # 标签类别数量\n        class_num = 0\n        if label_dims == 2:\n            class_num = time_series_list[0].labels.shape[1]\n            for series in time_series_list:\n                if series.labels.shape[1] != class_num:\n                    raise ValueError(\"time series labels do not have \"\n                                     \"the same number of classes\")\n\n        self.__class_num = class_num\n\n        # 获取日期列表（所有时间序列日期的并集）\n        self.__distinct_dates = _np.unique([date for stock in time_series_list\n                                            for date in stock.dates])\n        self.__distinct_dates.sort()\n\n        # 聚合数据为(序列(股票), 时间, 特征数量)的张量，缺失数据为np.NaN\n        # 标签维度为(序列(股票), 时间)\n        self.__data = _np.empty((len(time_series_list),\n                                 len(self.__distinct_dates),\n                                 self.__feature_counts),\n                                dtype=_np.float32)\n        if self.__class_num == 0:\n            self.__labels = _np.empty((len(time_series_list),\n                                       len(self.__distinct_dates)),\n                                      dtype=_np.float32)\n        else:\n            self.__labels = _np.empty((len(time_series_list),\n                                       len(self.__distinct_dates),\n                                       self.__class_num),\n                                      dtype=_np.float32)\n\n        self.__series_date_matrix = _np.empty((len(time_series_list),\n                                               len(self.__distinct_dates), 2),\n                                              dtype=_np.int32)\n        self.__data[:] = fill_na\n        self.__labels[:] = fill_na\n\n        # 根据日期序列的位置向张量填充数据\n        dates_positions = {date: index\n                           for index, date in enumerate(self.__distinct_dates)}\n        dates_position_mapper = _np.vectorize(lambda d: dates_positions[d])\n        for i, series in enumerate(time_series_list):\n            # 找到该序列series.dates日期在日期列表中的位置\n            # 将第i个序列填充至tensor的第i行\n            position_index = dates_position_mapper(series.dates)\n            self.__data[i, position_index, :] = series.data\n            if self.__class_num == 0:\n                self.__labels[i, position_index] = series.labels\n            else:\n                self.__labels[i, position_index, :] = series.labels\n            self.__series_date_matrix[i, position_index, 0] = series.dates\n            self.__series_date_matrix[i, position_index, 1] = i\n\n        self.__train_length = train_length\n        self.__validate_length = validate_length\n        self.__history_length = history_length\n        self.__sample_step = sample_step\n        self.__train_val_gap = train_val_gap\n        self.__normalize = normalize\n\n    def get(self,\n            start_date: int,\n            order=\"by_date\",\n            validate_only=False,\n            validate_length=None,\n            normalize=False):\n        \"\"\"获取从某天开始的训练集和验证集.\n\n        Notes:\n            根据设定的训练集天数以及验证集天数，从start_date开始获取正确的\n            训练集以及验证集，以及他们各自的日期范围信息(该信息以字典形式返回)。\n\n            需要注意:\n            训练集的的开始和结束是指其data, label时间范围并集，而\n            验证集的开始和结束则只是指其label的时间范围。\n            验证集的输入数据可以与训练集重叠，只要其标签数据的包含的时间范围\n            与训练集数据包含的时间范围没有交集即可。\n\n            具体时间信息参考函数返回的最后一个元素，是一个包含时间信息的``dict``。\n\n        Args:\n            start_date: 该轮训练开始日期，整数``YYYYMMDD``\n            order: 有三种顺序 ``shuffle``, ``by_date``, ``by_series``。\n                分别为随机打乱股票和时间，按时间顺序优先，按股票顺序优先，默认by_date。\n            validate_only: 如果设置为True，则只返回validate set\n                和训练集、验证集时间信息。可以用于训练后的分析。\n            validate_length (int): override class validate_length\n            normalize (bool): override class normalize\n\n        Returns:\n            如果``validate_only=False``，返回训练集、验证集、日期信息：\n            (train, val, dates_info(dict))。\n            如果为``True``，则返回验证集、日期信息。\n\n        Raises:\n            ValueError: 日期范围超出最大日期会报ValueError。\n\n        \"\"\"\n        if validate_length is not None:\n            if type(validate_length) is not int:\n                raise ValueError(\"`validate_length` must be an integer\")\n            if validate_length < 1:\n                raise ValueError(\"`validate_length` should be at least 1\")\n        else:\n            validate_length = self.__validate_length\n        if not normalize:\n            normalize = self.__normalize\n        return self.__get_in_memory__(start_date,\n                                      order,\n                                      validate_only,\n                                      validate_length,\n                                      normalize)\n\n    def __get_in_memory__(self,\n                          start_date,\n                          order=\"by_date\",\n                          validate_only=False,\n                          validate_length=None,\n                          normalize=False):\n        \"\"\"使用显存生成历史数据.\n\n        使用tensorflow from_tensor_slices，通过传递完整的tensor进行训练，\n        股票数量大时，需要较大内存\n\n        \"\"\"\n        # 获取用于构建训练集、验证集的相关信息\n        kwargs = {\"start_date\": start_date, \"order\": order}\n        if validate_length is not None:\n            kwargs.update({\"validate_length\": validate_length})\n        train_args, val_args, dates_info = self.__get_period_info__(**kwargs)\n        train_args = (*train_args, normalize)\n        val_args = (*val_args, normalize)\n        # 将输入的数据、标签片段转化为单个sample包含history日期长度的历史信息\n        (val_x,\n         val_y,\n         val_dates_series) = __full_tensor_generation__(*val_args)\n        # 转化为tensorflow DataSet\n        val = _tf.data.Dataset.from_tensor_slices((val_x, val_y))\n        val_dates_list = val_dates_series[:, 0].tolist()\n        val_series_list = val_dates_series[:, 1].tolist()\n        dates_info[\"validation\"][\"dates_list\"] = val_dates_list\n        dates_info[\"validation\"][\"series_list\"] = val_series_list\n\n        if validate_only:\n            return val, dates_info\n\n        (train_x,\n         train_y,\n         train_dates_series) = __full_tensor_generation__(*train_args)\n        train = _tf.data.Dataset.from_tensor_slices((train_x, train_y))\n        train_dates_list = train_dates_series[:, 0].tolist()\n        train_series_list = train_dates_series[:, 1].tolist()\n        dates_info[\"training\"][\"dates_list\"] = train_dates_list\n        dates_info[\"training\"][\"series_list\"] = train_series_list\n        return train, val, dates_info\n\n    def __get_period_info__(self, start_date, order=\"by_date\",\n                            validate_length=None):\n        \"\"\"根据开始时间计算用于构建训练集、验证集的相关信息.\"\"\"\n        if type(start_date) is not int:\n            raise ValueError(\"start date should be an integer YYYYMMDD\")\n\n        # 找到大于等于start_date的最小日期\n        after_start_date = self.__distinct_dates >= start_date\n        first_date = _np.min(self.__distinct_dates[after_start_date])\n\n        # 查看剩余日期数量是否大于等于训练集验证集总长度\n        if _np.sum(after_start_date) < (self.__train_length +\n                                        validate_length +\n                                        self.__train_val_gap):\n            raise ValueError(\"date range exceeded end of dates\")\n\n        # 计算各个时间节点在时间列表中的位置\n        # 训练集开始位置(data的开始位置)\n        train_start_index = __first_index__(self.__distinct_dates, first_date)\n        # 训练集结束位置(不包含)\n        train_end_index = train_start_index + self.__train_length\n        # 验证集开始位置(data的开始位置)\n        val_start_index = (train_end_index -\n                           self.__history_length +\n                           self.__train_val_gap + 1)\n        # 验证集结束位置(不包含)\n        val_end_index = (train_end_index +\n                         validate_length +\n                         self.__train_val_gap)\n\n        # 根据各个数据集的开始结束位置以及训练数据的顺序选项，获取构建数据的参数\n        train_args = self.__get_generator_args__(train_start_index,\n                                                 train_end_index,\n                                                 order=order)\n        val_args = self.__get_generator_args__(val_start_index,\n                                               val_end_index,\n                                               order=order)\n        dates_info = self.__dates_info__(train_start_index,\n                                         val_start_index,\n                                         train_args,\n                                         val_args)\n\n        return train_args, val_args, dates_info\n\n    def __get_generator_args__(self, start_index, end_index, order=\"by_date\"):\n        \"\"\"获取单个generator需要的数据片段.\n\n        Notes:\n            根据数据集的开始、结束位置以及的顺序选项，获取该训练集的数据、标签片段\n            以及用于生成训练数据的(序列, 日期)pair列表的顺序信息(generation_list)。\n\n            generation_list第一列为序列编号，第二列为日期。\n\n            generation_list中的日期数字代表*每个历史数据片段*的第一个日期相对\n            该数据集片段（start_index:end_index）的位置。\n\n            注意：\n\n                - 该处的日期列表不代表每个历史片段的结束位置\n\n                - 也不是相对TrainValData类日期列表的位置\n        \"\"\"\n        length = end_index - start_index\n        data = self.__data[:, start_index:end_index, :]\n        label = self.__labels[:, start_index:end_index]\n        dates_series = self.__series_date_matrix[:, start_index:end_index, :]\n        generation_list = [[series_i, t]\n                           for t in range(0,\n                                          length - self.__history_length + 1,\n                                          self.__sample_step)\n                           for series_i in range(len(data))]\n\n        if order == \"shuffle\":\n            generation_list = _np.array(generation_list, dtype=_np.int32)\n            _np.random.shuffle(generation_list)\n        elif order == \"by_date\":\n            generation_list = _np.array(generation_list, dtype=_np.int32)\n        elif order == \"by_series\":\n            generation_list = sorted(generation_list, key=lambda k: k[0])\n            generation_list = _np.array(generation_list, dtype=_np.int32)\n        else:\n            raise ValueError(\"wrong order argument, choose from `shuffle`, \"\n                             \"`by_date`, and `by_series`\")\n\n        history_length = self.__history_length\n\n        return data, label, generation_list, history_length, dates_series\n\n    def __dates_info__(self,\n                       train_start_index,\n                       val_start_index,\n                       train_args,\n                       val_args):\n        \"\"\"根据生成数据的列表，计算用于显示的日期信息.\"\"\"\n        # 获取generation_list(生成数据的顺序信息)的时间列\n        # 该时间列为相对数据片段开头的时间位置\n        train_generation_list = train_args[2]\n        val_generation_list = val_args[2]\n        train_time_index = train_generation_list[:, 1]\n        val_time_index = val_generation_list[:, 1]\n\n        # 加上片段的开始位置，得到相对TrainValData类日期列表的位置\n        train_time_index = train_time_index + train_start_index\n        val_time_index = val_time_index + val_start_index\n\n        # 训练集在日期列表中的开始位置\n        training_beginning = _np.min(train_time_index)\n\n        # 结束位置：加上历史长度减去一，获取最大日期位置(inclusive)\n        training_ending = _np.max(train_time_index)\n        training_ending += self.__history_length - 1\n\n        # validation集每次取的都是某历史片段末尾的数据\n        # 所以加上历史减去一\n        validation_index = val_time_index + self.__history_length - 1\n        validation_beginning = _np.min(validation_index)\n        validation_ending = _np.max(validation_index)\n\n        dates_info = {\n            \"training\": {\n                \"start_date\": int(self.__distinct_dates[training_beginning]),\n                \"end_date\": int(self.__distinct_dates[training_ending]),\n            },\n            \"validation\": {\n                \"start_date\": int(self.__distinct_dates[validation_beginning]),\n                \"end_date\": int(self.__distinct_dates[validation_ending]),\n            }\n        }\n        return dates_info\n\n\ndef __full_tensor_generation__(data,\n                               label,\n                               generation_list,\n                               history,\n                               dates_series,\n                               normalize):\n    \"\"\"将输入的数据、标签片段转化为单个sample包含history日期长度的历史信息.\"\"\"\n    # 先将该数据片段的历史维度展开\n\n    # 根据generation_list指定的series，日期，获取标签及数据片段\n    total_time_length = data.shape[1]\n    expanded = [__gather_2d__(data[:, i: (total_time_length + i\n                                          - history + 1), :], generation_list)\n                for i in range(history)]\n\n    # date_all dimensions: (series * dates, features, history)\n    data_all = _np.stack(expanded, axis=-1)\n    label_all = __gather_2d__(label[:, history - 1:], generation_list)\n    dates_series_all = __gather_2d__(dates_series[:, history - 1:],\n                                     generation_list)\n\n    # 去掉所有包含缺失数据的某股票某时间历史片段\n    label_nan = _np.isnan(label_all)\n    if _np.ndim(label_all) == 2:\n        # 如果是分类问题, 需要特殊处理\n        label_nan = _np.any(label_nan, axis=1)\n    data_nan = _np.isnan(data_all)\n    series_time_nan = _np.any(\n        _np.any(data_nan, axis=2),\n        axis=1\n    )\n    not_nan = _np.logical_not(_np.logical_or(series_time_nan, label_nan))\n\n    data_all = data_all[not_nan]\n    label_all = label_all[not_nan]\n    dates_series_all = dates_series_all[not_nan]\n\n    # max/min standardization for series greater than 1\n    if normalize:\n        max_val = _np.max(data_all, axis=-1, keepdims=True)\n        non_rate_mask = _np.less(1.0, _np.squeeze(max_val))\n        min_val = _np.min(data_all, axis=-1, keepdims=True)\n        with _np.errstate(divide='ignore', invalid='ignore'):\n            normalized = _np.nan_to_num((data_all - min_val)\n                                        / (max_val - min_val))\n        data_all[non_rate_mask] = normalized[non_rate_mask]\n\n    data_all = _np.transpose(data_all, axes=(0, 2, 1))\n    data_all = _tf.constant(data_all, dtype=_tf.float32)\n    label_all = _tf.constant(label_all, dtype=_tf.float32)\n\n    return data_all, label_all, dates_series_all\n\n\ndef __first_index__(array, element):\n    \"\"\"计算第一个出现的元素的位置.\"\"\"\n    return _np.min(_np.where(array == element))\n\n\n@njit\ndef __gather_2d__(array: _np.ndarray, generation_list: _np.ndarray):\n    out_shape = (len(generation_list), *array.shape[2:])\n    out_array = np.empty(shape=out_shape,\n                         dtype=array.dtype)\n    pointer = 0\n    for i, j in generation_list:\n        out_array[pointer] = array[i, j]\n        pointer += 1\n    return out_array\n", "meta": {"hexsha": "121c24c59f89ae83b0e82cc7ab09b4bd94690a4f", "size": 19147, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/alphanet/data.py", "max_stars_repo_name": "UtorYeung/AlphaNetV3", "max_stars_repo_head_hexsha": "807f36f1bb2405543db8015446d1ee470292d92a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 57, "max_stars_repo_stars_event_min_datetime": "2021-07-29T14:55:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T16:18:26.000Z", "max_issues_repo_path": "src/alphanet/data.py", "max_issues_repo_name": "UtorYeung/AlphaNetV3", "max_issues_repo_head_hexsha": "807f36f1bb2405543db8015446d1ee470292d92a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2021-08-05T05:24:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-22T13:26:41.000Z", "max_forks_repo_path": "src/alphanet/data.py", "max_forks_repo_name": "UtorYeung/AlphaNetV3", "max_forks_repo_head_hexsha": "807f36f1bb2405543db8015446d1ee470292d92a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 36, "max_forks_repo_forks_event_min_datetime": "2021-08-02T09:10:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T00:04:52.000Z", "avg_line_length": 37.8399209486, "max_line_length": 79, "alphanum_fraction": 0.5678696402, "include": true, "reason": "import numpy,from numba", "num_tokens": 5354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.1646505824218291}}
{"text": "\"\"\"\nrun MD, replica exchange (parallel tempering) and calcaulte energy using OpenMM\n\"\"\"\n\nfrom sys import stdout\n\nimport copy\n\nimport numpy as np\nimport netCDF4\n\nimport simtk.openmm\nimport simtk.openmm.app\nimport simtk.unit\n\nfrom rotation import random_rotation\n\nopenmm_solvent_models = {  \"OpenMM_Gas\":None,\n                            \"OpenMM_GBn\":simtk.openmm.app.GBn,\n                            \"OpenMM_GBn2\":simtk.openmm.app.GBn2,\n                            \"OpenMM_HCT\":simtk.openmm.app.HCT,\n                            \"OpenMM_OBC1\":simtk.openmm.app.OBC1,\n                            \"OpenMM_OBC2\":simtk.openmm.app.OBC2 }\n\n\nKB = 0.001987204134799235  # kcal/mol/K\n\n\nclass OpenMM_MD(object):\n    def __init__(self, prmtop, inpcrd, phase=\"OpenMM_Gas\", temperature=300.):\n        \"\"\"\n        \"\"\"\n        self._prmtop = simtk.openmm.app.AmberPrmtopFile(prmtop)\n        inpcrd = simtk.openmm.app.AmberInpcrdFile(inpcrd)\n        \n        selected_solvent = openmm_solvent_models[phase]\n        system = self._prmtop.createSystem(nonbondedMethod = simtk.openmm.app.NoCutoff, \\\n                constraints = simtk.openmm.app.HBonds, implicitSolvent = selected_solvent)\n        integrator = simtk.openmm.LangevinIntegrator(temperature*simtk.unit.kelvin, 1/simtk.unit.picosecond, 0.002*simtk.unit.picoseconds)\n        \n        self._simulation = simtk.openmm.app.Simulation(self._prmtop.topology, system, integrator)\n        self._simulation.context.setPositions(inpcrd.positions)\n        print(\"Energy minimizing\")\n        self._simulation.minimizeEnergy()\n\n    def _initialize_nc(self, nc_file_name, niterations):\n        nc_handle = netCDF4.Dataset(nc_file_name, mode=\"w\", format=\"NETCDF4\")\n        natoms = len( list( self._prmtop.topology.atoms() ) )\n\n        nc_handle.createDimension(\"three\", 3)\n        nc_handle.createDimension(\"natoms\", natoms)\n        nc_handle.createDimension(\"nconfs\", niterations)\n\n        nc_handle.createVariable(\"positions\", \"f8\", tuple([\"nconfs\", \"natoms\", \"three\"]))\n        return nc_handle\n    \n    def run(self, nc_file_name, steps_per_iteration=500, niterations=1000):\n        \"\"\"\n        \"\"\"\n        self._simulation.reporters.append(simtk.openmm.app.StateDataReporter(stdout, steps_per_iteration,\n                                            step=True, potentialEnergy=True))\n        \n        nc_handle = self._initialize_nc(nc_file_name, niterations)\n\n        for iteration in range(niterations):\n            self._simulation.step(steps_per_iteration)\n            state = self._simulation.context.getState(getPositions=True, getEnergy=True)\n            \n            positions = copy.deepcopy(state.getPositions())\n            conf = np.array(positions.value_in_unit(simtk.unit.angstrom), dtype=float)    \n            conf = random_rotation(conf)\n\n            nc_handle.variables[\"positions\"][iteration,:,:] = conf\n        nc_handle.close()\n\n        return None\n\n\nclass OpenMM_TREMD(object):\n    def __init__(self, prmtop, inpcrd, phase, temperatures):\n        \"\"\"\n        :param prmtop: str, name of AMBER prmtop file\n        :param inpcrd: str, name of AMBER coordinate file\n        :param phase: str\n        :param temperatures: list or ndarray of float\n        \"\"\"\n        self._temperatures = list(temperatures)\n        self._simulations  = self._create_simulations(prmtop, inpcrd, phase, temperatures)\n        self._acepted_exchange = np.zeros([len(self._temperatures)-1], dtype=float)\n        self._nr_attempts = np.zeros([len(self._temperatures)-1], dtype=float)\n        self._start = 0\n\n    def run(self, nc_file_name, steps_per_iteration, niterations, rotations_per_iteration):\n        \"\"\"\n        \"\"\"\n        nc_handle = self._initialize_nc(nc_file_name, niterations, rotations_per_iteration)\n\n        nrotations = 0\n        for iteration in range(niterations):\n\n            self._md_evolve(steps_per_iteration)\n\n            energies = self._get_potential_energies()\n            nc_handle.variables[\"energies\"][iteration, :] = np.array(energies, dtype=float)\n\n            positions = self._get_positions()\n            for state, p in enumerate(positions):\n                crd = np.array(p.value_in_unit(simtk.unit.angstrom), dtype=float)\n                nc_handle.variables[\"positions\"][iteration, state, :, :] = crd\n\n            crd = np.array(positions[0].value_in_unit(simtk.unit.angstrom), dtype=float)\n            for rotation in range(rotations_per_iteration):\n                rotated_crd = random_rotation(crd)\n                nc_handle.variables[\"rotated_positions\"][nrotations, :, :] = rotated_crd\n                nrotations += 1\n\n            self._exchange(self._start)\n            self._switch_start()\n\n            print(\"iteration \", iteration)\n            print(\"energies \", energies)\n\n        acceptance_rate = self._acepted_exchange / self._nr_attempts\n        nc_handle.variables[\"acceptance_rate\"][:] = acceptance_rate\n        nc_handle.close()\n        return None\n\n    def _switch_start(self):\n        if self._start == 0:\n            self._start = 1\n        elif self._start == 1:\n            self._start = 0\n        else:\n            raise RuntimeError(\"self._start is %d\"%self._start)\n        return\n\n    def _create_simulation(self, prmtop, inpcrd, phase, temperature):\n        prmtop = simtk.openmm.app.AmberPrmtopFile(prmtop)\n        inpcrd = simtk.openmm.app.AmberInpcrdFile(inpcrd)\n        selected_solvent = openmm_solvent_models[phase]\n\n        system = prmtop.createSystem(nonbondedMethod=simtk.openmm.app.NoCutoff, constraints=simtk.openmm.app.HBonds, implicitSolvent=selected_solvent)\n        integrator = simtk.openmm.LangevinIntegrator(temperature*simtk.unit.kelvin, 1/simtk.unit.picosecond, 0.002*simtk.unit.picoseconds)\n\n        simulation = simtk.openmm.app.Simulation(prmtop.topology, system, integrator)\n        simulation.context.setPositions(inpcrd.positions)\n        simulation.minimizeEnergy()\n        return simulation\n\n    def _create_simulations(self, prmtop, inpcrd, phase, temperatures):\n        simulations = []\n        for temperature in temperatures:\n            sim = self._create_simulation(prmtop, inpcrd, phase, temperature)\n            simulations.append(sim)\n        return simulations\n\n    def _md_evolve(self, steps):\n        for sim in self._simulations:\n            sim.step(steps)\n        return None\n\n    def _get_potential_energies(self):\n        energies = []\n        for sim in self._simulations:\n            state = sim.context.getState(getEnergy=True)\n            energy = copy.deepcopy(state.getPotentialEnergy())\n            e = energy.value_in_unit(simtk.unit.kilocalorie_per_mole)\n            energies.append(e)\n        return energies\n\n    def _get_positions(self):\n        positions = []\n        for sim in self._simulations:\n            state = sim.context.getState(getPositions=True)\n            pos = copy.deepcopy(state.getPositions())\n            positions.append(pos)\n        return positions\n\n    def _get_velocities(self):\n        velocities = []\n        for sim in self._simulations:\n            state = sim.context.getState(getVelocities=True)\n            vel = copy.deepcopy(state.getVelocities())\n            velocities.append(vel)\n        return velocities\n\n    def _metropolis_prob(self, T1, E1, T2, E2):\n        assert T1 > 0 and T2 > 0, \"T1 and T2 must be possitive\"\n        deltaE = ((1./T1 - 1./T2) / KB) * (E2 - E1)\n        return np.exp(-deltaE)\n\n    def _exchange(self, start):\n        assert start in [0, 1], \"start must be either 0 or 1\"\n        simulation_pairs = zip( self._simulations[start : -1 : 2], self._simulations[start+1 : : 2] )\n\n        energies = self._get_potential_energies()\n        energy_pairs = zip( energies[start : -1 : 2], energies[start+1 : : 2] )\n\n        temperature_pairs = zip( self._temperatures[start : -1 : 2], self._temperatures[start+1 : : 2] )\n\n        positions = self._get_positions()\n        position_pairs = zip( positions[start : -1 : 2], positions[start+1 : : 2] )\n\n        velocities = self._get_velocities()\n        velocity_pairs = zip( velocities[start : -1 : 2], velocities[start+1 : : 2] )\n\n        pair_indices = range(start, len(self._temperatures)-1, 2) \n\n        for i in range(len(simulation_pairs)):\n            E1 = energy_pairs[i][0]\n            E2 = energy_pairs[i][1]\n            T1 = temperature_pairs[i][0]\n            T2 = temperature_pairs[i][1]\n\n            x_prob = self._metropolis_prob(T1, E1, T2, E2)\n            if x_prob >= 1. or x_prob > np.random.random():\n                simulation_pairs[i][0].context.setPositions( position_pairs[i][1] )\n                simulation_pairs[i][1].context.setPositions( position_pairs[i][0] )\n\n                vel_unit = simtk.unit.nanometer/simtk.unit.picosecond\n\n                v1 = np.sqrt(T1 / T2 ) * np.array( velocity_pairs[i][1].value_in_unit(vel_unit) )\n                v2 = np.sqrt(T2 / T1 ) * np.array( velocity_pairs[i][0].value_in_unit(vel_unit) )\n\n                simulation_pairs[i][0].context.setVelocities( simtk.unit.quantity.Quantity(v1, unit=vel_unit) )\n                simulation_pairs[i][1].context.setVelocities( simtk.unit.quantity.Quantity(v2, unit=vel_unit) )\n\n                self._acepted_exchange[pair_indices[i]] += 1. \n\n            self._nr_attempts[pair_indices[i]] += 1.\n        return \n\n    def _initialize_nc(self, nc_file_name, niterations, rotations_per_iteration):\n        \"\"\"\n        \"\"\"\n        nc_handle = netCDF4.Dataset(nc_file_name, mode=\"w\", format=\"NETCDF4\")\n        natoms = len( list( self._simulations[0].topology.atoms() ) )\n\n        nc_handle.createDimension(\"three\", 3)\n        nc_handle.createDimension(\"natoms\", natoms)\n        nc_handle.createDimension(\"nstates\", len(self._simulations) )\n        nc_handle.createDimension(\"niterations\", niterations)\n        nc_handle.createDimension(\"nrotations\", niterations * rotations_per_iteration)\n        nc_handle.createDimension(\"npairs\", len(self._simulations) - 1)\n\n        nc_handle.createVariable(\"energies\", \"f8\", tuple([\"niterations\", \"nstates\"]) )\n        nc_handle.createVariable(\"positions\", \"f4\", tuple([\"niterations\", \"nstates\", \"natoms\", \"three\"]))\n        nc_handle.createVariable(\"rotated_positions\", \"f4\", tuple([\"nrotations\", \"natoms\", \"three\"]))\n        nc_handle.createVariable(\"acceptance_rate\", \"f8\", tuple([\"npairs\"]))\n        nc_handle.createVariable(\"temperatures\", \"f8\", tuple([\"nstates\"]))\n\n        nc_handle.variables[\"temperatures\"][:] = np.array(self._temperatures)\n        return nc_handle\n\n\ndef openmm_energy(prmtop_file, crd, phase):\n    \"\"\"\n    crd in angstroms\n    crd can be an inpcrd file name, a array with shape (natom, 3) or shape (nframe, natom, 3)\n    \"\"\"\n    implicit_solvents = openmm_solvent_models\n    selected_solvent = implicit_solvents[phase]\n    \n    if type(crd) == str:\n        inpcrd = simtk.openmm.app.AmberInpcrdFile(crd)\n        position = inpcrd.positions\n        crd = position.value_in_unit(simtk.unit.angstrom) \n    \n    crd_ensemble = np.array(crd, dtype=float)\n    if len(crd_ensemble.shape) == 2:\n        crd_ensemble = np.array([crd_ensemble], dtype=float)\n    \n    if len(crd_ensemble.shape) != 3:\n        raise RuntimeError(\"crd_ensemble has wrong shape\")\n    \n    prmtop = simtk.openmm.app.AmberPrmtopFile(prmtop_file)\n    system = prmtop.createSystem(nonbondedMethod=simtk.openmm.app.NoCutoff,\n                                 constraints=None, implicitSolvent=selected_solvent)\n    dummy_integrator = simtk.openmm.VerletIntegrator(0.002*simtk.unit.picoseconds)\n    simulation = simtk.openmm.app.Simulation(prmtop.topology, system, dummy_integrator)\n    \n    pot_energies = []\n    for conf in crd_ensemble:\n        simulation.context.setPositions(conf / 10.)  # convert to nano-meter which is internal unit of OpenMM\n        state = simulation.context.getState(getEnergy=True)\n        energy = state.getPotentialEnergy()\n        pot_energies.append(energy.value_in_unit(simtk.unit.kilocalorie_per_mole))\n    \n    return np.array(pot_energies, dtype=float)\n\n", "meta": {"hexsha": "291434758185788ec5d8a6004f43ac2375fa2ae6", "size": 11967, "ext": "py", "lang": "Python", "max_stars_repo_path": "bpmfwfft/md_openmm.py", "max_stars_repo_name": "jimtufts/bpmfwfft", "max_stars_repo_head_hexsha": "091d2269b122f00b9dd8a01e34303e3e946f8ea0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bpmfwfft/md_openmm.py", "max_issues_repo_name": "jimtufts/bpmfwfft", "max_issues_repo_head_hexsha": "091d2269b122f00b9dd8a01e34303e3e946f8ea0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bpmfwfft/md_openmm.py", "max_forks_repo_name": "jimtufts/bpmfwfft", "max_forks_repo_head_hexsha": "091d2269b122f00b9dd8a01e34303e3e946f8ea0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1237113402, "max_line_length": 150, "alphanum_fraction": 0.6442717473, "include": true, "reason": "import numpy", "num_tokens": 2967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3242353989809524, "lm_q1q2_score": 0.1646505824218291}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n###############################################################################\n#                                                                             #\n# RMG - Reaction Mechanism Generator                                          #\n#                                                                             #\n# Copyright (c) 2002-2019 Prof. William H. Green (whgreen@mit.edu),           #\n# Prof. Richard H. West (r.west@neu.edu) and the RMG Team (rmg_dev@mit.edu)   #\n#                                                                             #\n# Permission is hereby granted, free of charge, to any person obtaining a     #\n# copy of this software and associated documentation files (the 'Software'),  #\n# to deal in the Software without restriction, including without limitation   #\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,    #\n# and/or sell copies of the Software, and to permit persons to whom the       #\n# Software is furnished to do so, subject to the following conditions:        #\n#                                                                             #\n# The above copyright notice and this permission notice shall be included in  #\n# all copies or substantial portions of the Software.                         #\n#                                                                             #\n# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR  #\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,    #\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER      #\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING     #\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER         #\n# DEALINGS IN THE SOFTWARE.                                                   #\n#                                                                             #\n###############################################################################\n\n\"\"\"\nThis module contains the TransportData class for storing transport properties.\n\"\"\"\n\nimport numpy as np\n\nimport rmgpy.constants as constants\nfrom rmgpy import quantity\nfrom rmgpy.quantity import DipoleMoment, Energy, Length, Volume\nfrom rmgpy.rmgobject import RMGObject\n\n\nclass TransportData(RMGObject):\n    \"\"\"\n    A set of transport properties.\n    \n    The attributes are:\n    =================  ============================================================\n    Attribute          Description\n    =================  ============================================================\n    `shapeIndex`        0 for monoatomic, 1 for linear, 2 for nonlinear\n    `epsilon`           Lennard-Jones well depth\n    `sigma`             Lennard-Jones collision diameter\n    `dipoleMoment`      Dipole Moment\n    `polarizability`    Polarizability Volume\n    `rotrelaxcollnum`   Rotational relaxation number at 298 K, saved as a double.\n    =================  ============================================================\n    \n    \"\"\"\n\n    def __init__(self, shapeIndex=None, epsilon=None, sigma=None, dipoleMoment=None, polarizability=None,\n                 rotrelaxcollnum=None, comment=''):\n        self.shapeIndex = shapeIndex\n        try:\n            self.epsilon = Energy(epsilon)\n        except quantity.QuantityError:\n            self.epsilon = quantity.Temperature(epsilon)\n            self.epsilon.value_si *= constants.R\n            self.epsilon.units = 'kJ/mol'\n        self.sigma = Length(sigma)\n        self.dipoleMoment = DipoleMoment(dipoleMoment)\n        self.polarizability = Volume(polarizability)\n        self.rotrelaxcollnum = rotrelaxcollnum\n        self.comment = comment\n\n    def __repr__(self):\n        \"\"\"\n        Return a string representation that can be used to reconstruct the\n        TransportData object.\n        \"\"\"\n        attributes = []\n        if self.shapeIndex is not None:\n            attributes.append('shapeIndex={0!r}'.format(self.shapeIndex))\n        if self.epsilon is not None:\n            attributes.append('epsilon={0!r}'.format(self.epsilon))\n        if self.sigma is not None:\n            attributes.append('sigma={0!r}'.format(self.sigma))\n        if self.dipoleMoment is not None:\n            attributes.append('dipoleMoment={0!r}'.format(self.dipoleMoment))\n        if self.polarizability is not None:\n            attributes.append('polarizability={0!r}'.format(self.polarizability))\n        if self.rotrelaxcollnum is not None:\n            attributes.append('rotrelaxcollnum={0!r}'.format(self.rotrelaxcollnum))\n        if self.comment:\n            attributes.append('comment=\"\"\"{0!s}\"\"\"'.format(self.comment))\n        string = 'TransportData({0!s})'.format(', '.join(attributes))\n        return string\n\n    def __reduce__(self):\n        \"\"\"\n        A helper function used when picking a TransportData object.\n        \"\"\"\n        return (TransportData, (self.shapeIndex, self.epsilon, self.sigma, self.dipoleMoment,\n                                self.polarizability, self.rotrelaxcollnum, self.comment))\n\n    def get_collision_frequency(self, T, M, mu):\n        \"\"\"\n        Return the value of the Lennard-Jones collision frequency in Hz at the\n        given temperature `T` in K for colliders with the given concentration\n        `M` in mol/m^3 and reduced mass `mu` in amu.\n        \n        This seems to also exist in rmgpy.pdep.configuration.calculate_collision_frequency\n        Why the redundancy?\n        \"\"\"\n        sigma = self.sigma.value_si\n        epsilon = self.epsilon.value_si\n        M *= constants.Na  # mol/m^3 -> molecules/m^3\n        Tred = constants.R * T / epsilon\n        omega22 = 1.16145 * Tred ** (-0.14874) + 0.52487 * np.exp(-0.77320 * Tred) + 2.16178 * np.exp(-2.43787 * Tred)\n        mu *= constants.amu\n        return omega22 * np.sqrt(8 * constants.kB * T / constants.pi / mu) * constants.pi * sigma * sigma * M\n\n    def to_cantera(self):\n        \"\"\"\n        Returns a Cantera GasTransportData object.\n    \n        The Cantera usage is as follows:\n        \n        GasTransportData().set_customary_units(self, geometry, diameter, well_depth, dipole=0.0, polarizability=0.0, rotational_relaxation=0.0, acentric_factor=0.0)\n        Set the parameters using customary units: diameter in Angstroms, well depth in Kelvin, dipole in Debye, rotational relaxiation at 298 K, and polarizability in Angstroms^3. \n        These are the units used in in CK-style input files.\n        \"\"\"\n        import cantera as ct\n\n        ct_transport = ct.GasTransportData()\n\n        if self.shapeIndex == 0:\n            geometry = 'atom'\n        elif self.shapeIndex == 1:\n            geometry = 'linear'\n        elif self.shapeIndex == 2:\n            geometry = 'nonlinear'\n\n        # collision diameter in angstroms\n        diameter = self.sigma.value_si * 1e10\n        # Well depth in Kelvins\n        well_depth = self.epsilon.value_si / constants.R\n        # Dipole in debye\n        dipole = self.dipoleMoment.value_si * constants.c * 1e21 if self.dipoleMoment else 0.0\n        # polarizability in cubic angstroms\n        polarizability = self.polarizability.value_si * 1e30 if self.polarizability else 0.0\n        rotational_relaxation = self.rotrelaxcollnum if self.rotrelaxcollnum else 0.0\n        acentric_factor = 0.0\n\n        ct_transport.set_customary_units(geometry, diameter, well_depth, dipole, polarizability,\n                                         rotational_relaxation, acentric_factor)\n\n        return ct_transport\n", "meta": {"hexsha": "290bb5d72baf1ecfa6373393e372f73be848b20b", "size": 7616, "ext": "py", "lang": "Python", "max_stars_repo_path": "rmgpy/transport.py", "max_stars_repo_name": "mbprend/RMG-Py", "max_stars_repo_head_hexsha": "29e111d683f2daa0b376417be60e76b32ce8a993", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rmgpy/transport.py", "max_issues_repo_name": "mbprend/RMG-Py", "max_issues_repo_head_hexsha": "29e111d683f2daa0b376417be60e76b32ce8a993", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rmgpy/transport.py", "max_forks_repo_name": "mbprend/RMG-Py", "max_forks_repo_head_hexsha": "29e111d683f2daa0b376417be60e76b32ce8a993", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.8993710692, "max_line_length": 180, "alphanum_fraction": 0.5697216387, "include": true, "reason": "import numpy", "num_tokens": 1621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3242353859211693, "lm_q1q2_score": 0.1646505757899163}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n# CODE NAME HERE\n\n# CODE DESCRIPTION HERE\n\nCreated on 2020-05-07\n\n@author: cook\n\"\"\"\nfrom astropy.io import fits\nfrom astropy.table import Table\nfrom astropy import units as uu\nfrom astropy.time import Time\nimport numpy as np\nimport sys\nimport os\nimport argparse\nfrom scipy.interpolate import InterpolatedUnivariateSpline\nimport matplotlib.pyplot as plt\nimport itertools\n\n\n# =============================================================================\n# Define variables\n# =============================================================================\n__VERSION__ = '0.2.000'\n__DATE__ = '2020-05-07'\n# constants\nSPEED_OF_LIGHT = 299792.458  # [km/s]\nIMAGE_PIXEL_SIZE = 2.28  # IMAGE_PIXEL_SIZE\n\n\n# =============================================================================\n# Argument functions\n# =============================================================================\nclass Arguments:\n    def __init__(self, rawargs):\n        self.version = __VERSION__\n        self.date = __DATE__\n        # static\n        self.CASE = 1\n        self.OUTDIR = '.'\n        self.PLOT = True\n        self.DEBUG = False\n        self.kernelparams = None\n        # can be dynamic\n        self.KERNEL = None\n        self.KERNEL_WIDTH = None\n        self.KERNEL_EWIDTH = None\n        self.KERNEL_BETA = None\n        self.IN_FILE = None\n        self.BLAZE_FILE = None\n        self.WAVE_FILE = None\n        self.MASK_FILE = None\n        self.MASK_WIDTH = None\n        self.MASK_MIN_WEIGHT = None\n        self.CCF_STEP = None\n        self.CCF_WIDTH = None\n        self.CCF_RV_NULL = None\n        self.IN_RV = None\n        self.CCF_N_ORD_MAX = None\n        self.BLAZE_NORM_PERCENTILE = None\n        self.BLAZE_THRESHOLD = None\n        self.NOISE_SIGDET = None\n        self.NOISE_SIZE = None\n        self.NOISE_THRES = None\n        # get raw args\n        self.rawargs = rawargs[1:]\n        self.cmdargs = None\n        # deal with version argument\n        if '--version' in self.rawargs:\n            print('Version={0} ({1})'.format(__VERSION__, __DATE__))\n            sys.exit(1)\n        # do we get arguments from args?\n        if len(self.rawargs) > 0:\n            self.parseargs()\n\n    def cmdkeys(self):\n        keys = dict()\n        keys['KERNEL'] = '--kernel={0} '\n        keys['KERNEL_WIDTH'] = '--kernelwid={0} '\n        keys['KERNEL_EWIDTH'] = '--kernelewid={0} '\n        keys['KERNEL_BETA'] = '--kernelbeta={0} '\n        keys['IN_FILE'] = '--infile={0} '\n        keys['BLAZE_FILE'] = '--blaze={0} '\n        keys['WAVE_FILE'] = '--wave={0} '\n        keys['MASK_WIDTH'] = '--maskwidth={0} '\n        keys['MASK_MIN_WEIGHT'] = '--maskminweight={0} '\n        keys['CCF_STEP'] = '--ccfstep={0} '\n        keys['CCF_WIDTH'] = '--ccfwidth={0} '\n        keys['CCF_RV_NULL'] = '--ccf_rv_null={0} '\n        keys['IN_RV'] = '--targetrv={0} '\n        keys['CCF_N_ORD_MAX'] = '--ccf_ord_max={0} '\n        keys['BLAZE_NORM_PERCENTILE'] = '--blazenormper={0} '\n        keys['BLAZE_THRESHOLD'] = '--blaze_thres={0} '\n        keys['NOISE_SIGDET'] = '--noise_sigdet={0} '\n        keys['NOISE_SIZE'] = '--noise_size={0} '\n        keys['NOISE_THRES'] = '--noise_thres={0} '\n        return keys\n\n\n    def parseargs(self):\n        # get parser\n        desc = ('Stand alone CCF code from the DRS. Version {0}. '\n                'Note any arguments left out will default to the default '\n                'defined in the --case argument '\n                '(if left out this defaults to --case=1)')\n        parser = argparse.ArgumentParser(description=desc.format(self.version))\n\n        parser.add_argument('--case', action='store', default=self.CASE,\n                            dest='CASE', choices=[1, 2], required=True,\n                            type=int,\n                            help='The case to use for all undefined keywords. '\n                                 'case=1   default setup for datatype=OBJ. '\n                                 'case=2   default setup for datatype=FP')\n        parser.add_argument('--plot', action='store_true', default=self.PLOT,\n                            dest='PLOT', help='If set plots graphics')\n        parser.add_argument('--debug', action='store_true', default=False,\n                            dest='DEBUG', help='Debug mode')\n        parser.add_argument('--outdir', action='store', default=self.OUTDIR,\n                            dest='OUTDIR',\n                            help='Output path for files (absolute path) if'\n                                 'blank uses the input file directory.')\n        parser.add_argument('--kernel', action='store', default=self.KERNEL,\n                            dest='KERNEL',\n                            choices=['None', 'boxcar', 'gaussian',\n                                     'supergaussian'],\n                            help='Kernal name. '\n                                 'If boxcar must define --kernelwid '\n                                 'If gaussian must define --kernelewid '\n                                 'If supergaussian must define '\n                                 '--kernelewid --kernelbeta.')\n        parser.add_argument('--kernelwid', action='store',\n                            default=self.KERNEL_WIDTH, dest='KERNEL_WIDTH',\n                            help='The kernel width if --kernel=boxcar')\n        parser.add_argument('--kernelewid', action='store',\n                            default=self.KERNEL_EWIDTH, dest='KERNEL_EWIDTH',\n                            help='The kernel e-width if --kernel=gaussian or'\n                                 '--kernel=supergaussian')\n        parser.add_argument('--kernelbeta', action='store',\n                            default=self.KERNEL_BETA, dest='KERNEL_BETA',\n                            help='The kernel beta value if '\n                                 '--kernel=supergaussian')\n        parser.add_argument('--infile', action='store',\n                            default=self.IN_FILE, dest='IN_FILE',\n                            help='The input e2dsff file (absolute path)')\n        parser.add_argument('--blaze', action='store',\n                            default=self.BLAZE_FILE, dest='BLAZE_FILE',\n                            help='The input blaze file (absolute path)')\n        parser.add_argument('--wave', action='store',\n                            default=self.WAVE_FILE, dest='WAVE_FILE',\n                            help='The input wave solution (absolute path)'\n                                 'if one wishes to use the header set this to'\n                                 '\"None\" or \"header\" i.e. --wave=\"None\" or'\n                                 ' --wave=\"header\"')\n        parser.add_argument('--mask', action='store', default=self.MASK_FILE,\n                            dest='MASK_FILE',\n                            help='The ccf mask file to use (absolute path)')\n        parser.add_argument('--maskwidth', action='store', type=float,\n                            default=self.MASK_WIDTH, dest='MASK_WIDTH',\n                            help='The size of the mask lines to use')\n        parser.add_argument('--maskminweight', action='store', type=float,\n                            default=self.MASK_MIN_WEIGHT,\n                            dest='MASK_MIN_WEIGHT',\n                            help='The minimum line weighting to use. If set to'\n                                 '1 forces all weights to be equal')\n        parser.add_argument('--ccfstep', action='store', default=self.CCF_STEP,\n                            dest='CCF_STEP', type=float,\n                            help='CCF step size [km/s]')\n        parser.add_argument('--ccfwidth', action='store',\n                            default=self.CCF_WIDTH, dest='CCF_WIDTH',\n                            help='CCF step width [km/s]')\n        parser.add_argument('--ccf_rv_null', action='store',\n                            default=self.CCF_RV_NULL, dest='CCF_RV_NULL',\n                            help='The largest absolute RV value to accept from '\n                                 'header. Above or below this values are '\n                                 'rejected')\n        parser.add_argument('--targetrv', action='store',\n                            default=self.IN_RV, dest='IN_RV',\n                            help='The input target RV [km/s]')\n        parser.add_argument('--ccf_ord_max', action='store',\n                            default=self.CCF_N_ORD_MAX, dest='CCF_N_ORD_MAX',\n                            help='The reddest order to use (bluest = 0)')\n        parser.add_argument('--blazenormper', action='store',\n                            default=self.BLAZE_NORM_PERCENTILE,\n                            dest='BLAZE_NORM_PERCENTILE',\n                            help='The blaze percentile to normalise by [0-100]')\n        parser.add_argument('--blaze_thres', action='store',\n                            default=self.BLAZE_THRESHOLD,\n                            dest='BLAZE_THRESHOLD',\n                            help='The blaze threshold to cut at '\n                                 '(below this blaze level flux is ignored)')\n        parser.add_argument('--noise_sigdet', action='store',\n                            default=self.NOISE_SIGDET, dest='NOISE_SIGDET',\n                            help='The noise level used to calculate dv rms '\n                                 'and ccf snr')\n        parser.add_argument('--noise_size', action='store',\n                            default=self.NOISE_SIZE, dest='NOISE_SIZE',\n                            help='The size around saturated pixels to flag as '\n                                 'unusable for dv rms')\n        parser.add_argument('--noise_thres', action='store',\n                            default=self.NOISE_THRES, dest='NOISE_THRES',\n                            help='The maximum flux for a good unsaturated pixel'\n                                 'for dv rms')\n\n        # parse arguments\n        self.cmdargs = parser.parse_args()\n        # update case (as other parameters are defined by default from this)\n        if self.cmdargs.CASE is not None:\n            self.CASE = self.cmdargs.CASE\n\n    def args_from_cmd(self):\n        \"\"\"\n        Push commands from arguments into constants in self\n        i.e. access through Argument.VARIABLE\n\n        :return:\n        \"\"\"\n        if self.cmdargs is None:\n            return\n        # update self with args\n        for key in self.__dict__:\n            if hasattr(self.cmdargs, key):\n                argval = getattr(self.cmdargs, key)\n                if argval is not None:\n                    setattr(self, key, argval)\n\n    def kernel_args(self):\n        # get the kernel name\n        name = self.KERNEL.lower()\n        # deal with kernel cases\n        if name in [None, 'None', '']:\n            self.kernelparams = None\n        elif 'box' in name:\n            # get the width\n            width = self.KERNEL_WIDTH\n            if width is None:\n                raise ValueError('ERROR: kernel width must be set')\n            try:\n                width = float(width)\n            except:\n                raise ValueError('ERROR: kernel width must be a valid float')\n            # set kernel params\n            self.kernelparams = ['boxcar', width]\n        elif ('gauss' in name) and ('super' not in name):\n            # get the e-width\n            ewidth = self.KERNEL_EWIDTH\n            if ewidth is None:\n                raise ValueError('ERROR: kernel e-width must be set')\n            try:\n                ewidth = float(ewidth)\n            except:\n                raise ValueError('ERROR: kernel e-width must be a valid float')\n            # set kernel params\n            self.kernelparams = ['gaussian', ewidth]\n        elif ('gauss' in name):\n            # get the e-width\n            ewidth = self.KERNEL_EWIDTH\n            if ewidth is None:\n                raise ValueError('ERROR: kernel e-width must be set')\n            try:\n                ewidth = float(ewidth)\n            except:\n                raise ValueError('ERROR: kernel e-width must be a valid float')\n            # get the beta value\n            beta = self.KERNEL_BETA\n            if beta is None:\n                raise ValueError('ERROR: kernel beta must be set')\n            try:\n                beta = float(beta)\n            except:\n                raise ValueError('ERROR: kernel beta must be a valid float')\n            # set kernel params\n            self.kernelparams = ['supergaussian', ewidth, beta]\n        else:\n            self.kernelparams = None\n\n\ndef get_combinations(names, variables, newdirs, outdir):\n    combinations = []\n    # generate time string\n    timestr = Time.now().iso.replace(' ', '_')\n    # get all combinations\n    combs = list(itertools.product(*variables))\n    # loop around combinations and create combination\n    for c_it, comb in enumerate(combs):\n        cargs = [c_it, comb, names, newdirs, len(combs), outdir, timestr]\n        combinations.append(Combination(*cargs))\n    # return all combination instances\n    return combinations\n\n\nclass Combination:\n    def __init__(self, number, variables, names, newdirs, total, outpath,\n                 timestr):\n        # get some stats (for ease of use)\n        self.number = number\n        self.total = total\n        # get output directory\n        self.outdir = str(timestr)\n        # setup parameter dictionary\n        self.parameters = dict()\n        # append parameters and outdir\n        for n_it, name in enumerate(names):\n            value = variables[n_it]\n            self.parameters[name] = value\n            # deal with paths\n            if os.sep in value:\n                strvalue = os.path.basename(value)\n                strvalue.split('.')[0]\n            # add to the outdir\n            if newdirs[n_it]:\n                self.outdir += '_{0}={1}'.format(name, strvalue)\n        # set output dir\n        self.outpath = os.path.join(outpath, self.outdir)\n        # need to make the directory\n        if not os.path.exists(self.outpath):\n            print('Creating directory {0}'.format(self.outpath))\n            os.mkdir(self.outpath)\n\n\n# =============================================================================\n# Reading functions\n# =============================================================================\ndef read_mask(mask_file, mask_cols):\n    table = Table.read(mask_file, format='ascii')\n    # get column names\n    oldcols = list(table.colnames)\n    # rename columns\n    for c_it, col in enumerate(mask_cols):\n        table[oldcols[c_it]].name = col\n    # return table\n    return table\n\n\ndef read_wave(image, iheader, wavefile):\n    if wavefile not in [None, 'None', '', 'False', False, 'header']:\n        # load the wave file and return it\n        wavemap, waveheader = fits.getdata(wavefile, header=True)\n        # return the wave map and the wave header\n        return wavemap, waveheader, wavefile\n    else:\n        # get image dimensions\n        nbo, nbx = image.shape\n        deg = iheader['WAVEDEGN']\n        # populate the wave coefficients\n        wave_coeffs = np.zeros((nbo, deg + 1))\n        for it in range(nbo):\n            for jt in range(deg + 1):\n                kt = it * (deg + 1 + jt)\n                wave_coeffs[it][jt] = iheader['WAVE{0:04d}'.format(kt)]\n        # set up storage\n        wavemap = np.zeros((nbo, nbx))\n        xpixels = np.arange(nbx)\n        # loop aroun each order and make the wave map\n        for order_num in range(nbo):\n            # get this order coefficients\n            ocoeffs = wave_coeffs[order_num][::-1]\n            # calculate polynomial values and push into wavemap\n            wavemap[order_num] = np.polyval(ocoeffs, xpixels)\n        # get wave keys from header\n        waveheader = fits.Header()\n        waveheader['MJDMID'] = iheader['WAVETIME']\n        # return the wave map and the wave header\n        return wavemap, waveheader, iheader['WAVEFILE']\n\n\ndef get_mask(table, mask_width, mask_min, mask_units='nm'):\n    ll_mask_e = np.array(table['ll_mask_e']).astype(float)\n    ll_mask_s = np.array(table['ll_mask_s']).astype(float)\n    ll_mask_d = ll_mask_e - ll_mask_s\n    ll_mask_ctr = ll_mask_s + ll_mask_d * 0.5\n    # if mask_width > 0 ll_mask_d is multiplied by mask_width/c\n    if mask_width > 0:\n        ll_mask_d = mask_width * ll_mask_s / SPEED_OF_LIGHT\n    # make w_mask an array\n    w_mask = np.array(table['w_mask']).astype(float)\n    # use w_min to select on w_mask or keep all if w_mask_min >= 1\n    if mask_min < 1.0:\n        mask = w_mask > mask_min\n        ll_mask_d = ll_mask_d[mask]\n        ll_mask_ctr = ll_mask_ctr[mask]\n        w_mask = w_mask[mask]\n    # else set all w_mask to one (and use all lines in file)\n    else:\n        w_mask = np.ones(len(ll_mask_d))\n    # ----------------------------------------------------------------------\n    # deal with the units of ll_mask_d and ll_mask_ctr\n    # must be returned in nanometers\n    # ----------------------------------------------------------------------\n    # get unit object from mask units string\n    unit = getattr(uu, mask_units)\n    # add units\n    ll_mask_d = ll_mask_d * unit\n    ll_mask_ctr = ll_mask_ctr * unit\n    # convert to nanometers\n    ll_mask_d = ll_mask_d.to(uu.nm).value\n    ll_mask_ctr = ll_mask_ctr.to(uu.nm).value\n    # ----------------------------------------------------------------------\n    # return the size of each pixel, the central point of each pixel\n    #    and the weight mask\n    return ll_mask_d, ll_mask_ctr, w_mask\n\n\n# =============================================================================\n# Math functions\n# =============================================================================\ndef relativistic_waveshift(dv, units='km/s'):\n    \"\"\"\n    Relativistic offset in wavelength\n\n    default is dv in km/s\n\n    :param dv: float or numpy array, the dv values\n    :param units: string or astropy units, the units of dv\n    :return:\n    \"\"\"\n    # get c in correct units\n    # noinspection PyUnresolvedReferences\n    if units == 'km/s' or units == uu.km / uu.s:\n        c = SPEED_OF_LIGHT\n    # noinspection PyUnresolvedReferences\n    elif units == 'm/s' or units == uu.m / uu.s:\n        c = SPEED_OF_LIGHT * 1000\n    else:\n        raise ValueError(\"Wrong units for dv ({0})\".format(units))\n    # work out correction\n    corrv = np.sqrt((1 + dv / c) / (1 - dv / c))\n    # return correction\n    return corrv\n\n\ndef iuv_spline(x, y, **kwargs):\n    # copy x and y\n    x, y = np.array(x), np.array(y)\n    # find all NaN values\n    nanmask = ~np.isfinite(y)\n\n    if np.sum(~nanmask) < 2:\n        y = np.zeros_like(x)\n    elif np.sum(nanmask) == 0:\n        pass\n    else:\n        # replace all NaN's with linear interpolation\n        badspline = InterpolatedUnivariateSpline(x[~nanmask], y[~nanmask],\n                                                 k=1, ext=1)\n        y[nanmask] = badspline(x[nanmask])\n    # return spline\n    return InterpolatedUnivariateSpline(x, y, **kwargs)\n\n\ndef gauss_function(x, a, x0, sigma, dc):\n    \"\"\"\n    A standard 1D gaussian function (for fitting against)]=\n\n    :param x: numpy array (1D), the x data points\n    :param a: float, the amplitude\n    :param x0: float, the mean of the gaussian\n    :param sigma: float, the standard deviation (FWHM) of the gaussian\n    :param dc: float, the constant level below the gaussian\n\n    :return gauss: numpy array (1D), size = len(x), the output gaussian\n    \"\"\"\n    return a * np.exp(-0.5 * ((x - x0) / sigma) ** 2) + dc\n\n\ndef fwhm(sigma=1.0):\n    \"\"\"\n    Get the Full-width-half-maximum value from the sigma value (~2.3548)\n\n    :param sigma: float, the sigma, default value is 1.0 (normalised gaussian)\n    :return: 2 * sqrt(2 * log(2)) * sigma = 2.3548200450309493 * sigma\n    \"\"\"\n    return 2 * np.sqrt(2 * np.log(2)) * sigma\n\n\n# =============================================================================\n# Plot functions\n# =============================================================================\ndef plotloop(looplist):\n    # check that looplist is a valid list\n    if not isinstance(looplist, list):\n        # noinspection PyBroadException\n        try:\n            looplist = list(looplist)\n        except Exception as _:\n            print('PLOT ERROR: looplist must be a list')\n    # define message to give to user\n    message = ('Plot loop navigation: Go to \\n\\t [P]revious plot '\n               '\\n\\t [N]ext plot \\n\\t [E]nd plotting '\n               '\\n\\t Number from [0 to {0}]: \\t')\n    message = message.format(len(looplist) - 1)\n    # start the iterator at zero\n    it = 0\n    first = True\n    # loop around until we hit the length of the loop list\n    while it < len(looplist):\n        # deal with end of looplist\n        if it == len(looplist):\n            # break out of while\n            break\n        # if this is the first iteration do not print message\n        if first:\n            # yield the first iteration value\n            yield looplist[it]\n            # increase the iterator value\n            it += 1\n            first = False\n        # else we need to ask to go to previous, next or end\n        else:\n            # get user input\n            userinput = input(message)\n            # try to cast into a integer\n            # noinspection PyBroadException\n            try:\n                userinput = int(userinput)\n            except Exception as _:\n                userinput = str(userinput)\n            # if 'p' in user input we assume they want to go to previous\n            if 'P' in str(userinput).upper():\n                yield looplist[it - 1]\n                it -= 1\n            # if 'n' in user input we assume they want to go to next\n            elif 'N' in str(userinput).upper():\n                yield looplist[it + 1]\n                it += 1\n            elif isinstance(userinput, int):\n                it = userinput\n                # deal with it too low\n                if it < 0:\n                    it = 0\n                # deal with it too large\n                elif it >= len(looplist):\n                    it = len(looplist) - 1\n                # yield the value of it\n                yield looplist[it]\n            # else we assume the loop is over and we want to exit\n            else:\n                # break out of while\n                break\n\n\ndef plot_individual_ccf(props, nbo):\n    # get the plot loop generator\n    generator = plotloop(range(nbo))\n    # loop around orders\n    for order_num in generator:\n        plt.close()\n        fig, frame = plt.subplots(ncols=1, nrows=1)\n        frame.plot(props['RV_CCF'], props['CCF'][order_num], color='b',\n                   marker='+', ls='None', label='data')\n        frame.plot(props['RV_CCF'], props['CCF_FIT'][order_num], color='r', )\n        rvorder = props['CCF_FIT_COEFFS'][order_num][1]\n        frame.set(title='Order {0}  RV = {1} km/s'.format(order_num, rvorder),\n                  xlabel='RV [km/s]', ylabel='CCF')\n        plt.show()\n        plt.close()\n\n\ndef plot_mean_ccf(props):\n    plt.close()\n    fig, frame = plt.subplots(ncols=1, nrows=1)\n    frame.plot(props['RV_CCF'], props['MEAN_CCF'], color='b', marker='+',\n               ls='None')\n    frame.plot(props['RV_CCF'], props['MEAN_CCF_FIT'], color='r')\n    frame.set(title='Mean CCF   RV = {0} km/s'.format(props['MEAN_RV']),\n              xlabel='RV [km/s]', ylabel='CCF')\n    plt.show()\n    plt.close()\n\n\n# =============================================================================\n# Writing functions\n# =============================================================================\ndef write_file(props, infile, maskname, header, wheader, wave_file,\n               outpath=None):\n    # ----------------------------------------------------------------------\n    # construct out file name\n    inbasename = os.path.basename(infile).split('.')[0]\n    maskbasename = os.path.basename(maskname).split('.')[0]\n    inpath = os.path.dirname(infile)\n    outfile = 'CCFTABLE_{0}_{1}.fits'.format(inbasename, maskbasename)\n    # deal with no outpath\n    if outpath is None:\n        outpath = os.path.join(inpath, outfile)\n    # ----------------------------------------------------------------------\n    # produce CCF table\n    table1 = Table()\n    table1['RV'] = props['RV_CCF']\n    for order_num in range(len(props['CCF'])):\n        table1['ORDER{0:02d}'.format(order_num)] = props['CCF'][order_num]\n    table1['COMBINED'] = props['MEAN_CCF']\n    # ----------------------------------------------------------------------\n    # produce stats table\n    table2 = Table()\n    table2['ORDERS'] = np.arange(len(props['CCF'])).astype(int)\n    table2['NLINES'] = props['CCF_LINES']\n    # get the coefficients\n    coeffs = props['CCF_FIT_COEFFS']\n    table2['CONTRAST'] = np.abs(100 * coeffs[:, 0])\n    table2['RV'] = coeffs[:, 1]\n    table2['FWHM'] = coeffs[:, 2]\n    table2['DC'] = coeffs[:, 3]\n    table2['SNR'] = props['CCF_SNR']\n    table2['NORM'] = props['CCF_NORM']\n\n    # ----------------------------------------------------------------------\n    # add to the header\n    # ----------------------------------------------------------------------\n    # add results from the CCF\n    header['CCFMNRV'] = (props['MEAN_RV'],\n                         'Mean RV calc. from the mean CCF [km/s]')\n    header['CCFMCONT'] = (props['MEAN_CONTRAST'],\n                          'Mean contrast (depth of fit) from mean CCF')\n    header['CCFMFWHM'] = (props['MEAN_FWHM'],\n                          'Mean FWHM from mean CCF')\n    header['CCFMRVNS'] = (props['MEAN_RV_NOISE'],\n                          'Mean RV Noise from mean CCF')\n    header['CCFTLINE'] = (props['TOT_LINE'],\n                          'Total no. of mask lines used in CCF')\n    # ----------------------------------------------------------------------\n    # add constants used to process\n    header['CCFMASK'] = (props['CCF_MASK'], 'CCF mask file used')\n    header['CCFSTEP'] = (props['CCF_STEP'], 'CCF step used [km/s]')\n    header['CCFWIDTH'] = (props['CCF_WIDTH'], 'CCF width used [km/s]')\n    header['CCFTRGRV'] = (props['TARGET_RV'],\n                          'CCF central RV used in CCF [km/s]')\n    header['CCFSIGDT'] = (props['CCF_SIGDET'],\n                          'Read noise used in photon noise calc. in CCF')\n    header['CCFBOXSZ'] = (props['CCF_BOXSIZE'],\n                          'Size of bad px used in photon noise calc. in CCF')\n    header['CCFMAXFX'] = (props['CCF_MAXFLUX'],\n                          'Flux thres for bad px in photon noise calc. in CCF')\n    header['CCFORDMX'] = (props['CCF_NMAX'],\n                          'Last order used in mean for mean CCF')\n    header['CCFMSKMN'] = (props['MASK_MIN'],\n                          'Minimum weight of lines used in the CCF mask')\n    header['CCFMSKWD'] = (props['MASK_WIDTH'],\n                          'Width of lines used in the CCF mask')\n    header['CCFMUNIT'] = (props['MASK_UNITS'], 'Units used in CCF Mask')\n    # ----------------------------------------------------------------------\n    header['RV_WAVFN'] = (os.path.basename(wave_file), 'RV wave file used')\n    header['RV_WAVTM'] = (wheader['MJDMID'],\n                          'RV wave file time [mjd]')\n    header['RV_WAVTD'] = (header['MJDMID'] - wheader['MJDMID'],\n                          'RV timediff [days] btwn file and wave solution')\n    header['RV_WAVFP'] = ('None', 'RV measured from wave sol FP CCF [km/s]')\n    header['RV_SIMFP'] = ('None', 'RV measured from simultaneous FP CCF [km/s]')\n    header['RV_DRIFT'] = ('None',\n                          'RV drift between wave sol and sim. FP CCF [km/s]')\n    header['RV_OBJ'] = (props['MEAN_RV'],\n                        'RV calc in the object CCF (non corr.) [km/s]')\n    header['RV_CORR'] = ('None', 'RV corrected for FP CCF drift [km/s]')\n    # ----------------------------------------------------------------------\n    # log where we are writing the file to\n    print('Writing file to {0}'.format(outpath))\n    # construct hdus\n    hdu = fits.PrimaryHDU()\n    t1 = fits.BinTableHDU(table1, header=header)\n    t2 = fits.BinTableHDU(table2, header=header)\n    # construct hdu list\n    hdulist = fits.HDUList([hdu, t1, t2])\n    # write hdulist\n    hdulist.writeto(outpath, overwrite=True)\n", "meta": {"hexsha": "3e9641af7f8f9b93b1c0f25624ab56158e8f67ba", "size": 28126, "ext": "py", "lang": "Python", "max_stars_repo_path": "general/apero-drs/problems/apero_rv/arv_util.py", "max_stars_repo_name": "njcuk9999/apero-utils", "max_stars_repo_head_hexsha": "f77de4c9123874e5bb6ed6bd03a7de3b27057402", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-08T17:03:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T17:49:44.000Z", "max_issues_repo_path": "misc/problems/apero_rv/arv_util.py", "max_issues_repo_name": "njcuk9999/apero-drs", "max_issues_repo_head_hexsha": "83b043e9f277a011b03e0227c77307961b200901", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 43, "max_issues_repo_issues_event_min_datetime": "2020-10-06T18:42:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T21:23:10.000Z", "max_forks_repo_path": "misc/problems/apero_rv/arv_util.py", "max_forks_repo_name": "njcuk9999/apero-drs", "max_forks_repo_head_hexsha": "83b043e9f277a011b03e0227c77307961b200901", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-04-10T06:41:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-16T21:09:14.000Z", "avg_line_length": 42.167916042, "max_line_length": 80, "alphanum_fraction": 0.5153238996, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 6426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.30735801052067535, "lm_q1q2_score": 0.1644667884554149}}
{"text": "from __future__ import print_function\n\nimport numpy as np\n\nfrom astropy import units as u\nfrom glue.external import six\nfrom astropy.io.fits import PrimaryHDU, ImageHDU, Header\n\nfrom .utils.wcs_utils import get_spatial_scale, sanitize_wcs\nfrom .geometry import extract_slice\nfrom .geometry import path as paths\nfrom .utils.wcs_slicing import slice_wcs\n\n\ndef extract_pv_slice(cube, path, wcs=None, spacing=1.0, order=3,\n                     respect_nan=True):\n    \"\"\"\n    Given a position-position-velocity cube with dimensions (nv, ny, nx), and\n    a path, extract a position-velocity slice.\n\n    Alternative implementations:\n        gipsy::sliceview\n        karma::kpvslice\n        casaviewer::slice\n\n    Parameters\n    ----------\n    cube : :class:`~numpy.ndarray` or :class:`~spectral_cube.SpectralCube` or str or HDU\n        The cube to extract a slice from. If this is a plain\n        :class:`~numpy.ndarray` instance, the WCS information can optionally\n        be specified with the ``wcs`` parameter. If a string, it should be\n        the name of a file containing a spectral cube.\n    path : `Path` or list of 2-tuples\n        The path along which to define the position-velocity slice. The path\n        can contain coordinates defined in pixel or world coordinates.\n    wcs : :class:`~astropy.wcs.WCS`, optional\n        The WCS information to use for the cube. This should only be\n        specified if the ``cube`` parameter is a plain\n        :class:`~numpy.ndarray` instance.\n    spacing : float\n        The position resolution in the final position-velocity slice. This\n        can be given in pixel coordinates or as a\n        :class:`~astropy.units.Quantity` instance with angle units.\n    order : int, optional\n        Spline interpolation order when using paths with zero width. Does not\n        have any effect for paths with a non-zero width.\n    respect_nan : bool, optional\n        If set to `False`, NaN values are changed to zero before computing\n        the slices. If set to `True`, in the case of line paths a second\n        computation is performed to ignore the NaN value while interpolating,\n        and set the output values of NaNs to NaN.\n\n    Returns\n    -------\n    slice : `PrimaryHDU`\n        The position-velocity slice, as a FITS HDU object\n    \"\"\"\n\n    if isinstance(cube, (six.string_types, ImageHDU, PrimaryHDU)):\n        try:\n            from spectral_cube import SpectralCube\n            cube = SpectralCube.read(cube)\n        except ImportError:\n            raise ImportError(\"spectral_cube package required for working \"\n                              \"with fits data. Install spectral_cube or \"\n                              \"use NumPy arrays\")\n\n    if _is_spectral_cube(cube):\n        wcs = cube.wcs\n        # The fits HEADER will preserve the UNIT, but pvextractor does not care\n        # what the flux units are\n        cube = cube.filled_data[...].value\n\n    if wcs is not None:\n        wcs = sanitize_wcs(wcs)\n\n    if not isinstance(cube, np.ndarray) or wcs is not None:\n        scale = get_spatial_scale(wcs)\n        if isinstance(spacing, u.Quantity):\n            pixel_spacing = (spacing / scale).decompose()\n            world_spacing = spacing\n        else:\n            pixel_spacing = spacing\n            world_spacing = spacing * scale\n    else:\n        if isinstance(spacing, u.Quantity):\n            raise TypeError(\"No WCS has been specified, so spacing should be given in pixels\")\n        else:\n            pixel_spacing = spacing\n            world_spacing = None\n\n    # Allow path to be passed in as list of 2-tuples\n    if not isinstance(path, paths.Path):\n        path = paths.Path(path)\n\n    pv_slice = extract_slice(cube, path, wcs=wcs, spacing=pixel_spacing,\n                             order=order, respect_nan=respect_nan)\n\n    # Generate output header\n    if wcs is None:\n        header = Header()\n    else:\n        header = slice_wcs(wcs, spatial_scale=world_spacing).to_header()\n\n    # TODO: write path to BinTableHDU\n\n    return PrimaryHDU(data=pv_slice, header=header)\n\n\ndef _is_spectral_cube(obj):\n    try:\n        from spectral_cube import SpectralCube\n        return isinstance(obj, SpectralCube)\n    except ImportError:\n        return False\n", "meta": {"hexsha": "48527daff859397867bc9c95f2e848941ba536e1", "size": 4218, "ext": "py", "lang": "Python", "max_stars_repo_path": "glue/external/pvextractor/pvextractor.py", "max_stars_repo_name": "tiagopereira/glue", "max_stars_repo_head_hexsha": "85bf7ce2d252d7bc405e8160b56fc83d46b9cbe4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "glue/external/pvextractor/pvextractor.py", "max_issues_repo_name": "tiagopereira/glue", "max_issues_repo_head_hexsha": "85bf7ce2d252d7bc405e8160b56fc83d46b9cbe4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "glue/external/pvextractor/pvextractor.py", "max_forks_repo_name": "tiagopereira/glue", "max_forks_repo_head_hexsha": "85bf7ce2d252d7bc405e8160b56fc83d46b9cbe4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-04T14:10:12.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-04T14:10:12.000Z", "avg_line_length": 36.3620689655, "max_line_length": 94, "alphanum_fraction": 0.6543385491, "include": true, "reason": "import numpy,from astropy", "num_tokens": 949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3140505578320071, "lm_q1q2_score": 0.16438045256407635}}
{"text": "import copy\nimport cmath\nimport h5py\nimport math\nimport numpy\nimport scipy.linalg\nimport sys\nimport time\nfrom pauxy.walkers.multi_ghf import MultiGHFWalker\nfrom pauxy.walkers.single_det import SingleDetWalker\nfrom pauxy.walkers.multi_det import MultiDetWalker\nfrom pauxy.walkers.multi_coherent import MultiCoherentWalker\nfrom pauxy.walkers.thermal import ThermalWalker\nfrom pauxy.walkers.stack import FieldConfig\nfrom pauxy.utils.io import get_input_value\nfrom pauxy.utils.misc import update_stack\n\n\nclass Walkers(object):\n    \"\"\"Container for groups of walkers which make up a wavefunction.\n\n    Parameters\n    ----------\n    system : object\n        System object.\n    trial : object\n        Trial wavefunction object.\n    nwalkers : int\n        Number of walkers to initialise.\n    nprop_tot : int\n        Total number of propagators to store for back propagation + itcf.\n    nbp : int\n        Number of back propagation steps.\n    \"\"\"\n\n    def __init__(self, system, trial, qmc, walker_opts={}, verbose=False,\n                 comm=None, nprop_tot=None, nbp=None):\n        self.nwalkers = qmc.nwalkers\n        self.ntot_walkers = qmc.ntot_walkers\n        if verbose:\n            print(\"# nwalkers = {}\".format(self.nwalkers))\n            print(\"# ntot_walkers = {}\".format(self.ntot_walkers))\n        self.write_freq = walker_opts.get('write_freq', 0)\n        self.write_file = walker_opts.get('write_file', 'restart.h5')\n        self.use_log_shift = walker_opts.get('use_log_shift', False)\n        self.shift_counter = 1\n        self.read_file = walker_opts.get('read_file', None)\n        if comm is None:\n            rank = 0\n        else:\n            rank = comm.rank\n        if verbose:\n            print(\"# Setting up wavefunction object.\")\n        if trial.name == 'MultiSlater':\n            self.walker_type = 'MSD'\n            # TODO: FDM FIXTHIS\n            if trial.ndets == 1:\n                if verbose:\n                    print(\"# Usinge single det walker with msd wavefunction.\")\n                self.walker_type = 'SD'\n                trial.psi = trial.psi[0]\n                self.walkers = [SingleDetWalker(system, trial, walker_opts=walker_opts,\n                                                index=w, nprop_tot=nprop_tot,\n                                                nbp=nbp)\n                                for w in range(qmc.nwalkers)]\n            else:\n                self.walkers = [\n                        MultiDetWalker(system, trial, walker_opts=walker_opts,\n                                       verbose=(verbose and w == 0))\n                        for w in range(qmc.nwalkers)\n                        ]\n            self.buff_size = self.walkers[0].buff_size\n            if nbp is not None:\n                self.buff_size += self.walkers[0].field_configs.buff_size\n            self.walker_buffer = numpy.zeros(self.buff_size,\n                                             dtype=numpy.complex128)\n        elif trial.name == 'thermal':\n            self.walker_type = 'thermal'\n            self.walkers = [ThermalWalker(system, trial,\n                                          walker_opts=walker_opts,\n                                          verbose=(verbose and w==0))\n                            for w in range(qmc.nwalkers)]\n            self.buff_size = self.walkers[0].buff_size + self.walkers[0].stack.buff_size\n            self.walker_buffer = numpy.zeros(self.buff_size,\n                                             dtype=numpy.complex128)\n            stack_size = self.walkers[0].stack_size\n            if system.name == \"Hubbard\":\n                if stack_size % qmc.nstblz != 0 or qmc.nstblz < stack_size:\n                    if verbose:\n                        print(\"# Stabilisation frequency is not commensurate \"\n                              \"with stack size.\")\n                        print(\"# Determining a better value.\")\n                    if qmc.nstblz < stack_size:\n                        qmc.nstblz = stack_size\n                        if verbose:\n                            print(\"# Updated stabilization frequency: \"\n                                  \" {}\".format(qmc.nstblz))\n                    else:\n                        qmc.nstblz = update_stack(qmc.nstblz, stack_size,\n                                                  name=\"nstblz\", verbose=verbose)\n        elif trial.name == \"coherent_state\" and trial.symmetrize:\n            self.walker_type = 'MSD'\n            self.walkers = [MultiCoherentWalker(system, trial, walker_opts=walker_opts,\n                                        index=w, nprop_tot=nprop_tot,\n                                        nbp=nbp)\n                        for w in range(qmc.nwalkers)]\n            self.buff_size = self.walkers[0].buff_size\n            if nbp is not None:\n                if verbose:\n                    print(\"# Performing back propagation.\")\n                    print(\"# Number of steps in imaginary time: {:}.\".format(nbp))\n                self.buff_size += self.walkers[0].field_configs.buff_size\n            self.walker_buffer = numpy.zeros(self.buff_size,\n                                             dtype=numpy.complex128)\n        else:\n            self.walker_type = 'SD'\n            self.walkers = [SingleDetWalker(system, trial, walker_opts=walker_opts,\n                                            index=w, nprop_tot=nprop_tot,\n                                            nbp=nbp)\n                            for w in range(qmc.nwalkers)]\n            self.buff_size = self.walkers[0].buff_size\n            if nbp is not None:\n                if verbose:\n                    print(\"# Performing back propagation.\")\n                    print(\"# Number of steps in imaginary time: {:}.\".format(nbp))\n                self.buff_size += self.walkers[0].field_configs.buff_size\n            self.walker_buffer = numpy.zeros(self.buff_size,\n                                             dtype=numpy.complex128)\n        if system.name == \"Generic\" or system.name == \"UEG\":\n            dtype = complex\n        else:\n            dtype = int\n        self.pcont_method = get_input_value(walker_opts, 'population_control',\n                                            default='comb')\n        self.min_weight = walker_opts.get('min_weight', 0.1)\n        self.max_weight = walker_opts.get('max_weight', 4.0)\n        if verbose:\n            print(\"# Using {} population control \"\n                  \"algorithm.\".format(self.pcont_method))\n            mem = float(self.walker_buffer.nbytes) / (1024.0**3)\n            print(\"# Buffer size for communication: {:13.8e} GB\".format(mem))\n            if mem > 2.0:\n                # TODO: FDM FIX THIS\n                print(\" # Warning: Walker buffer size > 2GB. May run into MPI\"\n                      \"issues.\")\n        if not self.walker_type == \"thermal\":\n            walker_size = 3 + self.walkers[0].phi.size\n        if self.write_freq > 0:\n            self.write_restart = True\n            self.dsets = []\n            with h5py.File(self.write_file,'w',driver='mpio',comm=comm) as fh5:\n                for i in range(self.ntot_walkers):\n                    fh5.create_dataset('walker_%d'%i, (walker_size,),\n                                       dtype=numpy.complex128)\n\n        else:\n            self.write_restart = False\n        if self.read_file is not None:\n            if verbose:\n                print(\"# Reading walkers from %s file series.\"%self.read_file)\n            self.read_walkers(comm)\n        self.target_weight = qmc.ntot_walkers\n        self.nw = qmc.nwalkers\n        self.set_total_weight(qmc.ntot_walkers)\n\n    def orthogonalise(self, trial, free_projection):\n        \"\"\"Orthogonalise all walkers.\n\n        Parameters\n        ----------\n        trial : object\n            Trial wavefunction object.\n        free_projection : bool\n            True if doing free projection.\n        \"\"\"\n        for w in self.walkers:\n            detR = w.reortho(trial)\n            if free_projection:\n                (magn, dtheta) = cmath.polar(detR)\n                w.weight *= magn\n                w.phase *= cmath.exp(1j*dtheta)\n\n    def add_field_config(self, nprop_tot, nbp, system, dtype):\n        \"\"\"Add FieldConfig object to walker object.\n\n        Parameters\n        ----------\n        nprop_tot : int\n            Total number of propagators to store for back propagation + itcf.\n        nbp : int\n            Number of back propagation steps.\n        nfields : int\n            Number of fields to store for each back propagation step.\n        dtype : type\n            Field configuration type.\n        \"\"\"\n        for w in self.walkers:\n            w.field_configs = FieldConfig(system.nfields, nprop_tot, nbp, dtype)\n\n    def copy_historic_wfn(self):\n        \"\"\"Copy current wavefunction to psi_n for next back propagation step.\"\"\"\n        for (i,w) in enumerate(self.walkers):\n            numpy.copyto(self.walkers[i].phi_old, self.walkers[i].phi)\n\n    def copy_bp_wfn(self, phi_bp):\n        \"\"\"Copy back propagated wavefunction.\n\n        Parameters\n        ----------\n        phi_bp : object\n            list of walker objects containing back propagated walkers.\n        \"\"\"\n        for (i, (w,wbp)) in enumerate(zip(self.walkers, phi_bp)):\n            numpy.copyto(self.walkers[i].phi_bp, wbp.phi)\n\n    def copy_init_wfn(self):\n        \"\"\"Copy current wavefunction to initial wavefunction.\n\n        The definition of the initial wavefunction depends on whether we are\n        calculating an ITCF or not.\n        \"\"\"\n        for (i,w) in enumerate(self.walkers):\n            numpy.copyto(self.walkers[i].phi_right, self.walkers[i].phi)\n\n    def pop_control(self, comm):\n        if self.ntot_walkers == 1:\n            return\n        if self.use_log_shift:\n           self.update_log_ovlp(comm)\n        weights = numpy.array([abs(w.weight) for w in self.walkers])\n        global_weights = numpy.empty(len(weights)*comm.size)\n        comm.Allgather(weights, global_weights)\n        total_weight = sum(global_weights)\n        # Rescale weights to combat exponential decay/growth.\n        scale = total_weight / self.target_weight\n        if total_weight < 1e-8:\n            if comm.rank == 0:\n                print(\"# Warning: Total weight is {:13.8e}: \"\n                      .format(total_weight))\n                print(\"# Something is seriously wrong.\")\n            sys.exit()\n        self.set_total_weight(total_weight)\n        # Todo: Just standardise information we want to send between routines.\n        for w in self.walkers:\n            w.unscaled_weight = w.weight\n            w.weight = w.weight / scale\n        if self.pcont_method == \"comb\":\n            global_weights = global_weights / scale\n            self.comb(comm, global_weights)\n        elif self.pcont_method == \"pair_branch\":\n            self.pair_branch(comm)\n        else:\n            if comm.rank == 0:\n                print(\"Unknown population control method.\")\n\n    def comb(self, comm, weights):\n        \"\"\"Apply the comb method of population control / branching.\n\n        See Booth & Gubernatis PRE 80, 046704 (2009).\n\n        Parameters\n        ----------\n        comm : MPI communicator\n        \"\"\"\n        # Need make a copy to since the elements in psi are only references to\n        # walker objects in memory. We don't want future changes in a given\n        # element of psi having unintended consequences.\n        # todo : add phase to walker for free projection\n        if comm.rank == 0:\n            parent_ix = numpy.zeros(len(weights), dtype='i')\n        else:\n            parent_ix = numpy.empty(len(weights), dtype='i')\n        if comm.rank == 0:\n            total_weight = sum(weights)\n            cprobs = numpy.cumsum(weights)\n            r = numpy.random.random()\n            comb = [(i+r) * (total_weight/self.target_weight) for i in\n                    range(self.target_weight)]\n            iw = 0\n            ic = 0\n            while ic < len(comb):\n                if comb[ic] < cprobs[iw]:\n                    parent_ix[iw] += 1\n                    ic += 1\n                else:\n                    iw += 1\n            data = {'ix': parent_ix}\n        else:\n            data = None\n\n        data = comm.bcast(data, root=0)\n        parent_ix = data['ix']\n        # Keep total weight saved for capping purposes.\n        # where returns a tuple (array,), selecting first element.\n        kill = numpy.where(parent_ix == 0)[0]\n        clone = numpy.where(parent_ix > 1)[0]\n        reqs = []\n        walker_buffers = []\n        # First initiate non-blocking sends of walkers.\n        comm.barrier()\n        for i, (c, k) in enumerate(zip(clone, kill)):\n            # Sending from current processor?\n            if c // self.nw == comm.rank:\n                # Location of walker to clone in local list.\n                clone_pos = c % self.nw\n                # copying walker data to intermediate buffer to avoid issues\n                # with accessing walker data during send. Might not be\n                # necessary.\n                dest_proc = k // self.nw\n                # with h5py.File('before_{}.h5'.format(comm.rank), 'a') as fh5:\n                    # fh5['walker_{}_{}_{}'.format(c,k,dest_proc)] = self.walkers[clone_pos].get_buffer()\n                buff = self.walkers[clone_pos].get_buffer()\n                reqs.append(comm.Isend(buff, dest=dest_proc, tag=i))\n        # Now receive walkers on processors where walkers are to be killed.\n        for i, (c, k) in enumerate(zip(clone, kill)):\n            # Receiving to current processor?\n            if k // self.nw == comm.rank:\n                # Processor we are receiving from.\n                source_proc = c // self.nw\n                # Location of walker to kill in local list of walkers.\n                kill_pos = k % self.nw\n                comm.Recv(self.walker_buffer, source=source_proc, tag=i)\n                # with h5py.File('walkers_recv.h5', 'w') as fh5:\n                    # fh5['walk_{}'.format(k)] = self.walker_buffer.copy()\n                self.walkers[kill_pos].set_buffer(self.walker_buffer)\n                # with h5py.File('after_{}.h5'.format(comm.rank), 'a') as fh5:\n                    # fh5['walker_{}_{}_{}'.format(c,k,comm.rank)] = self.walkers[kill_pos].get_buffer()\n        # Complete non-blocking send.\n        for rs in reqs:\n            rs.wait()\n        # Necessary?\n        # if len(kill) > 0 or len(clone) > 0:\n            # sys.exit()\n        comm.Barrier()\n        # Reset walker weight.\n        # TODO: check this.\n        for w in self.walkers:\n            w.weight = 1.0\n\n    def pair_branch(self, comm):\n        walker_info = [[abs(w.weight),1,comm.rank,comm.rank] for w in self.walkers]\n        glob_inf = comm.gather(walker_info, root=0)\n        # Want same random number seed used on all processors\n        if comm.rank == 0:\n            # Rescale weights.\n            glob_inf = numpy.array([item for sub in glob_inf for item in sub])\n            total_weight = sum(w[0] for w in glob_inf)\n            sort = numpy.argsort(glob_inf[:,0], kind='mergesort')\n            isort = numpy.argsort(sort, kind='mergesort')\n            glob_inf = glob_inf[sort]\n            s = 0\n            e = len(glob_inf) - 1\n            tags = []\n            isend = 0\n            while s < e:\n                if glob_inf[s][0] < self.min_weight or glob_inf[e][0] > self.max_weight:\n                    # sum of paired walker weights\n                    wab = glob_inf[s][0] + glob_inf[e][0]\n                    r = numpy.random.rand()\n                    if r < glob_inf[e][0] / wab:\n                        # clone large weight walker\n                        glob_inf[e][0] = 0.5 * wab\n                        glob_inf[e][1] = 2\n                        # Processor we will send duplicated walker to\n                        glob_inf[e][3] = glob_inf[s][2]\n                        send = glob_inf[s][2]\n                        # Kill small weight walker\n                        glob_inf[s][0] = 0.0\n                        glob_inf[s][1] = 0\n                        glob_inf[s][3] = glob_inf[e][2]\n                    else:\n                        # clone small weight walker\n                        glob_inf[s][0] = 0.5 * wab\n                        glob_inf[s][1] = 2\n                        # Processor we will send duplicated walker to\n                        glob_inf[s][3] = glob_inf[e][2]\n                        send = glob_inf[e][2]\n                        # Kill small weight walker\n                        glob_inf[e][0] = 0.0\n                        glob_inf[e][1] = 0\n                        glob_inf[e][3] = glob_inf[s][2]\n                    tags.append([send])\n                    s += 1\n                    e -= 1\n                else:\n                    break\n            nw = self.nwalkers\n            glob_inf = glob_inf[isort].reshape((comm.size,nw,4))\n        else:\n            data = None\n            total_weight = 0\n        data = comm.scatter(glob_inf, root=0)\n        # Keep total weight saved for capping purposes.\n        walker_buffers = []\n        reqs = []\n        for iw, walker in enumerate(data):\n            if walker[1] > 1:\n                tag = comm.rank*len(walker_info) + walker[3]\n                self.walkers[iw].weight = walker[0]\n                buff = self.walkers[iw].get_buffer()\n                reqs.append(comm.Isend(buff,\n                                       dest=int(round(walker[3])),\n                                       tag=tag))\n        for iw, walker in enumerate(data):\n            if walker[1] == 0:\n                tag = walker[3]*len(walker_info) + comm.rank\n                comm.Recv(self.walker_buffer,\n                          source=int(round(walker[3])),\n                          tag=tag)\n                self.walkers[iw].set_buffer(self.walker_buffer)\n        for r in reqs:\n            r.wait()\n\n\n    def recompute_greens_function(self, trial, time_slice=None):\n        for w in self.walkers:\n            w.greens_function(trial, time_slice)\n\n    def set_total_weight(self, total_weight):\n        for w in self.walkers:\n            w.total_weight = total_weight\n            w.old_total_weight = w.total_weight\n\n    def reset(self, trial):\n        for w in self.walkers:\n            w.stack.reset()\n            w.stack.set_all(trial.dmat)\n            w.greens_function(trial)\n            w.weight = 1.0\n            w.phase = 1.0 + 0.0j\n\n    def get_write_buffer(self, i):\n        w = self.walkers[i]\n        buff = numpy.concatenate([[w.weight], [w.phase], [w.ot], w.phi.ravel()])\n        return buff\n\n    def set_walker_from_buffer(self, i, buff):\n        w = self.walkers[i]\n        w.weight = buff[0]\n        w.phase = buff[1]\n        w.ot = buff[2]\n        w.phi = buff[3:].reshape(self.walkers[i].phi.shape)\n\n    def write_walkers(self, comm):\n        start = time.time()\n        with h5py.File(self.write_file,'r+',driver='mpio',comm=comm) as fh5:\n            for (i,w) in enumerate(self.walkers):\n                ix = i + self.nwalkers*comm.rank\n                buff = self.get_write_buffer(i)\n                fh5['walker_%d'%ix][:] = self.get_write_buffer(i)\n        if comm.rank == 0:\n            print(\" # Writing walkers to file.\")\n            print(\" # Time to write restart: {:13.8e} s\"\n                  .format(time.time()-start))\n\n    def update_log_ovlp(self, comm):\n        send = numpy.zeros(3, dtype=numpy.complex128)\n        # Overlap log factor\n        send[0] = sum(abs(w.ot) for w in self.walkers)\n        # Det R log factor\n        send[1] = sum(abs(w.detR) for w in self.walkers)\n        send[2] = sum(abs(w.log_detR) for w in self.walkers)\n        global_av = numpy.zeros(3, dtype=numpy.complex128)\n        comm.Allreduce(send, global_av)\n        log_shift = numpy.log(global_av[0]/self.ntot_walkers)\n        detR_shift = numpy.log(global_av[1]/self.ntot_walkers)\n        log_detR_shift = global_av[2]/self.ntot_walkers\n        # w.log_shift = -0.5\n        n = self.shift_counter\n        nm1 = self.shift_counter - 1\n        for w in self.walkers:\n            w.log_shift = (w.log_shift*nm1 + log_shift)/n\n            w.log_detR_shift = (w.log_detR_shift*nm1 + log_detR_shift)/n\n            w.detR_shift = (w.detR_shift*nm1 + detR_shift)/n\n        self.shift_counter += 1\n\n    def read_walkers(self, comm):\n        with h5py.File(self.read_file, 'r') as fh5:\n            for (i,w) in enumerate(self.walkers):\n                try:\n                    ix = i + self.nwalkers*comm.rank\n                    self.set_walker_from_buffer(i, fh5['walker_%d'%ix][:])\n                except KeyError:\n                    print(\" # Could not read walker data from:\"\n                          \" %s\"%(self.read_file))\n", "meta": {"hexsha": "fa078b878dbe30e91904cdecca0939654da23115", "size": 20669, "ext": "py", "lang": "Python", "max_stars_repo_path": "pauxy/walkers/handler.py", "max_stars_repo_name": "pauxy-qmc/pauxy", "max_stars_repo_head_hexsha": "1da80284284769b59361c73cfa3c2d914c74a73f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2020-08-05T17:17:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T04:06:18.000Z", "max_issues_repo_path": "pauxy/walkers/handler.py", "max_issues_repo_name": "pauxy-qmc/pauxy", "max_issues_repo_head_hexsha": "1da80284284769b59361c73cfa3c2d914c74a73f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-05-17T21:28:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-22T18:05:50.000Z", "max_forks_repo_path": "pauxy/walkers/handler.py", "max_forks_repo_name": "pauxy-qmc/pauxy", "max_forks_repo_head_hexsha": "1da80284284769b59361c73cfa3c2d914c74a73f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-18T01:03:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T15:36:29.000Z", "avg_line_length": 42.5288065844, "max_line_length": 105, "alphanum_fraction": 0.524215008, "include": true, "reason": "import numpy,import scipy", "num_tokens": 4653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.16438044920366546}}
{"text": "#!/usr/bin/env python\n\nimport copy, math, numpy, os, pdb, sys\nimport chipseq_analysis, cmdlineProgs, random, selexDb, seq_utility, seqUtils, utility\nimport numpy\n\n# SUMMARY: I have created this class to encapsulate motifs, for use in my\n# chipseq qc work. Should possibly have done this earlier, as there are\n# various motif-related functions etc. scattered throughout my python libraries.\n\n\n# Introduced on June 18th 2013, for use in snv analysis. Should be useful\n# elsewhere too:\ndef motifPrefixes2meme(outputFile, motifPrefixes, baseDir, suffix):\n    for motifPrefix in motifPrefixes:\n        currMotif = pwm(open(baseDir + motifPrefix + suffix))\n        currMotif.setName(motifPrefix)\n        currMotif.writeToMEME(outputFile)\n        print >> outputFile, \"\"\n\n\n# Introduced on June 18th 2013, for use in snv analysis. Should be useful\n# elsewhere too:\ndef getTFsForMotifPrefix(motifPrefix, motifsCursor):\n    \"\"\"Retrieves all TFs corresponding to the specified motif prefix,\n    by identity and sequence similarity, according to the motifs database.\"\"\"\n\n    # Get the TFs linked by gene ID:\n    cmdStr = \"select genes.Name from motifs.genes inner join motifs.tfMotifs on motifs.genes.geneID = motifs.tfMotifs.geneID where motifs.tfMotifs.motifPrefix = \\\"\" + str(motifPrefix) + \"\\\";\"\n    motifsCursor.execute(cmdStr)\n    rows = motifsCursor.fetchall()\n\n    tfsByGeneID = map(lambda row: row[0], rows)\n\n    # Get the TFs linked by DBD sequence similarity:\n    cmdStr = \"select distinct g2.Name from motifs.genes inner join motifs.tfMotifs on motifs.genes.geneID = motifs.tfMotifs.geneID inner join geneProteins on genes.GeneID = geneProteins.GeneID inner join proteins on geneProteins.proteinID = proteins.proteinID inner join dbdBlocks on proteins.proteinID = dbdBlocks.proteinID inner join aaSeq on dbdBlocks.aaSeqID = aaSeq.seqID inner join aaSeqSim on aaSeq.seqID = aaSeqSim.seq1id inner join aaSeq as2 on aaSeqSim.seq2id = as2.seqID inner join dbdBlocks db2 on as2.seqID = db2.aaSeqID inner join proteins p2 on db2.proteinID = p2.proteinID inner join geneProteins gp2 on p2.proteinID = gp2.proteinID inner join genes g2 on gp2.geneID = g2.geneID where motifs.tfMotifs.motifPrefix = \\\"\" + str(motifPrefix) + \"\\\" and aaSeqSim.similarity >= 1;\"\n    motifsCursor.execute(cmdStr)\n    rows = motifsCursor.fetchall()\n\n    tfsBySeqSim = map(lambda row: row[0], rows)\n\n    if (len(rows) > 0):\n        tfName = rows[0][0]\n    else:\n        tfName = None # There are no chip-seq TFs for that motif\n\n    # Fixed bug on July 29th 2013: Uniquify the resulting list before returning:\n    tfsForMotifDict = {}\n    for tf in tfsByGeneID + tfsBySeqSim:\n        tfsForMotifDict[tf] = 1\n    return tfsForMotifDict.keys()\n\n\ndef cons2countMatrix(consString, count):\n    \"\"\"Takes a consensus sequence and a count value as input, and generates a\n    numpy matrix representing the equivelant pwm. Returns that matrix object\n    (rather than a pwm object).\"\"\"\n\n    # Set up the alphabet mapping dictionary, in order to map from letters to\n    # indeces in the matrix:\n    mappingDict = {'A':0, 'C':1, 'G':2, 'T':3, 'a':0, 'c':1, 'g':2, 't':3}\n    aLen = 4\n\n    # Generate a new zeros matrix as long as the alphabet and as wide as the\n    # consensus string, to build the count matrix on:\n    countMat = numpy.zeros((len(consString), aLen))\n\n    # Set the count value in each column of the matrix, based on the consensus\n    # sequence letter at that position, and the specified input count value:\n    for seqIdx in range(len(consString)):\n        lettIdx = mappingDict[consString[seqIdx]]\n        countMat[seqIdx][lettIdx] = count\n    return countMat\n\n\nclass pwm(object):\n    \"\"\"A single pwm motif model.\"\"\"\n\n    def __init__(self, motifData, dataType=\"memeFile\"):\n        self.name = None\n        self.matrix = None\n        self.memeFilePath = None\n        self.eValue = None\n        self.consensusCount = None # Optional, for count data such as selex\n        if (dataType == \"memeFile\"):\n            assert (isinstance(motifData, file))\n            # Input data is a MEME file => Initialise accordingly:\n            self.initFromMEME(motifData)\n            if (self.matrix == []):\n                # Matrix was still empty after trying to initialise from\n                # MEME file -> Report this as an exception:\n                raise ValueError(\"MEME file had no more motifs in it:\" +\n                                 motifData.name)\n        if (dataType == \"xxMotifFile\"):\n            assert (isinstance(motifData, file))\n            # Input data is a xxMotif file => Initialise accordingly:\n            self.initFrom_xxMotif(motifData)\n            if (self.matrix == []):\n                # Matrix was still empty after trying to initialise from\n                # xxMotif file -> Report this as an exception:\n                raise ValueError(\"xxMotif file had no more motifs in it:\" +\n                                 motifData.name)\n        elif (dataType == \"countsFile\"):\n            assert (isinstance(motifData, file))\n            self.initFromCounts(motifData)\n        elif (dataType == \"freqMatrix\"):\n            self.initFromFreqMatrix(motifData)\n        elif (dataType == \"seqAln\"):\n            # Input data is a list of strings representing aligned DNA sequences\n            # from which this pwm should be constructed:\n            self.initFromAlign(motifData)\n        elif (dataType == \"iniMotifFile\"):\n            self.initFromInimotifFile(motifData)\n        self.logoFilename = None\n\n    def getScoreProf(self, dnaSeq, bgFreqs = [0.25,0.25,0.25,0.25,0.25]):\n        \"\"\"Introduced April 15th 2011.\n\n        Calculates the motif LLR score contribution at each position in the\n        specified DNA sequence. Returns the resulting LLR score contributions\n        as an array. Sequence positions with the letter \"N\" result in a zero\n        value contribution.\n\n        NOTE: This only works/makes sense when a zero-order background\n        model is used. Thus, the bgFreqs is assumed to be an array describing\n        such a background model (for A, C, G, T and N).\"\"\"\n\n        assert len(dnaSeq) == self.getWidth()\n\n        # Generate a data structure mapping from letter to pwm (and background\n        # model) index:\n        lett2colIdx = {'A':0, 'C':1, 'G':2, 'T':3, 'N':4, \\\n                           'a':0, 'c':1, 'g':2, 't':3, 'n':4}\n\n        # The array showing contributions of each letter to the total LLR:\n        llrScoreContribs = []\n\n        # Consider each position in the motif...\n        for columnIdx in range(self.getWidth()):\n            # Current column; bgFreqs[-1] gives the \"N\" frequency:\n            motifColumn = self.getMatrix()[columnIdx] + [bgFreqs[-1]]\n\n            # Get motif likelihood, bg likelihood, and then calculate llr:\n            letter = dnaSeq[columnIdx]\n            letterColIdx = lett2colIdx[letter]\n            motifProb = motifColumn[letterColIdx]\n            bgProb = bgFreqs[letterColIdx]\n            llrScoreContribs.append(math.log(motifProb/bgProb, 10))\n\n        return llrScoreContribs\n\n    def getName(self):\n        return self.name\n\n    def setName(self, name):\n        self.name = name\n\n    def getIC_arr(self):\n        \"\"\"Returns an array storing the information content of each column of\n        this pwm, in order of motif position.\"\"\"\n        matrix = self.matrix\n        ICs = []\n        for col in matrix:\n            ICs.append(seq_utility.calc_IC(col))\n        return ICs\n\n    def getMatrix(self):\n        return self.matrix\n\n    def getWidth(self):\n        return len(self.matrix)\n\n    def getLogoFilename(self):\n        return self.logoFilename\n\n    def getMemeFilePath(self):\n        return self.memeFilePath\n\n    def getEValue(self):\n        return self.eValue\n\n    def trimLowIC(self, icThresh=0.5, copy=False):\n        \"\"\"Trims off low information-content flanking columns from the motif.\"\"\"\n        trimmedMotif = self.getMatrix()\n\n        # Trim the leading low IC columns...\n        while ((len(trimmedMotif) > 0) and\n               (seq_utility.calc_IC(trimmedMotif[0]) < icThresh)):\n            trimmedMotif = trimmedMotif[1:]\n\n        # Trim the tailing low IC columns...\n        while ((len(trimmedMotif) > 0) and\n               (seq_utility.calc_IC(trimmedMotif[-1]) < icThresh)):\n            trimmedMotif = trimmedMotif[:-1]\n        if (not copy):\n            # Editing the original motif => Set matrix:\n            self.matrix = trimmedMotif\n            return None\n        else:\n            # Making a copy matrix:\n            copyMotif = pwm(trimmedMotif, dataType=\"freqMatrix\")\n            return copyMotif\n\n    def makeSeqLogo(self, outFilePrefix, format=\"eps\"):\n        \"\"\"Generates an eps sequence logo for this motif, writing it out to the\n        specified filename.\"\"\"\n\n        self.logoFilename = outFilePrefix + \".\" + format\n\n        tmpMemeFilename = \\\n            utility.makeTempFilename(outFilePrefix + \"_tmp_MEME_file_ceqlogo\",\n                                     fileSuffix = \".meme\")\n        tmpMemeFile = open(tmpMemeFilename, 'w')\n        self.writeToMEME(tmpMemeFile)\n        print >> tmpMemeFile, \"\"\n        tmpMemeFile.flush()\n        tmpMemeFile.close()\n\n        # FIXME: Currently, I assume the matrix file exists, and that it is\n        # in MEME format. Will need to adapt this in the future when\n        # dynamically-generated motifs are run instead:\n        seqUtils.run_ceqlogo(tmpMemeFilename, outFilePrefix, format=format)\n        cmdlineProgs.deleteFiles([tmpMemeFilename])\n\n    def writeToMAST(self, outFile, pseudo=0.01):\n        \"\"\"Writes the motif out the specified filehandle in MAST format.\"\"\"\n\n        # The motif matrix data must have been set before this method can\n        # be called:\n        assert (self.matrix != None)\n\n        lengthStr = str(len(self.matrix))\n\n        hdrString = \"\"\"MEME version 4.5\n\nALPHABET= ACGT\n\nstrands: + -\n\nBackground letter frequencies (from dataset with add-one prior applied):\nA 0.25 C 0.25 G 0.25 T 0.25\n\nMOTIF \"\"\"\n        extra = str(self.name) + \"\\nBL   MOTIF \" + str(self.name) + \" width= \" + lengthStr + \" seqs=0\\n\\nlog-odds matrix: alength= 4 w= \" + lengthStr + \"\\n\"\n        hdrString = hdrString + extra\n\n        outFile.write(hdrString)\n\n        # Currently just assume uniform background model:\n        for col in self.matrix:\n            # Add pseudo-counts to the elements of the matrix...\n            # FIXME: This could be done better. What pseudo-count\n            # value is best? Shouldn't this be in a psfm2llr function?\n            newCol = map(lambda prob: (prob+pseudo)/(1+(pseudo*4)), col)\n\n            # From mast source code, it seems the log base is 10, although I'm\n            # not 100% sure!:\n            try:\n                llrCol = map(lambda prob: math.log(prob/0.25, 10), newCol)\n            except ValueError, e:\n                print >> sys.stderr, \"Invalid probability column:\", newCol\n                raise e\n            outFile.write(reduce(lambda p1, p2: str(p1) + \" \" + str(p2),\n                                 llrCol, \"\") + \"\\n\")\n        print >> outFile, \"\"\n\n    def writeToTRANSFAC(self, outFile, nSeqs=1000, pseudo=0.01):\n        \"\"\"Writes the motif out the specified filehandle in TRANSFAC format.\"\"\"\n\n        # The motif matrix data must have been set before this method can\n        # be called:\n        assert (self.matrix != None)\n\n        lengthStr = str(len(self.matrix))\n\n        hdrString = \"AC \" + self.name + \"\"\"\nXX\nTY Motif\nID \"\"\" + self.name + \"\"\"\nBF undef\nP0\\tA\\tC\\tG\\tT\\n\"\"\"\n\n        outFile.write(hdrString)\n\n        # Currently just assume uniform background model:\n        colNum = 0\n        for col in self.matrix:\n            # Add pseudo-counts to the elements of the matrix...\n            newCol = map(lambda prob: (prob+pseudo)/(1+(pseudo*4)), col)\n            newColCounts = map(lambda freq: int(freq*1000), newCol)\n\n            colNumStr = (\"%2d\" % colNum).replace(\" \", \"0\")\n            outFile.write(colNumStr +\n                          reduce(lambda p1, p2: str(p1) + \"\\t\" + str(p2),\n                                 newColCounts, \"\") + \"\\n\")\n            colNum += 1\n\n        print >> outFile, \"XX\\n//\"\n\n    def addPseudoCounts(self, pseudo=0.01):\n        \"\"\"Modifies the psfm for this motif, by adding a specified pseudo count\n        at each position.\"\"\"\n\n        newMatrix = []\n        for col in self.matrix:\n            newCol = map(lambda prob: (prob+pseudo)/(1+(pseudo*4)), col)\n            newMatrix.append(newCol)\n        self.matrix = newMatrix\n\n    def writeCountMatrix(self, outFile, nSeqs=100, pseudo=0.01):\n        \"\"\"Writes the motif out as a count matrix, using the specified\n        number of sequences.\"\"\"\n        assert (self.matrix != None)\n\n        hdrString = \">\" + self.getName()\n        outFile.write(hdrString + \"\\n\")\n        for col in self.matrix:\n            probCol = map(lambda prob: (prob+pseudo)/(1+(pseudo*4)), col)\n            countCol = map(lambda prob: int(prob*nSeqs), probCol)\n            outFile.write(reduce(lambda p1, p2: str(p1) + \" \" + str(p2),\n                                 countCol, \"\") + \"\\n\")\n\n    def writeFreqMatrix(self, outFile, nSeqs=100, pseudo=0.01):\n        \"\"\"Writes the motif out as a frequency matrix.\"\"\"\n        assert (self.matrix != None)\n\n        hdrString = \">\" + self.getName()\n        outFile.write(hdrString + \"\\n\")\n        for col in self.matrix:\n            probCol = map(lambda prob: (prob+pseudo)/(1+(pseudo*4)), col)\n            outFile.write(reduce(lambda p1, p2: str(p1) + \" \" + str(p2),\n                                 probCol, \"\") + \"\\n\")\n        \n    def writeToMEME(self, outFile, pseudo=0.01):\n        \"\"\"Writes the motif out the specified filehandle in MEME format.\"\"\"\n\n        # The motif matrix data must have been set before this method can\n        # be called:\n        assert (self.matrix != None)\n\n        hdrString = \"\"\"MEME version 4.5\n\nALPHABET= ACGT\n\nstrands:  + -\n\nBackground letter frequencies (from dataset with add-one prior applied):\nA 0.25 C 0.25 G 0.25 T 0.25\n\nMOTIF \"\"\" + str(self.name) + \"\"\"\nBL   MOTIF \"\"\" + str(self.name) + \"\"\" width= \"\"\" + str(len(self.matrix)) + \"\"\" seqs=0\nletter-probability matrix: alength= 4 w= \"\"\" + str(len(self.matrix)) + \" nsites= 10 E= 0\\n\"\n\n        outFile.write(hdrString)\n\n        # Currently just assume uniform background model:\n        for col in self.matrix:\n            newCol = map(lambda prob: (prob+pseudo)/(1+(pseudo*4)), col)\n            outFile.write(reduce(lambda p1, p2: str(p1) + \" \" + str(p2),\n                                 newCol, \"\") + \"\\n\")\n        outFile.flush()\n\n    def initFromFreqMatrix(self, matrix, name=\"Unknown\"):\n        \"\"\"Initialise the matrix by simply assigning to the specified frequency\n        matrix.\"\"\"\n\n        self.matrix = matrix\n\n    def initFromInimotifFile(self, iniMotifFile, name=\"Unknown\"):\n        \"\"\"Initialise the matrix from an iniMotif file.\"\"\"\n\n        # Read in the count of the consensus sequence...\n        currLine = iniMotifFile.readline()\n        elems = currLine.split()\n        while ((len(elems) < 2) or (elems[1] != \"consensus\")):\n            currLine = iniMotifFile.readline()\n            elems = currLine.split()\n        self.consensusCount = int(elems[-1])\n\n        # Skip to the start of the frequency matrix...\n        while (currLine[:16] != \"Frequency Matrix\"):\n            currLine = iniMotifFile.readline()\n\n        # Read the matrix information:\n        currLine = iniMotifFile.readline()\n        freqsTranspose = []\n        while (currLine != \"\\n\"):\n            elems = currLine.split()\n            freqs = map(lambda tok: float(tok), elems[1:])\n            freqsTranspose.append(freqs)\n            currLine = iniMotifFile.readline()\n\n        freqMatrixTranspose = numpy.matrix(freqsTranspose)\n        freqMatrix = freqMatrixTranspose.transpose()\n        freqMatrixAsList = freqMatrix.tolist()\n        self.matrix = freqMatrixAsList\n\n    def initFromCounts(self, countsInfile, name=\"Unknown\", pseudo=0.01):\n        \"\"\"Initialise the matrix from an input text file of counts, where each\n        row has four values specifying the A, C, G, T counts for a given column\n        of the psfm.\"\"\"\n\n        self.name = name\n\n        matrix = []\n        for line in countsInfile.readlines():\n            elems = line.strip().split()\n            countsColumn = map(lambda tok: int(tok), elems)\n            countsSum = reduce(lambda count1, count2: count1 + count2,\n                               countsColumn)\n            freqsColumn = \\\n                map(lambda count: float(count + pseudo)/float(countsSum + pseudo*4),\n                              countsColumn)\n            matrix.append(freqsColumn)\n        self.matrix = matrix\n\n    def initFromAlign(self, seqAlnList, name=\"Unknown\", pseudo=0.01):\n        \"\"\"Initialise the matrix from a list of aligned DNA sequences.\"\"\"\n\n        lett_to_idx = \\\n            {'A':0, 'C':1, 'G':2, 'T':3, \\\n                 'a':0, 'c':1, 'g':2, 't':3}\n\n        # Initialise count matrix:\n        seq_len = len(seqAlnList[0])\n        count_matrix = []\n        seq_idx = 0\n        while (seq_idx < seq_len):\n            count_matrix.append([0,0,0,0])\n            seq_idx = seq_idx + 1\n\n        for sequence in seqAlnList:\n            # Add counts to count_matrix for current sequence:\n            seq_idx = 0;\n            while (seq_idx < seq_len):\n                curr_lett = sequence[seq_idx]\n                # If 'N' is found, add a count of 0.25 to each count\n                # matrix letter:\n                if ((curr_lett == 'N') or (curr_lett == 'n')):\n                    count_matrix[seq_idx][0] = count_matrix[seq_idx][0] + 0.25\n                    count_matrix[seq_idx][1] = count_matrix[seq_idx][1] + 0.25\n                    count_matrix[seq_idx][2] = count_matrix[seq_idx][2] + 0.25\n                    count_matrix[seq_idx][3] = count_matrix[seq_idx][3] + 0.25\n                else:\n                    lett_idx = lett_to_idx[curr_lett]\n                    count_matrix[seq_idx][lett_idx] = \\\n                        count_matrix[seq_idx][lett_idx] + 1\n                seq_idx = seq_idx + 1\n                self.name = name\n\n        freqMatrix = []\n        for countsColumn in count_matrix:\n            countsSum = reduce(lambda count1, count2: count1 + count2,\n                               countsColumn)\n            freqsColumn = \\\n                map(lambda count: float(count + pseudo)/float(countsSum + pseudo*4),\n                              countsColumn)\n            freqMatrix.append(freqsColumn)\n        self.matrix = freqMatrix\n\n    def initFrom_xxMotif(self, xxMotif_infile):\n        # Store name of file as attribute of motif:\n\n        self.xxMotifFilePath = xxMotif_infile.name\n\n        # Parse a single motif from the assumed open file...\n\n        # Throw away lines until the next motif line is reached...\n        currLine = xxMotif_infile.readline()\n        if (currLine == \"\"):\n            raise ValueError(xxMotif_infile.name + \" contains no more motifs!\")\n\n        while ((currLine != \"\") and (currLine[:5] != \"Motif\")):\n            currLine = xxMotif_infile.readline()\n\n        if (currLine == \"\"):\n            raise ValueError(xxMotif_infile.name + \" contains no more motifs!\")\n\n        # Parse the motif line, to obtain the motif name:\n        elems = currLine.strip().split()\n        motifName = elems[1][:-1]\n        motifEvalue = float(elems[-1])\n        self.name = motifName\n        self.eValue = motifEvalue\n\n        # Parse the frequency matrix:\n        freqMatrixList = []\n        for lettIdx in [1,2,3,4]:\n            currLine = xxMotif_infile.readline()\n            elems = currLine.strip().split()\n            freqsCol = map(lambda tok: float(tok), elems[1:])\n            freqMatrixList.append(freqsCol)\n\n        freqMatrix = numpy.matrix(freqMatrixList)\n        freqMatrixTranspose = freqMatrix.transpose()\n        freqMatrixTransposeList = freqMatrixTranspose.tolist()\n        self.matrix = freqMatrixTransposeList\n\n    def initFromMEME(self, meme_infile):\n        # Initialise this motif from the specified motifData input file...\n\n        # Store the name of the file as an attribute of this motif:\n        self.memeFilePath = meme_infile.name\n\n        # Parse a single motif from an open MEME file...\n\n        # While the currline doesn't start with \"MOTIF\", discard the line and\n        # get the next...\n        currLine = meme_infile.readline()\n        if (currLine == \"\"):\n            raise ValueError(meme_infile.name + \" contains no more motifs!\")\n\n        # Ignore lines until \"MOTIF\" is reached:\n        while ((currLine != \"\") and (currLine[:5] != \"MOTIF\")):\n            currLine = meme_infile.readline()\n\n        if (currLine == \"\"):\n            raise ValueError(meme_infile.name + \" contains no more motifs!\")\n\n        # Parse the motif line, to obtain the motif name:\n        elems = currLine.strip().split()\n        motifName = elems[1]\n\n        # Discard lines until the  \"letter-probability\" line is reached...\n        while ((currLine != \"\") and (currLine[:18] != \"letter-probability\")):\n            currLine = meme_infile.readline()\n\n        if (currLine == \"\"):\n            raise ValueError(meme_infile.name + \" contains no matrix info\" + \\\n                                 \" for matrix \" + motifName)\n\n        # Parse the motif stats; extract and save the E-value of the motif:\n        elems = currLine.strip().split()\n        eValue = float(elems[9])\n        nsites = int(elems[7])\n\n        # Instantiate the motif with the parsed values:\n        self.name = motifName\n        self.eValue = eValue\n        self.nsites = nsites\n\n        # Parse the actual matrix data...\n        currLine = meme_infile.readline()\n        matrix = []\n        # Modified April 17th 2013; allowing new line character to indicate\n        # end of current motif:\n        while ((currLine != \"\") and (currLine[:3] != \"---\") and (currLine != \"\\n\")):\n            elems = currLine.strip().split()\n            matrixCol = map(lambda tok: float(tok), elems)\n            matrix.append(matrixCol)\n            currLine = meme_infile.readline()\n        self.matrix = matrix\n\n    def getRevCompMatrix(self):\n        \"\"\"Returns a raw frequency matrix representing the reverse complement of this matrix.\"\"\"\n        matrixCopy = copy.deepcopy(self.matrix)\n        matrixCopy.reverse()\n        for col in matrixCopy:\n            col.reverse()\n        return matrixCopy\n\n    def getConsensus(self):\n        \"\"\"Returns the consensus sequence of this motif.\"\"\"\n\n        letters = [\"A\",\"C\",\"G\",\"T\"]\n\n        maxPositions = numpy.array(self.matrix).argmax(1)\n        consensus = reduce(lambda lett1, lett2: lett1+lett2,\n                           map(lambda maxPos:letters[maxPos], maxPositions))\n        return consensus\n\n    def loadIntoDb(self, analysisID, cycle, db):\n        \"\"\"Loads this motif into the specified SELEX database, with the\n        specified analysisID and SELEX cycle number that it was generated\n        from.\"\"\"\n\n        # Obtain the ensemble ID of this factor, using the analysisID and a\n        # mysql query...\n        \n        # Find the Barcode and Batch studied with the specified analysis:\n        cursor=db.cursor()\n        cmdStr = \"select BarcodeAnalysed, BarcodeBatchAnalysed from SELEX_Analyses where (AnalysisID = \" + str(analysisID) + \");\"\n        cursor.execute(cmdStr)\n        rows = cursor.fetchall()\n\n        # Return the first element of the first result from the query run:\n        (barcode, batch) = rows[0]\n\n        # Obtain the ensembleID, by using a SelexSample object:\n        selexSample = selexDb.SelexSample(barcode, batch, cycle)\n        ensembleID = selexSample.getEnsembleID()\n\n        # Obtain the width of the motif:\n        motWidth=self.getWidth()\n\n        # Obtain the consensus sequence:\n        consensus=self.getConsensus()\n        consensusCount=self.consensusCount\n\n        # Insert a new entry into the Motifs table using a new mysql command,\n        # inserting analysisID, ensembleID, width, cycle, consensus sequence\n        # and consensus count:\n        if (ensembleID != None):\n            cmdStr = \"INSERT INTO Motifs (AnalysisID, EnsembleID, Width, SelexCycle, ConsensusSequence, ConsensusCount) VALUES (\" + str(analysisID) + \",\\\"\" + str(ensembleID) + \"\\\",\" + str(motWidth) + \",\" + str(cycle) + \",\\\"\" + consensus  + \"\\\",\" + str(consensusCount) + \");\"\n        else:\n            cmdStr = \"INSERT INTO Motifs (AnalysisID, Width, SelexCycle, ConsensusSequence, ConsensusCount) VALUES (\" + str(analysisID) + \",\" + str(motWidth) + \",\" + str(cycle) + \",\\\"\" + consensus  + \"\\\",\" + str(consensusCount) + \");\"\n    \n        # Run that command:\n        cursor=db.cursor()\n        cursor.execute(cmdStr)\n\n        # Obtain the new autoincremented motifID value:\n        newMotifID = db.insert_id()\n\n        # Insert data for the columns...\n        for columnIdx in range(len(self.matrix)):\n            currColumn = self.matrix[columnIdx]\n\n            # Calculate information content of that column:\n            ic = seq_utility.calc_IC(currColumn)\n\n            # Insert a new entry into MotifColumns, with the above motifID,\n            # columnIdx, information content, and A, C, G and T frequencies:\n            cmdStr = \"INSERT INTO MotifColumns (MotifID, ColumnNumber, InformationContent, A, C, G, T) VALUES (\" + str(newMotifID) + \",\" + str(columnIdx) + \",\" + str(ic) + \",\" + str(currColumn[0]) + \",\" + str(currColumn[1]) + \",\" + str(currColumn[2]) + \",\" + str(currColumn[3]) + \");\"\n    \n            # Run that command:\n            cursor=db.cursor()\n            cursor.execute(cmdStr)\n\n    def permuteMatrix(self):\n        \"\"\"Permutes the columns of this matrix.\"\"\"\n        random.shuffle(self.matrix)\n\n    def isCrap(self):\n        \"\"\"Returns True if this motif is dodgy, False otherwise.\"\"\"\n\n        # A bit tricky; Get a trimmed version of the motif, and then compute\n        # whether the motif is crap based on the trimmed version and the\n        # original version...\n\n        trimmedMot = self.trimLowIC(icThresh=0.5, copy=True)\n        if (self.eValue > 0.01):\n            return True\n        if (trimmedMot.getWidth() <= 10):\n            return False\n        if (self.eValue < 10**-30):\n            return False\n        motICs = trimmedMot.getIC_arr()\n        letters = trimmedMot.getConsensus()\n        lettersAtHighIC = {}\n        columnIdx = 0\n        while (columnIdx < trimmedMot.getWidth()):\n            currLetter = letters[columnIdx]\n            ic = motICs[columnIdx]\n            if (ic >= 1.5):\n                if (not lettersAtHighIC.has_key(currLetter)):\n                    lettersAtHighIC[currLetter] = 1\n            columnIdx += 1\n        if (len(lettersAtHighIC.keys()) >= 3):\n            return False\n        return True\n\n\nclass JASPAR_pwm(pwm):\n    \"\"\"A pwm derived from a high-throughput SELEX experiment.\"\"\"\n    def __init__(self, db, motifID):\n        super(JASPAR_pwm, self).__init__(None, dataType=\"\")\n\n        # Obtain the JASPAR ID and collection values for this motifID:\n        cmdStr = \"SELECT COLLECTION, BASE_ID, NAME, VERSION from MATRIX where ID = \" + str(motifID) + \";\"\n        cursor=db.cursor()\n        cursor.execute(cmdStr)\n        rows = cursor.fetchall()\n\n        assert(len(rows) > 0) # Otherwise motifID is an invalid input.\n\n        self.collection = rows[0][0]\n        self.jasparID = rows[0][1]\n        tfName = rows[0][2]\n        version = rows[0][3]\n\n        # Set the name of the matrix to the jaspar code and tf name:\n        self.setName(self.jasparID + \"_\" + str(version) + \"_\" + tfName)\n\n        # Obtain the motif data:\n        cmdStr = \"SELECT col, row, val from MATRIX_DATA where ID = \\\"\" + str(motifID) + \"\\\";\"\n        cursor=db.cursor()\n        cursor.execute(cmdStr)\n        rows = cursor.fetchall()\n\n        positions = map(lambda tup: tup[0], rows)\n        maxColNum = max(positions)\n\n        # Parse the output into the matrix attribute...\n\n        # Obtain the count matrix:\n        countMatrix = numpy.zeros((maxColNum, 4))\n        lett2col = {'A':0, 'C':1, 'G':2, 'T':3}\n        for tup in rows:\n            row = tup[0] - 1\n            col = lett2col[tup[1]]\n            countMatrix[row][col] = tup[2]\n\n        # Divide all entries by row sums to obtain freq matrix:\n        freqMatrix = numpy.zeros((maxColNum, 4))\n        for rowIdx in range(maxColNum):\n            rowSum = float(sum(countMatrix[rowIdx]))\n            for colIdx in range(4):\n                freqMatrix[rowIdx][colIdx] = \\\n                    (countMatrix[rowIdx][colIdx])/rowSum\n        \n        self.matrix = freqMatrix.tolist()\n\n\nclass SELEX_pwm(pwm):\n    \"\"\"A pwm derived from a high-throughput SELEX experiment.\"\"\"\n    def __init__(self, db, motifID):\n        super(SELEX_pwm, self).__init__(None, dataType=\"\")\n\n        # Obtain the cycle and consensusCount values for this motifID:\n        cmdStr = \"SELECT SelexCycle, ConsensusCount from Motifs where MotifID = \\\"\" + str(motifID) + \"\\\";\"\n        cursor=db.cursor()\n        cursor.execute(cmdStr)\n        rows = cursor.fetchall()\n\n        self.cycle = rows[0][0]\n        self.consensusCount = rows[0][1]\n\n        # Obtain the motif data:\n        cmdStr = \"SELECT ColumnNumber, A, C, G, T from MotifColumns where MotifID = \\\"\" + str(motifID) + \"\\\";\"\n        cursor=db.cursor()\n        cursor.execute(cmdStr)\n        rows = cursor.fetchall()\n        matrixData = list(rows)\n        matrixData.sort(cmpTups1)\n\n        # Obtain a name for the motif:\n        cmdStr = \"select tf.HGNC_Name, \\\"w\\\", m.Width, \\\"cyc\\\", m.SelexCycle, sa.BarcodeBatchAnalysed, sa.BarcodeAnalysed from Motifs m inner join SELEX_Analyses sa on m.AnalysisID = sa.AnalysisID inner join TranscriptionFactors tf on m.EnsembleID = tf.EnsembleID where m.MotifID = \" + str(motifID) + \";\"\n        cursor=db.cursor()\n        cursor.execute(cmdStr)\n\n        rows = cursor.fetchall()\n        name = reduce(lambda tok1, tok2: str(tok1) + \"_\" + str(tok2), rows[0])\n\n        self.setName(name)\n\n        # Parse the output into the matrix attribute:\n        matrix = map(lambda col: col[1:], matrixData)\n        self.matrix = matrix\n\n    def getConsCount(self):\n        return self.consensusCount\n\n\ndef cmpTups1(tup1, tup2):\n    if (tup1[0] < tup2[0]):\n        return -1\n    elif (tup1[0] == tup2[0]):\n        return 0\n    else:\n        return 1\n\n\nclass motifLibrary:\n    \"\"\"A library of motifs. Introduced on 9th November 2010 in order to allow\n    MEME-derived motifs to be added to an existing set of motifs more\n    seamlessly.\"\"\"\n\n    def __init__(self, inputLibrary):\n        self.motifs = {}\n        if (isinstance(inputLibrary, list)):\n            # Library specifies name of file containing motif locations =>\n            # initialise as such:\n            self.initFromMEME(inputLibrary)\n\n    def getMotif(self, motifName):\n        return self.motifs[motifName]\n\n    def getMotifs(self):\n        return self.motifs\n\n    def initFromMEME(self, motifLibraryList):\n        \"\"\"motifLibraryList is a list of strings specifying the absolute\n        paths of motifs in the input library.\"\"\"\n\n        # Set up the motif library from the input file...\n\n        # For each motif filename in the input library...\n        for currMotifFilename in motifLibraryList:\n            if (not os.path.exists(currMotifFilename)):\n                # Don't quit if a motif file isn't found; just skip it:\n                print >> sys.stderr, \"WARNING: Specified motif file \\\"\" + \\\n                    currMotifFilename + \"\\\" does not exist.\"\n            else:\n                # Attempt to generate a new motif object from that file, using\n                # the motif constructor:\n                try:\n                    currMotif = pwm(open(currMotifFilename))\n                    currMotifName = currMotif.getName()\n                    if (self.motifs.has_key(currMotifName)):\n                        print >> sys.stderr, \"WARNING: motif \\\"\" + \\\n                            currMotif.getName() + \\\n                            \"\\\" was encountered more than once.\" + \\\n                            \" Excluding second instance from the input library.\"\n                    else:\n                        # Non-redundant motif was successfully parsed => Add\n                        # it to the library of motifs:\n                        self.motifs[currMotifName] = currMotif\n                except ValueError, e:\n                    print >> sys.stderr, \"WARNING: ValueError occured \\\"\" + \\\n                        \"whilst parsing motif file \\\"\" + currMotifFilename + \\\n                        \"\\\". Excluding that motif from the input library.\"\n                    print >> sys.stderr, e\n\n    def addMotif(self, motif):\n        \"\"\"Add a single specified motif to this library.\"\"\"\n        assert(not self.motifs.has_key(motif.getName()))\n        self.motifs[motif.getName()] = motif\n\n\nclass scannedReg:\n    \"\"\"This class encapsulates the general idea of a genomic region that has\n    been scanned by a set of motifs.\"\"\"\n\n    def __init__(self, region):\n        # Store the attributes (in particular the genomic coordinates) of the\n        # genomic region:\n        self.reg = region # A BED_line object.\n        \n        # Set up an intially-empty dictionary of motif hits. It will be\n        # populated with motif name as keys and motifOccurence as values:\n        self.hits = {}\n\n    def addHit(self, motifHit):\n        \"\"\"Stores the specified motifOccurence object under it's name.\n        Throws an Exception if a motif by that name has already been\n        registered for this sequence.\"\"\"\n\n        if (self.hits.has_key(motifHit.getMotif().getName())):\n            raise Exception(\"Region already had motif instance of that name.\")\n        else:\n            self.hits[motifHit.getMotif().getName()] = motifHit\n\n    def getHit(self, motifName):\n        \"\"\"Returns the occurence of the specified motif for this region.\n        Returns None if no hits are registered for the region.\"\"\"\n        if (self.hits.has_key(motifName)):\n            return self.hits[motifName]\n        else:\n            return None\n\n    def getDisp(self, mot1_name, mot2_name):\n        \"\"\"Returns a (displacement, sameStrand) tuple showing the\n        displacement from motif1 to motif2 and whether they occur on the\n        same strand of this sequence. Returns None if the two motifs overlap.\n        Throws a KeyError exception if either motif is not present in the\n        sequence.\"\"\"\n        mot1_hit = self.hits[mot1_name]\n        mot2_hit = self.hits[mot2_name]\n        disp1to2 = mot1_hit.get_disp(mot2_hit)\n\n    def getBED(self):\n        \"\"\"Returns the BED_line object showing the coordinates of this\n        region.\"\"\"\n        return self.reg\n\n    def getMotCoords(self, motifName, flankWidth=0):\n        \"\"\"Returns a strand-specific BED_line object representing the\n        *genomic* coordinates of the occurrence of the specific motif in this\n        scanned region. Returns None if no motif hit exists in this region for\n        the specified motif.\"\"\"\n\n        motifHit = self.getHit(motifName)\n        if (motifHit == None):\n            return None\n\n        genomicHitLoc = chipseq_analysis.bestHit_scanner.getAbsHitCoords(self.getBED(), motifHit, flankWidth=flankWidth)\n        return genomicHitLoc\n", "meta": {"hexsha": "bc797f2adf9a6b71b5795f87f2b7f74e0e10c7d3", "size": 35194, "ext": "py", "lang": "Python", "max_stars_repo_path": "motifModule.py", "max_stars_repo_name": "tomwhi/snpCrmAnnotation", "max_stars_repo_head_hexsha": "61aaa63728d5b533fbe1d4dd919cfc21b7112bc7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "motifModule.py", "max_issues_repo_name": "tomwhi/snpCrmAnnotation", "max_issues_repo_head_hexsha": "61aaa63728d5b533fbe1d4dd919cfc21b7112bc7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "motifModule.py", "max_forks_repo_name": "tomwhi/snpCrmAnnotation", "max_forks_repo_head_hexsha": "61aaa63728d5b533fbe1d4dd919cfc21b7112bc7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0386803185, "max_line_length": 790, "alphanum_fraction": 0.6002159459, "include": true, "reason": "import numpy", "num_tokens": 8478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.16438044920366546}}
{"text": "import contextlib\nimport copy\nimport functools\nimport itertools\nimport json\nimport os\nimport re\nimport time\nimport warnings\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sympy as sy\nimport yaml\nfrom scipy.interpolate import UnivariateSpline, interp1d\nfrom scipy.optimize import BFGS, basinhopping, minimize\n\nfrom tf_pwa.adaptive_bins import AdaptiveBound, cal_chi2\nfrom tf_pwa.amp import (\n    AmplitudeModel,\n    DecayChain,\n    DecayGroup,\n    HelicityDecay,\n    get_decay,\n    get_particle,\n)\nfrom tf_pwa.applications import (\n    cal_hesse_correct,\n    cal_hesse_error,\n    corr_coef_matrix,\n    fit,\n    fit_fractions,\n    force_pos_def,\n    num_hess_inv_3point,\n)\nfrom tf_pwa.cal_angle import prepare_data_from_decay\nfrom tf_pwa.data import (\n    data_index,\n    data_merge,\n    data_shape,\n    data_split,\n    data_to_numpy,\n    load_data,\n    save_data,\n)\nfrom tf_pwa.fit import FitResult\nfrom tf_pwa.fit_improve import minimize as my_minimize\nfrom tf_pwa.model import FCN, CombineFCN, MixLogLikehoodFCN, Model, Model_new\nfrom tf_pwa.model.cfit import Model_cfit, Model_cfit_cached\nfrom tf_pwa.model.opt_int import ModelCachedAmp, ModelCachedInt\nfrom tf_pwa.particle import split_particle_type\nfrom tf_pwa.root_io import has_uproot, save_dict_to_root\nfrom tf_pwa.utils import time_print\nfrom tf_pwa.variable import Variable, VarsManager\n\nfrom .base_config import BaseConfig\nfrom .data import load_data_mode\nfrom .decay_config import DecayConfig\n\n\nclass ConfigLoader(BaseConfig):\n    \"\"\"class for loading config.yml\"\"\"\n\n    def __init__(self, file_name, vm=None, share_dict=None):\n        if share_dict is None:\n            share_dict = {}\n        super().__init__(file_name, share_dict)\n        self.config[\"data\"] = self.config.get(\"data\", {})\n        self.share_dict = share_dict\n        self.decay_config = DecayConfig(self.config, share_dict)\n        self.dec = self.decay_config.dec\n        self.particle_map, self.particle_property = (\n            self.decay_config.particle_map,\n            self.decay_config.particle_property,\n        )\n        self.top, self.finals = self.decay_config.top, self.decay_config.finals\n        self.full_decay = self.decay_config.full_decay\n        self.decay_struct = self.decay_config.decay_struct\n        if vm is None:\n            vm = VarsManager()\n        self.vm = vm\n        self.amps = {}\n        self.cached_data = None\n        self.bound_dic = {}\n        self.gauss_constr_dic = {}\n        self.init_value = {}\n        self.plot_params = PlotParams(\n            self.config.get(\"plot\", {}), self.decay_struct\n        )\n        self._neglect_when_set_params = []\n        self.data = load_data_mode(self[\"data\"], self.decay_struct)\n        self.inv_he = None\n        self._Ngroup = 1\n        self.cached_fcn = {}\n        self.extra_constrains = {}\n        self.resolution_size = self.config.get(\"data\", {}).get(\n            \"resolution_size\", 1\n        )\n\n    @staticmethod\n    def load_config(file_name, share_dict={}):\n        if isinstance(file_name, dict):\n            return copy.deepcopy(file_name)\n        if isinstance(file_name, str):\n            if file_name in share_dict:\n                return ConfigLoader.load_config(share_dict[file_name])\n            with open(file_name) as f:\n                ret = yaml.load(f, yaml.FullLoader)\n            return ret\n        raise TypeError(\"not support config {}\".format(type(file_name)))\n\n    def get_data_file(self, idx):\n        if idx in self.config[\"data\"]:\n            ret = self.config[\"data\"][idx]\n        else:\n            ret = None\n        return ret\n\n    def get_dat_order(self, standard=False):\n        order = self.config[\"data\"].get(\"dat_order\", None)\n        if order is None:\n            order = list(self.decay_struct.outs)\n        else:\n            order = [get_particle(str(i)) for i in order]\n        if not standard:\n            return order\n\n        re_map = self.decay_struct.get_chains_map()\n\n        def particle_item():\n            for j in re_map:\n                for k, v in j.items():\n                    for s, l in v.items():\n                        yield s, l\n\n        new_order = []\n        for i in order:\n            for s, l in particle_item():\n                if str(l) == str(i):\n                    new_order.append(s)\n                    break\n            else:\n                new_order.append(i)\n        return new_order\n\n    def get_data_mode(self):\n        data_config = self.config.get(\"data\", {})\n        data = data_config.get(\"data\", \"\")\n        if isinstance(data, str):\n            mode = \"single\"\n        elif isinstance(data, list):\n            data_i = data[0]\n            if isinstance(data_i, str):\n                return \"single\"\n            elif isinstance(data_i, list):\n                return \"multi\"\n\n    @functools.lru_cache()\n    def get_data(self, idx):\n        return self.data.get_data(idx)\n\n    def load_cached_data(self, file_name=None):\n        return self.data.load_cached_data(file_name)\n\n    def save_cached_data(self, data, file_name=None):\n        self.data.save_cached_data(data, file_name=file_name)\n\n    def get_all_data(self):\n        datafile = [\"data\", \"phsp\", \"bg\", \"inmc\"]\n        self.load_cached_data()\n        data, phsp, bg, inmc = [self.get_data(i) for i in datafile]\n        self._Ngroup = len(data)\n        assert len(phsp) == self._Ngroup\n        if bg is None:\n            bg = [None] * self._Ngroup\n        if inmc is None:\n            inmc = [None] * self._Ngroup\n        assert len(bg) == self._Ngroup\n        assert len(inmc) == self._Ngroup\n        self.save_cached_data(dict(zip(datafile, [data, phsp, bg, inmc])))\n        return data, phsp, bg, inmc\n\n    def get_data_index(self, sub, name):\n        return self.plot_params.get_data_index(sub, name)\n\n    def get_phsp_noeff(self):\n        if \"phsp_noeff\" in self.config[\"data\"]:\n            phsp_noeff = self.get_data(\"phsp_noeff\")\n            assert len(phsp_noeff) == 1\n            return phsp_noeff[0]\n        warnings.warn(\n            \"No data file as 'phsp_noeff', using the first 'phsp' file instead.\"\n        )\n        return self.get_data(\"phsp\")[0]\n\n    def get_phsp_plot(self):\n        if \"phsp_plot\" in self.config[\"data\"]:\n            assert len(self.config[\"data\"][\"phsp_plot\"]) == len(\n                self.config[\"data\"][\"phsp\"]\n            )\n            return self.get_data(\"phsp_plot\")\n        return self.get_data(\"phsp\")\n\n    def get_decay(self, full=True):\n        if full:\n            return self.full_decay\n        else:\n            return self.decay_struct\n\n    @functools.lru_cache()\n    def get_amplitude(self, vm=None, name=\"\"):\n        use_tf_function = self.config.get(\"data\", {}).get(\n            \"use_tf_function\", False\n        )\n        decay_group = self.full_decay\n        self.check_valid_jp(decay_group)\n        if vm is None:\n            vm = self.vm\n        if vm in self.amps:\n            return self.amps[vm]\n        amp = AmplitudeModel(\n            decay_group, vm=vm, name=name, use_tf_function=use_tf_function\n        )\n        self.add_constraints(amp)\n        self.amps[vm] = amp\n        return amp\n\n    def check_valid_jp(self, decay_group):\n        for decay_chain in decay_group:\n            for dec in decay_chain:\n                if isinstance(dec, HelicityDecay):\n                    dec.check_valid_jp()\n\n    def add_constraints(self, amp):\n        constrains = self.config.get(\"constrains\", {})\n        if constrains is None:\n            constrains = {}\n        self.add_decay_constraints(amp, constrains.get(\"decay\", {}))\n        self.add_particle_constraints(amp, constrains.get(\"particle\", {}))\n        self.add_fix_var_constraints(amp, constrains.get(\"fix_var\", {}))\n        self.add_free_var_constraints(amp, constrains.get(\"free_var\", []))\n        self.add_var_range_constraints(amp, constrains.get(\"var_range\", {}))\n        self.add_var_equal_constraints(amp, constrains.get(\"var_equal\", []))\n        for k, v in self.extra_constrains.items():\n            v(amp, constrains.get(k, {}))\n\n    def register_extra_constrains(self, name, f=None):\n        \"\"\"\n        add extra_constrains\n        \"\"\"\n\n        def _reg(g):\n            self.extra_constrains[name] = g\n            return g\n\n        if f is None:\n            return _reg\n        else:\n            return _reg(f)\n\n    def add_fix_var_constraints(self, amp, dic=None):\n        if dic is None:\n            dic = {}\n        for k, v in dic.items():\n            print(\"fix var: \", k, \"=\", v)\n            amp.vm.set_fix(k, v)\n\n    def add_free_var_constraints(self, amp, dic=None):\n        if dic is None:\n            dic = []\n        for k in dic:\n            print(\"free var: \", k)\n            amp.vm.set_fix(k, unfix=True)\n\n    def add_var_range_constraints(self, amp, dic=None):\n        if dic is None:\n            dic = {}\n        for k, v in dic.items():\n            print(\"variable range: \", k, \" in \", v)\n            self.bound_dic[k] = v\n\n    def add_var_equal_constraints(self, amp, dic=None):\n        if dic is None:\n            dic = []\n        for k in dic:\n            print(\"same value:\", k)\n            amp.vm.set_same(k)\n\n    def add_decay_constraints(self, amp, dic=None):\n        if dic is None:\n            dic = {}\n        fix_total_idx = dic.get(\"fix_chain_idx\", 0)\n        fix_total_val = dic.get(\"fix_chain_val\", np.random.uniform(0, 2))\n\n        fix_decay = amp.decay_group.get_decay_chain(fix_total_idx)\n        # fix which total factor\n        fix_decay.total.set_fix_idx(fix_idx=0, fix_vals=(fix_total_val, 0.0))\n\n    def add_particle_constraints(self, amp, dic=None):\n        if dic is None:\n            dic = {}\n\n        res_dec = {}\n        for d in amp.decay_group:\n            for p_i in d.inner:\n                i = str(p_i)\n                res_dec[i] = d\n                prefix_map = {\n                    \"m0\": \"mass\",\n                    \"g0\": \"width\",\n                    \"m_\": \"mass_\",\n                    \"g_\": \"width_\",\n                }\n                particle_config = self.config[\"particle\"][i].copy()\n\n                params_dic = self.config[\"particle\"][i].get(\"params\", None)\n                if params_dic is None:\n                    params_dic = {}\n                for name in list(particle_config):\n                    for prefix_i in prefix_map.keys():\n                        if name.startswith(prefix_i):\n                            name2 = (\n                                prefix_map[prefix_i] + name[len(prefix_i) :]\n                            )\n                            params_dic[name2] = particle_config[name]\n                    for prefix_i in prefix_map.values():\n                        if name.startswith(prefix_i):\n                            params_dic[name] = particle_config[name]\n\n                variable_prefix = p_i.get_variable_name()\n\n                set_prefix_constrains(self.vm, p_i, params_dic, self)\n\n                simple_map = {\"m\": \"mass\", \"g\": \"width\"}\n\n                gauss_constr = particle_config.get(\"gauss_constr\", None)\n                if gauss_constr is not None:\n                    assert isinstance(gauss_constr, dict)\n                    for k, v in gauss_constr.items():\n                        if v:\n                            name = simple_map.get(k, k)\n                            full_name = variable_prefix + name\n                            var0 = self.vm.get(full_name)\n                            self.gauss_constr_dic[full_name] = (\n                                var0.value,\n                                v,\n                            )\n                        else:\n                            raise Exception(\n                                f\"Need sigma of {k} of {p_i} when adding gaussian constraint\"\n                            )\n\n                if isinstance(p_i.mass, Variable) or isinstance(\n                    p_i.width, Variable\n                ):\n                    if (\n                        \"float\" in self.config[\"particle\"][i]\n                        and self.config[\"particle\"][i][\"float\"]\n                    ):\n                        if \"m\" in self.config[\"particle\"][i][\"float\"]:\n                            p_i.mass.freed()  # set_fix(i+'_mass',unfix=True)\n                            if \"m_max\" in self.config[\"particle\"][i]:\n                                upper = self.config[\"particle\"][i][\"m_max\"]\n                            # elif m_sigma is not None:\n                            #    upper = self.config[\"particle\"][i][\"m0\"] + 10 * m_sigma\n                            else:\n                                upper = None\n                            if \"m_min\" in self.config[\"particle\"][i]:\n                                lower = self.config[\"particle\"][i][\"m_min\"]\n                            # elif m_sigma is not None:\n                            #    lower = self.config[\"particle\"][i][\"m0\"] - 10 * m_sigma\n                            else:\n                                lower = None\n                            self.bound_dic[str(p_i.mass)] = (lower, upper)\n                        else:\n                            self._neglect_when_set_params.append(str(p_i.mass))\n                        if \"g\" in self.config[\"particle\"][i][\"float\"]:\n                            p_i.width.freed()  # amp.vm.set_fix(i+'_width',unfix=True)\n                            if \"g_max\" in self.config[\"particle\"][i]:\n                                upper = self.config[\"particle\"][i][\"g_max\"]\n                            # elif g_sigma is not None:\n                            #    upper = self.config[\"particle\"][i][\"g0\"] + 10 * g_sigma\n                            else:\n                                upper = None\n                            if \"g_min\" in self.config[\"particle\"][i]:\n                                lower = self.config[\"particle\"][i][\"g_min\"]\n                            # elif g_sigma is not None:\n                            #    lower = self.config[\"particle\"][i][\"g0\"] - 10 * g_sigma\n                            else:\n                                lower = None\n                            self.bound_dic[str(p_i.width)] = (lower, upper)\n                        else:\n                            self._neglect_when_set_params.append(\n                                str(p_i.width)\n                            )\n                    else:\n                        self._neglect_when_set_params.append(\n                            i + \"_mass\"\n                        )  # p_i.mass.name\n                        self._neglect_when_set_params.append(\n                            i + \"_width\"\n                        )  # p_i.width.name\n\n                # share helicity variables\n                if \"coef_head\" in self.config[\"particle\"][i]:\n                    coef_head = self.config[\"particle\"][i][\"coef_head\"]\n                    if coef_head in res_dec:\n                        d_coef_head = res_dec[coef_head]\n                        for j, h in zip(d, d_coef_head):\n                            if i in [str(jj) for jj in j.outs] or i is str(\n                                j.core\n                            ):\n                                h.g_ls.sameas(j.g_ls)\n                        # share total radium\n                        d_coef_head.total.r_shareto(d.total)\n                    else:\n                        self.config[\"particle\"][coef_head][\"coef_head\"] = i\n\n        equal_params = dic.get(\"equal\", {})\n        for k, v in equal_params.items():\n            for vi in v:\n                a = []\n                for i in amp.decay_group.resonances:\n                    if str(i) in vi:\n                        a.append(i)\n                a0 = a.pop(0)\n                arg = getattr(a0, k)\n                for i in a:\n                    arg_i = getattr(i, k)\n                    if isinstance(arg_i, Variable):\n                        arg_i.sameas(arg)\n\n    @functools.lru_cache()\n    def _get_model(self, vm=None, name=\"\"):\n        amp = self.get_amplitude(vm=vm, name=name)\n        model_name = self.config[\"data\"].get(\"model\", \"auto\")\n        w_bkg, w_inmc = self._get_bg_weight()\n        model = []\n        if model_name == \"cfit\":\n            bg_function = self.config[\"data\"].get(\"bg_function\", None)\n            eff_function = self.config[\"data\"].get(\"eff_function\", None)\n            w_bkg = self.config[\"data\"][\"bg_frac\"]\n            if not isinstance(w_bkg, list):\n                w_bkg = [w_bkg]\n            for wb in w_bkg:\n                if self.config[\"data\"].get(\"cached_amp\", False):\n                    model.append(\n                        Model_cfit_cached(amp, wb, bg_function, eff_function)\n                    )\n                else:\n                    model.append(\n                        Model_cfit(amp, wb, bg_function, eff_function)\n                    )\n        elif \"inmc\" in self.config[\"data\"]:\n            float_wmc = self.config[\"data\"].get(\n                \"float_inmc_ratio_in_pdf\", False\n            )\n            if not isinstance(float_wmc, list):\n                float_wmc = [float_wmc] * self._Ngroup\n            assert len(float_wmc) == self._Ngroup\n            for wb, wi, fw in zip(w_bkg, w_inmc, float_wmc):\n                model.append(Model_new(amp, wb, wi, fw))\n        elif self.config[\"data\"].get(\"cached_int\", False):\n            for wb in w_bkg:\n                model.append(ModelCachedInt(amp, wb))\n        elif self.config[\"data\"].get(\"cached_amp\", False):\n            for wb in w_bkg:\n                model.append(ModelCachedAmp(amp, wb))\n        else:\n            for wb in w_bkg:\n                model.append(\n                    Model(amp, wb, resolution_size=self.resolution_size)\n                )\n        return model\n\n    def _get_bg_weight(self, data=None, bg=None, display=True):\n        w_bkg = self.config[\"data\"].get(\"bg_weight\", 0.0)\n        if not isinstance(w_bkg, list):\n            w_bkg = [w_bkg] * self._Ngroup\n        assert len(w_bkg) == self._Ngroup\n        w_inmc = self.config[\"data\"].get(\"inject_ratio\", 0.0)\n        if not isinstance(w_inmc, list):\n            w_inmc = [w_inmc] * self._Ngroup\n        assert len(w_inmc) == self._Ngroup\n        weight_scale = self.config[\"data\"].get(\"weight_scale\", False)  # ???\n        if weight_scale:\n            data = data if data is not None else self.get_data(\"data\")\n            bg = bg if bg is not None else self.get_data(\"bg\")\n            tmp = []\n            for wb, dt, sb in zip(w_bkg, data, bg):\n                if isinstance(wb, str):\n                    wb = self.data.load_weight_file(wb)\n                tmp.append(wb * data_shape(dt) / data_shape(sb))\n            w_bkg = tmp\n            if display:\n                print(\"background weight:\", w_bkg)\n        else:\n            tmp = []\n            for wb in w_bkg:\n                if isinstance(wb, str):\n                    wb = self.data.load_weight_file(wb)\n                tmp.append(wb)\n            w_bkg = tmp\n        return w_bkg, w_inmc\n\n    def get_fcn(self, all_data=None, batch=65000, vm=None, name=\"\"):\n        if all_data is None:\n            if vm in self.cached_fcn:\n                return self.cached_fcn[vm]\n            data, phsp, bg, inmc = self.get_all_data()\n        else:\n            data, phsp, bg, inmc = all_data\n        self._Ngroup = len(data)\n        if inmc is None:\n            inmc = [None] * self._Ngroup\n        if bg is None:\n            bg = [None] * self._Ngroup\n        model = self._get_model(vm=vm, name=name)\n        fcns = []\n        # print(self.config[\"data\"].get(\"using_mix_likelihood\", False))\n        if self.config[\"data\"].get(\"using_mix_likelihood\", False):\n            print(\"  Using Mix Likelihood\")\n            fcn = MixLogLikehoodFCN(\n                model,\n                data,\n                phsp,\n                bg=bg,\n                batch=batch,\n                gauss_constr=self.gauss_constr_dic,\n            )\n            if all_data is None:\n                self.cached_fcn[vm] = fcn\n            return fcn\n        for md, dt, mc, sb, ij in zip(model, data, phsp, bg, inmc):\n            if self.config[\"data\"].get(\"model\", \"auto\") == \"cfit\":\n                fcns.append(\n                    FCN(\n                        md,\n                        dt,\n                        mc,\n                        batch=batch,\n                        inmc=ij,\n                        gauss_constr=self.gauss_constr_dic,\n                    )\n                )\n            else:\n                fcns.append(\n                    FCN(\n                        md,\n                        dt,\n                        mc,\n                        bg=sb,\n                        batch=batch,\n                        inmc=ij,\n                        gauss_constr=self.gauss_constr_dic,\n                    )\n                )\n        if len(fcns) == 1:\n            fcn = fcns[0]\n        else:\n            fcn = CombineFCN(fcns=fcns, gauss_constr=self.gauss_constr_dic)\n        if all_data is None:\n            self.cached_fcn[vm] = fcn\n        return fcn\n\n    def get_ndf(self):\n        amp = self.get_amplitude()\n        args_name = amp.vm.trainable_vars\n        return len(args_name)\n\n    @staticmethod\n    def reweight_init_value(amp, phsp, ns=None):\n        \"\"\"reset decay chain total and make the integration to be ns\"\"\"\n        total = [i.total for i in amp.decay_group]\n        n_phsp = data_shape(phsp)\n        weight = np.array(phsp.get(\"weight\", [1] * n_phsp))\n        sw = np.sum(weight)\n        if ns is None:\n            ns = [1] * len(total)\n        elif isinstance(ns, (int, float)):\n            ns = [ns / len(total)] * len(total)\n        for i in total:\n            i.set_rho(1.0)\n        pw = amp.partial_weight(phsp)\n        for i, w, ni in zip(total, pw, ns):\n            i.set_rho(np.sqrt(ni / np.sum(weight * w) * sw))\n\n    @time_print\n    def fit(\n        self,\n        data=None,\n        phsp=None,\n        bg=None,\n        inmc=None,\n        batch=65000,\n        method=\"BFGS\",\n        check_grad=False,\n        improve=False,\n        reweight=False,\n        maxiter=None,\n    ):\n        if data is None and phsp is None:\n            data, phsp, bg, inmc = self.get_all_data()\n            fcn = self.get_fcn(batch=batch)\n        else:\n            fcn = self.get_fcn([data, phsp, bg, inmc], batch=batch)\n        # print(\"sss\")\n        amp = self.get_amplitude()\n        print(\"decay chains included: \")\n        for i in self.full_decay:\n            ls_list = [getattr(j, \"get_ls_list\", lambda x: None)() for j in i]\n            print(\"  \", i, \" ls: \", *ls_list)\n        if reweight:\n            ConfigLoader.reweight_init_value(\n                amp, phsp[0], ns=data_shape(data[0])\n            )\n\n        print(\"\\n########### initial parameters\")\n        print(json.dumps(amp.get_params(), indent=2), flush=True)\n        print(\"initial NLL: \", fcn({}))  # amp.get_params()))\n        # fit configure\n        # self.bound_dic[\"\"] = (,)\n        self.fit_params = fit(\n            fcn=fcn,\n            method=method,\n            bounds_dict=self.bound_dic,\n            check_grad=check_grad,\n            improve=False,\n            maxiter=maxiter,\n        )\n        if self.fit_params.hess_inv is not None:\n            self.inv_he = self.fit_params.hess_inv\n        return self.fit_params\n\n    def reinit_params(self):\n        vm = self.get_amplitude().vm\n        vm.refresh_vars(init_val=self.init_value, bound_dic=self.bound_dic)\n\n    def fitNtimes(self, N, *args, **kwargs):\n        for i in range(N):\n            self.reinit_params()\n            fit_result = self.fit(*args, **kwargs)\n            fit_pars = json.dumps(fit_result.params, indent=2)\n            print(fit_pars, flush=True)\n\n    def get_params_error(\n        self,\n        params=None,\n        data=None,\n        phsp=None,\n        bg=None,\n        inmc=None,\n        batch=10000,\n        using_cached=False,\n        method=None,\n        force_pos=True,\n        correct_params=None,\n    ):\n        \"\"\"\n        calculate parameters error\n        \"\"\"\n        if params is None:\n            params = {}\n        if correct_params is None:\n            correct_params = []\n            if method is None:\n                method = \"correct\"\n        if data is None:\n            data, phsp, bg, inmc = self.get_all_data()\n        if hasattr(params, \"params\"):\n            params = getattr(params, \"params\")\n        fcn = self.get_fcn([data, phsp, bg, inmc], batch=batch)\n        if using_cached and self.inv_he is not None:\n            hesse_error = np.sqrt(np.fabs(self.inv_he.diagonal())).tolist()\n        elif method == \"3-point\":\n            self.inv_he = num_hess_inv_3point(fcn, params)\n            diag_he = self.inv_he.diagonal()\n            hesse_error = np.sqrt(np.fabs(diag_he)).tolist()\n        elif method == \"correct\":\n            h = cal_hesse_correct(fcn, params, correct_params)\n            if force_pos:\n                self.inv_he = force_pos_def(h)\n            else:\n                self.inv_he = np.linalg.pinv(h)\n            diag_he = self.inv_he.diagonal()\n            hesse_error = np.sqrt(np.fabs(diag_he)).tolist()\n        else:\n            hesse_error, self.inv_he = cal_hesse_error(\n                fcn,\n                params,\n                check_posi_def=True,\n                save_npy=True,\n                force_pos=force_pos,\n            )\n        # print(\"parameters order\")\n        # print(fcn.model.Amp.vm.trainable_vars)\n        # print(\"error matrix:\")\n        # print(self.inv_he)\n        # print(\"correlation matrix:\")\n        # print(corr_coef_matrix(self.inv_he))\n        print(\"hesse_error:\", hesse_error)\n        err = dict(zip(fcn.vm.trainable_vars, hesse_error))\n        if hasattr(self, \"fit_params\"):\n            self.fit_params.set_error(err)\n        return err\n\n    @classmethod\n    def register_function(cls, name=None):\n        def _f(f):\n            my_name = name\n            if my_name is None:\n                my_name = f.__name__\n            if hasattr(cls, my_name):\n                warnings.warn(\"override function {}\".format(name))\n            setattr(cls, my_name, f)\n            return f\n\n        return _f\n\n    def get_chain(self, idx):\n        decay_group = self.full_decay\n        return decay_group.get_decay_chain(idx)\n\n    def get_chain_property(self, idx, display=True):\n        \"\"\"Get chain name and curve style in plot\"\"\"\n        chain = self.get_chain(idx)\n        for i in chain:\n            curve_style = i.curve_style\n            break\n        combine = []\n        for i in chain:\n            if i.core == chain.top:\n                combine = list(i.outs)\n        names = []\n        displays = []\n        for i in combine:\n            pro = self.particle_property[str(i)]\n            names.append(str(i))\n            displays.append(pro.get(\"display\", str(i)))\n        if display:\n            return \" \".join(displays), curve_style\n        return \"_\".join(names), curve_style\n\n    def cal_fitfractions(\n        self, params={}, mcdata=None, res=None, exclude_res=[], batch=25000\n    ):\n        if hasattr(params, \"params\"):\n            params = getattr(params, \"params\")\n        if mcdata is None:\n            mcdata = self.get_phsp_noeff()\n        amp = self.get_amplitude()\n        if res is None:\n            res = sorted(\n                list(set([str(i) for i in amp.res]) - set(exclude_res))\n            )\n        frac, err_frac = fit_fractions(\n            amp, mcdata, self.inv_he, params, batch, res\n        )\n        return frac, err_frac\n\n    def cal_signal_yields(self, params={}, mcdata=None, batch=25000):\n        if hasattr(params, \"params\"):\n            params = getattr(params, \"params\")\n        if mcdata is None:\n            mcdata = self.get_data(\"phsp\")\n        amp = self.get_amplitude()\n        fracs = [\n            fit_fractions(amp, i, self.inv_he, params, batch) for i in mcdata\n        ]\n        data = self.get_data(\"data\")\n        bg = self.get_data(\"bg\")\n        if bg is None:\n            N_total = [data_shape(i) for i in data]\n            for i in data:\n                N_data = data_shape(i)\n                N_total.append((N_data, np.sqrt(N_data)))\n        else:\n            bg_weight, _ = self._get_bg_weight(data, bg)\n            N_total = []\n            for i, j, w in zip(data, bg, bg_weight):\n                N_data = data_shape(i)\n                N_bg = data_shape(j)\n                N_total.append(\n                    (N_data - w * N_bg, np.sqrt(N_data + w * w * N_bg))\n                )\n\n        N_sig_s = []\n        for frac_e, N_e in zip(fracs, N_total):\n            frac, frac_err = frac_e\n            N, N_err = N_e\n            N_sig = {}\n            for i in frac:\n                N_sig[i] = (\n                    frac[i] * N,\n                    np.sqrt(\n                        (N * frac_err.get(i, 0.0)) ** 2\n                        + (N_err * frac[i]) ** 2\n                    ),\n                )\n            N_sig_s.append(N_sig)\n        return N_sig_s\n\n    def likelihood_profile(self, var, var_min, var_max, N=100):\n        params = self.get_params()\n        var0 = params[var]\n        delta_var = (var_max - var_min) / N\n        vm = self.get_amplitude().vm\n        unfix = var in vm.get_all_dic(True)\n        nlls_up = []\n        vars_up = []\n        while var0 <= var_max:\n            vm.set_fix(var, var0)\n            fit_result = self.fit()\n            vars_up.append(var0)\n            nlls_up.append(fit_result.min_nll)\n            var0 += delta_var\n        self.set_params(params)\n        var0 = params[var] - delta_var\n        vars_down = []\n        nlls_down = []\n        while var0 >= var_min:\n            vm.set_fix(var, var0)\n            fit_result = self.fit()\n            vars_down.append(var0)\n            nlls_down.append(fit_result.min_nll)\n            var0 -= delta_var\n        self.set_params(params)\n        vm.set_fix(var, params[var], unfix=unfix)\n        return vars_down[::-1] + vars_up, nlls_down[::-1] + nlls_up\n\n    def get_params(self, trainable_only=False):\n        return self.get_amplitude().get_params(trainable_only)\n\n    def set_params(self, params, neglect_params=None):\n        if isinstance(params, str):\n            if params == \"\":\n                return False\n            try:\n                with open(params) as f:\n                    params = yaml.safe_load(f)\n            except Exception as e:\n                print(e)\n                return False\n        if hasattr(params, \"params\"):\n            params = params.params\n        if isinstance(params, dict):\n            if \"value\" in params:\n                params = params[\"value\"]\n        amplitude = self.get_amplitude()\n        ret = params.copy()\n        if neglect_params is None:\n            neglect_params = self._neglect_when_set_params\n        if len(neglect_params) != 0:\n            # warnings.warn(\"Neglect {} when setting params.\".format(neglect_params))\n            for v in params:\n                if v in self._neglect_when_set_params:\n                    del ret[v]\n        amplitude.set_params(ret)\n        return True\n\n    def save_params(self, file_name):\n        params = self.get_params()\n        val = {k: float(v) for k, v in params.items()}\n        with open(file_name, \"w\") as f:\n            json.dump(val, f, indent=2)\n\n    @contextlib.contextmanager\n    def params_trans(self):\n        with self.vm.error_trans(self.inv_he) as f:\n            yield f\n\n\ndef set_prefix_constrains(vm, base, params_dic, self):\n    prefix = base.get_variable_name()\n    p_list = []\n    for v in params_dic:\n        vname = v\n        for tail in [\"_range\", \"_sigma\", \"_free\", \"_constr\", \"_min\", \"_max\"]:\n            if v.endswith(tail):\n                vname = v[: -len(tail)]\n                break\n\n        if vname not in p_list:\n            # print(vname, v)\n            p_list.append(vname)\n            vv = base.get_var(vname)\n            # print(vv, prefix + vname)\n            # if isinstance(vv, Variable):# getattr(p_i, vname)\n            if vv is None:\n                continue\n            p_sigma = params_dic.get(vname + \"_sigma\", None)\n            if vname in params_dic and params_dic[vname] is not None:\n                p_value = params_dic[vname]\n                vv.set_value(p_value)\n                if p_sigma is None:\n                    self.init_value[vname] = p_value\n                else:\n                    self.init_value[vname] = [p_value, p_sigma]\n            else:\n                p_value = None\n            p_free = params_dic.get(vname + \"_free\", None)\n            if p_free:\n                vv.freed()\n            elif p_free is False:\n                vv.fixed()\n            p_range = vname + \"_range\"\n            if p_range in params_dic and params_dic[p_range] is not None:\n                lower, upper = params_dic[p_range]\n                self.bound_dic[vv.name] = (lower, upper)\n                # vm.set_bound({vv.name: (lower, upper)})\n            else:\n                lower = params_dic.get(vname + \"_min\")\n                upper = params_dic.get(vname + \"_max\")\n                # print(lower, upper)\n                if lower is not None or upper is not None:\n                    self.bound_dic[vv.name] = (lower, upper)\n                    # vm.set_bound({vv.name: (lower, upper)})\n\n                # self.bound_dic[vv.name] = (lower, upper)\n            # elif p_sigma is not None and p_value is not None:\n            #    p_10sigma = 10 * p_sigma\n            #    self.bound_dic[vv.name] = (\n            #        p_value - p_10sigma,\n            #        p_value + p_10sigma,\n            #    )\n            p_constr = vname + \"_constr\"\n            if p_constr in params_dic and params_dic[p_constr] is not None:\n                if params_dic[p_constr]:\n                    if p_value is None:\n                        raise Exception(\n                            \"Need central value of {0} of {1} when adding gaussian constraint\".format(\n                                vname, prefix\n                            )\n                        )\n                    if p_sigma is None:\n                        raise Exception(\n                            \"Need sigma of {0} of {1} when adding gaussian constraint\".format(\n                                vname, prefix\n                            )\n                        )\n                    self.gauss_constr_dic[vv.name] = (\n                        params_dic[vname],\n                        p_sigma,\n                    )\n\n\ndef validate_file_name(s):\n    rstr = r\"[\\/\\\\\\:\\*\\?\\\"\\<\\>\\|]\"  # '/ \\ : * ? \" < > |'\n    name = re.sub(rstr, \"_\", s)\n    return name\n\n\nclass PlotParams(dict):\n    def __init__(self, plot_config, decay_struct):\n        self.config = plot_config\n        self.defaults_config = {}\n        self.defaults_config.update(self.config.get(\"config\", {}))\n        self.decay_struct = decay_struct\n        chain_map = self.decay_struct.get_chains_map()\n        self.re_map = {}\n        for i in chain_map:\n            for _, j in i.items():\n                for k, v in j.items():\n                    self.re_map[v] = k\n        self.params = []\n        for i in self.get_mass_vars():\n            self.params.append(i)\n        for i in self.get_angle_vars():\n            self.params.append(i)\n\n    def get_data_index(self, sub, name):\n        dec = self.decay_struct.topology_structure()\n        if sub == \"mass\":\n            p = get_particle(name)\n            return \"particle\", self.re_map.get(p, p), \"m\"\n        if sub == \"p\":\n            p = get_particle(name)\n            return \"particle\", self.re_map.get(p, p), \"p\"\n        if sub == \"angle\":\n            name_i = name.split(\"/\")\n            de_i = self.decay_struct.get_decay_chain(name_i)\n            p = get_particle(name_i[-1])\n            for i in de_i:\n                if p in i.outs:\n                    de = i\n                    break\n            else:\n                raise IndexError(\"not found such decay {}\".format(name))\n            return (\n                \"decay\",\n                de_i.standard_topology(),\n                self.re_map.get(de, de),\n                self.re_map.get(p, p),\n                \"ang\",\n            )\n        if sub == \"aligned_angle\":\n            name_i = name.split(\"/\")\n            de_i = self.decay_struct.get_decay_chain(name_i)\n            p = get_particle(name_i[-1])\n            for i in de_i:\n                if p in i.outs:\n                    de = i\n                    break\n            else:\n                raise IndexError(\"not found such decay {}\".format(name))\n            return (\n                \"decay\",\n                de_i.standard_topology(),\n                self.re_map.get(de, de),\n                self.re_map.get(p, p),\n                \"aligned_angle\",\n            )\n        raise ValueError(\"unknown sub {}\".format(sub))\n\n    def get_mass_vars(self):\n        mass = self.config.get(\"mass\", {})\n        x = sy.symbols(\"x\")\n        for k, v in mass.items():\n            display = v.get(\"display\", \"M({})\".format(k))\n            upper_ylim = v.get(\"upper_ylim\", None)\n            xrange = v.get(\"range\", None)\n            trans = v.get(\"trans\", None)\n            if trans is None:\n                trans = lambda x: x\n            else:\n                trans = sy.sympify(trans)\n                trans = sy.lambdify(x, trans, modules=\"numpy\")\n            units = v.get(\"units\", \"GeV\")\n            bins = v.get(\"bins\", self.defaults_config.get(\"bins\", 50))\n            legend = v.get(\"legend\", self.defaults_config.get(\"legend\", True))\n            yscale = v.get(\n                \"yscale\", self.defaults_config.get(\"yscale\", \"linear\")\n            )\n            yield {\n                \"name\": \"m_\" + k,\n                \"display\": display,\n                \"upper_ylim\": upper_ylim,\n                \"idx\": (\n                    \"particle\",\n                    self.re_map.get(get_particle(k), get_particle(k)),\n                    \"m\",\n                ),\n                \"legend\": legend,\n                \"range\": xrange,\n                \"bins\": bins,\n                \"trans\": trans,\n                \"units\": units,\n                \"yscale\": yscale,\n            }\n\n    def get_angle_vars(self):\n        ang = self.config.get(\"angle\", {})\n        for k, i in ang.items():\n            names = k.split(\"/\")\n            name = names[0]\n            number_decay = True\n            if len(names) > 1:\n                try:\n                    count = int(names[-1])\n                except ValueError:\n                    number_decay = False\n            else:\n                count = 0\n            if number_decay:\n                decay_chain, decay = None, None\n                part = self.re_map.get(get_particle(name), get_particle(name))\n                for decs in self.decay_struct:\n                    for dec in decs:\n                        if dec.core == get_particle(name):\n                            decay = dec.core.decay[count]\n                            for j in self.decay_struct:\n                                if decay in j:\n                                    decay_chain = j.standard_topology()\n                            decay = self.re_map.get(decay, decay)\n                part = decay.outs[0]\n            else:\n                _, decay_chain, decay, part, _ = self.get_data_index(\n                    \"angle\", k\n                )\n            for j, v in i.items():\n                display = v.get(\"display\", j)\n                upper_ylim = v.get(\"upper_ylim\", None)\n                theta = j\n                trans = lambda x: x\n                if \"cos\" in j:\n                    theta = j[4:-1]\n                    trans = np.cos\n                bins = v.get(\"bins\", self.defaults_config.get(\"bins\", 50))\n                xrange = v.get(\"range\", None)\n                legend = v.get(\n                    \"legend\", self.defaults_config.get(\"legend\", False)\n                )\n                yscale = v.get(\n                    \"yscale\", self.defaults_config.get(\"yscale\", \"linear\")\n                )\n                yield {\n                    \"name\": validate_file_name(k + \"_\" + j),\n                    \"display\": display,\n                    \"upper_ylim\": upper_ylim,\n                    \"idx\": (\"decay\", decay_chain, decay, part, \"ang\", theta),\n                    \"trans\": trans,\n                    \"bins\": bins,\n                    \"range\": xrange,\n                    \"legend\": legend,\n                    \"yscale\": yscale,\n                }\n\n    def get_params(self, params=None):\n        if params is None:\n            return self.params\n        if isinstance(params, str):\n            params = [params]\n        params_list = []\n        for i in self.params:\n            if i[\"display\"] in params:\n                params_list.append(i)\n        return params_list\n", "meta": {"hexsha": "33300a1a7ab5419868959af78ac9b5dded16c236", "size": 40612, "ext": "py", "lang": "Python", "max_stars_repo_path": "tf_pwa/config_loader/config_loader.py", "max_stars_repo_name": "jiangyi15/tf-pwa", "max_stars_repo_head_hexsha": "17980750407a89bfd694e0b4f470332a886a3de9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-05-10T15:17:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-16T07:40:06.000Z", "max_issues_repo_path": "tf_pwa/config_loader/config_loader.py", "max_issues_repo_name": "jiangyi15/tf-pwa", "max_issues_repo_head_hexsha": "17980750407a89bfd694e0b4f470332a886a3de9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 45, "max_issues_repo_issues_event_min_datetime": "2020-10-24T08:26:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T06:14:58.000Z", "max_forks_repo_path": "tf_pwa/config_loader/config_loader.py", "max_forks_repo_name": "jiangyi15/tf-pwa", "max_forks_repo_head_hexsha": "17980750407a89bfd694e0b4f470332a886a3de9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-10-24T06:41:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T01:29:49.000Z", "avg_line_length": 36.3255813953, "max_line_length": 102, "alphanum_fraction": 0.4931793559, "include": true, "reason": "import numpy,from scipy,import sympy", "num_tokens": 9035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3140505321516081, "lm_q1q2_score": 0.16438043912243297}}
{"text": "\"\"\"\nMain Lomb-Scargle Implementation\n\nThe ``lombscargle`` function here is essentially a sophisticated switch\nstatement for the various implementations available in this submodule\n\"\"\"\n\n__all__ = ['lombscargle', 'available_methods']\n\nimport warnings\n\nimport numpy as np\n\nfrom .slow_impl import lombscargle_slow\nfrom .fast_impl import lombscargle_fast\nfrom .scipy_impl import lombscargle_scipy\nfrom .chi2_impl import lombscargle_chi2\nfrom .fastchi2_impl import lombscargle_fastchi2\nfrom .cython_impl import lombscargle_cython\n\n\nMETHODS = {'slow': lombscargle_slow,\n           'fast': lombscargle_fast,\n           'chi2': lombscargle_chi2,\n           'scipy': lombscargle_scipy,\n           'fastchi2': lombscargle_fastchi2,\n           'cython': lombscargle_cython}\n\n\ndef available_methods():\n    methods = ['auto', 'slow', 'chi2', 'cython', 'fast', 'fastchi2']\n\n    # Scipy required for scipy algorithm (obviously)\n    try:\n        import scipy\n    except ImportError:\n        pass\n    else:\n        methods.append('scipy')\n    return methods\n\n\ndef _is_regular(frequency):\n    frequency = np.asarray(frequency)\n\n    if frequency.ndim != 1:\n        return False\n    elif len(frequency) == 1:\n        return True\n    else:\n        diff = np.diff(frequency)\n        return np.allclose(diff[0], diff)\n\n\ndef _get_frequency_grid(frequency, assume_regular_frequency=False):\n    \"\"\"Utility to get grid parameters from a frequency array\n\n    Parameters\n    ----------\n    frequency : array_like or Quantity\n        input frequency grid\n    assume_regular_frequency : bool (default = False)\n        if True, then do not check whether frequency is a regular grid\n\n    Returns\n    -------\n    f0, df, N : scalars\n        Parameters such that all(frequency == f0 + df * np.arange(N))\n    \"\"\"\n    frequency = np.asarray(frequency)\n    if frequency.ndim != 1:\n        raise ValueError(\"frequency grid must be 1 dimensional\")\n    elif len(frequency) == 1:\n        return frequency[0], frequency[0], 1\n    elif not (assume_regular_frequency or _is_regular(frequency)):\n        raise ValueError(\"frequency must be a regular grid\")\n\n    return frequency[0], frequency[1] - frequency[0], len(frequency)\n\n\ndef validate_method(method, dy, fit_mean, nterms,\n                    frequency, assume_regular_frequency):\n    \"\"\"\n    Validate the method argument, and if method='auto'\n    choose the appropriate method\n    \"\"\"\n    methods = available_methods()\n    prefer_fast = (len(frequency) > 200\n                   and (assume_regular_frequency or _is_regular(frequency)))\n    prefer_scipy = 'scipy' in methods and dy is None and not fit_mean\n\n    # automatically choose the appropriate method\n    if method == 'auto':\n\n        if nterms != 1:\n            if prefer_fast:\n                method = 'fastchi2'\n            else:\n                method = 'chi2'\n        elif prefer_fast:\n            method = 'fast'\n        elif prefer_scipy:\n            method = 'scipy'\n        else:\n            method = 'cython'\n\n    if method not in METHODS:\n        raise ValueError(\"invalid method: {0}\".format(method))\n\n    return method\n\n\ndef lombscargle(t, y, dy=None,\n                frequency=None,\n                method='auto',\n                assume_regular_frequency=False,\n                normalization='standard',\n                fit_mean=True, center_data=True,\n                method_kwds=None, nterms=1):\n    \"\"\"\n    Compute the Lomb-scargle Periodogram with a given method.\n\n    Parameters\n    ----------\n    t : array_like\n        sequence of observation times\n    y : array_like\n        sequence of observations associated with times t\n    dy : float or array_like (optional)\n        error or sequence of observational errors associated with times t\n    frequency : array_like\n        frequencies (not angular frequencies) at which to evaluate the\n        periodogram. If not specified, optimal frequencies will be chosen using\n        a heuristic which will attempt to provide sufficient frequency range\n        and sampling so that peaks will not be missed. Note that in order to\n        use method='fast', frequencies must be regularly spaced.\n    method : string (optional)\n        specify the lomb scargle implementation to use. Options are:\n\n        - 'auto': choose the best method based on the input\n        - 'fast': use the O[N log N] fast method. Note that this requires\n          evenly-spaced frequencies: by default this will be checked unless\n          ``assume_regular_frequency`` is set to True.\n        - `slow`: use the O[N^2] pure-python implementation\n        - `chi2`: use the O[N^2] chi2/linear-fitting implementation\n        - `fastchi2`: use the O[N log N] chi2 implementation. Note that this\n          requires evenly-spaced frequencies: by default this will be checked\n          unless `assume_regular_frequency` is set to True.\n        - `scipy`: use ``scipy.signal.lombscargle``, which is an O[N^2]\n          implementation written in C. Note that this does not support\n          heteroskedastic errors.\n\n    assume_regular_frequency : bool (optional)\n        if True, assume that the input frequency is of the form\n        freq = f0 + df * np.arange(N). Only referenced if method is 'auto'\n        or 'fast'.\n    normalization : string (optional, default='standard')\n        Normalization to use for the periodogram.\n        Options are 'standard' or 'psd'.\n    fit_mean : bool (optional, default=True)\n        if True, include a constant offset as part of the model at each\n        frequency. This can lead to more accurate results, especially in the\n        case of incomplete phase coverage.\n    center_data : bool (optional, default=True)\n        if True, pre-center the data by subtracting the weighted mean\n        of the input data. This is especially important if `fit_mean = False`\n    method_kwds : dict (optional)\n        additional keywords to pass to the lomb-scargle method\n    nterms : int (default=1)\n        number of Fourier terms to use in the periodogram.\n        Not supported with every method.\n\n    Returns\n    -------\n    PLS : array_like\n        Lomb-Scargle power associated with each frequency omega\n    \"\"\"\n    # frequencies should be one-dimensional arrays\n    output_shape = frequency.shape\n    frequency = frequency.ravel()\n\n    # we'll need to adjust args and kwds for each method\n    args = (t, y, dy)\n    kwds = dict(frequency=frequency,\n                center_data=center_data,\n                fit_mean=fit_mean,\n                normalization=normalization,\n                nterms=nterms,\n                **(method_kwds or {}))\n\n    method = validate_method(method, dy=dy, fit_mean=fit_mean, nterms=nterms,\n                             frequency=frequency,\n                             assume_regular_frequency=assume_regular_frequency)\n\n    # scipy doesn't support dy or fit_mean=True\n    if method == 'scipy':\n        if kwds.pop('fit_mean'):\n            raise ValueError(\"scipy method does not support fit_mean=True\")\n        if dy is not None:\n            dy = np.ravel(np.asarray(dy))\n            if not np.allclose(dy[0], dy):\n                raise ValueError(\"scipy method only supports \"\n                                 \"uniform uncertainties dy\")\n        args = (t, y)\n\n    # fast methods require frequency expressed as a grid\n    if method.startswith('fast'):\n        f0, df, Nf = _get_frequency_grid(kwds.pop('frequency'),\n                                         assume_regular_frequency)\n        kwds.update(f0=f0, df=df, Nf=Nf)\n\n    # only chi2 methods support nterms\n    if not method.endswith('chi2'):\n        if kwds.pop('nterms') != 1:\n            raise ValueError(\"nterms != 1 only supported with 'chi2' \"\n                             \"or 'fastchi2' methods\")\n\n    PLS = METHODS[method](*args, **kwds)\n    return PLS.reshape(output_shape)\n", "meta": {"hexsha": "d5f85be49da64033e6a32e71caa7c38cfe75262e", "size": 7800, "ext": "py", "lang": "Python", "max_stars_repo_path": "astropy/stats/lombscargle/implementations/main.py", "max_stars_repo_name": "b1quint/astropy", "max_stars_repo_head_hexsha": "a170a74739e4356c169429a42e554f9777b53f4d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-04-27T01:19:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T03:31:01.000Z", "max_issues_repo_path": "astropy/stats/lombscargle/implementations/main.py", "max_issues_repo_name": "b1quint/astropy", "max_issues_repo_head_hexsha": "a170a74739e4356c169429a42e554f9777b53f4d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2017-12-18T16:27:29.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-29T14:54:22.000Z", "max_forks_repo_path": "astropy/stats/lombscargle/implementations/main.py", "max_forks_repo_name": "b1quint/astropy", "max_forks_repo_head_hexsha": "a170a74739e4356c169429a42e554f9777b53f4d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-04-27T01:19:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-20T15:15:19.000Z", "avg_line_length": 35.4545454545, "max_line_length": 79, "alphanum_fraction": 0.6366666667, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.3140505321516081, "lm_q1q2_score": 0.16438043912243294}}
{"text": "#!/usr/bin/env python -u \n'''\npDMET: Density Matrix Embedding theory for Periodic Systems\nCopyright (C) 2018 Hung Q. Pham. All Rights Reserved.\nA few functions in pDMET are modifed from QC-DMET Copyright (C) 2015 Sebastian Wouters\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nEmail: Hung Q. Pham <pqh3.14@gmail.com>\n'''\n\nimport datetime\nimport numpy as np\nfrom pyscf import lib\nfrom scipy import optimize\nfrom functools import reduce\nfrom pdmet import localbasis, qcsolvers, diis, helper, df_hamiltonian\nfrom pdmet.schmidtbasis import get_bath_using_RHF_1RDM, get_bath_using_gamma_RHF_1RDM\nfrom pdmet.tools import tchkfile, tplot, tprint, tunix, misc\nfrom pdmet.lib.build import libdmet\nimport sys\nsys.path.append('/panfs/roc/groups/6/gagliard/phamx494/pyWannier90/src')\nimport pywannier90\n\n\nclass pDMET:\n    def __init__(self, cell, kmf, w90, solver = 'HF',  state_average_mix_=None, nevpt2_spin=None):\n        '''\n        Args:\n            kmf                             : a rhf wave function from pyscf/pbc\n            w90                                : a converged wannier90 object\n            OEH_type                        : One-electron Hamiltonian used in the bath construction, h(k) = OEH(k) + umat(k) \n            SCmethod                        : 'BFGS'/'CG'/'Newton-CG' self-consistent iteration method, defaut: BFGS\n            SC_threshold                    : convergence criteria for correlatiself.e_toton potential, default: 1e-6\n            SC_maxcycle                     : maximum cycle for self-consistent iteration, default: 50\n            umat                            : correlation potential\n            chempot                         : global chemical potential\n            emb_corr_1RDM                   : correlated 1RDM from high-level calculations\n            emb_orbs                        : a list of the fragment and bath orbitals for each fragment            \n        Return:\n        \n        '''        \n        \n        tprint.print_header()\n\n        # Chkfiles:\n        self.cell = cell          \n        self.kmf = kmf\n        self.w90 = w90        \n        self.kmf_chkfile = None \n        self.w90_chkfile = None \n        \n        # Options\n        self.OEH_type = 'FOCK' # Options: FOCK/OEI        \n        \n        # QC Solver    \n        solver_list   = ['HF', 'MP2', 'CASCI', 'DMRG-CI', 'CASSCF', 'DMRG-SCF', \\\n                            'SS-CASSCF', 'SS-DMRG-SCF', 'SA-CASSCF', 'SA-DMRG-SCF', \\\n                            'FCI', 'DMRG', 'RCCSD', 'RCCSD_T', 'SHCI'\n                            ]\n        assert solver in solver_list, \"Solver options: HF, MP2, CASCI, DMRG-CI, \\\n                                     CASSCF, DMRG-SCF,SS-CASSCF, SS-DMRG-SCF, SA-CASSCF, SA-DMRG-SCF \\\n                                     FCI, DMRG, RCCSD, SHCI\"\n        self.solver   = solver        \n        self.e_shift  = None         # Use to fix spin of the wrong state with FCI, hence CASCI/CASSCF solver\n        self.use_GDF  = True          # Mostly using for FFTDF where density fitting is not available\n        \n        # Gamma sampling embedding\n        self.impCluster = None\n        self._impOrbs_threshold = 1.0\n        self._impOrbs_rmlist = None\n        self._impOrbs_addlist = None\n        self._num_bath = None\n        self.nroots = 10\n        self.nevpt2_nroots = 10\n        self.nevpt2_roots = None\n        self.nevpt2_spin = nevpt2_spin\n        self.state_average_ = None\n        self.state_average_mix_  = None\n        if solver in ['CASCI', 'CASSCF', 'SS-CASSCF', 'SS-DMRG-SCF', 'SA-CASSCF', 'SA-DMRG-SCF']:\n            self.cas    = None\n            self.molist = None  \n            if solver in ['SS-CASSCF', 'SS-DMRG-SCF']:\n                self.state_specific_ = 0\n            elif solver in ['SA-CASSCF', 'SA-DMRG-SCF']:\n                if state_average_mix_ is None:\n                    self.state_average_ = [0.5, 0.5]\n                else:\n                    self.state_average_mix_ = state_average_mix_ \n                \n        \n        # Parameters    \n        self.SC_method          = \"BFGS\"        # BFGS, CG, Newton-CG\n        self.SC_threshold       = 1e-4            \n        self.SC_maxcycle        = 200\n        self.SC_CFtype          = \"F\" # Options: ['F','diagF', 'FB','diagFB']\n        self.alt_CF             = False \n        self.dft_CF             = False\n        self.dft_is_kpts        = False\n        self.dft_CF_constraint  = 1\n        self.dft_HF             = None  \n        self.xc                 = None   \n        self.xc_omega           = None\n        self.damping            = 1.0 # 1.0 means no damping\n        self.DIIS               = False       \n        self.DIIS_m             = 1   \n        self.DIIS_n             = 8  \n        \n        # DMET Output\n        self.state_percent      = None        \n        self.twoS               = None\n        self.verbose            = 0\n        self.max_memory         = 4000  # in MB \n        self.loc_OEH_kpts       = None      \n        self.loc_1RDM_kpts      = None        \n        self.loc_1RDM_R0        = None\n        self.loc_corr_1RDM_R0   = None\n        self.baths              = None\n        self.emb_corr_1RDM      = None  \n        self.emb_orbs           = None\n        self.emb_mf_1RDM        = None\n        self.e_tot              = 0.       # energy per unit cell     \n        self.e_corr             = 0.\n        self.nelec_per_cell     = None      \n        \n        # Others\n        self.bath_truncation = True  # if self.truncate = a threshold, then a bath truncation scheme is used          \n        self.chkfile         = 'pdmet.chk'    # Save integrals in the WFs basis as well as chem potential and uvec\n        self.restart         = False   # Run a calculation using saved chem potential and uvec             \n        self._cycle           = 1        \n        \n    def initialize(self, ERI = None):\n        '''\n        Prepare the local integrals, correlation/chemical potential    \n        '''    \n        \n        tprint.print_msg(\"Initializing ...\")\n        \n        # -------------------------------------------------        \n        # General initialized attributes \n        self.kmesh = self.w90.mp_grid_loc\n        if (self.kmf_chkfile is not None) and hasattr(self.kmf.with_df, '_cderi'):\n            self.kmf = tchkfile.load_kmf(self.cell, self.kmf, self.kmesh, self.kmf_chkfile, max_memory=self.max_memory)\n            if self.kmf.with_df._cderi == None:\n                if tunix.check_exist('gdf.h5'):\n                    self.kmf.with_df._cderi = 'gdf.h5'\n                else:\n                    print(\"WARNING: Provide density fitting file in initiating kmf object or make sure the saved kmf object is using the same density fitting\")\n            self._is_ROHF = self.kmf._is_ROHF \n        else:\n            from pyscf.pbc import scf\n            if isinstance(self.kmf, scf.krohf.KROHF):\n                self._is_ROHF = True\n            else:\n                self._is_ROHF = False\n            \n        if self.kmf.exxdiv is not None: \n            raise Exception('The pDMET has not been developed for the RHF calculation with exxdiv is not None')\n            # TODO: if self.kmf.exxdiv != None, consider to run two SCF (one with and one without exx treatment\n            # if self.kmf.exxdiv == 'ewald': actOEI_kpts += self.exxdiv_ewald(cell) \n            # to get the finite correction, see https://github.com/pyscf/pyscf/issues/250   \n            \n        if self.w90_chkfile is not None:\n            self.w90 = tchkfile.load_w90(self.w90, self.w90_chkfile)\n        else:\n            self.w90 = self.w90 \n            \n        if self.twoS is None:\n            self.twoS = self.cell.spin\n            \n        else:\n            if self.twoS != self.cell.spin:\n                tprint.print_msg(\" WARNING: the 2S in DMET is different from that of the mean-field wave function. \\\n                                   Hope you know what you're doing\")\n                                   \n        if self.nevpt2_spin is None:\n            self.nevpt2_spin = self.twoS\n        \n        assert (self.chkfile == None) or isinstance(self.chkfile,str)\n        self.kpts = self.kmf.kpts\n        self.Nkpts = self.kpts.shape[0]   \n        if self.xc is not None:\n            self.dft_CF = True\n            self.OEH_type = self.xc\n            if self.xc == 'RSH-PBE0' and self.xc_omega is None:\n                self.xc_omega = 0.2\n        else:\n            self.dft_CF = False\n\n        # For the Gamma-sampling DMET\n        if self.impCluster is not None:\n            assert np.prod(self.kmesh) == 1, \"impCluster is used only for a Gamma-point sampling calculation\"\n            self._impOrbs, self._impAtms = misc.make_imp_orbs(self.cell, self.w90, self.impCluster, \\\n                                    threshold=self._impOrbs_threshold, rm_list=self._impOrbs_rmlist, add_list=self._impOrbs_addlist)\n            self.Nimp = np.sum(self._impOrbs)\n            self._is_gamma = True\n            \n            tprint.print_msg(\"==== Impurity cluster ====\")\n            tprint.print_msg(\" No. of Impurity atoms   : {0}\".format(len(self.impCluster)))\n            tprint.print_msg(\" No. of Impurity orbitals: {0}\".format(self.Nimp))\n            atom_coords = self.cell.atom_coords() * lib.param.BOHR\n            for i, atm in enumerate(self.impCluster):\n                symbol = self.cell.atom_symbol(atm - 1)\n                x, y, z = atom_coords[atm - 1]\n                tprint.print_msg(\"  {0:3d}  {1:3s}  {2:3.5f} {3:3.5f} {4:3.5f}\".format(atm, symbol, x, y, z))\n                impAtms = self._impAtms[i].tolist()\n                nimpOrbs = len(impAtms)\n                impAtms = [nimpOrbs] + impAtms\n                tprint.print_msg((\"       {:d} Orbitals: \" + \"{:d} \"*nimpOrbs).format(*impAtms))\n\n            tprint.print_msg(\"==========================\")\n        else:\n            self.Nimp = self.local.nlo     # the whole reference unit cell is the imputity\n            self._is_gamma = False\n            assert self.twoS ==0 , \"ROHF bath is only available for Gamma-sampling calculation\"\n            \n        # Initilize the local space object\n        self.local = localbasis.Local(self.cell, self.kmf, self.w90, self._is_ROHF, self.xc_omega)  \n        self.e_core = self.local.e_core   \n        \n        # -------------------------------------------------        \n        # The number of bath orbitals depends on whether one does Schmidt decomposition on RHF or ROHF wave function        \n        if self._is_ROHF:\n            self.bathtype = 'ROHF'          \n        else:\n            self.bathtype = 'RHF'            \n            \n        self.Norbs = self.local.nlo * self.Nkpts\n        self.Nelec_total    = self.local.nelec_total\n        self.Nelec_per_cell = self.local.nelec_per_cell\n        self.numPairs = self.Nelec_per_cell // 2 \n        \n        if self.SC_CFtype in ['diagF', 'diagFB']: \n            self.Nterms = self.Nimp \n        else:            \n            self.Nterms = self.Nimp*(self.Nimp + 1) // 2 \n\n        self.mask = self.make_mask(self._is_gamma)  \n        if self._is_gamma: \n            self.mask4Gamma = self.mask\n        else:\n            self.mask4Gamma = None\n        self.H1start, self.H1row, self.H1col = self.make_H1(self._is_gamma, self._impOrbs)[1:4]    #Use in the calculation of 1RDM derivative\n  \n                  \n        self.chempot = 0.0\n        if self.dft_CF:\n            self.uvec = df_hamiltonian.get_init_uvec(self.xc, self.dft_HF)\n            self.bounds = df_hamiltonian.get_bounds(self.xc, self.dft_CF_constraint, self.dft_HF)           \n        else:\n            self.uvec = np.zeros(self.Nterms, dtype=np.float64)           \n        self.umat = self.uvec2umat(self.uvec)\n\n        # -------------------------------------------------       \n        # Load/initiate chem pot, uvec, umat  \n        # TODO: no longer used, Consider to remove this\n        self.restart_success = False        \n        if self.chkfile is not None and self.restart == True:\n            if tunix.check_exist(self.chkfile):\n                self.save_pdmet     = tchkfile.load_pdmet(self.chkfile)           \n                self.chempot        = self.save_pdmet.chempot\n                self.uvec           = self.save_pdmet.uvec\n                self.umat           = self.save_pdmet.umat   \n                self.emb_corr_1RDM       = self.save_pdmet.actv1RDMloc\n                self.emb_orbs       = self.save_pdmet.emb_orbs\n                tprint.print_msg(\"-> Load the pDMET chkfile\")\n                self.restart_success = True                 \n            else:\n                tprint.print_msg(\"-> Cannot load the pDMET chkfile\") \n                self.restart_success = False\n            \n        if self.alt_CF == True: \n            #TODO: debugging the alternative cost function, this will be updated\n            pass\n        else:\n            self.CF = self.cost_func            \n            self.CF_grad = self.cost_func_grad  \n            \n        # Initializing damping procedure and DIIS object          \n        if self.DIIS == True:\n            assert self.DIIS_m >= 1        \n            self._diis = diis.DIIS(self.DIIS_m, self.DIIS_n)   \n            \n        if self.damping != 1.0:\n            assert (0 <= self.damping <= 1.0)          \n\n        # Initializing the QC solver\n        if self.nroots > 1:\n            if self.state_percent == None: \n                self.state_percent = [1/self.nroots]*self.nroots\n            else:\n                assert len(self.state_percent) == self.nroots\n                assert abs(sum(self.state_percent) - 1.0) < 1.e-10      # The total percent has be 1   \n                \n        if self.twoS != 0 and self.solver == 'RCCSD': \n            raise Exception('RCCSD solver does not support ROHF wave function')             \n\n        # For FCI, CAS-like solver\n        print(qcsolvers.QCsolvers)\n        self._SS = 0.5*self.twoS*(0.5*self.twoS + 1)       \n        self.qcsolver = qcsolvers.QCsolvers(self.solver, self.twoS, self._is_ROHF, self.e_shift, self.nroots, self.state_percent, verbose=self.verbose, memory=self.max_memory) \n        if self.solver in ['CASCI', 'CASSCF', 'SS-CASSCF', 'SS-DMRG-SCF', 'SA-CASSCF', 'SA-DMRG-SCF']:\n            self.qcsolver.cas = self.cas\n            self.qcsolver.molist = self.molist \n            if \"SS-\" in self.solver: \n                assert self.nroots > self.state_specific_, \"Increasing the number of roots in the FCI solver\"\n            if \"SA-\" in self.solver: \n                self.qcsolver.nroots = len(self.state_average_) \n        if self.nevpt2_roots is not None:\n            assert self.nevpt2_nroots >= len(self.nevpt2_roots), \"Increasing the number of roots in the FCI solver\"\n            \n        tprint.print_msg(\"Initializing ... DONE\")       \n                \n    def kernel(self, chempot=0.0):\n        '''\n        This is the main kernel for DMET calculation.\n        It is solving the embedding problem, then returning the total number of electrons per unit cell \n        and updating the schmidt orbitals and 1RDM.\n        Args:\n            chempot                    : global chemical potential to adjust the number of electrons in the unit cell\n        Return:\n            nelecs                     : the total number of electrons\n        Update the class attributes:\n            energy                          : the energy for the unit cell  \n            nelec                           : the number of electrons for the unit cell    \n            emb_corr_1RDM                   : correlated 1RDM for the unit cell                \n        '''            \n              \n        # Transform the 1e/2e integrals and the JK core constribution to schmidt basis\n        if self._is_new_bath == True:\n            ao2eo = self.local.get_ao2eo(self.emb_orbs)\n            self.emb_OEI  = self.local.get_emb_OEI(ao2eo)\n            if self.use_GDF == True:\n                self.emb_TEI  = self.local.get_emb_TEI(ao2eo)\n            else:\n                self.emb_TEI  = self.local.get_TEI(ao2eo)\n            self.emb_mf_1RDM = self.local.loc_kpts_to_emb(self.loc_1RDM_kpts, self.emb_orbs)\n            self.emb_JK = self.local.get_emb_JK(self.loc_1RDM_kpts, ao2eo)\n            self.emb_coreJK = self.local.get_emb_coreJK(self.emb_JK, self.emb_TEI, self.emb_mf_1RDM)         \n            \n        #TODO: currently, the 1RDM guess is chempot independent\n        #emb_guess_1RDM = self.local.get_emb_guess_1RDM(self.emb_FOCK, self.Nelec_in_emb, self.Nimp, chempot)\n        emb_guess_1RDM = self.emb_mf_1RDM\n        if self._cycle == 1 : \n            tprint.print_msg(\"   Embedding size: %2d electrons in (%2d impurities + %2d baths )\" \\\n                                                                    % (self.Nelec_in_emb, self.Nimp, self.Nbath))\n        \n        self.qcsolver.initialize(self.local.e_core, self.emb_OEI, self.emb_TEI, \\\n                                self.emb_coreJK, emb_guess_1RDM, self.Nimp + self.Nbath, self.Nelec_in_emb, self.Nimp, chempot)\n        if self.solver == 'HF':\n            e_cell, e_solver, RDM1 = self.qcsolver.HF()\n        elif self.solver == 'MP2':\n            e_cell, e_solver, RDM1 = self.qcsolver.MP2()\n        elif self.solver in ['CASCI']:\n            e_cell, e_solver, RDM1 = self.qcsolver.CASCI(nevpt2_roots=self.nevpt2_roots, nevpt2_nroots=self.nevpt2_nroots)      \n        elif self.solver in ['DMRG-CI']:\n            e_cell, e_solver, RDM1 = self.qcsolver.CASCI(solver = 'CheMPS2', nevpt2_roots=self.nevpt2_roots, nevpt2_nroots=self.nevpt2_nroots)  \n        elif self.solver in ['CASSCF']:\n            e_cell, e_solver, RDM1 = self.qcsolver.CASSCF(nevpt2_roots=self.nevpt2_roots, nevpt2_nroots=self.nevpt2_nroots, nevpt2_spin=self.nevpt2_spin)     \n        elif self.solver in ['DMRG-SCF']:\n            e_cell, e_solver, RDM1 = self.qcsolver.CASSCF(solver = 'CheMPS2', nevpt2_roots=self.nevpt2_roots, nevpt2_nroots=self.nevpt2_nroots, nevpt2_spin=self.nevpt2_spin) \n        elif self.solver in ['SS-CASSCF']:\n            e_cell, e_solver, RDM1 = self.qcsolver.CASSCF(state_specific_=self.state_specific_, nevpt2_roots=self.nevpt2_roots, nevpt2_nroots=self.nevpt2_nroots, nevpt2_spin=self.nevpt2_spin) \n        elif self.solver in ['SA-CASSCF']:\n            e_cell, e_solver, RDM1 = self.qcsolver.CASSCF(state_average_=self.state_average_, state_average_mix_=self.state_average_mix_, nevpt2_roots=self.nevpt2_roots, nevpt2_nroots=self.nevpt2_nroots, nevpt2_spin=self.nevpt2_spin)  \n        elif self.solver in ['SS-DMRG-SCF']:\n            e_cell, e_solver, RDM1 = self.qcsolver.CASSCF(solver = 'CheMPS2', state_specific_=self.state_specific_, nevpt2_roots=self.nevpt2_roots, nevpt2_nroots=self.nevpt2_nroots)  \n        elif self.solver in ['SA-DMRG-SCF']:\n            e_cell, e_solver, RDM1 = self.qcsolver.CASSCF(solver = 'CheMPS2', state_average_=self.state_average_, nevpt2_roots=self.nevpt2_roots, nevpt2_nroots=self.nevpt2_nroots) \n        elif self.solver == 'FCI':\n            e_cell, e_solver, RDM1 = self.qcsolver.FCI()\n        elif self.solver == 'DMRG':\n            e_cell, e_solver, RDM1 = self.qcsolver.DMRG()          \n        elif self.solver == 'RCCSD':\n            e_cell, e_solver, RDM1 = self.qcsolver.RCCSD()  \n        elif self.solver == 'RCCSD_T':\n            e_cell, e_solver, RDM1 = self.qcsolver.RCCSD_T()              \n        elif self.solver == 'SHCI':\n            e_cell, e_solver, RDM1 = self.qcsolver.SHCI()              \n        \n        self.emb_corr_1RDM    = RDM1\n        self.loc_corr_1RDM_R0 = lib.einsum('Rim,mn,jn->Rij', self.emb_orbs, RDM1, self.emb_orbs[0].conj())\n        \n        if not np.isclose(self._SS, self.qcsolver.SS): \n            tprint.print_msg(\"           WARNING: Spin contamination. Computed <S^2>: %10.8f, Target: %10.8f\" % (self.qcsolver.SS, self._SS)) \n            \n        # Get the cell energy:\n        if self._is_gamma:\n            # The Gamma-point calculation assumes one active space, so CASCI-like formular is used to compute the energy\n            if self._is_new_bath:\n                if np.shape([self.core_orbs])[-1] != 0:\n                    ao2core = self.local.get_ao2core(self.core_orbs)\n                    lo2core = self.local.get_lo2core(self.core_orbs)\n                    core_OEI = self.local.get_core_OEI(ao2core)\n                    Nelec_in_core = self.Nelec_total - self.Nelec_in_emb\n                    core_1RDM = self.local.get_core_mf_1RDM(lo2core, Nelec_in_core, self.loc_OEH_kpts)\n                    loc_core_1RDM = lib.einsum('kim,mn,kjn->kij', lo2core, core_1RDM, lo2core.conj())\n                    core_JK = self.local.get_core_JK(ao2core, loc_core_1RDM)\n                    core_energy = np.sum((core_OEI + 0.5 * core_JK)* core_1RDM)\n                    self.core_energy = core_energy.real\n                    self.loc_core_1RDM = loc_core_1RDM.real.reshape(1, self.Norbs, self.Norbs)    \n                else:\n                    self.core_energy = 0.0\n                    self.loc_core_1RDM = 0.0\n                    E_core = 0.0\n                    \n            self.loc_corr_1RDM_R0 += self.loc_core_1RDM\n            self.nelec_per_cell = self.Nelec_total\n            if self.nevpt2_roots is not None:\n                e_CAS, e_CASCI_NEVPT2, t_dm1s = e_solver\n                self.ss_CASCI = e_CASCI_NEVPT2[:,0]\n                e_CASCI = e_CASCI_NEVPT2[:,1] \n                e_NEVPT2 = e_CASCI_NEVPT2[:,2]\n                self.e_tot = e_CAS + self.core_energy + self.local.e_core\n                self.e_emb = e_CAS \n                self.e_imp = e_cell - self.local.e_core  \n                self.e_casci_tot = np.asarray(e_CASCI) + self.core_energy + self.local.e_core\n                self.e_nept2_tot = np.asarray(e_NEVPT2) + self.core_energy + self.local.e_core\n                self.t_dm1s = t_dm1s\n            else:\n                self.e_tot = e_solver + self.core_energy + self.local.e_core\n                self.e_emb = e_solver \n                self.e_imp = e_cell - self.local.e_core             \n        else:\n            self.nelec_per_cell = np.trace(RDM1[:self.Nimp,:self.Nimp])\n            self.e_tot = e_cell   \n                \n        return self.nelec_per_cell\n        \n    def bath_contruction(self, loc_1RDM_R0, impCluster):\n        '''Get the bath orbitals'''\n        emb_orbs, core_orbs, Nelec, Nbath = get_bath_using_RHF_1RDM(loc_1RDM_R0, impCluster,  is_ROHF=self._is_ROHF, num_bath=self._num_bath, bath_truncation=self.bath_truncation)\n        # self._num_bath is used to keep the no. of baths are the same as in the 1st cycle of SCF\n        if self._num_bath is None: self._num_bath = Nbath           \n        Nemb = self.Nimp + Nbath\n        emb_orbs = emb_orbs.reshape(self.Nkpts, self.local.nlo, Nemb) # NR = Nkpts\n        core_orbs = core_orbs.reshape(self.Nkpts, self.local.nlo, self.local.nlo - Nemb)\n        Nenv = self.Norbs - Nemb\n        Nelec_in_emb = Nelec\n\n        if Nelec_in_emb > self.Nelec_total:\n            Nelec_in_emb = self.Nelec_total\n        elif self.Nelec_total - Nelec_in_emb > 2 * Nenv:\n            Nelec_in_emb = self.Nelec_total - 2 * Nenv\n        self._is_new_bath = True\n        return emb_orbs, core_orbs, Nbath, Nelec_in_emb\n\n    def check_exact(self, error = 1.e-6):\n        '''\n        Do one-shot DMET, only the chemical potential is optimized\n        '''\n        \n        tprint.print_msg(\"--------------------------------------------------------------------\")   \n        \n        if self.dft_CF:\n            umat = df_hamiltonian.get_init_uvec(self.xc)\n        else:\n            umat = 0.\n            \n        self.loc_OEH_kpts, self.loc_1RDM_kpts, self.loc_1RDM_R0 = self.local.make_loc_1RDM(umat, self.mask4Gamma, OEH_type=self.OEH_type, dft_HF=None)      \n        \n        self.emb_orbs, self.core_orbs, self.Nbath, self.Nelec_in_emb = self.bath_contruction(self.loc_1RDM_R0, self._impOrbs)\n        \n        solver = self.solver\n        self.solver = 'HF'\n        nelec_cell = self.kernel(chempot=0.0)\n        self.solver = solver        \n        \n        diff = abs(self.e_tot - self.kmf.e_tot)\n        tprint.print_msg(\"   E(RHF)        : %12.8f\" % (self.kmf.e_tot))\n        tprint.print_msg(\"   E(RHF-DMET)   : %12.8f\" % (self.e_tot))\n        tprint.print_msg(\"   |RHF - RHF(DMET)|          : %12.8f\" % (diff))\n        if diff < error : \n            tprint.print_msg(\"   HF-in-HF embedding is exact: True\")\n        else:\n             raise Exception('WARNING: HF-in-HF embedding is not exact')                    \n        \n    def one_shot(self, umat=0.0, proj_DMET=False):\n        '''\n        Do one-shot DMET, only the chemical potential is optimized\n        this function takes umat or loc_1RDM_R0 (p-DMET algorthm)\n        '''\n\n        tprint.print_msg(\"-- One-shot DMET ... starting at %s\" % (tunix.current_time()))    \n        if self.solver == 'HF' and self.twoS == 0 and not self._is_ROHF:\n            tprint.print_msg(\"   Bath type: %s | QC Solver: %s\" % (self.bathtype, 'RHF'))\n        elif (self.solver == 'HF' and self.twoS != 0) or (self.solver == 'HF' and self._is_ROHF):        \n            tprint.print_msg(\"   Bath type: %s | QC Solver: %s | 2S = %d\" % (self.bathtype, 'ROHF', self.twoS)) \n        elif self.solver == 'RCCSD': \n            tprint.print_msg(\"   Bath type: %s | QC Solver: %s | 2S = %d\" % (self.bathtype, self.solver, self.twoS))        \n        else:      \n            tprint.print_msg(\"   Bath type: %s | QC Solver: %s | 2S = %d | Nroots: %d\" % (self.bathtype, self.solver, self.twoS, self.nroots))\n            \n        if self.solver in ['CASCI', 'CASSCF', 'SS-CASSCF', 'SS-DMRG-SCF', 'SA-CASSCF', 'SA-DMRG-SCF']:                \n            if self.qcsolver.cas is not None: tprint.print_msg(\"   Active space     :\", self.qcsolver.cas)\n            if self.qcsolver.cas is not None: tprint.print_msg(\"   Active space MOs :\", self.qcsolver.molist)\n            if \"SS-\" in self.solver: tprint.print_msg(\"   State-specific CASSCF using state id :\", self.state_specific_)\n            if \"SA-\" in self.solver: tprint.print_msg(\"   State-average CASSCF with weight :\", self.state_average_)\n            \n        self._cycle = 1 \n        if not proj_DMET:\n            self.loc_OEH_kpts, self.loc_1RDM_kpts, self.loc_1RDM_R0 = self.local.make_loc_1RDM(umat, self.mask4Gamma, OEH_type=self.OEH_type, dft_HF=self.dft_HF)       \n                    \n        self.emb_orbs, self.core_orbs, self.Nbath, self.Nelec_in_emb = self.bath_contruction(self.loc_1RDM_R0, self._impOrbs)\n\n        # Optimize the chemical potential\n        if self._is_gamma:\n            nelec_per_cell_from_embedding = self.kernel(chempot=0.0)\n        else:\n            self.chempot = optimize.newton(self.nelec_cost_func, self.chempot)\n            tprint.print_msg(\"   No. of electrons per cell : %12.8f\" % (self.nelec_per_cell))\n            \n        if isinstance(self.e_tot, list) or isinstance(self.e_tot, np.ndarray):\n            tprint.print_msg(\"   Energy per cell           : %12.8f\" % (self.e_tot[0])) \n            if self.state_average_ is not None:\n                for i, e in enumerate(self.e_tot):\n                    tprint.print_msg(\"      State %d weight %7.5f: E = %12.8f\" % (i, self.state_average_[i], e))  \n            else:\n                for i, e in enumerate(self.e_tot):\n                    tprint.print_msg(\"      State %d: E = %12.8f\" % (i, e))  \n        else:\n            tprint.print_msg(\"   Energy per cell           : %12.8f\" % (self.e_tot))   \n\n        if self.nevpt2_roots is not None:\n            tprint.print_msg(\"   NEVPT2 energies for the selected states:\") \n            for i, e_nevpt2 in enumerate(self.e_nept2_tot):\n                tprint.print_msg(\"      State %d: E(CASCI) = %12.8f   E(NEVPT2) = %12.8f   <S^2> = %8.6f\" % (self.nevpt2_roots[i], self.e_casci_tot[i], e_nevpt2, self.ss_CASCI[i]))  \n        \n        tprint.print_msg(\"-- One-shot DMET ... finished at %s\" % (tunix.current_time()))\n        tprint.print_msg()            \n        \n    def self_consistent(self, get_band=False, interpolate_band=None):\n        '''\n        Do self-consistent pDMET\n        '''    \n           \n        tprint.print_msg(\"--------------------------------------------------------------------\")\n        tprint.print_msg(\"- SELF-CONSISTENT DMET CALCULATION ... STARTING -\")\n        tprint.print_msg(\"  Convergence criteria\")   \n        tprint.print_msg(\"    Threshold :\", self.SC_threshold)     \n        tprint.print_msg(\"  Fitting 1-RDM of :\", self.SC_CFtype) \n            \n        if self.dft_CF: tprint.print_msg(\"  DF-like cost function:\", self.xc)          \n        if self.damping != 1.0:        \n            tprint.print_msg(\"  Damping factor   :\", self.damping)                \n        if self.DIIS:\n            tprint.print_msg(\"  DIIS start at %dth cycle and using %d previous umats\" % (self.DIIS_m, self.DIIS_n))  \n            \n        #------------------------------------#\n        #---- SELF-CONSISTENT PROCEDURE ----#      \n        #------------------------------------#    \n        OEH_kpts, rdm1_kpts, rdm1_R0 = self.local.make_loc_1RDM(self.umat, self.mask4Gamma, OEH_type=self.OEH_type, dft_HF=self.dft_HF)\n        for cycle in range(self.SC_maxcycle):\n            \n            tprint.print_msg(\"- CYCLE %d:\" % (cycle + 1))    \n            umat_old = self.umat      \n            rdm1_R0_old = rdm1_R0     \n            energy_old = self.e_tot\n            \n            # Do one-shot with each uvec                  \n            self.one_shot(umat=self.umat) \n            tprint.print_msg(\"   + Chemical potential        : %12.8f\" % (self.chempot))\n\n            # Optimize uvec to minimize the cost function\n            if self.dft_CF:\n                result = optimize.minimize(self.CF, self.uvec, method='L-BFGS-B', jac=None, options={'disp': False, 'gtol': 1e-4, 'eps': 1e-8}, bounds=self.bounds)\n            else:\n                # result = optimize.minimize(self.CF, self.uvec, method=self.SC_method, jac=self.CF_grad, options={'disp': False, 'gtol': 1e-12})\n                result = optimize.minimize(self.CF, self.uvec, method = self.SC_method , options = {'disp': False, 'gtol': 1e-6}, tol=1e-4)\n                \n            if not result.success:         \n                tprint.print_msg(\"     WARNING: Correlation potential is not converged\")    \n                  \n            uvec = result.x\n            self.umat = self.uvec2umat(uvec)   \n            \n            # Construct new global 1RDM in k-space\n            global_corr_1RDM = self.local.get_1RDM_Rs(self.loc_corr_1RDM_R0)\n            global_corr_1RDM = 0.5*(global_corr_1RDM.T.conj() + global_corr_1RDM) \n            if not self._is_gamma:\n                loc_1RDM_R0 = global_corr_1RDM[:,:self.Nimp].reshape(self.Nkpts, self.Nimp, self.Nimp)\n            else:\n                loc_1RDM_R0 = global_corr_1RDM\n            rdm1_R0 =  loc_1RDM_R0\n            \n            # Remove arbitrary chemical potential shifts\n            if not self.dft_CF:\n                self.umat = self.umat - np.eye(self.umat.shape[0])*np.average(np.diag(self.umat))\n\n            if self.verbose > 0:\n                tprint.print_msg(\"   + Correlation potential vector    : \", uvec)\n                    \n            umat_diff = umat_old - self.umat  \n            rdm_diff  = rdm1_R0_old - rdm1_R0  \n            energy_diff = self.e_tot - energy_old\n            if self.state_average_ is not None:\n                energy_diff = self.e_tot - energy_old\n                energy_diff = np.sum(energy_diff * np.asarray(self.state_average_))\n            norm_u    = np.linalg.norm(umat_diff)             \n            norm_rdm  = np.linalg.norm(rdm_diff) \n            \n            tprint.print_msg(\"   + Cost function             : %20.15f\" % (result.fun))\n            tprint.print_msg(\"   + 2-norm of umat difference : %20.15f\" % (norm_u)) \n            tprint.print_msg(\"   + 2-norm of rdm1 difference : %20.15f\" % (norm_rdm))  \n            tprint.print_msg(\"   + Energy difference         : %20.15f\" % (energy_diff))  \n            \n            # Export band structure at every cycle:\n            if get_band:\n                band = self.get_bands()\n                pywannier90.save_kmf(band, str(self.solver) + '_band_cyc_' + str(cycle + 1))               \n                \n            # DEBUG \n            if interpolate_band is not None:\n                frac_kpts = interpolate_band\n                bands = self.interpolate_band(frac_kpts)          \n            \n            # Check convergence of 1-RDM            \n            if self.dft_CF:\n                if (norm_rdm <= self.SC_threshold): break\n            elif (norm_u <= self.SC_threshold): \n                break\n            \n            if self.DIIS == True:  \n                self.umat = self._diis.update(cycle, self.umat, umat_diff)            \n                \n            if self.damping != 1.0:                \n                self.umat = (1.0 - self.damping)*umat_old + self.damping*self.umat        \n\n            self.uvec =  self.umat2uvec(self.umat)    \n            tprint.print_msg()            \n            \n        tprint.print_msg(\"- SELF-CONSISTENT DMET CALCULATION ... DONE -\")\n        tprint.print_msg(\"--------------------------------------------------------------------\")            \n        \n\n    def projected_DMET(self, get_band=False):\n        '''\n        Do projected DMET\n        '''    \n           \n        tprint.print_msg(\"--------------------------------------------------------------------\")\n        tprint.print_msg(\"- p-DMET CALCULATION ... STARTING -\")\n        tprint.print_msg(\"  Convergence criteria\")   \n        tprint.print_msg(\"    Threshold :\", self.SC_threshold)    \n        tprint.print_msg(\"  Fitting 1-RDM of :\", self.SC_CFtype)         \n        \n        if self.damping != 1.0:        \n            tprint.print_msg(\"  Damping factor   :\", self.damping)                \n        if self.DIIS:\n            tprint.print_msg(\"  DIIS start at %dth cycle and using %d previous umats\" % (self.DIIS_m, self.DIIS_n))         \n                                              \n        #------------------------------------#\n        #---- SELF-CONSISTENT PROCEDURE ----#     \n        #------------------------------------#    \n        self.loc_OEH_kpts, self.loc_1RDM_kpts, self.loc_1RDM_R0 = self.local.make_loc_1RDM(0.0, self.mask4Gamma, OEH_type=self.OEH_type, dft_HF=self.dft_HF)\n        global_corr_1RDM = self.local.k_to_R(self.loc_1RDM_kpts)\n        for cycle in range(self.SC_maxcycle):\n            tprint.print_msg(\"- CYCLE %d:\" % (cycle + 1))  \n            global_corr_1RDM_old = global_corr_1RDM\n            self.one_shot(proj_DMET=True) \n           \n            if not self._is_gamma:\n                tprint.print_msg(\"   + Chemical potential        : %12.8f\" % (self.chempot))\n            \n            # Construct new global 1RDM in k-space\n            global_corr_1RDM = self.local.get_1RDM_Rs(self.loc_corr_1RDM_R0)\n            global_corr_1RDM = 0.5*(global_corr_1RDM.T.conj() + global_corr_1RDM) \n            global_corr_1RDM_residual  = global_corr_1RDM_old - global_corr_1RDM             \n            norm_1RDM  = np.linalg.norm(global_corr_1RDM_residual) / self.kpts.shape[0]\n            tprint.print_msg(\"   + 2-norm of rdm1 difference : %20.15f\" % (norm_1RDM))  \n            \n            if get_band == True:\n                band = self.get_bands()\n                pywannier90.save_kmf(band, str(self.solver) + '_band_cyc_' + str(cycle + 1))\n\n            # Check convergence of 1-RDM            \n            if norm_1RDM <= self.SC_threshold: \n                break\n \n            if self.DIIS == True:  \n                global_corr_1RDM = self._diis.update(cycle, global_corr_1RDM, global_corr_1RDM_residual)   \n                \n            if self.damping != 1.0:\n                global_corr_1RDM = self.damping*global_corr_1RDM + (1-self.damping)*global_corr_1RDM_old\n                       \n            # Construct new mean-field 1-RDM from the correlated one\n            eigenvals, eigenvecs = np.linalg.eigh(global_corr_1RDM)\n            idx = (-eigenvals).argsort()\n            eigenvals = eigenvals[idx]\n            eigenvecs = eigenvecs[:,idx]\n            num_pairs = self.Nelec_total//2\n            global_mf_1RDM = 2 * eigenvecs[:,:num_pairs].dot(eigenvecs[:,:num_pairs].T)\n            if self._is_gamma:\n                self.loc_1RDM_R0 = global_mf_1RDM.reshape(1, self.Norbs, self.Norbs) + self.loc_core_1RDM\n            else:\n                self.loc_1RDM_R0 = global_mf_1RDM[:,:self.Nimp].reshape(self.Nkpts, self.Nimp, self.Nimp)\n                \n            self.loc_1RDM_kpts = self.local.R0_to_k(self.loc_1RDM_R0)        \n            tprint.print_msg()            \n            \n        tprint.print_msg(\"- p-DMET CALCULATION ... DONE -\")\n        tprint.print_msg(\"--------------------------------------------------------------------\")        \n        \n    def nelec_cost_func(self, chempot):\n        '''\n        The different in the correct number of electrons (provided) and the calculated one \n        '''\n        \n        nelec_per_cell_from_embedding = self.kernel(chempot)\n        self._is_new_bath = False\n        tprint.print_msg(\"     Cycle %2d. Chem potential: %12.8f | Elec/cell = %12.8f | <S^2> = %12.8f\" % \\\n                                                        (self._cycle, chempot, nelec_per_cell_from_embedding, self.qcsolver.SS))                                                                               \n        self._cycle += 1\n        return nelec_per_cell_from_embedding - self.Nelec_per_cell\n\n    def cost_func(self, uvec):\n        '''\n        Cost function: \\mathbf{CF}(u) = \\mathbf{\\Sigma}_{rs} (D^{mf}_{rs}(u) - D^{corr}_{rs})^2\n        where D^{mf} and D^{corr} are the mean-field and correlated 1-RDM, respectively.\n        and D^{mf} = \\mathbf{FT}(D^{mf}(k))\n        '''\n        rdm_diff = self.get_rdm_diff(uvec)\n        cost = np.power(rdm_diff, 2).sum()  \n        return cost\n        \n\n    def cost_func_grad(self, uvec):\n        '''\n        Analytical derivative of the cost function,\n        deriv(CF(u)) = Sum^x [Sum_{rs} (2 * rdm_diff^x_{rs}(u) * deriv(rdm_diff^x_{rs}(u))]\n        ref: J. Chem. Theory Comput. 2016, 12, 2706−2719\n        '''\n        rdm_diff = self.get_rdm_diff(uvec)   \n        rdm_diff_grad = self.rdm_diff_grad(uvec)  \n        CF_grad = np.zeros(self.Nterms)\n        \n        for u in range(self.Nterms):\n            CF_grad[u] = np.sum(2 * rdm_diff * rdm_diff_grad[u])\n        return CF_grad\n        \n    def get_rdm_diff(self, uvec):\n        '''\n        Calculating the different between mf-1RDM (transformed in schmidt basis) and correlated-1RDM for the unit cell\n        Args:\n            uvec            : the correlation potential vector\n        Return:\n            error            : an array of errors for the unit cell.\n        '''\n\n        loc_OEH_kpts, loc_1RDM_kpts, loc_1RDM_R0 = self.local.make_loc_1RDM(self.uvec2umat(uvec), self.mask4Gamma, OEH_type=self.OEH_type, dft_HF=self.dft_HF)\n        if self.SC_CFtype in ['F', 'diagF']:        \n            mf_1RDM = self.local.loc_kpts_to_emb(loc_1RDM_kpts, self.emb_orbs[:,:,:self.Nimp])\n            corr_1RDM = self.emb_corr_1RDM[:self.Nimp,:self.Nimp]              \n        elif self.SC_CFtype in ['FB', 'diagFB']:  \n            mf_1RDM = self.local.loc_kpts_to_emb(loc_1RDM_kpts, self.emb_orbs)\n            corr_1RDM = self.emb_corr_1RDM    \n            \n        error = mf_1RDM - corr_1RDM\n        if self.SC_CFtype in ['diagF', 'diagFB']: error = np.diag(error)      \n        \n        return error\n        \n    def rdm_diff_grad(self, uvec):\n        '''\n        Compute the rdm_diff gradient\n        Args:\n            uvec            : the correlation potential vector\n        Return:\n            the_gradient    : a list with the size of the number of u values in uvec\n                              Each element of this list is an array of derivative corresponding to each rs.\n                             \n        '''\n        \n        RDM_deriv_kpts = self.construct_1RDM_response_kpts(uvec)\n        the_gradient = []    \n        for u in range(self.Nterms):\n            RDM_deriv_R0 = self.local.k_to_R0(RDM_deriv_kpts[:,u,:,:])    # Transform RDM_deriv from k-space to the reference cell         \n            if self.SC_CFtype in ['F','diagF']: \n                emb_error_deriv = self.local.loc_kpts_to_emb(RDM_deriv_kpts[:,u,:,:], self.emb_orbs[:,:,:self.Nimp])\n            elif self.SC_CFtype in ['FB','diagFB']:\n                emb_error_deriv = self.local.loc_kpts_to_emb(RDM_deriv_kpts[:,u,:,:], self.emb_orbs) \n            if self.SC_CFtype in ['diagF', 'diagFB']: emb_error_deriv = np.diag(emb_error_deriv)\n            the_gradient.append(emb_error_deriv)\n\n        return np.asarray(the_gradient)       \n\n    def glob_cost_func(self, uvec):\n        '''TODO write it \n        '''\n        rdm_diff = self.get_glob_rdm_diff(uvec)\n        cost = np.power(rdm_diff, 2).sum()\n        return cost \n        \n    def glob_cost_func_grad(self, uvec):\n        '''TODO\n        '''\n        rdm_diff = self.get_glob_rdm_diff(uvec)   \n        rdm_diff_grad = self.glob_rdm_diff_grad(uvec)  \n        CF_grad = np.zeros(self.Nterms)\n        \n        for u in range(self.Nterms):\n            CF_grad[u] = np.sum(2 * rdm_diff * rdm_diff_grad[u])\n        return CF_grad\n        \n    def get_glob_rdm_diff(self, uvec):\n        '''\n        Calculating the different between mf-1RDM (transformed in schmidt basis) and correlated-1RDM for the unit cell\n        Args:\n            uvec            : the correlation potential vector\n        Return:\n            error            : an array of errors for the unit cell.\n        '''                     \n        loc_OEH_kpts, loc_1RDM_kpts, loc_1RDM_R0 = self.local.make_loc_1RDM(self.uvec2umat(uvec), self.mask4Gamma, OEH_type=self.OEH_type, dft_HF=self.dft_HF)\n        error = loc_1RDM_R0 - self.loc_corr_1RDM_R0\n        return error\n        \n\n    def glob_rdm_diff_grad(self, uvec):\n        '''\n        Compute the rdm_diff gradient\n        Args:\n            uvec            : the correlation potential vector\n        Return:\n            the_gradient    : a list with the size of the number of u values in uvec\n                              Each element of this list is an array of derivative corresponding to each rs.\n                             \n        '''\n        \n        RDM_deriv_kpts = self.construct_1RDM_response_kpts(uvec)\n        the_gradient = []    \n\n        for u in range(self.Nterms):\n            RDM_deriv_R0 = self.local.k_to_R0(RDM_deriv_kpts[:,u,:,:])    # Transform RDM_deriv from k-space to the reference cell         \n            the_gradient.append(RDM_deriv_R0)\n        \n        return np.asarray(the_gradient)\n        \n    def alt_cost_func(self, uvec):\n        '''\n        TODO: DEBUGGING\n        '''\n        \n        umat = self.uvec2umat(uvec)\n                     \n        loc_OEH_kpts, loc_1RDM_kpts, loc_1RDM_R0 = self.local.make_loc_1RDM(umat, self.mask4Gamma, OEH_type=self.OEH_type, dft_HF=self.dft_HF)\n        if self.OEH_type == 'FOCK':\n            OEH = self.local.loc_actFOCK_kpts #+umat\n            OEH = self.local.k_to_R(OEH)\n            e_fun = np.trace(OEH.dot(loc_1RDM_R0))\n        else: \n            tprint.print_msg('Other type of 1e electron is not supported')\n          \n        rdm_diff = self.glob_rdm_diff(uvec)[0]  \n        e_cstr = np.sum(umat_Rs*rdm_diff)  \n\n        return -e_fun-e_cstr   \n        \n    def alt_cost_func_grad(self, uvec):\n        '''\n        TODO: DEBUGGING\n        '''\n        rdm_diff = self.glob_rdm_diff(uvec)[0]\n        return -rdm_diff\n        \n######################################## USEFUL FUNCTION for pDMET class ######################################## \n\n    def make_irred_kpts(self, kpts=None):\n        '''\n        Make k-dependent uvec considering kmesh symmetry\n        Attributes:\n            kpts_irred      : a list of irreducible k-point   \n            sym_id          : a list of symmetry label. k and -k should have the same label\n            sym_map         : used to map the uvec (irreducible k-points) to umat (full k-points)        \n        '''        \n        if kpts is None: kpts = self.kpts\n        kpts = np.asarray(kpts)\n        \n        sym_id = np.asarray(range(self.Nkpts))   \n        kpts_irred, sym_counts = np.unique(sym_id, return_counts=True)                        \n        sym_map = [np.where(kpts_irred == sym_id[kpt])[0][0] for kpt in range(self.Nkpts)]  \n        nkpts_irred = kpts_irred.size         \n        num_u = nkpts_irred * self.Nterms      \n        uvec = np.zeros(num_u, dtype=np.float64)\n        \n        return kpts_irred, sym_counts, sym_map, uvec            \n    \n    def make_mask(self, is_gamma=False):\n        '''\n        Make a mask used to convert uvec to umat and vice versa\n        '''     \n        if is_gamma:\n            impCluster = np.asarray(self._impOrbs)\n            if self.SC_CFtype in ['F', 'FB']:\n                mask = np.matrix(impCluster).T.dot(np.matrix(impCluster)) == 1\n                mask[np.tril_indices(self.Norbs,-1)] = False\n            else:\n                mask = np.zeros([self.Norbs,self.Norbs], dtype=bool)\n                mask[impCluster==1, impCluster==1] = True\n        else:\n            mask = np.zeros([self.Nimp, self.Nimp], dtype=bool)            \n            if self.SC_CFtype in ['F', 'FB']:\n                mask[np.triu_indices(self.Nimp)] = True\n            else:\n                np.fill_diagonal(mask, True)      \n        return mask            \n\n    def uvec2umat(self, uvec):\n        '''\n        Convert uvec to the umat which is will be added up to the local one-electron Hamiltonian at each k-point\n        '''  \n        if self.dft_CF:\n            the_umat = uvec        \n        elif self._is_gamma:\n            the_umat = np.zeros([self.Norbs, self.Norbs], dtype=np.float64)          \n            the_umat[self.mask] = uvec\n            the_umat = the_umat.T\n            the_umat[self.mask] = uvec \n        else:\n            the_umat = np.zeros([self.Nimp, self.Nimp], dtype=np.float64)          \n            the_umat[self.mask] = uvec\n            the_umat = the_umat.T\n            the_umat[self.mask] = uvec\n            \n        return np.asarray(the_umat)                \n\n    def umat2uvec(self, umat):\n        '''\n        Convert umat to the uvec\n        '''           \n        if self.dft_CF == True:\n            return umat\n        else:\n            return umat[self.mask]       \n        \n    def make_H1(self, is_gamma=False, impCluster=None):\n        '''\n        The H1 is the correlation potential operator, this function taking advantage of sparsity of the u matrix in calculating gradient of 1-RDM at each k-point\n        Return:\n            H1start: \n            H1row: \n            H1col: \n        '''\n        if is_gamma == True:\n            assert impCluster is not None, \"In Gamma-point sampling, you need a list to define impurity orbitals\"\n        \n        theH1 = []\n        if is_gamma == True:\n\n            imp_indices = np.where(np.asarray(impCluster) == 1)[0]\n            if self.SC_CFtype in ['diagF', 'diagFB']:\n                for idx in imp_indices:\n                    H1 = np.zeros([self.Norbs, self.Norbs])\n                    H1[idx, idx] = 1\n                    theH1.append(H1)\n            else:      \n                for i, row in enumerate(imp_indices):\n                    for col in imp_indices[i:]:\n                        H1 = np.zeros([self.Norbs, self.Norbs])\n                        H1[row, col] = 1\n                        H1[col, row] = 1      \n                        theH1.append(H1)  \n        else:\n            if self.SC_CFtype in ['diagF', 'diagFB']:\n                for row in range(self.Nimp):\n                    H1 = np.zeros([self.Nimp, self.Nimp])\n                    H1[row, row] = 1\n                    theH1.append(H1)\n            else:        \n                for row in range(self.Nimp):                                    #Fitting the whole umat\n                    for col in range(row, self.Nimp):\n                        H1 = np.zeros([self.Nimp, self.Nimp])\n                        H1[row, col] = 1\n                        H1[col, row] = 1                                \n                        theH1.append(H1)    \n    \n        # Convert the sparse H1 to one dimension H1start, H1row, H1col arrays used in libdmet.rhf_response()\n        H1start = []\n        H1row   = []\n        H1col   = []\n        H1start.append(0)\n        totalsize = 0\n        for count in range(len(theH1)):\n            rowco, colco = np.where(theH1[count] == 1)\n            totalsize += len(rowco)\n            H1start.append(totalsize)\n            for count2 in range(len(rowco)):\n                H1row.append(rowco[count2])\n                H1col.append(colco[count2])\n        H1start = np.array(H1start)\n        H1row   = np.array(H1row)\n        H1col   = np.array(H1col)\n        \n        return theH1, H1start, H1row, H1col\n        \n    def construct_1RDM_response_kpts(self, uvec):\n        '''\n        Calculate the derivative of 1RDM\n        TODO: Currently the number of electron is the same at every k-point. This is not the case for\n        metallic sytem. So need to consider this later\n        '''\n            \n        rdm_deriv_kpts = []\n        loc_actFOCK_kpts = self.local.loc_actFOCK_kpts + self.uvec2umat(uvec)\n        Norb = loc_actFOCK_kpts.shape[-1]\n        for kpt in range(self.Nkpts):\n            #rdm_deriv = libdmet.rhf_response_c(Norb, self.Nterms, self.numPairs, self.H1start, self.H1row, self.H1col, loc_actFOCK_kpts[kpt])\n            rdm_deriv = libdmet.rhf_response(Norb, self.Nterms, self.numPairs, self.H1start, self.H1row, self.H1col, loc_actFOCK_kpts[kpt].real)\n            rdm_deriv = np.complex128(rdm_deriv)\n            rdm_deriv_kpts.append(rdm_deriv)\n            \n        return np.asarray(rdm_deriv_kpts) \n\n    def construct_global_1RDM(self):\n        ''' Construct the global 1RDM in the R-space'''\n        \n        imp_1RDM = lib.einsum('Rim,mn,jn->Rij', self.emb_orbs, self.emb_corr_1RDM, self.emb_orbs[0])\n        RDM1_Rs = self.local.get_1RDM_Rs(imp_1RDM)\n        RDM1_Rs = 0.5*(RDM1_Rs.T + RDM1_Rs)          # make sure the global DM is hermitian\n        \n        return RDM1_Rs      \n    \n######################################## POST pDMET ANALYSIS ######################################## \n    def get_bands(self, cell=None, dm_kpts=None, kpts=None, cost_func='glob', method='BFGS'):\n        ''' Embedding 1RDM is used to construct the global 1RDM.\n            The 'closest' mean-field 1RDM to the global 1RDM is found by minizing the norm(D_global - D_mf) \n        '''     \n        if cell is None: cell = self.cell\n        if kpts is None: kpts = self.kmf.kpts\n        \n        # Compute the total DM in the local basis\n        if cost_func == 'FB':\n            CF = self.cost_func\n            CF_grad = self.cost_func_grad\n            self.SC_CFtype = 'FB'\n        elif cost_func == 'F':\n            CF = self.cost_func\n            CF_grad = self.cost_func_grad\n            self.SC_CFtype = 'F'\n        else:\n            CF = self.glob_cost_func\n            CF_grad = self.glob_cost_func_grad\n       \n        if self.dft_CF and self.xc == 'PBE0':\n            result = optimize.minimize(self.CF, self.uvec, method='L-BFGS-B', jac=None, options={'disp': False, 'gtol': 1e-6}, bounds=self.bounds)\n        else:\n            result = optimize.minimize(CF, self.uvec, method=method, jac=None, options={'disp': False, 'gtol': 1e-12})\n \n        uvec = result.x\n        error = np.linalg.norm(self.get_glob_rdm_diff(uvec))\n        if result.success == False:     \n            tprint.print_msg('Band structure error: %12.8f' % (error))\n            tprint.print_msg(\" WARNING: Correlation potential is not converged\")\n        else:\n            tprint.print_msg('Band structure error: %12.8f' % (error))\n            \n        if self.dft_CF:\n            eigvals, eigvecs = self.local.make_loc_1RDM_kpts(self.uvec2umat(uvec), self.mask4Gamma, OEH_type=self.xc, get_band=True, dft_HF=self.dft_HF)\n        else:\n            eigvals, eigvecs = self.local.make_loc_1RDM_kpts(self.uvec2umat(uvec), self.mask4Gamma, OEH_type='FOCK', get_band=True, dft_HF=self.dft_HF)\n\n        dmet_orbs = lib.einsum('kpq,kqr->kpr', self.local.ao2lo, eigvecs) # embedding orbs are spaned by AO instead of MLWFs here\n        mo_coeff_kpts = []\n        mo_energy_kpts = []\n        for kpt in range(self.Nkpts):\n            mo_coeff = self.kmf.mo_coeff_kpts[kpt].copy()\n            mo_coeff[:, self.w90.band_included_list] = dmet_orbs[kpt]\n            mo_energy = self.kmf.mo_energy_kpts[kpt].copy()\n            mo_energy[self.w90.band_included_list] = eigvals[kpt]\n            mo_coeff_kpts.append(mo_coeff)\n            mo_energy_kpts.append(mo_energy)\n            \n        ovlp = self.kmf.get_ovlp()\n        class fake_kmf:\n            def __init__(self):\n                self.kpts = kpts\n                self.mo_energy_kpts = mo_energy_kpts\n                self.mo_coeff_kpts = mo_coeff_kpts  \n                self.get_ovlp  = lambda *arg: ovlp\n                \n        kmf = fake_kmf()\n        \n        return kmf\n        \n    def interpolate_band(self, frac_kpts, use_ws_distance=True, ws_search_size=[2,2,2], ws_distance_tol=1e-6):\n        ''' Interpolate the band structure using the Slater-Koster scheme\n            Return:\n                eigenvalues and eigenvectors at the desired kpts\n        '''\n        OEH_kpts, eigvals, eigvecs = self.local.make_loc_1RDM_kpts(self.uvec2umat(self.uvec), self.mask4Gamma, OEH_type=self.xc, get_ham=True, dft_HF=self.dft_HF)\n        eigvals, eigvecs = self.w90.interpolate_band(frac_kpts, OEH_kpts, use_ws_distance, \n                                                    ws_search_size, ws_distance_tol)\n        return (eigvals, eigvecs)\n    \n        \n    def get_supercell_Hamiltonian(self, twoS = 0):        \n        '''Make mf object of the effective Hamiltonian for a molecular solver.\n        '''        \n        \n        # 1-ERI\n        Hcore_kpts = self.local.loc_actOEI_kpts \n        Hcore = self.local.k_to_R(Hcore_kpts) \n        \n        # 2-ERI\n        TEI = self.local.get_loc_TEI()\n        \n        from pyscf import gto, scf,ao2mo        \n        mol = gto.Mole()\n        mol.build(verbose = self.verbose)\n        mol.atom.append(('He', (0, 0, 0)))\n        mol.nelectron = self.Nelec_total\n        mol.incore_anyway = True\n        mol.spin = twoS\n        mol.verbose = self.verbose\n        if mol.spin == 0:        \n            mf = scf.RHF(mol)    \n        else:\n            mf = scf.ROHF(mol)         \n        mf.get_hcore = lambda *args: Hcore\n        mf.get_ovlp = lambda *args: np.eye(self.Norbs)\n        mf._eri = ao2mo.restore(8, TEI, self.Norbs)\n        mf.scf()        \n        DMloc = np.dot(np.dot(mf.mo_coeff, np.diag(mf.mo_occ)), mf.mo_coeff.T)\n        if ( mf.converged == False ):\n            mf.newton().kernel(dm0=DMloc)\n            DMloc = np.dot(np.dot(mf.mo_coeff, np.diag(mf.mo_occ)), mf.mo_coeff.T)                \n        \n        return mol, mf      \n\n    def plot(self, orb = 'emb', grid = [50,50,50], path='./'):        \n        '''Plot orbitals for CAS solvers\n            orb = 'emb', 'mf', 'mc', 'mc_nat'\n        '''            \n\n        emb_orbs = self.emb_orbs[0]    \n        if orb == 'wfs' : \n            rotate_mat = None        \n        if orb == 'emb' : \n            rotate_mat = emb_orbs                  \n        elif orb == 'mf'  : \n            mo = self.qcsolver.mf.mo_coeff       \n            rotate_mat = emb_orbs.dot(mo)    \n        elif orb == 'mc'  : \n            mo = self.qcsolver.mo\n            rotate_mat = emb_orbs.dot(mo)      \n        elif orb == 'nat' : \n            mo = self.qcsolver.mo_nat  \n            rotate_mat = emb_orbs.dot(mo)  \n        elif orb == 'nto':\n            assert self.nevpt2_roots is not None, \"NEVPT2 must be called to calculate the NTOs\"\n            pass\n            \n        tplot.plot_wf(self.w90, rotate_mat, path + '/' + orb, self.kmesh, grid)        \n\n\n    def get_trans_dipole(self):        \n        '''Calculate transition dipole\n        '''     \n        import scipy\n        assert self.nevpt2_roots is not None, \"NEVPT2 must be called to calculate the NTOs\"\n        charges = self.cell.atom_charges()\n        coords = self.cell.atom_coords()\n        nuc_charge_center = np.einsum('z,zx->x', charges, coords) / charges.sum()\n        self.cell.set_common_orig_(nuc_charge_center)\n        dip_ints = self.cell.intor('cint1e_r_sph', comp=3) \n        ao2eo = self.local.get_ao2eo(self.emb_orbs)[0]\n        def makedip(ci_id):\n            t_dm1_emb = self.t_dm1s[ci_id]\n            # transform density matrix from MO to AO representation\n            t_dm1_ao = ao2eo @ t_dm1_emb @ ao2eo.T.conj()\n            return np.einsum('xij,ji->x', dip_ints, t_dm1_ao).real\n\n        for i in range(len(self.e_nept2_tot)):\n            dipole = makedip(i)\n            norm = np.linalg.norm(dipole)\n            print('Transition dipole between |0> and |{0:d}>: {1:3.5f} {2:3.5f} {3:3.5f} | Norm: {4:3.5f}'.format(i, dipole[0], dipole[1], dipole[2], norm))\n", "meta": {"hexsha": "066ccc6d21ed918db079901afeefca25c8ea0e86", "size": 57498, "ext": "py", "lang": "Python", "max_stars_repo_path": "pdmet/dmet.py", "max_stars_repo_name": "hungpham2017/pdmet", "max_stars_repo_head_hexsha": "50848c9f22879f8154e86af783d8036f304bac54", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pdmet/dmet.py", "max_issues_repo_name": "hungpham2017/pdmet", "max_issues_repo_head_hexsha": "50848c9f22879f8154e86af783d8036f304bac54", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pdmet/dmet.py", "max_forks_repo_name": "hungpham2017/pdmet", "max_forks_repo_head_hexsha": "50848c9f22879f8154e86af783d8036f304bac54", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.4806070826, "max_line_length": 235, "alphanum_fraction": 0.5459146405, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 15218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.3140505385717078, "lm_q1q2_score": 0.1643804378133936}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nContains relevant classes for executing transition state searches using the\nfreezing string method. The resulting transition state should be further\noptimized using another method in order to find the true transition state.\n\"\"\"\n\nfrom __future__ import division\n\nimport logging\nimport os\nimport time\n\nimport numpy as np\nfrom scipy import optimize\n\nimport util\nimport constants\nimport props\nfrom quantum import QuantumError\nfrom node import Node\nfrom interpolation import LST\n\n###############################################################################\n\ndef removeDuplicateBondChanges(bc):\n    \"\"\"\n    Given a list of bond changes as a numpy vector, remove duplicates.\n    \"\"\"\n    if bc.size:\n        out = []\n        for b in bc:\n            if b[1] > b[0]:\n                out.append(b)\n\n        return np.vstack(out)\n    else:\n        return bc\n\n###############################################################################\n\nclass String(object):\n    \"\"\"\n    Base class from which the freezing string method can inherit.\n    The attributes are:\n\n    =============== ======================== ===================================\n    Attribute       Type                     Description\n    =============== ======================== ===================================\n    `name`          ``str``                  The name of the object\n    `reactant`      :class:`node.Node`       A node object containing the coordinates and atoms of the reactant molecule\n    `product`       :class:`node.Node`       A node object containing the coordinates and atoms of the product molecule\n    `reac_cmat`     :class:`numpy.ndarray`   The connectivity matrix of the reactant\n    `bc`            ``list``                 A list of bond changes between reactant and product\n    `nsteps`        ``int``                  The number of gradient evaluations per node optimization\n    `nnode`         ``int``                  The desired number of nodes, which determines the spacing between them\n    `tol`           ``float``                The gradient convergence tolerance (Hartree/Angstrom)\n    `nLSTnodes`     ``int``                  The number of nodes on a high-density LST interpolation path\n    `Qclass`        ``class``                A class representing the quantum software\n    `nproc`         ``int``                  The number of processors available for the string method\n    `output_dir`    ``str``                  The path to the output directory\n    `kwargs`        ``dict``                 Additional arguments for quantum calculations\n    `node_spacing`  ``float``                The interpolation distance between nodes\n    `ngrad`         ``int``                  The total number of gradient evaluations\n    `logger`        :class:`logging.Logger`  The logger\n    =============== ======================== ===================================\n\n    \"\"\"\n\n    def __init__(self, reactant, product, name='0000', logger=None,\n                 nsteps=4, nnode=15, tol=0.1, nlstnodes=100, qprog='qchem', **kwargs):\n        if reactant.atoms != product.atoms:\n            raise Exception('Atom labels of reactant and product do not match')\n        self.reactant = reactant\n        self.product = product\n        self.name = name\n\n        self.reac_cmat = self.reactant.toConnectivityMat()\n        self.bc = None\n        self.findBondChanges()\n\n        self.nsteps = int(nsteps)\n        self.nnode = int(nnode)\n        self.tol = float(tol)\n        self.nLSTnodes = int(nlstnodes)\n\n        self.Qclass = util.assignQclass(qprog)\n        self.nproc = int(kwargs.get('nproc', 1))\n        self.output_dir = kwargs.get('output_dir', '')\n        self.kwargs = kwargs\n\n        self.node_spacing = None\n        self.ngrad = None\n\n        # Set up logger\n        if logger is None:\n            log_level = logging.INFO\n            logfile = 'output.' + self.name + '.log'\n            self.logger = util.initializeLog(log_level, os.path.join(self.output_dir, logfile))\n        else:\n            self.logger = logger\n\n    def findBondChanges(self):\n        \"\"\"\n        Save the list of bond changes between reactant and product.\n        \"\"\"\n        prod_cmat = self.product.toConnectivityMat()\n        Rmat = prod_cmat - self.reac_cmat\n        bc = np.transpose(np.nonzero(Rmat))\n        bc = removeDuplicateBondChanges(bc)\n        self.bc = bc.tolist()\n\n    def coincidenceObjective(self, angles):\n        \"\"\"\n        Defines the objective function for rotating the product structure to\n        obtain maximum coincidence in non-mass weighted Cartesian coordinates.\n        The rotation matrix is defined by the product of three separate\n        rotation matrices which describe rotations about the three principal\n        axes and are each defined by an angle in `angles` (i.e., angles[0]\n        corresponds to the angle of rotation about the x-axis, etc.). The objective\n        function is a measure of the \"distance\" between reactant and product.\n        \"\"\"\n        rotated_product = (util.rotationMatrix(angles).dot(self.product.coords.T)).T.flatten()\n        diff = self.reactant.coords.flatten() - rotated_product\n        return diff.dot(diff)\n\n    def align(self):\n        \"\"\"\n        Align the reactant and product structures to maximum coincidence in\n        non-mass weighted Cartesian coordinates. This is done by shifting the\n        centroids of both structures to the origin and rotating the molecules\n        in order to minimize the distance between them.\n        \"\"\"\n        # Translate reactant and product so that centroids coincide at the origin\n        self.reactant.translate(-self.reactant.getCentroid())\n        self.product.translate(-self.product.getCentroid())\n\n        # Find optimal rotation matrix iteratively\n        angles_guess = np.array([0.0, 0.0, 0.0])\n        result = optimize.minimize(self.coincidenceObjective, angles_guess, method='BFGS')\n        if not result.success:\n            message = ('Maximum coincidence alignment terminated with status ' +\n                       str(result.status) + ':\\n' + result.message + '\\n')\n            self.logger.warning(message)\n\n        # Check for positive eigenvalues to ensure that aligned structure is a minimum\n        eig_val = np.linalg.eig(result.hess_inv)[0]\n        if not all(eig_val > 0.0):\n            self.logger.warning('Not all Hessian eigenvalues were positive for the alignment process.\\n' +\n                                'The aligned structure may not be optimal.\\n')\n\n        # Rotate product to maximum coincidence\n        self.product.rotate(util.rotationMatrix(result.x))\n\n    def initialize(self, logHeader):\n        \"\"\"\n        Initialize the FSM/GSM job. Prints the header specified in the function\n        `logHeader`, aligns the product and reactant structure to maximum\n        coincidence in non-mass weighted Cartesian coordinates, and computes\n        the product and reactant energies.\n\n        A tuple of two lists is returned. The first one contains the reactant\n        and product nodes, and the second one contains their energies.\n        \"\"\"\n        # Log start timestamp\n        self.logger.info('\\n----------------------------------------------------------------------')\n        self.logger.info('String method initiated on ' + time.asctime() + '\\n')\n\n        # Print FSM header\n        logHeader()\n\n        # Find distance between product and reactant nodes and calculate\n        # interpolation distance after aligning product and reactant to maximum\n        # coincidence\n        self.logger.info('Aligning product and reactant structure to maximum coincidence')\n        self.align()\n        arclength = LST(self.reactant, self.product, self.nproc).getTotalArclength(self.nLSTnodes)\n        self.node_spacing = arclength / self.nnode\n        self.logger.info('Aligned reactant structure:\\n' + str(self.reactant))\n        self.logger.info('Aligned product structure:\\n' + str(self.product))\n        self.logger.info('Total reactant to product arc length:   {0:>8.4f} Angstrom'.format(arclength))\n        self.logger.info('Interpolation arc length for new nodes: {0:>8.4f} Angstrom'.format(self.node_spacing))\n\n        # Initialize gradient counter\n        self.ngrad = 0\n\n        # Initialize path by adding reactant and product structures and computing their energies\n        self.logger.info('Calculating reactant and product energies')\n        path = [self.reactant, self.product]\n        self.reactant.computeEnergy(self.Qclass, name='reac_energy.' + self.name, **self.kwargs)\n        self.product.computeEnergy(self.Qclass, name='prod_energy.' + self.name, **self.kwargs)\n        self.logger.info(\n            'Reactant: {0:.9f} Hartree; Product: {1:.9f} Hartree'.format(self.reactant.energy, self.product.energy)\n        )\n\n        return path\n\n    def finalize(self, start_time, success=True):\n        \"\"\"\n        Finalize the job.\n        \"\"\"\n        self.logger.info('Number of gradient evaluations during string method: {0}'.format(self.ngrad))\n        if success:\n            self.logger.info('\\nString method terminated successfully on ' + time.asctime())\n        else:\n            self.logger.warning('String method terminated abnormally on ' + time.asctime())\n        self.logger.info('Total string method run time: {0:.1f} s'.format(time.time() - start_time))\n        self.logger.info('----------------------------------------------------------------------\\n')\n\n    def writeStringfile(self, path):\n        \"\"\"\n        Write the nodes along the path and their corresponding energies\n        relative to the reactant energy (in kcal/mol) to the output file.\n        \"\"\"\n        with open(os.path.join(self.output_dir, 'string.{}.out'.format(self.name)), 'w') as f:\n            for node_num, node in enumerate(path):\n                f.write(str(len(node.atoms)) + '\\n')\n\n                energy = (node.energy - self.reactant.energy) * constants.hartree_to_kcal_per_mol\n                f.write('Energy = ' + str(energy) + '\\n')\n                f.write(str(node) + '\\n')\n\n    def writeDistMat(self, node, msg=None):\n        \"\"\"\n        Write the distance matrix at a node and check for undesired bond\n        changes.\n        \"\"\"\n        with open(os.path.join(self.output_dir, 'bond_changes.{}.out'.format(self.name)), 'a') as f:\n            if msg is not None:\n                f.write(msg + '\\n')\n\n            dist_mat = util.getDistMat(node.coords)\n\n            dmat_string = ''\n            for anum, row in enumerate(dist_mat):\n                line = ' '.join(['{:7.4f}'.format(d) for d in row])\n                dmat_string += '{}  {}\\n'.format(props.atomnum[node.atoms[anum]], line)\n\n            f.write(dmat_string)\n\n            if self.detectUndesiredBondChange(node):\n                f.write('Above distance matrix contains undesired bond change.\\n')\n\n    def detectUndesiredBondChange(self, node):\n        \"\"\"\n        Detect undesired bond changes that do not correspond to the desired\n        reaction between the given reactant and product. Returns a boolean.\n        \"\"\"\n        cmat = node.toConnectivityMat()\n        Rmat = cmat - self.reac_cmat\n        bc = np.transpose(np.nonzero(Rmat))\n        bc = removeDuplicateBondChanges(bc)\n        bc = bc.tolist()\n\n        for b in bc:\n            if b not in self.bc:\n                return True\n        else:\n            return False\n\n    @util.timeFn\n    def getPerpGrad(self, node, tangent, name='grad.0000'):\n        \"\"\"\n        Calculate and return a tuple of the perpendicular gradient and its\n        magnitude given a node and the string tangent. `name` is the name of\n        the quantum job to be executed.\n        \"\"\"\n        # Calculate gradient and energy\n        node.computeGradient(self.Qclass, name=name, **self.kwargs)\n        self.logger.debug('Gradient:\\n' + str(node.gradient.reshape(len(node.atoms), 3)))\n        self.logger.debug('Energy: ' + str(node.energy))\n\n        # Calculate perpendicular gradient and its magnitude\n        perp_grad = (np.eye(3 * len(node.atoms)) - np.outer(tangent, tangent)).dot(node.gradient.flatten())\n        perp_grad_mag = np.linalg.norm(perp_grad)\n        self.logger.debug('Perpendicular gradient:\\n' + str(perp_grad.reshape(len(node.atoms), 3)))\n        self.logger.debug('Magnitude: ' + str(perp_grad_mag))\n\n        return perp_grad, perp_grad_mag\n\n    @staticmethod\n    def getSearchDir(hess_inv, perp_grad, line_search_factor, desired_energy_change):\n        \"\"\"\n        Calculate and return Newton-Raphson search direction, scaling factor,\n        and exact line search condition given the perpendicular gradient, the\n        inverse Hessian, the line search factor, and the minimum desired energy\n        change.\n        \"\"\"\n        # Calculate search direction\n        direction = hess_inv.dot(perp_grad)\n        direction_norm = np.linalg.norm(direction)\n        search_dir = - direction / direction_norm\n\n        # Calculate maximum and minimum scaling factors\n        scale_factor_max = 0.05 / np.absolute(search_dir).max()\n        scale_factor_min = (1.0 - line_search_factor) * direction_norm\n\n        # Calculate scaling factor\n        scale_factor = - 2.0 * desired_energy_change / (perp_grad.dot(search_dir))\n\n        # Refine scaling factor based on limits\n        if scale_factor < scale_factor_min:\n            scale_factor = scale_factor_min\n        if scale_factor > scale_factor_max:\n            scale_factor = scale_factor_max\n\n        return search_dir, scale_factor\n\n    @staticmethod\n    def updateHess(hess_inv, step, grad_diff):\n        \"\"\"\n        Update and return the inverse Hessian according to the BFGS update\n        scheme given the step and the difference in the gradients.\n        \"\"\"\n        denom = step.dot(grad_diff)\n        return hess_inv + (1.0 + grad_diff.dot((hess_inv.dot(grad_diff))) / denom) * np.outer(step, step) / denom - \\\n            (np.outer(step, grad_diff.dot(hess_inv)) + np.outer(hess_inv.dot(grad_diff), step)) / denom\n\n###############################################################################\n\nclass FSM(String):\n    \"\"\"\n    Freezing string method.\n    The attributes are:\n\n    ================== ===================== ==================================\n    Attribute          Type                  Description\n    ================== ===================== ==================================\n    `lsf`              ``float``             A line search factor determining how strong the line search is\n    ================== ===================== ==================================\n\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        self.lsf = float(kwargs.pop('lsf', 0.7))\n        if not (0.0 < self.lsf < 1.0):\n            raise ValueError('Line search factor must be between 0 and 1')\n\n        super(FSM, self).__init__(*args, **kwargs)\n\n    @util.timeFn\n    def getNodes(self, node1, node2):\n        \"\"\"\n        Generates new FSM nodes based on an LST interpolation path between the\n        two nodes. If the distance between the nodes is less than the desired\n        node spacing, then nothing is returned. Only one node is generated\n        halfway between the two previous nodes if the distance between them is\n        between one and two times the desired node spacing. Otherwise, two\n        nodes are generated at the desired node spacing from the end nodes.\n\n        The tangent vectors at each node are also returned. For the LST path,\n        this vector is determined from the two LST nodes that are directly\n        adjacent to the interpolated node.\n        \"\"\"\n        if self.node_spacing is None:\n            raise Exception('Interpolation distance has to be set first')\n\n        # Create high density LST path between nodes\n        path, arclength = LST(node1, node2, self.nproc).getLSTpath(self.nLSTnodes)\n\n        # Find new nodes based on nodes that are closest to desired arc length spacing\n        if arclength[-1] < self.node_spacing:\n            return None, None\n        elif self.node_spacing <= arclength[-1] <= 2.0 * self.node_spacing:\n            new_node_idx = util.findClosest(arclength, arclength[-1] / 2.0)\n            return path[new_node_idx], path[new_node_idx - 1].getTangent(path[new_node_idx + 1])\n        new_node1_idx = util.findClosest(arclength, self.node_spacing)\n        new_node2_idx = util.findClosest(arclength, arclength[-1] - self.node_spacing)\n        tangent1 = path[new_node1_idx - 1].getTangent(path[new_node1_idx + 1])\n        tangent2 = path[new_node2_idx + 1].getTangent(path[new_node2_idx - 1])\n        return (path[new_node1_idx], path[new_node2_idx]), (tangent1, tangent2)\n\n    def execute(self):\n        \"\"\"\n        Run the freezing string method and return a tuple containing all\n        optimized nodes along the FSM path. The output file is updated each\n        time nodes have been optimized.\n        \"\"\"\n        start_time = time.time()\n        FSMpath = self.initialize(self.logHeader)\n\n        # The minimum desired energy change in an optimization step should be\n        # at least the difference between reactant and product\n        energy_diff = abs(FSMpath[1].energy - FSMpath[0].energy) * 627.5095\n        if energy_diff < 2.5:\n            min_en_change = energy_diff\n        else:\n            min_en_change = 2.5\n\n        # Impose restriction on maximum number of nodes that can be created in\n        # case FSM does not converge\n        for i in range(2 * self.nnode):\n            self.logger.info('\\nStarting iteration {0}\\n'.format(i + 1))\n\n            # Compute indices for inserting new nodes into FSM path\n            innernode_p_idx = len(FSMpath) // 2\n            innernode_r_idx = innernode_p_idx - 1\n\n            # Compute distance between innermost nodes\n            distance = FSMpath[innernode_r_idx].getDistance(FSMpath[innernode_p_idx])\n            self.logger.info('Linear distance between innermost nodes: {0:.4f} Angstrom'.format(distance))\n\n            # Obtain interpolated nodes\n            nodes, tangents = self.getNodes(FSMpath[innernode_r_idx], FSMpath[innernode_p_idx])\n\n            # Return if no new nodes were generated\n            if nodes is None:\n                self.logger.info('No new nodes were generated')\n                self.finalize(start_time)\n                self.writeStringfile(FSMpath)\n                return FSMpath\n\n            # Optimize halfway node if only one was generated and return\n            elif isinstance(nodes, Node):\n                self.logger.info('Added one node:\\n' + str(nodes))\n\n                # Compute distance from reactant and product side innermost nodes\n                self.logger.info('Linear distance from innermost reactant side node: {0:>8.4f} Angstrom'.\n                                 format(nodes.getDistance(FSMpath[innernode_r_idx])))\n                self.logger.info('Linear distance from innermost product side node:  {0:>8.4f} Angstrom'.\n                                 format(nodes.getDistance(FSMpath[innernode_p_idx])))\n\n                # Perpendicular optimization\n                self.logger.info('Optimizing final node')\n                self.writeDistMat(nodes, msg='Distance matrix before perpendicular optimization (final node):')\n                self.logger.debug('Tangent:\\n' + str(tangents.reshape(len(nodes.atoms), 3)))\n                self.perpOpt(nodes, tangents, min_desired_energy_change=min_en_change)\n                self.logger.info('Energy = {0:.9f} Hartree'.format(nodes.energy))\n\n                self.logger.info('Optimized node:\\n' + str(nodes))\n                self.logger.info('After opt distance from innermost reactant side node: {0:>8.4f} Angstrom'.\n                                 format(nodes.getDistance(FSMpath[innernode_r_idx])))\n                self.logger.info('After opt distance from innermost product side node:  {0:>8.4f} Angstrom'.\n                                 format(nodes.getDistance(FSMpath[innernode_p_idx])))\n                self.logger.info('')\n\n                # Insert optimized node and corresponding energy into path\n                FSMpath.insert(innernode_p_idx, nodes)\n\n                self.finalize(start_time)\n                self.writeStringfile(FSMpath)\n                return FSMpath\n\n            # Optimize new nodes\n            else:\n                self.logger.info('Added two nodes:\\n' + str(nodes[0]) + '\\n****\\n' + str(nodes[1]))\n\n                # Compute distance from reactant and product side innermost nodes\n                self.logger.info('Linear distance between previous and current reactant side nodes: {0:>8.4f} Angstrom'.\n                                 format(nodes[0].getDistance(FSMpath[innernode_r_idx])))\n                self.logger.info('Linear distance between previous and current product side nodes:  {0:>8.4f} Angstrom'.\n                                 format(nodes[1].getDistance(FSMpath[innernode_p_idx])))\n\n                # Perpendicular optimization\n                self.logger.info('Optimizing new reactant side node')\n                self.writeDistMat(nodes[0], msg='Distance matrix before perpendicular optimization (reactant side):')\n                self.logger.debug('Tangent:\\n' + str(tangents[0].reshape(len(nodes[0].atoms), 3)))\n                self.perpOpt(nodes[0], tangents[0], nodes[1], min_en_change)\n                self.logger.info('Energy = {0:.9f} Hartree'.format(nodes[0].energy))\n\n                self.logger.info('Optimizing new product side node')\n                self.writeDistMat(nodes[1], msg='Distance matrix before perpendicular optimization (product side):')\n                self.logger.debug('Tangent:\\n' + str(tangents[1].reshape(len(nodes[1].atoms), 3)))\n                self.perpOpt(nodes[1], tangents[1], nodes[0], min_en_change)\n                self.logger.info('Energy = {0:.9f} Hartree'.format(nodes[1].energy))\n\n                self.logger.info('Optimized nodes:\\n' + str(nodes[0]) + '\\n****\\n' + str(nodes[1]))\n                self.logger.info(\n                    'After opt distance between previous and current reactant side nodes: {0:>8.4f} Angstrom'.\n                    format(nodes[0].getDistance(FSMpath[innernode_r_idx]))\n                )\n                self.logger.info(\n                    'After opt distance between previous and current product side nodes:  {0:>8.4f} Angstrom'.\n                    format(nodes[1].getDistance(FSMpath[innernode_p_idx]))\n                )\n                self.logger.info('')\n\n                # Insert optimized nodes and corresponding energies into path\n                FSMpath.insert(innernode_p_idx, nodes[1])\n                FSMpath.insert(innernode_p_idx, nodes[0])\n                self.writeStringfile(FSMpath)\n\n        self.finalize(start_time, success=False)\n        self.writeStringfile(FSMpath)\n        return FSMpath\n\n    @util.timeFn\n    def perpOpt(self, node, tangent, other_node=None, min_desired_energy_change=2.5):\n        \"\"\"\n        Optimize node in direction of negative perpendicular gradient using the\n        Newton-Raphson method with a BFGS Hessian update scheme. Requires input\n        of tangent vector between closest two nodes on the string so that the\n        appropriate perpendicular gradient can be calculated. Also requires\n        that the innermost node on the other side of the string is input so\n        that the forward progress towards joining string ends can be assessed.\n        If no other node is specified, then the node is optimized without such\n        a constraint.\n\n        Returns the energy of the optimized node in Hartree.\n\n        Set `min_desired_energy_change` to the energy difference between\n        reactant and product if the difference is less than 2.5 kcal/mol.\n        \"\"\"\n\n        # Compute maximum allowed distance between nodes based on initial distance\n        if other_node is not None:\n            max_distance = node.getDistance(other_node) + 0.5 * self.node_spacing\n        else:\n            max_distance = 0\n\n        # Initialize Hessian inverse to identity matrix\n        identity_mat = np.eye(3 * len(node.atoms))\n        hess_inv = np.copy(identity_mat)\n\n        # Convert units to Hartree\n        min_desired_energy_change /= constants.hartree_to_kcal_per_mol\n\n        # Calculate perpendicular gradient and set node energy\n        perp_grad, perp_grad_mag = self.getPerpGrad(node, tangent, name='grad.{}.0'.format(self.name))\n        self.ngrad += 1\n        energy_old = node.energy\n\n        # Create empty array for storing old perpendicular gradient\n        perp_grad_old = np.empty_like(perp_grad)\n\n        k = 1\n        unstable = False\n        while k <= self.nsteps:\n            # Calculate desired change in energy\n            desired_energy_change = max(energy_old - node.energy, min_desired_energy_change)\n\n            # Calculate search direction, scaling factor, and exact line search condition\n            search_dir, scale_factor = self.getSearchDir(hess_inv, perp_grad, self.lsf, desired_energy_change)\n\n            # Handle unstable searches by reinitializing the Hessian\n            if scale_factor < 0.0:\n                # Terminate if resetting Hessian did not resolve instability\n                if unstable:\n                    self.logger.warning('Optimization terminated prematurely due to unstable scaling factor')\n                    break\n                unstable = True\n                np.copyto(hess_inv, identity_mat)\n                continue\n            unstable = False\n\n            # Take minimization step\n            step = scale_factor * search_dir\n            node.displaceCoordinates(step.reshape(len(node.atoms), 3))\n            self.logger.debug('Updated coordinates:\\n' + str(node))\n            self.writeDistMat(node, msg='After step {}:'.format(k))\n\n            # Save old values\n            np.copyto(perp_grad_old, perp_grad)\n            energy_old = node.energy\n\n            # Calculate new perpendicular gradient and set energy\n            try:\n                perp_grad, perp_grad_mag = self.getPerpGrad(node, tangent, name='grad.{}.{}'.format(self.name, k))\n            except QuantumError:\n                self.logger.info('SCF error ignored. Previous gradient used.')\n                grad_success = False\n                pass  # Ignore error and use previous gradient\n            else:\n                grad_success = True\n\n            self.ngrad += 1\n\n            # Check termination conditions:\n            #     - Maximum number of steps\n            #     - Energy increase from previous step\n            #     - Small energy change\n            #     - Stable line search condition\n            #     - Perpendicular gradient tolerance reached\n            #     - Exceeding of maximum distance\n            if k == self.nsteps:\n                self.logger.info('Optimization terminated because maximum number of steps was reached')\n                break\n            if grad_success:\n                if k > 1:\n                    energy_change = node.energy - energy_old\n                    if energy_change > 0.0:\n                        self.logger.info('Optimization terminated due to energy increase')\n                        node.displaceCoordinates(-step.reshape(len(node.atoms), 3))\n                        node.energy = energy_old\n                        break\n                    if abs(energy_change) < 0.5 / constants.hartree_to_kcal_per_mol:\n                        self.logger.info('Optimization terminated due to small energy change')\n                        break\n                if perp_grad_mag < self.tol:\n                    self.logger.info('Perpendicular gradient convergence criterion satisfied')\n                    break\n                if abs(perp_grad.dot(search_dir)) <= - self.lsf * perp_grad_old.dot(search_dir):\n                    self.logger.info('Optimization terminated due to stable line search condition')\n                    break\n                if node.getDistance(other_node) > max_distance:\n                    self.logger.warning('Optimization terminated because maximum distance between nodes was exceeded')\n                    break\n\n                # Update inverse Hessian\n                perp_grad_diff = perp_grad - perp_grad_old\n                hess_inv = self.updateHess(hess_inv, step, perp_grad_diff)\n                self.logger.debug('Hessian inverse:\\n' + str(hess_inv))\n\n            # Update counter\n            k += 1\n\n    def logHeader(self):\n        \"\"\"\n        Output a log file header containing identifying information about the\n        FSM job.\n        \"\"\"\n        self.logger.info('######################################################################')\n        self.logger.info('####################### FREEZING STRING METHOD #######################')\n        self.logger.info('######################################################################')\n        self.logger.info('# Number of gradient calculations per optimization step:     {0:>5}   #'.format(self.nsteps))\n        self.logger.info('# Number of nodes for calculation of interpolation distance: {0:>5}   #'.format(self.nnode))\n        self.logger.info('# Line search factor during Newton-Raphson optimization:     {0:>5.2f}   #'.format(self.lsf))\n        self.logger.info('# Gradient convergence tolerance (Hartree/Angstrom):         {0:>5.2f}   #'.format(self.tol))\n        self.logger.info('# Number of high density LST nodes:                          {0:>5}   #'.\n                         format(self.nLSTnodes))\n        self.logger.info('######################################################################')\n        self.logger.info('Reactant structure:\\n' + str(self.reactant))\n        self.logger.info('Product structure:\\n' + str(self.product))\n        self.logger.info('######################################################################\\n')\n\n###############################################################################\n\nif __name__ == '__main__':\n    import argparse\n\n    from main import readInput\n\n    # Set up parser for reading the input filename from the command line\n    parser = argparse.ArgumentParser(description='A freezing string method transition state search')\n    parser.add_argument('-n', '--nproc', default=1, type=int, metavar='N', help='number of processors')\n    parser.add_argument('-m', '--mem', default=2000, type=int, metavar='M', help='memory requirement')\n    parser.add_argument('file', type=str, metavar='infile', help='an input file describing the FSM job options')\n    args = parser.parse_args()\n\n    # Read input file\n    input_file = os.path.abspath(args.file)\n    options = readInput(input_file)\n\n    # Set output directory\n    output_dir = os.path.abspath(os.path.dirname(input_file))\n    options['output_dir'] = output_dir\n\n    # Set number of processors\n    options['nproc'] = args.nproc\n    options['mem'] = str(args.mem) + 'mb'\n\n    # Execute job\n    fsm = FSM(**options)\n    fsm.execute()\n", "meta": {"hexsha": "0a01b12f549384bc737236c50dc742d574745a19", "size": 30820, "ext": "py", "lang": "Python", "max_stars_repo_path": "ard/sm.py", "max_stars_repo_name": "ms860309/AutomaticReactionDiscovery", "max_stars_repo_head_hexsha": "ea009e1066058afd8a6a5d317d28d79016d8c93e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-12T11:42:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-12T11:42:49.000Z", "max_issues_repo_path": "ard/sm.py", "max_issues_repo_name": "ms860309/AutomaticReactionDiscovery", "max_issues_repo_head_hexsha": "ea009e1066058afd8a6a5d317d28d79016d8c93e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ard/sm.py", "max_forks_repo_name": "ms860309/AutomaticReactionDiscovery", "max_forks_repo_head_hexsha": "ea009e1066058afd8a6a5d317d28d79016d8c93e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.9101978691, "max_line_length": 120, "alphanum_fraction": 0.5945165477, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.28457601028405616, "lm_q1q2_score": 0.16434132284346545}}
{"text": "\"\"\"This module contains classes for handling dust opacities\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nimport traceback\nimport subprocess as sp\nimport os\n\ntry:\n    import numpy as np\nexcept ImportError:\n    np = None\n    print(' Numpy cannot be imported ')\n    print(' To use the python module of RADMC-3D you need to install Numpy')\n    print(traceback.format_exc())\n\n\nfrom . import natconst as nc\nfrom . import miescat\nfrom . reggrid import *\nimport warnings\nfrom scipy.interpolate import interp1d\n\nclass radmc3dDustOpac(object):\n    \"\"\"\n    Class to handle dust opacities.\n\n\n    Attributes\n    ----------\n\n    wav     : list\n                Each element of the list contains an ndarray with the wavelength grid\n\n    freq    : list\n                Each element of the list contains an ndarray with the frequency grid\n\n    nwav    : list\n                Each element of the list contains an integer with the number of wavelengths\n\n    kabs    : list\n                Each element of the list contains an ndarray with the absorption coefficient per unit mass\n\n    ksca    : list\n                Each element of the list contains an ndarray with the scattering coefficient per unit mass\n\n    phase_g : list\n                Each element of the list contains an ndarray with the hase function\n\n    ext     : list\n                Each element of the list contains a string wht the file name extension of the duskappa_ext.Kappa file\n\n    therm   : list\n                Each element of the list contains a bool, if it is set to False the dust grains are quantum-heated\n                (default: True)\n\n    idust   : lisintt\n                Each element of the list contains an integer with the index of the dust species in the dust density\n                distribution array\n\n    scatmat : list\n                Each element is a boolean indicating whether the dust opacity table includes (True) the full scattering\n                matrix or not (False)\n\n    nang    : list\n                Each element is a string, containing the number of scattering angles in the scattering matrix if its\n                given\n\n    scatang : list\n                Each element is a numpy ndarray containing the scattering angles in the scattering matrix if its given\n\n    z11     : list\n                Each element is a numpy ndarray containing the (1,1) element of the scattering angles in the scattering\n                matrix if its given\n\n    z12     : list\n                Each element is a numpy ndarray containing the (1,2) element of the scattering angles in the scattering\n                matrix if its given\n\n    z22     : list\n                Each element is a numpy ndarray containing the (2,2) element of the scattering angles in the scattering\n                matrix if its given\n\n    z33     : list\n                Each element is a numpy ndarray containing the (3,3) element of the scattering angles in the scattering\n                matrix if its given\n\n    z34     : list\n                Each element is a numpy ndarray containing the (3,4) element of the scattering angles in the scattering\n                matrix if its given\n\n    z44     : list\n                Each element is a numpy ndarray containing the (4,4) element of the scattering angles in the scattering\n                matrix if its given\n\n    \"\"\"\n\n    # --------------------------------------------------------------------------------------------------\n    def __init__(self):\n\n        self.wav = []\n        self.freq = []\n        self.nwav = []\n        self.nfreq = []\n        self.kabs = []\n        self.ksca = []\n        self.phase_g = []\n        self.ext = []\n        self.idust = []\n        self.therm = []\n        self.scatmat = []\n        self.z11 = []\n        self.z12 = []\n        self.z22 = []\n        self.z33 = []\n        self.z34 = []\n        self.z44 = []\n        self.scatang = []\n        self.nang = []\n\n    def writeOpac(self, fname=None, ext=None, idust=None, scatmat=False):\n        \"\"\"\n        Writes dust opacities to file\n\n        Parameters\n        ----------\n        fname       : str\n                      Name of the file to write the dust opacties into\n\n        ext         : str\n                      If fname is not specified, the output file name will be generated as dustkappa_EXT.inp or\n                      dustkapscatmat_EXT.inp depending on the file format\n\n        idust       : int\n                      Dust species index whose opacities should be written to file\n\n        scatmat     : bool\n                      If True the full scattering matrix will be written to file on top of the opacities (i.e.\n                      the file name should be dustkapscatmat_EXT.inp). If False only the dust opacities and the\n                      asymmetry parameter (if present) will be written to file (dustkappa_EXT.inp type files)\n\n        \"\"\"\n\n        if fname is None:\n            if ext is None:\n                msg = 'Neither fname nor ext is specified. Filename cannot be generated '\n                raise ValueError(msg)\n            else:\n                if idust is None:\n                    msg = 'idust is not specified. If output file name should be generated both ext and idust should ' \\\n                          'be set'\n                    raise ValueError(msg)\n                else:\n                    if scatmat == True:\n                        fname = 'dustkapscatmat_' + ext + '.inp'\n                    else:\n                        fname = 'dustkappa_' + ext + '.inp'\n\n        with open(fname, 'w') as wfile:\n            if scatmat == True:\n                wfile.write('1\\n')  # Format number\n                wfile.write('%d\\n' % self.nwav[idust])\n                wfile.write('%d\\n' % self.nang[idust])\n                wfile.write('\\n')\n                for i in range(self.nwav[idust]):\n                    wfile.write('%16.9e %16.9e %16.9e %16.9e\\n' % (self.wav[idust][i],\n                                                                   self.kabs[idust][i],\n                                                                   self.ksca[idust][i],\n                                                                   self.phase_g[idust][i]))\n                wfile.write('\\n')\n                for j in range(self.nang[idust]):\n                    wfile.write('%16.9e\\n' % (self.scatang[idust][j]))\n                wfile.write('\\n')\n                for i in range(self.nwav[idust]):\n                    for j in range(self.nang[idust]):\n                        wfile.write('%16.9e %16.9e %16.9e %16.9e %16.9e %16.9e\\n' % (self.z11[idust][i, j],\n                                                                                     self.z12[idust][i, j],\n                                                                                     self.z22[idust][i, j],\n                                                                                     self.z33[idust][i, j],\n                                                                                     self.z34[idust][i, j],\n                                                                                     self.z44[idust][i, j]))\n                wfile.write('\\n')\n            else:\n                if self.ksca[idust].mean() != -999.:\n                    if self.phase_g[idust].mean() != -999.:\n                        wfile.write('3\\n')  # Format number\n                    else:\n                        wfile.write('2\\n')  # Format number\n                else:\n                    wfile.write('1\\n')  # Format number\n\n                wfile.write('%d\\n' % self.nwav[idust]) # Nr of wavelengths\n\n                if self.ksca[idust].mean() != -999.:\n                    if self.phase_g[idust].mean() != -999.:\n                        for i in range(self.nwav[idust]):\n                            wfile.write('%16.9e %16.9e %16.9e %16.9e\\n' % (self.wav[idust][i],\n                                                                           self.kabs[idust][i],\n                                                                           self.ksca[idust][i],\n                                                                           self.phase_g[idust][i]))\n                    else:\n                        for i in range(self.nwav[idust]):\n                            wfile.write('%16.9e %16.9e %16.9e\\n' % (self.wav[idust][i], self.kabs[idust][i],\n                                                                           self.ksca[idust][i]))\n                else:\n                    for i in range(self.nwav[idust]):\n                        wfile.write('%16.9e %16.9e \\n' % (self.wav[idust][i], self.kabs[idust][i]))\n\n                wfile.write('\\n')\n\n\n    def readOpac(self, ext=None, idust=None, scatmat=None, old=False):\n        \"\"\"Reads the dust opacity files.\n\n        Parameters\n        ----------\n\n        ext  : list\n                File name extension (file names should look like 'dustkappa_ext.inp')\n\n        idust: list\n                Indices of the dust species in the master opacity file (dustopac.inp') - starts at 0\n\n        scatmat: list\n                If specified, its elements should be booleans indicating whether the opacity file\n                contains also the full scattering matrix (True) or only dust opacities (False)\n\n        old   : bool, optional\n                If set to True the file format of the previous, 2D version of radmc will be used\n        \"\"\"\n\n        # Check the input keywords and if single strings are given convert them to lists\n        # This assumes, though, that there is a single dust opacity file or dust species, though!!\n        if ext is None:\n            if idust is None:\n                msg = 'Unknown ext and idust. File name extension must be given to be able to read the opacity ' \\\n                      'from file.'\n                raise ValueError(msg)\n            else:\n                if isinstance(idust, int):\n                    idust = [idust]\n        else:\n            if isinstance(ext, str):\n                ext = [ext]\n\n            if (len(ext) == 1) & (ext[0] != ''):\n                if idust is not None:\n                    msg = 'Either idust or ext should be specified, but not both'\n                    raise ValueError(msg)\n\n        if scatmat is None:\n            # If the scatmat keyword is not given (i.e. if it is None) then assume that\n            # it is False for all dust species\n            scatmat = []\n            if idust is None:\n                for i in range(len(ext)):\n                    scatmat.append(False)\n\n            else:\n                for i in range(len(idust)):\n                    scatmat.append(False)\n        else:\n            if isinstance(scatmat, bool):\n                scatmat = [scatmat]\n\n        for i in range(len(scatmat)):\n            self.scatmat.append(scatmat[i])\n\n        # Find the file name extensions in the master opacity file if idust is specified instead of ext\n        if idust:\n            # Read the master dust opacity file to get the dust indices and dustkappa file name extensions\n            mopac = self.readMasterOpac()\n\n            ext = []\n            for ispec in idust:\n                if (ispec + 1) > len(mopac['ext']):\n                    msg = 'No dust species found at index ' + (\"%d\" % ispec)\n                    raise ValueError(msg)\n                else:\n                    ext.append(mopac['ext'][ispec])\n\n        # If only the extension is specified look for the master opacity file and find the index of this dust species\n        #  or set the index to -1 if no such dust species is present in the master opacity file\n        else:\n            # # Read the master dust opacity file to get the dust indices and dustkappa file name extensions\n            idust = [i for i in range(len(ext))]\n\n        # Now read all dust opacities\n        for i in range(len(ext)):\n            if scatmat[i]:\n                fname = 'dustkapscatmat_' + ext[i] + '.inp'\n                print('Reading ' + fname)\n\n                # Check the file format\n                iformat = np.fromfile(fname, count=1, sep=\" \", dtype=np.int)\n                iformat = iformat[0]\n                if iformat != 1:\n                    msg = 'Format number of the file dustkapscatmat_' + ext[i] + '.inp (iformat=' + (\"%d\" % iformat) + \\\n                          ') is unkown'\n                    raise ValueError(msg)\n\n                data = np.fromfile(fname, count=-1, sep=\" \", dtype=np.float64)\n                hdr = np.array(data[:3], dtype=np.int)\n                data = data[3:]\n\n                self.nwav.append(hdr[1])\n                self.nfreq.append(hdr[1])\n                self.nang.append(hdr[2])\n                self.ext.append(ext[i])\n                self.idust.append(idust[i])\n\n                # Get the opacities\n                data_opac = np.reshape(data[:hdr[1]*4], [hdr[1], 4])\n                data = data[hdr[1]*4:]\n                self.wav.append(data_opac[:, 0])\n                self.freq.append(nc.cc / data_opac[:, 0] * 1e4)\n                self.kabs.append(data_opac[:, 1])\n                self.ksca.append(data_opac[:, 2])\n                self.phase_g.append(data_opac[:, 3])\n\n                # Get the angular grid\n                self.scatang.append(data[:hdr[2]])\n                data = data[hdr[2]:]\n\n                # Now get the scattering matrix\n                data = np.reshape(data, [hdr[1], hdr[2], 6])\n                self.z11.append(data[:, :, 0])\n                self.z12.append(data[:, :, 1])\n                self.z22.append(data[:, :, 2])\n                self.z33.append(data[:, :, 3])\n                self.z34.append(data[:, :, 4])\n                self.z44.append(data[:, :, 5])\n\n            else:\n                if not old:\n                    fname = 'dustkappa_' + ext[i] + '.inp'\n\n                    print('Reading '+fname)\n\n                    # Check the file format\n                    iformat = np.fromfile(fname, count=1, sep=\" \", dtype=np.int)\n                    iformat = iformat[0]\n                    if (iformat < 1) | (iformat > 3):\n                        msg = 'Unknown file format in the dust opacity file ' + fname\n                        raise ValueError(msg)\n\n                    data = np.fromfile(fname, count=-1, sep=\" \", dtype=np.float64)\n                    hdr = np.array(data[:2], dtype=np.int)\n                    data = data[2:]\n\n                    self.ext.append(ext[i])\n                    self.idust.append(idust[i])\n                    self.nwav.append(hdr[1])\n                    self.nfreq.append(hdr[1])\n\n                    # If only the absorption coefficients are specified\n                    if hdr[0] == 1:\n                        data = np.reshape(data, [hdr[1], 2])\n                        self.wav.append(data[:, 0])\n                        self.freq.append(nc.cc / data[:, 0] * 1e4)\n                        self.kabs.append(data[:, 1])\n                        self.ksca.append([-999.])\n                        self.phase_g.append([-999.])\n\n                    # If the absorption and scattering coefficients are specified\n                    elif hdr[0] == 2:\n                        data = np.reshape(data, [hdr[1], 3])\n                        self.wav.append(data[:, 0])\n                        self.freq.append(nc.cc / data[:, 0] * 1e4)\n                        self.kabs.append(data[:, 1])\n                        self.ksca.append(data[:, 2])\n                        self.phase_g.append([-999.])\n\n                    # If the absorption and scattering coefficients and also the scattering phase\n                    # function are specified\n                    elif hdr[0] == 3:\n                        data = np.reshape(data, [hdr[1], 4])\n                        self.wav.append(data[:, 0])\n                        self.freq.append(nc.cc / data[:, 0] * 1e4)\n                        self.kabs.append(data[:, 1])\n                        self.ksca.append(data[:, 2])\n                        self.phase_g.append(data[:, 3])\n\n                else:\n                    fname = 'dustopac_' + ext[i] + '.inp'\n                    print('Reading '+fname)\n                    freq = np.fromfile('frequency.inp', count=-1, sep=\" \", dtype=np.float64)\n                    nfreq = int(freq[0])\n                    freq = freq[1:]\n                    self.ext.append(ext[i])\n                    self.idust.append(idust[i])\n\n                    data = np.fromfile(fname, count=-1, sep=\" \", dtype=np.float64)\n                    hdr = np.array(data[:2], dtype=np.int)\n                    data = data[2:]\n                    if hdr[0] != nfreq:\n                        msg = fname + ' contains a different number of frequencies than frequency.inp'\n                        raise ValueError(msg)\n\n                    wav = nc.cc / freq * 1e4\n                    kabs = data[:nfreq]\n                    ksca = data[nfreq:]\n\n                    self.wav.append(wav[::-1])\n                    self.freq.append(freq[::-1])\n                    self.kabs.append(kabs[::-1])\n                    self.ksca.append(ksca[::-1])\n                    self.phase_g.append([-1])\n\n        return 0\n\n    def makeOpac(self, ppar=None, wav=None, old=False, code='python',\n                 theta=None, logawidth=None, wfact=3.0, na=20, chopforward=0., errtol=0.01,\n                 verbose=False, extrapolate=False):\n        \"\"\"Createst the dust opacities using a Mie code distributed with RADMC-3D.\n\n        Parameters\n        ----------\n\n        ppar        : dictionary\n                      Parameters of the simulations\n\n        wav         : ndarray, optional\n                      Wavelength grid on which the mass absorption coefficients should be calculated\n\n        code        : {'python', 'fortran'}\n                      Version of the mie scattering code BHMIE to be used. 'fortran' - use the original fortran77\n                      code of Bruce Drain (should be downloaded separately, compiled and its path added to the PATH\n                      environment variable), 'python' a python version of BHMIE by Kees Dullemond (radmc3dPy.miescat).\n\n        theta       : ndarray, optional\n                      Angular grid (a numpy array) between 0 and 180\n                      which are the scattering angle sampling points at\n                      which the scattering phase function is computed.\n\n        logawidth   : float, optional\n                     If set, the size agrain will instead be a\n                     sample of sizes around agrain. This helps to smooth out\n                     the strong wiggles in the phase function and opacity\n                     of spheres at an exact size. Since in Nature it rarely\n                     happens that grains all have exactly the same size, this\n                     is quite natural. The value of logawidth sets the width\n                     of the Gauss in ln(agrain), so for logawidth<<1 this\n                     give a real width of logawidth*agraincm.\n\n        wfact       : float\n                      Grid width of na sampling points in units\n                      of logawidth. The Gauss distribution of grain sizes is\n                      cut off at agrain * exp(wfact*logawidth) and\n                      agrain * exp(-wfact*logawidth). Default = 3\n\n\n        na          : int\n                      Number of size sampling points (if logawidth set, default=20)\n\n        chopforward : float\n                      If >0 this gives the angle (in degrees from forward)\n                      within which the scattering phase function should be\n                      kept constant, essentially removing the strongly peaked\n                      forward scattering. This is useful for large grains\n                      (large ratio 2*pi*agraincm/lamcm) where the forward\n                      scattering peak is extremely strong, yet extremely\n                      narrow. If we are not interested in very forward-peaked\n                      scattering (e.g. only relevant when modeling e.g. the\n                      halo around the moon on a cold winter night), this will\n                      remove this component and allow a lower angular grid\n                      resolution for the theta grid.\n\n\n        errtol      : float\n                      Tolerance of the relative difference between kscat\n                      and the integral over the zscat Z11 element over angle.\n                      If this tolerance is exceeded, a warning is given.\n\n        verbose     : bool\n                      If set to True, the code will give some feedback so\n                      that one knows what it is doing if it becomes slow.\n\n        extrapolate : bool\n                      If set to True, then if the wavelength grid lamcm goes\n                      out of the range of the wavelength grid of the\n                      optical constants file, then it will make a suitable\n                      extrapolation: keeping the optical constants constant\n                      for lamcm < minimum, and extrapolating log-log for\n                      lamcm > maximum.\n\n\n        old         : bool, optional\n                      If set to True the file format of the previous, 2D version of radmc will be used\n        \"\"\"\n        #\n        # Create the wavelength grid if it is not specified\n        #\n        if wav is None:\n            grid = radmc3dGrid()\n            grid.makeWavelengthGrid(ppar=ppar)\n            wav = grid.wav\n\n            #\n            # Do we need to mix the opacities?\n            #\n        if ppar is None:\n            msg = 'Unknown ppar. The parameter dictionary is required to get the lnk file names.'\n            raise ValueError(msg)\n\n        if isinstance(ppar['lnk_fname'], str):\n            ppar['lnk_fname'] = [ppar['lnk_fname']]\n\n        if len(ppar['lnk_fname']) > 1:\n            ext = []\n            for idust in range(len(ppar['lnk_fname'])):\n\n                # makedust needs the lnk file to be sorted in wavelength so create a dummy file\n                # which contains the sorted optical constants\n                with open(ppar['lnk_fname'][idust], 'r') as rfile:\n                    w = []\n                    n = []\n                    k = []\n                    dum = rfile.readline()\n                    while len(dum) > 0:\n                        dum = dum.split()\n                        w.append(dum[0])\n                        n.append(dum[1])\n                        k.append(dum[2])\n                        dum = rfile.readline()\n\n                w = np.array(w, dtype=float)\n                n = np.array(n, dtype=float)\n                k = np.array(k, dtype=float)\n\n                if float(w[0]) > float(w[w.shape[0] - 1]):\n                    w = w[::-1]\n                    n = n[::-1]\n                    k = k[::-1]\n\n                # Write out the dummy file containing the sorted optical constants\n                with open('opt_const.dat', 'w') as wfile:\n                    for iwav in range(w.shape[0]):\n                        wfile.write(\"%s %s %s \\n\" % (w[iwav], n[iwav], k[iwav]))\n\n                if code.lower().strip() == 'fortran':\n                    # Run makedust\n                    self.runMakedust(freq=nc.cc / wav * 1e4, gmin=ppar['gsmin'], gmax=ppar['gsmax'], ngs=ppar['ngs'],\n                                     lnk_fname='opt_const.dat', gdens=ppar['gdens'][idust])\n\n                    # Change the name of makedust's output\n                    for igs in range(ppar['ngs']):\n                        dum = sp.Popen('mv dustkappa_' + str(igs + 1) + '.inp dustkappa_idust_' + str(idust + 1)\n                                       + '_igsize_' + str(igs + 1) + '.inp', shell=True).wait()\n                        ext.append('idust_' + str(idust + 1) + '_igsize_' + str(igs + 1))\n\n                elif code.lower().strip() == 'python':\n\n                    if 'nscatang' in ppar:\n                        nang = ppar['nscatang']\n                    else:\n                        nang = 180\n                    theta = 180. * np.arange(nang, dtype=np.float) / np.float(nang - 1)\n\n                    if 'logawidth' in ppar:\n                        logawidth = ppar['logawidth']\n                    else:\n                        logawidth = None\n\n                    if 'wfact' in ppar:\n                        wfact = ppar['wfact']\n                    else:\n                        wfact = 3.0\n\n                    if 'chopforward' in ppar:\n                        if ppar['chopforward'] > 0.:\n                            chopforward = ppar['chopforward']\n                        else:\n                            chopforward = None\n                    else:\n                        chopforward = 0.0\n\n                    if 'errtol' in ppar:\n                        errtol = ppar['errtol']\n                    else:\n                        errtol = 0.01\n\n                    if 'miescat_verbose' in ppar:\n                        verbose = ppar['miescat_verbose']\n                    else:\n                        verbose = False\n\n                    if 'extrapolate' in ppar:\n                        extrapolate = ppar['extrapolate']\n                    else:\n                        extrapolate = False\n\n                    # Get the grain sizes in micrometer\n                    gsize = ppar['gsmin'] * (ppar['gsmax'] / ppar['gsmin'])**(\n                        np.arange(ppar['ngs'], dtype=np.float64) / (float(ppar['ngs']) - 1.))\n\n\n                    for igs in range(ppar['ngs']):\n                        o = computeDustOpacMie(fname=ppar['lnk_fname'][idust], matdens=ppar['gdens'][idust],\n                                                 agraincm=gsize[igs] * 1e-4, lamcm=wav * 1e-4, theta=theta,\n                                                 logawidth=logawidth, wfact=wfact, na=na, chopforward=chopforward,\n                                                 errtol=errtol, verbose=verbose, extrapolate=extrapolate, return_type=1)\n\n                        o.writeOpac(ext='idust_' + (str(idust + 1)) + '_igsize_' + str(igs + 1), idust=0, scatmat=True)\n                        if ppar['scattering_mode_max'] <= 2:\n                            o.writeOpac(ext='idust_' + (str(idust + 1)) + '_igsize_' + str(igs + 1), idust=0,\n                                        scatmat=False)\n\n\n                        # if ppar['scattering_mode_max'] <= 2:\n                        #     miescat.write_radmc3d_kappa_file(package=o, name='idust_1_igsize_' + str(igs + 1))\n                        # else:\n                        #     miescat.write_radmc3d_scatmat_file(package=o, name='idust_1_igsize_' + str(igs + 1))\n\n                os.remove('opt_const.dat')\n\n            # Mix the opacity of different dust species for a given grain size if mixing is requested\n            if 'mixabun' in ppar:\n                if len(ppar['mixabun']) == len(ppar['lnk_fname']):\n                    ext = []\n                    for igs in range(ppar['ngs']):\n                        mixnames = ['dustkappa_igsize_' + str(igs + 1) + '.inp']\n                        mixspecs = [['dustkappa_idust_' + str(idust + 1) + '_igsize_' + str(igs + 1) + '.inp'\n                                     for idust in range(len(ppar['lnk_fname']))]]\n                        self.mixOpac(mixnames=mixnames, mixspecs=mixspecs, mixabun=[ppar['mixabun']])\n                        ext.append('igsize_' + str(igs + 1))\n                else:\n                    msg = 'ppar[\"mixabun\"] or ppar[\"lnk_fname\"] has the wrong shape. They both should have '\\\n                          + 'the same number of elements, but the number of elements are different.'\n                    raise ValueError(msg)\n\n            therm = [True for i in range(len(ext))]\n            self.writeMasterOpac(ext=ext, therm=therm, scattering_mode_max=ppar['scattering_mode_max'], old=old)\n\n            if old:\n                self.makeopacRadmc2D(ext=ext)\n\n        else:\n            # makedust needs the lnk file to be sorted in wavelength so create a dummy file\n            # which contains the sorted optical constants\n            with open(ppar['lnk_fname'][0], 'r') as rfile:\n                w = []\n                n = []\n                k = []\n                dum = rfile.readline()\n                while len(dum) > 0:\n                    dum = dum.split()\n                    w.append(dum[0])\n                    n.append(dum[1])\n                    k.append(dum[2])\n                    dum = rfile.readline()\n\n            w = np.array(w, dtype=float)\n            n = np.array(n, dtype=float)\n            k = np.array(k, dtype=float)\n\n            if float(w[0]) > float(w[w.shape[0] - 1]):\n                w = w[::-1]\n                n = n[::-1]\n                k = k[::-1]\n\n            # Write out the dummy file containing the sorted optical constants\n            with open('opt_const.dat', 'w') as wfile:\n                for iwav in range(w.shape[0]):\n                    wfile.write(\"%s %s %s \\n\" % (w[iwav], n[iwav], k[iwav]))\n\n            if code.lower().strip() == 'fortran':\n                # Run makedust\n                self.runMakedust(freq=nc.cc / wav * 1e4, gmin=ppar['gsmin'], gmax=ppar['gsmax'], ngs=ppar['ngs'],\n                                 lnk_fname='opt_const.dat', gdens=ppar['gdens'][0])\n\n                # Change the name of makedust's output\n                ext = []\n                therm = []\n                for igs in range(ppar['ngs']):\n                    dum = sp.Popen('mv dustkappa_' + str(igs + 1) + '.inp dustkappa_idust_1_igsize_' + str(igs + 1)\n                                   + '.inp', shell=True).wait()\n                    ext.append('idust_1_igsize_' + str(igs + 1))\n                    therm.append(True)\n\n            elif code.lower().strip() == 'python':\n\n                if 'nscatang' in ppar:\n                    nang = ppar['nscatang']\n                else:\n                    nang = 180\n                theta = 180. * np.arange(nang, dtype=np.float) / np.float(nang - 1)\n\n                if 'logawidth' in ppar:\n                    logawidth = ppar['logawidth']\n                else:\n                    logawidth = None\n\n                if 'wfact' in ppar:\n                    wfact = ppar['wfact']\n                else:\n                    wfact = 3.0\n\n                if 'chopforward' in ppar:\n                    if ppar['chopforward'] > 0.:\n                        chopforward = ppar['chopforward']\n                    else:\n                        chopforward = None\n                else:\n                    chopforward = 0.0\n\n                if 'errtol' in ppar:\n                    errtol = ppar['errtol']\n                else:\n                    errtol = 0.01\n\n                if 'miescat_verbose' in ppar:\n                    verbose = ppar['miescat_verbose']\n                else:\n                    verbose = False\n\n                if 'extrapolate' in ppar:\n                    extrapolate = ppar['extrapolate']\n                else:\n                    extrapolate = False\n\n                # Get the grain sizes in micrometer\n                gsize = ppar['gsmin'] * (ppar['gsmax'] / ppar['gsmin'])**(\n                        np.arange(ppar['ngs'], dtype=np.float64) / (float(ppar['ngs']) - 1.))\n\n                ext = []\n                therm = []\n                for igs in range(ppar['ngs']):\n                    print('Computing dust opacities for grain size : ', gsize[igs])\n                    o = computeDustOpacMie(fname='opt_const.dat', matdens=ppar['gdens'][0],\n                                             agraincm=gsize[igs] * 1e-4, lamcm=wav * 1e-4, theta=theta,\n                                             logawidth=logawidth, wfact=wfact, na=na, chopforward=chopforward,\n                                             errtol=errtol, verbose=verbose, extrapolate=extrapolate, return_type=1)\n\n                    o.writeOpac(ext='idust_1_igsize_' + str(igs + 1), idust=0, scatmat=True)\n                    if ppar['scattering_mode_max'] <= 2:\n                        o.writeOpac(ext='idust_1_igsize_' + str(igs + 1), idust=0, scatmat=False)\n                    ext.append('idust_1_igsize_' + str(igs + 1))\n                    therm.append(True)\n                # if ppar['scattering_mode_max'] <= 2:\n                #     miescat.write_radmc3d_kappa_file(package=o, name='idust_1_igsize_1')\n                # else:\n                #     miescat.write_radmc3d_scatmat_file(package=o, name='idust_1_igsize_1')\n\n            else:\n                msg = 'Unknown mie scattering code version ' + code\n                raise ValueError(msg)\n\n            self.writeMasterOpac(ext=ext, therm=therm, scattering_mode_max=ppar['scattering_mode_max'], old=old)\n            if old:\n                self.makeopacRadmc2D(ext=ext)\n\n        # Clean up and remove dust.inp and frequency.inp\n        if code.lower().strip() == 'fortran':\n            os.remove('dust.inp')\n            if not old:\n                os.remove('frequency.inp')\n\n    @staticmethod\n    def mixOpac(ppar=None, mixnames=None, mixspecs=None, mixabun=None, writefile=True):\n        \"\"\"Mixes dust opacities.\n\n\n        Parameters\n        -----------\n        ppar      : dictionary, optional\n                    All parameters of the actual model setup.\n\n        mixnames  : list, optional\n                    Names of the files into which the mixed dust opacities will be written\n                    (not needed if writefile=False)\n\n        mixspecs  : list, optional\n                    Names of the files from which the dust opacities are read (not needed if readfile=False)\n\n        mixabun   : list, optional\n                    Abundances of different dust species\n\n        writefile : bool\n                    If False the mixed opacities will not be written out to files given in mixnames.\n\n        NOTE, either ppar or  mixname, mixspecs, and mixabun should be set.\n\n        \"\"\"\n\n        if writefile:\n            if mixnames is None:\n                if ppar is None:\n                    msg = 'Neither ppar nor mixnames are set in mixOpac'\n                    raise ValueError(msg)\n                else:\n                    mixnames = ppar['mixnames']\n\n        if mixspecs is None:\n            if ppar is None:\n                msg = ' Neither ppar nor mixspecs are set in mixOpac '\n                raise ValueError(msg)\n            else:\n                mixspecs = ppar['mixspecs']\n\n        if mixabun is None:\n            if ppar is None:\n                msg = ' Neither ppar nor mixabun are set in mixOpac '\n                raise ValueError(msg)\n            else:\n                mixabun = ppar['mixabun']\n\n        for i in range(len(mixnames)):\n            #\n            # Read the dust opacities to be mixed for composite dust species #1\n            #\n            ocabs = []\n            ocsca = []\n            ogsym = []\n            oform = 0\n            for j in range(len(mixspecs[i])):\n                with open(mixspecs[i][j], 'r') as rfile:\n                    form = int(rfile.readline())\n                    nwav = int(rfile.readline())\n                    dw = np.zeros(nwav, dtype=float)\n                    dcabs = np.zeros(nwav, dtype=float)\n                    dcsca = np.zeros(nwav, dtype=float)\n                    gsym = np.zeros(nwav, dtype=float)\n                    if form == 1:\n                        if (oform == 0) | (oform == 1):\n                            oform = 1\n                        else:\n                            print(' ')\n                            print('WARNING')\n                            print(' You are trying to mix opacity tables with different formats. Some of the tables \\n'\n                                  + ' contain scattering coefficients while (format>=2) while others do not '\n                                  + ' (format=1).\\n'\n                                  + ' If you wish to continue mixing will only be done for the absorption and the \\n'\n                                  + 'output opacity table will have a format number of 1.')\n                            dum = input('Do you wish to continue (1-yes, 0-no) ?')\n                            if dum.strip() != '1':\n                                return\n\n                        for iwav in range(nwav):\n                            dum = rfile.readline().split()\n                            dw[iwav], dcabs[iwav] = float(dum[0]), float(dum[1])\n                    if form == 2:\n                        if (oform == 0) | (oform == 2):\n                            oform = 2\n                        else:\n                            print(' ')\n                            print('WARNING')\n                            print(' You are trying to mix opacity tables with different formats. Some of the tables \\n'\n                                  + ' contain scattering coefficients while (format>=2) while other do not '\n                                  + '(format=1). \\n'\n                                  + ' If you wish to continue mixing will only be done for the absorption and the \\n'\n                                  + 'output opacity table will have a format number of 1.')\n\n                            dum = input('Do you wish to continue (1-yes, 0-no) ?')\n                            if dum.strip() != '1':\n                                return\n                        for iwav in range(nwav):\n                            dum = rfile.readline().split()\n                            dw[iwav], dcabs[iwav], dcsca[iwav] = float(dum[0]), float(dum[1]), float(dum[2])\n                    if form == 3:\n                        if (oform == 0) | (oform == 3):\n                            oform = 3\n                        else:\n                            print(' ')\n                            print('WARNING')\n                            print(' You are trying to mix opacity tables with different formats. Some of the tables \\n'\n                                  + ' contain scattering coefficients while (format>=2) while other do not '\n                                  + '(format=1) \\n'\n                                  + ' If you wish to continue mixing will only be done for the absorption and the '\n                                  + 'output opacity table will have a format number of 1.')\n                            dum = input('Do you wish to continue (1-yes, 0-no) ?')\n                            if dum.strip() != '1':\n                                return\n                        for iwav in range(nwav):\n                            dum = rfile.readline().split()\n                            dw[iwav], dcabs[iwav], dcsca[iwav], gsym[iwav] = float(dum[0]), float(dum[1]), float(\n                                dum[2]), float(dum[3])\n                    if form > 3:\n                        msg = ' Unsupported dust opacity table format (format number: ' + (\"%d\" % form) + ')' \\\n                              + ' Currently only format number 1 and 2 are supported'\n                        raise ValueError(msg)\n\n                    if dw[1] < dw[0]:\n                        print(' Dust opacity table seems to be sorted in frequency instead of wavelength')\n                        print(' Reversing the arrays')\n                        dw = dw[::-1]\n                        dcabs = dcabs[::-1]\n                        dcsca = dcsca[::-1]\n\n                if j == 0:\n                    ocabs = np.array(dcabs) * mixabun[i][j]\n                    ocsca = np.array(dcsca) * mixabun[i][j]\n                    ogsym = np.array(gsym) * mixabun[i][j]\n                    nwav0 = dw.shape[0]\n                    owav = np.array(dw)\n                else:\n                    #\n                    # Interpolate dust opacities to the wavelength grid of the first dust species\n                    #\n                    ii = ((owav >= dw[0]) & (owav <= dw[nwav - 1]))\n                    il = (owav < dw[0])\n                    ih = (owav > dw[nwav - 1])\n                    dum = np.zeros(nwav0, dtype=float)\n                    dum[ii] = 10. ** np.interp(np.log10(owav[ii]), np.log10(dw), np.log10(dcabs))\n\n                    # Edwtrapolate the absorption coefficients using linear fit in log-log space\n                    # (i.e. fitting a polinomial) for short wavelengths\n                    # der = np.log10(dcabs[1] / dcabs[0]) / np.log10(dw[1] / dw[0])\n                    dum[il] = 10. ** (np.log10(dcabs[0]) + np.log10(dw[0] / owav[il]))\n\n                    # Edwtrapolate the absorption coefficients using linear fit in log-log space\n                    # (i.e. fitting a polinomial) for long wavelengths\n                    # der = np.log10(dcabs[nwav - 1] / dcabs[nwav - 2]) / np.log10(dw[nwav - 1] / dw[nwav - 2])\n                    dum[ih] = 10. ** (np.log10(dcabs[nwav - 1]) + np.log10(owav[il] / dw[nwav - 1]))\n\n                    ocabs = ocabs + np.array(dum) * mixabun[i][j]\n\n                    if oform == 2:\n                        # Do the inter-/extrapolation of for the scattering coefficients\n                        dum = np.zeros(nwav0, dtype=float)\n                        dum[ii] = 10. ** np.interp(np.log10(owav[ii]), np.log10(dw), np.log10(dcsca))\n\n                        # der = np.log10(dcsca[1] / dcsca[0]) / np.log10(dw[1] / dw[0])\n                        dum[il] = 10. ** (np.log10(dcsca[0]) + np.log10(dw[0] / owav[il]))\n\n                        # der = np.log10(dcsca[nwav - 1] / dcsca[nwav - 2]) / np.log10(dw[nwav - 1] / dw[nwav - 2])\n                        dum[ih] = 10. ** (np.log10(dcsca[nwav - 1]) + np.log10(owav[il] / dw[nwav - 1]))\n\n                        ocsca = ocsca + np.array(dum) * mixabun[i][j]\n\n                    if oform == 3:\n                        # Do the inter-/extrapolation of for the scattering phase function\n                        dum = np.zeros(nwav0, dtype=float)\n                        dum[ii] = 10. ** np.interp(np.log10(owav[ii]), np.log10(dw), np.log10(gsym))\n\n                        # der = np.log10(gsym[1] / gsym[0]) / np.log10(dw[1] / dw[0])\n                        dum[il] = 10. ** (np.log10(gsym[0]) + np.log10(dw[0] / owav[il]))\n\n                        # der = np.log10(gsym[nwav - 1] / gsym[nwav - 2]) / np.log10(dw[nwav - 1] / dw[nwav - 2])\n                        dum[ih] = 10. ** (np.log10(gsym[nwav - 1]) + np.log10(owav[il] / dw[nwav - 1]))\n\n                        ogsym = ogsym + np.array(dum) * mixabun[i][j]\n\n            #\n            # Write out the mixed dust opacities\n            #\n            with open(mixnames[i], 'w') as wfile:\n                wfile.write(\"%d\\n\" % oform)\n                wfile.write(\"%d\\n\" % owav.shape[0])\n                if oform == 1:\n                    for iwav in range(owav.shape[0]):\n                        wfile.write(\"%.9e %.9e\\n\" % (owav[iwav], ocabs[iwav]))\n                if oform == 2:\n                    for iwav in range(owav.shape[0]):\n                        wfile.write(\"%.9e %.9e %.9e\\n\" % (owav[iwav], ocabs[iwav], ocsca[iwav]))\n                if oform == 3:\n                    for iwav in range(owav.shape[0]):\n                        wfile.write(\"%.9e %.9e %.9e %.9e\\n\" % (owav[iwav], ocabs[iwav], ocsca[iwav], ogsym[iwav]))\n\n        return\n\n    @staticmethod\n    def readMasterOpac():\n        \"\"\"Reads the master opacity file 'dustopac.inp'.\n        It reads the dustkappa filename extensions (dustkappa_ext.inp) corresponding to dust species indices\n\n        Returns\n        -------\n\n        Returns a dictionary with the following keys:\n\n            *ext   : list of dustkappa file name extensions\n\n            *therm : a list of integers specifying whether the dust grain is thermal or quantum heated\n            (0 - thermal, 1 - quantum heated)\n        \"\"\"\n\n        with open('dustopac.inp', 'r') as rfile:\n\n            # file format\n            dum = rfile.readline()\n            # nr of dust species\n            ndust = int(rfile.readline().split()[0])\n            # Comment line\n            dum = rfile.readline()\n\n            ext = []\n            therm = []\n            scatmat = []\n            for idust in range(ndust):\n                # Check if we have dust opacities also for the full scattering matrix\n                dum = rfile.readline().split()\n                if int(dum[0]) == 1:\n                    scatmat.append(False)\n                elif int(dum[0]) == 10:\n                    scatmat.append(True)\n\n                # Check if the dust grain is thermal or quantum heated\n                dum = int(rfile.readline().split()[0])\n                if dum == 0:\n                    therm.append(True)\n                else:\n                    therm.append(False)\n                # Dustkappa filename extension\n                dum = rfile.readline().split()[0]\n                ext.append(dum)\n                # Comment line\n                dum = rfile.readline()\n\n        return {'ext': ext, 'therm': therm, 'scatmat': scatmat}\n\n    @staticmethod\n    def writeMasterOpac(ext=None, therm=None, scattering_mode_max=1, old=False):\n        \"\"\"Writes the master opacity file 'dustopac.inp'.\n\n        Parameters\n        ----------\n\n        ext                 : list\n                              List of dustkappa file name extensions\n\n        therm               : list\n                              List of integers specifying whether the dust grain is thermal or quantum heated\n                              (0-thermal, 1-quantum)\n\n        scattering_mode_max : int\n                              Scattering mode code in radmc3d : 0 - no scattering, 1 - isotropic scattering,\n                              2 - anisotropic scattering with Henyei-Greenstein phase function, 5 - anisotropic\n                              scattering using the full scattering matrix and stokes vectors.\n\n        old                 : bool, optional\n                              If set to True the file format of the previous, 2D version of radmc will be used\n        \"\"\"\n\n        print('Writing dustopac.inp')\n\n        if not ext:\n            msg = 'Unknown ext. No file name extension is specified. Without it dustopac.inp cannot be written'\n            raise ValueError(msg)\n        else:\n            if isinstance(ext, str):\n                ext = [ext]\n\n        if therm is None:\n            # If therm is not specified it is assumed that all grains are thermal, no quantum heating\n            therm = [True for i in range(len(ext))]\n        else:\n            if isinstance(therm, int):\n                therm = [therm]\n            if len(ext) != len(therm):\n                msg = ' The number of dust species in ext and in therm are different'\n                raise ValueError(msg)\n\n        with open('dustopac.inp', 'w') as wfile:\n\n            # File format\n            wfile.write('%-15s %s\\n' % ('2', 'Format number of this file'))\n            # Number of dust species\n            wfile.write('%-15s %s\\n' % (str(len(ext)), 'Nr of dust species'))\n            # Separator\n            wfile.write('%s\\n' % '============================================================================')\n\n            if not old:\n                for idust in range(len(ext)):\n                    # Dust opacity will be read from a file\n                    if scattering_mode_max < 5:\n                        wfile.write('%-15s %s\\n' % ('1', 'Way in which this dust species is read'))\n                    else:\n                        wfile.write('%-15s %s\\n' % ('10', 'Way in which this dust species is read'))\n\n                    # Check if the dust grain is thermal or quantum heated\n                    if therm:\n                        if therm[idust]:\n                            wfile.write('%-15s %s\\n' % ('0', '0=Thermal grain, 1=Quantum heated'))\n                    else:\n                        wfile.write('%-15s %s\\n' % ('1', '0=Thermal grain, 1=Quantum heated'))\n\n                    # Dustkappa filename extension\n                    wfile.write('%s %s %s\\n' % (ext[idust], '    ', 'Extension of name of dustkappa_***.inp file'))\n                    # Separator\n                    wfile.write('%s\\n' % '----------------------------------------------------------------------------')\n            else:\n                for idust in range(len(ext)):\n                    # Dust opacity will be read from a file\n                    wfile.write('%-15s %s\\n' % ('-1', 'Way in which this dust species is read (-1=File)'))\n\n                    # Check if the dust grain is thermal or quantum heated\n                    wfile.write('%-15s %s\\n' % ('0', '0=Thermal grain, 1=Quantum heated'))\n                    # Dustkappa filename extension\n                    wfile.write('%d %s %s\\n' % ((idust + 1), '    ', 'Extension of name of dustopac_***.inp file'))\n                    # Separator\n                    wfile.write('%s\\n' % '----------------------------------------------------------------------------')\n\n    def makeopacRadmc2D(self, ext=None):\n        \"\"\"\n        Creates dust opacities (dustopac_*.inp files) for the previous 2D version of radmc\n        It takes the input dust opacity files and interpolates them onto the used frequency grid\n\n        Parameters\n        ----------\n\n            ext : list\n                  List of dustkappa file name extensions, i.e. the input file name has to be named\n                  as dustkappa_ext[i].inp\n\n        \"\"\"\n\n        if ext is None:\n            msg = 'Unknown ext. Dust opacity file name extensions are mandatory.'\n            raise ValueError(msg)\n\n        else:\n            if isinstance(ext, str):\n                ext = [ext]\n\n        self.readOpac(ext=ext, old=False)\n        #\n        # Read the frequency.inp file\n        #\n        freq = np.fromfile('frequency.inp', count=-1, sep=\"\\n\", dtype=float)\n        nfreq = int(freq[0])\n        freq = freq[1:]\n        freq = freq[::-1]\n        wav = nc.cc / freq * 1e4\n        #\n        # Check if the frequency grid is ordered in frequency or in wavelength\n        #\n        worder = False\n        if freq[-1] < freq[0]:\n            worder = True\n\n        for i in range(len(ext)):\n            kabs = np.zeros(nfreq, dtype=float)\n            ksca = np.zeros(nfreq, dtype=float)\n            ish = (wav < self.wav[i][0])\n            ilo = (wav > self.wav[i][-1])\n            ii = ((wav >= self.wav[i][0]) & (wav <= self.wav[i][-1]))\n\n            #\n            # Do logarithmic interpolation for the overlapping wavelenght domain\n            #\n            kabs[ii] = 10. ** np.interp(np.log10(wav[ii]), np.log10(self.wav[i]), np.log10(self.kabs[i]))\n            if len(self.ksca[i]) > 1:\n                ksca[ii] = 10. ** np.interp(np.log10(wav[ii]), np.log10(self.wav[i]), np.log10(self.ksca[i]))\n\n            #\n            # Do the long wavelength part\n            #\n            if True in ilo:\n                x1 = np.log10(self.wav[i][-1])\n                x0 = np.log10(self.wav[i][-2])\n\n                y1 = np.log10(self.kabs[i][-1])\n                y0 = np.log10(self.kabs[i][-2])\n                der = (y1 - y0) / (x1 - x0)\n                kabs[ilo] = 10. ** (y1 + der * (np.log10(wav[ilo]) - x1))\n\n                y1 = np.log10(self.ksca[i][-1])\n                y0 = np.log10(self.ksca[i][-2])\n                der = (y1 - y0) / (x1 - x0)\n                ksca[ilo] = 10. ** (y1 + der * (np.log10(wav[ilo]) - x1))\n\n            #\n            # Do the shorter wavelength\n            #\n            if True in ish:\n                kabs[ish] = self.kabs[0][0]\n                ksca[ish] = self.ksca[0][0]\n\n            #\n            # Now write the results to file\n            #\n            fname = 'dustopac_' + (\"%d\" % (i + 1)) + '.inp'\n            with open(fname, 'w') as wfile:\n                print('Writing ' + fname)\n                wfile.write(\"%d 1\\n\" % nfreq)\n                wfile.write(\" \\n\")\n                #\n                # Reverse the order of kabs,ksca as they are ordered in frequency in radmc\n                #\n                if worder:\n                    x = kabs[::-1]\n                else:\n                    x = kabs\n                for ilam in range(nfreq):\n                    wfile.write(\"%.7e\\n\" % x[ilam])\n\n                wfile.write(\" \\n\")\n                if worder:\n                    x = ksca[::-1]\n                else:\n                    x = ksca\n                for ilam in range(nfreq):\n                    wfile.write(\"%.7e\\n\" % x[ilam])\n\n    @staticmethod\n    def runMakedust(freq=None, gmin=None, gmax=None, ngs=None, lnk_fname=None, gdens=None):\n        \"\"\"Interface function to the F77 code makedust to calculate mass absorption coefficients.\n\n        Parameters\n        ----------\n        freq       : ndarray\n                    Contains the frequency grid on which the opacities should be calculated\n\n        gmin       : float\n                    Minimum grain size\n\n        gmax       : float\n                    Maximum grain size\n\n        ngs        : int\n                    Number of grain sizes\n\n        gdens      : float\n                    Density of the dust grain in g/cm^3\n\n        lnk_fname  : str\n                    Name of the file in which the optical constants are stored\n\n        Returns\n        -------\n\n        Returns an ndarray with [nfreq,ngs] dimensions containing the resulting opacities\n        \"\"\"\n\n        #\n        # Calculate the grain sizes\n        #\n        if ngs > 1:\n            gsize = gmin * (gmax / gmin) ** (np.arange(ngs, dtype=np.float64) / (float(ngs) - 1.))\n        else:\n            gsize = [gmin]\n\n        #\n        # Write the frequency.inp file\n        #\n        with open('frequency.inp', 'w') as wfile:\n            wfile.write(\"%d\\n\" % freq.shape[0])\n            wfile.write(\"  \\n\")\n            for i in range(freq.shape[0]):\n                wfile.write(\"%.10e\\n\" % freq[i])\n\n        #\n        # Write the dust.inp file (makedust main control file)\n        #\n        with open('dust.inp', 'w') as wfile:\n            for igs in range(ngs):\n                wfile.write(\"%s\\n\" % lnk_fname)\n                wfile.write(\"%s\\n\" % \"MIE\")\n                wfile.write(\"%d %f %f %f %d %f %f %f\\n\" %\n                            (1, 0.0, np.log10(gsize[igs]), np.log10(gsize[igs]), 1., -3.5, gdens, -2.0))\n\n        #\n        # Run the Mie-code\n        #\n        dum = sp.Popen('makedust', shell=True).wait()\n\n\n\ndef computeDustOpacMie(fname='', matdens=None, agraincm=None, lamcm=None,\n                     theta=None, logawidth=None, wfact=3.0, na=20,\n                     chopforward=0.0, errtol=0.01, verbose=False,\n                     extrapolate=False, return_type=1):\n    \"\"\"\n    Compute dust opacity with Mie theory based on the optical constants\n    in the optconst_file. Optionally also the scattering phase function\n    in terms of the Mueller matrix elements can be computed. To smear out\n    the resonances that appear due to the perfect sphere shape, you can\n    optionally smear out the grain size distribution a bit with setting\n    the width of a Gaussian grain size distribution.\n\n    Parameters\n    ----------\n    fname       : str\n                  File name of the optical constants file. This file\n                  should contain three columns: first the wavelength\n                  in micron, then the n-coefficient and then the\n                  k-coefficient. See Jena optical constants database:\n                  http://www.astro.uni-jena.de/Laboratory/Database/databases.html\n\n    matdens     : float\n                  Material density in g/cm^3\n\n    agraincm    : float\n                  Grain radius in cm\n\n    lamcm       : ndarray\n                  Wavelength grid in cm\n\n    theta       : ndarray, optional\n                  Angular grid (a numpy array) between 0 and 180\n                  which are the scattering angle sampling points at\n                  which the scattering phase function is computed.\n\n    logawidth   : float, optional\n                 If set, the size agrain will instead be a\n                 sample of sizes around agrain. This helps to smooth out\n                 the strong wiggles in the phase function and opacity\n                 of spheres at an exact size. Since in Nature it rarely\n                 happens that grains all have exactly the same size, this\n                 is quite natural. The value of logawidth sets the width\n                 of the Gauss in ln(agrain), so for logawidth<<1 this\n                 give a real width of logawidth*agraincm.\n\n    wfact       : float\n                  Grid width of na sampling points in units\n                  of logawidth. The Gauss distribution of grain sizes is\n                  cut off at agrain * exp(wfact*logawidth) and\n                  agrain * exp(-wfact*logawidth). Default = 3\n\n\n    na          : int\n                  Number of size sampling points (if logawidth set, default=20)\n\n    chopforward : float\n                  If >0 this gives the angle (in degrees from forward)\n                  within which the scattering phase function should be\n                  kept constant, essentially removing the strongly peaked\n                  forward scattering. This is useful for large grains\n                  (large ratio 2*pi*agraincm/lamcm) where the forward\n                  scattering peak is extremely strong, yet extremely\n                  narrow. If we are not interested in very forward-peaked\n                  scattering (e.g. only relevant when modeling e.g. the\n                  halo around the moon on a cold winter night), this will\n                  remove this component and allow a lower angular grid\n                  resolution for the theta grid.\n\n\n    errtol      : float\n                  Tolerance of the relative difference between kscat\n                  and the integral over the zscat Z11 element over angle.\n                  If this tolerance is exceeded, a warning is given.\n\n    verbose     : bool\n                  If set to True, the code will give some feedback so\n                  that one knows what it is doing if it becomes slow.\n\n    extrapolate : bool\n                  If set to True, then if the wavelength grid lamcm goes\n                  out of the range of the wavelength grid of the\n                  optical constants file, then it will make a suitable\n                  extrapolation: keeping the optical constants constant\n                  for lamcm < minimum, and extrapolating log-log for\n                  lamcm > maximum.\n\n    return_type : {0, 1}\n                  If 0 a dictionary is returned (original return type)\n                  if 1 an instance of radmc3dDustOpac will be returned\n\n    Returns\n    -------\n    A dictionary with the following keys:\n\n        * kabs          : ndarray\n                          Absorption opacity kappa_abs_nu (a numpy array) in\n                          units of cm^2/gram\n\n        * ksca          : ndarray\n                          Scattering opacity kappa_abs_nu (a numpy array) in\n                          units of cm^2/gram\n\n        * gsca          : ndarray\n                          The <cos(theta)> g-factor of scattering\n\n        * theta         : ndarray (optional, only if theta is given at input)\n                          The theta grid itself (just a copy of what was given)\n\n        * zscat         : ndarray (optional, only if theta is given at input)\n                          The components of the scattering Mueller matrix\n                          Z_ij for each wavelength and each scattering angel.\n                          The normalization of Z is such that kscat can be\n                          reproduced (as can be checked) by the integral:\n                          2*pi*int_{-1}^{+1}Z11(mu)dmu=kappa_scat.\n                          For symmetry reasons only 6 elements of the Z\n                          matrix are returned: Z11, Z12, Z22, Z33, Z34, Z44.\n                          Note that Z21 = Z12 and Z43 = -Z34.\n                          The scattering matrix is normalized such that\n                          if a plane wave with Stokes flux\n                             Fin = (Fin_I,Fin_Q,Fin_U,Fin_V)\n                          hits a dust grain (which has mass mgrain), then\n                          the scattered flux\n                             Fout = (Fout_I,Fout_Q,Fout_U,Fout_V)\n                          at distance r from the grain at angle theta\n                          is given by\n                             Fout(theta) = (mgrain/r^2) * Zscat . Fin\n                          where . is the matrix-vector multiplication.\n                          Note that the Stokes components must be such\n                          that the horizontal axis in the \"image\" is\n                          pointing in the scattering plane. This means\n                          that radiation with Fin_Q < 0 is scattered well,\n                          because it is vertically polarized (along the\n                          scattering angle axis), while radiation with\n                          Fin_Q > 0 is scatterd less well because it\n                          is horizontally polarized (along the scattering\n                          plane).\n\n        * kscat_from_z11 : ndarray  (optional, only if theta is given at input)\n                           The kscat computed from the (above mentioned)\n                           integral of Z11 over all angles. This should be\n                           nearly identical to kscat if the angular grid\n                           is sufficiently fine. If there are strong\n                           differences, this is an indication that the\n                           angular gridding (the theta grid) is not fine\n                           enough. But you should have then automatically\n                           gotten a warning message as well (see errtol).\n\n        * wavmic        : ndarray (optional, only if extrapolate is set to True)\n                          The original wavelength grid from the optical constants file,\n                          with possibly an added extrapolated\n\n        * ncoef         : ndarray (optional, only if extrapolate is set to True)\n                          The optical constant n at that grid\n\n        * kcoef         : ndarray (optional, only if extrapolate is set to True)\n                          The optical constant k at that grid\n\n        * agr           : ndarray (optional, only if logawidth is not None)\n                          Grain sizes\n\n        * wgt           : ndarray (optional, only if logawidth is not None)\n                          The averaging weights of these grain (not the masses!)\n                          The sum of wgt.sum() must be 1.\n\n        * zscat_nochop  : ndarray (optional, only if chopforward > 0)\n                          The zscat before the forward scattering was chopped off\n\n        * kscat_nochop  : ndarray (optional, only if chopforward > 0)\n                          The kscat originally from the bhmie code\n    \"\"\"\n    #\n    # Load the optical constants\n    #\n    if matdens is None:\n        msg = \"Unknown material density matdens\"\n        raise ValueError(msg)\n\n    if agraincm is None:\n        msg = \"Unknown grain size agraincm\"\n        raise ValueError(msg)\n\n    if lamcm is None:\n        msg = \"Unknown wavelength grid lamcm\"\n        raise ValueError(msg)\n\n    if theta is None:\n        angles = np.array([0., 90., 180.])  # Minimalistic angular s\n        if chopforward != 0.:\n            warnings.warn(\"Chopping disabled. Chopping is only possible if theta grid is given. \", RuntimeWarning)\n    else:\n        angles = theta\n\n    #\n    # Check that the theta array goes from 0 to 180 or\n    # 180 to 0, and store which is 0 and which is 180\n    #\n    if angles[0] != 0:\n        msg = \"First element of the angular grid array is not 0. Scattering angle grid must extend from 0 to 180 \" \\\n              \"degrees.\"\n        raise ValueError(msg)\n    if angles[-1] != 180:\n        msg = \"Last element of the angular grid array is not 180. Scattering angle grid must extend from 0 to 180 \" \\\n              \"degrees.\"\n        raise ValueError(msg)\n\n    nang = angles.shape[0]\n\n    #\n    # Load the optical constants\n    #\n    data = np.loadtxt(fname)\n    wavmic, ncoef, kcoef = data.T\n\n    if wavmic.size <= 1:\n        msg = \"Optical constants file must have at least two rows with two different wavelengths\"\n        raise ValueError(msg)\n\n    if wavmic[1] == wavmic[0]:\n        msg = \"Optical constants file must have at least two rows with two different wavelengths\"\n        raise ValueError(msg)\n\n    #\n    # Check range, and if needed and requested, extrapolate the\n    # optical constants to longer or shorter wavelengths\n    #\n    if extrapolate:\n        wmin = np.min(lamcm)*1e4 * 0.999\n        wmax = np.max(lamcm)*1e4 * 1.001\n        if wmin < np.min(wavmic):\n            if wavmic[0] < wavmic[1]:\n                ncoef = np.append([ncoef[0]], ncoef)\n                kcoef = np.append([kcoef[0]], kcoef)\n                wavmic = np.append([wmin], wavmic)\n            else:\n                ncoef = np.append(ncoef, [ncoef[-1]])\n                kcoef = np.append(kcoef, [kcoef[-1]])\n                wavmic = np.append(wavmic, [wmin])\n        if wmax > np.max(wavmic):\n            if wavmic[0] < wavmic[1]:\n                ncoef = np.append(ncoef, [ncoef[-1] * np.exp((np.log(wmax) - np.log(wavmic[-1])) *\n                                                             (np.log(ncoef[-1]) - np.log(ncoef[-2])) /\n                                                             (np.log(wavmic[-1]) - np.log(wavmic[-2])))])\n                kcoef = np.append(kcoef, [kcoef[-1]*np.exp((np.log(wmax) - np.log(wavmic[-1])) *\n                                                           (np.log(kcoef[-1]) - np.log(kcoef[-2])) /\n                                                           (np.log(wavmic[-1]) - np.log(wavmic[-2])))])\n                wavmic = np.append(wavmic, [wmax])\n            else:\n                ncoef = np.append(ncoef, [ncoef[0]*np.exp((np.log(wmax)-np.log(wavmic[0])) *\n                                                          (np.log(ncoef[0]) - np.log(ncoef[1])) /\n                                                          (np.log(wavmic[0]) - np.log(wavmic[1])))])\n                kcoef = np.append(kcoef, [kcoef[0]*np.exp((np.log(wmax) - np.log(wavmic[0])) *\n                                                          (np.log(kcoef[0]) - np.log(kcoef[1])) /\n                                                          (np.log(wavmic[0]) - np.log(wavmic[1])))])\n                wavmic = np.append([wmax], wavmic)\n    else:\n        if lamcm.min() <= wavmic.min()*1e4:\n            raise ValueError(\"Wavelength range out of range of the optical constants file\")\n\n        if lamcm.max() >= wavmic.max()*1e-4:\n            raise ValueError(\"Wavelength range out of range of the optical constants file\")\n\n    # Interpolate\n    # Note: Must be within range, otherwise stop\n    #\n    f = interp1d(np.log(wavmic*1e-4), np.log(ncoef))\n    ncoefi = np.exp(f(np.log(lamcm)))\n    f = interp1d(np.log(wavmic*1e-4), np.log(kcoef))\n    kcoefi = np.exp(f(np.log(lamcm)))\n    #\n    # Make the complex index of refraction\n    #\n    refidx = ncoefi + kcoefi*1j\n    #\n    # Make a size distribution for the grains\n    # If width is not set, then take just one size\n    #\n    if logawidth is None:\n        agr = np.array([agraincm])\n        wgt = np.array([1.0])\n    else:\n        if logawidth != 0.0:\n            agr = np.exp(np.linspace(np.log(agraincm) - wfact * logawidth, np.log(agraincm) + wfact * logawidth, na))\n            wgt = np.exp(-0.5*((np.log(agr / agraincm)) / logawidth)**2)\n            wgt = wgt / wgt.sum()\n        else:\n            agr = np.array([agraincm])\n            wgt = np.array([1.0])\n    #\n    # Get the true number of grain sizes\n    #\n    nagr = agr.size\n    #\n    # Compute the geometric cross sections\n    #\n    siggeom = np.pi*agr*agr\n    #\n    # Compute the mass of the grain\n    #\n    mgrain = (4*np.pi/3.0)*matdens*agr*agr*agr\n    #\n    # Now prepare arrays\n    #\n    nlam = lamcm.size\n    kabs = np.zeros(nlam)\n    kscat = np.zeros(nlam)\n    gscat = np.zeros(nlam)\n    if theta is not None:\n        zscat = np.zeros((nlam, nang, 6))\n        S11 = np.zeros(nang)\n        S12 = np.zeros(nang)\n        S33 = np.zeros(nang)\n        S34 = np.zeros(nang)\n        if chopforward > 0:\n            zscat_nochop = np.zeros((nlam, nang, 6))\n            kscat_nochop = np.zeros(nlam)\n\n    #\n    # Set error flag to False\n    #\n    error = False\n    errmax = 0.0\n    kscat_from_z11 = np.zeros(nlam)\n    #\n    # Loop over wavelengths\n    #\n    for i in range(nlam):\n        #\n        # Message\n        #\n        if verbose:\n            print(\"Doing wavelength %13.6e cm\" % lamcm[i])\n        #\n        # Now loop over the grain sizes\n        #\n        for l in range(nagr):\n            #\n            # Message\n            #\n            if verbose and nagr > 1:\n                print(\"...Doing grain size %13.6e cm\" % agr[l])\n            #\n            # Compute x\n            #\n            x = 2*np.pi*agr[l]/lamcm[i]\n            #\n            # Call the bhmie code\n            #\n            S1, S2, Qext, Qabs, Qsca, Qback, gsca = miescat.bhmie(x, refidx[i], angles)\n            #\n            # Add results to the averaging over the size distribution\n            #\n            kabs[i] += wgt[l] * Qabs*siggeom[l] / mgrain[l]\n            kscat[i] += wgt[l] * Qsca*siggeom[l] / mgrain[l]\n            gscat[i] += wgt[l] * gsca\n            #\n            # If angles were set, then also compute the Z matrix elements\n            #\n            if theta is not None:\n                #\n                # Compute conversion factor from the Sxx matrix elements\n                # from the Bohren & Huffman code to the Zxx matrix elements we\n                # use (such that 2*pi*int_{-1}^{+1}Z11(mu)dmu=kappa_scat).\n                # This includes the factor k^2 (wavenumber squared) to get\n                # the actual cross section in units of cm^2 / ster, and there\n                # is the mass of the grain to get the cross section per gram.\n                #\n                factor = (lamcm[i]/(2*np.pi))**2/mgrain[l]\n                #\n                # Compute the scattering Mueller matrix elements at each angle\n                #\n                S11[:] = 0.5 * (np.abs(S2[:])**2 + np.abs(S1[:])**2)\n                S12[:] = 0.5 * (np.abs(S2[:])**2 - np.abs(S1[:])**2)\n                S33[:] = np.real(S2[:] * np.conj(S1[:]))\n                S34[:] = np.imag(S2[:] * np.conj(S1[:]))\n                zscat[i, :, 0] += wgt[l] * S11[:] * factor\n                zscat[i, :, 1] += wgt[l] * S12[:] * factor\n                zscat[i, :, 2] += wgt[l] * S11[:] * factor\n                zscat[i, :, 3] += wgt[l] * S33[:] * factor\n                zscat[i, :, 4] += wgt[l] * S34[:] * factor\n                zscat[i, :, 5] += wgt[l] * S33[:] * factor\n        #\n        # If possible, do a check if the integral over zscat is consistent\n        # with kscat\n        #\n        if theta is not None:\n            mu = np.cos(angles * np.pi / 180.)\n            dmu = np.abs(mu[1:nang] - mu[0:nang-1])\n            zav = 0.5 * (zscat[i, 1:nang, 0] + zscat[i, 0:nang-1, 0])\n            dum = 0.5 * zav * dmu\n            kscat_from_z11[i] = dum.sum() * 4 * np.pi\n            err = abs(kscat_from_z11[i]/kscat[i]-1.0)\n            if err > errtol:\n                error = True\n                errmax = max(err, errmax)\n        #\n        # If the chopforward angle is set >0, then we will remove\n        # excessive forward scattering from the opacity. The reasoning\n        # is that extreme forward scattering is, in most cases, equivalent\n        # to no scattering at all.\n        #\n        if chopforward > 0:\n            iang = np.where(angles < chopforward)\n            if angles[0] == 0.0:\n                iiang = np.max(iang)+1\n            else:\n                iiang = np.min(iang)-1\n            zscat_nochop[i, :, :] = zscat[i, :, :]  # Backup\n            kscat_nochop[i] = kscat[i]      # Backup\n            zscat[i, iang, 0] = zscat[i, iiang, 0]\n            zscat[i, iang, 1] = zscat[i, iiang, 1]\n            zscat[i, iang, 2] = zscat[i, iiang, 2]\n            zscat[i, iang, 3] = zscat[i, iiang, 3]\n            zscat[i, iang, 4] = zscat[i, iiang, 4]\n            zscat[i, iang, 5] = zscat[i, iiang, 5]\n            mu = np.cos(angles * np.pi / 180.)\n            dmu = np.abs(mu[1:nang] - mu[0:nang-1])\n            zav = 0.5 * (zscat[i, 1:nang, 0] + zscat[i, 0:nang-1, 0])\n            dum = 0.5 * zav * dmu\n            kscat[i] = dum.sum() * 4 * np.pi\n\n            zav = 0.5 * (zscat[i, 1:nang, 0] * mu[1:] + zscat[i, 0:nang-1, 0] * mu[:-1])\n            dum = 0.5 * zav * dmu\n            gscat[i] = dum.sum() * 4 * np.pi / kscat[i]\n\n    #\n    # If error found, then warn (Then shouldn't it be called a warning? If it's a true error\n    #  shouldn't we stop the execution and raise an exception?)\n    #\n    if error:\n        msg = \" Angular integral of Z11 is not equal to kscat at all wavelength. \\n\"\n        msg += \"Maximum error = %13.6e\" % errmax\n        if chopforward > 0:\n            msg += \"But I am using chopforward to remove strong forward scattering, and then renormalized kapscat.\"\n        warnings.warn(msg, RuntimeWarning)\n    #\n    # Now return what we computed in a dictionary\n    #\n    package = {\"lamcm\": lamcm, \"kabs\": kabs, \"kscat\": kscat,\n               \"gscat\": gscat, \"matdens\": matdens, \"agraincm\": agraincm}\n    if theta is not None:\n        package[\"zscat\"] = np.copy(zscat)\n        package[\"theta\"] = np.copy(angles)\n        package[\"kscat_from_z11\"] = np.copy(kscat_from_z11)\n    if extrapolate:\n        package[\"wavmic\"] = np.copy(wavmic)\n        package[\"ncoef\"] = np.copy(ncoef)\n        package[\"kcoef\"] = np.copy(kcoef)\n    if nagr > 1:\n        package[\"agr\"] = np.copy(agr)\n        package[\"wgt\"] = np.copy(wgt)\n        package[\"wfact\"] = wfact\n        package[\"logawidth\"] = logawidth\n    if chopforward > 0:\n        package[\"zscat_nochop\"] = np.copy(zscat_nochop)\n        package[\"kscat_nochop\"] = np.copy(kscat_nochop)\n\n\n    if return_type == 0:\n        return package\n    else:\n        opac = radmc3dDustOpac()\n        opac.nwav = [nlam]\n        opac.nfreq = [nlam]\n        opac.nang = [nang]\n        opac.wav = [lamcm*1e4]\n        opac.scatang = [angles]\n        opac.freq = [nc.cc/lamcm]\n        opac.kabs = [kabs]\n        opac.ksca = [kscat]\n        opac.phase_g = [gscat]\n        opac.z11 = [zscat[:, :, 0]]\n        opac.z12 = [zscat[:, :, 1]]\n        opac.z22 = [zscat[:, :, 2]]\n        opac.z33 = [zscat[:, :, 3]]\n        opac.z34 = [zscat[:, :, 4]]\n        opac.z44 = [zscat[:, :, 5]]\n        opac.therm = [True]\n        opac.scatmat = [True]\n        return opac\n", "meta": {"hexsha": "dc5d5fb8dfb6eb55a30ccc50d7119f741f7e1c78", "size": 74520, "ext": "py", "lang": "Python", "max_stars_repo_path": "radmc-3d/version_0.41/python/radmc3dPy/dustopac.py", "max_stars_repo_name": "dlmatra/miao", "max_stars_repo_head_hexsha": "71799811b21a4249754390a8ec00972723edab99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-23T00:03:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-23T00:03:40.000Z", "max_issues_repo_path": "radmc-3d/version_0.41/python/radmc3dPy/dustopac.py", "max_issues_repo_name": "dlmatra/miao", "max_issues_repo_head_hexsha": "71799811b21a4249754390a8ec00972723edab99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-05-26T12:54:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-27T10:58:48.000Z", "max_forks_repo_path": "radmc-3d/version_0.41/python/radmc3dPy/dustopac.py", "max_forks_repo_name": "dlmatra/miao", "max_forks_repo_head_hexsha": "71799811b21a4249754390a8ec00972723edab99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-23T14:09:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T14:09:52.000Z", "avg_line_length": 42.852213916, "max_line_length": 120, "alphanum_fraction": 0.4751610306, "include": true, "reason": "import numpy,from scipy", "num_tokens": 17424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.28457599814899737, "lm_q1q2_score": 0.16434131997417215}}
{"text": "__all__ = ['summarize', 'unite', 'subtract_bg']\n\nimport numbers\nimport os\nimport sys\nimport traceback\n\nimport ipy_table\nimport matplotlib\nimport matplotlib.cm\nimport matplotlib.colors\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom IPython.core.getipython import get_ipython\nfrom IPython.display import display\nfrom mpl_toolkits.axes_grid import make_axes_locatable\nfrom sastool.classes2 import Curve, Exposure\nfrom sastool.libconfig import qunit\nfrom sastool.misc.easylsq import FixedParameter, nonlinear_odr\nfrom sastool.misc.errorvalue import ErrorValue\n\nfrom .atsas import datcmp\nfrom .calculation import correlmatrix\nfrom .io import get_different_distances, load_exposure\nfrom .plotting import plotsascurve\nfrom .utils import print_abscissavalue, putlogo, writemarkdown\n\n\ndef _collect_data_for_summarization(headers, raw, reintegrate, qrange):\n    ip = get_ipython()\n    data1d = []\n    data2d = 0\n    headersout = []\n    if not headers:\n        return\n    for head in headers:\n        try:\n            mo = ip.user_ns['mask_override'](head)\n        except KeyError:\n            mo = None\n        ex = None\n        last_exception = None\n        try:\n            ex = load_exposure(head.fsn, raw=raw, processed=not raw)\n            assert isinstance(ex, Exposure)\n            if mo is not None:\n                try:\n                    ex.mask = ex.loader.loadmask(mo)\n                except FileNotFoundError:\n                    print('Could not load mask: %s' % mo)\n                    raise FileNotFoundError('Could not load mask: %s' % mo)\n        except FileNotFoundError as exc:\n            last_exception = sys.exc_info()\n        if ex is None:\n            print('Could not load {} 2D file for FSN {:d}. Exception: {}'.format(\n                ['processed', 'raw'][raw], head.fsn, '\\n'.join(traceback.format_exception(*last_exception))))\n            ip.user_ns['badfsns'] = set(ip.user_ns['badfsns'])\n            ip.user_ns['badfsns'].add(head.fsn)\n            continue\n        ex.header = head\n        curve = None\n        if not reintegrate:\n            for l in [l_ for l_ in ip.user_ns['_loaders'] if l_.processed != raw]:\n                try:\n                    curve = l.loadcurve(head.fsn)\n                    break\n                except FileNotFoundError:\n                    continue\n            if curve is None:\n                print('Cannot load curve for FSN %d: reintegrating.' % head.fsn)\n        if curve is None:\n            # this happens if reintegrate==True or if reintegrate==False but the curve could not be loaded.\n            curve = ex.radial_average(qrange, errorpropagation=3,\n                                      abscissa_errorpropagation=3, raw_result=False)\n        curve = curve.sanitize()\n        data1d.append(curve)\n\n        data1d[-1].save(os.path.join(ip.user_ns['saveto_dir'], 'curve_%05d.txt' % head.fsn))\n        mat = np.zeros((len(data1d[-1]), 3))\n        mat[:, 0] = data1d[-1].q\n        mat[:, 1] = data1d[-1].Intensity\n        mat[:, 2] = data1d[-1].Error\n        np.savetxt(os.path.join(ip.user_ns['saveto_dir'], 'curve_%s_%05d.dat' % (head.title, head.fsn)), mat)\n        del mat\n        data2d = data2d + ex\n        headersout.append(ex.header)\n    data2d /= len(data1d)\n    return data1d, data2d, headersout\n\n\ndef _stabilityassessment(headers, data1d, dist, fig_correlmatrices, correlmatrixaxes, std_multiplier,\n                         correlmatrix_colormap,\n                         correlmatrix_filename, logarithmic_correlmatrix=True, cormaptest=True):\n    # calculate and plot correlation matrix\n    cmatrix, badidx, rowavg = correlmatrix(data1d, std_multiplier, logarithmic_correlmatrix)\n    rowavgmean = rowavg.mean()\n    rowavgstd = rowavg.std()\n    writemarkdown('#### Assessing sample stability')\n    writemarkdown(\"- Mean of row averages: \" + str(rowavgmean))\n    writemarkdown(\"- Std of row averages: \" + str(rowavgstd) + ' (%.2f %%)' % (rowavgstd / rowavgmean * 100))\n\n    img = correlmatrixaxes.imshow(cmatrix, interpolation='nearest', cmap=matplotlib.cm.get_cmap(correlmatrix_colormap))\n    cax = make_axes_locatable(correlmatrixaxes).append_axes('right', size=\"5%\", pad=0.1)\n    fig_correlmatrices.colorbar(img, cax=cax)\n    fsns = [h.fsn for h in headers]\n\n    correlmatrixaxes.set_title('%.2f mm' % dist)\n    correlmatrixaxes.set_xticks(list(range(len(data1d))))\n    correlmatrixaxes.set_xticklabels([str(f) for f in fsns], rotation='vertical')\n    correlmatrixaxes.set_yticks(list(range(len(data1d))))\n    correlmatrixaxes.set_yticklabels([str(f) for f in fsns])\n    np.savez_compressed(correlmatrix_filename,\n                        correlmatrix=cmatrix, fsns=np.array(fsns))\n\n    # Report table on sample stability\n    tab = [['FSN', 'Date', 'Discrepancy', 'Relative discrepancy ((x-mean(x))/std(x))', 'Quality', 'Quality (cormap)']]\n    badfsns = []\n    badfsns_datcmp = []\n    if cormaptest:\n        matC, matp, matpadj, datcmp_ok = datcmp(*data1d)\n    else:\n        datcmp_ok = [not x for x in badidx]\n    for h, bad, discr, dcmp_ok in zip(headers, badidx, rowavg, datcmp_ok):\n        tab.append([h.fsn, h.date.isoformat(), discr, (discr - rowavgmean) / rowavgstd,\n                    [\"\\u2713\", \"\\u2718\\u2718\\u2718\\u2718\\u2718\"][bad],\n                    [\"\\u2713\", \"\\u2718\\u2718\\u2718\\u2718\\u2718\"][dcmp_ok != 1]])\n        if bad:\n            badfsns.append(h.fsn)\n        if (not dcmp_ok and not np.isnan(dcmp_ok)):\n            badfsns_datcmp.append(h.fsn)\n    tab = ipy_table.IpyTable(tab)\n    tab.apply_theme('basic')\n    return badfsns, badfsns_datcmp, tab, rowavg\n\n\ndef summarize(reintegrate=True, dist_tolerance=3, qranges=None,\n              samples=None, raw=False, late_radavg=True, graph_ncols=3,\n              std_multiplier=3, graph_extension='png',\n              graph_dpi=80, correlmatrix_colormap='coolwarm',\n              image_colormap='viridis', correlmatrix_logarithmic=True, cormaptest=True):\n    \"\"\"Summarize scattering patterns and curves for all samples defined \n    by the global `allsamplenames`.\n    \n    Inputs:\n        reintegrate (bool, default=True): if the curves are to be obained\n            by reintegrating the patterns. Otherwise 1D curves are loaded.\n        dist_tolerance (float, default=3): sample-to-detector distances\n            nearer than this are considered the same\n        qranges (dict): a dictionary mapping approximate sample-to-detector\n            distances (within dist_tolerance) to one-dimensional np.ndarrays\n            of the desired q-range of the reintegration.\n        samples (list or None): the names of the samples to summarize. If\n            None, all samples defined by ``allsamplenames`` are used.\n        raw (bool, default=False): if raw images are to be treated instead\n            the evaluated ones (default).\n        late_radavg (bool, default=True): if the scattering curves are to\n            be calculated from the summarized scattering pattern. If False,\n            scattering curves are calculated from each pattern and will be\n            averaged.\n        graph_ncols: the number of columns in graphs (2D patterns, \n            correlation matrices)\n        std_multiplier: if the absolute value of the relative discrepancy \n            is larger than this limit, the exposure is deemed an outlier.\n        graph_extension: the extension of the produced hardcopy files.\n        graph_dpi: resolution of the graphs\n        correlmatrix_colormap: name of the colormap to be used for the\n            correlation matrices (resolved by matplotlib.cm.get_cmap())\n        image_colormap: name of the colormap to be used for the scattering\n            patterns (resolved by matplotlib.cm.get_cmap())\n        correlmatrix_logarithmic: if the correlation matrix has to be\n            calculated from the logarithm of the intensity.\n    \"\"\"\n    if qranges is None:\n        qranges = {}\n    ip = get_ipython()\n    data2d = {}\n    data1d = {}\n    headers_tosave = {}\n    rowavg = {}\n    if raw:\n        writemarkdown('# Summarizing RAW images.')\n        headers = ip.user_ns['_headers']['raw']\n        rawpart = '_raw'  # this will be added in the filenames saved\n    else:\n        writemarkdown('# Summarizing CORRECTED images.')\n        headers = ip.user_ns['_headers']['processed']\n        rawpart = ''  # nothing will be added in the filenames saved\n\n    if samples is None:\n        samples = sorted(ip.user_ns['allsamplenames'])\n    for samplename in samples:\n        writemarkdown('## ' + samplename)\n        headers_sample = [h for h in headers if h.title == samplename]\n        data2d[samplename] = {}\n        rowavg[samplename] = {}\n        data1d[samplename] = {}\n        headers_tosave[samplename] = {}\n        dists = get_different_distances([h for h in headers if h.title == samplename], dist_tolerance)\n        if not dists:\n            writemarkdown('No measurements from sample, skipping.')\n            continue\n        fig_2d = plt.figure()\n        fig_curves = plt.figure()\n        fig_correlmatrices = plt.figure()\n        distaxes = {}\n        correlmatrixaxes = {}\n        ncols = min(len(dists), graph_ncols)\n        nrows = int(np.ceil(len(dists) / ncols))\n        onedimaxes = fig_curves.add_axes((0.1, 0.3, 0.8, 0.5))\n        onedimstdaxes = fig_curves.add_axes((0.1, 0.1, 0.8, 0.2))\n        for distidx, dist in enumerate(dists):\n            writemarkdown(\"### Distance \" + str(dist) + \" mm\")\n            headers_narrowed = [h for h in headers_sample if abs(float(h.distance) - dist) < dist_tolerance]\n            distaxes[dist] = fig_2d.add_subplot(\n                nrows, ncols, distidx + 1)\n            correlmatrixaxes[dist] = fig_correlmatrices.add_subplot(\n                nrows, ncols, distidx + 1)\n            # determine the q-range to be used from the qranges argument.\n            try:\n                distkey_min = min([np.abs(k - dist)\n                                   for k in qranges if np.abs(k - dist) < dist_tolerance])\n            except ValueError:\n                # no matching key in qranges dict\n                qrange = None  # request auto-determination of q-range\n            else:\n                distkey = [\n                    k for k in qranges if np.abs(k - dist) == distkey_min][0]\n                qrange = qranges[distkey]\n\n            (data1d[samplename][dist], data2d[samplename][dist], headers_tosave[samplename][dist]) = \\\n                _collect_data_for_summarization(headers_narrowed, raw, reintegrate, qrange)\n\n            badfsns, badfsns_datcmp, tab, rowavg[samplename][dist] = _stabilityassessment(\n                headers_tosave[samplename][dist],\n                data1d[samplename][dist], dist,\n                fig_correlmatrices,\n                correlmatrixaxes[dist], std_multiplier, correlmatrix_colormap,\n                os.path.join(ip.user_ns['saveto_dir'], 'correlmatrix_%s_%s' % (\n                    samplename,\n                    ('%.2f' % dist).replace('.', '_')) +\n                             rawpart + '.npz'),\n                logarithmic_correlmatrix=correlmatrix_logarithmic,\n                cormaptest=cormaptest)\n\n            if 'badfsns' not in ip.user_ns:\n                ip.user_ns['badfsns'] = {}\n            elif 'badfsns_datcmp' not in ip.user_ns:\n                ip.user_ns['badfsns_datcmp'] = {}\n            ip.user_ns['badfsns'] = set(ip.user_ns['badfsns']).union(badfsns)\n            ip.user_ns['badfsns_datcmp'] = set(ip.user_ns['badfsns_datcmp']).union(badfsns_datcmp)\n            display(tab)\n\n            # Plot the image\n            try:\n                data2d[samplename][dist].imshow(axes=distaxes[dist], show_crosshair=False,\n                                                norm=matplotlib.colors.LogNorm(),\n                                                cmap=matplotlib.cm.get_cmap(image_colormap))\n            except ValueError:\n                print('Error plotting 2D image for sample %s, distance %.2f' % (samplename, dist))\n            distaxes[dist].set_xlabel('q (' + qunit() + ')')\n            distaxes[dist].set_ylabel('q (' + qunit() + ')')\n            distaxes[dist].set_title(\n                '%.2f mm (%d curve%s)' % (dist, len(headers_tosave[samplename][dist]),\n                                          ['', 's'][len(headers_tosave[samplename][dist]) > 1]))\n\n            # Plot the curves\n            Istd = np.stack([c.Intensity for c in data1d[samplename][dist]], axis=1)\n            for c, h in zip(data1d[samplename][dist], headers_tosave[samplename][dist]):\n                color = 'green'\n                if h.fsn in badfsns_datcmp:\n                    color = 'magenta'\n                if h.fsn in badfsns:\n                    color = 'red'\n                c.loglog(axes=onedimaxes, color=color)\n            if Istd.shape[1] > 1:\n                onedimstdaxes.loglog(data1d[samplename][dist][0].q, Istd.std(axis=1) / Istd.mean(axis=1) * 100, 'b-')\n            if not late_radavg:\n                data1d[samplename][dist] = Curve.average(\n                    *data1d[samplename][dist])\n            else:\n                data1d[samplename][dist] = (\n                    data2d[samplename][dist].radial_average(\n                        qrange,\n                        errorpropagation=3,\n                        abscissa_errorpropagation=3, raw_result=False))\n            data1d[samplename][dist].loglog(\n                label='Average', lw=2, color='k', axes=onedimaxes)\n\n            ##Saving image, headers, mask and curve\n            # data2d[samplename][dist].write(\n            #    os.path.join(ip.user_ns['saveto_dir'],\n            #                 samplename + '_'+(\n            #                     '%.2f' % dist).replace('.', '_') +\n            #                 rawpart + '.npz'), plugin='CREDO Reduced')\n            # data2d[samplename][dist].header.write(\n            #    os.path.join(ip.user_ns['saveto_dir'],\n            ###                 samplename + '_'+(\n            #                     '%.2f' % dist).replace('.', '_') +\n            #                 rawpart +'.log'), plugin='CREDO Reduced')\n            # data2d[samplename][dist].mask.write_to_mat(\n            #    os.path.join(ip.user_ns['saveto_dir'],\n            #                 data2d[samplename][dist].mask.maskid+'.mat'))\n            data1d[samplename][dist].save(os.path.join(ip.user_ns['saveto_dir'],\n                                                       samplename + '_' + ('%.2f' % dist).replace('.',\n                                                                                                  '_') + rawpart + '.txt'))\n\n            # Report on qrange and flux\n            q_ = data1d[samplename][dist].q\n            qmin = q_[q_ > 0].min()\n            writemarkdown('#### Q-range & flux')\n            writemarkdown(\n                '- $q_{min}$: ' + print_abscissavalue(qmin, headers_tosave[samplename][dist][0].wavelength, dist))\n            writemarkdown('- $q_{max}$: ' + print_abscissavalue(data1d[samplename][dist].q.max(),\n                                                                headers_tosave[samplename][dist][0].wavelength, dist))\n            writemarkdown('- Number of $q$ points: ' + str(len(data1d[samplename][dist])))\n            meastime = sum([h.exposuretime for h in headers_tosave[samplename][dist]])\n            writemarkdown(\"- from %d exposures, total exposure time %.0f sec <=> %.2f hr\" % (\n                len(headers_tosave[samplename][dist]),\n                meastime, meastime / 3600.))\n            try:\n                flux = [h.flux for h in headers_tosave[samplename][dist]]\n                flux = ErrorValue(np.mean(flux), np.std(flux))\n                writemarkdown(\"- beam flux (photon/sec): %s\" % flux)\n            except KeyError:\n                writemarkdown(\"- *No information on beam flux: dealing with raw data.*\")\n        onedimaxes.set_xlabel('')\n        onedimaxes.set_ylabel('$d\\\\Sigma/d\\\\Omega$ (cm$^{-1}$ sr$^{-1}$)')\n        # plt.legend(loc='best')\n        onedimaxes.grid(True, which='both')\n        onedimaxes.axis('tight')\n        onedimaxes.set_title(samplename)\n        onedimstdaxes.set_xlabel('q (' + qunit() + ')')\n        onedimstdaxes.set_ylabel('Rel.std.dev. of intensity (%)')\n        onedimstdaxes.grid(True, which='both')\n        onedimstdaxes.set_xlim(*onedimaxes.get_xlim())\n        onedimstdaxes.set_xscale(onedimaxes.get_xscale())\n        putlogo(fig_curves)\n        putlogo(fig_2d)\n        fig_2d.tight_layout()\n        fig_correlmatrices.suptitle(samplename)\n        fig_correlmatrices.tight_layout()\n        fig_2d.savefig(\n            os.path.join(ip.user_ns['auximages_dir'],\n                         'averaging2D_' +\n                         samplename + rawpart + '.' + graph_extension),\n            dpi=graph_dpi)\n        fig_curves.savefig(\n            os.path.join(ip.user_ns['auximages_dir'],\n                         'averaging1D_' +\n                         samplename + rawpart + '.' + graph_extension),\n            dpi=graph_dpi)\n        putlogo(fig_correlmatrices)\n        fig_correlmatrices.savefig(\n            os.path.join(ip.user_ns['auximages_dir'],\n                         'correlation_' +\n                         samplename + rawpart + '.' + graph_extension),\n            dpi=graph_dpi)\n        writemarkdown(\"### Collected images from all distances\")\n        plt.show()\n    writemarkdown(\"Updated badfsns list:\")\n    writemarkdown('[' + ', '.join(str(f) for f in ip.user_ns['badfsns']) + ']')\n    writemarkdown(\"Updated badfsns list using datcmp:\")\n    writemarkdown('[' + ', '.join(str(f) for f in ip.user_ns['badfsns_datcmp']) + ']')\n    ip.user_ns['_data1d'] = data1d\n    ip.user_ns['_data2d'] = data2d\n    ip.user_ns['_headers_sample'] = headers_tosave\n    ip.user_ns['_rowavg'] = rowavg\n\n\ndef _merge_two_curves(curve1: Curve, curve2: Curve, qmin, qmax, qsep, use_additive_constant=False):\n    \"\"\"Merge two scattering curves\n\n    :param curve1: the first curve (longer distance)\n    :type curve1: sastool.classes.curve.GeneralCurve\n    :param curve2: the second curve (shorter distance)\n    :type curve2: sastool.classes.curve.GeneralCurve\n    :param qmin: lower bound of the interval for determining the scaling factor\n    :type qmin: float\n    :param qmax: upper bound of the interval for determining the scaling factor\n    :type qmax: float\n    :param qsep: separating (tailoring) point for the merge\n    :type qsep: float\n    :return: merged_curve, factor, background, stat\n    :rtype tuple of a sastool.classes2.curve.Curve and a float\n    \"\"\"\n    curve1=curve1.sanitize()\n    curve2=curve2.sanitize()\n    if len(curve1.trim(qmin, qmax)) > len(curve2.trim(qmin, qmax)):\n        curve2_interp = curve2.trim(qmin, qmax)\n        curve1_interp = curve1.interpolate(curve2_interp.q)\n    else:\n        curve1_interp = curve1.trim(qmin, qmax)\n        curve2_interp = curve2.interpolate(curve1_interp.q)\n    if use_additive_constant:\n        bg_init = 0\n    else:\n        bg_init = FixedParameter(0)\n    factor, bg, stat = nonlinear_odr(curve2_interp.Intensity, curve1_interp.Intensity,\n                                     curve2_interp.Error, curve1_interp.Error,\n                                     lambda x, factor, bg: x * factor + bg, [1.0, bg_init])\n    return Curve.merge(curve1 - bg, curve2 * factor, qsep), factor, bg, stat\n\n\ndef _scale_two_exposures(exp1, exp2, qmin, qmax, N=10, use_additive_constant=False):\n    qrange = np.linspace(qmin, qmax, N)\n    rad1 = exp1.radial_average(qrange=qrange, raw_result=False)\n    rad2 = exp2.radial_average(qrange=qrange, raw_result=False)\n    if use_additive_constant:\n        bg_init = 0\n    else:\n        bg_init = FixedParameter(0)\n    factor, bg, stat = nonlinear_odr(rad2.y, rad1.y, rad2.dy, rad1.dy, lambda x, factor, bg: x * factor + bg,\n                                     [1, bg_init])\n    return factor, bg\n\n\ndef unite(samplename, uniqmin=[], uniqmax=[], uniqsep=[], graph_ncols=2, graph_subplotpars={'hspace': 0.3},\n          graph_extension='png', graph_dpi=80, additive_constant=False):\n    ip = get_ipython()\n    if isinstance(uniqmin, numbers.Number):\n        uniqmin = [uniqmin]\n    if isinstance(uniqmax, numbers.Number):\n        uniqmax = [uniqmax]\n    if isinstance(uniqsep, numbers.Number):\n        uniqsep = [uniqsep]\n    data1d = ip.user_ns['_data1d'][samplename]\n    print(\"Uniting measurements of sample %s at different s-d distances\" % samplename)\n    uniparams = {'qmin': uniqmin, 'qmax': uniqmax, 'qsep': uniqsep}\n    for p in uniparams:\n        uniparams[p] = uniparams[p] + [None] * \\\n                                      max(0, len(data1d) - 1 - len(uniparams[p]))\n    dists = list(reversed(sorted(data1d.keys())))\n    if len(dists) < 2:\n        print(\"Less than two distances found for sample %s; no point of uniting.\" % samplename)\n        return\n    united = None\n    graph_nrows = int(\n        np.ceil((len(dists)) / (graph_ncols * 1.0)))\n    fig = plt.figure()\n    unitedaxis = fig.add_subplot(graph_nrows, graph_ncols, 1)\n    factor = 1.0\n    for idx, dist1, dist2, qmin, qmax, qsep in zip(list(range(len(dists) - 1)),\n                                                   dists[:-1], dists[1:],\n                                                   uniparams['qmin'],\n                                                   uniparams['qmax'],\n                                                   uniparams['qsep']):\n        print(\"    Scaling together distances %f and %f mm\" % (dist1, dist2), flush=True)\n        if united is None:\n            united = data1d[dist1]\n        if qmin is None:\n            qmin = data1d[dist2].sanitize().q.min()\n            print(\"        Auto-detected qmin:\", qmin, flush=True)\n        if qmax is None:\n            qmax = data1d[dist1].sanitize().q.max()\n            print(\"        Auto-detected qmax:\", qmax, flush=True)\n        if qsep is None:\n            qsep = 0.5 * (qmin + qmax)\n            print(\"        Auto-detected qsep:\", qsep, flush=True)\n        ax = fig.add_subplot(graph_nrows, graph_ncols, 2 + idx)\n        (factor * data1d[dist1]).loglog(axes=ax, label='%.2f mm' % dist1)\n        united, factor1, bg, stat = _merge_two_curves(united,\n                                                      data1d[dist2], qmin, qmax, qsep,\n                                                      use_additive_constant=additive_constant)\n        factor = factor1 * factor\n        uniparams['qmin'][idx] = qmin\n        uniparams['qmax'][idx] = qmax\n        uniparams['qsep'][idx] = qsep\n        print(\"        Scaling factor is\", factor.tostring(), flush=True)\n        if not additive_constant:\n            print(\"        Additive constant has not been used.\", flush=True)\n        else:\n            print(\"        Additive constant is:\", bg.tostring(), flush=True)\n        print(\"        Reduced Chi^2 of the ODR fit:\", stat['Chi2_reduced'], flush=True)\n        print(\"        DoF of the ODR fit:\", stat['DoF'], flush=True)\n        (data1d[dist2] * factor + bg).loglog(axes=ax, label='%.2f mm' % dist2)\n        ax.set_xlabel('q (' + qunit() + ')')\n        ax.set_ylabel('$d\\\\Sigma/d\\\\Omega$ (cm$^{-1}$ sr$^{-1}$)')\n        ax.legend(loc='best')\n        # ax.grid(which='both')\n        ax.axis('tight')\n        ax.set_title('Factor: ' + str(factor))\n        lims = ax.axis()\n        ax.plot([qmin, qmin], lims[2:], '--r', lw=2)\n        ax.plot([qmax, qmax], lims[2:], '--r', lw=2)\n        ax.plot([qsep, qsep], lims[2:], '--k')\n        ax.grid(True, which='both')\n    if '_data1dunited' not in ip.user_ns:\n        ip.user_ns['_data1dunited'] = {}\n    united.loglog(axes=unitedaxis)\n    unitedaxis.set_xlabel('q (' + qunit() + ')')\n    unitedaxis.set_ylabel('$d\\\\Sigma/d\\\\Omega$ (cm$^{-1}$ sr$^{-1}$)')\n    unitedaxis.legend(loc='best')\n    unitedaxis.set_title('United scattering of %s' % samplename)\n    unitedaxis.grid(True, which='both')\n    # unitedaxis.grid(which='both')\n    unitedaxis.axis('tight')\n    lims = unitedaxis.axis()\n    for qs in uniparams['qsep']:\n        unitedaxis.plot([qs] * 2, lims[2:], '--r')\n    ip.user_ns['_data1dunited'][samplename] = united\n    putlogo()\n    fig.subplots_adjust(**graph_subplotpars)\n    plt.savefig(\n        os.path.join(ip.user_ns['auximages_dir'], 'uniting_' + samplename + '.' + graph_extension), dpi=graph_dpi)\n    print(\"    United curve spans the following ranges:\")\n    print(\"        q_min: \",\n          print_abscissavalue(united.q.min(), ip.user_ns['_headers_sample'][samplename][dists[0]][0].wavelength))\n    print(\"        q_max: \",\n          print_abscissavalue(united.q.max(), ip.user_ns['_headers_sample'][samplename][dists[0]][0].wavelength))\n    print(\"        q_max/q_min:\", united.q.max() / united.q.min())\n    print(\"        I_min: \", united.Intensity.min(), \"cm^{-1}\")\n    print(\"        I_max: \", united.Intensity.max(), \"cm^{-1}\")\n    print(\"        I_max/I_min:\", united.Intensity.max() / united.Intensity.min())\n    print(\"        # of points: \", len(united))\n    united.save(os.path.join(ip.user_ns['saveto_dir'], 'united_' + samplename + '.txt'))\n    plt.show()\n\n\ndef subtract_bg(samplename, bgname, factor=1, distance=None, disttolerance=2,\n                subname=None, qrange=(), graph_extension='png', graph_dpi=80):\n    \"\"\"Subtract background from measurements.\n\n    Inputs:\n        samplename: the name of the sample\n        bgname: the name of the background measurements. Alternatively, it can\n            be a numeric value (float or ErrorValue), which will be subtracted.\n            If None, this constant will be determined by integrating the\n            scattering curve in the range given by qrange.\n        factor: the background curve will be multiplied by this\n        distance: if None, do the subtraction for all sample-to-detector distances.\n            Otherwise give here the value of the sample-to-detector distance.\n        qrange: a tuple (qmin, qmax)\n        disttolerance: the tolerance in which two distances are considered\n            equal.\n        subname: the sample name of the background-corrected curve. The default\n            is samplename + '-' + bgname\n    \"\"\"\n    ip = get_ipython()\n    data1d = ip.user_ns['_data1d']\n    data2d = ip.user_ns['_data2d']\n    if 'subtractedsamplenames' not in ip.user_ns:\n        ip.user_ns['subtractedsamplenames'] = set()\n    subtractedsamplenames = ip.user_ns['subtractedsamplenames']\n    if subname is None:\n        if isinstance(bgname, str):\n            subname = samplename + '-' + bgname\n        else:\n            subname = samplename + '-const'\n    if distance is None:\n        dists = data1d[samplename]\n    else:\n        dists = [d for d in data1d[samplename] if abs(d - distance) < disttolerance]\n    for dist in dists:\n        if isinstance(bgname, str):\n            if not disttolerance:\n                if dist not in data1d[bgname]:\n                    print(\n                        'Warning: Missing distance %g for background measurement (samplename: %s, background samplename: %s)' % (\n                            dist, samplename, bgname))\n                    continue\n                else:\n                    bgdist = dist\n            else:\n                bgdist = sorted([(d, r) for (d, r) in [(d, np.abs(d - dist)) for d in list(data1d[bgname].keys())] if\n                                 r <= disttolerance], key=lambda x: x[1])[0][0]\n        if subname not in data1d:\n            data1d[subname] = {}\n        if subname not in data2d:\n            data2d[subname] = {}\n        if subname not in ip.user_ns['_headers_sample']:\n            ip.user_ns['_headers_sample'][subname] = {}\n        data1_s = data1d[samplename][dist]\n        data2_s = data2d[samplename][dist]\n        if isinstance(bgname, str):\n            data1_bg = data1d[bgname][bgdist]\n            data2_bg = data2d[bgname][bgdist]\n            if factor is None:\n                factor = data1_s.trim(*qrange).momentum(0) / data1_bg.trim(*qrange).momentum(0)\n        elif bgname is None:\n            data1_bg = data1_s.trim(*qrange).momentum(0)\n            data2_bg = data1_bg\n        else:\n            data1_bg = bgname\n            data2_bg = bgname\n        if factor is None:\n            factor = 1\n        data1d[subname][dist] = data1_s - factor * data1_bg\n        data2d[subname][dist] = data2_s - factor * data2_bg\n        data1d[subname][dist].save(\n            os.path.join(ip.user_ns['saveto_dir'], subname + '_' + ('%.2f' % dist).replace('.', '_') + '.txt'))\n        ip.user_ns['_headers_sample'][subname][dist] = ip.user_ns['_headers_sample'][samplename][\n            dist]  # ugly hack, I have no better idea.\n        plt.figure()\n        plotsascurve(samplename, dist=dist)\n        if isinstance(bgname, str):\n            plotsascurve(bgname, dist=dist, factor=factor)\n        plotsascurve(subname, dist=dist)\n        plt.savefig(os.path.join(ip.user_ns['auximages_dir'],\n                                 'subtractbg_' + samplename + '.' + graph_extension),\n                    dpi=graph_dpi)\n\n        subtractedsamplenames.add(subname)\n", "meta": {"hexsha": "45bd55025141174a178a48f7c21135995328504b", "size": 28890, "ext": "py", "lang": "Python", "max_stars_repo_path": "credolib/procedures.py", "max_stars_repo_name": "awacha/credolib", "max_stars_repo_head_hexsha": "11c0be3eea7257d3d6e13697d3e76ce538f2f1b2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "credolib/procedures.py", "max_issues_repo_name": "awacha/credolib", "max_issues_repo_head_hexsha": "11c0be3eea7257d3d6e13697d3e76ce538f2f1b2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "credolib/procedures.py", "max_forks_repo_name": "awacha/credolib", "max_forks_repo_head_hexsha": "11c0be3eea7257d3d6e13697d3e76ce538f2f1b2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.9104477612, "max_line_length": 129, "alphanum_fraction": 0.5809276566, "include": true, "reason": "import numpy", "num_tokens": 7418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.16426816455144932}}
{"text": "# -*- coding: utf-8 -*-\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n#\n# LICENSE\n#\n# Copyright (C) 2010-2018 GEM Foundation, G. Weatherill, M. Pagani,\n# D. Monelli.\n#\n# The Hazard Modeller's Toolkit is free software: you can redistribute\n# it and/or modify it under the terms of the GNU Affero General Public\n# License as published by the Free Software Foundation, either version\n# 3 of the License, or (at your option) any later version.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>\n#\n# DISCLAIMER\n#\n# The software Hazard Modeller's Toolkit (openquake.hmtk) provided herein\n# is released as a prototype implementation on behalf of\n# scientists and engineers working within the GEM Foundation (Global\n# Earthquake Model).\n#\n# It is distributed for the purpose of open collaboration and in the\n# hope that it will be useful to the scientific, engineering, disaster\n# risk and software design communities.\n#\n# The software is NOT distributed as part of GEM’s OpenQuake suite\n# (https://www.globalquakemodel.org/tools-products) and must be considered as a\n# separate entity. The software provided herein is designed and implemented\n# by scientific staff. It is not developed to the design standards, nor\n# subject to same level of critical review by professional software\n# developers, as GEM’s OpenQuake software suite.\n#\n# Feedback and contribution to the software is welcome, and can be\n# directed to the hazard scientific staff of the GEM Model Facility\n# (hazard@globalquakemodel.org).\n#\n# The Hazard Modeller's Toolkit (openquake.hmtk) is therefore distributed WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n# for more details.\n#\n# The GEM Foundation, and the authors of the software, assume no\n# liability for use of the software.\n\n# -*- coding: utf-8 -*-\n\"\"\"\n\"\"\"\n\nimport numpy as np\nfrom openquake.hmtk.seismicity.occurrence.utils import input_checks, recurrence_table\nfrom openquake.hmtk.seismicity.occurrence.base import (\n    SeismicityOccurrence, OCCURRENCE_METHODS)\nfrom openquake.hmtk.seismicity.occurrence.aki_maximum_likelihood import AkiMaxLikelihood\n\n\n@OCCURRENCE_METHODS.add(\n    'calculate', **{\n        'completeness': True,\n        'reference_magnitude': 0.0,\n        'magnitude_interval': 0.1,\n        'Average Type': ['Weighted', 'Harmonic']})\nclass BMaxLikelihood(SeismicityOccurrence):\n    \"\"\" Implements maximum likelihood calculations taking into account time\n    variation in completeness\"\n    \"\"\"\n\n    def calculate(self, catalogue, config, completeness=None):\n        \"\"\" Calculates recurrence parameters a_value and b_value, and their\n        respective uncertainties\n\n        :param catalogue: Earthquake Catalogue\n            An instance of :class:`openquake.hmtk.seismicity.catalogue`\n        :param dict config:\n            A configuration dictionary; the only parameter that can be\n            defined in this case if the type of average to be applied\n            in the calculation\n        :param list or numpy.ndarray completeness:\n            Completeness table\n        \"\"\"\n\n        # Input checks\n        cmag, ctime, ref_mag, dmag, config = input_checks(catalogue,\n                                                          config,\n                                                          completeness)\n\n        # Check the configuration\n        if not config['Average Type'] in ['Weighted', 'Harmonic']:\n            raise ValueError('Average type not recognised in bMaxLiklihood!')\n        return self._b_ml(catalogue, config, cmag, ctime, ref_mag, dmag)\n\n    def _b_ml(self, catalogue, config, cmag, ctime, ref_mag, dmag):\n        end_year = float(catalogue.end_year)\n        catalogue = catalogue.data\n        ival = 0\n        mag_eq_tolerance = 1E-5\n        aki_ml = AkiMaxLikelihood()\n\n        while ival < np.shape(ctime)[0]:\n\n            id0 = np.abs(ctime - ctime[ival]) < mag_eq_tolerance\n            m_c = np.min(cmag[id0])\n\n            print('--- ctime', ctime[ival], ' m_c', m_c)\n\n            # Find events later than cut-off year, and with magnitude\n            # greater than or equal to the corresponding completeness\n            # magnitude. m_c - mag_eq_tolerance is required to correct\n            # floating point differences.\n            id1 = np.logical_and(\n                catalogue['year'] >= ctime[ival],\n                catalogue['magnitude'] >= (m_c - mag_eq_tolerance))\n            # Get a- and b- value for the selected events\n            temp_rec_table = recurrence_table(catalogue['magnitude'][id1],\n                                              dmag,\n                                              catalogue['year'][id1],\n                                              end_year - ctime[ival] + 1)\n\n            bval, sigma_b = aki_ml._aki_ml(temp_rec_table[:, 0],\n                                           temp_rec_table[:, 1], dmag, m_c)\n\n            if ival == 0:\n                gr_pars = np.array([np.hstack([bval, sigma_b])])\n                neq = np.sum(id1)  # Number of events\n            else:\n                gr_pars = np.vstack([gr_pars, np.hstack([bval, sigma_b])])\n                neq = np.hstack([neq, np.sum(id1)])\n            ival = ival + np.sum(id0)\n\n        # Get average GR parameters\n        bval, sigma_b = self._average_parameters(\n            gr_pars, neq, config['Average Type'])\n        aval = self._calculate_a_value(bval,\n                                       np.float(np.sum(neq)),\n                                       cmag,\n                                       ctime,\n                                       catalogue['magnitude'],\n                                       end_year,\n                                       dmag)\n        sigma_a = self._calculate_a_value(bval + sigma_b,\n                                          np.float(np.sum(neq)),\n                                          cmag,\n                                          ctime,\n                                          catalogue['magnitude'],\n                                          end_year,\n                                          dmag)\n        if not config['reference_magnitude']:\n            return bval,\\\n                sigma_b,\\\n                aval,\\\n                sigma_a - aval\n        else:\n            rate = 10. ** (aval - bval * config['reference_magnitude'])\n            sigma_rate = 10. ** (sigma_a -\n                                 bval * config['reference_magnitude']) - rate\n            return bval,\\\n                sigma_b,\\\n                rate,\\\n                sigma_rate\n\n    def _average_parameters(self, gr_params, neq, average_type='Weighted'):\n        \"\"\"\n        Calculates the average of a set of Gutenberg-Richter parameters\n        depending on the average type\n\n        :param numpy.ndarray gr_params:\n            Gutenberg-Richter parameters [b, sigma_b, a, sigma_a]\n        :param numpy.ndarray neq:\n\n        \"\"\"\n        if np.shape(gr_params)[0] != neq.size:\n            raise ValueError('Number of weights does not correspond'\n                             ' to number of parameters')\n\n        if 'Harmonic' in average_type:\n            average_parameters = self._harmonic_mean(gr_params, neq)\n        else:\n            average_parameters = self._weighted_mean(gr_params, neq)\n        bval = average_parameters[0]\n        sigma_b = average_parameters[1]\n        return bval, sigma_b\n\n    def _calculate_a_value(self, bvalue, nvalue, cmag, cyear, magnitude,\n                           end_year, dmag):\n        \"\"\"\n        Calculates the a-value using the method of Weichert (1980) and \n        McGuire (2004)\n        \"\"\"\n        mmin = cmag[0]\n        mmax = np.max(magnitude)\n        if mmax > np.max(cmag):\n            cmag = np.hstack([cmag, mmax + dmag])\n        target_mag = (cmag[:-1] + cmag[1:]) / 2.\n        nyear = end_year - cyear + 1.\n        beta = bvalue * np.log(10.)\n        rate_mmin = nvalue * np.sum(np.exp(-beta * target_mag)) /\\\n            np.sum(nyear * np.exp(-beta * target_mag))\n        return np.log10(rate_mmin) + bvalue * mmin\n\n    def _weighted_mean(self, parameters, neq):\n        '''Simple weighted mean'''\n        weight = neq.astype(float) / np.sum(neq)\n        if np.shape(parameters)[0] != weight.size:\n            raise ValueError('Parameter vector not same shape as weights')\n        else:\n            average_value = np.zeros(np.shape(parameters)[1], dtype=float)\n            for iloc in range(0, np.shape(parameters)[1]):\n                average_value[iloc] = np.sum(parameters[:, iloc] * weight)\n        return average_value\n\n    def _harmonic_mean(self, parameters, neq):\n        '''Harmonic mean'''\n        weight = neq.astype(float) / np.sum(neq)\n        if np.shape(parameters)[0] != weight.size:\n            raise ValueError('Parameter vector not same shape as weights')\n\n        average_value = np.zeros(np.shape(parameters)[1], dtype=float)\n        for iloc in range(0, np.shape(parameters)[1]):\n            average_value[iloc] = 1. / np.sum(\n                (weight * (1. / parameters[:, iloc])))\n        return average_value\n", "meta": {"hexsha": "12b3824005f51e7c9729350efa200563244e9259", "size": 9193, "ext": "py", "lang": "Python", "max_stars_repo_path": "openquake/hmtk/seismicity/occurrence/b_maximum_likelihood.py", "max_stars_repo_name": "gfzriesgos/shakyground-lfs", "max_stars_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-01T00:28:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-01T00:28:24.000Z", "max_issues_repo_path": "openquake/hmtk/seismicity/occurrence/b_maximum_likelihood.py", "max_issues_repo_name": "gfzriesgos/shakyground-lfs", "max_issues_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-08-31T14:14:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-11T12:53:13.000Z", "max_forks_repo_path": "openquake/hmtk/seismicity/occurrence/b_maximum_likelihood.py", "max_forks_repo_name": "gfzriesgos/shakyground-lfs", "max_forks_repo_head_hexsha": "2caf67cc32e6800286eded2df1efb05973ccf41b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-08-31T14:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-17T10:06:02.000Z", "avg_line_length": 41.0401785714, "max_line_length": 88, "alphanum_fraction": 0.5821820951, "include": true, "reason": "import numpy", "num_tokens": 2032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.164169590097715}}
{"text": "#!/usr/bin/env python\n\nimport copy\nfrom importlib import import_module\nimport logging\n\nimport numpy as np\n\nfrom openquake.hazardlib.gsim.base import GMPE\nfrom openquake.hazardlib.gsim.boore_2014 import BooreEtAl2014\nfrom openquake.hazardlib.gsim.campbell_bozorgnia_2014 import CampbellBozorgnia2014\nfrom openquake.hazardlib.imt import PGA, PGV, SA\nfrom openquake.hazardlib import const\nfrom openquake.hazardlib.valid import gsim\nfrom openquake.hazardlib.contexts import RuptureContext\n\nfrom shakelib.conversions.imt.abrahamson_bhasin_2020 import AbrahamsonBhasin2020\nfrom shakelib.conversions.imc.boore_kishida_2017 import BooreKishida2017\nfrom shakelib.sites import Sites\n\n# Special case GMPEs:\nfrom shakelib.gmpe.nga_east import NGAEast\n\n\ndef set_sites_depth_parameters(sites, gmpe):\n    \"\"\"\n    Need to select the appropriate z1pt0 value for different GMPEs.\n    Note that these are required site parameters, so even though\n    OQ has these equations built into the class in most cases.\n    I have submitted an issue to OQ requesting subclasses of these\n    methods that do not require the depth parameters in the\n    SitesContext to make this easier.\n\n    Args:\n        sites:1 An OQ sites context.\n        gmpe: An OQ GMPE instance.\n\n    Returns:\n        An OQ sites context with the depth parameters set for the\n        requested GMPE.\n    \"\"\"\n    if gmpe == \"[MultiGMPE]\":\n        return sites\n\n    Sites._addDepthParameters(sites)\n\n    if (\n        gmpe == \"[AbrahamsonEtAl2014]\"\n        or gmpe == \"[AbrahamsonEtAl2014]\\nregion = 'TWN'\"\n        or gmpe == \"[AbrahamsonEtAl2014]\\nregion = 'CHN'\"\n    ):\n        sites.z1pt0 = sites.z1pt0_ask14_cal\n    if gmpe == \"[AbrahamsonEtAl2014]\\nregion = 'JPN'\":\n        sites.z1pt0 = sites.z1pt0_ask14_jpn\n    if gmpe == \"[ChiouYoungs2014]\" or isinstance(gmpe, BooreEtAl2014):\n        sites.z1pt0 = sites.z1pt0_cy14_cal\n    if isinstance(gmpe, CampbellBozorgnia2014):\n        if (\n            gmpe == \"[CampbellBozorgnia2014JapanSite]\"\n            or gmpe == \"[CampbellBozorgnia2014HighQJapanSite]\"\n            or gmpe == \"[CampbellBozorgnia2014LowQJapanSite]\"\n        ):\n            sites.z2pt5 = sites.z2pt5_cb14_jpn\n        else:\n            sites.z2pt5 = sites.z2pt5_cb14_cal\n    if (\n        gmpe == \"[ChiouYoungs2008]\"\n        or gmpe == \"[Bradley2013]\"\n        or gmpe == \"[Bradley2013Volc]\"\n    ):\n        sites.z1pt0 = sites.z1pt0_cy08\n    if gmpe == \"[CampbellBozorgnia2008]\":\n        sites.z2pt5 = sites.z2pt5_cb07\n    if gmpe == \"[AbrahamsonSilva2008]\":\n        sites.z1pt0 = gmpe._compute_median_z1pt0(sites.vs30)\n\n    return sites\n\n\ndef stuff_context(sites, rup, dists):\n    \"\"\"\n    Function to fill a rupture context with the contents of all of the\n    other contexts.\n\n    Args:\n        sites (SiteCollection): A SiteCollection object.\n\n        rup (RuptureContext): A RuptureContext object.\n\n        dists (DistanceContext): A DistanceContext object.\n\n    Returns:\n        RuptureContext: A new RuptureContext whose attributes are all of\n        the elements of the three inputs.\n    \"\"\"\n    ctx = RuptureContext()\n\n    for name in [name for name in vars(sites) if not name.startswith(\"__\")]:\n        setattr(ctx, name, getattr(sites, name))\n    for name in [name for name in vars(rup) if not name.startswith(\"__\")]:\n        setattr(ctx, name, getattr(rup, name))\n    for name in [name for name in vars(dists) if not name.startswith(\"__\")]:\n        setattr(ctx, name, getattr(dists, name))\n\n    return ctx\n\n\ndef get_gmpe_from_name(name, conf):\n\n    # Only import the NullGMPE when we're testing\n    # We'll want to import any other GMPEs we add at the top of this module\n    # so that gsim() picks them up; anything in OQ is already included\n    if name == \"NullGMPE\":\n        mod = import_module(conf[\"gmpe_modules\"][name][1])\n    return gsim(name)\n\n\nclass MultiGMPE(GMPE):\n    \"\"\"\n    Implements a GMPE that is the combination of multiple GMPEs.\n\n    \"\"\"\n\n    DEFINED_FOR_TECTONIC_REGION_TYPE = None\n    DEFINED_FOR_INTENSITY_MEASURE_TYPES = None\n    DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = None\n    DEFINED_FOR_STANDARD_DEVIATION_TYPES = set([const.StdDev.TOTAL])\n    REQUIRES_SITES_PARAMETERS = None\n    REQUIRES_RUPTURE_PARAMETERS = None\n    REQUIRES_DISTANCES = None\n\n    def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):\n        \"\"\"\n        See superclass `method <http://docs.openquake.org/oq-hazardlib/master/gsim/index.html#openquake.hazardlib.gsim.base.GroundShakingIntensityModel.get_mean_and_stddevs>`__.\n\n        Unlike the superclass method, the stddev list returned by this\n        function will have twice as many arrays as are requested in\n        stddev_types: The first set will include the standard deviation\n        inflation due to the point-source to finite fault conversion (if\n        any), and the second set will not include this inflation. In the\n        case where a finite rupture is provided (and, thus, no point-source\n        to finite rupture adjustments are made) the two sets of stddev\n        arrays will be identical. Thus, if::\n\n            stddev_types = [const.StdDev.TOTAL, const.StdDev.INTRA_EVENT,\n                            const.StdDev.INTER_EVENT]\n\n        the returned stddev list will contain six arrays: the first three\n        will include the point-source inflation, and the second three will\n        not.\n        \"\"\"  # noqa\n\n        # ---------------------------------------------------------------------\n        # Sort out shapes of the sites and dists elements\n        # Need to turn all 2D arrays into 1D arrays because of\n        # inconsistencies in how arrays are handled in OpenQuake.\n        # ---------------------------------------------------------------------\n        shapes = []\n        for k, v in sites.__dict__.items():\n            if k == \"_slots_\":\n                continue\n            if (k != \"lons\") and (k != \"lats\"):\n                shapes.append(v.shape)\n                sites.__dict__[k] = np.reshape(sites.__dict__[k], (-1,))\n        for k, v in dists.__dict__.items():\n            if k == \"_slots_\":\n                continue\n            if (k != \"lons\") and (k != \"lats\") and v is not None:\n                shapes.append(v.shape)\n                dists.__dict__[k] = np.reshape(dists.__dict__[k], (-1,))\n        shapeset = set(shapes)\n        if len(shapeset) != 1:\n            raise Exception(\"All dists and sites elements must have same shape.\")\n        else:\n            orig_shape = list(shapeset)[0]\n\n        sd_avail = self.DEFINED_FOR_STANDARD_DEVIATION_TYPES\n        if not sd_avail.issuperset(set(stddev_types)):\n            raise Exception(\"Requested an unavailable stddev_type.\")\n\n        # Evaluate MultiGMPE:\n        lnmu, lnsd = self.__get_mean_and_stddevs__(sites, rup, dists, imt, stddev_types)\n\n        # Check for large-distance cutoff/weights\n        if hasattr(self, \"CUTOFF_DISTANCE\"):\n            lnmu_large, lnsd_large = self.__get_mean_and_stddevs__(\n                sites, rup, dists, imt, stddev_types, large_dist=True\n            )\n            # Stomp on lnmu and lnsd at large distances\n            dist_cutoff = self.CUTOFF_DISTANCE\n            lnmu[dists.rjb > dist_cutoff] = lnmu_large[dists.rjb > dist_cutoff]\n            for i in range(len(lnsd)):\n                lnsd[i][dists.rjb > dist_cutoff] = lnsd_large[i][\n                    dists.rjb > dist_cutoff\n                ]\n\n        # Undo reshapes of inputs\n        for k, v in dists.__dict__.items():\n            if k == \"_slots_\":\n                continue\n            if (k != \"lons\") and (k != \"lats\") and v is not None:\n                dists.__dict__[k] = np.reshape(dists.__dict__[k], orig_shape)\n        for k, v in sites.__dict__.items():\n            if k == \"_slots_\":\n                continue\n            if (k != \"lons\") and (k != \"lats\"):\n                sites.__dict__[k] = np.reshape(sites.__dict__[k], orig_shape)\n\n        # Reshape output\n        lnmu = np.reshape(lnmu, orig_shape)\n        for i in range(len(lnsd)):\n            lnsd[i] = np.reshape(lnsd[i], orig_shape)\n\n        return lnmu, lnsd\n\n    def __get_mean_and_stddevs__(\n        self, sites, rup, dists, imt, stddev_types, large_dist=False\n    ):\n\n        # ---------------------------------------------------------------------\n        # Sort out which set of weights to use\n        # ---------------------------------------------------------------------\n        if large_dist is False:\n            wts = self.WEIGHTS\n        else:\n            wts = self.WEIGHTS_LARGE_DISTANCE\n\n        # ---------------------------------------------------------------------\n        # This is the array to hold the weighted combination of the GMPEs\n        # ---------------------------------------------------------------------\n        lnmu = np.zeros_like(sites.vs30)\n        # ---------------------------------------------------------------------\n        # Hold on to the individual means and stddevs so we can compute the\n        # combined stddev\n        # ---------------------------------------------------------------------\n        lnmu_list = []\n        lnsd_list = []\n\n        for i, gmpe in enumerate(self.GMPES):\n            # -----------------------------------------------------------------\n            # Loop over GMPE list\n            # -----------------------------------------------------------------\n\n            set_sites_depth_parameters(sites, gmpe)\n\n            # -----------------------------------------------------------------\n            # Select the IMT\n            # -----------------------------------------------------------------\n\n            gmpe_imts = [\n                imt.__name__ for imt in list(gmpe.DEFINED_FOR_INTENSITY_MEASURE_TYPES)\n            ]\n\n            if (\n                not isinstance(gmpe, MultiGMPE)\n                and (imt.string == \"PGV\")\n                and (\"PGV\" not in gmpe_imts)\n            ):\n                ab2020 = AbrahamsonBhasin2020(rup.mag)\n                timt = SA(ab2020.getTref())\n            else:\n                timt = imt\n\n            # -----------------------------------------------------------------\n            # Grab GMPE_LIMITS in gmpe instance for later as the multigmpe\n            # nests downward.\n            # -----------------------------------------------------------------\n            if hasattr(self, \"GMPE_LIMITS\"):\n                # Remember that GMPE_LIMITS is only present if it is getting\n                # loaded from a config... we could change this eventually.\n                gmpe.GMPE_LIMITS = self.GMPE_LIMITS\n\n            # -----------------------------------------------------------------\n            # Apply GMPE_LIMITS if applicable\n            # -----------------------------------------------------------------\n            if hasattr(gmpe, \"GMPE_LIMITS\"):\n                gmpes_with_limits = list(gmpe.GMPE_LIMITS.keys())\n                gmpe_class_str = str(gmpe).replace(\"[\", \"\").replace(\"]\", \"\")\n                if gmpe_class_str in gmpes_with_limits:\n                    limit_dict = gmpe.GMPE_LIMITS[gmpe_class_str]\n                    for k, v in limit_dict.items():\n                        if k == \"vs30\":\n                            vs30min = float(v[0])\n                            vs30max = float(v[1])\n                            sites.vs30 = np.clip(sites.vs30, vs30min, vs30max)\n                            Sites._addDepthParameters(sites)\n\n            # -----------------------------------------------------------------\n            # Evaluate\n            # -----------------------------------------------------------------\n            if not isinstance(gmpe, MultiGMPE):\n                ctx = stuff_context(sites, rup, dists)\n                lmean, lsd = gmpe.get_mean_and_stddevs(\n                    ctx, ctx, ctx, timt, stddev_types\n                )\n            else:\n                lmean, lsd = gmpe.get_mean_and_stddevs(\n                    sites, rup, dists, timt, stddev_types\n                )\n\n            if not isinstance(gmpe, MultiGMPE):\n                # -------------------------------------------------------------\n                # We may need to inflate the standard deviations to account for\n                # the point-source to finite rupture conversion.\n                # -------------------------------------------------------------\n                lsd_new = self.__inflatePSSigma__(\n                    gmpe, lmean, lsd, sites, rup, dists, timt, stddev_types\n                )\n                for sd in lsd:\n                    lsd_new.append(sd)\n                lsd = lsd_new\n\n                # -------------------------------------------------------------\n                # If IMT is PGV and PGV is not given by the GMPE, then\n                # convert from the appropriate PSA\n                # -------------------------------------------------------------\n                if (imt.string == \"PGV\") and (\"PGV\" not in gmpe_imts):\n                    lmean, lsd = ab2020.getPGVandSTDDEVS(\n                        lmean, lsd, stddev_types, ctx.rrup, ctx.vs30\n                    )\n\n                # -------------------------------------------------------------\n                # -------------------------------------------------------------\n                if self.HAS_SITE[i] is False:\n                    lamps = self.__get_site_factors__(\n                        sites, rup, dists, timt, default=True\n                    )\n                    lmean = lmean + lamps\n\n                # -------------------------------------------------------------\n                # Convertions due to component definition\n                # -------------------------------------------------------------\n                imc_in = gmpe.DEFINED_FOR_INTENSITY_MEASURE_COMPONENT\n                imc_out = self.DEFINED_FOR_INTENSITY_MEASURE_COMPONENT\n                if imc_in != imc_out:\n                    bk17 = BooreKishida2017(imc_in, imc_out)\n                    lmean = bk17.convertAmps(imt, lmean, dists.rrup, rup.mag)\n                    #\n                    # The extra sigma from the component conversion appears to\n                    # apply to the total sigma, so the question arises as to\n                    # how to apportion it between the intra- and inter-event\n                    # sigma. Here we assume it all enters as intra-event sigma.\n                    #\n                    for j, stddev_type in enumerate(stddev_types):\n                        if stddev_type == const.StdDev.INTER_EVENT:\n                            continue\n                        lsd[j] = bk17.convertSigmas(imt, lsd[j])\n\n            # End: if GMPE is not MultiGMPE\n\n            #\n            # At this point lsd will have 2 * len(stddev_types) entries, the\n            # first group will have the point-source to finite rupture\n            # inflation (if any), and the second set will not; in cases where\n            # a finite rupture is used, the two sets will be identical\n            #\n\n            # -----------------------------------------------------------------\n            # Compute weighted mean and collect the elements to compute sd\n            # -----------------------------------------------------------------\n\n            lnmu = lnmu + wts[i] * lmean\n            lnmu_list.append(lmean)\n            lnsd_list = lnsd_list + lsd\n\n        # -----------------------------------------------------------------\n        # The mean is a weighted sum of random variables, so the stddev\n        # is the weighted sum of of their covariances (effectively). See:\n        # https://en.wikipedia.org/wiki/Variance#Weighted_sum_of_variables\n        # for an explanation. Also see:\n        # http://usgs.github.io/shakemap/manual4_0/tg_processing.html#ground-motion-prediction\n        # for a discussion on the way this is implemented here.\n        # -------------------------------------------------------------- # noqa\n\n        nwts = len(wts)\n        npwts = np.array(wts).reshape((1, -1))\n        nsites = len(lnmu)\n        # Find the correlation coefficients among the gmpes; if there are\n        # fewer than 10 points, just use an approximation (noting that the\n        # correlation among GMPEs tends to be quite high).\n        if nsites < 10:\n            cc = np.full((nwts, nwts), 0.95)\n            np.fill_diagonal(cc, 1.0)\n        else:\n            np.seterr(divide=\"ignore\", invalid=\"ignore\")\n            cc = np.reshape(np.corrcoef(lnmu_list), (nwts, nwts))\n            np.seterr(divide=\"warn\", invalid=\"warn\")\n            cc[np.isnan(cc)] = 1.0\n\n        # Multiply the correlation coefficients by the weights matrix\n        # (this is cheaper than multiplying all of elements of each\n        # stddev array by their weights since we have to multiply\n        # everything by the correlation coefficient matrix anyway))\n        cc = ((npwts * npwts.T) * cc).reshape((nwts, nwts, 1))\n        nstds = len(stddev_types)\n        lnsd_new = []\n        for i in range(nstds * 2):\n            sdlist = []\n            for j in range(nwts):\n                sdlist.append(lnsd_list[j * nstds * 2 + i].reshape((1, 1, -1)))\n            sdstack = np.hstack(sdlist)\n            wcov = (sdstack * np.transpose(sdstack, axes=(1, 0, 2))) * cc\n            # This sums the weighted covariance as each point in the output\n            lnsd_new.append(np.sqrt(wcov.sum((0, 1))))\n\n        return lnmu, lnsd_new\n\n    @classmethod\n    def __from_config__(cls, conf, filter_imt=None):\n        \"\"\"\n        Construct a MultiGMPE from a config file.\n\n        Args:\n            conf (dict): Dictionary of config options.\n            filter_imt (IMT): An optional IMT to filter/reweight the GMPE list.\n\n        Returns:\n            MultiGMPE object.\n\n        \"\"\"\n        IMC = getattr(const.IMC, conf[\"interp\"][\"component\"])\n        selected_gmpe = conf[\"modeling\"][\"gmpe\"]\n\n        logging.debug(f\"selected_gmpe: {selected_gmpe}\")\n        logging.debug(f\"IMC: {IMC}\")\n\n        # ---------------------------------------------------------------------\n        # Allow for selected_gmpe to be found in either conf['gmpe_sets'] or\n        # conf['gmpe_modules'], if it is a GMPE set, then all entries must be\n        # either a GMPE or a GMPE set (cannot have a GMPE set that is a mix of\n        # GMPEs and GMPE sets).\n        # ---------------------------------------------------------------------\n\n        if selected_gmpe in conf[\"gmpe_sets\"].keys():\n            selected_gmpe_sets = conf[\"gmpe_sets\"][selected_gmpe][\"gmpes\"]\n            gmpe_set_weights = [\n                float(w) for w in conf[\"gmpe_sets\"][selected_gmpe][\"weights\"]\n            ]\n            logging.debug(f\"selected_gmpe_sets: {selected_gmpe_sets}\")\n            logging.debug(f\"gmpe_set_weights: {gmpe_set_weights}\")\n\n            # -----------------------------------------------------------------\n            # If it is a GMPE set, does it contain GMPEs or GMPE sets?\n            # -----------------------------------------------------------------\n\n            set_of_gmpes = all([s in conf[\"gmpe_modules\"] for s in selected_gmpe_sets])\n            set_of_sets = all([s in conf[\"gmpe_sets\"] for s in selected_gmpe_sets])\n\n            if set_of_sets is True:\n                mgmpes = []\n                for s in selected_gmpe_sets:\n                    mgmpes.append(\n                        cls.__multigmpe_from_gmpe_set__(conf, s, filter_imt=filter_imt)\n                    )\n                out = MultiGMPE.__from_list__(mgmpes, gmpe_set_weights, imc=IMC)\n            elif set_of_gmpes is True:\n                out = cls.__multigmpe_from_gmpe_set__(\n                    conf, selected_gmpe, filter_imt=filter_imt\n                )\n            else:\n                raise TypeError(\n                    \"%s must consist exclusively of keys in \"\n                    \"conf['gmpe_modules'] or conf['gmpe_sets']\" % selected_gmpe\n                )\n        elif selected_gmpe in conf[\"gmpe_modules\"].keys():\n            modinfo = conf[\"gmpe_modules\"][selected_gmpe]\n            # mod = import_module(modinfo[1])\n            # tmpclass = getattr(mod, modinfo[0])\n            # out = MultiGMPE.__from_list__([tmpclass()], [1.0], imc=IMC)\n            out = MultiGMPE.__from_list__(\n                [get_gmpe_from_name(modinfo[0], conf)], [1.0], imc=IMC\n            )\n        else:\n            raise TypeError(\n                \"conf['modeling']['gmpe'] must be a key in \"\n                \"conf['gmpe_modules'] or conf['gmpe_sets']\"\n            )\n\n        out.DESCRIPTION = selected_gmpe\n\n        # ---------------------------------------------------------------------\n        # Deal with GMPE limits\n        # ---------------------------------------------------------------------\n        gmpe_lims = conf[\"gmpe_limits\"]\n\n        # We need to replace the short name in the dictionary key with module\n        # name here since the conf is not available within the MultiGMPE class.\n        mods = conf[\"gmpe_modules\"]\n        mod_keys = mods.keys()\n        new_gmpe_lims = {}\n        for k, v in gmpe_lims.items():\n            if k in mod_keys:\n                new_gmpe_lims[mods[k][0]] = v\n            else:\n                new_gmpe_lims[k] = v\n\n        out.GMPE_LIMITS = new_gmpe_lims\n\n        return out\n\n    def __multigmpe_from_gmpe_set__(conf, set_name, filter_imt=None):\n        \"\"\"\n        Private method for constructing a MultiGMPE from a set_name.\n\n        Args:\n            conf (ConfigObj): A ShakeMap config object.\n            filter_imt (IMT): An optional IMT to filter/reweight the GMPE list.\n            set_name (str): Set name; must correspond to a key in\n                conf['set_name'].\n\n        Returns:\n            MultiGMPE.\n\n        \"\"\"\n        IMC = getattr(const.IMC, conf[\"interp\"][\"component\"])\n\n        selected_gmpes = conf[\"gmpe_sets\"][set_name][\"gmpes\"]\n        selected_gmpe_weights = [\n            float(w) for w in conf[\"gmpe_sets\"][set_name][\"weights\"]\n        ]\n\n        # Check for large distance GMPEs\n        if \"weights_large_dist\" in conf[\"gmpe_sets\"][set_name].keys():\n            if not conf[\"gmpe_sets\"][set_name][\"weights_large_dist\"]:\n                selected_weights_large_dist = None\n            else:\n                selected_weights_large_dist = [\n                    float(w) for w in conf[\"gmpe_sets\"][set_name][\"weights_large_dist\"]\n                ]\n        else:\n            selected_weights_large_dist = None\n\n        if \"dist_cutoff\" in conf[\"gmpe_sets\"][set_name].keys():\n            if np.isnan(conf[\"gmpe_sets\"][set_name][\"dist_cutoff\"]):\n                selected_dist_cutoff = None\n            else:\n                selected_dist_cutoff = float(conf[\"gmpe_sets\"][set_name][\"dist_cutoff\"])\n        else:\n            selected_dist_cutoff = None\n\n        if \"site_gmpes\" in conf[\"gmpe_sets\"][set_name].keys():\n            if not conf[\"gmpe_sets\"][set_name][\"site_gmpes\"]:\n                selected_site_gmpes = None\n            else:\n                selected_site_gmpes = conf[\"gmpe_sets\"][set_name][\"site_gmpes\"]\n        else:\n            selected_site_gmpes = None\n\n        if \"weights_site_gmpes\" in conf[\"gmpe_sets\"][set_name].keys():\n            if not conf[\"gmpe_sets\"][set_name][\"weights_site_gmpes\"]:\n                selected_weights_site_gmpes = None\n            else:\n                selected_weights_site_gmpes = conf[\"gmpe_sets\"][set_name][\n                    \"weights_site_gmpes\"\n                ]\n        else:\n            selected_weights_site_gmpes = None\n\n        # ---------------------------------------------------------------------\n        # Import GMPE modules and initialize classes into list\n        # ---------------------------------------------------------------------\n        gmpes = []\n        for g in selected_gmpes:\n            # This is the old school way of importing the modules; I'm\n            # leaving it in here temporarily just for documentation.\n            # mod = import_module(conf['gmpe_modules'][g][1])\n            # tmpclass = getattr(mod, conf['gmpe_modules'][g][0])\n            # gmpes.append(tmpclass())\n            gmpe_name = conf[\"gmpe_modules\"][g][0]\n            gmpes.append(get_gmpe_from_name(gmpe_name, conf))\n\n        # ---------------------------------------------------------------------\n        # Filter out GMPEs not applicable to this period\n        # ---------------------------------------------------------------------\n        if filter_imt is not None:\n            filtered_gmpes, filtered_wts = filter_gmpe_list(\n                gmpes, selected_gmpe_weights, filter_imt\n            )\n        else:\n            filtered_gmpes, filtered_wts = gmpes, selected_gmpe_weights\n\n        # ---------------------------------------------------------------------\n        # Import site GMPEs\n        # ---------------------------------------------------------------------\n        if selected_site_gmpes is not None:\n            if isinstance(selected_site_gmpes, str):\n                selected_site_gmpes = [selected_site_gmpes]\n            site_gmpes = []\n            for g in selected_site_gmpes:\n                # This is the old school way of importing the modules; I'm\n                # leaving it in here temporarily just for documentation.\n                # mod = import_module(conf['gmpe_modules'][g][1])\n                # tmpclass = getattr(mod, conf['gmpe_modules'][g][0])\n                # site_gmpes.append(tmpclass())\n                gmpe_name = conf[\"gmpe_modules\"][g][0]\n                site_gmpes.append(get_gmpe_from_name(gmpe_name, conf))\n        else:\n            site_gmpes = None\n\n        # ---------------------------------------------------------------------\n        # Filter out site GMPEs not applicable to this period\n        # ---------------------------------------------------------------------\n        if site_gmpes is not None:\n            if filter_imt is not None:\n                filtered_site_gmpes, filtered_site_wts = filter_gmpe_list(\n                    site_gmpes, selected_weights_site_gmpes, filter_imt\n                )\n            else:\n                filtered_site_gmpes = copy.copy(site_gmpes)\n                filtered_site_wts = copy.copy(selected_weights_site_gmpes)\n        else:\n            filtered_site_gmpes = None\n            filtered_site_wts = None\n\n        # ---------------------------------------------------------------------\n        # Construct MultiGMPE\n        # ---------------------------------------------------------------------\n        logging.debug(f\"    filtered_gmpes: {filtered_gmpes}\")\n        logging.debug(f\"    filtered_wts: {filtered_wts}\")\n\n        mgmpe = MultiGMPE.__from_list__(\n            filtered_gmpes,\n            filtered_wts,\n            default_gmpes_for_site=filtered_site_gmpes,\n            default_gmpes_for_site_weights=filtered_site_wts,\n            imc=IMC,\n        )\n\n        # ---------------------------------------------------------------------\n        # Append large-distance info if specified\n        # ---------------------------------------------------------------------\n        if selected_dist_cutoff is not None:\n            if filter_imt is not None:\n                filtered_gmpes_ld, filtered_wts_ld = filter_gmpe_list(\n                    gmpes, selected_weights_large_dist, filter_imt\n                )\n            else:\n                filtered_wts_ld = copy.copy(selected_weights_large_dist)\n\n            mgmpe.CUTOFF_DISTANCE = copy.copy(selected_dist_cutoff)\n            mgmpe.WEIGHTS_LARGE_DISTANCE = copy.copy(filtered_wts_ld)\n\n        mgmpe.DESCRIPTION = set_name\n\n        return mgmpe\n\n    @classmethod\n    def __from_list__(\n        cls,\n        gmpes,\n        weights,\n        imc=const.IMC.GREATER_OF_TWO_HORIZONTAL,\n        default_gmpes_for_site=None,\n        default_gmpes_for_site_weights=None,\n        reference_vs30=760,\n    ):\n        \"\"\"\n        Construct a MultiGMPE instance from lists of GMPEs and weights.\n\n        Args:\n            gmpes (list): List of OpenQuake\n                `GMPE <http://docs.openquake.org/oq-hazardlib/master/gsim/index.html#built-in-gsims>`__\n                instances.\n\n            weights (list): List of weights; must sum to 1.0.\n\n            imc: Requested intensity measure component. Must be one listed\n                `here <http://docs.openquake.org/oq-hazardlib/master/const.html?highlight=imc#openquake.hazardlib.const.IMC>`__.\n                The amplitudes returned by the GMPEs will be converted to this\n                IMT. Default is 'GREATER_OF_TWO_HORIZONTAL', which is used by\n                ShakeMap. See discussion in\n                `this section <http://usgs.github.io/shakemap/tg_choice_of_parameters.html#use-of-peak-values-rather-than-mean>`__\n                of the ShakeMap manual.\n\n            default_gmpes_for_site (list):\n                Optional list of OpenQuake GMPE instance to use as a site term\n                for any of the GMPEs that do not have a site term.\n\n                Notes:\n\n                    * We do not check for consistency in the reference rock\n                      defintion, so the user nees to be aware of this issue and\n                      holds responsibiilty for ensuring compatibility.\n                    * We check whether or not a GMPE has a site term by c\n                      hecking the REQUIRES_SITES_PARAMETERS slot for vs30.\n\n            default_gmpes_for_site_weights: Weights for default_gmpes_for_site.\n                Must sum to one and be same length as default_gmpes_for_site.\n                If None, then weights are set to be equal.\n\n            reference_vs30:\n                Reference rock Vs30 in m/s. We do not check that this matches\n                the reference rock in the GMPEs so this is the responsibility\n                of the user.\n\n        \"\"\"  # noqa\n\n        # ---------------------------------------------------------------------\n        # Check that GMPE weights sum to 1.0:\n        # ---------------------------------------------------------------------\n\n        if np.abs(np.sum(weights) - 1.0) > 1e-7:\n            raise Exception(\"Weights must sum to one.\")\n\n        # ---------------------------------------------------------------------\n        # Check that length of GMPE weights equals length of gmpe list\n        # ---------------------------------------------------------------------\n\n        if len(weights) != len(gmpes):\n            raise Exception(\"Length of weights must match length of GMPE list.\")\n\n        # ---------------------------------------------------------------------\n        # Check that gmpes is a list of OQ GMPE instances\n        # ---------------------------------------------------------------------\n\n        for g in gmpes:\n            if not isinstance(g, GMPE):\n                raise Exception(f'\"{g}\" is a {type(g)} not a GMPE instance.')\n\n        self = cls()\n        self.GMPES = gmpes\n        self.WEIGHTS = weights\n\n        # ---------------------------------------------------------------------\n        # Combine the intensity measure types. This is problematic:\n        #   - Logically, we should only include the intersection of the sets\n        #     of imts for the different GMPEs.\n        #   - In practice, this is not feasible because most GMPEs in CEUS and\n        #     subduction zones do not have PGV.\n        #   - So instead we will use the union of the imts and then convert\n        #     to get the missing imts later in get_mean_and_stddevs.\n        # ---------------------------------------------------------------------\n\n        imts = [set(g.DEFINED_FOR_INTENSITY_MEASURE_TYPES) for g in gmpes]\n        self.DEFINED_FOR_INTENSITY_MEASURE_TYPES = set.union(*imts)\n\n        # ---------------------------------------------------------------------\n        # For VirtualIPE class, we also want to know if ALL of the GMPEs are\n        # defined for PGV, in which case we will convert from PGV to MI,\n        # otherwise use PGA or Sa.\n        # ---------------------------------------------------------------------\n        haspgv = [PGV in set(g.DEFINED_FOR_INTENSITY_MEASURE_TYPES) for g in gmpes]\n        self.ALL_GMPES_HAVE_PGV = all(haspgv)\n\n        # ---------------------------------------------------------------------\n        # Store intensity measure types for conversion in get_mean_and_stddevs.\n        # ---------------------------------------------------------------------\n        self.IMCs = [g.DEFINED_FOR_INTENSITY_MEASURE_COMPONENT for g in gmpes]\n\n        # ---------------------------------------------------------------------\n        # Store the component\n        # ---------------------------------------------------------------------\n        self.DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = imc\n\n        # ---------------------------------------------------------------------\n        # Intersection of GMPE standard deviation types\n        # ---------------------------------------------------------------------\n        stdlist = [set(g.DEFINED_FOR_STANDARD_DEVIATION_TYPES) for g in gmpes]\n        self.DEFINED_FOR_STANDARD_DEVIATION_TYPES = set.intersection(*stdlist)\n\n        # ---------------------------------------------------------------------\n        # Need union of site parameters, but it is complicated by the\n        # different depth parameter flavors.\n        # ---------------------------------------------------------------------\n        sitepars = [set(g.REQUIRES_SITES_PARAMETERS) for g in gmpes]\n        self.REQUIRES_SITES_PARAMETERS = set.union(*sitepars)\n\n        # ---------------------------------------------------------------------\n        # Construct a list of whether or not each GMPE has a site term\n        # ---------------------------------------------------------------------\n        self.HAS_SITE = [\"vs30\" in g.REQUIRES_SITES_PARAMETERS for g in gmpes]\n\n        # ---------------------------------------------------------------------\n        # Checks and sort out defaults\n        # ---------------------------------------------------------------------\n\n        # things to check if default_gmpes_for_site is provided\n        if default_gmpes_for_site is not None:\n            # check that default_gmpe_for_site are OQ GMPEs or None\n            for g in default_gmpes_for_site:\n                if not isinstance(g, GMPE):\n                    raise Exception(f'\"{g}\" is not a GMPE instance.')\n\n            # apply default weights if necessary\n            if default_gmpes_for_site_weights is None:\n                n = len(default_gmpes_for_site)\n                default_gmpes_for_site_weights = [1 / n] * n\n\n        # Things to check if one or more GMPE does not have a site term\n        if not all(self.HAS_SITE):\n            # Raise an exception if no default site is provided\n            if default_gmpes_for_site is None:\n                raise Exception(\n                    \"Must provide default_gmpes_for_site if one or\"\n                    \" more GMPE does not have site term.\"\n                )\n\n            # If weights are unspecified, use equal weight\n            if default_gmpes_for_site_weights is None:\n                default_gmpes_for_site_weights = [\n                    1 / len(default_gmpes_for_site)\n                ] * len(default_gmpes_for_site)\n\n            # check that length of default_gmpe_for_site matches length of\n            # default_gmpe_for_site_weights\n            if len(default_gmpes_for_site_weights) != len(default_gmpes_for_site):\n                raise Exception(\n                    \"Length of default_gmpes_for_site_weights \"\n                    \"must match length of default_gmpes_for_site \"\n                    \"list.\"\n                )\n\n            # check weights sum to one if needed\n            if not all(self.HAS_SITE):\n                if np.sum(default_gmpes_for_site_weights) != 1.0:\n                    raise Exception(\n                        \"default_gmpes_for_site_weights must sum\" \" to one.\"\n                    )\n\n        # Note: if ALL of the GMPEs do not have a site term (requiring Vs30),\n        #       then REQUIRES_SITES_PARAMETERS for the MultiGMPE will not\n        #       include Vs30 even though it will be needed to compute the\n        #       default site term. So if the site checks have passed to this\n        #       point, we should add Vs30 to the set of required site pars:\n        self.REQUIRES_SITES_PARAMETERS = set.union(\n            set(self.REQUIRES_SITES_PARAMETERS), set([\"vs30\"])\n        )\n\n        self.DEFAULT_GMPES_FOR_SITE = default_gmpes_for_site\n        self.DEFAULT_GMPES_FOR_SITE_WEIGHTS = default_gmpes_for_site_weights\n        self.REFERENCE_VS30 = reference_vs30\n\n        # ---------------------------------------------------------------------\n        # Union of rupture parameters\n        # ---------------------------------------------------------------------\n        ruppars = [set(g.REQUIRES_RUPTURE_PARAMETERS) for g in gmpes]\n        self.REQUIRES_RUPTURE_PARAMETERS = set.union(*ruppars)\n\n        # ---------------------------------------------------------------------\n        # Union of distance parameters\n        # ---------------------------------------------------------------------\n        distpars = [set(g.REQUIRES_DISTANCES) for g in gmpes]\n        self.REQUIRES_DISTANCES = set.union(*distpars)\n\n        return self\n\n    def __get_site_factors__(self, sites, rup, dists, imt, default=False):\n        \"\"\"\n        Method for computing site amplification factors from the defalut GMPE\n        to be applied to GMPEs which do not have a site term.\n\n        **NOTE** Amps are calculated in natural log units and so the ln(amp)\n        is returned.\n\n        Args:\n            sites (SitesContext): Instance of SitesContext.\n            rup (RuptureContext): Instance of RuptureContext.\n            dists (DistancesContext): Instance of DistancesContext.\n            imt: An instance openquake.hazardlib.imt.\n            default (bool): Boolean of whether or not to return the\n                amplificaiton factors for the gmpes or default_gmpes_for_site.\n                This argument is primarily only intended to be used internally\n                for when we just need to access the default amplifications to\n                apply to those GMPEs that do not have site terms.\n\n        Returns:\n            Site amplifications in natural log units.\n        \"\"\"\n\n        # ---------------------------------------------------------------------\n        # Make reference sites context\n        # ---------------------------------------------------------------------\n\n        ref_sites = copy.deepcopy(sites)\n        ref_sites.vs30 = np.full_like(sites.vs30, self.REFERENCE_VS30)\n        # TODO: Should we reset the Sites depth parameters here? Probably.\n\n        # ---------------------------------------------------------------------\n        # If default True, construct new MultiGMPE with default GMPE/weights\n        # ---------------------------------------------------------------------\n        if default is True:\n            tmp = MultiGMPE.__from_list__(\n                self.DEFAULT_GMPES_FOR_SITE,\n                self.DEFAULT_GMPES_FOR_SITE_WEIGHTS,\n                self.DEFINED_FOR_INTENSITY_MEASURE_COMPONENT,\n            )\n\n        # ---------------------------------------------------------------------\n        # If default False, just use self\n        # ---------------------------------------------------------------------\n        else:\n            tmp = self\n\n        lmean, lsd = tmp.get_mean_and_stddevs(\n            sites, rup, dists, imt, list(tmp.DEFINED_FOR_STANDARD_DEVIATION_TYPES)\n        )\n        lmean_ref, lsd = tmp.get_mean_and_stddevs(\n            ref_sites, rup, dists, imt, list(tmp.DEFINED_FOR_STANDARD_DEVIATION_TYPES)\n        )\n\n        lamps = lmean - lmean_ref\n\n        return lamps\n\n    def __describe__(self):\n        \"\"\"\n        Construct a dictionary that describes the MultiGMPE.\n\n        Note: For simplicity, this method ignores issues related to\n        GMPEs used for the site term and changes in the GMPE with\n        distance. For this level of detail, please see the config files.\n\n        Returns:\n            A dictionary representation of the MultiGMPE.\n        \"\"\"\n        gmpe_dict = {\"gmpes\": [], \"weights\": [], \"name\": self.DESCRIPTION}\n\n        for i in range(len(self.GMPES)):\n            gmpe_dict[\"weights\"].append(self.WEIGHTS[i])\n            if isinstance(self.GMPES[i], MultiGMPE):\n                gmpe_dict[\"gmpes\"].append(self.GMPES[i].__describe__())\n            else:\n                gmpe_dict[\"gmpes\"].append(str(self.GMPES[i]))\n\n        return gmpe_dict\n\n    def __inflatePSSigma__(\n        self, gmpe, lmean, lsd, sites, rup, dists, imt, stddev_types\n    ):\n        \"\"\"\n        If the point-source to finite-fault factors are used, we need to\n        inflate the intra-event and total standard deviations. We do this\n        by standard propagation of error techniques: taking the (numerical)\n        derivative of the GMPE (as a function of distance) squared times the\n        additional variance from the conversion, added\n        to the variance of the GMPE (then taking the square root). We do\n        this separately for each of Rrup and Rjb and sum the results.\n        If Rrup and Rjb are calculated from a finite rupture model, their\n        variance arrays will be \"None\" and lsd will remain unchanged.\n        Otherwise the error inflation will be applied. Normally one or the\n        other of Rrup/Rjb will not be used and so that term will be zero; in\n        some cases both may be used and both may result in non-zero\n        derivatives.\n\n        Args:\n            gmpe:\n                The GMPE to use for the calculations. Must be a base GMPE and\n                not a GMPE set, otherwise no action is taken.\n            lmean:\n                The mean values returned by the \"normal\" evaluation of the\n                GMPE.\n            lsd:\n                The standard deviations returned by the \"normal\" evaluation\n                of the GMPE.\n            sites:\n                The sites context required by the GMPE.\n            rup:\n                The rupture context required by the GMPE.\n            dists:\n                The distance context required by the GMPE.\n            imt:\n                The intensity measure type being evaluated.\n            stddev_types:\n                The list of stddev types found in lsd.\n\n        Returns:\n            list: A list of arrays of inflated standard deviations\n            corresponding to the elements of lsd.\n        \"\"\"\n        new_sd = []\n        delta_distance = 0.01\n        delta_var = [0, 0]\n        for i, dtype in enumerate((\"rrup\", \"rjb\")):\n            # Skip dtype if the gmpe does not require it\n            if dtype not in gmpe.REQUIRES_DISTANCES:\n                continue\n            # Skip dtype if it has not been subject to a point-source to\n            # finite rupture conversion\n            dvar = getattr(dists, dtype + \"_var\", None)\n            if dvar is None:\n                continue\n            # Add a small amound to the rupture distance (rrup or rjb)\n            # and re-evaluate the GMPE\n            rup_dist = getattr(dists, dtype)\n            rup_dist += delta_distance\n            ctx = stuff_context(sites, rup, dists)\n            tmean, tsd = gmpe.get_mean_and_stddevs(ctx, ctx, ctx, imt, stddev_types)\n            # Find the derivative w.r.t. the rupture distance\n            dm_dr = (lmean - tmean) / delta_distance\n            # The additional variance is (dm/dr)^2 * dvar\n            delta_var[i] = dm_dr ** 2 * dvar\n            # Put the rupture distance back to what it was\n            rup_dist -= delta_distance\n        for i, stdtype in enumerate(stddev_types):\n            if stdtype == const.StdDev.INTER_EVENT:\n                new_sd.append(lsd[i].copy())\n                continue\n            new_sd.append(np.sqrt(lsd[i] ** 2 + delta_var[0] + delta_var[1]))\n        return new_sd\n\n\ndef filter_gmpe_list(gmpes, wts, imt):\n    \"\"\"\n    Method to remove GMPEs from the GMPE list that are not applicable\n    to a specific IMT. Rescales the weights to sum to one.\n\n    Args:\n        gmpes (list): List of GMPE instances.\n        wts (list): List of floats indicating the weight of the GMPEs.\n        imt (IMT): OQ IMT to filter GMPE list for.\n\n    Returns:\n        tuple: List of GMPE instances and list of weights.\n\n    \"\"\"\n    if wts is None:\n        n = len(gmpes)\n        wts = [1 / n] * n\n\n    per_max = [np.max(get_gmpe_sa_periods(g)) for g in gmpes]\n    per_min = [np.min(get_gmpe_sa_periods(g)) for g in gmpes]\n    if imt == PGA():\n        sgmpe = [g for g in gmpes if PGA in g.DEFINED_FOR_INTENSITY_MEASURE_TYPES]\n        swts = [\n            w\n            for g, w in zip(gmpes, wts)\n            if PGA in g.DEFINED_FOR_INTENSITY_MEASURE_TYPES\n        ]\n    elif imt == PGV():\n        sgmpe = []\n        swts = []\n        for i in range(len(gmpes)):\n            if (PGV in gmpes[i].DEFINED_FOR_INTENSITY_MEASURE_TYPES) or (\n                per_max[i] >= 1.0 and per_min[i] <= 1.0\n            ):\n                sgmpe.append(gmpes[i])\n                swts.append(wts[i])\n    else:\n        per = imt.period\n        sgmpe = []\n        swts = []\n        for i in range(len(gmpes)):\n            if per_max[i] >= per and per_min[i] <= per:\n                sgmpe.append(gmpes[i])\n                swts.append(wts[i])\n\n    if len(sgmpe) == 0:\n        raise KeyError(f\"No applicable GMPEs from GMPE list for {str(imt)}\")\n\n    # Scale weights to sum to one\n    swts = np.array(swts)\n    swts = swts / np.sum(swts)\n\n    return sgmpe, swts\n\n\ndef get_gmpe_sa_periods(gmpe):\n    \"\"\"\n    Method to extract the SA periods defined by a GMPE.\n\n    Args:\n        gmpe (GMPE): A GMPE instance.\n\n    Retunrs:\n        list: List of periods.\n\n    \"\"\"\n    if gmpe == \"[NGAEast]\":\n        per = gmpe.per_array\n    else:\n        ctab = get_gmpe_coef_table(gmpe).sa_coeffs\n        ilist = list(ctab.keys())\n        per = [i.period for i in ilist]\n    return per\n\n\ndef get_gmpe_coef_table(gmpe):\n    \"\"\"\n    Method for finding the (or \"a\") GMPE table.\n\n    Notes:\n\n      *  The reason for the complexity here is that there can be multiple\n         coefficient tables, and some of them may not have the sa_coeffs\n         attribute, which is the main reason for getting the table.\n      *  We are also assuming that if there are more than one  coefficient\n         table, the range of periods will be the same across all of the\n         tables.\n\n    Args:\n        gmpe (GMPE): An OQ GMPE instance.\n\n    Returns:\n        The associated coefficient table.\n\n    \"\"\"\n    stuff = gmpe.__dir__()\n    coef_list = [s for s in stuff if \"COEFFS\" in s]\n    for coef_sel in coef_list:\n        cobj = getattr(gmpe, coef_sel)\n        if \"sa_coeffs\" in cobj.__dir__():\n            return cobj\n    raise Exception(f\"GMPE {gmpe} does not contain sa_coeffs attribute.\")\n", "meta": {"hexsha": "762cef124abb3a7b35920576da3f8cbbbe0513f8", "size": 46815, "ext": "py", "lang": "Python", "max_stars_repo_path": "shakelib/multigmpe.py", "max_stars_repo_name": "cbworden/shakemap", "max_stars_repo_head_hexsha": "a0130bf03645cc635d48606560309bf65310506a", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "shakelib/multigmpe.py", "max_issues_repo_name": "cbworden/shakemap", "max_issues_repo_head_hexsha": "a0130bf03645cc635d48606560309bf65310506a", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shakelib/multigmpe.py", "max_forks_repo_name": "cbworden/shakemap", "max_forks_repo_head_hexsha": "a0130bf03645cc635d48606560309bf65310506a", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4048913043, "max_line_length": 177, "alphanum_fraction": 0.5141087258, "include": true, "reason": "import numpy", "num_tokens": 10222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3208213008246071, "lm_q1q2_score": 0.16416958677474158}}
{"text": "#!/usr/bin/env python3\nimport os\nimport sys\nimport argparse\nimport logging\nfrom astropy.io.registry import identify_format\n\nimport numpy as np\nfrom astropy.io import ascii, fits\nfrom astropy.io.votable import parse_single_table\nfrom astropy.table import Table\nfrom astropy.coordinates import Angle, SkyCoord\nfrom astropy.wcs import WCS\nfrom astropy.time import Time\nimport astropy.units as u\nfrom mskpy.photometry import airmass_app\n\nparser = argparse.ArgumentParser(\n    'lmi-standard-phot.py',\n    description='Extract standard stars from LMI photometry catalogs.',\n    epilog='Use after lmi-add-cat.py.')\n\nparser.add_argument('files', nargs='+', help='files to search for photometry')\nparser.add_argument('--catalogs', default=os.path.expanduser('~/data/catalogs'),\n                    help='directory holding the catalog files.')\nparser.add_argument('--dmax', type=u.Quantity, default='2 arcsec',\n                    help='maximum distance for catalog matches')\nparser.add_argument('--keep-all', action='store_true',\n                    help='when there are multiple matches, save all measurements, otherwise only save the brightest')\nparser.add_argument('--logfile', default='lmi-standard-phot.log')\nparser.add_argument('-o', default='standard-phot.txt',\n                    help='output file name')\nparser.add_argument('-f', action='store_true',\n                    help='force overwrite of output file')\n\nargs = parser.parse_args()\n\nif os.path.exists(args.o) and not args.f:\n    raise SystemExit('Refusing to overwrite output file.')\n\nHB_FILTERS = ['OH', 'NH', 'UC', 'CN', 'C3', 'CO+', 'BC',\n              'C2', 'GC', 'H2O+', 'RC']\nelevation = 2380 * u.m  # DCT elevation\n\n\ndef setup_logging(logfile):\n    logger = logging.Logger('lmi-standard-phot.py')\n    logger.setLevel(logging.DEBUG)\n\n    # This test allows logging to work when it is run multiple times\n    # from ipython\n    if len(logger.handlers) == 0:\n        formatter = logging.Formatter('%(levelname)s: %(message)s')\n\n        console = logging.StreamHandler(sys.stdout)\n        console.setLevel(logging.DEBUG)\n        console.setFormatter(formatter)\n        logger.addHandler(console)\n\n        logfile = logging.FileHandler(logfile)\n        logfile.setLevel(logging.INFO)\n        logfile.setFormatter(formatter)\n        logger.addHandler(logfile)\n\n    logger.info('#' * 70)\n    logger.info(Time.now().iso + 'Z')\n    logger.info('Command line: ' + ' '.join(sys.argv[1:]))\n    for handler in logger.handlers:\n        if hasattr(handler, 'baseFilename'):\n            logger.info('Logging to ' + handler.baseFilename)\n\n    return logger\n\n\ndef landolt09():\n    table = (parse_single_table(args.catalogs + \"/landolt09-sources.xml\")\n             .to_table(use_names_over_ids=True))\n    cat = dict()\n    cat['names'] = table['Star'].data.data.astype(str)\n    ra = Angle((table['RAh'].data, table['RAm'].data, table['RAs'].data),\n               unit=u.hourangle)\n    dec = Angle((table['DEd'].data, table['DEm'].data, table['DEs'].data),\n                unit=u.deg)\n    dec[table['DE-'].data == b'-'] *= -1\n    cat['coords'] = SkyCoord(ra, dec)\n    cat['V'] = table['Vmag'].data.data\n    cat['R'] = table['Vmag'].data.data - table['V-R'].data.data\n    cat['R_err'] = np.sqrt(table['e_Vmag'].data.data**2\n                           + table['e_V-R'].data.data**2)\n    cat['color'] = table['V-R'].data.data\n    cat['color_err'] = table['e_V-R'].data.data\n    return cat\n\n\ndef smith02():\n    table = (parse_single_table(\"/home/msk/data/catalogs/smith02-standards.xml\")\n             .to_table(use_names_over_ids=True))\n    cat = dict()\n    cat['names'] = table['Name'].data.data.astype(str)\n    ra = [s for s in table['RAJ2000']]\n    dec = [s for s in table['DEJ2000']]\n    cat['coords'] = SkyCoord(ra, dec, unit=[u.hourangle, u.deg])\n    cat['SDSS-R'] = table[\"r'mag\"].data.data\n    cat['SDSS-R_err'] = table[\"e_r'mag\"].data.data\n    cat['color'] = table[\"g'-r'\"].data.data\n    cat['color_err'] = table[\"e_g'-r'\"].data.data\n    cat['SDSS-G'] = table[\"r'mag\"].data.data + cat['color']\n    cat['SDSS-G_err'] = np.sqrt(\n        table[\"e_r'mag\"].data.data**2 + cat['color_err']**2)\n    return cat\n\n\ndef farnham00():\n    table = ascii.read('/home/msk/data/catalogs/hb-standards.txt')\n    cat = dict()\n    cat['names'] = ['HD {}'.format(n) for n in table['HD']]\n    cat['coords'] = SkyCoord(table['RA'], table['Dec'],\n                             unit=[u.hourangle, u.deg])\n    for filt in HB_FILTERS:\n        cat[filt] = table[filt].data.data\n        cat[filt + '_err'] = np.repeat(0.01, len(table))\n    cat['color'] = table['B-V'].data.data\n    cat['color_err'] = np.repeat(0.01, len(table))\n    return cat\n\n\nlogger = setup_logging(args.logfile)\n\ncatalogs = {\n    'Farnham et al. 2000': farnham00(),\n    'Landolt 2009': landolt09(),\n    'Smith et al 2002': smith02()\n}\n\ncolumns = ['file', 'catalog', 'object', 'date', 'za', 'airmass', 'filter',\n           'color', 'dist', 'm', 'm_err', 'm_inst', 'm_inst_err']\nformats = {\n    'airmass': '{:.4f}',\n    'color': '{:.4f}',\n    'dist': '{:3f}',\n    'm': '{:.4f}',\n    'm_err': '{:.4f}',\n    'm_inst': '{:.4f}',\n    'm_inst_err': '{:.4f}'\n}\n\nrows = []\nfor f in sorted(args.files):\n    with fits.open(f, mode='readonly') as hdu:\n        h = hdu[0].header\n        if h['OBSTYPE'] != 'OBJECT':\n            logger.info(f + ': wrong OBSTYPE')\n            continue\n\n        if 'CAT' not in hdu:\n            logger.info(f + ': missing photometry catalog')\n            continue\n\n        date = h['DATE-OBS'].replace('T', ' ')\n        za = h['ZA']\n        am = airmass_app(h['ZA'] * u.deg, elevation)\n        filt = h['filters']\n        exptime = h['exptime']\n\n        phot = Table(hdu['CAT'].data)\n        phot = phot[phot['krflux'] > 0]  # clean out bad data\n        w = WCS(hdu[0])\n        radec = np.array(w.pixel_to_world_values(\n            list(zip(phot['x'], phot['y']))))\n        coords = SkyCoord(*radec.T, unit='deg')\n        m = -2.5 * np.log10(phot['krflux'] / exptime)\n        merr = 1.0857 * phot['krfluxerr'] / phot['krflux']\n\n        n = 0\n        for name, cat in catalogs.items():\n            if filt not in cat:\n                continue\n            indices, dist, d3 = coords.match_to_catalog_sky(cat['coords'])\n            i = dist < args.dmax\n            indices, dist, d3 = indices[i], dist[i], d3[i]\n            for i in set(indices):\n                n += 1\n                matches = np.flatnonzero((indices == i))\n                brightest = matches[m[matches].argmin()]\n                for j in matches:\n                    if not args.keep_all and j != brightest:\n                        continue\n                    rows.append((f, name, cat['names'][i], date, za,\n                                 am, filt, cat['color'][i], dist[j].arcsec,\n                                 cat[filt][i], cat[filt + '_err'][i],\n                                 m[j], merr[j]))\n\n        logger.info('{}: {} standards found'.format(f, n))\n\nif len(rows) == 0:\n    logger.info('No standards found in any file.')\nelse:\n    tab = Table(rows=rows, names=columns)\n    tab.meta['comments'] = [Time.now().iso]\n    for c, f in formats.items():\n        tab[c].format = f\n\n    tab.write(args.o, format='ascii.fixed_width_two_line', overwrite=args.f)\n", "meta": {"hexsha": "8781a3347ac3eea82e9bcabe994214a1af2fb237", "size": 7238, "ext": "py", "lang": "Python", "max_stars_repo_path": "bin/lmi-standard-phot.py", "max_stars_repo_name": "mkelley/dct-redux", "max_stars_repo_head_hexsha": "935dbf49d77d0856fe55991bd1eeadc3a2ee8291", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bin/lmi-standard-phot.py", "max_issues_repo_name": "mkelley/dct-redux", "max_issues_repo_head_hexsha": "935dbf49d77d0856fe55991bd1eeadc3a2ee8291", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bin/lmi-standard-phot.py", "max_forks_repo_name": "mkelley/dct-redux", "max_forks_repo_head_hexsha": "935dbf49d77d0856fe55991bd1eeadc3a2ee8291", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4803921569, "max_line_length": 117, "alphanum_fraction": 0.5794418348, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 1928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3208212943308302, "lm_q1q2_score": 0.1641695834517681}}
{"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 23 08:46:02 2017\n@author: mschull\n\"\"\"\n\n# This file is part of PyDisALEXI for running disALEXI using different TSEB models\n# Copyright 2016 Mitchell Schull and contributors listed in the README.md file.\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\nimport os\nimport numpy as np\nimport subprocess\nfrom osgeo import gdal\nfrom osgeo.gdalconst import GA_ReadOnly\nimport pandas as pd\nfrom .TSEB_usda import TSEB_PT_usda\nfrom .utils import writeArray2Tiff, getParFromExcel, warp, folders\nfrom scipy import ndimage, interp\nfrom .landsatTools import landsat_metadata, GeoTIFF\nfrom .TSEB_utils_usda import sunset_sunrise, interp_ta\n# from joblib import Parallel, delayed\nfrom astropy.convolution import Gaussian2DKernel, Box2DKernel\nfrom astropy.convolution import convolve_fft\nfrom joblib import Memory\n\ncachedir = os.path.join(os.getcwd(), 'cachedir')\nif not os.path.exists(cachedir):\n    os.mkdir(cachedir)\n\nmemory = Memory(cachedir, verbose=0)\n\n\ndef _DisALEXI_PT(ET_ALEXI,\n                 Rs_1,\n                 Rs24in,\n                 Tr_K,\n                 Ta,\n                 vza,\n                 u,\n                 p,\n                 zs,\n                 aleafv,\n                 aleafn,\n                 aleafl,\n                 adeadv,\n                 adeadn,\n                 adeadl,\n                 albedo,\n                 ndvi,\n                 LAI,\n                 clump,\n                 hc,\n                 mask,\n                 time,\n                 t_rise,\n                 t_end,\n                 leaf_width=1.,\n                 alpha_PT=1.32):\n    '''DisALEXI based on Priestley-Taylor TSEB\n    \n        Calculates the Priestley Taylor TSEB fluxes using a single observation of\n        composite radiometric temperature and using resistances in series.\n    \n        Parameters\n        ----------\n        ET_ALEXI : float\n            Coarse resolution daily ET from ALEXI\n        geoDict : dictionary\n            Dictionary containing:\n            inProj4 : proj4 string\n                ALEXI ET proj4 string\n            outProj4 : proj4 string\n                DisALEXI ET proj4 string\n            inUL : float array\n                Upper left lat/lon coordinates of ALEXI image\n            inRes : float array\n                ALEXI ET lat/lon resolution\n        Rs_1 : float\n            Overpass insolation (w m-2)\n        Rs24 : float\n            Total daily insolation (w m-2)\n        Tr_K : float\n            Radiometric composite temperature (Kelvin).\n        vza : float\n            View Zenith Angle (degrees).\n        u : float\n            Wind speed above the canopy (m s-1).\n        ea : float\n            Water vapour pressure above the canopy (mb).\n        p : float\n            Atmospheric pressure (mb), use 1013 mb by default.\n        Sn_C : float\n            Canopy net shortwave radiation (W m-2).\n        Sn_S : float\n            Soil net shortwave radiation (W m-2).\n        LAI : float\n            Effective Leaf Area Index (m2 m-2).\n        hc : float\n            Canopy height (m).\n        emis_C : float\n            Leaf emissivity.\n        emis_S : flaot\n            Soil emissivity.\n        z_0M : float\n            Aerodynamic surface roughness length for momentum transfer (m).\n        d_0 : float\n            Zero-plane displacement height (m).\n        z_u : float\n            Height of measurement of windspeed (m).\n        z_T : float\n            Height of measurement of air temperature (m).\n        leaf_width : float, optional\n            average/effective leaf width (m).\n        z0_soil : float, optional\n            bare soil aerodynamic roughness length (m).\n        alpha_PT : float, optional\n            Priestley Taylor coeffient for canopy potential transpiration,\n            use 1.26 by default.\n        x_LAD : float, optional\n            Campbell 1990 leaf inclination distribution function chi parameter.\n        f_c : float, optional\n            Fractional cover.\n        f_g : float, optional\n            Fraction of vegetation that is green.\n        w_C : float, optional\n            Canopy width to height ratio.\n        resistance_form : int, optional\n            Flag to determine which Resistances R_x, R_S model to use.\n    \n                * 0 [Default] Norman et al 1995 and Kustas et al 1999.\n                * 1 : Choudhury and Monteith 1988.\n                * 2 : McNaughton and Van der Hurk 1995.\n    \n        calcG_params : list[list,float or array], optional\n            Method to calculate soil heat flux,parameters.\n    \n                * [[1],G_ratio]: default, estimate G as a ratio of Rn_S, default Gratio=0.35.\n                * [[0],G_constant] : Use a constant G, usually use 0 to ignore the computation of G.\n                * [[2,Amplitude,phase_shift,shape],time] : estimate G from Santanello and Friedl with G_param list of parameters (see :func:`~TSEB.calc_G_time_diff`).\n        UseL : float or None, optional\n            If included, its value will be used to force the Moning-Obukhov stability length.\n    \n        Returns\n        -------\n        flag : int\n            Quality flag, see Appendix for description.\n        T_S : float\n            Soil temperature  (Kelvin).\n        T_C : float\n            Canopy temperature  (Kelvin).\n        T_AC : float\n            Air temperature at the canopy interface (Kelvin).\n        L_nS : float\n            Soil net longwave radiation (W m-2)\n        L_nC : float\n            Canopy net longwave radiation (W m-2)\n        LE_C : float\n            Canopy latent heat flux (W m-2).\n        H_C : float\n            Canopy sensible heat flux (W m-2).\n        LE_S : float\n            Soil latent heat flux (W m-2).\n        H_S : float\n            Soil sensible heat flux (W m-2).\n        G : float\n            Soil heat flux (W m-2).\n        R_S : float\n            Soil aerodynamic resistance to heat transport (s m-1).\n        R_x : float\n            Bulk canopy aerodynamic resistance to heat transport (s m-1).\n        R_A : float\n            Aerodynamic resistance to heat transport (s m-1).\n        u_friction : float\n            Friction velocity (m s-1).\n        L : float\n            Monin-Obuhkov length (m).\n        n_iterations : int\n            number of iterations until convergence of L.\n    \n        References\n        ----------\n        .. [Norman1995] J.M. Norman, W.P. Kustas, K.S. Humes, Source approach for estimating\n            soil and vegetation energy fluxes in observations of directional radiometric\n            surface temperature, Agricultural and Forest Meteorology, Volume 77, Issues 3-4,\n            Pages 263-293,\n            http://dx.doi.org/10.1016/0168-1923(95)02265-Y.\n        .. [Kustas1999] William P Kustas, John M Norman, Evaluation of soil and vegetation heat\n            flux predictions using a simple two-source model with radiometric temperatures for\n            partial canopy cover, Agricultural and Forest Meteorology, Volume 94, Issue 1,\n            Pages 13-29,\n            http://dx.doi.org/10.1016/S0168-1923(99)00005-2.\n        '''\n\n    # Set up input parameters\n    MatXsize = 7\n    Tr_Kresize = np.tile(np.array(np.resize(Tr_K, [np.size(Tr_K), 1])), (1, MatXsize))\n    vzaresize = np.tile(np.resize(vza, [np.size(vza), 1]), (1, MatXsize))\n    #        T_A_Kresize = np.tile(range(270,340,10),(np.size(vza),1))\n    Tr_ADD = np.tile(np.transpose(range(0, 20, 3)), [np.size(hc), 1])\n    #        Tr_Kcol = np.resize(Tr_K,[np.size(Tr_K),1])\n    Tr_Kcol = np.resize(Ta, [np.size(Ta), 1])\n    T_A_Kresize = Tr_Kcol + Tr_ADD\n    uresize = np.tile(np.resize(u, [np.size(u), 1]), (1, MatXsize))\n    presize = np.tile(np.resize(p, [np.size(p), 1]), (1, MatXsize))\n    Rs_1resize = np.tile(np.resize(Rs_1, [np.size(Rs_1), 1]), (1, MatXsize))\n    zsresize = np.tile(np.resize(zs, [np.size(zs), 1]), (1, MatXsize))\n    aleafvresize = np.tile(np.resize(aleafv, [np.size(hc), 1]), (1, MatXsize))\n    aleafnresize = np.tile(np.resize(aleafn, [np.size(hc), 1]), (1, MatXsize))\n    aleaflresize = np.tile(np.resize(aleafl, [np.size(hc), 1]), (1, MatXsize))\n    adeadvresize = np.tile(np.resize(adeadv, [np.size(hc), 1]), (1, MatXsize))\n    adeadnresize = np.tile(np.resize(adeadn, [np.size(hc), 1]), (1, MatXsize))\n    adeadlresize = np.tile(np.resize(adeadl, [np.size(hc), 1]), (1, MatXsize))\n    albedoresize = np.tile(np.resize(albedo, [np.size(hc), 1]), (1, MatXsize))\n    ndviresize = np.tile(np.resize(ndvi, [np.size(hc), 1]), (1, MatXsize))\n    LAIresize = np.tile(np.resize(LAI, [np.size(LAI), 1]), (1, MatXsize))\n    clumpresize = np.tile(np.resize(clump, [np.size(hc), 1]), (1, MatXsize))\n    hcresize = np.tile(np.resize(hc, [np.size(hc), 1]), (1, MatXsize))\n    maskresize = np.tile(np.array(np.resize(mask, [np.size(hc), 1])), (1, MatXsize))\n    timeresize = np.tile(np.array(np.resize(time, [np.size(hc), 1])), (1, MatXsize))\n    t_riseresize = np.tile(np.array(np.resize(t_rise, [np.size(hc), 1])), (1, MatXsize))\n    t_endresize = np.tile(np.array(np.resize(t_end, [np.size(hc), 1])), (1, MatXsize))\n    leaf_widthresize = np.tile(np.resize(leaf_width, [np.size(hc), 1]), (1, MatXsize))\n    alpha_PTresize = np.tile(np.resize(alpha_PT, [np.size(hc), 1]), (1, MatXsize))\n\n    # run TSEB over TA options\n    output = TSEB_PT_usda(\n        Tr_Kresize,\n        vzaresize,\n        T_A_Kresize,\n        uresize,\n        presize,\n        Rs_1resize,\n        zsresize,\n        aleafvresize,\n        aleafnresize,\n        aleaflresize,\n        adeadvresize,\n        adeadnresize,\n        adeadlresize,\n        albedoresize,\n        ndviresize,\n        LAIresize,\n        clumpresize,\n        hcresize,\n        maskresize,\n        timeresize,\n        t_riseresize,\n        t_endresize,\n        leaf_width=leaf_widthresize,\n        a_PT_in=alpha_PTresize)\n\n    scaling = 1.0\n    Fsun = (output[4] + output[6]) / np.resize(Rs_1, [np.size(hc), 1])\n    EFeq = Fsun * (np.reshape(Rs24in, [np.size(hc), 1]))\n    et = EFeq / 2.45 * scaling\n    et[et < 0.01] = 0.01\n\n    # =============find Average ETd======================================\n\n    et_alexi = np.array(np.reshape(ET_ALEXI, [np.size(ET_ALEXI)]) * 10000, dtype='int')\n    etDict = {'ID': et_alexi,\n              'et1': np.reshape(et[:, 0], [np.size(ET_ALEXI)]),\n              'et2': np.reshape(et[:, 1], [np.size(ET_ALEXI)]),\n              'et3': np.reshape(et[:, 2], [np.size(ET_ALEXI)]),\n              'et4': np.reshape(et[:, 3], [np.size(ET_ALEXI)]),\n              'et5': np.reshape(et[:, 4], [np.size(ET_ALEXI)]),\n              'et6': np.reshape(et[:, 5], [np.size(ET_ALEXI)]),\n              'et7': np.reshape(et[:, 6], [np.size(ET_ALEXI)])}\n\n    etDF = pd.DataFrame(etDict, columns=etDict.keys())\n    etDF = pd.DataFrame(etDict)\n    group = etDF.groupby(etDF['ID'])\n    valMean = group.mean()\n    outData = np.zeros(et.shape)\n    for i in range(valMean.shape[0]):\n        outData[et_alexi == valMean.index[i]] = valMean.iloc[i]\n    et = np.reshape(outData, et.shape)\n    # ======interpolate over mutiple Ta ===================================\n\n    from scipy.interpolate import interp1d\n    x = range(0, 20, 3)\n    ET_ALEXI[mask == 0] = -9999.\n    et_alexi = np.reshape(ET_ALEXI, [np.size(hc), 1])\n    bias = et_alexi - et\n    # check if all values inrow are nan\n    nanIndex = np.sum(np.isnan(bias), axis=1)\n    # set all to 1 so it doesnt throw an error below\n    bias[np.where(nanIndex == MatXsize), :] = 1.\n    f_bias = interp1d(x, bias, kind='linear', bounds_error=False)\n    f_ta = interp1d(x, T_A_Kresize, kind='linear', bounds_error=False)\n\n    biasInterp = f_bias(np.linspace(0, 20, 1000))\n    TaInterp = f_ta(np.linspace(0, 20, 1000))\n    # extract the Ta based on minimum bias at Fine resolution\n    minBiasIndex = np.array(np.nanargmin(abs(biasInterp), axis=1))\n    TaExtrap = TaInterp[np.array(range(np.size(hc))), minBiasIndex]\n    TaExtrap[np.where(nanIndex == MatXsize)] = np.nan\n    Tareshape = np.reshape(TaExtrap, np.shape(hc))\n\n    T_A_K = Tareshape\n    output = {'T_A_K': T_A_K}\n    return output\n\n\nclass disALEXI(object):\n    def __init__(self, fn, dt, isUSA):\n        #        base = os.path.abspath(os.path.join(fn,os.pardir,os.pardir,os.pardir,\n        #                                            os.pardir,os.pardir))\n        base = os.getcwd()\n\n        Folders = folders(base)\n        self.landsatSR = Folders['landsatSR']\n        #        self.landsatNDVI = Folders['landsatNDVI']\n        #        self.ALEXIbase = Folders['ALEXIbase']\n        #        self.metBase = Folders['metBase']\n        #        self.landsatDataBase = Folders['landsatDataBase']\n        self.resultsBase = Folders['resultsBase']\n        self.fn = fn\n        self.meta = landsat_metadata(fn)\n        self.sceneID = self.meta.LANDSAT_SCENE_ID\n        self.productID = fn.split(os.sep)[-1][:-8]\n        #        self.productID = self.meta.LANDSAT_PRODUCT_ID\n        self.scene = self.sceneID[3:9]\n        self.isUSA = isUSA\n        self.dt = dt\n        self.satscene_path = os.sep.join(fn.split(os.sep)[:-2])\n\n    def DisALEXI_PT(self,\n                    ET_ALEXI,\n                    Rs_1,\n                    Rs24in,\n                    Tr_K,\n                    Ta,\n                    vza,\n                    u,\n                    p,\n                    zs,\n                    aleafv,\n                    aleafn,\n                    aleafl,\n                    adeadv,\n                    adeadn,\n                    adeadl,\n                    albedo,\n                    ndvi,\n                    LAI,\n                    clump,\n                    hc,\n                    mask,\n                    time,\n                    t_rise,\n                    t_end,\n                    leaf_width=1.,\n                    alpha_PT=1.32):\n        disalexi = _DisALEXI_PT\n        return disalexi(ET_ALEXI, Rs_1, Rs24in, Tr_K, Ta, vza, u, p, zs, aleafv, aleafn,\n                        aleafl, adeadv, adeadn, adeadl, albedo, ndvi, LAI, clump, hc,\n                        mask, time, t_rise, t_end, leaf_width=1., alpha_PT=1.32)\n\n    def smoothTaData(self, ALEXIgeodict):\n\n        ALEXILatRes = ALEXIgeodict['ALEXI_LatRes']\n        ALEXILonRes = ALEXIgeodict['ALEXI_LonRes']\n        sceneID = self.sceneID\n        scene = self.scene\n        outFN = os.path.join(self.resultsBase, scene, '%s_Ta.tif' % sceneID[:-5])\n        inProj4 = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'\n        # =======================convert fine TA to coarse resolution=========\n        outfile = os.path.join(self.resultsBase, scene, 'testTa_DisALEXI.tif')\n        #            outfile = os.path.join(self.resultsBase,scene,'%s_Ta.tif' % sceneID[:-5])\n\n        coarseFile = os.path.join(self.resultsBase, scene, 'TaCoarse.tif')\n        coarse2fineFile = os.path.join(self.resultsBase, scene, 'TaCoarse2Fine.tif')\n        #            outFN = coarseFile[:-10]+'.tif'\n\n        if not os.path.exists(outFN):\n            print 'get->Ta'\n            # get mask from Landsat LAI\n            ls = GeoTIFF(outfile)\n            #                laiFN = os.path.join(self.landsatDataBase,'LAI',scene,'lndlai.%s.hdf' % sceneID)\n            #                hdf = SD(laiFN,SDC.READ)\n            #                data2D = hdf.select('cfmask')\n            #                cfmask = data2D[:,:].astype(np.double)\n            sceneDir = os.path.join(self.satscene_path, 'CF_MASK')\n            maskFN = os.path.join(sceneDir, '%s_Mask.tiff' % sceneID)\n            g = gdal.Open(maskFN, GA_ReadOnly)\n            cfmask = g.ReadAsArray()\n            g = None\n            # =============find Average Ta====================================== COMMENTED FOR TESTING\n            in_ds = gdal.Open(outfile)\n            coarseds = gdal.Translate(coarseFile, in_ds,\n                                      options=gdal.TranslateOptions(\n                                          resampleAlg='average',\n                                          xRes=400,\n                                          yRes=400))\n            fineds = gdal.Warp(outFN, coarseds, options=gdal.WarpOptions(resampleAlg='average',\n                                                                         height=ls.nrow,\n                                                                         width=ls.ncol))\n            coarseds = None\n            # ========smooth Ta data========================================\n            ta = fineds.ReadAsArray()\n            fineRes = ls.Lat[1, 0] - ls.Lat[0, 0]\n            coarseRes = ALEXILatRes\n            course2fineRatio = coarseRes ** 2 / fineRes ** 2\n            rid2 = int(np.sqrt(course2fineRatio))\n            #            gauss_kernal = Gaussian2DKernel(rid2)\n            box_kernal = Box2DKernel(rid2)\n            ta = convolve_fft(ta, box_kernal, allow_huge=True)\n            fineds.GetRasterBand(1).WriteArray(ta)\n            fineds = None\n\n            ulx = ls.ulx\n            uly = ls.uly\n            delx = ls.delx\n            dely = -ls.dely\n            fineRes = ls.Lat[1, 0] - ls.Lat[0, 0]\n            coarseRes = ALEXILatRes\n            inUL = [ulx, uly]\n            inRes = [delx, dely]\n\n            #            Ta = interp_ta(ta,coarseRes,fineRes)-273.16\n            Ta = ta - 273.16  # FOR TESTING!!\n\n            outFormat = gdal.GDT_Float32\n            writeArray2Tiff(Ta, inRes, inUL, ls.proj4, outFN, outFormat)\n            os.remove(coarseFile)\n\n    def runDisALEXI(self, xStart, yStart, xSize, ySize, ALEXIgeodict, TSEB_only):\n        # USER INPUT============================================================\n        ALEXILatRes = ALEXIgeodict['ALEXI_LatRes']\n        ALEXILonRes = ALEXIgeodict['ALEXI_LonRes']\n        sceneID = self.sceneID\n        scene = self.scene\n        productID = self.productID\n        #        xSize = 200\n        #        ySize = 200\n\n        # -------------pick Landcover map----------------\n        if self.isUSA == 1:\n            landcover = 'NLCD'\n        else:\n            landcover = 'GlobeLand30'\n\n        yeardoy = sceneID[9:16]\n        # -------------get Landsat information-----------\n        #        ls = GeoTIFF(os.path.join(self.landsatSR,'temp',\"%s_band10.tif\" % productID))\n        sceneDir = os.path.join(self.satscene_path, 'LST')\n        ls = GeoTIFF(os.path.join(sceneDir, '%s_lstSharp.tiff' % sceneID))\n        g = gdal.Open(os.path.join(sceneDir, '%s_lstSharp.tiff' % sceneID))\n        solZen = self.meta.SUN_ELEVATION\n        #        nsamples = int(self.meta.REFLECTIVE_SAMPLES)\n        #        nlines = int(self.meta.REFLECTIVE_LINES)\n        nsamples = g.RasterXSize\n        nlines = g.RasterYSize\n        if xStart == ((nsamples / xSize) * xSize):\n            xSize = (nsamples - xStart)\n        if yStart == ((nlines / ySize) * ySize):\n            ySize = (nlines - yStart)\n        g = None\n        inProj4 = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'\n        sz = np.radians(90 - solZen)  # convert sza to radians\n\n        # ===========================get the ETd data==============================\n\n        #        sceneDir = os.path.join(self.ALEXIbase,'%s' % scene)\n        sceneDir = os.path.join(self.satscene_path, 'ET', '400m')\n        outFN = os.path.join(sceneDir, '%s_alexiET.tiff' % sceneID)\n        g = gdal.Open(outFN, GA_ReadOnly)\n        ET_ALEXI = g.ReadAsArray(xStart, yStart, xSize, ySize)\n        g = None\n\n        # =============get MET data================================================\n        # get CFSR MET data at overpass time\n\n        #        sceneDir = os.path.join(self.metBase,'%s' % scene)\n        sceneDir = os.path.join(self.satscene_path, 'MET')\n        # ------------get-> surface pressure...\n        outFN = os.path.join(sceneDir, '%s_p.tiff' % sceneID)\n        g = gdal.Open(outFN, GA_ReadOnly)\n        #        print(\"xsize:%d\" % xSize)\n        #        print(\"ysize:%d\" % ySize)\n        p = g.ReadAsArray(xStart, yStart, xSize, ySize)\n        p /= 100.  # convert to mb\n        g = None\n\n        # ------------get-> ea...\n        outFN = os.path.join(sceneDir, '%s_q2.tiff' % sceneID)\n        g = gdal.Open(outFN, GA_ReadOnly)\n        q2 = g.ReadAsArray(xStart, yStart, xSize, ySize)\n        g = None\n\n        ea = ((q2 * (1000. / 621.9907)) * (p * 100.)) * 0.001  # kPa\n        ea *= 10.  # mb\n        # ====get CFSR air temperature==========================================\n        outFN = os.path.join(sceneDir, '%s_Ta.tiff' % sceneID)\n        g = gdal.Open(outFN, GA_ReadOnly)\n        Ta = g.ReadAsArray(xStart, yStart, xSize, ySize)\n        g = None\n\n        outFN = os.path.join(self.resultsBase, scene, '%s_Ta.tif' % sceneID[:-5])\n        if (TSEB_only == 1):\n            #            if ((xStart==0) & (yStart==0)):\n            #                #ls = GeoTIFF(os.path.join(self.landsatSR, scene,'%s_sr_band1.tif' % productID))\n            #\n            #                #=======================convert fine TA to coarse resolution=========\n            #                outfile = os.path.join(self.resultsBase,scene,'Ta_DisALEXI.tif')\n            #    #            outfile = os.path.join(self.resultsBase,scene,'%s_Ta.tif' % sceneID[:-5])\n            #\n            #                coarseFile = os.path.join(self.resultsBase,scene,'TaCoarse.tif')\n            #                coarse2fineFile = os.path.join(self.resultsBase,scene,'TaCoarse2Fine.tif')\n            #    #            outFN = coarseFile[:-10]+'.tif'\n            #\n            #                if not os.path.exists(outFN):\n            #                    print 'get->Ta'\n            #                    # get mask from Landsat LAI\n            #                    ls = GeoTIFF(outfile)\n            #    #                laiFN = os.path.join(self.landsatDataBase,'LAI',scene,'lndlai.%s.hdf' % sceneID)\n            #    #                hdf = SD(laiFN,SDC.READ)\n            #    #                data2D = hdf.select('cfmask')\n            #    #                cfmask = data2D[:,:].astype(np.double)\n            #\n            #                    maskFN = os.path.join(self.landsatDataBase,'Mask',scene,'%s_mask.tiff' % sceneID)\n            #                    g = gdal.Open(maskFN,GA_ReadOnly)\n            #                    cfmask = g.ReadAsArray()\n            #                    g= None\n            #                    g = gdal.Open(outfile,GA_ReadOnly)\n            #                    ta = g.ReadAsArray()\n            #                    ta[cfmask > 0]=0\n            #                    g= None\n            #                    mask = os.path.join(self.resultsBase,scene,\"TafineMask.tif\")\n            #                    masked = os.path.join(self.resultsBase,scene,\"TafineMasked.tif\")\n            #                    ls.clone(mask,ta)\n            #                    subprocess.check_output('gdal_fillnodata.py %s %s -mask %s -of GTiff' % (outfile,masked,mask),shell=True)\n            #                    optionList = ['-overwrite', '-s_srs', '%s' % ls.proj4,'-t_srs',\n            #                                  '%s' % inProj4,'-r', 'average','-tr',\n            #                                  '%f' % ALEXILatRes, '%f' % ALEXILonRes,\n            #                                  '-srcnodata','270.','-dstnodata','0.0',\n            #                                  '-of','GTiff','%s' % masked, '%s' % coarseFile]\n            #\n            #                    warp(optionList)\n            #                    #=======now convert the averaged coarse Ta to fine resolution==\n            #                    nrow = ls.nrow+100.\n            #                    ncol = ls.ncol+100.\n            #                    optionList = ['-overwrite', '-s_srs', '%s' % inProj4, '-t_srs',\n            #                                  '%s' % ls.proj4,'-r', 'near','-ts',\n            #                                  '%f' % nrow, '%f' % ncol,'-of',\n            #                                  'GTiff','%s' % coarseFile, '%s' % coarse2fineFile]\n            #                    warp(optionList)\n            #                    #========smooth Ta data========================================\n            #                    ulx = ls.ulx\n            #                    uly = ls.uly\n            #                    lrx = ls.lrx\n            #                    lry = ls.lry\n            #                    delx = ls.delx\n            #                    dely = -ls.dely\n            #                    fineRes = ls.Lat[1,0]-ls.Lat[0,0]\n            #                    coarseRes = ALEXILatRes\n            #                    inUL = [ulx,uly]\n            #                    inRes = [delx,dely]\n            #                    g = gdal.Open(coarse2fineFile,GA_ReadOnly)\n            #                    ta = g.ReadAsArray()\n            #                    g= None\n            #\n            #                    Ta = interp_ta(ta,coarseRes,fineRes)-273.16\n            #\n            #                    outFormat = gdal.GDT_Float32\n            #                    writeArray2Tiff(Ta,inRes,inUL,ls.proj4,outFN,outFormat)\n            #    #\n            #    #                optionList = ['-overwrite','-te', '%f' % ulx, '%f' % lry,\n            #    #                              '%f' % lrx,'%f' % uly,'-tr',\n            #    #                              '%f' % delx, '%f' % dely ,'-multi','-of','GTiff',\n            #    #                              '%s' % coarse2fineFile, '%s' % outFN]\n            #    #                warp(optionList)\n            #                    #os.remove(coarseFile)\n            g = gdal.Open(outFN, GA_ReadOnly)\n            T_A_K = g.ReadAsArray(xStart, yStart, xSize, ySize) + 273.16\n            g = None\n\n        #        sceneDir = os.path.join(self.metBase,'%s' % scene)\n        outFN = os.path.join(sceneDir, '%s_u.tiff' % sceneID)\n        g = gdal.Open(outFN, GA_ReadOnly)\n        u = g.ReadAsArray(xStart, yStart, xSize, ySize)\n        g = None\n        # ===create lat long files==============================================\n\n        inUL = [ls.ulx, ls.uly]\n        inRes = [ls.delx, -ls.dely]\n        lat_fName = os.path.join(self.landsatSR, 'temp', 'lat.tif')\n        lon_fName = os.path.join(self.landsatSR, 'temp', 'lon.tif')\n        if not os.path.exists(lat_fName):\n            lats = ls.Lat_pxcenter\n            lons = ls.Lon_pxcenter\n            writeArray2Tiff(lats, inRes, inUL, ls.proj4, lat_fName, gdal.GDT_Float32)\n            writeArray2Tiff(lons, inRes, inUL, ls.proj4, lon_fName, gdal.GDT_Float32)\n        g = gdal.Open(lat_fName, GA_ReadOnly)\n        lat = g.ReadAsArray(xStart, yStart, xSize, ySize)\n        g = None\n\n        g = gdal.Open(lon_fName, GA_ReadOnly)\n        lon = g.ReadAsArray(xStart, yStart, xSize, ySize)\n        g = None\n\n        # ====get overpass hour insolation======================================\n        sceneDir = os.path.join(self.satscene_path, 'INSOL')\n        outFN = os.path.join(sceneDir, '%s_Insol1.tiff' % sceneID)\n        g = gdal.Open(outFN, GA_ReadOnly)\n        Rs_1 = g.ReadAsArray(xStart, yStart, xSize, ySize) * 0.042727217\n        g = None\n\n        # ====get daily insolation=========================================\n        outFN = os.path.join(sceneDir, '%s_Insol24.tiff' % sceneID)\n        g = gdal.Open(outFN, GA_ReadOnly)\n        Rs24 = g.ReadAsArray(xStart, yStart, xSize, ySize)\n        g = None\n\n        # ===============get biophysical parameters at overpass time============\n        sceneDir = os.path.join(self.satscene_path, 'ALBEDO')\n        #        sceneDir = os.path.join(self.landsatDataBase,'albedo',scene)\n        outFN = os.path.join(sceneDir, '%s_albedo.tiff' % sceneID)\n        g = gdal.Open(outFN, GA_ReadOnly)\n        albedo = g.ReadAsArray(xStart, yStart, xSize, ySize)\n        g = None\n\n        # ------>get LAI...\n        #        outFN = os.path.join(self.landsatDataBase,'LAI',scene,'lndlai.%s.hdf' % sceneID)\n        sceneDir = os.path.join(self.satscene_path, 'LAI')\n        outFN = os.path.join(sceneDir, '%s_lai.tiff' % sceneID)\n        g = gdal.Open(outFN, GA_ReadOnly)\n        LAI = g.ReadAsArray(xStart, yStart, xSize, ySize) * 0.001  # TESTING\n        g = None\n        #        LAI[np.where(LAI==-9.999)]=np.nan\n        #        LAI[np.where(LAI<=0.)]=0.001\n\n        #        hdf = SD(outFN,SDC.READ)\n        #        data2D = hdf.select('LAI')\n        #        LAI = data2D[yStart:yStart+ySize,xStart:xStart+xSize].astype(np.double)*0.001\n        #\n        #        LAI[np.where(LAI==-9.999)]=np.nan\n        #        LAI[np.where(LAI<=0.)]=0.001\n\n        # ------>get ndvi...'\n        #        sceneDir = os.path.join(self.landsatNDVI,scene)\n        sceneDir = os.path.join(self.satscene_path, 'NDVI')\n        outFN = os.path.join(sceneDir, '%s_ndvi.tiff' % sceneID)\n        g = gdal.Open(outFN, GA_ReadOnly)\n        ndvi = g.ReadAsArray(xStart, yStart, xSize, ySize)  # *0.001 # TESTING\n        g = None\n        #        ndvi[np.where(ndvi==-9999.)]=np.nan\n\n        #        data2D = hdf.select('NDVI')\n        #        ndvi = data2D[yStart:yStart+ySize,xStart:xStart+xSize].astype(np.double)*0.001\n        #        ndvi[np.where(ndvi==-9.999)]=np.nan\n\n        # ===get cfmask=======\n        sceneDir = os.path.join(self.satscene_path, 'CF_MASK')\n        outFN = os.path.join(sceneDir, '%s_Mask.tiff' % sceneID)\n        g = gdal.Open(outFN, GA_ReadOnly)\n        cfmask = g.ReadAsArray(xStart, yStart, xSize, ySize)\n        g = None\n        #        laiFN = os.path.join(self.landsatDataBase,'LAI',scene,'lndlai.%s.hdf' % sceneID)\n        #        hdf = SD(laiFN,SDC.READ)\n        #        data2D = hdf.select('cfmask')\n        #        cfmask = data2D[yStart:yStart+ySize,xStart:xStart+xSize].astype(np.double)\n\n        # ---------->get LST...\n        sceneDir = os.path.join(self.satscene_path, 'LST')\n        outFN = os.path.join(sceneDir, '%s_lstSharp.tiff' % sceneID)\n        g = gdal.Open(outFN, GA_ReadOnly)\n        # *NOTE: version 0.2.0 forward------>\n        # convert from scaled celcius to kelvin int16->float32\n        Tr_K = (g.ReadAsArray(xStart, yStart, xSize, ySize) / 100.) + 273.15\n        #        Tr_K = g.ReadAsArray(xStart,yStart,xSize,ySize)+273.16 # TESTING\n        g = None\n        Tr_K[np.where(albedo < 0)] = np.nan\n        # ---------->get LC...\n        sceneDir = os.path.join(self.satscene_path, 'LC')\n        #        sceneDir = os.path.join(self.landsatDataBase,'LC',scene)\n        outFN = os.path.join(sceneDir, '%s_LC.tiff' % sceneID)\n        g = gdal.Open(outFN, GA_ReadOnly)\n        LCdata = g.ReadAsArray(xStart, yStart, xSize, ySize)\n        g = None\n        # ---------->get ALEXI mask...\n        #        ET_ALEXI[np.where(albedo<0)]=-9999\n        #        mask = ET_ALEXI.copy()\n        mask = np.tile(1., albedo.shape)\n        mask[cfmask > 0] = 0.\n        mask[albedo < 0] = 0.\n        #        mask[mask==0]=1.\n        #        mask[mask==-9999.] = 0.\n        albedo[np.where(albedo < 0.)] = np.nan\n\n        # ====================get LC based variables===============================\n        s = ndimage.__file__\n        envPath = os.sep.join(s.split(os.sep)[:-6])\n        landsatLC = os.path.join(envPath, 'share', 'disalexi')\n        aleafv = getParFromExcel(LCdata, landsatLC, landcover, 'aleafv')\n        aleafn = getParFromExcel(LCdata, landsatLC, landcover, 'aleafn')\n        aleafl = getParFromExcel(LCdata, landsatLC, landcover, 'aleafl')\n        adeadv = getParFromExcel(LCdata, landsatLC, landcover, 'adeadv')\n        adeadn = getParFromExcel(LCdata, landsatLC, landcover, 'adeadn')\n        adeadl = getParFromExcel(LCdata, landsatLC, landcover, 'adeadl')\n        hc_min = getParFromExcel(LCdata, landsatLC, landcover, 'hmin')\n        hc_max = getParFromExcel(LCdata, landsatLC, landcover, 'hmax')\n        xl = getParFromExcel(LCdata, landsatLC, landcover, 'xl')\n        clump = getParFromExcel(LCdata, landsatLC, landcover, 'omega')\n        clump[clump == 0] = 0.99\n        LAI[LCdata == 11] = 0.01\n        ndvi[LCdata == 11] = -0.5\n\n        aleafv[np.isnan(aleafv)] = 0.9\n        aleafn[np.isnan(aleafn)] = 0.9\n        aleafl[np.isnan(aleafl)] = 0.9\n        adeadv[np.isnan(adeadv)] = 0.2\n        adeadn[np.isnan(adeadn)] = 0.2\n        adeadl[np.isnan(adeadl)] = 0.2\n        hc_min[np.isnan(hc_min)] = 0.1\n        hc_max[np.isnan(hc_max)] = 0.5\n        xl[np.isnan(xl)] = 0.5\n        xl[xl == 0.] = 0.5\n\n        F = LAI * clump  # LAI for leafs spherical distribution\n        f_c = 1 - (np.exp(-0.5 * F))  # fraction cover at nadir (view=0)\n        f_c[f_c <= 0.01] = 0.01\n        f_c[f_c >= 0.9] = 0.9\n\n        # ************************************************************************\n        # Compute Canopy height and Roughness Parameters\n        hc = hc_min + ((hc_max - hc_min) * f_c)\n\n        #        LAI[np.where(LAI==0.0)]=0.001\n        vza = np.tile(0.0, np.shape(LAI))\n        #        Rs24 = Rs24+500. # FOR TESTING ONLY\n        #        Rs24 = (Rs24*0.0864)/24.0 # MERRA\n        Rs24 = Rs24 * 0.0864  # GSIP\n\n        leaf_width = xl\n        alpha_PT = np.tile(1.32, np.shape(LAI))\n        time = self.dt.hour + (self.dt.minute / 60.)\n        #        print(\"time:%f\" % time)\n        t_rise, t_end, zs = sunset_sunrise(self.dt, np.deg2rad(lon), np.deg2rad(lat), time)\n        #        print(\"t_rise:%f, t_end:%f\" % (t_rise[0,0],t_end[0,0]))\n        #        zs = np.tile(sz,np.shape(LAI))\n\n        # ================RUN DisALEXI=================================\n\n        if TSEB_only == 1:\n            # convert TA from scaled celcius to kelvin\n            #            T_A_K = (T_A_K/1000.)+273.15  # removed /1000 FOR TESTING!!!!\n            #            T_A_K = (T_A_K)+273.16  # removed /1000 FOR TESTING!!!!\n            nan_check = np.sum(np.isnan(LAI)) / LAI.size\n            if nan_check == 1:  # All nans\n                ET_24 = np.tile(np.nan, LAI.shape)\n            else:\n                output = TSEB_PT_usda(\n                    Tr_K,\n                    vza,\n                    T_A_K,\n                    u,\n                    p,\n                    Rs_1,\n                    zs,\n                    aleafv,\n                    aleafn,\n                    aleafl,\n                    adeadv,\n                    adeadn,\n                    adeadl,\n                    albedo,\n                    ndvi,\n                    LAI,\n                    clump,\n                    hc,\n                    mask,\n                    time,\n                    t_rise,\n                    t_end,\n                    leaf_width=leaf_width,\n                    a_PT_in=alpha_PT)  # atmospheric emissivity (clear-sly) Idso and Jackson (1969)\n\n                scaling = 1.0\n                Fsun = (output[4] + output[6]) / Rs_1\n                #            Rs24 = ndimage.gaussian_filter(Rs24, sigma=5)\n                EFeq = Fsun * (Rs24)\n                #            ET_24 = EFeq/2.45*scaling\n                ET_24 = EFeq * 0.408 * scaling\n                ET_24[ET_24 < 0.01] = 0.01\n        #            ET_24 = np.array(ET_24*1000.,dtype='uint16')\n        else:\n            nan_check = np.sum(np.isnan(LAI)) / LAI.size\n            if nan_check == 1:  # All nans\n                T_A_K = np.tile(np.nan, LAI.shape)\n            else:\n                output = self.DisALEXI_PT(\n                    ET_ALEXI,\n                    Rs_1,\n                    Rs24,\n                    Tr_K,\n                    Ta,\n                    vza,\n                    u,\n                    p,\n                    zs,\n                    aleafv,\n                    aleafn,\n                    aleafl,\n                    adeadv,\n                    adeadn,\n                    adeadl,\n                    albedo,\n                    ndvi,\n                    LAI,\n                    clump,\n                    hc,\n                    mask,\n                    time,\n                    t_rise,\n                    t_end,\n                    leaf_width=leaf_width,\n                    alpha_PT=alpha_PT)\n                #            T_A_K= np.array((output['T_A_K']-273.15)*1000.,dtype='uint16')\n                T_A_K = np.array(output['T_A_K'], dtype='float32')\n\n        #        outFormat = gdal.GDT_UInt16\n        outFormat = gdal.GDT_Float32\n        outET24Path = os.path.join(self.resultsBase, scene)\n        if not os.path.exists(outET24Path):\n            os.makedirs(outET24Path)\n        # set ouput location and resolution\n        #        ulx = self.meta.CORNER_UL_PROJECTION_X_PRODUCT\n        #        uly = self.meta.CORNER_UL_PROJECTION_Y_PRODUCT\n        #        delx = self.meta.GRID_CELL_SIZE_REFLECTIVE\n        #        dely = self.meta.GRID_CELL_SIZE_REFLECTIVE\n        ulx = ls.ulx\n        uly = ls.uly\n        delx = ls.delx\n        dely = -ls.dely\n        inUL = [ulx + (xStart * delx), uly - (yStart * dely)]\n        inRes = [delx, dely]\n\n        if TSEB_only == 1:\n            outFormat = gdal.GDT_Float32  # FOR TESTING WE CAN GO BACK TO INT LATER\n            ET_24outName = 'ETd_%s_part_%d_%d.tif' % (yeardoy, xStart, yStart)\n            fName = '%s%s%s' % (outET24Path, os.sep, ET_24outName)\n            writeArray2Tiff(ET_24, inRes, inUL, ls.proj4, fName, outFormat)\n\n            # ======write out fluxes==================================\n            #            flag, Ts, Tc, Tac, lETc, H_c, lEs, H_s, G0\n            outFormat = gdal.GDT_Float32\n            # ==Ts=====>\n            Ts_24outName = 'Ts_%s_part_%d_%d.tif' % (yeardoy, xStart, yStart)\n            fName = '%s%s%s' % (outET24Path, os.sep, Ts_24outName)\n            writeArray2Tiff(output[1], inRes, inUL, ls.proj4, fName, outFormat)\n            # ==Tc=====>\n            Tc_24outName = 'Tc_%s_part_%d_%d.tif' % (yeardoy, xStart, yStart)\n            fName = '%s%s%s' % (outET24Path, os.sep, Tc_24outName)\n            writeArray2Tiff(output[2], inRes, inUL, ls.proj4, fName, outFormat)\n            # ==Tac=====>\n            Tac_24outName = 'Tac_%s_part_%d_%d.tif' % (yeardoy, xStart, yStart)\n            fName = '%s%s%s' % (outET24Path, os.sep, Tac_24outName)\n            writeArray2Tiff(output[3], inRes, inUL, ls.proj4, fName, outFormat)\n            # ==lETc=====>\n            lETc_24outName = 'lETc_%s_part_%d_%d.tif' % (yeardoy, xStart, yStart)\n            fName = '%s%s%s' % (outET24Path, os.sep, lETc_24outName)\n            writeArray2Tiff(output[4], inRes, inUL, ls.proj4, fName, outFormat)\n            # ==H_c=====>\n            H_c_24outName = 'H_c_%s_part_%d_%d.tif' % (yeardoy, xStart, yStart)\n            fName = '%s%s%s' % (outET24Path, os.sep, H_c_24outName)\n            writeArray2Tiff(output[5], inRes, inUL, ls.proj4, fName, outFormat)\n            # ==lEs=====>\n            lEs_24outName = 'lEs_%s_part_%d_%d.tif' % (yeardoy, xStart, yStart)\n            fName = '%s%s%s' % (outET24Path, os.sep, lEs_24outName)\n            writeArray2Tiff(output[6], inRes, inUL, ls.proj4, fName, outFormat)\n            # ==H_s=====>\n            H_s_24outName = 'H_s_%s_part_%d_%d.tif' % (yeardoy, xStart, yStart)\n            fName = '%s%s%s' % (outET24Path, os.sep, H_s_24outName)\n            writeArray2Tiff(output[7], inRes, inUL, ls.proj4, fName, outFormat)\n            # ==G0=====>\n            G0_24outName = 'G0_%s_part_%d_%d.tif' % (yeardoy, xStart, yStart)\n            fName = '%s%s%s' % (outET24Path, os.sep, G0_24outName)\n            writeArray2Tiff(output[8], inRes, inUL, ls.proj4, fName, outFormat)\n\n\n\n        else:\n            T_A_KoutName = 'Ta_%s_%d_%d.tif' % (yeardoy, xStart, yStart)\n            fName = '%s%s%s' % (outET24Path, os.sep, T_A_KoutName)\n            writeArray2Tiff(T_A_K, inRes, inUL, ls.proj4, fName, outFormat)\n", "meta": {"hexsha": "c02c9398aa028b80c05724fb090ae7dd43b1ad68", "size": 40057, "ext": "py", "lang": "Python", "max_stars_repo_path": "pydisalexi/disalexi_usda.py", "max_stars_repo_name": "Yun1/projectMAS", "max_stars_repo_head_hexsha": "fb25dc50f2c70a62aa0854aca9c4295d4221b843", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pydisalexi/disalexi_usda.py", "max_issues_repo_name": "Yun1/projectMAS", "max_issues_repo_head_hexsha": "fb25dc50f2c70a62aa0854aca9c4295d4221b843", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pydisalexi/disalexi_usda.py", "max_forks_repo_name": "Yun1/projectMAS", "max_forks_repo_head_hexsha": "fb25dc50f2c70a62aa0854aca9c4295d4221b843", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.4583795782, "max_line_length": 166, "alphanum_fraction": 0.5026087825, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 11065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.16387336119674775}}
{"text": "#!/usr/bin/env python\n\n\"\"\"\nModule containing analysis classes which compute a pourbaix diagram given a\ntarget compound/element.\n\"\"\"\n\nfrom __future__ import division\n\n__author__ = \"Sai Jayaraman\"\n__copyright__ = \"Copyright 2012, The Materials Project\"\n__version__ = \"0.0\"\n__maintainer__ = \"Sai Jayaraman\"\n__email__ = \"sjayaram@mit.edu\"\n__status__ = \"Development\"\n__date__ = \"Nov 1, 2012\"\n\n\nimport logging\nimport numpy as np\nimport itertools\nimport re\nfrom itertools import chain\nfrom pyhull.convex_hull import ConvexHull\nfrom pymatgen.analysis.pourbaix.entry import MultiEntry\nfrom pymatgen.core.periodic_table import Element\nfrom pymatgen.core import Composition\nfrom pymatgen.core.ion import Ion\n\n\nlogger = logging.getLogger(__name__)\n\nPREFAC = 0.0591\nMU_H2O = -2.4583\n\n\nclass PourbaixDiagram(object):\n    \"\"\"\n    Class to create a Pourbaix diagram from entries\n    \"\"\"\n    def __init__(self, entries, comp_dict=None):\n        \"\"\"\n        Args:\n            entries:\n                Entries list containing both Solids and Ions\n            comp_dict:\n                Dictionary of compositions\n        \"\"\"\n        self._solid_entries = list()\n        self._ion_entries = list()\n        for entry in entries:\n            if entry.phase_type == \"Solid\":\n                self._solid_entries.append(entry)\n            elif entry.phase_type == \"Ion\":\n                self._ion_entries.append(entry)\n            else:\n                raise StandardError(\"Incorrect Phase type - needs to be \\\n                Pourbaix entry of phase type Ion/Solid\")\n        self._unprocessed_entries = self._solid_entries + self._ion_entries\n        self._elt_comp = comp_dict\n        if comp_dict:\n            self._multielement = True\n            self.pourbaix_elements = [key for key in comp_dict]\n            w = [comp_dict[key] for key in comp_dict]\n            A = []\n            for comp in comp_dict:\n                m = re.search(r\"\\[([^\\[\\]]+)\\]|\\(aq\\)\", comp)\n                if m:\n                    comp_obj = Ion.from_formula(comp)\n                else:\n                    comp_obj = Composition.from_formula(comp)\n                Ai = []\n                for elt in self.pourbaix_elements:\n                    Ai.append(comp_obj[Element(elt)])\n                A.append(Ai)\n            A = np.array(A).T.astype(float)\n            w = np.array(w)\n            A /= np.dot([A[i].sum() for i in xrange(len(A))], w)\n            x = np.linalg.solve(A, w)\n            self._elt_comp = dict(zip(self.pourbaix_elements, x))\n\n        else:\n            self._multielement = False\n            self.pourbaix_elements = [el.symbol\n                                      for el in entries[0].composition.elements\n                                      if el.symbol not in [\"H\", \"O\"]]\n        self._make_pourbaixdiagram()\n\n    def _create_conv_hull_data(self):\n        \"\"\"\n        Make data conducive to convex hull generator.\n        \"\"\"\n        if self._multielement:\n            self._all_entries = self._process_multielement_entries()\n        else:\n            self._all_entries = self._unprocessed_entries\n        entries_to_process = list()\n        for entry in self._all_entries:\n            entry.scale(entry.normalization_factor)\n            entry.correction += (- MU_H2O * entry.nH2O + entry.conc_term)\n            entries_to_process.append(entry)\n        self._qhull_entries = entries_to_process\n        return self._process_conv_hull_data(entries_to_process)\n\n    def _process_conv_hull_data(self, entries_to_process):\n        \"\"\"\n        From a sequence of ion+solid entries, generate the necessary data\n        for generation of the convex hull.\n        \"\"\"\n        data = []\n        for entry in entries_to_process:\n            row = [entry.npH, entry.nPhi, entry.g0]\n            data.append(row)\n        temp = zip(data, self._qhull_entries)\n        temp.sort(key=lambda x: x[0][2])\n        [data, self._qhull_entries] = zip(*temp)\n        return data\n\n    def _process_multielement_entries(self):\n        \"\"\"\n        Create entries for multi-element Pourbaix construction\n        \"\"\"\n        N = len(self._elt_comp)  # No. of elements\n        entries = self._unprocessed_entries\n        el_list = self._elt_comp.keys()\n        comp_list = [self._elt_comp[el] for el in el_list]\n        list_of_entries = list(itertools.combinations(\n            [i for i in xrange(len(entries))], N))\n        processed_entries = list()\n        self._entry_components_list = list_of_entries\n        self._entry_components_dict = {}\n        count = 0\n        for entry_list in list_of_entries:\n            # Check if all elements in composition list are present in entry_list\n            if not (set([Element(el) for el in el_list]).issubset(set(list(chain.from_iterable([entries[i].composition.keys() for i in entry_list]))))):\n                continue\n            count += 1\n            A = [[0.0] * (len(el_list) - 1) for _ in range(len(entry_list) - 1)]\n            multi_entries = [entries[j] for j in entry_list]\n            entry0 = entries[entry_list[0]]\n            comp0 = entry0.composition\n            if entry0.phase_type == \"Solid\":\n                red_fac = comp0.get_reduced_composition_and_factor()[1]\n            else:\n                red_fac = 1.0\n            sum_nel = sum([comp0[el] / red_fac for el in el_list])\n            b = [comp0[Element(el_list[i])] / red_fac - comp_list[i] * sum_nel\n                 for i in xrange(1, len(el_list))]\n            for j in xrange(1, len(entry_list)):\n                entry = entries[entry_list[j]]\n                comp = entry.composition\n                if entry.phase_type == \"Solid\":\n                    red_fac = comp.get_reduced_composition_and_factor()[1]\n                else:\n                    red_fac = 1.0\n                sum_nel = sum([comp[el] / red_fac for el in el_list])\n                for i in xrange(1, len(el_list)):\n                    el = el_list[i]\n                    A[i-1][j-1] = comp_list[i] * sum_nel -\\\n                        comp[Element(el)] / red_fac\n            try:\n                weights = np.linalg.solve(np.array(A), np.array(b))\n            except np.linalg.linalg.LinAlgError as err:\n                if 'Singular matrix' in err.message:\n                    continue\n                else:\n                    raise StandardError(\"Unknown Error message!\")\n            if not(np.all(weights > 0.0)):\n                continue\n            weights = list(weights)\n            weights.insert(0, 1.0)\n            super_entry = MultiEntry(multi_entries, weights)\n            self._entry_components_dict[super_entry] = entry_list\n            processed_entries.append(super_entry)\n        return processed_entries\n\n    def _make_pourbaixdiagram(self):\n        \"\"\"\n        Calculates entries on the convex hull in the dual space.\n        \"\"\"\n        stable_entries = set()\n        self._qhull_data = self._create_conv_hull_data()\n        dim = len(self._qhull_data[0])\n        if len(self._qhull_data) < dim:\n            raise StandardError(\"Can only do elements with at-least 3 entries\"\n                                \" for now\")\n        if len(self._qhull_data) == dim:\n            self._facets = [range(dim)]\n        else:\n            facets_pyhull = np.array(ConvexHull(self._qhull_data).vertices)\n            self._facets = np.sort(np.array(facets_pyhull))\n            logger.debug(\"Final facets are\\n{}\".format(self._facets))\n\n            logger.debug(\"Removing vertical facets...\")\n            vert_facets_removed = list()\n            for facet in self._facets:\n                facetmatrix = np.zeros((len(facet), len(facet)))\n                count = 0\n                for vertex in facet:\n                    facetmatrix[count] = np.array(self._qhull_data[vertex])\n                    facetmatrix[count, dim - 1] = 1\n                    count += 1\n                if abs(np.linalg.det(facetmatrix)) > 1e-8:\n                    vert_facets_removed.append(facet)\n                else:\n                    print \"removed facet\", facet\n                    logger.debug(\"Removing vertical facet : {}\".format(facet))\n\n            logger.debug(\"Removing UCH facets by eliminating normal.z >0 ...\")\n\n            # Find center of hull\n            vertices = set()\n            for facet in vert_facets_removed:\n                for vertex in facet:\n                    vertices.add(vertex)\n            c = [0.0, 0.0, 0.0]\n            c[0] = np.average([self._qhull_data[vertex][0]\n                               for vertex in vertices])\n            c[1] = np.average([self._qhull_data[vertex][1]\n                               for vertex in vertices])\n            c[2] = np.average([self._qhull_data[vertex][2]\n                               for vertex in vertices])\n\n            # Shift origin to c\n            new_qhull_data = np.array(self._qhull_data)\n            for vertex in vertices:\n                new_qhull_data[vertex] -= c\n\n            # For each facet, find normal n, find dot product with P, and\n            # check if this is -ve\n            final_facets = list()\n            for facet in vert_facets_removed:\n                a = new_qhull_data[facet[1]] - new_qhull_data[facet[0]]\n                b = new_qhull_data[facet[2]] - new_qhull_data[facet[0]]\n                n = np.cross(a, b)\n                val = np.dot(n, new_qhull_data[facet[0]])\n                if val < 0:\n                    n = -n\n                if n[2] <= 0:\n                    final_facets.append(facet)\n                else:\n                    print \"removed UCH facet\", facet\n                    logger.debug(\"Removing UCH facet : {}\".format(facet))\n            final_facets = np.array(final_facets)\n            self._facets = final_facets\n\n        stable_vertices = set()\n        for facet in self._facets:\n            for vertex in facet:\n                stable_vertices.add(vertex)\n                stable_entries.add(self._qhull_entries[vertex])\n        self._stable_entries = stable_entries\n        self._vertices = stable_vertices\n\n    @property\n    def facets(self):\n        \"\"\"\n        Facets of the convex hull in the form of  [[1,2,3],[4,5,6]...]\n        \"\"\"\n        return self._facets\n\n    @property\n    def qhull_data(self):\n        \"\"\"\n        Data used in the convex hull operation. This is essentially a matrix of\n        composition data and energy per atom values created from qhull_entries.\n        \"\"\"\n        return self._qhull_data\n\n    @property\n    def qhull_entries(self):\n        \"\"\"\n        Return qhull entries\n        \"\"\"\n        return self._qhull_entries\n\n    @property\n    def stable_entries(self):\n        \"\"\"\n        Returns the stable entries in the phase diagram.\n        \"\"\"\n        return self._stable_entries\n\n    @property\n    def all_entries(self):\n        \"\"\"\n        Return all entries\n        \"\"\"\n        return self._all_entries\n\n    @property\n    def vertices(self):\n        \"\"\"\n        Return vertices of the convex hull\n        \"\"\"\n        return self._vertices\n\n    @property\n    def unprocessed_entries(self):\n        \"\"\"\n        Return unprocessed entries\n        \"\"\"\n        return self._unprocessed_entries\n", "meta": {"hexsha": "b9816f3bb12fecd7bfca849ab2bc849994be4036", "size": 11116, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymatgen/analysis/pourbaix/maker.py", "max_stars_repo_name": "jmflorez/pymatgen", "max_stars_repo_head_hexsha": "d3da257812f6f53575117caf959b16291c3bbcb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-28T04:24:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T04:24:46.000Z", "max_issues_repo_path": "pymatgen/analysis/pourbaix/maker.py", "max_issues_repo_name": "jmflorez/pymatgen", "max_issues_repo_head_hexsha": "d3da257812f6f53575117caf959b16291c3bbcb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pymatgen/analysis/pourbaix/maker.py", "max_forks_repo_name": "jmflorez/pymatgen", "max_forks_repo_head_hexsha": "d3da257812f6f53575117caf959b16291c3bbcb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5657894737, "max_line_length": 152, "alphanum_fraction": 0.5558654192, "include": true, "reason": "import numpy", "num_tokens": 2510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376236, "lm_q2_score": 0.2782567996876011, "lm_q1q2_score": 0.16386240088296655}}
{"text": "#!/usr/bin/env python\nimport argparse\nfrom pathlib import Path\nfrom astropy.time import Time\nfrom scipy.optimize import leastsq\nimport fitsio\nimport numpy as np\nimport textwrap\nfrom . import sdss_paths\n\ntry:\n    from bin import epics_fetch\nexcept ImportError as e:\n    raise ImportError('Please add ObserverTools/bin to your PYTHONPATH:\\n'\n                      '    {}'.format(e))\n\n__version__ = '3.2.1'\n\n\nclass APOGEERaw:\n    \"\"\"A class to parse raw data from APOGEE. The purpose of this class is to\n    read raw image files from /data/apogee/archive, regardless of any future\n    changes in SDSS. This\n    will hopefully help SDSS-V logging.\n\n    Methods:\n        compute_offets: Returns the offsets of an arc/object to compute the\n        relative dither\n\n        ap_test: Returns a list of faint fibers and missing fibers from a flat\n        \"\"\"\n\n    def __init__(self, fil, args, ext=1, ):\n        self.file = Path(fil)\n        if not self.file.exists():\n            raise FileNotFoundError(f\"Could not find file {self.file.absolute()}\")\n        self.ext = ext\n        self.args = args\n        header = fitsio.read_header(fil, ext=ext)\n        self.telemetry = epics_fetch.telemetry\n        dithers = self.telemetry.get('25m:apogee:ditherNamedPositions',\n                                     start=(Time.now() - 5 / 24 / 60).datetime,\n                                     end=Time.now().datetime,\n                                     scan_archives=False, interpolation='raw')\n        # layer = self.image[layer_ind]\n        # An A dither is DITHPIX=12.994, a B dither is DITHPIX=13.499\n        if (header['DITHPIX'] - dithers.values[-1][0]) < 0.05:\n            self.dither = 'A'\n        elif (header['DITHPIX'] - dithers.values[-1][1]) < 0.05:\n            self.dither = 'B'\n        else:\n            self.dither = '{:.1f}'.format(header['DITHPIX'])\n        self.exp_time = header['EXPTIME']\n        self.isot = Time(header['DATE-OBS'])  # Local\n        self.plate_id = header['PLATEID']\n        self.cart_id = header['CARTID']\n        self.exp_id = int(str(fil).split('-')[-1].split('.')[0])\n        if header['EXPTYPE'].capitalize() == 'Arclamp':\n            if header['LAMPUNE']:\n                self.exp_type = 'UNe Arc'\n            elif header['LAMPTHAR']:\n                self.exp_type = 'ThAr Arc'\n            elif \"FPI\" in header[\"OBSCMNT\"]:\n                self.exp_type = \"FPI Lamp\"\n            else:\n                print('Could not process exposure type of {}'.format(self.file))\n        else:\n            self.exp_type = header['EXPTYPE'].capitalize()\n        self.n_read = header['NREAD']\n        self.lead = header['PLATETYP']\n        self.img_type = header['IMAGETYP'].capitalize()\n        if header['EXPTYPE'] == 'OBJECT':\n            self.seeing = header['SEEING']\n        else:\n            self.seeing = 0.0\n\n        self.quickred_data = np.array([[]])\n        self.quickred_file = ''\n        self.utr_file = ''\n        self.utr_data = np.array([[]])\n\n    # noinspection PyTupleAssignmentBalance,PyTypeChecker\n    def compute_offset(self, fibers=(30, 35), w0=939, dw=40, sigma=1.2745):\n        \"\"\"This is based off of apogeeThar.OneFileFitting written by Elena. It\n        is supposed to generate a float for the pixel offsets of an APOGEE\n        ThAr cal. Here is how it works:\n        It opens a quickred file, which is of shape n_fiber*n_dispersion_pixels,\n        and then it averages the fibers inside the fibers tuple. It then based\n        off of the provided w0 (mean) and sigma, it creates a gaussian function\n        and then creates a function called err_func that compares the gaussian\n        with a slice of the data, from w0-dw/2 to w0+dw/2. It then uses scipy's\n        least squared equation solver to find the difference between w0 given as\n        an input and the actual w0 of the spectral line. This only works if you\n        pick a prominent line to go off of. The default parameters are given for\n        ThAr lines, but UNe lines could also be used, with the following inputs:\n        fibers: (30, 35)\n        w0: 1761\n        dw: 20\n        sigma: 3\n        \"\"\"\n        w0 = int(w0)\n        dw = int(dw)\n        mjd = self.file.absolute().parent.name\n        self.quickred_file = (self.file.absolute().parent.parent.parent\n                              / 'quickred/{}/ap1D-a-{}.fits.fz'\n                                ''.format(mjd, self.exp_id))\n        try:\n            if not self.quickred_data:\n                self.quickred_data = fitsio.read(self.quickred_file, 1)\n        except OSError as e:\n            if self.args.verbose:\n                print('Offsets for {} produced this error\\n{}'.format(self.file,\n                                                                      e))\n            return np.nan\n        lower = w0 - dw // 2\n        upper = w0 + dw // 2\n        line_inds = np.arange(self.quickred_data.shape[1])[lower:upper]\n        line = np.average(self.quickred_data[fibers[0]:fibers[1], lower:upper],\n                          axis=0)\n\n        def fit_func(w, x):\n            return np.exp(-0.5 * ((x - w) / sigma) ** 2)\n\n        def err_func(w, x, y):\n            return fit_func(w, x) - y\n\n        w_model, success = leastsq(err_func, w0, args=(line_inds, line))\n\n        diff = w_model[0] - w0\n        if np.abs(diff) > 10:\n            print('A large dither was reported for exposure {}: {:.3f}'\n                  '\\n  This may mean the zero point needs to be'\n                  ' adjusted, currently it is {}'\n                  ''.format(self.exp_id, diff, w0))\n        return diff\n\n    def ap_test(self, ws=(900, 910), master_col=None, plot=False, legacy=False,\n                dome_flat_shape=None, n_fibers=300, print_it=False):\n        if master_col is None:\n            raise ValueError(\"APTest didn't receive a valid master_col: {}\"\n                             \"\".format(master_col))\n        if legacy:\n            mjd = self.file.absolute().parent.name\n            self.utr_file = sdss_paths.ap_utr / f\"{mjd}/apRaw-{self.exp_id}.fits\"\n            if not self.utr_file.exists():\n                raise FileNotFoundError(f\"Couldn't fine the file: {self.utr_file.as_posix()}\")\n            try:\n                self.utr_data = fitsio.read(self.utr_file, 0)\n            except OSError as e:\n                if self.args.verbose:\n                    print('APTest for {} produced this error\\n{}'.format(\n                        self.file, e))\n            slc0 = np.average(self.utr_data[::-1, ws[0]:ws[1]], axis=1)\n            # print(slc0.mean(), slc0.shape, slc0[0])\n            slc = np.zeros(n_fibers)\n            for j in range(n_fibers):\n                for k in range(10):\n                    if dome_flat_shape[j, k] != 0:\n                        slc[j] += slc0[dome_flat_shape[j, k]]\n            # print(slc.mean(), slc.shape, slc[100])\n\n        else:\n            if self.quickred_data.size == 0:\n                mjd = self.file.absolute().parent.name\n                self.quickred_file = (self.file.absolute().parent.parent.parent\n                                      / 'quickred/{}/ap1D-a-{}.fits.fz'\n                                        ''.format(mjd, self.exp_id))\n                try:\n                    self.quickred_data = fitsio.read(self.quickred_file, 1)\n                except OSError as e:\n                    if self.args.verbose:\n                        print('APTest for {} produced this error\\n{}'.format(\n                            self.file, e))\n            slc = np.average(self.quickred_data[:, ws[0]:ws[1]], axis=1)\n        # print(master_col.mean(), master_col.shape, master_col[100])\n        flux_ratio = slc / master_col\n        # flux_ratio = flux_ratio / flux_ratio.sum() / flux_ratio.shape[0]\n        flux_ratio = flux_ratio / flux_ratio.sum() * flux_ratio.shape[0]\n        # print(flux_ratio.mean(), flux_ratio.shape, flux_ratio[100])\n        bad_data = ((flux_ratio == np.inf)\n                    | (flux_ratio == -np.inf)\n                    | np.isnan(flux_ratio))\n        flux_ratio[bad_data] = np.nan\n        avg = np.nanmean(flux_ratio)\n        missing = flux_ratio < 0.2\n        faint = (flux_ratio < 0.7) & (0.2 <= flux_ratio)\n        bright = ~missing & ~faint\n        i_missing = np.where(missing)[0].astype(int) + 1\n        i_faint = np.where(faint)[0].astype(int) + 1\n        i_bright = np.where(bright)[0]\n        missing_bundles = self.create_bundles(i_missing)\n        faint_bundles = self.create_bundles(i_faint)\n        if print_it:\n\n            print(textwrap.fill('Missing Fibers: {}'.format(missing_bundles),\n                                80))\n            print(textwrap.fill('Faint Fibers: {}'.format(faint_bundles), 80))\n            print()\n\n        if plot:\n            import matplotlib.pyplot as plt\n            fig = plt.figure(figsize=(9, 4))\n            ax = fig.gca()\n            x = np.arange(len(flux_ratio)) + 1\n            ax.plot(x[i_bright], flux_ratio[i_bright], 'o', c=(0, 0.6, 0.533))\n            ax.plot(x[i_faint], flux_ratio[i_faint], 'o', c=(0.933, 0.466, 0.2))\n            ax.plot(x[i_missing], flux_ratio[i_missing], 'o',\n                    c=(0.8, 0.2, 0.066))\n            ax.set_xlabel('Fiber ID')\n            ax.set_ylabel('Throughput Efficiency')\n            ax.axis([1, 300, -0.2, 1.35])\n            ax.grid(True)\n            ax.axhline(0.7, c=(0, 0.6, 0.533))\n            ax.axhline(0.2, c=(0.933, 0.466, 0.2))\n            ax.set_title('APOGEE Fiber Relative Intensity {}'.format(\n                self.exp_id), size=15)\n            fig.show()\n\n        return missing_bundles, faint_bundles, avg\n\n    @staticmethod\n    def create_bundles(subset):\n        \"\"\"This method converts an array of ints into a list of strings that\n        describe a large series of fibers and ints for lone fibers.\n\n        Ex: [1, 2, 3, 5] -> ['1 - 3', 5]\n\n        \"\"\"\n        if len(subset) == 0:\n            return []\n        bundles = [subset[0]]\n        b = 0\n        for fib in subset[1:]:\n            if isinstance(bundles[b], np.int64):\n                if bundles[b] + 1 == fib:\n                    if fib % 30 == 0:\n                        bundles.append(fib)\n                        b += 1\n                    else:\n                        # All strings are created here\n                        bundles[b] = '{} - {}'.format(bundles[b], fib)\n                else:\n                    bundles.append(fib)\n                    b += 1\n            elif isinstance(bundles[b], str):\n                if int(bundles[b].split()[-1]) + 1 == fib:\n                    if fib % 30 == 1:\n                        bundles.append(fib)\n                        b += 1\n                    else:\n                        bundles[b] = '{} - {}'.format(\n                            bundles[b].split()[0], fib)\n                else:\n                    bundles.append(fib)\n                    b += 1\n        # for i, bundle in enumerate(bundles):\n        #     if isinstance(bundle, str):\n        #         low, high = np.array(bundle.split(' - ')).astype(int)\n        #         if ((low - 1) // 30) == ((high - 1) // 30):\n        #             bundles[i] = '{} bundle'.format(low)\n        return bundles\n\n\ndef main():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('-t', '--today', action='store_true',\n                        help=\"Whether or not you want to search for today's\"\n                             \" data, whether or not the night is complete.\"\n                             \" Note: must be run after 00:00Z\")\n    parser.add_argument('-m', '--mjd',\n                        help='If not today (-t), the mjd to search')\n    parser.add_argument('-v', '--verbose', action='count', default=1,\n                        help='Show details, can be stacked')\n    args = parser.parse_args()\n    if args.today:\n        mjd_today = int(Time.now().sjd)\n        data_dir = sdss_paths.ap_archive / f\"{mjd_today}/\"\n    elif args.mjd:\n        data_dir = sdss_paths.ap_archive / f\"{args.mjd}\"\n    else:\n        raise Exception('No date specified')\n    # print(data_dir)\n    for path in data_dir.rglob('apR*.apz'):\n        print(path)\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "99ffcce13c5c60701fee74af68c001c464b94466", "size": 12119, "ext": "py", "lang": "Python", "max_stars_repo_path": "sdssobstools/apogee_data.py", "max_stars_repo_name": "sdss/ObserverTools", "max_stars_repo_head_hexsha": "7f9949341edc91a79dac69d79e24af09e8558ffa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sdssobstools/apogee_data.py", "max_issues_repo_name": "sdss/ObserverTools", "max_issues_repo_head_hexsha": "7f9949341edc91a79dac69d79e24af09e8558ffa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdssobstools/apogee_data.py", "max_forks_repo_name": "sdss/ObserverTools", "max_forks_repo_head_hexsha": "7f9949341edc91a79dac69d79e24af09e8558ffa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9342560554, "max_line_length": 94, "alphanum_fraction": 0.5261985312, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 2991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.31069437683198775, "lm_q1q2_score": 0.1638342832405133}}
{"text": "\"\"\"\nmodel the Subaru optics system\n\nThis is a code modified from Rupert's original optics_propagate.py. This code adds more optics to the system,\nas well as puts the AO, etc in order for Subaru.\n\nHere, we will add the basic functionality of the Subaru Telescope, including the primary, secondary, and AO188.\nThe SCExAO system sits behind the AO188 instrument of Subaru, which is a 188-element AO system located at the\nNasmyth focus (IR) of the telescope. AO188 is a basic 4f-type optical system with a 188 element DM (not perfectly\nrepresented here. Proper will only simulate 2D square DM's, so we use a 14x14 square) inserted in the middle of the\ncollimated beam. This routine simulates an idealized detector at the A0188 focus.\n\nIf you want to scale the intensity of the companion, you can't then normalize the intensity\n(prop_define_entrance) since the normalization is per wavefront, so the companion will normalize to itself\nrather than to the star. Doing it this way may cause confusion, but better than re-writing things in proper\n\nAO188 uses laser guide-star technology. More info here:\nhttps://subarutelescope.org/Introduction/instrument/AO188.html\n\nA more detailed model of SCExAO will be modelled in a SCExAO_optics.py code. However, this routine is designed for\nsimple simulations that need to optimize runtime but still have relevance to the Subaru Telescope.\n\nThis script is meant to override any Subaru/SCExAO-specific parameters specified in the user's params.py\n\"\"\"\n\nimport numpy as np\nfrom inspect import getframeinfo, stack\nimport proper\n\nfrom medis.params import ap, tp, sp\nfrom medis.utils import dprint\nimport medis.optics as opx\nimport medis.aberrations as aber\nimport medis.adaptive as ao\nimport medis.atmosphere as atmos\n\n\n#################################################################################################\n#################################################################################################\n#################################################################################################\n# Defining Subaru parameters\n# ----------------------------\n# According to Iye-et.al.2004-Optical_Performance_of_Subaru:AstronSocJapan, the AO188 uses the IR-Cass secondary,\n# but then feeds it to the IR Nasmyth f/13.6 focusing arrangement. So instead of simulating the full Subaru system,\n# we can use the effective focal length at the Nasmyth focus, and simulate it as a single lens.\ntp.d_nsmyth = 7.9716  # m pupil diameter\ntp.fn_nsmyth = 13.612  # f# Nasmyth focus\ntp.flen_nsmyth = tp.d_nsmyth * tp.fn_nsmyth  # m focal length\ntp.dist_nsmyth_ao1 = tp.flen_nsmyth + 1.14  # m distance secondary to M1 of AO188 (hand-tuned, could update with\n                                            # data from literature)\n\n#  Below are the actual dimenstions of the Subaru telescope.\n# --------------------------------\n# tp.enterence_d = 8.2  # m diameter of primary\n# tp.flen_primary = 15  # m focal length of primary\n# tp.dist_pri_second = 12.652  # m distance primary -> secondary\n# Secondary\ntp.d_secondary = 1.265  # m diameter secondary, used for central obscuration\n# tp.fn_secondary = 12.6\n\n# Re-writing params terms in Subaru-units\n# need this to accurately make atmospheric and aberration maps\ntp.entrance_d = tp.d_nsmyth\ntp.flen_primary = tp.flen_nsmyth\n\n# Effective Primary Aberrations\n# primary_aber_vals = {'a': [7.2e-17, 3e-17],  # power at low spatial frequencies (m4)\n#                      'b': [0.8, 0.2],  # correlation length (b/2pi defines knee)\n#                      'c': [3.1, 0.5],  #\n#                      'a_amp': [0.05, 0.01]}\n# ----------------------------\n# AO188 OAP1\n# Paramaters taken from \"Design of the Subaru laser guide star adaptive optics module\"\n#  Makoto Watanabe et. al. SPIE doi: 10.1117/12.551032\ntp.d_ao1 = 0.20  # m  diamater of AO1\ntp.fl_ao1 = 1.201  # m  focal length OAP1\ntp.dist_ao1_dm = 1.345  # m distance OAP1 to DM\n# OAP1_aber_vals = {'a': [7.2e-17, 3e-17],  # power at low spatial frequencies (m4)\n#                   'b': [0.8, 0.2],  # correlation length (b/2pi defines knee)\n#                   'c': [3.1, 0.5],  #\n#                   'a_amp': [0.05, 0.01]}\n\n# ----------------------------\n# AO188 OAP2\ntp.dist_dm_ao2 = 2.511-tp.dist_ao1_dm  # m distance DM to OAP2\ntp.d_ao2 = 0.2  # m  diamater of AO2\ntp.fl_ao2 = 1.201  # m  focal length AO2\ntp.dist_oap2_focus = 1.261\n# OAP2_aber_vals = {'a': [7.2e-17, 3e-17],  # power at low spatial frequencies (m4)\n#                   'b': [0.8, 0.2],  # correlation length (b/2pi defines knee)\n#                   'c': [3.1, 0.5],  #\n#                   'a_amp': [0.05, 0.01]}\n\ntp.lens_params = [{'aber_vals': [7.2e-17, 0.8, 3.1],\n                   'diam': tp.entrance_d,\n                   'fl': tp.flen_nsmyth,\n                   'dist': tp.dist_nsmyth_ao1,\n                   'name': 'effective-primary'},\n\n                  {'aber_vals': [7.2e-17, 0.8, 3.1],\n                   'diam': tp.d_ao1,\n                   'fl': tp.fl_ao1,\n                   'dist': tp.dist_ao1_dm,\n                   'name': 'ao188-OAP1'},\n\n                  {'aber_vals': [7.2e-17, 0.8, 3.1],\n                   'diam': tp.d_ao2,\n                   'fl': tp.fl_ao2,\n                   'dist': tp.dist_oap2_focus,\n                   'name': 'ao188-OAP2'}\n                    ]\n#################################################################################################\n#################################################################################################\n#################################################################################################\n\ndef Subaru_frontend(empty_lamda, grid_size, PASSVALUE):\n    \"\"\"\n    propagates instantaneous complex E-field thru Subaru from the primary through the AO188\n        AO system in loop over wavelength range\n\n    this function is called a 'prescription' by proper\n\n    uses PyPROPER3 to generate the complex E-field at the source, then propagates it through atmosphere,\n        then telescope, to the focal plane\n    the AO simulator happens here\n    this does not include the observation of the wavefront by the detector\n    :returns spectral cube at instantaneous time in the focal_plane()\n    \"\"\"\n    # print(\"Propagating Broadband Wavefront Through Subaru\")\n\n    # Initialize the Wavefront in Proper\n    wfo = opx.Wavefronts()\n    wfo.initialize_proper()\n\n    # Atmosphere\n    # atmos has only effect on phase delay, not intensity\n    wfo.loop_collection(atmos.add_atmos, PASSVALUE['iter'], plane_name='atmosphere')\n\n    # Defines aperture (baffle-before primary)\n    # Obscurations (Secondary and Spiders)\n    wfo.loop_collection(opx.add_obscurations, d_primary=tp.d_nsmyth, d_secondary=tp.d_secondary, legs_frac=0.05)\n    wfo.loop_collection(proper.prop_circular_aperture,\n                           **{'radius': tp.entrance_d / 2})  # clear inside, dark outside\n    wfo.loop_collection(proper.prop_define_entrance, plane_name='entrance_pupil')  # normalizes abs intensity\n\n    if ap.companion:\n        # Must do this after all calls to prop_define_entrance\n        wfo.loop_collection(opx.offset_companion)\n        wfo.loop_collection(proper.prop_circular_aperture,\n                               **{'radius': tp.entrance_d / 2})  # clear inside, dark outside\n\n    # Test Sampling\n    if sp.verbose:\n        opx.check_sampling(PASSVALUE['iter'], wfo, \"initial\", getframeinfo(stack()[0][0]), units='mm')\n    # Testing Primary Focus (instead of propagating to focal plane)\n    # wfo.loop_collection(opx.prop_pass_lens, tp.flen_nsmyth, tp.flen_nsmyth)  # test only going to prime focus\n\n    ########################################\n    # Subaru Propagation\n    #######################################\n    # Effective Primary\n    # CPA from Effective Primary\n    wfo.loop_collection(aber.add_aber, step=PASSVALUE['iter'], lens_name='ao188-OAP1')\n    # Zernike Aberrations- Low Order\n    # wfo.loop_collection(aber.add_zern_ab, tp.zernike_orders, aber.randomize_zern_values(tp.zernike_orders))\n    wfo.loop_collection(opx.prop_pass_lens, tp.flen_nsmyth, tp.dist_nsmyth_ao1)\n\n    ########################################\n    # AO188 Propagation\n    ########################################\n    # # AO188-OAP1\n    wfo.loop_collection(aber.add_aber, step=PASSVALUE['iter'], lens_name='ao188-OAP1')\n    wfo.loop_collection(opx.prop_pass_lens, tp.fl_ao1, tp.dist_ao1_dm)\n\n    # AO System\n    if tp.use_ao:\n        WFS_map = ao.open_loop_wfs(wfo)\n        wfo.loop_collection(ao.deformable_mirror, WFS_map, PASSVALUE['iter'], plane_name='woofer',\n                            debug=sp.debug)  # don't use PASSVALUE['WFS_map'] here because open loop\n    # ------------------------------------------------\n    wfo.loop_collection(proper.prop_propagate, tp.dist_dm_ao2)\n\n    # AO188-OAP2\n    wfo.loop_collection(aber.add_aber, step=PASSVALUE['iter'], lens_name='ao188-OAP2')\n    # wfo.loop_collection(aber.add_zern_ab, tp.zernike_orders, aber.randomize_zern_values(tp.zernike_orders)/2)\n    wfo.loop_collection(opx.prop_pass_lens, tp.fl_ao2, tp.dist_oap2_focus)\n\n    ########################################\n    # Focal Plane\n    # #######################################\n    # Check Sampling in focal plane\n    if sp.verbose:\n        wfo.loop_collection(opx.check_sampling, PASSVALUE['iter'], \"focal plane\",\n                            getframeinfo(stack()[0][0]), units='nm')\n\n    # wfo.focal_plane fft-shifts wfo from Fourier Space (origin==lower left corner) to object space (origin==center)\n    cpx_planes, sampling = wfo.focal_plane()\n\n    print(f\"Finished datacube at timestep = {PASSVALUE['iter']}\")\n\n    return cpx_planes, sampling\n\n", "meta": {"hexsha": "160b542f8481ef23a5cdc4131d554ad300bac9c1", "size": 9616, "ext": "py", "lang": "Python", "max_stars_repo_path": "simulations/Subaru/Subaru_frontend.py", "max_stars_repo_name": "jessmos/MEDIS", "max_stars_repo_head_hexsha": "eeea1904d31878fb3ad6444af144ee6f1d3ab705", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-25T17:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T17:35:42.000Z", "max_issues_repo_path": "simulations/Subaru/Subaru_frontend.py", "max_issues_repo_name": "jessmos/MEDIS", "max_issues_repo_head_hexsha": "eeea1904d31878fb3ad6444af144ee6f1d3ab705", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-01-22T22:32:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-22T22:32:50.000Z", "max_forks_repo_path": "simulations/Subaru/Subaru_frontend.py", "max_forks_repo_name": "jessmos/MEDIS", "max_forks_repo_head_hexsha": "eeea1904d31878fb3ad6444af144ee6f1d3ab705", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-24T23:25:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-24T23:25:34.000Z", "avg_line_length": 47.3694581281, "max_line_length": 116, "alphanum_fraction": 0.6072171381, "include": true, "reason": "import numpy", "num_tokens": 2475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.310694383214554, "lm_q1q2_score": 0.1638342819902576}}
{"text": "from __future__ import print_function\nimport sys\nimport numpy as np #, scipy as sp, os, gc\nfrom copy import deepcopy\n#from warnings import warn\nfrom time import time\n\nclass BoundaryCondition(object):\n    \"\"\"Base class for applying all types of boundary conditions\"\"\"\n\n    def __init__(self,\n        surface_identification_algorithm='minimisation',\n        modify_linear_mesh_on_projection=False,\n        project_on_curves=True,\n        activate_bounding_box=False,\n        bounding_box_padding=1e-3,\n        has_planar_surfaces=True,\n        solve_for_planar_faces=True,\n        save_dirichlet_data=False,\n        save_nurbs_data=False,\n        filename=None,\n        read_dirichlet_from_file=False,\n        make_loading=\"ramp\",\n        compound_dirichlet_bcs=False\n        ):\n\n        # TYPE OF BOUNDARY: straight or nurbs\n        self.boundary_type = 'straight'\n        self.dirichlet_data_applied_at = 'node' # or 'faces'\n        self.neumann_data_applied_at = 'node' # or 'faces'\n        self.requires_cad = False\n        self.cad_file = None\n        # PROJECTION TYPE FOR CAD EITHER orthogonal OR arc_length\n        self.projection_type = 'orthogonal'\n        # WHAT TYPE OF ARC LENGTH BASED PROJECTION, EITHER 'equal' OR 'fekete'\n        self.nodal_spacing_for_cad = 'equal'\n        self.project_on_curves = project_on_curves\n        self.scale_mesh_on_projection = False\n        self.scale_value_on_projection = 1.0\n        self.condition_for_projection = 1.0e20\n        self.has_planar_surfaces = False\n        self.solve_for_planar_faces = solve_for_planar_faces\n        self.projection_flags = None\n        # FIX DEGREES OF FREEDOM EVERY WHERE CAD PROJECTION IS NOT APPLIED\n        self.fix_dof_elsewhere = True\n        # FOR 3D ARC-LENGTH PROJECTION\n        self.orthogonal_fallback_tolerance = 1.0\n        # WHICH ALGORITHM TO USE FOR SURFACE IDENTIFICATION, EITHER 'minimisation' or 'pure_projection'\n        self.surface_identification_algorithm = surface_identification_algorithm\n        # MODIFY LINEAR MESH ON PROJECTION\n        self.modify_linear_mesh_on_projection = modify_linear_mesh_on_projection\n        # COMPUTE A BOUNDING BOX FOR EACH CAD SURFACE\n        self.activate_bounding_box = activate_bounding_box\n        self.bounding_box_padding = float(bounding_box_padding)\n\n        # FOR IGAKit WRAPPER\n        self.nurbs_info = None\n        self.nurbs_condition = None\n\n        self.analysis_type = 'static'\n        self.analysis_nature = 'linear'\n\n        self.dirichlet_flags = None\n        self.applied_dirichlet = None\n        self.is_dirichlet_computed = False\n        self.columns_out = None\n        self.columns_in = None\n        self.save_dirichlet_data = save_dirichlet_data\n        self.save_nurbs_data = save_nurbs_data\n        self.filename = filename\n        self.read_dirichlet_from_file = read_dirichlet_from_file\n\n        self.neumann_flags = None\n        self.applied_neumann = None\n        self.is_applied_neumann_shape_functions_computed = False\n\n        self.pressure_flags = None\n        self.applied_pressure = None\n        self.pressure_increment = 1.0\n        self.spring_flags = None\n        self.applied_spring = None\n        self.master_faces = None\n        self.slave_faces = None\n        self.applied_connector = None\n        self.connector_flags = None\n        self.connector_elements = None\n        self.connector_faces = None\n        self.is_body_force_shape_functions_computed = False\n\n        self.make_loading = make_loading # \"ramp\" or \"constant\"\n        self.has_step_wise_dirichlet_loading = False\n        self.step_wise_dirichlet_data = None\n        self.has_step_wise_neumann_loading = False\n        self.step_wise_neumann_data = None\n\n        self.compound_dirichlet_bcs = compound_dirichlet_bcs\n\n        # STORE A COPY OF SELF AT THE START TO RESET TO AT THE END\n        self.__save_state__()\n        # FOR INTERNAL PURPOSES WHEN WE DO NOT WANT TO REST\n        self.do_not_reset = True\n\n    def __save_state__(self):\n        self.__initialdict__ = deepcopy(self.__dict__)\n\n    def SetDirichletCriteria(self, func, *args, **kwargs):\n        \"\"\"Applies user defined Dirichlet data to self\n        \"\"\"\n\n        if \"apply\" in kwargs.keys():\n            del kwargs[\"apply\"]\n            self.has_step_wise_dirichlet_loading = True\n            self.step_wise_dirichlet_data = {'func':func, 'args': args, 'kwargs': kwargs}\n            self.dirichlet_flags = func(0, *args, **kwargs)\n            return self.dirichlet_flags\n\n        self.dirichlet_flags = func(*args, **kwargs)\n        return self.dirichlet_flags\n\n    def SetNeumannCriteria(self, func, *args, **kwargs):\n        \"\"\"Applies user defined Neumann data to self\n        \"\"\"\n\n        if \"apply\" in kwargs.keys():\n            del kwargs[\"apply\"]\n            self.has_step_wise_neumann_loading = True\n            self.step_wise_neumann_data = {'func':func, 'args': args, 'kwargs': kwargs}\n            tups = func(0, *args, **kwargs)\n        else:\n            tups = func(*args, **kwargs)\n\n        if not isinstance(tups,tuple) and self.neumann_data_applied_at == \"node\":\n            self.neumann_flags = tups\n            return self.neumann_flags\n        else:\n            self.neumann_data_applied_at == \"face\"\n            if len(tups) !=2:\n                raise ValueError(\"User-defined Neumann criterion function {} \"\n                    \"should return one flag and one data array\".format(func.__name__))\n            self.neumann_flags = tups[0]\n            self.applied_neumann = tups[1]\n            return tups\n\n    def SetRobinCriteria(self, func, *args, **kwargs):\n        \"\"\"Applies user defined Robin data to self, just working on surfaces\n        \"\"\"\n\n        dics = func(*args, **kwargs)\n\n        if isinstance(dics,dict):\n            self.RobinLoadSelector(dics)\n        elif isinstance(dics,tuple):\n            for idic in range(len(dics)):\n                if isinstance(dics[idic],dict):\n                    self.RobinLoadSelector(dics[idic])\n                else:\n                    raise ValueError(\"User-defined Robin criterion function {} \"\n                        \"should return dictionary or tuple(dict,dict,...)\".format(func.__name__))\n        else:\n            raise ValueError(\"User-defined Robin criterion function {} \"\n                \"should return dictionary or tuple\".format(func.__name__))\n\n        return dics\n\n    def RobinLoadSelector(self, tups):\n        if tups['type'] == 'Pressure':\n            self.pressure_flags = tups['flags']\n            self.applied_pressure = tups['data']\n        elif tups['type'] == 'Spring':\n            self.spring_flags = tups['flags']\n            self.applied_spring = tups['data']\n        elif tups['type'] == 'Connector':\n            self.master_faces = tups['master_faces']\n            self.slave_faces = tups['slave_faces']\n            self.applied_connector = tups['data']\n            self.connector_flags = tups['flags']\n            if self.master_faces.shape[0] != self.slave_faces.shape[0]:\n                raise ValueError(\"The size of master_faces and slave_faces should be equal\")\n        elif tups['type'] == 'Dashpot':\n            raise ValueError(\"Surrounding viscoelastic effects not implemented yet\")\n        else:\n            raise ValueError(\"Type force {} not understood or not available. \"\n                \"Types are Pressure, Spring, SpringJoint and Dashpot.\".format(tups['type']))\n\n    def GetConnectorElements(self, mesh):\n        \"\"\" Receive the faces along the surfaces interacting \"\"\"\n\n        # gets the points in the dissection surfaces\n        master_points = np.unique(mesh.faces[self.master_faces,:])\n        slave_points = np.unique(mesh.faces[self.slave_faces,:])\n        # array with the coordinate of the master and slave points\n        master_points_coor = mesh.points[master_points]\n        slave_points_coor = mesh.points[slave_points]\n        # look for a connection between master and slave points\n        from scipy.spatial import cKDTree\n        tree = cKDTree(master_points_coor)\n        distance, id_point = tree.query(slave_points_coor,k=1)\n        pair_node_master_slave = np.c_[master_points[id_point],slave_points]\n        # build the elements\n        nodeperface = mesh.faces.shape[1]\n        connector_elements = np.zeros((self.master_faces.shape[0],2*nodeperface),np.uint64)\n        connector_elements[:,:4] = mesh.faces[self.master_faces]\n        # match the master nodes with its slave within the element\n        faces_s = np.zeros(self.master_faces.shape[0],dtype=np.uint64)\n        for i in range(self.master_faces.shape[0]):\n            iface = self.master_faces[i]\n            jnode_array = np.zeros(nodeperface,dtype=np.uint64)\n            for j in range(nodeperface):\n                inode = mesh.faces[iface,j]\n                idx = np.where(pair_node_master_slave[:,0]==inode)[0]\n                jnode = pair_node_master_slave[idx,1]\n                connector_elements[i,j+nodeperface] = jnode\n                jnode_array[j] = jnode\n            # use the slave point to recover the slave face respect a master face\n            jface_array = np.where(mesh.faces==jnode_array[0])[0]\n            for k in range(1,jnode_array.shape[0]):\n                jface_array = np.append(jface_array, np.where(mesh.faces==jnode_array[k])[0])\n            values, counts = np.unique(jface_array,return_counts=True)\n            jface = values[np.where(counts==nodeperface)[0]]\n            faces_s[i] = jface\n\n        pair_face_master_slave = np.c_[self.master_faces,faces_s]\n        pair_face_master_slave = np.array(pair_face_master_slave, dtype=np.uint64, copy=True)\n\n        self.connector_elements = connector_elements\n        self.connector_faces = pair_face_master_slave\n\n        return\n\n    def GetDirichletBoundaryConditions(self, formulation, mesh, materials=None, solver=None, fem_solver=None):\n\n        nvar = formulation.nvar\n        ndim = formulation.ndim\n        self.columns_in, self.applied_dirichlet = [], []\n\n        #----------------------------------------------------------------------------------------------------#\n        #-------------------------------------- NURBS BASED SOLUTION ----------------------------------------#\n        #----------------------------------------------------------------------------------------------------#\n        if self.boundary_type == 'nurbs':\n\n            tCAD = time()\n\n            if self.read_dirichlet_from_file is False:\n\n                if not self.is_dirichlet_computed:\n                    # GET DIRICHLET BOUNDARY CONDITIONS BASED ON THE EXACT GEOMETRY FROM CAD\n                    if self.requires_cad:\n                        # CALL POSTMESH WRAPPER\n                        nodesDBC, Dirichlet = self.PostMeshWrapper(formulation, mesh, materials, solver, fem_solver)\n                else:\n                    nodesDBC, Dirichlet = self.nodesDBC, self.Dirichlet\n\n\n                # GET DIRICHLET DoFs\n                self.columns_out = (np.repeat(nodesDBC,nvar,axis=1)*nvar +\\\n                 np.tile(np.arange(nvar)[None,:],nodesDBC.shape[0]).reshape(nodesDBC.shape[0],formulation.ndim)).ravel()\n                self.applied_dirichlet = Dirichlet.ravel()\n\n\n                # FIX THE DOF IN THE REST OF THE BOUNDARY\n                if self.fix_dof_elsewhere:\n                    if ndim==2:\n                        rest_dofs = np.setdiff1d(np.unique(mesh.edges),nodesDBC)\n                    elif ndim==3:\n                        rest_dofs = np.setdiff1d(np.unique(mesh.faces),nodesDBC)\n\n                    rest_out = np.repeat(rest_dofs,nvar)*nvar + np.tile(np.arange(nvar),rest_dofs.shape[0])\n                    rest_app = np.zeros(rest_dofs.shape[0]*nvar)\n\n                    self.columns_out = np.concatenate((self.columns_out,rest_out)).astype(np.int64)\n                    self.applied_dirichlet = np.concatenate((self.applied_dirichlet,rest_app))\n\n\n                print('Finished identifying Dirichlet boundary conditions from CAD geometry.',\n                    ' Time taken', time()-tCAD, 'seconds')\n\n            else:\n\n                end = -3\n                self.applied_dirichlet = np.loadtxt(mesh.filename.split(\".\")[0][:end]+\"_dirichlet.dat\",  dtype=np.float64)\n                self.columns_out = np.loadtxt(mesh.filename.split(\".\")[0][:end]+\"_columns_out.dat\")\n\n                print('Finished identifying Dirichlet boundary conditions from CAD geometry.',\n                    ' Time taken', time()-tCAD, 'seconds')\n\n        #----------------------------------------------------------------------------------------------------#\n        #------------------------------------- NON-NURBS BASED SOLUTION -------------------------------------#\n        #----------------------------------------------------------------------------------------------------#\n\n        elif self.boundary_type == 'straight' or self.boundary_type == 'mixed':\n            # IF DIRICHLET BOUNDARY CONDITIONS ARE APPLIED DIRECTLY AT NODES\n            if self.dirichlet_flags is None:\n                raise RuntimeError(\"Dirichlet boundary conditions are not set for the analysis\")\n\n            if self.dirichlet_data_applied_at == 'node':\n                if self.analysis_type == \"dynamic\":\n                    # FOR DYNAMIC ANALYSIS IT IS ASSUMED THAT\n                    # self.columns_in and self.columns_out DO NOT CHANGE\n                    # DURING THE ANALYSIS\n                    if self.dirichlet_flags.ndim == 3:\n                        flat_dirich = self.dirichlet_flags[:,:,0].ravel()\n                        self.columns_out = np.arange(self.dirichlet_flags[:,:,0].size)[~np.isnan(flat_dirich)]\n                        self.applied_dirichlet = np.zeros((self.columns_out.shape[0],self.dirichlet_flags.shape[2]))\n\n                        for step in range(self.dirichlet_flags.shape[2]):\n                            flat_dirich = self.dirichlet_flags[:,:,step].ravel()\n                            self.applied_dirichlet[:,step] = flat_dirich[~np.isnan(flat_dirich)]\n\n                    elif self.dirichlet_flags.ndim == 2:\n                        flat_dirich = self.dirichlet_flags.ravel()\n                        self.columns_out = np.arange(self.dirichlet_flags.size)[~np.isnan(flat_dirich)]\n                        self.applied_dirichlet = flat_dirich[~np.isnan(flat_dirich)]\n                    else:\n                        raise ValueError(\"Incorrect Dirichlet flags for dynamic analysis\")\n\n                else:\n                    flat_dirich = self.dirichlet_flags.ravel()\n                    self.columns_out = np.arange(self.dirichlet_flags.size)[~np.isnan(flat_dirich)]\n                    self.applied_dirichlet = flat_dirich[~np.isnan(flat_dirich)]\n\n        # GENERAL PROCEDURE - GET REDUCED MATRICES FOR FINAL SOLUTION\n        self.columns_out = self.columns_out.astype(np.int64)\n        self.columns_in = np.delete(np.arange(0,nvar*mesh.points.shape[0]),self.columns_out)\n\n        if self.columns_in.shape[0] == 0:\n            warn(\"No Dirichlet boundary conditions have been applied. The system is unconstrained\")\n        if self.columns_out.shape[0] == 0:\n            warn(\"Dirichlet boundary conditions have been applied on the entire mesh\")\n\n        if self.save_dirichlet_data:\n            from scipy.io import savemat\n            diri_dict = {'columns_in':self.columns_in,\n                'columns_out':self.columns_out,\n                'applied_dirichlet':self.applied_dirichlet}\n            savemat(self.filename,diri_dict, do_compression=True)\n\n\n    def ComputeNeumannForces(self, mesh, materials, function_spaces, compute_traction_forces=True, compute_body_forces=False):\n        \"\"\"Compute/assemble traction and body forces\"\"\"\n\n        if self.neumann_flags is None:\n            return np.zeros((mesh.points.shape[0]*materials[0].nvar,1),dtype=np.float64)\n\n        nvar = materials[0].nvar\n        ndim = mesh.InferSpatialDimension()\n\n        if self.neumann_flags.shape[0] == mesh.points.shape[0]:\n            self.neumann_data_applied_at = \"node\"\n        else:\n            if ndim==3:\n                if self.neumann_flags.shape[0] == mesh.faces.shape[0]:\n                    self.neumann_data_applied_at = \"face\"\n            elif ndim==2:\n                if self.neumann_flags.shape[0] == mesh.edges.shape[0]:\n                    self.neumann_data_applied_at = \"face\"\n\n\n        if self.neumann_data_applied_at == 'face':\n            from Kuru.FiniteElements.Assembly import AssembleForces\n            if not isinstance(function_spaces,tuple):\n                raise ValueError(\"Boundary functional spaces not available for computing Neumman and body forces\")\n            else:\n                # CHECK IF A FUNCTION SPACE FOR BOUNDARY EXISTS - SAFEGAURDS AGAINST FORMULATIONS THAT DO NO PROVIDE ONE\n                has_boundary_spaces = False\n                for fs in function_spaces:\n                    if ndim == 3 and fs.ndim == 2:\n                        has_boundary_spaces = True\n                        break\n                    elif ndim == 2 and fs.ndim == 1:\n                        has_boundary_spaces = True\n                        break\n                if not has_boundary_spaces:\n                    from Kuru import QuadratureRule, FunctionSpace\n                    # COMPUTE BOUNDARY FUNCTIONAL SPACES\n                    p = mesh.InferPolynomialDegree()\n                    bquadrature = QuadratureRule(optimal=3, norder=2*p+1,\n                        mesh_type=mesh.boundary_element_type, is_flattened=False)\n                    bfunction_space = FunctionSpace(mesh.CreateDummyLowerDimensionalMesh(),\n                        bquadrature, p=p, equally_spaced=mesh.IsEquallySpaced, use_optimal_quadrature=False)\n                    function_spaces = (function_spaces[0],bfunction_space)\n                    # raise ValueError(\"Boundary functional spaces not available for computing Neumman and body forces\")\n\n            t_tassembly = time()\n            if self.analysis_type == \"static\":\n                F = AssembleForces(self, mesh, materials, function_spaces,\n                    compute_traction_forces=compute_traction_forces, compute_body_forces=compute_body_forces)\n            elif self.analysis_type == \"dynamic\":\n                if self.neumann_flags.ndim==2:\n                    # THE POSITION OF NEUMANN DATA APPLIED AT FACES CAN CHANGE DYNAMICALLY\n                    tmp_flags = np.copy(self.neumann_flags)\n                    tmp_data = np.copy(self.applied_neumann)\n                    F = np.zeros((mesh.points.shape[0]*nvar,self.neumann_flags.shape[1]))\n                    for step in range(self.neumann_flags.shape[1]):\n                        self.neumann_flags = tmp_flags[:,step]\n                        self.applied_neumann = tmp_data[:,:,step]\n                        F[:,step] = AssembleForces(self, mesh, materials, function_spaces,\n                            compute_traction_forces=compute_traction_forces, compute_body_forces=compute_body_forces).flatten()\n\n                    self.neumann_flags = tmp_flags\n                    self.applied_neumann = tmp_data\n                else:\n                    # THE POSITION OF NEUMANN DATA APPLIED AT FACES CAN CHANGE DYNAMICALLY\n                    F = AssembleForces(self, mesh, materials, function_spaces,\n                            compute_traction_forces=compute_traction_forces, compute_body_forces=compute_body_forces).flatten()\n\n            print(\"Assembled external traction forces. Time elapsed is {} seconds\".format(time()-t_tassembly))\n\n\n        elif self.neumann_data_applied_at == 'node':\n            # A DIRICHLET TYPE METHODOLGY FOR APPLYING NEUMANN BOUNDARY CONDITONS (i.e. AT NODES)\n            if self.analysis_type == \"dynamic\":\n                if self.neumann_flags.ndim ==3:\n                    # FOR DYNAMIC ANALYSIS IT IS ASSUMED THAT\n                    # to_apply DOOES NOT CHANGE DURING THE ANALYSIS\n                    flat_neu = self.neumann_flags[:,:,0].ravel()\n                    to_apply = np.arange(self.neumann_flags[:,:,0].size)[~np.isnan(flat_neu)]\n                    F = np.zeros((mesh.points.shape[0]*nvar,self.neumann_flags.shape[2]))\n\n                    for step in range(self.neumann_flags.shape[2]):\n                        flat_neu = self.neumann_flags[:,:,step].ravel()\n                        to_apply = np.arange(self.neumann_flags[:,:,step].size)[~np.isnan(flat_neu)]\n                        F[to_apply,step] = flat_neu[~np.isnan(flat_neu)]\n                else:\n                    F = np.zeros((mesh.points.shape[0]*nvar,1))\n                    flat_neu = self.neumann_flags.ravel()\n                    to_apply = np.arange(self.neumann_flags.size)[~np.isnan(flat_neu)]\n                    applied_neumann = flat_neu[~np.isnan(flat_neu)]\n                    F[to_apply,0] = applied_neumann\n            else:\n                F = np.zeros((mesh.points.shape[0]*nvar,1))\n                flat_neu = self.neumann_flags.ravel()\n                to_apply = np.arange(self.neumann_flags.size)[~np.isnan(flat_neu)]\n                applied_neumann = flat_neu[~np.isnan(flat_neu)]\n                F[to_apply,0] = applied_neumann\n\n        return F\n\n    def ComputeRobinForces(self, mesh, materials, function_spaces, fem_solver, Eulerx, stiffness, F):\n        \"\"\"Compute/assemble traction and body forces\"\"\"\n\n        from Kuru.FiniteElements.Assembly import AssembleRobinForces\n        if not self.pressure_flags is None:\n            K_pressure, F_pressure = AssembleRobinForces(self, mesh,\n                materials[0], function_spaces, fem_solver, Eulerx, 'pressure')\n            stiffness -= K_pressure\n            F -= F_pressure[:,None]\n        if not self.spring_flags is None:\n            K_spring, F_spring = AssembleRobinForces(self, mesh,\n                materials[0], function_spaces, fem_solver, Eulerx, 'spring')\n            stiffness += K_spring\n            F += F_spring[:,None]\n        if not self.connector_elements is None:\n            K_connector, F_connector = AssembleRobinForces(self, mesh,\n                materials[0], function_spaces, fem_solver, Eulerx, 'connector')\n            stiffness += K_connector\n            F += F_connector[:,None]\n\n        return stiffness, F\n\n    def GetReducedMatrices(self, stiffness, F, mass=None, only_residual=False):\n\n        # GET REDUCED FORCE VECTOR\n        F_b = F[self.columns_in,0]\n        if only_residual:\n            return F_b\n\n        # GET REDUCED STIFFNESS MATRIX\n        stiffness_b = stiffness[self.columns_in,:][:,self.columns_in]\n\n        # GET REDUCED MASS MATRIX\n        mass_b = np.array([])\n\n        return stiffness_b, F_b, mass_b\n\n    def ApplyDirichletGetReducedMatrices(self, stiffness, F, AppliedDirichlet, LoadFactor=1., mass=None, only_residual=False):\n        \"\"\"AppliedDirichlet is a non-member because it can be external incremental Dirichlet,\n            which is currently not implemented as member of BoundaryCondition. F also does not\n            correspond to Dirichlet forces, as it can be residual in incrementally linearised\n            framework.\n        \"\"\"\n\n        # # APPLY DIRICHLET BOUNDARY CONDITIONS\n        # for i in range(self.columns_out.shape[0]):\n            # F = F - LoadFactor*AppliedDirichlet[i]*stiffness.getcol(self.columns_out[i])\n\n        # MUCH FASTER APPROACH\n        # F = F - (stiffness[:,self.columns_out]*AppliedDirichlet*LoadFactor)[:,None]\n        nnz_cols = ~np.isclose(AppliedDirichlet,0.0)\n        if self.columns_out[nnz_cols].shape[0]==0:\n            F[self.columns_in] = F[self.columns_in]\n        else:\n            F[self.columns_in] = F[self.columns_in] - (stiffness[self.columns_in,:]\\\n                [:,self.columns_out[nnz_cols]]*AppliedDirichlet[nnz_cols]*LoadFactor)[:,None]\n\n        if only_residual:\n            return F\n\n        # GET REDUCED FORCE VECTOR\n        F_b = F[self.columns_in,0]\n\n        # GET REDUCED STIFFNESS\n        stiffness_b = stiffness[self.columns_in,:][:,self.columns_in]\n\n        # GET REDUCED MASS MATRIX\n        if self.analysis_type != 'static':\n            mass_b = mass[self.columns_in,:][:,self.columns_in]\n            return stiffness_b, F_b, F, mass_b\n\n        return stiffness_b, F_b, F\n\n    def UpdateFixDoFs(self, AppliedDirichletInc, fsize, nvar):\n        \"\"\"Updates the geometry (DoFs) with incremental Dirichlet boundary conditions\n            for fixed/constrained degrees of freedom only. Needs to be applied per time steps\"\"\"\n\n        # GET TOTAL SOLUTION\n        TotalSol = np.zeros((fsize,1))\n        TotalSol[self.columns_out,0] = AppliedDirichletInc\n\n        # RE-ORDER SOLUTION COMPONENTS\n        dU = TotalSol.reshape(int(TotalSol.shape[0]/nvar),nvar)\n\n        return dU\n\n    def UpdateFreeDoFs(self, sol, fsize, nvar):\n        \"\"\"Updates the geometry with iterative solutions of Newton-Raphson\n            for free degrees of freedom only. Needs to be applied per time NR iteration\"\"\"\n\n        # GET TOTAL SOLUTION\n        TotalSol = np.zeros((fsize,1))\n        TotalSol[self.columns_in,0] = sol\n\n        # RE-ORDER SOLUTION COMPONENTS\n        dU = TotalSol.reshape(int(TotalSol.shape[0]/nvar),nvar)\n\n        return dU\n", "meta": {"hexsha": "c7b8970fc8e7d50396a66b84aa58fc027526403b", "size": 25074, "ext": "py", "lang": "Python", "max_stars_repo_path": "Kuru/BoundaryCondition/BoundaryCondition.py", "max_stars_repo_name": "jdlaubrie/Kuru", "max_stars_repo_head_hexsha": "517ff8f88cd8587d259e960c4b8ff5be42e99ca1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Kuru/BoundaryCondition/BoundaryCondition.py", "max_issues_repo_name": "jdlaubrie/Kuru", "max_issues_repo_head_hexsha": "517ff8f88cd8587d259e960c4b8ff5be42e99ca1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Kuru/BoundaryCondition/BoundaryCondition.py", "max_forks_repo_name": "jdlaubrie/Kuru", "max_forks_repo_head_hexsha": "517ff8f88cd8587d259e960c4b8ff5be42e99ca1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-22T10:43:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-22T10:43:44.000Z", "avg_line_length": 46.7798507463, "max_line_length": 127, "alphanum_fraction": 0.6015394432, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.16383428199025754}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nFujifilm F-Gamut Colourspace\n============================\n\nDefines the *Fujifilm F-Gamut* colourspace:\n\n-   :attr:`colour.models.F_GAMUT_COLOURSPACE`.\n\nReferences\n----------\n-   :cite:`Fujifilm2016` : Fujifilm. (2016). F-Log Data Sheet Ver.1.0 (pp.\n    1-4). https://www.fujifilm.com/support/digital_cameras/software/lut/pdf/\\\nF-Log_DataSheet_E_Ver.1.0.pdf\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\n\nfrom colour.colorimetry import ILLUMINANTS\nfrom colour.models.rgb import (RGB_Colourspace, log_encoding_FLog,\n                               normalised_primary_matrix, log_decoding_FLog)\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2020 - Colour Developers'\n__license__ = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-developers@colour-science.org'\n__status__ = 'Production'\n\n__all__ = [\n    'F_GAMUT_PRIMARIES', 'F_GAMUT_WHITEPOINT_NAME', 'F_GAMUT_WHITEPOINT',\n    'F_GAMUT_TO_XYZ_MATRIX', 'XYZ_TO_F_GAMUT_MATRIX', 'F_GAMUT_COLOURSPACE'\n]\n\nF_GAMUT_PRIMARIES = np.array([\n    [0.70800, 0.29200],\n    [0.17000, 0.79700],\n    [0.13100, 0.04600],\n])\n\"\"\"\n*Fujifilm F-Gamut* colourspace primaries.\n\nF_GAMUT_PRIMARIES : ndarray, (3, 2)\n\"\"\"\n\nF_GAMUT_WHITEPOINT_NAME = 'D65'\n\"\"\"\n*Fujifilm F-Gamut* colourspace whitepoint name.\n\nF_GAMUT_WHITEPOINT : unicode\n\"\"\"\n\nF_GAMUT_WHITEPOINT = (ILLUMINANTS['CIE 1931 2 Degree Standard Observer'][\n    F_GAMUT_WHITEPOINT_NAME])\n\"\"\"\n*Fujifilm F-Gamut* colourspace whitepoint.\n\nF_GAMUT_WHITEPOINT : ndarray\n\"\"\"\n\nF_GAMUT_TO_XYZ_MATRIX = normalised_primary_matrix(F_GAMUT_PRIMARIES,\n                                                  F_GAMUT_WHITEPOINT)\n\"\"\"\n*Fujifilm F-Gamut* colourspace to *CIE XYZ* tristimulus values matrix.\n\nF_GAMUT_TO_XYZ_MATRIX : array_like, (3, 3)\n\"\"\"\n\nXYZ_TO_F_GAMUT_MATRIX = np.linalg.inv(F_GAMUT_TO_XYZ_MATRIX)\n\"\"\"\n*CIE XYZ* tristimulus values to *Fujifilm F-Gamut* colourspace matrix.\n\nXYZ_TO_F_GAMUT_MATRIX : array_like, (3, 3)\n\"\"\"\n\nF_GAMUT_COLOURSPACE = RGB_Colourspace(\n    'F-Gamut',\n    F_GAMUT_PRIMARIES,\n    F_GAMUT_WHITEPOINT,\n    F_GAMUT_WHITEPOINT_NAME,\n    F_GAMUT_TO_XYZ_MATRIX,\n    XYZ_TO_F_GAMUT_MATRIX,\n    log_encoding_FLog,\n    log_decoding_FLog,\n)\nF_GAMUT_COLOURSPACE.__doc__ = \"\"\"\n*Fujifilm F-Gamut* colourspace.\n\nReferences\n----------\n:cite:`Fujifilm2016`\n\nF_GAMUT_COLOURSPACE : RGB_Colourspace\n\"\"\"\n", "meta": {"hexsha": "c44b43f755b2cb1c4d67d8eec980ff0f2ccbd3bb", "size": 2434, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/models/rgb/datasets/fujifilm_f_gamut.py", "max_stars_repo_name": "OmarWagih1/colour", "max_stars_repo_head_hexsha": "bdc880a2783ff523dafb19f1233212dd03a639bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-20T03:44:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-20T14:08:41.000Z", "max_issues_repo_path": "colour/models/rgb/datasets/fujifilm_f_gamut.py", "max_issues_repo_name": "OmarWagih1/colour", "max_issues_repo_head_hexsha": "bdc880a2783ff523dafb19f1233212dd03a639bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/models/rgb/datasets/fujifilm_f_gamut.py", "max_forks_repo_name": "OmarWagih1/colour", "max_forks_repo_head_hexsha": "bdc880a2783ff523dafb19f1233212dd03a639bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0927835052, "max_line_length": 77, "alphanum_fraction": 0.7144617913, "include": true, "reason": "import numpy", "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.23651623106411435, "lm_q1q2_score": 0.16382107132780163}}
{"text": "#!/usr/bin/env python\n\"\"\"\nSatellite lensing EMCEE wrapper\n\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nimport emcee\nimport numpy\nimport os\nimport sys\nfrom astropy.io.fits import BinTableHDU, Column, Header, PrimaryHDU\nfrom itertools import count, izip\nfrom numpy import all as npall, array, append, concatenate, dot, inf, isnan\nfrom numpy import isfinite, log, log10, outer, pi, sqrt, transpose, zeros\nfrom os import remove\nfrom os.path import isfile\nfrom time import ctime\nimport pickle\n\nfrom . import sampling_utils\n\n\ndef run_emcee(hm_options, sampling_options, args):\n    # load halo model setup\n    function, params, param_types, prior_types, \\\n        val1, val2, val3, val4, params_join, hm_functions, \\\n        starting, meta_names, fits_format = hm_options\n    # load MCMC sampler setup\n    datafile, datacols, covfile, covcols, exclude_bins, output, \\\n        sampler, nwalkers, nsteps, nburn, \\\n        thin, k, threads, sampler_type, update_freq = sampling_options\n\n    #function = cloud.serialization.cloudpickle.dumps(model)\n    #del model\n    #print(function)\n\n    #pickle.dumps(function)\n    #print('pickled')\n\n    if args.demo:\n        print(' ** Running demo only **')\n    elif isfile(output):\n        msg = 'Warning: output file %s exists. Overwrite? [y/N] ' %output\n        answer = raw_input(msg)\n        if len(answer) == 0:\n            exit()\n        if answer.lower() not in ('y', 'yes'):\n            exit()\n    if not args.demo:\n        print('Started -', ctime())\n\n    #load data files\n    Ndatafiles = len(datafile)\n    R, esd = sampling_utils.load_datapoints(datafile, datacols, exclude_bins)\n    Nobsbins, Nrbins = esd.shape\n    rng_obsbins = xrange(Nobsbins)\n    rng_rbins = xrange(Nrbins)\n    # load covariance\n    cov = sampling_utils.load_covariance(covfile, covcols,\n                                         Nobsbins, Nrbins, exclude_bins)\n    cov, icov, likenorm, esd_err, cov2d = cov\n\n    # needed for offset central profile\n    R, Rrange = sampling_utils.setup_integrand(R, k)\n    angles = numpy.linspace(0, 2*pi, 540)\n    val1 = numpy.append(val1, [Rrange, angles])\n\n    # identify fixed and free parameters\n    jfixed = (prior_types == 'fixed') | (prior_types == 'read') | \\\n             (prior_types == 'function')\n    jfree = ~jfixed\n    ndim = len(val1[(jfree)])\n    if len(starting) != ndim:\n        msg = 'ERROR: Not all starting points defined for free parameters.'\n        print(msg)\n        exit()\n    print('starting =', starting)\n\n    # identify the function. Raises an AttributeError if not found\n    #function = model.model()\n    #sat_profile = params.sat_profile()\n    #group_profile = params.group_profile()\n    #function = model\n\n    if not args.demo:\n        hdrfile = '.'.join(output.split('.')[:-1]) + '.hdr'\n        print('Printing header information to', hdrfile)\n        hdr = open(hdrfile, 'w')\n        print('Started', ctime(), file=hdr)\n        print('datafile', ','.join(datafile), file=hdr)\n        print('cols', ','.join([str(c) for c in datacols]), file=hdr)\n        print('covfile', covfile, file=hdr)\n        print('covcols', ','.join([str(c) for c in covcols]), file=hdr)\n        if exclude_bins is not None:\n            print('exclude_bins', ','.join([str(c) for c in exclude_bins]),\n                  file=hdr)\n        print('model %s' %function, file=hdr)\n        for p, pt, v1, v2, v3, v4 in izip(params, prior_types,\n                                        val1, val2, val3, val4):\n            try:\n                line = '%s  %s  ' %(p, pt)\n                line += ','.join(numpy.array(v1, dtype=str))\n            except TypeError:\n                line = '%s  %s  %s  %s  %s  %s' \\\n                    %(p, pt, str(v1), str(v2), str(v3), str(v4))\n            print(line, file=hdr)\n        print('nwalkers  {0:5d}'.format(nwalkers), file=hdr)\n        print('nsteps    {0:5d}'.format(nsteps), file=hdr)\n        print('nburn     {0:5d}'.format(nburn), file=hdr)\n        print('thin      {0:5d}'.format(thin), file=hdr)\n        hdr.close()\n\n    # are we just running a demo?\n    if args.demo:\n        import pylab\n        from matplotlib import cm\n        def plot_demo(ax, Ri, gt, gt_err, f, fsat, fhost):\n            Ri = Ri[1:]\n            ax.errorbar(Ri, gt, yerr=gt_err, fmt='ko', ms=10)\n            ax.plot(Ri, f, 'r-', lw=3)\n            ax.plot(Ri, fsat, 'b--', lw=2)\n            ax.plot(Ri, fhost, 'g-.', lw=2)\n            ax.set_xscale('log')\n            for x, fi, gti, gei in izip(Ri, f, gt, gt_err):\n                ax.annotate('{0:.2f}'.format((fi-gti)/gei),\n                            xy=(x,gti+20), ha='center', va='bottom',\n                            color='r')\n            return\n        val1[jfree] = starting\n        if params_join is not None:\n            v1 = list(val1)\n            for p in params_join:\n                # without this list comprehension numpy can't keep track of the\n                # data type. I believe this is because there are elements of\n                # different types in val1 and therefore its type is not \n                # well defined (so it gets \"object\")\n                v1[p[0]] = array([val1[pj] for pj in p])\n            # need to delete elements backwards to preserve indices\n            aux = [[v1.pop(pj) for pj in p[1:][::-1]]\n                   for p in params_join[::-1]]\n            val1 = v1 #array(v1) ??\n        model = function(val1, R)\n        residuals = esd - model[0]\n        dof = esd.size - starting.size - 1\n        chi2 = array([dot(residuals[m], dot(icov[m][n], residuals[n]))\n                      for m in rng_obsbins for n in rng_obsbins]).sum()\n        print(' ** chi2 = %.2f/%d **' %(chi2, dof))\n        fig, axes = pylab.subplots(figsize=(4*Ndatafiles,4), ncols=Ndatafiles)\n        if Ndatafiles == 1:\n            plot_demo(axes, R, esd, esd_err, model[0], model[1], model[2])\n        else:\n            for i in izip(axes, R, esd, esd_err, model[0], model[1], model[2]):\n                plot_demo(*i)\n        if npall(esd - esd_err > 0):\n            for ax in axes:\n                ax.set_yscale('log')\n        fig.tight_layout(w_pad=0.01)\n        pylab.show()\n        fig, axes = pylab.subplots(figsize=(8,8), nrows=cov.shape[0],\n                                   ncols=cov.shape[0])\n        for m, axm in enumerate(axes):\n            for n, axmn in enumerate(axm):\n                axmn.imshow(cov[m][-n-1][::-1], interpolation='nearest',\n                            cmap=cm.CMRmap_r)\n        fig.tight_layout()\n        pylab.show()\n        exit()\n\n    # set up starting point for all walkers\n    po = starting * numpy.random.uniform(0.99, 1.01, size=(nwalkers,ndim))\n    lnprior = zeros(ndim)\n    mshape = meta_names.shape\n    # this assumes that all parameters are floats -- can't imagine a\n    # different scenario\n    metadata = [[] for m in meta_names]\n    for j in xrange(len(metadata)):\n        for f in fits_format[j]:\n            if len(f) == 1:\n                metadata[j].append(zeros(nwalkers*nsteps/thin))\n            else:\n                size = [nwalkers*nsteps/thin, int(f[:-1])]\n                # only for ESDs. Note that there will be trouble if outputs\n                # other than the ESD have the same length, so avoid them at\n                # all cost.\n                if exclude_bins is not None \\\n                    and size[1] == esd.shape[-1]+len(exclude_bins):\n                    size[1] -= len(exclude_bins)\n                metadata[j].append(zeros(size))\n    metadata = [array(m) for m in metadata]\n    fail_value = []\n    for m in metadata:\n        shape = list(m.shape)\n        shape.remove(max(shape))\n        fail_value.append(zeros(shape))\n    # the last numbers are data chi2, lnLdata, lnPderived\n    for i in xrange(4):\n        fail_value.append(9999)\n\n    sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob,\n                                    threads=threads,\n                                    args=(R,esd,icov,function,\n                                          params,prior_types[jfree],\n                                          val1,val2,val3,val4,params_join,\n                                          jfree,lnprior,likenorm,\n                                          rng_obsbins,fail_value,\n                                          array,dot,inf,izip,outer,pi))\n                                          #isfinite,log,log10\n                                          #outer,sqrt,zeros))\n    # burn-in\n    if nburn > 0:\n        pos, prob, state, blobs = sampler.run_mcmc(po, nburn)\n        sampler.reset()\n        print('{0} Burn-in steps finished ({1})'.format(nburn, ctime()))\n    else:\n        pos = po\n    # incrementally save output\n    chi2 = [zeros(nwalkers*nsteps/thin) for i in xrange(4)]\n    nwritten = 0\n    for i, result in enumerate(sampler.sample(pos, iterations=nsteps,\n                                              thin=thin)):\n        # make sure that nwalkers is a factor of this number!\n        if i*nwalkers % update_freq == nwalkers:\n            out = write_to_fits(output, chi2, sampler, nwalkers, thin,\n                                params, jfree, metadata, meta_names, i,\n                                nwritten, Nobsbins,\n                                array, BinTableHDU, Column, ctime, enumerate,\n                                isfile, izip, transpose, xrange)\n            metadata, nwriten = out\n\n    hdr = open(hdrfile, 'a')\n    try:\n        print('acceptance_fraction =', sampler.acceptance_fraction)\n        print('acceptance_fraction =', file=hdr, end=' ')\n        for af in sampler.acceptance_fraction:\n            print(af, file=hdr, end=' ')\n    except ImportError:\n        pass\n    try:\n        print('acor =', sampler.acor)\n        print('\\nacor =', file=hdr, end=' ')\n        for ac in sampler.acor:\n            print(ac, file=hdr, end=' ')\n    except ImportError:\n        pass\n    try:\n        print('acor_time =', sampler.get_autocorr_time())\n        print('\\nacor_time =', file=hdr, end=' ')\n        for act in sampler.get_autocorr_time():\n            print(act, file=hdr, end=' ')\n    except AttributeError:\n        pass\n    print('\\nFinished', ctime(), file=hdr)\n    hdr.close()\n    print('Saved to', hdrfile)\n\n    cmd = 'mv {0} {1}'.format(output, output.replace('.fits', '.temp.fits'))\n    print(cmd)\n    os.system(cmd)\n    print('Saving everything to {0}...'.format(output))\n    print(i, nwalkers, nwritten)\n    write_to_fits(output, chi2, sampler, nwalkers, thin,\n                  params, jfree, metadata, meta_names, i+1,\n                  nwritten, Nobsbins,\n                  array, BinTableHDU, Column, ctime, enumerate,\n                  isfile, izip, transpose, xrange)\n    os.remove(output.replace('.fits', '.temp.fits'))\n    print('Everything saved to {0}!'.format(output))\n    return\n\ndef lnprob(theta, R, esd, icov, function, params, prior_types,\n           val1, val2, val3, val4, params_join, jfree, lnprior, likenorm,\n           rng_obsbins, fail_value, array, dot, inf, izip, outer, pi):\n           #array, dot, inf, izip, isfinite, log, log10, sqrt):\n    \"\"\"\n    Probability of a model given the data, i.e., log-likelihood of the data\n    given a model, times the prior on the model parameters.\n\n    Parameters\n    ----------\n        theta\n            whatever *free* parameters are received by the model selected.\n        R\n            projected distances from the satellite\n        esd\n            Excess surface density at distances R\n        esd_err\n            Uncertainties on the ESD\n        function\n            the model used to calculate the likelihood\n        prior_types\n            one value per parameter in *theta*, {'normal', 'uniform', 'fixed'}\n        val1\n            depends on each prior_type:\n                -normal : the mean of the gaussian\n                -uniform : the minimum allowed value\n                -fixed : the fixed value\n        val2\n            depends on each prior_type:\n                -normal : the half-width of the gaussian\n                -uniform : the maximum allowed value\n                -fixed : ignored (but must be there)\n        jfree\n            indices of the free values\n        lnprior\n            just a placeholder, should be an array with a length\n            equal to theta, so that it doesn't have to be defined every\n            time\n\n    \"\"\"\n    _log = log\n    v1free = val1[jfree]\n    v2free = val2[jfree]\n    v3free = val3[jfree]\n    v4free = val4[jfree]\n    if not isfinite(v1free.sum()):\n        return -inf, fail_value\n    # satellites cannot be more massive than the group!\n    #if theta[params[jfree] == 'Msat'] >= theta[params[jfree] == 'Mgroup']:\n        #return -inf, fail_value\n    # not normalized yet\n    j = (prior_types == 'normal')\n    lnprior[j] = array([-(v-v1)**2 / (2*v2**2) - _log(2*pi*v2**2)/2\n                        if v3 <= v <= v4 else -inf\n                        for v, v1, v2, v3, v4\n                        in izip(theta[j], v1free[j], v2free[j],\n                                v3free[j], v4free[j])])\n    j = (prior_types == 'lognormal')\n    lnprior[j] = array([-(log10(v)-v1)**2 / (2*v2**2) - _log(2*pi*v2**2)/2\n                        if v3 <= v <= v4 else -inf\n                        for v, v1, v2, v3, v4\n                        in izip(theta[j], v1free[j], v2free[j],\n                                v3free[j], v4free[j])])\n    j = (prior_types == 'uniform')\n    lnprior[j] = array([0-_log(v2-v1) if v1 <= v <= v2 else -inf\n                        for v, v1, v2\n                        in izip(theta[j], v1free[j], v2free[j])])\n    # note that exp is not normalized\n    j = (prior_types == 'exp')\n    lnprior[j] = array([v**v1 if v2 <= v <= v3 else -inf\n                        for v, v1, v2, v3\n                        in izip(theta[j], v1free[j], v2free[j], v3free[j])])\n    lnprior_total = lnprior.sum()\n    if not isfinite(lnprior_total):\n        return -inf, fail_value\n    # all other types ('fixed', 'read') should not contribute to the prior\n    # run the given model\n    v1 = val1.copy()\n    v1[jfree] = theta\n    if params_join is not None:\n        v1j = list(v1)\n        for p in params_join:\n            # without this list comprehension numpy can't keep track of the\n            # data type. I believe this is because there are elements of\n            # different types in val1 and therefore its type is not \n            # well defined (so it gets \"object\")\n            v1j[p[0]] = array([v1[pi] for pi in p])\n        # need to delete elements backwards to preserve indices\n        aux = [[v1j.pop(pi) for pi in p[1:][::-1]]\n                for p in params_join[::-1]]\n        v1 = v1j #array(v1j) ??\n\n    model = function(v1, R)\n    # no covariance\n    #chi2 = (((esd-model[0]) / esd_err) ** 2).sum()\n    # full covariance included\n    residuals = esd - model[0]\n    chi2 = array([dot(residuals[m], dot(icov[m][n], residuals[n]))\n                  for m in rng_obsbins for n in rng_obsbins]).sum()\n    if not isfinite(chi2):\n        return -inf, fail_value\n    # remember that the last value returned by the models must be a lnprior\n    # from the derived parameters\n    lnlike = -chi2/2. + likenorm\n    model.append(lnprior_total)\n    model.append(chi2)\n    model.append(lnlike)\n    return lnlike + model[-3] + lnprior_total, model\n\ndef write_to_fits(output, chi2, sampler, nwalkers, thin, params, jfree,\n                  metadata, meta_names, iternum, nwritten,\n                  Nobsbins, array, BinTableHDU, Column, ctime, enumerate,\n                  isfile, izip, transpose, xrange):\n    nexclude = len(chi2)\n    lnprior, lnPderived, chi2, lnlike = chi2\n    if isfile(output):\n        remove(output)\n    chain = transpose(sampler.chain, axes=(2,1,0))\n    columns = [Column(name=param, format='E', array=data[:iternum].flatten())\n               for param, data in izip(params[jfree], chain)]\n    columns.append(Column(name='lnprob', format='E',\n                          array=sampler.lnprobability.T[:iternum].flatten()))\n    if len(meta_names) > 0:\n        # save only the last chunk (starting from t),\n        # all others are already in metadata.\n        # NOTE that this is only implemented for a model with the\n        # same format as fiducial()\n        for j, blob in izip(xrange(nwritten, iternum),\n                            sampler.blobs[nwritten:]):\n            data = [transpose([b[i] for b in blob])\n                    for i in xrange(len(blob[0])-nexclude)]\n            # re-arrange blobs\n            if Nobsbins == 1:\n                for i in xrange(len(data)):\n                    if len(data[i].shape) == 2:\n                        data[i] = array([b[i] for b in blob])\n            else:\n                for i in xrange(len(data)):\n                    if len(data[i].shape) == 3:\n                        data[i] = transpose([b[i] for b in blob],\n                                            axes=(1,0,2))\n            # store data\n            for k in xrange(len(data)):\n                for i in xrange(len(data[k])):\n                    metadata[k][i][j*nwalkers:(j+1)*nwalkers] = data[k][i]\n            lnPderived[j*nwalkers:(j+1)*nwalkers] = array([b[-4]\n                                                           for b in blob])\n            lnprior[j*nwalkers:(j+1)*nwalkers] = array([b[-3] for b in blob])\n            chi2[j*nwalkers:(j+1)*nwalkers] = array([b[-2] for b in blob])\n            lnlike[j*nwalkers:(j+1)*nwalkers] = array([b[-1] for b in blob])\n        columns.append(Column(name='lnprior', format='E', array=lnprior))\n        columns.append(Column(name='lnPderived', format='E',\n                              array=lnPderived))\n        columns.append(Column(name='chi2', format='E', array=chi2))\n        columns.append(Column(name='lnlike', format='E', array=lnlike))\n        # this handles exclude_bins properly\n        for name, val in izip(meta_names, metadata):\n            for name_i, val_i in izip(name, val):\n                try:\n                    fmt = '{0}E'.format(val_i.shape[1])\n                except IndexError:\n                    fmt = 'E'\n                columns.append(Column(name=name_i, array=val_i, format=fmt))\n        nwritten = iternum * nwalkers\n    fitstbl = BinTableHDU.from_columns(columns)\n    fitstbl.writeto(output)\n    print('Saved to {0} with {1} samples'.format(output, iternum*nwalkers),\n          end=' ')\n    if thin > 1:\n        print('(printing every {0}th sample)'.format(thin), end=' ')\n    print('- {0}'.format(ctime()))\n    return metadata, nwritten\n", "meta": {"hexsha": "524fcb315de774a15c35f6b65042e71af58fbf46", "size": 18460, "ext": "py", "lang": "Python", "max_stars_repo_path": "astro/ggl/sampler.py", "max_stars_repo_name": "cristobal-sifon/astro", "max_stars_repo_head_hexsha": "e3ca00bebc5dbdd33e2df8df30191cc54c17f722", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "astro/ggl/sampler.py", "max_issues_repo_name": "cristobal-sifon/astro", "max_issues_repo_head_hexsha": "e3ca00bebc5dbdd33e2df8df30191cc54c17f722", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-01-28T18:27:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-11T13:29:11.000Z", "max_forks_repo_path": "astro/ggl/sampler.py", "max_forks_repo_name": "cristobal-sifon/astro", "max_forks_repo_head_hexsha": "e3ca00bebc5dbdd33e2df8df30191cc54c17f722", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-06T14:29:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T14:29:13.000Z", "avg_line_length": 41.6704288939, "max_line_length": 79, "alphanum_fraction": 0.5420368364, "include": true, "reason": "import numpy,from numpy,from astropy", "num_tokens": 4801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.29746995506106744, "lm_q1q2_score": 0.16378914828206068}}
{"text": "import theano\nimport theano.tensor as T\n\nfrom nn.layers.core import Unit\nfrom nn.utils import logsumexp\n\n\nclass SeqLabelAlg(Unit):\n    def __init__(self, name='SeqLabelModel'):\n        super(SeqLabelAlg, self).__init__(name=name)\n\n    def viterbi(self, emit_scores, trans_scores):\n        \"\"\"\n        :param emit_scores: 1D: n_words, 2D: batch_size, 3D: n_labels\n        :param trans_scores: 1D: n_words, 2D: n_labels\n        :return: 1D: n_words; 2D: batch_size, elem=label id\n        \"\"\"\n        [scores, labels], _ = theano.scan(fn=self._viterbi_forward,\n                                          sequences=[emit_scores[1:]],\n                                          outputs_info=[emit_scores[0], None],\n                                          non_sequences=trans_scores)\n\n        label_max_last = T.argmax(scores[-1], axis=1)\n        labels_max, _ = theano.scan(fn=self._viterbi_backward,\n                                    sequences=labels[::-1],\n                                    outputs_info=label_max_last)\n\n        y = T.zeros(shape=(emit_scores.shape[0], emit_scores.shape[1]), dtype='int32')\n        y = T.set_subtensor(y[-1], label_max_last)\n        y = T.set_subtensor(y[:-1], labels_max[::-1])\n        return y\n\n    @staticmethod\n    def _viterbi_forward(e_t, score_prev, trans):\n        \"\"\"\n        :param e_t: 1D: batch_size, 2D: n_labels\n        :param score_prev: 1D: batch_size, 2D: n_labels\n        :param trans: 1D: n_labels, 2D, n_labels\n        :return: max_scores_t: 1D: batch_size, 2D: n_labels\n        :return: max_labels_t: 1D: batch_size, 2D: n_labels\n        \"\"\"\n        score = score_prev.dimshuffle(0, 'x', 1) + trans + e_t.dimshuffle(0, 1, 'x')\n        max_scores_t, max_labels_t = T.max_and_argmax(score, axis=2)\n        return max_scores_t, max_labels_t\n\n    @staticmethod\n    def _viterbi_backward(labels_t, label_max):\n        \"\"\"\n        :param labels_t: 1D: batch_size, 2D: n_labels; elem=label id\n        :param label_max: 1D: batch_size; elem=label id\n        :return: 1D: batch_size; elem=label id\n        \"\"\"\n        return labels_t[T.arange(labels_t.shape[0]), label_max]\n\n\nclass CRF(SeqLabelAlg):\n    def __init__(self,\n                 input_dim,\n                 output_dim,\n                 use_bias=True,\n                 weight_init='xavier',\n                 bias_init='zero'):\n        super(CRF, self).__init__(name='CRF(%dx%d)' % (input_dim, output_dim))\n        self.W = self._set_param(shape=(input_dim, output_dim),\n                                 init_type=weight_init,\n                                 name='W_crf')\n        self.W_t = self._set_param(shape=(output_dim, output_dim),\n                                   init_type=weight_init,\n                                   name='W_tran_crf')\n\n        if use_bias:\n            self.b = self._set_param(shape=output_dim,\n                                     init_type=bias_init,\n                                     name='b_crf')\n            self.params = [self.W, self.W_t, self.b]\n        else:\n            self.b = None\n            self.params = [self.W, self.W_t]\n\n    def forward(self, x):\n        emit_scores = T.dot(x, self.W)\n        if self.b:\n            emit_scores = emit_scores + self.b\n        return emit_scores\n\n    def get_y_proba(self, emit_scores, y_true):\n        \"\"\"\n        :param emit_scores: 1D: n_words, 2D: batch_size, 3D: n_labels\n        :param y_true: 1D: n_words, 2D: batch_size\n        :return: 1D: batch_size; elem=log probability\n        \"\"\"\n        # 1D: batch_size, 2D: n_labels\n        z_score0 = emit_scores[0]\n        # 1D: batch_size; elem=path score\n        y_score0 = z_score0[T.arange(z_score0.shape[0]), y_true[0]]\n\n        inputs = [emit_scores[1:], y_true[1:]]\n        [_, y_scores, z_scores], _ = theano.scan(fn=self._forward_step,\n                                                 sequences=inputs,\n                                                 outputs_info=[y_true[0], y_score0, z_score0],\n                                                 non_sequences=self.W_t)\n\n        y_score = y_scores[-1]\n        z_score = logsumexp(z_scores[-1], axis=1).flatten()\n\n        return y_score - z_score\n\n    @staticmethod\n    def _forward_step(h_t, y_t, y_prev, y_score_prev, z_score_prev, trans):\n        \"\"\"\n        :param h_t: 1D: batch_size, 2D: n_labels\n        :param y_t: 1D: batch_size\n        :param y_prev: 1D: batch_size\n        :param y_score_prev: 1D: batch_size\n        :param z_score_prev: 1D: batch_size, 2D: n_labels\n        :param trans: 1D: n_labels, 2D, n_labels\n        \"\"\"\n        # 1D: batch_size\n        y_score_t = y_score_prev + trans[y_t, y_prev] + h_t[T.arange(h_t.shape[0]), y_t]\n        # 1D: batch_size, 2D: n_labels, 3D: n_labels\n        z_sum = z_score_prev.dimshuffle(0, 'x', 1) + trans\n        # 1D: batch_size, 2D: n_labels\n        z_score_t = logsumexp(z_sum, axis=2).reshape(h_t.shape) + h_t\n        return y_t, y_score_t, z_score_t\n\n    def get_y_pred(self, emit_scores):\n        \"\"\"\n        :param emit_scores: 1D: n_words, 2D: batch_size, 3D: n_labels\n        :return: 1D: batch_size, 2D: n_words; elem=label id\n        \"\"\"\n        return self.viterbi(emit_scores=emit_scores, trans_scores=self.W_t).dimshuffle(1, 0)\n", "meta": {"hexsha": "e387edce186bd512360cf85a817bb6602be3cc7f", "size": 5209, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/nn/layers/seqlabel.py", "max_stars_repo_name": "OE-Heart/span-based-srl", "max_stars_repo_head_hexsha": "a03b46a5ea4c59e14bea80ea724b0de276df4bc1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2018-10-05T21:48:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T10:24:39.000Z", "max_issues_repo_path": "src/nn/layers/seqlabel.py", "max_issues_repo_name": "OE-Heart/span-based-srl", "max_issues_repo_head_hexsha": "a03b46a5ea4c59e14bea80ea724b0de276df4bc1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2018-10-21T14:45:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T14:25:29.000Z", "max_forks_repo_path": "src/nn/layers/seqlabel.py", "max_forks_repo_name": "OE-Heart/span-based-srl", "max_forks_repo_head_hexsha": "a03b46a5ea4c59e14bea80ea724b0de276df4bc1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-10-16T07:00:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T13:10:47.000Z", "avg_line_length": 39.4621212121, "max_line_length": 94, "alphanum_fraction": 0.555960837, "include": true, "reason": "import theano", "num_tokens": 1399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.29746994260479465, "lm_q1q2_score": 0.16378913703630746}}
{"text": "# -*- coding: utf-8 -*-\nimport numpy as np\nfrom pyGRBz.utils import mag2Jy, convAB\nfrom astropy.table import Table, Column\nfrom pyGRBz.extinction_correction import correct_MW_ext\nfrom pyGRBz.io_grb import load_telescope_transmissions\nimport imp\n\n\ndef load_sys_response(data, wavelength, path):\n    \"\"\" Load the system throuput curves for each filter in the data\n\n    Returns\n    -------\n    sys_rep: astropy Table\n    \"\"\"\n    # works for constant wvl_step\n    dwvl = np.gradient(wavelength)\n\n    sys_res = []\n    tel_name = []\n    tel_band = []\n    wvl_eff = []\n    width = []\n    zp = []\n\n    # Sort the telescope used\n    for tel in data.group_by([\"telescope\", \"band\"]).groups.keys:\n        # Import the filter throughput curve only once if filter used several\n        # times (for a light curve for instance)\n        tel_name.append(tel[\"telescope\"])\n        tel_band.append(tel[\"band\"])\n\n        # Import the throughput curve\n        filter_trans = load_telescope_transmissions(\n            {\"telescope\": tel[\"telescope\"], \"band\": tel[\"band\"], \"path\": path},\n            wavelength,\n        )\n        sys_res.append(filter_trans)\n\n        # calculate the effective wavelength\n        a = np.trapz(wavelength * filter_trans, wavelength)\n        b = np.trapz(filter_trans, wavelength)\n        wvl_eff.append(a / b)\n\n        # Calculate the width of the band\n        mask = filter_trans > 0.05 * max(filter_trans)\n\n        width.append(wavelength[mask][-1] - wavelength[mask][0])\n\n        # print (tel['telescope'], tel['band'], a/b, width[-1])\n        # Not sure it is used anymore ... to be checked. Formula also to check\n        zp.append(2.5 * np.log10(np.sum(filter_trans * dwvl, axis=0)) + 23.9)\n\n    sys_res_table = Table(\n        [tel_name, tel_band, wvl_eff, width, sys_res, zp],\n        names=[\"telescope\", \"band\", \"wvl_eff\", \"band_width\",\n               \"sys_response\", \"zeropoint\"])\n\n    # Sort the table by telescope names and ascending eff. wavelength\n    sys_res_table.sort([\"telescope\", \"wvl_eff\"])\n    return sys_res_table\n\n\ndef formatting_data(data, system_response, grb_info, wavelength,\n                    dustrecalib=\"yes\"):\n    \"\"\" \"\"\"\n    try:\n        _, path_dust_map, _ = imp.find_module(\"pyGRBaglow\")\n    except:\n        print(\"path to pyGRBaglow can not be found.\")\n\n    dustmapdir = path_dust_map + \"/galactic_dust_maps\"\n\n    #  Add filter info to data (throughut curve,eff. wvl and width)\n    col_band_width = Column(name=\"band_width\", data=np.zeros(len(data)))\n    col_band_effwvl = Column(name=\"eff_wvl\", data=np.zeros(len(data)))\n    col_band_zp = Column(name=\"zeropoint\", data=np.zeros(len(data)))\n    col_band_sysres = Column(\n        name=\"sys_response\", data=np.zeros((len(data), len(wavelength)))\n    )\n    data.add_columns([col_band_effwvl, col_band_width, col_band_zp,\n                      col_band_sysres])\n\n    for table in data.group_by([\"telescope\", \"band\"]).groups.keys:\n        # print (table)\n        mask1 = data[\"telescope\"] == table[\"telescope\"]\n        mask1[mask1 == True] = data[mask1][\"band\"] == table[\"band\"]\n        mask2 = system_response[\"telescope\"] == table[\"telescope\"]\n        mask2[mask2 == True] = system_response[mask2][\"band\"] == table[\"band\"]\n        # print (system_response[mask3][mask4]['sys_response'])\n        # print (system_response[mask3][mask4]['sys_response'][0])\n\n        width = []\n        effwvl = []\n        zp = []\n        sys_res = []\n        for i in range(np.sum(mask2)):\n            width.append(system_response[mask2][\"band_width\"][0])\n            effwvl.append(system_response[mask2][\"wvl_eff\"][0])\n            zp.append(system_response[mask2][\"zeropoint\"][0])\n            sys_res.append(system_response[mask2][\"sys_response\"][0])\n        data[\"band_width\"][mask1] = width\n        data[\"eff_wvl\"][mask1] = effwvl\n        data[\"zeropoint\"][mask1] = zp\n        data[\"sys_response\"][mask1] = sys_res\n\n    # Convert vega magnitudes in AB if needed\n    mask1 = data[\"phot_sys\"] == \"vega\"\n    if mask1.any():\n        # print ('some vega')\n\n        #  If a Vega-AB correction is present in the file use this value\n\n        if \"ABcorr\" in data.colnames:\n            mask2 = (data[\"phot_sys\"] == \"vega\") & (~data[\"ABcorr\"].mask)\n            if mask2.any():\n                # print ('AB corr')\n                for table in data[mask2]:\n                    mask3 = mask2.copy()\n\n                    mask3[mask3 == True] = data[mask3][\"Name\"] == table[\"Name\"]\n                    mask3[mask3 == True] = (\n                        data[mask3][\"telescope\"] == table[\"telescope\"]\n                    )\n                    mask3[mask3 == True] = data[mask3][\"band\"] == table[\"band\"]\n                    mask3[mask3 == True] = (\n                        data[mask3][\"time_since_burst\"] == table[\"time_since_burst\"]\n                    )\n\n                    newABmag = table[\"mag\"] + table[\"ABcorr\"]\n                    photsys = \"AB\"\n                    # substitute the vega magnitudes by AB ones\n                    data[\"mag\"][mask3] = newABmag\n                    data[\"phot_sys\"][mask3] = photsys\n\n            #  When no AB correction is given in input file, compute it\n            mask2 = (data[\"phot_sys\"] == \"vega\") & (data[\"ABcorr\"].mask)\n            if mask2.any():\n\n                # print ('convAB')\n                for table in data[mask2]:\n                    mask3 = mask2.copy()\n\n                    mask3[mask3 == True] = data[mask3][\"Name\"] == table[\"Name\"]\n                    mask3[mask3 == True] = (\n                        data[mask3][\"telescope\"] == table[\"telescope\"]\n                    )\n                    mask3[mask3 == True] = data[mask3][\"band\"] == table[\"band\"]\n                    mask3[mask3 == True] = (\n                        data[mask3][\"time_since_burst\"] == table[\"time_since_burst\"]\n                    )\n\n                    newABmag = table[\"mag\"] + convAB(wavelength, table[\"sys_response\"])\n                    photsys = \"AB\"\n                    # substitute the vega magnitudes by AB ones\n                    data[\"mag\"][mask3] = newABmag\n                    data[\"phot_sys\"][mask3] = photsys\n\n        else:\n            # print ('convAB')\n            for table in data[mask1]:\n                mask3 = mask1.copy()\n\n                mask3[mask3 == True] = data[mask3][\"Name\"] == table[\"Name\"]\n                mask3[mask3 == True] = data[mask3][\"telescope\"] == table[\"telescope\"]\n                mask3[mask3 == True] = data[mask3][\"band\"] == table[\"band\"]\n                mask3[mask3 == True] = (\n                    data[mask3][\"time_since_burst\"] == table[\"time_since_burst\"]\n                )\n\n                newABmag = table[\"mag\"] + convAB(wavelength,\n                                                 table[\"sys_response\"])\n                photsys = \"AB\"\n                # substitute the vega magnitudes by AB ones\n                data[\"mag\"][mask3] = newABmag\n                data[\"phot_sys\"][mask3] = photsys\n\n    # Correct for galactic extinction\n    data = correct_MW_ext(data, grb_info, wavelength,\n                          dustmapdir=dustmapdir,\n                          recalibration=dustrecalib)\n\n    # Add Flux to the seds\n    convert_dict = {\"photometry_system\": \"AB\"}\n\n    flux = mag2Jy(convert_dict, data[\"mag\"] - data[\"ext_mag\"]) * 1e6\n    flux_err = np.array(abs(flux * -0.4 * np.log(10) * data[\"mag_err\"]))\n    mask = data[\"detection\"] == -1\n    if mask.any():\n        flux_err[mask] = flux[mask] / 2.0\n\n    col_flux = Column(name=\"flux\", data=flux, unit=\"microJy\")\n    col_flux_err = Column(name=\"flux_err\", data=flux_err, unit=\"microJy\")\n\n    data.add_columns([col_flux, col_flux_err])\n\n    data.sort([\"Name\", \"eff_wvl\"])\n    return data\n", "meta": {"hexsha": "11e638cda6caad79afd95861c018681c24296f08", "size": 7677, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyGRBz/formatting.py", "max_stars_repo_name": "dcorre/pyGRBz", "max_stars_repo_head_hexsha": "4955e9454a19fcc409649ad623c31d5bec66cc64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-21T15:06:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T07:22:09.000Z", "max_issues_repo_path": "pyGRBz/formatting.py", "max_issues_repo_name": "dcorre/pyGRBz", "max_issues_repo_head_hexsha": "4955e9454a19fcc409649ad623c31d5bec66cc64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyGRBz/formatting.py", "max_forks_repo_name": "dcorre/pyGRBz", "max_forks_repo_head_hexsha": "4955e9454a19fcc409649ad623c31d5bec66cc64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-07-29T10:42:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T07:15:53.000Z", "avg_line_length": 38.385, "max_line_length": 87, "alphanum_fraction": 0.549172854, "include": true, "reason": "import numpy,from astropy", "num_tokens": 1909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3174262720448507, "lm_q1q2_score": 0.16367130764003696}}
{"text": "\"\"\"\nObject to Object relationship models\n\"\"\"\nimport numpy as np\nfrom scipy.spatial.distance import euclidean\nimport ipdb\nfrom collections import OrderedDict\n\n# Params\nOBJ_W_SIZE = 0.02  # Object width size\nNEAR_DIST_TH = 0.1  # Near distance threshold\nHOLD_DIST_TH = 0.02 # Holding distance threshold\nIN_DIST_TH = 0.01 # Object in target distance threshold\n\nclass SpatialObject(object):\n\n    OBJ_CLASSES = OrderedDict([\n        (\"eef\", 0),\n        (\"can\", 1),\n        (\"milk\", 2),\n        (\"bread\", 3),\n        (\"cereal\", 4),\n        (\"roundnut\", 5),\n        (\"squarenut\", 6)\n    ])\n\n    def __init__(self, name, pos, orient, is_robot=False):\n        \"\"\" Constructor\n\n            Args\n            -----\n            name: str\n                Object name\n            pos: np.ndarray\n                Position vector (3,1)\n            orient: np.ndarray \n                Orientation Quaternion  (4,1)\n        \"\"\"\n        self.name = name\n        self.pos = pos\n        self.orient = orient\n        self.is_robot = is_robot\n        self.encode_onehot()\n\n    def encode_onehot(self):\n        \"\"\" Encode into One-hot vector\n        \"\"\"\n        self.encoding = np.array([ \n                1. if self.name == _c else 0. \\\n                    for _c in self.OBJ_CLASSES \n            ])\n\n    def __repr__(self):\n        return \"<\" + self.name + \">\"\n\n\nclass Relation(object):\n\n    def __init__(self, name, validator):\n        \"\"\" Constructor\n        \n            Args\n            -----\n            name : str\n                Name of the relation\n            validator : function | lambda\n                Validation function\n        \"\"\"\n        self._name = name\n        self._f_validator = validator\n\n    @property\n    def name(self):\n        \"\"\" Name getter\n        \"\"\"\n        return self._name\n\n    @property\n    def validator(self):\n        \"\"\" Validator Function getter\n        \"\"\"\n        return self._f_validator\n    \n    def __call__(self, *args):\n        \"\"\" Relation validation call\n\n            Returns\n            -----\n            int (0 or 1)\n                Returns weather the relation applies or not\n        \"\"\"\n        return self._f_validator(*args)\n\n\nclass O2ORelation(object):\n    \n    # Object to object relations\n    O2O_RELATIONS = OrderedDict([\n        (\"on\", \"is_on\"),\n        (\"in\", \"is_in\"),\n        (\"front\", \"is_front\"),\n        (\"behind\", \"is_behind\"),\n        (\"right_side\", \"is_right\"),\n        (\"left_side\", \"is_left\"),\n        (\"above\", \"is_above\"),\n        (\"below\", \"is_below\"),\n        (\"holding\", \"is_holding\"),\n        (\"near\", \"is_near\")\n    ])\n    # o2o_index = {_o: _j for _j, _o in enumerate(O2O_RELATIONS)}\n\n    def __init__(self, *args):\n        \"\"\" Constructor\n        \"\"\"\n        self._rep = [] # Representation vector\n        self.objs = args  # Objects to compute the relationship between\n        # initializes all possible relations\n        for _n, _func in self.O2O_RELATIONS.items():\n            self.__dict__[_n] = Relation(\n                _n, \n                getattr(self, _func)\n            )\n        # Compute rules\n        self.evaluate()\n        \n    @property\n    def rep(self):\n        \"\"\" Relations getter\n        \"\"\"\n        return self._rep\n    \n    def decode(self):\n        \"\"\" Decode relationships for human interpretation\n        \"\"\"\n        o_reps = [_o.__repr__() for _o  in self.objs]\n        return [(\"_\" \n                + list(self.O2O_RELATIONS.keys())[_i].upper()\n                + \"_\").join(o_reps) \\\n            for _i, _r in enumerate(self._rep) if _r\n        ]\n    \n    def __repr__(self):\n        return '<' + ','.join(self.decode()) \\\n                +  \":\" + super().__repr__().split('.')[-1]\n    \n    def evaluate(self):\n        \"\"\" Evaluate over all registered relations,\n            set which of them are valid with 1 and 0 otherwise,\n            to return a one-hot vector.\n        \"\"\"\n        # Call all rules\n        _evals = [self.__dict__[_r]() \\\n            for _r in self.O2O_RELATIONS.keys()]\n        # Set the relations representation\n        self._rep = np.array(_evals)\n\n    @staticmethod\n    def zeros():\n        \"\"\" Return zero vector with \n            O2O Relations cardinality\n\n            Returns\n            -----\n            np.ndarray \n                Zero Vector\n        \"\"\"\n        return np.zeros((len(O2ORelation.O2O_RELATIONS),))\n\n    def default(self):\n        \"\"\" Default Rule function\n        \"\"\"\n        # print(\"Executing DEFAULT..\")\n        return 0.\n\n    def is_on(self):\n        \"\"\" ON rule validator: returns 1 in case\n            the 1st object has greater Z and \n            the X and Y absolute difference is less or equal\n            to the OBJ_W_SIZE, otherwise returns 0\n        \"\"\"\n        # print(\"Executing IS_ON..\")\n        if self.objs[0].pos[2] > self.objs[1].pos[2]:\n            _xdif = abs(self.objs[0].pos[0] - self.objs[1].pos[0])\n            _ydif = abs(self.objs[0].pos[1] - self.objs[1].pos[1])\n            if (_xdif <= OBJ_W_SIZE) and (_ydif <= OBJ_W_SIZE):\n                return 1.\n        return 0.\n    \n    def is_below(self):\n        \"\"\" BELOW rule validator: 1 if the 1st object \n            has lower Z than the 2nd one, otherwise returns 0\n        \"\"\"\n        # print(\"Executing IS_BELOW..\")\n        if self.objs[0].pos[2] < self.objs[1].pos[2]:\n            return 1.\n        return 0.\n    \n    def is_above(self):\n        \"\"\" ABOVE rule validator: 1 if the 1st object \n            has greater Z than the 2nd one, otherwise returns 0\n        \"\"\"\n        # print(\"Executing IS_ABOVE..\")\n        if self.objs[0].pos[2] > self.objs[1].pos[2]:\n            return 1.\n        return 0.\n    \n    def is_front(self):\n        \"\"\" FRONT rule validator: 1 if the 1st object \n            has greater X than the 2nd one, otherwise returns 0\n        \"\"\"\n        # print(\"Executing IS_FRONT..\")\n        if self.objs[0].pos[0] > self.objs[1].pos[0]:\n            return 1.\n        return 0.\n    \n    def is_behind(self):\n        \"\"\" BEHING rule validator: 1 if the 1st object \n            has lower X than the 2nd one, otherwise returns 0\n        \"\"\"\n        # print(\"Executing IS_BEHIND..\")\n        if self.objs[0].pos[0] < self.objs[1].pos[0]:\n            return 1.\n        return 0.\n    \n    def is_right(self):\n        \"\"\" RIGHT rule validator: 1 if the 1st object \n            has greater Y than the 2nd one, otherwise returns 0\n        \"\"\"\n        # print(\"Executing IS_RIGHT..\")\n        if self.objs[0].pos[1] > self.objs[1].pos[1]:\n            return 1.\n        return 0.\n    \n    def is_left(self):\n        \"\"\" LEFT rule validator: 1 if the 1st object \n            has lower Y than the 2nd one, otherwise returns 0\n        \"\"\"\n        # print(\"Executing IS_LEFT..\")\n        if self.objs[0].pos[1] < self.objs[1].pos[1]:\n            return 1.\n        return 0.\n\n    def is_near(self):\n        \"\"\" NEAR rule validator: 1 if the euclidean distance\n            between the 2 objects is less or equal to the\n            NEAR_DIST_TH and greater than HOLD_DIST_TH, \n            otherwise 0\n        \"\"\"\n        # print(\"Executing IS_NEAR..\")\n        _dist = euclidean(self.objs[0].pos, self.objs[1].pos)\n        if  _dist <= NEAR_DIST_TH and _dist > HOLD_DIST_TH:\n            return 1.\n        return 0.\n    \n    def is_holding(self):\n        \"\"\" HOLD rule validator: 1 if the euclidean distance\n            between the 2 objects is less or equal to the\n            HOLD_DIST_TH, otherwise 0\n        \"\"\"\n        # print(\"Executing IS_HOLDING..\")\n        if not self.objs[0].is_robot:\n            return 0.\n        _dist = euclidean(self.objs[0].pos, self.objs[1].pos)\n        if  _dist <= HOLD_DIST_TH:\n            return 1.\n        return 0.\n\n    def is_in(self, ):\n        \"\"\" IN rule validator: 1 if the euclidean distance\n            between the 1st object and the 2nd one is less \n            or equal to the IN_DIST_TH\n        \"\"\"\n        # print(\"Executing IS_IN..\")\n        _dist = euclidean(self.objs[0].pos, self.objs[1].pos)\n        if  _dist <= IN_DIST_TH:\n            return 1.\n        return 0.\n", "meta": {"hexsha": "5e8ef58583029346bc36dbb4fcf413967cc55159", "size": 8031, "ext": "py", "lang": "Python", "max_stars_repo_path": "robosuite/models/relation.py", "max_stars_repo_name": "jorgeviz/robosuite", "max_stars_repo_head_hexsha": "7fca50214dfa4978c9f3b5db0016b35a2920b0c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "robosuite/models/relation.py", "max_issues_repo_name": "jorgeviz/robosuite", "max_issues_repo_head_hexsha": "7fca50214dfa4978c9f3b5db0016b35a2920b0c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "robosuite/models/relation.py", "max_forks_repo_name": "jorgeviz/robosuite", "max_forks_repo_head_hexsha": "7fca50214dfa4978c9f3b5db0016b35a2920b0c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8884892086, "max_line_length": 71, "alphanum_fraction": 0.5188644004, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.16367130431058896}}
{"text": "\"\"\"\nUtilities for making finder charts and overlay images for ALMA proposing\n\"\"\"\nimport string\n\nimport numpy as np\n\nfrom astropy import wcs\nfrom astropy import log\nfrom astropy import units as u\nfrom astropy.io import fits\n\nfrom astroquery.skyview import SkyView\nfrom astroquery.alma import Alma\n\ndef pyregion_subset(region, data, mywcs):\n    \"\"\"\n    Return a subset of an image (`data`) given a region.\n\n    Parameters\n    ----------\n    region : `pyregion.parser_helper.Shape`\n        A Shape from a pyregion-parsed region file\n    data : np.ndarray\n        An array with shape described by WCS\n    mywcs : `astropy.wcs.WCS`\n        A world coordinate system describing the data\n    \"\"\"\n    import pyregion\n\n    shapelist = pyregion.ShapeList([region])\n    if shapelist[0].coord_format not in ('physical','image'):\n        # Requires astropy >0.4...\n        # pixel_regions = shapelist.as_imagecoord(self.wcs.celestial.to_header())\n        # convert the regions to image (pixel) coordinates\n        celhdr = mywcs.sub([wcs.WCSSUB_CELESTIAL]).to_header()\n        pixel_regions = shapelist.as_imagecoord(celhdr)\n    else:\n        # For this to work, we'd need to change the reference pixel after cropping.\n        # Alternatively, we can just make the full-sized mask... todo....\n        raise NotImplementedError(\"Can't use non-celestial coordinates with regions.\")\n        pixel_regions = shapelist\n\n    # This is a hack to use mpl to determine the outer bounds of the regions\n    # (but it's a legit hack - pyregion needs a major internal refactor\n    # before we can approach this any other way, I think -AG)\n    mpl_objs = pixel_regions.get_mpl_patches_texts()[0]\n\n    # Find the minimal enclosing box containing all of the regions\n    # (this will speed up the mask creation below)\n    extent = mpl_objs[0].get_extents()\n    xlo, ylo = extent.min\n    xhi, yhi = extent.max\n    all_extents = [obj.get_extents() for obj in mpl_objs]\n    for ext in all_extents:\n        xlo = xlo if xlo < ext.min[0] else ext.min[0]\n        ylo = ylo if ylo < ext.min[1] else ext.min[1]\n        xhi = xhi if xhi > ext.max[0] else ext.max[0]\n        yhi = yhi if yhi > ext.max[1] else ext.max[1]\n\n    log.debug(\"Region boundaries: \")\n    log.debug(\"xlo={xlo}, ylo={ylo}, xhi={xhi}, yhi={yhi}\".format(xlo=xlo,\n                                                                  ylo=ylo,\n                                                                  xhi=xhi,\n                                                                  yhi=yhi))\n\n    \n    subwcs = mywcs[ylo:yhi, xlo:xhi]\n    subhdr = subwcs.sub([wcs.WCSSUB_CELESTIAL]).to_header()\n    subdata = data[ylo:yhi, xlo:xhi]\n    \n    mask = shapelist.get_mask(header=subhdr,\n                              shape=subdata.shape)\n    log.debug(\"Shapes: data={0}, subdata={2}, mask={1}\".format(data.shape, mask.shape, subdata.shape))\n    return (xlo,xhi,ylo,yhi),mask\n\n\ndef parse_frequency_support(frequency_support_str):\n    \"\"\"\n    Given a \"Frequency Support\" string from ALMA queries, parse it into a set\n    of frequency ranges\n\n    Example input:\n\n        '[86.26..88.14GHz,976.56kHz, XX YY] U [88.15..90.03GHz,976.56kHz, XX YY] U [98.19..100.07GHz,976.56kHz, XX YY] U [100.15..102.03GHz,976.56kHz, XX YY]'\n    \"\"\"\n    supports = frequency_support_str.split(\"U\")\n    freq_ranges = [(float(sup.strip('[] ').split(\"..\")[0]),\n                    float(sup.strip('[] ').split(\"..\")[1].split(',')[0].strip(string.ascii_letters)))\n                   *u.Unit(sup.strip('[] ').split(\"..\")[1].split(',')[0].strip(string.punctuation+string.digits))\n                   for sup in supports]\n    return u.Quantity(freq_ranges)\n\ndef approximate_primary_beam_sizes(frequency_support_str):\n    \"\"\"\n    Given a frequency support string, return the approximate 12m array beam\n    size using 1.22 lambda / D\n    \"\"\"\n    freq_ranges = parse_frequency_support(frequency_support_str)\n    beam_sizes = [(1.22*fr.mean().to(u.m, u.spectral())/(12*u.m)).to(u.arcsec,\n                                                                     u.dimensionless_angles())\n                  for fr in freq_ranges]\n    return u.Quantity(beam_sizes)\n\n\n\ndef make_finder_chart(target, radius, save_prefix, service=SkyView.get_images,\n                      service_kwargs={'survey':['2MASS-K'], 'pixels':500},\n                      alma_kwargs={'public':False, 'science':False},\n                      private_band_colors=('red','darkred','orange','brown','maroon'),\n                      public_band_colors=('blue','cyan','green','turquoise','teal'),\n                      integration_time_contour_levels=np.logspace(0,5,base=2, num=6),\n                     ):\n    \"\"\"\n    Create a \"finder chart\" showing where ALMA has pointed in various bands,\n    including different color coding for public/private data and each band.\n\n    Contours are set at various integration times.\n\n    Parameters\n    ----------\n    target : `astropy.coordinates` or str\n        A legitimate target name\n    radius : `astropy.units.Quantity`\n        A degree-equivalent radius\n    save_prefix : str\n        The prefix for the output files.  Both .reg and .png files will be written.\n        The .reg files will have the band numbers and public/private appended,\n        while the .png file will be named prefix_almafinderchart.png\n    service : function\n        The `get_images` function of an astroquery service, e.g. SkyView.\n    service_kwargs : dict\n        The keyword arguments to pass to the specified service.  For example,\n        for SkyView, you can give it the survey ID (e.g., 2MASS-K) and the\n        number of pixels in the resulting image.  See the documentation for the\n        individual services for more details.\n    alma_kwargs : dict\n        Keywords to pass to the ALMA archive when querying.  \n    private_band_colors / public_band_colors : tuple\n        A tuple or list of colors to be associated with private/public observations\n        in the various bands\n    integration_time_contour_levels : list or np.array\n        The levels at which to draw contours in units of seconds.  Default is\n        log-spaced (2^n) seconds: [  1.,   2.,   4.,   8.,  16.,  32.])\n    \"\"\"\n    import aplpy\n\n    import pyregion\n    from pyregion.parser_helper import Shape\n\n    log.info(\"Querying {0} for images\".format(service))\n    images = service(target, radius=radius, **service_kwargs)\n\n    log.info(\"Querying ALMA around {0}\".format(target))\n    catalog = Alma.query_region(coordinate=target, radius=radius,\n                                **alma_kwargs)\n\n    primary_beam_radii = [approximate_primary_beam_sizes(row['Frequency support'])\n                          for row in catalog]\n\n    bands = np.unique(catalog['Band'])\n    log.info(\"The bands used include: {0}\".format(bands))\n    band_colors_priv = dict(zip(bands, private_band_colors))\n    band_colors_pub = dict(zip(bands, public_band_colors))\n\n    private_circle_parameters = {band: [(row['RA'],row['Dec'],np.mean(rad).to(u.deg).value)\n                                 for row,rad in zip(catalog, primary_beam_radii)\n                                 if row['Release date']!='' and row['Band']==band]\n                                 for band in bands}\n    public_circle_parameters = {band: [(row['RA'],row['Dec'],np.mean(rad).to(u.deg).value)\n                                 for row,rad in zip(catalog, primary_beam_radii)\n                                 if row['Release date']=='' and row['Band']==band]\n                                 for band in bands}\n\n    unique_private_circle_parameters = {band:\n                                        np.array(list(set(private_circle_parameters[band])))\n                                        for band in bands}\n    unique_public_circle_parameters = {band:\n                                       np.array(list(set(public_circle_parameters[band])))\n                                       for band in bands}\n\n    for band in bands:\n        log.info( \"BAND {0}\".format(band) )\n        privrows = sum((catalog['Band']==band) & (catalog['Release date'] != ''))\n        pubrows  = sum((catalog['Band']==band) & (catalog['Release date'] == ''))\n        log.info(\"PUBLIC:  Number of rows: {0}.  Unique pointings: \"\n                 \"{1}\".format(pubrows,\n                 len(unique_public_circle_parameters[band])))\n        log.info( \"PRIVATE: Number of rows: {0}.  Unique pointings: \"\n                 \"{1}\".format(privrows,\n                 len(unique_private_circle_parameters[band])))\n\n    prv_regions = {band: pyregion.ShapeList([Shape('circle',[x,y,r]) for x,y,r\n                                             in\n                                             private_circle_parameters[band]])\n                   for band in bands}\n    pub_regions = {band: pyregion.ShapeList([Shape('circle',[x,y,r]) for x,y,r\n                                             in\n                                             public_circle_parameters[band]])\n                   for band in bands}\n    for band in bands:\n        circle_pars = np.vstack([x for x in (private_circle_parameters[band],\n                                        public_circle_parameters[band]) if any(x)])\n        for r,(x,y,c) in zip(prv_regions[band]+pub_regions[band],\n                             circle_pars):\n            r.coord_format = 'fk5'\n            r.coord_list = [x,y,c]\n            r.attr = ([], {'color': 'green',  'dash': '0 ',  'dashlist': '8 3',\n                           'delete': '1 ',  'edit': '1 ', 'fixed': '0 ',\n                           'font': '\"helvetica 10 normal roman\"',  'highlite':\n                           '1 ', 'include': '1 ',  'move': '1 ',  'select': '1',\n                           'source': '1',  'text': '', 'width': '1 '})\n            \n        if prv_regions[band]:\n            prv_regions[band].write('{0}_band{1}_private.reg'.format(save_prefix, band))\n        if pub_regions[band]:\n            pub_regions[band].write('{0}_band{1}_public.reg'.format(save_prefix, band))\n\n    prv_mask = {band: fits.PrimaryHDU(prv_regions[band].get_mask(images[0][0]).astype('int'),\n                               header=images[0][0].header) for band in bands\n                if prv_regions[band]}\n    pub_mask = {band: fits.PrimaryHDU(pub_regions[band].get_mask(images[0][0]).astype('int'),\n                               header=images[0][0].header) for band in bands\n                if pub_regions[band]}\n\n    hit_mask_public = {band: np.zeros_like(images[0][0].data) for band in pub_mask}\n    hit_mask_private = {band: np.zeros_like(images[0][0].data) for band in prv_mask}\n    mywcs = wcs.WCS(images[0][0].header)\n\n    for band in bands:\n        log.debug('Band: {0}'.format(band))\n        for row,rad in zip(catalog, primary_beam_radii):\n            shape = Shape('circle', (row['RA'], row['Dec'],np.mean(rad).to(u.deg).value))\n            shape.coord_format = 'fk5'\n            shape.coord_list = (row['RA'], row['Dec'],np.mean(rad).to(u.deg).value)\n            shape.attr = ([], {'color': 'green',  'dash': '0 ',  'dashlist': '8 3 ',\n                               'delete': '1 ',  'edit': '1 ', 'fixed': '0 ',\n                               'font': '\"helvetica 10 normal roman\"',\n                               'highlite': '1 ', 'include': '1 ',  'move': '1 ',\n                               'select': '1 ',  'source': '1',  'text': '',\n                               'width': '1 '})\n            log.debug('{1} {2}: {0}'.format(shape, row['Release date'], row['Band']))\n            if row['Release date']!='' and row['Band']==band and band in prv_mask:\n                (xlo,xhi,ylo,yhi),mask = pyregion_subset(shape,\n                                                         hit_mask_private[band],\n                                                         mywcs) \n                log.debug(\"{0},{1},{2},{3}: {4}\".format(xlo,xhi,ylo,yhi,mask.sum()))\n                hit_mask_private[band][ylo:yhi,xlo:xhi] += row['Integration']*mask\n            if row['Release date']=='' and row['Band']==band and band in pub_mask:\n                (xlo,xhi,ylo,yhi),mask = pyregion_subset(shape,\n                                                         hit_mask_public[band],\n                                                         mywcs) \n                log.debug(\"{0},{1},{2},{3}: {4}\".format(xlo,xhi,ylo,yhi,mask.sum()))\n                hit_mask_public[band][ylo:yhi,xlo:xhi] += row['Integration']*mask\n\n\n\n    fig = aplpy.FITSFigure(images[0])\n    fig.show_grayscale(stretch='arcsinh')\n    for band in bands:\n        if band in pub_mask:\n            fig.show_contour(fits.PrimaryHDU(data=hit_mask_public[band],\n                                             header=images[0][0].header),\n                             levels=integration_time_contour_levels,\n                             colors=[band_colors_pub[band]]*6)\n        if band in prv_mask:\n            fig.show_contour(fits.PrimaryHDU(data=hit_mask_private[band],\n                                             header=images[0][0].header),\n                             levels=integration_time_contour_levels,\n                             colors=[band_colors_priv[band]]*6)\n\n    fig.save('{0}_almafinderchart.png'.format(save_prefix))\n\n    return images, catalog, hit_mask_public, hit_mask_private\n", "meta": {"hexsha": "92647c37fc9a900e737d35ca13ed5d796fa1a118", "size": 13214, "ext": "py", "lang": "Python", "max_stars_repo_path": "astroquery/alma/utils.py", "max_stars_repo_name": "eteq/astroquery", "max_stars_repo_head_hexsha": "70db53f8f047a2ee3481fd3242e6b364bc1ca639", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-20T00:07:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-20T00:07:01.000Z", "max_issues_repo_path": "astroquery/alma/utils.py", "max_issues_repo_name": "eteq/astroquery", "max_issues_repo_head_hexsha": "70db53f8f047a2ee3481fd3242e6b364bc1ca639", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "astroquery/alma/utils.py", "max_forks_repo_name": "eteq/astroquery", "max_forks_repo_head_hexsha": "70db53f8f047a2ee3481fd3242e6b364bc1ca639", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-20T00:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-20T00:07:05.000Z", "avg_line_length": 48.0509090909, "max_line_length": 158, "alphanum_fraction": 0.5560768881, "include": true, "reason": "import numpy,from astropy", "num_tokens": 3080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.16367130098114108}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nSimulate exoplanet transmission and/or emission spectroscopy without\nusing the coronagraph routines. This uses the same telesope and detector\nparameters as the coronagraph model, but does not suppress the star's light.\nAs a result, stellar photons dominate the noise budget.\n\nFor transmission spectroscopy calculations use :class:`TransitNoise`,\nand for emission spectroscopy use :class:`EclipseNoise`. You may also get an\nexample transmission and emission spectrum of the Earth by calling\n:func:`get_earth_trans_spectrum`.\n\n\"\"\"\n\nfrom __future__ import (division as _, print_function as _,\n                absolute_import as _, unicode_literals as _)\n\nimport numpy as np\nimport astropy.units as u\nimport matplotlib.pyplot as plt\nimport sys, os\n\nfrom .noise_routines import *\nfrom .degrade_spec import *\nfrom .observe import random_draw\nfrom .teleplanstar import *\n\n__all__ = [\"TransitNoise\", \"EclipseNoise\", \"get_earth_trans_spectrum\"]\n\nh = 6.62607004e-34\nc = 2.998e8\n\nclass EclipseNoise(object):\n    \"\"\"\n    Simulate exoplanet secondary eclipse emission spectroscopy with a next-generation\n    telescope.\n\n    Parameters\n    ----------\n    telescope : Telescope\n        Initialized object containing ``Telescope`` parameters\n    planet : Planet\n        Initialized object containing ``Planet`` parameters\n    star : Star\n        Initialized object containing ``Star`` parameters\n    tdur : float\n        Transit duration [s]\n    ntran : float\n        Number of transits/eclipses\n    nout : float\n        Number of out-of-eclipse transit durations to observe\n    wantsnr : float, optional\n        Desired signal-to-noise ratio in each pixel\n    FIX_OWA : bool, optional\n        Set to fix OWA at ``OWA*lammin/D``, as would occur if lenslet array is\n        limiting the OWA\n    COMPUTE_LAM : bool, optional\n        Set to compute lo-res wavelength grid, otherwise the grid input as\n        variable ``lam`` is used\n    SILENT : bool, optional\n        Set to suppress print statements\n    NIR : bool, optional\n        Re-adjusts pixel size in NIR, as would occur if a second instrument\n        was designed to handle the NIR\n    THERMAL : bool, optional\n        Set to compute thermal photon counts due to telescope temperature\n    GROUND : bool, optional\n        Set to simulate ground-based observations through atmosphere\n    vod : bool, optional\n        \"Valley of Death\" red QE parameterization from Robinson et al. (2016)\n\n    \"\"\"\n    def __init__(self, tdur    = 3432.,  # TRAPPIST-1e\n                       telescope = Telescope(),\n                       planet = Planet(),\n                       star = Star(),\n                       ntran   = 1,\n                       nout    = 1,\n                       wantsnr = 1000.0,\n                       NIR     = True,\n                       THERMAL = True,\n                       GROUND  = False,\n                       vod     = False,\n                       IMAGE   = False):\n        self.telescope = telescope\n        self.planet    = planet\n        self.star      = star\n        self.tdur      = tdur\n        self.ntran     = ntran\n        self.nout      = nout\n        self.wantsnr   = wantsnr\n        self.NIR       = NIR\n        self.THERMAL   = THERMAL\n        self.GROUND    = GROUND\n        self.vod       = vod\n        self.IMAGE     = IMAGE\n\n        self._computed = False\n\n        return\n\n    def run_count_rates(self, lamhr = None, Fphr = None, Fshr = None):\n        \"\"\"\n        Calculate the photon count rates and signal to noise on a secondary\n        eclipse spectrum observation\n\n        Parameters\n        ----------\n        lamhr : numpy.ndarray\n            Wavelength [$\\mu$m]\n        Fphr : numpy.ndarray\n            Dayside exoplanet TOA flux spectrum [W/m$^2$/$\\mu$]\n        Fshr : numpy.ndarray\n            Stellar flux incident at the planet's TOA [W/m$^2$/$\\mu$]\n\n        Calling ``run_count_rates()`` creates the following attributes for\n        the ``EclipseNoise`` instance:\n\n        Attributes\n        ----------\n        lamhr : array\n            Wavelength [$\\mu$m]\n        Fphr : array\n            Dayside exoplanet TOA flux spectrum [W/m$^2$/$\\mu$]\n        Fshr : array\n            Stellar flux incident at the planet's TOA [W/m$^2$/$\\mu$]\n        cs : array\n            Stellar photon count rate [photons/s]\n        cback : array\n            Background photon count rate [photons/s]\n        cz : array\n            Zodi photon count rate [photons/s]\n        cez : array\n            Exo-zodi photon count rate [photons/s]\n        cth : array\n            Thermal photon count rate [photons/s]\n        cD : array\n            Dark current photon count rate [photons/s]\n        cR : array\n            Read noise photon count rate [photons/s]\n        cmiss : array\n            Occulted stellar photon count rate [photons/s]\n        SNR1 : array\n            S/N for one eclipse\n        SNRn : array\n            S/N for ``ntran`` eclipses\n        tSNR : array\n            Exposure time to ``wantsnr`` [s]\n        nSNR : array\n            Number of eclipses to ``wantsnr``\n        lam : array\n            Observed wavelength grid [$\\mu$m]\n        dlam : array\n            Observed wavelength grid widths [$\\mu$m]\n        FpFslr : array\n            Low-res planet/star flux ratio\n        FpFshr : array\n            High-res planetr/star flux ratio\n        \"\"\"\n\n        self.lamhr = lamhr\n        self.Fphr = Fphr\n        self.Fshr = Fshr\n\n        if self.telescope.A_collect is None:\n            diam_collect = self.telescope.diameter\n        else:\n            diam_collect = 2. * (self.telescope.A_collect / np.pi)**0.5\n\n        # Set the convolution function\n        convolution_function = downbin_spec\n\n        # Does the telescope object already have a wavelength grid?\n        if (self.telescope.lam is None) or (self.telescope.dlam is None):\n            # Create wavelength grid\n            lam, dlam = construct_lam(self.telescope.lammin,\n                                      self.telescope.lammax,\n                                      self.telescope.resolution)\n        else:\n            # Use existing grids\n            lam = self.telescope.lam\n            dlam = self.telescope.dlam\n\n        # Set Quantum Efficiency\n        q = set_quantum_efficiency(lam,\n                                   self.telescope.qe,\n                                   NIR=self.NIR,\n                                   vod=self.vod)\n\n        # Set Dark current and Read noise\n        De = set_dark_current(lam,\n                              self.telescope.darkcurrent,\n                              self.telescope.lammax,\n                              self.telescope.Tdet,\n                              NIR=self.NIR)\n        Re = set_read_noise(lam,\n                            self.telescope.readnoise,\n                            NIR=self.NIR)\n\n        # Set Angular size of lenslet\n        theta = set_lenslet(lam,\n                            self.telescope.lammin,\n                            diam_collect,\n                            self.telescope.X,\n                            NIR=self.NIR)\n\n        # Set throughput\n        #sep  = r/d*np.sin(alpha*np.pi/180.)*np.pi/180./3600. # separation in radians\n        #T = set_throughput(lam, Tput, diam, sep, IWA, OWA, lammin, FIX_OWA=FIX_OWA, SILENT=SILENT)\n        T = self.telescope.throughput * np.ones_like(lam)\n\n        # Apply wavelength-dependent throuput, if needed\n        if self.telescope.Tput_lam is not None:\n            # Bin input throughput curve to native res\n            Tlam = np.interp(lam, self.telescope.Tput_lam[0], self.telescope.Tput_lam[1])\n            # Multiply into regular throughput\n            T = T * Tlam\n\n        # Apply wavelength-dependent quantum efficiency, if needed\n        if self.telescope.qe_lam is not None:\n            # Bin input QE curve to native res\n            qlam = np.interp(lam, self.telescope.qe_lam[0], self.telescope.qe_lam[1])\n            # Multiply into regular QE\n            q = q * qlam\n\n        # Modify throughput by atmospheric transmission if GROUND-based\n        if self.GROUND:\n            # Use SMART calc\n            Tatmos = set_atmos_throughput(lam, dlam, convolution_function)\n            # Multiply telescope throughput by atmospheric throughput\n            T = T * Tatmos\n\n        # Calculate intensity of the planet [W/m^2/um/sr]\n        if Fphr is None:\n            # Using a blackbody\n            Bplan = planck(self.planet.Tplan, lamhr)\n        else:\n            # Using provided TOA planet flux\n            Bplan = Fphr / np.pi\n\n        # Calculate intensity of the star [W/m^2/um/sr]\n        if Fshr is None:\n            # Using a blackbody\n            Bstar = planck(self.star.Teff, lamhr)\n        else:\n            # Using provided TOA stellar flux\n            Bstar = Fshr / ( np.pi*(self.star.Rs*u.Rsun.in_units(u.km)/\\\n                           (self.planet.a*u.AU.in_units(u.km)))**2. )\n\n        # Solid angle in steradians\n        omega_star = np.pi*(self.star.Rs*u.Rsun.in_units(u.km)/\\\n                           (self.planet.distance*u.pc.in_units(u.km)))**2.\n        omega_planet = np.pi*(self.planet.Rp*u.Rearth.in_units(u.km)/\\\n                             (self.planet.distance*u.pc.in_units(u.km)))**2.\n\n        # Fluxes at earth [W/m^2/um]\n        Fs = Bstar * omega_star\n        Fp = Bplan * omega_planet\n        FpFs = Fp/Fs\n\n        # Degrade planet and stellar spectrum to instrument res\n        Fplr = convolution_function(Fp, lamhr, lam, dlam=dlam)\n        Fslr = convolution_function(Fs, lamhr, lam, dlam=dlam)\n        FpFslr = convolution_function(FpFs, lamhr, lam, dlam=dlam)\n\n        # Fraction of planetary signal in Airy pattern\n        fpa = 1.0   # No fringe pattern here --> all of stellar psf falls on CCD\n\n        ########## Calculate Photon Count Rates ##########\n\n        # Planet photon count rate\n        cp = cplan(q, fpa, T, lam, dlam, Fplr, diam_collect)\n\n        # Stellar photon count rate\n        cs = cstar(q, fpa, T, lam, dlam, Fslr, diam_collect)\n\n        # Solar System Zodi count rate\n        cz =  czodi(q, self.telescope.X, T, lam, dlam,\n                    diam_collect, self.planet.MzV)\n\n        # Exo-Zodi count rate\n        cez =  cezodi(q, self.telescope.X, T, lam, dlam, diam_collect,\n                      self.planet.a,\n                      Fstar(lam, self.star.Teff, self.star.Rs, 1., AU=True),\n                      self.planet.Nez, self.planet.MezV)\n\n        # Dark current count rate\n        cD =  cdark(De, self.telescope.X, lam,\n                    diam_collect, theta,\n                    self.telescope.DNHpix, IMAGE=self.IMAGE)\n\n        # Read noise count rate\n        cR =  cread(Re, self.telescope.X, lam, diam_collect,\n                    theta, self.telescope.DNHpix, self.telescope.Dtmax,\n                    IMAGE=self.IMAGE)\n\n        # Thermal background count rate\n        if self.THERMAL:\n            # telescope internal thermal count rate\n            cth =  ctherm(q, self.telescope.X, T, lam, dlam,\n                          diam_collect, self.telescope.Tsys,\n                          self.telescope.emissivity)\n        else:\n            cth = np.zeros_like(cs)\n\n        # Additional background from sky for ground-based observations\n        if self.GROUND:\n\n            if self.GROUND == \"ESO\":\n                # Use ESO SKCALC\n                wl_sky, Isky = get_sky_flux()\n                # Convolve to instrument resolution\n                Itherm = convolution_function(Isky, wl_sky, lam, dlam=dlam)\n            else:\n                # Get SMART computed surface intensity due to sky background\n                Itherm  = get_thermal_ground_intensity(lam, dlam, convolution_function)\n\n            # Compute Earth thermal photon count rate\n            cthe = ctherm_earth(q, self.telescope.X, T, lam, dlam,\n                                diam_collect, Itherm)\n\n            # Add earth thermal photon counts to telescope thermal counts\n            cth = cth + cthe\n\n        # Calculate background photon count rate\n        cback = cz + cez + cth + cD + cR\n\n        # Save count rates as attributes\n        self.cp = cp\n        self.cs = cs\n        self.cback = cback\n        self.cz = cz\n        self.cez = cez\n        self.cth = cth\n        self.cD = cD\n        self.cR = cR\n\n        # Flip the switch\n        self._computed = True\n\n        ########## Calculate SNR-like Quantities ##########\n\n        # Count PLANET photons per eclipse\n        Nplan = self.tdur * 1 * cp\n\n        # Count STELLAR photons per eclipse\n        Nstar = self.tdur * 1 * cs\n\n        # Count BACKGROUND photons per eclipse\n        Nback = self.tdur * 1 * cback\n\n        # Calculate SNR on missing planet photons in one eclipse\n        #   This formula assumes a homogeneous planet disk (i.e. no limb darkening / hot-spots),\n        #   and comes from standard error propigation on the missing photons due to the\n        #   star occulting the planet calculation in terms of observables\n        SNR1 = Nplan / np.sqrt( (1+1./self.nout)*Nstar + 1./self.nout*Nplan+(1+1./self.nout)*Nback)\n\n        # Calculate SNR on missing planet photons in ntran eclipses\n        SNRn =  np.sqrt(self.ntran) * SNR1\n\n        # Calculate the SECONDS required to observe a given SNR as a function of the spectral res\n        tSNR = self.wantsnr**2 * ( (1+1./self.nout)*cs + 1./self.nout*cp+(1+1./self.nout)*cback ) / cp**2\n\n        # Calculate the NUMBER OF ECLIPSES required to observe a given SNR as a function of the spectral res\n        nSNR = self.wantsnr**2 * ( (1+1./self.nout) * self.tdur * cs + 1./self.nout * self.tdur * cp + (1+1./self.nout)*self.tdur*cback ) / (self.tdur * cp)**2\n\n        # Save SNR quantities as attributes\n        self.SNR1 = SNR1\n        self.SNRn = SNRn\n        self.tSNR = tSNR\n        self.nSNR = nSNR\n\n        # Save additional stuff\n        self.lam = lam\n        self.dlam = dlam\n        self.FpFslr = FpFslr\n        self.FpFshr = FpFs\n\n        # Create fake data\n        self.make_fake_data()\n\n        return\n\n    def make_fake_data(self):\n        \"\"\"\n        Make a fake dataset by sampling from a Gaussian.\n\n        Attributes\n        ----------\n        SNRn : array\n            S/N in ``ntran`` eclipses\n        obs : array\n            Observed emission specrum with noise\n        sig : array\n            Observed uncertainties on emission spectrum\n        \"\"\"\n\n        # Ensure that simulation has been run\n        assert self._computed\n\n        # Calculate SNR on missing planet photons in ntran eclipses\n        self.SNRn =  np.sqrt(self.ntran) * self.SNR1\n\n        # Generate synthetic observations\n        self.sig = self.FpFslr / self.SNRn\n        self.obs = random_draw(self.FpFslr, self.sig)\n\n    def recalc_wantsnr(self, wantsnr = None):\n        \"\"\"\n        Recalculate the time and number of eclipses required to achieve a\n        user specified SNR via `wantsnr`.\n\n        Attributes\n        ----------\n        tSNR : array\n            Exposure time to ``wantsnr`` [s]\n        nSNR : array\n            Number of eclipses to ``wantsnr``\n        \"\"\"\n\n        assert self._computed\n\n        if wantsnr is not None:\n            self.wantsnr = wantsnr\n\n        # Calculate the SECONDS required to observe a given SNR as a function of the spectral res\n        self.tSNR = self.wantsnr**2 * ( (1+1./self.nout)*self.cs \\\n                                  + 1./self.nout*self.cp+(1+1./self.nout)*self.cback )\\\n                                  / self.cp**2\n\n        # Calculate the NUMBER OF ECLIPSES required to observe a given SNR as a function of the spectral res\n        self.nSNR = self.wantsnr**2 * ( (1+1./self.nout) * self.tdur * self.cs \\\n                                  + 1./self.nout * self.tdur * self.cp \\\n                                  + (1+1./self.nout)*self.tdur*self.cback ) \\\n                                  / (self.tdur * self.cp)**2\n\n        return\n\n\n    def plot_spectrum(self, SNR_threshold = 0.0, Nsig = None, ax0 = None,\n                      err_kws = {\"fmt\" : \".\", \"c\" : \"k\", \"alpha\" : 1},\n                      plot_kws = {\"lw\" : 1.0, \"c\" : \"C4\", \"alpha\" : 0.5},\n                      draw_box = True):\n        \"\"\"\n        Plot noised emission spectrum.\n\n        Parameters\n        ----------\n        SNR_threshold : float\n            Threshold SNR below which do not plot\n        Nsig : float\n            Number of standard deviations about median observed points to set\n            yaxis limits\n        ax0 : `matplotlib.axes`\n            Optional axis to provide\n        err_kws : dic\n            Keyword arguments for `errorbar`\n        plot_kws : dic\n            Keyword arguments for `plot`\n        draw_box : bool\n            Draw important quantities in a box?\n\n        Returns\n        -------\n        fig : `matplotlib.figure.Figure`\n            Returns a figure if `ax0` is `None`\n        ax : `matplotlib.axes`\n            Returns an axis if `ax0` is `None`\n\n        Note\n        ----\n        Only returns `fig` and `ax` is ``ax0 is None``\n        \"\"\"\n\n        m = [self.SNRn > SNR_threshold]\n\n        scale = 1e6\n\n        if ax0 is None:\n            # Create Plot\n            fig, ax = plt.subplots(figsize = (10,8))\n            ax.set_xlabel(r\"Wavelength [$\\mu$m]\")\n            ax.set_ylabel(r\"Eclipse Depth $(F_p / F_{\\star})$ [ppm]\")\n        else:\n            ax = ax0\n\n        #ax.plot(lam, scale*RpRs2, alpha = 1.0, ls = \"steps-mid\")\n        ax.errorbar(self.lam[m], scale*self.obs[m], yerr=scale*self.sig[m], zorder = 100, **err_kws)\n        #ax.set_yscale(\"log\")\n\n        # Set ylim\n        if Nsig is not None:\n            mederr = scale*np.median(self.sig)\n            medy = scale*np.median(self.obs)\n            ax.set_ylim([medy - Nsig*mederr, medy + Nsig*mederr])\n\n        ylims = ax.get_ylim()\n        xlims = ax.get_xlim()\n\n        ax.plot(self.lamhr, scale*self.FpFshr, **plot_kws)\n\n        ax.set_ylim(ylims)\n        ax.set_xlim(xlims)\n\n\n        if draw_box:\n            text = \"%i eclipses \\n %i m \\n %i\\%% throughput\" %(self.ntran, self.telescope.diameter, 100*self.telescope.throughput)\n            ax.text(0.02, 0.975, text, transform=ax.transAxes, ha = \"left\", va = \"top\",\n                    bbox=dict(boxstyle=\"square\", fc=\"w\", ec=\"k\", alpha=0.9), zorder=101)\n\n        #ax.legend()\n\n        if ax0 is None:\n            return fig, ax\n        else:\n            return\n\n    def plot_SNRn(self, ax0 = None, plot_kws = {\"ls\" : \"steps-mid\"}):\n        \"\"\"\n        Plot the S/N on the Eclipse Depth as a function of wavelength.\n\n        Parameters\n        ----------\n        ax0 : `matplotlib.axes`\n            Optional axis to provide\n        plot_kws : dic\n            Keyword arguments for `plot`\n\n        Returns\n        -------\n        fig : `matplotlib.figure.Figure`\n            Returns a figure if `ax0` is `None`\n        ax : `matplotlib.axes`\n            Returns an axis if `ax0` is `None`\n\n        Note\n        ----\n        Only returns `fig` and `ax` is ``ax0 is None``\n        \"\"\"\n        if ax0 is None:\n            # Create Plot\n            fig, ax = plt.subplots(figsize = (10,8))\n        else:\n            ax = ax0\n\n        ax.plot(self.lam, self.SNRn, **plot_kws)\n        #ax.set_yscale(\"log\")\n        ax.set_xlabel(r\"Wavelength [$\\mu$m]\")\n        ax.set_ylabel(\"S/N on Eclipse Depth\")\n        #ax.legend()\n\n        if ax0 is None:\n            return fig, ax\n        else:\n            return\n\n    def plot_ntran_to_wantsnr(self, ax0 = None,\n                              plot_kws = {\"ls\" : \"steps-mid\", \"alpha\" : 1.0}):\n        \"\"\"\n        Plot the number of eclipses to get a SNR on the eclipse depth as\n        a function of wavelength.\n\n        Parameters\n        ----------\n        ax0 : `matplotlib.axes`\n            Optional axis to provide\n        plot_kws : dic\n            Keyword arguments for `plot`\n\n        Returns\n        -------\n        fig : `matplotlib.figure.Figure`\n            Returns a figure if `ax0` is `None`\n        ax : `matplotlib.axes`\n            Returns an axis if `ax0` is `None`\n\n        Note\n        ----\n        Only returns `fig` and `ax` is ``ax0 is None``\n        \"\"\"\n\n        if ax0 is None:\n            # Create Plot\n            fig, ax = plt.subplots(figsize = (10,8))\n            ax.set_xlabel(r\"Wavelength [$\\mu$m]\")\n            ax.set_ylabel(\"Eclipses to S/N = %i on Eclipse Depth\" %self.wantsnr)\n            ax.set_yscale(\"log\")\n        else:\n            ax = ax0\n\n        ax.plot(self.lam, self.nSNR, **plot_kws)\n\n        if ax0 is None:\n            return fig, ax\n        else:\n            return\n\n    def plot_time_to_wantsnr(self, ax0 = None, plot_kws = {\"ls\" : \"steps-mid\", \"alpha\" : 1.0}):\n        \"\"\"\n        Plot the time to get a SNR on the eclipse depth as\n        a function of wavelength.\n\n        Parameters\n        ----------\n        ax0 : `matplotlib.axes`\n            Optional axis to provide\n        plot_kws : dic\n            Keyword arguments for `plot`\n\n        Returns\n        -------\n        fig : `matplotlib.figure.Figure`\n            Returns a figure if `ax0` is `None`\n        ax : `matplotlib.axes`\n            Returns an axis if `ax0` is `None`\n\n        Note\n        ----\n        Only returns `fig` and `ax` is ``ax0 is None``\n        \"\"\"\n\n        if ax0 is None:\n            # Create Plot\n            fig, ax = plt.subplots(figsize = (10,8))\n            ax.set_xlabel(r\"Wavelength [$\\mu$m]\")\n            ax.set_ylabel(\"Time to S/N = %i on Eclipse Depth [s]\" %self.wantsnr)\n            ax.set_yscale(\"log\")\n        else:\n            ax = ax0\n\n        ax.plot(self.lam, self.tSNR, **plot_kws)\n\n        if ax0 is None:\n            return fig, ax\n        else:\n            return\n\n    def plot_count_rates(self, ax0 = None):\n        \"\"\"\n        Plot the photon count rate for all sources.\n\n        Parameters\n        ----------\n        ax0 : `matplotlib.axes`\n            Optional axis to provide\n\n        Returns\n        -------\n        fig : `matplotlib.figure.Figure`\n            Returns a figure if `ax0` is `None`\n        ax : `matplotlib.axes`\n            Returns an axis if `ax0` is `None`\n\n        Note\n        ----\n        Only returns `fig` and `ax` is ``ax0 is None``\n        \"\"\"\n\n        if ax0 is None:\n            # Create Plot\n            fig, ax = plt.subplots(figsize = (10,8))\n            ax.set_xlabel(r\"Wavelength [$\\mu$m]\")\n            ax.set_ylabel(\"Photons / s\")\n            ax.set_yscale(\"log\")\n        else:\n            ax = ax0\n\n        ax.plot(self.lam, self.cp, label = \"Planet\", ls = \"dashed\")\n        ax.plot(self.lam, self.cs, label = \"Star\")\n        ax.plot(self.lam, self.cback, label = \"Total Bkg\")\n        ax.plot(self.lam, self.cz, label = \"SS Zodi\")\n        ax.plot(self.lam, self.cez, label = \"Exo-Zodi\")\n        ax.plot(self.lam, self.cth, label = \"Thermal Bkg\")\n        ax.plot(self.lam, self.cD, label = \"Dark\")\n        ax.plot(self.lam, self.cR, label = \"Read\")\n\n        if ax0 is None:\n            leg = ax.legend(fontsize = 14, ncol = 2)\n            return fig, ax\n        else:\n            return\n\nclass TransitNoise(object):\n    \"\"\"\n    Simulate exoplanet transit transmission spectroscopy with a next-generation\n    telescope.\n\n    Parameters\n    ----------\n    telescope : Telescope\n        Initialized object containing ``Telescope`` parameters\n    planet : Planet\n        Initialized object containing ``Planet`` parameters\n    star : Star\n        Initialized object containing ``Star`` parameters\n    tdur : float\n        Transit duration [s]\n    ntran : float\n        Number of transits\n    nout : float\n        Number of out-of-transit transit durations to observe\n    wantsnr : float, optional\n        Desired signal-to-noise ratio in each pixel\n    FIX_OWA : bool, optional\n        Set to fix OWA at ``OWA*lammin/D``, as would occur if lenslet array is\n        limiting the OWA\n    COMPUTE_LAM : bool, optional\n        Set to compute lo-res wavelength grid, otherwise the grid input as\n        variable ``lam`` is used\n    SILENT : bool, optional\n        Set to suppress print statements\n    NIR : bool, optional\n        Re-adjusts pixel size in NIR, as would occur if a second instrument\n        was designed to handle the NIR\n    THERMAL : bool, optional\n        Set to compute thermal photon counts due to telescope temperature\n    GROUND : bool, optional\n        Set to simulate ground-based observations through atmosphere\n    vod : bool, optional\n        \"Valley of Death\" red QE parameterization from Robinson et al. (2016)\n\n    \"\"\"\n    def __init__(self, tdur    = 3432.,  # TRAPPIST-1e\n                       telescope = Telescope(),\n                       planet = Planet(),\n                       star = Star(),\n                       ntran   = 1,\n                       nout    = 1,\n                       wantsnr = 1000.0,\n                       NIR     = True,\n                       THERMAL = True,\n                       GROUND  = False,\n                       vod     = False,\n                       IMAGE   = False):\n        self.telescope = telescope\n        self.planet    = planet\n        self.star      = star\n        self.tdur      = tdur\n        self.ntran     = ntran\n        self.nout      = nout\n        self.wantsnr   = wantsnr\n        self.NIR       = NIR\n        self.THERMAL   = THERMAL\n        self.GROUND    = GROUND\n        self.vod       = vod\n        self.IMAGE     = IMAGE\n\n        self._computed = False\n\n        return\n\n    def run_count_rates(self, lamhr = None, tdhr = None, Fshr = None):\n        \"\"\"\n        Calculate the photon count rates and signal to noise on a\n        transmission spectrum observation\n\n        Parameters\n        ----------\n        lamhr : numpy.ndarray\n            Wavelength [$\\mu$m]\n        tdhr : numpy.ndarray\n            Transit Depth $(Rp/Rs)^2$\n        Fshr : numpy.ndarray\n            Flux density incident at the planet's TOA [W/m$^2$/$\\mu$]\n\n        Calling ``run_count_rates()`` creates the following attributes for\n        the ``TransitNoise`` instance:\n\n        Attributes\n        ----------\n        lamhr : array\n            Wavelength [$\\mu$m]\n        tdhr : array\n            Transit Depth $(Rp/Rs)^2$\n        Fshr : array\n            Flux density incident at the planet's TOA [W/m$^2$/$\\mu$]\n        cs : array\n            Stellar photon count rate [photons/s]\n        cback : array\n            Background photon count rate [photons/s]\n        cz : array\n            Zodi photon count rate [photons/s]\n        cez : array\n            Exo-zodi photon count rate [photons/s]\n        cth : array\n            Thermal photon count rate [photons/s]\n        cD : array\n            Dark current photon count rate [photons/s]\n        cR : array\n            Read noise photon count rate [photons/s]\n        cmiss : array\n            Occulted stellar photon count rate [photons/s]\n        SNR1 : array\n            S/N for one transit\n        SNRn : array\n            S/N for ``ntran`` transits\n        tSNR : array\n            Exposure time to ``wantsnr`` [s]\n        nSNR : array\n            Number of transits to ``wantsnr``\n        lam : array\n            Observed wavelength grid [$\\mu$m]\n        dlam : array\n            Observed wavelength grid widths [$\\mu$m]\n        RpRs2 : array\n            Low-res transit depth\n\n        \"\"\"\n\n        self.lamhr = lamhr\n        self.tdhr = tdhr\n        self.Fshr = Fshr\n\n        if self.telescope.A_collect is None:\n            diam_collect = self.telescope.diameter\n        else:\n            diam_collect = 2. * (self.telescope.A_collect / np.pi)**0.5\n\n        # Set the convolution function\n        convolution_function = downbin_spec\n\n        # Does the telescope object already have a wavelength grid?\n        if (self.telescope.lam is None) or (self.telescope.dlam is None):\n            # Create wavelength grid\n            lam, dlam = construct_lam(self.telescope.lammin,\n                                      self.telescope.lammax,\n                                      self.telescope.resolution)\n        else:\n            # Use existing grids\n            lam = self.telescope.lam\n            dlam = self.telescope.dlam\n\n        # Set Quantum Efficiency\n        q = set_quantum_efficiency(lam,\n                                   self.telescope.qe,\n                                   NIR=self.NIR,\n                                   vod=self.vod)\n\n        # Set Dark current and Read noise\n        De = set_dark_current(lam,\n                              self.telescope.darkcurrent,\n                              self.telescope.lammax,\n                              self.telescope.Tdet,\n                              NIR=self.NIR)\n        Re = set_read_noise(lam,\n                            self.telescope.readnoise,\n                            NIR=self.NIR)\n\n        # Set Angular size of lenslet\n        theta = set_lenslet(lam,\n                            self.telescope.lammin,\n                            diam_collect,\n                            self.telescope.X,\n                            NIR=self.NIR)\n\n        # Set throughput\n        #sep  = r/d*np.sin(alpha*np.pi/180.)*np.pi/180./3600. # separation in radians\n        #T = set_throughput(lam, Tput, diam, sep, IWA, OWA, lammin, FIX_OWA=FIX_OWA, SILENT=SILENT)\n        T = self.telescope.throughput * np.ones_like(lam)\n\n        # Apply wavelength-dependent throuput, if needed\n        if self.telescope.Tput_lam is not None:\n            # Bin input throughput curve to native res\n            Tlam = np.interp(lam, self.telescope.Tput_lam[0], self.telescope.Tput_lam[1])\n            # Multiply into regular throughput\n            T = T * Tlam\n\n        # Apply wavelength-dependent quantum efficiency, if needed\n        if self.telescope.qe_lam is not None:\n            # Bin input QE curve to native res\n            qlam = np.interp(lam, self.telescope.qe_lam[0], self.telescope.qe_lam[1])\n            # Multiply into regular QE\n            q = q * qlam\n\n        # Modify throughput by atmospheric transmission if GROUND-based\n        if self.GROUND:\n            # Use SMART calc\n            Tatmos = set_atmos_throughput(lam, dlam, convolution_function)\n            # Multiply telescope throughput by atmospheric throughput\n            T = T * Tatmos\n\n        # Degrade transit and stellar spectrum\n        RpRs2 = convolution_function(tdhr,lamhr,lam,dlam=dlam)\n\n        # Calculate intensity of the star [W/m^2/um/sr]\n        if Fshr is None:\n            # Using a blackbody\n            Bstar = planck(self.star.Teff, lam)\n        else:\n            # Using provided TOA stellar flux\n            Fslr = convolution_function(Fshr, lamhr, lam, dlam=dlam)\n            Bstar = Fslr / ( np.pi*(self.star.Rs*u.Rsun.in_units(u.km)/\\\n                           (self.planet.a*u.AU.in_units(u.km)))**2. )\n\n        # Solid angle in steradians\n        omega_star = np.pi*(self.star.Rs*u.Rsun.in_units(u.km)/\\\n                           (self.planet.distance*u.pc.in_units(u.km)))**2.\n        omega_planet = np.pi*(self.planet.Rp*u.Rearth.in_units(u.km)/\\\n                             (self.planet.distance*u.pc.in_units(u.km)))**2.\n\n        # Fluxes at earth [W/m^2/um]\n        Fs = Bstar * omega_star\n        #Fback = jwst_background(lam)\n        Fstar_miss = Fs * RpRs2\n\n        # Fraction of planetary signal in Airy pattern\n        fpa = 1.0   # No fringe pattern here --> all of stellar psf falls on CCD\n\n        ########## Calculate Photon Count Rates ##########\n\n        # Stellar photon count rate\n        cs = cstar(q, fpa, T, lam, dlam, Fs, diam_collect)\n\n        # Missing photon count rate (is this a thing? it is now!)\n        cmiss = Fstar_miss*dlam*(lam*1e-6)/(h*c)*T*(np.pi * (0.5*diam_collect)**2)\n\n        # Solar System Zodi count rate\n        cz =  czodi(q, self.telescope.X, T, lam, dlam,\n                    diam_collect, self.planet.MzV)\n\n        # Exo-Zodi count rate\n        cez =  cezodi(q, self.telescope.X, T, lam, dlam, diam_collect,\n                      self.planet.a,\n                      Fstar(lam, self.star.Teff, self.star.Rs, 1., AU=True),\n                      self.planet.Nez, self.planet.MezV)\n\n        # Dark current count rate\n        cD =  cdark(De, self.telescope.X, lam,\n                    diam_collect, theta,\n                    self.telescope.DNHpix, IMAGE=self.IMAGE)\n\n        # Read noise count rate\n        cR =  cread(Re, self.telescope.X, lam, diam_collect,\n                    theta, self.telescope.DNHpix, self.telescope.Dtmax,\n                    IMAGE=self.IMAGE)\n\n        # Thermal background count rate\n        if self.THERMAL:\n            # telescope internal thermal count rate\n            cth =  ctherm(q, self.telescope.X, T, lam, dlam,\n                          diam_collect, self.telescope.Tsys,\n                          self.telescope.emissivity)\n        else:\n            cth = np.zeros_like(cs)\n\n        # Additional background from sky for ground-based observations\n        if self.GROUND:\n\n            if self.GROUND == \"ESO\":\n                # Use ESO SKCALC\n                wl_sky, Isky = get_sky_flux()\n                # Convolve to instrument resolution\n                Itherm = convolution_function(Isky, wl_sky, lam, dlam=dlam)\n            else:\n                # Get SMART computed surface intensity due to sky background\n                Itherm  = get_thermal_ground_intensity(lam, dlam, convolution_function)\n\n            # Compute Earth thermal photon count rate\n            cthe = ctherm_earth(q, self.telescope.X, T, lam, dlam,\n                                diam_collect, Itherm)\n\n            # Add earth thermal photon counts to telescope thermal counts\n            cth = cth + cthe\n\n        # Calculate background photon count rate\n        cback = cz + cez + cth + cD + cR\n\n        # Save count rates as attributes\n        self.cs = cs\n        self.cback = cback\n        self.cz = cz\n        self.cez = cez\n        self.cth = cth\n        self.cD = cD\n        self.cR = cR\n        self.cmiss = cmiss\n\n        # Flip the switch\n        self._computed = True\n\n        ########## Calculate SNR-like Quantities ##########\n\n        # Count STELLAR photons per transit\n        Nstar = self.tdur * 1 * cs\n\n        # Count BACKGROUND photons per transit\n        Nback = self.tdur * 1 * cback\n\n        # Calculate SNR on missing stellar photons in one transit\n        #   This formula assumes a homogeneous stellar disk (i.e. no limb darkening),\n        #   and comes from standard error propigation on the missing photons due to the\n        #   planet occulting the star calculation in terms of observables\n        SNR1 = (Nstar * RpRs2) / np.sqrt((1 + 1./self.nout - RpRs2) * Nstar + (1 + 1./self.nout) * Nback)\n\n        # Calculate SNR on missing stellar photons in ntran transits\n        SNRn =  np.sqrt(self.ntran) * SNR1\n\n        # Calculate the SECONDS required to observe a given SNR as a function of the spectral res\n        tSNR = self.wantsnr**2 * ((1 + 1./self.nout - RpRs2) * cs + (1 + 1./self.nout) * cback) / (cs * RpRs2)**2\n\n        # Calculate the NUMBER OF TRANSITS required to observe a given SNR as a function of the spectral res\n        nSNR = self.wantsnr**2 * ((1 + 1./self.nout - RpRs2) *  self.tdur * cs + (1 + 1./self.nout) * self.tdur * cback) / (self.tdur * cs * RpRs2)**2\n\n        # Save SNR quantities as attributes\n        self.SNR1 = SNR1\n        self.SNRn = SNRn\n        self.tSNR = tSNR\n        self.nSNR = nSNR\n\n        # Save additional stuff\n        self.lam = lam\n        self.dlam = dlam\n        self.RpRs2 = RpRs2\n\n        # Create fake data\n        self.make_fake_data()\n\n        return\n\n    def make_fake_data(self):\n        \"\"\"\n        Make a fake dataset by sampling from a Gaussian.\n\n        Attributes\n        ----------\n        SNRn : array\n            S/N in ``ntran`` transits\n        obs : array\n            Observed transit depth with noise\n        sig : array\n            Observed uncertainties on transit depth\n        \"\"\"\n\n        # Ensure that simulation has been run\n        assert self._computed\n\n        # Calculate SNR on missing stellar photons in ntran transits\n        self.SNRn =  np.sqrt(self.ntran) * self.SNR1\n\n        # Generate synthetic observations\n        self.sig = self.RpRs2 / self.SNRn\n        self.obs = random_draw(self.RpRs2, self.sig)\n\n    def recalc_wantsnr(self, wantsnr = None):\n        \"\"\"\n        Recalculate the time and number of transits required to achieve a\n        user specified SNR via `wantsnr`.\n\n        Attributes\n        ----------\n        tSNR : array\n            Exposure time to ``wantsnr`` [s]\n        nSNR : array\n            Number of transits to ``wantsnr``\n        \"\"\"\n\n        assert self._computed\n\n        if wantsnr is not None:\n            self.wantsnr = wantsnr\n\n        # Calculate the SECONDS required to observe a given SNR as a function of the spectral res\n        self.tSNR = self.wantsnr**2 * ((1 + 1./self.nout - self.RpRs2) \\\n                                       * self.cs + (1 + 1./self.nout) \\\n                                       * self.cback) / (self.cs * self.RpRs2)**2\n\n        # Calculate the NUMBER OF TRANSITS required to observe a given SNR as a function of the spectral res\n        self.nSNR = self.wantsnr**2 * ((1 + 1./self.nout - self.RpRs2) \\\n                                       *  self.tdur * self.cs + (1 + 1./self.nout) \\\n                                       * self.tdur * self.cback) / (self.tdur * self.cs * self.RpRs2)**2\n\n        return\n\n\n    def plot_spectrum(self, SNR_threshold = 1.0, Nsig = 6.0, ax0 = None,\n                      err_kws = {\"fmt\" : \".\", \"c\" : \"k\", \"alpha\" : 1},\n                      plot_kws = {\"lw\" : 1.0, \"c\" : \"C4\", \"alpha\" : 0.5},\n                      draw_box = True):\n        \"\"\"\n        Plot noised transmission spectrum.\n\n        Parameters\n        ----------\n        SNR_threshold : float\n            Threshold SNR below which do not plot\n        Nsig : float\n            Number of standard deviations about median observed points to set\n            yaxis limits\n        ax0 : `matplotlib.axes`\n            Optional axis to provide\n        err_kws : dic\n            Keyword arguments for `errorbar`\n        plot_kws : dic\n            Keyword arguments for `plot`\n        draw_box : bool\n            Draw important quantities in a box?\n\n        Returns\n        -------\n        fig : `matplotlib.figure.Figure`\n            Returns a figure if `ax0` is `None`\n        ax : `matplotlib.axes`\n            Returns an axis if `ax0` is `None`\n\n        Note\n        ----\n        Only returns `fig` and `ax` is ``ax0 is None``\n        \"\"\"\n\n        m = [self.SNRn > SNR_threshold]\n\n        scale = 1e6\n\n        if ax0 is None:\n            # Create Plot\n            fig, ax = plt.subplots(figsize = (10,8))\n            ax.set_xlabel(r\"Wavelength [$\\mu$m]\")\n            ax.set_ylabel(\"Transit Depth $(R_p / R_{\\star})^2$ [ppm]\")\n        else:\n            ax = ax0\n\n        #ax.plot(lam, scale*RpRs2, alpha = 1.0, ls = \"steps-mid\")\n        ax.errorbar(self.lam[m], scale*self.obs[m], yerr=scale*self.sig[m], zorder = 100, **err_kws)\n        #ax.set_yscale(\"log\")\n\n        # Set ylim\n        mederr = scale*np.median(self.sig)\n        medy = scale*np.median(self.obs)\n        ax.set_ylim([medy - Nsig*mederr, medy + Nsig*mederr])\n\n        ylims = ax.get_ylim()\n        xlims = ax.get_xlim()\n\n        ax.plot(self.lamhr, scale*self.tdhr, **plot_kws)\n\n        ax.set_ylim(ylims)\n        ax.set_xlim(xlims)\n\n\n        if draw_box:\n            text = \"%i transits \\n %i m \\n %i\\%% throughput\" %(self.ntran, self.telescope.diameter, 100*self.telescope.throughput)\n            ax.text(0.02, 0.975, text, transform=ax.transAxes, ha = \"left\", va = \"top\",\n                    bbox=dict(boxstyle=\"square\", fc=\"w\", ec=\"k\", alpha=0.9), zorder=101)\n\n        #ax.legend()\n\n        if ax0 is None:\n            return fig, ax\n        else:\n            return\n\n    def plot_SNRn(self, ax0 = None, plot_kws = {\"ls\" : \"steps-mid\"}):\n        \"\"\"\n        Plot the S/N on the Transit Depth as a function of wavelength.\n\n        Parameters\n        ----------\n        ax0 : `matplotlib.axes`\n            Optional axis to provide\n        plot_kws : dic\n            Keyword arguments for `plot`\n\n        Returns\n        -------\n        fig : `matplotlib.figure.Figure`\n            Returns a figure if `ax0` is `None`\n        ax : `matplotlib.axes`\n            Returns an axis if `ax0` is `None`\n\n        Note\n        ----\n        Only returns `fig` and `ax` is ``ax0 is None``\n        \"\"\"\n        if ax0 is None:\n            # Create Plot\n            fig, ax = plt.subplots(figsize = (10,8))\n        else:\n            ax = ax0\n\n        ax.plot(self.lam, self.SNRn, **plot_kws)\n        #ax.set_yscale(\"log\")\n        ax.set_xlabel(r\"Wavelength [$\\mu$m]\")\n        ax.set_ylabel(\"S/N on Transit Depth\")\n        #ax.legend()\n\n        if ax0 is None:\n            return fig, ax\n        else:\n            return\n\n    def plot_ntran_to_wantsnr(self, ax0 = None,\n                              plot_kws = {\"ls\" : \"steps-mid\", \"alpha\" : 1.0}):\n        \"\"\"\n        Plot the number of transits to get a SNR on the transit depth as\n        a function of wavelength.\n\n        Parameters\n        ----------\n        ax0 : `matplotlib.axes`\n            Optional axis to provide\n        plot_kws : dic\n            Keyword arguments for `plot`\n\n        Returns\n        -------\n        fig : `matplotlib.figure.Figure`\n            Returns a figure if `ax0` is `None`\n        ax : `matplotlib.axes`\n            Returns an axis if `ax0` is `None`\n\n        Note\n        ----\n        Only returns `fig` and `ax` is ``ax0 is None``\n        \"\"\"\n\n        if ax0 is None:\n            # Create Plot\n            fig, ax = plt.subplots(figsize = (10,8))\n            ax.set_xlabel(r\"Wavelength [$\\mu$m]\")\n            ax.set_ylabel(\"Transits to S/N = %i on Transit Depth\" %self.wantsnr)\n            ax.set_yscale(\"log\")\n        else:\n            ax = ax0\n\n        ax.plot(self.lam, self.nSNR, **plot_kws)\n\n        if ax0 is None:\n            return fig, ax\n        else:\n            return\n\n    def plot_time_to_wantsnr(self, ax0 = None, plot_kws = {\"ls\" : \"steps-mid\", \"alpha\" : 1.0}):\n        \"\"\"\n        Plot the time to get a SNR on the transit depth as\n        a function of wavelength.\n\n        Parameters\n        ----------\n        ax0 : `matplotlib.axes`\n            Optional axis to provide\n        plot_kws : dic\n            Keyword arguments for `plot`\n\n        Returns\n        -------\n        fig : `matplotlib.figure.Figure`\n            Returns a figure if `ax0` is `None`\n        ax : `matplotlib.axes`\n            Returns an axis if `ax0` is `None`\n\n        Note\n        ----\n        Only returns `fig` and `ax` is ``ax0 is None``\n        \"\"\"\n\n        if ax0 is None:\n            # Create Plot\n            fig, ax = plt.subplots(figsize = (10,8))\n            ax.set_xlabel(r\"Wavelength [$\\mu$m]\")\n            ax.set_ylabel(\"Time to S/N = %i on Transit Depth [s]\" %self.wantsnr)\n            ax.set_yscale(\"log\")\n        else:\n            ax = ax0\n\n        ax.plot(self.lam, self.tSNR, **plot_kws)\n\n        if ax0 is None:\n            return fig, ax\n        else:\n            return\n\n    def plot_count_rates(self, ax0 = None):\n        \"\"\"\n        Plot the photon count rate for all sources.\n\n        Parameters\n        ----------\n        ax0 : `matplotlib.axes`\n            Optional axis to provide\n\n        Returns\n        -------\n        fig : `matplotlib.figure.Figure`\n            Returns a figure if `ax0` is `None`\n        ax : `matplotlib.axes`\n            Returns an axis if `ax0` is `None`\n\n        Note\n        ----\n        Only returns `fig` and `ax` is ``ax0 is None``\n        \"\"\"\n\n        if ax0 is None:\n            # Create Plot\n            fig, ax = plt.subplots(figsize = (10,8))\n            ax.set_xlabel(r\"Wavelength [$\\mu$m]\")\n            ax.set_ylabel(\"Photons / s\")\n            ax.set_yscale(\"log\")\n        else:\n            ax = ax0\n\n        ax.plot(self.lam, self.cmiss, label = \"Occulted\", ls = \"dashed\")\n        ax.plot(self.lam, self.cs, label = \"Star\")\n        ax.plot(self.lam, self.cback, label = \"Total Bkg\")\n        ax.plot(self.lam, self.cz, label = \"SS Zodi\")\n        ax.plot(self.lam, self.cez, label = \"Exo-Zodi\")\n        ax.plot(self.lam, self.cth, label = \"Thermal Bkg\")\n        ax.plot(self.lam, self.cD, label = \"Dark\")\n        ax.plot(self.lam, self.cR, label = \"Read\")\n\n        if ax0 is None:\n            leg = ax.legend(fontsize = 14, ncol = 2)\n            return fig, ax\n        else:\n            return\n\ndef get_earth_trans_spectrum():\n    '''\n    Get the transmission spectrum of the Earth around the Sun.\n\n    Returns\n    -------\n    lam : `numpy.ndarray`\n        Wavelength grid [um]\n    tdepth : `numpy.ndarray`\n        Transit depth (Rp/Rs)^2\n    fplan : `numpy.ndarray`\n        TOA planet flux [W/m^2/um]\n    fstar : `numpy.ndarray`\n        Stellar flux at planet [W/m^2/um]\n    '''\n\n    # Read in transit data\n    here = os.path.join(os.path.dirname(__file__))\n    plus = \"planets/earth_avg_hitran2012_300_100000cm.trnst\"\n    data = np.loadtxt(os.path.join(here, plus))\n\n    # Parse\n    lam = data[:,0]\n    tdepth = data[:,3]\n\n    # Read in flux data\n    plus = \"planets/earth_avg_hitran2012_300_100000cm_toa.rad\"\n    data = np.loadtxt(os.path.join(here, plus))\n\n    # Parse\n    fplan = data[:,3]\n    fstar = data[:,2]\n\n    return lam, tdepth, fplan, fstar\n", "meta": {"hexsha": "5115d9e99cbec26d837994307451b378babb37ba", "size": 45323, "ext": "py", "lang": "Python", "max_stars_repo_path": "coronagraph/transits.py", "max_stars_repo_name": "jlustigy/coronagraph", "max_stars_repo_head_hexsha": "b321693512422343b08ada7e246413e1f4bae4cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-05-25T07:48:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T00:40:57.000Z", "max_issues_repo_path": "coronagraph/transits.py", "max_issues_repo_name": "jlustigy/coronagraph", "max_issues_repo_head_hexsha": "b321693512422343b08ada7e246413e1f4bae4cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-04-12T22:17:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-07T00:01:11.000Z", "max_forks_repo_path": "coronagraph/transits.py", "max_forks_repo_name": "jlustigy/coronagraph", "max_forks_repo_head_hexsha": "b321693512422343b08ada7e246413e1f4bae4cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-11-14T06:46:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-31T06:50:55.000Z", "avg_line_length": 33.5229289941, "max_line_length": 159, "alphanum_fraction": 0.5347395362, "include": true, "reason": "import numpy,import astropy", "num_tokens": 11349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.2598256436924554, "lm_q1q2_score": 0.1636315927500151}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n# -*- coding: utf-8 -*-\n\"\"\"\nfiberassign.hardware\n=======================\n\nFunctions for loading information about the telescope hardware.\n\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nfrom datetime import datetime, timezone\n\nimport numpy as np\n\nfrom scipy.interpolate import interp1d\n\nimport desimodel.io as dmio\n\nfrom .utils import Logger\n\nfrom ._internal import (\n    Hardware,\n    FIBER_STATE_OK,\n    FIBER_STATE_UNASSIGNED,\n    FIBER_STATE_STUCK,\n    FIBER_STATE_BROKEN,\n    FIBER_STATE_RESTRICT,\n    Circle,\n    Segments,\n    Shape,\n)\n\ndef expand_closed_curve(xx, yy, margin):\n    '''\n    For the --margin-{pos,petal,gfa} options, we can add a buffer zone\n    around the positioner keep-out polygons.  This function implements\n    the geometry to achieve this.\n\n    Given a RIGHT-HANDED closed polygon xx,yy and margin, returns new\n    x,y coordinates expanded by a margin of `margin`.\n\n    (By right-handed, I mean that the points are listed\n    counter-clockwise, and if you walk the boundary, the inside of the\n    shape is to the left; the expanded points will be to the right.)\n\n    If the order of the polygon is reversed, the \"expanded\" points\n    will actually be on the *inside* of the polygon.  Setting the\n    margin negative counteracts this.\n\n    Note that we strictly require a closed curve.  Collinear polygon\n    segments will cause problems!\n\n    '''\n    ex, ey = [],[]\n\n    # These are closed curves (last point = first point)\n    # (this isn't strictly required by the fundamental algorithm, but is assumed\n    # in the way we select previous and next points in the loop below.)\n    if (xx[0] != xx[-1]) or (yy[0] != yy[-1]):\n        log = Logger.get()\n        log.warning('Expected exclusion polygons to be closed curves; got x, y = %s, %s' % (str(xx), str(yy)))\n        return xx, yy\n    assert(xx[0] == xx[-1])\n    assert(yy[0] == yy[-1])\n\n    N = len(xx)\n\n    for j in range(N):\n        # We go through the points, and for each point we consider the previous\n        # and next point.  The \"expanded\" point will be defined according to the\n        # two edges (vector) coming from the point.\n        i = j - 1\n        if i == -1:\n            # wrap around, skipping repeated point\n            i = N-2\n        k = j + 1\n        if k == N:\n            k = 1\n\n        x1 = xx[i]\n        y1 = yy[i]\n        x2 = xx[j]\n        y2 = yy[j]\n        x3 = xx[k]\n        y3 = yy[k]\n\n        # Vectors to and from the central point.\n        vx1 = x2 - x1\n        vy1 = y2 - y1\n        vx2 = x3 - x2\n        vy2 = y3 - y2\n        # We can't handle repeated points!\n        assert(not(vx2 == 0. and vy2 == 0.))\n\n        # Get the angle between the vectors -- our expanded point is going to\n        # be halfway between these two vectors.\n        cross1 = vx1 * vy2 - vx2 * vy1\n        vv1 = np.hypot(vx1,vy1)\n        vv2 = np.hypot(vx2,vy2)\n        theta = np.arcsin(np.clip(cross1 / (vv1 * vv2), -1., 1.))\n        # Detect sharp (>90 degree) turns\n        dot = vx1*vx2 + vy1*vy2\n        # the angle of the expanded point is relative to vector 1\n        a = np.arctan2(vy1, vx1)\n        if dot < 0:\n            # sharp turn -- the theta=arcsin aliases the angle, which is outside\n            # the range of [-pi/2, +pi/2]; adjust theta to the aliased angle.\n            if theta > 0:\n                theta =  np.pi - theta\n            else:\n                theta = -np.pi - theta\n        da = np.pi/2. + theta/2.\n        # This places the point further from the original keeps the vectors parallel to their originals\n        stretch = 1./np.cos(theta/2.)\n        dx = -margin * stretch * np.cos(a + da)\n        dy = -margin * stretch * np.sin(a + da)\n\n        ex.append(x2 + dx)\n        ey.append(y2 + dy)\n\n    return ex, ey\n\n\ndef load_hardware(focalplane=None, rundate=None,\n                  add_margins={}):\n    \"\"\"Create a hardware class representing properties of the telescope.\n\n    Args:\n        focalplane (tuple):  Override the focalplane model.  If not None, this\n            should be a tuple of the same data types returned by\n            desimodel.io.load_focalplane()\n        rundate (str):  ISO 8601 format time stamp as a string in the\n            format YYYY-MM-DDTHH:MM:SS+-zz:zz.  If None, uses current time.\n\n    Returns:\n        (Hardware):  The hardware object.\n\n    \"\"\"\n    log = Logger.get()\n\n    # The timestamp for this run.\n    runtime = None\n    if rundate is None:\n        runtime = datetime.now(tz=timezone.utc)\n    else:\n        try:\n            runtime = datetime.strptime(rundate, \"%Y-%m-%dT%H:%M:%S%z\")\n        except ValueError:\n            runtime = datetime.strptime(rundate, \"%Y-%m-%dT%H:%M:%S\")\n            msg = \"Requested run date '{}' is not timezone-aware.  Assuming UTC.\".format(runtime)\n            log.warning(msg)\n            runtime = runtime.replace(tzinfo=timezone.utc)\n    runtimestr = None\n    try:\n        runtimestr = runtime.isoformat(timespec=\"seconds\")\n    except TypeError:\n        runtimestr = runtime.isoformat()\n\n    # Get the focalplane information\n    fp = None\n    exclude = None\n    state = None\n    create_time = \"UNKNOWN\"\n    if focalplane is None:\n        fp, exclude, state, create_time = dmio.load_focalplane(runtime)\n    else:\n        fp, exclude, state = focalplane\n\n    # Get the plate scale\n    platescale = dmio.load_platescale()\n\n    # We are going to do a quadratic interpolation to the platescale on a fine grid,\n    # and then use that for *linear* interpolation inside the compiled code.  The\n    # default platescale data is on a one mm grid spacing.  We also do the same\n    # interpolation of the arclength S(R).\n\n    fine_radius = np.linspace(\n        platescale[\"radius\"][0], platescale[\"radius\"][-1], num=10000, dtype=np.float64\n    )\n    fn = interp1d(platescale[\"radius\"], platescale[\"theta\"], kind=\"quadratic\")\n    fine_theta = fn(fine_radius).astype(np.float64)\n    fn = interp1d(platescale[\"radius\"], platescale[\"arclength\"], kind=\"quadratic\")\n    fine_arc = fn(fine_radius).astype(np.float64)\n\n    # We are only going to keep rows for LOCATIONs that are assigned to a\n    # science or sky monitor positioner.\n\n    log.info(\"Loaded focalplane for time stamp {}\".format(runtime))\n\n    pos_rows = np.where(fp[\"DEVICE_TYPE\"].astype(str) == \"POS\")[0]\n    etc_rows = np.where(fp[\"DEVICE_TYPE\"].astype(str) == \"ETC\")[0]\n    keep_rows = np.unique(np.concatenate((pos_rows, etc_rows)))\n\n    nloc = len(keep_rows)\n    log.debug(\"  focalplane table keeping {} rows for POS and ETC devices\".format(nloc))\n\n    device_type = np.full(nloc, \"OOPSBUG\", dtype=\"a8\")\n    device_type[:] = fp[\"DEVICE_TYPE\"][keep_rows]\n\n    locations = np.copy(fp[\"LOCATION\"][keep_rows])\n\n    # Map location to row in the table\n\n    loc_to_fp = dict()\n    for rw, loc in enumerate(fp[\"LOCATION\"]):\n        loc_to_fp[loc] = rw\n\n    # FIXME:  Here we assume that the 32bit STATE column has the same bit\n    # definitions as what is used by fiberassign (defined in hardware.h):\n    # If this is not true, then re-map those values here inside the \"state\"\n    # table loaded above.\n\n    # Map location to row of the state table\n\n    loc_to_state = dict()\n    for rw, loc in enumerate(state[\"LOCATION\"]):\n        loc_to_state[loc] = rw\n\n    # Slightly reformat the 'add_margins' dict: 'pos' gets copied to\n    # 'theta' and 'phi'.\n    margins = {}\n    if 'pos' in add_margins:\n        margins['theta'] = add_margins['pos']\n        margins['phi']   = add_margins['pos']\n    if 'gfa' in add_margins:\n        margins['gfa'] = add_margins['gfa']\n    # PLUS -- and this is a HACK --\n    # because the 'petal' exclusion polygons are listed in the db dump files\n    # in \"left-handed\" order, unlike the other polygons, we must NEGATE the\n    # margin!\n    if 'petal' in add_margins:\n        margins['petal'] = -add_margins['petal']\n\n    # Convert the exclusion polygons into shapes (as required)\n    excl = dict()\n    # cache expanded polygons (because many of the polygons are actually duplicates)\n    expanded = {}\n    def get_exclusions(exclname):\n        e = excl.get(exclname)\n        if e is not None:\n            return e\n        shp = exclude[exclname]\n        excl[exclname] = dict()\n        for obj in shp.keys():\n            cr = list()\n            for crc in shp[obj][\"circles\"]:\n                cr.append(Circle(crc[0], crc[1]))\n            sg = list()\n            for sgm in shp[obj][\"segments\"]:\n                if obj in margins:\n                    key = (obj, tuple(tuple(xy) for xy in sgm))\n                    if key in expanded:\n                        sgm = expanded[key]\n                    else:\n                        sx = [x for x,y in sgm]\n                        sy = [y for x,y in sgm]\n                        ex,ey = expand_closed_curve(sx, sy, margins[obj])\n                        sgm = list(zip(ex, ey))\n                        expanded[key] = sgm\n                sg.append(Segments(sgm))\n            fshp = Shape((0.0, 0.0), cr, sg)\n            excl[exclname][obj] = fshp\n        return excl[exclname]\n\n    # For each positioner, select the exclusion polynomials.\n    positioners = dict()\n\n    for loc in locations:\n        exclname = state[\"EXCLUSION\"][loc_to_state[loc]]\n        positioners[loc] = dict()\n        posexcl = get_exclusions(exclname)\n        positioners[loc][\"theta\"] = Shape(posexcl[\"theta\"])\n        positioners[loc][\"phi\"] = Shape(posexcl[\"phi\"])\n        if \"gfa\" in posexcl:\n            positioners[loc][\"gfa\"] = Shape(posexcl[\"gfa\"])\n        else:\n            positioners[loc][\"gfa\"] = Shape()\n        if \"petal\" in posexcl:\n            positioners[loc][\"petal\"] = Shape(posexcl[\"petal\"])\n        else:\n            positioners[loc][\"petal\"] = Shape()\n\n    hw = None\n    if \"MIN_P\" in state.colnames:\n        # This is a new-format focalplane model (after desimodel PR #143)\n        hw = Hardware(\n            runtimestr,\n            locations,\n            fp[\"PETAL\"][keep_rows],\n            fp[\"DEVICE\"][keep_rows],\n            fp[\"SLITBLOCK\"][keep_rows],\n            fp[\"BLOCKFIBER\"][keep_rows],\n            fp[\"FIBER\"][keep_rows],\n            device_type,\n            fp[\"OFFSET_X\"][keep_rows],\n            fp[\"OFFSET_Y\"][keep_rows],\n            np.array([state[\"STATE\"][loc_to_state[x]] for x in locations]),\n            np.array([fp[\"OFFSET_T\"][loc_to_fp[x]] for x in locations]),\n            np.array([state[\"MIN_T\"][loc_to_state[x]] for x in locations]),\n            np.array([state[\"MAX_T\"][loc_to_state[x]] for x in locations]),\n            np.array([state[\"POS_T\"][loc_to_state[x]] for x in locations]),\n            np.array([fp[\"LENGTH_R1\"][loc_to_fp[x]] for x in locations]),\n            np.array([fp[\"OFFSET_P\"][loc_to_fp[x]] for x in locations]),\n            np.array([state[\"MIN_P\"][loc_to_state[x]] for x in locations]),\n            np.array([state[\"MAX_P\"][loc_to_state[x]] for x in locations]),\n            np.array([state[\"POS_P\"][loc_to_state[x]] for x in locations]),\n            np.array([fp[\"LENGTH_R2\"][loc_to_fp[x]] for x in locations]),\n            fine_radius,\n            fine_theta,\n            fine_arc,\n            [positioners[x][\"theta\"] for x in locations],\n            [positioners[x][\"phi\"] for x in locations],\n            [positioners[x][\"gfa\"] for x in locations],\n            [positioners[x][\"petal\"] for x in locations],\n            add_margins\n        )\n    else:\n        # This is an old-format focalplane model (prior to desimodel PR #143).  For\n        # stuck positioners, we want to specify a default POS_T / POS_P to use.\n        # These old models did not include any information about that, so we use the\n        # minimum Theta value and either the maximum Phi value or PI, whichever is\n        # smaller\n        fake_pos_p = np.zeros(len(locations), dtype=np.float64)\n        fake_pos_t = np.zeros(len(locations), dtype=np.float64)\n        for ilid, lid in enumerate(locations):\n            pt = fp[\"MIN_T\"][loc_to_fp[lid]] + fp[\"OFFSET_T\"][loc_to_fp[lid]]\n            pp = fp[\"MAX_P\"][loc_to_fp[lid]] + fp[\"OFFSET_P\"][loc_to_fp[lid]]\n            if pp > 180.0:\n                pp = 180.0\n            fake_pos_p[ilid] = pp\n            fake_pos_t[ilid] = pt\n        hw = Hardware(\n            runtimestr,\n            locations,\n            fp[\"PETAL\"][keep_rows],\n            fp[\"DEVICE\"][keep_rows],\n            fp[\"SLITBLOCK\"][keep_rows],\n            fp[\"BLOCKFIBER\"][keep_rows],\n            fp[\"FIBER\"][keep_rows],\n            device_type,\n            fp[\"OFFSET_X\"][keep_rows],\n            fp[\"OFFSET_Y\"][keep_rows],\n            np.array([state[\"STATE\"][loc_to_state[x]] for x in locations]),\n            np.array([fp[\"OFFSET_T\"][loc_to_fp[x]] for x in locations]),\n            np.array([fp[\"MIN_T\"][loc_to_fp[x]] for x in locations]),\n            np.array([fp[\"MAX_T\"][loc_to_fp[x]] for x in locations]),\n            fake_pos_t,\n            np.array([fp[\"LENGTH_R1\"][loc_to_fp[x]] for x in locations]),\n            np.array([fp[\"OFFSET_P\"][loc_to_fp[x]] for x in locations]),\n            np.array([fp[\"MIN_P\"][loc_to_fp[x]] for x in locations]),\n            np.array([fp[\"MAX_P\"][loc_to_fp[x]] for x in locations]),\n            fake_pos_p,\n            np.array([fp[\"LENGTH_R2\"][loc_to_fp[x]] for x in locations]),\n            fine_radius,\n            fine_theta,\n            fine_arc,\n            [positioners[x][\"theta\"] for x in locations],\n            [positioners[x][\"phi\"] for x in locations],\n            [positioners[x][\"gfa\"] for x in locations],\n            [positioners[x][\"petal\"] for x in locations],\n            add_margins\n        )\n    return hw\n\ndef radec2xy(hw, tile_ra, tile_dec, tile_obstime, tile_obstheta, tile_obsha,\n             ra, dec, use_cs5, threads=0):\n    '''\n    For the tile pointed at (tilera, tiledec), project the (ra, dec)\n    value into X/Y mm.\n\n    Args:\n      hw: Hardware object\n      tile_ra (float): Tile RA\n      tile_dec (float): Tile Dec\n      tile_obstime (string): Tile observation time, YYYY-MM-DDTHH:MM:SS / Astropy \"isot\" format.\n      tile_obstheta (float): Tile \"fieldrot\" rotation angle.\n      tile_obsha (float): Tile designed Hour Angle, in degrees.\n      ra (numpy array): RA to project, in degrees\n      dec (numpy array): Dec to project, in degrees\n      use_CS5 (bool):  If True, return CS5 coordinates, else curved.\n      threads=0 (int): currently unused; for backward compatibility.\n\n    Returns:\n      x, y: numpy arrays: the (X, Y) projected locations.\n    '''\n    #xy = hw.radec2xy_multi(\n    #    tile_ra, tile_dec, tile_obstheta, ra, dec, use_cs5, threads=0\n    #)\n    #x = np.array([x for x,y in xy])\n    #y = np.array([y for x,y in xy])\n    from astropy.time import Time\n    from desimeter.fiberassign import fiberassign_radec2xy_cs5, fiberassign_radec2xy_flat\n    # Note that MJD is only used for precession, so no need for\n    # high precision.\n    t = Time(tile_obstime, format='isot')\n    mjd = t.mjd\n\n    # Don't pass adc[12]: Let desimeter use its pm-alike routines\n    if use_cs5:\n        x, y = fiberassign_radec2xy_cs5(ra, dec, tile_ra, tile_dec, mjd,\n                                        tile_obsha, tile_obstheta)\n    else:\n        x, y = fiberassign_radec2xy_flat(ra, dec, tile_ra, tile_dec, mjd,\n                                         tile_obsha, tile_obstheta)\n    return x,y\n\ndef xy2radec(hw, tile_ra, tile_dec, tile_obstime, tile_obstheta, tile_obsha,\n             x, y, use_cs5, threads=0):\n    '''\n    For the tile pointed at (tilera, tiledec), compute the RA,Dec\n    pointing of the specified X/Y location in millimeters.\n\n    Args:\n      hw: Hardware object\n      tile_obstime (string): Tile observation time, YYYY-MM-DDTHH:MM:SS / Astropy \"isot\" format.\n      tile_obstheta (float): Tile \"fieldrot\" rotation angle.\n      tile_obsha (float): Tile designed Hour Angle, in degrees.\n      x (numpy array): X position in mm.\n      y (numpy array): Y position in mm.\n      use_CS5 (bool):  If True, assume X,Y are CS5 coordinates, else curved.\n      threads=0 (int): currently unused; for backward compatibility.\n\n    Returns:\n      ra, dec (numpy arrays): the (RA, Dec) values of the focalplane locations,\n                              in degrees.\n    '''\n    # radec = hw.xy2radec_multi(\n    #     tile_ra, tile_dec, tile_obstheta, x, y, use_cs5, threads\n    #     )\n    # ra  = np.array([r for r,d in radec])\n    # dec = np.array([d for r,d in radec])\n    from desimeter.fiberassign import fiberassign_cs5_xy2radec, fiberassign_flat_xy2radec\n    from astropy.time import Time\n    t = Time(tile_obstime, format='isot')\n    mjd = t.mjd\n    if use_cs5:\n        ra,dec = fiberassign_cs5_xy2radec(x, y, tile_ra, tile_dec, mjd,\n                                          tile_obsha, tile_obstheta)\n    else:\n        ra,dec = fiberassign_flat_xy2radec(x, y, tile_ra, tile_dec, mjd,\n                                           tile_obsha, tile_obstheta)\n    return ra,dec\n\ndef xy2cs5(x, y):\n    '''\n    Converts from curved focal-plane X,Y coordinates in mm into CS5\n    coordinates in mm.\n\n    Args:\n    x (numpy array): X coord (mm)\n    y (numpy array): Y coord (mm)\n\n    Returns:\n    cs5x (numpy array): CS5 X coord (mm)\n    cs5y (numpy array): CS5 Y coord (mm)\n    '''\n    # There's a change in terminology between the focal-plane team and\n    # the outside world here...\n    from desimeter.transform.pos2ptl import flat2ptl\n    return flat2ptl(x, y)\n\ndef cs52xy(x, y):\n    '''\n    Converts from CS5 coordinates (mm) into curved focal-plane X,Y coordinates in mm.\n\n    Args:\n    cs5x (numpy array): CS5 X coord (mm)\n    cs5y (numpy array): CS5 Y coord (mm)\n\n    Returns:\n    x (numpy array): X coord (mm)\n    y (numpy array): Y coord (mm)\n    '''\n    # There's a change in terminology between the focal-plane team and\n    # the outside world here...\n    from desimeter.transform.pos2ptl import ptl2flat\n    return ptl2flat(x, y)\n", "meta": {"hexsha": "0c4e29d971f8050b422fc9381e641a1b422e0355", "size": 17873, "ext": "py", "lang": "Python", "max_stars_repo_path": "py/fiberassign/hardware.py", "max_stars_repo_name": "desihub/fiberassign", "max_stars_repo_head_hexsha": "ac6e935614cad8c888f2bd5b93000eb955185292", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2016-04-05T20:43:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-19T06:03:00.000Z", "max_issues_repo_path": "py/fiberassign/hardware.py", "max_issues_repo_name": "desihub/fiberassign", "max_issues_repo_head_hexsha": "ac6e935614cad8c888f2bd5b93000eb955185292", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 323, "max_issues_repo_issues_event_min_datetime": "2015-07-29T15:19:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T00:15:57.000Z", "max_forks_repo_path": "py/fiberassign/hardware.py", "max_forks_repo_name": "desihub/fiberassign", "max_forks_repo_head_hexsha": "ac6e935614cad8c888f2bd5b93000eb955185292", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2015-04-10T14:16:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T23:14:03.000Z", "avg_line_length": 37.3131524008, "max_line_length": 110, "alphanum_fraction": 0.5932412018, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 4711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.2598256264980406, "lm_q1q2_score": 0.16363158192140925}}
{"text": "#!/usr/bin/env python\n\nimport staticmpdparser\nimport common\nfrom threading import Lock\nimport math\nimport videoplayer\nimport os\nimport pdb\nimport sys\nimport time\nfrom collections import OrderedDict\n\nimport os\nos.environ['CUDA_VISIBLE_DEVICES']=''\n\nimport numpy as np\nimport tensorflow as tf\nimport a3c\n\n## The following parameters are specific to Pensieve ABR\nS_INFO = 6  # bit_rate, buffer_size, rebuffering_time, bandwidth_measurement, chunk_til_video_end\nS_LEN = 8  # take how many frames in the past\nA_DIM = 6\nACTOR_LR_RATE = 0.0001\nCRITIC_LR_RATE = 0.001\n\nNN_MODEL = './pensieve_pretrained_models/pretrain_linear_reward.ckpt'\nDEFAULT_QUALITY = 0  # default video quality without agent\nM_IN_K = 1000.0\nMILLISECONDS_IN_SECOND = 1000.0\nREBUF_PENALTY = 4.3  # 1 sec rebuffering -> this number of Mbps\nSMOOTH_PENALTY = 1\nRAND_RANGE = 1000\nVIDEO_BIT_RATE = [300,750,1200,1850,2850,4300] # Kbps\nBUFFER_NORM_FACTOR = 10.0\nTOTAL_VIDEO_CHUNKS = 48\nCHUNK_TIL_VIDEO_END_CAP = 48.0\n\n# video chunk sizes\nsize_video1 = [2354772, 2123065, 2177073, 2160877, 2233056, 1941625, 2157535, 2290172, 2055469, 2169201, 2173522, 2102452, 2209463, 2275376, 2005399, 2152483, 2289689, 2059512, 2220726, 2156729, 2039773, 2176469, 2221506, 2044075, 2186790, 2105231, 2395588, 1972048, 2134614, 2164140, 2113193, 2147852, 2191074, 2286761, 2307787, 2143948, 1919781, 2147467, 2133870, 2146120, 2108491, 2184571, 2121928, 2219102, 2124950, 2246506, 1961140, 2155012, 1433658]\nsize_video2 = [1728879, 1431809, 1300868, 1520281, 1472558, 1224260, 1388403, 1638769, 1348011, 1429765, 1354548, 1519951, 1422919, 1578343, 1231445, 1471065, 1491626, 1358801, 1537156, 1336050, 1415116, 1468126, 1505760, 1323990, 1383735, 1480464, 1547572, 1141971, 1498470, 1561263, 1341201, 1497683, 1358081, 1587293, 1492672, 1439896, 1139291, 1499009, 1427478, 1402287, 1339500, 1527299, 1343002, 1587250, 1464921, 1483527, 1231456, 1364537, 889412]\nsize_video3 = [1034108, 957685, 877771, 933276, 996749, 801058, 905515, 1060487, 852833, 913888, 939819, 917428, 946851, 1036454, 821631, 923170, 966699, 885714, 987708, 923755, 891604, 955231, 968026, 874175, 897976, 905935, 1076599, 758197, 972798, 975811, 873429, 954453, 885062, 1035329, 1026056, 943942, 728962, 938587, 908665, 930577, 858450, 1025005, 886255, 973972, 958994, 982064, 830730, 846370, 598850]\nsize_video4 = [668286, 611087, 571051, 617681, 652874, 520315, 561791, 709534, 584846, 560821, 607410, 594078, 624282, 687371, 526950, 587876, 617242, 581493, 639204, 586839, 601738, 616206, 656471, 536667, 587236, 590335, 696376, 487160, 622896, 641447, 570392, 620283, 584349, 670129, 690253, 598727, 487812, 575591, 605884, 587506, 566904, 641452, 599477, 634861, 630203, 638661, 538612, 550906, 391450]\nsize_video5 = [450283, 398865, 350812, 382355, 411561, 318564, 352642, 437162, 374758, 362795, 353220, 405134, 386351, 434409, 337059, 366214, 360831, 372963, 405596, 350713, 386472, 399894, 401853, 343800, 359903, 379700, 425781, 277716, 400396, 400508, 358218, 400322, 369834, 412837, 401088, 365161, 321064, 361565, 378327, 390680, 345516, 384505, 372093, 438281, 398987, 393804, 331053, 314107, 255954]\nsize_video6 = [181801, 155580, 139857, 155432, 163442, 126289, 153295, 173849, 150710, 139105, 141840, 156148, 160746, 179801, 140051, 138313, 143509, 150616, 165384, 140881, 157671, 157812, 163927, 137654, 146754, 153938, 181901, 111155, 153605, 149029, 157421, 157488, 143881, 163444, 179328, 159914, 131610, 124011, 144254, 149991, 147968, 161857, 145210, 172312, 167025, 160064, 137507, 118421, 112270]\n## End of Pensieve parameters\n\nNETFLIX_INITIAL_BUFFER = 2\nNETFLIX_RESERVOIR = 0.1\nNETFLIX_CUSHION = 0.9\nNETFLIX_INITIAL_FACTOR = 0.875\n\n'''\nConfig defines the configuration that any ABR algo takes before processing.\nRight now, it takes 'fetches'.\nprepare will set the bitrates in ascending order, using the 'bandwidth' from mpd file.\n'''\nclass Config:\n    def __init__(self, mpd, base_url=None, verbose=False):\n        # Can house more parameters if needed\n        self.mpd = mpd\n        self.base_url = base_url\n        self.verbose = verbose\n        self.reps = None\n        if mpd.type != \"static\":\n            print \"Can only handle static MPDs.\"\n            sys.exit(1)\n        self.prepare()\n\n\n    def prepare(self):\n        \"Prepare by gathering info for each representation to download.\"\n        reps = []\n        print \"Fetcher prepare phase\"\n\n        # We assume only one adaption set here (for video).\n        adaptation_set = self.mpd.periods[0].adaptation_sets[0]\n        if self.verbose:\n            print adaptation_set\n        for rep in adaptation_set.representations:\n            init = adaptation_set.segment_template.initialization\n            # Check if the given rep has segment_template or else use parent\n            segment_template = adaptation_set.segment_template\n            if hasattr(rep, 'segment_template'):\n                media = rep.segment_template.media\n                segment_template = rep.segment_template\n            else:\n                media = adaptation_set.segment_template.media\n\n            rep_data = {'init' : init, 'media' : media,\n                        'duration' : segment_template.duration,\n                        'timescale' : segment_template.timescale,\n                        'dur_s' : (segment_template.duration * 1.0 /\n                                   segment_template.timescale),\n                        'startNr' : segment_template.startNumber,\n                        'periodDuration' : int(self.mpd.periods[0].duration),\n                        'base_url' : self.base_url,\n                        'bandwidth': rep.bandwidth,\n                        'height': rep.height,\n                        'id' : rep.id}\n            reps.append(rep_data)\n        self.reps = reps\n\n    # Returns the index in the self.fetch of the lowest bandwidth\n    def getLowestBitRateIndex(self):\n        min_val = self.reps[0]['bandwidth']\n        index = 0\n        for i, f in enumerate(self.reps):\n            if f['bandwidth'] < min_val:\n                min_val = f['bandwidth']\n                index = i\n        return index\n\n\nclass Client:\n\n    def download_init_segment(self, config, file_writer):\n        # 1. Find the lowest bit rate representation id\n        lowQualIndex = config.getLowestBitRateIndex()\n\n        # 2. Download the init segment in lowest quality.\n        fetchObj = config.reps[lowQualIndex]\n        # If there is a representationID, then replace it with least rep id\n        initName = fetchObj['init'].replace(\"$RepresentationID$\", \"video6\")\n        init_url = os.path.join(fetchObj['base_url'], initName)\n        print 'Using bitrate ', config.reps[lowQualIndex]['bandwidth'], ' for initial segment'\n        print 'init url', init_url\n        data, duration, size = common.fetch_file(init_url)\n        file_writer.write_file(initName, data)\n        return duration, size\n\n    def download_video_segment(self, config, fetcher, number):\n        # Download in lowest quality.\n        lowQualIndex = config.getLowestBitRateIndex()\n        return fetcher.fetch(config.reps[lowQualIndex], number)\n\n'''\nDownload all the representations.\n'''\nclass SimpleClient:\n    def __init__(self, mpd, base_url, base_dst):\n        # config can be the mpd file\n        self.config = Config(mpd, base_url)\n        self.file_writer = common.FileWriter(base_dst)\n\n    def download(self):\n        for rep in self.config.reps:\n            init_url = os.path.join(rep['base_url'], rep['init'])\n            data, _, _ = common.fetch_file(init_url)\n            self.file_writer.write_file(rep['init'], data)\n            thread = common.FetchThread(\"SegmentFetcher_%s\" % rep['id'], rep, self.file_writer)\n            thread.start()\n\n'''\nAbr class implements a basic ABR algo. init needs config which is of type Config\nquality_from_throughput is called with last observed tput value.\n'''\nclass AbrClient(Client):\n    def __init__(self, mpd, base_url, base_dst, options):\n        # config can be the mpd file\n        self.config = Config(mpd, base_url)\n        self.quality_rep_map = {}\n        self.file_writer = common.FileWriter(base_dst)\n        for rep in self.config.reps:\n            self.quality_rep_map[rep['bandwidth']] = rep\n        self.bitrates = self.quality_rep_map.keys()\n        self.bitrates.sort()\n        utility_offset = -math.log(self.bitrates[0]) # so utilities[0] = 0\n        self.utilities = [math.log(b) + utility_offset for b in self.bitrates]\n        self.buffer_size = options.buffer_size * 1000\n        self.verbose = options.verbose\n        self.quality_switch = 0\n        # Segment time is in ms\n        self.segment_time = self.config.reps[0]['dur_s']*1000\n        self.player = videoplayer.VideoPlayer(self.segment_time, self.utilities, self.bitrates)\n        self.bandwidth_changerscript_path = options.bandwidth_changerscript_path\n\n    def quality_from_throughput(self, tput):\n        # in seconds\n        segment_time = self.config.reps[0]['dur_s']\n        quality = 0\n        bitrates = self.quality_rep_map.keys() \n        bitrates.sort()\n        latency = 0.1 # 100ms\n        while (quality + 1 < len(bitrates) and (latency + (segment_time * bitrates[quality + 1])/tput) <= segment_time):\n            quality += 1\n        return bitrates[quality], quality\n\n    def download(self):\n        throughput = 0\n        # download init segment\n        duration, size = self.download_init_segment(self.config, self.file_writer)\n        fetcher = common.Fetcher(self.file_writer)\n        res_bitrates = [self.bitrates[0] / 1000]\n        startNumber = self.config.reps[0]['startNr'] \n        os.system('%s &' % self.bandwidth_changerscript_path)\n        # Download the first segment with lowest quality\n        duration, size = self.download_video_segment(self.config, fetcher, startNumber)\n        res_end_time = [duration]\n        last_quality  = self.bitrates[0]\n        # Re-calculate throughput and measure latency.\n        throughput = size/duration\n        #print size, duration, throughput\n        # Add the lowest quality to the buffer for first segment\n        self.player.buffer_contents += [0]\n        self.player.total_play_time += duration * 1000\n        if self.verbose:\n           print \"Downloaded first segment\"\n      \n        total_segments = self.config.reps[0]['periodDuration'] / self.config.reps[0]['dur_s']\n        cur_seg = 1\n        # Using index 0 - ASSUMPTION - all representation set have same duration and same start number\n        # Note - we do not need threads until there are multiple adaptation sets i.e. audio and video separate adaptation sets.\n        while cur_seg < total_segments:\n            number = startNumber + cur_seg\n            #if buffer is full\n            bufferOverflow = self.player.get_buffer_level() + self.segment_time - self.buffer_size\n            if bufferOverflow > 0:\n               print \"Buffer full\"\n               self.player.deplete_buffer(self.config.reps[0]['dur_s'] * 1000)\n\n            # Call Abr(throughput). It returns the highest quality id that can be fetched.\n            bitrateQuality, quality = self.quality_from_throughput(throughput)\n            #print 'Using quality', quality, 'for segment', cur_seg, 'based on throughput ', throughput\n            self.quality_switch += abs(last_quality - self.bitrates[quality])\n            last_quality = self.bitrates[quality]\n            # Use the quality as index to fetch the media\n            # quality directly corresponds to the index in self.fetches\n            duration, size = fetcher.fetch(self.quality_rep_map[bitrateQuality], number)\n            res_bitrates.append(self.bitrates[quality]/1000)\n            res_end_time.append(res_end_time[-1] + duration)\n            self.player.deplete_buffer(int(duration * 1000))\n            self.player.buffer_contents += [quality]\n            # Recalculate throughput\n            throughput = size*8/duration\n            cur_seg += 1\n\n        self.player.deplete_buffer(self.player.get_buffer_level())\n        print(\"Total play time = %d sec\" % (self.player.total_play_time/1000))\n        print('Total played utility: %f' % self.player.played_utility)\n        print('Avg played bitrate: %f' % (self.player.played_bitrate / total_segments))\n        print('Rebuffer time = %f sec' % (self.player.rebuffer_time / 1000))        \n        print('Rebuffer count = %d' % self.player.rebuffer_event_count)\n        print res_bitrates\n        print res_end_time\n        print(\"QOE metrics\")\n        bitrate_reward = self.player.played_bitrate / 1000.0\n        rebuf_penalty = REBUF_PENALTY * self.player.rebuffer_time / 1000.0\n        smooth_penalty = SMOOTH_PENALTY * self.quality_switch / 1000.0\n        total_qoe = bitrate_reward - rebuf_penalty - smooth_penalty\n        print(\"Total Bitrate Utility= \", bitrate_reward)\n        print(\"Rebuffer penalty= \", rebuf_penalty)\n        print(\"Smoothness penalty=\", smooth_penalty)\n        print(\"Average QOE=\", total_qoe/total_segments)\n\nclass BolaClient(Client):\n\n    def __init__(self, mpd, base_url, base_dst, options):\n        self.config = Config(mpd, base_url)\n        self.quality_rep_map = {}\n        self.file_writer = common.FileWriter(base_dst)\n        for rep in self.config.reps:\n            self.quality_rep_map[rep['bandwidth']] = rep\n        self.bitrates = self.quality_rep_map.keys()\n        self.bitrates.sort()\n        utility_offset = -math.log(self.bitrates[0]) # so utilities[0] = 0\n        self.utilities = [math.log(b) + utility_offset for b in self.bitrates]\n        self.verbose = options.verbose\n        self.gp = options.gp\n        self.quality_switch = 0\n        # buffer_size is in ms\n        self.buffer_size = options.buffer_size * 1000\n        print \"buffer = \", self.buffer_size, \"gp = \", self.gp\n\n        self.bandwidth_changerscript_path = options.bandwidth_changerscript_path\n        # Segment time is in ms\n        self.segment_time = self.config.reps[0]['dur_s']*1000\n        self.Vp = (self.buffer_size - self.segment_time) / (self.utilities[-1] + self.gp)\n        self.player = videoplayer.VideoPlayer(self.segment_time, self.utilities, self.bitrates)\n        if options.verbose:\n            for q in range(len(self.bitrates)):\n                b = self.bitrates[q]\n                u = self.utilities[q]\n                l = self.Vp * (self.gp + u)\n                if q == 0:\n                    print('%d %d' % (q, l))\n                else:\n                    qq = q - 1\n                    bb = self.bitrates[qq]\n                    uu = self.utilities[qq]\n                    ll = self.Vp * (self.gp + (b * uu - bb * u) / (b - bb))\n                    print('%d %d    <- %d %d' % (q, l, qq, ll))\n\n    def quality_from_buffer(self):\n        level = self.player.get_buffer_level()\n        quality = 0\n        score = None\n        for q in range(len(self.bitrates)):\n            s = ((self.Vp * (self.utilities[q] + self.gp) - level) / self.bitrates[q])\n            if score == None or s > score:\n                quality = q\n                score = s\n        return quality\n\n    def download(self):\n       # download init segment\n       self.download_init_segment(self.config, self.file_writer)\n       fetcher = common.Fetcher(self.file_writer)\n       os.system('%s &' % self.bandwidth_changerscript_path)\n       res_bitrates = [self.bitrates[0] / 1000]\n       # Download the first segment\n       duration, size = self.download_video_segment(self.config, fetcher, 1)\n       res_end_time = [duration]\n       last_quality = self.bitrates[0]\n       # Add the lowest quality to the buffer for first segment\n       self.player.buffer_contents += [0]\n       self.player.total_play_time += duration * 1000\n       if self.verbose:\n           print \"Downloaded first segment\\n\"\n       total_segments = self.config.reps[0]['periodDuration'] / self.config.reps[0]['dur_s']\n       next_seg = 2\n       while next_seg <= total_segments:\n           #if buffer is full\n           bufferOverflow = self.player.get_buffer_level() + self.segment_time - self.buffer_size\n           if bufferOverflow > 0:\n               print \"bufferoverflow\"\n               self.player.deplete_buffer(self.config.reps[0]['dur_s'] * 1000)\n\n           quality = self.quality_from_buffer()\n           res_bitrates.append(self.bitrates[quality] / 1000)\n           #print 'Using quality', quality, 'for segment', next_seg, 'based on quality', quality\n           self.quality_switch += abs(last_quality - self.bitrates[quality])\n           last_quality = self.bitrates[quality]\n           duration, size = fetcher.fetch(self.quality_rep_map[self.bitrates[quality]], next_seg)\n           res_end_time.append(res_end_time[-1] + duration)\n           self.player.deplete_buffer(int(duration * 1000))\n           self.player.buffer_contents += [quality]\n           next_seg += 1\n\n       self.player.deplete_buffer(self.player.get_buffer_level())\n       print(\"Total play time = %d sec\" % (self.player.total_play_time/1000))\n       print('total played utility: %f' % self.player.played_utility)\n       print('Avg played bitrate: %f' % (self.player.played_bitrate / total_segments))\n       print('Total played bitrate: %d' % (self.player.played_bitrate))\n       print('Rebuffer time = %f sec' % (self.player.rebuffer_time / 1000))        \n       print('Rebuffer count = %d' % self.player.rebuffer_event_count)\n       print res_bitrates\n       print res_end_time\n       print(\"QOE metrics\")\n       bitrate_reward = self.player.played_bitrate / 1000.0\n       rebuf_penalty = REBUF_PENALTY * self.player.rebuffer_time / 1000.0\n       smooth_penalty = SMOOTH_PENALTY * self.quality_switch / 1000.0\n       total_qoe = bitrate_reward - rebuf_penalty - smooth_penalty\n       print(\"Total Bitrate Utility= \", bitrate_reward)\n       print(\"Rebuffer penalty= \", rebuf_penalty)\n       print(\"Smoothness penalty=\", smooth_penalty)\n       print(\"Average QOE=\", total_qoe/total_segments)\n\nclass BBAClient(Client):\n\n    def __init__(self, mpd, base_url, base_dst, options):\n        self.config = Config(mpd, base_url)\n        self.quality_rep_map = {}\n        self.file_writer = common.FileWriter(base_dst)\n        for rep in self.config.reps:\n            self.quality_rep_map[rep['bandwidth']] = rep\n        self.bitrates = self.quality_rep_map.keys()\n        self.bitrates.sort()\n        utility_offset = -math.log(self.bitrates[0]) # so utilities[0] = 0\n        self.utilities = [math.log(b) + utility_offset for b in self.bitrates]\n        self.verbose = options.verbose\n        self.gp = options.gp\n        self.quality_switch = 0\n        self.rate_map = self.get_rate_map()\n        # buffer_size is in ms\n        self.buffer_size = options.buffer_size * 1000\n\n        # Segment time is in ms\n        self.segment_time = self.config.reps[0]['dur_s']*1000\n        self.bandwidth_changerscript_path = options.bandwidth_changerscript_path\n        self.player = videoplayer.VideoPlayer(self.segment_time, self.utilities, self.bitrates)\n\n    def get_rate_map(self):\n        \"\"\"\n        Module to generate the rate map for the bitrates, reservoir, and cushion\n        \"\"\"\n        rate_map = OrderedDict()\n        rate_map[NETFLIX_RESERVOIR] = 0\n        #intermediate_levels = self.bitrates[1:-1]\n        blen = len(self.bitrates)\n        marker_length = (NETFLIX_CUSHION - NETFLIX_RESERVOIR)/(blen - 1)\n        current_marker = NETFLIX_RESERVOIR + marker_length\n        for quality in range(1, blen-1):\n            rate_map[current_marker] = quality\n            current_marker += marker_length\n        rate_map[NETFLIX_CUSHION] = blen - 1\n        return rate_map\n\n    def get_quality_netflix(self, rate_map=None):\n        \"\"\"\n        Module that estimates the next bitrate basedon the rate map.\n        Rate Map: Buffer Occupancy vs. Bitrates:\n            If Buffer Occupancy < RESERVOIR (10%) :\n                select the minimum bitrate\n            if RESERVOIR < Buffer Occupancy < Cushion(90%) :\n                Linear function based on the rate map\n            if Buffer Occupancy > Cushion :\n                Maximum Bitrate\n        Ref. Fig. 6 from [1]\n        :param current_buffer_occupancy: Current buffer occupancy in number of segments\n        :param bitrates: List of available bitrates [r_min, .... r_max]\n        :return:the bitrate for the next segment\n        \"\"\"\n        next_bitrate = None\n        # Calculate the current buffer occupancy percentage\n        try:\n            buffer_percentage = self.player.get_buffer_level()/self.buffer_size\n            #print buffer_percentage\n        except ZeroDivisionError:\n            print \"Buffer Size was found to be Zero\"\n            return None\n        # Selecting the next bitrate based on the rate map\n        #print \"buffer percentage = \", buffer_percentage        \n        if buffer_percentage <= NETFLIX_RESERVOIR:\n            next_bitrate = 0\n        elif buffer_percentage >= NETFLIX_CUSHION:\n            next_bitrate = len(self.bitrates) - 1\n        else:\n            #if self.verbose:\n            #    print \"Rate Map: {}\".format(self.rate_map)\n            for marker in reversed(self.rate_map.keys()):\n                if marker < buffer_percentage:\n                    break\n                next_bitrate = self.rate_map[marker]\n        return next_bitrate\n\n    def get_quality_bba2(self, average_segment_sizes, segment_download_rate, curr_bitrate, state):\n        available_video_segments = self.player.get_buffer_level()\n        if state == \"INITIAL\":\n            # if the B increases by more than 0.875V s. Since B = V - ChunkSize/c[k],\n            # B > 0:875V also means that the chunk is downloaded eight times faster than it is played\n            next_bitrate = curr_bitrate\n            # delta-B = V - ChunkSize/c[k]\n            #print \"curr bit rate = \", curr_bitrate, \" download rate = \", segment_download_rate\n            delta_B = (self.segment_time/1000) - average_segment_sizes[curr_bitrate]/segment_download_rate\n            # Select the higher bitrate as long as delta B > 0.875 * V\n            if delta_B > NETFLIX_INITIAL_FACTOR * self.segment_time:\n                next_bitrate = self.bitrates.index(curr_bitrate)+1\n            # if the current buffer occupancy is less that NETFLIX_INITIAL_BUFFER, then do NOY use rate map\n            if not available_video_segments < NETFLIX_INITIAL_BUFFER:\n\n                # get the next bitrate based on the ratemap\n                rate_map_next_bitrate = self.get_quality_netflix()\n                # Consider the rate map only if the rate map gives a higher value.\n                # Once the rate mao returns a higher value exit the 'INITIAL' stage\n                if rate_map_next_bitrate > next_bitrate:\n                    next_bitrate = rate_map_next_bitrate\n                    state = \"RUNNING\"\n        else:\n            next_bitrate = self.get_quality_netflix()\n        return next_bitrate, state\n\n\n\n    def download_bba0(self):\n        # download init segment\n       self.download_init_segment(self.config, self.file_writer)\n       fetcher = common.Fetcher(self.file_writer)\n       os.system('%s &' % self.bandwidth_changerscript_path)\n       res_bitrates = [self.bitrates[0] / 1000]\n       \n       # Download the first segment\n       duration, size = self.download_video_segment(self.config, fetcher, 1)\n       res_end_time = [duration]\n       last_quality = self.bitrates[0]\n       # Add the lowest quality to the buffer for first segment\n       self.player.buffer_contents += [0]\n       self.player.total_play_time += duration * 1000\n       #if self.verbose:\n           #print \"Downloaded first segment\\n\"\n       total_segments = self.config.reps[0]['periodDuration'] / self.config.reps[0]['dur_s']\n       next_seg = 2\n       while next_seg <= total_segments:\n           #if buffer is full\n           bufferOverflow = self.player.get_buffer_level() + self.segment_time - self.buffer_size\n           if bufferOverflow > 0:\n               self.player.deplete_buffer(self.config.reps[0]['dur_s'] * 1000)\n\n           quality = self.get_quality_netflix()\n           self.quality_switch += abs(last_quality - self.bitrates[quality])\n           last_quality = self.bitrates[quality]\n           #print 'Using quality ', quality, 'for segment ', next_seg, 'based on quality ', quality\n           res_bitrates.append(self.bitrates[quality] / 1000)\n           duration, size = fetcher.fetch(self.quality_rep_map[self.bitrates[quality]], next_seg)\n           res_end_time.append(res_end_time[-1] + duration)\n           self.player.deplete_buffer(int(duration * 1000))\n           self.player.buffer_contents += [quality]\n           next_seg += 1\n\n       self.player.deplete_buffer(self.player.get_buffer_level())\n       print(\"Total play time = %d sec\" % (self.player.total_play_time/1000))\n       print('total played utility: %f' % self.player.played_utility)\n       print('Avg played bitrate: %f' % (self.player.played_bitrate / total_segments))\n       print('Rebuffer time = %f sec' % (self.player.rebuffer_time / 1000))\n       print('Rebuffer count = %d' % self.player.rebuffer_event_count)\n       print res_bitrates\n       print res_end_time\n       print(\"QOE metrics\")\n       bitrate_reward = self.player.played_bitrate / 1000.0\n       rebuf_penalty = REBUF_PENALTY * self.player.rebuffer_time / 1000.0\n       smooth_penalty = SMOOTH_PENALTY * self.quality_switch / 1000.0\n       total_qoe = bitrate_reward - rebuf_penalty - smooth_penalty\n       print(\"Total Bitrate Utility= \", bitrate_reward)\n       print(\"Rebuffer penalty= \", rebuf_penalty)\n       print(\"Smoothness penalty=\", smooth_penalty)\n       print(\"Average QOE=\", total_qoe/total_segments)\n    \n    def get_average_segment_sizes(self):\n        \"\"\"\n        Module to get the avearge segment sizes for each bitrate\n        :param dp_object:\n        :return: A dictionary of aveage segment sizes for each bitrate\n        \"\"\"\n        average_segment_sizes = dict()\n        average_segment_sizes[0] = sum(size_video6)/CHUNK_TIL_VIDEO_END_CAP\n        average_segment_sizes[1] = sum(size_video5)/CHUNK_TIL_VIDEO_END_CAP\n        average_segment_sizes[2] = sum(size_video4)/CHUNK_TIL_VIDEO_END_CAP\n        average_segment_sizes[3] = sum(size_video3)/CHUNK_TIL_VIDEO_END_CAP\n        average_segment_sizes[4] = sum(size_video2)/CHUNK_TIL_VIDEO_END_CAP\n        average_segment_sizes[5] = sum(size_video1)/CHUNK_TIL_VIDEO_END_CAP\n        \n        #print \"The average segment size for is {}\".format(average_segment_sizes.items())\n        return average_segment_sizes\n\n\n    def download_bba2(self):\n       # download init segment\n       self.download_init_segment(self.config, self.file_writer)\n       fetcher = common.Fetcher(self.file_writer)\n       os.system('%s &' % self.bandwidth_changerscript_path)\n       res_bitrates = [self.bitrates[0] / 1000]\n       # get average segment sizes.\n       average_segment_sizes = self.get_average_segment_sizes()\n      \n      \n       # Download the first segment\n       duration, size = self.download_video_segment(self.config, fetcher, 1)\n       # Add the lowest quality to the buffer for first segment\n       last_quality = self.bitrates[0]\n       res_end_time = [duration]\n       self.player.buffer_contents += [0]\n       self.player.total_play_time += duration * 1000\n       \n       segment_size = segment_download_time  = None\n       state = \"INITIAL\"\n       total_segments = self.config.reps[0]['periodDuration'] / self.config.reps[0]['dur_s']\n       next_seg = 2\n       curr_bitrate = 0\n       segment_download_rate = size / duration\n       while next_seg <= total_segments:\n           #if buffer is full\n           bufferOverflow = self.player.get_buffer_level() + self.segment_time - self.buffer_size\n           if bufferOverflow > 0:\n               print \"overflow\"\n               self.player.deplete_buffer(self.config.reps[0]['dur_s'] * 1000)\n\n           if segment_size and segment_download_time:\n               segment_download_rate = segment_size / segment_download_time\n           \n           curr_bitrate, state = self.get_quality_bba2(average_segment_sizes, segment_download_rate, curr_bitrate, state)\n           quality = curr_bitrate\n           self.quality_switch += abs(last_quality - self.bitrates[quality])\n           last_quality = self.bitrates[quality]\n           print 'Using quality ', quality, 'for segment ', next_seg, 'based on quality ', quality\n           res_bitrates.append(self.bitrates[quality] / 1000)\n           segment_download_time, segment_size = fetcher.fetch(self.quality_rep_map[self.bitrates[quality]], next_seg)\n           res_end_time.append(res_end_time[-1] + segment_download_time)\n           self.player.deplete_buffer(int(segment_download_time * 1000))\n           self.player.buffer_contents += [quality]\n           next_seg += 1\n\n       self.player.deplete_buffer(self.player.get_buffer_level())\n       print(\"Total play time = %d sec\" % (self.player.total_play_time/1000))\n       print('total played utility: %f' % self.player.played_utility)\n       print('Avg played bitrate: %f' % (self.player.played_bitrate / total_segments))\n       print('Rebuffer time = %f sec' % (self.player.rebuffer_time / 1000))\n       print('Rebuffer count = %d' % self.player.rebuffer_event_count)\n       print res_bitrates\n       print res_end_time\n       print(\"QOE metrics\")\n       bitrate_reward = self.player.played_bitrate / 1000.0\n       rebuf_penalty = REBUF_PENALTY * self.player.rebuffer_time / 1000.0\n       smooth_penalty = SMOOTH_PENALTY * self.quality_switch / 1000.0\n       total_qoe = bitrate_reward - rebuf_penalty - smooth_penalty\n       print(\"Total Bitrate Utility= \", bitrate_reward)\n       print(\"Rebuffer penalty= \", rebuf_penalty)\n       print(\"Smoothness penalty=\", smooth_penalty)\n       print(\"Average QOE=\", total_qoe/total_segments)\n\nclass PensieveClient(Client):\n    def __init__(self, mpd, base_url, base_dst, options):\n        self.config = Config(mpd, base_url)\n        self.quality_rep_map = {}\n        self.file_writer = common.FileWriter(base_dst)\n\n        for rep in self.config.reps:\n            self.quality_rep_map[rep['bandwidth']] = rep\n\n        self.bitrates = self.quality_rep_map.keys()\n        self.bitrates.sort()\n        utility_offset = -math.log(self.bitrates[0])\n        self.utilities = [math.log(b) + utility_offset for b in self.bitrates]\n        self.buffer_size = options.buffer_size * 1000\n        self.verbose = options.verbose\n        self.segment_time = self.config.reps[0]['dur_s']*1000\n        self.bandwidth_changerscript_path = options.bandwidth_changerscript_path\n        self.player = videoplayer.VideoPlayer(self.segment_time, self.utilities, self.bitrates)\n        self.sess = tf.Session()\n        self.quality_switch =  0\n        self.actor = a3c.ActorNetwork(self.sess, state_dim=[S_INFO, S_LEN], action_dim=A_DIM, learning_rate=ACTOR_LR_RATE)\n        self.critic = a3c.CriticNetwork(self.sess, state_dim=[S_INFO, S_LEN], learning_rate=CRITIC_LR_RATE)\n\n        self.sess.run(tf.initialize_all_variables())\n        self.saver = tf.train.Saver()\n\n        # restore neural net parameters\n        self.nn_model = NN_MODEL\n        if self.nn_model is not None:  # nn_model is the path to file\n            self.saver.restore(self.sess, self.nn_model)\n            print(\"Model restored.\")\n\n        self.init_action = np.zeros(A_DIM)\n        self.init_action[DEFAULT_QUALITY] = 1\n\n        self.s_batch = [np.zeros((S_INFO, S_LEN))]\n        self.a_batch = [self.init_action]\n        self.r_batch = []\n\n        self.last_quality = DEFAULT_QUALITY\n        self.last_bit_rate = DEFAULT_QUALITY\n        # need this storage, because observation only contains total rebuffering time\n        # we compute the difference to get\n\n        self.last_total_rebuf = 0\n        self.video_chunk_count = 0\n        self.chunk_fetch_time = 0\n        self.chunk_size = 0\n        self.ptime = 0\n\n    def get_chunk_size(self, quality, index):\n        if index+A_DIM <= TOTAL_VIDEO_CHUNKS:\n            # note that the quality and video labels are inverted (i.e., quality 5 is highest and this pertains to video1)\n            sizes = {5: size_video1[index], 4: size_video2[index], 3: size_video3[index], 2: size_video4[index], 1: size_video5[index], 0: size_video6[index]}\n            return sizes[quality]\n        else:\n            return 0\n\n    def get_quality_delay(self, segment_index):\n        rebuffer_time = self.player.rebuffer_time - self.last_total_rebuf\n        reward = VIDEO_BIT_RATE[self.last_quality] / M_IN_K - REBUF_PENALTY * rebuffer_time / M_IN_K - SMOOTH_PENALTY * np.abs(VIDEO_BIT_RATE[self.last_quality] - self.last_bit_rate) / M_IN_K\n\n        self.last_bit_rate = VIDEO_BIT_RATE[self.last_quality]\n        self.last_total_rebuf = self.player.rebuffer_time\n\n        # retrieve previous state\n        if len(self.s_batch) == 0:\n            state = [np.zeros((S_INFO, S_LEN))]\n        else:\n            state = np.array(self.s_batch[-1], copy=True)\n\n        # compute bandwidth measurement\n        # in ms\n        video_chunk_fetch_time = self.chunk_fetch_time * 1000\n        video_chunk_size = self.chunk_size\n\n        # compute number of video chunks left\n        video_chunk_remain = TOTAL_VIDEO_CHUNKS - self.video_chunk_count\n        self.video_chunk_count += 1\n        self.ptime += self.chunk_fetch_time\n\n        #print(\"Time\", self.ptime, \"Video bit rate\", self.last_bit_rate, \"Buffer\", self.player.get_buffer_level() / MILLISECONDS_IN_SECOND, \"Chunk size\", video_chunk_size, \"duration\", video_chunk_fetch_time, \"reward\", reward)\n\n        # dequeue history record\n        state = np.roll(state, -1, axis=1)\n\n        next_video_chunk_sizes = []\n        for i in range(A_DIM):\n            next_video_chunk_sizes.append(self.get_chunk_size(i, self.video_chunk_count))\n\n        # this should be S_INFO number of terms\n        try:\n            # bit_rate\n            state[0, -1] = VIDEO_BIT_RATE[self.last_quality] / float(np.max(VIDEO_BIT_RATE))\n            # buffer_size\n            state[1, -1] = self.player.get_buffer_level() / MILLISECONDS_IN_SECOND / BUFFER_NORM_FACTOR\n            # rebuffering_time\n            state[2, -1] = float(video_chunk_size) / float(video_chunk_fetch_time) / M_IN_K  # kilo byte / ms\n            state[3, -1] = float(video_chunk_fetch_time) / M_IN_K / BUFFER_NORM_FACTOR  # 10 sec\n            # bandwidth_measurement\n            state[4, :A_DIM] = np.array(next_video_chunk_sizes) / M_IN_K / M_IN_K  # mega byte\n            # chunk_til_video_end\n            state[5, -1] = np.minimum(video_chunk_remain, CHUNK_TIL_VIDEO_END_CAP) / float(CHUNK_TIL_VIDEO_END_CAP)\n        except ZeroDivisionError:\n            # this should occur VERY rarely (1 out of 3000), should be a dash issue\n            # in this case we ignore the observation and roll back to an eariler one\n            if len(self.s_batch) == 0:\n                state = [np.zeros((S_INFO, S_LEN))]\n            else:\n                state = np.array(self.s_batch[-1], copy=True)\n\n        action_prob = self.actor.predict(np.reshape(state, (1, S_INFO, S_LEN)))\n        action_cumsum = np.cumsum(action_prob)\n        bit_rate = (action_cumsum > np.random.randint(1, RAND_RANGE) / float(RAND_RANGE)).argmax()\n        \n        # put it here after training, notice there is a shift in reward storage\n        if self.video_chunk_count >= TOTAL_VIDEO_CHUNKS:\n            self.s_batch = [np.zeros((S_INFO, S_LEN))]\n        else:\n            self.s_batch.append(state)\n\n        self.last_quality = bit_rate\n\n        return bit_rate\n\n    def download_pensieve(self):\n        # Download init segment\n        self.download_init_segment(self.config, self.file_writer)\n        fetcher = common.Fetcher(self.file_writer)\n        os.system('%s &' % self.bandwidth_changerscript_path)\n        res_bitrates = [self.bitrates[0] / 1000]\n\n        # Download the first segment\n        duration, size = self.download_video_segment(self.config, fetcher, 1)\n        self.chunk_size = size\n        self.chunk_fetch_time = duration\n        # Add the lowest quality to the buffer for first segment\n        self.player.buffer_contents += [0]\n        self.player.total_play_time += duration * 1000\n        last_quality = self.bitrates[0]\n        res_end_time = [duration]\n        if self.verbose:\n            print \"Downloaded first segment\\n\"\n        self.video_chunk_count += 1\n\n        next_seg = 2\n        while next_seg <= TOTAL_VIDEO_CHUNKS:\n            bufferOverflow = self.player.get_buffer_level() + self.segment_time  - self.buffer_size\n            if bufferOverflow > 0:\n                self.player.deplete_buffer( self.segment_time)\n            \n            quality = self.get_quality_delay(next_seg)\n            self.quality_switch += abs(last_quality - self.bitrates[quality])\n            last_quality = self.bitrates[quality]\n            res_bitrates.append(self.bitrates[quality] / 1000)\n            #print 'Using quality ', quality, 'for segment ', next_seg\n            duration, size = fetcher.fetch(self.quality_rep_map[self.bitrates[quality]], next_seg)\n            res_end_time.append(res_end_time[-1] + duration)\n            #res_end_time.append(self.player.total_play_time)\n            self.chunk_size = size\n            self.chunk_fetch_time = duration\n            self.player.deplete_buffer(int(duration * 1000))\n            self.player.buffer_contents += [quality]\n            next_seg += 1\n\n        self.player.deplete_buffer(self.player.get_buffer_level())\n        print(\"Total play time = %d sec\" % (self.player.total_play_time/1000))\n        print('Total played utility= %f' % self.player.played_utility)\n        print('Avg played bitrate= %f' % (self.player.played_bitrate / TOTAL_VIDEO_CHUNKS))\n        print('Rebuffer time = %f sec' % (self.player.rebuffer_time / 1000)) \n        print('Rebuffer count = %d' % self.player.rebuffer_event_count)\n        print res_bitrates\n        print res_end_time\n        print(\"QOE metrics\")\n        bitrate_reward = self.player.played_bitrate / 1000.0\n        rebuf_penalty = REBUF_PENALTY * self.player.rebuffer_time / 1000.0\n        smooth_penalty = SMOOTH_PENALTY * self.quality_switch / 1000.0\n        total_qoe = bitrate_reward - rebuf_penalty - smooth_penalty\n        print(\"Total Bitrate Utility= \", bitrate_reward)\n        print(\"Rebuffer penalty= \", rebuf_penalty)\n        print(\"Smoothness penalty=\", smooth_penalty)\n        print(\"Average QOE=\", total_qoe/TOTAL_VIDEO_CHUNKS)\n", "meta": {"hexsha": "8515b6e233d641e8e48bf71f42548fdd56ba25e8", "size": 38335, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/dash_tools/client.py", "max_stars_repo_name": "jainsat/media-tools", "max_stars_repo_head_hexsha": "1f457d3a84dc3e1c8a5461774ebd45bcbb2eefb4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-26T06:34:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T06:34:08.000Z", "max_issues_repo_path": "python/dash_tools/client.py", "max_issues_repo_name": "jainsat/media-tools", "max_issues_repo_head_hexsha": "1f457d3a84dc3e1c8a5461774ebd45bcbb2eefb4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/dash_tools/client.py", "max_forks_repo_name": "jainsat/media-tools", "max_forks_repo_head_hexsha": "1f457d3a84dc3e1c8a5461774ebd45bcbb2eefb4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-18T22:08:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-18T22:08:07.000Z", "avg_line_length": 48.9591315453, "max_line_length": 455, "alphanum_fraction": 0.6531889918, "include": true, "reason": "import numpy", "num_tokens": 9768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.25982562649804053, "lm_q1q2_score": 0.16363158192140922}}
{"text": "# -*- coding: utf-8 -*-\n# @Author  : LG\nfrom __future__ import division\nfrom collections import defaultdict\nimport itertools\nimport numpy as np\nimport six\n\n__all__ = ['eval_detection_voc']\n\ndef bbox_iou(bbox_a, bbox_b):\n    \"\"\"Calculate the Intersection of Unions (IoUs) between bounding boxes.\n    IoU is calculated as a ratio of area of the intersection\n    and area of the union.\n    This function accepts both :obj:`numpy.ndarray` and :obj:`cupy.ndarray` as\n    inputs. Please note that both :obj:`bbox_a` and :obj:`bbox_b` need to be\n    same type.\n    The output is same type as the type of the inputs.\n    Args:\n        bbox_a (array): An array whose shape is :math:`(N, 4)`.\n            :math:`N` is the number of bounding boxes.\n            The dtype should be :obj:`numpy.float32`.\n        bbox_b (array): An array similar to :obj:`bbox_a`,\n            whose shape is :math:`(K, 4)`.\n            The dtype should be :obj:`numpy.float32`.\n    Returns:\n        array:\n        An array whose shape is :math:`(N, K)`. \\\n        An element at index :math:`(n, k)` contains IoUs between \\\n        :math:`n` th bounding box in :obj:`bbox_a` and :math:`k` th bounding \\\n        box in :obj:`bbox_b`.\n    \"\"\"\n    if bbox_a.shape[1] != 4 or bbox_b.shape[1] != 4:\n        raise IndexError\n\n    # top left\n    tl = np.maximum(bbox_a[:, None, :2], bbox_b[:, :2])\n    # bottom right\n    br = np.minimum(bbox_a[:, None, 2:], bbox_b[:, 2:])\n\n    area_i = np.prod(br - tl, axis=2) * (tl < br).all(axis=2)\n    area_a = np.prod(bbox_a[:, 2:] - bbox_a[:, :2], axis=1)\n    area_b = np.prod(bbox_b[:, 2:] - bbox_b[:, :2], axis=1)\n    return area_i / (area_a[:, None] + area_b - area_i)\n\n\ndef eval_detection_voc(\n        pred_bboxes,\n        pred_labels,\n        pred_scores,\n        gt_bboxes,\n        gt_labels,\n        gt_difficults=None,\n        iou_thresh=0.5,\n        use_07_metric=False):\n    \"\"\"Calculate average precisions based on evaluation code of PASCAL VOC.\n\n    This function evaluates predicted bounding boxes obtained from a dataset\n    which has :math:`N` images by using average precision for each class.\n    The code is based on the evaluation code used in PASCAL VOC Challenge.\n\n    Args:\n        pred_bboxes (iterable of numpy.ndarray): An iterable of :math:`N`\n            sets of bounding boxes.\n            Its index corresponds to an index for the base dataset.\n            Each element of :obj:`pred_bboxes` is a set of coordinates\n            of bounding boxes. This is an array whose shape is :math:`(R, 4)`,\n            where :math:`R` corresponds\n            to the number of bounding boxes, which may vary among boxes.\n            The second axis corresponds to\n            :math:`y_{min}, x_{min}, y_{max}, x_{max}` of a bounding box.\n        pred_labels (iterable of numpy.ndarray): An iterable of labels.\n            Similar to :obj:`pred_bboxes`, its index corresponds to an\n            index for the base dataset. Its length is :math:`N`.\n        pred_scores (iterable of numpy.ndarray): An iterable of confidence\n            scores for predicted bounding boxes. Similar to :obj:`pred_bboxes`,\n            its index corresponds to an index for the base dataset.\n            Its length is :math:`N`.\n        gt_bboxes (iterable of numpy.ndarray): An iterable of ground truth\n            bounding boxes\n            whose length is :math:`N`. An element of :obj:`gt_bboxes` is a\n            bounding box whose shape is :math:`(R, 4)`. Note that the number of\n            bounding boxes in each image does not need to be same as the number\n            of corresponding predicted boxes.\n        gt_labels (iterable of numpy.ndarray): An iterable of ground truth\n            labels which are organized similarly to :obj:`gt_bboxes`.\n        gt_difficults (iterable of numpy.ndarray): An iterable of boolean\n            arrays which is organized similarly to :obj:`gt_bboxes`.\n            This tells whether the\n            corresponding ground truth bounding box is difficult or not.\n            By default, this is :obj:`None`. In that case, this function\n            considers all bounding boxes to be not difficult.\n        iou_thresh (float): A prediction is correct if its Intersection over\n            Union with the ground truth is above this value.\n        use_07_metric (bool): Whether to use PASCAL VOC 2007 evaluation metric\n            for calculating average precision. The default value is\n            :obj:`False`.\n\n    Returns:\n        dict:\n\n        The keys, value-types and the description of the values are listed\n        below.\n\n        * **ap** (*numpy.ndarray*): An array of average precisions. \\\n            The :math:`l`-th value corresponds to the average precision \\\n            for class :math:`l`. If class :math:`l` does not exist in \\\n            either :obj:`pred_labels` or :obj:`gt_labels`, the corresponding \\\n            value is set to :obj:`numpy.nan`.\n        * **map** (*float*): The average of Average Precisions over classes.\n\n    \"\"\"\n\n    prec, rec = calc_detection_voc_prec_rec(pred_bboxes,\n                                            pred_labels,\n                                            pred_scores,\n                                            gt_bboxes,\n                                            gt_labels,\n                                            gt_difficults,\n                                            iou_thresh=iou_thresh)\n\n    ap = calc_detection_voc_ap(prec, rec, use_07_metric=use_07_metric)\n\n    return {'ap': ap, 'map': np.nanmean(ap)}\n\n\ndef calc_detection_voc_prec_rec(\n        pred_bboxes, pred_labels, pred_scores, gt_bboxes, gt_labels,\n        gt_difficults=None,\n        iou_thresh=0.5):\n    \"\"\"Calculate precision and recall based on evaluation code of PASCAL VOC.\n\n    This function calculates precision and recall of\n    predicted bounding boxes obtained from a dataset which has :math:`N`\n    images.\n    The code is based on the evaluation code used in PASCAL VOC Challenge.\n\n    Args:\n        pred_bboxes (iterable of numpy.ndarray): An iterable of :math:`N`\n            sets of bounding boxes.\n            Its index corresponds to an index for the base dataset.\n            Each element of :obj:`pred_bboxes` is a set of coordinates\n            of bounding boxes. This is an array whose shape is :math:`(R, 4)`,\n            where :math:`R` corresponds\n            to the number of bounding boxes, which may vary among boxes.\n            The second axis corresponds to\n            :math:`y_{min}, x_{min}, y_{max}, x_{max}` of a bounding box.\n        pred_labels (iterable of numpy.ndarray): An iterable of labels.\n            Similar to :obj:`pred_bboxes`, its index corresponds to an\n            index for the base dataset. Its length is :math:`N`.\n        pred_scores (iterable of numpy.ndarray): An iterable of confidence\n            scores for predicted bounding boxes. Similar to :obj:`pred_bboxes`,\n            its index corresponds to an index for the base dataset.\n            Its length is :math:`N`.\n        gt_bboxes (iterable of numpy.ndarray): An iterable of ground truth\n            bounding boxes\n            whose length is :math:`N`. An element of :obj:`gt_bboxes` is a\n            bounding box whose shape is :math:`(R, 4)`. Note that the number of\n            bounding boxes in each image does not need to be same as the number\n            of corresponding predicted boxes.\n        gt_labels (iterable of numpy.ndarray): An iterable of ground truth\n            labels which are organized similarly to :obj:`gt_bboxes`.\n        gt_difficults (iterable of numpy.ndarray): An iterable of boolean\n            arrays which is organized similarly to :obj:`gt_bboxes`.\n            This tells whether the\n            corresponding ground truth bounding box is difficult or not.\n            By default, this is :obj:`None`. In that case, this function\n            considers all bounding boxes to be not difficult.\n        iou_thresh (float): A prediction is correct if its Intersection over\n            Union with the ground truth is above this value..\n\n    Returns:\n        tuple of two lists:\n        This function returns two lists: :obj:`prec` and :obj:`rec`.\n\n        * :obj:`prec`: A list of arrays. :obj:`prec[l]` is precision \\\n            for class :math:`l`. If class :math:`l` does not exist in \\\n            either :obj:`pred_labels` or :obj:`gt_labels`, :obj:`prec[l]` is \\\n            set to :obj:`None`.\n        * :obj:`rec`: A list of arrays. :obj:`rec[l]` is recall \\\n            for class :math:`l`. If class :math:`l` that is not marked as \\\n            difficult does not exist in \\\n            :obj:`gt_labels`, :obj:`rec[l]` is \\\n            set to :obj:`None`.\n\n    \"\"\"\n\n    pred_bboxes = iter(pred_bboxes)\n    pred_labels = iter(pred_labels)\n    pred_scores = iter(pred_scores)\n    gt_bboxes = iter(gt_bboxes)\n    gt_labels = iter(gt_labels)\n    if gt_difficults is None:\n        gt_difficults = itertools.repeat(None)\n    else:\n        gt_difficults = iter(gt_difficults)\n\n    n_pos = defaultdict(int)\n    score = defaultdict(list)\n    match = defaultdict(list)\n\n    for pred_bbox, pred_label, pred_score, gt_bbox, gt_label, gt_difficult in \\\n            six.moves.zip(\n                pred_bboxes, pred_labels, pred_scores,\n                gt_bboxes, gt_labels, gt_difficults):\n\n        if gt_difficult is None:\n            gt_difficult = np.zeros(gt_bbox.shape[0], dtype=bool)\n\n        for l in np.unique(np.concatenate((pred_label, gt_label)).astype(int)):\n            pred_mask_l = pred_label == l\n            pred_bbox_l = pred_bbox[pred_mask_l]\n            pred_score_l = pred_score[pred_mask_l]\n            # sort by score\n            order = pred_score_l.argsort()[::-1]\n            pred_bbox_l = pred_bbox_l[order]\n            pred_score_l = pred_score_l[order]\n\n            gt_mask_l = gt_label == l\n            gt_bbox_l = gt_bbox[gt_mask_l]\n            gt_difficult_l = gt_difficult[gt_mask_l]\n\n            n_pos[l] += np.logical_not(gt_difficult_l).sum()\n            score[l].extend(pred_score_l)\n\n            if len(pred_bbox_l) == 0:\n                continue\n            if len(gt_bbox_l) == 0:\n                match[l].extend((0,) * pred_bbox_l.shape[0])\n                continue\n\n            # VOC evaluation follows integer typed bounding boxes.\n            pred_bbox_l = pred_bbox_l.copy()\n            pred_bbox_l[:, 2:] += 1\n            gt_bbox_l = gt_bbox_l.copy()\n            gt_bbox_l[:, 2:] += 1\n\n            iou = bbox_iou(pred_bbox_l, gt_bbox_l)\n            gt_index = iou.argmax(axis=1)\n            # set -1 if there is no matching ground truth\n            gt_index[iou.max(axis=1) < iou_thresh] = -1\n            del iou\n\n            selec = np.zeros(gt_bbox_l.shape[0], dtype=bool)\n            for gt_idx in gt_index:\n                if gt_idx >= 0:\n                    if gt_difficult_l[gt_idx]:\n                        match[l].append(-1)\n                    else:\n                        if not selec[gt_idx]:\n                            match[l].append(1)\n                        else:\n                            match[l].append(0)\n                    selec[gt_idx] = True\n                else:\n                    match[l].append(0)\n\n    for iter_ in (\n            pred_bboxes, pred_labels, pred_scores,\n            gt_bboxes, gt_labels, gt_difficults):\n        if next(iter_, None) is not None:\n            raise ValueError('Length of input iterables need to be same.')\n\n    n_fg_class = max(n_pos.keys()) + 1\n    prec = [None] * n_fg_class\n    rec = [None] * n_fg_class\n\n    for l in n_pos.keys():\n        score_l = np.array(score[l])\n        match_l = np.array(match[l], dtype=np.int8)\n\n        order = score_l.argsort()[::-1]\n        match_l = match_l[order]\n\n        tp = np.cumsum(match_l == 1)\n        fp = np.cumsum(match_l == 0)\n\n        # If an element of fp + tp is 0,\n        # the corresponding element of prec[l] is nan.\n        prec[l] = tp / (fp + tp)\n        # If n_pos[l] is 0, rec[l] is None.\n        if n_pos[l] > 0:\n            rec[l] = tp / n_pos[l]\n\n    return prec, rec\n\n\ndef calc_detection_voc_ap(prec, rec, use_07_metric=False):\n    \"\"\"Calculate average precisions based on evaluation code of PASCAL VOC.\n\n    This function calculates average precisions\n    from given precisions and recalls.\n    The code is based on the evaluation code used in PASCAL VOC Challenge.\n\n    Args:\n        prec (list of numpy.array): A list of arrays.\n            :obj:`prec[l]` indicates precision for class :math:`l`.\n            If :obj:`prec[l]` is :obj:`None`, this function returns\n            :obj:`numpy.nan` for class :math:`l`.\n        rec (list of numpy.array): A list of arrays.\n            :obj:`rec[l]` indicates recall for class :math:`l`.\n            If :obj:`rec[l]` is :obj:`None`, this function returns\n            :obj:`numpy.nan` for class :math:`l`.\n        use_07_metric (bool): Whether to use PASCAL VOC 2007 evaluation metric\n            for calculating average precision. The default value is\n            :obj:`False`.\n\n    Returns:\n        ~numpy.ndarray:\n        This function returns an array of average precisions.\n        The :math:`l`-th value corresponds to the average precision\n        for class :math:`l`. If :obj:`prec[l]` or :obj:`rec[l]` is\n        :obj:`None`, the corresponding value is set to :obj:`numpy.nan`.\n\n    \"\"\"\n\n    n_fg_class = len(prec)\n    ap = np.empty(n_fg_class)\n    for l in six.moves.range(n_fg_class):\n        if prec[l] is None or rec[l] is None:\n            ap[l] = np.nan\n            continue\n\n        if use_07_metric:\n            # 11 point metric\n            ap[l] = 0\n            for t in np.arange(0., 1.1, 0.1):\n                if np.sum(rec[l] >= t) == 0:\n                    p = 0\n                else:\n                    p = np.max(np.nan_to_num(prec[l])[rec[l] >= t])\n                ap[l] += p / 11\n        else:\n            # correct AP calculation\n            # first append sentinel values at the end\n            mpre = np.concatenate(([0], np.nan_to_num(prec[l]), [0]))\n            mrec = np.concatenate(([0], rec[l], [1]))\n\n            mpre = np.maximum.accumulate(mpre[::-1])[::-1]\n\n            # to calculate area under PR curve, look for points\n            # where X axis (recall) changes value\n            i = np.where(mrec[1:] != mrec[:-1])[0]\n\n            # and sum (\\Delta recall) * prec\n            ap[l] = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n\n    return ap\n", "meta": {"hexsha": "8129eaeb70d0ae18f3fc12468393c1a13aec013c", "size": 14429, "ext": "py", "lang": "Python", "max_stars_repo_path": "Utils/voc_cal_ap.py", "max_stars_repo_name": "argusswift/SSD-pytorch", "max_stars_repo_head_hexsha": "cdf7076b2d4fee388d90c53c6acd31813a4a7c46", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 379, "max_stars_repo_stars_event_min_datetime": "2019-09-25T05:25:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T06:24:32.000Z", "max_issues_repo_path": "Utils/voc_cal_ap.py", "max_issues_repo_name": "dalveasy/SSD-Pytorch", "max_issues_repo_head_hexsha": "559b86701d68c4ff0d77396c2d43bddc11407636", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2019-10-18T07:30:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T01:15:53.000Z", "max_forks_repo_path": "Utils/voc_cal_ap.py", "max_forks_repo_name": "dalveasy/SSD-Pytorch", "max_forks_repo_head_hexsha": "559b86701d68c4ff0d77396c2d43bddc11407636", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 176, "max_forks_repo_forks_event_min_datetime": "2019-10-08T01:18:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T02:12:20.000Z", "avg_line_length": 41.3438395415, "max_line_length": 79, "alphanum_fraction": 0.5844479867, "include": true, "reason": "import numpy", "num_tokens": 3483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.26284184314569564, "lm_q1q2_score": 0.1636083578963325}}
{"text": "\"\"\"\nModule containing the Pythia version of the `SimpleRhNeutrino` model.\n\"\"\"\n\nfrom functools import partial\nfrom typing import Callable, Dict, List, Tuple\n\nimport numpy as np\n\nfrom storm.models.simple._base import SimpleRhNeutrinoBase, StateType\nfrom storm.models.simple._spectra import dndx_l_u_d as _dndx_l_u_d\nfrom storm.models.simple._spectra import dndx_l_w as _dndx_l_w\nfrom storm.models.simple._spectra import dndx_vl_d_d as _dndx_vl_d_d\nfrom storm.models.simple._spectra import dndx_vl_h as _dndx_vl_h\nfrom storm.models.simple._spectra import dndx_vl_l_l as _dndx_vl_l_l\nfrom storm.models.simple._spectra import dndx_vl_lp_lp as _dndx_vl_lp_lp\nfrom storm.models.simple._spectra import dndx_vl_u_u as _dndx_vl_u_u\nfrom storm.models.simple._spectra import dndx_vl_z as _dndx_vl_z\nfrom storm.models.simple._spectra import dndx_vlp_lp_l as _dndx_vlp_lp_l\nfrom storm.models.simple._widths import width_l_u_d as _width_l_u_d\nfrom storm.models.simple._widths import width_l_w as _width_l_w\nfrom storm.models.simple._widths import width_vl_d_d as _width_vl_d_d\nfrom storm.models.simple._widths import width_vl_h as _width_vl_h\nfrom storm.models.simple._widths import width_vl_l_l as _width_vl_l_l\nfrom storm.models.simple._widths import width_vl_lp_lp as _width_vl_lp_lp\nfrom storm.models.simple._widths import width_vl_u_u as _width_vl_u_u\nfrom storm.models.simple._widths import width_vl_vl_vl as _width_vl_vl_vl\nfrom storm.models.simple._widths import width_vl_z as _width_vl_z\nfrom storm.models.simple._widths import width_vlp_lp_l as _width_vlp_lp_l\n\n\nclass SimpleRhNeutrinoPythia(SimpleRhNeutrinoBase):\n    \"\"\"\"\"\"\n\n    def __init__(self, mvr: float, theta: float, lep: str):\n        super().__init__(mvr, theta, lep)\n\n        # Dictionary of functions to compute the partial widths of a given\n        # final state.\n        self._width_dispatch: Dict[Tuple[str, ...],\n                                   Callable[..., float]] = dict()\n        # Dictionary of functions to compute the spectra of from the decay into\n        # a given final state.\n        self._dndx_dispatch: Dict[\n            Tuple[str, ...],\n            Callable[..., Tuple[np.ndarray, np.ndarray]]] = dict()\n        # List of tuples specifying all decay modes\n        self._decay_final_states: List[Tuple[str, ...]] = list()\n        # Dictionary specifying to conjugate of a given final state.\n        self._conj_map: Dict[Tuple[str, ...], Tuple[str, ...]] = dict()\n\n        self.__create_states_and_dispatch_tables()\n\n    def __create_states_and_dispatch_tables(self):\n        \"\"\"\n        Create the dispatch tables for the partial width and spectrum\n        functions.\n        \"\"\"\n        lep = self._lep\n        genl = self._genl\n        dt = {\n            (f\"v{lep}\", \"h\"): partial(_width_vl_h, genl=genl),\n            (f\"v{lep}\", \"z\"): partial(_width_vl_z, genl=genl),\n            (f\"{lep}\", \"w\"): partial(_width_l_w, genl=genl),\n            (f\"{lep}bar\", \"wbar\"): partial(_width_l_w, genl=genl),\n            (f\"v{lep}\", f\"v{lep}\", f\"v{lep}\"):\n                partial(_width_vl_vl_vl, genl=genl),\n            (f\"v{lep}\", f\"{lep}\", f\"{lep}bar\"):\n                partial(_width_vl_l_l, genl=genl),\n        }\n        sdt = {\n            (f\"v{lep}\", \"h\"): partial(_dndx_vl_h, genl=genl),\n            (f\"v{lep}\", \"z\"): partial(_dndx_vl_z, genl=genl),\n            (f\"{lep}\", \"w\"): partial(_dndx_l_w, genl=genl, anti=False),\n            (f\"{lep}bar\", \"wbar\"): partial(_dndx_l_w, genl=genl, anti=True),\n            (f\"v{lep}\", f\"{lep}\", f\"{lep}bar\"):\n                partial(_dndx_vl_l_l, genl=genl),\n        }\n\n        self._conj_map = {(f\"{lep}bar\", \"wbar\"): (f\"{lep}\", \"w\")}\n\n        # Add states of the form vl + q + qbar and l + u + dbar\n        for i, (u, d) in enumerate([(\"u\", \"d\"), (\"c\", \"s\"), (\"t\", \"b\")]):\n            state = (f\"v{lep}\", u, f\"{u}bar\")\n            dt[state] = partial(_width_vl_u_u, genl=genl, genq=i)\n            sdt[state] = partial(_dndx_vl_u_u, genl=genl, genq=i)\n\n            state = (f\"v{lep}\", d, f\"{d}bar\")\n            dt[state] = partial(_width_vl_d_d, genl=genl, genq=i)\n            sdt[state] = partial(_dndx_vl_d_d, genl=genl, genq=i)\n\n            state = (f\"{lep}\", u, f\"{d}bar\")\n            dt[state] = partial(_width_l_u_d, genl=genl, genq=i)\n            sdt[state] = partial(_dndx_l_u_d, genl=genl, genq=i, anti=False)\n\n            state = (f\"{lep}bar\", f\"{u}bar\", f\"{d}\")\n            dt[state] = partial(_width_l_u_d, genl=genl, genq=i)\n            sdt[state] = partial(_dndx_l_u_d, genl=genl, genq=i, anti=True)\n\n            self._conj_map[state] = (f\"{lep}\", u, f\"{d}bar\")\n\n        for i, ell in enumerate([\"e\", \"mu\", \"tau\"]):\n            if ell != lep:\n                state = (f\"v{lep}\", f\"{ell}\", f\"{ell}bar\")\n                dt[state] = partial(_width_vl_lp_lp, genl=genl, genlp=i)\n                sdt[state] = partial(_dndx_vl_lp_lp, genl=genl, genlp=i)\n\n                state = (f\"v{ell}\", f\"{ell}\", f\"{lep}bar\")\n                dt[state] = partial(_width_vlp_lp_l, genl=genl, genlp=i)\n                sdt[state] = partial(\n                    _dndx_vlp_lp_l, genl=genl, genlp=i, anti=False)\n\n                state = (f\"v{ell}\", f\"{lep}\", f\"{ell}bar\")\n                dt[state] = partial(_width_vlp_lp_l, genl=genl, genlp=i)\n                sdt[state] = partial(\n                    _dndx_vlp_lp_l, genl=genl, genlp=i, anti=True)\n\n                self._conj_map[state] = (f\"v{ell}\", f\"{ell}\", f\"{lep}bar\")\n\n        self._width_dispatch = dt\n        self._dndx_dispatch = sdt\n        self._decay_final_states = list(dt.keys())\n\n    @property\n    def lep(self) -> str:\n        return self._lep\n\n    @lep.setter\n    def lep(self, lep: str) -> None:\n        self._lep = lep\n        self.__create_states_and_dispatch_tables()\n\n    @property\n    def decay_final_states(self) -> List[StateType]:\n        return self._decay_final_states\n\n    @decay_final_states.setter\n    def decay_final_states(self, val: List[StateType]) -> None:\n        raise AttributeError('Cannot set \"decay final states.\"')\n\n    def partial_width(self, state: StateType, **kwargs) -> float:\n        \"\"\"\n        Compute the partial width for a right-handed neutrino to decay into a\n        particular final state.\n\n        Parameters\n        ----------\n        state: Tuple[str, ...]\n            A tuple of strings representing the final state. For example,\n            state=('ve', 'h') will return the partial width for vr -> ve + h.\n            See `decay_final_states` for a list of all final states.\n\n        Returns\n        -------\n        pw: float\n            The partial decay width.\n        \"\"\"\n        if state in self._width_dispatch.keys():\n            return self._width_dispatch[state](self._mvr, self._theta)\n        raise ValueError(f\"Invalid state: {state}\")\n\n    def partial_widths(self, **kwargs) -> Dict[StateType, float]:\n        \"\"\"\n        Compute the partial width for a right-handed neutrino to decay into all\n        possible final states.\n\n        Parameters\n        ----------\n        remove_conjugates: Optional[bool]\n            If true, the conjugate states are removed and their partial widths\n            are added into the unconjugated state.\n\n        Returns\n        -------\n        pws: Dict[str, float]\n            Dictionary containing all partial decay widths from the decay of a\n            right-handed neutrino.\n        \"\"\"\n        pws = {\n            key: func(self._mvr, self._theta)\n            for key, func in self._width_dispatch.items()\n        }\n\n        if \"remove_conjugates\" in kwargs:\n            for key, val in self._conj_map.items():\n                pws[val] += pws[key]\n                del pws[key]\n\n        pws[(\"total\",)] = sum(pws.values())\n        return pws\n\n    def branching_fractions(self, **kwargs) -> Dict[StateType, float]:\n        \"\"\"\n        Compute the branching fractions for a right-handed neutrino to decay\n        into a all availible final states.\n\n        Parameters\n        ----------\n        remove_conjugates: Optional[bool]\n            If true, the conjugate states are removed and their partial widths\n            are added into the unconjugated state.\n\n        Returns\n        -------\n        bf: Dict[str, float]\n            Dictionary containing all branching fractions from the decay of a\n            right-handed neutrino.\n        \"\"\"\n        remove_conjugates = kwargs.get(\"remove_conjugates\")\n        if remove_conjugates is None:\n            remove_conjugates = True\n\n        pws = self.partial_widths(remove_conjugates=remove_conjugates)\n        return {\n            key: val / pws[(\"total\",)]\n            for key, val in pws.items() if key != (\"total\",)\n        }\n\n    def dndx_single_state(\n        self,\n        x: np.ndarray,\n        product: int,\n        state: StateType,\n        **kwargs\n    ) -> Tuple[np.ndarray, np.ndarray]:\n        \"\"\"\n        Compute the spectrum of a specified product from the decay of a\n        right-handed neutrino into all availible final states of a specified\n        final state.\n\n        Parameters\n        ----------\n        product: int,\n            PDG code of the product to compute spectrum for. For example, to\n            compute the photon spectrum, use `22`.\n        xbounds: Tuple[float, float]\n            Bounds on `x = 2*E/mvr`.\n        nevents: Optional[int]\n            Number of Pythia events to use in generating the spectrum. Default\n            is 10_000.\n        state: Optional[Tuple[str, ...]]\n            A tuple of strings representing the final state. For example,\n            state=('ve', 'h') will return the partial width for vr -> ve + h.\n            See `decay_final_states` for a list of all final states.\n\n        Returns\n        -------\n        dndx:\n            If a state was specified, the return is the x and spectrum values.\n            Otherwise, the x values are returns along with a dictionary of the\n            spectra for all posible final states.\n        \"\"\"\n\n        nevents = kwargs[\"nevents\"] if \"nevents\" in kwargs else 10_000\n\n        # Set the arguments to pass to c++ functions\n        _kwargs = {\n            \"mvr\": self._mvr,\n            \"theta\": self._theta,\n            \"product\": product,\n            \"xbounds\": (np.min(x), np.max(x)),\n            \"nbins\": len(x),\n            \"nevents\": nevents,\n        }\n\n        if state in self._dndx_dispatch.keys():\n            return self._dndx_dispatch[state](**_kwargs)\n        raise ValueError(f\"Invalid state: {state}\")\n\n    def dndx(\n            self,\n            x: np.ndarray,\n            product: int,\n            **kwargs\n    ) -> Tuple[np.ndarray, Dict[StateType, np.ndarray]]:\n        \"\"\"\n        Compute the spectrum of a specified product from the decay of a\n        right-handed neutrino into all availible final states of a specified\n        final state.\n\n        Parameters\n        ----------\n        product: int,\n            PDG code of the product to compute spectrum for. For example, to\n            compute the photon spectrum, use `22`.\n        xbounds: Tuple[float, float]\n            Bounds on `x = 2*E/mvr`.\n        nevents: Optional[int]\n            Number of Pythia events to use in generating the spectrum. Default\n            is 10_000.\n        state: Optional[Tuple[str, ...]]\n            A tuple of strings representing the final state. For example,\n            state=('ve', 'h') will return the partial width for vr -> ve + h.\n            See `decay_final_states` for a list of all final states.\n\n        Returns\n        -------\n        dndx:\n            If a state was specified, the return is the x and spectrum values.\n            Otherwise, the x values are returns along with a dictionary of the\n            spectra for all posible final states.\n        \"\"\"\n\n        nevents = kwargs[\"nevents\"] if \"nevents\" in kwargs else 10_000\n\n        # Set the arguments to pass to c++ functions\n        _kwargs = {\n            \"mvr\": self._mvr,\n            \"theta\": self._theta,\n            \"product\": product,\n            \"xbounds\": (np.min(x), np.max(x)),\n            \"nbins\": len(x),\n            \"nevents\": nevents,\n        }\n\n        dndx = {key: np.zeros_like(x) for key in self._dndx_dispatch.keys()}\n        # Use the first state to get xs\n        first_state = list(self._dndx_dispatch.keys())[0]\n        xs, dndx[first_state] = self._dndx_dispatch[first_state](**_kwargs)\n\n        # Compute spectra for all other states\n        dndx = {\n            key: func(**_kwargs)[1]\n            for key, func in self._dndx_dispatch.items()\n            if key != first_state\n        }\n\n        # Apply branching fractions and compute total spectrum\n        total = np.zeros_like(xs)\n        bfs = self.branching_fractions(remove_conjugates=False)\n        for key in dndx.keys():\n            dndx[key] *= bfs[key]\n            total += dndx[key]\n        dndx[(\"total\",)] = total\n\n        return xs, dndx\n", "meta": {"hexsha": "57fa2b7f0cb6799ee48d3ae8c5e810d4e268d982", "size": 12844, "ext": "py", "lang": "Python", "max_stars_repo_path": "storm/models/simple/_simple_pythia.py", "max_stars_repo_name": "LoganAMorrison/Storm", "max_stars_repo_head_hexsha": "b189f276064a904d1792a10249fa3555237e3062", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "storm/models/simple/_simple_pythia.py", "max_issues_repo_name": "LoganAMorrison/Storm", "max_issues_repo_head_hexsha": "b189f276064a904d1792a10249fa3555237e3062", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "storm/models/simple/_simple_pythia.py", "max_forks_repo_name": "LoganAMorrison/Storm", "max_forks_repo_head_hexsha": "b189f276064a904d1792a10249fa3555237e3062", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1127596439, "max_line_length": 79, "alphanum_fraction": 0.5876673933, "include": true, "reason": "import numpy", "num_tokens": 3327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.16358260173684624}}
{"text": "'''Nuclear Landmark model for budding yeast'''\nimport os\nimport sys\nimport numpy as np\nimport datetime\nimport string\nimport math\nimport IMP\nimport IMP.core\nimport IMP.atom\nimport IMP.display\nimport IMP.algebra\nimport unittest\nfrom StringIO import StringIO\nimport time\nimport argparse\nimport csv\n\n#parse arguments\nparser = argparse.ArgumentParser(description='Run volume exclusion model')\nparser.add_argument('seed', type=int, help='seed')\nparser.add_argument('name', type=str, help='model name')\nparser.add_argument('chrlen', type=str, help='chromosome lengths')\nparser.add_argument('chrcen', type=str, help='centromeres')\nparser.add_argument('size', type=float, help='nuclear radius')\nargs = parser.parse_args()\n\n# Chromosome lengths and list of chromosomes\nchrlens = list(csv.reader(open(args.chrlen,'rb'),delimiter='\\t'))\nchr_seq = {}\nchain_list = []\nfor i in range(0,len(chrlens)):\n    chr_seq[chrlens[i][0]] = int(chrlens[i][1])\n    chain_list.append(chrlens[i][0])\n\n# Chromosome centromeres\nchrcens = list(csv.reader(open(args.chrcen,'rb'),delimiter='\\t'))\nchr_cen = {}\nfor i in range(0,len(chrcens)):\n    chr_cen[chrcens[i][0]] = (int(chrcens[i][1]) + int(chrcens[i][2]))/2\n\n# Chromosome names for PDB\nchr_pdb = {}\nfor i in range(0,len(chrlens)):\n    if i < 16:\n        chr_pdb[chrlens[i][0]] = \"c\" + str(i+1).zfill(2) + \" \" + string.ascii_uppercase[i]\n    else:\n        chr_pdb[chrlens[i][0]] = \"c\" + str(i+1).zfill(2) + \" \" + string.ascii_lowercase[i-16]\n\n# parameters\nsep = 3200       # 3200 bp separation\nnuclear_rad = 1000.0 * args.size\nnucleolus_pos = -1200.0 * args.size\nnucleolus_in_rad = 750.0 * args.size\nnucleolus_ex_rad = 1600.0 * args.size\ncentro_pos = -750.0 * args.size\ncentro_rad = 300.0 * args.size\nenvelope_thick = 50 * args.size\n\n# Set the seed and the random state\nrandom_state = np.random.RandomState(seed=args.seed)\n\nbasedir = os.path.dirname(os.path.realpath(__file__))\noutname = os.path.join(basedir, args.name, str(args.seed))\nprint 'nucleus R={}, cen {}, R={}, nucleolus {}, Rin={}, Rex={}, tel {} from NE, seed={}'.format(nuclear_rad,centro_pos,centro_rad,nucleolus_pos,nucleolus_in_rad,nucleolus_ex_rad,envelope_thick,args.seed)\nprint 'output pdb:', outname\nif os.path.exists(outname):\n    sys.exit(0)\n\n#------------------------------------------------------------\n\nt1=time.time()\nchr_bead = {}    # number of beads for each chromosome\nnbead = 0\nbead_start = {}  # bead label starts of a chr\nfor i in chr_seq.keys():\n    n = chr_seq[i]/sep + 1\n    chr_bead[i] = n\n    nbead = nbead + n\n    bead_start[i] = nbead - n\n\n#print bead_start\nrdnaStart = bead_start[chain_list[11]] + 140 #begin rDNA\nrdnaEnd = bead_start[chain_list[11]] + 147 #not included as rDNA\nrdna1 = rdnaStart + 2 #last bead 1st chain\nrdna2 = rdnaStart + 3 #begin 2nd chain\nrdnaStart2 = bead_start[chain_list[27]] + 140 #begin rDNA\nrdnaEnd2 = bead_start[chain_list[27]] + 147 #not included as rDNA\nrdna3 = rdnaStart2 + 2 #last bead 1st chain\nrdna4 = rdnaStart2 + 3 #begin 2nd chain\n\nstartChr_pdb = [] #indexing starts from 0\nn = 0\nstartChr_pdb.append(n)\nfor i in chain_list:\n    n += chr_bead[i]\n    startChr_pdb.append(n)\n\n#---------------------------------------------------------\n\ndef bead_id(chr,gpos):\n    '''Given chromosome id and genome position, returns bead id'''\n    for i in range(chr_bead[chr]):\n        if gpos >= i*sep and gpos < (i+1)*sep:\n            beadnum = i + bead_start[chr]\n            break\n    return beadnum\n\ndef find_chromosome(bid):\n    \"\"\" Returns a chromosome id given a bead number\"\"\"\n    for i in chr_seq.keys():\n        if bid < bead_start[i] + chr_bead[i]\\\n        and bid >= bead_start[i]:\n            chrid=i\n            break\n    return chrid\n\ndef find_bead_in_chr(bid):\n    \"\"\" Returns a chromosome and bead_order and mid genome position given a beadnum\"\"\"\n    for i in chr_seq.keys():\n        if bid < bead_start[i] + chr_bead[i]\\\n        and bid >= bead_start[i]:\n            order = bid - bead_start[i] + 1 #order starts from 1\n            genpos = order*sep - sep/2\n            break\n    return i,order,genpos\n\ndef pdboutput(name):\n    pdb=[[] for i in range(nbead)]\n    #-----------------------------\n    cen_pos=[]\n    for k in chr_seq.keys():\n        j= bead_id(k,chr_cen[k])\n        cen_pos.append(j)\n    #------------------------------------\n    for i in range(nbead):\n        p0=IMP.core.XYZR(chain.get_particle(i))\n        chr=find_chromosome(i)\n        #pdb[i].append('ATOM') \n        if i in cen_pos:       \n            pdb[i].append(' CEN')  #1\n        elif rdnaStart<=i<=rdnaEnd or rdnaStart2<=i<=rdnaEnd2:\n            pdb[i].append('rDNA') \n        elif i == bead_start[chr]:\n            pdb[i].append(' L  ') \n        elif i == (bead_start[chr]+chr_bead[chr]-1):\n            pdb[i].append(' R  ') \n        else:\n            pdb[i].append(' O  ')\n        #pdb[i].append('L')\n        chr_num=filter(lambda k: bead_start[k]<=i, chr_seq.keys())[-1]\n        pdb[i].append(chr_pdb[chr_num])  #2\n        pdb[i].append(i-bead_start[chr_num]+1) #3\n        pdb[i].append(p0.get_x()) #4\n        pdb[i].append(p0.get_y()) #5\n        pdb[i].append(p0.get_z()) #6\n        #pdb[i].append(15)\n        pdb[i].append(chr_num)  #7\n    ###sort the file by chromosome order\n    sorted_pdb=[]\n    for i in chain_list:\n        for j in range(len(pdb)):\n            if pdb[j][6]==i:\n                sorted_pdb.append(pdb[j])\n    #insert sorted number\n    for i in range(len(sorted_pdb)):\n        sorted_pdb[i].insert(0,i+1)\n\n    name=str(name)+'.pdb'\n    #------------------------------------------------\n    out=open(name,'w')\n    for l in sorted_pdb:\n        out.write(\"ATOM %6i %4s %5s %3i     %7.1f %7.1f %7.1f %s\\n\"\\\n        %(l[0],l[1],l[2],l[3],l[4],l[5],l[6],l[7]))\n    out.close()\n\ndef mdstep(t,step):\n    o = IMP.atom.MolecularDynamics()\n    o.set_model(m)\n    md = IMP.atom.VelocityScalingOptimizerState(xyzr,t,10)  # replace 300 K with 500 K\n    o.add_optimizer_state(md)\n    #print 'optimizing with temperature',t,'and',step,'steps'\n    s=o.optimize(step)\n    o.remove_optimizer_state(md)\n    #print 'MD',step,'steps done @',datetime.datetime.now()\n    return s\n\ndef cgstep(step):\n    o = IMP.core.ConjugateGradients()\n    o.set_model(m)\n    f=o.optimize(step)\n    #print 'CG',step,'steps done @',datetime.datetime.now()\n    return f\n\n#___________________________ IMP starts _____________________________________\n#IMP.set_check_level(IMP.NONE)\nIMP.set_log_level(IMP.SILENT)\nm = IMP.Model()\nr = 15.0\nlb = 30.0 # length of bond\nkbend=0.2 \ncontact_dict = {}\nxyzr = IMP.core.create_xyzr_particles(m,nbead,r)\nchain = IMP.container.ListSingletonContainer(xyzr)\n# First beads\ncorner1=IMP.algebra.Vector3D(-nuclear_rad,-nuclear_rad,-nuclear_rad)\ncorner2=IMP.algebra.Vector3D(nuclear_rad,nuclear_rad,nuclear_rad)\nbox=IMP.algebra.BoundingBox3D(corner1,corner2)\nrdummy=int(random_state.rand() * 10000)\nfor i in range(rdummy):\n    ranvec = IMP.algebra.get_random_vector_in(box)\n#----------------------------------------------------------  \n#print nbead\nfor i in range(nbead):\n    p0 = chain.get_particle(i)\n    IMP.atom.Mass.setup_particle(p0,1)\n    p = IMP.core.XYZR(p0)\n    coor = IMP.algebra.get_random_vector_in(box)\n    p.set_coordinates(coor)\n    #ch,b,gpos = find_bead_in_chr(i)\n    #print ch,b,pdbOrder(ch,gpos)+1,i\n\n#sys.exit()\n#---------------------------------------------------------------------------------\n#print 'Setting up restraints'\n# Create bonds for consecutive beads in a string\nbonds = IMP.container.ListSingletonContainer(m)\nfor id in chr_seq.keys():\n    istart = bead_start[id]\n    iend = istart + chr_bead[id]\n    IMP.atom.Bonded.setup_particle(chain.get_particle(istart))\n    for i in range(istart + 1,iend):\n        if i != rdna2 and i != rdna4:\n            bp = IMP.atom.Bonded.decorate_particle(chain.get_particle(i-1))\n            bpr = IMP.atom.Bonded.setup_particle(chain.get_particle(i))\n            b = IMP.atom.create_custom_bond(bp, bpr, lb, 2)\n            bonds.add_particle(b.get_particle())\n        elif i == rdna4:\n            IMP.atom.Bonded.setup_particle(chain.get_particle(rdna4))\n        else:\n            IMP.atom.Bonded.setup_particle(chain.get_particle(rdna2))\n\n# Restraint for bonds\nbss = IMP.atom.BondSingletonScore(IMP.core.Harmonic(0,1))\nbr = IMP.container.SingletonsRestraint(bss, bonds)\nm.add_restraint(br) #0\n\n# Set up excluded volume\nevr = IMP.core.ExcludedVolumeRestraint(chain)\nm.add_restraint(evr) #1\n\n\n# Set up cap\ncenter = IMP.algebra.Vector3D(0,0,0)\ncenter_nucleolus = IMP.algebra.Vector3D(nucleolus_pos,0,0)\nnot_rDNA = IMP.container.ListSingletonContainer(m)\nfor i in range(nbead):\n    if not ((i >= rdnaStart and i < rdnaEnd) or (i >= rdnaStart2 and i < rdnaEnd2)):\n        p = chain.get_particle(i)\n        not_rDNA.add_particle(p)\nubcell = IMP.core.HarmonicUpperBound(nuclear_rad,1.0)\nsscell = IMP.core.DistanceToSingletonScore(ubcell,center)\nrcell = IMP.container.SingletonsRestraint(sscell,chain)\nm.add_restraint(rcell) #2\n\n# centromeres in radius 300 @-700\ncentro = IMP.algebra.Vector3D(centro_pos,0,0)\nlistcentro = IMP.container.ListSingletonContainer(m)\nfor k in chr_seq.keys():\n    j = bead_id(k,chr_cen[k])\n    pcen = chain.get_particle(j)\n    listcentro.add_particle(pcen)\n\nubcen = IMP.core.HarmonicUpperBound(centro_rad,1.0)\nsscen = IMP.core.DistanceToSingletonScore(ubcen,centro)\nrcentro = IMP.container.SingletonsRestraint(sscen,listcentro)\nm.add_restraint(rcentro) #4\n\nprint 'High temp MD..'\nmdstep(1000000,500)\nmdstep(500000,500)\nmdstep(300000,500)\nmdstep(100000,500)\nmdstep(5000,500)\nscore=cgstep(1000)\nprint 'before telo: ',score\n\n# Telomeres near nuclear envelope thickness 50\ntelo = IMP.container.ListSingletonContainer(m)\n#galBead =  bead_id(galpos[0],galpos[1])\n#telo.add_particle(chain.get_particle(galBead))\nfor k in chr_seq.keys():\n    j1 = bead_start[k]\n    pt = chain.get_particle(j1)\n    telo.add_particle(pt)\n    j2 = j1 - 1 + chr_bead[k]\n    pt = chain.get_particle(j2)\n    telo.add_particle(pt)\ntlb = IMP.core.HarmonicLowerBound(nuclear_rad-envelope_thick,1.0)\nsst = IMP.core.DistanceToSingletonScore(tlb,center)\nrt = IMP.container.SingletonsRestraint(sst,telo)\nm.add_restraint(rt) #5\n\n# outside centro sphere\n#lbcen = IMP.core.HarmonicLowerBound(centro_rad,1.0)\n#sstc = IMP.core.DistanceToSingletonScore(lbcen,centro)\n#rtc = IMP.container.SingletonsRestraint(sstc,telo)\n#m.add_restraint(rtc) #6\n\n# rDNA chr12 near nucleolus\nrDNA = IMP.container.ListSingletonContainer(m)\nrDNA.add_particle(chain.get_particle(rdna1))\nrDNA.add_particle(chain.get_particle(rdna3))\nub_bn2 = IMP.core.HarmonicLowerBound(nucleolus_in_rad,0.5)  #can also try lowerbound nucleolus_rad-rncutoff\nmindts2 = IMP.core.DistanceToSingletonScore(ub_bn2,center_nucleolus)\nnucleolir2 = IMP.container.SingletonsRestraint(mindts2,rDNA)\nm.add_restraint(nucleolir2) #7\n\nrDNA2 = IMP.container.ListSingletonContainer(m)\nrDNA2.add_particle(chain.get_particle(rdna2))\nrDNA2.add_particle(chain.get_particle(rdna4))\nub_bn3 = IMP.core.HarmonicLowerBound(nucleolus_ex_rad,0.5)  #can also try lowerbound nucleolus_rad-rncutoff\nmindts3 = IMP.core.DistanceToSingletonScore(ub_bn3,center_nucleolus)\nnucleolir3 = IMP.container.SingletonsRestraint(mindts3,rDNA2)\nm.add_restraint(nucleolir3) #7\n\n# Set up Nucleolis #\nlbn0 = IMP.core.HarmonicUpperBound(nucleolus_ex_rad,0.5)\nssn0 = IMP.core.DistanceToSingletonScore(lbn0,center_nucleolus)\nrn0 = IMP.container.SingletonsRestraint(ssn0,not_rDNA)\nm.add_restraint(rn0) #3\n#-------------------\n\nprint 'High temp MD in nuc ...'\nmdstep(500000,5000)\nmdstep(300000,5000)\nmdstep(5000,10000)\nscore=cgstep(500)\nprint 'before angle',score\n\n# Angle Restraint\nangle = math.pi\nangle_set=[]\nnoangle=[i for i in bead_start.values()]  #do not apply angle restraints\nnoangle.append(rdna1)\nnoangle.append(rdna2)\nnoangle.append(rdna3)\nnoangle.append(rdna4)\n\nfor i in range(nbead-1):\n    ieval = i+1\n    if ieval in noangle:\n        continue\n    elif i in noangle:\n        continue\n    else:\n        d1 = chain.get_particle(i-1)\n        d2 = chain.get_particle(i)\n        d3 = chain.get_particle(i+1)\n        pot = IMP.core.Harmonic(angle,kbend)\n        ar = IMP.core.AngleRestraint(pot,d1,d2,d3)\n        m.add_restraint(ar)\n        angle_set.append(ar)\n\nmdstep(50000,500)\nmdstep(25000,500)\nmdstep(20000,1000)\nmdstep(10000,1000)\nmdstep(5000,3000)\nmdstep(2000,5000)\nmdstep(1000,7000)\nmdstep(500,10000)\nscore=cgstep(2500)\n\nprint 'angle: %.1f '%(score)\n#-----------------------\nfor i in angle_set:\n    m.remove_restraint(i)\nscore=cgstep(1000)\nprint 'Final score:%.1f' %(score)\n\npdboutput(outname)\n\n#-------------------------\n\n#mdstep(1000,1000)\n#score=cgstep(1000)\n#print '\\nFinal score with remove angle restraint is: ',score\n\n#name='final_without_angle'\n#output(chain,nbead,name)\nt2=time.time()\n\nprint 'time spend is ', t2-t1, ' s'\n", "meta": {"hexsha": "26ea76ac695599d7db44e673e71ca99f8b634efb", "size": 12731, "ext": "py", "lang": "Python", "max_stars_repo_path": "model/diploid_landmark.py", "max_stars_repo_name": "gesinecauer/HybridYeastHiC", "max_stars_repo_head_hexsha": "5df9eb176227109ec617e0ac4591788f5bfc9338", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-11-29T11:34:01.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-29T11:34:01.000Z", "max_issues_repo_path": "model/diploid_landmark.py", "max_issues_repo_name": "gesinecauer/HybridYeastHiC", "max_issues_repo_head_hexsha": "5df9eb176227109ec617e0ac4591788f5bfc9338", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model/diploid_landmark.py", "max_forks_repo_name": "gesinecauer/HybridYeastHiC", "max_forks_repo_head_hexsha": "5df9eb176227109ec617e0ac4591788f5bfc9338", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-02-22T22:17:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-04T21:57:14.000Z", "avg_line_length": 32.2303797468, "max_line_length": 204, "alphanum_fraction": 0.6667190323, "include": true, "reason": "import numpy", "num_tokens": 3820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.28140561345566495, "lm_q1q2_score": 0.16358195282643703}}
{"text": "''' decision_tree.py\nMatthew Kiyoi\nmkkiyoi\n\nImplementation of decision tree classifier based on CART algorithm.\n\nMethod of use:\n\nIf using the CIFAR-10 dataset:\n  1) use the get_dataset function to get a dictionary of the data from the batch file parsed on bytes.\n  2) use the get_dataset_labels function to get a dict parsed on strings.\n  3) use the preprocess method to transform the picture data from the dictionaries to the form (RGB values, label)\n    - ex: (0, 255, 206, ... , 'airplane')\n  4) Build the decision tree using build_decision_tree\n  5) To run test data through the decision tree, repeat 1-3 on the test data batch file\n  6) Run classify dataset \n'''\n\n\nimport math\nimport numpy as np\nimport pickle\nfrom sklearn import datasets\nfrom pprint import pprint\n\nclass decision_node:\n  '''\n  Represents a node in the decision tree.\n  leaf - true if the node is a leaf node, false if the node is the root or intermediate node\n  true_branch - true subtree\n  true_branch - false subtree\n  prediction - what the current decision tree has classified the given data as\n  '''\n\n  def __init__(self, leaf = False, column = -1, attribute = None, prediction = None, true_branch = None, false_branch = None):\n    self.leaf = leaf\n    self.attribute_column = column\n    self.attribute = attribute\n    self.prediction = prediction\n    self.true_branch = true_branch\n    self.false_branch = false_branch\n\n##  def __str__(self):\n##    result = ''\n##    result += ('(Leaf: ' + str(self.leaf) + '\\n')\n##    result += ('Attribute column: ' + str(self.attribute_column) + '\\n')\n##    result += ('Attribute: ' + str(self.attribute) + '\\n')\n##    result += ('Prediction: ' + str(self.prediction) + '\\n')\n##    result += ('True Branch: ' + str(self.true_branch) + '\\n')\n##    result += ('False Branch: ' + str(self.false_branch) + '\\n')\n##    return result\n\n\ndef get_dataset(file):\n  '''\n  Extracts CIFAR-10 data from the file\n  '''\n  with open(file, 'rb') as fo:\n    dict = pickle.load(fo, encoding='bytes')\n  return dict\n\ndef get_dataset_labels(file):\n  '''\n  Extracts CIFAR-10 data labels from the file.\n  Labels are encoded as strings instead of bytes\n  '''\n  with open(file, 'rb') as fo:\n    dict = pickle.load(fo)\n  return dict\n\ndef get_iris_data():\n  '''\n  Get the iris dataset from sklearn to test the decision tree.\n  '''\n  data = datasets.load_iris()\n  dataset = []\n  for i in range(len(data['data'])):\n    dataset.append(np.append(data['data'][i], data.target[i]))\n  return dataset\n\ndef preprocess_data(data, labels, num):\n  '''\n  Preprocessing for CIFAR-10 dataset.\n  Appends the string label to the end of each array of RGB color values.\n  Chooses a subset of the CIFAR-10 dataset to train the tree.\n    - num = 1000 uses the entire dataset.\n  '''\n  print('Preprocessing data...')\n  dataset = data[b'data'] # Gets the data from the \n  types = data[b'labels']\n  result_0 = []\n  result_1 = []\n  result_2 = []\n  result_3 = []\n  result_4 = []\n  result_5 = []\n  result_6 = []\n  result_7 = []\n  result_8 = []\n  result_9 = []\n  for i in range(len(dataset)): # For each row in the dataset sort the data by category\n    if types[i] == 0:\n      if len(result_0) < num:\n        result_0.append(np.append(dataset[i], labels[types[i]]))\n    if types[i] == 1:\n      if len(result_1) < num:\n        result_1.append(np.append(dataset[i], labels[types[i]]))\n    if types[i] == 2:\n      if len(result_2) < num:\n        result_2.append(np.append(dataset[i], labels[types[i]]))\n    if types[i] == 3:\n      if len(result_3) < num:\n        result_3.append(np.append(dataset[i], labels[types[i]]))\n    if types[i] == 4:\n      if len(result_4) < num:\n        result_4.append(np.append(dataset[i], labels[types[i]]))\n    if types[i] == 5:\n      if len(result_5) < num:\n        result_5.append(np.append(dataset[i], labels[types[i]]))\n    if types[i] == 6:\n      if len(result_6) < num:\n        result_6.append(np.append(dataset[i], labels[types[i]]))\n    if types[i] == 7:\n      if len(result_7) < num:\n        result_7.append(np.append(dataset[i], labels[types[i]]))\n    if types[i] == 8:\n      if len(result_8) < num:\n        result_8.append(np.append(dataset[i], labels[types[i]]))\n    if types[i] == 9:\n      if len(result_9) < num:\n        result_9.append(np.append(dataset[i], labels[types[i]]))\n    results = result_0 + result_1 + result_2 + result_3 + result_4 + result_5 + result_6 + result_7 + result_8 + result_9\n    np.random.shuffle(results) # Combine the subsets of the data sorted in categories and randomly shuffle the array\n  return results\n\ndef is_numeric(value):\n  '''\n  Returns true if the value is numeric\n  '''\n  return isinstance(value, int) or isinstance(value, float)\n\ndef count_values(dataset):\n  '''\n  Finds the unique values for a column in the dataset we are looking at.\n  '''\n  counts = {}\n  for data in dataset:\n    value = data[-1]\n    if value not in counts:\n      counts[value] = 0\n    counts[value] += 1\n  return counts\n\ndef entropy(dataset):\n  '''\n  Returns \n  '''\n  n = float(len(dataset)) # denominator for probabilities\n  counts = count_values(dataset)\n  entropy = 0.0\n  for count in counts:\n    p = float(counts[count])/n # probability of this item within the population\n    logp = math.log(p,2) # log, base 2, of the probability\n    entropy -= p * logp # accumulation by subtraction of a negative number\n  return entropy\n\ndef gini_index(dataset):\n  '''\n  Calculates how often an value would be mislabeled if it were labeled randomly\n  based on the values in the dataset.\n  '''\n  counts = count_values(dataset) # Get the counts of each category of data\n  impurity = 1\n  for count in counts:\n    probability = counts[count]/float(len(dataset)) # Probability that the current value would be chosen out of the dataset\n    impurity -= probability**2 # subtract off the square of the probability\n  return impurity\n\n    \ndef split(dataset, attribute, value):\n  '''\n  Finds the best split based on the attribute selected and the value given.\n  Checks equality for strings and checks >= for numeric data\n  '''\n  split_function = None\n  if is_numeric(value):\n    split_function = lambda data : data[attribute] >= value # Function to check if numeric value is less than data at the attribute\n  else:\n    split_function = lambda data : data[attribute] == value # Function to check if string value is equal to string data at attribute\n  true_branch = []\n  false_branch = []\n  for data in dataset:\n    if split_function(data):\n      true_branch.append(data) # Divides dataset into a branch with values that return true from the condition\n    else:\n      false_branch.append(data) # Divides dataset into a branch with values that return false from the condition\n  return (true_branch, false_branch)\n\ndef build_decision_tree(dataset = [], max_level = None, level = 0):\n  '''\n  Builds and returns a binary decision tree.\n  Uses gini impurity to evaluate sets and information gain\n  '''\n  if len(dataset) == 0:\n    return decision_node()\n  if max_level != None and level == max_level:\n    value_prediction = count_values(dataset)\n    return decision_node(True, None, None, value_prediction, None, None)\n  gini = gini_index(dataset)\n  num_attributes = len(dataset[0]) - 1 # Want to compare each attribute, where the last element is the value\n  best_info_gain = 0.0               # Store the best information gain\n  best_attribute = None              # Store the best attribute to split on\n  best_split = None                  # Store the split dataset as two sets\n  \n  for attribute in range(0, num_attributes): # Loop through attributes, find which one gives the best gain\n    attribute_values = [data[attribute] for data in dataset] # Get the attribute values for the attribute for each row of data\n    for value in attribute_values:\n      (true_branch, false_branch) = split(dataset, attribute, value) # Split the sets on the given attribute with the given value\n      prob = float(len(true_branch)) / len(dataset) # get the probability that a row of data is in the true branch\n      info_gain = gini - prob * gini_index(true_branch) - (1-prob) * gini_index(false_branch) # Get the information gain splitting on this attribute with the value\n      if info_gain > best_info_gain and true_branch and false_branch: # Check if we have greater info gain and both true/false branches are nonempty\n        best_info_gain = info_gain                                    # Set the best information gain to the new information gain\n        best_attribute = (attribute, value)                           # Set the best attribute to split on to the current attribute being considered\n        best_split = (true_branch, false_branch)                      # Set the best dataset split to the current true/false branches\n  if best_info_gain > 0: # If we have information gain keep building the decision tree\n    print('Splitting on attribute: ' + str(best_attribute)+ ', with information gain of: ' + str(best_info_gain))\n    true_branch = build_decision_tree(best_split[0], max_level, level+1) # Recursively build decision tree on true branch set\n    false_branch = build_decision_tree(best_split[1], max_level, level+1) #  Recursively build decision tree on false branch set\n    return decision_node(False, best_attribute[0], best_attribute[1], None, true_branch, false_branch)\n  else: # No more information gain\n    value_prediction = count_values(dataset)\n    print('No more information gain, created leaf node: ' + str(value_prediction))\n    return decision_node(True, None, None, value_prediction, None, None)\n    \n\ndef classify_data(unknown_data, decision_tree):\n  '''\n  Classifies data using the decision tree. \n  '''\n  if decision_tree != None:\n    if decision_tree.leaf: # If we are at a leaf, return prediction of what data is\n      if len(decision_tree.prediction) == 1:\n        return list(decision_tree.prediction.keys())[0]\n      else:\n        best_prediction = None\n        best_prediction_count = 0\n        for value in decision_tree.prediction:\n          count = decision_tree.prediction[value]\n          # print('Count is ' + str(count) + ' for ' + value)\n          if count > best_prediction_count:\n            best_prediction_count = count\n            best_prediction = value\n        return best_prediction\n    else: # Recursively narrow down what data is using the value of the best attribute at current node in the tree\n      value = unknown_data[decision_tree.attribute_column]\n      if is_numeric(value): # If the data is numeric, compare the attribute value to the splitting attribute value in the tree\n        if value >= decision_tree.attribute:\n          branch = decision_tree.true_branch # Attribute is greater than the one in the tree.\n        else:\n          branch = decision_tree.false_branch # Attribute is less than the one in the tree.\n      else: # The attribute value is a string value\n        if value == decision_tree.attribute: # Attribute is equal to the one in the tree. \n          branch = decision_tree.true_branch\n        else: # Attribute is not equal to the one in the tree. \n          branch = decision_tree.false_branch \n      return classify_data(unknown_data, branch)\n    \ndef classify_dataset(dataset, decision_tree):\n  '''\n  Classifies an entire test dataset from the CIFAR-10 image dataset.\n  '''\n  total_successful = 0                                            # Record successful classifications\n  total_unsuccessful = 0                                          # Record unsuccessful classifications\n  for data in dataset:                                       # Classify all of the images in the test dataset\n    classification = classify_data(data, decision_tree)\n    actual_classification = data[-1]\n    print('Classified ' + str(actual_classification) + ' as ' + str(classification) + '.')\n    if classification == actual_classification: # Count the number of successful and unsuccessful classifications. \n      total_successful += 1\n    else:\n      total_unsuccessful += 1\n  print('Statistics:\\n')\n  print('Total successful classifications: ' + str(total_successful))\n  print('total unsuccessful classifications: ' + str(total_unsuccessful))\n  print('Percent successfully classified: ' + str(float(total_successful)/len(dataset)))\n\ndef prune_tree(tree, min_info_gain):\n  '''\n  Prunes the decision tree based on a minimum expected information gain. \n  '''\n  if not tree.true_branch.leaf: # If the true branch is not a leaf, recurse on the branch\n    prune_tree(tree.true_branch, min_info_gain)\n  if not tree.false_branch.leaf: # If the false branch is not a leaf, recurse on the branch\n    prune_tree(tree.false_branch, min_info_gain)\n  if tree.true_branch.leaf and tree.false_branch.leaf: # If both branches are leaves, check to see if they can combined\n    true_branch = []\n    false_branch = []\n    for value in tree.true_branch.prediction:\n        true_branch += [[value]] * tree.true_branch.prediction[value] # Recreate the number of values originally in this branch\n    for value in tree.false_branch.prediction:\n        false_branch += [[value]] * tree.false_branch.prediction[value] # Recreate the number of values originally in this branch\n    prob = float(len(true_branch)) / len(true_branch + false_branch) # Get the probability that a row of data is in the true branch\n    delta_info_gain = gini_index(true_branch + false_branch) - prob * gini_index(true_branch) - (1-prob) * gini_index(false_branch)\n    if delta_info_gain < min_info_gain: # Prune the the leaves and make the branch a leaf combining the sets of the original leaves \n      print('Pruning branch, information gain was: ' + str(delta_info_gain))\n      tree.true_branch = None\n      tree.false_branch = None\n      tree.leaf = True\n      tree.prediction = count_values(true_branch + false_branch)\n    \niris_attributes = ['Sepal Length', 'Sepal Width', 'Petal Length', 'Petal Width']\ncifar_labels = []\ndef print_tree(tree, level, indent = ''):\n  '''\n  prints out a textual representation of the decision tree.\n  '''\n  if tree:\n    if tree.leaf:\n      print(indent + 'Leaf: ' + str(tree.prediction) + ', Level: ' + str(level))\n    else:\n      print(indent + 'True Branch: Attribute ' + str(tree.attribute_column)+ ' = ' + str(tree.attribute) + ', Level: ' + str(level))\n      print_tree(tree.true_branch, level+1, indent + '  ')\n      print(indent + 'False Branch: Attribute ' + str(tree.attribute_column)+ ' = ' + str(tree.attribute) + ', Level: ' + str(level))\n      print_tree(tree.false_branch, level+1, indent + '  ')\n\ndef test():\n  files = ['data_batch_1', 'data_batch_2', 'data_batch_3', 'data_batch_4', 'data_batch_5', 'test_batch']\n  label_file = 'batches.meta'\n  \n  cifar_labels = get_dataset_labels(label_file)['label_names']    # Get the string representation of the labels for CIFAR data\n  data = get_dataset(files[0])                                    # Get the 10000 x 3072 array of picture RGB values as trainging data\n  training_dataset = preprocess_data(data, cifar_labels, )     # Append the label to the end of each picture array\n  print('Building Tree...')\n  decision_tree = build_decision_tree(training_dataset, None, 0)  # Build the decision tree\n  # prune_tree(decision_tree, 0.03)                                 # Prune the decision tree based on some minimum information gain\n  print_tree(decision_tree, 0)                                    # print out the tree\n  print('Classifying data...')\n  test_data = get_dataset(files[5])                               # Get test data\n  test_dataset = preprocess_data(test_data, cifar_labels, 100)    # Similarly append labels to arrays\n  classify_dataset(test_dataset, decision_tree)\n\ndef test_iris():\n  '''\n  Used to test the tree.\n  Smaller number of attributes to run on and takes less time.\n  '''\n  dataset = get_iris_data()\n  np.random.shuffle(dataset)\n  dataset = np.array_split(dataset, 2)\n  \n  training_dataset = dataset[0]\n  test_dataset = dataset[0]\n  decision_tree = build_decision_tree(training_dataset, None, 0)\n  print_tree(decision_tree, 0)\n  classify_dataset(test_dataset, decision_tree)\n\nif __name__ == '__main__':\n##  test()\n  test_iris()\n  \n  \n\n\n  \n  \n  \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "6a36a18a9d5992cf67441077ddf521714b925871", "size": 16084, "ext": "py", "lang": "Python", "max_stars_repo_path": "decision_tree.py", "max_stars_repo_name": "Mkkiyoi/Supervised-Learning-Hot-Dog-or-Not-Hot-Dog", "max_stars_repo_head_hexsha": "edd757200feeaffe2f1ebd4e85a70fb17193393b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "decision_tree.py", "max_issues_repo_name": "Mkkiyoi/Supervised-Learning-Hot-Dog-or-Not-Hot-Dog", "max_issues_repo_head_hexsha": "edd757200feeaffe2f1ebd4e85a70fb17193393b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "decision_tree.py", "max_forks_repo_name": "Mkkiyoi/Supervised-Learning-Hot-Dog-or-Not-Hot-Dog", "max_forks_repo_head_hexsha": "edd757200feeaffe2f1ebd4e85a70fb17193393b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3470437018, "max_line_length": 163, "alphanum_fraction": 0.6813603581, "include": true, "reason": "import numpy", "num_tokens": 3840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3242353989809524, "lm_q1q2_score": 0.16338421825046023}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2019 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#         Alexander Sokolov <alexander.y.sokolov@gmail.com>\n#\n\n'''\nSelected CI using Heat-Bath CI algorithm\n(JCTC 2016, 12, 3674-3680)\n\nSimple usage::\n\n'''\n\nimport numpy\nimport time\nimport ctypes\nfrom pyscf import lib\nfrom pyscf import ao2mo\nfrom pyscf.lib import logger\nfrom pyscf.fci import cistring\nfrom pyscf.fci import direct_spin1\n\nlibhci = lib.load_library('libhci')\n\ndef contract_2e_ctypes(h1_h2, civec, norb, nelec, hdiag=None, **kwargs):\n    h1, eri = h1_h2\n    strs = civec._strs\n    ndet = len(strs)\n    if hdiag is None:\n        hdiag = make_hdiag(h1, eri, strs, norb, nelec)\n    ci1 = numpy.zeros_like(civec)\n\n    h1 = numpy.asarray(h1, order='C')\n    eri = numpy.asarray(eri, order='C')\n    strs = numpy.asarray(strs, order='C')\n    civec = numpy.asarray(civec, order='C')\n    hdiag = numpy.asarray(hdiag, order='C')\n    ci1 = numpy.asarray(ci1, order='C')\n\n    libhci.contract_h_c(h1.ctypes.data_as(ctypes.c_void_p), \n                        eri.ctypes.data_as(ctypes.c_void_p), \n                        ctypes.c_int(norb), \n                        ctypes.c_int(nelec[0]), \n                        ctypes.c_int(nelec[1]), \n                        strs.ctypes.data_as(ctypes.c_void_p), \n                        civec.ctypes.data_as(ctypes.c_void_p), \n                        hdiag.ctypes.data_as(ctypes.c_void_p), \n                        ctypes.c_ulonglong(ndet), \n                        ci1.ctypes.data_as(ctypes.c_void_p))\n\n    return ci1\n\ndef contract_2e(h1_h2, civec, norb, nelec, hdiag=None, **kwargs):\n    h1, eri = h1_h2\n    strs = civec._strs\n    ndet = len(strs)\n    if hdiag is None:\n        hdiag = make_hdiag(h1, eri, strs, norb, nelec)\n    ci1 = numpy.zeros_like(civec)\n\n    eri = eri.reshape([norb]*4)\n\n    for ip in range(ndet):\n        for jp in range(ip):\n            stria, strib = strs[ip].reshape(2,-1)\n            strja, strjb = strs[jp].reshape(2,-1)\n            desa, crea = str_diff(stria, strja)\n            if len(desa) > 2:\n                continue\n            desb, creb = str_diff(strib, strjb)\n            if len(desb) + len(desa) > 2:\n                continue\n            if len(desa) + len(desb) == 1:\n# alpha->alpha\n                if len(desb) == 0:\n                    i,a = desa[0], crea[0]\n                    occsa = str2orblst(stria, norb)[0]\n                    occsb = str2orblst(strib, norb)[0]\n                    fai = h1[a,i]\n                    for k in occsa:\n                        fai += eri[k,k,a,i] - eri[k,i,a,k]\n                    for k in occsb:\n                        fai += eri[k,k,a,i]\n                    sign = cre_des_sign(a, i, stria)\n                    ci1[jp] += sign * fai * civec[ip]\n                    ci1[ip] += sign * fai * civec[jp]\n# beta ->beta\n                elif len(desa) == 0:\n                    i,a = desb[0], creb[0]\n                    occsa = str2orblst(stria, norb)[0]\n                    occsb = str2orblst(strib, norb)[0]\n                    fai = h1[a,i]\n                    for k in occsb:\n                        fai += eri[k,k,a,i] - eri[k,i,a,k]\n                    for k in occsa:\n                        fai += eri[k,k,a,i]\n                    sign = cre_des_sign(a, i, strib)\n                    ci1[jp] += sign * fai * civec[ip]\n                    ci1[ip] += sign * fai * civec[jp]\n\n            else:\n# alpha,alpha->alpha,alpha\n                if len(desb) == 0:\n                    i,j = desa\n                    a,b = crea\n# 6 conditions for i,j,a,b\n# --++, ++--, -+-+, +-+-, -++-, +--+ \n                    if a > j or i > b:\n# condition --++, ++--\n                        v = eri[a,j,b,i]-eri[a,i,b,j]\n                        sign = cre_des_sign(b, i, stria)\n                        sign*= cre_des_sign(a, j, stria)\n                    else:\n# condition -+-+, +-+-, -++-, +--+ \n                        v = eri[a,i,b,j]-eri[a,j,b,i]\n                        sign = cre_des_sign(b, j, stria)\n                        sign*= cre_des_sign(a, i, stria)\n                    ci1[jp] += sign * v * civec[ip]\n                    ci1[ip] += sign * v * civec[jp]\n# beta ,beta ->beta ,beta\n                elif len(desa) == 0:\n                    i,j = desb\n                    a,b = creb\n                    if a > j or i > b:\n                        v = eri[a,j,b,i]-eri[a,i,b,j]\n                        sign = cre_des_sign(b, i, strib)\n                        sign*= cre_des_sign(a, j, strib)\n                    else:\n                        v = eri[a,i,b,j]-eri[a,j,b,i]\n                        sign = cre_des_sign(b, j, strib)\n                        sign*= cre_des_sign(a, i, strib)\n                    ci1[jp] += sign * v * civec[ip]\n                    ci1[ip] += sign * v * civec[jp]\n# alpha,beta ->alpha,beta\n                else:\n                    i,a = desa[0], crea[0]\n                    j,b = desb[0], creb[0]\n                    v = eri[a,i,b,j]\n                    sign = cre_des_sign(a, i, stria)\n                    sign*= cre_des_sign(b, j, strib)\n                    ci1[jp] += sign * v * civec[ip]\n                    ci1[ip] += sign * v * civec[jp]\n        ci1[ip] += hdiag[ip] * civec[ip]\n\n    return ci1\n\ndef spin_square(civec, norb, nelec):\n    ss = numpy.dot(civec.T, contract_ss(civec, norb, nelec))\n    s = numpy.sqrt(ss+.25) - .5\n    multip = s*2+1\n    return ss, multip\n\ndef contract_ss(civec, norb, nelec):\n    strs = civec._strs\n    ndet = len(strs)\n    ci1 = numpy.zeros_like(civec)\n\n    strs = numpy.asarray(strs, order='C')\n    civec = numpy.asarray(civec, order='C')\n    ci1 = numpy.asarray(ci1, order='C')\n\n    libhci.contract_ss_c(ctypes.c_int(norb), \n                        ctypes.c_int(nelec[0]), \n                        ctypes.c_int(nelec[1]), \n                        strs.ctypes.data_as(ctypes.c_void_p), \n                        civec.ctypes.data_as(ctypes.c_void_p), \n                        ctypes.c_ulonglong(ndet), \n                        ci1.ctypes.data_as(ctypes.c_void_p))\n\n    return ci1\n\ndef make_hdiag(h1e, eri, strs, norb, nelec):\n    eri = ao2mo.restore(1, eri, norb)\n    diagj = numpy.einsum('iijj->ij',eri)\n    diagk = numpy.einsum('ijji->ij',eri)\n\n    ndet = len(strs)\n    hdiag = numpy.zeros(ndet)\n    for idet, (stra, strb) in enumerate(strs.reshape(ndet,2,-1)):\n        aocc = str2orblst(stra, norb)[0]\n        bocc = str2orblst(strb, norb)[0]\n        e1 = h1e[aocc,aocc].sum() + h1e[bocc,bocc].sum()\n        e2 = diagj[aocc][:,aocc].sum() + diagj[aocc][:,bocc].sum() \\\n           + diagj[bocc][:,aocc].sum() + diagj[bocc][:,bocc].sum() \\\n           - diagk[aocc][:,aocc].sum() - diagk[bocc][:,bocc].sum()\n        hdiag[idet] = e1 + e2*.5\n    return hdiag\n\ndef cre_des_sign(p, q, string):\n    nset = len(string)\n    pg, pb = p//64, p%64\n    qg, qb = q//64, q%64\n\n    if pg > qg:\n        n1 = 0\n        for i in range(nset-pg, nset-qg-1):\n            n1 += bin(string[i]).count('1')\n        n1 += bin(string[-1-pg] & numpy.uint64((1<<pb) - 1)).count('1')\n        n1 += string[-1-qg] >> numpy.uint64(qb+1)\n    elif pg < qg:\n        n1 = 0\n        for i in range(nset-qg, nset-pg-1):\n            n1 += bin(string[i]).count('1')\n        n1 += bin(string[-1-qg] & numpy.uint64((1<<qb) - 1)).count('1')\n        n1 += string[-1-pg] >> numpy.uint64(pb+1)\n    else:\n        if p > q:\n            mask = numpy.uint64((1 << pb) - (1 << (qb+1)))\n        else:\n            mask = numpy.uint64((1 << qb) - (1 << (pb+1)))\n        n1 = bin(string[-1-pg]&mask).count('1')\n\n    if n1 % 2:\n        return -1\n    else:\n        return 1\n\ndef argunique(strs):\n    def order(x, y):\n        for i in range(y.size):\n            if x[i] > y[i]:\n                return 1\n            elif y[i] > x[i]:\n                return -1\n        return 0\n    def qsort_idx(idx):\n        nstrs = len(idx)\n        if nstrs <= 1:\n            return idx\n        else:\n            ref = idx[-1]\n            group_lt = []\n            group_gt = []\n            for i in idx[:-1]:\n                c = order(strs[i], strs[ref])\n                if c == -1:\n                    group_lt.append(i)\n                elif c == 1:\n                    group_gt.append(i)\n            return qsort_idx(group_lt) + [ref] + qsort_idx(group_gt)\n    return qsort_idx(range(len(strs)))\n\ndef argunique_ctypes(strs):\n    nstrs, nset = strs.shape\n\n    sort_idx = numpy.empty(nstrs, dtype=numpy.uint64)\n\n    strs = numpy.asarray(strs, order='C')\n    sort_idx = numpy.asarray(sort_idx, order='C')\n\n    nstrs_ = numpy.array([nstrs])\n\n    libhci.argunique(strs.ctypes.data_as(ctypes.c_void_p), \n                     sort_idx.ctypes.data_as(ctypes.c_void_p), \n                     nstrs_.ctypes.data_as(ctypes.c_void_p), \n                     ctypes.c_int(nset))\n\n    sort_idx = sort_idx[:nstrs_[0]]\n\n    return sort_idx.tolist()\n\ndef str_diff(string0, string1):\n    des_string0 = []\n    cre_string0 = []\n    nset = len(string0)\n    off = 0\n    for i in reversed(range(nset)):\n        df = string0[i] ^ string1[i]\n        des_string0.extend([x+off for x in find1(df & string0[i])])\n        cre_string0.extend([x+off for x in find1(df & string1[i])])\n        off += 64\n    return des_string0, cre_string0\n\ndef excitation_level(string, nelec=None):\n    nset = len(string)\n    if nelec is None:\n        nelec = 0\n        for i in range(nset):\n            nelec += bin(string[i]).count('1')\n\n    g, b = nelec//64, nelec%64\n    tn = nelec - bin(string[-1-g])[-b:].count('1')\n    for s in string[nset-g:]:\n        tn -= bin(s).count('1')\n    return tn\n\ndef find1(s):\n    return [i for i,x in enumerate(bin(s)[2:][::-1]) if x is '1']\n\ndef toggle_bit(s, place):\n    nset = len(s)\n    g, b = place//64, place%64\n    s[-1-g] ^= numpy.uint64(1<<b)\n    return s\n\ndef select_strs_ctypes(myci, civec, h1, eri, jk, eri_sorted, jk_sorted, norb, nelec):\n    strs = civec._strs\n    ndet = strs.shape[0]\n    ndet, nset = strs.shape\n    nset = nset // 2\n    neleca, nelecb = nelec\n\n    h1 = numpy.asarray(h1, order='C')  \n    eri = numpy.asarray(eri, order='C')\n    jk = numpy.asarray(jk, order='C')\n    civec = numpy.asarray(civec, order='C')\n    strs = numpy.asarray(strs, order='C')\n    eri_sorted = numpy.asarray(eri_sorted, order='C')\n    jk_sorted = numpy.asarray(jk_sorted, order='C')\n\n    str_add = numpy.empty((0,strs.shape[1]), dtype=numpy.uint64)\n\n    batch_size = max(1, 8 * 4 * neleca * nelecb * (norb-neleca) * (norb-nelecb))\n    ndet_batch = int(myci.max_memory * 1024**2) // batch_size\n    nbatches = ndet // ndet_batch + 1\n\n    for i in range(nbatches):\n        ndet_start = ndet_batch * i\n        ndet_finish = min(ndet_batch * (i + 1), ndet)\n        ndet_select_max = 4 * neleca * nelecb * (norb-neleca) * (norb-nelecb) * ndet_batch\n\n        str_add_batch = numpy.empty((ndet_select_max, strs.shape[1]), dtype=numpy.uint64)\n        n_str_add_batch = numpy.array([str_add_batch.shape[0]])\n\n        str_add_batch = numpy.asarray(str_add_batch, order='C')\n\n        libhci.select_strs(h1.ctypes.data_as(ctypes.c_void_p), \n                           eri.ctypes.data_as(ctypes.c_void_p), \n                           jk.ctypes.data_as(ctypes.c_void_p), \n                           eri_sorted.ctypes.data_as(ctypes.c_void_p), \n                           jk_sorted.ctypes.data_as(ctypes.c_void_p), \n                           ctypes.c_int(norb), \n                           ctypes.c_int(neleca), \n                           ctypes.c_int(nelecb), \n                           strs.ctypes.data_as(ctypes.c_void_p), \n                           civec.ctypes.data_as(ctypes.c_void_p), \n                           ctypes.c_ulonglong(ndet_start), \n                           ctypes.c_ulonglong(ndet_finish), \n                           ctypes.c_double(myci.select_cutoff),\n                           str_add_batch.ctypes.data_as(ctypes.c_void_p),\n                           n_str_add_batch.ctypes.data_as(ctypes.c_void_p))\n\n        n_str_add_batch = n_str_add_batch[0]\n        str_add_batch = str_add_batch[:n_str_add_batch]\n        str_add = numpy.vstack((str_add, str_add_batch))\n\n    str_add = numpy.asarray(str_add)\n    return str_add\n\ndef enlarge_space(myci, civec, h1, eri, jk, eri_sorted, jk_sorted, norb, nelec):\n    if not isinstance(civec, (tuple, list)):\n        civec = [civec]\n\n    strs = civec[0]._strs\n\n    nroots = len(civec)\n\n    cidx = abs(civec[0]) > myci.ci_coeff_cutoff\n    for p in range(1,nroots):\n        cidx += abs(civec[p]) > myci.ci_coeff_cutoff\n\n    strs = strs[cidx]\n\n    ci_coeff = [as_SCIvector(c[cidx], strs) for c in civec]\n \n    strs_new = strs.copy()\n\n    for p in range(nroots):\n        str_add = select_strs_ctypes(myci, ci_coeff[p], h1, eri, jk, eri_sorted, jk_sorted, norb, nelec)\n        strs_new = numpy.vstack((strs, str_add))\n\n    # Add strings together and remove duplicate strings\n    tmp = numpy.ascontiguousarray(strs_new).view(numpy.dtype((numpy.void, strs_new.dtype.itemsize * strs_new.shape[1])))\n    _, tmpidx = numpy.unique(tmp, return_index=True)\n\n    new_ci = []\n    for p in range(nroots):\n        c = numpy.zeros(strs_new.shape[0])\n        c[:ci_coeff[p].shape[0]] = ci_coeff[p]\n        new_ci.append(c[tmpidx])\n\n    strs_new = strs_new[tmpidx]\n\n    return [as_SCIvector(ci, strs_new) for ci in new_ci]\n\ndef str2orblst(string, norb):\n    occ = []\n    vir = []\n    nset = len(string)\n    off = 0\n    for k in reversed(range(nset)):\n        s = string[k]\n        occ.extend([x+off for x in find1(s)])\n        for i in range(0, min(64, norb-off)): \n            if not (s & numpy.uint64(1<<i)):\n                vir.append(i+off)\n        off += 64\n    return occ, vir\n\ndef orblst2str(lst, norb):\n    nset = (norb+63) // 64\n    string = numpy.zeros(nset, dtype=numpy.uint64)\n    for i in lst:\n        toggle_bit(string, i)\n    return string\n\ndef kernel_float_space(myci, h1e, eri, norb, nelec, ci0=None,\n                       tol=None, lindep=None, max_cycle=None, max_space=None,\n                       nroots=None, davidson_only=None, max_iter=None,\n                       max_memory=None, verbose=None, ecore=0, return_integrals=False, \n                       eri_sorted=None, jk=None, jk_sorted=None, **kwargs):\n    if verbose is None:\n        log = logger.Logger(myci.stdout, myci.verbose)\n    elif isinstance(verbose, logger.Logger):\n        log = verbose\n    else:\n        log = logger.Logger(myci.stdout, verbose)\n    if tol is None: tol = myci.conv_tol\n    if lindep is None: lindep = myci.lindep\n    if max_cycle is None: max_cycle = myci.max_cycle\n    if max_space is None: max_space = myci.max_space\n    if max_memory is None: max_memory = myci.max_memory\n    if nroots is None: nroots = myci.nroots\n    if max_iter is None: max_iter = myci.max_iter\n    if myci.verbose >= logger.WARN:\n        myci.check_sanity()\n\n    log.info('\\nStarting heat-bath CI algorithm...\\n')\n    log.info('Selection threshold:                  %8.5e',    myci.select_cutoff)\n    log.info('CI coefficient cutoff:                %8.5e',    myci.ci_coeff_cutoff)\n    log.info('Energy convergence tolerance:         %8.5e',    tol)\n    log.info('Number of determinants tolerance:     %8.5e',    myci.conv_ndet_tol)\n    log.info('Number of electrons:                  %s',       nelec)\n    log.info('Number of orbitals:                   %3d',      norb)\n    log.info('Number of roots:                      %3d',    nroots)\n\n    nelec = direct_spin1._unpack_nelec(nelec, myci.spin)\n    eri = ao2mo.restore(1, eri, norb)\n\n    # Avoid resorting the integrals by storing them in memory\n    eri = eri.ravel()\n\n    if eri_sorted is None and jk is None and jk_sorted is None:\n        log.debug(\"\\nSorting two-electron integrals...\")\n        t_start = time.time()\n        eri_sorted = abs(eri).argsort()[::-1]\n        jk = eri.reshape([norb]*4)\n        jk = jk - jk.transpose(2,1,0,3)\n        jk = jk.ravel()\n        jk_sorted = abs(jk).argsort()[::-1]\n        t_current = time.time() - t_start\n        log.debug('Timing for sorting the integrals: %10.3f', t_current)\n\n    # Initial guess\n    if ci0 is None:\n        hf_str = numpy.hstack([orblst2str(range(nelec[0]), norb), orblst2str(range(nelec[1]), norb)]).reshape(1,-1)\n        ci0 = [as_SCIvector(numpy.ones(1), hf_str)]\n    else:\n        assert(nroots == len(ci0))\n\n    ci0 = myci.enlarge_space(ci0, h1e, eri, jk, eri_sorted, jk_sorted, norb, nelec)\n\n    def hop(c):\n        hc = myci.contract_2e((h1e, eri), as_SCIvector(c, ci_strs), norb, nelec, hdiag)\n        return hc.ravel()\n    precond = lambda x, e, *args: x/(hdiag-e+myci.level_shift)\n\n    e_last = 0\n    float_tol = 3e-4\n    conv = False\n    for icycle in range(max_iter):\n        ci_strs = ci0[0]._strs\n        float_tol = max(float_tol*.3, tol*1e2)\n        log.info('\\nMacroiteration %d', icycle)\n        log.info('Number of CI configurations: %d', ci_strs.shape[0])\n        hdiag = myci.make_hdiag(h1e, eri, ci_strs, norb, nelec)\n        t_start = time.time()\n        e, ci0 = myci.eig(hop, ci0, precond, tol=float_tol, lindep=lindep,\n                          max_cycle=max_cycle, max_space=max_space, nroots=nroots,\n                          max_memory=max_memory, verbose=log, **kwargs)\n        if not isinstance(ci0, (tuple, list)):\n            ci0 = [ci0]\n            e = [e]\n        t_current = time.time() - t_start\n        log.debug('Timing for solving the eigenvalue problem: %10.3f', t_current)\n        ci0 = [as_SCIvector(c, ci_strs) for c in ci0]\n        de, e_last = min(e)-e_last, min(e)\n        log.info('Cycle %d  E = %s  dE = %.8g', icycle, numpy.array(e)+ecore, de)\n\n        if abs(de) < tol*1e3:\n            conv = True\n            break\n\n        last_ci0_size = float(len(ci_strs))\n        t_start = time.time()\n        ci0 = myci.enlarge_space(ci0, h1e, eri, jk, eri_sorted, jk_sorted, norb, nelec)\n        t_current = time.time() - t_start\n        log.debug('Timing for selecting configurations: %10.3f', t_current)\n        if (((1 - myci.conv_ndet_tol) < len(ci0[0]._strs)/last_ci0_size < (1 + myci.conv_ndet_tol))):\n            conv = True\n            break\n\n    ci_strs = ci0[0]._strs\n    log.info('\\nExtra CI in the final selected space')\n    log.info('Number of CI configurations: %d', ci_strs.shape[0])\n    hdiag = myci.make_hdiag(h1e, eri, ci_strs, norb, nelec)\n    e, c = myci.eig(hop, ci0, precond, tol=tol, lindep=lindep,\n                    max_cycle=max_cycle, max_space=max_space, nroots=nroots,\n                    max_memory=max_memory, verbose=log, **kwargs)\n    if not isinstance(c, (tuple, list)):\n        c = [c]\n        e = [e]\n    log.info('\\nSelected CI  E = %s', numpy.array(e)+ecore)\n\n    if (return_integrals):\n        return (numpy.array(e)+ecore), [as_SCIvector(ci, ci_strs) for ci in c], eri_sorted, jk, jk_sorted\n    else:\n        return (numpy.array(e)+ecore), [as_SCIvector(ci, ci_strs) for ci in c]\n\ndef fix_spin(myci, shift=.2, ss=None, **kwargs):\n    r'''If Selected CI solver cannot stick on spin eigenfunction, modify the solver by\n    adding a shift on spin square operator\n\n    .. math::\n\n        (H + shift*S^2) |\\Psi\\rangle = E |\\Psi\\rangle\n\n    Args:\n        myci : An instance of :class:`SelectedCI`\n\n    Kwargs:\n        shift : float\n            Level shift for states which have different spin\n        ss : number\n            S^2 expection value == s*(s+1)\n\n    Returns\n            A modified Selected CI object based on myci.\n    '''\n    if 'ss_value' in kwargs:\n        sys.stderr.write('fix_spin_: kwarg \"ss_value\" will be removed in future release. '\n                         'It was replaced by \"ss\"\\n')\n        ss_value = kwargs['ss_value']\n    else:\n        ss_value = ss\n\n    def contract_2e(h1_h2, civec, norb, nelec, hdiag=None, **kwargs):\n        if isinstance(nelec, (int, numpy.number)):\n            sz = (nelec % 2) * .5\n        else:\n            sz = abs(nelec[0]-nelec[1]) * .5\n        if ss_value is None:\n            ss = sz*(sz+1)\n        else:\n            ss = ss_value\n\n        h1, eri = h1_h2\n        strs = civec._strs\n        ndet = len(strs)\n        if hdiag is None:\n            hdiag = make_hdiag(h1, eri, strs, norb, nelec)\n        ci1 = numpy.zeros_like(civec)\n        ci2 = numpy.zeros_like(civec)\n\n        h1 = numpy.asarray(h1, order='C')\n        eri = numpy.asarray(eri, order='C')\n        strs = numpy.asarray(strs, order='C')\n        civec = numpy.asarray(civec, order='C')\n        hdiag = numpy.asarray(hdiag, order='C')\n        ci1 = numpy.asarray(ci1, order='C')\n        ci2 = numpy.asarray(ci2, order='C')\n\n        libhci.contract_h_c_ss_c(h1.ctypes.data_as(ctypes.c_void_p), \n                                 eri.ctypes.data_as(ctypes.c_void_p), \n                                 ctypes.c_int(norb), \n                                 ctypes.c_int(nelec[0]), \n                                 ctypes.c_int(nelec[1]), \n                                 strs.ctypes.data_as(ctypes.c_void_p), \n                                 civec.ctypes.data_as(ctypes.c_void_p), \n                                 hdiag.ctypes.data_as(ctypes.c_void_p), \n                                 ctypes.c_ulonglong(ndet), \n                                 ci1.ctypes.data_as(ctypes.c_void_p),\n                                 ci2.ctypes.data_as(ctypes.c_void_p))\n\n        if ss < sz*(sz+1)+.1:\n# (S^2-ss)|Psi> to shift state other than the lowest state\n            ci2 -= ss * civec\n        else:\n# (S^2-ss)^2|Psi> to shift states except the given spin.\n# It still relies on the quality of initial guess\n            tmp = ci2.copy()\n            tmp -= ss * civec\n            ci2 = -ss * tmp\n            ci2 += myci.contract_ss(as_SCIvector_if_not(tmp, strs), norb, nelec)\n            tmp = None\n        ci2 *= shift\n        ci1 += ci2\n\n        return as_SCIvector_if_not(ci1, strs)\n\n    myci.contract_2e = contract_2e\n    return myci\n\ndef to_fci(civec, norb, nelec, root=0):\n    assert(norb <= 64)\n    neleca, nelecb = nelec\n    strsa = cistring.gen_strings4orblist(range(norb), neleca)\n    stradic = dict(zip(strsa,range(strsa.__len__())))\n    strsb = cistring.gen_strings4orblist(range(norb), nelecb)\n    strbdic = dict(zip(strsb,range(strsb.__len__())))\n    na = len(stradic)\n    nb = len(strbdic)\n    ndet = len(civec[root])\n    fcivec = numpy.zeros((na,nb))\n    for idet, (stra, strb) in enumerate(civec[root]._strs.reshape(ndet,2,-1)):\n        ka = stradic[stra[0]]\n        kb = strbdic[strb[0]]\n        fcivec[ka,kb] = civec[root][idet]\n    return fcivec\n\ndef from_fci(fcivec, ci_strs, norb, nelec):\n    neleca, nelecb = nelec\n    strsa = cistring.gen_strings4orblist(range(norb), neleca)\n    stradic = dict(zip(strsa,range(strsa.__len__())))\n    strsb = cistring.gen_strings4orblist(range(norb), nelecb)\n    strbdic = dict(zip(strsb,range(strsb.__len__())))\n    na = len(stradic)\n    nb = len(strbdic)\n    fcivec = fcivec.reshape(na,nb)\n    ta = [excitation_level(s, neleca) for s in strsa.reshape(-1,1)]\n    tb = [excitation_level(s, nelecb) for s in strsb.reshape(-1,1)]\n    ndet = len(ci_strs)\n    civec = numpy.zeros(ndet)\n    for idet, (stra, strb) in enumerate(ci_strs.reshape(ndet,2,-1)):\n        ka = stradic[stra[0]]\n        kb = strbdic[strb[0]]\n        civec[idet] = fcivec[ka,kb]\n    return as_SCIvector(civec, ci_strs)\n\ndef make_rdm12s(civec, norb, nelec):\n    '''Spin orbital 1- and 2-particle reduced density matrices (aa, bb, aaaa, aabb, bbbb)\n    '''\n    strs = civec._strs\n    ndet = len(strs)\n    rdm1a = numpy.zeros(norb*norb)\n    rdm1b = numpy.zeros(norb*norb)\n    rdm2aa = numpy.zeros(norb*norb*norb*norb)\n    rdm2ab = numpy.zeros(norb*norb*norb*norb)\n    rdm2bb = numpy.zeros(norb*norb*norb*norb)\n\n    civec = numpy.asarray(civec, order='C')\n    strs = numpy.asarray(strs, order='C')\n    rdm1a  = numpy.asarray(rdm1a, order='C')\n    rdm1b  = numpy.asarray(rdm1b, order='C')\n    rdm2aa = numpy.asarray(rdm2aa, order='C')\n    rdm2ab = numpy.asarray(rdm2ab, order='C')\n    rdm2bb = numpy.asarray(rdm2bb, order='C')\n\n    # Compute 1- and 2-RDMs\n    libhci.compute_rdm12s(ctypes.c_int(norb), \n                          ctypes.c_int(nelec[0]), \n                          ctypes.c_int(nelec[1]), \n                          strs.ctypes.data_as(ctypes.c_void_p), \n                          civec.ctypes.data_as(ctypes.c_void_p), \n                          ctypes.c_ulonglong(ndet), \n                          rdm1a.ctypes.data_as(ctypes.c_void_p),\n                          rdm1b.ctypes.data_as(ctypes.c_void_p),\n                          rdm2aa.ctypes.data_as(ctypes.c_void_p),\n                          rdm2ab.ctypes.data_as(ctypes.c_void_p),\n                          rdm2bb.ctypes.data_as(ctypes.c_void_p))\n\n    rdm1a = rdm1a.reshape([norb]*2)\n    rdm1b = rdm1b.reshape([norb]*2)\n    rdm2aa = rdm2aa.reshape([norb]*4)\n    rdm2ab = rdm2ab.reshape([norb]*4)\n    rdm2bb = rdm2bb.reshape([norb]*4)\n\n    # Sort 2-RDM into chemists' notation: <p_1 q_2|r_1 s_2> -> (p_1 r_1| q_2 s_2)\n    rdm2aa = rdm2aa.transpose(0,2,1,3)\n    rdm2ab = rdm2ab.transpose(0,2,1,3)\n    rdm2bb = rdm2bb.transpose(0,2,1,3)\n\n    return (rdm1a, rdm1b), (rdm2aa, rdm2ab, rdm2bb)\n\nclass SelectedCI(direct_spin1.FCISolver):\n    def __init__(self, mol=None):\n        direct_spin1.FCISolver.__init__(self, mol)\n        self.ci_coeff_cutoff = .5e-3\n        self.select_cutoff = .5e-3\n        self.conv_tol = 1e-9\n        self.conv_ndet_tol = 0.001\n        self.nroots = 1\n        self.max_iter = 10\n        # Maximum memory in MB for storing lists of selected strings\n        self.max_memory = 1000\n\n##################################################\n# don't modify the following attributes, they are not input options\n        #self.converged = False\n        #self.ci = None\n        self._strs = None\n        self._keys = set(self.__dict__.keys())\n\n    def dump_flags(self, verbose=None):\n        direct_spin1.FCISolver.dump_flags(self, verbose)\n        logger.info(self, 'ci_coeff_cutoff %g', self.ci_coeff_cutoff)\n        logger.info(self, 'select_cutoff   %g', self.select_cutoff)\n\n    # define absorb_h1e for compatibility to other FCI solver\n    def absorb_h1e(h1, eri, *args, **kwargs):\n        return (h1, eri)\n\n    def contract_2e(self, h1_h2, civec, norb, nelec, hdiag=None, **kwargs):\n        if getattr(civec, '_strs', None) is not None:\n            self._strs = civec._strs\n        else:\n            assert(civec.size == len(self._strs))\n            civec = as_SCIvector(civec, self._strs)\n        return contract_2e_ctypes(h1_h2, civec, norb, nelec, hdiag, **kwargs)\n#        return contract_2e(h1_h2, civec, norb, nelec, hdiag, **kwargs)\n\n    def contract_ss(self, civec, norb, nelec):\n        if getattr(civec, '_strs', None) is not None:\n            self._strs = civec._strs\n        else:\n            assert(civec.size == len(self._strs))\n            civec = as_SCIvector(civec, self._strs)\n        return contract_ss(civec, norb, nelec)\n\n    def spin_square(self, civec, norb, nelec):\n        if getattr(civec, '_strs', None) is not None:\n            self._strs = civec._strs\n        else:\n            assert(civec.size == len(self._strs))\n            civec = as_SCIvector(civec, self._strs)\n        return spin_square(civec, norb, nelec)\n\n    def make_hdiag(self, h1e, eri, strs, norb, nelec):\n        return make_hdiag(h1e, eri, strs, norb, nelec)\n\n    def to_fci(self, civec, norb, nelec):\n\n        if getattr(civec, '_strs', None) is not None:\n            self._strs = civec._strs\n        else:\n            assert(civec.size == len(self._strs))\n            civec = as_SCIvector(civec, self._strs)\n\n        return to_fci(civec, norb, nelec)\n\n    def make_rdm12s(self, civec, norb, nelec):\n\n        if getattr(civec, '_strs', None) is not None:\n            self._strs = civec._strs\n        else:\n            assert(civec.size == len(self._strs))\n            civec = as_SCIvector(civec, self._strs)\n\n        return make_rdm12s(civec, norb, nelec)\n\n    enlarge_space = enlarge_space\n    kernel = kernel_float_space\n\nSCI = SelectedCI\n\n\nclass _SCIvector(numpy.ndarray):\n    def __array_finalize__(self, obj):\n        self._strs = getattr(obj, '_strs', None)\n\ndef as_SCIvector(civec, ci_strs):\n    civec = civec.view(_SCIvector)\n    civec._strs = ci_strs\n    return civec\n\ndef as_SCIvector_if_not(civec, ci_strs):\n    if getattr(civec, '_strs', None) is None:\n        civec = as_SCIvector(civec, ci_strs)\n    return civec\n\n\nif __name__ == '__main__':\n    numpy.random.seed(3)\n    strs = (numpy.random.random((14,3)) * 4).astype(numpy.uint64)\n    print(strs)\n    print(argunique(strs))\n\n    norb = 6\n    nelec = 3,3\n    hf_str = numpy.hstack([orblst2str(range(nelec[0]), norb),\n                           orblst2str(range(nelec[1]), norb)]).reshape(1,-1)\n    numpy.random.seed(3)\n    h1 = numpy.random.random([norb]*2)**4 * 1e-2\n    h1 = h1 + h1.T\n    eri = numpy.random.random([norb]*4)**4 * 1e-2\n    eri = eri + eri.transpose(0,1,3,2)\n    eri = eri + eri.transpose(1,0,2,3)\n    eri = eri + eri.transpose(2,3,0,1)\n    eri_sorted = abs(eri).argsort()[::-1]\n    jk = eri.reshape([norb]*4)\n    jk = jk - jk.transpose(2,1,0,3)\n    jk = jk.ravel()\n    jk_sorted = abs(jk).argsort()[::-1]\n    ci1 = [as_SCIvector(numpy.ones(1), hf_str)]\n\n    myci = SelectedCI()\n    myci.select_cutoff = .001\n    myci.ci_coeff_cutoff = .001\n\n    ci2 = enlarge_space(myci, ci1, h1, eri, jk, eri_sorted, jk_sorted, norb, nelec)\n    print(len(ci2[0]))\n\n    ci2 = enlarge_space(myci, ci1, h1, eri, jk, eri_sorted, jk_sorted, norb, nelec)\n    numpy.random.seed(1)\n    ci3 = numpy.random.random(ci2[0].size)\n    ci3 *= 1./numpy.linalg.norm(ci3)\n    ci3 = [ci3]\n    ci3 = enlarge_space(myci, ci2, h1, eri, jk, eri_sorted, jk_sorted, norb, nelec)\n\n    efci = direct_spin1.kernel(h1, eri, norb, nelec, verbose=5)[0]\n\n    ci4 = contract_2e_ctypes((h1, eri), ci3[0], norb, nelec)\n\n    fci3 = to_fci(ci3, norb, nelec)\n    h2e = direct_spin1.absorb_h1e(h1, eri, norb, nelec, .5)\n    fci4 = direct_spin1.contract_2e(h2e, fci3, norb, nelec)\n    fci4 = from_fci(fci4, ci3[0]._strs, norb, nelec)\n    print(abs(ci4-fci4).sum())\n\n    e = myci.kernel(h1, eri, norb, nelec, verbose=5)[0]\n    print(e, efci)\n", "meta": {"hexsha": "d2f521476264b468516fa3c4ffcdd8206d83228c", "size": 30560, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/hci/hci.py", "max_stars_repo_name": "crisely09/pyscf", "max_stars_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-03T12:32:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T08:19:02.000Z", "max_issues_repo_path": "pyscf/hci/hci.py", "max_issues_repo_name": "crisely09/pyscf", "max_issues_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-09-16T17:58:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-22T17:26:01.000Z", "max_forks_repo_path": "pyscf/hci/hci.py", "max_forks_repo_name": "crisely09/pyscf", "max_forks_repo_head_hexsha": "cb92f7974bd9c87c0ef5b2b52abf5d3219b3d6b6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-06-01T05:31:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T02:38:33.000Z", "avg_line_length": 36.1229314421, "max_line_length": 120, "alphanum_fraction": 0.557460733, "include": true, "reason": "import numpy", "num_tokens": 9208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.30735802955444114, "lm_q1q2_score": 0.16327147084315458}}
{"text": "##########################\n##########################\n###                    ###\n###  MUTE              ###\n###  William Woodley   ###\n###  19 December 2021  ###\n###                    ###\n##########################\n##########################\n\n# Import packages\n\nimport os\n\nimport numpy as np\nfrom tqdm import tqdm\n\nimport mute.constants as constants\n\ntry:\n\n    import proposal as pp\n\nexcept ImportError:\n\n    pass\n\n# Create the propagator\n\n\ndef _create_propagator(force):\n\n    \"\"\"This function creates the propagator object in PROPOSAL for use in _propagation_loop()\"\"\"\n\n    # Check values\n\n    constants.check_constants(force=force)\n\n    # Global variables\n    # The propagator is used in every iteration of the doubly-nested propagation loop\n    # Make it a global variable so it only has to be created once\n\n    global propagator\n\n    if constants.get_verbose() > 1:\n        print(\"Creating propagator.\")\n\n    # Propagator arguments\n\n    mu = pp.particle.MuMinusDef()\n    cuts = pp.EnergyCutSettings(500, 0.05, True)\n\n    if constants.get_medium() == \"rock\":\n\n        medium = pp.medium.StandardRock()\n\n    elif constants.get_medium() == \"water\":\n\n        medium = pp.medium.Water()\n\n    elif constants.get_medium() == \"ice\":\n\n        medium = pp.medium.Ice()\n\n    elif constants.get_medium() == \"air\":\n\n        medium = pp.medium.Air()\n\n    else:\n\n        raise NotImplementedError(\n            \"Medium type {0} not implemented.\".format(constants.get_medium())\n        )\n\n    args = {\"particle_def\": mu, \"target\": medium, \"interpolate\": True, \"cuts\": cuts}\n\n    # Initialise standard cross-sections, then specify and set parametrisation models\n\n    cross_sections = pp.crosssection.make_std_crosssection(**args)\n\n    brems_param = pp.parametrization.bremsstrahlung.KelnerKokoulinPetrukhin(lpm=False)\n    epair_param = pp.parametrization.pairproduction.KelnerKokoulinPetrukhin(lpm=False)\n    ionis_param = pp.parametrization.ionization.BetheBlochRossi(energy_cuts=cuts)\n    shado_param = pp.parametrization.photonuclear.ShadowButkevichMikheyev()\n    photo_param = pp.parametrization.photonuclear.AbramowiczLevinLevyMaor97(\n        shadow_effect=shado_param\n    )\n\n    cross_sections[0] = pp.crosssection.make_crosssection(brems_param, **args)\n    cross_sections[1] = pp.crosssection.make_crosssection(epair_param, **args)\n    cross_sections[2] = pp.crosssection.make_crosssection(ionis_param, **args)\n    cross_sections[3] = pp.crosssection.make_crosssection(photo_param, **args)\n\n    # Propagation utility\n\n    collection = pp.PropagationUtilityCollection()\n\n    collection.interaction = pp.make_interaction(cross_sections, True)\n    collection.displacement = pp.make_displacement(cross_sections, True)\n    collection.time = pp.make_time(cross_sections, mu, True)\n    collection.decay = pp.make_decay(cross_sections, mu, True)\n\n    pp.PropagationUtilityCollection.cont_rand = False\n\n    utility = pp.PropagationUtility(collection=collection)\n\n    # Other settings\n\n    pp.do_exact_time = False\n\n    # Set up geometry\n\n    detector = pp.geometry.Sphere(\n        position=pp.Cartesian3D(0, 0, 0), radius=10000000, inner_radius=0\n    )\n    density_distr = pp.density_distribution.density_homogeneous(\n        mass_density=constants.get_density()\n    )\n\n    propagator = pp.Propagator(mu, [(detector, utility, density_distr)])\n\n    if constants.get_verbose() > 1:\n        print(\"Finished creating propagator.\")\n\n    return propagator\n\n\n# Propagation function\n\n\ndef _propagation_loop(energy, slant_depth, force):\n\n    # This function propagates n_muon muons, looping over the energies and slant depths, and returns the muons' underground energies\n\n    # Check values\n\n    n_muon = constants.get_n_muon()\n\n    constants.check_constants(force=force)\n\n    # Convert the slant depth from [km.w.e.] to [cm]\n\n    convert_to_cm = 1e5 * 0.997 / constants.get_density()\n\n    # Initialise the list of underground energies\n\n    u_energies_ix = []\n\n    # Define the initial state of the muon\n\n    mu_initial = pp.particle.ParticleState()\n    mu_initial.energy = energy + constants.MU_MASS\n    mu_initial.position = pp.Cartesian3D(0, 0, 0)\n    mu_initial.direction = pp.Cartesian3D(0, 0, -1)\n\n    # Propagate n_muon muons\n\n    for _ in range(n_muon):\n\n        # Propagate the muons\n\n        track = propagator.propagate(mu_initial, slant_depth * convert_to_cm)\n\n        # Test whether or not the muon has energy left (has not lost all of its energy or has not decayed)\n        # If it does, record its energy\n        # If it does not, ignore this muon and proceed with the next loop iteration\n\n        if (\n            track.track_energies()[-1] != constants.MU_MASS\n            and track.track_types()[-1] != pp.particle.Interaction_Type.decay\n        ):\n\n            # Store the final underground energy of the muon\n\n            u_energies_ix.append(track.track_energies()[-1])\n\n    # Return the underground energies for the muon\n\n    return u_energies_ix\n\n\n# Propagate the muons and return underground energies\n\n\ndef propagate_muons(seed=0, job_array_number=0, output=None, force=False):\n\n    \"\"\"\n    Propagate muons for the default surface energy grid and slant depths.\n\n    The default surface energy grid is given by constants.ENERGIES, and the default slant depths are given by constants.SLANT_DEPTHS.\n\n    Parameters\n    ----------\n    seed : str, optional (default: 0)\n        The random seed for use in the PROPOSAL propagator.\n\n    job_array_number : int, optional (default: 0)\n        The job array number from a high-statistics run on a computer cluster. This is set so the underground energy files from each job in the job array will be named differently.\n\n    output : bool, optional (default: taken from constants.get_output())\n        If True, an output file will be created to store the results.\n\n    force : bool, optional (default: False)\n        If True, this will force the creation of an underground_energies directory if one does not already exist.\n\n    Returns\n    -------\n    u_energies : NumPy ndarray\n        A two-dimensional array containing lists of underground energies for muons that survived the propagation.\n    \"\"\"\n\n    # Check values\n\n    assert type(job_array_number) == int, \"job_array_number must be an integer.\"\n\n    constants.check_constants(force=force)\n\n    if output is None:\n        output = constants.get_output()\n\n    # Create the propagator once\n\n    _create_propagator(force=force)\n\n    # Set the random seed\n\n    pp.RandomGenerator.get().set_seed(seed)\n\n    # Initialise the matrix of underground energies\n\n    u_energies = np.zeros(\n        (len(constants.ENERGIES), len(constants.SLANT_DEPTHS)), dtype=np.ndarray\n    )\n\n    # Run the propagation function and print the underground energies\n\n    if constants.get_verbose() >= 1:\n        print(\n            \"Propagating \"\n            + str(\n                constants.get_n_muon()\n                * len(constants.ENERGIES)\n                * len(constants.SLANT_DEPTHS)\n            )\n            + \" muons.\"\n        )\n\n    for i in (\n        tqdm(range(len(constants.ENERGIES)))\n        if constants.get_verbose() >= 1\n        else range(len(constants.ENERGIES))\n    ):\n\n        for x in range(len(constants.SLANT_DEPTHS)):\n\n            u_energies[i, x] = _propagation_loop(\n                constants.ENERGIES[i], constants.SLANT_DEPTHS[x], force=force\n            )\n\n    if constants.get_verbose() >= 1:\n        print(\"Finished propagation.\")\n\n    if output:\n\n        constants.check_directory(\n            os.path.join(constants.get_directory(), \"underground_energies\"), force=force\n        )\n\n        file_name = os.path.join(\n            constants.get_directory(),\n            \"underground_energies\",\n            \"{0}_{1}_{2}_Underground_Energies_{3}.npy\".format(\n                constants.get_medium(),\n                constants.get_density(),\n                constants.get_n_muon(),\n                job_array_number,\n            ),\n        )\n\n        np.save(file_name, u_energies)\n\n        if constants.get_verbose() > 1:\n            print(\"Underground energies written to \" + file_name + \".\")\n\n    return u_energies\n\n\n# Load underground energies\n\n\ndef _load_u_energies_from_files(file_name, n_job=1, force=False):\n\n    \"\"\"\n    Load the underground energies resulting from the PROPOSAL Monte Carlo from a file or collection of files stored in data/underground_energies.\n\n    Parameters\n    ----------\n    file_name : str, optional\n        The file name pattern that the underground energy data is stored in. This should end in an underscore so the function can append the job array number.\n\n    n_job : int, optional (default: 1)\n        The number of jobs that were run on the computer cluster. Set this to the number of files the underground energies are spread across.\n\n    force : bool, optional (default: False)\n        If True, this will force the creation of an underground_energies directory if one does not already exist.\n\n    Returns\n    -------\n    u_energies : NumPy ndarray\n        A two-dimensional array containing lists of underground energies for muons that survived the propagation.\n    \"\"\"\n\n    # Check values\n\n    constants.check_constants(force=force)\n\n    # Check that the directory exists\n\n    if not os.path.exists(constants.get_directory() + \"/underground_energies\"):\n\n        if constants.get_verbose() >= 1:\n\n            print(\n                constants.get_directory()\n                + \"/underground_energies does not exist. Underground energies not loaded.\"\n            )\n\n        return None\n\n    # Test if the file exists\n\n    if not os.path.isfile(file_name + \"_0.npy\"):\n\n        if constants.get_verbose() >= 1:\n\n            print(file_name + \"_0.npy does not exist. Underground energies not loaded.\")\n\n        return None\n\n    # Fill a u_energies array with empty lists that will be able to be extended\n\n    u_energies = np.empty(\n        (len(constants.ENERGIES), len(constants.SLANT_DEPTHS)), dtype=object\n    )\n\n    for i in np.ndindex(u_energies.shape):\n        u_energies[i] = []\n\n    # Loop over all output files and add the contents to u_energies\n\n    for a in tqdm(range(n_job)) if constants.get_verbose() >= 1 else range(n_job):\n\n        u_energies += np.load(file_name + \"_\" + str(a) + \".npy\", allow_pickle=True)\n\n    if constants.get_verbose() > 1:\n        print(\"Loaded underground energies.\")\n\n    return u_energies\n\n\ndef calc_survival_probability_tensor(\n    seed=0, file_name=None, n_job=1, output=None, force=False\n):\n\n    \"\"\"\n    Calculate survival probabilities for the default surface energy grid and slant depths.\n\n    The default surface energy grid is given by constants.ENERGIES, and the default slant depths are given by constants.SLANT_DEPTHS. If the propagation of muons has already been done, this will load the underground energies file (it will load it for n_job = 1; to load for more jobs, call load_u_energies_from_files() directly), unless force is set to True.\n\n    Parameters\n    ----------\n    seed : int, optional (default: 0)\n        The random seed for use in the PROPOSAL propagator.\n\n    file_name : str, optional\n        The file name pattern that the underground energy data is stored in. This should end in an underscore so the function can append the job array number.\n\n    n_job : int, optional (default: 1)\n        The number of jobs that were run on the computer cluster. Set this to the number of files the underground energies are spread across.\n\n    output : bool, optional (default: taken from constants.get_output())\n        If True, an output file will be created to store the results.\n\n    force : bool, optional (default: False)\n        If True, this will force the muons to be propagated whether an underground energies file already exists or not.\n\n    Returns\n    -------\n    survival : NumPy ndarray\n        A three-dimensional array containing the survival probabilities.\n    \"\"\"\n\n    # Check values\n\n    if output is None:\n        output = constants.get_output()\n\n    # Construct a file name\n\n    file_name_default = os.path.join(\n        constants.get_directory(),\n        \"underground_energies\",\n        \"{0}_{1}_{2}_Underground_Energies\".format(\n            constants.get_medium(),\n            constants.get_density(),\n            int(constants.get_n_muon() / n_job),\n        ),\n    )\n\n    # Check if propagate_muons() should be forced or not\n    # If not, check if underground energy files exist\n    # If not, ask if muons should be propagated\n\n    if force:\n\n        u_energies = propagate_muons(seed=seed, output=output, force=force)\n\n    else:\n\n        # Check if the user has specified underground energies to load\n        # If not, look for the default file name pattern, and check if it exists\n        # If so, load the underground energies\n        # If not, ask if muons should be propagated\n\n        if file_name is not None:\n\n            u_energies = _load_u_energies_from_files(\n                file_name=os.path.join(\n                    constants.get_directory(), \"underground_energies\", file_name\n                ),\n                n_job=n_job,\n                force=force,\n            )\n\n        elif os.path.isfile(file_name_default + \"_0.npy\"):\n\n            u_energies = _load_u_energies_from_files(\n                file_name=file_name_default, n_job=n_job, force=force\n            )\n\n        else:\n\n            answer = input(\n                \"No underground energy file currently exists for the set lab, medium, or number of muons. Would you like to create one (y/n)?: \"\n            )\n\n            if answer.lower() == \"y\":\n\n                u_energies = propagate_muons(seed=seed, output=output, force=force)\n\n            else:\n\n                print(\"Underground energies not calculated.\")\n                print(\"Survival probabilities not calculated.\")\n\n                return\n\n    # Check that the underground energies were loaded\n\n    if u_energies is None:\n\n        print(\"Survival probabilities not calculated.\")\n\n        return\n\n    # Calculate the survival probabilities\n    # First index  = Surface energy\n    # Second index = Slant depth\n    # Third index  = Underground energy\n\n    survival = np.zeros(\n        (len(constants.ENERGIES), len(constants.SLANT_DEPTHS), len(constants.ENERGIES))\n    )\n\n    if constants.get_verbose() > 1:\n        print(\"Calculating survival probabilities.\")\n\n    for i in range(len(constants.ENERGIES)):\n\n        for x in range(len(constants.SLANT_DEPTHS)):\n\n            survival[i, x, :] = np.histogram(\n                np.array(u_energies[i, x]), bins=constants.E_BINS\n            )[0] / float(constants.get_n_muon())\n\n    if constants.get_verbose() > 1:\n        print(\"Finished calculating survival probabilities.\")\n\n    # Write the results to a file\n\n    if output:\n\n        constants.check_directory(\n            os.path.join(constants.get_directory(), \"survival_probabilities\"),\n            force=force,\n        )\n\n        file_name = os.path.join(\n            constants.get_directory(),\n            \"survival_probabilities\",\n            \"{0}_{1}_{2}_Survival_Probabilities.txt\".format(\n                constants.get_medium(), constants.get_density(), constants.get_n_muon()\n            ),\n        )\n\n        file_out = open(file_name, \"w\")\n\n        for i in range(len(constants.ENERGIES)):\n\n            for x in range(len(constants.SLANT_DEPTHS)):\n\n                for u in range(len(constants.ENERGIES)):\n\n                    file_out.write(\n                        \"{0:1.14f} {1:1.5f} {2:1.14f} {3:1.14e}\\n\".format(\n                            constants.ENERGIES[i],\n                            constants.SLANT_DEPTHS[x],\n                            constants.ENERGIES[u],\n                            survival[i, x, u],\n                        )\n                    )\n\n        file_out.close()\n\n        if constants.get_verbose() > 1:\n            print(\"Survival probabilities written to \" + file_name + \".\")\n\n    return survival\n\n\ndef load_survival_probability_tensor_from_file(force=False):\n\n    \"\"\"\n    Retrieve a survival probability matrix stored in data/survival_probabilities based on the set global parameters.\n\n    The function searches for a file name that matches the set lab, medium, and number of muons. If the file does not exist, prompt the user to run calc_survival().\n\n    Parameters\n    ----------\n    force : bool\n        If True, force the calculation of a new survival probability tensor if required.\n\n    Returns\n    -------\n    survival : NumPy ndarray\n        A two-dimensional array containing the survival probabilities.\n    \"\"\"\n\n    # Define a function to run if there is no survival probability file\n\n    def no_file(force):\n\n        # If the file does not exist, ask the user if they want to run PROPOSAL to create it\n\n        if not force:\n\n            answer = input(\n                \"No survival probability matrix currently exists for the set lab, medium, or number of muons. Would you like to create one (y/n)?: \"\n            )\n\n        if force or answer.lower() == \"y\":\n\n            survival_full = calc_survival_probability_tensor(force=force)\n\n            return survival_full\n\n        else:\n\n            print(\"Survival probabilities not calculated.\")\n\n            return None\n\n    # Construct a file name based on the set lab, medium, and number of muons\n\n    file_name = os.path.join(\n        constants.get_directory(),\n        \"survival_probabilities\",\n        \"{0}_{1}_{2}_Survival_Probabilities.txt\".format(\n            constants.get_medium(), constants.get_density(), constants.get_n_muon()\n        ),\n    )\n\n    # Check if the file exists\n    # Also check that the file has the correct number of energies and angles\n\n    if os.path.isfile(file_name):\n\n        if constants.get_verbose() > 1:\n            print(\"Loading survival probabilities from \" + file_name + \".\")\n\n        # If the file exists, read in the survival probabilities from it\n\n        file = open(file_name, \"r\")\n        n_lines = len(file.read().splitlines())\n\n        file.close()\n\n        if n_lines == constants.len_iju:\n\n            survival = np.reshape(\n                np.loadtxt(file_name)[:, 3],\n                (\n                    len(constants.ENERGIES),\n                    len(constants.SLANT_DEPTHS),\n                    len(constants.ENERGIES),\n                ),\n            )\n\n            if constants.get_verbose() > 1:\n                print(\"Loaded survival probabilities.\")\n\n            return survival\n\n        else:\n\n            return no_file(force=force)\n\n    else:\n\n        return no_file(force=force)\n\n\n# Read the energies and slant depths from a survival probabilities file\n\n\ndef print_survival_probability_tensor_grids(file_name):\n\n    \"\"\"Return the slant depths and underground energies in a survival probability file.\"\"\"\n\n    file_contents = np.loadtxt(\n        os.path.join(constants.get_directory(), \"survival_probabilities\", file_name)\n    )\n\n    file_s_energies = np.unique(file_contents[:, 0])\n    file_slant_depths = np.unique(file_contents[:, 1])\n    file_u_energies = np.unique(file_contents[:, 2])\n\n    print(\"This file has \" + str(len(file_s_energies)) + \" surface energies:\")\n    print(file_s_energies)\n    print(\"This file has \" + str(len(file_slant_depths)) + \" slant depths:\")\n    print(file_slant_depths)\n    print(\"This file has \" + str(len(file_u_energies)) + \" underground energies:\")\n    print(file_u_energies)\n\n    return\n", "meta": {"hexsha": "8be3856bb503566854ad6485418521b3a812d34c", "size": 19346, "ext": "py", "lang": "Python", "max_stars_repo_path": "mute/propagation.py", "max_stars_repo_name": "afedynitch/mute", "max_stars_repo_head_hexsha": "87ee12fcf2050bae29b471804866029ce9979aaa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-12-13T07:43:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T05:09:29.000Z", "max_issues_repo_path": "mute/propagation.py", "max_issues_repo_name": "afedynitch/mute", "max_issues_repo_head_hexsha": "87ee12fcf2050bae29b471804866029ce9979aaa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-19T13:18:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T13:18:23.000Z", "max_forks_repo_path": "mute/propagation.py", "max_forks_repo_name": "afedynitch/mute", "max_forks_repo_head_hexsha": "87ee12fcf2050bae29b471804866029ce9979aaa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-01-19T13:11:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T23:52:05.000Z", "avg_line_length": 29.9473684211, "max_line_length": 358, "alphanum_fraction": 0.6412695131, "include": true, "reason": "import numpy", "num_tokens": 4355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.1632714629107022}}
{"text": "#!/usr/bin/env python\nimport glob\nimport os\nimport os.path\nimport shutil\nimport socket\nimport struct\nimport sys\nimport time\nimport subprocess\nimport warnings\nimport re\nimport types\nimport tarfile\nimport tempfile\n\nimport numpy as np\nimport psr_utils\nimport presto\nimport sifting\n\nimport datafile\nimport config.searching\nimport config.processing\n\n# Sifting specific parameters (don't touch without good reason!)\n# incoherent power threshold (sigma)\nsifting.sigma_threshold = config.searching.sifting_sigma_threshold \n# coherent power threshold\nsifting.c_pow_threshold = config.searching.sifting_c_pow_threshold \n# Fourier bin tolerence for candidate equivalence\nsifting.r_err           = config.searching.sifting_r_err    \n# Shortest period candidates to consider (s)\nsifting.short_period    = config.searching.sifting_short_period \n# Longest period candidates to consider (s)\nsifting.long_period     = config.searching.sifting_long_period   \n# Power required in at least one harmonic\nsifting.harm_pow_cutoff = config.searching.sifting_harm_pow_cutoff\n\ndebug = 0\n\n\ndef get_baryv(ra, dec, mjd, T, obs=\"AO\"):\n   \"\"\"\n   get_baryv(ra, dec, mjd, T):\n     Determine the average barycentric velocity towards 'ra', 'dec'\n       during an observation from 'obs'.  The RA and DEC are in the\n       standard string format (i.e. 'hh:mm:ss.ssss' and \n       'dd:mm:ss.ssss'). 'T' is in sec and 'mjd' is (of course) in MJD.\n   \"\"\"\n   tts = psr_utils.span(mjd, mjd+T/86400.0, 100)\n   nn = len(tts)\n   bts = np.zeros(nn, dtype=np.float64)\n   vel = np.zeros(nn, dtype=np.float64)\n   presto.barycenter(tts, bts, vel, nn, ra, dec, obs, \"DE200\")\n   avgvel = np.add.reduce(vel)/nn\n   return avgvel\n\ndef find_masked_fraction(obs):\n    \"\"\"\n    find_masked_fraction(obs):\n        Parse the output file from an rfifind run and return the\n            fraction of the data that was suggested to be masked.\n    \"\"\"\n    rfifind_out = obs.basefilenm + \"_rfifind.out\"\n    for line in open(rfifind_out):\n        if \"Number of  bad   intervals\" in line:\n            return float(line.split(\"(\")[1].split(\"%\")[0])/100.0\n    # If there is a problem reading the file, return 100%\n    return 100.0\n\ndef get_all_subdms(ddplans):\n    \"\"\"\n    get_all_subdms(ddplans):\n        Return a sorted array of the subdms from the list of ddplans.\n    \"\"\"\n    subdmlist = []\n    for ddplan in ddplans:\n        subdmlist += [float(x) for x in ddplan.subdmlist]\n    subdmlist.sort()\n    subdmlist = np.asarray(subdmlist)\n    return subdmlist\n\n\ndef find_closest_subbands(obs, subdms, DM):\n    \"\"\"\n    find_closest_subbands(obs, subdms, DM):\n        Return the basename of the closest set of subbands to DM\n        given an obs_info class and a sorted array of the subdms.\n    \"\"\"\n    subdm = subdms[np.fabs(subdms - DM).argmin()]\n    return \"obs.tempdir/%s_DM%.2f.sub[0-6]*\"%(obs.basefilenm, subdm)\n\n\ndef timed_execute(cmd, stdout=None, stderr=sys.stderr): \n    \"\"\"\n    timed_execute(cmd, stdout=None, stderr=sys.stderr):\n        Execute the command 'cmd' after logging the command\n            to STDOUT.  Return the wall-clock amount of time\n            the command took to execute.\n\n            Output standard output to 'stdout' and standard\n            error to 'stderr'. Both are strings containing filenames.\n            If values are None, the out/err streams are not recorded.\n            By default stdout is None and stderr is combined with stdout.\n    \"\"\"\n    # Log command to stdout\n    sys.stdout.write(\"\\n'\"+cmd+\"'\\n\")\n    sys.stdout.flush()\n\n    stdoutfile = False\n    stderrfile = False\n    if type(stdout) == types.StringType:\n        stdout = open(stdout, 'w')\n        stdoutfile = True\n    if type(stderr) == types.StringType:\n        stderr = open(stderr, 'w')\n        stderrfile = True\n    \n    # Run (and time) the command. Check for errors.\n    start = time.time()\n    retcode = subprocess.call(cmd, shell=True, stdout=stdout, stderr=stderr)\n    if retcode < 0:\n        raise PrestoError(\"Execution of command (%s) terminated by signal (%s)!\" % \\\n                                (cmd, -retcode))\n    elif retcode > 0:\n        raise PrestoError(\"Execution of command (%s) failed with status (%s)!\" % \\\n                                (cmd, retcode))\n    else:\n        # Exit code is 0, which is \"Success\". Do nothing.\n        pass\n    end = time.time()\n    \n    # Close file objects, if any\n    if stdoutfile:\n        stdout.close()\n    if stderrfile:\n        stderr.close()\n    return end - start\n\n\ndef get_folding_command(cand, obs):\n    \"\"\"\n    get_folding_command(cand, obs):\n        Return a command for prepfold for folding the subbands using\n            an obs_info instance, and a candidate instance that \n            describes the observations and searches.\n    \"\"\"\n    # Folding rules are based on the facts that we want:\n    #   1.  Between 24 and 200 bins in the profiles\n    #   2.  For most candidates, we want to search length = 101 p/pd/DM cubes\n    #       (The side of the cube is always 2*M*N+1 where M is the \"factor\",\n    #       either -npfact (for p and pd) or -ndmfact, and N is the number of bins\n    #       in the profile).  A search of 101^3 points is pretty fast.\n    #   3.  For slow pulsars (where N=100 or 200), since we'll have to search\n    #       many points, we'll use fewer intervals in time (-npart 30)\n    #   4.  For the slowest pulsars, in order to avoid RFI, we'll\n    #       not search in period-derivative.\n    zmax = cand.filename.split(\"_\")[-1]\n    outfilenm = obs.basefilenm+\"_DM%s_Z%s\"%(cand.DMstr, zmax)\n\n    # Note:  the following calculations should probably only be done once,\n    #        but in general, these calculation are effectively instantaneous\n    #        compared to the folding itself\n    if config.searching.fold_rawdata:\n        # Fold raw data\n        foldfiles = obs.filenmstr\n        mask = \"-mask %s\" % (obs.basefilenm + \"_rfifind.mask\")\n    else:\n        if config.searching.use_subbands:\n            # Fold the subbands\n            subdms = get_all_subdms(obs.ddplans)\n            subfiles = find_closest_subbands(obs, subdms, cand.DM)\n            foldfiles = subfiles\n            mask = \"\"\n        else:  # Folding the downsampled PSRFITS files instead\n            #\n            # TODO: Apply mask!?\n            #\n            mask = \"\"\n            hidms = [x.lodm for x in obs.ddplans[1:]] + [2000]\n            dfacts = [x.downsamp for x in obs.ddplans]\n            for hidm, dfact in zip(hidms, dfacts):\n                if cand.DM < hidm:\n                    downsamp = dfact\n                    break\n            if downsamp==1:\n                foldfiles = obs.filenmstr\n            else:\n                dsfiles = [] \n                for f in obs.filenames:\n                    fbase = f.rstrip(\".fits\")\n                    dsfiles.append(fbase+\"_DS%d.fits\"%downsamp)\n                foldfiles = ' '.join(dsfiles)\n    p = 1.0 / cand.f\n    if p < 0.002:\n        Mp, Mdm, N = 2, 2, 24\n        npart = 50\n        otheropts = \"-ndmfact 3\"\n    elif p < 0.05:\n        Mp, Mdm, N = 2, 1, 50\n        npart = 40\n        otheropts = \"-pstep 1 -pdstep 2 -dmstep 3\"\n    elif p < 0.5:\n        Mp, Mdm, N = 1, 1, 100\n        npart = 30\n        otheropts = \"-pstep 1 -pdstep 2 -dmstep 1\"\n    else:\n        Mp, Mdm, N = 1, 1, 200\n        npart = 30\n        otheropts = \"-nopdsearch -pstep 1 -pdstep 2 -dmstep 1\"\n\n    # If prepfold is instructed to use more subbands than there are rows in the PSRFITS file\n    # it doesn't use any data when folding since the amount of data for each part is\n    # shorter than the PSRFITS row. However, PRESTO doesn't break up rows.\n    # Set npart to the number of rows in the PSRFITS file.\n    if npart > obs.numrows:\n        npart = obs.numrows\n\n    # Get number of subbands to use\n    if obs.backend.lower() == 'pdev':\n        nsub = 96\n    else:\n        nsub = 64\n    return \"prepfold -noxwin -accelcand %d -accelfile %s.cand -dm %.2f -o %s \" \\\n                \"-nsub %d -npart %d %s -n %d -npfact %d -ndmfact %d %s %s\" % \\\n           (cand.candnum, cand.filename, cand.DM, outfilenm, nsub,\n            npart, otheropts, N, Mp, Mdm, mask, foldfiles)\n\n\nclass obs_info:\n    \"\"\"\n    class obs_info(filenms, resultsdir)\n        A class describing the observation and the analysis.\n    \"\"\"\n    def __init__(self, filenms, resultsdir):\n        # Where to dump all the results\n        self.outputdir = resultsdir\n        \n        self.filenms = filenms\n        self.filenmstr = ' '.join(self.filenms)\n        self.basefilenm = os.path.split(filenms[0])[1].rstrip(\".fits\")\n        print \"Read info from PSRFITS file\", self.filenms\n        # Read info from PSRFITS file\n        data = datafile.autogen_dataobj(self.filenms)\n        # Correct positions in data file headers for WappPsrfitsData\n        print \"Updating positions\"\n        if isinstance(data, datafile.WappPsrfitsData):\n            data.update_positions()\n        print \"Positions updated\"\n        spec_info = data.specinfo\n        self.backend = spec_info.backend\n        self.MJD = spec_info.start_MJD[0]\n        self.ra_string = spec_info.ra_str\n        self.dec_string = spec_info.dec_str\n        self.orig_N = spec_info.N\n        self.dt = spec_info.dt # in sec\n        self.BW = spec_info.BW\n        self.orig_T = spec_info.T\n        # Downsampling is catered to the number of samples per row.\n        # self.N = psr_utils.choose_N(self.orig_N)\n        self.N = self.orig_N\n        self.T = self.N * self.dt\n        self.nchan = spec_info.num_channels\n        self.samp_per_row = spec_info.spectra_per_subint\n        self.fctr = spec_info.fctr\n        self.numrows = np.sum(spec_info.num_subint) \n       \n        # Determine the average barycentric velocity of the observation\n        print \"Determine the average barycentric velocity of the observation\"\n#        self.baryv = get_baryv(self.ra_string, self.dec_string,\n#                               self.MJD, self.T, obs=\"AO\")\n        self.baryv = 0.0\n        # Figure out which host we are processing on\n        print \"Figure out which host we are processing on\"\n        self.hostname = socket.gethostname()\n        # The fraction of the data recommended to be masked by rfifind\n        self.masked_fraction = 0.0\n        # The number of candidates folded\n        self.num_cands_folded = 0\n        # Initialize our timers\n        self.rfifind_time = 0.0\n        self.downsample_time = 0.0\n        self.subbanding_time = 0.0\n        self.dedispersing_time = 0.0\n        self.FFT_time = 0.0\n        self.lo_accelsearch_time = 0.0\n        self.hi_accelsearch_time = 0.0\n        self.singlepulse_time = 0.0\n        self.modindex_time = 0.0    #Added by LGS 30Mar12\n        self.sifting_time = 0.0\n        self.folding_time = 0.0\n        self.total_time = 0.0\n        # Inialize some candidate counters\n        self.num_sifted_cands = 0\n        self.num_folded_cands = 0\n        self.num_single_cands = 0\n        # Set dedispersion plan\n        print \"Set dedispersion plan\"\n        self.set_DDplan()\n\n    def set_DDplan(self):\n        \"\"\"Set the dedispersion plan.\n\n            The dedispersion plans are hardcoded and\n            depend on the backend data were recorded with.\n        \"\"\"\n        # Generate dedispersion plan\n        self.ddplans = []\n\n        # The following code will run the dedispersion planner on demand.\n        # Instead, dedispersion plans for WAPP and Mock data are hardcoded.\n        #\n        # import DDplan2b\n        # obs = DDplan2b.Observation(self.dt, self.fctr, self.BW, self.nchan, \\\n        #                             self.samp_per_row)\n        # plan = obs.gen_ddplan(config.searching.lodm, config.searching.hidm, \\\n        #                       config.searching.numsub, config.searching.resolution)\n        # plan.plot(fn=os.path.join(self.outputdir, self.basefilenm+\"_ddplan.ps\"))\n        # print plan\n        # for ddstep in plan.DDsteps:\n        #     self.ddplans.append(dedisp_plan(ddstep.loDM, ddstep.dDM, ddstep.DMs_per_prepsub, \\\n        #                    ddstep.numprepsub, ddstep.numsub, ddstep.downsamp))\n\n        if self.backend.lower() == 'pdev':\n            # The values here are:       lodm dmstep dms/call #calls #subbands downsamp\n            # This line added for debugging. Searches fewer DM so it goes faster\n            self.ddplans.append(dedisp_plan(   98.8,  0.1,    76,      1,     96,        1 ))\n#            self.ddplans.append(dedisp_plan(   0.0,  0.1,    76,     28,     96,        1 ))\n#            self.ddplans.append(dedisp_plan( 212.8,  0.3,    64,     12,     96,        2 ))\n#            self.ddplans.append(dedisp_plan( 443.2,  0.3,    76,      4,     96,        3 ))\n#            self.ddplans.append(dedisp_plan( 534.4,  0.5,    76,      9,     96,        5 ))\n#            self.ddplans.append(dedisp_plan( 876.4,  0.5,    76,      3,     96,        6 ))\n#            self.ddplans.append(dedisp_plan( 990.4,  1.0,    76,      10,     96,       10 ))\n#            self.ddplans.append(dedisp_plan(1750.4,  2.0,    72,      2,     96,       15 ))\n        elif self.backend.lower() == 'wapp':\n            # The values here are:       lodm dmstep dms/call #calls #subbands downsamp\n            self.ddplans.append(dedisp_plan(   0.0,  0.3,    76,      9,     96,        1 ))\n            self.ddplans.append(dedisp_plan( 205.2,  2.0,    76,      5,     96,        5 ))\n            self.ddplans.append(dedisp_plan( 965.2, 10.0,    76,      1,     96,       25 ))\n        else:\n            raise ValueError(\"No dediserpsion plan for unknown backend (%s)!\" % self.backend)\n        \n\n    def write_report(self, filenm):\n        report_file = open(filenm, \"w\")\n        report_file.write(\"---------------------------------------------------------\\n\")\n        report_file.write(\"Data (%s) were processed on %s\\n\" % \\\n                                (', '.join(self.filenms), self.hostname))\n        report_file.write(\"Ending UTC time:  %s\\n\"%(time.asctime(time.gmtime())))\n        report_file.write(\"Total wall time:  %.1f s (%.2f hrs)\\n\"%\\\n                          (self.total_time, self.total_time/3600.0))\n        report_file.write(\"Fraction of data masked:  %.2f%%\\n\"%\\\n                          (self.masked_fraction*100.0))\n        report_file.write(\"Number of candidates folded: %d\\n\"%\\\n                          self.num_cands_folded)\n        report_file.write(\"---------------------------------------------------------\\n\")\n        report_file.write(\"          rfifind time = %7.1f sec (%5.2f%%)\\n\"%\\\n                          (self.rfifind_time, self.rfifind_time/self.total_time*100.0))\n        if config.searching.use_subbands:\n            report_file.write(\"       subbanding time = %7.1f sec (%5.2f%%)\\n\"%\\\n                              (self.subbanding_time, self.subbanding_time/self.total_time*100.0))\n        else:\n            report_file.write(\"     downsampling time = %7.1f sec (%5.2f%%)\\n\"%\\\n                              (self.downsample_time, self.downsample_time/self.total_time*100.0))\n        report_file.write(\"     dedispersing time = %7.1f sec (%5.2f%%)\\n\"%\\\n                          (self.dedispersing_time, self.dedispersing_time/self.total_time*100.0))\n        report_file.write(\"     single-pulse time = %7.1f sec (%5.2f%%)\\n\"%\\\n                          (self.singlepulse_time, self.singlepulse_time/self.total_time*100.0))\n        report_file.write(\" modulation index time = %7.1f sec (%5.2f%%)\\n\"%\\\n                          (self.modindex_time, self.modindex_time/self.total_time*100.0))\n        report_file.write(\"              FFT time = %7.1f sec (%5.2f%%)\\n\"%\\\n                          (self.FFT_time, self.FFT_time/self.total_time*100.0))\n        report_file.write(\"   lo-accelsearch time = %7.1f sec (%5.2f%%)\\n\"%\\\n                          (self.lo_accelsearch_time, self.lo_accelsearch_time/self.total_time*100.0))\n        report_file.write(\"   hi-accelsearch time = %7.1f sec (%5.2f%%)\\n\"%\\\n                          (self.hi_accelsearch_time, self.hi_accelsearch_time/self.total_time*100.0))\n        report_file.write(\"          sifting time = %7.1f sec (%5.2f%%)\\n\"%\\\n                          (self.sifting_time, self.sifting_time/self.total_time*100.0))\n        report_file.write(\"          folding time = %7.1f sec (%5.2f%%)\\n\"%\\\n                          (self.folding_time, self.folding_time/self.total_time*100.0))\n        report_file.write(\"---------------------------------------------------------\\n\")\n        report_file.close()\n\nclass dedisp_plan:\n    \"\"\"\n    class dedisp_plan(lodm, dmstep, dmsperpass, numpasses, numsub, downsamp)\n        A class describing a de-dispersion plan for prepsubband in detail.\n    \"\"\"\n    def __init__(self, lodm, dmstep, dmsperpass, numpasses, numsub, downsamp):\n        self.lodm = float(lodm)\n        self.dmstep = float(dmstep)\n        self.dmsperpass = int(dmsperpass)\n        self.numpasses = int(numpasses)\n        self.numsub = int(numsub)\n        self.downsamp = int(downsamp)\n        # Downsample less for the subbands so that folding\n        # candidates is more acurate\n        #\n        # Turning this off because downsampling factors are not necessarily\n        # powers of 2 any more! Also, are we folding from raw data now?\n        # -- PL Nov. 26, 2010\n        #\n        self.sub_downsamp = self.downsamp\n        self.dd_downsamp = 1\n        # self.sub_downsamp = self.downsamp / 2\n        # if self.sub_downsamp==0: self.sub_downsamp = 1\n        # The total downsampling is:\n        #   self.downsamp = self.sub_downsamp * self.dd_downsamp\n\n        # if self.downsamp==1: self.dd_downsamp = 1\n        # else: self.dd_downsamp = 2\n        self.sub_dmstep = self.dmsperpass * self.dmstep\n        self.dmlist = []  # These are strings for comparison with filenames\n        self.subdmlist = []\n        for ii in range(self.numpasses):\n            self.subdmlist.append(\"%.2f\"%(self.lodm + (ii+0.5)*self.sub_dmstep))\n            lodm = self.lodm + ii * self.sub_dmstep\n            dmlist = [\"%.2f\"%dm for dm in \\\n                      np.arange(self.dmsperpass)*self.dmstep + lodm]\n            self.dmlist.append(dmlist)\n\n\ndef main(filenms, workdir, resultsdir):\n\n    # Change to the specified working directory\n    os.chdir(workdir)\n    print workdir\n    job = set_up_job(filenms, workdir, resultsdir)\n    \n    print \"\\nBeginning PALFA search of %s\" % (', '.join(job.filenms))\n    print \"UTC time is:  %s\"%(time.asctime(time.gmtime()))\n    print \"NOTE: This version of the pipeline has been modified by\"\n    print \"   Laura Spitler to do only the single pulse search and\"\n    print \"   also includes the calculation of the modulation index.\"\n    try:\n        search_job(job)\n    except:\n        print \"***********************ERRORS!************************\"\n        print \"  Search has been aborted due to errors encountered.\"\n        print \"  See error output for more information.\"\n        print \"******************************************************\"\n        raise\n    finally:\n        clean_up(job)\n\n        # And finish up\n        job.total_time = time.time() - job.total_time\n        print \"\\nFinished\"\n        print \"UTC time is:  %s\"%(time.asctime(time.gmtime()))\n\n        # Write the job report\n        # job.write_report(job.basefilenm+\".report\")\n        job.write_report(os.path.join(job.outputdir, job.basefilenm+\".report\"))\n\n    \ndef set_up_job(filenms, workdir, resultsdir):\n    \"\"\"Change to the working directory and set it up.\n        Create a obs_info instance, set it up and return it.\n    \"\"\"\n    # Get information on the observation and the job\n    print filenms\n    job = obs_info(filenms, resultsdir)\n    if job.T < config.searching.low_T_to_search:\n        raise PrestoError(\"The observation is too short to search. \" \\\n                            \"(%.2f s < %.2f s)\" % \\\n                            (job.T, config.searching.low_T_to_search))\n    job.total_time = time.time()\n\n    print \"Inside set_up_job for files: \", job.filenms    \n    # Make sure the output directory (and parent directories) exist\n    try:\n        os.makedirs(job.outputdir)\n    except: pass\n\n    job.workdir = workdir\n    # Create a directory to hold all the subbands\n    job.tempdir = tempfile.mkdtemp(suffix=\"_tmp\", prefix=job.basefilenm, \\\n                        dir=config.processing.base_tmp_dir)\n    \n    #####\n    # Print some info useful for debugging\n    print \"Initial contents of workdir (%s): \" % workdir\n    for fn in os.listdir(workdir):\n        print \"    %s\" % fn\n    print \"Initial contents of resultsdir (%s): \" % resultsdir\n    for fn in os.listdir(resultsdir):\n        print \"    %s\" % fn\n    print \"Initial contents of job.tempdir (%s): \" % job.tempdir\n    for fn in os.listdir(job.tempdir):\n        print \"    %s\" % fn\n    sys.stdout.flush()\n    #####\n\n    return job\n\n\ndef search_job(job):\n    \"\"\"Search the observation defined in the obs_info\n        instance 'job'.\n    \"\"\"\n    # Use whatever .zaplist is found in the current directory\n    zaplist = glob.glob(\"*.zaplist\")[0]\n    print \"Using %s as zaplist\" % zaplist\n    if config.searching.use_subbands and config.searching.fold_rawdata:\n        # make a directory to keep subbands so they can be used to fold later\n        try:\n            os.makedirs(os.path.join(job.workdir, 'subbands'))\n        except: pass\n\n    # rfifind the data file\n    cmd = \"rfifind %s -time %.17g -o %s %s\" % \\\n          (config.searching.datatype_flag, config.searching.rfifind_chunk_time, job.basefilenm,\n           job.filenmstr)\n    job.rfifind_time += timed_execute(cmd, stdout=\"%s_rfifind.out\" % job.basefilenm)\n    maskfilenm = job.basefilenm + \"_rfifind.mask\"\n    # Find the fraction that was suggested to be masked\n    # Note:  Should we stop processing if the fraction is\n    #        above some large value?  Maybe 30%?\n    job.masked_fraction = find_masked_fraction(job)\n    \n    # Iterate over the stages of the overall de-dispersion plan\n    dmstrs = []\n    for ddplan in job.ddplans:\n\n        # Iterate over the individual passes through the data file\n        for passnum in range(ddplan.numpasses):\n            subbasenm = \"%s_DM%s\"%(job.basefilenm, ddplan.subdmlist[passnum])\n\n            if config.searching.use_subbands:\n                try:\n                    os.makedirs(os.path.join(job.tempdir, 'subbands'))\n                except: pass\n    \n                # Create a set of subbands\n\t\t#LGS: -nobary flag added on 19Jan12\n                cmd = \"prepsubband %s -sub -noweights -noscales -nooffsets -subdm %s -downsamp %d -nsub %d -mask %s \" \\\n                        \"-o %s/subbands/%s %s\" % \\\n                        (config.searching.datatype_flag, ddplan.subdmlist[passnum], ddplan.sub_downsamp,\n                        ddplan.numsub, maskfilenm, job.tempdir, job.basefilenm,\n                        job.filenmstr)\n                job.subbanding_time += timed_execute(cmd, stdout=\"%s.subout\" % subbasenm)\n            \n                # Now de-disperse using the subbands\n\t\t#LGS: -nobary flag added on 19Jan12\n                cmd = \"prepsubband -noweights -noscales -nooffsets -lodm %.2f -dmstep %.2f -numdms %d -downsamp %d \" \\\n                        \"-nsub %d -numout %d -o %s/%s %s/subbands/%s.sub[0-9]*\" % \\\n                        (ddplan.lodm+passnum*ddplan.sub_dmstep, ddplan.dmstep,\n                        ddplan.dmsperpass, ddplan.dd_downsamp, ddplan.numsub,\n                        psr_utils.choose_N(job.orig_N/ddplan.downsamp),\n                        job.tempdir, job.basefilenm, job.tempdir, subbasenm)\n                job.dedispersing_time += timed_execute(cmd, stdout=\"%s.prepout\" % subbasenm)\n            \n            else:  # Not using subbands\n                cmd = \"prepsubband -mask %s -lodm %.2f -dmstep %.2f -numdms %d -downsamp %d \" \\\n                        \"-numout %d -o %s/%s %s\"%\\\n                        (maskfilenm, ddplan.lodm+passnum*ddplan.sub_dmstep, ddplan.dmstep,\n                        ddplan.dmsperpass, ddplan.dd_downsamp*ddplan.sub_downsamp, \n                        psr_utils.choose_N(job.orig_N/ddplan.downsamp),\n                        job.tempdir, job.basefilenm, job.filenmstr)\n                job.dedispersing_time += timed_execute(cmd)\n            \n            # Iterate over all the new DMs\n            for dmstr in ddplan.dmlist[passnum]:\n                dmstrs.append(dmstr)\n                basenm = os.path.join(job.tempdir, job.basefilenm+\"_DM\"+dmstr)\n                datnm = basenm+\".dat\"\n                fftnm = basenm+\".fft\"\n                infnm = basenm+\".inf\"\n\n                # Do the single-pulse search\n\t\t#LGS: Added processing speed option 19Jan12\n                #LGS: Added cluster search option 09Feb12\n                cmd = \"single_pulse_search.py %s %s %s -p -m %f -t %f %s\"%\\\n                      (config.searching.singlepulse_flag,\\\n                       config.searching.singlepulse_cluster,\\\n                       config.searching.singlepulse_speed,\\\n                       config.searching.singlepulse_maxwidth, \\\n                       config.searching.singlepulse_threshold, datnm)\n                job.singlepulse_time += timed_execute(cmd)\n                try:\n                    shutil.move(basenm+\".singlepulse\", job.workdir)\n                    if config.searching.singlepulse_cluster: shutil.move(basenm+\".cluster\", job.workdir)\n                except: pass\n\n                # Move the .inf files\n                try:\n                    shutil.move(infnm, job.workdir)\n                except: pass\n                # Remove the .dat and .fft files\n                try:\n                    os.remove(datnm)\n                except: pass\n\n            if config.searching.use_subbands:\n                if config.searching.fold_rawdata:\n                    # Subband files are no longer needed\n                    shutil.rmtree(os.path.join(job.tempdir, 'subbands'))\n                else:\n                    # Move subbands to workdir\n                    for sub in glob.glob(os.path.join(job.tempdir, 'subbands', \"*\")):\n                        shutil.move(sub, os.path.join(job.workdir, 'subbands'))\n\n    #Create the masked version of the tf-data\n    cmd = \"maskdata -nobary -noweights -nooffsets -noscales -mask %s -o junk.dat %s\" % (maskfilenm, job.filenmstr)\n    job.modindex_time += timed_execute(cmd)\n\n    #Consolidate all singlepulse files into a single file\n    cmd=\"awk '$1!=\\\"#\\\" {print}' %s > %s\" % (job.basefilenm+'_DM*.singlepulse', job.basefilenm+'_MF.sp')\n    job.modindex_time += timed_execute(cmd)\n\n    if config.searching.singlepulse_cluster:\n        cmd=\"awk '$1!=\\\"#\\\" {print $1, $9, $12, $13, $14, $6, $7, $8}' %s > %s\" % (job.basefilenm+'_DM*.cluster', job.basefilenm+'_CL.sp')\n        job.modindex_time += timed_execute(cmd) \n\n    #Calculate mod index\n    cmd=\"palfa_mi %s raw_data_with_mask.fits %s\" % (job.basefilenm+'_MF.sp', job.basefilenm+'_MF.mi')\n    job.modindex_time += timed_execute(cmd)\n\n    if config.searching.singlepulse_cluster:\n        cmd=\"palfa_mi %s raw_data_with_mask.fits %s\" % (job.basefilenm+'_CL.sp', job.basefilenm+'_CL.mi')\n        job.modindex_time += timed_execute(cmd)\n\n    # Make the single-pulse plots\n    basedmb = job.basefilenm+\"_DM\"\n    basedme = \".singlepulse \"\n    # The following will make plots for DM ranges:\n    #    0-110, 100-310, 300-1000+\n    dmglobs = [basedmb+\"[0-9].[0-9][0-9]\"+basedme +\n               basedmb+\"[0-9][0-9].[0-9][0-9]\"+basedme +\n               basedmb+\"10[0-9].[0-9][0-9]\"+basedme,\n               basedmb+\"[12][0-9][0-9].[0-9][0-9]\"+basedme +\n               basedmb+\"30[0-9].[0-9][0-9]\"+basedme,\n               basedmb+\"[3-9][0-9][0-9].[0-9][0-9]\"+basedme +\n               basedmb+\"1[0-9][0-9][0-9].[0-9][0-9]\"+basedme]\n    dmrangestrs = [\"0-110\", \"100-310\", \"300-1000+\"]\n    psname = job.basefilenm+\"_singlepulse.ps\"\n    for dmglob, dmrangestr in zip(dmglobs, dmrangestrs):\n        dmfiles = []\n        for dmg in dmglob.split():\n            dmfiles += glob.glob(dmg.strip())\n        # Check that there are matching files and they are not all empty\n        if dmfiles and sum([os.path.getsize(f) for f in dmfiles]):\n            cmd = 'single_pulse_search.py -t %f -g \"%s\"' % \\\n                (config.searching.singlepulse_plot_SNR, dmglob)\n            job.singlepulse_time += timed_execute(cmd)\n            os.rename(psname,\n                        job.basefilenm+\"_DMs%s_singlepulse.ps\" % dmrangestr)\n\n    # Make the cluster plots\n    if config.searching.singlepulse_cluster:\n        basedmb = job.basefilenm+\"_DM\"\n        basedme = \".cluster \"\n        # The following will make plots for DM ranges:\n        #    0-110, 100-310, 300-1000+\n        dmglobs = [basedmb+\"[0-9].[0-9][0-9]\"+basedme +\n               basedmb+\"[0-9][0-9].[0-9][0-9]\"+basedme +\n               basedmb+\"10[0-9].[0-9][0-9]\"+basedme,\n               basedmb+\"[12][0-9][0-9].[0-9][0-9]\"+basedme +\n               basedmb+\"30[0-9].[0-9][0-9]\"+basedme,\n               basedmb+\"[3-9][0-9][0-9].[0-9][0-9]\"+basedme +\n               basedmb+\"1[0-9][0-9][0-9].[0-9][0-9]\"+basedme]\n        dmrangestrs = [\"0-110\", \"100-310\", \"300-1000+\"]\n        psname = job.basefilenm+\"_cluster.ps\"\n        for dmglob, dmrangestr in zip(dmglobs, dmrangestrs):\n            dmfiles = []\n            for dmg in dmglob.split():\n                dmfiles += glob.glob(dmg.strip())\n            # Check that there are matching files and they are not all empty\n            if dmfiles and sum([os.path.getsize(f) for f in dmfiles]):\n                cmd = 'single_pulse_search.py --clust -t %f -g \"%s\"' % \\\n                    (config.searching.singlepulse_plot_SNR, dmglob)\n                job.singlepulse_time += timed_execute(cmd)\n                os.rename(psname,\n                        job.basefilenm+\"_DMs%s_cluster.ps\" % dmrangestr)\n\n    # Now step through the .ps files and convert them to .png and gzip them\n    psfiles = glob.glob(\"*.ps\")\n    for psfile in psfiles:\n        # The '[0]' appeneded to the end of psfile is to convert only the 1st page\n        timed_execute(\"convert -quality 90 %s -background white -flatten -rotate 90 +matte %s\" % \\\n                            (psfile+\"[0]\", psfile[:-3]+\".png\"))\n        timed_execute(\"gzip \"+psfile)\n    \n\ndef clean_up(job):\n    \"\"\"Clean up.\n        Tar results, copy them to the results director.\n    \"\"\"\n    # Dump search paramters to file\n    paramfn = open(\"search_params.txt\", 'w')\n    cfgs = config.searching_check.searching.configs\n    for key in cfgs:\n        paramfn.write(\"%-25s = %r\\n\" % (key, cfgs[key].value))\n    paramfn.close()\n\n    # Tar up the results files \n    tar_suffixes = [\"_singlepulse.tgz\",\n                    \"_inf.tgz\"]\n    tar_globs = [\"*.singlepulse\",\n                 \"*_DM[0-9]*.inf\"]\n    if config.searching.singlepulse_cluster == '--clust':\n        tar_suffixes.append(\"_cluster.tgz\")\n        tar_globs.append(\"*.cluster\")\n    print \"Tarring up results\"\n    for (tar_suffix, tar_glob) in zip(tar_suffixes, tar_globs):\n        print \"Opening tarball %s\" % (job.basefilenm+tar_suffix)\n        print \"Using glob %s\" % tar_glob\n        tf = tarfile.open(job.basefilenm+tar_suffix, \"w:gz\")\n        for infile in glob.glob(tar_glob):\n            print \"    Adding file %s\" % infile\n            tf.add(infile)\n            os.remove(infile)\n        tf.close()\n    sys.stdout.flush()\n    \n    # Copy all the important stuff to the output directory\n    resultglobs = [\"*rfifind.[bimors]*\", \"*.ps.gz\", \"*.tgz\", \"*.png\", \\\n                    \"*.zaplist\", \"search_params.txt\", \\\n                    \"*_merge.out\", \"*.mi\", \"*.sp\"]\n    \n    for resultglob in resultglobs:\n            for file in glob.glob(resultglob):\n                shutil.move(file, job.outputdir)\n\n    # Remove the tmp directory (in a tmpfs mount)\n    try:\n        shutil.rmtree(job.tempdir)\n    except: pass\n  \n\nclass PrestoError(Exception):\n    \"\"\"Error to throw when a PRESTO program returns with \n        a non-zero error code.\n    \"\"\"\n    pass\n\n\nif __name__ == \"__main__\":\n    # Arguments to the search program are\n    # sys.argv[3:] = data file names\n    # sys.argv[1] = working directory name\n    # sys.argv[2] = results directory name\n    workdir = sys.argv[1]\n    resultsdir = sys.argv[2]\n    filenms = sys.argv[3:]\n    main(filenms, workdir, resultsdir)\n", "meta": {"hexsha": "5425f5a3a9379dc367cc6950cbff7cbff3498631", "size": 32160, "ext": "py", "lang": "Python", "max_stars_repo_path": "pipeline2.0/lib/python/PALFA2_presto_search_noaccel.py", "max_stars_repo_name": "federatedcloud/transients_pipeline2", "max_stars_repo_head_hexsha": "5a919e3141c4721454584159b5d74bd17c07e377", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pipeline2.0/lib/python/PALFA2_presto_search_noaccel.py", "max_issues_repo_name": "federatedcloud/transients_pipeline2", "max_issues_repo_head_hexsha": "5a919e3141c4721454584159b5d74bd17c07e377", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pipeline2.0/lib/python/PALFA2_presto_search_noaccel.py", "max_forks_repo_name": "federatedcloud/transients_pipeline2", "max_forks_repo_head_hexsha": "5a919e3141c4721454584159b5d74bd17c07e377", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9946524064, "max_line_length": 138, "alphanum_fraction": 0.5808768657, "include": true, "reason": "import numpy", "num_tokens": 8745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.16327146291070216}}
{"text": "\"Implements Model\"\nimport numpy as np\nfrom .costed import CostedConstraintSet\nfrom ..nomials import Monomial\nfrom .prog_factories import _progify_fctry, _solve_fctry\nfrom .gp import GeometricProgram\nfrom .sgp import SequentialGeometricProgram\nfrom ..small_scripts import mag\nfrom ..tools.autosweep import autosweep_1d\nfrom ..exceptions import InvalidGPConstraint\nfrom .. import NamedVariables\nfrom ..tools.docstring import expected_unbounded\nfrom .set import add_meq_bounds\n\n\nclass Model(CostedConstraintSet):\n    \"\"\"Symbolic representation of an optimization problem.\n\n    The Model class is used both directly to create models with constants and\n    sweeps, and indirectly inherited to create custom model classes.\n\n    Arguments\n    ---------\n    cost : Posynomial (optional)\n        Defaults to `Monomial(1)`.\n\n    constraints : ConstraintSet or list of constraints (optional)\n        Defaults to an empty list.\n\n    substitutions : dict (optional)\n        This dictionary will be substituted into the problem before solving,\n        and also allows the declaration of sweeps and linked sweeps.\n\n    name : str (optional)\n        Allows \"naming\" a model in a way similar to inherited instances,\n        and overrides the inherited name if there is one.\n\n    Attributes with side effects\n    ----------------------------\n    `program` is set during a solve\n    `solution` is set at the end of a solve\n    \"\"\"\n\n    # name and num identify a model uniquely\n    name = None\n    num = None\n    # naming holds the name and num evironment in which a model was created\n    # this includes its own name and num, and those of models containing it\n    naming = None\n    program = None\n    solution = None\n\n    def __init__(self, cost=None, constraints=None, *args, **kwargs):\n        setup_vars = None\n        substitutions = kwargs.pop(\"substitutions\", None)  # reserved keyword\n        if hasattr(self, \"setup\"):\n            self.cost = None\n            with NamedVariables(self.__class__.__name__):\n                start_args = [cost, constraints]\n                args = tuple(a for a in start_args if a is not None) + args\n                cs = self.setup(*args, **kwargs)  # pylint: disable=no-member\n                if (isinstance(cs, tuple) and len(cs) == 2\n                        and isinstance(cs[1], dict)):\n                    constraints, substitutions = cs  # TODO: remove\n                else:\n                    constraints = cs\n                from .. import NAMEDVARS, MODELS, MODELNUMS\n                setup_vars = NAMEDVARS[tuple(MODELS), tuple(MODELNUMS)]\n                self.name, self.num = MODELS[-1], MODELNUMS[-1]\n                self.naming = (tuple(MODELS), tuple(MODELNUMS))\n            cost = self.cost  # TODO: remove\n        elif args and not substitutions:\n            # backwards compatibility: substitutions as third arg\n            substitutions, = args\n\n        cost = cost or Monomial(1)\n        constraints = constraints or []\n        if setup_vars:\n            # add all the vars created in .setup to the Model's varkeys\n            # even if they aren't used in any constraints\n            self.unique_varkeys = frozenset(v.key for v in setup_vars)\n        CostedConstraintSet.__init__(self, cost, constraints, substitutions)\n        if hasattr(self, \"setup\") and self.__class__.__doc__:\n            if ((\"Unbounded\" in self.__class__.__doc__ or\n                 \"Bounded by\" in self.__class__.__doc__) and\n                    \"SKIP VERIFICATION\" not in self.__class__.__doc__):\n                self.verify_docstring()\n\n    gp = _progify_fctry(GeometricProgram)\n    sp = _progify_fctry(SequentialGeometricProgram)\n    solve = _solve_fctry(_progify_fctry(GeometricProgram, \"solve\"))\n    localsolve = _solve_fctry(_progify_fctry(SequentialGeometricProgram,\n                                             \"localsolve\"))\n\n    def verify_docstring(self):  # pylint:disable=too-many-locals,too-many-branches,too-many-statements\n        \"Verifies docstring bounds are sufficient but not excessive.\"\n        err = \"while verifying %s:\\n\" % self.__class__.__name__\n        bounded, meq_bounded = self.bounded.copy(), self.meq_bounded.copy()\n        doc = self.__class__.__doc__\n        exp_unbounds = expected_unbounded(self, doc)\n        unexp_bounds = bounded.intersection(exp_unbounds)\n        if unexp_bounds:  # anything bounded that shouldn't be? err!\n            for direction in [\"lower\", \"upper\"]:\n                badvks = [v for v, d in unexp_bounds if d == direction]\n                if not badvks:\n                    continue\n                badvks = \", \".join(str(v) for v in badvks)\n                badvks += (\" were\" if len(badvks) > 1 else \" was\")\n                err += (\"    %s %s-bounded; expected %s-unbounded\"\n                        \"\\n\" % (badvks, direction, direction))\n            raise ValueError(err)\n        bounded.update(exp_unbounds)  # if not, treat expected as bounded\n        add_meq_bounds(bounded, meq_bounded)  # and add more meqs\n        self.missingbounds = {}  # now let's figure out what's missing\n        for bound in meq_bounded:  # first add the un-dealt-with meq bounds\n            for condition in list(meq_bounded[bound]):\n                meq_bounded[bound].remove(condition)\n                newcond = condition - bounded\n                if newcond and not any(c.issubset(newcond)\n                                       for c in meq_bounded[bound]):\n                    meq_bounded[bound].add(newcond)\n            bsets = \" or \".join(str(list(c)) for c in meq_bounded[bound])\n            self.missingbounds[bound] = (\", but would gain it from any of\"\n                                         \" these sets of bounds: \" + bsets)\n        # then add everything that's not in bounded\n        if len(bounded)+len(self.missingbounds) != 2*len(self.varkeys):\n            for key in self.varkeys:\n                for bound in (\"upper\", \"lower\"):\n                    if (key, bound) not in bounded:\n                        if (key, bound) not in self.missingbounds:\n                            self.missingbounds[(key, bound)] = \"\"\n        if self.missingbounds:  # anything unbounded? err!\n            boundstrs = \"\\n\".join(\"  %s has no %s bound%s\" % (v, b, x)\n                                  for (v, b), x\n                                  in self.missingbounds.items())\n            docstring = (\"To fix this add the following to %s's\"\n                         \" docstring (you may not need it all):\"\n                         \" \\n\" % self.__class__.__name__)\n            for direction in [\"upper\", \"lower\"]:\n                mb = [k for (k, b) in self.missingbounds if b == direction]\n                if mb:\n                    docstring += \"\"\"\n%s Unbounded\n---------------\n%s\n\"\"\" % (direction.title(), \", \".join(set(k.name for k in mb)))\n            raise ValueError(err + boundstrs + \"\\n\\n\" + docstring)\n\n    def as_gpconstr(self, x0):\n        \"Returns approximating constraint, keeping name and num\"\n        cs = CostedConstraintSet.as_gpconstr(self, x0)\n        cs.name, cs.num = self.name, self.num\n        return cs\n\n    def subconstr_str(self, excluded=None):\n        \"The collapsed appearance of a ConstraintBase\"\n        return \"%s_%s\" % (self.name, self.num) if self.name else None\n\n    def subconstr_latex(self, excluded=None):\n        \"The collapsed appearance of a ConstraintBase\"\n        return \"%s_{%s}\" % (self.name, self.num) if self.name else None\n\n    def sweep(self, sweeps, **solveargs):\n        \"Sweeps {var: values} pairs in sweeps. Returns swept solutions.\"\n        sols = []\n        for sweepvar, sweepvals in sweeps.items():\n            original_val = self.substitutions.get(sweepvar, None)\n            self.substitutions.update({sweepvar: ('sweep', sweepvals)})\n            try:\n                sols.append(self.solve(**solveargs))\n            except InvalidGPConstraint:\n                sols.append(self.localsolve(**solveargs))\n            if original_val:\n                self.substitutions[sweepvar] = original_val\n            else:\n                del self.substitutions[sweepvar]\n        if len(sols) == 1:\n            return sols[0]\n        return sols\n\n    def autosweep(self, sweeps, tol=0.01, samplepoints=100, **solveargs):\n        \"\"\"Autosweeps {var: (start, end)} pairs in sweeps to tol.\n\n        Returns swept and sampled solutions.\n        The original simplex tree can be accessed at sol.bst\n        \"\"\"\n        sols = []\n        for sweepvar, sweepvals in sweeps.items():\n            sweepvar = self[sweepvar].key\n            start, end = sweepvals\n            bst = autosweep_1d(self, tol, sweepvar, [start, end], **solveargs)\n            sols.append(bst.sample_at(np.linspace(start, end, samplepoints)))\n        if len(sols) == 1:\n            return sols[0]\n        return sols\n\n    # pylint: disable=too-many-locals,too-many-branches,too-many-statements\n    def debug(self, solver=None, verbosity=1, **solveargs):\n        \"\"\"Attempts to diagnose infeasible models.\n\n        If a model debugs but errors in a process_result call, debug again\n        with `process_results=False`\n        \"\"\"\n        from .relax import ConstantsRelaxed, ConstraintsRelaxed\n        from .bounded import Bounded\n\n        sol = None\n\n        solveargs[\"solver\"] = solver\n        solveargs[\"verbosity\"] = verbosity - 1\n        solveargs[\"process_result\"] = False\n\n        if verbosity:\n            print(\"< DEBUGGING >\")\n            print(\"> Trying with bounded variables and relaxed constants:\")\n\n        bounded = Bounded(self)\n        if self.substitutions:\n            constsrelaxed = ConstantsRelaxed(bounded)\n            feas = Model(constsrelaxed.relaxvars.prod()**30 * self.cost,\n                         constsrelaxed)\n            # NOTE: It hasn't yet been seen but might be possible that\n            #       the self.cost component above could cause infeasibility\n        else:\n            feas = Model(self.cost, bounded)\n\n        try:\n            try:\n                sol = feas.solve(**solveargs)\n            except InvalidGPConstraint:\n                sol = feas.localsolve(**solveargs)\n            sol[\"boundedness\"] = bounded.check_boundaries(sol)\n            if self.substitutions:\n                relaxed = get_relaxed([sol(r) for r in constsrelaxed.relaxvars],\n                                      constsrelaxed.origvars,\n                                      min_return=0 if sol[\"boundedness\"] else 1)\n                if verbosity and relaxed:\n                    if sol[\"boundedness\"]:\n                        print(\"and these constants relaxed:\")\n                    else:\n                        print(\"\\nSolves with these constants relaxed:\")\n                    for (_, orig) in relaxed:\n                        print(\"  %s: relaxed from %-.4g to %-.4g\"\n                              % (orig, mag(constsrelaxed.constants[orig.key]),\n                                 mag(sol(orig))))\n                    print\n            if verbosity:\n                print(\">> Success!\")\n        except (ValueError, RuntimeWarning):\n            if verbosity:\n                print(\">> Failure.\")\n                print(\"> Trying with relaxed constraints:\")\n\n            try:\n                constrsrelaxed = ConstraintsRelaxed(self)\n                feas = Model(constrsrelaxed.relaxvars.prod()**30 * self.cost,\n                             constrsrelaxed)\n                try:\n                    sol = feas.solve(**solveargs)\n                except InvalidGPConstraint:\n                    sol = feas.localsolve(**solveargs)\n                relaxed = get_relaxed(sol(constrsrelaxed.relaxvars),\n                                      range(len(feas[0][0])))\n                if verbosity and relaxed:\n                    print(\"\\nSolves with these constraints relaxed:\")\n                    for relaxval, i in relaxed:\n                        constraint = feas[0][0][i][0]\n                        # substitutions of the final relax value\n                        conleft = constraint.left.sub(\n                            {constrsrelaxed.relaxvars[i]: relaxval})\n                        conright = constraint.right.sub(\n                            {constrsrelaxed.relaxvars[i]: relaxval})\n                        origconstraint = constrsrelaxed.origconstrs[i]\n                        relax_percent = \"%i%%\" % (0.5+(relaxval-1)*100)\n                        print(\" %3i: %5s relaxed, from %s %s %s \\n\"\n                              \"                     to %s %s %s \"\n                              % (i, relax_percent, origconstraint.left,\n                                 origconstraint.oper, origconstraint.right,\n                                 conleft, constraint.oper, conright))\n                if verbosity:\n                    print(\"\\n>> Success!\")\n            except (ValueError, RuntimeWarning):\n                if verbosity:\n                    print(\">> Failure\")\n        if verbosity:\n            print\n        return sol\n\n\ndef get_relaxed(relaxvals, mapped_list, min_return=1):\n    \"Determines which relaxvars are considered 'relaxed'\"\n    sortrelaxed = sorted(zip(relaxvals, mapped_list), key=lambda x: x[0],\n                         reverse=True)\n    # arbitrarily 1.01 is the min that counts as \"relaxed\"\n    mostrelaxed = max(sortrelaxed[0][0], 1.01)\n    for i, (val, _) in enumerate(sortrelaxed):\n        if i >= min_return and val <= 1.01 and (val-1) <= (mostrelaxed-1)/10:\n            return sortrelaxed[:i]\n    return sortrelaxed\n", "meta": {"hexsha": "4ded64ac263c19d444ce6c827c5c7d360de6e687", "size": 13448, "ext": "py", "lang": "Python", "max_stars_repo_path": "gpkit/gpkit/constraints/model.py", "max_stars_repo_name": "UCLA-StarAI/LearnFairNB", "max_stars_repo_head_hexsha": "f922d885399955737bd9f16a104f700004cd3846", "max_stars_repo_licenses": ["Fair"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-07-07T17:29:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-20T18:52:28.000Z", "max_issues_repo_path": "gpkit/gpkit/constraints/model.py", "max_issues_repo_name": "UCLA-StarAI/LearnFairNB", "max_issues_repo_head_hexsha": "f922d885399955737bd9f16a104f700004cd3846", "max_issues_repo_licenses": ["Fair"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-11-23T22:26:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-23T22:26:05.000Z", "max_forks_repo_path": "gpkit/gpkit/constraints/model.py", "max_forks_repo_name": "UCLA-StarAI/LearnFairNB", "max_forks_repo_head_hexsha": "f922d885399955737bd9f16a104f700004cd3846", "max_forks_repo_licenses": ["Fair"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8266666667, "max_line_length": 103, "alphanum_fraction": 0.5630577037, "include": true, "reason": "import numpy", "num_tokens": 2977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.30074558520860073, "lm_q1q2_score": 0.16326373578597742}}
{"text": "'''\nArtifact detection on MEG data.\n\nTODO: Update doc.\n\nFor now\n'''\nimport glob\nimport logging\n\nimport mne\nimport numpy as np\nimport pandas as pd\n\nfrom .tools import hilbert\n\n\ndef annotate_blinks(raw, ch_mapping={'x': 'UADC002-3705', 'y': 'UADC003-3705', 'p': 'UADC004-3705'}):\n    '''\n    Detect blinks and annotate as bad blinks\n    '''\n    logging.info('Annotating blinks artifacts')\n    x, y, p = eye_voltage2gaze(raw, ch_mapping=ch_mapping)\n    xpos, ypos = x.ravel() / ppd(), y.ravel() / ppd()\n    sc = saccade_detection(xpos, ypos, threshold=10, acc_thresh=2000, Hz=1200)\n    blinks, scfilt = blink_detection(xpos, ypos, sc)\n    if len(blinks) == 0:\n        return None\n    blink_onsets = raw.times[blinks[:, 0]]\n    blink_durations = raw.times[blinks[:, 1]] - raw.times[blinks[:, 0]]\n    return mne.Annotations(blink_onsets, blink_durations, 'bad blinks')\n\n\ndef annotate_muscle(raw, cutoff=10):\n    logging.info('Annotating muscle artifacts')\n    try:\n        arts, z = detect_muscle(raw.copy(), cutoff=cutoff)\n    except MemoryError:\n        print('Memory Error detected:', raw)\n        raise RuntimeError(\n            'Memory error detected in annotate muscle: ' + raw.info['filename'])\n\n    annotations = None\n    if len(arts) > 0:\n        annotations = mne.Annotations(arts[:, 0],\n                                      arts[:, 1], 'bad muscle')\n    return annotations, z\n\n\ndef annotate_cars(raw, cutoff=4.0, der_cutoff=7.):\n    logging.info('Annotating car artifacts')\n    arts, z, d = detect_cars(raw.copy(), cutoff=cutoff, der_cutoff=der_cutoff)\n    annotations = None\n    if len(arts) > 0:\n        annotations = mne.Annotations(arts[:, 0], arts[:, 1], 'bad car')\n    return annotations, z, d\n\n\ndef annotate_jumps(raw, cutoff=25, allowed_before_bad=np.inf):\n    logging.info('Annotating jump artifacts')\n    arts, z, jumps_per_channel = detect_jumps(raw.copy(), cutoff=cutoff)\n    # Need to check for jumps_per_channel\n    bads = [k for k, v in jumps_per_channel.items() if v >\n            allowed_before_bad]\n    arts = [arts[k] for k, v in jumps_per_channel.items() if v <=\n            allowed_before_bad]\n\n    if len(bads) > 0:\n        if 'bads' in raw.info.keys():\n            raw.info['bads'].extend(bads)\n        else:\n            raw.info['bads'] = bads\n    a = []\n    for k in arts:\n        if len(k) is not 0:\n            a.extend(k)\n    arts = np.array(a)\n    annotations = None\n    try:\n        if len(arts) > 0:\n            annotations = mne.Annotations(arts[:, 0], arts[:, 1], 'bad jump')\n    except IndexError:\n        pass\n    return raw, annotations, z, jumps_per_channel\n\n\ndef detect_cars(raw, cutoff=3.5, der_cutoff=5.0, frequency_band=(None, 1)):\n    '''\n    Detect cars artifacts on blocks and ignore intermediate data.\n\n    This works analagously to the fieldtrip detect artifact routine.\n\n    Data epochs that are already marked as bad by the annotations in raw will be\n    excluded for computation of mean and std.\n    '''\n\n    logging.info('Detecting car events with cutoff %i' % cutoff)\n    if not hasattr(raw, '_data'):\n        logging.info('Loading data for car artifact detection')\n        raw.load_data()\n    raw.pick_channels([x for x in raw.ch_names if x.startswith('M')])\n    raw.filter(l_freq=None, h_freq=1)\n    hilb = hilbert(raw._data)\n    del raw._data\n    hilb = np.abs(hilb).astype(float)\n\n    # Compute IGR and median\n    Qs = np.percentile(hilb, [10, 50, 90], axis=1)\n    IQR = Qs[2, :] - Qs[0, :]\n    m = Qs[1, :]\n    zh = ((((hilb - m[:, np.newaxis]) / IQR[:, np.newaxis]))**2).mean(0)\n\n    # Normalize zh to have 80 between 0 an 1\n    q80 = np.percentile(zh, [80])\n    zh = zh / q80\n\n    # Compute derivative of zh\n    d = np.concatenate(([0], np.diff(zh)))\n    # Normalize to have 80 between -1 and 1\n    d = d / np.diff(np.percentile(d, [10, 80]))\n    d[:int(raw.info['sfreq'])] = 0\n    d[-int(raw.info['sfreq']):] = 0\n\n    # Compute artifact borders\n    art_borders = np.where(np.diff(np.concatenate([[0], zh > cutoff, [0]])))[0]\n    artifacts = []\n    for start, end in zip(art_borders[0::2], art_borders[1::2]):\n        onset_t = max((start - 1) - int(2.5 * raw.info['sfreq']), 0)\n        end_t = min((end) + int(2.5 * raw.info['sfreq']), len(zh))\n        # Check for derivative\n        if d[onset_t:end_t].min() < -der_cutoff and d[onset_t:end_t].max() > der_cutoff:\n            onset_t /= raw.info['sfreq']\n            end_t /= raw.info['sfreq']\n            duration = end_t - onset_t\n            artifacts.append((onset_t, duration))\n    return np.array(artifacts), zh, d\n\n\ndef detect_muscle(raw, cutoff=10, frequency_band=(110, 140)):\n    '''\n    Detect muscle artifacts on blocks and ignore intermediate data.\n\n    This works analagously to the fieldtrip detect artifact routine.\n\n    Data epochs that are already marked as bad by the annotations in raw will be\n    excluded for computation of mean and std.\n    '''\n\n    logging.info('Detecting muscle events with cutoff %i' % cutoff)\n    if not hasattr(raw, '_data'):\n        logging.info('Loading data for muscle artifact detection')\n        raw.load_data()\n    raw.pick_channels([x for x in raw.ch_names if x.startswith('M')])\n\n    # filt = mne.filter.band_pass_filter(raw._data, raw.info['sfreq'],\n    #                                   frequency_band[0], frequency_band[1],  method='iir',\n    #                                   iir_params = dict(order=9, ftype='butter'),\n    #                                   copy=False)\n    filt = mne.filter.filter_data(raw._data, raw.info['sfreq'],\n                                  l_freq=frequency_band[\n                                      0], h_freq=frequency_band[1],  method='iir',\n                                  iir_params=dict(order=9, ftype='butter'),\n                                  copy=False)\n\n    hilb = abs(hilbert(filt)).astype(float)\n    del filt\n    # Compute IGR and median\n    Qs = np.percentile(hilb, [10, 50, 90], axis=1)\n    IQR = Qs[2, :] - Qs[0, :]\n    m = Qs[1, :]\n    zh = ((((hilb - m[:, np.newaxis]) / IQR[:, np.newaxis]))**2).mean(0)\n\n    # Normalize zh to have 80 between 0 an 1\n    q80 = np.percentile(zh, [80])\n    zh = zh / q80\n\n    art_borders = np.where(np.diff(np.concatenate([[0], zh > cutoff, [0]])))[0]\n\n    artifacts = []\n    for start, end in zip(art_borders[0::2], art_borders[1::2]):\n        artifacts.append((\n                         ((start - 1) / raw.info['sfreq']) - 0.2,\n                         ((end - start) / raw.info['sfreq']) + 0.2,\n                         ))\n    return np.array(artifacts), zh\n\n\ndef detect_jumps(raw, cutoff=25):\n    '''\n    Detect jumps by convolving with a jump detection filter.\n    '''\n    logging.info('Detecting muscle events with cutoff %i' % cutoff)\n    if not hasattr(raw, '_data'):\n        logging.info('Loading data for muscle artifact detection')\n        raw.load_data()\n    raw.pick_channels([x for x in raw.ch_names if x.startswith('M')])\n    #filt = mne.filter.low_pass_filter(raw._data, raw.info['sfreq'], 1)\n    filt = mne.filter.filter_data(\n        raw._data, raw.info['sfreq'], l_freq=None, h_freq=1)\n\n    jump_kernel = (np.array([1] * 50),\n                   [0, 0],\n                   np.array([-1] * 50))\n    jump_kernel = np.concatenate(jump_kernel)\n    filt = 0 * raw._data.copy()\n    for i in range(filt.shape[0]):\n        filt[i, :] = np.convolve(\n            raw._data[i, :], jump_kernel, mode='same') - filt[i, :]\n        filt[i, :int(len(jump_kernel) / 2)] = 0\n        filt[i, -int(len(jump_kernel) / 2):] = 0\n\n    # Compute IGR and median\n    Qs = np.percentile(filt, [10, 50, 90], axis=1)\n    IQR = Qs[2, :] - Qs[0, :]\n    m = Qs[1, :]\n    filt = (((filt - m[:, np.newaxis]) / IQR[:, np.newaxis]))**2\n    # Need to keep information about channels here.\n\n    artifacts = {}\n    channel_count = {}\n    for i, zh in enumerate(filt):\n        artifacts[raw.ch_names[i]] = []\n        art_borders = np.where(\n            np.diff(np.concatenate([[0], zh > cutoff, [0]])))[0]\n        channel_count[raw.ch_names[i]] = 0\n        for start, end in zip(art_borders[0::2], art_borders[1::2]):\n            artifacts[raw.ch_names[i]].append(\n                ((start - 1) / raw.info['sfreq'], (end - start) / raw.info['sfreq']))\n            channel_count[raw.ch_names[i]] += 1\n    return artifacts, zh, channel_count\n\n\ndef eye_voltage2gaze(raw, ranges=(-5, 5), screen_x=(0, 1920),\n                     screen_y=(0, 1080),\n                     ch_mapping={'x': 'UADC002-3705', 'y': 'UADC003-3705', 'p': 'UADC004-3705'}):\n    '''\n    Convert analog output of EyeLink 1000+ to gaze coordinates.\n    '''\n    minvoltage, maxvoltage = ranges\n    maxrange, minrange = 1., 0.\n    screenright, screenleft = screen_x\n    screenbottom, screentop = screen_y\n\n    idx = np.where(np.array(raw.ch_names) == ch_mapping['x'])[0][0]\n    R = (raw[idx, :][0] - minvoltage) / (maxvoltage - minvoltage)\n    S = R * (maxrange - minrange) + minrange\n    x = S * (screenright - screenleft + 1) + screenleft\n\n    idy = np.where(np.array(raw.ch_names) == ch_mapping['y'])[0][0]\n    R = (raw[idy, :][0] - minvoltage) / (maxvoltage - minvoltage)\n    S = R * (maxrange - minrange) + minrange\n    y = S * (screenbottom - screentop + 1) + screentop\n\n    idp = np.where(np.array(raw.ch_names) == ch_mapping['p'])[0][0]\n    p = raw[idp, :][0]\n    return x, y, p\n\n\ndef eye_voltage2gaze_epochs(epochs, ranges=(-5, 5), screen_x=(0, 1920),\n                            screen_y=(0, 1080),\n                            ch_mapping={'x': 'UADC002-3705', 'y': 'UADC003-3705', 'p': 'UADC004-3705'}):\n    '''\n    Convert analog output of EyeLink 1000+ to gaze coordinates.\n    '''\n    minvoltage, maxvoltage = ranges\n    maxrange, minrange = 1., 0.\n    screenright, screenleft = screen_x\n    screenbottom, screentop = screen_y\n\n    idx = np.where(np.array(epochs.ch_names) == ch_mapping['x'])[0][0]\n    R = (epochs._data[:, idx, :].squeeze() -\n         minvoltage) / (maxvoltage - minvoltage)\n    S = R * (maxrange - minrange) + minrange\n    x = S * (screenright - screenleft + 1) + screenleft\n\n    idy = np.where(np.array(epochs.ch_names) == ch_mapping['y'])[0][0]\n    R = (epochs._data[:, idy, :].squeeze() -\n         minvoltage) / (maxvoltage - minvoltage)\n    S = R * (maxrange - minrange) + minrange\n    y = S * (screenbottom - screentop + 1) + screentop\n\n    idp = np.where(np.array(epochs.ch_names) == ch_mapping['p'])[0][0]\n    p = epochs._data[:, idp:].squeeze()\n    return x, y, p\n\nvelocity_window_size = 3\n\n\ndef get_velocity(x, y, Hz):\n    '''\n    Compute velocity of eye-movements.\n\n    'x' and 'y' specify the x,y coordinates of gaze location. The function\n    assumes that the values in x,y are sampled continously at a rate specified\n    by 'Hz'.\n    '''\n    Hz = float(Hz)\n    distance = ((np.diff(x) ** 2) +\n                (np.diff(y) ** 2)) ** .5\n    distance = np.hstack(([distance[0]], distance))\n    win = np.ones((velocity_window_size)) / float(velocity_window_size)\n    velocity = np.convolve(distance, win, mode='same')\n    velocity = velocity / (velocity_window_size / Hz)\n    acceleration = np.diff(velocity) / (1. / Hz)\n    acceleration = np.abs(np.hstack(([acceleration[0]], acceleration)))\n    return velocity, acceleration\n\n\ndef saccade_detection(x, y, Hz=1200, threshold=30,\n                      acc_thresh=2000):\n    '''\n    Detect saccades in a stream of gaze location samples.\n\n    Coordinates of x,y are assumed to be in degrees.\n\n    Saccades are detect by a velocity/acceleration threshold approach.\n    A saccade starts when a) the velocity is above threshold, b) the\n    acceleration is above acc_thresh at least once during the interval\n    defined by the velocity threshold.\n    '''\n\n    velocity, acceleration = get_velocity(x, y, float(Hz))\n    saccades = (velocity > threshold)\n\n    borders = np.where(np.diff(saccades.astype(int)))[0] + 1\n    if velocity[1] > threshold:\n        borders = np.hstack(([0], borders))\n\n    saccade = 0 * np.ones(x.shape)\n\n    saccade_times = []\n    # Only count saccades when acceleration also surpasses threshold\n    for i, (start, end) in enumerate(zip(borders[0::2], borders[1::2])):\n        if np.sum(acceleration[start:end] > acc_thresh) >= 1:\n            saccade[start:end] = 1\n            saccade_times.append((start, end))\n\n    return np.array(saccade_times)\n\n\ndef microssacade_detection(x, y, VFAC):\n    '''\n    Microsaccade detection a la Engbert et al.\n    '''\n    if len(x) < 5:\n        return None\n    dt = 1 / 1200.\n    kernel = np.array([1., 1., 0., -1., -1.])\n    vx = np.convolve(x, kernel, mode='same') / (6 * dt)\n    vy = np.convolve(y, kernel, mode='same') / (6 * dt)\n    msdx = np.sqrt(np.median((vx - np.median(vx))**2))\n    msdy = np.sqrt(np.median((vy - np.median(vy))**2))\n    radiusx = VFAC * msdx\n    radiusy = VFAC * msdy\n    test = (vx / radiusx)**2 + (vy / radiusy)**2\n    borders = np.where(np.diff((test > 1).astype(int)))[0] + 1\n    if test[0] > 1:\n        borders = np.hstack(([0], borders))\n    if test[-1] > 1:\n        borders = np.hstack((borders, [len(x)]))\n\n    borders = borders.reshape(len(borders) / 2, 2)\n    return borders\n\n\ndef blink_detection(x, y, saccades):\n    '''\n    A blink is everything that is surrounded by two saccades and period in\n    between where the eye is off screen.\n    '''\n    rm_sac = (saccades[:, 0] * 0).astype(bool)\n    blinks = []\n    skipnext = False\n    for i, ((pss, pse), (nss, nse)) in enumerate(zip(saccades[:-1], saccades[1:])):\n        if skipnext:\n            skipnext = False\n            continue\n        xavg = x[pse:nss].mean()\n        yavg = y[pse:nss].mean()\n\n        if (xavg > 40) and (yavg > 20):\n            rm_sac[i:i + 2] = True\n            blinks.append((pss, nse))\n            skip_next = True\n\n    return np.array(blinks), saccades[~rm_sac, :]\n\n\ndef nan_bad_epochs(data, raw):\n    '''\n    Overwrite data with NANs for all epochs in the Nx3 artifacts matrix.\n    '''\n    Hz = raw.info['sfreq']\n    if raw.annotations is not None:\n        for start, duration, desc in zip(raw.annotations.onset,\n                                         raw.annotations.duration,\n                                         raw.annotations.description):\n            if not 'bad' in desc:\n                continue\n            start = int(start * Hz)\n            data[start:start + int(duration * Hz)] = nan\n    return data\n\n\ndef ppd(vieweing_distance=62.5, screen_width=38.0, x_resolution=1450):\n    '''\n    Compute pixels per degree for the current setup.\n    '''\n    o = np.tan(0.5 * np.pi / 180) * vieweing_distance\n    return 2 * o * x_resolution / screen_width\n\n\ndef combine_annotations(annotations):\n    '''\n    Add annotations to a raw object. Makes sure that old annotations are kept.\n    '''\n    if len(annotations) == 0:\n        return mne.Annotations(np.array([0]), np.array([0]), 'dummy')\n    elif len(annotations) == 1:\n        return annotations[0]\n    else:\n        old = annotations[0]\n        for new in annotations[1:]:\n            if new is None:\n                continue\n            orig_time = None\n            onsets = np.concatenate((old.onset, new.onset))\n            duration = np.concatenate((old.duration, new.duration))\n            descr = np.concatenate((old.description, new.description))\n            if old.orig_time is not None:\n                orig_time = np.concatenate((old.orig_time, new.orig_time))\n            old = mne.Annotations(onsets, duration, descr, orig_time)\n        return old\n\n\ndef concatenate_annotations(annotations, durations):\n    '''\n    Concatenat annotations for several consecutive raw objects that are to be\n    merged. Each annotation must come with one duration for the raw object that\n    it belongs to.\n\n    durations is in s.\n\n    TODO: This was because of a bug in pymne - which should have been fixed upstream by now.\n    '''\n    durations[0] = 0\n    onsets = np.concatenate([a.onset + (li)\n                             for a, li in zip(annotations, cumsum(durations))])\n    durations = np.concatenate([a.duration\n                                for a in annotations])\n    description = np.concatenate([a.description\n                                  for a in annotations])\n    return mne.Annotations(onsets, durations, description)\n", "meta": {"hexsha": "55e1cdef3cab7ed515fe90aaa966fc493b96e56f", "size": 16157, "ext": "py", "lang": "Python", "max_stars_repo_path": "source_reconstruct/pymeg/artifacts.py", "max_stars_repo_name": "DonnerLab/2021_Murphy_Adaptive-Circuit-Dynamics-Across-Human-Cortex", "max_stars_repo_head_hexsha": "3ab8dd323451173818f8572653bb88cc2c4f2665", "max_stars_repo_licenses": ["BSD-Source-Code"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-17T10:13:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T10:13:40.000Z", "max_issues_repo_path": "source_reconstruct/pymeg/artifacts.py", "max_issues_repo_name": "DonnerLab/2021_Murphy_Adaptive-Circuit-Dynamics-Across-Human-Cortex", "max_issues_repo_head_hexsha": "3ab8dd323451173818f8572653bb88cc2c4f2665", "max_issues_repo_licenses": ["BSD-Source-Code"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source_reconstruct/pymeg/artifacts.py", "max_forks_repo_name": "DonnerLab/2021_Murphy_Adaptive-Circuit-Dynamics-Across-Human-Cortex", "max_forks_repo_head_hexsha": "3ab8dd323451173818f8572653bb88cc2c4f2665", "max_forks_repo_licenses": ["BSD-Source-Code"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5881057269, "max_line_length": 104, "alphanum_fraction": 0.5886612614, "include": true, "reason": "import numpy", "num_tokens": 4501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.30074558520860073, "lm_q1q2_score": 0.16326373578597742}}
{"text": "import os, sys\nsys.path.append(os.getcwd())\n\nimport time\nimport functools\n\nimport numpy as np\nimport tensorflow as tf\nimport scipy.misc\n\nimport tflib as lib\nimport tflib.ops.linear\nimport tflib.ops.conv2d\nimport tflib.ops.batchnorm\nimport tflib.ops.deconv2d\nimport tflib.save_images\nimport tflib.celebA_64x64\nimport tflib.small_imagenet\nimport tflib.ops.layernorm\nimport tflib.plot\n\nFLAGS = tf.app.flags.FLAGS\n\n# Configurations\ntf.app.flags.DEFINE_string('mode', 'wgan-gp',\n                           \"loss function option. [wgan-gp | dcgan | wgan | lsgan]\")\ntf.app.flags.DEFINE_string('data_dir', 'data/celebA_64x64', \"data directory\")\ntf.app.flags.DEFINE_string('train_dir', 'train', \"image output direcotory\")\ntf.app.flags.DEFINE_string('summary_dir', 'summary', \"tensorboard summary directory\")\ntf.app.flags.DEFINE_integer('max_runtime', 20, \"maximum run time in min\")\ntf.app.flags.DEFINE_integer('max_iter', 500, \"maximum mini-batch iterations\")\ntf.app.flags.DEFINE_float('LAMBDA', 10., \"gradient penalty lambda parameter\")\ntf.app.flags.DEFINE_float('gen_l1_weight', 0.9, \"weight of L1 difference in generator loss\")\ntf.app.flags.DEFINE_integer('architecture', 0, \"index of architecture\")\n\n# Download 64x64 ImageNet at http://image-net.org/small/download.php and\n# fill in the path to the extracted files here!\nDATA_DIR = FLAGS.data_dir\nSUMMARY_DIR = FLAGS.summary_dir\nGEN_L1_WEIGHT = FLAGS.gen_l1_weight # Weighting factor for L1 difference in generator loss\nTRAIN_DIR = FLAGS.train_dir # Directory to output image\nMODE = FLAGS.mode # dcgan, wgan, wgan-gp, lsgan\nITERS = FLAGS.max_iter # How many iterations to train for\nLAMBDA = FLAGS.LAMBDA # Gradient penalty lambda hyperparameter\n\nif len(DATA_DIR) == 0:\n    raise Exception('Please specify path to data directory in gan_64x64.py!')\n\nDIM = 64 # Model dimensionality\nK = 4 # How much to downsample\nCRITIC_ITERS = 5 # How many iterations to train the critic for\nN_GPUS = 1 # Number of GPUs\nBATCH_SIZE = 16 # Batch size. Must be a multiple of N_GPUS\nINPUT_DIM = 16*16*3 # Number of pixels in each input\nOUTPUT_DIM = 64*64*3 # Number of pixels in each iamge\nDELETE_TRAIN_DIR=True\n\nlib.print_model_settings(locals().copy())\n\n# create summary dir\nif not tf.gfile.Exists(FLAGS.summary_dir):\n    tf.gfile.MakeDirs(FLAGS.summary_dir)\n\n# clean directory\nif DELETE_TRAIN_DIR:\n    if tf.gfile.Exists(FLAGS.train_dir):\n        tf.gfile.DeleteRecursively(FLAGS.train_dir)\n        tf.gfile.MakeDirs(FLAGS.train_dir)\n    tf.gfile.MakeDirs(FLAGS.train_dir)\n\n# architecture dictionary\ndef get_architectures():\n    ARCHITECTURE_TABLE = {\n        # Baseline (G: DCGAN, D: DCGAN)\n        0: (DCGANGenerator, DCGANDiscriminator),\n\n        # No BN and constant number of filts in G\n        1: (WGANPaper_CrippledDCGANGenerator, DCGANDiscriminator),\n\n        # 512-dim 4-layer ReLU MLP G\n        2: (FCGenerator, DCGANDiscriminator),\n\n        # No normalization anywhere\n        3: (functools.partial(DCGANGenerator, bn=False),\n            functools.partial(DCGANDiscriminator, bn=False)),\n\n        # Gated multiplicative nonlinearities everywhere\n        4: (MultiplicativeDCGANGenerator, MultiplicativeDCGANDiscriminator),\n\n        # tanh nonlinearities everywhere\n        5: (functools.partial(DCGANGenerator, bn=True, nonlinearity=tf.tanh),\n            functools.partial(DCGANDiscriminator, bn=True, nonlinearity=tf.tanh)),\n\n        # 101-layer ResNet G and D\n        6: (ResnetGenerator, ResnetDiscriminator)\n    }\n    return ARCHITECTURE_TABLE\n\ndef GeneratorAndDiscriminator():\n    \"\"\"\n    Choose which generator and discriminator architecture to use by\n    uncommenting one of these lines.\n    \"\"\"\n    table = get_architectures()\n    if FLAGS.architecture <= len(table):\n        return table[FLAGS.architecture]\n\n    raise Exception('You must choose an architecture!')\n\nDEVICES = ['/gpu:{}'.format(i) for i in range(N_GPUS)]\n\ndef LeakyReLU(x, alpha=0.2):\n    return tf.maximum(alpha*x, x)\n\ndef ReLULayer(name, n_in, n_out, inputs):\n    output = lib.ops.linear.Linear(name+'.Linear', n_in, n_out, inputs, initialization='he')\n    return tf.nn.relu(output)\n\ndef LeakyReLULayer(name, n_in, n_out, inputs):\n    output = lib.ops.linear.Linear(name+'.Linear', n_in, n_out, inputs, initialization='he')\n    return LeakyReLU(output)\n\ndef Batchnorm(name, axes, inputs):\n    if ('Discriminator' in name) and (MODE == 'wgan-gp'):\n        if axes != [0,2,3]:\n            raise Exception('Layernorm over non-standard axes is unsupported')\n        return lib.ops.layernorm.Layernorm(name,[1,2,3],inputs)\n    else:\n        return lib.ops.batchnorm.Batchnorm(name,axes,inputs,fused=True)\n\ndef pixcnn_gated_nonlinearity(a, b):\n    return tf.sigmoid(a) * tf.tanh(b)\n\ndef SubpixelConv2D(*args, **kwargs):\n    kwargs['output_dim'] = 4*kwargs['output_dim']\n    output = lib.ops.conv2d.Conv2D(*args, **kwargs)\n    output = tf.transpose(output, [0,2,3,1])\n    output = tf.depth_to_space(output, 2)\n    output = tf.transpose(output, [0,3,1,2])\n    return output\n\ndef ResidualBlock(name, input_dim, output_dim, filter_size, inputs, resample=None, he_init=True):\n    \"\"\"\n    resample: None, 'down', or 'up'\n    \"\"\"\n    if resample=='down':\n        conv_shortcut = functools.partial(lib.ops.conv2d.Conv2D, stride=2)\n        conv_1        = functools.partial(lib.ops.conv2d.Conv2D, input_dim=input_dim, output_dim=input_dim//2)\n        conv_1b       = functools.partial(lib.ops.conv2d.Conv2D, input_dim=input_dim//2, output_dim=output_dim//2, stride=2)\n        conv_2        = functools.partial(lib.ops.conv2d.Conv2D, input_dim=output_dim//2, output_dim=output_dim)\n    elif resample=='up':\n        conv_shortcut = SubpixelConv2D\n        conv_1        = functools.partial(lib.ops.conv2d.Conv2D, input_dim=input_dim, output_dim=input_dim//2)\n        conv_1b       = functools.partial(lib.ops.deconv2d.Deconv2D, input_dim=input_dim//2, output_dim=output_dim//2)\n        conv_2        = functools.partial(lib.ops.conv2d.Conv2D, input_dim=output_dim//2, output_dim=output_dim)\n    elif resample==None:\n        conv_shortcut = lib.ops.conv2d.Conv2D\n        conv_1        = functools.partial(lib.ops.conv2d.Conv2D, input_dim=input_dim,  output_dim=input_dim//2)\n        conv_1b       = functools.partial(lib.ops.conv2d.Conv2D, input_dim=input_dim//2,  output_dim=output_dim/2)\n        conv_2        = functools.partial(lib.ops.conv2d.Conv2D, input_dim=input_dim//2, output_dim=output_dim)\n\n    else:\n        raise Exception('invalid resample value')\n\n    if output_dim==input_dim and resample==None:\n        shortcut = inputs # Identity skip-connection\n    else:\n        shortcut = conv_shortcut(name+'.Shortcut', input_dim=input_dim, output_dim=output_dim, filter_size=1,\n                                 he_init=False, biases=True, inputs=inputs)\n\n    output = inputs\n    output = tf.nn.relu(output)\n    output = conv_1(name+'.Conv1', filter_size=1, inputs=output, he_init=he_init, weightnorm=False)\n    output = tf.nn.relu(output)\n    output = conv_1b(name+'.Conv1B', filter_size=filter_size, inputs=output, he_init=he_init, weightnorm=False)\n    output = tf.nn.relu(output)\n    output = conv_2(name+'.Conv2', filter_size=1, inputs=output, he_init=he_init, weightnorm=False, biases=False)\n    output = Batchnorm(name+'.BN', [0,2,3], output)\n\n    return shortcut + (0.3*output)\n\n# ! Generators\n\ndef FCGenerator(n_samples, noise=None, FC_DIM=512, input_dim=INPUT_DIM):\n    if noise is None:\n        noise = tf.random_normal([n_samples, input_dim])\n\n    output = ReLULayer('Generator.1', input_dim, FC_DIM, noise)\n    output = ReLULayer('Generator.2', FC_DIM, FC_DIM, output)\n    output = ReLULayer('Generator.3', FC_DIM, FC_DIM, output)\n    output = ReLULayer('Generator.4', FC_DIM, FC_DIM, output)\n    output = lib.ops.linear.Linear('Generator.Out', FC_DIM, OUTPUT_DIM, output)\n\n    output = tf.tanh(output)\n\n    return output\n\ndef DCGANGenerator(\n        n_samples, noise=None, dim=DIM, input_dim=INPUT_DIM,\n        k=K, bn=True, nonlinearity=tf.nn.relu):\n\n    lib.ops.conv2d.set_weights_stdev(0.02)\n    lib.ops.deconv2d.set_weights_stdev(0.02)\n    lib.ops.linear.set_weights_stdev(0.02)\n    \n    if noise is None:\n        noise = tf.random_normal([n_samples, input_dim])\n        output = lib.ops.linear.Linear(\n            'Generator.Input', 256, (dim//k)*(dim//k)*8*dim, noise)\n        output = tf.reshape(output, [-1, 8*dim, dim//k, dim//k])\n        if bn:\n            output = Batchnorm('Generator.BN1', [0,2,3], output)\n            output = nonlinearity(output)\n    else:\n        # downsampled data as input (noise)\n        # input (noise) dimension [batchsize, 3*(dim/K)*(dim/K)]\n        # decode twice to tensor of [batchsize, 8*dim, 4, 4]\n        output = tf.reshape(noise, [-1, 3, dim//k, dim//k])\n        output = tflib.ops.conv2d.Conv2D(\n            'Generator.Encoder1.1', 3, 4*dim, 5, output, stride=2)\n        if bn:\n            output = Batchnorm('Generator.BN1.1', [0,2,3], output)\n            output = nonlinearity(output)\n            \n        output = tflib.ops.conv2d.Conv2D(\n            'Generator.Encode1.2', 4*dim, 8*dim, 5, output, stride=2)\n        if bn:\n            output = Batchnorm('Generator.BN1.2', [0, 2, 3], output)\n            output = nonlinearity(output)\n\n    output = lib.ops.deconv2d.Deconv2D('Generator.2', 8*dim, 4*dim, 5, output)\n    if bn:\n        output = Batchnorm('Generator.BN2', [0,2,3], output)\n    output = nonlinearity(output)\n\n    output = lib.ops.deconv2d.Deconv2D('Generator.3', 4*dim, 2*dim, 5, output)\n    if bn:\n        output = Batchnorm('Generator.BN3', [0,2,3], output)\n    output = nonlinearity(output)\n\n    output = lib.ops.deconv2d.Deconv2D('Generator.4', 2*dim, dim, 5, output)\n    if bn:\n        output = Batchnorm('Generator.BN4', [0,2,3], output)\n    output = nonlinearity(output)\n\n    output = lib.ops.deconv2d.Deconv2D('Generator.5', dim, 3, 5, output)\n    output = tf.tanh(output)\n    \n    lib.ops.conv2d.unset_weights_stdev()\n    lib.ops.deconv2d.unset_weights_stdev()\n    lib.ops.linear.unset_weights_stdev()\n\n    return tf.reshape(output, [-1, OUTPUT_DIM])\n\ndef WGANPaper_CrippledDCGANGenerator(\n        n_samples, noise=None, dim=DIM, input_dim=INPUT_DIM):\n    if noise is None:\n        noise = tf.random_normal([n_samples, input_dim])\n\n    output = lib.ops.linear.Linear('Generator.Input', input_dim, 4*4*dim, noise)\n    output = tf.nn.relu(output)\n    output = tf.reshape(output, [-1, dim, 4, 4])\n\n    output = lib.ops.deconv2d.Deconv2D('Generator.2', dim, dim, 5, output)\n    output = tf.nn.relu(output)\n\n    output = lib.ops.deconv2d.Deconv2D('Generator.3', dim, dim, 5, output)\n    output = tf.nn.relu(output)\n\n    output = lib.ops.deconv2d.Deconv2D('Generator.4', dim, dim, 5, output)\n    output = tf.nn.relu(output)\n\n    output = lib.ops.deconv2d.Deconv2D('Generator.5', dim, 3, 5, output)\n    output = tf.tanh(output)\n\n    return tf.reshape(output, [-1, OUTPUT_DIM])\n\ndef ResnetGenerator(n_samples, noise=None, dim=DIM, input_dim=INPUT_DIM):\n    if noise is None:\n        noise = tf.random_normal([n_samples, input_dim])\n\n    output = lib.ops.linear.Linear('Generator.Input', input_dim, 4*4*8*dim, noise)\n    output = tf.reshape(output, [-1, 8*dim, 4, 4])\n\n    for i in range(6):\n        output = ResidualBlock('Generator.4x4_{}'.format(i), 8*dim, 8*dim, 3, output, resample=None)\n    output = ResidualBlock('Generator.Up1', 8*dim, 4*dim, 3, output, resample='up')\n    for i in range(6):\n        output = ResidualBlock('Generator.8x8_{}'.format(i), 4*dim, 4*dim, 3, output, resample=None)\n    output = ResidualBlock('Generator.Up2', 4*dim, 2*dim, 3, output, resample='up')\n    for i in range(6):\n        output = ResidualBlock('Generator.16x16_{}'.format(i), 2*dim, 2*dim, 3, output, resample=None)\n    output = ResidualBlock('Generator.Up3', 2*dim, 1*dim, 3, output, resample='up')\n    for i in range(6):\n        output = ResidualBlock('Generator.32x32_{}'.format(i), 1*dim, 1*dim, 3, output, resample=None)\n    output = ResidualBlock('Generator.Up4', 1*dim, dim//2, 3, output, resample='up')\n    for i in range(5):\n        output = ResidualBlock('Generator.64x64_{}'.format(i), dim/2, dim/2, 3, output, resample=None)\n\n    output = lib.ops.conv2d.Conv2D('Generator.Out', dim//2, 3, 1, output, he_init=False)\n    output = tf.tanh(output / 5.)\n\n    return tf.reshape(output, [-1, OUTPUT_DIM])\n\n\ndef MultiplicativeDCGANGenerator(n_samples, noise=None, dim=DIM, bn=True, input_dim=INPUT_DIM):\n    if noise is None:\n        noise = tf.random_normal([n_samples, input_dim])\n\n    output = lib.ops.linear.Linear('Generator.Input', input_dim, 4*4*8*dim*2, noise)\n    output = tf.reshape(output, [-1, 8*dim*2, 4, 4])\n    if bn:\n        output = Batchnorm('Generator.BN1', [0,2,3], output)\n    output = pixcnn_gated_nonlinearity(output[:,::2], output[:,1::2])\n\n    output = lib.ops.deconv2d.Deconv2D('Generator.2', 8*dim, 4*dim*2, 5, output)\n    if bn:\n        output = Batchnorm('Generator.BN2', [0,2,3], output)\n    output = pixcnn_gated_nonlinearity(output[:,::2], output[:,1::2])\n\n    output = lib.ops.deconv2d.Deconv2D('Generator.3', 4*dim, 2*dim*2, 5, output)\n    if bn:\n        output = Batchnorm('Generator.BN3', [0,2,3], output)\n    output = pixcnn_gated_nonlinearity(output[:,::2], output[:,1::2])\n\n    output = lib.ops.deconv2d.Deconv2D('Generator.4', 2*dim, dim*2, 5, output)\n    if bn:\n        output = Batchnorm('Generator.BN4', [0,2,3], output)\n    output = pixcnn_gated_nonlinearity(output[:,::2], output[:,1::2])\n\n    output = lib.ops.deconv2d.Deconv2D('Generator.5', dim, 3, 5, output)\n    output = tf.tanh(output)\n\n    return tf.reshape(output, [-1, OUTPUT_DIM])\n\n# ! Discriminators\n\ndef MultiplicativeDCGANDiscriminator(inputs, dim=DIM, bn=True):\n    output = tf.reshape(inputs, [-1, 3, 64, 64])\n\n    output = lib.ops.conv2d.Conv2D('Discriminator.1', 3, dim*2, 5, output, stride=2)\n    output = pixcnn_gated_nonlinearity(output[:,::2], output[:,1::2])\n\n    output = lib.ops.conv2d.Conv2D('Discriminator.2', dim, 2*dim*2, 5, output, stride=2)\n    if bn:\n        output = Batchnorm('Discriminator.BN2', [0,2,3], output)\n    output = pixcnn_gated_nonlinearity(output[:,::2], output[:,1::2])\n\n    output = lib.ops.conv2d.Conv2D('Discriminator.3', 2*dim, 4*dim*2, 5, output, stride=2)\n    if bn:\n        output = Batchnorm('Discriminator.BN3', [0,2,3], output)\n    output = pixcnn_gated_nonlinearity(output[:,::2], output[:,1::2])\n\n    output = lib.ops.conv2d.Conv2D('Discriminator.4', 4*dim, 8*dim*2, 5, output, stride=2)\n    if bn:\n        output = Batchnorm('Discriminator.BN4', [0,2,3], output)\n    output = pixcnn_gated_nonlinearity(output[:,::2], output[:,1::2])\n\n    output = tf.reshape(output, [-1, 4*4*8*dim])\n    output = lib.ops.linear.Linear('Discriminator.Output', 4*4*8*dim, 1, output)\n\n    return tf.reshape(output, [-1])\n\n\ndef ResnetDiscriminator(inputs, dim=DIM):\n    output = tf.reshape(inputs, [-1, 3, 64, 64])\n    output = lib.ops.conv2d.Conv2D('Discriminator.In', 3, dim//2, 1, output, he_init=False)\n\n    for i in range(5):\n        output = ResidualBlock('Discriminator.64x64_{}'.format(i), dim/2, dim/2, 3, output, resample=None)\n    output = ResidualBlock('Discriminator.Down1', dim//2, dim*1, 3, output, resample='down')\n    for i in range(6):\n        output = ResidualBlock('Discriminator.32x32_{}'.format(i), dim*1, dim*1, 3, output, resample=None)\n    output = ResidualBlock('Discriminator.Down2', dim*1, dim*2, 3, output, resample='down')\n    for i in range(6):\n        output = ResidualBlock('Discriminator.16x16_{}'.format(i), dim*2, dim*2, 3, output, resample=None)\n    output = ResidualBlock('Discriminator.Down3', dim*2, dim*4, 3, output, resample='down')\n    for i in range(6):\n        output = ResidualBlock('Discriminator.8x8_{}'.format(i), dim*4, dim*4, 3, output, resample=None)\n    output = ResidualBlock('Discriminator.Down4', dim*4, dim*8, 3, output, resample='down')\n    for i in range(6):\n        output = ResidualBlock('Discriminator.4x4_{}'.format(i), dim*8, dim*8, 3, output, resample=None)\n\n    output = tf.reshape(output, [-1, 4*4*8*dim])\n    output = lib.ops.linear.Linear('Discriminator.Output', 4*4*8*dim, 1, output)\n\n    return tf.reshape(output / 5., [-1])\n\n\ndef FCDiscriminator(inputs, FC_DIM=512, n_layers=3):\n    output = LeakyReLULayer('Discriminator.Input', OUTPUT_DIM, FC_DIM, inputs)\n    for i in range(n_layers):\n        output = LeakyReLULayer('Discriminator.{}'.format(i), FC_DIM, FC_DIM, output)\n    output = lib.ops.linear.Linear('Discriminator.Out', FC_DIM, 1, output)\n\n    return tf.reshape(output, [-1])\n\ndef DCGANDiscriminator(inputs, dim=DIM, bn=True, nonlinearity=LeakyReLU):\n    output = tf.reshape(inputs, [-1, 3, 64, 64])\n\n    lib.ops.conv2d.set_weights_stdev(0.02)\n    lib.ops.deconv2d.set_weights_stdev(0.02)\n    lib.ops.linear.set_weights_stdev(0.02)\n\n    output = lib.ops.conv2d.Conv2D('Discriminator.1', 3, dim, 5, output, stride=2)\n    output = nonlinearity(output)\n\n    output = lib.ops.conv2d.Conv2D('Discriminator.2', dim, 2*dim, 5, output, stride=2)\n    if bn:\n        output = Batchnorm('Discriminator.BN2', [0,2,3], output)\n    output = nonlinearity(output)\n\n    output = lib.ops.conv2d.Conv2D('Discriminator.3', 2*dim, 4*dim, 5, output, stride=2)\n    if bn:\n        output = Batchnorm('Discriminator.BN3', [0,2,3], output)\n    output = nonlinearity(output)\n\n    output = lib.ops.conv2d.Conv2D('Discriminator.4', 4*dim, 8*dim, 5, output, stride=2)\n    if bn:\n        output = Batchnorm('Discriminator.BN4', [0,2,3], output)\n    output = nonlinearity(output)\n\n    output = tf.reshape(output, [-1, 4*4*8*dim])\n    output = lib.ops.linear.Linear('Discriminator.Output', 4*4*8*dim, 1, output)\n\n    lib.ops.conv2d.unset_weights_stdev()\n    lib.ops.deconv2d.unset_weights_stdev()\n    lib.ops.linear.unset_weights_stdev()\n\n    return tf.reshape(output, [-1])\n\n# kernel for downsampling\narr = np.zeros([K, K, 3, 3])\narr[:,:,0,0] = 1.0/(K*K)\narr[:,:,1,1] = 1.0/(K*K)\narr[:,:,2,2] = 1.0/(K*K)\n_downsample_weight = tf.constant(arr, dtype=tf.float32)\n\ndef downsample(data, method='conv'):\n    data = tf.reshape(data, [-1, 3, DIM, DIM])\n    # BCHW -> BHWC\n    data = tf.transpose(data, [0, 2, 3, 1])\n    if method == 'conv':\n        data = tf.nn.conv2d(data, _downsample_weight,\n                            strides=[1, K, K, 1], padding='SAME')\n    elif method == 'area':\n        data = tf.image.resize_area(data, [DIM//K, DIM//K])\n    # BHWC -> BCHW\n    data = tf.transpose(data, [0, 3, 1, 2])\n    data = tf.reshape(data, [-1, 3 * DIM//K * DIM//K])\n    return data\n\nGenerator, Discriminator = GeneratorAndDiscriminator()\n\nwith tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as session:\n\n    all_real_data_conv = tf.placeholder(tf.int32, shape=[BATCH_SIZE, 3, 64, 64])\n    if tf.__version__.startswith('1.'):\n        split_real_data_conv = tf.split(all_real_data_conv, len(DEVICES))\n    else:\n        split_real_data_conv = tf.split(0, len(DEVICES), all_real_data_conv)\n\n    gen_l1_costs, gen_gan_costs = [], []\n    gen_costs, disc_costs = [],[]\n\n    for device_index, (device, real_data_conv) in enumerate(zip(DEVICES, split_real_data_conv)):\n        with tf.device(device):\n            real_data = 2*((tf.cast(real_data_conv, tf.float32)/255.)-.5)\n            real_data = tf.reshape(real_data, [BATCH_SIZE//len(DEVICES), OUTPUT_DIM])\n            # downsampled (by K) as generator input\n            real_data_downsampled = downsample(real_data)\n            fake_data = Generator(BATCH_SIZE//len(DEVICES), noise=real_data_downsampled)\n            \n            disc_real = Discriminator(real_data)\n            disc_fake = Discriminator(fake_data)\n\n            if MODE == 'wgan':\n                gen_cost = tf.reduce_mean(disc_fake)\n                disc_cost = tf.reduce_mean(disc_real) - tf.reduce_mean(disc_fake)\n\n            elif MODE == 'wgan-gp':\n                gen_cost = tf.reduce_mean(disc_fake)\n                disc_cost = tf.reduce_mean(disc_real) - tf.reduce_mean(disc_fake)\n\n                alpha = tf.random_uniform(\n                    shape=[BATCH_SIZE//len(DEVICES),1], \n                    minval=0.,\n                    maxval=1.\n                )\n                differences = fake_data - real_data\n                interpolates = real_data + (alpha*differences)\n                gradients = tf.gradients(Discriminator(interpolates), [interpolates])[0]\n                slopes = tf.sqrt(tf.reduce_sum(tf.square(gradients), reduction_indices=[1]))\n                gradient_penalty = tf.reduce_mean((slopes-1.)**2)\n                disc_cost += LAMBDA*gradient_penalty\n\n            elif MODE == 'dcgan':\n                try: # tf pre-1.0 (bottom) vs 1.0 (top)\n                    gen_cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=disc_fake,\n                                                                                      labels=tf.ones_like(disc_fake)))\n                    disc_cost =  tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=disc_fake,\n                                                                                        labels=tf.zeros_like(disc_fake)))\n                    disc_cost += tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=disc_real,\n                                                                                        labels=tf.ones_like(disc_real)))                    \n                except Exception as e:\n                    gen_cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(disc_fake, tf.ones_like(disc_fake)))\n                    disc_cost =  tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(disc_fake, tf.zeros_like(disc_fake)))\n                    disc_cost += tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(disc_real, tf.ones_like(disc_real)))                    \n                disc_cost /= 2.\n\n            elif MODE == 'lsgan':\n                gen_cost = tf.reduce_mean((disc_fake - 1)**2)\n                disc_cost = (tf.reduce_mean((disc_real - 1)**2) + tf.reduce_mean((disc_fake - 0)**2))/2.\n\n            else:\n                raise Exception()\n\n            # add L1 difference to penalty\n            fake_data_downsampled = downsample(fake_data)\n            gen_l1_cost = tf.reduce_mean(\n                tf.abs(fake_data_downsampled - real_data_downsampled))\n\n            gen_l1_costs.append(gen_l1_cost)\n            gen_gan_costs.append(gen_cost)\n\n            gen_cost = GEN_L1_WEIGHT * gen_l1_cost + (1 - GEN_L1_WEIGHT) * gen_cost\n\n            gen_costs.append(gen_cost)\n            disc_costs.append(disc_cost)\n\n    gen_cost = tf.add_n(gen_costs) / len(DEVICES)\n    disc_cost = tf.add_n(disc_costs) / len(DEVICES)\n    gen_gan_cost = tf.add_n(gen_gan_costs) / len(DEVICES)\n    gen_l1_cost = tf.add_n(gen_l1_costs) / len(DEVICES)\n    tf.summary.scalar('gen gan loss', gen_gan_cost, collections=['scalars'])\n    tf.summary.scalar('gen l1 diff', gen_l1_cost, collections=['scalars'])\n    tf.summary.scalar('gen loss', gen_cost, collections=['scalars'])\n    tf.summary.scalar('disc loss', disc_cost, collections=['scalars'])\n\n    if MODE == 'wgan':\n        gen_train_op = tf.train.RMSPropOptimizer(learning_rate=1e-4).minimize(\n            gen_cost, var_list=lib.params_with_name('Generator'), colocate_gradients_with_ops=True)\n        disc_train_op = tf.train.RMSPropOptimizer(learning_rate=1e-4).minimize(disc_cost,\n                                             var_list=lib.params_with_name('Discriminator.'), colocate_gradients_with_ops=True)\n\n        clip_ops = []\n        for var in lib.params_with_name('Discriminator'):\n            clip_bounds = [-.01, .01]\n            clip_ops.append(tf.assign(var, tf.clip_by_value(var, clip_bounds[0], clip_bounds[1])))\n        clip_disc_weights = tf.group(*clip_ops)\n\n    elif MODE == 'wgan-gp':\n        gen_train_op = tf.train.AdamOptimizer(\n            learning_rate=1e-4, beta1=0.5, beta2=0.9).minimize(\n                gen_cost,var_list=lib.params_with_name('Generator'), colocate_gradients_with_ops=True)\n        disc_train_op = tf.train.AdamOptimizer(learning_rate=1e-4, beta1=0.5, beta2=0.9).minimize(disc_cost,\n                                           var_list=lib.params_with_name('Discriminator.'), colocate_gradients_with_ops=True)\n\n    elif MODE == 'dcgan':\n        gen_train_op = tf.train.AdamOptimizer(learning_rate=2e-4, beta1=0.5).minimize(gen_cost,\n                                          var_list=lib.params_with_name('Generator'), colocate_gradients_with_ops=True)\n        disc_train_op = tf.train.AdamOptimizer(learning_rate=2e-4, beta1=0.5).minimize(disc_cost,\n                                           var_list=lib.params_with_name('Discriminator.'), colocate_gradients_with_ops=True)\n\n    elif MODE == 'lsgan':\n        gen_train_op = tf.train.RMSPropOptimizer(learning_rate=1e-4).minimize(gen_cost,\n                                             var_list=lib.params_with_name('Generator'), colocate_gradients_with_ops=True)\n        disc_train_op = tf.train.RMSPropOptimizer(learning_rate=1e-4).minimize(disc_cost,\n                                              var_list=lib.params_with_name('Discriminator.'), colocate_gradients_with_ops=True)\n\n    else:\n        raise Exception()\n\n#     # For generating samples\n#     fixed_noise = tf.constant(np.random.normal(size=(BATCH_SIZE, INPUT_DIM)).astype('float32'))\n#     all_fixed_noise_samples = []\n#     for device_index, device in enumerate(DEVICES):\n#         n_samples = BATCH_SIZE // len(DEVICES)\n#         all_fixed_noise_samples.append(Generator(n_samples, noise=fixed_noise[device_index*n_samples:(device_index+1)*n_samples]))\n#     if tf.__version__.startswith('1.'):\n#         all_fixed_noise_samples = tf.concat(all_fixed_noise_samples, axis=0)\n#     else:\n#         all_fixed_noise_samples = tf.concat(0, all_fixed_noise_samples)\n\n#     def generate_image(iteration):\n#         # add image to summary\n#         samples_reshaped = tf.reshape(\n#             all_fixed_noise_samples, (BATCH_SIZE, 3, DIM, DIM))\n#         samples_reshaped = tf.transpose(samples_reshaped, [0, 2, 3, 1])\n#         image_op = tf.summary.image(\n#             'generator output', samples_reshaped)\n#         image_summary = session.run(image_op)\n#         summary_writer.add_summary(image_summary, iteration)\n\n#         samples = session.run(all_fixed_noise_samples)\n#         samples = ((samples+1.)*(255.99/2)).astype('int32')\n#         lib.save_images.save_images(samples.reshape((BATCH_SIZE, 3, 64, 64)), 'samples_{}.png'.format(iteration))\n\n    \n    def generate_test_image(iteration, real_data, fake_data,  max_samples=10):\n        feature = tf.reshape(real_data_downsampled, [-1, 3, DIM//K, DIM//K])\n        # BCHW -> BHWC\n        feature = (tf.transpose(feature, [0, 2, 3, 1]) + 1)/2.\n        nearest = tf.image.resize_nearest_neighbor(feature, [DIM, DIM])\n        nearest = tf.maximum(tf.minimum(nearest, 1.), 0.)\n        bicubic = tf.image.resize_bicubic(feature, [DIM, DIM])\n        bicubic = tf.maximum(tf.minimum(bicubic, 1.), 0.)\n        fake_data = (tf.reshape(fake_data, [-1, 3, DIM, DIM]) + 1.)/2.\n        fake_data = tf.transpose(fake_data, [0, 2, 3, 1])\n        real_data = tf.reshape(real_data, [-1, 3, DIM, DIM])\n        real_data = tf.transpose(real_data, [0, 2, 3, 1])\n        real_data = (real_data + 1.) / 2.\n        clipped = tf.maximum(tf.minimum(fake_data, 1.), 0.)\n        image = tf.concat([nearest, bicubic, clipped, real_data], 2)\n\n        feed_dict = {real_data_conv: test_data}\n        image_col = tf.summary.image('generator output', image, max_samples)\n        image_summary = session.run(image_col, feed_dict=feed_dict)\n        summary_writer.add_summary(image_summary, iteration)\n\n        image = image[0:max_samples,:,:,:]\n        image = tf.concat([image[i,:,:,:] for i in range(max_samples)], 0)\n        clipped = clipped[0:max_samples, :, :, :]\n        clipped = tf.concat([clipped[i, :, :, :] for i in range(max_samples)], 1)\n\n        image, clipped = session.run([image, clipped], feed_dict=feed_dict)\n        \n        filename_1 = 'batch%06d_image.png' % iteration\n        filename_2 = 'batch%06d_row.png' % iteration\n        filename_1 = os.path.join(TRAIN_DIR, filename_1)\n        filename_2 = os.path.join(TRAIN_DIR, filename_2)\n        scipy.misc.toimage(image, cmin=0., cmax=1.).save(filename_1)\n        scipy.misc.toimage(clipped, cmin=0., cmax=1.).save(filename_2)\n        print(\"Saved %s %s\" % (filename_1, filename_2))\n\n        \n\n\n\n    # Dataset iterator and test set (for visualization) \n    train_gen, test_data = lib.celebA_64x64.load(BATCH_SIZE, data_dir=DATA_DIR)\n    #train_gen, dev_gen = lib.small_imagenet.load(BATCH_SIZE, data_dir=DATA_DIR)\n\n    def inf_train_gen():\n        while True:\n            for (images,) in train_gen():\n                yield images\n\n    # Save a batch of ground-truth samples\n    _x = next(inf_train_gen())\n    _x_r = session.run(real_data, feed_dict={real_data_conv: _x})\n    _x_r = ((_x_r+1.)*(255.99/2)).astype('int32')\n    lib.save_images.save_images(_x_r.reshape((BATCH_SIZE, 3, 64, 64)), 'samples_groundtruth.png')\n\n    # Train loop\n    merged_scalars = tf.summary.merge_all(key='scalars')\n    summary_writer = tf.summary.FileWriter(SUMMARY_DIR, session.graph)\n\n    session.run(tf.global_variables_initializer())\n    gen = inf_train_gen()\n    all_start_time = time.time()\n    for iteration in range(ITERS):\n        start_time = time.time()\n        # finish if run overtime\n        total_elapsed = (start_time - all_start_time) / 60.\n        if total_elapsed > FLAGS.max_runtime:\n            break\n\n        # Train generator\n        if iteration > 0:\n            _ = session.run(gen_train_op, feed_dict={all_real_data_conv: _data})\n\n        # Train critic\n        if (MODE == 'dcgan') or (MODE == 'lsgan'):\n            disc_iters = 1\n        else:\n            disc_iters = CRITIC_ITERS\n        for i in range(disc_iters):\n            _data = next(gen)\n            _disc_cost, _ = session.run([disc_cost, disc_train_op], feed_dict={all_real_data_conv: _data})\n            if MODE == 'wgan':\n                _ = session.run([clip_disc_weights])\n\n        lib.plot.plot('train disc cost', _disc_cost)\n        lib.plot.plot('time', time.time() - start_time)\n        #print('iter={0} disc_loss={1:.3g} time={2:.2g}'.format(\n        #    iteration, _disc_cost, time.time() - start_time))\n\n        if iteration % 10 == 0:\n            merged_summary = session.run(merged_scalars, feed_dict={all_real_data_conv: _data})\n            summary_writer.add_summary(merged_summary, iteration)\n\n        if iteration % 200 == 9:\n            t = time.time()\n            #dev_disc_costs = []\n            #for (images,) in dev_gen():\n            #    _dev_disc_cost = session.run(disc_cost, feed_dict={all_real_data_conv: _data}) \n            #    dev_disc_costs.append(_dev_disc_cost)\n            #lib.plot.plot('dev disc cost', np.mean(dev_disc_costs))\n            generate_test_image(iteration, real_data, fake_data)\n\n        if (iteration < 5) or (iteration % 200 == 199):\n            lib.plot.flush()\n\n        lib.plot.tick()\n\n\nif __name__ == '__main__':\n    tf.app.run()\n", "meta": {"hexsha": "a2c7321b92e73a5156e1b59e4a34d6737161a408", "size": 30983, "ext": "py", "lang": "Python", "max_stars_repo_path": "gan_SR.py", "max_stars_repo_name": "YuguangTong/improved_wgan_training", "max_stars_repo_head_hexsha": "42e8b63ac599739b51ee6566cb9f550c2e2138a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2017-05-13T21:17:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:00:30.000Z", "max_issues_repo_path": "gan_SR.py", "max_issues_repo_name": "love666666shen/improved_wgan_training", "max_issues_repo_head_hexsha": "42e8b63ac599739b51ee6566cb9f550c2e2138a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gan_SR.py", "max_forks_repo_name": "love666666shen/improved_wgan_training", "max_forks_repo_head_hexsha": "42e8b63ac599739b51ee6566cb9f550c2e2138a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-05-14T01:07:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-05T19:56:46.000Z", "avg_line_length": 43.638028169, "max_line_length": 144, "alphanum_fraction": 0.6453539038, "include": true, "reason": "import numpy,import scipy", "num_tokens": 8618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.30074558520860073, "lm_q1q2_score": 0.16326373578597742}}
{"text": "\n# Main entrance of GAIL\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport gym\nimport safety_gym\nimport time\nimport os.path as osp\n\nimport wandb\n\nfrom neural_nets import Discriminator, ActorCritic, count_vars\n\nfrom utils import BufferStudent, BufferTeacher\nfrom utils import mpi_fork, proc_id, num_procs, EpochLogger,\\\n    average_gradients, sync_all_params, setup_pytorch_for_mpi, sync_params, mpi_avg_grads\n\n\ndef gail_penalized(env_fn, actor_critic=ActorCritic, ac_kwargs=dict(),\n         disc=Discriminator,\n         dc_kwargs=dict(), seed=0,\n         episodes_per_epoch=40,\n         epochs=500,\n         gamma=0.99, lam=0.97,\n         # Cost constraints / penalties:\n         cost_lim=25,\n         penalty_init=1.,\n         penalty_lr=5e-3,\n         clip_ratio=0.2,\n         pi_lr=3e-3, vf_lr=3e-3, dc_lr=5e-4,\n         train_v_iters=80, train_pi_iters=80, train_dc_iters=80,\n         max_ep_len=1000, logger_kwargs=dict(), config_name = 'standard', save_freq=10):\n    # W&B Logging\n    wandb.login()\n\n    composite_name = 'new_gail_penalized_' + config_name\n    wandb.init(project=\"LearningCurves\", group=\"GAIL Clone\", name=composite_name)\n\n    # Special function to avoid certain slowdowns from PyTorch + MPI combo.\n    setup_pytorch_for_mpi()\n\n    l_lam = 0  # balance two loss terms\n\n\n    # Set up logger and save configuration\n    logger = EpochLogger(**logger_kwargs)\n    logger.save_config(locals())\n\n    seed += 10000 * proc_id()\n    torch.manual_seed(seed)\n    np.random.seed(seed)\n\n    # Instantiate environment\n    env = env_fn()\n    obs_dim = env.observation_space.shape\n    act_dim = env.action_space.shape\n\n    ac_kwargs['action_space'] = env.action_space\n\n    # Models  # Create actor-critic and discriminator modules\n    ac = actor_critic(input_dim=obs_dim[0], **ac_kwargs)\n    discrim = disc(input_dim=obs_dim[0], **dc_kwargs)\n\n    # Set up model saving\n    logger.setup_pytorch_saver([ac, discrim])\n\n    # Sync params across processes\n    sync_params(ac)\n    sync_params(discrim)\n\n\n    # Load expert policy here\n    expert = actor_critic(input_dim=obs_dim[0], **ac_kwargs)\n    # expert_name = \"expert_torch_save.pt\"\n    expert_name = \"model.pt\"\n    # expert = torch.load(osp.join(logger_kwargs['output_dir'],'pyt_save' , expert_name))\n    # expert = torch.load('/home/tyna/Documents/openai/research-project/data/anonymous-expert/anonymous-expert_s0/pyt_save/model.pt')\n    expert = torch.load(\n        '/home/tyna/Documents/openai/research-project/data/test-pen-ppo/test-pen-ppo_s0/pyt_save/model.pt')\n\n    print('RUNNING GAIL')\n\n    # Buffers\n    local_episodes_per_epoch = int(episodes_per_epoch / num_procs())\n    buff_s = BufferStudent(obs_dim[0], act_dim[0], local_episodes_per_epoch, max_ep_len)\n    buff_t = BufferTeacher(obs_dim[0], act_dim[0], local_episodes_per_epoch, max_ep_len)\n\n    # Count variables\n    var_counts = tuple(count_vars(module) for module in [ac.pi, ac.v, discrim.pi])\n    logger.log('\\nNumber of parameters: \\t pi: %d, \\t v: %d, \\t d: %d\\n' % var_counts)\n\n\n    # Optimizers\n    pi_optimizer = torch.optim.Adam(ac.pi.parameters(), lr=pi_lr)\n    vf_optimizer = torch.optim.Adam(ac.v.parameters(), lr=vf_lr)\n    discrim_optimizer = torch.optim.Adam(discrim.pi.parameters(), lr=dc_lr)\n\n    # # Parameters Sync\n    # sync_all_params(ac.parameters())\n    # sync_all_params(disc.parameters())\n\n    # Set up function for computing PPO policy loss\n    def compute_loss_pi(obs, act, adv, logp_old):\n        # Policy loss # policy gradient term + entropy term\n        # Policy loss with clipping (without clipping, loss_pi = -(logp*adv).mean()).\n        # TODO: Think about removing clipping\n        _, logp, _ = ac.pi(obs, act)\n        ratio = torch.exp(logp - logp_old)\n        clip_adv = torch.clamp(ratio, 1 - clip_ratio, 1 + clip_ratio) * adv\n        loss_pi = -(torch.min(ratio * adv, clip_adv)).mean()\n\n        return loss_pi\n\n\n    def penalty_update(cur_penalty):\n        cur_cost = logger.get_stats('EpCostS')[0]\n        cur_rew = logger.get_stats('EpRetS')[0]\n\n        # Penalty update\n        cur_penalty = max(0, cur_penalty + penalty_lr * (cur_cost - cost_lim))\n        return cur_penalty\n\n    def update(e):\n        obs_s, act, adv, ret, log_pi_old = [torch.Tensor(x) for x in buff_s.retrieve_all()]\n        obs_t, _ = [torch.Tensor(x) for x in buff_t.retrieve_all()]\n\n        # Policy\n        _, logp, _ = ac.pi(obs_s, act)\n        entropy = (-logp).mean()\n\n        # Policy loss   # policy gradient term + entropy term\n        # loss_pi = -(logp * adv).mean() - l_lam * entropy\n\n        # Train policy\n        if e > 10:\n            # Train policy with multiple steps of gradient descent\n            for _ in range(train_pi_iters):\n                pi_optimizer.zero_grad()\n                loss_pi = compute_loss_pi(obs, act, adv, ret)\n                loss_pi.backward()\n                mpi_avg_grads(ac.pi)\n                pi_optimizer.step()\n\n        # Value function\n        v = ac.v(obs_s)\n        v_l_old = F.mse_loss(v, ret)\n\n        for _ in range(train_v_iters):\n            v = ac.v(obs_s)\n            v_loss = F.mse_loss(v, ret)\n\n            # Value function train\n            vf_optimizer.zero_grad()\n            v_loss.backward()\n            mpi_avg_grads(ac.v)  # average gradients across MPI processes\n            vf_optimizer.step()\n\n        # Discriminator\n        gt1 = torch.ones(obs_s.size()[0], dtype=torch.int)\n        gt2 = torch.zeros(obs_t.size()[0], dtype=torch.int)\n        _, logp_student, _ = discrim(obs_s, gt=gt1)\n        _, logp_teacher, _ = discrim(obs_t, gt=gt2)\n        discrim_l_old = - logp_student.mean() - logp_teacher.mean()\n\n        for _ in range(train_dc_iters):\n            _, logp_student, _ = discrim(obs_s, gt=gt1)\n            _, logp_teacher, _ = discrim(obs_t, gt=gt2)\n            dc_loss = - logp_student.mean() - logp_teacher.mean()\n\n            # Discriminator train\n            discrim_optimizer.zero_grad()\n            dc_loss.backward()\n            # average_gradients(discrim_optimizer.param_groups)\n            mpi_avg_grads(discrim.pi)\n            discrim_optimizer.step()\n\n\n        _, logp_student, _ = discrim(obs_s, gt=gt1)\n        _, logp_teacher, _ = discrim(obs_t, gt=gt2)\n        dc_loss_new = - logp_student.mean() - logp_teacher.mean()\n\n        # Log the changes\n        _, logp, _, v = ac(obs, act)\n        entropy_new = (-logp).mean()\n        pi_loss_new = -(logp * adv).mean() - l_lam * entropy\n        v_loss_new = F.mse_loss(v, ret)\n        kl = (log_pi_old - logp).mean()\n        logger.store(\n            # LossPi=loss_pi,\n            LossV=v_l_old, LossDC=discrim_l_old,\n                     # DeltaLossPi=(pi_loss_new - loss_pi),\n                     DeltaLossV=(v_loss_new - v_l_old), DeltaLossDC=(dc_loss_new - discrim_l_old),\n                     DeltaEnt=(entropy_new - entropy),\n                     Entropy=entropy, KL=kl)\n\n    start_time = time.time()\n    o, r, sdr, d, ep_ret, ep_cost, ep_sdr, ep_len = env.reset(), 0, 0, False, 0, 0, 0, 0\n    total_t = 0\n    ep_len_t = 0\n\n    # Initialize penalty\n    cur_penalty = np.log(max(np.exp(penalty_init) - 1, 1e-8))\n\n    for epoch in range(epochs):\n        ac.eval()\n        discrim.eval()\n        # We recognize the probability term of index [0] correspond to the teacher's policy\n\n        # Student's policy rollout\n        for _ in range(local_episodes_per_epoch):\n            for _ in range(max_ep_len):\n                obs = torch.Tensor(o.reshape(1, -1))\n                a, _, lopg_t, v_t = ac(obs)\n\n                buff_s.store(o, a.detach().numpy(), r, sdr, v_t.item(), lopg_t.detach().numpy())\n                logger.store(VVals=v_t)\n\n                o, r, d, info = env.step(a.detach().numpy()[0])\n                # print(\"INFO: \", info)\n                c = info.get(\"cost\")\n\n                _, sdr, _ = discrim(torch.Tensor(o.reshape(1, -1)), gt=torch.Tensor([0]))\n                if sdr < -4:  # Truncate rewards\n                    sdr = -4\n\n                ep_ret += r\n                ep_cost += c\n                ep_sdr += sdr\n                ep_len += 1\n                total_t += 1\n\n                terminal = d or (ep_len == max_ep_len)\n                if terminal:\n                    buff_s.end_episode()\n                    logger.store(EpRetS=ep_ret, EpCostS= ep_cost, EpLenS=ep_len, EpSdrS=ep_sdr)\n                    print(\"Student Episode Return: \\t\", ep_ret)\n                    o, r, sdr, d, ep_ret, ep_cost, ep_sdr, ep_len = env.reset(), 0, 0, False, 0, 0, 0, 0\n\n        # Teacher's policy rollout\n        for _ in range(local_episodes_per_epoch):\n            for _ in range(max_ep_len):\n                # obs =\n                a, _, _, _ = expert(torch.Tensor(o.reshape(1, -1)))\n\n                buff_t.store(o, a.detach().numpy(), r)\n\n                o, r, d, info = env.step(a.detach().numpy()[0])\n                c = info.get(\"cost\")\n                ep_ret += r\n                ep_cost += c\n                ep_len += 1\n                total_t += 1\n\n                terminal = d or (ep_len == max_ep_len)\n                if terminal:\n                    buff_t.end_episode()\n                    logger.store(EpRetT=ep_ret, EpCostT=ep_cost, EpLenT=ep_len)\n                    print(\"Teacher Episode Return: \\t\", ep_ret)\n                    o, r, d, ep_ret, ep_cost, ep_len = env.reset(), 0, False, 0, 0, 0\n\n        if (epoch % save_freq == 0) or (epoch == epochs - 1):\n            logger.save_state({'env': env}, [ac, discrim], None)\n\n        # Update\n        ac.train()\n        discrim.train()\n\n        # update penalty\n        cur_penalty = penalty_update(cur_penalty)\n\n        # update networks\n        update(epoch)\n\n        # Log\n        logger.log_tabular('Epoch', epoch)\n        logger.log_tabular('EpRetS', average_only=True)\n        logger.log_tabular('EpSdrS', average_only=True)\n        logger.log_tabular('EpLenS', average_only=True)\n        logger.log_tabular('EpRetT', average_only=True)\n        logger.log_tabular('EpLenT', average_only=True)\n        logger.log_tabular('VVals', with_min_and_max=True)\n        logger.log_tabular('TotalEnvInteracts', total_t)\n        # logger.log_tabular('LossPi', average_only=True)\n        # logger.log_tabular('DeltaLossPi', average_only=True)\n        logger.log_tabular('LossV', average_only=True)\n        logger.log_tabular('DeltaLossV', average_only=True)\n        logger.log_tabular('LossDC', average_only=True)\n        logger.log_tabular('DeltaLossDC', average_only=True)\n        # logger.log_tabular('Entropy', average_only=True)\n        # logger.log_tabular('DeltaEnt', average_only=True)\n        # logger.log_tabular('KL', average_only=True)\n        logger.log_tabular('Time', time.time() - start_time)\n        logger.dump_tabular()\n\n\n\nif __name__ == '__main__':\n    import argparse\n\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--env', type=str, default='Safexp-PointGoal1-v0')\n    parser.add_argument('--hid', type=int, default=64)\n    parser.add_argument('--l', type=int, default=2)\n    parser.add_argument('--gamma', type=float, default=0.99)\n    parser.add_argument('--lam', type=float, default=0.97)\n    parser.add_argument('--seed', '-s', type=int, default=0)\n    parser.add_argument('--cpu', type=int, default=1)\n    parser.add_argument('--episodes-per-epoch', type=int, default=5)\n    # parser.add_argument('--episodes-per-epoch', type=int, default=40)\n    parser.add_argument('--epochs', type=int, default=1000)\n    parser.add_argument('--exp_name', type=str, default='valor-anonymous-expert')\n    parser.add_argument('--con', type=int, default=5)\n    args = parser.parse_args()\n\n    mpi_fork(args.cpu)\n\n    from utils import setup_logger_kwargs\n\n    logger_kwargs = setup_logger_kwargs(args.exp_name, args.seed)\n\n    gail_penalized(lambda: gym.make(args.env), actor_critic=ActorCritic, ac_kwargs=dict(hidden_dims=[args.hid] * args.l),\n         disc=Discriminator, dc_kwargs=dict(hidden_dims=[args.hid] * args.l), gamma=args.gamma, lam=args.lam,\n         seed=args.seed, episodes_per_epoch=args.episodes_per_epoch, epochs=args.epochs, logger_kwargs=logger_kwargs)\n", "meta": {"hexsha": "9ea720b3a1eef4d021eb7536669b8128e49a8c4b", "size": 12085, "ext": "py", "lang": "Python", "max_stars_repo_path": "algos/behavioral_cloning/train_clone_gail_penalized.py", "max_stars_repo_name": "feloundou/safe-experts", "max_stars_repo_head_hexsha": "9592bd48ce7eed721a36cb688dd10dc7f527a13b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "algos/behavioral_cloning/train_clone_gail_penalized.py", "max_issues_repo_name": "feloundou/safe-experts", "max_issues_repo_head_hexsha": "9592bd48ce7eed721a36cb688dd10dc7f527a13b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algos/behavioral_cloning/train_clone_gail_penalized.py", "max_forks_repo_name": "feloundou/safe-experts", "max_forks_repo_head_hexsha": "9592bd48ce7eed721a36cb688dd10dc7f527a13b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1846153846, "max_line_length": 133, "alphanum_fraction": 0.6119983451, "include": true, "reason": "import numpy", "num_tokens": 3094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.1632637357859774}}
{"text": "#!/usr/bin/env python\n'''\nmcu: Modeling and Crystallographic Utilities\nCopyright (C) 2019 Hung Q. Pham. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nEmail: Hung Q. Pham <pqh3.14@gmail.com>\n'''\n\n\nimport numpy as np\nfrom ..utils import plot\nfrom ..vasp import const\nfrom . import crystal_io\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n        \nclass main:\n    def __init__(self,  seedname=\"outfile\"):\n        '''\n        \n        '''\n        self.seedname = seedname\n        \n\n############ Plotting ################# \n    def get_band(self, phonon=False, gamma_correct=False, threshold=8.06554):\n        '''Make a band from from \n           NOTE: the proj_kpath is computed from the dk and nkp. Due to the round out error in f25, the computed high symmetric k-point coordinates won't be exactly the same as values obtained from *.BAND file.\n           \n           if phonon == True: the phonon band is read. Three small negative acoustic modes at Gamma can be removed by using the gamma_correct keyword and threshold 1 meV = 8.06554 cm^-1  \n        '''\n        data = crystal_io.read_f25(self.seedname + \".f25\")\n        temp = []\n        ihferm_list = []\n        proj_kpath = []\n        sym_kpoint_coor = [0.0]\n        shift = 0\n        for block in data:\n            ihferm, type, nband, nkp, dk, efermi, eigenvals = block\n            if type == 'BAND':\n                temp.append(eigenvals.reshape(-1, nband))\n                path = np.arange(nkp)*dk + shift\n                proj_kpath.append(path)\n                shift = path[-1] + dk\n                sym_kpoint_coor.append(path[-1])\n        \n        if ihferm == 0 or ihferm == 2:\n            band = np.float64([np.vstack(temp)])\n            proj_kpath = np.hstack(proj_kpath)\n        elif ihferm == 1 or ihferm == 3:\n            nblock = len(temp) // 2\n            band_up = np.vstack(temp[:nblock])            \n            band_down = np.vstack(temp[nblock:])  \n            band = np.float64([band_up, band_down])\n            proj_kpath = np.hstack(proj_kpath[:nblock])\n        sym_kpoint_coor = np.float64(sym_kpoint_coor)\n        if phonon == True:\n            if gamma_correct == True:\n                # Should be checked first before using the correction to make sure it is really acoustic phonon modes\n                nspin, nkpts, nband = band.shape\n                band = band.flatten()\n                imag_mode_idx = band < 0.0\n                imag_mode = band[imag_mode_idx]\n                imag_mode_idx2 = imag_mode > -threshold\n                imag_mode[imag_mode_idx2] = 0.0\n                band[imag_mode_idx] = imag_mode\n                band = band.reshape(nspin, nkpts, nband)\n        else:\n            band = const.AUTOEV * band\n            efermi = const.AUTOEV * efermi\n            \n        return band, proj_kpath, sym_kpoint_coor, efermi\n\n    def get_bandgap(self):\n        '''Get the bandgap'''\n        \n        band, proj_kpath, sym_kpoint_coor, efermi = self.get_band() \n        nspin, nkpts, nbands = band.shape\n        for spin in range(nspin):\n            print('Spin:', spin)  \n            CBM = None\n            for bandth in range(nbands):\n                shifted_band = band[spin,:,bandth] - efermi\n                if (shifted_band > 0.0).all() == True:\n                    CBM = band[spin,:, bandth]\n                    VBM = band[spin,:, bandth -1]                \n                    break\n                elif ((shifted_band < 0.0).any() == True) and ((shifted_band > 0.0).any() == True):\n                    print(\"This is a metal\")\n                    break\n                    \n            if CBM is not None:\n                vbm_idx = np.argmax(VBM)\n                cbm_idx = np.argmin(CBM)\n                bandgap = CBM[cbm_idx] - VBM[vbm_idx]\n                direct = False\n                if vbm_idx == cbm_idx: direct = True\n                \n                # TODO: the kpath_frac currently cannot be obtained form f25.\n                # Other outputs are needed\n                # kpath_frac = self.cp2k_io.kpath_frac[set_block]\n                # print('  E(VBM) = %7.4f at k = [%6.4f,%6.4f,%6.4f]' % (VBM[vbm_idx], \n                                                                # kpath_frac[vbm_idx,0], kpath_frac[vbm_idx,1], kpath_frac[vbm_idx,2]))\n                # print('  E(CBM) = %7.4f at k = [%6.4f,%6.4f,%6.4f]' % (CBM[cbm_idx], \n                                                                # kpath_frac[cbm_idx,0], kpath_frac[cbm_idx,1], kpath_frac[cbm_idx,2]))\n                if direct == True: \n                    print('  Direct bandgap   : %6.3f' % (bandgap))             \n                else:  \n                    print('  Indirect bandgap : %6.3f' % (bandgap))              \n                    gap1 = CBM[vbm_idx] - VBM[vbm_idx]\n                    gap2 = CBM[cbm_idx] - VBM[cbm_idx]\n                    direct_gap = min(gap1, gap2)\n                    print('  Direct bandgap   : %6.3f' % (direct_gap))\n \n    def _generate_band(self, efermi=None, spin=0, label=None):\n        '''Processing/collecting the band data before the plotting function\n        '''\n        band, proj_kpath, sym_kpoint_coor, efermi_ = self.get_band()\n        if efermi is None: efermi = efermi_  \n        band = band[spin] - efermi\n        \n        return band, proj_kpath, sym_kpoint_coor, label\n        \n    def plot_band(self, efermi=None, label=None, spin=0, save=False, band_color=['#007acc','#808080','#808080'],\n                    figsize=(6,6), figname='BAND', xlim=None, ylim=[-6,6], fontsize=18, dpi=600, format='png'):\n        '''Plot band structure\n           \n            Attribute:\n                efermi          : a Fermi level or a list of Fermi levels\n                spin            : 0  for spin unpolarized and LSORBIT = .TRUE.\n                                  0 or 1 for spin polarized\n                color           : a list of three color codes for band curves, high symmetric kpoint grid, and Fermi level\n                                  \n                                  \n        '''\n        assert isinstance(band_color,list)\n        assert len(band_color) == 3\n        plot.plot_band(self, efermi=efermi, spin=spin, save=save, band_color=band_color,\n                figsize=figsize, figname=figname, xlim=xlim, ylim=ylim, fontsize=fontsize, dpi=dpi, format=format, label=label)\n                \n    def _generate_phononband(self, unit=\"CM\", gamma_correct=False, threshold=8.06554, spin=0, label=None):\n        '''Processing/collecting the phnon band (cm^-1) data before the plotting function\n           Unit: CM = CM^-1, THZ = THz, MEV = meV\n        '''\n        band, proj_kpath, sym_kpoint_coor, efermi_ = self.get_band(phonon=True, gamma_correct=gamma_correct, threshold=threshold)        \n        if unit.lower() == \"thz\":\n            band = const.CMTOTHZ * band\n        elif unit.lower() == \"mev\":\n            band = const.CMTOMEV * band\n            \n        return band[spin], proj_kpath, sym_kpoint_coor, label\n        \n    def plot_phononband(self, unit=\"CM\", gamma_correct=False, threshold=8.06554, label=None, spin=0, save=False, band_color=['#007acc','#808080','#808080'],\n                    figsize=(6,6), figname='PHONONBAND', xlim=None, ylim=None, fontsize=18, dpi=600, format='png'):\n        '''Plot band structure\n           \n            Attribute:\n                efermi          : a Fermi level or a list of Fermi levels\n                spin            : 0  for spin unpolarized and LSORBIT = .TRUE.\n                                  0 or 1 for spin polarized\n                color           : a list of three color codes for band curves, high symmetric kpoint grid, and Fermi level\n                                  \n                                  \n        '''\n        assert isinstance(band_color,list)\n        assert len(band_color) == 3\n        plot.plot_phononband(self, unit=unit, gamma_correct=gamma_correct, threshold=threshold, spin=spin, save=save, band_color=band_color,\n                figsize=figsize, figname=figname, xlim=xlim, ylim=ylim, fontsize=fontsize, dpi=dpi, format=format, label=label)\n        \n", "meta": {"hexsha": "01dfc7dbe2cbc520feb2eea9896706de7d4949f9", "size": 8589, "ext": "py", "lang": "Python", "max_stars_repo_path": "mcu/crystal/crystal.py", "max_stars_repo_name": "rwoodsrobinson/mcu", "max_stars_repo_head_hexsha": "6bd8f29cffa4afb1a057322ea349a4889bffbe14", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2019-05-04T19:23:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T04:47:37.000Z", "max_issues_repo_path": "mcu/crystal/crystal.py", "max_issues_repo_name": "rwoodsrobinson/mcu", "max_issues_repo_head_hexsha": "6bd8f29cffa4afb1a057322ea349a4889bffbe14", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2019-07-25T09:20:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-29T17:46:31.000Z", "max_forks_repo_path": "mcu/crystal/crystal.py", "max_forks_repo_name": "rwoodsrobinson/mcu", "max_forks_repo_head_hexsha": "6bd8f29cffa4afb1a057322ea349a4889bffbe14", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2019-07-25T08:25:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T02:06:18.000Z", "avg_line_length": 47.1923076923, "max_line_length": 210, "alphanum_fraction": 0.5461636978, "include": true, "reason": "import numpy", "num_tokens": 2142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.16326372898133906}}
{"text": "\"\"\"\nColloid_Setup contains background classes and methods to prepare a\nmodel domain for colloid simulation. The user should not need to\nimport or call methods directly from this module.\n\"\"\"\n\nimport numpy as np\nfrom scipy import interpolate\nfrom copy import copy\nimport h5py as H\nimport sys\n\n\nclass Hdf5Reader(object):\n    \"\"\"\n    Hdf5 reader class to grab results from lattice Boltzmann model runs\n    to parameterize the colloid simulation. Consider moving this class to\n    the Colloid_IO module\n\n    Parameters:\n    ----------\n    :param str HDF_name: lattice boltzmann hdf file name.\n\n    :ivar np.ndarray imarray: binary image array defining model boundaries\n    :ivar np.ndarray uarry: velocity array of [y, x]\n    :ivar np.ndarray yu: y velocity array from lattice Boltzmann simulation\n    :ivar np.ndarray xu: x velocity array from lattice Boltzmann simulation\n    :ivar float mean_yu: mean velocity in the y direction\n    :ivar float mean_xu: mean velocity in the x direction\n    :ivar float velocity_factor: velocity dimensionalization factor\n    \"\"\"\n    def __init__(self, hdf_name):\n        hdf = H.File(hdf_name, 'r+')\n        self.imarray = hdf['Binary_image'][()]\n        self.uarray = hdf['results/uarray'][()]\n        self.yu = hdf['results/uarray'][()][0]\n        self.xu = hdf['results/uarray'][()][1]\n        self.mean_xu = hdf['results/mean_ux'][()]\n        self.mean_yu = hdf['results/mean_uy'][()]\n        self.velocity_factor = hdf['results/velocity_factor'][()]\n        hdf.close()\n\n\nclass GridArray(object):\n    \"\"\"\n    Gridarray class creates arrays of distances from pore spaces, corrects for\n    interpolation effects at pore boundaries, and creates vector arrays that are\n    later used to give direction to forces.\n\n    Parameters:\n    ----------\n    :param (np.array, bool) arr: Array of boolean porous media (segmented image array)\n    :param float gridres: model resolution in meters\n    :param int gridsplit: interpolation factor for refining grid mesh\n    :param bool solid: solid phase boolean identifier, default=True\n    \"\"\"\n    def __init__(self, arr, gridres, gridsplit, solid=True):\n        self.yarr = np.copy(arr.T)\n        self._vimgx, self._vimgy = self._create_vector_array(arr, solid)\n        self.__gridx, self.__vector_x = self._arrx(arr, self._vimgx, gridres, gridsplit)\n        self.__gridy, self.__vector_y = self._arry(self.yarr, self._vimgy, gridres, gridsplit)\n\n    @property\n    def gridx(self):\n        \"\"\"\n        :return: (np.array, np.float) Array of distances from nearest solid phase in the x-direction\n        \"\"\"\n        return copy(self.__gridx)\n\n    @property\n    def gridy(self):\n        \"\"\"\n        :return: (np.array, np.float) Array of distances from nearest solid phase in the y-direction\n        \"\"\"\n        return copy(self.__gridy)\n\n    @property\n    def vector_x(self):\n        \"\"\"\n        :return: (np.array, np.float) Array of specific vector directions in the x-direction (-1 == left, 1 == right)\n        \"\"\"\n        return copy(self.__vector_x)\n\n    @property\n    def vector_y(self):\n        \"\"\"\n        :return: (np.array, np.float) Array of specific vector directions in the y-direction (-1 == down, 1 == up)\n        \"\"\"\n        return copy(self.__vector_y)\n\n    def _create_vector_array(self, img, solid):\n        \"\"\"\n        creates an x-dir copy and y-dir copy of the image domain for vector\n        directions to populate.\n        \"\"\"\n        vimgx = np.copy(img)\n        vimgy = np.copy(img.T)\n        vimgx[vimgx == solid] = np.nan\n        vimgy[vimgy == solid] = np.nan\n        return vimgx, vimgy\n\n    def _arrx(self, arr, vector_x, gridres, gridsplit):\n        \"\"\"\n        Method that handles looping through array and sends it to distance_gridx\n        \"\"\"\n        for line in range(len(arr)):\n            arr[line], vector_x[line] = self._distance_gridx(arr[line], vector_x[line], gridres, gridsplit)\n        return arr, vector_x\n\n    def _arry(self, yarr, vector_y, gridres, gridsplit):\n        \"\"\"\n        Method that handles looping through array and sends it to distance_gridy\n        \"\"\"\n        for line in range(len(yarr)):\n            ylen = len(yarr[0])\n            yarr[line], vector_y[line] = self._distance_gridy(yarr[line], vector_y[line], gridres, ylen, gridsplit)\n        return yarr.T, vector_y.T\n    \n    def _distance_gridx(self, line, vline, gridres, gridsplit):\n        \"\"\"\n        Method uses linear interpolation to correct pore boundary space\n\n        Follows by creating an array of pore boundaries and then counts the distance\n        from the nearest solid. It also creates a a vector direction array that corresponds.\n        \"\"\"\n\n        # Saner(?) method which does not raise warnings from Python 2.7.12\n        # Forward compatable with Python 3.5.2\n        for i in range(len(line)):\n            if line[i] > 0.:\n                vline[i] = 1\n                line[i] = 1\n            else:\n                vline[i] = 0\n                line[i] = 0\n        np.array(line)\n        \n        # create an array of pore boundaries from binary system\n        boundary= np.where(np.abs(np.diff(line)) >= 1)[0]\n        try:\n            for i in range(1, len(boundary), 2):\n                rbound = boundary[i] + 1\n                lbound = boundary[i-1]\n                gap = rbound - lbound\n\n                if gap % 2 == 0:\n                    gap = gap//2\n\n                    if gridres > 1e-9:\n                        left = (np.arange(1, gap + 1) * gridres) - (gridres - 1e-9)\n                    else:\n                        left = np.arange(1, gap + 1) * gridres\n\n                    right = left[::-1]\n                    line[lbound:rbound] = np.append(left, right)\n\n                    left = np.ones(gap) * -1\n                    right = np.ones(gap)\n                    vline[lbound:rbound] = np.append(left, right)\n\n                else:\n                    gap = gap//2\n\n                    if gridres > 1e-9:\n                        left = (np.arange(1, gap + 2) * gridres) - (gridres - 1e-9)\n                        right = (np.arange(1, gap + 1) * gridres) - (gridres - 1e-9)\n                    else:\n                        left = np.arange(1, gap + 2) * gridres\n                        right = np.arange(1, gap + 1) * gridres\n\n                    line[lbound:rbound] = np.append(left, right)\n\n                    left = np.ones(gap + 1) * -1\n                    right = np.ones(gap)\n                    vline[lbound:rbound] = np.append(left, right)\n                    \n        except IndexError:\n            print('volume does not percolate')\n            sys.exit()\n        return line, vline\n\n    def _distance_gridy(self, line, vline, gridres, ylen, gridsplit):\n        '''\n        Method uses linear interpolation to correct pore boundary space\n\n        Follows by creating an array of pore boundaries and then counts the distance\n        from the nearest solid. It also creates a a vector direction array that corresponds.\n        '''\n        \n        for i in range(len(line)):\n            if line[i] > 0:\n                vline[i] = 1\n                line[i] = 1\n            else:\n                vline[i] = 0\n                line[i] = 0\n        np.array(line)\n        \n        # create an array of pore boundaries from binary system\n        boundary = np.where(np.abs(np.diff(line)) >= 1)[0]\n\n        if len(boundary) > 0:\n            rbound = boundary[0] + 1 \n            lbound = 0\n\n            if gridres > 1e-9:\n                # Use this statement to enforce nm scale DLVO @ boundary\n                top = (np.arange(rbound, lbound, -1) * gridres) - (gridres - 1e-9)\n            else:\n                top = np.arange(rbound, lbound, -1) * gridres\n\n            line[lbound:rbound] = top\n            vtop = np.ones(len(top)) * -1\n            vline[lbound:rbound] = vtop\n            \n            for i in range(2, len(boundary), 2):\n                rbound = boundary[i] + 1\n                lbound = boundary[i - 1] + 1\n                gap = rbound - lbound\n                if gap % 2 == 0:\n                    gap = gap // 2\n\n                    if gridres > 1e-9:\n                        # use this statement to enforce nm scale DLVO @ boundaries\n                        left = (np.arange(1, gap + 1) * gridres) - (gridres - 1e-9)\n                    else:\n                        left = np.arange(1, gap + 1) * gridres\n\n                    right = left[::-1]\n                    line[lbound:rbound] = np.append(left, right)\n\n                    left = np.ones(gap)\n                    right = np.ones(gap) * -1\n                    vline[lbound:rbound] = np.append(left, right)\n                    \n                else:\n                    gap = gap // 2\n\n                    if gridres > 1e-9:\n                        left = (np.arange(1, gap + 2) * gridres) - (gridres - 1e-9)\n                        right = (np.arange(1, gap + 1) * gridres) - (gridres - 1e-9)\n                    else:\n                        left = np.arange(1, gap + 2) * gridres\n                        right = np.arange(1, gap + 1) * gridres\n\n                    line[lbound:rbound] = np.append(left, right)\n\n                    left = np.ones(gap + 1)\n                    right = np.ones(gap) * -1\n                    vline[lbound:rbound] = np.append(left, right)\n                    \n            rbound = ylen\n            lbound = boundary[-1] + 1\n            gap = rbound - lbound\n\n            if gridres > 1e-9:\n                bottom = (np.arange(1, gap + 1) * gridres) - (gridres - 1e-9)\n            else:\n                bottom = np.arange(1, gap + 1) * gridres\n\n            line[lbound:rbound] = bottom\n\n            bottom = np.ones(gap)\n            vline[lbound:rbound] = bottom\n        else:\n            pass\n        return line, vline\n\n\ndef LBVArray(LBv, img):\n    \"\"\"\n    Method to create a velocity array for use in the colloid simulation model\n\n    Parameters:\n    ----------\n    :param np.ndarray LBv: lattice boltzmann velocity array\n    :param np.ndarray img: boolean image array\n\n    Returns:\n    -------\n    :return: np.ndarray of velocity\n    \"\"\"\n    vel = np.zeros((len(LBv), len(LBv[0])))\n    invert = np.invert(img.astype(bool))\n    vel = np.array([LBv[i] * invert[i] for i in range(len(LBv))])\n    print(vel.shape)\n    return vel\n\n\ndef InterpV(LBv, gridsplit, img=False):\n    \"\"\"\n    Interpolation method for the lattice Boltzmann velocity array\n\n    Parameters:\n    ----------\n    :param np.ndarray LBv: lattice boltzmann velocity array with pore boundaries enforced\n    :param float gridsplit: interpolation factor\n    :param bool img: flag to indicate boolean image interpolation or velocity interpolation\n\n    Returns:\n    -------\n    :return: (np.ndarray) interpolated velocity array\n    \"\"\"\n    ylen = len(LBv)\n    xlen = len(LBv[0])\n    xindex = np.arange(0, xlen)\n    yindex = np.arange(0, ylen)\n    ifactor = 1. / gridsplit\n    xnew = np.arange(0, xlen - 1 + (ifactor), ifactor)\n    ynew = np.arange(0, ylen - 1 + (ifactor), ifactor)\n    f = interpolate.interp2d(xindex, yindex, LBv, kind='linear')\n    znew = f(xnew, ynew)\n\n    if img:\n        # correct pore boundaries from interpolation\n        znew[znew >= ifactor * gridsplit / 2.] = 1  # 0] = 1# ifactor*gridsplit/2.] = 1\n        znew[znew < ifactor * gridsplit / 2.] = 0  # 0] = 0# ifactor*gridsplit/2.] = 0\n\n    return znew\n\n\n\n", "meta": {"hexsha": "4f372cde044d7593033483bfee5259c10243eed6", "size": 11337, "ext": "py", "lang": "Python", "max_stars_repo_path": "lb_colloids/Colloids/Colloid_Setup.py", "max_stars_repo_name": "jdlarsen-UA/LB-colloids", "max_stars_repo_head_hexsha": "92ad3cc8a08e8bdf4f468e55a3f5cf7bcc319a67", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-17T02:45:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T02:45:12.000Z", "max_issues_repo_path": "lb_colloids/Colloids/Colloid_Setup.py", "max_issues_repo_name": "Gweiqi/LB-colloids", "max_issues_repo_head_hexsha": "92ad3cc8a08e8bdf4f468e55a3f5cf7bcc319a67", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lb_colloids/Colloids/Colloid_Setup.py", "max_forks_repo_name": "Gweiqi/LB-colloids", "max_forks_repo_head_hexsha": "92ad3cc8a08e8bdf4f468e55a3f5cf7bcc319a67", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-12-28T21:06:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-17T02:45:10.000Z", "avg_line_length": 35.0990712074, "max_line_length": 117, "alphanum_fraction": 0.5440592749, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.28457601028405616, "lm_q1q2_score": 0.16325511237894635}}
{"text": "import numpy as np\nimport time\nimport os\nfrom atomistic_domains import Atom\nfrom typing import List\n\n\nclass Lattice:\n    \"\"\"\n    The class \"lattice\" defines methods which manipulate lattice structures.\n    Lattice structures have the following attributes:\n    :param type: Lattice type: e.g. fcc, hcp, bcc, etc.\n    :param box: Unit cell box dimensions (including tilt)\n    :param basis_atoms: List of atoms (of object class: atom) which make up the\n                                                primitive unit cell (in relative coordinates)\n    :param chem: List of chemical elements in alloy\n    :param num_el: Number of different elements present\n    :param num_atoms: number of atoms per each element (dictionary type)\n    :param tot_atoms: Total number of atoms in unit cell\n    \"\"\"\n\n    def __init__(\n        self,\n        x_vector: np.ndarray = np.zeros(shape=(1, 3)),\n        y_vector: np.ndarray = np.zeros(shape=(1, 3)),\n        z_vector: np.ndarray = np.zeros(shape=(1, 3)),\n        basis_atoms: List[Atom] = None,\n    ):\n        self.x_vector = x_vector\n        self.y_vector = y_vector\n        self.z_vector = z_vector\n        if not basis_atoms:\n            basis_atoms = []\n        else:\n            self.basis_atoms = basis_atoms\n        return\n\n    def add_atom(self, new_atom):\n        \"\"\"\n        Adds an atom to the list of basis atoms of the lattice. The new atom\n        must be of the type: \"atom\",\n        \"\"\"\n        self.basis_atoms.append(new_atom)\n        self.tot_atoms += 1\n        new = False\n        for i in range(self.num_el):\n            if new_atom.element == self.chem[i]:\n                new = True\n        if new == False:\n            self.chem.append(new_atom.element)\n            self.num_atoms[new_atom.element] = 0\n        self.num_atoms[new_atom.element] += 1\n\n        return\n\n    def genfromposcar(self, filename):\n        scale = np.genfromtxt(filename, skip_header=1, max_rows=1)\n        box = np.genfromtxt(filename, delimiter=\"\", skip_header=2, max_rows=3)\n        self.box = box\n        self.chem = np.genfromtxt(filename, delimiter=\"\", skip_header=5, max_rows=1, dtype=str)\n        self.num_el = len(self.chem)\n        atom_numbers = np.genfromtxt(filename, delimiter=\"\", skip_header=6, max_rows=1, dtype=int)\n        for i in range(self.num_el):\n            self.num_atoms[self.chem[i]] = atom_numbers[i]\n        self.tot_atoms = sum(atom_numbers)\n        ptype = np.genfromtxt(filename, delimiter=\">\", skip_header=7, max_rows=1, dtype=str)\n        if ptype == \"Selective Dynamics\":\n            eln = 0\n            j = 0\n            for i in range(self.tot_atoms):\n                if j < self.num_atoms[self.chem[eln]]:\n                    atomel = self.chem[eln]\n                    j += 1\n                else:\n                    eln += 1\n                    atomel = self.chem[eln]\n                    j = 1\n                acoord = np.genfromtxt(filename, delimiter=\"\", skip_header=9 + i, max_rows=1)[\n                    :, 0:3\n                ]\n                adyn = np.genfromtxt(\n                    filename, delimiter=\"\", skip_header=9 + i, max_rows=1, dtype=str\n                )[:, 3:]\n                newatom = atom(id=i + 1, element=atomel, pos=acoord, dyn=adyn)\n                self.basis_atoms.append(newatom)\n        else:\n            eln = 0\n            j = 0\n            for i in range(self.tot_atoms):\n                if j < self.num_atoms[self.chem[eln]]:\n                    atomel = self.chem[eln]\n                    j += 1\n                else:\n                    eln += 1\n                    atomel = self.chem[eln]\n                    j = 1\n                acoord = np.genfromtxt(filename, delimiter=\"\", skip_header=8 + i, max_rows=1)\n                newatom = atom(id=i + 1, element=atomel, pos=acoord)\n                self.basis_atoms.append(newatom)\n\n        mag_header = int(self.tot_atoms + 9)\n        self.mag_mom = np.genfromtxt(filename, delimiter=\"\", skip_header=mag_header)\n        if self.mag_mom.shape[0] != self.tot_atoms:\n            print(\n                \"WARNING: Insufficient number of magnetic moments. \\\n\t\t\t\t\tMagnetism ignored.\"\n            )\n            self.mag_mom = np.zeros(shape=(self.tot_atoms, 3))\n\n        for i in range(self.tot_atoms):\n            self.basis_atoms[i].mag_mom = self.mag_mom[i]\n\n        self.tot_atoms = len(self.basis_atoms)\n        print(self.tot_atoms)\n        return\n\n    def repeated_length(self, direction=np.zeros(shape=(1, 3))):\n        \"\"\"\n        Calculates the repeatable euclidian distance length of the unit cell in\n        the Miller Incex direction specified.\n        :param direction: Crystallographic direction of axis of interest\n        :return: repeatable length\n        \"\"\"\n        lengths = np.zeros(shape=(3, 1))\n\n        for i in range(3):\n            if direction[i] == 0:\n                lengths[i] = 1e6\n            else:\n                t = 0.5 * self.box[i, i] / float(direction[i])\n                lengths[i] = 2 * sqrt(\n                    (t * direction[0]) ** 2 + (t * direction[1]) ** 2 + (t * direction[2]) ** 2\n                )\n        rl = min(lengths)\n        return rl\n\n    def hexCij(c11, c12, c13, c33, c44):\n        \"\"\"\n        Populates 6x6 elastic tensor for hexagonal crystals\n        :param c11: c11 elastic constant\n        :param c12: c12 elastic constant\n        :param c13: c13 elastic constant\n        :param c44: c44 elastic constant\n        :return C: 6x6 elastic tensor for Voigt notation calculations\n        :return S: 6x6 compliance tensor for Voigt notation calculations\n        \"\"\"\n        C = np.zeros(shape=(6, 6))\n        C[0, 0] = C[1, 1] = c11\n        C[0, 1] = C[1, 0] = c12\n        C[0, 2] = C[2, 0] = C[1, 2] = C[2, 1] = c13\n        C[2, 2] = c33\n        C[3, 3] = C[4, 4] = c44\n        C[5, 5] = 0.5 * (c11 - c12)\n        S = np.linalg.inv(C)\n        return {\"C\": C, \"S\": S}\n", "meta": {"hexsha": "2fcb67e006d662ccf3aad31764bf386b5c8dfd50", "size": 5875, "ext": "py", "lang": "Python", "max_stars_repo_path": "lattice.py", "max_stars_repo_name": "ianbakst/atomisticdomains", "max_stars_repo_head_hexsha": "c0c3b9bc5aa5e425e043ec25da91357cc4d9b308", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lattice.py", "max_issues_repo_name": "ianbakst/atomisticdomains", "max_issues_repo_head_hexsha": "c0c3b9bc5aa5e425e043ec25da91357cc4d9b308", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lattice.py", "max_forks_repo_name": "ianbakst/atomisticdomains", "max_forks_repo_head_hexsha": "c0c3b9bc5aa5e425e043ec25da91357cc4d9b308", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6602564103, "max_line_length": 98, "alphanum_fraction": 0.5412765957, "include": true, "reason": "import numpy", "num_tokens": 1526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.16325510889813571}}
{"text": "'''\nREFER TO: https://github.com/ej0cl6/pytorch-adversarial-examples/blob/master/attackers.py\n'''\n\n# Copyright (c) 2018-present, Royal Bank of Canada.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom advertorch.utils import calc_l2distsq\nfrom advertorch.utils import tanh_rescale\nfrom advertorch.utils import torch_arctanh\nfrom advertorch.utils import clamp\nfrom advertorch.utils import to_one_hot\nfrom advertorch.utils import replicate_input\n\nfrom advertorch.attacks.base import Attack\nfrom advertorch.attacks.base import LabelMixin\nfrom advertorch.attacks.utils import is_successful\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\n\n\nclass Attacker:\n    def __init__(self, clip_max=0.5, clip_min=-0.5):\n        self.clip_max = clip_max\n        self.clip_min = clip_min\n\n    def generate(self, model, x, y):\n        pass\n\n\nclass FGSM(Attacker):\n    \"\"\"\n    Fast Gradient Sign Method\n    Ian J. Goodfellow, Jonathon Shlens, Christian Szegedy.\n    Explaining and Harnessing Adversarial Examples.\n    ICLR, 2015\n    \"\"\"\n\n    def __init__(self, eps=0.15, clip_max=0.5, clip_min=-0.5):\n        super(FGSM, self).__init__(clip_max, clip_min)\n        self.eps = eps\n\n    def generate(self, model, x, y):\n        model.eval()\n        nx = torch.unsqueeze(x, 0)\n        ny = torch.unsqueeze(y, 0)\n        nx.requires_grad_()\n        out = model(nx)\n        loss = F.cross_entropy(out, ny)\n        loss.backward()\n        x_adv = nx + self.eps * torch.sign(nx.grad.data)\n        x_adv.clamp_(self.clip_min, self.clip_max)\n        x_adv.squeeze_(0)\n\n        return x_adv.detach()\n\n\nclass BIM(Attacker):\n    \"\"\"\n    Basic Iterative Method\n    Alexey Kurakin, Ian J. Goodfellow, Samy Bengio.\n    Adversarial Examples in the Physical World.\n    arXiv, 2016\n    \"\"\"\n\n    def __init__(self, eps=0.15, eps_iter=0.01, n_iter=50, clip_max=0.5, clip_min=-0.5):\n        super(BIM, self).__init__(clip_max, clip_min)\n        self.eps = eps\n        self.eps_iter = eps_iter\n        self.n_iter = n_iter\n\n    def generate(self, model, x, y):\n        model.eval()\n        nx = torch.unsqueeze(x, 0)\n        ny = torch.unsqueeze(y, 0)\n        nx.requires_grad_()\n        eta = torch.zeros(nx.shape)\n\n        for i in range(self.n_iter):\n            out = model(nx + eta)\n            loss = F.cross_entropy(out, ny)\n            loss.backward()\n\n            eta += self.eps_iter * torch.sign(nx.grad.data)\n            eta.clamp_(-self.eps, self.eps)\n            nx.grad.data.zero_()\n\n        x_adv = nx + eta\n        x_adv.clamp_(self.clip_min, self.clip_max)\n        x_adv.squeeze_(0)\n\n        return x_adv.detach()\n\n\nclass DeepFool(Attacker):\n    \"\"\"\n    DeepFool\n    Seyed-Mohsen Moosavi-Dezfooli, Alhussein Fawzi, Pascal Frossard\n    DeepFool: A Simple and Accurate Method to Fool Deep Neural Networks.\n    CVPR, 2016\n    \"\"\"\n\n    def __init__(self, model,max_iter=50, clip_max=0.5, clip_min=-0.5,epsilon=0.00784):\n        super(DeepFool, self).__init__(clip_max, clip_min)\n        self.max_iter = max_iter\n        self.model = model\n        self.epsilon = epsilon\n\n    def perturb(self,x,y):\n        x = x.detach().clone()\n        adv = torch.zeros_like(x)\n        for i in range (x.size()[0]):\n            adv[i] = self.generate(x[i],y[i])\n        return adv.detach()\n\n\n    def generate(self, x, y):\n        model = self.model\n        model.eval()\n        nx = torch.unsqueeze(x.detach().clone(),0)\n        nx.requires_grad_()\n        eta = torch.zeros_like(nx) # instead of torch.zeors(nx.shape)\n\n        out = model(nx + eta)\n        n_class = out.shape[1]\n        py = out.max(1)[1].item()\n        ny = out.max(1)[1].item()\n\n        i_iter = 0\n\n        while py == ny and i_iter < self.max_iter  :\n            out[0, py].backward(retain_graph=True)\n            grad_np = nx.grad.data.clone()\n            value_l = np.inf\n            ri = None\n\n            for i in range(n_class):\n                if i == py:\n                    continue\n\n                nx.grad.data.zero_()\n                out[0, i].backward(retain_graph=True)\n                grad_i = nx.grad.data.clone()\n\n                wi = grad_i - grad_np\n                fi = out[0, i] - out[0, py]\n                value_i = np.abs(fi.item()) / np.linalg.norm(wi.cpu().numpy().flatten())\n\n                if value_i < value_l:\n                    ri = value_i / np.linalg.norm(wi.cpu().numpy().flatten()) * wi\n\n            eta += ri.clone()\n            eta.clamp_(-self.epsilon,self.epsilon)\n\n            nx.grad.data.zero_()\n            out = model(nx + eta)\n            py = out.max(1)[1].item()\n            i_iter += 1\n\n        x_adv = nx + eta\n\n        x_adv.clamp_(self.clip_min, self.clip_max)\n        x_adv.squeeze_(0)\n\n        return x_adv.detach()\n\n\n\nCARLINI_L2DIST_UPPER = 1e10\nCARLINI_COEFF_UPPER = 1e10\nINVALID_LABEL = -1\nREPEAT_STEP = 10\nONE_MINUS_EPS = 0.999999\nUPPER_CHECK = 1e9\nPREV_LOSS_INIT = 1e6\nTARGET_MULT = 10000.0\nNUM_CHECKS = 10\n\n\nclass CarliniWagnerL2Attack(Attack, LabelMixin):\n    \"\"\"\n    The Carlini and Wagner L2 Attack, https://arxiv.org/abs/1608.04644\n    :param predict: forward pass function.\n    :param num_classes: number of clasess.\n    :param confidence: confidence of the adversarial examples.\n    :param targeted: if the attack is targeted.\n    :param learning_rate: the learning rate for the attack algorithm\n    :param binary_search_steps: number of binary search times to find the\n        optimum\n    :param max_iterations: the maximum number of iterations\n    :param abort_early: if set to true, abort early if getting stuck in local\n        min\n    :param initial_const: initial value of the constant c\n    :param clip_min: mininum value per input dimension.\n    :param clip_max: maximum value per input dimension.\n    :param loss_fn: loss function\n    \"\"\"\n\n    def __init__(self, predict, num_classes, epsilon=0.00784,confidence=0,\n                 targeted=False, learning_rate=0.01,\n                 binary_search_steps=9, max_iterations=10000,\n                 abort_early=True, initial_const=1e-3,\n                 clip_min=0., clip_max=1., loss_fn=None):\n        \"\"\"Carlini Wagner L2 Attack implementation in pytorch.\"\"\"\n        if loss_fn is not None:\n            import warnings\n            warnings.warn(\n                \"This Attack currently do not support a different loss\"\n                \" function other than the default. Setting loss_fn manually\"\n                \" is not effective.\"\n            )\n\n        loss_fn = None\n\n        super(CarliniWagnerL2Attack, self).__init__(\n            predict, loss_fn, clip_min, clip_max)\n\n        self.learning_rate = learning_rate\n        self.max_iterations = max_iterations\n        self.binary_search_steps = binary_search_steps\n        self.abort_early = abort_early\n        self.confidence = confidence\n        self.initial_const = initial_const\n        self.num_classes = num_classes\n        # The last iteration (if we run many steps) repeat the search once.\n        self.repeat = binary_search_steps >= REPEAT_STEP\n        self.targeted = targeted\n        self.epsilon = epsilon\n\n    def _loss_fn(self, output, y_onehot, l2distsq, const):\n        # TODO: move this out of the class and make this the default loss_fn\n        #   after having targeted tests implemented\n        real = (y_onehot * output).sum(dim=1)\n\n        # TODO: make loss modular, write a loss class\n        other = ((1.0 - y_onehot) * output - (y_onehot * TARGET_MULT)\n                 ).max(1)[0]\n        # - (y_onehot * TARGET_MULT) is for the true label not to be selected\n\n        if self.targeted:\n            loss1 = clamp(other - real + self.confidence, min=0.)\n        else:\n            loss1 = clamp(real - other + self.confidence, min=0.)\n        loss2 = (l2distsq).sum()\n        loss1 = torch.sum(const * loss1)\n        loss = loss1 + loss2\n        return loss\n\n    def _is_successful(self, output, label, is_logits):\n        # determine success, see if confidence-adjusted logits give the right\n        #   label\n\n        if is_logits:\n            output = output.detach().clone()\n            if self.targeted:\n                output[torch.arange(len(label)).long(),\n                       label] -= self.confidence\n            else:\n                output[torch.arange(len(label)).long(),\n                       label] += self.confidence\n            pred = torch.argmax(output, dim=1)\n        else:\n            pred = output\n            if pred == INVALID_LABEL:\n                return pred.new_zeros(pred.shape).byte()\n\n        return is_successful(pred, label, self.targeted)\n\n\n    def _forward_and_update_delta(\n            self, optimizer, x_atanh, delta, y_onehot, loss_coeffs):\n\n        optimizer.zero_grad()\n        adv = tanh_rescale(delta + x_atanh, self.clip_min, self.clip_max)\n        transimgs_rescale = tanh_rescale(x_atanh, self.clip_min, self.clip_max)\n        output = self.predict(adv)\n        l2distsq = calc_l2distsq(adv, transimgs_rescale)\n        loss = self._loss_fn(output, y_onehot, l2distsq, loss_coeffs)\n        loss.backward()\n        optimizer.step()\n\n        return loss.item(), l2distsq.data, output.data, adv.data\n\n\n    def _get_arctanh_x(self, x):\n        result = clamp((x - self.clip_min) / (self.clip_max - self.clip_min),\n                       min=0., max=1.) * 2 - 1\n        return torch_arctanh(result * ONE_MINUS_EPS)\n\n    def _update_if_smaller_dist_succeed(\n            self, adv_img, labs, output, l2distsq, batch_size,\n            cur_l2distsqs, cur_labels,\n            final_l2distsqs, final_labels, final_advs):\n\n        target_label = labs\n        output_logits = output\n        _, output_label = torch.max(output_logits, 1)\n\n        mask = (l2distsq < cur_l2distsqs) & self._is_successful(\n            output_logits, target_label, True)\n\n        cur_l2distsqs[mask] = l2distsq[mask]  # redundant\n        cur_labels[mask] = output_label[mask]\n\n        mask = (l2distsq < final_l2distsqs) & self._is_successful(\n            output_logits, target_label, True)\n        final_l2distsqs[mask] = l2distsq[mask]\n        final_labels[mask] = output_label[mask]\n        final_advs[mask] = adv_img[mask]\n\n    def _update_loss_coeffs(\n            self, labs, cur_labels, batch_size, loss_coeffs,\n            coeff_upper_bound, coeff_lower_bound):\n\n        # TODO: remove for loop, not significant, since only called during each\n        # binary search step\n        for ii in range(batch_size):\n            cur_labels[ii] = int(cur_labels[ii])\n            if self._is_successful(cur_labels[ii], labs[ii], False):\n                coeff_upper_bound[ii] = min(\n                    coeff_upper_bound[ii], loss_coeffs[ii])\n\n                if coeff_upper_bound[ii] < UPPER_CHECK:\n                    loss_coeffs[ii] = (\n                        coeff_lower_bound[ii] + coeff_upper_bound[ii]) / 2\n            else:\n                coeff_lower_bound[ii] = max(\n                    coeff_lower_bound[ii], loss_coeffs[ii])\n                if coeff_upper_bound[ii] < UPPER_CHECK:\n                    loss_coeffs[ii] = (\n                        coeff_lower_bound[ii] + coeff_upper_bound[ii]) / 2\n                else:\n                    loss_coeffs[ii] *= 10\n\n\n    def perturb(self, x, y=None):\n        x, y = self._verify_and_process_inputs(x, y)\n\n        # Initialization\n        if y is None:\n            y = self._get_predicted_label(x)\n        x = replicate_input(x)\n        batch_size = len(x)\n        coeff_lower_bound = x.new_zeros(batch_size)\n        coeff_upper_bound = x.new_ones(batch_size) * CARLINI_COEFF_UPPER\n        loss_coeffs = torch.ones_like(y).float() * self.initial_const\n        final_l2distsqs = [CARLINI_L2DIST_UPPER] * batch_size\n        final_labels = [INVALID_LABEL] * batch_size\n        final_advs = x\n        x_atanh = self._get_arctanh_x(x)\n        y_onehot = to_one_hot(y, self.num_classes).float()\n\n        final_l2distsqs = torch.FloatTensor(final_l2distsqs).to(x.device)\n        final_labels = torch.LongTensor(final_labels).to(x.device)\n\n        # Start binary search\n        for outer_step in range(self.binary_search_steps):\n            delta = nn.Parameter(torch.zeros_like(x))\n            optimizer = optim.Adam([delta], lr=self.learning_rate)\n            cur_l2distsqs = [CARLINI_L2DIST_UPPER] * batch_size\n            cur_labels = [INVALID_LABEL] * batch_size\n            cur_l2distsqs = torch.FloatTensor(cur_l2distsqs).to(x.device)\n            cur_labels = torch.LongTensor(cur_labels).to(x.device)\n            prevloss = PREV_LOSS_INIT\n\n            if (self.repeat and outer_step == (self.binary_search_steps - 1)):\n                loss_coeffs = coeff_upper_bound\n            for ii in range(self.max_iterations):\n                loss, l2distsq, output, adv_img = \\\n                    self._forward_and_update_delta(\n                        optimizer, x_atanh, delta, y_onehot, loss_coeffs)\n                if self.abort_early:\n                    if ii % (self.max_iterations // NUM_CHECKS or 1) == 0:\n                        if loss > prevloss * ONE_MINUS_EPS:\n                            break\n                        prevloss = loss\n\n                self._update_if_smaller_dist_succeed(\n                    adv_img, y, output, l2distsq, batch_size,\n                    cur_l2distsqs, cur_labels,\n                    final_l2distsqs, final_labels, final_advs)\n\n            self._update_loss_coeffs(\n                y, cur_labels, batch_size,\n                loss_coeffs, coeff_upper_bound, coeff_lower_bound)\n\n        #calculate perturbation\n        eta = final_advs - x\n        eta.clamp_(-self.epsilon,self.epsilon)\n        final_advs = x + eta\n\n        return final_advs", "meta": {"hexsha": "3e35b1eb2efb24557fcad3b3ece5d801c4f98374", "size": 13914, "ext": "py", "lang": "Python", "max_stars_repo_path": "attackers.py", "max_stars_repo_name": "leeyegy/Tiny-ImageNet", "max_stars_repo_head_hexsha": "d09d49761e246823a2eeeb1b6dad658ccd8effd4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "attackers.py", "max_issues_repo_name": "leeyegy/Tiny-ImageNet", "max_issues_repo_head_hexsha": "d09d49761e246823a2eeeb1b6dad658ccd8effd4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "attackers.py", "max_forks_repo_name": "leeyegy/Tiny-ImageNet", "max_forks_repo_head_hexsha": "d09d49761e246823a2eeeb1b6dad658ccd8effd4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1867321867, "max_line_length": 89, "alphanum_fraction": 0.6077332183, "include": true, "reason": "import numpy", "num_tokens": 3421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.16315595762929777}}
{"text": "'''\nThis includes the module to realize the transformation between mesh and location map.\nPart of the codes is adapted from https://github.com/Lotayou/densebody_pytorch\n'''\n\nfrom time import time\nfrom tqdm import tqdm\nfrom numpy.linalg import solve\nfrom os.path import join\nimport torch\nfrom torch import nn\nimport os\nimport torch.nn.functional as F\n\nimport pickle\nimport numpy as np\nimport pdb\n\n'''\nIndex_UV_Generator is used to transform mesh and location map\nThe verts is in shape (B * V *C)\nThe UV map is in shape (B * H * W * C)\nB: batch size;     V: vertex number;   C: channel number\nH: height of uv map;  W: width of uv map\n'''\nclass Index_UV_Generator(nn.Module):\n    def __init__(self, UV_height, UV_width=-1, uv_type='BF', data_dir=None):\n        super(Index_UV_Generator, self).__init__()\n\n        if uv_type == 'SMPL':\n            obj_file = 'smpl_fbx_template_expanded.obj'\n        elif uv_type == 'BF':\n            obj_file = 'smpl_boundry_free_template_expanded.obj'\n\n        self.uv_type = uv_type\n\n        if data_dir is None:\n            d = os.path.dirname(__file__)\n            data_dir = os.path.join(d, '..', 'data', 'uv_sampler')\n        self.data_dir = data_dir\n        self.h = UV_height\n        self.w = self.h if UV_width < 0 else UV_width\n        self.obj_file = obj_file\n        self.para_file = 'paras_h{:04d}_w{:04d}_{}.npz'.format(self.h, self.w, self.uv_type)\n\n        if not os.path.isfile(join(data_dir, self.para_file)):\n            self.process()\n\n        para = np.load(join(data_dir, self.para_file))\n\n        self.v_index = torch.LongTensor(para['v_index'])\n        self.bary_weights = torch.FloatTensor(para['bary_weights'])\n        self.vt2v = torch.LongTensor(para['vt2v'])\n        self.vt_count = torch.FloatTensor(para['vt_count'])\n        self.texcoords = torch.FloatTensor(para['texcoords'])\n        self.texcoords = 2 * self.texcoords - 1\n        self.mask = torch.ByteTensor(para['mask'].astype('uint8'))\n\n    def process(self):\n        ##############################################################################\n        # Load template obj file\n        print('Loading obj file')\n        with open(join(self.data_dir, self.obj_file), 'r') as fin:\n            lines = [l\n                     for l in fin.readlines()\n                     if len(l.split()) > 0\n                     and not l.startswith('#')\n                     ]\n\n        # Load all vertices (v) and texcoords (vt)\n        vertices = []\n        texcoords = []\n\n        for line in lines:\n            lsp = line.split()\n            if lsp[0] == 'v':\n                x = float(lsp[1])\n                y = float(lsp[2])\n                z = float(lsp[3])\n                vertices.append((x, y, z))\n            elif lsp[0] == 'vt':\n                u = float(lsp[1])\n                v = float(lsp[2])\n                # texcoords.append((1 - v, u))\n                texcoords.append((u, v))\n\n\n        # Stack these into an array\n        vertices = np.vstack(vertices).astype(np.float32)\n        texcoords = np.vstack(texcoords).astype(np.float32)\n\n        # Load face data. All lines are of the form:\n        # f v1/vt1/vn1 v2/vt2/vn2 v3/vt3/vn3\n        # Store the texcoord faces and a mapping from texcoord faces to vertex faces\n        vt_faces = []\n        v_num = vertices.shape[0]\n        vt_num = texcoords.shape[0]\n        vt2v = np.zeros(vt_num).astype('int64') - 1\n        v2vt = [None] * v_num\n        for i in range(v_num):\n            v2vt[i] = set()\n\n        for line in lines:\n            vs = line.split()\n            if vs[0] == 'f':\n                v0 = int(vs[1].split('/')[0]) - 1\n                v1 = int(vs[2].split('/')[0]) - 1\n                v2 = int(vs[3].split('/')[0]) - 1\n                vt0 = int(vs[1].split('/')[1]) - 1\n                vt1 = int(vs[2].split('/')[1]) - 1\n                vt2 = int(vs[3].split('/')[1]) - 1\n                vt_faces.append((vt0, vt1, vt2))\n\n                vt2v[vt0] = v0\n                vt2v[vt1] = v1\n                vt2v[vt2] = v2\n\n                v2vt[v0].add(vt0)\n                v2vt[v1].add(vt1)\n                v2vt[v2].add(vt2)\n\n        vt_faces = np.vstack(vt_faces)\n        vt_count = np.zeros(v_num)\n        for v_id in range(v_num):\n            vt_count[v_id] = len(v2vt[v_id])\n\n        ############################################################################\n        # Calculating the barycentric weights used for UV map generation\n        print('Calculating barycentric weights')\n        s = time()\n        h = self.h\n        w = self.w\n        face_num = vt_faces.shape[0]\n\n        face_id = np.zeros((h, w), dtype=np.int)\n        bary_weights = np.zeros((h, w, 3), dtype=np.float32)\n        # uvs = texcoords * np.array([[h - 1, w - 1]])\n        uvs = texcoords * np.array([[w - 1, h - 1]])\n        grids = np.ones((face_num, 3), dtype=np.float32)\n        anchors = np.concatenate((\n            uvs[vt_faces].transpose(0, 2, 1),\n            np.ones((face_num, 1, 3), dtype=uvs.dtype)\n        ), axis=1)  # [F * 3 * 3]\n\n        _loop = tqdm(np.arange(h * w), ncols=80)\n        for i in _loop:\n            r = i // w\n            c = i % w\n            # grids[:, 0] = r\n            # grids[:, 1] = c\n\n            grids[:, 0] = c\n            grids[:, 1] = r\n\n            weights = solve(anchors, grids)  # not enough accuracy?\n            inside = np.logical_and.reduce(weights.T > 1e-10)\n            index = np.where(inside == True)[0]\n\n            if 0 == index.size:\n                face_id[r, c] = -1  # just assign random id with all zero weights.\n            # elif index.size > 1:\n            #    print('bad %d' %i)\n            else:\n                face_id[r, c] = index[0]\n                bary_weights[r, c] = weights[index[0]]\n\n        v_index = vt2v[vt_faces[face_id]]\n        mask = face_id >= 0\n        v_index[face_id < 0, :] = 0\n        bary_weights[face_id < 0, :] = 0\n        print('Calculating finished. Time elapsed: {}s'.format(time() - s))\n\n        ############################################################################\n        # Ensure the neighboring pixels of vt on the UV map are meaningful\n        tex = torch.FloatTensor(texcoords) * torch.FloatTensor([[w-1, h-1]])\n        u_grid = tex[:, 0]\n        u_lo = u_grid.floor().long().clamp(min=0, max=w - 1)\n        u_hi = (u_lo + 1).clamp(max=w - 1)\n        u_grid = torch.min(u_hi.float(), u_grid)\n        u_w = u_grid - u_lo.float()\n\n        v_grid = tex[:, 1]\n        v_lo = v_grid.floor().long().clamp(min=0, max=h - 1)\n        v_hi = (v_lo + 1).clamp(max=h - 1)\n        v_grid = torch.min(v_hi.float(), v_grid)\n        v_w = v_grid - v_lo.float()\n\n        w_vlo_ulo = (1.0 - u_w) * (1.0 - v_w)\n        w_vlo_uhi = u_w * (1.0 - v_w)\n        w_vhi_ulo = (1.0 - u_w) * v_w\n        w_vhi_uhi = u_w * v_w\n\n        w = torch.cat([w_vlo_ulo, w_vlo_uhi, w_vhi_ulo, w_vhi_uhi], dim=0)\n        u = torch.cat([u_lo, u_hi, u_lo, u_hi], dim=0)\n        v = torch.cat([v_lo, v_lo, v_hi, v_hi], dim=0)\n        v_id = torch.LongTensor(vt2v).repeat(4)        # The function repeat for ndarray and tensor are different!\n\n        w_sorted, sort_index = w.sort(dim=0, descending=True)\n        u_sorted = u[sort_index]\n        v_sorted = v[sort_index]\n        v_id_sorted = v_id[sort_index]\n\n        # asign the empty pixel with the value of the 1 vt with maximal weights\n        n_expand = 0\n        for i in range(len(w_sorted)):\n            m = mask[v_sorted[i], u_sorted[i]]\n            if not m:\n                v_index[v_sorted[i], u_sorted[i], 0] = v_id_sorted[i]\n                bary_weights[v_sorted[i], u_sorted[i], 0] = 1\n                mask[v_sorted[i], u_sorted[i]] = 1\n                n_expand += 1\n\n        np.savez(join(self.data_dir, self.para_file),\n                 v_index=v_index,\n                 bary_weights=bary_weights,\n                 texcoords=texcoords,\n                 vt2v=vt2v,\n                 vt_count=vt_count,\n                 mask=mask,\n                 )\n\n\n    def get_UV_map(self, verts):\n        '''every pixel in UV map is determined by 3 adjacent vertices\n        '''\n        self.bary_weights = self.bary_weights.type(verts.dtype).to(verts.device) # shape: [res, res, 3]\n        self.v_index = self.v_index.to(verts.device) # shape: [res, res, 3]\n\n        if verts.dim() == 2:\n            verts = verts.unsqueeze(0)\n\n        im = verts[:, self.v_index, :]\n        bw = self.bary_weights[:, :, None, :]\n        im = torch.matmul(bw, im).squeeze(dim=3)\n        return im\n\n    def resample(self, uv_map):\n        batch_size, _, _, channel_num = uv_map.shape\n        v_num = self.vt_count.shape[0]\n        self.texcoords = self.texcoords.type(uv_map.dtype).to(uv_map.device)\n        self.vt2v = self.vt2v.to(uv_map.device)\n        self.vt_count = self.vt_count.type(uv_map.dtype).to(uv_map.device)\n\n        uv_grid = self.texcoords[None, None, :, :].expand(batch_size, -1, -1, -1)\n\n        vt = F.grid_sample(uv_map.permute(0, 3, 1, 2), uv_grid, mode='bilinear')\n        vt = vt.squeeze(2).permute(0, 2, 1)\n        v = vt.new_zeros([batch_size, v_num, channel_num])\n        v.index_add_(1, self.vt2v, vt)\n        v = v / self.vt_count[None, :, None]\n        return v\n\n    # just used for the generation of GT UVmaps\n    def forward(self, verts):\n        return self.get_UV_map(verts)\n\n    # generate part map\n    def gen_part_map(self, face_part):\n        part_map = np.zeros(self.bary_id.shape) - 1\n        mask = self.bary_id >= 0\n        part_map[mask] = face_part[self.bary_id[mask]]\n        # plt.imshow(part_map)\n        # part_map = self._dilate(torch.tensor(part_map+1)[None,:,:,None].float()).squeeze().numpy() -1\n        return part_map\n\n\n# Compute the weight map in UV space according to human body parts.\ndef cal_uv_weight(sampler, out_path):\n\n    with open('data/segm_per_v_overlap.pkl', 'rb') as f:\n        tmp = pickle.load(f)\n\n    part_names = ['hips',\n                  'leftUpLeg',\n                  'rightUpLeg',\n                  'spine',\n                  'leftLeg',\n                  'rightLeg',\n                  'spine1',\n                  'leftFoot',\n                  'rightFoot',\n                  'spine2',\n                  'leftToeBase',\n                  'rightToeBase',\n                  'neck',\n                  'leftShoulder',\n                  'rightShoulder',\n                  'head',\n                  'leftArm',\n                  'rightArm',\n                  'leftForeArm',\n                  'rightForeArm',\n                  'leftHand',\n                  'rightHand',\n                  'leftHandIndex1',\n                  'rightHandIndex1']\n\n    part_weight = torch.tensor([1, 5, 5, 1, 5, 5, 1, 25, 25, 1, 25, 25, 2, 1, 1, 2, 5, 5, 5, 5, 25, 25, 25, 25])\n\n    vert_part = torch.zeros([6890, 24])\n    for i in range(24):\n        key = part_names[i]\n        verts = tmp[key]\n        vert_part[verts, i] = 1\n\n    part_map = sampler.get_UV_map(vert_part).squeeze(0)\n    part_map = part_map > 0\n    weight_map = part_weight[None, None, :].float() * part_map.float()\n    weight_map = weight_map.max(dim=-1)[0]\n    weight_map = weight_map / weight_map.mean()\n\n    np.save(out_path, weight_map.numpy())\n    return\n\n\n\n\n", "meta": {"hexsha": "e28d2c51dd62568999a0881014681bd1a64b02b3", "size": 11149, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/uv_generator.py", "max_stars_repo_name": "SheldonTsui/stylegan2-ada-pytorch", "max_stars_repo_head_hexsha": "731d87d6cc6ba3d02c12fd54db908f7f312b74c6", "max_stars_repo_licenses": ["BSD-Source-Code"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-03T12:17:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-03T12:17:27.000Z", "max_issues_repo_path": "scripts/uv_generator.py", "max_issues_repo_name": "SheldonTsui/stylegan2-ada-pytorch", "max_issues_repo_head_hexsha": "731d87d6cc6ba3d02c12fd54db908f7f312b74c6", "max_issues_repo_licenses": ["BSD-Source-Code"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/uv_generator.py", "max_forks_repo_name": "SheldonTsui/stylegan2-ada-pytorch", "max_forks_repo_head_hexsha": "731d87d6cc6ba3d02c12fd54db908f7f312b74c6", "max_forks_repo_licenses": ["BSD-Source-Code"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0597484277, "max_line_length": 114, "alphanum_fraction": 0.5172661225, "include": true, "reason": "import numpy,from numpy", "num_tokens": 3058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.29421497216298875, "lm_q1q2_score": 0.1631335167456447}}
{"text": "#!/usr/bin/env python\n\"\"\"\nProgram to generate sample SANS datasets for neural network training. A\nmodified version of compare_multi.py.\n\nThe program writes datafiles as result_<modelname>_<run_number> to the out/\ndirectory. See example_data.dat for a sample of the file format used.\n\n**TODOS**\n\n* don't save q, dq with every dataset\n* use hdf5 rather than sqlite\n\n\"\"\"\nfrom __future__ import print_function\n\nfrom copy import deepcopy\nimport argparse\nimport os\nimport resource\nimport sys\nimport time\nimport traceback\nfrom collections import OrderedDict, namedtuple\nimport sqlite3\nimport logging\nimport fnmatch\n\nimport numpy as np  # type: ignore\n\nfrom sasmodels import core as sascore\nfrom sasmodels import compare as sascomp\nfrom sasmodels import data as sasdata\n\nfrom . import sas_io\nfrom .util.utils import columnize\n\nMODELS = sascore.list_models()\n\n# Maxim @ stackoverflow\n# https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse/43357954#43357954\n# (with mods by PAK)\ndef str2bool(value):\n    \"\"\"parse boolean argument\"\"\"\n    if isinstance(value, bool):\n       return value\n    value = value.lower()\n    if value in ('yes', 'true', 't', 'y', '1'):\n        return True\n    elif value in ('no', 'false', 'f', 'n', '0'):\n        return False\n    else:\n        raise argparse.ArgumentTypeError('Boolean value (1/0, Y[es]/N[o], T[rue]/F[alse]) expected.')\n\nparser = argparse.ArgumentParser(\n    description=\"\"\"\n    A script that generates SANS datasets for use in neural network training.\"\"\")\nparser.add_argument(\n    \"models\", nargs='*',\n    help=f\"A list of models or kinds ({', '.join(sascore.KINDS)}).\"\n         f\" A pattern such as *sphere will select all sphere models.\")\nparser.add_argument(\n    \"-x\", \"--exclude\", type=str, default=\"\",\n    help=\"Exclude specific models separated by commas.\")\nparser.add_argument(\n    \"--tag\", type=str, default=\"train\",\n    help=\"Tag for the generated data: train, test or validate.\")\nparser.add_argument(\n    \"--database\", type=str, default=sas_io.DB_FILE,\n    help=\"Path to the sqlite database file.\")\nparser.add_argument(\n    \"--count\", type=int, default=1000,\n    help=\"Count is the number of distinct models to generate.\")\nparser.add_argument(\n    \"--template\", type=str, default=\"\",\n    help=\"SANS dataset defining q and resolution.\")\nparser.add_argument(\n    \"--resolution\", type=float, default=3,\n    help=\"Constant dQ/Q resolution percentage.\")\nparser.add_argument(\n    \"--noise\", type=float, default=2,\n    help=\"Constant dI/I uncertainty percentage.\")\nparser.add_argument(\n    \"--dimension\", choices=('1D', '2D'), default='1D',\n    help=\"Choose whether to generate 1D or 2D data.\")\nparser.add_argument(\n    \"--npoint\", type=int, default=128,\n    help=\"The number of points per model.\")\nparser.add_argument(\n    \"--mono\", type=str2bool, default=True,\n    help=\"Force all models to be monodisperse.\")\nparser.add_argument(\n    \"--magnetic\", type=str2bool, default=False,\n    help=\"Allow magnetic parameters in the model\")\nparser.add_argument(\n    \"--cutoff\", type=float, default=0.,\n    help=\"\"\"\n    CUTOFF is the cutoff value to use for the polydisperse distribution.\n    Weights below the cutoff will be ignored.\"\"\")\nparser.add_argument(\n    \"--precision\", default='default',\n    choices=['default', 'single', 'double', 'fast', 'single!', 'double!', 'quad!'],\n    help=\"\"\"\n    Precision to use in floating point calculations. If postfixed with\n    an '!', builds a DLL for the CPU. If default, use single unless the\n    model requires double.\"\"\")\nparser.add_argument(\n    \"-v\", \"--verbose\",\n    help=\"Verbose output level.\", choices=[0, 1, 2])\n\n\n# noinspection PyTypeChecker\ndef gen_data(model_name, data, count=1, noise=2,\n             mono=True, magnetic=False, cutoff=1e-5,\n             maxdim=np.inf, precision='double'):\n    r\"\"\"\n    Generates the data for the given model and parameters.\n\n    *model_name* is the name of the model.\n\n    *data* is the data object giving $q, \\Delta q$ calculation points.\n\n    *N* is the number of comparisons to make.\n\n    *cutoff* is the polydispersity weight cutoff to make the calculation\n    a little bit faster.\n\n    *maxdim* is maximum value for any shape dimension.\n\n    *precision* is the name of the calculation engine to use.\n\n    Returns iterator *(seed, pars, data), ...* where *pars* is\n    *{par: value, ...}* and *data* is *(q, dq, iq, diq)*.\n    \"\"\"\n    is2d = False\n    assert data.x.size > 0\n    model_info = sascore.load_model_info(model_name)\n    calculator = sascomp.make_engine(model_info, data, precision, cutoff)\n    default_pars = sascomp.get_pars(model_info)\n    assert calculator._data.x.size > 0\n    x, dx = calculator._data.x, calculator._data.dx\n\n    # A not very clean macro for evaluating the models, wich uses name and\n    # seed from the current scope even though they haven't been defined yet.\n    def simulate(pars):\n        \"\"\"\n        Generate a random dataset for *fn* evaluated at *pars*.\n        Returns *(x, dx, y, dy)*, o.\n\n        Note that this replaces the data object within *fn*.\n        \"\"\"\n        # TODO: support 2D data, which does not use x, dx, y, dy\n        try:\n            assert calculator._data.x.size > 0\n            calculator.simulate_data(noise=noise, **pars)\n            assert calculator._data.x.size > 0\n            data = calculator._data\n            # TODO: Do we need to copy? [Yes if data.y is reused.]\n            result = (x, dx, data.y.copy(), data.dy.copy())\n        except Exception:\n            traceback.print_exc()\n            print(f\"Error when generating {model_name} for {seed}\")\n            result = (x, dx, np.NaN*x, np.NaN*x)\n            #raise\n        return result\n\n    def pretty(pars):\n        \"\"\"\n        Pretty the parameter set for displaying on one line\n        \"\"\"\n        parlist = sascomp.parlist(model_info, pars, is2d)\n        parlist = parlist.replace(os.linesep, '  ')\n        parlist = parlist.replace(': ', '=')\n        return parlist\n\n    t0 = -np.inf\n    interval = 5\n    for k in range(count):\n        seed = np.random.randint(int(1e6))\n        t1 = time.perf_counter()\n        if t1 > t0 + interval:\n            print(f\"generating {model_name} {k+1} of {count}\")\n            t0 = t1\n\n        # Generate parameters\n        with sascomp.push_seed(seed):\n            pars = sascomp.randomize_pars(model_info, default_pars, maxdim)\n        sascomp.constrain_pars(model_info, pars)\n        if mono:\n            pars = sascomp.suppress_pd(pars)\n        if not magnetic:\n            pars = sascomp.suppress_magnetism(pars)\n        pars.update({'scale': 1, 'background': 1e-5})\n        #print(f\"{model_name} {seed} {pretty(pars)}\")\n\n        # Evaluate model\n        data = simulate(pars) # q, dq, iq, diq\n\n        # Skip data sets with NaN or negative numbers.\n        # Note: some datasets will have fewer entries than others.\n        if np.isnan(data[2]).any():\n            print(f\">>> NaN in {model_name} {seed} {pretty(pars)}\")\n            continue\n        if (data[2] <= 0.).any():\n            print(f\">>> Negative values in {model_name} {seed} {pretty(pars)}\")\n            continue\n\n        yield seed, pars, data\n\n    # TODO: can free the calculator now\n    print(f\"Complete {model_name}\")\n\ndef model_group(models, required=False):\n    \"\"\"\n    Build a list of models from the items in *models*.  Could be individual\n    model names or could be a unix-style glob pattern.\n    \"\"\"\n    good = []\n    bad = []\n    for name in models:\n        if name == \"\":\n            continue\n        items = fnmatch.filter(MODELS, name)\n        if not items:\n            try:\n                items = sascore.list_models(name)\n            except ValueError:\n                pass\n        if items:\n            good.extend(items)\n        else:\n            bad.append(name)\n\n    if bad:\n        print(f\"Bad model(s): {', '.join(bad)}.  \", file=sys.stderr)\n    if bad or (required and not good):\n        print(f\"Use kind ({', '.join(sascore.KINDS)}) or one of:\", file=sys.stderr)\n        print(columnize(MODELS, indent=\"  \"), file=sys.stderr, end='')\n        print(f\"Patterns such as *sphere will also work.\")\n        sys.exit(1)\n\n    return sorted(set(good))\n\ndef run_model(opts):\n    tag = opts.tag\n    count = opts.count\n    is2D = opts.dimension.startswith('2d')\n    nq = opts.npoint\n    mono = opts.mono\n    magnetic = opts.magnetic\n    cutoff = opts.cutoff if not mono else 0\n    precision = opts.precision\n    res = opts.resolution\n    noise = opts.noise\n\n    # Figure out which models we are using.\n    include = model_group(opts.models, required=True)\n    exclude = model_group(opts.exclude.split(','))\n    model_list = sorted(set(include)-set(exclude))\n    print(\"Selected models:\\n\", columnize(model_list, indent=\"  \"))\n\n    if opts.template:\n        # Fetch q, dq from an actual SANS file\n        data, index = sasdata.read(opts.template), None\n    else:\n        # Generate\n        data, index = sascomp.make_data({\n            'qmin': 1e-4, 'qmax': 0.2, 'is2d': is2D, 'nq': nq, 'res': res/100,\n            'accuracy': 'Low', 'view': 'log', 'zero': False,\n            })\n\n    # Open database and lookup model counts.\n    db = sas_io.sql_connect(opts.database)\n    model_counts = sas_io.model_counts(db, tag)\n    #print(model_counts)\n    for model in model_list:\n        # Figure out how many more entries we need for the model\n        missing = count - model_counts.get(model, 0)\n        if missing <= 0:\n            continue\n        # TODO: should not need deepcopy(data) but something is messing with q\n        seq = gen_data(\n            model, deepcopy(data), count=missing, mono=mono, magnetic=magnetic,\n            cutoff=cutoff, precision=precision, noise=noise)\n        # Process the missing entries batch by batch so if there is an\n        # error we won't lose the entire group.\n        for batch in chunk(seq, batch_size=100):\n            sas_io.write_sql(db, model, batch, tag=tag)\n            #sas_io.write_1d(path, model, items, tag=tag)\n    #sas_io.read_sql(db, tag)\n    db.close()\n\ndef chunk(seq, batch_size):\n    \"\"\"\n    Generic iter tool: chunk sequence in groups of *batch_size*.\n\n    Remaining items are returned in final group.\n    \"\"\"\n    batch = []\n    for item in seq:\n        if len(batch) == batch_size:\n            yield batch\n            batch = []\n        batch.append(item)\n    yield batch\n\ndef main():\n    logging.basicConfig(level=logging.INFO)\n    opts = parser.parse_args()\n\n    time_start = time.perf_counter()\n    run_model(opts)\n    time_end = time.perf_counter() - time_start\n    print('Total computation time (s): %.2f' % (time_end / 10))\n    print('Total memory usage: %.2f' %\n          resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n    # Units of mem are OS dependent\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "07bed276cdcf9d9d9fcdfce603d43012e82b51df", "size": 10763, "ext": "py", "lang": "Python", "max_stars_repo_path": "sasnets/sasgen.py", "max_stars_repo_name": "martintb/sasnets", "max_stars_repo_head_hexsha": "82d44fc38c795603f887529ef653b1cc0bc3234f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sasnets/sasgen.py", "max_issues_repo_name": "martintb/sasnets", "max_issues_repo_head_hexsha": "82d44fc38c795603f887529ef653b1cc0bc3234f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sasnets/sasgen.py", "max_forks_repo_name": "martintb/sasnets", "max_forks_repo_head_hexsha": "82d44fc38c795603f887529ef653b1cc0bc3234f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-14T21:07:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-14T21:07:39.000Z", "avg_line_length": 33.5295950156, "max_line_length": 101, "alphanum_fraction": 0.6308650005, "include": true, "reason": "import numpy", "num_tokens": 2700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.16313351584488725}}
{"text": "\"\"\"\nHoneycomb\n=========\n\n\"\"\"\n\nimport numpy as np\n\n\nfrom .cof import Cof\nfrom .vertices import LinearVertex, NonLinearVertex\nfrom ..topology_graph import Edge\n\n\nclass Honeycomb(Cof):\n    \"\"\"\n    Represents a honeycomb COF topology graph.\n\n    Unoptimized construction\n\n    .. moldoc::\n\n        import moldoc.molecule as molecule\n        import stk\n\n        bb1 = stk.BuildingBlock('BrCCBr', [stk.BromoFactory()])\n        bb2 = stk.BuildingBlock('BrCC(CBr)CBr', [stk.BromoFactory()])\n\n        cof = stk.ConstructedMolecule(\n            topology_graph=stk.cof.Honeycomb(\n                building_blocks=(bb1, bb2),\n                lattice_size=(3, 3, 1),\n            ),\n        )\n        moldoc_display_molecule = molecule.Molecule(\n            atoms=(\n                molecule.Atom(\n                    atomic_number=atom.get_atomic_number(),\n                    position=position,\n                ) for atom, position in zip(\n                    cof.get_atoms(),\n                    cof.get_position_matrix(),\n                )\n            ),\n            bonds=(\n                molecule.Bond(\n                    atom1_id=bond.get_atom1().get_id(),\n                    atom2_id=bond.get_atom2().get_id(),\n                    order=(\n                        1\n                        if bond.get_order() == 9\n                        else bond.get_order()\n                    ),\n                ) for bond in cof.get_bonds()\n            ),\n        )\n\n    ``Collapser(scale_steps=False)`` optimized construction\n\n    .. moldoc::\n\n        import moldoc.molecule as molecule\n        import stk\n\n        bb1 = stk.BuildingBlock('BrCCBr', [stk.BromoFactory()])\n        bb2 = stk.BuildingBlock('BrCC(CBr)CBr', [stk.BromoFactory()])\n\n        cof = stk.ConstructedMolecule(\n            topology_graph=stk.cof.Honeycomb(\n                building_blocks=(bb1, bb2),\n                lattice_size=(3, 3, 1),\n                optimizer=stk.Collapser(scale_steps=False),\n            ),\n        )\n        moldoc_display_molecule = molecule.Molecule(\n            atoms=(\n                molecule.Atom(\n                    atomic_number=atom.get_atomic_number(),\n                    position=position,\n                ) for atom, position in zip(\n                    cof.get_atoms(),\n                    cof.get_position_matrix(),\n                )\n            ),\n            bonds=(\n                molecule.Bond(\n                    atom1_id=bond.get_atom1().get_id(),\n                    atom2_id=bond.get_atom2().get_id(),\n                    order=(\n                        1\n                        if bond.get_order() == 9\n                        else bond.get_order()\n                    ),\n                ) for bond in cof.get_bonds()\n            ),\n        )\n\n    Building blocks with three and two functional groups are required\n    for this topology graph.\n\n    When using a :class:`dict` for the `building_blocks` parameter,\n    as in :ref:`cof-topology-graph-examples`:\n    *Multi-Building Block COF Construction*, a\n    :class:`.BuildingBlock`, with the following number of functional\n    groups, needs to be assigned to each of the following vertex ids:\n\n        | 3-functional groups: 0 to 1\n        | 2-functional groups: 2 to 4\n\n    See :class:`.Cof` for more details and examples.\n\n    \"\"\"\n\n    _lattice_constants = _a, _b, _c = (\n        np.array([1., 0., 0.]),\n        np.array([0.5, 0.866, 0]),\n        np.array([0, 0, 5/1.7321])\n    )\n\n    _vertex_prototypes = (\n        NonLinearVertex(0, (1/3)*_a + (1/3)*_b + (1/2)*_c),\n        NonLinearVertex(1, (2/3)*_a + (2/3)*_b + (1/2)*_c),\n    )\n\n    _vertex_prototypes = (\n        *_vertex_prototypes,\n        LinearVertex.init_at_center(\n            id=2,\n            vertices=(_vertex_prototypes[0], _vertex_prototypes[1]),\n        ),\n        LinearVertex.init_at_shifted_center(\n            id=3,\n            vertices=(_vertex_prototypes[0], _vertex_prototypes[1]),\n            cell_shifts=((0, 0, 0), (0, -1, 0)),\n            lattice_constants=_lattice_constants,\n        ),\n        LinearVertex.init_at_shifted_center(\n            id=4,\n            vertices=(_vertex_prototypes[0], _vertex_prototypes[1]),\n            cell_shifts=((0, 0, 0), (-1, 0, 0)),\n            lattice_constants=_lattice_constants,\n        )\n    )\n\n    _edge_prototypes = (\n        Edge(0, _vertex_prototypes[2], _vertex_prototypes[0]),\n        Edge(1, _vertex_prototypes[2], _vertex_prototypes[1]),\n\n        Edge(2, _vertex_prototypes[3], _vertex_prototypes[0]),\n        Edge(\n            id=3,\n            vertex1=_vertex_prototypes[3],\n            vertex2=_vertex_prototypes[1],\n            periodicity=(0, -1, 0),\n        ),\n\n        Edge(4, _vertex_prototypes[4], _vertex_prototypes[0]),\n        Edge(\n            id=5,\n            vertex1=_vertex_prototypes[4],\n            vertex2=_vertex_prototypes[1],\n            periodicity=(-1, 0, 0),\n        )\n    )\n", "meta": {"hexsha": "dc192bc86a14d2196160dd0427996790c39602c0", "size": 4890, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/stk/molecular/topology_graphs/cof/honeycomb.py", "max_stars_repo_name": "andrewtarzia/stk", "max_stars_repo_head_hexsha": "1ac2ecbb5c9940fe49ce04cbf5603fd7538c475a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2018-04-12T16:25:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T23:05:43.000Z", "max_issues_repo_path": "src/stk/molecular/topology_graphs/cof/honeycomb.py", "max_issues_repo_name": "JelfsMaterialsGroup/stk", "max_issues_repo_head_hexsha": "0d3e1b0207aa6fa4d4d5ee8dfe3a29561abb08a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-03-19T12:36:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-11T12:46:00.000Z", "max_forks_repo_path": "src/stk/molecular/topology_graphs/cof/honeycomb.py", "max_forks_repo_name": "supramolecular-toolkit/stk", "max_forks_repo_head_hexsha": "0d3e1b0207aa6fa4d4d5ee8dfe3a29561abb08a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-08-07T13:00:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T00:55:10.000Z", "avg_line_length": 29.6363636364, "max_line_length": 69, "alphanum_fraction": 0.5145194274, "include": true, "reason": "import numpy", "num_tokens": 1177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.2942149597859341, "lm_q1q2_score": 0.1631335055508203}}
{"text": "#!/usr/bin/env python3\n#\n# Script to calculate the integral of one or multiple cube file\n# by Patrick Melix\n# 2022/04/04\n#\n# You can import the module and then call .main() or use it as a script\nfrom curses import has_key\nfrom pymatgen.io.vasp.outputs import Chgcar\nfrom pymatgen.io.ase import AseAtomsAdaptor\nfrom ase.io.cube import write_cube\nimport numpy as np\nimport os\n\n\ndef main(inFiles, outFiles, verbose=True, return_integrals=False, return_spin_integrals=False, mult_volume=False):\n    assert len(inFiles) == len(outFiles), \"Number of input and output files must be equal!\"\n    integrals = []\n    spin_integrals = []\n    for iFile,inFile in enumerate(inFiles):\n        if not os.path.isfile(inFile):\n            raise ValueError('File {:} does not exist'.format(inFile))\n\n        #if output exists mv to .bak\n        if os.path.isfile(outFiles[iFile]):\n            if verbose: print('ATTENTION: {:} exists, moving to *.bak'.format(outFiles[iFile]))\n            os.rename(outFiles[iFile], outFiles[iFile]+'.bak')\n\n        if verbose: print(\"Reading {}\".format(inFile))\n        full_chgcar = Chgcar.from_file(inFile)\n        spinpol = 'diff' in full_chgcar.data.keys()\n        if return_spin_integrals and not spinpol:\n            raise ValueError(\"File {} is not spinpolarized!\".format(inFile))\n        shape = full_chgcar.data['total'].shape\n        n_data = np.prod(shape)\n        \n        if return_integrals:\n            integrals.append(np.sum(np.abs(full_chgcar.data['total'])))\n            integrals[-1] /= n_data\n        if return_spin_integrals:\n            spin_integrals.append(np.sum(np.abs(full_chgcar.data['diff'])))\n            spin_integrals[-1] /= n_data\n        if verbose:\n            print(\"Shape of data: {}\".format(shape))\n            print(\"Total number of datapoints: {}\".format(n_data))\n            if return_integrals:\n                integral = integrals[-1]\n            else:\n                integral = np.sum(np.abs(full_chgcar.data['total']))\n                integral /= n_data\n            print(\"Integral of total data is {}\".format(integral))\n            if spinpol:\n                if return_spin_integrals:\n                    spin_integral = spin_integrals[-1]\n                else:\n                    spin_integral = np.sum(np.abs(full_chgcar.data['diff']))\n                    spin_integral /= n_data\n                print(\"Integral of diff data is {}\".format(spin_integral))\n\n            origin = np.zeros(3)\n            atoms = AseAtomsAdaptor.get_atoms(full_chgcar.structure)\n\n            #Contrary to VASP Wiki, the CHGCAR is not rho*V, but rho*n_data.\n            #So in order to have the integral over space = nelectrons, we need to divide by n_data.\n            #Since this would result in super small numbers, we can transform to rho*V\n            factor = n_data\n            if mult_volume:\n                factor /= atoms.get_volume()\n            full_chgcar.data['total'] /= factor\n            if spinpol: full_chgcar.data['diff'] /= factor\n            #write cube\n            filename = \"{}.cube\".format(outFiles[iFile])\n            if verbose: print(\"Writing {}\".format(filename))\n            with open(filename, 'w') as f:\n                write_cube(f, atoms, data=full_chgcar.data['total'], origin=origin)\n            if spinpol:\n                filename = \"{}_mag.cube\".format(outFiles[iFile])\n                if verbose: print(\"Writing {}\".format(filename))\n                with open(filename, 'w') as f:\n                    write_cube(f, atoms, data=full_chgcar.data['diff'], origin=origin)\n                \n    if return_integrals:\n        if len(integrals) == 1:\n            if return_spin_integrals: return integrals[0], spin_integrals[0]\n            else: return integrals[0]\n        else:\n            if return_spin_integrals: return integrals, spinpol\n            else: return integrals\n    else:\n        return\n\n\n\nif __name__ == \"__main__\":\n    import argparse\n    parser = argparse.ArgumentParser(description='Sum up cube files')\n    parser.add_argument('input', type=str, nargs='+', help='Input Files')\n    parser.add_argument('-output', type=str, nargs='+', help='Output File Names (no extension)')\n    parser.add_argument('-v', help='Verbose', action='store_true')\n    parser.add_argument('--volume', help='Multiply the Density with the Cell Volume', action='store_true')\n    args = parser.parse_args()\n    main(args.input, args.output, verbose=args.v, mult_volume=args.volume)", "meta": {"hexsha": "63ca83a712374f3e7da187c67dbb335f7b275cb3", "size": 4452, "ext": "py", "lang": "Python", "max_stars_repo_path": "chgcar2cube.py", "max_stars_repo_name": "patrickmelix/VASP-tools", "max_stars_repo_head_hexsha": "b33811793e176cf61f678e60a85ae984bf74b150", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-10T07:42:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T12:24:10.000Z", "max_issues_repo_path": "chgcar2cube.py", "max_issues_repo_name": "patrickmelix/VASP-tools", "max_issues_repo_head_hexsha": "b33811793e176cf61f678e60a85ae984bf74b150", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chgcar2cube.py", "max_forks_repo_name": "patrickmelix/VASP-tools", "max_forks_repo_head_hexsha": "b33811793e176cf61f678e60a85ae984bf74b150", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.6470588235, "max_line_length": 114, "alphanum_fraction": 0.6111859838, "include": true, "reason": "import numpy", "num_tokens": 1029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.1629168661698401}}
{"text": "'''\nBuild a simple neural machine translation model\n'''\nimport theano\nimport theano.tensor as tensor\nfrom theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams\n\nimport cPickle as pkl\nimport ipdb\nimport numpy\nimport copy\n\nimport os\nimport warnings\nimport sys\nimport time\n\nfrom collections import OrderedDict\n\nfrom data_iterator import TextIterator\n\nprofile = False\n\n\n# push parameters to Theano shared variables\ndef zipp(params, tparams):\n    for kk, vv in params.iteritems():\n        tparams[kk].set_value(vv)\n\n\n# pull parameters from Theano shared variables\ndef unzip(zipped):\n    new_params = OrderedDict()\n    for kk, vv in zipped.iteritems():\n        new_params[kk] = vv.get_value()\n    return new_params\n\n\n# get the list of parameters: Note that tparams must be OrderedDict\ndef itemlist(tparams):\n    return [vv for kk, vv in tparams.iteritems()]\n\n\n# dropout\ndef dropout_layer(state_before, use_noise, trng):\n    proj = tensor.switch(\n        use_noise,\n        state_before * trng.binomial(state_before.shape, p=0.5, n=1,\n                                     dtype=state_before.dtype),\n        state_before * 0.5)\n    return proj\n\n\n# make prefix-appended name\ndef _p(pp, name):\n    return '%s_%s' % (pp, name)\n\n\n# initialize Theano shared variables according to the initial parameters\ndef init_tparams(params):\n    tparams = OrderedDict()\n    for kk, pp in params.iteritems():\n        tparams[kk] = theano.shared(params[kk], name=kk)\n    return tparams\n\n\n# load parameters\ndef load_params(path, params):\n    pp = numpy.load(path)\n    for kk, vv in params.iteritems():\n        if kk not in pp:\n            warnings.warn('%s is not in the archive' % kk)\n            continue\n        params[kk] = pp[kk]\n\n    return params\n\n# layers: 'name': ('parameter initializer', 'feedforward')\nlayers = {'ff': ('param_init_fflayer', 'fflayer'),\n          'gru': ('param_init_gru', 'gru_layer'),\n          'gru_cond_simple': ('param_init_gru_cond_simple',\n                              'gru_cond_simple_layer'),\n          }\n\n\ndef get_layer(name):\n    fns = layers[name]\n    return (eval(fns[0]), eval(fns[1]))\n\n\n# some utilities\ndef ortho_weight(ndim):\n    W = numpy.random.randn(ndim, ndim)\n    u, s, v = numpy.linalg.svd(W)\n    return u.astype('float32')\n\n\ndef norm_weight(nin, nout=None, scale=0.01, ortho=True):\n    if nout is None:\n        nout = nin\n    if nout == nin and ortho:\n        W = ortho_weight(nin)\n    else:\n        W = scale * numpy.random.randn(nin, nout)\n    return W.astype('float32')\n\n\ndef tanh(x):\n    return tensor.tanh(x)\n\n\ndef linear(x):\n    return x\n\n\ndef concatenate(tensor_list, axis=0):\n    \"\"\"\n    Alternative implementation of `theano.tensor.concatenate`.\n    This function does exactly the same thing, but contrary to Theano's own\n    implementation, the gradient is implemented on the GPU.\n    Backpropagating through `theano.tensor.concatenate` yields slowdowns\n    because the inverse operation (splitting) needs to be done on the CPU.\n    This implementation does not have that problem.\n    :usage:\n        >>> x, y = theano.tensor.matrices('x', 'y')\n        >>> c = concatenate([x, y], axis=1)\n    :parameters:\n        - tensor_list : list\n            list of Theano tensor expressions that should be concatenated.\n        - axis : int\n            the tensors will be joined along this axis.\n    :returns:\n        - out : tensor\n            the concatenated tensor expression.\n    \"\"\"\n    concat_size = sum(tt.shape[axis] for tt in tensor_list)\n\n    output_shape = ()\n    for k in range(axis):\n        output_shape += (tensor_list[0].shape[k],)\n    output_shape += (concat_size,)\n    for k in range(axis + 1, tensor_list[0].ndim):\n        output_shape += (tensor_list[0].shape[k],)\n\n    out = tensor.zeros(output_shape)\n    offset = 0\n    for tt in tensor_list:\n        indices = ()\n        for k in range(axis):\n            indices += (slice(None),)\n        indices += (slice(offset, offset + tt.shape[axis]),)\n        for k in range(axis + 1, tensor_list[0].ndim):\n            indices += (slice(None),)\n\n        out = tensor.set_subtensor(out[indices], tt)\n        offset += tt.shape[axis]\n\n    return out\n\n\n# batch preparation, returns padded batches for both source and target\n# sequences with their corresponding masks\ndef prepare_data(seqs_x, seqs_y, maxlen=None,\n                 n_words_src=30000, n_words=30000):\n\n    # x: a list of sentences\n    lengths_x = [len(s) for s in seqs_x]\n    lengths_y = [len(s) for s in seqs_y]\n\n    # filter sequences according to maximum sequence length\n    if maxlen is not None:\n        new_seqs_x = []\n        new_seqs_y = []\n        new_lengths_x = []\n        new_lengths_y = []\n        for l_x, s_x, l_y, s_y in zip(lengths_x, seqs_x, lengths_y, seqs_y):\n            if l_x < maxlen and l_y < maxlen:\n                new_seqs_x.append(s_x)\n                new_lengths_x.append(l_x)\n                new_seqs_y.append(s_y)\n                new_lengths_y.append(l_y)\n        lengths_x = new_lengths_x\n        seqs_x = new_seqs_x\n        lengths_y = new_lengths_y\n        seqs_y = new_seqs_y\n\n        if len(lengths_x) < 1 or len(lengths_y) < 1:\n            return None, None, None, None\n\n    n_samples = len(seqs_x)\n    maxlen_x = numpy.max(lengths_x) + 1\n    maxlen_y = numpy.max(lengths_y) + 1\n\n    # pad batches and create masks\n    x = numpy.zeros((maxlen_x, n_samples)).astype('int64')\n    y = numpy.zeros((maxlen_y, n_samples)).astype('int64')\n    x_mask = numpy.zeros((maxlen_x, n_samples)).astype('float32')\n    y_mask = numpy.zeros((maxlen_y, n_samples)).astype('float32')\n    for idx, [s_x, s_y] in enumerate(zip(seqs_x, seqs_y)):\n        x[:lengths_x[idx], idx] = s_x\n        x_mask[:lengths_x[idx]+1, idx] = 1.\n        y[:lengths_y[idx], idx] = s_y\n        y_mask[:lengths_y[idx]+1, idx] = 1.\n\n    return x, x_mask, y, y_mask\n\n\n# feedforward layer: affine transformation + point-wise nonlinearity\ndef param_init_fflayer(options, params, prefix='ff', nin=None, nout=None,\n                       ortho=True):\n    if nin is None:\n        nin = options['dim_proj']\n    if nout is None:\n        nout = options['dim_proj']\n    params[_p(prefix, 'W')] = norm_weight(nin, nout, scale=0.01, ortho=ortho)\n    params[_p(prefix, 'b')] = numpy.zeros((nout,)).astype('float32')\n\n    return params\n\n\ndef fflayer(tparams, state_below, options, prefix='rconv',\n            activ='lambda x: tensor.tanh(x)', **kwargs):\n    return eval(activ)(\n        tensor.dot(state_below, tparams[_p(prefix, 'W')]) +\n        tparams[_p(prefix, 'b')])\n\n\n# GRU layer\ndef param_init_gru(options, params, prefix='gru', nin=None, dim=None):\n\n    if nin is None:\n        nin = options['dim_proj']\n    if dim is None:\n        dim = options['dim_proj']\n\n    # embedding to gates transformation weights, biases\n    W = numpy.concatenate([norm_weight(nin, dim),\n                           norm_weight(nin, dim)], axis=1)\n    params[_p(prefix, 'W')] = W\n    params[_p(prefix, 'b')] = numpy.zeros((2 * dim,)).astype('float32')\n\n    # recurrent transformation weights for gates\n    U = numpy.concatenate([ortho_weight(dim),\n                           ortho_weight(dim)], axis=1)\n    params[_p(prefix, 'U')] = U\n\n    # embedding to hidden state proposal weights, biases\n    Wx = norm_weight(nin, dim)\n    params[_p(prefix, 'Wx')] = Wx\n    params[_p(prefix, 'bx')] = numpy.zeros((dim,)).astype('float32')\n\n    # recurrent transformation weights for hidden state proposal\n    Ux = ortho_weight(dim)\n    params[_p(prefix, 'Ux')] = Ux\n\n    return params\n\n\ndef gru_layer(tparams, state_below, options, prefix='gru', mask=None,\n              **kwargs):\n    nsteps = state_below.shape[0]\n    if state_below.ndim == 3:\n        n_samples = state_below.shape[1]\n    else:\n        n_samples = 1\n\n    dim = tparams[_p(prefix, 'Ux')].shape[1]\n\n    if mask is None:\n        mask = tensor.alloc(1., state_below.shape[0], 1)\n\n    # utility function to slice a tensor\n    def _slice(_x, n, dim):\n        if _x.ndim == 3:\n            return _x[:, :, n*dim:(n+1)*dim]\n        return _x[:, n*dim:(n+1)*dim]\n\n    # state_below is the input word embeddings\n    # input to the gates, concatenated\n    state_below_ = tensor.dot(state_below, tparams[_p(prefix, 'W')]) + \\\n        tparams[_p(prefix, 'b')]\n    # input to compute the hidden state proposal\n    state_belowx = tensor.dot(state_below, tparams[_p(prefix, 'Wx')]) + \\\n        tparams[_p(prefix, 'bx')]\n\n    # step function to be used by scan\n    # arguments    | sequences |outputs-info| non-seqs\n    def _step_slice(m_, x_, xx_,  h_,          U, Ux):\n        preact = tensor.dot(h_, U)\n        preact += x_\n\n        # reset and update gates\n        r = tensor.nnet.sigmoid(_slice(preact, 0, dim))\n        u = tensor.nnet.sigmoid(_slice(preact, 1, dim))\n\n        # compute the hidden state proposal\n        preactx = tensor.dot(h_, Ux)\n        preactx = preactx * r\n        preactx = preactx + xx_\n\n        # hidden state proposal\n        h = tensor.tanh(preactx)\n\n        # leaky integrate and obtain next hidden state\n        h = u * h_ + (1. - u) * h\n        h = m_[:, None] * h + (1. - m_)[:, None] * h_\n\n        return h\n\n    # prepare scan arguments\n    seqs = [mask, state_below_, state_belowx]\n    init_states = [tensor.alloc(0., n_samples, dim)]\n    _step = _step_slice\n    shared_vars = [tparams[_p(prefix, 'U')],\n                   tparams[_p(prefix, 'Ux')]]\n\n    rval, updates = theano.scan(_step,\n                                sequences=seqs,\n                                outputs_info=init_states,\n                                non_sequences=shared_vars,\n                                name=_p(prefix, '_layers'),\n                                n_steps=nsteps,\n                                profile=profile,\n                                strict=True)\n    rval = [rval]\n    return rval\n\n\n# Conditional GRU layer without Attention\ndef param_init_gru_cond_simple(options, params, prefix='gru_cond', nin=None,\n                               dim=None, dimctx=None):\n    if nin is None:\n        nin = options['dim']\n    if dim is None:\n        dim = options['dim']\n    if dimctx is None:\n        dimctx = options['dim']\n\n    params = param_init_gru(options, params, prefix, nin=nin, dim=dim)\n\n    # context to GRU gates\n    Wc = norm_weight(dimctx, dim*2)\n    params[_p(prefix, 'Wc')] = Wc\n\n    # context to hidden proposal\n    Wcx = norm_weight(dimctx, dim)\n    params[_p(prefix, 'Wcx')] = Wcx\n\n    return params\n\n\ndef gru_cond_simple_layer(tparams, state_below, options, prefix='gru',\n                          mask=None, context=None, one_step=False,\n                          init_state=None,\n                          **kwargs):\n\n    assert context, 'Context must be provided'\n\n    if one_step:\n        assert init_state, 'previous state must be provided'\n\n    nsteps = state_below.shape[0]\n    if state_below.ndim == 3:\n        n_samples = state_below.shape[1]\n    else:\n        n_samples = 1\n\n    # mask\n    if mask is None:\n        mask = tensor.alloc(1., state_below.shape[0], 1)\n\n    dim = tparams[_p(prefix, 'Ux')].shape[1]\n\n    # initial/previous state\n    if init_state is None:\n        init_state = tensor.alloc(0., n_samples, dim)\n\n    assert context.ndim == 2, 'Context must be 2-d: #sample x dim'\n    # projected context to GRU gates\n    pctx_ = tensor.dot(context, tparams[_p(prefix, 'Wc')])\n    # projected context to hidden state proposal\n    pctxx_ = tensor.dot(context, tparams[_p(prefix, 'Wcx')])\n\n    def _slice(_x, n, dim):\n        if _x.ndim == 3:\n            return _x[:, :, n*dim:(n+1)*dim]\n        return _x[:, n*dim:(n+1)*dim]\n\n    # projected x to gates\n    state_belowx = tensor.dot(state_below, tparams[_p(prefix, 'Wx')]) + \\\n        tparams[_p(prefix, 'bx')]\n    # projected x to hidden state proposal\n    state_below_ = tensor.dot(state_below, tparams[_p(prefix, 'W')]) + \\\n        tparams[_p(prefix, 'b')]\n\n    # step function to be used by scan\n    # arguments    | sequences |outputs-info|       non-seqs\n    def _step_slice(m_, x_, xx_,    h_,       pctx_, pctxx_, U, Ux):\n        preact = tensor.dot(h_, U)\n        preact += x_\n        preact += pctx_\n        preact = tensor.nnet.sigmoid(preact)\n\n        r = _slice(preact, 0, dim)\n        u = _slice(preact, 1, dim)\n\n        preactx = tensor.dot(h_, Ux)\n        preactx *= r\n        preactx += xx_\n        preactx += pctxx_\n\n        h = tensor.tanh(preactx)\n\n        h = u * h_ + (1. - u) * h\n        h = m_[:, None] * h + (1. - m_)[:, None] * h_\n\n        return h\n\n    seqs = [mask, state_below_, state_belowx]\n    _step = _step_slice\n\n    shared_vars = [tparams[_p(prefix, 'U')],\n                   tparams[_p(prefix, 'Ux')]]\n\n    if one_step:\n        rval = _step(*(seqs+[init_state, pctx_, pctxx_]+shared_vars))\n    else:\n        rval, updates = theano.scan(_step,\n                                    sequences=seqs,\n                                    outputs_info=[init_state],\n                                    non_sequences=[pctx_,\n                                                   pctxx_]+shared_vars,\n                                    name=_p(prefix, '_layers'),\n                                    n_steps=nsteps,\n                                    profile=profile,\n                                    strict=True)\n    return rval\n\n\n# initialize all parameters\ndef init_params(options):\n    params = OrderedDict()\n    # embedding\n    params['Wemb'] = norm_weight(options['n_words_src'], options['dim_word'])\n    params['Wemb_dec'] = norm_weight(options['n_words'], options['dim_word'])\n    # encoder\n    params = get_layer(options['encoder'])[0](options, params,\n                                              prefix='encoder',\n                                              nin=options['dim_word'],\n                                              dim=options['dim'])\n    ctxdim = options['dim']\n    # init_state, init_cell\n    params = get_layer('ff')[0](options, params, prefix='ff_state',\n                                nin=ctxdim, nout=options['dim'])\n    # decoder\n    params = get_layer(options['decoder'])[0](options, params,\n                                              prefix='decoder',\n                                              nin=options['dim_word'],\n                                              dim=options['dim'],\n                                              dimctx=ctxdim)\n    # readout\n    params = get_layer('ff')[0](options, params, prefix='ff_logit_lstm',\n                                nin=options['dim'], nout=options['dim_word'],\n                                ortho=False)\n    params = get_layer('ff')[0](options, params, prefix='ff_logit_prev',\n                                nin=options['dim_word'],\n                                nout=options['dim_word'], ortho=False)\n    params = get_layer('ff')[0](options, params, prefix='ff_logit_ctx',\n                                nin=ctxdim, nout=options['dim_word'],\n                                ortho=False)\n    params = get_layer('ff')[0](options, params, prefix='ff_logit',\n                                nin=options['dim_word'],\n                                nout=options['n_words'])\n\n    return params\n\n\n# build a training model\ndef build_model(tparams, options):\n    opt_ret = dict()\n\n    trng = RandomStreams(1234)\n    use_noise = theano.shared(numpy.float32(0.))\n\n    # description string: #words x #samples\n    x = tensor.matrix('x', dtype='int64')\n    x_mask = tensor.matrix('x_mask', dtype='float32')\n    y = tensor.matrix('y', dtype='int64')\n    y_mask = tensor.matrix('y_mask', dtype='float32')\n\n    n_timesteps = x.shape[0]\n    n_timesteps_trg = y.shape[0]\n    n_samples = x.shape[1]\n\n    # word embedding (source)\n    emb = tparams['Wemb'][x.flatten()]\n    emb = emb.reshape([n_timesteps, n_samples, options['dim_word']])\n\n    # pass through encoder gru, recurrence here\n    proj = get_layer(options['encoder'])[1](tparams, emb, options,\n                                            prefix='encoder',\n                                            mask=x_mask)\n\n    # last hidden state of encoder rnn will be used to initialize decoder rnn\n    ctx = proj[0][-1]\n    ctx_mean = ctx\n\n    # initial decoder state\n    init_state = get_layer('ff')[1](tparams, ctx_mean, options,\n                                    prefix='ff_state', activ='tanh')\n\n    # word embedding (target), we will shift the target sequence one time step\n    # to the right. This is done because of the bi-gram connections in the\n    # readout and decoder rnn. The first target will be all zeros and we will\n    # not condition on the last output.\n    emb = tparams['Wemb_dec'][y.flatten()]\n    emb = emb.reshape([n_timesteps_trg, n_samples, options['dim_word']])\n    emb_shifted = tensor.zeros_like(emb)\n    emb_shifted = tensor.set_subtensor(emb_shifted[1:], emb[:-1])\n    emb = emb_shifted\n\n    # decoder - pass through the decoder gru, recurrence here\n    proj = get_layer(options['decoder'])[1](tparams, emb, options,\n                                            prefix='decoder',\n                                            mask=y_mask, context=ctx,\n                                            one_step=False,\n                                            init_state=init_state)\n    # hidden states of the decoder gru\n    proj_h = proj[0]\n\n    # we will condition on the last state of the encoder only\n    ctxs = ctx[None, :, :]\n\n    # compute word probabilities\n    logit_lstm = get_layer('ff')[1](tparams, proj_h, options,\n                                    prefix='ff_logit_lstm', activ='linear')\n    logit_prev = get_layer('ff')[1](tparams, emb, options,\n                                    prefix='ff_logit_prev', activ='linear')\n    logit_ctx = get_layer('ff')[1](tparams, ctxs, options,\n                                   prefix='ff_logit_ctx', activ='linear')\n    logit = tensor.tanh(logit_lstm+logit_prev+logit_ctx)\n    logit = get_layer('ff')[1](tparams, logit, options, prefix='ff_logit',\n                               activ='linear')\n    logit_shp = logit.shape\n    probs = tensor.nnet.softmax(\n        logit.reshape([logit_shp[0]*logit_shp[1], logit_shp[2]]))\n\n    # cost\n    y_flat = y.flatten()\n    y_flat_idx = tensor.arange(y_flat.shape[0]) * options['n_words'] + y_flat\n    cost = -tensor.log(probs.flatten()[y_flat_idx])\n    cost = cost.reshape([y.shape[0], y.shape[1]])\n    cost = (cost * y_mask).sum(0)\n\n    return trng, use_noise, x, x_mask, y, y_mask, opt_ret, cost\n\n\n# build a sampler\ndef build_sampler(tparams, options, trng):\n    x = tensor.matrix('x', dtype='int64')\n    n_timesteps = x.shape[0]\n    n_samples = x.shape[1]\n\n    # word embedding (source)\n    emb = tparams['Wemb'][x.flatten()]\n    emb = emb.reshape([n_timesteps, n_samples, options['dim_word']])\n\n    # encoder\n    proj = get_layer(options['encoder'])[1](tparams, emb, options,\n                                            prefix='encoder')\n    ctx = proj[0][-1]\n    ctx_mean = ctx\n    init_state = get_layer('ff')[1](tparams, ctx_mean, options,\n                                    prefix='ff_state', activ='tanh')\n\n    print 'Building f_init...',\n    outs = [init_state, ctx]\n    f_init = theano.function([x], outs, name='f_init', profile=profile)\n    print 'Done'\n\n    # y: 1 x 1\n    y = tensor.vector('y_sampler', dtype='int64')\n    init_state = tensor.matrix('init_state', dtype='float32')\n\n    # if it's the first word, emb should be all zero\n    emb = tensor.switch(y[:, None] < 0,\n                        tensor.alloc(0., 1, tparams['Wemb_dec'].shape[1]),\n                        tparams['Wemb_dec'][y])\n\n    # apply one step of gru layer\n    proj = get_layer(options['decoder'])[1](tparams, emb, options,\n                                            prefix='decoder',\n                                            mask=None, context=ctx,\n                                            one_step=True,\n                                            init_state=init_state)\n    next_state = proj\n    ctxs = ctx\n\n    # compute the output probability dist and sample\n    logit_lstm = get_layer('ff')[1](tparams, next_state, options,\n                                    prefix='ff_logit_lstm', activ='linear')\n    logit_prev = get_layer('ff')[1](tparams, emb, options,\n                                    prefix='ff_logit_prev', activ='linear')\n    logit_ctx = get_layer('ff')[1](tparams, ctxs, options,\n                                   prefix='ff_logit_ctx', activ='linear')\n    logit = tensor.tanh(logit_lstm+logit_prev+logit_ctx)\n    logit = get_layer('ff')[1](tparams, logit, options,\n                               prefix='ff_logit', activ='linear')\n    next_probs = tensor.nnet.softmax(logit)\n    next_sample = trng.multinomial(pvals=next_probs).argmax(1)\n\n    # next word probability\n    print 'Building f_next..',\n    inps = [y, ctx, init_state]\n    outs = [next_probs, next_sample, next_state]\n    f_next = theano.function(inps, outs, name='f_next', profile=profile)\n    print 'Done'\n\n    return f_init, f_next\n\n\n# generate sample, either with stochastic sampling or beam search\ndef gen_sample(tparams, f_init, f_next, x, options, trng=None, k=1, maxlen=30,\n               stochastic=True, argmax=False):\n\n    # k is the beam size we have\n    if k > 1:\n        assert not stochastic, \\\n            'Beam search does not support stochastic sampling'\n\n    sample = []\n    sample_score = []\n    if stochastic:\n        sample_score = 0\n\n    live_k = 1\n    dead_k = 0\n\n    hyp_samples = [[]] * live_k\n    hyp_scores = numpy.zeros(live_k).astype('float32')\n    hyp_states = []\n\n    # get initial state of decoder rnn and encoder context\n    ret = f_init(x)\n    next_state, ctx0 = ret[0], ret[1]\n    next_w = [-1]  # indicator for the first target word (bos target)\n\n    for ii in xrange(maxlen):\n        ctx = numpy.tile(ctx0, [live_k, 1])\n        inps = [next_w, ctx, next_state]\n        ret = f_next(*inps)\n        next_p, next_w, next_state = ret[0], ret[1], ret[2]\n\n        if stochastic:\n            if argmax:\n                nw = next_p[0].argmax()\n            else:\n                nw = next_w[0]\n            sample.append(nw)\n            sample_score += next_p[0, nw]\n            if nw == 0:\n                break\n        else:\n            cand_scores = hyp_scores[:, None] - numpy.log(next_p)\n            cand_flat = cand_scores.flatten()\n            ranks_flat = cand_flat.argsort()[:(k-dead_k)]\n\n            voc_size = next_p.shape[1]\n            trans_indices = ranks_flat / voc_size\n            word_indices = ranks_flat % voc_size\n            costs = cand_flat[ranks_flat]\n\n            new_hyp_samples = []\n            new_hyp_scores = numpy.zeros(k-dead_k).astype('float32')\n            new_hyp_states = []\n\n            for idx, [ti, wi] in enumerate(zip(trans_indices, word_indices)):\n                new_hyp_samples.append(hyp_samples[ti]+[wi])\n                new_hyp_scores[idx] = copy.copy(costs[idx])\n                new_hyp_states.append(copy.copy(next_state[ti]))\n\n            # check the finished samples\n            new_live_k = 0\n            hyp_samples = []\n            hyp_scores = []\n            hyp_states = []\n\n            for idx in xrange(len(new_hyp_samples)):\n                if new_hyp_samples[idx][-1] == 0:\n                    sample.append(new_hyp_samples[idx])\n                    sample_score.append(new_hyp_scores[idx])\n                    dead_k += 1\n                else:\n                    new_live_k += 1\n                    hyp_samples.append(new_hyp_samples[idx])\n                    hyp_scores.append(new_hyp_scores[idx])\n                    hyp_states.append(new_hyp_states[idx])\n            hyp_scores = numpy.array(hyp_scores)\n            live_k = new_live_k\n\n            if new_live_k < 1:\n                break\n            if dead_k >= k:\n                break\n\n            next_w = numpy.array([w[-1] for w in hyp_samples])\n            next_state = numpy.array(hyp_states)\n\n    if not stochastic:\n        # dump every remaining one\n        if live_k > 0:\n            for idx in xrange(live_k):\n                sample.append(hyp_samples[idx])\n                sample_score.append(hyp_scores[idx])\n\n    return sample, sample_score\n\n\n# calculate the log probablities on a given corpus using translation model\ndef pred_probs(f_log_probs, prepare_data, options, iterator, verbose=True):\n    probs = []\n\n    n_done = 0\n\n    for x, y in iterator:\n        n_done += len(x)\n\n        x, x_mask, y, y_mask = prepare_data(x, y,\n                                            n_words_src=options['n_words_src'],\n                                            n_words=options['n_words'])\n\n        pprobs = f_log_probs(x, x_mask, y, y_mask)\n        for pp in pprobs:\n            probs.append(pp)\n\n        if numpy.isnan(numpy.mean(probs)):\n            ipdb.set_trace()\n\n        if verbose:\n            print >>sys.stderr, '%d samples computed' % (n_done)\n\n    return numpy.array(probs)\n\n\n# optimizers\n# name(hyperp, tparams, grads, inputs (list), cost) = f_grad_shared, f_update\ndef adam(lr, tparams, grads, inp, cost):\n    gshared = [theano.shared(p.get_value() * 0.,\n                             name='%s_grad' % k)\n               for k, p in tparams.iteritems()]\n    gsup = [(gs, g) for gs, g in zip(gshared, grads)]\n\n    f_grad_shared = theano.function(inp, cost, updates=gsup, profile=profile)\n\n    lr0 = 0.0002\n    b1 = 0.1\n    b2 = 0.001\n    e = 1e-8\n\n    updates = []\n\n    i = theano.shared(numpy.float32(0.))\n    i_t = i + 1.\n    fix1 = 1. - b1**(i_t)\n    fix2 = 1. - b2**(i_t)\n    lr_t = lr0 * (tensor.sqrt(fix2) / fix1)\n\n    for p, g in zip(tparams.values(), gshared):\n        m = theano.shared(p.get_value() * 0.)\n        v = theano.shared(p.get_value() * 0.)\n        m_t = (b1 * g) + ((1. - b1) * m)\n        v_t = (b2 * tensor.sqr(g)) + ((1. - b2) * v)\n        g_t = m_t / (tensor.sqrt(v_t) + e)\n        p_t = p - (lr_t * g_t)\n        updates.append((m, m_t))\n        updates.append((v, v_t))\n        updates.append((p, p_t))\n    updates.append((i, i_t))\n\n    f_update = theano.function([lr], [], updates=updates,\n                               on_unused_input='ignore', profile=profile)\n\n    return f_grad_shared, f_update\n\n\ndef adadelta(lr, tparams, grads, inp, cost):\n    zipped_grads = [theano.shared(p.get_value() * numpy.float32(0.),\n                                  name='%s_grad' % k)\n                    for k, p in tparams.iteritems()]\n    running_up2 = [theano.shared(p.get_value() * numpy.float32(0.),\n                                 name='%s_rup2' % k)\n                   for k, p in tparams.iteritems()]\n    running_grads2 = [theano.shared(p.get_value() * numpy.float32(0.),\n                                    name='%s_rgrad2' % k)\n                      for k, p in tparams.iteritems()]\n\n    zgup = [(zg, g) for zg, g in zip(zipped_grads, grads)]\n    rg2up = [(rg2, 0.95 * rg2 + 0.05 * (g ** 2))\n             for rg2, g in zip(running_grads2, grads)]\n\n    f_grad_shared = theano.function(inp, cost, updates=zgup+rg2up,\n                                    profile=profile)\n\n    updir = [-tensor.sqrt(ru2 + 1e-6) / tensor.sqrt(rg2 + 1e-6) * zg\n             for zg, ru2, rg2 in\n             zip(zipped_grads, running_up2, running_grads2)]\n    ru2up = [(ru2, 0.95 * ru2 + 0.05 * (ud ** 2))\n             for ru2, ud in zip(running_up2, updir)]\n    param_up = [(p, p + ud) for p, ud in zip(itemlist(tparams), updir)]\n\n    f_update = theano.function([lr], [], updates=ru2up+param_up,\n                               on_unused_input='ignore', profile=profile)\n\n    return f_grad_shared, f_update\n\n\ndef rmsprop(lr, tparams, grads, inp, cost):\n    zipped_grads = [theano.shared(p.get_value() * numpy.float32(0.),\n                                  name='%s_grad' % k)\n                    for k, p in tparams.iteritems()]\n    running_grads = [theano.shared(p.get_value() * numpy.float32(0.),\n                                   name='%s_rgrad' % k)\n                     for k, p in tparams.iteritems()]\n    running_grads2 = [theano.shared(p.get_value() * numpy.float32(0.),\n                                    name='%s_rgrad2' % k)\n                      for k, p in tparams.iteritems()]\n\n    zgup = [(zg, g) for zg, g in zip(zipped_grads, grads)]\n    rgup = [(rg, 0.95 * rg + 0.05 * g) for rg, g in zip(running_grads, grads)]\n    rg2up = [(rg2, 0.95 * rg2 + 0.05 * (g ** 2))\n             for rg2, g in zip(running_grads2, grads)]\n\n    f_grad_shared = theano.function(inp, cost, updates=zgup+rgup+rg2up,\n                                    profile=profile)\n\n    updir = [theano.shared(p.get_value() * numpy.float32(0.),\n                           name='%s_updir' % k)\n             for k, p in tparams.iteritems()]\n    updir_new = [(ud, 0.9 * ud - 1e-4 * zg / tensor.sqrt(rg2 - rg ** 2 + 1e-4))\n                 for ud, zg, rg, rg2 in zip(updir, zipped_grads, running_grads,\n                                            running_grads2)]\n    param_up = [(p, p + udn[1])\n                for p, udn in zip(itemlist(tparams), updir_new)]\n    f_update = theano.function([lr], [], updates=updir_new+param_up,\n                               on_unused_input='ignore', profile=profile)\n\n    return f_grad_shared, f_update\n\n\ndef sgd(lr, tparams, grads, x, mask, y, cost):\n    gshared = [theano.shared(p.get_value() * 0., name='%s_grad' % k)\n               for k, p in tparams.iteritems()]\n    gsup = [(gs, g) for gs, g in zip(gshared, grads)]\n\n    f_grad_shared = theano.function([x, mask, y], cost, updates=gsup,\n                                    profile=profile)\n\n    pup = [(p, p - lr * g) for p, g in zip(itemlist(tparams), gshared)]\n    f_update = theano.function([lr], [], updates=pup, profile=profile)\n\n    return f_grad_shared, f_update\n\n\ndef train(dim_word=100,  # word vector dimensionality\n          dim=1000,  # the number of GRU units\n          encoder='gru',\n          decoder='gru_cond_simple',\n          patience=10,  # early stopping patience\n          max_epochs=5000,\n          finish_after=10000000,  # finish after this many updates\n          dispFreq=100,\n          decay_c=0.,  # L2 regularization penalty\n          alpha_c=0.,  # not used\n          lrate=0.01,  # learning rate\n          n_words_src=100000,  # source vocabulary size\n          n_words=100000,  # target vocabulary size\n          maxlen=100,  # maximum length of the description\n          optimizer='rmsprop',\n          batch_size=16,\n          valid_batch_size=16,\n          saveto='model.npz',\n          validFreq=1000,\n          saveFreq=1000,  # save the parameters after every saveFreq updates\n          sampleFreq=100,  # generate some samples after every sampleFreq\n          datasets=[\n              '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok',\n              '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok'],\n          valid_datasets=['../data/dev/newstest2011.en.tok',\n                          '../data/dev/newstest2011.fr.tok'],\n          dictionaries=[\n              '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok.pkl',\n              '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok.pkl'],\n          use_dropout=False,\n          reload_=False):\n\n    # Model options\n    model_options = locals().copy()\n\n    # load dictionaries and invert them\n    worddicts = [None] * len(dictionaries)\n    worddicts_r = [None] * len(dictionaries)\n    for ii, dd in enumerate(dictionaries):\n        with open(dd, 'rb') as f:\n            worddicts[ii] = pkl.load(f)\n        worddicts_r[ii] = dict()\n        for kk, vv in worddicts[ii].iteritems():\n            worddicts_r[ii][vv] = kk\n\n    # reload options\n    if reload_ and os.path.exists(saveto):\n        with open('%s.pkl' % saveto, 'rb') as f:\n            models_options = pkl.load(f)\n\n    print 'Loading data'\n    train = TextIterator(datasets[0], datasets[1],\n                         dictionaries[0], dictionaries[1],\n                         n_words_source=n_words_src, n_words_target=n_words,\n                         batch_size=batch_size,\n                         maxlen=maxlen)\n    valid = TextIterator(valid_datasets[0], valid_datasets[1],\n                         dictionaries[0], dictionaries[1],\n                         n_words_source=n_words_src, n_words_target=n_words,\n                         batch_size=valid_batch_size,\n                         maxlen=maxlen)\n\n    print 'Building model'\n    params = init_params(model_options)\n    # reload parameters\n    if reload_ and os.path.exists(saveto):\n        params = load_params(saveto, params)\n\n    tparams = init_tparams(params)\n\n    trng, use_noise, \\\n        x, x_mask, y, y_mask, \\\n        opt_ret, \\\n        cost = \\\n        build_model(tparams, model_options)\n    inps = [x, x_mask, y, y_mask]\n\n    print 'Buliding sampler'\n    f_init, f_next = build_sampler(tparams, model_options, trng)\n\n    # before any regularizer\n    print 'Building f_log_probs...',\n    f_log_probs = theano.function(inps, cost, profile=profile)\n    print 'Done'\n\n    cost = cost.mean()\n\n    # apply L2 regularization on weights\n    if decay_c > 0.:\n        decay_c = theano.shared(numpy.float32(decay_c), name='decay_c')\n        weight_decay = 0.\n        for kk, vv in tparams.iteritems():\n            weight_decay += (vv ** 2).sum()\n        weight_decay *= decay_c\n        cost += weight_decay\n\n    # un used, attention weight regularization\n    if alpha_c > 0. and not model_options['decoder'].endswith('simple'):\n        alpha_c = theano.shared(numpy.float32(alpha_c), name='alpha_c')\n        alpha_reg = alpha_c * (\n            (tensor.cast(y_mask.sum(0)//x_mask.sum(0), 'float32')[:, None] -\n             opt_ret['dec_alphas'].sum(0))**2).sum(1).mean()\n        cost += alpha_reg\n\n    # after all regularizers - compile the computational graph for cost\n    print 'Building f_cost...',\n    f_cost = theano.function(inps, cost, profile=profile)\n    print 'Done'\n\n    print 'Computing gradient...',\n    grads = tensor.grad(cost, wrt=itemlist(tparams))\n    print 'Done'\n\n    # compile the optimizer, the actual computational graph is compiled here\n    lr = tensor.scalar(name='lr')\n    print 'Building optimizers...',\n    f_grad_shared, f_update = eval(optimizer)(lr, tparams, grads, inps, cost)\n    print 'Done'\n\n    print 'Optimization'\n\n    history_errs = []\n    # reload history\n    if reload_ and os.path.exists(saveto):\n        history_errs = list(numpy.load(saveto)['history_errs'])\n    best_p = None\n    bad_count = 0\n\n    if validFreq == -1:\n        validFreq = len(train[0])/batch_size\n    if saveFreq == -1:\n        saveFreq = len(train[0])/batch_size\n    if sampleFreq == -1:\n        sampleFreq = len(train[0])/batch_size\n\n    uidx = 0\n    estop = False\n    for eidx in xrange(max_epochs):\n        n_samples = 0\n\n        for x, y in train:\n            n_samples += len(x)\n            uidx += 1\n            use_noise.set_value(1.)\n\n            x, x_mask, y, y_mask = prepare_data(x, y, maxlen=maxlen,\n                                                n_words_src=n_words_src,\n                                                n_words=n_words)\n\n            if x is None:\n                print 'Minibatch with zero sample under length ', maxlen\n                uidx -= 1\n                continue\n\n            ud_start = time.time()\n\n            # compute cost, grads and copy grads to shared variables\n            cost = f_grad_shared(x, x_mask, y, y_mask)\n\n            # do the update on parameters\n            f_update(lrate)\n\n            ud = time.time() - ud_start\n\n            # check for bad numbers\n            if numpy.isnan(cost) or numpy.isinf(cost):\n                print 'NaN detected'\n                return 1., 1., 1.\n\n            # verbose\n            if numpy.mod(uidx, dispFreq) == 0:\n                print 'Epoch ', eidx, 'Update ', uidx, 'Cost ', cost, 'UD ', ud\n\n            # save the best model so far\n            if numpy.mod(uidx, saveFreq) == 0:\n                print 'Saving...',\n\n                if best_p is not None:\n                    params = best_p\n                else:\n                    params = unzip(tparams)\n                numpy.savez(saveto, history_errs=history_errs, **params)\n                pkl.dump(model_options, open('%s.pkl' % saveto, 'wb'))\n                print 'Done'\n\n            # generate some samples with the model and display them\n            if numpy.mod(uidx, sampleFreq) == 0:\n                # FIXME: random selection?\n                for jj in xrange(numpy.minimum(5, x.shape[1])):\n                    stochastic = True\n                    sample, score = gen_sample(tparams, f_init, f_next,\n                                               x[:, jj][:, None],\n                                               model_options, trng=trng, k=1,\n                                               maxlen=30,\n                                               stochastic=stochastic,\n                                               argmax=False)\n                    print 'Source ', jj, ': ',\n                    for vv in x[:, jj]:\n                        if vv == 0:\n                            break\n                        if vv in worddicts_r[0]:\n                            print worddicts_r[0][vv],\n                        else:\n                            print 'UNK',\n                    print\n                    print 'Truth ', jj, ' : ',\n                    for vv in y[:, jj]:\n                        if vv == 0:\n                            break\n                        if vv in worddicts_r[1]:\n                            print worddicts_r[1][vv],\n                        else:\n                            print 'UNK',\n                    print\n                    print 'Sample ', jj, ': ',\n                    if stochastic:\n                        ss = sample\n                    else:\n                        score = score / numpy.array([len(s) for s in sample])\n                        ss = sample[score.argmin()]\n                    for vv in ss:\n                        if vv == 0:\n                            break\n                        if vv in worddicts_r[1]:\n                            print worddicts_r[1][vv],\n                        else:\n                            print 'UNK',\n                    print\n\n            # validate model on validation set and early stop if necessary\n            if numpy.mod(uidx, validFreq) == 0:\n                use_noise.set_value(0.)\n                valid_errs = pred_probs(f_log_probs, prepare_data,\n                                        model_options, valid)\n                valid_err = valid_errs.mean()\n                history_errs.append(valid_err)\n\n                if uidx == 0 or valid_err <= numpy.array(history_errs).min():\n                    best_p = unzip(tparams)\n                    bad_counter = 0\n                if len(history_errs) > patience and valid_err >= \\\n                        numpy.array(history_errs)[:-patience].min():\n                    bad_counter += 1\n                    if bad_counter > patience:\n                        print 'Early Stop!'\n                        estop = True\n                        break\n\n                if numpy.isnan(valid_err):\n                    ipdb.set_trace()\n\n                print 'Valid ', valid_err\n\n            # finish after this many updates\n            if uidx >= finish_after:\n                print 'Finishing after %d iterations!' % uidx\n                estop = True\n                break\n\n        print 'Seen %d samples' % n_samples\n\n        if estop:\n            break\n\n    if best_p is not None:\n        zipp(best_p, tparams)\n\n    use_noise.set_value(0.)\n    valid_err = pred_probs(f_log_probs, prepare_data,\n                           model_options, valid).mean()\n\n    print 'Valid ', valid_err\n\n    params = copy.copy(best_p)\n    numpy.savez(saveto, zipped_params=best_p,\n                history_errs=history_errs,\n                **params)\n\n    return valid_err\n\n\nif __name__ == '__main__':\n    pass\n", "meta": {"hexsha": "7c42b0ea93afa9cc6d3f4f56de4711d36fe80858", "size": 39739, "ext": "py", "lang": "Python", "max_stars_repo_path": "session1/nmt.py", "max_stars_repo_name": "sebastien-j/doc-nmt-public", "max_stars_repo_head_hexsha": "822497af387b1c6ea80626cd3da26543231a6cd7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "session1/nmt.py", "max_issues_repo_name": "sebastien-j/doc-nmt-public", "max_issues_repo_head_hexsha": "822497af387b1c6ea80626cd3da26543231a6cd7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "session1/nmt.py", "max_forks_repo_name": "sebastien-j/doc-nmt-public", "max_forks_repo_head_hexsha": "822497af387b1c6ea80626cd3da26543231a6cd7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6460331299, "max_line_length": 79, "alphanum_fraction": 0.5445028813, "include": true, "reason": "import numpy,import theano,from theano", "num_tokens": 9847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3208213008246071, "lm_q1q2_score": 0.16291686287222318}}
{"text": "import os\nimport zmq\nimport json\nimport time\nimport argparse\nimport numpy as np\nfrom tqdm import tqdm\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\nimport itertools\nfrom mendeleev import element\nfrom termcolor import colored\nimport pyfiglet\n\n\ndef get_parser():\n\n    parser = argparse.ArgumentParser(description = 'Plotting script')\n\n    parser.add_argument('-Talys',\n                        dest='Talysfolder',\n                        type=str,\n                        help='Talys simulation folder')\n\n    parser.add_argument('-Fluka',\n                        dest='Flukafolder',\n                        type=str,\n                        help='Fluka simulation folder')\n\n    parser.add_argument('-PACE',\n                        dest='PACEfolder',\n                        type=str,\n                        help='PACE4 simulation folder')\n\n    parser.add_argument('-EXFOR',\n                        dest='EXFORfolder',\n                        type=str,\n                        help='EXFOR experimental data folder')\n\n    parser.add_argument('-o',\n                        dest='Outfolder',\n                        type=str,\n                        help='output folder')\n\n\n    args = parser.parse_args()\n\n    return args, parser\n\n#def extract_EXS(filename):\n\ndef Talys_rpExtractor(SimulationDIR):\n\n    rpData = dict()\n\n    for folder in tqdm(os.listdir(SimulationDIR)):\n        if ( folder.find('Energy_') != -1 ) :\n            #print('------',folder,'------')\n            for isotope in os.listdir(SimulationDIR+'/'+folder):\n                if ( isotope.find('rp') != -1 and isotope.find('.tot') != -1) :\n                    IsoKey = isotope[2:8]\n                    data = np.loadtxt(SimulationDIR+'/'+folder+'/'+isotope)\n                    if (rpData.get(IsoKey) == None) :\n                        rpData[IsoKey] = [ [data[0]],[data[1]] ]\n                    else:\n                        rpData[IsoKey][0].append(data[0])\n                        rpData[IsoKey][1].append(data[1])\n\n    return rpData\n\ndef Talys_recExtractor(SimulationDIR):\n\n    recData = dict()\n\n    for folder in tqdm(os.listdir(SimulationDIR)):\n        if ( folder.find('Energy_') != -1 ) :\n            Energy = '{:03d}'.format(int(folder[7:]))\n            for isotope in os.listdir(SimulationDIR+'/'+folder):\n                if ( isotope.find('rec') != -1 and isotope.find('.tot') != -1) :\n                    IsoKey = isotope[3:9]\n                    data = np.loadtxt(SimulationDIR+'/'+folder+'/'+isotope)\n\n                    if (recData.get(IsoKey) == None) :\n                        recData[IsoKey] = dict()\n                        cycleflag = True\n                        list_tmp = []\n                        for line in data:\n                            if cycleflag:\n                                list_tmp = [ [line[0]], [line[1]]]\n                                cycleflag = False\n                            else:\n                                list_tmp[0].append(line[0])\n                                list_tmp[1].append(line[1])\n                        recData[IsoKey][Energy] = list_tmp[:]\n                    else:\n                        cycleflag = True\n                        list_tmp = []\n                        for line in data:\n                            if cycleflag:\n                                list_tmp = [ [line[0]], [line[1]]]\n                                cycleflag = False\n                            else:\n                                list_tmp[0].append(line[0])\n                                list_tmp[1].append(line[1])\n                        recData[IsoKey][Energy] = list_tmp[:]\n\n    return recData\n\ndef PACE_rpExtractor(SimulationDIR):\n\n    rpData = dict()\n\n    for files in tqdm(os.listdir(SimulationDIR+'/xsec')):\n            Energy = 10 + 5*(int(files[-6:-4])-1)\n            data = np.loadtxt(SimulationDIR+'/xsec/'+files,comments='!')\n            if (len(data.shape) == 1):\n                IsoKey = '{:03d}'.format(int(data[0]))+'{:03d}'.format(int(data[0]+data[1]))\n\n                if (rpData.get(IsoKey) == None) :\n                    rpData[IsoKey] = [ [Energy],[data[2]] ]\n                else:\n                    rpData[IsoKey][0].append(Energy)\n                    rpData[IsoKey][1].append(data[2])\n            else:\n                for entry in data:\n                    IsoKey = '{:03d}'.format(int(entry[0]))+'{:03d}'.format(int(entry[0]+entry[1]))\n\n                    if (rpData.get(IsoKey) == None) :\n                        rpData[IsoKey] = [ [Energy],[entry[2]] ]\n                    else:\n                        rpData[IsoKey][0].append(Energy)\n                        rpData[IsoKey][1].append(entry[2])\n\n    return rpData\n\ndef PACE_recExtractor(SimulationDIR):\n\n    recData = dict()\n\n    for files in tqdm(os.listdir(SimulationDIR+'/simufiles')):\n            if (files.find('.particles') != -1 ):\n                Energy = '{:03d}'.format(10 + 5*(int(files[-12:-10])-1))\n                data = np.loadtxt(SimulationDIR+'/simufiles/'+files, skiprows = 2, usecols = (4,5,6,7,14)) #4-Zf 5-Nf 6-Zc 7-Nc 14-Ep_Lab\n                for line in data:\n                    IsoKey = '{:03d}'.format(int(line[0]))+'{:03d}'.format(int(line[0]+line[1]))\n\n                    if (recData.get(IsoKey) == None) :\n                        recData[IsoKey] = dict()\n                        recData[IsoKey][Energy] = [line[4]]\n                    elif (recData[IsoKey].get(Energy) == None) :\n                        recData[IsoKey][Energy] = [line[4]]\n                    else :\n                        recData[IsoKey][Energy].append(line[4])\n\n    return recData\n\ndef Fluka_rpExtractor(SimulationDIR):\n\n    rpData = dict()\n    #conversionfactor = 0.385469 # conv for 238U 0.8cm thick\n    conversionfactor = 2.40918e-06 # conv for 238U 0.000005cm thick\n    for folder in tqdm(os.listdir(SimulationDIR)):\n        if ( folder.find('Energy_') != -1 ) :\n            #print('------',folder,'------')\n            Energy = '{:03d}'.format(int(folder[7:]))\n            for output in os.listdir(SimulationDIR+'/'+folder):\n                if ( output.find('_tab.lis') != -1 ) :\n                    with open(SimulationDIR+'/'+folder+'/'+output,'r') as file:\n                        continueflag = True\n                        for line in file.readlines():\n                            if (line.find('# A/Z Isotopes:')!= -1) :\n                                continueflag = False\n                                continue\n                            if (continueflag) : continue\n\n                            data = line.split()\n                            IsoKey = '{:03d}'.format(int(data[1]))+'{:03d}'.format(int(data[0]))\n                            if (float(data[2])/conversionfactor > 0.001 and int(data[0]) > 200) :\n\n                                if (rpData.get(IsoKey) == None) :\n                                    rpData[IsoKey] = [ [int(Energy)],[float(data[2])/conversionfactor] ]\n                                else:\n                                    rpData[IsoKey][0].append(int(Energy))\n                                    rpData[IsoKey][1].append(float(data[2])/conversionfactor)\n    #print(rpData)\n    return rpData\n\ndef EXFOR_Extractor(DIR):\n\n    rpData = dict()\n\n    for files in os.listdir(DIR):\n        IsoKey = files[0:6]\n        with open(DIR+'/'+files) as fp:\n            titlekey = ''\n            dataflag = False\n            cycleflag = True\n            DataList_tmp = []\n\n            for line in fp:\n                if (line[0:2] == '//') :\n                    dataflag = False\n                    if (rpData.get(titlekey) == None) :\n                        rpData[titlekey] = dict()\n                    rpData[titlekey][IsoKey] = DataList_tmp[:]\n                    DataList_tmp.clear()\n                    titlekey = ''\n\n                if (line[0] != '#' and dataflag) :\n                    data = line.strip().split(' ')\n\n                    if ( cycleflag ) :\n                        DataList_tmp = [ [float(data[0])], [float(data[1])], [float(data[2])]]\n                        cycleflag = False\n\n                    else :\n                        DataList_tmp[0].append(float(data[0]))\n                        DataList_tmp[1].append(float(data[1]))\n                        DataList_tmp[2].append(float(data[2]))\n\n\n                if (line[0:4] == 'tit:') :\n                    titlekey = line[5:-1]\n                    dataflag = True\n                    cycleflag = True\n\n\n\n    return rpData\n\ndef edgefinder(IsoList):\n\n    Zlist = []\n    Nlist = []\n    for key in IsoList:\n        if (int(key[0:3])-0.5 not in Zlist):\n            Zlist.append(int(key[0:3])-0.5)\n        if ((int(key[3:6])-int(key[0:3])-0.5) not in Nlist):\n            Nlist.append(int(key[3:6])-int(key[0:3])-0.5)\n\n    Zlist.sort()\n    Nlist.sort()\n    Zlist.append(Zlist[-1]+1)\n    Nlist.append(Nlist[-1]+1)\n    return [Nlist,Zlist]\n\ndef histolister(rpData, energy):\n    x = []\n    y = []\n    w = []\n    for key in rpData.keys():\n        try:\n            index = rpData[key][0].index(energy)\n            x.append(int(key[3:6])-int(key[0:3]))\n            y.append(int(key[0:3]))\n            w.append(rpData[key][1][index])\n        except:\n            continue\n\n\n\n    return x, y, w\n\ndef keysorter(rpData):\n    keyList = []\n    for key in rpData.keys():\n        keyList.append(key)\n    keyList.sort()\n    return keyList\n\ndef listsorter(X,Y):\n    list1, list2 = zip(*sorted(zip(X,Y)))\n    Xlist, Ylist = (list(t) for t in zip(*sorted(zip(list1, list2))))\n    return Xlist, Ylist\n\ndef segreplotter(outfolder,code,rpData):\n    print('------Plotting segre plot for ',code,'------')\n    for energy in range(20,140,5):\n\n        keyList = []\n        for key in rpData.keys():\n            keyList.append(key)\n\n        keyList.sort()\n\n        BIN = edgefinder(keyList)\n        N, Z, W = histolister(rpData,energy)\n\n        hist, xbins, ybins, im = plt.hist2d(N,Z,bins=BIN, weights=W, cmap='autumn', norm=LogNorm(vmin=0.001, vmax=max(W)))\n\n        Title =  str(energy)+' MeV'\n        outfile = outfolder+'/SEGRESIM/'+code+'/Energy_'+str(energy)+'.png'\n\n        plt.title(Title)\n        plt.xlabel(\"N\")\n        plt.ylabel(\"Z\")\n\n\n        cbar = plt.colorbar()\n        cbar.set_label(\"Cross Section [mb]\")\n        print('Segre chart for energy -> ',energy)\n        for i in range(len(ybins)-1):\n            for j in range(len(xbins)-1):\n                El = element(int(ybins[i]+0.5))\n                label = str(int(xbins[j]+0.5+ybins[i]+0.5))+El.symbol\n                if(hist.T[i,j]): plt.text(xbins[j]+0.5,ybins[i]+0.5, label, color=\"k\", ha=\"center\", va=\"center\",fontsize = 4)\n\n        plt.savefig(outfile,dpi = 300)\n        plt.close()\n\ndef clear():\n    os.system('clear')\n\ndef menu():\n        strs = ('Enter 1 for plotting Segre production charts\\n'\n                'Enter 2 for plotting EXFOR data comparison\\n'\n                'Enter 3 for plotting Simulated production Cross Sections comparison\\n'\n                'Enter 4 for plotting Simulated production Cross Sections CODE separated\\n'\n                'Enter 5 for plotting Recoil spectra\\n'\n                'Enter 6 for sorting production cross section\\n'\n                'Enter 7 for Talys dedicated plot\\n'\n                'Enter 8 to exit : ')\n        choice = input(strs)\n        return int(choice)\n\n\ndef main():\n\n    clear()\n    ascii_banner = pyfiglet.figlet_format(\"Simulation Data Sorter\")\n    print(ascii_banner)\n    #-----Getting parser-----#\n    args, parser = get_parser()\n\n    #-----Define data containers-----#\n    rpTalysData = dict()\n    rpFlukaData = dict()\n    rpPACEData = dict()\n    rpEXFORData = dict()\n\n    #-----retrieve data from dataset-----#\n    if args.Talysfolder is not None:\n        print('--Sorting ',colored('Talys', 'green'),' Data--')\n        rpTalysData = Talys_rpExtractor(args.Talysfolder)\n    else:\n        print(colored('WARNING :', 'yellow'), ' Talys Data not provided')\n\n    if args.Flukafolder is not None:\n        print('--Sorting ',colored('Fluka', 'green'),' Data--')\n        rpFlukaData = Fluka_rpExtractor(args.Flukafolder)\n    else:\n        print(colored('WARNING :', 'yellow'), ' Fluka Data not provided')\n\n    if args.PACEfolder is not None:\n        print('--Sorting ',colored('PACE4', 'green'),' Data--')\n        rpPACEData = PACE_rpExtractor(args.PACEfolder)\n    else:\n        print(colored('WARNING :', 'yellow'), ' PACE4 Data not provided')\n\n    if args.EXFORfolder is not None:\n        print('--Sorting ',colored('EXFOR', 'green'),' Data--')\n        rpEXFORData = EXFOR_Extractor(args.EXFORfolder)\n    else:\n        print(colored('WARNING :', 'yellow'), ' EXFOR Data not provided')\n\n    if args.Outfolder is not None:\n        print('--Output folder is -> ', os.path.abspath(args.Outfolder))\n        try:\n            os.mkdir(args.Outfolder)\n        except:\n            print(colored('WARNING :', 'yellow'),args.Outfolder,\" already exist\")\n    else:\n        print(colored('ERROR :', 'red'), 'Output folder not provided')\n        raise SystemExit\n\n\n    while True:\n        clear()\n        print(ascii_banner)\n        choice = menu()\n\n\n        if choice == 1:\n            clear()\n            print(ascii_banner)\n            try:\n                os.mkdir(args.Outfolder+\"/SEGRESIM\")\n            except:\n                print(colored('WARNING :', 'yellow'),\" Segre plot already exist. All content will be replaced\")\n            finally:\n                os.system('rm -r '+args.Outfolder+\"/SEGRESIM\")\n                os.mkdir(args.Outfolder+\"/SEGRESIM\")\n\n            if args.Flukafolder is not None:\n                os.mkdir(args.Outfolder+\"/SEGRESIM/Fluka\")\n                segreplotter(args.Outfolder,'Fluka',rpFlukaData)\n\n            if args.Talysfolder is not None:\n                os.mkdir(args.Outfolder+\"/SEGRESIM/Talys\")\n                segreplotter(args.Outfolder,'Talys',rpTalysData)\n\n            if args.PACEfolder is not None:\n                os.mkdir(args.Outfolder+\"/SEGRESIM/PACE\")\n                segreplotter(args.Outfolder,'PACE',rpPACEData)\n\n\n        elif choice == 2:\n            clear()\n            print(ascii_banner)\n\n            EXFORauthorList = []\n            EXFORIsokeyList = []\n            TalyskeyList    = []\n            FlukakeyList    = []\n            PACEkeyList     = []\n            CN = ''\n            while True:\n                CN = input('Insert CN [ZZZAAA] : ')\n                if (len(CN) == 6): break\n                print(colored('WARNING :', 'yellow'),\" Wrong CN format\")\n\n            #-----sort produced istopes-----#\n            if args.Talysfolder is not None:\n                TalyskeyList = keysorter(rpTalysData)\n            else:\n                print(colored('ERROR :', 'red'), ' Talys Data not provided')\n                raise SystemExit\n\n            if args.Flukafolder is not None:\n                FlukakeyList = keysorter(rpFlukaData)\n            else:\n                print(colored('ERROR :', 'red'), ' Fluka Data not provided')\n                raise SystemExit\n\n            if args.PACEfolder is not None:\n                PACEkeyList = keysorter(rpPACEData)\n            else:\n                print(colored('ERROR :', 'red'), ' PACE Data not provided')\n                raise SystemExit\n\n            if args.EXFORfolder is not None:\n                EXFORauthorList = []\n                EXFORIsokeyList = []\n                for key in rpEXFORData.keys():\n                    EXFORauthorList.append(key)\n                    for isokey in rpEXFORData[key].keys():\n                        if (isokey in EXFORIsokeyList): continue\n                        else: EXFORIsokeyList.append(isokey)\n                EXFORauthorList.sort()\n                EXFORIsokeyList.sort()\n            else:\n                print(colored('ERROR :', 'red'), ' EXFOR Data not provided')\n                raise SystemExit\n\n\n\n            CommonIsoKeyEXP = []\n            for key in rpPACEData.keys():\n                if key in rpTalysData:\n                    if key in rpFlukaData:\n                        if key in EXFORIsokeyList:\n                            CommonIsoKeyEXP.append(key)\n            # print(PACEkeyList)\n            print(TalyskeyList)\n            print(FlukakeyList)\n            # print(CommonIsoKeyEXP)\n            input('wait')\n            CommonIsoKeyEXP.sort()\n            try:\n                os.mkdir(args.Outfolder+\"/EXPSIM\")\n            except:\n                print(colored('WARNING :', 'yellow'),\" Comparison plots already exist. All content will be replaced\")\n            finally:\n                os.system('rm -r '+args.Outfolder+\"/EXPSIM\")\n                os.mkdir(args.Outfolder+\"/EXPSIM\")\n\n\n            marker = itertools.cycle(('s', 'p', 'o'))\n            color = itertools.cycle(('m', 'b'))\n\n            for key in CommonIsoKeyEXP:\n                print('------Plotting production Cross Section for ',key,'------')\n                outfile = args.Outfolder+'/EXPSIM/'+key+'.png'\n                #sorting\n                X1, Y1 = listsorter(rpPACEData[key][0], rpPACEData[key][1])\n                X2, Y2 = listsorter(rpTalysData[key][0], rpTalysData[key][1])\n                X3, Y3 = listsorter(rpFlukaData[key][0], rpFlukaData[key][1])\n\n                plt.figure()\n                plt.plot(X1,Y1,label='PACE4',marker = 'o', ms = 3, color = 'green',linestyle = 'None')\n                plt.plot(X2,Y2,label='Talys',marker = 'o', ms = 3, color = 'orange',linestyle = 'None')\n                plt.plot(X3,Y3,label='Fluka',marker = 'o', ms = 3, color = 'red',linestyle = 'None')\n\n\n\n                Title =  str(int(CN[3:6])-int(key[3:6]))+' evaporated neutrons'\n                plt.title(Title)\n                for author in rpEXFORData.keys():\n                    if (key in rpEXFORData[author]):\n                        plt.errorbar(rpEXFORData[author][key][0],rpEXFORData[author][key][1], yerr = rpEXFORData[author][key][2], label = author,marker = next(marker), color = next(color), ecolor='k', elinewidth=1, capsize=2,markersize = 2, linestyle = 'None' )\n                plt.legend()\n                plt.xlabel(\"Energy [MeV]\")\n                plt.ylabel(\"Cross Section [mb]\")\n                plt.xlim((10,150))\n                plt.yscale('log')\n                #plt.show()\n                plt.savefig(outfile,dpi = 300)\n                plt.close()\n\n        elif choice == 3:\n            clear()\n            print(ascii_banner)\n            subchoice = ''\n            CN = ''\n            CommonIsoKey = []\n\n            while True:\n                subchoice = input('Enter all for plotting everything\\nEnter n for plotting only the neutron evaporated residuals\\nEnter [ZZZAAA] for plotting a specific isotope : ')\n                if (subchoice == 'all' or subchoice == 'n' or (len(subchoice) == 6)): break\n                print(colored('WARNING :', 'yellow'),\" Wrong choice format\")\n\n\n            #-----sort produced istopes-----#\n            if args.Talysfolder is not None:\n                TalyskeyList = keysorter(rpTalysData)\n            else:\n                print(colored('ERROR :', 'red'), ' Talys Data not provided')\n                raise SystemExit\n\n            if args.Flukafolder is not None:\n                FlukakeyList = keysorter(rpFlukaData)\n            else:\n                print(colored('ERROR :', 'red'), ' Fluka Data not provided')\n                raise SystemExit\n\n            if args.PACEfolder is not None:\n                PACEkeyList = keysorter(rpPACEData)\n            else:\n                print(colored('ERROR :', 'red'), ' PACE Data not provided')\n                raise SystemExit\n\n\n            if (subchoice == 'n'):\n                while True:\n                    CN = input('Insert CN [ZZZAAA] : ')\n                    if (len(CN) == 6): break\n                    print(colored('WARNING :', 'yellow'),\" Wrong CN format\")\n                for key in rpPACEData.keys():\n                    if key in rpTalysData.keys():\n                        if key in rpFlukaData.keys():\n                            if key[0:3] == CN[0:3]:\n                                CommonIsoKey.append(key)\n\n            elif (subchoice == 'all'):\n                for key in rpPACEData.keys():\n                    if key in rpTalysData.keys():\n                        if key in rpFlukaData.keys():\n                            CommonIsoKey.append(key)\n            elif (len(subchoice) == 6):\n                CommonIsoKey.append(subchoice)\n\n            try:\n                os.mkdir(args.Outfolder+'/SIM')\n            except:\n                print(colored('WARNING :', 'yellow'),\" Simulation plot already exist. Content will be replaced\")\n\n            for key in CommonIsoKey:\n                print('------Plotting production Cross Section for ',key,'------')\n                outfile = args.Outfolder+'/SIM/'+key+'.png'\n                plt.figure()\n                #sorting\n                X1, Y1 = listsorter(rpPACEData[key][0], rpPACEData[key][1])\n                X2, Y2 = listsorter(rpTalysData[key][0], rpTalysData[key][1])\n                X3, Y3 = listsorter(rpFlukaData[key][0], rpFlukaData[key][1])\n\n                plt.figure()\n                plt.plot(X1,Y1,label='PACE4',marker = 'o', ms = 3, color = 'green',linestyle = 'None')\n                plt.plot(X2,Y2,label='Talys',marker = 'o', ms = 3, color = 'orange',linestyle = 'None')\n                plt.plot(X3,Y3,label='Fluka',marker = 'o', ms = 3, color = 'red',linestyle = 'None')\n                if (subchoice == 'n'):\n                    Title =  str(int(CN[3:6])-int(key[3:6]))+' evaporated neutrons'\n                    plt.title(Title)\n                plt.legend()\n                plt.xlabel(\"Energy [MeV]\")\n                plt.ylabel(\"Cross Section [mb]\")\n                plt.xlim((10,150))\n                plt.yscale('log')\n                #plt.show()\n                plt.savefig(outfile,dpi = 300)\n                plt.close()\n\n        elif choice == 4:\n            clear()\n            print(ascii_banner)\n            subchoice = ''\n            CN = ''\n            CommonIsoKey = []\n            SimuChoice = ''\n            ISO1 = ''\n            ISO2 = ''\n            IsoKey = []\n            while True:\n                subchoice = input('Enter 1 for Talys\\nEnter 2 for PACE\\nEnter 3 for Fluka : ')\n                if (subchoice == '1' or subchoice == '2' or subchoice == '3'): break\n                print(colored('WARNING :', 'yellow'),\" Wrong choice format\")\n\n\n            while True:\n                ISO1 = input('Insert lower range limit [ZZZAAA] : ')\n                if (len(ISO1) == 6): break\n                print(colored('WARNING :', 'yellow'),\" Wrong Isotope format\")\n            while True:\n                ISO2 = input('Insert top range limit [ZZZAAA] : ')\n                if (len(ISO2) == 6): break\n                print(colored('WARNING :', 'yellow'),\" Wrong Isotope format\")\n\n\n\n            try:\n                os.mkdir(args.Outfolder+'/SIM')\n            except:\n                print(colored('WARNING :', 'yellow'),\" Simulation plot already exist. Content will be replaced\")\n\n\n            #-----sort produced istopes-----#\n            if subchoice == '1':\n                if args.Talysfolder is not None:\n                    CommonIsoKey = keysorter(rpTalysData)\n                    SimuChoice = 'Talys'\n                else:\n                    print(colored('ERROR :', 'red'), ' Talys Data not provided')\n                    raise SystemExit\n\n            elif subchoice == '2':\n                if args.PACEfolder is not None:\n                    CommonIsoKey = keysorter(rpPACEData)\n                    SimuChoice = 'PACE'\n                else:\n                    print(colored('ERROR :', 'red'), ' PACE Data not provided')\n                    raise SystemExit\n\n            elif subchoice == '3':\n                if args.Flukafolder is not None:\n                    CommonIsoKey = keysorter(rpFlukaData)\n                    SimuChoice = 'Fluka'\n                else:\n                    print(colored('ERROR :', 'red'), ' Fluka Data not provided')\n                    raise SystemExit\n\n            for Z in range(int(ISO1[0:3]),int(ISO2[0:3])+1,1):\n                for A in range(int(ISO1[3:6]),int(ISO2[3:6])+1,1):\n                    Key = '{:03d}'.format(Z)+'{:03d}'.format(A)\n                    if (Key in CommonIsoKey): IsoKey.append(Key)\n\n\n            try:\n                os.mkdir(args.Outfolder+'/SIM/'+SimuChoice)\n            except:\n                print(colored('WARNING :', 'yellow'),\" Simulation folder already exist. Content will be deleted\")\n            finally:\n                os.system('rm -r '+args.Outfolder+'/SIM/'+SimuChoice)\n                os.mkdir(args.Outfolder+'/SIM/'+SimuChoice)\n\n            for key in IsoKey:\n                print('------Plotting ',SimuChoice,' production Cross Section for ',key,'------')\n\n                outfile = args.Outfolder+'/SIM/'+SimuChoice+'/'+key+'.png'\n                plt.figure()\n                #sorting\n                X = []\n                Y = []\n                if subchoice == '1':\n                    X, Y = listsorter(rpTalysData[key][0], rpTalysData[key][1])\n\n                elif subchoice == '2':\n                    X, Y = listsorter(rpPACEData[key][0], rpPACEData[key][1])\n\n                elif subchoice == '3':\n                    X, Y = listsorter(rpFlukaData[key][0], rpFlukaData[key][1])\n\n\n\n                plt.figure()\n                plt.plot(X,Y,label=SimuChoice,marker = 'o', ms = 3, color = 'green',linestyle = 'None')\n\n                plt.legend()\n                plt.xlabel(\"Energy [MeV]\")\n                plt.ylabel(\"Cross Section [mb]\")\n                plt.xlim((10,150))\n                plt.yscale('log')\n                #plt.show()\n                plt.savefig(outfile,dpi = 300)\n                plt.close()\n\n        elif choice == 5:\n            clear()\n            print(ascii_banner)\n            #-----retrieve recoil information-----#\n            recTalysData = dict()\n            recPACEData = dict()\n            if args.Talysfolder is not None:\n                print('--Sorting ',colored('Talys', 'green'),' recoil information--')\n                recTalysData = Talys_recExtractor(args.Talysfolder)\n            else:\n                print(colored('ERROR :', 'red'), ' Talys Data not provided')\n                raise SystemExit\n\n            if args.PACEfolder is not None:\n                print('--Sorting ',colored('PACE', 'green'),' recoil information--')\n                #recPACEData = PACE_recExtractor(args.PACEfolder)\n            else:\n                print(colored('ERROR :', 'red'), ' PACE Data not provided')\n                raise SystemExit\n\n            subchoice = ''\n            CN = ''\n            PACEIsoKey = []\n            TalysIsoKey = []\n            clear()\n            print(ascii_banner)\n            while True:\n                subchoice = input('Enter all for plotting everything\\nEnter n for plotting only the neutron evaporated residuals\\nEnter [ZZZAAA] for plotting a specific isotope \\nEnter range for plotting isotopes in a specific range:')\n                if (subchoice == 'all' or subchoice == 'n' or subchoice == 'range' or (len(subchoice) == 6)): break\n                print(colored('WARNING :', 'yellow'),\" Wrong choice format\")\n\n            if (subchoice == 'n'):\n                while True:\n                    CN = input('Insert CN [ZZZAAA] : ')\n                    if (len(CN) == 6): break\n                    print(colored('WARNING :', 'yellow'),\" Wrong CN format\")\n\n                for key in recPACEData.keys():\n                    if key[0:3] == CN[0:3]: PACEIsoKey.append(key)\n                for key in recTalysData.keys():\n                    if key[0:3] == CN[0:3]: TalysIsoKey.append(key)\n\n            elif (subchoice == 'range'):\n                while True:\n                    ISO1 = input('Insert lower range limit [ZZZAAA] : ')\n                    if (len(ISO1) == 6): break\n                    print(colored('WARNING :', 'yellow'),\" Wrong Isotope format\")\n                while True:\n                    ISO2 = input('Insert top range limit [ZZZAAA] : ')\n                    if (len(ISO2) == 6): break\n                    print(colored('WARNING :', 'yellow'),\" Wrong Isotope format\")\n\n\n\n                for Z in range(int(ISO1[0:3]),int(ISO2[0:3])+1,1):\n                    for A in range(int(ISO1[3:6]),int(ISO2[3:6])+1,1):\n                        IsoKey = '{:03d}'.format(Z)+'{:03d}'.format(A)\n                        if (IsoKey in recTalysData.keys()): TalysIsoKey.append(IsoKey)\n                print(TalysIsoKey)\n\n            elif (subchoice == 'all'):\n                PACEIsoKey = keysorter(recPACEData)\n                TalysIsoKey = keysorter(recTalysData)\n\n            elif (len(subchoice) == 6):\n                if (subchoice in recTalysData.keys()) : TalysIsoKey.append(subchoice)\n                if (subchoice in recPACEData.keys()) : PACEIsoKey.append(subchoice)\n            PACEIsoKey.sort()\n            TalysIsoKey.sort()\n            try:\n                os.mkdir(args.Outfolder+'/RECSIM')\n            except:\n                print(colored('WARNING :', 'yellow'),\" Recoil spectra already exist. Content will be replaced\")\n            try:\n                os.mkdir(args.Outfolder+'/RECSIM/Talys')\n            except:\n                print(colored('WARNING :', 'yellow'),\" Talys Recoil spectra already exist. Content will be replaced\")\n            try:\n                os.mkdir(args.Outfolder+'/RECSIM/PACE')\n            except:\n                print(colored('WARNING :', 'yellow'),\" PACE Recoil spectra already exist. Content will be replaced\")\n\n            for key in TalysIsoKey:\n                try:\n                    os.mkdir(args.Outfolder+'/RECSIM/Talys/rec'+key)\n                    print('---Creating rec'+key+' folder---')\n                except:\n                    print('---Creating rec'+key+' folder---')\n                finally:\n                    os.system('rm -r '+args.Outfolder+'/RECSIM/Talys/rec'+key)\n                    os.mkdir(args.Outfolder+'/RECSIM/Talys/rec'+key)\n\n            for key in PACEIsoKey:\n                try:\n                    os.mkdir(args.Outfolder+'/RECSIM/PACE/rec'+key)\n                    print('---Creating rec'+key+' folder---')\n                except:\n                    print('---Creating rec'+key+' folder---')\n                finally:\n                    os.system('rm -r '+args.Outfolder+'/RECSIM/PACE/rec'+key)\n                    os.mkdir(args.Outfolder+'/RECSIM/PACE/rec'+key)\n\n            Elist = recTalysData[TalysIsoKey[0]].keys()\n\n            for isokey in TalysIsoKey:\n                Elist = list(set(recTalysData[isokey].keys()) & set(Elist))\n\n            Elist.sort()\n            print(Elist)\n            for energykey in Elist:\n                print('------Plotting Talys recoil spectra for ',energykey,' MeV proton------')\n                plt.figure()\n                outfile = args.Outfolder+'/RECSIM/Talys/E'+energykey+'.png'\n                Title = 'Energy -> '+energykey+' MeV'\n                plt.title(Title)\n                plt.xlabel(\"Energy [MeV]\")\n                plt.ylabel(\"Counts [a.u.]\")\n                for isokey in TalysIsoKey:\n                    X1, Y1 = listsorter(recTalysData[isokey][energykey][0], recTalysData[isokey][energykey][1])\n                    El = element(int(isokey[0:3]))\n                    label = isokey[3:6]+El.symbol\n                    plt.plot(X1,Y1,label=label,marker = 'o', ms = 3 )#,linestyle = 'None')\n\n                    #plt.hist(X1, bins=X1, weights=Y1, label=label, density = True)\n\n                    #plt.yscale('log')\n                    #plt.show()\n                plt.legend()\n                plt.xlim((0,2.5))\n                plt.savefig(outfile,dpi = 300)\n                plt.close()\n\n\n\n\n            for isokey in PACEIsoKey:\n                for energykey in recPACEData[isokey].keys():\n                    outfile = args.Outfolder+'/RECSIM/PACE/rec'+isokey+'/'+isokey+'E'+energykey+'.png'\n                    print('------Plotting PACE recoil spectra for ',isokey,' produced with ',energykey,' MeV proton------')\n                    plt.figure()\n                    plt.hist(recPACEData[isokey][energykey][0], bins = 30,density = True)\n                    #plt.plot(X1,Y1,label='PACE',marker = 'o', ms = 3, color = 'green',linestyle = 'None')\n                    El = element(int(isokey[0:3]))\n                    Title = isokey[3:6]+El.symbol+' recoil. \\n p energy = '+energykey+' MeV'\n                    plt.title(Title)\n                    plt.xlabel(\"Energy [MeV]\")\n                    plt.ylabel(\"Counts [a.u.]\")\n                    #plt.yscale('log')\n                    #plt.show()\n                    plt.savefig(outfile,dpi = 300)\n                    plt.close()\n\n            for isokey in TalysIsoKey:\n                for energykey in recTalysData[isokey].keys():\n                    outfile = args.Outfolder+'/RECSIM/Talys/rec'+isokey+'/'+isokey+'E'+energykey+'.png'\n                    print('------Plotting Talys recoil spectra for ',isokey,' produced with ',energykey,' MeV proton------')\n\n                    #sorting\n                    X1, Y1 = listsorter(recTalysData[isokey][energykey][0], recTalysData[isokey][energykey][1])\n\n                    plt.figure()\n                    plt.hist(X1, bins=X1, weights=Y1, density = True)\n                    #plt.plot(X1,Y1,label='Talys',marker = 'o', ms = 3, color = 'green',linestyle = 'None')\n                    El = element(int(isokey[0:3]))\n                    Title = isokey[3:6]+El.symbol+' recoil. \\n p energy = '+energykey+' MeV'\n                    plt.title(Title)\n                    plt.xlabel(\"Energy [MeV]\")\n                    plt.ylabel(\"Counts [a.u.]\")\n                    #plt.yscale('log')\n                    #plt.show()\n                    plt.savefig(outfile,dpi = 300)\n                    plt.close()\n\n        elif choice == 6:\n            clear()\n            print(ascii_banner)\n\n            IsoKey = []\n\n            if args.Talysfolder is not None:\n                IsoKey = keysorter(rpTalysData)\n                \n\n            else:\n                print(colored('ERROR :', 'red'), ' Talys Data not provided')\n                raise SystemExit\n\n            try:\n                os.mkdir(args.Outfolder+'/ISOLIST/')\n            except:\n                print(colored('WARNING :', 'yellow'),\"IsoKey list folder already exist. Content will be deleted\")\n            finally:\n                os.system('rm -r '+args.Outfolder+'/ISOLIST/')\n                os.mkdir(args.Outfolder+'/ISOLIST/')\n\n            with open(args.Outfolder+'/ISOLIST/ProductionList.txt','w') as file:\n                for E in range(30,140,5):\n                    xsec = []\n                    isokeys = []\n                    for key in IsoKey:\n                        if E in rpTalysData[key][0]:\n                            index = rpTalysData[key][0].index(E)\n                            xsec.append(rpTalysData[key][1][index])\n                            isokeys.append(key)\n                    \n                    sort = listsorter(xsec,isokeys)\n                    file.write('# Energy -> {:03d} \\n'.format(int(E)))\n                    for i in range(len(sort[0])):\n                        file.write(str(sort[0][i])+' '+str(sort[1][i]+'\\n'))\n\n        elif choice == 7:\n            clear()\n            print(ascii_banner)\n\n            IsoKey = []\n            \n            if args.Talysfolder is not None:\n                tmpKey = keysorter(rpTalysData)\n                CN = ''\n                while True:\n                    CN = input('Insert CN [ZZZAAA] : ')\n                    if (len(CN) == 6): break\n                    print(colored('WARNING :', 'yellow'),\" Wrong CN format\")\n                for key in tmpKey:\n                    if key[0:3] == CN[0:3]: IsoKey.append(key)\n            else:\n                print(colored('ERROR :', 'red'), ' Talys Data not provided')\n                raise SystemExit\n\n            try:\n                os.mkdir(args.Outfolder+'/TALYSPLOT/')\n            except:\n                print(colored('WARNING :', 'yellow'),\"TALYSPLOT folder already exist. Content will be deleted\")\n            finally:\n                os.system('rm -r '+args.Outfolder+'/TALYSPLOT/')\n                os.mkdir(args.Outfolder+'/TALYSPLOT/')\n\n            \n            print('------Plotting Talys production Xsec as a function of E')\n            plt.figure()\n            outfile = args.Outfolder+'/TALYSPLOT/XsecVsE.png'\n            Title = 'XsecVsE'\n            plt.title(Title)\n            plt.xlabel(\"Energy [MeV]\")\n            plt.ylabel(\"Cross Section [mb]\")\n            for key in IsoKey:\n                if (int(CN[3:6])-int(key[3:6])) < 10 :\n                    X, Y = listsorter(rpTalysData[key][0], rpTalysData[key][1])\n                    El = element(int(key[0:3]))\n                    label = key[3:6]+El.symbol+'-'+str(int(CN[3:6])-int(key[3:6]))+' n ev.'\n                    plt.plot(X[:-10],Y[:-10],label=label,marker = 'o', ms = 3 )#,linestyle = 'None')\n\n                    #plt.hist(X1, bins=X1, weights=Y1, label=label, density = True)\n\n            plt.yscale('log')\n            plt.legend(loc='lower right', frameon=False)\n            plt.show()\n            plt.savefig(outfile,dpi = 300)\n            plt.close()\n            \n            print('------Plotting Talys production Xsec as a function of A')\n            \n            sortedData = dict()\n            for energy in range(20,100,5):\n                xsec = []\n                A = []\n                for key in IsoKey:\n                    if energy in rpTalysData[key][0]:\n                        index = rpTalysData[key][0].index(energy)\n                        xsec.append(rpTalysData[key][1][index])\n                        A.append(int(key[3:6]))\n                sortedData[energy] = listsorter(A,xsec)\n            \n            plt.figure()\n            outfile = args.Outfolder+'/TALYSPLOT/XsecVsA.png'\n            Title = 'XsecVsA'\n            plt.title(Title)\n            plt.xlabel(\"A\")\n            plt.ylabel(\"Cross Section [mb]\")\n            for energy in range(45,80,5): \n                label = str(energy)+' MeV'\n                plt.plot(sortedData[energy][0],sortedData[energy][1],label=label,marker = 'o', ms = 2 )#,linestyle = 'None')\n\n                #plt.hist(X1, bins=X1, weights=Y1, label=label, density = True)\n\n                \n                #plt.show()\n            plt.yscale('log')\n            plt.legend(loc='lower right', frameon=False)\n            plt.savefig(outfile,dpi = 300)\n            plt.show()\n            plt.close()\n\n        elif choice == 8:\n            clear()\n            break\n\n\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "3fbd27994c6a1a770f138a219133cb0915db04ea", "size": 38606, "ext": "py", "lang": "Python", "max_stars_repo_path": "Sorter.py", "max_stars_repo_name": "andry3vi/Multi_Threads_Simulation_Manager", "max_stars_repo_head_hexsha": "38e325e4e5d3f622ccca6743807973204935c802", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sorter.py", "max_issues_repo_name": "andry3vi/Multi_Threads_Simulation_Manager", "max_issues_repo_head_hexsha": "38e325e4e5d3f622ccca6743807973204935c802", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sorter.py", "max_forks_repo_name": "andry3vi/Multi_Threads_Simulation_Manager", "max_forks_repo_head_hexsha": "38e325e4e5d3f622ccca6743807973204935c802", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6833667335, "max_line_length": 261, "alphanum_fraction": 0.4790706108, "include": true, "reason": "import numpy", "num_tokens": 9041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3208212943308302, "lm_q1q2_score": 0.16291685957460622}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport logging\nimport numpy as np\nimport astropy.units as u\nfrom astropy.io import fits\nfrom astropy.nddata.utils import NoOverlapError\nfrom astropy.table import Table\nfrom astropy.utils import lazyproperty\nfrom regions import CircleSkyRegion, RectangleSkyRegion\nfrom gammapy.data import GTI\nfrom gammapy.irf import EDispKernel, EffectiveAreaTable\nfrom gammapy.irf.edisp_map import EDispMap, EDispKernelMap\nfrom gammapy.irf.psf_kernel import PSFKernel\nfrom gammapy.irf.psf_map import PSFMap\nfrom gammapy.maps import Map, MapAxis\nfrom gammapy.modeling.models import BackgroundModel, Models, ProperModels\nfrom gammapy.stats import cash, cash_sum_cython, wstat\nfrom gammapy.utils.random import get_random_state\nfrom gammapy.utils.scripts import make_name, make_path\nfrom .core import Dataset\n\n__all__ = [\"MapDataset\", \"MapDatasetOnOff\"]\n\nlog = logging.getLogger(__name__)\n\nCUTOUT_MARGIN = 0.1 * u.deg\nRAD_MAX = 0.66\nRAD_AXIS_DEFAULT = MapAxis.from_bounds(\n    0, RAD_MAX, nbin=66, node_type=\"edges\", name=\"theta\", unit=\"deg\"\n)\nMIGRA_AXIS_DEFAULT = MapAxis.from_bounds(\n    0.2, 5, nbin=48, node_type=\"edges\", name=\"migra\"\n)\n\nBINSZ_IRF_DEFAULT = 0.2\n\n\nclass MapDataset(Dataset):\n    \"\"\"Perform sky model likelihood fit on maps.\n\n    Parameters\n    ----------\n    models : `~gammapy.modeling.models.Models`\n        Source sky models.\n    counts : `~gammapy.maps.WcsNDMap`\n        Counts cube\n    exposure : `~gammapy.maps.WcsNDMap`\n        Exposure cube\n    mask_fit : `~gammapy.maps.WcsNDMap`\n        Mask to apply to the likelihood for fitting.\n    psf : `~gammapy.cube.PSFKernel` or `~gammapy.cube.PSFMap`\n        PSF kernel\n    edisp : `~gammapy.irf.EDispKernel` or `~gammapy.cube.EDispMap`\n        Energy dispersion kernel\n    evaluation_mode : {\"local\", \"global\"}\n        Model evaluation mode.\n        The \"local\" mode evaluates the model components on smaller grids to save computation time.\n        This mode is recommended for local optimization algorithms.\n        The \"global\" evaluation mode evaluates the model components on the full map.\n        This mode is recommended for global optimization algorithms.\n    use_cache : bool\n        Use cached values of frozen models or recompute them\n    mask_safe : `~gammapy.maps.WcsNDMap`\n        Mask defining the safe data range.\n    gti : `~gammapy.data.GTI`\n        GTI of the observation or union of GTI if it is a stacked observation\n    meta_table : `~astropy.table.Table`\n        Table listing informations on observations used to create the dataset.\n        One line per observation for stacked datasets.\n    \"\"\"\n\n    stat_type = \"cash\"\n    tag = \"MapDataset\"\n\n    def __init__(\n        self,\n        models=None,\n        counts=None,\n        exposure=None,\n        mask_fit=None,\n        psf=None,\n        edisp=None,\n        name=None,\n        evaluation_mode=\"local\",\n        use_cache=True,\n        mask_safe=None,\n        gti=None,\n        meta_table=None,\n    ):\n        if mask_fit is not None and mask_fit.data.dtype != np.dtype(\"bool\"):\n            raise ValueError(\"mask data must have dtype bool\")\n\n        if mask_safe is not None and mask_safe.data.dtype != np.dtype(\"bool\"):\n            raise ValueError(\"mask data must have dtype bool\")\n\n        self._name = make_name(name)\n        self._background_model = None\n        self.evaluation_mode = evaluation_mode\n        self.counts = counts\n        self.exposure = exposure\n        self.mask_fit = mask_fit\n        self.psf = psf\n        self.edisp = edisp\n        self.mask_safe = mask_safe\n        self.models = models\n        self.gti = gti\n        self.use_cache = use_cache\n        self.meta_table = meta_table\n\n        # check whether a reference geom is defined\n        _ = self._geom\n\n    @property\n    def name(self):\n        return self._name\n\n    def __str__(self):\n        str_ = f\"{self.__class__.__name__}\\n\"\n        str_ += \"-\" * len(self.__class__.__name__) + \"\\n\"\n        str_ += \"\\n\"\n\n        str_ += \"\\t{:32}: {} \\n\\n\".format(\"Name\", self.name)\n\n        counts = np.nan\n        if self.counts is not None:\n            counts = np.sum(self.counts.data)\n        str_ += \"\\t{:32}: {:.0f} \\n\".format(\"Total counts\", counts)\n\n        npred = np.nan\n        if self.models is not None:\n            npred = np.sum(self.npred().data)\n        str_ += \"\\t{:32}: {:.2f}\\n\".format(\"Total predicted counts\", npred)\n\n        background = np.nan\n        if self.background_model is not None:\n            background = np.sum(self.background_model.evaluate().data)\n        str_ += \"\\t{:32}: {:.2f}\\n\\n\".format(\"Total background counts\", background)\n\n        exposure_min, exposure_max, exposure_unit = np.nan, np.nan, \"\"\n        if self.exposure is not None:\n            if self.mask_safe is not None:\n                mask = self.mask_safe.reduce_over_axes(np.logical_or).data\n                if not mask.any():\n                    mask = None\n            else:\n                mask = None\n            exposure_min = np.min(self.exposure.data[..., mask])\n            exposure_max = np.max(self.exposure.data[..., mask])\n            exposure_unit = self.exposure.unit\n\n        str_ += \"\\t{:32}: {:.2e} {}\\n\".format(\n            \"Exposure min\", exposure_min, exposure_unit\n        )\n        str_ += \"\\t{:32}: {:.2e} {}\\n\\n\".format(\n            \"Exposure max\", exposure_max, exposure_unit\n        )\n\n        # data section\n        n_bins = 0\n        if self.counts is not None:\n            n_bins = self.counts.data.size\n        str_ += \"\\t{:32}: {} \\n\".format(\"Number of total bins\", n_bins)\n\n        n_fit_bins = 0\n        if self.mask is not None:\n            n_fit_bins = np.sum(self.mask.data)\n        str_ += \"\\t{:32}: {} \\n\\n\".format(\"Number of fit bins\", n_fit_bins)\n\n        # likelihood section\n        str_ += \"\\t{:32}: {}\\n\".format(\"Fit statistic type\", self.stat_type)\n\n        stat = np.nan\n        if self.counts is not None and self.models is not None:\n            stat = self.stat_sum()\n        str_ += \"\\t{:32}: {:.2f}\\n\\n\".format(\"Fit statistic value (-2 log(L))\", stat)\n\n        # model section\n        n_models, n_pars, n_free_pars = 0, 0, 0\n        if self.models is not None:\n            n_models = len(self.models)\n            n_pars = len(self.models.parameters)\n            n_free_pars = len(self.models.parameters.free_parameters)\n\n        str_ += \"\\t{:32}: {} \\n\".format(\"Number of models\", n_models)\n        str_ += \"\\t{:32}: {}\\n\".format(\"Number of parameters\", n_pars)\n        str_ += \"\\t{:32}: {}\\n\\n\".format(\"Number of free parameters\", n_free_pars)\n\n        if self.models is not None:\n            str_ += \"\\t\" + \"\\n\\t\".join(str(self.models).split(\"\\n\")[2:])\n\n        return str_.expandtabs(tabsize=2)\n\n    @property\n    def models(self):\n        \"\"\"Models (`~gammapy.modeling.models.Models`).\"\"\"\n        return ProperModels(self)\n\n    @property\n    def background_model(self):\n        return self._background_model\n\n    @models.setter\n    def models(self, models):\n        if models is None:\n            self._models = None\n        else:\n            self._models = Models(models)\n\n        # TODO: clean this up (probably by removing)\n        if self.models is not None:\n            for model in self.models:\n                if isinstance(model, BackgroundModel):\n                    if model.datasets_names is not None:\n                        if self.name in model.datasets_names:\n                            self._background_model = model\n                            break\n            else:\n                log.warning(f\"No background model defined for dataset {self.name}\")\n        self._evaluators = {}\n\n    @property\n    def evaluators(self):\n        \"\"\"Model evaluators\"\"\"\n\n        models = self.models\n        if models:\n            keys = list(self._evaluators.keys())\n            for key in keys:\n                if key not in models:\n                    del self._evaluators[key]\n\n            for model in models:\n                evaluator = self._evaluators.get(model)\n\n                if evaluator is None:\n                    evaluator = MapEvaluator(\n                        model=model, evaluation_mode=self.evaluation_mode, gti=self.gti\n                    )\n                    self._evaluators[model] = evaluator\n\n                # if the model component drifts out of its support the evaluator has\n                # has to be updated\n                if evaluator.needs_update:\n                    evaluator.update(self.exposure, self.psf, self.edisp, self._geom)\n\n        return self._evaluators\n\n    @property\n    def _geom(self):\n        \"\"\"Main analysis geometry\"\"\"\n        if self.counts is not None:\n            return self.counts.geom\n        elif self.background_model is not None:\n            return self.background_model.map.geom\n        elif self.mask_safe is not None:\n            return self.mask_safe.geom\n        elif self.mask_fit is not None:\n            return self.mask_fit.geom\n        else:\n            raise ValueError(\n                \"Either 'counts', 'background_model', 'mask_fit'\"\n                \" or 'mask_safe' must be defined.\"\n            )\n\n    @property\n    def data_shape(self):\n        \"\"\"Shape of the counts or background data (tuple)\"\"\"\n        return self._geom.data_shape\n\n    def npred(self):\n        \"\"\"Predicted source and background counts (`~gammapy.maps.Map`).\"\"\"\n        npred_total = Map.from_geom(self._geom, dtype=float)\n\n        for evaluator in self.evaluators.values():\n            if evaluator.contributes:\n                if self.use_cache is False:\n                    evaluator._pars_cached = None\n                npred = evaluator.compute_npred()\n                npred_total.stack(npred)\n        return npred_total\n\n    @classmethod\n    def from_geoms(\n        cls,\n        geom,\n        geom_exposure,\n        geom_psf,\n        geom_edisp,\n        reference_time=\"2000-01-01\",\n        name=None,\n        **kwargs,\n    ):\n        \"\"\"\n        Create a MapDataset object with zero filled maps according to the specified geometries\n\n        Parameters\n        ----------\n        geom : `Geom`\n            geometry for the counts and background maps\n        geom_exposure : `Geom`\n            geometry for the exposure map\n        geom_psf : `Geom`\n            geometry for the psf map\n        geom_edisp : `Geom`\n            geometry for the energy dispersion kernel map.\n            If geom_edisp has a migra axis, this wil create an EDispMap instead.\n        reference_time : `~astropy.time.Time`\n            the reference time to use in GTI definition\n        name : str\n            Name of the returned dataset.\n\n        Returns\n        -------\n        empty_maps : `MapDataset`\n            A MapDataset containing zero filled maps\n        \"\"\"\n        name = make_name(name)\n        kwargs = kwargs.copy()\n        kwargs[\"name\"] = name\n        kwargs[\"counts\"] = Map.from_geom(geom, unit=\"\")\n\n        background = Map.from_geom(geom, unit=\"\")\n        kwargs[\"models\"] = Models(\n            [BackgroundModel(background, name=name + \"-bkg\", datasets_names=[name])]\n        )\n        kwargs[\"exposure\"] = Map.from_geom(geom_exposure, unit=\"m2 s\")\n\n        if geom_edisp.axes[0].name.lower() == \"energy\":\n            kwargs[\"edisp\"] = EDispKernelMap.from_geom(geom_edisp)\n        else:\n            kwargs[\"edisp\"] = EDispMap.from_geom(geom_edisp)\n\n        kwargs[\"psf\"] = PSFMap.from_geom(geom_psf)\n\n        kwargs.setdefault(\n            \"gti\", GTI.create([] * u.s, [] * u.s, reference_time=reference_time)\n        )\n        kwargs[\"mask_safe\"] = Map.from_geom(geom, unit=\"\", dtype=bool)\n\n        return cls(**kwargs)\n\n    @classmethod\n    def create(\n        cls,\n        geom,\n        energy_axis_true=None,\n        migra_axis=None,\n        rad_axis=None,\n        binsz_irf=None,\n        reference_time=\"2000-01-01\",\n        name=None,\n        meta_table=None,\n        **kwargs,\n    ):\n        \"\"\"Create a MapDataset object with zero filled maps.\n\n        Parameters\n        ----------\n        geom : `~gammapy.maps.WcsGeom`\n            Reference target geometry in reco energy, used for counts and background maps\n        energy_axis_true : `~gammapy.maps.MapAxis`\n            True energy axis used for IRF maps\n        migra_axis : `~gammapy.maps.MapAxis`\n            If set, this provides the migration axis for the energy dispersion map.\n            If not set, an EDispKernelMap is produced instead. Default is None\n        rad_axis : `~gammapy.maps.MapAxis`\n            Rad axis for the psf map\n        binsz_irf : float\n            IRF Map pixel size in degrees.\n        reference_time : `~astropy.time.Time`\n            the reference time to use in GTI definition\n        name : str\n            Name of the returned dataset.\n        meta_table : `~astropy.table.Table`\n            Table listing informations on observations used to create the dataset.\n            One line per observation for stacked datasets.\n\n        Returns\n        -------\n        empty_maps : `MapDataset`\n            A MapDataset containing zero filled maps\n        \"\"\"\n        rad_axis = rad_axis or RAD_AXIS_DEFAULT\n\n        if energy_axis_true is not None:\n            if energy_axis_true.name != \"energy_true\":\n                raise ValueError(\"True enery axis name must be 'energy_true'\")\n        else:\n            energy_axis_true = geom.get_axis_by_name(\"energy\").copy(name=\"energy_true\")\n\n        binsz_irf = binsz_irf or BINSZ_IRF_DEFAULT\n        geom_image = geom.to_image()\n        geom_exposure = geom_image.to_cube([energy_axis_true])\n        geom_irf = geom_image.to_binsz(binsz=binsz_irf)\n        geom_psf = geom_irf.to_cube([rad_axis, energy_axis_true])\n        if migra_axis:\n            geom_edisp = geom_irf.to_cube([migra_axis, energy_axis_true])\n        else:\n            geom_edisp = geom_irf.to_cube(\n                [geom.get_axis_by_name(\"energy\"), energy_axis_true]\n            )\n\n        return cls.from_geoms(\n            geom,\n            geom_exposure,\n            geom_psf,\n            geom_edisp,\n            reference_time=reference_time,\n            name=name,\n            **kwargs,\n        )\n\n    def stack(self, other):\n        \"\"\"Stack another dataset in place.\n\n        Parameters\n        ----------\n        other: `~gammapy.cube.MapDataset` or `~gammapy.cube.MapDatasetOnOff`\n            Map dataset to be stacked with this one. If other is an on-off\n            dataset alpha * counts_off is used as a background model.\n        \"\"\"\n        if self.mask_safe is None:\n            self.mask_safe = Map.from_geom(\n                self._geom, data=np.ones_like(self.data_shape)\n            )\n\n        if other.mask_safe is None:\n            other_mask_safe = Map.from_geom(\n                other._geom, data=np.ones_like(other.data_shape)\n            )\n        else:\n            other_mask_safe = other.mask_safe\n\n        if self.counts and other.counts:\n            self.counts *= self.mask_safe\n            self.counts.stack(other.counts, weights=other_mask_safe)\n\n        if self.exposure and other.exposure:\n            mask_image = self.mask_safe.reduce_over_axes(func=np.logical_or)\n            self.exposure *= mask_image.data\n            # TODO: apply energy dependent mask to exposure. Does this require\n            #  a mask_safe in true energy?\n            mask_image_other = other_mask_safe.reduce_over_axes(func=np.logical_or)\n            self.exposure.stack(other.exposure, weights=mask_image_other)\n\n        # TODO: unify background model handling\n        if other.stat_type == \"wstat\":\n            background_model = BackgroundModel(other.background)\n        else:\n            background_model = other.background_model\n\n        if self.background_model and background_model:\n            self._background_model.map *= self.mask_safe\n            self._background_model.stack(background_model, other_mask_safe)\n            self.models = Models([self.background_model])\n        else:\n            self.models = None\n\n        if self.psf and other.psf:\n            if isinstance(self.psf, PSFMap) and isinstance(other.psf, PSFMap):\n                mask_irf = self._mask_safe_irf(self.psf.psf_map, mask_image)\n                self.psf.psf_map *= mask_irf.data\n                self.psf.exposure_map *= mask_irf.data\n\n                mask_image_other = other_mask_safe.reduce_over_axes(func=np.logical_or)\n                mask_irf_other = self._mask_safe_irf(\n                    other.psf.psf_map, mask_image_other\n                )\n                self.psf.stack(other.psf, weights=mask_irf_other)\n            else:\n                raise ValueError(\"Stacking of PSF kernels not supported\")\n\n        if self.edisp and other.edisp:\n            if isinstance(self.edisp, EDispMap) and isinstance(other.edisp, EDispMap):\n                mask_irf = self._mask_safe_irf(self.edisp.edisp_map, mask_image)\n                self.edisp.edisp_map *= mask_irf.data\n                self.edisp.exposure_map *= mask_irf.data\n\n                mask_image_other = other_mask_safe.reduce_over_axes(func=np.logical_or)\n                mask_irf_other = self._mask_safe_irf(\n                    other.edisp.edisp_map, mask_image_other\n                )\n                self.edisp.stack(other.edisp, weights=mask_irf_other)\n            elif isinstance(self.edisp, EDispKernelMap) and isinstance(\n                other.edisp, EDispKernelMap\n            ):\n                mask_irf = self._mask_safe_irf(self.edisp.edisp_map, mask_image)\n                self.edisp.edisp_map *= mask_irf.data\n                self.edisp.exposure_map *= mask_irf.data\n\n                mask_image_other = other_mask_safe.reduce_over_axes(func=np.logical_or)\n                mask_irf_other = self._mask_safe_irf(\n                    other.edisp.edisp_map, mask_image_other\n                )\n                self.edisp.stack(other.edisp, weights=mask_irf_other)\n            else:\n                raise ValueError(\"Stacking of edisp kernels not supported\")\n\n        self.mask_safe.stack(other_mask_safe)\n\n        if self.gti and other.gti:\n            self.gti = self.gti.stack(other.gti).union()\n\n    @staticmethod\n    def _mask_safe_irf(irf_map, mask):\n        geom = irf_map.geom.to_image()\n        coords = geom.get_coord()\n        data = mask.get_by_coord(coords).astype(bool)\n        return Map.from_geom(geom=geom, data=data)\n\n    def stat_array(self):\n        \"\"\"Likelihood per bin given the current model parameters\"\"\"\n        return cash(n_on=self.counts.data, mu_on=self.npred().data)\n\n    def residuals(self, method=\"diff\"):\n        \"\"\"Compute residuals map.\n\n        Parameters\n        ----------\n        method: {\"diff\", \"diff/model\", \"diff/sqrt(model)\"}\n            Method used to compute the residuals. Available options are:\n                - \"diff\" (default): data - model\n                - \"diff/model\": (data - model) / model\n                - \"diff/sqrt(model)\": (data - model) / sqrt(model)\n\n        Returns\n        -------\n        residuals : `gammapy.maps.WcsNDMap`\n            Residual map.\n        \"\"\"\n        return self._compute_residuals(self.counts, self.npred(), method=method)\n\n    def plot_residuals(\n        self,\n        method=\"diff\",\n        smooth_kernel=\"gauss\",\n        smooth_radius=\"0.1 deg\",\n        region=None,\n        figsize=(12, 4),\n        **kwargs,\n    ):\n        \"\"\"\n        Plot spatial and spectral residuals.\n\n        The spectral residuals are extracted from the provided region, and the\n        normalization used for the residuals computation can be controlled using\n        the method parameter. If no region is passed, only the spatial\n        residuals are shown.\n\n        Parameters\n        ----------\n        method : {\"diff\", \"diff/model\", \"diff/sqrt(model)\"}\n            Method used to compute the residuals, see `MapDataset.residuals()`\n        smooth_kernel : {'gauss', 'box'}\n            Kernel shape.\n        smooth_radius: `~astropy.units.Quantity`, str or float\n            Smoothing width given as quantity or float. If a float is given it\n            is interpreted as smoothing width in pixels.\n        region: `~regions.Region`\n            Region (pixel or sky regions accepted)\n        figsize : tuple\n            Figure size used for the plotting.\n        **kwargs : dict\n            Keyword arguments passed to `~matplotlib.pyplot.imshow`.\n\n        Returns\n        -------\n        ax_image, ax_spec : `~matplotlib.pyplot.Axes`,\n            Image and spectrum axes.\n        \"\"\"\n        import matplotlib.pyplot as plt\n\n        fig = plt.figure(figsize=figsize)\n\n        counts, npred = self.counts, self.npred()\n\n        if self.mask is not None:\n            counts = counts * self.mask\n            npred = npred * self.mask\n\n        counts_spatial = counts.sum_over_axes().smooth(\n            width=smooth_radius, kernel=smooth_kernel\n        )\n        npred_spatial = npred.sum_over_axes().smooth(\n            width=smooth_radius, kernel=smooth_kernel\n        )\n        spatial_residuals = self._compute_residuals(\n            counts_spatial, npred_spatial, method\n        )\n\n        if self.mask_safe is not None:\n            mask = self.mask_safe.reduce_over_axes(func=np.logical_or)\n            spatial_residuals.data[~mask.data] = np.nan\n\n        # If no region is provided, skip spectral residuals\n        ncols = 2 if region is not None else 1\n        ax_image = fig.add_subplot(1, ncols, 1, projection=spatial_residuals.geom.wcs)\n        ax_spec = None\n\n        kwargs.setdefault(\"cmap\", \"coolwarm\")\n        kwargs.setdefault(\"stretch\", \"linear\")\n        kwargs.setdefault(\"vmin\", -5)\n        kwargs.setdefault(\"vmax\", 5)\n        spatial_residuals.plot(ax=ax_image, add_cbar=True, **kwargs)\n\n        # Spectral residuals\n        if region:\n            ax_spec = fig.add_subplot(1, 2, 2)\n            counts_spec = counts.get_spectrum(region=region)\n            npred_spec = npred.get_spectrum(region=region)\n            residuals = self._compute_residuals(counts_spec, npred_spec, method)\n            ax = residuals.plot()\n            ax.set_yscale(\"linear\")\n            ax.axhline(0, color=\"black\", lw=0.5)\n\n            y_max = 2 * np.nanmax(residuals.data)\n            plt.ylim(-y_max, y_max)\n            label = self._residuals_labels[method]\n            plt.ylabel(f\"Residuals ({label})\")\n\n            # Overlay spectral extraction region on the spatial residuals\n            pix_region = region.to_pixel(wcs=spatial_residuals.geom.wcs)\n            pix_region.plot(ax=ax_image)\n\n        return ax_image, ax_spec\n\n    @lazyproperty\n    def _counts_data(self):\n        return self.counts.data.astype(float)\n\n    def stat_sum(self):\n        \"\"\"Total likelihood given the current model parameters.\"\"\"\n        counts, npred = self._counts_data, self.npred().data\n\n        if self.mask is not None:\n            return cash_sum_cython(counts[self.mask.data], npred[self.mask.data])\n        else:\n            return cash_sum_cython(counts.ravel(), npred.ravel())\n\n    def fake(self, random_state=\"random-seed\"):\n        \"\"\"Simulate fake counts for the current model and reduced IRFs.\n\n        This method overwrites the counts defined on the dataset object.\n\n        Parameters\n        ----------\n        random_state : {int, 'random-seed', 'global-rng', `~numpy.random.RandomState`}\n                Defines random number generator initialisation.\n                Passed to `~gammapy.utils.random.get_random_state`.\n        \"\"\"\n        random_state = get_random_state(random_state)\n        npred = self.npred()\n        npred.data = random_state.poisson(npred.data)\n        self.counts = npred\n\n    def to_hdulist(self):\n        \"\"\"Convert map dataset to list of HDUs.\n\n        Returns\n        -------\n        hdulist : `~astropy.io.fits.HDUList`\n            Map dataset list of HDUs.\n        \"\"\"\n        # TODO: what todo about the model and background model parameters?\n        exclude_primary = slice(1, None)\n\n        hdu_primary = fits.PrimaryHDU()\n        hdulist = fits.HDUList([hdu_primary])\n        if self.counts is not None:\n            hdulist += self.counts.to_hdulist(hdu=\"counts\")[exclude_primary]\n\n        if self.exposure is not None:\n            hdulist += self.exposure.to_hdulist(hdu=\"exposure\")[exclude_primary]\n\n        if self.background_model is not None:\n            hdulist += self.background_model.map.to_hdulist(hdu=\"background\")[\n                exclude_primary\n            ]\n\n        if self.edisp is not None:\n            if isinstance(self.edisp, EDispKernel):\n                hdus = self.edisp.to_hdulist()\n                hdus[\"MATRIX\"].name = \"edisp_matrix\"\n                hdus[\"EBOUNDS\"].name = \"edisp_matrix_ebounds\"\n                hdulist.append(hdus[\"EDISP_MATRIX\"])\n                hdulist.append(hdus[\"EDISP_MATRIX_EBOUNDS\"])\n            else:\n                hdulist += self.edisp.edisp_map.to_hdulist(hdu=\"EDISP\")[exclude_primary]\n                hdulist += self.edisp.exposure_map.to_hdulist(hdu=\"edisp_exposure\")[\n                    exclude_primary\n                ]\n\n        if self.psf is not None:\n            if isinstance(self.psf, PSFKernel):\n                hdulist += self.psf.psf_kernel_map.to_hdulist(hdu=\"psf_kernel\")[\n                    exclude_primary\n                ]\n            else:\n                hdulist += self.psf.psf_map.to_hdulist(hdu=\"psf\")[exclude_primary]\n                hdulist += self.psf.exposure_map.to_hdulist(hdu=\"psf_exposure\")[\n                    exclude_primary\n                ]\n\n        if self.mask_safe is not None:\n            mask_safe_int = self.mask_safe.copy()\n            mask_safe_int.data = mask_safe_int.data.astype(int)\n            hdulist += mask_safe_int.to_hdulist(hdu=\"mask_safe\")[exclude_primary]\n\n        if self.mask_fit is not None:\n            mask_fit_int = self.mask_fit.copy()\n            mask_fit_int.data = mask_fit_int.data.astype(int)\n            hdulist += mask_fit_int.to_hdulist(hdu=\"mask_fit\")[exclude_primary]\n\n        if self.gti is not None:\n            hdulist.append(fits.BinTableHDU(self.gti.table, name=\"GTI\"))\n\n        return hdulist\n\n    @classmethod\n    def from_hdulist(cls, hdulist, name=None):\n        \"\"\"Create map dataset from list of HDUs.\n\n        Parameters\n        ----------\n        hdulist : `~astropy.io.fits.HDUList`\n            List of HDUs.\n        name : str\n            Name of the new dataset.\n\n        Returns\n        -------\n        dataset : `MapDataset`\n            Map dataset.\n        \"\"\"\n        name = make_name(name)\n        kwargs = {\"name\": name}\n\n        if \"COUNTS\" in hdulist:\n            kwargs[\"counts\"] = Map.from_hdulist(hdulist, hdu=\"counts\")\n\n        if \"EXPOSURE\" in hdulist:\n            exposure = Map.from_hdulist(hdulist, hdu=\"exposure\")\n            if exposure.geom.axes[0].name == \"energy\":\n                exposure.geom.axes[0].name = \"energy_true\"\n            kwargs[\"exposure\"] = exposure\n\n        if \"BACKGROUND\" in hdulist:\n            background_map = Map.from_hdulist(hdulist, hdu=\"background\")\n            kwargs[\"models\"] = Models(\n                [\n                    BackgroundModel(\n                        background_map, datasets_names=[name], name=name + \"-bkg\"\n                    )\n                ]\n            )\n\n        if \"EDISP_MATRIX\" in hdulist:\n            kwargs[\"edisp\"] = EDispKernel.from_hdulist(\n                hdulist, hdu1=\"EDISP_MATRIX\", hdu2=\"EDISP_MATRIX_EBOUNDS\"\n            )\n        if \"EDISP\" in hdulist:\n            edisp_map = Map.from_hdulist(hdulist, hdu=\"edisp\")\n            exposure_map = Map.from_hdulist(hdulist, hdu=\"edisp_exposure\")\n            if edisp_map.geom.axes[0].name == \"energy\":\n                kwargs[\"edisp\"] = EDispKernelMap(edisp_map, exposure_map)\n            else:\n                kwargs[\"edisp\"] = EDispMap(edisp_map, exposure_map)\n\n        if \"PSF_KERNEL\" in hdulist:\n            psf_map = Map.from_hdulist(hdulist, hdu=\"psf_kernel\")\n            kwargs[\"psf\"] = PSFKernel(psf_map)\n        if \"PSF\" in hdulist:\n            psf_map = Map.from_hdulist(hdulist, hdu=\"psf\")\n            exposure_map = Map.from_hdulist(hdulist, hdu=\"psf_exposure\")\n            kwargs[\"psf\"] = PSFMap(psf_map, exposure_map)\n\n        if \"MASK_SAFE\" in hdulist:\n            mask_safe = Map.from_hdulist(hdulist, hdu=\"mask_safe\")\n            mask_safe.data = mask_safe.data.astype(bool)\n            kwargs[\"mask_safe\"] = mask_safe\n\n        if \"MASK_FIT\" in hdulist:\n            mask_fit = Map.from_hdulist(hdulist, hdu=\"mask_fit\")\n            mask_fit.data = mask_fit.data.astype(bool)\n            kwargs[\"mask_fit\"] = mask_fit\n\n        if \"GTI\" in hdulist:\n            gti = GTI(Table.read(hdulist, hdu=\"GTI\"))\n            kwargs[\"gti\"] = gti\n\n        return cls(**kwargs)\n\n    def write(self, filename, overwrite=False):\n        \"\"\"Write map dataset to file.\n\n        Parameters\n        ----------\n        filename : str\n            Filename to write to.\n        overwrite : bool\n            Overwrite file if it exists.\n        \"\"\"\n        self.to_hdulist().writeto(make_path(filename), overwrite=overwrite)\n\n    @classmethod\n    def read(cls, filename, name=None):\n        \"\"\"Read map dataset from file.\n\n        Parameters\n        ----------\n        filename : str\n            Filename to read from.\n        name : str\n            Name of the new dataset.\n\n        Returns\n        -------\n        dataset : `MapDataset`\n            Map dataset.\n        \"\"\"\n        with fits.open(make_path(filename), memmap=False) as hdulist:\n            return cls.from_hdulist(hdulist, name=name)\n\n    @classmethod\n    def from_dict(cls, data, models):\n        \"\"\"Create from dicts and models list generated from YAML serialization.\"\"\"\n\n        filename = make_path(data[\"filename\"])\n        dataset = cls.read(filename, name=data[\"name\"])\n\n        for model in models:\n            if (\n                isinstance(model, BackgroundModel)\n                and model.filename is None\n                and dataset.name == model.datasets_names[0]\n            ):\n                model.map = dataset.background_model.map\n\n        dataset.models = models\n        return dataset\n\n    def to_dict(self, filename=\"\"):\n        \"\"\"Convert to dict for YAML serialization.\"\"\"\n        return {\n            \"name\": self.name,\n            \"type\": self.tag,\n            \"filename\": str(filename),\n        }\n\n    def info_dict(self, region=None):\n        \"\"\"Basic info dict with summary statistics\n\n        If a region is passed, then a spectrum dataset is\n        extracted, and the corresponding info returned.\n\n        Parameters\n        ----------\n        region : `~regions.SkyRegion`, optional\n            the input ON region on which to extract the spectrum\n\n        Returns\n        -------\n        info_dict : dict\n            Dictionary with summary info.\n        \"\"\"\n        if self.gti is not None:\n            if region is None:\n                region = RectangleSkyRegion(\n                    center=self._geom.center_skydir,\n                    width=self._geom.width[0][0],\n                    height=self._geom.width[1][0],\n                )\n            info = self.to_spectrum_dataset(on_region=region).info_dict()\n        else:\n            info = dict()\n            if self.counts:\n                info[\"counts\"] = np.sum(self.counts.data)\n            if self.background_model:\n                info[\"background\"] = np.sum(self.background_model.evaluate().data)\n                info[\"excess\"] = info[\"counts\"] - info[\"background\"]\n\n            info[\"npred\"] = np.sum(self.npred())\n            if self.mask_safe is not None:\n                mask = self.mask_safe.reduce_over_axes(np.logical_or).data\n                if not mask.any():\n                    mask = None\n            else:\n                mask = None\n            if self.exposure:\n                exposure_min = np.min(self.exposure.data[..., mask])\n                exposure_max = np.max(self.exposure.data[..., mask])\n                info[\"aeff_min\"] = exposure_min * self.exposure.unit\n                info[\"aeff_max\"] = exposure_max * self.exposure.unit\n\n        info[\"name\"] = self.name\n\n        return info\n\n    def to_spectrum_dataset(self, on_region, containment_correction=False, name=None):\n        \"\"\"Return a ~gammapy.spectrum.SpectrumDataset from on_region.\n\n        Counts and background are summed in the on_region.\n\n        Effective area is taken from the average exposure divided by the livetime.\n        Here we assume it is the sum of the GTIs.\n\n        The energy dispersion kernel is obtained at the on_region center.\n        Only regions with centers are supported.\n\n        The model is not exported to the ~gammapy.spectrum.SpectrumDataset.\n        It must be set after the dataset extraction.\n\n        Parameters\n        ----------\n        on_region : `~regions.SkyRegion`\n            the input ON region on which to extract the spectrum\n        containment_correction : bool\n            Apply containment correction for point sources and circular on regions\n        name : str\n            Name of the new dataset.\n\n        Returns\n        -------\n        dataset : `~gammapy.spectrum.SpectrumDataset`\n            the resulting reduced dataset\n        \"\"\"\n        from .spectrum import SpectrumDataset\n\n        kwargs = {\"gti\": self.gti, \"name\": name}\n\n        if self.gti is not None:\n            kwargs[\"livetime\"] = self.gti.time_sum\n        else:\n            raise ValueError(\"No GTI in `MapDataset`, cannot compute livetime\")\n\n        if self.counts is not None:\n            kwargs[\"counts\"] = self.counts.get_spectrum(on_region, np.sum)\n\n        if self.background_model is not None:\n            kwargs[\"background\"] = self.background_model.evaluate().get_spectrum(\n                on_region, np.sum\n            )\n\n        if self.exposure is not None:\n            exposure = self.exposure.get_spectrum(on_region, np.mean)\n            energy = exposure.geom.axes[0].edges\n            kwargs[\"aeff\"] = EffectiveAreaTable(\n                energy_lo=energy[:-1],\n                energy_hi=energy[1:],\n                data=exposure.quantity[:, 0, 0] / kwargs[\"livetime\"],\n            )\n\n        if containment_correction:\n            if not isinstance(on_region, CircleSkyRegion):\n                raise TypeError(\n                    \"Containement correction is only supported for\"\n                    \" `CircleSkyRegion`.\"\n                )\n            elif self.psf is None or isinstance(self.psf, PSFKernel):\n                raise ValueError(\"No PSFMap set. Containement correction impossible\")\n            else:\n                psf = self.psf.get_energy_dependent_table_psf(on_region.center)\n                containment = psf.containment(\n                    kwargs[\"aeff\"].energy.center, on_region.radius\n                )\n                kwargs[\"aeff\"].data.data *= containment.squeeze()\n\n        if self.edisp is not None:\n            if isinstance(self.edisp, EDispKernel):\n                edisp = self.edisp\n            elif isinstance(self.edisp, EDispKernelMap):\n                edisp = self.edisp.get_edisp_kernel(on_region.center)\n            else:\n                axis = self._geom.get_axis_by_name(\"energy\")\n                edisp = self.edisp.get_edisp_kernel(on_region.center, e_reco=axis.edges)\n            kwargs[\"edisp\"] = edisp\n\n        return SpectrumDataset(**kwargs)\n\n    def to_image(self, spectrum=None, name=None):\n        \"\"\"Create images by summing over the energy axis.\n\n        Exposure is weighted with an assumed spectrum,\n        resulting in a weighted mean exposure image.\n\n        Currently the PSFMap and EdispMap are dropped from the\n        resulting image dataset.\n\n        Parameters\n        ----------\n        spectrum : `~gammapy.modeling.models.SpectralModel`\n            Spectral model to compute the weights.\n            Default is power-law with spectral index of 2.\n        name : str\n            Name of the new dataset.\n\n        Returns\n        -------\n        dataset : `MapDataset`\n            Map dataset containing images.\n        \"\"\"\n        from gammapy.makers.utils import _map_spectrum_weight\n\n        name = make_name(name)\n        kwargs = {}\n        kwargs[\"name\"] = name\n        kwargs[\"gti\"] = self.gti\n\n        if self.mask_safe is not None:\n            mask_safe = self.mask_safe\n            kwargs[\"mask_safe\"] = mask_safe.reduce_over_axes(\n                func=np.logical_or, keepdims=True\n            )\n        else:\n            mask_safe = 1\n\n        if self.counts is not None:\n            counts = self.counts * mask_safe\n            kwargs[\"counts\"] = counts.sum_over_axes(keepdims=True)\n\n        if self.exposure is not None:\n            exposure = _map_spectrum_weight(self.exposure, spectrum)\n            kwargs[\"exposure\"] = exposure.sum_over_axes(keepdims=True)\n\n        if self.background_model is not None:\n            background = self.background_model.evaluate() * mask_safe\n            background = background.sum_over_axes(keepdims=True)\n            kwargs[\"models\"] = Models(\n                [BackgroundModel(background, datasets_names=[name])]\n            )\n\n        if self.psf is not None:\n            # TODO: implement PSFKernel.to_image()\n            if not isinstance(self.psf, PSFKernel):\n                kwargs[\"psf\"] = self.psf.to_image(spectrum=spectrum, keepdims=True)\n            else:\n                # assume exposure at center position\n                kwargs[\"psf\"] = None\n\n        return self.__class__(**kwargs)\n\n    def cutout(self, position, width, mode=\"trim\", name=None):\n        \"\"\"Cutout map dataset.\n\n        Parameters\n        ----------\n        position : `~astropy.coordinates.SkyCoord`\n            Center position of the cutout region.\n        width : tuple of `~astropy.coordinates.Angle`\n            Angular sizes of the region in (lon, lat) in that specific order.\n            If only one value is passed, a square region is extracted.\n        mode : {'trim', 'partial', 'strict'}\n            Mode option for Cutout2D, for details see `~astropy.nddata.utils.Cutout2D`.\n        name : str\n            Name of the new dataset.\n\n        Returns\n        -------\n        cutout : `MapDataset`\n            Cutout map dataset.\n        \"\"\"\n        name = make_name(name)\n        kwargs = {\"gti\": self.gti, \"name\": name}\n        cutout_kwargs = {\"position\": position, \"width\": width, \"mode\": mode}\n\n        if self.counts is not None:\n            kwargs[\"counts\"] = self.counts.cutout(**cutout_kwargs)\n\n        if self.exposure is not None:\n            kwargs[\"exposure\"] = self.exposure.cutout(**cutout_kwargs)\n\n        if self.background_model is not None:\n            model = self.background_model.cutout(**cutout_kwargs, name=name + \"-bkg\")\n            model.datasets_names = [name]\n            kwargs[\"models\"] = model\n\n        if self.edisp is not None:\n            kwargs[\"edisp\"] = self.edisp.cutout(**cutout_kwargs)\n\n        if self.psf is not None:\n            kwargs[\"psf\"] = self.psf.cutout(**cutout_kwargs)\n\n        if self.mask_safe is not None:\n            kwargs[\"mask_safe\"] = self.mask_safe.cutout(**cutout_kwargs)\n\n        if self.mask_fit is not None:\n            kwargs[\"mask_fit\"] = self.mask_fit.cutout(**cutout_kwargs)\n\n        return self.__class__(**kwargs)\n\n\nclass MapDatasetOnOff(MapDataset):\n    \"\"\"Map dataset for on-off likelihood fitting.\n\n    Parameters\n    ----------\n    models : `~gammapy.modeling.models.Models`\n        Source sky models.\n    counts : `~gammapy.maps.WcsNDMap`\n        Counts cube\n    counts_off : `~gammapy.maps.WcsNDMap`\n        Ring-convolved counts cube\n    acceptance : `~gammapy.maps.WcsNDMap`\n        Acceptance from the IRFs\n    acceptance_off : `~gammapy.maps.WcsNDMap`\n        Acceptance off\n    exposure : `~gammapy.maps.WcsNDMap`\n        Exposure cube\n    mask_fit : `~numpy.ndarray`\n        Mask to apply to the likelihood for fitting.\n    psf : `~gammapy.cube.PSFKernel`\n        PSF kernel\n    edisp : `~gammapy.irf.EDispKernel`\n        Energy dispersion\n    evaluation_mode : {\"local\", \"global\"}\n        Model evaluation mode.\n        The \"local\" mode evaluates the model components on smaller grids to save computation time.\n        This mode is recommended for local optimization algorithms.\n        The \"global\" evaluation mode evaluates the model components on the full map.\n        This mode is recommended for global optimization algorithms.\n    mask_safe : `~numpy.ndarray`\n        Mask defining the safe data range.\n    gti : `~gammapy.data.GTI`\n        GTI of the observation or union of GTI if it is a stacked observation\n    meta_table : `~astropy.table.Table`\n        Table listing informations on observations used to create the dataset.\n        One line per observation for stacked datasets.\n    name : str\n        Name of the dataset.\n\n    \"\"\"\n\n    stat_type = \"wstat\"\n    tag = \"MapDatasetOnOff\"\n\n    def __init__(\n        self,\n        models=None,\n        counts=None,\n        counts_off=None,\n        acceptance=None,\n        acceptance_off=None,\n        exposure=None,\n        mask_fit=None,\n        psf=None,\n        edisp=None,\n        name=None,\n        evaluation_mode=\"local\",\n        mask_safe=None,\n        gti=None,\n        meta_table=None,\n    ):\n        if mask_fit is not None and mask_fit.dtype != np.dtype(\"bool\"):\n            raise ValueError(\"mask data must have dtype bool\")\n\n        self.evaluation_mode = evaluation_mode\n        self.counts = counts\n        self.counts_off = counts_off\n        self.exposure = exposure\n\n        if np.isscalar(acceptance):\n            acceptance = Map.from_geom(\n                self._geom, data=np.ones(self.data_shape) * acceptance\n            )\n\n        if np.isscalar(acceptance_off):\n            acceptance_off = Map.from_geom(\n                self._geom, data=np.ones(self.data_shape) * acceptance_off\n            )\n\n        self.acceptance = acceptance\n        self.acceptance_off = acceptance_off\n        self._background_model = None\n        self.mask_fit = mask_fit\n        self.psf = psf\n        self.edisp = edisp\n        self._name = make_name(name)\n        self.models = models\n        self.mask_safe = mask_safe\n        self.gti = gti\n        self.meta_table = meta_table\n\n    def __str__(self):\n        str_ = super().__str__()\n\n        counts_off = np.nan\n        if self.counts_off is not None:\n            counts_off = np.sum(self.counts_off.data)\n        str_ += \"\\t{:32}: {:.0f} \\n\".format(\"Total counts_off\", counts_off)\n\n        acceptance = np.nan\n        if self.acceptance is not None:\n            acceptance = np.sum(self.acceptance.data)\n        str_ += \"\\t{:32}: {:.0f} \\n\".format(\"Acceptance\", acceptance)\n\n        acceptance_off = np.nan\n        if self.acceptance_off is not None:\n            acceptance_off = np.sum(self.acceptance_off.data)\n        str_ += \"\\t{:32}: {:.0f} \\n\".format(\"Acceptance off\", acceptance_off)\n\n        return str_.expandtabs(tabsize=4)\n\n    @property\n    def alpha(self):\n        \"\"\"Exposure ratio between signal and background regions\"\"\"\n        alpha = self.acceptance / self.acceptance_off\n        alpha.data = np.nan_to_num(alpha.data)\n        return alpha\n\n    @property\n    def background(self):\n        \"\"\"Predicted background in the on region.\n\n        Notice that this definition is valid under the assumption of cash statistic.\n        \"\"\"\n        return self.alpha * self.counts_off\n\n    @property\n    def excess(self):\n        \"\"\"Excess (counts - alpha * counts_off)\"\"\"\n        return self.counts.data - self.background.data\n\n    def stat_array(self):\n        \"\"\"Likelihood per bin given the current model parameters\"\"\"\n        mu_sig = self.npred().data\n        on_stat_ = wstat(\n            n_on=self.counts.data,\n            n_off=self.counts_off.data,\n            alpha=list(self.alpha.data),\n            mu_sig=mu_sig,\n        )\n        return np.nan_to_num(on_stat_)\n\n    @classmethod\n    def from_geoms(\n        cls,\n        geom,\n        geom_exposure,\n        geom_psf,\n        geom_edisp,\n        reference_time=\"2000-01-01\",\n        name=None,\n        **kwargs,\n    ):\n        \"\"\"\n        Create a MapDatasetOnOff object with zero filled maps according to the specified geometries\n\n        Parameters\n        ----------\n        geom : `gammapy.maps.WcsGeom`\n            geometry for the counts, counts_off, acceptance and acceptance_off maps\n        geom_exposure : `gammapy.maps.WcsGeom`\n            geometry for the exposure map\n        geom_psf : `gammapy.maps.WcsGeom`\n            geometry for the psf map\n        geom_edisp : `gammapy.maps.WcsGeom`\n            geometry for the energy dispersion kernel map.\n            If geom_edisp has a migra axis, this wil create an EDispMap instead.\n        reference_time : `~astropy.time.Time`\n            the reference time to use in GTI definition\n        name : str\n            Name of the returned dataset.\n\n        Returns\n        -------\n        empty_maps : `MapDatasetOnOff`\n            A MapDatasetOnOff containing zero filled maps\n        \"\"\"\n        kwargs = kwargs.copy()\n        kwargs[\"name\"] = name\n\n        for key in [\"counts\", \"counts_off\", \"acceptance\", \"acceptance_off\"]:\n            kwargs[key] = Map.from_geom(geom, unit=\"\")\n\n        kwargs[\"exposure\"] = Map.from_geom(geom_exposure, unit=\"m2 s\")\n        if geom_edisp.axes[0].name.lower() == \"energy\":\n            kwargs[\"edisp\"] = EDispKernelMap.from_geom(geom_edisp)\n        else:\n            kwargs[\"edisp\"] = EDispMap.from_geom(geom_edisp)\n\n        kwargs[\"psf\"] = PSFMap.from_geom(geom_psf)\n        kwargs[\"gti\"] = GTI.create([] * u.s, [] * u.s, reference_time=reference_time)\n        kwargs[\"mask_safe\"] = Map.from_geom(geom, dtype=bool)\n\n        return cls(**kwargs)\n\n    @classmethod\n    def from_map_dataset(\n        cls, dataset, acceptance, acceptance_off, counts_off=None, name=None\n    ):\n        \"\"\"Create spectrum dataseton off from another dataset.\n\n        Parameters\n        ----------\n        dataset : `MapDataset`\n            Spectrum dataset defining counts, edisp, aeff, livetime etc.\n        acceptance : `Map`\n            Relative background efficiency in the on region.\n        acceptance_off : `Map`\n            Relative background efficiency in the off region.\n        counts_off : `Map`\n            Off counts map . If the dataset provides a background model,\n            and no off counts are defined. The off counts are deferred from\n            counts_off / alpha.\n        name : str\n            Name of the returned dataset.\n\n        Returns\n        -------\n        dataset : `MapDatasetOnOff`\n            Map dataset on off.\n\n        \"\"\"\n        kwargs = {\"name\": name}\n\n        if counts_off is None and dataset.background_model is not None:\n            alpha = acceptance / acceptance_off\n            kwargs[\"counts_off\"] = dataset.background_model.evaluate() / alpha\n\n        return cls(\n            counts=dataset.counts,\n            exposure=dataset.exposure,\n            counts_off=counts_off,\n            edisp=dataset.edisp,\n            gti=dataset.gti,\n            mask_safe=dataset.mask_safe,\n            mask_fit=dataset.mask_fit,\n            acceptance=acceptance,\n            acceptance_off=acceptance_off,\n            name=dataset.name,\n            evaluation_mode=dataset.evaluation_mode,\n        )\n\n    @property\n    def _is_stackable(self):\n        \"\"\"Check if the Dataset contains enough information to be stacked\"\"\"\n        if (\n            self.acceptance_off is None\n            or self.acceptance is None\n            or self.counts_off is None\n        ):\n            return False\n        else:\n            return True\n\n    def stack(self, other):\n        r\"\"\"Stack another dataset in place.\n\n        The ``acceptance`` of the stacked dataset is normalized to 1,\n        and the stacked ``acceptance_off`` is scaled so that:\n\n        .. math::\n            \\alpha_\\text{stacked} =\n            \\frac{1}{a_\\text{off}} =\n            \\frac{\\alpha_1\\text{OFF}_1 + \\alpha_2\\text{OFF}_2}{\\text{OFF}_1 + OFF_2}\n\n        Parameters\n        ----------\n        other : `MapDatasetOnOff`\n            Other dataset\n        \"\"\"\n        if not isinstance(other, MapDatasetOnOff):\n            raise TypeError(\"Incompatible types for MapDatasetOnOff stacking\")\n\n        if not self._is_stackable or not other._is_stackable:\n            raise ValueError(\"Cannot stack incomplete MapDatsetOnOff.\")\n\n        # Factor containing: self.alpha * self.counts_off + other.alpha * other.counts_off\n        tmp_factor = (self.alpha * self.counts_off).copy()\n        tmp_factor.data[~self.mask_safe.data] = 0\n        tmp_factor.stack(other.alpha * other.counts_off, weights=other.mask_safe)\n\n        # Stack the off counts (in place)\n        self.counts_off.data[~self.mask_safe.data] = 0\n        self.counts_off.stack(other.counts_off, weights=other.mask_safe)\n\n        self.acceptance_off = self.counts_off / tmp_factor\n        self.acceptance.data = np.ones(self.data_shape)\n\n        super().stack(other)\n\n    def stat_sum(self):\n        \"\"\"Total likelihood given the current model parameters.\"\"\"\n        return Dataset.stat_sum(self)\n\n    def fake(self, background_model, random_state=\"random-seed\"):\n        \"\"\"Simulate fake counts (on and off) for the current model and reduced IRFs.\n\n        This method overwrites the counts defined on the dataset object.\n\n        Parameters\n        ----------\n        random_state : {int, 'random-seed', 'global-rng', `~numpy.random.RandomState`}\n                Defines random number generator initialisation.\n                Passed to `~gammapy.utils.random.get_random_state`.\n        \"\"\"\n        random_state = get_random_state(random_state)\n        npred = self.npred()\n        npred.data = random_state.poisson(npred.data)\n\n        npred_bkg = background_model.copy()\n        npred_bkg.data = random_state.poisson(npred_bkg.data)\n\n        self.counts = npred + npred_bkg\n\n        npred_off = background_model / self.alpha\n        npred_off.data = random_state.poisson(npred_off.data)\n        self.counts_off = npred_off\n\n    def to_hdulist(self):\n        \"\"\"Convert map dataset to list of HDUs.\n\n        Returns\n        -------\n        hdulist : `~astropy.io.fits.HDUList`\n            Map dataset list of HDUs.\n        \"\"\"\n        hdulist = super().to_hdulist()\n        exclude_primary = slice(1, None)\n\n        if self.counts_off is not None:\n            hdulist += self.counts_off.to_hdulist(hdu=\"counts_off\")[exclude_primary]\n\n        if self.acceptance is not None:\n            hdulist += self.acceptance.to_hdulist(hdu=\"acceptance\")[exclude_primary]\n\n        if self.acceptance_off is not None:\n            hdulist += self.acceptance_off.to_hdulist(hdu=\"acceptance_off\")[\n                exclude_primary\n            ]\n\n        return hdulist\n\n    @classmethod\n    def from_hdulist(cls, hdulist, name=None):\n        \"\"\"Create map dataset from list of HDUs.\n\n        Parameters\n        ----------\n        hdulist : `~astropy.io.fits.HDUList`\n            List of HDUs.\n        name : str\n            Name of the new dataset.\n\n        Returns\n        -------\n        dataset : `MapDataset`\n            Map dataset.\n        \"\"\"\n        kwargs = {}\n        kwargs[\"name\"] = name\n        if \"COUNTS\" in hdulist:\n            kwargs[\"counts\"] = Map.from_hdulist(hdulist, hdu=\"counts\")\n\n        if \"COUNTS_OFF\" in hdulist:\n            kwargs[\"counts_off\"] = Map.from_hdulist(hdulist, hdu=\"counts_off\")\n\n        if \"ACCEPTANCE\" in hdulist:\n            kwargs[\"acceptance\"] = Map.from_hdulist(hdulist, hdu=\"acceptance\")\n\n        if \"ACCEPTANCE_OFF\" in hdulist:\n            kwargs[\"acceptance_off\"] = Map.from_hdulist(hdulist, hdu=\"acceptance_off\")\n\n        if \"EXPOSURE\" in hdulist:\n            kwargs[\"exposure\"] = Map.from_hdulist(hdulist, hdu=\"exposure\")\n\n        if \"EDISP_MATRIX\" in hdulist:\n            kwargs[\"edisp\"] = EDispKernel.from_hdulist(\n                hdulist, hdu1=\"EDISP_MATRIX\", hdu2=\"EDISP_MATRIX_EBOUNDS\"\n            )\n\n        if \"PSF_KERNEL\" in hdulist:\n            psf_map = Map.from_hdulist(hdulist, hdu=\"psf_kernel\")\n            kwargs[\"psf\"] = PSFKernel(psf_map)\n\n        if \"MASK_SAFE\" in hdulist:\n            mask_safe = Map.from_hdulist(hdulist, hdu=\"mask_safe\")\n            mask_safe.data = mask_safe.data.astype(bool)\n            kwargs[\"mask_safe\"] = mask_safe\n\n        if \"MASK_FIT\" in hdulist:\n            mask_fit = Map.from_hdulist(hdulist, hdu=\"mask_fit\")\n            mask_fit.data = mask_fit.data.astype(bool)\n            kwargs[\"mask_fit\"] = mask_fit\n\n        if \"GTI\" in hdulist:\n            gti = GTI(Table.read(hdulist, hdu=\"GTI\"))\n            kwargs[\"gti\"] = gti\n        return cls(**kwargs)\n\n    def info_dict(self, region=None):\n        \"\"\"Basic info dict with summary statistics\n\n        If a region is passed, then a spectrum dataset is\n        extracted, and the corresponding info returned.\n\n        Parameters\n        ----------\n        region : `~regions.SkyRegion`, optional\n            the input ON region on which to extract the spectrum\n\n        Returns\n        -------\n        info_dict : dict\n            Dictionary with summary info.\n        \"\"\"\n        info = super().info_dict(region)\n        info[\"name\"] = self.name\n        if self.gti is None:\n            if self.counts_off is not None:\n                info[\"counts_off\"] = np.sum(self.counts_off.data)\n\n            if self.acceptance is not None:\n                info[\"acceptance\"] = np.sum(self.acceptance.data)\n\n            if self.acceptance_off is not None:\n                info[\"acceptance_off\"] = np.sum(self.acceptance_off.data)\n\n            info[\"excess\"] = np.sum(self.excess.data)\n        return info\n\n    def to_spectrum_dataset(self, on_region, containment_correction=False, name=None):\n        \"\"\"Return a ~gammapy.spectrum.SpectrumDatasetOnOff from on_region.\n\n        Counts and OFF counts are summed in the on_region.\n\n        Acceptance is the average of all acceptances while acceptance OFF\n        is taken such that number of excess is preserved in the on_region.\n\n        Effective area is taken from the average exposure divided by the livetime.\n        Here we assume it is the sum of the GTIs.\n\n        The energy dispersion kernel is obtained at the on_region center.\n        Only regions with centers are supported.\n\n        The model is not exported to the ~gammapy.spectrum.SpectrumDataset.\n        It must be set after the dataset extraction.\n\n        Parameters\n        ----------\n        on_region : `~regions.SkyRegion`\n            the input ON region on which to extract the spectrum\n        containment_correction : bool\n            Apply containment correction for point sources and circular on regions\n        name : str\n            Name of the new dataset.\n\n        Returns\n        -------\n        dataset : `~gammapy.spectrum.SpectrumDatasetOnOff`\n            the resulting reduced dataset\n        \"\"\"\n        from .spectrum import SpectrumDatasetOnOff\n\n        dataset = super().to_spectrum_dataset(on_region, containment_correction, name)\n\n        kwargs = {}\n        if self.counts_off is not None:\n            kwargs[\"counts_off\"] = self.counts_off.get_spectrum(on_region, np.sum)\n\n        if self.acceptance is not None:\n            kwargs[\"acceptance\"] = self.acceptance.get_spectrum(on_region, np.mean)\n            background = self.background.get_spectrum(on_region, np.sum)\n            kwargs[\"acceptance_off\"] = (\n                kwargs[\"acceptance\"] * kwargs[\"counts_off\"] / background\n            )\n\n        return SpectrumDatasetOnOff.from_spectrum_dataset(dataset=dataset, **kwargs)\n\n    def cutout(self, position, width, mode=\"trim\", name=None):\n        \"\"\"Cutout map dataset.\n\n        Parameters\n        ----------\n        position : `~astropy.coordinates.SkyCoord`\n            Center position of the cutout region.\n        width : tuple of `~astropy.coordinates.Angle`\n            Angular sizes of the region in (lon, lat) in that specific order.\n            If only one value is passed, a square region is extracted.\n        mode : {'trim', 'partial', 'strict'}\n            Mode option for Cutout2D, for details see `~astropy.nddata.utils.Cutout2D`.\n        name : str\n            Name of the new dataset.\n\n        Returns\n        -------\n        cutout : `MapDatasetOnOff`\n            Cutout map dataset.\n        \"\"\"\n        cutout_kwargs = {\n            \"position\": position,\n            \"width\": width,\n            \"mode\": mode,\n            \"name\": name,\n        }\n\n        cutout_dataset = super().cutout(**cutout_kwargs)\n\n        del cutout_kwargs[\"name\"]\n\n        if self.counts_off is not None:\n            cutout_dataset.counts_off = self.counts_off.cutout(**cutout_kwargs)\n\n        if self.acceptance is not None:\n            cutout_dataset.acceptance = self.acceptance.cutout(**cutout_kwargs)\n\n        if self.acceptance_off is not None:\n            cutout_dataset.acceptance_off = self.acceptance_off.cutout(**cutout_kwargs)\n\n        return cutout_dataset\n\n    def to_image(self, spectrum=None, name=None):\n        \"\"\"Create images by summing over the energy axis.\n\n        Exposure is weighted with an assumed spectrum,\n        resulting in a weighted mean exposure image.\n\n        Currently the PSFMap and EdispMap are dropped from the\n        resulting image dataset.\n\n        Parameters\n        ----------\n        spectrum : `~gammapy.modeling.models.SpectralModel`\n            Spectral model to compute the weights.\n            Default is power-law with spectral index of 2.\n        name : str\n            Name of the new dataset.\n\n        Returns\n        -------\n        dataset : `MapDatasetOnOff`\n            Map dataset containing images.\n        \"\"\"\n        kwargs = {\"name\": name}\n        dataset = super().to_image(spectrum, name)\n\n        if self.mask_safe is not None:\n            mask_safe = self.mask_safe\n        else:\n            mask_safe = 1\n\n        if self.counts_off is not None:\n            counts_off = self.counts_off * mask_safe\n            kwargs[\"counts_off\"] = counts_off.sum_over_axes(keepdims=True)\n\n        if self.acceptance is not None:\n            acceptance = self.acceptance * mask_safe\n            kwargs[\"acceptance\"] = acceptance.sum_over_axes(keepdims=True)\n\n            background = self.background * mask_safe\n            background = background.sum_over_axes(keepdims=True)\n            kwargs[\"acceptance_off\"] = (\n                kwargs[\"acceptance\"] * kwargs[\"counts_off\"] / background\n            )\n\n        return self.from_map_dataset(dataset, **kwargs)\n\n\nclass MapEvaluator:\n    \"\"\"Sky model evaluation on maps.\n\n    This evaluates a sky model on a 3D map and convolves with the IRFs,\n    and returns a map of the predicted counts.\n    Note that background counts are not added.\n\n    For now, we only make it work for 3D WCS maps with an energy axis.\n    No HPX, no other axes, those can be added later here or via new\n    separate model evaluator classes.\n\n    Parameters\n    ----------\n    model : `~gammapy.modeling.models.SkyModel`\n        Sky model\n    exposure : `~gammapy.maps.Map`\n        Exposure map\n    psf : `~gammapy.cube.PSFKernel`\n        PSF kernel\n    edisp : `~gammapy.irf.EDispKernel`\n        Energy dispersion\n    gti : `~gammapy.data.GTI`\n        GTI of the observation or union of GTI if it is a stacked observation\n    evaluation_mode : {\"local\", \"global\"}\n        Model evaluation mode.\n    \"\"\"\n\n    def __init__(\n        self,\n        model=None,\n        exposure=None,\n        psf=None,\n        edisp=None,\n        gti=None,\n        evaluation_mode=\"local\",\n    ):\n\n        self.model = model\n        self.exposure = exposure\n        self.psf = psf\n        self.edisp = edisp\n        self.gti = gti\n        self.contributes = True\n        self._npred_cached = None\n        self._pars_cached = None\n\n        if evaluation_mode not in {\"local\", \"global\"}:\n            raise ValueError(f\"Invalid evaluation_mode: {evaluation_mode!r}\")\n        self.evaluation_mode = evaluation_mode\n\n        # TODO: this is preliminary solution until we have further unified the model handling\n        if isinstance(self.model, BackgroundModel):\n            self.evaluation_mode = \"global\"\n\n    @property\n    def geom(self):\n        \"\"\"True energy map geometry (`~gammapy.maps.Geom`)\"\"\"\n        return self.exposure.geom\n\n    @property\n    def needs_update(self):\n        \"\"\"Check whether the model component has drifted away from its support.\"\"\"\n        # TODO: simplify and clean up\n        if isinstance(self.model, BackgroundModel):\n            return False\n        elif self.exposure is None:\n            return True\n        elif self.evaluation_mode == \"global\" or self.model.evaluation_radius is None:\n            return False\n        else:\n            position = self.model.position\n            separation = self._init_position.separation(position)\n            update = separation > (self.model.evaluation_radius + CUTOUT_MARGIN)\n        return update\n\n    def update(self, exposure, psf, edisp, geom):\n        \"\"\"Update MapEvaluator, based on the current position of the model component.\n\n        Parameters\n        ----------\n        exposure : `~gammapy.maps.Map`\n            Exposure map.\n        psf : `gammapy.cube.PSFMap`\n            PSF map.\n        edisp : `gammapy.cube.EDispMap`\n            Edisp map.\n        geom : `WcsGeom`\n            Counts geom\n        \"\"\"\n        # TODO: simplify and clean up\n        log.debug(\"Updating model evaluator\")\n        # cache current position of the model component\n\n        if isinstance(edisp, EDispKernelMap):\n            self.edisp = edisp.get_edisp_kernel(self.model.position)\n        elif isinstance(edisp, EDispMap):\n            e_reco = geom.get_axis_by_name(\"energy\").edges\n            self.edisp = edisp.get_edisp_kernel(self.model.position, e_reco=e_reco)\n        else:\n            self.edisp = edisp\n\n        if isinstance(psf, PSFMap):\n            self.psf = psf.get_psf_kernel(self.model.position, geom=exposure.geom)\n        else:\n            self.psf = psf\n\n        if self.evaluation_mode == \"local\" and self.model.evaluation_radius is not None:\n            self._init_position = self.model.position\n            if self.psf is not None:\n                psf_width = np.max(self.psf.psf_kernel_map.geom.width)\n            else:\n                psf_width = 0 * u.deg\n\n            width = psf_width + 2 * (self.model.evaluation_radius + CUTOUT_MARGIN)\n            try:\n                self.exposure = exposure.cutout(\n                    position=self.model.position, width=width\n                )\n                self.contributes = True\n            except (NoOverlapError, ValueError):\n                self.contributes = False\n        else:\n            self.exposure = exposure\n\n        self._pars_cached = None\n\n    def compute_dnde(self):\n        \"\"\"Compute model differential flux at map pixel centers.\n\n        Returns\n        -------\n        model_map : `~gammapy.maps.Map`\n            Sky cube with data filled with evaluated model values.\n            Units: ``cm-2 s-1 TeV-1 deg-2``\n        \"\"\"\n        return self.model.evaluate_geom(self.geom, self.gti)\n\n    def compute_flux(self):\n        \"\"\"Compute model integral flux over map pixel volumes.\n\n        For now, we simply multiply dnde with bin volume.\n        \"\"\"\n        return self.model.integrate_geom(self.geom, self.gti)\n\n    def apply_exposure(self, flux):\n        \"\"\"Compute npred cube\n\n        For now just divide flux cube by exposure\n        \"\"\"\n        npred = (flux.quantity * self.exposure.quantity).to_value(\"\")\n        return Map.from_geom(self.geom, data=npred, unit=\"\")\n\n    def apply_psf(self, npred):\n        \"\"\"Convolve npred cube with PSF\"\"\"\n        tmp = npred.convolve(self.psf)\n        tmp.data[tmp.data < 0.0] = 0\n        return tmp\n\n    def apply_edisp(self, npred):\n        \"\"\"Convolve map data with energy dispersion.\n\n        Parameters\n        ----------\n        npred : `~gammapy.maps.Map`\n            Predicted counts in true energy bins\n\n        Returns\n        -------\n        npred_reco : `~gammapy.maps.Map`\n            Predicted counts in reco energy bins\n        \"\"\"\n        return npred.apply_edisp(self.edisp)\n\n    def compute_npred(self):\n        \"\"\"\n        Evaluate model predicted counts.\n\n        Returns\n        -------\n        npred : `~gammapy.maps.Map`\n            Predicted counts on the map (in reco energy bins)\n        \"\"\"\n\n        pars = list(self.model.parameters.values)\n        npred = self._npred_cached\n        if self._pars_cached != pars:\n            self._pars_cached = pars\n            if isinstance(self.model, BackgroundModel):\n                npred = self.model.evaluate()\n            else:\n                flux = self.compute_flux()\n\n                if self.model.apply_irf[\"exposure\"]:\n                    npred = self.apply_exposure(flux)\n\n                if self.psf and self.model.apply_irf[\"psf\"]:\n                    npred = self.apply_psf(npred)\n\n                if self.model.apply_irf[\"edisp\"]:\n                    npred = self.apply_edisp(npred)\n\n            self._npred_cached = npred\n        return npred\n", "meta": {"hexsha": "66f4d5dbdc5ed61289dba847e75fa367b4ff1d42", "size": 64917, "ext": "py", "lang": "Python", "max_stars_repo_path": "gammapy/datasets/map.py", "max_stars_repo_name": "vikasj78/gammapy", "max_stars_repo_head_hexsha": "46deb872bbcbf36748df71e659dc3fa592f6dc27", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gammapy/datasets/map.py", "max_issues_repo_name": "vikasj78/gammapy", "max_issues_repo_head_hexsha": "46deb872bbcbf36748df71e659dc3fa592f6dc27", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gammapy/datasets/map.py", "max_forks_repo_name": "vikasj78/gammapy", "max_forks_repo_head_hexsha": "46deb872bbcbf36748df71e659dc3fa592f6dc27", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8641245972, "max_line_length": 99, "alphanum_fraction": 0.5890136636, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 14518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.32082128783705344, "lm_q1q2_score": 0.16291685627698937}}
{"text": "#! /usr/bin/python\n# differentail corrrection for\n#\n# mlpd /home/astro115/carmenes/data/svn/zero/CARM_VIS/J16167+672S.avc.dat  /home/astro115/carmenes/data/svn/other-rvs/J16167+672S/J16167+672S_hires.dat --fbeg 0.00022\n\n\n# -*- coding: utf-8 -*-\n# Copyright (c) 2012 Sebastian Schrter, Stefan Czesla, and Mathias Zechmeister\n\n# The MIT License (MIT)\n\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n# sell copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n# Note : The software is also available as part of the PyAstronomy package.\n#        See: http://www.hs.uni-hamburg.de/DE/Ins/Per/Czesla/index.html\n\nfrom __future__ import print_function, division\nimport numpy as np\nfrom numpy import sum, pi, cos, sin, arctan2, exp, log, sqrt,\\\n                  dot, argmax, arange\n#from pause import *\n#from gplot import *\nfrom scipy import optimize as op\nimport time\ntry:\n   from pathos.pools import ProcessPool as Pool\nexcept:\n   pass\n\n\n# for python3: emulate the nice python2 behaviour of map and zip\nxmap = map\nmap = lambda *x: list(xmap(*x))\nxzip = zip\nzip = lambda *x: list(xzip(*x))\n\n__version__ = '2021-08-18'\n__author__ = 'Mathias Zechmeister'\n\ndef mod_abc(x, a):\n   ''' sine model with multiple data set and offsets\n   x - list of tuples with cosx and sinx terms\n   '''\n   y = [a[0]*cosx + a[1]*sinx + a[2+i] for i,(cosx,sinx) in enumerate(x)]\n   return y\n\ndef mod_c(x, a):\n   ''' sine model with multiple data set and offsets\n   x - list of tuples with cosx and sinx terms\n   '''\n   y = [0*cosx + a[i] for i,cosx in enumerate(x)]\n   return y\n\nclass Gls:\n    \"\"\"\n    Compute the Generalized Lomb-Scargle (GLS) periodogram.\n\n    The *Gls* class computes the error-weighted Lomb-Scargle periodogram as\n    developed by [ZK09]_ using various possible normalizations.\n\n    The constructor of *Gls* takes a *TimeSeries* instance (i.e., a light curve)\n    as first argument. The constructor allows to pass keywords to adjust the\n    `freq` array, which will be used to calculate the periodogram.\n\n    The main result of the calculation, i.e., the power, are stored in the\n    class property `power`.\n\n    Parameters\n    ----------\n    lc : TimeSeries object or tuple or list\n        The light curve data either in the form of a TimeSeries object (or any\n        object providing the attributes time, flux, and error) or a tuple or list\n        providing time as first element, flux as second element, and optionally,\n        the error as third element.\n    fbeg, fend : float, optional\n        The beginning and end frequencies for the periodogram\n        (inverse units of time axis).\n    Pbeg, Pend : float, optional\n        The beginning and end periods for the periodogram\n        (same units as for time axis).\n    ofac : int\n        Oversampling factor of frequency grid (default=10).\n    hifac : float\n        Maximum frequency `freq` = `hifac` * (average Nyquist frequency)\n        (default=1).\n    freq : array, optional\n        Contains the frequencies at which to calculate the periodogram.\n        If given, fast and verbose option are not available.\n        If not given, a frequency array will be automatically generated.\n    norm : string, optional\n        The normalization; either of \"lnL\", \"Scargle\", \"HorneBaliunas\", \"Cumming\", \"wrms\", \"chisq\".\n        The default is unity (\"lnL\").\n    ls : boolean, optional\n        If True, the conventional Lomb-Scargle periodogram will be computed\n        (default is False).\n    fast : boolean, optional\n        If True, recursive relations for trigonometric functions will be used\n        leading to faster evaluation (default is False).\n    verbose : boolean, optional\n        Set True to obtain some statistical output (default is False).\n\n    Attributes\n    ----------\n    power : array\n        The normalized power of the GLS.\n    freq : array\n        The frequency array.\n    ofac : int\n        The oversampling factor of frequency grid.\n    hifac : float\n        The maximum frequency.\n    t : array\n        The abscissa data values.\n    y : array\n        The ordinate data values.\n    e_y : array\n        The errors of the data values.\n    norm : string, {'lnL', 'Scargle', 'HorneBaliunas', 'Cumming', 'wrms', 'chisq'}\n        The used normalization.\n\n    Examples\n    --------\n    Create 1000 unevenly sampled data points with frequency=0.1,\n    measurement error and Gaussian noise\n    >>> time = np.random.uniform(54000., 56000., 1000)\n    >>> flux = 0.15 * np.sin(2. * np.pi * time / 10.)\n\n    Add some noise\n    >>> error = 0.3 * np.ones(time.size)\n    >>> flux += np.random.normal(0, error+0.2)\n\n    Compute the full error-weighted Lomb-Periodogram\n    in 'lnL' normalization and calculate the significance\n    of the maximum peak.\n    >>> gls = Gls((time, flux, error), verbose=True)\n\n    >>> maxPower = gls.pmax\n    >>> print(\"GLS maximum power: \", maxPower)\n    >>> print(\"GLS statistics of maximum power peak: \", gls.stats(maxPower))\n    >>> gls.plot(block=True)\n\n    \"\"\"\n    # Available normalizations\n    norms = ['dlnL', 'lnL', 'Scargle', 'HorneBaliunas', 'Cumming', 'wrms', 'chisq']\n\n    def __init__(self, lc, fbeg=None, fend=None, Pbeg=None, Pend=None, ofac=10, hifac=1, freq=None, norm=\"dlnL\", ls=False, fast=False, ncpus=None, verbose=False, **kwargs):\n\n        self.freq = freq\n        self.fbeg = fbeg\n        self.fend = fend\n        self.Pbeg = Pbeg\n        self.Pend = Pend\n        self.ofac = ofac\n        self.hifac = hifac\n        self.ls = ls\n        self.norm = norm\n        self.fast = fast\n        self.ncpus = ncpus\n        self.label = {'title': 'Maximum Likelihood Periodogram',\n                      'xlabel': 'Frequency'}\n        if \"stats\" in kwargs:\n          print(\"Warning: 'stats' option is outdated. Please use 'verbose' instead.\")\n          verbose = kwargs[\"stats\"]\n\n        self._normcheck(norm)\n\n        self._assignTimeSeries(lc)\n        self._buildFreq()\n        self._calcPeriodogram()\n        self.pnorm(norm)\n        self._peakPeriodogram()\n\n        # Output statistics\n        if verbose:\n            self.info()\n\n    def _assignTimeSeries(self, lcs):\n      \"\"\"\n      A container class that holds the observed light curve.\n\n      Parameters\n      ----------\n      time : array\n          The time array.\n      flux : array\n          The observed flux/data.\n      error : array, optional\n          The error of the data values.\n\n      \"\"\"\n      self.t = []\n      self.y = []\n      self.e_y = []\n      self.N = 0\n      self.Nj = len(lcs)\n      for lc in lcs:\n         if isinstance(lc, (tuple, list)):\n             # t, y[, e_y] were given as list or tuple.\n             if len(lc) in (2, 3):\n                 t = np.ravel(lc[0])\n                 y = np.ravel(lc[1])\n                 e_y = None\n                 if len(lc) == 3 and lc[2] is not None:\n                     # Error has been specified.\n                     e_y = np.ravel(lc[2])\n             else:\n                 raise(ValueError(\"lc is a list or tuple with \" + str(len(lc)) + \" elements. Needs to have 2 or 3 elements.\" + \\\n                                    \" solution=Use 2 or 3 elements (t, y[, e_y]) or an instance of TimeSeries\"))\n         else:\n             # Assume lc is an instance of TimeSeries.\n             t, y, e_y = lc.time, lc.flux, lc.error\n         self.t += [t]\n         self.y += [y]\n         self.e_y += [e_y]\n\n         N = len(y)\n         self.N += N\n\n         # Re-check array length compatibility\n         if (len(t) != N) or ((e_y is not None) and (len(e_y) != N)):\n             raise(ValueError(\"Incompatible dimensions of input data arrays (time and flux [and error]). Current shapes are: \" + \\\n                              ', '.join(str(np.shape(x)) for x in (t, y, e_y))))\n\n      self.data = zip(self.t, self.y, self.e_y)\n      self.tmin = min(map(min,self.t))\n      self.th = [t - self.tmin for t in self.t]\n      self.tbase = max(map(max,self.th))\n\n\n    def _buildFreq(self):\n        \"\"\"\n        Build frequency array (`freq` attribute).\n\n        Attributes\n        ----------\n        fnyq : float\n            Half of the average sampling frequency of the time series.\n\n        \"\"\"\n        self.fstep = 1 / self.tbase / self.ofac   # frequency sampling depends on the time span, default for start frequency\n        self.fnyq = 0.5 / self.tbase * self.N     # Nyquist frequency\n        self.f = self.freq\n\n        if self.freq is None:\n            # Build frequency array if not present.\n            if self.fbeg is None:\n                self.fbeg = self.fstep if self.Pend is None else 1 / self.Pend\n            if self.fend is None:\n                self.fend = self.fnyq * self.hifac if self.Pbeg is None else 1 / self.Pbeg\n\n            if self.fend <= self.fbeg:\n                raise(ValueError(\"fend is smaller than (or equal to) fbeg but it must be larger.\" + \\\n                               \"Choose fbeg and fend so that fend > fbeg.\"))\n\n            self.freq = arange(self.fbeg, self.fend, self.fstep)\n        elif self.fast:\n            raise(ValueError(\"freq and fast cannot be used together.\"))\n\n        self.nf = len(self.freq)\n\n        # An ad-hoc estimate of the number of independent frequencies (Eq. (24) in ZK_09).\n        self.M = (self.fend-self.fbeg) * self.tbase\n\n    def lnL(self, theta, X, Y, e_Y, func):\n       # the log-likelihood\n       global L, chisqr, wtrms # a blob\n       L = []   # log-likelihood for each instrument\n       Ymod = func(X, theta)\n       chisqr = []\n       wtrms = []   # weighted rms for each instrument\n       N = len(X)\n       for y,e_y,ymod,lnf in zip(Y,e_Y,Ymod,theta[-N:]):\n          # loop over data sets\n          sigma2 = e_y**2 + lnf**2\n          #weight = 1/sigma2\n          chisqr += [np.sum((y-ymod)**2/sigma2)]\n          L += [-0.5 * np.sum((y-ymod)**2/sigma2 + np.log(2*pi*sigma2))]\n          wtrms += [np.sqrt(np.sum((y-ymod)**2/sigma2)/np.sum(1/sigma2))]\n       return sum(L)\n\n\n    def single_freq_fit(self, omega):\n\n      # Circular frequencies\n      X = [omega*th for th in self.th]\n      cosX = map(cos, X)\n      sinX = map(sin, X)\n      a = op.fmin_powell(self.nll, self.a, args=(zip(cosX,sinX), self.y, self.e_y, mod_abc), disp=False)\n\n      _a= a[0]\n      _b= a[1]\n      _off= a[2:2+self.Nj]\n      _lnMLj = L\n      _chisqr = chisqr\n      lnML = sum(L)\n      _wtrms = wtrms\n      W = [np.sum(1/(e_y**2+jit**2)) for e_y,jit in zip(self.e_y, a[-self.Nj:])]\n      _wrms = np.sqrt(np.sum(chisqr)/np.sum(W))   # a bit handwavy defined\n\n      return (a, _a, _b, _off, _lnMLj, _chisqr, lnML, _wtrms, _wrms)\n\n\n\n    def _calcPeriodogram(self):\n\n        self._a, self._b, self.p, self.lnML = np.zeros((4, self.nf))\n        self.par = []\n        self._off = np.zeros((self.nf, self.Nj))\n        self._lnMLj = np.zeros((self.nf, self.Nj))\n        self._chij = np.zeros((self.nf, self.Nj))\n        self._chisqr = np.zeros((self.nf, self.Nj))\n        self._chi = np.zeros(self.nf)\n        self._wrmsj = np.zeros((self.nf, self.Nj))\n        self._wrms = np.zeros(self.nf)\n        self._wtrms = np.zeros((self.nf, self.Nj))\n\n        global L, chisqr, wtrms\n        nll = lambda *args: -self.lnL(*args)\n        #a0 = [0.]*self.Nj + [3.]*self.Nj # start guess for first frequency\n        a0 = map(np.mean, self.y) + map(np.std, self.y)\n        #print(a0)\n        self.nll = nll\n        # The model with only offset c\n        a0 = op.fmin_powell(nll, a0, args=(self.th, self.y, self.e_y, mod_c), disp=False)\n        self.lnML0 = sum(L)\n        self.lnML0j = L\n        self.a0 = a0\n        W0 = [np.sum(e_y**2+jit**2) for e_y,jit in zip(self.e_y, a0[-self.Nj:])]\n        self.wrms0 = np.sqrt(np.sum(chisqr)/np.sum(W0)*self.N)   # hand-wavy definition\n\n        self.chisqr = chisqr\n        self.wtrms = wtrms\n        self.a = [np.median(a0[len(a0)//2:])]*2 + list(a0)   # start guess for first frequency\n\n        # frequency grid\n        omegas = [omega for omega in 2.*pi*self.freq]\n\n        start_time = time.time()\n        if self.ncpus is not None:\n           with Pool(ncpus=self.ncpus) as thread:\n              results = thread.map(self.single_freq_fit, omegas)\n\n        for k, omega in enumerate(omegas):\n           if self.ncpus is None:\n              res_k = self.single_freq_fit(omega)\n              print(end=\"%6.2f %%\\r\" % (k/(self.nf-1)*100))    # progress indicator\n           else:\n              res_k = results[k]\n\n           self.par.append(res_k[0])\n           self._a[k] = res_k[1]\n           self._b[k] = res_k[2]\n           self._off[k] = res_k[3]\n           self._lnMLj[k] = res_k[4]\n           self._chisqr[k] = res_k[5]\n           self.lnML[k] = res_k[6]\n           self._wtrms[k] = res_k[7]\n           self._wrms[k] = res_k[8]\n\n        self.p = self.lnML\n\n        print(\"--- %s CPUs done in %s seconds --- \" % (self.ncpus, time.time() - start_time))     \n\n\n    def _normcheck(self, norm):\n        \"\"\"\n        Check normalization\n\n        Parameters\n        ----------\n        norm : string\n            Normalization string\n\n        \"\"\"\n        if norm not in self.norms:\n            raise(ValueError(\"Unknown norm: \" + str(norm) + \". \" + \\\n                \"Use either of \" + ', '.join(self.norms)))\n\n    def pnorm(self, norm=\"dlnL\"):\n        \"\"\"\n        Assign or modify normalization (can be done afterwards).\n\n        Parameters\n        ----------\n        norm : string, optional\n            The normalization to be used (default is 'lnL').\n\n        Examples\n        --------\n        >>> gls.pnorm('wrms')\n\n        \"\"\"\n        self._normcheck(norm)\n        self.norm = norm\n        p = self.p\n        power = p   # default lnL\n        self.label[\"ylabel\"] = norm\n\n        if norm == \"Scargle\":\n            popvar = input('pyTiming::gls - Input a priori known population variance:')\n            power = p / float(popvar)\n        elif norm == \"HorneBaliunas\":\n            power = (self.N-1)/2. * p\n        elif norm == \"Cumming\":\n            power = (self.N-3)/2. * p / (1.-self.p.max())\n        elif norm == \"chisq\":\n            power = self._YY *self.wsum * (1.-p)\n            self.label[\"ylabel\"] = \"chisq\"\n        elif norm == \"wrms\":\n            power = sqrt(self._YY*(1.-p))\n            self.label[\"ylabel\"] = \"wrms\"\n        elif norm == \"dlnL\":\n            self.powerj = self._lnMLj - self.lnML0j\n            power = self.lnML - self.lnML0\n            self.label[\"ylabel\"] = \"$\\Delta$lnL\"\n        else:\n            self.powerj = self._lnMLj.T\n            power = self.lnML\n\n        self.power = power\n\n    def _peakPeriodogram(self):\n        \"\"\"\n        Analyze the highest periodogram peak.\n        \"\"\"\n        # Index with maximum power\n        k = argmax(self.p)\n        # Maximum power\n        self.pmax = pmax = self.p[k]\n        self.rms = rms = self._wrms[k]\n        # Statistics of highest peak\n        self.hpstat = p = {}\n\n        # Best parameters\n        p[\"fbest\"] = fbest = self.freq[k]\n        p[\"P\"] = 1/fbest\n        p[\"amp\"] = amp = sqrt(self._a[k]**2 + self._b[k]**2)\n        p[\"ph\"] = ph = arctan2(self._a[k], self._b[k]) / (2.*pi)\n        p[\"T0\"]  = self.tmin - ph/fbest\n        p[\"offset\"] = self._off[k]\n        #print(len(self.par),self.Nj)\n        p[\"jitter\"] = self.par[k][-self.Nj:]\n\n        # Error estimates\n        p[\"amp_err\"] = sqrt(2./self.N) * rms\n        p[\"ph_err\"] = ph_err = sqrt(2./self.N) * rms/amp/(2.*pi)\n        p[\"T0_err\"] = ph_err / fbest\n        p[\"offset_err\"] = sqrt(1./self.N) * rms\n\n        # Get the curvature in the power peak by fitting a parabola y=aa*x^2\n        if 1 < k < self.nf-2:\n            # Shift the parabola origin to power peak\n            xh = (self.freq[k-1:k+2] - self.freq[k])**2\n            yh = self.p[k-1:k+2] - pmax\n            # Calculate the curvature (final equation from least square)\n            aa = dot(yh, xh) / dot(xh, xh)\n            p[\"f_err\"] = e_f = sqrt(-2./self.N / aa * (1.-self.pmax))\n            p[\"Psin_err\"] = e_f / fbest**2\n        else:\n            self.hpstat[\"f_err\"] = np.nan\n            self.hpstat[\"Psin_err\"] = np.nan\n            print(\"WARNING: Highest peak is at the edge of the frequency range.\\nNo output of frequency error.\\nIncrease frequency range to sample the peak maximum.\")\n\n    def sinmod(self, t):\n        \"\"\"\n        Calcuate best-fit sine curve.\n\n        Parameters\n        ----------\n        t : array\n            Time array at which to calculate the sine.\n\n        Returns\n        -------\n        Sine curve : array\n            The best-fit sine curve (i.e., that for which the\n            power is maximal).\n        \"\"\"\n        try:\n            p = self.hpstat\n            if isinstance(t, (list, tuple)):\n               return [p[\"amp\"] * sin(2*np.pi*p[\"fbest\"]*(tj-p[\"T0\"])) + offj for tj,offj in zip(t,p[\"offset\"])]\n            else:\n               return p[\"amp\"] * sin(2*np.pi*p[\"fbest\"]*(t-p[\"T0\"]))\n        except Exception as e:\n            print(\"Failed to calcuate best-fit sine curve.\")\n            raise(e)\n\n    def info(self, stdout=True):\n        \"\"\"\n        Prints some basic statistical output screen.\n        \"\"\"\n        lines = (\"MLP - statistical output\",\n           \"-----------------------------------\",\n           \"Number of input points:     %6d\" % self.N,\n           \"Weighted rms of dataset:    %f\"  % self.wrms0,\n           \"Time base:                  %f\"  % self.tbase,\n           \"Number of frequency points: %6d\" % self.nf,\n           \"Weighted rms of residuals:  %f\" % self.rms,\n           \"\")\n\n        k = argmax(self.p)\n        Yfit = self.sinmod([t for t,y,e in self.data])\n        W = [1/(e_y**2+jit**2) for e_y,jit in zip(self.e_y, self.hpstat[\"jitter\"])]\n        wrmsj = [np.sqrt(np.sum(w*(yfit-y)**2)/np.sum(w)) for y,w,yfit in zip(self.y, W, Yfit)]\n\n        header = \"%s:   %10s %10s  %10s %10s\" % (\"j\", \"lnL0\", \"dlnL\", \"wrms\",\"jit\")\n        fmt = \"%d:   %10.3f %10.3f  %10.3f %10.3f\"\n        if self.e_y is not None:\n           header += \" %10s\" % \"internal error\"\n           fmt += \" %10.3f\"\n        lines += (header,)\n\n        col = list(self.lnML0j), list(self._lnMLj[k]-self.lnML0j)\n        col += wrmsj, self.hpstat[\"jitter\"]\n        if self.e_y is not None:\n           col += [np.mean(1./e_y**2)**-0.5 for e_y in self.e_y],\n\n        for j,line in enumerate(zip(*col)):\n           lines += fmt % ((j,)+line),\n\n        wrmsall = np.sqrt(np.sum([np.sum(w*(yfit-y)**2) for y,w,yfit in zip(self.y, W, Yfit)])/sum(map(sum,W)))\n        lines += \"-\"*60,\n        lines += \"all: %10.3f %10.3f  %10.3f\\n\" % (self.lnML0, self.lnML.max()-self.lnML0, wrmsall),\n\n        self.best = self.hpstat\n        lines += (\"Best sine frequency:  {fbest:f} +/- {f_err:f}\",\n             \"Best sine period:     {P:f} +/- {Psin_err:f}\",\n             \"Amplitude:            {amp:f} +/- {amp_err:f}\")\n             #\"Phase (ph):           %f +/- %f\" % (self.best[\"ph\"], self.best[\"ph_err\"]),\n             #\"Phase (T0):           %f +/- %f\" % (self.best[\"T0\"], self.best[\"T0_err\"]))\n        for j,off in enumerate(self.best[\"offset\"]):\n           lines += \"Offset %d:             %f +/- %f\" % (j, off, self.best[\"offset_err\"]),\n        #for j,jit in enumerate(self.best[\"jitter\"]:\n        #   print(\"Jitter %d:             %f +/- %f\" % (j, jit, self.best[\"offset_err\"]))\n        lines += \"-----------------------------------\",\n        text = \"\\n\".join(lines).format(**self.best)\n        if stdout:\n           print(text)\n        else:\n           return text\n\n    def plot(self, block=False, period=False):\n        \"\"\"\n        Create a plot.\n        \"\"\"\n        try:\n            import matplotlib\n            import matplotlib.pyplot as plt\n            from matplotlib.ticker import FormatStrFormatter\n        except ImportError:\n            raise(ImportError(\"Could not import matplotlib.pylab.\"))\n\n        fig = plt.figure()\n        fig.subplots_adjust(hspace=0.15, wspace=0.08, right=0.97, top=0.95)\n        ax = fig.add_subplot(3, 1, 1)\n        ax.set_title(\"Maximum likelihood periodogram\")\n        if period:\n           ax.set_xscale(\"log\")\n           ax.set_xlabel(\"Period\")\n        else:\n           ax.set_xlabel(\"Frequency\")\n        ax.set_ylabel(self.label[\"ylabel\"])\n        #pause()\n        for pj in self.powerj.T:\n           ax.plot(1/self.freq if period else self.freq, pj, '-')\n        ax.plot(1/self.freq if period else self.freq, self.power, 'k-')\n\n        fbest, T0 = self.hpstat[\"fbest\"], self.hpstat[\"T0\"]\n        # Data and model\n        datstyle = {'fmt':'.', 'capsize':0}\n        tt = arange(self.tmin, self.tmin+self.tbase, 0.01/fbest)\n        ymod = self.sinmod(tt)\n        yfit = self.sinmod([t for t,y,e in self.data])\n        ax1 = fig.add_subplot(3, 2, 3)\n        # ax1.set_xlabel(\"Time\")\n        ax1.set_ylabel(\"Data\")\n        plt.setp(ax1.get_xticklabels(), visible=False)\n        #ax1.errorbar(self.t, self.y, **datstyle)\n        for (tj,yj,e_yj),off in zip(self.data, self.hpstat['offset']):\n           ax1.errorbar(tj, yj-off, yerr=e_yj, **datstyle)\n        ax1.plot(tt, ymod, 'k-')\n\n        tt = arange(T0, T0+1/fbest, 0.01/fbest)\n        yy = self.sinmod(tt)\n        ax2 = fig.add_subplot(3, 2, 4, sharey=ax1)\n        plt.setp(ax2.get_xticklabels(), visible=False)\n        plt.setp(ax2.get_yticklabels(), visible=False)\n        # ax2.set_xlabel(\"Time\")\n        # ax2.set_ylabel(\"Data\")\n        for (tj,yj,e_yj),off in zip(self.data, self.hpstat['offset']):\n           ax2.errorbar(tj*fbest % 1, yj-off, yerr=e_yj, **datstyle)\n        xx = tt*fbest % 1\n        ii = np.argsort(xx)\n        ax2.plot(xx[ii], yy[ii], 'k-')\n\n        # Residuals\n        #yres = self.y - yfit\n        ax3 = fig.add_subplot(3, 2, 5, sharex=ax1)\n        ax3.set_xlabel(\"Time\")\n        ax3.set_ylabel(\"Residuals\")\n        for (tj,yj,e_yj),yjfit in zip(self.data, yfit):\n           ax3.errorbar(tj, yj-yjfit, yerr=e_yj, **datstyle)\n        ax3.plot([self.tmin, self.tmin+self.tbase], [0,0], 'k-')\n\n        ax4 = fig.add_subplot(3, 2, 6, sharex=ax2, sharey=ax3)\n        # ax4.set_title(\"Data\")\n        ax4.set_xlabel(\"Phase\")\n        # ax4.set_ylabel(\"Data\")\n        plt.setp(ax4.get_yticklabels(), visible=False)\n        for (tj,yj,e_yj),yjfit in zip(self.data, yfit):\n           ax4.errorbar(tj*fbest % 1,  yj-yjfit, yerr=e_yj, **datstyle)\n        ax4.plot([0,1], [0,0], 'k-')\n\n        if hasattr(plt.get_current_fig_manager(), 'toolbar'):\n            # check seems not needed when \"TkAgg\" is set\n            plt.get_current_fig_manager().toolbar.pan()\n        #t = fig.canvas.toolbar\n        #plt.ToggleTool(plt.wx_ids['Pan'], False)\n        if block:\n           print(\"Close the plot to continue.\")\n        else:\n           plt.ion()\n        plt.show()\n        # plt.show(block=block) # unexpected keyword argument 'block' in older matplotlib\n        return plt\n\n    def prob(self, Pn):\n        \"\"\"\n        Probability of obtaining the given power.\n\n        Calculate the probability to obtain a power higher than\n        `Pn` from the noise, which is assumed to be Gaussian.\n\n        .. note:: Normalization\n          (see [ZK09]_ for further details).\n\n          - `Scargle`:\n          .. math::\n            exp(-Pn)\n\n          - `HorneBaliunas`:\n          .. math::\n            \\\\left(1 - 2 \\\\times \\\\frac{Pn}{N-1} \\\\right)^{(N-3)/2}\n\n          - `Cumming`:\n          .. math::\n            \\\\left(1+2\\\\times \\\\frac{Pn}{N-3}\\\\right)^{-(N-3)/2}\n\n        Parameters\n        ----------\n        Pn : float\n            Power threshold.\n\n        Returns\n        -------\n        Probability : float\n            The probability to obtain a power equal or\n            higher than the threshold from the noise.\n\n        \"\"\"\n        self._normcheck(self.norm)\n        if self.norm == \"lnL\": return (1.-Pn)**((self.N-3.)/2.)\n        if self.norm == \"Scargle\": return exp(-Pn)\n        if self.norm == \"HorneBaliunas\": return (1.-2.*Pn/(self.N-1.))**((self.N-3.)/2.)\n        if self.norm == \"Cumming\": return (1.+2.*Pn/(self.N-3.))**(-(self.N-3.)/2.)\n        if self.norm == \"wrms\": return (Pn**2/self._YY)**((self.N-3.)/2.)\n        if self.norm == \"chisq\": return (Pn/self._YY/self.wsum)**((self.N-3.)/2.)\n\n    def probInv(self, Prob):\n        \"\"\"\n        Calculate minimum power for given probability.\n\n        This function is the inverse of `Prob(Pn)`.\n        Returns the minimum power for a given probability threshold `Prob`.\n\n        Parameters\n        ----------\n        Prob : float\n            Probability threshold.\n\n        Returns\n        -------\n        Power threshold : float\n            The minimum power for the given false-alarm probability threshold.\n\n        \"\"\"\n        self._normcheck(self.norm)\n        if self.norm == \"lnL\": return 1.-Prob**(2./(self.N-3.))\n        if self.norm == \"Scargle\": return -log(Prob)\n        if self.norm == \"HorneBaliunas\": return (self.N-1) / 2. * (1.-Prob**(2./(self.N-3)))\n        if self.norm == \"Cumming\": return (self.N-3) / 2. * (Prob**(-2./(self.N-3.))-1.)\n        if self.norm == \"wrms\": return sqrt(self._YY * Prob**(2./(self.N-3.)))\n        if self.norm == \"chisq\": return self._YY * self.wsum * Prob**(2./(self.N-3.))\n\n    def FAP(self, Pn):\n        \"\"\"\n        Obtain the false-alarm probability (FAP).\n\n        The FAP denotes the probability that at least one out of M independent\n        power values in a prescribed search band of a power spectrum computed\n        from a white-noise time series is as large as or larger than the\n        threshold, `Pn`. It is assessed through\n\n        .. math:: FAP(Pn) = 1 - (1-Prob(P>Pn))^M \\\\; ,\n\n        where \"Prob(P>Pn)\" depends on the type of periodogram and normalization\n        and is calculated by using the *prob* method; *M* is the number of\n        independent power values and is computed internally.\n\n        Parameters\n        ----------\n        Pn : float\n            Power threshold.\n\n        Returns\n        -------\n        FAP : float\n            False alarm probability.\n\n        \"\"\"\n        prob = self.M * self.prob(Pn)\n        if prob > 0.01:\n           return 1. - (1.-self.prob(Pn))**self.M\n        return prob\n\n    def powerLevel(self, FAPlevel):\n        \"\"\"\n        Power threshold for FAP level.\n\n        Parameters\n        ----------\n        FAPlevel : float or array_like\n              \"False Alarm Probability\" threshold\n\n        Returns\n        -------\n        Threshold : float or array\n            The power threshold pertaining to a specified false-alarm\n            probability (FAP). Powers exceeding this threshold have FAPs\n            smaller than FAPlevel.\n\n        \"\"\"\n        Prob = 1. - (1.-FAPlevel)**(1./self.M)\n        return self.probInv(Prob)\n\n    def stats(self, Pn):\n        \"\"\"\n        Obtain basic statistics for power threshold.\n\n        Parameters\n        ----------\n        Pn : float\n            Power threshold.\n\n        Returns\n        -------\n        Statistics : dictionary\n            A dictionary containing {'Pn': *Pn*, 'Prob': *Prob(Pn)* ,\n            'FAP': *FAP(Pn)*} for the specified power threshold, *Pn*.\n\n        \"\"\"\n        return {'Pn': Pn, 'Prob': self.prob(Pn), 'FAP': self.FAP(Pn)}\n\n    def toFile(self, ofile, header=True):\n        \"\"\"\n        Write periodogram to file.\n\n        Parameters\n        ----------\n        ofile : string\n            Name of the output file.\n\n        \"\"\"\n        with open(ofile, 'w') as f:\n            if header:\n               f.write(\"# Generalized Lomb-Scargle periodogram\\n\")\n               f.write(\"# Parameters:\\n\")\n               if hasattr(self, 'df'):\n                  f.write(\"#    Data file: %s\\n\" % self.df)\n               f.write(\"#    ofac     : %s\\n\" % self.ofac)\n               f.write(\"#    norm     : %s\\n\" % self.norm)\n               f.write(\"# 1) Frequency, 2) Normalized power\\n\")\n            for line in zip(self.freq, self.power, *self.powerj.T.tolist()):\n               f.write((\"%f \"*len(line)) % line + \"\\n\")\n\n        print(\"Results have been written to file: \", ofile)\n\n\ndef example():\n    # Run the example in the Gls class.\n    print(\"--- EXAMPLE CALCULATION ---\")\n    import doctest\n    exec(doctest.script_from_examples(Gls.__doc__))\n    print(\"----------------------------------------------------\")\n\n\nif __name__ == \"__main__\":\n\n  import argparse\n\n  parser = argparse.ArgumentParser(description='Generalized Lomb-Scargle periodogram.', add_help=False)\n  argadd = parser.add_argument   # function short cut\n  argadd('df', nargs='*',\n                 help='Data file (three columns: time, data, error). If not specified example will be shown.')\n  argadd('-fbeg', '--fbeg', type=float, help=\"Starting frequency for periodogram.\")\n  argadd('-fend', '--fend', type=float, help=\"Stopping frequency for periodogram.\")\n  argadd('-Pbeg', '--Pbeg', type=float, help=\"Starting period for periodogram.\")\n  argadd('-Pend', '--Pend', type=float, help=\"Stopping period for periodogram.\")\n  argadd('-ofac', '--ofac', type=float, help=\"Oversampling factor (default=10).\", default=10)\n  argadd('-hifac', '--hifac', type=float, help=\"Maximum frequency (default=1).\", default=1)\n  argadd('-fast', '--fast', help=\"Use trigonometric recurrences.\", action='store_true')\n  argadd('-nojit', '--nojit', help=\"Optimise jitter.\", dest='jit', action='store_false')\n  argadd('-norm', '--norm', help=\"The normalization (default=dlnL).\", choices=Gls.norms, default='dlnL')\n  argadd('-ofile', '--ofile', type=str, help=\"Output file for results.\")\n  argadd('-noplot', '--noplot', help=\"Suppress plots.\", dest='plot', action='store_false')\n  argadd('-nostat', '--nostat', help=\"Switch off statistical output on screen.\", dest='verbose',\n                 action='store_false')\n  argadd('-?', '-h', '-help', '--help', help='Show this help message and exit.', action='help')\n\n  args = vars(parser.parse_args())\n  df = args.pop('df')\n  ofile = args.pop('ofile')\n  plot = args.pop('plot')\n\n  if df is None:\n    # No data file given. Show example:\n    example()\n    print(\"Available options:\")\n    parser.print_help()\n    exit(0)\n\n  # A data file has been given.\n  try:\n   DAT = []\n   for dfi in df:\n     dat = np.loadtxt(dfi, unpack=True)\n     tye = None\n     if len(dat) > 1:\n        tye = dat[0], dat[1]\n     if len(dat) > 2:\n        tye += dat[2],\n     DAT += [tye]\n   tye = DAT\n  except Exception as e:\n     print(\"An error occurred while trying to read data file: \")\n     print(\"  \" + str(e))\n     exit(9)\n\n  gls = Gls(tye, **args)\n\n  if ofile:\n     gls.df = df\n     gls.toFile(ofile)\n\n  if plot:\n     gls.plot(block=True)\n\n#import numpy as np\n#x = np.genfromtxt('/home/astro115/carmenes/data/svn/serval/CARM_VIS/J11421+267/J11421+267.rvc.dat', usecols=(0,1,2)).T\n#print(x)\n\n##g = Gls(tuple(x),fbeg=0.37,fend=0.384, plot=True)\n#ml = Gls(tuple(x),fend=1., plot=True)\n##g.plot()\n##g=Gls(tuple(x), plot=True)\n\n\n##import numpy as np; import mlp; g=mlp.Gls(tuple(x),fbeg=0.37,fend=0.384); g.plot()\n##import numpy as np; import gls; g=gls.Gls(tuple(x),fbeg=0.37,fend=0.384);\n#import numpy as np; import gls; g=gls.Gls(tuple(x),fend=1.);\n#from gplot import*\n#gplot(ml.freq,ml.p,',',g.freq,g.p)\n#g.plot()\n\n\n", "meta": {"hexsha": "1dee0a2e33b968964b27fd9be0c43938efc5840d", "size": 31783, "ext": "py", "lang": "Python", "max_stars_repo_path": "mlp.py", "max_stars_repo_name": "3fon3fonov/python", "max_stars_repo_head_hexsha": "424b9a629355b0692b3fada22a8bad9b642952f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-11-01T08:47:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-21T00:00:46.000Z", "max_issues_repo_path": "mlp.py", "max_issues_repo_name": "3fon3fonov/python", "max_issues_repo_head_hexsha": "424b9a629355b0692b3fada22a8bad9b642952f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2018-05-25T13:40:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-18T10:16:10.000Z", "max_forks_repo_path": "mlp.py", "max_forks_repo_name": "3fon3fonov/python", "max_forks_repo_head_hexsha": "424b9a629355b0692b3fada22a8bad9b642952f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-04-18T08:29:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-30T09:59:51.000Z", "avg_line_length": 35.5912653975, "max_line_length": 172, "alphanum_fraction": 0.5563351477, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 8857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3040416623541848, "lm_q1q2_score": 0.16269221576274706}}
{"text": "#!/usr/bin/env python\n#\n# pKaTool - analysis of systems of titratable groups\n# Copyright (C) 2010 Jens Erik Nielsen\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n#\n# Contact information: \n# Email: Jens.Nielsen_at_gmail.com\n# Normal mail:\n# Jens Nielsen\n# SBBS, Conway Institute\n# University College Dublin\n# Dublin 4, Ireland\n#\nfrom Tkinter import *\nfrom numpy import *\nfrom numpy.linalg import * \ninverse=inv\nFloat=float\n\nfrom titration_class import *\n    \nimport math\n\nclass Optimisation_Analysis:\n\n    def stab_and_CCPS_pop(self):\n        \"\"\"Driver for optimising stability and CCPS population\"\"\"\n        #\n        # Open the optimisation window\n        #\n        self.optwin=Toplevel()\n        parent_geom=self.window.winfo_geometry()\n        parent_geom=parent_geom.split('+')[1:]\n        # Position optimisation window at same position as parent (titration curve window\n        self.optwin.geometry('+%d+%d' %(int(parent_geom[0])+100,int(parent_geom[1])+200))\n        self.optwin.title('System optimisation and analysis')\n        #\n        # Add scoring function specification interface\n        #\n        Label(self.optwin,text='Name').grid(row=1,column=0)\n        Label(self.optwin,text='Optimise').grid(row=1,column=1)\n        Label(self.optwin,text='Opt type').grid(row=1,column=2)\n        Label(self.optwin,text='Cutoff value').grid(row=1,column=3)\n        Label(self.optwin,text='Weight').grid(row=1,column=4)\n        Label(self.optwin,text='pH range').grid(row=1,column=5)\n        Label(self.optwin,text='Use profile').grid(row=1,column=6)\n        Label(self.optwin,text='Optimise sum').grid(row=1,column=7)\n        #\n        self.properties={'CCPS population':{},\n                         'CCPS2 population':{},\n                         'CCPS maxrange':{},\n                         'Stability':{},\n                         'individual intpKa shift':{},\n                         'individual intene':{}\n                         }\n        props=self.properties.keys()\n        props.sort()\n        row=1\n        for prop in props:\n            row=row+1\n            Label(self.optwin,text=prop).grid(row=row,column=0)\n            #\n            self.properties[prop]['include']={'var':IntVar()}\n            self.properties[prop]['include']['widget']=Checkbutton(self.optwin,variable=self.properties[prop]['include']['var'],onvalue=1,offvalue=0)\n            self.properties[prop]['include']['widget'].grid(row=row,column=1)\n            self.properties[prop]['include']['var'].set(1)\n            #\n            self.properties[prop]['opttype']={'var':StringVar()}\n            self.properties[prop]['opttype']['widget']=Menubutton(self.optwin,textvariable=self.properties[prop]['opttype']['var'],relief='raised')\n            self.properties[prop]['opttype']['menu']=Menu(self.properties[prop]['opttype']['widget'],tearoff=0)\n            (self.properties[prop]['opttype']['widget'])['menu']=self.properties[prop]['opttype']['menu']\n            #\n            # Set defaults\n            #\n            if prop=='CCPS population':\n                value=90.0\n                defopttype='maximise'\n                weight=1.0\n            elif prop=='CCPS2 population':\n                value=10.0\n                defopttype='maximise'\n                weight=1.0     \n            elif prop=='Stability':\n                value=0.0\n                defopttype='maximise'\n                weight=1.0\n            elif prop=='individual intpKa shift':\n                value=2.0\n                defopttype='keep below'\n                weight=10000.0\n            elif prop=='individual intene':\n                value=4.6\n                defopttype='keep below'\n                weight=10000.0\n            elif prop=='CCPS maxrange':\n                value=0.20\n                defopttype='maximise'\n                weight=1.0\n            else:\n                raise Exception\n            #\n            # Add all opttypes\n            #\n            for opttype in ['maximise','minimise','keep at','keep above','keep below']:\n                self.properties[prop]['opttype']['menu'].add_radiobutton(label=opttype,\n                                                                         variable=self.properties[prop]['opttype']['var'],\n                                                                         value=opttype,\n                                                                         indicatoron=1)\n            self.properties[prop]['opttype']['widget'].grid(row=row,column=2)\n            self.properties[prop]['opttype']['var'].set(defopttype)\n            #\n            self.properties[prop]['cutoff']={'var':DoubleVar()}\n \n            self.properties[prop]['cutoff']['var'].set(value)\n            self.properties[prop]['cutoff']['widget']=Entry(self.optwin,textvariable=self.properties[prop]['cutoff']['var'],width=10)\n            self.properties[prop]['cutoff']['widget'].grid(row=row,column=3)\n            #\n            self.properties[prop]['weight']={'var':DoubleVar()}\n            self.properties[prop]['weight']['var'].set(weight)\n            self.properties[prop]['weight']['widget']=Entry(self.optwin,textvariable=self.properties[prop]['weight']['var'],width=10)\n            self.properties[prop]['weight']['widget'].grid(row=row,column=4)\n            #\n            self.properties[prop]['pH']={'var':StringVar()}\n            self.properties[prop]['pH']['var'].set('6.5-7.5')\n            self.properties[prop]['pH']['widget']=Entry(self.optwin,textvariable=self.properties[prop]['pH']['var'],width=10)\n            self.properties[prop]['pH']['widget'].grid(row=row,column=5)\n            #\n            # Add a profile selector\n            #\n            if prop in ['CCPS maxrange','CCPS population','CCPS2 population','Stability']:\n                self.properties[prop]['profile']={'var':IntVar()}\n                self.properties[prop]['profile']['var'].set(0)\n                self.properties[prop]['profile']['widget']=Checkbutton(self.optwin,\n                    variable=self.properties[prop]['profile']['var'],onvalue=1,offvalue=0)\n                self.properties[prop]['profile']['widget'].grid(row=row,column=6)\n            #\n            # Selector for individual opt of protonation state populations\n            #\n            if prop in ['CCPS maxrange','CCPS population','CCPS2 population']:\n                self.properties[prop]['sumopt']={'var':IntVar()}\n                self.properties[prop]['sumopt']['var'].set(1)\n                self.properties[prop]['sumopt']['widget']=Checkbutton(self.optwin,\n                                                                       variable=self.properties[prop]['sumopt']['var'],onvalue=1,offvalue=0)\n                self.properties[prop]['sumopt']['widget'].grid(row=row,column=7)\n            \n        #\n        # Open the microscopic population states\n        #\n        self.micro_var.set(1)\n        self.update_pkasystem_curves(0)\n        #\n        # Open the stability window\n        #\n        self.stab_button.select()\n        self.stability_on_off()\n        #\n        # Continue with the optimisation window\n        #\n        row=row+1\n        Label(self.optwin,text='CCPS chosen').grid(row=row,column=0)\n        self.chosen_CCPS=StringVar()\n        Label(self.optwin,textvariable=self.chosen_CCPS).grid(row=row,column=1)\n        self.find_chosen_CCPS()\n        Button(self.optwin,text='update',command=self.find_chosen_CCPS).grid(row=row,column=2)\n        #\n        # Add action buttons\n        #\n        row=row+1\n        Button(self.optwin,text='Load primary pH-activity profile',command=self.pre_load_pH_activity_profile).grid(row=row,column=0)\n        Button(self.optwin,text='Load second pH-activity profile',command=self.pre_load_2nd_pH_activity_profile).grid(row=row,column=1)\n        Button(self.optwin,text='Load pH-stability profile',state=DISABLED).grid(row=row,column=2)\n        #\n        row=row+1\n        Button(self.optwin,text='Randomize system',fg='pink',command=self.randomizesystem).grid(row=row,column=0)\n        Button(self.optwin,text='Start optimisation',fg='green',command=self.optimise_system).grid(row=row,column=1)\n        Button(self.optwin,text='Stop optimisation',fg='red',command=self.stopopt).grid(row=row,column=2)\n        \n        #\n        # Status bar/window\n        #\n        row=row+1\n        self.status=StringVar()\n        Label(self.optwin,textvariable=self.status,bg='white').grid(row=row,column=0,columnspan=4)\n        #\n        # Adjust the resolution of sliders\n        #\n        for group in self.groups:\n            self.groups[group].intpka_scale.configure(resolution=0.01)\n            for group2 in self.groups[group].intenes.keys():\n                self.groups[group].intenes_scales[group2].configure(resolution=0.01)\n        #\n        # Set pH step\n        #\n        self.pHstep.set(0.1)\n        return\n\n    #\n    # ----\n    #\n\n    def pre_load_pH_activity_profile(self):\n        \"\"\"Handle the pH_activity profile load\"\"\"\n        self.load_pH_activity_profile(parent=self.optwin)\n        self.properties['CCPS population']['profile']['var'].set(1)\n        return\n\n    def pre_load_2nd_pH_activity_profile(self):\n        \"\"\"Handle the pH_activity profile load\"\"\"\n        self.load_pH_activity_profile(parent=self.optwin)\n        self.properties['CCPS2 population']['profile']['var'].set(1)\n        return\n\n    #\n    # ----\n    #\n\n    def stopopt(self):\n        \"\"\"Stop the current fitting operation\"\"\"\n        self.keep_running_opt=0\n        return\n\n    #\n    # -----\n    #\n\n    def find_chosen_CCPS(self):\n        \"\"\"Sets the variable that displays the protonation states that are chosen for the CCPS\"\"\"\n        self.chosen_CCPS.set(self.get_CCPSs())\n        return\n    \n    #\n    # -----\n    #\n\n    def randomizesystem(self):\n        return\n\n    #\n    # -----\n    #\n\n    def optimise_system(self):\n        \"\"\"Optimise the system according to the values given by the user\"\"\"\n        #\n        # Did the bozo choose the CCPS?\n        #\n        self.find_chosen_CCPS()\n        if self.get_CCPSs()==[]:\n            import tkMessageBox\n            tkMessageBox.showwarning('No CCPS selected',\n                                     'You have to chose the CCPS from the microscopic states',\n                                     parent=self.optwin)\n            return\n        #\n        # Find the properties we will use\n        #\n        self.active_properties=[]\n        props=self.properties.keys()\n        for prop in props:\n            if self.properties[prop]['include']['var'].get()==1:\n                self.active_properties.append(prop)\n        #\n        print 'I am optimising these properties:',self.active_properties\n \n        #\n        # Get the variables\n        #\n        self.intpkas=[]\n        self.intenes=[]\n        for group in self.groups:\n            self.intpkas.append(self.groups[group].intpka)\n            for group2 in self.groups[group].intenes.keys():\n                self.intenes.append(self.groups[group].intenes[group2])\n        #\n        # Perform all variations within the limits\n        #\n        self.intpka_limit=self.properties['individual intpKa shift']['cutoff']['var'].get()\n        self.intene_limit=self.properties['individual intene']['cutoff']['var'].get()\n        print 'Intpka limit: %5.3f' %self.intpka_limit\n        print 'intene limit: %5.3f' %self.intene_limit\n        #\n        # Make copies of all the variables\n        #\n        self.vars=[]\n        for group in self.groups:\n            self.vars.append([self.groups[group].intpka,'intpka',group])\n            for group2 in self.groups[group].intenes.keys():\n                self.vars.append([self.groups[group].intenes[group2],'intene',group])\n        #\n        # Set damper\n        #\n        self.LM_damper = 0.1\n        #\n        # Update the counter\n        #\n        self.count=0\n        self.keep_running_opt=1\n        #\n        # Init vars for the scoring function\n        #\n        self.CCPS_pH_vals=None\n        self.CCPSmax_pH_vals=None\n        self.Stability_pH_vals=None\n        #\n        # Start off the iterations\n        #\n        scores=self.get_system_score().values()\n        old_diff=10000.0\n        now_diff=0.0\n        for val in self.get_system_score().values():\n            now_diff=now_diff+val\n        min_steps=100\n        for x in range(1,10000):\n            self.fit_LM_optimise()\n            #\n            # Update the counter, the scales and the titration curves\n            #\n            self.status.set(\"Optimisation running. Step %5d\" %self.count)\n            self.count=self.count+1\n            self.window.update()\n            self.optwin.update()\n\n            #self.optwin.update_idletasks()\n            self.update_scales_from_fit()\n            self.titwin.update() # This statement is essential for propagating changes in variable values\n            #\n            #\n            # recalculate the differences\n            #\n            now_diff=0.0\n            for val in self.get_system_score().values():\n                now_diff=now_diff+val\n            #\n            # Check convergence\n            #\n            if abs(now_diff-old_diff)<0.000005 and x>min_steps:\n                print 'Converged',now_diff\n                break\n            else:\n                old_diff=now_diff\n            #\n            # Should we stop?\n            #\n            if self.keep_running_opt==0:\n                print 'User abort'\n                break\n        self.update_pkasystem_curves()\n        return\n\n    #\n    # ----\n    #\n\n    def get_jacobian_optimise(self):\n        \"\"\"Get the Jacobian matrix and errors of the data points\"\"\"\n        #\n        # We have one score for each property included\n        #\n        no_data_points=len(self.active_properties)\n        if 'CCPS2 population' in self.active_properties:\n            no_data_points=no_data_points-1\n        errors = resize(array(0,float),[no_data_points])        \n        jacobian = resize(array(0,float),[no_data_points,len(self.vars)])\n        #\n        # Precalculate the variation of all parameters\n        #\n        \n        variations=[]\n        step = 1e-8\n        for var in range(len(self.vars)):\n            self.vars[var][0].set(self.vars[var][0].get()+step)\n            variations.append(self.get_system_score())\n            self.vars[var][0].set(self.vars[var][0].get()-step)\n        #\n        # construct jacobian\n        #\n        data_id=0\n        #\n        # Find the errors \n        #\n        now=self.get_system_score()\n        for prop in self.active_properties:\n            if prop=='CCPS2 population':\n                continue\n            y=0 # All functions always have minimum at zero\n            errors[data_id] =0-now[prop]\n            #\n            # Find the derivatives\n            #\n            diff=resize(array(0,float),[len(self.vars)])\n            count=0\n            for variation in variations:\n                diff[count]=(now[prop]-variation[prop])/step\n                count=count+1\n            jacobian[data_id]=diff\n            data_id=data_id+1\n        return jacobian,errors\n\n    #\n    # ----\n    #\n\n    def calc_sq_diff_optimise(self,charges):\n        \"\"\"Calculate the square difference\"\"\"\n        diff=0.0\n        import math\n        for pH,crg in charges:\n            y=crg\n            fit_val=eval(self.funktion)\n            diff=diff+math.pow(fit_val-y,2)\n        return diff\n\n    #\n    # ------\n    #\n\n    def fit_LM_optimise(self):\n        \"\"\"Do Levenberg-Marquardt fitting\"\"\"\n        J,E =self.get_jacobian_optimise()\n        JT = transpose(J)\n        JTE = dot(JT,E)\n        JTJ = dot(JT,J)\n        JTJd = JTJ + self.LM_damper*identity(shape(JTJ)[0])\n        invJTJd = inverse(JTJd)\n        q = -dot(JTE,invJTJd)\n        #\n        # Change the values\n        #\n        for var in range(len(self.vars)):\n            #\n            # Update the vars if they do not get outside the bounds\n            #\n            new_val=self.vars[var][0].get()+(q[var]/abs(q[var]))*min(abs(q[var]),0.2)\n            group=self.vars[var][2]\n            ok=None\n            if self.vars[var][1]=='intpka':\n                dintpka=abs(new_val-self.unfolded_groups[group].intpka.get())\n                if dintpka<=self.intpka_limit and new_val>=0.0:\n                    ok=1\n                if self.properties['individual intpKa shift']['include']['var'].get()==0:\n                    #\n                    # If no restriction then the shift is always ok\n                    #\n                    ok=1\n            elif self.vars[var][1]=='intene':\n                if new_val<=self.intene_limit and new_val>=0.0:\n                    ok=1\n                if self.properties['individual intene']['include']['var'].get()==0:\n                    #\n                    # If no restriction then the shift is always ok\n                    #\n                    ok=1\n            else:\n                print 'Unknown variable'\n                raise Exception\n            #\n            # If ok, then update vars\n            #\n            if ok:\n                self.vars[var][0].set(new_val)\n        return\n\n    #\n    # -----\n    #\n    \n    def get_system_score(self):\n        \"\"\"Get value of the scoring function specified by the user\"\"\"\n\n        self.X,pKa_values=self.calc_pKas(self.groups)\n        curve=titration_curve(self.X.prot_states)\n        self.stability=self.do_stab_curve(self.X)\n\n\n        self.act_prof={}\n        for pH in self.phvals:\n            act=0.0\n            for state in self.states:\n                if self.act_state[state].get()==1:\n                    act=act+self.X.all_states[pH][state]['pop']\n            self.act_prof[pH]=act\n        #\n        # Secondary activity profile\n        #\n        self.act_prof2={}\n        for pH in self.phvals:\n            act=0.0\n            for state in self.states:\n                if self.act_state2[state].get()==1:\n                    act=act+self.X.all_states[pH][state]['pop']\n            self.act_prof2[pH]=act\n        #\n        # Score everything\n        #\n        scores={}\n        CCPS2_score=None\n        for prop in self.active_properties:\n            thisprop=self.properties[prop]\n            function=getattr(self,'_'+prop.replace(' ','_'))\n            if prop=='CCPS2 population':\n                CCPS2_score=function(thisprop)\n            else:\n                scores[prop]=function(thisprop)\n        #\n        # Score CCPSs under one\n        #\n        if CCPS2_score:\n            scores['CCPS population']=max(CCPS2_score,scores['CCPS population'])\n            print 'Doing max'\n        #\n        #\n        props=scores.keys()\n        props.sort()\n        for prop in props:\n            print '%10s score: %9.5f,' %(prop,scores[prop])\n        print\n        return scores\n\n    #\n    # -----\n    #\n\n    def _CCPS_population_base(self,variable,primary,spec):\n        \"\"\"Function that will give a score for how well one of the CCPS population meets the targets\"\"\"\n        #\n        # Loaded profile or entered values\n        #\n        if spec['profile']['var'].get()==0:\n            #\n            # Entered values\n            #\n            # Get the pH values where we want to impose the criterium\n            #\n            if not self.CCPS_pH_vals:\n                self.CCPS_pH_vals=self.get_pH_range(spec['pH']['var'].get())\n            print 'Monitoring activity at these pH values',self.CCPS_pH_vals\n            #\n            # pH values have already been identified\n            #\n            opttype=spec['opttype']['var'].get()\n            cutoff=spec['cutoff']['var'].get()\n            if opttype=='maximise':\n                sum_act=0.0\n                count=0\n                for pH in self.CCPS_pH_vals:\n                    if primary:\n                        if self.act_prof[pH]<cutoff:\n                            sum_act=sum_act+self.act_prof[pH]\n                            count=count+1\n                    else:\n                        if self.act_prof2[pH]<cutoff:\n                            sum_act=sum_act+self.act_prof2[pH]\n                            count=count+1\n            \n                if count>1:\n                    sum_act=sum_act/float(count)\n                sum_act=max(cutoff/100.0-sum_act,0)\n            else:\n                raise Exception\n        else:\n            #\n            # Loaded profile\n            #\n            sum_act=0.0\n            #\n            # Optimse profile, or each protonation state on its own\n            #\n            if spec['sumopt']['var'].get()==1:\n                for pH in variable.keys():\n                    if primary:\n                        sum_act=sum_act+abs(variable[pH]-self.act_prof[pH])\n                    else:\n                        sum_act=sum_act+abs(variable[pH]-self.act_prof2[pH])\n            else:\n                #\n                # Find the difference between each protonation state\n                #\n                diffs=[]\n                for state in self.states:\n                    thisdiff=0.0\n                    if (primary and self.act_state[state].get()==1) or (not primary and self.act_state2[state].get()==1):\n                        for pH in variable.keys():\n                            thisdiff=thisdiff+abs(self.X.all_states[pH][state]['pop']-variable[pH])\n                        diffs.append(thisdiff)\n                sum_act=max(diffs)\n        #\n        # Scale the sum by the weight\n        #\n        sum_act=sum_act*spec['weight']['var'].get()\n        return sum_act\n\n    #\n    # ----\n    #\n\n    def _CCPS_population(self,spec):\n        \"\"\"Get the score for the primary CCPS population\"\"\"\n        return self._CCPS_population_base(self.activity_data,1,spec)\n\n    def _CCPS2_population(self,spec):\n        \"\"\"Get the score for the seconary CCPS population\"\"\"\n        return self._CCPS_population_base(self.secondary_activity_data,1,spec)\n\n\n    #\n    # ----\n    #\n\n    def _CCPS_maxrange(self,spec):\n        \"\"\"Score for having the maximum of the CCPS in a range\"\"\"\n        #\n        # Get the pH values where we want to impose the criterium\n        #\n        if not self.CCPSmax_pH_vals:\n            self.CCPSmax_pH_vals=self.get_pH_range(spec['pH']['var'].get())\n            print 'Monitoring activity at these pH values',self.CCPSmax_pH_vals\n        #\n        # pH values have already been identified\n        #\n        opttype=spec['opttype']['var'].get()\n        cutoff=spec['cutoff']['var'].get()\n        if opttype=='maximise':\n            #\n            # Find the maximum activity\n            #\n            maxact=0.0\n            for pH in self.act_prof.keys():\n                maxact=max(maxact,self.act_prof[pH])\n            #\n            # Report the fraction of points that are within 10%\n            #\n            count=0\n            ok=0.0\n            for pH in self.CCPSmax_pH_vals:\n                if maxact>0.000001:\n                    if abs((self.act_prof[pH]-maxact)/maxact)<=cutoff:\n                        pass\n                    else:\n                        ok=ok+abs((self.act_prof[pH]-maxact)/maxact)\n                        print pH,(self.act_prof[pH]-maxact)/maxact\n                else:\n                    ok=ok+10*(0.000001-maxact)\n                count=count+1\n            if count>0:\n                ok=ok/float(count)\n            #\n        else:\n            raise Exception\n        ok=ok*spec['weight']['var'].get()\n        return ok\n\n    #\n    # ----\n    #\n\n    def _Stability(self,spec):\n        \"\"\"Score the stability of the system\"\"\"\n        if not self.Stability_pH_vals:\n            self.Stability_pH_vals=self.get_pH_range(spec['pH']['var'].get())\n        #\n        # Score the stability\n        #\n        opttype=spec['opttype']['var'].get()\n        cutoff=spec['cutoff']['var'].get()\n        if opttype=='maximise':\n            # Maximising stability means minimising the dG of folding\n            sum_stab=0\n            count=0\n            for pH in self.Stability_pH_vals:\n                if self.stability[pH]>cutoff:\n                    sum_stab=sum_stab+self.stability[pH]-cutoff\n                    count=count+1\n            if count>1:\n                sum_stab=sum_stab/float(count)\n        else:\n            raise Exeption\n        import math\n        sum_stab=sum_stab*spec['weight']['var'].get()\n        #print 'Stability',math.exp(sum_stab)\n        return sum_stab\n\n    #\n    # ----\n    #\n\n    def _individual_intpKa_shift(self,spec):\n        \"\"\"Score the total pKa shift\"\"\"\n        return 0.0\n        opttype=spec['opttype']['var'].get()\n        cutoff=spec['cutoff']['var'].get()\n        if opttype=='keep below':\n            score=0.0\n            for group in self.groups:\n                dintpka=abs(self.groups[group].intpka.get()-self.unfolded_groups[group].intpka.get())\n                if dintpka>cutoff:\n                    score=score+math.pow(dintpka-cutoff,4)\n        else:\n            raise Exception\n        return score*spec['weight']['var'].get()\n\n    #\n    # ----\n    #\n\n    def _individual_intene(self,spec):\n        return 0.0\n        \"\"\"Keep all interaction energies below a certain kT limit\"\"\"\n        import math\n        opttype=spec['opttype']['var'].get()\n        cutoff=spec['cutoff']['var'].get()\n        if opttype=='keep below':\n            score=0.0\n            for group in self.groups:\n                for num in self.groups[group].intenes:\n                    intene=self.groups[group].intenes[num].get()\n                    if intene>cutoff:\n                        score=score+math.pow(intene-cutoff,4)\n        else:\n            raise Exception\n        return score*spec['weight']['var'].get()\n    #\n    # ----\n    #\n\n\n    def get_pH_range(self,pH_vals):\n        \"\"\"Return a list of pH values that should be monitored in the individual scoring functions\n        from the input given in the pH range field\"\"\"\n        ranges=pH_vals.split(',')\n        pH_vals=[]\n        for sep in ranges:\n            if sep.find('-')!=-1:\n                start_end=sep.split('-')\n                start=float(start_end[0])\n                end=float(start_end[1])\n                for pH in self.act_prof.keys():\n                    if pH>=start and pH<=end:\n                        pH_vals.append(pH)\n            else:\n                #\n                # Simple number - just pick a value closer than 0.1\n                #\n                pH_set=float(sep)\n                if self.act_prof.has_key(pH_set):\n                    pH_vals.append(pH_set)\n                else:\n                    for pH in self.act_prof.keys():\n                        if abs(pH-pHset)<0.1:\n                            pH_vals.append(pH)\n        pH_vals.sort()\n        return pH_vals\n", "meta": {"hexsha": "24e1fad48201c38399d82abedd0e89b9cd0b208e", "size": 27127, "ext": "py", "lang": "Python", "max_stars_repo_path": "pKaTool/CCPS_stab_opt.py", "max_stars_repo_name": "shambo001/peat", "max_stars_repo_head_hexsha": "7a26e896aa9914b084a9064df09ed15df4047cf3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-11-11T06:11:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-12T22:13:51.000Z", "max_issues_repo_path": "pKaTool/CCPS_stab_opt.py", "max_issues_repo_name": "shambo001/peat", "max_issues_repo_head_hexsha": "7a26e896aa9914b084a9064df09ed15df4047cf3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pKaTool/CCPS_stab_opt.py", "max_forks_repo_name": "shambo001/peat", "max_forks_repo_head_hexsha": "7a26e896aa9914b084a9064df09ed15df4047cf3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-02-15T16:10:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-27T10:33:21.000Z", "avg_line_length": 35.460130719, "max_line_length": 149, "alphanum_fraction": 0.5279242084, "include": true, "reason": "from numpy", "num_tokens": 6049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.2538610013242243, "lm_q1q2_score": 0.16263245959385692}}
{"text": "from einops import rearrange\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom collections import OrderedDict\nimport pandas as pd\nfrom numpy.random import binomial\nfrom torch.cuda.amp import GradScaler, autocast\nfrom advbench.datasets import FFCV_AVAILABLE\n\nfrom advbench import attacks, networks, optimizers, perturbations\nfrom advbench.lib import meters\n\nALGORITHMS = [\n    'ERM',\n    'PGD',\n    'FGSM',\n    'TRADES',\n    'ALP',\n    'CLP',\n    'Gaussian_DALE',\n    'Laplacian_DALE',\n    'Discrete_DALE',\n    'Gaussian_DALE_PD',\n    'Gaussian_DALE_PD_Reverse',\n    'MH_DALE_PD_Reverse',\n    'KL_DALE_PD',\n    'Worst_Of_K',\n    'Augmentation',\n    'Batch_Augmentation',\n    'Grid_Search',\n    'Batch_Grid',\n    'Uniform_DALE_PD_Reverse',\n    'Worst_DALE_PD_Reverse',\n    'PGD_DALE_PD_Reverse'\n]\n\nclass Algorithm(nn.Module):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf'):\n        super(Algorithm, self).__init__()\n        self.hparams = hparams\n        self.classifier = networks.Classifier(\n            input_shape, num_classes, hparams)\n        #summary(self.classifier.to(device), input_size=input_shape)\n        if hparams['optimizer']==\"SGD\":\n            self.optimizer = optimizers.Optimizer(\n             self.classifier, hparams)\n        elif hparams['optimizer']==\"SFCNN\":\n            self.optimizer = optimizers.SFCNN_Optimizer(self.classifier, hparams)\n        else:\n            print(\"Optimizer not suported\")\n            raise NotImplementedError\n        self.device = device\n        \n        self.meters = OrderedDict()\n        self.meters['loss'] = meters.AverageMeter()\n        self.meters_df = None\n        self.perturbation_name = perturbation\n        if FFCV_AVAILABLE:\n            self.scaler = GradScaler()\n        \n        self.label_smoothing = hparams['label_smoothing']\n\n    def step(self, imgs, labels):\n        raise NotImplementedError\n\n    def predict(self, imgs):\n        return self.classifier(imgs)\n\n    def reset_meters(self):\n        for meter in self.meters.values():\n            meter.reset()\n\n    def meters_to_df(self, epoch):\n        if self.meters_df is None:\n            keys = []\n            for key, val in self.meters.items():\n                if val.print:\n                    keys.append(key)\n            columns = ['Epoch'] + keys\n            self.meters_df = pd.DataFrame(columns=columns)\n            self.meters_df_keys = keys\n        metrics = []\n        for key in self.meters_df_keys:\n            metrics.append(self.meters[key].avg)\n        values = [epoch] + metrics\n        self.meters_df.loc[len(self.meters_df)] = values\n        return self.meters_df\n    def export(self):\n        pass\n    def unexport(self):\n        pass\n\nclass ERM(Algorithm):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf'):\n        super(ERM, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation)\n        self.attack = attacks.Rand_Aug(self.classifier, self.hparams, device, perturbation=perturbation)\n    def step(self, imgs, labels):\n        self.optimizer.zero_grad(set_to_none=True)\n        if FFCV_AVAILABLE:\n            with autocast():\n                loss = self.classifier.loss(self.predict(imgs), labels)\n                self.scaler.scale(loss).backward()\n                self.scaler.step(self.optimizer)\n                self.scaler.update()\n        else:\n            loss = self.classifier.loss(self.predict(imgs), labels)\n            loss.backward()\n        self.optimizer.step()\n        \n        self.meters['loss'].update(loss.item(), n=imgs.size(0))\n\nclass Adversarial(Algorithm):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf'):\n        super(Adversarial, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation)\n        self.penalty = hparams[\"adv_penalty\"]\n\n    def step(self, imgs, labels):\n        if FFCV_AVAILABLE:\n            with autocast():\n                adv_imgs, deltas = self.attack(imgs, labels)\n                self.optimizer.zero_grad()\n                adv_loss = self.classifier.loss(self.predict(adv_imgs), labels)\n                clean_loss = self.classifier.loss(self.predict(imgs), labels)\n                loss = clean_loss+adv_loss*self.penalty\n                self.scaler.scale(loss).backward()\n                self.scaler.step(self.optimizer)\n                self.scaler.update()\n        else:\n            adv_imgs, deltas =   self.attack(imgs, labels)\n            self.optimizer.zero_grad()\n            adv_loss = self.classifier.loss(self.predict(adv_imgs), labels)\n            clean_loss = self.classifier.loss(self.predict(imgs), labels)\n            loss = clean_loss+adv_loss*self.penalty\n            loss.backward()\n            self.optimizer.step()\n\n        self.meters['loss'].update(loss.item(), n=imgs.size(0))\n\nclass Adversarial_PGD(Adversarial):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf'):\n        super(Adversarial_PGD, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation)\n        self.attack = attacks.Fo_PGD(self.classifier, self.hparams, device, perturbation=perturbation)\n\nclass Adversarial_SGD(Adversarial):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf'):\n        super(Adversarial_SGD, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation)\n        self.attack = attacks.Fo_SGD(self.classifier, self.hparams, device, perturbation=perturbation)\n\nclass Adversarial_Adam(Adversarial):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf'):\n        super(Adversarial_Adam, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation)\n        self.attack = attacks.Fo_Adam(self.classifier, self.hparams, device, perturbation=perturbation)\n\nclass Adversarial_Smoothed(Adversarial):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf'):\n        super(Adversarial_Smoothed, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation)\n        self.attack = attacks.LMC_Laplacian_Linf(self.classifier, self.hparams, device, perturbation=perturbation)\n\nclass Gaussian_DALE(Algorithm):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf'):\n        super(Gaussian_DALE, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation)\n        self.attack = attacks.LMC_Gaussian_Linf(self.classifier, self.hparams, device, perturbation=perturbation)\n        self.meters['clean loss'] = meters.AverageMeter()\n        self.meters['robust loss'] = meters.AverageMeter()\n\n    def step(self, imgs, labels):\n        if FFCV_AVAILABLE:\n            with autocast():\n                adv_imgs, deltas = self.attack(imgs, labels)\n                adv_imgs, deltas =   self.attack(imgs, labels)\n                self.optimizer.zero_grad()\n                clean_loss = self.classifier.loss(self.predict(imgs), labels)\n                robust_loss = self.classifier.loss(self.predict(adv_imgs), labels)\n                total_loss = robust_loss + self.hparams['g_dale_nu'] * clean_loss\n                self.scaler.scale(total_loss).backward()\n                self.scaler.step(self.optimizer)\n                self.scaler.update()\n        else:\n            adv_imgs, deltas =   self.attack(imgs, labels)\n            self.optimizer.zero_grad()\n            clean_loss = self.classifier.loss(self.predict(imgs), labels)\n            robust_loss = self.classifier.loss(self.predict(adv_imgs), labels)\n            total_loss = robust_loss + self.hparams['g_dale_nu'] * clean_loss\n            total_loss.backward()\n            self.optimizer.step()\n\n        self.meters['loss'].update(total_loss.item(), n=imgs.size(0))\n        self.meters['clean loss'].update(clean_loss.item(), n=imgs.size(0))\n        self.meters['robust loss'].update(robust_loss.item(), n=imgs.size(0))\n\nclass Laplacian_DALE(Algorithm):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf'):\n        super(Laplacian_DALE, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation)\n        self.attack = attacks.LMC_Laplacian_Linf(self.classifier, self.hparams, device, perturbation=perturbation)\n        self.meters['clean loss'] = meters.AverageMeter()\n        self.meters['robust loss'] = meters.AverageMeter()\n\n    def step(self, imgs, labels):\n        if FFCV_AVAILABLE:\n            with autocast():\n                adv_imgs, deltas =   self.attack(imgs, labels)\n                self.optimizer.zero_grad()\n                clean_loss = self.classifier.loss(self.predict(imgs), labels)\n                robust_loss = self.classifier.loss(self.predict(adv_imgs), labels)\n                total_loss = robust_loss + self.hparams['g_dale_nu'] * clean_loss\n                self.scaler.scale(total_loss).backward()\n                self.scaler.step(self.optimizer)\n                self.scaler.update()\n        else:\n            adv_imgs, deltas =   self.attack(imgs, labels)\n            self.optimizer.zero_grad()\n            clean_loss = self.classifier.loss(self.predict(imgs), labels)\n            robust_loss = self.classifier.loss(self.predict(adv_imgs), labels)\n            total_loss = robust_loss + self.hparams['l_dale_nu'] * clean_loss\n            total_loss.backward()\n            self.optimizer.step()\n\n        self.meters['loss'].update(total_loss.item(), n=imgs.size(0))\n        self.meters['clean loss'].update(clean_loss.item(), n=imgs.size(0))\n        self.meters['robust loss'].update(robust_loss.item(), n=imgs.size(0))\n\nclass PrimalDualBase(Algorithm):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf', init=0.0):\n        super(PrimalDualBase, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation)\n        self.dual_params = {'dual_var': torch.tensor(init).to(self.device)}\n        self.meters['clean loss'] = meters.AverageMeter()\n        self.meters['robust loss'] = meters.AverageMeter()\n        self.meters['dual variable'] = meters.AverageMeter()\n        self.meters['delta L1-border'] = meters.AverageMeter()\n        perturbation = vars(perturbations)[perturbation](0)\n        self.meters['delta hist'] = meters.WBDeltaMeter(names = perturbation.names, dims = perturbation.dim)\n\nclass Gaussian_DALE_PD(PrimalDualBase):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf', init=1.0):\n        super(Gaussian_DALE_PD, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation, init=init)\n        self.attack = attacks.LMC_Gaussian_Linf(self.classifier, self.hparams, device, perturbation=perturbation)\n        self.pd_optimizer = optimizers.PrimalDualOptimizer(\n            parameters=self.dual_params,\n            margin=self.hparams['g_dale_pd_margin'],\n            eta=self.hparams['g_dale_pd_eta'])\n\n    def step(self, imgs, labels):\n        if FFCV_AVAILABLE:\n            with autocast():\n                adv_imgs, deltas = self.attack(imgs, labels)\n                self.optimizer.zero_grad()\n                clean_loss = self.classifier.loss(self.predict(imgs), labels)\n                robust_loss = self.classifier.loss(self.predict(adv_imgs), labels)\n                total_loss = robust_loss + self.hparams['g_dale_nu'] * clean_loss\n                self.scaler.scale(total_loss).backward()\n                self.scaler.step(self.optimizer)\n                self.scaler.update()\n        else:\n            adv_imgs, deltas =self.attack(imgs, labels)\n            self.optimizer.zero_grad()\n            clean_loss = self.classifier.loss(self.predict(imgs), labels)\n            robust_loss = self.classifier.loss(self.predict(adv_imgs), labels)\n            total_loss = robust_loss + self.dual_params['dual_var'] * clean_loss\n            total_loss.backward()\n            self.optimizer.step()\n        \n        self.pd_optimizer.step(clean_loss.detach())\n        \n        self.meters['loss'].update(total_loss.item(), n=imgs.size(0))\n        self.meters['clean loss'].update(clean_loss.item(), n=imgs.size(0))\n        self.meters['robust loss'].update(robust_loss.item(), n=imgs.size(0))\n        self.meters['dual variable'].update(self.dual_params['dual_var'].item(), n=imgs.size(0))\n        self.meters['delta L1-border'].update((torch.abs(deltas)-self.hparams['epsilon']).mean().item(), n=imgs.size(0))\n        self.meters['delta hist'].update(deltas.cpu())        \n        #print(deltas[0])\n        \nclass Gaussian_DALE_PD_Reverse(PrimalDualBase):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf', init=1.0):\n        super(Gaussian_DALE_PD_Reverse, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation, init=init)\n        self.attack = attacks.LMC_Gaussian_Linf(self.classifier, self.hparams, device, perturbation=perturbation)\n        self.pd_optimizer = optimizers.PrimalDualOptimizer(\n            parameters=self.dual_params,\n            margin=self.hparams['g_dale_pd_inv_margin'],\n            eta=self.hparams['g_dale_pd_inv_eta'])\n\n    def step(self, imgs, labels):\n        adv_imgs, deltas =self.attack(imgs, labels)\n        self.optimizer.zero_grad()\n        clean_loss = self.classifier.loss(self.predict(imgs), labels)\n        robust_loss = self.classifier.loss(self.predict(adv_imgs), labels)\n        total_loss = clean_loss + self.dual_params['dual_var'] * robust_loss\n        total_loss.backward()\n        self.optimizer.step()\n        self.pd_optimizer.step(robust_loss.detach())\n        self.meters['loss'].update(total_loss.item(), n=imgs.size(0))\n        self.meters['clean loss'].update(clean_loss.item(), n=imgs.size(0))\n        self.meters['robust loss'].update(robust_loss.item(), n=imgs.size(0))\n        self.meters['dual variable'].update(self.dual_params['dual_var'].item(), n=1)\n        self.meters['delta L1-border'].update((torch.abs(deltas)-self.hparams['epsilon']).mean().item(), n=imgs.size(0))\n        self.meters['delta hist'].update(deltas.cpu())\n\nclass Laplacian_DALE_PD_Reverse(PrimalDualBase):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf', init=0.0):\n        super(Laplacian_DALE_PD_Reverse, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation, init=init)\n        self.attack = attacks.LMC_Laplacian_Linf(self.classifier, self.hparams, device, perturbation=perturbation)\n        self.pd_optimizer = optimizers.PrimalDualOptimizer(\n            parameters=self.dual_params,\n            margin=self.hparams['l_dale_pd_inv_margin'],\n            eta=self.hparams['l_dale_pd_inv_eta'])\n\n    def step(self, imgs, labels):\n        if FFCV_AVAILABLE:\n            with autocast():\n                adv_imgs, deltas = self.attack(imgs, labels)\n                self.optimizer.zero_grad()\n                clean_loss = self.classifier.loss(self.predict(imgs), labels)\n                robust_loss = self.classifier.loss(self.predict(adv_imgs), labels)\n                total_loss = clean_loss + self.dual_params['dual_var'] * robust_loss\n                self.scaler.scale(total_loss).backward()\n                self.scaler.step(self.optimizer)\n                self.scaler.update()\n        else:\n            adv_imgs, deltas =self.attack(imgs, labels)\n            self.optimizer.zero_grad()\n            clean_loss = self.classifier.loss(self.predict(imgs), labels)\n            robust_loss = self.classifier.loss(self.predict(adv_imgs), labels)\n            total_loss = clean_loss + self.dual_params['dual_var'] * robust_loss\n            total_loss.backward()\n            self.optimizer.step()\n        self.pd_optimizer.step(robust_loss.detach())\n        self.meters['loss'].update(total_loss.item(), n=imgs.size(0))\n        self.meters['clean loss'].update(clean_loss.item(), n=imgs.size(0))\n        self.meters['robust loss'].update(robust_loss.item(), n=imgs.size(0))\n        self.meters['dual variable'].update(self.dual_params['dual_var'].item(), n=1)\n        self.meters['delta L1-border'].update((torch.abs(deltas)-self.hparams['epsilon']).mean().item(), n=imgs.size(0))\n        self.meters['delta hist'].update(deltas.cpu())\n\nclass Worst_DALE_PD_Reverse(Laplacian_DALE_PD_Reverse):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf', init=0.0):\n        super(Worst_DALE_PD_Reverse, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation, init=init)\n        self.attack = attacks.Worst_Of_K(self.classifier, self.hparams, device, perturbation=perturbation)\n\nclass PGD_DALE_PD_Reverse(Laplacian_DALE_PD_Reverse):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf', init=0.0):\n        super(PGD_DALE_PD_Reverse, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation, init=init)\n        self.attack = attacks.Fo_PGD(self.classifier, self.hparams, device, perturbation=perturbation)\n\nclass Adam_DALE_PD_Reverse(Laplacian_DALE_PD_Reverse):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf', init=0.0):\n        super(Adam_DALE_PD_Reverse, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation, init=init)\n        self.attack = attacks.Fo_Adam(self.classifier, self.hparams, device, perturbation=perturbation)\n\nclass MH_DALE_PD_Reverse(PrimalDualBase):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf', init=0.0):\n        super(MH_DALE_PD_Reverse, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation, init=init)\n        self.meters['acceptance rate'] = meters.AverageMeter()\n        self.attack = attacks.MH(self.classifier, self.hparams, device, perturbation=perturbation, acceptance_meter=self.meters['acceptance rate'])\n        self.pd_optimizer = optimizers.PrimalDualOptimizer(\n            parameters=self.dual_params,\n            margin=self.hparams['g_dale_pd_inv_margin'],\n            eta=self.hparams['g_dale_pd_inv_eta'])\n\n    def step(self, imgs, labels):\n        if FFCV_AVAILABLE:\n            with autocast():\n                adv_imgs, deltas = self.attack(imgs, labels)\n                self.optimizer.zero_grad()\n                clean_loss = self.classifier.loss(self.predict(imgs), labels)\n                robust_loss = self.classifier.loss(self.predict(adv_imgs), labels)\n                total_loss = clean_loss + self.dual_params['dual_var'] * robust_loss\n                self.scaler.scale(total_loss).backward()\n                self.scaler.step(self.optimizer)\n                self.scaler.update()\n        else:\n            adv_imgs, deltas =self.attack(imgs, labels)\n            self.optimizer.zero_grad()\n            clean_loss = self.classifier.loss(self.predict(imgs), labels)\n            robust_loss = self.classifier.loss(self.predict(adv_imgs), labels)\n            total_loss = clean_loss + self.dual_params['dual_var'] * robust_loss\n            total_loss.backward()\n            self.optimizer.step()\n        self.pd_optimizer.step(robust_loss.detach())\n        self.meters['loss'].update(total_loss.item(), n=imgs.size(0))\n        self.meters['clean loss'].update(clean_loss.item(), n=imgs.size(0))\n        self.meters['robust loss'].update(robust_loss.item(), n=imgs.size(0))\n        self.meters['dual variable'].update(self.dual_params['dual_var'].item(), n=1)\n        self.meters['delta L1-border'].update((torch.abs(deltas)-self.hparams['epsilon']).mean().item(), n=imgs.size(0))\n        self.meters['delta hist'].update(deltas.cpu())\n\nclass KL_DALE_PD(PrimalDualBase):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf', init=0.0):\n        super(KL_DALE_PD, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation, init=init)\n        self.attack = attacks.TRADES_Linf(self.classifier, self.hparams, device, perturbation=perturbation)\n        self.kl_loss_fn = nn.KLDivLoss(reduction='batchmean')\n        self.pd_optimizer = optimizers.PrimalDualOptimizer(\n            parameters=self.dual_params,\n            margin=self.hparams['g_dale_pd_margin'],\n            eta=self.hparams['g_dale_pd_eta'])\n\n    def step(self, imgs, labels):\n        if FFCV_AVAILABLE:\n            with autocast():\n                adv_imgs, deltas = self.attack(imgs, labels)\n                self.optimizer.zero_grad()\n                clean_loss = self.classifier.loss(self.predict(imgs), labels)\n                robust_loss = self.kl_loss_fn(\n                F.log_softmax(self.predict(adv_imgs), dim=1),\n                F.softmax(self.predict(imgs), dim=1))\n                total_loss = clean_loss + self.dual_params['dual_var'] * robust_loss\n                self.scaler.scale(total_loss).backward()\n                self.scaler.step(self.optimizer)\n                self.scaler.update()\n        else:\n            adv_imgs, deltas =self.attack(imgs, labels)\n            self.optimizer.zero_grad()\n            clean_loss = self.classifier.loss(self.predict(imgs), labels)\n            robust_loss = self.kl_loss_fn(\n                F.log_softmax(self.predict(adv_imgs), dim=1),\n                F.softmax(self.predict(imgs), dim=1))\n            total_loss = robust_loss + self.dual_params['dual_var'] * clean_loss\n            total_loss.backward()\n            self.optimizer.step()\n        self.pd_optimizer.step(clean_loss.detach())\n\n        self.meters['loss'].update(total_loss.item(), n=imgs.size(0))\n        self.meters['clean loss'].update(clean_loss.item(), n=imgs.size(0))\n        self.meters['robust loss'].update(robust_loss.item(), n=imgs.size(0))\n        self.meters['dual variable'].update(self.dual_params['dual_var'].item(), n=1)\n\n\nclass Adversarial_Worst_Of_K(Algorithm):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf'):\n        super(Adversarial_Worst_Of_K, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation)\n        self.attack = attacks.Worst_Of_K(self.classifier, self.hparams, device, perturbation=perturbation)\n\n    def step(self, imgs, labels):\n        if FFCV_AVAILABLE:\n            with autocast():\n                with torch.no_grad():\n                    adv_imgs, deltas =   self.attack(imgs, labels)\n                self.optimizer.zero_grad()\n                clean_loss = self.classifier.loss(self.predict(imgs), labels)\n                robust_loss = self.classifier.loss(self.predict(adv_imgs), labels)\n                total_loss = clean_loss + self.dual_params['dual_var'] * robust_loss\n                self.scaler.scale(total_loss).backward()\n                self.scaler.step(self.optimizer)\n                self.scaler.update()\n        else:        \n            with torch.no_grad():\n                adv_imgs, deltas =   self.attack(imgs, labels)\n            self.optimizer.zero_grad()\n            loss = self.classifier.loss(self.predict(adv_imgs), labels)\n            loss.backward()\n            self.optimizer.step()\n\n        self.meters['loss'].update(loss.item(), n=imgs.size(0))\n\nclass Grid_Search(Algorithm):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf'):\n        super(Grid_Search, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation)\n        self.attack = attacks.Grid_Search(self.classifier, self.hparams, device, perturbation=perturbation)\n\n    def step(self, imgs, labels):\n        if FFCV_AVAILABLE:\n            with autocast():\n                with torch.no_grad():\n                    adv_imgs, deltas =   self.attack(imgs, labels)\n                    self.optimizer.zero_grad()\n                    loss = self.classifier.loss(self.predict(adv_imgs), labels)\n                    self.scaler.scale(loss).backward()\n                    self.scaler.step(self.optimizer)\n                    self.scaler.update()\n        else:\n            with torch.no_grad():\n                adv_imgs, deltas =   self.attack(imgs, labels)\n            self.optimizer.zero_grad()\n            loss = self.classifier.loss(self.predict(adv_imgs), labels)\n            loss.backward()\n            self.optimizer.step()\n\n        self.meters['loss'].update(loss.item(), n=imgs.size(0))\n\nclass Augmentation(Algorithm):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf'):\n        super(Augmentation, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation)\n        self.attack = attacks.Rand_Aug(self.classifier, self.hparams, device, perturbation=perturbation)\n        self.p = hparams['augmentation_prob']\n    def step(self, imgs, labels):\n        if FFCV_AVAILABLE:\n            with autocast():\n                if binomial(1, self.p):\n                    adv_imgs, _ =   self.attack(imgs, labels)\n                else:\n                    adv_imgs = imgs\n                self.optimizer.zero_grad()\n                loss = self.classifier.loss(self.predict(adv_imgs), labels)\n                self.scaler.scale(loss).backward()\n                self.scaler.step(self.optimizer)\n                self.scaler.update()\n        else:        \n            if binomial(1, self.p):\n                adv_imgs, _ =   self.attack(imgs, labels)\n            else:\n                adv_imgs = imgs\n            self.optimizer.zero_grad()\n            loss = self.classifier.loss(self.predict(adv_imgs), labels)\n            loss.backward()\n            self.optimizer.step()\n\n        self.meters['loss'].update(loss.item(), n=imgs.size(0))\n\nclass Laplacian(Augmentation):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf'):\n        super(Laplacian, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation)\n        self.attack = attacks.Laplace_aug(self.classifier, self.hparams, device, perturbation=perturbation)\n        self.p = 1\n\nclass Gaussian(Augmentation):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf'):\n        super(Gaussian, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation)\n        self.attack = attacks.Gaussian_aug(self.classifier, self.hparams, device, perturbation=perturbation)\n        self.p = 1\n\nclass Batch_Random(Algorithm):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf'):\n        super(Batch_Random, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation)\n        self.attack = attacks.Rand_Aug_Batch(self.classifier, self.hparams, device, perturbation=perturbation)\n    def step(self, imgs, labels):\n        adv_imgs, deltas, new_labels =   self.attack(imgs, labels)\n        self.optimizer.zero_grad()\n        loss = self.classifier.loss(self.predict(adv_imgs), new_labels)\n        loss.backward()\n        self.optimizer.step()\n\n        self.meters['loss'].update(loss.item(), n=imgs.size(0))\n\nclass Batch_Grid(Algorithm):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf'):\n        super(Batch_Grid, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation)\n        self.attack = attacks.Grid_Batch(self.classifier, self.hparams, device, perturbation=perturbation)\n    \n    def step(self, imgs, labels):\n        adv_imgs, deltas, new_labels =  self.attack(imgs, labels)\n        self.optimizer.zero_grad()\n        loss = self.classifier.loss(self.predict(adv_imgs), new_labels)\n        loss.backward()\n        self.optimizer.step()\n        self.meters['loss'].update(loss.item(), n=imgs.size(0))\n\n\nclass Discrete_DALE(PrimalDualBase):\n    def __init__(self, input_shape, num_classes, hparams, device, perturbation='Linf', init=0.0, batched=False):\n        if perturbation != 'SE':\n            raise NotImplementedError\n        super(Discrete_DALE, self).__init__(input_shape, num_classes, hparams, device, perturbation=perturbation, init=init)\n        self.attack = attacks.Grid_Batch(self.classifier, hparams, device, perturbation=perturbation)\n        translations = []\n        for idx in (1, 2):\n            eps = hparams['epsilon'][idx]\n            step = 2*eps/hparams['d_num_translations']\n            translations.append(torch.arange(-eps, eps, step=step, device=self.device))\n        eps = hparams['epsilon'][0]\n        step = 2*eps/hparams['d_num_rotations']\n        self.translations = translations\n        self.rotation = torch.arange(-eps, eps, step=step, device=self.device)\n        grids =  [self.rotation] + translations\n        self.grid = torch.cartesian_prod(*grids)\n        self.attack.grid = self.grid\n        self.attack.grid_size = self.grid.shape[0]\n        self.dual_params = {'dual_var': torch.ones(self.grid.shape[0]).to(self.device)*init}\n        self.pd_optimizer = optimizers.PrimalDualOptimizer(parameters=self.dual_params,\n                                                            margin=self.hparams['d_dale_pd_inv_margin'],\n                                                            eta=self.hparams['d_dale_pd_inv_eta'])\n        loc0 = (int(translations[0].shape[0]//2), int(translations[1].shape[0]//2))\n        # Dual plot logger\n        self.meters['dual plot'] = meters.WBDualMeter(self.grid,translations, names = \"Dual var vs angle\",\n                                                         locs = [(0,0), loc0, (-1, -1)])\n        \n    def step(self, imgs, labels):\n        if FFCV_AVAILABLE:\n            with autocast():\n                with torch.no_grad():\n                    adv_imgs, deltas, new_labels = self.attack(imgs, labels)\n                self.optimizer.zero_grad()\n                clean_loss = self.classifier.loss(self.predict(imgs), labels)\n                robust_loss = self.classifier.loss(self.predict(adv_imgs), new_labels, reduction='none')\n                robust_loss = rearrange(robust_loss, '(B S) -> B S', B = imgs.shape[0])\n                total_loss = clean_loss +  torch.mean(robust_loss@self.dual_params['dual_var'].to(self.device))\n                self.scaler.scale(total_loss).backward()\n                self.scaler.step(self.optimizer)\n                self.scaler.update()\n        else:\n            with torch.no_grad():\n                adv_imgs, deltas, new_labels =self.attack(imgs, labels)\n            self.optimizer.zero_grad()\n            clean_loss = self.classifier.loss(self.predict(imgs), labels)\n            robust_loss = self.classifier.loss(self.predict(adv_imgs), new_labels, reduction='none')\n            robust_loss = rearrange(robust_loss, '(B S) -> B S', B = imgs.shape[0])\n            total_loss = clean_loss +  torch.mean(robust_loss@self.dual_params['dual_var'].to(self.device))\n            total_loss.backward()\n            self.optimizer.step()\n        #print(\"rloss before\", robust_loss[:10])\n        #print(\"dual before upd\", self.dual_params['dual_var'])\n        with torch.no_grad():\n            self.pd_optimizer.step(torch.mean(robust_loss, 0).detach())\n        #print(\"rloss\", robust_loss[:10])\n        #print(\"dual after upd\", self.dual_params['dual_var'][:10])\n        #print(f\"clean {clean_loss.item()}, robust {robust_loss.mean().item()}, total {total_loss.item()}, dual {self.dual_params['dual_var'].mean().item()}\")\n        self.meters['loss'].update(total_loss.item(), n=imgs.size(0))\n        self.meters['clean loss'].update(clean_loss.item(), n=imgs.size(0))\n        self.meters['robust loss'].update(robust_loss.mean().item(), n=imgs.size(0))\n        self.meters['dual variable'].update(self.dual_params['dual_var'].mean().item(), n=1)\n        self.meters['dual plot'].update(self.dual_params['dual_var'])\n        #print(\"dual after log\", self.dual_params['dual_var'][:10])\n\n        \n    def get_grid(self, tx, ty):\n        angle_grid = self.attack.grid\n        ones = torch.ones_like(angle_grid)\n        grid = torch.column_stack([angle_grid, tx*ones, ty*ones])\n        return grid\n", "meta": {"hexsha": "44ba7ba9fa5111ed113c780e5af8ea9b41bc7494", "size": 32023, "ext": "py", "lang": "Python", "max_stars_repo_path": "advbench/algorithms.py", "max_stars_repo_name": "constrainedlearning/advbench", "max_stars_repo_head_hexsha": "68f9f6d77268aad45517ca84d383b996724cc976", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "advbench/algorithms.py", "max_issues_repo_name": "constrainedlearning/advbench", "max_issues_repo_head_hexsha": "68f9f6d77268aad45517ca84d383b996724cc976", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "advbench/algorithms.py", "max_forks_repo_name": "constrainedlearning/advbench", "max_forks_repo_head_hexsha": "68f9f6d77268aad45517ca84d383b996724cc976", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.8171521036, "max_line_length": 158, "alphanum_fraction": 0.6466914405, "include": true, "reason": "from numpy", "num_tokens": 7487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.31069438959712026, "lm_q1q2_score": 0.1626237658154829}}
{"text": "# read snapshot and obtain multiple systems\nimport collections\nfrom scipy import spatial as sp\nfrom .base import *\nfrom .bse import *\n\nG_MSUN_PC_MYR=0.00449830997959438 # Msun, pc, myr\nG_HENON=1 # Henon unit\n\nclass PeTarDataHeader():\n    \"\"\" Petar snapshot data header\n    members:\n        fid: file id\n        n: number of particles\n        time: time of snapshot\n    \"\"\"\n\n    def __init__(self, _filename=None):\n        \"\"\" Initial data header\n        \n        Parameters:\n        -----------\n        _filename: string\n            PeTar snapshot file name to read the header, if not provide, all members are initialized to zero (None)\n        \"\"\"\n        self.fid = 0\n        self.n = 0\n        self.time = 0.0\n        \n        if (_filename!=None): self.read(_filename)\n\n    def read(self, _filename):\n        \"\"\" Read snapshot file to obtain the header information\n\n        Parameters:\n        -----------\n        _filename: string\n            PeTar snapshot file name to read the header\n        \"\"\"\n\n        fp = open(_filename, 'r')\n        header=fp.readline()\n        file_id, n_glb, t = header.split()\n        fp.close()\n\n        self.fid = int(file_id)\n        self.n = int(n_glb)\n        self.time = float(t)\n        \n\nclass SimpleParticle(DictNpArrayMix):\n    \"\"\" Simple particle class with only mass, postion, velocity\n    keys: (class members)\n        mass (1D): mass\n        pos (2D,3): postion x, y, z\n        vel (2D,3): velocity vx, vy, vz\n    \"\"\"\n    def __init__(self, _dat=None, _offset=int(0), _append=False, **kwargs):\n        \"\"\" DictNpArrayMix type initialzation, see help(DictNpArrayMix.__init__)\n        \"\"\"\n        keys = [['mass',1], ['pos',3], ['vel',3]]\n        DictNpArrayMix.__init__(self, keys, _dat, _offset, _append, **kwargs)\n\n    def calcR2(self):\n        \"\"\" calculate distance square, r2, and add it as a class member\n        \"\"\"\n        if (not 'r2' in self.__dict__.keys()): \n            self.ncols += 1\n            self.keys.append(['r2',1])\n        self.r2 = vecDot(self.pos,self.pos)\n\n    def calcEkin(self):\n        \"\"\" calculate kinetic energy\n        \"\"\"\n        if (not 'ekin' in self.__dict__.keys()): \n            self.ncols += 1\n            self.keys.append(['ekin',1])\n        self.ekin = 0.5*vecDot(self.vel,self.vel)*self.mass\n\n    def correctCenter(self, cm_pos, cm_vel):\n        self.pos -= cm_pos\n        self.vel -= cm_vel\n\nclass Particle(SimpleParticle):\n    \"\"\" Particle class \n    keys: (class members)\n        The final keys are a combination of sub keys depending on kwargs of initial function\n\n        Sub key list:\n        basic: [inherit SimpleParticle]\n        add: binary_state: binary interruption state \n        se: radius:        (1D): radius for merger checker\n            dm:            (1D): mass loss\n            time_record    (1D): last time of interruption check\n            time_interrupt (1D): next interruption time\n        ptcl: r_search (1D): searching radius\n              id       (1D): identification\n              mass_bk  (1D): artificial particle parameter 1 \n              status   (1D): artificial particle parameter 2\n              r_in     (1D): changeover function inner boundary\n              r_out    (1D): changeover function outer boundary\n        hermite: dt    (1D): time step\n                 time  (1D): current time\n                 acc   (2D,3): acceleration x, y, z\n                 jerk  (2D,3): acceleration derivative x, y, z\n                 pot   (1D): potential\n        soft: acc_soft (2D,3): long-range interaction acceleration (particle-tree) x, y, z\n              pot      (1D): total potential\n              pot_soft (1D): long-range interaction potential\n              n_nb:    (1D): number of neighbors (short-interaction)\n\n        Combination: \n        ends:\n            kwargs['particle_type']:\n                hermite:   ptcl + hermite\n                hard:      ptcl\n                soft (default): ptcl + soft\n        Final:\n        keys:\n            kwargs['interrupt_mode']:\n                base:      basic + add + se + ends\n                bse:       basic + add + se + ['star',SSEStarParameter] + ends\n                none (default): basic + add + ends\n\n    \"\"\"\n\n    def __init__ (self, _dat=None, _offset=int(0), _append=False, **kwargs):\n        \"\"\" DictNpArrayMix type initialzation, see help(DictNpArrayMix.__init__)\n\n        Parameters\n        ----------\n        keyword arguments:\n            particle_type: basic particle type: hermite, hard, soft (soft)\n            interrupt_mode: PeTar interrupt mode: base, bse, none (none)\n        \"\"\"\n\n        keys_add = [['binary_state',1]]\n        keys_se  = [['radius',1],['dm',1],['time_record',1],['time_interrupt',1]]\n        keys_ptcl_add = [['r_search',1], ['id',1], ['mass_bk',1], ['status',1], ['r_in',1], ['r_out',1]]\n        keys_hermite_add = [['dt',1],['time',1],['acc',3],['jerk',3],['pot',1]]\n        keys_soft_add = [['acc_soft',3], ['pot',1], ['pot_soft',1], ['n_nb',1]]\n        keys_end =  keys_ptcl_add + keys_soft_add\n        if ('particle_type' in kwargs.keys()):\n            if (kwargs['particle_type']=='hermite'):\n                keys_end = keys_ptcl_add + keys_hermite_add\n            elif (kwargs['particle_type']=='hard'):\n                keys_end = keys_ptcl_add\n        keys=keys_add+keys_end\n        if ('interrupt_mode' in kwargs.keys()):\n            if (kwargs['interrupt_mode']=='base'):\n                keys = keys_add+keys_se+keys_end\n            elif (kwargs['interrupt_mode']=='bse'):\n                keys = keys_add+keys_se+[['star',SSEStarParameter]]+keys_end\n            \n        SimpleParticle.__init__(self, _dat, _offset, _append, **kwargs)\n        DictNpArrayMix.__init__(self, keys, _dat, _offset+self.ncols, True, **kwargs)\n\n    def calcEtot(self):\n        \"\"\" Calculate total energy and add it as the member, etot\n        \"\"\"\n        if (not 'etot' in self.__dict__.keys()): \n            self.ncols += 1\n            self.keys.append(['etot',1])\n        self.etot = self.ekin + self.mass*self.pot\n\ndef calculateParticleCMDict(pcm, _p1, _p2):\n    \"\"\" Calculate the center-of-the-mass of two particle sets\n    \n    Parameters\n    ----------\n    _p1: inherited SimpleParticle\n        particle set 1\n    _p2: inherited SimpleParticle \n        particle set 2, should have the same size as _p1\n    pcm: dict \n        particle center-of-the-mass, should include keys: 'mass','pos','vel'.\n    \"\"\"\n    if (issubclass(type(_p1), SimpleParticle)) & (issubclass(type(_p2),SimpleParticle)):\n        pcm['mass'] = _p1.mass + _p2.mass\n        pcm['pos']  = np.array(list(map(lambda m1,x1,m2,x2:(m1*x1+m2*x2)/(m1+m2), _p1.mass, _p1.pos, _p2.mass, _p2.pos)))\n        pcm['vel']  = np.array(list(map(lambda m1,x1,m2,x2:(m1*x1+m2*x2)/(m1+m2), _p1.mass, _p1.vel, _p2.mass, _p2.vel)))\n    elif (isinstance(_p1, collections.OrderedDict)) & (isinstance(_p2,collections.OrderedDict)) | (isinstance(_p1, dict)) & (isinstance(_p2, dict)):\n        pcm['mass'] = _p1['mass'] + _p2['mass']\n        pcm['pos']  = np.array(list(map(lambda m1,x1,m2,x2:(m1*x1+m2*x2)/(m1+m2), _p1['mass'], _p1['pos'], _p2['mass'], _p2['pos'])))\n        pcm['vel']  = np.array(list(map(lambda m1,x1,m2,x2:(m1*x1+m2*x2)/(m1+m2), _p1['mass'], _p1['vel'], _p2['mass'], _p2['vel'])))\n    else:\n        raise ValueError('Initial fail, date type should be Particle or collections.OrderDict, given',type(_p1))\n\nclass Binary(DictNpArrayMix):\n    \"\"\" Binary class\n    Keys:\n        The final keys depends on kwargs of initial function\n  \n        kwargs['simple_mode'] (bool)\n            True: (default)\n                mass (1D): total mass of two components\n                pos  (2D,3): c.m. position x, y, z\n                vel  (2D,3): c.m. velocity vx, vy, vz\n                rrel (1D): relative distance\n                semi (1D): semi-major axis\n                ecc  (1D): eccentricity\n                p1   (member_particle_type) component one\n                p2   (member_particle_type) component two\n            False:\n                mass (1D): total mass of two components\n                pos  (2D,3): c.m. position x, y, z\n                vel  (2D,3): c.m. velocity vx, vy, vz\n                m1   (1D): component 1 mass\n                m2   (1D): component 2 mass\n                rrel (1D): relative distance\n                semi (1D): semi-major axis\n                am   (2D,3): specific angular momemtum x, y, z\n                L    (2D,3): angular momemtum x, y, z\n                eccvec  (2D,3): eccentric vector\n                incline (1D): inclination\n                rot_horizon (1D): frame rotational angle in x-y plane (longitude of ascending node)\n                ecc  (1D): eccentricity\n                rot_self (1D): frame rotational angle in orbital plane (argument of periapsis)\n                ecca (1D): eccentric anomaly\n                period (1D): period\n                t_peri (1D): time to peri-center\n                p1 (member_particle_type) component one\n                p2 (member_particle_type) component two\n\n        member_particle_type is given by kwargs['member_particle_type'], in default it is SimpleParticle\n               \n    \"\"\"\n    def __init__ (self, _p1=None, _p2=None, _offset=int(0), _append=False, **kwargs):\n        \"\"\"\n        Parameters\n        ----------\n        _p1: inherited SimpleParticle | 2D numpy.ndarray | Binary | None\n            If the type is inherited SimpleParticle, it is the first component of binary (_p2 should be the same type).\n            If the type is Binary, the class instance is initialized by copy the data of _p1.\n            If it is None, initialize class with empty data\n        _p2: inherited SimpleParticle | None\n            If the type is inherited SimpleParticle, it is the second component of binary \n            If it is None, _p1 should be either 2D numpy.ndarray or Bina\n        _offset: int (0)\n            Reading column offset of _dat if it is 2D np.ndarray\n        _append: bool (False)\n            If true, append keys and ncols to the current class instead of create new class members\n        kwaygs: dict ()\n            keyword arguments:\n                simple_mode: only calculate semi and ecc, save computing time significantly (True)\n                G: gravitational constant (1.0)\n                member_particle_type: type of component particle (SimpleParticle)\n        \"\"\"\n        G=1\n        simple_mode=True\n        member_particle_type=SimpleParticle\n        \n        if 'G' in kwargs.keys(): G=kwargs['G']\n        if 'simple_mode' in kwargs.keys(): simple_mode=kwargs['simple_mode']\n        if 'member_particle_type' in kwargs.keys(): member_particle_type=kwargs['member_particle_type']\n\n        if (issubclass(type(_p1), SimpleParticle)) & (issubclass(type(_p2),SimpleParticle)):\n            member_particle_type = type(_p1)\n            if (simple_mode): \n                self.keys = [['mass',1],['pos',3],['vel',3],['rrel',1],['semi',1],['ecc',1],['p1',member_particle_type], ['p2', member_particle_type]]\n                self.particleToSemiEcc(_p1, _p2, G)\n                self.ncols= int(10)\n            else:\n                self.keys = [['mass',1],['pos',3],['vel',3],['m1',1],['m2',1],['rrel',1],['semi',1],['am',3],['L',3],['eccvec',3],['incline',1],['rot_horizon',1],['ecc',1],['rot_self',1],['ecca',1],['period',1],['t_peri',1],['p1', member_particle_type],['p2', member_particle_type]]\n                self.particleToBinary(_p1, _p2, G)\n                self.ncols= int(27)\n            self.p1 = _p1\n            self.p2 = _p2\n            self.size = _p1.size\n            self.ncols += self.p1.ncols + self.p2.ncols\n        elif (_p2==None):\n            if (simple_mode):\n                keys = [['mass',1],['pos',3],['vel',3],['rrel',1],['semi',1],['ecc',1],['p1',member_particle_type], ['p2', member_particle_type]]\n                DictNpArrayMix.__init__(self, keys, _p1, _offset, _append, **kwargs)\n            else:\n                keys=[['mass',1],['pos',3],['vel',3],['m1',1],['m2',1],['rrel',1],['semi',1],['am',3],['L',3],['eccvec',3],['incline',1],['rot_horizon',1],['ecc',1],['rot_self',1],['ecca',1],['period',1],['t_peri',1],['p1', member_particle_type],['p2', member_particle_type]]\n                DictNpArrayMix.__init__(self, keys, _p1, _offset, _append, **kwargs)\n        else:\n            raise ValueError('Initial fail, date type should be Particle (2), Binary (1) or no argument (0)')\n        self.initargs = kwargs.copy()\n        self.initargs['G'] = G\n\n    def calcEkin(self):\n        \"\"\" Calculate c.m. kinetic energy, ekin, and add it as a member\n        \"\"\"\n        if (not 'ekin' in self.__dict__.keys()): \n            self.ncols += 1\n            self.keys.append(['ekin',1])\n        self.ekin = 0.5*vecDot(self.vel,self.vel)*self.mass\n\n    def calcEtot(self):\n        \"\"\" Calculate c.m. total energy (binary energy is excluded) , etot, and add it as a member\n        \"\"\"\n        if (not 'etot' in self.__dict__.keys()): \n            self.ncols += 1\n            self.keys.append(['etot',1])\n        self.etot = self.ekin + self.mass*self.pot\n\n    def calcR2(self, member_also=False):\n        \"\"\" Calculate c.m. distance square, r2, and add it as a member\n        \"\"\"\n        if (not 'r2' in self.__dict__.keys()): \n            self.ncols += 1\n            self.keys.append(['r2',1])\n        self.r2 = vecDot(self.pos,self.pos)\n        if (member_also):\n            ncols = self.p1.ncols + self.p2.ncols\n            self.p1.calcR2()\n            self.p2.calcR2()\n            ncols = self.p1.ncols + self.p2.ncols - ncols\n            self.ncols += ncols\n\n    def calcEbin(self):\n        \"\"\" Calculate binding energy, ebin, and add it as a member \n            Notice G should be given the correct value in initialization (keyword argument 'G')\n        \"\"\"\n        if (not 'ebin' in self.__dict__.keys()):\n            self.ncols += 1\n            self.keys.append(['ebin',1])\n        self.ebin = self.initargs['G']*self.p1.mass*self.p2.mass/(2*self.semi)\n\n    def calcPot(self):\n        \"\"\" Calculate potential of c.m., pot, and add it as a member\n            Notice G should be given the correct value in initialization (keyword argument 'G')\n        \"\"\"\n        G = self.initargs['G']\n        pos_b1 = self.p1.pos\n        pos_b2 = self.p2.pos\n        m_b1 = self.p1.mass\n        m_b2 = self.p2.mass\n        dr = pos_b1-pos_b2\n        dr2 = vecDot(dr,dr)\n        invr = 1/np.sqrt(dr2)\n        pot_b1 = self.p1.pot + G*m_b2*invr\n        pot_b2 = self.p2.pot + G*m_b1*invr\n        if (not 'pot' in self.__dict__.keys()): \n            self.ncols += 1\n            self.keys.append(['pot',1])\n        self.pot = (m_b2*pot_b1 + m_b1*pot_b2)/self.mass\n            \n    def correctCenter(self, cm_pos, cm_vel):\n        \"\"\" Corrent c.m and component position and velocity by subtracting cm_pos and cm_vel\n        \"\"\"\n        self.pos -= cm_pos\n        self.vel -= cm_vel\n        self.p1.correctCenter(cm_pos, cm_vel)\n        self.p2.correctCenter(cm_pos, cm_vel)\n\n    def particleToSemiEcc(self, _p1, _p2, _G):\n        \"\"\" Calculate relative distance, semi-major axis and eccentricity from particle pairs\n\n        Parameters\n        ----------\n        _p1, _p2: inherited SimpleParticle\n            Particle pair data set\n        _G: float\n            Gravitational constant\n\n        \"\"\"\n        calculateParticleCMDict(self.__dict__, _p1, _p2)\n\n        dr = (_p1.pos - _p2.pos)\n        dv = (_p1.vel - _p2.vel)\n        \n        dr2  = (dr*dr).sum(axis=1)\n        dv2  = (dv*dv).sum(axis=1)\n        rvdot= (dr*dv).sum(axis=1)\n    \n        dr   = np.sqrt(dr2)\n        m    = (_p1.mass+_p2.mass)\n        semi = 1.0/(2.0/dr - dv2/(_G*m))\n\n        dr_semi = 1.0 - dr/semi\n        ecc = np.sqrt(dr_semi*dr_semi + rvdot*rvdot/(_G*m*semi))\n\n        self.rrel = dr\n        self.semi = semi\n        self.ecc  = ecc\n\n    def particleToBinary(self, _p1, _p2, _G):\n        \"\"\" Calculate binary orbit from particle pairs\n\n        Parameters\n        ----------\n        _p1, _p2: inherited SimpleParticle\n            Particle pair data set\n        _G: float\n            Gravitational constant\n\n        \"\"\"\n        binary=self.__dict__\n     \n        def regular_sign(_a,_a_err):\n            _a[(_a<0) & (_a>-_a_err)] *= -1\n     \n        f_err = 1e-2\n        calculateParticleCMDict(binary, _p1, _p2)\n\n        binary['m1'] = _p1.mass\n        binary['m2'] = _p2.mass\n        m_tot = binary['mass']\n        Gm_tot = _G*m_tot\n        \n        dx = _p1.pos-_p2.pos\n        dv = _p1.vel-_p2.vel\n        dr2  = vecDot(dx,dx)\n        dv2  = vecDot(dv,dv)\n        rvdot= vecDot(dx,dv)\n        dr   = np.sqrt(dr2)\n        binary['rrel'] = np.sqrt(dr2)\n     \n        inv_dr = 1.0 / binary['rrel']\n        binary['semi'] = 1.0 / (2.0*inv_dr - dv2 / Gm_tot)\n        binary['am'] = np.array(list(map(lambda x,y:np.cross(x,y),dx,dv)))\n        dp = np.array(list(map(lambda m1,x1,m2,x2:m1*x1-m2*x2,_p1.mass,_p1.vel,_p2.mass,_p2.vel)))\n        binary['L'] = np.array(list(map(lambda x,y:np.cross(x,y),dx,dp)))\n        binary['eccvec'] = np.array(list(map(lambda v,am,gm,dx,dr:np.cross(v,am)/gm-dx/dr,dv,binary['am'],Gm_tot,dx,dr)))\n     \n        binary['incline'] = np.arctan2(np.sqrt(binary['am'][:,0]*binary['am'][:,0]+binary['am'][:,1]*binary['am'][:,1]),binary['am'][:,2])\n        binary['rot_horizon'] = np.arctan2(binary['am'][:,0],-binary['am'][:,1])\n        regular_sign(binary['am'][:,0],f_err)\n        regular_sign(binary['am'][:,1],f_err)\n        #binary['rot_horizon'][binary['rot_horizon']<0] += np.pi\n        binary['rot_horizon'][binary['am'][:,1]==0.0]=0.0\n     \n        cosOMG = np.cos(binary['rot_horizon'])\n        sinOMG = np.sin(binary['rot_horizon'])\n        cosinc = np.cos(binary['incline'])\n        sininc = np.sin(binary['incline'])\n     \n        pos_bar_x =   dx[:,0]*cosOMG + dx[:,1]*sinOMG\n        pos_bar_y = (-dx[:,0]*sinOMG + dx[:,1]*cosOMG)*cosinc + dx[:,2]*sininc\n        pos_bar_z = 0.0\n        vel_bar_x =   dv[:,0]*cosOMG + dv[:,1]*sinOMG\n        vel_bar_y = (-dv[:,0]*sinOMG + dv[:,1]*cosOMG)*cosinc + dv[:,2]*sininc\n        vel_bar_z = 0.0\n     \n        h = np.array(list(map(lambda x:np.sqrt(np.inner(x,x)),binary['am'])))\n        ecccosomg =  h/Gm_tot*vel_bar_y - pos_bar_x*inv_dr\n        eccsinomg = -h/Gm_tot*vel_bar_x - pos_bar_y*inv_dr\n        binary['ecc'] = np.sqrt( ecccosomg*ecccosomg + eccsinomg*eccsinomg )\n        regular_sign(ecccosomg,f_err)\n        regular_sign(eccsinomg,f_err)\n        binary['rot_self'] = np.arctan2(eccsinomg,ecccosomg)\n        #binary['rot_self'][binary['rot_self']<-np.pi+1e-5] += 2*np.pi \n        #binary['rot_self'][binary['rot_self']>=np.pi-1e-5] -= 2*np.pi\n     \n        regular_sign(pos_bar_y,f_err)\n        regular_sign(pos_bar_x,f_err)\n        phi = np.arctan2(pos_bar_y, pos_bar_x)\n        #phi[phi<-np.pi+1e-5] += 2*np.pi\n        #phi[phi>=np.pi-1e-5] -= 2*np.pi\n     \n        f = phi - binary['rot_self']\n        binary['ecca'] = np.arctan(np.sin(f)*np.sqrt(np.abs(binary['ecc']*binary['ecc'] - 1.0))/(binary['ecc']+np.cos(f)))\n        n = np.sqrt(Gm_tot/np.abs(binary['semi']*binary['semi']*binary['semi']))\n        binary['period'] = 8.0*np.arctan(1.0)/n\n        l = binary['ecca'] - binary['ecc']*np.sin(binary['ecca'])\n        binary['t_peri'] = l / n\n\ndef findPair(_dat, _G, _rmax, use_kdtree=False, simple_binary=True):\n    \"\"\"  Find binaries in a particle data set\n    The scipy.spatial.cKDTree is used to find pairs\n\n    Parameters\n    ----------\n    _dat: inhermited SimpleParticle\n        Particle data set\n    _G: float\n        Gravitational constant\n    _rmax: float\n        Maximum binary separation\n    use_kdtree: bool (False)\n        If True, use KDtree to find all binaries (slow); otherwise use information from PeTar, only hard binaries are detected (fast)\n    simple_binary: bool (True)\n        If True, only calculate semi and ecc (fast); otherwise calculating all binary parameters (slow)\n\n    Return\n    ----------\n    kdt: KDtree structure if use_kdtree=True\n    single: type of _dat\n        single particle data set\n    binary: Binary(simple_mode=simple_binary, member_particle_type=type(single), G=_G)\n        binary data set\n    \"\"\"\n    if (not issubclass(type(_dat), SimpleParticle)):\n        raise ValueError(\"Data type wrong\",type(_dat),\" should be subclass of \", SimpleParticle)\n\n    if (use_kdtree):\n        # create KDTree\n        #print('create KDTree')\n        kdt=sp.cKDTree(_dat.pos)\n     \n        # find all close pairs\n        #pairs=kdt.query_pairs(_rmax*AU2PC)\n            \n        # only check nearest index\n        #pair_index=np.unique(np.transpose(np.array([np.array([x[0],x[1]]) for x in pairs])),axis=0)\n         \n        # find pair index and distance\n        #print('Get index')\n        r,index=kdt.query(_dat.pos,k=2)\n        pair_index=np.transpose(np.unique(np.sort(index,axis=1),axis=0))\n        #pair_index = np.transpose(index)\n\n        #index = kdt.query_pairs(_rmax,output_type='ndarray')\n        #pair_index = np.transpose(index)\n     \n        # two members\n        p1 = _dat[pair_index[0]]\n        p2 = _dat[pair_index[1]]\n     \n        # check orbits\n        #print('Create binary')\n        binary = Binary(p1, p2, G=_G, simple_mode=simple_binary)\n        apo =binary.semi*(binary.ecc+1.0)\n     \n        bsel= ((binary.semi>0) & (apo<_rmax))\n        binary = binary[bsel]\n        \n        single_mask = np.ones(_dat.size).astype(bool)\n        single_mask[pair_index[0][bsel]]=False\n        single_mask[pair_index[1][bsel]]=False\n        single = _dat[single_mask]\n        return kdt, single, binary\n    else:\n        idx = _dat.status.argsort()\n        dat_sort = _dat[idx]\n        status, index, inverse, counts = np.unique(dat_sort.status, return_index=True, return_inverse=True, return_counts=True)\n        binary_i1 = index[counts==2]\n        binary_i2 = binary_i1+1\n        binary = Binary(dat_sort[binary_i1], dat_sort[binary_i2], _G)\n        single = dat_sort[index[-1]:]\n\n        return single, binary\n\n", "meta": {"hexsha": "e3c5625580a4cc96b14ec77953ec996f37f5c183", "size": 21925, "ext": "py", "lang": "Python", "max_stars_repo_path": "tools/analysis/data.py", "max_stars_repo_name": "rieder/PeTar", "max_stars_repo_head_hexsha": "922e4ea64458b3f6c6797f964fcf9543f5c14ee5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tools/analysis/data.py", "max_issues_repo_name": "rieder/PeTar", "max_issues_repo_head_hexsha": "922e4ea64458b3f6c6797f964fcf9543f5c14ee5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/analysis/data.py", "max_forks_repo_name": "rieder/PeTar", "max_forks_repo_head_hexsha": "922e4ea64458b3f6c6797f964fcf9543f5c14ee5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.8286778399, "max_line_length": 282, "alphanum_fraction": 0.563968073, "include": true, "reason": "from scipy", "num_tokens": 6183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.29098086621490676, "lm_q1q2_score": 0.1624624724428726}}
{"text": "\"\"\"\nModule for alignment of variants to the wild type sequence.\n\nThis module is optional, and using it will dramatically increase runtime when\ncounting variants. It is only recommended for users who need to count\ninsertion and deletion variants (i.e. not coding sequences).\n\"\"\"\n\nimport numpy as np\n\n#: Default similarity matrix used by the aligner.\n#: User-defined matrices must have this format.\n_simple_similarity = {\n    \"A\": {\"A\": 1, \"C\": -1, \"G\": -1, \"T\": -1, \"N\": 0, \"X\": 0},\n    \"C\": {\"A\": -1, \"C\": 1, \"G\": -1, \"T\": -1, \"N\": 0, \"X\": 0},\n    \"G\": {\"A\": -1, \"C\": -1, \"G\": 1, \"T\": -1, \"N\": 0, \"X\": 0},\n    \"T\": {\"A\": -1, \"C\": -1, \"G\": -1, \"T\": 1, \"N\": 0, \"X\": 0},\n    \"N\": {\"A\": 0, \"C\": 0, \"G\": 0, \"T\": 0, \"N\": 0, \"X\": 0},\n    \"X\": {\"A\": 0, \"C\": 0, \"G\": 0, \"T\": 0, \"N\": 0, \"X\": 0},\n    \"gap\": -1,\n}\n\n\nclass Aligner(object):\n    \"\"\"\n    Class for performing local alignment of two DNA sequences.\n\n    This class implements `Needleman-Wunsch <http://en.wikipedia.org/wiki/\n    Needleman%E2%80%93Wunsch_algorithm>`_ local alignment.\n\n    The :py:class:`~aligner.Aligner` requires a scoring matrix when\n    created. The format is a nested dictionary, with a special ``'gap'`` entry\n    for the gap penalty (this value is used for both gap opening and gap\n    extension).\n\n    The ``'X'`` nucleotide is a special case for unresolvable mismatches in\n    :py:class:`~overlap.OverlapSeqLib` variant data.\n    \"\"\"\n\n    _MAT = 1  # match\n    _INS = 2  # insertion (with respect to wild type)\n    _DEL = 3  # deletion (with respect to wild type)\n    _END = 4  # end of traceback\n\n    def __init__(self, similarity=_simple_similarity):\n        similarity_keys = similarity.keys()\n        if \"gap\" in similarity_keys:\n            similarity_keys.remove(\"gap\")\n        for key in similarity_keys:\n            if not all(x in similarity[key] for x in similarity_keys) or len(\n                similarity[key]\n            ) != len(similarity_keys):\n                raise ValueError(\"Asymmetrical alignment scoring matrix\")\n\n        self.similarity = similarity\n        if \"gap\" not in self.similarity:\n            raise ValueError(\"No gap penalty in alignment scoring matrix.\")\n\n        self.matrix = None\n        self.seq1 = None\n        self.seq2 = None\n        self.calls = 0\n\n    def align(self, seq1, seq2):\n        \"\"\"\n        Aligns the two sequences, *seq1* and *seq2* and returns a list of\n        tuples describing the differences between the sequences.\n\n        The tuple format is ``(i, j, type, length)``, where ``i`` and ``j``\n        are the positions in *seq1* and *seq2*, respectively, and type is one\n        of ``\"match\"``, ``\"mismatch\"``, ``\"insertion\"``, or ``\"deletion\"``.\n        For indels, the ``length`` value is the number of bases inserted or\n        deleted with respect to *seq1* starting at ``i``.\n        \"\"\"\n        self.matrix = np.ndarray(\n            shape=(len(seq1) + 1, len(seq2) + 1),\n            dtype=np.dtype([(\"score\", np.int), (\"trace\", np.byte)]),\n        )\n        seq1 = seq1.upper()\n        seq2 = seq2.upper()\n\n        # build matrix of scores/traceback information\n        for i in xrange(len(seq1) + 1):\n            self.matrix[i, 0] = (self.similarity[\"gap\"] * i, Aligner._DEL)\n        for j in xrange(len(seq2) + 1):\n            self.matrix[0, j] = (self.similarity[\"gap\"] * j, Aligner._INS)\n        for i in xrange(1, len(seq1) + 1):\n            for j in xrange(1, len(seq2) + 1):\n                match = (\n                    self.matrix[i - 1, j - 1][\"score\"]\n                    + self.similarity[seq1[i - 1]][seq2[j - 1]],\n                    Aligner._MAT,\n                )\n                delete = (\n                    self.matrix[i - 1, j][\"score\"] + self.similarity[\"gap\"],\n                    Aligner._DEL,\n                )\n                insert = (\n                    self.matrix[i, j - 1][\"score\"] + self.similarity[\"gap\"],\n                    Aligner._INS,\n                )\n                self.matrix[i, j] = max(delete, insert, match, key=lambda x: x[0])\n        self.matrix[0, 0] = (0, Aligner._END)\n\n        # calculate alignment from the traceback\n        i = len(seq1)\n        j = len(seq2)\n        traceback = list()\n        while i > 0 or j > 0:\n            if self.matrix[i, j][\"trace\"] == Aligner._MAT:\n                if seq1[i - 1] == seq2[j - 1]:\n                    traceback.append((i - 1, j - 1, \"match\", None))\n                else:\n                    traceback.append((i - 1, j - 1, \"mismatch\", None))\n                i -= 1\n                j -= 1\n            elif self.matrix[i, j][\"trace\"] == Aligner._INS:\n                traceback.append((i - 1, j - 1, \"insertion\", 1))\n                j -= 1\n            elif self.matrix[i, j][\"trace\"] == Aligner._DEL:\n                traceback.append((i - 1, j - 1, \"deletion\", 1))\n                i -= 1\n            elif self.matrix[i, j][\"trace\"] == Aligner._END:\n                pass\n            else:\n                raise RuntimeError(\"Invalid value in alignment traceback.\")\n        traceback.reverse()\n\n        # combine indels\n        indel = None\n        traceback_combined = list()\n        for t in traceback:\n            if t[2] == \"insertion\" or t[2] == \"deletion\":\n                if indel is not None:\n                    if t[2] == indel[2]:\n                        indel[3] += t[3]\n                    else:\n                        raise RuntimeError(\n                            \"Aligner failed to combine indels. \" \"Check gap penalty.\"\n                        )\n                else:\n                    indel = list(t)\n            else:\n                if indel is not None:\n                    traceback_combined.append(tuple(indel))\n                    indel = None\n                traceback_combined.append(t)\n        if indel is not None:\n            traceback_combined.append(tuple(indel))\n\n        self.calls += 1\n        return traceback_combined\n", "meta": {"hexsha": "30a1f06f2443a42f66914a129a32fcecad4283e2", "size": 5891, "ext": "py", "lang": "Python", "max_stars_repo_path": "enrich2/aligner.py", "max_stars_repo_name": "FowlerLab/Enrich2", "max_stars_repo_head_hexsha": "9c9b9a7498e6adeb1ca09fc58b956d30c660f94c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2016-09-25T21:23:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T17:38:51.000Z", "max_issues_repo_path": "enrich2/aligner.py", "max_issues_repo_name": "FowlerLab/Enrich2", "max_issues_repo_head_hexsha": "9c9b9a7498e6adeb1ca09fc58b956d30c660f94c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 51, "max_issues_repo_issues_event_min_datetime": "2016-11-20T02:37:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T17:39:18.000Z", "max_forks_repo_path": "enrich2/aligner.py", "max_forks_repo_name": "FowlerLab/Enrich2", "max_forks_repo_head_hexsha": "9c9b9a7498e6adeb1ca09fc58b956d30c660f94c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2016-11-19T01:26:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-16T17:41:28.000Z", "avg_line_length": 38.5032679739, "max_line_length": 85, "alphanum_fraction": 0.5095909014, "include": true, "reason": "import numpy", "num_tokens": 1569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.16246246900997285}}
{"text": "#!/usr/bin/env python\n\nimport sys, os\nimport copy\nimport time\nimport numpy as np\nfrom skimage import measure as skmeasure\nimport waterlib as wl\nimport water_properties as wp\nfrom netCDF4 import Dataset\nimport parmed as pmd\nimport pytraj as pt\nfrom pymbar import mbar\n\n\nUsage=\"\"\"solute_water_structure topFile inBulk doReweight\n  Computes various properties of water in the hydration shell of a solute. This \n  is intended to be used with expanded-ensemble simulation inserting a molecule\n  into either bulk solution or at an interface. This requires that all configurations\n  be reweighted to the appropriate ensemble, which includes removing restraints\n  that keep the solute in a specific part of the interface. Two functions related\n  to that which computes the solvation free energy, etc. are provided to help with\n  this. For simulations in bulk, inBulk should be True to use the appropriate\n  reweighting calculation, while if inBulk is False it reweights for a solute at\n  an interface - if this is the case, you must have directories named Quad*\n  that restrain the solute to different quadrants on the surface. Must be run\n  from the directory containing either the four directories with simulations\n  at each quadrant restraint or the bulk simulation directory with a single \n  trajectory.\n  Inputs:\n    topFile - topology file associated with trajectories\n    inBulk - (default False) flag to say if simulation in bulk or at an interface\n    doReweight - (default True) flag for whether or not need to reweight (i.e. in\n                                expanded ensemble or not)\n  Outputs (all files, no returns):\n    \n\"\"\"\n\n\ndef getConfigWeightsSurf(kB=0.008314459848, T=298.15):\n  \"\"\"Computes and returns the configuration weights for simulations with a solute\n   at an interface.\n   Mostly replicates calcdGsolv in genetic_lib, but returns config weights in both\n   the fully coupled and decoupled states (also includes pV term - won't matter very\n   much for free energy differences, but maybe matters for weighting configurations, \n   even though also probably not too much).\n  \"\"\"\n  #First define directory structure, spring constants, etc.\n  simDirs = ['Quad_0.25X_0.25Y', 'Quad_0.25X_0.75Y', 'Quad_0.75X_0.25Y', 'Quad_0.75X_0.75Y']\n  kXY = [10.0, 10.0, 10.0, 10.0] #spring constant in kJ/mol*A^2\n  refX = [7.4550, 7.4550, 22.3650, 22.3650]\n  refY = [8.6083, 25.8249, 8.6083, 25.8249]\n  distRefX = [7.4550, 7.4550, 7.4550, 7.4550]\n  distRefY = [8.6083, 8.6083, 8.6083, 8.6083]\n  numStates = 19\n\n  #And some constants\n  kBT = kB*T\n  beta = 1.0 / kBT\n\n  #First make sure all the input arrays have the same dimensions\n  numSims = len(simDirs)\n  allLens = np.array([len(a) for a in [kXY, refX, refY, distRefX, distRefY]])\n\n  #Want to loop over all trajectories provided, storing solute position information to calculate restraints\n  xyPos = None #X and Y coordinates of first heavy atom for all solutes - get shape later\n  nSamps = np.zeros((len(simDirs), numStates), dtype=int) #Have as many x-y restraints as sims and same number of lambda states for each \n  allPots = np.array([[]]*numStates).T #Potential energies, EXCLUDING RESTRAINT, for each simulation frame and lambda state\n                                       #Will also include pV term because may matter for configurations\n  xyBox = np.zeros(2)\n\n  for i, adir in enumerate(simDirs):\n\n    topFile = \"%s/../sol_surf.top\"%adir\n    trajFile = \"%s/prod.nc\"%adir\n    alchemicalFile = \"%s/alchemical_output.txt\"%adir\n\n    #First load in topology and get atom indices \n    top = pmd.load_file(topFile)\n\n    #Get solute heavy atoms for each solute\n    #Also get indices of surface atoms to use as references later\n    #Only taking last united atoms of first SAM molecule we find\n    heavyIndices = []\n    for res in top.residues:\n      if res.name not in ['OTM', 'CTM', 'STM', 'NTM', 'SOL']: #Assumes working with SAM surface...\n        thisheavyinds = []\n        for atom in res.atoms:\n          if not atom.name[0] == 'H':\n            thisheavyinds.append(atom.idx)\n        heavyIndices.append(thisheavyinds)\n\n    #Make into arrays for easier referencing\n    heavyIndices = np.array(heavyIndices)\n\n    #Load in the potential energies, INCLUDING RESTRAINT, at all states for this simulation to figure out frames to skip\n    alcDat = np.loadtxt(alchemicalFile)\n    startTime = alcDat[0, 1]\n    startFrame = int(startTime) - 1 #Be careful here... need write frequency in alchemical file to match exactly with positions\n                                    #AND assuming that have written in 1 ps increments... \n                                    #Also, first frame in trajectory is NOT at time zero, so subtract 1\n    thisPot = alcDat[:, 3:-1]\n    thispV = alcDat[:, -1]\n\n    #Next load in the trajectory and get all solute coordinates that matter\n    top.rb_torsions = pmd.TrackedList([])\n    top = pt.load_parmed(top, traj=False)\n    traj = pt.iterload(trajFile, top, frame_slice=(startFrame, -1))\n    nFrames = len(traj)\n    xyBox = np.array(traj[0].box.values)[:2] #A little lazy, but all boxes should be same and fixed in X and Y dimensions\n\n    thisxyPos = np.zeros((nFrames, len(heavyIndices), 2))\n    thisnSamps = np.zeros(numStates, dtype=int)\n\n    #Reference x and y coordinates for this restraint\n    thisRefXY = np.array([refX[i], refY[i]])\n\n    for j, frame in enumerate(traj):\n\n      thisPos = np.array(frame.xyz)\n      thisXY = thisPos[heavyIndices[:,0]][:, :2] #Takes XY coords for first heavy atom from each solute\n      thisxyPos[j,:] = thisXY \n      thisnSamps[int(alcDat[j, 2])] += 1 #Lambda states must be indexed starting at 0\n\n      #Also get wrapped positions relative to each reference face\n      #AND calculate xy restraint energy to remove by adding this for each solute\n      xyEnergy = 0.0\n      for k in range(len(heavyIndices)):\n        xy = thisXY[k]\n        #Then separately reimage around the restraint reference positions to calculate energy\n        xy = wl.reimage([xy], thisRefXY, xyBox)[0] - thisRefXY\n        xyEnergy += (  0.5*kXY[i]*(0.5*(np.sign(xy[0] - distRefX[i]) + 1))*((xy[0] - distRefX[i])**2)\n                     + 0.5*kXY[i]*(0.5*(np.sign(xy[1] - distRefY[i]) + 1))*((xy[1] - distRefY[i])**2) )\n\n      #Remove the restraint energy (only for x-y restraint... z is the same in all simulations)\n      thisPot[j,:] -= (xyEnergy / kBT)\n\n      #And also add in pV contribution\n      thisPot[j,:] += thispV[j]\n\n    #Add to other things we're keeping track of\n    if xyPos is None:\n      xyPos = copy.deepcopy(thisxyPos)\n    else:\n      xyPos = np.vstack((xyPos, thisxyPos))\n    nSamps[i,:] = thisnSamps\n    allPots = np.vstack((allPots, thisPot))\n\n  #Now should have all the information we need\n  #Next, put it into the format that MBAR wants, adding energies as needed\n  Ukn = np.zeros((len(simDirs)*numStates, int(np.sum(nSamps))))\n\n  for i in range(len(simDirs)):\n\n    #First get energy of ith type of x-y restraint for all x-y positions\n    thisRefXY = np.array([refX[i], refY[i]])\n    #Must do by looping over each solute\n    xyEnergy = np.zeros(xyPos.shape[0])\n    for k in range(len(heavyIndices)):\n      xy = wl.reimage(xyPos[:,k,:], thisRefXY, xyBox) - thisRefXY\n      xyEnergy += (  0.5*kXY[i]*(0.5*(np.sign(xy[:,0] - distRefX[i]) + 1))*((xy[:,0] - distRefX[i])**2)\n                   + 0.5*kXY[i]*(0.5*(np.sign(xy[:,1] - distRefY[i]) + 1))*((xy[:,1] - distRefY[i])**2) )\n\n    #Loop over alchemical states with this restraint and add energy\n    for j in range(numStates):\n    \n      Ukn[i*numStates+j, :] = allPots[:,j] + (xyEnergy / kBT)\n  \n  #Now should be set to run MBAR\n  mbarObj = mbar.MBAR(Ukn, nSamps.flatten())\n\n  #Following computePMF in MBAR to get configuration weights with desired potential of interest\n  logwCoupled = mbarObj._computeUnnormalizedLogWeights(allPots[:,0])\n  logwDecoupled = mbarObj._computeUnnormalizedLogWeights(allPots[:,-1])\n\n  #Also report average solute-system LJ and coulombic potential energies in the fully coupled ensemble\n  #(with restraints removed)\n  #Just printing these values\n  avgQ, stdQ = mbarObj.computeExpectations(allPots[:,0] - allPots[:,4], allPots[:,0])\n  avgLJ, stdLJ = mbarObj.computeExpectations(allPots[:,4] - allPots[:,-1], allPots[:,0])\n  print(\"\\nAverage solute-system electrostatic potential energy: %f +/- %f\"%(avgQ, stdQ))\n  print(\"Average solute-system LJ potential energy: %f +/- %f\\n\"%(avgLJ, stdLJ))\n\n  #Also print information that can be used to break free energy into components\n  #Start by just printing all of the free energies between states\n  alldGs, alldGerr = mbarObj.computePerturbedFreeEnergies(allPots.T)\n  print(\"\\nAll free energies relative to first (coupled) state:\")\n  print(alldGs.tolist())\n  print(alldGerr.tolist())\n  #And the free energy changes associated with just turning on LJ and elctrostatics separately\n  dGq = alldGs[0][0] - alldGs[0][4]\n  dGqErr = np.sqrt((alldGerr[0][0]**2) + (alldGerr[0][4])**2)\n  print(\"\\nElectrostatic dG (with LJ on): %f +/- %f\"%(dGq, dGqErr))\n  dGlj = alldGs[4][4] - alldGs[4][-1]\n  dGljErr = np.sqrt((alldGerr[4][4]**2) + (alldGerr[4][-1])**2)\n  print(\"\\nLJ dG (no charges): %f +/- %f\"%(dGlj, dGljErr))\n  #Now calculate average potential energy differences needed for computing relative entropies\n  dUq, dUqErr = mbarObj.computeExpectations(allPots[:,0] - allPots[:,4], allPots[:,0])\n  print(\"\\nAverage electrostatic potential energy in fully coupled state: %f +/- %f\"%(dUq, dUqErr))\n  dUlj, dUljErr = mbarObj.computeExpectations(allPots[:,4] - allPots[:,-1], allPots[:,4])\n  print(\"\\nAverage LJ potential energy (no charges) in uncharged state: %f +/- %f\"%(dUlj, dUljErr))\n\n  #And return weights after exponentiating log weights and normalizing\n  wCoupled = np.exp(logwCoupled)\n  wCoupled /= np.sum(wCoupled)\n  wDecoupled = np.exp(logwDecoupled)\n  wDecoupled /= np.sum(wDecoupled)\n\n  return wCoupled, wDecoupled\n\n\ndef getConfigWeightsBulk(alchfile='alchemical_output.txt', kB=0.008314459848, T=298.15):\n  \"\"\"Given an alchemical output file, computes and returns configuration weights in\n   both the fully coupled and decoupled ensembles of the solute.\n  \"\"\"\n  rawdat = np.loadtxt(alchfile)\n  lstates = rawdat[:,2]\n  Ukn = rawdat[:,3:-1] \n  pV = rawdat[:,-1] #pV term is in last column\n  #pV term doesn't matter for free energy differences\n  #But does matter for configuration weights (even though it's a small contribution)\n\n  Nsamps = np.zeros(Ukn.shape[1], dtype=int)\n\n  for i in range(Ukn.shape[1]):\n    Nsamps[i] = int(np.sum((lstates==i)))\n    Ukn[:,i] += pV\n\n  #neworder = np.argsort(lstates)\n  #Ukn = Ukn[neworder]\n\n  Ukn /= (kB*T)\n\n  mbarObj = mbar.MBAR(Ukn.T, Nsamps)\n\n  #Following computePMF in MBAR to get configuration weights with desired potential of interest\n  logwCoupled = mbarObj._computeUnnormalizedLogWeights(Ukn[:,0])\n  logwDecoupled = mbarObj._computeUnnormalizedLogWeights(Ukn[:,-1])\n\n  #Also report average solute-system LJ and coulombic potential energies in the fully coupled ensemble\n  #(with restraints removed)\n  #Just printing these values\n  avgQ, stdQ = mbarObj.computeExpectations(Ukn[:,0] - Ukn[:,4], Ukn[:,0])\n  avgLJ, stdLJ = mbarObj.computeExpectations(Ukn[:,4] - Ukn[:,-1], Ukn[:,0])\n  print(\"\\nAverage solute-water electrostatic potential energy: %f +/- %f\"%(avgQ, stdQ))\n  print(\"Average solute-water LJ potential energy: %f +/- %f\\n\"%(avgLJ, stdLJ))\n\n  #Also print information that can be used to break free energy into components\n  #Start by just printing all of the free energies between states\n  alldGs, alldGerr = mbarObj.computePerturbedFreeEnergies(Ukn.T)\n  print(\"\\nAll free energies relative to first (coupled) state:\")\n  print(alldGs.tolist())\n  print(alldGerr.tolist())\n  #And the free energy changes associated with just turning on LJ and elctrostatics separately\n  dGq = alldGs[0][0] - alldGs[0][4]\n  dGqErr = np.sqrt((alldGerr[0][0]**2) + (alldGerr[0][4])**2)\n  print(\"\\nElectrostatic dG (with LJ on): %f +/- %f\"%(dGq, dGqErr))\n  dGlj = alldGs[4][4] - alldGs[4][-1]\n  dGljErr = np.sqrt((alldGerr[4][4]**2) + (alldGerr[4][-1])**2)\n  print(\"\\nLJ dG (no charges): %f +/- %f\"%(dGlj, dGljErr))\n  #Now calculate average potential energy differences needed for computing relative entropies\n  dUq, dUqErr = mbarObj.computeExpectations(Ukn[:,0] - Ukn[:,4], Ukn[:,0])\n  print(\"\\nAverage electrostatic potential energy in fully coupled state: %f +/- %f\"%(dUq, dUqErr))\n  dUlj, dUljErr = mbarObj.computeExpectations(Ukn[:,4] - Ukn[:,-1], Ukn[:,4])\n  print(\"\\nAverage LJ potential energy (no charges) in uncharged state: %f +/- %f\"%(dUlj, dUljErr))\n\n  #And return weights after exponentiating log weights\n  wCoupled = np.exp(logwCoupled)\n  wCoupled /= np.sum(wCoupled)\n  wDecoupled = np.exp(logwDecoupled)\n  wDecoupled /= np.sum(wDecoupled)\n\n  return wCoupled, wDecoupled\n\n\ndef main(args):\n\n  print time.ctime(time.time())\n\n  #Get topology file we're working with\n  topFile = args[0]\n\n  #And figure out if we're dealing with solute at surface or in bulk\n  if (args[1] == 'True'):\n    inBulk = True\n  else:\n    inBulk = False\n\n  if (args[2] == 'True'):\n    doReweight = True\n  else:\n    doReweight = False\n\n  #Read in topology file now to get information on solute atoms\n  top = pmd.load_file(topFile)\n  soluteInds = []\n  for res in top.residues:\n    if res.name not in ['OTM', 'CTM', 'STM', 'NTM', 'SOL']:\n      for atom in res.atoms:\n        soluteInds.append(atom.idx)\n\n  #Now define how we compute three-body angles with bins and cut-off\n  #Shell cut-off\n  shellCut = 3.32 #1st minimum distance for TIP4P-Ew water at 298.15 K and 1 bar\n  #Number of angle bins\n  nAngBins = 100 #500\n  #Define bin centers (should be nBins equally spaced between 0 and 180)\n  angBinCents = 0.5 * (np.arange(0.0, 180.001, 180.0/nAngBins)[:-1] + np.arange(0.0, 180.001, 180.0/nAngBins)[1:])\n\n  #And distance bins for local oxygen-oxygen RDF calculation \n  #(really distance histograms from central oxygens - can normalize however we want, really)\n  distBinWidth = 0.05\n  nDistBins = int(shellCut / distBinWidth)\n  distBins = np.arange(0.0, nDistBins*distBinWidth+0.00001, distBinWidth)\n  distBinCents = 0.5 * (distBins[:-1] + distBins[1:])\n\n  #Define the size of the probes used for assessing density fluctuations near solute\n  probeRadius = 3.3 # radius in Angstroms; the DIAMETER of a methane so assumes other atoms methane-sized\n\n  #And bins for numbers of waters in probes\n  probeBins = np.arange(0.0, 21.00001, 1.0)\n  nProbeBins = len(probeBins) - 1 #Will use np.histogram, which includes left edge in bin (so if want up to 20, go to 21)\n\n  #And will record number waters in each solvation shell (histograms of)\n  shellBins = np.arange(0.0, 251.00001, 1.0) #probably way too many bins, but don't want to run out\n  nShellBins = len(shellBins) - 1\n\n  #Should we do 2D histogram for angles and distances?\n  #Or also do 2D histogram for number of waters in probe and three-body angle?\n  #Interesting if make probe radius same size as three-body angle cutoff?\n\n  #Finally, also define the bins for computing RDFs of waters near all solute atoms\n  #Will use to define 1st and 2nd solvation shells\n  rdfBinWidth = 0.2\n  rdfMax = 12.00\n  rdfBins = np.arange(0.0, rdfMax+0.000001, rdfBinWidth)\n  rdfBinCents = 0.5 * (rdfBins[:-1] + rdfBins[1:])\n  nRDFBins = len(rdfBinCents)\n  rdfBinVols = (4.0*np.pi/3.0)*(rdfBins[1:]**3 - rdfBins[:-1]**3)\n  bulkDens = 0.0332 #Roughly right for TIP4P-EW at 298.15 K and 1 bar in inverse Angstroms cubed\n\n  #Need to create a variety of arrays to hold the data we're interested in\n  #Will record distributions in both 1st and 2nd solvation shells\n  shellCountsCoupled = np.zeros((nShellBins, 2)) #Histograms for numbers of waters in hydration shells of solutes\n  probeHistsCoupled = np.zeros((nProbeBins, 2)) #Histograms for numbers waters in probes in 1st and 2nd hydration shells \n  angHistsCoupled = np.zeros((nAngBins, 2)) #Histograms of three-body angles for water oxygens within solvation shells\n  distHistsCoupled = np.zeros((nDistBins, 2)) #Histograms of distances to water oxygens from central oxygens\n  solRDFsCoupled = np.zeros((nRDFBins, len(soluteInds))) #RDFs between each solute atom and water oxygens\n  shellCountsDecoupled = np.zeros((nShellBins, 2)) #Same as above, but decoupled state, not coupled state \n  probeHistsDecoupled = np.zeros((nProbeBins, 2)) \n  angHistsDecoupled = np.zeros((nAngBins, 2)) \n  distHistsDecoupled = np.zeros((nDistBins, 2)) \n  solRDFsDecoupled = np.zeros((nRDFBins, len(soluteInds))) \n\n  #First need configuration weights to use in computing average quantities\n  #But only do if we're using a simuation with an expanded ensemble\n  if doReweight:\n    if inBulk:\n      weightsCoupled, weightsDecoupled = getConfigWeightsBulk(kB=1.0, T=1.0)\n      #Using 1 for kB and T because alchemical_output.txt should already have potential energies in kBT\n      simDirs = ['.']\n    else:\n      weightsCoupled, weightsDecoupled = getConfigWeightsSurf()\n      simDirs = ['Quad_0.25X_0.25Y', 'Quad_0.25X_0.75Y', 'Quad_0.75X_0.25Y', 'Quad_0.75X_0.75Y']\n  else:\n    weightsCoupled = np.array([])\n    weightsDecoupled = np.array([])\n    simDirs = ['.']\n\n  #To correctly match weights up to configurations, need to count frames from all trajectories\n  countFrames = 0\n\n  #Next, want to loop over all trajectories and compute RDFs from solute atoms to water oxygens\n  #Will use this to define solvation shells for finding other properties\n  #Actually, having looked at RDFs, just use 5.5 for first shell and 8.5 for second shell...\n  #AND use all atoms, including hydrogens, which have LJ interactions in GAFF2, to define shells\n  #Actually now only using heavy atoms... but when look at RDFs, examine all atoms \n  for adir in simDirs:\n\n    if doReweight:\n      #Before loading trajectory, figure out how many frames to exclude due to weight equilibration\n      alcDat = np.loadtxt(adir+'/alchemical_output.txt')\n      startTime = alcDat[0, 1]\n      startFrame = int(startTime) - 1\n    else:\n      startFrame = 0\n \n    top = pmd.load_file(topFile)\n    top.rb_torsions = pmd.TrackedList([]) #This is just for SAM systems so that it doesn't break pytraj\n    top = pt.load_parmed(top, traj=False)\n    traj = pt.iterload(adir+'/prod.nc', top, frame_slice=(startFrame, -1))\n\n    if not doReweight:\n      weightsCoupled = np.hstack((weightsCoupled, np.ones(len(traj))))\n      weightsDecoupled = np.hstack((weightsDecoupled, np.ones(len(traj))))\n  \n    print(\"\\nTopology and trajectory loaded from directory %s\" % adir)\n\n    owInds = top.select('@OW')\n    soluteInds = top.select('!(:OTM,CTM,STM,NTM,SOL)')\n\n    print(\"\\n\\tFound %i water oxygens\" % len(owInds))\n    print(\"\\tFound %i solute atoms\" % len(soluteInds))\n\n    for i, frame in enumerate(traj):\n      \n      if i%1000 == 0:\n        print \"On frame %i\" % i\n    \n      boxDims = np.array(frame.box.values[:3])\n\n      currCoords = np.array(frame.xyz)\n\n      #Wrap based on soluate atom center of geometry and get coordinates of interest\n      wrapCOM = np.average(currCoords[soluteInds], axis=0)\n      currCoords = wl.reimage(currCoords, wrapCOM, boxDims) - wrapCOM\n      owCoords = currCoords[owInds]\n      solCoords = currCoords[soluteInds]\n\n      #Loop over solute atoms and find pair-distance histograms with water oxygens\n      for j, acoord in enumerate(solCoords):\n        solRDFsCoupled[:,j] += (weightsCoupled[countFrames+i]\n                                * wl.pairdistancehistogram(np.array([acoord]), owCoords, rdfBinWidth, nRDFBins, boxDims))\n        solRDFsDecoupled[:,j] += (weightsDecoupled[countFrames+i]\n                                  * wl.pairdistancehistogram(np.array([acoord]), owCoords, rdfBinWidth, nRDFBins, boxDims))\n        #Note that pairdistancehistogram is right-edge inclusive, NOT left-edge inclusive\n        #In practice, not a big difference\n\n    countFrames += len(traj)\n\n  #Finish by normalizing RDFs properly\n  for j in range(len(soluteInds)):\n    solRDFsCoupled[:,j] /= rdfBinVols #bulkDens*rdfBinVols\n    solRDFsDecoupled[:,j] /= rdfBinVols #bulkDens*rdfBinVols\n  if not doReweight:\n    solRDFsCoupled /= float(countFrames)\n    solRDFsDecoupled /= float(countFrames)\n\n  #And save to file\n  np.savetxt('solute-OW_RDFs_coupled.txt', np.hstack((np.array([rdfBinCents]).T, solRDFsCoupled)), \n             header='RDF bins (A)    solute atom-OW RDF for solute atom indices %s'%(str(soluteInds)))\n  np.savetxt('solute-OW_RDFs_decoupled.txt', np.hstack((np.array([rdfBinCents]).T, solRDFsDecoupled)), \n             header='RDF bins (A)    solute atom-OW RDF for solute atom indices %s'%(str(soluteInds)))\n\n  print(\"\\tFound RDFs for water oxygens from solute indices.\")\n\n  solShell1Cut = 5.5 #Angstroms from all solute atoms (including hydrogens)\n  solShell2Cut = 8.5\n\n  #And now that we know how many frames, we can assign real weights if not reweighting\n  if not doReweight:\n    weightsCoupled /= float(countFrames)\n    weightsDecoupled /= float(countFrames)\n\n  #Reset countFrames so get weights right\n  countFrames = 0\n\n  #Repeat looping over trajectories to calculate water properties in solute solvation shell\n  for adir in simDirs:\n\n    if doReweight:\n      #Before loading trajectory, figure out how many frames to exclude due to weight equilibration\n      alcDat = np.loadtxt(adir+'/alchemical_output.txt')\n      startTime = alcDat[0, 1]\n      startFrame = int(startTime) - 1\n    else:\n      startFrame = 0\n \n    top = pmd.load_file(topFile)\n    top.rb_torsions = pmd.TrackedList([]) #This is just for SAM systems so that it doesn't break pytraj\n    top = pt.load_parmed(top, traj=False)\n    traj = pt.iterload(adir+'/prod.nc', top, frame_slice=(startFrame, -1))\n  \n    print(\"\\nTopology and trajectory loaded from directory %s\" % adir)\n\n    owInds = top.select('@OW')\n    soluteInds = top.select('!(:OTM,CTM,STM,NTM,SOL)&!(@H=)')\n    surfInds = top.select('(:OTM,CTM,STM,NTM)&!(@H=)') #For probe insertions, also include solute and surface heavy atoms\n\n    print(\"\\n\\tFound %i water oxygens\" % len(owInds))\n    print(\"\\tFound %i solute heavy atoms\" % len(soluteInds))\n    print(\"\\tFound %i non-hydrogen surface atoms\" % len(surfInds))\n\n    if len(surfInds) == 0:\n      surfInds.dtype=int\n\n    for i, frame in enumerate(traj):\n  \n      #if i%10 == 0:\n      #  print \"On frame %i\" % i\n    \n      boxDims = np.array(frame.box.values[:3])\n  \n      currCoords = np.array(frame.xyz)\n  \n      #Wrap based on soluate atom center of geometry and get coordinates of interest\n      wrapCOM = np.average(currCoords[soluteInds], axis=0)\n      currCoords = wl.reimage(currCoords, wrapCOM, boxDims) - wrapCOM\n      owCoords = currCoords[owInds]\n      solCoords = currCoords[soluteInds]\n      surfCoords = currCoords[surfInds]\n\n      #Now get solvent shells around solute\n      shell1BoolMat = wl.nearneighbors(solCoords, owCoords, boxDims, 0.0, solShell1Cut)\n      shell1Bool = np.array(np.sum(shell1BoolMat, axis=0), dtype=bool)\n\n      shell2BoolMat = wl.nearneighbors(solCoords, owCoords, boxDims, solShell1Cut, solShell2Cut)\n      shell2Bool = np.array(np.sum(shell2BoolMat, axis=0), dtype=bool)\n\n      #And add weight to histogram for numbers of waters in shells\n      thisCount1 = int(np.sum(shell1Bool))\n      shellCountsCoupled[thisCount1, 0] += weightsCoupled[countFrames+i]\n      shellCountsDecoupled[thisCount1, 0] += weightsDecoupled[countFrames+i]\n\n      thisCount2 = int(np.sum(shell2Bool))\n      shellCountsCoupled[thisCount2, 1] += weightsCoupled[countFrames+i]\n      shellCountsDecoupled[thisCount2, 1] += weightsDecoupled[countFrames+i]\n\n      #And compute water properties of solvent shells, first 3-body angles\n      thisAngs1, thisNumAngs1 = wp.getCosAngs(owCoords[shell1Bool], owCoords, boxDims, highCut=shellCut)\n      thisAngHist1, thisAngBins1 = np.histogram(thisAngs1, bins=nAngBins, range=[0.0, 180.0], density=False)\n      angHistsCoupled[:,0] += weightsCoupled[countFrames+i] * thisAngHist1\n      angHistsDecoupled[:,0] += weightsDecoupled[countFrames+i] * thisAngHist1\n\n      thisAngs2, thisNumAngs2 = wp.getCosAngs(owCoords[shell2Bool], owCoords, boxDims, highCut=shellCut)\n      thisAngHist2, thisAngBins2 = np.histogram(thisAngs2, bins=nAngBins, range=[0.0, 180.0], density=False)\n      angHistsCoupled[:,1] += weightsCoupled[countFrames+i] * thisAngHist2\n      angHistsDecoupled[:,1] += weightsDecoupled[countFrames+i] * thisAngHist2\n\n      #And ow-ow pair distance histograms in both shells as well\n      thisDistHist1 = wl.pairdistancehistogram(owCoords[shell1Bool], owCoords, distBinWidth, nDistBins, boxDims)\n      distHistsCoupled[:,0] += weightsCoupled[countFrames+i] * thisDistHist1\n      distHistsDecoupled[:,0] += weightsDecoupled[countFrames+i] * thisDistHist1\n\n      thisDistHist2 = wl.pairdistancehistogram(owCoords[shell2Bool], owCoords, distBinWidth, nDistBins, boxDims)\n      distHistsCoupled[:,1] += weightsCoupled[countFrames+i] * thisDistHist2\n      distHistsDecoupled[:,1] += weightsDecoupled[countFrames+i] * thisDistHist2\n\n      #Next compute distributions of numbers of waters in probes centered within each shell\n      #To do this, create random grid of points in SQUARE that encompasses both shells\n      #Then only keep points within each shell based on distance\n      #Square will be based on shell cutoffs and min and max coordinates in each dimension of solute\n      minSolX = np.min(solCoords[:,0]) - solShell2Cut\n      maxSolX = np.max(solCoords[:,0]) + solShell2Cut\n      minSolY = np.min(solCoords[:,1]) - solShell2Cut\n      maxSolY = np.max(solCoords[:,1]) + solShell2Cut\n      minSolZ = np.min(solCoords[:,2]) - solShell2Cut\n      maxSolZ = np.max(solCoords[:,2]) + solShell2Cut\n      thisGridX = minSolX + np.random.random(500)*(maxSolX - minSolX)\n      thisGridY = minSolY + np.random.random(500)*(maxSolY - minSolY)\n      thisGridZ = minSolZ + np.random.random(500)*(maxSolZ - minSolZ)\n      thisGrid = np.vstack((thisGridX, thisGridY, thisGridZ)).T\n\n      gridBoolMat1 = wl.nearneighbors(solCoords, thisGrid, boxDims, 0.0, solShell1Cut)\n      gridBool1 = np.array(np.sum(gridBoolMat1, axis=0), dtype=bool)\n      thisNum1 = wl.probegrid(np.vstack((owCoords, surfCoords, solCoords)), thisGrid[gridBool1], probeRadius, boxDims)\n      thisProbeHist1, thisProbeBins1 = np.histogram(thisNum1, bins=probeBins, density=False)\n      probeHistsCoupled[:,0] += weightsCoupled[countFrames+i] * thisProbeHist1\n      probeHistsDecoupled[:,0] += weightsDecoupled[countFrames+i] * thisProbeHist1\n\n      gridBoolMat2 = wl.nearneighbors(solCoords, thisGrid, boxDims, solShell1Cut, solShell2Cut)\n      gridBool2 = np.array(np.sum(gridBoolMat2, axis=0), dtype=bool)\n      thisNum2 = wl.probegrid(np.vstack((owCoords, surfCoords, solCoords)), thisGrid[gridBool2], probeRadius, boxDims)\n      thisProbeHist2, thisProbeBins2 = np.histogram(thisNum2, bins=probeBins, density=False)\n      probeHistsCoupled[:,1] += weightsCoupled[countFrames+i] * thisProbeHist2\n      probeHistsDecoupled[:,1] += weightsDecoupled[countFrames+i] * thisProbeHist2\n\n    countFrames += len(traj)\n\n  #Should have everything we need, so save to text files\n  np.savetxt('solute_shell_hists.txt', \n             np.hstack((np.array([shellBins[:-1]]).T, shellCountsCoupled, shellCountsDecoupled)),\n             header='Histograms of numbers of waters in first and second solute solvation shells with solvent in coupled (columns 2, 3) and decoupled (columns 4, 5) states')\n  np.savetxt('solute_probe_hists.txt', \n             np.hstack((np.array([probeBins[:-1]]).T, probeHistsCoupled, probeHistsDecoupled)),\n             header='Number waters in probe histograms in first and second solute solvation shells with solvent in coupled (columns 2, 3) and decoupled (columns 4, 5) states')\n  np.savetxt('solute_ang_hists.txt', \n             np.hstack((np.array([angBinCents]).T, angHistsCoupled, angHistsDecoupled)),\n             header='3-body angle histograms in first and second solute solvation shells with solvent in coupled (columns 2, 3) and decoupled (columns 4, 5) states')\n  np.savetxt('solute_pair_hists.txt', \n             np.hstack((np.array([distBinCents]).T, distHistsCoupled, distHistsDecoupled)),\n             header='O-O pair-distance histograms in first and second solute solvation shells with solvent in coupled (columns 2, 3) and decoupled (columns 4, 5) states')\n\n  print time.ctime(time.time())\n \n\nif __name__ == \"__main__\":\n  main(sys.argv[1:])\n\n\n", "meta": {"hexsha": "bb8d2dbecf1460e157929f32e0219a9535f3ee4d", "size": 28278, "ext": "py", "lang": "Python", "max_stars_repo_path": "analysis_scripts/solute_water_structure.py", "max_stars_repo_name": "JIMonroe/Surface_Affinities_Optimization", "max_stars_repo_head_hexsha": "94853571c690b099362431aac32d26611134a009", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analysis_scripts/solute_water_structure.py", "max_issues_repo_name": "JIMonroe/Surface_Affinities_Optimization", "max_issues_repo_head_hexsha": "94853571c690b099362431aac32d26611134a009", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analysis_scripts/solute_water_structure.py", "max_forks_repo_name": "JIMonroe/Surface_Affinities_Optimization", "max_forks_repo_head_hexsha": "94853571c690b099362431aac32d26611134a009", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-07T11:52:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-07T11:52:27.000Z", "avg_line_length": 47.847715736, "max_line_length": 175, "alphanum_fraction": 0.699766603, "include": true, "reason": "import numpy", "num_tokens": 8352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.16243229087044808}}
{"text": "# base.py\n# Author: Jacob Schreiber <jmschreiber91@gmail.com> \n\n\"\"\"\nThis file contains code that implements the core of the submodular selection\nalgorithms.\n\"\"\"\n\nimport numpy\nfrom tqdm import tqdm\n\nfrom ..optimizers import BaseOptimizer\nfrom ..optimizers import NaiveGreedy\nfrom ..optimizers import LazyGreedy\nfrom ..optimizers import ApproximateLazyGreedy\nfrom ..optimizers import TwoStageGreedy\nfrom ..optimizers import StochasticGreedy\nfrom ..optimizers import BidirectionalGreedy\nfrom ..optimizers import GreeDi\nfrom ..optimizers import SieveGreedy\nfrom ..optimizers import OPTIMIZERS\n\nfrom ..utils import PriorityQueue\nfrom ..utils import check_random_state\nfrom ..utils import _calculate_pairwise_distances\n\nfrom scipy.sparse import csr_matrix\n\n\nclass BaseSelection(object):\n\t\"\"\"The base selection object.\n\n\tThis object defines the structures that all submodular selection algorithms\n\tshould follow. All algorithms will have the same public methods and the\n\tsame attributes.\n\n\tParameters\n\t----------\n\tn_samples : int\n\t\tThe number of samples to return.\n\n\tinitial_subset : list, numpy.ndarray or None, optional\n\t\tIf provided, this should be a list of indices into the data matrix\n\t\tto use as the initial subset, or a group of examples that may not be\n\t\tin the provided data should beused as the initial subset. If indices, \n\t\tthe provided array should be one-dimensional. If a group of examples,\n\t\tthe data should be 2 dimensional.\n\n\toptimizer : string or optimizers.BaseOptimizer, optional\n\t\tThe optimization approach to use for the selection. Default is\n\t\t'two-stage', which makes selections using the naive greedy algorithm\n\t\tinitially and then switches to the lazy greedy algorithm. Must be\n\t\tone of\n\n\t\t\t'naive' : the naive greedy algorithm\n\t\t\t'lazy' : the lazy (or accelerated) greedy algorithm\n\t\t\t'approximate-lazy' : the approximate lazy greedy algorithm\n\t\t\t'two-stage' : starts with naive and switches to lazy\n\t\t\t'stochastic' : the stochastic greedy algorithm\n\t\t\t'greedi' : the GreeDi distributed algorithm\n\t\t\t'bidirectional' : the bidirectional greedy algorithm\n\n\t\tDefault is 'naive'.\n\n\toptimizer_kwds : dict or None\n\t\tA dictionary of arguments to pass into the optimizer object. The keys\n\t\tof this dictionary should be the names of the parameters in the optimizer\n\t\tand the values in the dictionary should be the values that these\n\t\tparameters take. Default is None.\n\n\treservoir : numpy.ndarray or None\n\t\tThe reservoir to use when calculating gains in the sieve greedy\n\t\tstreaming optimization algorithm in the `partial_fit` method.\n\t\tCurrently only used for graph-based functions. If a numpy array\n\t\tis passed in, it will be used as the reservoir. If None is passed in,\n\t\twill use reservoir sampling to collect a reservoir. Default is None.\n\n\tmax_reservoir_size : int \n\t\tThe maximum size that the reservoir can take. If a reservoir is passed\n\t\tin, this value is set to the size of that array. Default is 1000.\n\n\tn_jobs : int\n\t\tThe number of threads to use when performing computation in parallel.\n\t\tCurrently, this parameter is exposed but does not actually do anything.\n\t\tThis will be fixed soon.\n\n\trandom_state : int or RandomState or None, optional\n\t\tThe random seed to use for the random selection process. Only used\n\t\tfor stochastic greedy.\n\n\tverbose : bool\n\t\tWhether to print output during the selection process.\n\n\tAttributes\n\t----------\n\tn_samples : int\n\t\tThe number of samples to select.\n\n\tranking : numpy.array int\n\t\tThe selected samples in the order of their gain with the first number in\n\t\tthe ranking corresponding to the index of the first sample that was\n\t\tselected by the greedy procedure.\n\n\tgains : numpy.array float\n\t\tThe gain of each sample in the returned set when it was added to the\n\t\tgrowing subset. The first number corresponds to the gain of the first\n\t\tadded sample, the second corresponds to the gain of the second added\n\t\tsample, and so forth.\n\t\"\"\"\n\n\tdef __init__(self, n_samples, initial_subset=None, optimizer='lazy', \n\t\toptimizer_kwds={}, reservoir=None, max_reservoir_size=1000, \n\t\tn_jobs=1, random_state=None, verbose=False):\n\t\tif n_samples <= 0:\n\t\t\traise ValueError(\"n_samples must be a positive value.\")\n\n\t\tif not isinstance(initial_subset, (list, numpy.ndarray)) and initial_subset is not None: \n\t\t\traise ValueError(\"initial_subset must be a list, numpy array, or None\")\n\t\tif isinstance(initial_subset, (list, numpy.ndarray)):\n\t\t\tinitial_subset = numpy.array(initial_subset)\n\n\t\tif not isinstance(optimizer, BaseOptimizer):\n\t\t\tif optimizer not in OPTIMIZERS.keys():\n\t\t\t\traise ValueError(\"Optimizer must be an optimizer object or \" \\\n\t\t\t\t\t\"a str in {}.\".format(str(OPTIMIZERS.keys())))\n\n\t\tif isinstance(optimizer, BaseOptimizer):\n\t\t\toptimizer.function = self\n\n\t\tif verbose not in (True, False):\n\t\t\traise ValueError(\"verbosity must be True or False\")\n\n\t\tself.n_samples = n_samples\n\t\tself.metric = 'ignore'\n\t\tself.random_state = check_random_state(random_state)\n\t\tself.optimizer = optimizer\n\t\tself.optimizer_kwds = optimizer_kwds\n\t\tself.n_jobs = n_jobs\n\t\tself.verbose = verbose\n\t\tself.initial_subset = initial_subset\n\n\t\tself.ranking = None\n\t\tself.idxs = None\n\t\tself.gains = None\n\t\tself.subset = None\n\t\tself.sparse = None\n\t\tself._X = None\n\t\t\n\t\tself.sieve_current_values_ = None\n\t\tself.n_seen_ = 0\n\t\tself.reservoir_size = 0 if reservoir is None else reservoir.shape[0]\n\t\tself.reservoir = reservoir\n\t\tself.max_reservoir_size = max_reservoir_size if reservoir is None else reservoir.shape[0]\n\t\tself.update_reservoir_ = reservoir is None\n\n\tdef fit(self, X, y=None, sample_weight=None, sample_cost=None):\n\t\t\"\"\"Run submodular optimization to select a subset of examples.\n\n\t\tThis method is a wrapper for the full submodular optimization process.\n\t\tIt takes in some data set (and optionally labels that are ignored\n\t\tduring this process) and selects `n_samples` from it in the greedy\n\t\tmanner specified by the optimizer.\n\n\t\tThis method will return the selector object itself, not the transformed\n\t\tdata set. The `transform` method will then transform a data set to the\n\t\tselected points, or alternatively one can use the ranking stored in\n\t\tthe `self.ranking` attribute. The `fit_transform` method will perform\n\t\tboth optimization and selection and return the selected items.\n\n\t\tParameters\n\t\t----------\n\t\tX : list or numpy.ndarray, shape=(n, d)\n\t\t\tThe data set to transform. Must be numeric.\n\n\t\ty : list or numpy.ndarray or None, shape=(n,), optional\n\t\t\tThe labels to transform. If passed in this function will return\n\t\t\tboth the data and th corresponding labels for the rows that have\n\t\t\tbeen selected.\n\n\t\tsample_weight : list or numpy.ndarray or None, shape=(n,), optional\n\t\t\tThe weight of each example. Currently ignored in apricot but\n\t\t\tincluded to maintain compatibility with sklearn pipelines. \n\n\t\tsample_cost : list or numpy.ndarray or None, shape=(n,), optional\n\t\t\tThe cost of each item. If set, indicates that optimization should\n\t\t\tbe performed with respect to a knapsack constraint.\n\n\t\tReturns\n\t\t-------\n\t\tself : BaseGraphSelection\n\t\t\tThe fit step returns this selector object.\n\t\t\"\"\"\n\n\t\tallowed_dtypes = list, numpy.ndarray, csr_matrix\n\n\t\tif not isinstance(X, allowed_dtypes):\n\t\t\traise ValueError(\"X must be either a list of lists, a 2D numpy \" \\\n\t\t\t\t\"array, or a scipy.sparse.csr_matrix.\")\n\t\tif isinstance(X, numpy.ndarray) and len(X.shape) != 2:\n\t\t\traise ValueError(\"X must have exactly two dimensions.\")\n\t\tif numpy.min(X) < 0.0 and numpy.max(X) > 0.:\n\t\t\traise ValueError(\"X cannot contain negative values or must be entirely \"\\\n\t\t\t\t\"negative values.\")\n\t\tif self.n_samples > X.shape[0]:\n\t\t\traise ValueError(\"Cannot select more examples than the number in\" \\\n\t\t\t\t\" the data set.\")\n\n\t\tif not self.sparse:\n\t\t\tif X.dtype != 'float64':\n\t\t\t\tX = X.astype('float64')\n\n\t\tif isinstance(self.optimizer, str):\n\t\t\toptimizer = OPTIMIZERS[self.optimizer](function=self, \n\t\t\t\tverbose=self.verbose, random_state=self.random_state,\n\t\t\t\t**self.optimizer_kwds)\n\t\telse:\n\t\t\toptimizer = self.optimizer\n\n\t\tself._X = X if self._X is None else self._X\n\t\tself._initialize(X)\n\n\t\tif self.verbose:\n\t\t\tself.pbar = tqdm(total=self.n_samples, unit_scale=True)\n\n\t\toptimizer.select(X, self.n_samples, sample_cost=sample_cost)\n\n\t\tif self.verbose == True:\n\t\t\tself.pbar.close()\n\n\t\tself.ranking = numpy.array(self.ranking)\n\t\tself.gains = numpy.array(self.gains)\n\t\treturn self\n\n\tdef partial_fit(self, X, y=None, sample_weight=None, sample_cost=None):\n\t\tallowed_dtypes = list, numpy.ndarray, csr_matrix\n\n\t\tif not isinstance(X, allowed_dtypes):\n\t\t\traise ValueError(\"X must be either a list of lists, a 2D numpy \" \\\n\t\t\t\t\"array, or a scipy.sparse.csr_matrix.\")\n\t\tif isinstance(X, numpy.ndarray) and len(X.shape) != 2:\n\t\t\traise ValueError(\"X must have exactly two dimensions.\")\n\n\t\tif not self.sparse:\n\t\t\tif X.dtype != 'float64':\n\t\t\t\tX = X.astype('float64')\n\n\t\tif not isinstance(self.optimizer, SieveGreedy):\n\t\t\tself.optimizer = OPTIMIZERS['sieve'](function=self, \n\t\t\t\tverbose=self.verbose, random_state=self.random_state,\n\t\t\t\t**self.optimizer_kwds)\n\n\t\tself._X = X if self._X is None else self._X\n\t\tself._initialize(X)\n\n\t\tif self.verbose:\n\t\t\tself.pbar = tqdm(total=self.n_samples, unit_scale=True)\n\n\t\tself.optimizer.select(X, self.n_samples, sample_cost=sample_cost)\n\n\t\tif self.verbose == True:\n\t\t\tself.pbar.close()\n\n\t\tself.ranking = numpy.array(self.ranking)\n\t\tself.gains = numpy.array(self.gains)\n\t\tself._X = None\n\t\treturn self\n\n\tdef transform(self, X, y=None, sample_weight=None):\n\t\t\"\"\"Transform a data set to include only the selected examples.\n\n\t\tThis method will return a selection of X and optionally selections\n\t\tof y and sample_weight. The default setting is to select items based\n\t\ton the ranking determined in the `fit` step with examples in the same\n\t\torder as that ranking. Optionally, the whole data set can be returned,\n\t\twith the weights corresponding to samples that were not selected set\n\t\tto 0. This setting can be controlled by setting `pipeline=True`. \n\n\t\tParameters\n\t\t----------\n\t\tX : list or numpy.ndarray, shape=(n, d)\n\t\t\tThe data set to transform. Must be numeric.\n\n\t\ty : list or numpy.ndarray or None, shape=(n,), optional\n\t\t\tThe labels to transform. If passed in this function will return\n\t\t\tboth the data and the corresponding labels for the rows that have\n\t\t\tbeen selected. Default is None. \n\n\t\tsample_weight : list or numpy.ndarray or None, shape=(n,), optional\n\t\t\tThe sample weights to transform. If passed in this function will\n\t\t\treturn the selected labels (y) and the selected samples, even\n\t\t\tif no labels were passed in. Default is None.\n\n\t\tReturns\n\t\t-------\n\t\tX_subset : numpy.ndarray, shape=(n_samples, d)\n\t\t\tA subset of the data such that n_samples < n and n_samples is the\n\t\t\tinteger provided at initialization.\n\n\t\ty_subset : numpy.ndarray, shape=(n_samples,), optional\n\t\t\tThe labels that match with the indices of the samples if y is\n\t\t\tpassed in. Only returned if passed in.\n\n\t\tsample_weight_subset : numpy.ndarray, shape=(n_samples,), optional\n\t\t\tThe weight of each example.\n\t\t\"\"\"\n\n\t\tr = self.ranking\n\n\t\tif sample_weight is not None:\n\t\t\tif y is None:\n\t\t\t\treturn X[r], None, sample_weight[r]\n\t\t\telse:\n\t\t\t\treturn X[r], y[r], sample_weight[r]\n\n\t\telse:\n\t\t\tif y is None:\n\t\t\t\treturn X[r]\n\t\t\telse:\n\t\t\t\treturn X[r], y[r]\n\n\tdef fit_transform(self, X, y=None, sample_weight=None, sample_cost=None):\n\t\t\"\"\"Run optimization and select a subset of examples.\n\n\t\tThis method will first perform the `fit` step and then perform the\n\t\t`transform` step, returning a transformed data set. \n\n\t\tParameters\n\t\t----------\n\t\tX : list or numpy.ndarray, shape=(n, d)\n\t\t\tThe data set to transform. Must be numeric.\n\n\t\ty : list or numpy.ndarray or None, shape=(n,), optional\n\t\t\tThe labels to transform. If passed in this function will return\n\t\t\tboth the data and the corresponding labels for the rows that have\n\t\t\tbeen selected. Default is None. \n\n\t\tsample_weight : list or numpy.ndarray or None, shape=(n,), optional\n\t\t\tThe sample weights to transform. If passed in this function will\n\t\t\treturn the selected labels (y) and the selected samples, even\n\t\t\tif no labels were passed in. Default is None.\n\n\t\tsample_cost : list or numpy.ndarray or None, shape=(n,), optional\n\t\t\tThe cost of each item. If set, indicates that optimization should\n\t\t\tbe performed with respect to a knapsack constraint.\n\n\t\tReturns\n\t\t-------\n\t\tX_subset : numpy.ndarray, shape=(n_samples, d)\n\t\t\tA subset of the data such that n_samples < n and n_samples is the\n\t\t\tinteger provided at initialization.\n\n\t\ty_subset : numpy.ndarray, shape=(n_samples,), optional\n\t\t\tThe labels that match with the indices of the samples if y is\n\t\t\tpassed in. Only returned if passed in.\n\n\t\tsample_weight_subset : numpy.ndarray, shape=(n_samples,), optional\n\t\t\tThe weight of each example.\n\t\t\"\"\"\n\n\t\treturn self.fit(X, y=y, sample_weight=sample_weight, \n\t\t\tsample_cost=sample_cost).transform(X, y=y, \n\t\t\tsample_weight=sample_weight)\n\n\tdef _initialize(self, X, idxs=None):\n\t\tn, d = X.shape\n\t\tself._X = X if self._X is None else self._X\n\n\t\tself.sparse = isinstance(X, csr_matrix)\n\t\tself.ranking = []\n\t\tself.gains = []\n\t\tself.subset = numpy.zeros((0, self._X.shape[1]), dtype='float64')\n\n\t\tself.current_values = numpy.zeros(d, dtype='float64')\n\t\tself.current_concave_values = numpy.zeros(d, dtype='float64')\n\t\tself.mask = numpy.zeros(n, dtype='int8')\n\n\t\tif self.initial_subset is not None:\n\t\t\tif self.initial_subset.ndim == 1:\n\t\t\t\tif self.initial_subset.dtype == bool:\n\t\t\t\t\tself.initial_subset = numpy.where(self.initial_subset == 1)[0]\n\t\t\t\t\n\t\t\t\tif len(self.initial_subset) + self.n_samples > X.shape[0]:\n\t\t\t\t\traise ValueError(\"When using a mask for the initial subset\" \\\n\t\t\t\t\t\t\" must selected fewer than the size of the subset minus\" \\\n\t\t\t\t\t\t\" the initial subset size, i.e., n_samples < X.shape[0] -\"\\\n\t\t\t\t\t\t\" initial_subset.shape[0].\")\n\n\t\t\t\tif self.initial_subset.max() > X.shape[0]:\n\t\t\t\t\traise ValueError(\"When passing in an integer mask for the initial subset\"\\\n\t\t\t\t\t\t\" the maximum value cannot exceed the size of the data set.\")\n\t\t\t\telif self.initial_subset.min() < 0:\n\t\t\t\t\traise ValueError(\"When passing in an integer mask for the initial subset\"\\\n\t\t\t\t\t\t\" the minimum value cannot be negative.\")\n\t\t\t\t\n\t\t\t\tself.mask[self.initial_subset] = 1\n\n\t\tself.idxs = numpy.where(self.mask == 0)[0]\n\n\tdef _calculate_gains(self, X, idxs=None):\n\t\traise NotImplementedError\n\n\tdef _calculate_sieve_gains(self, X, thresholds, idxs):\n\t\tn = X.shape[0]\n\t\td = X.shape[1] if self.reservoir is None else self.max_reservoir_size\n\t\tl = len(thresholds)\n\n\t\tif self.sieve_current_values_ is None:\n\t\t\tself.sieve_current_values_ = numpy.zeros((l, d), \n\t\t\t\tdtype='float64')\n\t\t\tself.sieve_selections_ = numpy.zeros((l, self.n_samples), \n\t\t\t\tdtype='int64') - 1\n\t\t\tself.sieve_gains_ = numpy.zeros((l, self.n_samples), \n\t\t\t\tdtype='float64') - 1\n\t\t\tself.sieve_n_selected_ = numpy.zeros(l, \n\t\t\t\tdtype='int64')\n\t\t\tself.sieve_total_gains_ = numpy.zeros(l, \n\t\t\t\tdtype='float64')\n\t\t\tself.sieve_subsets_ = numpy.zeros((l, self.n_samples, \n\t\t\t\tself._X.shape[1]), dtype='float64')\n\t\telse:\n\t\t\tj = l - self.sieve_current_values_.shape[0]\n\t\t\tif j > 0:\n\t\t\t\tself.sieve_current_values_ = numpy.vstack([\n\t\t\t\t\tself.sieve_current_values_, numpy.zeros((j, d), \n\t\t\t\t\t\tdtype='float64')])\n\t\t\t\tself.sieve_selections_ = numpy.vstack([\n\t\t\t\t\tself.sieve_selections_, numpy.zeros((j, self.n_samples), \n\t\t\t\t\t\tdtype='int64') - 1])\n\t\t\t\tself.sieve_gains_ = numpy.vstack([self.sieve_gains_, \n\t\t\t\t\tnumpy.zeros((j, self.n_samples), dtype='float64')])\n\t\t\t\tself.sieve_n_selected_ = numpy.concatenate([\n\t\t\t\t\tself.sieve_n_selected_, numpy.zeros(j, dtype='int64')])\n\t\t\t\tself.sieve_total_gains_ = numpy.concatenate([\n\t\t\t\t\tself.sieve_total_gains_, numpy.zeros(j, dtype='float64')])\n\t\t\t\tself.sieve_subsets_ = numpy.concatenate([self.sieve_subsets_, \n\t\t\t\t\tnumpy.zeros((j, self.n_samples, self._X.shape[1]), \n\t\t\t\t\t\tdtype='float64')])\n\n\tdef _select_next(self, X, gain, idx):\n\t\tself.ranking.append(idx)\n\t\tself.gains.append(gain)\n\t\tself.mask[idx] = True\n\t\tself.idxs = numpy.where(self.mask == 0)[0]\n\n\t\tif self.sparse:\n\t\t\tX = self._X[idx:idx+1].toarray()\n\t\telse:\n\t\t\tX = self._X[idx:idx+1]\n\n\t\tif self.metric != 'precomputed':\n\t\t\tself.subset = numpy.concatenate([self.subset, X])\n\n\nclass BaseGraphSelection(BaseSelection):\n\t\"\"\"The base graph selection object.\n\n\tThis object defines the structures that all submodular selection algorithms\n\tshould follow if they operate on a graph, such as pairwise similarity \n\tmeasurements. All algorithms will have the same public methods and the same \n\tattributes.\n\n\tNOTE: All ~pairwise~ values in your data must be positive for these\n\tselection methods to work.\n\n\tThis implementation allows users to pass in either their own symmetric\n\tsquare matrix of similarity values, or a data matrix as normal and a function\n\tthat calculates these pairwise values.\n\n\tParameters\n\t----------\n\tn_samples : int\n\t\tThe number of samples to return.\n\n\tmetric : str\n\t\tThe method for converting a data matrix into a square symmetric matrix\n\t\tof pairwise similarities. If a string, can be any of the metrics\n\t\timplemented in sklearn (see https://scikit-learn.org/stable/modules/\n\t\tgenerated/sklearn.metrics.pairwise_distances.html), including\n\t\t\"precomputed\" if one has already generated a similarity matrix. Note\n\t\tthat sklearn calculates distance matrices whereas apricot operates on\n\t\tsimilarity matrices, and so a distances.max() - distances transformation\n\t\tis performed on the resulting distances. For backcompatibility,\n\t\t'corr' will be read as 'correlation'.\n\n\tinitial_subset : list, numpy.ndarray or None\n\t\tIf provided, this should be a list of indices into the data matrix\n\t\tto use as the initial subset, or a group of examples that may not be\n\t\tin the provided data should beused as the initial subset. If indices, \n\t\tthe provided array should be one-dimensional. If a group of examples,\n\t\tthe data should be 2 dimensional.\n\n\toptimizer : string or optimizers.BaseOptimizer, optional\n\t\tThe optimization approach to use for the selection. Default is\n\t\t'two-stage', which makes selections using the naive greedy algorithm\n\t\tinitially and then switches to the lazy greedy algorithm. Must be\n\t\tone of\n\n\t\t\t'naive' : the naive greedy algorithm\n\t\t\t'lazy' : the lazy (or accelerated) greedy algorithm\n\t\t\t'approximate-lazy' : the approximate lazy greedy algorithm\n\t\t\t'two-stage' : starts with naive and switches to lazy\n\t\t\t'stochastic' : the stochastic greedy algorithm\n\t\t\t'greedi' : the GreeDi distributed algorithm\n\t\t\t'bidirectional' : the bidirectional greedy algorithm\n\n\t\tDefault is 'naive'.\n\n\toptimizer_kwds : dict or None\n\t\tA dictionary of arguments to pass into the optimizer object. The keys\n\t\tof this dictionary should be the names of the parameters in the optimizer\n\t\tand the values in the dictionary should be the values that these\n\t\tparameters take. Default is None.\n\n\tn_neighbors : int or None\n\t\tWhen constructing a similarity matrix, the number of nearest neighbors\n\t\twhose similarity values will be kept. The result is a sparse similarity\n\t\tmatrix which can significantly speed up computation at the cost of\n\t\taccuracy. Default is None.\n\n\treservoir : numpy.ndarray or None\n\t\tThe reservoir to use when calculating gains in the sieve greedy\n\t\tstreaming optimization algorithm in the `partial_fit` method.\n\t\tCurrently only used for graph-based functions. If a numpy array\n\t\tis passed in, it will be used as the reservoir. If None is passed in,\n\t\twill use reservoir sampling to collect a reservoir. Default is None.\n\n\tmax_reservoir_size : int \n\t\tThe maximum size that the reservoir can take. If a reservoir is passed\n\t\tin, this value is set to the size of that array. Default is 1000.\n\n\tn_jobs : int\n\t\tThe number of threads to use when performing computation in parallel.\n\t\tCurrently, this parameter is exposed but does not actually do anything.\n\t\tThis will be fixed soon.\n\n\trandom_state : int or RandomState or None, optional\n\t\tThe random seed to use for the random selection process. Only used\n\t\tfor stochastic greedy.\n\n\tverbose : bool\n\t\tWhether to print output during the selection process.\n\n\tAttributes\n\t----------\n\tn_samples : int\n\t\tThe number of samples to select.\n\n\tmetric : callable\n\t\tA function that takes in a data matrix and converts it to a square\n\t\tsymmetric matrix.\n\n\tranking : numpy.array int\n\t\tThe selected samples in the order of their gain.\n\n\tgains : numpy.array float\n\t\tThe gain of each sample in the returned set when it was added to the\n\t\tgrowing subset. The first number corresponds to the gain of the first\n\t\tadded sample, the second corresponds to the gain of the second added\n\t\tsample, and so forth.\n\t\"\"\"\n\n\tdef __init__(self, n_samples, metric='euclidean', \n\t\tinitial_subset=None, optimizer='two-stage', optimizer_kwds={},\n\t\tn_neighbors=None, reservoir=None, max_reservoir_size=1000, \n\t\tn_jobs=1, random_state=None, verbose=False):\n\n\t\tsuper(BaseGraphSelection, self).__init__(n_samples=n_samples, \n\t\t\tinitial_subset=initial_subset, optimizer=optimizer, \n\t\t\toptimizer_kwds=optimizer_kwds, reservoir=reservoir, \n\t\t\tmax_reservoir_size=max_reservoir_size, n_jobs=n_jobs, \n\t\t\trandom_state=random_state, verbose=verbose)\n\n\t\tself.metric = metric.replace(\"corr\", \"correlation\")\n\t\tself.n_neighbors = n_neighbors\n\n\n\tdef fit(self, X, y=None, sample_weight=None, sample_cost=None):\n\t\t\"\"\"Run submodular optimization to select a subset of examples.\n\n\t\tThis method is a wrapper for the full submodular optimization process.\n\t\tIt takes in some data set (and optionally labels that are ignored\n\t\tduring this process) and selects `n_samples` from it in the greedy\n\t\tmanner specified by the optimizer.\n\n\t\tThis method will return the selector object itself, not the transformed\n\t\tdata set. The `transform` method will then transform a data set to the\n\t\tselected points, or alternatively one can use the ranking stored in\n\t\tthe `self.ranking` attribute. The `fit_transform` method will perform\n\t\tboth optimization and selection and return the selected items.\n\n\t\tParameters\n\t\t----------\n\t\tX : list or numpy.ndarray, shape=(n, d)\n\t\t\tThe data set to transform. Must be numeric.\n\n\t\ty : list or numpy.ndarray or None, shape=(n,), optional\n\t\t\tThe labels to transform. If passed in this function will return\n\t\t\tboth the data and th corresponding labels for the rows that have\n\t\t\tbeen selected.\n\n\t\tsample_weight : list or numpy.ndarray or None, shape=(n,), optional\n\t\t\tThe weight of each example. Currently ignored in apricot but\n\t\t\tincluded to maintain compatibility with sklearn pipelines. \n\n\t\tsample_cost : list or numpy.ndarray or None, shape=(n,), optional\n\t\t\tThe cost of each item. If set, indicates that optimization should\n\t\t\tbe performed with respect to a knapsack constraint.\n\n\t\tReturns\n\t\t-------\n\t\tself : BaseGraphSelection\n\t\t\tThe fit step returns this selector object.\n\t\t\"\"\"\n\n\t\tif isinstance(X, csr_matrix) and self.metric not in (\"precomputed\", \"ignore\"):\n\t\t\traise ValueError(\"Must passed in a precomputed sparse \" \\\n\t\t\t\t\"similarity matrix or a dense feature matrix.\")\n\t\tif self.metric == 'precomputed' and X.shape[0] != X.shape[1]:\n\t\t\traise ValueError(\"Precomputed similarity matrices \" \\\n\t\t\t\t\"must be square and symmetric.\")\n\n\t\tX_pairwise = _calculate_pairwise_distances(X, metric=self.metric, \n\t\t\tn_neighbors=self.n_neighbors)\n\t\n\t\tself._X = X\n\t\treturn super(BaseGraphSelection, self).fit(X_pairwise, y=y,\n\t\t\tsample_weight=sample_weight, sample_cost=sample_cost)\n\n\tdef partial_fit(self, X, y=None, sample_weight=None, sample_cost=None):\n\t\tif self.reservoir is None:\n\t\t\tself.reservoir = numpy.empty((self.max_reservoir_size, X.shape[1]))\n\n\t\tif self.update_reservoir_:\n\t\t\tfor i in range(X.shape[0]):\n\t\t\t\tif self.reservoir_size < self.max_reservoir_size:\n\t\t\t\t\tself.reservoir[self.reservoir_size] = X[i]\n\t\t\t\t\tself.reservoir_size += 1\n\t\t\t\telse:\n\t\t\t\t\tr = self.random_state.choice(self.n_seen_ + i)\n\t\t\t\t\tif r < self.max_reservoir_size:\n\t\t\t\t\t\tself.reservoir[r] = X[i]\n\t\t\t\t\t\t#self.current_values_[:, r] = 0.\n\n\t\tX_pairwise = _calculate_pairwise_distances(X, \n\t\t\tY=self.reservoir[:self.reservoir_size], metric=self.metric)\n\n\t\tself._X = X\n\t\tsuper(BaseGraphSelection, self).partial_fit(X_pairwise, y=y, \n\t\t\tsample_weight=sample_weight, sample_cost=sample_cost)\n\n\t\tself.current_values = numpy.zeros(self.reservoir_size, \n\t\t\tdtype='float64')\n\t\tself.n_seen_ += X.shape[0]\n\n\tdef _initialize(self, X_pairwise, idxs=None):\n\t\tsuper(BaseGraphSelection, self)._initialize(X_pairwise, idxs=idxs)\n\n\tdef _calculate_gains(self, X_pairwise):\n\t\tsuper(BaseGraphSelection, self)._calculate_gains(X_pairwise)\n\n\tdef _calculate_sieve_gains(self, X, thresholds, idxs):\n\t\tsuper(BaseGraphSelection, self)._calculate_sieve_gains(X, thresholds,\n\t\t\tidxs)\n\n\tdef _select_next(self, X_pairwise, gain, idx):\n\t\tsuper(BaseGraphSelection, self)._select_next(X_pairwise, gain, idx)\n", "meta": {"hexsha": "b3f308f892778fab972e80ce97c74f3b6117f123", "size": 24552, "ext": "py", "lang": "Python", "max_stars_repo_path": "apricot/functions/base.py", "max_stars_repo_name": "wfondrie/apricot", "max_stars_repo_head_hexsha": "d31365c96bcb61a7ae2550f39a5f9c144e1346ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 389, "max_stars_repo_stars_event_min_datetime": "2018-09-25T07:30:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T17:09:09.000Z", "max_issues_repo_path": "apricot/functions/base.py", "max_issues_repo_name": "wfondrie/apricot", "max_issues_repo_head_hexsha": "d31365c96bcb61a7ae2550f39a5f9c144e1346ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2018-09-26T15:36:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T07:10:55.000Z", "max_forks_repo_path": "apricot/functions/base.py", "max_forks_repo_name": "wfondrie/apricot", "max_forks_repo_head_hexsha": "d31365c96bcb61a7ae2550f39a5f9c144e1346ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2018-09-25T17:32:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-30T17:36:40.000Z", "avg_line_length": 36.8095952024, "max_line_length": 91, "alphanum_fraction": 0.7375366569, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.31742625913050115, "lm_q1q2_score": 0.16243228756620462}}
{"text": "import os\nimport errno\nimport json\nimport numpy as np\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as plt\nfrom Stele.processing.processing_hsg import helper_functions as procHSGHelp\nfrom .pmt import PMT\nfrom .high_sideband_pmt import HighSidebandPMT\n\nnp.set_printoptions(linewidth=500)\n\n\nclass HighSidebandPMTOld(PMT):\n    \"\"\"\n    Old version: Replaced March 01, 2017\n\n    Class initialized by loading in data set.\n\n    Multiple copies of the same sideband were stacked as raw data and combined,\n    effectively causing (2) 10-pt scans to be treated the same as (1) 20pt\n    scan.  This works well until you have photon counted pulses.\n    \"\"\"\n    def __init__(self, file_path, verbose=False):\n        \"\"\"\n        Initializes a SPEX spectrum.  It'll open a single file, then read\n        the data from that file using .add_sideband().  The super's init will\n        handle the parameters and the description.\n\n        attributes:\n            self.parameters - dictionary of important experimental parameters,\n                              created in PMT\n            self.sb_dict - keys are sideband order, values are PMT data arrays\n            self.sb_list - sorted list of included sidebands\n\n        :param file_path: path to the current file\n        :type file_path: str\n        :param verbose: Flag to see the nitty gritty details\n        :type verbose: bool\n        :return:\n        \"\"\"\n        # Creates the json parameters dictionary\n        super(HighSidebandPMT, self).__init__(file_path)\n        self.fname = file_path\n        self.parameters[\"files included\"] = [file_path]\n        with open(file_path, 'r') as f:\n            sb_num = int(f.readline()[1:])\n        raw_temp = np.genfromtxt(file_path, comments='#', delimiter=',')[3:, :]\n        self.initial_sb = sb_num\n        self.initial_data = np.array(raw_temp)\n        self.sb_dict = {sb_num: np.array(raw_temp)}\n        self.sb_list = [sb_num]\n\n    def add_sideband(self, other):\n        \"\"\"\n        This bad boy will add another PMT sideband object to the sideband\n        spectrum of this object.  It handles when you measure the same sideband\n        twice.  It assumes both are equally \"good\"\n\n        It currently doesn't do any sort of job combining dictionaries or\n        anything, but it definitely could, if you have two incomplete\n        dictionaries\n\n        :param other: the new sideband data to add to the larger spectrum.\n                      Add means append, no additino is performed\n        :type other: HighSidebandPMT\n        :return:\n        \"\"\"\n        \"\"\"\n        This bad boy will add another PMT sideband object to the sideband\n        spectrum of this object\n\n        It currently doesn't do any sort of job combining dictionaries or\n        anything, but it definitely could\n        \"\"\"\n        self.parameters[\"files included\"].append(other.fname)\n\n        if other.initial_sb in self.sb_list:\n            self.sb_list.append(other.initial_sb)\n\n        # Make things comma delimited?\n        try:\n            self.sb_dict[other.initial_sb].vstack((other.initial_data))\n        except Exception:\n            self.sb_dict[other.initial_sb] = np.array(other.initial_data)\n\n    def process_sidebands(self, verbose=False):\n        \"\"\"\n        This bad boy will clean up the garbled mess that is the object before\n        hand, including clearing out misfired shots and doing the averaging.\n\n        Affects:\n            self.sb_dict = Averages over sidebands\n\n        Creates:\n            self.sb_list = The sideband orders included in this object.\n\n        :param verbose: Flag to see the nitty gritty details.\n        :type verbose: bool\n        :return: None\n        \"\"\"\n\n        for sb_num, sb in list(self.sb_dict.items()):\n            if sb_num == 0:\n                # This way the FEL doesn't need to be on during laser\n                # line measurement\n                fire_condition = -np.inf\n            else:\n                # Say FEL fired if the cavity dump signal is\n                # more than half the mean of the cavity dump signal\n                fire_condition = np.mean(sb[:, 2]) / 2\n            frequencies = sorted(list(set(sb[:, 0])))\n\n            temp = None\n            for freq in frequencies:\n                data_temp = np.array([])\n                for point in sb:\n                    if point[0] == freq and point[2] > fire_condition:\n                        data_temp = np.hstack((data_temp, point[3]))\n                try:\n                    temp = np.vstack((temp, np.array([\n                        freq, np.mean(data_temp),\n                        np.std(data_temp) / np.sqrt(len(data_temp))\n                        ])))\n                except Exception:\n                    temp = np.array([\n                        freq, np.mean(data_temp),\n                        np.std(data_temp) / np.sqrt(len(data_temp))\n                        ])\n            # turn NIR freq into eV\n            temp[:, 0] = temp[:, 0] / 8065.6\n            temp = temp[temp[:, 0].argsort()]\n            self.sb_dict[sb_num] = np.array(temp)\n        self.sb_list = sorted(self.sb_dict.keys())\n        if verbose:\n            print(\"Sidebands included\", self.sb_list)\n\n    def integrate_sidebands(self, verbose=False):\n        \"\"\"\n        This method will integrate the sidebands to find their strengths, and\n        then use a magic number to define the width, since they are currently\n        so utterly undersampled for fitting.\n\n        It is currently the preferred method for calculating sideband\n        strengths.  self.fit_sidebands is probably better with better-sampled\n        lines.\n\n        Creates:\n        self.sb_results = full list of integrated data. Column order is:\n                          [sb order, Freq (eV), \"error\" (eV), Integrate area\n                          (arb.), area error, \"Linewidth\" (eV),\n                          \"Linewidth error\" (eV)\n        self.full_dict = Dictionary where the SB order column is removed and\n                         turned into the keys.  The values are the rest of that\n                         sideband's results.\n\n        :param verbose: Flag to see the nitty gritty details\n        :type verbose: bool\n        :return: None\n        \"\"\"\n        self.full_dict = {}\n        for sideband in list(self.sb_dict.items()):\n            index = np.argmax(sideband[1][:, 1])\n            nir_frequency = sideband[1][index, 0]\n            area = np.trapz(np.nan_to_num(\n                sideband[1][:, 1]), sideband[1][:, 0]\n                )\n            # Divide by the step size?\n            error = np.sqrt(np.sum(np.nan_to_num(\n                sideband[1][:, 2]) ** 2)) / 8065.6\n            if verbose:\n                print(\"order\", sideband[0])\n                print(\"area\", area)\n                print(\"error\", error)\n                print(\"ratio\", area / error)\n            details = np.array([\n                sideband[0], nir_frequency, 1 / 8065.6, area, error,\n                2 / 8065.6, 1 / 8065.6\n                ])\n            if area < 0:\n                if verbose:\n                    print(\"area less than 0\", sideband[0])\n                continue\n            # Two seems like a good cutoff?\n            elif area < 1.5 * error:\n                if verbose:\n                    print(\"I did not keep sideband \", sideband[0])\n                continue\n            try:\n                self.sb_results = np.vstack((self.sb_results, details))\n            except Exception:\n                self.sb_results = np.array(details)\n            self.full_dict[sideband[0]] = details[1:]\n        try:\n            self.sb_results = self.sb_results[self.sb_results[:, 0].argsort()]\n\n        except (IndexError, AttributeError):\n            # IndexError where there's only one sideband\n            # AttributeError when there aren't any (one sb which wasn't fit)\n            pass\n\n    def fit_sidebands(self, plot=False, verbose=False):\n        \"\"\"\n        This method will fit a gaussian to each of the sidebands provided in\n        the self.sb_dict and make a list just like in the EMCCD version.  It\n        will also use the standard error of the integral of the PMT peak as the\n        error of the gaussian area instead of that element from the covariance\n        matrix.  Seems more legit.\n\n        attributes:\n        self.sb_results: the numpy array that contains all of the fit info just\n                         like it does in the CCD class.\n        self.full_dict = A dictionary version of self.sb_results\n\n        :param plot: Flag to see the results plotted\n        :type plot: bool\n        :param verbose: Flag to see the nitty gritty details\n        :type verbose: bool\n        :return: None\n        \"\"\"\n        sb_fits = {}\n        for sideband in list(self.sb_dict.items()):\n            if verbose:\n                print(\"Sideband number\", sideband[0])\n                print(\"Sideband data:\\n\", sideband[1])\n            index = np.argmax(sideband[1][:, 1])\n            nir_frequency = sideband[1][index, 0]\n            peak = sideband[1][index, 1]\n            width_guess = 0.0001  # Yep, another magic number\n            p0 = [nir_frequency, peak * width_guess, width_guess, 0.00001]\n\n            if verbose:\n                x_vals = np.linspace(np.amin(sideband[1][:, 0]),\n                                     np.amax(sideband[1][:, 0]), num=50)\n                plt.plot(x_vals, procHSGHelp.gauss(x_vals, *p0),\n                         label=\"fit :{}\".format(sideband[1]))\n                print(\"p0:\", p0)\n            try:\n                coeff, var_list = curve_fit(\n                    gauss, sideband[1][:, 0], sideband[1][:, 1],\n                    sigma=sideband[1][:, 2], p0=p0\n                    )\n                coeff[1] = abs(coeff[1])\n                coeff[2] = abs(coeff[2])\n                if verbose:\n                    print(\"coeffs:\", coeff)\n                    print(\"stdevs:\", np.sqrt(np.diag(var_list)))\n                    print(\"integral\", np.trapz(\n                        sideband[1][:, 1], sideband[1][:, 0]\n                        ))\n                # The error on where the sideband is should be small\n                if np.sqrt(np.diag(var_list))[0] / coeff[0] < 0.5:\n                    sb_fits[sideband[0]] = np.concatenate((\n                        np.array([sideband[0]]), coeff,\n                        np.sqrt(np.diag(var_list))\n                        ))\n                    # print \"error then:\", sb_fits[sideband[0]][6]\n                    relative_error = (\n                        np.sqrt(sum([\n                            x ** 2 for x in sideband[1][index - 1:index + 2, 2]\n                            ]))\n                        / np.sum(sideband[1][index - 1:index + 2, 1]))\n                    if verbose:\n                        print(\"relative error:\", relative_error)\n                    sb_fits[sideband[0]][6] = coeff[1] * relative_error\n                    # print \"error now:\", sb_fits[sideband[0]][6]\n                    if plot:\n                        x_vals = np.linspace(np.amin(sideband[1][:, 0]),\n                                             np.amax(sideband[1][:, 0]), num=50\n                                             )\n                        plt.plot(x_vals, procHSGHelp.gauss(x_vals, *coeff))\n                        # plt.plot(x_vals, gauss(x_vals, *p0))\n                else:\n                    print(\"what happened?\")\n            except Exception:\n                print(\"God damn it, Leroy.\\nYou couldn't fit this.\")\n                sb_fits[sideband[0]] = None\n\n        for result in sorted(sb_fits.keys()):\n            try:\n                self.sb_results = np.vstack((self.sb_results, sb_fits[result]))\n            except Exception:\n                self.sb_results = np.array(sb_fits[result])\n\n        self.sb_results = self.sb_results[:, [0, 1, 5, 2, 6, 3, 7, 4, 8]]\n        self.sb_results = self.sb_results[:, :7]\n        if verbose:\n            print(\"And the results, please:\\n\", self.sb_results)\n\n        self.full_dict = {}\n        for sb in self.sb_results:\n            self.full_dict[sb[0]] = np.asarray(sb[1:])\n\n    def laser_line(self, verbose=False):\n        \"\"\"\n        This method is designed to scale everything in the PMT to the\n        conversion efficiency based on our measurement of the laser line with a\n        fixed attenuation.\n\n        Creates:\n            self.parameters['normalized?'] = Flag to specify if the laser has\n            been accounted for.\n\n        :return: None\n        \"\"\"\n\n        if 0 not in self.sb_list:\n            self.parameters['normalized?'] = False\n            return\n        else:\n            laser_index = np.where(self.sb_results[:, 0] == 0)[0][0]\n            if verbose:\n                print(\"sb_results\", self.sb_results[laser_index, :])\n                print(\"laser_index\", laser_index)\n\n            laser_strength = np.array(self.sb_results[laser_index, 3:5])\n\n            if verbose:\n                print(\"Laser_strength\", laser_strength)\n\n            for sb in self.sb_results:\n                sb[4] = (sb[3] / laser_strength[0]) * np.sqrt(\n                    (sb[4] / sb[3]) ** 2 + (laser_strength[1] / laser_strength[0]) ** 2)\n                sb[3] = sb[3] / laser_strength[0]\n            for sb in list(self.full_dict.values()):\n                sb[3] = (sb[2] / laser_strength[0]) * np.sqrt(\n                    (sb[3] / sb[2]) ** 2 + (laser_strength[1] / laser_strength[0]) ** 2)\n                sb[2] = sb[2] / laser_strength[0]\n            self.parameters['normalized?'] = True\n\n    def save_processing(self, file_name, folder_str, marker='', index=''):\n        \"\"\"\n        This will save all of the self.proc_data and the results from the\n        fitting of this individual file.\n\n        Format:\n        spectra_fname = file_name + '_' + marker + '_' + str(index) + '.txt'\n        fit_fname = file_name + '_' + marker + '_' + str(index) + '_fits.txt'\n\n        Inputs:\n        file_name = the beginning of the file name to be saved\n        folder_str = the location of the folder where the file will be saved,\n                     will create the folder, if necessary.\n        marker = I...I don't know what this was originally for\n        index = used to keep these files from overwriting themselves when in a\n                list\n\n        Outputs:\n        Two files:\n            self.proc_data = the continuous spectrum\n            self.sb_results = the individual sideband details\n\n        :param file_name: The base name for the saved file\n        :type file_name: str\n        :param folder_str: The full name for the folder hte file is saved it.\n                           Folder can be created\n        :type folder_str: str\n        :param marker: Marker for the file, appended to file_name, often the\n                       self.parameters['series']\n        :type marker: str\n        :param index: used to keep these files from overwriting themselves when\n                      marker is the same\n        :type index: str or int\n        :return: None\n        \"\"\"\n        try:\n            os.mkdir(folder_str)\n        except OSError as e:\n            if e.errno == errno.EEXIST:\n                pass\n            else:\n                raise\n\n        spectra_fname = file_name + '_' + marker + '_' + str(index) + '.txt'\n        fit_fname = file_name + '_' + marker + '_' + str(index) + '_fits.txt'\n        self.save_name = spectra_fname\n        # self.parameters[\"files included\"] = list(self.files)\n        try:\n            parameter_str = json.dumps(\n                self.parameters, sort_keys=True, indent=4,\n                separators=(',', ': ')\n                )\n        except Exception:\n            print(\"Source: PMT.save_images\\nJSON FAILED\")\n            print(\"Here is the dictionary that broke JSON:\\n\", self.parameters)\n            return\n        parameter_str = parameter_str.replace('\\n', '\\n#')\n\n        # Make the number of lines constant so importing is easier\n        # for num in range(99 - num_lines): parameter_str += '\\n#'\n        num_lines = parameter_str.count('#')\n        parameter_str += '\\n#' * (99 - num_lines)\n\n        origin_import_spec = '\\nNIR frequency,Signal,Standard error\\neV,arb. u.,arb. u.\\n,{:.3f},'.format(\n            self.parameters[\"fieldStrength\"][\"mean\"])\n        spec_header = '#' + parameter_str + origin_import_spec\n\n        origin_import_fits = '\\nCenter energy,error,Amplitude,error,Linewidth,error\\neV,,arb. u.,,eV,,\\n,,'  # + marker\n        fits_header = '#' + parameter_str + origin_import_fits\n\n        for sideband in sorted(self.sb_dict.keys()):\n            # TODO: REPLACE ALL INSTANCES OF ERRORS AS CONTROL STATEMENTS WITH\n            #       CORRECT IF/ELSE OR SIMILAR LOGIC\n            try:\n                complete = np.vstack((complete, self.sb_dict[sideband]))\n            except Exception:\n                complete = np.array(self.sb_dict[sideband])\n\n        np.savetxt(\n            os.path.join(folder_str, spectra_fname), complete, delimiter=',',\n            header=spec_header, comments='', fmt='%0.6e')\n\n        try:\n            np.savetxt(os.path.join(folder_str, fit_fname), self.sb_results,\n                       delimiter=',',\n                       header=fits_header, comments='', fmt='%0.6e')\n        except AttributeError:\n            # Catch the error that happens if you save something without files\n            print(\"warning, couldn't save fit file (no sidebands found?)\")\n\n        print(\"Saved PMT spectrum.\\nDirectory: {}\".format(\n            os.path.join(folder_str, spectra_fname)))\n", "meta": {"hexsha": "88a7d67d58012da87dbb8d526e736aef24932b39", "size": 17513, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Stele/processing/processing_hsg/pmt_collection/high_sideband_pmt_old.py", "max_stars_repo_name": "SherwinGroup/Stele", "max_stars_repo_head_hexsha": "9bb7da0b406a801975e21c9f7ce05d369ae661e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Stele/processing/processing_hsg/pmt_collection/high_sideband_pmt_old.py", "max_issues_repo_name": "SherwinGroup/Stele", "max_issues_repo_head_hexsha": "9bb7da0b406a801975e21c9f7ce05d369ae661e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Stele/processing/processing_hsg/pmt_collection/high_sideband_pmt_old.py", "max_forks_repo_name": "SherwinGroup/Stele", "max_forks_repo_head_hexsha": "9bb7da0b406a801975e21c9f7ce05d369ae661e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.401891253, "max_line_length": 119, "alphanum_fraction": 0.5430822817, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.1624322842619611}}
{"text": "#!/usr/bin/env python\nimport os\nimport numpy as np\nimport time\nimport copy\nimport sys\n\nimport argparse\n\nang_2_bohr = 1.0/0.52917721067\nhart_2_ev = 27.21138602\n\nimport atomistic_tools.cp2k_grid_orbitals as cgo\nimport atomistic_tools.cp2k_stm_sts as css\nfrom atomistic_tools import common\nfrom atomistic_tools.cube import Cube\n\nfrom mpi4py import MPI\n\ncomm = MPI.COMM_WORLD\nmpi_rank = comm.Get_rank()\nmpi_size = comm.Get_size()\n\nparser = argparse.ArgumentParser(\n    description='Puts the CP2K orbitals on grid and calculates STM.')\n\n### ----------------------------------------------------------------------\n### Input and output files\nparser.add_argument(\n    '--cp2k_input_file',\n    metavar='FILENAME',\n    required=True,\n    help='CP2K input of the SCF calculation.')\nparser.add_argument(\n    '--basis_set_file',\n    metavar='FILENAME',\n    required=True,\n    help='File containing the used basis sets.')\nparser.add_argument(\n    '--xyz_file',\n    metavar='FILENAME',\n    required=True,\n    help='.xyz file containing the geometry.')\nparser.add_argument(\n    '--wfn_file',\n    metavar='FILENAME',\n    required=True,\n    help='Restart file containing the final wavefunction.')\nparser.add_argument(\n    '--hartree_file',\n    metavar='FILENAME',\n    required=True,\n    help='Cube file containing the hartree potential.')\nparser.add_argument(\n    '--output_file',\n    metavar='FILENAME',\n    default=\"./stm.npz\",\n    help='File, where to save the STM/STS output')\nparser.add_argument(\n    '--orb_output_file',\n    metavar='FILENAME',\n    default=\"./orb.npz\",\n    help='File, where to save the orbital output')\n### ----------------------------------------------------------------------\n### Parameters for putting orbitals on grid\nparser.add_argument(\n    '--eval_region',\n    type=str,\n    nargs=6,\n    metavar='X',\n    required=True,\n    help=common.eval_region_description\n)\nparser.add_argument(\n    '--dx',\n    type=float,\n    metavar='DX',\n    required=True,\n    help='Spatial step for the grid (angstroms).')\nparser.add_argument(\n    '--eval_cutoff',\n    type=float,\n    metavar='D',\n    default=16.0,\n    help=(\"Size of the region around the atom where each\"\n          \" orbital is evaluated (only used for 'G' region).\")\n)\nparser.add_argument(\n    '--extrap_extent',\n    type=float,\n    metavar='H',\n    default=4.0,\n    required=True,\n    help=\"The extent of the extrapolation region. (angstrom)\")\n### ----------------------------------------------------------------------\n### Gas phase analysis parameters\nparser.add_argument(\n    '--n_homo',\n    type=int,\n    metavar='N',\n    default=0,\n    help=\"Number of HOMO orbitals to analyse.\")\nparser.add_argument(\n    '--n_lumo',\n    type=int,\n    metavar='N',\n    default=0,\n    help=\"Number of LUMO orbitals to analyse.\")\nparser.add_argument(\n    '--orb_heights',\n    nargs='*',\n    type=float,\n    metavar='H',\n    help=\"List of heights for constant height orbital pictures (wrt topmost atom).\")\nparser.add_argument(\n    '--orb_isovalues',\n    nargs='*',\n    type=float,\n    metavar='C',\n    help=\"List of charge density isovalues for constant current orbital pictures\")\nparser.add_argument(\n    '--orb_fwhms',\n    nargs='*',\n    type=float,\n    default=[0.02],\n    help=\"Full width at half maximum for orbital STS gaussian broadening. (eV)\")\n### ----------------------------------------------------------------------\n### Slab system analysis parameters\n###\n### Option 1: continuous selection\nparser.add_argument(\n    '--energy_range',\n    nargs=3,\n    type=float,\n    metavar='E',\n    help='Selection of STM/STS energy values based on a range: min, max and differential.')\n###\n### Option 2: discrete selection\nparser.add_argument(\n    '--energies',\n    nargs='*',\n    type=float,\n    metavar='E',\n    help='Discrete energies where to run the STM/STS.')\n### ----------------------------------------------------------------------\n### Parameters for STM/STS series\nparser.add_argument(\n    '--heights',\n    nargs='*',\n    type=float,\n    metavar='H',\n    help=\"List of heights for constant height STM pictures (wrt topmost atom).\")\nparser.add_argument(\n    '--isovalues',\n    nargs='*',\n    type=float,\n    metavar='C',\n    help=\"List of charge density isovalues for constant current STM pictures.\")\nparser.add_argument(\n    '--fwhms',\n    nargs='*',\n    type=float,\n    default=[0.1],\n    help=\"Full width at half maximum for STS gaussian broadening. (eV)\")\n\n\ntime0 = time.time()\n\n### ------------------------------------------------------\n### Parse args for only one rank to suppress duplicate stdio\n### ------------------------------------------------------\n\nargs = None\nargs_success = False\ntry:\n    if mpi_rank == 0:\n        args = parser.parse_args()\n        args_success = True\nfinally:\n    args_success = comm.bcast(args_success, root=0)\n\nif not args_success:\n    print(mpi_rank, \"exiting\")\n    exit(0)\n\nargs = comm.bcast(args, root=0)\n\n### ------------------------------------------------------\n### Energy values for STM/STS\n### ------------------------------------------------------\n\nif args.energies is not None:\n    e_arr = np.array(args.energies)\nelif args.energy_range is not None:\n    emin, emax, de = args.energy_range\n    e_arr = np.arange(emin, emax+de/2, de)\nelse:\n    e_arr = None\n\nmax_fwhm = np.max(args.fwhms)\nif e_arr is not None:\n    sel_emin = np.min(e_arr) - 2.0*max_fwhm\n    sel_emax = np.max(e_arr) + 2.0*max_fwhm\nelse:\n    sel_emin = None\n    sel_emax = None\n\n### ------------------------------------------------------\n### Evaluate orbitals on the real-space grid\n### ------------------------------------------------------\n\ncp2k_grid_orb = cgo.Cp2kGridOrbitals(mpi_rank, mpi_size, mpi_comm=comm, single_precision=True)\ncp2k_grid_orb.read_cp2k_input(args.cp2k_input_file)\ncp2k_grid_orb.read_xyz(args.xyz_file)\ncp2k_grid_orb.center_atoms_to_cell()\ncp2k_grid_orb.read_basis_functions(args.basis_set_file)\ncp2k_grid_orb.load_restart_wfn_file(args.wfn_file,\n                                    emin=sel_emin, emax=sel_emax,\n                                    n_occ=args.n_homo, n_virt=args.n_lumo\n)\n\n\n\nprint(\"R%d/%d: loaded wfn, %.2fs\"%(mpi_rank, mpi_size, (time.time() - time0)))\nsys.stdout.flush()\ntime1 = time.time()\n\neval_reg = common.parse_eval_region_input(args.eval_region, cp2k_grid_orb.ase_atoms, cp2k_grid_orb.cell)\n\ncp2k_grid_orb.calc_morbs_in_region(args.dx,\n                                x_eval_region = eval_reg[0],\n                                y_eval_region = eval_reg[1],\n                                z_eval_region = eval_reg[2],\n                                reserve_extrap = args.extrap_extent,\n                                eval_cutoff = args.eval_cutoff)\n\nprint(\"R%d/%d: evaluated wfn, %.2fs\"%(mpi_rank, mpi_size, (time.time() - time1)))\nsys.stdout.flush()\ntime1 = time.time()\n\n### ------------------------------------------------------\n### Extrapolate orbitals\n### ------------------------------------------------------\n\nhart_cube = Cube()\nhart_cube.read_cube_file(args.hartree_file)\nextrap_plane_z = eval_reg[2][1] / ang_2_bohr - np.max(cp2k_grid_orb.ase_atoms.positions[:, 2])\nhart_plane = hart_cube.get_plane_above_topmost_atom(extrap_plane_z) - cp2k_grid_orb.ref_energy/hart_2_ev\n\ncp2k_grid_orb.extrapolate_morbs(hart_plane=hart_plane)\n\nprint(\"R%d/%d: extrapolated wfn, %.2fs\"%(mpi_rank, mpi_size, (time.time() - time1)))\nsys.stdout.flush()\ntime1 = time.time()\n\n### ------------------------------------------------------\n### Set up STM object\n### ------------------------------------------------------\n\nstm = css.STM(mpi_comm = comm, cp2k_grid_orb = cp2k_grid_orb)\nstm.gather_global_energies()\nstm.divide_by_space()\n\n### ------------------------------------------------------\n### Run STM-STS analysis for orbitals\n### ------------------------------------------------------\n\norb_heights = args.orb_heights if args.orb_heights is not None else []\norb_isovalues = args.orb_isovalues if args.orb_isovalues is not None else []\norb_fwhms = args.orb_fwhms if args.orb_fwhms is not None else []\n\nif len(orb_fwhms) != 0 and (len(orb_heights) != 0 or len(orb_isovalues) != 0):\n\n    orbital_list = list(range(-args.n_homo + 1, args.n_lumo + 1))\n\n    stm.create_orbital_images(orbital_list, orb_heights, orb_isovalues)\n\n    orbital_list_wrt_0 = list(np.array(orbital_list) + stm.cgo.i_homo_glob[0])\n    orbital_energies = stm.global_morb_energies[0][orbital_list_wrt_0]\n\n    stm.calculate_stm_maps(orb_fwhms, orb_isovalues, orb_heights, orbital_energies)\n\n    stm.collect_and_save_orb_maps(path=args.orb_output_file)\n\n### ------------------------------------------------------\n### Run STM-STS analysis for general energies\n### ------------------------------------------------------\n\nheights = args.heights if args.heights is not None else []\nisovalues = args.isovalues if args.isovalues is not None else []\nfwhms = args.fwhms if args.fwhms is not None else []\n\nif e_arr is not None and len(fwhms) != 0 and (len(heights) != 0 or len(isovalues) != 0):\n\n    stm.calculate_stm_maps(fwhms, isovalues, heights, e_arr)\n\n    stm.collect_and_save_stm_maps(path=args.output_file)\n\nprint(\"R%d/%d: finished, total time: %.2fs\"%(mpi_rank, mpi_size, (time.time() - time0)))\n", "meta": {"hexsha": "20fd5d63df99a3a29af9368526f0dee700de58f9", "size": 9161, "ext": "py", "lang": "Python", "max_stars_repo_path": "stm_sts_from_wfn.py", "max_stars_repo_name": "hifabian/atomistic_tools", "max_stars_repo_head_hexsha": "5b882e512405e6998a8dcec858b2da6e7cc59aeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stm_sts_from_wfn.py", "max_issues_repo_name": "hifabian/atomistic_tools", "max_issues_repo_head_hexsha": "5b882e512405e6998a8dcec858b2da6e7cc59aeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stm_sts_from_wfn.py", "max_forks_repo_name": "hifabian/atomistic_tools", "max_forks_repo_head_hexsha": "5b882e512405e6998a8dcec858b2da6e7cc59aeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5366666667, "max_line_length": 104, "alphanum_fraction": 0.596004803, "include": true, "reason": "import numpy", "num_tokens": 2208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.2720245392906821, "lm_q1q2_score": 0.16224445183032676}}
{"text": "\"\"\"Plots Figures 1, EDF Figures 1 and 7 in Gillett et al.\"\"\"\nimport logging\nimport os\nfrom pprint import pformat\nimport numpy as np\nimport csv\nimport matplotlib\nfrom scipy import stats\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport esmvaltool.diag_scripts.attribute.ncblendmask_esmval as ncbm\nimport random\nimport math\nimport sys\n\nfrom esmvaltool.diag_scripts.shared import (group_metadata, run_diagnostic,\n                                            select_metadata, sorted_metadata)\nfrom esmvaltool.diag_scripts.shared._base import (\n    ProvenanceLogger, get_diagnostic_filename, get_plot_filename)\nfrom esmvaltool.diag_scripts.shared.plot import quickplot\n\nlogger = logging.getLogger(os.path.basename(__file__))\nlogging.getLogger().addHandler(logging.StreamHandler(sys.stdout))\n\n\ndef main(cfg):\n    matplotlib.use('Agg')\n    plt.ioff() #Turn off interactive plotting.\n    # Get a description of the preprocessed data that we will use as input, as well as other flags.\n    input_data = cfg['input_data'].values()\n    auxiliary_data_dir=cfg['auxiliary_data_dir']\n    plot_dir=cfg['plot_dir']\n    output_file_type=cfg['output_file_type']\n    obs=cfg['obs']\n    if obs=='had5':\n        obs_file=auxiliary_data_dir+'/HadCRUT.5.0.1.0.anomalies.ensemble_mean.nc'\n        hadlabel='HadCRUT5'\n        ensobs=auxiliary_data_dir+'/HadCRUT.5.0.1.0.anomalies.' #If set apply multi-model analysis using ensemble obs data.\n    elif obs=='had4':\n        obs_file=auxiliary_data_dir+'/HadCRUT.4.6.0.0.median.nc'  #Updated to end of 2019.\n        hadlabel='HadCRUT4'\n        ensobs=auxiliary_data_dir+'/HadCRUT.4.6.0.0.anomalies.' #If set apply multi-model analysis using ensemble obs data.\n    else:\n        exit('Obs not recognised')\n    sftlf_file=auxiliary_data_dir+'/CNRM-CM6-1-5x5-sftlf.nc' #Hard-coded path to sftlf file for CNRM-CM6 on a 5x5 grid.\n\n    grouped_input_data = group_metadata(\n        input_data, 'dataset', sort='ensemble')\n    logger.info(\n        \"Group input data by model and sort by ensemble:\"\n        \"\\n%s\", pformat(grouped_input_data))\n    type (grouped_input_data)\n    nmodel=len(grouped_input_data)\n\n#Initialise variables.\n    experiments=['historical-ssp245','hist-GHG','hist-aer','hist-nat','hist-volc','hist-sol','hist-stratO3','hist-CO2','hist-GHG-ssp245-GHG','hist-aer-ssp245-aer','hist-nat-ssp245-nat']\n    labels=['Anthropogenic and natural forcings','Greenhouse gases','Aerosols','Natural forcings']\n    nexp=len(experiments)-3 #Subtract three to account for repetition of hist-GHG, hist-nat, hist-aer.\n    diag_name='gmst02' #Annual mean GMST.\n    ldiag=85 #length of diagnostic,hard-coded.\n    years=list(range(1850,2020,2)) #Used for plotting.\n    anom_max=500 #arbitrary max size for number of anomalies.\n    mean_diag=np.zeros((ldiag,nexp,nmodel))\n    mean_gmst_comp_warming=np.zeros((ldiag,nexp,nmodel))\n    mean_ann_warming=np.zeros((ldiag,nexp,nmodel))\n    mm_ann_warming=np.zeros((ldiag,nexp))\n    range_ann_warming=np.zeros((ldiag,nexp,2)) # 5-95% range.\n    nensmax=50\n    msval=1e20\n    all_ann_warming=np.full((ldiag,nexp,nmodel,nensmax),msval)\n    all_ann_warming_comp=np.full((ldiag,nexp,nmodel,nensmax),msval)\n    all_ann_warming_gsat=np.full((ldiag,nexp,nmodel,nensmax),msval)\n    ens_sizes=np.zeros((nexp,nmodel))\n    model_names=[]\n    ensobs_diag=[]\n    ensobs_dec_warming=[]\n\n\n#Set up figure including colours.\n    font = {'size'   : 5}\n    matplotlib.rc('font', **font)\n    mm_conv=0.0394\n    mod_cols=np.array([[0,73,73],[255,255,109],[0,146,146],[255,109,182],[255,182,119],[146,0,0],[0,109,219],[182,109,255],[109,182,255],[182,219,255],[73,0,146],[146,73,0],[219,209,0],[36,255,36]])/256.\n    cols=np.array([[0,0,0],[196,121,0],[178,178,178],[0,52,102],[0,79,0],[200,0,0],[0,200,0],[0,0,200],[112,160,205]])/256.\n    shade_cols=np.array([[128,128,128,128],[204,174,113,128],[191,191,191,128],[67,147,195,128],[223,237,195,128],[255,150,150,128],[150,255,150,128],[150,150,255,128],[91,174,178,128]])/256.\n\n    plt.figure(figsize=[88*mm_conv,113*mm_conv])\n    plt.subplot(211)\n\n#Loop over models, then experiments, then ensemble members.\n    for mm, dataset in enumerate(grouped_input_data):\n        logger.info(\"*************** Processing model %s\", dataset)\n        model_names.append(dataset)\n        lbl=dataset\n        grouped_model_input_data = group_metadata(\n            grouped_input_data[dataset], 'exp', sort='ensemble')\n        for exp in grouped_model_input_data:\n            logger.info(\"***** Processing experiment %s\", exp)\n            exp_string = [experiments.index(i) for i in experiments if exp == i]\n            experiment = exp_string[0]\n            #Label hist-nat-ssp245-nat as hist-nat, hist-ghg-ssp245-ghg as hist-ghg etc\n            #(some models' hist-nat ends in 2014 so is merged with ssp245-nat).\n            if experiment > 7: experiment=experiment-7\n            print ('*** Experiment',exp,'Index:',experiment)\n            grouped_exp_input_data = group_metadata(\n              grouped_model_input_data[exp], 'ensemble', sort='variable_group')\n            nens=len(grouped_exp_input_data)\n            ens_sizes[experiment,mm]=nens\n            exp_diags=np.zeros((ldiag,nens))\n            exp_ann_warming=np.zeros((ldiag,nens))\n            exp_gmst_comp_warming=np.zeros((ldiag,nens))\n\n\n            for ee, ensemble in enumerate(grouped_exp_input_data):\n                logger.info(\"** Processing ensemble %s\", ensemble)\n                for attributes in grouped_exp_input_data[ensemble]:\n                    logger.info(\"Processing variable %s\", attributes['variable_group'])\n                    file=attributes['filename']\n                logger.info(\"*************** Files for blend and mask %s\", file)\n                #Calculate masked and blended GMST for individual simulation.\n                (exp_diags[:,ee],obs_diag, dec_warming, obs_dec_warming, ann_warming, gmst_comp_warming)=ncbm.ncblendmask_esmval(\n                    file,obs_file,diag_name,ensobs,ensobs_diag,ensobs_dec_warming, cfg=cfg)\n                ensobs='' #Set to empty string so that ensemble obs diagnostics are only calculated on the first iteration.\n                #Take anomalies relative to 1850-1900.\n                exp_diags[:,ee]=exp_diags[:,ee]-np.mean(exp_diags[0:int(np.round((1901-1850)/2)),ee])\n                obs_diag=obs_diag-np.mean(obs_diag[0:int(np.round((1901-1850)/2))])\n                exp_ann_warming[:,ee]=ann_warming\n                exp_gmst_comp_warming[:,ee]=gmst_comp_warming\n                #Plot first ensemble member of historical.\n                if exp==\"historical-ssp245\" and ee==0:\n                    alpha_ens=1. if ee==0 else 0.2\n                    ls='dashed' if mm > 7 else 'solid'\n                    plt.plot(years,exp_diags[:,ee],color=mod_cols[mm],linewidth=0.5,label=lbl,zorder=1-ee,alpha=alpha_ens,linestyle=ls)\n                    lbl=\"\"\n            mean_diag[:,experiment,mm]=np.mean(exp_diags,axis=1)\n            mean_ann_warming[:,experiment,mm]=np.mean(exp_ann_warming,axis=1)\n            mean_gmst_comp_warming[:,experiment,mm]=np.mean(exp_gmst_comp_warming,axis=1)\n            all_ann_warming[:,experiment,mm,0:nens]=exp_diags #Use GMST.\n            all_ann_warming_comp[:,experiment,mm,0:nens]=exp_gmst_comp_warming #Use spatially complete GMST.\n            all_ann_warming_gsat[:,experiment,mm,0:nens]=exp_ann_warming #Use GSAT.\n\n    #Write GMST and GSAT timeseries to CSV file for other applications (not needed for Gillett et al. plots).\n    with open(plot_dir+'/cmip6_gmst.csv', mode='w') as file:\n        data_writer=csv.writer(file,delimiter=',',quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n        data_writer.writerow(['CMIP6 DAMIP models HadCRUT4-masked blended GMST (Cowtan et al., 2015) and globally-complete GSAT'])\n        for experiment in range(nexp):\n            data_writer.writerow(['Experiment:',experiments[experiment]])\n            for mm, dataset in enumerate(grouped_input_data):\n                data_writer.writerow([dataset])\n                for ee in range(int(ens_sizes[experiment,mm])):\n                    data_writer.writerow(['Ensemble member',ee])\n                    data_writer.writerow(['Year, GMST_complete, GMST_HadCRUT4_masked, GSAT'])\n                    for yy in range(ldiag):\n                        data_writer.writerow([years[yy],all_ann_warming[yy,experiment,mm,ee],all_ann_warming_comp[yy,experiment,mm,ee],all_ann_warming_gsat[yy,experiment,mm,ee]])\n\n#Calculate ratio of GSAT to GMST warming for individual simulations.\n    denom=np.mean(all_ann_warming[int((2010-1850)/2):int((2020-1850)/2),0,:,:],axis=0)\n    ratio_by_model=np.mean(all_ann_warming_gsat[int((2010-1850)/2):int((2020-1850)/2),0,:,:],axis=0)/denom\n    copy_ratio_by_model=np.reshape(ratio_by_model[:,:],nmodel*nensmax)\n#Equivalent calculation for spatially-complete GMST.\n    denom=np.mean(all_ann_warming_comp[int((2010-1850)/2):int((2020-1850)/2),0,:,:],axis=0)\n    ratio_by_model_comp=np.mean(all_ann_warming_gsat[int((2010-1850)/2):int((2020-1850)/2),0,:,:],axis=0)/denom\n    copy_ratio_by_model_comp=np.reshape(ratio_by_model_comp[:,:],nmodel*nensmax)\n\n\n    plt.plot(years,obs_diag,color='black',linewidth=1,label=hadlabel)\n    plt.plot(years,np.mean(mean_diag[:,0,:],axis=1),color=cols[1],linewidth=1,label='Model mean GMST')\n    plt.plot(years,np.mean(mean_ann_warming[:,0,:],axis=1),color='red',linewidth=1,label='Model mean GSAT')\n    plt.plot([1850,2020],[0,0],color='silver',linewidth=0.5,ls='--',zorder=0)\n    plt.axis([1850,2020,-2,3])\n    plt.xlabel('Year')\n    plt.ylabel('Global mean temperature anomaly ($^\\circ$C)')\n    plt.legend(loc=2, ncol=2, fontsize='x-small', fancybox=False, frameon=False, columnspacing=0.5,handlelength=1)\n    for experiment in range(nexp):\n        wts=np.zeros((nmodel,nensmax))\n        for mm in range(nmodel):\n            wts[mm,0:int(ens_sizes[experiment,mm])]=1./ens_sizes[experiment,mm]\n        wts=np.reshape(wts,nmodel*nensmax)/np.sum(wts)\n        if experiment==0:\n#Calculate ratio of GSAT to obs-masked GMST warming 5-95% range.\n           sort_ratio=np.sort(copy_ratio_by_model)\n           sort_index=np.argsort(copy_ratio_by_model)\n           cdf=np.cumsum(wts[sort_index])\n           range_ratio=[sort_ratio[cdf>=0.05][0],sort_ratio[cdf>=0.95][0]]\n           print ('5-95% range of ratio for GSAT/obs-masked GMST',range_ratio)\n#Equivalent calculation for spatially-complete GMST\n           sort_ratio=np.sort(copy_ratio_by_model_comp)\n           sort_index=np.argsort(copy_ratio_by_model_comp)\n           cdf=np.cumsum(wts[sort_index])\n           range_ratio=[sort_ratio[cdf>=0.05][0],sort_ratio[cdf>=0.95][0]]\n           print ('5-95% range of ratio for GSAT/spatially-complete GMST',range_ratio)\n        for yy in range(ldiag):\n                year_warming=np.reshape(all_ann_warming[yy,experiment,:,:],nmodel*nensmax)\n                sort_warming=np.sort(year_warming)\n                sort_index=np.argsort(year_warming)\n                cdf=np.cumsum(wts[sort_index])\n                range_ann_warming[yy,experiment,:]=[sort_warming[cdf>=0.05][0],sort_warming[cdf>=0.95][0]]\n                mm_ann_warming[yy,experiment]=np.sum(year_warming*wts)\n    plt.text (1825,2.25,'a',fontsize =7,fontweight='bold', va='center', ha='center')\n    plt.subplot(212)\n    zzs=[3,1,0,2]\n    for experiment in range(4):\n        offset=0\n        plt.fill_between(years,range_ann_warming[:,experiment,0]+offset,range_ann_warming[:,experiment,1]+offset,color=shade_cols[experiment+1,:],zorder=zzs[experiment])\n        plt.plot(years,mm_ann_warming[:,experiment]+offset,color=cols[experiment+1,:],linewidth=1,label=labels[experiment],zorder=zzs[experiment]+4)\n\n    plt.plot(years,obs_diag,color='black',linewidth=1,label=hadlabel,zorder=8)\n    plt.axis([1850,2020,-2,3])\n    plt.plot([1850,2020],[0,0],color='black',linewidth=0.5,ls='--',zorder=0)\n    plt.xlabel('Year')\n    plt.ylabel('Global mean surface temperature anomaly ($^\\circ$C)')\n    plt.legend(loc=2, ncol=2, fontsize='x-small', fancybox=False, frameon=False, columnspacing=0.5,handlelength=1)\n    plt.text (1825,2.25,'b',fontsize =7,fontweight='bold', va='center', ha='center')\n    plt.savefig(plot_dir+'/Fig1_'+obs+'.'+output_file_type)\n    plt.close()\n\n#Plot Extended Data Fig 1 showing all DAMIP GMST timeseries.\n    fig=plt.figure(figsize=[88*mm_conv,176*mm_conv])\n    ax1=fig.add_subplot(111)\n    for experiment in range(nexp):\n        offset=experiment*-1.5\n        plt.fill_between(years,range_ann_warming[:,experiment,0]+offset,range_ann_warming[:,experiment,1]+offset,color=shade_cols[experiment+1,:])\n        plt.plot([1850,2025],[offset,offset],color='black',linewidth=0.5)\n        plt.plot(years,mm_ann_warming[:,experiment]+offset,color=cols[experiment+1,:],linewidth=0.5,label=experiments[experiment])\n        plt.text(1860,offset+0.4,experiments[experiment])\n    plt.plot(years,obs_diag,color='black',linewidth=0.5,label=hadlabel,zorder=8)\n    ax1.set_xlim(1850,2020)\n    ax1.set_xlabel('Year')\n    ax1.set_ylim(-11,2)\n    plt.yticks(np.arange(27)*0.5-11,['','','-1.0','-0.5','0.0','0.5','1.0','','-1.0','-0.5','0.0','0.5','1.0','','-1.0','-0.5','0.0','0.5','1.0','','-1.0','-0.5','0.0','0.5','1.0','',''])\n    ax1.set_ylabel('Global mean surface temperature change ($^\\circ$C)')\n    ax2=ax1.twinx()\n    ax2.set_ylim(-11,2)\n    plt.yticks(np.arange(27)*0.5-11,['-0.5',' 0.0',' 0.5',' 1.0','','-1.0','-0.5',' 0.0',' 0.5',' 1.0','','-1.0','-0.5',' 0.0',' 0.5',' 1.0','','-1.0','-0.5',' 0.0',' 0.5',' 1.0','','','','',''])\n    plt.savefig(plot_dir+'/supplement_timeseries'+obs+'.'+output_file_type)\n    plt.close()\n\n#Calculate uncertainty in GMST and GSAT warming in obs (as reported in Gillett et al.).\n    ensobs_dec_warming=np.sort(ensobs_dec_warming)\n    enssize=len(ensobs_dec_warming)\n    print ('Obs GMST warming: mean, 5, 95%',np.mean(ensobs_dec_warming),ensobs_dec_warming[math.floor((enssize-1)*0.05)],ensobs_dec_warming[math.ceil((enssize-1)*0.95)])\n    nmc=10000\n    obs_gsat=np.zeros((nmc))\n    for mc_counter in range(nmc):\n      ens=random.randint(0,enssize-1)\n      mm=random.randint(0,nmodel-1)\n      ee=random.randint(0,ens_sizes[0,mm]-1)\n      obs_gsat[mc_counter]=ensobs_dec_warming[ens]*np.mean(all_ann_warming_gsat[int((2010-1850)/2):int((2020-1850)/2),0,mm,ee],axis=0)/np.mean(all_ann_warming[int((2010-1850)/2):int((2020-1850)/2),0,mm,ee],axis=0)\n    obs_gsat=np.sort(obs_gsat)\n    print ('Obs GSAT warming: mean, 5, 95%',np.mean(obs_gsat),obs_gsat[math.floor((nmc-1)*0.05)],obs_gsat[math.ceil((nmc-1)*0.95)])\n\n\nif __name__ == '__main__':\n\n    with run_diagnostic() as config:\n        main(config)\n", "meta": {"hexsha": "2caffaf87a2a0a1facecc5668eff3b1daa2c279b", "size": 14576, "ext": "py", "lang": "Python", "max_stars_repo_path": "esmvaltool/diag_scripts/attribute/damip_timeseries.py", "max_stars_repo_name": "malininae/ESMValTool", "max_stars_repo_head_hexsha": "9a1bf70a153135ebe2698e2275f6d6b1251e4d30", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-27T22:55:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T22:55:19.000Z", "max_issues_repo_path": "esmvaltool/diag_scripts/attribute/damip_timeseries.py", "max_issues_repo_name": "malininae/ESMValTool", "max_issues_repo_head_hexsha": "9a1bf70a153135ebe2698e2275f6d6b1251e4d30", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "esmvaltool/diag_scripts/attribute/damip_timeseries.py", "max_forks_repo_name": "malininae/ESMValTool", "max_forks_repo_head_hexsha": "9a1bf70a153135ebe2698e2275f6d6b1251e4d30", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.7159533074, "max_line_length": 213, "alphanum_fraction": 0.6669868277, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.1620968196691172}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"Model atmospheric emission and absorption for spectroscopic simulations.\n\nThe atmosphere model is responsible for calculating the spectral flux density\narriving at the telescope given a source flux entering the atmosphere. The\ncalculation is either performed as:\n\n.. math::\n\n    f(\\\\lambda) = 10^{-e(\\\\lambda) X / 2.5} s(\\\\lambda) + a b(\\\\lambda)\n\nif ``extinct_emission`` is False, or else as:\n\n.. math::\n\n    f(\\\\lambda) = 10^{-e(\\\\lambda) X / 2.5} \\\\left[\n    s(\\\\lambda) + a b(\\\\lambda)\\\\right]\n\nwhere :math:`s(\\\\lambda)` is the source flux entering the atmosphere,\n:math:`e(\\\\lambda)` is the zenith extinction, :math:`X` is the airmass,\n:math:`a` is the fiber entrance face area, and :math:`b(\\\\lambda)` is the\nsky emission surface brightness.  The sky brightness can optionally include\na scattered moonlight component.\n\nAn atmosphere model is usually initialized from a configuration used to create\na simulator and then accessible via its ``atmosphere`` attribute, for example:\n\n    >>> import specsim.simulator\n    >>> simulator = specsim.simulator.Simulator('test')  # doctest: +IGNORE_OUTPUT\n    >>> simulator.atmosphere.airmass\n    1.0\n\nSee :doc:`/api` for examples of changing model parameters defined in the\nconfiguration.  Certain parameters can also be changed after a model has\nbeen initialized, for example:\n\n    >>> simulator.atmosphere.airmass = 1.5\n    >>> simulator.atmosphere.moon.moon_phase = 0.25\n    >>> simulator.atmosphere.moon.moon_zenith = 25 * u.deg\n\nSee :class:`Atmosphere` and :class:`Moon` for details.\n\"\"\"\nfrom __future__ import print_function, division\n\nimport numpy as np\n\nimport astropy.units as u\n\nimport speclite.filters\n\nimport specsim.config\n\n\nclass Atmosphere(object):\n    \"\"\"Model atmospheric surface brightness and extinction.\n\n    A simulation uses only our read-only :attr:`surface_brightness` and\n    :attr:`extinction` attributes.  Use the :attr:`condition` and\n    :attr:`airmass` attributes to update this model.  Refer to the\n    :class:`moon model <Moon>` for details on updating the optional\n    scattered moon model.\n\n    Parameters\n    ----------\n    wavelength : astropy.units.Quantity\n        Array of wavelengths with units where data is tabulated.\n    surface_brightness_dict : dict\n        Dictionary of tabulated sky emission surface brightness values. Each\n        dictionary key defines a possible sky condition.\n    extinction_coefficient : array\n        Array of extinction coefficients tabulated on ``wavelength``.\n    extinct_emission : bool\n        If set, atmospheric extinction is applied to sky emission.\n    condition : str\n        Sky emission condition to use, which must be one of the keys\n        of ``surface_brightness_dict``.\n    seeing : dict or None\n        Dictionary of seeing PSF parameters to use which must contain keys\n        \"fwhm_ref\", \"wlen_ref\" and \"moffat_beta\".  Seeing is used to define\n        the atmospheric PSF, which is only used when\n        :attr:`instrument.fiberloss_method` equals \"galsim\".\n    airmass : float\n        Airmass of the observation.\n    moon : :class:`Moon` or None\n        Model to use for scattered moonlight.\n    \"\"\"\n    def __init__(self, wavelength, surface_brightness_dict,\n                 extinction_coefficient, extinct_emission, condition, airmass,\n                 seeing, moon):\n        self._wavelength = wavelength\n        self._surface_brightness_dict = surface_brightness_dict\n        self._extinction_coefficient = extinction_coefficient\n        self._extinct_emission = extinct_emission\n        self._condition_names = surface_brightness_dict.keys()\n        self._moon = moon\n        self.condition = condition\n        self.airmass = airmass\n        if seeing is not None:\n            for required in ('fwhm_ref', 'wlen_ref', 'moffat_beta'):\n                if required not in seeing:\n                    raise ValueError('Missing required seeing key \"{0}\"'\n                                     .format(required))\n        self._seeing = seeing\n\n\n    @property\n    def moon(self):\n        \"\"\"Moon or None: Model of scattered moonlight.\n\n        See :class:`Moon` for details on changing scattered moon simulation\n        parameters via this attribute.\n        \"\"\"\n        return self._moon\n\n\n    @property\n    def surface_brightness(self):\n        \"\"\"astropy.units.Quantity: Total sky surface brightness.\n\n        Includes both dark sky emission and (if configured) scattered moonlight.\n        Changes to :attr:`condition` or :attr:`airmass` are reflected here.\n        \"\"\"\n        sky = self._surface_brightness_dict[self.condition].copy()\n        if self._extinct_emission:\n            sky *= self.extinction\n        if self.moon is not None and self.moon.visible:\n            sky += self.moon.surface_brightness\n        return sky\n\n\n    @property\n    def extinction(self):\n        \"\"\"numpy.ndarray: The extinction factor for the current model airmass.\n\n        Tabulated as a function of wavelength. Changes to :attr:`airmass`\n        automatically update these values.\n        \"\"\"\n        return self._extinction\n\n\n    @property\n    def condition(self):\n        \"\"\"str: Sky emission condition.\n\n        Must be one of the predefined names in :attr:`condition_names`.\n        \"\"\"\n        return self._condition\n\n\n    @condition.setter\n    def condition(self, name):\n        if name not in self._condition_names:\n            raise ValueError(\n                \"Invalid condition '{0}'. Pick one of {1}.\"\n                .format(name, self._condition_names))\n        self._condition = name\n\n\n    @property\n    def condition_names(self):\n        \"\"\"list: The list of valid sky condition names.\n\n        The valid names are keys of the ``atmosphere.sky.table.paths`` node,\n        or \"default\" if only a single path is specified via a\n        ``atmosphere.sky.table.path`` node.\n        \"\"\"\n        return self._condition_names\n\n\n    @property\n    def airmass(self):\n        \"\"\"float: Observing airmass.\n\n        Changes to this value automatically propagate to our scattered\n        moon model, if there is one.\n        \"\"\"\n        return self._airmass\n\n\n    @airmass.setter\n    def airmass(self, airmass):\n        self._airmass = airmass\n        self._extinction = 10 ** (-self._extinction_coefficient * airmass / 2.5)\n        if self.moon is not None:\n            self.moon.airmass = airmass\n\n\n    @property\n    def seeing_moffat_beta(self):\n        \"\"\"float: Beta parameter for atmospheric Moffat profile.\n\n        Returns None if no seeing has been specified.\n        \"\"\"\n        return self._seeing['moffat_beta'] if self._seeing else None\n\n\n    @property\n    def seeing_wlen_ref(self):\n        \"\"\"float: Reference wavelength for :attr:`seeing_fwhm_ref`\n\n        Returns None if no seeing has been specified.\n        \"\"\"\n        return self._seeing['wlen_ref'] if self._seeing else None\n\n\n    @property\n    def seeing_fwhm_ref(self):\n        \"\"\"float: FWHM zenith seeing at :attr:`seeing_wlen_ref`.\n\n        Returns None if no seeing has been specified.\n        \"\"\"\n        return self._seeing['fwhm_ref'] if self._seeing else None\n\n\n    @seeing_fwhm_ref.setter\n    def seeing_fwhm_ref(self, fwhm_ref):\n        try:\n            self._seeing['fwhm_ref'] = fwhm_ref.to(u.arcsec)\n        except TypeError:\n            raise ValueError('Seeing has not been initialized.')\n        except (u.UnitConversionError, AttributeError):\n            raise ValueError('Invalid units for seeing_fwhm_ref.')\n\n\n    def get_seeing_fwhm(self, wavelength):\n        \"\"\"Calculate the seeing FWHM at the specified wavelength.\n\n        Assumes that seeing scales with wavelength with a power -1/5, as\n        predicted by Kolmogorov turbulence theory.\n\n        Parameters\n        ----------\n        wavelength : astropy.units.Quantity\n            Wavelength in units convertible to Angstroms.\n\n        Returns\n        -------\n        astropy.units.Quantity\n            Full-width half maximum of seeing distribution at the specified\n            wavelength, in on-sky angular units.\n        \"\"\"\n        wlen_ratio = (wavelength.to(u.Angstrom).value /\n                      self._seeing['wlen_ref'].to(u.Angstrom).value)\n        return self._seeing['fwhm_ref'] * wlen_ratio ** (-0.2)\n\n\n    def plot(self):\n        \"\"\"Plot a summary of this atmosphere model.\n\n        Requires that the matplotlib package is installed.\n        \"\"\"\n        import matplotlib.pyplot as plt\n\n        fig, ax1 = plt.subplots(figsize=(8, 4))\n        ax1_rhs = ax1.twinx()\n\n        wave = self._wavelength.to(u.Angstrom).value\n        wave_unit = u.Angstrom\n\n        sky_unit = 1e-17 * u.erg / (u.cm**2 * u.s * u.Angstrom * u.arcsec**2)\n        sky = self.surface_brightness.to(sky_unit).value\n        sky_min, sky_max = np.percentile(sky, (1, 99))\n\n        ext = self._extinction_coefficient\n        ext_min, ext_max = np.percentile(ext, (1, 99))\n\n        ax1.scatter(wave, sky, color='g', lw=0, s=1.)\n        if self.moon is not None and self.moon.visible:\n            moon = self.moon.surface_brightness.to(sky_unit).value\n            ax1.scatter(wave, moon, color='b', lw=0, s=1.)\n            # Adjust the vertical limits to include the moon.\n            moon_min, moon_max = np.percentile(moon, (1, 99))\n            sky_min = min(moon_min, sky_min)\n            sky_max = max(moon_max, sky_max)\n        ax1_rhs.scatter(wave, ext, color='r', lw=0, s=1.)\n\n        ax1.set_yscale('log')\n        ax1_rhs.set_yscale('log')\n\n        ax1.set_ylabel(\n            'Surface Brightness [$10^{-17}\\\\mathrm{erg}/(\\\\mathrm{cm}^2' +\n            '\\\\mathrm{s} \\\\AA)/\\\\mathrm{arcsec}^2$]')\n        ax1.set_ylim(0.5 * sky_min, 1.5 * sky_max)\n        ax1_rhs.set_ylabel('Zenith Extinction')\n        ax1_rhs.set_ylim(0.5 * ext_min, 1.5 * ext_max)\n\n        ax1.set_xlabel('Wavelength [$\\\\AA$]')\n        ax1.set_xlim(wave[0], wave[-1])\n\n        ncol = 2\n        ax1.plot([], [], 'g-',\n                 label='Total Emission ({0})'.format(self.condition))\n        if self.moon is not None and self.moon.visible:\n            ax1.plot([], [], 'b-', label='Scattered Moon')\n            ncol += 1\n        ax1.plot([], [], 'r-', label='Extinction')\n        ax1.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,\n                   ncol=ncol, mode='expand', borderaxespad=0.)\n\n\nclass Moon(object):\n    \"\"\"Model of scattered moonlight.\n\n    Most of the work is performed by :func:`krisciunas_schaefer`, which\n    implements the model of their 1991 paper. This class uses the predicted\n    V-band surface brightness to normalize an input lunar spectrum (or solar\n    spectrum if you assume the moon is grey).\n\n    The predicted :attr:`surface_brightness` is automatically updated to\n    reflect changes in the following attributes: :attr:`airmass`,\n    :attr:`moon_zenith`, :attr:`moon_phase` and :attr:`separation_angle`.\n\n    This implementation is loosely based on and tested against [IDL code]\n    (https://desi.lbl.gov/svn/code/desimodel/tags/0.4.2/pro/lunarmodel.pro)\n    from Connie Rockosi.\n\n    Parameters\n    ----------\n    wavelength : astropy.units.Quantity\n        Array of wavelengths with units where data is tabulated.\n    moon_spectrum : astropy.units.Quantity\n        Tabulated spectrum of scattered moonlight with units of flux density.\n        The normalization does not matter since it will be fixed by\n        :meth:`get_lunar_surface_brightness`.  A solar spectrum can be used,\n        which effectively assumes that the moon's reflectance is wavelength\n        independent.\n    extinction_coefficient : array\n        Array of extinction coefficients tabulated on ``wavelength``.\n    airmass : float\n        Airmass of the observation.\n    moon_zenith : astropy.units.Quantity\n        See :func:`krisciunas_schaefer`.\n    separation_angle : astropy.units.Quantity\n        See :func:`krisciunas_schaefer`.\n    moon_phase : float\n        See :func:`krisciunas_schaefer`.\n    \"\"\"\n    def __init__(self, wavelength, moon_spectrum, extinction_coefficient,\n                 airmass, moon_zenith, separation_angle, moon_phase):\n        self._wavelength = wavelength\n        self._moon_spectrum = moon_spectrum\n        self._extinction_coefficient = extinction_coefficient\n\n        # Calculate the V-band extinction of the moon spectrum.\n        self._vband = speclite.filters.load_filter('bessell-V')\n        V = self._vband.get_ab_magnitude(moon_spectrum, wavelength)\n        extinction = 10 ** (-extinction_coefficient / 2.5)\n        Vstar = self._vband.get_ab_magnitude(\n            moon_spectrum * extinction, wavelength)\n        self._vband_extinction = Vstar - V\n\n        # Initialize the model parameters.\n        self.airmass = airmass\n        self.moon_zenith = moon_zenith\n        self.separation_angle = separation_angle\n        self.moon_phase = moon_phase\n\n\n    def _update(self):\n        \"\"\"Update the model based on the current parameter values.\n        \"\"\"\n        self._update_required = False\n\n        if not self.visible:\n            self._surface_brightness = (\n                np.zeros_like(self._moon_spectrum) / (u.arcsec ** 2))\n            self._scattered_V = None\n            return\n\n        # Calculate the V-band surface brightness of scattered moonlight.\n        self._scattered_V = krisciunas_schaefer(\n            self.obs_zenith, self.moon_zenith, self.separation_angle,\n            self.moon_phase, self.vband_extinction)\n\n        # Calculate the wavelength-dependent extinction of moonlight\n        # scattered once into the observed field of view.\n        scattering_airmass = (\n            1 - 0.96 * np.sin(self.moon_zenith) ** 2) ** (-0.5)\n        extinction = (\n            10 ** (-self._extinction_coefficient * scattering_airmass / 2.5) *\n            (1 - 10 ** (-self._extinction_coefficient * self.airmass / 2.5)))\n        self._surface_brightness = self._moon_spectrum * extinction\n\n        # Renormalized the extincted spectrum to the correct V-band magnitude.\n        raw_V = self._vband.get_ab_magnitude(\n            self._surface_brightness, self._wavelength) * u.mag\n        area = 1 * u.arcsec ** 2\n        self._surface_brightness *= 10 ** (\n            -(self._scattered_V * area - raw_V) / (2.5 * u.mag)) / area\n\n\n    @property\n    def scattered_V(self):\n        \"\"\"V-band surface brightness of scattered moonlight.\n\n        This is a read-only attribute whose value depends\n        on the current values of :attr:`airmass`, :attr:`moon_zenith`,\n        :attr:`moon_phase` and :attr:`separation_angle`.  Returns None if\n        the moon is below the horizon.\n        \"\"\"\n        if self._update_required:\n            self._update()\n        return self._scattered_V\n\n\n    @property\n    def surface_brightness(self):\n        \"\"\"astropy.units.Quantity: Tabulated scattered moon surface brightness.\n\n        This is the only model attribute used for simulation. Its value depends\n        on the current values of :attr:`airmass`, :attr:`moon_zenith`,\n        :attr:`moon_phase` and :attr:`separation_angle`.\n        \"\"\"\n        if self._update_required:\n            self._update()\n        return self._surface_brightness\n\n\n    @property\n    def airmass(self):\n        \"\"\"Airmass of observation used for lunar scattering model.\n\n        Changes to this value will update :attr:`obs_zenith` and\n        :attr:`surface_brightness`.\n\n        This should normally be the same airmass that is used in the\n        :class:`Atmosphere` model to calculate source extinction, but this\n        is not checked here.\n        \"\"\"\n        return self._airmass\n\n\n    @airmass.setter\n    def airmass(self, airmass):\n        # Remove any dimensionless astropy.units.Quantity wrapper since\n        # np.arcsin(Quantity(1)) has u.rad added automatically, but we\n        # add it explicitly below.\n        self._airmass = np.float(airmass)\n        # Estimate the zenith angle corresponding to this observing airmass.\n        # We invert eqn.3 of KS1991 for this (instead of eqn.14).\n        self._obs_zenith = np.arcsin(\n            np.sqrt((1 - self._airmass ** -2) / 0.96)) * u.rad\n        self._update_required = True\n\n\n    @property\n    def visible(self):\n        \"\"\"bool: Read-only visibility of the moon.\n\n        The visibility criterion is :attr:`moon_zenith` < 90 degrees.\n        \"\"\"\n        return self._visible\n\n\n    @property\n    def moon_phase(self):\n        \"\"\"Phase of the moon.\n\n        See :func:`krisciunas_schaefer`. Changes to this value will update\n        :attr:`surface_brightness`.\n        \"\"\"\n        return self._moon_phase\n\n\n    @moon_phase.setter\n    def moon_phase(self, moon_phase):\n        self._moon_phase = moon_phase\n        self._update_required = True\n\n\n    @property\n    def obs_zenith(self):\n        \"\"\"Read-only value of the observing zenith angle.\n\n        This attribute is calculated from :attr:`airmass` by inverting\n        Eqn.3 of Krisciunas & Schaefer 1991:\n\n        .. math::\n\n            X = (1 - 0.96 \\\\sin^2 Z)^{-0.5}\n        \"\"\"\n        return self._obs_zenith\n\n\n    @property\n    def moon_zenith(self):\n        \"\"\"Moon zenith angle.\n\n        See :func:`krisciunas_schaefer`. Changes to this value will update\n        :attr:`surface_brightness` and :attr:`visible`.\n        \"\"\"\n        return self._moon_zenith\n        self._update_required = True\n\n\n    @moon_zenith.setter\n    def moon_zenith(self, moon_zenith):\n        self._moon_zenith = moon_zenith\n        self._visible = self._moon_zenith < 90 * u.deg\n\n\n    @property\n    def separation_angle(self):\n        \"\"\"Read-only value of the observation-moon separation angle.\n\n        See :func:`krisciunas_schaefer`. Changes to this value will update\n        :attr:`surface_brightness`.\n        \"\"\"\n        return self._separation_angle\n\n\n    @separation_angle.setter\n    def separation_angle(self, separation_angle):\n        self._separation_angle = separation_angle\n        self._update_required = True\n\n\n    @property\n    def vband_extinction(self):\n        \"\"\"Read-only value of the V-band extinction of the moon spectrum.\n\n        Calculated as V* - V where V is the Bessell-V magnitude of the\n        input lunar spectrum and V* is calculated with airmass 1.0\n        extinction applied.\n        \"\"\"\n        return self._vband_extinction\n\n\ndef krisciunas_schaefer(obs_zenith, moon_zenith, separation_angle, moon_phase,\n                        vband_extinction):\n    \"\"\"Calculate the scattered moonlight surface brightness in V band.\n\n    Based on Krisciunas and Schaefer, \"A model of the brightness of moonlight\",\n    PASP, vol. 103, Sept. 1991, p. 1033-1039 (http://dx.doi.org/10.1086/132921).\n    Equation numbers in the code comments refer to this paper.\n\n    The function :func:`plot_lunar_brightness` provides a convenient way to\n    plot this model's predictions as a function of observation pointing.\n\n    Units are required for the angular inputs and the result has units of\n    surface brightness, for example:\n\n    >>> sb = krisciunas_schaefer(20*u.deg, 70*u.deg, 50*u.deg, 0.25, 0.15)\n    >>> print(np.round(sb, 3))\n    19.855 mag / arcsec2\n\n    The output is automatically broadcast over input arrays following the usual\n    numpy rules.\n\n    This method has several caveats but the authors find agreement with data at\n    the 8% - 23% level.  See the paper for details.\n\n    Parameters\n    ----------\n    obs_zenith : astropy.units.Quantity\n        Zenith angle of the observation in angular units.\n    moon_zenith : astropy.units.Quantity\n        Zenith angle of the moon in angular units.\n    separation_angle : astropy.units.Quantity\n        Opening angle between the observation and moon in angular units.\n    moon_phase : float\n        Phase of the moon from 0.0 (full) to 1.0 (new), which can be calculated\n        as abs((d / D) - 1) where d is the time since the last new moon\n        and D = 29.5 days is the period between new moons.  The corresponding\n        illumination fraction is ``0.5*(1 + cos(pi * moon_phase))``.\n    vband_extinction : float\n        V-band extinction coefficient to use.\n\n    Returns\n    -------\n    astropy.units.Quantity\n        Observed V-band surface brightness of scattered moonlight.\n    \"\"\"\n    moon_phase = np.asarray(moon_phase)\n    if np.any((moon_phase < 0) | (moon_phase > 1)):\n        raise ValueError(\n            'Invalid moon phase {0}. Expected 0-1.'.format(moon_phase))\n    # Calculate the V-band magnitude of the moon (eqn. 9).\n    abs_alpha = 180. * moon_phase\n    m = -12.73 + 0.026 * abs_alpha + 4e-9 * abs_alpha ** 4\n    # Calculate the illuminance of the moon outside the atmosphere in\n    # foot-candles (eqn. 8).\n    Istar = 10 ** (-0.4 * (m + 16.57))\n    # Calculate the scattering function (eqn.21).\n    rho = separation_angle.to(u.deg).value\n    f_scatter = (10 ** 5.36 * (1.06 + np.cos(separation_angle) ** 2) +\n                 10 ** (6.15 - rho / 40.))\n    # Calculate the scattering airmass along the lines of sight to the\n    # observation and moon (eqn. 3).\n    X_obs = (1 - 0.96 * np.sin(obs_zenith) ** 2) ** (-0.5)\n    X_moon = (1 - 0.96 * np.sin(moon_zenith) ** 2) ** (-0.5)\n    # Calculate the V-band moon surface brightness in nanoLamberts.\n    B_moon = (f_scatter * Istar *\n        10 ** (-0.4 * vband_extinction * X_moon) *\n        (1 - 10 ** (-0.4 * (vband_extinction * X_obs))))\n    # Convert from nanoLamberts to to mag / arcsec**2 using eqn.19 of\n    # Garstang, \"Model for Artificial Night-Sky Illumination\",\n    # PASP, vol. 98, Mar. 1986, p. 364 (http://dx.doi.org/10.1086/131768)\n    return ((20.7233 - np.log(B_moon / 34.08)) / 0.92104 *\n            u.mag / (u.arcsec ** 2))\n\n\ndef plot_lunar_brightness(moon_zenith, moon_azimuth, moon_phase,\n                          vband_extinction=0.162, ngrid=250,\n                          cmap='YlGnBu', figure_size=(8, 6)):\n    \"\"\"Create a polar plot of the scattered moon brightness in V band.\n\n    Evaluates the model of :func:`krisciunas_schaefer` on a polar grid of\n    observation pointings, for a fixed moon position and phase.\n\n    This method requires that matplotlib is installed.\n\n    Parameters\n    ----------\n    moon_zenith : astropy.units.Quantity\n        See :func:`krisciunas_schaefer`.\n    moon_azimuth : astropy.units.Quantity\n        Aziumuthal angle of the moon in angular units.  Azimuth is measured\n        clockwize from zero (North).\n    moon_phase : float\n        See :func:`krisciunas_schaefer`.\n    vband_extinction : float\n        See :func:`krisciunas_schaefer`.\n    ngrid : int\n        Size of observing location zenith and azimuth grids to use.\n    cmap : str\n        Name of the matplotlib color map to use.\n    figure_size : tuple or None\n        Tuple (width, height) giving the figure dimensions in inches.\n\n    Returns\n    -------\n    tuple\n        Tuple (fig, ax, cax) of matplotlib objects created for this plot. You\n        can ignore these unless you want to make further changes to the plot.\n    \"\"\"\n    import matplotlib.pyplot as plt\n\n    # Build a grid in observation (zenith, azimuth).\n    # Build a grid in observation (zenith, azimuth).\n    obs_zenith = np.linspace(0., 90., ngrid, endpoint=False) * u.deg\n    obs_az = (np.linspace(0., 360., ngrid) * u.deg)[:, np.newaxis]\n\n    # Calculate the separation angles.\n    cos_sep = (np.cos(moon_zenith) * np.cos(obs_zenith) +\n               np.cos(moon_azimuth - obs_az) * np.sin(moon_zenith) *\n               np.sin(obs_zenith))\n    sep = np.arccos(cos_sep)\n\n    # Calculate the V-band moon brightness.\n    moon_V = krisciunas_schaefer(\n        obs_zenith, moon_zenith, sep, moon_phase, vband_extinction)\n\n    # Initialize the plot. We are borrowing from:\n    # http://blog.rtwilson.com/producing-polar-contour-plots-with-matplotlib/\n    fig, ax = plt.subplots(\n        figsize=figure_size, subplot_kw=dict(projection='polar'))\n    r, theta = np.meshgrid(\n        obs_zenith.to(u.deg).value, obs_az.to(u.rad).value[:,0], copy=False)\n    ax.set_theta_zero_location('N')\n    ax.set_theta_direction(-1)\n    ax.set_ylim(0., 90.)\n\n    # Draw a polar contour plot.\n    cax = ax.contourf(theta, r, moon_V.value, 50, cmap=cmap)\n    fig.colorbar(cax).set_label('Scattered Moon V [mag/arcsec2]')\n\n    # Draw a point indicating the moon position.\n    plt.scatter(moon_azimuth.to(u.rad).value, moon_zenith.to(u.deg).value,\n                s=150., marker='o', color='w', lw=0.5, edgecolor='k')\n\n    # Add labels.\n    xy, coords = (1., 0.), 'axes fraction'\n    plt.annotate('$k_V$ = {0:.3f}'.format(vband_extinction),\n                 xy, xy, coords, coords,\n                 horizontalalignment='right', verticalalignment='top',\n                 size='x-large', color='k')\n    xy, coords = (0., 0.), 'axes fraction'\n    plt.annotate('$\\\\phi$ = {0:.1f}%'.format(100. * moon_phase),\n                 xy, xy, coords, coords,\n                 horizontalalignment='left', verticalalignment='top',\n                 size='x-large', color='k')\n\n    plt.tight_layout()\n    return fig, ax, cax\n\n\ndef initialize(config):\n    \"\"\"Initialize the atmosphere model from configuration parameters.\n\n    After an atmosphere model has been initialized, further changes to the\n    input configuration will no effect unless this method is called to\n    initialize a new model. However, certain model attributes can be\n    varied after a model is initialized.  See :class:`Atmosphere` and\n    :class:`Moon` for details.\n\n    Parameters\n    ----------\n    config : :class:`specsim.config.Configuration`\n        The configuration parameters to use.\n\n    Returns\n    -------\n    Atmosphere\n        An initialized :class:`atmosphere model <Atmosphere>`, possibly\n        containing a :class:`scattered moonlight model <Moon>`.\n    \"\"\"\n    atm_config = config.atmosphere\n\n    # Load tabulated data.\n    surface_brightness_dict = config.load_table(\n        atm_config.sky, 'surface_brightness', as_dict=True)\n    extinction_coefficient = config.load_table(\n        atm_config.extinction, 'extinction_coefficient')\n\n    # Initialize an optional atmospheric seeing PSF.\n    psf_config = getattr(atm_config, 'seeing', None)\n    if psf_config:\n        seeing = dict(\n            fwhm_ref=specsim.config.parse_quantity(psf_config.fwhm_ref),\n            wlen_ref=specsim.config.parse_quantity(psf_config.wlen_ref),\n            moffat_beta=float(psf_config.moffat_beta))\n    else:\n        seeing = None\n\n    # Initialize an optional lunar scattering model.\n    moon_config = getattr(atm_config, 'moon', None)\n    if moon_config:\n        moon_spectrum = config.load_table(moon_config, 'flux')\n        c = config.get_constants(moon_config,\n            ['moon_zenith', 'separation_angle', 'moon_phase'])\n        moon = Moon(\n            config.wavelength, moon_spectrum, extinction_coefficient,\n            atm_config.airmass, c['moon_zenith'], c['separation_angle'],\n            c['moon_phase'])\n    else:\n        moon = None\n\n    atmosphere = Atmosphere(\n        config.wavelength, surface_brightness_dict, extinction_coefficient,\n        atm_config.extinct_emission, atm_config.sky.condition,\n        atm_config.airmass, seeing, moon)\n\n    if config.verbose:\n        print(\n            \"Atmosphere initialized with condition '{0}' from {1}.\"\n            .format(atmosphere.condition, atmosphere.condition_names))\n        if seeing:\n            print('Seeing is {0} at {1} with Moffat beta {2}.'\n                  .format(seeing['fwhm_ref'], seeing['wlen_ref'],\n                          seeing['moffat_beta']))\n        if moon:\n            print(\n                'Lunar V-band extinction coefficient is {0:.5f}.'\n                .format(moon.vband_extinction))\n\n    return atmosphere\n", "meta": {"hexsha": "4259854fa3500b55378a8a7d631078bb1490201d", "size": 27548, "ext": "py", "lang": "Python", "max_stars_repo_path": "specsim/atmosphere.py", "max_stars_repo_name": "michaelJwilson/specsim", "max_stars_repo_head_hexsha": "0e3e1b3fa84282b32d61c3c8f189fe98c1a327cf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-12-08T23:31:00.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-18T19:01:02.000Z", "max_issues_repo_path": "specsim/atmosphere.py", "max_issues_repo_name": "michaelJwilson/specsim", "max_issues_repo_head_hexsha": "0e3e1b3fa84282b32d61c3c8f189fe98c1a327cf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 104, "max_issues_repo_issues_event_min_datetime": "2015-09-15T17:33:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T18:11:03.000Z", "max_forks_repo_path": "specsim/atmosphere.py", "max_forks_repo_name": "michaelJwilson/specsim", "max_forks_repo_head_hexsha": "0e3e1b3fa84282b32d61c3c8f189fe98c1a327cf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2016-01-21T08:54:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-02T19:18:28.000Z", "avg_line_length": 36.3430079156, "max_line_length": 82, "alphanum_fraction": 0.6432045884, "include": true, "reason": "import numpy,import astropy", "num_tokens": 6803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.3007455664065234, "lm_q1q2_score": 0.16209680953511332}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Built-in imports\nimport warnings\nimport itertools\n\n# 3rd party imports\nimport numpy as np\nimport xarray as xr\n\nfrom scipy import constants\n\n# Local imports\nfrom ..pyrf import iso86012datetime64, time_clip, ts_scalar, ts_skymap\n\nfrom .psd_rebin import psd_rebin\n\n__author__ = \"Louis Richard\"\n__email__ = \"louisr@irfu.se\"\n__copyright__ = \"Copyright 2020-2021\"\n__license__ = \"MIT\"\n__version__ = \"2.3.7\"\n__status__ = \"Prototype\"\n\n\ndef _coord_sys(coord_sys):\n    x_vec = coord_sys[0, :] / np.linalg.norm(coord_sys[0, :])\n    y_vec = coord_sys[1, :] / np.linalg.norm(coord_sys[1, :])\n\n    z_vec = np.cross(x_vec, y_vec) / np.linalg.norm(np.cross(x_vec, y_vec))\n    y_vec = np.cross(z_vec, x_vec) / np.linalg.norm(np.cross(z_vec, x_vec))\n\n    changed_xyz = [False, False, False]\n\n    for i, vec, c in zip([0, 1, 2], [x_vec, y_vec, z_vec], [\"x\", \"y\", \"z\"]):\n        if abs(np.rad2deg(np.arccos(np.dot(vec, coord_sys[:, i])))) > 1.:\n            msg = \" \".join([\"In making 'xyz' a right handed orthogonal\"\n                            \"coordinate system, {}\".format(c, i),\n                            \"(in-plane {:d}) was changed from\",\n                            np.array2string(coord_sys[:, i]),\n                            \"to\",\n                            np.array2string(x_vec),\n                            \"Please verify that this is according to your\"\n                            \"intentions.\"])\n            warnings.warn(msg, UserWarning)\n            changed_xyz[i] = True\n\n    return x_vec, y_vec, z_vec, changed_xyz\n\n\ndef _init(vdf, tint):\n    assert isinstance(vdf, xr.Dataset), \"vdf must be a xarray.Dataset\"\n\n    len_e = 32\n\n    if vdf.phi.data.ndim == 1:\n        phi = xr.DataArray(np.tile(vdf.phi.data, (len(vdf.data), 1)),\n                           coords=[vdf.time.data,\n                                   np.arange(len(vdf.phi.data))],\n                           dims=[\"time\", \"idx\"])\n    else:\n        phi = vdf.phi\n\n    theta = vdf.theta\n    polar = np.deg2rad(theta)\n    azimuthal = np.deg2rad(phi)\n    step_table = vdf.attrs.get(\"esteptable\", np.zeros(len(vdf.time)))\n\n    energy0 = vdf.attrs.get(\"energy0\", vdf.energy.data[0, :])\n    energy1 = vdf.attrs.get(\"energy1\", vdf.energy.data[1, :])\n\n    diff_energ = np.median(np.diff(np.log10(energy0))) / 2\n\n    energy0_edges = np.hstack([10 ** (np.log10(energy0) - diff_energ),\n                               10 ** (np.log10(energy0[-1]) + diff_energ)])\n    energy1_edges = np.hstack([10 ** (np.log10(energy1) - diff_energ),\n                               10 ** (np.log10(energy1[-1]) + diff_energ)])\n\n    if tint is not None and len(tint) == 1:\n        t_id = np.argmin(\n            np.abs(vdf.time.data - iso86012datetime64(np.array(tint))[0]))\n\n        dist = vdf.data.data[t_id, ...]\n        dist = dist[None, ...]\n        step_table = step_table[t_id]\n        azimuthal = azimuthal[t_id, ...]\n\n        if step_table.data:\n            energy_edges = energy1_edges\n        else:\n            energy_edges = energy1_edges\n\n    elif tint is not None and len(tint) == 2:\n        dist = time_clip(vdf.data, tint)\n        step_table = ts_scalar(vdf.time.data, step_table)\n        step_table = time_clip(step_table, tint)\n        azimuthal = time_clip(azimuthal, tint)\n\n        if len(dist.time) > 1 and list(energy0) != list(energy1):\n            print(\"notice: Rebinning distribution.\")\n            temp = ts_skymap(dist.time.data, dist, time_clip(vdf.energy, tint),\n                             np.rad2deg(azimuthal), theta)\n            newt, dist, energy, phi = psd_rebin(temp, phi, energy0, energy1,\n                                                step_table)\n            dist = ts_skymap(newt, dist, np.tile(energy, (len(newt), 1)), phi,\n                             theta)\n            dist = time_clip(dist.data, tint).data\n            azimuthal = xr.DataArray(phi,\n                                     coords=[newt, np.arange(phi.shape[1])],\n                                     dims=[\"time\", \"odx\"])\n            len_e = dist.shape[1]\n            energy_edges = np.hstack(\n                [10 ** (np.log10(energy) - diff_energ / 2),\n                 10 ** (np.log10(energy[-1]) + diff_energ / 2)])\n        else:\n            if all(step_table.data):\n                energy_edges = energy1_edges\n            else:\n                energy_edges = energy0_edges\n    else:\n        raise ValueError(\"Invalid time interval\")\n\n    return dist, polar.data, azimuthal.data, energy_edges, len_e\n\n\ndef _cotrans(dist, polar, azimuthal, x_vec, y_vec, z_vec, e_lim,\n             bin_corr):\n    # Construct polar and azimuthal angle matrices\n    polar = np.ones((len(dist), 1)) * polar\n\n    f_mat = np.zeros((len(dist), dist.shape[2], dist.shape[1]))  #\n    # azimuthal, energy\n    edges_az = np.linspace(0, 2 * np.pi, azimuthal.shape[1] + 1)\n\n    for i in range(len(dist)):\n        pol_mat, azm_mat = np.meshgrid(polar[i, :], azimuthal[i, :])\n\n        # '-' because the data shows which direction the particles were\n        # coming from\n        x_mat = -np.sin(pol_mat) * np.cos(azm_mat)\n        y_mat = -np.sin(pol_mat) * np.sin(azm_mat)\n        z_mat = -np.cos(pol_mat)\n\n        # Transform into different coordinate system\n        xx_mat = np.reshape(x_mat, (x_mat.shape[0] * x_mat.shape[1], 1))\n        yy_mat = np.reshape(y_mat, (y_mat.shape[0] * y_mat.shape[1], 1))\n        zz_mat = np.reshape(z_mat, (z_mat.shape[0] * z_mat.shape[1], 1))\n\n        new_tmp_x = np.dot(np.hstack([xx_mat, yy_mat, zz_mat]), x_vec)\n        new_tmp_y = np.dot(np.hstack([xx_mat, yy_mat, zz_mat]), y_vec)\n        new_tmp_z = np.dot(np.hstack([xx_mat, yy_mat, zz_mat]), z_vec)\n\n        new_x_mat = np.reshape(new_tmp_x, (x_mat.shape[0], x_mat.shape[1]))\n        new_y_mat = np.reshape(new_tmp_y, (x_mat.shape[0], x_mat.shape[1]))\n        new_z_mat = np.reshape(new_tmp_z, (x_mat.shape[0], x_mat.shape[1]))\n\n        elevation_angle = np.arctan(\n            new_z_mat / np.sqrt(new_x_mat ** 2 + new_y_mat ** 2))\n        plane_az = np.arctan2(new_y_mat, new_x_mat) + np.pi\n\n        # gets velocity in direction normal to 'z'-axis\n        geo_factor_elev = np.cos(elevation_angle)\n\n        # geoFactorBinSize - detector bins in 'equator' plane are bigger and\n        # get a larger weight. I think this is not good for the\n        # implementation in this function\n        if bin_corr:\n            geo_factor_bin_size = np.sin(pol_mat)\n        else:\n            geo_factor_bin_size = np.ones(pol_mat.shape)\n\n        f_mat[i, ...] = _cotrans_jit(dist.data[i, ...], elevation_angle, e_lim,\n                                     plane_az, edges_az, geo_factor_elev,\n                                     geo_factor_bin_size)\n\n    return f_mat\n\n\ndef _cotrans_jit(dist, elevation_angle, elevation_lim, plane_az, edges_az,\n                 geo_factor_elev, geo_factor_bin_size):\n    out = np.zeros((dist.shape[1], dist.shape[0]))  # azimuthal, energy\n\n    for ie, iaz in itertools.product(range(dist.shape[0]),\n                                     range(dist.shape[1])):\n        # dist.data has dimensions nT x nE x nAz x nPol\n        c_mat = dist[ie, ...].copy()\n        c_mat = c_mat * geo_factor_elev * geo_factor_bin_size\n        c_mat[np.abs(elevation_angle) > np.deg2rad(elevation_lim)] = np.nan\n        # use 0.1 deg to fix Az angle edges bug\n        c_mat[plane_az < edges_az[iaz] - np.deg2rad(.1)] = np.nan\n        # use 0.1 deg to fix Az angle edges bug\n        c_mat[plane_az > edges_az[iaz + 1] + np.deg2rad(.1)] = np.nan\n\n        out[iaz, ie] = np.nanmean(c_mat)\n\n    return out\n\n\ndef vdf_projection(vdf, tint, coord_sys: np.ndarray = np.eye(3),\n                   sc_pot: xr.DataArray = None, e_lim: float = 20,\n                   bins_correction: bool = False):\n    r\"\"\"Computes projection of the velocity distribution onto a specified\n    plane.\n\n    Parameters\n    ----------\n    vdf : xarray.Dataset\n        Electron or ion 3D skymap velocity distribution function.\n    tint : list of str\n        Computes data for time interval if len(tint) = 2 or closest time if\n        len(tint) = 1. For tint includes two or more distributions the\n        energies are rebinned into 64 channels.\n    coord_sys : ndarray, Optional\n        3x3 matrix with 1st column is x, 2nd column is y and 3rd column is z.\n        z is normal to the projection plane and x and y are made orthogonal to\n        z and each other if they are not already. Default is np.eye(3)\n        (project onto spacecraft spin plane).\n    sc_pot : xarray.DataArray, Optional\n        Spacecraft potential to correct velocities. For a single value of tint\n        the closest potential is used. For an interval the spacecraft\n        potential is average over that interval. Default is None (no\n        correction).\n    e_lim : float, Optional\n        Elevation angle limit in degrees above/below projection plane to\n        include in projection. Default is e_lim = 20.\n    bins_correction : bool, Optional\n        Flag to correction elevation bins. Default is False.\n\n    Returns\n    -------\n    v_x : ndarray\n        2D grid of the velocities in the x direction.\n    v_y : ndarray\n        2D grid of the velocities in the y direction.\n    f_mat : ndarray\n        2D projection of the velocity distribution onto the specified plane\n\n    \"\"\"\n\n    specie = vdf.attrs.get(\"species\", \"electrons\")\n    is_des = specie.lower() == \"electrons\"\n\n    dist, polar, azimuthal, energy_edges, len_e = _init(vdf, tint)\n    x_vec, y_vec, z_vec, changed_xyz = _coord_sys(coord_sys)\n\n    if azimuthal.ndim == 1:\n        azimuthal = np.ones((len(dist), 1)) * azimuthal\n\n    f_mat = _cotrans(dist, polar, azimuthal, x_vec, y_vec, z_vec, e_lim,\n                     bins_correction)\n    if len(dist) == 1:\n        f_mat = np.squeeze(f_mat)\n    else:\n        f_mat = np.squeeze(np.nanmean(f_mat, axis=0))\n\n    if sc_pot is not None:\n        if len(tint) == 1:\n            time_datetime64 = iso86012datetime64(np.array(tint))[0]\n            t_id = np.argmin(np.abs(sc_pot.time.data - time_datetime64))\n            sc_pot = sc_pot.data[t_id]\n        else:\n            sc_pot = time_clip(sc_pot, tint)\n            sc_pot = np.nanmean(sc_pot.data)\n    else:\n        sc_pot = 0.\n\n    if is_des:\n        mass = constants.electron_mass\n    else:\n        mass = constants.proton_mass\n        sc_pot *= -1\n\n    q_e = constants.elementary_charge\n\n    speed_table = np.sqrt((energy_edges - sc_pot) * q_e * 2 / mass)\n    speed_table = np.real(speed_table * 1e-3)  # km/s\n\n    r_en = speed_table\n    v_x = np.matmul(r_en[:, None],\n                    np.cos(np.linspace(0, 2 * np.pi, azimuthal.shape[1] + 1)\n                           + np.pi)[None, :])\n    v_y = np.matmul(r_en[:, None],\n                    np.sin(np.linspace(0, 2 * np.pi, azimuthal.shape[1] + 1)\n                           + np.pi)[None, :])\n\n    f_mat[f_mat <= 0] = np.nan\n\n    return v_x, v_y, f_mat\n", "meta": {"hexsha": "a2c27c048918a4a2ac13dde26c94d57a53936ad4", "size": 10880, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyrfu/mms/vdf_projection.py", "max_stars_repo_name": "ablotekar/irfu-python", "max_stars_repo_head_hexsha": "740cb51ca9ce2ab0d62cb6fef3a7a722d430d79e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-27T11:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-17T11:08:10.000Z", "max_issues_repo_path": "pyrfu/mms/vdf_projection.py", "max_issues_repo_name": "ablotekar/irfu-python", "max_issues_repo_head_hexsha": "740cb51ca9ce2ab0d62cb6fef3a7a722d430d79e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-04T07:55:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-10T12:45:27.000Z", "max_forks_repo_path": "pyrfu/mms/vdf_projection.py", "max_forks_repo_name": "ablotekar/irfu-python", "max_forks_repo_head_hexsha": "740cb51ca9ce2ab0d62cb6fef3a7a722d430d79e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-17T11:08:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-18T18:41:42.000Z", "avg_line_length": 37.5172413793, "max_line_length": 79, "alphanum_fraction": 0.5809742647, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3140505514119072, "lm_q1q2_score": 0.16193071885177415}}
{"text": "#!/usr/bin/env python\n# encoding: utf-8\n\n################################################################################\n#\n#   RPMDrate - Bimolecular reaction rates via ring polymer molecular dynamics\n#\n#   Copyright (c) 2012 by Joshua W. Allen (jwallen@mit.edu)\n#                         William H. Green (whgreen@mit.edu)\n#                         Yury V. Suleimanov (ysuleyma@mit.edu, ysuleyma@princeton.edu)\n#\n#   Permission is hereby granted, free of charge, to any person obtaining a \n#   copy of this software and associated documentation files (the \"Software\"), \n#   to deal in the Software without restriction, including without limitation\n#   the rights to use, copy, modify, merge, publish, distribute, sublicense, \n#   and/or sell copies of the Software, and to permit persons to whom the \n#   Software is furnished to do so, subject to the following conditions:\n#\n#   The above copyright notice and this permission notice shall be included in\n#   all copies or substantial portions of the Software.\n#\n#   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n#   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n#   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n#   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n#   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING \n#   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER \n#   DEALINGS IN THE SOFTWARE. \n#\n################################################################################\n\n\"\"\"\nThis module contains representations of various thermostats available in RPMD.\n\"\"\"\n\nimport os.path\nimport numpy\n\nimport rpmdrate.constants as constants\nimport rpmdrate.quantity as quantity\n\n################################################################################\n\nclass AndersenThermostat:\n    \"\"\"\n    A representation of an Andersen thermostat, a simple method of sampling\n    the NVT ensemble which periodically replaces the momenta with a fresh\n    sampling from a Gaussian distribution at the temperature of interest, as\n    if resulting from a collision with a heat bath.\n    \"\"\"\n    \n    def __init__(self, samplingTime=None):\n        if samplingTime is not None:\n            self.samplingTime = float(quantity.convertTime(samplingTime, \"ps\") / 2.418884326505e-5)\n        else:\n            self.samplingTime = 0.0\n\n    def activate(self, module, Natoms, Nbeads):\n        \"\"\"\n        Set the thermostat as active in the Fortran layer of the given\n        `module`.\n        \"\"\"\n        module.thermostat = 1\n        module.andersen_sampling_time = self.samplingTime\n\n################################################################################\n\nclass GLEThermostat(object):\n    \"\"\"\n    A representation of a colored-noise, generalized Langevin equation\n    thermostat. The GLE thermostat offers significantly faster convergence\n    when compared to the simpler Andersen thermostat, but requires more effort\n    to set up. In particular, the thermostat requires two matrices be specified\n    as input; these can be generated at \n    \n        http://gle4md.berlios.de/compose.php?page=matrix\n    \n    and supplied either as a file on disk or as numpy arrays. The A and C\n    matrices are assumed to have units of s^-1 and K, respectively.\n    \"\"\"\n    \n    def __init__(self, A=None, C=None):\n        self.A = A\n        self.C = C\n\n    @property\n    def A(self):\n        return self._A\n    @A.setter\n    def A(self, value):\n        if isinstance(value, (list,tuple)) and len(value) == 2 and os.path.exists(value[0]):\n            # value is the path of a file on disk to load from and the corresponding units\n            path, units = value\n            _A = []\n            f = open(path, 'r')\n            for line in f:\n                # Remove comment\n                if '#' in line: line = line[0:line.index('#')].strip()\n                tokens = line.split()\n                if len(tokens) > 0:\n                    _A.append([float(t) for t in tokens])\n            f.close()\n            self._A = numpy.array(quantity.convertFrequency((_A,units),'s^-1'))\n        elif isinstance(value, numpy.ndarray):\n            self._A = value\n        elif value is None:\n            self._A = None\n        else:\n            raise ValueError('Unexpected value {0!r} for A attribute.'.format(value))\n        \n    @property\n    def C(self):\n        return self._C\n    @C.setter\n    def C(self, value):\n        if isinstance(value, (list,tuple)) and len(value) == 2 and os.path.exists(value[0]):\n            # value is the path of a file on disk to load from and the corresponding units\n            path, units = value\n            _C = []\n            f = open(path, 'r')\n            for line in f:\n                # Remove comment\n                if '#' in line: line = line[0:line.index('#')].strip()\n                tokens = line.split()\n                if len(tokens) > 0:\n                    _C.append([float(t) for t in tokens])\n            f.close()\n            self._C = numpy.array(quantity.convertTemperature((_C,units),'K'))\n        elif isinstance(value, numpy.ndarray):\n            self._C = value\n        elif value is None:\n            self._C = None\n        else:\n            raise ValueError('Unexpected value {0!r} for C attribute.'.format(value))\n\n    def activate(self, module, Natoms, Nbeads):\n        \"\"\"\n        Set the thermostat as active in the Fortran layer of the given\n        `module`.\n        \"\"\"\n        Ns = self._A.shape[0] - 1\n        module.thermostat = 2\n        module.gle_ns = Ns\n        module.gle_a[0:Ns+1,0:Ns+1] = self._A * 2.418884326505e-17  # s^-1 to atomic units of inverse time\n        if self._C is None:\n            module.gle_c[0:Ns+1,0:Ns+1] = numpy.zeros((Ns+1,Ns+1))\n            for s in range(Ns+1):\n                module.gle_c[s,s] = Nbeads / module.beta\n        else:\n            module.gle_c[0:Ns+1,0:Ns+1] = self._C * constants.kB / 4.35974417e-18  # K to atomic units of energy\n", "meta": {"hexsha": "dc2d16c55a5a05570a95a93dfb0947149541cee5", "size": 6031, "ext": "py", "lang": "Python", "max_stars_repo_path": "rpmdrate/thermostat.py", "max_stars_repo_name": "GreenGroup/RPMDrate", "max_stars_repo_head_hexsha": "8c1828d2302aacf09a15faf5c7fc50a18d4c113e", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2015-05-07T18:31:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T02:50:46.000Z", "max_issues_repo_path": "rpmdrate/thermostat.py", "max_issues_repo_name": "GreenGroup/RPMDrate", "max_issues_repo_head_hexsha": "8c1828d2302aacf09a15faf5c7fc50a18d4c113e", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rpmdrate/thermostat.py", "max_forks_repo_name": "GreenGroup/RPMDrate", "max_forks_repo_head_hexsha": "8c1828d2302aacf09a15faf5c7fc50a18d4c113e", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2016-01-09T18:24:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T21:03:13.000Z", "avg_line_length": 39.940397351, "max_line_length": 112, "alphanum_fraction": 0.5866357155, "include": true, "reason": "import numpy", "num_tokens": 1391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.16193071223111163}}
{"text": "def selection_3():\n\n    # Library import\n    import numpy\n    import matplotlib\n    import matplotlib.pyplot   as plt\n    import matplotlib.gridspec as gridspec\n\n    # Library version\n    matplotlib_version = matplotlib.__version__\n    numpy_version      = numpy.__version__\n\n    # Histo binning\n    xBinning = numpy.linspace(0.0,1000.0,101,endpoint=True)\n\n    # Creating data sequence: middle of each bin\n    xData = numpy.array([5.0,15.0,25.0,35.0,45.0,55.0,65.0,75.0,85.0,95.0,105.0,115.0,125.0,135.0,145.0,155.0,165.0,175.0,185.0,195.0,205.0,215.0,225.0,235.0,245.0,255.0,265.0,275.0,285.0,295.0,305.0,315.0,325.0,335.0,345.0,355.0,365.0,375.0,385.0,395.0,405.0,415.0,425.0,435.0,445.0,455.0,465.0,475.0,485.0,495.0,505.0,515.0,525.0,535.0,545.0,555.0,565.0,575.0,585.0,595.0,605.0,615.0,625.0,635.0,645.0,655.0,665.0,675.0,685.0,695.0,705.0,715.0,725.0,735.0,745.0,755.0,765.0,775.0,785.0,795.0,805.0,815.0,825.0,835.0,845.0,855.0,865.0,875.0,885.0,895.0,905.0,915.0,925.0,935.0,945.0,955.0,965.0,975.0,985.0,995.0])\n\n    # Creating weights for histo: y4_PT_0\n    y4_PT_0_weights = numpy.array([0.0,0.0,77.1570947131,70.4141404187,65.4685046035,60.1625490931,55.8433127479,50.5660372133,46.0298010516,41.5918048069,37.0432726556,32.3227926499,28.6667757435,24.3311394121,21.9893253936,19.1603117874,16.4500300807,15.2954990576,13.2934927516,11.4020223521,10.0878234641,8.15132110272,7.54539761542,6.67745034984,5.77675111197,5.035723739,4.43389224824,3.9712614397,3.51272422769,3.22204407365,2.68162493093,2.31725163925,2.00200710599,1.8546200307,1.64991580391,1.43702358405,1.23231935727,1.03989752009,0.998956354728,0.77378174526,0.777876141796,0.626394669973,0.544513139257,0.528136753114,0.417596446649,0.368467568219,0.266115454825,0.233362802539,0.262021378289,0.180139687574,0.126916612609,0.192421957181,0.151481111823,0.10644618993,0.0614112680365,0.0409408453577,0.0573171915008,0.0655053445723,0.0573171915008,0.0655053445723,0.0573171915008,0.0286585877504,0.0409408453577,0.0368467568219,0.0204704186788,0.0163763341431,0.0163763341431,0.0,0.0,0.0122822536073,0.00818816907154,0.00818816907154,0.0122822536073,0.0,0.00409408453577,0.0,0.00409408453577,0.00409408453577,0.00409408453577,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_1\n    y4_PT_1_weights = numpy.array([0.0,0.0,0.012170493784,0.0242554668822,0.0121753353338,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_2\n    y4_PT_2_weights = numpy.array([0.0,0.0,0.120516882096,0.190667418918,0.170688939005,0.230969775691,0.220865995678,0.150608273824,0.0702865634698,0.0100459438961,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_3\n    y4_PT_3_weights = numpy.array([0.0,0.0,0.198079494608,0.313504754258,0.445485992003,0.467609163722,0.555495714045,0.550065266778,0.66560578175,0.500527416221,0.484060164817,0.434396780617,0.4346267225,0.291517882011,0.280484693568,0.176024330435,0.132027673006,0.0659114595513,0.0274955403792,0.0219792671012,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_4\n    y4_PT_4_weights = numpy.array([0.0,0.0,0.107569860232,0.152926540276,0.210197820351,0.240799506276,0.261535469359,0.272370115988,0.26647304052,0.260512233252,0.234839540748,0.220064946095,0.240789926465,0.217085664782,0.206244003646,0.217111558331,0.199345296751,0.209240079692,0.167774646956,0.169731052908,0.152957845016,0.107567695756,0.0967098411313,0.0769771127922,0.0513190906281,0.0404724592134,0.0256560981852,0.0197415465757,0.00691344537533,0.0039493642969,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_5\n    y4_PT_5_weights = numpy.array([0.0,0.0,0.026469421877,0.0368111391992,0.0463847330278,0.0582429397943,0.0610034742498,0.063025161425,0.0627723705057,0.0703289704757,0.0632682696279,0.0693279296382,0.0647784533032,0.0657827750611,0.0617574057619,0.0683043624811,0.0620074359067,0.0607485227243,0.057973624239,0.0564609998791,0.0546985854417,0.0549544172141,0.0451169373535,0.0486532894611,0.0456235994952,0.0441150962915,0.0405815849808,0.0403250730175,0.037557744656,0.0373196338551,0.0347905563338,0.0274836224064,0.0184009863138,0.0173888783715,0.0121017470906,0.00957741890171,0.00781076327444,0.00352860713483,0.00302506466826,0.00125954976101,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_6\n    y4_PT_6_weights = numpy.array([0.0,0.0,0.0117456805932,0.0160510745363,0.0160202634536,0.0145996546028,0.017471013581,0.0166051341817,0.0226137751752,0.0246249031193,0.0197479046086,0.0211858684365,0.0191812086204,0.0177440945465,0.01545980566,0.0200310426635,0.0171768487175,0.0166043644045,0.0177452941993,0.0146041333066,0.0148982281904,0.0146048331041,0.013461813914,0.0103127253157,0.0143026005755,0.0140366175557,0.00887486445792,0.0117502692651,0.0157392547825,0.0105858062812,0.0148863416305,0.0134570153028,0.0105856663217,0.0117342838916,0.0131758866663,0.0128871402346,0.010307316881,0.00800864615675,0.0120300482921,0.00773851133852,0.00744036662685,0.00944570224741,0.0065943574768,0.00543734833563,0.00544087731428,0.00458387734516,0.00343941757198,0.00286485386084,0.00372256662366,0.00229384012227,0.00315330237875,0.00114373298353,0.000570390518938,0.000570257457448,0.000855298861446,0.00142800071144,0.0,0.000855811113191,0.000283957617664,0.000287252564049,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_7\n    y4_PT_7_weights = numpy.array([0.0,0.0,0.00125284526549,0.00168499598199,0.00185749861251,0.00183575971121,0.00146715015491,0.00174627318844,0.00142449880858,0.00129467728017,0.00131802299351,0.00125308205443,0.00125139351877,0.00136074097602,0.000950247018111,0.00109966712725,0.00107859542594,0.0011877844651,0.000993808220713,0.000734331544785,0.000993849292069,0.000907425938116,0.000864211746567,0.000690913672835,0.000539714503417,0.000756157617944,0.000518467620202,0.000777672303167,0.000583256427627,0.000561812150443,0.000389169458214,0.000538299218003,0.00068936804873,0.000821239373105,0.00058142204674,0.000669569140375,0.000539869568742,0.000777473651913,0.000799001748191,0.00086378552647,0.000475164161317,0.000475416875887,0.000712993717852,0.000734323581971,0.000496547669656,0.000561526327331,0.000820794712808,0.000583353657777,0.000777707926283,0.000842200852303,0.000734339088503,0.000821016833409,0.000583154587427,0.000647766117466,0.000842340411096,0.000777750674021,0.000604580005314,0.000583402691947,0.000604679750036,0.000647765698371,0.000496820919905,0.000604629877675,0.000388622915807,0.000453413106247,0.00038890961902,0.000518156232265,0.000151311277457,0.000216013835034,0.000151211826102,0.000172851066499,0.000129724256356,4.32307039111e-05,2.15259505091e-05,4.32537122525e-05,2.1598366016e-05,8.64288860134e-05,0.0,0.0,2.1625766478e-05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_8\n    y4_PT_8_weights = numpy.array([0.0,0.0,0.000254018618774,0.000340757810034,0.000227098125768,0.000170284616993,0.000225875351156,0.000170440229354,0.00014128029926,0.000255240799445,0.000198750691169,0.000142064062893,8.51446694092e-05,0.000142025798288,0.000198913282328,5.66653206676e-05,8.46910920435e-05,5.68266794011e-05,5.68161963546e-05,0.000140559537847,8.50190955793e-05,5.68978186016e-05,8.47994119074e-05,8.43635042659e-05,8.51739803635e-05,2.84292647251e-05,2.83498697542e-05,5.6797754508e-05,2.84292647251e-05,0.000112168537726,0.000113373508977,2.84080907531e-05,5.67658896104e-05,2.84292647251e-05,0.0,2.84489093008e-05,5.68570000539e-05,0.0,0.0,5.68781740259e-05,0.0,2.84292647251e-05,2.83973998275e-05,2.84292647251e-05,0.0,2.83498697542e-05,5.66865985791e-05,8.52544147299e-05,0.0,5.6611405736e-05,2.84292647251e-05,5.68055054291e-05,5.68266794011e-05,0.0,5.68173990838e-05,2.83684897829e-05,0.000113596533563,0.0,5.68266794011e-05,5.67658896104e-05,0.0,2.84489093008e-05,0.0,0.000113114179789,2.84489093008e-05,8.5052133509e-05,8.52240792286e-05,2.83684897829e-05,0.0,0.0,5.67183446887e-05,2.83498697542e-05,0.000141993933391,0.0,0.0,5.6797754508e-05,2.83498697542e-05,0.0,5.64019972314e-05,0.0,0.000113494539163,0.0,2.83498697542e-05,0.0,5.67658896104e-05,2.83973998275e-05,0.0,2.83684897829e-05,0.0,2.84292647251e-05,2.84292647251e-05,2.84489093008e-05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_9\n    y4_PT_9_weights = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_10\n    y4_PT_10_weights = numpy.array([0.0,0.0,1.05462838872,0.0,1.0521138287,0.0,1.0529581672,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_11\n    y4_PT_11_weights = numpy.array([0.0,0.0,1.15201585626,4.14563454124,2.07136934156,2.30323550525,2.53414099414,1.38301356993,0.689926667059,0.690363197688,0.921327864146,0.460933689557,1.38374637267,0.230645222875,0.69068560015,0.230673159298,0.230128533541,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_12\n    y4_PT_12_weights = numpy.array([0.0,0.0,2.35389244344,1.27419718775,1.57835356252,1.21847771158,0.858756115524,0.526086439007,0.443056541367,0.581372385888,0.387378994831,0.387488627348,0.470541990192,0.276966356723,0.249345271318,0.249169359214,0.221480994065,0.166164465482,0.249253910888,0.193844252367,0.138586309862,0.0829313822454,0.0553826158335,0.221369784379,0.027658683588,0.0553746530507,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_13\n    y4_PT_13_weights = numpy.array([0.0,0.0,0.746043904483,0.574843087491,0.353046902195,0.201630148184,0.1511673845,0.110770130708,0.131139960181,0.131117201951,0.0705911738551,0.0906791654103,0.121036095087,0.0503486326784,0.0705673839189,0.050436461239,0.0704838156989,0.0806136555195,0.0604845717045,0.030176514568,0.0403463421156,0.0403272737534,0.0402882449065,0.0604881341261,0.0907026519035,0.0302662912331,0.0302700660648,0.0100533236174,0.0302963806474,0.0100733690662,0.0302270014251,0.0302662912331,0.0,0.0,0.010103349241,0.0302004744324,0.0100953565507,0.0,0.0,0.0100853125852,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_14\n    y4_PT_14_weights = numpy.array([0.0,0.0,0.316899125281,0.195206783525,0.118805873014,0.0820486906046,0.0509245525742,0.0594061683611,0.0424593269034,0.0311218026312,0.0339577659611,0.0339541878371,0.022619179794,0.0169751894332,0.0226083838631,0.0169668443248,0.0254663584264,0.0197985254483,0.019781338911,0.0169776517981,0.0283019100796,0.0169629545578,0.0141450472878,0.0113239851129,0.0113149051424,0.0141430658536,0.0198120107433,0.00564490605272,0.0113192642977,0.0226471237878,0.0169683294386,0.0169794370126,0.0113288367412,0.00282347952472,0.00565764494347,0.0141606602201,0.0141401071683,0.0169860046014,0.0169683217437,0.0141465593338,0.0113152975818,0.00849572052068,0.00849465477839,0.0084750289609,0.0,0.0,0.0,0.0,0.00283250409196,0.00283041377503,0.0113201607524,0.0,0.0,0.0,0.00282747702018,0.0,0.0,0.0,0.00282544018274,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_15\n    y4_PT_15_weights = numpy.array([0.0,0.0,0.0197527910952,0.0137030901086,0.0121841674005,0.003067188295,0.00761977251509,0.00455442442883,0.00150849604052,0.0,0.00458426252112,0.00152094965608,0.00153153115177,0.0,0.0,0.0,0.00150849604052,0.0,0.0,0.0,0.0,0.0,0.0,0.00457388076549,0.0,0.0,0.0,0.0,0.0,0.00154541013132,0.0,0.00153219773991,0.0,0.0,0.00152449651954,0.0,0.00458437007346,0.0,0.0,0.00152305579093,0.0,0.00152192826419,0.0,0.0,0.0,0.0,0.0,0.0,0.00305829572562,0.00152162924505,0.0,0.0,0.0,0.0,0.00151727396619,0.00304183194421,0.0,0.0,0.00154541013132,0.00150849604052,0.0015126539431,0.0,0.00153629536591,0.00152094965608,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating weights for histo: y4_PT_16\n    y4_PT_16_weights = numpy.array([0.0,0.0,0.0021680746957,0.00162497960558,0.00126313090509,0.000901888554933,0.000360688396201,0.00018116843031,0.00036127033852,0.000722436192292,0.0,0.000180533822134,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.000180203005096,0.000180626141377,0.0,0.0,0.0,0.0,0.000180970240375,0.0,0.0,0.0,0.0,0.0,0.000180657132616,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.000180734321975,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.000180626141377,0.0,0.0,0.0,0.0,0.0,0.0,0.000180626141377,0.0,0.0,0.0,0.0,0.000180626141377,0.0,0.0,0.000180553032852,0.000180503369873,0.000180003621709,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])\n\n    # Creating a new Canvas\n    fig   = plt.figure(figsize=(12,6),dpi=80)\n    frame = gridspec.GridSpec(1,1,right=0.7)\n    pad   = fig.add_subplot(frame[0])\n\n    # Creating a new Stack\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights+y4_PT_14_weights+y4_PT_15_weights+y4_PT_16_weights,\\\n             label=\"$bg\\_dip\\_1600\\_inf$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#e5e5e5\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights+y4_PT_14_weights+y4_PT_15_weights,\\\n             label=\"$bg\\_dip\\_1200\\_1600$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#f2f2f2\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights+y4_PT_14_weights,\\\n             label=\"$bg\\_dip\\_800\\_1200$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#ccc6aa\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights,\\\n             label=\"$bg\\_dip\\_600\\_800$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#ccc6aa\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights,\\\n             label=\"$bg\\_dip\\_400\\_600$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#c1bfa8\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights,\\\n             label=\"$bg\\_dip\\_200\\_400$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#bab5a3\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights,\\\n             label=\"$bg\\_dip\\_100\\_200$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#b2a596\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights,\\\n             label=\"$bg\\_dip\\_0\\_100$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#b7a39b\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights,\\\n             label=\"$bg\\_vbf\\_1600\\_inf$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#ad998c\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights,\\\n             label=\"$bg\\_vbf\\_1200\\_1600$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#9b8e82\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights,\\\n             label=\"$bg\\_vbf\\_800\\_1200$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#876656\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights,\\\n             label=\"$bg\\_vbf\\_600\\_800$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#afcec6\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights,\\\n             label=\"$bg\\_vbf\\_400\\_600$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#84c1a3\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights,\\\n             label=\"$bg\\_vbf\\_200\\_400$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#89a8a0\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights,\\\n             label=\"$bg\\_vbf\\_100\\_200$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#829e8c\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights,\\\n             label=\"$bg\\_vbf\\_0\\_100$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#adbcc6\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n    pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights,\\\n             label=\"$signal$\", histtype=\"step\", rwidth=1.0,\\\n             color=None, edgecolor=\"#7a8e99\", linewidth=1, linestyle=\"solid\",\\\n             bottom=None, cumulative=False, normed=False, align=\"mid\", orientation=\"vertical\")\n\n\n    # Axis\n    plt.rc('text',usetex=False)\n    plt.xlabel(r\"p_{T} [ j_{2} ]   ( GeV ) \",\\\n               fontsize=16,color=\"black\")\n    plt.ylabel(r\"$\\mathrm{Events}$ $(\\mathcal{L}_{\\mathrm{int}} = 40.0\\ \\mathrm{fb}^{-1})$ \",\\\n               fontsize=16,color=\"black\")\n\n    # Boundary of y-axis\n    ymax=(y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights+y4_PT_14_weights+y4_PT_15_weights+y4_PT_16_weights).max()*1.1\n    ymin=0 # linear scale\n    #ymin=min([x for x in (y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights+y4_PT_14_weights+y4_PT_15_weights+y4_PT_16_weights) if x])/100. # log scale\n    plt.gca().set_ylim(ymin,ymax)\n\n    # Log/Linear scale for X-axis\n    plt.gca().set_xscale(\"linear\")\n    #plt.gca().set_xscale(\"log\",nonposx=\"clip\")\n\n    # Log/Linear scale for Y-axis\n    plt.gca().set_yscale(\"linear\")\n    #plt.gca().set_yscale(\"log\",nonposy=\"clip\")\n\n    # Legend\n    plt.legend(bbox_to_anchor=(1.05,1), loc=2, borderaxespad=0.)\n\n    # Saving the image\n    plt.savefig('../../HTML/MadAnalysis5job_0/selection_3.png')\n    plt.savefig('../../PDF/MadAnalysis5job_0/selection_3.png')\n    plt.savefig('../../DVI/MadAnalysis5job_0/selection_3.eps')\n\n# Running!\nif __name__ == '__main__':\n    selection_3()\n", "meta": {"hexsha": "ed3c0ff92a34d4c6c58b0d7d31e2dc5cf0175926", "size": 25044, "ext": "py", "lang": "Python", "max_stars_repo_path": "post_optimization_studies/mad_analyses/four_cuts_eff_flow_chart/Output/Histos/MadAnalysis5job_0/selection_3.py", "max_stars_repo_name": "sheride/axion_pheno", "max_stars_repo_head_hexsha": "7d3fc08f5ae5b17a3500eba19a2e43f87f076ce5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "post_optimization_studies/mad_analyses/four_cuts_eff_flow_chart/Output/Histos/MadAnalysis5job_0/selection_3.py", "max_issues_repo_name": "sheride/axion_pheno", "max_issues_repo_head_hexsha": "7d3fc08f5ae5b17a3500eba19a2e43f87f076ce5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "post_optimization_studies/mad_analyses/four_cuts_eff_flow_chart/Output/Histos/MadAnalysis5job_0/selection_3.py", "max_forks_repo_name": "sheride/axion_pheno", "max_forks_repo_head_hexsha": "7d3fc08f5ae5b17a3500eba19a2e43f87f076ce5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 129.0927835052, "max_line_length": 1464, "alphanum_fraction": 0.7292764734, "include": true, "reason": "import numpy", "num_tokens": 12663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.21206881431678096, "lm_q1q2_score": 0.16191109648707233}}
{"text": "#!/usr/bin/env python\n# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#\n\n'''\nAnalytical nuclear gradients for domain decomposition COSMO\n\nSee also\n\n[1] Fast Domain Decomposition Algorithm for Continuum Solvation Models: Energy and First Derivatives.\nF. Lipparini, B. Stamm, E. Cances, Y. Maday, B. Mennucci\nJ. Chem. Theory Comput., 9, 3637-3648 (2013)\nhttp://dx.doi.org/10.1021/ct400280b\n\n[2] Quantum, classical, and hybrid QM/MM calculations in solution: General implementation of the ddCOSMO linear scaling strategy.\nF. Lipparini, G. Scalmani, L. Lagardere, B. Stamm, E. Cances, Y. Maday, J.-P.Piquemal, M. J. Frisch, B. Mennucci\nJ. Chem. Phys., 141, 184108 (2014)\nhttp://dx.doi.org/10.1063/1.4901304\n'''\n\nimport ctypes\nimport numpy\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf import gto\nfrom pyscf import df\nfrom pyscf.dft import gen_grid, numint\nfrom pyscf.symm import sph\nfrom pyscf.solvent import ddcosmo\nfrom pyscf.grad import rhf as rhf_grad\nfrom pyscf.grad import rks as rks_grad\n\n\n# TODO: Define attribute grad_method.base to point to the class of the 0th\n# order calculation for all gradients class. Then this function can be\n# extended and used as the general interface to initialize solvent gradients.\ndef ddcosmo_grad(grad_method, pcmobj=None):\n    grad_method_class = grad_method.__class__\n    class WithSolventGrad(grad_method.__class__):\n        def __init__(self, pcmobj):\n            self.__dict__.update(grad_method.__dict__)\n            self.with_solvent = pcmobj\n            self.de_solvent = None\n            self.de_solute = None\n            self._keys = self._keys.union(['with_solvent', 'de_solvent', 'de_solute'])\n\n        def kernel(self, dm=None, atmlst=None):\n            if dm is None:\n                dm = grad_method.base.make_rdm1(ao_repr=True)\n\n            # de_solvent needs to be called first because _finalize method\n            # is called in the grad_method.kernel function.  de_solvent is\n            # required by the _finalize method.\n            self.de_solvent = kernel(self.with_solvent, dm)\n            self.de_solute = grad_method_class.kernel(self, atmlst=atmlst)\n            self.de = self.de_solute + self.de_solvent\n\n            if self.verbose >= logger.NOTE:\n                logger.note(self, '--------------- %s (%s) gradients ---------------',\n                            grad_method.base.__class__.__name__,\n                            self.with_solvent.__class__.__name__)\n                rhf_grad._write(self, self.mol, self.de, self.atmlst)\n                logger.note(self, '----------------------------------------------')\n            return self.de\n\n        def _finalize(self):\n            # disable _finalize. It is called in grad_method.kernel method\n            # where self.de was not yet initialized.\n            pass\n\n    if pcmobj is None:\n        pcmobj = ddcosmo.DDCOSMO(mf.mol)\n    return WithSolventGrad(pcmobj)\n\n# Inject DDCOSMO gradients into other modules\ntry:\n    from pyscf import grad\n    for mod in dir(grad):\n        if 1 or hasattr(mod, 'Gradients'):\n            mod.Gradients.DDCOSMO = ddcosmo_grad\n    del(mod, grad)\nexcept Exception as e:\n    print('Error for registering ddcosmo gradients: ' + str(e))\n\n\ndef kernel(pcmobj, dm, verbose=None):\n    mol = pcmobj.mol\n    natm = mol.natm\n    lmax = pcmobj.lmax\n    if pcmobj.grids.coords is None:\n        pcmobj.grids.build(with_non0tab=True)\n\n    if not (isinstance(dm, numpy.ndarray) and dm.ndim == 2):\n        # UHF density matrix\n        dm = dm[0] + dm[1]\n\n    r_vdw = ddcosmo.get_atomic_radii(pcmobj)\n    coords_1sph, weights_1sph = ddcosmo.make_grids_one_sphere(pcmobj.lebedev_order)\n    ylm_1sph = numpy.vstack(sph.real_sph_vec(coords_1sph, lmax, True))\n\n    fi = ddcosmo.make_fi(pcmobj, r_vdw)\n    ui = 1 - fi\n    ui[ui<0] = 0\n\n    cached_pol = ddcosmo.cache_fake_multipoles(pcmobj.grids, r_vdw, lmax)\n\n    nlm = (lmax+1)**2\n    L0 = ddcosmo.make_L(pcmobj, r_vdw, ylm_1sph, fi)\n    L0 = L0.reshape(natm*nlm,-1)\n    L1 = make_L1(pcmobj, r_vdw, ylm_1sph, fi)\n\n    phi0 = ddcosmo.make_phi(pcmobj, dm, r_vdw, ui)\n    phi1 = make_phi1(pcmobj, dm, r_vdw, ui)\n    L0_X = numpy.linalg.solve(L0, phi0.ravel()).reshape(natm,-1)\n    psi0, vmat, L0_S = \\\n            ddcosmo.make_psi_vmat(pcmobj, dm, r_vdw, ui, pcmobj.grids, ylm_1sph,\n                                  cached_pol, L0_X, L0)\n    e_psi1 = make_e_psi1(pcmobj, dm, r_vdw, ui, pcmobj.grids, ylm_1sph,\n                         cached_pol, L0_X, L0)\n    dielectric = pcmobj.eps\n    if dielectric > 0:\n        f_epsilon = (dielectric-1.)/dielectric\n    else:\n        f_epsilon = 1\n    de = .5 * f_epsilon * e_psi1\n    de+= .5 * f_epsilon * numpy.einsum('jx,azjx->az', L0_S, phi1)\n    de-= .5 * f_epsilon * numpy.einsum('aziljm,il,jm->az', L1, L0_S, L0_X)\n    return de\n\ndef make_L1(pcmobj, r_vdw, ylm_1sph, fi):\n    # See JCTC, 9, 3637, Eq (18)\n    mol = pcmobj.mol\n    natm = mol.natm\n    lmax = pcmobj.lmax\n    eta = pcmobj.eta\n    nlm = (lmax+1)**2\n\n    coords_1sph, weights_1sph = ddcosmo.make_grids_one_sphere(pcmobj.lebedev_order)\n    ngrid_1sph = weights_1sph.size\n    atom_coords = mol.atom_coords()\n    ylm_1sph = ylm_1sph.reshape(nlm,ngrid_1sph)\n\n    Lmat = numpy.zeros((natm,3,natm,nlm,natm,nlm))\n    fi1 = make_fi1(pcmobj, pcmobj.get_atomic_radii())\n\n    for ja in range(natm):\n        part_weights = weights_1sph.copy()\n        part_weights[fi[ja]>1] /= fi[ja,fi[ja]>1]\n\n        part_weights1 = numpy.zeros((natm,3,ngrid_1sph))\n        tmp = part_weights[fi[ja]>1] / fi[ja,fi[ja]>1]\n        part_weights1[:,:,fi[ja]>1] = -tmp * fi1[:,:,ja,fi[ja]>1]\n\n        for ka in ddcosmo.atoms_with_vdw_overlap(ja, atom_coords, r_vdw):\n            vjk = r_vdw[ja] * coords_1sph + atom_coords[ja] - atom_coords[ka]\n            rv = lib.norm(vjk, axis=1)\n            tjk = rv / r_vdw[ka]\n            wjk0 = pcmobj.regularize_xt(tjk, eta, r_vdw[ka])\n            wjk1 = regularize_xt1(tjk, eta*r_vdw[ka])\n            sjk = vjk.T / rv\n            wjk1 = 1./r_vdw[ka] * wjk1 * sjk\n\n            wjk01 = wjk0 * part_weights1\n            wjk0 *= part_weights\n            wjk1 *= part_weights\n\n            pol0 = sph.multipoles(vjk, lmax)\n            pol1 = multipoles1(vjk, lmax)\n            p1 = 0\n            for l in range(lmax+1):\n                fac = 4*numpy.pi/(l*2+1) / r_vdw[ka]**(l+1)\n                p0, p1 = p1, p1 + (l*2+1)\n                a = numpy.einsum('xn,zn,mn->zxm', ylm_1sph, wjk1, pol0[l])\n                a+= numpy.einsum('xn,n,zmn->zxm', ylm_1sph, wjk0, pol1[l])\n                Lmat[ja,:,ja,:,ka,p0:p1] += -fac * a\n                Lmat[ka,:,ja,:,ka,p0:p1] -= -fac * a\n                a = numpy.einsum('xn,azn,mn->azxm', ylm_1sph, wjk01, pol0[l])\n                Lmat[:,:,ja,:,ka,p0:p1] += -fac * a\n    return Lmat\n\n\ndef multipoles1(r, lmax, reorder_dipole=True):\n    ngrid = r.shape[0]\n    xs = numpy.ones((lmax+1,ngrid))\n    ys = numpy.ones((lmax+1,ngrid))\n    zs = numpy.ones((lmax+1,ngrid))\n    for i in range(1,lmax+1):\n        xs[i] = xs[i-1] * r[:,0]\n        ys[i] = ys[i-1] * r[:,1]\n        zs[i] = zs[i-1] * r[:,2]\n    ylms = []\n    for l in range(lmax+1):\n        nd = (l+1)*(l+2)//2\n        c = numpy.empty((nd,3,ngrid))\n        k = 0\n        for lx in reversed(range(0, l+1)):\n            for ly in reversed(range(0, l-lx+1)):\n                lz = l - lx - ly\n                c[k,0] = lx * xs[lx-1] * ys[ly] * zs[lz]\n                c[k,1] = ly * xs[lx] * ys[ly-1] * zs[lz]\n                c[k,2] = lz * xs[lx] * ys[ly] * zs[lz-1]\n                k += 1\n        ylm = gto.cart2sph(l, c.reshape(nd,3*ngrid).T)\n        ylm = ylm.reshape(3,ngrid,l*2+1).transpose(0,2,1)\n        ylms.append(ylm)\n\n# when call libcint, p functions are ordered as px,py,pz\n# reorder px,py,pz to p(-1),p(0),p(1)\n    if (not reorder_dipole) and lmax >= 1:\n        ylms[1] = ylms[1][:,[1,2,0]]\n    return ylms\n\n\ndef regularize_xt1(t, eta):\n    xt = numpy.zeros_like(t)\n    # no response if grids are inside the cavity\n    # inner = t <= 1-eta\n    # xt[inner] = 0\n    on_shell = (1-eta < t) & (t < 1)\n    ti = t[on_shell]\n    xt[on_shell] = -30./eta**5 * (1-ti)**2 * (1-eta-ti)**2\n    return xt\n\ndef make_fi1(pcmobj, r_vdw):\n    coords_1sph, weights_1sph = ddcosmo.make_grids_one_sphere(pcmobj.lebedev_order)\n    mol = pcmobj.mol\n    eta = pcmobj.eta\n    natm = mol.natm\n    atom_coords = mol.atom_coords()\n    ngrid_1sph = coords_1sph.shape[0]\n    fi1 = numpy.zeros((natm,3,natm,ngrid_1sph))\n    for ia in range(natm):\n        for ja in ddcosmo.atoms_with_vdw_overlap(ia, atom_coords, r_vdw):\n            v = r_vdw[ia]*coords_1sph + atom_coords[ia] - atom_coords[ja]\n            rv = lib.norm(v, axis=1)\n            t = rv / r_vdw[ja]\n            xt1 = regularize_xt1(t, eta*r_vdw[ja])\n            s_ij = v.T / rv\n            xt1 = 1./r_vdw[ja] * xt1 * s_ij\n            fi1[ia,:,ia] += xt1\n            fi1[ja,:,ia] -= xt1\n\n    fi = ddcosmo.make_fi(pcmobj, r_vdw)\n    fi1[:,:,fi<1e-20] = 0\n    return fi1\n\ndef make_phi1(pcmobj, dm, r_vdw, ui):\n    mol = pcmobj.mol\n    natm = mol.natm\n    nlm = (pcmobj.lmax+1)**2\n\n    if not (isinstance(dm, numpy.ndarray) and dm.ndim == 2):\n        dm = dm[0] + dm[1]\n    tril_dm = lib.pack_tril(dm+dm.T)\n    nao = dm.shape[0]\n    diagidx = numpy.arange(nao)\n    diagidx = diagidx*(diagidx+1)//2 + diagidx\n    tril_dm[diagidx] *= .5\n\n    atom_coords = mol.atom_coords()\n    atom_charges = mol.atom_charges()\n\n    coords_1sph, weights_1sph = ddcosmo.make_grids_one_sphere(pcmobj.lebedev_order)\n    ylm_1sph = numpy.vstack(sph.real_sph_vec(coords_1sph, pcmobj.lmax, True))\n    extern_point_idx = ui > 0\n\n    fi1 = make_fi1(pcmobj, pcmobj.get_atomic_radii())\n    fi1[:,:,ui==0] = 0\n    ui1 = -fi1\n\n    ngrid_1sph = weights_1sph.size\n    v_phi0 = numpy.empty((natm,ngrid_1sph))\n    for ia in range(natm):\n        cav_coords = atom_coords[ia] + r_vdw[ia] * coords_1sph\n        d_rs = atom_coords.reshape(-1,1,3) - cav_coords\n        v_phi0[ia] = numpy.einsum('z,zp->p', atom_charges, 1./lib.norm(d_rs,axis=2))\n    phi1 = -numpy.einsum('n,ln,azjn,jn->azjl', weights_1sph, ylm_1sph, ui1, v_phi0)\n\n    for ia in range(natm):\n        cav_coords = atom_coords[ia] + r_vdw[ia] * coords_1sph\n        for ja in range(natm):\n            rs = atom_coords[ja] - cav_coords\n            d_rs = lib.norm(rs, axis=1)\n            v_phi = atom_charges[ja] * numpy.einsum('px,p->px', rs, 1./d_rs**3)\n            tmp = numpy.einsum('n,ln,n,nx->xl', weights_1sph, ylm_1sph, ui[ia], v_phi)\n            phi1[ja,:,ia] += tmp  # response of the other atoms\n            phi1[ia,:,ia] -= tmp  # response of cavity grids\n\n    int3c2e = mol._add_suffix('int3c2e')\n    int3c2e_ip1 = mol._add_suffix('int3c2e_ip1')\n    aoslices = mol.aoslice_by_atom()\n    for ia in range(natm):\n        cav_coords = atom_coords[ia] + r_vdw[ia] * coords_1sph\n        #fakemol = gto.fakemol_for_charges(cav_coords[ui[ia]>0])\n        fakemol = gto.fakemol_for_charges(cav_coords)\n        v_nj = df.incore.aux_e2(mol, fakemol, intor=int3c2e, aosym='s1')\n        v_phi = numpy.einsum('ij,ijk->k', dm, v_nj)\n        phi1[:,:,ia] += numpy.einsum('n,ln,azn,n->azl', weights_1sph, ylm_1sph, ui1[:,:,ia], v_phi)\n\n        v_e1_nj = df.incore.aux_e2(mol, fakemol, intor=int3c2e_ip1, comp=3, aosym='s1')\n        v_e2_nj = v_e1_nj + v_e1_nj.transpose(0,2,1,3)\n        phi1_e2_nj = numpy.einsum('ji,xijr->xr', dm, v_e2_nj)\n        phi1[ia,:,ia] += numpy.einsum('n,ln,n,xn->xl', weights_1sph, ylm_1sph, ui[ia], phi1_e2_nj)\n\n        for ja in range(natm):\n            shl0, shl1, p0, p1 = aoslices[ja]\n            phi1_nj  = numpy.einsum('ij,xijr->xr', dm[p0:p1  ], v_e1_nj[:,p0:p1])\n            phi1_nj += numpy.einsum('ji,xijr->xr', dm[:,p0:p1], v_e1_nj[:,p0:p1])\n            phi1[ja,:,ia] -= numpy.einsum('n,ln,n,xn->xl', weights_1sph, ylm_1sph, ui[ia], phi1_nj)\n    return phi1\n\ndef make_e_psi1(pcmobj, dm, r_vdw, ui, grids, ylm_1sph, cached_pol, L_X, L):\n    mol = pcmobj.mol\n    natm = mol.natm\n    lmax = pcmobj.lmax\n    nlm = (lmax+1)**2\n\n    if not (isinstance(dm, numpy.ndarray) and dm.ndim == 2):\n        dm = dm[0] + dm[1]\n    ni = numint.NumInt()\n    max_memory = pcmobj.max_memory - lib.current_memory()[0]\n    make_rho, nset, nao = ni._gen_rho_evaluator(mol, dm)\n    den = numpy.empty((4,grids.weights.size))\n\n    ao_loc = mol.ao_loc_nr()\n    vmat = numpy.zeros((3,nao,nao))\n    psi1 = numpy.zeros((natm,3))\n    i1 = 0\n    for ia, (coords, weight, weight1) in enumerate(rks_grad.grids_response_cc(grids)):\n        i0, i1 = i1, i1 + weight.size\n        ao = ni.eval_ao(mol, coords, deriv=1)\n        mask = gen_grid.make_mask(mol, coords)\n        den[:,i0:i1] = make_rho(0, ao, mask, 'GGA')\n\n        fak_pol, leak_idx = cached_pol[mol.atom_symbol(ia)]\n        eta_nj = 0\n        p1 = 0\n        for l in range(lmax+1):\n            fac = 4*numpy.pi/(l*2+1)\n            p0, p1 = p1, p1 + (l*2+1)\n            eta_nj += fac * numpy.einsum('mn,m->n', fak_pol[l], L_X[ia,p0:p1])\n        psi1 -= numpy.einsum('n,n,zxn->zx', den[0,i0:i1], eta_nj, weight1)\n        psi1[ia] -= numpy.einsum('xn,n,n->x', den[1:4,i0:i1], eta_nj, weight)\n\n        vtmp = numpy.zeros((3,nao,nao))\n        aow = numpy.einsum('pi,p->pi', ao[0], weight*eta_nj)\n        rks_grad._d1_dot_(vtmp, mol, ao[1:4], aow, mask, ao_loc, True)\n        vmat += vtmp\n\n    aoslices = mol.aoslice_by_atom()\n    for ia in range(natm):\n        shl0, shl1, p0, p1 = aoslices[ia]\n        psi1[ia] += numpy.einsum('xij,ij->x', vmat[:,p0:p1], dm[p0:p1]) * 2\n    return psi1\n\n\nif __name__ == '__main__':\n    from pyscf import scf\n    mol = gto.M(atom='H 0 0 0; H 0 1 1.2; H 1. .1 0; H .5 .5 1', unit='B')\n    mf = ddcosmo.ddcosmo_for_scf(scf.RHF(mol))\n    mf.kernel()\n    de = mf.nuc_grad_method().kernel()\n    de_cosmo = kernel(mf.with_solvent, mf.make_rdm1())\n    dm1 = mf.make_rdm1()\n\n    mol = gto.M(atom='H 0 0 -0.001; H 0 1 1.2; H 1. .1 0; H .5 .5 1', unit='B')\n    mf = ddcosmo.ddcosmo_for_scf(scf.RHF(mol))\n    e1 = mf.kernel()\n    e1_cosmo = mf.with_solvent.energy(dm1)\n\n    mol = gto.M(atom='H 0 0 0.001; H 0 1 1.2; H 1. .1 0; H .5 .5 1', unit='B')\n    mf = ddcosmo.ddcosmo_for_scf(scf.RHF(mol))\n    e2 = mf.kernel()\n    e2_cosmo = mf.with_solvent.energy(dm1)\n    print(abs((e2-e1)/0.002 - de[0,2]).max())\n    print(abs((e2_cosmo-e1_cosmo)/0.002 - de_cosmo[0,2]).max())\n", "meta": {"hexsha": "54d2a83c3e98d9628fdacfe825af49ed5deb632a", "size": 14821, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/solvent/ddcosmo_grad.py", "max_stars_repo_name": "highlight0112/pyscf", "max_stars_repo_head_hexsha": "4afbd42bad3e72db5bb94d8cacf1d5de76537bdd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyscf/solvent/ddcosmo_grad.py", "max_issues_repo_name": "highlight0112/pyscf", "max_issues_repo_head_hexsha": "4afbd42bad3e72db5bb94d8cacf1d5de76537bdd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscf/solvent/ddcosmo_grad.py", "max_forks_repo_name": "highlight0112/pyscf", "max_forks_repo_head_hexsha": "4afbd42bad3e72db5bb94d8cacf1d5de76537bdd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.905370844, "max_line_length": 129, "alphanum_fraction": 0.5998920451, "include": true, "reason": "import numpy", "num_tokens": 5229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.28776780354463427, "lm_q1q2_score": 0.16177629686431425}}
{"text": "from __future__ import division, absolute_import, print_function\nfrom past.builtins import xrange\n\nimport numpy as np\nimport esutil\nimport time\n\nimport matplotlib.pyplot as plt\n\nfrom .fgcmUtilities import objFlagDict\nfrom .fgcmUtilities import obsFlagDict\n\nfrom .sharedNumpyMemManager import SharedNumpyMemManager as snmm\n\nclass FgcmStars(object):\n    \"\"\"\n    Class to describe the stars and observations of the stars.  Note that\n     after initialization you must call loadStarsFromFits() or loadStars()\n     to load the star information.  This allows an external caller to clear\n     out memory after it has been copied to the shared memory buffers.\n\n    parameters\n    ----------\n    fgcmConfig: FgcmConfig\n\n    Config variables\n    ----------------\n    minObsPerBand: int\n       Minumum number of observations per band to be \"good\"\n    sedFitBandFudgeFactors: float array\n       Fudge factors for computing fnuprime for the fit bands\n    sedExtraBandFudgeFactors: float array\n       Fudge factors for computing fnuprime for the extra bands\n    starColorCuts: list\n       List that contains lists of [bandIndex0, bandIndex1, minColor, maxColor]\n    sigma0Phot: float\n       Floor on photometric error to add to every observation\n    reserveFraction: float\n       Fraction of stars to hold in reserve\n    mapLongitudeRef: float\n       Reference longitude for plotting maps of stars\n    mapNSide: int\n       Healpix nside of map plotting.\n    superStarSubCCD: bool\n       Use sub-ccd info to make superstar flats?\n    obsFile: string, only if using fits mode\n       Star observation file\n    indexFile: string, only if using fits mode\n       Star index file\n    \"\"\"\n\n    def __init__(self,fgcmConfig):\n\n        self.fgcmLog = fgcmConfig.fgcmLog\n\n        self.fgcmLog.info('Initializing stars.')\n\n        self.obsFile = fgcmConfig.obsFile\n        self.indexFile = fgcmConfig.indexFile\n\n        self.bands = fgcmConfig.bands\n        self.nBands = len(fgcmConfig.bands)\n        self.nCCD = fgcmConfig.nCCD\n        self.minObsPerBand = fgcmConfig.minObsPerBand\n        self.fitBands = fgcmConfig.fitBands\n        self.nFitBands = len(fgcmConfig.fitBands)\n        self.extraBands = fgcmConfig.extraBands\n        self.sedFitBandFudgeFactors = fgcmConfig.sedFitBandFudgeFactors\n        self.sedExtraBandFudgeFactors = fgcmConfig.sedExtraBandFudgeFactors\n        self.starColorCuts = fgcmConfig.starColorCuts\n        self.sigma0Phot = fgcmConfig.sigma0Phot\n        self.ccdStartIndex = fgcmConfig.ccdStartIndex\n        self.plotPath = fgcmConfig.plotPath\n        self.outfileBaseWithCycle = fgcmConfig.outfileBaseWithCycle\n        self.expField = fgcmConfig.expField\n        self.ccdField = fgcmConfig.ccdField\n        self.reserveFraction = fgcmConfig.reserveFraction\n        self.modelMagErrors = fgcmConfig.modelMagErrors\n\n        self.inFlagStarFile = fgcmConfig.inFlagStarFile\n\n        self.mapLongitudeRef = fgcmConfig.mapLongitudeRef\n        self.mapNSide = fgcmConfig.mapNSide\n\n        self.lambdaStdBand = fgcmConfig.lambdaStdBand\n\n        self.bandRequiredFlag = fgcmConfig.bandRequiredFlag\n        self.bandRequiredIndex = np.where(self.bandRequiredFlag)[0]\n        self.bandExtraFlag = fgcmConfig.bandExtraFlag\n        self.bandExtraIndex = np.where(self.bandExtraFlag)[0]\n\n        self.lutFilterNames = fgcmConfig.lutFilterNames\n        self.filterToBand = fgcmConfig.filterToBand\n\n        self.superStarSubCCD = fgcmConfig.superStarSubCCD\n\n        #self.expArray = fgcmPars.expArray\n\n        #self._loadStars(fgcmPars)\n\n        self.magStdComputed = False\n        self.allMagStdComputed = False\n        self.sedSlopeComputed = False\n\n        #if (computeNobs):\n        #    allExps = np.arange(fgcmConfig.expRange[0],fgcmConfig.expRange[1],dtype='i4')\n        #    self.fgcmLog.info('Checking stars with full possible range of exp numbers')\n            #self.selectStarsMinObs(goodExps=allExps,doPlots=False)\n        #    allExpsIndex = np.arange(fgcmPars.expArray.size)\n        #    self.selectStarsMinObsExpIndex(allExpsIndex)\n\n        self.magConstant = 2.5/np.log(10)\n\n        self.hasXY = False\n\n    def loadStarsFromFits(self,fgcmPars,computeNobs=True):\n        \"\"\"\n        Load stars from fits files.\n\n        parameters\n        ----------\n        fgcmPars: FgcmParameters\n        computeNobs: bool, default=True\n           Compute number of observations of each star/band\n\n        Config variables\n        ----------------\n        indexFile: string\n           Star index file\n        obsFile: string\n           Star observation file\n        inFlagStarFile: string, optional\n           Flagged star file\n        \"\"\"\n\n        import fitsio\n\n        # read in the observation indices...\n        startTime = time.time()\n        self.fgcmLog.info('Reading in observation indices...')\n        index = fitsio.read(self.indexFile, ext='INDEX')\n        self.fgcmLog.info('Done reading in %d observation indices in %.1f seconds.' %\n                         (index.size, time.time() - startTime))\n\n        # read in obsfile and cut\n        startTime = time.time()\n        self.fgcmLog.info('Reading in star observations...')\n        obs = fitsio.read(self.obsFile, ext=1)\n        # cut down to those that are indexed\n        obs = obs[index['OBSINDEX']]\n        self.fgcmLog.info('Done reading in %d observations in %.1f seconds.' %\n                         (obs.size, time.time() - startTime))\n\n        # and positions...\n        startTime = time.time()\n        self.fgcmLog.info('Reading in star positions...')\n        pos = fitsio.read(self.indexFile, ext='POS')\n        self.fgcmLog.info('Done reading in %d unique star positions in %.1f secondds.' %\n                         (pos.size, time.time() - startTime))\n\n        #obsBand = np.core.defchararray.strip(obs['BAND'][:])\n        obsFilterName = np.core.defchararray.strip(obs['FILTERNAME'][:])\n\n        if (self.inFlagStarFile is not None):\n            self.fgcmLog.info('Reading in list of previous flagged stars from %s' %\n                             (self.inFlagStarFile))\n\n            inFlagStars = fitsio.read(self.inFlagStarFile, ext=1)\n\n            flagID = inFlagStars['OBJID']\n            flagFlag = inFlagStars['OBJFLAG']\n        else:\n            flagID = None\n            flagFlag = None\n\n        # FIXME: add support to x/y from fits files\n        if ('X' in obs.dtype.names and 'Y' in obs.dtype.names):\n            self.fgcmLog.info('Found X/Y in input observations')\n            obsX = obs['X']\n            obsY = obs['Y']\n        else:\n            obsX = None\n            obsY = None\n\n        # process\n        self.loadStars(fgcmPars,\n                       obs[self.expField],\n                       obs[self.ccdField],\n                       obs['RA'],\n                       obs['DEC'],\n                       obs['MAG'],\n                       obs['MAGERR'],\n                       obsFilterName,\n                       pos['FGCM_ID'],\n                       pos['RA'],\n                       pos['DEC'],\n                       pos['OBSARRINDEX'],\n                       pos['NOBS'],\n                       obsX=obsX,\n                       obsY=obsY,\n                       flagID=flagID,\n                       flagFlag=flagFlag,\n                       computeNobs=computeNobs)\n\n        # and clear memory\n        index = None\n        obs = None\n        pos = None\n\n    def loadStars(self, fgcmPars,\n                  obsExp, obsCCD, obsRA, obsDec, obsMag, obsMagErr, obsFilterName,\n                  objID, objRA, objDec, objObsIndex, objNobs, obsX=None, obsY=None,\n                  flagID=None, flagFlag=None, computeNobs=True):\n        \"\"\"\n        Load stars from arrays\n\n        parameters\n        ----------\n        fgcmPars: fgcmParameters\n        obsExp: int array\n           Exposure number (or equivalent) for each observation\n        obsCCD: int array\n           CCD number (or equivalent) for each observation\n        obsRA: double array\n           RA for each observation (degrees)\n        obsDec: double array\n           Dec for each observation (degrees)\n        obsMag: float array\n           Raw ADU magnitude for each observation\n        obsMagErr: float array\n           Raw ADU magnitude error for each observation\n        obsFilterName: string array\n           Filter name for each observation\n        objID: int array\n           Unique ID number for each object\n        objRA: double array\n           RA for each object (degrees)\n        objDec: double array\n           Dec for each object (degrees)\n        objObsIndex: int array\n           For each object, where in the obs table to look\n        objNobs: int array\n           number of observations of this object (all bands)\n        obsX: float array, optional\n           x position for each observation\n        obsY: float array, optional\n           y position for each observation\n        flagID: int array, optional\n           ID of each object that is flagged from previous cycle\n        flagFlag: int array, optional\n           Flag value from previous cycle\n        computeNobs: bool, default=True\n           Compute number of good observations of each object?\n        \"\"\"\n\n        # FIXME: check that these are all the same length!\n\n        self.obsIndexHandle = snmm.createArray(obsRA.size, dtype='i4')\n        snmm.getArray(self.obsIndexHandle)[:] = np.arange(obsRA.size)\n\n\n        # need to stuff into shared memory objects.\n        #  nStarObs: total number of observations of all starus\n        self.nStarObs = obsRA.size\n\n        #  obsExp: exposure number of individual observation (pointed by obsIndex)\n        self.obsExpHandle = snmm.createArray(self.nStarObs,dtype='i4')\n        #  obsExpIndex: exposure index\n        self.obsExpIndexHandle = snmm.createArray(self.nStarObs,dtype='i4')\n        #  obsCCD: ccd number of individual observation\n        self.obsCCDHandle = snmm.createArray(self.nStarObs,dtype='i2')\n        #  obsBandIndex: band index of individual observation\n        self.obsBandIndexHandle = snmm.createArray(self.nStarObs,dtype='i2')\n        #  obsLUTFilterIndex: filter index in LUT of individual observation\n        self.obsLUTFilterIndexHandle = snmm.createArray(self.nStarObs,dtype='i2')\n        #  obsFlag: individual bad observation\n        self.obsFlagHandle = snmm.createArray(self.nStarObs,dtype='i2')\n        #  obsRA: RA of individual observation\n        self.obsRAHandle = snmm.createArray(self.nStarObs,dtype='f8')\n        #  obsDec: Declination of individual observation\n        self.obsDecHandle = snmm.createArray(self.nStarObs,dtype='f8')\n        #  obsSecZenith: secant(zenith) of individual observation\n        self.obsSecZenithHandle = snmm.createArray(self.nStarObs,dtype='f8')\n        #  obsMagADU: log raw ADU counts of individual observation\n        ## FIXME: need to know default zeropoint?\n        self.obsMagADUHandle = snmm.createArray(self.nStarObs,dtype='f4')\n        #  obsMagADUErr: raw ADU counts error of individual observation\n        self.obsMagADUErrHandle = snmm.createArray(self.nStarObs,dtype='f4')\n        #  obsMagADUModelErr: modeled ADU counts error of individual observation\n        self.obsMagADUModelErrHandle = snmm.createArray(self.nStarObs,dtype='f4')\n        #  obsSuperStarApplied: SuperStar correction that was applied\n        self.obsSuperStarAppliedHandle = snmm.createArray(self.nStarObs,dtype='f4')\n        #  obsMagStd: corrected (to standard passband) mag of individual observation\n        self.obsMagStdHandle = snmm.createArray(self.nStarObs,dtype='f4',syncAccess=True)\n        if (obsX is not None and obsY is not None):\n            self.hasXY = True\n\n            #  obsX: x position on the CCD of the given observation\n            self.obsXHandle = snmm.createArray(self.nStarObs,dtype='f4')\n            #  obsY: y position on the CCD of the given observation\n            self.obsYHandle = snmm.createArray(self.nStarObs,dtype='f4')\n        else:\n            # hasXY = False\n            if self.superStarSubCCD:\n                raise ValueError(\"Input stars do not have x/y but superStarSubCCD is set.\")\n\n        snmm.getArray(self.obsExpHandle)[:] = obsExp\n        snmm.getArray(self.obsCCDHandle)[:] = obsCCD\n        snmm.getArray(self.obsRAHandle)[:] = obsRA\n        snmm.getArray(self.obsDecHandle)[:] = obsDec\n        snmm.getArray(self.obsMagADUHandle)[:] = obsMag\n        snmm.getArray(self.obsMagADUErrHandle)[:] = obsMagErr\n        snmm.getArray(self.obsMagStdHandle)[:] = obsMag   # same as raw at first\n        snmm.getArray(self.obsSuperStarAppliedHandle)[:] = 0.0\n        if self.hasXY:\n            snmm.getArray(self.obsXHandle)[:] = obsX\n            snmm.getArray(self.obsYHandle)[:] = obsY\n\n        self.fgcmLog.info('Applying sigma0Phot = %.4f to mag errs' %\n                         (self.sigma0Phot))\n\n        obsMagADUErr = snmm.getArray(self.obsMagADUErrHandle)\n\n        obsFlag = snmm.getArray(self.obsFlagHandle)\n        bad, = np.where(obsMagADUErr <= 0.0)\n        obsFlag[bad] |= obsFlagDict['BAD_ERROR']\n        if (bad.size > 0):\n            self.fgcmLog.info('Flagging %d observations with bad errors.' %\n                             (bad.size))\n\n        obsMagADUErr[:] = np.sqrt(obsMagADUErr[:]**2. + self.sigma0Phot**2.)\n\n        # Initially, we set the model error to the observed error\n        obsMagADUModelErr = snmm.getArray(self.obsMagADUModelErrHandle)\n        obsMagADUModelErr[:] = obsMagADUErr[:]\n\n        startTime = time.time()\n        self.fgcmLog.info('Matching observations to exposure table.')\n        obsExpIndex = snmm.getArray(self.obsExpIndexHandle)\n        obsExpIndex[:] = -1\n        a,b=esutil.numpy_util.match(fgcmPars.expArray,\n                                    snmm.getArray(self.obsExpHandle)[:])\n        obsExpIndex[b] = a\n        self.fgcmLog.info('Observations matched in %.1f seconds.' %\n                         (time.time() - startTime))\n\n        bad, = np.where(obsExpIndex < 0)\n        obsFlag[bad] |= obsFlagDict['NO_EXPOSURE']\n\n        if (bad.size > 0):\n            self.fgcmLog.info('Flagging %d observations with no associated exposure.' %\n                             (bad.size))\n\n        # match bands and filters to indices\n        startTime = time.time()\n        self.fgcmLog.info('Matching observations to bands.')\n\n        #for i in xrange(self.nBands):\n        #    use, = np.where(obsBand == self.bands[i])\n        #    if (use.size == 0):\n        #        raise ValueError(\"No observations in band %s!\" % (self.bands[i]))\n        #    snmm.getArray(self.obsBandIndexHandle)[use] = i\n\n        # new version for multifilter support\n        # First, we have the filterNames\n        for filterIndex,filterName in enumerate(self.lutFilterNames):\n            #try:\n            #    bandIndex, = np.where(self.filterToBand[filterName] == self.bands)\n            #except:\n            #    self.fgcmLog.info('WARNING: observations with filter %s not in config' % (filterName))\n            #    bandIndex = -1\n            try:\n                bandIndex = self.bands.index(self.filterToBand[filterName])\n            except:\n                self.fgcmLog.info('WARNING: observations with filter %s not in config' % (filterName))\n                bandIndex = -1\n\n            # obsFilterName is an array from fits/numpy.  filterName needs to be encoded to match\n            use, = np.where(obsFilterName == filterName.encode('utf-8'))\n            if use.size == 0:\n                self.fgcmLog.info('WARNING: no observations in filter %s' % (filterName))\n            else:\n                snmm.getArray(self.obsLUTFilterIndexHandle)[use] = filterIndex\n                snmm.getArray(self.obsBandIndexHandle)[use] = bandIndex\n\n        self.fgcmLog.info('Observations matched in %.1f seconds.' %\n                         (time.time() - startTime))\n\n\n        #obs=None\n\n        #startTime=time.time()\n        #self.fgcmLog.info('Reading in star positions...')\n        #pos=fitsio.read(self.indexFile,ext='POS')\n        #self.fgcmLog.info('Done reading in %d unique star positions in %.1f secondds.' %\n        #                 (pos.size,time.time()-startTime))\n\n        #  nStars: total number of unique stars\n        #self.nStars = pos.size\n        self.nStars = objID.size\n\n        #  objID: unique object ID\n        self.objIDHandle = snmm.createArray(self.nStars,dtype='i4')\n        #  objRA: mean RA for object\n        self.objRAHandle = snmm.createArray(self.nStars,dtype='f8')\n        #  objDec: mean Declination for object\n        self.objDecHandle = snmm.createArray(self.nStars,dtype='f8')\n        #  objObsIndex: for each object, the first\n        self.objObsIndexHandle = snmm.createArray(self.nStars,dtype='i4')\n        #  objNobs: number of observations of this object (all bands)\n        self.objNobsHandle = snmm.createArray(self.nStars,dtype='i4')\n        #  objNGoodObsHandle: number of good observations, per band\n        self.objNGoodObsHandle = snmm.createArray((self.nStars,self.nBands),dtype='i4')\n\n        #snmm.getArray(self.objIDHandle)[:] = pos['FGCM_ID'][:]\n        #snmm.getArray(self.objRAHandle)[:] = pos['RA'][:]\n        #snmm.getArray(self.objDecHandle)[:] = pos['DEC'][:]\n        snmm.getArray(self.objIDHandle)[:] = objID\n        snmm.getArray(self.objRAHandle)[:] = objRA\n        snmm.getArray(self.objDecHandle)[:] = objDec\n\n        #try:\n            # new field name\n        #    snmm.getArray(self.objObsIndexHandle)[:] = pos['OBSARRINDEX'][:]\n        #except:\n            # old field name\n        #    snmm.getArray(self.objObsIndexHandle)[:] = pos['OBSINDEX'][:]\n        #snmm.getArray(self.objNobsHandle)[:] = pos['NOBS'][:]\n        snmm.getArray(self.objObsIndexHandle)[:] = objObsIndex\n        snmm.getArray(self.objNobsHandle)[:] = objNobs\n\n\n        #  minObjID: minimum object ID\n        self.minObjID = np.min(snmm.getArray(self.objIDHandle))\n        #  maxObjID: maximum object ID\n        self.maxObjID = np.max(snmm.getArray(self.objIDHandle))\n\n        #  obsObjIDIndex: object ID Index of each observation\n        #    (to get objID, then objID[obsObjIDIndex]\n\n        startTime = time.time()\n        self.fgcmLog.info('Indexing star observations...')\n        self.obsObjIDIndexHandle = snmm.createArray(self.nStarObs,dtype='i4')\n        obsObjIDIndex = snmm.getArray(self.obsObjIDIndexHandle)\n        objID = snmm.getArray(self.objIDHandle)\n        obsIndex = snmm.getArray(self.obsIndexHandle)\n        objObsIndex = snmm.getArray(self.objObsIndexHandle)\n        objNobs = snmm.getArray(self.objNobsHandle)\n        ## FIXME: check if this extra obsIndex reference is necessary or not.\n        ##   probably extraneous.\n        for i in xrange(self.nStars):\n            obsObjIDIndex[obsIndex[objObsIndex[i]:objObsIndex[i]+objNobs[i]]] = i\n        self.fgcmLog.info('Done indexing in %.1f seconds.' %\n                         (time.time() - startTime))\n\n        #pos=None\n        obsObjIDIndex = None\n        objID = None\n        obsIndex = None\n        objObsIndex = None\n        objNobs = None\n\n        # and create a objFlag which flags bad stars as they fall out...\n\n        self.objFlagHandle = snmm.createArray(self.nStars,dtype='i2')\n\n        # and read in the previous bad stars if available\n        #if (self.inBadStarFile is not None):\n        #   self.fgcmLog.info('Reading in list of previous bad stars from %s' %\n        #                     (self.inBadStarFile))\n\n        #    objID = snmm.getArray(self.objIDHandle)\n        #    objFlag = snmm.getArray(self.objFlagHandle)\n\n        #    inBadStars = fitsio.read(self.inBadStarFile,ext=1)\n\n        #    a,b=esutil.numpy_util.match(inBadStars['OBJID'],\n        #                                objID)\n\n        #    self.fgcmLog.info('Flagging %d stars as bad.' %\n        #                     (a.size))\n\n        #    objFlag[b] = inBadStars['OBJFLAG'][a]\n        if (flagID is not None):\n            # the objFlag contains information on RESERVED stars\n            objID = snmm.getArray(self.objIDHandle)\n            objFlag = snmm.getArray(self.objFlagHandle)\n\n            a,b=esutil.numpy_util.match(flagID, objID)\n\n            test,=np.where((flagFlag[a] & objFlagDict['VARIABLE']) > 0)\n            self.fgcmLog.info('Flagging %d stars as variable from previous cycles.' %\n                             (test.size))\n            test,=np.where((flagFlag[a] & objFlagDict['RESERVED']) > 0)\n            self.fgcmLog.info('Flagging %d stars as reserved from previous cycles.' %\n                             (test.size))\n\n            objFlag[b] = flagFlag[a]\n        else:\n            # we want to reserve stars, if necessary\n            if self.reserveFraction > 0.0:\n                objFlag = snmm.getArray(self.objFlagHandle)\n\n                nReserve = int(self.reserveFraction * objFlag.size)\n                reserve = np.random.choice(objFlag.size,\n                                           size=nReserve,\n                                           replace=False)\n\n                self.fgcmLog.info('Reserving %d stars from the fit.' % (nReserve))\n                objFlag[reserve] |= objFlagDict['RESERVED']\n\n\n\n        # And we need to record the mean mag, error, SED slopes...\n\n        #  objMagStdMean: mean standard magnitude of each object, per band\n        self.objMagStdMeanHandle = snmm.createArray((self.nStars,self.nBands),dtype='f4',\n                                                    syncAccess=True)\n        #  objMagStdMeanErr: error on the mean standard mag of each object, per band\n        self.objMagStdMeanErrHandle = snmm.createArray((self.nStars,self.nBands),dtype='f4')\n        #  objSEDSlope: linearized approx. of SED slope of each object, per band\n        self.objSEDSlopeHandle = snmm.createArray((self.nStars,self.nBands),dtype='f4',\n                                                  syncAccess=True)\n        #  objMagStdMeanNoChrom: mean std mag of each object, no chromatic correction, per band\n        self.objMagStdMeanNoChromHandle = snmm.createArray((self.nStars,self.nBands),dtype='f4')\n\n        # note: if this takes too long it can be moved to the star computation,\n        #       but it seems pretty damn fast (which may raise the question of\n        #       why it needs to be precomputed...)\n        # compute secZenith for every observation\n\n        startTime=time.time()\n        self.fgcmLog.info('Computing secZenith for each star observation...')\n        objRARad = np.radians(snmm.getArray(self.objRAHandle))\n        objDecRad = np.radians(snmm.getArray(self.objDecHandle))\n        ## FIXME: deal with this at some point...\n        hi,=np.where(objRARad > np.pi)\n        objRARad[hi] -= 2*np.pi\n        obsExpIndex = snmm.getArray(self.obsExpIndexHandle)\n        obsObjIDIndex = snmm.getArray(self.obsObjIDIndexHandle)\n        obsIndex = snmm.getArray(self.obsIndexHandle)\n\n        obsHARad = (fgcmPars.expTelHA[obsExpIndex] +\n                    fgcmPars.expTelRA[obsExpIndex] -\n                    objRARad[obsObjIDIndex])\n        tempSecZenith = 1./(np.sin(objDecRad[obsObjIDIndex]) * fgcmPars.sinLatitude +\n                            np.cos(objDecRad[obsObjIDIndex]) * fgcmPars.cosLatitude *\n                            np.cos(obsHARad))\n\n        bad,=np.where(obsFlag != 0)\n        tempSecZenith[bad] = 1.0  # filler here, but these stars aren't used\n        snmm.getArray(self.obsSecZenithHandle)[:] = tempSecZenith\n        self.fgcmLog.info('Computed secZenith in %.1f seconds.' %\n                         (time.time() - startTime))\n\n        if (computeNobs):\n            self.fgcmLog.info('Checking stars with all exposure numbers')\n            allExpsIndex = np.arange(fgcmPars.expArray.size)\n            self.selectStarsMinObsExpIndex(allExpsIndex)\n\n\n\n\n    def selectStarsMinObsExpIndex(self, goodExpsIndex, temporary=False,\n                                  minObsPerBand=None):\n        \"\"\"\n        Select stars that have at least the minimum number of observations per band,\n         using a list of good exposures\n\n        parameters\n        ----------\n        goodExpsIndex: int array\n           Array of good (photometric) exposure indices\n        temporary: bool, default=False\n           Only flag bad objects temporarily\n        minObsPerBand: int\n           Specify the min obs per band, or use self.minObsPerBand\n        \"\"\"\n\n        if (minObsPerBand is None):\n            minObsPerBand = self.minObsPerBand\n\n        # Given a list of good exposures, which stars have at least minObs observations\n        #  in each required band?\n\n        obsExpIndex = snmm.getArray(self.obsExpIndexHandle)\n        obsBandIndex = snmm.getArray(self.obsBandIndexHandle)\n        obsObjIDIndex = snmm.getArray(self.obsObjIDIndexHandle)\n        objNGoodObs = snmm.getArray(self.objNGoodObsHandle)\n        obsFlag = snmm.getArray(self.obsFlagHandle)\n        objFlag = snmm.getArray(self.objFlagHandle)\n\n        self.fgcmLog.info('Selecting good stars from %d exposures.' %\n                         (goodExpsIndex.size))\n        _,goodObs=esutil.numpy_util.match(goodExpsIndex,obsExpIndex)\n\n        # Filter out bad (previously flagged) individual observations\n        gd, = np.where(obsFlag[goodObs] == 0)\n        goodObs = goodObs[gd]\n\n        # count all the good observations\n        objNGoodObs[:,:] = 0\n        np.add.at(objNGoodObs,\n                  (obsObjIDIndex[goodObs],\n                   obsBandIndex[goodObs]),\n                  1)\n\n        # and find the minimum of all the required bands\n        minObs = objNGoodObs[:,self.bandRequiredIndex].min(axis=1)\n\n        # reset too few obs flag if it's already set\n        if not temporary:\n            objFlag &= ~objFlagDict['TOO_FEW_OBS']\n\n        # choose the bad objects with too few observations\n        bad,=np.where(minObs < minObsPerBand)\n\n        if (not temporary) :\n            objFlag[bad] |= objFlagDict['TOO_FEW_OBS']\n\n            self.fgcmLog.info('Flagging %d of %d stars with TOO_FEW_OBS' % (bad.size,self.nStars))\n        else:\n            objFlag[bad] |= objFlagDict['TEMPORARY_BAD_STAR']\n\n            self.fgcmLog.info('Flagging %d of %d stars with TEMPORARY_BAD_STAR' % (bad.size,self.nStars))\n\n\n    def selectStarsMinObsExpAndCCD(self, goodExps, goodCCDs, minObsPerBand=None):\n        \"\"\"\n        Select stars that have at least the minimum number of observations per band,\n         using a list of good exposures and ccds.\n\n        parameters\n        ----------\n        goodExps: int array\n           Array of good (photometric) exposure numbers\n        goodCCDs: int array\n           Array of good (photometric) ccd numbers\n        minObsPerBand: int\n           Specify the min obs per band, or use self.minObsPerBand\n        \"\"\"\n\n        if (minObsPerBand is None):\n            minObsPerBand = self.minObsPerBand\n\n        if (goodExps.size != goodCCDs.size) :\n            raise ValueError(\"Length of goodExps and goodCCDs must be the same\")\n\n        obsExp = snmm.getArray(self.obsExpHandle)\n        obsExpIndex = snmm.getArray(self.obsExpIndexHandle)\n        obsCCD = snmm.getArray(self.obsCCDHandle)\n        obsBandIndex = snmm.getArray(self.obsBandIndexHandle)\n        obsObjIDIndex = snmm.getArray(self.obsObjIDIndexHandle)\n        objNGoodObs = snmm.getArray(self.objNGoodObsHandle)\n        obsFlag = snmm.getArray(self.obsFlagHandle)\n        objFlag = snmm.getArray(self.objFlagHandle)\n\n        self.fgcmLog.info( 'Selecting good stars from %d exposure/ccd pairs.' %\n                         (goodExps.size))\n\n        # hash together exposure and ccd and match this\n        obsHash = obsExp * (self.nCCD + self.ccdStartIndex) + obsCCD\n        goodHash = goodExps * (self.nCCD + self.ccdStartIndex) + goodCCDs\n\n        _,goodObs = esutil.numpy_util.match(goodHash, obsHash)\n\n        # Filter out bad (previously flagged) individual observations\n        gd, = np.where(obsFlag[goodObs] == 0)\n        goodObs = goodObs[gd]\n\n        # count all the good observations\n        objNGoodObs[:,:] = 0\n        np.add.at(objNGoodObs,\n                  (obsObjIDIndex[goodObs],\n                   obsBandIndex[goodObs]),\n                  1)\n\n                # and find the minimum of all the required bands\n        minObs = objNGoodObs[:,self.bandRequiredIndex].min(axis=1)\n\n        # reset too few obs flag if it's already set\n        objFlag &= ~objFlagDict['TOO_FEW_OBS']\n\n        # choose the bad objects with too few observations\n        bad,=np.where(minObs < minObsPerBand)\n\n        objFlag[bad] |= objFlagDict['TOO_FEW_OBS']\n        self.fgcmLog.info('Flagging %d of %d stars with TOO_FEW_OBS' % (bad.size,self.nStars))\n\n\n    def plotStarMap(self,mapType='initial'):\n        \"\"\"\n        Plot star map.\n\n        parameters\n        ----------\n        mapType: string, default='initial'\n           A key for labeling the map.\n        \"\"\"\n\n        import healpy as hp\n        try:\n            from .fgcmPlotmaps import plot_hpxmap\n        except:\n            self.fgcmLog.info(\"Map plotting not available.  Sorry!\")\n            return\n\n        goodStars,=np.where(snmm.getArray(self.objFlagHandle)[:] == 0.0)\n\n        theta = (90.0-snmm.getArray(self.objDecHandle)[goodStars])*np.pi/180.\n        phi = snmm.getArray(self.objRAHandle)[goodStars]*np.pi/180.\n\n        ipring = hp.ang2pix(self.mapNSide,theta,phi)\n\n        densMap = esutil.stat.histogram(ipring,min=0,max=12*self.mapNSide*self.mapNSide-1)\n        densMap = densMap.astype(np.float32)\n\n        bad,=np.where(densMap == 0)\n        densMap[bad] = hp.UNSEEN\n\n        raStarRot = snmm.getArray(self.objRAHandle)[goodStars]\n        hi,=np.where(raStarRot > 180.0)\n        raStarRot[hi] -= 360.0\n\n        decStar = snmm.getArray(self.objDecHandle)[goodStars]\n\n        fig,ax = plot_hpxmap(densMap,\n                             raRange=[np.min(raStarRot),np.max(raStarRot)],\n                             decRange=[np.min(decStar),np.max(decStar)],\n                             lonRef = self.mapLongitudeRef)\n\n        fig.savefig('%s/%s_%sGoodStars.png' % (self.plotPath, self.outfileBaseWithCycle,\n                                               mapType))\n        plt.close(fig)\n\n    def computeObjectSEDSlopes(self,objIndicesIn):\n        \"\"\"\n        Compute fnuprime (object SED slopes) for a list of objects.\n        Output is saved in objSEDSlope.\n\n        parameters\n        ----------\n        objIndicesIn: int array\n           Array of object indices to do computation\n        \"\"\"\n\n        if self.nBands < 3:\n            # cannot compute SED slopes ... just leave at 0\n            return\n\n        # work on multiple indices\n\n        objMagStdMean = snmm.getArray(self.objMagStdMeanHandle)\n        objSEDSlope = snmm.getArray(self.objSEDSlopeHandle)\n\n        objMagStdMeanLock = snmm.getArrayBase(self.objMagStdMeanHandle).get_lock()\n        objSEDSlopeLock = snmm.getArrayBase(self.objSEDSlopeHandle).get_lock()\n\n        # select out good ones\n        # NOTE: assumes that the required bands are sequential.\n        #  in fact, this whole thing does.\n        ## FIXME: require required bands to be explicitly sequential\n\n        ## NOTE: this check is probably redundant, since we already have\n        #   a list of good stars in most cases.\n\n        # protect access to copy to local\n        objMagStdMeanLock.acquire()\n\n        objMagStdMeanOI = objMagStdMean[objIndicesIn,:]\n\n        # release access\n        objMagStdMeanLock.release()\n\n        # and make a temporary local copy of the SED\n        objSEDSlopeOI = np.zeros((objIndicesIn.size,self.nBands),dtype='f4')\n\n        maxMag = np.max(objMagStdMeanOI[:,self.bandRequiredIndex.min():\n                                              self.bandRequiredIndex.max()+1],axis=1)\n\n        goodIndicesOI,=np.where(maxMag < 90.0)\n\n\n        # can this be non-looped?\n        S=np.zeros((goodIndicesOI.size,self.nBands-1),dtype='f8')\n        for i in xrange(self.nBands-1):\n            S[:,i] = (-1/self.magConstant) * (objMagStdMeanOI[goodIndicesOI,i+1] -\n                                              objMagStdMeanOI[goodIndicesOI,i]) / (\n                (self.lambdaStdBand[i+1] - self.lambdaStdBand[i]))\n\n        ## FIXME: will have to handle u band \"extra\"\n\n        tempIndex=self.bandRequiredIndex[0]\n        objSEDSlopeOI[goodIndicesOI, tempIndex] = (\n            S[:, tempIndex] + self.sedFitBandFudgeFactors[0] * (\n                S[:, tempIndex+1] + S[:, tempIndex]))\n\n        # and the middle ones...\n        #  these are straight averages\n        for tempIndex in self.bandRequiredIndex[1:-1]:\n            objSEDSlopeOI[goodIndicesOI,tempIndex] = (\n                self.sedFitBandFudgeFactors[tempIndex] * (\n                    S[:,tempIndex-1] + S[:,tempIndex]) / 2.0)\n\n        # and the last one\n        tempIndex = self.bandRequiredIndex[-1]\n        objSEDSlopeOI[goodIndicesOI,tempIndex] = (\n            S[:,tempIndex-1] + self.sedFitBandFudgeFactors[-1] * (\n                (self.lambdaStdBand[tempIndex] - self.lambdaStdBand[tempIndex-1]) /\n                (self.lambdaStdBand[tempIndex] - self.lambdaStdBand[tempIndex-2])) *\n            (S[:,tempIndex-1] - S[:,tempIndex-2]))\n\n        # and the extra bands, only redward now\n        #tempIndex = self.bandRequiredIndex[-1]\n        #for i in xrange(len(self.bandExtraIndex)):\n        #    extraIndex=self.bandExtraIndex[i]\n        #    use,=np.where(objMagStdMeanOI[goodIndicesOI,extraIndex] < 90.0)\n        #    objSEDSlopeOI[goodIndicesOI[use],extraIndex] = (\n        #        S[use,tempIndex-1] + self.sedExtraBandFudgeFactors[i] * (\n        #            (self.lambdaStd[tempIndex] - self.lambdaStd[tempIndex-1]) /\n        #            (self.lambdaStd[tempIndex] - self.lambdaStd[tempIndex-2])) *\n        #        (S[use,tempIndex-1] - S[use,tempIndex-2]))\n        for i in xrange(len(self.bandExtraIndex)):\n            extraIndex=self.bandExtraIndex[i]\n            use,=np.where(objMagStdMeanOI[goodIndicesOI,extraIndex] < 90.0)\n            objSEDSlopeOI[goodIndicesOI[use],extraIndex] = (\n                S[use,extraIndex-1] + self.sedExtraBandFudgeFactors[i] * (\n                    (self.lambdaStdBand[extraIndex] - self.lambdaStdBand[extraIndex-1]) /\n                    (self.lambdaStdBand[extraIndex] - self.lambdaStdBand[extraIndex-2])) *\n                (S[use,extraIndex-1] - S[use,extraIndex-2]))\n\n        # and save the values, protected\n        objSEDSlopeLock.acquire()\n\n        objSEDSlope[objIndicesIn,:] = objSEDSlopeOI\n\n        objSEDSlopeLock.release()\n\n    def computeObjectSEDSlopesLUT(self, objIndicesIn, fgcmLUT):\n        \"\"\"\n        Compute fnuprime (object SED slopes) for a list of objects, from the SED fit\n          in the look-up table.  Experimental.\n        Output is saved in objSEDSlope.\n\n        parameters\n        ----------\n        objIndicesIn: int array\n           Array of object indices to do computation\n        fgcmLUT: FgcmLUT\n        \"\"\"\n\n        objMagStdMean = snmm.getArray(self.objMagStdMeanHandle)\n        objSEDSlope = snmm.getArray(self.objSEDSlopeHandle)\n\n        objMagStdMeanLock = snmm.getArrayBase(self.objMagStdMeanHandle).get_lock()\n        objSEDSlopeLock = snmm.getArrayBase(self.objSEDSlopeHandle).get_lock()\n\n        # protect access to copy to local\n        objMagStdMeanLock.acquire()\n\n        objMagStdMeanOI = objMagStdMean[objIndicesIn,:]\n\n        # release access\n        objMagStdMeanLock.release()\n\n        # and make a temporary local copy of the SED\n        #objSEDSlopeOI = np.zeros((objIndicesIn.size,self.nBands),dtype='f4')\n\n        # compute SED color...\n        ## FIXME: make this configurable\n        objSEDColorOI = objMagStdMeanOI[:,0] - objMagStdMeanOI[:,2]\n\n        # do the look-up\n        objSEDSlopeOI = fgcmLUT.computeSEDSlopes(objSEDColorOI)\n\n        # and save the values, protected\n        objSEDSlopeLock.acquire()\n\n        objSEDSlope[objIndicesIn,:] = objSEDSlopeOI\n\n        objSEDSlopeLock.release()\n\n\n\n    def performColorCuts(self):\n        \"\"\"\n        Make the color cuts that are specified in the config.\n        \"\"\"\n\n        if (not self.magStdComputed):\n            raise ValueError(\"Must compute magStd before performing color cuts\")\n\n        objMagStdMean = snmm.getArray(self.objMagStdMeanHandle)\n        objFlag = snmm.getArray(self.objFlagHandle)\n\n        for cCut in self.starColorCuts:\n            thisColor = objMagStdMean[:,cCut[0]] - objMagStdMean[:,cCut[1]]\n            bad,=np.where((thisColor < cCut[2]) |\n                          (thisColor > cCut[3]))\n            objFlag[bad] |= objFlagDict['BAD_COLOR']\n\n            self.fgcmLog.info('Flag %d stars of %d with BAD_COLOR' % (bad.size,self.nStars))\n\n    def applySuperStarFlat(self,fgcmPars):\n        \"\"\"\n        Apply superStarFlat to raw magnitudes.\n\n        parameters\n        ----------\n        fgcmPars: FgcmParameters\n        \"\"\"\n\n        self.fgcmLog.info('Applying SuperStarFlat to raw magnitudes')\n\n        obsMagADU = snmm.getArray(self.obsMagADUHandle)\n        obsSuperStarApplied = snmm.getArray(self.obsSuperStarAppliedHandle)\n        obsExpIndex = snmm.getArray(self.obsExpIndexHandle)\n        obsCCDIndex = snmm.getArray(self.obsCCDHandle) - self.ccdStartIndex\n\n        # two different tracks, if x/y available or not.\n\n        if self.hasXY:\n            # new style\n\n            from .fgcmUtilities import poly2dFunc\n\n            obsX = snmm.getArray(self.obsXHandle)\n            obsY = snmm.getArray(self.obsYHandle)\n\n            epochFilterHash = (fgcmPars.expEpochIndex[obsExpIndex]*\n                               (fgcmPars.nLUTFilter+1)*(fgcmPars.nCCD+1) +\n                               fgcmPars.expLUTFilterIndex[obsExpIndex]*\n                               (fgcmPars.nCCD+1) +\n                               obsCCDIndex)\n\n            h, rev = esutil.stat.histogram(epochFilterHash, rev=True)\n\n            for i in xrange(h.size):\n                if h[i] == 0: continue\n\n                i1a = rev[rev[i]:rev[i+1]]\n\n                # get the indices for this epoch/filter/ccd\n                epInd = fgcmPars.expEpochIndex[obsExpIndex[i1a[0]]]\n                fiInd = fgcmPars.expLUTFilterIndex[obsExpIndex[i1a[0]]]\n                cInd = obsCCDIndex[i1a[0]]\n\n                obsSuperStarApplied[i1a] = poly2dFunc(np.vstack((obsX[i1a],\n                                                        obsY[i1a])),\n                                                       *fgcmPars.parSuperStarFlat[epInd, fiInd, cInd, :])\n        else:\n            # old style\n\n            obsSuperStarApplied[:] = fgcmPars.expCCDSuperStar[obsExpIndex,\n                                                              obsCCDIndex]\n\n        # And finally apply the superstar correction\n        obsMagADU[:] += obsSuperStarApplied[:]\n\n    def applyApertureCorrection(self,fgcmPars):\n        \"\"\"\n        Apply aperture corrections to raw magnitudes.\n\n        parameters\n        ----------\n        fgcmPars: FgcmParameters\n        \"\"\"\n\n        self.fgcmLog.info('Applying ApertureCorrections to raw magnitudes')\n\n        obsExpIndex = snmm.getArray(self.obsExpIndexHandle)\n\n        obsMagADU = snmm.getArray(self.obsMagADUHandle)\n\n        # Note that EXP^gray = < <mstd>_j - mstd_ij >\n        #  when we have seeing loss, that makes mstd_ij larger and EXP^gray smaller\n        #  So the slope of aperCorr is negative.\n        #  If we add aperCorr to each of mstd_ij, then we get a smaller (brighter)\n        #  magnitude.  And this will bring mstd_ij closer to <mstd>_j\n\n        obsMagADU[:] += fgcmPars.expApertureCorrection[obsExpIndex]\n\n    def computeModelMagErrors(self, fgcmPars):\n        \"\"\"\n        Compute model magnitude errors.\n\n        parameters\n        ----------\n        fgcmPars: FgcmParameters\n        \"\"\"\n\n        if (fgcmPars.compModelErrFwhmPivot[0] <= 0.0) :\n            self.fgcmLog.info('No model for mag errors, so mag errors are unchanged.')\n            return\n\n        if not self.modelMagErrors:\n            self.fgcmLog.info('Model magnitude errors are turned off.')\n            return\n\n        if not self.magStdComputed:\n            raise RuntimeError(\"Must run FgcmChisq to compute magStd before computeModelMagErrors\")\n\n        self.fgcmLog.info('Computing model magnitude errors for photometric observations')\n\n        objFlag = snmm.getArray(self.objFlagHandle)\n        objNGoodObs = snmm.getArray(self.objNGoodObsHandle)\n        objMagStdMean = snmm.getArray(self.objMagStdMeanHandle)\n\n        obsObjIDIndex = snmm.getArray(self.obsObjIDIndexHandle)\n        obsFlag = snmm.getArray(self.obsFlagHandle)\n        obsExpIndex = snmm.getArray(self.obsExpIndexHandle)\n        obsBandIndex = snmm.getArray(self.obsBandIndexHandle)\n        obsMagADU = snmm.getArray(self.obsMagADUHandle)\n        obsMagADUErr = snmm.getArray(self.obsMagADUErrHandle)\n        obsMagADUModelErr = snmm.getArray(self.obsMagADUModelErrHandle)\n        obsMagStd = snmm.getArray(self.obsMagStdHandle)\n\n        obsExptime = fgcmPars.expExptime[obsExpIndex]\n        obsFwhm = fgcmPars.expFwhm[obsExpIndex]\n        obsSkyBrightness = fgcmPars.expSkyBrightness[obsExpIndex]\n\n        # we will compute all stars that are possibly good, including reserved\n        resMask = 255 & ~objFlagDict['RESERVED']\n        goodStars, = np.where((objFlag & resMask) == 0)\n\n        goodStarsSub, goodObs = esutil.numpy_util.match(goodStars,\n                                                        obsObjIDIndex,\n                                                        presorted=True)\n\n        # Do we want to allow more selection of exposures here?\n        gd, = np.where((obsFlag[goodObs] == 0) &\n                       (fgcmPars.expFlag[obsExpIndex[goodObs]] == 0))\n        goodObs = goodObs[gd]\n        goodStarsSub = goodStarsSub[gd]\n\n        # loop over bands\n        for bandIndex in xrange(fgcmPars.nBands):\n            use, = np.where((obsBandIndex[goodObs] == bandIndex) &\n                            (objNGoodObs[obsObjIDIndex[goodObs], bandIndex] > self.minObsPerBand))\n            pars = fgcmPars.compModelErrPars[:, bandIndex]\n            fwhmPivot = fgcmPars.compModelErrFwhmPivot[bandIndex]\n            skyPivot = fgcmPars.compModelErrSkyPivot[bandIndex]\n            exptimePivot = fgcmPars.compModelErrExptimePivot[bandIndex]\n\n            obsMagADUMeanGOu = (objMagStdMean[obsObjIDIndex[goodObs[use]], bandIndex] -\n                                (obsMagStd[goodObs[use]] - obsMagADU[goodObs[use]]) -\n                                2.5 * np.log10(obsExptime[goodObs[use]] / exptimePivot))\n\n            modErr = 10.**(pars[0] + pars[1] * obsMagADUMeanGOu + pars[2] * obsMagADUMeanGOu**2. +\n                           pars[3] * np.log10(obsFwhm[goodObs[use]] / fwhmPivot) +\n                           pars[4] * np.log10(obsSkyBrightness[goodObs[use]] / skyPivot) +\n                           pars[5] * obsMagADUMeanGOu * np.log10(obsFwhm[goodObs[use]] / fwhmPivot) +\n                           pars[6] * obsMagADUMeanGOu * np.log10(obsSkyBrightness[goodObs[use]] / skyPivot))\n\n            obsMagADUModelErr[goodObs[use]] = np.sqrt(modErr**2. + self.sigma0Phot**2.)\n\n            # debug bit...\n            \"\"\"\n            plt.set_cmap('viridis')\n            fig = plt.figure(1, figsize=(8,6))\n            fig.clf()\n            ax = fig.add_subplot(111)\n\n            ax.hexbin(obsMagADUErr[goodObs[use]], obsMagADUModelErr[goodObs[use]], bins='log')\n            ax.plot([0., 0.08], [0., 0.08], 'r--')\n            ax.set_title('band = %s, %d' % (self.bands[bandIndex], use.size))\n            ax.set_xlabel('Observed error')\n            ax.set_ylabel('Model Error')\n\n            fig.savefig('temp_%s.png' % (self.bands[bandIndex]))\n            plt.close(fig)\n            \"\"\"\n    def saveFlagStarIndices(self,flagStarFile):\n        \"\"\"\n        Save flagged stars to fits.\n\n        parameters\n        ----------\n        flagStarFile: string\n           Filename to output.\n        \"\"\"\n\n        import fitsio\n\n        flagObjStruct = self.getFlagStarIndices()\n\n        self.fgcmLog.info('Saving %d flagged star indices to %s' %\n                         (flagObjStruct.size,flagStarFile))\n\n        # set clobber == True?\n        fitsio.write(flagStarFile,flagObjStruct,clobber=True)\n\n    def getFlagStarIndices(self):\n        \"\"\"\n        Retrieve flagged star indices.\n        \"\"\"\n\n        objID = snmm.getArray(self.objIDHandle)\n        objFlag = snmm.getArray(self.objFlagHandle)\n\n        # we only store VARIABLE and RESERVED stars\n        # everything else should be recomputed based on the good exposures, calibrations, etc\n        flagMask = (objFlagDict['VARIABLE'] |\n                    objFlagDict['RESERVED'])\n\n        flagged,=np.where((objFlag & flagMask) > 0)\n\n        flagObjStruct = np.zeros(flagged.size,dtype=[('OBJID',objID.dtype),\n                                                     ('OBJFLAG',objFlag.dtype)])\n        flagObjStruct['OBJID'] = objID[flagged]\n        flagObjStruct['OBJFLAG'] = objFlag[flagged]\n\n        return flagObjStruct\n\n    def saveStdStars(self, starFile, fgcmPars):\n        \"\"\"\n        Save standard stars.  Note that this does not fill in holes.\n\n        parameters\n        ----------\n        starFile: string\n           Output star file\n        fgcmPars: FgcmParameters\n        \"\"\"\n\n        import fitsio\n\n        self.fgcmLog.info( 'Saving standard stars to %s' % (starFile))\n\n        objID = snmm.getArray(self.objIDHandle)\n        objFlag = snmm.getArray(self.objFlagHandle)\n        objRA = snmm.getArray(self.objRAHandle)\n        objDec = snmm.getArray(self.objDecHandle)\n        objNGoodObs = snmm.getArray(self.objNGoodObsHandle)\n        objMagStdMean = snmm.getArray(self.objMagStdMeanHandle)\n        objMagStdMeanErr = snmm.getArray(self.objMagStdMeanErrHandle)\n\n        # reset TEMPORARY_BAD_STAR\n        #objFlag &= ~objFlagDict['TEMPORARY_BAD_STAR']\n\n        # only take photometric exposures...\n        #goodExpsIndex, = np.where(fgcmPars.expFlag == 0)\n\n        # this doesn't work because we'd have to recompute all the mags\n        # this is more honest about what stars are actually well measured\n\n        #self.selectStarsMinObsExpIndex(goodExpsIndex, minObsPerBand=1, temporary=True)\n\n        rejectMask = (objFlagDict['BAD_COLOR'] | objFlagDict['VARIABLE'] |\n                      objFlagDict['TOO_FEW_OBS'])\n\n        goodStars, = np.where((objFlag & rejectMask) == 0)\n\n        outCat = np.zeros(goodStars.size, dtype=[('FGCM_ID', 'i8'),\n                                                 ('RA', 'f8'),\n                                                 ('DEC', 'f8'),\n                                                 ('NGOOD', 'i4', self.bands.size),\n                                                 ('MAG_STD', 'f4', self.bands.size),\n                                                 ('MAGERR_STD', 'f4', self.bands.size)])\n\n        outCat['FGCM_ID'] = objID[goodStars]\n        outCat['RA'] = objRA[goodStars]\n        outCat['DEC'] = objDec[goodStars]\n        outCat['NGOOD'] = objNGoodObs[goodStars, :]\n        outCat['MAG_STD'][:, :] = objMagStdMean[goodStars, :]\n        outCat['MAGERR_STD'][:, :] = objMagStdMeanErr[goodStars, :]\n\n        # reset TEMPORARY_BAD_STAR\n        #objFlag &= ~objFlagDict['TEMPORARY_BAD_STAR']\n\n        fitsio.write(starFile, outCat, clobber=True)\n\n    def __getstate__(self):\n        # Don't try to pickle the logger.\n\n        state = self.__dict__.copy()\n        del state['fgcmLog']\n        return state\n", "meta": {"hexsha": "266aa32dd92d0a0c12b8489a7816cd454061d8d3", "size": 47197, "ext": "py", "lang": "Python", "max_stars_repo_path": "fgcm/fgcmStars.py", "max_stars_repo_name": "gcmshadow/fgcm", "max_stars_repo_head_hexsha": "f94231d90dc5f1b5711af3b1e259d26a6144cc15", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fgcm/fgcmStars.py", "max_issues_repo_name": "gcmshadow/fgcm", "max_issues_repo_head_hexsha": "f94231d90dc5f1b5711af3b1e259d26a6144cc15", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fgcm/fgcmStars.py", "max_forks_repo_name": "gcmshadow/fgcm", "max_forks_repo_head_hexsha": "f94231d90dc5f1b5711af3b1e259d26a6144cc15", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0313825276, "max_line_length": 108, "alphanum_fraction": 0.6024747336, "include": true, "reason": "import numpy", "num_tokens": 11820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3208212943308302, "lm_q1q2_score": 0.16166382985043162}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct  3 07:47:36 2019\n\n@author: bressler\n\"\"\"\n\n\nimport SBCcode as sbc\nimport numpy as np\nimport scipy\nimport matplotlib.pyplot as plt\nfrom collections import Counter\nimport runlistscatalogue as rlc\nfrom PICOcode.REFPROP.SeitzModel import SeitzModel\nfrom os import listdir\nfrom os.path import isfile,join\n\n#LED_INDUCED_DEAD_TIME_FRACTION= 0.1289\n\n\ndef mult(runs,mergedfilename,Qbins,FeedbackTransducer, lightBins, binsname, LED_INDUCED_DEAD_TIME_FRACTION):\n    if FeedbackTransducer == \"PT4\":\n        pt = 3\n    elif FeedbackTransducer == \"PT6\":\n        pt = 5\n    spectrumFile = open('/nashome/b/bressler/sbcoutput/'+mergedfilename+\"%s_coincident_spectrum.txt\"%binsname,'w')\n    separator = '\\t'\n    spectrumFile.write(\"lightBin\\t\"+separator.join([\"Q=%.1f-%.1fkeV\"%(Qbins[i],\n                                                                      Qbins[i+1]) for i in range(len(Qbins)-1)])+\"\\n\")\n    spectrumFile_multiples = open('/nashome/b/bressler/sbcoutput/'+mergedfilename+\"%s_coincident_spectrum_multibub.txt\"%binsname,'w')\n    spectrumFile_multiples.write(\"lightBin\\t\"+separator.join([\"Q=%.1f-%.1fkeV\"%(Qbins[i],\n                                                                      Qbins[i+1]) for i in range(len(Qbins)-1)])+\"\\n\")\n    fractionFile = open('/nashome/b/bressler/sbcoutput/'+mergedfilename+\"%s_coincident_spectrum_fraction.txt\"%binsname,'w')\n    fractionFile.write(\"lightBin\\t\"+separator.join([\"Q=%.1f-%.1fkeV\"%(Qbins[i],\n                                                                      Qbins[i+1]) for i in range(len(Qbins)-1)])+\"\\n\")\n    \n    #with open(\"/nashome/b/bressler/sbcoutput/%s_merged_oldPMT.txt\"%mergedfilename,\"r\") as fin:\n    with open(\"/nashome/b/bressler/sbcoutput/%s_merged.txt\"%mergedfilename,\"r\") as fin:\n        data = fin.readlines()\n        \n    headers = data[0].split()\n    runind = headers.index(\"run\")\n    eventind = headers.index(\"event\")\n    xind = headers.index(\"x\")\n    yind = headers.index(\"y\")\n    zind = headers.index(\"z\")\n    lagind = headers.index(\"lag\")\n    spectind = headers.index(\"PMTphe\")\n    blockedind = headers.index('isBlocked')\n    nbubind = headers.index('nbub')\n    x=[]\n    y=[]\n    z=[]\n    evid = []\n    lag = []\n    spect = []\n    isblocked = []\n    nbub = []\n    i=0\n    for line in data:\n        if i>0:\n            split_line = line.split()\n            evid.append(split_line[runind]+\"-\"+split_line[eventind])\n            isblocked.append(float(split_line[blockedind]))\n            x.append(float(split_line[xind]))\n            y.append(float(split_line[yind]))\n            z.append(float(split_line[zind]))\n            lag.append(float(split_line[lagind]))\n            spect.append(float(split_line[spectind]))\n            nbub.append(float(split_line[nbubind]))\n    \n        i+=1\n\n    counts = []\n    nbubs = []\n    didntpass = 0\n    bubInfo = []\n    eventcount = np.zeros(87)\n    spectra = [[] for i in range(87)]\n    twobub_spectra = [[] for i in range(87)]\n    threebub_spectra = [[] for i in range(87)]\n    LT = np.zeros(87)\n    LT_by_Q = np.zeros(len(Qbins)-1)\n    expand_times = [[] for i in range(87)]\n    totbub = 0\n    onebubcount = np.zeros(87)\n    twobubcount = np.zeros(87)\n    threebubcount = np.zeros(87)\n    setpoints = []\n    elt = 0\n    temps = []\n        \n    for run in runs:\n        print(run)\n        z_low = -4\n        z_high = 0\n        preq = 1\n        runrawpath = '/bluearc/storage/SBC-17-data/'+run\n        events = [evnt for evnt in listdir(runrawpath) if not isfile(join(runrawpath,evnt))]\n        Nevents = len(events)\n        runreconpath = \"/pnfs/coupp/persistent/grid_output/SBC-17/output/%s/\"%run\n        historyfilename = runreconpath+\"HistoryAnalysis_%s.bin\"%run\n        history = sbc.DataHandling.ReadBinary.ReadBlock(historyfilename)\n        getbubfile = \"/coupp/data/home/coupp/HumanGetBub_output_SBC-17/HumanGetBub_%s.bin\"%run\n        c = sbc.DataHandling.ReadBinary.ReadBlock(getbubfile)\n\n        eventn = c[\"ev\"]\n        count = Counter(eventn)\n        edges = history[\"PressureEdge\"][pt]\n        centersp = [(edges[i]+edges[i+1])/2 for i in range(len(edges)-1)]\n        #centers = Qvals\n        e0 = sbc.DataHandling.GetSBCEvent.GetEvent(runrawpath,0,\"slowDAQ\")\n        T=np.mean(e0[\"slowDAQ\"][\"T1\"])\n        temps.append(T)\n        sm = SeitzModel(list(edges),T,'xenon')\n        edges_by_Q = sm.Q\n        centers = [(edges_by_Q[i] + edges_by_Q[i+1])/2 for i in range(len(edges_by_Q)-1)]\n\n        print(\"T=%f C\"%T)\n        \n        for c in count:\n            N = count[c]\n            counts.append(N)\n            \"\"\"\n            if N%2 != 0 and N != 1:\n                print(\"lines isn't even\")\n                print(c)\n                print(N)\n            elif N%2 == 0:\n                n = N/2\n                nbubs.append(n)\n                \"\"\"\n        for eventn in range(Nevents):\n            try:\n                indices_back = 30\n                event_ID = run+\"-\"+str(eventn)\n                mergedind = evid.index(event_ID)\n                bl = isblocked[mergedind]\n                light = spect[mergedind]\n                ev_z = z[mergedind]\n                if np.isnan(light):\n                    light = 0\n                ev_z = z[mergedind]\n                #onebub = not np.isnan(runposreco[\"z\"][0][int(eventn)])\n                n_from_merged = nbub[mergedind]\n                n = 0\n                N = count[eventn]\n                if N%2 == 0:\n                    n = N/2\n                    nbubs.append(n)\n                \n                if n_from_merged != n:\n                    print('n and merged n dont match')\n                    print(\"n here: %d\"%n)\n                    print(\"n from merged: %d\"%n_from_merged)\n                e = sbc.DataHandling.GetSBCEvent.GetEvent(runrawpath,eventn,\"slowDAQ\",\"event\")\n                t = e[\"slowDAQ\"][\"elapsed_time\"]\n                tcenters = [(t[i+1] + t[i])/2 for i in range(len(t)-1)]\n                trig_time = t[list(e[\"slowDAQ\"][\"TriggerOut\"]).index(1.0)-indices_back]\n                pslope = np.diff(e[\"slowDAQ\"][FeedbackTransducer])\n                expstartind = list(pslope).index(min(list(pslope)))\n                exp_start = tcenters[expstartind]\n                trig_pressure = e[\"slowDAQ\"][FeedbackTransducer][list(e[\"slowDAQ\"][\"TriggerOut\"]).index(1.0)-indices_back]\n                T = np.mean(e[\"slowDAQ\"][\"T1\"])\n                SM = SeitzModel(trig_pressure,T,'xenon')\n                Q = (SM.Q)\n                #print(Q[0])\n                pset = e[\"event\"][\"Pset\"]\n                ev_lt = e[\"event\"]['livetime']\n                elt += ev_lt\n                if pset not in setpoints:\n                    setpoints.append(pset)\n                    #print(pset)\n                #print(len(history[\"PressureBins\"][eventn]))\n                times = history[\"PressureBins\"][eventn][pt][:]\n                \"\"\"\n                plt.figure()\n                plt.plot([trig_time,trig_time],[0,200],label=\"Bubble time\")\n                plt.plot([exp_start,exp_start],[0,200],label=\"Expansion start\")\n                plt.plot([0,max(t)],[trig_pressure,trig_pressure],label=\"Bubble pressure\")\n                plt.plot(t,e[\"slowDAQ\"][\"PT6\"],label=\"PT6\")\n                plt.plot(tcenters,pslope,label=\"Pressure slope\")\n                plt.xlabel(\"time\",fontsize=18)\n                plt.ylabel(\"signal\",fontsize=18)\n                plt.legend(fontsize=18)\n                plt.show\n                \"\"\"\n                if n == 1 and ev_lt > 20:\n                    totbub += 1\n                    for i in range(len(centers)):\n                        if trig_time > exp_start:\n                            #print(trig_pressure)\n                            #print(pset)\n                            if (trig_pressure >= edges[i] \n                                and trig_pressure <= edges[i+1]) and abs(trig_pressure-pset)<preq/2:\n                                onebubcount[i] += 1\n                                eventcount[i] += 1\n                                if not bl:\n                                    spectra[i].append(light)\n                                    #if light < 1:\n                                        #print(\"%s-%d is passing single not blocked and light < 1\"%(run, eventn))\n                                bubInfo.append([n,Q,bl,light,ev_z])\n                                #print(\"added %s-%d to bubInfo\"%(run,eventn))\n                                expand_times[i].append(ev_lt)\n                            if abs(centersp[i]-pset)<preq/2:\n                                LT[i] += times[i]*(1-LED_INDUCED_DEAD_TIME_FRACTION)\n                                for j in range(len(Qbins)-1):\n                                    if Q >= Qbins[j] and Q <= Qbins[j+1]:\n                                        LT_by_Q[j] += times[i]*(1-LED_INDUCED_DEAD_TIME_FRACTION)\n                    if Q>1.5 and Q<2 and abs(trig_pressure-pset)<preq/2 and trig_time > exp_start:\n                        print(event_ID)\n                        print(Q)\n                    \n                        \n                        \n                elif n == 2 and ev_lt > 20:\n                    totbub += 1\n                    for i in range(len(centers)):\n                        if trig_time > exp_start:\n                            if (trig_pressure >= edges[i] \n                                and trig_pressure <= edges[i+1]) and abs(trig_pressure-pset)<preq/2:\n                                eventcount[i] += 1\n                                twobubcount[i] += 1\n                                expand_times[i].append(ev_lt)\n                                bubInfo.append([n,Q,bl,light,ev_z])\n                                if not bl:\n                                    twobub_spectra[i].append(light)\n                                print(\"%s-%d multibubble event: %d bubbles, %.2f phe\"%(run, eventn, n, light))\n                            if abs(centersp[i]-pset)<preq/2:\n                                LT[i] += times[i]*(1-LED_INDUCED_DEAD_TIME_FRACTION)\n                                for j in range(len(Qbins)-1):\n                                    if Q >= Qbins[j] and Q <= Qbins[j+1]:\n                                        LT_by_Q[j] += times[i]*(1-LED_INDUCED_DEAD_TIME_FRACTION)\n\n                elif n >= 3 and ev_lt > 20:\n                    for i in range(len(centers)):\n                        if trig_time > exp_start:\n                            if (trig_pressure >= edges[i] \n                                and trig_pressure <= edges[i+1]) and abs(trig_pressure-pset)<preq/2:\n                                eventcount[i] += 1\n                                threebubcount[i] += 1\n                                expand_times[i].append(ev_lt)\n                                bubInfo.append([n,Q,bl,light,ev_z])\n                                if not bl:\n                                    threebub_spectra[i].append(light)\n                                print(\"%s-%d multibubble event: %d bubbles, %.2f phe\"%(run, eventn, n, light))\n                            if abs(centersp[i]-pset)<preq/2:\n                                LT[i] += times[i]*(1-LED_INDUCED_DEAD_TIME_FRACTION)\n                                for j in range(len(Qbins)-1):\n                                    if Q >= Qbins[j] and Q <= Qbins[j+1]:\n                                        LT_by_Q[j] += times[i]*(1-LED_INDUCED_DEAD_TIME_FRACTION)\n\n                else:\n                    if n>0:\n                        didntpass += 1\n                    for i in range(len(centers)):\n                        if trig_time > exp_start and ev_lt > 20:\n                            if (trig_pressure >= edges[i] \n                                and trig_pressure <= edges[i+1]) and abs(trig_pressure-pset)<preq/2:\n                                eventcount[i] += 1\n                                expand_times[i].append(ev_lt)\n                                bubInfo.append([n,Q,bl,light,ev_z])\n                            if abs(centersp[i]-pset)<preq/2:\n                                LT[i] += times[i]*(1-LED_INDUCED_DEAD_TIME_FRACTION)\n                                for j in range(len(Qbins)-1):\n                                    if Q >= Qbins[j] and Q <= Qbins[j+1]:\n                                        LT_by_Q[j] += times[i]*(1-LED_INDUCED_DEAD_TIME_FRACTION)\n\n                #if (ev_z > z_low and ev_z < z_high):                    \n                    \n        \n            except Exception as x:\n                print(x)\n                #break\n        \n    blockedEvents = [x for x in bubInfo if x[2] == 1]\n    print(\"fraction of LED-blocked bubbles: \"+str(len(blockedEvents)/len([x for x in bubInfo if x[0]>0])))\n    print(\"Number of single-bubble zero phe non-blocked events:\" + str(len([x for x in bubInfo if x[0]==1 and x[2] == 0 and (x[3]>0 and x[3] <1)])))\n    print(\"Number of single-bubble one phe non-blocked events:\" + str(len([x for x in bubInfo if x[0]==1 and x[2] == 0 and (x[3]>1 and x[3] <2)])))\n    print(\"Number of single-bubble two phe non-blocked events:\" + str(len([x for x in bubInfo if x[0]==1 and x[2] == 0 and (x[3]>2 and x[3] <3)])))\n\n    rateList1 = [onebubcount[i]/LT[i] for i in range(len(onebubcount))]\n    rateErrList1h = [(0.5+np.sqrt(onebubcount[i]+0.25))/LT[i] for i in range(len(onebubcount))]\n    rateErrList1l = [(-0.5+np.sqrt(onebubcount[i]+0.25))/LT[i] for i in range(len(onebubcount))]\n    standard_error1 = [np.sqrt(onebubcount[i])/LT[i] for i in range(len(onebubcount))]\n\n\n    rateList2 = [twobubcount[i]/LT[i] for i in range(len(twobubcount))]\n    rateErrList2h = [(0.5+np.sqrt(twobubcount[i]+0.25))/LT[i] for i in range(len(twobubcount))]\n    rateErrList2l = [(-0.5+np.sqrt(twobubcount[i]+0.25))/LT[i] for i in range(len(twobubcount))]\n    \n    rateList3 = [threebubcount[i]/LT[i] for i in range(len(threebubcount))]\n    rateErrList3h = [(0.5+np.sqrt(threebubcount[i]+0.25))/LT[i] for i in range(len(threebubcount))]\n    rateErrList3l = [(-0.5+np.sqrt(threebubcount[i]+0.25))/LT[i] for i in range(len(threebubcount))]\n    \n    rateListE = [eventcount[i]/LT[i] for i in range(len(eventcount))]\n    rateErrListEh = [(0.5+np.sqrt(eventcount[i]+0.25))/LT[i] for i in range(len(eventcount))]\n    rateErrListEl = [(-0.5+np.sqrt(eventcount[i]+0.25))/LT[i] for i in range(len(eventcount))]\n    \"\"\"\n    plt.figure()\n    q = [bub[1] for bub in bubInfo]\n    plt.hist(q,int(np.ceil(np.sqrt(len(q)))))\n    plt.xlabel('Seitz Threshold')\n    plt.ylabel('Count')\n    plt.show()\n    \n    #Threshold:\n    plt.figure()\n    plt.errorbar(centers,rateList1,[rateErrList1l,rateErrList1h],fmt='ro',label='Single Bubbles')\n    plt.errorbar(centers,rateList2,[rateErrList2l,rateErrList2h],fmt='go',label='Double Bubbles')\n    plt.errorbar(centers,rateList3,[rateErrList3l,rateErrList3h],fmt='bo',label='Triple Bubbles')\n    plt.errorbar(centers,rateListE,[rateErrListEl,rateErrListEh],fmt='ko',label='All Events')\n    #plt.yscale('log')\n    plt.ylim([1e-4,0.1])\n    plt.xlabel('Seitz Threshold [keV]',fontsize=18)\n    plt.ylabel('Rate [Hz]', fontsize=18)\n    plt.legend(fontsize=18)\n    plt.grid()\n    plt.show\n    \n    #single bubbles\n    def line(x,m,b):\n        return m*x + b\n    \n    QForFit = []\n    RForFit = []\n    errForFit = []\n    for i in range(len(rateList1)):\n        if (not np.isnan(rateList1[i])) and (not np.isinf(rateList1[i])) and rateList1[i] != 0:\n            QForFit.append(centers[i])\n            RForFit.append(rateList1[i])\n            errForFit.append(standard_error1[i])\n\n    popt,pcov = scipy.optimize.curve_fit(line,QForFit,RForFit,p0=[0.005,0.01],sigma=errForFit)\n    plt.figure()\n    plt.errorbar(QForFit,RForFit,yerr=errForFit,fmt=\"ro\")\n    xfine = np.linspace(min(centers),3,50)\n    y1 = line(xfine,popt[0]+pcov[0,0]**0.5, popt[1]-pcov[1,1]**0.5)\n    y2 = line(xfine,popt[0]-pcov[0,0]**0.5, popt[1]+pcov[1,1]**0.5)\n    plt.plot(xfine,line(xfine,popt[0],popt[1]),'k-')\n    plt.plot(xfine,y1,'k--')\n    plt.plot(xfine,y2,'k--')\n    plt.plot([0,5],[0,0],'b-')\n    plt.fill_between(xfine,y1,y2,facecolor='gray',alpha=0.1)\n    plt.ylabel('Rate [Hz]',fontsize=18)\n    plt.xlabel('Seitz Threshold [keV]',fontsize=18)\n    plt.title('Crosses x-axis at %f'%(-popt[1]/popt[0]))\n    plt.show\n    \"\"\"\n    \n    totbub = len(nbubs)\n    print(\"total number of bubbles: %d\"%totbub)\n    print(\"total number of events: %d\" %len(counts))\n    print(\"didn't pass: %d\"%didntpass)\n    m = max(nbubs)\n    for i in range(len(nbubs)):\n        if nbubs[i]>3:\n            nbubs[i] = 3\n            \n    binedges = [0.5,1.5,2.5,3.5] #bins for bubble multiplicity\n    bincenters = [1,2,3]\n    plt.figure()\n    ns, _ = np.histogram(nbubs,binedges)\n    print(\"bubble counts: \")\n    print(ns)\n    plt.errorbar(bincenters,ns,np.sqrt(ns),fmt='o')\n    plt.yscale('log')\n    plt.title(\"Max Nbub: %d\"%int(m),fontsize=20)\n    plt.xlabel(\"Nbub\",fontsize=18)\n    plt.ylabel(\"counts\",fontsize=18)\n    plt.xlim(0.5,3.5)\n    plt.grid()\n    plt.show\n    \n    f = [ns[i]/totbub for i in range(len(ns))]\n    ferrh = [(0.5+np.sqrt(ns[i]+0.25))/totbub for i in range(len(ns))]\n    ferrl = [(-0.5+np.sqrt(ns[i]+0.25))/totbub for i in range(len(ns))]\n\n    plt.figure()\n    plt.errorbar(bincenters,f,[ferrl,ferrh],fmt='o')\n    plt.xlabel(\"Nbub\",fontsize=18)\n    plt.ylabel(\"fraction of bubbles\",fontsize=18)\n    plt.xlim([0.5,3.5])\n    plt.grid()\n    plt.show\n    \n    \"\"\"\n    #Pressure\n    plt.figure()\n    plt.errorbar(centersp,rateList1,[rateErrList1l,rateErrList1h],fmt='ro',label='Single Bubbles')\n    plt.errorbar(centersp,rateList2,[rateErrList2l,rateErrList2h],fmt='go',label='Double Bubbles')\n    plt.errorbar(centersp,rateList3,[rateErrList3l,rateErrList3h],fmt='bo',label='Triple Bubbles')\n    plt.errorbar(centersp,rateListE,[rateErrListEl,rateErrListEh],fmt='ko',label='All Events')\n    plt.yscale('log')\n    plt.xlabel('Pressure [psia]',fontsize=18)\n    plt.ylabel('Rate [Hz]', fontsize=18)\n    plt.legend(fontsize=18)\n    plt.grid()\n    plt.show\n    \n    plt.figure()\n    hy = []\n    hx = []\n    for i in range(len(expand_times)):\n        if len(expand_times[i])>0:\n            for j in range(len(expand_times[i])):\n                hx.append(centersp[i])\n                hy.append(expand_times[i][j])\n\n    plt.hist2d(hx,hy,bins=(len(centers),30),cmap='magma')\n    plt.colorbar()\n    plt.xlabel('PT6 [psia]',fontsize=18)\n    plt.ylabel('Total time since expansion [s]',fontsize=18)\n    plt.show\n    \n        \n    hy = []\n    hx = []\n    for i in range(len(expand_times)):\n        if len(spectra[i])>0:\n            for j in range(len(spectra[i])):\n                hx.append(centersp[i])\n                hy.append(spectra[i][j])\n    plt.figure()\n    plt.hist2d(hx,hy,bins=(40,int(max(hy))),cmap='Greys')\n    plt.colorbar()\n    plt.xlabel('PT6 [psia]',fontsize=18)\n    plt.ylabel('Light collected [phe]',fontsize=18)\n    plt.yscale('symlog',linthreshy = 0.9)\n    plt.show\n    \n    \n    \n    xedges = np.arange(88)\n    #yedges = np.arange(int(max(hy))+1)\n    bins = [10**i+0.5 for i in range(5)] # light bins\n    #bins = np.arange(0.5,1+np.ceil(max(spect)))\n    bins = np.insert(bins,0,0.5)\n    bins=np.insert(bins,0,-0.5)\n    bins=np.insert(bins,0,-1.5)\n    H, xedges, yedges = np.histogram2d(hx,hy,bins=(xedges,bins))\n    for i in range(len(xedges)-1):\n        for j in range(len(H[i,:])):\n            #print(LT[i])\n            H[i,j] = H[i,j]/LT[i]\n    print(\"max rate: %f\"%np.amax(H))\n            \n    fig = plt.figure()\n    ax = fig.add_subplot(1,1,1)\n    X,Y = np.meshgrid(xedges,yedges)\n\n    im=ax.pcolormesh(X,Y,H.T,cmap=\"magma\")\n    plt.yscale('symlog',linthreshy = 0.9)\n    fig.colorbar(im,ax=ax)\n    plt.show()\n    \"\"\"\n    hy = []\n    hx = []\n    hy_multi = []\n    hx_multi = []\n    for bubble in bubInfo:\n        if bubble[0]==1 and bubble[2] == 0:\n        #if bubble[0]==1:\n            hx.append(bubble[1]) # Seitz threshold\n            hy.append(bubble[3]) # phe\n        elif (bubble[0] == 2 or bubble[0] == 3):\n            hx_multi.append(bubble[1])\n            hy_multi.append(bubble[3])\n    plt.figure()\n    plt.hist2d(hx,hy,bins=(40,int(max(hy))),cmap='Greys')\n    plt.colorbar()\n    plt.xlabel('Q [keV]',fontsize=18)\n    plt.ylabel('Light collected [phe]',fontsize=18)\n    plt.yscale('symlog',linthreshy = 0.9)\n    plt.show\n    \n    #print(temps)\n    \n    xedges = edges\n    Qedges = np.zeros(np.shape(xedges))\n    for i in range(1,len(xedges)):\n        SM = SeitzModel(float(xedges[i]),np.mean(temps),'xenon')\n        if SM is not None:\n            Qedges[i]=SM.Q\n    \n    OArateQ = [(Qbins[i]+Qbins[i+1])/2 for i in range(len(Qbins)-1)]\n    OArate_multi = []\n    OArateErr_multi = []\n    OArate_singles = []\n    OArateErr_singles = []\n    Qedges = Qbins    \n    #print(Qbins)\n    #yedges = np.arange(int(max(hy))+1)\n    \n    bins = lightBins # light bins\n    #bins = np.arange(1,int(1+np.ceil(max(spect))))\n    bins = np.insert(bins,0,0.5)\n    bins=np.insert(bins,0,-0.5)\n    #bins=np.insert(bins,0,-1.5)\n    \n    #bins = [-0.5, 2**9+0.5, 2**13+0.5]\n    binc=[(bins[i+1]+bins[i])/2 for i in range(len(bins)-1)]\n    binwidths = [bins[i+1]-bins[i] for i in range(len(bins)-1)]\n    print(binwidths)\n    H, Qedges, yedges = np.histogram2d(hx,hy,bins=(Qedges,bins)) # using hx and hy defined a few lines above in the previous plot section\n    H_multi, Qedges, yedges_multi = np.histogram2d(hx_multi, hy_multi, bins=(Qedges, bins))\n    multi_ns = H_multi.copy()\n    ns = H.copy()\n    errorbararray_upper = np.zeros_like(H)\n    errorbararray_lower = np.zeros_like(H)\n    errorbararray_multi_upper = np.zeros_like(H_multi)\n    errorbararray_multi_lower = np.zeros_like(H_multi)\n    print(\"total number of events in H: %d\"%np.sum(H))\n    print(\"total number of multiples in H_multi: %d\"%np.sum(H_multi))\n    for i in range(len(LT_by_Q)):\n        OArate_singles.append(sum(H[i,:])/LT_by_Q[i])\n        OArateErr_singles.append(np.sqrt(sum(H[i,:]))/LT_by_Q[i])\n        for j in range(len(H[i,:])):\n            H[i,j] = H[i,j]/LT_by_Q[i]\n            if ns[i,j] > 10:\n                errorbararray_upper[i,j]= np.sqrt(ns[i,j])/LT_by_Q[i]\n                errorbararray_lower[i,j]= np.sqrt(ns[i,j])/LT_by_Q[i]\n            else:\n                errorbararray_upper[i,j]= (0.5+np.sqrt(ns[i,j]+0.25))/LT_by_Q[i]\n                errorbararray_lower[i,j]= (-0.5+np.sqrt(ns[i,j]+0.25))/LT_by_Q[i]\n            #print(H[i,j])\n            #print(errorbararray[i,j])\n            if np.isnan(H[i,j]):\n                H[i,j]=0\n                errorbararray_upper[i,j] = 0\n                errorbararray_lower[i,j] = 0\n        OArate_multi.append(sum(H_multi[i,:])/LT_by_Q[i])\n        OArateErr_multi.append(np.sqrt(sum(H_multi[i,:]))/LT_by_Q[i])\n        for j in range(len(H_multi[i,:])):\n            H_multi[i,j] = H_multi[i,j]/LT_by_Q[i]\n            if multi_ns[i,j] > 10:\n               errorbararray_multi_upper[i,j]= np.sqrt(multi_ns[i,j])/LT_by_Q[i]\n               errorbararray_multi_lower[i,j]= np.sqrt(multi_ns[i,j])/LT_by_Q[i]\n            else:\n               errorbararray_multi_upper[i,j]= (0.5+np.sqrt(multi_ns[i,j] + 0.25))/LT_by_Q[i]\n               errorbararray_multi_lower[i,j]= (-0.5+np.sqrt(multi_ns[i,j] + 0.25))/LT_by_Q[i]\n            #print(H[i,j])\n            #print(errorbararray[i,j])\n            if np.isnan(H_multi[i,j]):\n                H_multi[i,j]=0\n                errorbararray_multi_upper[i,j] = 0\n                errorbararray_multi_lower[i,j] = 0\n    #print(sum(H))\n    #print(OArate)\n    print(\"singles:\")\n    print(ns)\n    print(\"multiples:\")\n    print(multi_ns)\n    \n    plt.figure()\n    plt.errorbar(OArateQ,OArate_singles,OArateErr_singles,marker='v',linestyle='')\n    plt.grid()\n    plt.xlabel('Seitz Threshold [keV]')\n    plt.ylabel('Rate [Hz]')\n    plt.show()\n    \n    print(\"max rate: %f\"%np.amax(H))\n    print(\"number in onebubcount: %f\"%np.sum(onebubcount))\n    print(np.sum([rateList1[i] * LT[i] for i in range(len(rateList1)) if not np.isnan(rateList1[i])]))\n    fig = plt.figure()\n    ax = fig.add_subplot(1,2,1)\n    ax.title.set_text('Rates [Hz/bin]')\n    X,Y = np.meshgrid(Qedges,yedges)\n\n    im=ax.pcolormesh(X,Y,H.T,cmap=\"Greys\")\n    plt.yscale('symlog',linthreshy = 0.9)\n    plt.ylabel(\"Collected light [phe]\")\n    plt.xlabel(\"Seitz Threshold [keV]\")\n    fig.colorbar(im,ax=ax)\n    \n    ax2 = fig.add_subplot(1,2,2)\n    ax2.title.set_text('Number of bubbles in each bin')\n    im2=ax2.pcolormesh(X,Y,ns.T,cmap=\"Blues\")\n    plt.yscale('symlog',linthreshy = 0.9)\n    plt.ylabel(\"Collected light [phe]\")\n    plt.xlabel(\"Seitz Threshold [keV]\")\n    fig.colorbar(im2,ax=ax2)\n    #plt.show()\n    \n    fig = plt.figure()\n    ax3 = fig.add_subplot(1,1,1)\n    ax3.title.set_text(\"Rates per Scintillation: fraction\")\n    for k in range(len(Qedges)-1):\n        print(\"%f-%f keV: %f bubbles in %f seconds\"%(Qedges[k],Qedges[k+1],sum(ns[k,:]),LT_by_Q[k]))\n        if LT_by_Q[k]>100:\n            ax3.errorbar(binc,H[k,:]/OArate_singles[k],[(errorbararray_upper[k,:]/OArate_singles[k]),(errorbararray_lower[k,:]/OArate_singles[k])],marker='.',markersize=7,\n                         linestyle='none',label=\"%f-%f keV\"%(Qedges[k],Qedges[k+1]))\n    for l in range(len(bins)-1):\n        fractionFile.write(\"%.1f-%.1fphe\\t\"%(bins[l],bins[l+1]))\n        for k in range(len(Qedges)-1):\n            fractionFile.write(\"%f,%f,%f\\t\"%(H[k,l]/OArate_singles[k], errorbararray_upper[k,l]/OArate_singles[k], errorbararray_lower[k,l]/OArate_singles[k]))\n        fractionFile.write('\\n')\n    plt.xscale('symlog',linthreshx=0.5)\n    #plt.yscale('symlog',linthreshy=0.0001)\n    plt.legend(fontsize=15)\n    plt.xlabel(\"collected light [phe]\")\n    plt.ylabel(\"Fraction\")\n    #plt.ylim([0,0.1])\n    plt.grid(which='both',axis='both')\n    plt.show()\n    \n    fig = plt.figure()\n    ax3 = fig.add_subplot(1,2,1)\n    #ax3.title.set_text(\"Rates per Scintillation\")\n    ax4 = fig.add_subplot(1,2,2)\n    for k in range(len(Qedges)-1):\n        print(\"%f-%f keV: %f seconds\"%(Qedges[k],Qedges[k+1],LT_by_Q[k]))\n        if LT_by_Q[k]>100:\n            ax3.errorbar(binc,H[k,:],[errorbararray_upper[k,:], errorbararray_lower[k,:]],marker='.',markersize=7,\n                         linestyle='none',label=\"%f-%f keV\"%(Qedges[k],Qedges[k+1]))\n            Hnew = []\n            errorbarnew_upper = []\n            errorbarnew_lower = []\n            for l in range(len(binwidths)):\n                Hnew.append(np.divide(H[k,l],binwidths[l]))\n                errorbarnew_upper.append(np.divide(errorbararray_upper[k,l],binwidths[l]))\n                errorbarnew_lower.append(np.divide(errorbararray_lower[k,l],binwidths[l]))\n            ax4.errorbar(binc, Hnew, [errorbarnew_upper, errorbarnew_lower],\n                         marker='.', markersize=7, linestyle='none',\n                         label='%f-%f keV'%(Qedges[k],Qedges[k+1]))\n    for l in range(len(bins)-1):\n        spectrumFile.write(\"%.1f-%.1fphe\\t\"%(bins[l],bins[l+1]))\n        for k in range(len(Qedges)-1):\n            spectrumFile.write(\"%f,%f,%f\\t\"%(H[k,l],errorbararray_upper[k,l], errorbararray_lower[k,l]))\n        spectrumFile.write('\\n')\n    ax3.set_xscale('symlog',linthreshx=0.5)\n    ax4.set_xscale('symlog',linthreshx=0.5)\n    ax3.set_yscale('log')\n    ax4.set_yscale('log')\n    #plt.yscale('symlog',linthreshy=0.0001)\n    ax3.legend(fontsize=15)\n    ax4.legend(fontsize=15)\n    plt.xlabel(\"collected light [phe]\")\n    ax3.set_ylabel(\"Rate per bin [Hz]\")\n    ax4.set_ylabel(\"rate per phe [Hz/phe]\")\n    #plt.ylim([0,0.1])\n    ax3.grid(which='both',axis='both')\n    ax4.grid(which='both',axis='both')\n    plt.show()\n    \n    fig = plt.figure()\n    ax3 = fig.add_subplot(1,2,1)\n    ax3.title.set_text(\"Rates per Scintillation, multiples\")\n    ax4 = fig.add_subplot(1,2,2)\n    for k in range(len(Qedges)-1):\n        print(\"%f-%f keV: %f seconds\"%(Qedges[k],Qedges[k+1],LT_by_Q[k]))\n        if LT_by_Q[k]>100:\n            ax3.errorbar(binc,H_multi[k,:],[errorbararray_multi_upper[k,:], errorbararray_multi_upper[k,:]],marker='.',markersize=7,\n                         linestyle='none',label=\"%f-%f keV\"%(Qedges[k],Qedges[k+1]))\n            Hnew_multi = []\n            errorbarnew_multi_upper = []\n            errorbarnew_multi_lower = []\n            for l in range(len(binwidths)):\n                Hnew_multi.append(np.divide(H_multi[k,l],binwidths[l]))\n                errorbarnew_multi_upper.append(np.divide(errorbararray_multi_upper[k,l],binwidths[l]))\n                errorbarnew_multi_lower.append(np.divide(errorbararray_multi_lower[k,l],binwidths[l]))\n            ax4.errorbar(binc, Hnew_multi, [errorbarnew_multi_upper, errorbarnew_multi_lower],\n                         marker='.', markersize=7, linestyle='none',\n                         label='%f-%f keV'%(Qedges[k],Qedges[k+1]))\n    for l in range(len(bins)-1):\n        spectrumFile_multiples.write(\"%.1f-%.1fphe\\t\"%(bins[l],bins[l+1]))\n        for k in range(len(Qedges)-1):\n            spectrumFile_multiples.write(\"%f,%f,%f\\t\"%(H_multi[k,l],errorbararray_multi_upper[k,l], errorbararray_multi_lower[k,l]))\n        spectrumFile_multiples.write('\\n')\n    ax3.set_xscale('symlog',linthreshx=0.5)\n    ax4.set_xscale('symlog',linthreshx=0.5)\n    ax3.set_yscale('log')\n    ax4.set_yscale('log')\n    #plt.yscale('symlog',linthreshy=0.0001)\n    ax3.legend(fontsize=15)\n    ax4.legend(fontsize=15)\n    plt.xlabel(\"collected light [phe]\")\n    ax3.set_ylabel(\"Rate per bin [Hz]\")\n    ax4.set_ylabel(\"rate per phe [Hz/phe]\")\n    #plt.ylim([0,0.1])\n    ax3.grid(which='both',axis='both')\n    ax4.grid(which='both',axis='both')\n    plt.show()\n\n\n    \n    plt.figure()\n    plt.scatter([x[1] for x in bubInfo],[x[3] for x in bubInfo])\n    plt.yscale('symlog',linthreshy=0.5)\n    plt.xlabel('Seitz Threshold [keV]')\n    plt.ylabel('collected light [phe]')\n    plt.show\n\n    \n    fig,ax1 = plt.subplots()\n    ax2 = ax1.twinx()\n    ax1.set_xlabel('Seitz Threshold (keV)',fontsize=18)\n    ax1.set_ylabel('Live time (s)',fontsize=18)\n    ax2.set_ylabel('Number of bubbles',fontsize=18)\n    ax1.scatter(centers,LT,20,'r')\n    ax2.scatter(centers,onebubcount,20,'b')\n    plt.show\n    \n    \n\n    \n    spectrumFile.close() \n    spectrumFile_multiples.close()       \n    fractionFile.close()\n\ndef main():\n    runs = rlc.cfJuneminus50CCombined\n    #runs=['20170628_9']\n    mult(runs,'cfJuneminus50CCombined',[0,1,1.5,2,2.5,3],\"PT6\", [(2**i)+0.5 for i in range(14)], 'powerof2bins', 0.1289)\nif __name__==\"__main__\":\n    main()", "meta": {"hexsha": "9ea77e082077656a73951bb9639b3451dabdc959", "size": 30312, "ext": "py", "lang": "Python", "max_stars_repo_path": "UserCode/bressler/XeBCBubMult.py", "max_stars_repo_name": "cericdahl/SBCcode", "max_stars_repo_head_hexsha": "90a7841a5c1208d64f71a332289d9005a011aa21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-08-27T18:02:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-09T21:19:04.000Z", "max_issues_repo_path": "UserCode/bressler/XeBCBubMult.py", "max_issues_repo_name": "SBC-Collaboration/SBC-Analysis", "max_issues_repo_head_hexsha": "90a7841a5c1208d64f71a332289d9005a011aa21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "UserCode/bressler/XeBCBubMult.py", "max_forks_repo_name": "SBC-Collaboration/SBC-Analysis", "max_forks_repo_head_hexsha": "90a7841a5c1208d64f71a332289d9005a011aa21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-06-20T21:36:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T17:23:14.000Z", "avg_line_length": 42.217270195, "max_line_length": 171, "alphanum_fraction": 0.5459553972, "include": true, "reason": "import numpy,import scipy", "num_tokens": 8624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3208212878370535, "lm_q1q2_score": 0.1616638265781775}}
{"text": "#!/usr/bin/env python\n#\n# Copyright 2019 DFKI GmbH.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the\n# following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n# USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\nFunctions for retargeting based on the paper \"Using an Intermediate Skeleton and Inverse Kinematics for Motion Retargeting\"\nby Monzani et al.\nSee: http://www.vis.uni-stuttgart.de/plain/vdl/vdl_upload/91_35_retargeting%20monzani00using.pdf\n\"\"\"\nimport numpy as np\nimport math\nfrom .constants import OPENGL_UP_AXIS, GAME_ENGINE_SPINE_OFFSET_LIST\nfrom transformations import quaternion_matrix, quaternion_multiply, quaternion_about_axis, quaternion_inverse, quaternion_from_matrix\nfrom .utils import normalize, align_axis, find_rotation_between_vectors, align_root_translation, to_local_cos, get_quaternion_rotation_by_name, apply_additional_rotation_on_frames, project_vector_on_axis, quaternion_from_vector_to_vector\nfrom ..animation_data.skeleton_models import JOINT_CHILD_MAP\nfrom .analytical import create_local_cos_map_from_skeleton_axes_with_map\n\nJOINT_CHILD_MAP = dict()\nJOINT_CHILD_MAP[\"root\"] = \"pelvis\"\nJOINT_CHILD_MAP[\"pelvis\"] = \"spine_2\"\nJOINT_CHILD_MAP[\"spine_2\"] = \"neck\"\nJOINT_CHILD_MAP[\"neck\"] = \"head\"\nJOINT_CHILD_MAP[\"left_clavicle\"] = \"left_shoulder\"\nJOINT_CHILD_MAP[\"left_shoulder\"] = \"left_elbow\"\nJOINT_CHILD_MAP[\"left_elbow\"] = \"left_wrist\"\nJOINT_CHILD_MAP[\"left_wrist\"] = \"left_finger\"\nJOINT_CHILD_MAP[\"right_clavicle\"] = \"right_shoulder\"\nJOINT_CHILD_MAP[\"right_shoulder\"] = \"right_elbow\"\nJOINT_CHILD_MAP[\"right_elbow\"] = \"right_wrist\"\nJOINT_CHILD_MAP[\"right_wrist\"] = \"right_finger\"\nJOINT_CHILD_MAP[\"left_hip\"] = \"left_knee\"\nJOINT_CHILD_MAP[\"left_knee\"] = \"left_ankle\"\nJOINT_CHILD_MAP[\"right_elbow\"] = \"right_wrist\"\nJOINT_CHILD_MAP[\"right_hip\"] = \"right_knee\"\nJOINT_CHILD_MAP[\"right_knee\"] = \"right_ankle\"\nJOINT_CHILD_MAP[\"left_ankle\"] = \"left_toe\"\nJOINT_CHILD_MAP[\"right_ankle\"] = \"right_toe\"\n\n\ndef estimate_correction(target_zero_vector_y, target_zero_vector_x,  src_zero_vector_y, src_zero_vector_x):\n    q = quaternion_from_vector_to_vector(target_zero_vector_y, src_zero_vector_y)\n    q = normalize(q)\n    m = quaternion_matrix(q)[:3, :3]\n    target_zero_vector_x = normalize(np.dot(m, target_zero_vector_x))\n    qx = quaternion_from_vector_to_vector(target_zero_vector_x, src_zero_vector_x)\n    q = quaternion_multiply(qx, q)\n    q = normalize(q)\n    return q\n\ndef create_correction_map(target_skeleton, target_to_src_joint_map, target_cos_map, src_cos_map):\n    correction_map = dict()\n    joint_map = target_skeleton.skeleton_model[\"joints\"]\n    for target_name in target_to_src_joint_map:\n        src_name = target_to_src_joint_map[target_name]\n        if src_name in src_cos_map and target_name is not None:\n            src_zero_vector_y = src_cos_map[src_name][\"y\"]\n            target_zero_vector_y = target_cos_map[target_name][\"y\"]\n            src_zero_vector_x = src_cos_map[src_name][\"x\"]\n            target_zero_vector_x = target_cos_map[target_name][\"x\"]\n            if target_zero_vector_y is not None and src_zero_vector_y is not None:\n                q = estimate_correction(target_zero_vector_y, target_zero_vector_x,  src_zero_vector_y, src_zero_vector_x)\n                correction_map[target_name] = q\n    return correction_map\n\n\ndef get_quaternion_to_axis(skeleton, joint_a, joint_b, axis):\n    ident_f = skeleton.identity_frame\n    ap = skeleton.nodes[joint_a].get_global_position(ident_f)\n    bp = skeleton.nodes[joint_b].get_global_position(ident_f)\n    delta = bp - ap\n    delta /= np.linalg.norm(delta)\n    return quaternion_from_vector_to_vector(axis, delta)\n\n\ndef rotate_axes2(cos, q):\n    m = quaternion_matrix(q)[:3, :3]\n    aligned_axes = dict()\n    for key, a in list(cos.items()):\n        aligned_axes[key] = np.dot(m, a)\n        aligned_axes[key] = normalize(aligned_axes[key])\n    return aligned_axes\n\n\ndef get_child_joint(skeleton_model, inv_joint_map, node_name, src_children_map):\n    \"\"\" Warning output is random if there are more than one child joints\n        and the value is not specified in the JOINT_CHILD_MAP \"\"\"\n    child_name = None\n    if node_name in src_children_map and len(src_children_map[node_name]) > 0:\n        child_name = src_children_map[node_name][-1]\n    if node_name in inv_joint_map:\n        joint_name = inv_joint_map[node_name]\n        while joint_name in JOINT_CHILD_MAP:\n            _child_joint_name = JOINT_CHILD_MAP[joint_name]\n\n            # check if child joint is mapped\n            joint_key = None\n            if _child_joint_name in skeleton_model[\"joints\"]:\n                joint_key = skeleton_model[\"joints\"][_child_joint_name]\n\n            if joint_key is not None: # return child joint\n                child_name = joint_key\n                return child_name\n            else: #keep traversing until end of child map is reached\n                if _child_joint_name in JOINT_CHILD_MAP:\n                    joint_name = JOINT_CHILD_MAP[_child_joint_name]\n                    #print(joint_name)\n                else:\n                    break\n    return child_name\n\ndef rotate_axes_in_place(cos, q):\n    m = quaternion_matrix(q)[:3, :3]\n    for key, a in list(cos.items()):\n        cos[key] = np.dot(m, a)\n        cos[key] = normalize(cos[key])\n    return cos\n\ndef align_axis_in_place(axes, key, new_vec):\n    q = quaternion_from_vector_to_vector(axes[key], new_vec)\n    aligned_axes = rotate_axes_in_place(axes, q)\n    return q, aligned_axes\n\n\n\ndef to_local_cos_fast(skeleton, node_name, frame, q):\n    # bring into parent coordinate system\n    pm = np.array(skeleton.nodes[node_name].get_global_matrix(frame, use_cache=True)[:3,:3])\n    inv_p = quaternion_inverse(quaternion_from_matrix(pm))\n    return quaternion_multiply(inv_p, q)\n\ndef align_root_joint(new_skeleton, free_joint_name, axes, global_src_up_vec, global_src_x_vec,joint_cos_map, max_iter_count=10):\n    # handle special case for the root joint\n    # apply only the y axis rotation of the Hip to the Game_engine node\n    q = [1, 0, 0, 0]\n    #apply first time\n    qx, axes = align_axis_in_place(axes, \"x\", global_src_x_vec)  # first find rotation to align x axis\n    q = quaternion_multiply(qx, q)\n    q = normalize(q)\n\n    qy, axes = align_axis_in_place(axes, \"y\", global_src_up_vec)  # then add a rotation to let the y axis point up\n    q = quaternion_multiply(qy, q)\n    q = normalize(q)\n\n    #apply second time\n    qx, axes = align_axis_in_place(axes, \"x\", global_src_x_vec)  # first find rotation to align x axis\n    q = quaternion_multiply(qx, q)\n    q = normalize(q)\n    qy, axes = align_axis_in_place(axes, \"y\", global_src_up_vec)  # then add a rotation to let the y axis point up\n    q = quaternion_multiply(qy, q)\n    q = normalize(q)\n\n    # print(\"handle special case for pelvis\")\n    # handle special case of applying the x axis rotation of the Hip to the pelvis\n    node = new_skeleton.nodes[free_joint_name]\n    t_pose_global_m = node.get_global_matrix(new_skeleton.reference_frame)[:3, :3]\n    global_original = np.dot(t_pose_global_m, joint_cos_map[free_joint_name][\"y\"])\n    global_original = normalize(global_original)\n    qoffset = find_rotation_between_vectors(OPENGL_UP_AXIS, global_original)\n    q = quaternion_multiply(q, qoffset)\n    q = normalize(q)\n    return q\n\ndef align_joint(local_target_axes, up_vec, x_vec):\n    q = [1, 0, 0, 0]\n    qy, axes = align_axis_in_place(local_target_axes, \"y\", up_vec)\n    q = quaternion_multiply(qy, q)\n    q = normalize(q)\n\n    # then align the twisting angles\n    if x_vec is not None:\n        qx, axes = align_axis_in_place(axes, \"x\", x_vec)\n        q = quaternion_multiply(qx, q)\n        q = normalize(q)\n        # print(\"set twist angle\", free_joint_name, twist_angle)\n    return q\n\ndef find_rotation_analytically(new_skeleton, free_joint_name, target, frame, joint_cos_map, is_root=False, max_iter_count=10, twist_angle=None):\n    global_src_up_vec = target[0]\n    if twist_angle is None:\n        global_src_x_vec = target[1]\n    else:\n        global_src_x_vec = None\n    local_target_axes = dict(joint_cos_map[free_joint_name])\n\n    if is_root:\n        q = align_root_joint(new_skeleton, free_joint_name, local_target_axes, global_src_up_vec,global_src_x_vec, joint_cos_map, max_iter_count)\n\n    else:\n        # first align the bone vectors\n        q = [1, 0, 0, 0]\n        qy, axes = align_axis_in_place(local_target_axes, \"y\", global_src_up_vec)\n        q = quaternion_multiply(qy, q)\n        q = normalize(q)\n\n        # then align the twisting angles\n        if global_src_x_vec is not None:\n            qx, axes = align_axis_in_place(axes, \"x\", global_src_x_vec)\n            q = quaternion_multiply(qx, q)\n            q = normalize(q)\n\n    #if \"FK\" in free_joint_name:\n    #    q = to_local_cos(new_skeleton, free_joint_name, frame, q)\n    if new_skeleton.nodes[free_joint_name].parent is not None:\n        #if \"upLeg\" in free_joint_name: # it does not work for the legs for some reason\n        #    q = to_local_cos(new_skeleton, new_skeleton.nodes[free_joint_name].parent.node_name, frame, q)\n        #else:\n        q = to_local_cos(new_skeleton, new_skeleton.nodes[free_joint_name].parent.node_name, frame, q)\n\n    if twist_angle is not None:\n        # separate rotation\n        local_twist_axis = np.array(joint_cos_map[free_joint_name][\"y\"])\n        swing_q, twist_q = swing_twist_decomposition(q, local_twist_axis)\n        # replace\n        twist_q = quaternion_about_axis(-twist_angle, local_twist_axis)\n        q = quaternion_multiply(swing_q, twist_q)\n        q = normalize(q)\n    return q\n\n\ndef find_rotation_analytically_with_guess(new_skeleton, free_joint_name, target, frame, joint_cos_map, prev_global_q, is_root=False, max_iter_count = 10):\n    global_src_up_vec = target[0]\n    global_src_x_vec = target[1]\n    local_target_axes = joint_cos_map[free_joint_name]\n    rotated_axes = rotate_axes2(local_target_axes, prev_global_q)\n    #print(\"rotate\",local_target_axes, rotated_axes, prev_global_q)\n    #print(\"\")\n    if is_root:\n        q = align_root_joint(new_skeleton, free_joint_name, rotated_axes, global_src_up_vec,global_src_x_vec, joint_cos_map, max_iter_count)\n    else:\n        q = align_joint(rotated_axes, global_src_up_vec, global_src_x_vec)\n    q = quaternion_multiply(q, prev_global_q)\n    q = normalize(q)\n    return to_local_cos_fast(new_skeleton, free_joint_name, frame, q)\n\n\ndef get_parent_map(joints):\n    \"\"\"Returns a dict of node names to their parent node's name\"\"\"\n    parent_dict = dict()\n    for joint_name in list(joints.keys()):\n        parent_dict[joint_name] = joints[joint_name]['parent']\n    return parent_dict\n\n\ndef get_children_map(joints):\n    \"\"\"Returns a dict of node names to a list of children names\"\"\"\n    child_dict = dict()\n    for joint_name in list(joints.keys()):\n        parent_name = joints[joint_name]['parent']\n        if parent_name not in child_dict:\n            child_dict[parent_name] = list()\n        child_dict[parent_name].append(joint_name)\n    return child_dict\n\ndef swing_twist_decomposition(q, twist_axis):\n    \"\"\" code by janis sprenger based on\n        Dobrowsolski 2015 Swing-twist decomposition in Clifford algebra. https://arxiv.org/abs/1506.05481\n    \"\"\"\n    #q = normalize(q)\n    #twist_axis = np.array((q * offset))[0]\n    projection = np.dot(twist_axis, np.array([q[1], q[2], q[3]])) * twist_axis\n    twist_q = np.array([q[0], projection[0], projection[1],projection[2]])\n    if np.linalg.norm(twist_q) == 0:\n        twist_q = np.array([1,0,0,0])\n    twist_q = normalize(twist_q)\n    swing_q = quaternion_multiply(q, quaternion_inverse(twist_q))#q * quaternion_inverse(twist)\n    return swing_q, twist_q\n\n\nclass PointCloudRetargeting(object):\n    def __init__(self, src_joints, src_model, target_skeleton, target_to_src_joint_map, scale_factor=1.0, additional_rotation_map=None, constant_offset=None, place_on_ground=False, ground_height=0):\n        self.src_joints = src_joints\n        self.src_model = src_model\n        self.target_skeleton = target_skeleton\n        self.target_to_src_joint_map = target_to_src_joint_map\n        if target_skeleton.skeleton_model[\"joints\"][\"pelvis\"] is not None:\n            self.target_skeleton_root = target_skeleton.skeleton_model[\"joints\"][\"pelvis\"]\n        else:\n            self.target_skeleton_root = target_skeleton.root\n\n        #FIXME: enable spine during retargeting\n        for j in [ \"spine_1\", \"spine\"]:#\"spine_2\",\n            k = self.target_skeleton.skeleton_model[\"joints\"][j]\n            self.target_to_src_joint_map[k] = None\n\n        self.src_to_target_joint_map = {v: k for k, v in list(self.target_to_src_joint_map.items())}\n        self.scale_factor = scale_factor\n        self.n_params = len(self.target_skeleton.animated_joints) * 4 + 3\n        self.ground_height = ground_height\n        self.additional_rotation_map = additional_rotation_map\n        self.src_inv_joint_map = dict((v,k) for k, v in src_model[\"joints\"].items())\n        self.src_child_map = dict()\n        self.src_parent_map = get_parent_map(src_joints)\n        src_children_map = get_children_map(src_joints)\n        for src_name in self.src_joints:\n            src_child = get_child_joint(self.src_model, self.src_inv_joint_map, src_name, src_children_map)\n            if src_child is not None:\n                self.src_parent_map[src_child] = src_name\n                self.src_child_map[src_name] = src_child\n            else:\n                self.src_child_map[src_name] = None\n        #print(\"ch\",self.src_child_map)\n        #for j in [\"pelvis\", \"spine\", \"spine_1\", \"spine_2\"]:\n        #    if j in target_joints:\n        src_joint_map = self.src_model[\"joints\"]\n        for j in [\"neck\", \"spine_2\", \"spine_1\", \"spine\"]:\n            if j in src_joint_map:\n                self.src_parent_map[\"spine_03\"] = \"pelvis\"\n        self.src_child_map[src_joint_map[\"pelvis\"]] = src_joint_map[\"neck\"]#\"pelvis\" \"neck_01\"\n\n        self.constant_offset = constant_offset\n        self.place_on_ground = place_on_ground\n        self.temp_frame_data = dict()\n\n        self.target_cos_map = create_local_cos_map_from_skeleton_axes_with_map(self.target_skeleton)\n        if \"cos_map\" in target_skeleton.skeleton_model:\n            self.target_cos_map.update(target_skeleton.skeleton_model[\"cos_map\"])\n\n        target_joints = self.target_skeleton.skeleton_model[\"joints\"]\n        self.target_spine_joints = [target_joints[j] for j in [\"neck\", \"spine_2\", \"spine_1\", \"spine\"] if j in target_joints]#[\"spine_03\", \"neck_01\"]\n        self.target_ball_joints = [target_joints[j] for j in [\"left_shoulder\", \"right_shoulder\", \"left_hip\", \"right_hip\"] if j in target_joints]# [\"thigh_r\", \"thigh_l\", \"upperarm_r\", \"upperarm_l\"]\n        self.target_ankle_joints = [target_joints[j] for j in [\"left_ankle\", \"right_ankle\"] if j in target_joints]\n        self.clavicle_joints = [target_joints[j] for j in [\"right_clavicle\", \"left_clavicle\"] if j in target_joints]\n        self.twist_angle_joints = [target_joints[j] for j in [\"right_knee\",\"left_knee\",\"left_shoulder\", \"right_shoulder\", \"right_clavicle\", \"left_clavicle\",\"right_elbow\", \"left_elbow\",\"left_wrist\", \"right_wrist\"] if j in target_joints]\n        if \"neck\" in target_joints:\n            self.target_neck_joint = target_joints[\"neck\"]\n        else:\n            self.target_neck_joint = None\n\n        left_hip = self.src_model[\"joints\"][\"left_hip\"]\n        right_hip = self.src_model[\"joints\"][\"right_hip\"]\n        self.left_hip_idx = self.src_joints[left_hip][\"index\"]\n        self.right_hip_idx = self.src_joints[right_hip][\"index\"]\n        left_shoulder = self.src_model[\"joints\"][\"left_shoulder\"]\n        right_shoulder = self.src_model[\"joints\"][\"right_shoulder\"]\n        self.left_shoulder_idx = self.src_joints[left_shoulder][\"index\"]\n        self.right_shoulder_idx = self.src_joints[right_shoulder][\"index\"]\n        self.ref_rotation = dict()\n        for target_name in self.target_skeleton.animated_joints:\n            self.ref_rotation[target_name] = get_quaternion_rotation_by_name(target_name, self.target_skeleton.reference_frame,\n                                                                             self.target_skeleton, root_offset=3)\n\n\n    def estimate_src_joint_cos(self, src_name, child_name, target_name, src_frame):\n        joint_idx = self.src_joints[src_name][\"index\"]\n        child_idx = self.src_joints[child_name][\"index\"]\n        global_src_up_vec = src_frame[child_idx] - src_frame[joint_idx]\n        global_src_up_vec /= np.linalg.norm(global_src_up_vec)\n        self.temp_frame_data[src_name] = global_src_up_vec\n        if target_name == self.target_skeleton.skeleton_model[\"joints\"][\"pelvis\"]:\n            global_src_x_vec = src_frame[self.left_hip_idx] - src_frame[self.right_hip_idx]\n            global_src_x_vec /= np.linalg.norm(global_src_x_vec)\n        elif target_name in self.target_spine_joints or target_name == \"CC_Base_Waist\":  # find x vector from shoulders\n            global_src_x_vec = src_frame[self.left_shoulder_idx] - src_frame[self.right_shoulder_idx]\n            global_src_x_vec /= np.linalg.norm(global_src_x_vec)\n        elif target_name in self.target_ball_joints:  # use x vector of child\n            child_child_name = self.src_child_map[child_name]\n            child_child_idx = self.src_joints[child_child_name][\"index\"]\n            child_global_src_up_vec = src_frame[child_child_idx] - src_frame[child_idx]\n            child_global_src_up_vec /= np.linalg.norm(child_global_src_up_vec)\n            global_src_x_vec = np.cross(global_src_up_vec, child_global_src_up_vec)\n            global_src_x_vec /= np.linalg.norm(global_src_x_vec)\n        else:  # find x vector by cross product with parent\n            global_src_x_vec = None\n            if src_name in self.src_parent_map:\n                parent_joint = self.src_parent_map[src_name]\n                if parent_joint in self.temp_frame_data:\n                    global_parent_up_vector = self.temp_frame_data[parent_joint]\n                    global_src_x_vec = np.cross(global_src_up_vec, global_parent_up_vector)\n                    global_src_x_vec /= np.linalg.norm(global_src_x_vec)\n                    if target_name not in self.target_ankle_joints:\n                        global_src_x_vec = -global_src_x_vec\n        return global_src_up_vec, global_src_x_vec\n\n    def rotate_bone(self, src_name, target_name, src_frame, target_frame, guess, pose_angles=None):\n        q = guess\n        if src_name not in self.src_child_map.keys() or self.src_child_map[src_name] is None:\n            return q\n        if self.src_child_map[src_name] in self.src_to_target_joint_map:#  and or target_name ==\"neck_01\" or target_name.startswith(\"hand\")\n            child_name = self.src_child_map[src_name]\n            if child_name not in self.src_joints.keys():\n                return q\n            is_root = False\n            if target_name == self.target_skeleton_root:\n                is_root = True\n            src_cos = self.estimate_src_joint_cos(src_name, child_name, target_name, src_frame)\n            if src_cos[1] is None:\n                return q\n            twist_angle = None\n            if pose_angles is not None and self.target_skeleton.nodes[target_name].parent is not None and target_name in self.twist_angle_joints:\n                joint_idx = self.src_joints[src_name][\"index\"]\n                twist_angle = pose_angles[joint_idx][0]\n            q = find_rotation_analytically(self.target_skeleton, target_name, src_cos, target_frame, self.target_cos_map, is_root=is_root, twist_angle=twist_angle)\n        return q/np.linalg.norm(q)\n\n    def retarget_frame(self, src_frame, ref_frame, pose_angles=None):\n\n        self.target_skeleton.clear_cached_global_matrices()\n        target_frame = np.zeros(self.n_params)\n        self.temp_frame_data.clear()\n        # copy the root translation assuming the rocketbox skeleton with static offset on the hips is used as source\n        target_frame[:3] = np.array(src_frame[0]) * self.scale_factor\n        if self.constant_offset is not None:\n            target_frame[:3] += self.constant_offset\n        animated_joints = self.target_skeleton.animated_joints\n        target_offset = 3\n        for target_name in animated_joints:\n            q = self.ref_rotation[target_name]\n            if target_name in self.target_to_src_joint_map.keys():\n                src_name = self.target_to_src_joint_map[target_name]\n                if src_name is not None and src_name in self.src_joints.keys():\n                    q = self.rotate_bone(src_name, target_name, src_frame, target_frame, q, pose_angles)\n            #if ref_frame is not None:\n            #    q = q if np.dot(ref_frame[target_offset:target_offset + 4], q) >= 0 else -q\n            target_frame[target_offset:target_offset + 4] = q\n            target_offset += 4\n        return target_frame\n\n    def run(self, src_frames, frame_range):\n        n_frames = len(src_frames)\n        target_frames = []\n        if n_frames > 0:\n            if frame_range is None:\n                frame_range = (0, n_frames)\n            if self.additional_rotation_map is not None:\n               src_frames = apply_additional_rotation_on_frames(self.src_skeleton.animated_joints, src_frames, self.additional_rotation_map)\n\n            ref_frame = None\n            for idx, src_frame in enumerate(src_frames[frame_range[0]:frame_range[1]]):\n                target_frame = self.retarget_frame(src_frame, ref_frame)\n                if ref_frame is None:\n                    ref_frame = target_frame\n                target_frames.append(target_frame)\n            target_frames = np.array(target_frames)\n            if self.place_on_ground:\n                delta = target_frames[0][1] - self.ground_height\n                target_frames[:, 1] -= delta\n        return target_frames\n\n\ndef generate_joint_map(src_model, target_model):\n    joint_map = dict()\n    for j in src_model[\"joints\"]:\n        if j in target_model[\"joints\"]:\n            src = src_model[\"joints\"][j]\n            target = target_model[\"joints\"][j]\n            joint_map[target] = src\n    return joint_map\n\n\ndef retarget_from_point_cloud_to_target(src_joints, src_model, target_skeleton, src_frames, joint_map=None, additional_rotation_map=None, scale_factor=1.0, frame_range=None, place_on_ground=False):\n    if joint_map is None:\n        joint_map = generate_joint_map(src_model, target_skeleton.skeleton_model)\n    retargeting = PointCloudRetargeting(src_joints, src_model, target_skeleton, joint_map, scale_factor, additional_rotation_map=additional_rotation_map, place_on_ground=place_on_ground)\n    return retargeting.run(src_frames, frame_range)\n", "meta": {"hexsha": "96981eb4c7019d3d1cebe373610f32017ea4e9c8", "size": 23528, "ext": "py", "lang": "Python", "max_stars_repo_path": "anim_utils/retargeting/point_cloud_retargeting.py", "max_stars_repo_name": "jsprenger2/anim_utils", "max_stars_repo_head_hexsha": "d28d4384cf16af5a8c1ec482e3c7d597286933e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-01T01:55:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T01:55:02.000Z", "max_issues_repo_path": "anim_utils/retargeting/point_cloud_retargeting.py", "max_issues_repo_name": "jsprenger2/anim_utils", "max_issues_repo_head_hexsha": "d28d4384cf16af5a8c1ec482e3c7d597286933e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "anim_utils/retargeting/point_cloud_retargeting.py", "max_forks_repo_name": "jsprenger2/anim_utils", "max_forks_repo_head_hexsha": "d28d4384cf16af5a8c1ec482e3c7d597286933e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.7420718816, "max_line_length": 237, "alphanum_fraction": 0.7001445087, "include": true, "reason": "import numpy", "num_tokens": 5721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3040416812727289, "lm_q1q2_score": 0.16150979098838966}}
{"text": "#!/usr/bin/env python\n\n\"\"\"\nThis module provides classes to create phase diagrams.\n\"\"\"\n\nfrom __future__ import division\n\n__author__ = \"Shyue Ping Ong\"\n__copyright__ = \"Copyright 2011, The Materials Project\"\n__version__ = \"2.0\"\n__maintainer__ = \"Shyue Ping Ong\"\n__email__ = \"shyue@mit.edu\"\n__status__ = \"Production\"\n__date__ = \"Nov 25, 2012\"\n\nimport collections\nimport logging\n\nimport numpy as np\n\nfrom pyhull.convex_hull import ConvexHull\n\nfrom pymatgen.core.composition import Composition\nfrom pymatgen.phasediagram.entries import GrandPotPDEntry, TransformedPDEntry\n\nfrom pymatgen.core.periodic_table import DummySpecie\nfrom pymatgen.analysis.reaction_calculator import Reaction, ReactionError\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass PhaseDiagram (object):\n    \"\"\"\n    Simple phase diagram class taking in elements and entries as inputs.\n    The algorithm is based on the work in the following papers:\n\n    1. S. P. Ong, L. Wang, B. Kang, and G. Ceder, Li-Fe-P-O2 Phase Diagram from\n       First Principles Calculations. Chem. Mater., 2008, 20(5), 1798-1807.\n       doi:10.1021/cm702327g\n\n    2. S. P. Ong, A. Jain, G. Hautier, B. Kang, G. Ceder, Thermal stabilities\n       of delithiated olivine MPO4 (M=Fe, Mn) cathodes investigated using first\n       principles calculations. Electrochem. Comm., 2010, 12(3), 427-430.\n       doi:10.1016/j.elecom.2010.01.010\n\n    .. attribute: elements:\n\n        Elements in the phase diagram.\n\n    ..attribute: all_entries\n\n        All entries provided for Phase Diagram construction. Note that this\n        does not mean that all these entries are actually used in the phase\n        diagram. For example, this includes the positive formation energy\n        entries that are filtered out before Phase Diagram construction.\n\n    .. attribute: qhull_data\n\n        Data used in the convex hull operation. This is essentially a matrix of\n        composition data and energy per atom values created from qhull_entries.\n\n    .. attribute: dim\n\n        The dimensionality of the phase diagram.\n\n    .. attribute: facets\n\n        Facets of the phase diagram in the form of  [[1,2,3],[4,5,6]...]\n\n    .. attribute: el_refs:\n\n        List of elemental references for the phase diagrams. These are\n        entries corresponding to the lowest energy element entries for simple\n        compositional phase diagrams.\n\n    .. attribute: qhull_entries:\n\n        Actual entries used in convex hull. Excludes all positive formation\n        energy entries.\n    \"\"\"\n\n    # Tolerance for determining if formation energy is positive.\n    formation_energy_tol = 1e-11\n\n    def __init__(self, entries, elements=None):\n        \"\"\"\n        Standard constructor for phase diagram.\n\n        Args:\n            entries:\n                A list of PDEntry-like objects having an energy,\n                energy_per_atom and composition.\n            elements:\n                Optional list of elements in the phase diagram. If set to None,\n                the elements are determined from the the entries themselves.\n        \"\"\"\n        if elements is None:\n            elements = set()\n            map(elements.update, [entry.composition.elements\n                                  for entry in entries])\n        self.all_entries = entries\n        self.elements = tuple(elements)\n        dim = len(self.elements)\n        self.el_refs = self._get_el_refs()\n        (self.qhull_entries, qhull_data) = self._create_convhull_data()\n        if len(qhull_data) == dim:\n            self.facets = [range(dim)]\n        else:\n            facets = ConvexHull(qhull_data).vertices\n            logger.debug(\"Final facets are\\n{}\".format(facets))\n\n            logger.debug(\"Removing vertical facets...\")\n            finalfacets = []\n            for facet in facets:\n                facetmatrix = np.zeros((len(facet), len(facet)))\n                count = 0\n                is_element_facet = True\n                for vertex in facet:\n                    facetmatrix[count] = np.array(qhull_data[vertex])\n                    facetmatrix[count, dim - 1] = 1\n                    count += 1\n                    if len(self.qhull_entries[vertex].composition) > 1:\n                        is_element_facet = False\n                if abs(np.linalg.det(facetmatrix)) > 1e-8 and\\\n                        (not is_element_facet):\n                    finalfacets.append(facet)\n                else:\n                    logger.debug(\"Removing vertical facet : {}\".format(facet))\n            self.facets = finalfacets\n        self.qhull_data = qhull_data\n        self.dim = dim\n\n    @property\n    def unstable_entries(self):\n        \"\"\"\n        Entries that are unstable in the phase diagram. Includes positive\n        formation energy entries.\n        \"\"\"\n        return [e for e in self.all_entries if e not in self.stable_entries]\n\n    @property\n    def stable_entries(self):\n        \"\"\"\n        Returns the stable entries in the phase diagram.\n        \"\"\"\n        stable_entries = set()\n        for facet in self.facets:\n            for vertex in facet:\n                stable_entries.add(self.qhull_entries[vertex])\n        return stable_entries\n\n    @property\n    def all_entries_hulldata(self):\n        \"\"\"\n        Same as qhull_data, but for all entries rather than just negative\n        formation energy ones.\n        \"\"\"\n        return self._process_entries_qhulldata(self.all_entries)\n\n    def get_form_energy(self, entry):\n        \"\"\"\n        Returns the formation energy for an entry (NOT normalized) from the\n        elemental references.\n\n        Args:\n            entry:\n                A PDEntry-like object.\n\n        Returns:\n            Formation energy from the elemental references.\n        \"\"\"\n        comp = entry.composition\n        energy = entry.energy - sum([comp[el] *\n                                     self.el_refs[el].energy_per_atom\n                                     for el in comp.elements])\n        return energy\n\n    def get_form_energy_per_atom(self, entry):\n        \"\"\"\n        Returns the formation energy per atom for an entry from the\n        elemental references.\n\n        Args:\n            entry:\n                An PDEntry-like object\n\n        Returns:\n            Formation energy **per atom** from the elemental references.\n        \"\"\"\n        comp = entry.composition\n        return self.get_form_energy(entry) / comp.num_atoms\n\n    def _process_entries_qhulldata(self, entries_to_process):\n        \"\"\"\n        From a sequence of entries, generate the necessary for the convex hull.\n        Using the Li-Fe-O phase diagram as an example, this is of the form:\n        [[ Fe_fraction_entry_1, O_fraction_entry_1, Energy_per_atom_entry_1],\n         [ Fe_fraction_entry_2, O_fraction_entry_2, Energy_per_atom_entry_2],\n         ...]]\n\n        Note that there are only two independent variables, since the third\n        elemental fraction is fixed by the constraint that all compositions sum\n        to 1. The choice of the elements is arbitrary.\n        \"\"\"\n        def make_row(entry):\n            comp = entry.composition\n            row = [comp.get_atomic_fraction(self.elements[i])\n                   for i in xrange(1, len(self.elements))]\n            row.append(entry.energy_per_atom)\n            return row\n\n        return map(make_row, entries_to_process)\n\n    def _get_el_refs(self):\n        el_refs = {}\n        for el in self.elements:\n            el_entries = filter(lambda e: e.composition.is_element and\n                                e.composition.elements[0] == el,\n                                self.all_entries)\n            if len(el_entries) == 0:\n                raise PhaseDiagramError(\"There are no entries associated with\"\n                                        \" terminal {}.\".format(el))\n            el_refs[el] = min(el_entries, key=lambda e: e.energy_per_atom)\n        return el_refs\n\n    def _create_convhull_data(self):\n        \"\"\"\n        Make data suitable for convex hull procedure from the list of entries.\n        The procedure is as follows:\n\n        1. First find the elemental references, i.e., the lowest energy entry\n           for the vertices of the phase diagram. Using the Li-Fe-O phase\n           diagram as an example, this means the lowest energy Li, Fe, and O\n           phases.\n        2. Calculate the formation energies from these elemental references for\n           all entries. Exclude all positive formation energy ones from the\n           data for convex hull.\n        3. Generate the convex hull data.\n        \"\"\"\n        logger.debug(\"Creating convex hull data...\")\n        # Remove positive formation energy entries\n        qhull_entries = []\n        for entry in self.all_entries:\n            if self.get_form_energy(entry) <= -self.formation_energy_tol:\n                qhull_entries.append(entry)\n            else:\n                logger.debug(\"Removing positive formation energy entry \" +\n                             \"{}\".format(entry))\n        qhull_entries.extend(self.el_refs.values())\n\n        return qhull_entries, self._process_entries_qhulldata(qhull_entries)\n\n    def __repr__(self):\n        return self.__str__()\n\n    def __str__(self):\n        symbols = [el.symbol for el in self.elements]\n        output = [\"{} phase diagram\".format(\"-\".join(symbols)),\n                  \"{} stable phases: \".format(len(self.stable_entries)),\n                  \", \".join([entry.name\n                             for entry in self.stable_entries])]\n        return \"\\n\".join(output)\n\n\nclass GrandPotentialPhaseDiagram(PhaseDiagram):\n    \"\"\"\n    A class representing a Grand potential phase diagram. Grand potential phase\n    diagrams are essentially phase diagrams that are open to one or more\n    components. To construct such phase diagrams, the relevant free energy is\n    the grand potential, which can be written as the Legendre transform of the\n    Gibbs free energy as follows\n\n    Grand potential = G - u\\ :sub:`X` N\\ :sub:`X`\\\n\n    The algorithm is based on the work in the following papers:\n\n    1. S. P. Ong, L. Wang, B. Kang, and G. Ceder, Li-Fe-P-O2 Phase Diagram from\n       First Principles Calculations. Chem. Mater., 2008, 20(5), 1798-1807.\n       doi:10.1021/cm702327g\n\n    2. S. P. Ong, A. Jain, G. Hautier, B. Kang, G. Ceder, Thermal stabilities\n       of delithiated olivine MPO4 (M=Fe, Mn) cathodes investigated using first\n       principles calculations. Electrochem. Comm., 2010, 12(3), 427-430.\n       doi:10.1016/j.elecom.2010.01.010\n    \"\"\"\n\n    def __init__(self, entries, chempots, elements=None):\n        \"\"\"\n        Standard constructor for grand potential phase diagram.\n\n        Args:\n            entries:\n                A list of PDEntry-like objects having an energy,\n                energy_per_atom and composition.\n            chempots:\n                A dict of {element: float} to specify the chemical potentials\n                of the open elements.\n            elements:\n                Optional list of elements in the phase diagram. If set to None,\n                the elements are determined from the entries themselves.\n        \"\"\"\n        if elements is None:\n            elements = set()\n            map(elements.update, [entry.composition.elements\n                                  for entry in entries])\n\n        elements = set(elements).difference(chempots.keys())\n        all_entries = [GrandPotPDEntry(e, chempots)\n                       for e in entries\n                       if (not e.is_element) or\n                       e.composition.elements[0] in elements]\n        self.chempots = chempots\n\n        super(GrandPotentialPhaseDiagram, self).__init__(all_entries, elements)\n\n    def __str__(self):\n        output = []\n        chemsys = \"-\".join([el.symbol for el in self.elements])\n        output.append(\"{} grand potential phase diagram with \".format(chemsys))\n        output[-1] += \", \".join([\"u{}={}\".format(el, v)\n                                 for el, v in self.chempots.items()])\n        output.append(\"{} stable phases: \".format(len(self.stable_entries)))\n        output.append(\", \".join([entry.name\n                                 for entry in self.stable_entries]))\n        return \"\\n\".join(output)\n\n\nclass CompoundPhaseDiagram(PhaseDiagram):\n    \"\"\"\n    Generates phase diagrams from compounds as terminations instead of\n    elements.\n    \"\"\"\n\n    # Tolerance for determining if amount of a composition is positive.\n    amount_tol = 1e-5\n\n    def __init__(self, entries, terminal_compositions,\n                 normalize_terminal_compositions=True):\n        \"\"\"\n        Args:\n            entries:\n                Sequence of input entries. For example, if you want a Li2O-P2O5\n                phase diagram, you might have all Li-P-O entries as an input.\n            terminal_compositions:\n                Terminal compositions of phase space. In the Li2O-P2O5 example,\n                these will be the Li2O and P2O5 compositions.\n            normalize_terminal_compositions:\n                Whether to normalize the terminal compositions to a per atom\n                basis. If normalized, the energy above hulls will be consistent\n                for comparison across systems. Non-normalized terminals are\n                more intuitive in terms of compositional breakdowns.\n        \"\"\"\n        self.original_entries = entries\n        self.terminal_compositions = terminal_compositions\n        self.normalize_terminals = normalize_terminal_compositions\n        (pentries, species_mapping) = \\\n            self.transform_entries(entries, terminal_compositions)\n        self.species_mapping = species_mapping\n        PhaseDiagram.__init__(self, pentries,\n                              elements=species_mapping.values())\n\n    def transform_entries(self, entries, terminal_compositions):\n        \"\"\"\n        Method to transform all entries to the composition coordinate in the\n        terminal compositions. If the entry does not fall within the space\n        defined by the terminal compositions, they are excluded. For example,\n        Li3PO4 is mapped into a Li2O:1.5, P2O5:0.5 composition. The terminal\n        compositions are represented by DummySpecies.\n\n        Args:\n            entries:\n                Sequence of all input entries\n            terminal_compositions:\n                Terminal compositions of phase space.\n\n        Returns:\n            Sequence of TransformedPDEntries falling within the phase space.\n        \"\"\"\n        new_entries = []\n        if self.normalize_terminals:\n            fractional_comp = [c.get_fractional_composition()\n                               for c in terminal_compositions]\n        else:\n            fractional_comp = terminal_compositions\n\n        #Map terminal compositions to unique dummy species.\n        sp_mapping = collections.OrderedDict()\n        for i, comp in enumerate(fractional_comp):\n            sp_mapping[comp] = DummySpecie(\"X\" + chr(102 + i))\n\n        for entry in entries:\n            try:\n                rxn = Reaction(fractional_comp, [entry.composition])\n                rxn.normalize_to(entry.composition)\n                #We only allow reactions that have positive amounts of\n                #reactants.\n                if all([rxn.get_coeff(comp) <= CompoundPhaseDiagram.amount_tol\n                        for comp in fractional_comp]):\n                    newcomp = {sp_mapping[comp]: -rxn.get_coeff(comp)\n                               for comp in fractional_comp}\n                    newcomp = {k: v for k, v in newcomp.items()\n                               if v > CompoundPhaseDiagram.amount_tol}\n                    transformed_entry = \\\n                        TransformedPDEntry(Composition(newcomp), entry)\n                    new_entries.append(transformed_entry)\n            except ReactionError:\n                #If the reaction can't be balanced, the entry does not fall\n                #into the phase space. We ignore them.\n                pass\n        return new_entries, sp_mapping\n\n\nclass PhaseDiagramError(Exception):\n    \"\"\"\n    An exception class for Phase Diagram.\n    \"\"\"\n    def __init__(self, msg):\n        \"\"\"\n        Args:\n            msg:\n                The error message.\n        \"\"\"\n        self.msg = msg\n\n    def __str__(self):\n        return self.msg\n", "meta": {"hexsha": "fa9301fdb23ff4aacb282fa8b006e7255dd8f582", "size": 16223, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymatgen/phasediagram/pdmaker.py", "max_stars_repo_name": "qimin/pymatgen", "max_stars_repo_head_hexsha": "4823c777a8af4a3ca7cd29297563ba8174ec402c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-29T20:03:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T20:03:58.000Z", "max_issues_repo_path": "pymatgen/phasediagram/pdmaker.py", "max_issues_repo_name": "qimin/pymatgen", "max_issues_repo_head_hexsha": "4823c777a8af4a3ca7cd29297563ba8174ec402c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pymatgen/phasediagram/pdmaker.py", "max_forks_repo_name": "qimin/pymatgen", "max_forks_repo_head_hexsha": "4823c777a8af4a3ca7cd29297563ba8174ec402c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8158508159, "max_line_length": 79, "alphanum_fraction": 0.6075941564, "include": true, "reason": "import numpy", "num_tokens": 3430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.30404168127272885, "lm_q1q2_score": 0.16150979098838963}}
{"text": "#!/usr/bin/env python\n\"\"\"\nThis module contains functions and class definitions for running forward\nmodels of models based on logistic regression.\n\"\"\"\n\n# stdlib imports\nimport numpy as np\nimport os.path\nimport re\nimport collections\nimport shutil\nimport tempfile\nfrom timeit import default_timer as timer\n\n# third party imports\nfrom mapio.shake import ShakeGrid\nfrom mapio.shake import getHeaderData\nfrom mapio.gmt import GMTGrid\nfrom mapio.gdal import GDALGrid\nfrom mapio.grid2d import Grid2D\nfrom mapio.geodict import GeoDict\n\nfrom gfail.temphdf import TempHdf\nfrom gfail.spatial import quickcut, trim_ocean\nfrom gfail.utilities import getFileType\nfrom gfail.stats import get_rangebeta\n\n# temporary until mapio is updated\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\nPARAM_PATTERN = 'b[0-9]+'\nLAYER_PATTERN = '_layer'\nTERM_PATTERN = 'term'\n\nSM_TERMS = ['MW', 'YEAR', 'MONTH', 'DAY', 'HOUR', 'pga', 'pgv', 'mmi']\nSM_GRID_TERMS = ['pga', 'pgv', 'mmi']\n# these will get np. prepended\nOPERATORS = ['log', 'log10', 'arctan', 'power', 'sqrt', 'minimum', 'pi']\nFLOATPAT = r'[+-]?(?=\\d*[.eE])(?=\\.?\\d)\\d*\\.?\\d*(?:[eE][+-]?\\d+)?'\nINTPAT = '[0-9]+'\nOPERATORPAT = r'[\\+\\-\\*\\/]*'\nMONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',\n          'Nov', 'Dec']\n\n\nclass LogisticModel(object):\n    def __init__(self, shakefile, config, uncertfile=None, saveinputs=False,\n                 slopefile=None, bounds=None, slopemod=None,\n                 trimfile=None):\n        \"\"\"\n        Sets up the logistic model\n\n        Args:\n            shakefile (str): Path to shakemap grid.xml file for the event.\n            config: configobj object defining the model and its inputs. Only\n                one model should be described in each config file.\n            uncertfile (str): Path to uncertainty.xml file.\n            saveinputs (bool): Save input layers as Grid2D objects in addition\n                to the model? If false (the default), it will just output the\n                model.\n            slopefile (str): Optional path to slopefile that will be resampled\n                to the other input files for applying thresholds. OVERWRITES\n                VALUE IN CONFIG.\n            bounds (dict): Default of None uses ShakeMap boundaries, otherwise\n                a dictionary of boundaries to cut to like\n\n                .. code-block:: python\n\n                    bounds = {\n                        'xmin': lonmin, 'xmax': lonmax,\n                        'ymin': latmin, 'ymax': latmax\n                    }\n            slopemod (str): How slope input should be modified to be in\n                degrees: e.g., ``np.arctan(slope) * 180. / np.pi`` or\n                ``slope/100.`` (note that this may be in the config file\n                already).\n            trimfile (str): shapefile of earth's landmasses to use to cut\n                offshore areas.\n        \"\"\"\n        mnames = getLogisticModelNames(config)\n        if len(mnames) == 0:\n            raise Exception('No config file found or problem with config '\n                            'file format')\n        if len(mnames) > 1:\n            raise Exception('Config file contains more than one model which '\n                            'is no longer allowed, update your config file '\n                            'to the newer format')\n\n        self.model = mnames[0]\n        self.config = config\n        cmodel = config[self.model]\n        self.modeltype = cmodel['gfetype']\n        self.coeffs = validateCoefficients(cmodel)\n        # key = layer name, value = file name\n        self.layers = validateLayers(cmodel)\n        self.terms, timeField = validateTerms(cmodel, self.coeffs, self.layers)\n        self.interpolations = validateInterpolations(cmodel, self.layers)\n        self.units = validateUnits(cmodel)\n        self.gmused = [value for term, value in cmodel['terms'].items()\n                       if 'pga' in value.lower() or 'pgv' in\n                       value.lower() or 'mmi' in value.lower()]\n        self.modelrefs, self.longrefs, self.shortrefs = validateRefs(cmodel)\n        # self.numstd = numstd\n        self.clips = validateClips(cmodel, self.layers, self.gmused)\n        self.notes = ''\n\n        if cmodel['baselayer'] not in list(self.layers.keys()):\n            raise Exception('You must specify a base layer corresponding to '\n                            'one of the files in the layer section.')\n        self.saveinputs = saveinputs\n        if slopefile is None:\n            try:\n                self.slopefile = cmodel['slopefile']\n            except BaseException:\n                # print('Slopefile not specified in config, no slope '\n                #      'thresholds will be applied\\n')\n                self.slopefile = None\n        else:\n            self.slopefile = slopefile\n        if slopemod is None:\n            try:\n                self.slopemod = cmodel['slopemod']\n            except BaseException:\n                self.slopemod = None\n\n        # See if trimfile exists\n        if trimfile is not None:\n            if not os.path.exists(trimfile):\n                print(\n                    'trimfile defined does not exist: %s\\nOcean will not be '\n                    'trimmed' % trimfile)\n                self.trimfile = None\n            elif os.path.splitext(trimfile)[1] != '.shp':\n                print('trimfile must be a shapefile, ocean will not be '\n                      'trimmed')\n                self.trimfile = None\n            else:\n                self.trimfile = trimfile\n        else:\n            self.trimfile = None\n\n        # Get month of event\n        griddict, eventdict, specdict, fields, uncertainties = \\\n            getHeaderData(shakefile)\n        MONTH = MONTHS[eventdict['event_timestamp'].month - 1]\n\n        # Figure out how/if need to cut anything\n        geodict = ShakeGrid.getFileGeoDict(shakefile, adjust='res')\n        if bounds is not None:  # Make sure bounds are within ShakeMap Grid\n            if geodict.xmin < geodict.xmax:  # only if signs are not opposite\n                if (geodict.xmin > bounds['xmin'] or\n                        geodict.xmax < bounds['xmax'] or\n                        geodict.ymin > bounds['ymin'] or\n                        geodict.ymax < bounds['ymax']):\n                    print('Specified bounds are outside shakemap area, using '\n                          'ShakeMap bounds instead.')\n                    bounds = None\n\n        if bounds is not None:\n            tempgdict = GeoDict.createDictFromBox(\n                bounds['xmin'], bounds['xmax'],\n                bounds['ymin'], bounds['ymax'],\n                geodict.dx, geodict.dy, inside=False)\n            # If Shakemap geodict crosses 180/-180 line, fix geodict so\n            # things don't break\n            if geodict.xmin > geodict.xmax:\n                if tempgdict.xmin < 0:\n                    geodict._xmin -= 360.\n                else:\n                    geodict._xmax += 360.\n            gdict = geodict.getBoundsWithin(tempgdict)\n        else:\n            gdict = geodict\n\n        # Now find the layer that is our base layer and get the largest bounds\n        # we can guarantee not to exceed shakemap bounds\n        basefile = self.layers[cmodel['baselayer']]\n        ftype = getFileType(basefile)\n        if ftype == 'esri':\n            basegeodict, firstcol = GDALGrid.getFileGeoDict(basefile)\n            if basegeodict == gdict:\n                sampledict = gdict\n            else:\n                sampledict = basegeodict.getBoundsWithin(gdict)\n        elif ftype == 'gmt':\n            basegeodict, firstcol = GMTGrid.getFileGeoDict(basefile)\n            if basegeodict == gdict:\n                sampledict = gdict\n            else:\n                sampledict = basegeodict.getBoundsWithin(gdict)\n        else:\n            raise Exception('All predictor variable grids must be a valid '\n                            'GMT or ESRI file type.')\n\n        # Do we need to subdivide baselayer?\n        if 'divfactor' in self.config[self.model].keys():\n            divfactor = float(self.config[self.model]['divfactor'])\n            if divfactor != 1.:\n                # adjust sampledict so everything will be resampled\n                newxmin = sampledict.xmin - sampledict.dx / \\\n                    2. + sampledict.dx / (2. * divfactor)\n                newymin = sampledict.ymin - sampledict.dy / \\\n                    2. + sampledict.dy / (2. * divfactor)\n                newxmax = sampledict.xmax + sampledict.dx / \\\n                    2. - sampledict.dx / (2. * divfactor)\n                newymax = sampledict.ymax + sampledict.dy / \\\n                    2. - sampledict.dy / (2. * divfactor)\n                newdx = sampledict.dx / divfactor\n                newdy = sampledict.dy / divfactor\n                if np.abs(newxmax) > 180.:\n                    newxmax = np.sign(newxmax) * 180.\n                if np.abs(newxmin) > 180.:\n                    newxmin = np.sign(newxmin) * 180.\n\n                sampledict = GeoDict.createDictFromBox(\n                    newxmin, newxmax, newymin,\n                    newymax, newdx, newdy, inside=True)\n\n        # Find slope thresholds, if applicable\n        self.slopemin = 'none'\n        self.slopemax = 'none'\n        if self.slopefile is not None:\n            try:\n                self.slopemin = float(config[self.model]['slopemin'])\n                self.slopemax = float(config[self.model]['slopemax'])\n            except BaseException:\n                print('Could not find slopemin and/or slopemax in config, '\n                      'limits. No slope thresholds will be applied.')\n                self.slopemin = 'none'\n                self.slopemax = 'none'\n\n        # Make temporary directory for hdf5 pytables file storage\n        self.tempdir = tempfile.mkdtemp()\n\n        # now load the shakemap, resampling and padding if necessary\n        temp = ShakeGrid.load(shakefile)  # , adjust='res')\n        self.shakedict = temp.getShakeDict()\n        self.eventdict = temp.getEventDict()\n        self.shakemap = {}\n\n        # Read both PGA and PGV in, may need them for thresholds\n        for gm in ['pga', 'pgv']:\n            junkfile = os.path.join(self.tempdir, 'temp.bil')\n            GDALGrid.copyFromGrid(temp.getLayer(gm)).save(junkfile)\n            if gm in self.interpolations.keys():\n                intermeth = self.interpolations[gm]\n            else:\n                intermeth = 'bilinear'\n            junkgrid = quickcut(junkfile, sampledict, precise=True,\n                                method=intermeth, override=True)\n            if gm in self.clips:\n                junkgrid.setData(np.clip(junkgrid.getData(),\n                                         self.clips[gm][0], self.clips[gm][1]))\n            self.shakemap[gm] = TempHdf(\n                junkgrid, os.path.join(self.tempdir, '%s.hdf5' % gm))\n            os.remove(junkfile)\n        del(temp)\n\n        # get updated geodict\n        sampledict = junkgrid.getGeoDict()\n\n        # take uncertainties into account, if available\n        if uncertfile is not None:\n            self.uncert = {}\n            # try:\n            # Only read in the ones that will be needed\n            temp = ShakeGrid.load(uncertfile)\n            already = []\n            for gm in self.gmused:\n                if 'pgv' in gm:\n                    gmsimp = 'pgv'\n                elif 'pga' in gm:\n                    gmsimp = 'pga'\n                elif 'mmi' in gm:\n                    gmsimp = 'mmi'\n                if gmsimp in already:\n                    continue\n                junkfile = os.path.join(self.tempdir, 'temp.bil')\n                GDALGrid.copyFromGrid(temp.getLayer(\n                    'std%s' % gmsimp)).save(junkfile)\n                if gmsimp in self.interpolations.keys():\n                    intermeth = self.interpolations[gmsimp]\n                else:\n                    intermeth = 'bilinear'\n                junkgrid = quickcut(junkfile, sampledict, precise=True,\n                                    method=intermeth, override=True)\n                if gmsimp in self.clips:\n                    junkgrid.setData(\n                        np.clip(junkgrid.getData(), self.clips[gmsimp][0],\n                                self.clips[gmsimp][1]))\n                self.uncert['std' + gmsimp] = TempHdf(\n                    junkgrid, os.path.join(self.tempdir,\n                                           'std%s.hdf5' % gmsimp))\n                already.append(gmsimp)\n                os.remove(junkfile)\n            del(temp)\n            # except:\n            # print('Could not read uncertainty file, ignoring '\n            #       'uncertainties')\n            # self.uncert = None\n        else:\n            self.uncert = None\n\n        # Load the predictor layers, save as hdf5 temporary files, put file\n        # locations into a dictionary.\n\n        # Will be replaced in the next section if a slopefile was defined\n        self.nonzero = None\n\n        # key = layer name, value = grid object\n        self.layerdict = {}\n\n        didslope = False\n        for layername, layerfile in self.layers.items():\n            start = timer()\n            if isinstance(layerfile, list):\n                for lfile in layerfile:\n                    if timeField == 'MONTH':\n                        if lfile.find(MONTH) > -1:\n                            layerfile = lfile\n                            # ftype = getFileType(layerfile)\n                            interp = self.interpolations[layername]\n                            temp = quickcut(layerfile, sampledict,\n                                            precise=True, method=interp)\n                            if layername in self.clips:\n                                temp.setData(\n                                    np.clip(temp.getData(),\n                                            self.clips[layername][0],\n                                            self.clips[layername][1]))\n                            self.layerdict[layername] = TempHdf(\n                                temp, os.path.join(self.tempdir,\n                                                   '%s.hdf5' % layername))\n                            del(temp)\n            else:\n                interp = self.interpolations[layername]\n                temp = quickcut(layerfile, sampledict,\n                                precise=True, method=interp)\n                if layername in self.clips:\n                    temp.setData(\n                        np.clip(temp.getData(),\n                                self.clips[layername][0],\n                                self.clips[layername][1]))\n                # Convert unconsolidated sediments to more reasonable coeff\n                if layername == 'rock':\n                    sub1 = temp.getData()\n                    # Change to mixed sed rock coeff\n                    sub1[sub1 <= -3.21] = -1.36\n                    temp.setData(sub1)\n                    self.notes += 'unconsolidated sediment coefficient ' \\\n                                  'changed to -1.36 (weaker) from -3.22 to ' \\\n                                  'better reflect that this ' \\\n                                  'unit is not actually strong\\n'\n                self.layerdict[layername] = TempHdf(\n                    temp, os.path.join(self.tempdir, '%s.hdf5' % layername))\n                td = temp.getGeoDict()\n                if td != sampledict:\n                    raise Exception(\n                        'Geodictionaries of resampled files do not match')\n\n                if layerfile == self.slopefile:\n                    flag = 0\n                    if self.slopemin == 'none' and self.slopemax == 'none':\n                        flag = 1\n                    if self.slopemod is None:\n                        slope1 = temp.getData().astype(float)\n                        slope = 0\n                    else:\n                        try:\n                            slope = temp.getData().astype(float)\n                            slope1 = eval(self.slopemod)\n                        except BaseException:\n                            print('slopemod provided not valid, continuing '\n                                  'without slope thresholds.')\n                            flag = 1\n                    if flag == 0:\n                        nonzero = np.array(\n                            [(slope1 > self.slopemin) &\n                             (slope1 <= self.slopemax)])\n                        self.nonzero = nonzero[0, :, :]\n                        del(slope1)\n                        del(slope)\n                    else:\n                        # Still remove areas where the slope equals exactly\n                        # 0.0 to remove offshore liq areas.\n                        nonzero = np.array([slope1 != 0.0])\n                        self.nonzero = nonzero[0, :, :]\n                        del(slope1)\n                    didslope = True\n                del(temp)\n\n            print('Loading %s layer: %1.1f sec'\n                  % (layername, timer() - start))\n\n        if didslope is False and self.slopefile is not None:\n            # Slope didn't get read in yet\n            temp = quickcut(self.slopefile, sampledict, precise=True,\n                            method='bilinear')\n            flag = 0\n            if self.slopemin == 'none' and self.slopemax == 'none':\n                flag = 1\n            if self.slopemod is None:\n                slope1 = temp.getData().astype(float)\n                slope = 0\n            else:\n                try:\n                    slope = temp.getData().astype(float)\n                    slope1 = eval(self.slopemod)\n                except BaseException:\n                    print('slopemod provided not valid, continuing without '\n                          'slope thresholds')\n                    flag = 1\n            if flag == 0:\n                nonzero = np.array([(slope1 > self.slopemin) &\n                                    (slope1 <= self.slopemax)])\n                self.nonzero = nonzero[0, :, :]\n                del(slope1)\n                del(slope)\n            else:\n                # Still remove areas where the slope equals exactly\n                # 0.0 to remove offshore liq areas.\n                nonzero = np.array([slope1 != 0.0])\n                self.nonzero = nonzero[0, :, :]\n                del(slope1)\n\n        self.nuggets = [str(self.coeffs['b0'])]\n\n        ckeys = sorted(self.terms.keys())\n        for key in ckeys:\n            term = self.terms[key]\n            coeff = self.coeffs[key]\n            self.nuggets.append('(%g * %s)' % (coeff, term))\n\n        self.equation = ' + '.join(self.nuggets)\n        self.geodict = sampledict\n\n    def getEquations(self):\n        \"\"\"\n        Method for LogisticModel class to extract strings defining the\n        equations for the model for median ground motions.\n\n        Returns:\n            equation: the equation for median ground motions,\n\n        \"\"\"\n        return self.equation\n\n    def getGeoDict(self):\n        \"\"\"\n        Returns the geodictionary of the LogisticModel class defining bounds\n        and resolution of model inputs and outputs.\n\n        Returns:\n            geodict: mapio geodict object\n        \"\"\"\n        return self.geodict\n\n    def calculate(self, cleanup=True, rowmax=300, colmax=None):\n        \"\"\"\n        Calculate the model.\n\n        Args:\n            cleanup (bool): If True, delete temporary hdf5 files\n            rowmax (int): Number of rows to compute at once; If None, all rows\n                will be computed at once.\n            colmax (int): Number of columns to compute at once; If None, all\n                columns will be computed at once.\n        Returns:\n            dict: Dictionary containing the model results (and model inputs if\n            saveinputs was set to True). See\n            `the description <https://github.com/usgs/groundfailure#api-for-model-output>`_\n            of the structure.\n        \"\"\"\n        tk = list(self.shakemap.keys())[0]\n        # Figure out what slices to do\n        rowstarts, rowends, colstarts, colends = \\\n            self.shakemap[tk].getSliceDiv(rowmax, colmax)\n\n        # Make empty matrix to fill\n        X = np.empty([self.geodict.ny, self.geodict.nx])\n\n        # Loop through slices, appending output each time\n        for rowstart, rowend, colstart, colend in \\\n                zip(rowstarts, rowends, colstarts, colends):\n            X[rowstart:rowend, colstart:colend] = eval(self.equation)\n\n        P = 1 / (1 + np.exp(-X))\n\n        if 'vs30max' in self.config[self.model].keys():\n            vs30 = self.layerdict['vs30'].getSlice(\n                None, None, None, None, name='vs30')\n            P[vs30 > float(self.config[self.model]['vs30max'])] = 0.0\n\n        if 'minpgv' in self.config[self.model].keys():\n            pgv = self.shakemap['pgv'].getSlice(\n                None, None, None, None, name='pgv')\n            P[pgv < float(self.config[self.model]['minpgv'])] = 0.0\n\n        if 'minpga' in self.config[self.model].keys():\n            pga = self.shakemap['pga'].getSlice(\n                None, None, None, None, name='pga')\n            P[pga < float(self.config[self.model]['minpga'])] = 0.0\n\n        if self.uncert is not None:  # hard code for now\n            if 'Zhu and others (2017)' in self.modelrefs['shortref']:\n                if 'stddev' in self.layerdict.keys():\n                    stdX = self.layerdict['stddev'].getSlice()\n                else:\n                    stdX = float(self.config[self.model]['default_stddev'])\n                varX = stdX**2. + \\\n                    (self.coeffs['b1']**2. *\n                     self.uncert['stdpgv'].getSlice()**2.)\n                varP = (np.exp(-X) / (np.exp(-X) + 1)**2.)**2. * varX\n                if 'coverage' in self.config[self.model].keys():\n                    a = 0.4915\n                    b = 42.4\n                    c = 9.165\n                    # ((2*a*b*c*np.exp(2*c*P))/(b+np.exp(c*P))**3.)**2.*varP\n                    varL = ((2 * a * b * c * np.exp(-c * P)) /\n                            ((1 + b * np.exp(-c * P))**3.))**2. * varP\n                    std1 = np.sqrt(varL)\n                else:\n                    std1 = np.sqrt(varP)\n            elif 'Jessee' in self.modelrefs['shortref']:\n                if 'stddev' in self.layerdict.keys():\n                    stdX = self.layerdict['stddev'].getSlice()\n                else:\n                    stdX = float(self.config[self.model]['default_stddev'])\n                cfs = self.coeffs\n                slp = self.layerdict['slope']\n                std = self.uncert['stdpgv']\n                varX = stdX**2. + ((\n                    cfs['b1'] + cfs['b6'] *\n                    (np.arctan(slp.getSlice()) * 180 / np.pi))**2.\n                    * std.getSlice()**2.)\n                varP = (np.exp(-X) / (np.exp(-X) + 1)**2.)**2. * varX\n                if 'coverage' in self.config[self.model].keys():\n                    a = -7.592\n                    b = 5.237\n                    c = -3.042\n                    d = 4.035\n                    varL = (np.exp(a + b * P + c * P**2. + d * P**3.) *\n                            (b + 2. * P * c + 3. * d * P**2.))**2. * varP\n                    std1 = np.sqrt(varL)\n                else:\n                    std1 = np.sqrt(varP)\n            else:\n                print('cannot do uncertainty for %s model, skipping' %\n                      self.modelrefs['shortref'])\n                self.uncert = None\n                std1 = None\n        else:\n            std1 = None\n\n        # P needs to be converted to areal coverage AFTER dealing with uncert\n        if 'coverage' in self.config[self.model].keys():\n            eqn = self.config[self.model]['coverage']['eqn']\n            P = eval(eqn)\n\n        # Compute quantiles\n        compute_quantiles = False\n        mconf = self.config[self.model]\n        if(('conf_int_probabilities' in mconf) and\n                (std1 is not None)):\n            compute_quantiles = True\n            ci_probabilities = [\n                float(cip) for cip in mconf['conf_int_probabilities']]\n\n        if compute_quantiles:\n            quantile_dict = {}\n            pmax = float(mconf['maxprob'])\n            beta_p = P / pmax * (((pmax * P - P**2) / std1**2) - 1)\n            beta_q = (1 - P / pmax) * (((pmax * P - P**2) / std1**2) - 1)\n            for ci_prob in ci_probabilities:\n                min_quantile = str(np.round(100 * (1.0 - ci_prob) / 2.0, 1))\n                max_quantile = str(np.round(\n                    100 * (1 - ((1.0 - ci_prob)) / 2.0), 1))\n                min_prob, max_prob = get_rangebeta(\n                    beta_p, beta_q, ci_prob, minlim=0, maxlim=pmax)\n                quantile_dict[min_quantile] = min_prob\n                quantile_dict[max_quantile] = max_prob\n\n        if self.slopefile is not None and self.nonzero is not None:\n            # Apply slope min/max limits\n            print('applying slope thresholds')\n            P = P * self.nonzero\n            if std1 is not None:\n                # No uncert for masked values\n                std1[P == 0] = 0.\n                if compute_quantiles:\n                    for q in quantile_dict.values():\n                        q[P == 0] = 0.\n\n        # Stuff into Grid2D object\n        if 'Jessee' in self.modelrefs['shortref']:\n            if 'coverage' not in self.config[self.model].keys():\n                units5 = 'Relative Hazard'\n            else:\n                units5 = 'Proportion of area affected'\n        elif 'Zhu' in self.modelrefs['shortref']:\n            if 'coverage' not in self.config[self.model].keys() and \\\n                    '2017' in self.modelrefs['shortref']:\n                units5 = 'Relative Hazard'\n            else:\n                units5 = 'Proportion of area affected'\n        else:\n            units5 = 'Probability of any occurrence'\n\n        shakedetail = (\n            '%s_ver%s'\n            % (self.shakedict['shakemap_id'],\n               self.shakedict['shakemap_version']))\n        description = {\n            'name': self.modelrefs['shortref'],\n            'longref': self.modelrefs['longref'],\n            'units': units5,\n            'shakemap': shakedetail,\n            'event_id': self.eventdict['event_id'],\n            'parameters': {'slopemin': self.slopemin,\n                           'slopemax': self.slopemax,\n                           'modeltype': self.modeltype,\n                           'notes': self.notes}}\n        if 'vs30max' in self.config[self.model].keys():\n            description['vs30max'] = float(self.config[self.model]['vs30max'])\n        if 'minpgv' in self.config[self.model].keys():\n            description['minpgv'] = float(self.config[self.model]['minpgv'])\n\n        Pgrid = Grid2D(P, self.geodict)\n        if self.trimfile is not None:\n            # Turn all offshore cells to nan\n            Pgrid = trim_ocean(Pgrid, self.trimfile)\n        rdict = collections.OrderedDict()\n        rdict['model'] = {\n            'grid': Pgrid,\n            'label': '%s estimate - %s' % (self.modeltype.capitalize(),\n                                           units5.title()),\n            'type': 'output',\n            'description': description\n        }\n        if self.uncert is not None:\n            Stdgrid = Grid2D(std1, self.geodict)\n            if self.trimfile is not None:\n                Stdgrid = trim_ocean(\n                    Stdgrid, self.trimfile)\n            rdict['std'] = {\n                'grid': Stdgrid,\n                'label': ('%s estimate - %s (std)'\n                          % (self.modeltype.capitalize(),\n                             units5.title())),\n                'type': 'output',\n                'description': description\n            }\n            if compute_quantiles:\n                for quantile, qgrid in quantile_dict.items():\n                    Qgrid = Grid2D(qgrid, self.geodict)\n                    qname = \"quantile%s\" % quantile\n                    rdict[qname] = {\n                        'grid': Qgrid,\n                        'label': (\n                            '%s %sth percentile - %s'\n                            % (self.modeltype.capitalize(), quantile,\n                               units5.title())),\n                        'type': 'output',\n                        'description': description\n                    }\n\n        # This step might swamp memory for higher resolution runs\n        if self.saveinputs is True:\n            for layername, layergrid in list(self.layerdict.items()):\n                units = self.units[layername]\n                if units is None:\n                    units = ''\n                rdict[layername] = {\n                    'grid': Grid2D(\n                        layergrid.getSlice(\n                            None, None, None, None, name=layername),\n                        self.geodict\n                    ),\n                    'label': '%s (%s)' % (layername, units),\n                    'type': 'input',\n                    'description': {\n                        'units': units,\n                        'name': self.shortrefs[layername],\n                        'longref': self.longrefs[layername]\n                    }\n                }\n            for gmused in self.gmused:\n                if 'pga' in gmused:\n                    units = '%g'\n                    getkey = 'pga'\n                elif 'pgv' in gmused:\n                    units = 'cm/s'\n                    getkey = 'pgv'\n                elif 'mmi' in gmused:\n                    units = 'intensity'\n                    getkey = 'mmi'\n                else:\n                    continue\n                    # Layer is derived from several input layers, skip\n                    # outputting this layer\n\n                if getkey in rdict:\n                    continue\n\n                layer = self.shakemap[getkey].getSlice(\n                    None, None, None, None, name=getkey)\n                rdict[getkey] = {\n                    'grid': Grid2D(layer, self.geodict),\n                    'label': '%s (%s)' % (getkey.upper(), units),\n                    'type': 'input',\n                    'description': {\n                        'units': units,\n                        'shakemap': shakedetail\n                    }\n                }\n        if cleanup:\n            shutil.rmtree(self.tempdir)\n        return rdict\n\n\ndef getLogisticModelNames(config):\n    \"\"\"\n    Get the names of the models present in the configobj\n\n    Args:\n        config: configobj object defining the model and its inputs.\n\n    Returns:\n        list: list of model names.\n    \"\"\"\n    names = []\n    lmodel_space = config\n    for key, value in lmodel_space.items():\n        if isinstance(value, str):\n            continue\n        else:  # this is a model\n            names.append(key)\n    return names\n\n\ndef getAllGridFiles(indir):\n    \"\"\"\n    Get list of all gmt or esri (.grd, .bil) files in a directory.\n\n    Args:\n        indir (str): Directory to search.\n    Returns:\n        list: List of file names.\n    \"\"\"\n    # TODO MOVE TO MAPIO\n    tflist = os.listdir(indir)\n    flist = []\n    for tf in tflist:\n        fullfile = os.path.join(indir, tf)\n        ftype = getFileType(fullfile)\n        if ftype in ['gmt', 'esri']:\n            flist.append(fullfile)\n    return flist\n\n\ndef validateCoefficients(cmodel):\n    \"\"\"\n    Ensures coefficients provided in model description are valid and outputs\n    a dictionary of the coefficients.\n\n    Args:\n        cmodel (dict): Sub-dictionary from config for specific model,\n            for example:\n\n            .. code-block:: python\n\n                cmodel = config['test_model']\n\n    Returns:\n        dict: a dictionary of model coefficients named b0, b1, b2...\n    \"\"\"\n    coeffs = {}\n    for key, value in cmodel['coefficients'].items():\n        if re.search('b[0-9]*', key) is None:\n            raise Exception('coefficients must be named b0, b1, ...')\n        coeffs[key] = float(value)\n    if 'b0' not in list(coeffs.keys()):\n        raise Exception('coefficients must include an intercept '\n                        'coefficient named b0.')\n    return coeffs\n\n\ndef validateClips(cmodel, layers, gmused):\n    \"\"\"\n    Ensures coefficients provided in model description are valid and outputs\n    a dictionary of the coefficients.\n\n    Args:\n        cmodel (dict): Sub-dictionary from config for specific model,\n            for example:\n\n            .. code-block:: python\n\n                cmodel = config['test_model']\n        layers: dictionary of layer names\n        gmused (list): List of ground motion parameters used\n\n    Returns:\n        dict: a dictionary of clip values for each layer (if exists)\n    \"\"\"\n    clips = {}\n    if 'clip' in cmodel:\n        for key, value in cmodel['clip'].items():\n            if key not in layers:\n                if key not in gmused:\n                    x1 = [par for par in gmused if key in par]\n                    if len(x1) == 0:\n                        raise Exception(\n                            'Clipping key %s does not match any layers'\n                            % key)\n            clips[key] = (float(value[0]), float(value[1]))\n    return clips\n\n\ndef validateLayers(cmodel):\n    \"\"\"\n    Ensures all input files required to run the model exist and are valid\n    file types. Make sure all layers are available for area of run\n\n    Args:\n        cmodel (dict): Sub-dictionary from config for specific model,\n            for example,\n\n            .. code-block:: python\n\n                cmodel = config['test_model']\n\n    Returns:\n        dict: a dictionary of file names, e.g.\n\n        .. code-block:: python\n\n            {\n                'slope': 'slopefile.bil',\n                'vs30': 'vs30.grd'\n            }\n\n    \"\"\"\n    layers = {}\n    longrefs = {}\n    shortrefs = {}\n    for key in cmodel['layers'].keys():\n        for item, value in cmodel['layers'][key].items():\n            if item == 'file':\n                ftype = getFileType(value)\n                if ftype == 'unknown':\n                    raise Exception('layer file %s is not a valid GMT or '\n                                    'ESRI file.' % value)\n                if ftype == 'dir':\n                    value = getAllGridFiles(value)\n                layers[key] = value\n            elif item == 'shortref':\n                shortrefs[key] = value\n            elif item == 'longref':\n                longrefs[key] = value\n    return layers\n\n\ndef validateTerms(cmodel, coeffs, layers):\n    \"\"\"\n    Reformats model inputs from config file, replacing functions with numpy\n    functions, inserting code for extracting data from each layer (required\n    to run eval in the calculate step), addressing any time variables, and\n    checks that term names match coefficient names.\n\n    Args:\n        cmodel (dict): Sub-dictionary from config for specific model,\n            e.g.\n\n            .. code-block:: python\n\n                cmodel = config['test_model']\n\n        coeffs (dict): Dictionary of model coefficients, e.g.\n\n            .. code-block:: python\n\n                {'b0': 3.5, 'b1': -0.01}\n\n        layers (dict): Dictionary of file names for all input layers, e.g.\n\n            .. code-block:: python\n\n                {'slope': 'slopefile.bil', 'vs30': 'vs30.grd'}\n\n    Returns:\n        tuple: (terms, timeField), where\n            - 'terms' is a dictionary of terms that form the model equation,\n              e.g.\n\n            .. code-block:: python\n\n                {\n                    'b1': \"self.layerdict['friction'].getData()\",\n                    'b2': \"self.layerdict['slope'].getData()/100.\"\n                }\n\n            - 'timeField' indicates the time that is used to know which input\n              file to read in, e.g. for monthly average precipitation, 'MONTH'.\n    \"\"\"\n    # TODO:\n    #    - Return a time field for every term, not just one global one.\n\n    terms = {}\n    timeField = None\n    for key, value in cmodel['terms'].items():\n        if key not in list(coeffs.keys()):\n            raise Exception('Term names must match names of coefficients')\n        # replace log with np.log, make sure variables are all in layers list,\n        # etc.\n        term, rem, tTimeField = checkTerm(value, layers)\n        if tTimeField is not None:\n            timeField = tTimeField\n        if len(rem):\n            msg = ('Term \"%s\" contains the unknown text fragment \"%s\". '\n                   'This may cause the expression to fail.')\n            tpl = (term, rem)\n            raise Exception(msg % tpl)\n        terms[key] = term\n    return terms, timeField\n\n\ndef validateInterpolations(cmodel, layers):\n    \"\"\"Validate logistic model interpolation.\n\n    Args:\n        cmodel (dict): Sub-dictionary from config for specific model.\n        layers (dict): Dictionary of file names for all input layers.\n\n    Returns:\n        dict: Model interpolation methods.\n    \"\"\"\n    interpolations = {}\n    for key, value in cmodel['interpolations'].items():\n        if key not in list(layers.keys()):\n            raise Exception(\n                'Interpolation key %s does not match any names of layers'\n                % key)\n        methods = ['linear', 'nearest', 'cubic', 'bilinear']\n        if value not in methods:\n            raise Exception(\n                'Interpolation method %s not in approved list of methods: %s'\n                % (key, str(methods)))\n        interpolations[key] = value\n    for key in list(layers.keys()):\n        if key not in list(interpolations.keys()):\n            raise Exception(\n                'No interpolation method configured for layer %s' % key)\n    return interpolations\n\n\ndef validateUnits(cmodel):\n    \"\"\"Validate model units.\n\n    Args:\n        cmodel (dict): Sub-dictionary from config for specific model.\n\n    Returns:\n        dict: Model units.\n    \"\"\"\n    units = {}\n    for key in cmodel['layers'].keys():\n        if 'units' in cmodel['layers'][key]:\n            units[key] = cmodel['layers'][key]['units']\n        else:\n            raise Exception('No unit string configured for layer %s' % key)\n    return units\n\n\ndef validateRefs(cmodel):\n    \"\"\"Validate references for models and layers.\n\n    Args:\n        cmodel (dict): Sub-dictionary from config for specific model.\n\n    Returns:\n        tuple: (modelrefs, longrefs, shortrefs) where:\n            * modelrefs: dictionary of citation information for model\n                keys='longref', 'shortref'\n            * shortrefs: dictionary containing short reference for each\n                input layer\n            * longrefs: dictionary containing full references for each\n                input layer\n\n    \"\"\"\n    longrefs = {}\n    shortrefs = {}\n    modelrefs = {}\n    for key in cmodel['layers'].keys():\n        if 'longref' in cmodel['layers'][key]:\n            longrefs[key] = cmodel['layers'][key]['longref']\n        else:\n            print('No longref provided for layer %s' % key)\n            longrefs[key] = 'unknown'\n        if 'shortref' in cmodel['layers'][key]:\n            shortrefs[key] = cmodel['layers'][key]['shortref']\n        else:\n            print('No shortref provided for layer %s' % key)\n            shortrefs[key] = 'unknown'\n    try:\n        modelrefs['longref'] = cmodel['longref']\n    except BaseException:\n        print('No model longref provided')\n        modelrefs['longref'] = 'unknown'\n    try:\n        modelrefs['shortref'] = cmodel['shortref']\n    except BaseException:\n        print('No model shortref provided')\n        modelrefs['shortref'] = 'unknown'\n    return modelrefs, longrefs, shortrefs\n\n\ndef checkTerm(term, layers):\n    \"\"\"Checks terms of equation and replaces text with machine readable\n    operators\n\n    Args:\n        term: term from model configuration file\n        layers: dictionary of file names for all input layers\n\n    Returns:\n        tuple: (term, tterm, timeField) where:\n            * term: dictionary of verified terms for equation with keys\n                corresponding to each layer name\n            * tterm: any unconverted and unverified text that may cause\n                expression to fail\n            * timeField: if any inputs are time dependent, output is unit of\n                time (e.g., 'YEAR'), otherwise, None.\n    \"\"\"\n    # startterm = term\n    # Strip out everything that isn't: 0-9.() operators, +-/* or layer names.\n    # Anything left is an unknown symbol.\n    tterm = term\n    # remove log, sqrt, etc.\n    for op in OPERATORS:\n        tterm = tterm.replace(op, '')\n    # remove ShakeMap variables\n    for sm_term in SM_TERMS:\n        tterm = tterm.replace(sm_term, '')\n    # remove layer names\n    for layer in layers:\n        tterm = tterm.replace(layer, '')\n    # remove arithmetic operators\n    tterm = re.sub(OPERATORPAT, '', tterm)\n    # remove floating point numbers\n    tterm = re.sub(FLOATPAT, '', tterm)\n    # remove integer numbers\n    tterm = re.sub(INTPAT, '', tterm)\n    # remove parentheses\n    tterm = re.sub('[()]*', '', tterm)\n    # remove any blank spaces\n    tterm = tterm.strip()\n    # remove commas\n    tterm = tterm.strip(',')\n    # anything left *might* cause an error\n    for op in OPERATORS:\n        if term.find(op) > -1:\n            term = term.replace(op, 'np.' + op)\n\n    for sm_term in SM_GRID_TERMS:\n        term = term.replace(\n            sm_term,\n            \"self.shakemap['%s'].getSlice(rowstart, rowend, \"\n            \"colstart, colend, name='%s')\" % (sm_term, sm_term))\n\n    # replace the macro MW with the magnitude value from the shakemap\n    term = term.replace('MW', \"self.eventdict['magnitude']\")\n\n    # term.replace('YEAR',\"self.shakemap.getEventDict()['event_time'].year\")\n    # hasTime = False\n    timeField = None\n    for unit in ['YEAR', 'MONTH', 'DAY', 'HOUR']:\n        if term.find(unit) > -1:\n            term = term.replace(unit, '')\n            timeField = unit\n\n    for layer in layers:\n        if layer == 'friction':\n            term = term.replace(\n                layer,\n                \"np.nan_to_num(self.layerdict['%s'].getSlice(rowstart, \"\n                \"rowend, colstart, colend, name='%s'))\" % (layer, layer))\n        else:\n            term = term.replace(\n                layer,\n                \"self.layerdict['%s'].getSlice(rowstart, rowend, colstart, \"\n                \"colend, name='%s')\" % (layer, layer))\n    return term, tterm, timeField\n", "meta": {"hexsha": "ce5704b62187dd04161c35dc85f7dacbd5ca5874", "size": 42305, "ext": "py", "lang": "Python", "max_stars_repo_path": "gfail/logisticmodel.py", "max_stars_repo_name": "mhearne-usgs/groundfailure", "max_stars_repo_head_hexsha": "e8a07e25e7006a50fd2a59b46e21e1e28f3a24b5", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2017-01-21T02:33:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T18:42:38.000Z", "max_issues_repo_path": "gfail/logisticmodel.py", "max_issues_repo_name": "mhearne-usgs/groundfailure", "max_issues_repo_head_hexsha": "e8a07e25e7006a50fd2a59b46e21e1e28f3a24b5", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 261, "max_issues_repo_issues_event_min_datetime": "2016-07-14T19:47:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T22:16:44.000Z", "max_forks_repo_path": "gfail/logisticmodel.py", "max_forks_repo_name": "mhearne-usgs/groundfailure", "max_forks_repo_head_hexsha": "e8a07e25e7006a50fd2a59b46e21e1e28f3a24b5", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2016-01-11T19:49:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-16T23:09:34.000Z", "avg_line_length": 38.5994525547, "max_line_length": 91, "alphanum_fraction": 0.5088996573, "include": true, "reason": "import numpy", "num_tokens": 9517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.16150978763848695}}
{"text": "import logging\n\nimport numpy as np\n\nfrom renormalizer.mps import MpDm, Mpo\nfrom renormalizer.mps.tdh import unitary_propagation\nfrom renormalizer.utils import TdMpsJob, Quantity, EvolveConfig\nfrom renormalizer.property import Property\n\nlogger = logging.getLogger(__name__)\n\n\nclass ThermalProp(TdMpsJob):\n    r\"\"\"\n    Thermally Propagate initial matrix product density operator (:class:`~renormalizer.mps.MpDm`) in imaginary time.\n\n    Args:\n        init_mpdm (:class:`~renormalizer.mps.MpDm`): the initial density matrix to be propagated. Usually identity.\n        h_mpo (:class:`~renormalizer.mps.Mpo`): the system Hamiltonian.\n        exact (bool): whether propagate assuming Hamiltonian is local\n            :math:`\\hat H = \\sum_i \\hat H_i = \\sum_{in} \\omega_{in} b^\\dagger_{in} b_{in}` and\n            exact propagation is possible through :math:`e^{xH} = e^{xh_1}e^{xh_2} \\cdots e^{xh_n}`.\n            If set to ``True``, properties such as occupations are not calculated during\n            time evolution for better efficiency.\n        space (str): the space of exact propagation. Possible options are ``\"GS\"`` or ``\"EX\"``.\n            If set to ``\"GS\"``, then the exact propagation is performed in zero exciton space.\n            If set to ``\"EX\"``, then the exact propagation is performed in one exciton space,\n            i.e. the vibrations are regarded as displaced oscillators.\n        evolve_config (:class:`~renormalizer.utils.EvolveConfig`): config when evolving the MpDm in imaginary time.\n        dump_mps (bool): if dump mps when dumping\n        dump_dir (str): the directory for logging and numerical result output.\n        job_name (str): the name of the calculation job which determines the file name of the logging and numerical result output.\n        properties (:class:`~renormalizer.property.Property`) calculate other properties with interface in Property\n    \"\"\"\n    def __init__(\n        self,\n        init_mpdm: MpDm,\n        h_mpo: Mpo,\n        exact: bool = False,\n        space: str = \"GS\",\n        evolve_config: EvolveConfig = None,\n        dump_mps: bool = False, \n        dump_dir: str = None,\n        job_name: str = None,\n        properties: Property = None,\n        auto_expand: bool = True,\n    ):\n        self.init_mpdm: MpDm = init_mpdm.canonicalise()\n        self.h_mpo = h_mpo\n        self.exact = exact\n        assert space in [\"GS\", \"EX\"]\n        self.space = space\n        self.energies = []\n        self._e_occupations_array = []\n        self._ph_occupations_array = []\n        self._vn_entropy_array = []\n        self.properties = properties\n        self.auto_expand = auto_expand\n\n        super().__init__(evolve_config=evolve_config, dump_mps=dump_mps, dump_dir=dump_dir,\n                job_name=job_name)\n\n    def init_mps(self):\n        self.init_mpdm.evolve_config = self.evolve_config\n        if self.evolve_config.is_tdvp and self.auto_expand:\n            self.init_mpdm = self.init_mpdm.expand_bond_dimension(self.h_mpo)\n        return self.init_mpdm\n\n    def process_mps(self, mps):\n        if self.exact:\n            # skip the fuss for efficiency\n            return\n        new_energy = mps.expectation(self.h_mpo)\n        self.energies.append(new_energy)\n        for attr_str in [\"e_occupations\", \"ph_occupations\"]:\n            attr = getattr(mps, attr_str)\n            logger.info(f\"{attr_str}: {attr}\")\n            self_array = getattr(self, f\"_{attr_str}_array\")\n            self_array.append(attr)\n        vn_entropy = mps.calc_vn_entropy()\n        self._vn_entropy_array.append(vn_entropy)\n        logger.info(f\"vn entropy: {vn_entropy}\")\n        logger.info(\n            f\"Energy: {new_energy}, total electron: {self._e_occupations_array[-1].sum()}\"\n        )\n        \n        # calculate other properties defined in Property\n        if self.properties is not None:\n            self.properties.calc_properties(mps)\n\n    def evolve_exact(self, old_mpdm, evolve_dt):\n        MPOprop, HAM, Etot = old_mpdm.hybrid_exact_propagator(\n            self.h_mpo, evolve_dt.imag, space=self.space\n        )\n        new_mpdm = MPOprop.apply(old_mpdm)\n        unitary_propagation(new_mpdm.tdh_wfns, HAM, Etot, evolve_dt)\n        # partition function can't be obtained. It's not practical anyway.\n        # The function is too large to be fit into float64 even float128\n        new_mpdm.canonicalise(normalize=True)\n        new_mpdm.normalize(1.0)\n        return new_mpdm\n\n    def evolve_prop(self, old_mpdm, evolve_dt):\n        h_mpo = Mpo(self.h_mpo.mol_list, offset=Quantity(self.energies[-1]))\n        return old_mpdm.evolve(h_mpo, evolve_dt)\n\n    def evolve_single_step(self, evolve_dt):\n        old_mpdm = self.latest_mps\n        if self.exact:\n            new_mpdm = self.evolve_exact(old_mpdm, evolve_dt)\n        else:\n            new_mpdm = self.evolve_prop(old_mpdm, evolve_dt)\n        return new_mpdm\n\n    def evolve(self, evolve_dt=None, nsteps=None, evolve_time=None):\n        if evolve_dt is not None:\n            assert np.iscomplex(evolve_dt) and evolve_dt.imag < 0\n        if evolve_time is not None:\n            assert np.iscomplex(evolve_time) and evolve_time.imag < 0\n        super().evolve(evolve_dt, nsteps, evolve_time)\n\n    @property\n    def e_occupations_array(self):\n        return np.array(self._e_occupations_array)\n\n    @property\n    def ph_occupations_array(self):\n        return np.array(self._ph_occupations_array)\n\n    @property\n    def vn_entropy_array(self):\n        return np.array(self._vn_entropy_array)\n\n    def get_dump_dict(self):\n        dump_dict = dict()\n        dump_dict[\"time series\"] = [-t.imag for t in self.evolve_times]\n        dump_dict[\"energies\"] = self.energies\n        dump_dict[\"electron occupations array\"] = self.e_occupations_array.tolist()\n        dump_dict[\"phonon occupations array\"] = self.ph_occupations_array.tolist()\n        dump_dict[\"vn entropy array\"] = self.vn_entropy_array.tolist()\n        \n        if self.properties is not None:\n            for prop_str in self.properties.prop_res.keys():\n                dump_dict[prop_str] = self.properties.prop_res[prop_str]\n\n        return dump_dict\n\n\ndef load_thermal_state(mol_list, path: str):\n    \"\"\"\n    Load thermal propagated state from disk. Return None if the file is not found.\n\n    Args:\n        mol_list (:class:`MolList`): system information\n        path (str): the path to load thermal state from. Should be an `npz` file.\n    Returns: Loaded MpDm\n    \"\"\"\n    try:\n        logger.info(f\"Try load from {path}\")\n        mpdm = MpDm.load(mol_list, path)\n        logger.info(f\"Init mpdm loaded: {mpdm}\")\n    except FileNotFoundError:\n        logger.info(f\"No file found in {path}\")\n        mpdm = None\n\n    return mpdm\n", "meta": {"hexsha": "f227d45f85644b53211399551c1320a4e515e9e6", "size": 6696, "ext": "py", "lang": "Python", "max_stars_repo_path": "renormalizer/mps/thermalprop.py", "max_stars_repo_name": "liwt31/Renormalizer", "max_stars_repo_head_hexsha": "123a9d53f4f5f32c0088c255475f0ee60d02c745", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "renormalizer/mps/thermalprop.py", "max_issues_repo_name": "liwt31/Renormalizer", "max_issues_repo_head_hexsha": "123a9d53f4f5f32c0088c255475f0ee60d02c745", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "renormalizer/mps/thermalprop.py", "max_forks_repo_name": "liwt31/Renormalizer", "max_forks_repo_head_hexsha": "123a9d53f4f5f32c0088c255475f0ee60d02c745", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0958083832, "max_line_length": 130, "alphanum_fraction": 0.6530764636, "include": true, "reason": "import numpy", "num_tokens": 1644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3040416623541847, "lm_q1q2_score": 0.16150978093868165}}
{"text": "# spin_system.py\n# Simon Hulse\n# simon.hulse@chem.ox.ac.uk\n# Last Edited: Fri 13 May 2022 10:55:09 BST\n\nr\"\"\"This module provides the :py:class:`SpinSystem` class, allowing specification\nof a specific spin system according to the nuclear idenitites, isotropic chemical\nshifts, and J-couplings of each spin, along with the temperature and magnetic\nfield they are subjected to.\n\nThe ``SpinSystem`` class is used by all experiment simulation functions to derive\nthe equilibrium operator and Hamiltonians required.\n\"\"\"\n\nfrom __future__ import annotations\nimport random\nfrom typing import Dict, Iterable, Optional, Tuple, Union\n\nimport networkx as nx\nimport numpy as np\n\nfrom nmr_sims.nuclei import Nucleus\nfrom nmr_sims._operators import CartesianBasis, Operator\nfrom nmr_sims import _sanity\n\n\ndef triangle(n: int) -> int:\n    return int(0.5 * n * (n - 1))\n\n\nclass SpinSystem(CartesianBasis):\n    \"\"\"Object representing a particular spin system.\n\n    This represents an ensemble of many identical spin systems subject to a\n    specified temperature and magnetic field strength.\n    \"\"\"\n    kB = 1.380649e-23\n    hbar = 1.054571817e-34\n\n    def __init__(\n        self,\n        spins: Dict[int, Dict],\n        default_nucleus: Union[Nucleus, str] = \"1H\",\n        field: Union[int, float, str] = \"500MHz\",\n        temperature: Union[int, float, str] = \"298K\",\n    ) -> None:\n        r\"\"\"Create an instance ``SpinSystem``.\n\n        Parameters\n        ----------\n\n        spins\n            A dictionary with information on each spin that makes up the system.\n            Below is an example of a valid format. This specifies a three proton\n            (AMX) system, with the following parameters:\n\n            .. math::\n\n                \\delta_1 = 5.4\\ \\mathrm{ppm}\n\n                \\delta_2 = 2.8\\ \\mathrm{ppm}\n\n                \\delta_3 = 0.5\\ \\mathrm{ppm}\n\n                J_{12} = 4.6\\ \\mathrm{Hz}\n\n                J_{13} = 7.4\\ \\mathrm{Hz}\n\n                J_{23} = 2.7\\ \\mathrm{Hz}\n\n            .. code:: python3\n\n                spins = {\n                    1: {\n                        \"shift\": 5.4,\n                        \"couplings\": {\n                            2: 4.6,\n                            3: 7.4,\n                        },\n                    },\n                    2: {\n                        \"shift\": 2.8,\n                        \"couplings\": {\n                            3: 2.7,\n                        },\n                    },\n                    3: {\n                        \"shift\": 0.5,\n                    },\n                }\n\n            Note that there is no need to repeat coupling information. As the\n            coupling between spins 1 and 2 has been specified within the entry\n            for spin 1, there is no need to repeat this for spin 2. Similary,\n            spin 3 has been given no explicit coupling information as this has\n            already been provided in the specification of spins 1 and 2.\n\n            Each entry in the ``spins`` dictionary should have an ``int`` as a key\n            and a ``dict`` as its value. Within the each ``dict``, the following\n            key-value pairs are permitted:\n\n            * ``\"shift\"`` (necessary) - The isotropic chemical shift of the spin\n              in ppm.\n            * ``\"couplings\"`` (optional) - The scalar couplings between the spin\n              and its coupling partners. This should be denoted by a ``dict`` with\n              an ``int`` key specifying the coupling partner, and a ``float`` value,\n              specifying the J-coupling in Hz.\n            * ``\"nucleus\"`` (optional) - The identity of nucelus giving rise to\n              the spin. If not specified, then ``default_nucleus`` will be used.\n              Can be either an instance of :py:class:`nmr_sims.nuclei.Nucleus`\n              of a string corresponding to one of the pre-defined nuclei.\n\n        default_nucleus\n            The nucleus identity of any spin in the ``spins`` dictionary that is not\n            given an explicit ``\"nucleus\"`` key. By default, all unspecified nuclei\n            will correspond to proton (¹H).\n\n        field\n            The magnetic field strength. The following inputs are valid:\n\n            * A positive number (``int`` or ``float``). The field will be taken to be\n              in Telsa.\n            * A ``str`` satisfying the regex ``r\"\\d+T\"``. Again, the field will be\n              taken to be in Tesla\n            * A ``str`` satisfying the regex ``r\"\\d+MHz\"``. This corresponds to the\n              field which induces the specified Larmor frequency for proton.\n\n            By default, this is set as ``\"500MHz\"``, correponding to approximately\n            11.74T.\n\n        temperature\n            The temperature. The following inputs are valid:\n\n            * A positive number (``int`` or ``float``). The field will be taken to be\n              in Kelvin.\n            * A ``str`` satisfying the regex ``r\"\\d+K\"``. Again, the field will be\n              taken to be in Kelvin.\n            * A ``str`` satisfying the regex ``r\"-?\\d+C\"``. The temperature will be\n              taken to be in Celcius.\n\n        .. warning::\n\n            **Current bug**\n\n            Negative Celcius specifications (``\"-\\d+C\"``) are not supported currently,\n            and will raise an error if given. PLease manually convert to Kelvin.\n        \"\"\"\n        self.__couplings_on = True\n        self.temperature = _sanity.process_temperature(temperature)\n        self.field = _sanity.process_field(field)\n        self.spin_dict = _sanity.process_spins(spins, default_nucleus)\n        super().__init__(\n            [(spin.nucleus.multiplicity - 1) / 2 for spin in self.spin_dict.values()]\n        )\n        if not all([I == 0.5 for I in self.spins]):\n            raise ValueError(\"Only spin-1/2 nuclei are supported currently!\")\n\n    def exclude_couplings(self) -> None:\n        \"\"\"Spin system's couplings will be turned off.\n\n        Can be reversed with :py:meth:`include_couplings`.\n        \"\"\"\n        self.__couplings_on = False\n\n    def include_couplings(self) -> None:\n        \"\"\"Spin system's couplings will be turned on.\n\n        Can be reversed with :py:meth:`exclude_couplings`.\n        \"\"\"\n        self.__couplings_on = True\n\n    @classmethod\n    def new_random(\n        cls,\n        nspins: Union[int, Tuple[int, int]] = 3,\n        ncouplings: Optional[int] = None,\n        max_couplings: Optional[int] = 3,\n        shifts_range: Tuple[float, float] = (0.0, 10.0),\n        couplings_range: Tuple[float, float] = (3.0, 15.0),\n        field: Union[int, float, str] = \"500MHz\",\n        temperature: Union[int, float, str] = \"298K\",\n    ) -> SpinSystem:\n        \"\"\"Create a new instance with random chemical shifts and offsets.\n\n        .. note::\n\n            Only homonucler ¹H spin systems are available currently.\n\n        Parameters\n        ----------\n        nspins\n            The number of spins the system should comprise.\n\n        ncouplings\n            The total number of couplings featured in the spin system. This must be\n            a value satisfying ``ncouplings <= int(0.5 * (nspins * (nspins - 1)))``\n            There is a possibility that the final spin system will have fewer couplings\n            than those stated if the random network of couplings does not satisfy\n            the constraint placed by ``max_couplings``.\n\n        max_couplings\n            The largest possible number of coupling interactions any particular spin\n            may have.\n\n        shifts_range\n            The smallest and greatest values of chemical shift any particular spin\n            may have.\n\n        couplings_range\n            The smallest and greatest values of scalar coupling any particular\n            interaction may have.\n\n        field\n            See :py:meth:`__init__`\n\n        temperature\n            See :py:meth:`__init__`\n        \"\"\"\n        if not (isinstance(nspins, int) and nspins >= 1):\n            raise ValueError(\"`nspins` is invalid\")\n\n        if not (isinstance(ncouplings, int) and 0 <= ncouplings <= triangle(nspins)):\n            raise ValueError(\n                \"`ncouplings` should be a positive int no greater than \"\n                f\"{triangle(nspins)}.\"\n            )\n\n        if max_couplings is None:\n            # No chance of this being exceeded.\n            max_couplings = nspins\n        elif isinstance(max_couplings, int) and max_couplings >= 1:\n            pass\n        else:\n            raise ValueError(\"`max_couplings` should be a positive int or None.\")\n\n        valid_range = lambda obj: (\n            isinstance(shifts_range, (list, tuple)) and\n            len(shifts_range) == 2 and\n            all([isinstance(x, float) for x in shifts_range])\n        )\n        if valid_range(shifts_range):\n            shifts_range = (min(shifts_range), max(shifts_range))\n        else:\n            raise ValueError(\"`shifts_range` is invalid.\")\n\n        if valid_range(couplings_range):\n            couplings_range = (min(couplings_range), max(couplings_range))\n        else:\n            raise ValueError(\"`couplings_range` is invalid.\")\n\n        graph = nx.gnm_random_graph(nspins, ncouplings)\n        overconnected_nodes = [\n            node for node, degree in graph.degree if degree > max_couplings\n        ]\n        for node in overconnected_nodes:\n            while graph.degree[node] > max_couplings:\n                graph.remove_edge(node, random.choice([x for x in graph[node]]))\n\n        spin_system = {}\n        for i in range(nspins):\n            spin_system[i + 1] = {\n                \"shift\": np.round(\n                    np.random.uniform(shifts_range[0], shifts_range[1]),\n                    decimals=3,\n                )\n            }\n            spin_system[i + 1][\"couplings\"] = {}\n\n        for i, j in graph.edges:\n            spin_system[i + 1][\"couplings\"][j + 1] = np.round(\n                np.random.uniform(couplings_range[0], couplings_range[1]),\n                decimals=3,\n            )\n\n        return cls(spin_system)\n\n    @property\n    def inverse_temperature(self) -> float:\n        r\"\"\"Return the inverse temperature for the system.\n\n        Given by :math:`\\beta = \\hbar / k_{\\mathrm{B}} T`.\n        \"\"\"\n        return self.hbar / (self.kB * self.temperature)\n\n    @property\n    def boltzmann_factor(self) -> Iterable[float]:\n        r\"\"\"Return the Boltzmann factor for each spin in the spin system.\n\n        This factor is given by :math:`2 \\pi \\beta \\gamma B_0`. See\n        :py:meth:`inverse_temperature` for the definition of :math:`\\beta`.\n        \"\"\"\n        return [\n            2 * np.pi * self.inverse_temperature * spin.nucleus.gamma * self.field\n            for spin in self.spin_dict.values()\n        ]\n\n    @property\n    def basic_frequencies(self) -> np.ndarray:\n        r\"\"\"Return the baisc (laboratory frame) frequencies of each spin.\n\n        Given by :math:`-\\gamma B_0 \\left(1 + \\delta \\times 10^{-6}\\right)`\n        \"\"\"\n        return np.array([\n            -spin.nucleus.gamma * self.field * (1 + (1e-6 * spin.shift))\n            for spin in self.spin_dict.values()\n        ])\n\n    @property\n    def rotframe_frequencies(self) -> np.ndarray:\n        r\"\"\"Return the rotating frame frequencies for each spin.\n\n        Given by :math:`-\\gamma B_0 \\left(\\delta \\times 10^{-6}\\right)`\n        \"\"\"\n        return np.array([\n            -spin.nucleus.gamma * self.field * (1e-6 * spin.shift)\n            for spin in self.spin_dict.values()\n        ])\n\n    @property\n    def couplings(self) -> np.ndarray:\n        couplings = np.zeros((self.nspins, self.nspins), dtype=\"float64\")\n\n        if self.__couplings_on:\n            for i, spin in self.spin_dict.items():\n                for j, coupling in spin.couplings.items():\n                    if i < j:\n                        couplings[i - 1, j - 1] = coupling\n        else:\n            couplings\n\n        return couplings + couplings.T\n\n    def pulse(\n        self, nucleus: str, phase: float = 0., angle: float = np.pi / 2\n    ) -> Operator:\n        \"\"\"Return the operator for a pulse targeting a specific nucleus, with\n        specified phase and flip angle.\n\n        Parameters\n        ----------\n\n        nucleus\n            The identity of the nucleus to be targeted. Should match the\n            ``nucleus.name``.\n\n        phase\n            Desired phase of the pulse in radians.\n\n        Angle\n            Desired flip angle in radians.\n        \"\"\"\n        operator = self.zero\n        for i, spin in self.spin_dict.items():\n            if spin.nucleus.name == nucleus:\n                operator += (\n                    np.cos(phase) * self.get(f\"{i}x\") +\n                    np.sin(phase) * self.get(f\"{i}y\")\n                )\n        return operator.rotation_operator(angle)\n\n    @property\n    def equilibrium_operator(self) -> Operator:\n        r\"\"\"Return the equilibrium operator of the spin system.\n\n        Given by:\n\n        .. math::\n\n            \\hat{\\rho}_{\\mathrm{eq}} =\n            \\frac{1}{N} \\left(\\hat{E} + 2 \\pi \\beta B_0 \\sum_{i=1}^N\n            \\gamma_i \\hat{I}_{iz}\\right)\n\n        Where :math:`N` is the number of spins, and :math:`\\hat{E}` is the identity\n        operator.\n        \"\"\"\n        return (1 / self.nspins) * (\n            self.identity + sum(\n                [b * self.get(f\"{i}z\") for i, b in\n                 enumerate(self.boltzmann_factor, start=1)],\n                self.zero,\n            )\n        )\n\n    def hamiltonian(self, offsets: Union[dict, None] = None, decouple=None) -> Operator:\n        r\"\"\"Return the Hamiltonian for the spin system.\n\n        Given by:\n\n        .. math::\n\n            \\hat{H} = -B_0 \\sum_{i=1}^N (\\delta_i \\times 10^{-6}) \\gamma_i\n            \\hat{I}_{iz}\n            + 2 \\pi \\sum_{i=1}^{N-1} \\sum_{j=i+1}^N\n            J_{ij} \\left(\n            \\hat{I}_{ix} \\hat{I}_{jx} +\n            \\hat{I}_{iy} \\hat{I}_{jy} +\n            \\hat{I}_{iz} \\hat{I}_{jz} \\right)\n\n        Parameters\n        ----------\n\n        offsets\n            Specification of transmitter offsets for given nuclei, in units of Hz.\n            As an example, the argument ``{\"1H\": 5000}`` would inorporate a\n            transmtter offset of 5000Hz for proton.\n        \"\"\"\n        H = self.zero\n        frequencies = self.rotframe_frequencies\n        couplings = self.couplings\n        isotopes = [self.spin_dict[i].nucleus.name for i in range(1, self.nspins + 1)]\n        for i, (isotope1, freq) in enumerate(zip(isotopes, frequencies), start=1):\n            H += freq * self.get(f\"{i}z\")\n            if i == self.nspins:\n                break\n            for j, (isotope2, coupling) in enumerate(zip(\n                isotopes[i:],\n                couplings[i:, i - 1]\n            ), start=i + 1):\n                if isotope1 == isotope2:\n                    H += np.pi * coupling * (\n                        self.get(f\"{i}x{j}x\") +\n                        self.get(f\"{i}y{j}y\") +\n                        self.get(f\"{i}z{j}z\")\n                    )\n                elif decouple not in (isotope1, isotope2):\n                    H += np.pi * coupling * self.get(f\"{i}z{j}z\")\n                # Decouple: don't include scalar coupling\n\n        if offsets is not None:\n            for nuc, off in offsets.items():\n                H += 2 * np.pi * off * sum(\n                    [self.get(f\"{i}z\")\n                     for i, spin in self.spin_dict.items()\n                     if spin.nucleus.name == nuc],\n                    self.zero\n                )\n\n        return H\n\n    def _get_sum(self, coord: str, nucleus: str) -> Operator:\n        if nucleus is None:\n            labels = list(range(1, self.nspins + 1))\n        else:\n            labels = [i for i, spin in self.spin_dict.items()\n                      if spin.nucleus.name == nucleus]\n\n        return sum([self.get(f\"{i}{coord}\") for i in labels], self.zero)\n\n    def Ix(self, nucleus: Union[str, None] = None) -> Operator:\n        r\"\"\"Return the :math:`\\hat{I}_x` operator correpsonding to the system,\n        with the option of specifying the nucelus to target.\n\n        For a given nucleus :math:`n`, this is given by:\n\n        .. math::\n\n            \\hat{I}_{x, n} = \\sum_{i} \\hat{I}_{ix},\n\n        :math:`\\forall i \\in \\{1, \\cdots, N\\}` satisfying the requirement that\n        spin :math:`i` corresponds to nucelus :math:`n`.\n\n        Parameters\n        ----------\n\n        nucleus\n            The identity of the nucelus to target. If ``None``, no constraint will\n            be put on the nucleus.\n        \"\"\"\n        return self._get_sum(\"x\", nucleus)\n\n    def Iy(self, nucleus: Union[str, None] = None) -> Operator:\n        r\"\"\"Return the :math:`\\hat{I}_y` operator correpsonding to the system,\n        with the option of specifying the nucelus to target.\n\n        For a given nucleus :math:`n`, this is given by:\n\n        .. math::\n\n            \\hat{I}_{y, n} = \\sum_{i} \\hat{I}_{iy},\n\n        :math:`\\forall i \\in \\{1, \\cdots, N\\}` satisfying the requirement that\n        spin :math:`i` corresponds to nucelus :math:`n`.\n\n        Parameters\n        ----------\n\n        nucleus\n            The identity of the nucelus to target. If ``None``, no constraint will\n            be put on the nucleus.\n        \"\"\"\n        return self._get_sum(\"y\", nucleus)\n\n    def Iz(self, nucleus: Union[str, None] = None) -> Operator:\n        r\"\"\"Return the :math:`\\hat{I}_z` operator correpsonding to the system,\n        with the option of specifying the nucelus to target.\n\n        For a given nucleus :math:`n`, this is given by:\n\n        .. math::\n\n            \\hat{I}_{z, n} = \\sum_{i} \\hat{I}_{iz},\n\n        :math:`\\forall i \\in \\{1, \\cdots, N\\}` satisfying the requirement that\n        spin :math:`i` corresponds to nucelus :math:`n`.\n\n        Parameters\n        ----------\n\n        nucleus\n            The identity of the nucelus to target. If ``None``, no constraint will\n            be put on the nucleus.\n        \"\"\"\n        return self._get_sum(\"z\", nucleus)\n\n\nif __name__ == \"__main__\":\n    ss = SpinSystem.new_random(nspins=6, ncouplings=6, max_couplings=2)\n    from nmr_sims.experiments.pa import PulseAcquireSimulation\n\n    sim = PulseAcquireSimulation(ss, 4096, \"10ppm\", \"5ppm\")\n    sim.simulate()\n    sh, sp, lab = sim.spectrum(zf_factor=4)\n    import matplotlib as mpl\n    mpl.use(\"tkAgg\")\n    import matplotlib.pyplot as plt\n    fig = plt.figure()\n    ax = fig.add_subplot()\n    ax.plot(sh, sp)\n    ax.set_xlim(reversed(ax.get_xlim()))\n    ax.set_xlabel(lab)\n    plt.show()\n", "meta": {"hexsha": "3608dd8d86a5eccb3d1fefad2cf72b2f8be315de", "size": 18441, "ext": "py", "lang": "Python", "max_stars_repo_path": "nmr_sims/spin_system.py", "max_stars_repo_name": "foroozandehgroup/nmr_sims", "max_stars_repo_head_hexsha": "a035bdf75f467f88e96f1ef90c26b9dd3b5c2884", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nmr_sims/spin_system.py", "max_issues_repo_name": "foroozandehgroup/nmr_sims", "max_issues_repo_head_hexsha": "a035bdf75f467f88e96f1ef90c26b9dd3b5c2884", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nmr_sims/spin_system.py", "max_forks_repo_name": "foroozandehgroup/nmr_sims", "max_forks_repo_head_hexsha": "a035bdf75f467f88e96f1ef90c26b9dd3b5c2884", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6635338346, "max_line_length": 88, "alphanum_fraction": 0.5494279052, "include": true, "reason": "import numpy,import networkx", "num_tokens": 4524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.29746995506106744, "lm_q1q2_score": 0.16148552084970066}}
{"text": "\"\"\"\n\n                  extra classes used in findR\n\n                  frame    -> store a frame\n                  species  -> store a species in a frame (or just as such)\n                  fcompare -> frame comparer\n                  revent   -> reaction event\n\n##################### NOTES /TO BE IMPLEMENTED\n\nadd xyz coord reference to frame object for mol object generation\n-> not completely implemented\n\nadd pmol also to species\nmove molg generation to the frame and species objects\n\n\"\"\"\n\nimport numpy as np\nimport os\n\nimport molsys\nfrom molsys.util import rotations\n\nfrom graph_tool import Graph, GraphView\nimport graph_tool.topology as gtt\nimport graph_tool.util as gtu\nimport graph_tool.draw as gtd\n\nimport uuid\nimport graph_tool\n\n#####################  FRAME CLASS ########################################################################################\n\nclass frame:\n    \"\"\"container to store info on a frame\n\n    the main attributes are:\n    - fid: frame id \n    - xyz:     numpy array (N,3) with the xyz coords of all atoms in this frame\n    - elems:   list of elems\n    - bondtab: bond table (M,2) with m bonds\n    - bondord: bon orders (M)\n    \"\"\"\n\n    def __init__(self, fid, xyz, mol, bondtab, bondord, cutoff=0.5, min_atom=6, min_elems={\"c\":2}):\n        self.fid = fid\n        self.xyz = xyz\n        self.mol = mol\n        self.natoms = self.mol.get_natoms()\n        self.bondord = bondord\n        self.bondtab = bondtab\n        self.maxbond = len(bondord)\n        self.specs = {}\n        # generate the molecular graph\n        molg = Graph(directed=False)\n        molg.add_vertex(n=self.natoms)\n        molg.vp.aid  = molg.new_vertex_property(\"int\")\n        molg.vp.aid.a[:] = np.arange(self.natoms, dtype=\"int32\")\n        molg.vp.filt = molg.new_vertex_property(\"bool\")\n        molg.vp.mid  = molg.new_vertex_property(\"int\")\n        molg.ep.bord = molg.new_edge_property(\"float\")\n        molg.ep.filt = molg.new_edge_property(\"bool\")\n        for j in range(self.maxbond):\n            o = bondord[j]\n            # invalid entries are marked with a bondord = -1.0\n            if o < 0.0:\n                break\n            e = bondtab[j]-1\n            # TO BE REMOVED ... this is a legacy check for the old incorrect mfp5 files \n            if (e[0] < 0 or e[0] >= self.natoms or e[1] < 0 or e[1] >= self.natoms):\n                break\n            # END TO BE REMOVED\n            newb = molg.add_edge(e[0], e[1])\n            isbond = o > cutoff\n            molg.ep.bord[newb] = o\n            molg.ep.filt[newb] = isbond \n        # apply edge filter\n        molg.set_edge_filter(molg.ep.filt)\n        self.molg = molg\n        self.mid, hist = gtt.label_components(molg, vprop=molg.vp.mid)\n        nspecies_all = len(hist)\n        nspecies = []\n        # collect number of critical elements in the species\n        elem_spec = {}\n        for e in min_elems.keys():\n            spec_ecount = np.zeros(nspecies_all, dtype=\"int32\")\n            for i in range(self.natoms):\n                if self.mol.elems[i] == e:\n                    spec_ecount[self.mid[i]] += 1\n            elem_spec[e] = spec_ecount\n        for i in range(nspecies_all):\n            track = True\n            if hist[i] < min_atom:\n                track = False\n            for e in min_elems.keys():\n                if elem_spec[e][i] < min_elems[e]:\n                    track = False\n            if track:\n                nspecies.append(i)\n        # append the species\n        for s in nspecies:\n            self.add_species(s)\n        return\n\n    def add_species(self, mid, tracked=True):\n        # make all frame species (observed) with a local graph representation\n        self.specs[mid] = species(self.fid, mid, self.molg, make_graph=True, tracked=tracked)\n        return\n\n    def make_species(self, mid):\n        # return a species object (without a local graph)\n        return species(self.fid, mid, self.molg, make_graph=False, tracked=False)\n\n\n    @property\n    def nspecies(self):\n        return len(self.specs)\n\n    def plot(self, selection=False):\n        if selection:\n            print (\"plotting species %s of frame %d\" % (str(selection), self.fid))\n            for s in selection:\n                gfname = \"frame_%d_species_%d.png\" % (self.fid, s)\n                g = self.specs[s].graph\n                pos = gtd.arf_layout(g, max_iter=0)\n                gtd.graph_draw(g, pos=pos, vertex_text=g.vp.aid, vertex_font_size=12, vertex_size=8, \\\n                                           edge_text=g.ep.bord, edge_font_size=10,\\\n                output_size=(800, 800), output=gfname, bg_color=[1,1,1,1])\n        else:            \n            print (\"plotting all species of frame %d\" % self.fid)\n            for s in self.specs.keys():\n                gfname = \"frame_%d_species_%d.png\" % (self.fid, s)\n                g = self.specs[s].graph\n                pos = gtd.arf_layout(g, max_iter=0)\n                gtd.graph_draw(g, pos=pos, vertex_text=g.vp.aid, vertex_font_size=12, vertex_size=8, \\\n                output_size=(200, 200), output=gfname, bg_color=[1,1,1,1])\n        return\n\n    def get_border(self, b):\n        \"\"\"get the bond order for a bond b\n        \n        currently no test is made if the edge exists ... you need to check\n\n        Args:\n            b (tuple of indices): atom indices of bond\n        \"\"\"\n        e = self.molg.edge(b[0], b[1])\n        border = self.molg.ep.bord[e]\n        return border\n\n    def make_mol(self, species):\n        \"\"\"generate a single mol object from a list of species for a TS\n\n        NOTE: the additional species added to the frame are considered to be non tracked\n\n        \"\"\"\n        aids = []\n        for mid in species:\n            if mid not in self.specs:\n                self.add_species(mid, tracked=False)\n            s = self.specs[mid]\n            aids += list(s.aids)\n        aids.sort() # This is necessary to ensure same ordering in mol object \n        mol = molsys.mol.from_array(self.xyz[aids])\n        mol.set_cell(self.mol.get_cell())\n        mol.set_elems([self.mol.elems[i] for i in aids])\n        mol.set_real_mass()\n        mol.center_com(check_periodic=False)\n        mol.apply_pbc()\n        mol.make_nonperiodic()\n        # rotate into principal axes\n        xyz = mol.get_xyz()\n        mol.set_xyz(rotations.align_pax(xyz, masses = mol.get_mass()))\n        mol.set_atypes(mol.get_elems())\n        # add connectivity\n        conn = []\n        for i in aids:\n            v = self.molg.vertex(i)\n            conn_i = []\n            for j in v.all_neighbors():\n                assert int(j) in aids\n                conn_i.append(aids.index(int(j)))\n            conn.append(conn_i)\n        mol.set_conn(conn)\n        return mol, aids\n\n    def make_species_mol(self):\n        \"\"\"get a list of mol objects for all species in the frame\n\n        NOTE: we use here the global xyz and pmol -> should be delegated to the species object which needs refactoring\n        - we should attacg \n        \"\"\"\n        mols = {}\n        for s in self.specs:\n            sp = self.specs[s]\n            sxyz = self.xyz[list(sp.aids)]\n            mols[s] = self.specs[s].make_mol(sxyz, self.mol) \n        return mols\n\n    ### some DEBUG methods ###\n\n    def write_species(self):\n        foldername = \"frame_%d_species\" % self.fid\n        os.mkdir(foldername)\n        os.chdir(foldername)\n        mols = self.make_species_mol()\n        for s in mols:\n            m = mols[s]\n            m.write(\"spec_%d.mfpx\" % s)\n        os.chdir(\"..\")\n\n    def get_main_species_formula(self):\n        \"\"\"get the sumformula of the tracked species\n        \"\"\"\n        sp = list(self.specs.keys())\n        sp.sort()\n        sumforms = []\n        for s in sp:\n            aids = list(self.specs[s].aids)\n            elems = [self.mol.elems[i] for i in aids]\n            cont  = list(set(elems))\n            cont.sort()\n            sumform = \"\"\n            for e in cont:\n                sumform += \"%s%d \" % (e, elems.count(e))\n            sumforms.append(sumform)\n        return sumforms\n\n    def DEBUG_write_as_xyz(self, fname):\n        f = open(fname, \"w\")\n        f.write(\"%d\\n\\n\" % self.natoms)\n        for i in range(self.natoms):\n            x, y, z = self.xyz[i]\n            f.write(\"%3s %12.6f %12.6f %12.6f\\n\" % (self.mol.elems[i], x, y, z))\n        f.close()\n        return\n\n#####################  SPECIES CLASS ########################################################################################\n\nclass species:\n    \"\"\"container class to keep species info (per frame!)\n    \"\"\"\n\n    def __init__(self, fid, mid, molg, make_graph=False, tracked = True):\n        \"\"\"init species\n        \n        Args:\n            fid (int): frame number\n            mid (int): molecule id (\"name\" of species from label components)\n            molg (graph): molg of the frame\n        \"\"\"\n        self.fid = fid\n        self.mid = mid\n        self.molg = molg # parent molgraph\n        # find all vertices in molg that belong to this species mid\n        vs = gtu.find_vertex(molg, molg.vp.mid, mid)\n        self.aids = set([int(v) for v in vs]) # atomids -> TBI do we need to sort? seems like they are sorted as they come\n        self.graph = None\n        if make_graph:\n            # now make a view of molg for this species         \n            self.make_graph()\n        self.tracked = tracked\n        return\n\n    def make_graph(self):\n        vfilt = self.molg.new_vertex_property(\"bool\")\n        vfilt.a[:] = False\n        for v in self.aids:\n            vfilt[v] = True\n        self.graph = GraphView(self.molg, vfilt=vfilt)\n        return\n\n    @property\n    def natoms(self):\n        return len(self.aids)\n\n    def make_mol(self, xyz, pmol):\n        \"\"\"generate a mol object for the species from a frame\n\n        we get the current coordinates as xyz and the parent mol object pmol from the mfp5 file\n        \n        Args:\n            xyz (numpy): coordinates of the atoms\n            pmol (molsys object): parent mol object from mfp5 file \n        \"\"\"\n        aids = list(self.aids) # in order to map backwards\n        self.mol = molsys.mol.from_array(xyz)\n        if pmol.get_cell() is not None:\n            self.mol.set_cell(pmol.get_cell())\n        self.mol.set_elems([pmol.elems[i] for i in aids])\n        self.mol.set_real_mass()\n        self.mol.center_com(check_periodic=False)\n        self.mol.apply_pbc()\n        self.mol.make_nonperiodic()\n        # rotate into principal axes\n        xyz = self.mol.get_xyz()\n        self.mol.set_xyz(rotations.align_pax(xyz, masses = self.mol.get_mass()))\n        self.mol.set_atypes(self.mol.get_elems())\n        # add connectivity\n        if self.graph is None:\n            self.make_graph()\n        ctab = []\n        for e in self.graph.edges():\n            i = aids.index(int(e.source()))\n            j = aids.index(int(e.target()))\n            ctab.append([i, j])\n        self.mol.set_ctab(ctab, conn_flag=True)\n        return self.mol\n\n    def __eq__(self, other):\n        \"\"\"compare two species whether they are equal\n\n        Compares \"exactly\" .. atom indices (wrt frame) and bonding must match exactly.\n        This can not be used to find similar species (same bonding etc but different atom numbers)\n        Note: The conformation of the species can be entirely differnt -> we do not compare postions!\n\n        Args:\n            other (species object): the other species object\n\n        Returns:\n            bool: if they are equal or not equal\n        \"\"\"\n        if not type(self) is type(other):\n            return NotImplemented\n        # check if atom IDs are equal\n        if self.aids != other.aids:\n            return False\n        # generate a set of bonds for each species\n        bself  = set([(int(e.source()),int(e.target())) for e in self.graph.edges()])\n        bother = set([(int(e.source()),int(e.target())) for e in other.graph.edges()])\n        if bself != bother:\n            return False\n\n        # if we are here the species are equal\n        return True\n        \n    def __repr__(self):\n        return \"SPECIES{frame %5d / molid %3d (%4d atoms)}\" % (self.fid, self.mid, self.natoms)\n\n#####################  FRAME COMPARE CLASS ########################################################################################\n\nclass fcompare:\n    \"\"\"This class compares two frames at different levels of resolution whether species are different\n       All info collected during the compairson is kept in this class in order to be exploited later\n    \"\"\"\n\n    def __init__(self, f1, f2):\n        \"\"\"generate comparer\n        \n        Args:\n            f1 (frame object): first frame object\n            f2 (frame object): second frame object (to be compared with f1)\n        \"\"\"\n        self.f1 = f1\n        self.f2 = f2\n        # defaults\n        self.compare_level = 0 # 0: no comparison, 1: atom id level, 2: connectivity level\n        self.umatch_f1 = [s for s in self.f1.specs if self.f1.specs[s].tracked]\n        self.umatch_f2 = [s for s in self.f2.specs if self.f2.specs[s].tracked]\n        self.aids_match = []\n        self.bond_match = []\n        self.aids_analyzed = False\n        self.bonds_analyzed = False\n        self.reacs = []\n        self.broken_bonds = []\n        self.formed_bonds = []\n        self.nreacs = 0 # number of independent reactions for this pair of frames .. should always be 1 (??)\n        return\n\n    def report(self, all = False):\n        \"\"\"this method is just to implement all levels of comparison\n\n           it does not return anything and just reports ... meant for debugging\n        \"\"\"\n        print(\"##################################################\")\n        print(\"FRAMES        %5d         %5d\" % (self.f1.fid, self.f2.fid))\n        mf = self.check_aids()\n        if all:\n            for m in self.aids_match:\n                print(\"          species %5d == species %5d\" % m)\n                print(\" natoms:          %5d            %5d\" % (self.f1.specs[m[0]].natoms, self.f2.specs[m[1]].natoms))\n        if mf > 0:\n            self.analyse_aids()\n            for r in self.reacs:\n                print (\"educts  : %s\" % str(list(r[0].keys())))\n                print (\"products: %s\" % str(list(r[1].keys())))\n        return\n\n    def check_aids(self, verbose = False):\n        \"\"\"check on level 1 for atom id matches\n\n        this method implements a rather complex logic:\n        which species form the educts and products to define a complete reaction event\n        \"\"\"\n        if self.compare_level < 1:\n            # we need to compare\n            for sk1 in self.f1.specs:\n                s1 = self.f1.specs[sk1]\n                # find a corresponding species in frame 2\n                for sk2 in self.umatch_f2:\n                    s2 = self.f2.specs[sk2]\n                    if s1.aids == s2.aids:      # NOTE: this works because the vertices are always properly sorted\n                        # s1 and s2 match -> add to match and to remove\n                        self.aids_match.append((sk1, sk2))\n                        self.umatch_f1.remove(sk1)\n                        self.umatch_f2.remove(sk2)\n                        break\n            # now matches are found -> set compare level\n            self.compare_level = 1\n        match_flag = 0 # all is equal on level 1\n        if len(self.umatch_f1) > 0 or len(self.umatch_f2) > 0:\n            match_flag = 1 # unmatched species!!\n        if verbose:\n            print (\"species in f1   : %s\" % str(self.f1.specs.keys()))\n            print (\"species in f2   : %s\" % str(self.f2.specs.keys()))\n            print (\"unmatched in f1 : %s\" % str(self.umatch_f1))\n            print (\"unmatched in f2 : %s\" % str(self.umatch_f2))\n\n        return match_flag\n\n    def analyse_aids(self):\n        if self.aids_analyzed:\n            return\n        if self.compare_level == 0:\n            self.check_aids()\n        if len(self.umatch_f1)==0 and len(self.umatch_f2)==0:\n            # there is nothing to do\n            return\n        # we have some unmatched species -> there is one (or more) reaction(s) between these frames\n        # find groups of species that define a reaction\n        #    all atom ids in the union of the educts sets must be also in the products set\n        for sk1 in self.umatch_f1:\n            # first search for atoms in the unmatched f2 species\n            s1 = self.f1.specs[sk1]\n            educts = {sk1: s1} # dictionary of species key/species for this reaction\n            educt_aids = s1.aids.copy() # set of atomids\n            products = {}\n            product_aids = set()\n            for sk2 in self.umatch_f2:\n                s2 = self.f2.specs[sk2]\n                common_aids = s1.aids & s2.aids\n                if len(common_aids)>0:\n                    products[sk2] = s2\n                    product_aids |= s2.aids\n            # do the following until educt_aids and product_aids match\n            while not (educt_aids == product_aids):\n                # which atoms are in products that are not in the educt species? --> add them\n                for a in product_aids - educt_aids:\n                    # to which species in frame 1 does this atom belong to?\n                    esk = self.f1.molg.vp.mid[a]\n                    # is this already in educts?\n                    if esk not in educts:\n                        # we need to make a new species object and add it (as non-tracked)\n                        educts[esk] = self.f1.make_species(esk)\n                        educt_aids |= educts[esk].aids\n\n                        # avoid that found educt is in first list. In that case you will find a reaction twice\n                        if esk in self.umatch_f1:\n                            self.umatch_f1.remove(esk)\n\n                # which atoms are in the educts that are not in the product species? add them\n                for a in educt_aids - product_aids:\n                    # to which species in frame 2 does this atom belong to?\n                    psk = self.f2.molg.vp.mid[a]\n                    # is this already in educts?\n                    if psk not in products:\n                        # we need to make a new species object and add it (as non-tracked)\n                        products[psk] = self.f2.make_species(psk)\n                        product_aids |= products[psk].aids\n\n                        # GS: unsure if this is required. Should avoid to assign a product twice\n                        if psk in self.umatch_f2:\n                            self.umatch_f2.remove(psk)\n                        \n            self.reacs.append((educts, products))\n        # the above will not work if there is no tracked species in umatch_f1 (but in umatch_f2)\n        # ... in other words a species has \"appeared\" or formed by merging two or more untracked species\n        if len(self.umatch_f1)==0:\n            for sk2 in self.umatch_f2:\n                s2 = self.f2.specs[sk2]\n                products = {sk2: s2}\n                product_aids = s2.aids.copy()\n                # now find all the species in frame 1 to match the atoms \n                educts = {}\n                educt_aids = set()\n                for a in product_aids:\n                    esk = self.f1.molg.vp.mid[a]\n                    if esk not in educts:\n                        educts[esk] = self.f1.make_species(esk)\n                        educt_aids |= educts[esk].aids\n                # do the following until educt_aids and product_aids match\n                while not (educt_aids == product_aids):\n                    # which atoms are in products that are not in the educt species? --> add them\n                    for a in product_aids - educt_aids:\n                        # to which species in frame 1 does this atom belong to?\n                        esk = self.f1.molg.vp.mid[a]\n                        # is this already in educts?\n                        if esk not in educts:\n                            # we need to make a new species object and add it (as non-tracked)\n                            educts[esk] = self.f1.make_species(esk)\n                            educt_aids |= educts[esk].aids\n\n\n                    # which atoms are in the educts that are not in the product species? add them\n                    for a in educt_aids - product_aids:\n                        # to which species in frame 2 does this atom belong to?\n                        psk = self.f2.molg.vp.mid[a]\n                        # is this already in educts?\n                        if psk not in products:\n                            # we need to make a new species object and add it (as non-tracked)\n                            products[psk] = self.f2.make_species(psk)\n                            product_aids |= products[psk].aids\n                # now add the final results to the reacs list\n                self.reacs.append((educts, products))   \n        self.nreacs = len(self.reacs)\n        self.aids_analyzed = True\n        return\n\n    def find_react_bond(self):\n        \"\"\"find a reactive bond in a bimolecular reaction \n        \n        Args:\n            r (int): index in self.reac to analyse\n        \"\"\"\n        assert self.aids_analyzed\n        g1 = self.f1.molg\n        g2 = self.f2.molg\n        for r in range(self.nreacs):\n            broken_bonds = []\n            formed_bonds = []\n            educts, products = self.reacs[r]\n            # get all involved atoms\n            aids = set()\n            for s in educts:\n                aids |= educts[s].aids\n            for a in aids:\n                bonds1 = []\n                v1 = g1.vertex(a)\n                for e in v1.out_edges(): \n                    bonds1.append(int(e.target()))\n                bonds2 = []\n                v2 = g2.vertex(a)\n                for e in v2.out_edges():\n                    bonds2.append(int(e.target()))\n                bs = set(bonds1) - set(bonds2)\n                fs = set(bonds2) - set(bonds1)\n                for b in bs:\n                    if b > a:\n                        broken_bonds.append((a,b))\n                for b in fs:\n                    if b > a:\n                        formed_bonds.append((a,b))\n            self.broken_bonds.append(broken_bonds)\n            self.formed_bonds.append(formed_bonds)\n        return\n\n    def check_bonds(self, verbose = False):\n        \"\"\"check on level 2 for identical bonds\n\n        we use the existing pairs of species in self.aids_match to identify species that have identical aids\n        => now we test if they have the same bonding pattern\n        \"\"\"\n        assert self.compare_level > 0\n        self.missmatch = []\n        for p in self.aids_match:\n            # get the species of the pair\n            s1 = self.f1.specs[p[0]]\n            s2 = self.f2.specs[p[1]]\n            # # TBI: this might not be enough \n            # #      do we need elements as vertex properties to be considered?\n            # #      what about a tautomerism when the initial and fianl state are symmetric?\n            # f = gtt.isomorphism(s1.graph, s2.graph)\n            # INDEED: isomoprhism is not strict enough\n            # print (\"%d %d %d %d %s\" % (self.f1.fid, self.f2.fid, p[0], p[1], f))\n            if  s1 == s2:\n                self.bond_match.append(p)\n            else:\n                self.missmatch.append(p)\n        self.compare_level = 2\n        if len(self.missmatch) > 0:\n            # unmatched species on level 2\n            return 2\n        else:\n            return 0 # all equal\n\n    def analyse_bonds(self):\n        if self.bonds_analyzed:\n            return\n        if self.compare_level < 2:\n            self.check_bonds()\n        if len(self.missmatch) == 0:\n            return\n        # now analyse all the pairs in self.missmatch: they have identical aids but a diffrent bond graph\n        self.nreacs = len(self.missmatch)\n        for p in self.missmatch:\n            # get the species of the pair\n            s1 = self.f1.specs[p[0]]\n            s2 = self.f2.specs[p[1]]\n            self.reacs.append(({p[0]: s1},{p[1]: s2}))\n            # get all edges as vertex id tuples (int tuples)\n            bs1 = set([(int(e.source()),int(e.target())) for e in s1.graph.edges()])\n            bs2 = set([(int(e.source()),int(e.target())) for e in s2.graph.edges()])\n            self.broken_bonds.append(list(bs1-bs2)) # broken: bond in frame1 but not in frame2\n            self.formed_bonds.append(list(bs2-bs1)) # formed: bond in frame2 but not in frame1\n        self.bonds_analyzed = True\n        return\n\n\n    def check(self, verbose = False):\n        \"\"\"check identity of species on all levels (1 and 2) \n        \"\"\"\n        mf = self.check_aids(verbose=verbose)\n        if mf > 0:\n            return mf\n        # aids are equal -> chek bonds\n        return self.check_bonds(verbose=verbose)\n\n#####################  REACTIVE EVENT CLASS ########################################################################################\n# this class is instantiated with a comparer (between two frames)\n# and stores a reactive event \n# it knows the TS_fid and if the event is bi- or unimolecular\n\nclass revent:\n\n    def __init__(self, comparer, fR, unimol= False, ireac=0):\n        \"\"\"generate a reaction event object\n\n        TBI: what to do if there are more then one reaction event (in two diffrent tracked species)\n             at the same time ... this is properly tracked in the comparer (nreacs>1)\n             but this means there are more revents to be generated. should we do this recursively?\n             how to store?\n        \n        Args:\n            comparer (fcompare object): comparer that gave a reactive event\n            fR (parent findR object): to access process_frame\n            unimol (bool, optional): is unimolecular. Defaults to False.\n            ireac (int,optional): specifies the reaction event\n        \"\"\"\n        self.unimol = unimol\n        self.fR = fR\n        self.comparer = comparer\n        # currently we allow only for single reaction events per frame \n        # this would change if there is more than one tracked species ....\n        #assert comparer.nreacs == 1 , \"Currently only single reaction events are processed. Error occured for frames %s and %s\" % (comparer.f1.fid, comparer.f2.fid)\n        #r = 0 # pick first reaction (the only one)\n        assert comparer.nreacs > ireac, \"Too many reaction events requested...\"\n        r = ireac\n        print(\"ireac \" + str(ireac) + \" frames \" + str(comparer.f1.fid) + \" and \" + str(comparer.f2.fid) )\n        educts, products = comparer.reacs[r]\n        self.broken_bonds     = comparer.broken_bonds[r]\n        self.formed_bonds     = comparer.formed_bonds[r]\n        f1               = comparer.f1\n        f2               = comparer.f2\n        # choose which frame we use as TS\n        # everything is referenced to f1 which is 0 (f2 is +1)\n        # find avereage bond order of reactive bonds at f1/f2\n        f1_averborder = 0.0\n        if len(self.broken_bonds) >0:\n            for b in self.broken_bonds:\n                f1_averborder += f1.molg.ep.bord[f1.molg.edge(b[0], b[1])]\n            f1_averborder/len(self.broken_bonds)\n        f2_averborder = 0.0\n        if len(self.formed_bonds) >0:\n            for b in self.formed_bonds:\n                f2_averborder += f2.molg.ep.bord[f2.molg.edge(b[0], b[1])]\n            f2_averborder/len(self.formed_bonds)\n        if f1_averborder == 0.0:\n            TS_rfid = 1\n        elif f2_averborder == 0.0:\n            TS_rfid = 0\n        else:\n            if abs(f1_averborder-0.5) < abs(f2_averborder-0.5):\n                # f1 closer to TS\n                TS_rfid = 0\n            else:\n                TS_rfid = 1\n        # now store data depending on relative frame id (rfid) of the TS\n        if TS_rfid == 0:\n            self.TS = f1\n            self.PR = f2\n            self.ED = self.fR.process_frame(self.TS.fid-1)\n            # get corresponding species numbers\n            self.TS_spec = educts\n            self.PR_spec = products\n            loccomp = fcompare(self.ED, self.TS)\n            if loccomp.check_aids() == 0:\n                # no change in atom ids .. we can use TS species for ED as well\n                self.ED_spec = {}\n                for e in educts:\n                    if e in self.ED.specs:\n                        self.ED_spec[e] = self.ED.specs[e]\n                    else:\n                        self.ED_spec[e] = self.ED.make_species(e)\n            else:\n                print (\"Houston we have a problem!!! species changed between ED and TS\")\n        else:\n            self.ED = f1\n            self.TS = f2\n            if self.fR.nframes > self.TS.fid+1:\n                self.PR = self.fR.process_frame(self.TS.fid+1)\n                self.ED_spec = educts\n                self.TS_spec = products\n                loccomp = fcompare(self.TS, self.PR)\n                if loccomp.check_aids() == 0:\n                    # no change in atom ids .. we can use TS species for PR as well\n                    self.PR_spec = {}\n                    for e in products:\n                        if e in self.PR.specs:\n                            self.PR_spec[e] = self.PR.specs[e]\n                        else:\n                            self.PR_spec[e] = self.PR.make_species(e)\n                else:\n                    print (\"Houston we have a problem!!! species changed between TS and PR\")\n            else:\n                print(\"Warning! We run out of frames to process to identify TS and PR.\")\n        # get TS_fid for ease\n        self.TS_fid = self.TS.fid\n\n\n        return\n", "meta": {"hexsha": "8c59cabba810fbaa5017f585bb0d26f82fa99e47", "size": 29451, "ext": "py", "lang": "Python", "max_stars_repo_path": "molsys/util/findR_classes.py", "max_stars_repo_name": "MOFplus/molsys_rel", "max_stars_repo_head_hexsha": "ff8b181fefc0ba03c5dd14fe2dde613298155203", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "molsys/util/findR_classes.py", "max_issues_repo_name": "MOFplus/molsys_rel", "max_issues_repo_head_hexsha": "ff8b181fefc0ba03c5dd14fe2dde613298155203", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "molsys/util/findR_classes.py", "max_forks_repo_name": "MOFplus/molsys_rel", "max_forks_repo_head_hexsha": "ff8b181fefc0ba03c5dd14fe2dde613298155203", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.734439834, "max_line_length": 165, "alphanum_fraction": 0.5327832671, "include": true, "reason": "import numpy", "num_tokens": 7139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.29746994883293104, "lm_q1q2_score": 0.16148551306860207}}
{"text": "#!/usr/bin/env python\n\n#Title:         Module to facilitate basic reaction calculations for Sub-Chandra research\n#Author:        Adam Jacobs\n#Creation Date: Nov. 1, 2013\n\n#Usage: load as a module\n\n#Description: This module contains code to facilitate carrying out some basic reaction calculations\n#             for analysis in the Sub-Chandra II paper.\n#\n#Revision History\n#Programmer            Date                    Change\n# ------------------------------------------------------------------------------\n#Adam Jacobs         11/01/2013              Code created\n\n#TODO: \n# 1) \n\n#Notes on conventions, programming style:\n#  1) All classes are in CamelCase with the first letter capitalized.  Class methods\n#     are also in CamelCase with the first letter lower-case, e.g. myMethod().\n#  2) Non-class functions and all variables are lowercase with underscores (_) \n#     acting as delimiters when needed/wanted.\n#  3) An underscore prefix, e.g. _variable, means the named item is intended to be\n#     private (Python doesn't provide for easily enforcing data hiding, it's all by \n#     convention).\n#  4) Names that are in ALL_CAPS are intended as constants.\n\n######################\n### Global Imports ###\n######################\nimport sys\n\n#################################\n### Global Data and Constants ###\n#################################\n#_EXAMPLE = 'string'\n\n###############\n### Classes ###\n###############\n\n#################\n### Functions ###\n#################\ndef plot_logenuc():\n  import numpy as np\n  import matplotlib\n  #If 'inline' backend, we're running within IPython so don't change anything.\n  #Otherwise, we're running as script to generate eps, so use PS backend\n  if 'inline' not in matplotlib.get_backend():\n    matplotlib.use('PS')\n  import matplotlib.pyplot as plt\n\n  matplotlib.rcParams['text.usetex'] = 'True'\n  # Make data based on MESA calcs in mesa_subch/\n  rho_exp = np.linspace(5.0, 7.0, 11)\n  rho     = np.array([10**rexp for rexp in rho_exp])\n  #rho_nco = np.array([10**rexp for rexp in rho_exp[-3:]])\n\n  # 200 MK rates, OLD, version 5XXX\n  #enuc_cagob2  = np.array(\n  #    [10**17.581540508, \n  #     10**17.800549914,\n  #     10**18.024481339,\n  #     10**18.254609218,\n  #     10**18.492973480,\n  #     10**18.738377513,\n  #     10**18.986558564,\n  #     10**19.234718720,\n  #     10**19.477401243,\n  #     10**19.704819234,\n  #     10**19.897451724])\n  #enuc_tralf2  = np.array(\n  #    [10**11.188457831,  #rho = 10**5.0\n  #     10**11.626476644,  #rho = 10**5.2\n  #     10**12.074446783,  #rho = 10**5.4\n  #     10**12.531401511,  #rho = 10**5.6\n  #     10**12.996679600,  #rho = 10**5.8\n  #     10**13.469768554,  #rho = 10**6.0\n  #     10**13.948445742,  #rho = 10**6.2\n  #     10**14.432637076,  #rho = 10**6.4\n  #     10**14.910185702,  #rho = 10**6.6\n  #     10**15.450434567,  #rho = 10**6.8\n  #     10**16.013534830]) #rho = 10**7.0\n  #enuc_nagf2   = np.array(\n  #    [10**10.356064284, \n  #     10**10.596664766,\n  #     10**10.840074663,\n  #     10**11.083643491,\n  #     10**11.322076922,\n  #     10**11.545046637,\n  #     10**11.796568378,\n  #     10**12.066216636,\n  #     10**12.348913239,\n  #     10**12.646625087,\n  #     10**12.961628265])\n  #enuc_cago2   = np.array(\n  #    [10**7.066187025, \n  #     10**7.303537281,\n  #     10**7.544452034,\n  #     10**7.787414219,\n  #     10**8.029050316,\n  #     10**8.262882790,\n  #     10**8.482066479,\n  #     10**8.743164789,\n  #     10**9.015982418,\n  #     10**9.302270992,\n  #     10**9.604056810])\n  #enuc_nco2    = np.array(\n  #    [10**7.621642798,\n  #     10**7.907935225,\n  #     10**8.209727138])\n  \n  # 200 MK rates, MESA version 7503, see mesa_subch/200MKSeries.out\n  enuc_cagob2  = np.array(\n      [3.88724408e+17,     #rho = 10**5.0\n       6.43552100e+17,     #rho = 10**5.2\n       1.07753194e+18,     #rho = 10**5.4\n       1.82999980e+18,     #rho = 10**5.6\n       3.16711338e+18,     #rho = 10**5.8\n       5.57201399e+18,     #rho = 10**6.0\n       9.86657427e+18,     #rho = 10**6.2\n       1.74726877e+19,     #rho = 10**6.4\n       3.05623900e+19,     #rho = 10**6.6\n       5.16352101e+19,     #rho = 10**6.8\n       8.07526663e+19])    #rho = 10**7.0\n  enuc_tralf2  = np.array(\n      [1.61236410e+11,\n       4.41923321e+11,\n       1.23924575e+12,\n       3.54801266e+12,\n       1.03546483e+13,\n       3.07691004e+13,\n       9.26265273e+13,\n       2.82426937e+14,\n       8.46686308e+14,\n       2.93507889e+15,\n       1.07243491e+16]) \n  enuc_nagf2   = np.array(\n      [2.39846615e+10,\n       4.17329568e+10,\n       7.30904519e+10,\n       1.28073324e+11,\n       2.21835352e+11,\n       3.71300418e+11,\n       6.60773488e+11,\n       1.22889032e+12,\n       2.35501530e+12,\n       4.67150539e+12,\n       9.64213931e+12])\n  enuc_cago2   = np.array(\n      [1.21008577e+07,\n       2.08980546e+07,\n       3.63892899e+07,\n       6.36683332e+07,\n       1.11075656e+08,\n       1.90389587e+08,\n       3.15051582e+08,\n       5.74527718e+08,\n       1.07630179e+09,\n       2.07969722e+09,\n       4.16416868e+09 ])\n  #\n  # 300 MK rates, OLD, version 5XXX\n  #\n  enuc_cagob3  = np.array(\n      [10**19.030792008, \n       10**19.241106991,\n       10**19.454092787,\n       10**19.670440935,\n       10**19.891022033,\n       10**20.116932101,\n       10**20.349550944,\n       10**20.591053956,\n       10**20.837613055,\n       10**21.086204225,\n       10**21.333254625])\n  enuc_tralf3  = np.array(\n      [10**13.785826231,  #rho = 10**5.0\n       10**14.206456199,  #rho = 10**5.2\n       10**14.632427790,  #rho = 10**5.4\n       10**15.065124085,  #rho = 10**5.6\n       10**15.506286282,  #rho = 10**5.8\n       10**15.957694147,  #rho = 10**6.0\n       10**16.417507200,  #rho = 10**6.2\n       10**16.885601880,  #rho = 10**6.4\n       10**17.360983029,  #rho = 10**6.6\n       10**17.842218167,  #rho = 10**6.8\n       10**18.324423763]) #rho = 10**7.0\n  enuc_nagf3   = np.array(\n      [10**13.685591364, \n       10**13.909659660,\n       10**14.141720810,\n       10**14.379825361,\n       10**14.621578864,\n       10**14.865447555,\n       10**15.108015882,\n       10**15.342720865,\n       10**15.567331414,\n       10**15.829352083,\n       10**16.103271007])\n  enuc_cago3   = np.array(\n      [10**9.738896065, \n       10**9.959526033,\n       10**10.185497624,\n       10**10.419619014,\n       10**10.658290572,\n       10**10.900155663,\n       10**11.143164162,\n       10**11.383040770,\n       10**11.611826212,\n       10**11.842872776,\n       10**12.107808383])\n  #enuc_nco3    = np.array(\n  #    [10**10.973769648,\n  #     10**11.204818056,\n  #     10**11.469756036])\n  \n  #make the plots\n  #fig, ax = plt.subplots(nrows=2, ncols=1)\n  fig, ax = plt.subplots(nrows=1, ncols=1)\n  \n  ###plot the 200MK data\n  ax.plot(rho,     enuc_cagob2, label=r'CagO-by')\n  ax.plot(rho,     enuc_tralf2, label=r'3$\\alpha$')\n  ax.plot(rho,     enuc_nagf2,  label=r'NagF')\n  ax.plot(rho,     enuc_cago2,  label=r'CagO')\n  #ax.plot(rho_nco, enuc_nco2,   label=r'NCO')\n\n  #ax[0].plot(rho,     enuc_tralf3, 'b--')\n  #ax[0].plot(rho,     enuc_cagob3, 'g--')\n  #ax[0].plot(rho,     enuc_cago3,  'r--')\n  #ax[0].plot(rho_nco, enuc_nco3,   'c--')\n\n  #tune plot settings\n  ax.set_yscale('log')\n  ax.set_xscale('log')\n  ax.set_ylabel(r'$\\dot{\\epsilon}~[\\rm{erg}~\\rm{g}^{-1}~\\rm{s}^{-1}]$', fontsize='x-large')\n  ax.set_ylim(1.e6, 1.e22)\n\n  ax.set_xlabel(r'$\\rho~[\\rm{g}~\\rm{cm}^{-3}]$', fontsize='x-large')\n  \n  ax.tick_params(labelsize='x-large')\n  ax.legend(loc=2, fontsize='medium')\n  ax.set_title(r'$T = 200~\\rm{MK}$', fontsize='x-large')\n\n  ###plot the 300MK data\n  #ax[1].plot(rho,     enuc_cagob3, label=r'CagO-by')\n  #ax[1].plot(rho,     enuc_tralf3, label=r'3$\\alpha$')\n  #ax[1].plot(rho,     enuc_nagf3,  label=r'NagF')\n  #ax[1].plot(rho,     enuc_cago3,  label=r'CagO')\n  #ax[1].plot(rho_nco, enuc_nco3,   label=r'NCO')\n\n  ##tune plot settings\n  #ax[1].set_yscale('log')\n  #ax[1].set_xscale('log')\n  #ax[1].set_ylabel(r'$\\dot{\\epsilon}~[\\rm{erg}~\\rm{g}^{-1}~\\rm{s}^{-1}]$', fontsize='xx-large')\n  #ax[1].set_ylim(1.e6, 1.e22)\n\n  #ax[1].set_xlabel(r'$\\rho~[\\rm{g}~\\rm{cm}^{-3}]$', fontsize='xx-large')\n  #\n  #ax[1].tick_params(labelsize='x-large')\n  #ax[1].legend(loc=2, fontsize='large')\n  #ax[1].set_title(r'$T = 300 ~\\rm{MK}$', fontsize='xx-large')\n\n  fig.set_size_inches(5.0*1.25, 5.0)\n  #fig.tight_layout()\n  #This fixes a bug in mpl's eps generation\n  matplotlib.rc('ps', usedistiller='xpdf')\n  fig.savefig('rxns.eps', bbox_inches='tight')\n\n  return\n\n\n\n#################\n### Execution ###\n#################\n#This is only for testing. rxncalcs.py is intended to be used as a module.\nif __name__== \"__main__\":\n  if(len(sys.argv) <= 1):\n    #TODO: Add arg checks\n    pass\n\n  #Put tests here\n  plot_logenuc()\n", "meta": {"hexsha": "2fd083434c83b98328ffad850fc9c8d36b413e8a", "size": 8672, "ext": "py", "lang": "Python", "max_stars_repo_path": "Exec/SCIENCE/sub_chandra/paper_II/IPyRoot/rxncalcs.py", "max_stars_repo_name": "sailoridy/MAESTRO", "max_stars_repo_head_hexsha": "f957d148d2028324a2a1076be244f73dad63fd67", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2017-05-15T15:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-09T08:13:32.000Z", "max_issues_repo_path": "Exec/SCIENCE/sub_chandra/paper_II/IPyRoot/rxncalcs.py", "max_issues_repo_name": "sailoridy/MAESTRO", "max_issues_repo_head_hexsha": "f957d148d2028324a2a1076be244f73dad63fd67", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2017-06-14T23:05:00.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-28T16:40:42.000Z", "max_forks_repo_path": "Exec/SCIENCE/sub_chandra/paper_II/IPyRoot/rxncalcs.py", "max_forks_repo_name": "sailoridy/MAESTRO", "max_forks_repo_head_hexsha": "f957d148d2028324a2a1076be244f73dad63fd67", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-06-14T14:52:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-04T07:16:09.000Z", "avg_line_length": 30.0069204152, "max_line_length": 99, "alphanum_fraction": 0.5535055351, "include": true, "reason": "import numpy", "num_tokens": 3428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.16148550630654904}}
{"text": "# -*- coding: utf-8 -*-\nfrom . import config\nfrom ._constants import *\nfrom .maps import MapBase, RVBase, ReflectedBase\nfrom ._core import OpsSystem, math\nimport numpy as np\nfrom astropy import units\nfrom inspect import getmro\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nfrom IPython.display import HTML\nimport os\nimport logging\n\nlogger = logging.getLogger(\"starry.maps\")\n\n\n__all__ = [\"Primary\", \"Secondary\", \"System\"]\n\n\nclass Body(object):\n    \"\"\"A generic body. Must be subclassed.\"\"\"\n\n    def __init__(\n        self,\n        map,\n        r=1.0,\n        m=1.0,\n        prot=1.0,\n        t0=0.0,\n        theta0=0.0,\n        length_unit=units.Rsun,\n        mass_unit=units.Msun,\n        time_unit=units.day,\n        angle_unit=units.degree,\n        **kwargs,\n    ):\n        # Surface map\n        self._lazy = map._lazy\n        self._math = map._math\n        self.map = map\n\n        # Units\n        self.length_unit = length_unit\n        self.mass_unit = mass_unit\n        self.time_unit = time_unit\n        self.angle_unit = angle_unit\n\n        # Attributes\n        self.r = r\n        self.m = m\n        self.prot = prot\n        self.t0 = t0\n        self.theta0 = theta0\n\n    @property\n    def length_unit(self):\n        \"\"\"An ``astropy.units`` unit defining the length metric for this body.\"\"\"\n        return self._length_unit\n\n    @length_unit.setter\n    def length_unit(self, value):\n        assert value.physical_type == \"length\"\n        self._length_unit = value\n        self._length_factor = value.in_units(units.Rsun)\n\n    @property\n    def mass_unit(self):\n        \"\"\"An ``astropy.units`` unit defining the mass metric for this body.\"\"\"\n        return self._mass_unit\n\n    @mass_unit.setter\n    def mass_unit(self, value):\n        assert value.physical_type == \"mass\"\n        self._mass_unit = value\n        self._mass_factor = value.in_units(units.Msun)\n\n    @property\n    def time_unit(self):\n        \"\"\"An ``astropy.units`` unit defining the time metric for this body.\"\"\"\n        return self._time_unit\n\n    @time_unit.setter\n    def time_unit(self, value):\n        assert value.physical_type == \"time\"\n        self._time_unit = value\n        self._time_factor = value.in_units(units.day)\n\n    @property\n    def angle_unit(self):\n        \"\"\"An ``astropy.units`` unit defining the angle metric for this body.\"\"\"\n        return self._angle_unit\n\n    @angle_unit.setter\n    def angle_unit(self, value):\n        assert value.physical_type == \"angle\"\n        self._angle_unit = value\n        self._angle_factor = value.in_units(units.radian)\n\n    @property\n    def _angle_unit(self):\n        return self._map._angle_unit\n\n    @_angle_unit.setter\n    def _angle_unit(self, value):\n        self._map._angle_unit = value\n\n    @property\n    def _angle_factor(self):\n        return self._map._angle_factor\n\n    @_angle_factor.setter\n    def _angle_factor(self, value):\n        self._map._angle_factor = value\n\n    @property\n    def map(self):\n        \"\"\"The surface map for this body.\"\"\"\n        return self._map\n\n    @map.setter\n    def map(self, value):\n        assert MapBase in getmro(\n            type(value)\n        ), \"The `map` attribute must be a `starry` map instance.\"\n        assert (\n            value._lazy == self._lazy\n        ), \"Map must have the same evaluation mode (lazy/greedy).\"\n        self._map = value\n\n    @property\n    def r(self):\n        \"\"\"The radius in units of :py:attr:`length_unit`.\"\"\"\n        return self._r / self._length_factor\n\n    @r.setter\n    def r(self, value):\n        self._r = self._math.cast(value * self._length_factor)\n\n    @property\n    def m(self):\n        \"\"\"The mass in units of :py:attr:`mass_unit`.\"\"\"\n        return self._m / self._mass_factor\n\n    @m.setter\n    def m(self, value):\n        self._m = self._math.cast(value * self._mass_factor)\n\n    @property\n    def prot(self):\n        \"\"\"The rotation period in units of :py:attr:`time_unit`.\"\"\"\n        return self._prot / self._time_factor\n\n    @prot.setter\n    def prot(self, value):\n        self._prot = self._math.cast(value * self._time_factor)\n\n    @property\n    def t0(self):\n        \"\"\"A reference time in units of :py:attr:`time_unit`.\"\"\"\n        return self._t0 / self._time_factor\n\n    @t0.setter\n    def t0(self, value):\n        self._t0 = self._math.cast(value * self._time_factor)\n\n    @property\n    def theta0(self):\n        \"\"\"The map rotational phase at time :py:attr:`t0`.\"\"\"\n        return self._theta0 / self._angle_factor\n\n    @theta0.setter\n    def theta0(self, value):\n        self._theta0 = self._math.cast(value * self._angle_factor)\n\n    def _check_kwargs(self, method, kwargs):\n        if not config.quiet:\n            for key in kwargs.keys():\n                message = \"Invalid keyword `{0}` in call to `{1}()`. Ignoring.\"\n                message = message.format(key, method)\n                logger.warning(message)\n\n\nclass Primary(Body):\n    \"\"\"A primary (central) body.\n\n    Args:\n        map: The surface map of this body. This should be an instance\n            returned by :py:func:`starry.Map`.\n        r (scalar, optional): The radius of the body in units of\n            :py:attr:`length_unit`. Defaults to 1.0.\n        m (scalar, optional): The mass of the body in units of\n            :py:attr:`mass_unit`. Defaults to 1.0.\n        prot (scalar, optional): The rotation period of the body in units of\n            :py:attr:`time_unit`. Defaults to 1.0.\n        t0 (scalar, optional): A reference time in units of\n            :py:attr:`time_unit`. Defaults to 0.0.\n        theta0 (scalar, optional): The rotational phase of the map at time\n            :py:attr:`t0` in units of :py:attr:`angle_unit`. Defaults to 0.0.\n        length_unit (optional): An ``astropy.units`` unit defining the\n            distance metric for this object. Defaults to\n            :py:attr:`astropy.units.Rsun.`\n        mass_unit (optional): An ``astropy.units`` unit defining the\n            mass metric for this object. Defaults to\n            :py:attr:`astropy.units.Msun.`\n        time_unit (optional): An ``astropy.units`` unit defining the\n            time metric for this object. Defaults to\n            :py:attr:`astropy.units.day.`\n        angle_unit (optional): An ``astropy.units`` unit defining the\n            angular metric for this object. Defaults to\n            :py:attr:`astropy.units.degree.`\n    \"\"\"\n\n    def __init__(self, map, **kwargs):\n        # Initialize `Body`\n        super(Primary, self).__init__(map, **kwargs)\n        for kw in [\n            \"r\",\n            \"m\",\n            \"prot\",\n            \"t0\",\n            \"theta0\",\n            \"length_unit\",\n            \"mass_unit\",\n            \"time_unit\",\n            \"angle_unit\",\n        ]:\n            kwargs.pop(kw, None)\n        self._check_kwargs(\"Primary\", kwargs)\n\n\nclass Secondary(Body):\n    \"\"\"A secondary (orbiting) body.\n\n    Args:\n        map: The surface map of this body. This should be an instance\n            returned by :py:func:`starry.Map`.\n        r (scalar, optional): The radius of the body in units of\n            :py:attr:`length_unit`. Defaults to 1.0.\n        m (scalar, optional): The mass of the body in units of\n            :py:attr:`mass_unit`. Defaults to 1.0.\n        a (scalar, optional): The semi-major axis of the body in units of\n            :py:attr:`time_unit`. Defaults to 1.0. If :py:attr:`porb` is\n            also provided, this value is ignored.\n        porb (scalar, optional): The orbital period of the body in units of\n            :py:attr:`time_unit`. Defaults to 1.0. Setting this value\n            overrides :py:attr:`a`.\n        prot (scalar, optional): The rotation period of the body in units of\n            :py:attr:`time_unit`. Defaults to 1.0.\n        t0 (scalar, optional): A reference time in units of\n            :py:attr:`time_unit`. This is taken to be the time of a reference\n            transit. Defaults to 0.0.\n        ecc (scalar, optional): The orbital eccentricity of the body.\n            Defaults to 0.\n        w, omega (scalar, optional): The argument of pericenter of the body\n            in units of :py:attr:`angle_unit`. Defaults to 90 degrees.\n        Omega (scalar, optional): The longitude of ascending node of the\n            body in units of :py:attr:`angle_unit`. Defaults to 0 degrees.\n        inc (scalar, optional): The orbital inclination of the body in\n            units of :py:attr:`angle_unit`. Defaults to 90 degrees.\n        theta0 (scalar, optional): The rotational phase of the map at time\n            :py:attr:`t0` in units of :py:attr:`angle_unit`. Defaults to\n            0.0.\n        length_unit (optional): An ``astropy.units`` unit defining the\n            distance metric for this object. Defaults to\n            :py:attr:`astropy.units.Rsun.`\n        mass_unit (optional): An ``astropy.units`` unit defining the\n            mass metric for this object. Defaults to\n            :py:attr:`astropy.units.Msun.`\n        time_unit (optional): An ``astropy.units`` unit defining the\n            time metric for this object. Defaults to\n            :py:attr:`astropy.units.day.`\n        angle_unit (optional): An ``astropy.units`` unit defining the\n            angular metric for this object. Defaults to\n            :py:attr:`astropy.units.degree.`\n    \"\"\"\n\n    def __init__(self, map, **kwargs):\n        # Initialize `Body`\n        super(Secondary, self).__init__(map, **kwargs)\n        for kw in [\n            \"r\",\n            \"m\",\n            \"prot\",\n            \"t0\",\n            \"theta0\",\n            \"length_unit\",\n            \"mass_unit\",\n            \"time_unit\",\n            \"angle_unit\",\n        ]:\n            kwargs.pop(kw, None)\n\n        # Attributes\n        if kwargs.get(\"porb\", None) is not None:\n            self.porb = kwargs.pop(\"porb\", None)\n        elif kwargs.get(\"a\", None) is not None:\n            self.a = kwargs.pop(\"a\", None)\n        else:\n            raise ValueError(\"Must provide a value for either `porb` or `a`.\")\n        self.ecc = kwargs.pop(\"ecc\", 0.0)\n        self.w = kwargs.pop(\n            \"w\", kwargs.pop(\"omega\", 0.5 * np.pi / self._angle_factor)\n        )\n        self.Omega = kwargs.pop(\"Omega\", 0.0)\n        self.inc = kwargs.pop(\"inc\", 0.5 * np.pi / self._angle_factor)\n        self._check_kwargs(\"Secondary\", kwargs)\n\n    @property\n    def porb(self):\n        \"\"\"The orbital period in units of :py:attr:`time_unit`.\n\n        .. note::\n            Setting this value overrides the value of :py:attr:`a`.\n        \"\"\"\n        if self._porb == 0.0:\n            return None\n        else:\n            return self._porb / self._time_factor\n\n    @porb.setter\n    def porb(self, value):\n        self._porb = self._math.cast(value * self._time_factor)\n        self._a = 0.0\n\n    @property\n    def a(self):\n        \"\"\"The semi-major axis in units of :py:attr:`length_unit`.\n\n        .. note::\n            Setting this value overrides the value of :py:attr:`porb`.\n        \"\"\"\n        if self._a == 0.0:\n            return None\n        else:\n            return self._a / self._length_factor\n\n    @a.setter\n    def a(self, value):\n        self._a = self._math.cast(value * self._length_factor)\n        self._porb = 0.0\n\n    @property\n    def ecc(self):\n        \"\"\"The orbital eccentricity.\"\"\"\n        return self._ecc\n\n    @ecc.setter\n    def ecc(self, value):\n        self._ecc = value\n\n    @property\n    def w(self):\n        \"\"\"The longitude of pericenter in units of :py:attr:`angle_unit`.\"\"\"\n        return self._w / self._angle_factor\n\n    @w.setter\n    def w(self, value):\n        self._w = self._math.cast(value * self._angle_factor)\n\n    @property\n    def omega(self):\n        \"\"\"Alias for the longitude of pericenter :py:attr:`w`.\"\"\"\n        return self.w\n\n    @omega.setter\n    def omega(self, value):\n        self.w = value\n\n    @property\n    def Omega(self):\n        \"\"\"The longitude of ascending node in units of :py:attr:`angle_unit`.\"\"\"\n        return self._Omega / self._angle_factor\n\n    @Omega.setter\n    def Omega(self, value):\n        self._Omega = self._math.cast(value * self._angle_factor)\n\n    @property\n    def inc(self):\n        \"\"\"The orbital inclination in units of :py:attr:`angle_unit`.\"\"\"\n        return self._inc / self._angle_factor\n\n    @inc.setter\n    def inc(self, value):\n        self._inc = self._math.cast(value * self._angle_factor)\n\n\nclass System(object):\n    \"\"\"A system of bodies in Keplerian orbits about a central primary body.\n\n    Args:\n        primary (:py:class:`Primary`): The central body.\n        secondaries (:py:class:`Secondary`): One or more secondary bodies\n            in orbit about the primary.\n        time_unit (optional): An ``astropy.units`` unit defining the\n            time metric for this object. Defaults to\n            :py:attr:`astropy.units.day.`\n        light_delay (bool, optional): Account for the light travel time\n            delay to the barycenter of the system? Default is False.\n        texp (scalar): The exposure time of each observation. This can be a\n            scalar or a tensor with the same shape as ``t``. If ``texp`` is\n            provided, ``t`` is assumed to indicate the timestamp at the middle\n            of an exposure of length ``texp``.\n        oversample (int): The number of function evaluations to use when\n            numerically integrating the exposure time.\n        order (int): The order of the numerical integration scheme. This must\n            be one of the following: ``0`` for a centered Riemann sum\n            (equivalent to the \"resampling\" procedure suggested by Kipping 2010),\n            ``1`` for the trapezoid rule, or ``2`` for Simpson’s rule.\n    \"\"\"\n\n    def _no_spectral(self):\n        if self._primary._map.nw is not None:  # pragma: no cover\n            raise NotImplementedError(\n                \"Method not yet implemented for spectral maps.\"\n            )\n\n    def __init__(\n        self,\n        primary,\n        *secondaries,\n        time_unit=units.day,\n        light_delay=False,\n        texp=None,\n        oversample=7,\n        order=0,\n    ):\n        # Units\n        self.time_unit = time_unit\n        self._light_delay = bool(light_delay)\n        if texp is None:\n            self._texp = 0.0\n        else:\n            self._texp = texp\n        assert self._texp >= 0.0, \"Parameter `texp` must be >= 0.\"\n        self._oversample = int(oversample)\n        assert self._oversample > 0, \"Parameter `oversample` must be > 0.\"\n        self._order = int(order)\n        assert self._order in [0, 1, 2], \"Invalid value for parameter `order`.\"\n\n        # Primary body\n        assert (\n            type(primary) is Primary\n        ), \"Argument `primary` must be an instance of `Primary`.\"\n        assert (\n            primary._map.__props__[\"reflected\"] == False\n        ), \"Reflected light map not allowed for the primary body.\"\n        self._primary = primary\n        self._rv = primary._map.__props__[\"rv\"]\n        self._lazy = primary._lazy\n        self._math = primary._math\n        if self._lazy:\n            self._linalg = math.lazy_linalg\n        else:\n            self._linalg = math.greedy_linalg\n\n        # Secondary bodies\n        assert len(secondaries) > 0, \"There must be at least one secondary.\"\n        for sec in secondaries:\n            assert type(sec) is Secondary, (\n                \"Argument `*secondaries` must be a sequence of \"\n                \"`Secondary` instances.\"\n            )\n            assert (\n                sec._map.nw == self._primary._map.nw\n            ), \"All bodies must have the same number of wavelength bins `nw`.\"\n            assert sec._map.__props__[\"rv\"] == self._rv, (\n                \"Radial velocity must be enabled \"\n                \"for either all or none of the bodies.\"\n            )\n            assert (\n                sec._lazy == self._lazy\n            ), \"All bodies must have the same evaluation mode (lazy/greedy).\"\n\n        reflected = [sec._map.__props__[\"reflected\"] for sec in secondaries]\n        if np.all(reflected):\n            self._reflected = True\n        elif np.any(reflected):\n            raise ValueError(\n                \"Reflected light must be enabled \"\n                \"for either all or none of the secondaries.\"\n            )\n        else:\n            self._reflected = False\n        self._secondaries = secondaries\n\n        # All bodies\n        self._bodies = [self._primary] + list(self._secondaries)\n\n        # Indices of each of the bodies in the design matrix\n        Ny = [self._primary._map.Ny] + [\n            sec._map.Ny for sec in self._secondaries\n        ]\n        self._inds = []\n        cur = 0\n        for N in Ny:\n            self._inds.append(cur + np.arange(N))\n            cur += N\n\n        # Theano ops class\n        self.ops = OpsSystem(\n            self._primary,\n            self._secondaries,\n            reflected=self._reflected,\n            rv=self._rv,\n            light_delay=self._light_delay,\n            texp=self._texp,\n            oversample=self._oversample,\n            order=self._order,\n        )\n\n        # Solve stuff\n        self._flux = None\n        self._C = None\n        self._solution = None\n        self._solved_bodies = []\n\n    @property\n    def light_delay(self):\n        \"\"\"Account for the light travel time delay? *Read-only*\"\"\"\n        return self._light_delay\n\n    @property\n    def texp(self):\n        \"\"\"The exposure time in units of :py:attr:`time_unit`. *Read-only*\"\"\"\n\n    @property\n    def oversample(self):\n        \"\"\"Oversample factor when integrating over exposure time. *Read-only*\"\"\"\n        return self._oversample\n\n    @property\n    def order(self):\n        \"\"\"The order of the numerical integration scheme. *Read-only*\n\n        - ``0``: a centered Riemann sum\n        - ``1``: trapezoid rule\n        - ``2``: Simpson’s rule\n        \"\"\"\n        return self._order\n\n    @property\n    def time_unit(self):\n        \"\"\"An ``astropy.units`` unit defining the time metric for the system.\"\"\"\n        return self._time_unit\n\n    @time_unit.setter\n    def time_unit(self, value):\n        assert value.physical_type == \"time\"\n        self._time_unit = value\n        self._time_factor = value.in_units(units.day)\n\n    @property\n    def primary(self):\n        \"\"\"The primary (central) object in the Keplerian system.\"\"\"\n        return self._primary\n\n    @property\n    def secondaries(self):\n        \"\"\"A list of the secondary (orbiting) object(s) in the Keplerian system.\"\"\"\n        return self._secondaries\n\n    @property\n    def bodies(self):\n        \"\"\"A list of all objects in the Keplerian system.\"\"\"\n        return self._bodies\n\n    @property\n    def map_indices(self):\n        \"\"\"A list of the indices corresponding to each body in the design matrix.\"\"\"\n        return self._inds\n\n    def show(\n        self,\n        t,\n        cmap=\"plasma\",\n        res=300,\n        interval=75,\n        file=None,\n        figsize=(3, 3),\n        html5_video=True,\n        window_pad=1.0,\n    ):\n        \"\"\"Visualize the Keplerian system.\n\n        Note that the body surface intensities are not normalized.\n\n        Args:\n            t (scalar or vector): The time(s) at which to evaluate the orbit and\n                the map in units of :py:attr:`time_unit`.\n            cmap (string or colormap instance, optional): The matplotlib colormap\n                to use. Defaults to ``plasma``.\n            res (int, optional): The resolution of the map in pixels on a\n                side. Defaults to 300.\n            figsize (tuple, optional): Figure size in inches. Default is\n                (3, 3) for orthographic maps and (7, 3.5) for rectangular\n                maps.\n            interval (int, optional): Interval between frames in milliseconds\n                (animated maps only). Defaults to 75.\n            file (string, optional): The file name (including the extension)\n                to save the animation to (animated maps only). Defaults to None.\n            html5_video (bool, optional): If rendering in a Jupyter notebook,\n                display as an HTML5 video? Default is True. If False, displays\n                the animation using Javascript (file size will be larger.)\n            window_pad (float, optional): Padding around the primary in units\n                of the primary radius. Bodies outside of this window will be\n                cropped. Default is 1.0.\n        \"\"\"\n        # Not yet implemented\n        if self._primary._map.nw is not None:  # pragma: no cover\n            raise NotImplementedError(\n                \"Method not implemented for spectral maps.\"\n            )\n\n        # Render the maps & get the orbital positions\n        if self._rv:\n            self._primary.map._set_RV_filter()\n            for sec in self._secondaries:\n                sec.map._set_RV_filter()\n        img_pri, img_sec, x, y, z = self.ops.render(\n            self._math.reshape(self._math.to_array_or_tensor(t), [-1])\n            * self._time_factor,\n            res,\n            self._primary._r,\n            self._primary._m,\n            self._primary._prot,\n            self._primary._t0,\n            self._primary._theta0,\n            self._primary._map._inc,\n            self._primary._map._obl,\n            self._primary._map._y,\n            self._primary._map._u,\n            self._primary._map._f,\n            self._primary._map._alpha,\n            self._primary._map._tau,\n            self._primary._map._delta,\n            self._math.to_array_or_tensor(\n                [sec._r for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._m for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._prot for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._t0 for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._theta0 for sec in self._secondaries]\n            ),\n            self._get_periods(),\n            self._math.to_array_or_tensor(\n                [sec._ecc for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._w for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._Omega for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._inc for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._inc for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._obl for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._y for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._u for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._f for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._alpha for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._tau for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._delta for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._sigr for sec in self._secondaries]\n            ),\n        )\n\n        # Convert to units of the primary radiu\n        x, y, z = (\n            x / self._primary._r,\n            y / self._primary._r,\n            z / self._primary._r,\n        )\n        r = self._math.to_array_or_tensor(\n            [sec._r for sec in self._secondaries]\n        )\n        r = r / self._primary._r\n\n        # Evaluate if needed\n        if config.lazy:\n            img_pri = img_pri.eval()\n            img_sec = img_sec.eval()\n            x = x.eval()\n            y = y.eval()\n            z = z.eval()\n            r = r.eval()\n\n        # We need this to be of shape (nplanet, nframe)\n        x = x.T\n        y = y.T\n        z = z.T\n\n        # Ensure we have an array of frames\n        if len(img_pri.shape) == 3:\n            nframes = img_pri.shape[0]\n        else:  # pragma: no cover\n            nframes = 1\n            img_pri = np.reshape(img_pri, (1,) + img_pri.shape)\n            img_sec = np.reshape(img_sec, (1,) + img_sec.shape)\n        animated = nframes > 1\n\n        # Set up the plot\n        fig, ax = plt.subplots(1, figsize=figsize)\n        ax.axis(\"off\")\n        ax.set_xlim(-1.0 - window_pad, 1.0 + window_pad)\n        ax.set_ylim(-1.0 - window_pad, 1.0 + window_pad)\n\n        # Render the first frame\n        img = [None for n in range(1 + len(self._secondaries))]\n        circ = [None for n in range(1 + len(self._secondaries))]\n        extent = np.array([-1.0, 1.0, -1.0, 1.0])\n        img[0] = ax.imshow(\n            img_pri[0],\n            origin=\"lower\",\n            extent=extent,\n            cmap=cmap,\n            interpolation=\"none\",\n            vmin=np.nanmin(img_pri),\n            vmax=np.nanmax(img_pri),\n            animated=animated,\n            zorder=0.0,\n        )\n        circ[0] = plt.Circle(\n            (0, 0), 1, color=\"k\", fill=False, zorder=1e-3, lw=2\n        )\n        ax.add_artist(circ[0])\n        for i, _ in enumerate(self._secondaries):\n            extent = np.array([x[i, 0], x[i, 0], y[i, 0], y[i, 0]]) + (\n                r[i] * np.array([-1.0, 1.0, -1.0, 1.0])\n            )\n            img[i + 1] = ax.imshow(\n                img_sec[i, 0],\n                origin=\"lower\",\n                extent=extent,\n                cmap=cmap,\n                interpolation=\"none\",\n                vmin=np.nanmin(img_sec),\n                vmax=np.nanmax(img_sec),\n                animated=animated,\n                zorder=z[i, 0],\n            )\n            circ[i] = plt.Circle(\n                (x[i, 0], y[i, 0]),\n                r[i],\n                color=\"k\",\n                fill=False,\n                zorder=z[i, 0] + 1e-3,\n                lw=2,\n            )\n            ax.add_artist(circ[i])\n\n        # Animation\n        if animated:\n\n            def updatefig(k):\n\n                # Update Primary map\n                img[0].set_array(img_pri[k])\n\n                # Update Secondary maps & positions\n                for i, _ in enumerate(self._secondaries):\n                    extent = np.array([x[i, k], x[i, k], y[i, k], y[i, k]]) + (\n                        r[i] * np.array([-1.0, 1.0, -1.0, 1.0])\n                    )\n                    if np.any(np.abs(extent) < 1.0 + window_pad):\n                        img[i + 1].set_array(img_sec[i, k])\n                        img[i + 1].set_extent(extent)\n                        img[i + 1].set_zorder(z[i, k])\n                        circ[i].center = (x[i, k], y[i, k])\n                        circ[i].set_zorder(z[i, k] + 1e-3)\n\n                return img + circ\n\n            ani = FuncAnimation(\n                fig, updatefig, interval=interval, blit=False, frames=nframes\n            )\n\n            # Business as usual\n            if (file is not None) and (file != \"\"):\n                if file.endswith(\".mp4\"):\n                    ani.save(file, writer=\"ffmpeg\")\n                elif file.endswith(\".gif\"):\n                    ani.save(file, writer=\"imagemagick\")\n                else:  # pragma: no cover\n                    # Try and see what happens!\n                    ani.save(file)\n                plt.close()\n            else:  # pragma: no cover\n                try:\n                    if \"zmqshell\" in str(type(get_ipython())):\n                        plt.close()\n                        if html5_video:\n                            display(HTML(ani.to_html5_video()))\n                        else:\n                            display(HTML(ani.to_jshtml()))\n                    else:\n                        raise NameError(\"\")\n                except NameError:\n                    plt.show()\n                    plt.close()\n\n            # Matplotlib generates an annoying empty\n            # file when producing an animation. Delete it.\n            try:\n                os.remove(\"None0000000.png\")\n            except FileNotFoundError:\n                pass\n\n        else:\n\n            if (file is not None) and (file != \"\"):\n                fig.savefig(file)\n                plt.close()\n            else:  # pragma: no cover\n                plt.show()\n\n        if self._rv:\n            self._primary.map._unset_RV_filter()\n            for sec in self._secondaries:\n                sec.map._unset_RV_filter()\n\n    def design_matrix(self, t):\n        \"\"\"Compute the system flux design matrix at times ``t``.\n\n        .. note::\n\n            This is the *unweighted* design matrix, i.e., it does not\n            include the scaling by the amplitude of each body's map.\n            To perform this weighting, do\n\n            .. code-block:: python\n\n                X = sys.design_matrix(**kwargs)\n                for i, body in zip(sys.map_indices, sys.bodies):\n                    X[:, i] *= body.map.amp\n\n        Args:\n            t (scalar or vector): An array of times at which to evaluate\n                the design matrix in units of :py:attr:`time_unit`.\n        \"\"\"\n        return self.ops.X(\n            self._math.reshape(self._math.to_array_or_tensor(t), [-1])\n            * self._time_factor,\n            self._primary._r,\n            self._primary._m,\n            self._primary._prot,\n            self._primary._t0,\n            self._primary._theta0,\n            self._math.to_array_or_tensor(1.0),\n            self._primary._map._inc,\n            self._primary._map._obl,\n            self._primary._map._u,\n            self._primary._map._f,\n            self._primary._map._alpha,\n            self._primary._map._tau,\n            self._primary._map._delta,\n            self._math.to_array_or_tensor(\n                [sec._r for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._m for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._prot for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._t0 for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._theta0 for sec in self._secondaries]\n            ),\n            self._get_periods(),\n            self._math.to_array_or_tensor(\n                [sec._ecc for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._w for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._Omega for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._inc for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [\n                    self._math.to_array_or_tensor(1.0)\n                    for sec in self._secondaries\n                ]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._inc for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._obl for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._u for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._f for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._alpha for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._tau for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._delta for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._sigr for sec in self._secondaries]\n            ),\n        )\n\n    def flux(self, t, total=True):\n        \"\"\"Compute the system flux at times ``t``.\n\n        Args:\n            t (scalar or vector): An array of times at which to evaluate\n                the flux in units of :py:attr:`time_unit`.\n            total (bool, optional): Return the total system flux? Defaults to\n                True. If False, returns arrays corresponding to the flux\n                from each body.\n        \"\"\"\n        X = self.design_matrix(t)\n\n        # Weight the ylms by amplitude\n        if self._reflected:\n            # If we're doing reflected light, scale the amplitude of\n            # each of the secondaries by the amplitude of the primary\n            # (the illumination source).\n            ay = [self._primary.map.amp * self._primary._map._y] + [\n                self._primary.map.amp * body.map.amp * body._map._y\n                for body in self._secondaries\n            ]\n        else:\n            ay = [body.map.amp * body._map._y for body in self._bodies]\n\n        if total:\n            return self._math.dot(X, self._math.concatenate(ay))\n        else:\n            return [\n                self._math.dot(X[:, idx], ay[i])\n                for i, idx in enumerate(self._inds)\n            ]\n\n    def rv(self, t, keplerian=True, total=True):\n        \"\"\"Compute the observed radial velocity of the system at times ``t``.\n\n        Args:\n            t (scalar or vector): An array of times at which to evaluate\n                the radial velocity in units of :py:attr:`time_unit`.\n            keplerian (bool): Include the Keplerian component of the radial\n                velocity of the primary? Default is True. If False, this\n                method returns a model for only the radial velocity anomaly\n                due to transits (the Rossiter-McLaughlin effect) and\n                time-variable surface features (Doppler tomography) for all\n                bodies in the system.\n            total (bool, optional): Return the total system RV? Defaults to\n                True. If False, returns arrays corresponding to the RV\n                contribution from each body.\n\n        \"\"\"\n        rv = self.ops.rv(\n            self._math.reshape(self._math.to_array_or_tensor(t), [-1])\n            * self._time_factor,\n            self._primary._r,\n            self._primary._m,\n            self._primary._prot,\n            self._primary._t0,\n            self._primary._theta0,\n            self._primary._map._amp,\n            self._primary._map._inc,\n            self._primary._map._obl,\n            self._primary._map._y,\n            self._primary._map._u,\n            self._primary._map._alpha,\n            self._primary._map._tau,\n            self._primary._map._delta,\n            self._primary._map._veq,\n            self._math.to_array_or_tensor(\n                [sec._r for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._m for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._prot for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._t0 for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._theta0 for sec in self._secondaries]\n            ),\n            self._get_periods(),\n            self._math.to_array_or_tensor(\n                [sec._ecc for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._w for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._Omega for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._inc for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._amp for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._inc for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._obl for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._y for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._u for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._alpha for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._tau for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._delta for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._sigr for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._map._veq for sec in self._secondaries]\n            ),\n            np.array(keplerian),\n        )\n        if total:\n            return self._math.sum(rv, axis=0)\n        else:\n            return rv\n\n    def position(self, t):\n        \"\"\"Compute the Cartesian positions of all bodies at times ``t``.\n\n        Args:\n            t (scalar or vector): An array of times at which to evaluate\n                the position in units of :py:attr:`time_unit`.\n        \"\"\"\n        x, y, z = self.ops.position(\n            self._math.reshape(self._math.to_array_or_tensor(t), [-1])\n            * self._time_factor,\n            self._primary._m,\n            self._primary._t0,\n            self._math.to_array_or_tensor(\n                [sec._m for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._t0 for sec in self._secondaries]\n            ),\n            self._get_periods(),\n            self._math.to_array_or_tensor(\n                [sec._ecc for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._w for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._Omega for sec in self._secondaries]\n            ),\n            self._math.to_array_or_tensor(\n                [sec._inc for sec in self._secondaries]\n            ),\n        )\n        fac = np.reshape(\n            [self._primary._length_factor]\n            + [sec._length_factor for sec in self._secondaries],\n            [-1, 1],\n        )\n        return (x / fac, y / fac, z / fac)\n\n    def _get_periods(self):\n        periods = [None for sec in self._secondaries]\n        for i, sec in enumerate(self._secondaries):\n            if sec.porb:\n                periods[i] = sec.porb\n            else:\n                periods[i] = (\n                    (2 * np.pi)\n                    * sec._a ** (3 / 2)\n                    / (self._math.sqrt(G_grav * (self._primary._m + sec._m)))\n                )\n        return self._math.to_array_or_tensor(periods)\n\n    def set_data(self, flux, C=None, cho_C=None):\n        \"\"\"Set the data vector and covariance matrix.\n\n        This method is required by the :py:meth:`solve` method, which\n        analytically computes the posterior over surface maps for all bodies\n        in the system given a dataset and a prior, provided both are described\n        as multivariate Gaussians.\n\n        Args:\n            flux (vector): The observed system light curve.\n            C (scalar, vector, or matrix): The data covariance. This may be\n                a scalar, in which case the noise is assumed to be\n                homoscedastic, a vector, in which case the covariance\n                is assumed to be diagonal, or a matrix specifying the full\n                covariance of the dataset. Default is None. Either `C` or\n                `cho_C` must be provided.\n            cho_C (matrix): The lower Cholesky factorization of the data\n                covariance matrix. Defaults to None. Either `C` or\n                `cho_C` must be provided.\n        \"\"\"\n        self._flux = self._math.cast(flux)\n        self._C = self._linalg.Covariance(\n            C=C, cho_C=cho_C, N=self._flux.shape[0]\n        )\n\n    def solve(self, *, design_matrix=None, t=None):\n        \"\"\"Solve the least-squares problem for the posterior over maps for all bodies.\n\n        This method solves the generalized least squares problem given a system\n        light curve and its covariance (set via the :py:meth:`set_data` method)\n        and a Gaussian prior on the spherical harmonic coefficients\n        (set via the :py:meth:`set_prior` method). The map amplitudes and\n        coefficients of each of the bodies in the system are then set to the\n        maximum a posteriori (MAP) solution.\n\n        Args:\n            design_matrix (matrix, optional): The flux design matrix, the\n                quantity returned by :py:meth:`design_matrix`. Default is\n                None, in which case this is computed based on ``kwargs``.\n            t (vector, optional): The vector of times at which to evaluate\n                :py:meth:`design_matrix`, if a design matrix is not provided.\n                Default is None.\n\n        Returns:\n            The posterior mean for the spherical harmonic \\\n            coefficients `l > 0` and the Cholesky factorization of the \\\n            posterior covariance of all of the bodies in the system, \\\n            stacked in order (primary, followed by each of the secondaries \\\n            in the order they were provided.)\n\n        .. note::\n            Users may call the :py:meth:`draw` method of this class to draw\n            from the posterior after calling :py:meth:`solve`.\n        \"\"\"\n        # TODO: Implement for spectral maps?\n        self._no_spectral()\n\n        # Check that the data is set\n        if self._flux is None or self._C is None:\n            raise ValueError(\"Please provide a dataset with `set_data()`.\")\n\n        # Get the full design matrix\n        if design_matrix is None:\n            assert t is not None, \"Please provide a time vector `t`.\"\n            design_matrix = self.design_matrix(t)\n        X = self._math.cast(design_matrix)\n\n        # Get the data vector\n        f = self._math.cast(self._flux)\n\n        # Check for bodies whose priors are set\n        self._solved_bodies = []\n        inds = []\n        dense_L = False\n        for k, body in enumerate(self._bodies):\n\n            if body.map._mu is None or body.map._L is None:\n\n                # Subtract out this term from the data vector,\n                # since it is fixed\n                f -= body.map.amp * self._math.dot(\n                    X[:, self._inds[k]], body.map.y\n                )\n\n            else:\n\n                # Add to our list of indices/bodies to solve for\n                inds.extend(self._inds[k])\n                self._solved_bodies.append(body)\n                if body.map._L.kind in [\"matrix\", \"cholesky\"]:\n                    dense_L = True\n\n        # Do we have at least one body?\n        if len(self._solved_bodies) == 0:\n            raise ValueError(\"Please provide a prior for at least one body.\")\n\n        # Keep only the terms we'll solve for\n        X = X[:, inds]\n\n        # Stack our priors\n        mu = self._math.concatenate(\n            [body.map._mu for body in self._solved_bodies]\n        )\n\n        if not dense_L:\n            # We can just concatenate vectors\n            LInv = self._math.concatenate(\n                [\n                    body.map._L.inverse * self._math.ones(body.map.Ny)\n                    for body in self._solved_bodies\n                ]\n            )\n        else:\n            # FACT: The inverse of a block diagonal matrix\n            # is the block diagonal matrix of the inverses.\n            LInv = self._math.block_diag(\n                *[\n                    body.map._L.inverse * self._math.eye(body.map.Ny)\n                    for body in self._solved_bodies\n                ]\n            )\n\n        # Compute the MAP solution\n        self._solution = self._linalg.solve(X, f, self._C.cholesky, mu, LInv)\n\n        # Set all the map vectors\n        x, cho_cov = self._solution\n        n = 0\n        for body in self._solved_bodies:\n            inds = slice(n, n + body.map.Ny)\n            body.map.amp = x[inds][0]\n            body.map[1:, :] = x[inds][1:] / body.map.amp\n            n += body.map.Ny\n\n        # Return the mean and covariance\n        self._solution = (x, cho_cov)\n        return self._solution\n\n    @property\n    def solution(self):\n        r\"\"\"The posterior probability distribution for the maps in the system.\n\n        This is a tuple containing the mean and lower Cholesky factorization of the\n        covariance of the amplitude-weighted spherical harmonic coefficient vectors,\n        obtained by solving the regularized least-squares problem\n        via the :py:meth:`solve` method.\n\n        Note that to obtain the actual covariance matrix from the lower Cholesky\n        factorization :math:`L`, simply compute :math:`L L^\\top`.\n\n        Note also that this is the posterior for the **amplitude-weighted**\n        map vectors. Under this convention, the map amplitude is equal to the\n        first term of the vector of each body and the spherical harmonic coefficients are\n        equal to the vector normalized by the first term.\n        \"\"\"\n        if self._solution is None:\n            raise ValueError(\"Please call `solve()` first.\")\n        return self._solution\n\n    def draw(self):\n        \"\"\"\n        Draw a map from the posterior distribution and set\n        the :py:attr:`y` map vector of each body.\n\n        Users should call :py:meth:`solve` to enable this attribute.\n        \"\"\"\n        if self._solution is None:\n            raise ValueError(\"Please call `solve()` first.\")\n\n        # Number of coefficients\n        N = np.sum([body.map.Ny for body in self._solved_bodies])\n\n        # Fast multivariate sampling using the Cholesky factorization\n        yhat, cho_ycov = self._solution\n        u = self._math.cast(np.random.randn(N))\n        x = yhat + self._math.dot(cho_ycov, u)\n\n        # Set all the map vectors\n        n = 0\n        for body in self._solved_bodies:\n            inds = slice(n, n + body.map.Ny)\n            body.map.amp = x[inds][0]\n            body.map[1:, :] = x[inds][1:] / body.map.amp\n            n += body.map.Ny\n\n    def lnlike(self, *, design_matrix=None, t=None, woodbury=True):\n        \"\"\"Returns the log marginal likelihood of the data given a design matrix.\n\n        This method computes the marginal likelihood (marginalized over the\n        spherical harmonic coefficients of all bodies) given a system\n        light curve and its covariance (set via the :py:meth:`set_data` method)\n        and a Gaussian prior on the spherical harmonic coefficients\n        (set via the :py:meth:`set_prior` method).\n\n        Args:\n            design_matrix (matrix, optional): The flux design matrix, the\n                quantity returned by :py:meth:`design_matrix`. Default is\n                None, in which case this is computed based on ``kwargs``.\n            t (vector, optional): The vector of times at which to evaluate\n                :py:meth:`design_matrix`, if a design matrix is not provided.\n                Default is None.\n            woodbury (bool, optional): Solve the linear problem using the\n                Woodbury identity? Default is True. The\n                `Woodbury identity <https://en.wikipedia.org/wiki/Woodbury_matrix_identity>`_\n                is used to speed up matrix operations in the case that the\n                number of data points is much larger than the number of\n                spherical harmonic coefficients. In this limit, it can\n                speed up the code by more than an order of magnitude. Keep\n                in mind that the numerical stability of the Woodbury identity\n                is not great, so if you're getting strange results try\n                disabling this. It's also a good idea to disable this in the\n                limit of few data points and large spherical harmonic degree.\n\n        Returns:\n            lnlike: The log marginal likelihood.\n        \"\"\"\n        # TODO: Implement for spectral maps?\n        self._no_spectral()\n\n        # Check that the data is set\n        if self._flux is None or self._C is None:\n            raise ValueError(\"Please provide a dataset with `set_data()`.\")\n\n        # Get the full design matrix\n        if design_matrix is None:\n            assert t is not None, \"Please provide a time vector `t`.\"\n            design_matrix = self.design_matrix(t)\n        X = self._math.cast(design_matrix)\n\n        # Get the data vector\n        f = self._math.cast(self._flux)\n\n        # Check for bodies whose priors are set\n        self._solved_bodies = []\n        inds = []\n        dense_L = False\n        for k, body in enumerate(self._bodies):\n\n            if body.map._mu is None or body.map._L is None:\n\n                # Subtract out this term from the data vector,\n                # since it is fixed\n                f -= body.map.amp * self._math.dot(\n                    X[:, self._inds[k]], body.map.y\n                )\n\n            else:\n\n                # Add to our list of indices/bodies to solve for\n                inds.extend(self._inds[k])\n                self._solved_bodies.append(body)\n                if body.map._L.kind in [\"matrix\", \"cholesky\"]:\n                    dense_L = True\n\n        # Do we have at least one body?\n        if len(self._solved_bodies) == 0:\n            raise ValueError(\"Please provide a prior for at least one body.\")\n\n        # Keep only the terms we'll solve for\n        X = X[:, inds]\n\n        # Stack our priors\n        mu = self._math.concatenate(\n            [body.map._mu for body in self._solved_bodies]\n        )\n\n        # Compute the likelihood\n        if woodbury:\n            if not dense_L:\n                # We can just concatenate vectors\n                LInv = self._math.concatenate(\n                    [\n                        body.map._L.inverse * self._math.ones(body.map.Ny)\n                        for body in self._solved_bodies\n                    ]\n                )\n            else:\n                LInv = self._math.block_diag(\n                    *[\n                        body.map._L.inverse * self._math.eye(body.map.Ny)\n                        for body in self._solved_bodies\n                    ]\n                )\n            lndetL = self._math.cast(\n                [body.map._L.lndet for body in self._solved_bodies]\n            )\n            return self._linalg.lnlike_woodbury(\n                X, f, self._C.inverse, mu, LInv, self._C.lndet, lndetL\n            )\n        else:\n            if not dense_L:\n                # We can just concatenate vectors\n                L = self._math.concatenate(\n                    [\n                        body.map._L.value * self._math.ones(body.map.Ny)\n                        for body in self._solved_bodies\n                    ]\n                )\n            else:\n                L = self._math.block_diag(\n                    *[\n                        body.map._L.value * self._math.eye(body.map.Ny)\n                        for body in self._solved_bodies\n                    ]\n                )\n            return self._linalg.lnlike(X, f, self._C.value, mu, L)\n", "meta": {"hexsha": "c4042b4ad12a26f7ba8010f3f90059ac4f74e79d", "size": 51470, "ext": "py", "lang": "Python", "max_stars_repo_path": "starry/kepler.py", "max_stars_repo_name": "fbartolic/starry", "max_stars_repo_head_hexsha": "d50576caf964ad925c490c9f3ffe1273ab155397", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "starry/kepler.py", "max_issues_repo_name": "fbartolic/starry", "max_issues_repo_head_hexsha": "d50576caf964ad925c490c9f3ffe1273ab155397", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "starry/kepler.py", "max_forks_repo_name": "fbartolic/starry", "max_forks_repo_head_hexsha": "d50576caf964ad925c490c9f3ffe1273ab155397", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9176552687, "max_line_length": 93, "alphanum_fraction": 0.5465513892, "include": true, "reason": "import numpy,from astropy", "num_tokens": 11860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.2689414330889797, "lm_q1q2_score": 0.16141551361612932}}
{"text": "\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\n# Dependency imports\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import tensor_array_ops\nfrom tensorflow_probability.python import distributions\nfrom tensorflow_probability.python.internal import distribution_util\nfrom tensorflow_probability.python.mcmc import kernel as kernel_base\nfrom tensorflow_probability.python.mcmc import metropolis_hastings\nfrom tensorflow_probability.python.mcmc.internal import util as mcmc_util\nfrom tensorflow.python.util import deprecation  # pylint: disable=g-direct-tensorflow-import\n\nfrom inspect import signature\n\nfrom GeneralLeapfrogIntegrator import GeneralLeapfrogIntegrator\n\nUncalibratedRiemannManifoldHamiltonianMonteCarloKernelResults = collections.namedtuple(\n    'UncalibratedRiemannManifoldHamiltonianMonteCarloKernelResults',\n    [\n        'log_acceptance_correction',\n        'target_log_prob',        # For \"next_state\".\n        'step_size',\n        'num_leapfrog_steps',\n    ])\n\nRiemannManifoldHamiltonianMonteCarloExtraKernelResults = collections.namedtuple(\n    'HamiltonianMonteCarloExtraKernelResults',\n    [\n        'step_size_assign',\n    ])\n\nclass RiemannManifoldHamiltonianMonteCarlo(kernel_base.TransitionKernel):\n  \n  @deprecation.deprecated_args(\n      '2019-05-22', 'The `step_size_update_fn` argument is deprecated. Use '\n      '`tfp.mcmc.SimpleStepSizeAdaptation` instead.', 'step_size_update_fn')\n  def __init__(self,\n               target_log_prob_fn,\n               step_size,\n               num_leapfrog_steps,\n               state_gradients_are_stopped=False,\n               step_size_update_fn=None,\n               seed=None,\n               store_parameters_in_results=False,\n               name=None):\n    \"\"\"Initializes this transition kernel.\n    Args:\n      target_log_prob_fn: Python callable which takes an argument like\n        `current_state` (or `*current_state` if it's a list) and returns its\n        (possibly unnormalized) log-density under the target distribution.\n      step_size: `Tensor` or Python `list` of `Tensor`s representing the step\n        size for the leapfrog integrator. Must broadcast with the shape of\n        `current_state`. Larger step sizes lead to faster progress, but\n        too-large step sizes make rejection exponentially more likely. When\n        possible, it's often helpful to match per-variable step sizes to the\n        standard deviations of the target distribution in each variable.\n      num_leapfrog_steps: Integer number of steps to run the leapfrog integrator\n        for. Total progress per HMC step is roughly proportional to\n        `step_size * num_leapfrog_steps`.\n      state_gradients_are_stopped: Python `bool` indicating that the proposed\n        new state be run through `tf.stop_gradient`. This is particularly useful\n        when combining optimization over samples from the HMC chain.\n        Default value: `False` (i.e., do not apply `stop_gradient`).\n      step_size_update_fn: Python `callable` taking current `step_size`\n        (typically a `tf.Variable`) and `kernel_results` (typically\n        `collections.namedtuple`) and returns updated step_size (`Tensor`s).\n        Default value: `None` (i.e., do not update `step_size` automatically).\n      seed: Python integer to seed the random number generator.\n      store_parameters_in_results: If `True`, then `step_size` and\n        `num_leapfrog_steps` are written to and read from eponymous fields in\n        the kernel results objects returned from `one_step` and\n        `bootstrap_results`. This allows wrapper kernels to adjust those\n        parameters on the fly. This is incompatible with `step_size_update_fn`,\n        which must be set to `None`.\n      name: Python `str` name prefixed to Ops created by this function.\n        Default value: `None` (i.e., 'hmc_kernel').\n    \"\"\"\n    if step_size_update_fn and store_parameters_in_results:\n      raise ValueError('It is invalid to simultaneously specify '\n                       '`step_size_update_fn` and set '\n                       '`store_parameters_in_results` to `True`.')\n\n    impl = metropolis_hastings.MetropolisHastings(\n        inner_kernel=UncalibratedRiemannManifoldHamiltonianMonteCarlo(\n            target_log_prob_fn=target_log_prob_fn,\n            step_size=step_size,\n            num_leapfrog_steps=num_leapfrog_steps,\n            state_gradients_are_stopped=state_gradients_are_stopped,\n            seed=seed,\n            name='rm_hmc_kernel' if name is None else name,\n            store_parameters_in_results=store_parameters_in_results),\n        seed=seed)\n    parameters = impl.inner_kernel.parameters.copy()\n\n    parameters['step_size_update_fn'] = step_size_update_fn\n    self._impl = impl\n    self._parameters = parameters\n\n\n  @property\n  def target_log_prob_fn(self):\n    return self._impl.inner_kernel.target_log_prob_fn\n\n  @property\n  def step_size(self):\n    \"\"\"Returns the step_size parameter.\n    If `store_parameters_in_results` argument to the initializer was set to\n    `True`, this only returns the value of the `step_size` placed in the kernel\n    results by the `bootstrap_results` method. The actual step size in that\n    situation is governed by the `previous_kernel_results` argument to\n    `one_step` method.\n    Returns:\n      step_size: A floating point `Tensor` or a list of such `Tensors`.\n    \"\"\"\n    return self._impl.inner_kernel.step_size\n\n  @property\n  def num_leapfrog_steps(self):\n    \"\"\"Returns the num_leapfrog_steps parameter.\n    If `store_parameters_in_results` argument to the initializer was set to\n    `True`, this only returns the value of the `num_leapfrog_steps` placed in\n    the kernel results by the `bootstrap_results` method. The actual\n    `num_leapfrog_steps` in that situation is governed by the\n    `previous_kernel_results` argument to `one_step` method.\n    Returns:\n      num_leapfrog_steps: An integer `Tensor`.\n    \"\"\"\n    return self._impl.inner_kernel.num_leapfrog_steps\n\n  @property\n  def state_gradients_are_stopped(self):\n    return self._impl.inner_kernel.state_gradients_are_stopped\n\n  @property\n  def step_size_update_fn(self):\n    return self._parameters['step_size_update_fn']\n\n  @property\n  def seed(self):\n    return self._impl.inner_kernel.seed\n\n  @property\n  def name(self):\n    return self._impl.inner_kernel.name\n\n  @property\n  def parameters(self):\n    \"\"\"Return `dict` of ``__init__`` arguments and their values.\"\"\"\n    return self._parameters\n\n  @property\n  def is_calibrated(self):\n    return True\n\n  #@tf.function\n  def one_step(self, current_state, previous_kernel_results):\n    \"\"\"Runs one iteration of Hamiltonian Monte Carlo.\n    Args:\n      current_state: `Tensor` or Python `list` of `Tensor`s representing the\n        current state(s) of the Markov chain(s). The first `r` dimensions index\n        independent chains, `r = tf.rank(target_log_prob_fn(*current_state))`.\n      previous_kernel_results: `collections.namedtuple` containing `Tensor`s\n        representing values from previous calls to this function (or from the\n        `bootstrap_results` function.)\n    Returns:\n      next_state: Tensor or Python list of `Tensor`s representing the state(s)\n        of the Markov chain(s) after taking exactly one step. Has same type and\n        shape as `current_state`.\n      kernel_results: `collections.namedtuple` of internal calculations used to\n        advance the chain.\n    Raises:\n      ValueError: if there isn't one `step_size` or a list with same length as\n        `current_state`.\n    \"\"\"\n    previous_step_size_assign = (\n        [] if self.step_size_update_fn is None\n        else (previous_kernel_results.extra.step_size_assign\n              if mcmc_util.is_list_like(\n                  previous_kernel_results.extra.step_size_assign)\n              else [previous_kernel_results.extra.step_size_assign]))\n\n    with tf.control_dependencies(previous_step_size_assign):\n      next_state, kernel_results = self._impl.one_step(\n          current_state, previous_kernel_results)\n      if self.step_size_update_fn is not None:\n        step_size_assign = self.step_size_update_fn(  # pylint: disable=not-callable\n            self.step_size, kernel_results)\n        kernel_results = kernel_results._replace(\n            extra=RiemannManifoldHamiltonianMonteCarloExtraKernelResults(\n                step_size_assign=step_size_assign))\n\n    return next_state, kernel_results\n\n  def bootstrap_results(self, init_state):\n    \"\"\"Creates initial `previous_kernel_results` using a supplied `state`.\"\"\"\n    kernel_results = self._impl.bootstrap_results(init_state)\n    if self.step_size_update_fn is not None:\n      step_size_assign = self.step_size_update_fn(self.step_size, None)  # pylint: disable=not-callable\n      kernel_results = kernel_results._replace(\n          extra=RiemannManifoldHamiltonianMonteCarloExtraKernelResults(\n              step_size_assign=step_size_assign))\n    return kernel_results\n\n\nclass UncalibratedRiemannManifoldHamiltonianMonteCarlo(kernel_base.TransitionKernel):\n  \"\"\"Runs one step of Uncalibrated Hamiltonian Monte Carlo.\n  Warning: this kernel will not result in a chain which converges to the\n  `target_log_prob`. To get a convergent MCMC, use `HamiltonianMonteCarlo(...)`\n  or `MetropolisHastings(UncalibratedHamiltonianMonteCarlo(...))`.\n  For more details on `UncalibratedHamiltonianMonteCarlo`, see\n  `HamiltonianMonteCarlo`.\n  \"\"\"\n\n  def __init__(self,\n               target_log_prob_fn,\n               step_size,\n               num_leapfrog_steps,\n               state_gradients_are_stopped=False,\n               seed=None,\n               store_parameters_in_results=False,\n               name=None):\n    \"\"\"Initializes this transition kernel.\n    Args:\n      target_log_prob_fn: Python callable which takes an argument like\n        `current_state` (or `*current_state` if it's a list) and returns its\n        (possibly unnormalized) log-density under the target distribution.\n      step_size: `Tensor` or Python `list` of `Tensor`s representing the step\n        size for the leapfrog integrator. Must broadcast with the shape of\n        `current_state`. Larger step sizes lead to faster progress, but\n        too-large step sizes make rejection exponentially more likely. When\n        possible, it's often helpful to match per-variable step sizes to the\n        standard deviations of the target distribution in each variable.\n      num_leapfrog_steps: Integer number of steps to run the leapfrog integrator\n        for. Total progress per HMC step is roughly proportional to\n        `step_size * num_leapfrog_steps`.\n      state_gradients_are_stopped: Python `bool` indicating that the proposed\n        new state be run through `tf.stop_gradient`. This is particularly useful\n        when combining optimization over samples from the HMC chain.\n        Default value: `False` (i.e., do not apply `stop_gradient`).\n      seed: Python integer to seed the random number generator.\n      store_parameters_in_results: If `True`, then `step_size` and\n        `num_leapfrog_steps` are written to and read from eponymous fields in\n        the kernel results objects returned from `one_step` and\n        `bootstrap_results`. This allows wrapper kernels to adjust those\n        parameters on the fly.\n      name: Python `str` name prefixed to Ops created by this function.\n        Default value: `None` (i.e., 'hmc_kernel').\n    \"\"\"\n    if seed is not None and tf.executing_eagerly():\n      # TODO(b/68017812): Re-enable once TFE supports `tf.random_shuffle` seed.\n      raise NotImplementedError('Specifying a `seed` when running eagerly is '\n                                'not currently supported. To run in Eager '\n                                'mode with a seed, use `tf.set_random_seed`.')\n    self._seed_stream = distributions.SeedStream(seed, 'hmc_one_step')\n    if not store_parameters_in_results:\n      mcmc_util.warn_if_parameters_are_not_simple_tensors(\n          dict(step_size=step_size, num_leapfrog_steps=num_leapfrog_steps))\n    self._parameters = dict(\n        target_log_prob_fn=target_log_prob_fn,\n        step_size=step_size,\n        num_leapfrog_steps=num_leapfrog_steps,\n        state_gradients_are_stopped=state_gradients_are_stopped,\n        seed=seed,\n        name=name,\n        store_parameters_in_results=store_parameters_in_results,\n    )\n    self._momentum_dtype = None\n\n  @property\n  def target_log_prob_fn(self):\n    return self._parameters['target_log_prob_fn']\n\n  @property\n  def step_size(self):\n    \"\"\"Returns the step_size parameter.\n    If `store_parameters_in_results` argument to the initializer was set to\n    `True`, this only returns the value of the `step_size` placed in the kernel\n    results by the `bootstrap_results` method. The actual step size in that\n    situation is governed by the `previous_kernel_results` argument to\n    `one_step` method.\n    Returns:\n      step_size: A floating point `Tensor` or a list of such `Tensors`.\n    \"\"\"\n    return self._parameters['step_size']\n\n  @property\n  def num_leapfrog_steps(self):\n    \"\"\"Returns the num_leapfrog_steps parameter.\n    If `store_parameters_in_results` argument to the initializer was set to\n    `True`, this only returns the value of the `num_leapfrog_steps` placed in\n    the kernel results by the `bootstrap_results` method. The actual\n    `num_leapfrog_steps` in that situation is governed by the\n    `previous_kernel_results` argument to `one_step` method.\n    Returns:\n      num_leapfrog_steps: An integer `Tensor`.\n    \"\"\"\n    return self._parameters['num_leapfrog_steps']\n\n  @property\n  def state_gradients_are_stopped(self):\n    return self._parameters['state_gradients_are_stopped']\n\n  @property\n  def seed(self):\n    return self._parameters['seed']\n\n  @property\n  def name(self):\n    return self._parameters['name']\n\n  @property\n  def parameters(self):\n    \"\"\"Return `dict` of ``__init__`` arguments and their values.\"\"\"\n    return self._parameters\n\n  @property\n  def is_calibrated(self):\n    return False\n\n  @property\n  def _store_parameters_in_results(self):\n    return self._parameters['store_parameters_in_results']\n\n  def expand(self, current):\n    \"\"\"Expands tensors to that they are of rank 2\n\n    Arguments:\n        * current: tensor to expand\n    Returns:\n        * expanded: expanded tensor\n\n    \"\"\"\n    currentShape=tf.pad(\n            tf.shape(current),\n            paddings=[[tf.where(tf.rank(current) > 1, 0, 1), 0]],\n            constant_values=1)\n    expanded=tf.reshape(current, currentShape)\n    return(expanded)\n  \n  #@tf.function\n  def get_hessian(self, argv):\n          n = None\n          gradeint=None\n          _gradients=None\n          #G = None\n          tensorList = []\n          for x in range(len(argv)):\n              tensorList.append(argv[x])\n          with tf.GradientTape(persistent=True, watch_accessed_variables=False) as SecondTape:\n              for x in tensorList:     \n                  SecondTape.watch(x)\n              with tf.GradientTape(persistent=False, watch_accessed_variables=False) as FirstTape:\n                  FirstTape.watch(tensorList)\n                  argv = tensorList\n                  theta = []\n                  index = 0\n                  for info in self.restoreShapes:\n                      theta.append(tf.reshape(argv[index:index + info[1]], info[0]))\n                      index += info[1]\n                  potential = self.target_log_prob_fn(*theta)\n              _gradients = FirstTape.gradient(potential, tensorList, unconnected_gradients=tf.UnconnectedGradients.NONE)\n              SecondTape.watch(_gradients)\n              #gradient=tf.convert_to_tensor(_gradients)\n              gradient=tf.stack(_gradients)\n              #n = array_ops.size(tensorList)\n              n=len(tensorList)\n          \"\"\"\n          loop_vars = [\n                  array_ops.constant(0, tf.int32),\n                  tensor_array_ops.TensorArray(tf.float32, n)\n          ]\n\n          gradientIter=iter(_gradients)\n          _, hessian = control_flow_ops.while_loop(\n              lambda j, _: j < n,\n              lambda j, result: (j + 1,\n                         result.write(j, SecondTape.gradient(next(gradientIter), tensorList, unconnected_gradients=tf.UnconnectedGradients.ZERO))),\n              loop_vars\n          )\n          \"\"\"\n        \n          hessian = SecondTape.jacobian(gradient, tensorList, unconnected_gradients=tf.UnconnectedGradients.ZERO)\n          #_shape = array_ops.shape(tensorList)\n          #_reshaped_hessian = array_ops.reshape(hessian.stack(),\n          #                                         array_ops.concat((_shape, _shape), 0))\n          #hessians = _reshaped_hessian\n          #G = -hessians\n          #print(hessian)\n          G=-tf.convert_to_tensor(hessian)\n          #print(G)\n        \n          \"\"\"\n          loop_vars = [\n                array_ops.constant(0, tf.int32),\n                tensor_array_ops.TensorArray(tf.float32, n)\n            ]\n          #print(gradient)\n          #print(n)\n          for x in range(n):\n                #print(gradient[x])\n          #print(gradient[0])\n          #print(gradient[1])\n          _, hessian = control_flow_ops.while_loop(\n                lambda j, _: j < n,\n                lambda j, result: (j + 1,\n                                   result.write(j, SecondTape.gradient(gradient[j], tensorList, unconnected_gradients=tf.UnconnectedGradients.ZERO))),\n                loop_vars\n          )\n        \n          _shape = array_ops.shape(tensorList)\n          _reshaped_hessian = array_ops.reshape(hessian.stack(),\n                                                   array_ops.concat((_shape, _shape), 0))\n          hessians = _reshaped_hessian\n          G = -hessians\n          \"\"\"\n            \n            \n            \n          # Compute first-order derivatives and iterate for each x in xs.\n          \"\"\"\n          hessians = []\n          _gradients = gradients(ys, xs, **kwargs)\n          for gradient, x in zip(_gradients, xs):\n            # change shape to one-dimension without graph branching\n            gradient = array_ops.reshape(gradient, [-1])\n\n            # Declare an iterator and tensor array loop variables for the gradients.\n            \n            # Iterate over all elements of the gradient and compute second order\n            # derivatives.\n          \"\"\"\n        \n        \n        \n        \n          \n          return(G, potential)\n\n  #@tf.function          \n  def hamiltonian_energy_fn(self, *argv):\n      #print()\n      G,potential=self.get_hessian(argv)\n      #print(\"potential\", potential)\n      #print()\n      #print(G)\n      #smallG=tf.minimum(G, 1e6)\n      #smallG=tf.maximum(smallG, -1e6)  \n\n      #condG=tf.reduce_any(tf.math.not_equal(G, smallG))\n      #G = smallG\n      s, u, v = tf.linalg.svd(G)\n      safeInvS=1/(tf.where(tf.reduce_any(tf.math.equal(s,0)), tf.ones_like(s),s))\n      safeLog=tf.math.log(tf.where(tf.reduce_any(tf.math.less_equal(s, 0)), tf.ones_like(s), s))\n      condA=tf.reduce_any(s==0)\n      #condB=tf.reduce_any(tf.math.not_equal(G, smallG))\n      #logDet = tf.where(tf.reduce_any([condA, condB, condG]),tf.constant(0.0),tf.reduce_sum(safeLog))\n      logDet = tf.where(tf.reduce_any([condA]),tf.constant(0.0),tf.reduce_sum(safeLog))\n      \n      #invG=tf.where(tf.reduce_any([condA, condB, condG]), tf.linalg.diag(tf.ones_like(s)), \n      #               tf.matmul(v ,tf.matmul(tf.linalg.diag(safeInvS), tf.transpose(u))))\n        \n      invG=tf.where(tf.reduce_any([condA]), tf.linalg.diag(tf.ones_like(s)), \n                     tf.matmul(v ,tf.matmul(tf.linalg.diag(safeInvS), tf.transpose(u))))\n      #print(-potential)\n      #print(G)\n      #print(invG)\n      #print(logDet)\n      #print()\n      return(-potential, G, invG, logDet)\n  \n  #@tf.function\n  def run_integrator(self,step_sizes, num_leapfrog_steps,current_momentum_parts, current_state_parts):\n      integrator = GeneralLeapfrogIntegrator(\n          self.hamiltonian_energy_fn, step_sizes, num_leapfrog_steps)\n      [\n          next_state_parts,\n          initial_kinetic,\n          final_kinetic,\n          final_target_log_prob\n      ] = integrator(current_momentum_parts,\n                     current_state_parts)\n      print(\"ik\", initial_kinetic)\n      print(\"fk\", final_kinetic)\n      return(next_state_parts,\n          initial_kinetic,\n          final_kinetic,\n          final_target_log_prob)\n    \n  @mcmc_util.set_doc(RiemannManifoldHamiltonianMonteCarlo.one_step.__doc__)\n  def one_step(self, current_state, previous_kernel_results):\n    with tf.compat.v2.name_scope(\n        mcmc_util.make_name(self.name, 'hmc', 'one_step')):\n      if self._store_parameters_in_results:\n        step_size = previous_kernel_results.step_size\n        num_leapfrog_steps = previous_kernel_results.num_leapfrog_steps\n      else:\n        step_size = self.step_size\n        num_leapfrog_steps = self.num_leapfrog_steps\n      [\n          current_state_parts,\n          step_sizes,\n          current_target_log_prob,\n      ] = _prepare_args(\n          self.target_log_prob_fn,\n          current_state,\n          step_size,\n          previous_kernel_results.target_log_prob,\n          maybe_expand=True,\n          state_gradients_are_stopped=self.state_gradients_are_stopped)\n\n      self.restoreShapes = []\n      for x in current_state_parts:\n          n = 1\n          shape = x.shape\n          for m in shape:\n              n *= m\n          self.restoreShapes.append([shape, n])\n      current_state_parts = [tf.reshape(part, [-1]) for part in current_state_parts]\n      current_state_parts = tf.concat(current_state_parts, -1)\n      temp=[]\n      #print(current_state_parts)\n      for x in range(current_state_parts.shape[0]):\n            temp.append(current_state_parts[x])\n      current_state_parts=temp\n      #print(current_state_parts)\n    \n        \n      current_momentum_parts = []\n\n      for x in current_state_parts:\n          current_momentum_parts.append(tf.random.normal(\n                shape=tf.shape(input=x),\n                dtype=self._momentum_dtype or x.dtype.base_dtype,\n                seed=self._seed_stream()))\n\n\n      next_state_parts, initial_kinetic, final_kinetic, final_target_log_prob =self.run_integrator(step_sizes, num_leapfrog_steps,current_momentum_parts, current_state_parts)\n    \n    \n      if self.state_gradients_are_stopped:\n        next_state_parts = [tf.stop_gradient(x) for x in next_state_parts]\n\n      def maybe_flatten(x):\n        return x if mcmc_util.is_list_like(current_state) else x[0]\n\n      independent_chain_ndims = distribution_util.prefer_static_rank(\n          current_target_log_prob)\n      \n      next_state_parts = maybe_flatten(next_state_parts)\n\n      new_kernel_results = previous_kernel_results._replace(\n          log_acceptance_correction=_compute_log_acceptance_correction(\n              initial_kinetic, final_kinetic,\n              independent_chain_ndims),\n          target_log_prob=final_target_log_prob\n      )\n      argv = next_state_parts#[0]\n      next_state_parts = []\n      index = 0\n      #print(self.restoreShapes)\n      for info in self.restoreShapes:\n          next_state_parts.append(tf.reshape(argv[index:index + info[1]], info[0]))\n          index += info[1]\n\n      return next_state_parts, new_kernel_results\n\n  @mcmc_util.set_doc(RiemannManifoldHamiltonianMonteCarlo.bootstrap_results.__doc__)\n  def bootstrap_results(self, init_state):\n      with tf.compat.v2.name_scope(\n              mcmc_util.make_name(self.name, 'hmc', 'bootstrap_results')):\n          if not mcmc_util.is_list_like(init_state):\n              init_state = [init_state]\n          if self.state_gradients_are_stopped:\n              init_state = [tf.stop_gradient(x) for x in init_state]\n          else:\n              init_state = [tf.convert_to_tensor(value=x) for x in init_state]\n          [\n              init_target_log_prob,\n              init_grads_target_log_prob,\n          ] = mcmc_util.maybe_call_fn_and_grads(self.target_log_prob_fn, init_state)\n          if self._store_parameters_in_results:\n              return UncalibratedRiemannManifoldHamiltonianMonteCarloKernelResults(\n                  log_acceptance_correction=tf.zeros_like(init_target_log_prob),\n                  target_log_prob=init_target_log_prob,\n                  step_size=tf.nest.map_structure(\n                      lambda x: tf.convert_to_tensor(  # pylint: disable=g-long-lambda\n                          value=x,\n                          dtype=init_target_log_prob.dtype,\n                          name='step_size'),\n                      self.step_size),\n                  num_leapfrog_steps=tf.convert_to_tensor(\n                      value=self.num_leapfrog_steps,\n                      dtype=tf.int32,\n                      name='num_leapfrog_steps'))\n          else:\n              return UncalibratedRiemannManifoldHamiltonianMonteCarloKernelResults(\n                  log_acceptance_correction=tf.zeros_like(init_target_log_prob),\n                  target_log_prob=init_target_log_prob,\n                  step_size=[],\n                  num_leapfrog_steps=[]\n              )\n\n\ndef _compute_log_acceptance_correction(current_kinetic,\n                                       proposed_kinetic,\n                                       independent_chain_ndims,\n                                       name=None):\n  \"\"\"Helper to `kernel` which computes the log acceptance-correction.\n  A sufficient but not necessary condition for the existence of a stationary\n  distribution, `p(x)`, is \"detailed balance\", i.e.:\n  ```none\n  p(x'|x) p(x) = p(x|x') p(x')\n  ```\n  In the Metropolis-Hastings algorithm, a state is proposed according to\n  `g(x'|x)` and accepted according to `a(x'|x)`, hence\n  `p(x'|x) = g(x'|x) a(x'|x)`.\n  Inserting this into the detailed balance equation implies:\n  ```none\n      g(x'|x) a(x'|x) p(x) = g(x|x') a(x|x') p(x')\n  ==> a(x'|x) / a(x|x') = p(x') / p(x) [g(x|x') / g(x'|x)]    (*)\n  ```\n  One definition of `a(x'|x)` which satisfies (*) is:\n  ```none\n  a(x'|x) = min(1, p(x') / p(x) [g(x|x') / g(x'|x)])\n  ```\n  (To see that this satisfies (*), notice that under this definition only at\n  most one `a(x'|x)` and `a(x|x') can be other than one.)\n  We call the bracketed term the \"acceptance correction\".\n  In the case of UncalibratedHMC, the log acceptance-correction is not the log\n  proposal-ratio. UncalibratedHMC augments the state-space with momentum, z.\n  Assuming a standard Gaussian distribution for momentums, the chain eventually\n  converges to:\n  ```none\n  p([x, z]) propto= target_prob(x) exp(-0.5 z**2)\n  ```\n  Relating this back to Metropolis-Hastings parlance, for HMC we have:\n  ```none\n  p([x, z]) propto= target_prob(x) exp(-0.5 z**2)\n  g([x, z] | [x', z']) = g([x', z'] | [x, z])\n  ```\n  In other words, the MH bracketed term is `1`. However, because we desire to\n  use a general MH framework, we can place the momentum probability ratio inside\n  the metropolis-correction factor thus getting an acceptance probability:\n  ```none\n                       target_prob(x')\n  accept_prob(x'|x) = -----------------  [exp(-0.5 z**2) / exp(-0.5 z'**2)]\n                       target_prob(x)\n  ```\n  (Note: we actually need to handle the kinetic energy change at each leapfrog\n  step, but this is the idea.)\n  Args:\n    current_momentums: `Tensor` representing the value(s) of the current\n      momentum(s) of the state (parts).\n    proposed_momentums: `Tensor` representing the value(s) of the proposed\n      momentum(s) of the state (parts).\n    independent_chain_ndims: Scalar `int` `Tensor` representing the number of\n      leftmost `Tensor` dimensions which index independent chains.\n    name: Python `str` name prefixed to Ops created by this function.\n      Default value: `None` (i.e., 'compute_log_acceptance_correction').\n  Returns:\n    log_acceptance_correction: `Tensor` representing the `log`\n      acceptance-correction.  (See docstring for mathematical definition.)\n  \"\"\"\n  with tf.compat.v2.name_scope(name or 'compute_log_acceptance_correction'):\n      \"\"\"\n      #current_momentums=tf.reshape(current_momentums,proposed_momentums.shape)\n      log_current_kinetic, log_proposed_kinetic = [], []\n      for current_momentum, proposed_momentum in zip(\n          current_momentums, proposed_momentums):\n        axis = tf.range(independent_chain_ndims, tf.rank(current_momentum))\n        log_current_kinetic.append(_log_sum_sq(current_momentum, axis))\n        log_proposed_kinetic.append(_log_sum_sq(proposed_momentum, axis))\n      current_kinetic = 0.5 * tf.exp(\n          tf.reduce_logsumexp(\n              input_tensor=tf.stack(log_current_kinetic, axis=-1), axis=-1))\n      proposed_kinetic = 0.5 * tf.exp(\n          tf.reduce_logsumexp(\n              input_tensor=tf.stack(log_proposed_kinetic, axis=-1), axis=-1))\n      \"\"\"\n      return mcmc_util.safe_sum([current_kinetic, -proposed_kinetic])#*0.0\n\n\ndef _prepare_args(target_log_prob_fn,\n                  state,\n                  step_size,\n                  target_log_prob=None,\n                  maybe_expand=False,\n                  state_gradients_are_stopped=False):\n  \"\"\"Helper which processes input args to meet list-like assumptions.\"\"\"\n  state_parts = list(state) if mcmc_util.is_list_like(state) else [state]\n  state_parts = [\n      tf.convert_to_tensor(value=s, name='current_state') for s in state_parts\n  ]\n  if state_gradients_are_stopped:\n    state_parts = [tf.stop_gradient(x) for x in state_parts]\n  target_log_prob, _ = mcmc_util.maybe_call_fn_and_grads(\n      target_log_prob_fn,\n      state_parts,\n      target_log_prob,\n      None)\n  step_sizes = (list(step_size) if mcmc_util.is_list_like(step_size)\n                else [step_size])\n  step_sizes = [\n      tf.convert_to_tensor(\n          value=s, name='step_size', dtype=target_log_prob.dtype)\n      for s in step_sizes\n  ]\n  if len(step_sizes) == 1:\n    step_sizes *= len(state_parts)\n  if len(state_parts) != len(step_sizes):\n    raise ValueError('There should be exactly one `step_size` or it should '\n                     'have same length as `current_state`.')\n  def maybe_flatten(x):\n    return x if maybe_expand or mcmc_util.is_list_like(state) else x[0]\n  return [\n      maybe_flatten(state_parts),\n      maybe_flatten(step_sizes),\n      target_log_prob\n  ]\n\n\ndef _log_sum_sq(x, axis=None):\n  \"\"\"Computes log(sum(x**2)).\"\"\"\n  return tf.reduce_logsumexp(\n      input_tensor=2. * tf.math.log(tf.abs(x)), axis=axis)\n", "meta": {"hexsha": "41983abcbae8db316a7522efa5fcd0cdd5da61dd", "size": 30552, "ext": "py", "lang": "Python", "max_stars_repo_path": "bayesianNetwork2.0/RMHMCTransitionKernel.py", "max_stars_repo_name": "brkronheim/BNNs-for-SUSY", "max_stars_repo_head_hexsha": "1f845e7cd5437970cfd6b2bd0b4af6c26354ce78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bayesianNetwork2.0/RMHMCTransitionKernel.py", "max_issues_repo_name": "brkronheim/BNNs-for-SUSY", "max_issues_repo_head_hexsha": "1f845e7cd5437970cfd6b2bd0b4af6c26354ce78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bayesianNetwork2.0/RMHMCTransitionKernel.py", "max_forks_repo_name": "brkronheim/BNNs-for-SUSY", "max_forks_repo_head_hexsha": "1f845e7cd5437970cfd6b2bd0b4af6c26354ce78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5673469388, "max_line_length": 174, "alphanum_fraction": 0.6633608274, "include": true, "reason": "import numpy", "num_tokens": 6927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.16141236332247377}}
{"text": "\"\"\"\nThis class computes activity cliffs on all compounds\nDerek van Tilborg, Eindhoven University of Technology, March 2022\n\"\"\"\n\nimport numpy as np\nfrom progress.bar import ShadyBar\nfrom rdkit import Chem\nfrom rdkit.Chem import AllChem\nfrom rdkit.Chem import DataStructs\nfrom Levenshtein import distance as levenshtein\n\nfrom rdkit.Chem.Scaffolds.MurckoScaffold import MakeScaffoldGeneric as GraphFramework\nfrom rdkit.Chem.Scaffolds.MurckoScaffold import GetScaffoldForMol\n\n\nclass Cliffs:\n    \"\"\"Find activity cliffs for a list of molecules and their bioactivity\n        We use a three-part activity cliff definition consisting of Tanimoto similarity, generic Murcko scaffold\n        similarity, and Levenshtein similarity. Compound pairs that have a similarity >= 0.7 and a fold-change\n        in bioactivity of >= 10x, are considered a activity cliff. Because activity cliffs can be defined from\n        different angles, we use a soft-consensus to determine if a compound is an activity cliff compound\"\"\"\n\n    def __init__(self, smiles: list, activity: list, test_smiles: list = None, test_activity: list = None,\n                 in_log10: bool = True, fold_threshold: int = 10, similarity_threshold: float = 0.9):\n        \"\"\"\n            smiles: (lst) List of SMILES strings\n            activity: (lst) List of bioactivities (standard in log10 [nM])\n            test_smiles: (lst) List of SMILES strings for compounds in the test set (optional)\n            test_activity: (lst) List of bioactivities (standard in log10 [nM]) for compounds in the test set (optional)\n            in_log10: (bool) is the bioactivity provided in log10? If True (default) it will be deconverted to determine\n            the fold change.\n            fold_threshold: (int) how much must the fold change be before being an activity cliff? (default=10)\n            similarity_threshold: (float) how similar must two compounds be before being an activity cliff (default=0.7)\n        \"\"\"\n        self.in_log10 = in_log10\n        self.smiles = smiles\n        self.test_smiles = test_smiles\n        if test_smiles is None:\n            self.test_smiles = []\n        self.all_smiles = self.smiles + self.test_smiles\n\n        self.activity = activity\n        self.test_activity = test_activity\n        if test_activity is None:\n            self.test_activity = []\n        self.all_activity = self.activity + self.test_activity\n\n        self.train_idx = list(range(len(smiles)))\n        self.test_idx = list(range(len(smiles), len(self.all_smiles)))\n\n        # Initiate a shitload of empty variables\n        self.fc = None\n        self.tanimoto_sim = None\n        self.levenshtein_sim = None\n        self.scaffold_sim = None\n        self.tanimoto = None\n        self.levenshtein = None\n        self.scaffold = None\n        self.soft_consensus = None\n        self.tanimoto_tr = None\n        self.tanimoto_tst = None\n        self.scaffold_tr = None\n        self.scaffold_tst = None\n        self.levenshtein_tr = None\n        self.levenshtein_tst = None\n        self.soft_consensus_tr = None\n        self.soft_consensus_tst = None\n        self.db_fp = None\n        self.db_scaf = None\n        self.fold_threshold = fold_threshold\n        self.similarity_threshold = similarity_threshold\n        self.cliff_mols_tanimoto = None\n        self.cliff_mols_tanimoto_tr = None\n        self.cliff_mols_tanimoto_tst = None\n        self.cliff_mols_scaffold = None\n        self.cliff_mols_scaffold_tr = None\n        self.cliff_mols_scaffold_tst = None\n        self.cliff_mols_levenshtein = None\n        self.cliff_mols_levenshtein_tr = None\n        self.cliff_mols_levenshtein_tst = None\n        self.cliff_mols_soft_consensus = None\n        self.cliff_mols_soft_consensus_tr = None\n        self.cliff_mols_soft_consensus_tst = None\n        self.stats = None\n\n        # Find cliffs, find which compounds are activity cliff compounds and subset the results if there is test data\n        self.find_cliffs(fold_threshold, similarity_threshold)\n        self.find_cliff_compounds()\n        self.train_test_cliffs(self.train_idx, self.test_idx)\n        self.get_stats()\n\n    def find_fc(self, a: float, b: float):\n        \"\"\"Get the fold change of to bioactivities (deconvert from log10 if needed)\"\"\"\n\n        if self.in_log10:\n            a, b = 10**a, 10**b\n        return max([a, b]) / min([a, b])\n\n    def get_fc(self, waitbar: bool = True):\n        \"\"\" Calculates the pairwise fold difference in compound activity given a list of activities\"\"\"\n\n        act_len = len(self.all_activity)\n        m = np.zeros([act_len, act_len])\n        if waitbar:\n            bar = ShadyBar('Calculating pairwise fold change                        ', max=act_len, check_tty=False)\n        # Calculate upper triangle of matrix\n        for i in range(act_len):\n            if waitbar:\n                bar.next()\n            for j in range(i, act_len):\n                m[i, j] = self.find_fc(self.all_activity[i], self.all_activity[j])\n\n        if waitbar:\n            bar.finish()\n\n        # Fill in the lower triangle without having to loop (saves ~50% of time)\n        m = m + m.T - np.diag(np.diag(m))\n        # Fill the diagonal with 0's\n        np.fill_diagonal(m, 0)\n\n        self.fc = m\n\n    def get_levenshtein_matrix(self, waitbar: bool = True, normalize: bool = True):\n        \"\"\" Calculates a matrix of levenshtein similarity scores for a list of SMILES string\"\"\"\n\n        smiles = self.all_smiles\n        smi_len = len(smiles)\n        if waitbar:\n            bar = ShadyBar('Calculating pairwise Levenshtein similarity (normalized)', max=smi_len, check_tty=False)\n        m = np.zeros([smi_len, smi_len])\n        # Calculate upper triangle of matrix\n        for i in range(smi_len):\n            if waitbar:\n                bar.next()\n            for j in range(i, smi_len):\n                if normalize:\n                    m[i, j] = levenshtein(smiles[i], smiles[j]) / max(len(smiles[i]), len(smiles[j]))\n                else:\n                    m[i, j] = levenshtein(smiles[i], smiles[j])\n        if waitbar:\n            bar.finish()\n        # Fill in the lower triangle without having to loop (saves ~50% of time)\n        m = m + m.T - np.diag(np.diag(m))\n        # Get from a distance to a similarity\n        m = 1 - m\n\n        # Fill the diagonal with 0's\n        np.fill_diagonal(m, 0)\n\n        self.levenshtein_sim = m\n\n    def get_tanimoto_matrix(self, waitbar: bool = True, radius: int = 2, nBits: int = 1024):\n        \"\"\" Calculates a matrix of Tanimoto similarity scores for a list of SMILES string\"\"\"\n\n        # Make a fingerprint database\n        self.db_fp = {}\n        for smi in self.all_smiles:\n            m = Chem.MolFromSmiles(smi)\n            fp = AllChem.GetMorganFingerprintAsBitVect(m, radius=radius, nBits=nBits)\n            self.db_fp[smi] = fp\n\n        smi_len = len(self.all_smiles)\n        if waitbar:\n            bar = ShadyBar('Calculating pairwise Tanimoto similarity                ', max=smi_len, check_tty=False)\n        m = np.zeros([smi_len, smi_len])\n        # Calculate upper triangle of matrix\n        for i in range(smi_len):\n            if waitbar:\n                bar.next()\n            for j in range(i, smi_len):\n                m[i, j] = DataStructs.TanimotoSimilarity(self.db_fp[self.all_smiles[i]],\n                                                         self.db_fp[self.all_smiles[j]])\n        if waitbar:\n            bar.finish()\n        # Fill in the lower triangle without having to loop (saves ~50% of time)\n        m = m + m.T - np.diag(np.diag(m))\n        # Fill the diagonal with 0's\n        np.fill_diagonal(m, 0)\n\n        self.tanimoto_sim = m\n\n    def get_scaffold_matrix(self, waitbar: bool = True, radius: int = 2, nBits: int = 1024):\n        \"\"\" Calculates a matrix of Tanimoto similarity scores for a list of SMILES string \"\"\"\n\n        # Make scaffold database\n        self.db_scaf = {}\n        for smi in self.all_smiles:\n            m = Chem.MolFromSmiles(smi)\n            try:\n                skeleton = GraphFramework(m)\n            except Exception:  # In the very rare case this doesnt work, use a normal scaffold\n                print(f\"Could not create a generic scaffold of {smi}, used a normal scaffold instead\")\n                skeleton = GetScaffoldForMol(m)\n            skeleton_fp = AllChem.GetMorganFingerprintAsBitVect(skeleton, radius=radius, nBits=nBits)\n            self.db_scaf[smi] = skeleton_fp\n\n        smi_len = len(self.all_smiles)\n        if waitbar:\n            bar = ShadyBar('Calculating pairwise generic scaffold similarity        ', max=smi_len, check_tty=False)\n        m = np.zeros([smi_len, smi_len])\n        # Calculate upper triangle of matrix\n        for i in range(smi_len):\n            if waitbar:\n                bar.next()\n            for j in range(i, smi_len):\n                m[i, j] = DataStructs.TanimotoSimilarity(self.db_scaf[self.all_smiles[i]],\n                                                         self.db_scaf[self.all_smiles[j]])\n        if waitbar:\n            bar.finish()\n        # Fill in the lower triangle without having to loop (saves ~50% of time)\n        m = m + m.T - np.diag(np.diag(m))\n        # Fill the diagonal with 0's\n        np.fill_diagonal(m, 0)\n\n        self.scaffold_sim = m\n\n    def find_cliffs(self, fold_threshold: int = 10, similarity_threshold: float = 0.90):\n        \"\"\"Find Tanimoto, scaffold, and Levenshtein activity cliffs \"\"\"\n\n        # Calculate fold change and similarity\n        self.get_fc()\n        self.get_tanimoto_matrix()\n        self.get_scaffold_matrix()\n        self.get_levenshtein_matrix()\n\n        # Determine which compound pairs are cliffs\n        self.tanimoto = np.logical_and(self.fc > fold_threshold,\n                                       self.tanimoto_sim > similarity_threshold).astype(int)\n\n        self.levenshtein = np.logical_and(self.fc > fold_threshold,\n                                          self.levenshtein_sim > similarity_threshold).astype(int)\n\n        self.scaffold = np.logical_and(self.fc > fold_threshold,\n                                       self.scaffold_sim > similarity_threshold).astype(int)\n\n        # If a compound pair is a cliff in at least 1 method for soft consensus\n        self.soft_consensus = self.tanimoto + self.scaffold + self.levenshtein\n        self.soft_consensus[self.soft_consensus > 0] = 1\n\n    def find_cliff_compounds(self):\n        \"\"\" Find activity cliff compounds (having at least 1 cliff with any compound) for the different cliff types\"\"\"\n        self.cliff_mols_tanimoto = [s for i, s in enumerate(self.all_smiles) if sum(self.tanimoto[i]) > 0]\n        self.cliff_mols_scaffold = [s for i, s in enumerate(self.all_smiles) if sum(self.scaffold[i]) > 0]\n        self.cliff_mols_levenshtein = [s for i, s in enumerate(self.all_smiles) if sum(self.levenshtein[i]) > 0]\n        self.cliff_mols_soft_consensus = [s for i, s in enumerate(self.all_smiles) if sum(self.soft_consensus[i]) > 0]\n\n    def train_test_cliffs(self, train_idx: list, test_idx: list):\n        \"\"\" Subset the activity cliff matrices with the train/test indices\"\"\"\n\n        # Tanimoto\n        self.tanimoto_tr = self.tanimoto[np.ix_(train_idx, train_idx)]\n        self.tanimoto_tst = self.tanimoto[np.ix_(test_idx, test_idx)]\n        self.cliff_mols_tanimoto_tr = [s for s in self.cliff_mols_tanimoto if s in self.smiles]\n        self.cliff_mols_tanimoto_tst = [s for s in self.cliff_mols_tanimoto if s in self.test_smiles]\n\n        # Scaffold\n        self.scaffold_tr = self.scaffold[np.ix_(train_idx, train_idx)]\n        self.scaffold_tst = self.scaffold[np.ix_(test_idx, test_idx)]\n        self.cliff_mols_scaffold_tr = [s for s in self.cliff_mols_scaffold if s in self.smiles]\n        self.cliff_mols_scaffold_tst = [s for s in self.cliff_mols_scaffold if s in self.test_smiles]\n\n        # Levenshtein\n        self.levenshtein_tr = self.levenshtein[np.ix_(train_idx, train_idx)]\n        self.levenshtein_tst = self.levenshtein[np.ix_(test_idx, test_idx)]\n        self.cliff_mols_levenshtein_tr = [s for s in self.cliff_mols_levenshtein if s in self.smiles]\n        self.cliff_mols_levenshtein_tst = [s for s in self.cliff_mols_levenshtein if s in self.test_smiles]\n\n        # consensus\n        self.soft_consensus_tr = self.soft_consensus[np.ix_(train_idx, train_idx)]\n        self.soft_consensus_tst = self.soft_consensus[np.ix_(test_idx, test_idx)]\n        self.cliff_mols_soft_consensus_tr = [s for s in self.cliff_mols_soft_consensus if s in self.smiles]\n        self.cliff_mols_soft_consensus_tst = [s for s in self.cliff_mols_soft_consensus if s in self.test_smiles]\n\n    def get_stats(self):\n        \"\"\" Calculate various stats on the found activity cliffs\"\"\"\n        self.stats = {\n            \"Fold change threshold\":\n                self.fold_threshold,\n            \"Structural similarity threshold\":\n                self.similarity_threshold,\n            \"n_tanimoto_cliffs\":\n                0 if self.tanimoto is None else sum(np.triu(self.tanimoto).flatten()),\n            \"n_scaffold_cliffs\":\n                0 if self.scaffold is None else sum(np.triu(self.scaffold).flatten()),\n            \"n_levenstein_cliffs\":\n                0 if self.levenshtein is None else sum(np.triu(self.levenshtein).flatten()),\n            \"n_soft_consensus_cliffs\":\n                0 if self.soft_consensus is None else sum(np.triu(self.soft_consensus).flatten()),\n            \"n_tanimoto_cliffs_train\":\n                0 if self.tanimoto_tr is None else sum(np.triu(self.tanimoto_tr).flatten()),\n            \"n_scaffold_cliffs_train\":\n                0 if self.scaffold_tr is None else sum(np.triu(self.scaffold_tr).flatten()),\n            \"n_levenstein_cliffs_train\":\n                0 if self.levenshtein_tr is None else sum(np.triu(self.levenshtein_tr).flatten()),\n            \"n_soft_consensus_cliffs_train\":\n                0 if self.soft_consensus_tr is None else sum(np.triu(self.soft_consensus_tr).flatten()),\n            \"n_tanimoto_cliffs_test\":\n                0 if self.tanimoto_tst is None else sum(np.triu(self.tanimoto_tst).flatten()),\n            \"n_scaffold_cliffs_test\":\n                0 if self.scaffold_tst is None else sum(np.triu(self.scaffold_tst).flatten()),\n            \"n_levenstein_cliffs_test\":\n                0 if self.levenshtein_tst is None else sum(np.triu(self.levenshtein_tst).flatten()),\n            \"n_soft_consensus_cliffs_test\":\n                0 if self.soft_consensus_tst is None else sum(np.triu(self.soft_consensus_tst).flatten()),\n            \"n_compounds\":\n                len(self.all_smiles),\n            \"n_compounds_train\":\n                len(self.all_smiles)-len(self.test_smiles),\n            \"n_compounds_test\":\n                len(self.test_smiles),\n            \"n_tanimoto_cliff_compounds\":\n                0 if self.cliff_mols_tanimoto is None else len(self.cliff_mols_tanimoto),\n            \"n_scaffold_cliff_compounds\":\n                0 if self.cliff_mols_scaffold is None else len(self.cliff_mols_scaffold),\n            \"n_levenshtein_cliff_compounds\":\n                0 if self.cliff_mols_levenshtein is None else len(self.cliff_mols_levenshtein),\n            \"n_soft_consensus_cliff_compounds\":\n                0 if self.cliff_mols_soft_consensus is None else len(self.cliff_mols_soft_consensus),\n            \"n_tanimoto_cliff_compounds_train\":\n                0 if self.cliff_mols_tanimoto_tr is None else len(self.cliff_mols_tanimoto_tr),\n            \"n_scaffold_cliff_compounds_train\":\n                0 if self.cliff_mols_scaffold_tr is None else len(self.cliff_mols_scaffold_tr),\n            \"n_levenshtein_cliff_compounds_train\":\n                0 if self.cliff_mols_levenshtein_tr is None else len(self.cliff_mols_levenshtein_tr),\n            \"n_soft_consensus_cliff_compounds_train\":\n                0 if self.cliff_mols_soft_consensus_tr is None else len(self.cliff_mols_soft_consensus_tr),\n            \"n_tanimoto_cliff_compounds_test\":\n                0 if self.cliff_mols_tanimoto_tst is None else len(self.cliff_mols_tanimoto_tst),\n            \"n_scaffold_cliff_compounds_test\":\n                0 if self.cliff_mols_scaffold_tst is None else len(self.cliff_mols_scaffold_tst),\n            \"n_levenshtein_cliff_compounds_test\":\n                0 if self.cliff_mols_levenshtein_tst is None else len(self.cliff_mols_levenshtein_tst),\n            \"n_soft_consensus_cliff_compounds_test\":\n                0 if self.cliff_mols_soft_consensus_tst is None else len(self.cliff_mols_soft_consensus_tst),\n        }\n\n    def __repr__(self):\n        self.get_stats()\n        out = ''\n        for i in list(self.stats.keys()):\n            if len(self.test_smiles) == 0:  # if no test data is provided, don't show test stats (they will be 0)\n                if not i.endswith('train') and not i.endswith('test'):\n                    out += f'{i}: {self.stats[i]}\\n'\n            else:\n                out += f'{i}: {self.stats[i]}\\n'\n        return out\n\n", "meta": {"hexsha": "4f639ff0f8f2fe2bd84dbdf757975db518f5014c", "size": 16956, "ext": "py", "lang": "Python", "max_stars_repo_path": "MoleculeACE/benchmark/utils/cliffs.py", "max_stars_repo_name": "molML/MoleculeACE", "max_stars_repo_head_hexsha": "e831d2371a9b89f4853a03d5c04cc4bf59f64ee0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2022-03-26T17:36:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T19:50:26.000Z", "max_issues_repo_path": "MoleculeACE/benchmark/utils/cliffs.py", "max_issues_repo_name": "molML/MoleculeACE", "max_issues_repo_head_hexsha": "e831d2371a9b89f4853a03d5c04cc4bf59f64ee0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MoleculeACE/benchmark/utils/cliffs.py", "max_forks_repo_name": "molML/MoleculeACE", "max_forks_repo_head_hexsha": "e831d2371a9b89f4853a03d5c04cc4bf59f64ee0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.5845272206, "max_line_length": 120, "alphanum_fraction": 0.635881104, "include": true, "reason": "import numpy", "num_tokens": 4250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305398, "lm_q2_score": 0.3106943832145539, "lm_q1q2_score": 0.16141236131336506}}
{"text": "\"\"\"\nModule: System\n    This module shall be used to implement subclasses of system. It wraps all information needed and generated by a simulation.\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n\npd.options.mode.use_inf_as_na = True\n\nfrom ensembler.util import dataStructure as data\nfrom ensembler.util.ensemblerTypes import samplerCls, conditionCls\nfrom ensembler.util.ensemblerTypes import Union, Iterable, NoReturn, Number\n\nfrom ensembler.potentials._basicPotentials import _potential1DClsPerturbed as _perturbedPotentialCls\nfrom ensembler.potentials.OneD import linearCoupledPotentials\nfrom ensembler.samplers.stochastic import metropolisMonteCarloIntegrator\n\nfrom ensembler.system.basic_system import system\n\n\nclass perturbedSystem(system):\n    \"\"\"\n    \n    \"\"\"\n    name = \"perturbed system\"\n    # Lambda Dependend Settings\n    state = data.lambdaState\n    currentState: data.lambdaState\n    potential: _perturbedPotentialCls\n\n    # current lambda\n    _currentLambda: Number = np.nan\n    _currentdHdLambda: Number = np.nan\n\n    \"\"\"\n    Attributes\n    \"\"\"\n    @property\n    def lam(self) -> Number:\n        return self._currentLambda\n\n    @lam.setter\n    def lam(self, lam: Number):\n        if lam < 0.0 or lam > 1.0:\n            raise ValueError(f\"Variable lam = {lam}.\"\\\n                              \"It cannot be lower than 0 or larger than 1.\")\n        self._currentLambda = lam\n        self.potential.set_lambda(lam=self._currentLambda)\n        self.update_current_state()\n\n    def set_lambda(self, lam:Number):\n        self.lam = lam\n\n    \"\"\"\n    Magic\n    \"\"\"\n\n    def __init__(self, potential: _perturbedPotentialCls=linearCoupledPotentials(), sampler: samplerCls=metropolisMonteCarloIntegrator(),\n                 conditions: Iterable[conditionCls] = [],\n                 temperature: float = 298.0, start_position: (Iterable[Number] or float) = None, lam: float = 0.0):\n        \"\"\"\n            __init__\n                construct a eds-System that can be used to manage a simulation.\n\n        Parameters\n        ----------\n        potential:  pot.envelopedPotential, optional\n            potential function class to be explored by sampling\n        sampler: sampler, optional\n            sampling method, that allows exploring the potential function\n        conditions: Iterable[condition], optional\n            conditions that shall be applied to the system.\n        temperature: float, optional\n            The temperature of the system (default: 298K)\n        start_position:\n            starting position for the simulation and setup of the system.\n        lam: Number, optional\n            the value of the copuling lambda\n        \"\"\"\n        super().__init__(potential=potential, sampler=sampler, conditions=conditions, temperature=temperature,\n                         start_position=start_position)\n\n        self.lam = lam\n        self.update_current_state()\n\n    \"\"\"\n    Overwrite Functions to adapt to EDS\n    \"\"\"\n\n    def set_current_state(self,\n                          current_position: Union[Number, Iterable[Number]],\n                          current_velocities: Union[Number, Iterable[Number]] = 0,\n                          current_force: Union[Number, Iterable[Number]] = 0,\n                          current_temperature: Union[Number, Iterable[Number]] = 298,\n                          current_lambda: Union[Number, Iterable[Number]] = 0,\n                          current_dHdLambda: Union[Number, Iterable[Number]] = 0):\n        \"\"\"\n            set_current_state\n                set s the current state to the given variables.\n\n        Parameters\n        ----------\n        Parameters\n        ----------\n        current_position: Union[Number, Iterable[Number]]\n            new current system position\n        current_velocities: Union[Number, Iterable[Number]], optional\n            new current system velocity. (default: 0)\n        current_force: Union[Number, Iterable[Number]], optional\n            new current system force. (default: 0)\n        current_temperature: Union[Number, Iterable[Number]], optional\n            new current system temperature. (default: 298)\n        current_lam: Union[Number, Iterable[Number]],\n            The new lambda value (default: 0)\n        current_dHdLam: Union[Number, Iterable[Number]],\n            The new dHdLam(default: 0)\n        \"\"\"\n        self._currentPosition = current_position\n        self._currentForce = current_force\n        self._currentVelocities = current_force\n        self._currentTemperature = current_temperature\n        self._currentLambda = current_lambda\n        self._currentdHdLambda = current_dHdLambda\n\n        self._update_energies()\n        self._update_dHdLambda()\n        self.update_current_state()\n\n    def update_system_properties(self) -> NoReturn:\n        \"\"\"\n            updateSystemProperties\n                update all system properties\n        \"\"\"\n        self._update_energies()\n        self._update_temperature()\n        self._update_dHdLambda()\n\n    def update_current_state(self):\n        \"\"\"\n        updateCurrentState\n                This function updates the current state from the _current Variables.\n\n        \"\"\"\n        self._currentState = self.state(position=self._currentPosition, temperature=self._currentTemperature,\n                                        total_system_energy=self._currentTotE,\n                                        total_potential_energy=self._currentTotPot,\n                                        total_kinetic_energy=self._currentTotKin,\n                                        dhdpos=self._currentForce, velocity=self._currentVelocities,\n                                        lam=self._currentLambda, dhdlam=self._currentdHdLambda)\n\n    def append_state(self, new_position: Union[Number, Iterable[Number]], new_velocity: Union[Number, Iterable[Number]], new_forces: Union[Number, Iterable[Number]],\n                     new_lambda: Number) -> NoReturn:\n        \"\"\"\n            append_state\n                Append a new state to the trajectory.\n\n        Parameters\n        ----------\n        new_position: Union[Number, Iterable[Number]]\n            new position for the system\n        new_velocity: Union[Number, Iterable[Number]]\n            new velocity for the system\n        new_forces: Union[Number, Iterable[Number]]\n            new forces for the system\n        new_lambda: Union[Number, Iterable[Number]]\n            new lambda for the system\n\n        \"\"\"\n        self._currentPosition = new_position\n        self._currentVelocities = new_velocity\n        self._currentForce = new_forces\n        self._currentLambda = new_lambda\n\n        self._update_temperature()\n        self._update_energies()\n        self._update_dHdLambda()\n        self.update_current_state()\n\n        self._trajectory.append(self.current_state)\n\n    \"\"\"\n    Functionality\n    \"\"\"\n\n    def _update_dHdLambda(self) -> Number:\n        \"\"\"\n            _update_dHdlambda\n                update the current dHdLambda value\n\n        Returns\n        -------\n        Number\n            dHdlambda\n\n        \"\"\"\n        self._currentdHdLambda = self.potential.dvdlam(self._currentPosition)\n        self.update_current_state()\n        return self._currentdHdLambda\n", "meta": {"hexsha": "d50c9fb96b0f9392e70c9a0abcc04cf6c8016bd1", "size": 7189, "ext": "py", "lang": "Python", "max_stars_repo_path": "ensembler/system/perturbed_system.py", "max_stars_repo_name": "philthiel/Ensembler", "max_stars_repo_head_hexsha": "943efac3c673eb40165927e81336386788e3a19f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2020-05-19T08:45:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T16:58:34.000Z", "max_issues_repo_path": "ensembler/system/perturbed_system.py", "max_issues_repo_name": "SchroederB/Ensembler", "max_issues_repo_head_hexsha": "943efac3c673eb40165927e81336386788e3a19f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38, "max_issues_repo_issues_event_min_datetime": "2020-06-18T13:02:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T14:29:17.000Z", "max_forks_repo_path": "ensembler/system/perturbed_system.py", "max_forks_repo_name": "SchroederB/Ensembler", "max_forks_repo_head_hexsha": "943efac3c673eb40165927e81336386788e3a19f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2020-05-19T08:45:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T16:18:20.000Z", "avg_line_length": 35.945, "max_line_length": 165, "alphanum_fraction": 0.6247044095, "include": true, "reason": "import numpy", "num_tokens": 1496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.1614123600065945}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"\nModels for doing PSF/PRF fitting photometry on image data.\n\"\"\"\n\nfrom __future__ import division\nimport numpy as np\nfrom astropy.table import Table\nfrom astropy.modeling import models, Parameter, Fittable2DModel\nfrom astropy.modeling.fitting import LevMarLSQFitter\nfrom astropy.nddata.utils import subpixel_indices\nfrom ..utils import mask_to_mirrored_num\nfrom ..extern.nddata_compat import extract_array\n\n\n__all__ = ['IntegratedGaussianPRF', 'PRFAdapter', 'prepare_psf_model',\n           'get_grouped_psf_model']\n\n\nclass DiscretePRF(Fittable2DModel):\n    \"\"\"\n    A discrete Pixel Response Function (PRF) model.\n\n    The discrete PRF model stores images of the PRF at different\n    subpixel positions or offsets as a lookup table. The resolution is\n    given by the subsampling parameter, which states in how many\n    subpixels a pixel is divided.\n\n    In the typical case of wanting to create a PRF from an image with\n    many point sources, use the `~DiscretePRF.create_from_image` method,\n    rather than directly initializing this class.\n\n    The discrete PRF model class in initialized with a 4 dimensional\n    array, that contains the PRF images at different subpixel positions.\n    The definition of the axes is as following:\n\n        1. Axis: y subpixel position\n        2. Axis: x subpixel position\n        3. Axis: y direction of the PRF image\n        4. Axis: x direction of the PRF image\n\n    The total array therefore has the following shape\n    (subsampling, subsampling, prf_size, prf_size)\n\n    Parameters\n    ----------\n    prf_array : ndarray\n        Array containing PRF images.\n    normalize : bool\n        Normalize PRF images to unity.  Equivalent to saying there is\n        *no* flux outside the bounds of the PRF images.\n    subsampling : int, optional\n        Factor of subsampling. Default = 1.\n\n    Notes\n    -----\n    See :ref:`psf-terminology` for more details on the distinction\n    between PSF and PRF as used in this module.\n    \"\"\"\n\n    flux = Parameter('flux')\n    x_0 = Parameter('x_0')\n    y_0 = Parameter('y_0')\n\n    def __init__(self, prf_array, normalize=True, subsampling=1):\n        # Array shape and dimension check\n        if subsampling == 1:\n            if prf_array.ndim == 2:\n                prf_array = np.array([[prf_array]])\n        if prf_array.ndim != 4:\n            raise TypeError('Array must have 4 dimensions.')\n        if prf_array.shape[:2] != (subsampling, subsampling):\n            raise TypeError('Incompatible subsampling and array size')\n        if np.isnan(prf_array).any():\n            raise Exception(\"Array contains NaN values. Can't create PRF.\")\n\n        # Normalize if requested\n        if normalize:\n            for i in range(prf_array.shape[0]):\n                for j in range(prf_array.shape[1]):\n                    prf_array[i, j] /= prf_array[i, j].sum()\n\n        # Set PRF asttributes\n        self._prf_array = prf_array\n        self.subsampling = subsampling\n\n        constraints = {'fixed': {'x_0': True, 'y_0': True}}\n        x_0 = 0\n        y_0 = 0\n        flux = 1\n        super(DiscretePRF, self).__init__(n_models=1, x_0=x_0, y_0=y_0,\n                                          flux=flux, **constraints)\n        self.fitter = LevMarLSQFitter()\n\n    @property\n    def prf_shape(self):\n        \"\"\"Shape of the PRF image.\"\"\"\n\n        return self._prf_array.shape[-2:]\n\n    def evaluate(self, x, y, flux, x_0, y_0):\n        \"\"\"\n        Discrete PRF model evaluation.\n\n        Given a certain position and flux the corresponding image of the\n        PSF is chosen and scaled to the flux. If x and y are outside the\n        boundaries of the image, zero will be returned.\n\n        Parameters\n        ----------\n        x : float\n            x coordinate array in pixel coordinates.\n        y : float\n            y coordinate array in pixel coordinates.\n        flux : float\n            Model flux.\n        x_0 : float\n            x position of the center of the PRF.\n        y_0 : float\n            y position of the center of the PRF.\n        \"\"\"\n\n        # Convert x and y to index arrays\n        x = (x - x_0 + 0.5 + self.prf_shape[1] // 2).astype('int')\n        y = (y - y_0 + 0.5 + self.prf_shape[0] // 2).astype('int')\n\n        # Get subpixel indices\n        y_sub, x_sub = subpixel_indices((y_0, x_0), self.subsampling)\n\n        # Out of boundary masks\n        x_bound = np.logical_or(x < 0, x >= self.prf_shape[1])\n        y_bound = np.logical_or(y < 0, y >= self.prf_shape[0])\n        out_of_bounds = np.logical_or(x_bound, y_bound)\n\n        # Set out of boundary indices to zero\n        x[x_bound] = 0\n        y[y_bound] = 0\n        result = flux * self._prf_array[int(y_sub), int(x_sub)][y, x]\n\n        # Set out of boundary values to zero\n        result[out_of_bounds] = 0\n        return result\n\n    @classmethod\n    def create_from_image(cls, imdata, positions, size, fluxes=None,\n                          mask=None, mode='mean', subsampling=1,\n                          fix_nan=False):\n        \"\"\"\n        Create a discrete point response function (PRF) from image data.\n\n        Given a list of positions and size this function estimates an\n        image of the PRF by extracting and combining the individual PRFs\n        from the given positions.\n\n        NaN values are either ignored by passing a mask or can be\n        replaced by the mirrored value with respect to the center of the\n        PRF.\n\n        Note that if fluxes are *not* specified explicitly, it will be\n        flux estimated from an aperture of the same size as the PRF\n        image. This does *not* account for aperture corrections so often\n        will *not* be what you want for anything other than quick-look\n        needs.\n\n        Parameters\n        ----------\n        imdata : array\n            Data array with the image to extract the PRF from\n        positions : List or array or `~astropy.table.Table`\n            List of pixel coordinate source positions to use in creating\n            the PRF.  If this is a `~astropy.table.Table` it must have\n            columns called ``x_0`` and ``y_0``.\n        size : odd int\n            Size of the quadratic PRF image in pixels.\n        mask : bool array, optional\n            Boolean array to mask out bad values.\n        fluxes : array, optional\n            Object fluxes to normalize extracted PRFs. If not given (or\n            None), the flux is estimated from an aperture of the same\n            size as the PRF image.\n        mode : {'mean', 'median'}\n            One of the following modes to combine the extracted PRFs:\n                * 'mean':  Take the pixelwise mean of the extracted PRFs.\n                * 'median':  Take the pixelwise median of the extracted PRFs.\n        subsampling : int\n            Factor of subsampling of the PRF (default = 1).\n        fix_nan : bool\n            Fix NaN values in the data by replacing it with the mirrored\n            value. Assuming that the PRF is symmetrical.\n\n        Returns\n        -------\n        prf : `photutils.psf.sandbox.DiscretePRF`\n            Discrete PRF model estimated from data.\n        \"\"\"\n\n        # Check input array type and dimension.\n        if np.iscomplexobj(imdata):\n            raise TypeError('Complex type not supported')\n        if imdata.ndim != 2:\n            raise ValueError('{0}-d array not supported. '\n                             'Only 2-d arrays supported.'.format(imdata.ndim))\n        if size % 2 == 0:\n            raise TypeError(\"Size must be odd.\")\n\n        if fluxes is not None and len(fluxes) != len(positions):\n            raise TypeError('Position and flux arrays must be of equal '\n                            'length.')\n\n        if mask is None:\n            mask = np.isnan(imdata)\n\n        if isinstance(positions, (list, tuple)):\n            positions = np.array(positions)\n\n        if isinstance(positions, Table) or \\\n            (isinstance(positions, np.ndarray) and\n             positions.dtype.names is not None):\n            # One can do clever things like\n            # positions['x_0', 'y_0'].as_array().view((positions['x_0'].dtype,\n            #                                          2))\n            # but that requires positions['x_0'].dtype is\n            # positions['y_0'].dtype.\n            # Better do something simple to allow type promotion if required.\n            pos = np.empty((len(positions), 2))\n            pos[:, 0] = positions['x_0']\n            pos[:, 1] = positions['y_0']\n            positions = pos\n\n        if isinstance(fluxes, (list, tuple)):\n            fluxes = np.array(fluxes)\n\n        if mode == 'mean':\n            combine = np.ma.mean\n        elif mode == 'median':\n            combine = np.ma.median\n        else:\n            raise Exception('Invalid mode to combine prfs.')\n\n        data_internal = np.ma.array(data=imdata, mask=mask)\n        prf_model = np.ndarray(shape=(subsampling, subsampling, size, size))\n        positions_subpixel_indices = \\\n            np.array([subpixel_indices(_, subsampling) for _ in positions],\n                     dtype=np.int)\n\n        for i in range(subsampling):\n            for j in range(subsampling):\n                extracted_sub_prfs = []\n                sub_prf_indices = np.all(positions_subpixel_indices == [j, i],\n                                         axis=1)\n                positions_sub_prfs = positions[sub_prf_indices]\n                for k, position in enumerate(positions_sub_prfs):\n                    x, y = position\n                    extracted_prf = extract_array(data_internal, (size, size),\n                                                  (y, x))\n                    # Check shape to exclude incomplete PRFs at the boundaries\n                    # of the image\n                    if (extracted_prf.shape == (size, size) and\n                            np.ma.sum(extracted_prf) != 0):\n                        # Replace NaN values by mirrored value, with respect\n                        # to the prf's center\n                        if fix_nan:\n                            prf_nan = extracted_prf.mask\n                            if prf_nan.any():\n                                if (prf_nan.sum() > 3 or\n                                        prf_nan[size // 2, size // 2]):\n                                    continue\n                                else:\n                                    extracted_prf = mask_to_mirrored_num(\n                                        extracted_prf, prf_nan,\n                                        (size // 2, size // 2))\n                        # Normalize and add extracted PRF to data cube\n                        if fluxes is None:\n                            extracted_prf_norm = (np.ma.copy(extracted_prf) /\n                                                  np.ma.sum(extracted_prf))\n                        else:\n                            fluxes_sub_prfs = fluxes[sub_prf_indices]\n                            extracted_prf_norm = (np.ma.copy(extracted_prf) /\n                                                  fluxes_sub_prfs[k])\n                        extracted_sub_prfs.append(extracted_prf_norm)\n                    else:\n                        continue\n                prf_model[i, j] = np.ma.getdata(\n                    combine(np.ma.dstack(extracted_sub_prfs), axis=2))\n        return cls(prf_model, subsampling=subsampling)\n\n\nclass IntegratedGaussianPRF(Fittable2DModel):\n    r\"\"\"\n    Circular Gaussian model integrated over pixels. Because it is\n    integrated, this model is considered a PRF, *not* a PSF (see\n    :ref:`psf-terminology` for more about the terminology used here.)\n\n    This model is a Gaussian *integrated* over an area of ``1`` (in\n    units of the model input coordinates, e.g. 1 pixel).  This is in\n    contrast to the apparently similar\n    `astropy.modeling.functional_models.Gaussian2D`, which is the value\n    of a 2D Gaussian *at* the input coordinates, with no integration.\n    So this model is equivalent to assuming the PSF is Gaussian at a\n    *sub-pixel* level.\n\n    Parameters\n    ----------\n    sigma : float\n        Width of the Gaussian PSF.\n    flux : float (default 1)\n        Total integrated flux over the entire PSF\n    x_0 : float (default 0)\n        Position of the peak in x direction.\n    y_0 : float (default 0)\n        Position of the peak in y direction.\n\n    Notes\n    -----\n    This model is evaluated according to the following formula:\n\n        .. math::\n\n            f(x, y) =\n                \\frac{F}{4}\n                \\left[\n                {\\rm erf} \\left(\\frac{x - x_0 + 0.5}\n                {\\sqrt{2} \\sigma} \\right) -\n                {\\rm erf} \\left(\\frac{x - x_0 - 0.5}\n                {\\sqrt{2} \\sigma} \\right)\n                \\right]\n                \\left[\n                {\\rm erf} \\left(\\frac{y - y_0 + 0.5}\n                {\\sqrt{2} \\sigma} \\right) -\n                {\\rm erf} \\left(\\frac{y - y_0 - 0.5}\n                {\\sqrt{2} \\sigma} \\right)\n                \\right]\n\n    where ``erf`` denotes the error function and ``F`` the total\n    integrated flux.\n    \"\"\"\n\n    flux = Parameter(default=1)\n    x_0 = Parameter(default=0)\n    y_0 = Parameter(default=0)\n    sigma = Parameter(default=1, fixed=True)\n\n    _erf = None\n    fit_deriv = None\n\n    @property\n    def bounding_box(self):\n        halfwidth = 4 * self.sigma\n        return ((int(self.y_0 - halfwidth), int(self.y_0 + halfwidth)),\n                (int(self.x_0 - halfwidth), int(self.x_0 + halfwidth)))\n\n    def __init__(self, sigma=sigma.default,\n                 x_0=x_0.default, y_0=y_0.default, flux=flux.default,\n                 **kwargs):\n        if self._erf is None:\n            from scipy.special import erf\n            self.__class__._erf = erf\n\n        super(IntegratedGaussianPRF, self).__init__(n_models=1, sigma=sigma,\n                                                    x_0=x_0, y_0=y_0,\n                                                    flux=flux, **kwargs)\n\n    def evaluate(self, x, y, flux, x_0, y_0, sigma):\n        \"\"\"Model function Gaussian PSF model.\"\"\"\n\n        return (flux / 4 *\n                ((self._erf((x - x_0 + 0.5) / (np.sqrt(2) * sigma)) -\n                  self._erf((x - x_0 - 0.5) / (np.sqrt(2) * sigma))) *\n                 (self._erf((y - y_0 + 0.5) / (np.sqrt(2) * sigma)) -\n                  self._erf((y - y_0 - 0.5) / (np.sqrt(2) * sigma)))))\n\n\nclass PRFAdapter(Fittable2DModel):\n    \"\"\"\n    A model that adapts a supplied PSF model to act as a PRF. It\n    integrates the PSF model over pixel \"boxes\".  A critical built-in\n    assumption is that the PSF model scale and location parameters are\n    in *pixel* units.\n\n    Parameters\n    ----------\n    psfmodel : a 2D model\n        The model to assume as representative of the PSF\n    renormalize_psf : bool\n        If True, the model will be integrated from -inf to inf and\n        re-scaled so that the total integrates to 1.  Note that this\n        renormalization only occurs *once*, so if the total flux of\n        ``psfmodel`` depends on position, this will *not* be correct.\n    xname : str or None\n        The name of the ``psfmodel`` parameter that corresponds to the\n        x-axis center of the PSF.  If None, the model will be assumed to\n        be centered at x=0.\n    yname : str or None\n        The name of the ``psfmodel`` parameter that corresponds to the\n        y-axis center of the PSF.  If None, the model will be assumed to\n        be centered at y=0.\n    fluxname : str or None\n        The name of the ``psfmodel`` parameter that corresponds to the\n        total flux of the star.  If None, a scaling factor will be\n        applied by the ``PRFAdapter`` instead of modifying the\n        ``psfmodel``.\n\n    Notes\n    -----\n    This current implementation of this class (using numerical\n    integration for each pixel) is extremely slow, and only suited for\n    experimentation over relatively few small regions.\n    \"\"\"\n\n    flux = Parameter(default=1)\n    x_0 = Parameter(default=0)\n    y_0 = Parameter(default=0)\n\n    def __init__(self, psfmodel, renormalize_psf=True, flux=flux.default,\n                 x_0=x_0.default, y_0=y_0.default, xname=None, yname=None,\n                 fluxname=None, **kwargs):\n\n        self.psfmodel = psfmodel.copy()\n\n        if renormalize_psf:\n            from scipy.integrate import dblquad\n            self._psf_scale_factor = 1. / dblquad(self.psfmodel,\n                                                  -np.inf, np.inf,\n                                                  lambda x: -np.inf,\n                                                  lambda x: np.inf)[0]\n        else:\n            self._psf_scale_factor = 1\n\n        self.xname = xname\n        self.yname = yname\n        self.fluxname = fluxname\n\n        # these can be used to adjust the integration behavior. Might be\n        # used in the future to expose how the integration happens\n        self._dblquadkwargs = {}\n\n        super(PRFAdapter, self).__init__(n_models=1, x_0=x_0, y_0=y_0,\n                                         flux=flux, **kwargs)\n\n    def evaluate(self, x, y, flux, x_0, y_0):\n        \"\"\"The evaluation function for PRFAdapter.\"\"\"\n\n        if self.xname is None:\n            dx = x - x_0\n        else:\n            dx = x\n            setattr(self.psfmodel, self.xname, x_0)\n\n        if self.xname is None:\n            dy = y - y_0\n        else:\n            dy = y\n            setattr(self.psfmodel, self.yname, y_0)\n\n        if self.fluxname is None:\n            return (flux * self._psf_scale_factor *\n                    self._integrated_psfmodel(dx, dy))\n        else:\n            setattr(self.psfmodel, self.yname, flux * self._psf_scale_factor)\n            return self._integrated_psfmodel(dx, dy)\n\n    def _integrated_psfmodel(self, dx, dy):\n        from scipy.integrate import dblquad\n\n        # infer type/shape from the PSF model.  Seems wasteful, but the\n        # integration step is a *lot* more expensive so its just peanuts\n        out = np.empty_like(self.psfmodel(dx, dy))\n        outravel = out.ravel()\n        for i, (xi, yi) in enumerate(zip(dx.ravel(), dy.ravel())):\n            outravel[i] = dblquad(self.psfmodel,\n                                  xi-0.5, xi+0.5,\n                                  lambda x: yi-0.5, lambda x: yi+0.5,\n                                  **self._dblquadkwargs)[0]\n        return out\n\n\ndef prepare_psf_model(psfmodel, xname=None, yname=None, fluxname=None,\n                      renormalize_psf=True):\n    \"\"\"\n    Convert a 2D PSF model to one suitable for use with\n    `psf_photometry`.\n\n    The resulting model may be a composite model, but should have only\n    the x, y, and flux related parameters un-fixed.\n\n    Parameters\n    ----------\n    psfmodel : a 2D model\n        The model to assume as representative of the PSF.\n    xname : str or None\n        The name of the ``psfmodel`` parameter that corresponds to the\n        x-axis center of the PSF.  If None, the model will be assumed to\n        be centered at x=0, and a new parameter will be added for the\n        offset.\n    yname : str or None\n        The name of the ``psfmodel`` parameter that corresponds to the\n        y-axis center of the PSF.  If None, the model will be assumed to\n        be centered at x=0, and a new parameter will be added for the\n        offset.\n    fluxname : str or None\n        The name of the ``psfmodel`` parameter that corresponds to the\n        total flux of the star.  If None, a scaling factor will be added\n        to the model.\n    renormalize_psf : bool\n        If True, the model will be integrated from -inf to inf and\n        re-scaled so that the total integrates to 1.  Note that this\n        renormalization only occurs *once*, so if the total flux of\n        ``psfmodel`` depends on position, this will *not* be correct.\n\n    Returns\n    -------\n    outmod : a model\n        A new model ready to be passed into `psf_photometry`.\n    \"\"\"\n\n    if xname is None:\n        xinmod = models.Shift(0, name='x_offset')\n        xname = 'offset_0'\n    else:\n        xinmod = models.Identity(1)\n        xname = xname + '_2'\n    xinmod.fittable = True\n\n    if yname is None:\n        yinmod = models.Shift(0, name='y_offset')\n        yname = 'offset_1'\n    else:\n        yinmod = models.Identity(1)\n        yname = yname + '_2'\n    yinmod.fittable = True\n\n    outmod = (xinmod & yinmod) | psfmodel\n\n    if fluxname is None:\n        outmod = outmod * models.Const2D(1, name='flux_scaling')\n        fluxname = 'amplitude_3'\n    else:\n        fluxname = fluxname + '_2'\n\n    if renormalize_psf:\n        # we do the import here because other machinery works w/o scipy\n        from scipy import integrate\n\n        integrand = integrate.dblquad(psfmodel, -np.inf, np.inf,\n                                      lambda x: -np.inf, lambda x: np.inf)[0]\n        normmod = models.Const2D(1./integrand, name='renormalize_scaling')\n        outmod = outmod * normmod\n\n    # final setup of the output model - fix all the non-offset/scale\n    # parameters\n    for pnm in outmod.param_names:\n        outmod.fixed[pnm] = pnm not in (xname, yname, fluxname)\n\n    # and set the names so that psf_photometry knows what to do\n    outmod.xname = xname\n    outmod.yname = yname\n    outmod.fluxname = fluxname\n\n    # now some convenience aliases if reasonable\n    outmod.psfmodel = outmod[2]\n    if 'x_0' not in outmod.param_names and 'y_0' not in outmod.param_names:\n        outmod.x_0 = getattr(outmod, xname)\n        outmod.y_0 = getattr(outmod, yname)\n    if 'flux' not in outmod.param_names:\n        outmod.flux = getattr(outmod, fluxname)\n\n    return outmod\n\n\ndef get_grouped_psf_model(template_psf_model, star_group):\n    \"\"\"\n    Construct a joint PSF model which consists of a sum of PSF's templated on\n    a specific model, but whose parameters are given by a table of objects.\n\n    Parameters\n    ----------\n    template_psf_model : `astropy.modeling.Fittable2DModel` instance\n        The model to use for *individual* objects.  Must have parameters named\n        ``x_0``, ``y_0``, and ``flux``.\n    star_group : `~astropy.table.Table`\n        Table of stars for which the compound PSF will be constructed.  It\n        must have columns named ``x_0``, ``y_0``, and ``flux_0``.\n\n    Returns\n    -------\n    group_psf\n        An `astropy.modeling` ``CompoundModel`` instance which is a sum of the\n        given PSF models.\n    \"\"\"\n\n    group_psf = None\n    for i in range(len(star_group)):\n        psf_to_add = template_psf_model.copy()\n        psf_to_add.flux = star_group['flux_0'][i]\n        psf_to_add.x_0 = star_group['x_0'][i]\n        psf_to_add.y_0 = star_group['y_0'][i]\n\n        if group_psf is None:\n            # this is the first one only\n            group_psf = psf_to_add\n        else:\n            group_psf += psf_to_add\n\n    return group_psf\n", "meta": {"hexsha": "cabfc7857fc93fe919fbb7355751664c8642a5a8", "size": 22814, "ext": "py", "lang": "Python", "max_stars_repo_path": "photutils/psf/models.py", "max_stars_repo_name": "barentsen/photutils", "max_stars_repo_head_hexsha": "57cbe18c8c1b8b08c93daa3d5c8dd74c10c3daae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "photutils/psf/models.py", "max_issues_repo_name": "barentsen/photutils", "max_issues_repo_head_hexsha": "57cbe18c8c1b8b08c93daa3d5c8dd74c10c3daae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "photutils/psf/models.py", "max_forks_repo_name": "barentsen/photutils", "max_forks_repo_head_hexsha": "57cbe18c8c1b8b08c93daa3d5c8dd74c10c3daae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7090909091, "max_line_length": 78, "alphanum_fraction": 0.5736389936, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 5613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521307073646, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.16141235538394447}}
{"text": "\"\"\"\nPython implementation of the LiNGAM algorithms.\nThe LiNGAM Project: https://sites.google.com/site/sshimizu06/lingam\n\"\"\"\n\nimport itertools\nimport warnings\nfrom abc import ABCMeta, abstractmethod\n\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.utils import check_array\n\nfrom .bootstrap import BootstrapMixin\nfrom .hsic import hsic_test_gamma\nfrom .utils import (get_exo_variables, get_sink_variables,\n                    predict_adaptive_lasso)\n\n\nclass _BaseLiNGAM(BootstrapMixin, metaclass=ABCMeta):\n    \"\"\"Base class for all LiNGAM algorithms.\"\"\"\n\n    def __init__(self, random_state=None):\n        \"\"\"Construct a _BaseLiNGAM model.\n\n        Parameters\n        ----------\n        random_state : int, optional (default=None)\n            random_state is the seed used by the random number generator.\n        \"\"\"\n        self._random_state = random_state\n        self._causal_order = None\n        self._adjacency_matrix = None\n\n    @abstractmethod\n    def fit(self, X):\n        \"\"\"Subclasses should implement this method!\n        Fit the model to X.\n\n        Parameters\n        ----------\n        X : array-like, shape (n_samples, n_features)\n            Training data, where n_samples is the number of samples\n            and n_features is the number of features.\n\n        Returns\n        -------\n        self : object\n            Returns the instance itself.\n        \"\"\"\n\n    def estimate_total_effect(self, X, from_index, to_index):\n        \"\"\"Estimate total effect using causal model.\n\n        Parameters\n        ----------\n        X : array-like, shape (n_samples, n_features)\n            Original data, where n_samples is the number of samples\n            and n_features is the number of features.\n        from_index : \n            Index of source variable to estimate total effect.\n        to_index : \n            Index of destination variable to estimate total effect.\n\n        Returns\n        -------\n        total_effect : float\n            Estimated total effect.\n        \"\"\"\n        # Check parameters\n        X = check_array(X)\n\n        # Check from/to causal order\n        from_order = self._causal_order.index(from_index)\n        to_order = self._causal_order.index(to_index)\n        if from_order > to_order:\n            warnings.warn(f'The estimated causal effect may be incorrect because '\n                          f'the causal order of the destination variable (to_index={to_index}) '\n                          f'is earlier than the source variable (from_index={from_index}).')\n\n        # from_index + parents indices\n        parents = np.where(np.abs(self._adjacency_matrix[from_index]) > 0)[0]\n        predictors = [from_index]\n        predictors.extend(parents)\n\n        # Estimate total effect\n        coefs = predict_adaptive_lasso(X, predictors, to_index)\n\n        return coefs[0]\n\n    def get_error_independence_p_values(self, X):\n        \"\"\"Calculate the p-value matrix of independence between error variables.\n\n        Parameters\n        ----------\n        X : array-like, shape (n_samples, n_features)\n            Original data, where n_samples is the number of samples\n            and n_features is the number of features.\n\n        Returns\n        -------\n        independence_p_values : array-like, shape (n_features, n_features)\n            p-value matrix of independence between error variables.\n        \"\"\"\n        # Check parameters\n        X = check_array(X)\n        n_samples = X.shape[0]\n        n_features = X.shape[1]\n\n        E = X - np.dot(self._adjacency_matrix, X.T).T\n        p_values = np.zeros([n_features, n_features])\n        for i, j in itertools.combinations(range(n_features), 2):\n            _, p_value = hsic_test_gamma(np.reshape(E[:, i], [n_samples, 1]),\n                                         np.reshape(E[:, j], [n_samples, 1]))\n            p_values[i, j] = p_value\n            p_values[j, i] = p_value\n\n        return p_values\n\n    def _estimate_adjacency_matrix(self, X, prior_knowledge=None):\n        \"\"\"Estimate adjacency matrix by causal order.\n\n        Parameters\n        ----------\n        X : array-like, shape (n_samples, n_features)\n            Training data, where n_samples is the number of samples\n            and n_features is the number of features.\n        prior_knowledge : array-like, shape (n_variables, n_variables), optional (default=None)\n            Prior knowledge matrix.\n\n        Returns\n        -------\n        self : object\n            Returns the instance itself.\n        \"\"\"\n        sink_vars = get_sink_variables(prior_knowledge)\n        exo_vars = get_exo_variables(prior_knowledge)\n\n        B = np.zeros([X.shape[1], X.shape[1]], dtype='float64')\n        for i in range(1, len(self._causal_order)):\n            target = self._causal_order[i]\n            predictors = self._causal_order[:i]\n\n            # target is not used for prediction if it is included in exogenous variables\n            if target in exo_vars:\n                continue\n\n            # sink variables are not used as predictors\n            predictors = [v for v in predictors if v not in sink_vars]\n\n            B[target, predictors] = predict_adaptive_lasso(\n                X, predictors, target)\n\n        self._adjacency_matrix = B\n        return self\n\n    @property\n    def causal_order_(self):\n        \"\"\"Estimated causal ordering.\n\n        Returns\n        -------\n        causal_order_ : array-like, shape (n_features)\n            The causal order of fitted model, where \n            n_features is the number of features.\n        \"\"\"\n        return self._causal_order\n\n    @property\n    def adjacency_matrix_(self):\n        \"\"\"Estimated adjacency matrix.\n\n        Returns\n        -------\n        adjacency_matrix_ : array-like, shape (n_features, n_features)\n            The adjacency matrix B of fitted model, where \n            n_features is the number of features.\n        \"\"\"\n        return self._adjacency_matrix\n", "meta": {"hexsha": "45159f835e0876340aac6e8eadbf1ee7b3e238d4", "size": 5923, "ext": "py", "lang": "Python", "max_stars_repo_path": "lingam/base.py", "max_stars_repo_name": "Koji-Kurihara/lingam", "max_stars_repo_head_hexsha": "880561f619d2d185614df4a97b6bc38917f9e901", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lingam/base.py", "max_issues_repo_name": "Koji-Kurihara/lingam", "max_issues_repo_head_hexsha": "880561f619d2d185614df4a97b6bc38917f9e901", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lingam/base.py", "max_forks_repo_name": "Koji-Kurihara/lingam", "max_forks_repo_head_hexsha": "880561f619d2d185614df4a97b6bc38917f9e901", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9055555556, "max_line_length": 96, "alphanum_fraction": 0.6078001013, "include": true, "reason": "import numpy", "num_tokens": 1246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.31069437683198775, "lm_q1q2_score": 0.161412353374836}}
{"text": "import functools\nimport multiprocessing\nimport os\nimport pathlib\nimport shelve\n\nimport numpy\nimport pandas\nimport seaborn\nimport ujson\nimport urllib\n\nfrom collections import defaultdict \n\nfrom IPython.display import Image, display\n\nfrom astropy.coordinates import SkyCoord\nfrom astropy import units as u\nimport astropy.io.fits as fits\nimport astropy.utils.data\nfrom astropy.table import vstack\nfrom astropy.timeseries import TimeSeries\nfrom astropy.stats import sigma_clip\n\nfrom astroquery.vizier import Vizier\n\nfrom matplotlib import pyplot\n\nastropy.utils.data.Conf.remote_timeout.set(60)\n\n\nDATA_LOCATION = os.path.join(os.path.expanduser('~'), 'Documents', 'superwasp-data')\nCACHE_LOCATION = os.path.join(DATA_LOCATION, 'cache')\n\nSECONDS_PER_DAY = 60 * 60 * 24\n\nMAIN_WORKFLOW = 7534\nJUNK_WORKFLOW = 17313\n\nif not os.path.exists(DATA_LOCATION):\n    os.mkdir(DATA_LOCATION)\nif not os.path.exists(CACHE_LOCATION):\n    os.mkdir(CACHE_LOCATION)\n\n\ndef batches(i, batch_size=100):\n    for x in range(int(len(i)/batch_size)+1):\n        subset = i[x*batch_size:(x+1)*batch_size]\n        if len(subset) == 0:\n            return\n        yield subset\n\n\nclass PandasDFWrapper(object):\n    def limit(self, limit):\n        return self.__class__(df=self.df[:limit])\n    \n    def cached_pandas_load(self, filename):\n        cache_file_path = pathlib.Path(os.path.join(CACHE_LOCATION, '{}.pickle'.format(filename)))\n        orig_file_path = pathlib.Path(os.path.join(DATA_LOCATION, filename))\n        if cache_file_path.exists() and (\n            not orig_file_path.exists() or\n            cache_file_path.stat().st_mtime > orig_file_path.stat().st_mtime\n        ):\n            return (pandas.read_pickle(cache_file_path), cache_file_path)\n        return (None, cache_file_path)\n\n    def _mpapply(self, func, df=None, axis='rows'):\n        \"\"\"\n        Splits the DataFrame and applies the function across a pool of worker processes.\n\n        On experiment this can actually add a lot of overhead to execution time.\n        But it might be worth it on really long running operations.\n        \"\"\"\n        if df is None:\n            df = self.df\n\n        split_df = numpy.array_split(df, multiprocessing.cpu_count())\n\n        results = []\n        with multiprocessing.Pool() as pool:\n            for part in split_df:\n                results.append(pool.apply_async(part.apply, args=(func, axis)))\n            return pandas.concat([r.get() for r in results])\n\n\nclass CoordinatesMixin(object):\n    VSX_MAG_AMPLITUDE_FLAG = '('\n    VSX_PERIOD_THRESHOLD = 0.1\n    VSX_SEARCH_RADIUS = 2 * u.arcsec\n    VSX_MAGNITUDE_LIMIT = 15\n    \n    @property\n    def coords(self):\n        return SkyCoord(self.df['SWASP ID'].replace(r'^1SWASP', '', regex=True).values, unit=(u.hour, u.deg))\n    \n    @property\n    def fits_urls(self):\n        return self.df['SWASP ID'].apply(lambda s: 'http://wasp.warwick.ac.uk/lcextract?{}'.format(\n            urllib.parse.urlencode(\n                {'objid': s.replace('1SWASP', '1SWASP ')},\n                quote_via=urllib.parse.quote,\n            )\n        ))\n    \n    @property\n    def fits(self):\n        for swasp_id, url in zip(self.df['SWASP ID'], self.fits_urls):\n            yield fits.open(url)\n            \n    @property\n    def timeseries(self):\n        for fits_file in self.fits:\n            hjd_col = fits.Column(name='HJD', format='D', array=fits_file[1].data['TMID'] / 86400 + 2453005.5)\n            lc_data = fits.BinTableHDU.from_columns(fits_file[1].data.columns + fits.ColDefs([hjd_col]))\n            yield TimeSeries.read(lc_data, time_column='HJD', time_format='jd')\n            \n    @property\n    def timeseries_folded(self):\n        for period, timeseries in zip(self.df['Period'], self.timeseries):\n            yield timeseries.fold(\n                period=period * u.second,\n            )\n    \n    def add_coords(self):\n        if 'Coords' not in self.df:\n            coords = self.coords\n            self.df['_RAJ2000'] = coords.ra\n            self.df['_DEJ2000'] = coords.dec\n            \n    def add_fits_urls(self):\n        if 'FITS URL' not in self.df:\n            self.df['FITS URL'] = self.fits_urls\n    \n    def _extend_epochs(self, ts, epochs=1):\n        epoch_length = ts['time'].max() - ts['time'].min()\n        ts_out = [ts]\n        for i in range(epochs):\n            ts_new = ts.copy()\n            ts_new['time'] = ts_new['time'] + epoch_length * (i + 1)\n            ts_out.append(ts_new)\n        return vstack(ts_out)\n\n    def plot(self, folded=False, clip=False, sigma=4, hue=None):\n        if folded:\n            self.add_classification_labels()\n            if 'Period' not in self.df:\n                self.df = self.df.merge(FoldedLightcurves().df, how='left')\n            ts_iter = self.timeseries_folded\n        else:\n            plotted_ids = set()\n            ts_iter = self.timeseries\n\n        for (subject_id, row), ts in zip(self.df.iterrows(), ts_iter):\n            if folded:\n                ts = self._extend_epochs(ts)\n            else:\n                if row['SWASP ID'] in plotted_ids:\n                    continue\n                plotted_ids.add(row['SWASP ID'])\n\n            if clip:\n                ts_flux = sigma_clip(ts['TAMFLUX2'], sigma=sigma)\n            else:\n                ts_flux = ts['TAMFLUX2']\n            \n            ts_data = {\n                'time': ts.time.jd,\n                'flux': ts_flux,\n                'camera': ts['CAMERA_ID'],\n            }\n            pyplot.figure()\n            plot = seaborn.scatterplot(\n                data=ts_data,\n                x='time',\n                y='flux',\n                hue=hue,\n                alpha=0.5,\n                s=1,\n                palette='Set2',\n            )\n            if folded:\n                plot.set_title('{} Period {}s ({})'.format(\n                    row['SWASP ID'],\n                    row['Period'],\n                    row['Classification Label'],\n                ))\n            else:\n                plot.set_title(row['SWASP ID'])\n        \n    def _query_vsx_for_coord(self, coord, cache):\n        coord_str = coord.to_string()\n        if coord_str not in cache:\n            cache[coord_str] = Vizier.query_region(\n                coord,\n                radius=self.VSX_SEARCH_RADIUS, \n                catalog='B/vsx/vsx',\n            )\n\n        return cache[coord_str]\n    \n    def _coords_for_row(self, row, cache):\n        if row['SWASP ID'] not in cache:\n            cache[row['SWASP ID']] = SkyCoord(\n                row['SWASP ID'].replace('1SWASP', ''),\n                unit=(u.hour, u.deg)\n            )\n        \n        return cache[row['SWASP ID']]\n \n    def add_vsx_types(self):\n        if self.df.index.name:\n            orig_index_name = self.df.index.name\n            self.df.reset_index(inplace=True)\n        else:\n            orig_index_name = None\n\n        vsx_types, vsx_types_cache_file = self.cached_pandas_load('vsx_types')\n        if vsx_types is None:\n            vsx_results_dict = defaultdict(list)\n            batch_size = 100\n            result_map = {\n                'VSX Period': 'Period',\n                'VSX Type': 'Type',\n                'VSX Name': 'Name',\n                'VSX Mag Max': 'max',\n                'VSX Mag Min': 'min',\n                'VSX Mag Format': 'f_min',\n            }\n\n            with shelve.open(os.path.join(CACHE_LOCATION, 'vsx_cache')) as vsx_cache:\n                with shelve.open(os.path.join(CACHE_LOCATION, 'coord_cache')) as coord_cache:\n                    for i, (_, row) in enumerate(self.df.iterrows(), start=1):\n                        if i % 100 == 0:\n                            print('Processing row: {}'.format(i), end='\\r')\n                        vsx_query = self._query_vsx_for_coord(\n                            self._coords_for_row(row, coord_cache),\n                            vsx_cache\n                        )\n                        if vsx_query is None:\n                            continue\n\n                        period_min = (row['Period'] / SECONDS_PER_DAY) * (1 - self.VSX_PERIOD_THRESHOLD)\n                        period_max = (row['Period'] / SECONDS_PER_DAY) * (1 + self.VSX_PERIOD_THRESHOLD)\n\n                        for vsx_table in vsx_query:\n                            for vsx_row in vsx_table:\n                                if vsx_row['Period'] < period_min:\n                                    continue\n                                if vsx_row['Period'] > period_max:\n                                    continue\n                                \n                                # When max is actually a mean and min is actually an amplitude\n                                if vsx_row['f_min'] == self.VSX_MAG_AMPLITUDE_FLAG:\n                                    if (vsx_row['max'] + vsx_row['min']) > self.VSX_MAGNITUDE_LIMIT:\n                                        continue\n                                else:\n                                    if vsx_row['min'] > self.VSX_MAGNITUDE_LIMIT:\n                                        continue\n\n                                vsx_results_dict['subject_id'].append(row['subject_id'])\n                                for result_key, vsx_key in result_map.items():\n                                    vsx_results_dict[result_key].append(vsx_row[vsx_key])\n\n            vsx_types = pandas.DataFrame(vsx_results_dict)\n            vsx_types.to_pickle(vsx_types_cache_file)\n\n        if len(vsx_types.index) > 0:\n            vsx_types['VSX Period'] = vsx_types['VSX Period'] * SECONDS_PER_DAY\n            self.df = self.df.merge(\n                vsx_types,\n                left_on='subject_id',\n                right_on='subject_id',\n                how='left',\n            )\n\n        if orig_index_name:\n            self.df.set_index('subject_id', inplace=True)\n\n        \nclass ZooLookupMixin(object):\n    @property\n    def zoo_lookup(self):\n        zoo_lookup, cache_file = self.cached_pandas_load('lookup.dat')\n        if zoo_lookup is not None:\n            return zoo_lookup\n        \n        zoo_lookup = pandas.read_csv(\n            os.path.join(DATA_LOCATION, 'lookup.dat'),\n            delim_whitespace=True,\n            header=None,\n        )\n        zoo_lookup.columns = [\n            'subject_id',\n            'SWASP ID',\n            'Period',\n            'Period Number',\n        ]\n        # Period in this file is rounded differently to the others\n        # So drop it here so it doesn't stop us from merging later\n        zoo_lookup.drop('Period', 'columns', inplace=True)\n        zoo_lookup.to_pickle(cache_file)\n        return zoo_lookup\n    \n    def merge_zoo_lookup(self):\n        if self.df.index.name:\n            orig_index_name = self.df.index.name\n            self.df.reset_index(inplace=True)\n        else:\n            orig_index_name = None\n                \n        self.df = self.df.merge(\n            self.zoo_lookup,\n            how='left',\n        )\n        if orig_index_name:\n            self.df.set_index(orig_index_name, inplace=True)\n\n\nclass ZooniverseSubjects(PandasDFWrapper, ZooLookupMixin):\n    def __init__(self, df=None):\n        if df is not None:\n            self.df = df\n            return\n\n        self.df, self.cache_file = self.cached_pandas_load('superwasp-variable-stars-subjects.csv')\n        if self.df is not None:\n            return\n        \n        self.df = pandas.read_csv(\n            os.path.join(DATA_LOCATION, 'superwasp-variable-stars-subjects.csv'),\n            index_col='subject_id',\n        )\n        self.df.to_pickle(self.cache_file)\n    \n    @property\n    def subject_sets(self):\n        return { set_id: self.get_subject_set(set_id) for set_id in set(self.df['subject_set_id']) }\n    \n    @property\n    def workflows(self):\n        return { \n            workflow_id: self.get_workflow(workflow_id) \n            for workflow_id in set(self.df[self.df['workflow_id'].notna()]['workflow_id'])\n        }\n\n    @property\n    def retired(self):\n        return self.__class__(df=self.df[self.df['retired_at'].notna()])\n\n    @property\n    def active(self):\n        return self.__class__(df=self.df[self.df['retired_at'].isna()])\n    \n    @property\n    def distinct(self):\n        new_df = self.df.reset_index('subject_id')\n        new_df.drop_duplicates('subject_id', inplace=True)\n        new_df.set_index('subject_id', inplace=True)\n        return self.__class__(df=new_df)\n    \n    def get_subject_set(self, set_id):\n        return self.__class__(df=self.df[self.df['subject_set_id'] == set_id])\n    \n    def get_workflow(self, workflow_id):\n        return self.__class__(df=self.df[self.df['workflow_id'] == workflow_id])\n    \n    def decode_locations(self, index=0, target='lightcurve'):\n        self.df = self.df.copy()\n        self.df[target] = self.df['locations'].apply(\n            lambda s: ujson.loads(s)[str(index)]\n        )\n    \n    def display_lightcurves(self, col='lightcurve', start=0, end=None):\n        if col not in self.df:\n            self.decode_locations(target=col)\n            \n        self.df[col][start:end].apply(\n            lambda s: display(Image(url=s, width=500, height=500))\n        )\n\n\nclass ZooniverseClassifications(PandasDFWrapper):\n    ANNOTATION_PREFIX = 'annotation_'\n    \n    def __init__(self, df=None, drop_duplicates=False, duplicate_columns=('subject_ids', 'user_id')):\n        if df is not None:\n            self.df = df\n            return\n\n        try:\n            self.df, self.cache_file = self.cached_pandas_load('superwasp-variable-stars-classifications.csv')\n            if self.df is not None:\n                return\n\n            self.df = pandas.read_csv(\n                os.path.join(DATA_LOCATION, 'superwasp-variable-stars-classifications.csv'),\n                index_col='classification_id',\n            )\n            self.df.to_pickle(self.cache_file)\n        finally:\n            if drop_duplicates:\n                self.df.drop_duplicates(duplicate_columns, inplace=True)\n    \n    @property\n    def workflows(self):\n        return { \n            workflow_id: self.get_workflow(workflow_id) \n            for workflow_id in set(self.df[self.df['workflow_id'].notna()]['workflow_id'])\n        }\n    \n    @property\n    def annotations(self):\n        self.decode_annotations()\n        return self.df[['subject_ids', 'user_id'] + self.annotation_keys]\n    \n    @property\n    def annotation_keys(self):\n        self.decode_annotations()\n        return [col for col in self.df.keys() if col.startswith(self.ANNOTATION_PREFIX)]\n    \n    def get_workflow(self, workflow_id):\n        return ZooniverseClassifications(df=self.df[self.df['workflow_id'] == workflow_id])\n    \n    def get_subjects(self, subject_ids):\n        return ZooniverseClassifications(df=self.df[self.df['subject_ids'].isin(subject_ids)])\n    \n    def get_users(self, user_names):\n        return ZooniverseClassifications(df=self.df[self.df['user_name'].isin(user_names)])\n\n    def decode_annotations(self):\n        if not 'annotations' in self.df.keys():\n            return\n        self.df = self.df.copy()\n        \n        for classification_id, annotations in self.df['annotations'].items():\n            for annotation in ujson.loads(annotations):\n                annotation_col = self.ANNOTATION_PREFIX + annotation['task']\n                if annotation_col not in self.df:\n                    self.df[annotation_col] = pandas.Series([], dtype=str)\n                self.df.at[classification_id, annotation_col] = annotation['value']\n        self.df.drop('annotations', 'columns', inplace=True)\n    \n    def count_annotations(self, col=None, drop_duplicates=True):\n        self.decode_annotations()\n        if not col:\n            col = self.annotation_keys[0]\n\n        df = self.annotations.reset_index()\n        if drop_duplicates:\n            df.drop_duplicates(['user_id', 'subject_ids'], inplace=True)\n\n        return pandas.pivot_table(\n            df, \n            index='subject_ids', \n            values='classification_id', \n            columns=col,\n            aggfunc=lambda x: len(x.unique()),\n            fill_value=0,\n        )\n\n\nclass FoldedLightcurves(PandasDFWrapper, CoordinatesMixin, ZooLookupMixin):\n    def __init__(self, min_period=0, df=None):\n        self.min_period = min_period\n        \n        if df is not None:\n            self.df = df\n            return\n        \n        self.df, self.cache_file = self.cached_pandas_load('results_total.dat')\n        if self.df is not None:\n            return\n        \n        self.df = pandas.read_csv(\n            os.path.join(DATA_LOCATION, 'results_total.dat'),\n            delim_whitespace=True,\n            header=None,\n        )\n        self.df.columns = [\n            'Camera Number',\n            'SWASP',\n            'ID',\n            'Period Number',\n            'Period',\n            'Sigma',\n            'Chi Squared',\n            'Period Flag'\n        ]\n        self.df = self.df[(self.df['Period Flag'] == 0) & (self.df['Period'] >= min_period)]\n        self.df['SWASP ID'] = self.df['SWASP'] + self.df['ID']\n        self.df.drop(['Period Flag', 'Camera Number', 'SWASP', 'ID'], 'columns', inplace=True)\n        self.df.to_pickle(self.cache_file)\n\n    def get_siblings(self, swasp_id):\n        return self.__class__(df=self.df[self.df['SWASP ID'] == swasp_id], min_period=self.min_period)\n\n\nclass AggregatedClassifications(PandasDFWrapper, CoordinatesMixin):\n    PULSATOR = 1\n    EA_EB = 2\n    EW = 3\n    ROTATOR = 4\n    UNKNOWN = 5\n    JUNK = 6\n    CLASSIFICATION_LABELS = {\n        PULSATOR: 'Pulsator',\n        EA_EB: 'EA/EB',\n        EW: 'EW',\n        ROTATOR: 'Rotator',\n        UNKNOWN: 'Unknown',\n        JUNK: 'Junk',\n    }\n\n    def __init__(self, df=None):\n        if df is not None:\n            self.df = df\n            return\n        \n        self.df, self.cache_file = self.cached_pandas_load('class_top.csv')\n        if self.df is not None:\n            return\n\n        self.df = pandas.read_csv(\n            os.path.join(DATA_LOCATION, 'class_top.csv'),\n            delim_whitespace=True,\n            header=None,\n        )\n        self.df.columns = [\n            'subject_id',\n            'SWASP ID',\n            'Period Number',\n            'Period',\n            'Classification',\n            'Period Uncertainty',\n            'Classification Count',\n        ]\n        # Period in this file is rounded differently to the others\n        # So drop it here so it doesn't stop us from merging later\n        self.df.drop('Period', 'columns', inplace=True)\n        self.df.set_index('subject_id', inplace=True)\n        self.df.to_pickle(self.cache_file)\n\n    def add_classification_labels(self):\n        self.df = self.df.copy()\n        self.df['Classification Label'] = self.get_classification_labels(self.df['Classification'])\n\n    def get_classification_labels(self, series):\n        return series.apply(lambda c: self.CLASSIFICATION_LABELS.get(c, None))\n\n    def get_class(self, classification):\n        return self.__class__(df=self.df[self.df['Classification'] == classification])\n\n    def remove_class(self, classification):\n        return self.__class__(df=self.df[self.df['Classification'] != classification])\n\n    @property\n    def pulsators(self):\n        return self.get_class(self.PULSATOR)\n\n    @property\n    def eaebs(self):\n        return self.get_class(self.EA_EB)\n\n    @property\n    def ews(self):\n        return self.get_class(self.EW)\n\n    @property\n    def rotators(self):\n        return self.get_class(self.ROTATOR)\n\n    @property\n    def unknowns(self):\n        return self.get_class(self.UNKNOWN)\n\n    @property\n    def junk(self):\n        return self.get_class(self.JUNK)\n\n    @property\n    def real(self):\n        return self.remove_class(self.JUNK)\n\n\nclass UnifiedSubjects(ZooniverseSubjects, FoldedLightcurves, AggregatedClassifications):\n    def __init__(\n        self, \n        zooniverse_subjects=None, \n        folded_lightcurves=None,\n        aggregated_classifications=None,\n        df=None, \n        min_period=0\n    ):\n        self.min_period = min_period\n        \n        if df is not None:\n            self.df = df\n            return\n        \n        if not zooniverse_subjects:\n            zooniverse_subjects = ZooniverseSubjects()\n        if not folded_lightcurves:\n            folded_lightcurves = FoldedLightcurves(min_period=min_period)\n        if not aggregated_classifications:\n            aggregated_classifications = AggregatedClassifications()\n        \n        self.df = zooniverse_subjects.df\n        self.merge_zoo_lookup()\n        self.df = self.df.reset_index().merge(\n            aggregated_classifications.df.reset_index(),\n            how='left',\n        )\n        self.df = self.df.merge(\n            folded_lightcurves.df,\n            how='left',\n        )\n        self.df.set_index('subject_id', inplace=True)\n    \n    def get_siblings(self, obj_id):\n        if type(obj_id) == int:\n            swasp_id = self.df[self.df.index == obj_id].iloc[0]['SWASP ID']\n        else:\n            swasp_id = obj_id\n        \n        return super().get_siblings(swasp_id)\n    \n\n", "meta": {"hexsha": "42e087fe59ccd3189e8e9bf491258aef12753596", "size": 21009, "ext": "py", "lang": "Python", "max_stars_repo_path": "swasputils.py", "max_stars_repo_name": "adammcmaster/superwasp-long-periods", "max_stars_repo_head_hexsha": "0fb008d2c4bdd5f43dc4138e0d025cd56ec6c278", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-14T17:32:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-14T17:32:18.000Z", "max_issues_repo_path": "swasputils.py", "max_issues_repo_name": "adammcmaster/superwasp-tools", "max_issues_repo_head_hexsha": "0fb008d2c4bdd5f43dc4138e0d025cd56ec6c278", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "swasputils.py", "max_forks_repo_name": "adammcmaster/superwasp-tools", "max_forks_repo_head_hexsha": "0fb008d2c4bdd5f43dc4138e0d025cd56ec6c278", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.40063593, "max_line_length": 110, "alphanum_fraction": 0.5649483555, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 4634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.1611928269782935}}
{"text": "\"\"\"\nModule used to mimic observations.\n\n----\n\n.. include license and copyright\n.. include:: ../include/copy.rst\n\n----\n\n.. include common links, assuming primary doc root is up one directory\n.. include:: ../include/links.rst\n\"\"\"\n\n#Extraction:\n#    - fiber-extraction aperture (pixels, optimal?)\n#    - fiber PSF FWHM on detector (pixels)\n#\n#    - spectral resolution (R)\n#    - dispersion on detector (A per pixel)\n#\n#Detector:\n#    - arcsec / pixel (spatial)\n#    - angstrom / pixel (spectral)\n#    - detector readnoise (e-)\n#    - detector darkcurrent (e-/hour)\n#\n#Throughput\n#    - spectrograph throughput\n#        - detector QE\n#        - camera efficiency\n#        - grating efficiency\n#        - focal-plane to grating tansmission efficiency\n#            - foreoptics, lenslet, coupling, fiber transmission, FRD,\n#              collimator, dichroic(s)\n#\n#    - top-of-telescope throughput\n#        - telescope efficiency\n#        - spectrograph efficiency\n#\n#Point-source Aperture losses\n#    - fiber diameter (arcsec, mm)\n#    - focal-plane plate scale (arcsec/mm)\n#    - seeing (arcsec)\n#    - pointing error (arcsec)\n#\n#*Source:\n#    - source spectrum (1e-17 erg/s/cm^2/angstrom)\n#\n#    - point source\n#        - source mag (at wavelength/in band above)\n#\n#    - extended source\n#        - source surface brightness (at wavelength/in band above)\n#        - source size (kpc/arcsec)\n#        - cosmology\n#\n#    - source velocity/redshift\n#\n#*Sky:\n#    - sky spectrum (1e-17 erg/s/cm^2/angstrom)\n#\n#Observation:\n#    - obs date\n#    - lunar phase/illumination (days, fraction)\n#    - sky coordinates\n#    - wavelength for calculation (angstroms)\n#    - band for calculation\n#    - sky surface brightness (mag/arcsec^2, at wavelength/in band above)\n#    - airmass\n#    - exposure time (s)\n#\n#Telescope:\n#    - location\n#    - telescope diameter (or effective) (m^2)\n#    - central obstruction\n\nimport os\nimport warnings\n\nfrom IPython import embed\n\nimport numpy\n\nfrom scipy import signal\n\nfrom matplotlib import pyplot\n\nfrom . import source, spectrum, util\n\nclass Observation:\n    \"\"\"\n    Observation of the sky with or without a source.\n\n    Args:\n        telescope (:class:`~enyo.etc.telescopes.Telescope`):\n            Telescope used for the observation.\n        sky_spectrum (:class:`~enyo.etc.spectrum.Spectrum`):\n            Sky spectrum\n        spec_aperture (:class:`~enyo.etc.aperture.Aperture`):\n            On-sky entrance aperture.\n        exposure_time (:obj:`float`):\n            Exposure time in seconds.\n        detector (:class:`~enyo.etc.detector.Detector`):\n            Instrument detector object.\n        system_throughput (:class:`~enyo.etc.efficiency.Efficiency`, optional):\n            System throughput; i.e., ratio of the number of photons\n            detected to the total number incident on the telescope\n            primary.  If None, system throughput is unity.\n        atmospheric_throughput (:class:`~enyo.etc.efficiency.Efficiency`, optional):\n            Atmospheric throughput; i.e., the ratio of the number of\n            the photons incident on the telescope primary to the\n            number of photons hitting the top of the atmosphere. If\n            None, assume there is no atmosphere.\n        airmass (:obj:`float`, optional):\n            Airmass of the observation. If None, assume\n            ``atmospheric_throughput`` is at the correct airmass or\n            there is no atmosphere.\n        onsky_source_distribution (:class:`~enyo.etc.source.Source`, optional):\n            On-sky source surface-brightness distribution, including\n            any seeing effects. If None, assume observation is only\n            of the sky. Normalization is irrelevant; used to\n            calculate aperture losses.\n        source_spectrum (:class:`~enyo.etc.spectrum.Spectrum`, optional):\n            Spectrum of the source with the flux normalized to the\n            *total* source flux.\n        extraction (:class:`~enyo.etc.extract.Extraction`, optional):\n            Object used to calculate the extraction losses and tally\n            the number of pixels included in the extraction to get\n            the read-noise hit. TODO: Currently *cannot* be None;\n            make a required argument.\n        snr_units (:obj:`str`, optional):\n            Units of the S/N calculation. Must be ``'pixel'``,\n            ``'angstrom'``, or ``'resolution'`` for S/N per pixel,\n            per angstrom, or per resolution element.\n\n    Raises:\n        ValueError:\n            Raised if the requested S/N units cannot be calculated\n            (i.e., the provided spectrum does not define the\n            resolution meaning that the S/N per resolution element is\n            undefined) or if the unit string for the S/N is not\n            recognized.\n\n    \"\"\"\n    def __init__(self, telescope, sky_spectrum, spec_aperture, exposure_time, detector,\n                 system_throughput=None, atmospheric_throughput=None, airmass=None,\n                 onsky_source_distribution=None, source_spectrum=None, extraction=None,\n                 snr_units='pixel'):\n\n        # Save the input or use defaults\n        self.source = onsky_source_distribution\n\n        # Sky spectrum is expected to be independent of position within\n        # the aperture and be the sky flux density per unit area, where\n        # the unit area is defined by the aperture object (arcsec^2)\n        # i.e., the units are, e.g., erg/s/cm^2/angstrom/arcsec^2\n        self.source_spectrum = source_spectrum\n\n        # Match the sampling of the sky and source spectrum, if possible\n        self.sky_spectrum = sky_spectrum if self.source_spectrum is None else \\\n                                spectrum.Spectrum(self.source_spectrum.wave,\n                                                  sky_spectrum.interp(self.source_spectrum.wave),\n                                                  log=self.source_spectrum.log)\n\n        # In the current implementation, the source spectrum is expected\n        # to be:\n        #   - independent of position within the source\n        #   - the source flux density integrated over the full source\n        #     distribution; i.e., units are, e.g., erg/s/cm^2/angstrom\n        self.wave = self.sky_spectrum.wave.copy()\n        self.sres = self.sky_spectrum.sres.copy() if sky_spectrum.sres is not None \\\n                        else (None if self.source_spectrum is None \n                                else self.source_spectrum.sres.copy())\n\n        self.atmospheric_throughput = atmospheric_throughput\n        self.telescope = telescope\n        self.aperture = spec_aperture\n        self.system_throughput = system_throughput\n        self.detector = detector\n        self.exptime = exposure_time\n        self.extraction = extraction\n\n        # Get the \"aperture factor\". If the source distribution is not\n        # provided, the source surface brightness is assumed to be\n        # uniform within the aperture (like the sky). In this case, the\n        # aperture factor is the area of the aperture itself so that\n        # the object flux is the integral of the surface brightness\n        # over the aperture size (like the sky).\n        self.aperture_factor = self.aperture.area if self.source is None \\\n                                     else self.aperture.integrate_over_source(self.source) \\\n                                                / self.source.integral\n\n        # Get the total object flux incident on the focal plane in\n        # electrons per second per angstrom\n        _object_flux = numpy.zeros(self.wave.size, dtype=float) if self.source_spectrum is None \\\n                            else self.source_spectrum.photon_flux(inplace=False) \\\n                                    * self.telescope.area * self.aperture_factor \\\n                                    * self.detector(self.wave)\n        if self.atmospheric_throughput is not None:\n            _object_flux *= self.atmospheric_throughput(self.wave)\n        if self.system_throughput is not None:\n            _object_flux *= self.system_throughput(self.wave)\n\n        # Total sky flux in electrons per second per angstrom; the\n        # provided sky spectrum is always assumed to be uniform over the\n        # aperture\n        _sky_flux = self.sky_spectrum.photon_flux(inplace=False) \\\n                        * self.telescope.area * self.aperture.area \\\n                        * self.detector(self.wave)\n        if self.system_throughput is not None:\n            _sky_flux *= self.system_throughput(self.wave)\n\n        # Set the units for the output:\n        dw = self.sky_spectrum.wavelength_step()\n        if snr_units == 'pixel':\n            _object_flux *= dw\n            _sky_flux *= dw\n            spectral_width = 1.\n        elif snr_units == 'angstrom':\n            spectral_width = 1./dw\n        elif snr_units == 'resolution':\n            if self.sres is None:\n                raise ValueError('Cannot compute S/N per resolution element without resolution '\n                                 'vector.')\n            _object_flux *= self.wave/self.sres\n            _sky_flux *= self.wave/self.sres\n            spectral_width = self.wave/self.sres/dw\n        else:\n            raise ValueError('Unknown S/N units requested.')\n\n        # Observe and extract the source\n        # TODO: Set spectral_pixels...\n        self.object_flux, self.obj_shot_var, self.sky_flux, self.sky_shot_var, self.read_var \\\n                = self.extraction.sum_signal_and_noise(_object_flux, _sky_flux, self.exptime,\n                                                       spectral_width=spectral_width)\n\n    def simulate(self, sky_only=False, sky_sub=False, sky_err=0.1):\n        \"\"\"\n        Return a simulated spectrum.\n\n        Args:\n            sky_only (:obj:`bool`, optional):\n                Only include the sky flux in the simulated spectrum\n                (no object flux)\n            sky_sub (:obj:`bool`, optional):\n                Provide the object spectrum only, but include the sky\n                flux shot noise and additional error from the sky\n                subtraction.\n            sky_err (:obj:`float`, optional):\n                The fraction of the total sky error incurred due to\n                the sky subtraction. Should be between 0 and 1; 0\n                means no additional error is incurred, 1 means that\n                the sky noise from the sky subtration is the same as\n                the sky noise from the observation itself.\n\n        Returns:\n            :class:`~enyo.etc.spectrum.Spectrum`: The simulated\n            spectrum.\n        \"\"\"\n        if sky_only:\n            shot_var = self.sky_shot_var\n            flux = self.sky_flux\n        elif sky_sub:\n            shot_var = self.obj_shot_var + (1 + numpy.square(sky_err))*self.sky_shot_var\n            flux = self.object_flux\n        else:\n            shot_var = self.obj_shot_var + self.sky_shot_var\n            flux = self.object_flux + self.sky_flux\n\n#        error=numpy.sqrt(shot_var + self.read_var)\n#        draw = numpy.random.normal(scale=error)\n#        return spectrum.Spectrum(self.wave, flux + draw, error=error,\n#                                 log=self.sky_spectrum.log if self.source_spectrum is None\n#                                         else self.source_spectrum.log)\n\n        # Draw from a Poisson distribution for the shot noise,\n        # subtracted the expectation value of the distribution so that\n        # only the noise is added\n        shot_draw = numpy.random.poisson(lam=shot_var)-shot_var\n        # Draw from a Gaussian distribution for the read noise\n        read_draw = numpy.random.normal(scale=numpy.sqrt(self.read_var))\n        return spectrum.Spectrum(self.wave, flux + shot_draw + read_draw,\n                                 error=numpy.sqrt(shot_var + self.read_var),\n                                 log=self.sky_spectrum.log if self.source_spectrum is None\n                                         else self.source_spectrum.log)\n\n    def snr(self, sky_sub=False, sky_err=0.1):\n        \"\"\"\n        Calculate the S/N.\n\n        Args:\n            sky_sub (:obj:`bool`, optional):\n                Provide the object spectrum only, but include the sky\n                flux shot noise and additional error from the sky\n                subtraction.\n            sky_err (:obj:`float`, optional):\n                The fraction of the total sky error incurred due to\n                the sky subtraction. Should be between 0 and 1; 0\n                means no additional error is incurred, 1 means that\n                the sky noise from the sky subtration is the same as\n                the sky noise from the observation itself.\n\n        Returns:\n            :class:`~enyo.etc.spectrum.Spectrum`: The S/N spectrum.\n            WARNING: Here, :class:`~enyo.etc.spectrum.Spectrum` is\n            used as a container class for the S/N vector; some\n            functionality of the class will not be valid!\n        \"\"\"\n        flux = self.object_flux + self.sky_flux\n        var = self.obj_shot_var + self.sky_shot_var + self.read_var\n        if sky_sub:\n            flux -= self.sky_flux\n            var += numpy.square(sky_err)*self.sky_shot_var\n        # TODO: add additional noise from sky subtraction\n        return spectrum.Spectrum(self.wave, flux / numpy.sqrt(var),\n                                 log=self.sky_spectrum.log if self.source_spectrum is None\n                                         else self.source_spectrum.log)\n\n\ndef monochromatic_image(sky, spec_aperture, spec_kernel, platescale, pixelsize, onsky_source=None,\n                        scramble=False):\n    \"\"\"\n    Generate a monochromatic image of the sky, with or with out a\n    source, taken by a spectrograph through an aperture.\n\n    .. warning::\n\n        - May resample the `source` and `spec_kernel` maps.\n\n    .. todo::\n\n        - Add effect of differential atmospheric refraction\n        - Allow a force map size and pixel sampling\n\n    Args:\n        sky (:class:`enyo.etc.source.OnSkySource`):\n            Sky flux distribution.\n        spec_aperture (:class:`enyo.etc.aperture.Aperture`):\n            Spectrograph aperture. Aperture is expected to be\n            oriented with the dispersion along the first axis (e.g.,\n            the slit width is along the abcissa).\n        spec_kernel (:class:`enyo.etc.kernel.SpectrographGaussianKernel`):\n            Convolution kernel describing the point-spread function\n            of the spectrograph.\n        platescale (:obj:`float`):\n            Platescale in mm/arcsec at the detector\n        pixelsize (:obj:`float`):\n            Size of the detector pixels in mm.\n        onsky_source (:class:`enyo.etc.source.OnSkySource`, optional):\n            On-sky distribution of the source flux. If None, only sky\n            is observed through the aperture.\n        scramble (:obj:`bool`, optional):\n            Fully scramble the source light passing through the\n            aperture. This should be False for slit observations. For\n            fiber observations, this should be True and makes the\n            nominal assumption that the focal plane incident on the\n            fiber face is perfectly scrambled.\n    \"\"\"\n    # Check input\n    if onsky_source is not None:\n        if onsky_source.sampling is None or onsky_source.size is None:\n            warnings.warn('Source was not provided with an initial map sampling; doing so now '\n                          'with default sampling and size.')\n            onsky_source.make_map()\n\n    # Detector pixel scale in arcsec/pixel\n    pixelscale = pixelsize/platescale\n\n    # Assume the sampling of the source is provided with the maximum\n    # allowed pixel size. Determine a pixel size that is no more than\n    # this, up to an integer number of detector pixels. Use an integer\n    # number specifically so that the result of the kernel convolution\n    # can be simply rebinned to match the detector pixel size.\n    # `sampling` is in arcsec per pixel\n    sampling = pixelscale if onsky_source is None else min(onsky_source.sampling, pixelscale)\n    oversample = int(pixelscale/sampling)+1 if sampling < pixelscale else 1\n    sampling = pixelscale/oversample\n\n    # Assume the size of the image properly samples the source.\n    # Determine a map size that at least encompasses the input source\n    # and the input aperture. The factor of 1.5 is ad hoc; could likely\n    # be lower. `size` is in arcsec\n    dx, dy = 1.5*numpy.diff(numpy.asarray(spec_aperture.bounds).reshape(2,-1), axis=0).ravel()\n    size = max(dx,dy) #if onsky_source is None else max(onsky_source.size, dx, dy)\n\n    # TODO: Below alters `source` and `spec_kernel`. Should maybe\n    # instead save the old sampling and size and then resample back to\n    # the input before returning.\n\n    # Resample the distribution maps. Classes OnSkySource and Aperture\n    # use arcsecond units.\n    if onsky_source is not None:\n        onsky_source.make_map(sampling=sampling, size=size)\n    sky.make_map(sampling=sampling, size=size)\n    ap_img = spec_aperture.response(sky.x, sky.y)\n\n    # However, SpectrographGaussianKernel uses mm, so we need to\n    # convert sampling from arcsec/pixel to mm/pixel using the\n    # platescale.\n    spec_kernel.resample(pixelscale=platescale*sampling)\n\n    # Construct the image. Note that scrambling simply scales the\n    # aperture image by the flux that enters it; otherwise, the source\n    # image is just attenuated by the aperture response map.\n    source_img = sky.data if onsky_source is None else onsky_source.data + sky.data\n    input_img = ap_img*numpy.sum(source_img*ap_img)/numpy.sum(ap_img) if scramble \\\n                        else source_img*ap_img\n\n    # Convolve it with the spectrograph imaging kernel\n    mono_img = signal.fftconvolve(input_img, spec_kernel.array, mode='same')\n    # Return the image, downsampling if necessary\n    return util.boxcar_average(mono_img, oversample) if oversample > 1 else mono_img\n\n\ndef twod_spectrum(sky_spectrum, spec_aperture, spec_kernel, platescale, linear_dispersion,\n                  pixelsize, source_distribution=None, source_spectrum=None, thresh=None,\n                  scramble=False, wave_lim=None, field_coo=None, opticalmodel=None):\n    \"\"\"\n    Documentation TBW.\n\n    if optical model is not provided:\n        - ignore field_coo\n        - return rectilinear 2D spectrum\n\n    platescale is in mm/arcsec\n    linear_dispersion is in A/mm\n    pixelsize is in mm\n\n    \"\"\"\n    # Ensure that the sky spectrum and source spectrum will have the same wavelength limits\n    if source_spectrum is not None and wave_lim is None:\n        wave_lim = source_spectrum.wave[[0,-1]]\n\n    # Get the sky-only monochromatic image\n    sky = source.OnSkyConstant(1.0)\n    sky_img = monochromatic_image(sky, spec_aperture, spec_kernel, platescale, pixelsize,\n                                  scramble=scramble)\n\n    # Renormalize the sky slit image such that the integral is the area of the aperture.\n    sky_img *= spec_aperture.area / numpy.sum(sky_img)/numpy.square(sky.sampling)\n\n    source_img = None\n    if source_distribution is not None and source_spectrum is not None:\n        # Reset the source distribution map\n        source_distribution.reset_map()\n\n        # Get the source-only monochromatic image\n        sky = source.OnSkyConstant(0.0)\n        source_img = monochromatic_image(sky, spec_aperture, spec_kernel, platescale, pixelsize,\n                                         onsky_source=source_distribution, scramble=scramble)\n        # Renormalize the source image by the integral of the onsky-source;\n        # this maintains the effects of aperture losses\n        source_img /= source_distribution.integral\n\n    s = numpy.array([0,0])\n    e = numpy.array([*sky_img.shape])\n    if thresh is not None:\n        indx = sky_img > thresh\n        s, e = numpy.append(numpy.where(numpy.any(indx, axis=1))[0][[0,-1]],\n                            numpy.where(numpy.any(indx, axis=0))[0][[0,-1]]).reshape(2,2).T\n        if source_img is not None:\n            indx = source_img > thresh\n            _s, _e = numpy.append(numpy.where(numpy.any(indx, axis=1))[0][[0,-1]],\n                                  numpy.where(numpy.any(indx, axis=0))[0][[0,-1]]).reshape(2,2).T\n            s = numpy.minimum(s, _s)\n            e = numpy.maximum(e, _e)\n\n    sky_img = sky_img[s[0]:e[0],s[1]:e[1]]\n    if source_img is not None:\n        source_img = source_img[s[0]:e[0],s[1]:e[1]]\n\n    # Get the 2D spectrum\n    dispscale = linear_dispersion*pixelsize\n    wave0, sky_2d_spec = rectilinear_twod_spectrum(sky_spectrum, sky_img, dispscale,\n                                                   wave_lim=wave_lim)\n\n    if source_distribution is None or source_spectrum is None:\n        return sky_2d_spec if opticalmodel is None \\\n                    else opticalmodel.project_2d_spectrum(sky_2d_spec, platescale,\n                                                          linear_dispersion, pixelsize, wave0,\n                                                          field_coo=field_coo)\n\n    # Get the 2D spectrum\n    wave0, source_2d_spec = rectilinear_twod_spectrum(source_spectrum, source_img, dispscale,\n                                                      wave_lim=wave_lim)\n\n    return sky_2d_spec + source_2d_spec if opticalmodel is None \\\n                    else opticalmodel.project_2d_spectrum(sky_2d_spec + source_2d_spec, platescale,\n                                                          linear_dispersion, pixelsize, wave0,\n                                                          field_coo=field_coo)\n\n#def rectilinear_twod_spectrum(spectrum, aperture_image, dispscale, wave_lim=None, oversample=1):\n#    \"\"\"\n#    Construct a rectilinear 2D spectrum.\n#\n#    spectral dimension of aperture_image is along the first axis\n#\n#    aperture_image has to be odd?\n#    \"\"\"\n#\n#    # TODO: Let dispersion scale be non-linear?\n#\n#    # Resample the spectrum to the appropriate dispersion scale up to some constant\n#    if wave_lim is None:\n#        # TODO: This should be the pixel boundaries, not the pixel centers!\n#        wave_lim = spectrum.wave[[0,-1]]\n#    resamp_wave = numpy.arange(wave_lim[0], wave_lim[1] + dispscale/oversample,\n#                               dispscale/oversample)\n#    resampled_spectrum = spectrum.resample(resamp_wave)\n##    pyplot.plot(spectrum.wave, spectrum.flux)\n##    pyplot.plot(resampled_spectrum.wave, resampled_spectrum.flux)\n##    pyplot.show()\n#\n#    # Oversample the image spectrally\n#    _aperture_image = util.block_replicate(aperture_image, (oversample,1)) \\\n#                            if oversample > 1 else aperture_image\n#\n#    # Number of spectral and spatial channels in the aperture image\n#    nspec, nspat = _aperture_image.shape\n#    width = nspec//2\n#    # Length of the spectrum\n#    npix = len(resampled_spectrum)\n#\n#    # Pad the spectrum with zeros and create one shifted copy per spectral channel\n#    flux = numpy.zeros((nspec,npix), dtype=float)\n#    for i in range(nspec):\n#        flux[i,width:-width] = resampled_spectrum.flux[i:npix-nspec+i+1]\n#\n#    import time\n#    t = time.perf_counter()\n#    flux = numpy.tile(flux, (nspat,1))\n#    print('Tile: {0}s'.format(time.perf_counter()-t))\n#\n#    # Do the convolution\n#    t = time.perf_counter()\n#    twodspec = flux[:,:] * _aperture_image.ravel()[:,None]\n#    indx = numpy.arange(0,nspec*nspat,nspec)\n#    twodspec = numpy.add.reduceat(twodspec, indx, axis=0)\n#    print('Mult: {0}s'.format(time.perf_counter()-t))\n#\n#    return util.block_average(twodspec, (oversample,1)) if oversample > 1 else twodspec\n\n\ndef rectilinear_twod_spectrum(spectrum, aperture_image, dispscale, wave_lim=None, oversample=1):\n    \"\"\"\n    Construct a rectilinear 2D spectrum.\n\n    Documentation TBW.\n\n    spectral dimension of aperture_image is along the first axis\n\n    aperture_image has to be odd?\n    dispscale is A/pixel\n\n    remove rows columns with no pixels above thresh\n\n    \"\"\"\n\n    # TODO: Let dispersion scale be non-linear?\n\n    # Resample the spectrum to the appropriate dispersion scale up to some constant\n    if wave_lim is None:\n        # TODO: This should be the pixel boundaries, not the pixel centers!\n        wave_lim = spectrum.wave[[0,-1]]\n    resamp_wave = numpy.arange(wave_lim[0], wave_lim[1] + dispscale/oversample,\n                               dispscale/oversample)\n    resampled_spectrum = spectrum.resample(resamp_wave)\n    wave0 = numpy.mean(resampled_spectrum.wave[:oversample])\n#    pyplot.plot(spectrum.wave, spectrum.flux)\n#    pyplot.plot(resampled_spectrum.wave, resampled_spectrum.flux)\n#    pyplot.show()\n\n    # Oversample the image spectrally\n    _aperture_image = util.block_replicate(aperture_image, (oversample,1)) \\\n                            if oversample > 1 else aperture_image.copy()\n\n    # Number of spectral and spatial channels in the aperture image;\n    # number of convolution kernels is nspat\n    nspat, nspec = _aperture_image.shape\n\n    twodspec = numpy.zeros((len(resampled_spectrum),nspat), dtype=float)\n    for i in range(nspat):\n        twodspec[:,i] = signal.fftconvolve(resampled_spectrum.flux, _aperture_image[i],\n                                           mode='same')\n    \n    return wave0, (util.block_average(twodspec, (oversample,1)) if oversample > 1 else twodspec)\n\n", "meta": {"hexsha": "d85433bd369dec59d34051434e35fa52d93c7efe", "size": 25285, "ext": "py", "lang": "Python", "max_stars_repo_path": "enyo/etc/observe.py", "max_stars_repo_name": "Keck-FOBOS/enyo", "max_stars_repo_head_hexsha": "82dd4324083d456c78bcbafdd081bee53f0c7ba9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "enyo/etc/observe.py", "max_issues_repo_name": "Keck-FOBOS/enyo", "max_issues_repo_head_hexsha": "82dd4324083d456c78bcbafdd081bee53f0c7ba9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "enyo/etc/observe.py", "max_forks_repo_name": "Keck-FOBOS/enyo", "max_forks_repo_head_hexsha": "82dd4324083d456c78bcbafdd081bee53f0c7ba9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9286926995, "max_line_length": 99, "alphanum_fraction": 0.6301364445, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.27512971787959795, "lm_q1q2_score": 0.16097871548696213}}
{"text": "from __future__ import annotations\nimport numpy as np\nimport math\nfrom pyscses.constants import fundamental_charge, boltzmann_eV\nfrom pyscses.grid_point import GridPoint\nfrom pyscses.defect_species import DefectSpecies\nfrom typing import List, Optional, Dict\nfrom pyscses.defect_at_site import DefectAtSite\nimport warnings\n\nclass LabelError(Exception):\n    pass\n\nclass Site:\n    \"\"\"The Site class contains all the information about a given site and the defects occupying that site.\n    This class contains functions for the calculations which correspond to each individual site, rather than the system as a whole.\n\n    Attributes:\n        label (str): Reference label for this site. i.e. 'O' for an oxygen site.\n        x (float): x coordinate of the site.\n        defect_energies (list): List of segregation energies for all defects present at the site.\n        defect_species (list): List of defect species for all defects present at the site.\n        defects (list): List of DefectAtSite objects, containing the properties of all individual defects at the site.\n        scaling (float): A scaling factor that can be applied in the charge calculation.\n        valence (float): The charge of the defect present at the site (in atomic units).\n        saturation_parameter (float): Optional saturation parameter as described in\n            `Hendricks et al. Sol. Stat. Ionics (2002)`_\n            and `Swift et al. Nature Comp. Sci. (2021)`_.\n            Setting `saturation_parameter` < `1.0` sets some proportion of excluded sites that are\n            unavailable for occupation by any explicit defects.\n            Default value is `1.0`, i.e., 100% of sites may be occupied.\n        defects (list): List of Defect_Species objects for all defects present at the site.\n        sites (list): List containing all x coordinates and corresponding  defect segregation energies.\n\n    .. _Hendricks et al. Sol. Stat. Ionics (2002):\n       https://doi.org/10.1016/S0167-2738(02)00484-8\n\n    .. _Swift et al. Nature Comp. Sci. (2021):\n       https://doi.org/10.1038/s43588-021-00041-y\n\n    \"\"\"\n\n    def __init__(self,\n                 label: str,\n                 x: float,\n                 defect_species: List[DefectSpecies],\n                 defect_energies: List[float],\n                 scaling: Optional[np.ndarray] = None,\n                 valence: float = 0.0,\n                 saturation_parameter: float = 1.0) -> None:\n        \"\"\"Initialise a Site object.\n\n        Args:\n            label (str): Reference label for this site.\n            x (float): x coordinate of this site.\n            defect_species (list(DefectSpecies)): List of `DefectSpecies` objects (one for each defect species that can occupy this site).\n            defect_energies (list(float)): List of defect segregation energies for each defect species at this site.\n            scaling (optional, list(float): Optional list of scaling factors for the net charge at this site. Default scaling for each defect species is 1.0.\n            valence (optional, float): Optional formal valence for this site in the absence of any defects. Default is 0.0.\n            saturation_parameter (optional, float): Optional saturation parameter as described in\n                Hendricks et al. Sol. Stat. Ionics (2002) [#HendricksEtAl_SolStatIonics2002]_\n                and Swift et al. Nature Comp. Sci. (2021). [#SwiftEtAl_NatureCompSci2021]_.\n                A saturation parameter < 1.0 introduces some proportion of excluded sites that are\n                unavailable for occupation by any explicit defects. Default is 1.0.\n\n        Raises:\n            ValueError if the number of DefectSpecies != the number of defect segregation energies != the number of scaling factors (if passed).\n\n        .. [HendricksEtAl_SolStatIonics2002]:\n           https://doi.org/10.1016/S0167-2738(02)00484-8\n\n        .. [SwiftEtAl_NatureCompSci2021]:\n           https://doi.org/10.1038/s43588-021-00041-y\n\n        \"\"\"\n        if len(defect_species) != len(defect_energies):\n            raise ValueError(\"len(defect_species) must be equal to len(defect_energies)\")\n        if scaling:\n            if len(defect_species) != len(scaling):\n                raise ValueError(\"len(defect_species) must be equal to len(scaling)\")\n        self.label = label\n        self.x = x\n        self.defect_energies = defect_energies\n        self.defect_species = defect_species\n        self.defects = [DefectAtSite(label=d.label,\n                                     valence=d.valence,\n                                     mole_fraction=d.mole_fraction,\n                                     mobility=d.mobility,\n                                     energy=e,\n                                     site=self,\n                                     fixed=d.fixed)\n            for d, e in zip(defect_species, defect_energies)]\n        if scaling:\n            self.scaling = scaling\n        else:\n            self.scaling = np.ones_like(defect_energies, dtype=float)\n        self.grid_point: Optional[GridPoint] = None\n        self.valence = valence\n        self.saturation_parameter = saturation_parameter\n        self.fixed_defects = tuple(d for d in self.defects if d.fixed)\n        self.mobile_defects = tuple(d for d in self.defects if not d.fixed)\n        self.alpha = self.saturation_parameter - sum((d.mole_fraction for d in self.fixed_defects))\n\n    def competing_defect_species(self) -> Dict[str, int]:\n        \"\"\"Returns a dictionary reporting the number of fixed and / or mobile defect species that can occupy this site.\n\n        Args:\n            None\n\n        Returns\n            Dict(str, int): Dictionary {'fixed': n_fixed, 'mobile': n_mobile}\n\n        \"\"\"\n        pass\n\n    def defect_with_label(self,\n                          label: str) -> DefectAtSite:\n        \"\"\"Select a defect at this site by the species label.\n\n        Args:\n            label (str): Label to identify defect species.\n\n        Returns:\n                DefectAtSite: The DefectAtSite that matches the label.\n\n        \"\"\"\n        if not label in (d.label for d in self.defects):\n            raise LabelError(f\"\\\"{label}\\\" does not match any of the defect species labels for this site.\")\n        else:\n            return next(d for d in self.defects if d.label == label)\n\n    def energies(self) -> List[float]:\n        \"\"\"Returns a list of the segregation energies for each defect from self.defects \"\"\"\n        return [d.energy for d in self.defects]\n\n    def average_local_energy(self,\n                             method: str = 'mean') -> Optional[np.ndarray]:\n        \"\"\"\n        Returns the average local segregation energy for each site based on a specified method.\n\n        Args:\n            method (str): The method in which the average segregation energies will be calculated.\n                          'mean' - Returns the sum of all values at that site divided by the number of values at that site.\n                          'min' - Returns the minimum segregation energy value for that site (appropriate for low temperature calculations).\n\n        Returns:\n            numpy.array: Average segregation energies on the site coordinates grid.\n\n        \"\"\"\n        if self.grid_point is not None:\n            return self.grid_point.average_site_energy(method)\n        else:\n            raise ValueError(\"TODO\")\n\n    def probabilities(self,\n                      phi: float,\n                      temp: float) -> Dict[str, float]:\n        \"\"\"Calculates the probabilities of this site being occupied by each defect species.\n\n        Args:\n            phi (float): Electrostatic potential at this site in Volts.\n            temp (float): Temperature in Kelvin.\n\n        Returns:\n            dict(str, float): Probabilities of site occupation for each defect species.\n\n        \"\"\"\n        probabilities_dict = {}\n        boltzmann_factors = {d.label: d.boltzmann_factor(phi, temp) for d in self.mobile_defects}\n        denominator = (self.alpha +\n                       sum([d.mole_fraction * (boltzmann_factors[d.label] - 1.0)\n                            for d in self.mobile_defects]))\n        for defect in self.defects:\n            if defect.fixed:\n                probabilities_dict[defect.label] = defect.mole_fraction\n            else:\n                numerator = self.alpha * defect.mole_fraction * boltzmann_factors[defect.label]\n                probabilities_dict[defect.label] = numerator / denominator\n        return probabilities_dict\n\n    def probabilities_as_list(self,\n                              phi: float,\n                              temp: float) -> List[float]:\n        \"\"\"Calculates the probabilities of this site being occupied by each defect species.\n\n        Legacy interface that returns a list of site-occupation probabilities\n        in the same order as `Site.defects`.\n\n            Args:\n            phi (float): Electrostatic potential at this site in Volts.\n            temp (float): Temperature in Kelvin.\n\n        Returns:\n            list(float): Probabilities of site occupation for each defect species.\n\n        \"\"\"\n        warnings.warn(\"Site.probabilities_as_list() is deprecated and targeted for removal. Please use Site.probabilities() instead.\", DeprecationWarning)\n        probabilities_dict = self.probabilities(phi=phi, temp=temp)\n        return [probabilities_dict[d.label] for d in self.defects]\n\n    def defect_valences(self) -> np.ndarray:\n        \"\"\"Returns an array of valences for each defect in `self.defects`\"\"\"\n        return np.array([d.valence for d in self.defects])\n\n    def charge(self,\n               phi: float,\n               temp: float) -> float:\n        \"\"\"\n        Charge at this site (in Coulombs).\n\n        Args:\n            phi (float):  Electrostatic potential at this site in Volts.\n            temp (float): Temperature in Kelvin.\n\n        Returns:\n            float: The charge at this site.\n\n        \"\"\"\n        defect_probabilities = self.probabilities(phi=phi, temp=temp)\n        charge = sum([defect_probabilities[d.label] * d.valence\n                      for d in self.defects]) * self.scaling\n        charge += self.valence\n        charge *= fundamental_charge\n        return float(charge)\n", "meta": {"hexsha": "a3ba510e2cd5edbf4435672386d53233b40bdc41", "size": 10185, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscses/site.py", "max_stars_repo_name": "j-m-dean/pyscses", "max_stars_repo_head_hexsha": "6c2875cb87a8f91ae7aed382922c34b0e611ba85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyscses/site.py", "max_issues_repo_name": "j-m-dean/pyscses", "max_issues_repo_head_hexsha": "6c2875cb87a8f91ae7aed382922c34b0e611ba85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscses/site.py", "max_forks_repo_name": "j-m-dean/pyscses", "max_forks_repo_head_hexsha": "6c2875cb87a8f91ae7aed382922c34b0e611ba85", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.2666666667, "max_line_length": 157, "alphanum_fraction": 0.6221894944, "include": true, "reason": "import numpy", "num_tokens": 2172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.27512971193602087, "lm_q1q2_score": 0.1609787080283811}}
{"text": "\"\"\"FDTD Postprocessing.\n\n\"\"\"\nfrom __future__ import print_function\nfrom builtins import str\nfrom builtins import range\nfrom builtins import object\n\nimport os\nimport numpy\nimport EMpy.utils\nimport pylab\n\n__author__ = \"Lorenzo Bolla\"\n\n\nclass Input(object):\n    \"\"\"Data structure to handle input files.\"\"\"\n\n    def __init__(self, filename):\n        \"\"\"Set the input filename.\"\"\"\n        self.filename = filename\n\n    def __str__(self):\n        \"\"\"Return a representation of the input file.\"\"\"\n\n        dftmon_str = \"%g ! #timemonitors \\n\" % len(self.dftmonitors)\n        if len(self.dftmonitors) > 0:\n            dftmon_str += \"\".join(\n                [\n                    \"%g %g %g %g %g %g\\n%g %g\\n\"\n                    % (\n                        dm[0][0],\n                        dm[0][1],\n                        dm[0][2],\n                        dm[0][3],\n                        dm[0][4],\n                        dm[0][5],\n                        dm[1][0],\n                        dm[1][1],\n                    )\n                    for dm in self.dftmonitors\n                ]\n            )\n\n        timemon_str = \"%g ! #timemonitors \\n\" % len(self.dftmonitors)\n        if len(timemon_str) > 0:\n            timemon_str += \"%g %g \\n %s\" % (\n                self.timemonitors_time_interval[0],\n                self.timemonitors_time_interval[1],\n                \"\".join(\n                    [\n                        \"%g %g %g ! time_monitor #%d\\n\" % (s[0], s[1], s[2], iss)\n                        for iss, s in enumerate(self.timemonitors)\n                    ]\n                ),\n            )\n\n        return (\n            \"%g %g %g %g ! dx dy dz cfl \\n\"\n            \"%g %g %g %g %g %g %s %g %g ! xmax ymax zmax pmlx pmly pmlz pmltype pmlsmooth pmlref \\n\"\n            \"%g %g %g %g ! xmax ymax zmax pmlx pmly pmlz \\n\"\n            \"%g ! output3deps? \\n\"\n            \"%g ! number diel slices \\n\"\n            \"%s \\n\"\n            \"%g ! number field slices \\n\"\n            \"%s \\n\"\n            \"%g %g %g ! #dielobjs, index of bg, conductivity of bg \\n\"\n            \"%s\"\n            \"%g ! smoothing method \\n\"\n            \"%g ! #sources \\n\"\n            \"%s\"\n            \"%g %g %g ! lambdamin, lambdamax, dlambda \\n\"\n            \"%s\"\n            \"%s\"\n            % (\n                self.dx,\n                self.dy,\n                self.dz,\n                self.cfl,\n                self.xmax,\n                self.ymax,\n                self.zmax,\n                self.pmlx,\n                self.pmly,\n                self.pmlz,\n                self.pmltype,\n                self.pmlsmooth,\n                self.pmlref,\n                self.start,\n                self.end,\n                self.slides,\n                self.snapshot,\n                self.output3deps,\n                len(self.dielslices),\n                \"\\n\".join(\n                    [\n                        \"%g %g %g ! dielslice #%d\" % (d[0], d[1], d[2], dd)\n                        for (dd, d) in enumerate(self.dielslices)\n                    ]\n                ),\n                len(self.fieldslices),\n                \"\\n\".join(\n                    [\n                        \"%g %g %g ! fieldslice #%d\" % (f[0], f[1], f[2], ff)\n                        for (ff, f) in enumerate(self.fieldslices)\n                    ]\n                ),\n                len(self.dielobjs),\n                self.bgrix,\n                self.bgsigma,\n                \"\".join([\"%s %s\\n\" % obj for obj in self.dielobjs]),\n                self.smoothing_method,\n                len(self.sources),\n                \"\".join([\"%s\\n%s\\n%s\\n%s\\n\" % src for src in self.sources]),\n                self.lambdamin,\n                self.lambdamax,\n                self.dlambda,\n                dftmon_str,\n                timemon_str,\n            )\n        )\n\n    def tofile(self, filename=None):\n        \"\"\"Save the input data to the input file.\"\"\"\n        if filename is None:\n            filename = self.filename\n        f = open(filename, \"w\")\n        f.write(self.__str__())\n        f.close()\n\n\nclass Param(object):\n    \"\"\"Data structure to handle the param file.\"\"\"\n\n    def __str__(self):\n        \"\"\"Return a representation of the input file.\"\"\"\n        return (\n            \"%g\\n\"\n            \"%g\\n\"\n            \"%g\\n\"\n            \"%g\\n\"\n            \"%g\\n\"\n            \"%g\\n\"\n            \"%g\\n\"\n            \"%g\\n\"\n            \"%g\\n\"\n            \"%g\\n\"\n            \"%g\\n\"\n            \"%g\\n\"\n            \"%g\\n\"\n            \"%g\\n\"\n            \"%s\"\n            % (\n                self.dx,\n                self.dy,\n                self.dz,\n                self.dt,\n                self.mx,\n                self.my,\n                self.mz,\n                self.pmlx,\n                self.pmly,\n                self.pmlz,\n                self.nflux,\n                self.ntime,\n                self.step1,\n                self.step2,\n                \"\\n\".join(\n                    [\n                        \"%d\\n%d\\n%d\\n%d\\n%d\\n%d\"\n                        % (\n                            dm[\"direction\"],\n                            dm[\"nfreq\"],\n                            dm[\"flxlim\"][0],\n                            dm[\"flxlim\"][1],\n                            dm[\"flxlim\"][2],\n                            dm[\"flxlim\"][3],\n                        )\n                        for dm in self.dftmonitors\n                    ]\n                ),\n            )\n        )\n\n\nclass Sensor(object):\n    \"\"\"Data structure to handle the FFT sensor's data.\"\"\"\n\n    def plot(self, n):\n        \"\"\"Plot the sensor's fields.\"\"\"\n        pylab.clf()\n        pylab.hot()\n        pylab.subplot(2, 2, 1)\n        pylab.contour(numpy.abs(self.E1[:, :, n].T), 16)\n        pylab.axis(\"image\")\n        pylab.title(\"E1\")\n        pylab.subplot(2, 2, 2)\n        pylab.contour(numpy.abs(self.H1[:, :, n].T), 16)\n        pylab.axis(\"image\")\n        pylab.title(\"H1\")\n        pylab.subplot(2, 2, 3)\n        pylab.contour(numpy.abs(self.E2[:, :, n].T), 16)\n        pylab.axis(\"image\")\n        pylab.title(\"E2\")\n        pylab.subplot(2, 2, 4)\n        pylab.contour(numpy.abs(self.H2[:, :, n].T), 16)\n        pylab.axis(\"image\")\n        pylab.title(\"H2\")\n        pylab.show()\n\n    def __str__(self):\n        \"\"\"Return a representation of the sensor.\"\"\"\n        return \"E1\\n%s\\nH1\\n%s\\nE2\\n%s\\nH2\\n%s\\n\" % (self.E1, self.H1, self.E2, self.H2)\n\n\nclass TimeSensor(object):\n    \"\"\"Data structure to handle the time sensor's data.\"\"\"\n\n    def plot_Ex(self, logplot=False):\n        self.__plot_field(self.Ex, logplot)\n\n    def plot_Ey(self, logplot=False):\n        self.__plot_field(self.Ey, logplot)\n\n    def plot_Ez(self, logplot=False):\n        self.__plot_field(self.Ez, logplot)\n\n    def plot_Hx(self, logplot=False):\n        self.__plot_field(self.Hx, logplot)\n\n    def plot_Hy(self, logplot=False):\n        self.__plot_field(self.Hy, logplot)\n\n    def plot_Hz(self, logplot=False):\n        self.__plot_field(self.Hz, logplot)\n\n    def __plot_field(self, field, logplot=False):\n        if logplot:\n            data = 20 * numpy.log10(1e-20 + numpy.abs(field))\n            pylab.plot(self.t, data)\n        else:\n            data = field\n            pylab.plot(self.t, data)\n        pylab.show()\n\n\nclass FDTD(object):\n    \"\"\"FDTD.\n    Data structure to handle an FDTD simulation. It manages an input file, a param file and the sensors' output.\n    It can run a simulation via a system call.\n    \"\"\"\n\n    def __init__(self):\n        self.input = None\n        self.param = None\n        self.sensors = None\n\n    def fetch_data(\n        self,\n        remote_dir_=\"./\",\n        input_file=\"inp.txt\",\n        param_file=\"param\",\n        directory_=\"./\",\n    ):\n        remote_dir = fixdir(remote_dir_)\n        directory = fixdir(directory_)\n        # input file\n        os.system(\n            \"scp -C bollalo001@pico:\" + remote_dir + \"/\" + input_file + \" \" + directory\n        )\n        # param file\n        os.system(\n            \"scp -C bollalo001@pico:\" + remote_dir + \"/\" + param_file + \" \" + directory\n        )\n        # fieldslices, flux and time sensors\n        os.system(\n            \"scp -C bollalo001@pico:\" + remote_dir + \"/[EHeh]*_*\" + \" \" + directory\n        )\n        # dielslices\n        os.system(\"scp -C bollalo001@pico:\" + remote_dir + \"/diel*\" + \" \" + directory)\n\n    def put_data(self, remote_dir_=\"./\", input_file=\"inp.txt\", directory_=\"./\"):\n        remote_dir = fixdir(remote_dir_)\n        directory = fixdir(directory_)\n        # input file\n        os.system(\"scp -C\" + directory + input_file + \" bollalo001@pico:\" + remote_dir)\n        # .dat modesolver's files\n        os.system(\"scp -C\" + directory + \"*.dat bollalo001@pico:\" + remote_dir)\n\n    def load(\n        self, directory_=\"./\", input_file=\"inp.txt\", param_file=\"param\", remote_dir_=\"\"\n    ):\n        \"\"\"Load input, param and sensors.\"\"\"\n        remote_dir = fixdir(remote_dir_)\n        directory = fixdir(directory_)\n        if remote_dir != \"\":\n            self.fetch_data(remote_dir, input_file, param_file, directory)\n        self.load_input_file(directory, input_file)\n        self.load_param(directory, param_file)\n        self.load_sensors(directory)\n        self.load_time_sensors(directory)\n\n    def load_input_file(self, directory_=\"./\", filename=\"inp.txt\"):\n        \"\"\"Load input file.\"\"\"\n        directory = fixdir(directory_)\n        try:\n            f = open(directory + filename)\n        except Exception:\n            print(\"ERROR: input file\")\n            return\n        inp = Input(filename)\n\n        (inp.dx, inp.dy, inp.dz, inp.cfl) = numpy.fromstring(\n            strip_comment(f.readline()), sep=\" \"\n        )\n        tmp = strip_comment(f.readline())\n        tmp_idx = tmp.find(\"P\")\n        if tmp_idx > 0:\n            inp.pmltype = \"P\"\n        else:\n            tmp_idx = tmp.find(\"G\")\n            if tmp_idx > 0:\n                inp.pmltype = \"G\"\n            else:\n                raise ValueError(\"wrong pmltype\")\n        (inp.xmax, inp.ymax, inp.zmax, inp.pmlx, inp.pmly, inp.pmlz) = numpy.fromstring(\n            tmp[:tmp_idx], sep=\" \"\n        )\n        (inp.pmlsmooth, inp.pmlref) = numpy.fromstring(tmp[tmp_idx + 1 :], sep=\" \")\n        (inp.start, inp.end, inp.slides, inp.snapshot) = numpy.fromstring(\n            strip_comment(f.readline()), sep=\" \"\n        )\n        inp.output3deps = numpy.fromstring(strip_comment(f.readline()), sep=\" \")\n\n        # dielslices\n        ndielslices = numpy.fromstring(strip_comment(f.readline()), sep=\" \")\n        inp.dielslices = []\n        for i in range(ndielslices):\n            inp.dielslices.append(\n                numpy.fromstring(strip_comment(f.readline()), sep=\" \")\n            )\n\n        # fieldslices\n        nfieldslices = numpy.fromstring(strip_comment(f.readline()), sep=\" \")\n        inp.fieldslices = []\n        for i in range(nfieldslices):\n            inp.fieldslices.append(\n                numpy.fromstring(strip_comment(f.readline()), sep=\" \")\n            )\n\n        # dielobjs\n        (ndielobjs, inp.bgrix, inp.bgsigma) = numpy.fromstring(\n            strip_comment(f.readline()), sep=\" \"\n        )\n        inp.dielobjs = []\n        for i in range(int(ndielobjs)):\n            inp.dielobjs.append(\n                (strip_comment(f.readline()), strip_comment(f.readline()))\n            )\n        inp.smoothing_method = numpy.fromstring(strip_comment(f.readline()), sep=\" \")\n\n        # sources\n        nsources = numpy.fromstring(strip_comment(f.readline()), dtype=int, sep=\" \")\n        inp.sources = []\n        #        (inp.time_dependence, inp.wls, inp.pwidth, inp.shift) = numpy.fromstring(strip_comment(f.readline()), sep = ' ')\n        for i in range(nsources):\n            inp.sources.append(\n                (\n                    strip_comment(f.readline()),\n                    strip_comment(f.readline()),\n                    strip_comment(f.readline()),\n                    strip_comment(f.readline()),\n                )\n            )\n\n        # dft monitors\n        (inp.lambdamin, inp.lambdamax, inp.dlambda) = numpy.fromstring(\n            strip_comment(f.readline()), sep=\" \"\n        )\n        ndftmonitors = numpy.fromstring(strip_comment(f.readline()), dtype=int, sep=\" \")\n        inp.dftmonitors = []\n        for i in range(ndftmonitors):\n            inp.dftmonitors.append(\n                (\n                    numpy.fromstring(strip_comment(f.readline()), sep=\" \"),\n                    numpy.fromstring(strip_comment(f.readline()), sep=\" \"),\n                )\n            )\n\n        # time monitors\n        ntimemonitors = numpy.fromstring(strip_comment(f.readline()), sep=\" \")\n        inp.timemonitors_time_interval = numpy.fromstring(\n            strip_comment(f.readline()), sep=\" \"\n        )\n        inp.timemonitors = []\n        for i in range(ntimemonitors):\n            inp.timemonitors.append(\n                numpy.fromstring(strip_comment(f.readline()), sep=\" \")\n            )\n\n        f.close()\n        self.input = inp\n\n    def load_param(self, directory_=\"./\", filename=\"param\"):\n        \"\"\"Load param file.\"\"\"\n        directory = fixdir(directory_)\n        param = Param()\n        try:\n            data = numpy.fromfile(directory + filename, sep=\" \")\n        except Exception:\n            print(\"ERROR: param file\")\n            return\n        param.dx, param.dy, param.dz, param.dt = data[0:4]\n        (\n            param.mx,\n            param.my,\n            param.mz,\n            param.pmlx,\n            param.pmly,\n            param.pmlz,\n            param.nflux,\n            param.ntime,\n            param.step1,\n            param.step2,\n        ) = data[4:14].astype(numpy.int32)\n        param.dftmonitors = []\n        for iflux in range(int(param.nflux)):\n            direction, nfreq = data[14 + iflux * 6 : 16 + iflux * 6]\n            flxlim = data[16 + iflux * 6 : 20 + iflux * 6]\n            param.dftmonitors.append(\n                {\"direction\": int(direction), \"nfreq\": int(nfreq), \"flxlim\": flxlim}\n            )\n        self.param = param\n\n    def load_time_sensors(self, directory_=\"./\"):\n        \"\"\"Load time sensors.\"\"\"\n        directory = fixdir(directory_)\n        time_sensors = []\n        if self.param is None:\n            self.load_param(directory)\n        for itime in range(self.param.ntime):\n            tmp = TimeSensor()\n            tmp.Ex = load_fortran_unformatted(directory + \"Ex_time_%02d\" % (itime + 1))\n            tmp.Ey = load_fortran_unformatted(directory + \"Ey_time_%02d\" % (itime + 1))\n            tmp.Ez = load_fortran_unformatted(directory + \"Ez_time_%02d\" % (itime + 1))\n            tmp.Hx = load_fortran_unformatted(directory + \"Hx_time_%02d\" % (itime + 1))\n            tmp.Hy = load_fortran_unformatted(directory + \"Hy_time_%02d\" % (itime + 1))\n            tmp.Hz = load_fortran_unformatted(directory + \"Hz_time_%02d\" % (itime + 1))\n            tmp.t = self.param.dt * numpy.arange(len(tmp.Ex))\n            time_sensors.append(tmp)\n\n        self.time_sensors = time_sensors\n\n    def load_sensors(self, directory_=\"./\"):\n        \"\"\"Load sensors.\"\"\"\n        directory = fixdir(directory_)\n        sensors = []\n        if self.param is None:\n            self.load_param(directory)\n        for iflux in range(self.param.nflux):\n            tmp = Sensor()\n            dm = self.param.dftmonitors[iflux]\n            tmp.E1 = load_fortran_unformatted(directory + \"E1_%02d\" % (iflux + 1))\n            tmp.H1 = load_fortran_unformatted(directory + \"H1_%02d\" % (iflux + 1))\n            tmp.E2 = load_fortran_unformatted(directory + \"E2_%02d\" % (iflux + 1))\n            tmp.H2 = load_fortran_unformatted(directory + \"H2_%02d\" % (iflux + 1))\n            # [tmp.E1, tmp.H1, tmp.E2, tmp.H2] = map(lambda x: x[0::2] + 1j * x[1::2], [tmp.E1, tmp.H1, tmp.E2, tmp.H2])\n            # more memory efficient!\n            tmp.E1 = tmp.E1[0::2] + 1j * tmp.E1[1::2]\n            tmp.H1 = tmp.H1[0::2] + 1j * tmp.H1[1::2]\n            tmp.E2 = tmp.E2[0::2] + 1j * tmp.E2[1::2]\n            tmp.H2 = tmp.H2[0::2] + 1j * tmp.H2[1::2]\n\n            n1 = dm[\"flxlim\"][1] - dm[\"flxlim\"][0] + 1\n            n2 = dm[\"flxlim\"][3] - dm[\"flxlim\"][2] + 1\n            tmp.E1 = tmp.E1.reshape((n1, n2 + 1, dm[\"nfreq\"]), order=\"F\")\n            tmp.H1 = tmp.H1.reshape((n1, n2 + 1, dm[\"nfreq\"]), order=\"F\")\n            tmp.E2 = tmp.E2.reshape((n1 + 1, n2, dm[\"nfreq\"]), order=\"F\")\n            tmp.H2 = tmp.H2.reshape((n1 + 1, n2, dm[\"nfreq\"]), order=\"F\")\n            if dm[\"direction\"] == 1:\n                # sensors in the x-direction\n                tmp.dx1 = self.param.dy\n                tmp.dx2 = self.param.dz\n            elif dm[\"direction\"] == 2:\n                # sensors in the y-direction\n                tmp.dx1 = self.param.dx\n                tmp.dx2 = self.param.dz\n            elif dm[\"direction\"] == 3:\n                # sensors in the z-direction\n                tmp.dx1 = self.param.dx\n                tmp.dx2 = self.param.dy\n            else:\n                raise ValueError(\"wrong direction\")\n\n            sensors.append(tmp)\n\n        self.sensors = sensors\n\n    def viz2D(self, filename, directory_=\"./\", const_dir=\"z\", logplot=False):\n        \"\"\"Visualize a slice.\"\"\"\n        directory = fixdir(directory_)\n        data = load_fortran_unformatted(directory + filename)\n        if self.param is None:\n            self.load_param(directory)\n        x = numpy.linspace(\n            self.param.dx / 2.0,\n            self.param.dx * self.param.mx - self.param.dx / 2.0,\n            self.param.mx,\n        )\n        y = numpy.linspace(\n            self.param.dy / 2.0,\n            self.param.dy * self.param.my - self.param.dy / 2.0,\n            self.param.my,\n        )\n        z = numpy.linspace(\n            self.param.dz / 2.0,\n            self.param.dz * self.param.mz - self.param.dz / 2.0,\n            self.param.mz,\n        )\n        if const_dir == \"x\":\n            n1 = self.param.my\n            n2 = self.param.mz\n            x1 = y\n            x2 = z\n            x1label = \"y\"\n            x2label = \"z\"\n        elif const_dir == \"y\":\n            n1 = self.param.mx\n            n2 = self.param.mz\n            x1 = x\n            x2 = z\n            x1label = \"x\"\n            x2label = \"z\"\n        else:\n            n1 = self.param.mx\n            n2 = self.param.my\n            x1 = x\n            x2 = y\n            x1label = \"x\"\n            x2label = \"y\"\n        data = data.reshape((n2, n1))\n        pylab.clf()\n        if logplot:\n            data = 20 * numpy.log10(numpy.abs(data).clip(1e-30, 1e30))\n            pylab.jet()\n        else:\n            pylab.hot()\n        pylab.contour(x1, x2, data, 64)\n        pylab.colorbar()\n        pylab.axis(\"image\")\n        pylab.xlabel(x1label + \" /um\")\n        pylab.ylabel(x2label + \" /um\")\n        pylab.show()\n\n    def memory(self):\n        \"\"\"Estimate the memory occupation.\"\"\"\n        # size_of_char = 1\n        # size_of_int = 4\n        size_of_real = 4\n        # size_of_complex = 2 * size_of_real\n        # size_of_dielobj = size_of_int + 31 * size_of_real + 2 * 16 * size_of_char\n        # size_of_source = 9 * size_of_int + 5 * size_of_real + 6 * 16 * size_of_char\n        # size_of_monitor = (6 + 2) * 6 * size_of_int\n\n        Gb = 1024 ** 3\n        max_available_RAM = 32 * Gb\n\n        dynamic_alloc_memory = 0\n\n        # epsx, epsy, epsz\n        dynamic_alloc_memory = (\n            dynamic_alloc_memory\n            + 3\n            * (self.param.mx + 2 * self.input.pmlx)\n            * (self.param.my + 2 * self.input.pmly)\n            * (self.param.mz + 2 * self.input.pmlz)\n            * size_of_real\n        )\n        # sigma\n        dynamic_alloc_memory = (\n            dynamic_alloc_memory\n            + 2\n            * (self.param.mx + 2 * self.input.pmlx)\n            * (self.param.my + 2 * self.input.pmly)\n            * (self.param.mz + 2 * self.input.pmlz)\n            * size_of_real\n        )\n        # cex, cmx\n        dynamic_alloc_memory = (\n            dynamic_alloc_memory\n            + 2 * 2 * (self.param.mx + 2 * self.input.pmlx) * size_of_real\n        )\n        # cey, cmy\n        dynamic_alloc_memory = (\n            dynamic_alloc_memory\n            + 2 * 2 * (self.param.my + 2 * self.input.pmly) * size_of_real\n        )\n        # cez, cmz\n        dynamic_alloc_memory = (\n            dynamic_alloc_memory\n            + 2 * 2 * (self.param.mz + 2 * self.input.pmlz) * size_of_real\n        )\n\n        # exy, exz, eyx, eyz, ...\n        dynamic_alloc_memory = (\n            dynamic_alloc_memory\n            + 12\n            * (self.param.mx + 2 * self.input.pmlx)\n            * (self.param.my + 2 * self.input.pmly)\n            * (self.param.mz + 2 * self.input.pmlz)\n            * size_of_real\n        )\n\n        print(\n            \"Alloc mem = %g Gb, [%d%%]\"\n            % (\n                1.0 * dynamic_alloc_memory / Gb,\n                int(1.0 * dynamic_alloc_memory / max_available_RAM * 100),\n            )\n        )\n\n    def run(\n        self,\n        directory_=\"./\",\n        exe_file=\"/xlv1/labsoi_devices/devices/f3d\",\n        output_file=\"output\",\n        ncpu=12,\n        bg=False,\n        remote=True,\n    ):\n        \"\"\"Run the simulation, possibly in remote.\"\"\"\n        directory = fixdir(directory_)\n        #        os.environ['OMP_NUM_THREAD'] = str(ncpu)\n        #        cmd = 'dplace -x6 ' + exe_file + ' > ' + output_file\n        cmd = (\n            \"cd\"\n            + directory\n            + \"; setenv OMP_NUM_THREAD\"\n            + str(ncpu)\n            + \"dplace -x6 \"\n            + exe_file\n            + \" > \"\n            + output_file\n        )\n        if bg:\n            cmd += \"&\"\n        if remote:\n            cmd = 'ssh pico \"' + cmd + '\"'\n        os.system(cmd)\n\n    def __str__(self):\n        \"\"\"Return a representation of the FDTD data structure.\"\"\"\n        return \"INPUT\\n%s\\nPARAM\\n%s\\nSENSORS\\n%s\\n\" % (\n            self.input,\n            self.param,\n            self.sensors,\n        )\n\n\ndef load_fortran_unformatted(filename):\n    \"\"\"Load data from an unformatted fortran binary file.\"\"\"\n    try:\n        f = open(filename, \"rb\")\n    except Exception:\n        print(\"ERROR\")\n        return\n    nbytes = numpy.fromfile(f, dtype=numpy.int32, count=1)\n    n = nbytes / numpy.float32().nbytes\n    data = numpy.fromfile(f, dtype=numpy.float32, count=n)\n    f.close()\n    return data\n\n\ndef strip_comment(line):\n    \"\"\"Get rid of fortran comments.\"\"\"\n    idx = line.find(\"!\")\n    if idx != -1:\n        return line[:idx].strip()\n    return line\n\n\ndef fixdir(str, sep=\"/\"):\n    tmp = str\n    if len(tmp) > 0:\n        if tmp[-1] != sep:\n            tmp += sep\n    return tmp\n\n\n# def overlap_f(simul, solver, nwl):\n#     vu = numpy.zeros((len(simul.sensors), len(solver.modes)), dtype=complex)\n#     ju = numpy.zeros((len(simul.sensors), len(solver.modes)), dtype=complex)\n#     for isens, sens in enumerate(simul.sensors):\n#         for imode, mode in enumerate(solver.modes):\n#             Ex, Ey, Ez, Hx, Hy, Hz = mode.get_fields_for_FDTD()\n#             vu[isens, imode] = 0.5 * (\n#                         numpy.trapz(numpy.trapz(sens.E1[:,1:-1,nwl] * Hy, dx=sens.dx2*1e-6), dx=sens.dx1*1e-6) -\n#                         numpy.trapz(numpy.trapz(sens.E2[1:-1,:,nwl] * Hx, dx=sens.dx2*1e-6), dx=sens.dx1*1e-6))\n#             ju[isens, imode] = 0.5 * (\n#                         numpy.trapz(numpy.trapz(sens.H2[1:-1,:,nwl] * Ey, dx=sens.dx2*1e-6), dx=sens.dx1*1e-6) -\n#                         numpy.trapz(numpy.trapz(sens.H1[:,1:-1,nwl] * Ex, dx=sens.dx2*1e-6), dx=sens.dx1*1e-6))\n#     A = (vu + ju) / 2.\n#     B = (vu - ju) / 2.\n#     Pm = numpy.abs(A)**2 - numpy.abs(B)**2\n#     P = Pm.sum(axis=1)\n#     return (vu, ju, A, B, Pm, P)\n\n\ndef overlap_f(sensors, solver, nwl):\n    vu = numpy.zeros((len(sensors), len(solver.modes)), dtype=complex)\n    ju = numpy.zeros((len(sensors), len(solver.modes)), dtype=complex)\n    for isens, sens in enumerate(sensors):\n        x = sens.dx1 * numpy.arange(sens.E2.shape[0])\n        y = sens.dx2 * numpy.arange(sens.E1.shape[1])\n        for imode, mode in enumerate(solver.modes):\n            # resample the mode to the sensor's grid\n            Ex, Ey, Ez, Hx, Hy, Hz = mode.get_fields_for_FDTD(x, y)\n            #            vu[isens, imode] = 0.5 * (\n            #                        numpy.trapz(numpy.trapz(sens.E1[:,1:-1,nwl] * Hy, dx=sens.dx2*1e-6), dx=sens.dx1*1e-6) -\n            #                        numpy.trapz(numpy.trapz(sens.E2[1:-1,:,nwl] * Hx, dx=sens.dx2*1e-6), dx=sens.dx1*1e-6))\n            #            ju[isens, imode] = 0.5 * (\n            #                        numpy.trapz(numpy.trapz(sens.H2[1:-1,:,nwl] * Ey, dx=sens.dx2*1e-6), dx=sens.dx1*1e-6) -\n            #                        numpy.trapz(numpy.trapz(sens.H1[:,1:-1,nwl] * Ex, dx=sens.dx2*1e-6), dx=sens.dx1*1e-6))\n            vu[isens, imode] = 0.5 * (\n                EMpy.utils.trapz2(\n                    sens.E1[:, 1:-1, nwl] * Hy, dx=sens.dx1 * 1e-6, dy=sens.dx2 * 1e-6\n                )\n                - EMpy.utils.trapz2(\n                    sens.E2[1:-1, :, nwl] * Hx, dx=sens.dx1 * 1e-6, dy=sens.dx2 * 1e-6\n                )\n            )\n            ju[isens, imode] = 0.5 * (\n                EMpy.utils.trapz2(\n                    sens.H2[1:-1, :, nwl] * Ey, dx=sens.dx1 * 1e-6, dy=sens.dx1 * 1e-6\n                )\n                - EMpy.utils.trapz2(\n                    sens.H1[:, 1:-1, nwl] * Ex, dx=sens.dx1 * 1e-6, dy=sens.dx1 * 1e-6\n                )\n            )\n    A = (vu + ju) / 2.0\n    B = (vu - ju) / 2.0\n    Pm = numpy.abs(A) ** 2 - numpy.abs(B) ** 2\n    P = Pm.sum(axis=1)\n    return (vu, ju, A, B, Pm, P)\n", "meta": {"hexsha": "910a2285efdd553b5031ec550f9f115a39435e5b", "size": 25518, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/FDTD.py", "max_stars_repo_name": "EMinsight/EMpy", "max_stars_repo_head_hexsha": "d311e0f47f4ce299261fc8d03b9523a7072e88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-11T07:40:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T07:40:42.000Z", "max_issues_repo_path": "scripts/FDTD.py", "max_issues_repo_name": "FelixSCT/EMpy", "max_issues_repo_head_hexsha": "d311e0f47f4ce299261fc8d03b9523a7072e88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/FDTD.py", "max_forks_repo_name": "FelixSCT/EMpy", "max_forks_repo_head_hexsha": "d311e0f47f4ce299261fc8d03b9523a7072e88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2064343164, "max_line_length": 129, "alphanum_fraction": 0.4769182538, "include": true, "reason": "import numpy", "num_tokens": 6732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543457, "lm_q2_score": 0.3007455789412415, "lm_q1q2_score": 0.16092849116723434}}
{"text": "#Arguments in order:\n#    1.) hoomd_path (string): the path to hoomd on your machine\n#    2.) tsteps (int): the number of timesteps your simulation is running\n#    3.) dump_freq (int): the frequency of gsd dumps\n#    4.) part_frac_a (float): particle fraction of type a particles\n#    5.) pe_a (float): activity of type a particles\n#    6.) pe_b (float): activity of tyep b particles\n\nimport sys\nimport os\n\n#hoomd_path = str(sys.argv[1])\nhoomd_path = \"${hoomd_path}\"\n#tsteps = int(sys.argv[2])\nrunfor = ${runfor}\n#dump_freq = int(sys.argv[3])\ndump_freq = ${dump_freq}\n#part_frac_a = float(sys.argv[4])\npart_perc_a = ${part_frac_a}\npart_frac_a = float(part_perc_a) / 100.0\n#pe_a = float(sys.argv[5])\npe_a = ${pe_a}\n#pe_b = float(sys.argv[6])\npe_b = ${pe_b}\n#gsd_path = str(sys.argv[7])\ngsd_path = \"${gsd_path}\"\n#part_num = int(sys.argv[8])\npart_num = ${part_num}\n#phi = float(sys.argv[9])\nphi = ${phi}\nphi = float(phi)/100.0\n#seed1 = int(sys.argv[10])\n#seed2 = int(sys.argv[11])\n#seed3 = int(sys.argv[12])\n#seed4 = int(sys.argv[13])\n#seed5 = int(sys.argv[14])\nseed1 = ${seed1}                # seed for position\nseed2 = ${seed2}                # seed for bd equilibration\nseed3 = ${seed3}                # seed for initial orientations\nseed4 = ${seed4}                # seed for A activity\nseed5 = ${seed5}                # seed for B activity\n\n\n# tau = sigma^2 / diffusion coefficient\ntau = 1\n# dt = 2E-5 * tau, or, x * sigma^2 / Diffusion coeff\nmy_dt = 0.000001 * tau\n# run for 100 tau, 100 * sigma^2 / Diffusion coeff\nsim_length = runfor * tau\n# compute number of tsteps to achieve this\ntsteps = sim_length / my_dt\n#my_dt = 0.00005\n#tsteps = 50000000\n# calculate number of tsteps which are dumped\ndumps = tsteps/dump_freq\n\nsys.path.append(hoomd_path)\n\nimport hoomd\nfrom hoomd import md\nfrom hoomd import deprecated\nimport numpy as np\n\npow = np.log10(1/my_dt)\none_length = int(18*(pow-2)+29)             # gives length of array w/ values below 1 tau\ntau_to_tstep = tau / my_dt                  # this is 1 tau in terms of tsteps\nspacer = tau / (10*my_dt)                   # 1/10th of tau, the spacer\ngr_one_len = (tsteps - tau_to_tstep)/spacer # gives length of remaining array (tau > 1)\nar_tot_len = int(gr_one_len + one_length)\n\n#get tsteps for msd calculations, needs to be in tau\nmsd_dumps = np.zeros((ar_tot_len), dtype=np.float64)\njumper = 5\nvalue_to_dump = 15\ncount = 10\nfor iii in range(0,len(msd_dumps)):\n    if iii <= 10:\n        msd_dumps[iii] = iii\n    elif value_to_dump * my_dt >= 1:\n        msd_dumps[iii] = tau_to_tstep\n        tau_to_tstep += spacer\n    elif count == 95:\n        msd_dumps[iii] = value_to_dump\n        jumper *= 10\n        value_to_dump += jumper\n        count = 10\n    else:\n        msd_dumps[iii] = value_to_dump\n        value_to_dump += jumper\n        count += 5\n\nten_size = 0\nfor jjj in range(0,len(msd_dumps)):\n    if msd_dumps[jjj]*my_dt <= 10:\n        ten_size += 1\n\nmsd_ten = np.zeros((ten_size), dtype=np.float64)\nfor hhh in range(0,len(msd_ten)):\n    msd_ten[hhh] = msd_dumps[hhh]\n\nmsd_dumps += 110000\nlast_ten = 10 * tau / my_dt\nmsd_ten += tsteps - last_ten + 110000\n\n#initialize system randomly, can specify GPU execution here\n\nhoomd.context.initialize()\n# attempting to initialize a high density with min_dist > 0.75 is unsuccesful\nsystem = hoomd.deprecated.init.create_random(N = part_num,\n                                             phi_p = phi,\n                                             name = 'A',\n                                             min_dist = 0.7,\n                                             seed = seed1,\n                                             dimensions = 2)\n\nsystem.particles.types.add('B')\nsnapshot = system.take_snapshot()\n\npart_a = part_num * part_frac_a         # get the total number of A particles\npart_a = int(part_a)\npart_b = part_num - part_a              # get the total number of B particles\npart_b = int(part_b)\nmid = int(part_a)                       # starting point for assigning B particles\n\nif part_perc_a == 0:                    # take care of all b case\n    mid = 0\n    for i in range(mid,part_num):\n        system.particles[i].type = 'B'\nelif part_perc_a != 100:                # mix of each\n    for i in range(mid,part_num):\n        system.particles[i].type = 'B'\n\nall=hoomd.group.all()\ngA = hoomd.group.type(type = 'A', update=True)\ngB = hoomd.group.type(type = 'B', update=True)\nN = len(all)\nNa = len(gA)\nNb = len(gB)\n\n#define potential between pairs\nnl = hoomd.md.nlist.cell()\nlj = hoomd.md.pair.lj(r_cut=2**(1/6), nlist=nl)\nlj.set_params(mode='shift')\nlj.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0)\nlj.pair_coeff.set('A', 'B', epsilon=1.0, sigma=1.0)\nlj.pair_coeff.set('B', 'B', epsilon=1.0, sigma=1.0)\n\n#integrator type\n#hoomd.md.integrate.mode_minimize_fire(group=all, dt=0.00001, ftol=1e-2, Etol=1e-7)\n#fire = hoomd.md.integrate.mode_minimize_fire(dt=0.00001, ftol=1e-2, Etol=1e-7)\n#nve = integrate.nve(group=all)\n#hoomd.run(1000)\n#nve.disable()\n\n#run simulation with current settings here\n#hoomd.md.integrate.mode_standard(dt=0.000005)\n#hoomd.md.integrate.mode_standard(dt=0.0000005)\nhoomd.md.integrate.mode_standard(dt=my_dt)\n\n# Here's where you'll have to differentiate between particle types\n# -each group should get a different temperature\n# -Pe = 3 v_0 tau_r / sigma  OR  = v_0 sigma / D_t\n# -tau_r = 1 / D_r\n# -D_r = 3 D_t / sigma^2\n# -D_t = sigma^2 / tau_lj\n# -D_t = kbT / 3*pi*eta*sigma\n# -tau_lj = sigma^2 / epsilon * beta * D_t\n# -tau_brown = sigma^2 / D_t\nhoomd.md.integrate.brownian(group=all, kT=1.0, seed=seed2)\nhoomd.run(100000)\n\n#set the activity of each type\nnp.random.seed(seed3)                           # seed for random orientations\nangle = np.random.rand(part_num) * 2 * np.pi    # random number for particle orientation\n\nif part_perc_a != 0 and part_perc_a != 100:\n    activity_a = []\n    for i in range(0,mid):\n        x = (np.cos(angle[i])) * pe_a\n        y = (np.sin(angle[i])) * pe_a\n        z = 0\n        tuple = (x, y, z)\n        activity_a.append(tuple)\n    activity_b = []\n    for i in range(mid,part_num):\n        x = (np.cos(angle[i])) * pe_b\n        y = (np.sin(angle[i])) * pe_b\n        z = 0\n        tuple = (x, y, z)\n        activity_b.append(tuple)\n    hoomd.md.force.active(group=gA,\n                          seed=seed4,\n                          f_lst=activity_a,\n                          rotation_diff=3.0,\n                          orientation_link=False,\n                          orientation_reverse_link=True)\n    hoomd.md.force.active(group=gB,\n                          seed=seed5,\n                          f_lst=activity_b,\n                          rotation_diff=3.0,\n                          orientation_link=False,\n                          orientation_reverse_link=True)\nelse:\n    if part_perc_a == 0:\n        activity_b = []\n        for i in range(0,part_num):\n            x = (np.cos(angle[i])) * pe_b\n            y = (np.sin(angle[i])) * pe_b\n            z = 0\n            tuple = (x, y, z)\n            activity_b.append(tuple)\n        hoomd.md.force.active(group=gB,\n                              seed=seed5,\n                              f_lst=activity_b,\n                              rotation_diff=3.0,\n                              orientation_link=False,\n                              orientation_reverse_link=True)\n    else:\n        activity_a = []\n        for i in range(0,part_num):\n            x = (np.cos(angle[i])) * pe_a\n            y = (np.sin(angle[i])) * pe_a\n            z = 0\n            tuple = (x, y, z)\n            activity_a.append(tuple)\n        hoomd.md.force.active(group=gA,\n                              seed=seed4,\n                              f_lst=activity_a,\n                              rotation_diff=3.0,\n                              orientation_link=False,\n                              orientation_reverse_link=True)\n\n#write dumps\nname = \"pa\" + str(pe_a) + \"_pb\" + str(pe_b) + \"_xa\" + str(part_perc_a) + \".gsd\"\nmsd_name = \"MSD_pa\" + str(pe_a) + \"_pb\" + str(pe_b) + \"_xa\" + str(part_perc_a) + \".gsd\"\nmsd_tentau = \"MSDten_pa\" + str(pe_a) + \"_pb\" + str(pe_b) + \"_xa\" + str(part_perc_a) + \".gsd\"\nsqlite_name = \"pa\" + str(pe_a) + \"_pb\" + str(pe_b) + \"_xa\" + str(part_perc_a) + \".sqlite\"\n\n### Dump for MSD ###\n# change this to units of tau?\n#def dump_spec(timestep):\n#    \n#    if timestep in msd_dumps:\n#        hoomd.dump.gsd(filename=msd_name,\n#                       period=None,\n#                       group=all,\n#                       overwrite=False,\n#                       dynamic=['attribute', 'property', 'momentum'])\n#        os.close(2)\n#\n#    if timestep in msd_ten:\n#        hoomd.dump.gsd(filename=msd_tentau,\n#                       period=None,\n#                       group=all,\n#                       overwrite=False,\n#                       dynamic=['attribute', 'property', 'momentum'])\n#        os.close(2)\n#\n#hoomd.analyze.callback(callback = dump_spec, period = 1)\n####################\n\nhoomd.dump.gsd(name,\n               period=dump_freq,\n               group=all,\n               overwrite=True,\n               phase=-1,\n               dynamic=['attribute', 'property', 'momentum'])\n\nhoomd.dump.getar.simple(sqlite_name, dump_freq, 'a',\n                        static=['dimensions', 'viz_static'],\n                        dynamic=['viz_aniso_dynamic', 'virial', 'velocity'])\n\n# Don't have to instantiate the compute, already passed to integrator\n#hoomd.compute.thermo(group=gB)\n#hoomd.analyze.log(filename=\"pressure_outii.txt\", quantities=[\"pressure\"], period=dump_freq)\n\n#run\nhoomd.run(tsteps)\n\n#########################################################################\n########################## Begin Data Analysis ##########################\n#########################################################################\n\nsys.path.append(gsd_path)\nimport gsd\nfrom gsd import hoomd\nfrom gsd import pygsd\nimport numpy as np\n\nmyfile = \"pa\" + str(pe_a) + \"_pb\" + str(pe_b) + \"_xa\" + str(part_perc_a) + \".gsd\"\nmsdfile = \"MSD_pa\" + str(pe_a) + \"_pb\" + str(pe_b) + \"_xa\" + str(part_perc_a) + \".gsd\"\n\nf = hoomd.open(name=myfile, mode='rb')\ndumps = f.__len__()\nsize_min = 1000                                         # minimum size of cluster\n\nposition_array = np.zeros((dumps), dtype=np.ndarray)    # array of position arrays\ntype_array = np.zeros((dumps), dtype=np.ndarray)        # particle types\nbox_data = np.zeros((1), dtype=np.ndarray)              # box dimensions\ntimesteps = np.zeros((dumps), dtype=np.float64)         # timesteps\n\nwith hoomd.open(name=myfile, mode='rb') as t:           # open for reading\n    snap = t[0]                                         # snap 0th snapshot\n    box_data = snap.configuration.box                   # get box dimensions\n    for i in range(0,dumps):\n        snap = t[i]                                     # take snap of each dump\n        type_array[i] = snap.particles.typeid\n        position_array[i] = snap.particles.position     # store all particle positions\n        timesteps[i] = snap.configuration.step          # store tstep for plotting purposes\n\ntimesteps -= timesteps[0]\nmsd_time = timesteps[1:]\n\npos_A = np.zeros((dumps), dtype=np.ndarray)             # type A positions\npos_B = np.zeros((dumps), dtype=np.ndarray)             # type B positions\ntmpA = np.zeros((part_a, 3), dtype=np.float32)          # temporary storage arrays\ntmpB = np.zeros((part_b, 3), dtype=np.float32)\n\nfrom freud import parallel, box, density, cluster\nparallel.setNumThreads(1)                               # don't run multiple threads\n\nmy_density = density.LocalDensity(r_cut=2.5,\n                                  volume=0.79,\n                                  diameter=1.0)         # initiate class, use area of circle\n\nl_box = box_data[0]                                     # get box dimensions (square here)\nf_box = box.Box(Lx=l_box,\n                Ly=l_box,\n                is2D=True)                               # initialize freud box\n\nmy_clusters = cluster.Cluster(box=f_box,\n                              rcut=1.0)                 # initialize class\ncluster_props = cluster.ClusterProperties(box=f_box)\n\nnumber_clusters = np.zeros((dumps), dtype=np.ndarray)   # arrays to store things\nids = np.zeros((dumps), dtype=np.ndarray)\nsize_clusters = np.zeros((dumps), dtype=np.ndarray)\ntot_size = np.zeros((dumps), dtype=np.ndarray)          # number of particles in clusters\ntot_num = np.zeros((dumps), dtype=np.ndarray)           # total number of clusters\nMCS = np.zeros((dumps), dtype=np.ndarray)               # Mean cluster size\nGF = np.zeros((dumps), dtype=np.ndarray)                # Gas fraction\nA_ids = np.zeros((part_a), dtype=np.ndarray)            # type A ids\nB_ids = np.zeros((part_b), dtype=np.ndarray)            # type B ids\npercent_A = np.zeros((dumps), dtype=np.ndarray)         # composition A at each timestep\nlargest = np.zeros((dumps), dtype=np.ndarray)           # read out largest cluster at each tstep\n\nLIQ_A = np.zeros((dumps - 1), dtype=np.ndarray)         # arrays for MSD\nLIQ_B = np.zeros((dumps - 1), dtype=np.ndarray)\nGAS_A = np.zeros((dumps - 1), dtype=np.ndarray)\nGAS_B = np.zeros((dumps - 1), dtype=np.ndarray)\nMSD_T = np.zeros((dumps - 1), dtype=np.float64)\nMSD_TL = np.zeros((dumps - 1), dtype=np.ndarray)\nMSD_TG = np.zeros((dumps - 1), dtype=np.ndarray)\n\ndisp_x = np.zeros((part_num), dtype=np.ndarray)         # displacement vectors\ndisp_y = np.zeros((part_num), dtype=np.ndarray)\ndisp_z = np.zeros((part_num), dtype=np.ndarray)\n\n# analyze all particles\nfor j in range(0, dumps):\n    \n    l_pos = position_array[j]\n    my_clusters.computeClusters(l_pos)\n    number_clusters[j] = my_clusters.getNumClusters()   # find number of clusters\n    ids = my_clusters.getClusterIdx()                   # get cluster ids\n    cluster_props.computeProperties(l_pos, ids)\n    size_clusters[j] = cluster_props.getClusterSizes()  # get number of particles in each\n    \n    how_many = my_clusters.getNumClusters()\n    \n    #############################################################\n    ### This finds the cluster ids for type A and B particles ###\n    #############################################################\n#    A_id_count = 0\n#    B_id_count = 0\n#    for h in range(0, part_num):\n#        if type_array[j][h] == 0:\n#            A_ids[A_id_count] = ids[h]                  # store the cluster ids for A type\n#            A_id_count += 1                             # IMPROVE: sort while placing?\n#        else:\n#            B_ids[B_id_count] = ids[h]                  # store the cluster ids for B type\n#            B_id_count += 1                             # could put ids in order ...\n#\n#    clust_dat = np.zeros((how_many), dtype = np.ndarray)\n#    clust_dat_A = np.zeros((how_many), dtype = np.ndarray)\n#    clust_dat_B = np.zeros((how_many), dtype = np.ndarray)\n#    numerator_A = 0\n#    denominator_tot = 0\n\n    #######################################################################\n    ### If clusters are greater than a threshold size, find composition ###\n    #######################################################################\n    \n#    for m in range(0, how_many):\n#        clust_dat_A[m] = (A_ids == m).sum()             # sum all A type particles in a cluster\n#        clust_dat_B[m] = (B_ids == m).sum()\n#        clust_dat[m] = clust_dat_A[m] + clust_dat_B[m]  # find total number of particles in cluster\n#        if clust_dat[m] > 15:\n#            numerator_A += clust_dat_A[m]\n#            denominator_tot += clust_dat[m]\n#    # get the total percent of A particles in all clusters\n#    if denominator_tot != 0:\n#        percent_A[j] =  float(numerator_A) / float(denominator_tot)\n\n    \n    #####################################################################\n    ### Find avg cluster size, gas fraction, and largest cluster size ###\n    #####################################################################\n    l_clust = 0                                             # int size of largest cluster\n    for k in range(0, len(size_clusters[j])):\n        # the size minimum is a very important value to consider\n        if size_clusters[j][k] > size_min and size_clusters[j][k] < part_num:\n            tot_size[j] += size_clusters[j][k]\n            tot_num[j] += 1\n            if size_clusters[j][k] > l_clust:           # if larger cluster is found\n                l_clust = size_clusters[j][k]           # set l_clust to that size\n\n    largest[j] = l_clust                                # save largest cluster size for tstep\n    \n    f_largest = \"largest_pa\" + str(pe_a) + \"_pb\" + str(pe_b) + \"_xa\" + str(part_perc_a) + \".txt\"\n    if j == 0:\n        a_w = 'w'\n    else:\n        a_w = 'a'\n    f = open(f_largest, a_w)\n    f.write(str(l_clust) + '\\n')\n    f.close()\n    \n    if tot_num[j] > 0:\n        MCS[j] = float(tot_size[j]/tot_num[j])/float(part_num)\n        GF[j] = float(part_num - tot_size[j]) / float(part_num)\n    else:\n        MCS[j] = 0\n        GF[j] = 1\n\n    #########################################################\n    ### Find MSD for A, B individually, also total system ###\n    #########################################################\n\n    # ?you can enhance difference between gas and liq by setting min clust requirement\n\n    sort_id = np.sort(ids)                              # array of IDs sorted small to large\n    q_clust = np.zeros((how_many), dtype=np.ndarray)    # my binary 'is it clustered?' array\n    index = 0                                           # index of the sorted array to look at\n    for a in range(0,len(q_clust)):\n        add_clust = 0\n        while 1:\n            add_clust += 1\n            if index == part_num:                       # break if index is too large\n                break\n            if sort_id[index] != a:                     # break if ID changes\n                break\n            if add_clust == 1:                          # all particles appear once\n                q_clust[a] = 0\n            if add_clust > size_min:                    # only multiple ids appear twice\n                q_clust[a] = 1\n            index += 1                                  # increment index\n\n    lq_a_count = 0\n    lq_b_count = 0\n    gs_a_count = 0\n    gs_b_count = 0\n    if j > 0:\n        numerator_A = 0\n        denominator_tot = 0\n        for b in range(0,part_num):\n            \n            # check instantaneous disp. over last timestep\n            dx = position_array[j][b][0] - position_array[j-1][b][0]\n            dy = position_array[j][b][1] - position_array[j-1][b][1]\n            dz = position_array[j][b][2] - position_array[j-1][b][2]\n            \n            # if it is over some threshold, then it went past a boundary\n            if dx < -50:\n                dx += l_box\n            if dx > 50:\n                dx -= l_box\n            disp_x[b] += dx\n            \n            if dy < -50:\n                dy += l_box\n            if dy > 50:\n                dy -= l_box\n            disp_y[b] += dy\n            \n            if dz < -50:\n                dz += l_box\n            if dz > 50:\n                dz -= l_box\n            disp_z[b] += dz\n            \n            msd_val = np.sqrt(((disp_x[b])**2) + ((disp_y[b])**2) + ((disp_z[b])**2))\n            MSD_T[j-1] += msd_val\n            if q_clust[ids[b]] == 1:                        # check if in liquid\n                MSD_TL[j-1] += msd_val                      # add to tot. lq. msd\n                if type_array[j][b] == 0:                   # type A case\n                    LIQ_A[j-1] += msd_val\n                    lq_a_count += 1\n                else:\n                    LIQ_B[j-1] += msd_val\n                    lq_b_count += 1\n            else:                                           # else, particle is gas\n                MSD_TG[j-1] += msd_val                      # add to tot. gs. msd\n                if type_array[j][b] == 0:                   # type A case\n                    GAS_A[j-1] += msd_val\n                    gs_a_count += 1\n                else:\n                    GAS_B[j-1] += msd_val\n                    gs_b_count += 1\n    \n        # if-gating these so we don't break our program\n        if lq_a_count != 0: LIQ_A[j-1] /= lq_a_count\n        if lq_b_count != 0: LIQ_B[j-1] /= lq_b_count\n        if gs_a_count != 0: GAS_A[j-1] /= gs_a_count\n        if gs_b_count != 0: GAS_B[j-1] /= gs_b_count\n        MSD_T[j-1] /= part_num\n        if lq_a_count + lq_b_count != 0: MSD_TL[j-1] /= lq_a_count + lq_b_count\n        if gs_a_count + gs_b_count != 0: MSD_TG[j-1] /= gs_a_count + gs_b_count\n\n        numerator_A = lq_a_count\n        denominator_tot = lq_a_count + lq_b_count\n        \n        if denominator_tot != 0:\n            percent_A[j] =  float(numerator_A) / float(denominator_tot)\n\n############################\n### Density caluclations ###\n############################\n\ndef getDensityPlease(n):                                # call this function as needed\n    l_pos = position_array[n]                           # get ith position array\n    my_density.compute(f_box,\n                       l_pos,\n                       l_pos)\n    return my_density.getDensity()\n\navg_sys_density = np.zeros((1), dtype=np.ndarray)\n\ntake_last = dumps - 10\nlast = dumps - 1\nmsd_last = dumps - 2\nfor j in range(take_last, dumps):\n    avg_sys_density[0] += getDensityPlease(j)\n\navg_sys_density[0] /= (dumps - take_last)\n\n################################################################################\n###### perform the same analysis on species A and species B individually #######\n################################################################################\n\nif part_perc_a != 0 and part_perc_a != 100:\n    \n    tot_size_A = np.zeros((dumps), dtype=np.ndarray)          # number of particles in clusters\n    tot_num_A = np.zeros((dumps), dtype=np.ndarray)           # total number of clusters\n    MCS_A = np.zeros((dumps), dtype=np.ndarray)               # Mean cluster size\n    GF_A = np.zeros((dumps), dtype=np.ndarray)                # Gas fraction\n    \n    tot_size_B = np.zeros((dumps), dtype=np.ndarray)          # number of particles in clusters\n    tot_num_B = np.zeros((dumps), dtype=np.ndarray)           # total number of clusters\n    MCS_B = np.zeros((dumps), dtype=np.ndarray)               # Mean cluster size\n    GF_B = np.zeros((dumps), dtype=np.ndarray)                # Gas fraction\n    \n    for j in range(0, dumps):\n        countA = 0\n        countB = 0\n        for g in range(0, part_num):\n            if type_array[j][g] == 0:\n                tmpA[countA][0] = position_array[j][g][0]\n                tmpA[countA][1] = position_array[j][g][1]\n                tmpA[countA][2] = position_array[j][g][2]\n                countA += 1\n            else:\n                tmpB[countB][0] = position_array[j][g][0]\n                tmpB[countB][1] = position_array[j][g][1]\n                tmpB[countB][2] = position_array[j][g][2]\n                countB += 1\n    \n        pos_A[j] = tmpA\n        pos_B[j] = tmpB\n        \n        l_pos = pos_A[j]\n        my_clusters.computeClusters(l_pos)\n        number_clusters[j] = my_clusters.getNumClusters()   # find number of clusters\n        ids = my_clusters.getClusterIdx()                   # get cluster ids\n        cluster_props.computeProperties(l_pos, ids)\n        size_clusters[j] = cluster_props.getClusterSizes()  # get number of particles in each\n        \n        ####################################\n        ### GF, MCS for A-A correlations ###\n        ####################################\n        \n        for k in range(0, len(size_clusters[j])):\n            # the size minimum is a very important value to consider\n            if size_clusters[j][k] > size_min and size_clusters[j][k] < part_num:\n                tot_size_A[j] += size_clusters[j][k]\n                tot_num_A[j] += 1\n\n        if tot_num_A[j] > 0:\n            MCS_A[j] = float(tot_size_A[j]/tot_num_A[j])/float(part_a)\n            GF_A[j] = float(part_a - tot_size_A[j]) / float(part_a)\n        \n        else:\n            MCS_A[j] = 0\n            GF_A[j] = 1\n\n        l_pos = pos_B[j]\n        my_clusters.computeClusters(l_pos)\n        number_clusters[j] = my_clusters.getNumClusters()   # find number of clusters\n        ids = my_clusters.getClusterIdx()                   # get cluster ids\n        cluster_props.computeProperties(l_pos, ids)\n        size_clusters[j] = cluster_props.getClusterSizes()  # get number of particles in each\n        \n        ####################################\n        ### GF, MCS for A-A correlations ###\n        ####################################\n        \n        for k in range(0, len(size_clusters[j])):\n            # the size minimum is a very important value to consider\n            if size_clusters[j][k] > size_min and size_clusters[j][k] < part_num:\n                tot_size_B[j] += size_clusters[j][k]\n                tot_num_B[j] += 1\n\n        if tot_num_B[j] > 0:\n            MCS_B[j] = float(tot_size_B[j]/tot_num_B[j])/float(part_b)\n            GF_B[j] = float(part_b - tot_size_B[j]) / float(part_b)\n        \n        else:\n            MCS_B[j] = 0\n            GF_B[j] = 1\n\n\n\n    def getDensityA(n):                                     # call this function as needed\n        countA = 0\n        for g in range(0, part_num):\n            if type_array[n][g] == 0:\n                tmpA[countA][0] = position_array[n][g][0]\n                tmpA[countA][1] = position_array[n][g][1]\n                tmpA[countA][2] = position_array[n][g][2]\n                countA += 1\n        pos_A[n] = tmpA\n        l_pos = pos_A[n]                                    # get ith position array\n        my_density.compute(f_box,\n                           l_pos,\n                           l_pos)\n        return my_density.getDensity()\n\n    avg_dense_A = np.zeros((1), dtype=np.ndarray)\n    \n    for j in range(take_last, dumps):\n        avg_dense_A[0] += getDensityA(j)\n\n    avg_dense_A[0] /= (dumps - take_last)\n\n    def getDensityB(n):                                     # call this function as needed\n        countB = 0\n        for g in range(0, part_num):\n            if type_array[n][g] == 1:\n                tmpB[countB][0] = position_array[n][g][0]\n                tmpB[countB][1] = position_array[n][g][1]\n                tmpB[countB][2] = position_array[n][g][2]\n                countB += 1\n        pos_B[n] = tmpB\n        l_pos = pos_B[n]                                    # get ith position array\n        my_density.compute(f_box,\n                           l_pos,\n                           l_pos)\n        return my_density.getDensity()\n\n    avg_dense_B = np.zeros((1), dtype=np.ndarray)\n    \n    for j in range(take_last, dumps):\n        avg_dense_B[0] += getDensityB(j)\n    \n    avg_dense_B[0] /= (dumps - take_last)\n\n################################################################################\n#################### Plot the individual and total data ########################\n################################################################################\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(color_codes=True)\n\nplt_name  = \"pa\" + str(pe_a) + \"_pb\" + str(pe_b) + \"_xa\" + str(part_perc_a)\nplt_name1 = \"pa\" + str(pe_a) + \"_pb\" + str(pe_b) + \"_xa\" + str(part_perc_a) + \"A\"\nplt_name2 = \"pa\" + str(pe_a) + \"_pb\" + str(pe_b) + \"_xa\" + str(part_perc_a) + \"B\"\n\nif part_perc_a != 0 and part_perc_a != 100:\n    sns.kdeplot(avg_sys_density[0], shade = True, color=\"g\")\n    sns.kdeplot(avg_dense_A[0], shade = True, color=\"r\")\n    sns.kdeplot(avg_dense_B[0], shade = True, color=\"b\")\n    plt.savefig('avg_density_' + plt_name + '.png', dpi=1000)\n    plt.close()\n    \n    sns.kdeplot(getDensityPlease(last), shade = True, color=\"g\")\n    sns.kdeplot(getDensityA(last), shade = True, color=\"r\")\n    sns.kdeplot(getDensityB(last), shade = True, color=\"b\")\n    plt.savefig('final_density_' + plt_name + '.png', dpi=1000)\n    plt.close()\n    \n    plt.plot(MCS, color=\"g\")\n    plt.plot(MCS_A, color=\"r\")\n    plt.plot(MCS_B, color=\"b\")\n    #plt.ylim((0,1))\n    plt.savefig('MCS_'+ plt_name + '.png', dpi=1000)\n    plt.close()\n    \n    plt.plot(GF, color=\"g\")\n    plt.plot(GF_A, color=\"r\")\n    plt.plot(GF_B, color=\"b\")\n    plt.ylim((0,1))\n    plt.savefig('GF_'+plt_name+'.png', dpi=1000)\n    plt.close()\n    \n    plt.plot(percent_A, color=\"r\")\n    #plt.ylim((0,1))\n    plt.savefig('A_comp_'+plt_name+'.png', dpi=1000)\n    plt.close()\n    \n    plt.plot(largest, color=\"g\")\n    plt.savefig('Largest_clust_'+plt_name+'.png', dpi=1000)\n    plt.close()\n    \n    plt.plot(msd_time, GAS_A,  color=\"r\", marker='o', markersize=1, linestyle='None', label='Gas_A')\n    plt.plot(msd_time, GAS_B,  color=\"b\", marker='o', markersize=1, linestyle='None', label='Gas_B')\n    plt.xscale('log')\n    plt.yscale('log')\n    plt.xlabel('Timesteps')\n    plt.ylabel('MSD')\n    plt.legend(loc='upper left')\n    plt.savefig('MSD_GAS_AB_' + plt_name + '.png', dpi=1000)\n    plt.close()\n    \n    plt.plot(msd_time, LIQ_A,  color=\"r\", marker='o', markersize=1, linestyle='None', label='Liq_A')\n    plt.plot(msd_time, LIQ_B,  color=\"b\", marker='o', markersize=1, linestyle='None', label='Liq_B')\n    plt.xscale('log')\n    plt.yscale('log')\n    plt.xlabel('Timesteps')\n    plt.ylabel('MSD')\n    plt.legend(loc='upper left')\n    plt.savefig('MSD_LIQ_AB_' + plt_name + '.png', dpi=1000)\n    plt.close()\n    \n    plt.plot(msd_time, MSD_T,  color=\"g\", marker='o', markersize=1, linestyle='None', label='MSD')\n    plt.xscale('log')\n    plt.yscale('log')\n    plt.xlabel('Timesteps')\n    plt.ylabel('MSD')\n    plt.legend(loc='upper left')\n    plt.savefig('MSD_total_' + plt_name + '.png', dpi=1000)\n    plt.close()\n    \n    plt.plot(msd_time, MSD_TL,  color=\"b\", marker='o', markersize=1, linestyle='None', label='Liq')\n    plt.plot(msd_time, MSD_TG,  color=\"r\", marker='o', markersize=1, linestyle='None', label='Gas')\n    plt.xscale('log')\n    plt.yscale('log')\n    plt.xlabel('Timesteps')\n    plt.ylabel('MSD')\n    plt.legend(loc='upper left')\n    plt.savefig('MSD_LG_' + plt_name + '.png', dpi=1000)\n    plt.close()\n\nelse:                                                           # if monodisperse plot total values\n    sns.kdeplot(avg_sys_density[0], shade = True, color=\"g\")\n    plt.savefig('avg_density_' + plt_name + '.png', dpi=1000)\n    plt.close()\n    \n    sns.kdeplot(getDensityPlease(last), shade = True, color=\"g\")\n    plt.savefig('final_density_' + plt_name + '.png', dpi=1000)\n    plt.close()\n    \n    plt.plot(MCS, color=\"g\")\n    plt.savefig('MCS_'+ plt_name + '.png', dpi=1000)\n    plt.close()\n    \n    plt.plot(GF, color=\"g\")\n    plt.ylim((0,1))\n    plt.savefig('GF_'+plt_name+'.png', dpi=1000)\n    plt.close()\n    \n    plt.plot(largest, color=\"g\")\n    plt.savefig('Largest_clust_'+plt_name+'.png', dpi=1000)\n    plt.close()\n    \n    plt.plot(msd_time, MSD_T,  color=\"g\", marker='o', markersize=1, linestyle='None', label='MSD')\n    plt.xscale('log')\n    plt.yscale('log')\n    plt.xlabel('Timesteps')\n    plt.ylabel('MSD')\n    plt.legend(loc='upper left')\n    plt.savefig('MSD_total_' + plt_name + '.png', dpi=1000)\n    plt.close()\n    \n    plt.plot(msd_time, MSD_TL,  color=\"b\", marker='o', markersize=1, linestyle='None', label='Liq')\n    plt.plot(msd_time, MSD_TG,  color=\"r\", marker='o', markersize=1, linestyle='None', label='Gas')\n    plt.xscale('log')\n    plt.yscale('log')\n    plt.xlabel('Timesteps')\n    #plt.xlabel(r'Time ($\\tau$)')\n    plt.ylabel('MSD')\n    plt.legend(loc='upper left')\n    plt.savefig('MSD_LG_' + plt_name + '.png', dpi=1000)\n    plt.close()\n", "meta": {"hexsha": "f466756acb67965b16eadb34c2dc6d9541c5912a", "size": 31447, "ext": "py", "lang": "Python", "max_stars_repo_path": "run_specific/template_spec.py", "max_stars_repo_name": "kolbt/whingdingdilly", "max_stars_repo_head_hexsha": "4c17b594ebc583750fe7565d6414f08678ea7882", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-09-04T14:36:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T23:24:58.000Z", "max_issues_repo_path": "run_specific/template_spec.py", "max_issues_repo_name": "kolbt/whingdingdilly", "max_issues_repo_head_hexsha": "4c17b594ebc583750fe7565d6414f08678ea7882", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "run_specific/template_spec.py", "max_forks_repo_name": "kolbt/whingdingdilly", "max_forks_repo_head_hexsha": "4c17b594ebc583750fe7565d6414f08678ea7882", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9677819083, "max_line_length": 100, "alphanum_fraction": 0.5306070531, "include": true, "reason": "import numpy", "num_tokens": 8294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3007455664065234, "lm_q1q2_score": 0.1609284800005509}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n################################################################################\n#\n#   RMG - Reaction Mechanism Generator\n#\n#   Copyright (c) 2002-2009 Prof. William H. Green (whgreen@mit.edu) and the\n#   RMG Team (rmg_dev@mit.edu)\n#\n#   Permission is hereby granted, free of charge, to any person obtaining a\n#   copy of this software and associated documentation files (the \"Software\"),\n#   to deal in the Software without restriction, including without limitation\n#   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n#   and/or sell copies of the Software, and to permit persons to whom the\n#   Software is furnished to do so, subject to the following conditions:\n#\n#   The above copyright notice and this permission notice shall be included in\n#   all copies or substantial portions of the Software.\n#\n#   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n#   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n#   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n#   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n#   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n#   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n#   DEALINGS IN THE SOFTWARE.\n#\n################################################################################\n\n\"\"\"\nThis module contains the :class:`ThermoJob` class, used to compute and save the\nthermodynamics information for a single species.\n\"\"\"\n\nimport os.path\nimport math\nimport numpy.linalg\nimport logging\n\nimport rmgpy.constants as constants\nfrom rmgpy.cantherm.output import prettify\n\nfrom rmgpy.statmech.translation import Translation, IdealGasTranslation\nfrom rmgpy.statmech.rotation import Rotation, LinearRotor, NonlinearRotor, KRotor, SphericalTopRotor\nfrom rmgpy.statmech.vibration import Vibration, HarmonicOscillator\nfrom rmgpy.statmech.torsion import Torsion, HinderedRotor\nfrom rmgpy.statmech.conformer import Conformer\n\nfrom rmgpy.thermo.thermodata import ThermoData\nfrom rmgpy.thermo.nasa import NASAPolynomial, NASA\nfrom rmgpy.thermo.wilhoit import Wilhoit\n\n################################################################################\n\nclass ThermoJob:\n    \"\"\"\n    A representation of a CanTherm thermodynamics job. This job is used to\n    compute and save the thermodynamics information for a single species.\n    \"\"\"\n    \n    def __init__(self, species, thermoClass):\n        self.species = species\n        self.thermoClass = thermoClass\n    \n    def execute(self, outputFile=None, plot=False):\n        \"\"\"\n        Execute the thermodynamics job, saving the results to the\n        given `outputFile` on disk.\n        \"\"\"\n        self.generateThermo()\n        if outputFile is not None:\n            self.save(outputFile)\n            if plot:\n                self.plot(os.path.dirname(outputFile))\n    \n    def generateThermo(self):\n        \"\"\"\n        Generate the thermodynamic data for the species and fit it to the\n        desired heat capacity model (as specified in the `thermoClass` \n        attribute).\n        \"\"\"\n        if self.thermoClass.lower() not in ['wilhoit', 'nasa']:\n            raise Exception('Unknown thermodynamic model \"{0}\".'.format(self.thermoClass))\n    \n        species = self.species\n    \n        logging.info('Generating {0} thermo model for {1}...'.format(self.thermoClass, species))\n        \n        Tlist = numpy.arange(10.0, 3001.0, 10.0, numpy.float64)\n        Cplist = numpy.zeros_like(Tlist)\n        H298 = 0.0\n        S298 = 0.0\n        conformer = self.species.conformer\n        for i in range(Tlist.shape[0]):\n            Cplist[i] += conformer.getHeatCapacity(Tlist[i])\n        H298 += conformer.getEnthalpy(298.) + conformer.E0.value_si\n        S298 += conformer.getEntropy(298.)\n        \n        if not any([isinstance(mode, (LinearRotor, NonlinearRotor)) for mode in conformer.modes]):\n            # Monatomic species\n            linear = False\n            Nfreq = 0\n            Nrotors = 0\n            Cp0 = 2.5 * constants.R\n            CpInf = 2.5 * constants.R\n        else:\n            # Polyatomic species\n            linear = True if isinstance(conformer.modes[1], LinearRotor) else False\n            Nfreq = len(conformer.modes[2].frequencies.value)\n            Nrotors = len(conformer.modes[3:])\n            Cp0 = (3.5 if linear else 4.0) * constants.R\n            CpInf = Cp0 + (Nfreq + 0.5 * Nrotors) * constants.R\n    \n        wilhoit = Wilhoit()\n        if Nfreq == 0 and Nrotors == 0:\n            wilhoit.Cp0 = (Cplist[0],\"J/(mol*K)\") \n            wilhoit.CpInf = (Cplist[0],\"J/(mol*K)\")\n            wilhoit.B = (500.,\"K\") \n            wilhoit.H0 = (0.0,\"J/mol\")\n            wilhoit.S0 = (0.0,\"J/(mol*K)\") \n            wilhoit.H0 =  (H298 -wilhoit.getEnthalpy(298.15), \"J/mol\") \n            wilhoit.S0 = (S298 - wilhoit.getEntropy(298.15),\"J/(mol*K)\")\n        else:\n            wilhoit.fitToData(Tlist, Cplist, Cp0, CpInf, H298, S298, B0=500.0)\n        \n        if self.thermoClass.lower() == 'nasa':\n            species.thermo = wilhoit.toNASA(Tmin=10.0, Tmax=3000.0, Tint=500.0)\n        else:\n            species.thermo = wilhoit\n\n    def save(self, outputFile):\n        \"\"\"\n        Save the results of the thermodynamics job to the file located\n        at `path` on disk.\n        \"\"\"\n        species = self.species\n        logging.info('Saving thermo for {0}...'.format(species.label))\n        \n        f = open(outputFile, 'a')\n    \n        f.write('# Thermodynamics for {0}:\\n'.format(species.label))\n        H298 = species.getThermoData().getEnthalpy(298) / 4184.\n        S298 = species.getThermoData().getEntropy(298) / 4.184\n        f.write('#   Enthalpy of formation (298 K)   = {0:9.3f} kcal/mol\\n'.format(H298))\n        f.write('#   Entropy of formation (298 K)    = {0:9.3f} cal/(mol*K)\\n'.format(S298))\n        f.write('#    =========== =========== =========== =========== ===========\\n')\n        f.write('#    Temperature Heat cap.   Enthalpy    Entropy     Free energy\\n')\n        f.write('#    (K)         (cal/mol*K) (kcal/mol)  (cal/mol*K) (kcal/mol)\\n')\n        f.write('#    =========== =========== =========== =========== ===========\\n')\n        for T in [300,400,500,600,800,1000,1500,2000,2400]:\n            Cp = species.getThermoData().getHeatCapacity(T) / 4.184\n            H = species.getThermoData().getEnthalpy(T) / 4184.\n            S = species.getThermoData().getEntropy(T) / 4.184\n            G = species.getThermoData().getFreeEnergy(T) / 4184.\n            f.write('#    {0:11g} {1:11.3f} {2:11.3f} {3:11.3f} {4:11.3f}\\n'.format(T, Cp, H, S, G))\n        f.write('#    =========== =========== =========== =========== ===========\\n')\n        \n        string = 'thermo(label={0!r}, thermo={1!r})'.format(species.label, species.getThermoData())\n        f.write('{0}\\n\\n'.format(prettify(string)))\n        \n        f.close()\n        \n        f = open(os.path.join(os.path.dirname(outputFile), 'chem.inp'), 'a')\n        \n        thermo = species.getThermoData()\n        if isinstance(thermo, NASA):\n        \n            poly_low = thermo.polynomials[0]\n            poly_high = thermo.polynomials[1]\n        \n            # Determine the number of each type of element in the molecule\n            elements = ['C','H','N','O']; elementCounts = [0,0,0,0]\n\n            # Remove elements with zero count\n            index = 2\n            while index < len(elementCounts):\n                if elementCounts[index] == 0:\n                    del elements[index]\n                    del elementCounts[index]\n                else:\n                    index += 1\n        \n            # Line 1\n            string = '{0:<16}        '.format(species.label)\n            if len(elements) <= 4:\n                # Use the original Chemkin syntax for the element counts\n                for symbol, count in zip(elements, elementCounts):\n                    string += '{0!s:<2}{1:<3d}'.format(symbol, count)\n                string += '     ' * (4 - len(elements))\n            else:\n                string += '     ' * 4\n            string += 'G{0:<10.3f}{1:<10.3f}{2:<8.2f}      1'.format(poly_low.Tmin.value_si, poly_high.Tmax.value_si, poly_low.Tmax.value_si)\n            if len(elements) > 4:\n                string += '&\\n'\n                # Use the new-style Chemkin syntax for the element counts\n                # This will only be recognized by Chemkin 4 or later\n                for symbol, count in zip(elements, elementCounts):\n                    string += '{0!s:<2}{1:<3d}'.format(symbol, count)\n            string += '\\n'\n        \n            # Line 2\n            string += '{0:< 15.8E}{1:< 15.8E}{2:< 15.8E}{3:< 15.8E}{4:< 15.8E}    2\\n'.format(poly_high.c0, poly_high.c1, poly_high.c2, poly_high.c3, poly_high.c4)\n        \n            # Line 3\n            string += '{0:< 15.8E}{1:< 15.8E}{2:< 15.8E}{3:< 15.8E}{4:< 15.8E}    3\\n'.format(poly_high.c5, poly_high.c6, poly_low.c0, poly_low.c1, poly_low.c2)\n        \n            # Line 4\n            string += '{0:< 15.8E}{1:< 15.8E}{2:< 15.8E}{3:< 15.8E}                   4\\n'.format(poly_low.c3, poly_low.c4, poly_low.c5, poly_low.c6)\n        \n            f.write(string)\n            \n            f.close()\n    \n\n    def plot(self, outputDirectory):\n        \"\"\"\n        Plot the heat capacity, enthapy, entropy, and Gibbs free energy of the\n        fitted thermodynamics model, along with the same values from the\n        statistical mechanics model that the thermodynamics model was fitted \n        to. The plot is saved to the file ``thermo.pdf`` in the output\n        directory. The plot is not generated if ``matplotlib`` is not installed.\n        \"\"\"\n        # Skip this step if matplotlib is not installed\n        try:\n            import pylab\n        except ImportError:\n            return\n        \n        Tlist = numpy.arange(10.0, 2501.0, 10.0)\n        Cplist = numpy.zeros_like(Tlist)\n        Cplist1 = numpy.zeros_like(Tlist)\n        Hlist = numpy.zeros_like(Tlist)\n        Hlist1 = numpy.zeros_like(Tlist)\n        Slist = numpy.zeros_like(Tlist)\n        Slist1 = numpy.zeros_like(Tlist)\n        Glist = numpy.zeros_like(Tlist)\n        Glist1 = numpy.zeros_like(Tlist)\n        \n        conformer = self.species.conformer\n        thermo = self.species.getThermoData()\n        for i in range(Tlist.shape[0]):\n            Cplist[i] = conformer.getHeatCapacity(Tlist[i])\n            Slist[i] = conformer.getEntropy(Tlist[i])\n            Hlist[i] = (conformer.getEnthalpy(Tlist[i]) + conformer.E0.value_si) * 0.001\n            Glist[i] = Hlist[i] - Tlist[i] * Slist[i] * 0.001\n            Cplist1[i] = thermo.getHeatCapacity(Tlist[i])\n            Slist1[i] = thermo.getEntropy(Tlist[i])\n            Hlist1[i] = thermo.getEnthalpy(Tlist[i]) * 0.001\n            Glist1[i] = thermo.getFreeEnergy(Tlist[i]) * 0.001\n\n        fig = pylab.figure(figsize=(10,8))\n\n        pylab.subplot(2,2,1)\n        pylab.plot(Tlist, Cplist / 4.184, '-r', Tlist, Cplist1 / 4.184, '-b')\n        pylab.xlabel('Temperature (K)')\n        pylab.ylabel('Heat capacity (cal/mol*K)')\n        pylab.legend(['statmech', 'thermo'], loc=4)\n\n        pylab.subplot(2,2,2)\n        pylab.plot(Tlist, Slist / 4.184, '-r', Tlist, Slist1 / 4.184, '-b')\n        pylab.xlabel('Temperature (K)')\n        pylab.ylabel('Entropy (cal/mol*K)')\n\n        pylab.subplot(2,2,3)\n        pylab.plot(Tlist, Hlist / 4.184, '-r', Tlist, Hlist1 / 4.184, '-b')\n        pylab.xlabel('Temperature (K)')\n        pylab.ylabel('Enthalpy (kcal/mol)')\n\n        pylab.subplot(2,2,4)\n        pylab.plot(Tlist, Glist / 4.184, '-r', Tlist, Glist1 / 4.184, '-b')\n        pylab.xlabel('Temperature (K)')\n        pylab.ylabel('Gibbs free energy (kcal/mol)')\n\n        fig.subplots_adjust(left=0.10, bottom=0.08, right=0.95, top=0.95, wspace=0.35, hspace=0.20)\n        pylab.savefig(os.path.join(outputDirectory, 'thermo.pdf'))\n        pylab.close()\n", "meta": {"hexsha": "0a7565a7a04243aa00e4146785cafeaa18d433f7", "size": 11971, "ext": "py", "lang": "Python", "max_stars_repo_path": "rmgpy/cantherm/thermo.py", "max_stars_repo_name": "nateharms/RMG-Py", "max_stars_repo_head_hexsha": "80deaebddcbb14b7c41e232b67e1c973e0b18324", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-18T18:43:22.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-18T18:43:22.000Z", "max_issues_repo_path": "rmgpy/cantherm/thermo.py", "max_issues_repo_name": "nateharms/RMG-Py", "max_issues_repo_head_hexsha": "80deaebddcbb14b7c41e232b67e1c973e0b18324", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rmgpy/cantherm/thermo.py", "max_forks_repo_name": "nateharms/RMG-Py", "max_forks_repo_head_hexsha": "80deaebddcbb14b7c41e232b67e1c973e0b18324", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.0611510791, "max_line_length": 163, "alphanum_fraction": 0.5660345836, "include": true, "reason": "import numpy", "num_tokens": 3219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3073580295544412, "lm_q1q2_score": 0.1608774470777666}}
{"text": "__author__ = 'sebastian'\n\nimport os\nimport copy\nimport numpy as np\nimport math\nfrom Utility.Logging_Extension import logger\nfrom Utility.Types.Extrinsics import Extrinsics\nfrom Utility.Types.Intrinsics import Intrinsics\nfrom Utility.Types.Ray import Ray\n\n\nclass Camera(Extrinsics, Intrinsics):\n\n    DEPTH_MAP_WRT_UNIT_VECTORS = \"DEPTH_MAP_WRT_UNIT_VECTORS\"\n    DEPTH_MAP_WRT_CANONICAL_VECTORS = \"DEPTH_MAP_WRT_CANONICAL_VECTORS\"  # Vectors where the last component is 1\n\n    def __init__(self, file_name=None, width=None, height=None):\n\n        # Coordinate system defines self._quaternion and self.rotation_mat\n        super(Camera, self).__init__()\n\n        # Used for visualization\n        self.normal = np.array([0, 0, 0], dtype=float)\n        # single color to represent the camera (for example in a ply file)\n        self.color = np.array([255, 255, 255], dtype=int)\n\n        self.file_name = file_name\n\n        self.width = width\n        self.height = height\n\n        # Differentiate between view/image index and reconstruction index\n        self.view_index = None          # This is the index w.r.t. to the input images\n        self.camera_index = None        # This is the index w.r.t the reconstructed cameras\n\n        self.depth_map_fp = None\n        self.depth_map_callback = None\n        self.depth_map_semantic = None\n\n\n    # defines how the class will be printed\n    def __repr__(self):\n        return self.__str__()\n\n    def __str__(self):\n        file_name = self.file_name\n        if file_name is None:\n            file_name = 'None'\n        return str('Camera: ' + file_name + ' ' + str(self._center) + ' ' + str(self.normal))\n\n    def is_monocular_cam(self):\n        return True\n\n    # def compare_file_name(self, other):\n    #     return self.file_name < other.file_name\n\n    def get_file_name(self):\n        return self.file_name\n\n    def get_h5_file_name(self):\n        return os.path.splitext(self.file_name)[0] + '.h5'\n\n    def get_viewing_dir_world_coord(self):\n\n        # Positive viewing dir\n        viewing_dir_cam_coord = np.asarray([0, 0, 1], dtype=float)\n        ray_dir_vec = np.dot(self.get_rotation_mat().T, viewing_dir_cam_coord)\n        return ray_dir_vec\n\n    def get_up_dir_world_coord(self):\n\n        # Positive viewing dir\n        up_dir_cam_coord = np.asarray([0, 1, 0], dtype=float)\n        ray_dir_vec = np.dot(self.get_rotation_mat().T, up_dir_cam_coord)\n        return ray_dir_vec\n\n    # ============================= Projecting Single POINTS into Image ==========================================\n\n    def project_single_point_woorld_coord_into_camera_image_as_image_coord(self, point_world_coord):\n        \"\"\"\n        $ >>> point_world_coordinates.shape\n        $ >>> (3,)\n        :param point_world_coord:\n        :return:\n        \"\"\"\n        image_point, visible = self.project_single_woorld_coord_into_camera_image_as_image_coord(\n            point_world_coord.coord)\n        return image_point, visible\n\n    # ============================= Projecting Single COORDS into Image ==========================================\n\n    def project_single_woorld_coord_into_camera_image_as_image_coord(self,\n                                                                     coord_in_world_coord):\n        \"\"\"\n        $ >>> point_world_coordinates.shape\n        $ >>> (3,)\n        :param coord_in_world_coord:\n        :return:\n        \"\"\"\n        point_cam_coord = self.world_to_cam_coord_single_coord(\n            world_coord=coord_in_world_coord)\n        image_point, visible = \\\n            self.project_single_point_cam_coord_into_camera_image_as_image_coord(\n            point_cam_coord)\n        return image_point, visible\n\n    def project_single_point_cam_coord_into_camera_image_as_image_coord(self,\n                                                                        point_cam_coord):\n\n        \"\"\"\n        THIS RETURNS IMAGE POINTS WITHIN [0, width] x [0, height]\n        :param point_cam_coord:\n        :param debug_output:\n        :return:\n        \"\"\"\n\n        visible = False\n        image_point = None\n\n        assert self.width > 0\n        assert self.height > 0\n\n        #logger.vinfo('calibration_mat', calibration_mat)\n\n        # To the Visibility of 3D points (on the image plane)\n        # Depth of a point with respect to a certain camera is described in Multiple View Geometry on page 162\n        # Further Key Words: View Frustum\n        # On the other hand: Each point is exactly visible if its projection into the camera coordinate frame\n        # has a z component > 0. In addition, we must check that the projection of the point lies within the image\n        # bounds (see below)\n        if point_cam_coord[2] > 0:\n\n            # Make sure the calibration matrix is valid\n\n            #  project the 3d point onto the 2D camera image plane\n            point_image_plane_hom = self.get_calibration_mat().dot(point_cam_coord)\n\n            # See Multiple View Geometry page 155\n            # point_image_plane_hom = [fX+Zp_x, fY+Zp_y, Z]\n            # with camera point [X,Y,Z] and principal point [p_x, p_y]\n            # Remember: two homogeneous coordinates hom_1 and hom_2 with hom_1 = a hom_2 for a scalar 'a' are\n            # considered as equivalent\n            # Dividing by the last component (i.e. z = 1) results in the image plane coordinates\n            # [fX+Zp_x, fY+Zp_y, Z] -> [fX/Z+p_x, fY/Z+p_y, 1]\n            point_image_plane_hom = (point_image_plane_hom / point_image_plane_hom[2])\n\n            # x_image_coord and y_image_coord are within [0, width] x [0, height]\n            x_image_coord = copy.deepcopy(point_image_plane_hom[0])\n            y_image_coord = copy.deepcopy(point_image_plane_hom[1])\n\n            if self.has_radial_distortion():\n\n                # http://ccwu.me/vsfm/doc.html#nvm\n                # https://groups.google.com/forum/#!msg/vsfm/IcbdIVv_Uek/Us32SBUNK9oJ\n\n                # NOTE that the parameters saved in NVM file is slightly different with the internal representation.\n                # Instead, NVM saves the following for each camera:\n                # f, R (as quaternion), C = - R'T, rn = r * f * f.\n                # The PBA code includes functions for loading the NVM file and convert the camera parameters.\n                rn = self.get_radial_distortion()\n\n                r = rn / float(self.get_focal_length() * self.get_focal_length())\n\n                # mx and my are centered around the principal point\n                principal_point = self.get_principal_point()\n                mx = x_image_coord - principal_point[0]\n                my = y_image_coord - principal_point[1]\n\n                # The distortion factor is r2 = r * (mx * mx + my * my)\n                r_2 = r * (mx * mx + my * my)\n                logger.vinfo('r_2', r_2)\n\n                # The undistorted measurement is (1 + r2) * (mx, my)\n                undistorted_x = (1 + r_2) * mx\n                undistorted_y = (1 + r_2) * my\n\n                logger.vinfo('x_image_coord (without undistortion)', x_image_coord)\n                logger.vinfo('y_image_coord (without undistortion)', y_image_coord)\n\n                x_image_coord = undistorted_x + principal_point[0]\n                y_image_coord = undistorted_y + principal_point[1]\n                logger.vinfo('x_image_coord (with undistortion)', x_image_coord)\n                logger.vinfo('y_image_coord (with undistortion)', y_image_coord)\n\n                # THE UNDISTORTED VALUES ARE NOT REALLY BETTER THAN THE ORIGINAL ONES\n                # TODO MAYBE BUG IS FIXED NOW\n                # TODO INVESTIGATE\n                # TODO TEST WITH FISHEYE\n                assert False    # Radial Distortion support is disabled for now\n\n            on_image_plane_x = abs(x_image_coord) < self.width\n            on_image_plane_y = abs(y_image_coord) < self.height\n\n            visible = on_image_plane_x and on_image_plane_y\n\n            image_point = (x_image_coord, y_image_coord)\n\n        return image_point, visible\n\n    def compute_reprojection_error_single_point(self, point):\n        projected_image_point, visible = \\\n            self.project_single_woorld_coord_into_camera_image_as_image_coord(\n                point.coord)\n        if not visible:\n            return None\n        for measurement in point.measurements:\n            if measurement.camera_index == self.camera_index:\n                error_x = measurement.x - projected_image_point[0]\n                error_y = measurement.y - projected_image_point[1]\n                error = math.sqrt(error_x * error_x + error_y * error_y)\n                return error\n\n\n    # ============================= Projecting Multiple POINTS into Image ==========================================\n\n    def project_multiple_points_woorld_coord_into_camera_image_as_image_coord(self, points_world_coord):\n        \"\"\"\n        $ >>> point_world_coordinates.shape\n        $ >>> (3,)\n        :param point_world_coord:\n        :return:\n        \"\"\"\n\n        image_points = []\n        visibility_flags = []\n        for point in points_world_coord:\n            image_point, visible = \\\n                self.project_single_point_woorld_coord_into_camera_image_as_image_coord(point)\n            image_points.append(image_point)\n            visibility_flags.append(visible)\n        return image_points, visibility_flags\n\n    # ============================= Projecting Multiple COORDS into Image ==========================================\n\n    def project_multiple_world_coords_into_camera_image_as_image_coord(self,\n                                                                       coords_world_coord):\n        \"\"\"\n        :param coords_world_coord: is a single array\n        :return: points_image_plane: is not necessarily lying on the image plane (check visibility array)\n        :return: visibility_array: contains True and False values (visibility_array.dtype is bool)\n        \"\"\"\n\n        #logger.info('project_multiple_world_coords_into_camera_image_as_image_coord: ...')\n\n        # shape = rows, columns\n        #logger.info('points_world_coordinates.shape: ' + str(coords_world_coord.shape))\n        assert coords_world_coord.shape[0] == 3 and coords_world_coord.shape[1] > 3\n        assert self.width is not None\n        assert self.height is not None\n\n        if self.has_radial_distortion():\n            assert False    # Radial distortion not supported atm\n\n        # transformation of the object coordinate system to the camera coordinate system\n        # point_cam_coord = (self.get_rotation_mat()).dot(point_world_coordinates - self.get_camera_center())\n\n        # make coordinate homogeneous and apply transformation\n        hom_row = np.ones(coords_world_coord.shape[1])\n        # can't use hstack or vstack here, since dimensions do not match\n        points_world_coordinates_hom = np.row_stack((coords_world_coord, hom_row))\n        points_cam_coord_hom = self.get_4x4_world_to_cam_mat().dot(\n            points_world_coordinates_hom)\n\n        coord_cam_coord = points_cam_coord_hom[0:3]\n        # Rows first, columns later => points_world_coordinates[row_index][column_index]\n        # points_world_coordinates has 3 ROWS and N COLUMNS (N >> 3)\n        # The first/second/third row contains the x/y/z values for ALL points\n        # points_world_coordinates[row_index] is a np.array with N elements\n        #logger.vinfo('points_world_coordinates.shape', points_world_coordinates.shape)\n        #logger.vinfo('coord_cam_coord.shape', coord_cam_coord.shape)\n\n        # logger.debug('============DEBUG============')\n        # points_cam_coord_ref = np.empty([3, 0], dtype=float)\n        # for ground_point in ground_points:\n        #     point_world_coordinates = ground_point.get_coord_as_array()\n        #     point_cam_coordinates = self.world_to_cam_coord_single_point(point_world_coordinates)\n        #     points_cam_coord_ref = np.column_stack((points_cam_coord_ref, point_cam_coordinates))\n        # # 'allclose' test due to numerical differences\n        # comp_val = np.allclose(coord_cam_coord, points_cam_coord_ref)\n        # assert comp_val\n        # logger.debug('=============================')\n\n        points_image_plane, visibility_array = \\\n            self.project_multiple_cam_coords_into_camera_image_as_image_coord(\n                coord_cam_coord)\n\n        #logger.info('project_multiple_world_coords_into_camera_image_as_image_coord: Done')\n\n        return points_image_plane, visibility_array\n\n    def project_multiple_cam_coords_into_camera_image_as_image_coord(self, coords_cam_coord):\n        \"\"\"\n\n        :param coords_cam_coord:\n        :return: points_image_plane: is not necessarily lying on the image plane (check visibility_array)\n        :return: visibility_array: contains True and False values (visibility_array.dtype is bool)\n        \"\"\"\n\n        #logger.vinfo('points_cam_coord.shape', coords_cam_coord.shape)\n        assert coords_cam_coord.shape[0] == 3 and coords_cam_coord.shape[1] > 3\n\n        points_image_plane_hom = self.get_calibration_mat().dot(coords_cam_coord)\n        #points_image_plane_hom = (self.get_calibration_mat()).dot(coords_cam_coord)\n        # logger.vinfo('points_image_plane_hom.shape', points_image_plane_hom.shape)\n\n        # element wise ops: np.true_divide(), np.greater()\n        in_front_of_array = np.greater(coords_cam_coord[2], np.zeros(len(coords_cam_coord[2]), dtype=float))\n\n        # normalization of the homogeneous coordinates\n        points_image_plane_hom[0] = np.true_divide(points_image_plane_hom[0], points_image_plane_hom[2])\n        points_image_plane_hom[1] = np.true_divide(points_image_plane_hom[1], points_image_plane_hom[2])\n\n        # use the absolute value to safe comparisons\n        on_image_plane_x = np.logical_and(points_image_plane_hom[0] >= 0, points_image_plane_hom[0] < self.width)\n        on_image_plane_y = np.logical_and(points_image_plane_hom[1] >= 0, points_image_plane_hom[1] < self.height)\n\n        # np.logical_and does not support 3 arguments (3 parameter is the output array)\n        visibility_array = np.logical_and(in_front_of_array, on_image_plane_x)\n        visibility_array = np.logical_and(visibility_array, on_image_plane_y)\n\n        points_image_plane_hom = copy.deepcopy(points_image_plane_hom)\n\n        return points_image_plane_hom[0:2].T, visibility_array\n\n    # ============================= Check Visibility ==========================================\n\n    def check_visibilty_of_single_point_world_coords(self, point_world_coordinates):\n        _, visible = self.project_single_point_woorld_coord_into_camera_image_as_image_coord(\n            point_world_coordinates)\n        return visible\n\n    def check_visibilty_of_single_point_cam_coords(self, point_cam_coord):\n        _, visible = self.project_single_point_cam_coord_into_camera_image_as_image_coord(\n            point_cam_coord)\n        return visible\n\n    def check_visibility_of_points_world_coords(self, points_world_coordinates):\n        \"\"\"\n        Checks the visibility of points in camera coordinates. Returns a binary array\n        $ >>> points_world_coordinates.shape\n        $ >>> (n,3)                 # where n is the number of points\n        :param points_world_coordinates:\n        :return:\n        \"\"\"\n        logger.info('check_visibility_of_world_points: ...')\n        _, visibility_array = \\\n            self.project_multiple_world_coords_into_camera_image_as_image_coord(\n                points_world_coordinates)\n        logger.info('check_visibility_of_world_points: Done')\n        return visibility_array\n\n    def check_visibility_of_points_cam_coords(self, points_cam_coord):\n        \"\"\"\n        Checks the visibility of points in camera coordinates. Returns a binary array\n        $ >>> points_world_coordinates.shape\n        $ >>> (n,3)                 # where n is the number of points\n        \"\"\"\n        logger.info('check_visibility_of_cam_points: ...' )\n        _, visibility_array = \\\n            self.project_multiple_cam_coords_into_camera_image_as_image_coord(points_cam_coord)\n        logger.info('check_visibility_of_cam_points: Done')\n        return visibility_array\n\n    # ============================== Measurements ===============================================================\n    def compute_measurement_pos_of_points(self, points):\n\n        measurement_pos = []\n        for point in points:\n            for measurement in point.measurements:\n                if measurement.camera_index == self.camera_index:\n                    measurement_pos.append(measurement.get_x_y())\n        return measurement_pos\n\n    # ============================== Camera Rays ===============================================================\n\n    def generate_camera_rays(self, x_y_positions, convert_to_world_coords=True):\n        \"\"\"\n        SUPPORTS ATM ONLY \"SIMPLE_PINHOLE\", i.e. f,cx,cy and a scale ratio of 0\n        \"\"\"\n\n        assert self.width is not None\n        assert self.height is not None\n\n        focal_length = self._calibration_mat[0][0]\n        rays = []\n        for x_y in x_y_positions:\n            #logger.info(x_y)\n            assert x_y[0] >= 0 and x_y[1] >= 0\n\n            # Compute the direction vector in CAMERA COORDINATES\n            ray_dir_vec = np.array([x_y[0] - self.width/float(2),       # x\n                                    x_y[1] - self.height/float(2),      # y\n                                    focal_length],\n                                   dtype=float)\n            ray_pos_vec = np.zeros(3)\n\n            if convert_to_world_coords:\n                # Compute the direction vector in WORLD COORDINATES\n                ray_dir_vec = np.dot(self.get_rotation_mat().T, ray_dir_vec)\n                ray_pos_vec = self.get_camera_center()\n\n            rays.append(Ray(pos_vec=ray_pos_vec, dir_vec=ray_dir_vec))\n        return rays\n\n    def set_depth_map(self, depth_map_ifp, depth_map_callback, depth_map_semantic):\n        self.depth_map_fp = depth_map_ifp\n        self.depth_map_callback = depth_map_callback\n        self.depth_map_semantic = depth_map_semantic\n\n    def get_depth_map(self):\n        if os.path.isfile(self.depth_map_fp):\n            return self.depth_map_callback(self.depth_map_fp)\n        else:\n            return None\n\n\n    def convert_depth_map_to_world_coords(self,\n                                          depth_map,\n                                          depth_map_semantic,\n                                          shift_to_pixel_center,        # False for Colmap, True for MVE\n                                          depth_map_display_sparsity=100,\n                                          inverted_cam_model=False):\n        \"\"\"\n        Do not confuse z_buffer with depth_buffer!\n        z_buffer contains values in [0,1]\n        depth_buffer contains the actual distance values\n\n        :param depth_buffer_matrix:\n        :param n_th_result_point:\n        :return:\n        \"\"\"\n        logger.info('Converting depth map to world coordinates: ...')\n        cam_coords = self.convert_depth_map_to_cam_coords(\n            depth_map,\n            depth_map_semantic,\n            shift_to_pixel_center,\n            depth_map_display_sparsity,\n            inverted_cam_model=inverted_cam_model)\n\n        world_coords = self.cam_to_world_coord_multiple_coords(\n            cam_coords)\n\n        logger.info('Converting depth map to world coordinates: Done')\n        return world_coords\n\n    def convert_depth_map_to_cam_coords(self,\n                                        depth_map,\n                                        depth_map_semantic,\n                                        shift_to_pixel_center,  # False for Colmap, True for MVE\n                                        depth_map_display_sparsity=100,\n                                        inverted_cam_model=False):\n\n        assert 0 < depth_map_display_sparsity\n\n        height, width = depth_map.shape\n        logger.info('height ' + str(height))\n        logger.info('width ' + str(width))\n\n        if self.height == height and self.width == width:\n            x_step_size = 1.0\n            y_step_size = 1.0\n        else:\n            x_step_size = self.width / width\n            y_step_size = self.height / height\n            logger.info('x_step_size ' + str(x_step_size))\n            logger.info('y_step_size ' + str(y_step_size))\n\n        fx, fy, skew, cx, cy = self.split_intrinsic_mat(self.get_calibration_mat())\n        logger.vinfo('fx, fy, skew, cx, cy: ', str([fx, fy, skew, cx, cy]))\n\n        indices = np.indices((height, width))\n        y_index_list = indices[0].flatten()\n        x_index_list = indices[1].flatten()\n\n        if inverted_cam_model:  # For Blender, VTK, etc\n            # Use the local coordinate system of the camera to analyze its viewing directions\n            # The Blender camera coordinate system looks along the negative z axis (blue),\n            # the up axis points along the y axis (green).\n            y_index_list = y_index_list[::-1]  # Reverse order of indices\n            x_index_list = x_index_list[::-1]  # Reverse order of indices\n            fx = -fx\n            fy = -fy\n            assert False    # TODO Verify this\n\n        depth_values = depth_map.flatten()\n\n        assert len(x_index_list) == len(y_index_list) == len(depth_values)\n\n        if shift_to_pixel_center:\n            # https://github.com/simonfuhrmann/mve/blob/master/libs/mve/depthmap.cc\n            #  math::Vec3f v = invproj * math::Vec3f(\n            #       (float)x + 0.5f, (float)y + 0.5f, 1.0f);\n            u_index_coord_list = x_step_size * x_index_list + 0.5\n            v_index_coord_list = y_step_size * y_index_list + 0.5\n        else:\n            # https://github.com/colmap/colmap/blob/dev/src/base/reconstruction.cc\n            #   // COLMAP assumes that the upper left pixel center is (0.5, 0.5)\n            # i.e. pixels are already shifted\n            u_index_coord_list = x_step_size * x_index_list\n            v_index_coord_list = y_step_size * y_index_list\n\n        # The cannoncial vectors are defined according to p.155 of\n        # \"Multiple View Geometry\" by Hartley and Zisserman using a canonical\n        # focal length of 1 , i.e. vec = [(x - cx) / fx, (y - cy) / fy, 1]\n        x_coords_canonical = (u_index_coord_list - cx) / fx + (cy - v_index_coord_list) * skew / (fx * fy)\n        y_coords_canonical = (v_index_coord_list - cy) / fy\n        z_coords_canonical = np.ones(len(depth_values), dtype=float)\n\n        # Determine non-background data\n        # non_background_flags = np.logical_not(np.isnan(depth_values))\n        depth_values_not_nan = np.nan_to_num(depth_values)\n        non_background_flags = depth_values_not_nan > 0\n\n        x_coords_canonical_filtered = x_coords_canonical[non_background_flags]\n        y_coords_canonical_filtered = y_coords_canonical[non_background_flags]\n        z_coords_canonical_filtered = z_coords_canonical[non_background_flags]\n        depth_values_filtered = depth_values[non_background_flags]\n\n        if depth_map_display_sparsity != 100:\n            x_coords_canonical_filtered = x_coords_canonical_filtered[::depth_map_display_sparsity]\n            y_coords_canonical_filtered = y_coords_canonical_filtered[::depth_map_display_sparsity]\n            z_coords_canonical_filtered = z_coords_canonical_filtered[::depth_map_display_sparsity]\n            depth_values_filtered = depth_values_filtered[::depth_map_display_sparsity]\n\n        if depth_map_semantic == Camera.DEPTH_MAP_WRT_CANONICAL_VECTORS:\n            # In this case, the depth values are defined w.r.t. the canonical\n            # vectors. This kind of depth data is used by Colmap.\n            x_coords_filtered = x_coords_canonical_filtered * depth_values_filtered\n            y_coords_filtered = y_coords_canonical_filtered * depth_values_filtered\n            z_coords_filtered = z_coords_canonical_filtered * depth_values_filtered\n\n        elif depth_map_semantic == Camera.DEPTH_MAP_WRT_UNIT_VECTORS:\n            # In this case the depth values are defined w.r.t. the normalized\n            # canonical vectors. This kind of depth data is used by MVE.\n            cannonical_norms_filtered = np.linalg.norm(\n                np.array(\n                    [x_coords_canonical_filtered,\n                     y_coords_canonical_filtered,\n                     z_coords_canonical_filtered],\n                    dtype=float),\n                axis=0)\n            # Instead of normalizing the x,y and z component, we divide the\n            # depth values by the corresponding norm.\n            normalized_depth_values_filtered = depth_values_filtered / cannonical_norms_filtered\n            x_coords_filtered = x_coords_canonical_filtered * normalized_depth_values_filtered\n            y_coords_filtered = y_coords_canonical_filtered * normalized_depth_values_filtered\n            z_coords_filtered = z_coords_canonical_filtered * normalized_depth_values_filtered\n\n        else:\n            assert False\n\n        cam_coords = np.dstack(\n            (x_coords_filtered,\n             y_coords_filtered,\n             z_coords_filtered))[0]\n\n        return cam_coords\n\n    @staticmethod\n    def parse_camera_image_files(cameras, path_to_images):\n        from PIL import Image\n        for camera in cameras:\n            # this does NOT load the data; into memory -> should be fast!\n            image = Image.open(os.path.join(path_to_images, camera.file_name))\n            camera.width, camera.height = image.size\n        return cameras\n\n    @staticmethod\n    def parse_camera_h5_files(cameras, path_to_h5_files):\n        from Utility.File_Handler.H5_File_Handler import H5FileHandler\n        for camera in cameras:\n            seg = H5FileHandler.read_h5(os.path.join(path_to_h5_files, camera.get_h5_file_name()))\n            camera.height, camera.width = seg.shape\n        return cameras\n\n    # ============================== Depth Buffer Legacy =============================================================\n\n    # def convert_depth_buffer_to_cam_coords_legazy(self,\n    #                                               depth_buffer_matrix,\n    #                                               depth_scale_value=1.0,\n    #                                               background_depth_value=1000,\n    #                                               invert_y=False,\n    #                                               n_th_result_point=100\n    #                                               ):\n    #     \"\"\"\n    #     Do not confuse z_buffer with depth_buffer!\n    #     z_buffer contains values in [0,1]\n    #     depth_buffer contains the actual distance values\n    #\n    #     Computes only 1/n_th_result_point points for the point cloud\n    #     :param depth_buffer_matrix:\n    #     :param n_th_result_point:\n    #     :return:\n    #     \"\"\"\n    #\n    #     logger.info('convert_depth_matrix_to_camera_coords: ...')\n    #\n    #     assert self.height is not None\n    #     assert self.width is not None\n    #\n    #     depth_buffer_matrix *= depth_scale_value\n    #\n    #     fx = self.get_calibration_mat()[0][0]\n    #     logger.vinfo('focal_length_in_pixel', fx)\n    #\n    #     # use the local coordinate system of the camera\n    #     # to analyze its viewing directions\n    #     # blender camera coordinate system looks along the negative z axis (blue)\n    #     # the up axis points along the y axis (green)\n    #\n    #     coords_cam_coord = []\n    #     result_point_idx = 0\n    #     num_pixels = self.width * self.height\n    #     for (y, x), depth_value in np.ndenumerate(depth_buffer_matrix):\n    #\n    #         if depth_value < background_depth_value:\n    #             if result_point_idx % n_th_result_point == 0:\n    #                 if result_point_idx % 10000 == 0:\n    #                     logger.info('result_point_idx ' + str(result_point_idx) + ' ' + str(num_pixels))\n    #\n    #                 cx, cy = self.get_principal_point()\n    #\n    #                 x = self.width - x  # Invert x\n    #                 if invert_y:\n    #                     y = self.height - y\n    #\n    #                 x = x - cx  # Shift x from image to camera coordinates\n    #                 y = y - cy  # Shift y from image to camera coordinates\n    #                 z = -fx  # Invert z\n    #                 pixel_vec = np.array([x, y, z], dtype=float)\n    #\n    #                 # convert to inhomogeneous coordinates\n    #                 # divide using the focal length (in pixels)\n    #                 # (i.e. the resulting vector is unit free)\n    #                 pixel_vec /= pixel_vec[2]\n    #                 # multiply by depth value in blender units / meters\n    #                 # (i.e. the resulting vector is in blender units / meters)\n    #                 pixel_vec *= depth_value\n    #                 coords_cam_coord.append(pixel_vec)\n    #             result_point_idx += 1\n    #\n    #     logger.info('convert_depth_matrix_to_camera_coords: Done')\n    #     return coords_cam_coord\n\n\n    # def convert_depth_buffer_to_world_coords_legazy(self,\n    #                                                 depth_buffer_matrix,\n    #                                                 depth_scale_value=1.0,\n    #                                                 background_depth_value=1000,\n    #                                                 invert_y=False,\n    #                                                 n_th_result_point=100\n    #                                                 ):\n    #\n    #     coords_cam_coord = self.convert_depth_buffer_to_cam_coords_legazy(\n    #         depth_buffer_matrix=depth_buffer_matrix,\n    #         depth_scale_value=depth_scale_value,\n    #         background_depth_value=background_depth_value,\n    #         invert_y=invert_y,\n    #         n_th_result_point=n_th_result_point\n    #     )\n    #\n    #     coords_world_coord = self.cam_to_world_coord_multiple_coords(\n    #         coords_cam_coord)\n    #     return coords_world_coord\n\n\n", "meta": {"hexsha": "9c9b0477b4067fd24a5c89c31943b29faa2418ae", "size": 29930, "ext": "py", "lang": "Python", "max_stars_repo_path": "Types/Camera.py", "max_stars_repo_name": "SBCV/PythonUtility", "max_stars_repo_head_hexsha": "0062e1e60dc151776b963d13bc4c1763eb90d333", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-02-20T14:56:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T12:31:53.000Z", "max_issues_repo_path": "Types/Camera.py", "max_issues_repo_name": "SBCV/PythonUtility", "max_issues_repo_head_hexsha": "0062e1e60dc151776b963d13bc4c1763eb90d333", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Types/Camera.py", "max_forks_repo_name": "SBCV/PythonUtility", "max_forks_repo_head_hexsha": "0062e1e60dc151776b963d13bc4c1763eb90d333", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-07T08:32:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-07T08:32:07.000Z", "avg_line_length": 44.8053892216, "max_line_length": 118, "alphanum_fraction": 0.6094553959, "include": true, "reason": "import numpy", "num_tokens": 6297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.30735802955444114, "lm_q1q2_score": 0.16087744707776658}}
{"text": "\"\"\"Everything needed for defining phases within an optimal control problem.\n\nClasses:\n\tPhase\n\"\"\"\n\n\nimport copy\nimport itertools\nfrom typing import (Optional, Tuple)\n\nimport sympy as sym\n\nfrom .bounds import PhaseBounds\nfrom .guess import PhaseGuess\nfrom .mesh import PhaseMesh\nfrom .scaling import PhaseScaling\nfrom .typing import (OptionalExprsType, OptionalSymsType, TupleSymsType)\nfrom .utils import (check_sym_name_clash, format_as_named_tuple)\n\n\n__all__ = [\"Phase\"]\n\n\nclass Phase:\n    \"\"\"A single continuous time phase as part of an optimal control problem.\n\n    Attributes:\n            name: The name associated with a problem. Should be something short \n                    like 'A'.\n            optimal_control_problem: The :obj:`OptimalControlProblem` with which \n                    this phase is to be associated.\n            state_variables: The continuous time state variables in this phase.\n            control_variables: The continuous time control variables in this phase.\n            state_equations: The dynamical state equations associated with this \n                    state variables in this phase.\n            integrand_functions: The integrand functions corresponding to the \n                    integral variables in this phase.\n            path_constraints: The continuous time path constraints associated with \n                    this phase.\n            bounds: The phase bounds on this phase. See :obj:PhaseBounds for more \n                    details.\n            scaling: The phase scaling on this phase. See :obj:PhaseScaling for \n                    more details.\n            guess: The initial guess at which this phase is to be solved.\n            mesh: This initial mesh on which this phase is to be solved.\n            _name: Protected version of :attr:`name`.\n            _ocp: Protected version of :attr:`optimal_control_problem`.\n            _phase_number: Protected integer number associated with this phase. If \n                    not associated with any optimal control problem then defaults to \n                    None until one is associated. These are ordered sequentially \n                    starting at '0' in the order with which phases are added to an \n                    optimal control problem.\n            _phase_suffix: Protected str which is used in the naming of auto-\n                    generated Pycollo variables such as the endpoint state variables.\n            _y_var_user: Protected version of :attr:`state_variables`. \n            _u_var_user: Protected version of :attr:`control_variables`.\n            _q_var_user: Protected version of :attr:`integral_variables`.\n            _t_var_user: Protected version of :attr:`time_variables`.\n            _y_eqn_user: Protected version of :attr:`state_equations`. \n            _c_con_user: Protected version of :attr:`path_constraints`. \n            _q_fnc_user: Protected version of :attr:`integrand_functions`.\n            _t0_USER: Protected version of :attr:`initial_time_variable`.\n            _tF_USER: Protected version of :attr:`final_time_variable`.\n            _t0: Internal Pycollo symbol for phase initial time.\n            _tF: Internal Pycollo symbol for phase final time.\n            _STRETCH: Convenience expression for phase time scaling stretch.\n            _SHIFT: Convenience expression for phase time scaling shift.\n    \"\"\"\n\n    def __init__(self,\n                 name: str,\n                 *,\n                 optimal_control_problem: Optional[\"OptimalControlProblem\"] = None,\n                 state_variables: OptionalSymsType = None,\n                 control_variables: OptionalSymsType = None,\n                 state_equations: OptionalExprsType = None,\n                 integrand_functions: OptionalExprsType = None,\n                 path_constraints: OptionalExprsType = None,\n                 bounds: Optional[PhaseBounds] = None,\n                 scaling: Optional[PhaseScaling] = None,\n                 guess: Optional[PhaseGuess] = None,\n                 mesh: Optional[PhaseMesh] = None,\n                 ):\n        \"\"\"Initialise the Phase object with minimum a name.\n\n        Args: \n                name: The name associated with a problem. Should be something short \n                        like 'A'.\n                optimal_control_problem: The :obj:`OptimalControlProblem` with \n                        which this phase is to be associated. Default value is None in \n                        which case the phase remain uninitialised to an optimal control \n                        problem.\n                state_variables: The continuous time state variables in this phase. \n                        Default value is None in which case the phase has no associated \n                        state variables and no phase-specific endpoint time or state \n                        variables are created.\n                control_variables: The continuous time control variables in this \n                        phase. Default value is None in which case the phase has no \n                        associated control variables.\n                state_equations: The dynamical state equations associated with this \n                        state variables in this phase. Default value is None in which \n                        case no dynamical equations have been added to the phase yet.\n                integrand_functions: The integrand functions corresponding to the \n                        integral variables in this phase. Default value is None in \n                        which case the phase has no integrand functions associated with \n                        it and no phase-specific integral variables are created.\n                path_constraints: The continuous time path constraints associated \n                        with this phase. Default value is None in which case the phase \n                        has no path constraints associated with it.\n                bounds: The phase bounds on this phase. See :obj:PhaseBounds for \n                        more details. Default value is None in which case an empty \n                        :obj:`PhaseBounds` object is instantiated and associated with \n                        the phase.\n                scaling: The phase scaling on this phase. See :obj:PhaseScaling for \n                        more details. Default value is None in which case an empty \n                        :obj:`PhaseScaling` object is instantiated and associated with \n                        the phase.\n                guess: The initial guess at which this phase is to be solved. \n                        Default value is None in which case an empty :obj:`PhaseGuess` \n                        object is instantiated and associated with the phase.\n                mesh: This initial mesh on which this phase is to be solved. \n                        Default value is None in which case an empty :obj:`PhaseMesh` \n                        object is instantiated and associated with the phase.\n        \"\"\"\n\n        self._name = str(name)\n        self._ocp = None\n        self._phase_number = None\n        self._phase_suffix = \"X\"\n\n        self._y_var_user = ()\n        self._u_var_user = ()\n        self._q_var_user = ()\n        self._t_var_user = ()\n\n        self._y_eqn_user = ()\n        self._c_con_user = ()\n        self._q_fnc_user = ()\n\n        if optimal_control_problem is not None:\n            self.optimal_control_problem = optimal_control_problem\n\n        self.state_variables = state_variables\n        self.control_variables = control_variables\n\n        self.state_equations = state_equations\n        self.integrand_functions = integrand_functions\n        self.path_constraints = path_constraints\n\n        self.bounds = bounds\n        self.scaling = scaling\n        self.guess = guess\n        self.mesh = mesh\n\n        self.auxiliary_data = {}\n\n    def create_new_copy(self,\n                        name: str,\n                        *,\n                        copy_state_variables: bool = True,\n                        copy_control_variables: bool = True,\n                        copy_state_equations: bool = True,\n                        copy_path_constraints: bool = True,\n                        copy_integrand_functions: bool = True,\n                        copy_state_endpoint_constraints: bool = False,\n                        copy_bounds: bool = True,\n                        copy_mesh: bool = True,\n                        copy_scaling: bool = True,\n                        copy_guess: bool = True,\n                        ):\n\n        self._check_variables_and_equations()\n        new_phase = Phase(name,\n                          optimal_control_problem=self.optimal_control_problem)\n\n        if copy_state_variables:\n            new_phase.state_variables = copy.deepcopy(self.state_variables)\n            if copy_bounds:\n                new_phase.bounds.state_variables = copy.deepcopy(self.bounds.state_variables)\n            if copy_guess:\n                new_phase.guess.state_variables = copy.deepcopy(self.guess.state_variables)\n            if copy_scaling:\n                new_phase.scaling.state_variables = copy.deepcopy(self.scaling.state_variables)\n\n        if copy_control_variables:\n            new_phase.control_variables = copy.deepcopy(self.control_variables)\n            if copy_bounds:\n                new_phase.bounds.control_variables = copy.deepcopy(self.bounds.control_variables)\n            if copy_guess:\n                new_phase.guess.control_variables = copy.deepcopy(self.guess.control_variables)\n            if copy_scaling:\n                new_phase.scaling.control_variables = copy.deepcopy(self.scaling.control_variables)\n\n        if copy_state_equations:\n            new_phase.state_equations = copy.deepcopy(self.state_equations)\n\n        if copy_path_constraints:\n            new_phase.path_constraints = copy.deepcopy(self.path_constraints)\n            if copy_bounds:\n                new_phase.bounds.path_constraints = copy.deepcopy(self.bounds.path_constraints)\n\n        if copy_integrand_functions:\n            new_phase.integrand_functions = copy.deepcopy(self.integrand_functions)\n            if copy_bounds:\n                new_phase.bounds.integral_variables = copy.deepcopy(self.bounds.integral_variables)\n\n        if copy_state_endpoint_constraints and copy_bounds:\n            new_phase.bounds.state_endpoint_constraints = copy.deepcopy(self.bounds.state_endpoint_constraints)\n\n        if copy_mesh:\n            new_phase.mesh = copy.deepcopy(self.mesh)\n\n        return new_phase\n\n    @staticmethod\n    def create_new_copy_like(phase_for_copying: \"Phase\", name: str, **kwargs):\n        \"\"\"Constructor class to copy a phase.\"\"\"\n        return phase_for_copying.create_new_copy(name, **kwargs)\n\n    @property\n    def name(self):\n        \"\"\"Name of the phase.\"\"\"\n        return self._name\n\n    @property\n    def optimal_control_problem(self) -> Optional[\"OptimalControlProblem\"]:\n        \"\"\"The optimal control problem with which this phase is associated.\n\n        There are two allowable scenarios. In the first scenario a phase may be \n        instantiated without being associated with an optimal control problem. \n        If this is the case then the default values of `None` for the phase \n        number and 'X' for the phase suffix remain. \n\n        In the second scenario a phase is instantiated with an associated \n        optimal control problem or is associated with an optimal control \n        problem after the first type of instantiation. In this case the phase \n        is appended to the protected `_phases` attribute of the \n        :obj:`OptimalControlProblem`, the phase number is set according to its \n        position in the order of addition to the optimal controls problem's \n        phases, and its phase suffix is set as a string version of the phase \n        number. Finally a replacement of any symbols that may have been used in \n        supplementary information about the phase that contained the placeholder \n        'X' phase suffix are renamed and substituted.\n\n        No checking is done to see whether the phase is already associated with \n        the optimal control problem in question or any other optimal control \n        problem. The reason being that if the setter method for this property is \n        accessed after having already been set then an `AttributeError` is \n        raised (see below). The reason this class works like that is to avoid \n        having to allow phases to be disassociated from an \n        :obj:`OptimalControlProblem` and thus having to handled the complexities \n        that would come with the phase renumbering and substitution of any \n        phase-related information that has already been given to the optimal \n        control problem.\n\n        Raises:\n                AttributeError: If an :obj:`OptimalControlProblem` has already been \n                        associated with `self`. If a argument of any type other than \n                        :obj:`OptimalControlProblem` is passed to the \n                        `optimal_control_problem` property setter.\n        \"\"\"\n        return self._ocp\n\n    @optimal_control_problem.setter\n    def optimal_control_problem(self, ocp):\n        if self._ocp is not None:\n            msg = ('Optimal control problem is already set for this phase and '\n                   'cannot be reset.')\n            raise AttributeError(msg)\n\n        try:\n            previous_phase_names = ocp._phases._fields\n        except AttributeError:\n            previous_phase_names = ()\n        phase_names = (*previous_phase_names, self.name)\n        ocp._phases = format_as_named_tuple([*ocp._phases, self],\n                                            named_keys=phase_names, sympify=False)\n\n        self._ocp = ocp\n        self._phase_number = self._ocp.number_phases - 1\n        self._phase_suffix = str(self.phase_number)\n\n        self.state_variables = self.state_variables\n        self.integrand_functions = self.integrand_functions\n\n    @property\n    def phase_number(self) -> Optional[int]:\n        \"\"\"The integer numerical identifier for the phase.\n\n        If this phase has not yet been associated with an optimal control \n        problem then None is returned.\n\n        Corresponds to the chronological order in which it was associated with \n        the optimal control problem in question.\n        \"\"\"\n        return self._phase_number\n\n    @property\n    def initial_time_variable(self) -> sym.Symbol:\n        \"\"\"Symbol for the time at which this phase begins.\"\"\"\n        try:\n            return self._t0_USER\n        except AttributeError:\n            msg = (\"Can't access initial time until associated with an optimal \"\n                   \"control problem.\")\n            raise AttributeError(msg)\n\n    @property\n    def final_time_variable(self) -> sym.Symbol:\n        \"\"\"Symbol for the time at which this phase begins.\"\"\"\n        try:\n            return self._tF_USER\n        except AttributeError:\n            msg = (\"Can't access final time until associated with an optimal \"\n                   \"control problem.\")\n            raise AttributeError(msg)\n\n    @property\n    def initial_state_variables(self) -> TupleSymsType:\n        \"\"\"Symbols for this phase's state variables at the initial time.\n\n        Raises:\n                AttributeError: If `optimal_control_problem` property has not yet \n                        been set to a not None value. See docstring for \n                        `state_variables` for details about why.\n        \"\"\"\n        try:\n            return self._y_t0_user\n        except AttributeError:\n            msg = (\"Can't access initial state until associated with an optimal \"\n                   \"control problem.\")\n            raise AttributeError(msg)\n\n    @property\n    def final_state_variables(self) -> TupleSymsType:\n        \"\"\"Symbols for this phase's state variables at the final time.\n\n        Raises:\n                AttributeError: If `optimal_control_problem` property has not yet \n                        been set to a not None value. See docstring for \n                        `state_variables` for details about why.\n        \"\"\"\n        try:\n            return self._y_tF_user\n        except AttributeError:\n            msg = (\"Can't access initial state until associated with an optimal \"\n                   \"control problem.\")\n            raise AttributeError(msg)\n\n    @property\n    def state_variables(self) -> TupleSymsType:\n        \"\"\"Symbols for this phase's state variables in order added by user.\n\n        The user may supply either a single symbol or an iterable of symbols. \n        The supplied argument is handled by the `format_as_tuple` method from \n        the `utils` module. Additional protected attributes `_y_t0_user` and \n        `_y_tF_user` are set by post-appending either '_PX(t0)' or '_PX(tF)' to \n        the user supplied symbols where the X is replaced by the phase suffix. \n        As such if this phase has not yet been associated with an optimal \n        control problem yet then `self` will not have attributes `_y_t0_user` \n        and `_y_tF_user` and accessing either the `initial_state` or \n        `final_state` property will raise an AttributeError.\n        \"\"\"\n        return self._y_var_user\n\n    @state_variables.setter\n    def state_variables(self, y_vars: OptionalSymsType):\n\n        self._y_var_user = format_as_named_tuple(y_vars)\n        check_sym_name_clash(self._y_var_user)\n\n        # Generate the state endpoint variable symbols only if phase has number\n        if self.optimal_control_problem is not None:\n            self._t0_USER = sym.Symbol(f't0_P{self._phase_suffix}')\n            self._tF_USER = sym.Symbol(f'tF_P{self._phase_suffix}')\n            self._t0 = sym.Symbol(f'_t0_P{self._phase_suffix}')\n            self._tF = sym.Symbol(f'_tF_P{self._phase_suffix}')\n            self._STRETCH = 0.5 * (self._tF - self._t0)\n            self._SHIFT = 0.5 * (self._t0 + self._tF)\n            self._t_var_user = (self._t0_USER, self._tF_USER)\n\n            try:\n                named_keys = self._y_var_user._fields\n            except AttributeError:\n                named_keys = ()\n\n            self._y_t0_user = format_as_named_tuple(\n                (sym.Symbol(f'{y}_P{self._phase_suffix}(t0)')\n                 for y in self._y_var_user),\n                named_keys=named_keys)\n            self._y_tF_user = format_as_named_tuple(\n                (sym.Symbol(f'{y}_P{self._phase_suffix}(tF)')\n                 for y in self._y_var_user),\n                named_keys=named_keys)\n\n    @property\n    def number_state_variables(self) -> int:\n        \"\"\"Integer number of state variables in the phase.\"\"\"\n        return len(self._y_var_user)\n\n    @property\n    def control_variables(self) -> TupleSymsType:\n        \"\"\"Symbols for this phase's control variables in order added by user.\n\n        The user may supply either a single symbol or an iterable of symbols.\n        The supplied argument is handled by the `format_as_tuple` method from\n        the `utils` module.\n        \"\"\"\n        return self._u_var_user\n\n    @control_variables.setter\n    def control_variables(self, u_vars: OptionalSymsType):\n        self._u_var_user = format_as_named_tuple(u_vars)\n        check_sym_name_clash(self._u_var_user)\n\n    @property\n    def number_control_variables(self) -> int:\n        \"\"\"Integer number of control variables in the phase.\"\"\"\n        return len(self._u_var_user)\n\n    @property\n    def integral_variables(self) -> TupleSymsType:\n        \"\"\"Symbols for this phase's integral variables.\n\n        These symbols are auto generated as required by the user-supplied\n        integrand functions.\n        \"\"\"\n        return self._q_var_user\n\n    @property\n    def time_variables(self) -> TupleSymsType:\n        \"\"\"The initial and final time symbols as a pair.\"\"\"\n        return (self.initial_time_variable, self.final_time_variable)\n\n    @property\n    def number_integral_variables(self) -> int:\n        \"\"\"Integer number of integral variables in the phase.\"\"\"\n        return len(self._q_var_user)\n\n    @property\n    def state_equations(self) -> Tuple[sym.Expr, ...]:\n        \"\"\"User-supplied dynamical equations in the phase.\n\n        These equations are the dynamical equations associated with each of the \n        state variables in the phase. There should therefore be exactly one \n        state equation for each dynamics symbol.\n\n        State equations can be supplied in a compact form by the user defining additional auxiliary symbols and \n        \"\"\"\n        return self._y_eqn_user\n\n    @state_equations.setter\n    def state_equations(self, y_eqns: OptionalExprsType):\n        try:\n            named_keys = self._y_var_user._fields\n        except AttributeError:\n            named_keys = ()\n        self._y_eqn_user = format_as_named_tuple(y_eqns, use_named=True,\n                                                  named_keys=named_keys)\n\n    @property\n    def number_state_equations(self) -> int:\n        \"\"\"Integer number of state equations in the phase.\n\n        Should be the same as the number of state variables, i.e. there should \n        be a direct mapping between the two.\n        \"\"\"\n        return len(self._y_eqn_user)\n\n    @property\n    def path_constraints(self):\n        return self._c_con_user\n\n    @path_constraints.setter\n    def path_constraints(self, c_cons):\n        self._c_con_user = format_as_named_tuple(c_cons, use_named=False)\n\n    @property\n    def number_path_constraints(self):\n        return len(self._c_con_user)\n\n    @property\n    def integrand_functions(self):\n        return self._q_fnc_user\n\n    @integrand_functions.setter\n    def integrand_functions(self, integrands):\n        self._q_fnc_user = format_as_named_tuple(integrands, use_named=False)\n        self._q_var_user = tuple(sym.Symbol(f'q{i_q}_P{self._phase_suffix}')\n                                  for i_q, _ in enumerate(self._q_fnc_user))\n\n    @property\n    def number_integrand_functions(self):\n        return len(self._q_fnc_user)\n\n    @property\n    def bounds(self):\n        return self._bounds\n\n    @bounds.setter\n    def bounds(self, bounds):\n        if bounds is None:\n            self._bounds = PhaseBounds(phase=self)\n        else:\n            self._bounds = bounds\n\n    @property\n    def scaling(self):\n        return self._scaling\n\n    @scaling.setter\n    def scaling(self, scaling):\n        if scaling is None:\n            self._scaling = PhaseScaling(phase=self)\n        else:\n            self._scaling = scaling\n\n    @property\n    def mesh(self):\n        return self._mesh\n\n    @mesh.setter\n    def mesh(self, mesh):\n        if mesh is None:\n            self._mesh = PhaseMesh(phase=self)\n        else:\n            self._mesh = mesh\n\n    @property\n    def guess(self):\n        return self._guess\n\n    @guess.setter\n    def guess(self, guess):\n        if guess is None:\n            self._guess = PhaseGuess(phase=self)\n        else:\n            self._guess = guess\n\n    def _check_variables_and_equations(self):\n        \"\"\"Check the user-supplied variables and equations for this OCP phase.\n\n        Steps involved are:\n            * Ensure that the same number of state variables and state\n              equations are supplied.\n            * Ensure that the symbols related to the state equations are the\n              same set as the set of state variables.\n            * If the two sets are not the same then issue an informative\n              warning to the user describing what is wrong about the supplied\n              state variables and state equations.\n\n        Raises\n        ------\n        ValueError\n            If the state variables and symbols associated with the state\n            equations are not the same.\n\n        \"\"\"\n        try:\n            set_state_variables_keys = set(self.state_variables._fields)\n        except AttributeError:\n            set_state_variables_keys = set()\n\n        try:\n            set_state_equations_keys = set(self.state_equations._fields)\n        except AttributeError:\n            set_state_equations_keys = set()\n\n        if set_state_variables_keys != set_state_equations_keys:\n\n            intersection = set_state_variables_keys.intersection(\n                set_state_equations_keys)\n            spacer = \"', '\"\n            msg_other = []\n\n            if len(set_state_variables_keys) != len(set_state_equations_keys):\n                if len(set_state_variables_keys) == 1:\n                    msg_vars_len = (f\"{len(set_state_variables_keys)} state \"\n                                    f\"variable is\")\n                else:\n                    msg_vars_len = (f\"{len(set_state_variables_keys)} state \"\n                                    f\"variables are\")\n                if len(set_state_equations_keys) == 1:\n                    msg_eqns_len = (f\"{len(set_state_equations_keys)} state \"\n                                    f\"equation is\")\n                else:\n                    msg_eqns_len = (f\"{len(set_state_equations_keys)} state \"\n                                    f\"equations are\")\n                msg_len = (f\"{msg_vars_len} defined while {msg_eqns_len} \"\n                           f\"supplied\")\n                msg_other.append(msg_len)\n\n            only_in_variables = set_state_variables_keys.difference(\n                intersection)\n            if only_in_variables:\n                immutable_only_in_variables = list(only_in_variables)\n                if len(only_in_variables) == 1:\n                    msg_vars = (f\"the state variable \"\n                                f\"'{immutable_only_in_variables[0]}' is defined \"\n                                f\"without a state equation\")\n                else:\n                    msg_vars = (f\"the state variables \"\n                                f\"'{spacer.join(immutable_only_in_variables[:-1])}' \"\n                                f\"and '{immutable_only_in_variables[-1]}' are defined \"\n                                f\"without state equations\")\n                msg_other.append(msg_vars)\n\n            only_in_equations = set_state_equations_keys.difference(\n                intersection)\n            if only_in_equations:\n                if len(only_in_equations) == 1:\n                    immutable_only_in_equations = list(only_in_equations)\n                    msg_eqns = (f\"a state derivative is supplied for \"\n                                f\"'{immutable_only_in_equations[0]}' which is not a \"\n                                f\"state variable\")\n                else:\n                    msg_eqns = (f\"state derivatives are supplied for \"\n                                f\"'{spacer.join(immutable_only_in_equations[:-1])}' \"\n                                f\"and '{immutable_only_in_equations[-1]}' which are \"\n                                f\"not defined as state variables\")\n                msg_other.append(msg_eqns)\n\n            msg = (\"A state equation must be supplied for each state variable \"\n                   f\"in each phase. Currently in phase '{self.name}'\")\n            if len(msg_other) == 1:\n                full_msg = (f\"{msg}, {msg_other[0]}.\")\n            else:\n                full_msg = (f\"{msg}: {'; '.join(msg_other[:-1])}; and \"\n                            f\"{msg_other[-1]}.\")\n            raise ValueError(full_msg)\n\n    def __str__(self):\n        string = (f\"Phase {self.phase_number} of {self.optimal_control_problem}\")\n        return string\n\n    def __repr__(self):\n        string = (f\"Phase({repr(self.optimal_control_problem)}, \"\n                  f\"phase_number={self.phase_number})\")\n        return string\n", "meta": {"hexsha": "2514663eade4f1969524defc4b4a6a3d192b8d3d", "size": 27545, "ext": "py", "lang": "Python", "max_stars_repo_path": "pycollo/phase.py", "max_stars_repo_name": "NoNotCar/pycollo", "max_stars_repo_head_hexsha": "5c5c425788acb9decdbcb70253aeb5a482b31c55", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-09-07T13:55:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T12:28:30.000Z", "max_issues_repo_path": "pycollo/phase.py", "max_issues_repo_name": "NoNotCar/pycollo", "max_issues_repo_head_hexsha": "5c5c425788acb9decdbcb70253aeb5a482b31c55", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-06-16T20:18:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T17:03:21.000Z", "max_forks_repo_path": "pycollo/phase.py", "max_forks_repo_name": "NoNotCar/pycollo", "max_forks_repo_head_hexsha": "5c5c425788acb9decdbcb70253aeb5a482b31c55", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-10-02T23:19:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T06:05:31.000Z", "avg_line_length": 42.9719188768, "max_line_length": 112, "alphanum_fraction": 0.6108186604, "include": true, "reason": "import sympy", "num_tokens": 5381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.1608774437568798}}
{"text": "# -*- coding: utf-8 -*-\n\n# BUG1989 is pleased to support the open source community by supporting ncnn available.\n#\n# Copyright (C) 2019 BUG1989. All rights reserved.\n#\n# Licensed under the BSD 3-Clause License (the \"License\"); you may not use this file except\n# in compliance with the License. You may obtain a copy of the License at\n#\n# https://opensource.org/licenses/BSD-3-Clause\n#\n# Unless required by applicable law or agreed to in writing, software distributed\n# under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations under the License.\n\n\n\"\"\"\nQuantization module for generating the calibration tables will be used by \nquantized (INT8) models from FP32 models.with bucket split,[k, k, cin, cout]\ncut into \"cout\" buckets.\nThis tool is based on Caffe Framework.\n\"\"\"\nfrom __future__ import division\nfrom __future__ import print_function\nimport argparse\nimport numpy as np\nimport math, copy\nimport matplotlib.pyplot as plt\nimport sys,os\nimport time\nimport datetime\nfrom scipy import stats\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n# np.set_printoptions(threshold='nan')\nnp.set_printoptions(suppress=True)\n\n# def parse_args():\n#     parser = argparse.ArgumentParser(\n#         description='find the pretrained caffe models int8 quantize scale value')\n#     parser.add_argument('--model', dest='model',\n#                         help='path to pretrained weights', type=str)\n#     parser.add_argument('--mean', dest='mean',\n#                         help='value of mean', type=float, nargs=3)\n#     parser.add_argument('--norm', dest='norm',\n#                         help='value of normalize', type=float, nargs=1, default=1.0)                            \n#     parser.add_argument('--images', dest='images',\n#                         help='path to calibration images', type=str)\n#     parser.add_argument('--output', dest='output',\n#                         help='path to output calibration table file', type=str, default='calibration-dev.table')\n#     parser.add_argument('--group', dest='group',\n#                         help='enable the group scale', type=int, default=1)        \n#     parser.add_argument('--gpu', dest='gpu',\n#                         help='use gpu to forward', type=int, default=0)\n\n#     args = parser.parse_args()\n#     return args, parser\n\n\n# global args, parser\n# args, parser = parse_args()\n\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n# global params\nQUANTIZE_NUM = 127\nQUANTIZE_WINOGRAND_NUM = 31\nSTATISTIC = 1\nINTERVAL_NUM = 2048\n\n# ugly global params\nquantize_layer_lists = []\n\n\nclass QuantizeLayer:\n    def __init__(self, name, blob_name, group_num):\n        self.name = name\n        self.blob_name = blob_name\n        self.group_num = group_num\n        self.weight_scale = np.zeros(group_num)\n        self.blob_max = 0.0\n        self.blob_distubution_interval = 0.0\n        self.blob_distubution = np.zeros(INTERVAL_NUM)\n        self.blob_threshold = 0\n        self.blob_scale = 1.0\n        self.group_zero = np.zeros(group_num)\n\n    def quantize_weight(self, weight_data, flag):\n        # spilt the weight data by cout num\n        blob_group_data = np.array_split(weight_data, self.group_num)\n        for i, group_data in enumerate(blob_group_data):\n            max_val = np.max(group_data)\n            min_val = np.min(group_data)\n            threshold = max(abs(max_val), abs(min_val))\n            if threshold < 0.0001:\n                self.weight_scale[i] = 0\n                self.group_zero[i] = 1\n            else:\n                if(flag == True):\n                    self.weight_scale[i] = QUANTIZE_WINOGRAND_NUM / threshold\n                else:\n                    self.weight_scale[i] = QUANTIZE_NUM / threshold\n            print(\"%-20s group : %-5d max_val : %-10f scale_val : %-10f\" % (self.name + \"_param0\", i, threshold, self.weight_scale[i]))\n\n    def initial_blob_max(self, blob_data):\n        # get the max value of blob\n        max_val = np.max(blob_data)\n        min_val = np.min(blob_data)\n        self.blob_max = max(self.blob_max, max(abs(max_val), abs(min_val)))\n\n    def initial_blob_distubution_interval(self):\n        self.blob_distubution_interval = STATISTIC * self.blob_max / INTERVAL_NUM\n        print(\"%-20s max_val : %-10.8f distribution_intervals : %-10.8f\" % (self.name, self.blob_max, self.blob_distubution_interval))\n\n    def initial_histograms(self, blob_data):\n        # collect histogram of every group channel blob\n        th = self.blob_max\n        hist, hist_edge = np.histogram(blob_data, bins=INTERVAL_NUM, range=(0, th))\n        self.blob_distubution += hist\n\n    def quantize_blob(self):\n        # calculate threshold  \n        distribution = np.array(self.blob_distubution)\n        # pick threshold which minimizes KL divergence\n        threshold_bin = threshold_distribution(distribution) \n        self.blob_threshold = threshold_bin\n        threshold = (threshold_bin + 0.5) * self.blob_distubution_interval\n        # get the activation calibration value\n        self.blob_scale = QUANTIZE_NUM / threshold\n        print(\"%-20s bin : %-8d threshold : %-10f interval : %-10f scale : %-10f\" % (self.name, threshold_bin, threshold, self.blob_distubution_interval, self.blob_scale))\n\n    \ndef _smooth_distribution(p, eps=0.0001):\n    \"\"\"Given a discrete distribution (may have not been normalized to 1),\n    smooth it by replacing zeros with eps multiplied by a scaling factor and taking the\n    corresponding amount off the non-zero values.\n    Ref: http://web.engr.illinois.edu/~hanj/cs412/bk3/KL-divergence.pdf\n    \"\"\"\n    is_zeros = (p == 0).astype(np.float32)\n    is_nonzeros = (p != 0).astype(np.float32)\n    n_zeros = is_zeros.sum()\n    n_nonzeros = p.size - n_zeros\n    if not n_nonzeros:\n        raise ValueError('The discrete probability distribution is malformed. All entries are 0.')\n    eps1 = eps * float(n_zeros) / float(n_nonzeros)\n    assert eps1 < 1.0, 'n_zeros=%d, n_nonzeros=%d, eps1=%f' % (n_zeros, n_nonzeros, eps1)\n    hist = p.astype(np.float32)\n    hist += eps * is_zeros + (-eps1) * is_nonzeros\n    assert (hist <= 0).sum() == 0\n    return hist\n    \n    \ndef threshold_distribution(distribution, target_bin=128):\n    \"\"\"\n    Return the best threshold value. \n    Ref: https://github.com//apache/incubator-mxnet/blob/master/python/mxnet/contrib/quantization.py\n    Args:\n        distribution: list, activations has been processed by histogram and normalize,size is 2048\n        target_bin: int, the num of bin that is used by quantize, Int8 default value is 128\n    Returns:\n        target_threshold: int, num of bin with the minimum KL \n    \"\"\"   \n    distribution = distribution[1:]\n    length = distribution.size\n    threshold_sum = sum(distribution[target_bin:])\n    kl_divergence = np.zeros(length - target_bin)\n\n    for threshold in range(target_bin, length):\n        sliced_nd_hist = copy.deepcopy(distribution[:threshold])\n\n        # generate reference distribution p\n        p = sliced_nd_hist.copy()\n        p[threshold-1] += threshold_sum\n        threshold_sum = threshold_sum - distribution[threshold]\n\n        # is_nonzeros[k] indicates whether hist[k] is nonzero\n        is_nonzeros = (p != 0).astype(np.int64)\n        # \n        quantized_bins = np.zeros(target_bin, dtype=np.int64)\n        # calculate how many bins should be merged to generate quantized distribution q\n        num_merged_bins = sliced_nd_hist.size // target_bin\n        \n        # merge hist into num_quantized_bins bins\n        for j in range(target_bin):\n            start = j * num_merged_bins\n            stop = start + num_merged_bins\n            quantized_bins[j] = sliced_nd_hist[start:stop].sum()\n        quantized_bins[-1] += sliced_nd_hist[target_bin * num_merged_bins:].sum()\n        \n        # expand quantized_bins into p.size bins\n        q = np.zeros(sliced_nd_hist.size, dtype=np.float64)\n        for j in range(target_bin):\n            start = j * num_merged_bins\n            if j == target_bin - 1:\n                stop = -1\n            else:\n                stop = start + num_merged_bins\n            norm = is_nonzeros[start:stop].sum()\n            if norm != 0:\n                q[start:stop] = float(quantized_bins[j]) / float(norm)\n        q[p == 0] = 0\n        # p = _smooth_distribution(p) # with some bugs, need to fix\n        # q = _smooth_distribution(q)\n        p[p == 0] = 0.0001\n        q[q == 0] = 0.0001\n        \n        # calculate kl_divergence between q and p\n        kl_divergence[threshold - target_bin] = stats.entropy(p, q)\n\n    min_kl_divergence = np.argmin(kl_divergence)\n    threshold_value = min_kl_divergence + target_bin\n\n    return threshold_value\n\n\n\ndef net_forward(net, image):\n    \"\"\"\n    network inference and statistics the cost time\n    Args:\n        net: the instance of PyTorch inference\n        image: a image need to be inference\n    Returns:\n        none\n    \"\"\" \n    # load image\n    \n    # transformer.preprocess the image\n    \n    # net forward\n    net(image)\n\n\ndef file_name(file_dir):\n    \"\"\"\n    Find the all file path with the directory\n    Args:\n        file_dir: The source file directory\n    Returns:\n        files_path: all the file path into a list\n    \"\"\"\n    files_path = []\n\n    for root, dir, files in os.walk(file_dir):\n        for name in files:\n            file_path = root + \"/\" + name\n            print(file_path)\n            files_path.append(file_path)\n\n    return files_path\n\n\ndef network_prepare(net, mean, norm):\n    \"\"\"\n    instance the prepare process param of PyTorch network inference \n    Args:\n        net: the instance of PyTorch inference\n        mean: the value of mean \n        norm: the value of normalize \n    Returns:\n        none\n    \"\"\"\n    print(\"Network initial\")\n\n    # img_mean = np.array(mean)\n    \n    # # initial transformer\n    # transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})\n    # # convert hwc to cwh \n    # transformer.set_transpose('data', (2,0,1))\n    # # load meanfile\n    # transformer.set_mean('data', img_mean)\n    # # resize image data from [0,1] to [0,255]\n    # transformer.set_raw_scale('data', 255)   \n    # # convert RGB -> BGR\n    # transformer.set_channel_swap('data', (2,1,0))   \n    # # normalize\n    # transformer.set_input_scale('data', norm)\n\n    # return transformer  \n\n\ndef weight_quantize(net):\n    \"\"\"\n    PyTorch convolution weight blob Int8 quantize\n    Args:\n        net: the instance of PyTorch inference\n    Returns:    \n        none\n    \"\"\"\n    print(\"\\nQuantize the kernel weight:\")\n\n    for name, layer in net.named_modules():\n        # find the convolution layers to get out the weight_scale\n        if isinstance(layer, nn.Conv2d):\n            weight_blob = layer.weight.detach().numpy()\n            quanitze_layer = QuantizeLayer(name, weight_blob, layer.out_channels)\n            # quantize the weight value using 6bit for conv3x3s1 layer to winograd F(4,3)\n            if layer.kernel_size[0] == 3 and layer.stride[0] == 1 and layer.groups != layer.out_channels:\n                quanitze_layer.quantize_weight(weight_blob, True)\n            # quantize the weight value using 8bit for another conv layers \n            else:\n                quanitze_layer.quantize_weight(weight_blob, False)\n            # add the quantize_layer into the save list\n            quantize_layer_lists.append(quanitze_layer)\n\n    return None                \n\n\nclass Hook_struct:\n    def __init__(self, name, hook):\n        self.name = name     \n        self.hook = hook\n\nhook_list = []\ninput_list = []  \n\n\ndef get_feature(modules, input):\n    input_list.append(input)\n\n\ndef activation_quantize(net, images_files):\n    \"\"\"\n    Activation Int8 quantize, optimaize threshold selection with KL divergence,\n    given a dataset, find the optimal threshold for quantizing it.\n    Ref: http://on-demand.gputechconf.com/gtc/2017/presentation/s7310-8-bit-inference-with-tensorrt.pdf\n    Args:\n        net: the instance of Caffe inference\n        transformer: \n        images_files: calibration dataset\n    Returns:\n        none\n    \"\"\"\n    print(\"\\nQuantize the Activation:\")\n    print(\"image num:%d\" % len(images_files))\n\n    # register the hook1\n    for name, layer in net.named_modules():\n        if isinstance(layer, nn.Conv2d):\n            hook = layer.register_forward_pre_hook(get_feature)\n            hook_status = Hook_struct(name, hook)\n            hook_list.append(hook_status)\n\n    # run float32 inference on calibration dataset to find the activations range\n    for i, image in enumerate(images_files):\n        # inference\n        # just to test\n        image = torch.rand(1, 3, 32, 32)\n        net(image)\n        # find max threshold\n        for j, layer in enumerate(quantize_layer_lists):\n            blob = input_list[j][0].detach().numpy().flatten()\n            layer.initial_blob_max(blob)\n        # if i % 100 == 0:\n            print(\"loop stage 1 : %d/%d\" % (i, len(images_files)))\n    \n    # calculate statistic blob scope and interval distribution\n    for layer in quantize_layer_lists:\n        layer.initial_blob_distubution_interval()\n\n    input_list.clear()\n\n    # for each layers\n    # collect histograms of activations\n    print(\"\\nCollect histograms of activations:\")\n    for i, image in enumerate(images_files):\n        image = torch.rand(1, 3, 32, 32)\n        net(image)\n        for j, layer in enumerate(quantize_layer_lists):\n            blob = input_list[j][0].detach().numpy().flatten()\n            layer.initial_histograms(blob)\n        # if i % 100 == 0:\n            print(\"loop stage 2 : %d/%d\" % (i, len(images_files)))          \n\n    # calculate threshold with KL divergence\n    for layer in quantize_layer_lists:\n        layer.quantize_blob()  \n\n    # remove the hook\n    for hook in hook_list:\n        hook.hook.remove()\n\n    return None\n\n\ndef save_calibration_file(calibration_path):\n    calibration_file = open(calibration_path, 'w') \n    # save temp\n    save_temp = []\n    # save weight scale\n    for layer in quantize_layer_lists:\n        save_string = layer.name + \"_param_0\"\n        for i in range(layer.group_num):\n            save_string = save_string + \" \" + str(layer.weight_scale[i])\n        save_temp.append(save_string)\n\n    # save bottom blob scales\n    for layer in quantize_layer_lists:\n        save_string = layer.name + \" \" + str(layer.blob_scale)\n        save_temp.append(save_string)\n\n    # save into txt file\n    for data in save_temp:\n        calibration_file.write(data + \"\\n\")\n\n    calibration_file.close()\n\n    # save calibration logs\n    save_temp_log = []\n    calibration_file_log = open(calibration_path + \".log\", 'w')\n    for layer in quantize_layer_lists:\n        save_string = layer.name + \": value range 0 - \" + str(layer.blob_max) \\\n                                 + \", interval \" + str(layer.blob_distubution_interval) \\\n                                 + \", interval num \" + str(INTERVAL_NUM) \\\n                                 + \", threshold num \" + str(layer.blob_threshold) + \"\\n\" \\\n                                 + str(layer.blob_distubution.astype(dtype=np.int64))\n        save_temp_log.append(save_string)\n\n    # save into txt file\n    for data in save_temp_log:\n        calibration_file_log.write(data + \"\\n\")\n\n\ndef usage_info():\n    \"\"\"\n    usage info\n    \"\"\"\n    print(\"Input params is illegal...╮(╯3╰)╭\")\n    print(\"try it again:\\n python pytorch-int8-convert-tool.py -h\")\n\n\nclass Net(nn.Module):\n    def __init__(self):\n        super(Net, self).__init__()\n        self.conv1 = nn.Conv2d(3, 6, 5)\n        self.pool = nn.MaxPool2d(2, 2)\n        self.conv2 = nn.Conv2d(6, 16, 5)\n        self.fc1 = nn.Linear(16 * 5 * 5, 120)\n        self.fc2 = nn.Linear(120, 84)\n        self.fc3 = nn.Linear(84, 10)\n\n    def forward(self, x):\n        x = self.pool(F.relu(self.conv1(x)))\n        x = self.pool(F.relu(self.conv2(x)))\n        x = x.view(-1, 16 * 5 * 5)\n        x = F.relu(self.fc1(x))\n        x = F.relu(self.fc2(x))\n        x = self.fc3(x)\n        return x\n\n\ndef main():\n    \"\"\"\n    main function\n    \"\"\"\n\n    # time start\n    time_start = datetime.datetime.now()\n\n    # print(args)\n\n    # if args.proto == None or args.model == None or args.mean == None or args.images == None:\n    #     usage_info()\n    #     return None\n\n    # # trained pytorch path\n    # pytorch_model = args.model\n\n    # # mean value\n    # mean = args.mean\n\n    # # norm value\n    # norm = 1.0\n    # if args.norm != 1.0:\n    #     norm = args.norm[0]\n\n    # # calibration dataset\n    # images_path = args.images\n    images_path = './Images'\n\n    # # the output calibration file\n    # calibration_path = args.output\n\n    # # enable the group scale\n    # group_on = args.group\n\n    # # default use CPU to forwark\n    # if args.gpu != 0:\n    #     print(\"gpu status: %d\" % (args.gpu))\n\n    # initial caffe net and the forword model(GPU or CPU)\n    net = torch.load('./cifar10.pkl')\n    print(net)\n\n    # prepare the cnn network\n    # transformer = network_prepare(net, mean, norm)\n\n    # get the calibration datasets images files path\n    images_files = file_name(images_path)\n\n    # quanitze kernel weight of the caffemodel to find it's calibration table\n    weight_quantize(net)\n\n    # quantize activation value of the caffemodel to find it's calibration table\n    activation_quantize(net, images_files)\n\n    # save the calibration tables,best wish for your INT8 inference have low accuracy loss :)\n    save_calibration_file('./cifar10.table')\n\n    # time end\n    time_end = datetime.datetime.now()\n\n    print(\"\\nPyTorch Int8 Calibration table is done, it's cost %s, best wish for your INT8 inference has a low accuracy loss...\\(^▽^)/...\" % (time_end - time_start))\n\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "25cc3c611254f839053e28caa029ac601e95f285", "size": 17804, "ext": "py", "lang": "Python", "max_stars_repo_path": "pytorch-int8-convert-tool-dev-weight.py", "max_stars_repo_name": "qaz734913414/caffe-int8-convert-tools", "max_stars_repo_head_hexsha": "d2d45c7c2fac94776790a9f8081dc48ae1e72dbb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pytorch-int8-convert-tool-dev-weight.py", "max_issues_repo_name": "qaz734913414/caffe-int8-convert-tools", "max_issues_repo_head_hexsha": "d2d45c7c2fac94776790a9f8081dc48ae1e72dbb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pytorch-int8-convert-tool-dev-weight.py", "max_forks_repo_name": "qaz734913414/caffe-int8-convert-tools", "max_forks_repo_head_hexsha": "d2d45c7c2fac94776790a9f8081dc48ae1e72dbb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-15T14:06:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-15T14:06:26.000Z", "avg_line_length": 33.8479087452, "max_line_length": 171, "alphanum_fraction": 0.6320489778, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.16087744375687976}}
{"text": "\"\"\"\ndesitarget.cuts\n===============\n\nAn old copy of the Main Survey cuts (../cuts.py) that were used for commissioning (cmx).\n\n.. _`the Gaia data model`: https://gea.esac.esa.int/archive/documentation/GDR2/Gaia_archive/chap_datamodel/sec_dm_main_tables/ssec_dm_gaia_source.html\n.. _`the Legacy Surveys`: http://www.legacysurvey.org/\n.. _`the wiki`: https://desi.lbl.gov/trac/wiki/TargetSelectionWG/TargetSelection\n.. _`Legacy Surveys mask`: http://www.legacysurvey.org/dr8/bitmasks/\n\"\"\"\n\nimport numpy as np\nfrom pkg_resources import resource_filename\nfrom desitarget.geomask import imaging_mask\n\n# ADM set up the DESI default logger\nfrom desiutil.log import get_logger\nlog = get_logger()\n\n\ndef shift_photo_north(gflux=None, rflux=None, zflux=None):\n    \"\"\"Convert fluxes in the northern (BASS/MzLS) to the southern (DECaLS) system.\n\n    Parameters\n    ----------\n    gflux, rflux, zflux : :class:`array_like` or `float`\n        The flux in nano-maggies of g, r, z bands.\n\n    Returns\n    -------\n    The equivalent fluxes shifted to the southern system.\n\n    Notes\n    -----\n    - see also https://desi.lbl.gov/DocDB/cgi-bin/private/RetrieveFile?docid=3390;filename=Raichoor_DESI_05Dec2017.pdf;version=1\n    - Update for DR9 https://desi.lbl.gov/trac/attachment/wiki/TargetSelectionWG/TargetSelection/North_vs_South_dr9.png\n    \"\"\"\n    # ADM if floats were sent, treat them like arrays.\n    flt = False\n    if _is_row(gflux):\n        flt = True\n        gflux = np.atleast_1d(gflux)\n        rflux = np.atleast_1d(rflux)\n        zflux = np.atleast_1d(zflux)\n\n    # ADM only use the g-band color shift when r and g are non-zero\n    gshift = gflux * 10**(-0.4*0.004)\n    w = np.where((gflux != 0) & (rflux != 0))\n    gshift[w] = (gflux[w] * 10**(-0.4*0.004) * (gflux[w]/rflux[w])**complex(-0.059)).real\n\n    # ADM only use the r-band color shift when r and z are non-zero\n    # ADM and only use the z-band color shift when r and z are non-zero\n    w = np.where((rflux != 0) & (zflux != 0))\n    rshift = rflux * 10**(0.4*0.003)\n    zshift = zflux * 10**(0.4*0.013)\n\n    rshift[w] = (rflux[w] * 10**(0.4*0.003) * (rflux[w]/zflux[w])**complex(-0.024)).real\n    zshift[w] = (zflux[w] * 10**(0.4*0.013) * (rflux[w]/zflux[w])**complex(+0.015)).real\n\n    if flt:\n        return gshift[0], rshift[0], zshift[0]\n\n    return gshift, rshift, zshift\n\n\ndef isLRG(gflux=None, rflux=None, zflux=None, w1flux=None, w2flux=None,\n          zfiberflux=None, rfluxivar=None, zfluxivar=None, w1fluxivar=None,\n          gnobs=None, rnobs=None, znobs=None, maskbits=None, primary=None,\n          south=True):\n    \"\"\"\n    Parameters\n    ----------\n    south: boolean, defaults to ``True``\n        Use cuts appropriate to the Northern imaging surveys (BASS/MzLS)\n        if ``south=False``, otherwise use cuts appropriate to the\n        Southern imaging survey (DECaLS).\n\n    Returns\n    -------\n    :class:`array_like`\n        ``True`` if and only if the object is an LRG target.\n\n    Notes\n    -----\n    - Current version (12/07/2020) is version 232 on `the wiki`_.\n    - See :func:`~desitarget.cuts.set_target_bits` for other parameters.\n    \"\"\"\n    # ADM LRG targets.\n    if primary is None:\n        primary = np.ones_like(rflux, dtype='?')\n    lrg = primary.copy()\n\n    # ADM basic quality cuts.\n    lrg &= notinLRG_mask(\n        primary=primary, rflux=rflux, zflux=zflux, w1flux=w1flux,\n        zfiberflux=zfiberflux, gnobs=gnobs, rnobs=rnobs, znobs=znobs,\n        rfluxivar=rfluxivar, zfluxivar=zfluxivar, w1fluxivar=w1fluxivar,\n        maskbits=maskbits\n    )\n\n    # ADM color-based selection of LRGs.\n    lrg &= isLRG_colors(\n        gflux=gflux, rflux=rflux, zflux=zflux, w1flux=w1flux,\n        zfiberflux=zfiberflux, south=south, primary=primary\n    )\n\n    return lrg\n\n\ndef notinLRG_mask(primary=None, rflux=None, zflux=None, w1flux=None,\n                  zfiberflux=None, gnobs=None, rnobs=None, znobs=None,\n                  rfluxivar=None, zfluxivar=None, w1fluxivar=None,\n                  maskbits=None):\n    \"\"\"See :func:`~desitarget.cuts.isLRG` for details.\n\n    Returns\n    -------\n    :class:`array_like`\n        ``True`` if and only if the object is NOT masked for poor quality.\n    \"\"\"\n    if primary is None:\n        primary = np.ones_like(rflux, dtype='?')\n    lrg = primary.copy()\n\n    # ADM to maintain backwards-compatibility with mocks.\n    if zfiberflux is None:\n        log.warning('Setting zfiberflux to zflux!!!')\n        zfiberflux = zflux.copy()\n\n    lrg &= (rfluxivar > 0) & (rflux > 0)   # ADM quality in r.\n    lrg &= (zfluxivar > 0) & (zflux > 0) & (zfiberflux > 0)   # ADM quality in z.\n    lrg &= (w1fluxivar > 0) & (w1flux > 0)  # ADM quality in W1.\n\n    # ADM observed in every band.\n    lrg &= (gnobs > 0) & (rnobs > 0) & (znobs > 0)\n\n    # ADM default mask bits from the Legacy Surveys not set.\n    lrg &= imaging_mask(maskbits)\n\n    return lrg\n\n\ndef isLRG_colors(gflux=None, rflux=None, zflux=None, w1flux=None,\n                 zfiberflux=None, ggood=None,\n                 w2flux=None, primary=None, south=True):\n    \"\"\"(see, e.g., :func:`~desitarget.cuts.isLRG`).\n\n    Notes:\n        - the `ggood` and `w2flux` inputs are an attempt to maintain\n          backwards-compatibility with the mocks.\n    \"\"\"\n    if primary is None:\n        primary = np.ones_like(rflux, dtype='?')\n    lrg = primary.copy()\n\n    # ADM to maintain backwards-compatibility with mocks.\n    if zfiberflux is None:\n        log.warning('Setting zfiberflux to zflux!!!')\n        zfiberflux = zflux.copy()\n\n    gmag = 22.5 - 2.5 * np.log10(gflux.clip(1e-7))\n    # ADM safe as these fluxes are set to > 0 in notinLRG_mask.\n    rmag = 22.5 - 2.5 * np.log10(rflux.clip(1e-7))\n    zmag = 22.5 - 2.5 * np.log10(zflux.clip(1e-7))\n    w1mag = 22.5 - 2.5 * np.log10(w1flux.clip(1e-7))\n    zfibermag = 22.5 - 2.5 * np.log10(zfiberflux.clip(1e-7))\n\n    if south:\n        lrg &= zmag - w1mag > 0.8 * (rmag-zmag) - 0.6    # non-stellar cut.\n        lrg &= (\n            ((gmag - w1mag > 2.6) & (gmag - rmag > 1.4))\n            | (rmag - w1mag > 1.8)                       # low-z cut.\n        )\n        lrg &= rmag - zmag > (zmag - 16.83) * 0.45       # double sliding cut 1.\n        lrg &= rmag - zmag > (zmag - 13.80) * 0.19       # double sliding cut 2.\n    else:\n        lrg &= zmag - w1mag > 0.8 * (rmag-zmag) - 0.6   # non-stellar cut.\n        lrg &= (\n            ((gmag - w1mag > 2.67) & (gmag - rmag > 1.45))\n            | (rmag - w1mag > 1.85)                      # low-z cut.\n        )\n        lrg &= rmag - zmag > (zmag - 16.79) * 0.45       # double sliding cut 1.\n        lrg &= rmag - zmag > (zmag - 13.76) * 0.19       # double sliding cut 2.\n\n    lrg &= zfibermag < 21.5    # faint limit.\n\n    return lrg\n\n\ndef isELG(gflux=None, rflux=None, zflux=None, w1flux=None, w2flux=None,\n          gsnr=None, rsnr=None, zsnr=None, gnobs=None, rnobs=None, znobs=None,\n          maskbits=None, south=True, primary=None):\n    \"\"\"Definition of ELG target classes. Returns a boolean array.\n    (see :func:`~desitarget.cuts.set_target_bits` for parameters).\n\n    Notes:\n    - Current version (12/09/20) is version 233 on `the wiki`_.\n    \"\"\"\n    if primary is None:\n        primary = np.ones_like(rflux, dtype='?')\n    elg = primary.copy()\n\n    elg &= notinELG_mask(maskbits=maskbits, gsnr=gsnr, rsnr=rsnr, zsnr=zsnr,\n                         gnobs=gnobs, rnobs=rnobs, znobs=znobs, primary=primary)\n\n    elg &= isELG_colors(gflux=gflux, rflux=rflux, zflux=zflux, w1flux=w1flux,\n                        w2flux=w2flux, south=south, primary=primary)\n\n    return elg\n\n\ndef notinELG_mask(maskbits=None, gsnr=None, rsnr=None, zsnr=None,\n                  gnobs=None, rnobs=None, znobs=None, primary=None):\n    \"\"\"Standard set of masking cuts used by all ELG target selection classes.\n    (see :func:`~desitarget.cuts.set_target_bits` for parameters).\n    \"\"\"\n    if primary is None:\n        primary = np.ones_like(maskbits, dtype='?')\n    elg = primary.copy()\n\n    # ADM good signal-to-noise in all bands.\n    elg &= (gsnr > 0) & (rsnr > 0) & (zsnr > 0)\n\n    # ADM observed in every band.\n    elg &= (gnobs > 0) & (rnobs > 0) & (znobs > 0)\n\n    # ADM default mask bits from the Legacy Surveys not set.\n    elg &= imaging_mask(maskbits)\n\n    return elg\n\n\ndef isELG_colors(gflux=None, rflux=None, zflux=None, w1flux=None,\n                 w2flux=None, south=True, primary=None):\n    \"\"\"Color cuts for ELG target selection classes\n    (see, e.g., :func:`~desitarget.cuts.set_target_bits` for parameters).\n    \"\"\"\n    if primary is None:\n        primary = np.ones_like(rflux, dtype='?')\n    elg = primary.copy()\n\n    # ADM work in magnitudes instead of fluxes. NOTE THIS IS ONLY OK AS\n    # ADM the snr masking in ALL OF g, r AND z ENSURES positive fluxes.\n    g = 22.5 - 2.5*np.log10(gflux.clip(1e-16))\n    r = 22.5 - 2.5*np.log10(rflux.clip(1e-16))\n    z = 22.5 - 2.5*np.log10(zflux.clip(1e-16))\n\n    # ADM cuts shared by the northern and southern selections.\n    elg &= g > 20                       # bright cut.\n    elg &= r - z > 0.3                  # blue cut.\n    elg &= r - z < 1.6                  # red cut.\n    elg &= g - r < -1.2*(r - z) + 1.6   # OII flux cut.\n\n    # ADM cuts that are unique to the north or south.\n    if south:\n        elg &= g < 23.4  # faint cut.\n        # ADM south has the FDR cut to remove stars and low-z galaxies.\n        elg &= g - r < 1.15*(r - z) - 0.15\n    else:\n        elg &= g < 23.5  # faint cut.\n        elg &= g - r < 1.15*(r - z) - 0.20  # remove stars and low-z galaxies.\n\n    return elg\n\n\ndef _check_BGS_targtype(targtype):\n    \"\"\"Fail if `targtype` is not one of the strings 'bright', 'faint' or 'wise'.\n    \"\"\"\n    targposs = ['faint', 'bright', 'wise']\n\n    if targtype not in targposs:\n        msg = 'targtype must be one of {} not {}'.format(targposs, targtype)\n        log.critical(msg)\n        raise ValueError(msg)\n\n\ndef isBGS(rfiberflux=None, gflux=None, rflux=None, zflux=None, w1flux=None, w2flux=None,\n          gnobs=None, rnobs=None, znobs=None, gfracmasked=None, rfracmasked=None, zfracmasked=None,\n          gfracflux=None, rfracflux=None, zfracflux=None, gfracin=None, rfracin=None, zfracin=None,\n          gfluxivar=None, rfluxivar=None, zfluxivar=None, maskbits=None, Grr=None, refcat=None,\n          w1snr=None, gaiagmag=None, objtype=None, primary=None, south=True, targtype=None):\n    \"\"\"Definition of BGS target classes. Returns a boolean array.\n\n    Args\n    ----\n    targtype: str, optional, defaults to ``faint``\n        Pass ``bright`` to use colors appropriate to the ``BGS_BRIGHT`` selection\n        or ``faint`` to use colors appropriate to the ``BGS_FAINT`` selection\n        or ``wise`` to use colors appropriate to the ``BGS_WISE`` selection.\n\n    Returns\n    -------\n    :class:`array_like`\n        ``True`` if and only if the object is a BGS target of type ``targtype``.\n\n    Notes\n    -----\n    - Current version (10/24/18) is version 143 on `the wiki`_.\n    - See :func:`~desitarget.cuts.set_target_bits` for other parameters.\n    \"\"\"\n    _check_BGS_targtype(targtype)\n\n    # ------ Bright Galaxy Survey\n    if primary is None:\n        primary = np.ones_like(rflux, dtype='?')\n    bgs = primary.copy()\n\n    bgs &= notinBGS_mask(gnobs=gnobs, rnobs=rnobs, znobs=znobs, primary=primary,\n                         gfracmasked=gfracmasked, rfracmasked=rfracmasked, zfracmasked=zfracmasked,\n                         gfracflux=gfracflux, rfracflux=rfracflux, zfracflux=zfracflux,\n                         gfracin=gfracin, rfracin=rfracin, zfracin=zfracin, w1snr=w1snr,\n                         gfluxivar=gfluxivar, rfluxivar=rfluxivar, zfluxivar=zfluxivar, Grr=Grr,\n                         gaiagmag=gaiagmag, maskbits=maskbits, targtype=targtype)\n\n    bgs &= isBGS_colors(rfiberflux=rfiberflux, gflux=gflux, rflux=rflux, zflux=zflux, w1flux=w1flux,\n                        w2flux=w2flux, south=south, targtype=targtype, primary=primary)\n\n    bgs |= isBGS_lslga(gflux=gflux, rflux=rflux, zflux=zflux, w1flux=w1flux, refcat=refcat,\n                       maskbits=maskbits, south=south, targtype=targtype)\n\n    return bgs\n\n\ndef notinBGS_mask(gnobs=None, rnobs=None, znobs=None, primary=None,\n                  gfracmasked=None, rfracmasked=None, zfracmasked=None,\n                  gfracflux=None, rfracflux=None, zfracflux=None,\n                  gfracin=None, rfracin=None, zfracin=None, w1snr=None,\n                  gfluxivar=None, rfluxivar=None, zfluxivar=None, Grr=None,\n                  gaiagmag=None, maskbits=None, targtype=None):\n    \"\"\"Standard set of masking cuts used by all BGS target selection classes\n    (see, e.g., :func:`~desitarget.cuts.isBGS` for parameters).\n    \"\"\"\n    _check_BGS_targtype(targtype)\n\n    if primary is None:\n        primary = np.ones_like(gnobs, dtype='?')\n    bgs = primary.copy()\n\n    bgs &= (gnobs >= 1) & (rnobs >= 1) & (znobs >= 1)\n    bgs &= (gfracmasked < 0.4) & (rfracmasked < 0.4) & (zfracmasked < 0.4)\n    bgs &= (gfracflux < 5.0) & (rfracflux < 5.0) & (zfracflux < 5.0)\n    bgs &= (gfracin > 0.3) & (rfracin > 0.3) & (zfracin > 0.3)\n    bgs &= (gfluxivar > 0) & (rfluxivar > 0) & (zfluxivar > 0)\n\n    # ADM geometric masking cuts from the Legacy Surveys.\n    bgs &= imaging_mask(maskbits)\n\n    if targtype == 'bright':\n        bgs &= ((Grr > 0.6) | (gaiagmag == 0))\n    elif targtype == 'faint':\n        bgs &= ((Grr > 0.6) | (gaiagmag == 0))\n    elif targtype == 'wise':\n        bgs &= Grr < 0.4\n        bgs &= Grr > -1\n        bgs &= w1snr > 5\n\n    return bgs\n\n\ndef isBGS_colors(rfiberflux=None, gflux=None, rflux=None, zflux=None, w1flux=None,\n                 w2flux=None, south=True, targtype=None, primary=None):\n    \"\"\"Standard set of color-based cuts used by all BGS target selection classes\n    (see, e.g., :func:`~desitarget.cuts.isBGS` for parameters).\n    \"\"\"\n    _check_BGS_targtype(targtype)\n\n    # ADM to maintain backwards-compatibility with mocks.\n    if rfiberflux is None:\n        log.warning('Setting rfiberflux to rflux!!!')\n        rfiberflux = rflux.copy()\n\n    if primary is None:\n        primary = np.ones_like(rflux, dtype='?')\n    bgs = primary.copy()\n    fmc = np.zeros_like(rflux, dtype='?')\n\n    if south:\n        bgs &= rflux > gflux * 10**(-1.0/2.5)\n        bgs &= rflux < gflux * 10**(4.0/2.5)\n        bgs &= zflux > rflux * 10**(-1.0/2.5)\n        bgs &= zflux < rflux * 10**(4.0/2.5)\n    else:\n        bgs &= rflux > gflux * 10**(-1.0/2.5)\n        bgs &= rflux < gflux * 10**(4.0/2.5)\n        bgs &= zflux > rflux * 10**(-1.0/2.5)\n        bgs &= zflux < rflux * 10**(4.0/2.5)\n\n    g = 22.5 - 2.5*np.log10(gflux.clip(1e-16))\n    r = 22.5 - 2.5*np.log10(rflux.clip(1e-16))\n    z = 22.5 - 2.5*np.log10(zflux.clip(1e-16))\n    rfib = 22.5 - 2.5*np.log10(rfiberflux.clip(1e-16))\n\n    # Fibre Magnitude Cut (FMC) -- This is a low surface brightness cut\n    # with the aim of increase the redshift success rate.\n    fmc |= ((rfib < (2.9 + 1.2 + 1.0) + r) & (r < 17.8))\n    fmc |= ((rfib < 22.9) & (r < 20.0) & (r > 17.8))\n    fmc |= ((rfib < 2.9 + r) & (r > 20))\n\n    bgs &= fmc\n\n    if targtype == 'bright':\n        bgs &= rflux > 10**((22.5-19.5)/2.5)\n    elif targtype == 'faint':\n        bgs &= rflux > 10**((22.5-20.0)/2.5)\n        bgs &= rflux <= 10**((22.5-19.5)/2.5)\n    elif targtype == 'wise':\n        bgs &= rflux > 10**((22.5-20.0)/2.5)\n        bgs &= w1flux*gflux > (zflux*rflux)*10**(-0.2)\n\n    return bgs\n\n\ndef isBGS_lslga(gflux=None, rflux=None, zflux=None, w1flux=None, refcat=None,\n                maskbits=None, south=True, targtype=None):\n    \"\"\"Module to recover the LSLGA objects in all BGS target selection classes\n    (see, e.g., :func:`~desitarget.cuts.isBGS` for parameters).\n    \"\"\"\n    _check_BGS_targtype(targtype)\n\n    bgs = np.zeros_like(rflux, dtype='?')\n\n    # the LSLGA galaxies.\n    LX = bgs.copy()\n    # ADM Could check on \"L2\" for DR8, need to check on \"LX\" post-DR8.\n    if refcat is not None:\n        rc1d = np.atleast_1d(refcat)\n        if isinstance(rc1d[0], str):\n            LX = [(rc[0] == \"L\") if len(rc) > 0 else False for rc in rc1d]\n        else:\n            LX = [(rc.decode()[0] == \"L\") if len(rc) > 0 else False for rc in rc1d]\n        if np.ndim(refcat) == 0:\n            LX = np.array(LX[0], dtype=bool)\n        else:\n            LX = np.array(LX, dtype=bool)\n\n    bgs |= LX\n    # ADM geometric masking cuts from the Legacy Surveys.\n    bgs &= imaging_mask(maskbits, bgsmask=True)\n\n    if targtype == 'bright':\n        bgs &= rflux > 10**((22.5-19.5)/2.5)\n    elif targtype == 'faint':\n        bgs &= rflux > 10**((22.5-20.0)/2.5)\n        bgs &= rflux <= 10**((22.5-19.5)/2.5)\n    elif targtype == 'wise':\n        bgs &= rflux > 10**((22.5-20.0)/2.5)\n        bgs &= w1flux*gflux > (zflux*rflux)*10**(-0.2)\n\n    return bgs\n\n\ndef isQSO_randomforest(gflux=None, rflux=None, zflux=None, maskbits=None,\n                       w1flux=None, w2flux=None, objtype=None, release=None,\n                       gnobs=None, rnobs=None, znobs=None, deltaChi2=None,\n                       primary=None, ra=None, dec=None, south=True, return_probs=False):\n    \"\"\"Define QSO targets from a Random Forest. Returns a boolean array.\n\n    Parameters\n    ----------\n    south : :class:`boolean`, defaults to ``True``\n        If ``False``, shift photometry to the Northern (BASS/MzLS)\n        imaging system.\n    return_probs : :class:`boolean`, defaults to ``False``\n        If ``True``, return the QSO/high-z QSO probabilities in addition\n        to the QSO target booleans. Only coded up for DR8 or later of the\n        Legacy Surveys. Will return arrays of zeros for earlier DRs.\n\n    Returns\n    -------\n    :class:`array_like`\n        ``True`` for objects that are Random Forest quasar targets.\n    :class:`array_like`\n        ``True`` for objects that are high-z RF quasar targets.\n    :class:`array_like`\n        The (float) probability that a target is a quasar. Only returned\n        if `return_probs` is ``True``.\n    :class:`array_like`\n        The (float) probability that a target is a high-z quasar. Only\n        returned if `return_probs` is ``True``.\n\n    Notes\n    -----\n    - Current version (20/11/20) is version 173 on `the wiki`_.\n    - See :func:`~desitarget.cuts.set_target_bits` for other parameters.\n    \"\"\"\n    # ADM Primary (True for anything to initially consider as a possible target).\n    if primary is None:\n        primary = np.ones_like(gflux, dtype=bool)\n\n    # RELEASE\n    # ADM default to RELEASE of 5000 if nothing is passed.\n    if release is None:\n        release = np.zeros_like(gflux, dtype='?') + 5000\n    release = np.atleast_1d(release)\n\n    # Build variables for random forest\n    nFeatures = 11   # Number of attributes describing each object to be classified by the rf\n    nbEntries = rflux.size\n    if not south:\n        gflux, rflux, zflux = shift_photo_north(gflux, rflux, zflux)\n\n    colors, r, photOK = _getColors(nbEntries, nFeatures, gflux, rflux, zflux, w1flux, w2flux)\n    r = np.atleast_1d(r)\n\n    # Preselection to speed up the process\n    rMax = 22.7   # r < 22.7\n    rMin = 17.5   # r > 17.5\n    preSelection = (r < rMax) & (r > rMin) & photOK & primary\n\n    # ADM targets have to be observed in every band.\n    preSelection &= (gnobs > 0) & (rnobs > 0) & (znobs > 0)\n\n    if objtype is not None:\n        preSelection &= _psflike(objtype)\n    if deltaChi2 is not None:\n        deltaChi2 = np.atleast_1d(deltaChi2)\n        preSelection[release < 5000] &= deltaChi2[release < 5000] > 30.\n    # ADM Reject objects in masks.\n    # ADM BRIGHT BAILOUT GALAXY CLUSTER (1, 10, 12, 13) bits not set.\n    # ALLMASK_G\t| ALLMASK_R | ALLMASK_Z (5, 6, 7) bits not set.\n    # Now only 1, 12, 13\n    if maskbits is not None:\n        # ADM default mask bits from the Legacy Surveys not set.\n        preSelection &= imaging_mask(maskbits)\n\n    # \"qso\" mask initialized to \"preSelection\" mask.\n    qso = np.copy(preSelection)\n    # ADM to specifically store the selection from the \"HighZ\" RF.\n    qsohiz = np.copy(preSelection)\n\n    # ADM these store the probabilities, should they need returned.\n    pqso = np.zeros_like(qso, dtype='>f4')\n    pqsohiz = np.zeros_like(qso, dtype='>f4')\n\n    if np.any(preSelection):\n\n        from desitarget.myRF import myRF\n\n        # Data reduction to preselected objects\n        colorsReduced = colors[preSelection]\n        releaseReduced = release[preSelection]\n        r_Reduced = r[preSelection]\n        colorsIndex = np.arange(0, nbEntries, dtype=np.int64)\n        colorsReducedIndex = colorsIndex[preSelection]\n\n        # Path to random forest files\n        pathToRF = resource_filename('desitarget', 'data')\n        # rf filenames\n        rf_DR3_fileName = pathToRF + '/rf_model_dr3.npz'\n        rf_DR7_fileName = pathToRF + '/rf_model_dr7.npz'\n        rf_DR7_HighZ_fileName = pathToRF + '/rf_model_dr7_HighZ.npz'\n        rf_DR8_fileName = pathToRF + '/rf_model_dr8.npz'\n        rf_DR8_HighZ_fileName = pathToRF + '/rf_model_dr8_HighZ.npz'\n        rf_DR9_fileName = pathToRF + '/rf_model_dr9.npz'\n        rf_DR9_HighZ_fileName = pathToRF + '/rf_model_dr9_HighZ.npz'\n\n        tmpReleaseOK = releaseReduced < 5000\n        if np.any(tmpReleaseOK):\n            # rf initialization - colors data duplicated within \"myRF\"\n            rf_DR3 = myRF(colorsReduced[tmpReleaseOK], pathToRF,\n                          numberOfTrees=200, version=1)\n            # rf loading\n            rf_DR3.loadForest(rf_DR3_fileName)\n            # Compute rf probabilities\n            tmp_rf_proba = rf_DR3.predict_proba()\n            tmp_r_Reduced = r_Reduced[tmpReleaseOK]\n            # Compute optimized proba cut\n            pcut = np.where(tmp_r_Reduced > 20.0,\n                            0.95 - (tmp_r_Reduced - 20.0) * 0.08, 0.95)\n            # Add rf proba test result to \"qso\" mask\n            qso[colorsReducedIndex[tmpReleaseOK]] = tmp_rf_proba >= pcut\n            # ADM no high-z selection for DR3.\n            qsohiz &= False\n\n        tmpReleaseOK = (releaseReduced >= 5000) & (releaseReduced < 8000)\n        if np.any(tmpReleaseOK):\n            # rf initialization - colors data duplicated within \"myRF\"\n            rf = myRF(colorsReduced[tmpReleaseOK], pathToRF,\n                      numberOfTrees=500, version=2)\n            rf_HighZ = myRF(colorsReduced[tmpReleaseOK], pathToRF,\n                            numberOfTrees=500, version=2)\n            # rf loading\n            rf.loadForest(rf_DR7_fileName)\n            rf_HighZ.loadForest(rf_DR7_HighZ_fileName)\n            # Compute rf probabilities\n            tmp_rf_proba = rf.predict_proba()\n            tmp_rf_HighZ_proba = rf_HighZ.predict_proba()\n            # Compute optimized proba cut\n            tmp_r_Reduced = r_Reduced[tmpReleaseOK]\n            pcut = np.where(tmp_r_Reduced > 20.8,\n                            0.83 - (tmp_r_Reduced - 20.8) * 0.025, 0.83)\n            pcut[tmp_r_Reduced > 21.5] = 0.8125 - 0.15 * (tmp_r_Reduced[tmp_r_Reduced > 21.5] - 21.5)\n            pcut[tmp_r_Reduced > 22.3] = 0.6925 - 0.70 * (tmp_r_Reduced[tmp_r_Reduced > 22.3] - 22.3)\n            pcut_HighZ = np.where(tmp_r_Reduced > 20.5,\n                                  0.55 - (tmp_r_Reduced - 20.5) * 0.025, 0.55)\n\n            # Add rf proba test result to \"qso\" mask\n            qso[colorsReducedIndex[tmpReleaseOK]] = \\\n                (tmp_rf_proba >= pcut) | (tmp_rf_HighZ_proba >= pcut_HighZ)\n            # ADM populate a mask specific to the \"HighZ\" selection.\n            qsohiz[colorsReducedIndex[tmpReleaseOK]] = \\\n                (tmp_rf_HighZ_proba >= pcut_HighZ)\n\n        tmpReleaseOK = (releaseReduced >= 8000) & (releaseReduced < 9000)\n        if np.any(tmpReleaseOK):\n            # rf initialization - colors data duplicated within \"myRF\"\n            rf = myRF(colorsReduced[tmpReleaseOK], pathToRF,\n                      numberOfTrees=500, version=2)\n            rf_HighZ = myRF(colorsReduced[tmpReleaseOK], pathToRF,\n                            numberOfTrees=500, version=2)\n            # rf loading\n            rf.loadForest(rf_DR8_fileName)\n            rf_HighZ.loadForest(rf_DR8_HighZ_fileName)\n            # Compute rf probabilities\n            tmp_rf_proba = rf.predict_proba()\n            tmp_rf_HighZ_proba = rf_HighZ.predict_proba()\n            # Compute optimized proba cut\n            tmp_r_Reduced = r_Reduced[tmpReleaseOK]\n            pcut = 0.88 - 0.03*np.tanh(tmp_r_Reduced - 20.5)\n            pcut_HighZ = 0.55\n\n            # Add rf proba test result to \"qso\" mask\n            qso[colorsReducedIndex[tmpReleaseOK]] = \\\n                (tmp_rf_proba >= pcut) | (tmp_rf_HighZ_proba >= pcut_HighZ)\n            # ADM populate a mask specific to the \"HighZ\" selection.\n            qsohiz[colorsReducedIndex[tmpReleaseOK]] = \\\n                (tmp_rf_HighZ_proba >= pcut_HighZ)\n            # ADM store the probabilities in case they need returned.\n            pqso[colorsReducedIndex[tmpReleaseOK]] = tmp_rf_proba\n            # ADM populate a mask specific to the \"HighZ\" selection.\n            pqsohiz[colorsReducedIndex[tmpReleaseOK]] = tmp_rf_HighZ_proba\n\n        tmpReleaseOK = releaseReduced >= 9000\n        if np.any(tmpReleaseOK):\n            # rf initialization - colors data duplicated within \"myRF\"\n            rf = myRF(colorsReduced[tmpReleaseOK], pathToRF,\n                      numberOfTrees=500, version=2)\n            rf_HighZ = myRF(colorsReduced[tmpReleaseOK], pathToRF,\n                            numberOfTrees=500, version=2)\n            # rf loading\n            rf.loadForest(rf_DR9_fileName)\n            rf_HighZ.loadForest(rf_DR9_HighZ_fileName)\n            # Compute rf probabilities\n            tmp_rf_proba = rf.predict_proba()\n            tmp_rf_HighZ_proba = rf_HighZ.predict_proba()\n            # Compute optimized proba cut\n            tmp_r_Reduced = r_Reduced[tmpReleaseOK]\n            if not south:\n                # threshold selection for North footprint.\n                pcut = 0.857 - 0.03*np.tanh(tmp_r_Reduced - 20.5)\n                pcut_HighZ = 0.7\n            else:\n                pcut = np.ones(tmp_rf_proba.size)\n                pcut_HighZ = np.ones(tmp_rf_HighZ_proba.size)\n                is_des = (gnobs[preSelection][tmpReleaseOK] > 4) &\\\n                         (rnobs[preSelection][tmpReleaseOK] > 4) &\\\n                         (znobs[preSelection][tmpReleaseOK] > 4) &\\\n                         ((ra[preSelection][tmpReleaseOK] >= 320) | (ra[preSelection][tmpReleaseOK] <= 100)) &\\\n                         (dec[preSelection][tmpReleaseOK] <= 10)\n                # threshold selection for DES footprint.\n                pcut[is_des] = 0.75 - 0.05*np.tanh(tmp_r_Reduced[is_des] - 20.5)\n                pcut_HighZ[is_des] = 0.50\n                # threshold selection for South footprint.\n                pcut[~is_des] = 0.85 - 0.04*np.tanh(tmp_r_Reduced[~is_des] - 20.5)\n                pcut_HighZ[~is_des] = 0.65\n\n            # Add rf proba test result to \"qso\" mask\n            qso[colorsReducedIndex[tmpReleaseOK]] = \\\n                (tmp_rf_proba >= pcut) | (tmp_rf_HighZ_proba >= pcut_HighZ)\n            # ADM populate a mask specific to the \"HighZ\" selection.\n            qsohiz[colorsReducedIndex[tmpReleaseOK]] = \\\n                (tmp_rf_HighZ_proba >= pcut_HighZ)\n            # ADM store the probabilities in case they need returned.\n            pqso[colorsReducedIndex[tmpReleaseOK]] = tmp_rf_proba\n            # ADM populate a mask specific to the \"HighZ\" selection.\n            pqsohiz[colorsReducedIndex[tmpReleaseOK]] = tmp_rf_HighZ_proba\n\n    # In case of call for a single object passed to the function with\n    # scalar arguments. Return \"numpy.bool_\" instead of \"~numpy.ndarray\".\n    if nbEntries == 1:\n        qso = qso[0]\n        qsohiz = qsohiz[0]\n        pqso = pqso[0]\n        pqsohiz = pqsohiz[0]\n\n    # ADM if requested, return the probabilities as well.\n    if return_probs:\n        return qso, qsohiz, pqso, pqsohiz\n    return qso, qsohiz\n\n\ndef _psflike(psftype):\n    \"\"\" If the object is PSF \"\"\"\n    # ADM explicitly checking for NoneType. I can't see why we'd ever want to\n    # ADM run this test on empty information. In the past we have had bugs where\n    # ADM we forgot to pass objtype=objtype in, e.g., isSTD\n    if psftype is None:\n        raise ValueError(\"NoneType submitted to _psfflike function\")\n\n    psftype = np.asarray(psftype)\n    # ADM in Python3 these string literals become byte-like\n    # ADM so to retain Python2 compatibility we need to check\n    # ADM against both bytes and unicode\n    # ADM, also 'PSF' for astropy.io.fits; 'PSF ' for fitsio (sigh)\n    psflike = ((psftype == 'PSF') | (psftype == b'PSF') |\n               (psftype == 'PSF ') | (psftype == b'PSF '))\n    return psflike\n\n\ndef _getColors(nbEntries, nfeatures, gflux, rflux, zflux, w1flux, w2flux):\n\n    limitInf = 1.e-04\n    gflux = gflux.clip(limitInf)\n    rflux = rflux.clip(limitInf)\n    zflux = zflux.clip(limitInf)\n    w1flux = w1flux.clip(limitInf)\n    w2flux = w2flux.clip(limitInf)\n\n    g = np.where(gflux > limitInf, 22.5-2.5*np.log10(gflux), 0.)\n    r = np.where(rflux > limitInf, 22.5-2.5*np.log10(rflux), 0.)\n    z = np.where(zflux > limitInf, 22.5-2.5*np.log10(zflux), 0.)\n    W1 = np.where(w1flux > limitInf, 22.5-2.5*np.log10(w1flux), 0.)\n    W2 = np.where(w2flux > limitInf, 22.5-2.5*np.log10(w2flux), 0.)\n\n    photOK = (g > 0.) & (r > 0.) & (z > 0.) & (W1 > 0.) & (W2 > 0.)\n\n    colors = np.zeros((nbEntries, nfeatures))\n    colors[:, 0] = g-r\n    colors[:, 1] = r-z\n    colors[:, 2] = g-z\n    colors[:, 3] = g-W1\n    colors[:, 4] = r-W1\n    colors[:, 5] = z-W1\n    colors[:, 6] = g-W2\n    colors[:, 7] = r-W2\n    colors[:, 8] = z-W2\n    colors[:, 9] = W1-W2\n    colors[:, 10] = r\n\n    return colors, r, photOK\n\n\ndef _is_row(table):\n    \"\"\"Return True/False if this is a row of a table instead of a full table.\n\n    supports numpy.ndarray, astropy.io.fits.FITS_rec, and astropy.table.Table\n    \"\"\"\n    import astropy.io.fits.fitsrec\n    import astropy.table.row\n    if isinstance(table, (astropy.io.fits.fitsrec.FITS_record, astropy.table.row.Row)) or \\\n       np.isscalar(table):\n        return True\n    else:\n        return False\n", "meta": {"hexsha": "bb1f77aa8f218b5480759eb63b5be30a8c4392df", "size": 30030, "ext": "py", "lang": "Python", "max_stars_repo_path": "py/desitarget/cmx/ms_cuts.py", "max_stars_repo_name": "echaussidon/desitarget", "max_stars_repo_head_hexsha": "1206380dac5155b9e7bf238c7cb187bc797d78a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2016-02-02T00:26:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T07:31:59.000Z", "max_issues_repo_path": "py/desitarget/cmx/ms_cuts.py", "max_issues_repo_name": "echaussidon/desitarget", "max_issues_repo_head_hexsha": "1206380dac5155b9e7bf238c7cb187bc797d78a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 674, "max_issues_repo_issues_event_min_datetime": "2015-09-15T15:02:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-23T18:39:02.000Z", "max_forks_repo_path": "py/desitarget/cmx/ms_cuts.py", "max_forks_repo_name": "echaussidon/desitarget", "max_forks_repo_head_hexsha": "1206380dac5155b9e7bf238c7cb187bc797d78a3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2015-06-09T13:51:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T06:03:18.000Z", "avg_line_length": 39.7222222222, "max_line_length": 150, "alphanum_fraction": 0.5996669997, "include": true, "reason": "import numpy,import astropy", "num_tokens": 9225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.16087744375687976}}
{"text": "u\"\"\"\nEnable the NASA 9 term polynomials to create chemical compound objects.\n\nThis module allows the user to use the NASA9 term polynomials (abbreviated as\nNASA 9) to model chemical compounds and reactions. It is worth noting that all\nthe output is stripped of any phyisical unit, that is, results are returned as\nnumpy floats. *Therefore to end any form of ambiguity we reinstate that all the\nresults are in SI units using molar basis*. It is up to the user to beware of\nany physical unit conversion concerning his problem.\n\nClasses:\n\n    Compound: chemical compound present in the NASA9 term polynomials\n    database.\n\n    CompoundIdealGas: chemical compound as an ideal gas present in the NASA9\n    term polynomials database. It inherits from Compound.\n\n    Reaction: model of a chemical reaction.\n\nExample:\n    >>> import thermopy\n    >>> from thermopy import nasa9polynomials as nasa9\n    >>> db = nasa9.Database()\n    >>> caf2 = db.set_compound('caf2')\n    >>> print(caf2.elements)\n    [('C', 1), ('F', 2)]\n    >>> print(caf2.inchikey)\n    WUKWITHWXAAZEY-UHFFFAOYSA-L\n    >>> print(caf2.enthalpy_of_formation)\n    -790828.409\n    >>> print(caf2.heat_capacity(300))\n    51.2707324499\n    >>> print(caf2.molecular_weight)\n    0.0780748064\n    >>> water = db.set_compound('h2o(l)')\n    >>> print(water.entropy(300))\n    69.633703\n    >>> print(water.elements)\n    [('H', 2), ('O', 1)]\n\nReferences: [1] Bonnie J. McBride, Michael J. Zehe, and Sanford Gordon. NASA\nGlenn Coefficients for Calculating Thermodynamic Properties of Individual\nSpecies. September 2002.\n\n\"\"\"\n\nimport os\nimport re\nimport xml.etree.ElementTree as ET\nimport numpy as np\nfrom thermopy.constants import ideal_gas_constant\n_R = ideal_gas_constant[0]\n\nDATADIR = '/usr/share/thermopy'\n\n\nclass Compound(object):\n    u\"\"\"\n    Chemical compound present in the NASA9 term polynomials database.\n\n    It is usually set by nasa9polyniomials.Database.set_compound('identifier').\n    If set this way this method already instantiates either a Compound or a\n    CompoundIdealGas based on the phase of the chemical compound specified by\n    the identifier (see note below).\n\n    Note: *The default phase for compounds in this database is gas.* Thus if\n    instantiating with the name 'H2O' one would get steam. For liquid water and\n    ice one would rather look for 'H2O(L)' or 'H2O(cr)'. The same is valid for\n    a lot of compounds expected to be in the condensed form (such as NaCl,\n    Tungsten, etc).\n\n    It has all the thermodynamic functions listed in [1] as methods which take\n    temperature as their sole argument. Those were expanded to include\n    gibbs_energy that could be defined by the given functions.\n\n    Attributes:\n        canonical_smiles (str): Canonical SMILES\n            (Simplified molecular-input line-entry system) of the compound.\n        cas_number (str): CAS (Chemical Abstract Service) number of the\n            compound.\n        comment (str): Comment found in the xml database. Usually references.\n        condensed (bool): True if the compound is condensed, False if not.\n        xml_compounds (list): List containing tuples of two entries. The first\n            is the xml_compound and the second is the proportion of the\n            xml_compound in the molecule. Both values are strings.\n        enthalpy_of_formation (float): Enthalpy of formation of the compound.\n        inchikey (str): InChI (International Chemical Identifier) key\n            for the compound.\n        inp_name (str): Name as per the original 'inp' file.\n        iupac_name (str): IUPAC (International Union of Pure and Applied\n            Chemistry) name of the compound.\n        molecular_weight (float): Molecular\n            weight of the compound.\n        reference (str): Reference for the compound. See [1] for details.\n\n    Methods:\n        enthalpy:calculates the enthalpy for a Compound object.\n        entropy: calculates the entropy for a Compound object.\n        gibbs_energy: calculates the Gibbs energy for a Compound object.\n        heat_capacity: calculates the heat capacity for a Compound object.\n\n    Subclasses:\n        CompoundIdealGas: chemical compound as an ideal gas present in\n        the NASA9 term polynomials database. It inherits from Compound.\n\n    Examples:\n        >>> import thermopy\n        >>> from thermopy import nasa9polynomials as nasa9\n        >>> db = nasa9.Database()\n        >>> uf6 = db.set_compound('uf6(cr)')\n        >>> print(uf6)\n        hexafluorouranium: UF6(cr)\n\n    \"\"\"\n\n    def __init__(self, xml_compound):\n        u\"\"\"\n        Instantiate a Compound object from xml info.\n\n        Arguments:\n            xml_compound: xml tree containing the relevant fields to\n        characterize the attributes and boundaries of temperature for which\n        calculations are valid.\n\n        \"\"\"\n        self._xml_compound = xml_compound\n        self.inp_name = xml_compound.attrib['inp_file_name']\n        self.inchikey = xml_compound.find('identification').find(\n            'InChIKey').text\n        self.canonical_smiles = xml_compound.find(\n            'identification').find('canonical_smiles').text\n        self.cas_number = xml_compound.find('identification').find(\n            'cas_number').text\n        self.iupac_name = xml_compound.find('identification').find(\n            'IUPAC_name').text\n        self.comment = xml_compound.find('comment').text\n        self.reference = xml_compound.find('reference').text\n        self.elements = self._get_xml_compounds(xml_compound.find(\n            'elements'))\n        self.condensed = bool(\n            xml_compound.find('condensed').text == 'True')\n        self.molecular_weight = float(\n            xml_compound.find('molecular_weight').text)\n        self.enthalpy_of_formation = float(\n            xml_compound.find('hf298.15').text)\n\n    def _get_xml_compounds(self, xml_compound):\n        u\"\"\"\n        Return a list of tuples containing the elements and their\n        proportion in the chemical compound.\n\n        Arguments:\n            xml_compound (list): list of Element Tree objects containing\n        elements.\n\n        Returns:\n            list: list of tuples. Tuples are of the form (str, int) where\n        str is the symbol of the element and int is its proportion in the\n        molecule.\n\n        \"\"\"\n        xml_compounds_list = []\n        for one_xml_compound in xml_compound:\n            xml_compounds_list.append(tuple(*map(\n                lambda x, y: (x, int(y)),\n                *one_xml_compound.items()[0])))\n        return xml_compounds_list\n\n    def _evaluate_temperature_interval(self, T):\n        u\"\"\"\n        Ouput temperature interval to be used by public methods.\n\n        Helper method to ouput temperature interval order.\n\n        Arguments:\n            T (float): temperature.\n\n        Returns:\n            int: The order of the temperature range (0th, 1st, 2nd, etc).\n        Some compounds have more than one temperature range with different\n        corrisponding coefficients. Therefore the temperature range has to be\n        specified.\n\n        Example: The KI gas has two temperature intervals (thus two sets of\n        coefficients to be used). The ranges are: [200, 1000] and [1000, 6000]\n        as for most gases. Thus requiring a property to be measured at 1100 K\n        the second interval should be used and this method shall return the\n        number 1 (as opposed to zero).\n\n        \"\"\"\n        for (i, Trange) in enumerate(self._xml_compound.findall('T_range')):\n            if (float(Trange.attrib['Tlow']) <= T <= float(\n                    Trange.attrib['Thigh'])):\n                return i\n        raise Exception('Temperature out of range for '\n                        + self.iupac_name + '/' + self.inp_name\n                        + ' with ' + str(T) + ' K')\n\n    def heat_capacity(self, T):\n        u\"\"\"\n        Calculate molar heat capacity at constant pressure for standard\n        state.\n\n        Arguments:\n            T (float): temperature.\n\n        Returns:\n            numpy_float: The molar heat capacity for the compound for a\n        given temperature.\n\n        Examples:\n            >>> import thermopy\n            >>> from thermopy import nasa9polynomials as nasa9\n            >>> db = nasa9.Database()\n            >>> libr = db.set_compound('LiBr')\n            >>> print(libr, '-', libr.heat_capacity(2700))\n            lithium;bromide: LiBr - 39.6593057506\n\n        \"\"\"\n        coefficients = np.empty(9, dtype=np.float32)\n        for (i, coef) in enumerate(self._xml_compound.findall(\n                'T_range')[self._evaluate_temperature_interval(T)]):\n            coefficients[i] = np.array(coef.text, dtype=np.float32)\n        exponents = np.array([-2, -1, 0, 1, 2, 3, 4], dtype=np.signedinteger)\n        return np.sum(\n            np.multiply(\n                np.power(T, exponents, dtype=np.float32),\n                coefficients[0:7]), dtype=np.float32) * _R\n\n    def enthalpy(self, T):\n        u\"\"\"\n        Calculate molar enthalpy at constant pressure for the compound for\n        a given temperature.\n\n        Arguments:\n            T (float): temperature.\n\n        Returns:\n            numpy_float: The molar enthalpy for the compound for a given\n            temperature.\n\n        Examples:\n            >>> import thermopy\n            >>> from thermopy import nasa9polynomials as nasa9\n            >>> db = nasa9.Database()\n            >>> magnesium_hydroxide = db.set_compound('Mg(OH)2(cr)')\n            >>> print(magnesium_hydroxide, '-',\n            >>> magnesium_hydroxide.enthalpy(500))  # J/mol\n            Mg(OH)2(cr) - -906097.801815\n\n        \"\"\"\n        coefficients = np.empty(9, dtype=np.float32)\n        for (i, coef) in enumerate(self._xml_compound.findall(\n                'T_range')[self._evaluate_temperature_interval(T)]):\n            coefficients[i] = np.array(coef.text, dtype=np.float32)\n        exponents = np.array([-2, -1, 0, 1, 2, 3, 4, -1],\n                             dtype=np.signedinteger)\n        other_factors = np.array([-1, np.log(T), 1, 0.5, 1/3, 0.25, 0.2, 1],\n                                 dtype=np.float32)\n        return np.sum(\n            np.multiply(\n                np.multiply(\n                    np.power(T, exponents, dtype=np.float32),\n                    coefficients[0:8]),\n                other_factors), dtype=np.float32) * _R * T\n\n    def entropy(self, T):\n        u\"\"\"\n        Calculate molar entropy at constant pressure for the compound for\n        a given temperature.\n\n        Arguments:\n            T (float): temperature.\n\n        Returns:\n            numpy_float: The molar entropy for the compound for a given\n            temperature.\n\n        Examples:\n            >>> import thermopy\n            >>> from thermopy import nasa9polynomials as nasa9\n            >>> db = nasa9.Database()\n            >>> argon = db.set_compound('ar')\n            >>> print(argon, '-', argon.entropy(200))\n            argon: Ar - 146.546470215\n\n        \"\"\"\n        coefficients = np.empty(9, dtype=np.float32)\n        for (i, coef) in enumerate(self._xml_compound.findall(\n                'T_range')[self._evaluate_temperature_interval(T)]):\n            coefficients[i] = np.array(coef.text, dtype=np.float32)\n        exponents = np.array([-2, -1, 0, 1, 2, 3, 4, 0, 0],\n                             dtype=np.signedinteger)\n        other_factors = np.array([-0.5, -1, np.log(T), 1, 0.5, 1/3, 0.25,\n                                  0, 1],\n                                 dtype=np.float32)\n        return np.sum(\n            np.multiply(\n                np.multiply(np.power(T, exponents, dtype=np.float32),\n                            coefficients[:]),\n                other_factors), dtype=np.float32) * _R\n\n    def gibbs_energy(self, T):\n        u\"\"\"\n        Calculate molar Gibbs energy at constant pressure for the compound\n        for a given temperature.\n\n        Arguments:\n            T (float): temperature.\n\n        Returns:\n            numpy_float: The molar entropy for the compound for a given\n            temperature.\n\n        Examples:\n            >>> import thermopy\n            >>> from thermopy import nasa9polynomials as nasa9\n            >>> db = nasa9.Database()\n            >>> csbr = db.set_compound('csbr(cr)')\n            >>> print(csbr, '-', csbr.gibbs_energy(273.15))\n            cesium;bromide: CsBr(cr) - -436504.410044\n\n        \"\"\"\n        return self.enthalpy(T) - T * self.entropy(T)\n\n    def __str__(self):\n        if self.iupac_name != 'N/A':\n            return str(self.iupac_name) + ': ' + self.inp_name\n        elif self.canonical_smiles != 'N/A':\n            return str(self.canonical_smiles)\n        else:\n            return str(self.inp_name)\n\n\nclass CompoundIdealGas(Compound):\n    u\"\"\"\n    Chemical compound as an ideal gas present in the NASA9 term\n    polynomials database.\n\n    It is usually set by nasa9polyniomials.Database.set_compound('identifier').\n    If set this way this method already instantiates either a Compound or a\n    CompoundIdealGas based on the phase of the chemical compound specified by\n    the identifier (see note below).\n\n    Note: *The default phase for compounds in this database is gas.* Thus if\n    instantiating with the name 'H2O' one would get steam. For liquid water and\n    ice one would rather look for 'H2O(L)' or 'H2O(cr)'. The same is valid for\n    a lot of compounds expected to be in the condensed form (such as NaCl,\n    Tungsten, etc).\n\n    It adds two extra methods which come from the thermodynamics of Ideal\n    Gases.\n\n    Inherits from Compound.\n\n    Methods:\n        heat_capacity_constant_v: calculates the heat capacity at a\n        constant volume for a CompoundIdealGas object.\n        internal_energy: calculates\n        the internal energy for a CompoundIdealGas object.\n\n    Examples:\n        >>> # Instantiating a Compound whose condensed attributed is False\n        >>> # automatically sets it as an Ideal Gas:\n        >>> import thermopy\n        >>> from thermopy import nasa9polynomials as nasa9\n        >>> db = nasa9.Database()\n        >>> co2 = db.set_compound('CO2')\n        >>> print(co2, type(co2))\n        carbon dioxide: CO2 <class\n        'thermopy.nasa9polynomials.CompoundIdealGas'>\n\n    \"\"\"\n\n    def __init__(self, xml_compound):\n        u\"\"\"\n        Initialize an ideal gas Compound.\n\n        Arguments:\n            xml_compound: xml tree containing the relevant fields to\n        characterize the attributes and boundaries of temperature for which\n        calculations are valid.\n\n        \"\"\"\n        Compound.__init__(self, xml_compound)\n\n    def heat_capacity_constant_v(self, T):\n        u\"\"\"\n        Calculate molar heat capacity at constant volume for standard\n        state.\n\n        Arguments:\n            T (float): temperature.\n\n        Returns:\n            numpy_float: The molar heat capacity for the compound for a\n            given temperature.\n\n        Examples:\n            >>> import thermopy\n            >>> from thermopy import nasa9polynomials as nasa9\n            >>> db = nasa9.Database()\n            >>> xenon = db.set_compound('Xe')\n            >>> print(xenon, '-', xenon.heat_capacity(298.15))\n            xenon: Xe - 20.78618\n            >>> print(xenon, '-', xenon.heat_capacity_constant_v(298.15))\n            xenon: Xe - 12.471708\n            >>> print('subtracting both hc:',\n            ...       xenon.heat_capacity(298.15)\n            ...       - xenon.heat_capacity_constant_v(298.15))\n            subtracting both hc: 8.314472\n\n        \"\"\"\n        return self.heat_capacity(T) - _R\n\n    def internal_energy(self, T):\n        u\"\"\"\n        Calculate molar internal energy at constant pressure for standard\n        state.\n\n        Arguments:\n            T (float): temperature.\n\n        Returns:\n            numpy_float: The molar internal energy for the compound for a\n            given temperature.\n\n        Examples:\n            >>> import thermopy\n            >>> from thermopy import nasa9polynomials as nasa9\n            >>> db = nasa9.Database()\n            >>> hcn = db.set_compound('hcn')\n            >>> print(hcn, '-', hcn.internal_energy(500))\n            formonitrile: HCN - 136809.830971\n\n        \"\"\"\n        return self.enthalpy(T) - _R * T\n\n\nclass Database(object):\n    u\"\"\"\n    Nasa 9 term polynomials database (see NASA/TP—2002-211556).\n\n    The preferred method for identifying compounds is via *usual name* followed\n    by an aggregation state if the compound is not a gas. E.g. '(L)', '(cr)',\n    '(a)', '(b)' where '(a)' and '(b)' are for allotropes.\n    Other methods are:\n        1. InChIKey.\n        2. CAS number.\n        3. IUPAC name.\n\n    Examples:\n        >>> from thermopy import nasa9polynomials as nasa9\n        >>> db = nasa9.Database()\n\n    \"\"\"\n\n    def __init__(self):\n        u\"\"\"Initializes the database.\"\"\"\n        xmlPath = os.path.join(DATADIR, 'databases/nasa9polynomials.xml')\n        self._nasa9 = ET.parse(os.path.abspath(xmlPath))\n        self._root = self._nasa9.getroot()\n\n    def _search_database(self, x):\n        u\"\"\"\n        Search the database.\n\n        Arguments:\n            x (str): identifier for compound being searched.\n\n        Returns:\n            tuple: (inp file name, iupac name, ET.Element).\n\n        Note:\n            The preferred method for identifying compounds is via *usual name*\n            followed by an aggregation state if the compound is not a gas. E.g.\n            '(L)', '(cr)', '(a)', '(b)' where '(a)' and '(b)' are for\n            allotropes.\n            Other methods are:\n                1. InChIKey.\n                2. CAS number.\n                3. IUPAC name.\n\n        \"\"\"\n        result_list = []\n        inchikey_re = re.compile('[A-Z]{14}-[A-Z]{10}-[A-Z]')\n        cas_re = re.compile('[0-9]{2,7}-[0-9][0-9]-[0-9]')\n        # InChIKey search\n        if re.match(inchikey_re, x):  # is an inchikey\n            for specie in self._root:\n                identification = specie.find('identification')\n                inchikey = identification.find('InChIKey')\n                if x == inchikey.text:\n                    result_list.append(specie)\n        # CAS search\n        elif re.match(cas_re, x):\n            for specie in self._root:\n                identification = specie.find('identification')\n                cas_number = identification.find('cas_number')\n                if x == cas_number.text:\n                    result_list.append(specie)\n        # usual name search\n        else:\n            # tries exact match first\n            for specie in self._root:\n                iupac_name = specie.find('identification').find('IUPAC_name')\n                if (x.lower() == specie.find('identification').find(\n                        'IUPAC_name').text.lower() or\n                        x.lower() == specie.attrib['inp_file_name'].lower()):\n                    result_list.append(specie)\n            if len(result_list) == 1:\n                pass\n            else:  # exact match was not sucessfull go to loose match\n                result_list = []\n                # if not found tries loose match\n                for specie in self._root:\n                    iupac_name = specie.find('identification').find(\n                        'IUPAC_name')\n                    augmented_namespace = (specie.attrib['inp_file_name']\n                                           + ' ' + specie.find('comment').text\n                                           + ' ' + iupac_name.text)\n                    if x.lower() in augmented_namespace.lower():\n                        result_list.append(specie)\n        for specie in result_list:\n            return [(y.attrib['inp_file_name'],\n                     y.find('identification').find('IUPAC_name').text,\n                     y) for y in result_list]\n\n    def list_compound(self, x):\n        u\"\"\"\n        List the compounds for a given input.\n        It is intended to be used in interactive mode.\n\n        Arguments:\n            x (str): identifier for compound being searched.\n\n        Returns:\n            list: list of tuples containing (str, str) being the 'inp name' and\n            the IUPAC name respectively.\n\n        Examples:\n            >>> from thermopy import nasa9polynomials as nasa9\n            >>> db = nasa9.Database()\n            >>> for i in db.list_compound('fes'):\n            ...     print(i)\n            ('FeS(a)', 'sulfanylideneiron')\n            ('FeS(b)', 'sulfanylideneiron')\n            ('FeS(c)', 'sulfanylideneiron')\n            ('FeS(L)', 'sulfanylideneiron')\n            ('FeSO4(cr)', 'iron(2+);sulfate')\n            ('FeS2(cr)', 'N/A')\n\n        Note:\n            The preferred method for identifying compounds is via *usual name*\n            followed by an aggregation state if the compound is not a gas. E.g.\n            '(L)', '(cr)', '(a)', '(b)' where '(a)' and '(b)' are for\n            allotropes.\n            Other methods are:\n                1. InChIKey.\n                2. CAS number.\n                3. IUPAC name.\n\n        \"\"\"\n        result_list = []\n        for i in self._search_database(x):\n            result_list.append((i[0], i[1]))\n        return result_list\n\n    def set_compound(self, x):\n        u\"\"\"\n        Set the compound if there is one entry specified on the database.\n\n        It is important to notice that due to the nature of the work of this\n        database, compounds are gases unless explicitly stated otherwise.\n\n        Arguments:\n            x (str): identifier for compound being searched.\n\n        Returns:\n            Compound: returns a Compound object if the phase is condensed.\n            Returns a CompoundIdealGas otherwise.\n\n        Example:\n            >>> # Someone is looking for the element gallium but is not certain\n            >>> # how to instantiate it. One would first list the compounds:\n            >>> from thermopy import nasa9polynomials as nasa9\n            >>> db = nasa9.Database()\n            >>> for i in db.list_compound('gallium'):\n            ...     print(i)\n            ...\n            ('Ga', 'gallium')\n            ('Ga+', 'gallium')\n            ('GaBr', 'bromogallium')\n            ('GaBr2', 'dibromogallium')\n            ('GaCl', 'chlorogallium')\n            ('GaCl2', 'gallium;dichloride')\n            ('GaF2', 'difluorogallium')\n            ('GaI2', 'diiodogallium')\n            ('GaO', 'oxogallium')\n            ('GaOH', 'gallium;hydroxide')\n            ('Ga2Cl4', 'gallium;gallium;tetrachloride')\n            ('Ga2O', 'gallium;oxygen(2-)')\n            ('Ga(cr)', 'gallium')\n            ('Ga(L)', 'gallium')\n            ('Ga2O3(cr)', 'digallium;oxygen(2-)')\n            ('Ga2O3(L)', 'digallium;oxygen(2-)')\n            >>> gallium = db.set_compound('Ga')\n            >>> print(gallium)\n            gallium: Ga\n\n        Note:\n            The preferred method for identifying compounds is via *usual name*\n            followed by an aggregation state if the compound is not a gas. E.g.\n            '(L)', '(cr)', '(a)', '(b)' where '(a)' and '(b)' are for\n            allotropes.\n            Other methods are:\n                1. InChIKey.\n                2. CAS number.\n                3. IUPAC name.\n\n        \"\"\"\n        result = self._search_database(x)\n        if len(result) != 1:  # could not set component: give error messages\n            if len(result) == 0:\n                raise Exception('No compound found.')\n            else:\n                raise Exception('The compound \\'' + str(x) + '\\' you are '\n                                'trying to set is not unique: ' + result[0][0],\n                                result[1][0])\n        if result[0][2].find('condensed') == 'True':\n            return Compound(result[0][2])\n        else:  # if it is an ideal gas\n            return CompoundIdealGas(result[0][2])\n\n\nclass Reaction(object):\n    u\"\"\"\n    Model of a chemical reaction.\n\n    Model of a chemical reaction using the NASA9 Compounds.\n\n    Inherits from object.\n\n    Methods:\n        enthalpy_reaction: enthalpy of the reaction.\n        entropy_reaction: entropy of the reaction.\n        gibbs_energy_reaction: Gibbs energy of the reaction.\n        equilibrium_constant: equilibrium constant of the reaction.\n\n    Examples:\n        >>> from thermopy import nasa9polynomials as nasa9\n        >>> db = nasa9.Database()\n        >>> na = db.set_compound('na(cr)')\n        >>> # being careful to initilize solid compounds\n        >>> water = db.set_compound('h2o(l)')\n        >>> # being careful to initilize liquid compounds\n        >>> sodium_hydroxide = db.set_compound('naoh(a)')\n        >>> # being careful to initilize solid compounds\n        >>> hydrogen = db.set_compound('h2')\n        >>> reacts = (na, water)\n        >>> prods = (sodium_hydroxide, hydrogen)\n        >>> reacts_coefs = (2, 2)\n        >>> prods_coefs = (2, 1)\n        >>> reaction1 = nasa9.Reaction(300, reacts, prods, reacts_coefs,\n        >>> prods_coefs)\n        >>> print(reaction1)\n        <reaction> +2 Na(cr) +2 H2O(L)  -> +2 NaOH(a) +1 H2\n        >>> print(reaction1.entropy_reaction())\n        149.097547531\n        >>> print(reaction1.enthalpy_reaction())\n        -279857.367433\n\n    Notes:\n        The Reaction class does not check for imbalances of the reaction (yet).\n\n    \"\"\"\n\n    def __init__(self, T, reactants, products,\n                 reactants_coefficients, product_coefficients):\n        u\"\"\"\n        Initializes a Reaction object.\n\n        Arguments:\n            T (float): temperature of the reaction.\n            reactants (tuple): tuple of the reactants as Compounds.\n            products (tuple): tuple of the products as Compounds.\n            reactants_coefficients (tuple): tuple of the reactants\n                coefficients.\n            product_coefficients (tuple): tuple of the products coefficients.\n\n        Examples:\n            >>> import thermopy\n            >>> from thermopy import nasa9polynomials as nasa9\n            >>> db = nasa9.Database()\n            >>> co = db.set_compound('carbon monoxide')\n            >>> molybdenium_oxide = db.set_compound('MoO2(cr)')  # to set it a\n            >>> solid\n            >>> co2 = db.set_compound('co2')\n            >>> molybdenium = db.set_compound('Mo(cr)')  # to set it a solid\n            >>> reagents = (co, molybdenium_oxide)\n            >>> products = (co2, molybdenium)\n            >>> reactants_stoichometry = (2, 1)\n            >>> prodcuts_stoichometry = (2, 1)\n            >>> reaction1 = nasa9.Reaction(\n            ...     298,\n            ...     reagents,\n            ...     products,\n            ...     reactants_stoichometry,\n            ...     prodcuts_stoichometry\n            ...     )\n            >>> print(reaction1, reaction1.enthalpy_reaction())\n            <reaction> +2 CO +1 MoO2(cr)  -> +2 CO2 +1 Mo(cr)  23352.3949968\n\n        Note:\n            The tuple of the reactants and its coefficients should refer to the\n            same compounds (follow the same order). See example.\n\n        \"\"\"\n        self.T = T\n        self._reactants = reactants\n        self._products = products\n        self._rcoefs = tuple(abs(z) for z in reactants_coefficients)\n        self._pcoefs = tuple(abs(z) for z in product_coefficients)\n        # error checking\n        if (len(self._reactants) != len(self._rcoefs) or\n                len(self._products) != len(self._pcoefs)):\n            raise Exception('Number of reactants or products is different'\n                            'from the number of coefficients given')\n\n    def enthalpy_reaction(self, T=None):\n        u\"\"\"\n        Calculate the enthalpy of the reaction at the standard state.\n\n        Arguments:\n            T (float): temperature.\n\n        Returns:\n            numpy_float: The enthalpy of the reaction for a given temperature.\n\n        Examples:\n            >>> import thermopy\n            >>> from thermopy import nasa9polynomials as nasa9\n            >>> db = nasa9.Database()\n            >>> nitric_acid = db.set_compound('hno3')\n            >>> # the liquid phase is not present in the database\n            >>> naoh = db.set_compound('naoh(a)')\n            >>> sodium_nitrate = db.set_compound('nano3(a)')\n            >>> water = db.set_compound('h2o(l)')\n            >>> reagents = (nitric_acid, naoh)\n            >>> products = (sodium_nitrate, water)\n            >>> reactants_stoichometry = (1, 1)\n            >>> prodcuts_stoichometry = (1, 1)\n            >>> reaction1 = nasa9.Reaction(\n            ...     298,\n            ...     reagents,\n            ...     products,\n            ...     reactants_stoichometry,\n            ...     prodcuts_stoichometry\n            ...     )\n            >>> print(reaction1, reaction1.enthalpy_reaction())\n            <reaction> +1 HNO3 +1 NaOH(a)  -> +1 NaNO3(a) +1 H2O(L)\n            -193773.133358\n\n        \"\"\"\n        if T is not None:\n            self.T = T\n        deltah = 0\n        for (coefficient, compound) in zip(self._rcoefs, self._reactants):\n            deltah = deltah - coefficient * compound.enthalpy(self.T)\n        for (coefficient, compound) in zip(self._rcoefs, self._products):\n            deltah = deltah + coefficient * compound.enthalpy(self.T)\n        return deltah\n\n    def entropy_reaction(self, T=None):\n        u\"\"\"\n        Calculate the entropy of the reaction at the standard state.\n\n        Arguments:\n            T (float): temperature.\n\n        Returns:\n            numpy_float: The entropy of the reaction for a given temperature.\n\n        Examples:\n            >>> import thermopy\n            >>> from thermopy import nasa9polynomials as nasa9\n            >>> db = nasa9.Database()\n            >>> nitric_acid = db.set_compound('hno3')\n            >>> # the liquid phase is not present in the database\n            >>> naoh = db.set_compound('naoh(a)')\n            >>> sodium_nitrate = db.set_compound('nano3(a)')\n            >>> water = db.set_compound('h2o(l)')\n            >>> reagents = (nitric_acid, naoh)\n            >>> products = (sodium_nitrate, water)\n            >>> reactants_stoichometry = (1, 1)\n            >>> prodcuts_stoichometry = (1, 1)\n            >>> reaction1 = nasa9.Reaction(\n            ...     298,\n            ...     reagents,\n            ...     products,\n            ...     reactants_stoichometry,\n            ...     prodcuts_stoichometry\n            ...     )\n            >>> print(reaction1, reaction1.entropy_reaction())\n            <reaction> +1 HNO3 +1 NaOH(a)  -> +1 NaNO3(a) +1 H2O(L)\n            -145.797754143\n\n        \"\"\"\n        if T is not None:\n            self.T = T\n        deltas = 0\n        for (coefficient, compound) in zip(self._rcoefs, self._reactants):\n            deltas = deltas - coefficient * compound.entropy(self.T)\n        for (coefficient, compound) in zip(self._rcoefs, self._products):\n            deltas = deltas + coefficient * compound.entropy(self.T)\n        return deltas\n\n    def gibbs_energy_reaction(self, T=None):\n        u\"\"\"\n        Calculate the Gibbs energy of the reaction at the standard state.\n\n        Arguments:\n            T (float): temperature.\n\n        Returns:\n            numpy_float: The Gibbs energy of the reaction for a given\n            temperature.\n\n        Examples:\n            >>> import thermopy\n            >>> from thermopy import nasa9polynomials as nasa9\n            >>> db = nasa9.Database()\n            >>> pcl5 = db.set_compound('pcl5')\n            >>> pcl3 = db.set_compound('pcl3')\n            >>> chlorine = db.set_compound('cl2')\n            >>> reagents = (pcl5,)\n            >>> products = (pcl3, chlorine)\n            >>> reactants_stoichometry = (1,)\n            >>> prodcuts_stoichometry = (1, 1)\n            >>> reaction1 = nasa9.Reaction(\n            ...     298,\n            ...     reagents,\n            ...     products,\n            ...     reactants_stoichometry,\n            ...     prodcuts_stoichometry\n            ...     )\n            >>> print(reaction1, reaction1.gibbs_energy_reaction())\n            <reaction> +1 PCl5  -> +1 PCl3 +1 Cl2  103038.712535\n\n        \"\"\"\n        if T is not None:\n            self.T = T\n        deltag = 0\n        for (coefficient, compound) in zip(self._rcoefs, self._reactants):\n            deltag = deltag - coefficient * compound.gibbs_energy(self.T)\n        for (coefficient, compound) in zip(self._rcoefs, self._products):\n            deltag = deltag + coefficient * compound.gibbs_energy(self.T)\n        return deltag\n\n    def equilibrium_constant(self, T=None):\n        u\"\"\"\n        Calculate the equilibrium constant of the reaction at the standard\n        state.\n\n        Definition: K = exp(- deltaG / (R T))\n\n        Arguments:\n            T (float): temperature.\n\n        Returns:\n            numpy_float: The Gibbs energy of the reaction for a given\n            temperature.\n\n\n        Examples:\n            >>> import thermopy\n            >>> from thermopy import nasa9polynomials as nasa9\n            >>> db = nasa9.Database()\n            >>> pcl5 = db.set_compound('pcl5')\n            >>> pcl3 = db.set_compound('pcl3')\n            >>> chlorine = db.set_compound('cl2')\n            >>> reagents = (pcl5,)\n            >>> products = (pcl3, chlorine)\n            >>> reactants_stoichometry = (1,)\n            >>> prodcuts_stoichometry = (1, 1)\n            >>> reaction1 = nasa9.Reaction(\n            ...     500,\n            ...     reagents,\n            ...     products,\n            ...     reactants_stoichometry,\n            ...     prodcuts_stoichometry\n            ...     )\n            >>> print(reaction1, reaction1.equilibrium_constant())\n            <reaction> +1 PCl5  -> +1 PCl3 +1 Cl2  6.39431126134e-13\n\n        \"\"\"\n        if T is not None:\n            self.T = T\n        return np.exp(-1 * self.gibbs_energy_reaction(self.T) / (\n            _R * self.T))\n\n    def __repr__(self):\n        u\"\"\"Define how a reaction should be print.\"\"\"\n        r = ''\n        for (reag, coef) in zip(self._reactants, self._rcoefs):\n            r = r + '+' + str(coef) + ' ' + reag.inp_name + ' '\n        r = r + ' -> '\n        for (reag, coef) in zip(self._products, self._pcoefs):\n            r = r + '+' + str(coef) + ' ' + reag.inp_name + ' '\n        return \"\"\"<reaction> {0}\"\"\".format(r)\n", "meta": {"hexsha": "7685a39712f0df41621c3dd0dbfcd4c2dccf16e5", "size": 34095, "ext": "py", "lang": "Python", "max_stars_repo_path": "thermopy/nasa9polynomials.py", "max_stars_repo_name": "jhdulaney/thermopy", "max_stars_repo_head_hexsha": "a413e2c18e257ea32492375a15968191520e7122", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thermopy/nasa9polynomials.py", "max_issues_repo_name": "jhdulaney/thermopy", "max_issues_repo_head_hexsha": "a413e2c18e257ea32492375a15968191520e7122", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thermopy/nasa9polynomials.py", "max_forks_repo_name": "jhdulaney/thermopy", "max_forks_repo_head_hexsha": "a413e2c18e257ea32492375a15968191520e7122", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3848684211, "max_line_length": 79, "alphanum_fraction": 0.5654201496, "include": true, "reason": "import numpy", "num_tokens": 8153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.16087743711510621}}
{"text": "# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\nimport felis\nfrom astropy.io import fits\nimport scipy.signal\nimport pdb\nimport matplotlib.pyplot as plt\nimport datetime\nimport pickle\nimport sys\nimport os\nimport numpy as np\n# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\ndef match_templates2specs(templates,spectra,speczs,picklename,wavewindow=[50.0],wavecen_restframe=[1908.0],\n                          vshift=None,min_template_level=1e-4,plotdir=None,plot_allCCresults=False,\n                          subtract_spec_median=True,overwrite=False,verbose=True):\n    \"\"\"\n    Wrapper around felis cross-correlation template matching, to match a list of spectra with a list of templtes.\n\n    --- INPUT ---\n    spectra               fits spectra to find a (cross-correlation) match to template for\n    templates             fits templates to correlate with\n    speczs                Spectroscopic redshifts to perform cross-correlation in rest-frame (shifting the spectrum).\n    subtract_spec_median  Subtract median value of spectrum (approximating the continuum level)\n    picklename            Name of pickle file to store final cross-correlation results in\n    wavewindow            Window (wavecen_restframe * (1+speczs) +/- wavewindow) to perform template matching over.\n    wavecen_restframe     Central rest-frame  wavelength of the region to match\n    vshift                If a velcotiy shift is known, provide it here and it will be stored in output (not used)\n    min_template_level    The template is interpolated to the wavelength grid of the spectrum and extrapolated\n                          beyond it's edges if nescessary. In this extrapolation (assuming the template goes to ~0\n                          at the edges), very small values (e.g., <1e-20) can be returned. To set these to 0.0\n                          provide a level below which all values in the interpolated template are treated as 0s.\n    plotdir               Directory to store plots to\n    plot_allCCresults     To plot all the cross-correlation plots, set this to True\n    overwrite             Overwrite existing pickle file if it already exists?\n    verbose               Toggle verbosity\n\n    --- EXAMPLE OF USE ---\n    import felis\n    import glob\n\n    specdir  = '/Users/kschmidt/work/MUSE/uvEmissionlineSearch/felis_testing/'\n    #specs    = glob.glob(specdir+'uves_felis_mock_MUSEspectrum_noisesigma*3p0.fits')\n    specs    = glob.glob(specdir+'uves_felis_mock_MUSEspectrum_noisesigma*.fits')\n    speczs   = [3.5]*len(specs)\n\n    tempdir  = '/Users/kschmidt/work/MUSE/uvEmissionlineSearch/felis_testing/'\n    #temps    = glob.glob(specdir+'uves_felis_template_CIIIdoublet_sig_0p25_fluxCIII1_4p0_flux*.fits')\n    temps    = glob.glob(specdir+'uves_felis_template_CIIIdoublet_*fits')\n    temps    = glob.glob(specdir+'uves_felis_template_CIVdoublet_*fits')\n\n    plotdir  = '/Users/kschmidt/work/MUSE/uvEmissionlineSearch/felis_testing/plots_CCresults180615/'\n    pickle   = '/Users/kschmidt/work/MUSE/uvEmissionlineSearch/felis_testing/CCresults180615_RENAME_.pkl'\n\n    specs = ['/Volumes/DATABCKUP1/TDOSEextractions/171201_TDOSEextraction/Modelimg/tdose_spectra/tdose_spectrum_candels-cdfs-15_modelimg_0115003085-0115003085.fits']\n    speczs = [3.2585198879241943]\n\n    ccdic    = felis.match_templates2specs(temps,specs,speczs,pickle,wavewindow=[60]*len(specs),plotdir=plotdir,wavecen_restframe=[1549.0]*len(specs))\n\n    --- OUTPUT ---\n\n    This wrapper will collect all the cross-correlation results in a main dictionary.\n    The dictionary will be returned directly but also saved to disk as a pickled filed.\n    This file can be loaded with: felis.load_picklefile(picklefilename)\n\n    The returned dictionary has the following format:\n\n    dictionary.keys()  = the list of spectra that have been crossmatched (input = 'spectra')\n\n    Each entry in the dictionary (dictionary[key]) contains the following entries:\n        'wavelengths'               :   The wavelength vector used for the cross-correlation matching of\n                                        each of the N templates\n        'templatevec'               :   list of each of the N templates matched to spectrum\n        'zspec'                     :   Spectroscopic redshift for spectrum\n        'zCCmaxvec'                 :   the redshift corresponding to max S/N for each of the N templates matched\n        'ccresultsarray_flux'       :   fluc vectors for each of the N templates matched\n        'ccresultsarray_variance'   :   Variance vecotrs for each of the N templates matched\n        'ccresultsarr_S2N'          :   S/N vector for each of the N templates matched\n        'ccresultsarr_chi2'         :   chi squared values for the cross-correlation of each of the N templates matched\n        'ccresultsarr_Ngoodent'     :   The number of good pixels used in the cross correlation for each of\n                                        the N templates matched\n        'S2NCCmaxvec'               :   vector with max(S/N) values for N templates matched\n        'continuumlevel'            :   The 'continuum level' of the spectrum removed in the cross-correlation.\n                                        Currently the value is simply the median of the spectrum.\n        'vshift'                    :   If a velocity shift was provided for the template match this is stored here\n\n    The picklefile can be used to assemble sub-sample results (e.g., S/N cuts) based on the\n    template cross-correlations with\n        felis.selection_from_picklefile()\n    And individual entries can be plotted using\n        felis.plot_picklefilecontent()\n\n    \"\"\"\n    ccresultdic = {}\n\n    if verbose: print(' - Starting cross-correlation of the '+str(len(spectra))+' spectra and '+\n                      str(len(templates))+' templates')\n    startstring = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\")\n    if verbose: print('   '+startstring+'\\n')\n\n    if len(spectra) == 0:\n        sys.exit(' No spectra provided')\n\n    if len(templates) == 0:\n        sys.exit(' No templates provided')\n\n    for ss, spec in enumerate(spectra):\n        # Nwave = pyfits.open(spec)[1].header['NAXIS2']\n        spec_namebase = spec.split('/')[-1].split('.fit')[0]\n        for tt, temp in enumerate(templates):\n            temp_namebase = temp.split('/')[-1].split('.fit')[0]\n\n            wavecenter  = wavecen_restframe[ss]  * (1.0 + speczs[ss])\n            waverange   = [wavecenter-wavewindow[ss],wavecenter+wavewindow[ss]]\n\n            wave, ccresults, max_S2N, max_z, continuumlevel = \\\n                felis.cross_correlate_template(spec,temp,z_restframe=speczs[ss],spec_median_sub=subtract_spec_median,\n                                               waverange=waverange,min_template_level=min_template_level,verbose=verbose)\n\n            if tt == 0:\n                ccresultsarr_flux      = np.array(ccresults[:,0])\n                ccresultsarr_variance  = ccresults[:,1]\n                ccresultsarr_S2N       = ccresults[:,2]\n                ccresultsarr_chi2      = ccresults[:,3]\n                ccresultsarr_Ngoodent  = ccresults[:,4]\n                templatevec            = np.array([temp])\n                S2NCCmaxvec            = np.array([max_S2N])\n                zCCmaxvec              = np.array([max_z])\n                #print('-------------------------->'+str(np.max(ccresultsarr_S2N))+'  '+str(max_S2N))\n            else:\n                ccresultsarr_flux      = np.vstack((ccresultsarr_flux,ccresults[:,0]))\n                ccresultsarr_variance  = np.vstack((ccresultsarr_variance,ccresults[:,1]))\n                ccresultsarr_S2N       = np.vstack((ccresultsarr_S2N,ccresults[:,2]))\n                ccresultsarr_chi2      = np.vstack((ccresultsarr_chi2,ccresults[:,3]))\n                ccresultsarr_Ngoodent  = np.vstack((ccresultsarr_Ngoodent,ccresults[:,4]))\n                templatevec            = np.append(templatevec,temp)\n                S2NCCmaxvec            = np.append(S2NCCmaxvec,max_S2N)\n                zCCmaxvec              = np.append(zCCmaxvec,max_z)\n                #print('-------------------------->'+str(np.max(ccresultsarr_S2N[tt,:]))+'  '+str(S2NCCmaxvec[tt]))\n\n        ccresultdic[spec]  = {'wavelengths':wave, 'templatevec':templatevec, 'zspec':speczs[ss],\n                              'zCCmaxvec':zCCmaxvec, 'ccresultsarray_flux':ccresultsarr_flux,\n                              'ccresultsarray_variance':ccresultsarr_variance,'S2NCCmaxvec':S2NCCmaxvec,\n                              'ccresultsarr_S2N':ccresultsarr_S2N,'ccresultsarr_chi2':ccresultsarr_chi2,\n                              'ccresultsarr_Ngoodent':ccresultsarr_Ngoodent}\n\n        ccresultdic[spec]['continuumlevel'] = continuumlevel\n        if vshift is not None:\n            ccresultdic[spec]['vshift'] = vshift[ss]\n\n\n    if verbose: print('\\n - Finished cross-correlation of the '+str(len(spectra))+' spectra and '+\n                      str(len(templates))+' templates')\n    if verbose: print('   '+datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\")+'  (started at '+startstring+')')\n\n    if verbose: print(' - Saving dictionary to '+picklename)\n    if os.path.isfile(picklename) & (overwrite == False):\n        print('\\n   FELIS WARNING: The output file '+picklename+'exists but overwrite==False so returning \"None\" ')\n        return None\n    else:\n        felis.save_dictionary(ccresultdic,picklename)\n\n        if verbose: print(' - Will plot all cross-correlation results in saved dictionary as plot_allCCresults=True')\n        if plot_allCCresults:\n            for ss, spec in enumerate(spectra):\n                spec_namebase = spec.split('/')[-1].split('.fit')[0]\n                for tt, temp in enumerate(templates):\n                    temp_namebase = temp.split('/')[-1].split('.fit')[0]\n                    plotname      = plotdir+spec_namebase+'_CCwith_'+temp_namebase+'.pdf'\n\n                    felis.plot_picklefilecontent([spec],picklename,plottemplates=[tt],showspecerr=False,\n                                                 plotnames=[plotname],plotdir=plotdir,verbose=verbose)\n\n        if verbose: print(' - Returning dictioniary with results ')\n        loaddic = felis.load_picklefile(picklename)\n        return  loaddic\n# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\ndef selection_from_picklefile(picklefile,S2Nmaxrange=[3,1e4],zspecrange=[0,10],voffsetrange=[-1e4,1e4],\n                              zspecISzLya=False,verbose=True):\n    \"\"\"\n    Function, returning the list of spectra (keys) from the FELIS tempalte match pickled dictionary satisfying\n    a set of criteria on SN, redshift, velocity offset, etc.\n\n    --- INPUT ---\n    picklefile          The path and name to FELIS output pickelfile to select subset of matches from.\n    S2Nmaxrange         The range of S/N template accepted for template matches returned.\n    zspecrange          The range of redshifts accepted for template matches returned.\n    voffsetrange        The range of velocity offsets in km/s (wrt. to the spectroscopic redshift in dictionary)\n                        accepted for template matches returned.\n    zspecISzLya         If picklefile contains zLya keyword insead of zspec (was generated before 180912), set this\n                        keyword to True to enable proper handling of the dictionary keywords.\n    verbose             Toggle the verbosity.\n\n    --- EXAMPLE OF USE ---\n    import felis\n\n    picklepath = '/Users/kschmidt/work/MUSE/uvEmissionlineSearch/'\n    picklefile = picklepath+'MUSEWideLAEs_CCresults180502_CIV_all_575specX12templates.pkl'\n\n    goodkeys   = felis.selection_from_picklefile(picklefile,S2Nmaxrange=[3,5])\n\n    \"\"\"\n    if verbose: print(' - Loading the picklefile \\n   '+picklefile)\n    loaddic  = felis.load_picklefile(picklefile)\n    goodkeys = []\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n    # Ensure compatibility with FELIS output dictionaries from before 180912\n    zkey = 'zspec'\n    if zspecISzLya: zkey = 'zLya'\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n    if verbose: print(' - Looking for keys in the pickled dictionary satisfying the cuts:')\n    if verbose: print('       '+zkey+'          :  ['+str(zspecrange[0])+','+str(zspecrange[1])+']')\n    if verbose: print('       max(S/N)       :  ['+str(S2Nmaxrange[0])+','+str(S2Nmaxrange[1])+']')\n    if verbose: print('       voffset[km/s]  :  ['+str(voffsetrange[0])+','+str(voffsetrange[1])+']')\n    for key in loaddic.keys():\n        keydic = loaddic[key]\n\n        template, vshift_intr, vshift_match, flux, fluxerr, S2Nmax, Ngoodent, chi2, zspec, zS2Nmax =  \\\n            felis.getresult4maxS2N(loaddic,key,zspecISzLya=zspecISzLya)\n\n        if ((keydic[zkey] > zspecrange[0]) & (keydic[zkey] < zspecrange[1])) & \\\n                ((S2Nmax > S2Nmaxrange[0]) & (S2Nmax < S2Nmaxrange[1])) & \\\n                ((vshift_match > voffsetrange[0]) & (vshift_match < voffsetrange[1])):\n            goodkeys.append(key)\n    if verbose: print(' - Found '+str(len(goodkeys))+' keys in the pickled dictionary satisfying the cuts:')\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n    if verbose: print(' - Returning those')\n    return goodkeys\n# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\ndef plot_picklefilecontent(specs2plot,picklefile,plotnames=None,plotdir=None,z_restframe=None,\n                           plottemplates=None,showspecerr=True,zspecISzLya=False,verbose=True):\n    \"\"\"\n    Function to plot individual results from a picklefile generated with felis.match_templates2specs()\n\n    --- INPUT ---\n    specs2plot          The spectra from the pickle file (the pickle dictinary keys) to plot. These can be\n                        provide in a list by hand or be selected with felis.selection_from_picklefile()\n    picklefile          The path and name to pickelfile to plot content of\n    plotnames           The names of the plot(s) to generate. If 'None' the string '_templatematch.pdf' will\n                        be appended that pickle dictionary key (spectrum name).\n    plotdir             To chose a different directory for saving the plots (other than the directory\n                        in which the spectrum provided is stored) provide this here.\n    z_restframe         The redshift used to move spectrum to rest-frame\n    plottemplates       By default the template match with highest S/N is plotted. To plot another template\n                        provide the entry in the dictionary of this template. To see the templates, look at\n                        the 'templatevec' entry:\n                            picload = felis.load_picklefile(picklefile)\n                            picload[specname]['templatevec']\n    showspecerr         Show the error on the data spectrum? Can make the automatically set y-axis range less ideal.\n    zspecISzLya         If picklefile contains zLya keyword insead of zspec (was generated before 180912), set this\n                        keyword to True to enable proper handling of the dictionary keywords.\n    verbose             Toggle the verbosity.\n\n    --- EXAMPLE OF USE ---\n    import felis\n\n    picklepath = '/Users/kschmidt/work/MUSE/uvEmissionlineSearch/'\n    picklefile = picklepath+'MUSEWideLAEs_CCresults180502_CIV_all_575specX12templates.pkl'\n\n    picklefile = '/Users/kschmidt/work/MUSE/uvEmissionlineSearch/felis_testing/CCresults180615_RENAME_.pkl'\n\n    plotdir    = '/Users/kschmidt/work/MUSE/uvEmissionlineSearch/MUSEwideLAE_FELISplots/'\n    specs2plot = ['/Volumes/DATABCKUP1/TDOSEextractions/171201_TDOSEextraction/Modelimg/tdose_spectra/tdose_spectrum_candels-cdfs-15_modelimg_0115003085-0115003085.fits']\n\n    felis.plot_picklefilecontent(specs2plot,picklefile,plotnames=None,plotdir=plotdir,verbose=True)\n\n\n    \"\"\"\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n    # Ensure compatibility with FELIS output dictionaries from before 180912\n    zkey = 'zspec'\n    if zspecISzLya: zkey = 'zLya'\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n    if verbose: print(' - loading the dictionary from the pickled file:\\n   '+picklefile)\n    loaddic  = felis.load_picklefile(picklefile)\n\n    for ss, spec in enumerate(specs2plot):\n        if plotnames is None:\n            plotname = spec.replace('.fits','_templatematch.pdf')\n        else:\n            plotname = plotnames[ss]\n\n        if plotdir is not None:\n            specdir  = '/'.join(plotname.split('/')[:-1])\n            plotname = plotname.replace(specdir,plotdir)\n\n        spec_wave, spec_flux, spec_df, spec_s2n = felis.load_spectrum(spec,verbose=verbose)\n        spec_dic  = loaddic[spec]\n\n        if plottemplates is None:\n            # Getting the entry of the template with maximum S/N in the CC results\n            max_S2N = np.max(spec_dic['S2NCCmaxvec'])\n            besttemplate_ent = np.where(spec_dic['ccresultsarr_S2N'] == max_S2N)[0][0] # Template of max S/N\n        else:\n            max_S2N          = spec_dic['S2NCCmaxvec'][plottemplates[ss]]\n            besttemplate_ent = plottemplates[ss]\n\n        # moving spectrum to restframe\n        if z_restframe is None:\n            z_spec=spec_dic[zkey]\n\n            spec_wave, spec_flux, spec_df, spec_s2n = \\\n                spec_wave / (1+z_spec), spec_flux * (1.0+z_spec), spec_df * (1.0+z_spec), spec_s2n\n        else:\n            z_spec = 0.0\n\n        # subtract continuum level from spectrum\n        spec_flux = spec_flux - spec_dic['continuumlevel'] * (1.0+z_spec)\n\n        # Limit spectrum to range of wavelengths cross-correlated with tempalte\n        goodent = np.where( (spec_wave >= spec_dic['wavelengths'][0]) & (spec_wave <= spec_dic['wavelengths'][-1]) )[0]\n        spec_wave, spec_flux, spec_df, spec_s2n = \\\n            spec_wave[goodent], spec_flux[goodent], spec_df[goodent], spec_s2n[goodent]\n\n        template         = spec_dic['templatevec'][besttemplate_ent]\n        max_z            = spec_dic['zCCmaxvec'][besttemplate_ent]\n\n        t_wave_init, t_flux_init, t_df_init, t_s2n_init = felis.load_spectrum(template,verbose=verbose)\n        func       = scipy.interpolate.interp1d(t_wave_init,t_flux_init,kind='linear',fill_value=\"extrapolate\")\n        t_flux     = func(spec_wave)\n\n        # Getting the entry in the CC flux scalings vector for the given template where S/N is max\n        max_S2N_ent      = np.where(spec_dic['ccresultsarr_S2N'][besttemplate_ent,:] == max_S2N)[0][0]\n\n        Npix = len(spec_flux)\n        template_triplelength            = np.zeros(3*Npix)\n        template_triplelength[0:Npix]    = t_flux\n        template_shift_S2Nmax            = np.roll(template_triplelength, int(max_S2N_ent+np.floor(Npix/2.)))[Npix:-Npix]\n        template_shift_S2Nmax_normalized = template_shift_S2Nmax/np.trapz(template_shift_S2Nmax,spec_wave)\n\n        flux_scale_S2Nmax     = spec_dic['ccresultsarray_flux'][besttemplate_ent,max_S2N_ent]\n        max_wave              = spec_dic['wavelengths'][max_S2N_ent]\n\n        if verbose: print(' - Setting up and generating plot:\\n   '+plotname)\n        fig = plt.figure(figsize=(6, 7))\n        fig.subplots_adjust(wspace=0.1, hspace=0.5,left=0.1, right=0.99, bottom=0.07, top=0.91)\n        Fsize    = 9\n        lthick   = 2\n        marksize = 4\n        plt.rc('text', usetex=True)\n        plt.rc('font', family='serif',size=Fsize)\n        plt.rc('xtick', labelsize=Fsize)\n        plt.rc('ytick', labelsize=Fsize)\n        plt.clf()\n        plt.ioff()\n\n        # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n        ax = plt.subplot(4,1,1)\n\n        plt.plot(spec_wave,template_shift_S2Nmax_normalized,'g.',lw=lthick+1, markersize=marksize,alpha=1.0,\n                 label='Temp. at z(S/N$_\\\\textrm{max}$) = '+str(max_z))\n        plt.plot(spec_wave,flux_scale_S2Nmax * template_shift_S2Nmax_normalized,\n                 'g-',lw=lthick+2, markersize=marksize,alpha=1.0,\n                 label='Temp. flux$_\\\\textrm{tot}$ scale $\\\\alpha$ = '+str(\"%.4f\" % flux_scale_S2Nmax)+'')\n\n        Ftot_trapz = np.trapz(flux_scale_S2Nmax * template_shift_S2Nmax_normalized,spec_wave)\n\n        if spec_dic['continuumlevel'] != 0.0:\n            plt.plot(spec_wave,spec_flux+spec_dic['continuumlevel']*(1+z_spec),'k-',lw=lthick,\n                     markersize=marksize,alpha=0.5, label='Spectrum (w/ cont.)')\n            speclabel = 'Spectrum (w/o cont.)'\n        else:\n            speclabel = 'Spectrum (w/ cont.)'\n        plt.plot(spec_wave,spec_flux,'k-',lw=lthick, markersize=marksize,alpha=1.0,label=speclabel)\n\n        #what about...\n        #  plt.step(specdat['wave'],specdat['flux'],'r',where='mid')\n        #  plt.fill_between(specdat['wave'],specdat['flux']-specdat['fluxerror'],specdat['flux']+specdat['fluxerror'],step='mid',color='red',alpha=0.5)\n\n\n\n        if showspecerr:\n            plt.fill_between(spec_wave, spec_flux-spec_df, spec_flux+spec_df,color='black',alpha=0.2,label='Spectrum err')\n\n            SNlineYrange = [np.min(spec_flux-spec_df),np.max(spec_flux+spec_df)]\n        else:\n            SNlineYrange = [np.min(spec_flux),np.max(spec_flux)]\n\n        plt.plot([max_wave,max_wave],SNlineYrange,'--r',lw=lthick,\n                 markersize=marksize,alpha=1.0,label='S/N$_\\\\textrm{max}$ = '+str(\"%.4f\" % max_S2N)+'')\n\n        plt.xlabel(' Wavelength [A]')\n        plt.ylabel(' Flux ')\n        #plt.ylim([-2,6])\n        leg = plt.legend(fancybox=True, loc='upper center',prop={'size':Fsize/1.3},ncol=3,numpoints=1,\n                         bbox_to_anchor=(0.45, 1.43))  # add the legend\n        leg.get_frame().set_alpha(0.7)\n        # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n        plt.text(0.45, 1.45, 'Template No. '+str(int(besttemplate_ent+1))+'/'+str(len(spec_dic['templatevec']))+\n                 ': '+template.split('/')[-1].replace('_','\\_')+\n                 ' (Ftot\\_trapz = '+str(\"%.2f\" % Ftot_trapz)+')',\n                 fontsize=Fsize/1.3, horizontalalignment='center', transform=ax.transAxes)\n\n        # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n        plt.subplot(4,1,2)\n\n        plt.plot(spec_wave,spec_s2n,'k-',lw=lthick, markersize=marksize,alpha=0.5)\n        plt.plot(spec_wave,spec_flux/spec_df,'k-',lw=lthick, markersize=marksize,alpha=1.0)\n\n        plt.plot([max_wave,max_wave],[np.min(spec_flux/spec_df),np.max(spec_flux/spec_df)],'--r',lw=lthick,\n                 markersize=marksize,alpha=1.0)\n        plt.xlabel(' Wavelength [A]')\n        plt.ylabel(' Spectrum S/N ')\n\n        # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n        plt.subplot(4,1,3)\n        plt.plot(spec_dic['wavelengths'],spec_dic['ccresultsarr_S2N'][besttemplate_ent,:],'-r',lw=lthick, markersize=marksize,alpha=1.0)\n        plt.plot([max_wave,max_wave],[np.min(spec_dic['ccresultsarr_S2N'][besttemplate_ent,:]),\n                                      np.max(spec_dic['ccresultsarr_S2N'])],'--r',lw=lthick,\n                 markersize=marksize,alpha=1.0)\n        plt.xlabel(' Wavelength [A]')\n        plt.ylabel(' Cross-Correlation S/N')\n\n        # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n        plt.subplot(4,1,4)\n        plt.plot(spec_dic['wavelengths'],spec_dic['ccresultsarr_chi2'][besttemplate_ent,:],'-r',lw=lthick, markersize=marksize,alpha=1.0)\n        plt.plot([max_wave,max_wave],[np.min(spec_dic['ccresultsarr_chi2'][besttemplate_ent,:]),np.max(spec_dic['ccresultsarr_chi2'][besttemplate_ent,:])],'--r',lw=lthick,\n                 markersize=marksize,alpha=1.0)\n        plt.xlabel(' Wavelength [A]')\n        plt.ylabel(' $\\chi^2_\\\\textrm{min}$')\n\n        # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n        if verbose: print('   Saving plot to '+plotname)\n        plt.savefig(plotname)\n        plt.clf()\n        plt.close('all')\n\n# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\ndef minimize_chi2(data,data_sigma,template,temp_wave=None,verbose=True):\n    \"\"\"\n    Minimizing chi2 for a 1D template matching and returning the corresponding (flux) scaling, alpha.\n\n    Done using that\n        chi**2         = Sum_i (d_i - alpha * t_i)**2 / sigma_i**2\n    and that dchi**2/dalpha = 0 implies\n        alpha          = ( Sum_i d_i*t_i/sigma_i**2 ) / ( Sum_i t_i**2 / sigma_i**2 )\n        sigma_alpha**2 = 1 / Sum_ix( t_i**2 / sigma_i**2 ) = alpha_variance\n\n    Here, d is the data (flux from spectrum), sigma is the uncertainty on the data, t is the template,\n    alpha is the flux scaling of the template, sigma_alpha is the uncertainty on alpha, and i runs\n    over the pixels in the spectrum.\n\n    --- INPUT ---\n\n    data            Data to match template to\n    data_sigma      Uncertainty on data, i.e., sqrt(variance)\n    template        Normalized template to search for in data. Should be of the same lenght as data\n    temp_wave       Provide template wavelengths for normalization check if dlam is not 1.\n    verbose         Toggle verbosity\n\n    \"\"\"\n    normlim = 1e-10\n    if temp_wave is not None:\n        temp_int = np.trapz(template,temp_wave)\n    else:\n        temp_int = np.trapz(template)\n\n    if temp_int == 0: # all pixels are 0\n        pass\n    else:\n        sumdiff = np.abs(temp_int-1.0)\n        if sumdiff > normlim: #checking if provided template is normalized\n            raise ValueError('FELIS WARNING: Template is not normalized: |np.trapz(template,dwave)-1.0| = '+\n                             str(sumdiff)+' > '+str(normlim))\n\n    if len(data) == len(template):\n        Npix = len(data)\n    else:\n        sys.exit('The length of the data and template should be the same; it is not.')\n    if verbose: print(' - Will calculate and minimize chi**2 for data and template of length '+str(Npix))\n    goodent  = np.where((data_sigma > 0) & (np.isfinite(data)) & (template != 0))[0]\n    Ngoodent = len(goodent)\n\n    if Ngoodent == 0:\n        if verbose: print(' - No entries left where data_sigma > 0 & data is finite & template != 0, so returning 0s')\n        chi2_min        = 0.0\n        alpha           = 0.0\n        alpha_variance  = 0.0\n        S2N             = 0.0\n    else:\n        t2err2         = template[goodent]**2 / data_sigma[goodent]**2\n        alpha          = np.sum( data[goodent] * template[goodent] / data_sigma[goodent]**2 ) / np.sum(t2err2)\n        alpha_variance = 1.0 / np.sum(t2err2)\n\n        S2N            = alpha / np.sqrt(alpha_variance)\n        chi2_min       = np.sum( ( data[goodent]-alpha*template[goodent] )**2 / data_sigma[goodent]**2 )\n\n    return alpha, alpha_variance, S2N, chi2_min, Ngoodent\n# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\ndef cross_correlate_template(spectrum,template,z_restframe=None,waverange=None,\n                             min_template_level=1e-2,spec_median_sub=False,verbose=True):\n    \"\"\"\n    Function to cross-correlate a spectrum with a template using felis.minimize_chi2().\n    It can be run for multiple spectra with the wrapper match_templates2specs which also enables\n    easy plotting of the results.\n\n    --- INPUT ---\n    spectrum            fits spectrum to find a (cross-correlation) match to template for (flux in f_lambda)\n    template            fits template to correlate with\n    z_restframe         To perform cross-correlation in rest-frame (shifting the spectrum) provide a redshift.\n    waverange           To prevent running the cross-correlation on the full spectrum, provide the wavelength\n                        range (based on wavelength-vector in spectrum) to restrict the correlation to.\n    min_template_level  The template is interpolated to the wavelength grid of the spectrum and extrapolated\n                        beyond it's edges if nescessary. In this extrapolation (assuming the template goes to ~0\n                        at the edges), very small values (e.g., <1e-20) can be returned. To set these to 0.0\n                        provide a level below which all values in the interpolated template are treated as 0s.\n    spec_median_sub     If True, the median level (continuum?) of the spectrum is subtracted prior to matching.\n    verbose             Toggle verbosity\n\n    --- EXAMPLE OF USE ---\n    import felis\n\n    specdir  = '/Users/kschmidt/work/MUSE/uvEmissionlineSearch/felis_testing/'\n    spectrum = specdir+'uves_felis_mock_MUSEspectrum_noisesigma1p0.fits'\n    spectrum = specdir+'uves_felis_mock_MUSEspectrum_noisesigma0p05.fits'\n    template = specdir+'uves_felis_template_CIIIdoublet_sig_0p25_fluxCIII1_2p0_fluxratio_0p5.fits'\n\n    s_wave, ccresults, max_S2N, max_z, continuumlevel = felis.cross_correlate_template(spectrum,template,z_restframe=3.5,waverange=[8560,8610])\n\n    \"\"\"\n    if verbose: print(' - Loading spectrum and template to cross-correlate ')\n    s_wave, s_flux, s_df, s_s2n = felis.load_spectrum(spectrum,verbose=verbose)\n\n\n    if waverange is not None:\n        if verbose: print(' - Limiting the wavelength range to cross-correlate over ')\n        goodent = np.where( (s_wave > waverange[0]) & (s_wave < waverange[1]) )\n        s_wave, s_flux, s_df, s_s2n = s_wave[goodent], s_flux[goodent], s_df[goodent], s_s2n[goodent]\n\n    if verbose: print(' - Estimating continuum from spectrum (median value) in observed units')\n    if spec_median_sub:\n        continuumval = np.median(s_flux)\n    else:\n        continuumval = 0.0\n\n    if z_restframe is not None:\n        if verbose: print(' - Shifting spectrum to rest-frame using the redshift '+str(z_restframe))\n        s_wave, s_flux, s_df, s_s2n = s_wave / (1+z_restframe), s_flux * (1+z_restframe), s_df * (1+z_restframe), s_s2n\n    else:\n        z_restframe=0.0\n\n    if verbose: print(' - Removing continuum from spectrum ')\n    s_flux       = s_flux - continuumval * (1.0+z_restframe)\n\n    if verbose: print(' - Interpolate template to spectrums wavelength resolution before cross-correlating')\n    t_wave_init, t_flux_init, t_df_init, t_s2n_init = felis.load_spectrum(template,verbose=verbose)\n    func       = scipy.interpolate.interp1d(t_wave_init,t_flux_init,kind='linear',fill_value=\"extrapolate\")\n    t_flux     = func(s_wave)\n    t_flux[t_flux < min_template_level] = 0.0\n\n    if verbose: print(' - Normalizing total template flux to 1')\n    if len(t_flux[t_flux != 0]) == 0:\n        if verbose: print('   FELIS WARNING All interpolated template pixels are 0.0')\n    else:\n        temp_int = np.trapz(t_flux,s_wave)\n        t_flux   = t_flux / temp_int\n\n    Npix = len(s_flux)\n\n    template_triplelength = np.zeros(3*Npix)\n    template_triplelength[0:Npix] = t_flux\n\n    ccresults = np.zeros([Npix,5])\n\n    for ii in np.arange(Npix):\n        rollsize       = int(ii+np.floor(Npix/2.))\n        template_shift = np.roll(template_triplelength, rollsize)[Npix:-Npix]\n\n        normlim   = 1e-10\n        temp_int  = np.trapz(template_shift,s_wave)\n        sumdiff   = np.abs(temp_int-1.0)\n        if sumdiff > normlim: # make sure \"half-template\" shifts are also normalized\n            if temp_int == 0: # only attempt normalization if template is not just zeros\n                pass\n            else:\n                template_shift   = template_shift / temp_int\n\n        try:\n            flux_scale, flux_scale_variance, S2N, chi2_min, NgoodentChi2 = \\\n                felis.minimize_chi2(s_flux,s_df,template_shift,temp_wave=s_wave,verbose=False)\n\n            ccresults[ii,:] = flux_scale, flux_scale_variance, S2N, chi2_min, NgoodentChi2\n        except:\n            print(' ERROR: Problems in minimizing Chi**2 with felis.minimize_chi2() while cross-correlating. '\n                  'Stopping for further investigation')\n\n            pdb.set_trace()\n\n    max_S2N     = np.max(ccresults[:,2])\n    max_S2N_ent = np.where(ccresults[:,2] == max_S2N)[0][0]\n    max_wave    = s_wave[max_S2N_ent]\n\n    dlam     = np.median(np.diff(s_wave))\n    t_wave   = np.arange(np.min(t_wave_init),np.max(t_wave_init),dlam)\n    t_cenent = int(np.ceil(len(t_wave)/2))\n    max_z    = (max_wave*(z_restframe+1.0) / t_wave[t_cenent]) - 1.0\n\n    return  s_wave, ccresults, max_S2N, max_z, continuumval\n\n# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\ndef load_spectrum(specfile,verbose=True):\n    \"\"\"\n    Loading spectrum generated with felis.save_spectrum() or TDOSE.\n\n    --- INPUT ---\n\n    --- EXAMPLE OF USE ---\n    import felis\n    specfile  = './spectrum_output.fits'\n    w, f, df, s2n = felis.load_spectrum(specfile)\n\n    \"\"\"\n    if verbose: print(' - Loading SPEC1D extension (spectrum) of \\n   '+specfile)\n    dat = fits.open(specfile)['SPEC1D'].data\n\n    wave    = dat['wave']\n    flux    = dat['flux']\n    fluxerr = dat['fluxerror']\n    s2n     = dat['s2n']\n\n    return wave, flux, fluxerr, s2n\n# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\ndef save_spectrum(outfile,wave,flux,fluxerr,headerinfo=None,waveunits='ANGSTROMS',fluxunits='',overwrite=False,verbose=True):\n    \"\"\"\n    Function saving a spectrum (or template) to a fits file\n\n    --- INPUT ---\n    outfile         Name of output file to generate\n    wave            Wavelength in units of Angstrom\n    flux            Flux to store to fits file\n    fluxerr         Error un flux\n    headerinfo      To add info to the header provide it to this keyword as a dictionary on the format:\n                       headerinfo = {'KEYNAME1':[VALUE1,INFOCOMMENT1], 'KEYNAME2':[VALUE2,INFOCOMMENT2]}\n    waveunits       Units of wave vector to store in fits header\n    fluxunits       Units of flux to store in fits header\n    overwrite       Overwrite existing file?\n    verbose         Toggle verbosity\n\n    --- EXAMPLE OF USE ---\n    import felis\n    import numpy as np\n    wave        = np.arange(1,100,1)\n    flux        = wave**0.5 + (wave*0.0+2.3)\n    fluxerr     = np.sqrt(flux)\n    headerinfo  = {'FEL_EL1':[1548,'Wave of FELIS line 1 in template'], 'FEL_EL2':[1551,'Wave of FELIS line 2 in template']}\n    outfile     = './spectrum_output.fits'\n\n    felis.save_spectrum(outfile,wave,flux,fluxerr,headerinfo=headerinfo,overwrite=False,verbose=True)\n\n\n    \"\"\"\n    S2N = flux/fluxerr\n\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n    if verbose: print(' - Saving wavelength and flux values to \\n   '+outfile)\n    mainHDU = fits.PrimaryHDU()       # primary HDU\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n    c1 = fits.Column(name='wave',      format='D', unit=waveunits, array=wave)\n    c2 = fits.Column(name='flux',      format='D', unit=fluxunits, array=flux)\n    c3 = fits.Column(name='fluxerror', format='D', unit=fluxunits, array=fluxerr)\n    c4 = fits.Column(name='s2n',       format='D', unit='', array=S2N)\n\n    coldefs = fits.ColDefs([c1,c2,c3,c4])\n    tbHDU   = fits.BinTableHDU.from_columns(coldefs) # creating default header\n\n    # writing hdrkeys:'---KEY--',                             '----------------MAX LENGTH COMMENT-------------'\n    tbHDU.header.append(('EXTNAME ','SPEC1D'                     ,'cube containing source'),end=True)\n    if headerinfo is not None:\n        for key in headerinfo.keys():\n            tbHDU.header.append((key,headerinfo[key][0],headerinfo[key][1]),end=True)\n\n    hdulist = fits.HDUList([mainHDU,tbHDU])\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n    hdulist.writeto(outfile, overwrite=overwrite)\n# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\ndef save_dictionary(dictionary, output='./saveddictionary_RENAME_.pkl'):\n    with open(output, 'wb') as f:\n        pickle.dump(dictionary, f, pickle.HIGHEST_PROTOCOL)\n# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\ndef load_picklefile(picklefile):\n    pversion = sys.version_info[0]\n    with open(picklefile, 'rb') as f:\n        if pversion == 2:\n            return pickle.load(f) # for python 2.X\n        elif pversion == 3:\n            return pickle.load(f, encoding='latin1') # for python 3.X\n        else:\n            sys.exit('   felis.load_picklefile() saw unknown version of python: version = '+str(pversion))\n# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\ndef getresult4maxS2N(dictionary,dictionarykey,zspecISzLya=False):\n    \"\"\"\n    Function returning results at maxmimum S/N for the template with maximum S/N overall, for a given\n    dictionary keyword of the pickled FELIS output.\n\n    --- INPUT ---\n    dictionary      = Dictionary containing FELIS outputs, i.e. the output from felis.load_picklefile()\n    dictionarykey   = The object/spectrum (dictionary key) to return results for\n    zspecISzLya         If picklefile contains zLya keyword insead of zspec (was generated before 180912), set this\n                        keyword to True to enable proper handling of the dictionary keywords.\n\n    \"\"\"\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n    # Ensure compatibility with FELIS output dictionaries from before 180912\n    zkey = 'zspec'\n    if zspecISzLya: zkey = 'zLya'\n    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n    keys = dictionary.keys()\n    if dictionarykey in keys:\n        keydic        = dictionary[dictionarykey]\n        S2Nmaxvec     = keydic['S2NCCmaxvec']\n        S2Nmax        = np.max(S2Nmaxvec)\n        templateent   = np.where(S2Nmaxvec == S2Nmax)[0]\n        if len(templateent) > 1:\n            print('    FELIS WARNING felis.getresult4maxS2N(): \\n    Multiple templates ('+str(len(templateent))+' of '+\n                  str(len(S2Nmaxvec))+' templates) share the same maximum S/N ('+str(S2Nmax)+\n                  ') of cross-correlation for \\n   '+dictionarykey)\n            print('   Will return the results for the first template')\n            templateent = np.array([templateent[0]])\n\n        template      = keydic['templatevec'][templateent][0]\n        zS2Nmax       = keydic['zCCmaxvec'][templateent][0]\n        zspec         = keydic[zkey]\n        vshift_match  = 299792.458 * (zspec - zS2Nmax)/(1.0+zS2Nmax) # cf. Erb+2014\n\n        if 'vshift' in keydic.keys():\n            vshift_intr   = keydic['vshift'] # velocity shift stored in dictionary with felis.match_templates2specs()\n        else:\n            vshift_intr   = -99\n\n        S2Nvec        = keydic['ccresultsarr_S2N'][templateent][0]\n        S2Nvecmax     = np.where(S2Nvec == np.max(S2Nvec))[0]\n\n        flux          = keydic['ccresultsarray_flux'][templateent,S2Nvecmax][0]\n        fluxerr       = np.sqrt(keydic['ccresultsarray_variance'][templateent,S2Nvecmax][0])\n        Ngoodent      = keydic['ccresultsarr_Ngoodent'][templateent,S2Nvecmax][0]\n        chi2          = keydic['ccresultsarr_chi2'][templateent,S2Nvecmax][0]\n    else:\n        template      = 'None'\n        vshift_intr   = -99.0\n        vshift_match  = -99.0\n        S2Nmax        = -99.0\n        flux          = -99.0\n        fluxerr       = -99.0\n        Ngoodent      = -99.0\n        chi2          = -99.0\n\n    return template, vshift_intr, vshift_match, flux, fluxerr, S2Nmax, Ngoodent, chi2, zspec, zS2Nmax\n# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\n", "meta": {"hexsha": "b41ebc42d96bc3664df7d2c43c1de152d80fac16", "size": 39893, "ext": "py", "lang": "Python", "max_stars_repo_path": "felis.py", "max_stars_repo_name": "kasperschmidt/FELIS", "max_stars_repo_head_hexsha": "beece4545bfc6dcb4da11337a9f9481ad6d116ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-10-24T14:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-02T00:09:34.000Z", "max_issues_repo_path": "felis.py", "max_issues_repo_name": "kasperschmidt/FELIS", "max_issues_repo_head_hexsha": "beece4545bfc6dcb4da11337a9f9481ad6d116ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "felis.py", "max_forks_repo_name": "kasperschmidt/FELIS", "max_forks_repo_head_hexsha": "beece4545bfc6dcb4da11337a9f9481ad6d116ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.261682243, "max_line_length": 171, "alphanum_fraction": 0.5913819467, "include": true, "reason": "import numpy,import scipy,from astropy", "num_tokens": 11140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.2942149783515163, "lm_q1q2_score": 0.1608585492042642}}
{"text": "#!/usr/bin/env python3\n\nimport logging\nimport math\nimport random\nimport time\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass\nfrom typing import (\n    Iterable,\n    Mapping,\n    MutableMapping,\n    MutableSequence,\n    Optional,\n    Sequence,\n    Set,\n    Tuple,\n    Union,\n)\n\nimport numpy as np\nimport torch\nfrom reagent.ope.estimators.estimator import (\n    Estimator,\n    EstimatorResult,\n    EstimatorSampleResult,\n)\nfrom reagent.ope.estimators.types import (\n    Action,\n    Items,\n    Objects,\n    Probability,\n    Reward,\n    Trainer,\n    TrainingData,\n    TypeWrapper,\n    Values,\n    ValueType,\n)\nfrom reagent.ope.utils import Clamper, RunningAverage\nfrom torch import Tensor\n\n\n# Main algorithms are from two papers:\n#   1. Offline Evaluation of Ranking Policies with Click Models\n#      https://arxiv.org/abs/1804.10488\n#   2. Off-policy evaluation for slate recommendation\n#      https://arxiv.org/abs/1605.04812\n\n# Types for slates\nSlateSlotType = Union[int, Tuple[int], float, Tuple[float], np.ndarray, Tensor]\nSlateSlot = TypeWrapper[SlateSlotType]\n\n\nclass SlateSlotValues(Values[SlateSlot]):\n    \"\"\"\n    Map from a slot to a value\n    \"\"\"\n\n    def _to_key(self, k: int) -> SlateSlot:\n        return SlateSlot(k)\n\n\nclass SlateSlots(Items[SlateSlot]):\n    \"\"\"\n    List of slot\n    \"\"\"\n\n    def _new_item(self, i: int) -> SlateSlot:\n        return SlateSlot(i)\n\n    def fill(\n        self,\n        values: Union[Mapping[SlateSlot, float], Sequence[float], np.ndarray, Tensor],\n    ) -> SlateSlotValues:\n        \"\"\"\n        Map slots to given values\n        Args:\n            values: given values\n\n        Returns:\n            Map from slots to given values\n        \"\"\"\n        return SlateSlotValues(super().fill(values))\n\n\nclass SlateSlotObjects(Objects[SlateSlot, ValueType]):\n    def __init__(\n        self,\n        values: Union[MutableMapping[SlateSlot, ValueType], MutableSequence[ValueType]],\n    ):\n        assert (len(values)) > 0\n        super().__init__(values)\n\n    def _to_key(self, k: int) -> SlateSlot:\n        return SlateSlot(k)\n\n    @property\n    def slots(self) -> SlateSlots:\n        if self.is_sequence:\n            return SlateSlots(len(self._values))\n        else:\n            return SlateSlots(list(self._key_to_index.keys()))\n\n    @property\n    def objects(self) -> Sequence[ValueType]:\n        return super().values\n\n    def fill(\n        self, values: Sequence[ValueType]\n    ) -> Union[Mapping[SlateSlot, ValueType], Sequence[ValueType]]:\n        assert len(values) >= len(self._values)\n        if self._key_to_index is None:\n            return values[: len(self._values)]\n        else:\n            return {s: v for s, v in zip(self.slots, values[: len(self._values)])}\n\n\n# type of valid slate candidates, e.g., doc id\nSlateItem = Action\n\n\nclass SlateItems(Items[SlateItem]):\n    def _new_item(self, i: int) -> SlateItem:\n        return SlateItem(i)\n\n\nclass SlateItemValues(Values[SlateItem]):\n    def _to_key(self, k: int) -> SlateItem:\n        return SlateItem(k)\n\n    @property\n    def items(self) -> SlateItems:\n        if self.is_sequence:\n            return SlateItems(len(self))\n        else:\n            return SlateItems(super().keys)\n\n\nclass SlateItemFeatures(Objects[SlateItem, Tensor]):\n    def __init__(\n        self,\n        values: Union[Mapping[SlateItem, Tensor], Sequence[Tensor], Tensor, np.ndarray],\n    ):\n        super().__init__(values)\n\n    def _init_values(\n        self,\n        values: Union[Mapping[SlateItem, Tensor], Sequence[Tensor], Tensor, np.ndarray],\n    ):\n        if isinstance(values, Tensor):\n            self._values = values.to(dtype=torch.double)\n        elif isinstance(values, np.ndarray):\n            self._values = torch.as_tensor(values, dtype=torch.double)\n        elif isinstance(values, Sequence):\n            self._values = torch.stack(values).to(dtype=torch.double)\n        elif isinstance(values, Mapping):\n            self._key_to_index = dict(zip(values.keys(), range(len(values))))\n            self._index_to_key = list(values.keys())\n            self._values = torch.stack(list(values.values())).to(dtype=torch.double)\n        else:\n            raise TypeError(f\"Unsupported values type {type(values)}\")\n\n    def _to_key(self, k: int) -> SlateItem:\n        return SlateItem(k)\n\n    @property\n    def items(self) -> SlateItems:\n        if self.is_sequence:\n            return SlateItems(len(self))\n        else:\n            return SlateItems(super().keys)\n\n\n# SlateSlotFeatures = SlateSlotObjects[Tensor]\nclass SlateSlotFeatures(SlateSlotObjects[Tensor]):\n    @property\n    def features(self) -> Tensor:\n        return torch.stack(self._values)\n\n\nclass Slate(SlateSlotObjects[SlateItem]):\n    \"\"\"\n    Class represents a slate: map from slots to items/docs\n    \"\"\"\n\n    def one_hots(self, items: SlateItems, device=None) -> Tensor:\n        oh = torch.zeros((len(self), len(items)), dtype=torch.double, device=device)\n        for t, i in zip(oh, self._values):\n            t[items.index_of(i)] = 1.0\n        return oh\n\n    @property\n    def items(self) -> Sequence[SlateItem]:\n        return super().values\n\n    def slot_values(self, item_values: SlateItemValues) -> SlateSlotValues:\n        \"\"\"\n        Map items in the slate to given values\n        Args:\n            item_values: Map from all items to some values\n\n        Returns:\n            List of values in the slate\n        \"\"\"\n        if self._key_to_index is None:\n            return SlateSlotValues([item_values[i] for i in self._values])\n        else:\n            return SlateSlotValues({k: item_values[i] for k, i in self._key_to_index})\n\n    def slot_features(self, item_features: SlateItemFeatures) -> SlateSlotFeatures:\n        \"\"\"\n        Map items in the slate to given values\n        Args:\n            item_values: Map from all items to some values\n\n        Returns:\n            List of values in the slate\n        \"\"\"\n        if self._key_to_index is None:\n            return SlateSlotFeatures(\n                [item_features[i].detach().clone() for i in self._values]\n            )\n        else:\n            return SlateSlotFeatures(\n                {k: item_features[i].detach().clone() for k, i in self._key_to_index}\n            )\n\n    def __repr__(self):\n        return f\"{self.__class__.__name__}{{value[{self._values}]}}\"\n\n\ndef make_slate(slots: SlateSlots, items: Sequence[SlateItem]) -> Slate:\n    \"\"\"\n    Assign items to slots to make a slate\n    \"\"\"\n    assert len(items) >= len(slots)\n    if slots.is_sequence:\n        return Slate(list(items[: len(slots)]))\n    else:\n        return Slate(dict(zip(slots, items[: len(slots)])))\n\n\nclass SlateSlotItemValues(SlateSlotObjects[SlateItemValues]):\n    def __init__(\n        self,\n        values: Union[\n            MutableMapping[SlateSlot, SlateItemValues], MutableSequence[SlateItemValues]\n        ],\n    ):\n        super().__init__(values)\n        self._item_size = len(self._values[0])\n        for v in self._values[1:]:\n            assert self._item_size == len(v)\n\n    def values_tensor(self, device=None) -> Tensor:\n        dist = [v.values for v in self._values]\n        return torch.stack(dist).to(device=device)\n\n\nclass SlateSlotItemExpectations(SlateSlotItemValues):\n    def expected_rewards(\n        self, item_rewards: SlateItemValues, device=None\n    ) -> SlateSlotValues:\n        \"\"\"\n        Calculate expected relevances of each slot, given each item's\n        relevances, under this distribution\n        Args:\n            item_rewards:\n            device:\n\n        Returns:\n            Map of slots to their expected relevance\n        \"\"\"\n        dist = self.values_tensor(device)\n        rewards = item_rewards.values.to(device=device)\n        rewards = torch.mm(dist, rewards.unsqueeze(0).t()).squeeze()\n        if self.is_sequence:\n            return SlateSlotValues(rewards)\n        else:\n            return SlateSlotValues(dict(zip(self.slots, rewards.tolist())))\n\n    @property\n    def expectations(self) -> Sequence[SlateItemValues]:\n        return super().values\n\n\ndef make_slot_item_distributions(\n    slots: SlateSlots, dists: Sequence[SlateItemValues]\n) -> SlateSlotItemExpectations:\n    assert len(dists) >= len(slots)\n    if slots.is_sequence:\n        return SlateSlotItemExpectations(list(dists[: len(slots)]))\n    else:\n        return SlateSlotItemExpectations(dict(zip(slots, dists[: len(slots)])))\n\n\ndef is_to_calculate_expectation(slate_size: int, item_size: int) -> bool:\n    \"\"\"\n    Switch between calculating and sampling expectations, balanced by execution\n    time and accuracy\n    Return:\n        True to calculate\n        False to sample\n    \"\"\"\n    return (\n        slate_size < 4\n        or (slate_size == 4 and item_size < 182)\n        or (slate_size == 5 and item_size < 47)\n        or (slate_size == 6 and item_size < 22)\n        or (slate_size == 7 and item_size < 15)\n    )\n\n\ndef _calculate_slot_expectation(\n    d_out: Tensor,\n    probs: Sequence[float],\n    buffer: Iterable[Tuple[Set[int], float, float, float]],\n) -> Iterable[Tuple[Set[int], float, float, float]]:\n    \"\"\"\n    A helper function to calculate items' expectations for a slot\n    \"\"\"\n    assert d_out.shape[0] == len(probs)\n    next_buffer = []\n    for b0, b1, b2, _ in buffer:\n        # memory buffer for all ordered combinations so far, list of tuples of\n        #   b0: all the items in this ordered combination\n        #   b1: cumulative probability of b0\n        #   b2: sum of the probabilities of b0\n        #   b3: = b1 / (1.0 - b2) cached value for faster computation\n        for i, i_prob in enumerate(probs):\n            # only add i if it's not already in\n            if i in b0:\n                continue\n            # nb* are next buffer values\n            nb2 = b2 + i_prob\n            # due to precision errors, sometimes nb2 becomes 1, in this\n            # case, discard the combination\n            if nb2 < 1.0:\n                nb1 = b1 * i_prob / (1.0 - b2)\n                next_buffer.append(({*b0, i}, nb1, nb2, nb1 / (1.0 - nb2)))\n    for i, i_prob in enumerate(probs):\n        p = 0.0\n        for b0, _, _, b3 in next_buffer:\n            if i in b0:\n                continue\n            p += b3\n        d_out[i] = p * i_prob\n    return next_buffer\n\n\nclass SlateItemProbabilities(SlateItemValues):\n    \"\"\"\n    Probabilities of each item being selected into the slate\n    \"\"\"\n\n    def __init__(\n        self,\n        values: Union[Mapping[SlateItem, float], Sequence[float], np.ndarray, Tensor],\n        greedy: bool = False,\n    ):\n        super().__init__(values)\n        self._greedy = greedy\n        self._slot_item_expectations = None\n\n    def _to_key(self, k: int) -> SlateItem:\n        return SlateItem(k)\n\n    def _reset(self):\n        super()._reset()\n        self._slot_item_expectations = None\n\n    def slate_probability(self, slate: Slate) -> Probability:\n        \"\"\"\n        Calculate probability of a slate under this distribution\n        Args:\n            slate:\n\n        Returns:\n            probability\n        \"\"\"\n        if self._greedy:\n            items = super().greedy(len(slate))\n            for i1, i2 in zip(items, slate.items):\n                if i1 != i2:\n                    return 0.0\n            return 1.0\n        else:\n            clamped = torch.clamp(self._values, 0.0)\n            indices = [self.index_of(item) for _, item in slate]\n            probs = clamped[indices]\n            sums = clamped[indices]\n            clamped[indices] = 0.0\n            sums = sums.flip(0).cumsum(0).flip(0) + clamped.sum()\n            return Probability((probs / sums).prod().item())\n\n    def slot_item_expectations(self, slots: SlateSlots) -> SlateSlotItemExpectations:\n        slate_size = len(slots)\n        if (\n            self._slot_item_expectations is not None\n            and len(self._slot_item_expectations) >= slate_size\n        ):\n            return self._slot_item_expectations\n        item_size = len(self)\n        assert item_size >= slate_size\n        if self._greedy:\n            self._slot_item_expectations = make_slot_item_distributions(\n                slots,\n                [\n                    self.replace(torch.zeros(item_size, dtype=torch.double))\n                    for _ in range(len(self))\n                ],\n            )\n            sorted_items, _ = self.sort()\n            for item, ds in zip(\n                sorted_items, self._slot_item_expectations.expectations\n            ):\n                ds[item] = 1.0\n        else:\n            self._normalize()\n            if is_to_calculate_expectation(len(slots), len(self)):\n                self._calculate_expectations(slots)\n            else:\n                self._sample_expectations(slots, 20000)\n        return self._slot_item_expectations\n\n    def _sample_expectations(self, slots: SlateSlots, num_samples: int):\n        slate_size = len(slots)\n        item_size = len(self)\n        dm = torch.zeros((slate_size, item_size), dtype=torch.double)\n        ri = torch.arange(slate_size)\n        ws = self._probabilities.repeat((num_samples, 1))\n        for _ in range(item_size):\n            samples = torch.multinomial(ws, slate_size)\n            for sample in samples:\n                dm[ri, sample] += 1\n        dm /= num_samples * item_size\n        self._slot_item_expectations = make_slot_item_distributions(\n            slots, [self.replace(vs) for vs in dm]\n        )\n\n    def _calculate_expectations(self, slots: SlateSlots):\n        \"\"\"\n        A brute-force way to calculate each item's expectations at each slot by\n        going through all l-choose-m (l!/(l-m)!) possible slates.\n        \"\"\"\n        slate_size = len(slots)\n        item_size = len(self)\n        dm = torch.zeros((slate_size, item_size), dtype=torch.double)\n        dm[0] = self._probabilities\n        buffer = [({}, 1.0, 0.0, 1.0)]\n        probs = self._probabilities.tolist()\n        for d in dm[1:]:\n            buffer = _calculate_slot_expectation(d, probs, buffer)\n        self._slot_item_expectations = make_slot_item_distributions(\n            slots, [self.replace(vs) for vs in dm]\n        )\n\n    def sample_slate(self, slots: SlateSlots) -> Slate:\n        slate_size = len(slots)\n        if self._greedy:\n            items = super().greedy(slate_size)\n        else:\n            items = super().sample(slate_size)\n        if slate_size == 1:\n            items = [items]\n        return make_slate(slots, items)\n\n    @property\n    def is_deterministic(self) -> bool:\n        return self._greedy\n\n    def slate_space(\n        self, slots: SlateSlots, max_size: int = -1\n    ) -> Iterable[Tuple[Sequence[SlateItem], float]]:\n        \"\"\"Return all possible slates and their probabilities\n\n        The algorithm is similar to :func:`~_calculate_expectations`, but has\n        less value to cache thus save both space and computation\n        Args:\n            slots: slots to be filled\n            max_size: max number of samples to be returned\n                      <= 0 return all samples\n        \"\"\"\n        slate_size = len(slots)\n        item_size = len(self)\n        assert item_size >= slate_size\n        if self._greedy:\n            items = super().greedy(slate_size)\n            return [(items, 1.0)]\n        else:\n            buffer = [([], 1.0, 0.0)]\n            probs = self._probabilities.tolist()\n            for _ in range(slate_size):\n                next_buffer = []\n                for b0, b1, b2 in buffer:\n                    # memory buffer for all ordered combinations so far, list of tuples of\n                    #   b0: all the items in this ordered combination\n                    #   b1: cumulative probability of b0\n                    #   b2: sum of the probabilities of b0\n                    for i, i_prob in enumerate(probs):\n                        if i in b0:\n                            continue\n                        nb2 = b2 + i_prob\n                        if nb2 < 1.0:\n                            nb1 = b1 * i_prob / (1.0 - b2)\n                            next_buffer.append(([*b0, i], nb1, nb2))\n                if max_size <= 0 or max_size > len(next_buffer):\n                    buffer = next_buffer\n                else:\n                    buffer = random.sample(next_buffer, max_size)\n            return [([SlateItem(i) for i in b[0]], b[1]) for b in buffer]\n\n\nclass SlateSlotItemProbabilities(SlateSlotItemValues):\n    def __init__(\n        self,\n        values: Union[\n            MutableMapping[SlateSlot, SlateItemValues], MutableSequence[SlateItemValues]\n        ],\n        greedy: bool = False,\n    ):\n        super().__init__(values)\n        self._greedy = greedy\n        self._slot_item_distributions = None\n        self._slot_item_expectations = None\n\n    def slate_probability(self, slate: Slate) -> Probability:\n        \"\"\"\n        Calculate probability of a slate under this distribution\n        Args:\n            slate:\n\n        Returns:\n            probability\n        \"\"\"\n        assert len(slate) <= len(self)\n        if self._greedy:\n            for slot, item in slate:\n                probs = self[slot]\n                its, _ = probs.sort()\n                if its[0] != item:\n                    return 0.0\n            return 1.0\n        else:\n            p = 1.0\n            last_items = []\n            for slot, item in slate:\n                item_probs = self[slot]\n                w = 1.0\n                for last_item in last_items:\n                    w -= item_probs.probability(last_item)\n                if math.fabs(w - 0.0) < 1.0e-10:\n                    return 0.0\n                p *= item_probs.probability(item) / w\n                last_items.append(item)\n            return p\n\n    def slot_item_expectations(self, samples: int = 20000) -> SlateSlotItemExpectations:\n        slate_size = len(self.slots)\n        if (\n            self._slot_item_expectations is not None\n            and len(self._slot_item_expectations) >= slate_size\n        ):\n            return self._slot_item_expectations\n        item_size = len(self._values[0])\n        assert item_size >= slate_size\n        ps = self.values_tensor()\n        if self._greedy:\n            dists = []\n            for i, value in zip(range(slate_size), self._values):\n                item = ps[i].argmax().item()\n                dist = torch.zeros(item_size, dtype=torch.double)\n                dist[item] = 1.0\n                dists.append(value.replace(dist))\n                ps[torch.arange(i + 1, slate_size), item] = 0.0\n            self._slot_item_expectations = make_slot_item_distributions(\n                self.slots, dists\n            )\n        else:\n            if is_to_calculate_expectation(slate_size, item_size):\n                self._calculate_expectations()\n            else:\n                self._sample_expectations(samples * item_size)\n        return self._slot_item_expectations\n\n    def _sample_expectations(self, num_samples: int):\n        slate_size = len(self.slots)\n        item_size = len(self._values[0])\n        dm = torch.zeros((slate_size, item_size), dtype=torch.double)\n        ri = torch.arange(slate_size)\n        for _ in range(num_samples):\n            ps = self.values_tensor()\n            sample = []\n            for i in range(slate_size):\n                item = ps[i].multinomial(1)\n                sample.append(item)\n                ps[torch.arange(i + 1, slate_size), item] = 0.0\n            dm[ri, sample] += 1\n        dm /= num_samples\n        self._slot_item_expectations = make_slot_item_distributions(\n            self.slots, [ivs.replace(vs) for ivs, vs in zip(self._values, dm)]\n        )\n\n    def _calculate_expectations(self):\n        slate_size = len(self.slots)\n        item_size = len(self._values[0])\n        dm = torch.zeros((slate_size, item_size), dtype=torch.double)\n        prob_list = []\n        for v in self._values:\n            v._normalize()\n            prob_list.append(v._probabilities.detach().clone())\n        dm[0] = prob_list[0]\n        buffer = [({}, 1.0, 0.0, 1.0)]\n        for d, probs in zip(dm[1:], prob_list[1:]):\n            buffer = _calculate_slot_expectation(d, probs.tolist(), buffer)\n        self._slot_item_expectations = make_slot_item_distributions(\n            self.slots, [its.replace(vs) for its, vs in zip(self._values, dm)]\n        )\n\n    def sample_slate(self, slots: SlateSlots) -> Slate:\n        slate_size = len(slots)\n        ps = self.values_tensor()\n        items = []\n        if self._greedy:\n            for i, value in zip(range(slate_size), self._values):\n                item = ps[i].argmax().item()\n                items.append(value.items[item])\n                ps[torch.arange(i + 1, slate_size), item] = 0.0\n        else:\n            for i, value in zip(range(slate_size), self._values):\n                item = ps[i].multinomial(1).item()\n                items.append(value.items[item])\n                ps[torch.arange(i + 1, slate_size), item] = 0.0\n        return make_slate(slots, items)\n\n\nclass RewardDistribution(ABC):\n    \"\"\"\n    Return customized probability distribution according to rewards\n    \"\"\"\n\n    def __init__(self, deterministic: bool = False):\n        self._deterministic = deterministic\n\n    @abstractmethod\n    def distribution(self, rewards: Tensor) -> Tensor:\n        pass\n\n    def __call__(self, rewards: SlateItemValues) -> SlateItemProbabilities:\n        dist = self.distribution(rewards.values)\n        return SlateItemProbabilities(rewards.items.fill(dist), self._deterministic)\n\n    @property\n    @abstractmethod\n    def name(self) -> str:\n        pass\n\n\nclass PassThruDistribution(RewardDistribution):\n    \"\"\"\n    No-op distribution, probability determined by reward\n    \"\"\"\n\n    def distribution(self, rewards: Tensor) -> Tensor:\n        return rewards.detach().clone()\n\n    @property\n    def name(self) -> str:\n        return f\"{self._deterministic}\"\n\n    def __repr__(self):\n        return f\"PassThruDistribution[deterministic={self._deterministic}]\"\n\n\nclass RankingDistribution(RewardDistribution):\n    \"\"\"\n    Ranking distribution according to https://arxiv.org/abs/1605.04812\n    \"\"\"\n\n    def __init__(self, alpha: float = -1.0, deterministic: bool = False):\n        super().__init__(deterministic)\n        self._alpha = alpha\n\n    def distribution(self, rewards: Tensor) -> Tensor:\n        dist = rewards.detach().clone()\n        if self._alpha >= 0:\n            _, ids = torch.sort(rewards, descending=True)\n            rank = torch.arange(1, ids.shape[0] + 1, dtype=torch.double)\n            dist[ids] = torch.pow(\n                2.0, (-1.0 * (self._alpha * torch.log2(rank)).floor_())\n            )\n        return dist\n\n    @property\n    def name(self) -> str:\n        return f\"ranking_{self._alpha}_{self._deterministic}\"\n\n    def __repr__(self):\n        return (\n            f\"RankingDistribution[alpha={self._alpha}\"\n            f\",deterministic={self._deterministic}]\"\n        )\n\n\nclass FrechetDistribution(RewardDistribution):\n    \"\"\"\n    Frechet distribution\n    \"\"\"\n\n    def __init__(self, shape: float, deterministic: bool = False):\n        super().__init__(deterministic)\n        self._shape = shape\n\n    def distribution(self, rewards: Tensor) -> Tensor:\n        return torch.pow(rewards, self._shape)\n\n    @property\n    def name(self) -> str:\n        return f\"frechet_{self._shape}_{self._deterministic}\"\n\n    def __repr__(self):\n        return (\n            f\"FrechetDistribution[shape={self._shape}]\"\n            f\",deterministic={self._deterministic}]\"\n        )\n\n\nSlateQueryType = Union[int, Tuple[int], float, Tuple[float], np.ndarray, Tensor]\nSlateQuery = TypeWrapper[SlateQueryType]\n\n\n@dataclass(frozen=True)\nclass SlateContext:\n    query: SlateQuery\n    slots: SlateSlots\n    params: object = None\n\n\nclass SlatePolicy(ABC):\n    \"\"\"\n    Policy interface\n    \"\"\"\n\n    def __init__(self, device=None):\n        self.device = device\n\n    @abstractmethod\n    def _query(self, context: SlateContext) -> SlateItemProbabilities:\n        pass\n\n    def __call__(self, context: SlateContext) -> SlateItemProbabilities:\n        return self._query(context)\n\n\nclass SlateMetric:\n    \"\"\"\n    Metric calculator for a slate: weights (dot) rewards\n\n    Base class is just sum of the all item rewards\n    \"\"\"\n\n    def __init__(self, device=None):\n        self._device = device\n\n    def calculate_reward(\n        self,\n        slots: SlateSlots,\n        rewards: SlateSlotValues = None,\n        slot_values: SlateSlotValues = None,\n        slot_weights: SlateSlotValues = None,\n    ) -> float:\n        if slot_values is None:\n            slot_values = self.slot_values(rewards)\n        values = slot_values.values.to(device=self._device)\n        if slot_weights is None:\n            slot_weights = self.slot_weights(slots)\n        weights = slot_weights.values.to(device=self._device)\n        return torch.tensordot(values, weights, dims=([0], [0])).item()\n\n    def __call__(self, slots: SlateSlots, rewards: SlateSlotValues) -> float:\n        return self.calculate_reward(slots, rewards)\n\n    def slot_weights(self, slots: SlateSlots) -> SlateSlotValues:\n        return slots.fill([1.0] * len(slots))\n\n    def slot_values(self, rewards: SlateSlotValues) -> SlateSlotValues:\n        return rewards\n\n\nclass DCGSlateMetric(SlateMetric):\n    _weights: Tensor = None\n\n    def _get_discount(self, slate_size: int) -> Tensor:\n        if (\n            DCGSlateMetric._weights is None\n            or DCGSlateMetric._weights.shape[0] < slate_size\n            or DCGSlateMetric._weights.device != self._device\n        ):\n            DCGSlateMetric._weights = torch.reciprocal(\n                torch.log2(\n                    torch.arange(\n                        2, slate_size + 2, dtype=torch.double, device=self._device\n                    )\n                )\n            )\n        return DCGSlateMetric._weights[:slate_size]\n\n    def slot_weights(self, slots: SlateSlots) -> SlateSlotValues:\n        return slots.fill(self._get_discount(len(slots)))\n\n    def slot_values(self, rewards: SlateSlotValues) -> SlateSlotValues:\n        return rewards.replace(torch.pow(2.0, rewards.values) - 1.0)\n\n\nclass NDCGSlateMetric(DCGSlateMetric):\n    def __init__(self, item_rewards: SlateItemValues, device=None):\n        super().__init__(device)\n        self._sorted_items, _ = item_rewards.sort()\n        self._item_rewards = item_rewards\n        self._idcg = {}\n\n    def slot_weights(self, slots: SlateSlots) -> SlateSlotValues:\n        slate_size = len(slots)\n        assert len(self._sorted_items) >= slate_size\n        if slate_size not in self._idcg:\n            i_slate = make_slate(slots, self._sorted_items[:slate_size])\n            idcg = super().calculate_reward(\n                slots,\n                i_slate.slot_values(self._item_rewards),\n                None,\n                super().slot_weights(slots),\n            )\n            self._idcg[slate_size] = idcg\n        else:\n            idcg = self._idcg[slate_size]\n        return slots.fill(\n            torch.zeros(slate_size, dtype=torch.double)\n            if idcg == 0\n            else self._get_discount(slate_size) / idcg\n        )\n\n\nclass ERRSlateMetric(SlateMetric):\n    def __init__(self, max_reward: float, device=None):\n        super().__init__(device)\n        self._max_reward = max_reward\n\n    def slot_weights(self, slots: SlateSlots) -> SlateSlotValues:\n        return slots.fill([1.0 / (r + 1) for r in range(len(slots))])\n\n    def slot_values(self, rewards: SlateSlotValues) -> SlateSlotValues:\n        d = torch.tensor(self._max_reward, device=self._device).pow(2.0)\n        r = (torch.pow(2.0, rewards.values.clamp(0.0, self._max_reward)) - 1.0) / d\n        p = 1.0\n        err = torch.zeros(len(rewards), dtype=torch.double, device=self._device)\n        for i in range(len(rewards)):\n            ri = r[i]\n            err[i] = p * ri\n            p = p * (1.0 - ri.item())\n        return rewards.replace(err)\n\n\nclass SlateModel(ABC):\n    \"\"\"\n    Model providing item relevance/reward, slot examination (click) distribution\n    \"\"\"\n\n    @abstractmethod\n    def item_rewards(self, context: SlateContext) -> SlateItemValues:\n        \"\"\"\n        Returns each item's relevance under the context\n        Args:\n            context:\n\n        Returns:\n            Item relevances\n        \"\"\"\n        pass\n\n    def slot_probabilities(self, context: SlateContext) -> SlateSlotValues:\n        \"\"\"\n        Returns each slot/positions's probability independent of showing item,\n        used in PBM estimator\n        Args:\n            context:\n\n        Returns:\n\n        \"\"\"\n        return context.slots.fill(torch.ones(len(context.slots), dtype=torch.double))\n\n\n@dataclass(frozen=True)\nclass LogSample:\n    context: SlateContext\n    metric: SlateMetric\n    log_slate: Slate\n    log_reward: Reward\n    _log_slate_probability: Probability = float(\"nan\")\n    # probability for each item being places at each slot\n    _log_slot_item_probabilities: Optional[SlateSlotItemProbabilities] = None\n    # item probability distribution from behavior policy\n    _log_item_probabilities: Optional[SlateItemProbabilities] = None\n    _tgt_slate_probability: Probability = float(\"nan\")\n    _tgt_slot_item_probabilities: Optional[SlateSlotItemProbabilities] = None\n    # item probability distribution from target policy\n    _tgt_item_probabilities: Optional[SlateItemProbabilities] = None\n    # gt_item_rewards: Optional[SlateItemValues] = None\n    # pre-calculated ground truth for target policy\n    ground_truth_reward: Reward = float(\"nan\")\n    # context dependent slot weights (e.g. DCG or ERR weights), used by PBM\n    slot_weights: Optional[SlateSlotValues] = None\n    # item/action independent examination probabilities of each slot, used by PBM\n    slot_probabilities: Optional[SlateSlotValues] = None\n    # features associated with the slate, to train direct model\n    item_features: SlateItemFeatures = None\n\n    def validate(self):\n        slate_size = len(self.context.slots)\n        item_size = len(self.items)\n        assert len(self.log_slate) == slate_size\n        assert (\n            math.isnan(self._log_slate_probability)\n            or self._log_slate_probability <= 1.0\n        )\n        assert (\n            math.isnan(self._tgt_slate_probability)\n            or self._tgt_slate_probability <= 1.0\n        )\n        assert (\n            self._log_slot_item_probabilities is None\n            or len(self._log_slot_item_probabilities) == slate_size\n        )\n        assert (\n            self._log_item_probabilities is None\n            or len(self._log_item_probabilities) == item_size\n        )\n        assert (\n            self._tgt_slot_item_probabilities is None\n            or len(self._tgt_slot_item_probabilities) == slate_size\n        )\n        assert (\n            self._tgt_item_probabilities is None\n            or len(self._tgt_item_probabilities) == item_size\n        )\n        assert self.slot_weights is None or len(self.slot_weights) == slate_size\n        assert (\n            self.slot_probabilities is None\n            or len(self.slot_probabilities) == slate_size\n        )\n\n    def log_slot_item_expectations(\n        self, slots: SlateSlots\n    ) -> Optional[SlateSlotItemExpectations]:\n        if self._log_slot_item_probabilities is not None:\n            return self._log_slot_item_probabilities.slot_item_expectations()\n        if self._log_item_probabilities is not None:\n            return self._log_item_probabilities.slot_item_expectations(slots)\n        return None\n\n    def log_slate_probability(self, slate: Optional[Slate] = None) -> float:\n        if not math.isnan(self._log_slate_probability):\n            return self._log_slate_probability\n        if slate is None:\n            slate = self.log_slate\n        if self._log_slot_item_probabilities is not None:\n            return self._log_slot_item_probabilities.slate_probability(slate)\n        if self._log_item_probabilities is not None:\n            return self._log_item_probabilities.slate_probability(slate)\n        return 0.0\n\n    def tgt_slot_expectations(\n        self, slots: SlateSlots\n    ) -> Optional[SlateSlotItemExpectations]:\n        if self._tgt_slot_item_probabilities is not None:\n            return self._tgt_slot_item_probabilities.slot_item_expectations()\n        if self._tgt_item_probabilities is not None:\n            return self._tgt_item_probabilities.slot_item_expectations(slots)\n        return None\n\n    def tgt_slate_probability(self) -> float:\n        if not math.isnan(self._tgt_slate_probability):\n            return self._tgt_slate_probability\n        if self._tgt_slot_item_probabilities is not None:\n            return self._tgt_slot_item_probabilities.slate_probability(self.log_slate)\n        if self._tgt_item_probabilities is not None:\n            return self._tgt_item_probabilities.slate_probability(self.log_slate)\n        return 0.0\n\n    def tgt_slate_space(\n        self, slots: SlateSlots\n    ) -> Iterable[Tuple[Sequence[SlateItem], float]]:\n        if self._tgt_item_probabilities is not None:\n            return self._tgt_item_probabilities.slate_space(slots)\n        return []\n\n    @property\n    def items(self) -> SlateItems:\n        if self._log_slot_item_probabilities is not None:\n            return self._log_slot_item_probabilities._values[0].items\n        if self._log_item_probabilities is not None:\n            return self._log_item_probabilities.items\n        return SlateItems(0)\n\n\n@dataclass(frozen=True)\nclass SlateEstimatorInput:\n    samples: Sequence[LogSample]\n\n    def validate(self):\n        for s in self.samples:\n            s.validate()\n\n\nclass SlateEstimator(Estimator):\n    @abstractmethod\n    def _evaluate_sample(\n        self, sample: LogSample, logger: logging.Logger\n    ) -> Optional[EstimatorSampleResult]:\n        pass\n\n\nclass DMEstimator(SlateEstimator):\n    \"\"\"\n    Direct Method estimator\n    \"\"\"\n\n    def __init__(self, trainer: Trainer, training_sample_ratio: float, device=None):\n        super().__init__(device)\n        self._trainer = trainer\n        self._training_sample_ratio = training_sample_ratio\n\n    def _train_model(\n        self, samples: Sequence[LogSample], logger: logging.Logger\n    ) -> Optional[Iterable[LogSample]]:\n        if self._trainer is None:\n            logger.error(\"Target model trainer is none, DM is not available\")\n            return None\n        self._trainer.reset()\n        logger.info(\"  training direct model...\")\n        st = time.perf_counter()\n        sample_size = len(samples)\n        if self._training_sample_ratio > 0.0 and self._training_sample_ratio < 1.0:\n            training_samples = range(int(sample_size * self._training_sample_ratio))\n        else:\n            training_samples = range(sample_size)\n        train_x = []\n        train_y = []\n        vali_mask = [True] * len(samples)\n        for i in training_samples:\n            sample = samples[i]\n            if sample.item_features is None:\n                continue\n            slate_features = sample.log_slate.slot_features(sample.item_features)\n            train_x.append(slate_features.features.flatten())\n            train_y.append(sample.log_reward)\n            vali_mask[i] = False\n        if len(train_x) == 0:\n            logger.error(\"Slate features not provided, DM is not available\")\n            return None\n        train_x = torch.stack(train_x)\n        train_y = torch.tensor(train_y, dtype=torch.double, device=train_x.device)\n        vali_x = []\n        vali_y = []\n        evaluate_samples = []\n        for mask, sample in zip(vali_mask, samples):\n            if not mask or sample.item_features is None:\n                continue\n            slate_features = sample.log_slate.slot_features(sample.item_features)\n            vali_x.append(slate_features.features.flatten())\n            vali_y.append(sample.log_reward)\n            evaluate_samples.append(sample)\n        if len(vali_x) == 0:\n            vali_x = train_x.detach().clone()\n            vali_y = train_y.detach().clone()\n            evaluate_samples = samples\n        else:\n            vali_x = torch.stack(vali_x)\n            vali_y = torch.tensor(vali_y, dtype=torch.double, device=vali_x.device)\n        training_data = TrainingData(train_x, train_y, None, vali_x, vali_y, None)\n        self._trainer.train(training_data)\n        logger.info(f\"  training direct model done: {time.perf_counter() - st}s\")\n\n        return evaluate_samples\n\n    def _evaluate_sample(\n        self, sample: LogSample, logger: logging.Logger\n    ) -> Optional[EstimatorSampleResult]:\n        slots = sample.context.slots\n        tgt_slate_space = sample.tgt_slate_space(slots)\n        features = []\n        probs = []\n        for items, prob in tgt_slate_space:\n            slate = make_slate(slots, items)\n            slate_features = slate.slot_features(sample.item_features)\n            features.append(slate_features.features.flatten())\n            probs.append(prob)\n        preds = self._trainer.predict(torch.stack(features), device=self._device)\n        tgt_reward = torch.dot(\n            preds.scores, torch.tensor(probs, dtype=torch.double, device=self._device)\n        )\n        return EstimatorSampleResult(\n            sample.log_reward,\n            tgt_reward.item(),\n            sample.ground_truth_reward,\n            float(\"nan\"),\n        )\n\n    def evaluate(\n        self, input: SlateEstimatorInput, *kwargs\n    ) -> Optional[EstimatorResult]:\n        input.validate()\n        logger = Estimator.logger()\n        samples = self._train_model(input.samples, logger)\n        if samples is None:\n            return None\n\n        log_avg = RunningAverage()\n        tgt_avg = RunningAverage()\n        gt_avg = RunningAverage()\n        for sample in samples:\n            result = self._evaluate_sample(sample, logger)\n            if result is None:\n                continue\n            log_avg.add(result.log_reward)\n            tgt_avg.add(result.target_reward)\n            gt_avg.add(result.ground_truth_reward)\n        return EstimatorResult(\n            log_avg.average, tgt_avg.average, gt_avg.average, tgt_avg.count\n        )\n\n    def __repr__(self):\n        return (\n            f\"DMEstimator(trainer({self._trainer.name})\"\n            f\",ratio({self._training_sample_ratio}),device({self._device}))\"\n        )\n\n\nclass IPSEstimator(SlateEstimator):\n    def __init__(\n        self, weight_clamper: Clamper = None, weighted: bool = True, device=None\n    ):\n        super().__init__(device)\n        self._weight_clamper = (\n            weight_clamper if weight_clamper is not None else Clamper()\n        )\n        self._weighted = weighted\n\n    def _evaluate_sample(\n        self, sample: LogSample, logger: logging.Logger\n    ) -> Optional[EstimatorSampleResult]:\n        tgt_prob = sample.tgt_slate_probability()\n        log_prob = sample.log_slate_probability(sample.log_slate)\n        if tgt_prob == log_prob:\n            weight = 1.0\n        elif tgt_prob <= 0.0:\n            weight = 0.0\n        elif log_prob <= 0.0:\n            return None\n        else:\n            weight = self._weight_clamper(tgt_prob / log_prob)\n        return EstimatorSampleResult(\n            sample.log_reward,\n            sample.log_reward * weight,\n            sample.ground_truth_reward,\n            weight,\n        )\n\n    def evaluate(\n        self, input: SlateEstimatorInput, *kwargs\n    ) -> Optional[EstimatorResult]:\n        input.validate()\n        logger = Estimator.logger()\n        log_avg = RunningAverage()\n        tgt_avg = RunningAverage()\n        acc_weight = RunningAverage()\n        gt_avg = RunningAverage()\n        zw = 0\n        for sample in input.samples:\n            result = self._evaluate_sample(sample, logger)\n            if result is None:\n                zw += 1\n                continue\n            log_avg.add(result.log_reward)\n            tgt_avg.add(result.target_reward)\n            gt_avg.add(result.ground_truth_reward)\n            acc_weight.add(result.weight)\n            if result.weight == 0.0:\n                zw += 1\n        logging.info(\n            f\"IPSEstimator invalid sample pct: {zw * 100 / len(input.samples)}%\"\n        )\n        if tgt_avg.count == 0:\n            return None\n        if self._weighted:\n            estimated = tgt_avg.total / acc_weight.total\n            return EstimatorResult(\n                log_avg.average, estimated, gt_avg.average, acc_weight.average\n            )\n        else:\n            return EstimatorResult(\n                log_avg.average, tgt_avg.average, gt_avg.average, tgt_avg.count\n            )\n\n    def __repr__(self):\n        return (\n            f\"IPSEstimator(weight_clamper({self._weight_clamper})\"\n            f\",weighted({self._weighted}),device({self._device}))\"\n        )\n\n\nclass DoublyRobustEstimator(DMEstimator):\n    def __init__(\n        self,\n        trainer: Trainer,\n        training_sample_ratio: float,\n        weight_clamper: Clamper = None,\n        weighted: bool = False,\n        device=None,\n    ):\n        super().__init__(trainer, training_sample_ratio, device)\n        self._weight_clamper = (\n            weight_clamper if weight_clamper is not None else Clamper()\n        )\n        self._weighted = weighted\n\n    def _evaluate_sample(\n        self, sample: LogSample, logger: logging.Logger\n    ) -> Optional[EstimatorSampleResult]:\n        slots = sample.context.slots\n        if self._trainer.is_trained:\n            tgt_slate_space = sample.tgt_slate_space(slots)\n            features = []\n            probs = []\n            for items, prob in tgt_slate_space:\n                slate = make_slate(slots, items)\n                slate_features = slate.slot_features(sample.item_features)\n                features.append(slate_features.features.flatten())\n                probs.append(prob)\n            preds = self._trainer.predict(torch.stack(features), device=self._device)\n            dm_reward = torch.dot(\n                preds.scores,\n                torch.tensor(probs, dtype=torch.double, device=self._device),\n            ).item()\n            log_slate_feature = sample.log_slate.slot_features(sample.item_features)\n            pred = self._trainer.predict(\n                torch.unsqueeze(log_slate_feature.features.flatten(), dim=0),\n                device=self._device,\n            )\n            log_dm_reward = pred.scores[0].item()\n        else:\n            dm_reward = 0.0\n            log_dm_reward = 0.0\n        tgt_prob = sample.tgt_slate_probability()\n        log_prob = sample.log_slate_probability(sample.log_slate)\n        if tgt_prob == log_prob:\n            weight = 1.0\n        elif tgt_prob <= 0.0:\n            weight = 0.0\n        elif log_prob <= 0.0:\n            return None\n        else:\n            weight = self._weight_clamper(tgt_prob / log_prob)\n        target_reward = (sample.log_reward - log_dm_reward) * weight + dm_reward\n        return EstimatorSampleResult(\n            sample.log_reward, target_reward, sample.ground_truth_reward, weight\n        )\n\n    def evaluate(\n        self, input: SlateEstimatorInput, *kwargs\n    ) -> Optional[EstimatorResult]:\n        input.validate()\n        logger = Estimator.logger()\n        samples = self._train_model(input.samples, logger)\n        if samples is None:\n            samples = input.samples\n\n        log_avg = RunningAverage()\n        tgt_avg = RunningAverage()\n        acc_weight = RunningAverage()\n        gt_avg = RunningAverage()\n        for sample in samples:\n            result = self._evaluate_sample(sample, logger)\n            if result is None:\n                continue\n            log_avg.add(result.log_reward)\n            tgt_avg.add(result.target_reward)\n            acc_weight.add(result.weight)\n            gt_avg.add(result.ground_truth_reward)\n        if self._weighted:\n            estimated = tgt_avg.total / acc_weight.total\n            return EstimatorResult(\n                log_avg.average, estimated, gt_avg.average, acc_weight.average\n            )\n        else:\n            return EstimatorResult(\n                log_avg.average, tgt_avg.average, gt_avg.average, tgt_avg.count\n            )\n\n    def __repr__(self):\n        return (\n            f\"DoublyRobustEstimator(trainer({self._trainer.name})\"\n            f\",ratio({self._training_sample_ratio})\"\n            f\",weight_clamper({self._weight_clamper})\"\n            f\",weighted({self._weighted}),device({self._device}))\"\n        )\n\n\nclass PseudoInverseEstimator(SlateEstimator):\n    \"\"\"\n    Estimator from reference 2\n    \"\"\"\n\n    def __init__(\n        self, weight_clamper: Clamper = None, weighted: bool = True, device=None\n    ):\n        super().__init__(device)\n        self._weight_clamper = (\n            weight_clamper if weight_clamper is not None else Clamper()\n        )\n        self._weighted = weighted\n\n    def _evaluate_sample(\n        self, sample: LogSample, logger: logging.Logger\n    ) -> Optional[EstimatorSampleResult]:\n        log_slot_expects = sample.log_slot_item_expectations(sample.context.slots)\n        if log_slot_expects is None:\n            logger.warning(f\"Log slot distribution not available\")\n            return None\n        tgt_slot_expects = sample.tgt_slot_expectations(sample.context.slots)\n        if tgt_slot_expects is None:\n            logger.warning(f\"Target slot distribution not available\")\n            return None\n        log_indicator = log_slot_expects.values_tensor(self._device)\n        tgt_indicator = tgt_slot_expects.values_tensor(self._device)\n        lm = len(sample.context.slots) * len(sample.items)\n        gamma = torch.as_tensor(\n            np.linalg.pinv(\n                torch.mm(\n                    log_indicator.view((lm, 1)), log_indicator.view((1, lm))\n                ).numpy()\n            )\n        )\n        # torch.pinverse is not very stable\n        # gamma = torch.pinverse(\n        #     torch.mm(log_indicator.view((lm, 1)), log_indicator.view((1, lm)))\n        # )\n        ones = sample.log_slate.one_hots(sample.items, self._device)\n        weight = self._weight_clamper(\n            torch.mm(tgt_indicator.view((1, lm)), torch.mm(gamma, ones.view((lm, 1))))\n        ).item()\n        return EstimatorSampleResult(\n            sample.log_reward,\n            sample.log_reward * weight,\n            sample.ground_truth_reward,\n            weight,\n        )\n\n    def evaluate(\n        self, input: SlateEstimatorInput, *kwargs\n    ) -> Optional[EstimatorResult]:\n        input.validate()\n        logger = Estimator.logger()\n        log_avg = RunningAverage()\n        tgt_avg = RunningAverage()\n        acc_weight = RunningAverage()\n        gt_avg = RunningAverage()\n        zw = 0\n        for sample in input.samples:\n            result = self._evaluate_sample(sample, logger)\n            if result is None:\n                zw += 1\n                continue\n            log_avg.add(result.log_reward)\n            tgt_avg.add(result.target_reward)\n            gt_avg.add(result.ground_truth_reward)\n            acc_weight.add(result.weight)\n            if result.weight == 0.0:\n                zw += 1\n            if tgt_avg.count % 1000 == 0:\n                logger.info(f\"  PseudoInverseEstimator: processed {tgt_avg.count}\")\n        logging.info(\n            f\"PseudoInverseEstimator invalid sample pct: {zw * 100 / len(input.samples)}%\"\n        )\n        if tgt_avg.count == 0:\n            return None\n        if self._weighted:\n            estimated = tgt_avg.total / acc_weight.total\n            return EstimatorResult(\n                log_avg.average, estimated, gt_avg.average, acc_weight.average\n            )\n        else:\n            return EstimatorResult(\n                log_avg.average, tgt_avg.average, gt_avg.average, tgt_avg.count\n            )\n\n    def __repr__(self):\n        return (\n            f\"PseudoInverseEstimator(weight_clamper({self._weight_clamper})\"\n            f\",weighted({self._weighted}),device({self._device}))\"\n        )\n\n\nclass PBMEstimator(SlateEstimator):\n    \"\"\"\n    Estimator from reference 1: Position-Based Click Model\n    \"\"\"\n\n    def __init__(\n        self, weight_clamper: Clamper = None, weighted: bool = True, device=None\n    ):\n        super().__init__(device)\n        self._weight_clamper = (\n            weight_clamper if weight_clamper is not None else Clamper()\n        )\n        self._weighted = weighted\n\n    def _evaluate_sample(\n        self, sample: LogSample, logger: logging.Logger\n    ) -> Optional[EstimatorSampleResult]:\n        log_slot_expects = sample.log_slot_item_expectations(sample.context.slots)\n        if log_slot_expects is None:\n            logger.warning(f\"  Log slot distribution not available\")\n            return None\n        tgt_slot_expects = sample.tgt_slot_expectations(sample.context.slots)\n        if tgt_slot_expects is None:\n            logger.warning(f\"  Target slot distribution not available\")\n            return None\n        slate_size = len(sample.context.slots)\n        slot_weights = sample.slot_weights\n        if slot_weights is None:\n            slot_weights = SlateSlotValues(torch.ones(slate_size, dtype=torch.double))\n        weights = slot_weights.values.to(device=self._device)\n        if sample.slot_probabilities is not None:\n            weights *= sample.slot_probabilities.values\n        h = torch.zeros(slate_size, dtype=torch.double, device=self._device)\n        p = torch.zeros(slate_size, dtype=torch.double, device=self._device)\n        i = 0\n        for slot, item in sample.log_slate:\n            h[i] = tgt_slot_expects[slot][item]\n            p[i] = log_slot_expects[slot][item]\n            i += 1\n        nu = torch.tensordot(h, weights, dims=([0], [0]))\n        de = torch.tensordot(p, weights, dims=([0], [0]))\n        if nu == de:\n            weight = 1.0\n        elif nu == 0:\n            weight = 0.0\n        elif de == 0:\n            return None\n        else:\n            weight = self._weight_clamper(nu / de)\n        return EstimatorSampleResult(\n            sample.log_reward,\n            sample.log_reward * weight,\n            sample.ground_truth_reward,\n            weight,\n        )\n\n    def evaluate(\n        self, input: SlateEstimatorInput, *kwargs\n    ) -> Optional[EstimatorResult]:\n        input.validate()\n        logger = Estimator.logger()\n        log_avg = RunningAverage()\n        tgt_avg = RunningAverage()\n        acc_weight = RunningAverage()\n        gt_avg = RunningAverage()\n        zw = 0\n        for sample in input.samples:\n            result = self._evaluate_sample(sample, logger)\n            if result is None:\n                zw += 1\n                continue\n            log_avg.add(result.log_reward)\n            tgt_avg.add(result.target_reward)\n            gt_avg.add(result.ground_truth_reward)\n            acc_weight.add(result.weight)\n            if result.weight == 0.0:\n                zw += 1\n            if tgt_avg.count % 1000 == 0:\n                logger.info(f\"  PBMEstimator: processed {tgt_avg.count}\")\n        logging.info(\n            f\"PBMEstimator invalid sample pct: {zw * 100 / len(input.samples)}%\"\n        )\n        if tgt_avg.count == 0:\n            return None\n        if self._weighted:\n            estimated = tgt_avg.total / acc_weight.total\n            return EstimatorResult(\n                log_avg.average, estimated, gt_avg.average, acc_weight.average\n            )\n        else:\n            return EstimatorResult(\n                log_avg.average, tgt_avg.average, gt_avg.average, tgt_avg.count\n            )\n\n    def __repr__(self):\n        return (\n            f\"PBMEstimator(weight_clamper({self._weight_clamper})\"\n            f\",weighted({self._weighted}),device({self._device}))\"\n        )\n", "meta": {"hexsha": "67b41620eb1a2a845d85023055d6825982a520de", "size": 51495, "ext": "py", "lang": "Python", "max_stars_repo_path": "reagent/ope/estimators/slate_estimators.py", "max_stars_repo_name": "japsonzbz/ReAgent", "max_stars_repo_head_hexsha": "7071b816b6e9a71228ded88f8a087b5060aa8ec0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-30T16:57:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-30T16:57:47.000Z", "max_issues_repo_path": "reagent/ope/estimators/slate_estimators.py", "max_issues_repo_name": "japsonzbz/ReAgent", "max_issues_repo_head_hexsha": "7071b816b6e9a71228ded88f8a087b5060aa8ec0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reagent/ope/estimators/slate_estimators.py", "max_forks_repo_name": "japsonzbz/ReAgent", "max_forks_repo_head_hexsha": "7071b816b6e9a71228ded88f8a087b5060aa8ec0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2386968085, "max_line_length": 90, "alphanum_fraction": 0.602310904, "include": true, "reason": "import numpy", "num_tokens": 11693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.16085854920426418}}
{"text": "from __future__ import absolute_import, unicode_literals, print_function\n\nimport os, re, math\nfrom ctypes import *\nimport numpy as N\nfrom numpy.ctypeslib import as_array\n\n# don't bother with parsing error\ntry:\n    lib = cdll.LoadLibrary('libnest3.so')\nexcept:\n    lib = cdll.LoadLibrary(os.path.dirname(__file__) + '/libnest3.so')\n\n# if we want to do OS X version detection:\n# import platform\n# if platform.system() == 'Darwin'\n# '.'.join(platform.mac_ver().split('.')[:2]) --> 10.X\n\n# libstempo.multinest.run borrows heavily from Johannes Buchner's pymultinest;\n# it requires MultiNest v3.2 patched with cwrapper.f90\n\ndef run(LogLikelihood,\n    Prior,\n    n_dims,\n    n_params = None,\n    n_clustering_params = None, wrapped_params = None,\n    importance_nested_sampling = True,\n    multimodal = True, const_efficiency_mode = False, n_live_points = 400,\n    evidence_tolerance = 0.5, sampling_efficiency = 0.8,\n    n_iter_before_update = 100, null_log_evidence = -1e90,\n    max_modes = 100, mode_tolerance = -1e90,\n    outputfiles_basename = \"./multinest-\", seed = -1, verbose = False,\n    resume = True, context = None, write_output = True, log_zero = -1e100,\n    max_iter = 0, init_MPI = True, dump_callback = None):\n    \"\"\"\n    Runs MultiNest\n\n    The most important parameters are the two log-probability functions Prior\n    and LogLikelihood. They are called by MultiNest.\n\n    Prior should transform the unit cube into the parameter cube. Here\n    is an example for a uniform prior::\n\n        def Prior(cube, ndim, nparams):\n            for i in range(ndim):\n                cube[i] = cube[i] * 10 * math.pi\n\n    The LogLikelihood function gets this parameter cube and should\n    return the logarithm of the likelihood.\n    Here is the example for the eggbox problem::\n\n        def Loglike(cube, ndim, nparams):\n            chi = 1.\n\n            for i in range(ndim):\n                chi *= math.cos(cube[i] / 2.)\n            return math.pow(2. + chi, 5)\n\n    Some of the parameters are explained below. Otherwise consult the\n    MultiNest documentation.\n\n    @param importance_nested_sampling:\n        If True, Multinest will use Importance Nested Sampling (INS). Read http://arxiv.org/abs/1306.2144\n        for more details on INS. Please read the MultiNest README file before using the INS in MultiNest v3.0.\n\n    @param n_params:\n        Total no. of parameters, should be equal to ndims in most cases\n        but if you need to store some additional\n        parameters with the actual parameters then you need to pass\n        them through the likelihood routine.\n\n    @param sampling_efficiency:\n        defines the sampling efficiency. 0.8 and 0.3 are recommended\n        for parameter estimation & evidence evalutation\n        respectively.\n        use 'parameter' or 'model' to select the respective default\n        values\n\n    @param mode_tolerance:\n        MultiNest can find multiple modes & also specify which samples belong to which mode. It might be\n        desirable to have separate samples & mode statistics for modes with local log-evidence value greater than a\n        particular value in which case Ztol should be set to that value. If there isn't any particularly interesting\n        Ztol value, then Ztol should be set to a very large negative number (e.g. -1e90).\n\n    @param evidence_tolerance:\n        A value of 0.5 should give good enough accuracy.\n\n    @param n_clustering_params:\n        If mmodal is T, MultiNest will attempt to separate out the\n        modes. Mode separation is done through a clustering\n        algorithm. Mode separation can be done on all the parameters\n        (in which case nCdims should be set to ndims) & it\n        can also be done on a subset of parameters (in which case\n        nCdims < ndims) which might be advantageous as\n        clustering is less accurate as the dimensionality increases.\n        If nCdims < ndims then mode separation is done on\n        the first nCdims parameters.\n\n    @param null_log_evidence:\n        If mmodal is T, MultiNest can find multiple modes & also specify\n        which samples belong to which mode. It might be\n        desirable to have separate samples & mode statistics for modes\n        with local log-evidence value greater than a\n        particular value in which case nullZ should be set to that\n        value. If there isn't any particulrly interesting\n        nullZ value, then nullZ should be set to a very large negative\n        number (e.g. -1.d90).\n\n    @param init_MPI:\n        initialize MPI routines?, relevant only if compiling with MPI\n\n    @param log_zero:\n        points with loglike < logZero will be ignored by MultiNest\n\n    @param max_iter:\n        maximum number of iterations. 0 is unlimited.\n\n    @param write_output:\n        write output files? This is required for analysis.\n\n    @param dump_callback:\n        a callback function for dumping the current status\n\n    \"\"\"\n\n    if n_params == None:\n        n_params = n_dims\n    if n_clustering_params == None:\n        n_clustering_params = n_dims\n    if wrapped_params == None:\n        wrapped_params = [0] * n_dims\n\n    WrappedType = c_int * len(wrapped_params)\n    wraps = WrappedType(*wrapped_params)\n\n    if sampling_efficiency == 'parameter':\n        sampling_efficiency = 0.8\n    if sampling_efficiency == 'model':\n        sampling_efficiency = 0.3\n\n    # MV 20130923\n\n    loglike_type = CFUNCTYPE(c_double,\n                             POINTER(c_double),c_int,c_int,c_void_p)\n\n    dumper_type  = CFUNCTYPE(c_void_p,\n                             c_int,c_int,c_int,\n                             POINTER(c_double),POINTER(c_double),POINTER(c_double),\n                             c_double,c_double,c_double,c_void_p)\n\n    if hasattr(LogLikelihood,'loglike') and hasattr(Prior,'remap') and hasattr(Prior,'prior'):\n        def loglike(cube,ndim,nparams,nullcontext):\n            # we're not using context with libstempo.like objects\n\n            pprior = Prior.premap(cube)\n\n            # mappers are supposed to throw a ValueError if they get out of range\n            try:\n                pars = Prior.remap(cube)\n            except ValueError:\n                return -N.inf\n\n            prior = pprior * Prior.prior(pars)\n    \n            return -N.inf if not prior else math.log(prior) + LogLikelihood.loglike(pars)\n    else:\n        def loglike(cube,ndim,nparams,nullcontext):\n            # it's actually easier to use the context, if any, at the Python level\n            # and pass a null pointer to MultiNest...\n\n            args = [cube,ndim,nparams] + ([] if context is None else context)\n\n            if Prior:\n                Prior(*args)\n\n            return LogLikelihood(*args)\n\n    def dumper(nSamples,nlive,nPar,\n               physLive,posterior,paramConstr,\n               maxLogLike,logZ,logZerr,nullcontext):\n\n        if dump_callback:\n            # It's not clear to me what the desired PyMultiNest dumper callback\n            # syntax is... but this should pass back the right numpy arrays,\n            # without copies. Untested!\n            pc =  as_array(paramConstr,shape=(nPar,4))\n\n            dump_callback(nSamples,nlive,nPar,\n                          as_array(physLive,shape=(nPar+1,nlive)).T,\n                          as_array(posterior,shape=(nPar+2,nSamples)).T,\n                          (pc[0,:],pc[1,:],pc[2,:],pc[3,:]),    # (mean,std,bestfit,map)\n                          maxLogLike,logZ,logZerr)\n\n    # MV 20130923: currently we support only multinest 3.2 (24 parameters),\n    # but it would not be a problem to build up the parameter list dynamically\n\n    lib.run(c_bool(importance_nested_sampling),c_bool(multimodal),c_bool(const_efficiency_mode),\n            c_int(n_live_points),c_double(evidence_tolerance),\n            c_double(sampling_efficiency),c_int(n_dims),c_int(n_params),\n            c_int(n_clustering_params),c_int(max_modes),\n            c_int(n_iter_before_update),c_double(mode_tolerance),\n            create_string_buffer(outputfiles_basename.encode()),    # MV 20130923: need a regular C string\n            c_int(seed),wraps,\n            c_bool(verbose),c_bool(resume),\n            c_bool(write_output),c_bool(init_MPI),\n            c_double(log_zero),c_int(max_iter),\n            loglike_type(loglike),dumper_type(dumper),\n            c_void_p(0))\n\nclass multinestdata(dict):\n    pass\n\nclass multinestpar(object):\n    pass\n\n# where are the multinest files?\ndef _findfiles(multinestrun,dirname,suffix='-post_equal_weights.dat'):\n    # try chains/multinestrun-...\n    #     chains/multinestrun/multinestrun-...\n    root = [dirname + '/',dirname + '/' + multinestrun]\n    \n    # and if multinestrun is something like pulsar-model,\n    # try chains/pulsar/model/pulsar-model-...\n    if '-' in multinestrun:\n        tokens = multinestrun.split('-')[:-1]\n        pulsar, model = '-'.join(tokens[:-1]), tokens[-1]\n        root.append(dirname + '/' + pulsar + '/' + model)\n\n    return filter(lambda r: os.path.isfile(r + '/' + multinestrun + suffix),root)\n\ndef _getcomment(ret,filename):\n    try:\n        ret.comment = open(filename,'r').read()\n    except IOError:\n        pass\n\ndef _getmeta(ret,filename):\n    try:\n        meta = N.load(filename)\n    except IOError:\n        return\n\n    ret.parnames  = list(meta['name'])\n    ret.tempopars = list(meta['val'])   # somewhat legacy?\n    ret.tempo = {}\n\n    ml = N.argmax(ret.data[:,-1])\n\n    for i,par in enumerate(ret.parnames):\n        ret[par] = multinestpar()\n\n        try:\n            ret[par].val, ret[par].err = N.mean(ret.data[:,i]) + meta['offset'][i], math.sqrt(N.var(ret.data[:,i]))\n            ret[par].offset = meta['offset'][i]\n        except ValueError:\n            ret[par].val, ret[par].err = N.mean(ret.data[:,i]), math.sqrt(N.var(ret.data[:,i]))\n\n        if 'ml' in meta.dtype.names:\n            ret[par].ml = meta['ml'][i]\n        else:   \n            ret[par].ml = ret.data[ml,i] + (meta['offset'][i] if 'offset' in meta.dtype.names else 0)\n\n        ret.tempo[par] = multinestpar()\n        ret.tempo[par].val, ret.tempo[par].err = meta['val'][i], meta['err'][i]\n\ndef load_mcmc(mcrun,dirname='.'):\n    root = _findfiles(mcrun,dirname,'-chain.npy')\n\n    ret = multinestdata()\n    ret.dirname = root[0]\n\n    alldata = N.load('{0}/{1}-chain.npy'.format(root[0],mcrun))\n\n    # keep all the steps\n    ret.data = alldata[:,:]\n\n    _getmeta(ret,'{0}/{1}-meta.npy'.format(root[0],mcrun))\n    _getcomment(ret,'{0}/{1}-comment.txt'.format(root[0],mcrun))\n\n    return ret\n\ndef load_emcee(emceerun,dirname='.',chains=False):\n    root = _findfiles(emceerun,dirname,'-chain.npy')\n\n    ret = multinestdata()\n    ret.dirname = root[0]\n\n    alldata = N.load('{0}/{1}-chain.npy'.format(root[0],emceerun))\n\n    # keep the last iteration of the walker cloud\n    ret.data = alldata[:,-1,:]\n\n    if chains:\n        ret.chains = alldata\n\n    _getmeta(ret,'{0}/{1}-meta.npy'.format(root[0],emceerun))\n    _getcomment(ret,'{0}/{1}-comment.txt'.format(root[0],emceerun))\n\n    return ret\n\ndef load(multinestrun,dirname='.'):\n    root = _findfiles(multinestrun,dirname,'-post_equal_weights.dat')\n\n    if not root:\n        # try to find a tar.gz archive\n        import tempfile, tarfile\n        root = _findfiles(multinestrun,dirname,'.tar.gz')\n        tar = tarfile.open('{0}/{1}.tar.gz'.format(root[0],multinestrun),mode='r|gz')\n        root = [tempfile.mkdtemp(prefix='/tmp/')]\n        tar.extractall(path=root[0])\n\n    ret = multinestdata()\n    ret.dirname = root[0]\n\n    # get data\n    ret.data = N.loadtxt('{0}/{1}-post_equal_weights.dat'.format(root[0],multinestrun))[:,:-1]\n\n    # get evidence\n    try:\n        lines = open('{0}/{1}-stats.dat'.format(root[0],multinestrun),'r').readlines()\n        try:\n            ret.ev = float(re.search(r'Global Evidence:\\s*(\\S*)\\s*\\+/-\\s*(\\S*)',lines[0]).group(1))\n        except:\n            ret.ev = float(re.search(r'Global Log-Evidence           :\\s*(\\S*)\\s*\\+/-\\s*(\\S*)',lines[0]).group(1))\n    except IOError:\n        pass\n\n    # get metadata\n    _getmeta(ret,'{0}/{1}-meta.npy'.format(root[0],multinestrun))\n    _getcomment(ret,'{0}/{1}-comment.txt'.format(root[0],multinestrun))\n\n    if root[0][:4] == '/tmp':\n        import shutil\n        shutil.rmtree(root[0])\n\n    return ret\n\ndef compress(rootname):\n    import sys, os, glob\n\n    dirname, filename = os.path.dirname(rootname), os.path.basename(rootname)\n\n    if filename[-1] == '-':\n        filename = filename[:-1]\n\n    files = [filename + '-' + ending for ending in ('.txt','phys_live.points','stats.dat','ev.dat',\n                                                    'post_equal_weights.dat','summary.txt','live.points',\n                                                    'post_separate.dat','meta.npy','resume.dat','comment.txt')]\n\n    cd = os.getcwd()\n    os.chdir(dirname)\n\n    os.system('tar zcf {0}.tar.gz {1}'.format(filename,' '.join(files)))\n\n    files_exclude = [filename + '-' + ending for ending in ('IS.iterinfo','IS.points','IS.ptprob')]\n\n    for f in files + files_exclude:\n        if os.path.isfile(f):\n            os.unlink(f)\n\n    os.chdir(cd)\n", "meta": {"hexsha": "1ed62dc14d78635579db0be3287d05a3555e8122", "size": 13049, "ext": "py", "lang": "Python", "max_stars_repo_path": "libstempo/multinest.py", "max_stars_repo_name": "bshapiroalbert/libstempo", "max_stars_repo_head_hexsha": "e5e6231e9d9897aa161080baedd0ea210780460e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libstempo/multinest.py", "max_issues_repo_name": "bshapiroalbert/libstempo", "max_issues_repo_head_hexsha": "e5e6231e9d9897aa161080baedd0ea210780460e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libstempo/multinest.py", "max_forks_repo_name": "bshapiroalbert/libstempo", "max_forks_repo_head_hexsha": "e5e6231e9d9897aa161080baedd0ea210780460e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.046961326, "max_line_length": 116, "alphanum_fraction": 0.6269445935, "include": true, "reason": "import numpy,from numpy", "num_tokens": 3305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.511716619597144, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.16070488326584847}}
{"text": "# ######################################################################\n# Original code:                                                       #\n# @author: Robert B. Von Dreele and Brian Toby                         #\n# General Structure Analysis System - II (GSAS-II)                     #\n# https://subversion.xor.aps.anl.gov/trac/pyGSAS                       #\n# Copyright 2010, UChicago Argonne, LLC, Operator of                   #\n# Argonne National Laboratory All rights reserved.                     #\n#                                                                      #\n# Copyright (c) 2014, Brookhaven Science Associates, Brookhaven        #\n# National Laboratory. All rights reserved.                            #\n#                                                                      #\n# Redistribution and use in source and binary forms, with or without   #\n# modification, are permitted provided that the following conditions   #\n# are met:                                                             #\n#                                                                      #\n# * Redistributions of source code must retain the above copyright     #\n#   notice, this list of conditions and the following disclaimer.      #\n#                                                                      #\n# * Redistributions in binary form must reproduce the above copyright  #\n#   notice this list of conditions and the following disclaimer in     #\n#   the documentation and/or other materials provided with the         #\n#   distribution.                                                      #\n#                                                                      #\n# * Neither the name of the Brookhaven Science Associates, Brookhaven  #\n#   National Laboratory nor the names of its contributors may be used  #\n#   to endorse or promote products derived from this software without  #\n#   specific prior written permission.                                 #\n#                                                                      #\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  #\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    #\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    #\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE       #\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,           #\n# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES   #\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR   #\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)   #\n# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,  #\n# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OTHERWISE) ARISING   #\n# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE   #\n# POSSIBILITY OF SUCH DAMAGE.                                          #\n########################################################################\n\n\"\"\"\nThis is the module for reading files created in GSAS file formats\nhttps://subversion.xor.aps.anl.gov/trac/pyGSAS\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\nimport os\nimport numpy as np\n\n\ndef gsas_reader(file):\n    \"\"\"\n    Parameters\n    ----------\n    file: str\n        GSAS powder data file\n\n    Returns\n    --------\n     tth : ndarray\n        twotheta values (degrees) shape (N, ) array\n\n    intensity : ndarray\n        intensity values shape (N, ) array\n\n    err : ndarray\n        error value of intensity shape(N, ) array\n    \"\"\"\n\n    if os.path.splitext(file)[1] != \".gsas\":\n        raise IOError(\"Provide a file with diffraction data saved in GSAS,\"\n                      \" file extension has to be .gsas \")\n\n    # find the file mode, could be 'std', 'esd', 'fxye'\n    with open(file, 'r') as fi:\n        S = fi.readlines()[1]\n        mode = S.split()[9]\n\n    try:\n        tth, intensity, err = _func_look_up[mode](file)\n    except KeyError:\n        raise ValueError(\"Provide a correct mode of the GSAS file, \"\n                         \"file modes could be in 'STD', 'ESD', 'FXYE' \")\n\n    return tth, intensity, err\n\n\ndef _get_fxye_data(file):\n    \"\"\"\n    Parameters\n    ----------\n    file: str\n        GSAS powder data file\n\n    Return\n    ------\n    tth : ndarray\n        twotheta values (degrees) shape (N, ) array\n\n    intensity : ndarray\n        intensity values shape (N, ) array\n\n    err : ndarray\n        error value of intensity shape(N, ) array\n\n    \"\"\"\n    tth = []\n    intensity = []\n    err = []\n\n    with open(file, 'r') as fi:\n        S = fi.readlines()[2:]\n        for line in S:\n            vals = line.split()\n\n            tth.append(float(vals[0]))\n            f = float(vals[1])\n            s = float(vals[2])\n\n            if f <= 0.0:\n                intensity.append(0.0)\n            else:\n                intensity.append(float(vals[1]))\n\n            if s > 0.0:\n                err.append(1.0/float(vals[2])**2)\n            else:\n                err.append(0.0)\n\n    return [np.array(tth), np.array(intensity), np.array(err)]\n\n\ndef _get_esd_data(file):\n    \"\"\"\n    Parameters\n    ----------\n    file: str\n        GSAS powder data file\n\n    Return\n    ------\n    tth : ndarray\n        twotheta values (degrees) shape (N, ) array\n\n    intensity : ndarray\n        intensity values shape (N, ) array\n\n    err : ndarray\n        error value of intensity shape(N, ) array\n\n    \"\"\"\n    tth = []\n    intensity = []\n    err = []\n\n    with open(file, 'r') as fi:\n        S = fi.readlines()[1:]\n\n        # convert from centidegrees to degrees\n        start = float(S[0].split()[5])/100.0\n        step = float(S[0].split()[6])/100.0\n\n        j = 0\n        for line in S[1:]:\n            for i in range(0, 80, 16):\n                xi = start + step*j\n                yi = _sfloat(line[i: i + 8])\n                ei = _sfloat(line[i + 8: i + 16])\n                tth.append(xi)\n\n                if yi > 0.0:\n                    intensity.append(yi)\n                else:\n                    intensity.append(0.0)\n\n                if ei > 0.0:\n                    err.append(1.0/ei**2)\n                else:\n                    err.append(0.0)\n                j += 1\n    return [np.array(tth), np.array(intensity), np.array(err)]\n\n\ndef _get_std_data(file):\n    \"\"\"\n    Parameters\n    ----------\n    file: str\n        GSAS powder data file\n\n    Return\n    ------\n    tth : ndarray\n        twotheta values (degrees) shape (N, ) array\n\n    intensity : ndarray\n        intensity values shape (N, ) array\n\n    err : ndarray\n        error value of intensity shape(N, ) array\n\n    \"\"\"\n    tth = []\n    intensity = []\n    err = []\n\n    with open(file, 'r') as fi:\n        S = fi.readlines()[1:]\n\n        # convert from centidegrees to degrees\n        start = float(S[0].split()[5])/100.0\n        step = float(S[0].split()[6])/100.0\n\n        # number of data values(two theta or intensity)\n        nch = float(S[0].split()[2])\n\n        j = 0\n        for line in S[1:]:\n            for i in range(0, 80, 8):\n                xi = start + step*j\n                ni = max(_sint(line[i: i + 2]), 1)\n                yi = max(_sfloat(line[i + 2: i + 8]), 0.0)\n                if yi:\n                    vi = yi/ni\n                else:\n                    yi = 0.0\n                    vi = 0.0\n                if j < nch:\n                    tth.append(xi)\n                    if vi <= 0.:\n                        intensity.append(0.)\n                        err.append(0.)\n                    else:\n                        intensity.append(yi)\n                        err.append(1.0/vi)\n                j += 1\n    return [np.array(tth), np.array(intensity), np.array(err)]\n\n\n# find the which function to use according to mode of the GSAS file\n# mode could be \"STD\", \"ESD\" or \"FXYE\"\n_func_look_up = {'STD': _get_std_data, 'ESD': _get_esd_data,\n                 'FXYE': _get_fxye_data}\n\n\ndef _sfloat(S):\n    \"\"\"\n    convert a string to a float, treating an all-blank string as zero\n    Parameter\n    ---------\n    S : str\n        string that need to be converted as float treating an\n        all-blank string as zero\n\n    Returns\n    -------\n    float or zero\n    \"\"\"\n    if S.strip():\n        return float(S)\n    else:\n        return 0.0\n\n\ndef _sint(S):\n    \"\"\"\n    convert a string to an integer, treating an all-blank string as zero\n    Parameter\n    ---------\n    S : str\n        string that need to be converted as integer treating an all-blank\n        strings as zero\n\n    Returns\n    -------\n    integer or zero\n    \"\"\"\n    if S.strip():\n        return int(S)\n    else:\n        return 0\n", "meta": {"hexsha": "87bbc0f4d481a3b388c732c3ddb298c1d14890fd", "size": 8616, "ext": "py", "lang": "Python", "max_stars_repo_path": "skbeam/io/gsas_file_reader.py", "max_stars_repo_name": "mrakitin/scikit-beam", "max_stars_repo_head_hexsha": "89fe81486431b72df4dc497564867b9b3a26ee26", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 71, "max_stars_repo_stars_event_min_datetime": "2016-01-04T22:32:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:57:54.000Z", "max_issues_repo_path": "skbeam/io/gsas_file_reader.py", "max_issues_repo_name": "mrakitin/scikit-beam", "max_issues_repo_head_hexsha": "89fe81486431b72df4dc497564867b9b3a26ee26", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 288, "max_issues_repo_issues_event_min_datetime": "2015-12-09T23:40:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-02T00:32:00.000Z", "max_forks_repo_path": "skbeam/io/gsas_file_reader.py", "max_forks_repo_name": "mrakitin/scikit-beam", "max_forks_repo_head_hexsha": "89fe81486431b72df4dc497564867b9b3a26ee26", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 53, "max_forks_repo_forks_event_min_datetime": "2015-12-10T14:35:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-24T13:36:00.000Z", "avg_line_length": 30.445229682, "max_line_length": 75, "alphanum_fraction": 0.4915273909, "include": true, "reason": "import numpy", "num_tokens": 1929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.1607048818739721}}
{"text": "\"\"\"\n\nGrid.py\n\nAuthor: Jordan Mirocha\nAffiliation: University of Colorado at Boulder\nCreated on: Thu Sep 20 14:18:27 2012\n\nDescription: \n\n\"\"\"\n\nimport copy, types\nimport numpy as np\nfrom collections import Iterable\nfrom ..util import parse_kwargs, rebin\nfrom ..physics.Hydrogen import Hydrogen\nfrom ..physics.Cosmology import Cosmology\nfrom ..physics.Constants import k_B, cm_per_kpc, s_per_myr, m_H\nfrom ..physics.CrossSections import PhotoIonizationCrossSection\n\ntry:\n    import chianti.core as cc\n    import chianti.util as util\n    have_chianti = True\nexcept ImportError:\n    from ..util import fake_chianti\n    util = fake_chianti()\n    have_chianti = False\n\ntry:\n    from periodic.table import element as ELEMENT\nexcept ImportError:\n    from ..util import ELEMENT\n\ntiny_number = 1e-8  # A relatively small species fraction\n\nclass Grid(object):\n    def __init__(self, dims=64, length_units=cm_per_kpc, start_radius=0.01,\n        approx_Salpha=1, approx_lya=0, logarithmic_grid=False):\n        \"\"\"\n        Initialize grid object.\n        \n        Parameters\n        ----------\n        dims : int\n            Number of resolution elements in grid.\n        length_units : float\n            Size of domain in centimeters.\n        start_radius : float\n            Radius (in code units) within which to ignore.\n            \n        \"\"\"\n        \n        self.dims = int(dims)\n        self.length_units = length_units\n        self.start_radius = start_radius\n        self.approx_Salpha = approx_Salpha\n        self.approx_lya = approx_lya\n        self.log_grid = logarithmic_grid\n\n        # Compute cell centers and edges\n        if logarithmic_grid:\n            self.r_edg = self.r = \\\n                np.logspace(np.log10(self.R0), np.log10(length_units), \n                self.dims + 1)            \n        else:\n            self.r_edg = self.r = \\\n                np.linspace(self.R0, length_units, self.dims + 1)\n        \n        # Compute interior cell walls, spacing, and mid-points        \n        self.r_int = self.r_edg[0:-1]\n        self.dr = np.diff(self.r_edg)\n        self.r_mid = rebin(self.r_edg)\n        \n        self.zi = 0\n                \n    @property\n    def zeros_absorbers(self):\n        return np.zeros(self.N_absorbers)\n    \n    @property\n    def zeros_absorbers2(self):\n        return np.zeros([self.N_absorbers] * 2)    \n    \n    @property\n    def zeros_grid_x_absorbers(self):\n        return np.zeros([self.dims, self.N_absorbers])\n        \n    @property\n    def zeros_grid_x_absorbers2(self):\n        return np.zeros([self.dims, self.N_absorbers, self.N_absorbers])     \n                \n    @property\n    def R0(self):\n        \"\"\" Start radius in length_units. \"\"\"\n        return self.start_radius * self.length_units\n        \n    @property\n    def Vsh(self):\n        \"\"\" Shell volume in length_units**3. \"\"\"\n        if not hasattr(self, '_Vsh_all'):\n            self._Vsh_all = self.ShellVolume(self.r_edg[0:-1], self.dr)\n            \n        return self._Vsh_all\n                \n    @property            \n    def neutrals(self):\n        \"\"\" Return list of all neutral species. \"\"\"            \n        if not hasattr(self, '_neutral_species'):\n            self._neutral_species = []\n            for element in self.elements:\n                self._neutral_species.append('%s_1' % element)\n\n        return self._neutral_species\n                    \n    @property            \n    def ions(self):\n        \"\"\" Return list of all ionized species. \"\"\"     \n        if not hasattr(self, '_ionized_species'):\n            neutrals = self.neutrals\n            self._ionized_species = []\n            for ion in self.all_ions:\n                if ion in neutrals:\n                    continue\n                \n                self._ionized_species.append(ion)\n                \n        return self._ionized_species\n    \n    @property\n    def absorbers(self):    \n        \"\"\" Return list of absorbers (don't include electrons). \"\"\"\n        if not hasattr(self, '_absorbing_species'):\n            self._absorbing_species = copy.copy(self.neutrals)\n            for parent in self.ions_by_parent:\n                self._absorbing_species.extend(self.ions_by_parent[parent][1:-1])\n            \n        return self._absorbing_species\n        \n    @property\n    def N_absorbers(self):\n        \"\"\" Return number of absorbing species. \"\"\"\n        if not hasattr(self, 'self._num_of_absorbers'):\n            absorbers = self.absorbers\n            self._num_of_absorbers = int(len(absorbers))\n            \n        return self._num_of_absorbers\n        \n    @property\n    def metals(self):\n        \"\"\" Return list of anything that is not hydrogen or helium. \"\"\"\n        if not hasattr(self, '_metals'):\n            self._metals = []\n            self._metal_ions = []\n            for element in self.ions_by_parent:\n                if element in ['h', 'he']:\n                    continue\n                     \n                self._metals.append(element)\n                for ion in self.ions_by_parent[element]:\n                    self._metal_ions.append(ion)\n            \n        return self._metals  \n        \n    @property\n    def metal_ions(self):\n        \"\"\" Return list of all metal (not H or He) ions.\"\"\"      \n        if not hasattr(self, '_metal_ions'):\n            all_metals = self.metals\n            \n        return self._metal_ions\n        \n    @property\n    def species_abundances(self):\n        \"\"\"\n        Return dictionary containing abundances of parent\n        elements of all ions.\n        \"\"\"\n        if not hasattr(self, '_species_abundances'):\n            self._species_abundances = {}\n            for ion in self.ions_by_parent:\n                for state in self.ions_by_parent[ion]:\n                    self._species_abundances[state] = \\\n                        self.element_abundances[self.elements.index(ion)]\n    \n        return self._species_abundances\n        \n    @property\n    def species(self):\n        if not hasattr(self, '_species'):\n            self._species = []\n            for parent in self.ions_by_parent:\n                for ion in self.ions_by_parent[parent]:\n                    self._species.append(ion)\n                \n        return self._species\n        \n    @property\n    def types(self):\n        \"\"\"\n        Return list (matching evolving_fields) with integers describing\n        species type:\n            0 = neutral\n           +1 = ion\n           -1 = other\n        \"\"\"\n        \n        if not hasattr(self, '_species_types'):\n            self._species_types = []\n            for species in self.evolving_fields:\n                if species in self.neutrals:\n                    self._species_types.append(0)\n                elif species in self.ions:\n                    self._species_types.append(1)\n                else:\n                    self._species_types.append(-1) \n        \n        return self._species_types       \n        \n    @property # MUST GENERALIZE THIS\n    def ioniz_thresholds(self):\n        \"\"\"\n        Return dictionary containing ionization threshold energies (in eV)\n        for all absorbers.\n        \"\"\"    \n        \n        if not hasattr(self, '_ioniz_thresholds'):\n            self._ioniz_thresholds = {}\n            #for absorber in self.absorbers:\n            #if absorber == 'h_1':\n            self._ioniz_thresholds['h_1'] = 13.6\n            #elif absorber == 'he_1':\n            self._ioniz_thresholds['he_1'] = 24.4\n            #elif absorber == 'he_2':\n            self._ioniz_thresholds['he_2'] = 54.4\n           \n        return self._ioniz_thresholds\n        \n    @property # MUST GENERALIZE THIS\n    def bf_cross_sections(self):\n        \"\"\"\n        Return dictionary containing functions that compute the bound-free \n        absorption cross-sections for all absorbers.\n        \"\"\"    \n        \n        if not hasattr(self, 'all_xsections'):\n            self._bf_xsections = {}\n            #for absorber in self.absorbers:\n                #ion = cc.continuum(absorber)\n                #ion.vernerCross(energy = np.logspace(1, 5, 1000))\n                #if absorber == 'h_1':\n            self._bf_xsections['h_1'] = lambda E: \\\n                PhotoIonizationCrossSection(E, species=0)\n                #elif absorber == 'he_1':\n            self._bf_xsections['he_1'] = lambda E: \\\n                PhotoIonizationCrossSection(E, species=1)\n                #elif absorber == 'he_2':\n            self._bf_xsections['he_2'] = lambda E: \\\n                PhotoIonizationCrossSection(E, species=2) \n                        \n        return self._bf_xsections\n        \n    @property\n    def x_to_n(self):\n        \"\"\"\n        Return dictionary containing conversion factor between species\n        fraction and number density for all species.\n        \"\"\"\n        if not hasattr(self, '_x_to_n_converter'):\n            self._x_to_n_converter = {}\n            for ion in self.all_ions:\n                self._x_to_n_converter[ion] = self.n_ref \\\n                    * self.species_abundances[ion]  \n        \n        return self._x_to_n_converter\n        \n    @property\n    def expansion(self):\n        if not hasattr(self, '_expansion'):\n            self.set_physics()\n        return self._expansion\n    \n    @property\n    def isothermal(self):\n        if not hasattr(self, '_isothermal'):\n            self.set_physics()\n        return self._isothermal\n    \n    @property\n    def secondary_ionization(self):\n        if not hasattr(self, '_secondary_ionization'):\n            self.set_physics()\n        return self._secondary_ionization\n    \n    @property\n    def compton_scattering(self):\n        if not hasattr(self, '_compton_scattering'):\n            self.set_physics()\n        return self._compton_scattering\n        \n    @property\n    def recombination(self):\n        if not hasattr(self, '_recombination'):\n            self.set_physics()\n        return self._recombination\n        \n    @property\n    def clumping_factor(self):\n        if not hasattr(self, '_clumping_factor'):\n            self.set_physics()\n        return self._clumping_factor\n        \n        \n    @property\n    def hydr(self):\n        if not hasattr(self, '_hydr'):\n            self._hydr = Hydrogen(self.cosm, approx_Salpha=self.approx_Salpha,\n                approx_lya=self.approx_lya)\n        return self._hydr    \n            \n    @property\n    def cosm(self):\n        if not hasattr(self, '_cosm'):\n            self._cosm = Cosmology()\n        return self._cosm            \n                \n    def initialize(self, data):\n        self.set_chemistry()            \n                \n    def set_physics(self, isothermal=False, compton_scattering=False,\n        secondary_ionization=0, expansion=False, recombination='B',\n        clumping_factor=1.0):\n        self._isothermal = isothermal\n        self._compton_scattering = compton_scattering\n        self._secondary_ionization = secondary_ionization\n        self._expansion = expansion\n        self._recombination = recombination\n        \n        if type(clumping_factor) is not types.FunctionType:\n            self._clumping_factor = lambda z: clumping_factor\n        else:\n            self._clumping_factor = clumping_factor\n        \n        if self._expansion:\n            self.set_cosmology()\n        \n    @property\n    def in_bubbles(self):    \n        if not hasattr(self, '_in_bubbles'):\n            self.set_recombination_rate()\n            \n        return self._in_bubbles\n        \n    def set_recombination_rate(self, in_bubbles=False):\n        self._in_bubbles = in_bubbles    \n        \n    def set_cosmology(self, initial_redshift=1e3, OmegaMatterNow=0.272, \n        OmegaLambdaNow=0.728, OmegaBaryonNow=0.044, HubbleParameterNow=0.702, \n        HeliumAbundanceByNumber=0.08, CMBTemperatureNow=2.725, \n        approx_highz=False):\n        \n        self.zi = initial_redshift\n        self._cosm = Cosmology(OmegaMatterNow=OmegaMatterNow, \n            OmegaLambdaNow=OmegaLambdaNow, OmegaBaryonNow=OmegaBaryonNow,\n            HubbleParameterNow=HubbleParameterNow, \n            HeliumAbundanceByNumber=HeliumAbundanceByNumber,\n            CMBTemperatureNow=CMBTemperatureNow, \n            approx_highz=approx_highz)        \n        \n    def set_chemistry(self, Z=1, abundances=1.0, energy=False):\n        \"\"\"\n        Initialize chemistry.\n        \n        This routine sets the chemical composition of the medium being \n        simulated.\n        \n        Parameters\n        ----------\n        Z : int, list\n            Atomic number(s) of elements to include in calculation.\n        abundances : float, list, str\n            Abundance(s) (relative to hydrogen) of elements.\n            If chiantiPy is installed, can be a string. Some acceptable\n            abundance strings are:\n                'cosmic', 'sun_photospheric', 'sun_coronal'\n        energy : bool\n            Solve for internal energy or temperature? (not sure if this is\n            used anywhere)\n\n        Example\n        -------\n        grid = Grid(dims=32)\n        grid.set_chemistry(Z=[1,2], abundances='cosmic')  \n        \n        \"\"\"                \n        \n        if type(Z) is not list:\n            Z = [Z]\n  \n        if type(abundances) not in [str, list]:\n            abundances = [abundances]   \n            \n        self.abundances = abundances\n        \n        self.Z = np.array(Z)\n        self.ions_by_parent = {} # Ions sorted by parent element in dictionary\n        self.parents_by_ion = {} # From ion name, determine parent element\n        self.elements = []       # Just a list of element names\n        self.all_ions = []       # All ion species          \n        self.tracked_fields = [] # Anything we're keeping track of\n        self.evolving_fields = []# Anything with an ODE we'll later solve\n          \n        for i, element in enumerate(self.Z):\n            element_name = util.z2element(element)\n                \n            self.ions_by_parent[element_name] = []\n            self.elements.append(element_name)\n            for ion in xrange(element + 1):\n                name = util.zion2name(element, ion + 1)\n                self.all_ions.append(name)\n                self.ions_by_parent[element_name].append(name)\n                self.parents_by_ion[name] = element_name\n                self.tracked_fields.append(name)\n                self.evolving_fields.append(name)\n\n        self.solve_ge = False      \n        self.evolving_fields.append('e')\n        if not self.isothermal:\n            if energy:\n                self.solve_ge = True\n                self.evolving_fields.append('ge')\n            else:    \n                self.evolving_fields.append('Tk')\n\n        # Create blank data fields    \n        if not hasattr(self, 'data'):            \n            self.data = {}\n            for field in self.tracked_fields:\n                self.data[field] = np.zeros(self.dims)\n            \n        # Read abundances from chianti\n        if type(abundances) is str and have_chianti:\n            self.abundances_by_number = util.abundanceRead(abundance)['abundance']\n            self.element_abundances = []\n            for i, Z in enumerate(self.Z):\n                self.element_abundances.append(self.abundances_by_number[Z-1])\n        elif type(abundances) is str:\n            raise ValueError('If chianti is not installed, must supply abundances by number.')             \n        else:\n            self.abundances_by_number = self.abundances\n            self.element_abundances = []\n            for i, Z in enumerate(self.Z):\n                self.element_abundances.append(self.abundances_by_number[i])\n                               \n        # Initialize mapping between q-vector and physical quantities (dengo)                \n        self._set_qmap()\n\n    def set_density(self, rho0=None):\n        \"\"\"\n        Initialize gas density, and from that, the hydrogen number density.\n        \n        Setting the gas density is necessary for computing the hydrogen \n        number density, which normalizes fractional abundances of elements\n        to proper number densities of all species.\n\n        Parameters\n        ----------\n        rho0 : float, array\n            Density of medium in g / cm**3. Can be a float (uniform medium),\n            or an array of values the same size as the grid itself.\n            \n        \"\"\"\n        \n        if isinstance(rho0, Iterable):\n            self.data['rho'] = rho0\n        else:\n            self.data['rho'] = rho0 * np.ones(self.dims)  \n            \n        if len(self.Z) == 1:\n            self.n_H = self.data['rho'] / m_H\n            self.n_He = 0.0 \n        elif len(self.Z) == 2:\n            if 2 not in self.Z:\n                raise ValueError('Only know how to do H+He gas.')\n                \n            self.n_H = (1. - self.cosm.Y) * self.data['rho'] / m_H\n            self.n_He = self.cosm.Y * self.data['rho'] / 4. / m_H\n        \n        self.n_ref = self.n_H\n                    \n        #if len(self.Z) == 1:\n        #    if self.Z == np.ones(1):\n        #        self.abundances_by_number = self.element_abundances = np.ones(1)\n        #        if self.expansion:\n        #            self.n_H = \\\n        #                (1. - self.cosm.Y) * self.data['rho'] / m_H\n        #        else:\n        #            self.n_H = self.data['rho'] / m_H\n        #    else:\n        #        self.n_H = self.data['rho'] / m_H \\\n        #            / ELEMENT(self.elements[0]).mass\n        #            \n        #    self.n_ref = copy.deepcopy(self.n_H)\n        #    return\n        #    \n        #    \n        #                    \n        ## Set hydrogen number density (which normalizes all other species)\n        #X = 0.0\n        #for i in xrange(len(self.abundances_by_number) - 1):\n        #    name = util.z2element(i + 1)\n        #    if not name.strip():\n        #        continue\n        #            \n        #    X += self.abundances_by_number[i] * ELEMENT(name).mass\n        #             \n        ## Set reference number density\n        #if 'h' in self.elements:\n        #    self.n_H = self.n_ref = self.data['rho'] / m_H / X\n        #else:\n        #    self.n_H = self.n_ref = self.data['rho'] / m_H \\\n        #        / ELEMENT(self.elements[0]).mass\n\n    def set_temperature(self, T0):\n        \"\"\"\n        Set initial temperature in grid.  \n        \n        Parameters\n        ----------\n        T0 : float, array\n            Initial temperature in grid. Can be constant value (corresponding\n            to uniform medium), or an array of values like the grid.\n        \"\"\"\n        \n        if isinstance(T0, Iterable):\n            self.data['Tk'] = T0\n        else:\n            self.data['Tk'] = T0 * np.ones(self.dims)\n            \n    def set_ionization(self, Z=None, x=None, state=None, perturb=0):\n        \"\"\"\n        Set initial ionization state.  If Z is None, assume constant ion fraction \n        of 1 / (1 + Z) for all elements.  Can be overridden by 'state', which can be\n        'equilibrium', and maybe eventually other options (e.g. perturbed out of\n        equilibrium slightly, perhaps).\n        \"\"\"       \n        \n        if x is not None:\n            self.data[util.zion2name(Z, 1)].fill(1. - x)\n            self.data[util.zion2name(Z, 2)].fill(x)\n            \n        elif state == 'equilibrium':\n            np.seterr(all = 'ignore')   # This tends to produce divide by zero errors\n            for Z in self.Z:\n                eq = cc.ioneq(Z, self.data['Tk'])\n                \n                for i in xrange(1 + Z):\n                    mask = np.isnan(eq.Ioneq[i])\n                    name = util.zion2name(Z, i + 1)\n                    self.data[name][:] = eq.Ioneq[i]\n                    self.data[name][mask] = np.ones_like(mask[mask == True])\n                    # For some reason chianti sometimes gives nans where\n                    # the neutral fraction (in oxygen at least) should be 1.\n                    # It only happens when cc.ioneq is given an array of temps,\n                    # i.e. everything is fine if you loop over T but that's \n                    # way slower.\n                    if perturb > 0:\n                        tmp = self.data[name] * np.random.normal(loc=1.0, \n                            scale=perturb, size=self.dims)\n                        tmp[tmp < tiny_number] = tiny_number\n                        self.data[name] = copy.copy(tmp)\n                                   \n                # Renormalize                                \n                if perturb > 0:\n                    C = 0\n                    for i in xrange(1 + Z):\n                        name = util.zion2name(Z, i + 1)\n                        C += self.data[name]    \n                            \n                    for i in xrange(1 + Z):\n                        name = util.zion2name(Z, i + 1)        \n                        self.data[name] /= C\n                                        \n            np.seterr(all=None)\n            \n        elif state == 'neutral':\n            for Z in self.Z:\n\n                N = len(self.ions_by_parent[util.z2element(Z)]) - 1\n                            \n                for i in xrange(1 + Z):\n                    name = util.zion2name(Z, i + 1)\n                    \n                    if i == 0:\n                        self.data[name] = np.ones(self.dims) - N * tiny_number\n                    else:\n                        self.data[name] = tiny_number * np.ones(self.dims)\n        \n        else:\n            for species in self.all_ions:\n                self.data[species].fill(1. \\\n                    / (1. + util.convertName(species)['Z']))\n        \n        # Set electron density\n        self._set_electron_fraction()\n        \n        if self.solve_ge:\n            self.set_gas_energy()\n        \n    def set_gas_energy(self):\n        \"\"\"\n        Store ge.\n        \"\"\"    \n        \n        self.data['n'] = self.particle_density(self.data)\n        self.data['ge'] = 1.5 * self.data['n'] * k_B * self.data['Tk']\n        \n    def set_ics(self, data):\n        \"\"\"\n        Simple way of setting all initial conditions at once with a data \n        dictionary.\n        \"\"\"\n        \n        self.data = {}\n        for key in data.keys():\n            if type(data[key]) is float:\n                self.data[key] = data[key]\n                continue\n                \n            self.data[key] = data[key].copy()\n    \n    def make_clump(self, position = None, radius = None, overdensity = None,\n        temperature = None, ionization = None, profile = None):\n        \"\"\" Create a clump! \"\"\"\n                \n        # Figure out where the clump is\n        gridarr = np.linspace(0, 1, self.dims)\n        isclump = (gridarr >= (position - radius)) \\\n                & (gridarr <= (position + radius))\n                \n        # First, modify density and temperature\n        if profile == 0:\n            self.data['rho'][isclump] *= overdensity\n            self.data['n'][isclump] *= overdensity\n            self.n_H[isclump] *= overdensity\n            self.n_ref[isclump] *= overdensity\n            self.data['Tk'][isclump] = temperature\n        #if profile == 1:\n        #    self.data['rho'] += self.data['rho'] * overdensity \\\n        #        * np.exp(-(gridarr - position)**2 / 2. / radius**2)\n        #    self.n_H += self.n_H * overdensity \\\n        #        * np.exp(-(gridarr - position)**2 / 2. / radius**2)\n        #    self.data['T'] -= self.data['T'] * overdensity \\\n        #        * np.exp(-(gridarr - position)**2 / 2. / radius**2)\n           \n        # Need to think more about Gaussian clump T, x.   \n                \n        # Ionization state - could generalize this more\n        for neutral in self.neutrals:\n            self.data[neutral][isclump] = 1. - ionization\n        for ion in self.ions:\n            self.data[ion][isclump] = ionization    \n        \n        # Reset electron density, particle density, and gas energy\n        self._set_electron_fraction()\n                \n        if hasattr(self, '_x_to_n_converter'):        \n            del self._x_to_n_converter\n        \n    def _set_electron_fraction(self):\n        \"\"\"\n        Set electron density - must have run set_density beforehand.\n        \"\"\"\n        \n        self.data['e'] = np.zeros(self.dims)\n        for i, Z in enumerate(self.Z):\n            for j in np.arange(1, 1 + Z):   # j = number of electrons donated by ion j + 1\n                x_i_jp1 = self.data[util.zion2name(Z, j + 1)]\n                self.data['e'] += j * x_i_jp1 * self.n_ref \\\n                    * self.element_abundances[i]  \n                    \n        self.data['e'] /= self.n_H              \n                \n    def particle_density(self, data, z=0):\n        \"\"\"\n        Compute total particle number density.\n        \"\"\"    \n        \n        n = data['e'].copy()\n        #for ion in self.all_ions:\n        #    n += data[ion] * self.x_to_n[ion] * (1. + z)**3 \\\n        #        / (1. + self.zi)**3\n        \n        if self.expansion:\n            n *= self.cosm.nH(z)\n            \n            n += self.cosm.nH(z)\n            \n            if 2 in self.Z:\n                n += self.cosm.nHe(z)\n                \n        else:\n            n *= self.n_H\n            \n            n += self.n_H\n            \n            if 2 in self.Z:\n                n += self.n_H * self.abundances[1]\n             \n        return n \n            \n    def electron_fraction(self, data, z):\n        de = np.zeros(self.dims)\n        for i, Z in enumerate(self.Z):\n            for j in np.arange(1, 1 + Z):   # j = number of electrons donated by ion j + 1\n                x_i_jp1 = data[util.zion2name(Z, j + 1)]\n                de += j * x_i_jp1 * self.n_ref * (1. + z)**3 / (1. + self.zi)**3 \\\n                    * self.element_abundances[i]\n\n        return de / self.n_H\n\n    def ColumnDensity(self, data):\n        \"\"\" Compute column densities for all absorbing species. \"\"\"    \n        \n        N = {}\n        Nc = {}\n        logN = {}\n        for absorber in self.absorbers:\n            Nc[absorber] = self.dr * data[absorber] * self.x_to_n[absorber]            \n            N[absorber] = np.cumsum(Nc[absorber])\n            logN[absorber] = np.log10(N[absorber])\n            \n        return N, logN, Nc\n\n    def _set_qmap(self):\n        \"\"\"\n        The vector 'q' is an array containing the values of all ion fractions and the\n        gas energy.  This routine sets up the mapping between elements in q and the\n        corrresponding physical quantities.\n        \n        Will be in order of increasing Z, then de, then ge.\n        \"\"\"\n        \n        self.qmap = []\n        for species in self.evolving_fields:\n            self.qmap.append(species)\n            \n    def ShellVolume(self, r, dr):\n        \"\"\"\n        Return volume of shell at distance r, thickness dr.\n        \"\"\"\n        \n        return 4. * np.pi * ((r + dr)**3 - r**3) / 3.            \n\n        \n\n        ", "meta": {"hexsha": "ba1a167e2d18d9fbfd5cc2466d39a1926d035df7", "size": 26798, "ext": "py", "lang": "Python", "max_stars_repo_path": "rt1d/static/Grid.py", "max_stars_repo_name": "astrojhgu/rt1d", "max_stars_repo_head_hexsha": "cb49510ae9850d1491dcf9336e3994fb1b153438", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rt1d/static/Grid.py", "max_issues_repo_name": "astrojhgu/rt1d", "max_issues_repo_head_hexsha": "cb49510ae9850d1491dcf9336e3994fb1b153438", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rt1d/static/Grid.py", "max_forks_repo_name": "astrojhgu/rt1d", "max_forks_repo_head_hexsha": "cb49510ae9850d1491dcf9336e3994fb1b153438", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3535620053, "max_line_length": 107, "alphanum_fraction": 0.5201880737, "include": true, "reason": "import numpy", "num_tokens": 6118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.2782568056728001, "lm_q1q2_score": 0.1606920156074511}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nSRI International社の Inter Gamut パターンを改良して、\nGamut の境界を検出するパターンを作成する。\n\"\"\"\n\n# 外部ライブラリのインポート\nimport os\nimport numpy as np\nimport cv2\n\n# 自作ライブラリのインポート\nimport test_pattern_generator2 as tpg\nimport color_space as cs\nimport transfer_functions as tf\nfrom DrawGamutPattern import DrawGamutPattern\nfrom DrawChromaticityDiagram import DrawChromaticityDiagram\nfrom DrawInformation import DrawInformation\nfrom CalcParameters import CalcParameters\n\nmini_primaries = [[0.45, 0.25], [0.30, 0.45], [0.25, 0.20], [0.45, 0.25]]\n\nBASE_PARAM = {\n    'revision': 1,\n    'inner_sample_num': 4,\n    'outer_sample_num': 4,\n    'hue_devide_num': 6,\n    'img_width': 1920,\n    'img_height': 1080,\n    'pattern_space_rate': 0.71,\n    'inner_gamut_name': 'ITU-R BT.709',\n    'outer_gamut_name': 'ITU-R BT.2020',\n    'inner_primaries': np.array(tpg.get_primaries(cs.BT709)[0]),\n    'outer_primaries': np.array(tpg.get_primaries(cs.BT2020)[0]),\n    'transfer_function': tf.SRGB,\n    'background_luminance': 2,\n    'reference_white': 100\n}\n\n\nclass GamutEdgeChecker:\n    \"\"\"\n    ## 概要\n\n    Gamutのエッジをチェックする。\n\n    ## 全体の処理の概要\n\n    ```\n    gamut_edge_checker = GamutEdgeChecker(base_param)\n    gamut_edge_checker.make()\n    gamut_edge_checker.preview()\n    gamut_edge_checker.save()\n    ```\n\n    ## Gec.make() の概要\n\n    ```\n    def make(self):\n        self.make_base_layer()  // 大元の背景画像を準備\n\n        calc_param = CalcParameters(self.base_param)\n        draw_param = calc_param.calc_parameters()\n\n        draw_pattern = DrawGamutPattern(draw_param, self.img)\n        draw_pattern.draw_gamut_tile_pattern()\n\n        draw_diagram = DrawChromaticityDiagram(draw_param, self.img)\n        draw_diagram.draw_chromaticity_diagram()\n\n        text_info = self.make_text_information()\n        draw_information = DrawInformation(text_imfo, self.img)\n        draw_information.draw_information()\n\n        self.apply_oetf()\n    ```\n\n    ## self.make_base_param() の吐き出す値\n\n    ```\n    typedef struct{\n        int revision;\n        int inner_sample_num;  // 内側の描画点の数\n        int outer_sample_num;  // 外側の描画点の数\n        int hue_devide_num;  // 色相方向の分割数。原則4固定。\n        int img_width;\n        int img_height;\n        char *inner_gamut_name;  // 内側の Gamut名\n        char *outer_gamut_name;  // 外側の Gamut名\n        double inner_primaries[3][3];  // 内側のxy色度座標\n        double outer_primaries[3][3];  // 外側のxy色度座標\n        char *transfer_function;  // OETF の指定\n        int reference_white;  // ref white の設定。単位は [cd/m2]。\n    }base_param;\n    ```\n\n    ## self.make_text_information() の吐き出す値\n\n    ```\n    typedef struct{\n        int diagram_width;\n        int diagram_height;\n    }text_info;\n    ```\n\n    ## calc_param.calc_parameters() の吐き出す draw_param 値\n\n    typedef struct{\n        double inner_xyY[12][inner_sample_num][3];\n        double outer_xyY[12][outer_sample_num][3];\n        double innnr_ref_xyY[12][inner_sample_num][3];\n        double outer_ref_xyY[12][inner_sample_num][3];\n        double min_large_y[12];  // inner_xy, outer_xy の largeY最小値。\n                                 // これに合わせて xyY to RGB 変換を行う\n    }draw_param // 12 は 3(RGB) * 4(hue_devide_num) から算出\n    \"\"\"\n    def __init__(self, base_param=BASE_PARAM):\n        self.base_param = base_param\n\n    def make(self):\n        \"\"\"\n        画像生成\n        \"\"\"\n        self.make_base_layer()\n        calc_param = CalcParameters(self.base_param)\n        draw_param = calc_param.calc_parameters()\n        draw_pattern = DrawGamutPattern(self.base_param, draw_param, self.img)\n        draw_pattern.draw_gamut_tile_pattern()\n        draw_diagram = DrawChromaticityDiagram(\n            self.base_param, draw_param, self.img)\n        draw_diagram.draw_chromaticity_diagram()\n        diagram_width, diagram_height =\\\n            draw_diagram.get_diagram_widgh_height()\n        draw_information = DrawInformation(\n            self.base_param, draw_param, self.img,\n            diagram_width, diagram_height)\n        draw_information.draw_information()\n        self.apply_oetf()\n\n    def int(self, x):\n        return int(x + 0.5)\n\n    def make_base_layer(self):\n        \"\"\"\n        ベースとなる背景画像を生成。\n        \"\"\"\n        # 大枠準備\n        width = self.base_param['img_width']\n        height = self.base_param['img_height']\n        self.img = np.zeros((height, width, 3))\n\n        # Gamut パターン配置場所のBG Colorを設定\n        pattern_space_rate = self.base_param['pattern_space_rate']\n        background_luminance = self.base_param['background_luminance']\n        gamut_area_width = int(width * pattern_space_rate)\n        bg_img = np.ones((height, gamut_area_width, 3)) * background_luminance\n        self.img[:, :gamut_area_width, :] = bg_img\n\n    def apply_oetf(self):\n        oetf_name = self.base_param['transfer_function']\n        self.img = tf.oetf_from_luminance(self.img, oetf_name)\n        if np.sum(self.img > 1.0) > 0:\n            print(\"warning. over flow\")\n        elif np.sum(self.img < 0.0) > 0:\n            print(\"warning. under flow\")\n        self.img = np.clip(self.img, 0, 1)\n        self.img = np.uint16(np.round(self.img * 0xFFFF))\n\n    def preview(self):\n        tpg.preview_image(self.img)\n\n    def save(self):\n        cv2.imwrite(\"test.tiff\", self.img[:, :, ::-1])\n\n    def print_output_xyY_header(self):\n        h_num = self.base_param['hue_devide_num'] * 3\n        strings = \"No\" + \",x,y,Y\" * h_num\n        print(strings)\n\n    def output_xyY(self):\n        \"\"\"\n        デバッグとか他のプロジェクトでの流用とかを見越して\n        xyY 情報を出力する。\n        \"\"\"\n        calc_param = CalcParameters(self.base_param)\n        draw_param = calc_param.calc_parameters()\n        self.print_output_xyY_header()\n        s = \",{:.6f},{:.6f},{:.6f}\"\n        counter = 0\n        for idx in range(self.base_param['inner_sample_num']):\n            print(counter, end=\"\")\n            for h_idx in range(self.base_param['hue_devide_num'] * 3):\n                print(s.format(draw_param['inner_xyY'][h_idx][idx][0],\n                               draw_param['inner_xyY'][h_idx][idx][1],\n                               draw_param['inner_xyY'][h_idx][idx][2]),\n                      end=\"\")\n            print(\"\")\n            counter += 1\n        for idx in range(self.base_param['outer_sample_num']):\n            print(counter, end=\"\")\n            for h_idx in range(self.base_param['hue_devide_num'] * 3):\n                print(s.format(draw_param['outer_xyY'][h_idx][idx][0],\n                               draw_param['outer_xyY'][h_idx][idx][1],\n                               draw_param['outer_xyY'][h_idx][idx][2]),\n                      end=\"\")\n            print(\"\")\n            counter += 1\n\n\ndef main_func():\n    gamut_edge_checker = GamutEdgeChecker(base_param=BASE_PARAM)\n    # gamut_edge_checker.make()\n    # gamut_edge_checker.preview()\n    # gamut_edge_checker.save()\n    gamut_edge_checker.output_xyY()\n\n\nif __name__ == '__main__':\n    os.chdir(os.path.dirname(os.path.abspath(__file__)))\n    main_func()\n", "meta": {"hexsha": "b2524de44f39aed896f877a643888945fae2c173", "size": 6913, "ext": "py", "lang": "Python", "max_stars_repo_path": "2019/007_Pixel_3a_low_level_checker/GamutEdgeChecker.py", "max_stars_repo_name": "toru-ver4/sample_code", "max_stars_repo_head_hexsha": "9165b4cb07a3cb1b3b5a7f6b3a329be081bddabe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-11-12T23:34:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T13:21:03.000Z", "max_issues_repo_path": "2019/007_Pixel_3a_low_level_checker/GamutEdgeChecker.py", "max_issues_repo_name": "colour-science/sample_code", "max_issues_repo_head_hexsha": "8bda35b674d770da5a0e6c210634a77691527fce", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 101, "max_issues_repo_issues_event_min_datetime": "2019-08-12T01:20:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T12:17:01.000Z", "max_forks_repo_path": "2019/007_Pixel_3a_low_level_checker/GamutEdgeChecker.py", "max_forks_repo_name": "colour-science/sample_code", "max_forks_repo_head_hexsha": "8bda35b674d770da5a0e6c210634a77691527fce", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-06-08T09:48:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T15:35:51.000Z", "avg_line_length": 31.0, "max_line_length": 78, "alphanum_fraction": 0.6173875307, "include": true, "reason": "import numpy", "num_tokens": 1980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.28776782186926264, "lm_q1q2_score": 0.16066853882098092}}
{"text": "from dataclasses import dataclass, field\nfrom typing import Sequence, List, Optional, cast, Any, TYPE_CHECKING\nimport lightweaver.constants as Const\nimport numpy as np\nfrom .atomic_table import PeriodicTable\nfrom .barklem import Barklem\n\nif TYPE_CHECKING:\n    from .atomic_model import AtomicLine\n    from .atmosphere import Atmosphere\n    from .atomic_set import SpeciesStateTable\n\n@dataclass\nclass LineBroadeningResult:\n    '''\n    Result expected from instances of `LineBroadening.broaden`.\n    '''\n    natural: np.ndarray\n    Qelast: np.ndarray\n    other: Optional[List] = None\n\n\n@dataclass\nclass LineBroadener:\n    '''\n    Base class for broadening implementations. To be used if your broadener\n    does something special and can't just return an array.\n    '''\n    def __repr__(self):\n        raise NotImplementedError\n\n    def setup(self, line: 'AtomicLine'):\n        pass\n\n    def broaden(self, atmos: 'Atmosphere', eqPops: 'SpeciesStateTable') -> Any:\n        raise NotImplementedError\n\n@dataclass\nclass StandardLineBroadener(LineBroadener):\n    '''\n    Standard base class for broadening implementations. Unless you need to do\n    something weird, inherit from this one.\n    '''\n    def __repr__(self):\n        raise NotImplementedError\n\n    def setup(self, line: 'AtomicLine'):\n        pass\n\n    def broaden(self, atmos: 'Atmosphere', eqPops: 'SpeciesStateTable') -> np.ndarray:\n        raise NotImplementedError\n\n\n@dataclass\nclass LineBroadening:\n    '''\n    Standard component of AtomicLine to compute the broadening parameters in\n    a flexible way.\n\n    For most Voigt-like situations, this should be usable without\n    modifications, but this class can be inherited from to make substantial\n    modifications.\n\n    Parameters\n    ----------\n    natural : list of StandardLineBroadener\n        List of broadening terms that are not elastic collisions (separated for PRD).\n    elastic : list of StandardLineBroadener\n        List of elastic broadening terms.\n    other : list of LineBroadener, optional\n        List of other broadening terms, not used by the VoigtLine by default,\n        but existing to provide _options_ (default: None)\n    '''\n    natural: List[StandardLineBroadener]\n    elastic: List[StandardLineBroadener]\n    other: Optional[List[LineBroadener]] = None\n\n    def __repr__(self):\n        otherStr = '' if self.other is None else ', other=%s' % repr(self.other)\n        s = 'LineBroadening(natural=%s, elastic=%s%s)' % (repr(self.natural), repr(self.elastic), otherStr)\n        return s\n\n    def __post_init__(self):\n        if len(self.natural) == 0 and len(self.elastic) == 0:\n            raise ValueError('No standard broadening terms provided to LineBroadening')\n\n    def setup(self, line: 'AtomicLine'):\n        b: LineBroadener\n        for b in self.natural:\n            b.setup(line)\n\n        for b in self.elastic:\n            b.setup(line)\n\n        if self.other is not None:\n            for b in self.other:\n                b.setup(line)\n\n    @staticmethod\n    def sum_broadening_list(broadeners: List[StandardLineBroadener], atmos: 'Atmosphere',\n                            eqPops: 'SpeciesStateTable') -> Optional[np.ndarray]:\n        '''\n        Sums a list of StandardLineBroadeners.\n        '''\n        if len(broadeners) == 0:\n            return None\n\n        result = broadeners[0].broaden(atmos, eqPops)\n        for b in broadeners[1:]:\n            result += b.broaden(atmos, eqPops)\n        return result\n\n    @staticmethod\n    def compute_other_broadening(broadeners: Optional[List[LineBroadener]],\n                                 atmos: 'Atmosphere',\n                                 eqPops: 'SpeciesStateTable') -> Optional[List]:\n        '''\n        Returns a list of the computed broadening terms.\n        '''\n\n        if broadeners is None:\n            return None\n        if len(broadeners) == 0:\n            return None\n\n        result = [b.broaden(atmos, eqPops) for b in broadeners]\n        return result\n\n    def broaden(self, atmos: 'Atmosphere', eqPops: 'SpeciesStateTable') -> LineBroadeningResult:\n        '''\n        Computes the broadening, this function is called by the AtomicLine object.\n        '''\n        natural = self.sum_broadening_list(self.natural, atmos, eqPops)\n        Qelast = self.sum_broadening_list(self.elastic, atmos, eqPops)\n\n        others = self.compute_other_broadening(self.other, atmos, eqPops)\n\n        if natural is None:\n            natural = np.zeros_like(Qelast)\n        elif Qelast is None:\n            Qelast = np.zeros_like(natural)\n\n        return LineBroadeningResult(natural=natural,\n                                    Qelast=Qelast, other=others)\n\n\n@dataclass(eq=False)\nclass VdwApprox(StandardLineBroadener):\n    '''\n    Base class for van der Waals approximation using a list of coefficients\n    (vals).\n    '''\n    vals: Sequence[float]\n    line: 'AtomicLine' = field(init=False)\n\n    def setup(self, line: 'AtomicLine'):\n        self.line = line\n\n    def __repr__(self):\n        s = '%s(vals=%s)' % (type(self).__name__, repr(self.vals))\n        return s\n\n    def __eq__(self, other):\n        if type(self) is not type(other):\n            return False\n\n        if self.vals != other.vals:\n            return False\n\n        try:\n            if self.line != other.line:\n                return False\n        except:\n            pass\n\n        return True\n\n\n@dataclass(eq=False, repr=False)\nclass VdwUnsold(VdwApprox):\n    '''\n    Implementation of the Unsold method for van der Waals broadening.\n    '''\n    def setup(self, line: 'AtomicLine'):\n        self.line = line\n        if len(self.vals) != 2:\n            raise ValueError('VdwUnsold expects 2 coefficients (%s)' % repr(line))\n\n        Z = line.jLevel.stage + 1\n        cont = line.overlyingContinuumLevel\n\n        deltaR = (Const.ERydberg / (cont.E_SI - line.jLevel.E_SI))**2 \\\n                 - (Const.ERydberg / (cont.E_SI - line.iLevel.E_SI))**2\n        fourPiEps0 = 4.0 * np.pi * Const.Epsilon0\n        self.C625 = (2.5 * Const.QElectron**2 / fourPiEps0 * Const.ABarH / fourPiEps0 \\\n                     * 2 * np.pi * (Z * Const.RBohr)**2 / Const.HPlanck * deltaR)**0.4\n\n        element = line.atom.element\n\n        self.vRel35He = (8.0 * Const.KBoltzmann / (np.pi*Const.Amu * element.mass)\\\n                         * (1.0 + element.mass / PeriodicTable[2].mass))**0.3\n        self.vRel35H = (8.0 * Const.KBoltzmann / (np.pi*Const.Amu * element.mass)\\\n                         * (1.0 + element.mass / PeriodicTable[1].mass))**0.3\n\n\n    def broaden(self, atmos: 'Atmosphere', eqPops: 'SpeciesStateTable') -> np.ndarray:\n        '''\n        The function that is called by LineBroadening.\n\n        Parameters\n        ----------\n        atmos : Atmosphere\n            The atmosphere in which to compute the broadening.\n        eqPops : SpeciesStateTable\n            The populations to use for computing the broadening.\n\n        Returns\n        -------\n        broad : np.ndarray\n            An array detailing the broadening at each location in the\n            atmosphere [Nspace].\n        '''\n        heAbund = eqPops.abundance[PeriodicTable[2]]\n        cross = 8.08 * (self.vals[0] * self.vRel35H \\\n                             + self.vals[1] * heAbund * self.vRel35He) * self.C625\n        nHGround = eqPops['H'][0, :]\n        broad = cross * atmos.temperature**0.3 * nHGround\n        return broad\n\n\n@dataclass(eq=False, repr=False)\nclass VdwBarklem(VdwApprox):\n    '''\n    Implementation of the Barklem method for van der Waals broadening.\n    '''\n    def setup(self, line: 'AtomicLine'):\n        self.line = line\n        if len(self.vals) != 2:\n            raise ValueError('VdwBarklem expects 2 coefficients (%s)' % (repr(line)))\n        newVals = Barklem.get_active_cross_section(line.atom, line, self.vals)\n\n        self.barklemVals = newVals\n\n        Z = line.jLevel.stage + 1\n        cont = line.overlyingContinuumLevel\n\n        deltaR = (Const.ERydberg / (cont.E_SI - line.jLevel.E_SI))**2 \\\n                 - (Const.ERydberg / (cont.E_SI - line.iLevel.E_SI))**2\n        fourPiEps0 = 4.0 * np.pi * Const.Epsilon0\n        self.C625 = (2.5 * Const.QElectron**2 / fourPiEps0 * Const.ABarH / fourPiEps0 \\\n                     * 2 * np.pi * (Z * Const.RBohr)**2 / Const.HPlanck * deltaR)**0.4\n\n        element = line.atom.element\n\n        self.vRel35He = (8.0 * Const.KBoltzmann / (np.pi*Const.Amu * element.mass)\\\n                         * (1.0 + element.mass / PeriodicTable[2].mass))**0.3\n\n\n    def broaden(self, atmos: 'Atmosphere', eqPops: 'SpeciesStateTable') -> np.ndarray:\n        '''\n        The function that is called by LineBroadening.\n\n        Parameters\n        ----------\n        atmos : Atmosphere\n            The atmosphere in which to compute the broadening.\n        eqPops : SpeciesStateTable\n            The populations to use for computing the broadening.\n\n        Returns\n        -------\n        broad : np.ndarray\n            An array detailing the broadening at each location in the\n            atmosphere [Nspace].\n        '''\n        heAbund = eqPops.abundance[PeriodicTable[2]]\n        nHGround = eqPops['H'][0, :]\n        cross = 8.08 * self.barklemVals[2] * heAbund * self.vRel35He * self.C625\n\n        broad = self.barklemVals[0] * atmos.temperature**(0.5*(1.0-self.barklemVals[1])) \\\n                 + cross * atmos.temperature**0.3\n        broad *= nHGround\n        return broad\n\n\n@dataclass(eq=False)\nclass RadiativeBroadening(StandardLineBroadener):\n    '''\n    Simple constant radiative broadening with coefficient gamma.\n    '''\n    gamma: float\n    line: 'AtomicLine' = field(init=False)\n\n    def setup(self, line: 'AtomicLine'):\n        self.line = line\n\n    def __repr__(self):\n        s = '%s(gamma=%g)' % (type(self).__name__, self.gamma)\n        return s\n\n    def __eq__(self, other):\n        if type(self) is not type(other):\n            return False\n\n        if self.gamma != other.gamma:\n            return False\n\n        try:\n            if self.line != other.line:\n                return False\n        except:\n            pass\n\n        return True\n\n    def broaden(self, atmos: 'Atmosphere', eqPops: 'SpeciesStateTable') -> np.ndarray:\n        '''\n        The function that is called by LineBroadening.\n\n        Parameters\n        ----------\n        atmos : Atmosphere\n            The atmosphere in which to compute the broadening.\n        eqPops : SpeciesStateTable\n            The populations to use for computing the broadening.\n\n        Returns\n        -------\n        broad : np.ndarray\n            An array detailing the broadening at each location in the\n            atmosphere [Nspace].\n        '''\n        return np.ones_like(atmos.temperature) * self.gamma\n\n@dataclass\nclass QuadraticStarkBroadening(StandardLineBroadener):\n    '''\n    Lindholm theory result for Quadratic Stark broadening by electrons and\n    singly ionised particles.\n    Follows HM2014 pp. 238-239, uses C4 from Traving 1960 via RH.\n    '''\n    coeff: float\n    line: 'AtomicLine' = field(init=False)\n\n    def __repr__(self):\n        s = '%s(coeff=%g)' % (type(self).__name__, self.coeff)\n        return s\n\n    def __eq__(self, other):\n        if type(self) is not type(other):\n            return False\n\n        if self.coeff != other.coeff:\n            return False\n\n        try:\n            if self.line != other.line:\n                return False\n        except:\n            pass\n\n        return True\n\n    def setup(self, line: 'AtomicLine'):\n        self.line = line\n        weight = line.atom.element.mass\n        C = 8.0 * Const.KBoltzmann / (np.pi * Const.Amu * weight)\n        Cm = (1.0 + weight / (Const.MElectron / Const.Amu))**(1.0/6.0)\n        # NOTE(cmo): 28.0 is average atomic weight\n        Cm += (1.0 + weight / (28.0))**(1.0/6.0)\n        self.C = C\n        self.Cm = Cm\n\n        Z = line.iLevel.stage + 1\n        cont = line.overlyingContinuumLevel\n\n        E_Ryd = Const.ERydberg / (1.0 + Const.MElectron / (weight * Const.Amu))\n        neff_l = Z * np.sqrt(E_Ryd / (cont.E_SI - line.iLevel.E_SI))\n        neff_u = Z * np.sqrt(E_Ryd / (cont.E_SI - line.jLevel.E_SI))\n\n        C4 = Const.QElectron**2 / (4.0 * np.pi * Const.Epsilon0) \\\n            * Const.RBohr \\\n            * (2.0 * np.pi * Const.RBohr**2 / Const.HPlanck) / (18.0 * Z**4) \\\n            * ((neff_u * (5.0 * neff_u**2 + 1.0))**2 \\\n                - (neff_l * (5.0 * neff_l**2 + 1.0))**2)\n        self.cStark23 = 11.37 * (self.coeff * C4)**(2.0/3.0)\n\n    def broaden(self, atmos: 'Atmosphere', eqPops: 'SpeciesStateTable') -> np.ndarray:\n        '''\n        The function that is called by LineBroadening.\n\n        Parameters\n        ----------\n        atmos : Atmosphere\n            The atmosphere in which to compute the broadening.\n        eqPops : SpeciesStateTable\n            The populations to use for computing the broadening.\n\n        Returns\n        -------\n        broad : np.ndarray\n            An array detailing the broadening at each location in the\n            atmosphere [Nspace].\n        '''\n        vRel = (self.C * atmos.temperature)**(1.0/6.0) * self.Cm\n        stark = self.cStark23 * vRel * atmos.ne\n        return stark\n\n@dataclass\nclass MultiplicativeStarkBroadening(StandardLineBroadener):\n    '''\n    Simple expression for multiplicative Stark broadening, assumes that this\n    can be expresed as a constant * ne.\n    '''\n    coeff: float\n\n    def __repr__(self):\n        s = '%s(coeff=%g)' % (type(self).__name__, self.coeff)\n        return s\n\n    def __eq__(self, other):\n        if type(self) is not type(other):\n            return False\n\n        if self.coeff != other.coeff:\n            return False\n\n        return True\n\n    def broaden(self, atmos: 'Atmosphere', eqPops: 'SpeciesStateTable') -> np.ndarray:\n        '''\n        The function that is called by LineBroadening.\n\n        Parameters\n        ----------\n        atmos : Atmosphere\n            The atmosphere in which to compute the broadening.\n        eqPops : SpeciesStateTable\n            The populations to use for computing the broadening.\n\n        Returns\n        -------\n        broad : np.ndarray\n            An array detailing the broadening at each location in the\n            atmosphere [Nspace].\n        '''\n        return self.coeff * atmos.ne # type: ignore\n\n@dataclass\nclass HydrogenLinearStarkBroadening(StandardLineBroadener):\n    '''\n    Linear Stark broadening for the case of Hydrogen from Sutton 1978 (like\n    RH).\n    '''\n    line: 'AtomicLine' = field(init=False)\n\n    def __repr__(self):\n        s = '%s()' % type(self).__name__\n        return s\n\n    def __eq__(self, other):\n        if type(self) is not type(other):\n            return False\n\n        try:\n            if self.line != other.line:\n                return False\n        except:\n            pass\n\n        return True\n\n    def setup(self, line: 'AtomicLine'):\n        self.line = line\n\n        if line.atom.element.Z != 1:\n            raise ValueError('HydrogenicLinearStarkBroadening applied to non-Hydrogen line')\n\n    def broaden(self, atmos: 'Atmosphere', eqPops: 'SpeciesStateTable') -> np.ndarray:\n        '''\n        The function that is called by LineBroadening.\n\n        Parameters\n        ----------\n        atmos : Atmosphere\n            The atmosphere in which to compute the broadening.\n        eqPops : SpeciesStateTable\n            The populations to use for computing the broadening.\n\n        Returns\n        -------\n        broad : np.ndarray\n            An array detailing the broadening at each location in the\n            atmosphere [Nspace].\n        '''\n        nUpper = int(np.round(np.sqrt(0.5*self.line.jLevel.g)))\n        nLower = int(np.round(np.sqrt(0.5*self.line.iLevel.g)))\n\n        a1 = 0.642 if nUpper - nLower == 1 else 1.0\n        C = a1 * 0.6 * (nUpper**2 - nLower**2) * Const.CM_TO_M**2\n        GStark = C * atmos.ne**(2.0/3.0)\n        return GStark\n", "meta": {"hexsha": "d0a7f04608f1e4a0c652b9e7944882aa8c86ef54", "size": 15854, "ext": "py", "lang": "Python", "max_stars_repo_path": "lightweaver/broadening.py", "max_stars_repo_name": "aasensio/Lightweaver", "max_stars_repo_head_hexsha": "9a261e72235f05df548148da140012f40dbd1e4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2020-01-13T14:01:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T08:36:45.000Z", "max_issues_repo_path": "lightweaver/broadening.py", "max_issues_repo_name": "aasensio/Lightweaver", "max_issues_repo_head_hexsha": "9a261e72235f05df548148da140012f40dbd1e4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-01-17T13:00:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T12:08:37.000Z", "max_forks_repo_path": "lightweaver/broadening.py", "max_forks_repo_name": "aasensio/Lightweaver", "max_forks_repo_head_hexsha": "9a261e72235f05df548148da140012f40dbd1e4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-07-07T11:21:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T06:52:02.000Z", "avg_line_length": 31.5188866799, "max_line_length": 107, "alphanum_fraction": 0.5906395862, "include": true, "reason": "import numpy", "num_tokens": 4001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.28140560742914383, "lm_q1q2_score": 0.16035973151630903}}
{"text": "# Copyright 1999-2021 Alibaba Group Holding Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport math\nfrom collections import OrderedDict\n\nfrom ....serialization.serializables import (\n    Int64Field,\n    BoolField,\n    Int32Field,\n    Float64Field,\n)\nfrom ....utils import pd_release_version\nfrom ...utils import validate_axis\nfrom ..core import Window\n\n_default_min_period_1 = pd_release_version >= (1, 1, 0)\n_pd_1_3_repr = pd_release_version >= (1, 3, 0)\n\n\nclass EWM(Window):\n    _alpha = Float64Field(\"alpha\")\n    _min_periods = Int64Field(\"min_periods\")\n    _adjust = BoolField(\"adjust\")\n    _ignore_na = BoolField(\"ignore_na\")\n    _axis = Int32Field(\"axis\")\n\n    def __init__(\n        self, alpha=None, min_periods=None, adjust=None, ignore_na=None, axis=None, **kw\n    ):\n        super().__init__(\n            _alpha=alpha,\n            _min_periods=min_periods,\n            _adjust=adjust,\n            _ignore_na=ignore_na,\n            _axis=axis,\n            **kw\n        )\n\n    @property\n    def alpha(self):\n        return self._alpha\n\n    @property\n    def min_periods(self):\n        return self._min_periods\n\n    @property\n    def adjust(self):\n        return self._adjust\n\n    @property\n    def ignore_na(self):\n        return self._ignore_na\n\n    @property\n    def axis(self):\n        return self._axis\n\n    @property\n    def params(self):\n        p = OrderedDict()\n        for k in [\"alpha\", \"min_periods\", \"adjust\", \"ignore_na\", \"axis\"]:\n            p[k] = getattr(self, k)\n        return p\n\n    def __call__(self, df):\n        return df.ewm(**self.params)\n\n    def _repr(self, params):\n        com = 1.0 / params.pop(\"alpha\") - 1\n        params[\"com\"] = int(com) if _pd_1_3_repr and com == math.floor(com) else com\n        try:\n            params.move_to_end(\"com\", last=False)\n        except AttributeError:  # pragma: no cover\n            pass\n        return super()._repr(params)\n\n    def _repr_name(self):\n        try:\n            from pandas.core.window import ExponentialMovingWindow  # noqa: F401\n\n            return \"ExponentialMovingWindow\"\n        except ImportError:  # pragma: no cover\n            return \"EWM\"\n\n    def aggregate(self, func):\n        from .aggregation import DataFrameEwmAgg\n\n        params = self.params\n        params[\"alpha_ignore_na\"] = params.pop(\"ignore_na\", False)\n        params[\"validate_columns\"] = False\n        op = DataFrameEwmAgg(func=func, **params)\n        return op(self)\n\n    agg = aggregate\n\n    def mean(self):\n        return self.aggregate(\"mean\")\n\n    def var(self):\n        return self.aggregate(\"var\")\n\n    def std(self):\n        return self.aggregate(\"std\")\n\n\ndef ewm(\n    obj,\n    com=None,\n    span=None,\n    halflife=None,\n    alpha=None,\n    min_periods=0,\n    adjust=True,\n    ignore_na=False,\n    axis=0,\n):\n    r\"\"\"\n    Provide exponential weighted functions.\n\n    Parameters\n    ----------\n    com : float, optional\n        Specify decay in terms of center of mass,\n        :math:`\\alpha = 1 / (1 + com),\\text{ for } com \\geq 0`.\n    span : float, optional\n        Specify decay in terms of span,\n        :math:`\\alpha = 2 / (span + 1),\\text{ for } span \\geq 1`.\n    halflife : float, optional\n        Specify decay in terms of half-life,\n        :math:`\\alpha = 1 - exp(log(0.5) / halflife),\\text{for} halflife > 0`.\n    alpha : float, optional\n        Specify smoothing factor :math:`\\alpha` directly,\n        :math:`0 < \\alpha \\leq 1`.\n    min_periods : int, default 0\n        Minimum number of observations in window required to have a value\n        (otherwise result is NA).\n    adjust : bool, default True\n        Divide by decaying adjustment factor in beginning periods to account\n        for imbalance in relative weightings\n        (viewing EWMA as a moving average).\n    ignore_na : bool, default False\n        Ignore missing values when calculating weights;\n        specify True to reproduce pre-0.15.0 behavior.\n    axis : {0 or 'index', 1 or 'columns'}, default 0\n        The axis to use. The value 0 identifies the rows, and 1\n        identifies the columns.\n\n    Returns\n    -------\n    DataFrame\n        A Window sub-classed for the particular operation.\n\n    See Also\n    --------\n    rolling : Provides rolling window calculations.\n    expanding : Provides expanding transformations.\n\n    Notes\n    -----\n    Exactly one of center of mass, span, half-life, and alpha must be provided.\n\n    Allowed values and relationship between the parameters are specified in the\n    parameter descriptions above; see the link at the end of this section for\n    a detailed explanation.\n\n    When adjust is True (default), weighted averages are calculated using\n    weights (1-alpha)**(n-1), (1-alpha)**(n-2), ..., 1-alpha, 1.\n\n    When adjust is False, weighted averages are calculated recursively as:\n\n       weighted_average[0] = arg[0];\n       weighted_average[i] = (1-alpha)*weighted_average[i-1] + alpha*arg[i].\n\n    When ignore_na is False (default), weights are based on absolute positions.\n    For example, the weights of x and y used in calculating the final weighted\n    average of [x, None, y] are (1-alpha)**2 and 1 (if adjust is True), and\n    (1-alpha)**2 and alpha (if adjust is False).\n\n    When ignore_na is True (reproducing pre-0.15.0 behavior), weights are based\n    on relative positions. For example, the weights of x and y used in\n    calculating the final weighted average of [x, None, y] are 1-alpha and 1\n    (if adjust is True), and 1-alpha and alpha (if adjust is False).\n\n    More details can be found at\n    https://pandas.pydata.org/pandas-docs/stable/user_guide/computation.html#exponentially-weighted-windows\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> import mars.dataframe as md\n    >>> df = md.DataFrame({'B': [0, 1, 2, np.nan, 4]})\n    >>> df.execute()\n         B\n    0  0.0\n    1  1.0\n    2  2.0\n    3  NaN\n    4  4.0\n    >>> df.ewm(com=0.5).mean().execute()\n              B\n    0  0.000000\n    1  0.750000\n    2  1.615385\n    3  1.615385\n    4  3.670213\n    \"\"\"\n    axis = validate_axis(axis, obj)\n\n    decay_count = 0\n    for arg in (com, span, halflife, alpha):\n        if arg is not None:\n            decay_count += 1\n\n    if decay_count == 0:\n        raise ValueError(\"Must pass one of comass, span, halflife, or alpha\")\n    if decay_count > 1:\n        raise ValueError(\"comass, span, halflife, and alpha are mutually exclusive\")\n\n    if com is not None:\n        if com < 0:\n            raise ValueError(\"comass must satisfy: comass >= 0\")\n        alpha = 1.0 / (1 + com)\n    elif span is not None:\n        if span < 1:\n            raise ValueError(\"span must satisfy: span >= 1\")\n        alpha = 2.0 / (1 + span)\n    elif halflife is not None:\n        if halflife <= 0:\n            raise ValueError(\"halflife must satisfy: halflife > 0\")\n        alpha = 1.0 - math.exp(math.log(0.5) / halflife)\n    if alpha <= 0 or alpha > 1:\n        raise ValueError(\"alpha must satisfy: 0 < alpha <= 1\")\n\n    if not adjust and not ignore_na:\n        raise NotImplementedError(\n            \"adjust == False when ignore_na == False not implemented\"\n        )\n    if axis == 1:\n        raise NotImplementedError(\"axis other than 0 is not supported\")\n\n    if alpha == 1:\n        return obj.expanding(min_periods=min_periods, axis=axis)\n\n    if _default_min_period_1:\n        min_periods = min_periods or 1\n\n    return EWM(\n        input=obj,\n        alpha=alpha,\n        min_periods=min_periods,\n        adjust=adjust,\n        ignore_na=ignore_na,\n        axis=axis,\n    )\n", "meta": {"hexsha": "8391d5adb91e632b9e54a99456746e228bb6e963", "size": 8008, "ext": "py", "lang": "Python", "max_stars_repo_path": "mars/dataframe/window/ewm/core.py", "max_stars_repo_name": "Marascax/mars", "max_stars_repo_head_hexsha": "1f6c3d4d7296fad475ce707bfa00104a1ec3edc7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mars/dataframe/window/ewm/core.py", "max_issues_repo_name": "Marascax/mars", "max_issues_repo_head_hexsha": "1f6c3d4d7296fad475ce707bfa00104a1ec3edc7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mars/dataframe/window/ewm/core.py", "max_forks_repo_name": "Marascax/mars", "max_forks_repo_head_hexsha": "1f6c3d4d7296fad475ce707bfa00104a1ec3edc7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8805970149, "max_line_length": 107, "alphanum_fraction": 0.6228771229, "include": true, "reason": "import numpy", "num_tokens": 2068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.28140560140262283, "lm_q1q2_score": 0.1603597280820801}}
{"text": "import os\nimport sys\nimport numpy as np\nimport math\nfrom matplotlib import pyplot as plt\nimport six\nfrom pyscirsc.gromacs.molecule import correct_pbc, correct_box\nfrom pyscirsc.counting.msd.msd_common import MSDException\nfrom pyscirsc.gromacs.band import Band\nfrom pmx.model import Model\nfrom pmx.xtc import Trajectory\nfrom pmx.ndx import IndexFile\nfrom pyscirsc.gromacs.index import indexes\nfrom pyscirsc.gromacs.trajectory import iterate\nfrom pyscirsc.utils import mkdir_p\n\n\nclass MSDSimplifiedDeviation:\n\n    def __init__(self,\n                 atom_group, bands, restarts,\n                 computation_ttl=[10,100],\n                 verbose=False):\n        \"\"\"\n        :param atom_group: some AtomSelection as in pmx.atomselection\n        :param band:       pyscirsc.gromacs.Band object\n        :param restarts:   list of frame numbers to start new msd computation\n                           (use msd select_starts ... for this purpose)\n        :param verbose:    [default:False] print some info to stdout in process\n        \"\"\"\n        # input\n        # for i, b in enumerate(bands):\n        #     print i, b.left, b.right\n        # for i, r in enumerate(restarts):\n        #     print i, r\n        self.bands = bands\n        self.group = atom_group\n        self.restarts = restarts\n        self.computation_ttl = computation_ttl\n        self.starts = [map(lambda x: x + computation_ttl[0], r) for r in self.restarts]\n        # self.finishes = [map(lambda x: x + computation_ttl[1], r) for r in self.restarts]\n        self.finishes = [[] for r in self.restarts]\n        self.current_restart = [0 for band in self.bands]\n        self.current_start = [0 for band in self.bands]\n        self.current_finish = [0 for band in self.bands]\n        self.xs = [[] for band in self.bands]\n        self.ys = [[] for band in self.bands]\n        self.zs = [[] for band in self.bands]\n        self.xf = [[] for band in self.bands]\n        self.yf = [[] for band in self.bands]\n        self.zf = [[] for band in self.bands]\n        self.ref_positions = [[] for band in self.bands]\n        self.times = []\n        self.frames = []\n        self.traj_len = 0\n        self.verbose = True\n        self.prev_pos = [(a.x[0], a.x[1], a.x[2]) for a in self.group]\n        if not restarts:\n            raise MSDException(\"No restart points given!\")\n\n    def hello(self):\n        s = \"\"\n        s += \"# hello, its MSDSimplifiedDeviation!\\n\"\n        s += \"#    band:          %s\\n\" % str(self.band)\n        s += \"#    atom_group:    %s\\n\" % str([a.x for a in self.group])\n        s += \"#    restarts:      %s\\n\" % self.restarts\n        s += \"#    reference_ttl: %s\\n\" % self.reference_ttl\n        return s\n\n    def count(self, data, frame, fc):\n        \"\"\"\n        Post-trajectory-update hook to be send to\n        pyscirsc.gromacs.trajectory.iterate(...)\n        \"\"\"\n        self.times.append(frame.time)\n        self.frames.append(fc)\n        self.traj_len += 1\n\n        if (True or self.verbose) and fc % 100 == 0:\n            print \"# at frame: \", fc\n\n        # if fc not in [self.restarts[r] for r in self.current_restart] and \\\n        #     fc not in [self.finishes[r] for r in self.current_finish]:\n        #     return\n\n        inband = []\n        for band in self.bands:\n\n            # set inband[i] = true if atom position is inside band borders\n            # we test BEFORE removing pbc, as after correct_pbc it may go to\n            # other periodic image... (we assume xtc trajectory is confined to BOX)\n            inband.append(band.mask(self.group))\n\n        # now correct periodicity (move atoms to their most probable position)\n        box = correct_box(data)\n        no_pbc = [correct_pbc(o, a.x, box) for o, a in zip(self.prev_pos, self.group)]\n\n        for bandidx, band in enumerate(self.bands):\n            # if fc != self.restarts[bandidx][self.current_restart[bandidx]] and \\\n            #     fc != [self.finishes[bandidx][self.current_finish[bandidx]]]:\n            #     continue\n\n            # append new restart position from list if\n            # it was selected for this frame.\n            if fc == self.restarts[bandidx][self.current_restart[bandidx]]:  # at defined intervals\n                self.ref_positions[bandidx].append({\n                    'positions': no_pbc,  # original positions of the atoms\n                    'inband': inband[bandidx],     # mask for the atoms in band\n                })\n                # this guarantees is always a valid index in restarts\n                if self.current_restart[bandidx] < len(self.restarts[bandidx]) - 1:\n                    self.current_restart[bandidx] += 1\n\n            if fc == self.starts[bandidx][self.current_start[bandidx]] or \\\n                (self.current_finish[bandidx] < len(self.finishes[bandidx]) and fc == self.finishes[bandidx][self.current_finish[bandidx]]):\n                # at defined intervals\n\n                if fc == self.starts[bandidx][self.current_start[bandidx]]:\n                    ref = self.ref_positions[bandidx][self.current_start[bandidx]]\n                else:\n                    ref = self.ref_positions[bandidx][self.current_finish[bandidx]]\n\n                x, y, z, N = 0.0, 0.0, 0.0, 0.0\n                common_test = [u and v for u, v in zip(inband[bandidx], ref['inband'])]\n                starts = ref['positions']\n                for atom, orig, common in zip(no_pbc, starts, common_test):\n                    if common:  # if atom is both in ref position and current inband\n                        dx = (atom[0] - orig[0]) ** 2\n                        dy = (atom[1] - orig[1]) ** 2\n                        dz = (atom[2] - orig[2]) ** 2\n                        x += dx\n                        y += dy\n                        z += dz\n                        N += 1.0\n\n                x /= 100.  # A^2 -> nm^2\n                y /= 100.  # A^2 -> nm^2\n                z /= 100.  # A^2 -> nm^2\n\n                if N:\n                    if fc == self.starts[bandidx][self.current_start[bandidx]]:\n                        self.xs[bandidx].append(x / N)\n                        self.ys[bandidx].append(y / N)\n                        self.zs[bandidx].append(z / N)\n                        print \"appending start at\", fc\n                        self.finishes[bandidx].append(fc - self.computation_ttl[0] + self.computation_ttl[1])\n                    else:\n                        self.xf[bandidx].append(x / N)\n                        self.yf[bandidx].append(y / N)\n                        self.zf[bandidx].append(z / N)\n                        print \"finished at\", fc\n\n                else:\n                    if any(inband[bandidx]):\n                        if self.verbose:\n                            msg = \"# EMPTY INTERSECTION at frame={0} time={1} bandidx={2}\"\n                            print msg.format(fc, frame.time, bandidx)\n                    else:\n                        if self.verbose:\n                            msg = \"# EMPTY INBAND at frame={0} time={1} bandidx={2}\"\n                            print msg.format(fc, frame.time, bandidx)\n\n                if fc == self.starts[bandidx][self.current_start[bandidx]]:\n                    if self.current_start[bandidx] < len(self.starts[bandidx]) - 1:\n                        self.current_start[bandidx] += 1\n                else:\n                    # this guarantees is always a valid index in finishes\n                    if self.current_finish[bandidx] < len(self.finishes[bandidx]) - 1:\n                        self.current_finish[bandidx] += 1\n\n        # remember for next frame PBC correction\n        self.prev_pos = no_pbc\n\n\n################################################################################\n# script to be used in msd.py                                                  #\n################################################################################\n\n\n# main function\ndef main(runfile_path=None):\n    # You can adjust those variables\n    pdb_filename   = \"odnPOPC_001.pdb\"  # pdb file with model\n    xtc_filename   = \"odnPOPC_test.xtc\"  # trajectory file\n    begin_frame    = 0     # start frame of the trajectory (in frames, not ps!)\n    end_frame      = 1000  # end frame (if -1 then all) (in frames, not ps!)\n    output_dir     = \"data/output\"  # output in current directory\n    group_resname  = \"OG\"  # residue name of the selected group to compute msd\n    reference_ttl  = 200   # length of msd calculation for each restart (not used at all in this script, but in msd_computation later)\n    min_stay       = 5     # restart points only for atoms in band for that many consecutive frames\n    min_gap        = 25    # minimal gap between restarts\n    max_gap        = 50    # maximal gap between restarts\n    band_dir       = 2     # 0 = x, 1 = y, 2 = z, z is default\n    # band separators:\n    separators = [  # computed externally (in nm!)\n        0.0,         0.85879874,  1.51332498,  # as defined by Ela Plesner\n        4.34488884,  5.00243812,  7.38666648,  # see Diff_tables.doc\n        8.04406502, 10.8815546,  11.5530146,   # first must be 0, last is some\n        25.0                                   # big number greater than the box\n    ]\n    separators = map(lambda x: 10 * x, separators)  # make it angstroems\n\n    starts = {\n        0: [15, 69, 97, 123, 164, 200, 229, 279, 329, 381, 408, 440, 540, 576,\n            609, 636, 670, 695, 721, 749, 775, 803, 829, 869, 919, 964, 990],\n        1: [1, 30, 60, 92, 120, 156, 187, 229, 256, 283, 315, 341, 381, 408,\n            440, 467, 494, 520, 549, 575, 609, 634, 667, 692, 724, 749, 775,\n            803, 831, 864, 894, 920, 953, 980],\n        2: [1, 26, 51, 77, 104, 129, 154, 182, 209, 236, 273, 303, 330, 358,\n            384, 409, 436, 461, 490, 515, 540, 576, 609, 635, 662, 694, 723,\n            749, 775, 800, 829, 861, 886, 914, 939, 964, 990],\n        3: [1, 51, 97, 123, 164, 196, 222, 247, 283, 329, 379, 408, 440, 490,\n            540, 576, 609, 636, 670, 695, 745, 775, 803, 853, 886, 936, 964,\n            990],\n        4: [1, 51, 97, 123, 164, 200, 229, 279, 329, 379, 408, 440, 490, 540,\n            576, 609, 636, 670, 695, 745, 775, 803, 853, 886, 936, 964, 990],\n        5: [1, 38, 69, 97, 123, 164, 200, 229, 279, 306, 335, 360, 391, 419,\n            446, 496, 535, 560, 595, 636, 662, 694, 724, 749, 775, 803, 837,\n            863, 893, 921, 957, 983],\n        6: [1, 26, 52, 81, 108, 140, 168, 195, 228, 254, 279, 309, 334, 365,\n            391, 425, 450, 475, 500, 530, 557, 593, 627, 653, 679, 705, 730,\n            755, 785, 811, 837, 864, 889, 914, 940, 965, 990],\n        7: [1, 51, 97, 123, 164, 200, 229, 279, 329, 379, 408, 440, 490, 540,\n            576, 609, 636, 670, 695, 720, 749, 775, 803, 853, 886, 936, 964,\n            990],\n        8: [1, 51, 89, 123, 165, 196, 225, 266, 316, 348, 377, 408, 435, 470,\n            495, 524, 560, 609, 646, 679, 725, 764, 814, 864, 914, 964, 992],\n    }\n\n    print \"###################################################\"\n    if runfile_path:\n                # this is not nice, but powerfull..\n        d = dict()\n        # exec (open(runfile_path).read(), d, d)\n        exec open(runfile_path).read() in d, d\n        # TODO: grrrrrrrrrrr\n        # TODO: because of the BUG I need to do this this way, grrrrrr....\n        # TODO: make it a local config, (e.g. Main class with main() method)\n        # TODO: and stroe config in self -> then can automatically assign in loop\n        pdb_filename  = d.get('pdb_filename', pdb_filename)\n        xtc_filename  = d.get('xtc_filename', xtc_filename)\n        begin_frame   = d.get('begin_frame', begin_frame)\n        end_frame     = d.get('end_frame', end_frame)\n        output_dir    = d.get('output_dir', output_dir)\n        group_resname = d.get('group_resname', group_resname)\n        reference_ttl = d.get('reference_ttl', reference_ttl)\n        min_stay      = d.get('min_stay', min_stay)\n        min_gap       = d.get('min_gap', min_gap)\n        max_gap       = d.get('max_gap', max_gap)\n        band_dir      = d.get('band_dir', band_dir)\n        separators    = d.get('separators', separators)\n        starts        = d.get('starts', starts)\n\n        print \"# Using config from file: \", sys.argv[-1]\n    else:\n        print \"# Using default (SAMPLE) config...\"\n        print \"# Please review the config and make your own\"\n        print \"# tailored to your needs.\"\n        print \"# To use your own file run: \"\n        print \"#\"\n        print \"#     python \" + \" \".join(sys.argv) + \" my_file.conf\"\n        print \"#\"\n        print \"# my_file.conf should be a python source file\"\n        print \"# (see help below). \"\n\n    in_conf = \"\"\n    in_conf += \"pdb_filename        = \\\"{0}\\\"\\n\".format(pdb_filename)\n    in_conf += \"xtc_filename        = \\\"{0}\\\"\\n\".format(xtc_filename)\n    in_conf += \"begin_frame         = {0}\\n\".format(begin_frame)\n    in_conf += \"end_frame           = {0}\\n\".format(end_frame)\n    in_conf += \"output_dir          = \\\"{0}\\\"\\n\".format(output_dir)\n    in_conf += \"group_resname       = \\\"{0}\\\"\\n\".format(group_resname)\n    in_conf += \"reference_ttl       = {0}\\n\".format(reference_ttl)\n    in_conf += \"min_stay            = {0}\\n\".format(min_stay)\n    in_conf += \"min_gap             = {0}\\n\".format(min_gap)\n    in_conf += \"max_gap             = {0}\\n\".format(max_gap)\n    in_conf += \"band_dir            = {0}\\n\".format(band_dir)\n    in_conf += \"separators          = {0}\\n\".format(separators)\n    in_conf += \"starts              = {0}\\n\".format(str(starts))\n    in_conf += \"end_frame           = {0}\\n\".format(end_frame)\n\n    help_str = \"\"\n    help_str += \"###################################################\\n\"\n    help_str += \"# Command issued was:\\n\"\n    help_str += \"###################################################\\n\"\n    help_str += \"#     python \" + \" \".join(sys.argv) + \"\\n\"\n    help_str += \"###################################################\\n\"\n    help_str += \"# Config file used:\\n\"\n    help_str += \"###################################################\\n\"\n    help_str += \"# (for meaning of variables see script file) ######\\n\"\n    help_str += \"###################################################\\n\"\n    for item in in_conf.split('\\n'):\n        if item:  # no empty lines\n            help_str += \"# {0}\\n\".format(item)\n    help_str += \"###################################################\\n\"\n    help_str += \"# (input file ends here) ##########################\\n\"\n    help_str += \"# Remember to uncomment variables if want to use  #\\n\"\n    help_str += \"# them in a rerun. They are commented for gnuplot #\\n\"\n    help_str += \"# (with default gnuplot comment character '#'     #\\n\"\n    help_str += \"###################################################\\n\"\n\n    # print help / summary\n    print help_str\n\n    reference_ttl = [10, 100]  # dla moich przykladow...\n\n    # make output directory structure\n    mkdir_p(\"{0}\".format(output_dir))  # TODO: backup?\n\n    # read data model\n    data = Model(pdb_filename)\n\n    # prepare useful indexes\n    group_ndx_filename = \"{0}/{1}.ndx\".format(output_dir, group_resname)\n    if not os.path.isfile(group_ndx_filename):\n        for resname, ndx in indexes(data):\n            ndx.write(\"{0}/{1}.ndx\".format(output_dir, resname))\n\n    # get the index for selected group resname\n    # Notice: there is only one group in groups for this index!\n    # we work on group to be faster\n    selected_ndx = IndexFile(group_ndx_filename)\n\n\n    bands = []\n    left_bound = separators[0]\n    for right_bound in separators[1:]:\n        bands.append(Band(left_bound, right_bound, band_dir))\n        left_bound = right_bound\n\n    restarts = [[] for i in range(max(starts.keys())+1)]\n    for key, r in starts.iteritems():\n        restarts[key] = r\n    # reload input data!\n    initial_model = Model(pdb_filename)\n    trajectory = Trajectory(xtc_filename)\n    group = selected_ndx.groups[0].select_atoms(initial_model)\n\n    counter = MSDSimplifiedDeviation(group, bands, restarts, reference_ttl)\n    iterate(initial_model, trajectory, begin_frame, end_frame, counter.count)\n\n    print \"end_frame           = {0}\\n\".format(end_frame)\n\n    print \"AAAAAAAAAA\"\n    print counter.xs\n    print counter.xf\n    print counter.ys\n    print counter.yf\n    print counter.zs\n    print counter.zf\n    print \"BBBBBBBBBB\"\n\n    for layer_no, band in enumerate(bands):\n        # put to file with commments for future use\n        out = file(\"{0}/deviation_layer_{1:03d}.csv\".format(output_dir, layer_no), \"w\")\n        xys = map(lambda a: sum(a), zip(counter.xs[layer_no], counter.ys[layer_no]))\n        xyzs = map(lambda a: sum(a), zip(counter.xs[layer_no], counter.ys[layer_no], counter.zs[layer_no]))\n        xyf = map(lambda a: sum(a), zip(counter.xf[layer_no], counter.yf[layer_no]))\n        xyzf = map(lambda a: sum(a), zip(counter.xf[layer_no], counter.yf[layer_no], counter.zf[layer_no]))\n\n        def simple_fit(t0, x0, t1, x1):\n            return (x1 - x0) / float(t1 - t0)\n\n        fit_fn = lambda x: simple_fit(reference_ttl[0], x[0], reference_ttl[1], x[1])\n        xy = map(fit_fn, zip(xys, xyf))\n        xyz = map(fit_fn, zip(xyzs, xyzf))\n        x = map(fit_fn, zip(counter.xs[layer_no], counter.xf[layer_no]))\n        y = map(fit_fn, zip(counter.ys[layer_no], counter.yf[layer_no]))\n        z = map(fit_fn, zip(counter.zs[layer_no], counter.zf[layer_no]))\n\n        xyz = [a * 1000.0 / 6.0 for a in xyz if a > 0]\n        xy = [a * 1000.0 / 4.0 for a in xy if a > 0]\n        x = [a * 1000.0 / 2.0 for a in x if a > 0]\n        y = [a * 1000.0 / 2.0 for a in y if a > 0]\n        z = [a * 1000.0 / 2.0 for a in z if a > 0]\n        mlen = min(map(len, [xyz, xy, x, y, z]))\n        if mlen:\n            xyz = xyz[:mlen]\n            xy = xy[:mlen]\n            x = x[:mlen]\n            y = y[:mlen]\n            z = z[:mlen]\n        else:\n            xyz = []\n            xy = []\n            x = []\n            y = []\n            z = []\n\n        def sddev(lst):\n            if len(lst):\n                av = sum(lst) / len(lst)\n                var = sum(map(lambda x: (x - av) ** 2, lst)) / len(lst)\n                return math.sqrt(var)\n            else:\n                return -1.0\n\n        stdevs = map(sddev, [xyz, xy, x, y, z])\n\n        data = zip(xyz, xy, x, y, z)\n        # out.write(help_str)\n        # out.write(\"#data in [nm^2]\\n\")\n        out.write(\" \".join(map(str, stdevs)) + \"\\n\\n\")\n        out.write(\"#xyz xy x y z\\n\")\n        for o in data:\n            if all([x > 0 for x in o]):\n                out.write(\" \".join(map(str, o)) + \"\\n\")\n\n        out.close()\n\n    print \"DONE!\"\n", "meta": {"hexsha": "de238bbf454490a1d2ee0fdb30183243744e1dde", "size": 18520, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscirsc/counting/msd/msd_simplified_deviation.py", "max_stars_repo_name": "robsontpm/mcb-permeation", "max_stars_repo_head_hexsha": "56659fe1f78a37a6b0b1fde6a9b6b2a23b257e78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyscirsc/counting/msd/msd_simplified_deviation.py", "max_issues_repo_name": "robsontpm/mcb-permeation", "max_issues_repo_head_hexsha": "56659fe1f78a37a6b0b1fde6a9b6b2a23b257e78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscirsc/counting/msd/msd_simplified_deviation.py", "max_forks_repo_name": "robsontpm/mcb-permeation", "max_forks_repo_head_hexsha": "56659fe1f78a37a6b0b1fde6a9b6b2a23b257e78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.9514563107, "max_line_length": 140, "alphanum_fraction": 0.5267278618, "include": true, "reason": "import numpy", "num_tokens": 5216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.2974699363766585, "lm_q1q2_score": 0.1603313087717543}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nSony Colourspaces\n=================\n\nDefines the *Sony* colourspaces:\n\n-   :attr:`colour.models.S_GAMUT_COLOURSPACE`.\n-   :attr:`colour.models.S_GAMUT3_COLOURSPACE`.\n-   :attr:`colour.models.S_GAMUT3_CINE_COLOURSPACE`.\n-   :attr:`colour.models.VENICE_S_GAMUT3_COLOURSPACE`.\n-   :attr:`colour.models.VENICE_S_GAMUT3_CINE_COLOURSPACE`.\n\nNotes\n-----\n-   The *Venice S-Gamut3* and *Venice S-Gamut3.Cine* primaries and whitepoint\n    were derived with the following `Google Colab Notebook \\\n<https://colab.research.google.com/drive/1ZGTij7jT8eZRMPUkyWlv_x5ix5Q5twMB>`__.\n\nReferences\n----------\n-   :cite:`Gaggioni` : Gaggioni, H., Dhanendra, P., Yamashita, J., Kawada, N.,\n    Endo, K., & Clark, C. (n.d.). S-Log: A new LUT for digital production\n    mastering and interchange applications (Vol. 709, pp. 1-13).\n    http://pro.sony.com/bbsccms/assets/files/mkt/cinema/solutions/slog_manual.pdf\n-   :cite:`SonyCorporation` : Sony Corporation. (n.d.). S-Log Whitepaper (pp.\n    1-17). http://www.theodoropoulos.info/attachments/076_on%20S-Log.pdf\n-   :cite:`SonyCorporationd` : Sony Corporation. (n.d.). Technical Summary\n    for S-Gamut3.Cine/S-Log3 and S-Gamut3/S-Log3 (pp. 1-7).\n    http://community.sony.com/sony/attachments/sony/\\\nlarge-sensor-camera-F5-F55/12359/2/\\\nTechnicalSummary_for_S-Gamut3Cine_S-Gamut3_S-Log3_V1_00.pdf\n-   :cite:`SonyCorporatione` : Sony Corporation. (n.d.).\n    S-Gamut3_S-Gamut3Cine_Matrix.xlsx.\n    https://community.sony.com/sony/attachments/sony/\\\nlarge-sensor-camera-F5-F55/12359/3/S-Gamut3_S-Gamut3Cine_Matrix.xlsx\n-   :cite:`SonyElectronicsCorporation2020` : Sony Electronics Corporation.\n    (2020). IDT.Sony.Venice_SLog3_SGamut3.ctl. https://github.com/ampas/\\\naces-dev/blob/710ecbe52c87ce9f4a1e02c8ddf7ea0d6b611cc8/transforms/ctl/idt/\\\nvendorSupplied/sony/IDT.Sony.Venice_SLog3_SGamut3.ctl\n-   :cite:`SonyElectronicsCorporation2020a` : Sony Electronics Corporation.\n    (2020). IDT.Sony.Venice_SLog3_SGamut3Cine.ctl. https://github.com/ampas/\\\naces-dev/blob/710ecbe52c87ce9f4a1e02c8ddf7ea0d6b611cc8/transforms/ctl/idt/\\\nvendorSupplied/sony/IDT.Sony.Venice_SLog3_SGamut3Cine.ctl\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\n\nfrom colour.colorimetry import ILLUMINANTS\nfrom colour.models.rgb import (RGB_Colourspace, log_encoding_SLog2,\n                               log_decoding_SLog2, log_encoding_SLog3,\n                               log_decoding_SLog3, normalised_primary_matrix)\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2020 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-developers@colour-science.org'\n__status__ = 'Production'\n\n__all__ = [\n    'S_GAMUT_PRIMARIES', 'S_GAMUT_WHITEPOINT_NAME', 'S_GAMUT_WHITEPOINT',\n    'S_GAMUT_TO_XYZ_MATRIX', 'XYZ_TO_S_GAMUT_MATRIX', 'S_GAMUT_COLOURSPACE',\n    'S_GAMUT3_PRIMARIES', 'S_GAMUT3_WHITEPOINT_NAME', 'S_GAMUT3_WHITEPOINT',\n    'S_GAMUT3_TO_XYZ_MATRIX', 'XYZ_TO_S_GAMUT3_MATRIX', 'S_GAMUT3_COLOURSPACE',\n    'S_GAMUT3_CINE_PRIMARIES', 'S_GAMUT3_CINE_WHITEPOINT_NAME',\n    'S_GAMUT3_CINE_WHITEPOINT', 'S_GAMUT3_CINE_TO_XYZ_MATRIX',\n    'XYZ_TO_S_GAMUT3_CINE_MATRIX', 'S_GAMUT3_CINE_COLOURSPACE',\n    'VENICE_S_GAMUT3_PRIMARIES', 'VENICE_S_GAMUT3_WHITEPOINT_NAME',\n    'VENICE_S_GAMUT3_WHITEPOINT', 'VENICE_S_GAMUT3_TO_XYZ_MATRIX',\n    'XYZ_TO_VENICE_S_GAMUT3_MATRIX', 'VENICE_S_GAMUT3_COLOURSPACE',\n    'VENICE_S_GAMUT3_CINE_PRIMARIES', 'VENICE_S_GAMUT3_CINE_WHITEPOINT_NAME',\n    'VENICE_S_GAMUT3_CINE_WHITEPOINT', 'VENICE_S_GAMUT3_CINE_TO_XYZ_MATRIX',\n    'XYZ_TO_VENICE_S_GAMUT3_CINE_MATRIX', 'VENICE_S_GAMUT3_CINE_COLOURSPACE'\n]\n\nS_GAMUT_PRIMARIES = np.array([\n    [0.7300, 0.2800],\n    [0.1400, 0.8550],\n    [0.1000, -0.0500],\n])\n\"\"\"\n*S-Gamut* colourspace primaries.\n\nS_GAMUT_PRIMARIES : ndarray, (3, 2)\n\"\"\"\n\nS_GAMUT_WHITEPOINT_NAME = 'D65'\n\"\"\"\n*S-Gamut* colourspace whitepoint name.\n\nS_GAMUT_WHITEPOINT_NAME : unicode\n\"\"\"\n\nS_GAMUT_WHITEPOINT = (ILLUMINANTS['CIE 1931 2 Degree Standard Observer'][\n    S_GAMUT_WHITEPOINT_NAME])\n\"\"\"\n*S-Gamut* colourspace whitepoint.\n\nS_GAMUT_WHITEPOINT : ndarray\n\"\"\"\n\nS_GAMUT_TO_XYZ_MATRIX = np.array([\n    [0.7064827132, 0.1288010498, 0.1151721641],\n    [0.2709796708, 0.7866064112, -0.0575860820],\n    [-0.0096778454, 0.0046000375, 1.0941355587],\n])\n\"\"\"\n*S-Gamut* colourspace to *CIE XYZ* tristimulus values matrix.\n\nS_GAMUT_TO_XYZ_MATRIX : array_like, (3, 3)\n\"\"\"\n\nXYZ_TO_S_GAMUT_MATRIX = np.array([\n    [1.5073998991, -0.2458221374, -0.1716116808],\n    [-0.5181517271, 1.3553912409, 0.1258786682],\n    [0.0155116982, -0.0078727714, 0.9119163656],\n])\n\"\"\"\n*CIE XYZ* tristimulus values to *S-Gamut* colourspace matrix.\n\nXYZ_TO_S_GAMUT_MATRIX : array_like, (3, 3)\n\"\"\"\n\nS_GAMUT_COLOURSPACE = RGB_Colourspace(\n    'S-Gamut',\n    S_GAMUT_PRIMARIES,\n    S_GAMUT_WHITEPOINT,\n    S_GAMUT_WHITEPOINT_NAME,\n    S_GAMUT_TO_XYZ_MATRIX,\n    XYZ_TO_S_GAMUT_MATRIX,\n    log_encoding_SLog2,\n    log_decoding_SLog2,\n)\nS_GAMUT_COLOURSPACE.__doc__ = \"\"\"\n*S-Gamut* colourspace.\n\nReferences\n----------\n:cite:`Gaggioni`, :cite:`SonyCorporation`\n\nS_GAMUT_COLOURSPACE : RGB_Colourspace\n\"\"\"\n\nS_GAMUT3_PRIMARIES = S_GAMUT_PRIMARIES\n\"\"\"\n*S-Gamut3* colourspace primaries.\n\nS_GAMUT3_PRIMARIES : ndarray, (3, 2)\n\"\"\"\n\nS_GAMUT3_WHITEPOINT_NAME = S_GAMUT_WHITEPOINT_NAME\n\"\"\"\n*S-Gamut3* colourspace whitepoint name.\n\nS_GAMUT3_WHITEPOINT_NAME : unicode\n\"\"\"\n\nS_GAMUT3_WHITEPOINT = S_GAMUT_WHITEPOINT\n\"\"\"\n*S-Gamut3* colourspace whitepoint.\n\nS_GAMUT3_WHITEPOINT : ndarray\n\"\"\"\n\nS_GAMUT3_TO_XYZ_MATRIX = S_GAMUT_TO_XYZ_MATRIX\n\"\"\"\n*S-Gamut3* colourspace to *CIE XYZ* tristimulus values matrix.\n\nS_GAMUT3_TO_XYZ_MATRIX : array_like, (3, 3)\n\"\"\"\n\nXYZ_TO_S_GAMUT3_MATRIX = XYZ_TO_S_GAMUT_MATRIX\n\"\"\"\n*CIE XYZ* tristimulus values to *S-Gamut3* colourspace matrix.\n\nXYZ_TO_S_GAMUT3_MATRIX : array_like, (3, 3)\n\"\"\"\n\nS_GAMUT3_COLOURSPACE = RGB_Colourspace(\n    'S-Gamut3',\n    S_GAMUT3_PRIMARIES,\n    S_GAMUT3_WHITEPOINT,\n    S_GAMUT3_WHITEPOINT_NAME,\n    S_GAMUT3_TO_XYZ_MATRIX,\n    XYZ_TO_S_GAMUT3_MATRIX,\n    log_encoding_SLog3,\n    log_decoding_SLog3,\n)\nS_GAMUT3_COLOURSPACE.__doc__ = \"\"\"\n*S-Gamut3* colourspace.\n\nReferences\n----------\n:cite:`SonyCorporationd`\n\nS_GAMUT3_COLOURSPACE : RGB_Colourspace\n\"\"\"\n\nS_GAMUT3_CINE_PRIMARIES = np.array([\n    [0.76600, 0.27500],\n    [0.22500, 0.80000],\n    [0.08900, -0.08700],\n])\n\"\"\"\n*S-Gamut3.Cine* colourspace primaries.\n\nS_GAMUT3_CINE_PRIMARIES : ndarray, (3, 2)\n\"\"\"\n\nS_GAMUT3_CINE_WHITEPOINT_NAME = S_GAMUT_WHITEPOINT_NAME\n\"\"\"\n*S-Gamut3.Cine* colourspace whitepoint name.\n\nS_GAMUT3_CINE_WHITEPOINT_NAME : unicode\n\"\"\"\n\nS_GAMUT3_CINE_WHITEPOINT = S_GAMUT_WHITEPOINT\n\"\"\"\n*S-Gamut3.Cine* colourspace whitepoint.\n\nS_GAMUT3_CINE_WHITEPOINT : ndarray\n\"\"\"\n\nS_GAMUT3_CINE_TO_XYZ_MATRIX = np.array([\n    [0.5990839208, 0.2489255161, 0.1024464902],\n    [0.2150758201, 0.8850685017, -0.1001443219],\n    [-0.0320658495, -0.0276583907, 1.1487819910],\n])\n\"\"\"\n*S-Gamut3.Cine* colourspace to *CIE XYZ* tristimulus values matrix.\n\nS_GAMUT3_CINE_TO_XYZ_MATRIX : array_like, (3, 3)\n\"\"\"\n\nXYZ_TO_S_GAMUT3_CINE_MATRIX = np.array([\n    [1.8467789693, -0.5259861230, -0.2105452114],\n    [-0.4441532629, 1.2594429028, 0.1493999729],\n    [0.0408554212, 0.0156408893, 0.8682072487],\n])\n\"\"\"\n*CIE XYZ* tristimulus values to *S-Gamut3.Cine* colourspace matrix.\n\nXYZ_TO_S_GAMUT3_CINE_MATRIX : array_like, (3, 3)\n\"\"\"\n\nS_GAMUT3_CINE_COLOURSPACE = RGB_Colourspace(\n    'S-Gamut3.Cine',\n    S_GAMUT3_CINE_PRIMARIES,\n    S_GAMUT3_CINE_WHITEPOINT,\n    S_GAMUT3_CINE_WHITEPOINT_NAME,\n    S_GAMUT3_CINE_TO_XYZ_MATRIX,\n    XYZ_TO_S_GAMUT3_CINE_MATRIX,\n    log_encoding_SLog3,\n    log_decoding_SLog3,\n)\nS_GAMUT3_CINE_COLOURSPACE.__doc__ = \"\"\"\n*S-Gamut3.Cine* colourspace.\n\nReferences\n----------\n:cite:`SonyCorporatione`\n\nS_GAMUT3_CINE_COLOURSPACE : RGB_Colourspace\n\"\"\"\n\nVENICE_S_GAMUT3_PRIMARIES = np.array([\n    [0.740464264304292, 0.279364374750660],\n    [0.089241145423286, 0.893809528608105],\n    [0.110488236673827, -0.052579333080476],\n])\n\"\"\"\n*Venice S-Gamut3* colourspace primaries.\n\nVENICE_S_GAMUT3_PRIMARIES : ndarray, (3, 2)\n\"\"\"\n\nVENICE_S_GAMUT3_WHITEPOINT_NAME = S_GAMUT_WHITEPOINT_NAME\n\"\"\"\n*Venice S-Gamut3* colourspace whitepoint name.\n\nVENICE_S_GAMUT3_WHITEPOINT_NAME : unicode\n\"\"\"\n\nVENICE_S_GAMUT3_WHITEPOINT = S_GAMUT_WHITEPOINT\n\"\"\"\n*Venice S-Gamut3* colourspace whitepoint.\n\nVENICE_S_GAMUT3_WHITEPOINT : ndarray\n\"\"\"\n\nVENICE_S_GAMUT3_TO_XYZ_MATRIX = normalised_primary_matrix(\n    VENICE_S_GAMUT3_PRIMARIES, VENICE_S_GAMUT3_WHITEPOINT)\n\"\"\"\n*Venice S-Gamut3* colourspace to *CIE XYZ* tristimulus values matrix.\n\nVENICE_S_GAMUT3_TO_XYZ_MATRIX : array_like, (3, 3)\n\"\"\"\n\nXYZ_TO_VENICE_S_GAMUT3_MATRIX = np.linalg.inv(VENICE_S_GAMUT3_TO_XYZ_MATRIX)\n\"\"\"\n*CIE XYZ* tristimulus values to *Venice S-Gamut3* colourspace matrix.\n\nXYZ_TO_VENICE_S_GAMUT3_MATRIX : array_like, (3, 3)\n\"\"\"\n\nVENICE_S_GAMUT3_COLOURSPACE = RGB_Colourspace(\n    'Venice S-Gamut3',\n    VENICE_S_GAMUT3_PRIMARIES,\n    VENICE_S_GAMUT3_WHITEPOINT,\n    VENICE_S_GAMUT3_WHITEPOINT_NAME,\n    VENICE_S_GAMUT3_TO_XYZ_MATRIX,\n    XYZ_TO_VENICE_S_GAMUT3_MATRIX,\n    log_encoding_SLog3,\n    log_decoding_SLog3,\n)\nVENICE_S_GAMUT3_COLOURSPACE.__doc__ = \"\"\"\n*Venice S-Gamut3* colourspace.\n\nReferences\n----------\n:cite:`SonyElectronicsCorporation2020`\n\nVENICE_S_GAMUT3_COLOURSPACE : RGB_Colourspace\n\"\"\"\n\nVENICE_S_GAMUT3_CINE_PRIMARIES = np.array([\n    [0.775901871567345, 0.274502392854799],\n    [0.188682902773355, 0.828684937020288],\n    [0.101337382499301, -0.089187517306263],\n])\n\"\"\"\n*Venice S-Gamut3.Cine* colourspace primaries.\n\nVENICE_S_GAMUT3_CINE_PRIMARIES : ndarray, (3, 2)\n\"\"\"\n\nVENICE_S_GAMUT3_CINE_WHITEPOINT_NAME = S_GAMUT_WHITEPOINT_NAME\n\"\"\"\n*Venice S-Gamut3.Cine* colourspace whitepoint name.\n\nVENICE_S_GAMUT3_CINE_WHITEPOINT_NAME : unicode\n\"\"\"\n\nVENICE_S_GAMUT3_CINE_WHITEPOINT = S_GAMUT_WHITEPOINT\n\"\"\"\n*Venice S-Gamut3.Cine* colourspace whitepoint.\n\nVENICE_S_GAMUT3_CINE_WHITEPOINT : ndarray\n\"\"\"\n\nVENICE_S_GAMUT3_CINE_TO_XYZ_MATRIX = normalised_primary_matrix(\n    VENICE_S_GAMUT3_CINE_PRIMARIES, VENICE_S_GAMUT3_CINE_WHITEPOINT)\n\"\"\"\n*Venice S-Gamut3.Cine* colourspace to *CIE XYZ* tristimulus values matrix.\n\nVENICE_S_GAMUT3_CINE_TO_XYZ_MATRIX : array_like, (3, 3)\n\"\"\"\n\nXYZ_TO_VENICE_S_GAMUT3_CINE_MATRIX = np.linalg.inv(\n    VENICE_S_GAMUT3_CINE_TO_XYZ_MATRIX)\n\"\"\"\n*CIE XYZ* tristimulus values to *Venice S-Gamut3.Cine* colourspace matrix.\n\nXYZ_TO_VENICE_S_GAMUT3_CINE_MATRIX : array_like, (3, 3)\n\"\"\"\n\nVENICE_S_GAMUT3_CINE_COLOURSPACE = RGB_Colourspace(\n    'Venice S-Gamut3.Cine',\n    VENICE_S_GAMUT3_CINE_PRIMARIES,\n    VENICE_S_GAMUT3_CINE_WHITEPOINT,\n    VENICE_S_GAMUT3_CINE_WHITEPOINT_NAME,\n    VENICE_S_GAMUT3_CINE_TO_XYZ_MATRIX,\n    XYZ_TO_VENICE_S_GAMUT3_CINE_MATRIX,\n    log_encoding_SLog3,\n    log_decoding_SLog3,\n)\nVENICE_S_GAMUT3_CINE_COLOURSPACE.__doc__ = \"\"\"\n*Venice S-Gamut3.Cine* colourspace.\n\nReferences\n----------\n:cite:`SonyElectronicsCorporation2020a`\n\nVENICE_S_GAMUT3_CINE_COLOURSPACE : RGB_Colourspace\n\"\"\"\n", "meta": {"hexsha": "30673d76effc1a83a6b8c5e58fa11de50e67159a", "size": 10987, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/models/rgb/datasets/sony.py", "max_stars_repo_name": "OmarWagih1/colour", "max_stars_repo_head_hexsha": "bdc880a2783ff523dafb19f1233212dd03a639bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-20T03:44:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-20T14:08:41.000Z", "max_issues_repo_path": "colour/models/rgb/datasets/sony.py", "max_issues_repo_name": "OmarWagih1/colour", "max_issues_repo_head_hexsha": "bdc880a2783ff523dafb19f1233212dd03a639bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/models/rgb/datasets/sony.py", "max_forks_repo_name": "OmarWagih1/colour", "max_forks_repo_head_hexsha": "bdc880a2783ff523dafb19f1233212dd03a639bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2442159383, "max_line_length": 81, "alphanum_fraction": 0.7580777282, "include": true, "reason": "import numpy", "num_tokens": 3976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.16033130436605184}}
{"text": "#\n# Implements the core metrics from sound event detection evaluation module http://tut-arg.github.io/sed_eval/ and\n# The DOA metrics are explained in the SELDnet paper\n#\n# This script has MIT license\n#\n\nimport numpy as np\nfrom scipy.optimize import linear_sum_assignment\neps = np.finfo(np.float).eps\n\n\n##########################################################################################\n# SELD scoring functions - class implementation\n#\n# NOTE: Supports only one-hot labels for both SED and DOA. Doesnt work for baseline method\n# directly, since it estimated DOA in regression approach. Check below the class for\n# one shot (function) implementations of all metrics. The function implementation has\n# support for both one-hot labels and regression values of DOA estimation.\n##########################################################################################\n\nclass SELDMetrics(object):\n    def __init__(self, nb_frames_1s=None, data_gen=None):\n        # SED params\n        self._S = 0\n        self._D = 0\n        self._I = 0\n        self._TP = 0\n        self._Nref = 0\n        self._Nsys = 0\n        self._block_size = nb_frames_1s\n\n        # DOA params\n        self._doa_loss_pred_cnt = 0\n        self._nb_frames = 0\n\n        self._doa_loss_pred = 0\n        self._nb_good_pks = 0\n\n        self._data_gen = data_gen\n\n        self._less_est_cnt, self._less_est_frame_cnt = 0, 0\n        self._more_est_cnt, self._more_est_frame_cnt = 0, 0\n\n    def f1_overall_framewise(self, O, T):\n        TP = ((2 * T - O) == 1).sum()\n        Nref, Nsys = T.sum(), O.sum()\n        self._TP += TP\n        self._Nref += Nref\n        self._Nsys += Nsys\n\n    def er_overall_framewise(self, O, T):\n        FP = np.logical_and(T == 0, O == 1).sum(1)\n        FN = np.logical_and(T == 1, O == 0).sum(1)\n        S = np.minimum(FP, FN).sum()\n        D = np.maximum(0, FN - FP).sum()\n        I = np.maximum(0, FP - FN).sum()\n        self._S += S\n        self._D += D\n        self._I += I\n\n    def f1_overall_1sec(self, O, T):        \n        new_size = int(np.ceil(float(O.shape[0]) / self._block_size))\n        O_block = np.zeros((new_size, O.shape[1]))\n        T_block = np.zeros((new_size, O.shape[1]))\n        for i in range(0, new_size):\n            O_block[i, :] = np.max(O[int(i * self._block_size):int(i * self._block_size + self._block_size - 1), :], axis=0)\n            T_block[i, :] = np.max(T[int(i * self._block_size):int(i * self._block_size + self._block_size - 1), :], axis=0)\n        return self.f1_overall_framewise(O_block, T_block)\n\n    def er_overall_1sec(self, O, T):        \n        new_size = int(np.ceil(float(O.shape[0]) / self._block_size))\n        O_block = np.zeros((new_size, O.shape[1]))\n        T_block = np.zeros((new_size, O.shape[1]))\n        for i in range(0, new_size):\n            O_block[i, :] = np.max(O[int(i * self._block_size):int(i * self._block_size + self._block_size - 1), :], axis=0)\n            T_block[i, :] = np.max(T[int(i * self._block_size):int(i * self._block_size + self._block_size - 1), :], axis=0)\n        return self.er_overall_framewise(O_block, T_block)\n\n    def update_sed_scores(self, pred, gt):\n        \"\"\"\n        Computes SED metrics for one second segments\n\n        :param pred: predicted matrix of dimension [nb_frames, nb_classes], with 1 when sound event is active else 0\n        :param gt:  reference matrix of dimension [nb_frames, nb_classes], with 1 when sound event is active else 0\n        :param nb_frames_1s: integer, number of frames in one second\n        :return:\n        \"\"\"\n        self.f1_overall_1sec(pred, gt)\n        self.er_overall_1sec(pred, gt)\n\n    def compute_sed_scores(self):\n        ER = (self._S + self._D + self._I) / (self._Nref + 0.0)\n\n        prec = float(self._TP) / float(self._Nsys + eps)\n        recall = float(self._TP) / float(self._Nref + eps)\n        F = 2 * prec * recall / (prec + recall + eps)\n\n        return ER, F\n\n    def update_doa_scores(self, pred_doa_thresholded, gt_doa):\n        '''\n        Compute DOA metrics when DOA is estimated using classification approach\n\n        :param pred_doa_thresholded: predicted results of dimension [nb_frames, nb_classes, nb_azi*nb_ele],\n                                    with value 1 when sound event active, else 0\n        :param gt_doa: reference results of dimension [nb_frames, nb_classes, nb_azi*nb_ele],\n                        with value 1 when sound event active, else 0\n        :param data_gen_test: feature or data generator class\n\n        :return: DOA metrics\n\n        '''\n        self._doa_loss_pred_cnt += np.sum(pred_doa_thresholded)\n        self._nb_frames += pred_doa_thresholded.shape[0]\n\n        for frame in range(pred_doa_thresholded.shape[0]):\n            nb_gt_peaks = int(np.sum(gt_doa[frame, :]))\n            nb_pred_peaks = int(np.sum(pred_doa_thresholded[frame, :]))\n\n            # good_frame_cnt includes frames where the nb active sources were zero in both groundtruth and prediction\n            if nb_gt_peaks == nb_pred_peaks:\n                self._nb_good_pks += 1\n            elif nb_gt_peaks > nb_pred_peaks:\n                self._less_est_frame_cnt += 1\n                self._less_est_cnt += (nb_gt_peaks - nb_pred_peaks)\n            elif nb_pred_peaks > nb_gt_peaks:\n                self._more_est_frame_cnt += 1\n                self._more_est_cnt += (nb_pred_peaks - nb_gt_peaks)\n\n            # when nb_ref_doa > nb_estimated_doa, ignores the extra ref doas and scores only the nearest matching doas\n            # similarly, when nb_estimated_doa > nb_ref_doa, ignores the extra estimated doa and scores the remaining matching doas\n            if nb_gt_peaks and nb_pred_peaks:\n                pred_ind = np.where(pred_doa_thresholded[frame] == 1)[1]\n                pred_list_rad = np.array(self._data_gen .get_matrix_index(pred_ind)) * np.pi / 180\n\n                gt_ind = np.where(gt_doa[frame] == 1)[1]\n                gt_list_rad = np.array(self._data_gen .get_matrix_index(gt_ind)) * np.pi / 180\n\n                frame_dist = distance_between_gt_pred(gt_list_rad.T, pred_list_rad.T)\n                self._doa_loss_pred += frame_dist\n\n    def compute_doa_scores(self):\n        doa_error = self._doa_loss_pred / self._doa_loss_pred_cnt\n        frame_recall = self._nb_good_pks / float(self._nb_frames)\n        return doa_error, frame_recall\n\n    def reset(self):\n        # SED params\n        self._S = 0\n        self._D = 0\n        self._I = 0\n        self._TP = 0\n        self._Nref = 0\n        self._Nsys = 0\n\n        # DOA params\n        self._doa_loss_pred_cnt = 0\n        self._nb_frames = 0\n\n        self._doa_loss_pred = 0\n        self._nb_good_pks = 0\n\n        self._less_est_cnt, self._less_est_frame_cnt = 0, 0\n        self._more_est_cnt, self._more_est_frame_cnt = 0, 0\n\n\n###############################################################\n# SED scoring functions\n###############################################################\n\n\ndef reshape_3Dto2D(A):\n    return A.reshape(A.shape[0] * A.shape[1], A.shape[2])\n\n\ndef f1_overall_framewise(O, T):\n    if len(O.shape) == 3:\n        O, T = reshape_3Dto2D(O), reshape_3Dto2D(T)\n    TP = ((2 * T - O) == 1).sum()\n    Nref, Nsys = T.sum(), O.sum()\n\n    prec = float(TP) / float(Nsys + eps)\n    recall = float(TP) / float(Nref + eps)\n    f1_score = 2 * prec * recall / (prec + recall + eps)\n    return f1_score\n\n\ndef er_overall_framewise(O, T):\n    if len(O.shape) == 3:\n        O, T = reshape_3Dto2D(O), reshape_3Dto2D(T)\n\n    FP = np.logical_and(T == 0, O == 1).sum(1)\n    FN = np.logical_and(T == 1, O == 0).sum(1)\n\n    S = np.minimum(FP, FN).sum()\n    D = np.maximum(0, FN-FP).sum()\n    I = np.maximum(0, FP-FN).sum()\n\n    Nref = T.sum()\n    ER = (S+D+I) / (Nref + 0.0)\n    return ER\n\n\ndef f1_overall_1sec(O, T, block_size):\n    if len(O.shape) == 3:\n        O, T = reshape_3Dto2D(O), reshape_3Dto2D(T)\n    new_size = int(np.ceil(float(O.shape[0]) / block_size))\n    O_block = np.zeros((new_size, O.shape[1]))\n    T_block = np.zeros((new_size, O.shape[1]))\n    for i in range(0, new_size):\n        O_block[i, :] = np.max(O[int(i * block_size):int(i * block_size + block_size - 1), :], axis=0)\n        T_block[i, :] = np.max(T[int(i * block_size):int(i * block_size + block_size - 1), :], axis=0)\n    return f1_overall_framewise(O_block, T_block)\n\n\ndef er_overall_1sec(O, T, block_size):\n    if len(O.shape) == 3:\n        O, T = reshape_3Dto2D(O), reshape_3Dto2D(T)\n    new_size = int(np.ceil(float(O.shape[0]) / block_size))\n    O_block = np.zeros((new_size, O.shape[1]))\n    T_block = np.zeros((new_size, O.shape[1]))\n    for i in range(0, new_size):\n        O_block[i, :] = np.max(O[int(i * block_size):int(i * block_size + block_size - 1), :], axis=0)\n        T_block[i, :] = np.max(T[int(i * block_size):int(i * block_size + block_size - 1), :], axis=0)\n    return er_overall_framewise(O_block, T_block)\n\n\ndef compute_sed_scores(pred, gt, nb_frames_1s):\n    \"\"\"\n    Computes SED metrics for one second segments\n\n    :param pred: predicted matrix of dimension [nb_frames, nb_classes], with 1 when sound event is active else 0\n    :param gt:  reference matrix of dimension [nb_frames, nb_classes], with 1 when sound event is active else 0\n    :param nb_frames_1s: integer, number of frames in one second\n    :return:\n    \"\"\"\n    f1o = f1_overall_1sec(pred, gt, nb_frames_1s)\n    ero = er_overall_1sec(pred, gt, nb_frames_1s)\n    scores = [ero, f1o]\n    return scores\n\n\n###############################################################\n# DOA scoring functions\n###############################################################\n\n\ndef compute_doa_scores_regr_xyz(pred_doa, gt_doa, pred_sed, gt_sed):\n    \"\"\"\n        Compute DOA metrics when DOA is estimated using regression approach\n\n    :param pred_doa: predicted doa_labels is of dimension [nb_frames, 3*nb_classes],\n                        nb_classes each for x, y, and z axes,\n                        if active, the DOA values will be in real numbers [-1 1] range, else, it will contain default doa values of (0, 0, 0)\n    :param gt_doa: reference doa_labels is of dimension [nb_frames, 3*nb_classes],\n    :param pred_sed: predicted sed label of dimension [nb_frames, nb_classes] which is 1 for active sound event else zero\n    :param gt_sed: reference sed label of dimension [nb_frames, nb_classes] which is 1 for active sound event else zero\n    :return:\n    \"\"\"\n\n    nb_src_gt_list = np.zeros(gt_doa.shape[0]).astype(int)\n    nb_src_pred_list = np.zeros(gt_doa.shape[0]).astype(int)\n    good_frame_cnt = 0\n    doa_loss_pred = 0.0\n    nb_sed = gt_sed.shape[-1]\n\n    less_est_cnt, less_est_frame_cnt = 0, 0\n    more_est_cnt, more_est_frame_cnt = 0, 0\n\n    for frame_cnt, sed_frame in enumerate(gt_sed):\n        nb_src_gt_list[frame_cnt] = int(np.sum(sed_frame))\n        nb_src_pred_list[frame_cnt] = int(np.sum(pred_sed[frame_cnt]))\n\n        # good_frame_cnt includes frames where the nb active sources were zero in both groundtruth and prediction\n        if nb_src_gt_list[frame_cnt] == nb_src_pred_list[frame_cnt]:\n            good_frame_cnt = good_frame_cnt + 1\n        elif nb_src_gt_list[frame_cnt] > nb_src_pred_list[frame_cnt]:\n            less_est_cnt = less_est_cnt + nb_src_gt_list[frame_cnt] - nb_src_pred_list[frame_cnt]\n            less_est_frame_cnt = less_est_frame_cnt + 1\n        elif nb_src_gt_list[frame_cnt] < nb_src_pred_list[frame_cnt]:\n            more_est_cnt = more_est_cnt + nb_src_pred_list[frame_cnt] - nb_src_gt_list[frame_cnt]\n            more_est_frame_cnt = more_est_frame_cnt + 1\n\n        # when nb_ref_doa > nb_estimated_doa, ignores the extra ref doas and scores only the nearest matching doas\n        # similarly, when nb_estimated_doa > nb_ref_doa, ignores the extra estimated doa and scores the remaining matching doas\n        if nb_src_gt_list[frame_cnt] and nb_src_pred_list[frame_cnt]:\n            # DOA Loss with respect to predicted confidence\n            sed_frame_gt = gt_sed[frame_cnt]\n            doa_frame_gt_x = gt_doa[frame_cnt][:nb_sed][sed_frame_gt == 1]\n            doa_frame_gt_y = gt_doa[frame_cnt][nb_sed:2*nb_sed][sed_frame_gt == 1]\n            doa_frame_gt_z = gt_doa[frame_cnt][2*nb_sed:][sed_frame_gt == 1]\n\n            sed_frame_pred = pred_sed[frame_cnt]\n            doa_frame_pred_x = pred_doa[frame_cnt][:nb_sed][sed_frame_pred == 1]\n            doa_frame_pred_y = pred_doa[frame_cnt][nb_sed:2*nb_sed][sed_frame_pred == 1]\n            doa_frame_pred_z = pred_doa[frame_cnt][2*nb_sed:][sed_frame_pred == 1]\n\n            doa_loss_pred += distance_between_gt_pred_xyz(np.vstack((doa_frame_gt_x, doa_frame_gt_y, doa_frame_gt_z)).T,\n                                                      np.vstack((doa_frame_pred_x, doa_frame_pred_y, doa_frame_pred_z)).T)\n\n    doa_loss_pred_cnt = np.sum(nb_src_pred_list)\n    if doa_loss_pred_cnt:\n        doa_loss_pred /= doa_loss_pred_cnt\n\n    frame_recall = good_frame_cnt / float(gt_sed.shape[0])\n    er_metric = [doa_loss_pred, frame_recall, doa_loss_pred_cnt, good_frame_cnt, more_est_cnt, less_est_cnt]\n    return er_metric\n\n\ndef compute_doa_scores_regr(pred_doa_rad, gt_doa_rad, pred_sed, gt_sed):\n    \"\"\"\n        Compute DOA metrics when DOA is estimated using regression approach\n\n    :param pred_doa_rad: predicted doa_labels is of dimension [nb_frames, 2*nb_classes],\n                        nb_classes each for azimuth and elevation angles,\n                        if active, the DOA values will be in RADIANS, else, it will contain default doa values\n    :param gt_doa_rad: reference doa_labels is of dimension [nb_frames, 2*nb_classes],\n                    nb_classes each for azimuth and elevation angles,\n                    if active, the DOA values will be in RADIANS, else, it will contain default doa values\n    :param pred_sed: predicted sed label of dimension [nb_frames, nb_classes] which is 1 for active sound event else zero\n    :param gt_sed: reference sed label of dimension [nb_frames, nb_classes] which is 1 for active sound event else zero\n    :return:\n    \"\"\"\n\n    nb_src_gt_list = np.zeros(gt_doa_rad.shape[0]).astype(int)\n    nb_src_pred_list = np.zeros(gt_doa_rad.shape[0]).astype(int)\n    good_frame_cnt = 0\n    doa_loss_pred = 0.0\n    nb_sed = gt_sed.shape[-1]\n\n    less_est_cnt, less_est_frame_cnt = 0, 0\n    more_est_cnt, more_est_frame_cnt = 0, 0\n\n    for frame_cnt, sed_frame in enumerate(gt_sed):\n        nb_src_gt_list[frame_cnt] = int(np.sum(sed_frame))\n        nb_src_pred_list[frame_cnt] = int(np.sum(pred_sed[frame_cnt]))\n\n        # good_frame_cnt includes frames where the nb active sources were zero in both groundtruth and prediction\n        if nb_src_gt_list[frame_cnt] == nb_src_pred_list[frame_cnt]:\n            good_frame_cnt = good_frame_cnt + 1\n        elif nb_src_gt_list[frame_cnt] > nb_src_pred_list[frame_cnt]:\n            less_est_cnt = less_est_cnt + nb_src_gt_list[frame_cnt] - nb_src_pred_list[frame_cnt]\n            less_est_frame_cnt = less_est_frame_cnt + 1\n        elif nb_src_gt_list[frame_cnt] < nb_src_pred_list[frame_cnt]:\n            more_est_cnt = more_est_cnt + nb_src_pred_list[frame_cnt] - nb_src_gt_list[frame_cnt]\n            more_est_frame_cnt = more_est_frame_cnt + 1\n\n        # when nb_ref_doa > nb_estimated_doa, ignores the extra ref doas and scores only the nearest matching doas\n        # similarly, when nb_estimated_doa > nb_ref_doa, ignores the extra estimated doa and scores the remaining matching doas\n        if nb_src_gt_list[frame_cnt] and nb_src_pred_list[frame_cnt]:\n            # DOA Loss with respect to predicted confidence\n            sed_frame_gt = gt_sed[frame_cnt]\n            doa_frame_gt_azi = gt_doa_rad[frame_cnt][:nb_sed][sed_frame_gt == 1]\n            doa_frame_gt_ele = gt_doa_rad[frame_cnt][nb_sed:][sed_frame_gt == 1]\n\n            sed_frame_pred = pred_sed[frame_cnt]\n            doa_frame_pred_azi = pred_doa_rad[frame_cnt][:nb_sed][sed_frame_pred == 1]\n            doa_frame_pred_ele = pred_doa_rad[frame_cnt][nb_sed:][sed_frame_pred == 1]\n\n            doa_loss_pred += distance_between_gt_pred(np.vstack((doa_frame_gt_azi, doa_frame_gt_ele)).T,\n                                                      np.vstack((doa_frame_pred_azi, doa_frame_pred_ele)).T)\n\n    doa_loss_pred_cnt = np.sum(nb_src_pred_list)\n    if doa_loss_pred_cnt:\n        doa_loss_pred /= doa_loss_pred_cnt\n\n    frame_recall = good_frame_cnt / float(gt_sed.shape[0])\n    er_metric = [doa_loss_pred, frame_recall, doa_loss_pred_cnt, good_frame_cnt, more_est_cnt, less_est_cnt]\n    return er_metric\n\n\ndef compute_doa_scores_clas(pred_doa_thresholded, gt_doa, data_gen_test):\n    '''\n    Compute DOA metrics when DOA is estimated using classification approach\n\n    :param pred_doa_thresholded: predicted results of dimension [nb_frames, nb_classes, nb_azi*nb_ele],\n                                with value 1 when sound event active, else 0\n    :param gt_doa: reference results of dimension [nb_frames, nb_classes, nb_azi*nb_ele],\n                    with value 1 when sound event active, else 0\n    :param data_gen_test: feature or data generator class\n\n    :return: DOA metrics\n\n    '''\n    doa_loss_pred_cnt = np.sum(pred_doa_thresholded)\n\n    doa_loss_pred = 0\n    nb_good_pks = 0\n\n    less_est_cnt, less_est_frame_cnt = 0, 0\n    more_est_cnt, more_est_frame_cnt = 0, 0\n\n    for frame in range(pred_doa_thresholded.shape[0]):\n        nb_gt_peaks = int(np.sum(gt_doa[frame, :]))\n        nb_pred_peaks = int(np.sum(pred_doa_thresholded[frame, :]))\n\n        # good_frame_cnt includes frames where the nb active sources were zero in both groundtruth and prediction\n        if nb_gt_peaks == nb_pred_peaks:\n            nb_good_pks += 1\n        elif nb_gt_peaks > nb_pred_peaks:\n            less_est_frame_cnt += 1\n            less_est_cnt += (nb_gt_peaks - nb_pred_peaks)\n        elif nb_pred_peaks > nb_gt_peaks:\n            more_est_frame_cnt += 1\n            more_est_cnt += (nb_pred_peaks - nb_gt_peaks)\n\n        # when nb_ref_doa > nb_estimated_doa, ignores the extra ref doas and scores only the nearest matching doas\n        # similarly, when nb_estimated_doa > nb_ref_doa, ignores the extra estimated doa and scores the remaining matching doas\n        if nb_gt_peaks and nb_pred_peaks:\n            pred_ind = np.where(pred_doa_thresholded[frame] == 1)[1]\n            pred_list_rad = np.array(data_gen_test.get_matrix_index(pred_ind)) * np.pi / 180\n\n            gt_ind = np.where(gt_doa[frame] == 1)[1]\n            gt_list_rad = np.array(data_gen_test.get_matrix_index(gt_ind)) * np.pi / 180\n\n            frame_dist = distance_between_gt_pred(gt_list_rad.T, pred_list_rad.T)\n            doa_loss_pred += frame_dist\n\n    if doa_loss_pred_cnt:\n        doa_loss_pred /= doa_loss_pred_cnt\n\n    frame_recall = nb_good_pks / float(pred_doa_thresholded.shape[0])\n    er_metric = [doa_loss_pred, frame_recall, doa_loss_pred_cnt, nb_good_pks, more_est_cnt, less_est_cnt]\n    return er_metric\n\n\ndef distance_between_gt_pred(gt_list_rad, pred_list_rad):\n    \"\"\"\n    Shortest distance between two sets of spherical coordinates. Given a set of groundtruth spherical coordinates,\n     and its respective predicted coordinates, we calculate the spherical distance between each of the spherical\n     coordinate pairs resulting in a matrix of distances, where one axis represents the number of groundtruth\n     coordinates and the other the predicted coordinates. The number of estimated peaks need not be the same as in\n     groundtruth, thus the distance matrix is not always a square matrix. We use the hungarian algorithm to find the\n     least cost in this distance matrix.\n\n    :param gt_list_rad: list of ground-truth spherical coordinates\n    :param pred_list_rad: list of predicted spherical coordinates\n    :return: cost -  distance\n    :return: less - number of DOA's missed\n    :return: extra - number of DOA's over-estimated\n    \"\"\"\n\n    gt_len, pred_len = gt_list_rad.shape[0], pred_list_rad.shape[0]\n    ind_pairs = np.array([[x, y] for y in range(pred_len) for x in range(gt_len)])\n    cost_mat = np.zeros((gt_len, pred_len))\n\n    # Slow implementation\n    # cost_mat = np.zeros((gt_len, pred_len))\n    # for gt_cnt, gt in enumerate(gt_list_rad):\n    #     for pred_cnt, pred in enumerate(pred_list_rad):\n    #         cost_mat[gt_cnt, pred_cnt] = distance_between_spherical_coordinates_rad(gt, pred)\n\n    # Fast implementation\n    if gt_len and pred_len:\n        az1, ele1, az2, ele2 = gt_list_rad[ind_pairs[:, 0], 0], gt_list_rad[ind_pairs[:, 0], 1], \\\n                               pred_list_rad[ind_pairs[:, 1], 0], pred_list_rad[ind_pairs[:, 1], 1]\n        cost_mat[ind_pairs[:, 0], ind_pairs[:, 1]] = distance_between_spherical_coordinates_rad(az1, ele1, az2, ele2)\n\n    row_ind, col_ind = linear_sum_assignment(cost_mat)\n    cost = cost_mat[row_ind, col_ind].sum()\n    return cost\n\n\ndef distance_between_gt_pred_xyz(gt_list, pred_list):\n    \"\"\"\n    Shortest distance between two sets of Cartesian coordinates. Given a set of groundtruth coordinates,\n     and its respective predicted coordinates, we calculate the spherical distance between each of the spherical\n     coordinate pairs resulting in a matrix of distances, where one axis represents the number of groundtruth\n     coordinates and the other the predicted coordinates. The number of estimated peaks need not be the same as in\n     groundtruth, thus the distance matrix is not always a square matrix. We use the hungarian algorithm to find the\n     least cost in this distance matrix.\n\n    :param gt_list: list of ground-truth Cartesian coordinates\n    :param pred_list: list of predicted Cartesian coordinates\n    :return: cost -  distance\n    :return: less - number of DOA's missed\n    :return: extra - number of DOA's over-estimated\n    \"\"\"\n\n    gt_len, pred_len = gt_list.shape[0], pred_list.shape[0]\n    ind_pairs = np.array([[x, y] for y in range(pred_len) for x in range(gt_len)])\n    cost_mat = np.zeros((gt_len, pred_len))\n\n    # Slow implementation\n    # cost_mat = np.zeros((gt_len, pred_len))\n    # for gt_cnt, gt in enumerate(gt_list_rad):\n    #     for pred_cnt, pred in enumerate(pred_list_rad):\n    #         cost_mat[gt_cnt, pred_cnt] = distance_between_spherical_coordinates_rad(gt, pred)\n\n    # Fast implementation\n    if gt_len and pred_len:\n        x1, y1, z1, x2, y2, z2 = gt_list[ind_pairs[:, 0], 0], gt_list[ind_pairs[:, 0], 1], gt_list[ind_pairs[:, 0], 2], \\\n                               pred_list[ind_pairs[:, 1], 0], pred_list[ind_pairs[:, 1], 1], pred_list[ind_pairs[:, 1], 2]\n        cost_mat[ind_pairs[:, 0], ind_pairs[:, 1]] = distance_between_cartesian_coordinates(x1, y1, z1, x2, y2, z2)\n\n    row_ind, col_ind = linear_sum_assignment(cost_mat)\n    cost = cost_mat[row_ind, col_ind].sum()\n    return cost\n\n\ndef distance_between_spherical_coordinates_rad(az1, ele1, az2, ele2):\n    \"\"\"\n    Angular distance between two spherical coordinates\n    MORE: https://en.wikipedia.org/wiki/Great-circle_distance\n\n    :return: angular distance in degrees\n    \"\"\"\n    dist = np.sin(ele1) * np.sin(ele2) + np.cos(ele1) * np.cos(ele2) * np.cos(np.abs(az1 - az2))\n    # Making sure the dist values are in -1 to 1 range, else np.arccos kills the job\n    dist = np.clip(dist, -1, 1)\n    dist = np.arccos(dist) * 180 / np.pi\n    return dist\n\n\ndef distance_between_cartesian_coordinates(x1, y1, z1, x2, y2, z2):\n    \"\"\"\n    Angular distance between two cartesian coordinates\n    MORE: https://en.wikipedia.org/wiki/Great-circle_distance\n    Check 'From chord length' section\n\n    :return: angular distance in degrees\n    \"\"\"\n    # Normalize the Cartesian vectors\n    N1 = np.sqrt(x1**2 + y1**2 + z1**2 + 1e-10)\n    N2 = np.sqrt(x2**2 + y2**2 + z2**2 + 1e-10)\n    x1, y1, z1, x2, y2, z2 = x1/N1, y1/N1, z1/N1, x2/N2, y2/N2, z2/N2\n\n    #Compute the distance\n    dist = x1*x2 + y1*y2 + z1*z2\n    dist = np.clip(dist, -1, 1)\n    dist = np.arccos(dist) * 180 / np.pi\n    return dist\n\n\ndef sph2cart(azimuth, elevation, r):\n    '''\n    Convert spherical to cartesian coordinates\n\n    :param azimuth: in radians\n    :param elevation: in radians\n    :param r: in meters\n    :return: cartesian coordinates\n    '''\n\n    x = r * np.cos(elevation) * np.cos(azimuth)\n    y = r * np.cos(elevation) * np.sin(azimuth)\n    z = r * np.sin(elevation)\n    return x, y, z\n\n\ndef cart2sph(x, y, z):\n    '''\n    Convert cartesian to spherical coordinates\n\n    :param x:\n    :param y:\n    :param z:\n    :return: azi, ele in radians and r in meters\n    '''\n\n    azimuth = np.arctan2(y,x)\n    elevation = np.arctan2(z,np.sqrt(x**2 + y**2))\n    r = np.sqrt(x**2 + y**2 + z**2)\n    return azimuth, elevation, r\n\n\n###############################################################\n# SELD scoring functions\n###############################################################\n\n\ndef early_stopping_metric(sed_error, doa_error):\n    \"\"\"\n    Compute early stopping metric from sed and doa errors.\n\n    :param sed_error: [error rate (0 to 1 range), f score (0 to 1 range)]\n    :param doa_error: [doa error (in degrees), frame recall (0 to 1 range)]\n    :return: seld metric result\n    \"\"\"\n    seld_metric = np.mean([\n        sed_error[0],\n        1 - sed_error[1],\n        doa_error[0]/180,\n        1 - doa_error[1]]\n        )\n    return seld_metric\n\n\n\n\n", "meta": {"hexsha": "6058f9fe70a369034b3f088c66e0dbf68586d0f5", "size": 25158, "ext": "py", "lang": "Python", "max_stars_repo_path": "baseline/metrics/evaluation_metrics.py", "max_stars_repo_name": "andresperezlopez/DCASE2020", "max_stars_repo_head_hexsha": "324f13e3ae9bb7e5677d93fa09e58a55020717a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-07-02T07:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T11:20:04.000Z", "max_issues_repo_path": "baseline/metrics/evaluation_metrics.py", "max_issues_repo_name": "andresperezlopez/DCASE2020", "max_issues_repo_head_hexsha": "324f13e3ae9bb7e5677d93fa09e58a55020717a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "baseline/metrics/evaluation_metrics.py", "max_forks_repo_name": "andresperezlopez/DCASE2020", "max_forks_repo_head_hexsha": "324f13e3ae9bb7e5677d93fa09e58a55020717a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-28T09:29:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-28T09:29:00.000Z", "avg_line_length": 42.4966216216, "max_line_length": 141, "alphanum_fraction": 0.646951268, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.16033130436605184}}
{"text": "\"\"\"\nGenerate a sample using the Method of Morris\n\nThree variants of Morris' sampling for elementary effects is supported:\n\n- Vanilla Morris\n- Optimised trajectories when ``optimal_trajectories=True`` (using\n    Campolongo's enhancements from 2007 and optionally Ruano's enhancement\n    from 2012; ``local_optimization=True``)\n- Groups with optimised trajectories when ``optimal_trajectories=True`` and\n    the problem definition specifies groups (note that ``local_optimization``\n    must be ``False``)\n\nAt present, optimised trajectories is implemented using either a brute-force\napproach, which can be very slow, especially if you require more than four\ntrajectories, or a local method based which is much faster. Both methods now\nimplement working with groups of factors.\n\nNote that the number of factors makes little difference,\nbut the ratio between number of optimal trajectories and the sample size\nresults in an exponentially increasing number of scores that must be\ncomputed to find the optimal combination of trajectories.  We suggest going\nno higher than 4 from a pool of 100 samples with the brute force approach.\nWith local_optimization = True (which is default),\nit is possible to go higher than the previously suggested 4 from 100.\n\n\"\"\"\nfrom __future__ import division\n\nimport numpy as np\n\nimport numpy.random as rd\n\nfrom . gurobi import GlobalOptimisation\nfrom . local import LocalOptimisation\nfrom . brute import BruteForce\n\nfrom . strategy import SampleMorris\n\nfrom SALib.sample import common_args\nfrom SALib.util import scale_samples, read_param_file, compute_groups_matrix\n\ntry:\n    import gurobipy\nexcept ImportError:\n    _has_gurobi = False\nelse:\n    _has_gurobi = True\n\n__all__ = ['sample']\n\n\ndef sample(problem, N, num_levels=4, optimal_trajectories=None,\n           local_optimization=True):\n    \"\"\"Generate model inputs using the Method of Morris\n\n    Returns a NumPy matrix containing the model inputs required for Method of\n    Morris.  The resulting matrix has :math:`(G+1)*T` rows and :math:`D`\n    columns, where :math:`D` is the number of parameters, :math:`G` is the\n    number of groups (if no groups are selected, the number of parameters).\n    :math:`T` is the number of trajectories :math:`N`,\n    or `optimal_trajectories` if selected.\n    These model inputs  are intended to be used with\n    :func:`SALib.analyze.morris.analyze`.\n\n    Parameters\n    ----------\n    problem : dict\n        The problem definition\n    N : int\n        The number of trajectories to generate\n    num_levels : int, default=4\n        The number of grid levels\n    optimal_trajectories : int\n        The number of optimal trajectories to sample (between 2 and N)\n    local_optimization : bool, default=True\n        Flag whether to use local optimization according to Ruano et al. (2012)\n        Speeds up the process tremendously for bigger N and num_levels.\n        If set to ``False`` brute force method is used, unless ``gurobipy`` is\n        available\n\n    Returns\n    -------\n    sample : numpy.ndarray\n        Returns a numpy.ndarray containing the model inputs required for Method\n        of Morris. The resulting matrix has :math:`(G/D+1)*N/T` rows and\n        :math:`D` columns, where :math:`D` is the number of parameters.\n    \"\"\"\n    if problem.get('groups'):\n        sample = _sample_groups(problem, N, num_levels)\n    else:\n        sample = _sample_oat(problem, N, num_levels)\n\n    if optimal_trajectories:\n\n        sample = _compute_optimised_trajectories(problem,\n                                                 sample,\n                                                 N,\n                                                 optimal_trajectories,\n                                                 local_optimization)\n\n    scale_samples(sample, problem['bounds'])\n    return sample\n\n\ndef _sample_oat(problem, N, num_levels=4):\n    \"\"\"Generate trajectories without groups\n\n    Arguments\n    ---------\n    problem : dict\n        The problem definition\n    N : int\n        The number of samples to generate\n    num_levels : int, default=4\n        The number of grid levels\n    \"\"\"\n    group_membership = np.asmatrix(np.identity(problem['num_vars'],\n                                               dtype=int))\n\n    num_params = group_membership.shape[0]\n    sample = np.array([generate_trajectory(group_membership,\n                                           num_levels)\n                       for n in range(N)])\n    return sample.reshape((N * (num_params + 1), num_params))\n\n\ndef _sample_groups(problem, N, num_levels=4):\n    \"\"\"Generate trajectories for groups\n\n    Returns an :math:`N(g+1)`-by-:math:`k` array of `N` trajectories,\n    where :math:`g` is the number of groups and :math:`k` is the number\n    of factors\n\n    Arguments\n    ---------\n    problem : dict\n        The problem definition\n    N : int\n        The number of trajectories to generate\n    num_levels : int, default=4\n        The number of grid levels\n\n    Returns\n    -------\n    numpy.ndarray\n    \"\"\"\n    if len(problem['groups']) != problem['num_vars']:\n        raise ValueError(\"Groups do not match to number of variables\")\n\n    group_membership, _ = compute_groups_matrix(problem['groups'])\n\n    if group_membership is None:\n        raise ValueError(\"Please define the 'group_membership' matrix\")\n    if not isinstance(group_membership, np.ndarray):\n        raise TypeError(\"Argument 'group_membership' should be formatted \\\n                         as a numpy ndarray\")\n\n    num_params = group_membership.shape[0]\n    num_groups = group_membership.shape[1]\n    sample = np.zeros((N * (num_groups + 1), num_params))\n    sample = np.array([generate_trajectory(group_membership,\n                                           num_levels)\n                       for n in range(N)])\n    return sample.reshape((N * (num_groups + 1), num_params))\n\n\ndef generate_trajectory(group_membership, num_levels=4):\n    \"\"\"Return a single trajectory\n\n    Return a single trajectory of size :math:`(g+1)`-by-:math:`k`\n    where :math:`g` is the number of groups,\n    and :math:`k` is the number of factors,\n    both implied by the dimensions of `group_membership`\n\n    Arguments\n    ---------\n    group_membership : np.ndarray\n        a k-by-g matrix which notes factor membership of groups\n    num_levels : int, default=4\n        The number of levels in the grid\n\n    Returns\n    -------\n    np.ndarray\n    \"\"\"\n\n    delta = compute_delta(num_levels)\n\n    # Infer number of groups `g` and number of params `k` from\n    # `group_membership` matrix\n    num_params = group_membership.shape[0]\n    num_groups = group_membership.shape[1]\n\n    # Matrix B - size (g + 1) * g -  lower triangular matrix\n    B = np.tril(np.ones([num_groups + 1, num_groups],\n                        dtype=int), -1)\n\n    P_star = generate_p_star(num_groups)\n\n    # Matrix J - a (g+1)-by-num_params matrix of ones\n    J = np.ones((num_groups + 1, num_params))\n\n    # Matrix D* - num_params-by-num_params matrix which decribes whether\n    # factors move up or down\n    D_star = np.diag(rd.choice([-1, 1], num_params))\n\n    x_star = generate_x_star(num_params, num_levels)\n\n    # Matrix B* - size (num_groups + 1) * num_params\n    B_star = compute_b_star(J, x_star, delta, B,\n                            group_membership, P_star, D_star)\n\n    return B_star\n\n\ndef compute_b_star(J, x_star, delta, B, G, P_star, D_star):\n    \"\"\"\n    \"\"\"\n    element_a = J[0, :] * x_star\n    element_b = np.matmul(G, P_star).T\n    element_c = np.matmul(2.0 * B, element_b)\n    element_d = np.matmul((element_c - J), D_star)\n\n    b_star = element_a + (delta / 2.0) * (element_d + J)\n    return b_star\n\n\ndef generate_p_star(num_groups):\n    \"\"\"Describe the order in which groups move\n\n    Arguments\n    ---------\n    num_groups : int\n\n    Returns\n    -------\n    np.ndarray\n        Matrix P* - size (g-by-g)\n    \"\"\"\n    p_star = np.eye(num_groups, num_groups)\n    rd.shuffle(p_star)\n    return p_star\n\n\ndef generate_x_star(num_params, num_levels):\n    \"\"\"Generate an 1-by-num_params array to represent initial position for EE\n\n    This should be a randomly generated array in the p level grid\n    :math:`\\omega`\n\n    Arguments\n    ---------\n    num_params : int\n        The number of parameters (factors)\n    num_levels : int\n        The number of levels\n\n    Returns\n    -------\n    numpy.ndarray\n        The initial starting positions of the trajectory\n\n    \"\"\"\n    x_star = np.zeros((1, num_params))\n    delta = compute_delta(num_levels)\n    bound = 1 - delta\n    grid = np.linspace(0, bound, 2)\n\n    x_star[0, :] = rd.choice(grid, num_params)\n\n    return x_star\n\n\ndef compute_delta(num_levels):\n    \"\"\"Computes the delta value from number of levels\n\n    Arguments\n    ---------\n    num_levels : int\n        The number of levels\n\n    Returns\n    -------\n    float\n    \"\"\"\n    return num_levels / (2.0 * (num_levels - 1))\n\n\ndef _compute_optimised_trajectories(problem, input_sample, N, k_choices,\n                                    local_optimization=False):\n    '''\n    Calls the procedure to compute the optimum k_choices of trajectories\n    from the input_sample.\n    If there are groups, then this procedure allocates the groups to the\n    correct call here.\n\n    Arguments\n    ---------\n    problem : dict\n        The problem definition\n    input_sample :\n    N : int\n        The number of samples to generate\n    k_choices : int\n        The number of optimal trajectories\n    local_optimization : bool, default=False\n        If true, uses local optimisation heuristic\n    '''\n    if _has_gurobi is False \\\n            and local_optimization is False \\\n            and k_choices > 10:\n        msg = \"Running optimal trajectories greater than values of 10 \\\n                will take a long time.\"\n        raise ValueError(msg)\n\n    num_params = problem['num_vars']\n\n    if np.any((input_sample < 0) | (input_sample > 1)):\n        raise ValueError(\"Input sample must be scaled between 0 and 1\")\n\n    if _has_gurobi and local_optimization is False:\n        # Use global optimization method\n        strategy = GlobalOptimisation()\n    elif local_optimization:\n        # Use local method\n        strategy = LocalOptimisation()\n    else:\n        # Use brute force approach\n        strategy = BruteForce()\n\n    if problem.get('groups'):\n        num_groups = len(set(problem['groups']))\n    else:\n        num_groups = None\n\n    context = SampleMorris(strategy)\n    output = context.sample(input_sample, N, num_params,\n                            k_choices, num_groups)\n\n    return output\n\n\ndef cli_parse(parser):\n    parser.add_argument('-l', '--levels', type=int, required=False,\n                        default=4, help='Number of grid levels \\\n                        (Morris only)')\n    parser.add_argument('-k', '--k-optimal', type=int, required=False,\n                        default=None,\n                        help='Number of optimal trajectories \\\n                        (Morris only)')\n    parser.add_argument('-lo', '--local', type=bool, required=True,\n                        default=False,\n                        help='Use the local optimisation method \\\n                        (Morris with optimization only)')\n    return parser\n\n\ndef cli_action(args):\n    rd.seed(args.seed)\n\n    problem = read_param_file(args.paramfile)\n    param_values = sample(problem, args.samples, args.levels,\n                          args.k_optimal, args.local)\n\n    np.savetxt(args.output, param_values, delimiter=args.delimiter,\n               fmt='%.' + str(args.precision) + 'e')\n\n\nif __name__ == \"__main__\":\n    common_args.run_cli(cli_parse, cli_action)\n", "meta": {"hexsha": "ab1aff9c319a6398fec673c8d5f5cf202f5b3bc3", "size": 11580, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/SALib/sample/morris/__init__.py", "max_stars_repo_name": "cmutel/SALib", "max_stars_repo_head_hexsha": "32e33c423bcc981d0cfd4339a3e2435d6b945de1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SALib/sample/morris/__init__.py", "max_issues_repo_name": "cmutel/SALib", "max_issues_repo_head_hexsha": "32e33c423bcc981d0cfd4339a3e2435d6b945de1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SALib/sample/morris/__init__.py", "max_forks_repo_name": "cmutel/SALib", "max_forks_repo_head_hexsha": "32e33c423bcc981d0cfd4339a3e2435d6b945de1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1290322581, "max_line_length": 79, "alphanum_fraction": 0.6363557858, "include": true, "reason": "import numpy", "num_tokens": 2604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.29746993014852224, "lm_q1q2_score": 0.1603313010091909}}
{"text": "import logging\n\nimport numpy as np\nfrom nengo.dists import Choice\nfrom nengo.exceptions import BuildError\nfrom nengo.neurons import (\n    LIF,\n    LIFRate,\n    RectifiedLinear,\n    RegularSpiking,\n    SpikingRectifiedLinear,\n)\n\nfrom nengo_loihi.compat import HAS_DL, HAS_TF, nengo_dl, tf\n\ntry:\n    from nengo_extras.loihi_training import (\n        LoihiLIFBuilder,\n        LoihiSpikingRectifiedLinearBuilder,\n    )\n\nexcept ImportError:  # pragma: no cover\n\n    class ErrorBuilder:\n        def __init__(self, ops):\n            raise BuildError(\n                \"Building Loihi neuron types in nengo-dl requires nengo-extras>=0.5. \"\n                \"Please install or upgrade nengo-extras.\"\n            )\n\n    LoihiLIFBuilder = LoihiSpikingRectifiedLinearBuilder = ErrorBuilder\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Installer:\n    def __init__(self):\n        self.installed = False\n\n    def __call__(self):\n        if self.installed or not HAS_DL:\n            pass\n        else:\n            logger.info(\"Installing NengoDL neuron builders\")\n            nengo_dl.neuron_builders.SimNeuronsBuilder.TF_NEURON_IMPL[\n                LoihiLIF\n            ] = LoihiLIFBuilder\n            nengo_dl.neuron_builders.SimNeuronsBuilder.TF_NEURON_IMPL[\n                LoihiSpikingRectifiedLinear\n            ] = LoihiSpikingRectifiedLinearBuilder\n            self.installed = True\n\n\ninstall_dl_builders = Installer()\n\n\ndef discretize_tau_rc(tau_rc, dt):\n    \"\"\"Discretize tau_rc as per discretize_compartment.\n\n    Parameters\n    ----------\n    tau_rc : float\n        The neuron membrane time constant.\n    dt : float\n        The simulator time step.\n    \"\"\"\n    lib = tf.math if HAS_TF and isinstance(tau_rc, tf.Tensor) else np\n\n    decay_rc = -(lib.expm1(-dt / tau_rc))\n    decay_rc = lib.round(decay_rc * (2**12 - 1)) / (2**12 - 1)\n    return -dt / lib.log1p(-decay_rc)\n\n\ndef discretize_tau_ref(tau_ref, dt):\n    \"\"\"Discretize tau_ref as per Compartment.configure_lif.\n\n    Parameters\n    ----------\n    tau_rc : float\n        The neuron membrane time constant.\n    dt : float\n        The simulator time step.\n    \"\"\"\n    lib = tf.math if HAS_TF and isinstance(tau_ref, tf.Tensor) else np\n\n    return dt * lib.round(tau_ref / dt)\n\n\ndef loihi_lif_rates(neuron_type, x, gain, bias, dt, amplitude=None):\n    tau_ref = discretize_tau_ref(neuron_type.tau_ref, dt)\n    tau_rc = discretize_tau_rc(neuron_type.tau_rc, dt)\n    amplitude = neuron_type.amplitude if amplitude is None else amplitude\n\n    j = neuron_type.current(x, gain, bias) - 1\n    out = np.zeros_like(j)\n    period = tau_ref + tau_rc * np.log1p(1.0 / j[j > 0])\n    out[j > 0] = (amplitude / dt) / np.ceil(period / dt)\n    return out\n\n\ndef loihi_spikingrectifiedlinear_rates(neuron_type, x, gain, bias, dt, amplitude=None):\n    amplitude = neuron_type.amplitude if amplitude is None else amplitude\n\n    j = neuron_type.current(x, gain, bias)\n    out = np.zeros_like(j)\n    period = 1.0 / j[j > 0]\n    out[j > 0] = (amplitude / dt) / np.ceil(period / dt)\n    return out\n\n\ndef loihi_regularspiking_rates(neuron_type, x, gain, bias, dt):\n    base_type = neuron_type.base_type\n    if type(base_type) is LIFRate:\n        return loihi_lif_rates(\n            base_type, x, gain, bias, dt, amplitude=neuron_type.amplitude\n        )\n    elif type(base_type) is RectifiedLinear:\n        return loihi_spikingrectifiedlinear_rates(\n            base_type, x, gain, bias, dt, amplitude=neuron_type.amplitude\n        )\n    else:\n        return neuron_type.rates(x, gain, bias)\n\n\ndef _broadcast_rates_inputs(x, gain, bias):\n    x = np.array(x, dtype=float, copy=False, ndmin=1)\n    gain = np.array(gain, dtype=float, copy=False, ndmin=1)\n    bias = np.array(bias, dtype=float, copy=False, ndmin=1)\n    if x.ndim == 1:\n        x = x[:, np.newaxis] * np.ones(gain.shape[-1])\n    return x, gain, bias\n\n\ndef loihi_rates(neuron_type, x, gain, bias, dt):\n    x, gain, bias = _broadcast_rates_inputs(x, gain, bias)\n    for cls in type(neuron_type).__mro__:\n        if cls in loihi_rate_functions:\n            return loihi_rate_functions[cls](neuron_type, x, gain, bias, dt)\n    return neuron_type.rates(x, gain, bias)\n\n\ndef nengo_rates(neuron_type, x, gain, bias):\n    \"\"\"Call NeuronType.rates with Nengo 3.0 broadcasting rules\"\"\"\n    x, gain, bias = _broadcast_rates_inputs(x, gain, bias)\n    return neuron_type.rates(x, gain, bias)\n\n\nloihi_rate_functions = {\n    LIF: loihi_lif_rates,\n    SpikingRectifiedLinear: loihi_spikingrectifiedlinear_rates,\n    RegularSpiking: loihi_regularspiking_rates,\n}\n\n\nclass LoihiLIF(LIF):\n    \"\"\"Simulate LIF neurons as done by Loihi.\n\n    On Loihi, the inter-spike interval has to be an integer. This causes\n    aliasing the firing rates where a wide variety of inputs can produce the\n    same output firing rate. This class reproduces this effect, as well as\n    the discretization of some of the neuron parameters. It can be used in\n    e.g. ``nengo`` or ``nengo_dl`` to reproduce these unique Loihi effects.\n\n    Parameters\n    ----------\n    nengo_dl_noise : `nengo_extras.loihi_training.NeuronOutputNoise`\n        Noise added to the rate-neuron output when training with this neuron\n        type in ``nengo_dl``.\n    \"\"\"\n\n    state = {\n        \"voltage\": Choice([0]),\n        \"refractory_time\": Choice([0]),\n    }\n\n    def __init__(\n        self,\n        tau_rc=0.02,\n        tau_ref=0.002,\n        min_voltage=0,\n        amplitude=1,\n        nengo_dl_noise=None,\n        **kwargs,\n    ):\n        super().__init__(\n            tau_rc=tau_rc,\n            tau_ref=tau_ref,\n            min_voltage=min_voltage,\n            amplitude=amplitude,\n            **kwargs,\n        )\n        self.nengo_dl_noise = nengo_dl_noise\n        install_dl_builders()\n\n    @property\n    def _argreprs(self):\n        args = super()._argreprs\n        if self.nengo_dl_noise is not None:\n            args.append(\"nengo_dl_noise=%s\" % self.nengo_dl_noise)\n        return args\n\n    def rates(self, x, gain, bias, dt=0.001):\n        return loihi_lif_rates(self, x, gain, bias, dt)\n\n    def step(self, dt, J, output, voltage, refractory_time):\n        tau_ref = discretize_tau_ref(self.tau_ref, dt)\n        tau_rc = discretize_tau_rc(self.tau_rc, dt)\n\n        refractory_time -= dt\n        delta_t = (dt - refractory_time).clip(0, dt)\n        voltage -= (J - voltage) * np.expm1(-delta_t / tau_rc)\n\n        spikes_mask = voltage > 1\n        output[:] = spikes_mask * (self.amplitude / dt)\n\n        voltage[voltage < self.min_voltage] = self.min_voltage\n        voltage[spikes_mask] = 0\n        refractory_time[spikes_mask] = tau_ref + dt\n\n\nclass LoihiSpikingRectifiedLinear(SpikingRectifiedLinear):\n    \"\"\"Simulate spiking rectified linear neurons as done by Loihi.\n\n    On Loihi, the inter-spike interval has to be an integer. This causes\n    aliasing in the firing rates such that a wide variety of inputs produce the\n    same output firing rate. This class reproduces this effect. It can be used\n    in e.g. ``nengo`` or ``nengo_dl`` to reproduce these unique Loihi effects.\n    \"\"\"\n\n    state = {\n        \"voltage\": Choice([0]),\n    }\n\n    def __init__(self, amplitude=1, **kwargs):\n        super().__init__(amplitude=amplitude, **kwargs)\n        install_dl_builders()\n\n    def rates(self, x, gain, bias, dt=0.001):\n        return loihi_spikingrectifiedlinear_rates(self, x, gain, bias, dt)\n\n    def step(self, dt, J, output, voltage):\n        voltage += J * dt\n\n        spikes_mask = voltage > 1\n        output[:] = spikes_mask * (self.amplitude / dt)\n\n        voltage[voltage < 0] = 0\n        voltage[spikes_mask] = 0\n", "meta": {"hexsha": "a29178c4d25d70ff1feea120b4daa11e4c700435", "size": 7571, "ext": "py", "lang": "Python", "max_stars_repo_path": "nengo_loihi/neurons.py", "max_stars_repo_name": "Michaeljurado24/nengo-loihi", "max_stars_repo_head_hexsha": "47a18efcda3324f74493d014b431cfd0e5b9fbe2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nengo_loihi/neurons.py", "max_issues_repo_name": "Michaeljurado24/nengo-loihi", "max_issues_repo_head_hexsha": "47a18efcda3324f74493d014b431cfd0e5b9fbe2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nengo_loihi/neurons.py", "max_forks_repo_name": "Michaeljurado24/nengo-loihi", "max_forks_repo_head_hexsha": "47a18efcda3324f74493d014b431cfd0e5b9fbe2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.284, "max_line_length": 87, "alphanum_fraction": 0.6499801876, "include": true, "reason": "import numpy", "num_tokens": 2041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.30404168757891037, "lm_q1q2_score": 0.16032620565656755}}
{"text": "#! /usr/bin/python\n\n\"\"\" Walking gait task.\n\"\"\"\n\n### IMPORTS ###\nimport random\n\n# Libraries\nimport pymunk\nimport numpy as np\n\n# Local\nfrom ..networks.rnn import NeuralNetwork\n\n# Shortcuts\npi = np.pi\n\n### FUNCTIONS ###\n\ndef angle_fix(theta):\n    \"\"\" Fixes an angle to a value between -pi and pi.\n        \n        >>> angle_fix(-2*pi)\n        0.0\n    \"\"\"\n    return ((theta + pi) % (2*pi)) - pi\n    \n### CLASSES ###\n\nclass Joint(object):\n    \"\"\" Joint object, contains pivot, motor and limit\"\"\"\n    \n    def __init__(self, a, b, position, range=(-pi, pi), max_rate=2.0):\n        self.pivot = pymunk.PivotJoint(a, b, position)\n        self.motor = pymunk.SimpleMotor(a, b, 0)\n        self.motor.max_force = 1e7\n        self.limit = pymunk.RotaryLimitJoint(a, b, range[0], range[1])\n        self.limit.max_force = 1e1\n        self.limit.max_bias = 0.5\n        self.max_rate = max_rate\n        \n    def angle(self):\n        return angle_fix(self.pivot.a.angle - self.pivot.b.angle)\n        \n    def set_target(self, target):\n        \"\"\" Target is between 0 and 1, representing min and max angle. \"\"\"\n        cur = self.angle()\n        tgt = angle_fix(target * (self.limit.max - self.limit.min) + self.limit.min)\n        if tgt > cur + 0.1:\n            self.motor.rate = self.max_rate\n        elif tgt < cur - 0.1:\n            self.motor.rate = -self.max_rate\n        else: \n            self.motor.rate = 0\n    \nclass Leg(object):\n    \"\"\" Leg object, contains joints and shapes \"\"\"\n    \n    def __init__(self, parent, position, walking_task):\n        self.walking_task = walking_task\n        (w, l) = walking_task.leg_length / 5.0, walking_task.leg_length\n        mass = w * l * 0.2\n        # Upper leg\n        upperleg = pymunk.Body(mass, pymunk.moment_for_box(mass, w, l))\n        upperleg.position = pymunk.Vec2d(parent.position) + pymunk.Vec2d(position) + pymunk.Vec2d(0, l/2.0 - w/2.0)\n        shape = pymunk.Poly.create_box(upperleg, (w,l))\n        shape.group = 1\n        shape.friction = 2.0\n        # Joints\n        pos = pymunk.Vec2d(parent.position) + pymunk.Vec2d(position)\n        hip = Joint(parent, upperleg, pos, (-0.1*pi, 0.9*pi), self.walking_task.max_rate)\n        walking_task.space.add(hip.pivot, hip.motor, hip.limit, upperleg, shape)\n\n        # Lower leg\n        lowerleg = pymunk.Body(mass, pymunk.moment_for_box(mass, w, l * 1.2))\n        lowerleg.position = pymunk.Vec2d(upperleg.position) + pymunk.Vec2d(0, l - w/2.0)\n        shape = pymunk.Poly.create_box(lowerleg, (w, l * 1.2))\n        shape.group = 1\n        shape.friction = 2.0\n        # Joints\n        pos =  pymunk.Vec2d(upperleg.position) + pymunk.Vec2d(0, l/2.0 - w/2.0)\n        knee = Joint(upperleg, lowerleg, pos, (-0.9*pi, 0.1*pi), self.walking_task.max_rate)\n        walking_task.space.add(knee.pivot, knee.motor, knee.limit, lowerleg, shape)\n        \n        self.upperleg = upperleg\n        self.lowerleg = lowerleg\n        self.hip = hip\n        self.knee = knee\n            \n\nclass WalkingTask(object):\n    \"\"\" Walking gait task.\n    \"\"\"\n    \n    def __init__(self, max_steps=1000, \n                       track_length=1000, \n                       max_rate=2.0, \n                       torso_height=40, \n                       torso_density=0.2,\n                       leg_spacing=30,\n                       leg_length=30,\n                       num_legs=4):\n        # Settings\n        self.max_steps = max_steps\n        self.track_length = track_length\n        self.max_rate = max_rate\n        self.torso_height = torso_height\n        self.torso_density = torso_density\n        self.leg_spacing = leg_spacing\n        self.leg_length = leg_length\n        self.num_legs = num_legs\n        \n    def evaluate(self, network, draw=False):\n        \"\"\" Evaluate the efficiency of the given network. Returns the\n            distance that the walker ran in the given time (max_steps).\n        \"\"\"\n        if not isinstance(network, NeuralNetwork):\n            network = NeuralNetwork(network)\n        \n        if draw:\n            import pygame\n            pygame.init()\n            screen = pygame.display.set_mode((self.track_length, 200))\n            pygame.display.set_caption(\"Simulation\")\n            clock = pygame.time.Clock()\n            running = True\n            font = pygame.font.Font(pygame.font.get_default_font(), 8)\n        \n        # Initialize pymunk\n        self.space = space = pymunk.Space()\n        space.gravity = (0.0, 900.0)\n        space.damping = 0.7\n        self.touching_floor = False\n        # Create objects\n        # Floor\n\n        floor = pymunk.Body()\n        floor.position = pymunk.Vec2d(self.track_length/2.0 , 210)\n        sfloor = pymunk.Poly.create_box(floor, (self.track_length, 40))\n        sfloor.friction = 1.0\n        sfloor.collision_type = 1\n        space.add_static(sfloor)\n\n        # Torso\n        torsolength = 20 + (self.num_legs // 2 - 1) * self.leg_spacing\n        mass = torsolength * self.torso_height * self.torso_density\n        torso = pymunk.Body(mass, pymunk.moment_for_box(mass, torsolength, self.torso_height))\n        torso.position = pymunk.Vec2d(200, 200 - self.leg_length * 2 - self.torso_height)\n        storso = pymunk.Poly.create_box(torso, (torsolength, self.torso_height))\n        storso.group = 1\n        storso.collision_type = 1\n        storso.friction = 2.0\n        # space.add_static(storso)\n        space.add(torso, storso)\n\n        # Legs\n        legs = []\n        for i in range(self.num_legs // 2):\n            x = 10 - torsolength / 2.0 + i * self.leg_spacing\n            y = self.torso_height / 2.0 - 10\n            legs.append( Leg(torso, (x,y), self) )\n            legs.append( Leg(torso, (x,y), self) )\n        \n        # Collision callback\n        def oncollide(space, arb):\n            self.touching_floor = True\n        space.add_collision_handler(1, 1, post_solve=oncollide)\n        \n        for step in xrange(self.max_steps):\n            \n            # Query network\n            input_width = max(len(legs), 4)\n            net_input = np.zeros((3, input_width))\n            torso_y = torso.position.y\n            torso_a = torso.angle\n            sine = np.sin(step / 10.0)\n            hip_angles = [leg.hip.angle() for leg in legs]\n            knee_angles = [leg.knee.angle() for leg in legs]\n            other = [torso_y, torso_a, sine, 1.0]\n            # Build a 2d input grid, \n            # as in Clune 2009 Evolving Quadruped Gaits, p4\n            net_input[0, :len(legs)] = hip_angles\n            net_input[1, :len(legs)] = knee_angles\n            net_input[2, :4] = other\n            act = network.feed(net_input, add_bias=False)\n\n            output = np.clip(act[-self.num_legs*2:] * self.max_rate, -1.0, 1.0) / 2.0 + 0.5\n\n            for i, leg in enumerate(legs):\n                leg.hip.set_target( output[i * 2] )\n                leg.knee.set_target( output[i * 2 + 1] )\n            \n            # Advance simulation\n            space.step(1/50.0)\n            # Check for success/failure\n            if torso.position.x < 0:\n                break\n            if torso.position.x > self.track_length - 50:\n                break\n            if self.touching_floor:\n                break\n\n            # Draw\n            if draw:\n                print act\n                # Clear\n                screen.fill((255, 255, 255))\n                # Do all drawing\n                txt = font.render('%d' % step, False, (0,0,0) )\n                screen.blit(txt, (0,0))\n                # Draw objects\n                for o in space.shapes + space.static_shapes:\n                    if isinstance(o, pymunk.Circle):\n                        pygame.draw.circle(screen, (0,0,0), (int(o.body.position.x), int(o.body.position.y)), int(o.radius))\n                    else:\n                        pygame.draw.lines(screen, (0,0,0), True, [(int(p.x), int(p.y)) for p in o.get_points()])\n                # Flip buffers\n                pygame.display.flip()\n                clock.tick(50)\n                \n        if draw:\n            pygame.quit()\n        \n        distance = torso.position.x\n        # print \"Travelled %.2f in %d steps.\" % (distance, step)\n        return {'fitness':distance}\n        \n    def solve(self, network):\n        return False\n        \n    def visualize(self, network, filename=None):\n        \"\"\" Visualize a solution strategy by the given individual. \"\"\"\n        self.evaluate(network, draw=True)\n        \n        \n    ", "meta": {"hexsha": "d315e39cdf13ae0eb0e9c2260753b07347422832", "size": 8412, "ext": "py", "lang": "Python", "max_stars_repo_path": "peas/tasks/walking.py", "max_stars_repo_name": "such-a-git/SpiNNaker_peas", "max_stars_repo_head_hexsha": "4bc0df3b503c8357ddaa5af10db5ac0a2f9a6aab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 149, "max_stars_repo_stars_event_min_datetime": "2015-03-14T23:40:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T13:24:39.000Z", "max_issues_repo_path": "peas/tasks/walking.py", "max_issues_repo_name": "such-a-git/SpiNNaker_peas", "max_issues_repo_head_hexsha": "4bc0df3b503c8357ddaa5af10db5ac0a2f9a6aab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2015-09-21T18:45:09.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-26T21:19:16.000Z", "max_forks_repo_path": "peas/tasks/walking.py", "max_forks_repo_name": "such-a-git/SpiNNaker_peas", "max_forks_repo_head_hexsha": "4bc0df3b503c8357ddaa5af10db5ac0a2f9a6aab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 52, "max_forks_repo_forks_event_min_datetime": "2015-06-16T18:48:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-20T09:47:04.000Z", "avg_line_length": 35.4936708861, "max_line_length": 124, "alphanum_fraction": 0.5468378507, "include": true, "reason": "import numpy", "num_tokens": 2197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.30404168757891037, "lm_q1q2_score": 0.16032620565656755}}
{"text": "from typing import Tuple, List, Dict, Union\nfrom threading import Thread\nfrom multiprocessing import cpu_count\n\nfrom numba import njit\nfrom numpy import int16 as nshort, inf, ndarray, float32 as nfloat\nimport numpy as np\nfrom pandas import DataFrame, Index, MultiIndex\n\n\n_NULL_INDEX = -1\n_NEG_INF = -inf\n\n\ndef _get_breaks(n_items: int, n_workers: int) -> List[Tuple[int, int]]:\n    \"\"\"Gets starts and stops for breaks similar to numpy.array_slice()\"\"\"\n    div, remainder = divmod(n_items, n_workers)\n    slices = []\n    bottom = 0\n    for i in range(n_workers):\n        top = bottom + div\n        top += int(i < remainder)\n        slices.append((bottom, top))\n        bottom = top\n    return slices\n\n\n@njit\ndef _update_heap(utilities: ndarray, zones: ndarray, new_u: float, new_zone: int):\n    \"\"\"Inserts a value into a sorted array, maintaining sort order, and the number of items in that array. The array\n    is sorted lowest-to-highest\"\"\"\n    i = 0\n    top = len(utilities)\n    while i < top:\n        current_u = utilities[i]\n        if new_u < current_u:\n            break\n        i += 1\n    if i <= 0:\n        return\n    for j in range(i - 1):\n        utilities[j] = utilities[j + 1]\n        zones[j] = zones[j + 1]\n    utilities[i - 1] = new_u\n    zones[i - 1] = new_zone\n\n\n@njit(nogil=True)\ndef _nbf_twopart_worker(access_utils: ndarray, egress_utils: ndarray, result_utils: ndarray, result_stations: ndarray,\n                        start: int, stop: int, k: int):\n    \"\"\"Performance-tuned NBF to operate on its own thread\"\"\"\n    n_origins, n_intermediate = access_utils.shape\n    n_destinations = egress_utils.shape[1]\n\n    # Allocate the sorted heap of utilities (and associated indices) once per thread\n    util_heap = np.full(shape=k, fill_value=-inf)\n    zones_heap = np.full(shape=k, fill_value=_NULL_INDEX)\n\n    for offset in range(start, stop):\n        origin_zone, destination_zone = divmod(offset, n_destinations)\n\n        # Reset the heap for this OD\n        util_heap[:] = _NEG_INF\n        zones_heap[:] = _NULL_INDEX\n\n        for interim_zone in range(n_intermediate):\n\n            if interim_zone >= n_intermediate:\n                print(\"ERR\", offset, origin_zone, destination_zone, interim_zone)\n                raise AssertionError()\n\n            interim_util = access_utils[origin_zone, interim_zone] + egress_utils[interim_zone, destination_zone]\n\n            # In general, for problems where (n_origins * n_destinations) >> k, most values will not be in the top k.\n            # So quickly check against the lowest utility in the heap to avoid calling the updater func\n            if interim_util < util_heap[0] or interim_util == _NEG_INF:\n                continue\n            _update_heap(util_heap, zones_heap, interim_util, interim_zone)\n\n        result_utils[origin_zone, destination_zone, :] = util_heap\n        result_stations[origin_zone, destination_zone, :] = zones_heap\n\n\ndef _validate_access_egress_tables(access_table: DataFrame, egress_table: DataFrame) -> Tuple[Index, Index, Index]:\n\n    assert access_table.index.nlevels == 2, \"Access table index must have two levels\"\n    assert egress_table.index.nlevels == 2, \"Egress table index must have two levels\"\n\n    # Take the unique index of each level, as Pandas can return more items than is present, if the frame is a slice\n    origin_zones: Index = access_table.index.unique(level=0)\n    intermediate_zones: Index = access_table.index.unique(level=1)\n    destination_zones: Index = egress_table.index.unique(level=1)\n\n    # Check that the access and egress tables have compatible indices\n    assert intermediate_zones.equals(egress_table.index.unique(level=0)), \\\n        \"Access index level 2 and egress index level 1 must be the same\"\n\n    return origin_zones, intermediate_zones, destination_zones\n\n\ndef best_intermediate_zones(access_table: DataFrame, egress_table: DataFrame, cost_column: str, k: int = 1,\n                            n_threads: int = None, squeeze=True, other_columns=True,\n                            intermediate_name: str = \"intermediate_zone\", maximize=True,\n                            availability_column: str = \"available\", null_index=0\n                            ) -> Union[DataFrame, Dict[int, DataFrame]]:\n    \"\"\"Numba-accelerated.\n\n    Triple-index operation for two matrices, finding the most- or least-cost intermediate zones. Takes an access matrix\n    of the shape (O, I) and an egress matrix of the shape (I, D) to produce a combined matrix of the shape (O, D), with\n    the best intermediate I. Also works to construct multiple (O, D) matrices - for the top _k_ intermediate zones in\n    _I_.\n\n    There is no restriction on the label dtypes, as long as the access and egress tables share the same _I_ index.\n\n    Both the input matrices must be provided in \"tall\" format - as Pandas Series with a 2-level MultiIndex.\n    Essentially, the access and egress tables are DataFrames with multiple matrices defined within. The output table(s)\n    are also returned in a tall format.\n\n    When constructing the result tables, columns in the access and egress tables are \"carried forward\" such that the\n    results columns will be the union of columns in the input tables. Columns in one table only will be carried forward\n    unmodified and retain their data type. Columns in both tables will be added together, and thus MUST be numeric.\n\n    In the specified cost column, a value of `-inf` (or `inf` when minimizing) is respected as the sentinel value for\n    unavailable. (O, I) or (I, D) interchanges with this sentinel value will not be considered.\n\n    Args:\n        access_table: DataFrame with 2-level MultiIndex of the shape ((O, I), A). Must include the specified cost column\n        egress_table: DataFrame with 2-level MultiIndex of the shape ((I, D), E). Must include the specified cost column\n        cost_column: Name of the column in the access and egress table to use as the cost to minimize/maximize. Values\n            of `+/- inf` are respected to indicate unavailable choices\n        k: The number of ranks to return (e.g., find the _k_ best intermediate zones). If k <= 0, it will be corrected\n            to 1.\n        n_threads: Number of threads to use. Defaults to cpu_count()\n        squeeze: If k == 1 and squeeze=True, a single DataFrame is returned. Otherwise, a Dictionary of DataFrames will\n            be returned.\n        other_columns: If True, the result DataFrame will include all columns in the access and egress tables. The\n            result table will be of the shape ((O, D), A | E + 3)\n        intermediate_name: Name of the column in the result table containing the selected intermediate zone.\n        maximize: If True, this function maximize the result. If False, it minimizes it.\n        availability_column: Name of the column in the result table containing a flag whether ANY intermediate zone\n            was found to be available.\n        null_index: Fill value used if NO intermediate zone is available.\n\n    Returns:\n        DataFrame: If k == 1 and squeeze=True. A DataFrame of the shape ((O, D), A | E + 3), containing the intermediate\n            zone selected, the associated max/min cost, and a flag indicating its availability. Additional columns from\n            the access and egress tables, indexed for the appropriately chosen intermediate zone, will also be included\n            if other_columns=True.\n        Dict[int, DataFrame]: If k > 1. The keys represent the ranks, so result[1] is the best intermediate zone,\n            result[2] is the second-best, etc. The value DataFrames are in the same format as if k == 1, just with\n            different intermediate zones chosen.\n    \"\"\"\n\n    # Check inputs\n    k = max(1, k)\n    if n_threads is None:\n        n_threads = cpu_count()\n    origins, intermediates, destinations = _validate_access_egress_tables(access_table, egress_table)\n    n_origins, n_intermediate, n_destinations = len(origins), len(intermediates), len(destinations)\n\n    # Compute best path(s)\n    access_cost = access_table[cost_column].values.reshape([n_origins, n_intermediate]).astype(nfloat)\n    egress_cost = egress_table[cost_column].values.reshape([n_intermediate, n_destinations]).astype(nfloat)\n\n    if not maximize:  # Invert the cost to use code set to maximize\n        access_cost *= -1\n        egress_cost *= -1\n\n    result_cost = np.zeros(shape=(n_origins, n_destinations, k), dtype=nfloat)\n    result_indices = np.zeros(dtype=nshort, shape=(n_origins, n_destinations, k))\n\n    # Setup the workers (1 per thread) to select best paths for a subset of ODs\n    breaks = _get_breaks(n_origins * n_destinations, n_threads)\n    threads = [\n        Thread(target=_nbf_twopart_worker, args=[\n            access_cost, egress_cost, result_cost, result_indices,\n            start, stop, k\n        ])\n        for start, stop in breaks\n    ]\n    for t in threads:\n        t.start()\n    for t in threads:\n        t.join()\n\n    # Construct composite result tables\n    if other_columns:\n        remaining_columns = set(access_table.columns | egress_table.columns) - {cost_column, intermediate_name,\n                                                                                availability_column}\n    else:\n        remaining_columns = set()\n\n    row_index = MultiIndex.from_product([origins, destinations])        # Labels for the rows\n    access_indexer = np.repeat(np.arange(n_origins), n_destinations)    # Indexer for the access table\n    egress_indexer = np.tile(np.arange(n_destinations), n_origins)      # Indexer for the egress table\n    tables = {}                                                         # Results\n\n    for i in range(k):\n        table = DataFrame(index=row_index)\n\n        offsets_i = result_indices[:, :, i]  # 2D indexer for this (i ∈ k) path\n        flat_offsets_i = offsets_i.flatten()  # Convert to 1D indexer\n        availability_i = flat_offsets_i != _NULL_INDEX\n\n        intermediate_result_i = intermediates.take(flat_offsets_i)\n        intermediate_result_i[~availability_i] = null_index\n        table[intermediate_name] = intermediate_result_i\n\n        table[availability_column] = availability_i\n        table[cost_column] = result_cost[offsets_i]\n\n        # If there are any columns left, add them to the composite table\n        for column in remaining_columns:\n            in_access = column in access_table\n            in_egress = column in egress_table\n\n            if in_access:\n                access_matrix = access_table[column].values.reshape([n_origins, n_intermediate])\n                access_component = access_matrix[access_indexer, flat_offsets_i]\n            if in_egress:\n                egress_matrix = egress_table[column].values.reshape([n_intermediate, n_destinations])\n                egress_component = egress_matrix[flat_offsets_i, egress_indexer]\n\n            if in_access and in_egress:\n                composite_data = access_component + egress_component\n            elif in_access:\n                composite_data = access_component\n            elif in_egress:\n                composite_data = egress_component\n            else:\n                raise RuntimeError(\"This shouldn't happen\")\n\n            table[column] = composite_data\n\n        tables[k - i] = table\n\n    if k == 1 and squeeze:\n        return tables[1]\n    return tables\n", "meta": {"hexsha": "1109a50e2038252a495e5bea42c8a09f8523a4c2", "size": 11313, "ext": "py", "lang": "Python", "max_stars_repo_path": "balsa/routines/best_intermediates.py", "max_stars_repo_name": "wsp-sag/balsa", "max_stars_repo_head_hexsha": "d522fba57e0bf70ffb757d061165ce9f1945acc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-10T15:40:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T22:19:22.000Z", "max_issues_repo_path": "balsa/routines/best_intermediates.py", "max_issues_repo_name": "wsp-sag/balsa", "max_issues_repo_head_hexsha": "d522fba57e0bf70ffb757d061165ce9f1945acc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-05-21T13:57:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T22:19:14.000Z", "max_forks_repo_path": "balsa/routines/best_intermediates.py", "max_forks_repo_name": "wsp-sag/balsa", "max_forks_repo_head_hexsha": "d522fba57e0bf70ffb757d061165ce9f1945acc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-04-10T15:45:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-25T13:15:24.000Z", "avg_line_length": 47.1375, "max_line_length": 120, "alphanum_fraction": 0.6741801467, "include": true, "reason": "import numpy,from numpy,from numba", "num_tokens": 2573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.30404166235418484, "lm_q1q2_score": 0.16032619235515297}}
{"text": "#!/usr/bin/env python3\nimport numpy as np\n\n\ndef rank_properties(prop_name, obs):\n    \"\"\"Select ranking method based on property name.\n\n    Parameters\n    ----------\n    prop_name : str\n        The property to rank.\n    obs : dict\n        The observations including metadata\n\n\n    Returns\n    -------\n    list of bool\n        Entry \"preferred\" in propertyCollection, True if preferred, else False\n    \"\"\"\n    if prop_name in [\"taxonomy\", \"taxonomies\"]:\n        return select_taxonomy(obs)\n    elif prop_name in [\"mass\", \"masses\"]:\n        return select_numeric_property(obs, \"mass\")\n    elif prop_name in [\"albedo\", \"albedos\"]:\n        return select_numeric_property(obs, \"albedo\")\n    elif prop_name in [\"diameter\", \"diameters\"]:\n        return select_numeric_property(obs, \"diameter\")\n    else:\n        return [True for i in obs]\n\n\ndef select_taxonomy(taxonomies):\n    \"\"\"Select a single taxonomic classification from multiple choices.\n\n    Evaluates the wavelength ranges, methods, schemes, and recency of\n    classification.\n\n    Parameters\n    ----------\n    taxonomies: dict\n        Taxonomic classifications retrieved from SsODNet:datacloud.\n\n    Returns\n    -------\n    list of bool\n        True if preferred, else False\n    \"\"\"\n    POINTS = {\n        \"scheme\": {\"bus-demeo\": 3, \"bus\": 2, \"smass\": 2, \"tholen\": 1, \"sdss\": 1},\n        \"waverange\": {\"vis\": 1, \"nir\": 3, \"visnir\": 6, \"mix\": 4},\n        \"method\": {\"spec\": 7, \"phot\": 3, \"mix\": 4},\n    }\n\n    taxonomies = [dict(zip(taxonomies, t)) for t in zip(*taxonomies.values())]\n\n    # Compute points of each classification\n    points = []\n\n    for row in taxonomies:\n        points.append(\n            sum(\n                [\n                    POINTS[crit][row[crit].lower()]\n                    for crit in [\"scheme\", \"waverange\", \"method\"]\n                ]\n            )\n        )\n\n    # Convert points to boolean\n    preferred = [True if p == max(points) else False for p in points]\n    return preferred\n\n\ndef select_numeric_property(obs, prop_name):\n    \"\"\"Select preferred observations ranking methods.\n\n    Parameters\n    ----------\n    obs : dict\n        Property measurements and metadata retrieved from SsODNet:datacloud.\n    prop_name : str\n        Name of the asteroid property.\n\n    Returns\n    -------\n    list of bool\n        True if selected, else False.\n\n    Notes\n    -----\n    The method ranking depends on the observable.\n    \"\"\"\n    RANKING = PROPERTIES[prop_name][\"ranking\"]\n    methods = set(obs[\"method\"])\n\n    for method in RANKING:\n\n        if set(method) & methods:  # method used at least once\n\n            # Ensure that rows do not contain all 0 values, as can be the case\n            # for albedo in diamalbedo\n            if all(\n                [\n                    obs[prop_name][i] == 0\n                    for i, m in enumerate(obs[\"method\"])\n                    if m in method\n                ]\n            ):\n                continue\n\n            # All entries using this method are preferred\n            preferred = [True if m in method else False for m in obs[\"method\"]]\n            return preferred\n\n    # No property entry is preferred (likely all 0), return list of False\n    return [False for o in obs[\"number\"]]\n\n\n# In alphabetic order\nPROPERTIES = {\n    # TEMPLATE\n    # property_name: Rock instance attribute name\n    #   attribute: attribute key in datacloud\n    #   collection: Rock instance attribute name for collection of parameters\n    #               Use plural form\n    #   extra_columns: names of additional columns to output on CLI\n    #   ssodnet_path: json path to asteroid property\n    #                 (to be replaced by ssoCard\n    #   type: asteroid property type, float or str\n    \"albedo\": {\n        \"ranking\": [\n            [\"SPACE\"],\n            [\"ADAM\", \"KOALA\", \"SAGE\", \"Radar\"],\n            [\"LC+TPM\", \"TPM\", \"LC+AO\", \"LC+Occ\", \"TE-IM\", \"TE-Occ\"],\n            [\"AO\", \"Occ\", \"IM\"],\n            [\"NEATM\"],\n            [\"STM\"],\n        ],\n    },\n    \"diameter\": {\n        \"ranking\": [\n            [\"SPACE\"],\n            [\"ADAM\", \"KOALA\", \"SAGE\", \"Radar\"],\n            [\"LC+TPM\", \"TPM\", \"LC+AO\", \"LC+Occ\", \"TE-IM\", \"TE-Occ\"],\n            [\"AO\", \"Occ\", \"IM\"],\n            [\"NEATM\"],\n            [\"STM\"],\n        ],\n    },\n    \"mass\": {\n        \"ranking\": [\n            [\"SPACE\"],\n            [\"Bin-Genoid\"],\n            [\"Bin-IM\", \"Bin-Radar\", \"Bin-PheMu\"],\n            [\"EPHEM\", \"DEFLECT\"],\n        ],\n    },\n}\n\n\n# Classes to complexes mapping\nCLASS_TO_COMPLEX = {\n    \"A\": \"A\",\n    \"Ad\": \"U\",\n    \"AQ\": \"U\",\n    \"AS\": \"U\",\n    \"AU\": \"U\",\n    \"AV\": \"U\",\n    \"B\": \"B\",\n    \"BC\": \"C\",\n    \"BCF\": \"C\",\n    \"BCU\": \"U\",\n    \"BFC\": \"C\",\n    \"BFU\": \"U\",\n    \"BFX\": \"U\",\n    \"Bk\": \"U\",\n    \"BU\": \"B\",\n    \"C\": \"C\",\n    \"Caa\": \"C\",\n    \"Cb\": \"C\",\n    \"CB\": \"C\",\n    \"CBU\": \"C\",\n    \"CD\": \"U\",\n    \"CDX\": \"U\",\n    \"CF\": \"C\",\n    \"CFB\": \"C\",\n    \"CFU\": \"U\",\n    \"CFXU\": \"U\",\n    \"Cg\": \"C\",\n    \"CG\": \"C\",\n    \"CGSU\": \"U\",\n    \"CGTP\": \"U\",\n    \"CGU\": \"U\",\n    \"Cgx\": \"C\",\n    \"CL\": \"U\",\n    \"CO\": \"U\",\n    \"CP\": \"U\",\n    \"CPF\": \"U\",\n    \"CPU\": \"U\",\n    \"CQ\": \"U\",\n    \"CS\": \"U\",\n    \"CSGU\": \"U\",\n    \"CSU\": \"U\",\n    \"CTGU\": \"U\",\n    \"CU\": \"U\",\n    \"CX\": \"U\",\n    \"CXF\": \"U\",\n    \"Cgh\": \"Ch\",\n    \"Ch\": \"Ch\",\n    \"D\": \"D\",\n    \"DCX\": \"U\",\n    \"DL\": \"D\",\n    \"DP\": \"D\",\n    \"DU\": \"D\",\n    \"Ds\": \"D\",\n    \"DS\": \"D\",\n    \"DSU\": \"D\",\n    \"DT\": \"D\",\n    \"DTU\": \"D\",\n    \"DU\": \"D\",\n    \"DX\": \"D\",\n    \"DXCU\": \"D\",\n    \"E\": \"E\",\n    \"EM\": \"X\",\n    \"EU\": \"U\",\n    \"F\": \"C\",\n    \"FBCU\": \"U\",\n    \"FC\": \"C\",\n    \"FCB\": \"C\",\n    \"FCU\": \"U\",\n    \"FCX\": \"U\",\n    \"FP\": \"U\",\n    \"FU\": \"U\",\n    \"FX\": \"U\",\n    \"FXU\": \"U\",\n    \"G\": \"C\",\n    \"GC\": \"C\",\n    \"GS\": \"U\",\n    \"J\": \"V\",\n    \"K\": \"K\",\n    \"Kl\": \"U\",\n    \"L\": \"L\",\n    \"LA\": \"U\",\n    \"Ld\": \"L\",\n    \"LQ\": \"U\",\n    \"LS\": \"U\",\n    \"M\": \"M\",\n    \"MU\": \"U\",\n    \"O\": \"O\",\n    \"OV\": \"U\",\n    \"P\": \"P\",\n    \"PC\": \"U\",\n    \"PCD\": \"U\",\n    \"PD\": \"U\",\n    \"PDC\": \"U\",\n    \"PF\": \"U\",\n    \"PU\": \"U\",\n    \"Q\": \"Q\",\n    \"QO\": \"Q\",\n    \"QRS\": \"U\",\n    \"QSV\": \"U\",\n    \"QV\": \"U\",\n    \"Qw\": \"Q\",\n    \"R\": \"R\",\n    \"S\": \"S\",\n    \"SA\": \"S\",\n    \"Sa\": \"S\",\n    \"SC\": \"U\",\n    \"SCTU\": \"U\",\n    \"SD\": \"U\",\n    \"SDU\": \"U\",\n    \"SG\": \"U\",\n    \"Sk\": \"S\",\n    \"Sl\": \"S\",\n    \"SMU\": \"U\",\n    \"SO\": \"S\",\n    \"Sq\": \"S\",\n    \"SQ\": \"S\",\n    \"Sqw\": \"S\",\n    \"Sr\": \"S\",\n    \"SR\": \"S\",\n    \"Srw\": \"S\",\n    \"ST\": \"U\",\n    \"STD\": \"U\",\n    \"STGD\": \"U\",\n    \"STU\": \"U\",\n    \"SU\": \"U\",\n    \"SV\": \"S\",\n    \"Sv\": \"S\",\n    \"Svw\": \"S\",\n    \"Sw\": \"S\",\n    \"SX\": \"U\",\n    \"T\": \"T\",\n    \"TCG\": \"U\",\n    \"TD\": \"U\",\n    \"TDG\": \"U\",\n    \"TDS\": \"U\",\n    \"TS\": \"U\",\n    \"TSD\": \"U\",\n    \"TX\": \"U\",\n    \"V\": \"V\",\n    \"Vw\": \"V\",\n    \"X\": \"X\",\n    \"XB\": \"U\",\n    \"Xc\": \"X\",\n    \"XC\": \"U\",\n    \"XCU\": \"U\",\n    \"XD\": \"U\",\n    \"XDC\": \"U\",\n    \"Xe\": \"X\",\n    \"XF\": \"U\",\n    \"XFC\": \"U\",\n    \"XFCU\": \"U\",\n    \"XFU\": \"U\",\n    \"Xk\": \"X\",\n    \"XL\": \"U\",\n    \"Xn\": \"X\",\n    \"XS\": \"U\",\n    \"XSC\": \"U\",\n    \"XSCU\": \"U\",\n    \"XT\": \"U\",\n    \"Xt\": \"X\",\n    \"XU\": \"U\",\n    \"Z\": \"U\",\n    np.nan: None,\n    \"\": None,\n    None: None,\n    float(\"nan\"): None,\n}\n", "meta": {"hexsha": "aac7ceecc512fa485c202214b809dc1dd73b69c8", "size": 7044, "ext": "py", "lang": "Python", "max_stars_repo_path": "rocks/definitions.py", "max_stars_repo_name": "maxmahlke/rocks", "max_stars_repo_head_hexsha": "f75980e7d6b9c63037de9d1a16d5daea80f49a49", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-05T13:09:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T22:17:47.000Z", "max_issues_repo_path": "rocks/definitions.py", "max_issues_repo_name": "maxmahlke/rocks", "max_issues_repo_head_hexsha": "f75980e7d6b9c63037de9d1a16d5daea80f49a49", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-11-12T14:07:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T15:32:33.000Z", "max_forks_repo_path": "rocks/definitions.py", "max_forks_repo_name": "maxmahlke/rocks", "max_forks_repo_head_hexsha": "f75980e7d6b9c63037de9d1a16d5daea80f49a49", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2809667674, "max_line_length": 81, "alphanum_fraction": 0.4244747303, "include": true, "reason": "import numpy", "num_tokens": 2328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.290980853917813, "lm_q1q2_score": 0.16021620139688164}}
{"text": "import os\nimport sys\nimport collections.abc\nimport multiprocessing\nimport queue\nimport signal\n\nimport numpy as np\nimport scipy.interpolate\n\nfrom cosmosis.datablock import option_section, names\n\nfrom cosmosis.datablock.cosmosis_py import errors\n\nimport bias_module\n\ndef setup(options):\n    config = {}\n\n    here = os.path.dirname(__file__)\n    window_file = options[option_section, \"window_file\"]\n    bands_file = options[option_section, \"bands_file\"]\n    config[\"window\"] = np.loadtxt(window_file)\n    config[\"bands\"] = np.loadtxt(bands_file)\n\n    config[\"verbose\"] = options.get_bool(option_section, \"verbose\", False)\n    config[\"timeout\"] = options.get_double(option_section, \"timeout\", default=-1.0)\n    if config[\"timeout\"] <= 0:\n        config[\"timeout\"] = None\n\n    try:\n        bands_range = options[option_section, \"bands_range\"]\n    except errors.BlockNameNotFound:\n        bands_range = [20, 160]\n    if len(bands_range) != 2 or not all(np.issubdtype(type(b), np.integer) for b in bands_range):\n        raise ValueError(f\"bands_range needs to be two integers, got {bands_range}, {[type(b) for b in bands_range]}\")\n\n    try:\n        points_range = options[option_section, \"points_range\"]\n    except errors.BlockNameNotFound:\n        points_range = [4, 32]\n    if len(points_range) != 2 or not all(np.issubdtype(type(b), np.integer) for b in points_range):\n        raise ValueError(f\"points_range needs to be two integers, got {points_range}\")\n    \n    n_points, n_bands = config[\"window\"].shape\n    \n    cut_points_idx = list(range(points_range[0])) + list(range(points_range[1], n_points))\n    cut_bands_idx = list(range(bands_range[0])) + list(range(bands_range[1], n_bands))\n\n    if config[\"verbose\"]:\n        print(\"Cutting bands\", cut_bands_idx)\n        print(\"Cutting points\", cut_points_idx)\n    if len(cut_points_idx) > 0:\n        config[\"window\"] = np.delete(config[\"window\"], cut_points_idx, axis=0)\n    if len(cut_bands_idx) > 0:\n        config[\"bands\"] = np.delete(config[\"bands\"], cut_bands_idx)\n        config[\"window\"] = np.delete(config[\"window\"], cut_bands_idx, axis=1)\n\n    config[\"output_section_wedges\"] = options.get_string(option_section, \"output_section_wedges\", \"xi_wedges\")\n    config[\"output_section_pk_mm\"] = options.get_string(option_section, \"output_section_pk_mm\", \"matter_matter_power_spectrum_pt\")\n    config[\"output_section_pk_gm\"] = options.get_string(option_section, \"output_section_pk_gm\", \"galaxy_matter_power_spectrum_pt\")\n    config[\"output_section_pk_gg\"] = options.get_string(option_section, \"output_section_pk_gg\", \"galaxy_galaxy_power_spectrum_pt\")\n\n    config[\"compute_lss_parameters\"] = options.get_bool(option_section, \"compute_lss_parameters\", True)\n\n    config[\"twopt_type\"] = 4\n    config[\"num_ell\"] = 3\n    config[\"num_points_use\"] = config[\"window\"].shape[0]\n    config[\"num_bands_use\"] = config[\"window\"].shape[1]\n    config[\"z_index\"] = 4\n    config[\"zm\"] = options[option_section, \"z_eff\"]\n    if not isinstance(config[\"zm\"], collections.abc.Iterable):\n        config[\"zm\"] = [config[\"zm\"]]\n    config[\"om_fid\"] = 0.31\n    config[\"h0_fid\"] = 0.7\n\n    config[\"use_growth\"] = options.get_bool(option_section, \"use_growth\", False)\n    config[\"local_lag_g2\"] = options.get_bool(option_section, \"local_lag_g2\", True)\n    config[\"local_lag_g3\"] = options.get_bool(option_section, \"local_lag_g3\", False)\n\n    config[\"no_interpolation\"] = options.get_bool(option_section, \"no_interpolation\", False)\n\n    # config[\"derived_parameters\"] = np.loadtxt(os.path.join(here, \"../output/derived_params.txt\"))\n    # config[\"data_parameters\"] = np.loadtxt(os.path.join(here, \"../output/data_params.txt\"))\n\n    # config[\"z_pk\"] = np.loadtxt(os.path.join(here, \"../output/z_p_k.txt\"))\n    # config[\"log_k_pk\"] = np.loadtxt(os.path.join(here, \"../output/log_k_h.txt\"))\n    # config[\"log_pk\"] = np.loadtxt(os.path.join(here, \"../output/log_p_k.txt\"))\n\n    # if config[\"verbose\"]:\n    #     print(config)\n    return config\n\ndef run_wedges(q, config, \n               h, omdm, omb, omv, omk, omnuh2, nnu, w, wa, \n               z_Pk, log_k_h, log_Pk,\n               growth, sigma8,\n               params):\n\n    module = bias_module.BiasModule()\n    wedges_config = []\n\n    for z in config[\"zm\"]:\n        wedges_config.append(module.initialize_wedges(config[\"twopt_type\"], config[\"num_ell\"], \n                                                         config[\"num_points_use\"], config[\"num_bands_use\"], \n                                                         z, config[\"om_fid\"], config[\"h0_fid\"], \n                                                         config[\"window\"], verbose=config[\"verbose\"]))\n\n    # Setup cosmology\n    module.setup_cosmology(h, omdm, omb, omv, omk, omnuh2, nnu, w, wa, \n                                     config[\"use_growth\"], config[\"local_lag_g2\"], config[\"local_lag_g3\"],\n                                     z_Pk, log_k_h, log_Pk.T,\n                                     growth, sigma8, verbose=config[\"verbose\"])\n\n    results = []\n    #print(\"Running compute_wedges\", flush=True)\n    for i, zm in enumerate(config[\"zm\"]):\n        b = i + 1\n        b1, b2, gamma2, gamma3, a_vir, gamma, z_index, H_z, DA_z = params[i]\n\n        vtheo, vtheo_convolved, Pk_mm, Pk_gm, Pk_gg = module.compute_wedges(\n                                                        wedges_config[i],\n                                                        b1, b2, gamma2, gamma3, a_vir, gamma,\n                                                        z_index+2,\n                                                        H_z, DA_z,\n                                                        config[\"bands\"],\n                                                        verbose=config[\"verbose\"])\n        results.append((vtheo, vtheo_convolved, Pk_mm, Pk_gm, Pk_gg))\n    \n    for c in wedges_config:\n        module.cleanup_wedges(c)\n    \n    module.cleanup_cosmology()\n\n    q.put(results)\n\n\ndef execute(block, config):\n    h = block[names.cosmological_parameters, \"h0\"]\n    omdm = block[names.cosmological_parameters, \"omega_c\"]\n    omb = block[names.cosmological_parameters, \"omega_b\"]\n    omv = block[names.cosmological_parameters, \"omega_lambda\"]\n    omk = block[names.cosmological_parameters, \"omega_k\"]\n    omnuh2 = block[names.cosmological_parameters, \"omnuh2\"]\n    nnu = block.get_double(names.cosmological_parameters, \"nnu\", default=3.046)\n    w = block[names.cosmological_parameters, \"w\"]\n    wa = block[names.cosmological_parameters, \"wa\"]\n\n    if config[\"use_growth\"]:\n        gamma = block[\"bias_parameters\", f\"gamma\"]\n    else:\n        gamma = 1.0\n        \n    log_Pk = np.log(block[names.matter_power_lin, \"p_k\"])\n    log_k_h = np.log(block[names.matter_power_lin, \"k_h\"])\n    z_Pk = block[names.matter_power_lin, \"z\"]\n\n    z_growth = block[names.growth_parameters, \"z\"]\n    if not np.allclose(z_Pk, z_growth):\n        raise ValueError(\"Redshifts of power spectrum and growth do not match.\")\n\n    sigma8 = block[names.growth_parameters, \"SIGMA_8\"]\n    if block.has_value(names.growth_parameters, \"fsigma_8\"):\n        growth = block[names.growth_parameters, \"fsigma_8\"]\n    else:\n        sigma2_vdelta_8 = block[names.growth_parameters, \"SIGMA2_VDELTA_8\"]\n        growth = sigma2_vdelta_8/sigma8\n\n    \n    Pk_mm_pt = np.zeros((len(config[\"zm\"]), len(log_k_h)))\n    Pk_gm_pt = np.zeros((len(config[\"zm\"]), len(log_k_h)))\n    Pk_gg_pt = np.zeros((len(config[\"zm\"]), len(log_k_h)))\n\n    params = []\n    for i, zm in enumerate(config[\"zm\"]):\n        b = i + 1\n\n        z = block[names.distances, \"z\"]\n        H_z = block[names.distances, \"h\"]*2.99792458e8/1e3\n        DA_z = block[names.distances, \"d_a\"]\n\n        if config[\"no_interpolation\"]:\n            # Original implementation taylored to the way the CosmoMC module reads\n            # these parameters. Sensitive to z resolution\n            z_index = np.argmin(np.abs(z-zm))\n\n            if z_index >= (200-13)//4:\n                # z_index too large to fit H_z and DA_z into derived_parameters array\n                # so we take a range around z[z_index]\n                s = slice(max(0, z_index-4), min(len(z), z_index+4))\n                z = z[s]\n                H_z = H_z[s]\n                DA_z = DA_z[s]\n                z_index = np.argmin(np.abs(z-zm))\n        else:\n            # More stable and sane.\n            H_z_intp = scipy.interpolate.InterpolatedUnivariateSpline(z, H_z, ext=2)\n            DA_z_intp = scipy.interpolate.InterpolatedUnivariateSpline(z, DA_z, ext=2)\n\n            H_z = np.atleast_1d(H_z_intp(zm))\n            DA_z = np.atleast_1d(DA_z_intp(zm))\n            z_index = 0\n\n        # Bias parameters\n        b1 = block[\"bias_parameters\", f\"b1_bin_{b}\"]\n        b2 = block[\"bias_parameters\", f\"b2_bin_{b}\"]\n        if not config[\"local_lag_g2\"]:\n            gamma2 = block[\"bias_parameters\", f\"gamma2_bin_{b}\"]\n        else:\n            gamma2 = 1.0\n        if not config[\"local_lag_g3\"]:\n            gamma3 = block[\"bias_parameters\", f\"gamma3_bin_{b}\"]\n        else:\n            gamma3 = 1.0\n        a_vir = block[\"bias_parameters\", f\"a_vir_bin_{b}\"]\n\n        params.append((b1, b2, gamma2, gamma3, a_vir, gamma, z_index, H_z, DA_z))\n        \n\n    # Run wedges\n    # Need fork. Using spawn launches the whole cosmosis process\n    mp_context = multiprocessing.get_context(\"fork\")\n\n    # Queue to get results back from the process\n    q = multiprocessing.Queue()\n\n    # Create the process\n    proc = mp_context.Process(target=run_wedges, \n                              args=(q, config, h, omdm, omb, omv, omk, omnuh2, nnu, w, wa, \n                                    z_Pk, log_k_h, log_Pk,\n                                    growth, sigma8,\n                                    params))\n    proc.start()\n    try:\n        # Wait for results to show up in the queue\n        result = q.get(block=True, timeout=config[\"timeout\"])\n    except queue.Empty:\n        print(f\"wedges module timed out after {config['timeout']} s. Attempting to tell process to stop.\", file=sys.stderr, flush=True)\n        # os.kill(proc.pid, signal.SIGTERM)\n        proc.join(0.5)\n        if proc.is_alive():\n            print(\"Wedges process is not cooperating. Terminating it.\", file=sys.stderr, flush=True)\n            proc.terminate()\n            proc.join(0.5)\n            if proc.exitcode is None:\n                print(\"So you have choosen death.\", file=sys.stderr, flush=True)\n                proc.kill()\n        return 1\n\n    proc.join(0.5)\n    if proc.is_alive():\n        print(\"Wedges process is not cooperating. Terminating it.\", file=sys.stderr, flush=True)\n        proc.terminate()\n        proc.join(0.5)\n        if proc.exitcode is None:\n            print(\"So you have choosen death.\", file=sys.stderr, flush=True)\n            proc.kill()\n\n    proc.close()\n\n    # Put the results into the datablock\n    for i, zm in enumerate(config[\"zm\"]):\n        b = i + 1\n\n        vtheo, vtheo_convolved, Pk_mm, Pk_gm, Pk_gg = result[i]\n\n        n = len(vtheo)//config[\"num_ell\"]\n        vtheo = np.array([vtheo[i*n:(i+1)*n] for i in range(config[\"num_ell\"])])\n        n = len(vtheo_convolved)//config[\"num_ell\"]\n        vtheo_convolved = np.array([vtheo_convolved[i*n:(i+1)*n] for i in range(config[\"num_ell\"])])\n\n        block[config[\"output_section_wedges\"], f\"vtheo_bin_{b}\"] = vtheo\n        block[config[\"output_section_wedges\"], f\"bin_{b}\"] = vtheo_convolved\n        Pk_mm_pt[i] = Pk_mm\n        Pk_gm_pt[i] = Pk_gm\n        Pk_gg_pt[i] = Pk_gg\n\n    block[config[\"output_section_wedges\"], \"n_wedge\"] = config[\"num_ell\"]\n    block[config[\"output_section_wedges\"], \"bands\"] = config[\"bands\"]\n    block[config[\"output_section_wedges\"], \"z\"] = config[\"zm\"]\n\n    block[config[\"output_section_pk_mm\"], \"z\"] = config[\"zm\"]\n    block[config[\"output_section_pk_gm\"], \"z\"] = config[\"zm\"]\n    block[config[\"output_section_pk_gg\"], \"z\"] = config[\"zm\"]\n\n    block[config[\"output_section_pk_mm\"], \"k_h\"] = np.exp(log_k_h)\n    block[config[\"output_section_pk_gm\"], \"k_h\"] = np.exp(log_k_h)\n    block[config[\"output_section_pk_gg\"], \"k_h\"] = np.exp(log_k_h)\n\n    block[config[\"output_section_pk_mm\"], \"p_k\"] = Pk_mm_pt\n    block[config[\"output_section_pk_gm\"], \"p_k\"] = Pk_gm_pt\n    block[config[\"output_section_pk_gg\"], \"p_k\"] = Pk_gg_pt\n\n    if config[\"compute_lss_parameters\"]:\n        z = block[names.growth_parameters, \"z\"]\n        fsigma_8 = scipy.interpolate.InterpolatedUnivariateSpline(z, block[names.growth_parameters, \"fsigma_8\"])\n        \n        z_background = block[names.distances, \"z\"]\n        F_AP = scipy.interpolate.InterpolatedUnivariateSpline(z_background, block[names.distances, \"F_AP\"])\n        rs_DV = scipy.interpolate.InterpolatedUnivariateSpline(z_background[1:], block[names.distances, \"rs_DV\"][1:])\n\n        for i, zm in enumerate(config[\"zm\"]):\n            b = i + 1\n\n            block[\"lss_parameters\", f\"rs_DV_bin_{b}\"] = float(rs_DV(zm))\n            block[\"lss_parameters\", f\"F_AP_bin_{b}\"] = float(F_AP(zm))\n            block[\"lss_parameters\", f\"fsigma_8_bin_{b}\"] = float(fsigma_8(zm))\n\n    return 0\n\ndef cleanup(config):\n    pass\n\n\n# def execute(block, config):\n#     h = block[names.cosmological_parameters, \"h0\"]\n#     omdm = block[names.cosmological_parameters, \"omega_c\"]\n#     omb = block[names.cosmological_parameters, \"omega_b\"]\n#     omv = block[names.cosmological_parameters, \"omega_lambda\"]\n#     omk = block[names.cosmological_parameters, \"omega_k\"]\n#     omnuh2 = block[names.cosmological_parameters, \"omnuh2\"]\n#     nnu = block.get_double(names.cosmological_parameters, \"nnu\", default=3.046)\n#     w = block[names.cosmological_parameters, \"w\"]\n#     wa = block[names.cosmological_parameters, \"wa\"]\n\n#     if config[\"use_growth\"]:\n#         gamma = block[\"bias_parameters\", f\"gamma\"]\n#     else:\n#         gamma = 1.0\n        \n#     log_Pk = np.log(block[names.matter_power_lin, \"p_k\"])\n#     log_k_h = np.log(block[names.matter_power_lin, \"k_h\"])\n#     z_Pk = block[names.matter_power_lin, \"z\"]\n\n#     z_growth = block[names.growth_parameters, \"z\"]\n#     if not np.allclose(z_Pk, z_growth):\n#         raise ValueError(\"Redshifts of power spectrum and growth do not match.\")\n\n#     sigma8 = block[names.growth_parameters, \"SIGMA_8\"]\n#     if block.has_value(names.growth_parameters, \"fsigma_8\"):\n#         growth = block[names.growth_parameters, \"fsigma_8\"]\n#     else:\n#         sigma2_vdelta_8 = block[names.growth_parameters, \"SIGMA2_VDELTA_8\"]\n#         growth = sigma2_vdelta_8/sigma8\n\n#     # Setup cosmology\n#     config[\"module\"].setup_cosmology(h, omdm, omb, omv, omk, omnuh2, nnu, w, wa, \n#                                      config[\"use_growth\"], config[\"local_lag_g2\"], config[\"local_lag_g3\"],\n#                                      z_Pk, log_k_h, log_Pk.T,\n#                                      growth, sigma8, verbose=config[\"verbose\"])\n\n    \n#     Pk_mm_pt = np.zeros((len(config[\"zm\"]), len(log_k_h)))\n#     Pk_gm_pt = np.zeros((len(config[\"zm\"]), len(log_k_h)))\n#     Pk_gg_pt = np.zeros((len(config[\"zm\"]), len(log_k_h)))\n\n#     for i, zm in enumerate(config[\"zm\"]):\n#         b = i + 1\n\n#         z = block[names.distances, \"z\"]\n#         H_z = block[names.distances, \"h\"]*2.99792458e8/1e3\n#         DA_z = block[names.distances, \"d_a\"]\n#         z_index = np.argmin(np.abs(z-zm))\n\n#         if z_index >= (200-13)//4:\n#             # z_index too large to fit H_z and DA_z into derived_parameters array\n#             # so we take a range around z[z_index]\n#             s = slice(max(0, z_index-4), min(len(z), z_index+4))\n#             z = z[s]\n#             H_z = H_z[s]\n#             DA_z = DA_z[s]\n#             z_index = np.argmin(np.abs(z-zm))\n\n#         # Bias parameters\n#         b1 = block[\"bias_parameters\", f\"b1_bin_{b}\"]\n#         b2 = block[\"bias_parameters\", f\"b2_bin_{b}\"]\n#         if not config[\"local_lag_g2\"]:\n#             gamma2 = block[\"bias_parameters\", f\"gamma2_bin_{b}\"]\n#         else:\n#             gamma2 = 1.0\n#         if not config[\"local_lag_g3\"]:\n#             gamma3 = block[\"bias_parameters\", f\"gamma3_bin_{b}\"]\n#         else:\n#             gamma3 = 1.0\n#         a_vir = block[\"bias_parameters\", f\"a_vir_bin_{b}\"]\n\n#         vtheo, vtheo_convolved, Pk_mm, Pk_gm, Pk_gg = config[\"module\"].compute_wedges(\n#                                                         config[\"wedges_config\"][i],\n#                                                         b1, b2, gamma2, gamma3, a_vir, gamma,\n#                                                         z_index+2,\n#                                                         H_z, DA_z,\n#                                                         config[\"bands\"],\n#                                                         verbose=config[\"verbose\"])\n\n#         n = len(vtheo)//config[\"num_ell\"]\n#         vtheo = np.array([vtheo[i*n:(i+1)*n] for i in range(config[\"num_ell\"])])\n#         n = len(vtheo_convolved)//config[\"num_ell\"]\n#         vtheo_convolved = np.array([vtheo_convolved[i*n:(i+1)*n] for i in range(config[\"num_ell\"])])\n\n#         block[config[\"output_section_wedges\"], f\"vtheo_bin_{b}\"] = vtheo\n#         block[config[\"output_section_wedges\"], f\"bin_{b}\"] = vtheo_convolved\n#         Pk_mm_pt[i] = Pk_mm\n#         Pk_gm_pt[i] = Pk_gm\n#         Pk_gg_pt[i] = Pk_gg\n\n#     block[config[\"output_section_wedges\"], \"n_wedge\"] = config[\"num_ell\"]\n#     block[config[\"output_section_wedges\"], \"bands\"] = config[\"bands\"]\n#     block[config[\"output_section_wedges\"], \"z\"] = config[\"zm\"]\n\n#     block[config[\"output_section_pk_mm\"], \"z\"] = config[\"zm\"]\n#     block[config[\"output_section_pk_gm\"], \"z\"] = config[\"zm\"]\n#     block[config[\"output_section_pk_gg\"], \"z\"] = config[\"zm\"]\n\n#     block[config[\"output_section_pk_mm\"], \"k_h\"] = np.exp(log_k_h)\n#     block[config[\"output_section_pk_gm\"], \"k_h\"] = np.exp(log_k_h)\n#     block[config[\"output_section_pk_gg\"], \"k_h\"] = np.exp(log_k_h)\n\n#     block[config[\"output_section_pk_mm\"], \"p_k\"] = Pk_mm_pt\n#     block[config[\"output_section_pk_gm\"], \"p_k\"] = Pk_gm_pt\n#     block[config[\"output_section_pk_gg\"], \"p_k\"] = Pk_gg_pt\n\n#     if config[\"compute_lss_parameters\"]:\n#         z = block[names.growth_parameters, \"z\"]\n#         fsigma_8 = scipy.interpolate.InterpolatedUnivariateSpline(z, block[names.growth_parameters, \"fsigma_8\"])\n        \n#         z_background = block[names.distances, \"z\"]\n#         F_AP = scipy.interpolate.InterpolatedUnivariateSpline(z_background, block[names.distances, \"F_AP\"])\n#         rs_DV = scipy.interpolate.InterpolatedUnivariateSpline(z_background[1:], block[names.distances, \"rs_DV\"][1:])\n\n#         for i, zm in enumerate(config[\"zm\"]):\n#             b = i + 1\n\n#             block[\"lss_parameters\", f\"rs_DV_bin_{b}\"] = float(rs_DV(zm))\n#             block[\"lss_parameters\", f\"F_AP_bin_{b}\"] = float(F_AP(zm))\n#             block[\"lss_parameters\", f\"fsigma_8_bin_{b}\"] = float(fsigma_8(zm))\n\n#     return 0\n\n# def cleanup(config):\n#     for c in config[\"wedges_config\"]:\n#         config[\"module\"].cleanup_wedges(c)\n    \n#     config[\"module\"].cleanup_cosmology()\n", "meta": {"hexsha": "6d4654384d0ecd095f756d963e0f4736d53b2cea", "size": 18980, "ext": "py", "lang": "Python", "max_stars_repo_path": "python_interface/cosmosis_module.py", "max_stars_repo_name": "KiDS-WL/kcap_boss_module", "max_stars_repo_head_hexsha": "0e894a7e58b257f50f9348f35309b3171688f004", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python_interface/cosmosis_module.py", "max_issues_repo_name": "KiDS-WL/kcap_boss_module", "max_issues_repo_head_hexsha": "0e894a7e58b257f50f9348f35309b3171688f004", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python_interface/cosmosis_module.py", "max_forks_repo_name": "KiDS-WL/kcap_boss_module", "max_forks_repo_head_hexsha": "0e894a7e58b257f50f9348f35309b3171688f004", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.7477477477, "max_line_length": 135, "alphanum_fraction": 0.5973656481, "include": true, "reason": "import numpy,import scipy", "num_tokens": 5196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.1602002116887026}}
{"text": "# (C) Crown Copyright, Met Office. All rights reserved.\n#\n# This file is part of ocean_error_covs and is released under the BSD 3-Clause license.\n# See LICENSE in the root of the repository for full licensing details.\n#######################################################################\nimport numpy as np\nimport arrays\n\nclass ObsProfiles():\n      \"\"\"Class of functions to deal with profile observations\"\"\"\n\n      def __init__(self):\n         self.undef = 1000\n\n\n      def random_subsample_profiles(self, depths, depth_range, fdbk_var_array):   \n          \"\"\" Thin profile observations vertically by choosing a single observation \n              at random within a pre-defined depth range.\n\n              **** PARAMETERS ****\n              1. depths: Array of depths of the profile observations\n              2. depth_range: Tuple defining boundaries over which to sub-sample\n                              profile observations\n              3. fdbk_var_arrays: object containing the arrays describing the \n                                  innovations \n              \n              ***** RETURNS *****\n              1. subsampled_fdbk_var_array: object containing the sub-sampled\n                                            arrays describing the innovations\n                                            with a single obs for each depth level\n          \"\"\"\n          \n          # Define new tuples\n          lat_dep=[] ; lon_dep =[] ; qc_dep =[] ; mod_dep =[] ; obs_dep = []\n\n          # Loop over obs number\n          for n in range(0, len(fdbk_var_array.lats)):\n              dep_mask = np.logical_and(depths[n,:] >= depth_range[0],\n                                        depths[n,:] <  depth_range[1])\n              num_in_mask=np.sum(dep_mask)\n              if num_in_mask > 0:\n                 lat_dep += [fdbk_var_array.lats[n]]\n                 lon_dep += [fdbk_var_array.lons[n]]\n                 qc_dep += [fdbk_var_array.obs_qc[n]]\n                 random_pick = np.random.random_integers(0, num_in_mask-1)       # NOTE: Results will not be\n                 obs_dep += [fdbk_var_array.obs_vals[n,dep_mask][random_pick]]   # reproduceable unless a\n                 mod_dep += [fdbk_var_array.mod_vals[n,dep_mask][random_pick]]   # random seed is pre-selected\n          \n          # define a new fdbk array object\n          subsampled_fdbk_var_array = arrays.FdbkVarArrays()\n          subsampled_fdbk_var_array.lats = np.array(lat_dep)\n          subsampled_fdbk_var_array.lons = np.array(lon_dep)\n          subsampled_fdbk_var_array.obs_qc = np.array(qc_dep)\n          subsampled_fdbk_var_array.obs_vals = np.array(obs_dep)\n          subsampled_fdbk_var_array.mod_vals = np.array(mod_dep)\n\n          # additional masking for profiles\n          subsampled_fdbk_var_array.obs_qc[np.abs(subsampled_fdbk_var_array.obs_vals)>self.undef] = self.undef\n          return subsampled_fdbk_var_array \n", "meta": {"hexsha": "e55d458b2be7928b0e14fc43d8c2416ff725442a", "size": 2898, "ext": "py", "lang": "Python", "max_stars_repo_path": "HL_error_covs/profiles.py", "max_stars_repo_name": "MetOffice/ocean_error_covs", "max_stars_repo_head_hexsha": "1817c0e31ddefaafd2dbb1f642f30488b5732b88", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HL_error_covs/profiles.py", "max_issues_repo_name": "MetOffice/ocean_error_covs", "max_issues_repo_head_hexsha": "1817c0e31ddefaafd2dbb1f642f30488b5732b88", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-08-25T10:15:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T12:23:49.000Z", "max_forks_repo_path": "HL_error_covs/profiles.py", "max_forks_repo_name": "MetOffice/ocean_error_covs", "max_forks_repo_head_hexsha": "1817c0e31ddefaafd2dbb1f642f30488b5732b88", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-11T06:10:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-11T06:10:41.000Z", "avg_line_length": 48.3, "max_line_length": 110, "alphanum_fraction": 0.5800552105, "include": true, "reason": "import numpy", "num_tokens": 616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.1602002083977244}}
{"text": "from __future__ import print_function\nfrom coordinate_systems import Distance, Angle, Dihedral, OutOfPlane\nfrom utilities import nifty, options, block_matrix\nfrom wrappers import Molecule\nfrom utilities.manage_xyz import write_molden_geoms\n# standard library imports\nimport sys\nimport os\nfrom os import path\n\n# third party\nimport numpy as np\nimport multiprocessing as mp\nfrom collections import Counter\nfrom copy import copy\nfrom itertools import chain\n\n# local application imports\nsys.path.append(path.dirname(path.dirname(path.abspath(__file__))))\n\n\ndef worker(arg):\n   obj, methname = arg[:2]\n   return getattr(obj, methname)(*arg[2:])\n\n\n#######################################################################################\n#### This class contains the main constructor, object properties and staticmethods ####\n#######################################################################################\n\n\n# TODO interpolate is still sloppy. It shouldn't create a new molecule node itself\n# but should create the xyz. GSM should create the new molecule based off that xyz.\n# TODO nconstraints in ic_reparam and write_iters is irrelevant\n\n\nclass GSM(object):\n\n    from utilities import units\n\n    @staticmethod\n    def default_options():\n        if hasattr(GSM, '_default_options'):\n            return GSM._default_options.copy()\n\n        opt = options.Options()\n\n        opt.add_option(\n            key='reactant',\n            required=True,\n            # allowed_types=[Molecule,wrappers.Molecule],\n            doc='Molecule object as the initial reactant structure')\n\n        opt.add_option(\n            key='product',\n            required=False,\n            # allowed_types=[Molecule,wrappers.Molecule],\n            doc='Molecule object for the product structure (not required for single-ended methods.')\n\n        opt.add_option(\n            key='nnodes',\n            required=False,\n            value=1,\n            allowed_types=[int],\n            doc=\"number of string nodes\"\n        )\n\n        opt.add_option(\n            key='optimizer',\n            required=True,\n            doc='Optimzer object  to use e.g. eigenvector_follow, conjugate_gradient,etc. \\\n                        most of the default options are okay for here since GSM will change them anyway',\n        )\n\n        opt.add_option(\n            key='driving_coords',\n            required=False,\n            value=[],\n            allowed_types=[list],\n            doc='Provide a list of tuples to select coordinates to modify atoms\\\n                 indexed at 1')\n\n        opt.add_option(\n            key='CONV_TOL',\n            value=0.0005,\n            required=False,\n            allowed_types=[float],\n            doc='Convergence threshold'\n        )\n\n        opt.add_option(\n            key='CONV_gmax',\n            value=0.001,\n            required=False,\n            allowed_types=[float],\n            doc='Convergence threshold'\n        )\n\n        opt.add_option(\n            key='CONV_Ediff',\n            value=0.1,\n            required=False,\n            allowed_types=[float],\n            doc='Convergence threshold'\n        )\n\n        opt.add_option(\n            key='CONV_dE',\n            value=0.5,\n            required=False,\n            allowed_types=[float],\n            doc='Convergence threshold'\n        )\n\n        opt.add_option(\n            key='ADD_NODE_TOL',\n            value=0.1,\n            required=False,\n            allowed_types=[float],\n            doc='Convergence threshold')\n\n        opt.add_option(\n            key=\"growth_direction\",\n            value=0,\n            required=False,\n            doc=\"how to grow string,0=Normal,1=from reactant\"\n        )\n\n        opt.add_option(\n            key=\"DQMAG_MAX\",\n            value=0.8,\n            required=False,\n            doc=\"max step along tangent direction for SSM\"\n        )\n        opt.add_option(\n            key=\"DQMAG_MIN\",\n            value=0.2,\n            required=False,\n            doc=\"\"\n        )\n\n        opt.add_option(\n            key='print_level',\n            value=1,\n            required=False\n        )\n\n        opt.add_option(\n            key='xyz_writer',\n            value=write_molden_geoms,\n            required=False,\n            doc='Function to be used to format and write XYZ files',\n        )\n\n        opt.add_option(\n            key='mp_cores',\n            value=1,\n            doc='multiprocessing cores for parallel programming. Use this with caution.',\n        )\n\n        opt.add_option(\n            key=\"BDIST_RATIO\",\n            value=0.5,\n            required=False,\n            doc=\"SE-Crossing uses this \\\n                        bdist must be less than 1-BDIST_RATIO of initial bdist in order to be \\\n                        to be considered grown.\",\n        )\n\n        opt.add_option(\n            key='ID',\n            value=0,\n            required=False,\n            doc='A number for identification of Strings'\n        )\n\n        opt.add_option(\n            key='interp_method',\n            value='DLC',\n                allowed_values=['Geodesic', 'DLC'],\n            required=False,\n            doc='Which reparameterization method to use',\n        )\n\n        opt.add_option(\n            key='noise',\n            value=100.0,\n            allowed_types=[float],\n            required=False,\n            doc='Noise to check for intermediate',\n        )\n\n        GSM._default_options = opt\n        return GSM._default_options.copy()\n\n    @classmethod\n    def from_options(cls, **kwargs):\n        return cls(cls.default_options().set_values(kwargs))\n\n    @classmethod\n    def copy_from_options(cls, gsm_obj, reactant, product):\n        new_gsm = cls.from_options(gsm_obj.options.copy().set_values({'reactant': reactant, 'product': product}))\n        return new_gsm\n\n    def __init__(\n            self,\n            options,\n    ):\n        \"\"\" Constructor \"\"\"\n        self.options = options\n\n        os.system('mkdir -p scratch')\n\n        # Cache attributes\n        self.nnodes = self.options['nnodes']\n        self.nodes = [None]*self.nnodes\n        self.nodes[0] = self.options['reactant']\n        self.nodes[-1] = self.options['product']\n        self.driving_coords = self.options['driving_coords']\n        self.growth_direction = self.options['growth_direction']\n        self.isRestarted = False\n        self.DQMAG_MAX = self.options['DQMAG_MAX']\n        self.DQMAG_MIN = self.options['DQMAG_MIN']\n        self.BDIST_RATIO = self.options['BDIST_RATIO']\n        self.ID = self.options['ID']\n        self.optimizer = []\n        self.interp_method = self.options['interp_method']\n        self.CONV_TOL = self.options['CONV_TOL']\n        self.noise = self.options['noise']\n        self.mp_cores = self.options['mp_cores']\n        self.xyz_writer = self.options['xyz_writer']\n\n        optimizer = options['optimizer']\n        for count in range(self.nnodes):\n            self.optimizer.append(optimizer.__class__(optimizer.options.copy()))\n        self.print_level = options['print_level']\n\n        # Set initial values\n        self.current_nnodes = 2\n        self.nR = 1\n        self.nP = 1\n        self.climb = False\n        self.find = False\n        self.ts_exsteps = 3  # multiplier for ts node\n        self.n0 = 1  # something to do with added nodes? \"first node along current block\"\n        self.end_early = False\n        self.tscontinue = True  # whether to continue with TS opt or not\n        self.found_ts = False\n        self.rn3m6 = np.sqrt(3.*self.nodes[0].natoms-6.)\n        self.gaddmax = self.options['ADD_NODE_TOL']  # self.options['ADD_NODE_TOL']/self.rn3m6;\n        print(\" gaddmax:\", self.gaddmax)\n        self.ictan = [None]*self.nnodes\n        self.active = [False] * self.nnodes\n        self.climber = False  # is this string a climber?\n        self.finder = False   # is this string a finder?\n        self.done_growing = False\n        self.nclimb = 0\n        self.nhessreset = 10  # are these used??? TODO\n        self.hessrcount = 0   # are these used?!  TODO\n        self.hess_counter = 0   # it is probably good to reset the hessian\n        self.newclimbscale = 2.\n        self.TS_E_0 = None\n        self.dE_iter = 100.  # change in max TS node\n\n        self.nopt_intermediate = 0     # might be a duplicate of endearly_counter\n        self.flag_intermediate = False\n        self.endearly_counter = 0  # Find the intermediate x time\n        self.pot_min = []\n        self.ran_out = False   # if it ran out of iterations\n\n        self.newic = Molecule.copy_from_options(self.nodes[0])  # newic object is used for coordinate transformations\n\n    @property\n    def TSnode(self):\n        '''\n        The current node with maximum energy\n        '''\n        # Treat GSM with penalty a little different since penalty will increase energy based on energy\n        # differences, which might not be great for Climbing Image\n        if self.__class__.__name__ != \"SE_Cross\" and self.nodes[0].PES.__class__.__name__ == \"Penalty_PES\":\n            energies = np.asarray([0.]*self.nnodes)\n            for i, node in enumerate(self.nodes):\n                if node is not None:\n                    energies[i] = (node.PES.PES1.energy + node.PES.PES2.energy)/2.\n            return int(np.argmax(energies))\n        else:\n            # make sure TS is not zero or last node\n            return int(np.argmax(self.energies[1:self.nnodes-1])+1)\n\n    @property\n    def emax(self):\n        return self.energies[self.TSnode]\n\n    @property\n    def npeaks(self):\n        '''\n        '''\n        minnodes = []\n        maxnodes = []\n        energies = self.energies\n        if energies[1] > energies[0]:\n            minnodes.append(0)\n        if energies[self.nnodes-1] < energies[self.nnodes-2]:\n            minnodes.append(self.nnodes-1)\n        for n in range(self.n0, self.nnodes-1):\n            if energies[n+1] > energies[n]:\n                if energies[n] < energies[n-1]:\n                    minnodes.append(n)\n            if energies[n+1] < energies[n]:\n                if energies[n] > energies[n-1]:\n                    maxnodes.append(n)\n\n        return len(maxnodes)\n\n    @property\n    def energies(self):\n        '''\n        Energies of string\n        '''\n        E = []\n        for ico in self.nodes:\n            if ico is not None:\n                E.append(ico.energy - self.nodes[0].energy)\n        return E\n\n    @energies.setter\n    def energies(self, list_of_E):\n        '''\n        setter for energies\n        '''\n        self.E = list_of_E\n\n    @property\n    def geometries(self):\n        geoms = []\n        for ico in self.nodes:\n            if ico is not None:\n                geoms.append(ico.geometry)\n        return geoms\n\n    @property\n    def gradrmss(self):\n        self._gradrmss = []\n        for ico in self.nodes:\n            if ico is not None:\n                self._gradrmss.append(ico.gradrms)\n        return self._gradrmss\n\n    @property\n    def dEs(self):\n        self._dEs = []\n        for ico in self.nodes:\n            if ico is not None:\n                self._dEs.append(ico.difference_energy)\n        return self._dEs\n\n    @property\n    def ictan(self):\n        return self._ictan\n\n    @ictan.setter\n    def ictan(self, value):\n        self._ictan = value\n\n    @property\n    def dqmaga(self):\n        return self._dqmaga\n\n    @dqmaga.setter\n    def dqmaga(self, value):\n        self._dqmaga = value\n\n    @staticmethod\n    def add_xyz_along_tangent(\n            xyz1,\n            constraints,\n            step,\n            coord_obj,\n    ):\n        dq0 = step*constraints\n        new_xyz = coord_obj.newCartesian(xyz1, dq0)\n\n        return new_xyz\n\n    @staticmethod\n    def add_node(\n            nodeR,\n            nodeP,\n            stepsize,\n            node_id,\n            **kwargs\n    ):\n        '''\n        Add a node between  nodeR and nodeP or if nodeP is none use driving coordinate to add new node\n        '''\n\n        # get driving coord\n        driving_coords = kwargs.get('driving_coords', None)\n        DQMAG_MAX = kwargs.get('DQMAG_MAX', 0.8)\n        DQMAG_MIN = kwargs.get('DQMAG_MIN', 0.2)\n\n        if nodeP is None:\n\n            if driving_coords is None:\n                raise RuntimeError(\"You didn't supply a driving coordinate and product node is None!\")\n\n            BDISTMIN = 0.05\n            ictan, bdist = GSM.get_tangent(nodeR, None, driving_coords=driving_coords)\n\n            if bdist < BDISTMIN:\n                print(\"bdist too small %.3f\" % bdist)\n                return None\n            new_node = Molecule.copy_from_options(nodeR, new_node_id=node_id)\n            new_node.update_coordinate_basis(constraints=ictan)\n            constraint = new_node.constraints[:, 0]\n            sign = -1.\n\n            dqmag_scale = 1.5\n            minmax = DQMAG_MAX - DQMAG_MIN\n            a = bdist/dqmag_scale\n            if a > 1.:\n                a = 1.\n            dqmag = sign*(DQMAG_MIN+minmax*a)\n            if dqmag > DQMAG_MAX:\n                dqmag = DQMAG_MAX\n            print(\" dqmag: %4.3f from bdist: %4.3f\" % (dqmag, bdist))\n\n            dq0 = dqmag*constraint\n            print(\" dq0[constraint]: %1.3f\" % dqmag)\n\n            new_node.update_xyz(dq0)\n            new_node.bdist = bdist\n\n        else:\n            ictan, _ = GSM.get_tangent(nodeR, nodeP)\n            nodeR.update_coordinate_basis(constraints=ictan)\n            constraint = nodeR.constraints[:, 0]\n            dqmag = np.linalg.norm(ictan)\n            print(\" dqmag: %1.3f\" % dqmag)\n            # sign=-1\n            sign = 1.\n            dqmag *= (sign*stepsize)\n            print(\" scaled dqmag: %1.3f\" % dqmag)\n\n            dq0 = dqmag*constraint\n            old_xyz = nodeR.xyz.copy()\n            new_xyz = nodeR.coord_obj.newCartesian(old_xyz, dq0)\n            new_node = Molecule.copy_from_options(MoleculeA=nodeR, xyz=new_xyz, new_node_id=node_id)\n\n        return new_node\n\n    @staticmethod\n    def interpolate_xyz(nodeR, nodeP, stepsize):\n        '''\n        Interpolate between two nodes\n        '''\n        ictan, _ = GSM.get_tangent(nodeR, nodeP)\n        Vecs = nodeR.update_coordinate_basis(constraints=ictan)\n        constraint = nodeR.constraints[:, 0]\n        prim_constraint = block_matrix.dot(Vecs, constraint)\n        dqmag = np.dot(prim_constraint.T, ictan)\n        print(\" dqmag: %1.3f\" % dqmag)\n        # sign=-1\n        sign = 1.\n        dqmag *= (sign*stepsize)\n        print(\" scaled dqmag: %1.3f\" % dqmag)\n\n        dq0 = dqmag*constraint\n        old_xyz = nodeR.xyz.copy()\n        new_xyz = nodeR.coord_obj.newCartesian(old_xyz, dq0)\n\n        return new_xyz\n\n    @staticmethod\n    def interpolate(start_node, end_node, num_interp):\n        '''\n    \n        '''\n        nifty.printcool(\" interpolate\")\n\n        num_nodes = num_interp + 2\n        nodes = [None]*(num_nodes)\n        nodes[0] = start_node\n        nodes[-1] = end_node\n        sign = 1\n        nR = 1\n        nP = 1\n        nn = nR + nP\n\n        for n in range(num_interp):\n            if num_nodes - nn > 1:\n                stepsize = 1./float(num_nodes - nn)\n            else:\n                stepsize = 0.5\n            if sign == 1:\n                iR = nR-1\n                iP = num_nodes - nP\n                iN = nR\n                nodes[nR] = GSM.add_node(nodes[iR], nodes[iP], stepsize, iN)\n                if nodes[nR] is None:\n                    raise RuntimeError\n\n                # print(\" Energy of node {} is {:5.4}\".format(nR,nodes[nR].energy-E0))\n                nR += 1\n                nn += 1\n\n            else:\n                n1 = num_nodes - nP\n                n2 = n1 - 1\n                n3 = nR - 1\n                nodes[n2] = GSM.add_node(nodes[n1], nodes[n3], stepsize, n2)\n                if nodes[n2] is None:\n                    raise RuntimeError\n                # print(\" Energy of node {} is {:5.4}\".format(nR,nodes[nR].energy-E0))\n                nP += 1\n                nn += 1\n            sign *= -1\n\n        return nodes\n\n    @staticmethod\n    def get_tangent_xyz(xyz1, xyz2, prim_coords):\n        PMDiff = np.zeros(len(prim_coords))\n        for k, prim in enumerate(prim_coords):\n            if type(prim) is Distance:\n                PMDiff[k] = 2.5 * prim.calcDiff(xyz2, xyz1)\n            else:\n                PMDiff[k] = prim.calcDiff(xyz2, xyz1)\n        return np.reshape(PMDiff, (-1, 1))\n\n    @staticmethod\n    def get_tangent(node1, node2, print_level=1, **kwargs):\n        '''\n        Get internal coordinate tangent between two nodes, assumes they have unique IDs\n        '''\n\n        if node2 is not None and node1.node_id != node2.node_id:\n            print(\" getting tangent from between %i %i pointing towards %i\" % (node2.node_id, node1.node_id, node2.node_id))\n            assert node2 != None, 'node n2 is None'\n\n            PMDiff = np.zeros(node2.num_primitives)\n            for k, prim in enumerate(node2.primitive_internal_coordinates):\n                if type(prim) is Distance:\n                    PMDiff[k] = 2.5 * prim.calcDiff(node2.xyz, node1.xyz)\n                else:\n                    PMDiff[k] = prim.calcDiff(node2.xyz, node1.xyz)\n\n            return np.reshape(PMDiff, (-1, 1)), None\n        else:\n            print(\" getting tangent from node \", node1.node_id)\n\n            driving_coords = kwargs.get('driving_coords', None)\n            assert driving_coords is not None, \" Driving coord is None!\"\n\n            c = Counter(elem[0] for elem in driving_coords)\n            nadds = c['ADD']\n            nbreaks = c['BREAK']\n            nangles = c['nangles']\n            ntorsions = c['ntorsions']\n\n            ictan = np.zeros((node1.num_primitives, 1), dtype=float)\n            # breakdq = 0.3\n            bdist = 0.0\n            atoms = node1.atoms\n            xyz = node1.xyz.copy()\n\n            for i in driving_coords:\n                if \"ADD\" in i:\n\n                    # order indices to avoid duplicate bonds\n                    if i[1] < i[2]:\n                        index = [i[1]-1, i[2]-1]\n                    else:\n                        index = [i[2]-1, i[1]-1]\n\n                    bond = Distance(index[0], index[1])\n                    prim_idx = node1.coord_obj.Prims.dof_index(index, 'Distance')\n                    if len(i) == 3:\n                        # TODO why not just use the covalent radii?\n                        d0 = (atoms[index[0]].vdw_radius + atoms[index[1]].vdw_radius)/2.8\n                    elif len(i) == 4:\n                        d0 = i[3]\n                    current_d = bond.value(xyz)\n\n                    # TODO don't set tangent if value is too small\n                    ictan[prim_idx] = -1*(d0-current_d)\n                    # if nbreaks>0:\n                    #    ictan[prim_idx] *= 2\n                    # => calc bdist <=\n                    if current_d > d0:\n                        bdist += np.dot(ictan[prim_idx], ictan[prim_idx])\n                    if print_level > 0:\n                        print(\" bond %s target (less than): %4.3f current d: %4.3f diff: %4.3f \" % ((i[1], i[2]), d0, current_d, ictan[prim_idx]))\n\n                elif \"BREAK\" in i:\n                    # order indices to avoid duplicate bonds\n                    if i[1] < i[2]:\n                        index = [i[1]-1, i[2]-1]\n                    else:\n                        index = [i[2]-1, i[1]-1]\n                    bond = Distance(index[0], index[1])\n                    prim_idx = node1.coord_obj.Prims.dof_index(index, 'Distance')\n                    if len(i) == 3:\n                        d0 = (atoms[index[0]].vdw_radius + atoms[index[1]].vdw_radius)\n                    elif len(i) == 4:\n                        d0 = i[3]\n\n                    current_d = bond.value(xyz)\n                    ictan[prim_idx] = -1*(d0-current_d)\n\n                    # => calc bdist <=\n                    if current_d < d0:\n                        bdist += np.dot(ictan[prim_idx], ictan[prim_idx])\n\n                    if print_level > 0:\n                        print(\" bond %s target (greater than): %4.3f, current d: %4.3f diff: %4.3f \" % ((i[1], i[2]), d0, current_d, ictan[prim_idx]))\n                elif \"ANGLE\" in i:\n\n                    if i[1] < i[3]:\n                        index = [i[1]-1, i[2]-1, i[3]-1]\n                    else:\n                        index = [i[3]-1, i[2]-1, i[1]-1]\n                    angle = Angle(index[0], index[1], index[2])\n                    prim_idx = node1.coord_obj.Prims.dof_index(index, 'Angle')\n                    anglet = i[4]\n                    ang_value = angle.value(xyz)\n                    ang_diff = anglet*np.pi/180. - ang_value\n                    # print(\" angle: %s is index %i \" %(angle,ang_idx))\n                    if print_level > 0:\n                        print((\" anglev: %4.3f align to %4.3f diff(rad): %4.3f\" % (ang_value, anglet, ang_diff)))\n                    ictan[prim_idx] = -ang_diff\n                    # TODO need to come up with an adist\n                    # if abs(ang_diff)>0.1:\n                    #    bdist+=ictan[ICoord1.BObj.nbonds+ang_idx]*ictan[ICoord1.BObj.nbonds+ang_idx]\n                elif \"TORSION\" in i:\n\n                    if i[1] < i[4]:\n                        index = [i[1]-1, i[2]-1, i[3]-1, i[4]-1]\n                    else:\n                        index = [i[4]-1, i[3]-1, i[2]-1, i[1]-1]\n                    torsion = Dihedral(index[0], index[1], index[2], index[3])\n                    prim_idx = node1.coord_obj.Prims.dof_index(index, 'Dihedral')\n                    tort = i[5]\n                    torv = torsion.value(xyz)\n                    tor_diff = tort - torv*180./np.pi\n                    if tor_diff > 180.:\n                        tor_diff -= 360.\n                    elif tor_diff < -180.:\n                        tor_diff += 360.\n                    ictan[prim_idx] = -tor_diff*np.pi/180.\n\n                    if tor_diff*np.pi/180. > 0.1 or tor_diff*np.pi/180. < 0.1:\n                        bdist += np.dot(ictan[prim_idx], ictan[prim_idx])\n                    if print_level > 0:\n                        print((\" current torv: %4.3f align to %4.3f diff(deg): %4.3f\" % (torv*180./np.pi, tort, tor_diff)))\n\n                elif \"OOP\" in i:\n                    index = [i[1]-1, i[2]-1, i[3]-1, i[4]-1]\n                    oop = OutOfPlane(index[0], index[1], index[2], index[3])\n                    prim_idx = node1.coord_obj.Prims.dof_index(index, 'OutOfPlane')\n                    oopt = i[5]\n                    oopv = oop.value(xyz)\n                    oop_diff = oopt - oopv*180./np.pi\n                    if oop_diff > 180.:\n                        oop_diff -= 360.\n                    elif oop_diff < -180.:\n                        oop_diff += 360.\n                    ictan[prim_idx] = -oop_diff*np.pi/180.\n\n                    if oop_diff*np.pi/180. > 0.1 or oop_diff*np.pi/180. < 0.1:\n                        bdist += np.dot(ictan[prim_idx], ictan[prim_idx])\n                    if print_level > 0:\n                        print((\" current oopv: %4.3f align to %4.3f diff(deg): %4.3f\" % (oopv*180./np.pi, oopt, oop_diff)))\n\n            bdist = np.sqrt(bdist)\n            if np.all(ictan == 0.0):\n                raise RuntimeError(\" All elements are zero\")\n            return ictan, bdist\n\n    @staticmethod\n    def get_tangents(nodes, n0=0, print_level=0):\n        '''\n        Get the normalized internal coordinate tangents and magnitudes between all nodes\n        '''\n        nnodes = len(nodes)\n        dqmaga = [0.]*nnodes\n        ictan = [[]]*nnodes\n\n        for n in range(n0+1, nnodes):\n            # print \"getting tangent between %i %i\" % (n,n-1)\n            assert nodes[n] is not None, \"n is bad\"\n            assert nodes[n-1] is not None, \"n-1 is bad\"\n            ictan[n] = GSM.get_tangent_xyz(nodes[n-1].xyz, nodes[n].xyz, nodes[0].primitive_internal_coordinates)\n\n            dqmaga[n] = 0.\n            # ictan0= np.copy(ictan[n])\n            dqmaga[n] = np.linalg.norm(ictan[n])\n\n            ictan[n] /= dqmaga[n]\n\n            # NOTE:\n            # vanilla GSM has a strange metric for distance\n            # no longer following 7/1/2020\n            # constraint = self.newic.constraints[:,0]\n            # just a fancy way to get the normalized tangent vector\n            # prim_constraint = block_matrix.dot(Vecs,constraint)\n            # for prim in self.newic.primitive_internal_coordinates:\n            #    if type(prim) is Distance:\n            #        index = self.newic.coord_obj.Prims.dof_index(prim)\n            #        prim_constraint[index] *= 2.5\n            # dqmaga[n] = float(np.dot(prim_constraint.T,ictan0))\n            # dqmaga[n] = float(np.sqrt(dqmaga[n]))\n            if dqmaga[n] < 0.:\n                raise RuntimeError\n\n        # TEMPORORARY parallel idea\n        # ictan = [0.]\n        # ictan += [ Process(target=get_tangent,args=(n,)) for n in range(n0+1,self.nnodes)]\n        # dqmaga = [ Process(target=get_dqmag,args=(n,ictan[n])) for n in range(n0+1,self.nnodes)]\n\n        if print_level > 1:\n            print('------------printing ictan[:]-------------')\n            for n in range(n0+1, nnodes):\n                print(\"ictan[%i]\" % n)\n                print(ictan[n].T)\n        if print_level > 0:\n            print('------------printing dqmaga---------------')\n            for n in range(n0+1, nnodes):\n                print(\" {:5.4}\".format(dqmaga[n]), end='')\n                if (n) % 5 == 0:\n                    print()\n            print()\n        return ictan, dqmaga\n\n    @staticmethod\n    def get_three_way_tangents(nodes, energies, find=True, n0=0, print_level=0):\n        '''\n        Calculates internal coordinate tangent with a three-way tangent at TS node\n        '''\n        nnodes = len(nodes)\n        ictan = [[]]*nnodes\n        dqmaga = [0.]*nnodes\n        # TSnode = np.argmax(energies[1:nnodes-1])+1\n        TSnode = np.argmax(energies)   # allow for the possibility of TS node to be endpoints?\n\n        last_node_max = (TSnode == nnodes-1)\n        first_node_max = (TSnode == 0)\n        if first_node_max or last_node_max:\n            print(\"*********** This will cause a range error in the following for loop *********\")\n            print(\"** Setting the middle of the string to be TS node to get proper directions **\")\n            TSnode = nnodes//2\n\n        for n in range(n0, nnodes):\n            do3 = False\n            print('getting tan[{' + str(n) + '}]')\n            if n < TSnode:\n                # The order is very important here\n                # the way it should be ;(\n                intic_n = n+1\n                newic_n = n\n\n                # old way\n                # intic_n = n\n                # newic_n = n+1\n\n            elif n > TSnode:\n                # The order is very important here\n                intic_n = n\n                newic_n = n-1\n            else:\n                do3 = True\n                newic_n = n\n                intic_n = n+1\n                int2ic_n = n-1\n\n            if do3:\n                if first_node_max or last_node_max:\n                    t1, _ = GSM.get_tangent(nodes[intic_n], nodes[newic_n])\n                    t2, _ = GSM.get_tangent(nodes[newic_n], nodes[int2ic_n])\n                    print(\" done 3 way tangent\")\n                    ictan0 = t1 + t2\n                else:\n                    f1 = 0.\n                    dE1 = abs(energies[n+1]-energies[n])\n                    dE2 = abs(energies[n] - energies[n-1])\n                    dEmax = max(dE1, dE2)\n                    dEmin = min(dE1, dE2)\n                    if energies[n+1] > energies[n-1]:\n                        f1 = dEmax/(dEmax+dEmin+0.00000001)\n                    else:\n                        f1 = 1 - dEmax/(dEmax+dEmin+0.00000001)\n\n                    print(' 3 way tangent ({}): f1:{:3.2}'.format(n, f1))\n\n                    t1, _ = GSM.get_tangent(nodes[intic_n], nodes[newic_n])\n                    t2, _ = GSM.get_tangent(nodes[newic_n], nodes[int2ic_n])\n                    print(\" done 3 way tangent\")\n                    ictan0 = f1*t1 + (1.-f1)*t2\n            else:\n                ictan0, _ = GSM.get_tangent(nodes[newic_n], nodes[intic_n])\n\n            ictan[n] = ictan0/np.linalg.norm(ictan0)\n            dqmaga[n] = np.linalg.norm(ictan0)\n\n        return ictan, dqmaga\n\n    @staticmethod\n    def ic_reparam(nodes, energies, climbing=False, ic_reparam_steps=8, print_level=1, NUM_CORE=1, MAXRE=0.25):\n        '''\n        Reparameterizes the string using Delocalizedin internal coordinatesusing three-way tangents at the TS node\n        Only pushes nodes outwards during reparameterization because otherwise too many things change.\n            Be careful, however, if the path is allup or alldown then this can cause\n        Parameters\n        ----------\n        nodes : list of molecule objects\n        energies : list of energies in kcal/mol\n        ic_reparam_steps : int max number of reparameterization steps\n        print_level : int verbosity\n        '''\n        nifty.printcool(\"reparametrizing string nodes\")\n\n        nnodes = len(nodes)\n        rpart = np.zeros(nnodes)\n        for n in range(1, nnodes):\n            rpart[n] = 1./(nnodes-1)\n        deltadqs = np.zeros(nnodes)\n        TSnode = np.argmax(energies)\n        disprms = 100\n        if ((TSnode == nnodes-1) or (TSnode == 0)) and climbing:\n            raise RuntimeError(\" TS node shouldn't be the first or last node\")\n\n        ideal_progress_gained = np.zeros(nnodes)\n        if climbing:\n            for n in range(1, TSnode):\n                ideal_progress_gained[n] = 1./(TSnode)\n            for n in range(TSnode+1, nnodes):\n                ideal_progress_gained[n] = 1./(nnodes-TSnode-1)\n            ideal_progress_gained[TSnode] = 0.\n        else:\n            for n in range(1, nnodes):\n                ideal_progress_gained[n] = 1./(nnodes-1)\n\n        for i in range(ic_reparam_steps):\n\n            ictan, dqmaga = GSM.get_tangents(nodes)\n            totaldqmag = np.sum(dqmaga)\n\n            if climbing:\n                progress = np.zeros(nnodes)\n                progress_gained = np.zeros(nnodes)\n                h1dqmag = np.sum(dqmaga[:TSnode+1])\n                h2dqmag = np.sum(dqmaga[TSnode+1:nnodes])\n                if print_level > 0:\n                    print(\" h1dqmag, h2dqmag: %3.2f %3.2f\" % (h1dqmag, h2dqmag))\n                progress_gained[:TSnode] = dqmaga[:TSnode]/h1dqmag\n                progress_gained[TSnode+1:] = dqmaga[TSnode+1:]/h2dqmag\n                progress[:TSnode] = np.cumsum(progress_gained[:TSnode])\n                progress[TSnode:] = np.cumsum(progress_gained[TSnode:])\n            else:\n                progress = np.cumsum(dqmaga)/totaldqmag\n                progress_gained = dqmaga/totaldqmag\n\n            if i == 0:\n                orig_dqmaga = copy(dqmaga)\n                orig_progress_gained = copy(progress_gained)\n\n            if climbing:\n                difference = np.zeros(nnodes)\n                for n in range(TSnode):\n                    difference[n] = ideal_progress_gained[n] - progress_gained[n]\n                    deltadqs[n] = difference[n]*h1dqmag\n                for n in range(TSnode+1, nnodes):\n                    difference[n] = ideal_progress_gained[n] - progress_gained[n]\n                    deltadqs[n] = difference[n]*h2dqmag\n            else:\n                difference = ideal_progress_gained - progress_gained\n                deltadqs = difference*totaldqmag\n\n            if print_level > 1:\n                print(\" ideal progress gained per step\", end=' ')\n                for n in range(nnodes):\n                    print(\" step [{}]: {:1.3f}\".format(n, ideal_progress_gained[n]), end=' ')\n                print()\n                print(\" path progress                 \", end=' ')\n                for n in range(nnodes):\n                    print(\" step [{}]: {:1.3f}\".format(n, progress_gained[n]), end=' ')\n                print()\n                print(\" difference                    \", end=' ')\n                for n in range(nnodes):\n                    print(\" step [{}]: {:1.3f}\".format(n, difference[n]), end=' ')\n                print()\n                print(\" deltadqs                      \", end=' ')\n                for n in range(nnodes):\n                    print(\" step [{}]: {:1.3f}\".format(n, deltadqs[n]), end=' ')\n                print()\n\n            # disprms = np.linalg.norm(deltadqs)/np.sqrt(nnodes-1)\n            disprms = np.linalg.norm(deltadqs)/np.sqrt(nnodes-1)\n            print(\" disprms: {:1.3}\\n\".format(disprms))\n\n            if disprms < 0.02:\n                break\n\n            # Move nodes\n            if climbing:\n                deltadqs[TSnode-2] -= deltadqs[TSnode-1]\n                deltadqs[nnodes-2] -= deltadqs[nnodes-1]\n                for n in range(1, nnodes-1):\n                    if abs(deltadqs[n]) > MAXRE:\n                        deltadqs[n] = np.sign(deltadqs[n])*MAXRE\n                for n in range(TSnode-1):\n                    deltadqs[n+1] += deltadqs[n]\n                for n in range(TSnode+1, nnodes-2):\n                    deltadqs[n+1] += deltadqs[n]\n                for n in range(nnodes):\n                    if abs(deltadqs[n]) > MAXRE:\n                        deltadqs[n] = np.sign(deltadqs[n])*MAXRE\n\n                if NUM_CORE > 1:\n\n                    # 5/14/2021 TS node fucks this up?!\n                    tans = [ictan[n] if deltadqs[n] < 0 else ictan[n+1] for n in chain(range(1, TSnode), range(TSnode+1, nnodes-1))]  # + [ ictan[n] if deltadqs[n]<0 else ictan[n+1] for n in range(TSnode+1,nnodes-1)]\n                    pool = mp.Pool(NUM_CORE)\n                    Vecs = pool.map(worker, ((nodes[0].coord_obj, \"build_dlc\", node.xyz, tan) for node, tan in zip(nodes[1:TSnode] + nodes[TSnode+1:nnodes-1], tans)))\n                    pool.close()\n                    pool.join()\n                    for n, node in enumerate(nodes[1:TSnode] + nodes[TSnode+1:nnodes-1]):\n                        node.coord_basis = Vecs[n]\n\n                    # move the positions\n                    dqs = [deltadqs[n]*nodes[n].constraints[:, 0] for n in chain(range(1, TSnode), range(TSnode+1, nnodes-1))]\n                    pool = mp.Pool(NUM_CORE)\n                    newXyzs = pool.map(worker, ((node.coord_obj, \"newCartesian\", node.xyz, dq) for node, dq in zip(nodes[1:TSnode] + nodes[TSnode+1:nnodes-1], dqs)))\n                    pool.close()\n                    pool.join()\n                    for n, node in enumerate(nodes[1:TSnode] + nodes[TSnode+1:nnodes-1]):\n                        node.xyz = newXyzs[n]\n                else:\n                    for n in chain(range(1, TSnode), range(TSnode+1, nnodes-1)):\n                        if deltadqs[n] < 0:\n                            # print(f\" Moving node {n} along tan[{n}] this much {deltadqs[n]}\")\n                            print(\" Moving node {} along tan[{}] this much {}\".format(n, n, deltadqs[n]))\n                            nodes[n].update_coordinate_basis(ictan[n])\n                            constraint = nodes[n].constraints[:, 0]\n                            dq = deltadqs[n]*constraint\n                            nodes[n].update_xyz(dq, verbose=(print_level > 1))\n                        elif deltadqs[n] > 0:\n                            print(\" Moving node {} along tan[{}] this much {}\".format(n, n+1, deltadqs[n]))\n                            nodes[n].update_coordinate_basis(ictan[n+1])\n                            constraint = nodes[n].constraints[:, 0]\n                            dq = deltadqs[n]*constraint\n                            nodes[n].update_xyz(dq, verbose=(print_level > 1))\n            else:\n                # e.g 11-2 = 9, deltadq[9] -= deltadqs[10]\n                deltadqs[nnodes-2] -= deltadqs[nnodes-1]\n                for n in range(1, nnodes-1):\n                    if abs(deltadqs[n]) > MAXRE:\n                        deltadqs[n] = np.sign(deltadqs[n])*MAXRE\n                for n in range(1, nnodes-2):\n                    deltadqs[n+1] += deltadqs[n]\n                for n in range(1, nnodes-1):\n                    if abs(deltadqs[n]) > MAXRE:\n                        deltadqs[n] = np.sign(deltadqs[n])*MAXRE\n\n                if NUM_CORE > 1:\n                    # Update the coordinate basis\n                    tans = [ictan[n] if deltadqs[n] < 0 else ictan[n+1] for n in range(1, nnodes-1)]\n                    pool = mp.Pool(NUM_CORE)\n                    Vecs = pool.map(worker, ((nodes[0].coord_obj, \"build_dlc\", node.xyz, tan) for node, tan in zip(nodes[1:nnodes-1], tans)))\n                    pool.close()\n                    pool.join()\n                    for n, node in enumerate(nodes[1:nnodes-1]):\n                        node.coord_basis = Vecs[n]\n                    # move the positions\n                    dqs = [deltadqs[n]*nodes[n].constraints[:, 0] for n in range(1, nnodes-1)]\n                    pool = mp.Pool(NUM_CORE)\n                    newXyzs = pool.map(worker, ((node.coord_obj, \"newCartesian\", node.xyz, dq) for node, dq in zip(nodes[1:nnodes-1], dqs)))\n                    pool.close()\n                    pool.join()\n                    for n, node in enumerate(nodes[1:nnodes-1]):\n                        node.xyz = newXyzs[n]\n                else:\n                    for n in range(1, nnodes-1):\n                        if deltadqs[n] < 0:\n                            # print(f\" Moving node {n} along tan[{n}] this much {deltadqs[n]}\")\n                            print(\" Moving node {} along tan[{}] this much {}\".format(n, n, deltadqs[n]))\n                            nodes[n].update_coordinate_basis(ictan[n])\n                            constraint = nodes[n].constraints[:, 0]\n                            dq = deltadqs[n]*constraint\n                            nodes[n].update_xyz(dq, verbose=(print_level > 1))\n                        elif deltadqs[n] > 0:\n                            print(\" Moving node {} along tan[{}] this much {}\".format(n, n+1, deltadqs[n]))\n                            nodes[n].update_coordinate_basis(ictan[n+1])\n                            constraint = nodes[n].constraints[:, 0]\n                            dq = deltadqs[n]*constraint\n                            nodes[n].update_xyz(dq, verbose=(print_level > 1))\n\n        if climbing:\n            ictan, dqmaga = GSM.get_tangents(nodes)\n            h1dqmag = np.sum(dqmaga[:TSnode+1])\n            h2dqmag = np.sum(dqmaga[TSnode+1:nnodes])\n            if print_level > 0:\n                print(\" h1dqmag, h2dqmag: %3.2f %3.2f\" % (h1dqmag, h2dqmag))\n            progress_gained[:TSnode] = dqmaga[:TSnode]/h1dqmag\n            progress_gained[TSnode+1:] = dqmaga[TSnode+1:]/h2dqmag\n            progress[:TSnode] = np.cumsum(progress_gained[:TSnode])\n            progress[TSnode:] = np.cumsum(progress_gained[TSnode:])\n        else:\n            ictan, dqmaga = GSM.get_tangents(nodes)\n            totaldqmag = np.sum(dqmaga)\n            progress = np.cumsum(dqmaga)/totaldqmag\n            progress_gained = dqmaga/totaldqmag\n        print()\n        if print_level > 0:\n            print(\" ideal progress gained per step\", end=' ')\n            for n in range(nnodes):\n                print(\" step [{}]: {:1.3f}\".format(n, ideal_progress_gained[n]), end=' ')\n            print()\n            print(\" original path progress        \", end=' ')\n            for n in range(nnodes):\n                print(\" step [{}]: {:1.3f}\".format(n, orig_progress_gained[n]), end=' ')\n            print()\n            print(\" reparameterized path progress \", end=' ')\n            for n in range(nnodes):\n                print(\" step [{}]: {:1.3f}\".format(n, progress_gained[n]), end=' ')\n            print()\n\n        print(\" spacings (begin ic_reparam, steps\", end=' ')\n        for n in range(nnodes):\n            print(\" {:1.2}\".format(orig_dqmaga[n]), end=' ')\n        print()\n        print(\" spacings (end ic_reparam, steps: {}/{}):\".format(i+1, ic_reparam_steps), end=' ')\n        for n in range(nnodes):\n            print(\" {:1.2}\".format(dqmaga[n]), end=' ')\n        print(\"\\n  disprms: {:1.3}\".format(disprms))\n\n        return\n\n    # TODO move to string utils or delete altogether\n    #def get_current_rotation(self,frag,a1,a2):\n    #    '''\n    #    calculate current rotation for single-ended nodes\n    #    '''\n    #\n    #    # Get the information on fragment to rotate\n    #    sa,ea,sp,ep = self.nodes[0].coord_obj.Prims.prim_only_block_info[frag]\n    #\n    #    theta = 0.\n    #    # Haven't added any nodes yet\n    #    if self.nR==1:\n    #        return theta\n\n    #    for n in range(1,self.nR):\n    #        xyz_frag = self.nodes[n].xyz[sa:ea].copy()\n    #        axis = self.nodes[n].xyz[a2] - self.nodes[n].xyz[a1]\n    #        axis /= np.linalg.norm(axis)\n    #\n    #        # only want the fragment of interest\n    #        reference_xyz = self.nodes[n-1].xyz.copy()\n\n    #        # Turn off\n    #        ref_axis = reference_xyz[a2] - reference_xyz[a1]\n    #        ref_axis /= np.linalg.norm(ref_axis)\n\n    #        # ALIGN previous and current node to get rotation around axis of rotation\n    #        #print(' Rotating reference axis to current axis')\n    #        I = np.eye(3)\n    #        v = np.cross(ref_axis,axis)\n    #        if v.all()==0.:\n    #            print('Rotation is identity')\n    #            R=I\n    #        else:\n    #            vx = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]])\n    #            c = np.dot(ref_axis,axis)\n    #            s = np.linalg.norm(v)\n    #            R = I + vx + np.dot(vx,vx) * (1. - c)/(s**2)\n    #        new_ref_axis = np.dot(ref_axis,R.T)\n    #        #print(' overlap of ref-axis and axis (should be 1.) %1.2f' % np.dot(new_ref_axis,axis))\n    #        new_ref_xyz = np.dot(reference_xyz,R.T)\n\n    #\n    #        # Calculate dtheta\n    #        ca = self.nodes[n].primitive_internal_coordinates[sp+3]\n    #        cb = self.nodes[n].primitive_internal_coordinates[sp+4]\n    #        cc = self.nodes[n].primitive_internal_coordinates[sp+5]\n    #        dv12_a = ca.calcDiff(self.nodes[n].xyz,new_ref_xyz)\n    #        dv12_b = cb.calcDiff(self.nodes[n].xyz,new_ref_xyz)\n    #        dv12_c = cc.calcDiff(self.nodes[n].xyz,new_ref_xyz)\n    #        dv12 = np.array([dv12_a,dv12_b,dv12_c])\n    #        #print(dv12)\n    #        dtheta = np.linalg.norm(dv12)  #?\n    #\n    #        dtheta = dtheta + np.pi % (2*np.pi) - np.pi\n    #        theta += dtheta\n\n    #    theta = theta/ca.w\n    #    angle = theta * 180./np.pi\n    #    print(angle)\n\n    #    return theta\n\n    @staticmethod\n    def calc_optimization_metrics(nodes):\n        '''\n        '''\n\n        nnodes = len(nodes)\n        rn3m6 = np.sqrt(3*nodes[0].natoms-6)\n        totalgrad = 0.0\n        gradrms = 0.0\n        sum_gradrms = 0.0\n        for i, ico in enumerate(nodes[1:nnodes-1]):\n            if ico != None:\n                print(\" node: {:02d} gradrms: {:.6f}\".format(i, float(ico.gradrms)), end='')\n                if i % 5 == 0:\n                    print()\n                totalgrad += ico.gradrms*rn3m6\n                gradrms += ico.gradrms*ico.gradrms\n                sum_gradrms += ico.gradrms\n        print('')\n        # TODO wrong for growth\n        gradrms = np.sqrt(gradrms/(nnodes-2))\n        return totalgrad, gradrms, sum_gradrms\n", "meta": {"hexsha": "72b2efe9db00740512ea0379c3d2a6eff67caf6e", "size": 43118, "ext": "py", "lang": "Python", "max_stars_repo_path": "pygsm/growing_string_methods/gsm.py", "max_stars_repo_name": "RaphaelRobidas/pyGSM", "max_stars_repo_head_hexsha": "da49e1864bd3dccf44c327281eb3bb07e94a5ee0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pygsm/growing_string_methods/gsm.py", "max_issues_repo_name": "RaphaelRobidas/pyGSM", "max_issues_repo_head_hexsha": "da49e1864bd3dccf44c327281eb3bb07e94a5ee0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pygsm/growing_string_methods/gsm.py", "max_forks_repo_name": "RaphaelRobidas/pyGSM", "max_forks_repo_head_hexsha": "da49e1864bd3dccf44c327281eb3bb07e94a5ee0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3612099644, "max_line_length": 216, "alphanum_fraction": 0.5035715942, "include": true, "reason": "import numpy", "num_tokens": 10920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.31069437683198775, "lm_q1q2_score": 0.1602002083977244}}
{"text": "import os\nimport glob\nimport math\nimport random\nimport sys\nimport time\nimport numpy as np\n\nfrom PIL import Image\n\nfrom scipy.signal import savgol_filter\nfrom six.moves import xrange\n\nimport umap\nimport argparse\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.distributed as dist\nfrom torch.utils.data import Dataset, DataLoader, DistributedSampler\n\nimport torchvision.datasets as datasets\nimport torchvision.transforms as transforms\nfrom torchvision.utils import make_grid, save_image\nimport pytorch_lightning as pl\n\n\nparser = argparse.ArgumentParser(description='VQ-VAE.')\nparser.add_argument(\n    '--rank',\n    default=0,\n    type=int,\n    help=\"Rank of the training task\"\n)\nparser.add_argument(\n    '--world_size',\n    default=1,\n    type=int,\n    help=\"World size of training tasks\"\n)\nparser.add_argument(\n    '--num_workers',\n    default=4,\n    type=int,\n    help=\"Number of parallel data loaders\"\n)\nparser.add_argument(\n    '--init_method',\n    default='tcp://192.168.1.154:23456',\n    help=\"Master host (e.g. 'tcp://192.168.1.154:23456')\"\n)\nparser.add_argument(\n    '--epoch_start',\n    default=1,\n    type=int,\n    help=\"Epoch to start training from (load savepoint)\"\n)\nparser.add_argument(\n    '--num_epochs',\n    default=15000,\n    type=int,\n    help=\"Number of epochs to run\"\n)\nparser.add_argument(\n    '--batch_size',\n    default=64,\n    type=int,\n    help=\"Number of data elements for one pass\"\n)\nparser.add_argument(\n    '--image_width',\n    default=128,\n    type=int,\n    help=\"Horizontal image dimension\"\n)\nparser.add_argument(\n    '--image_height',\n    default=128,\n    type=int,\n    help=\"Vertical image dimension\"\n)\nparser.add_argument(\n    '--backend',\n    default=\"nccl\",\n    help=\"Distributed backend to use\"\n)\n\nargs = parser.parse_args()\nprint(args)\n\nnum_hiddens = 128\nnum_residual_hiddens = 32\nnum_residual_layers = 2\nembedding_dim = 64\nnum_embeddings = 512\ncommitment_cost = 0.25\ndecay = 0.99\nlearning_rate = 1e-3\nsaved_models_path = \"./saved_models/{epoch:08d}.vq-vae.net\"\nsaved_results_path = \"./results/{epoch:08d}.vq-vae.{name}\"\n\nif (torch.cuda.is_available()):\n    device = \"cuda\"\n    print(\"CUDA is available.\")\nelse:\n    device = \"cpu\"\n    print(\"This example uses nccl as backend which is only available for (nVidia) GPUs.\")\n    sys.exit(-1)\n\npl.seed_everything(12345)\n\nos.makedirs(os.path.dirname(saved_models_path.format(epoch=0)), exist_ok=True)\nos.makedirs(os.path.dirname(saved_results_path.format(epoch=0,name='')), exist_ok=True)\n\n\nclass NoisySource_ImageDataset(Dataset):\n    def __init__(self, images_pattern, transforms_before=None, transforms_after=None):\n        self.images_pattern = images_pattern\n        self.transforms_before = transforms_before\n        self.transforms_after = transforms_after\n        self.image_names = glob.glob(images_pattern)\n\n    def __len__(self):\n        return len(self.image_names)\n\n    def __getitem__(self, idx):\n        while True:\n            img_name = self.image_names[idx]\n            try:\n                image_trg = self._load_image(img_name)\n                if (image_trg.size[0] >= args.image_width) and (image_trg.size[1] >= args.image_height):\n                    break\n                print(\"Image {} too small ({}).\".format(img_name, image_trg.size))\n            except Exception as e:\n                print(\"Exception {} - caught.\".format(str(e)))\n            idx = (idx+1) % len(self)\n            \n        if self.transforms_before:\n            image_trg = self.transforms_before(image_trg)\n        image_src = self._pixel_noise(image_trg)\n        if self.transforms_after:\n            image_trg = self.transforms_after(image_trg)\n        if self.transforms_after:\n            image_src = self.transforms_after(image_src)\n        return {\n            \"image_src\": image_src,\n            \"image_trg\": image_trg,\n        }\n\n    def _load_image(self, path):\n        with open(path, 'rb') as f:\n            img = Image.open(f)\n            return img.convert('RGB')\n        \n    def _pixel_noise(self, src):\n        factor = random.randint(8,64)\n        pix = src.copy()\n        nsiz_w = max(int(src.width/factor),1)\n        nsiz_h = max(int(src.height/factor),1)\n        pix = pix.resize((nsiz_w, nsiz_h))\n        pix = pix.resize(src.size, Image.NEAREST)\n        w0 = random.randint(0,src.width)\n        h0 = random.randint(0,src.height)\n        w1 = random.randint(w0, src.width)\n        h1 = random.randint(h0, src.height)\n        pix = pix.crop((w0,h0,w1,h1))\n        res = src.copy()\n        res.paste(pix, (w0,h0))\n        return res\n\n# Training Data\n# Dataset\n\ntraining_data_dataset = NoisySource_ImageDataset(\n    \"/data/imagenet/imagenet_images/*/*.jpg\",\n    transforms_before=transforms.Compose(\n        [\n            transforms.RandomCrop((args.image_height,args.image_width), padding_mode='reflect')\n        ]\n    ),\n    transforms_after=transforms.Compose(\n        [\n            transforms.ToTensor(),\n            transforms.Normalize((0.5,0.5,0.5), (1.0,1.0,1.0))\n        ]\n    ),\n)\n\n# training_data_dataset = datasets.ImageFolder(\n#     \"/data/imagenet\",\n#     transform=transforms.Compose(\n#         [\n#             transforms.Resize((args.image_height,args.image_width), interpolation=2),\n#             transforms.ToTensor(),\n#             transforms.Normalize((0.5,0.5,0.5), (1.0,1.0,1.0))\n#         ]\n#     ),\n# #    target_transform=None,\n# #    loader=<function default_loader>,\n# #    is_valid_file=None\n# )\n# training_data_dataset = datasets.CIFAR10(\n#     root=\"data\", train=True, download=True,\n#     transform=transforms.Compose(\n#         [\n#             transforms.Resize(IMAGE_SIZE, interpolation=2),\n#             transforms.ToTensor(),\n#             transforms.Normalize((0.5,0.5,0.5), (1.0,1.0,1.0))\n#         ]\n#     )\n# )\n# training_data_dataset = datasets.MNIST(\n#     root=\"data\",\n#     train=True,\n#     transform=transforms.Compose(\n#         [\n#             transforms.Resize(IMAGE_SIZE, interpolation=2),\n#             transforms.Grayscale(num_output_channels=3),\n#             transforms.ToTensor(),\n#             transforms.Normalize((0.5,0.5,0.5), (1.0,1.0,1.0))\n#         ]\n#     ),\n#     target_transform=None,\n#     download=True\n# )\n# DataSampler\ntraining_data_sampler = DistributedSampler(\n    training_data_dataset,\n    num_replicas=args.world_size,\n    rank=args.rank,\n    shuffle=True\n)\n# DataLoader\ntraining_data_loader = DataLoader(\n    training_data_dataset,\n    batch_size=args.batch_size, \n    shuffle=(training_data_sampler is None),\n    sampler=training_data_sampler,\n    pin_memory=True,\n    num_workers=args.num_workers,\n)\n\n# Validation Data\n# Dataset\nvalidation_data_dataset = NoisySource_ImageDataset(\n    \"/data/imagenet/imagenet_images/*/*.jpg\",\n    transforms_before=transforms.Compose(\n        [\n            transforms.RandomCrop((args.image_height,args.image_width), )\n        ]\n    ),\n    transforms_after=transforms.Compose(\n        [\n            transforms.ToTensor(),\n            transforms.Normalize((0.5,0.5,0.5), (1.0,1.0,1.0))\n        ]\n    ),\n)\n# validation_data_dataset = datasets.ImageFolder(\n#     \"/data/imagenet\",\n#     transform=transforms.Compose(\n#         [\n#             transforms.Resize((args.image_height,args.image_width), interpolation=2),\n#             transforms.ToTensor(),\n#             transforms.Normalize((0.5,0.5,0.5), (1.0,1.0,1.0))\n#         ]\n#     ),\n# #    target_transform=None,\n# #    loader=<function default_loader>,\n# #    is_valid_file=None\n# )\n# validation_data_dataset = datasets.CIFAR10(\n#     root=\"data\", train=False, download=True,\n#     transform=transforms.Compose(\n#         [\n#             transforms.Resize(IMAGE_SIZE, interpolation=2),\n#             transforms.ToTensor(),\n#             transforms.Normalize((0.5,0.5,0.5), (1.0,1.0,1.0))\n#         ]\n#     )\n# )\n# validation_data_dataset = datasets.MNIST(\n#     root=\"data\",\n#     train=False,\n#     transform=transforms.Compose(\n#         [\n#             transforms.Resize(IMAGE_SIZE, interpolation=2),\n#             transforms.Grayscale(num_output_channels=3),\n#             transforms.ToTensor(),\n#             transforms.Normalize((0.5,0.5,0.5), (1.0,1.0,1.0))\n#         ]\n#     ),\n#     target_transform=None,\n#     download=True\n# )\n# DataSampler\nvalidation_data_sampler = DistributedSampler(\n    validation_data_dataset,\n    num_replicas=args.world_size,\n    rank=args.rank,\n    shuffle=True\n)\n# DataLoader\nvalidation_data_loader = DataLoader(\n    validation_data_dataset,\n    batch_size=32,\n    shuffle=(validation_data_sampler is None),\n    sampler=validation_data_sampler,\n    pin_memory=True,\n)\n\ntraining_data_loader_iterator = iter(training_data_loader)\nvalidation_data_loader_iterator = iter(validation_data_loader)\n\n\n# Vector Quantizer Layer\n# \n# This layer takes a tensor to be quantized. The channel dimension will be used as the space in which to quantize. All other dimensions will be flattened and will be seen as different examples to quantize.\n# \n# The output tensor will have the same shape as the input.\n# \n# As an example for a `BCHW` tensor of shape `[16, 64, 32, 32]`, we will first convert it to an `BHWC` tensor of shape `[16, 32, 32, 64]` and then reshape it into `[16384, 64]` and all `16384` vectors of size `64`  will be quantized independently. In otherwords, the channels are used as the space in which to quantize. All other dimensions will be flattened and be seen as different examples to quantize, `16384` in this case.\n\nclass VectorQuantizer(nn.Module):\n    def __init__(self, num_embeddings, embedding_dim, commitment_cost):\n        super(VectorQuantizer, self).__init__()\n        \n        self._embedding_dim = embedding_dim\n        self._num_embeddings = num_embeddings\n        \n        self._embedding = nn.Embedding(self._num_embeddings, self._embedding_dim)\n        self._embedding.weight.data.uniform_(-1/self._num_embeddings, 1/self._num_embeddings)\n        self._commitment_cost = commitment_cost\n\n    def forward(self, inputs):\n        # convert inputs from BCHW -> BHWC\n        inputs = inputs.permute(0, 2, 3, 1).contiguous()\n        input_shape = inputs.shape\n        \n        # Flatten input\n        flat_input = inputs.view(-1, self._embedding_dim)\n        \n        # Calculate distances\n        distances = (torch.sum(flat_input**2, dim=1, keepdim=True) \n                    + torch.sum(self._embedding.weight**2, dim=1)\n                    - 2 * torch.matmul(flat_input, self._embedding.weight.t()))\n            \n        # Encoding\n        encoding_indices = torch.argmin(distances, dim=1).unsqueeze(1)\n        encodings = torch.zeros(encoding_indices.shape[0], self._num_embeddings, device=inputs.device)\n        encodings.scatter_(1, encoding_indices, 1)\n        \n        # Quantize and unflatten\n        quantized = torch.matmul(encodings, self._embedding.weight).view(input_shape)\n        \n        # Loss\n        e_latent_loss = F.mse_loss(quantized.detach(), inputs)\n        q_latent_loss = F.mse_loss(quantized, inputs.detach())\n        loss = q_latent_loss + self._commitment_cost * e_latent_loss\n        \n        quantized = inputs + (quantized - inputs).detach()\n        avg_probs = torch.mean(encodings, dim=0)\n        perplexity = torch.exp(-torch.sum(avg_probs * torch.log(avg_probs + 1e-10)))\n        \n        # convert quantized from BHWC -> BCHW\n        return loss, quantized.permute(0, 3, 1, 2).contiguous(), perplexity, encodings\n\n# We will also implement a slightly modified version  which will use exponential moving averages to update the embedding vectors instead of an auxillary loss. This has the advantage that the embedding updates are independent of the choice of optimizer for the encoder, decoder and other parts of the architecture. For most experiments the EMA version trains faster than the non-EMA version.\n\nclass VectorQuantizerEMA(nn.Module):\n    def __init__(self, num_embeddings, embedding_dim, commitment_cost, decay, epsilon=1e-5):\n        super(VectorQuantizerEMA, self).__init__()\n        \n        self._embedding_dim = embedding_dim\n        self._num_embeddings = num_embeddings\n        \n        self._embedding = nn.Embedding(self._num_embeddings, self._embedding_dim)\n        self._embedding.weight.data.normal_()\n        self._commitment_cost = commitment_cost\n        \n        self.register_buffer('_ema_cluster_size', torch.zeros(num_embeddings))\n        self._ema_w = nn.Parameter(torch.Tensor(num_embeddings, self._embedding_dim))\n        self._ema_w.data.normal_()\n        \n        self._decay = decay\n        self._epsilon = epsilon\n\n    def forward(self, inputs):\n        # convert inputs from BCHW -> BHWC\n        inputs = inputs.permute(0, 2, 3, 1).contiguous()\n        input_shape = inputs.shape\n        \n        # Flatten input\n        flat_input = inputs.view(-1, self._embedding_dim)\n        \n        # Calculate distances\n        distances = (torch.sum(flat_input**2, dim=1, keepdim=True) \n                    + torch.sum(self._embedding.weight**2, dim=1)\n                    - 2 * torch.matmul(flat_input, self._embedding.weight.t()))\n            \n        # Encoding\n        encoding_indices = torch.argmin(distances, dim=1).unsqueeze(1)\n        encodings = torch.zeros(encoding_indices.shape[0], self._num_embeddings, device=inputs.device)\n        encodings.scatter_(1, encoding_indices, 1)\n        \n        # Quantize and unflatten\n        quantized = torch.matmul(encodings, self._embedding.weight).view(input_shape)\n        \n        # Use EMA to update the embedding vectors\n        if self.training:\n            self._ema_cluster_size = self._ema_cluster_size * self._decay +                                      (1 - self._decay) * torch.sum(encodings, 0)\n            \n            # Laplace smoothing of the cluster size\n            n = torch.sum(self._ema_cluster_size.data)\n            self._ema_cluster_size = (\n                (self._ema_cluster_size + self._epsilon)\n                / (n + self._num_embeddings * self._epsilon) * n)\n            \n            dw = torch.matmul(encodings.t(), flat_input)\n            self._ema_w = nn.Parameter(self._ema_w * self._decay + (1 - self._decay) * dw)\n            \n            self._embedding.weight = nn.Parameter(self._ema_w / self._ema_cluster_size.unsqueeze(1))\n        \n        # Loss\n        e_latent_loss = F.mse_loss(quantized.detach(), inputs)\n        loss = self._commitment_cost * e_latent_loss\n        \n        # Straight Through Estimator\n        quantized = inputs + (quantized - inputs).detach()\n        avg_probs = torch.mean(encodings, dim=0)\n        perplexity = torch.exp(-torch.sum(avg_probs * torch.log(avg_probs + 1e-10)))\n        \n        # convert quantized from BHWC -> BCHW\n        return loss, quantized.permute(0, 3, 1, 2).contiguous(), perplexity, encodings\n\n# Encoder & Decoder Architecture\n# \n# The encoder and decoder architecture is based on a ResNet and is implemented below:\n\nclass Residual(nn.Module):\n    def __init__(self, in_channels, num_hiddens, num_residual_hiddens):\n        super(Residual, self).__init__()\n        self._block = nn.Sequential(\n            nn.ReLU(True),\n            nn.Conv2d(in_channels=in_channels,\n                      out_channels=num_residual_hiddens,\n                      kernel_size=3, stride=1, padding=1, bias=False),\n            nn.ReLU(True),\n            nn.Conv2d(in_channels=num_residual_hiddens,\n                      out_channels=num_hiddens,\n                      kernel_size=1, stride=1, bias=False)\n        )\n    \n    def forward(self, x):\n        return x + self._block(x)\n\nclass ResidualStack(nn.Module):\n    def __init__(self, in_channels, num_hiddens, num_residual_layers, num_residual_hiddens):\n        super(ResidualStack, self).__init__()\n        self._num_residual_layers = num_residual_layers\n        self._layers = nn.ModuleList([Residual(in_channels, num_hiddens, num_residual_hiddens)\n                             for _ in range(self._num_residual_layers)])\n\n    def forward(self, x):\n        for i in range(self._num_residual_layers):\n            x = self._layers[i](x)\n        return F.relu(x)\n\nclass Encoder(nn.Module):\n    def __init__(self, in_channels, num_hiddens, num_residual_layers, num_residual_hiddens):\n        super(Encoder, self).__init__()\n\n        self._conv_1 = nn.Conv2d(\n            in_channels=in_channels,\n            out_channels=num_hiddens//2,\n            kernel_size=4,\n            stride=2, padding=1\n        )\n        self._conv_2 = nn.Conv2d(\n            in_channels=num_hiddens//2,\n            out_channels=num_hiddens,\n            kernel_size=4,\n            stride=2, padding=1\n        )\n        self._conv_3 = nn.Conv2d(\n            in_channels=num_hiddens,\n            out_channels=num_hiddens,\n            kernel_size=3,\n            stride=1, padding=1\n        )\n        self._residual_stack = ResidualStack(\n            in_channels=num_hiddens,\n            num_hiddens=num_hiddens,\n            num_residual_layers=num_residual_layers,\n            num_residual_hiddens=num_residual_hiddens\n        )\n\n    def forward(self, inputs):\n        x = self._conv_1(inputs)\n        x = F.relu(x)\n        \n        x = self._conv_2(x)\n        x = F.relu(x)\n        \n        x = self._conv_3(x)\n        return self._residual_stack(x)\n\nclass Decoder(nn.Module):\n    def __init__(self, in_channels, num_hiddens, num_residual_layers, num_residual_hiddens):\n        super(Decoder, self).__init__()\n        \n        self._conv_1 = nn.Conv2d(\n            in_channels=in_channels,\n            out_channels=num_hiddens,\n            kernel_size=3, \n            stride=1, padding=1\n        )\n        \n        self._residual_stack = ResidualStack(\n            in_channels=num_hiddens,\n            num_hiddens=num_hiddens,\n            num_residual_layers=num_residual_layers,\n            num_residual_hiddens=num_residual_hiddens\n        )\n        \n        self._conv_trans_1 = nn.ConvTranspose2d(\n            in_channels=num_hiddens, \n            out_channels=num_hiddens//2,\n            kernel_size=4, \n            stride=2, padding=1\n        )\n        \n        self._conv_trans_2 = nn.ConvTranspose2d(\n            in_channels=num_hiddens//2, \n            out_channels=3,\n            kernel_size=4, \n            stride=2, padding=1\n        )\n\n    def forward(self, inputs):\n        x = self._conv_1(inputs)\n        \n        x = self._residual_stack(x)\n        \n        x = self._conv_trans_1(x)\n        x = F.relu(x)\n        \n        return self._conv_trans_2(x)\n\n\n# Model & Optimizer\nclass Model(nn.Module):\n    def __init__(self, num_hiddens, num_residual_layers, num_residual_hiddens, \n                 num_embeddings, embedding_dim, commitment_cost, decay=0):\n        super(Model, self).__init__()\n        \n        self._encoder = Encoder(\n            3, num_hiddens,\n            num_residual_layers, \n            num_residual_hiddens\n        )\n        self._pre_vq_conv = nn.Conv2d(\n            in_channels=num_hiddens, \n            out_channels=embedding_dim,\n            kernel_size=1, \n            stride=1\n        )\n        if decay > 0.0:\n            self._vq_vae = VectorQuantizerEMA(\n                num_embeddings, embedding_dim, \n                commitment_cost, decay\n            )\n        else:\n            self._vq_vae = VectorQuantizer(\n                num_embeddings, embedding_dim,\n                commitment_cost\n            )\n        self._decoder = Decoder(\n            embedding_dim,\n            num_hiddens, \n            num_residual_layers, \n            num_residual_hiddens\n        )\n\n    def forward(self, x):\n        z = self._encoder(x)\n        z = self._pre_vq_conv(z)\n        loss, quantized, perplexity, _ = self._vq_vae(z)\n        x_recon = self._decoder(quantized)\n        return loss, x_recon, perplexity\n\nmodel = Model(\n    num_hiddens, num_residual_layers, num_residual_hiddens,\n    num_embeddings, embedding_dim, \n    commitment_cost, decay\n).to(device)\n\nload_model_path = saved_models_path.format(epoch=args.epoch_start)\nif os.path.exists(load_model_path):\n    print(\"Loading {}\".format(load_model_path))\n    load_dict = torch.load(load_model_path)\n    model.load_state_dict(load_dict['model_state_dict'])\n    print(load_dict.keys())\nelse:\n    print(\"Could not read {}; no data was loaded.\".format(load_model_path))\n\noptimizer = optim.Adam(model.parameters(), lr=learning_rate, amsgrad=False)\n\ndef save_model(model, epoch):\n    save_dict = {\n        'model_state_dict': model.state_dict(),\n        'epoch': epoch,\n        'args': repr(args),\n    }\n    torch.save(save_dict, saved_models_path.format(epoch=epoch))\n\n    \n# Show reconstructions\ndef validate():\n    global validation_data_loader_iterator\n    model.eval()\n\n    # (valid_originals, _) = next(iter(validation_data_loader))\n    while True:\n        try:\n            data = next(validation_data_loader_iterator)\n            break\n        except StopIteration:\n            validation_data_loader_iterator = iter(validation_data_loader)\n    valid_originals = data['image_src']\n    valid_originals_targets = data['image_trg']\n    valid_originals = valid_originals.to(device)\n    vq_output_eval = model._pre_vq_conv(model._encoder(valid_originals))\n    _, valid_quantize, _, _ = model._vq_vae(vq_output_eval)\n    valid_reconstructions = model._decoder(valid_quantize)\n\n    save_image(\n        valid_reconstructions.cpu().data+0.5,\n        fp=saved_results_path.format(epoch=epoch, name='reconstruction.png'),\n        nrow=8,\n        padding=2,\n        normalize=False,\n        range=None,\n        scale_each=False,\n        pad_value=0,\n        format=\"png\"\n    )\n    save_image(\n        valid_originals.cpu()+0.5,\n        fp=saved_results_path.format(epoch=epoch, name='originals.png'),\n        nrow=8,\n        padding=2,\n        normalize=False,\n        range=None,\n        scale_each=False,\n        pad_value=0,\n        format=\"png\"\n    )\n    save_image(\n        valid_originals_targets.cpu()+0.5,\n        fp=saved_results_path.format(epoch=epoch, name='targets.png'),\n        nrow=8,\n        padding=2,\n        normalize=False,\n        range=None,\n        scale_each=False,\n        pad_value=0,\n        format=\"png\"\n    )\n    model.train()\n\n    \ndef convert_size(size_bytes):\n   if size_bytes == 0:\n       return \"0B\"\n   size_name = (\"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\")\n   i = int(math.floor(math.log(size_bytes, 1024)))\n   p = math.pow(1024, i)\n   s = round(size_bytes / p, 2)\n   return \"%s %s\" % (s, size_name[i])\n\ndef device_memory_info(device_number=0):\n    t = torch.cuda.get_device_properties(device_number).total_memory\n    c = torch.cuda.memory_cached(device_number)\n    a = torch.cuda.memory_allocated(device_number)\n    f = c-a  # free inside cache\n    return {\n        'total': t,\n        'cached': c,\n        'allocated': a,\n        'free': f,\n    }\n\ndef print_device_memory_info():\n    info = device_memory_info()\n    print(\n        \"Total: {}, Cached: {}, Allocated: {}, Free: {}\".format(\n            convert_size(info['total']),\n            convert_size(info['cached']),\n            convert_size(info['allocated']),\n            convert_size(info['free']),\n        )\n    )\n\n\nclass Timer(object):\n    def __init__(self):\n        self.time_instantiated = time.time()\n        self.time_last = None\n        self.kwargs_last = None\n    \n    def start(self, **kwargs):\n        self.kwargs_last = kwargs\n        self.time_last = time.time()\n        return {\n            'span': 0,\n            'kwargs': kwargs,\n        }\n        \n    def lap(self, **kwargs):\n        time_now = time.time()\n        span = time_now - self.time_last\n        kwargs = self.kwargs_last\n        self.time_last = time_now\n        self.kwargs_last = kwargs\n        result = kwargs\n        result['span'] = span\n        return result\n\n\n# Train\n\nprint_device_memory_info()\n\nprint(\"Initializing process group...\")\ndist.init_process_group(\n    backend=args.backend,\n    init_method=args.init_method,\n    rank=args.rank,\n    world_size=args.world_size\n)\n\nprint(\"Trainig starts!\")\nmodel.train()\ntrain_res_recon_error = []\ntrain_res_perplexity = []\n\ntimer = Timer()\ntimer.start(iterations=args.epoch_start)\n\nfor epoch in xrange(args.epoch_start, args.epoch_start+args.num_epochs+1):\n    try:\n        data = next(training_data_loader_iterator)\n    except StopIteration:\n        training_data_loader_iterator = iter(training_data_loader)\n        data = next(training_data_loader_iterator)\n    image_src = data['image_src']\n    image_trg = data['image_trg']\n    image_src = data['image_src'].to(device)\n    image_trg = data['image_trg'].to(device)\n    optimizer.zero_grad()\n\n    vq_loss, data_recon, perplexity = model(image_src)\n    recon_error = F.mse_loss(data_recon, image_trg)\n    loss = recon_error + vq_loss\n    loss = loss / float(len(data['image_src']))\n    loss.backward()\n    optimizer.step()\n    \n    train_res_recon_error.append(recon_error.item())\n    train_res_perplexity.append(perplexity.item())\n\n    for param in model.parameters():\n        if param.grad is not None:\n            dist.all_reduce(param.grad.data, op=torch.distributed.ReduceOp.SUM)\n            param.grad.data /= float(args.world_size)\n\n    if ((epoch % 100 == 0) or (epoch==args.epoch_start+args.num_epochs)) and (epoch != args.epoch_start):\n        timer_info = timer.lap(iterations=epoch)\n        fract = len(image_trg) * (epoch - timer_info['iterations']) / timer_info['span']\n        \n        # from IPython.display import clear_output\n        # clear_output(wait=True)\n        print(\n            '{iterations:d} iterations, {fract:f}/s'.format(\n                iterations=epoch,\n                fract=fract\n            )\n        )\n        print('recon_error: %.3f' % np.mean(train_res_recon_error[-100:]))\n        print('perplexity: %.3f' % np.mean(train_res_perplexity[-100:]))\n        save_model(model, epoch)\n        validate()\n        \n        print_device_memory_info()\n        timer.start(iterations=epoch)\n\nprint(\"Done.\")\n\n\n# # Plot Loss\n# train_res_recon_error_smooth = savgol_filter(train_res_recon_error, 201, 7)\n# train_res_perplexity_smooth = savgol_filter(train_res_perplexity, 201, 7)\n# \n# f = plt.figure(figsize=(16,8))\n# ax = f.add_subplot(1,2,1)\n# ax.plot(train_res_recon_error_smooth)\n# ax.set_yscale('log')\n# ax.set_title('Smoothed NMSE.')\n# ax.set_xlabel('iteration')\n# \n# ax = f.add_subplot(1,2,2)\n# ax.plot(train_res_perplexity_smooth)\n# ax.set_title('Smoothed Average codebook usage (perplexity).')\n# ax.set_xlabel('iteration')\n\n\n# def show(img):\n#     npimg = img.numpy()\n#     fig = plt.imshow(np.transpose(npimg, (1,2,0)), interpolation='nearest')\n#     fig.axes.get_xaxis().set_visible(False)\n#     fig.axes.get_yaxis().set_visible(False)\n\n# show(make_grid(valid_reconstructions.cpu().data+0.5, range=(0.0, 1.0), scale_each=True))\n# show(make_grid(valid_originals.cpu()+0.5))\n\n# # View Embedding\n# proj = umap.UMAP(n_neighbors=3,\n#                  min_dist=0.1,\n#                  metric='cosine').fit_transform(model._vq_vae._embedding.weight.data.cpu())\n# \n# plt.scatter(proj[:,0], proj[:,1], alpha=0.3)\n# \n\n# python vq-vae.py --rank 0 --world_size 2 --epoch_start 0 --num_epochs 15000 --init_method 'tcp://192.168.1.154:23456'\n# python vq-vae.py --rank 1 --world_size 2 --epoch_start 0 --num_epochs 15000 --init_method 'tcp://192.168.1.154:23456'\n", "meta": {"hexsha": "cf5c4d71e3ca335d66c4617935cbd0d2b86cacb5", "size": 27251, "ext": "py", "lang": "Python", "max_stars_repo_path": "vq-vae.py", "max_stars_repo_name": "gogobd/pytorch-vq-vae", "max_stars_repo_head_hexsha": "cf51d3319c26ebb9ba43134f2c811eaa7a5ad92a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vq-vae.py", "max_issues_repo_name": "gogobd/pytorch-vq-vae", "max_issues_repo_head_hexsha": "cf51d3319c26ebb9ba43134f2c811eaa7a5ad92a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vq-vae.py", "max_forks_repo_name": "gogobd/pytorch-vq-vae", "max_forks_repo_head_hexsha": "cf51d3319c26ebb9ba43134f2c811eaa7a5ad92a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4803337306, "max_line_length": 427, "alphanum_fraction": 0.6310227148, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.27202454519235225, "lm_q1q2_score": 0.16019229796583914}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"Module which provides classes to perform PSF Photometry\"\"\"\n\nimport numpy as np\nimport warnings\n\nfrom astropy.modeling.fitting import LevMarLSQFitter\nfrom astropy.nddata.utils import overlap_slices\nfrom astropy.stats import gaussian_sigma_to_fwhm, SigmaClip\nfrom astropy.table import Table, Column, vstack, hstack\nfrom astropy.utils.exceptions import AstropyUserWarning\n\nfrom .groupstars import DAOGroup\nfrom .utils import (get_grouped_psf_model, subtract_psf,\n                    _extract_psf_fitting_names)\nfrom ..aperture import CircularAperture, aperture_photometry\nfrom ..background import MMMBackground\nfrom ..detection import DAOStarFinder\n\n\n__all__ = ['BasicPSFPhotometry', 'IterativelySubtractedPSFPhotometry',\n           'DAOPhotPSFPhotometry']\n\n\nclass BasicPSFPhotometry:\n    \"\"\"\n    This class implements a PSF photometry algorithm that can find\n    sources in an image, group overlapping sources into a single model,\n    fit the model to the sources, and subtracting the models from the\n    image. This is roughly equivalent to the DAOPHOT routines FIND,\n    GROUP, NSTAR, and SUBTRACT.  This implementation allows a flexible\n    and customizable interface to perform photometry. For instance, one\n    is able to use different implementations for grouping and finding\n    sources by using ``group_maker`` and ``finder`` respectivelly. In\n    addition, sky background estimation is performed by\n    ``bkg_estimator``.\n\n    Parameters\n    ----------\n    group_maker : callable or `~photutils.psf.GroupStarsBase`\n        ``group_maker`` should be able to decide whether a given star\n        overlaps with any other and label them as beloging to the same\n        group.  ``group_maker`` receives as input an\n        `~astropy.table.Table` object with columns named as ``id``,\n        ``x_0``, ``y_0``, in which ``x_0`` and ``y_0`` have the same\n        meaning of ``xcentroid`` and ``ycentroid``.  This callable must\n        return an `~astropy.table.Table` with columns ``id``, ``x_0``,\n        ``y_0``, and ``group_id``. The column ``group_id`` should cotain\n        integers starting from ``1`` that indicate which group a given\n        source belongs to. See, e.g., `~photutils.psf.DAOGroup`.\n    bkg_estimator : callable, instance of any `~photutils.BackgroundBase` subclass, or None\n        ``bkg_estimator`` should be able to compute either a scalar\n        background or a 2D background of a given 2D image. See, e.g.,\n        `~photutils.background.MedianBackground`.  If None, no\n        background subtraction is performed.\n    psf_model : `astropy.modeling.Fittable2DModel` instance\n        PSF or PRF model to fit the data. Could be one of the models in\n        this package like `~photutils.psf.sandbox.DiscretePRF`,\n        `~photutils.psf.IntegratedGaussianPRF`, or any other suitable 2D\n        model.  This object needs to identify three parameters (position\n        of center in x and y coordinates and the flux) in order to set\n        them to suitable starting values for each fit. The names of\n        these parameters should be given as ``x_0``, ``y_0`` and\n        ``flux``.  `~photutils.psf.prepare_psf_model` can be used to\n        prepare any 2D model to match this assumption.\n    fitshape : int or length-2 array-like\n        Rectangular shape around the center of a star which will be used\n        to collect the data to do the fitting. Can be an integer to be\n        the same along both axes. E.g., 5 is the same as (5, 5), which\n        means to fit only at the following relative pixel positions:\n        [-2, -1, 0, 1, 2].  Each element of ``fitshape`` must be an odd\n        number.\n    finder : callable or instance of any `~photutils.detection.StarFinderBase` subclasses or None\n        ``finder`` should be able to identify stars, i.e. compute a\n        rough estimate of the centroids, in a given 2D image.\n        ``finder`` receives as input a 2D image and returns an\n        `~astropy.table.Table` object which contains columns with names:\n        ``id``, ``xcentroid``, ``ycentroid``, and ``flux``. In which\n        ``id`` is an integer-valued column starting from ``1``,\n        ``xcentroid`` and ``ycentroid`` are center position estimates of\n        the sources and ``flux`` contains flux estimates of the sources.\n        See, e.g., `~photutils.detection.DAOStarFinder`.  If ``finder``\n        is ``None``, initial guesses for positions of objects must be\n        provided.\n    fitter : `~astropy.modeling.fitting.Fitter` instance\n        Fitter object used to compute the optimized centroid positions\n        and/or flux of the identified sources. See\n        `~astropy.modeling.fitting` for more details on fitters.\n    aperture_radius : float or None\n        The radius (in units of pixels) used to compute initial\n        estimates for the fluxes of sources. If ``None``, one FWHM will\n        be used if it can be determined from the ``psf_model``.\n\n    Notes\n    -----\n    Note that an ambiguity arises whenever ``finder`` and\n    ``init_guesses`` (keyword argument for ``do_photometry``) are both\n    not ``None``. In this case, ``finder`` is ignored and initial\n    guesses are taken from ``init_guesses``. In addition, an warning is\n    raised to remaind the user about this behavior.\n\n    If there are problems with fitting large groups, change the\n    parameters of the grouping algorithm to reduce the number of sources\n    in each group or input a ``star_groups`` table that only includes\n    the groups that are relevant (e.g. manually remove all entries that\n    coincide with artifacts).\n\n    References\n    ----------\n    [1] Stetson, Astronomical Society of the Pacific, Publications,\n        (ISSN 0004-6280), vol. 99, March 1987, p. 191-222.\n        Available at: http://adsabs.harvard.edu/abs/1987PASP...99..191S\n    \"\"\"\n\n    def __init__(self, group_maker, bkg_estimator, psf_model, fitshape,\n                 finder=None, fitter=LevMarLSQFitter(), aperture_radius=None):\n        self.group_maker = group_maker\n        self.bkg_estimator = bkg_estimator\n        self.psf_model = psf_model\n        self.fitter = fitter\n        self.fitshape = fitshape\n        self.finder = finder\n        self.aperture_radius = aperture_radius\n        self._pars_to_set = None\n        self._pars_to_output = None\n        self._residual_image = None\n\n    @property\n    def fitshape(self):\n        return self._fitshape\n\n    @fitshape.setter\n    def fitshape(self, value):\n        value = np.asarray(value)\n\n        # assume a lone value should mean both axes\n        if value.shape == ():\n            value = np.array((value, value))\n\n        if value.size == 2:\n            if np.all(value) > 0:\n                if np.all(value % 2) == 1:\n                    self._fitshape = tuple(value)\n                else:\n                    raise ValueError('fitshape must be odd integer-valued, '\n                                     'received fitshape = {}'.format(value))\n            else:\n                raise ValueError('fitshape must have positive elements, '\n                                 'received fitshape = {}'.format(value))\n        else:\n            raise ValueError('fitshape must have two dimensions, '\n                             'received fitshape = {}'.format(value))\n\n    @property\n    def aperture_radius(self):\n        return self._aperture_radius\n\n    @aperture_radius.setter\n    def aperture_radius(self, value):\n        if isinstance(value, (int, float)) and value > 0:\n            self._aperture_radius = value\n        elif value is None:\n            self._aperture_radius = value\n        else:\n            raise ValueError('aperture_radius must be a real-valued '\n                             'number, received aperture_radius = {}'\n                             .format(value))\n\n    def get_residual_image(self):\n        \"\"\"\n        Returns an image that is the result of the subtraction between\n        the original image and the fitted sources.\n\n        Returns\n        -------\n        residual_image : 2D array-like, `~astropy.io.fits.ImageHDU`, `~astropy.io.fits.HDUList`\n        \"\"\"\n\n        return self._residual_image\n\n    def __call__(self, image, init_guesses=None):\n        \"\"\"\n        Performs PSF photometry. See `do_photometry` for more details\n        including the `__call__` signature.\n        \"\"\"\n\n        return self.do_photometry(image, init_guesses)\n\n    def do_photometry(self, image, init_guesses=None):\n        \"\"\"\n        Perform PSF photometry in ``image``.\n\n        This method assumes that ``psf_model`` has centroids and flux\n        parameters which will be fitted to the data provided in\n        ``image``. A compound model, in fact a sum of ``psf_model``,\n        will be fitted to groups of stars automatically identified by\n        ``group_maker``. Also, ``image`` is not assumed to be background\n        subtracted.  If ``init_guesses`` are not ``None`` then this\n        method uses ``init_guesses`` as initial guesses for the\n        centroids. If the centroid positions are set as ``fixed`` in the\n        PSF model ``psf_model``, then the optimizer will only consider\n        the flux as a variable.\n\n        Parameters\n        ----------\n        image : 2D array-like, `~astropy.io.fits.ImageHDU`, `~astropy.io.fits.HDUList`\n            Image to perform photometry.\n        init_guesses: `~astropy.table.Table`\n            Table which contains the initial guesses (estimates) for the\n            set of parameters. Columns 'x_0' and 'y_0' which represent\n            the positions (in pixel coordinates) for each object must be\n            present.  'flux_0' can also be provided to set initial\n            fluxes.  If 'flux_0' is not provided, aperture photometry is\n            used to estimate initial values for the fluxes. Additional\n            columns of the form '<parametername>_0' will be used to set\n            the initial guess for any parameters of the ``psf_model``\n            model that are not fixed.\n\n        Returns\n        -------\n        output_tab : `~astropy.table.Table` or None\n            Table with the photometry results, i.e., centroids and\n            fluxes estimations and the initial estimates used to start\n            the fitting process. Uncertainties on the fitted parameters\n            are reported as columns called ``<paramname>_unc`` provided\n            that the fitter object contains a dictionary called\n            ``fit_info`` with the key ``param_cov``, which contains the\n            covariance matrix. If ``param_cov`` is not present,\n            uncertanties are not reported.\n        \"\"\"\n\n        if self.bkg_estimator is not None:\n            image = image - self.bkg_estimator(image)\n\n        if self.aperture_radius is None:\n            if hasattr(self.psf_model, 'fwhm'):\n                self.aperture_radius = self.psf_model.fwhm.value\n            elif hasattr(self.psf_model, 'sigma'):\n                self.aperture_radius = (self.psf_model.sigma.value *\n                                        gaussian_sigma_to_fwhm)\n\n        if init_guesses is not None:\n            # make sure the code does not modify user's input\n            init_guesses = init_guesses.copy()\n            if self.aperture_radius is None:\n                if 'flux_0' not in init_guesses.colnames:\n                    raise ValueError('aperture_radius is None and could not '\n                                     'be determined by psf_model. Please, '\n                                     'either provided a value for '\n                                     'aperture_radius or define fwhm/sigma '\n                                     'at psf_model.')\n\n            if self.finder is not None:\n                warnings.warn('Both init_guesses and finder are different '\n                              'than None, which is ambiguous. finder is '\n                              'going to be ignored.', AstropyUserWarning)\n\n            if 'flux_0' not in init_guesses.colnames:\n                apertures = CircularAperture((init_guesses['x_0'],\n                                              init_guesses['y_0']),\n                                             r=self.aperture_radius)\n\n                init_guesses['flux_0'] = aperture_photometry(\n                    image, apertures)['aperture_sum']\n        else:\n            if self.finder is None:\n                raise ValueError('Finder cannot be None if init_guesses are '\n                                 'not given.')\n            sources = self.finder(image)\n            if len(sources) > 0:\n                apertures = CircularAperture((sources['xcentroid'],\n                                              sources['ycentroid']),\n                                             r=self.aperture_radius)\n\n                sources['aperture_flux'] = aperture_photometry(\n                    image, apertures)['aperture_sum']\n\n                init_guesses = Table(names=['x_0', 'y_0', 'flux_0'],\n                                     data=[sources['xcentroid'],\n                                           sources['ycentroid'],\n                                           sources['aperture_flux']])\n\n        self._define_fit_param_names()\n        for p0, param in self._pars_to_set.items():\n            if p0 not in init_guesses.colnames:\n                init_guesses[p0] = (len(init_guesses) *\n                                    [getattr(self.psf_model, param).value])\n\n        star_groups = self.group_maker(init_guesses)\n        output_tab, self._residual_image = self.nstar(image, star_groups)\n\n        star_groups = star_groups.group_by('group_id')\n        output_tab = hstack([star_groups, output_tab])\n\n        return output_tab\n\n    def nstar(self, image, star_groups):\n        \"\"\"\n        Fit, as appropriate, a compound or single model to the given\n        ``star_groups``. Groups are fitted sequentially from the\n        smallest to the biggest. In each iteration, ``image`` is\n        subtracted by the previous fitted group.\n\n        Parameters\n        ----------\n        image : numpy.ndarray\n            Background-subtracted image.\n        star_groups : `~astropy.table.Table`\n            This table must contain the following columns: ``id``,\n            ``group_id``, ``x_0``, ``y_0``, ``flux_0``.  ``x_0`` and\n            ``y_0`` are initial estimates of the centroids and\n            ``flux_0`` is an initial estimate of the flux. Additionally,\n            columns named as ``<param_name>_0`` are required if any\n            other parameter in the psf model is free (i.e., the\n            ``fixed`` attribute of that parameter is ``False``).\n\n        Returns\n        -------\n        result_tab : `~astropy.table.Table`\n            Astropy table that contains photometry results.\n        image : numpy.ndarray\n            Residual image.\n        \"\"\"\n\n        result_tab = Table()\n        for param_tab_name in self._pars_to_output.keys():\n            result_tab.add_column(Column(name=param_tab_name))\n\n        unc_tab = Table()\n        for param, isfixed in self.psf_model.fixed.items():\n            if not isfixed:\n                unc_tab.add_column(Column(name=param + \"_unc\"))\n\n        y, x = np.indices(image.shape)\n\n        star_groups = star_groups.group_by('group_id')\n        for n in range(len(star_groups.groups)):\n            group_psf = get_grouped_psf_model(self.psf_model,\n                                              star_groups.groups[n],\n                                              self._pars_to_set)\n            usepixel = np.zeros_like(image, dtype=np.bool)\n\n            for row in star_groups.groups[n]:\n                usepixel[overlap_slices(large_array_shape=image.shape,\n                                        small_array_shape=self.fitshape,\n                                        position=(row['y_0'], row['x_0']),\n                                        mode='trim')[0]] = True\n\n            fit_model = self.fitter(group_psf, x[usepixel], y[usepixel],\n                                    image[usepixel])\n            param_table = self._model_params2table(fit_model,\n                                                   len(star_groups.groups[n]))\n            result_tab = vstack([result_tab, param_table])\n\n            if 'param_cov' in self.fitter.fit_info.keys():\n                unc_tab = vstack([unc_tab,\n                                  self._get_uncertainties(\n                                      len(star_groups.groups[n]))])\n            try:\n                from astropy.nddata.utils import NoOverlapError\n            except ImportError:\n                raise ImportError(\"astropy 1.1 or greater is required in \"\n                                  \"order to use this class.\")\n            # do not subtract if the fitting did not go well\n            try:\n                image = subtract_psf(image, self.psf_model, param_table,\n                                     subshape=self.fitshape)\n            except NoOverlapError:\n                pass\n\n        if 'param_cov' in self.fitter.fit_info.keys():\n            result_tab = hstack([result_tab, unc_tab])\n\n        return result_tab, image\n\n    def _define_fit_param_names(self):\n        \"\"\"\n        Convenience function to define mappings between the names of the\n        columns in the initial guess table (and the name of the fitted\n        parameters) and the actual name of the parameters in the model.\n\n        This method sets the following parameters on the ``self`` object:\n        * ``pars_to_set`` : Dict which maps the names of the parameters\n          initial guesses to the actual name of the parameter in the\n          model.\n        * ``pars_to_output`` : Dict which maps the names of the fitted\n          parameters to the actual name of the parameter in the model.\n        \"\"\"\n\n        xname, yname, fluxname = _extract_psf_fitting_names(self.psf_model)\n        self._pars_to_set = {'x_0': xname, 'y_0': yname, 'flux_0': fluxname}\n        self._pars_to_output = {'x_fit': xname, 'y_fit': yname,\n                                'flux_fit': fluxname}\n\n        for p, isfixed in self.psf_model.fixed.items():\n            p0 = p + '_0'\n            pfit = p + '_fit'\n            if p not in (xname, yname, fluxname) and not isfixed:\n                self._pars_to_set[p0] = p\n                self._pars_to_output[pfit] = p\n\n    def _get_uncertainties(self, star_group_size):\n        \"\"\"\n        Retrieve uncertainties on fitted parameters from the fitter\n        object.\n\n        Parameters\n        ----------\n        star_group_size : int\n            Number of stars in the given group.\n\n        Returns\n        -------\n        unc_tab : `~astropy.table.Table`\n            Table which contains uncertainties on the fitted parameters.\n            The uncertainties are reported as one standard deviation.\n        \"\"\"\n\n        unc_tab = Table()\n        for param_name in self.psf_model.param_names:\n            if not self.psf_model.fixed[param_name]:\n                unc_tab.add_column(Column(name=param_name + \"_unc\",\n                                          data=np.empty(star_group_size)))\n\n        if 'param_cov' in self.fitter.fit_info.keys():\n            if self.fitter.fit_info['param_cov'] is not None:\n                k = 0\n                n_fit_params = len(unc_tab.colnames)\n                for i in range(star_group_size):\n                    unc_tab[i] = np.sqrt(np.diag(\n                                          self.fitter.fit_info['param_cov'])\n                                         )[k: k + n_fit_params]\n                    k = k + n_fit_params\n        return unc_tab\n\n    def _model_params2table(self, fit_model, star_group_size):\n        \"\"\"\n        Place fitted parameters into an astropy table.\n\n        Parameters\n        ----------\n        fit_model : `astropy.modeling.Fittable2DModel` instance\n            PSF or PRF model to fit the data. Could be one of the models\n            in this package like `~photutils.psf.sandbox.DiscretePRF`,\n            `~photutils.psf.IntegratedGaussianPRF`, or any other\n            suitable 2D model.\n        star_group_size : int\n            Number of stars in the given group.\n\n        Returns\n        -------\n        param_tab : `~astropy.table.Table`\n            Table that contains the fitted parameters.\n        \"\"\"\n\n        param_tab = Table()\n\n        for param_tab_name in self._pars_to_output.keys():\n            param_tab.add_column(Column(name=param_tab_name,\n                                        data=np.empty(star_group_size)))\n\n        if star_group_size > 1:\n            for i in range(star_group_size):\n                for param_tab_name, param_name in self._pars_to_output.items():\n                    param_tab[param_tab_name][i] = getattr(fit_model,\n                                                           param_name +\n                                                           '_' + str(i)).value\n        else:\n            for param_tab_name, param_name in self._pars_to_output.items():\n                param_tab[param_tab_name] = getattr(fit_model, param_name).value\n\n        return param_tab\n\n\nclass IterativelySubtractedPSFPhotometry(BasicPSFPhotometry):\n    \"\"\"\n    This class implements an iterative algorithm to perform point spread\n    function photometry in crowded fields. This consists of applying a\n    loop of find sources, make groups, fit groups, subtract groups, and\n    then repeat until no more stars are detected or a given number of\n    iterations is reached.\n\n    Parameters\n    ----------\n    group_maker : callable or `~photutils.psf.GroupStarsBase`\n        ``group_maker`` should be able to decide whether a given star\n        overlaps with any other and label them as beloging to the same\n        group.  ``group_maker`` receives as input an\n        `~astropy.table.Table` object with columns named as ``id``,\n        ``x_0``, ``y_0``, in which ``x_0`` and ``y_0`` have the same\n        meaning of ``xcentroid`` and ``ycentroid``.  This callable must\n        return an `~astropy.table.Table` with columns ``id``, ``x_0``,\n        ``y_0``, and ``group_id``. The column ``group_id`` should cotain\n        integers starting from ``1`` that indicate which group a given\n        source belongs to. See, e.g., `~photutils.psf.DAOGroup`.\n    bkg_estimator : callable, instance of any `~photutils.BackgroundBase` subclass, or None\n        ``bkg_estimator`` should be able to compute either a scalar\n        background or a 2D background of a given 2D image. See, e.g.,\n        `~photutils.background.MedianBackground`.  If None, no\n        background subtraction is performed.\n    psf_model : `astropy.modeling.Fittable2DModel` instance\n        PSF or PRF model to fit the data. Could be one of the models in\n        this package like `~photutils.psf.sandbox.DiscretePRF`,\n        `~photutils.psf.IntegratedGaussianPRF`, or any other suitable 2D\n        model.  This object needs to identify three parameters (position\n        of center in x and y coordinates and the flux) in order to set\n        them to suitable starting values for each fit. The names of\n        these parameters should be given as ``x_0``, ``y_0`` and\n        ``flux``.  `~photutils.psf.prepare_psf_model` can be used to\n        prepare any 2D model to match this assumption.\n    fitshape : int or length-2 array-like\n        Rectangular shape around the center of a star which will be used\n        to collect the data to do the fitting. Can be an integer to be\n        the same along both axes. E.g., 5 is the same as (5, 5), which\n        means to fit only at the following relative pixel positions:\n        [-2, -1, 0, 1, 2].  Each element of ``fitshape`` must be an odd\n        number.\n    finder : callable or instance of any `~photutils.detection.StarFinderBase` subclasses\n        ``finder`` should be able to identify stars, i.e. compute a\n        rough estimate of the centroids, in a given 2D image.\n        ``finder`` receives as input a 2D image and returns an\n        `~astropy.table.Table` object which contains columns with names:\n        ``id``, ``xcentroid``, ``ycentroid``, and ``flux``. In which\n        ``id`` is an integer-valued column starting from ``1``,\n        ``xcentroid`` and ``ycentroid`` are center position estimates of\n        the sources and ``flux`` contains flux estimates of the sources.\n        See, e.g., `~photutils.detection.DAOStarFinder` or\n        `~photutils.detection.IRAFStarFinder`.\n    fitter : `~astropy.modeling.fitting.Fitter` instance\n        Fitter object used to compute the optimized centroid positions\n        and/or flux of the identified sources. See\n        `~astropy.modeling.fitting` for more details on fitters.\n    aperture_radius : float\n        The radius (in units of pixels) used to compute initial\n        estimates for the fluxes of sources. If ``None``, one FWHM will\n        be used if it can be determined from the ```psf_model``.\n    niters : int or None\n        Number of iterations to perform of the loop FIND, GROUP,\n        SUBTRACT, NSTAR. If None, iterations will proceed until no more\n        stars remain.  Note that in this case it is *possible* that the\n        loop will never end if the PSF has structure that causes\n        subtraction to create new sources infinitely.\n\n    Notes\n    -----\n    If there are problems with fitting large groups, change the\n    parameters of the grouping algorithm to reduce the number of sources\n    in each group or input a ``star_groups`` table that only includes\n    the groups that are relevant (e.g. manually remove all entries that\n    coincide with artifacts).\n\n    References\n    ----------\n    [1] Stetson, Astronomical Society of the Pacific, Publications,\n        (ISSN 0004-6280), vol. 99, March 1987, p. 191-222.\n        Available at: http://adsabs.harvard.edu/abs/1987PASP...99..191S\n    \"\"\"\n\n    def __init__(self, group_maker, bkg_estimator, psf_model, fitshape,\n                 finder, fitter=LevMarLSQFitter(), niters=3,\n                 aperture_radius=None):\n\n        super().__init__(group_maker, bkg_estimator, psf_model, fitshape,\n                         finder, fitter, aperture_radius)\n        self.niters = niters\n\n    @property\n    def niters(self):\n        return self._niters\n\n    @niters.setter\n    def niters(self, value):\n        if value is None:\n            self._niters = None\n        else:\n            try:\n                if value <= 0:\n                    raise ValueError('niters must be positive.')\n                else:\n                    self._niters = int(value)\n            except ValueError:\n                raise ValueError('niters must be None or an integer or '\n                                 'convertable into an integer.')\n\n    @property\n    def finder(self):\n        return self._finder\n\n    @finder.setter\n    def finder(self, value):\n        if value is None:\n            raise ValueError(\"finder cannot be None for \"\n                             \"IterativelySubtractedPSFPhotometry - you may \"\n                             \"want to use BasicPSFPhotometry. Please see the \"\n                             \"Detection section on photutils documentation.\")\n        else:\n            self._finder = value\n\n    def do_photometry(self, image, init_guesses=None):\n        \"\"\"\n        Perform PSF photometry in ``image``.\n\n        This method assumes that ``psf_model`` has centroids and flux\n        parameters which will be fitted to the data provided in\n        ``image``. A compound model, in fact a sum of ``psf_model``,\n        will be fitted to groups of stars automatically identified by\n        ``group_maker``. Also, ``image`` is not assumed to be background\n        subtracted.  If ``init_guesses`` are not ``None`` then this\n        method uses ``init_guesses`` as initial guesses for the\n        centroids. If the centroid positions are set as ``fixed`` in the\n        PSF model ``psf_model``, then the optimizer will only consider\n        the flux as a variable.\n\n        Parameters\n        ----------\n        image : 2D array-like, `~astropy.io.fits.ImageHDU`, `~astropy.io.fits.HDUList`\n            Image to perform photometry.\n        init_guesses: `~astropy.table.Table`\n            Table which contains the initial guesses (estimates) for the\n            set of parameters. Columns 'x_0' and 'y_0' which represent\n            the positions (in pixel coordinates) for each object must be\n            present.  'flux_0' can also be provided to set initial\n            fluxes.  If 'flux_0' is not provided, aperture photometry is\n            used to estimate initial values for the fluxes. Additional\n            columns of the form '<parametername>_0' will be used to set\n            the initial guess for any parameters of the ``psf_model``\n            model that are not fixed.\n\n        Returns\n        -------\n        output_table : `~astropy.table.Table` or None\n            Table with the photometry results, i.e., centroids and\n            fluxes estimations and the initial estimates used to start\n            the fitting process. Uncertainties on the fitted parameters\n            are reported as columns called ``<paramname>_unc`` provided\n            that the fitter object contains a dictionary called\n            ``fit_info`` with the key ``param_cov``, which contains the\n            covariance matrix.\n        \"\"\"\n\n        if init_guesses is not None:\n            table = super().do_photometry(image, init_guesses)\n            table['iter_detected'] = np.ones(table['x_fit'].shape,\n                                             dtype=np.int32)\n\n            # n_start = 2 because it starts in the second iteration\n            # since the first iteration is above\n            output_table = self._do_photometry(init_guesses.colnames,\n                                               n_start=2)\n            output_table = vstack([table, output_table])\n        else:\n            if self.bkg_estimator is not None:\n                self._residual_image = image - self.bkg_estimator(image)\n\n            if self.aperture_radius is None:\n                if hasattr(self.psf_model, 'fwhm'):\n                    self.aperture_radius = self.psf_model.fwhm.value\n                elif hasattr(self.psf_model, 'sigma'):\n                    self.aperture_radius = (self.psf_model.sigma.value *\n                                            gaussian_sigma_to_fwhm)\n\n            output_table = self._do_photometry(['x_0', 'y_0', 'flux_0'])\n        return output_table\n\n    def _do_photometry(self, param_tab, n_start=1):\n        \"\"\"\n        Helper function which performs the iterations of the photometry\n        process.\n\n        Parameters\n        ----------\n        param_names :  list\n            Names of the columns which represent the initial guesses.\n            For example, ['x_0', 'y_0', 'flux_0'], for intial guesses on\n            the center positions and the flux.\n        n_start : int\n            Integer representing the start index of the iteration.  It\n            is 1 if init_guesses are None, and 2 otherwise.\n\n        Returns\n        -------\n        output_table : `~astropy.table.Table` or None\n            Table with the photometry results, i.e., centroids and\n            fluxes estimations and the initial estimates used to start\n            the fitting process.\n        \"\"\"\n\n        output_table = Table()\n        self._define_fit_param_names()\n\n        for (init_parname, fit_parname) in zip(self._pars_to_set.keys(),\n                                               self._pars_to_output.keys()):\n            output_table.add_column(Column(name=init_parname))\n            output_table.add_column(Column(name=fit_parname))\n\n        sources = self.finder(self._residual_image)\n\n        n = n_start\n        while(len(sources) > 0 and\n              (self.niters is None or n <= self.niters)):\n            apertures = CircularAperture((sources['xcentroid'],\n                                          sources['ycentroid']),\n                                         r=self.aperture_radius)\n            sources['aperture_flux'] = aperture_photometry(\n                self._residual_image, apertures)['aperture_sum']\n\n            init_guess_tab = Table(names=['id', 'x_0', 'y_0', 'flux_0'],\n                                   data=[sources['id'], sources['xcentroid'],\n                                         sources['ycentroid'],\n                                         sources['aperture_flux']])\n\n            for param_tab_name, param_name in self._pars_to_set.items():\n                if param_tab_name not in (['x_0', 'y_0', 'flux_0']):\n                    init_guess_tab.add_column(\n                        Column(name=param_tab_name,\n                               data=(getattr(self.psf_model,\n                                             param_name) *\n                                     np.ones(len(sources)))))\n\n            star_groups = self.group_maker(init_guess_tab)\n            table, self._residual_image = super().nstar(\n                self._residual_image, star_groups)\n\n            star_groups = star_groups.group_by('group_id')\n            table = hstack([star_groups, table])\n\n            table['iter_detected'] = n*np.ones(table['x_fit'].shape,\n                                               dtype=np.int32)\n\n            output_table = vstack([output_table, table])\n\n            # do not warn if no sources are found beyond the first iteration\n            with warnings.catch_warnings():\n                warnings.simplefilter('ignore', AstropyUserWarning)\n                sources = self.finder(self._residual_image)\n\n            n += 1\n\n        return output_table\n\n\nclass DAOPhotPSFPhotometry(IterativelySubtractedPSFPhotometry):\n    \"\"\"\n    This class implements  an iterative algorithm based on the DAOPHOT\n    algorithm presented by Stetson (1987) to perform point spread\n    function photometry in crowded fields. This consists of applying a\n    loop of find sources, make groups, fit groups, subtract groups, and\n    then repeat until no more stars are detected or a given number of\n    iterations is reached.\n\n    Basically, this classes uses\n    `~photutils.psf.IterativelySubtractedPSFPhotometry`, but with\n    grouping, finding, and background estimation routines defined a\n    priori. More precisely, this class uses `~photutils.psf.DAOGroup`\n    for grouping, `~photutils.detection.DAOStarFinder` for finding\n    sources, and `~photutils.background.MMMBackground` for background\n    estimation. Those classes are based on GROUP, FIND, and SKY routines\n    used in DAOPHOT, respectively.\n\n    The parameter ``crit_separation`` is associated with\n    `~photutils.psf.DAOGroup`.  ``sigma_clip`` is associated with\n    `~photutils.background.MMMBackground`.  ``threshold`` and ``fwhm``\n    are associated with `~photutils.detection.DAOStarFinder`.\n    Parameters from ``ratio`` to ``roundhi`` are also associated with\n    `~photutils.detection.DAOStarFinder`.\n\n    Parameters\n    ----------\n    crit_separation : float or int\n        Distance, in units of pixels, such that any two stars separated\n        by less than this distance will be placed in the same group.\n    threshold : float\n        The absolute image value above which to select sources.\n    fwhm : float\n        The full-width half-maximum (FWHM) of the major axis of the\n        Gaussian kernel in units of pixels.\n    psf_model : `astropy.modeling.Fittable2DModel` instance\n        PSF or PRF model to fit the data. Could be one of the models in\n        this package like `~photutils.psf.sandbox.DiscretePRF`,\n        `~photutils.psf.IntegratedGaussianPRF`, or any other suitable 2D\n        model.  This object needs to identify three parameters (position\n        of center in x and y coordinates and the flux) in order to set\n        them to suitable starting values for each fit. The names of\n        these parameters should be given as ``x_0``, ``y_0`` and\n        ``flux``.  `~photutils.psf.prepare_psf_model` can be used to\n        prepare any 2D model to match this assumption.\n    fitshape : int or length-2 array-like\n        Rectangular shape around the center of a star which will be used\n        to collect the data to do the fitting. Can be an integer to be\n        the same along both axes. E.g., 5 is the same as (5, 5), which\n        means to fit only at the following relative pixel positions:\n        [-2, -1, 0, 1, 2].  Each element of ``fitshape`` must be an odd\n        number.\n    sigma : float, optional\n        Number of standard deviations used to perform sigma clip with a\n        `astropy.stats.SigmaClip` object.\n    ratio : float, optional\n        The ratio of the minor to major axis standard deviations of the\n        Gaussian kernel.  ``ratio`` must be strictly positive and less\n        than or equal to 1.0.  The default is 1.0 (i.e., a circular\n        Gaussian kernel).\n    theta : float, optional\n        The position angle (in degrees) of the major axis of the\n        Gaussian kernel measured counter-clockwise from the positive x\n        axis.\n    sigma_radius : float, optional\n        The truncation radius of the Gaussian kernel in units of sigma\n        (standard deviation) [``1 sigma = FWHM /\n        (2.0*sqrt(2.0*log(2.0)))``].\n    sharplo : float, optional\n        The lower bound on sharpness for object detection.\n    sharphi : float, optional\n        The upper bound on sharpness for object detection.\n    roundlo : float, optional\n        The lower bound on roundess for object detection.\n    roundhi : float, optional\n        The upper bound on roundess for object detection.\n    fitter : `~astropy.modeling.fitting.Fitter` instance\n        Fitter object used to compute the optimized centroid positions\n        and/or flux of the identified sources. See\n        `~astropy.modeling.fitting` for more details on fitters.\n    niters : int or None\n        Number of iterations to perform of the loop FIND, GROUP,\n        SUBTRACT, NSTAR. If None, iterations will proceed until no more\n        stars remain.  Note that in this case it is *possible* that the\n        loop will never end if the PSF has structure that causes\n        subtraction to create new sources infinitely.\n    aperture_radius : float\n        The radius (in units of pixels) used to compute initial\n        estimates for the fluxes of sources. If ``None``, one FWHM will\n        be used if it can be determined from the ```psf_model``.\n\n    Notes\n    -----\n    If there are problems with fitting large groups, change the\n    parameters of the grouping algorithm to reduce the number of sources\n    in each group or input a ``star_groups`` table that only includes\n    the groups that are relevant (e.g. manually remove all entries that\n    coincide with artifacts).\n\n    References\n    ----------\n    [1] Stetson, Astronomical Society of the Pacific, Publications,\n        (ISSN 0004-6280), vol. 99, March 1987, p. 191-222.\n        Available at: http://adsabs.harvard.edu/abs/1987PASP...99..191S\n    \"\"\"\n\n    def __init__(self, crit_separation, threshold, fwhm, psf_model, fitshape,\n                 sigma=3., ratio=1.0, theta=0.0, sigma_radius=1.5,\n                 sharplo=0.2, sharphi=1.0, roundlo=-1.0, roundhi=1.0,\n                 fitter=LevMarLSQFitter(),\n                 niters=3, aperture_radius=None):\n\n        self.crit_separation = crit_separation\n        self.threshold = threshold\n        self.fwhm = fwhm\n        self.sigma = sigma\n        self.ratio = ratio\n        self.theta = theta\n        self.sigma_radius = sigma_radius\n        self.sharplo = sharplo\n        self.sharphi = sharphi\n        self.roundlo = roundlo\n        self.roundhi = roundhi\n\n        group_maker = DAOGroup(crit_separation=self.crit_separation)\n        bkg_estimator = MMMBackground(sigma_clip=SigmaClip(sigma=self.sigma))\n        finder = DAOStarFinder(threshold=self.threshold, fwhm=self.fwhm,\n                               ratio=self.ratio, theta=self.theta,\n                               sigma_radius=self.sigma_radius,\n                               sharplo=self.sharplo, sharphi=self.sharphi,\n                               roundlo=self.roundlo, roundhi=self.roundhi)\n\n        super().__init__(group_maker=group_maker, bkg_estimator=bkg_estimator,\n                         psf_model=psf_model, fitshape=fitshape,\n                         finder=finder, fitter=fitter, niters=niters,\n                         aperture_radius=aperture_radius)\n", "meta": {"hexsha": "0ab3758a8018bfcf9cabc0be543f00bea80497c3", "size": 40310, "ext": "py", "lang": "Python", "max_stars_repo_path": "photutils/psf/photometry.py", "max_stars_repo_name": "nden/photutils", "max_stars_repo_head_hexsha": "87879b2464ccfcd160f6a0c53ea4c0869a6e1cc2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "photutils/psf/photometry.py", "max_issues_repo_name": "nden/photutils", "max_issues_repo_head_hexsha": "87879b2464ccfcd160f6a0c53ea4c0869a6e1cc2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "photutils/psf/photometry.py", "max_forks_repo_name": "nden/photutils", "max_forks_repo_head_hexsha": "87879b2464ccfcd160f6a0c53ea4c0869a6e1cc2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.9111617312, "max_line_length": 97, "alphanum_fraction": 0.6076903994, "include": true, "reason": "import numpy,from astropy", "num_tokens": 8978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.28457601028405616, "lm_q1q2_score": 0.15998194152259246}}
{"text": "#!/usr/bin/env python\n#\n# Author: Qiming Sun <osirpt.sun@gmail.com>\n#\n\nimport time\nimport ctypes\nimport tempfile\nimport numpy\nimport h5py\nfrom pyscf import lib\nfrom functools import reduce\nfrom pyscf.lib import logger\nfrom pyscf import gto\nfrom pyscf import ao2mo\nfrom pyscf.cc import ccsd\nfrom pyscf.cc import _ccsd\nfrom pyscf.cc import ccsd_rdm\nfrom pyscf.scf import rhf_grad\nfrom pyscf.scf import cphf\n\nBLKSIZE = 192\n\n\ndef IX_intermediates(mycc, t1, t2, l1, l2, eris=None, d1=None, d2=None):\n    if eris is None:\n# Note eris are in Chemist's notation\n        eris = ccsd._ERIS(mycc)\n    if d1 is None:\n        d1 = ccsd_rdm.gamma1_intermediates(mycc, t1, t2, l1, l2)\n    doo, dov, dvo, dvv = d1\n    if d2 is None:\n        _d2tmpfile = tempfile.NamedTemporaryFile(dir=lib.param.TMPDIR)\n        fd2intermediate = h5py.File(_d2tmpfile.name, 'w')\n        ccsd_rdm.gamma2_outcore(mycc, t1, t2, l1, l2, fd2intermediate)\n        dovov = fd2intermediate['dovov']\n        dvvvv = fd2intermediate['dvvvv']\n        doooo = fd2intermediate['doooo']\n        doovv = fd2intermediate['doovv']\n        dovvo = fd2intermediate['dovvo']\n        dovvv = fd2intermediate['dovvv']\n        dooov = fd2intermediate['dooov']\n    else:\n        dovov, dvvvv, doooo, doovv, dovvo, dvvov, dovvv, dooov = d2\n\n    log = logger.Logger(mycc.stdout, mycc.verbose)\n    nocc, nvir = t1.shape\n    nov = nocc * nvir\n    nvir_pair = nvir * (nvir+1) //2\n    _tmpfile = tempfile.NamedTemporaryFile(dir=lib.param.TMPDIR)\n    fswap = h5py.File(_tmpfile.name, 'w')\n    fswap.create_group('e_vvov')\n    fswap.create_group('c_vvov')\n\n# Note Ioo, Ivv are not hermitian\n    Ioo = numpy.zeros((nocc,nocc))\n    Ivv = numpy.zeros((nvir,nvir))\n    Ivo = numpy.zeros((nvir,nocc))\n    Xvo = numpy.zeros((nvir,nocc))\n\n    eris_oooo = _cp(eris.oooo)\n    eris_ooov = _cp(eris.ooov)\n    d_oooo = _cp(doooo)\n    d_oooo = _cp(d_oooo + d_oooo.transpose(1,0,2,3))\n    #:Ioo += numpy.einsum('jmlk,imlk->ij', d_oooo, eris_oooo) * 2\n    Ioo += lib.dot(eris_oooo.reshape(nocc,-1), d_oooo.reshape(nocc,-1).T, 2)\n    d_oooo = _cp(d_oooo.transpose(0,2,3,1))\n    #:Xvo += numpy.einsum('iljk,ljka->ai', d_oooo, eris_ooov) * 2\n    Xvo += lib.dot(eris_ooov.reshape(-1,nvir).T, d_oooo.reshape(nocc,-1).T, 2)\n    Xvo +=(numpy.einsum('kj,kjia->ai', doo, eris_ooov) * 4\n         - numpy.einsum('kj,ikja->ai', doo+doo.T, eris_ooov))\n    eris_oooo = eris_ooov = d_oooo = None\n\n    d_ovov = numpy.empty((nocc,nvir,nocc,nvir))\n    blksize = 8\n    for p0, p1 in prange(0, nocc, blksize):\n        d_ovov[p0:p1] = _cp(dovov[p0:p1])\n        d_ovvo = _cp(dovvo[p0:p1])\n        for i in range(p0,p1):\n            d_ovov[i] += d_ovvo[i-p0].transpose(0,2,1)\n    d_ovvo = None\n    d_ovov = lib.transpose_sum(d_ovov.reshape(nov,nov)).reshape(nocc,nvir,nocc,nvir)\n    #:Ivo += numpy.einsum('jbka,jbki->ai', d_ovov, eris.ovoo)\n    Ivo += lib.dot(d_ovov.reshape(-1,nvir).T, _cp(eris.ovoo).reshape(-1,nocc))\n    eris_ovov = _cp(eris.ovov)\n    #:Ioo += numpy.einsum('jakb,iakb->ij', d_ovov, eris.ovov)\n    #:Ivv += numpy.einsum('jcib,jcia->ab', d_ovov, eris.ovov)\n    Ioo += lib.dot(eris_ovov.reshape(nocc,-1), d_ovov.reshape(nocc,-1).T)\n    Ivv += lib.dot(eris_ovov.reshape(-1,nvir).T, d_ovov.reshape(-1,nvir))\n    eris_ovov = None\n    fswap['dovvo'] = d_ovov.transpose(0,1,3,2)\n    d_ovov = None\n\n    max_memory = mycc.max_memory - lib.current_memory()[0]\n    unit = max(nvir**3*2.5, nvir**3*2+nocc*nvir**2)\n    blksize = max(ccsd.BLKMIN, int(max_memory*1e6/8/unit))\n    iobuflen = int(256e6/8/(blksize*nvir))\n    log.debug1('IX_intermediates pass 1: block size = %d, nocc = %d in %d blocks',\n               blksize, nocc, int((nocc+blksize-1)/blksize))\n    for istep, (p0, p1) in enumerate(prange(0, nocc, blksize)):\n        d_ooov = _cp(dooov[p0:p1])\n        eris_oooo = _cp(eris.oooo[p0:p1])\n        eris_ooov = _cp(eris.ooov[p0:p1])\n        #:Ivv += numpy.einsum('ijkb,ijka->ab', d_ooov, eris_ooov)\n        #:Ivo += numpy.einsum('jlka,jlki->ai', d_ooov, eris_oooo)\n        Ivv += lib.dot(eris_ooov.reshape(-1,nvir).T, d_ooov.reshape(-1,nvir))\n        Ivo += lib.dot(d_ooov.reshape(-1,nvir).T, eris_oooo.reshape(-1,nocc))\n        #:Ioo += numpy.einsum('klja,klia->ij', d_ooov, eris_ooov)\n        #:Xvo += numpy.einsum('kjib,kjba->ai', d_ooov, eris.oovv)\n        eris_oovv = _cp(eris.oovv[p0:p1])\n        tmp = _cp(d_ooov.transpose(0,1,3,2).reshape(-1,nocc))\n        Ioo += lib.dot(_cp(eris_ooov.transpose(0,1,3,2).reshape(-1,nocc)).T, tmp)\n        Xvo += lib.dot(eris_oovv.reshape(-1,nvir).T, tmp)\n        eris_oooo = tmp = None\n\n        d_ooov = d_ooov + dooov[:,p0:p1].transpose(1,0,2,3)\n        eris_ovov = _cp(eris.ovov[p0:p1])\n        #:Ioo += numpy.einsum('ljka,lika->ij', d_ooov, eris_ooov)\n        #:Xvo += numpy.einsum('jikb,jakb->ai', d_ooov, eris_ovov)\n        for i in range(p1-p0):\n            lib.dot(eris_ooov[i].reshape(nocc,-1),\n                    d_ooov[i].reshape(nocc,-1).T, 1, Ioo, 1)\n            lib.dot(eris_ovov[i].reshape(nvir,-1),\n                    d_ooov[i].reshape(nocc,-1).T, 1, Xvo, 1)\n        d_ooov = None\n\n        #:Ioo += numpy.einsum('kjba,kiba->ij', d_oovv, eris.oovv)\n        #:Ivv += numpy.einsum('ijcb,ijca->ab', d_oovv, eris.oovv)\n        #:Ivo += numpy.einsum('kjba,kjib->ai', d_oovv, eris.ooov)\n        d_oovv = _cp(doovv[p0:p1]) + doovv[:,p0:p1].transpose(1,0,3,2)\n        for i in range(p1-p0):\n            Ioo += lib.dot(eris_oovv[i].reshape(nocc, -1), d_oovv[i].reshape(nocc,-1).T)\n        Ivv += lib.dot(eris_oovv.reshape(-1,nvir).T, d_oovv.reshape(-1,nvir))\n        Ivo += lib.dot(d_oovv.reshape(-1,nvir).T,\n                       _cp(eris_ooov.transpose(0,1,3,2).reshape(-1,nocc)))\n        eris_ooov = None\n        d_oovv = _ccsd.precontract(d_oovv.reshape(-1,nvir,nvir)).reshape(p1-p0,nocc,-1)\n\n        d_ovvv = numpy.empty((p1-p0,nvir,nvir,nvir))\n        ao2mo.outcore._load_from_h5g(dovvv, p0*nvir, p1*nvir,\n                                     d_ovvv.reshape(-1,nvir**2))\n        #:Ivo += numpy.einsum('jadc,jidc->ai', d_ovvv, eris_oovv)\n        for i in range(p1-p0):\n            Ivo += lib.dot(d_ovvv[i].reshape(nvir,-1), eris_oovv[i].reshape(nocc,-1).T)\n        eris_oovv = None\n\n        # tril part of (d_ovvv + d_ovvv.transpose(0,1,3,2))\n        c_ovvv = _ccsd.precontract(d_ovvv.reshape(-1,nvir,nvir))\n        ao2mo.outcore._transpose_to_h5g(fswap, 'c_vvov/%d'%istep, c_ovvv, iobuflen)\n        c_ovvv = c_ovvv.reshape(-1,nvir,nvir_pair)\n        eris_ovx = _cp(eris.ovvv[p0:p1])\n        ao2mo.outcore._transpose_to_h5g(fswap, 'e_vvov/%d'%istep,\n                                        eris_ovx.reshape(-1,nvir_pair), iobuflen)\n        #:Xvo += numpy.einsum('jibc,jabc->ai', d_oovv, eris_ovvv)\n        #:Ivv += numpy.einsum('ibdc,iadc->ab', d_ovvv, eris_ovvv)\n        for i in range(p1-p0):\n            lib.dot(eris_ovx[i].reshape(nvir,-1),\n                    d_oovv[i].reshape(nocc,-1).T, 1, Xvo, 1)\n            lib.dot(eris_ovx[i].reshape(nvir,-1),\n                    c_ovvv[i].reshape(nvir,-1).T, 1, Ivv, 1)\n        c_ovvv = d_oovv = None\n\n        eris_ovvo = numpy.empty((p1-p0,nvir,nvir,nocc))\n        for i in range(p1-p0):\n            d_ovvv[i] = _ccsd.sum021(d_ovvv[i])\n            eris_ovvo[i] = eris_ovov[i].transpose(0,2,1)\n        #:Ivo += numpy.einsum('abjc,ibjc->ai', d_ovvv, eris_ovov)\n        Ivo += lib.dot(d_ovvv.reshape(-1,nvir).T, eris_ovvo.reshape(-1,nocc))\n        eris_ovvo = eris_ovov = None\n\n        eris_ovvv = lib.unpack_tril(eris_ovx.reshape(-1,nvir_pair))\n        eris_ovx = None\n        eris_ovvv = eris_ovvv.reshape(p1-p0,nvir,nvir,nvir)\n        #:Ivv += numpy.einsum('icdb,icda->ab', d_ovvv, eris_ovvv)\n        #:Xvo += numpy.einsum('jibc,jabc->ai', d_oovv, eris_ovvv)\n        Ivv += lib.dot(eris_ovvv.reshape(-1,nvir).T, d_ovvv.reshape(-1,nvir))\n        Xvo[:,p0:p1] +=(numpy.einsum('cb,iacb->ai', dvv, eris_ovvv) * 4\n                      - numpy.einsum('cb,icba->ai', dvv+dvv.T, eris_ovvv))\n\n        d_ovvo = _cp(fswap['dovvo'][p0:p1])\n        #:Xvo += numpy.einsum('jbic,jbca->ai', d_ovov, eris_ovvv)\n        lib.dot(eris_ovvv.reshape(-1,nvir).T, d_ovvo.reshape(-1,nocc), 1, Xvo, 1)\n\n        d_ovvv = d_ovvo = eris_ovvv = None\n\n    max_memory = mycc.max_memory - lib.current_memory()[0]\n    unit = nocc*nvir**2 + nvir**3*2.5\n    blksize = max(ccsd.BLKMIN, int(max_memory*1e6/8/unit))\n    log.debug1('IX_intermediates pass 2: block size = %d, nocc = %d in %d blocks',\n               blksize, nocc, int((nocc+blksize-1)/blksize))\n    for p0, p1 in prange(0, nvir, blksize):\n        off0 = p0*(p0+1)//2\n        off1 = p1*(p1+1)//2\n        d_vvvv = _cp(dvvvv[off0:off1]) * 4\n        for i in range(p0, p1):\n            d_vvvv[i*(i+1)//2+i-off0] *= .5\n        d_vvvv = lib.unpack_tril(d_vvvv)\n        eris_vvvv = lib.unpack_tril(_cp(eris.vvvv[off0:off1]))\n        #:Ivv += numpy.einsum('decb,deca->ab', d_vvvv, eris_vvvv) * 2\n        #:Xvo += numpy.einsum('dbic,dbca->ai', d_vvov, eris_vvvv)\n        lib.dot(eris_vvvv.reshape(-1,nvir).T, d_vvvv.reshape(-1,nvir), 2, Ivv, 1)\n        #:d_vvvv = _cp(d_vvvv + d_vvvv.transpose(0,1,3,2))\n        d_vvov = numpy.empty((off1-off0,nocc,nvir))\n        ao2mo.outcore._load_from_h5g(fswap['c_vvov'], off0, off1, d_vvov.reshape(-1,nov))\n        d_vvvo = _cp(d_vvov.transpose(0,2,1))\n        lib.dot(eris_vvvv.reshape(-1,nvir).T, d_vvvo.reshape(-1,nocc), 1, Xvo, 1)\n        d_vvov = eris_vvvv = None\n\n        eris_vvov = numpy.empty((off1-off0,nocc,nvir))\n        ao2mo.outcore._load_from_h5g(fswap['e_vvov'], off0, off1,\n                                     eris_vvov.reshape(-1,nov))\n        eris_vvvo = _cp(eris_vvov.transpose(0,2,1))\n        #:Ioo += numpy.einsum('abjc,abci->ij', d_vvov, eris_vvvo)\n        #:Ivo += numpy.einsum('dbca,dbci->ai', d_vvvv, eris_vvvo) * 2\n        lib.dot(d_vvvv.reshape(-1,nvir).T, eris_vvvo.reshape(-1,nocc), 2, Ivo, 1)\n        lib.dot(eris_vvvo.reshape(-1,nocc).T, d_vvvo.reshape(-1,nocc), 1, Ioo, 1)\n        eris_vvov = eris_vovv = d_vvvv = None\n\n    del(fswap['e_vvov'])\n    del(fswap['c_vvov'])\n    del(fswap['dovvo'])\n    fswap.close()\n    _tmpfile = None\n\n    if d2 is None:\n        for key in fd2intermediate.keys():\n            del(fd2intermediate[key])\n        fd2intermediate.close()\n        _d2tmpfile = None\n\n    Ioo *= -1\n    Ivv *= -1\n    Ivo *= -1\n    Xvo += Ivo\n    return Ioo, Ivv, Ivo, Xvo\n\n\ndef response_dm1(mycc, t1, t2, l1, l2, eris=None, IX=None):\n    if eris is None:\n# Note eris are in Chemist's notation\n        eris = ccsd._ERIS(mycc)\n    if IX is None:\n        Ioo, Ivv, Ivo, Xvo = IX_intermediates(mycc, t1, t2, l1, l2, eris)\n    else:\n        Ioo, Ivv, Ivo, Xvo = IX\n    nocc, nvir = t1.shape\n    nmo = nocc + nvir\n    max_memory = mycc.max_memory - lib.current_memory()[0]\n    blksize = max(ccsd.BLKMIN, int(max_memory*1e6/8/(nocc*nvir**2)))\n    def fvind(x):\n        x = x.reshape(Xvo.shape)\n        if eris is None:\n            mo_coeff = mycc.mo_coeff\n            dm = reduce(numpy.dot, (mo_coeff[:,nocc:], x, mo_coeff[:,:nocc].T))\n            dm = (dm + dm.T) * 2\n            v = reduce(numpy.dot, (mo_coeff[:,nocc:].T, mycc._scf.get_veff(mol, dm),\n                                   mo_coeff[:,:nocc]))\n        else:\n            v = numpy.zeros((nocc,nvir))\n            for p0, p1 in prange(0, nocc, blksize):\n                eris_ovov = _cp(eris.ovov[p0:p1])\n                v[p0:p1] += numpy.einsum('iajb,bj->ia', eris_ovov, x) * 4\n                v[p0:p1] -= numpy.einsum('ibja,bj->ia', eris_ovov, x)\n                eris_ovov = None\n                v[p0:p1] -= numpy.einsum('ijba,bj->ia', _cp(eris.oovv[p0:p1]), x[:,p0:p1])\n        return v.T\n    mo_energy = eris.fock.diagonal()\n    mo_occ = numpy.zeros_like(mo_energy)\n    mo_occ[:nocc] = 2\n    dvo = cphf.solve(fvind, mo_energy, mo_occ, Xvo, max_cycle=30)[0]\n    dm1 = numpy.zeros((nmo,nmo))\n    dm1[nocc:,:nocc] = dvo\n    dm1[:nocc,nocc:] = dvo.T\n    return dm1\n\n\n#\n# Note: only works with canonical orbitals\n# Non-canonical formula refers to JCP, 95, 2639\n#\ndef kernel(mycc, t1=None, t2=None, l1=None, l2=None, eris=None, atmlst=None,\n           mf_grad=None, verbose=logger.INFO):\n    if t1 is None: t1 = mycc.t1\n    if t2 is None: t2 = mycc.t2\n    if l1 is None: l1 = mycc.l1\n    if l2 is None: l2 = mycc.l2\n    if eris is None: eris = ccsd._ERIS(mycc)\n    if mf_grad is None:\n        mf_grad = rhf_grad.Gradients(mycc._scf)\n\n    log = logger.Logger(mycc.stdout, mycc.verbose)\n    time0 = time.clock(), time.time()\n    mol = mycc.mol\n    moidx = numpy.ones(mycc.mo_coeff.shape[1], dtype=numpy.bool)\n    if isinstance(mycc.frozen, (int, numpy.integer)):\n        raise NotImplementedError('frozen orbital ccsd_grad')\n        moidx[:mycc.frozen] = False\n    else:\n        moidx[mycc.frozen] = False\n    mo_coeff = mycc.mo_coeff[:,moidx]  #FIXME: ensure mycc.mo_coeff is canonical orbital\n    mo_energy = eris.fock.diagonal()\n    nocc, nvir = t1.shape\n    nao, nmo = mo_coeff.shape\n    nao_pair = nao * (nao+1) // 2\n\n    log.debug('Build ccsd rdm1 intermediates')\n    d1 = ccsd_rdm.gamma1_intermediates(mycc, t1, t2, l1, l2)\n    doo, dov, dvo, dvv = d1\n    time1 = log.timer('rdm1 intermediates', *time0)\n\n    log.debug('Build ccsd rdm2 intermediates')\n    _d2tmpfile = tempfile.NamedTemporaryFile(dir=lib.param.TMPDIR)\n    fd2intermediate = h5py.File(_d2tmpfile.name, 'w')\n    d2 = ccsd_rdm.gamma2_outcore(mycc, t1, t2, l1, l2, fd2intermediate)\n    time1 = log.timer('rdm2 intermediates', *time1)\n    log.debug('Build ccsd response_rdm1')\n    Ioo, Ivv, Ivo, Xvo = IX_intermediates(mycc, t1, t2, l1, l2, eris, d1, d2)\n    time1 = log.timer('response_rdm1 intermediates', *time1)\n\n    dm1mo = response_dm1(mycc, t1, t2, l1, l2, eris, (Ioo, Ivv, Ivo, Xvo))\n    dm1mo[:nocc,:nocc] = doo + doo.T\n    dm1mo[nocc:,nocc:] = dvv + dvv.T\n    dm1ao = reduce(numpy.dot, (mo_coeff, dm1mo, mo_coeff.T))\n    im1 = numpy.zeros_like(dm1mo)\n    im1[:nocc,:nocc] = Ioo\n    im1[nocc:,nocc:] = Ivv\n    im1[nocc:,:nocc] = Ivo\n    im1[:nocc,nocc:] = Ivo.T\n    im1 = reduce(numpy.dot, (mo_coeff, im1, mo_coeff.T))\n    time1 = log.timer('response_rdm1', *time1)\n\n    log.debug('symmetrized rdm2 and MO->AO transformation')\n    _dm2file = tempfile.NamedTemporaryFile(dir=lib.param.TMPDIR)\n# Basically, 4 times of dm2 is computed. *2 in _rdm2_mo2ao, *2 in _load_block_tril\n    fdm2 = h5py.File(_dm2file.name, 'w')\n    dm1_with_hf = dm1mo.copy()\n    for i in range(nocc):  # HF 2pdm ~ 4(ij)(kl)-2(il)(jk), diagonal+1 because of 4*dm2\n        dm1_with_hf[i,i] += 1\n    _rdm2_mo2ao(mycc, d2, dm1_with_hf, mo_coeff, fdm2)\n    time1 = log.timer('MO->AO transformation', *time1)\n    for key in fd2intermediate.keys():\n        del(fd2intermediate[key])\n    fd2intermediate.close()\n\n#TODO: pass hf_grad object to compute h1 and s1\n    log.debug('h1 and JK1')\n    h1 = mf_grad.get_hcore(mol)\n    s1 = mf_grad.get_ovlp(mol)\n    zeta = lib.direct_sum('i+j->ij', mo_energy, mo_energy) * .5\n    zeta[nocc:,:nocc] = mo_energy[:nocc]\n    zeta[:nocc,nocc:] = mo_energy[:nocc].reshape(-1,1)\n    zeta = reduce(numpy.dot, (mo_coeff, zeta*dm1mo, mo_coeff.T))\n    p1 = numpy.dot(mo_coeff[:,:nocc], mo_coeff[:,:nocc].T)\n    vhf4sij = reduce(numpy.dot, (p1, mycc._scf.get_veff(mol, dm1ao+dm1ao.T), p1))\n    time1 = log.timer('h1 and JK1', *time1)\n\n    # Hartree-Fock part contribution\n    hf_dm1 = mycc._scf.make_rdm1(mycc._scf.mo_coeff, mycc._scf.mo_occ)\n    dm1ao += hf_dm1\n    zeta += mf_grad.make_rdm1e(mycc._scf.mo_energy, mycc._scf.mo_coeff,\n                               mycc._scf.mo_occ)\n\n    if atmlst is None:\n        atmlst = range(mol.natm)\n    offsetdic = mol.offset_nr_by_atom()\n    max_memory = mycc.max_memory - lib.current_memory()[0]\n    blksize = max(1, int(max_memory*1e6/8/(nao**3*2.5)))\n    ioblksize = fdm2['dm2/0'].shape[-1]\n    de = numpy.zeros((len(atmlst),3))\n    for k, ia in enumerate(atmlst):\n        shl0, shl1, p0, p1 = offsetdic[ia]\n# s[1] dot I, note matrix im1 is not hermitian\n        de[k] =(numpy.einsum('xij,ij->x', s1[:,p0:p1], im1[p0:p1])\n              + numpy.einsum('xji,ij->x', s1[:,p0:p1], im1[:,p0:p1]))\n# h[1] \\dot DM, *2 for +c.c.,  contribute to f1\n        h1ao = mf_grad._grad_rinv(mol, ia)\n        h1ao[:,p0:p1] += h1[:,p0:p1]\n        de[k] +=(numpy.einsum('xij,ij->x', h1ao, dm1ao)\n               + numpy.einsum('xji,ij->x', h1ao, dm1ao))\n# -s[1]*e \\dot DM,  contribute to f1\n        de[k] -=(numpy.einsum('xij,ij->x', s1[:,p0:p1], zeta[p0:p1]  )\n               + numpy.einsum('xji,ij->x', s1[:,p0:p1], zeta[:,p0:p1]))\n# -vhf[s_ij[1]],  contribute to f1, *2 for s1+s1.T\n        de[k] -= numpy.einsum('xij,ij->x', s1[:,p0:p1], vhf4sij[p0:p1]) * 2\n\n# 2e AO integrals dot 2pdm\n        ip0 = p0\n        for b0, b1, nf in shell_prange(mol, shl0, shl1, blksize):\n            eri1 = mol.intor('cint2e_ip1_sph', comp=3, aosym='s2kl',\n                             shls_slice=(b0,b1,0,mol.nbas,0,mol.nbas,0,mol.nbas))\n            eri1 = eri1.reshape(3,nf,nao,-1)\n            dm2buf = numpy.empty((nf,nao,nao_pair))\n            for ic, (i0, i1) in enumerate(prange(0, nao_pair, ioblksize)):\n                _load_block_tril(fdm2['dm2/%d'%ic], ip0, ip0+nf, dm2buf[:,:,i0:i1])\n            de[k] -= numpy.einsum('xijk,ijk->x', eri1, dm2buf) * 2\n            eri1 = dm2buf = None\n            ip0 += nf\n        log.debug('grad of atom %d %s = %s', ia, mol.atom_symbol(ia), de[k])\n        time1 = log.timer('grad of atom %d'%ia, *time1)\n\n    log.note('CCSD gradinets')\n    log.note('==============')\n    log.note('           x                y                z')\n    for k, ia in enumerate(atmlst):\n        log.note('%d %s  %15.9f  %15.9f  %15.9f', ia, mol.atom_symbol(ia),\n                 de[k,0], de[k,1], de[k,2])\n    log.timer('CCSD gradients', *time0)\n    for key in fdm2.keys():\n        del(fdm2[key])\n    fdm2.close()\n    _d2tmpfile = _dm2file = None\n    return de\n\ndef shell_prange(mol, start, stop, blksize):\n    nao = 0\n    ib0 = start\n    for ib in range(start, stop):\n        now = (mol.bas_angular(ib)*2+1) * mol.bas_nctr(ib)\n        nao += now\n        if nao > blksize and nao > now:\n            yield (ib0, ib, nao-now)\n            ib0 = ib\n            nao = now\n    yield (ib0, stop, nao)\n\ndef _rdm2_mo2ao(mycc, d2, dm1, mo_coeff, fsave=None):\n    log = logger.Logger(mycc.stdout, mycc.verbose)\n    if fsave is None:\n        _dm2file = tempfile.NamedTemporaryFile(dir=lib.param.TMPDIR)\n        fsave = h5py.File(_dm2file.name, 'w')\n    else:\n        _dm2file = None\n    time1 = time.clock(), time.time()\n    dovov, dvvvv, doooo, doovv, dovvo, dvvov, dovvv, dooov = d2\n    nocc, nvir = dovov.shape[:2]\n    nov = nocc * nvir\n    nao, nmo = mo_coeff.shape\n    nao_pair = nao * (nao+1) // 2\n    nvir_pair = nvir * (nvir+1) //2\n    mo_coeff = numpy.asarray(mo_coeff, order='F')\n    def _trans(vin, orbs_slice, out=None):\n        nrow = vin.shape[0]\n        if out is None:\n            out = numpy.empty((nrow,nao_pair))\n        fdrv = getattr(_ccsd.libcc, 'AO2MOnr_e2_drv')\n        pao_loc = ctypes.POINTER(ctypes.c_void_p)()\n        fdrv(_ccsd.libcc.AO2MOtranse2_nr_s1, _ccsd.libcc.CCmmm_transpose_sum,\n             out.ctypes.data_as(ctypes.c_void_p),\n             vin.ctypes.data_as(ctypes.c_void_p),\n             mo_coeff.ctypes.data_as(ctypes.c_void_p),\n             ctypes.c_int(nrow), ctypes.c_int(nao),\n             (ctypes.c_int*4)(*orbs_slice), pao_loc, ctypes.c_int(0))\n        return out\n\n# transform dm2_ij to get lower triangular (dm2+dm2.transpose(0,1,3,2))\n    _tmpfile = tempfile.NamedTemporaryFile(dir=lib.param.TMPDIR)\n    fswap = h5py.File(_tmpfile.name)\n    max_memory = mycc.max_memory - lib.current_memory()[0]\n    blksize = max(1, int(max_memory*1e6/8/(nmo*nao_pair+nmo**3+nvir**3)))\n    iobuflen = int(256e6/8/(blksize*nmo))\n    log.debug1('_rdm2_mo2ao pass 1: blksize = %d, iobuflen = %d', blksize, iobuflen)\n    fswap.create_group('o')  # for h5py old version\n    pool1 = numpy.empty((blksize,nmo,nmo,nmo))\n    pool2 = numpy.empty((blksize,nmo,nao_pair))\n    bufd_ovvv = numpy.empty((blksize,nvir,nvir,nvir))\n    for istep, (p0, p1) in enumerate(prange(0, nocc, blksize)):\n        buf1 = pool1[:p1-p0]\n        buf1[:,:nocc,:nocc,:nocc] = doooo[p0:p1]\n        buf1[:,:nocc,:nocc,nocc:] = dooov[p0:p1]\n        buf1[:,:nocc,nocc:,:nocc] = 0\n        buf1[:,:nocc,nocc:,nocc:] = doovv[p0:p1]\n        buf1[:,nocc:,:nocc,:nocc] = 0\n        buf1[:,nocc:,:nocc,nocc:] = dovov[p0:p1]\n        buf1[:,nocc:,nocc:,:nocc] = dovvo[p0:p1]\n        d_ovvv = bufd_ovvv[:p1-p0]\n        ao2mo.outcore._load_from_h5g(dovvv, p0*nvir, p1*nvir,\n                                     d_ovvv.reshape(-1,nvir**2))\n        buf1[:,nocc:,nocc:,nocc:] = d_ovvv\n        for i in range(p0, p1):\n            buf1[i-p0,i,:,:] += dm1\n            buf1[i-p0,:,:,i] -= dm1 * .5\n        buf2 = pool2[:p1-p0].reshape(-1,nao_pair)\n        _trans(buf1.reshape(-1,nmo**2), (0,nmo,0,nmo), buf2)\n        ao2mo.outcore._transpose_to_h5g(fswap, 'o/%d'%istep, buf2, iobuflen)\n    pool1 = pool2 = bufd_ovvv = None\n    time1 = log.timer_debug1('_rdm2_mo2ao pass 1', *time1)\n\n    fswap.create_group('v')  # for h5py old version\n    pool1 = numpy.empty((blksize*nvir,nao_pair))\n    pool2 = numpy.empty((blksize*nvir,nvir,nvir))\n    for istep, (p0, p1) in enumerate(prange(0, nvir_pair, blksize*nvir)):\n        buf1 = _cp(dvvvv[p0:p1])\n        buf2 = lib.unpack_tril(buf1, out=pool2[:p1-p0])\n        buf1 = _trans(buf2, (nocc,nmo,nocc,nmo), out=pool1[:p1-p0])\n        ao2mo.outcore._transpose_to_h5g(fswap, 'v/%d'%istep, buf1, iobuflen)\n    pool1 = pool2 = None\n    time1 = log.timer_debug1('_rdm2_mo2ao pass 2', *time1)\n\n# transform dm2_kl then dm2 + dm2.transpose(2,3,0,1)\n    max_memory = mycc.max_memory - lib.current_memory()[0]\n    blksize = max(nao, int(max_memory*1e6/8/(nao_pair+nmo**2)))\n    iobuflen = int(256e6/8/blksize)\n    log.debug1('_rdm2_mo2ao pass 3: blksize = %d, iobuflen = %d', blksize, iobuflen)\n    gsave = fsave.create_group('dm2')\n    for istep, (p0, p1) in enumerate(prange(0, nao_pair, blksize)):\n        gsave.create_dataset(str(istep), (nao_pair,p1-p0), 'f8')\n    diagidx = numpy.arange(nao)\n    diagidx = diagidx*(diagidx+1)//2 + diagidx\n    pool1 = numpy.empty((blksize,nmo,nmo))\n    pool2 = numpy.empty((blksize,nvir_pair))\n    pool3 = numpy.empty((blksize,nvir,nvir))\n    pool4 = numpy.empty((blksize,nao_pair))\n    for istep, (p0, p1) in enumerate(prange(0, nao_pair, blksize)):\n        buf1 = pool1[:p1-p0]\n        ao2mo.outcore._load_from_h5g(fswap['o'], p0, p1,\n                                     buf1[:,:nocc].reshape(p1-p0,-1))\n        buf2 = ao2mo.outcore._load_from_h5g(fswap['v'], p0, p1, pool2[:p1-p0])\n        buf3 = lib.unpack_tril(buf2, out=pool3[:p1-p0])\n        buf1[:,nocc:,nocc:] = buf3\n        buf1[:,nocc:,:nocc] = 0\n        buf2 = _trans(buf1, (0,nmo,0,nmo), out=pool4[:p1-p0])\n        ic = 0\n        idx = diagidx[diagidx<p1]\n        if p0 > 0:\n            buf1 = _cp(gsave[str(istep)][:p0])\n            for i0, i1 in prange(0, p1-p0, BLKSIZE):\n                for j0, j1, in prange(0, p0, BLKSIZE):\n                    buf1[j0:j1,i0:i1] += buf2[i0:i1,j0:j1].T\n                    buf2[i0:i1,j0:j1] = buf1[j0:j1,i0:i1].T\n            buf1[:,idx[p0<=idx]-p0] *= .5\n            gsave[str(istep)][:p0] = buf1\n        lib.transpose_sum(buf2[:,p0:p1], inplace=True)\n        buf2[:,idx] *= .5\n        for ic, (i0, i1) in enumerate(prange(0, nao_pair, blksize)):\n            gsave[str(ic)][p0:p1] = buf2[:,i0:i1]\n    time1 = log.timer_debug1('_rdm2_mo2ao pass 3', *time1)\n    del(fswap['o'])\n    del(fswap['v'])\n    fswap.close()\n    _tmpfile = None\n    time1 = log.timer_debug1('_rdm2_mo2ao cleanup', *time1)\n    if _dm2file is not None:\n        nvir_pair = nvir * (nvir+1) // 2\n        dm2 = numpy.empty((nvir_pair, nvir_pair))\n        ao2mo.outcore._load_from_h5g(fsave['dm2'], 0, nvir_pair, dm2)\n        fsave.close()\n        _dm2file = None\n        return dm2\n    else:\n        return fsave\n\n#\n# .\n# . .\n# ----+             -----------\n# ----|-+       =>  -----------\n# . . | | .\n# . . | | . .\n#\ndef _load_block_tril(dat, row0, row1, out=None):\n    shape = dat.shape\n    nd = int(numpy.sqrt(shape[0]*2))\n    if out is None:\n        out = numpy.empty((row1-row0,nd)+shape[1:])\n    else:\n        out = numpy.ndarray((row1-row0,nd)+shape[1:], buffer=out)\n    p0 = row0*(row0+1)//2\n    for i in range(row0, row1):\n        out[i-row0,:i+1] = _cp(dat[p0:p0+i+1])\n        for j in range(row0, i):\n            out[j-row0,i] = out[i-row0,j]\n        p0 += i + 1\n    for i in range(row1, nd):\n        i2 = i*(i+1)//2\n        out[:,i] = dat[i2+row0:i2+row1]\n    return out\n\n\ndef hf_get_jk_incore(eri, dm):\n    ni, nj = eri.shape[:2]\n    vj = numpy.empty((ni,nj))\n    vk = numpy.empty((ni,nj))\n    _ccsd.libcc.CCvhfs2kl(eri.ctypes.data_as(ctypes.c_void_p),\n                          dm.ctypes.data_as(ctypes.c_void_p),\n                          vj.ctypes.data_as(ctypes.c_void_p),\n                          vk.ctypes.data_as(ctypes.c_void_p),\n                          ctypes.c_int(ni), ctypes.c_int(nj))\n    return vj, vk\n\ndef prange(start, end, step):\n    for i in range(start, end, step):\n        yield i, min(i+step, end)\n\ndef _cp(a):\n    return numpy.array(a, copy=False, order='C')\n\n\nif __name__ == '__main__':\n    from pyscf import gto\n    from pyscf import scf\n    from pyscf import ao2mo\n    from pyscf import grad\n\n    mol = gto.M()\n    mf = scf.RHF(mol)\n\n    mycc = ccsd.CCSD(mf)\n\n    numpy.random.seed(2)\n    nocc = 5\n    nmo = 12\n    nvir = nmo - nocc\n    eri0 = numpy.random.random((nmo,nmo,nmo,nmo))\n    eri0 = ao2mo.restore(1, ao2mo.restore(8, eri0, nmo), nmo)\n    fock0 = numpy.random.random((nmo,nmo))\n    fock0 = fock0 + fock0.T + numpy.diag(range(nmo))*20\n    t1 = numpy.random.random((nocc,nvir))\n    t2 = numpy.random.random((nocc,nocc,nvir,nvir))\n    t2 = t2 + t2.transpose(1,0,3,2)\n    l1 = numpy.random.random((nocc,nvir))\n    l2 = numpy.random.random((nocc,nocc,nvir,nvir))\n    l2 = l2 + l2.transpose(1,0,3,2)\n\n    h1 = fock0 - (numpy.einsum('kkpq->pq', eri0[:nocc,:nocc])*2\n                - numpy.einsum('pkkq->pq', eri0[:,:nocc,:nocc]))\n    eris = lambda:None\n    idx = numpy.tril_indices(nvir)\n    eris.oooo = eri0[:nocc,:nocc,:nocc,:nocc].copy()\n    eris.ooov = eri0[:nocc,:nocc,:nocc,nocc:].copy()\n    eris.ovoo = eri0[:nocc,nocc:,:nocc,:nocc].copy()\n    eris.oovo = eri0[:nocc,:nocc,nocc:,:nocc].copy()\n    eris.oovv = eri0[:nocc,:nocc,nocc:,nocc:].copy()\n    eris.ovov = eri0[:nocc,nocc:,:nocc,nocc:].copy()\n    eris.ovvv = eri0[:nocc,nocc:,nocc:,nocc:]\n    eris.ovvv = eris.ovvv[:,:,idx[0],idx[1]].copy()\n    eris.vvvv = eri0[nocc:,nocc:,nocc:,nocc:]\n    eris.vvvv = eris.vvvv[idx[0],idx[1]][:,idx[0],idx[1]].copy()\n    eris.fock = fock0\n\n    print('-----------------------------------')\n    Ioo, Ivv, Ivo, Xvo = IX_intermediates(mycc, t1, t2, l1, l2, eris)\n    numpy.random.seed(1)\n    h1 = numpy.random.random((nmo,nmo))\n    h1 = h1 + h1.T\n    print(numpy.einsum('ij,ij', h1[:nocc,:nocc], Ioo) - 2613213.0346526774)\n    print(numpy.einsum('ab,ab', h1[nocc:,nocc:], Ivv) - 6873038.9907923322)\n    print(numpy.einsum('ai,ai', h1[nocc:,:nocc], Ivo) - 4353360.4241635408)\n    print(numpy.einsum('ai,ai', h1[nocc:,:nocc], Xvo) - 203575.42337558540)\n    dm1 = response_dm1(mycc, t1, t2, l1, l2, eris)\n    print(numpy.einsum('pq,pq', h1[nocc:,:nocc], dm1[nocc:,:nocc])--486.638981725713393)\n\n    print('-----------------------------------')\n    mol = gto.M(\n        verbose = 0,\n        atom = [\n            [\"O\" , (0. , 0.     , 0.)],\n            [1   , (0. ,-0.757  , 0.587)],\n            [1   , (0. , 0.757  , 0.587)]],\n        basis = '631g'\n    )\n    mf = scf.RHF(mol)\n    ehf = mf.scf()\n\n    mycc = ccsd.CCSD(mf)\n    mycc.conv_tol = 1e-10\n    mycc.conv_tol_normt = 1e-10\n    ecc, t1, t2 = mycc.kernel()\n    l1, l2 = mycc.solve_lambda()\n    g1 = kernel(mycc, t1, t2, l1, l2, mf_grad=grad.RHF(mf))\n    print('gcc')\n    print(g1 + grad.grad_nuc(mol))\n#[[ 0   0                1.00950925e-02]\n# [ 0   2.28063426e-02  -5.04754623e-03]\n# [ 0  -2.28063426e-02  -5.04754623e-03]]\n\n    lib.parameters.BOHR = 1\n    r = 1.76#.748\n    mol = gto.M(\n        verbose = 0,\n        atom = '''H 0 0 0; H 0 0 %f''' % r,\n        basis = '631g')\n    mf = scf.RHF(mol)\n    mf.conv_tol = 1e-14\n    ehf0 = mf.scf()\n    ghf = grad.RHF(mf).grad()\n    mycc = ccsd.CCSD(mf)\n    mycc.conv_tol = 1e-10\n    mycc.conv_tol_normt = 1e-10\n    ecc, t1, t2 = mycc.kernel()\n    l1, l2 = mycc.solve_lambda()\n    g1 = kernel(mycc, t1, t2, l1, l2, mf_grad=grad.RHF(mf))\n    print('gcc')\n    print(g1 + grad.grad_nuc(mol))\n#[[ 0.          0.         -0.07080036]\n# [ 0.          0.          0.07080036]]\n", "meta": {"hexsha": "f8f5e9a3c65b1828472c8a27cac02f8318cf05bf", "size": 28479, "ext": "py", "lang": "Python", "max_stars_repo_path": "cc/ccsd_grad.py", "max_stars_repo_name": "gmwang18/pyscf", "max_stars_repo_head_hexsha": "fcd6877751661c8a9743c1c872a4a2b65f6dd7ac", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cc/ccsd_grad.py", "max_issues_repo_name": "gmwang18/pyscf", "max_issues_repo_head_hexsha": "fcd6877751661c8a9743c1c872a4a2b65f6dd7ac", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cc/ccsd_grad.py", "max_forks_repo_name": "gmwang18/pyscf", "max_forks_repo_head_hexsha": "fcd6877751661c8a9743c1c872a4a2b65f6dd7ac", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9181034483, "max_line_length": 90, "alphanum_fraction": 0.5835879069, "include": true, "reason": "import numpy", "num_tokens": 10702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.2845759981489974, "lm_q1q2_score": 0.15998193887548673}}
{"text": "\"\"\"\nModule containing various thermostat. Berendsen only for now.\n\"\"\"\nimport numpy as np\nfrom numba import njit\n\n\nclass Thermostat:\n    \"\"\"\n    Thermostat object.\n\n    Attributes\n    ----------\n    kB : float\n        Boltzmann constant in correct units.\n\n    no_species : int\n        Total number of species.\n\n    species_np : numpy.ndarray\n        Number of particles of each species.\n\n    species_masses : numpy.ndarray\n        Mass of each species.\n\n    relaxation_rate: float\n        Berendsen parameter tau.\n\n    relaxation_timestep: int\n        Timestep at which thermostat is turned on.\n\n    type: str\n        Thermostat type\n\n    berendsen_tau: float\n        Berendsen parameter.\n\n    \"\"\"\n\n    def __init__(self):\n        self.temperatures = None\n        self.temperatures_eV = None\n        self.type = None\n        self.relaxation_rate = None\n        self.relaxation_timestep = None\n        self.kB = None\n        self.species_num = None\n        self.species_masses = None\n        self.berendsen_tau = None\n        self.eV_temp_flag = False\n        self.K_temp_flag = False\n\n    def __repr__(self):\n        sortedDict = dict(sorted(self.__dict__.items(), key=lambda x: x[0].lower()))\n        disp = 'Thermostat( \\n'\n        for key, value in sortedDict.items():\n            disp += \"\\t{} : {}\\n\".format(key, value)\n        disp += ')'\n        return disp\n\n    def from_dict(self, input_dict: dict):\n        \"\"\"\n        Update attributes from input dictionary.\n\n        Parameters\n        ----------\n        input_dict: dict\n            Dictionary to be copied.\n\n        \"\"\"\n        self.__dict__.update(input_dict)\n\n        # Make sure list are turned into numpy arrays\n        if self.temperatures_eV:\n            if not isinstance(self.temperatures_eV, np.ndarray):\n                self.temperatures_eV = np.array([self.temperatures_eV])\n            self.eV_temp_flag = True\n\n        if self.temperatures:\n            if not isinstance(self.temperatures, np.ndarray):\n                self.temperatures = np.array([self.temperatures])\n            self.K_temp_flag = True\n\n    def pretty_print(self):\n        \"\"\"Print Thermostat information in a user-friendly way.\"\"\"\n        print('Type: {}'.format(self.type))\n        print('First thermostating timestep, i.e. relaxation_timestep = {}'.format(self.relaxation_timestep))\n        print(\"Berendsen parameter tau: {:.3f} [timesteps]\".format(self.berendsen_tau))\n        print(\"Berendsen relaxation rate: {:.3f} [1/timesteps] \".format(self.relaxation_rate))\n        if not self.eV_temp_flag and not self.K_temp_flag:\n            # If you forgot to give thermostating temperatures\n            print(\"\\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\n            print(\"Equilibration temperatures not defined. I will use the species's temperatures\")\n            print(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\")\n        print(\"Thermostating temperatures: \")\n        for i, (t, t_ev) in enumerate(zip(self.temperatures, self.temperatures_eV)):\n            print(\"Species ID {}: T_eq = {:.6e} [K] = {:.6e} [eV]\".format(i, t, t_ev))\n\n    def setup(self, params):\n        \"\"\"\n        Assign attributes from simulation's parameters.\n\n        Parameters\n        ----------\n        params: sarkas.core.Parameters\n            Simulation's parameters\n\n        \"\"\"\n\n        # Check whether you input temperatures in eV or K\n\n        if self.eV_temp_flag:\n            self.temperatures = params.eV2K * np.copy(self.temperatures_eV)\n        elif self.K_temp_flag:\n            self.temperatures_eV = np.copy(self.temperatures) / params.eV2K\n        else:\n            self.temperatures = np.copy(params.species_temperatures)\n            self.temperatures_eV = np.copy(self.temperatures) / params.eV2K\n\n        if self.berendsen_tau:\n            self.relaxation_rate = 1.0 / self.berendsen_tau\n        else:\n            self.berendsen_tau = 1.0 / self.relaxation_rate\n\n        if not self.temperatures.all():\n            self.temperatures = np.copy(params.species_temperatures)\n\n        self.kB = params.kB\n        self.species_num = np.copy(params.species_num)\n        self.species_masses = np.copy(params.species_masses)\n\n        assert self.type.lower() == \"berendsen\", \"Only Berendsen thermostat is supported.\"\n\n    def update(self, ptcls, it):\n        \"\"\"\n        Update particles' velocities according to the chosen thermostat\n\n        Parameters\n        ----------\n        ptcls : sarkas.core.Particles\n            Particles' data.\n\n        it : int\n            Current timestep.\n\n        \"\"\"\n        K, T = ptcls.kinetic_temperature()\n        berendsen(ptcls.vel, self.temperatures, T, self.species_num, self.relaxation_timestep,\n                  self.relaxation_rate, it)\n\n\n@njit\ndef calc_kin_temp(vel, nums, masses, kB):\n    \"\"\"\n    Calculates the kinetic energy and temperature.\n\n    Parameters\n    ----------\n    kB: float\n        Boltzmann constant in chosen units.\n\n    masses: numpy.ndarray\n        Mass of each species.\n\n    nums: numpy.ndarray\n        Number of particles of each species.\n\n    vel: numpy.ndarray\n        Particles' velocities.\n\n    Returns\n    -------\n    K : numpy.ndarray\n        Kinetic energy of each species.\n\n    T : numpy.ndarray\n        Temperature of each species.\n    \"\"\"\n\n    num_species = len(nums)\n\n    K = np.zeros(num_species)\n    T = np.zeros(num_species)\n    const = 2.0 / (kB * nums * vel.shape[1])\n    kinetic_energies = 0.5 * masses * (vel ** 2).transpose()\n\n    species_start = 0\n    species_end = 0\n    for i, num in enumerate(nums):\n        species_end += num\n        K[i] = np.sum(kinetic_energies[:, species_start:species_end])\n        T[i] = const[i] * K[i]\n        species_start += num\n\n    return K, T\n\n\n@njit\ndef berendsen(vel, T_desired, T, species_np, therm_timestep, tau, it):\n    \"\"\"\n    Update particle velocity based on Berendsen thermostat [Berendsen1984]_.\n\n    Parameters\n    ----------\n    T : numpy.ndarray\n        Instantaneous temperature of each species.\n\n    vel : numpy.ndarray\n        Particles' velocities to rescale.\n\n    T_desired : numpy.ndarray\n        Target temperature of each species.\n\n    tau : float\n        Scale factor.\n\n    therm_timestep : int\n        Timestep at which to turn on the thermostat.\n\n    species_np : numpy.ndarray\n        Number of each species.\n\n    it : int\n        Current timestep.\n\n    References\n    ----------\n    .. [Berendsen1984] `H.J.C. Berendsen et al., J Chem Phys 81 3684 (1984) <https://doi.org/10.1063/1.448118>`_\n\n    \"\"\"\n\n    # if it < therm_timestep:\n    #     fact = np.sqrt(T_desired / T)\n    # else:\n    #     fact = np.sqrt(1.0 + (T_desired / T - 1.0) * tau)  # eq.(11)\n\n    # branchless programming\n    fact = 1.0 * (it < therm_timestep) + np.sqrt(1.0 + (T_desired / T - 1.0) * tau) * (it >= therm_timestep)\n    species_start = 0\n    species_end = 0\n\n    for i, num in enumerate(species_np):\n        species_end += num\n        vel[species_start:species_end, :] *= fact[i]\n        species_start += num\n", "meta": {"hexsha": "c2076bbd05bf7abea8893cd91d75804c7ca4c9f3", "size": 7046, "ext": "py", "lang": "Python", "max_stars_repo_path": "sarkas/time_evolution/thermostats.py", "max_stars_repo_name": "pwessels-uhh/sarkas", "max_stars_repo_head_hexsha": "78fb9f8106ed6b15fb67c22afea09593fed01730", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sarkas/time_evolution/thermostats.py", "max_issues_repo_name": "pwessels-uhh/sarkas", "max_issues_repo_head_hexsha": "78fb9f8106ed6b15fb67c22afea09593fed01730", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-18T00:32:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-18T00:32:25.000Z", "max_forks_repo_path": "sarkas/time_evolution/thermostats.py", "max_forks_repo_name": "pwessels-uhh/sarkas", "max_forks_repo_head_hexsha": "78fb9f8106ed6b15fb67c22afea09593fed01730", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6422764228, "max_line_length": 112, "alphanum_fraction": 0.5906897531, "include": true, "reason": "import numpy,from numba", "num_tokens": 1724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3174262720448507, "lm_q1q2_score": 0.15995305717144281}}
{"text": "# -*- coding: utf-8; -*-\n#\n# (c) 2016 microquake development team\n#\n# This file is part of the microquake library\n#\n# microquake is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 3 of the License, or\n# (at your option) any later version.\n#\n# microquake is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with microquake.  If not, see <http://www.gnu.org/licenses/>.\n\nimport numpy as np\nfrom microquake.core import Stream, Trace\nfrom obspy.signal.trigger import recursive_sta_lta, pk_baer, \\\n    classic_sta_lta, coincidence_trigger\nfrom obspy.realtime.signal import kurtosis\nfrom scipy.signal import detrend\nfrom scipy.ndimage.filters import gaussian_filter1d\nfrom microquake.core import event\nfrom microquake.core.util.decorator import deprecated\nimport microquake.core.nlloc as nll\n#from microquake.core.util.decorator import logger\nfrom loguru import logger\n\nfrom microquake.core.event import make_pick\nfrom microquake.core.util.tools import copy_picks_to_dict\n\n\ndef measure_polarity(st, catalog, site, average_time_window=1e-3,\n                     hp_filter_freq=100):\n    \"\"\"\n    Measure the P- and S-wave polarities\n    :param st: seismograms\n    :type st: either obspy.core.Stream or microquake.core.Stream\n    :param catalog: catalog object\n    :type catalog: microquake.core.Catalog\n    :param site: sensor information\n    :type site: microquake.core.station.Site\n    :param average_time_window: time window over which the polarity is measured (s)\n    :type average_time_window: float\n    :rparam: returns a copy of the input catalog\n    :rtype: microquake.core.Stream\n    \"\"\"\n    cat_out = catalog.copy()\n\n    for iev, ev in enumerate(cat_out.events):\n        for ipick, pick in enumerate(ev.picks):\n            sta_code = pick.waveform_id.station_code\n            ch_code = pick.waveform_id.channel_code\n            trs = st.select(station=sta_code, channel=ch_code)\n            trs = trs.detrend('linear').detrend('demean')\n            sta = site.select(station=sta_code, channel=ch_code)\n            if not sta.networks[0].stations:\n                continue\n            if (len(sta.networks) > 1) or (len(sta.networks[0].stations) > 1):\n                logger.warning(\"MeasurePolarity: multiple station selected \"\n                               \"from site. Only the first will be used\")\n            sta = sta.networks[0].stations[0]\n            motion_type = sta.motion_type\n            if motion_type == 'acceleration':\n                trs = trs.integrate().detrend('linear').detrend(\n                    'demean').integrate()\n            elif motion_type == 'velocity':\n                trs.integrate()\n            elif motion_type == 'displacement':\n                pass\n            else:\n                logger.warning(\"MeasurePolarity: motion_type not set for \"\n                               \"sensor %s... Displacement will be assumed\"\n                               %stname)\n\n            trs.filter('highpass', freq=hp_filter_freq)\n            if len(trs) > 1:\n                logger.warning(\"number of trace for station %s and channel %s\"\n                 \"is greater than 1. Only the first trace will be used\" % (\n                                   sta_code, ch_code))\n            tr = trs.traces[0]\n\n            sp_s = int((pick.time - tr.stats.starttime) * tr.stats.sampling_rate)\n            sp_e = int((sp_s + average_time_window * tr.stats.sampling_rate)) + 1\n            pol = np.sign(np.mean(tr.data[sp_s:sp_e]) - tr.data[sp_s])\n\n            if pol > 0:\n                cat_out.events[iev].picks[ipick].polarity = \"positive\"\n            elif pol < 0:\n                cat_out.events[iev].picks[ipick].polarity = \"negative\"\n            else:\n                cat_out.events[iev].picks[ipick].polarity = \"undecidable\"\n\n    return cat_out\n\n\ndef _measure_pick_polarity_tr(tr, pick_time, signal_type='Acceleration', nsamp_avg=10):\n    \"\"\"Mesure pick polarity\n    The pick polarity is measured on the displacement trace looking at the difference\n    between the amplitude at the pick time and the sign of the average amplitude\n    for the 10 samples following the pick time\n\n    :param tr: signal trace seismogram\n    :type tr: obspy Trace\n    :param pick_time: pick time\n    :type pick_time: obspy UTCDateTime\n    :param signal_type: Type of signal\n    :type signal_type: str [accepted values are 'Acceleration', 'Velocity', and 'Displacement']\n    :param nsamp_avg: number of sample on which to calculate the average difference\n    :type nsamp_avg: int\n    :returns: signa of signal polarity (1 or -1)\n    :rtype: int\n    \"\"\"\n\n    if signal_type not in ['Acceleration', 'Velocity', 'Displacement']:\n        # raise error and exit funciton\n        pass\n\n    starttime = tr.stats.starttime\n    sampling_rate = tr.stats.sampling_rate\n    sample_pick = int(pick_time - starttime * sampling_rate)\n\n    polarity = np.sign(np.mean(tr.data[sample_pick + 1:sample_pick +\n                                                       nsamp_avg + 2] -\n                               tr.data[sample_pick]))\n\n    return polarity\n\n\ndef pick_uncertainty(tr, pick_time, snr_window=10):\n    \"\"\"Estimate the pick uncertainty, dt, based on the following equation\n    dt = 1 / (fm * log_2(1 + SNR ** 2)\n    where fm is the middle frequency and SNR, the signal to noise ratio in dB.\n\n    :param tr: signal trace seismogram\n    :type tr: obspy Trace\n    :param pick_time: pick time\n    :type pick_time: obspy UTCDateTime\n    :param snr_window: length of window in ms centered on pick_time to\n    calculate SNR.\n        Noise and signal energy are calculated over the first and second half of\n        the pick window, respectively.\n    :type snr_window: float\n    :returns: pick uncertainty in second\n    :rtype: float\n    \"\"\"\n\n    fm = 100  # central frequency in Hz\n    # fm = centralfrequency(tr, pick_time, window)\n    # tr is obspy tr, pick_time same, window window from pick over wich\n    # signal frequencies are calculated\n    st = Stream(traces=[tr])\n    snr = calculate_snr(st, pick_time, snr_window)\n    return 1 / (fm * np.log(1 + snr ** 2) / np.log(2))\n\n# noinspection PyProtectedMember\ndef STALTA_picker_refraction(st, nsta=1e-3, nlta=4e-2, fc=50, nc=2,\n    noise_mag=1e-25, SNR_window=5e-3):\n    \"\"\"The STA/LTA picker provides a first order good estimate of the arrival\n    times for both the P- and S- wave. The STA/LTA picker uses\n    :py:class:`obspy.signal.trigger.recursive_sta_lta`.\n\n    :param st: seismogram containing a seismic event\n    :type st: :py:class:`obspy.core.stream.Stream`\n    :param nsta: Length of the short term average (STA) window in seconds.\n    The value\n        must be smaller than the minimum separation between the P- and S-\n        wave arrival (explanation to be improved).\n    :param nlta: Length of the long term average (LTA) window in seconds. The value\n        must be long enough to capture well the noise but not too long (\n        description to be improved)\n    :param fc: Corner frequency of the Gaussian kernel used to smooth the\n    LTA/STA\n        function in Hz. This parameter must be chosen to limit the number of\n        peaks in the STA/LTA function.\n    :param nc: Number of desired onset. *** PARAMETER NOT USED ***\n    :param noise_mag: Amplitude of the noise that is add to the original signal\n    :param SNR_window: Length of window in seconds in which the SNR is\n    calculated before and after the pick\n    :returns:  :py:class:`obspy.core.event.Catalog` -- a new catalog\n    containing a single event with a list of picks\n    \"\"\"\n\n    # nphase = 1\n    st.detrend('demean')\n    stations = np.unique([tr.stats.station for tr in st])\n\n    # for station in stations:\n    opicks = []\n    cfs = []\n    snrs = []\n    for station in stations:\n\n        trs = st.select(station=station)\n        # if len(trs) == 3:\n        #   trs = _RotateP_S(trs)\n\n        # else:\n        #   continue\n\n        sta = int(nsta * trs.traces[0].stats['sampling_rate'])\n        lta = int(nlta * trs.traces[0].stats['sampling_rate'])\n\n        # Noise added to avoid zeroed trace.\n        rd = np.random.randn(len(trs.traces[0].data)) * noise_mag\n        trstmp = [Trace(\n            data=np.hstack(\n                (tr.data[::-1].reshape(len(tr)) + rd[::-1].reshape(len(rd)),\n                tr.data.reshape(len(tr)) + rd.reshape(len(rd)))),\n            header=tr.stats) for tr in trs]\n        sttmp = Stream(traces=trstmp)\n\n        # tr.data = tr.data + np.random.randn(len(tr.data)) * 1e-10\n\n        StaLta = np.sum([classic_sta_lta(tr, sta, lta) for tr in sttmp], axis=0)\n        StaLta = StaLta[len(StaLta) / 2::]\n\n        sfreq = trs.traces[0].stats['sampling_rate']\n        sigma = sfreq / (2 * np.pi * fc)\n        StaLtaf = gaussian_filter1d(StaLta, sigma=sigma, mode='reflect')\n\n        picks = _Pick_STALTA_refraction(trs, StaLtaf)\n        snrs = [calculate_snr(trs, p, SNR_window) for p in picks]\n\n        cfs.append(StaLtaf)\n        snrs.append(snrs)\n\n        for k, p in enumerate(picks):\n            if k == 0:\n                opicks.append(make_pick(p, 'P', trs.traces[0], snrs[k]))\n            elif k == 1:\n                opicks.append(make_pick(p, 'S', trs.traces[0], snrs[k]))\n            else:\n                opicks.append(make_pick(p, '?', trs.traces[0], snrs[k]))\n\n    catalog = event.Catalog()\n    catalog.events.append(event.Event(picks=opicks))\n\n    return catalog, cfs, snrs\n\n\ndef STALTA_picker(st, nphase=2, nsta=1e-3, nlta=4e-2, fc=50, nc=2,\n    noise_mag=1e-25, SNR_window=5e-3):\n    \"\"\"The STA/LTA picker provides a first order good estimate of the arrival\n    times for both the P- and S- wave. The STA/LTA picker uses\n    :py:class:`obspy.signal.trigger.recursive_sta_lta `.\n\n    :param st: seismogram containing a seismic event\n    :type st: :py:class:`obspy.core.stream.Stream`\n    :param nphase: Number of phases to pick. The number of phase should\n    represent the number of phase present in the signal. This parameter will\n    be set-up to two for picking the P- and S-wave onset times.\n    :param nsta: Length of the short term average (STA) window in seconds. The value\n        must be smaller than the minimum separation between the P- and S-\n        wave arrival (explanation to be improved).\n    :param nlta: Length of the long term average (LTA) window in seconds. The value\n        must be long enough to capture well the noise but not too long (\n        description to be improved)\n    :param fc: Corner frequency of the Gaussian kernel used to smooth the LTA/STA\n        function in Hz. This parameter must be chosen to limit the number of\n        peaks in the STA/LTA function (default 50 Hz).\n    :param nc: Number of desired onset. *** PARAMETER NOT USED ***\n    :param noise_mag: Amplitude of the noise to be added to the original signal\n    :param SNR_window: Length of window in seconds in which the SNR is\n    calculated before and after the pick\n    :returns:  :py:class:`obspy.core.event.Catalog` -- a new catalog\n    containing a single event with a list of picks\n    \"\"\"\n\n    st.detrend('demean')\n    stations = np.unique([tr.stats.station for tr in st])\n\n    # for station in stations:\n    opicks = []\n    cfs = []\n    snrs = []\n    for station in stations:\n\n        trs = st.select(station=station)\n        # if len(trs) == 3:\n        #   trs = _RotateP_S(trs)\n\n        # else:\n        #   continue\n\n        sta = int(nsta * trs.traces[0].stats['sampling_rate'])\n        lta = int(nlta * trs.traces[0].stats['sampling_rate'])\n\n        # Noise added to avoid zeroed trace.\n        rd = np.random.randn(len(trs.traces[0].data)) * noise_mag\n        trstmp = [Trace(\n            data=np.hstack(\n                (tr.data[::-1].reshape(len(tr)) + rd[::-1].reshape(len(rd)),\n                tr.data.reshape(len(tr)) + rd.reshape(len(rd)))),\n            header=tr.stats) for tr in trs]\n        sttmp = Stream(traces=trstmp)\n\n        # tr.data = tr.data + np.random.randn(len(tr.data)) * 1e-10\n\n        StaLta = np.sum([recursive_sta_lta(tr, sta, lta) for tr in sttmp],\n                        axis=0)\n        StaLta = StaLta[len(StaLta) / 2::]\n\n        sfreq = trs.traces[0].stats['sampling_rate']\n        sigma = sfreq / (2 * np.pi * fc)\n        StaLtaf = gaussian_filter1d(StaLta, sigma=sigma, mode='reflect')\n\n        picks = _Pick_STALTA(trs, StaLtaf, nphase)\n        SNRs = [calculate_snr(trs, p, SNR_window) for p in picks]\n\n        # print picks[0], (picks - trs[0].stats.starttime) * trs[0].stats.sampling_rate, SNRs\n\n        cfs.append(StaLtaf)\n        snrs.append(SNRs)\n\n        for k, p in enumerate(picks):\n            if k == 0:\n                opicks.append(make_pick(p, 'P', trs.traces[0], SNRs[k]))\n            elif k == 1:\n                opicks.append(make_pick(p, 'S', trs.traces[0], SNRs[k]))\n            else:\n                opicks.append(make_pick(p, '?', trs.traces[0], SNRs[k]))\n\n    catalog = event.Catalog()\n    catalog.events.append(event.Event(picks=opicks))\n\n    return catalog, cfs, snrs\n\n\ndef kurtosis_picker(st, picks, freqmin=100, freqmax=1000, pick_freqs=None,\n    kurtosis_window=None, CF3_tol=10e-3, SNR_window=5e-3):\n    \"\"\"Kurtosis picker adapted for microseismic event processing\n    from ``Baillard et al. 2014``.\n\n    :param st: seismogram containing a seismic event\n    :type st: :py:class:`obspy.core.stream.Stream`\n    :param cat: catalog containing the event with previous picks\n    :type cat: obspy.core.event.Catalog\n    :param freqmin: Low end of frequency band used to prefilter the seismograms.\n        This value depends on the type of sensor.\n        The default value is optimized for 2:3 kHz accelerometers.\n    :param freqmax: High end of frequency band used to prefilter the seismograms.\n        This value depends on the type of sensor.\n        The default value is optimized for 2:3 kHz accelerometers.\n    :param pick_freqs: The smoothing frequencies for the smoothing\n        window applied to the CF3 function (this is used instead of Ns).\n    :param kurtosis_window: Windows lengths used to calculate CF3 up to P-S delay\n    :param CF3_tol: Maximum time to move a pick\n    :param SNR_window: Length of window in seconds in which the SNR is calculated before and after the pick\n    :returns:  :py:class:`obspy.core.event.Catalog` -- a new catalog containing a single event with a list of picks\n    \"\"\"\n\n    '''\n    if not cat.events:\n        return None\n\n    evt = cat.events[0]\n\n    if not evt['picks']:\n        return None\n\n    prevPicks = evt['picks']\n    '''\n    prevPicks = copy_picks_to_dict(picks)\n\n    # # clip the signal to the existing picks\n    # if prevPicks:\n    #   p_early = UTCDateTime(2100, 1, 1)\n    #   p_late = UTCDateTime(1970, 1, 1)\n\n    #   for picks in prevPicks:\n    #       if picks['time'] < p_early:\n    #           p_early = picks['time']\n    #       if picks['time'] > p_late:\n    #           p_late = picks['time']\n\n    #   p_early -= 25e-3\n    #   p_late += 25e-3\n    #   st.trim(starttime=p_early, endtime=p_late)\n\n    if pick_freqs is None:\n        pick_freqs = np.linspace(50, 1000, 20)\n    if kurtosis_window is None:\n        kurtosis_window = np.array([1, 2, 3]) * 1e-3\n\n    st.detrend('demean')\n    stations = np.unique([tr.stats.station for tr in st])\n\n    opicks = []\n    cfs = []\n    snrs = []\n    for station in stations:\n        # find the existing P and S picks for the current station\n        trs = st.select(station=station)\n        #print('kurtosis: sta:%s ntr=%d' % (station, len(trs)))\n        #if len(trs) < 3:\n            #continue\n        CF3 = np.zeros(len(trs.traces[0].data))\n\n        for ws in kurtosis_window:\n            for tr in trs:\n                cf1, cf2, cf3 = _CalculateCF1_3(tr, WS=ws,\n                                         BW=[freqmin, freqmax])\n                CF3 += cf3\n\n        cfs.append(CF3)\n\n        # TODO:\n        # Picker should probably work with no previous picks.\n        # If the current station has not been picked before, a new pick will not be generated.\n        # If the old pick has only either P or S, then only a new corresponding P or S will be generated, not both.\n        if not prevPicks:\n            continue\n\n        for phase in prevPicks[station]:\n            oldPick = prevPicks[station][phase]\n\n        #for oldPick in prevPicks:\n            #if oldPick['waveform_id'].station_code != station:\n                #continue\n\n            pick = _Pick_CF3(trs, CF3, oldPick['time'], pick_freqs, CF3_tol)\n            SNR = calculate_snr(trs, pick, SNR_window)\n            snrs.append(SNR)\n            opicks.append(make_pick(pick, oldPick['phase_hint'], trs.traces[0], SNR))\n\n            print('kurtosis: sta:%s pha:%s old_pick:%s new:%s' % (station,phase,oldPick.time,opicks[-1].time))\n\n    #catalog = event.Catalog()\n    #catalog.events.append(event.Event(picks=opicks))\n\n    #return catalog, cfs, snrs\n    return opicks\n\n\ndef snr_picker(st, picks, snr_dt=None, snr_window=(1e-3, 20e-3), filter=None):\n    \"\"\"\n    Function to improve the picks based on the SNR.\n    :param st: seismogram containing a seismic event\n    :type st: :py:class:`obspy.core.stream.Stream`\n    :param picks: list of microquake.core.event.Pick object\n    picks\n    :type picks: microquake.core.event.Catalog\n    :param snr_dt: Window in which the picks will be improved.\n    :param snr_window: Length of window in seconds in which the SNR is calculated\n    before and after the pick\n    :type snr_window: (tuple)\n    :returns:  Tuple comprising 1) a :py:class:`microquake.core.event.Catalog`\n    a new catalog containing a single event with a list of picks and 2) the SNR\n    \"\"\"\n\n    function_name = 'snr_picker'\n\n    filter_p = False\n    filter_s = False\n    if filter == 'S':\n        filter_p = True\n    elif filter == 'P':\n        filter_s = True\n\n    previous_picks = copy_picks_to_dict(picks)\n\n    if snr_dt is None:\n        snr_dt = np.linspace(-5e-3, 5e-3, 20)\n\n    st.detrend('demean')\n    stations = np.unique([tr.stats.station for tr in st])\n\n    opicks = []\n    snrs = []\n\n    pre_window_length = snr_window[0]\n    post_window_length = snr_window[1]\n\n    for station in stations:\n\n        tr = st.select(station=station).composite()[0]\n\n        if station not in previous_picks:\n            logger.warning('SNR_detect: station:[%s] has no previous picks'\n                           % station)\n            continue\n\n        for phase in previous_picks[station]:\n\n            if filter_p and phase == 'P':\n                continue\n            elif filter_s and phase == 'S':\n                continue\n\n            earliest_time = latest_time = None\n            if phase == 'S' and 'P' in previous_picks[station]:\n                delta = 1 / 2 * (previous_picks[station]['S'].time -\n                                 previous_picks[station]['P'].time)\n                earliest_time = previous_picks[station]['S'].time - delta\n\n            elif phase == 'S' and 'P' not in previous_picks[station]:\n                earliest_time = previous_picks[station]['S'].time - \\\n                                pre_window_length\n            elif phase == 'P' and 'S' in previous_picks[station]:\n                delta = 1 / 2 * (previous_picks[station]['S'].time -\n                                 previous_picks[station]['P'].time)\n                latest_time = previous_picks[station]['P'].time + delta\n            elif phase == 'P' and 'S' not in previous_picks[station]:\n                latest_time = previous_picks[station]['P'].time + \\\n                              post_window_length\n\n            old_pick = previous_picks[station][phase]\n\n            if earliest_time is None or earliest_time < tr.stats.starttime + \\\n                    .03:\n                earliest_time = tr.stats.starttime + .03\n\n            if latest_time is None or latest_time > tr.stats.endtime - .06:\n                latest_time = tr.stats.endtime - .06\n\n            tau = []\n            for dt in snr_dt:\n                taut = old_pick.time + dt\n\n                if earliest_time <= taut <= latest_time:\n                    tau.append(taut)\n\n            if not tau:\n                continue\n            if tau[0] <= tr.stats.starttime:\n                logger.error(\"Too early! tau[0]=%s <= tr.st=%s\"\n                             % (tau[0], tr.stats.starttime))\n                logger.error(\"earliest_time:%s latest_time:%s\"\n                             % (earliest_time, latest_time))\n\n                continue\n            if tau[-1] >= tr.stats.endtime:\n                logger.error(\"Too late! tau[-1]=%s >= tr.et=%s\"\n                             % (tau[-1], tr.stats.endtime))\n                continue\n\n            tau = np.array(tau)\n            indices = (tau - tr.stats.starttime) * tr.stats.sampling_rate\n            tmp = np.array([(taut, index, calculate_snr(tr, taut,\n                                                 pre_wl=pre_window_length,\n                                                 post_wl=post_window_length))\n                            for taut, index in zip(tau, indices)])\n\n        # MTH: this is a hack to try to force the solution close to the oldPick\n            alpha = 0\n            \"\"\"\n            alpha = 10.\n            for i, foo in enumerate(tmp):\n                time = foo[0]\n                snr = foo[1]\n                dt = np.abs(old_pick.time - foo[0])\n                #dt = np.abs(oldPick['time'] - foo[0])\n                scale = np.exp(-alpha * dt)\n                tmp[i,1] *= np.exp(-alpha * dt)\n                #print(time, dt, snr, scale, snr*scale, tmp[i,1])\n            \"\"\"\n\n            index = np.argmax(tmp[:, 2])\n            pick_time = tmp[index, 0]\n\n            import matplotlib.pyplot as plt\n\n            snr = calculate_snr(tr, pick_time, pre_wl=pre_window_length,\n                                post_wl=post_window_length)\n\n            # plt.plot(tmp[:, 1], tmp[:, 2] / np.max(tmp[:, 2]))\n            # plt.plot(tr.data / np.max(tr.data))\n            # plt.axvline(tmp[index, 1], color='r', ls='--')\n            # plt.xlim([tmp[0, 1], tmp[-1, 1]])\n            # plt.show()\n\n            # from ipdb import set_trace; set_trace()\n            logger.debug(\"%s: sta:%s [%s] time_diff:%0.3f SNR:%.2f\" %\n                         (function_name, station, phase, old_pick.time -\n                          pick_time, snr))\n\n            method_string = 'snr_picker preWl=%.3g postWl=%.3g alpha=%.1f' % \\\n                            (pre_window_length, post_window_length, alpha)\n            opicks.append(make_pick(pick_time, phase=old_pick.phase_hint,\n                                    wave_data=tr, snr=snr,\n                                    method_string=method_string,\n                                    resource_id=old_pick.resource_id))\n            snrs.append(snr)\n\n    return snrs, opicks\n\n\ndef calculate_snr(trace, pick, pre_wl=1e-3, post_wl=10e-3):\n    \"\"\"\n    input :\n    trs - Obspy stream\n    Pick Time - in Obspy UTCDateTime\n    preWl - Length of pre-window in seconds\n    postWl - Length of post-window in seconds\n\n    output:\n    SNR - Signal to noise ratio\n    \"\"\"\n\n    tr = trace\n\n    sr = tr.stats.sampling_rate\n    st = tr.stats.starttime\n    et = tr.stats.endtime\n    ps = int((pick - st) * sr)\n    n_pre = int(pre_wl * sr)\n    n_post = int(post_wl * sr)\n\n    if pick + post_wl > et:\n        energy_s = np.var(tr.data[ps:])\n    else:\n        energy_s = np.var(tr.data[ps:ps + n_post])\n\n    if pick - pre_wl < st:\n        energy_n = np.var(tr.data[:ps])\n    else:\n        energy_n = np.var(tr.data[ps - n_pre:ps])\n\n    if (energy_n == 0) | (energy_s == 0):\n        return 0\n\n    snr = 10 * np.log10(energy_s / energy_n)\n\n    return snr\n\n\ndef calculate_energy(stream, pick, Wl=5e-3):\n    sr = stream.traces[0].stats['sampling_rate']\n    st = stream.traces[0].stats['starttime']\n    Ps = int((pick - st) * sr)\n    Nb = int(Wl * sr)\n\n    EnergyS = np.sum([np.var(tr.data[Ps-Nb/4:Ps+3*Nb/2]) for tr in stream])\n\n    return EnergyS\n\n\ndef _CalculateCF1_3(tr1, BW=None, WS=1e-3):\n    if not BW:\n        BW = [100, 5000]\n    tr = tr1.copy()\n    tr.taper(max_percentage=0.5, type='cosine')\n    tr.filter(type='bandpass', freqmin=BW[0], freqmax=BW[1])\n\n    cf1 = kurtosis(tr, win=WS)\n    cf1 /= np.max(np.abs(cf1))\n\n    cf2 = np.zeros(cf1.shape)\n    dcf1 = np.diff(cf1)\n    dcf1[dcf1 < 0] = 0\n    cf2[0] = cf1[0]\n\n    for k in range(1, len(cf1)):\n        cf2[k] = cf2[k - 1] + dcf1[k - 1]\n\n    try:\n        cf3 = detrend(cf2, type='linear')\n    except:\n        cf3 = np.zeros(cf2.shape)\n\n    return cf1, cf2, cf3\n\n\ndef _Pick_STALTA(st, stalta, nphase):\n\n    # Finding the two largest maximum of the smoothed STALTA\n    # function. The two largest maximum are used as starting pick\n    # values.\n\n    sr = st.traces[0].stats['sampling_rate']\n    starttime = st.traces[0].stats['starttime']\n    endtime = st.traces[0].stats['endtime']\n\n    buf = (endtime - starttime) * 0.0001  # picks cannot be in the first and last 1% of the stream\n\n    mx = np.r_[True, stalta[1:] > stalta[:-1]] & np.r_[stalta[:-1] > stalta[1:], True]\n\n    i1 = np.nonzero(mx)[0]\n\n    i2 = np.argsort(stalta[i1])[::-1]\n    # i2 = i1\n\n    # EnergySs = np.array([calculate_energy(st, starttime + i1[k] / sr, Wl=5e-3) for k in i2])\n\n    # Eratio = EnergySs / np.max(EnergySs)\n    # ie = np.nonzero(Eratio > 0.05)[0]\n    # i2 = i2[ie]\n\n    picks = []\n    for k in range(0, nphase):\n        try:\n            picks.append(i1[i2[k]])\n        except:\n            pass\n            # logger.warning(\"_Pick_STALTA: station=%s phase=%d FAILED!\" % (st.traces[0].stats.station, k))\n            # picks.append(int((endtime - starttime)*sr))\n\n    # if len(picks) < nphase:\n    #   logger.warning(\"_Pick_STALTA: Not all phases were picked\")\n\n    picks = np.sort([starttime + p / sr for p in picks])\n    picks = np.array([p for p in picks if ((starttime + buf) < p < (endtime - buf))])\n\n    return picks\n\n\ndef _Pick_STALTA_refraction(st, stalta):\n\n    # Finding the two largest maximum of the smoothed STALTA\n    # function. The two largest maximum are used as starting pick\n    # values.\n\n    sr = st.traces[0].stats['sampling_rate']\n    starttime = st.traces[0].stats['starttime']\n    # endtime = st.traces[0].stats['endtime']\n\n    mx = np.r_[True, stalta[1:] > stalta[:-1]] & np.r_[stalta[:-1] > stalta[1:], True]\n\n    i1 = np.nonzero(mx)[0]\n\n    i2 = 0  # np.argsort(stalta[i1])[::-1]\n    # i2 = i1\n\n    # EnergySs = np.array([calculate_energy(st,starttime+i1[k]/sr,Wl = 5e-3) for k in i2])\n\n    # Eratio = EnergySs/np.max(EnergySs)\n    # ie = np.nonzero(Eratio > 0.05)[0]\n    # i2 = i2[ie]\n\n    picks = [i1[i2]]\n\n    picks = np.sort([starttime + p / sr for p in picks])\n\n    return picks\n\n\n# This should work with only one pick at a time regardless whether it is a P or S pick.\ndef _Pick_CF3(st, cf3, iniPick, f=np.linspace(50, 1000, 20), tol=10e-3):\n    \"\"\"\n    input :\n    st - stream object\n    cf3 - characteristic function number 3\n    f - list of frequency (used instead of the Ns parameter)\n    tol - maximum time to move a pick\n    \"\"\"\n\n    sr = st.traces[0].stats['sampling_rate']\n    ST = st.traces[0].stats['starttime']\n    # first = True\n    CF3_2 = np.hstack((cf3, cf3[::-1])) - cf3[0]\n    CF3_2TR = Trace(data=CF3_2, header=st.traces[0].stats)  # ??\n\n    Pick = int((iniPick - ST) * sr)  # initial pick in sample\n    Pick_stalta = Pick\n\n    for freq in f:\n        # sigma = sfreq/(2*np.pi*freq)\n        CF3_2TR_F = CF3_2TR.copy()\n        CF3_2TR_F.filter('lowpass', freq=freq)\n        # CF3_f = gaussian_filter1d(CF3,sigma=sigma,mode='reflect')\n        CF3_f = CF3_2TR_F.data\n        #CF3_f = CF3_f[:len(CF3_f) / 2]\n        CF3_f = CF3_f[:int(len(CF3_f) / 2)]\n        s = np.r_[True, CF3_f[1:] < CF3_f[:-1]] & np.r_[CF3_f[:-1] < CF3_f[1:], True]\n        indices = np.nonzero(s)[0]\n        CF4 = np.zeros(CF3_f.shape)\n        for i in indices[0:-1]:\n            CF4[i] = CF3_f[i] - CF3_f[i + 1]\n\n        indices = np.nonzero(CF4)[0]\n\n        try:\n            pick_tmp = indices[np.argmin(np.abs(Pick - indices[indices <= Pick_stalta]))]\n        except:\n            pick_tmp = Pick\n\n        if np.abs(pick_tmp - Pick_stalta) <= (tol * sr):\n                Pick = pick_tmp\n\n    # Return pick time in samples\n    pick = ST + Pick / sr\n    return pick\n\n\n@deprecated\ndef triggersByGroup(st, trigger_type=\"recstalta\", group=\"station\", thr_on=3, thr_off=2,\n    thr_coincidence_sum=1, sta=0.01, lta=1):\n\n    # Accentuate peaks - bug below, skip for now\n    # for i,tr in enumerate(st):\n    #   st2.traces[0].data = tr.data**2*np.sign(tr.data)\n\n    gp = np.array([])\n\n    if group == \"all\":\n        # one trigger for all stations\n        trig = coincidence_trigger(trigger_type, thr_on, thr_off, st,\n                                   thr_coincidence_sum, sta=sta, lta=lta, details=True)\n\n    elif group == \"station\":\n        # one trigger per station\n        trig = []\n\n        SensorList = []\n        for tr in st:\n            SensorList.append(tr.stats.station)\n        SensorList = np.unique(SensorList)\n\n        for k, S in enumerate(SensorList):\n            st2 = st.select(station=S)\n            try:\n                trigtmp = coincidence_trigger(trigger_type, thr_on, thr_off,\n                st2, thr_coincidence_sum, sta=sta, lta=lta, details=True)\n            except:\n                trigtmp = []\n\n            # plot - debug\n            # for tr in st2:\n            #   cft = classic_sta_lta(tr.data, int(sta * tr.stats.sampling_rate), int(lta * tr.stats.sampling_rate))\n            #   plotTrigger(tr, cft, thr_on, thr_off)\n            # rpdb.set_trace()\n\n            if k == 0:\n                trig = trigtmp\n            else:\n                trig = trig + trigtmp\n\n            gp = np.hstack((gp, np.ones(len(trigtmp)) * k))\n    else:\n\n        # individual recursive_sta_lta for each trace\n        trig = []\n        pass\n\n    return trig, gp\n\n\n@deprecated\ndef associateTriggers(trig, gp, tolerance=25e-3):\n\n    tme = np.sort([trg['time'] for trg in trig])\n\n    trigger = []\n\n    # at least 2 sensors need to be in the same tolerance window\n    indices2 = np.argsort([trg['time'] for trg in trig])\n    gp = gp[indices2]\n    trig = np.array(trig)\n    trig = trig[indices2]\n\n    k = 0\n    while k < len(tme):\n        indices = np.nonzero((tme - tme[k] > 0) & (tme - tme[k] < tolerance))[0]\n        if len(indices) > 0:\n            k = indices[-1]\n            gp2 = gp[indices]\n            if len(np.unique(gp2)) > 1:\n                trigs = trig[indices]\n                best_trig = np.argmax([t['cft_peak_wmean'] for t in trigs])\n                best_trig = trigs[best_trig]\n\n                data = {'mean_time': best_trig['time'],\n                        'data': trigs}\n\n                trigger.append(data)\n        else:\n                k += 1\n\n    return trigger\n\n\n@deprecated\ndef picksFromTriggers(st, trg, method=\"by_triggers\", tolerance=20e-3, clip_stream=True, filter_stream=True):\n\n    picks = []\n\n    if method == \"all\":\n        SensorList = []\n        for tr in st:\n            SensorList.append(tr.stats.station)\n\n        SensorList = np.unique(SensorList)\n        for S in SensorList:\n            st2 = st.select(station=S)\n\n            picks2 = compute_picks(st2, trg, tolerance, clip_stream, filter_stream)\n            if picks2 is not None:\n                picks = np.hstack((picks, picks2))\n\n    elif method == \"by_triggers\":\n        for tg in trg:\n            SensorList = np.unique(tg['stations'])\n            for S in SensorList:\n                st2 = st.select(station=S)\n\n                picks2 = compute_picks(st2, tg, tolerance, clip_stream, filter_stream)\n                if picks2 is not None:\n                    picks = np.hstack((picks, picks2))\n\n    return picks\n\n\n@deprecated\ndef compute_picks(st2, trg, tolerance=20e-3, clip_stream=True, filter_stream=True):\n\n    picks = []\n\n    tg_time = trg['time']\n    if clip_stream:\n        st = st2.trim(tg_time - tolerance, tg_time + tolerance)\n        if filter_stream:\n            st = st.filter_stream(lf=100, hf=1000, copy=False)\n    else:\n        if filter_stream:\n            st = st2.filter_stream(lf=100, hf=1000, copy=True)\n        else:\n            st = st2\n\n    starttime = st.traces[0].stats.starttime\n    # starttime2 = st2.traces[0].stats.starttime\n    sr = st.traces[0].stats.sampling_rate\n    station_type = st.traces[0].stats.station_type\n\n    try:\n        if len(st) < 3:\n            data = st.traces[0].data ** 2 * np.sign(st.traces[0].data)\n        else:\n            data = (st.traces[0].data ** 2 +\n                    st.traces[1].data ** 2 +\n                    st.traces[2].data ** 2) * \\\n                    np.sign(st.traces[0].data)\n        i = np.argmax(np.abs(data))\n        data = data / data[i]\n\n    except:\n        return\n\n    if 'A' in station_type:\n        # Parameters originally estimated for Northparkes TBM project (which had a sampling rate of around 5000) -> Correction x2\n        pickBaer = pk_baer(reltrc=data, samp_int=1, tdownmax=2, tupevent=40, thr1=10, thr2=20, preset_len=10, p_dur=10)\n        # pickBaer = pk_baer(reltrc=data, samp_int=1, tdownmax=16, tupevent=60, thr1=10, thr2=20, preset_len=20, p_dur=20)\n    else:\n        # Parameters originally estimated for Northparkes TBM project (which had a sampling rate of around 2500) -> Correction x4\n        pickBaer = pk_baer(reltrc=data, samp_int=1, tdownmax=4, tupevent=10, thr1=10, thr2=20, preset_len=10, p_dur=10)\n        # pickBaer = pk_baer(reltrc=data, samp_int=1, tdownmax=32, tupevent=40, thr1=10, thr2=20, preset_len=10, p_dur=10)\n\n    # plot - debug\n    # if st.traces[0].stats.station == '14_A1':\n    # trg_time = (trg['time'] - starttime)*sr\n    # diff_samples = (starttime - starttime2)*sr\n    # num_traces = len(st)\n    # plt.close()\n    # # for k, (tr, tr2) in enumerate(zip(st, st3.select(station=st.traces[0].stats.station))):\n    # for k, (tr, tr2) in enumerate(zip(st, st2)):\n    #   trace.plot_traces(tr, k, num_traces*2, pickSample=[trg_time, pickBaer[0]])\n    #   trace.plot_traces(tr2, k+num_traces, num_traces*2, pickSample=[trg_time+diff_samples, pickBaer[0]+diff_samples])\n    # plt.show()\n\n    if pickBaer[0] < 10:  # pick can't occur in the first N samples\n        return\n\n    Noise = np.var(data[0:pickBaer[0]])\n    Signal = np.var(data[pickBaer[0]:pickBaer[0] + 50])\n    # SNR = 10*np.log((Signal-Noise)/(Noise+1e-10))\n    SNR = 10 * np.log10(Signal / (Noise + 1e-10))\n    # print SNR, pickBaer\n\n    if SNR < 3:\n        return\n\n    t = starttime + pickBaer[0] / sr\n\n    for tr in st:\n        this_pick = event.Pick()\n        this_pick.time = t\n        this_pick.phase_hint = 'P'\n        this_pick.waveform_id = event.WaveformStreamID(\n            network_code=tr.stats.network,\n            station_code=tr.stats.station,\n            location_code=tr.stats.location,\n            channel_code=tr.stats.channel)\n        this_pick.evaluation_mode = 'automatic'\n        # this_pick.creation_info = creation_info\n        if 'E' in pickBaer[1]:\n            this_pick.onset = 'emergent'\n        if 'I' in pickBaer[1]:\n            this_pick.onset = 'impulsive'\n        this_pick.evaluation_status = 'preliminary'\n\n        if len(st) < 3:\n            if 'U' in pickBaer[1]:\n                this_pick.polarity = 'positive'\n            elif 'D' in pickBaer[1]:\n                this_pick.polarity = 'negative'\n        else:\n            d_0 = tr.data[pickBaer[0]]\n            d_1 = tr.data[pickBaer[0] + 3]\n            if d_1 > d_0:\n                this_pick.polarity = 'positive'\n            else:\n                this_pick.polarity = 'negative'\n\n        this_pick.SNR = SNR\n\n        picks.append(this_pick)\n\n    return picks\n\n\ndef automatic_picking(st_in, site, params):\n    \"\"\"\n    Automatic picking algorithm\n    :param st_in: time series data\n    :type st_in: microquake.core.Stream\n    :param site: an object containing information on the station\n    :type site: microquake.core.station.Site\n    :param params: dictionnary containing the control parameters for the\n    automatic picker\n    :type params: AttribDict\n    :return: returns an event\n    :rtype: obspy.core.event.Event\n    \"\"\"\n\n    st = st_in.copy()\n\n    if not ('picker' in params.keys()):\n        logger.error('params is not well formed... exiting')\n        return\n\n    #NLL_BASE = params.nll.NLL_BASE\n    nll_opts_auto = nll.init_nlloc_from_params(params)\n    #nll_opts_auto = nll.NLL(params.project_code, suffix=nll_suffix, base_folder=NLL_BASE)\n\n    pcks = []\n\n    try:\n        Polarity_kwargs = params.picker.polarity\n    except:\n        logger.warning('Probably no parameter for polarity measurements in '\n                       'the control file')\n        Polarity_kwargs = None\n\n\n    for stname in st.unique_stations():\n        for net in site.select(station=stname).networks:\n            if net:\n                curr_sta = net.stations[0]\n                stype = curr_sta.sensor_type\n\n                try:\n                    STALTA_picker_kwargs = params.picker.STALTA_picker[stype]\n                except:\n                    logger.warning('Probably no parameter for STALTA_picker '\n                                   'in the control file for %s...' %stype)\n                    STALTA_picker_kwargs = None\n\n                try:\n                    SNR_picker_kwargs = params.picker.SNR_picker[stype]\n                except:\n                    logger.warning('Probably no parameter for SNR_picker in '\n                                   'the control file for %s...' %stype)\n                    SNR_picker_kwargs = None\n\n\n        st_station = st.select(station=stname)\n        cat_STALTA1, cfs, snrs = STALTA_picker(st_station,\n                                               **STALTA_picker_kwargs)\n\n        try:\n            cat_SNR1, snrs = SNR_picker(st_station, cat_STALTA1,\n                                        **SNR_picker_kwargs)\n        except:\n            return\n\n        snr_th = params.picker[stype].SNR_threshold\n\n        for (pk, snr) in zip(cat_SNR1.events[0].picks, snrs):\n            if snr > snr_th:\n                pcks.append(pk)\n\n    if (len(pcks) < params.picker.min_picks):\n        logger.info('too few picks ... exiting')\n        return\n\n    cat_auto1 = event.Catalog(cat_SNR1)\n    cat_auto1.events[0].picks = pcks\n\n    cat_filt1 = event.Catalog(cat_auto1)\n    # cat_filt2.events[0].picks = picks\n\n    # we remove bad picks only from uniaxials\n    while True:\n        # creating an Origin and associating pick to arrivals\n        origin = event.Origin()\n        cat_filt1[0].preferred_origin_id = origin.resource_id.id\n        for k, pick in enumerate(cat_filt1[0].picks):\n            arrival = event.Arrival()\n            arrival.pick_id = pick.resource_id.id\n            arrival.phase = pick.phase_hint\n            origin.arrivals.append(arrival)\n\n        cat_filt1[0].origins.append(origin)\n        cat_filt1[0].preferred_origin_id = origin.resource_id.id\n        cat_auto = nll_opts_auto.run_event(cat_filt1[0], status='preliminary')\n        if not cat_auto:\n            logger.error('unable to locate the event')\n            return\n        res = np.abs([arr.time_residual for arr in cat_auto.events[0].origins[0].arrivals])\n\n        if (np.max(res) < params.picker.rms_residual_threshold) or (len(res) \\\n            < params.picker.min_picks):\n            break\n        del cat_filt1.events[0].picks[np.argmax(res)]\n\n    if (len(res) < params.picker.min_picks):\n        return\n\n    res = np.abs([arr.time_residual for arr in cat_auto.events[0].origins[0].arrivals])\n\n    g = lambda x: x ** 2\n    rms_residual = np.sqrt(np.mean(g(res)))\n\n    uncertainty = cat_auto.events[0].origins[0].origin_uncertainty.confidence_ellipsoid.semi_major_axis_length\n    if (rms_residual > params.picker.rms_residual_threshold) \\\n        or (uncertainty > params.picker.uncertainty_threshold):\n        cat_auto.events[0].origins[0].evaluation_status = 'rejected'\n    else:\n        cat_auto.events[0].origins[0].evaluation_status = 'preliminary'\n\n    return cat_auto[0]\n\n\ndef eventCategorization_polarity(catalog, site):\n    \"\"\"\n    determine the event category by looking at the polarity of the first motion.\n    It is assumed that blast will generate mostly positive first motion whereas seismic event\n    will generate mixte first motion\n\n    :param st: seismograms\n    :type st: obspy.core.Stream or microquake.core.Stream\n    :param catalog: events catalog\n    :type catalog: obspy.core.event.Catalog or microquake.core.event.Catalog\n    :param site: information on network\n    :type site: microquake.core.data.station.Site\n    \"\"\"\n\n    catalog = event.Catalog(cat=catalog)\n    for evi, evt in enumerate(catalog.events):\n        picks = evt.picks\n        polarity = []\n        for origin in evt.origins:\n            evloc = np.array([origin.x, origin.y, origin.z])\n            for pick in picks:\n                if not pick.polarity:\n                    continue\n                if pick.polarity.lower() == \"positive\":\n                    pick_polarity = 1\n                elif pick.polarity.lower() == 'negative':\n                    pick_polarity = -1\n                else:\n                    continue\n\n                sta_code = pick.waveform_id.station_code\n                station = site.stations(station=sta_code)[0]\n                stloc = station.loc\n                ev_st_vect = stloc - evloc\n                for channel in station:\n                    if not np.any(channel.orientation):\n                        continue\n\n                    polarity.append(np.sign(np.dot(channel.orientation, ev_st_vect)))\n\n        polarity = np.array(polarity)\n        if len(polarity[polarity == 1]) >= 0.85 * len(polarity):\n            catalog.events[evi].event_type = \"mining explosion\"\n        else:\n            catalog.events[evi].event_type = \"induced or triggered event\"\n\n        catalog.events[evi].event_type_certainty = \"suspected\"\n\n    return catalog\n\n\n\n", "meta": {"hexsha": "e8fb494d5ab90bbf265e45e43767558de7f2ce45", "size": 42061, "ext": "py", "lang": "Python", "max_stars_repo_path": "microquake/waveform/pick.py", "max_stars_repo_name": "jeanphilippemercier/microquake", "max_stars_repo_head_hexsha": "0b9d07be11eddd64619e46939c320487531602a3", "max_stars_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "microquake/waveform/pick.py", "max_issues_repo_name": "jeanphilippemercier/microquake", "max_issues_repo_head_hexsha": "0b9d07be11eddd64619e46939c320487531602a3", "max_issues_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "microquake/waveform/pick.py", "max_forks_repo_name": "jeanphilippemercier/microquake", "max_forks_repo_head_hexsha": "0b9d07be11eddd64619e46939c320487531602a3", "max_forks_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3453781513, "max_line_length": 129, "alphanum_fraction": 0.5923539621, "include": true, "reason": "import numpy,from scipy", "num_tokens": 11229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3174262720448507, "lm_q1q2_score": 0.15995305717144281}}
{"text": "\"\"\"\nModel steps for lubricated contacts\n\"\"\"\nimport typing\nimport warnings\nfrom collections.abc import Sequence\nfrom numbers import Number\n\nimport numpy as np\nimport slippy\n\nfrom slippy.core import _NonDimensionalReynoldSolverABC\nfrom ._model_utils import get_gap_from_model\nfrom ._step_utils import make_interpolation_func, solve_normal_loading\nfrom slippy.core.influence_matrix_utils import plan_convolve\nfrom .steps import _ModelStep\nfrom slippy.core.materials import _IMMaterial\n\n__all__ = ['IterSemiSystem']\n\n\nclass IterSemiSystem(_ModelStep):\n    \"\"\"\n    Lubrication solutions by iteration of semi systems\n\n    Parameters\n    ----------\n    step_name: str\n        An identifying name for the step used for errors and outputs\n    reynolds_solver: _NonDimensionalReynoldSolverABC\n        A reynolds solver object which will be used to solve for pressures\n    rolling_speed: float or Sequence of float, optional (None)\n        The mean speed of the surfaces (u1+u2)/2 parameters can be:\n\n        * A constant (float) value, indicating a constant rolling speed.\n        * A two element sequence of floats, indicating the the start and finish rolling speed, if this is used, the\n          movement_interpolation_mode will be used to generate intermediate values\n        * A 2 by n array of n rolling speed and n time values normalised to a 0-1 scale. array[0] should be\n          position values and array[1] should be time values, time values must be between 0 and 1. The\n          movement_interpolation_mode will be used to generate intermediate values\n    number_of_steps: int\n        The number of sub steps the problem will be split into, together with the time_period this controls the duration\n        of the time steps used\n    no_time: bool, optional (False)\n        Set to true if there is no time dependence and the time steps can be solved in any order (no permanent changes\n        between steps such as plastic deformation or heat generation), if True the model will be solved more efficiently\n    time_period: float, optional (1.0)\n        The total time period of this model step, used for solving sub-models and writing outputs\n    off_set_x, off_set_y: float or Sequence of float, optional (0.0)\n        The off set between the surfaces in the x and y directions, this can be a relative off set or an absolute off\n        set, controlled by the relative_loading parameter:\n\n        * A constant (float) value, indicating a constant offset between the surfaces (no relative movement of profiles)\n        * A two element sequence of floats, indicating the the start and finish offsets, if this is used, the\n          movement_interpolation_mode will be used to generate intermediate values\n        * A 2 by n array of n absolute position values and n time values normalised to a 0-1 scale. array[0] should be\n          position values and array[1] should be time values, time values must be between 0 and 1. The\n          movement_interpolation_mode will be used to generate intermediate values\n    interference, normal_load: float or Sequence of float, optional (None)\n        The interference and normal load between the surfaces, only one of these can be set (the other will be solved\n        for) setting neither keeps the interference as it is at the start of this model step. As above for the off sets,\n        either of these parameters can be:\n\n        * A constant (float) value, indicating a constant load/ interference between the surfaces.\n        * A two element sequence of floats, indicating the the start and finish load. interference, if this is used, the\n          movement_interpolation_mode will be used to generate intermediate values\n        * A 2 by n array of n absolute position values and n time values normalised to a 0-1 scale. array[0] should be\n          position values and array[1] should be time values, time values must be between 0 and 1. The\n          movement_interpolation_mode will be used to generate intermediate values\n    relative_loading: bool, optional (False)\n        If True the load or displacement and off set will be applied relative to the value at the start of the step,\n        otherwise the absolute value will be used. eg, if the previous step ended with a load of 10N and this step ramps\n        from 0 to 10N setting relative_loading to True will ramp the total load form 10 to 20N over this step.\n    movement_interpolation_mode: str or int, optional ('linear')\n        Any valid input to scipy.interpolate.interp1d as the 'kind' parameter, using 'nearest', 'previous' or 'next'\n        will cause a warning. This parameter controls how the offset and loading is interpolated over the step\n    profile_interpolation_mode: {'nearest', 'linear'}, optional ('nearest')\n        Used to generate the grid points for the second surface at the location of the grid points for the first\n        surface, nearest ensures compatibility with sub models which change the profile, if the grid spacings of the\n        surfaces match\n    periodic_geometry: bool, optional (False)\n        If True the surface profile will warp when applying the off set between the surfaces\n    periodic_axes: tuple, optional ((False, False))\n        For each True value the corresponding axis will be solved by circular convolution, meaning the result is\n        periodic in that direction. NOTE: this only controls the deformation result from the materials, ensure that the\n        reynolds equation solver used supports periodic solutions and is set to produce a periodic solution to the\n        pressure equation. Additionally, ensure that the axes of periodicity match.\n    periodic_im_repeats: tuple, optional (1,1)\n        The number of times the influence matrix should be wrapped along periodic dimensions, only used if at least one\n        of periodic axes is True. This is necessary to ensure truly periodic behaviour, no physical limit exists\n    max_it_pressure: int, optional (100)\n        The maximum number of iterations in the fluid pressure calculation loop\n    rtol_pressure: float, optional (1e-7)\n        The relative tolerance for the fluid pressure calculation loop\n    max_it_interference: int, optional (100)\n        The maximum number of iterations in the loop that finds the interference between the surfaces\n    rtol_interference: float, optional (1e-7)\n        The relative tolerance on the total load (integral of the pressure solution minus the applied load)\n    initial_guess: {callable, 'previous', list}, optional ('previous')\n        The initial guess for the interference, and/ or pressure profile between the surfaces, any callable will be\n        called with the contact model and the undeformed nd_gap as positional arguments, it must return the interference\n        and the pressure profile. 'previous' will use the result(s) from the previous step, if results are not found the\n        interference and pressure profile will be set to 0. Can also be a 2 element list, the first element being the\n        interference and the second being the pressure profile as an array, if this is the wrong shape zeros wil be\n        used.\n    no_update_warning: bool, optional (True)\n        Change to False to suppress warning given when no movement or loading changes are specified\n\n    Notes\n    -----\n    The solver iterates through a 'pressure loop' until the solution has converged to a set of pressure values, then the\n    loading is checked, if the total pressure is too low the surfaces are brought closer together. This is continued\n    until the total load has converged to the set value. This outer loop is referred to as the interference loop.\n\n    Examples\n    --------\n    In this example we will model smooth surface EHL with a non newtonian fluid:\n\n    >>> import slippy\n    >>> slippy.CUDA = False  # Note: we are using a reynolds solver which does not currently support the CUDA back end\n    >>> import slippy.surface as s\n    >>> import slippy.contact as c\n    >>>\n    >>> radius = 0.01905       # The radius of the ball\n    >>> load = 800             # The load on the ball in N\n    >>> rolling_speed = 4      # The rolling speed in m/s (The mean speed of the surfaces)\n    >>> youngs_modulus = 200e9 # The youngs modulus of the surfaces\n    >>> p_ratio = 0.3          # The poission's ratio of the surfaces\n    >>> grid_size = 65         # The number of points in the descretisation grid\n    >>> eta_0 = 0.096          # Coefficient in the roelands pressure-viscosity equation\n    >>> roelands_p_0 = 1/5.1e-9# Coefficient in the roelands pressure-viscosity equation\n    >>> roelands_z = 0.68      # Coefficient in the roelands pressure-viscosity equation\n    >>>\n    >>> # Solving the hertzian contact to get the domain size and the initial guess\n    >>> hertz_result = c.hertz_full([radius, radius], [float('inf'), float('inf')],\n    >>>                             [youngs_modulus, youngs_modulus],\n    >>>                             [p_ratio, p_ratio], load)\n    >>> hertz_pressure = hertz_result['max_pressure']\n    >>> hertz_a = hertz_result['contact_radii'][0]\n    >>> hertz_deflection = hertz_result['total_deflection']\n    >>> hertz_pressure_function = hertz_result['pressure_f']\n    >>>\n    >>> # make the surfaces\n    >>> ball = s.RoundSurface((radius,)*3, shape = (grid_size, grid_size),\n    >>>                       extent=(hertz_a*4,hertz_a*4), generate = True)\n    >>> flat = s.FlatSurface()\n    >>>\n    >>> # assigning materials\n    >>> steel = c.Elastic('steel', {'E' : youngs_modulus, 'v' : p_ratio})\n    >>> ball.material = steel\n    >>> flat.material = steel\n    >>>\n    >>> # make the non newtonian fluid\n    >>> oil = c.Lubricant('oil') # Making a lubricant object to contain our sub models\n    >>> oil.add_sub_model('nd_viscosity', c.lubricant_models.nd_roelands(eta_0, roelands_p_0,\n    >>>                                                                  hertz_pressure, roelands_z))\n    >>> oil.add_sub_model('nd_density', c.lubricant_models.nd_dowson_higginson(hertz_pressure))\n    >>>\n    >>> # make the contact model\n    >>> my_model = c.ContactModel('lubrication_test', ball, flat, oil)\n    >>>\n    >>> # make a reynolds solver\n    >>> reynolds = c.UnifiedReynoldsSolver(time_step = 0,\n    >>>                                    grid_spacing = ball.grid_spacing,\n    >>>                                    hertzian_pressure = hertz_pressure,\n    >>>                                    radius_in_rolling_direction=radius,\n    >>>                                    hertzian_half_width=hertz_a,\n    >>>                                    dimentional_viscosity=eta_0,\n    >>>                                    dimentional_density=872)\n    >>>\n    >>> # Find the hertzian pressure distribution as an initial guess\n    >>> X, Y = ball.get_points_from_extent()\n    >>> X, Y = X + ball._total_shift[0], Y + ball._total_shift[1]\n    >>> hertzian_pressure_dist = hertz_pressure_function(X, Y)\n    >>>\n    >>> # Making the step\n    >>> step = c.IterSemiSystem('main', reynolds, rolling_speed, 1, no_time=True, normal_load=load,\n    >>>                         initial_guess=[hertz_deflection, hertzian_pressure_dist],\n    >>>                         relaxation_factor=0.05, max_it_interference=3000)\n    >>>\n    >>> # Adding the step to the contact model\n    >>> my_model.add_step(step)\n    >>>\n    >>> # solve the model:\n    >>> state = my_model.solve()\n\n    \"\"\"\n    \"The minimum number of iterations in the reynolds solving loop\"\n    _dh = 0\n    \"The base change in height\"\n    _interferences = list()\n    _load_errors = list()\n\n    _reynolds: typing.Optional[_NonDimensionalReynoldSolverABC] = None\n    initial_guess: typing.Optional[typing.Union[typing.Callable, list, str]]\n\n    def __init__(self, step_name: str, reynolds_solver: _NonDimensionalReynoldSolverABC,\n                 rolling_speed: typing.Union[float, typing.Sequence[float]],\n                 number_of_steps: int = 1,\n                 no_time: bool = False, time_period: float = 1.0,\n                 off_set_x: typing.Union[float, typing.Sequence[float]] = 0.0,\n                 off_set_y: typing.Union[float, typing.Sequence[float]] = 0.0,\n                 interference: typing.Union[float, typing.Sequence[float]] = None,\n                 normal_load: typing.Union[float, typing.Sequence[float]] = None,\n                 relative_loading: bool = False,\n                 movement_interpolation_mode: str = 'linear',\n                 profile_interpolation_mode: str = 'nearest',\n                 periodic_geometry: bool = False, periodic_axes: tuple = (False, False),\n                 periodic_im_repeats: tuple = (1, 1),\n                 max_it_pressure: int = 5000, rtol_pressure: float = 2e-6,\n                 max_it_interference: int = 5000,\n                 rtol_interference: float = 1e-4,\n                 relaxation_factor: float = 0.1,\n                 initial_guess: typing.Union[typing.Callable, str, typing.Sequence] = 'previous',\n                 no_update_warning: bool = True):\n\n        self._adjust_height_every_step = True\n        self._initial_guess = initial_guess\n        self._no_time = no_time\n        self.total_time = time_period\n        self._relative_loading = relative_loading\n        self.profile_interpolation_mode = profile_interpolation_mode\n        self._periodic_profile = periodic_geometry\n        self._periodic_axes = periodic_axes\n        self._periodic_im_repeats = periodic_im_repeats\n        self._max_it_pressure = max_it_pressure\n        self._max_it_interference = max_it_interference\n        self._rtol_pressure = rtol_pressure\n        self._rtol_interference = rtol_interference\n        self._nd_max_pressure = None\n\n        self.reynolds = reynolds_solver\n\n        if relaxation_factor <= 0 or relaxation_factor > 1:\n            raise ValueError(\"Relaxation factor must be greater than 0 and less than or equal to 1\")\n        self._relaxation_factor = relaxation_factor\n\n        self.time_step = time_period / number_of_steps\n        self.number_of_steps = number_of_steps\n\n        self.update = set()\n\n        if not isinstance(off_set_x, Number) or not isinstance(off_set_y, Number):\n            if no_time:\n                raise ValueError(\"Can not have no time dependence and sliding contact\")\n            off_set_x = [off_set_x] * 2 if isinstance(off_set_x, Number) else off_set_x\n            off_set_y = [off_set_y] * 2 if isinstance(off_set_y, Number) else off_set_y\n            off_set_x_func = make_interpolation_func(off_set_x, movement_interpolation_mode, 'relative_off_set_x')\n            off_set_y_func = make_interpolation_func(off_set_y, movement_interpolation_mode, 'relative_off_set_y')\n            self._off_set_upd = lambda time: np.array([off_set_x_func(time), off_set_y_func(time)])\n            self.update.add('off_set')\n            self.off_set = None\n        else:\n            self.off_set = np.array([off_set_x, off_set_y])\n\n        if normal_load is not None and interference is not None:\n            raise ValueError(\"Both normal_load and interference are set, only one of these can be set\")\n        if normal_load is None and interference is None:\n            if relative_loading:\n                interference = 0\n            else:\n                raise ValueError(\"Cannot have no set load or interference and not relative loading, set either the\"\n                                 \"normal load, normal interference or change relative_loading to True\")\n\n        if isinstance(rolling_speed, Number):\n            self.rolling_speed = rolling_speed\n        else:\n            self.rolling_speed = None\n            self._rolling_speed_upd = make_interpolation_func(rolling_speed, movement_interpolation_mode,\n                                                              'rolling_speed')\n            self.update.add('rolling_speed')\n\n        if normal_load is not None:\n            if isinstance(normal_load, Number):\n                self.normal_load = normal_load\n            else:\n                self.normal_load = None\n                self._normal_load_upd = make_interpolation_func(normal_load, movement_interpolation_mode,\n                                                                'normal_load')\n                self.update.add('normal_load')\n            self.load_controlled = True\n        else:\n            self.normal_load = None\n\n        if interference is not None:\n            if isinstance(interference, Number):\n                self.interference = interference\n            else:\n                self.interference = None\n                self._interference_upd = make_interpolation_func(interference, movement_interpolation_mode,\n                                                                 'interference')\n                self.update.add('interference')\n            self.load_controlled = False\n\n        if not self.update and no_update_warning:\n            warnings.warn(\"Nothing set to update\")\n\n        self._provides = None\n\n        base_provides = {'just_touching_gap', 'surface_1_points', 'surface_2_points', 'off_set', 'time_step', 'time',\n                         'interference', 'total_normal_load', 'pressure', 'nd_pressure', 'loads',\n                         'surface_1_displacement', 'surface_2_displacement', 'total_displacement', 'converged',\n                         'gap', 'nd_gap', 'rolling_speed'}\n\n        provides = base_provides.union(reynolds_solver.provides).union(reynolds_solver.requires)\n\n        super().__init__(step_name, time_period, provides)\n\n    @property\n    def provides(self):\n        results_set = self._provides\n        if self.model is None:\n            return results_set\n        if self.model.lubricant_model is None:\n            return results_set\n        return results_set.union(set(self.model.lubricant_model.sub_models.keys()))\n\n    @provides.setter\n    def provides(self, value):\n        if self._provides is None:\n            self._provides = value\n        else:\n            raise ValueError(\"The provides property can only be set during instantiation\")\n\n    @property\n    def reynolds(self):\n        return self._reynolds\n\n    @reynolds.setter\n    def reynolds(self, value):\n        if isinstance(value, _NonDimensionalReynoldSolverABC):\n            self._reynolds = value\n        else:\n            raise ValueError(\"Cannot set a non reynolds solver object as the reynolds solver, to use custom solvers\"\n                             f\"first subclass _NonDimensionalReynoldSolverABC from slippy.core, received \"\n                             f\"type was {type(value)}\")\n\n    @reynolds.deleter\n    def reynolds(self):\n        self._reynolds = None\n\n    def data_check(self, current_state):\n        if self.reynolds is None:\n            _data_check_error_or_warn(f\"Reynolds solver not set for step {self.name}\")\n        if self.model.lubricant_model is None:\n            _data_check_error_or_warn(f\"Step {self.name} requires a lubricant to be defined in the contact model\")\n        if (self.reynolds.requires - set(self.model.lubricant_model.sub_models)) - {'nd_gap', 'nd_pressure'}:\n            _data_check_error_or_warn(f\"Reynolds solve in step {self.name} has requirements which are not provided by\"\n                                      f\" the lubricant sub models:\\n\"\n                                      f\"Requires: {self.reynolds.requires}\\n\"\n                                      f\"Sub models provide: {set(self.model.lubricant_model.sub_models)}\")\n\n    def update_movement(self, relative_time, original):\n        for name in self.update:\n            if self._relative_loading:\n                self.__setattr__(name, original[name] + self.__getattribute__(f'_{name}_upd')(relative_time))\n            else:\n                self.__setattr__(name, self.__getattribute__(f'_{name}_upd')(relative_time))\n\n    def solve(self, previous_state: dict, output_file):\n        cuda = slippy.CUDA\n        slippy.CUDA = False\n        start_time = previous_state['time']\n        gs = self.model.surface_1.grid_spacing\n\n        im_mats = (isinstance(self.model.surface_1.material, _IMMaterial) and\n                   isinstance(self.model.surface_2.material, _IMMaterial))\n        surf_1_material = self.model.surface_1.material\n        surf_2_material = self.model.surface_2.material\n\n        for s in self.sub_models:\n            s.no_time = self._no_time\n\n        relative_time = np.linspace(0, 1, self.number_of_steps+1)[1:]\n        just_touching_gap = None\n\n        original = dict()\n\n        if self._relative_loading:\n            original['normal_load'] = previous_state['total_normal_load'] if 'total_normal_load' in previous_state \\\n                else 0\n            original['interference'] = previous_state['interference'] if 'interference' in previous_state else 0\n            original['off_set'] = np.array(previous_state['off_set']) if 'off_set' in previous_state else \\\n                np.array([0, 0])\n\n        previous_gap_shape = None  # shape of just touching gap array\n\n        for i in range(self.number_of_steps):\n            self.update_movement(relative_time[i], original)\n            self.reynolds.rolling_speed = self.rolling_speed\n            # find overlapping nodes\n            if 'off_set' in self.update or just_touching_gap is None or not self._no_time:\n                just_touching_gap, surface_1_points, surface_2_points \\\n                    = get_gap_from_model(self.model, interference=0, off_set=self.off_set,\n                                         mode=self.profile_interpolation_mode, periodic=self._periodic_profile)\n\n            time_step_current_state = dict(just_touching_gap=just_touching_gap, surface_1_points=surface_1_points,\n                                           surface_2_points=surface_2_points, off_set=self.off_set,\n                                           time_step=self.time_step, time=start_time+(i+1)*self.time_step)\n\n            # make a new loads function if we need it\n            if (previous_gap_shape is None or previous_gap_shape != just_touching_gap.shape) and im_mats:\n                span = tuple([s*(2-pa) for s, pa in zip(just_touching_gap.shape, self._periodic_axes)])\n                max_pressure = self.reynolds.dimensionalise_pressure(min([surf_1_material.max_load,\n                                                                          surf_2_material.max_load]), True)\n                self._nd_max_pressure = max_pressure\n                im1 = surf_1_material.influence_matrix(components=['zz'], grid_spacing=[gs] * 2,\n                                                       span=span, periodic_strides=self._periodic_im_repeats)['zz']\n                im2 = surf_2_material.influence_matrix(components=['zz'], grid_spacing=[gs] * 2, span=span,\n                                                       periodic_strides=self._periodic_im_repeats)['zz']\n                total_im = im1 + im2\n                loads_func = plan_convolve(just_touching_gap, total_im, circular=self._periodic_axes)\n                previous_gap_shape = just_touching_gap.shape\n\n            elif not im_mats:\n                def loads_func(loads):\n                    return solve_normal_loading(loads_z=loads, model=self.model,\n                                                deflections='z', current_state=time_step_current_state)[0]['z']\n            # sort out initial guess\n            if i >= 0:\n                initial_guess = 'previous'\n            else:\n                initial_guess = self.initial_guess\n\n            if initial_guess is None:\n                initial_guess = [self.reynolds.dimensionalise_gap(0.01),\n                                 self.reynolds.dimensionalise_pressure(0.05)]\n            if isinstance(initial_guess, str) and initial_guess.lower() == 'previous':\n                pressure = np.zeros_like(just_touching_gap) if 'pressure' not in previous_state else \\\n                    previous_state['pressure']\n                interference = 0.0 if 'interference' not in previous_state else previous_state['interference']\n            elif isinstance(initial_guess, Sequence):\n                interference = initial_guess[0]\n                if isinstance(initial_guess[1], Number):\n                    pressure = initial_guess[1] * np.ones_like(just_touching_gap)\n                else:\n                    try:\n                        pressure = np.asarray(initial_guess[1], dtype=np.float)\n                        assert (pressure.shape == just_touching_gap.shape)\n                    except ValueError:\n                        raise ValueError('Initial guess for pressure could not be converted to a numeric array')\n                    except AssertionError:\n                        # noinspection PyUnboundLocalVariable\n                        raise ValueError(\"Initial guess for pressure produced an array of the wrong size:\"\n                                         f\"expected {just_touching_gap.shape}, got: {pressure.shape}\")\n            elif hasattr(initial_guess, '__call__'):\n                interference, pressure = initial_guess(self.model, just_touching_gap)\n            else:\n                raise ValueError('Unsupported type for initial guess')\n\n            results_last_it = {'nd_pressure': self.reynolds.dimensionalise_pressure(pressure, True),\n                               'just_touching_gap': just_touching_gap,\n                               'interference': interference,\n                               'pressure': pressure}\n\n            # we have the interference, and the pressure initial guesses, find the initial displacement before solving\n\n            if not (results_last_it['nd_pressure'] == 0).all():\n                # noinspection PyUnboundLocalVariable\n                results_last_it['total_displacement_z'] = loads_func(previous_state['pressure'])\n\n            else:\n                results_last_it['total_displacement_z'] = np.zeros_like(just_touching_gap)\n            results_last_it = self.model.lubricant_model.solve_sub_models(results_last_it)\n            # main loops\n            it_num = 0\n            # Find the gap and non denationalise it\n            gap = just_touching_gap + results_last_it['total_displacement_z'] - results_last_it['interference']\n            results_last_it['nd_interference'] = self.reynolds.dimensionalise_gap(results_last_it['interference'], True)\n            results_last_it['gap'] = gap\n\n            while True:\n                nd_gap = self.reynolds.dimensionalise_gap(results_last_it['gap'], True)\n                results_last_it['nd_gap'] = nd_gap\n                # if flag:\n                #     return locals()\n                # else:\n                #     flag = True\n                # solve reynolds equation\n                results_this_it = self.reynolds.solve(results_last_it, self._nd_max_pressure)\n\n                # add just touching gap, needed for sub models\n                results_this_it['just_touching_gap'] = just_touching_gap\n\n                # check for pressure convergence\n                change_in_pressures = results_this_it['nd_pressure'] - results_last_it['nd_pressure']\n                total_nd_pressure = np.sum(results_last_it['nd_pressure'])  # use previous state here ... more stable\n                if total_nd_pressure > 0:\n                    pressure_relative_error = np.sum(np.abs(change_in_pressures)) / total_nd_pressure\n                else:\n                    pressure_relative_error = 1\n                pressure_converged = pressure_relative_error < self._rtol_pressure\n\n                # apply the relaxation factor to the pressure result\n                if self._nd_max_pressure is not None:\n                    results_this_it['nd_pressure'] = np.clip(results_last_it['nd_pressure'] +\n                                                             self._relaxation_factor * change_in_pressures, None,\n                                                             self._nd_max_pressure)\n                else:\n                    results_this_it['nd_pressure'] = (results_last_it['nd_pressure'] +\n                                                      self._relaxation_factor * change_in_pressures)\n\n                # solve contact geometry\n                results_this_it['pressure'] = self.reynolds.dimensionalise_pressure(results_this_it['nd_pressure'])\n                results_this_it['total_displacement_z'] = loads_func(results_this_it['pressure'])\n\n                # find gap\n                gap = just_touching_gap + results_this_it['total_displacement_z'] - results_last_it['interference']\n                results_this_it['gap'] = gap\n\n                # solve lubricant sub models\n                results_this_it = self.model.lubricant_model.solve_sub_models(results_this_it)\n\n                # check for load convergence\n                total_load = np.sum(results_this_it['pressure']) * gs ** 2\n\n                if self.load_controlled:\n                    load_relative_error = (total_load / self.normal_load) - 1\n                    load_converged = abs(load_relative_error) < self._rtol_pressure\n                else:\n                    load_converged = True\n                    load_relative_error = 0.0\n\n                results_this_it['nd_gap'] = self.reynolds.dimensionalise_gap(results_this_it['gap'], True)\n                results_this_it['interference'] = results_last_it['interference']\n\n                # escape the loop if it converged\n                if pressure_converged and load_converged:\n                    converged = True\n                    print(f\"Step {self.name} converged successfully after {it_num} iterations.\")\n                    print(f\"Converged load is {total_load}, last change in pressure was {pressure_relative_error}\\n\")\n                    break\n\n                # escape the loop it if failed\n                if it_num > self._max_it_pressure:  # this logic has changed used to just check the error\n                    converged = False\n                    print(f\"Step {self.name} failed to converge after {it_num} iterations.\\n\")\n                    print(\"Consider increasing the maximum number of iterations or reducing the relaxation factor\")\n                    print(f\"Converged load is {total_load}, last change in pressure was {pressure_relative_error}\")\n                    break\n\n                # adjust height for load balance\n\n                if self._adjust_height_every_step and self.load_controlled:\n                    # adjust height based on load balance\n                    new_nd_interference = self.update_interference(it_num, pressure_relative_error,\n                                                                   load_relative_error,\n                                                                   results_last_it['nd_interference'],\n                                                                   np.mean(results_this_it['nd_gap']),\n                                                                   np.min(results_this_it['nd_gap']))\n                    interference_updated = True\n\n                elif pressure_converged:\n                    # adjust height based on load balance\n                    new_nd_interference = self.update_interference(it_num, pressure_relative_error,\n                                                                   load_relative_error,\n                                                                   results_last_it['nd_interference'],\n                                                                   np.mean(results_this_it['nd_gap']),\n                                                                   np.min(results_this_it['nd_gap']))\n                    interference_updated = True\n                else:\n                    new_nd_interference = 0\n                    interference_updated = False\n\n                if interference_updated:\n                    results_this_it['nd_interference'] = new_nd_interference\n                    results_this_it['interference'] = self.reynolds.dimensionalise_gap(new_nd_interference)\n                    gap = (just_touching_gap + results_this_it['total_displacement_z'] - results_this_it['interference'])\n                    results_this_it['gap'] = gap\n                    # print summary of iteration to log file\n                    old_int = results_last_it['nd_interference']\n                    print(f'{it_num}\\ter_load: {load_relative_error:.4g}\\t'\n                          f'er_press: {pressure_relative_error:.4g}\\t'\n                          f'old_int: {old_int:.6g}\\t'\n                          f'new_int: {new_nd_interference:.6g}')\n                else:\n                    results_this_it['nd_interference'] = results_last_it['nd_interference']\n                    results_this_it['interference'] = results_last_it['interference']\n\n                it_num += 1\n                results_last_it = results_this_it\n\n            # clean up after it has converged\n            current_state = {**time_step_current_state, **results_this_it}\n            pressure = current_state['pressure']\n            if im_mats:\n                current_state['surface_1_displacement_z'] = plan_convolve(pressure, im1,\n                                                                          circular=self._periodic_axes)(pressure)\n                current_state['surface_2_displacement_z'] = plan_convolve(pressure, im2,\n                                                                          circular=self._periodic_axes)(pressure)\n                current_state['total_displacement_z'] = current_state['total_displacement_z']\n\n            else:\n                all_disp = solve_normal_loading(pressure, self.model, current_state, 'z')\n                current_state['total_displacement_z'] = all_disp[0]\n                current_state['surface_1_displacement_z'] = all_disp[1]\n                current_state['surface_2_displacement_z'] = all_disp[2]\n\n            # del current_state['total_displacement_z']\n            current_state['total_normal_load'] = total_load\n            current_state['loads_z'] = current_state['pressure']\n            current_state['converged'] = converged\n            current_state['rolling_speed'] = self.rolling_speed\n            current_state = self.solve_sub_models(current_state)\n            self.save_outputs(current_state, output_file)\n\n            previous_state = current_state\n\n        slippy.CUDA = cuda\n\n        return current_state\n\n    def __repr__(self):\n        return \"Lubrication step\"\n\n    def update_interference(self, it_num, pressure_error_rel, load_error_rel, current_interference, mean_gap, min_gap):\n        \"\"\"This method updates the interference between the 2 surfaces during solution\n\n        Parameters\n        ----------\n        it_num: int\n            The current iteration number of the solution\n        pressure_error_rel\n            The current relative pressure error on the solution\n        load_error_rel: float\n            The current relative load error\n        current_interference: float\n            The current interference between the two bodies (the maximum overlap between the undeformed profiles)\n        mean_gap\n            The average nd_gap between the surfaces\n        min_gap\n            The minimum nd_gap between the surfaces\n\n        Returns\n        -------\n        new_interference: float\n            The non dimensional interference between the surfaces\n\n        Notes\n        -----\n        This method is quite basic at the moment and can definitely be improved, if executed on every loop, the height\n        is just updated by a fixed proportion of the minimum nd_gap size\n\n        If updated only when the solver converges, the Regula-Falsi method is used\n        \"\"\"\n        if self._adjust_height_every_step:\n            new_interference = current_interference - 0.1 * load_error_rel\n            return new_interference\n\n        # else:  # height only adjusted when the load has converged, in this case use the Regula-Falsi method\n        self._interferences.append(current_interference)\n        self._load_errors.append(load_error_rel)\n\n        if len(self._interferences) == 1:  # if this is the first guess give a value that will probably bound it\n            new_interference = current_interference + abs(mean_gap) * -np.sign(load_error_rel)\n            return new_interference\n\n        if len(self._interferences) > 2 and abs(sum(np.sign(self._load_errors))) == 1:\n            # if this is true we must have bound a root\n\n            if self._load_errors[0] * self._load_errors[2] < 0:\n                del (self._interferences[1])\n                del (self._load_errors[1])\n            else:\n                del (self._interferences[0])\n                del (self._load_errors[0])\n\n        else:  # we have not bound a root, continue with the secant method but del the first item so we progress\n            del (self._interferences[0])\n            del (self._load_errors[0])\n\n        new_interference = (self._interferences[0] - self._load_errors[0] * (self._interferences[1] -\n                                                                             self._interferences[0]) /\n                            (self._load_errors[1] - self._load_errors[0]))\n\n        print(f'Adjusting interference, new interference is {new_interference}')\n\n        return new_interference\n\n\ndef _data_check_error_or_warn(msg: str):\n    if slippy.ERROR_IN_DATA_CHECK:\n        raise ValueError(msg)\n    else:\n        warnings.warn(msg)\n", "meta": {"hexsha": "8f2151563f8b7da2b15505bb4ae75c4c12d09218", "size": 37289, "ext": "py", "lang": "Python", "max_stars_repo_path": "slippy/contact/lubrication_steps.py", "max_stars_repo_name": "KDriesen/slippy", "max_stars_repo_head_hexsha": "816723fe6ab9f5ed26b14b4fe0f66423649b85e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2020-12-06T15:30:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T06:37:15.000Z", "max_issues_repo_path": "slippy/contact/lubrication_steps.py", "max_issues_repo_name": "KDriesen/slippy", "max_issues_repo_head_hexsha": "816723fe6ab9f5ed26b14b4fe0f66423649b85e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slippy/contact/lubrication_steps.py", "max_forks_repo_name": "KDriesen/slippy", "max_forks_repo_head_hexsha": "816723fe6ab9f5ed26b14b4fe0f66423649b85e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-03-18T05:53:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T15:18:43.000Z", "avg_line_length": 54.3571428571, "max_line_length": 121, "alphanum_fraction": 0.6207728821, "include": true, "reason": "import numpy", "num_tokens": 7712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.1599530571714428}}
{"text": "import numpy as np\nfrom astropy import units as u\nfrom astropy import table\nfrom scipy import interpolate as scinterp\n\nclass SNANAHostLib():\n    \"\"\"Class for parsing a SNANA HOSTLIB file.\n    The file may contain a weight map, and must contain host galaxy data,\n    following the standard SNANA HOSTLIB format.\n    \"\"\"\n    def __init__(self, filename):\n        \"\"\"Read in a SNANA HOSTLIB file\"\"\"\n        # find the 'VARNAMES' line, use it to define the start of the hostlib\n        # section (as opposed to the wgtmap section)\n        nwgtmapstart = -1\n        ngaldataheader = -1\n        ngaldatastart = -1\n        iline = 0\n        with open(filename, 'r') as read_obj:\n            for line in read_obj:\n                if len(line.strip().lstrip('#'))==0:\n                    continue\n                if line.strip().startswith('NVAR_WGTMAP:'):\n                    wgtmaphdrline = line.split()\n                    varnames_wgtmap = wgtmaphdrline[3:]\n                if line.strip().startswith('WGT:') and nwgtmapstart<0:\n                    nwgtmapstart = iline\n                if line.strip().startswith('GAL:') and ngaldatastart<0:\n                    ngaldatastart = iline\n                if line.strip().startswith('VARNAMES:'):\n                    ngaldataheader = iline\n                iline += 1\n        if ngaldataheader < 0:\n            raise RuntimeError(r\"{filename} is not an SNANA HOSTLIB file\")\n\n        if nwgtmapstart >= 0:\n            self.wgtmaptable = table.Table.read(\n                filename, format='ascii.basic',\n                names=['label']+varnames_wgtmap+['wgt','snmagshift'],\n                data_start=nwgtmapstart-1,\n                data_end=ngaldataheader-2,\n                comment='#'\n                )\n        else:\n            self.wgtmaptable = None\n\n        galdatatable = table.Table.read(filename, format='ascii.basic',\n                                  header_start=ngaldataheader-1,\n                                  data_start=ngaldatastart-1, comment='#'\n                                  )\n        galdatatable.remove_columns(['VARNAMES:'])\n        self.galdatatable = galdatatable\n        return\n\n\nclass CatalogBasedRedshiftSim():\n    \"\"\"Class for projecting redshift completeness from an input\n    galaxy catalog.\n    \"\"\"\n\n    def __init__(self):\n        self.postsurvey = False\n        self.galaxies = None\n\n    def read_galaxy_catalog(self, filename):\n        \"\"\"Read in a catalog of galaxy properties\n\n        Parameters\n        ----------\n        filename : str\n          full path to the file containing galaxy properties (e.g. Mass, SFR,\n          magnitudes, etc.).  May be a SNANA HOSTLIB file, or any formtat that\n          can be auto-parsed by astropy.table.Table.read()\n        \"\"\"\n        # TODO: check if it is a hostlib without try/except\n        try :\n            self.galaxies = table.Table.read(filename)\n        except:\n            try:\n                hostlib = SNANAHostLib(filename)\n                self.galaxies = hostlib.galdatatable\n            except:\n                raise RuntimeError(\n                    f\"Can't read in {filename}. \"\n                    \"It may not be a valid hostlib or astropy-readable table.\")\n        return\n\n\n    def assign_snhost_prob(self, snr_model='AH18S',\n                           logmasscolname='logmass',\n                           logsfrcolname='logsfr',\n                           verbose=True):\n        \"\"\"Add a column to the 'galaxies' catalog that gives the relative\n        probability for each galaxy hosting a SN in any given observer-frame\n        year.  This is computed based on the predicted SN rate (number of SN\n        explosions per observer-frame year) of each galaxy, adopting the\n        specified SN rate model.\n\n        Parameters\n        ----------\n        snr_model : str\n           'A+B' : SNR = A*M + B*SFR   (Scannapieco & Bildsten 2005)\n           'AH18S' : the smooth logarithmic sSFR model (Andersen & Hjorth 2018)\n           'AH18PW' : the piecewise sSFR model (Andersen & Hjorth 2018)\n\n        logmasscolname : str\n           name of column in the galaxies Table containing the log10(Mass)\n\n        logsfrcolname : str\n           name of column in the galaxies Table containing the\n           log10(StarFormationRate)\n\n        verbose : bool\n            Set to True to print messages.\n        \"\"\"\n        if self.galaxies is None:\n            print(\"No 'galaxies' catalog loaded. Use 'read_galaxy_catalog()'\")\n\n        if snr_model.lower()=='a+b':\n            # Note: adopting the A and B values from Andersen & Hjorth 2018\n            # but dividing by 1e-4 (so the SNR below actually counts the number\n            # of SN explodiing per 10000 yrs)\n            A = 4.66 * 1e-10\n            B = 4.88\n            snr = A * 10 ** self.galaxies[logmasscolname] + B * 10 ** self.galaxies[logsfrcolname]\n            # divide by the total snr to get relative probabilities\n            snr /= np.nanmax(snr)\n            snrcolname = 'snr_A+B'\n            snrcol = table.Column(data=snr, name='snr_A+B')\n        elif snr_model.lower() == 'ah18s':\n            logssfr = self.galaxies[logsfrcolname] - self.galaxies[logmasscolname]\n            ssnr = ssnr_ah18_smooth(logssfr)\n            snr = ssnr * 10 ** self.galaxies[logmasscolname]\n            snr /= np.nanmax(snr)\n            snrcolname = 'snr_AH18_smooth'\n            snrcol = table.Column(data=snr, name=snrcolname)\n        elif snr_model.lower() == 'ah18pw':\n            logssfr = self.galaxies[logsfrcolname] - self.galaxies[logmasscolname]\n            ssnr = ssnr_ah18_piecewise(logssfr)\n            snr = ssnr * 10 ** self.galaxies[logmasscolname]\n            snr /= np.nanmax(snr)\n            snrcolname = 'snr_AH18_piecewise'\n        else:\n            raise RuntimeError(r\"{snr_model} is not a know SN rate model.\")\n\n        snrcol = table.Column(data=snr, name=snrcolname)\n        if snrcolname in self.galaxies.colnames:\n            self.galaxies[snrcolname] = snr\n        else:\n            self.galaxies.add_column(snrcol)\n        if verbose:\n            print(f\"Added/updated relative SN rate column using {snr_model} model\")\n        return\n\n\n    def pick_host_galaxies(self, nsn, snrcolname='snr_AH18_piecewise',\n                           replace=False, verbose=True):\n        \"\"\"Do a random draw to assign 'nsn' supernovae to galaxies in the\n        galaxies catalog, based on the (pre-defined) relative SN rates.\n\n        TODO: (Alternatively, read in a SNANA output file (.dump file maybe?)\n        that has already run a survey simulation and picked host galaxies.)\n\n        Parameters\n        ----------\n        replace\n        nsn : int\n          number of SN to assign to host galaxies\n\n        snrcolname : str\n           name of the column in the galaxies catalog that gives the relative\n           SN rate (or 'weight') for each galaxy.  This may be created by the\n           assign_snhost_prob() method.\n\n        replace : bool\n           Whether to sample with replacement.  If True, a galaxy may host\n           more than one SN. If False, then assign no more than one SN to\n           each galaxy (requires nsn<len(galaxies))\n        \"\"\"\n        if ~replace and nsn > len(self.galaxies):\n            raise RuntimeError(\n                r'Picking hosts without replacement, but Nsn > len(galaxies)')\n\n        # Pick SN host galaxies\n        galindices = np.arange(len(self.galaxies))\n        psnhost = self.galaxies[snrcolname]/np.sum(self.galaxies[snrcolname])\n        snindices = np.random.choice(\n            galindices, nsn, replace=replace, p=psnhost)\n\n        # Add a boolean 'host' column to the galaxies catalog\n        ishost = np.zeros(len(self.galaxies), dtype=bool)\n        ishost[snindices] = True\n        hostcol = table.Column(name='host', data=ishost)\n        if 'host' in self.galaxies.colnames:\n            self.galaxies['host'] = hostcol\n        else:\n            self.galaxies.add_column(hostcol, index=1)\n\n        # TODO: Alternate approach:  read in a SNANA output file (.dump file\n        #  maybe?) that has already run a survey simulation and picked hosts.\n\n        if verbose:\n            print(f\"Assigned {nsn} SNe to hosts using {snrcolname} probabilities.\")\n        return\n\n\n\n    def apply_specz_completeness_map(self, filename,\n                                     defining_columns_galcat,\n                                     defining_columns_speczmap,\n                                     efficiency_columns_speczmap,\n                                     fill_value = np.nan\n                                     ):\n        \"\"\"Read in a 'map' for spectroscopic redshift completeness, which\n        maps from one or more galaxy properties (mag, SFR, z...) onto a\n        probability of getting a spec-z.\n\n        Preferred format of the input file is a .ecsv file, but anything\n        that astropy.table can read is OK in principle.\n\n        Then apply the specz completeness map to the catalog\n        of host galaxy properties (already read in) to define exactly which\n        of the galaxies gets a redshift.\n\n        If the method 'pick_host_galaxies' has already been run\n        (so the flag postsurvey == True), then only galaxies defined as SN\n        hosts are assigned a redshift.\n\n        Parameters\n        ----------\n        filename : str\n           path to astropy-readable file\n\n        defining_columns_galcat : listlike\n           list of strings specifying the column names in the galaxy catalog\n           (self.galaxies) for parameters that are used to define the specz\n           efficiency (e.g. if this is a SFR-based specz map then this may\n           be ['logSFR'])\n\n        defining_columns_speczmap : listlike, same length as above\n           list of strings specifying the corresponding column names in the\n           specz map file (given by 'filename').  Must be the same length as\n           defining_columns_galcat, giving corresponding column names in the\n           same order.\n\n        efficiency_columns_speczmap : listlike, same length as above\n           list of column names giving the specz\n           efficiency (or completeness fraction) for each row in the specz\n           map file.\n        \"\"\"\n        if (len(defining_columns_galcat)!=len(defining_columns_speczmap) or\n            len(defining_columns_galcat)!=len(efficiency_columns_speczmap)):\n            raise RuntimeError(\n                'You must specify the same number of columns from the '\n                'galaxy catalog and the specz efficiency catalog.')\n\n        # TODO : make a masked array to remove NaNs ? ?\n        speczmap = table.Table.read(filename)\n\n        # TODO : build a separate interpolating function for each of\n        #  the possible input parameters ?\n        interpolatordict = {}\n        for i in range(len(defining_columns_galcat)):\n            colname_galcat = defining_columns_galcat[i]\n            xobs = self.galaxies[colname_galcat]\n            colname_param = defining_columns_speczmap[i]\n            x = speczmap[colname_param]\n            colname_efficiency = efficiency_columns_speczmap[i]\n            y = speczmap[colname_efficiency]\n            interpolator = scinterp.interp1d(\n                x, y, bounds_error=False, fill_value=fill_value)\n            interpolatordict[colname_galcat] = interpolator\n\n        return(interpolatordict)\n\n    def make_photoz_accuracy_map(self):\n        \"\"\"For every galaxy in the catalog of galaxy properties, apply a\n        photo-z function that defines the 'measured' photo-z value and\n        uncertainty (photoz pdf).  Includes catastrophic outliers.\n        \"\"\"\n        pass\n\n    def report_redshift_completeness(self):\n        \"\"\"Produce a report of the overall redshift completeness, accuracy\n        and precision, based on multiple spectroscopic 'filters' and the\n        random assignment of photo-z values.\n        \"\"\"\n        pass\n\n\n\ndef ssnr_ah18_smooth(logssfr):\n    \"\"\" Returns the Type Ia specific SN rate per Tyr\n    (number of SN Ia exploding per 10^12 yr per solar mass)\n    for a galaxy, using the model of Andersen & Hjorth 2018, which is based\n    on the specific star formation rate, given as log10(SSFR).\n    \"\"\"\n    a = (1.5)*1e-13 # (1.12)*1e-13\n    b = 0.5 # 0.73\n    k = 0.4 # 0.49\n    ssfr0 = 1.7e-10# 1.665e-10\n    # logssfr0 = -9.778585762157661    # log10(ssfr0)\n    ssfr = np.power(10.,logssfr)\n    ssnr = (a + (a/k) * np.log10(ssfr/ssfr0 + b)) * 1e12\n    #ssnr = np.max(ssnr, 0.7)\n    return(ssnr)\n\n\ndef ssnr_ah18_piecewise(logssfr):\n    \"\"\" Returns the Type Ia specific SN rate per Tyr\n    (number of SN Ia exploding per 10^12 yr per solar mass)\n    for a galaxy, using the piecwise linear model\n    of Andersen & Hjorth 2018, which is based\n    on the specific star formation rate, given as log10(SSFR).\n    \"\"\"\n    # Note that the alpha scaling parameter\n    # has been multiplied by 1e12 to get units of Tyr-1\n    alpha = (1.12)* 1e5\n    beta = 0.586\n    ssfr2 = 1.01e-11\n    ssfr1 = 1.04e-9\n\n    S1 = np.power(ssfr1, beta)\n    S2 = np.power(ssfr2, beta)\n\n    if not np.iterable(logssfr):\n        logssfr = np.array([logssfr])\n\n    ssfr = np.power(10.,logssfr)\n\n    ilow = np.where(ssfr<=ssfr2)[0]\n    imid = np.where((ssfr>ssfr2) & (ssfr<ssfr1))[0]\n    ihi = np.where(ssfr>=ssfr1)[0]\n\n    ssnrmid = alpha * np.power(ssfr[imid], beta)\n\n    ssnr = alpha * np.where(ssfr<=ssfr2, S2,\n                            np.where(ssfr>=ssfr1, S1,\n                                     np.power(ssfr, beta)))\n    if len(ssnr)==1:\n        ssnr = ssnr[0]\n    return(ssnr)\n\n", "meta": {"hexsha": "e03351c9d6bf8130138d146b5db60183e45ece9c", "size": 13523, "ext": "py", "lang": "Python", "max_stars_repo_path": "romanz/romanz.py", "max_stars_repo_name": "jpierel14/roman-sn-redshifts", "max_stars_repo_head_hexsha": "5532b5de9d47f646eebac493eb2c9d9585e5ddb8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-23T20:18:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-23T20:18:10.000Z", "max_issues_repo_path": "romanz/romanz.py", "max_issues_repo_name": "jpierel14/roman-sn-redshifts", "max_issues_repo_head_hexsha": "5532b5de9d47f646eebac493eb2c9d9585e5ddb8", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-03-23T16:18:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-23T20:02:08.000Z", "max_forks_repo_path": "romanz/romanz.py", "max_forks_repo_name": "jpierel14/roman-sn-redshifts", "max_forks_repo_head_hexsha": "5532b5de9d47f646eebac493eb2c9d9585e5ddb8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-04-21T16:57:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-17T18:43:26.000Z", "avg_line_length": 39.3110465116, "max_line_length": 98, "alphanum_fraction": 0.5940989425, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 3382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.27512971193602087, "lm_q1q2_score": 0.1599337558678401}}
{"text": "# This file is part of QuTiP: Quantum Toolbox in Python.\n#\n#    Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.\n#    All rights reserved.\n#\n#    Redistribution and use in source and binary forms, with or without\n#    modification, are permitted provided that the following conditions are\n#    met:\n#\n#    1. Redistributions of source code must retain the above copyright notice,\n#       this list of conditions and the following disclaimer.\n#\n#    2. Redistributions in binary form must reproduce the above copyright\n#       notice, this list of conditions and the following disclaimer in the\n#       documentation and/or other materials provided with the distribution.\n#\n#    3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names\n#       of its contributors may be used to endorse or promote products derived\n#       from this software without specific prior written permission.\n#\n#    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n#    \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n#    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n#    PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n#    HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n#    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n#    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n#    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n#    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n#    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n#    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n###############################################################################\nfrom collections.abc import Iterable\nimport warnings\nfrom copy import deepcopy\n\nimport numpy as np\nfrom scipy.interpolate import CubicSpline\n\nfrom qutip.qobj import Qobj\nfrom qutip.qobjevo import QobjEvo\nfrom qutip.operators import identity\nfrom qutip.qip.operations.gates import expand_operator, globalphase\nfrom qutip.tensor import tensor\nfrom qutip.mesolve import mesolve\nfrom qutip.mcsolve import mcsolve\nfrom qutip.qip.circuit import QubitCircuit\nfrom qutip.qip.noise import (\n    Noise, RelaxationNoise, DecoherenceNoise,\n    ControlAmpNoise, RandomNoise, process_noise)\nfrom qutip.qip.pulse import Pulse, Drift, _merge_qobjevo, _fill_coeff\n\n\n__all__ = ['Processor']\n\n\nclass Processor(object):\n    \"\"\"\n    A simulator of a quantum device based on the QuTiP solver\n    :func:`qutip.mesolve`.  It is defined by the available driving Hamiltonian\n    and the decoherence time for each component systems.  The processor can\n    simulate the evolution under the given control pulses. Noisy evolution is\n    supported by :class:`.Noise` and can be added to the processor.\n\n    Parameters\n    ----------\n    N: int\n        The number of component systems.\n\n    t1: list or float, optional\n        Characterize the decoherence of amplitude damping for\n        each qubit. A list of size `N` or a float for all qubits.\n\n    t2: list of float, optional\n        Characterize the decoherence of dephasing for\n        each qubit. A list of size `N` or a float for all qubits.\n\n    dims: list, optional\n        The dimension of each component system.\n        Default value is a\n        qubit system of ``dim=[2,2,2,...,2]``\n\n    spline_kind: str, optional\n        Type of the coefficient interpolation. Default is \"step_func\"\n        Note that they have different requirement for the length of ``coeff``.\n\n        - \"step_func\":\n          The coefficient will be treated as a step function.  E.g.\n          ``tlist=[0,1,2]`` and ``coeff=[3,2]``, means that the coefficient is\n          3 in t=[0,1) and 2 in t=[2,3). It requires\n          ``len(coeff)=len(tlist)-1`` or ``len(coeff)=len(tlist)``, but in the\n          second case the last element of `coeff` has no effect.\n\n        - \"cubic\": Use cubic interpolation for the coefficient. It requires\n          ``len(coeff)=len(tlist)``\n\n    Attributes\n    ----------\n    N: int\n        The number of component systems.\n\n    pulses: list of :class:`.Pulse`\n        A list of control pulses of this device\n\n    t1: float or list\n        Characterize the decoherence of amplitude damping of\n        each qubit.\n\n    t2: float or list\n        Characterize the decoherence of dephasing for\n        each qubit.\n\n    noise: :class:`.Noise`, optional\n        A list of noise objects. They will be processed when creating the\n        noisy :class:`qutip.QobjEvo` from the processor or run the simulation.\n\n    drift: :class:`qutip.qip.pulse.Drift`\n        A `Drift` object representing the drift Hamiltonians.\n\n    dims: list\n        The dimension of each component system.\n        Default value is a\n        qubit system of ``dim=[2,2,2,...,2]``\n\n    spline_kind: str\n        Type of the coefficient interpolation.\n        See parameters of :class:`.Processor` for details.\n    \"\"\"\n    def __init__(self, N, t1=None, t2=None,\n                 dims=None, spline_kind=\"step_func\"):\n        self.N = N\n        self.pulses = []\n        self.t1 = t1\n        self.t2 = t2\n        self.noise = []\n        self.drift = Drift()\n        if dims is None:\n            self.dims = [2] * N\n        else:\n            self.dims = dims\n        self.pulse_mode = \"discrete\"\n        self.spline_kind = spline_kind\n\n    @property\n    def num_qubits(self):\n        return self.N\n\n    @num_qubits.setter\n    def num_qubits(self, value):\n        self.N = value\n\n    def add_drift(self, qobj, targets, cyclic_permutation=False):\n        \"\"\"\n        Add a drift Hamiltonians. The drift Hamiltonians are intrinsic\n        of the quantum system and cannot be controlled by external field.\n\n        Parameters\n        ----------\n        qobj: :class:`qutip.Qobj`\n            The drift Hamiltonian.\n        targets: list\n            The indices of the target qubits\n            (or subquantum system of other dimensions).\n        \"\"\"\n        if not isinstance(qobj, Qobj):\n            raise TypeError(\"The drift Hamiltonian must be a qutip.Qobj.\")\n        if not qobj.isherm:\n            raise ValueError(\"The drift Hamiltonian must be Hermitian.\")\n\n        num_qubits = len(qobj.dims[0])\n        if targets is None:\n            targets = list(range(num_qubits))\n        if not isinstance(targets, list):\n            targets = [targets]\n        if cyclic_permutation:\n            for i in range(self.N):\n                temp_targets = [(t + i) % self.N for t in targets]\n                self.drift.add_drift(qobj, temp_targets)\n        else:\n            self.drift.add_drift(qobj, targets)\n\n    def add_control(self, qobj, targets=None, cyclic_permutation=False,\n                    label=None):\n        \"\"\"\n        Add a control Hamiltonian to the processor. It creates a new\n        :class:`.Pulse`\n        object for the device that is turned off\n        (``tlist = None``, ``coeff = None``). To activate the pulse, one\n        can set its `tlist` and `coeff`.\n\n        Parameters\n        ----------\n        qobj: :class:`qutip.Qobj`\n            The Hamiltonian for the control pulse..\n\n        targets: list, optional\n            The indices of the target qubits\n            (or subquantum system of other dimensions).\n\n        cyclic_permutation: bool, optional\n            If true, the Hamiltonian will be expanded for\n            all cyclic permutation of the target qubits.\n\n        label: str, optional\n            The label (name) of the pulse\n        \"\"\"\n        # Check validity of ctrl\n        if not isinstance(qobj, Qobj):\n            raise TypeError(\"The control Hamiltonian must be a qutip.Qobj.\")\n        if not qobj.isherm:\n            raise ValueError(\"The control Hamiltonian must be Hermitian.\")\n\n        num_qubits = len(qobj.dims[0])\n        if targets is None:\n            targets = list(range(num_qubits))\n        if not isinstance(targets, list):\n            targets = [targets]\n        if cyclic_permutation:\n            for i in range(self.N):\n                temp_targets = [(t + i) % self.N for t in targets]\n                if label is not None:\n                    temp_label = label + \"_\" + str(temp_targets)\n                temp_label = label\n                self.pulses.append(\n                    Pulse(qobj, temp_targets, spline_kind=self.spline_kind,\n                          label=temp_label))\n        else:\n            self.pulses.append(\n                Pulse(qobj, targets, spline_kind=self.spline_kind, label=label)\n                )\n\n    def find_pulse(self, pulse_name):\n        if isinstance(pulse_name, str):\n            try:\n                return self.pulses[self.pulse_dict[pulse_name]]\n            except (KeyError):\n                raise KeyError(\n                    \"Pulse name {} undefined. \"\n                    \"Please define it in the attribute \"\n                    \"`pulse_dict`.\".format(pulse_name))\n        elif isinstance(pulse_name, int):\n            return self.pulses[pulse_name]\n        else:\n            raise TypeError(\n                \"pulse_name is either a string or an integer, not \"\n                \"{}\".format(type(pulse_name))\n                )\n\n    @property\n    def ctrls(self):\n        \"\"\"\n        A list of Hamiltonians of all pulses.\n        \"\"\"\n        result = []\n        for pulse in self.pulses:\n            result.append(pulse.get_ideal_qobj(self.dims))\n        return result\n\n    @property\n    def coeffs(self):\n        \"\"\"\n        A list of the coefficients for all control pulses.\n        \"\"\"\n        if not self.pulses:\n            return None\n        coeffs_list = [pulse.coeff for pulse in self.pulses]\n        return coeffs_list\n\n    @coeffs.setter\n    def coeffs(self, coeffs_list):\n        for i, coeff in enumerate(coeffs_list):\n            self.pulses[i].coeff = coeff\n\n    @property\n    def pulse_mode(self):\n        if self.spline_kind == \"step_func\":\n            return \"discrete\"\n        elif self.spline_kind == \"cubic\":\n            return \"continuous\"\n        else:\n            raise ValueError(\n                \"Saved spline_kind not understood.\")\n\n    @pulse_mode.setter\n    def pulse_mode(self, mode):\n        if mode == \"discrete\":\n            spline_kind = \"step_func\"\n        elif mode == \"continuous\":\n            spline_kind = \"cubic\"\n        else:\n            raise ValueError(\n                \"Pulse mode must be either discrete or continuous.\")\n\n        self.spline_kind = spline_kind\n        for pulse in self.pulses:\n            pulse.spline_kind = spline_kind\n\n    def get_full_tlist(self, tol=1.0e-10):\n        \"\"\"\n        Return the full tlist of the ideal pulses.\n        If different pulses have different time steps,\n        it will collect all the time steps in a sorted array.\n\n        Returns\n        -------\n        full_tlist: array-like 1d\n            The full time sequence for the ideal evolution.\n        \"\"\"\n        full_tlist = [pulse.tlist\n                      for pulse in self.pulses if pulse.tlist is not None]\n        if not full_tlist:\n            return None\n        full_tlist = np.unique(np.sort(np.hstack(full_tlist)))\n        # account for inaccuracy in float-point number\n        full_tlist = np.concatenate(\n            (full_tlist[:1], full_tlist[1:][np.diff(full_tlist) > tol]))\n        return full_tlist\n\n    def get_full_coeffs(self, full_tlist=None):\n        \"\"\"\n        Return the full coefficients in a 2d matrix form.\n        Each row corresponds to one pulse. If the `tlist` are\n        different for different pulses, the length of each row\n        will be same as the `full_tlist` (see method\n        `get_full_tlist`). Interpolation is used for\n        adding the missing coefficient according to `spline_kind`.\n\n        Returns\n        -------\n        coeffs: array-like 2d\n            The coefficients for all ideal pulses.\n        \"\"\"\n        # TODO add tests\n        self._is_pulses_valid()\n        if not self.pulses:\n            return np.array((0, 0), dtype=float)\n        if full_tlist is None:\n            full_tlist = self.get_full_tlist()\n        coeffs_list = []\n        for pulse in self.pulses:\n            if pulse.tlist is None and pulse.coeff is None:\n                coeffs_list.append(np.zeros(len(full_tlist)))\n                continue\n            if not isinstance(pulse.coeff, (bool, np.ndarray)):\n                raise ValueError(\n                    \"get_full_coeffs only works for \"\n                    \"NumPy array or bool coeff.\")\n            if isinstance(pulse.coeff, bool):\n                if pulse.coeff:\n                    coeffs_list.append(np.ones(len(full_tlist)))\n                else:\n                    coeffs_list.append(np.zeros(len(full_tlist)))\n                continue\n            if self.spline_kind == \"step_func\":\n                arg = {\"_step_func_coeff\": True}\n                coeffs_list.append(\n                    _fill_coeff(pulse.coeff, pulse.tlist, full_tlist, arg))\n            elif self.spline_kind == \"cubic\":\n                coeffs_list.append(\n                    _fill_coeff(pulse.coeff, pulse.tlist, full_tlist, {}))\n            else:\n                raise ValueError(\"Unknown spline kind.\")\n        return np.array(coeffs_list)\n\n    def set_all_tlist(self, tlist):\n        \"\"\"\n        Set the same `tlist` for all the pulses.\n\n        Parameters\n        ----------\n        tlist: array-like, optional\n            A list of time at which the time-dependent coefficients are\n            applied. See :class:`.Pulse` for detailed information`\n        \"\"\"\n        if isinstance(tlist, list) and len(tlist) == len(self.pulses):\n            for i, pulse in enumerate(self.pulses):\n                pulse.tlist = tlist[i]\n        else:\n            for pulse in self.pulses:\n                pulse.tlist = tlist\n\n    def add_pulse(self, pulse):\n        \"\"\"\n        Add a new pulse to the device.\n\n        Parameters\n        ----------\n        pulse: :class:`.Pulse`\n            `Pulse` object to be added.\n        \"\"\"\n        if isinstance(pulse, Pulse):\n            if pulse.spline_kind is None:\n                pulse.spline_kind = self.spline_kind\n            self.pulses.append(pulse)\n        else:\n            raise ValueError(\"Invalid input, pulse must be a Pulse object\")\n\n    def remove_pulse(self, indices=None, label=None):\n        \"\"\"\n        Remove the control pulse with given indices.\n\n        Parameters\n        ----------\n        indices: int or list of int\n            The indices of the control Hamiltonians to be removed.\n        label: str\n            The label of the pulse\n        \"\"\"\n        if indices is not None:\n            if not isinstance(indices, Iterable):\n                indices = [indices]\n            indices.sort(reverse=True)\n            for ind in indices:\n                del self.pulses[ind]\n        else:\n            for ind, pulse in enumerate(self.pulses):\n                if pulse.label == label:\n                    del self.pulses[ind]\n\n    def _is_pulses_valid(self):\n        \"\"\"\n        Check if the pulses are in the correct shape.\n\n        Returns: bool\n            If they are valid or not\n        \"\"\"\n        for i, pulse in enumerate(self.pulses):\n            if pulse.coeff is None or isinstance(pulse.coeff, bool):\n                # constant pulse\n                continue\n            if pulse.tlist is None:\n                raise ValueError(\n                    \"Pulse id={} is invalid. \"\n                    \"Please define a tlist for the pulse.\".format(i))\n            if pulse.tlist is not None and pulse.coeff is None:\n                raise ValueError(\n                    \"Pulse id={} is invalid. \"\n                    \"Please define a coeff for the pulse.\".format(i))\n            coeff_len = len(pulse.coeff)\n            tlist_len = len(pulse.tlist)\n            if pulse.spline_kind == \"step_func\":\n                if coeff_len == tlist_len-1 or coeff_len == tlist_len:\n                    pass\n                else:\n                    raise ValueError(\n                        \"The length of tlist and coeff of the pulse \"\n                        \"labelled {} is invalid. \"\n                        \"It's either len(tlist)=len(coeff) or \"\n                        \"len(tlist)-1=len(coeff) for coefficients \"\n                        \"as step function\".format(i))\n            else:\n                if coeff_len == tlist_len:\n                    pass\n                else:\n                    raise ValueError(\n                        \"The length of tlist and coeff of the pulse \"\n                        \"labelled {} is invalid. \"\n                        \"It should be either len(tlist)=len(coeff)\".format(i))\n        return True\n\n    def add_noise(self, noise):\n        \"\"\"\n        Add a noise object to the processor\n\n        Parameters\n        ----------\n        noise: :class:`.Noise`\n            The noise object defined outside the processor\n        \"\"\"\n        if isinstance(noise, Noise):\n            self.noise.append(noise)\n        else:\n            raise TypeError(\"Input is not a Noise object.\")\n\n    def save_coeff(self, file_name, inctime=True):\n        \"\"\"\n        Save a file with the control amplitudes in each timeslot.\n\n        Parameters\n        ----------\n        file_name: string\n            Name of the file.\n\n        inctime: bool, optional\n            True if the time list should be included in the first column.\n        \"\"\"\n        self._is_pulses_valid()\n        coeffs = np.array(self.get_full_coeffs())\n        if inctime:\n            shp = coeffs.T.shape\n            data = np.empty((shp[0], shp[1] + 1), dtype=np.float64)\n            data[:, 0] = self.get_full_tlist()\n            data[:, 1:] = coeffs.T\n        else:\n            data = coeffs.T\n\n        np.savetxt(file_name, data, delimiter='\\t', fmt='%1.16f')\n\n    def read_coeff(self, file_name, inctime=True):\n        \"\"\"\n        Read the control amplitudes matrix and time list\n        saved in the file by `save_amp`.\n\n        Parameters\n        ----------\n        file_name: string\n            Name of the file.\n\n        inctime: bool, optional\n            True if the time list in included in the first column.\n\n        Returns\n        -------\n        tlist: array_like\n            The time list read from the file.\n\n        coeffs: array_like\n            The pulse matrix read from the file.\n        \"\"\"\n        data = np.loadtxt(file_name, delimiter='\\t')\n        if not inctime:\n            self.coeffs = data.T\n            return self.coeffs\n        else:\n            tlist = data[:, 0]\n            self.set_all_tlist(tlist)\n            self.coeffs = data[:, 1:].T\n            return self.get_full_tlist, self.coeffs\n\n    def get_noisy_pulses(self, device_noise=False, drift=False):\n        \"\"\"\n        It takes the pulses defined in the `Processor` and\n        adds noise according to `Processor.noise`. It does not modify the\n        pulses saved in `Processor.pulses` but returns a new list.\n        The length of the new list of noisy pulses might be longer\n        because of drift Hamiltonian and device noise. They will be\n        added to the end of the pulses list.\n\n        Parameters\n        ----------\n        device_noise: bool, optional\n            If true, include pulse independent noise such as single qubit\n            Relaxation. Default is False.\n        drift: bool, optional\n            If true, include drift Hamiltonians. Default is False.\n\n        Returns\n        -------\n        noisy_pulses: list of :class:`.Pulse`\n            A list of noisy pulses.\n        \"\"\"\n        pulses = deepcopy(self.pulses)\n        noisy_pulses = process_noise(\n            pulses, self.noise, self.dims, t1=self.t1, t2=self.t2,\n            device_noise=device_noise)\n        if drift:\n            noisy_pulses += [self.drift]\n        return noisy_pulses\n\n    def get_qobjevo(self, args=None, noisy=False):\n        \"\"\"\n        Create a :class:`qutip.QobjEvo` representation of the evolution.\n        It calls the method `get_noisy_pulses` and create the `QobjEvo`\n        from it.\n\n        Parameters\n        ----------\n        args: dict, optional\n            Arguments for :class:`qutip.QobjEvo`\n        noisy: bool, optional\n            If noise are included. Default is False.\n\n        Returns\n        -------\n        qobjevo: :class:`qutip.QobjEvo`\n            The :class:`qutip.QobjEvo` representation of the unitary evolution.\n        c_ops: list of :class:`qutip.QobjEvo`\n            A list of lindblad operators is also returned. if ``noisy==Flase``,\n            it is always an empty list.\n        \"\"\"\n        # TODO test it for non array-like coeff\n        # check validity\n        self._is_pulses_valid()\n\n        if args is None:\n            args = {}\n        else:\n            args = args\n        # set step function\n\n        if not noisy:\n            dynamics = self.pulses\n        else:\n            dynamics = self.get_noisy_pulses(\n                device_noise=True, drift=True)\n\n        qu_list = []\n        c_ops = []\n        for pulse in dynamics:\n            if noisy:\n                qu, new_c_ops = pulse.get_noisy_qobjevo(dims=self.dims)\n                c_ops += new_c_ops\n            else:\n                qu = pulse.get_ideal_qobjevo(dims=self.dims)\n            qu_list.append(qu)\n\n        final_qu = _merge_qobjevo(qu_list)\n        final_qu.args.update(args)\n\n        # bring all c_ops to the same tlist, won't need it in QuTiP 5\n        full_tlist = self.get_full_tlist()\n        temp = []\n        for c_op in c_ops:\n            temp.append(_merge_qobjevo([c_op], full_tlist))\n        c_ops = temp\n\n        if noisy:\n            return final_qu, c_ops\n        else:\n            return final_qu, []\n\n    def run_analytically(self, init_state=None, qc=None):\n        \"\"\"\n        Simulate the state evolution under the given `qutip.QubitCircuit`\n        with matrice exponentiation. It will calculate the propagator\n        with matrix exponentiation and return a list of :class:`qutip.Qobj`.\n        This method won't include noise or collpase.\n\n        Parameters\n        ----------\n        qc: :class:`.QubitCircuit`, optional\n            Takes the quantum circuit to be implemented. If not given, use\n            the quantum circuit saved in the processor by ``load_circuit``.\n\n        init_state: :class:`qutip.Qobj`, optional\n            The initial state of the qubits in the register.\n\n        Returns\n        -------\n        U_list: list\n            A list of propagators obtained for the physical implementation.\n        \"\"\"\n        if init_state is not None:\n            U_list = [init_state]\n        else:\n            U_list = []\n        tlist = self.get_full_tlist()\n        coeffs = self.get_full_coeffs()\n\n        # Compute drift Hamiltonians\n        H_drift = 0\n        for drift_ham in self.drift.drift_hamiltonians:\n            H_drift += drift_ham.get_qobj(self.dims)\n\n        # Compute control Hamiltonians\n        for n in range(len(tlist)-1):\n            H = H_drift + sum(\n                [coeffs[m, n] * self.ctrls[m]\n                    for m in range(len(self.ctrls))])\n            dt = tlist[n + 1] - tlist[n]\n            U = (-1j * H * dt).expm()\n            U = self.eliminate_auxillary_modes(U)\n            U_list.append(U)\n\n        try:  # correct_global_phase are defined for ModelProcessor\n            if self.correct_global_phase and self.global_phase != 0:\n                U_list.append(globalphase(\n                    self.global_phase, N=self.num_qubits)\n                )\n        except AttributeError:\n            pass\n\n        return U_list\n\n    def run(self, qc=None):\n        \"\"\"\n        Calculate the propagator of the evolution by matrix exponentiation.\n        This method won't include noise or collpase.\n\n        Parameters\n        ----------\n        qc: :class:`.QubitCircuit`, optional\n            Takes the quantum circuit to be implemented. If not given, use\n            the quantum circuit saved in the processor by `load_circuit`.\n\n        Returns\n        -------\n        U_list: list\n            The propagator matrix obtained from the physical implementation.\n        \"\"\"\n        if qc:\n            self.load_circuit(qc)\n        return self.run_analytically(qc=qc, init_state=None)\n\n    def run_state(self, init_state=None, analytical=False, states=None,\n                  noisy=True, solver=\"mesolve\", **kwargs):\n        \"\"\"\n        If `analytical` is False, use :func:`qutip.mesolve` to\n        calculate the time of the state evolution\n        and return the result. Other arguments of mesolve can be\n        given as keyword arguments.\n\n        If `analytical` is True, calculate the propagator\n        with matrix exponentiation and return a list of matrices.\n        Noise will be neglected in this option.\n\n        Parameters\n        ----------\n        init_state: Qobj\n            Initial density matrix or state vector (ket).\n\n        analytical: bool\n            If True, calculate the evolution with matrices exponentiation.\n\n        states: :class:`qutip.Qobj`, optional\n            Old API, same as init_state.\n\n        solver: str\n            \"mesolve\" or \"mcsolve\"\n\n        **kwargs\n            Keyword arguments for the qutip solver.\n\n        Returns\n        -------\n        evo_result: :class:`qutip.Result`\n            If ``analytical`` is False,  an instance of the class\n            :class:`qutip.Result` will be returned.\n\n            If ``analytical`` is True, a list of matrices representation\n            is returned.\n        \"\"\"\n        if states is not None:\n            warnings.warn(\n                \"states will be deprecated and replaced by init_state\",\n                DeprecationWarning)\n        if init_state is None and states is None:\n            raise ValueError(\"Qubit state not defined.\")\n        elif init_state is None:\n            # just to keep the old parameters `states`,\n            # it is replaced by init_state\n            init_state = states\n        if analytical:\n            if kwargs or self.noise:\n                raise warnings.warn(\n                    \"Analytical matrices exponentiation\"\n                    \"does not process noise or\"\n                    \"any keyword arguments.\")\n            return self.run_analytically(init_state=init_state)\n\n        # kwargs can not contain H or tlist\n        if \"H\" in kwargs or \"tlist\" in kwargs:\n            raise ValueError(\n                \"`H` and `tlist` are already specified by the processor \"\n                \"and can not be given as a keyword argument\")\n\n        # construct qobjevo for unitary evolution\n        if \"args\" in kwargs:\n            noisy_qobjevo, sys_c_ops = self.get_qobjevo(\n                    args=kwargs[\"args\"], noisy=noisy)\n        else:\n            noisy_qobjevo, sys_c_ops = self.get_qobjevo(noisy=noisy)\n\n        # add collpase operators into kwargs\n        if \"c_ops\" in kwargs:\n            if isinstance(kwargs[\"c_ops\"], (Qobj, QobjEvo)):\n                kwargs[\"c_ops\"] += [kwargs[\"c_ops\"]] + sys_c_ops\n            else:\n                kwargs[\"c_ops\"] += sys_c_ops\n        else:\n            kwargs[\"c_ops\"] = sys_c_ops\n\n        # choose solver:\n        if solver == \"mesolve\":\n            evo_result = mesolve(\n                H=noisy_qobjevo, rho0=init_state,\n                tlist=noisy_qobjevo.tlist, **kwargs)\n        elif solver == \"mcsolve\":\n            evo_result = mcsolve(\n                H=noisy_qobjevo, psi0=init_state,\n                tlist=noisy_qobjevo.tlist, **kwargs)\n\n        return evo_result\n\n    def load_circuit(self, qc):\n        \"\"\"\n        Translate an :class:`.QubitCircuit` to its\n        corresponding Hamiltonians. (Defined in subclasses)\n        \"\"\"\n        raise NotImplementedError(\"Use the function in the sub-class\")\n\n    def eliminate_auxillary_modes(self, U):\n        \"\"\"\n        Eliminate the auxillary modes like the cavity modes in cqed.\n        (Defined in subclasses)\n        \"\"\"\n        return U\n\n    def get_operators_labels(self):\n        \"\"\"\n        Get the labels for each Hamiltonian.\n        It is used in the method``plot_pulses``.\n        It is a 2-d nested list, in the plot,\n        a different color will be used for each sublist.\n        \"\"\"\n        label_list = []\n        for pulse in self.pulses:\n            label_list.append(pulse.label)\n        return [label_list]\n\n    def plot_pulses(\n            self, title=None, figsize=(12, 6), dpi=None,\n            show_axis=False, rescale_pulse_coeffs=True,\n            num_steps=1000):\n        \"\"\"\n        Plot the ideal pulse coefficients.\n\n        Parameters\n        ----------\n        title: str, optional\n            Title for the plot.\n\n        figsize: tuple, optional\n            The size of the figure.\n\n        dpi: int, optional\n            The dpi of the figure.\n\n        show_axis: bool, optional\n            If the axis are shown.\n\n        rescale_pulse_coeffs: bool, optional\n            Rescale the hight of each pulses.\n\n        num_steps: int, optional\n            Number of time steps in the plot.\n\n        Returns\n        -------\n        fig: matplotlib.figure.Figure\n            The `Figure` object for the plot.\n\n        ax: matplotlib.axes._subplots.AxesSubplot\n            The axes for the plot.\n\n        Notes\n        -----\n        ``plot_pulses`` only works for array_like coefficients\n        \"\"\"\n        import matplotlib.pyplot as plt\n        import matplotlib.gridspec as gridspec\n        color_list = plt.rcParams['axes.prop_cycle'].by_key()['color']\n\n        # create a axis for each pulse\n        fig = plt.figure(figsize=figsize, dpi=dpi)\n        grids = gridspec.GridSpec(len(self.pulses), 1)\n        grids.update(wspace=0., hspace=0.)\n\n        tlist = np.linspace(0., self.get_full_tlist()[-1], num_steps)\n        dt = tlist[1] - tlist[0]\n\n        # make sure coeffs start and end with zero, for ax.fill\n        tlist = np.hstack(([-dt*1.e-20], tlist, [tlist[-1] + dt*1.e-20]))\n        coeffs = []\n        for pulse in self.pulses:\n            coeffs.append(_pulse_interpolate(pulse, tlist))\n\n        pulse_ind = 0\n        axis = []\n        for i, label_group in enumerate(self.get_operators_labels()):\n            for j, label in enumerate(label_group):\n                grid = grids[pulse_ind]\n                ax = plt.subplot(grid)\n                axis.append(ax)\n                ax.fill(tlist, coeffs[pulse_ind], color_list[i], alpha=0.7)\n                ax.plot(tlist, coeffs[pulse_ind], color_list[i])\n                if rescale_pulse_coeffs:\n                    ymax = np.max(np.abs(coeffs[pulse_ind])) * 1.1\n                else:\n                    ymax = np.max(np.abs(coeffs)) * 1.1\n                if ymax != 0.:\n                    ax.set_ylim((-ymax, ymax))\n\n                # disable frame and ticks\n                if not show_axis:\n                    ax.set_xticks([])\n                    ax.spines['bottom'].set_visible(False)\n                ax.spines['top'].set_visible(False)\n                ax.spines['right'].set_visible(False)\n                ax.spines['left'].set_visible(False)\n                ax.set_yticks([])\n                ax.set_ylabel(label, rotation=0)\n                pulse_ind += 1\n                if i == 0 and j == 0 and title is not None:\n                    ax.set_title(title)\n        fig.tight_layout()\n        return fig, axis\n\n\ndef _pulse_interpolate(pulse, tlist):\n    \"\"\"\n    A function that calls Scipy interpolation routine. Used for plotting.\n    \"\"\"\n    if pulse.tlist is None and pulse.coeff is None:\n        coeff = np.zeros(len(tlist))\n        return coeff\n    if isinstance(pulse.coeff, bool):\n        if pulse.coeff:\n            coeff = np.ones(len(tlist))\n        else:\n            coeff = np.zeros(len(tlist))\n        return coeff\n    coeff = pulse.coeff\n    if len(coeff) == len(pulse.tlist)-1:  # for discrete pulse\n        coeff = np.concatenate([coeff, [0]])\n\n    from scipy import interpolate\n    if pulse.spline_kind == \"step_func\":\n        kind = \"previous\"\n    else:\n        kind = \"cubic\"\n    inter = interpolate.interp1d(\n        pulse.tlist, coeff, kind=kind,\n        bounds_error=False, fill_value=0.0)\n    return inter(tlist)\n", "meta": {"hexsha": "07b226e664e299119b62a6bb43b35ae0e598895a", "size": 32146, "ext": "py", "lang": "Python", "max_stars_repo_path": "qutip/qip/device/processor.py", "max_stars_repo_name": "madphysicist/qutip", "max_stars_repo_head_hexsha": "2123c66d2a1ed4555e15bbd4dba0d3dc90eced78", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "qutip/qip/device/processor.py", "max_issues_repo_name": "madphysicist/qutip", "max_issues_repo_head_hexsha": "2123c66d2a1ed4555e15bbd4dba0d3dc90eced78", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qutip/qip/device/processor.py", "max_forks_repo_name": "madphysicist/qutip", "max_forks_repo_head_hexsha": "2123c66d2a1ed4555e15bbd4dba0d3dc90eced78", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7149028078, "max_line_length": 79, "alphanum_fraction": 0.5696198594, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.275129717879598, "lm_q1q2_score": 0.15993375134015664}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nDeprecated Colour Models Transformations\n========================================\n\nDefines various deprecated colour models transformations:\n\n-   :func:`RGB_to_HSV`\n-   :func:`HSV_to_RGB`\n-   :func:`RGB_to_HSL`\n-   :func:`HSL_to_RGB`\n-   :func:`RGB_to_CMY`\n-   :func:`CMY_to_RGB`\n-   :func:`CMY_to_CMYK`\n-   :func:`CMYK_to_CMY`\n-   :func:`RGB_to_HEX`\n-   :func:`HEX_to_RGB`\n\nThese colour models are stated as deprecated because they trade off perceptual\nrelevance for computation speed. They should not be used in the colour science\ndomain although they are useful for image analysis and provide end user\nsoftware colour selection tools.\n\nThey are provided for convenience and completeness.\n\nWarning\n-------\nDon't use that! Seriously...\n\nReferences\n----------\n.. [1]  http://en.wikipedia.org/wiki/HSL_and_HSV\n        (Last accessed 10 August 2014)\n.. [2]  `Color Gamut Transform Pairs\n        <http://alvyray.com/Papers/CG/color78.pdf>`_,\n        DOI: http://dx.doi.org/10.1145/800248.807361\n        (Last accessed 10 August 2014)\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport math\nimport numpy as np\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013 - 2014 - Colour Developers'\n__license__ = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-science@googlegroups.com'\n__status__ = 'Production'\n\n__all__ = ['RGB_to_HSV',\n           'HSV_to_RGB',\n           'RGB_to_HSL',\n           'HSL_to_RGB',\n           'RGB_to_CMY',\n           'CMY_to_RGB',\n           'CMY_to_CMYK',\n           'CMYK_to_CMY',\n           'RGB_to_HEX',\n           'HEX_to_RGB']\n\n\ndef RGB_to_HSV(RGB):\n    \"\"\"\n    Converts from *RGB* colourspace to *HSV* colourspace.\n\n    Parameters\n    ----------\n    RGB : array_like, (3,)\n        *RGB* colourspace matrix.\n\n    Returns\n    -------\n    ndarray, (3,)\n        *HSV* matrix.\n\n    Notes\n    -----\n    -   Input *RGB* colourspace matrix is in domain [0, 1].\n    -   Output *HSV* colourspace matrix is in domain [0, 1].\n\n    References\n    ----------\n    .. [3]  http://www.easyrgb.com/index.php?X=MATH&H=20#text20\n            (Last accessed 18 May 2014)\n\n    Examples\n    --------\n    >>> RGB = np.array([0.49019608, 0.98039216, 0.25098039])\n    >>> RGB_to_HSV(RGB)  # doctest: +ELLIPSIS\n    array([ 0.2786738...,  0.744     ,  0.98039216])\n    \"\"\"\n\n    R, G, B = np.ravel(RGB)\n\n    minimum = min(R, G, B)\n    maximum = max(R, G, B)\n    delta = maximum - minimum\n\n    V = maximum\n\n    if delta == 0:\n        H = 0\n        S = 0\n    else:\n\n        S = delta / maximum\n\n        delta_R = (((maximum - R) / 6) + (delta / 2)) / delta\n        delta_G = (((maximum - G) / 6) + (delta / 2)) / delta\n        delta_B = (((maximum - B) / 6) + (delta / 2)) / delta\n\n        if R == maximum:\n            H = delta_B - delta_G\n        elif G == maximum:\n            H = (1 / 3) + delta_R - delta_B\n        elif B == maximum:\n            H = (2 / 3) + delta_G - delta_R\n\n        if H < 0:\n            H += 1\n        if H > 1:\n            H -= 1\n\n    return np.array([H, S, V])\n\n\ndef HSV_to_RGB(HSV):\n    \"\"\"\n    Converts from *HSV* colourspace to *RGB* colourspace.\n\n    Parameters\n    ----------\n    HSV : array_like, (3,)\n        *HSV* colourspace matrix.\n\n    Returns\n    -------\n    ndarray, (3,)\n        *RGB* colourspace matrix.\n\n    Notes\n    -----\n    -   Input *HSV* colourspace matrix is in domain [0, 1].\n    -   Output *RGB* colourspace matrix is in domain [0, 1].\n\n    References\n    ----------\n    .. [4]  http://www.easyrgb.com/index.php?X=MATH&H=21#text21\n            (Last accessed 18 May 2014)\n\n    Examples\n    --------\n    >>> HSV = np.array([0.27867384, 0.744, 0.98039216])\n    >>> HSV_to_RGB(HSV)  # doctest: +ELLIPSIS\n    array([ 0.4901960...,  0.9803921...,  0.2509803...])\n    \"\"\"\n\n    H, S, V = np.ravel(HSV)\n\n    if S == 0:\n        R = V\n        G = V\n        B = V\n    else:\n        h = H * 6\n        if h == 6:\n            h = 0\n\n        i = math.floor(h)\n        j = V * (1 - S)\n        k = V * (1 - S * (h - i))\n        l = V * (1 - S * (1 - (h - i)))\n        if i == 0:\n            R = V\n            G = l\n            B = j\n        elif i == 1:\n            R = k\n            G = V\n            B = j\n        elif i == 2:\n            R = j\n            G = V\n            B = l\n        elif i == 3:\n            R = j\n            G = k\n            B = V\n        elif i == 4:\n            R = l\n            G = j\n            B = V\n        elif i == 5:\n            R = V\n            G = j\n            B = k\n\n    return np.array([R, G, B])\n\n\ndef RGB_to_HSL(RGB):\n    \"\"\"\n    Converts from *RGB* colourspace to *HSL* colourspace.\n\n    Parameters\n    ----------\n    RGB : array_like, (3,)\n        *RGB* colourspace matrix.\n\n    Returns\n    -------\n    ndarray, (3,)\n        *HSL* matrix.\n\n    Notes\n    -----\n    -   Input *RGB* colourspace matrix is in domain [0, 1].\n    -   Output *HSL* colourspace matrix is in domain [0, 1].\n\n    References\n    ----------\n    .. [5]  http://www.easyrgb.com/index.php?X=MATH&H=18#text18\n            (Last accessed 18 May 2014)\n\n    Examples\n    --------\n    >>> RGB = np.array([0.49019608, 0.98039216, 0.25098039])\n    >>> RGB_to_HSL(RGB)  # doctest: +ELLIPSIS\n    array([ 0.2786738...,  0.9489796...,  0.6156862...])\n    \"\"\"\n\n    R, G, B = np.ravel(RGB)\n\n    minimum = min(R, G, B)\n    maximum = max(R, G, B)\n    delta = maximum - minimum\n\n    L = (maximum + minimum) / 2\n\n    if delta == 0:\n        H = 0\n        S = 0\n    else:\n\n        S = delta / (maximum + minimum) if L < 0.5 else delta / (\n            2 - maximum - minimum)\n\n        delta_R = (((maximum - R) / 6) + (delta / 2)) / delta\n        delta_G = (((maximum - G) / 6) + (delta / 2)) / delta\n        delta_B = (((maximum - B) / 6) + (delta / 2)) / delta\n\n        if R == maximum:\n            H = delta_B - delta_G\n        elif G == maximum:\n            H = (1 / 3) + delta_R - delta_B\n        elif B == maximum:\n            H = (2 / 3) + delta_G - delta_R\n\n        if H < 0:\n            H += 1\n        if H > 1:\n            H -= 1\n\n    return np.array([H, S, L])\n\n\ndef HSL_to_RGB(HSL):\n    \"\"\"\n    Converts from *HSL* colourspace to *RGB* colourspace.\n\n    Parameters\n    ----------\n    HSL : array_like, (3,)\n        *HSL* colourspace matrix.\n\n    Returns\n    -------\n    ndarray, (3,)\n        *RGB* colourspace matrix.\n\n    Notes\n    -----\n    -   Input *HSL* colourspace matrix is in domain [0, 1].\n    -   Output *RGB* colourspace matrix is in domain [0, 1].\n\n    References\n    ----------\n    .. [6]  http://www.easyrgb.com/index.php?X=MATH&H=19#text19\n            (Last accessed 18 May 2014)\n\n    Examples\n    --------\n    >>> HSL = np.array([0.27867384, 0.94897959, 0.61568627])\n    >>> HSL_to_RGB(HSL)  # doctest: +ELLIPSIS\n    array([ 0.4901960...,  0.9803921...,  0.2509803...])\n    \"\"\"\n\n    H, S, L = np.ravel(HSL)\n\n    if S == 1:\n        R = L\n        G = L\n        B = L\n    else:\n        def H_to_RGB(vi, vj, vH):\n            \"\"\"\n            Converts *hue* value to *RGB* colourspace.\n            \"\"\"\n\n            if vH < 0:\n                vH += 1\n            if vH > 1:\n                vH -= 1\n            if 6 * vH < 1:\n                return vi + (vj - vi) * 6 * vH\n            if 2 * vH < 1:\n                return vj\n            if 3 * vH < 2:\n                return vi + (vj - vi) * ((2 / 3) - vH) * 6\n            return vi\n\n        j = L * (1 + S) if L < 0.5 else (L + S) - (S * L)\n        i = 2 * L - j\n\n        R = H_to_RGB(i, j, H + (1 / 3))\n        G = H_to_RGB(i, j, H)\n        B = H_to_RGB(i, j, H - (1 / 3))\n\n    return np.array([R, G, B])\n\n\ndef RGB_to_CMY(RGB):\n    \"\"\"\n    Converts from *RGB* colourspace to *CMY* colourspace.\n\n    Parameters\n    ----------\n    RGB : array_like, (3,)\n        *RGB* colourspace matrix.\n\n    Returns\n    -------\n    ndarray, (3,)\n        *CMY* matrix.\n\n    Notes\n    -----\n    -   Input *RGB* colourspace matrix is in domain [0, 1].\n    -   Output *CMY* colourspace matrix is in domain [0, 1].\n\n    References\n    ----------\n    .. [7]  http://www.easyrgb.com/index.php?X=MATH&H=11#text11\n            (Last accessed 18 May 2014)\n\n    Examples\n    --------\n    >>> RGB = np.array([0.49019608, 0.98039216, 0.25098039])\n    >>> RGB_to_CMY(RGB)  # doctest: +ELLIPSIS\n    array([ 0.5098039...,  0.0196078...,  0.7490196...])\n    \"\"\"\n\n    R, G, B = np.ravel(RGB)\n    return np.array([1 - R, 1 - G, 1 - B])\n\n\ndef CMY_to_RGB(CMY):\n    \"\"\"\n    Converts from *CMY* colourspace to *CMY* colourspace.\n\n    Parameters\n    ----------\n    CMY : array_like, (3,)\n        *CMY* colourspace matrix.\n\n    Returns\n    -------\n    ndarray, (3,)\n        *RGB* colourspace matrix.\n\n    Notes\n    -----\n    -   Input *CMY* colourspace matrix is in domain [0, 1].\n    -   Output *RGB* colourspace matrix is in domain [0, 1].\n\n    References\n    ----------\n    .. [8]  http://www.easyrgb.com/index.php?X=MATH&H=12#text12\n            (Last accessed 18 May 2014)\n\n    Examples\n    --------\n    >>> CMY = np.array([0.50980392, 0.01960784, 0.74901961])\n    >>> CMY_to_RGB(CMY)  # doctest: +ELLIPSIS\n    array([ 0.4901960...,  0.9803921...,  0.2509803...])\n    \"\"\"\n\n    C, M, Y = np.ravel(CMY)\n    return np.array([1 - C, 1 - M, 1 - Y])\n\n\ndef CMY_to_CMYK(CMY):\n    \"\"\"\n    Converts from *CMY* colourspace to *CMYK* colourspace.\n\n    Parameters\n    ----------\n    CMY : array_like, (3,)\n        *CMY* colourspace matrix.\n\n    Returns\n    -------\n    ndarray, (4,)\n        *CMYK* matrix.\n\n    Notes\n    -----\n    -   Input *CMY* colourspace matrix is in domain [0, 1].\n    -   Output*CMYK* colourspace matrix is in domain [0, 1].\n\n    References\n    ----------\n    .. [9]  http://www.easyrgb.com/index.php?X=MATH&H=13#text13\n            (Last accessed 18 May 2014)\n\n    Examples\n    --------\n    >>> CMY = np.array([0.50980392, 0.01960784, 0.74901961])\n    >>> CMY_to_CMYK(CMY)  # doctest: +ELLIPSIS\n    array([ 0.5       ,  0.        ,  0.744     ,  0.0196078...])\n    \"\"\"\n\n    C, M, Y = np.ravel(CMY)\n\n    K = 1\n\n    if C < K:\n        K = C\n    if M < K:\n        K = M\n    if Y < K:\n        K = Y\n    if K == 1:\n        C = 0\n        M = 0\n        Y = 0\n    else:\n        C = (C - K) / (1 - K)\n        M = (M - K) / (1 - K)\n        Y = (Y - K) / (1 - K)\n\n    return np.array([C, M, Y, K])\n\n\ndef CMYK_to_CMY(CMYK):\n    \"\"\"\n    Converts from *CMYK* colourspace to *CMY* colourspace.\n\n    Parameters\n    ----------\n    CMYK : array_like, (4,)\n        *CMYK* colourspace matrix.\n\n    Returns\n    -------\n    ndarray, (3,)\n        *CMY* matrix.\n\n    Notes\n    -----\n    -   Input *CMYK* colourspace matrix is in domain [0, 1].\n    -   Output *CMY* colourspace matrix is in domain [0, 1].\n\n    References\n    ----------\n    .. [10] http://www.easyrgb.com/index.php?X=MATH&H=14#text14\n            (Last accessed 18 May 2014)\n\n    Examples\n    --------\n    >>> CMYK = np.array([0.5, 0, 0.744, 0.01960784])\n    >>> CMYK_to_CMY(CMYK)  # doctest: +ELLIPSIS\n    array([ 0.5098039...,  0.0196078...,  0.7490196...])\n    \"\"\"\n\n    C, M, Y, K = np.ravel(CMYK)\n\n    return np.array(\n        [C * (1 - K) + K, M * (1 - K) + K, Y * (1 - K) + K])\n\n\ndef RGB_to_HEX(RGB):\n    \"\"\"\n    Converts from *RGB* colourspace to hex triplet representation.\n\n    Parameters\n    ----------\n    RGB : array_like, (3,)\n        *RGB* colourspace matrix.\n\n    Returns\n    -------\n    unicode\n        Hex triplet representation.\n\n    Notes\n    -----\n    -   Input *RGB* colourspace matrix is in domain [0, 1].\n\n    Examples\n    --------\n    >>> RGB = np.array([0.66666667, 0.86666667, 1])\n    >>> # Doctests skip for Python 2.x compatibility.\n    >>> RGB_to_HEX(RGB)  # doctest: +SKIP\n    '#aaddff'\n    \"\"\"\n\n    RGB = np.ravel(RGB)\n    R, G, B = map(int, RGB * 255)\n    return '#{0:02x}{1:02x}{2:02x}'.format(R, G, B)\n\n\ndef HEX_to_RGB(HEX):\n    \"\"\"\n    Converts from hex triplet representation to *RGB* colourspace.\n\n    Parameters\n    ----------\n    HEX : unicode\n        Hex triplet representation.\n\n    Returns\n    -------\n    ndarray, (3,)\n        *RGB* colourspace matrix.\n\n    Notes\n    -----\n    -   Output *RGB* colourspace matrix is in domain [0, 1].\n\n    Examples\n    --------\n    >>> HEX = '#aaddff'\n    >>> HEX_to_RGB(HEX)  # doctest: +ELLIPSIS\n    array([ 0.6666666...,  0.8666666...,  1.        ])\n    \"\"\"\n\n    HEX = HEX.lstrip('#')\n    length = len(HEX)\n    return np.array([int(HEX[i:i + length // 3], 16) for i in\n                     range(0, length, length // 3)]) / 255\n", "meta": {"hexsha": "70fa7f73eac69bc29dcb31e0c5c4fadd651f0d10", "size": 12470, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/models/deprecated.py", "max_stars_repo_name": "canavandl/colour", "max_stars_repo_head_hexsha": "a453cd37b6135a9092d5ea5b2aafb8d19134bdff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-27T11:32:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-27T11:32:48.000Z", "max_issues_repo_path": "colour/models/deprecated.py", "max_issues_repo_name": "canavandl/colour", "max_issues_repo_head_hexsha": "a453cd37b6135a9092d5ea5b2aafb8d19134bdff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/models/deprecated.py", "max_forks_repo_name": "canavandl/colour", "max_forks_repo_head_hexsha": "a453cd37b6135a9092d5ea5b2aafb8d19134bdff", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.428057554, "max_line_length": 78, "alphanum_fraction": 0.4854049719, "include": true, "reason": "import numpy", "num_tokens": 4023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.25386101825929835, "lm_q1q2_score": 0.15987522310953423}}
{"text": "#!/usr/bin/env python\r\n\r\nfrom __future__ import division\r\nimport mdtraj as md\r\nimport numpy\r\nfrom Bython.Cheminfo import Bymol\r\nfrom Bython.Structure.configstruc import NON_POLAR_ATOMS, PROTEIN_AROMATIC_RES, POLAR_ATOMS, PROTEIN_POSITIVE, PROTEIN_NEGATIVE, PROTEIN_POLAR_SC\r\nfrom itertools import product, chain\r\n\r\ndef SIFT_7bit(traj_ob=None, res_index2=None, res_index=None, aro_cut=4.0, apolar_cut=4.5, hbond_cut=3.5,elec_cut=4.0,verbose=True, use_sc_only=False):\r\n    #Make a list of all protein residue indexes if res_index not defined\r\n    if res_index2 == None:\r\n        res_index2 = [traj_ob.topology.atom(atom_index).residue.index for atom_index in traj_ob.topology.select(' chainid 0 1 and name CA')]\n\n    if res_index == None:\r\n        res_index = [traj_ob.topology.atom(atom_index).residue.index for atom_index in traj_ob.topology.select('chainid 2 3 and name CA')]\r\n           \r\n                  \r\n        print (\"Fingerprint resolution: 7-bits per residue (Apolar, Aromatic Face to Face, Aromatic Edge to Face, \"+\r\n               \"Hbond Protein as Donor, Hbond Protein as Acceptor, Electrostatic Protein +ve, Electrostatic Protein -ve)\")\r\n    #Initialize the array, No_residue X 7 X No_of_ligands\r\n    #sift7bit= numpy.zeros((len(res_index)*7*len(lig_names)), dtype=numpy.int) #traj_ob.xyz.shape[0],\r\n    sift7bit = {} #Key: Ligand index, value: list of bits = 7*no_residues\r\n    #Go through each residue and compute its interaction with each ligands\r\n    for q_res in res_index:\r\n        #Get the residue heavy atom indices\r\n        if not use_sc_only:\r\n            res_heavy_idx = [a_idx for a_idx in traj_ob.topology.select(\"resid \" + str(q_res))\r\n                             if traj_ob.topology.atom(a_idx).element.symbol != 'H']\r\n        else:\r\n            #Do only if residue is not Gly\r\n            if traj_ob.topology.residue(q_res).name.lower() == 'gly':\r\n                continue\r\n            res_heavy_idx = [a_idx for a_idx in traj_ob.topology.select(\"resid \" + str(q_res))\r\n                             if traj_ob.topology.atom(a_idx).element.symbol != 'H' and traj_ob.topology.atom(a_idx).is_sidechain == True]\r\n        \r\n        for q2_res in res_index2:\r\n            #Initialize the residue bits for this ligand\r\n            temp_bits = [0]*7\n\n\t    #Get the residue heavy atom indices\r\n            if not use_sc_only:\r\n                res2_heavy_idx = [a_idx for a_idx in traj_ob.topology.select(\"resid \" + str(q2_res))\r\n                             if traj_ob.topology.atom(a_idx).element.symbol != 'H']\r\n            else:\r\n                #Do only if residue is not Gly\r\n                if traj_ob.topology.residue(q2_res).name.lower() == 'gly':\r\n                    continue\r\n                res2_heavy_idx = [a_idx for a_idx in traj_ob.topology.select(\"resid \" + str(q2_res))\r\n                             if traj_ob.topology.atom(a_idx).element.symbol != 'H' and traj_ob.topology.atom(a_idx).is_sidechain == True]\t\n\r\n            #Create residue and ligand atom-pairs\r\n            a_pairs_dist = list(product(numpy.array(res_heavy_idx), numpy.array(res2_heavy_idx)))\r\n            #Compute all pairwise distances and covert to Angstrom; These distances are in nanometers\r\n            pair_distances = md.compute_distances(traj_ob, a_pairs_dist)*10 #shape (1, no_of_a_pairs_dist)\r\n            #Check If ligand is within Apolar interaction distance\r\n            if numpy.any(pair_distances[pair_distances < apolar_cut]):\r\n                #Check if interaction is apolar\r\n                if IsApolar(traj_ob, numpy.array(a_pairs_dist), pair_distances[0],apolar_cut):\r\n                    #Change the apolar bit\r\n                    temp_bits[0] = 1\r\n            #Check If ligand is within Aromatic interaction distance\r\n            if numpy.any(pair_distances[pair_distances < aro_cut]):\r\n                #Check if interaction is aromatic\r\n                isf2f, ise2f = IsAromatic(traj_ob, numpy.array(a_pairs_dist)\r\n                                                 , pair_distances[0], aro_cut)\r\n                if isf2f:\r\n                    #Change the f2f bit\r\n                    temp_bits[1] = 1\r\n                if ise2f:\r\n                    #Change the f2f bit\r\n                    temp_bits[2] = 1\r\n            #Check If ligand is within Hbond interaction distance\r\n            if numpy.any(pair_distances[pair_distances < hbond_cut]):\r\n                #Check if interaction is Hbond type\r\n                isprotdon, isprotacc = IsHbond(traj_ob, numpy.array(a_pairs_dist),pair_distances[0], hbond_cut)\r\n                if isprotdon:\r\n                    #Change the protein donor bit\r\n                    temp_bits[3] = 1\r\n                if isprotacc:\r\n                    #Change the protein acceptor bit\r\n                    temp_bits[4] = 1\r\n            #Check If ligand is within Electrostatic interaction distance\r\n            if numpy.any(pair_distances[pair_distances < elec_cut]):\r\n                #Check if interaction is Electrostatic\r\n                prot_pos, prot_neg = IsElectro(traj_ob, numpy.array(a_pairs_dist),\r\n                                               pair_distances[0], elec_cut)\r\n                \r\n                if prot_pos:\r\n                    #Change the protein positive bit\r\n                    temp_bits[5] = 1\r\n                if prot_neg:\r\n                    #Change the protein negative bit\r\n                    temp_bits[6] = 1\r\n            \r\n            #append temp_bits to sift7bits\r\n            if not sift7bit.has_key(q2_res):\r\n                sift7bit[q2_res] = temp_bits\r\n            else:\r\n                sift7bit[q2_res].extend(temp_bits)\r\n    #Now Combine the bits for different ligands (also corresponding residue indexes) and return it\r\n    if len(res_index2)> 1:\r\n        combined_sift = [lig_bits for key in sorted(sift7bit) for lig_bits in sift7bit[key]]\r\n        #return combined_sift, list(numpy.array(res_index)+1)*len(sift7bit) #+1 since res_index is 0-based\r\n        return combined_sift, (res_index)*len(sift7bit)\r\n    else:\r\n        return sift7bit[0], res_index        \r\n        \r\ndef IsApolar(traj_object, pair_indices, pair_dist, apolar_cut):\r\n    #Get the atom pair indices that are within cutoff\r\n    prospective_pairs = pair_indices[pair_dist < apolar_cut]\r\n    isapolar = False\r\n    #Check if any of the pairs is non_polar_atom pair\r\n    for a_pair in prospective_pairs:\r\n        #Get the atom symbol\r\n        a1_symbol = traj_object.topology.atom(a_pair[0]).element.symbol.lower()\r\n        a2_symbol = traj_object.topology.atom(a_pair[1]).element.symbol.lower()\r\n        if a1_symbol in NON_POLAR_ATOMS and a2_symbol in NON_POLAR_ATOMS:\r\n            isapolar = True\r\n            break\r\n    return isapolar\r\n\r\ndef IsAromatic(traj_object, pair_indices, pair_dist, aro_cut):\r\n    #Get the atom pair indices that are within cutoff\r\n    prospective_pairs = pair_indices[pair_dist < aro_cut]\r\n    ise2f = False #Interaction is edge to face\r\n    isf2f = False #Interaction is face to face\r\n    \r\n    #Check if any of the pairs is aromatic pair\r\n    for a_pair in prospective_pairs:\r\n        #Get the residue name (first index is for protein atom)\r\n        a1_res_name = traj_object.topology.atom(a_pair[0]).residue.name.lower()\n\ta2_res_name = traj_object.topology.atom(a_pair[1]).residue.name.lower()\r\n        #Check if residue is aromatic type\r\n        if a1_res_name in PROTEIN_AROMATIC_RES and a2_res_name in PROTEIN_AROMATIC_RES:\r\n            #Check if protein atom is in aromatic ring\r\n            a1_atom_name = traj_object.topology.atom(a_pair[0]).name.lower()\r\n            if traj_object.topology.atom(a_pair[0]).is_sidechain and a1_atom_name not in ('cb', 'oh'): # oh for tyr\r\n                #Check if the ligand atom is also aromatic\r\n                a2_atom_name = traj_object.topology.atom(a_pair[1]).name.lower()\r\n                if traj_object.topology.atom(a_pair[1]).is_sidechain and a2_atom_name not in ('cb', 'oh'): # oh for tyr\r\n                    ###Check the angles to see if inteaction is f2f or e2f###\r\n                    \r\n                    #Get the Neighbor atoms (atom objects) of protein atom\r\n                    a1_atom_neighb = GetNeighbor(traj_object, traj_object.topology.atom(a_pair[0]))\r\n                    #Get the coordinates for protein atom in Angstrom and two of its ring neighbor; Hydrogens don't matter\r\n                    a1_atom_cord = traj_object.xyz[:,a_pair[0],:][0]*10\r\n                    a1_atom_neighb1_cord = traj_object.xyz[:,a1_atom_neighb[0].index,:][0]*10\r\n                    a1_atom_neighb2_cord = traj_object.xyz[:,a1_atom_neighb[1].index,:][0]*10\r\n                    #Get the cross product for protein ring\r\n                    prot_ring_normal = GetCross(numpy.array([a1_atom_cord, a1_atom_neighb1_cord, a1_atom_neighb2_cord]))\r\n                    uni_norm_prot_ring = prot_ring_normal / numpy.sqrt((prot_ring_normal*prot_ring_normal).sum()) #Unit-vector\r\n                    \n\n\t\t    #Get the Neighbor atoms (atom objects) of 2nd protein atom\r\n                    a2_atom_neighb = GetNeighbor(traj_object, traj_object.topology.atom(a_pair[1]))\r\n                    #Get the coordinates for protein atom in Angstrom and two of its ring neighbor; Hydrogens don't matter\r\n                    a2_atom_cord = traj_object.xyz[:,a_pair[1],:][0]*10\r\n                    a2_atom_neighb1_cord = traj_object.xyz[:,a2_atom_neighb[0].index,:][0]*10\r\n                    a2_atom_neighb2_cord = traj_object.xyz[:,a2_atom_neighb[1].index,:][0]*10\r\n                    #Get the cross product for protein ring\r\n                    prot_ring_normal = GetCross(numpy.array([a2_atom_cord, a2_atom_neighb1_cord, a2_atom_neighb2_cord]))\r\n                    uni_norm_prot2_ring = prot_ring_normal / numpy.sqrt((prot_ring_normal*prot_ring_normal).sum()) #Unit-vector\n\n\n\t\t    #Get the angle between unit normal vectors\r\n                    normal_thetha_deg = numpy.degrees(numpy.arccos(numpy.dot(uni_norm_prot2_ring, uni_norm_prot_ring)))  # In radians\r\n                    \r\n                    if normal_thetha_deg <= 30.0 or normal_thetha_deg >= 150.0:\r\n                        isf2f = True\r\n                    if normal_thetha_deg > 30.0 and normal_thetha_deg < 150.0:\r\n                        ise2f = True\r\n                    #If both e2f and f2f have been assigned then no need to check further pairs for this residue\r\n                    if isf2f and ise2f:\r\n                        break\r\n    return isf2f, ise2f\r\n\r\ndef IsHbond(traj_object, pair_indices, pair_dist, hbond_cut):\r\n    #Get the atom pair indices that are within cutoff\r\n    prospective_pairs = pair_indices[pair_dist < hbond_cut]\r\n    hbond_prot_acceptor = False\r\n    hbond_prot_donor = False\r\n    #Check if any of the pairs is polar_atom pair\r\n    for a_pair in prospective_pairs:\r\n        #Get the atom symbol\r\n        a1_symbol = traj_object.topology.atom(a_pair[0]).element.symbol.lower()\r\n        a2_symbol = traj_object.topology.atom(a_pair[1]).element.symbol.lower()\r\n        if a1_symbol in POLAR_ATOMS and a2_symbol in POLAR_ATOMS:\r\n            ###Check if angle criteria is satisfied###\r\n            #Get the Neighbor atoms (atom objects) of protein atom\r\n            a1_atom_neighb = GetNeighbor(traj_object, traj_object.topology.atom(a_pair[0]))\r\n            #Check if protein 1 atom is DONOR\r\n            prot_don_hyd = [a1_neig for a1_neig in a1_atom_neighb if a1_neig.element.symbol == 'H']\r\n            if prot_don_hyd:\r\n                is_prot_donor = True\r\n            else:\r\n                is_prot_donor = False\r\n            \n            #Get the neighbors of the 2nd protein atom\r\n            #Get the Neighbor atoms (atom objects) of protein atom\r\n            a2_atom_neighb = GetNeighbor(traj_object, traj_object.topology.atom(a_pair[1]))\r\n            #Check if protein 2 atom is DONOR\r\n            prot2_don_hyd = [a2_neig for a2_neig in a2_atom_neighb if a2_neig.element.symbol == 'H']\r\n            if prot2_don_hyd:\r\n                is_prot2_donor = True\r\n            else:\r\n                is_prot2_donor = False\r\n            #Get protein atom coordinate\r\n            a1_atom_cord = traj_object.xyz[:,a_pair[0],:][0]*10\r\n            #Get protein 2 atom coordinate\r\n            a2_atom_cord = traj_object.xyz[:,a_pair[1],:][0]*10\r\n            #Check angles if protein acceptor and protein 2 donor\r\n            if not is_prot_donor and is_prot2_donor:\r\n                #Go through each neighboring hydrogen atom\r\n                for h_neig in prot2_don_hyd:\r\n                    #Get the coordinates\r\n                    prot2_hyd_cord = traj_object.xyz[:,h_neig.index,:][0]*10\r\n                    Thetha_degree = GetAngle(numpy.array([a1_atom_cord, prot2_hyd_cord, a2_atom_cord]))\r\n                    if Thetha_degree > 135.0:\r\n                        hbond_prot_acceptor = True\r\n                        break #No need to go through rest of the hydrogens\r\n            #Check angles if protein donor and protein 2 acceptor\r\n            if is_prot_donor and not is_prot2_donor:\r\n                #Go through each neighboring hydrogen atom\r\n                for h_neig in prot_don_hyd:\r\n                    #Get the coordinates\r\n                    prot_hyd_cord = traj_object.xyz[:,h_neig.index,:][0]*10\r\n                    Thetha_degree = GetAngle(numpy.array([a2_atom_cord, prot_hyd_cord, a1_atom_cord]))\r\n                    if Thetha_degree > 135.0:\r\n                        hbond_prot_donor = True\r\n                        break #No need to go through rest of the hydrogens\r\n            #Check if both ligand and protein atom are donor, then Hbond still possible with one as acceptor and other as donor\r\n            if is_prot_donor and is_prot2_donor:\r\n                #Do Hbond determination for both to see which one is acceptor/donor\r\n                #Assuming protein donor, go through each neighboring hydrogen atom of protein donor\r\n                for h_neig in prot_don_hyd:\r\n                    #Get the coordinates\r\n                    prot_hyd_cord = traj_object.xyz[:,h_neig.index,:][0]*10\r\n                    Thetha_degree = GetAngle(numpy.array([a2_atom_cord, prot_hyd_cord, a1_atom_cord]))\r\n                    if Thetha_degree > 135.0:\r\n                        hbond_prot_donor = True\r\n                        break #No need to go through rest of the hydrogens\r\n                #Assuming ligand donor, go through each neighboring hydrogen atom of ligand donor\r\n                for h_neig in prot2_don_hyd:\r\n                    #Get the coordinates\r\n                    prot2_hyd_cord = traj_object.xyz[:,h_neig.index,:][0]*10\r\n                    Thetha_degree = GetAngle(numpy.array([a1_atom_cord, prot2_hyd_cord, a2_atom_cord]))\r\n                    if Thetha_degree > 135.0:\r\n                        hbond_prot_acceptor = True\r\n                        break #No need to go through rest of the hydrogens\r\n                \r\n            #If both donor and acceptor have been assigned then no need to check further pairs for this residue\r\n            if hbond_prot_acceptor and hbond_prot_donor:\r\n                break\r\n    return hbond_prot_donor, hbond_prot_acceptor\r\n\r\ndef IsElectro(traj_object, pair_indices, pair_dist, elec_cut):\r\n    #Get the atom pair indices that are within cutoff\r\n    prospective_pairs = pair_indices[pair_dist < elec_cut]\r\n    prot_pos = False\r\n    prot_neg = False\r\n    #Check if any of the pairs is polar_atom pair\r\n    for a_pair in prospective_pairs:\r\n        #Get the residue name (first index is for protein atom)\r\n        a1_res_name = traj_object.topology.atom(a_pair[0]).residue.name.lower()\n\ta2_res_name = traj_object.topology.atom(a_pair[1]).residue.name.lower()\r\n        #Check if residue is charged type\r\n        if a1_res_name in PROTEIN_POSITIVE + PROTEIN_NEGATIVE and a2_res_name in PROTEIN_POSITIVE + PROTEIN_NEGATIVE:\r\n            #Get the atom symbol\r\n            a1_symbol = traj_object.topology.atom(a_pair[0]).element.symbol.lower()\r\n            #Check if protein atom is in sidechain and is polar\r\n            if traj_object.topology.atom(a_pair[0]).is_sidechain and a1_symbol in POLAR_ATOMS:\r\n                #Check if protein 2 atom is in sidechain and polar\r\n                a2_symbol = traj_object.topology.atom(a_pair[1]).element.symbol.lower()\r\n            \tif traj_object.topology.atom(a_pair[1]).is_sidechain and a2_symbol in POLAR_ATOMS:\r\n                    #If protein 1 is negatively charged and protein 2 is postively charged\r\n                    if a1_res_name in PROTEIN_NEGATIVE and a2_res_name in PROTEIN_POSITIVE:\r\n                        prot_neg = True\r\n                    if a1_res_name in PROTEIN_POSITIVE and a2_res_name in PROTEIN_NEGATIVE:\r\n                        prot_pos = True\r\n            if prot_neg and prot_pos:\r\n                break       \r\n    return prot_pos, prot_neg\r\n    \r\ndef GetNeighbor(traj_object, atom_name):\r\n    '''\r\n    Returns a tuple of Neighbors of atom (atom object is returned)\r\n    atom_name (in the format ex. TYR86-CE1; mdtraj atom object)\r\n    '''\r\n    #print atom_name\r\n    each_neighb = [list(each_bond) for each_bond in traj_object.topology.bonds if atom_name in each_bond]\r\n    if not each_neighb:\r\n        raise Exception(\"Topology Object doesn't contain bond information. Use PDB file to define top in Readtraj\")\r\n    neighbs = list(set([all_neighb for all_neighb in chain(*each_neighb)]))\r\n    neighbs.remove(atom_name)\r\n    return tuple(neighbs)\r\n\r\n\r\ndef GetCross(cord_array):\r\n    '''\r\n    Cross product of input 3x3 cord_array\r\n    '''\r\n    vec_12 = cord_array[1] - cord_array[0] #Vector tail at atm1 and head at atm2\r\n    vec_13 = cord_array[2] - cord_array[0] #Vector tail at atm1 and head at atm3\r\n    return numpy.cross(vec_12, vec_13)\r\n\r\ndef GetAngle(cord_array):\r\n    '''\r\n    Returns the angle formed by atom coordinates in input 3x3 cord_array\r\n    '''\r\n    vec_21 = cord_array[0] - cord_array[1] #Vector tail at atm2 and head at atm1\r\n    vec_31 = cord_array[2] - cord_array[1] #Vector tail at atm2 and head at atm3\r\n    dot = numpy.dot(vec_21, vec_31)\r\n    vec_21mod = numpy.sqrt((vec_21*vec_21).sum()) #length of vector 21\r\n    vec_31mod = numpy.sqrt((vec_31*vec_31).sum())\r\n    return numpy.degrees(numpy.arccos(dot / vec_21mod / vec_31mod))        \r\n    \r\n    \r\n    \r\n            \r\n            \r\n       \r\n    \r\n        \r\n            \r\n        \r\n    \r\n    \r\n        \r\n    \r\n    \r\n    \r\n    \r\n    \r\n    \r\n    \r\n", "meta": {"hexsha": "57586762f6eb356c9ab0862fd97408e9e7455b1f", "size": 18414, "ext": "py", "lang": "Python", "max_stars_repo_path": "Trajectory/sift_pro_pro.py", "max_stars_repo_name": "akapoor85/Bython", "max_stars_repo_head_hexsha": "957a274039b168e7144378c0ce80f35abcae631a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Trajectory/sift_pro_pro.py", "max_issues_repo_name": "akapoor85/Bython", "max_issues_repo_head_hexsha": "957a274039b168e7144378c0ce80f35abcae631a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Trajectory/sift_pro_pro.py", "max_forks_repo_name": "akapoor85/Bython", "max_forks_repo_head_hexsha": "957a274039b168e7144378c0ce80f35abcae631a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-15T23:18:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:18:13.000Z", "avg_line_length": 54.6409495549, "max_line_length": 151, "alphanum_fraction": 0.6111111111, "include": true, "reason": "import numpy", "num_tokens": 4422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.2538610013242243, "lm_q1q2_score": 0.1598752089162638}}
{"text": "\"\"\"\n=================\nRoman Instruments\n=================\n\nWARNING: This model has not yet been validated against other PSF\n         simulations, and uses several approximations (e.g. for\n         mirror polishing errors, which are taken from HST).\n\"\"\"\n\nimport os.path\nimport poppy\nimport numpy as np\n\nfrom scipy.interpolate import griddata, RegularGridInterpolator\nfrom astropy.io import fits\nimport astropy.units as u\nimport logging\n\nfrom . import utils\nfrom . import webbpsf_core\nfrom .optics import _fix_zgrid_NaNs\n\n\n_log = logging.getLogger('webbpsf')\nimport pprint\n\nGRISM_FILTERS = ('GRISM0', 'GRISM1')\nPRISM_FILTERS = ('PRISM',)\n\nclass WavelengthDependenceInterpolator(object):\n    \"\"\"WavelengthDependenceInterpolator can be configured with\n    `n_zernikes` worth of Zernike coefficients at up to `n_wavelengths`\n    wavelengths, and will let you `get_aberration_terms` for any\n    wavelength in range interpolated linearly between measured/known\n    points\n    \"\"\"\n\n    def __init__(self, n_wavelengths=16, n_zernikes=22):\n        self._n_wavelengths = n_wavelengths\n        self._n_zernikes = n_zernikes\n        self._aberration_terms = np.zeros((n_wavelengths, n_zernikes), dtype=np.float64)\n        self._wavelengths = []\n\n    def set_aberration_terms(self, wavelength, zernike_array):\n        \"\"\"Supply a reference `wavelength` and a `zernike_array`\n        (of length `n_zernikes`) where the aberration is known\n        \"\"\"\n        n_wavelengths_set = len(self._wavelengths)\n        if wavelength not in self._wavelengths and n_wavelengths_set < self._n_wavelengths:\n            self._wavelengths.append(wavelength)\n            aberration_row_idx = n_wavelengths_set  # which is now index of last row\n        elif wavelength in self._wavelengths:\n            aberration_row_idx = self._wavelengths.index(wavelength)\n        else:\n            # can't add more wavelengths without allocating new _aberration_terms array\n            raise ValueError(\"Already have information at {} wavelengths \"\n                             \"(pass larger n_wavelengths to __init__?)\".format(self._n_wavelengths))\n        if len(zernike_array) != self._n_zernikes:\n            raise ValueError(\"Expected {} aberration terms (pass different \"\n                             \"n_zernikes to __init__?)\".format(self._n_zernikes))\n        self._aberration_terms[aberration_row_idx] = zernike_array\n\n    def get_aberration_terms(self, wavelength):\n        \"\"\"Return the Zernike coefficients as interpolated for this\n        `wavelength`\"\"\"\n        # return array of length n_zernikes interpolated for this wavelength\n        if wavelength in self._wavelengths:\n            # aberration known exactly for this wavelength\n            aberration_row_idx = self._wavelengths.index(wavelength)\n            return self._aberration_terms[aberration_row_idx]\n        else:\n            # we have to interpolate @ this wavelength\n            aberration_terms = griddata(self._wavelengths, self._aberration_terms, wavelength, method='linear')\n            if np.any(np.isnan(aberration_terms)):\n                if isinstance(wavelength, u.Quantity):\n                    wavelength = wavelength.to(u.m).value\n                wavelength_closest = np.clip(wavelength, np.min(self._wavelengths), np.max(self._wavelengths))\n                _log.warn(\"Attempted to get aberrations at wavelength {:.2g} \"\n                          \"outside the range of the reference data; clipping to closest wavelength {:.2g}\".format(\n                    wavelength, wavelength_closest))\n\n                aberration_terms = griddata(self._wavelengths, self._aberration_terms, wavelength_closest,\n                                            method='linear')\n            return aberration_terms\n\nclass FieldDependentAberration(poppy.ZernikeWFE):\n    \"\"\"FieldDependentAberration incorporates aberrations that\n    are interpolated in wavelength, x, and y pixel positions by\n    computing the Zernike coefficients for a particular wavelength\n    and position.\n    \"\"\"\n\n    \"\"\"By default, `get_aberration_terms` will zero out Z1, Z2, and Z3\n    (piston, tip, and tilt) as they are not meaningful for telescope\n    PSF calculations (the former is irrelevant, the latter two would\n    be handled by a distortion solution). Change\n    `_omit_piston_tip_tilt` to False to include the Z1-3 terms.\"\"\"\n    _omit_piston_tip_tilt = True\n    _field_position = None\n\n    def __init__(self, pixel_width, pixel_height,\n                 name=\"Field-dependent Aberration\", radius=1.0, oversample=1, interp_order=3):\n        self.pixel_width, self.pixel_height = pixel_width, pixel_height\n        self.field_position = pixel_width // 2, pixel_height // 2\n        self._wavelength_interpolators = {}\n        self.pupil_diam = radius * 2.0\n        super().__init__(\n            name=name,\n            verbose=True,\n            radius=radius,\n            oversample=oversample,\n            interp_order=interp_order\n        )\n\n    def get_opd(self, wave):\n        \"\"\"Set the Zernike coefficients (for ZernikeWFE.getOPD) based\n        on the wavelength of the incoming wavefront and the pixel\n        position\n        \"\"\"\n        if not isinstance(wave, poppy.Wavefront):\n            wavelength = wave\n        else:\n            wavelength = wave.wavelength\n        self.coefficients = wavelength * self.get_aberration_terms(wavelength)\n        return super().get_opd(wave)\n\n    @property\n    def field_position(self):\n        return self._field_position\n\n    @field_position.setter\n    def field_position(self, position):\n        \"\"\"Set the x and y pixel position on the detector for which to\n        interpolate aberrations\"\"\"\n        x_pixel, y_pixel = position\n        if x_pixel > self.pixel_width or x_pixel < 0:\n            raise ValueError(\"Requested pixel_x position lies outside \"\n                             \"the detector width ({})\".format(x_pixel))\n        if y_pixel > self.pixel_height or y_pixel < 0:\n            raise ValueError(\"Requested pixel_y position lies outside \"\n                             \"the detector height ({})\".format(y_pixel))\n\n        self._field_position = x_pixel, y_pixel\n\n    def add_field_point(self, x_pixel, y_pixel, interpolator):\n        \"\"\"Supply a wavelength-space interpolator for a pixel position\n        on the detector\"\"\"\n        self._wavelength_interpolators[(x_pixel, y_pixel)] = interpolator\n\n    def get_aberration_terms(self, wavelength):\n        \"\"\"Supply the Zernike coefficients for the aberration based on\n        the wavelength and pixel position on the detector\"\"\"\n        if self.field_position in self._wavelength_interpolators:\n            # short path: this is a known point\n            interpolator = self._wavelength_interpolators[self.field_position]\n            coefficients = interpolator.get_aberration_terms(wavelength)\n        else:\n            # get aberrations at all field points\n            field_points, aberration_terms = [], []\n            for field_point_coords, point_interpolator in self._wavelength_interpolators.items():\n                field_points.append(field_point_coords)\n                aberration_terms.append(point_interpolator.get_aberration_terms(wavelength))\n            aberration_array = np.asarray(aberration_terms)\n            assert len(aberration_array.shape) == 2, \"computed aberration array is not 2D \" \\\n                                                     \"(inconsistent number of Zernike terms \" \\\n                                                     \"at each point?)\"\n            field_position = tuple(self.field_position)\n            coefficients = griddata(\n                np.asarray(field_points),\n                np.asarray(aberration_terms),\n                field_position,\n                method='linear'\n            )\n            if np.any(np.isnan(coefficients)):\n                # FIND TWO CLOSEST INPUT GRID POINTS:\n                dist = []\n                corners = field_points[1:]  # use only the corner points\n                for i, ip in enumerate(corners):\n                    dist.append(np.sqrt(((ip[0] - field_position[0]) ** 2) + ((ip[1] - field_position[1]) ** 2)))\n                min_dist_indx = np.argsort(dist)[:2]  # keep two closest points\n                # DEFINE LINE B/W TWO POINTS, FIND ORTHOGONAL LINE AT POINT OF INTEREST,\n                # AND FIND INTERSECTION OF THESE TWO LINES.\n                x1, y1 = corners[min_dist_indx[0]]\n                x2, y2 = corners[min_dist_indx[1]]\n                dx = x2 - x1\n                dy = y2 - y1\n                a = (dy * (field_position[1] - y1) + dx * (field_position[0] - x1)) / (dx * dx + dy * dy)\n                closest_interp_point = (x1 + a * dx, y1 + a * dy)\n                # INTERPOLATE ABERRATIONS TO CLOSEST INTERPOLATED POINT:\n                coefficients = griddata(\n                    np.asarray(field_points),\n                    np.asarray(aberration_terms),\n                    closest_interp_point,\n                    method='linear')\n                # IF CLOSEST INTERPOLATED POINT IS STILL OUTSIDE THE INPUT GRID,\n                # THEN USE NEAREST GRID POINT INSTEAD:\n                if np.any(np.isnan(coefficients)):\n                    coefficients = aberration_terms[min_dist_indx[0] + 1]\n                    _log.warn(\"Attempted to get aberrations at field point {} which is outside the range \"\n                              \"of the reference data; approximating to nearest input grid point\".format(field_position))\n                else:\n                    _log.warn(\"Attempted to get aberrations at field point {} which is outside the range \"\n                              \"of the reference data; approximating to nearest interpolated point {}\".format(\n                        field_position, closest_interp_point))\n                assert not np.any(np.isnan(coefficients)), \"Could not compute aberration \" \\\n                                                           \"at field point {}\".format(field_position)\n        if self._omit_piston_tip_tilt:\n            _log.debug(\"Omitting piston/tip/tilt\")\n            coefficients[:3] = 0.0  # omit piston, tip, and tilt Zernikes\n        return coefficients\n\n\ndef _load_wfi_detector_aberrations(filename):\n    from astropy.io import ascii\n    zernike_table = ascii.read(filename, encoding='utf-8-sig')\n    detectors = {}\n\n    def build_detector_from_table(number, zernike_table):\n        \"\"\"Build a FieldDependentAberration optic for a detector using\n        Zernikes Z1-Z22 at various wavelengths and field points\"\"\"\n        single_detector_info = zernike_table[zernike_table['sca'] == number]\n        field_points = set(single_detector_info['field_point'])\n        interpolators = {}\n        detector = FieldDependentAberration(\n            4096,\n            4096,\n            radius=RomanInstrument.PUPIL_RADIUS,\n            name=\"Field Dependent Aberration (SCA{:02})\".format(number)\n        )\n        for field_id in field_points:\n            field_point_rows = single_detector_info[single_detector_info['field_point'] == field_id]\n            local_x, local_y = field_point_rows[0]['local_x'], field_point_rows[0]['local_y']\n            interpolator = build_wavelength_dependence(field_point_rows)\n\n            midpoint_pixel = 4096 / 2\n            # (local_x in mm / 10 um pixel size) -> * 1e2\n            # local_x and _y range from -20.44 to +20.44, so adding to the midpoint pixel\n            # makes sense to place (-20.44, -20.44) at (4, 4)\n            pixx, pixy = (round(midpoint_pixel - local_x * 1e2),\n                          round(midpoint_pixel + local_y * 1e2))\n\n            detector.add_field_point(pixx, pixy, interpolator)\n        return detector\n\n    def build_wavelength_dependence(rows):\n        \"\"\"Build an interpolator object that interpolates Z1-Z22 in\n        wavelength space\"\"\"\n        wavelengths = set(rows['wavelength'])\n        interpolator = WavelengthDependenceInterpolator(n_wavelengths=len(wavelengths),\n                                                        n_zernikes=22)\n        for row in rows:\n            z = np.zeros(22)\n            for idx in range(22):\n                z[idx] = row['Z{}'.format(idx + 1)]\n            interpolator.set_aberration_terms(row['wavelength'] * 1e-6, z)\n\n        return interpolator\n\n    detector_ids = set(zernike_table['sca'])\n    for detid in detector_ids:\n        detectors[\"SCA{:02}\".format(detid)] = build_detector_from_table(detid, zernike_table)\n\n    return detectors\n\n\n@utils.combine_docstrings\nclass RomanInstrument(webbpsf_core.SpaceTelescopeInstrument):\n    PUPIL_RADIUS = 2.4 / 2.0\n    \"\"\"\n    RomanInstrument contains data and functionality common to Roman\n    instruments, such as setting the pupil shape\n    \"\"\"\n    telescope = \"Roman\"\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.options['jitter'] = 'gaussian'\n        self.options['jitter_sigma'] = 0.012 # arcsec/axis, see https://roman.ipac.caltech.edu/sims/Param_db.html#telescope\n\n    def calc_psf(self, outfile=None, source=None, nlambda=None, monochromatic=None,\n                 fov_arcsec=None, fov_pixels=None, oversample=None, detector_oversample=None, fft_oversample=None,\n                 overwrite=True, display=False, save_intermediates=False, return_intermediates=False,\n                 normalize='first', add_distortion=False, crop_psf=False):\n        \"\"\"\n        Compute a PSF\n\n        Parameters\n        ----------\n        add_distortion : bool\n            Included for API compatibility with the JWST instrument classes, but has no\n            effect on the results for Roman WFI PSF calculations.\n        crop_psf : bool\n            Included for API compatibility with the JWST instrument classes, but has no\n            effect on the results for Roman WFI PSF calculations.\n\n        \"\"\"\n\n        if add_distortion is not False or crop_psf is not False:\n            raise AttributeError('`add_distortion` and `crop_psf` still under '\n                                 'development for Roman WFI')\n            # return default values to True once implemented\n\n        # Run poppy calc_psf\n        psf = webbpsf_core.SpaceTelescopeInstrument.calc_psf(self, outfile=outfile, source=source, nlambda=nlambda,\n                                                monochromatic=monochromatic, fov_arcsec=fov_arcsec,\n                                                fov_pixels=fov_pixels, oversample=oversample,\n                                                detector_oversample=detector_oversample, fft_oversample=fft_oversample,\n                                                overwrite=overwrite, display=display,\n                                                save_intermediates=save_intermediates,\n                                                return_intermediates=return_intermediates, normalize=normalize)\n\n        return psf\n\n    # slightly different versions of the following two functions\n    # from the parent superclass\n    # in order to interface with the FieldDependentAberration class\n    @property\n    def detector_position(self):\n        \"\"\"The pixel position in (X, Y) on the detector\"\"\"\n        return self._detectors[self._detector].field_position\n\n    @detector_position.setter\n    def detector_position(self, position):\n        # exact copy of superclass function except we save the\n        # into a different location.\n        try:\n            x, y = map(int, position)\n        except ValueError:\n            raise ValueError(\"Detector pixel coordinates must be pairs of nonnegative numbers, \"\n                             \"not {}\".format(position))\n        if x < 0 or y < 0:\n            raise ValueError(\"Detector pixel coordinates must be nonnegative integers\")\n        if x > self._detector_npixels - 1 or y > self._detector_npixels - 1:\n            raise ValueError(\"The maximum allowed detector pixel \"\n                             \"coordinate value is {}\".format(self._detector_npixels - 1))\n\n        self._detectors[self._detector].field_position = (int(position[0]), int(position[1]))\n\n    def _get_aberrations(self):\n        \"\"\"Get the OpticalElement that applies the field-dependent\n        optical aberrations. (Called in get_optical_system.)\"\"\"\n        return self._detectors[self._detector]\n\n    def _get_fits_header(self, result, options):\n        \"\"\"Populate FITS Header keywords\"\"\"\n        super()._get_fits_header(result, options)\n        result[0].header['DETXPIXL'] = (self.detector_position[0],\n                                        'X pixel position (for field dependent aberrations)')\n        result[0].header['DETYPIXL'] = (self.detector_position[1],\n                                        'Y pixel position (for field dependent aberrations)')\n        result[0].header['DETECTOR'] = (self.detector, 'Detector selected')\n\n\nclass WFIPupilController:\n    \"\"\"\n    This is a helper class for the WFI and is used to swap in\n    the correct pupil each time the detector is changed.\n    The pupil depends on pupil_mask, detector, and filter;\n    pupil_mask is set automatically upon the receipt of the\n    detector and filter values selected by the user in the WFI class.\n    The user should not interact with this class directly, only\n    through the API provided through the WFI class.\n    \"\"\"\n\n    def __init__(self):\n        self._datapath = None\n        self._pupil_basepath = None\n\n        self._pupil = None\n        self._pupil_mask = None # new for webbpsf 1.0\n\n        # Flag to en-/disable automatic selection of the appropriate pupil_mask\n        self._auto_pupil = True\n\n        # Flag to en-/disable automatic selection of the appropriate pupil file\n        self._auto_pupil_mask = True\n\n        # Save formattable pupil file names for each pupil mask\n        self.pupil_file_formatters = {\n            'SKINNY': 'RST_WIM_Filter_skinny_{0}.fits.gz',\n            'WIDE': 'RST_WIM_Filter_F184_{0}.fits.gz',\n            'GRISM': 'RST_WSM_Grism_Grism_{0}.fits.gz',\n            'PRISM': 'RST_WSM_Prism_Prism_{0}.fits.gz'}\n\n    @property\n    def pupil(self):\n        \"\"\"\n        The path to the FITS file containing pupil information for the\n        detector/filter combination sent from the WFI class. Cannot be\n        directly set by the user.\n        \"\"\"\n        return self._pupil\n\n    @pupil.setter\n    def pupil(self, value):\n        raise AttributeError('Pupil cannot be directly specified. '\n                             'Use lock_pupil() instead.')\n\n    @property\n    def pupil_mask(self):\n        \"\"\"\n        The corresponding mask for the filter sent from the WFI class.\n        (See WFI.pupil_mask_list for a list of valid filters.) Cannot\n        be directly set by the user.\n        \"\"\"\n        return self._pupil_mask\n\n    @pupil_mask.setter\n    def pupil_mask(self, name):\n        raise AttributeError('Pupil mask cannot be directly specified. '\n                             'Use lock_pupil_mask() instead.')\n\n    def _get_filter_mask(self, wfi_filter):\n        \"\"\"\n        Returns the appropriate mask for a given WFI filter.\n\n        Parameters\n        ----------\n        wfi_filter : string\n            See WFI.filter_list for a list of valid filters.\n        \"\"\"\n        wfi_filter = wfi_filter.upper()\n\n        if wfi_filter in GRISM_FILTERS:\n            return 'GRISM'\n        elif wfi_filter in PRISM_FILTERS:\n            return 'PRISM'\n        elif wfi_filter in ['F184', 'F213']:\n            return 'WIDE'\n        else:\n            # this method should only be called after WFI.filter was validated,\n            # so we assume all inputs are valid and direct those that don't pass\n            # preceding cases to skinny\n            return 'SKINNY'\n\n    def set_base_path(self, datapath):\n        \"\"\"\n        Sets the root directory of the path to WebbPSF's data files.\n        This should be set before this class is used.\n\n        Parameters\n        ----------\n        datapath : string\n            Path to WebbPSF-WFI data files\n        \"\"\"\n        self._datapath = datapath\n        self._pupil_basepath = os.path.join(self._datapath, \"pupils\")\n\n    def update_pupil(self, filter, detector):\n        \"\"\"\n        Selects the specific pupil file corresponding with a detector\n        and filter combination sent from the WFI class. Also finds and\n        indirectly sets the proper pupil_mask in the process.\n\n        Parameters\n        ----------\n        filter : string\n            See WFI.filter_list for a list of valid filters.\n\n        detector : string\n            See WFI.detector_list for a list of valid detectors.\n        \"\"\"\n        if not self._auto_pupil:\n            _log.info('Automatic pupil selection was locked; '\n                      'using user-provided pupil.')\n            return\n\n        if self._pupil_basepath is None:\n           raise Exception('update_pupil called before setting pupil file path')\n\n        # change detector string to match file format (e.g., \"SCA01\" -> \"SCA_1\")\n        det_substr = f\"{detector[:3]}_{str(int((detector[3:])))}\"\n\n        # figure out proper mask based on filter (or use locked mask if enabled)\n        pupil_mask = (self._get_filter_mask(filter) if self._auto_pupil_mask\n                      else self.pupil_mask)\n\n        path_formatter = self.pupil_file_formatters[pupil_mask]\n        pupil = os.path.join(self._pupil_basepath,\n                             path_formatter.format(det_substr))\n\n        self._pupil_mask = pupil_mask\n        self._pupil = pupil\n\n        _log.info(f\"Using {'' if self._auto_pupil_mask else 'locked '}\"\n                  f\"pupil mask '{pupil_mask}' and detector '{detector}'.\")\n\n    def lock_pupil(self, pupil_path):\n        \"\"\"\n        Prevents the WFIPupilController class from dynamically updating\n        the path to the pupil on any changes to the detector or filter\n        selected in the WFI class. Instead, the path remains locked on\n        whichever `pupil_path` was provided to this method.\n\n        CAUTION: This is non-standard usage of the WFI class and may\n        lead to unexpected behavior.\n\n        Parameters\n        ----------\n        pupil_path : string\n            The custom path to your pupil file.\n        \"\"\"\n        self._pupil_mask = None\n        self._pupil = pupil_path\n        self._auto_pupil = False\n\n    def unlock_pupil(self):\n        \"\"\"\n        Undoes the effects of lock_pupil() and resets WFIPupilController\n        to its default state of updating the pupil whenever a detector\n        or filter is changed in the WFI class.\n        \"\"\"\n        self._auto_pupil = True\n\n    def lock_pupil_mask(self, pupil_mask):\n        \"\"\"\n        Prevents the WFIPupilController class from dynamically updating\n        the pupil mask on any changes to the filter selected in the WFI\n        class. Instead, the pupil mask remains locked on whichever\n        `pupil_mask` was provided to this method.\n\n        CAUTION: This is non-standard usage of the WFI class and may\n        lead to unexpected behavior.\n\n        Parameters\n        ----------\n        filter : string\n            See WFI.pupil_mask_list for a list of valid pupil masks.\n        \"\"\"\n        if pupil_mask not in self.pupil_file_formatters.keys():\n            raise Exception('invalid pupil mask')\n        elif not self._auto_pupil:\n            raise Exception('Pupil is locked. Unlock pupil before locking pupil mask.')\n        else:\n            self._pupil_mask = pupil_mask\n            self._auto_pupil_mask = False\n\n    def unlock_pupil_mask(self):\n        \"\"\"\n        Undoes the effects of lock_pupil_mask() and resets\n        WFIPupilController to its default state of updating the pupil\n        mask whenever filter is changed in the WFI class.\n        \"\"\"\n        self._auto_pupil_mask = True\n\n\nclass WFI(RomanInstrument):\n    \"\"\"\n    WFI represents the Roman mission's Wide Field Imager.\n\n    WARNING: This model has not yet been validated against other PSF\n             simulations, and uses several approximations (e.g. for\n             mirror polishing errors, which are taken from HST).\n    \"\"\"\n\n    def __init__(self):\n        # pixel scale is from Roman-AFTA SDT report final version (p. 91)\n        # https://roman.ipac.caltech.edu/sims/Param_db.html\n        pixelscale = 110e-3 # arcsec/px\n\n        # Initialize the aberrations for super().__init__\n        self._aberration_files = {}\n        self._is_custom_aberration = False\n        self._current_aberration_file = \"\"\n\n        super().__init__(\"WFI\", pixelscale=pixelscale)\n\n        # Initialize the pupil controller\n        self._pupil_controller = WFIPupilController()\n        self._pupil_controller.set_base_path(self._datapath)\n\n        self.pupil_mask_list = list(self._pupil_controller.pupil_file_formatters.keys())\n\n        # Define default aberration files for WFI modes\n        self._aberration_files = {\n            'imaging': os.path.join(self._datapath, 'wim_zernikes_cycle9.csv'),\n            'prism': os.path.join(self._datapath,\n                                  'wsm_prism_zernikes_cycle9.csv'),\n            'grism': os.path.join(self._datapath,\n                                  'wsm_grism_zernikes_cycle9.csv'),\n            'custom': None}\n\n        # Load and set default detector from aberration file\n        self._detector_npixels = 4096\n        self._load_detector_aberrations(self._aberration_files[self.mode])\n        self.detector = 'SCA01'\n\n        self.opd_list = [os.path.join(self._WebbPSF_basepath,\n                                      'upscaled_HST_OPD.fits')]\n        self.pupilopd = self.opd_list[-1]\n\n    def _addAdditionalOptics(self, optsys, **kwargs):\n        return optsys, False, None\n\n    def _load_detector_aberrations(self, path):\n        \"\"\"\n        Helper function that, given a path to a file containing detector\n        aberrations, loads the Zernike values and populates the class'\n        dictator list with `FieldDependentAberration` detectors. This\n        function achieves this by calling the\n        `webbpsf.roman._load_wfi_detector_aberrations` function.\n\n        Users should use the `override_aberrations` function to override\n        current aberrations.\n\n        Parameters\n        ----------\n        path : string\n            The path to the file containing detector aberrations.\n        \"\"\"\n        detectors = _load_wfi_detector_aberrations(path)\n        assert len(detectors.keys()) > 0\n\n        self._detectors = detectors\n        self._current_aberration_file = path\n\n    def _validate_config(self, **kwargs):\n        \"\"\"\n        Validates that the WFI is configured sensibly.\n\n        This mainly consists of selecting the masked or unmasked pupil\n        appropriately based on the wavelengths requested.\n        \"\"\"\n        assert self.filter is not None, 'filter is None'\n        assert self.detector is not None, 'detector is None'\n        self._update_pupil()\n\n        assert self.pupil is not None, 'pupil is None'\n        super()._validate_config(**kwargs)\n\n    def _get_filter_mode(self, wfi_filter):\n        \"\"\"\n        Given a filter name, returns the WFI mode.\n\n        Parameters\n        ----------\n        wfi_filter : string\n            Name of WFI filter. See WFI.filter_list for valid values.\n\n        Returns\n        -------\n        mode : string\n            Returns 'imaging', 'grism', or 'prism' depending on filter.\n\n        Raises\n        ------\n        ValueError\n            ...if the input filter is not found in the WFI filter list.\n        \"\"\"\n\n        wfi_filter = wfi_filter.upper()\n        if wfi_filter in GRISM_FILTERS:\n            return 'grism'\n        elif wfi_filter in PRISM_FILTERS:\n            return 'prism'\n        elif wfi_filter in self.filter_list:\n            return 'imaging'\n        else:\n            raise ValueError(f\"Instrument {self.name} doesn't have a filter \"\n                             f\"called {wfi_filter}.\")\n\n    def _update_pupil(self, filter=None, detector=None):\n        if detector is None:\n            detector = self.detector\n        if filter is None:\n            filter = self.filter\n\n        if detector is not None and filter is not None:\n            self._pupil_controller.update_pupil(filter=filter,detector=detector)\n\n    @RomanInstrument.detector.setter\n    def detector(self, value):\n        \"\"\"\n        The current WFI detector. See WFI.detector_list for valid values.\n        \"\"\"\n        if value.upper() not in self.detector_list:\n            raise ValueError(\"Invalid detector. Valid detector names are: {}\".format(', '.join(self.detector_list)))\n\n        self._detector = value.upper()\n        if self._detector is not None:\n            self._update_pupil(detector=self._detector)\n\n    @RomanInstrument.filter.setter\n    def filter(self, value):\n        \"\"\"\n        The current WFI filter. See WFI.filter_list for valid values.\n        \"\"\"\n        # Update filter\n        value = value.upper()\n\n        if value not in self.filter_list:\n            raise ValueError(f\"Instrument {self.name} doesn't have a \"\n                             f\"filter called {value}.\")\n\n        self._filter = value\n\n        # Update aberrations if self._aberration_files has been initiated (not\n        # empty) and if they haven't been locked by user\n        if self._aberration_files and not self._is_custom_aberration:\n\n            # identify aberration file for new mode\n            mode = self._get_filter_mode(self._filter)\n            aberration_file = self._aberration_files[mode]\n\n            # if aberrations are not already loaded for the new mode,\n            # load and replace detectors using the new mode's aberration file\n            if not os.path.samefile(self._current_aberration_file,\n                                    aberration_file):\n                self._load_detector_aberrations(aberration_file)\n\n        # Update pupil only if detector was previously loaded\n        # ( i.e., skip this step when called by super() )\n        if self.detector is not None:\n            self._update_pupil(filter=self._filter)\n\n    @property\n    def pupil(self):\n        \"\"\"\n        The path to the FITS file containing pupil information for the\n        detector/filter combination sent from the WFI class. Cannot be\n        directly set by the user.\n        \"\"\"\n        return self._pupil_controller.pupil\n\n    @pupil.setter\n    def pupil(self, value):\n        # don't allow pupil to be set until the pupil controller is active. (a\n        # parent class tries to set it to None in WFI's preceding super() call)\n        if hasattr(self, '_pupil_controller'):\n            raise AttributeError('Pupil cannot be directly specified. '\n                                 'Use lock_pupil() instead.')\n\n    @property\n    def pupil_mask(self):\n        \"\"\"\n        The corresponding mask for the current filter. Cannot be\n        directly set by the user.\n        \"\"\"\n        return self._pupil_controller.pupil_mask\n\n    @pupil_mask.setter\n    def pupil_mask(self, name):\n        raise AttributeError('Pupil mask cannot be directly specified. '\n                             'Use lock_pupil_mask() instead.')\n\n    @property\n    def mode(self):\n        \"\"\"\n        The current WFI mode. Cannot be directly set by the user.\n        \"\"\"\n        return self._get_filter_mode(self.filter)\n\n    @mode.setter\n    def mode(self, value):\n        raise AttributeError(\"WFI mode cannot be directly specified; \"\n                             \"it is set by changing filters.\")\n\n    def lock_aberrations(self, aberration_path):\n        \"\"\"\n        This function loads user provided aberrations from a file and\n        locks this instrument to only use the provided aberrations (even\n        if the filter or mode change).\n\n        To release the lock and load the default aberrations, use\n        unlock_aberrations(). To load new user provided\n        aberrations, call this function with the new path.\n\n        To load custom aberrations, please provide a csv file\n        containing the detector names, field point positions and Zernike\n        values. The file should contain the following column\n        names/values (comments in parentheses should not be included):\n            - sca (Detector number)\n            - wavelength (µm)\n            - field_point (field point number/ID for SCA and wavelength,\n            starts with 1)\n            - local_x (mm, local detector coords)\n            - local_y (mm, local detector coords)\n            - global_x (mm, global instrument coords)\n            - global_y (mm, global instrument coords)\n            - axis_local_angle_x (XAN)\n            - axis_local_angle_y (YAN)\n            - wfe_rms_waves (nm)\n            - wfe_pv_waves (waves)\n            - Z1 (Zernike phase NOLL coefficients)\n            - Z2 (Zernike phase NOLL coefficients)\n            - Z3 (Zernike phase NOLL coefficients)\n            - Z4 (Zernike phase NOLL coefficients)\n              .\n              .\n              .\n\n        Please refer to the default aberration files for examples. If\n        you have the WebbPSF data installed and defined, you can get the\n        path to that file by running the following:\n            >>> from webbpsf import roman\n            >>> wfi = roman.WFI()\n            >>> print(wfi._aberration_files[\"imaging\"])\n\n        Warning: You should not edit the default files!\n        \"\"\"\n        self._load_detector_aberrations(aberration_path)\n        self._aberration_files['custom'] = aberration_path\n        self._is_custom_aberration = True\n\n    def unlock_aberrations(self):\n         \"\"\"\n         Releases the lock on the detector aberration file location\n         and loads the default file.\n         \"\"\"\n         aberration_path = self._aberration_files[self.mode]\n         self._load_detector_aberrations(aberration_path)\n         self._aberration_files['custom'] = None\n         self._is_custom_aberration = False\n\n    def lock_pupil(self, pupil_path):\n        \"\"\"\n        Prevents dynamic updates of the path to the proper pupil file on\n        any changes to the selected detector or filter. Instead, the\n        path remains locked on whichever `pupil_path` was provided here.\n\n        WARNING: This is non-standard usage of the WFI class and may\n        lead to unexpected behavior.\n\n        Parameters\n        ----------\n        pupil_path : string\n            The custom path to your pupil file.\n        \"\"\"\n        if os.path.isfile(pupil_path):\n            self._pupil_controller.lock_pupil(pupil_path)\n        else:\n            raise FileNotFoundError(f\"{pupil_path} not found.\")\n\n        _log.warning(\"Disabling default pupil selection behavior.\")\n\n    def unlock_pupil(self):\n        \"\"\"\n        Undoes the effects of lock_pupil() by resetting the class to\n        its default state of updating the pupil whenever a detector or\n        filter is changed. If necessary, it also sets the proper pupil\n        for the current detector/filter combination.\n        \"\"\"\n        self._pupil_controller.unlock_pupil()\n        self._update_pupil() # reset pupil\n\n    def lock_pupil_mask(self, pupil_mask):\n        \"\"\"\n        Prevents dynamic updates of the pupil mask on any change to the\n        selected filter. Instead, the pupil mask remains locked on\n        whichever `pupil_mask` was provided here.\n\n        WARNING: This is non-standard usage of the WFI class and may\n        lead to unexpected behavior.\n\n        Parameters\n        ----------\n        filter : string\n            See WFI.pupil_mask_list for a list of valid pupil masks.\n        \"\"\"\n        self._pupil_controller.lock_pupil_mask(pupil_mask)\n        self._update_pupil()\n\n    def unlock_pupil_mask(self):\n        \"\"\"\n        Undoes the effects of lock_pupil_mask() and resets the class to\n        its default state of updating the pupil mask whenever the filter\n        is changed.\n        \"\"\"\n        self._pupil_controller.unlock_pupil_mask()\n        self._update_pupil() # reset pupil mask\n\n\nclass RomanCoronagraph(RomanInstrument):\n    \"\"\"\n    Roman Coronagraph Instrument\n\n    Simulates the PSF of the Roman coronagraph.\n\n    Current functionality is limited to the Shaped Pupil Coronagraph (SPC)\n    observing modes, and these modes are only simulated with static, unaberrated\n    wavefronts, without relay optics and without DM control. The design\n    respresented here is an approximation to a baseline concept, and will be\n    subject to change based on trades studies and technology development.\n\n    Parameters\n    ----------\n    mode : str\n        Roman Coronagraph Instrument observing mode. If not specified, the\n        __init__ function will set this to a default mode 'CHARSPC_F660'\n    pixelscale : float\n        Detector pixelscale. If not specified, the pixelscale will default to\n        0.02 arcsec for configurations usint the IMAGER camera and 0.025 arcsec\n        for the IFS.\n    fov_arcsec : float\n        Field of view in arcseconds. If not specified, the field of view will\n        default to 3.20 arcsec for the IMAGER camera and 1.76 arcsec for the IFS.\n\n    \"\"\"\n\n    camera_list = ['IMAGER', 'IFS']\n    filter_list = ['F660', 'F721', 'F770', 'F890']\n    apodizer_list = ['CHARSPC', 'DISKSPC']\n    fpm_list = ['CHARSPC_F660_BOWTIE', 'CHARSPC_F770_BOWTIE', 'CHARSPC_F890_BOWTIE', 'DISKSPC_F721_ANNULUS']\n    lyotstop_list = ['LS30D88']\n\n    _mode_table = {  # MODE             CAMERA    FILTER  APODIZER   FPM             LYOT STOP\n        'CHARSPC_F660': ('IFS', 'F660', 'CHARSPC', 'CHARSPC_F660_BOWTIE', 'LS30D88'),\n        'CHARSPC_F770': ('IFS', 'F770', 'CHARSPC', 'CHARSPC_F770_BOWTIE', 'LS30D88'),\n        'CHARSPC_F890': ('IFS', 'F890', 'CHARSPC', 'CHARSPC_F890_BOWTIE', 'LS30D88'),\n        'DISKSPC_F721': ('IMAGER', 'F721', 'DISKSPC', 'DISKSPC_F721_ANNULUS', 'LS30D88')}\n\n    def __init__(self, mode=None, pixelscale=None, fov_arcsec=None, apply_static_opd=False):\n        super().__init__(\"RomanCoronagraph\", pixelscale=pixelscale)\n\n        self._detector_npixels = 1024\n        self._detectors = {camera: 'placeholder' for camera in self.camera_list}\n\n        self.pupil_mask_list = self.lyotstop_list  # alias for use in webbpsf_core\n        self.image_mask_list = self.fpm_list  # alias for use in webbpsf_core\n        self.pupil = os.path.join(self._WebbPSF_basepath, 'AFTA_CGI_C5_Pupil_onax_256px_flip.fits')\n        if apply_static_opd:\n            self.pupilopd = os.path.join(self._WebbPSF_basepath, 'CGI', 'OPD', 'CGI_static_OPD.fits')\n        else:\n            self.pupilopd = None\n        self.aberration_optic = None\n        self.options = {'force_coron': True}\n        # Allow the user to pre-emptively override the default instrument FoV and pixel scale\n        if fov_arcsec is not None:\n            self.fov_arcsec = fov_arcsec\n            self._override_fov = True\n        else:\n            self._override_fov = False\n        if pixelscale is not None:\n            self._pixelscale = pixelscale\n            self._override_pixelscale = True\n        else:\n            self._override_pixelscale = False\n\n        if mode is None:\n            self.print_mode_table()\n            _log.info(\"Since the mode was not specified at instantiation, defaulting to CHARSPC_F660\")\n            self.mode = 'CHARSPC_F660'\n        else:\n            self.mode = mode\n\n    @property\n    def camera(self):\n        \"\"\"Currently selected camera name\"\"\"\n        return self._camera\n\n    @camera.setter\n    def camera(self, value):\n        value = value.upper()  # force to uppercase\n        if value not in self.camera_list:\n            raise ValueError(\"Instrument {0} doesn't have a camera called {1}.\".format(self.name, value))\n        self._camera = value\n        if value == 'IMAGER':\n            if not hasattr(self, 'fov_arcsec') or not self._override_fov:\n                self.fov_arcsec = 3.2\n            if not hasattr(self, 'pixelscale') or not self._override_pixelscale:\n                self.pixelscale = 0.020  # Nyquist at 465 nm\n        else:  # default to 'IFS'\n            if not hasattr(self, 'fov_arcsec') or not self._override_fov:\n                self.fov_arcsec = 2 * 0.82  # 2015 SDT report, Section 3.4.1.1.1:\n                                            # IFS has 76 lenslets across the (2 x 0.82) arcsec FoV.\n            if not hasattr(self, 'pixelscale') or not self._override_pixelscale:\n                self.pixelscale = 0.025  # Nyquist at 600 nm\n\n    # for coronagraph, there is one detector per camera and it should be set automatically.\n    @property\n    def detector(self):\n        return self.camera\n\n    @detector.setter\n    def detector(self, value):\n        raise RuntimeError(\"Can't set detector directly for RomanCoronagraph; set camera instead.\")\n\n    @property\n    def filter(self):\n        \"\"\"Currently selected filter name\"\"\"\n        return self._filter\n\n    @filter.setter\n    def filter(self, value):\n        value = value.upper()  # force to uppercase\n        if value not in self.filter_list:\n            raise ValueError(\"Instrument {0} doesn't have a filter called {1}.\".format(self.name, value))\n        self._filter = value\n\n    @property\n    def apodizer(self):\n        \"\"\"Currently selected apodizer name\"\"\"\n        return self._apodizer\n\n    @apodizer.setter\n    def apodizer(self, value):\n        value = value.upper()  # force to uppercase\n        if value not in self.apodizer_list:\n            raise ValueError(\"Instrument {0} doesn't have a apodizer called {1}.\".format(self.name, value))\n        self._apodizer = value\n        if value == 'DISKSPC':\n            self._apodizer_fname = \\\n                os.path.join(self._datapath, \"optics/DISKSPC_SP_256pix.fits.gz\")\n        else:  # for now, default to CHARSPC\n            self._apodizer_fname = \\\n                os.path.join(self._datapath, \"optics/CHARSPC_SP_256pix.fits.gz\")\n\n    @property\n    def fpm(self):\n        \"\"\"Currently selected FPM name\"\"\"\n        return self._fpm\n\n    @fpm.setter\n    def fpm(self, value):\n        value = value.upper()  # force to uppercase\n        if value not in self.fpm_list:\n            raise ValueError(\"Instrument {0} doesn't have a FPM called {1}.\".format(self.name, value))\n        self._fpm = value\n        if value.startswith('DISKSPC'):\n            self._fpmres = 3\n            self._owa = 20.\n            self._Mfpm = int(np.ceil(self._fpmres * self._owa))\n            self._fpm_fname = \\\n                os.path.join(self._datapath,\n                             \"optics/DISKSPC_FPM_65WA200_360deg_-_FP1res{0:d}_evensamp_D{1:03d}_{2:s}.fits.gz\".format(\n                                 self._fpmres, 2 * self._Mfpm, self.filter))\n        else:\n            self._fpmres = 4\n            self._owa = 9.\n            self._Mfpm = int(np.ceil(self._fpmres * self._owa))\n            self._fpm_fname = \\\n                os.path.join(self._datapath,\n                             \"optics/CHARSPC_FPM_25WA90_2x65deg_-_FP1res{0:d}_evensamp_D{1:03d}_{2:s}.fits.gz\".format(\n                                 self._fpmres, 2 * self._Mfpm, self.filter))\n\n    @property\n    def lyotstop(self):\n        \"\"\"Currently selected Lyot stop name\"\"\"\n        return self._lyotstop\n\n    @lyotstop.setter\n    def lyotstop(self, value):\n        # preserve case for this one since we're used to that with the lyot mask names\n        if value not in self.lyotstop_list:\n            raise ValueError(\"Instrument {0} doesn't have a Lyot mask called {1}.\".format(self.name, value))\n        self._lyotstop = value\n        self._lyotstop_fname = os.path.join(self._datapath, \"optics/SPC_LS_30D88_256pix.fits.gz\")\n\n    @property\n    def mode_list(self):\n        \"\"\"Available Observation Modes\"\"\"\n        keys = self._mode_table.keys()\n        keys = sorted(keys)\n        return keys\n\n    # mode works differently since it's a meta-property that affects the other ones:\n    @property\n    def mode(self):\n        \"\"\"Currently selected mode name\"\"\"\n        for modename, settings in self._mode_table.items():\n            if (self.camera == settings[0].upper() and self.filter == settings[1].upper() and\n                    self.apodizer == settings[2].upper() and self.fpm == settings[3].upper() and\n                    self.lyotstop == settings[4]):\n                return modename\n        return 'Custom'\n\n    @mode.setter\n    def mode(self, value):\n        if value not in self.mode_list:\n            raise ValueError(\"Instrument {0} doesn't have a mode called {1}.\".format(self.name, value))\n        settings = self._mode_table[value]\n        self.camera = settings[0]\n        self.filter = settings[1]\n        self.apodizer = settings[2]\n        self.fpm = settings[3]\n        self.lyotstop = settings[4]\n        _log.info('Set the following optical configuration:')\n        _log.info('camera = {0}, filter = {1}, apodizer = {2}, fpm = {3}, lyotstop = {4}'.format(\\\n                  self.camera, self.filter, self.apodizer, self.fpm, self.lyotstop))\n\n    def print_mode_table(self):\n        \"\"\"Print the table of observing mode options and their associated optical configuration\"\"\"\n        _log.info(\"Printing the table of Roman Coronagraph Instrument observing modes supported by WebbPSF.\")\n        _log.info(\"Each is defined by a combo of camera, filter, apodizer, \"\n                  \"focal plane mask (FPM), and Lyot stop settings:\")\n        _log.info(pprint.pformat(self._mode_table))\n\n    @property\n    def detector_position(self):\n        \"\"\"The pixel position in (X, Y) on the detector\"\"\"\n        return 512, 512\n\n    @detector_position.setter\n    def detector_position(self, position):\n        raise RuntimeError(\"Detector position not adjustable for RomanCoronagraph\")\n\n    def _validate_config(self, **kwargs):\n        super()._validate_config(**kwargs)\n\n    def _addAdditionalOptics(self, optsys, oversample=4):\n        \"\"\"Add coronagraphic or spectrographic optics for RomanCoronagraph.\"\"\"\n\n        trySAM = False\n\n        if ('pupil_shift_x' in self.options and self.options['pupil_shift_x'] != 0) or \\\n                ('pupil_shift_y' in self.options and self.options['pupil_shift_y'] != 0):\n            shift = (self.options['pupil_shift_x'], self.options['pupil_shift_y'])\n        else:\n            shift = None\n\n        # Add the shaped pupil apodizer\n        optsys.add_pupil(transmission=self._apodizer_fname, name=self.apodizer, shift=None)\n\n        # Add the FPM\n        optsys.add_image(transmission=self._fpm_fname, name=self.fpm)\n\n        # Add Lyot stop\n        self.pupil_mask = self.lyotstop\n        optsys.add_pupil(transmission=self._lyotstop_fname, name=self.lyotstop, shift=shift)\n\n        # Cast as MatrixFTCoronagraph; this configures the detector\n        occ_box_size = 1.\n        mft_optsys = poppy.MatrixFTCoronagraph(optsys, oversample=oversample, occulter_box=occ_box_size)\n\n        return mft_optsys, trySAM, occ_box_size\n\n    def _get_aberrations(self):\n        \"\"\"Get the OpticalElement that applies the field-dependent\n        optical aberrations. (Called in get_optical_system.)\"\"\"\n        return None\n\n    def _get_fits_header(self, result, options):\n        \"\"\"Populate FITS Header keywords\"\"\"\n        super()._get_fits_header(result, options)\n        pupil_hdr = fits.getheader(self.pupil)\n        apodizer_hdr = fits.getheader(self._apodizer_fname)\n        fpm_hdr = fits.getheader(self._fpm_fname)\n        lyotstop_hdr = fits.getheader(self._lyotstop_fname)\n\n        result[0].header.set('MODE', self.mode, comment='Observing mode')\n        result[0].header.set('CAMERA', self.camera, comment='Imager or IFS')\n        result[0].header.set('APODIZER', self.apodizer, comment='Apodizer')\n        result[0].header.set('APODTRAN', os.path.basename(self._apodizer_fname),\n                             comment='Apodizer transmission')\n        result[0].header.set('PUPLSCAL', apodizer_hdr['PUPLSCAL'],\n                             comment='Apodizer pixel scale in m/pixel')\n        result[0].header.set('PUPLDIAM', apodizer_hdr['PUPLDIAM'],\n                             comment='Full apodizer array size, incl padding.')\n        result[0].header.set('FPM', self.fpm, comment='Focal plane mask')\n        result[0].header.set('FPMTRAN', os.path.basename(self._fpm_fname),\n                             comment='FPM transmission')\n        result[0].header.set('FPMSCAL', fpm_hdr['PIXSCALE'], comment='FPM spatial sampling, arcsec/pix')\n        result[0].header.set('LYOTSTOP', self.lyotstop, comment='Lyot stop')\n        result[0].header.set('LSTRAN', os.path.basename(self._lyotstop_fname),\n                             comment='Lyot stop transmission')\n        result[0].header.set('PUPLSCAL', lyotstop_hdr['PUPLSCAL'],\n                             comment='Lyot stop pixel scale in m/pixel')\n        result[0].header.set('PUPLDIAM', lyotstop_hdr['PUPLDIAM'],\n                             comment='Lyot stop array size, incl padding.')\n", "meta": {"hexsha": "57c0af9af8d88e051302f18f4714d029b8eb108b", "size": 48618, "ext": "py", "lang": "Python", "max_stars_repo_path": "webbpsf/roman.py", "max_stars_repo_name": "check-spelling/webbpsf", "max_stars_repo_head_hexsha": "88d2915e623750dff8be4b9ddbdf15ed15285f4f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "webbpsf/roman.py", "max_issues_repo_name": "check-spelling/webbpsf", "max_issues_repo_head_hexsha": "88d2915e623750dff8be4b9ddbdf15ed15285f4f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-02T15:06:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-02T15:06:50.000Z", "max_forks_repo_path": "webbpsf/roman.py", "max_forks_repo_name": "check-spelling/webbpsf", "max_forks_repo_head_hexsha": "88d2915e623750dff8be4b9ddbdf15ed15285f4f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-27T04:24:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-27T04:24:30.000Z", "avg_line_length": 41.8759689922, "max_line_length": 123, "alphanum_fraction": 0.622999712, "include": true, "reason": "import numpy,from scipy,import astropy,from astropy", "num_tokens": 11127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.25683199138751883, "lm_q1q2_score": 0.15986746959031545}}
{"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport h5py as h5\nfrom . import tof_tools\nimport os,sys\n\n__all__ = [\"sample\",'get_montrig','count_rate','dtc','inc']\n\nclass sample:\n    \"\"\"\n    Store all relevant information for a sample being \n    studied at the RPI Linac. \n\n    Stores and calculates data about a sample studied at\n    the RPI Linac and follows the file structure and naming \n    conventions that are found in codes originating from \n    Brian McDermott, such as \"40mprocess\" and \"h5query\".\n    The output from these codes is used as input for this\n    class.\n\n    Parameters\n    ----------\n    samp_name : str\n        Name of sample of interest, e.g. Ta-2mm, MUST be \n        the same as it appears in file structure of initial\n        raw binary files as it is typically propagated \n        through to the HDF5 file.\n    data_type : str\n        Type of data which was collected, e.g. yield,\n        or transmission\n    tof_arr : numpy array\n        Time of flight data, 1st column is ascending\n        time bins [us], 2nd column is bin width, 3rd\n        column is the summed counts\n    hdf_address : str, optional\n        File address of the hdf file output from 40mprocess\n        which contains: monitors, triggers, and pulse events;\n        must end with slash\n    phys_dims : array_like, optional\n        Physical dimensions [cm] of sample being studied, must be \n        in format [thickness,length,width] or [thickness,radius]\n        where thickness is the length of sample parallel to the\n        Linac beam\n    tau : float, optional\n        The dead time of the system [us] used to collect the counts\n        data, default value is 0 \n    paralyzeable : bool, optional\n        If system used to collect counts data was paralyzeable \n        a different dead time model must be used, default is \n        non-paralyzeable dead-time model\n    plot_montrig : bool, optional\n        Plot the monitor ratio through the montrig function\n    factor : 1-d numpy array, optional\n        Compression factors for the tof groups, 1st compression factor\n        corresponds to time of flights below c_pt[0], 2nd corresponds to tofs above\n        c_pt[0] and below c_pt[1], and so on until end of range is found.\n    c_pts : 1-d numpy array, optional\n        Compression time of flights that seperate the bins that are to be grouped.\n        List points from lowest to highest.\n    avg : bool, optional\n        Return an average of group values instead of\n        the sum in the group. group error is 1/N*(sum(error^2))^(1/2)\n    binedge : bool, optional\n        Return TOF column for grouped data as the first\n        tof in group instead of the mean tof of the\n        group.\n    verbose : bool, optional\n        Choose whether to print out approximate comp pt energy locations\n        and indices. Default is False.\n    FP : float, optional\n        Flight path needed to convert the time of flight values of bins to\n        energies for the compression point selection.\n    verbose : bool, optional\n        Option to print out extra information\n\n    Notes\n    -----\n    Will eventually require break points and grouping \n    metadata.\n\n    Allows for yield calculations, must later include \n    transmission.\n    \"\"\"\n    def __init__(self,samp_name,data_type,tof_arr,hdf_address=None,\n                 phys_dims=None,tau=0.0,paralyzeable=False,\n                 plot_montrig=False,factor=None,c_pts=None,\n                 avg=False,binedge=False,FP=None,verbose=False):\n        \n        if verbose == True:\n            print(\"--------\\n {} data for {}\\n--------\".format(data_type,\n                  samp_name))\n\n        self.samp_name = samp_name\n        self.phys_dims = phys_dims\n        self.data_type = data_type\n\n        #------------------------------------------------------------\n        #------------ Monitors and triggers -------------------------\n        #------------------------------------------------------------\n        default_montrig = False\n\n        if hdf_address == None:\n\n            default_montrig = True\n            print(\"----------\\n----------\")\n            print(\"Monitors and triggers not given, cps calculated with\")\n            print(\"default 1e8 monitor and trigger counts.\")\n            print(\"----------\\n----------\")\n\n            self.montrig = np.array([1e8,1e8])\n\n        else:\n            self.montrig = get_montrig(hdf_address,samp_name,plot=plot_montrig,\n                                       verbose=verbose)\n\n        #------------------------------------------------------------\n        #------------ Count rate ------------------------------------\n        #------------------------------------------------------------\n        if default_montrig:\n            self.cps = count_rate(tof_arr,self.montrig[1],tau,paralyzeable=paralyzeable,\n                 factor=factor,c_pts=c_pts,avg=avg,binedge=binedge,verbose=verbose,FP=FP)\n        else: \n            self.cps = count_rate(tof_arr,self.montrig[1][1],tau,paralyzeable=paralyzeable,\n                 factor=factor,c_pts=c_pts,avg=avg,binedge=binedge,verbose=verbose,FP=FP)\n        #------------------------------------------------------------\n\n\n#------------------------------------------------------------------------------\n\ndef get_montrig(hdf_address,samp_name,plot=False,verbose=False):\n    \"\"\"\n    Collect monitors and triggers used to reduce\n    capture data to proper dead time corrected\n    monitor normalized count rates\n\n    Parameters\n    ----------\n    hdf_address : str\n        File address of the HDF5 file, must end with \"/\"\n    samp_name : str\n        Name of the sample being analyzed. Should\n        match the sample name in the HDF5 filename\n    plot : bool, optional\n        Choose whether to plot the monitors and triggers\n        as a function of cycle number\n    verbose : bool, optional\n        Choose whether to print out trigger and monitor \n        information.\n\n    Returns\n    -------\n    montrig : numpy array\n        Vector of monitor counts and triggers\n\n    Notes\n    -----\n    The montrig array is printed out when function\n    is called, user can see order of monitors and\n    triggers.\n    \"\"\"\n\n    with h5.File(hdf_address+samp_name+\"_master.h5\",\"r\") as hdf:\n\n        mon_counts = []\n        det_counts = []\n        sum_mon = np.zeros(8)\n        sum_trig = np.zeros(2)\n\n        for cycle in hdf[samp_name]:\n            mon_vector = hdf[samp_name+\"/\"+cycle+\"/MON\"]\n            trig_vector = hdf[samp_name+\"/\"+cycle+\"/TRIG\"][0]\n            datag_array = hdf[samp_name+\"/\"+cycle+\"/DATA/GOOD\"]\n            datat_array = hdf[samp_name+\"/\"+cycle+\"/DATA/TRUNC\"]\n            sum_detcts = len(datag_array)+len(datat_array)\n            mon_counts.append(mon_vector)\n            det_counts.append(sum_detcts)\n\n            # number of monitors stored in /MON != to 8\n            if (len(sum_mon) != len(mon_vector)) or (len(sum_trig) != len(trig_vector)):\n                raise ValueError(\"Unexpected number of mon's in /MON\")\n\n            sum_mon += mon_vector\n            sum_trig += trig_vector\n\n        num_cyc = len(hdf[samp_name])\n        mon_counts = np.transpose(mon_counts)\n        # monitor ratios \n        mr0,mr1,mr2 = np.zeros(num_cyc),np.zeros(num_cyc),np.zeros(num_cyc)\n        for i in range(num_cyc):\n            mr0[i] = det_counts[i]/mon_counts[0][i]\n            mr1[i] = det_counts[i]/mon_counts[1][i]\n            mr2[i] = det_counts[i]/mon_counts[2][i]\n        # std of monitor cycles / mean of mon. cycles\n        stdmean = [0,0,0]\n        stdmean[0] = np.std(mr0)/np.mean(mr0)\n        stdmean[1] = np.std(mr1)/np.mean(mr1)\n        stdmean[2] = np.std(mr2)/np.mean(mr2)\n        \n        if plot:\n            x = range(num_cyc)\n            plt.plot(x,mr0/np.mean(mr0),label=\"Sum/Mon 0\")\n            plt.plot(x,mr1/np.mean(mr1),label=\"Sum/Mon 1\")\n            plt.plot(x,mr2/np.mean(mr2),label=\"Sum/Mon 2\")\n            plt.legend()\n            plt.show()\n        \n        montrig = np.array([sum_mon,sum_trig])\n        if verbose == True:\n            print(\"         Counts          Std/mean\")\n            for i in range(len(stdmean)):\n                print(\"Mon. {} : {}  ,  {}\".format(i,sum_mon[i],stdmean[i]))\n            if len(sum_trig>1):\n                print(\"Triggers : {}  {}\".format(montrig[1][0],montrig[1][1]))\n\n    return montrig\n\n\ndef count_rate(tof_arr,trig,tau=None,paralyzeable=False,factor=None,c_pts=None,\n               avg=False,binedge=False,verbose=False,FP=None):\n    \"\"\"\n    Converts counts to dead-time corrected count\n    rates\n\n    Parameters\n    ----------\n    tof_arr : 2-d numpy array\n        Time of flight data, 1st column is ascending\n        time bins [us], 2nd column is the summed counts,\n        and the 3rd column (if desired) is error on the \n        counts. 3rd column only necessary if avg==True.\n        !! time of flight data **MUST** be equal bin sizes !!\n    trig : float\n        Triggers recorded for the sample\n    tau : float\n        The dead time of the system used to collect \n        counts data [us]\n    paralyzeable : bool,optional\n        If the system used to collect the counts data\n        was paralyzeable, a different dead time model\n        must be used\n    factor : 1-d numpy array, optional\n        Compression factors for the tof groups, 1st compression factor\n        corresponds to time of flights below c_pt[0], 2nd corresponds to tofs above\n        c_pt[0] and below c_pt[1], and so on until end of range is found.\n    c_pts : 1-d numpy array\n        Compression time of flights that seperate the bins that are to be grouped.\n        List points from lowest to highest.\n    avg : bool, optional\n        Return an average of group values instead of\n        the sum in the group. group error is 1/N*(sum(error^2))^(1/2)\n    binedge : bool, optional\n        Return TOF column for grouped data as the first\n        tof in group instead of the mean tof of the\n        group.\n    verbose : bool, optional\n        Choose whether to print out approximate comp pt energy locations\n        and indices. Default is False.\n    FP : float\n        Flight path needed to convert the time of flight values of bins to\n        energies for the compression point selection.\n\n    Returns\n    -------\n    dc_arr : 2-d numpy array\n        TOF data, 1st column ascending time bins [us],\n        2nd column is count rate [cps], 3rd column is \n        the error on that count rate\n\n    Notes\n    -----\n    Units matter!!\n\n    Error for count rates are sqrt of the counts vector user \n    provides.\n\n    Dead time correction error given in the dead time correction\n    function `dtc()`.\n\n    .. math:: CPS = \\\\frac{C}{b_w Trig}\n\n    .. math:: \\\\Delta C = \\\\sqrt{C}\n\n    .. math:: \\\\Delta CPS = \\\\sqrt{\\\\left(\\\\frac{\\\\Delta C}{b_w Trig}\\\\right)^2}\n\n    .. math:: CPS_{DC} = (CPS) dtcf \n\n    .. math:: \\\\Delta CPS_{DC}=\\\\sqrt{\\\\left(\\\\frac{\\\\Delta CPS}{CPS} \\\\right)^2 + \\\\left(\\\\frac{\\\\Delta dtcf}{dtcf} \\\\right)^2}\n\n    \"\"\"\n    use_single_group = False\n    use_comp_group = False\n\n    # -------------------------------------------------------------------------\n    # ---- run some checks ----------------------------------------------------\n    # -------------------------------------------------------------------------\n    # did the user give one grouping input but not the other?\n    mismatch1 = ((factor is None) and (c_pts is not None))\n    mismatch2 = ((factor is not None) and (c_pts is None))\n    if mismatch1:\n        raise ValueError(\"c_pts given, but factor is not.\")\n    # if mismatch2, we may need to use single group if factor is not an array\n    if mismatch2:\n        try:\n            len(factor)\n            raise ValueError()\n        except TypeError:\n            print('Using single group')\n            use_single_group = True\n        except:\n            print('Factor is an array and c_pts is not given. Aborting.')\n            raise ValueError(\"Check input for argument: factor.\")\n    if factor is not None and c_pts is not None:\n        use_comp_group = True\n    if use_comp_group:\n        # we need the flight path for comp_group\n        if FP is None:\n            raise ValueError(\"Specify the flight path for comp_group()\")\n\n    # cast array into np array\n    tof_arr = np.array(tof_arr)\n    # if input is pandas, may need to transpose\n    if tof_arr.shape[0] > tof_arr.shape[1]:\n        tof_arr = np.transpose(tof_arr)\n\n    # -------------------------------------------------------------------------\n    # ---- Calculate and apply dead time correction ---------------------------\n    # -------------------------------------------------------------------------\n    if tau is None:\n        tau = 0.0     # will be \"corrected\" by 1.0, with error 0.0\n\n    tau = tau*1e-6    # [us --> s]\n\n    if paralyzeable == False:\n        bin_width = tof_arr[0][1]-tof_arr[0][0]\n        dtcf = dtc(tof_arr[1],tau,trig,bin_width)\n        dc_counts = tof_arr[1]*dtcf[0]\n        # sum of the squares of relative errors in counts and dead-time corr.\n        # time the corrected counts\n        if avg:\n            ecounts = tof_arr[2]\n        else:\n            ecounts = np.sqrt(tof_arr[1])\n\n        rel_err_dtcf = (dtcf[1]/dtcf[0])\n        rel_err_counts = (ecounts/tof_arr[1])\n        edc_counts = np.sqrt(rel_err_dtcf**2 + rel_err_counts**2) * dc_counts\n        # --------------------------------------------\n        # check if error on correction is significant\n        # --------------------------------------------\n        ratio = rel_err_dtcf/(rel_err_dtcf+rel_err_counts)\n        if (ratio > 0.02).any():\n            print(\"Max % of dead time error: \",max(ratio))\n            print(\"!! Dead time correction factor accounts for > 2% error in the counts !!\")\n            print(\"!! This is not accounted for in grouping if avg is not used !!\")\n            print(\"To fix, you have to change the hard-coded grouping function.\")\n\n    else:\n        raise NotImplementedError(\"paralyzeable dead time not implemented.\")\n\n    # -------------------------------------------------------------------------\n    # ---- Group the counts if user has specified -----------------------------\n    # -------------------------------------------------------------------------\n    if use_single_group:\n        # include the input error on the counts\n        gtof_array = tof_tools.single_group([tof_arr[0],dc_counts,ecounts],\n            factor,avg=avg,binedge=binedge)\n    if use_comp_group:\n        # include the input error on the counts\n        gtof_array = tof_tools.comp_group([tof_arr[0],dc_counts,ecounts],\n            factor,c_pts,FP,avg=avg,binedge=binedge,verbose=verbose)\n\n    # -------------------------------------------------------------------------\n    # ---- Calculate the count rate -------------------------------------------\n    # -------------------------------------------------------------------------\n    if use_comp_group is False and use_single_group is False:\n        cps = dc_counts/bin_width/trig/1e-6\n        # error in the cps \n        err_cps = 1/bin_width/trig/1e-6 * edc_counts\n        # stage a tof array for the return statement\n        time_of_flight = tof_arr[0]\n    else:\n        cps = gtof_array[2]/gtof_array[1]/trig/1e-6\n        # error in cps\n        err_cps = 1/gtof_array[1]/trig/1e-6 * gtof_array[3]\n        # stage a tof array for the return statement\n        time_of_flight = gtof_array[0]\n\n    cps_arr = np.array([time_of_flight,cps,err_cps])\n\n\n    return cps_arr\n\n\n\ndef dtc(counts,dead_time,trigs,bin_width):\n    \"\"\"\n    Calculate the TOF dead-time correction factor according\n    to the non-paralyzable model\n\n    Parameters\n    ----------\n    counts : array_like\n        A 1-d array of counts as a function of tof (tof \n        in ascending order, equal bin spacing throughout)\n    dead_time : float\n        The dead time [us] associated with the data collection \n        system.\n    trigs : int\n        The number of triggers = the number of times channel \n        was collecting data. For RPI the number of LINAC \n        pulses.\n    bin_width : float\n        The width of the bins in time [us]. Should be constant\n        for the array of counts.\n\n    Returns\n    -------\n    dtcf : 2-d numpy array\n        The dead time correction factor for the counts array\n        based on the non-paralyzeable dead time model is in \n        column 0 of array dtcf, the error associated with it\n        is in column 1. \n        len(dtcf[0]) = len(dtcf[1]) = len(counts).\n\n    Notes\n    -----\n    dtc() returns 0's for the first bins that span the dead \n    time. 1's would keep the signal closer to reality, but \n    0's make it obvious to the user that those channels do \n    not have a correction applied, and data in this time of\n    flight range is rarely used since it usually occurs before\n    the gamma flash.\n\n    .. math:: dtcf_{\\\\tau>b_w} = \\\\frac{1}{1-\\\\frac{SUM}{trig}} = \\\\frac{1}{1-\\\\frac{\\\\sum_iw_iC_i}{trig}}\n\n    where the weights are all 1 except the first and last bin. \n    First weight is 0.5, last weight is the fraction of bins\n    the dead time minus 0.5 covers (e.g. 3.1 minus 1/2 = 2.6) \n    minus the whole bins dead time minus 0.5 covers (2), so \n    the last weight is 0.6.\n\n    Now the error.\n\n    .. math:: \\\\Delta SUM = \\\\sqrt{\\\\sum_i(w_i\\\\sqrt{C_i})^2}\n\n    .. math:: \\\\Delta dtcf_{\\\\tau>b_w} = \\\\sqrt{\\\\left(\\\\frac{\\\\partial dtcf_{\\\\tau>b_w}}{\\\\partial SUM}\\\\Delta SUM\\\\right)^2} = \\\\sqrt{\\\\left(\\\\frac{\\\\Delta SUM}{trig\\\\left(1-\\\\frac{SUM}{trig}\\\\right)^2}\\\\right)^2} \n\n    .. math:: = \\\\frac{\\\\Delta SUM}{trig\\\\left(1-\\\\frac{SUM}{trig}\\\\right)^2} = \\\\frac{\\\\Delta SUM}{trig}dtcf_{\\\\tau>b_w}^2\n\n    If the dead time is less than the bin width:\n\n    .. math:: dtcf_{\\\\tau<b_w} = \\\\frac{1}{1-\\\\frac{C\\\\tau}{b_wtrig}}\n\n    .. math:: \\\\Delta dtcf_{\\\\tau<b_w} = \\\\sqrt{\\\\left(\\\\frac{\\\\partial dtcf_{\\\\tau<b_w}}{\\\\partial C}\\\\Delta C\\\\right)^2} = \\\\frac{\\\\tau\\\\sqrt{C}}{b_wtrig\\\\left(1-\\\\frac{C\\\\tau}{b_wtrig}\\\\right)^2}\n    \n    Algorithm is a Pythonized version of the dead-time-correction algorithm by Y. Danon, \"Design and Construction of the RPI Enhanced Thermal Neutron Target and Thermal Cross Section Measurements of Rare Earth Isotopes.\", Doctoral Thesis, (1993).\n    \"\"\"\n\n    # cast as numpy = major speedup\n    counts = np.array(counts)\n    lc = len(counts)\n    dtcf = np.zeros(lc)\n    ddtcf = np.zeros(lc)\n    if bin_width>=dead_time:\n        x = counts*dead_time/bin_width/trigs\n        dtcf = 1/(1-x)\n        ddtcf = dead_time*np.sqrt(counts)/bin_width/trigs/(1-x)**2\n    else:\n        # how many bins does the dead time span - 0.5 a bin\n        an = dead_time/bin_width-0.5\n        # how many whole bins does the dead time span\n        n = int(an)\n        # bins 0-n will be left 0 \n        print(\"Channels 0 -\",n,\"set to 0\")\n        # fraction of earliest bin that dead time spans\n        f1 = an-n\n        # add half of current bin\n        SUM = counts[n+1:lc] * 0.5\n        # (w_i(C_i)^0.5)^2 = C_i*0.5*0.5\n        sSUM = SUM*0.5\n        # add preceding whole bins within span of dead time\n        for j in range(1,n+1):\n            SUM += counts[n+1-j:lc-j]\n            sSUM += counts[n+1-j:lc-j]\n        # add the fraction of the last bin dead time spans\n        SUM += f1*counts[0:lc-n-1]\n        sSUM += f1**2*counts[0:lc-n-1]\n        dSUM = np.sqrt(sSUM)\n\n        dtcf[n+1:lc] = 1/(1-SUM/trigs)\n        ddtcf[n+1:lc] = dSUM/trigs*dtcf[n+1:lc]**2\n    return np.array([dtcf,ddtcf])\n\n\ndef inc(x):\n    return x + 1\n\n\n\n\n\n", "meta": {"hexsha": "6c60282c0d58a047c408f77c20374c6d605c2053", "size": 19397, "ext": "py", "lang": "Python", "max_stars_repo_path": "nuctools/sample_create.py", "max_stars_repo_name": "brownjm1968/nuctools", "max_stars_repo_head_hexsha": "159506bd73867684b46deaef8c0075e5092d8cb1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nuctools/sample_create.py", "max_issues_repo_name": "brownjm1968/nuctools", "max_issues_repo_head_hexsha": "159506bd73867684b46deaef8c0075e5092d8cb1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nuctools/sample_create.py", "max_forks_repo_name": "brownjm1968/nuctools", "max_forks_repo_head_hexsha": "159506bd73867684b46deaef8c0075e5092d8cb1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6394422311, "max_line_length": 246, "alphanum_fraction": 0.5693148425, "include": true, "reason": "import numpy", "num_tokens": 4856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.15975887832758262}}
{"text": "#    This file is part of qdpy.\n#\n#    qdpy is free software: you can redistribute it and/or modify\n#    it under the terms of the GNU Lesser General Public License as\n#    published by the Free Software Foundation, either version 3 of\n#    the License, or (at your option) any later version.\n#\n#    qdpy is distributed in the hope that it will be useful,\n#    but WITHOUT ANY WARRANTY; without even the implied warranty of\n#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n#    GNU Lesser General Public License for more details.\n#\n#    You should have received a copy of the GNU Lesser General Public\n#    License along with qdpy. If not, see <http://www.gnu.org/licenses/>.\n\n\n\"\"\"This file contains the CMA-ME emitters, as defined in paper \"Covariance Matrix Adaptation for the Rapid Illumination of Behavior Space\"(https://arxiv.org/abs/1912.02400). Additional algorithms are also included, notably the ME-MAP-Elites algorithm (Multi-Emitter MAP-Elites), as presented in the paper \"Multi-Emitter MAP-Elites: Improving quality, diversity and convergence speed with heterogeneous sets of emitters\".  All emitters are implemented as subclasses of the CMA-ES class, so the library \"cma\" needs to be installed to use them. \"\"\"\n\n__all__ = [\"CMAMEOptimizingEmitter\", \"CMAMERandomDirectionEmitter\", \"CMAMEImprovementEmitter\", \"MEMAPElitesUCB1\"]\n\nfrom typing import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, Mapping, MutableMapping, overload\nimport numpy as np\nimport random\n\n\nfrom .base import *\nfrom .evolution import *\nfrom qdpy.utils import *\nfrom qdpy.phenotype import *\nfrom qdpy.base import *\nfrom qdpy.containers import *\nfrom qdpy import tools\n\n\ntry:\n    import cma\nexcept ImportError:\n    pass\n\n\n\n@registry.register\nclass CMAMEOptimizingEmitter(CMAES):\n    \"\"\"TODO\"\"\"\n\n#    def __init__(self, container: Container, budget: int,\n#            dimension: int, **kwargs):\n#        super().__init__(container, budget, dimension=dimension, **kwargs)\n\n    def reinit(self) -> None:\n        super().reinit()\n        self.restart()\n\n    def restart(self):\n        if len(self.container):\n            init_ind = random.choice(self.container)\n        else:\n            init_ind = [0.] * self.dimension\n        self.es = cma.CMAEvolutionStrategy(init_ind, self.sigma0, self._opts)\n        self._pop_inds.clear()\n        self._pop_fitness_vals.clear()\n\n    def _stop(self) -> bool:\n        term_cond = self.es.stop(check=False)\n        #if len(term_cond) > 0:\n        #    print(f\"RESTART!!!: {term_cond}\")\n        return len(term_cond) > 0\n\n    def _internal_ask(self, base_ind: IndividualLike) -> IndividualLike:\n        if self._stop():\n            self.restart()\n        return super()._internal_ask(base_ind)\n\n\n@registry.register\nclass CMAMERandomDirectionEmitter(CMAMEOptimizingEmitter):\n    \"\"\"TODO\"\"\"\n\n    def restart(self):\n        super().restart()\n        features_domain = np.array(self.container.features_domain)\n        self._direction = np.random.normal(0., 1., features_domain.shape[0])\n        self._direction = features_domain[:,0] + self._direction * (features_domain[:,1] - features_domain[:,0])\n        self._features_mean = np.zeros(features_domain.shape[0])\n\n    def _internal_tell(self, individual: IndividualLike, added_to_container: bool, xattr: Mapping[str, Any] = {}) -> None:\n        if self.ignore_if_not_added_to_container and not added_to_container:\n            return\n\n        self._features_mean += np.array(individual.features)\n        if added_to_container:\n            self._pop_inds += [individual]\n\n        if len(self._pop_inds) >= self.es.popsize:\n            self._features_mean /= self.es.popsize\n            _pop_delta = []\n            for ind in self._pop_inds:\n                dv = ind.features - self._features_mean\n                _pop_delta.append(self._direction.dot(dv))\n            try:\n                self.es.tell(self._pop_inds, _pop_delta)\n            except RuntimeError:\n                pass\n            else:\n                self._pop_inds.clear()\n                self._pop_fitness_vals.clear()\n\n\n@registry.register\nclass CMAMEImprovementEmitter(CMAMEOptimizingEmitter):\n    \"\"\"TODO\"\"\"\n\n    _novel_pop_inds: MutableSequence[IndividualLike]\n    _novel_pop_fitness_vals: MutableSequence[Any]\n\n    def restart(self):\n        super().restart()\n        self._novel_pop_inds = []\n        self._novel_pop_fitness_vals = []\n\n    def _tell_before_container_update(self, individual: IndividualLike) -> Tuple[MutableMapping[str, Any], bool]:\n        novel = None\n        delta = 0.\n        prev = None\n        if hasattr(self.container, \"index_grid\") and hasattr(self.container, \"solutions\"):\n            try:\n                idx = self.container.index_grid(individual.features) # type: ignore\n                novel = len(self.container.solutions[idx]) == 0 # type: ignore\n                if not novel:\n                    prev = self.container.solutions[0] # type: ignore\n            except:\n                pass\n        delta = sum(individual.fitness.values)\n        if prev is not None:\n            delta -= sum(prev.fitness.values)\n        return {\"novel\": novel, \"delta\": delta}, True\n\n    def _internal_tell(self, individual: IndividualLike, added_to_container: bool, xattr: Mapping[str, Any] = {}) -> None:\n        if self.ignore_if_not_added_to_container and not added_to_container:\n            return\n        novel = xattr.get(\"novel\", False)\n        delta = xattr.get(\"delta\", 0.)\n\n        if added_to_container:\n            if novel:\n                self._novel_pop_inds += [individual]\n                self._novel_pop_fitness_vals += [-1. * delta]\n            else:\n                self._pop_inds += [individual]\n                self._pop_fitness_vals += [-1. * delta]\n\n        if len(self._pop_inds) + len(self._novel_pop_inds) >= self.es.popsize:\n            tot_pop = []\n            tot_pop_fitness_vals = []\n\n            # Sort individuals\n            sorted_pop_inds = [self._pop_inds[k] for k in argsort(self._pop_fitness_vals)]\n            #sorted_pop_fitness_vals = sorted(self._pop_fitness_vals)\n            sorted_novel_pop_inds = [self._novel_pop_inds[k] for k in argsort(self._novel_pop_fitness_vals)]\n            #sorted_novel_pop_fitness_vals = sorted(self._novel_pop_fitness_vals)\n            for i, ind in enumerate(sorted_novel_pop_inds):\n                tot_pop.append(ind)\n                tot_pop_fitness_vals.append(i)\n            for i, ind in enumerate(sorted_pop_inds):\n                tot_pop.append(ind)\n                tot_pop_fitness_vals.append(len(sorted_novel_pop_inds) + i)\n\n            try:\n                self.es.tell(tot_pop, tot_pop_fitness_vals)\n            except RuntimeError:\n                pass\n            else:\n                self._pop_inds.clear()\n                self._pop_fitness_vals.clear()\n                self._novel_pop_inds.clear()\n                self._novel_pop_fitness_vals.clear()\n\n\n@registry.register\nclass MEMAPElitesUCB1(AlgWrapper):\n    \"\"\"Implementation of the ME-MAP-Elites algorithm (Multi-Emitter MAP-Elites), as presented in the paper \"Multi-Emitter MAP-Elites: Improving quality, diversity and convergence speed with heterogeneous sets of emitters\". UCB1 is used to select the active emitters. \"\"\"\n    zeta: float\n    nb_active_emitters: int\n    _active_emitters_idx: Sequence[int]\n    current_active_idx: int\n    initial_expected_rwds: float\n    shuffle_emitters: bool\n\n    def __init__(self, algorithms: Any, zeta: float = 0.0005, nb_active_emitters: int = 1, initial_expected_rwds: float = 1.,\n            shuffle_emitters: bool = True, **kwargs):\n        self.zeta = zeta\n        self.nb_active_emitters = nb_active_emitters\n        self.initial_expected_rwds = initial_expected_rwds\n        self.shuffle_emitters = shuffle_emitters\n        super().__init__(algorithms, **kwargs)\n\n    def reinit(self) -> None:\n        super().reinit()\n        self._up_active_emitters()\n        self.current_active_idx = 0\n\n    def _up_active_emitters(self) -> None:\n        \"\"\"Update the list of active emitters.\"\"\"\n        #expected_rwds = [\n        #        self.initial_expected_rwds if alg.nb_evaluations == 0 else\n        #        float(alg.nb_updated) / float(alg.nb_evaluations) + self.zeta * math.sqrt(math.log(self.nb_evaluations) / float(alg.nb_evaluations))\n        #        for alg in self.algorithms]\n        #self._active_emitters_idx = argsort(expected_rwds, reverse=True)[:self.nb_active_emitters]\n\n        algos_idx = list(range(len(self.algorithms)))\n        if self.shuffle_emitters:\n            # Shuffle algorithm list\n            random.shuffle(algos_idx)\n        # Compute expected rewards\n        expected_rwds = [\n                self.initial_expected_rwds if self.algorithms[a].nb_evaluations == 0 else\n                    float(self.algorithms[a].nb_updated) / float(self.algorithms[a].nb_evaluations) +\n                    self.zeta * math.sqrt(math.log(self.nb_evaluations) / float(self.algorithms[a].nb_evaluations))\n                for a in algos_idx]\n        # Update active emitters indexes list\n        self._active_emitters_idx = [algos_idx[a] for a in argsort(expected_rwds, reverse=True)][:self.nb_active_emitters]\n        #print(f\"DEBUG _up_active_emitters: {argsort(expected_rwds, reverse=True)}\")\n        #print(f\"DEBUG _up_active_emitters: {expected_rwds}\")\n        #print(f\"DEBUG _up_active_emitters: {self._active_emitters_idx}\")\n\n    def next(self) -> None:\n        \"\"\"Switch to the next algorithm in Sequence `self.algorithms`, if there is one.\"\"\"\n        if self.current_active_idx < len(self._active_emitters_idx) - 1:\n            self.current_active_idx += 1\n        else:\n            self._up_active_emitters()\n            self.current_active_idx = 0\n        next_idx = self._active_emitters_idx[self.current_active_idx]\n        self.switch_to(next_idx)\n        #print(f\"NEXT: {next_idx}\")\n\n\n\n\n\n\n# MODELINE\t\"{{{1\n# vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8\n# vim:foldmethod=marker\n", "meta": {"hexsha": "b9e30ffe5e553153e1514c95d54d5fb85da6f887", "size": 10069, "ext": "py", "lang": "Python", "max_stars_repo_path": "submodules/qdpy/qdpy/algorithms/cmame.py", "max_stars_repo_name": "JiangZehua/control-pcgrl3D", "max_stars_repo_head_hexsha": "f9b04e65e1cbf70b7306f4df251450d83c6fb2be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "submodules/qdpy/qdpy/algorithms/cmame.py", "max_issues_repo_name": "JiangZehua/control-pcgrl3D", "max_issues_repo_head_hexsha": "f9b04e65e1cbf70b7306f4df251450d83c6fb2be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "submodules/qdpy/qdpy/algorithms/cmame.py", "max_forks_repo_name": "JiangZehua/control-pcgrl3D", "max_forks_repo_head_hexsha": "f9b04e65e1cbf70b7306f4df251450d83c6fb2be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0979591837, "max_line_length": 545, "alphanum_fraction": 0.65448406, "include": true, "reason": "import numpy", "num_tokens": 2346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.30074557894124154, "lm_q1q2_score": 0.15975887053430443}}
{"text": "import os\nimport numpy as np\nimport tensorflow as tf\n\nfrom .models.schnet import SchNet\n\n\ndef get_atom_indices(n_atoms, batch_size):\n    n_distances = n_atoms ** 2 - n_atoms\n    seg_m = np.repeat(range(batch_size), n_atoms).astype(np.int32)\n    seg_i = np.repeat(np.arange(n_atoms * batch_size), n_atoms - 1).astype(np.int32)\n    idx_ik = seg_i\n    idx_j = []\n    for b in range(batch_size):\n        for i in range(n_atoms):\n            for j in range(n_atoms):\n                if j != i:\n                    idx_j.append(j + b * n_atoms)\n\n    idx_j = np.hstack(idx_j).ravel().astype(np.int32)\n    offset = np.zeros((n_distances * batch_size, 3), dtype=np.float32)\n    ratio_j = np.ones((n_distances * batch_size,), dtype=np.float32)\n    seg_j = np.arange(n_distances * batch_size, dtype=np.int32)\n\n    seg_m, idx_ik, seg_i, idx_j, seg_j, offset, ratio_j = \\\n        tf.constant(seg_m), tf.constant(idx_ik), tf.constant(seg_i), tf.constant(idx_j), \\\n        tf.constant(seg_j), tf.constant(offset), tf.constant(ratio_j)\n    idx_jk = idx_j\n    return seg_m, idx_ik, seg_i, idx_j, idx_jk, seg_j, offset, ratio_j\n\n\nclass SchNetMD:\n    def __init__(self, energy_model_path, force_model_path=None, batch_size=1,\n                 nuclear_charges=6. * np.ones((20,), dtype=np.int64)):\n\n        self.n_atoms = len(nuclear_charges)\n        seg_m, idx_ik, seg_i, idx_j, idx_jk, seg_j, offset, ratio_j = get_atom_indices(self.n_atoms, batch_size)\n\n        self.energy_model = self.load_model(energy_model_path)\n        self.force_model = self.load_model(force_model_path) \\\n            if force_model_path is not None else None\n\n        self.positions = tf.placeholder(tf.float32, shape=(batch_size * self.n_atoms, 3))\n        self.charges = tf.tile(tf.constant(nuclear_charges.ravel(), dtype=tf.int64),\n                               (batch_size,))\n\n        g = tf.get_default_graph()\n        with g.gradient_override_map({\"Tile\": \"TileDense\"}):\n            self.energy = self.energy_model(self.charges, self.positions,\n                                            offset, idx_ik, idx_jk, idx_j,\n                                            seg_m, seg_i, seg_j, ratio_j)\n            if self.force_model is None:\n                self.forces = -tf.reshape(tf.convert_to_tensor(\n                    tf.gradients(tf.reduce_sum(self.energy), self.positions)[0]),\n                    (batch_size, self.n_atoms, 3))\n            else:\n                energy = self.force_model(self.charges, self.positions,\n                                          offset, idx_ik, idx_jk, idx_j,\n                                          seg_m, seg_i, seg_j, ratio_j)\n                self.forces = -tf.reshape(tf.convert_to_tensor(tf.gradients(tf.reduce_sum(energy),\n                                                                            self.positions)[0]),\n                                          (batch_size, self.n_atoms, 3))\n        self.error = tf.reduce_max(tf.sqrt(tf.reduce_sum(self.forces ** 2, 2)))\n\n        ckpt = tf.train.latest_checkpoint(os.path.join(energy_model_path, 'validation'))\n        self.session = tf.Session()\n        self.energy_model.restore(self.session, ckpt)\n        if self.force_model is not None:\n            ckpt = tf.train.latest_checkpoint(os.path.join(force_model_path, 'validation'))\n            self.force_model.restore(self.session, ckpt)\n\n    def load_model(self, model_path):\n        args = np.load(os.path.join(model_path, 'args.npy')).item()\n\n        model = SchNet(args.interactions, args.basis, args.filters, args.cutoff,\n                       intensive=args.intensive, filter_pool_mode=args.filter_pool_mode)\n        return model\n\n    def get_energy_and_forces(self, positions):\n        positions = positions.reshape((-1, 3)).astype(np.float32)\n        feed_dict = {\n            self.positions: positions\n        }\n        E, F = self.session.run([self.energy, self.forces], feed_dict=feed_dict)\n        return E, F\n\n    def relax(self, positions, eps=0.01, rate=1e-4):\n        err = 100.\n        positions = positions.reshape((-1, 3)).astype(np.float32)\n        print('Start relaxation')\n        count = 0\n        while err > eps:\n            feed_dict = {\n                self.positions: positions\n            }\n            F, err = self.session.run([self.forces, self.error], feed_dict=feed_dict)\n            positions += rate * F[0]\n            count += 1\n            if count % 100 == 0:\n                print('Iteration ', str(count), 'Max Force:', err)\n        print('Maximal force length: ' + str(err))\n        return positions\n", "meta": {"hexsha": "a1f770577c443d819bdefa2daae66e97c8d32a10", "size": 4556, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/schnet/md.py", "max_stars_repo_name": "Yidansong/SchNet", "max_stars_repo_head_hexsha": "49a1e6031f50d79a83ea21148b8e8cbcabdaabb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 155, "max_stars_repo_stars_event_min_datetime": "2017-11-10T19:13:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T05:23:30.000Z", "max_issues_repo_path": "src/schnet/md.py", "max_issues_repo_name": "Yidansong/SchNet", "max_issues_repo_head_hexsha": "49a1e6031f50d79a83ea21148b8e8cbcabdaabb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-10-30T14:02:56.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-26T15:04:47.000Z", "max_forks_repo_path": "src/schnet/md.py", "max_forks_repo_name": "Yidansong/SchNet", "max_forks_repo_head_hexsha": "49a1e6031f50d79a83ea21148b8e8cbcabdaabb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 48, "max_forks_repo_forks_event_min_datetime": "2018-01-11T15:50:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:52:30.000Z", "avg_line_length": 44.2330097087, "max_line_length": 112, "alphanum_fraction": 0.5858208955, "include": true, "reason": "import numpy", "num_tokens": 1063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.15975886720502455}}
{"text": "#!/usr/bin/env python\n\n# Built-in\nimport os\nimport argparse\n\n# Common\nimport numpy as np\n\n_save = True\n_here = os.path.abspath(os.path.dirname(__file__))\n_Exp, _Cls, _name = os.path.split(__file__)[1].split('_')[:3]\nassert not any([any([ss in s for ss in ['Notes','.']])\n               for s in [_Exp, _Cls, _name]])\n\n\n\ndef get_notes():\n    notes = {'DPhi':{}, 'dPhi':{}}\n    # Total toiroidal width in equatorial plane\n    notes['DPhi'] = 346.756\n    # Toroidal gap between central tiles in equatorial plane\n    notes['dPhi'] = 1.500\n    # Total vertical height\n    notes['DZ'] = 1047.517\n    # Poloidal gap between central tiles\n    notes['dl'] = 2.249\n    # Radial width\n    notes['DR'] = 134.678\n\n    # sampleXZY\n    notes['sampleXZY'] = [[2159.632, 523.758, 2030.517],#0\n                          [2149.423, 514.993, 2020.128],\n                          [2148.227, 508.130, 2018.912],\n                          [2154.559, 442.235, 2071.259],    # h\n                          [2166.380, 414.998, 2085.893],    # h\n                          [2178.412, 385.686, 2095.532],    # h\n                          [2206.053, 371.041, 2077.756],    # e1\n                          [2210.863, 369.335, 2082.651],\n                          [2221.072, 378.101, 2093.040],\n                          [2222.233, 374.874, 2094.221],\n                          [2211.288, 368.155, 2083.083],#10\n                          [2209.454, 361.586, 2081.216],    # e2\n                          [2192.106, 347.606, 2109.467],    # h\n                          [2201.248, 317.292, 2118.769],    # h\n                          [2210.389, 286.979, 2128.072],    # h\n                          [2234.025, 280.107, 2106.220],    # e1\n                          [2230.026, 271.564, 2115.303],    # i\n                          [2234.631, 268.948, 2119.988],\n                          [2245.923, 275.667, 2130.785],\n                          [2246.768, 272.245, 2131.645],\n                          [2234.940, 267.696, 2120.303],#20\n                          [2232.501, 261.541, 2117.821],    # i\n                          [2240.819, 252.580, 2113.134],    # e2\n                          [2220.353, 246.610, 2138.212],    # h\n                          [2226.542, 214.813, 2144.510],    # h\n                          [2232.731, 183.016, 2150.808],    # h\n                          [2257.455, 167.114, 2130.063],    # e1\n                          [2261.769, 163.634, 2134.453],\n                          [2273.250, 168.183, 2146.136],\n                          [2273.763, 164.630, 2146.658],\n                          [2261.957, 162.335, 2134.644],#30\n                          [2258.958, 156.705, 2131.592],    # e2\n                          [2238.784, 141.097, 2156.967],    # h\n                          [2241.907, 108.399, 2160.145],    # h\n                          [2245.030, 075.701, 2163.323],    # h\n                          [2268.232, 059.603, 2141.030],    # e1\n                          [2272.178, 055.324, 2145.045],\n                          [2283.984, 057.619, 2157.059],\n                          [2284.156, 054.000, 2157.234],\n                          [2272.241, 054.000, 2145.109],\n                          [2268.736, 049.000, 2141.543],#40 e2\n                          [2247.062, 033.000, 2165.391],    # h\n                          [2272.659, 011.500, 2137.688],    # i\n                          [2247.062, 000.000, 2165.391],    # h\n                          [2247.062,-033.000, 2165.391],    # h\n                          [2268.736,-049.000, 2141.543],    # e1\n                          [2272.241,-054.000, 2145.109],\n                          [2284.156,-054.000, 2157.234],\n                          [2283.984,-057.619, 2157.059],\n                          [2272.178,-055.324, 2145.045],\n                          [2268.232,-059.603, 2141.030],#50 e2\n                          [2245.030,-075.701, 2163.323],    # h\n                          [2241.907,-108.399, 2160.145],    # h\n                          [2238.784,-141.097, 2156.967],    # h\n                          [2258.958,-156.705, 2131.592],    # e1\n                          [2261.957,-162.335, 2134.644],\n                          [2273.763,-164.630, 2146.658],\n                          [2273.250,-168.183, 2146.136],\n                          [2261.769,-163.634, 2134.453],\n                          [2257.455,-167.114, 2130.063],#59 e2\n                          [2232.731,-183.016, 2150.808],    # h\n                          [2226.542,-214.813, 2144.510],    # h\n                          [2220.353,-246.610, 2138.212],    # h\n                          [2240.819,-252.580, 2113.134],    # e1\n                          [2232.501,-261.541, 2117.821],    # i\n                          [2234.940,-267.696, 2120.303],\n                          [2246.768,-272.245, 2131.645],\n                          [2245.923,-275.667, 2130.785],\n                          [2234.631,-268.948, 2119.988],\n                          [2230.026,-271.564, 2115.303],    # i\n                          [2234.025,-280.107, 2106.220],#70 e2\n                          [2210.389,-286.979, 2128.072],    # h\n                          [2201.248,-317.292, 2118.769],    # h\n                          [2192.106,-347.606, 2109.467],    # h\n                          [2209.454,-361.586, 2081.216],    # e1\n                          [2211.288,-368.155, 2083.083],\n                          [2222.233,-374.874, 2094.221],\n                          [2221.072,-378.101, 2093.040],\n                          [2210.863,-369.335, 2082.651],\n                          [2206.053,-371.041, 2077.756],#79 e2\n                          [2178.412,-385.686, 2095.532],    # h\n                          [2166.486,-413.961, 2083.395],    # h\n                          [2154.559,-442.235, 2071.259],    # h\n                          [2148.227,-508.130, 2018.912],\n                          [2149.423,-514.993, 2020.128],\n                          [2159.632,-523.758, 2030.517],\n                          [2152.686,-542.612, 2243.735],    # Back\n                          [2452.439,-057.045, 2300.172],\n                          [3550.000,-057.150, 0000.000],\n                          [3550.000, 057.150, 0000.000],\n                          [2452.118, 056.737, 2302.204],#90\n                          [2151.698, 544.667, 2242.729]]\n    notes['sampleXZY'] = np.array(notes['sampleXZY'])\n    notes['ind_h'] = [3,4,5,12,13,14,23,24,25,32,33,34,41,43,44,51,52,53,\n                      60,61,62,71,72,73,80,81,82]\n    notes['ind_Back'] = [86,87,88,89,90,91]\n    notes['ind_i'] = [16,21,42,64,69]\n    notes['ind_e1'] = [6,15,26,35,45,54,63,74]\n    notes['ind_e2'] = [11,22,31,40,50,59,70,79]\n\n\n    for kk in notes.keys():\n        if type(notes[kk]) is dict:\n            notes[kk]['In'] = notes[kk]['In']*1.e-3\n            notes[kk]['Out'] = notes[kk]['Out']*1.e-3\n        elif not 'nb' in kk and not 'ind' in kk:\n            notes[kk] = notes[kk]*1.e-3\n    return notes\n\ndef _get_intersect(D0,u0,D1,u1):\n    k = -np.cross(D0-D1,u1)/np.cross(u0,u1)\n    return D0 + k*u0\n\n\ndef make_Poly(save=_save, path=_here):\n    notes = get_notes()\n\n    Poly = np.array([np.hypot(notes['sampleXZY'][:,0],notes['sampleXZY'][:,2]),\n                     notes['sampleXZY'][:,1]])\n    # Finish V2\n    ind = np.zeros((Poly.shape[1],),dtype=bool)\n    ind[notes['ind_h']] = True\n    ind[notes['ind_i']] = True\n    nind = np.arange(0,Poly.shape[1])\n    Polybis = Poly.copy()\n    for ii in range(0,len(notes['ind_e1'])+1):\n        i0 = notes['ind_e2'][ii-1] if ii>0 else 2\n        i1 = notes['ind_e1'][ii] if ii<len(notes['ind_e1']) else 83\n        indi = ind & (nind>i0) & (nind<i1)\n        D0 = Poly[:,i0]\n        u = Poly[:,i1]-D0\n        un2 = np.linalg.norm(u)**2\n        k = -np.sum((D0[:,np.newaxis]-Poly[:,indi])*u[:,np.newaxis],axis=0)/un2\n        Polybis[:,indi] = D0[:,np.newaxis] + k[np.newaxis,:]*u[:,np.newaxis]\n\n    # Make V0 and V1\n    ind0 = np.ones((Poly.shape[1],),dtype=bool)\n    ind0[notes['ind_h']] = False\n    ind0[notes['ind_i']] = False\n    ind0[[0,1,84,85]] = False\n    Poly0 = Poly[:,ind0]\n    inde1 = np.zeros((Poly.shape[1],),dtype=bool)\n    inde2 = np.zeros((Poly.shape[1],),dtype=bool)\n    inde1[notes['ind_e1']] = True\n    inde2[notes['ind_e2']] = True\n    inde1 = inde1[ind0].nonzero()[0]\n    inde2 = inde2[ind0].nonzero()[0]\n    p0 = [Poly0[:,:inde1[0]]]\n    p1 = [Poly0[:,:inde1[0]]]\n    for ii in range(0,len(inde1)):\n        D0, D1 = Poly0[:,inde1[ii]],        Poly0[:,inde2[ii]]\n        u0, u1 = D0-Poly0[:,inde1[ii]-1],   D1-Poly0[:,inde2[ii]+1]\n        p0.append(_get_intersect(D0,u0,D1,u1)[:,np.newaxis])\n        u0, u1 = Poly0[:,inde1[ii]+1]-D0,   Poly0[:,inde2[ii]-1]-D1\n        p1.append(np.vstack([D0,_get_intersect(D0,u0,D1,u1),D1]).T)\n\n    p0.append(Poly0[:,inde2[ii]+1:])\n    p1.append(Poly0[:,inde2[ii]+1:])\n    Poly0 = np.concatenate(tuple(p0),axis=1)\n    Poly1 = np.concatenate(tuple(p1),axis=1)\n\n    if save:\n        nn = _name+'V0'\n        pfe = os.path.join(path, nn+'.txt')\n        np.savetxt(pfe, Poly0.T, comments='#',\n                   header='Exp = %s\\nName = %s\\nCls = %s'%(_Exp,nn,_Cls))\n        nn = _name+'V1'\n        pfe = os.path.join(path, nn+'.txt')\n        np.savetxt(pathfilext, Poly1.T, comments='#',\n                   header='Exp = %s\\nName = %s\\nCls = %s'%(_Exp,nn,_Cls))\n        nn = _name+'V2'\n        pfe = os.path.join(path, nn+'.txt')\n        np.savetxt(pathfilext, Poly.T, comments='#',\n                   header='Exp = %s\\nName = %s\\nCls = %s'%(_Exp,nn,_Cls))\n    return Poly0, Poly1, Poly, notes\n\n\nif __name__=='__main__':\n\n    # Parse input arguments\n    msg = 'Launch creation of polygons txt from bash'\n    parser = argparse.ArgumentParser(description = msg)\n\n    parser.add_argument('-save', type=bool, help='save ?', default=_save)\n    parser.add_argument('-path', type=str, help='saving path ?', default=_here)\n\n    args = parser.parse_args()\n\n    # Call wrapper function\n    make_Poly(save=args.save, path=args.path)\n", "meta": {"hexsha": "577650e085db90dd45ba746edde2c31366931ea1", "size": 9972, "ext": "py", "lang": "Python", "max_stars_repo_path": "tofu/geom/inputs/_DEPRECATED_WEST_PFC_BumperOuter_Notes.py", "max_stars_repo_name": "Louwrensth/tofu", "max_stars_repo_head_hexsha": "df2841d24eaf223ae07d862ffaa33fdb2fc079d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tofu/geom/inputs/_DEPRECATED_WEST_PFC_BumperOuter_Notes.py", "max_issues_repo_name": "Louwrensth/tofu", "max_issues_repo_head_hexsha": "df2841d24eaf223ae07d862ffaa33fdb2fc079d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tofu/geom/inputs/_DEPRECATED_WEST_PFC_BumperOuter_Notes.py", "max_forks_repo_name": "Louwrensth/tofu", "max_forks_repo_head_hexsha": "df2841d24eaf223ae07d862ffaa33fdb2fc079d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.9189189189, "max_line_length": 79, "alphanum_fraction": 0.4416365824, "include": true, "reason": "import numpy", "num_tokens": 3341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.15975886720502452}}
{"text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport re\nimport os\nimport numpy as np\nimport sqlite3\nimport pandas as pd\n\nfrom .plotter import colors\nfrom .plotter import _init_plot\nfrom .plotter import _close_plot\nfrom .dbmgr import get_cursor\nfrom .isotope import Isotope\n\nglobal ZG_CONNECTIONS_DICT\nZG_CONNECTIONS_DICT = {}\n\n#### TODO: allow new compound definitions as {'El':wt_pct} and accept .json stack\n\nclass Ziegler(object):\n\t\"\"\"Method for solving energy loss within stacked-target foil experiment\n\n\t...\n\n\tParameters\n\t----------\n\tx : type\n\t\tDescription of parameter `x`.\n\n\tAttributes\n\t----------\n\n\tMethods\n\t-------\n\n\tNotes\n\t-----\n\n\tReferences\n\t----------\n\n\tExamples\n\t--------\n\n\t\"\"\"\n\n\tdef __init__(self, stack, beam=None, **kwargs):\n\t\t### stack is list of dicts, which must have 'compound' specified.\n\t\t### Areal density specified by either 'ad' (mg/cm^2), both mass (g) and area (cm^2),\n\t\t### 'thickness' (mm) or both 'density' (g/cm^3) and 'thickness' (mm)\n\n\t\tzdb = get_cursor('ziegler')\n\t\t\n\t\tself.protons = {int(i[0]):list(map(float,i[1:])) for i in zdb.execute('SELECT * FROM protons')}\n\t\tself.helium = {int(i[0]):list(map(float,i[1:])) for i in zdb.execute('SELECT * FROM helium')}\n\t\tself.ionization = {int(i[0]):list(map(float,i[1:])) for i in zdb.execute('SELECT * FROM ionization')}\n\t\tself.weights = {int(i[0]):list(map(float,i[1:3])) for i in zdb.execute('SELECT * FROM weights')}\n\t\tself.compounds = {str(i[0]):[[int(h.split(':')[0]), float(h.split(':')[1])] for h in i[2].split(',')] for i in zdb.execute('SELECT * FROM compounds')}\n\t\tself.compounds = {cm:[[i[0],i[1]/sum([m[1] for m in self.compounds[cm]])] for i in self.compounds[cm]] for cm in self.compounds}\n\t\tself.densities = {str(i[0]):float(i[1]) for i in zdb.execute('SELECT * FROM compounds')}\n\t\tself.elements = sorted([[str(i[0]), int(i[2].split(':')[0])] for i in zdb.execute('SELECT * FROM compounds') if len(i[2].split(':'))==2], key=lambda h:len(h[0]), reverse=True)\n\n\t\tself._meta = {}\n\t\tself.meta = {'beam_istp':'1H', 'E0':33.0, 'dE0':0.3, 'N':10000, 'dp':1.0,\n\t\t\t\t\t\t'chunk_size':1E7, 'threads':1,\n\t\t\t\t\t\t'solved':False, 'accuracy':0.01, 'min_steps':2, 'max_steps':50}\n\t\tself._stack = []\n\t\tif beam is not None:\n\t\t\tprint('Keyword `beam` deprecated: see documentation for proper input.')\n\t\t\tself.meta = beam\n\t\tself.meta = kwargs\n\t\tif type(stack)==str:\n\t\t\tstack = pd.read_csv(stack)\n\t\t\tstack = [{i:r[i] for i in stack.columns if not (np.isnan(r[i]) if type(r[i])==float else False)} for n,r in stack.iterrows()]\n\t\tself.stack = stack\n\n\tdef check_db(self, db=None):\n\t\tif db is not None:\n\t\t\tpath, fnm = os.path.split(db)\n\t\t\tif path in ['',' ']:\n\t\t\t\tpath = os.getcwd()\n\t\t\tif fnm in ['',' ']:\n\t\t\t\traise ValueError('Invalid db Filename: {}'.format(db))\n\t\t\tdb_fnm = os.path.join(path, fnm)\n\n\t\t\tglobal ZG_CONNECTIONS_DICT\n\t\t\tif os.path.exists(db_fnm):\n\t\t\t\tif db_fnm not in ZG_CONNECTIONS_DICT:\n\t\t\t\t\tZG_CONNECTIONS_DICT[db_fnm] = sqlite3.connect(db_fnm)\n\t\t\t\tself.db_connection = ZG_CONNECTIONS_DICT[db_fnm]\n\t\t\t\tself.db = self.db_connection.cursor()\n\t\t\telse:\n\t\t\t\tprint('WARNING: DB {} does not exist, creating new file.'.format(fnm))\n\t\t\t\tfrom sqlite3 import Error\n\t\t\t\ttry:\n\t\t\t\t\tself.db_connection = sqlite3.connect(db_fnm)\n\t\t\t\t\tZG_CONNECTIONS_DICT[db_fnm] = self.db_connection\n\t\t\t\t\tself.db = self.db_connection.cursor()\n\t\t\t\texcept Error as e:\n\t\t\t\t\tprint(e)\n\n\t@property\n\tdef meta(self):\n\t\treturn self._meta\n\n\t@meta.setter\n\tdef meta(self, meta_dict):\n\t\tfor nm in meta_dict:\n\t\t\tself._meta[nm] = meta_dict[nm]\n\t\t\tif nm in ['beam_istp', 'istp']:\n\t\t\t\t_ITP = Isotope(meta_dict[nm])\n\t\t\t\tself._meta['Z'] = _ITP.Z\n\t\t\t\tself._meta['amu'] = _ITP.mass\n\t\tif self._meta['min_steps']>self._meta['max_steps']:\n\t\t\tself._meta['max_steps'] = self._meta['min_steps']+1\n\t\t\tprint('WARNING: min_steps > max_steps, setting max_steps to {}'.format(self._meta['max_steps']))\n\t\tself._meta['solved'] = False\n\n\tdef __getitem__(self, key):\n\t\tif type(key)==str:\n\t\t\tfor s in self.stack:\n\t\t\t\tif s['name']==key:\n\t\t\t\t\treturn s\n\t\t\treturn None\n\t\telse:\n\t\t\treturn self.stack[int(key)]\n\n\t@property\n\tdef stack(self):\n\t\tif not self.meta['solved']:\n\t\t\tself._solve()\n\t\treturn self._stack\n\n\t@stack.setter\n\tdef stack(self, _stack):\n\t\tself._stack = list(_stack)\n\t\tself._meta['solved'] = False\n\t\tfor s in self._stack:\n\t\t\tif 'name' not in s:\n\t\t\t\ts['name'] = None\n\t\t\tif 'compound' not in s:\n\t\t\t\traise ValueError('compound must be specified')\n\n\t\t\tif type(s['compound'])==dict:\n\t\t\t\tcs = ''\n\t\t\t\tfor c in s['compound']:\n\t\t\t\t\tcs = c\n\t\t\t\t\tself.compounds[c] = s['compound'][c]\n\t\t\t\ts['compound'] = cs\n\t\t\t\tif s['compound']=='':\n\t\t\t\t\traise ValueError('compound must be specified')\n\n\t\t\tif 'ad' not in s:\n\t\t\t\tif 'area' in s and 'mass' in s:\n\t\t\t\t\ts['ad'] = 1e3*s['mass']/s['area']\n\t\t\t\telif 'density' in s and 'thickness' in s:\n\t\t\t\t\ts['ad'] = 100.0*s['density']*s['thickness']\n\t\t\t\telif s['compound'] in self.densities and 'thickness' in s:\n\t\t\t\t\ts['ad'], s['density'] = 100.0*self.densities[s['compound']]*s['thickness'], self.densities[s['compound']]\n\n\t\t\tif 'density' not in s:\n\t\t\t\tif s['compound'] in self.densities:\n\t\t\t\t\ts['density'] = self.densities[s['compound']]\n\t\t\t\t\tif 'thickness' not in s and 'ad' in s:\n\t\t\t\t\t\ts['thickness'] = s['ad']/(100.0*s['density'])\n\n\t\t\tif 'ad' not in s:\n\t\t\t\traise ValueError('Areal density either not specified or not computable: {}'.format(s))\n\n\t\t\tif s['compound'] not in self.compounds:\n\t\t\t\tcm = s['compound']\n\t\t\t\tnums = [str(i) for i in range(10)]\n\t\t\t\tcm_list = []\n\t\t\t\tfor el,Z in self.elements:\n\t\t\t\t\tif len(cm)==0:\n\t\t\t\t\t\tbreak\n\t\t\t\t\tf = cm.split(el)\n\t\t\t\t\tif len(f)>1:\n\t\t\t\t\t\tc = f[0]\n\t\t\t\t\t\tfor e in f[1:]:\n\t\t\t\t\t\t\tif len(e):\n\t\t\t\t\t\t\t\tif e[0] in nums:\n\t\t\t\t\t\t\t\t\tcm_list.append([Z, float(e[0])])\n\t\t\t\t\t\t\t\t\tif len(e)>1:\n\t\t\t\t\t\t\t\t\t\tc += e[1:]\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tcm_list.append([Z, 1.0])\n\t\t\t\t\t\t\t\t\tc += e\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tcm_list.append([Z, 1.0])\n\t\t\t\t\t\tcm = c\n\t\t\t\tif len(cm)==0 and len(cm_list):\n\t\t\t\t\tself.compounds[s['compound']] = [[i[0], i[1]/sum([i[1] for i in cm_list])] for i in cm_list] \n\n\t\t\tif s['compound'] not in self.compounds:\n\t\t\t\traise ValueError('compound {} not known.'.format(s['compound']))\n\n\n\tdef get_S(self, E, cm):\n\t\t\"\"\"Description\n\n\t\t...\n\n\t\tParameters\n\t\t----------\n\t\tx : type\n\t\t\tDescription of parameter `x`.\n\n\t\tReturns\n\t\t-------\n\n\t\tNotes\n\t\t-----\n\n\t\tReferences\n\t\t----------\n\n\t\tExamples\n\t\t--------\n\n\t\t\"\"\"\n\n\t\t# energy E in MeV , stopping power in MeV/(mg/cm2)\n\t\tE, r0 = np.asarray(E), False\n\t\tif not E.shape:\n\t\t\tE, r0 = np.array([E]), True\n\t\tS = np.zeros(len(E))\n\t\tA_ave = sum([self.weights[z2][0]*w for z2,w in self.compounds[cm]])\n\t\tfor z2, w in self.compounds[cm]:\n\t\t\tS_nucl = self.get_S_nucl(E, self.meta['Z'], self.meta['amu'], z2, self.weights[z2][0])\n\t\t\tif self.meta['Z']==1:\n\t\t\t\tS += w*(S_nucl+self.get_S_p(E, z2, self.meta['amu']))\n\t\t\telif self.meta['Z']==2:\n\t\t\t\tS += w*(S_nucl+self.get_S_He(E, z2, self.meta['amu']))\n\t\t\telse:\n\t\t\t\tS += w*(S_nucl+self.get_S_elec(E, z2, self.meta['amu'], self.meta['Z']))\n\t\treturn S[0]*0.6022140857/A_ave if r0 else S*0.6022140857/A_ave\n\n\tdef get_S_nucl(self, E, z1, m1, z2, m2):\n\t\tRM = (m1+m2)*np.sqrt((z1**(2/3.0)+z2**(2/3.0)))\n\t\tER = 32.53*m2*1E3*E/(z1*z2*RM)\n\t\treturn (0.5*np.log(1.0+ER)/(ER+0.10718+ER**0.37544))*8.462*z1*z2*m1/RM\n\n\tdef get_S_p(self, eng, z2, M1=1.00727647):\n\t\tS = np.zeros(len(eng))\n\t\tE = 1E3*eng/M1\n\t\tA = self.protons[z2]\n\t\tbeta_sq = np.where(E>=1E3,1.0-1.0/(1.0+E/931478.0)**2,0.9)\n\t\tB0 = np.where(E>=1E3,np.log(A[6]*beta_sq/(1.0-beta_sq))-beta_sq,0.0)\n\t\tY = np.log(E[(1E3<=E)&(E<=5E4)])\n\t\tB0[np.nonzero(np.where((1E3<=E)&(E<=5E4),B0,0))] -= A[7]+A[8]*Y+A[9]*Y**2+A[10]*Y**3+A[11]*Y**4\n\t\tS[E>=1E3] = (A[5]/beta_sq[E>=1E3])*B0[E>=1E3]\n\t\tS_low = A[1]*E[(10<=E)&(E<1E3)]**0.45\n\t\tS_high = (A[2]/E[(10<=E)&(E<1E3)])*np.log(1.0+(A[3]/E[(10<=E)&(E<1E3)])+A[4]*E[(10<=E)&(E<1E3)])\n\t\tS[(10<=E)&(E<1E3)] = S_low*S_high/(S_low+S_high)\n\t\tS[(0<E)&(E<10)] = A[0]*E[(0<E)&(E<10)]**0.5\n\t\treturn S\n\n\tdef get_S_He(self,eng,z2,M1=4.003):\n\t\tS = np.zeros(len(eng))\n\t\tE = eng*4.0015/M1\n\t\tE = np.where(E>=0.001,E,0.001)\n\t\tA = self.helium[z2]\n\t\tS_low = A[0]*(1E3*E[E<=10])**A[1]\n\t\tS_high = (A[2]/E[E<=10])*np.log(1.0+(A[3]/E[E<=10])+A[4]*E[E<=10])\n\t\tS[E<=10] = S_low*S_high/(S_low+S_high)\n\t\tY = np.log(1.0/E[E>10])\n\t\tS[E>10] = np.exp(A[5]+A[6]*Y+A[7]*Y**2+A[8]*Y**3)\n\t\treturn S\n\n\tdef get_S_elec(self, eng, z2, M1, z1):\n\t\tS = np.zeros(len(eng))\n\t\tE_keV = 1E3*eng\n\t\tS[E_keV/M1<1000] = self.get_eff_Z_ratio(E_keV[E_keV/M1<1000],z1,M1)**2*self.get_S_p(eng[E_keV/M1<1000],z2,M1)\n\t\tY = E_keV[E_keV/M1>=1000]/M1\n\t\tbeta_sq = 1.0-1.0/(1.0+Y/931478.0)**2\n\t\tFX = np.log(2E6*0.511003*beta_sq/(1.0-beta_sq))-beta_sq\n\t\tZHY = 1.0-np.exp(-0.2*np.sqrt(Y)-0.0012*Y-0.00001443*Y**2)\n\t\tZ1EFF = self.get_eff_Z_ratio(E_keV[E_keV/M1>=1000],z1,M1)*ZHY\n\t\tS[E_keV/M1>=1000] = 4E-1*np.pi*(1.9732857/137.03604)**2*Z1EFF**2*z2*(FX-np.log(self.ionization[z2][0]))/(0.511003*beta_sq)\n\t\treturn S\n\n\tdef get_eff_Z_ratio(self, E_keV, z1, M1):\n\t\tif z1==1:\n\t\t\treturn np.ones(len(eng))\n\t\telif z1==2:\n\t\t\tY = np.log(E_keV/M1)\n\t\t\treturn z1*(1.0-np.exp(-0.7446-0.1429*Y-0.01562*Y**2+0.00267*Y**3-0.000001325*Y**8))\n\t\telif z1==3:\n\t\t\tY = E_keV/M1\n\t\t\treturn z1*(1.0-np.exp(-0.7138-0.002797*Y-0.000001348*Y**2))\n\t\tBB = -0.886*np.sqrt(0.04*E_keV/M1)/z1**(2/3.0)\n\t\treturn z1*(1.0-np.exp(BB-0.0378*np.sin(0.5*np.pi*BB))*(1.034-0.1777*np.exp(-0.08114*z1)))\n\n\tdef _calc_bins(self):\n\t\treturn np.arange(0.0, self.meta['E0']+10.0*self.meta['dE0'], min([0.1, self.meta['E0']/500.0]))\n\n\tdef _solve_chunk(self, N):\n\t\tE0 = self.meta['E0']+self.meta['dE0']*np.random.normal(size=int(N))\n\t\tbins = self._calc_bins()\n\t\thists = []\n\t\tdp = self.meta['dp']\n\t\tfor n, sm in enumerate(self._stack):\n\t\t\tE_bar = [E0]\n\t\t\tif np.average(E0)<=0.0:\n\t\t\t\thists.append(np.concatenate([[N],np.zeros(len(bins)-2)]))\n\t\t\telse:\n\t\t\t\tsteps = int((1.0/self.meta['accuracy'])*sm['ad']*dp*self.get_S(np.average(E0), sm['compound'])/np.average(E0))\n\t\t\t\tsteps = min([max([self.meta['min_steps'], steps]), self.meta['max_steps']])\n\t\t\t\tdr = (1.0/float(steps))\n\t\t\t\tfor i in range(steps):\n\t\t\t\t\tS1 = self.get_S(E0, sm['compound'])\n\t\t\t\t\tE1 = E0 - dr*dp*sm['ad']*S1\n\t\t\t\t\tE1 = np.where(E1>0, E1, 0.0)\n\t\t\t\t\tE0 = E0 - dr*0.5*dp*sm['ad']*(S1+self.get_S(E1, sm['compound']))\n\t\t\t\t\tE0 = np.where(E0>0, E0, 0.0)\n\t\t\t\t\tE_bar.append(E0)\n\t\t\t\thists.append(np.histogram(np.concatenate(E_bar), bins=bins)[0])\n\t\treturn hists\n\n\tdef _solve(self):\n\t\tif self.meta['solved']:\n\t\t\treturn\n\t\tself.meta['solved'] = True\n\t\tdN = np.linspace(0, self.meta['N'], int(np.ceil(self.meta['N']/float(self.meta['chunk_size'])))+1, dtype=int)\n\t\thistos = list(map(self._solve_chunk, dN[1:]-dN[:-1]))\n\n\t\tbins = self._calc_bins()\n\t\tenergy = 0.5*(bins[1:]+bins[:-1])\n\t\tfor n,sm in enumerate(self._stack):\n\t\t\tsm['flux'] = np.sum([h[n] for h in histos], axis=0)\n\t\t\tsm['flux'] = sm['flux']/np.sum(sm['flux'])\n\t\t\tsm['mu_E'] = np.sum(sm['flux']*energy)\n\t\t\tsm['sig_E'] = np.sqrt(np.sum(sm['flux']*(energy-sm['mu_E'])**2))\n\t\t\tlh = np.where(sm['flux']>0)[0]\n\t\t\tif lh.size:\n\t\t\t\tif lh[0]==0:\n\t\t\t\t\tnm = sm['name'] if sm['name'] is not None else sm['compound']+str(n+1)\n\t\t\t\t\tprint('WARNING: Beam stopped in foil {}'.format(nm))\n\t\t\tsm['flux'] = sm['flux'][lh[0]:lh[-1]]\n\t\t\tsm['energy'] = energy[lh[0]:lh[-1]]\n\t\t\tsm['bins'] = bins[lh[0]:lh[-1]+1]\n\n\tdef saveas(self, *fnms):\n\t\t\"\"\"Description\n\n\t\t...\n\n\t\tParameters\n\t\t----------\n\t\tx : type\n\t\t\tDescription of parameter `x`.\n\n\t\tReturns\n\t\t-------\n\n\t\tNotes\n\t\t-----\n\n\t\tReferences\n\t\t----------\n\n\t\tExamples\n\t\t--------\n\n\t\t\"\"\"\n\n\t\tcols = ['name','compound','thickness','density','ad','mu_E','sig_E']\n\t\tstack = pd.DataFrame([{c:(sm[c] if c in sm else None) for c in cols} for sm in self.stack], columns=cols)\n\t\tcols = ['name','energy','flux']\n\t\tfluxes = pd.concat([pd.DataFrame({c:sm[c] for c in cols}, columns=cols) for sm in self.stack if sm['name'] is not None], ignore_index=True)\n\t\tfor fl in fnms:\n\t\t\tif any([fl.endswith(e) for e in ['.png','.pdf','.eps','.pgf','.ps','.raw','.rgba','.svg','.svgz']]):\n\t\t\t\tself.plot(saveas=fl, show=False)\n\t\t\tif fl.endswith('.csv'):\n\t\t\t\tstack.to_csv(fl.replace('.csv','_stack.csv'), index=False)\n\t\t\t\tfluxes.to_csv(fl.replace('.csv','_fluxes.csv'), index=False)\n\t\t\tif fl.endswith('.db'):\n\t\t\t\tself.check_db(fl)\n\t\t\t\tstack.to_sql('stack', self.db_connection, if_exists='replace', index=False)\n\t\t\t\tfluxes.to_sql('fluxes', self.db_connection, if_exists='replace', index=False)\n\n\tdef summarize(self, samples=None):\n\t\t\"\"\"Description\n\n\t\t...\n\n\t\tParameters\n\t\t----------\n\t\tx : type\n\t\t\tDescription of parameter `x`.\n\n\t\tReturns\n\t\t-------\n\n\t\tNotes\n\t\t-----\n\n\t\tReferences\n\t\t----------\n\n\t\tExamples\n\t\t--------\n\n\t\t\"\"\"\n\n\t\tfor n,sm in enumerate(self.stack):\n\t\t\tif sm['name'] is not None:\n\t\t\t\tif samples is not None:\n\t\t\t\t\tif not any([re.match(s, sm['name']) for s in samples]):\n\t\t\t\t\t\tcontinue\n\t\t\t\tnm = sm['name'] if sm['name'] is not None else sm['compound']+str(n+1)\n\t\t\t\tprint(nm+': '+str(round(sm['mu_E'], 2))+' +/- '+str(round(sm['sig_E'], 2))+' (MeV)')\n\n\tdef plot_S(self, compound, energy=None, **kwargs):\n\t\t\"\"\"Description\n\n\t\t...\n\n\t\tParameters\n\t\t----------\n\t\tx : type\n\t\t\tDescription of parameter `x`.\n\n\t\tReturns\n\t\t-------\n\n\t\tNotes\n\t\t-----\n\n\t\tReferences\n\t\t----------\n\n\t\tExamples\n\t\t--------\n\n\t\t\"\"\"\n\n\t\tif energy is None:\n\t\t\tenergy = 10.0**np.arange(0.1,2.8,0.1)\n\t\tf,ax = _init_plot(**kwargs)\n\t\tax.plot(energy, self.get_S(energy, compound), label=compound.title())\n\t\tax.set_xlabel('Energy (MeV)')\n\t\tax.set_ylabel(r'Stopping Power (MeV$\\cdot$mg$^{-1}\\cdot$cm$^{-2}$)')\n\t\tax.set_xscale('log')\n\t\tax.legend(loc=0)\n\t\treturn _close_plot(f, ax, **kwargs)\n\n\tdef plot(self, samples=None,  **kwargs):\n\t\t\"\"\"Description\n\n\t\t...\n\n\t\tParameters\n\t\t----------\n\t\tx : type\n\t\t\tDescription of parameter `x`.\n\n\t\tReturns\n\t\t-------\n\n\t\tNotes\n\t\t-----\n\n\t\tReferences\n\t\t----------\n\n\t\tExamples\n\t\t--------\n\n\t\t\"\"\"\n\n\t\tif type(samples)==str:\n\t\t\tsamples = [samples]\n\t\tf,ax = _init_plot(**kwargs)\n\t\tfor sm in self.stack:\n\t\t\tif sm['name'] is not None:\n\t\t\t\tif samples is not None:\n\t\t\t\t\tif not any([re.match(s, sm['name']) for s in samples]):\n\t\t\t\t\t\tcontinue\n\t\t\t\tx, y = np.array([sm['bins'][:-1],sm['bins'][1:]]).T.flatten(), np.array([sm['flux'],sm['flux']]).T.flatten()\n\t\t\n\t\t\t\tax.plot(x,y,label=sm['name'])\n\n\t\tax.set_xlabel('Energy (MeV)')\n\t\tax.set_ylabel('Flux (a.u.)')\n\t\tax.legend(loc=0)\n\t\treturn _close_plot(f, ax, **kwargs)\n", "meta": {"hexsha": "9c56c3c60bd2cf02fdbc5f23e2211167bf3bb76c", "size": 14146, "ext": "py", "lang": "Python", "max_stars_repo_path": "npat/irradiation.py", "max_stars_repo_name": "CallumCordwell/npat", "max_stars_repo_head_hexsha": "9990ed982948389af78cc456fd579b98732b6490", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-27T15:00:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-27T15:00:30.000Z", "max_issues_repo_path": "npat/irradiation.py", "max_issues_repo_name": "CallumCordwell/npat", "max_issues_repo_head_hexsha": "9990ed982948389af78cc456fd579b98732b6490", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "npat/irradiation.py", "max_forks_repo_name": "CallumCordwell/npat", "max_forks_repo_head_hexsha": "9990ed982948389af78cc456fd579b98732b6490", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-06-27T17:29:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-15T10:42:23.000Z", "avg_line_length": 28.8105906314, "max_line_length": 177, "alphanum_fraction": 0.5956454121, "include": true, "reason": "import numpy", "num_tokens": 4995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.2942149721629888, "lm_q1q2_score": 0.15971850574690732}}
{"text": "from __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom builtins import str\nfrom past.utils import old_div\nimport anuga\nimport numpy as num\nimport math\nfrom . import parallel_inlet_enquiry \nfrom anuga.utilities import parallel_abstraction as pypar\n\nfrom anuga.utilities.system_tools import log_to_file\nfrom anuga.utilities.numerical_tools import ensure_numeric\nfrom anuga.structures.inlet_enquiry import Inlet_enquiry\n\n\nclass Parallel_Structure_operator(anuga.Operator):\n    \"\"\"Parallel Structure Operator - transfer water from one rectangular box to another.\n    Sets up the geometry of problem\n    \n    This is the base class for structures (culverts, pipes, bridges etc) that exist across multiple\n    parallel shallow water domains. Inherit from this class (and overwrite discharge_routine method \n    for specific subclasses)\n    \n    Input: Two points, pipe_size (either diameter or width, depth),\n    mannings_rougness,\n    \"\"\" \n\n    counter = 0\n\n    \"\"\"\n     ===========================================================================================\n     PETE: Inputs to this constructor are identical to the serial\n     structure operator, except for the following arguments:\n     master_proc - the processor that coordinates all processors (with domains) associated with this structure [INT]\n     procs - the list of processors associated with thisstructure (List[INT])\n     inlet_master_proc - master_proc of the first and second inlet (List[2])\n     inlet_procs - list of processors associated with the first and second inlet (LIST[2][INT])\n     enquiry_proc - processor associated the first and second enquiry point (List[2])\n    \"\"\"\n\n    def __init__(self,\n                 domain,\n                 end_points,\n                 exchange_lines,\n                 enquiry_points,\n                 invert_elevations,\n                 width,\n                 height,\n                 diameter,\n                 z1,\n                 z2,\n                 blockage,\n                 barrels,\n                 apron,\n                 manning,\n                 enquiry_gap,\n                 use_momentum_jet,\n                 zero_outflow_momentum,\n                 use_old_momentum_method,\n                 always_use_Q_wetdry_adjustment,\n                 force_constant_inlet_elevations,\n                 description,\n                 label,\n                 structure_type,\n                 logging,\n                 verbose,\n                 master_proc = 0,\n                 procs = None,\n                 inlet_master_proc = [0,0],\n                 inlet_procs = None,\n                 enquiry_proc = None):\n\n\n        self.myid = pypar.rank()\n        self.num_procs = pypar.size()\n        \n        anuga.Operator.__init__(self,domain)\n\n        # Allocate default processor associations if not specified in arguments\n        # although we assume that such associations are provided correctly by the \n        # parallel_operator_factory.\n\n        self.master_proc = master_proc\n        self.inlet_master_proc = inlet_master_proc\n        \n        if procs is None:\n            self.procs = [master_proc]\n        else:\n            self.procs = procs\n\n        if inlet_procs is None:\n            self.inlet_procs = [[inlet_master_proc[0]],[inlet_master_proc[0]]]\n        else:\n            self.inlet_procs = inlet_procs\n\n        if enquiry_proc is None:\n            self.enquiry_proc = [[inlet_master_proc[0]],[inlet_master_proc[0]]]\n        else:\n            self.enquiry_proc = enquiry_proc\n\n        self.end_points = ensure_numeric(end_points)\n        self.exchange_lines = ensure_numeric(exchange_lines)\n        self.enquiry_points = ensure_numeric(enquiry_points)\n        self.invert_elevations = ensure_numeric(invert_elevations)\n\n        assert (width is not None and diameter is None) or (width is None and diameter is not None)\n\n        if width is None:\n            width = diameter\n\n        if diameter is None:\n            diameter = width\n\n        if height is None:\n            height = width\n\n        if apron is None:\n            apron = width\n\n        self.width  = width\n        self.height = height\n        self.diameter = diameter\n        self.z1 = z1\n        self.z2 = z2\n        self.blockage = blockage\n        self.barrels = barrels\n        self.apron  = apron\n        self.manning = manning\n        self.enquiry_gap = enquiry_gap\n        self.use_momentum_jet = use_momentum_jet\n        self.zero_outflow_momentum = zero_outflow_momentum\n        if use_momentum_jet and zero_outflow_momentum:\n            msg = \"Can't have use_momentum_jet and zero_outflow_momentum both True\"\n            raise Exception(msg)\n        self.use_old_momentum_method = use_old_momentum_method\n        self.always_use_Q_wetdry_adjustment = always_use_Q_wetdry_adjustment\n\n        if description is None:\n            self.description = ' '\n        else:\n            self.description = description\n        \n        if label is None:\n            self.label = \"structure_%g\" % Parallel_Structure_operator.counter + \"_P\" + str(self.myid)\n        else:\n            self.label = label + '_%g' % Parallel_Structure_operator.counter + \"_P\" + str(self.myid)\n\n        if structure_type is None:\n            self.structure_type = 'generic structure'\n        else:\n            self.structure_type = structure_type\n            \n        self.verbose = verbose        \n        \n        # Keep count of structures\n        if self.myid == master_proc:\n            Parallel_Structure_operator.counter += 1\n\n        # Slots for recording current statistics\n        self.accumulated_flow = 0.0\n        self.discharge = 0.0\n        self.discharge_abs_timemean = 0.0\n        self.velocity = 0.0\n        self.outlet_depth = 0.0\n        self.delta_total_energy = 0.0\n        self.driving_energy = 0.0\n        \n        if exchange_lines is not None:\n            self.__process_skew_culvert()\n        elif end_points is not None:\n            self.__process_non_skew_culvert()\n        else:\n            raise Exception('Define either exchange_lines or end_points')\n        \n        self.inlets = []\n\n        # Allocate parallel inlet enquiry, assign None if processor is not associated with particular\n        # inlet.\n\n        if self.myid in self.inlet_procs[0]:\n            line0 = self.exchange_lines[0]\n            if self.apron is None:\n                poly0 = line0\n            else:\n                offset = -self.apron*self.outward_vector_0 \n                poly0 = num.array([ line0[0], line0[1], line0[1]+offset, line0[0]+offset])\n\n            if self.invert_elevations is None:\n                invert_elevation0 = None\n            else:\n                invert_elevation0 = self.invert_elevations[0]\n\n            enquiry_point0 = self.enquiry_points[0]\n            outward_vector0 = self.culvert_vector\n\n            self.inlets.append(parallel_inlet_enquiry.Parallel_Inlet_enquiry(\n                               self.domain,\n                               line0,\n                               enquiry_point0,\n                               invert_elevation = invert_elevation0,\n                               outward_culvert_vector = outward_vector0, \n                               master_proc = self.inlet_master_proc[0],\n                               procs = self.inlet_procs[0],\n                               enquiry_proc = self.enquiry_proc[0],\n                               verbose = self.verbose))\n\n            if force_constant_inlet_elevations: \n                # Try to enforce a constant inlet elevation \n                inlet_global_elevation = self.inlets[-1].get_global_average_elevation() \n                self.inlets[-1].set_elevations(inlet_global_elevation)\n       \n        else:\n            self.inlets.append(None)\n\n        if self.myid in self.inlet_procs[1]:\n            line1 = self.exchange_lines[1]\n            if self.apron is None:\n                poly1 = line1\n            else:\n                offset = -self.apron*self.outward_vector_1\n                poly1 = num.array([ line1[0], line1[1], line1[1]+offset, line1[0]+offset])\n\n            if self.invert_elevations is None:\n                invert_elevation1 = None\n            else:\n                invert_elevation1 = self.invert_elevations[1]\n\n\n            enquiry_point1 = self.enquiry_points[1]\n            outward_vector1  = - self.culvert_vector\n\n\n            self.inlets.append(parallel_inlet_enquiry.Parallel_Inlet_enquiry(\n                               self.domain,\n                               line1,\n                               enquiry_point1,\n                               invert_elevation = invert_elevation1,\n                               outward_culvert_vector = outward_vector1,\n                               master_proc = self.inlet_master_proc[1],\n                               procs = self.inlet_procs[1],\n                               enquiry_proc = self.enquiry_proc[1],\n                               verbose = self.verbose))\n\n            if force_constant_inlet_elevations: \n                # Try to enforce a constant inlet elevation \n                inlet_global_elevation = self.inlets[-1].get_global_average_elevation() \n                self.inlets[-1].set_elevations(inlet_global_elevation)\n            \n\n        else:\n            self.inlets.append(None)\n\n        self.inflow_index = 0\n        self.outflow_index = 1\n\n        self.set_parallel_logging(logging)\n\n    def __call__(self):\n\n        timestep = self.domain.get_timestep()\n\n        Q, barrel_speed, outlet_depth = self.discharge_routine()\n\n        # Get attributes of Inflow inlet, all procs associated with inlet must call\n        if self.myid in self.inlet_procs[self.inflow_index]:\n            old_inflow_depth = self.inlets[self.inflow_index].get_global_average_depth()\n            old_inflow_stage = self.inlets[self.inflow_index].get_global_average_stage()\n            old_inflow_xmom = self.inlets[self.inflow_index].get_global_average_xmom()\n            old_inflow_ymom = self.inlets[self.inflow_index].get_global_average_ymom()\n            inflow_area = self.inlets[self.inflow_index].get_global_area()\n\n        # Master proc of inflow inlet sends attributes to master proc of structure\n        if self.myid == self.master_proc:\n            if self.myid != self.inlet_master_proc[self.inflow_index]:\n                old_inflow_depth = pypar.receive(self.inlet_master_proc[self.inflow_index])\n                old_inflow_stage = pypar.receive(self.inlet_master_proc[self.inflow_index])\n                old_inflow_xmom = pypar.receive(self.inlet_master_proc[self.inflow_index])\n                old_inflow_ymom = pypar.receive(self.inlet_master_proc[self.inflow_index])\n                inflow_area = pypar.receive(self.inlet_master_proc[self.inflow_index])\n        elif self.myid == self.inlet_master_proc[self.inflow_index]:\n            pypar.send(old_inflow_depth, self.master_proc)\n            pypar.send(old_inflow_stage, self.master_proc)\n            pypar.send(old_inflow_xmom, self.master_proc)\n            pypar.send(old_inflow_ymom, self.master_proc)\n            pypar.send(inflow_area, self.master_proc)\n\n        # Implement the update of flow over a timestep by\n        # using a semi-implict update. This ensures that\n        # the update does not create a negative depth\n        \n        # Master proc of structure only\n        if self.myid == self.master_proc:\n            if old_inflow_depth > 0.0 :\n                dt_Q_on_d = old_div(timestep*Q,old_inflow_depth)\n            else:\n                dt_Q_on_d = 0.0\n\n            # Check whether we should use the wet-dry Q adjustment (where Q is\n            # multiplied by new_inflow_depth/old_inflow_depth)\n            always_use_Q_wetdry_adjustment = self.always_use_Q_wetdry_adjustment\n            # Always use it if we are near wet-dry\n            use_Q_wetdry_adjustment = ((always_use_Q_wetdry_adjustment) |\\\n                (old_inflow_depth*inflow_area <= Q*timestep))\n\n            factor = 1.0/(1.0 + old_div(dt_Q_on_d,inflow_area))\n        \n            if use_Q_wetdry_adjustment:\n                new_inflow_depth = old_inflow_depth*factor\n                if old_inflow_depth > 0.:\n                    timestep_star = old_div(timestep*new_inflow_depth,old_inflow_depth)\n                else:\n                    timestep_star = 0.\n            else:\n                new_inflow_depth = old_inflow_depth - old_div(timestep*Q,inflow_area)\n                timestep_star = timestep\n\n            #new_inflow_xmom = old_inflow_xmom*factor\n            #new_inflow_ymom = old_inflow_ymom*factor\n            if(self.use_old_momentum_method):\n                # This method is here for consistency with the old version of the\n                # routine\n                new_inflow_xmom = old_inflow_xmom*factor\n                new_inflow_ymom = old_inflow_ymom*factor\n\n            else:\n                # For the momentum balance, note that Q also transports the velocity,\n                # which has an average value of new_inflow_mom/depth (or old_inflow_mom/depth). \n                #\n                #     new_inflow_xmom*inflow_area = \n                #     old_inflow_xmom*inflow_area - \n                #     timestep*Q*(new_inflow_xmom/old_inflow_depth)\n                # and:\n                #     new_inflow_ymom*inflow_area = \n                #     old_inflow_ymom*inflow_area - \n                #     timestep*Q*(new_inflow_ymom/old_inflow_depth)\n                #\n                # The choice of new_inflow_mom in the final term might be\n                # replaced with old_inflow_mom.\n                #\n                # The units balance: (m^2/s)*(m^2) = (m^2/s)*(m^2) - s*(m^3/s)*(m^2/s)*(m^(-1))\n                #\n                if old_inflow_depth > 0.:\n                    if use_Q_wetdry_adjustment:\n                        factor2 = 1.0/(1.0 + old_div(dt_Q_on_d*new_inflow_depth,(old_inflow_depth*inflow_area)))\n                    else:\n                        factor2 = 1.0/(1.0 + old_div(timestep*Q,(old_inflow_depth*inflow_area)))\n                else:\n                    factor2 = 0.\n\n                new_inflow_xmom = old_inflow_xmom*factor2\n                new_inflow_ymom = old_inflow_ymom*factor2\n\n        # Master proc of structure sends new inflow attributes to all inflow inlet processors\n\n        if self.myid == self.master_proc:\n            for i in self.inlet_procs[self.inflow_index]:\n                if i == self.master_proc: continue\n                pypar.send(new_inflow_depth, i)\n                pypar.send(new_inflow_xmom, i)\n                pypar.send(new_inflow_ymom, i)\n        elif self.myid in self.inlet_procs[self.inflow_index]:\n            new_inflow_depth = pypar.receive(self.master_proc)\n            new_inflow_xmom = pypar.receive(self.master_proc)\n            new_inflow_ymom = pypar.receive(self.master_proc)\n\n        # Inflow inlet procs sets new attributes\n        if self.myid in self.inlet_procs[self.inflow_index]:\n            self.inlets[self.inflow_index].set_depths(new_inflow_depth)\n            self.inlets[self.inflow_index].set_xmoms(new_inflow_xmom)\n            self.inlets[self.inflow_index].set_ymoms(new_inflow_ymom)\n\n        # Get outflow inlet attributes, all processors associated with outflow inlet must call\n        if self.myid in self.inlet_procs[self.outflow_index]:\n            outflow_area = self.inlets[self.outflow_index].get_global_area()\n            outflow_average_depth = self.inlets[self.outflow_index].get_global_average_depth()\n            outflow_outward_culvert_vector = self.inlets[self.outflow_index].outward_culvert_vector\n            outflow_average_xmom = self.inlets[self.outflow_index].get_global_average_xmom()\n            outflow_average_ymom = self.inlets[self.outflow_index].get_global_average_ymom()\n\n        # Master proc of outflow inlet sends attribute to master proc of structure\n        if self.myid == self.master_proc:\n            if self.myid != self.inlet_master_proc[self.outflow_index]:\n                outflow_area = pypar.receive(self.inlet_master_proc[self.outflow_index])\n                outflow_average_depth = pypar.receive(self.inlet_master_proc[self.outflow_index])\n                outflow_outward_culvert_vector = pypar.receive(self.inlet_master_proc[self.outflow_index])\n                outflow_average_xmom = pypar.receive(self.inlet_master_proc[self.outflow_index])\n                outflow_average_ymom = pypar.receive(self.inlet_master_proc[self.outflow_index])\n        elif self.myid == self.inlet_master_proc[self.outflow_index]:\n            pypar.send(outflow_area, self.master_proc)\n            pypar.send(outflow_average_depth, self.master_proc)\n            pypar.send(outflow_outward_culvert_vector, self.master_proc)\n            pypar.send(outflow_average_xmom, self.master_proc)\n            pypar.send(outflow_average_ymom, self.master_proc)\n\n        # Master proc of structure computes new outflow attributes\n        if self.myid == self.master_proc:\n            loss = (old_inflow_depth - new_inflow_depth)*inflow_area\n            xmom_loss = (old_inflow_xmom - new_inflow_xmom)*inflow_area\n            ymom_loss = (old_inflow_ymom - new_inflow_ymom)*inflow_area\n\n            # set outflow\n            outflow_extra_depth = old_div(Q*timestep_star,outflow_area)\n            outflow_direction = - outflow_outward_culvert_vector\n            #outflow_extra_momentum = outflow_extra_depth*barrel_speed*outflow_direction\n            \n            gain = outflow_extra_depth*outflow_area\n\n            # Update Stats\n            self.discharge  = old_div(Q*timestep_star,timestep) #outflow_extra_depth*self.outflow.get_area()/timestep\n            self.discharge_abs_timemean += old_div(Q*timestep_star,self.domain.yieldstep)\n            self.velocity = barrel_speed #self.discharge/outlet_depth/self.width\n\n            new_outflow_depth = outflow_average_depth + outflow_extra_depth\n\n            self.outlet_depth = new_outflow_depth\n            #if self.use_momentum_jet :\n            #    # FIXME (SR) Review momentum to account for possible hydraulic jumps at outlet\n            #    #new_outflow_xmom = outflow.get_average_xmom() + outflow_extra_momentum[0]\n            #    #new_outflow_ymom = outflow.get_average_ymom() + outflow_extra_momentum[1]\n\n            #    new_outflow_xmom = barrel_speed*new_outflow_depth*outflow_direction[0]\n            #    new_outflow_ymom = barrel_speed*new_outflow_depth*outflow_direction[1]\n\n            #else:\n            #    #new_outflow_xmom = outflow.get_average_xmom()\n            #    #new_outflow_ymom = outflow.get_average_ymom()\n\n            #    new_outflow_xmom = 0.0\n            #    new_outflow_ymom = 0.0\n            if self.use_momentum_jet:\n                # FIXME (SR) Review momentum to account for possible hydraulic jumps at outlet\n                # FIXME (GD) Depending on barrel speed I think this will be either\n                # a source or sink of momentum (considering the momentum losses\n                # above). Might not always be reasonable.\n                #new_outflow_xmom = self.outflow.get_average_xmom() + outflow_extra_momentum[0]\n                #new_outflow_ymom = self.outflow.get_average_ymom() + outflow_extra_momentum[1]\n                new_outflow_xmom = barrel_speed*new_outflow_depth*outflow_direction[0]\n                new_outflow_ymom = barrel_speed*new_outflow_depth*outflow_direction[1]\n                \n            elif self.zero_outflow_momentum:\n                new_outflow_xmom = 0.0\n                new_outflow_ymom = 0.0\n                #new_outflow_xmom = outflow.get_average_xmom()\n                #new_outflow_ymom = outflow.get_average_ymom()\n\n            else:\n                # Add the momentum lost from the inflow to the outflow. For\n                # structures where barrel_speed is unknown + direction doesn't\n                # change from inflow to outflow\n                new_outflow_xmom = outflow_average_xmom + old_div(xmom_loss,outflow_area)\n                new_outflow_ymom = outflow_average_ymom + old_div(ymom_loss,outflow_area)\n\n            # master proc of structure sends outflow attributes to all outflow procs\n            for i in self.inlet_procs[self.outflow_index]:\n                if i == self.myid: continue\n                pypar.send(new_outflow_depth, i)\n                pypar.send(new_outflow_xmom, i)\n                pypar.send(new_outflow_ymom, i)\n        # outflow inlet procs receives new outflow attributes\n        elif self.myid in self.inlet_procs[self.outflow_index]:\n            new_outflow_depth = pypar.receive(self.master_proc)\n            new_outflow_xmom = pypar.receive(self.master_proc)\n            new_outflow_ymom = pypar.receive(self.master_proc)\n\n        # outflow inlet procs sets new outflow attributes\n        if self.myid in self.inlet_procs[self.outflow_index]:\n            self.inlets[self.outflow_index].set_depths(new_outflow_depth)\n            self.inlets[self.outflow_index].set_xmoms(new_outflow_xmom)\n            self.inlets[self.outflow_index].set_ymoms(new_outflow_ymom)\n\n    def __process_non_skew_culvert(self):\n        \"\"\"Create lines at the end of a culvert inlet and outlet.\n        At either end two lines will be created; one for the actual flow to pass through and one a little further away\n        for enquiring the total energy at both ends of the culvert and transferring flow.\n        \"\"\"\n        \n        self.culvert_vector = self.end_points[1] - self.end_points[0]\n        self.culvert_length = math.sqrt(num.sum(self.culvert_vector**2))   \n        assert self.culvert_length > 0.0, 'The length of culvert is less than 0'\n        \n        self.culvert_vector /= self.culvert_length\n        self.outward_vector_0 =   self.culvert_vector\n        self.outward_vector_1 = - self.culvert_vector        \n        \n        culvert_normal = num.array([-self.culvert_vector[1], self.culvert_vector[0]])  # Normal vector\n        w = 0.5*self.width*culvert_normal # Perpendicular vector of 1/2 width\n\n        self.exchange_lines = []\n\n        # Build exchange polyline and enquiry point\n        if self.enquiry_points is None:\n            \n            gap = (self.apron + self.enquiry_gap)*self.culvert_vector\n            self.enquiry_points = []\n            \n            for i in [0, 1]:\n                p0 = self.end_points[i] + w\n                p1 = self.end_points[i] - w\n                self.exchange_lines.append(num.array([p0, p1]))\n                ep = self.end_points[i] + (2*i - 1)*gap #(2*i - 1) determines the sign of the points\n                self.enquiry_points.append(ep)\n            \n        else:            \n            for i in [0, 1]:\n                p0 = self.end_points[i] + w\n                p1 = self.end_points[i] - w\n                self.exchange_lines.append(num.array([p0, p1]))\n            \n  \n    def __process_skew_culvert(self):    \n        \n        \"\"\"Compute skew culvert.\n        If exchange lines are given, the enquiry points are determined. This is for enquiring \n        the total energy at both ends of the culvert and transferring flow.\n        \"\"\"\n            \n        centre_point0 = 0.5*(self.exchange_lines[0][0] + self.exchange_lines[0][1])\n        centre_point1 = 0.5*(self.exchange_lines[1][0] + self.exchange_lines[1][1])\n\n        n_exchange_0 = len(self.exchange_lines[0])\n        n_exchange_1 = len(self.exchange_lines[1])\n\n        assert n_exchange_0 == n_exchange_1, 'There should be the same number of points in both exchange_lines'\n\n        if n_exchange_0 == 2:\n            \n            if self.end_points is None:\n                self.culvert_vector = centre_point1 - centre_point0\n            else:\n                self.culvert_vector = self.end_points[1] - self.end_points[0]\n\n            self.outward_vector_0 =   self.culvert_vector\n            self.outward_vector_1 = - self.culvert_vector\n\n        elif n_exchange_0 == 4:\n\n            self.outward_vector_0 = self.exchange_lines[0][3] - self.exchange_lines[0][2]\n            self.outward_vector_1 = self.exchange_lines[1][3] - self.exchange_lines[1][2]\n\n            self.culvert_vector = centre_point1 - centre_point0\n\n        else:\n            raise Exception('n_exchange_0 != 2 or 4')\n\n        self.culvert_length = math.sqrt(num.sum(self.culvert_vector**2))\n        assert self.culvert_length > 0.0, 'The length of culvert is less than 0'\n        self.culvert_vector /= self.culvert_length\n\n        outward_vector_0_length = math.sqrt(num.sum(self.outward_vector_0**2))\n        assert outward_vector_0_length > 0.0, 'The length of outlet_vector_0 is less than 0'\n        self.outward_vector_0 /= outward_vector_0_length\n\n        outward_vector_1_length = math.sqrt(num.sum(self.outward_vector_1**2))\n        assert outward_vector_1_length > 0.0, 'The length of outlet_vector_1 is less than 0'\n        self.outward_vector_1 /= outward_vector_1_length\n\n        \n        if self.enquiry_points is None:\n        \n\n            gap = (self.apron + self.enquiry_gap)*self.culvert_vector\n        \n            self.enquiry_points = []\n\n            self.enquiry_points.append(centre_point0 - gap)\n            self.enquiry_points.append(centre_point1 + gap)\n            \n\n    def discharge_routine(self):\n\n        msg = 'Need to impelement '\n        raise\n            \n\n    def statistics(self):\n        # Warning: requires synchronization, must be called by all procs associated\n        # with this structure\n\n        message = ' '\n\n        if self.myid == self.master_proc:\n\n            message  = '===============================================\\n'\n            message += 'Parallel Structure Operator: %s\\n' % self.label\n            message += '===============================================\\n'\n\n            message += 'Structure Type: %s\\n' % self.structure_type\n\n            message += 'Description\\n'\n            message += '%s' % self.description\n            message += '\\n'\n\n            #add the culvert dimensions, blockage factor here\n            if self.structure_type == 'boyd_pipe':\n                message += 'Culvert Diameter: %s\\n'% self.diameter\n                message += 'Culvert Blockage: %s\\n'% self.blockage\n                message += 'No.  of  barrels: %s\\n'% self.barrels\n            elif self.structure_type == 'boyd_box':\n                message += 'Culvert   Height: %s\\n'% self.height\n                message += 'Culvert    Width: %s\\n'% self.width\n                message += 'Culvert Blockage: %s\\n'% self.blockage\n                message += 'No.  of  barrels: %s\\n'% self.barrels\n            else:\n                message += 'Culvert Height  : %s\\n'% self.height\n                message += 'Culvert  Width  : %s\\n'% self.width\n                message += 'Batter Slope 1  : %s\\n'% self.z1\n                message += 'Batter Slope 2  : %s\\n'% self.z2\n                message += 'Culvert Blockage: %s\\n'% self.blockage\n                message += 'No.  of  barrels: %s\\n'% self.barrels\n                \n        #print \"Structure Myids \",self.myid, self.label\n        \n        for i, inlet in enumerate(self.inlets):\n            if self.myid == self.master_proc:\n                message += '-------------------------------------\\n'\n                message +=  'Inlet %i\\n' %(i)\n                message += '-------------------------------------\\n'\n\n            #print \"*****\",inlet, i,self.myid\n            if inlet is not None:\n                \n                \n                stats = inlet.statistics()\n\n            if self.myid == self.master_proc:\n                if self.myid != self.inlet_master_proc[i]:\n                    stats = pypar.receive(self.inlet_master_proc[i])                    \n            elif self.myid == self.inlet_master_proc[i]:\n                pypar.send(stats, self.master_proc)\n\n            if self.myid == self.master_proc: message += stats\n \n\n        if self.myid == self.master_proc: message += '=====================================\\n'\n\n        return message\n\n\n    def print_statistics(self):\n        # Warning: requires synchronization, must be called by all procs associated\n        # with this structure\n\n        print(self.statistics())\n\n\n    def print_timestepping_statistics(self):\n        # Warning: must be called by the master proc of this structure to obtain \n        # meaningful output\n\n        message = ' '\n\n        if self.myid == self.master_proc:\n            message = '--------------------------------------------------\\n'\n            message += 'Parallel Structure report for %s:\\n' % self.label\n            message += '-------------------------------------------------\\n'\n            message += 'Type: %s\\n' % self.structure_type\n            message += 'Discharge [m^3/s]: %.2f\\n' % self.discharge\n            message += 'Discharge function value [m^3/s]: %.2f\\n' % self.discharge_abs_timemean\n            message += 'Velocity  [m/s]: %.2f\\n' % self.velocity\n            message += 'Inlet Driving Energy %.2f\\n' % self.driving_energy\n            message += 'Delta Total Energy %.2f\\n' % self.delta_total_energy\n            message += 'Control at this instant: %s\\n' % self.case\n\n        print(message)\n\n\n    def set_parallel_logging(self, flag=True):\n        # Warning: requires synchronization, must be called by all procs associated\n        # with this structure\n\n        stats = self.statistics()\n        self.logging = flag\n\n        # If flag is true open file with mode = \"w\" to form a clean file for logging\n        if self.logging and self.myid == self.master_proc:\n            self.log_filename = self.domain.get_datadir() + '/' + self.label + '.log'\n            log_to_file(self.log_filename, stats, mode='w')\n            log_to_file(self.log_filename, 'time,discharge_instantaneous,discharge_abs_timemean,velocity_instantaneous,driving_energy_instantaneous,delta_total_energy_instantaneous')\n\n            #log_to_file(self.log_filename, self.culvert_type)\n\n    def set_logging(self, flag=True):\n        # Overwrite the sequential procedure with a dummy procedure.\n        # Need to call set_parallel_logging which needs to be done later\n        # after the calculation of master processors\n\n        pass\n\n\n    def log_timestepping_statistics(self):\n\n        from anuga.utilities.system_tools import log_to_file\n        if self.logging and self.myid == self.master_proc:\n            log_to_file(self.log_filename, self.timestepping_statistics())\n\n\n\n    def timestepping_statistics(self):\n\n        message  = '%.5f, ' % self.domain.get_time()\n        message += '%.5f, ' % self.discharge\n        message += '%.5f, ' % self.discharge_abs_timemean\n        message += '%.5f, ' % self.velocity\n        message += '%.5f, ' % self.driving_energy\n        message += '%.5f' % self.delta_total_energy\n\n        # Reset discharge_abs_timemean each time there is reporting (FIXME:\n        # This assumes this function is only called after each yieldstep)\n        self.discharge_abs_timemean = 0.\n\n        return message\n\n\n    def get_inlets(self):\n        return self.inlets\n        \n        \n    def get_culvert_length(self):\n        return self.culvert_length\n\n\n    def get_culvert_width(self):        \n        return self.width\n        \n        \n    def get_culvert_diameter(self):\n        return self.diameter\n        \n        \n    def get_culvert_height(self):\n        return self.height\n\n    def get_culvert_z1(self):\n        return self.z1\n\n    def get_culvert_z2(self):   \n        return self.z2\n\n    def get_culvert_blockage(self):\t\n        return self.blockage\n\n    def get_culvert_barrels(self):\t\n        return self.barrels\n                        \n    def get_culvert_apron(self):\n        return self.apron\n\n    # Get id of master proc of this structure\n    def get_master_proc(self):\n        return self.master_proc\n\n    # Get id of master proc of first and second inlet\n    def get_inlet_master_proc(self):\n        return self.inlet_master_proc\n\n    # Get id of processors associated with first and second inlet enquiry points\n    def get_enquiry_proc(self, id=None):\n\n        if id is none:\n            return self.enquiry_proc\n        else:\n            return self.enquiry_proc[id]\n\n\n    def set_culvert_height(self, height):\n\n        self.culvert_height = height\n\n    def set_culvert_width(self, width):\n\n        self.culvert_width = width\n\n    def set_culvert_z1(self, z1):\n\n        self.culvet_z1 = z1        \n\n    def set_culvert_z2(self, z2):\n\n        self.culvert_z2 = z2  \n\n    def set_culvert_blockage(self, blockage): \n\n        self.culvert_blockage = blockage \n\n    def set_culvert_blockage(self, barrels): \n\n        self.culvert_barrels = barrels \n        \n                        \n    def parallel_safe(self):\n        return True\n\n\n    def get_enquiry_stages(self):\n        # Should be called from all processors associated with operator\n\n        enq0 = None\n        enq1 = None\n\n        get0 = 'self.inlets[0].get_enquiry_stage()'\n        get1 = 'self.inlets[1].get_enquiry_stage()'\n\n        if self.myid == self.master_proc:\n\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n            else:\n                enq0 = pypar.receive(self.enquiry_proc[0])\n\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n            else:\n                enq1 = pypar.receive(self.enquiry_proc[1])\n\n        else:\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n                pypar.send(enq0, self.master_proc)\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n                pypar.send(enq1, self.master_proc)\n\n\n        return [enq0, enq1]\n\n    def get_enquiry_depths(self):\n        # Should be called from all processors associated with operator\n\n        enq0 = None\n        enq1 = None\n\n        get0 = 'self.inlets[0].get_enquiry_depth()'\n        get1 = 'self.inlets[1].get_enquiry_depth()'\n\n        if self.myid == self.master_proc:\n\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n            else:\n                enq0 = pypar.receive(self.enquiry_proc[0])\n\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n            else:\n                enq1 = pypar.receive(self.enquiry_proc[1])\n\n        else:\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n                pypar.send(enq0, self.master_proc)\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n                pypar.send(enq1, self.master_proc)\n\n\n        return [enq0, enq1]\n\n\n\n    def get_enquiry_positions(self):\n\n        enq0 = None\n        enq1 = None\n\n        get0 = 'self.inlets[0].get_enquiry_position()'\n        get1 = 'self.inlets[1].get_enquiry_position()'\n\n\n        if self.myid == self.master_proc:\n\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n            else:\n                enq0 = pypar.receive(self.enquiry_proc[0])\n\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n            else:\n                enq1 = pypar.receive(self.enquiry_proc[1])\n\n        else:\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n                pypar.send(enq0, self.master_proc)\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n                pypar.send(enq1, self.master_proc)\n\n\n        return [enq0, enq1]\n\n\n    def get_enquiry_xmoms(self):\n\n        enq0 = None\n        enq1 = None\n\n        get0 = 'self.inlets[0].get_enquiry_xmom()'\n        get1 = 'self.inlets[1].get_enquiry_xmom()'\n\n\n        if self.myid == self.master_proc:\n\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n            else:\n                enq0 = pypar.receive(self.enquiry_proc[0])\n\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n            else:\n                enq1 = pypar.receive(self.enquiry_proc[1])\n\n        else:\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n                pypar.send(enq0, self.master_proc)\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n                pypar.send(enq1, self.master_proc)\n\n\n        return [enq0, enq1]\n\n    def get_enquiry_ymoms(self):\n\n        enq0 = None\n        enq1 = None\n\n        get0 = 'self.inlets[0].get_enquiry_ymom()'\n        get1 = 'self.inlets[1].get_enquiry_ymom()'\n\n\n        if self.myid == self.master_proc:\n\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n            else:\n                enq0 = pypar.receive(self.enquiry_proc[0])\n\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n            else:\n                enq1 = pypar.receive(self.enquiry_proc[1])\n\n        else:\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n                pypar.send(enq0, self.master_proc)\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n                pypar.send(enq1, self.master_proc)\n\n\n        return [enq0, enq1]\n\n\n    def get_enquiry_elevations(self):\n\n        enq0 = None\n        enq1 = None\n\n        get0 = 'self.inlets[0].get_enquiry_elevation()'\n        get1 = 'self.inlets[1].get_enquiry_elevation()'\n\n\n        if self.myid == self.master_proc:\n\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n            else:\n                enq0 = pypar.receive(self.enquiry_proc[0])\n\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n            else:\n                enq1 = pypar.receive(self.enquiry_proc[1])\n\n        else:\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n                pypar.send(enq0, self.master_proc)\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n                pypar.send(enq1, self.master_proc)\n\n\n        return [enq0, enq1]\n\n\n\n    def get_enquiry_water_depths(self):\n\n        enq0 = None\n        enq1 = None\n\n        get0 = 'self.inlets[0].get_enquiry_water_depth()'\n        get1 = 'self.inlets[1].get_enquiry_water_depth()'\n\n\n        if self.myid == self.master_proc:\n\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n            else:\n                enq0 = pypar.receive(self.enquiry_proc[0])\n\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n            else:\n                enq1 = pypar.receive(self.enquiry_proc[1])\n\n        else:\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n                pypar.send(enq0, self.master_proc)\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n                pypar.send(enq1, self.master_proc)\n\n\n        return [enq0, enq1]\n\n\n    def get_enquiry_invert_elevations(self):\n\n        enq0 = None\n        enq1 = None\n\n        get0 = 'self.inlets[0].get_enquiry_invert_elevation()'\n        get1 = 'self.inlets[1].get_enquiry_invert_elevation()'\n\n\n        if self.myid == self.master_proc:\n\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n            else:\n                enq0 = pypar.receive(self.enquiry_proc[0])\n\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n            else:\n                enq1 = pypar.receive(self.enquiry_proc[1])\n\n        else:\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n                pypar.send(enq0, self.master_proc)\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n                pypar.send(enq1, self.master_proc)\n\n\n        return [enq0, enq1]\n\n\n    def get_enquiry_velocitys(self):\n\n        enq0 = None\n        enq1 = None\n\n        get0 = 'self.inlets[0].get_enquiry_velocity()'\n        get1 = 'self.inlets[1].get_enquiry_velocity()'\n\n        if self.myid == self.master_proc:\n\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n            else:\n                enq0 = pypar.receive(self.enquiry_proc[0])\n\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n            else:\n                enq1 = pypar.receive(self.enquiry_proc[1])\n\n        else:\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n                pypar.send(enq0, self.master_proc)\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n                pypar.send(enq1, self.master_proc)\n\n\n        return [enq0, enq1]\n\n\n    def get_enquiry_xvelocitys(self):\n\n        enq0 = None\n        enq1 = None\n\n        get0 = 'self.inlets[0].get_enquiry_xvelocity()'\n        get1 = 'self.inlets[1].get_enquiry_xvelocity()'\n\n        if self.myid == self.master_proc:\n\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n            else:\n                enq0 = pypar.receive(self.enquiry_proc[0])\n\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n            else:\n                enq1 = pypar.receive(self.enquiry_proc[1])\n\n        else:\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n                pypar.send(enq0, self.master_proc)\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n                pypar.send(enq1, self.master_proc)\n\n\n        return [enq0, enq1]\n\n    def get_enquiry_yvelocitys(self):\n\n        enq0 = None\n        enq1 = None\n\n        get0 = 'self.inlets[0].get_enquiry_yvelocity()'\n        get1 = 'self.inlets[1].get_enquiry_yvelocity()'\n\n\n        if self.myid == self.master_proc:\n\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n            else:\n                enq0 = pypar.receive(self.enquiry_proc[0])\n\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n            else:\n                enq1 = pypar.receive(self.enquiry_proc[1])\n\n        else:\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n                pypar.send(enq0, self.master_proc)\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n                pypar.send(enq1, self.master_proc)\n\n\n        return [enq0, enq1]\n\n\n    def get_enquiry_speeds(self):\n\n        enq0 = None\n        enq1 = None\n\n        get0 = 'self.inlets[0].get_enquiry_speed()'\n        get1 = 'self.inlets[1].get_enquiry_speed()'\n\n        \n        if self.myid == self.master_proc:\n\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n            else:\n                enq0 = pypar.receive(self.enquiry_proc[0])\n\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n            else:\n                enq1 = pypar.receive(self.enquiry_proc[1])\n\n        else:\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n                pypar.send(enq0, self.master_proc)\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n                pypar.send(enq1, self.master_proc)\n\n\n        return [enq0, enq1]\n\n\n    def get_enquiry_velocity_heads(self):\n\n        enq0 = None\n        enq1 = None\n\n        get0 = 'self.inlets[0].get_enquiry_velocity_head()'\n        get1 = 'self.inlets[1].get_enquiry_velocity_head()'\n\n        if self.myid == self.master_proc:\n\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n            else:\n                enq0 = pypar.receive(self.enquiry_proc[0])\n\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n            else:\n                enq1 = pypar.receive(self.enquiry_proc[1])\n\n        else:\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n                pypar.send(enq0, self.master_proc)\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n                pypar.send(enq1, self.master_proc)\n\n\n        return [enq0, enq1]\n\n\n    def get_enquiry_total_energys(self):\n\n        enq0 = None\n        enq1 = None\n\n        get0 = 'self.inlets[0].get_enquiry_total_energy()'\n        get1 = 'self.inlets[1].get_enquiry_total_energy()'\n\n        if self.myid == self.master_proc:\n\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n            else:\n                enq0 = pypar.receive(self.enquiry_proc[0])\n\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n            else:\n                enq1 = pypar.receive(self.enquiry_proc[1])\n\n        else:\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n                pypar.send(enq0, self.master_proc)\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n                pypar.send(enq1, self.master_proc)\n\n\n        return [enq0, enq1]\n\n\n    def get_enquiry_specific_energys(self):\n\n        enq0 = None\n        enq1 = None\n\n        get0 = 'self.inlets[0].get_enquiry_specific_energy()'\n        get1 = 'self.inlets[1].get_enquiry_specific_energy()'\n\n        if self.myid == self.master_proc:\n\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n            else:\n                enq0 = pypar.receive(self.enquiry_proc[0])\n\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n            else:\n                enq1 = pypar.receive(self.enquiry_proc[1])\n\n        else:\n            if self.myid == self.enquiry_proc[0]:\n                enq0 = eval(get0)\n                pypar.send(enq0, self.master_proc)\n\n            if self.myid == self.enquiry_proc[1]:\n                enq1 = eval(get1)\n                pypar.send(enq1, self.master_proc)\n\n\n        return [enq0, enq1]\n\n\n", "meta": {"hexsha": "b065211e64ed5c3c2992a868fe37844c30b1d9a5", "size": 45973, "ext": "py", "lang": "Python", "max_stars_repo_path": "anuga/parallel/parallel_structure_operator.py", "max_stars_repo_name": "samcom12/anuga_core", "max_stars_repo_head_hexsha": "f4378114dbf02d666fe6423de45798add5c42806", "max_stars_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_stars_count": 136, "max_stars_repo_stars_event_min_datetime": "2015-05-07T05:47:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T03:07:40.000Z", "max_issues_repo_path": "anuga/parallel/parallel_structure_operator.py", "max_issues_repo_name": "samcom12/anuga_core", "max_issues_repo_head_hexsha": "f4378114dbf02d666fe6423de45798add5c42806", "max_issues_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_issues_count": 184, "max_issues_repo_issues_event_min_datetime": "2015-05-03T09:27:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-20T04:22:48.000Z", "max_forks_repo_path": "anuga/parallel/parallel_structure_operator.py", "max_forks_repo_name": "samcom12/anuga_core", "max_forks_repo_head_hexsha": "f4378114dbf02d666fe6423de45798add5c42806", "max_forks_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_forks_count": 70, "max_forks_repo_forks_event_min_datetime": "2015-03-18T07:35:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T07:07:29.000Z", "avg_line_length": 34.9870624049, "max_line_length": 182, "alphanum_fraction": 0.5744458704, "include": true, "reason": "import numpy", "num_tokens": 10959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.15967904653056467}}
{"text": "#!/opt/local/bin/python\n# -*- Encoding: UTF-8 -*-\n\n\"\"\"\n=========\nplotting\n=========\n\n\nPlotting routines for blobtrail objects\n\n* plot_trail_simple -> Simple plotting without special geometry\n* plot_trail_geom -> Use outboard midplane geometry of CMOD. Needs geometry and separatrix data\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.interpolate import griddata, interp1d\nimport matplotlib.patches as mpatches\nfrom geometry import velocity_max, velocity_com\n\ndef plot_trail_simple(blobtrail, frames, plot_com='o', plot_max='^', plot_shape=True, save_frames=False):\n    \"\"\"\n    Plot the motion of the blob. The GPI frames are to \n    be supplied externally\n\n    Input:\n        frames:         GPI data\n        plot_com:       Mark the center of mass of the blob\n        plot_max:       Mark the maximum of the blob\n        plot_shape:     If available, plot the radial extend of the blob\n        save_frames:    Save the frames\n\n    \"\"\"\n\n    # find the frames needed to track the object\n    frame_idx = blobtrail.get_event_frames()\n\n    # Length of the blobtrail object\n    tau = np.arange(blobtrail.get_tau().size)\n\n    # Get the coordinates of the blob\n    xymax = blobtrail.get_xymax()\n    xycom = blobtrail.get_xycom()\n\n    ell_rad = blobtrail.get_ell_rad()\n    ell_pol = blobtrail.get_ell_pol()\n\n    # Get minimum and maximum value for color scales\n    minval = frames[frame_idx, :, :].min()\n    maxval = frames[frame_idx, :, :].max()\n\n    num_levels = 64\n    color_levels = np.linspace(minval, maxval, num_levels)\n\n    for fidx, tau_idx in zip(frame_idx, tau):\n        plt.figure()\n        plt.title('frame %05d' % (fidx))\n        plt.xlabel('x / px')\n        plt.ylabel('y / px')\n\n        plt.contourf(frames[fidx], cmap=plt.cm.hot, levels=color_levels)\n\n        if plot_com is not None:\n            plt.plot(xycom[:tau_idx, 1], xycom[:tau_idx, 0], plot_com)\n\n        # Plot maximum with errorbars\n        if plot_max is not None:\n            if plot_shape:\n                plt.errorbar(xymax[:tau_idx, 1], xymax[:tau_idx, 0], \n                             xerr=ell_rad[:tau_idx], yerr=ell_pol[:tau_idx],\n                             ecolor='w', linestyle='None',\n                             mfc='white', mec='green', marker=plot_max)\n            else:\n                plt.plot(xymax[:tau_idx, 1], xymax[:tau_idx, 0], plot_max)\n\n        plt.colorbar()\n\n    if save_frames:\n        F = plt.gcf()\n        F.savefig('%d/frames/frame_%05d.eps' % (self.shotnr,\n                                                self.event[1] +\n                                                self.frame0 + tau))\n        plt.close()\n\n    plt.show()\n\n\n\ndef plot_trail_geom(blobtrail, frames, rz_array=None, xyi=None, trigger_box=None,\n                    sep_data=None, plot_com=False, plot_max=False,\n                    plot_shape=False, plot_geom=False, save_frames=False):\n    \"\"\"\n    Plot the motion of the blob using CMOD GPI geometry\n    The GPI frames are to be supplied externally.\n\n    Input:\n        frames:         ndarray, GPI data. axis0: time, axis1: poloidal, axis2: radial\n        rz_array:       ndarray, Where the GPI data is known\n        xyi:            ndarray, Array on which we interpolate GPI data for output\n        trigger_box:    ndarray, Array where blobs have been detected\n        sep_data:       IDL .sav structure, see /home/rkube/IDL/separatrix.pro\n        plot_com:       Mark the center of mass of the blob\n        plot_max:       Mark the maximum of the blob\n        plot_shape:     If available, mark the FWHM of the blob\n        plot_geom:      Overplot triggering blox, limiter shadow and\n                        separatrix\n        save_frames:    Save the frames\n    \"\"\"\n\n    # find the frames needed to track the object\n    frame_idx = blobtrail.get_event_frames()\n    tau = np.arange(blobtrail.get_tau().size)\n    xymax = blobtrail.get_xymax()\n    xycom = blobtrail.get_xycom()\n    ell_rad = blobtrail.get_ell_rad()\n    ell_pol = blobtrail.get_ell_pol()\n\n    # Get minimum and maximum value for color scales\n    minval = frames[frame_idx, :, :].min()\n    maxval = frames[frame_idx, :, :].max()\n    print 'min = %f, max = %f' % (minval, maxval)\n    print 'plotting from %d - %d' % (tau[0], tau[-1])\n\n    # Number of levels in contour plots\n    num_levels = 64\n    color_levels = np.linspace(minval, maxval, num_levels)\n\n    # Positiion of velocity label\n    text_x, text_y = 86.2, -6.\n    # Font of velocity label\n    vlabel_font = dict(size=16., color='white', weight='bold')\n\n    # Blob velocity\n    vmax = velocity_max(blobtrail, rz_array)\n    vcom = velocity_com(blobtrail, rz_array)\n\n    print 'mean(vmax) rad=%f, pol=%f' % (vmax.mean(axis=0)[0], vmax.mean(axis=0)[1])\n    print 'mean(vcom) rad=%f, pol=%f' % (vcom.mean(axis=0)[0], vcom.mean(axis=0)[1])\n\n    for fidx, tau_idx in zip(frame_idx, tau):\n        plt.figure()\n        plt.title('frame %05d' % (fidx))\n        plt.xlabel('R / cm')\n        plt.ylabel('Z / cm')\n\n        # Try plotting everythin in machine coordinates. If it fails draw in pixels\n        zi = griddata(rz_array.reshape(64 * 64, 2),\n                frames[fidx, :, :].reshape(64 * 64),\n                xyi.reshape(64 * 64, 2), method='linear')\n        #plt.contour(xyi[:, :, 0], xyi[:, :, 1], zi.reshape(64, 64),\n        #            32, linewidths=0.5, colors='k')\n        plt.contourf(xyi[:, :, 0], xyi[:, :, 1], zi.reshape(64, 64),\n                     num_levels, cmap=plt.cm.hot, levels=color_levels)\n\n        #except:\n        #    print 'Failed to grid data on rz_array... Drawing in pixels'\n        #    #plt.contour(frames[self.event[1] + self.frame0 + tau, :, :],\n        #    #            32, linewidths=0.5, colors='k')\n        #    plt.contourf(frames[fidx, :, :], num_levels, cmap=plt.cm.hot, levels=color_levels)\n        plt.colorbar(ticks=np.arange(minval, maxval, (maxval - minval) / 5.), format='%3.1f')\n\n        if plot_com:\n            # Plot the leading up blob trail without error bars\n            plt.plot(xyi[xycom[:tau_idx + 1, 0].astype('int'),\n                         xycom[:tau_idx + 1, 1].astype('int'),\n                         0],\n                     xyi[xycom[:tau_idx + 1, 0].astype('int'),\n                         xycom[:tau_idx + 1, 1].astype('int'),\n                     1], '-ws')\n\n            # Interpolate width from pixel to physical units\n            ip_rad = interp1d(np.arange(64), xyi[xycom[tau_idx, 0].astype('int'), :, 0], kind='quadratic')\n            ip_pol = interp1d(np.arange(64), xyi[:, xycom[tau_idx, 1].astype('int'), 1], kind='quadratic')\n            # lower and upper 1-sigma intervall of com position in pixel coordinates\n            # Extend these intervals not out of bounds in pixel coordinates, otherwise interp1d throws ValueError\n            sigma_x_px = np.array([max(xycom[tau_idx, 0] - ell_rad[tau_idx], 0), min(xycom[tau_idx, 0] + ell_rad[tau_idx], 63)])\n            sigma_x = ip_rad(sigma_x_px)\n            sigma_y_px = np.array([max(xycom[tau_idx, 0] - ell_pol[tau_idx], 0), min(xycom[tau_idx, 0] + ell_pol[tau_idx], 63)])\n            sigma_y = ip_rad(sigma_y_px)\n            #frame_xerr = ip_rad(np.array([xycom[tau_idx, 0] - ell_rad[tau_idx], xycom[tau_idx, 0] + ell_rad[tau_idx]]))\n            #frame_yerr = ip_pol(np.array([xycom[tau_idx, 0] - ell_pol[tau_idx], xycom[tau_idx, 0] + ell_pol[tau_idx]]))\n\n            sigma_x = np.abs(sigma_x[1] - sigma_x[0])\n            sigma_y = np.abs(sigma_y[1] - sigma_y[0])\n            # Plot current blob position with error bars\n            plt.errorbar(xyi[xycom[tau_idx, 0].astype('int'),\n                             xycom[tau_idx, 1].astype('int'), 0],\n                         xyi[xycom[tau_idx, 0].astype('int'),\n                             xycom[tau_idx, 1].astype('int'), 1],\n                         xerr=sigma_x, yerr=sigma_y, ecolor='w', linestyle='None', mfc='white', mec='green', marker='s')\n\n            # Set the coordinates for plotting the text field\n\n            if (tau_idx > 0):\n                str_vcom = r\"$V_\\mathrm{COM} = (%4.1f, %4.1f)$\" % (vcom[tau_idx - 1, 0], vcom[tau_idx - 1, 1])\n                plt.text(text_x, text_y, str_vcom, fontdict=vlabel_font)\n\n        if plot_max:\n            plt.plot(xyi[xymax[:tau_idx + 1, 0].astype('int'),\n                         xymax[:tau_idx + 1, 1].astype('int'), 0],\n                     xyi[xymax[:tau_idx + 1, 0].astype('int'),\n                         xymax[:tau_idx + 1, 1].astype('int'), 1], '-.wo')\n\n            if (tau_idx > 0): \n                str_vmax = r\"$V_{max} = (%4.1f, %4.1f)$\" % (vmax[tau_idx - 1, 0], vmax[tau_idx - 1, 1])\n                plt.text(text_x, text_y, str_vmax, fontdict=vlabel_font)\n\n        if plot_geom:\n            # Get the position of the pixels for the separatrix\n            # and limiter\n            separatrix_pxs = surface_line(sep_data['rmid'].\n                                          reshape(64, 64) >\n                                          sep_data['rmid_sepx'],\n                                          mode='max')\n            limiter_pxs = surface_line(sep_data['rmid'].\n                                       reshape(64, 64) <\n                                       sep_data['rmid_lim'],\n                                       mode='min')\n\n            # Compute position, width and height of the triggering box\n            tb_lower_left = (xyi[trigger_box[2], trigger_box[0], 0],\n                             xyi[trigger_box[2], trigger_box[0], 1])\n            tb_width = (xyi[trigger_box[2], trigger_box[1], 0] -\n                        xyi[trigger_box[2], trigger_box[0], 0])\n            tb_height = (xyi[trigger_box[3], trigger_box[0], 1] -\n                         xyi[trigger_box[2], trigger_box[0], 1])\n\n            # Plot the triggering domain. Position, height and width\n            # are not automatically determined but static values.\n\n            triggering_box = mpatches.Rectangle(tb_lower_left,\n                                                width=tb_width, height=tb_height,\n                                                fill=False,\n                                                ls='dashdot',\n                                                ec='w', lw=3)\n            fig = plt.gcf()\n            ax = fig.gca()\n            ax.add_patch(triggering_box)\n\n            # Plot the separatrix\n            sep_x = [xyi[i, separatrix_pxs[i], 0] for i in\n                     np.arange(64)]\n            sep_y = [xyi[i, separatrix_pxs[i], 1] for i in\n                     np.arange(64)]\n            plt.plot(sep_x, sep_y, 'w--', linewidth=4)\n\n            lim_x = [xyi[i, limiter_pxs[i], 0] for i in np.arange(64)]\n            lim_y = [xyi[i, limiter_pxs[i], 1] for i in np.arange(64)]\n            plt.plot(lim_x, lim_y, 'w-.', linewidth=4)\n\n\n        if save_frames:\n            F = plt.gcf()\n            F.savefig('%d/frames/frame_%05d.eps' % (self.shotnr,\n                                                    self.event[1] +\n                                                    self.frame0 + tau))\n            plt.close()\n\n    plt.show()\n\n\ndef surface_line(sep_pixels, mode='max'):\n    \"\"\"\n    Given the pixels which are mapped to the closed field line region,\n    return the pixel with the largest radial coordinate for each\n    poloidal coordinate.\n    \"\"\"\n\n    # Index all pixels radially\n    lin_array = np.repeat(np.arange(64), 64).reshape(64, 64).T\n\n    # Apply the mask\n    la_masked = np.ma.array(lin_array, mask=sep_pixels)\n\n    # Return the maximum radial indices for each poloidal position\n    if (mode == 'max'):\n        return la_masked.argmax(axis=1)\n    elif (mode == 'min'):\n        return la_masked.argmin(axis=1)\n\n\n# End of file plotting.py\n", "meta": {"hexsha": "3b708a70313a047b5b64e83fe90dc63ceec6e55f", "size": 11677, "ext": "py", "lang": "Python", "max_stars_repo_path": "plotting.py", "max_stars_repo_name": "rkube/blob_tracking", "max_stars_repo_head_hexsha": "6c3242fadf71a19d335f96b7dd238553be196e4a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "plotting.py", "max_issues_repo_name": "rkube/blob_tracking", "max_issues_repo_head_hexsha": "6c3242fadf71a19d335f96b7dd238553be196e4a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plotting.py", "max_forks_repo_name": "rkube/blob_tracking", "max_forks_repo_head_hexsha": "6c3242fadf71a19d335f96b7dd238553be196e4a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9719298246, "max_line_length": 128, "alphanum_fraction": 0.548085981, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3140505385717078, "lm_q1q2_score": 0.15947858946998714}}
{"text": "#!/usr/bin/env python3\n# Christopher Vollmers\n# Roger Volden\n\nimport sys\nimport numpy as np\n\ncontent_file  =  sys.argv[1]\nout_path = sys.argv[2]\ncutoff = float(sys.argv[3])\ngenome_file = sys.argv[4]\nrefine = sys.argv[5]\n\nminimum_read_count = 3\n\nsplice_site_width = 10\n\ndef scan_for_best_bin(entry, distance_range, iterator_shift, density_dict,\n                      base_cutoff_min, base_cutoff_max,\n                      peak_areas, chromosome, side):\n    '''\n    Stuff about the inputs, outputs, and how it works\n    '''\n\n    best_extra_list, peak_center, bases = [], 0, []\n    coverage_area, best_direction_l, best_direction_r = [], [], []\n    for x in distance_range:\n        extra_list_bases, extra_list_expression = [], []\n        direction_l, direction_r = {}, {}\n        coverage_set = []\n        called = False\n        for y in distance_range:\n            try:\n               called = peak_areas[chromosome][side][entry+x+y]\n            except KeyError:\n               pass\n        if not called:\n             highest_y = 0\n             highest_y_pos = 0\n             for y in distance_range:\n                try:\n                    for item in density_dict[entry+x+y]:\n                        extra_list_bases.append(item[0])\n                        extra_list_expression.append(1)\n                        if not direction_l.get(item[4]):\n                            direction_l[item[4]] = 1\n                        else:\n                            direction_l[item[4]] += 1\n                        if not direction_r.get(item[5]):\n                            direction_r[item[5]] = 1\n                        else:\n                            direction_r[item[5]] += 1\n                        for covered_position in item[3]:\n                            coverage_set.append(covered_position)\n                except:\n                    pass\n\n        if base_cutoff_min <= np.median(extra_list_bases) <= base_cutoff_max:\n            if sum(extra_list_expression) > sum(best_extra_list):\n                best_extra_list = extra_list_expression\n                peak_center = entry+x\n                bases = extra_list_bases\n                coverage_area = coverage_set\n                best_direction_l = direction_l\n                best_direction_r = direction_r\n\n    return best_extra_list, peak_center, bases, coverage_area, \\\n           best_direction_l, best_direction_r\n\ndef determine_coverage(coverage_area, chromosome, reverse,\n                       peak_center, histo_coverage):\n    '''\n    Insert docstring\n    '''\n    coverage = [0]\n    coverage_area2 = []\n    for covered_position in set(coverage_area):\n        if coverage_area.count(covered_position) > 1:\n            coverage_area2.append(covered_position)\n\n    coverage_area = sorted(coverage_area2, reverse=reverse)\n    counter = 0\n    for base_f in coverage_area:\n        count = 0\n        if not reverse:\n            if base_f > peak_center:\n                count = 1\n        elif reverse:\n            if base_f < peak_center:\n                count = 1\n        if count == 1:\n            if counter <= 3:\n                counter += 1\n                base_f = myround(base_f)\n                try:\n                    coverage.append(histo_coverage[chromosome][base_f])\n                except KeyError:\n                    pass\n            else:\n                break\n    coverage = max(coverage)\n    return coverage, coverage_area\n\ndef read_seq_file(seq_file):\n    read_seq = {}\n    length = 0\n    for line2 in open(seq_file):\n        length += 1\n    seq_file_open = open(seq_file, 'r')\n    counter = 0\n    while counter < length:\n        fasta_name = seq_file_open.readline().strip()\n        fasta_seq = seq_file_open.readline().strip()\n        fasta_name = fasta_name[1:]\n        read_seq[fasta_name] = fasta_seq\n        counter += 2\n    return read_seq\n\ndef myround(x, base=10):\n    '''Rounds to the nearest base'''\n    return int(base * round(float(x)/base))\n\ndef find_peaks(density_dict, out, peaks, reverse, cutoff, base_cutoff_min,\n               base_cutoff_max, histo_coverage, side, peak_areas,chromosome):\n    '''\n    Insert docstring\n    '''\n\n    if not reverse:\n        distance_range = range(-splice_site_width, splice_site_width)\n        iterator_shift = 1\n    if reverse:\n        distance_range = range(splice_site_width, -splice_site_width, -1)\n        iterator_shift =- 1\n\n    entry_list = []\n    for entry in density_dict:\n      entry_list.append([entry, density_dict[entry]])\n\n\n    for entry, density in sorted(entry_list,\n                                 key=lambda x: sum(np.array(x[1])[:,2]),\n                                 reverse=True):\n        \n        if len(density) >= minimum_read_count:\n          if not peak_areas[chromosome][side].get(entry):\n\n            best_extra_list, peak_center, bases, \\\n            coverage_area, best_direction_l, best_direction_r \\\n            = scan_for_best_bin(entry, distance_range, iterator_shift,\n                                density_dict, base_cutoff_min,\n                                base_cutoff_max, peak_areas,\n                                chromosome, side)\n\n            coverage, coverage_area \\\n            = determine_coverage(coverage_area, chromosome, reverse,\n                                 peak_center, histo_coverage)\n         \n            if coverage > 0:\n                proportion = round(sum(best_extra_list)/coverage, 3)\n                print(chromosome + '\\t' + str(peak_center - 1) + '\\t'\n                      + str(peak_center + 1) + '\\t' + str(proportion))\n                if proportion > cutoff:\n                    try:\n                        Left_TSS = best_direction_l['TSS']\n                    except:\n                        Left_TSS = 0\n                    try:\n                        Left_TES = best_direction_l['TES']\n                    except:\n                        Left_TES = 0\n                    try:\n                        Right_TSS = best_direction_r['TSS']\n                    except:\n                        Right_TSS = 0\n                    try:\n                        Right_TES = best_direction_r['TES']\n                    except:\n                        Right_TES = 0\n                    Left_to_Right = Left_TSS + Right_TES\n                    Right_to_Left = Left_TES + Right_TSS\n                    Type = '-'\n\n                    if Left_to_Right < Right_to_Left and reverse:\n                        Type = '3'\n                    elif Left_to_Right < Right_to_Left and not reverse:\n                        Type = '5'\n                    elif Left_to_Right > Right_to_Left and reverse:\n                        Type = '5'\n                    elif Left_to_Right > Right_to_Left and not reverse:\n                        Type = '3'\n\n                    if Type != '-':\n                        peaks += 1\n                        out.write(chromosome + '\\t'\n                                  + str(peak_center-splice_site_width)\n                                  + '\\t' + str(peak_center+splice_site_width)\n                                  + '\\t' + str(Type) + side + str(peaks) + '_'\n                                  + str(peak_center-splice_site_width) + '_'\n                                  + str(peak_center+splice_site_width) + '_'\n                                  + str(proportion) + '\\t' + str(peaks) + '\\n')\n                        for base in range(peak_center - splice_site_width,\n                                          peak_center + splice_site_width):\n                            peak_areas[chromosome][side][base] = 1\n\n        else:\n            break\n\n    return peaks, peak_areas\n\ndef collect_reads(content_file,chromosome_list):\n    '''\n    Insert docstring\n    '''\n\n    histo_left_bases, histo_right_bases = {}, {}\n    chromosome_list_left, chromosome_list_right = chromosome_list, chromosome_list\n    histo_coverage = {}\n    base_cutoff_min, base_cutoff_max = 0, 5\n    \n    for line in open(content_file):\n        total = 0\n        b = line.strip().split('\\t')\n        infile = b[0]\n        sam_file = b[4]\n        length = 0\n        direction_dict=get_alignment_direction(sam_file)\n        for line in open(infile):\n            total += 1\n            a = line.strip().split('\\t')\n            chromosome = a[13]\n            name=a[9].split('_')[0]\n            if direction_dict.get(name):\n                direction=direction_dict[name]\n                if not histo_coverage.get(chromosome):\n                    histo_coverage[chromosome] = {}\n\n                score, direction, name,length = int(a[0]), a[8], a[9], int(a[10])\n    #            coverage = int(name.split('_')[3])\n    #            if coverage >= minimum_read_coverage:\n                \n                begin, span = int(a[15]), int(a[16])\n                blocksizes = a[18].split(',')[:-1]\n                blockstarts = a[20].split(',')[:-1]\n                readstarts = a[19].split(',')[:-1]\n\n                if direction == '+':\n                    start_seq, end_seq = 'S', 'E'\n                    left_match, right_match = 'TSS', 'TES'\n\n                else:\n                    start_seq, end_seq= 'E', 'S'\n                    left_match, right_match = 'TES', 'TSS'\n\n                coverage_set = set()\n                previous_blocksize, previous_start = -1, -1\n                previous_blockend = np.inf\n                intron, indel, indel1 = 0, 0, 0\n                low_bounds, up_bounds = [], []\n                aligned_bases=0\n                for x in range(0, len(blocksizes)):\n                    blockstart = int(blockstarts[x])\n                    blocksize = int(blocksizes[x])\n                    readstart = int(readstarts[x])\n                    aligned_bases += blocksize\n                    blockend = blockstart + blocksize\n                    if blocksize > 10:\n                        for y in range(0, blocksize, 10):\n                            rounded = myround(blockstart + y)\n                            coverage_set.add(rounded)\n                        for yy in range(y, blocksize):\n                            rounded = myround(blockstart + yy)\n                            coverage_set.add(rounded)\n                        if previous_start == -1:\n                            previous_start = blockstart\n                            min_length = 10\n                        else:\n                            min_length = 10\n\n                        if blockstart - previous_blockend > 20:\n                            previous_start = blockstart\n\n                        if blockend - previous_start > min_length:\n                            if intron == 1:\n                                up_bounds.append([previous_start, indel1, blockend])\n                                low_bounds.append([remember_blockend,\n                                                   remember_indel1, remember_start])\n                                intron = 0\n                            else:\n                                try:\n                                    next_blockstart = int(blockstarts[x+1])\n                                    next_blocksize = int(blocksizes[x+1])\n                                    next_readstart = int(readstarts[x+1])\n\n                                    insert = next_blockstart - blockend\n                                    if insert > 50:\n                                        indel1 = next_readstart \\\n                                                 - (readstart + blocksize)\n                                        remember_blockend = blockend\n                                        remember_indel1 = indel1\n                                        remember_start = previous_start\n                                        intron = 1\n                                        previous_start = next_blockstart\n                                        blockend = next_blockstart\n                                except:\n                                    pass\n                        previous_blockend = blockend\n\n                for rounded in coverage_set:\n                    try:\n                        histo_coverage[chromosome][rounded] += 1\n                    except:\n                        histo_coverage[chromosome][rounded] = 1\n\n                if aligned_bases/length > 0.70:\n                    for low_bound, indel1, blockend in low_bounds:\n                        chromosome_list_left.add(chromosome)\n                        if not histo_left_bases.get(chromosome):\n                            histo_left_bases[chromosome] = {}\n                        if not histo_left_bases[chromosome].get(low_bound):\n                            histo_left_bases[chromosome][low_bound] = []\n                        histo_left_bases[chromosome][low_bound].append([indel1, begin,\n                                                                        span, coverage_set,\n                                                                        left_match,\n                                                                        right_match])\n                    for up_bound, indel1, blockend in up_bounds:\n                        chromosome_list_right.add(chromosome)\n                        if not histo_right_bases.get(chromosome):\n                            histo_right_bases[chromosome] = {}\n                        if not histo_right_bases[chromosome].get(up_bound):\n                            histo_right_bases[chromosome][up_bound] = []\n                        histo_right_bases[chromosome][up_bound].append([indel1, begin,\n                                                                        span, coverage_set,\n                                                                        left_match,\n                                                                        right_match])\n\n    chromosome_list = chromosome_list_left & chromosome_list_right\n    return histo_left_bases, histo_right_bases, chromosome_list, histo_coverage\n\ndef parse_genome(input_file, left_bounds, right_bounds):\n    '''\n    Insert docstring\n    '''\n    chromosome_list=set()\n    gene_dict = {}\n    for line in open(input_file):\n        a = line.strip().split('\\t')\n        if len(a) > 7:\n             if a[2] == 'exon':\n                 testKey = a[8].split('; transcript_id \"')[1].split('\"')[0]\n                 if not gene_dict.get(testKey):\n                     gene_dict[testKey] = []\n                 gene_dict[testKey].append((a[0], a[3], a[4], a[6]))\n\n    read_list = []\n    for transcript_id in gene_dict:\n        transcript_data = gene_dict[transcript_id]\n\n        chromosome = transcript_data[0][0]\n        if not right_bounds.get(chromosome):\n            left_bounds[chromosome], right_bounds[chromosome]= {}, {}\n            left_bounds[chromosome]['5'], right_bounds[chromosome]['5'] = [], []\n            left_bounds[chromosome]['3'], right_bounds[chromosome]['3'] = [], []\n\n        start = sorted(transcript_data, key=lambda x: int(x[1]))[0][1]\n        end = sorted(transcript_data, key=lambda x: int(x[2]), reverse=True)[0][2]\n\n        for entry in transcript_data:\n            if entry[1] != start:\n                if entry[3] == '+':\n                    right_bounds[chromosome]['3'].append(int(entry[1])-1)\n                elif entry[3] == '-':\n                    right_bounds[chromosome]['5'].append(int(entry[1])-1)\n            if entry[2] != end:\n                if entry[3] == '+':\n                    left_bounds[chromosome]['5'].append(int(entry[2]))\n                if entry[3] == '-':\n                    left_bounds[chromosome]['3'].append(int(entry[2]))\n    return chromosome_list, left_bounds, right_bounds\n\ndef make_genome_bins(bounds, side, peaks, chromosome, peak_areas,out):\n    '''\n    Insert docstring\n    '''\n\n    for type1 in ['5', '3']:\n        covered = {}\n        position_list = sorted(bounds[type1], key=int)\n        for index1 in range(0, len(position_list)):\n            if not covered.get(index1):\n                sub_list=[]\n                sub_list.append(position_list[index1])\n                for index2 in range(index1, len(position_list)):\n                    if position_list[index2] - max(sub_list) <= splice_site_width:\n                        sub_list.append(position_list[index2])\n                        covered[index2] = 1\n                    else:\n                        break\n                single = 0\n                if len(sub_list) > 1:\n                    splice_distances = []\n                    for splice_pos in range(0, len(sub_list)-1):\n                        splice_distances.append(int(sub_list[splice_pos+1])\n                                                -int(sub_list[splice_pos]))\n                    if min(splice_distances) > 3:\n                        for x in range(0,len(sub_list),1):\n                            if x != 0:\n                                start = int(sub_list[x]\n                                            - ((sub_list[x] - sub_list[x-1])/2))\n                            else:\n                                start = int(sub_list[x]) - 1\n                            if x != len(sub_list) - 1:\n                                end = int(sub_list[x]\n                                          + ((sub_list[x+1] - sub_list[x])/2))\n                            else:\n                                end = int(sub_list[x]) + 1\n\n                            out.write(chromosome + '\\t' + str(start) + '\\t'\n                                      + str(end) + '\\t' + type1 + side\n                                      + str(peaks) + '_' + str(start) + '_'\n                                      + str(end) + '_A' + '\\t' + str(peaks) + '\\n')\n                            for base in range(start, end):\n                                peak_areas[chromosome][side][base] = 1\n                            peaks += 1\n                    else:\n                         single = 1\n                else:\n                    single = 1\n                if single == 1:\n                    start = min(sub_list) - splice_site_width\n                    end = max(sub_list) + splice_site_width\n                    out.write(chromosome + '\\t' + str(start) + '\\t' + str(end)\n                              + '\\t' + type1 + side + str(peaks) + '_'\n                              + str(start) + '_' + str(end) + '_A'\n                              + '\\t' + str(peaks) + '\\n')\n                    for base in range(start-1, end+1):\n                        peak_areas[chromosome][side][base] = 1\n                    peaks += 1\n\n    return peaks, peak_areas\n\n\ndef get_alignment_direction(sam_file):\n    direction_dict={}\n    for line in open(sam_file):\n        if line[0]!='@':\n            a=line.strip().split('\\t')\n            read_name=a[0]\n            for entry in a[10:]:\n                if 'ts:A:' in entry:\n                    direction=entry.split('ts:A:')[1]\n                    direction_dict[read_name]=direction\n    return direction_dict\n\ndef main():\n    left_bounds = {}\n    right_bounds = {}\n\n    chromosome_list,left_bounds, right_bounds = parse_genome(genome_file, left_bounds, right_bounds)\n\n    Left_Peaks = 0\n    Right_Peaks = 0\n\n    histo_left_bases, histo_right_bases, \\\n    chromosome_list, histo_coverage = collect_reads(content_file,chromosome_list)\n    out = open(out_path + '/SS.bed', 'w')\n\n    peak_areas = {}\n    print(chromosome_list)\n    for chromosome in chromosome_list:\n        peak_areas[chromosome] = {}\n        peak_areas[chromosome]['l'] = {}\n        peak_areas[chromosome]['r'] = {}\n        if not left_bounds.get(chromosome):\n            left_bounds[chromosome]={}\n            left_bounds[chromosome]['5'],left_bounds[chromosome]['3']=[],[]\n        if not right_bounds.get(chromosome):\n            right_bounds[chromosome]={}\n            right_bounds[chromosome]['5'],right_bounds[chromosome]['3']=[],[]\n        print(chromosome)\n\n        if 'g' in refine:\n            Left_Peaks_old = Left_Peaks\n            Right_Peaks_old = Right_Peaks\n            Left_Peaks, peak_areas = make_genome_bins(left_bounds[chromosome], 'l',\n                                                      Left_Peaks, chromosome, peak_areas,out)\n            Right_Peaks, peak_areas = make_genome_bins(right_bounds[chromosome], 'r',\n                                                       Right_Peaks, chromosome, peak_areas,out)\n            print('Annotation-Based',\n                  Left_Peaks - Left_Peaks_old,\n                  Right_Peaks - Right_Peaks_old)\n        Left_Peaks_old = Left_Peaks\n        Right_Peaks_old = Right_Peaks\n        Left_Peaks, peak_areas = find_peaks(histo_left_bases[chromosome],\n                                            out, Left_Peaks, True, cutoff,\n                                            0, 5, histo_coverage, 'l',\n                                            peak_areas, chromosome)\n        Right_Peaks, peak_areas = find_peaks(histo_right_bases[chromosome],\n                                             out, Right_Peaks, False, cutoff,\n                                             0, 5, histo_coverage, 'r',\n                                             peak_areas, chromosome)\n        print('Read-Based',\n              Left_Peaks - Left_Peaks_old,\n              Right_Peaks - Right_Peaks_old)\n    print(Left_Peaks)\n    print(Right_Peaks)\n\nmain()\n\n", "meta": {"hexsha": "a9c84fb6b6672502f1f15779dbffb715ad4fd498", "size": 21197, "ext": "py", "lang": "Python", "max_stars_repo_path": "spliceSites.py", "max_stars_repo_name": "christopher-vollmers/Mandalorion-Episode-II", "max_stars_repo_head_hexsha": "bef544c51910eec138a905aba8184cf5510f4d46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-08-16T21:40:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-11T06:23:40.000Z", "max_issues_repo_path": "spliceSites.py", "max_issues_repo_name": "christopher-vollmers/Mandalorion-Episode-II", "max_issues_repo_head_hexsha": "bef544c51910eec138a905aba8184cf5510f4d46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spliceSites.py", "max_forks_repo_name": "christopher-vollmers/Mandalorion-Episode-II", "max_forks_repo_head_hexsha": "bef544c51910eec138a905aba8184cf5510f4d46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-09-23T12:12:23.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-23T12:12:23.000Z", "avg_line_length": 41.562745098, "max_line_length": 100, "alphanum_fraction": 0.4686984007, "include": true, "reason": "import numpy", "num_tokens": 4217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.29746994260479465, "lm_q1q2_score": 0.15917569885147392}}
{"text": "import os\nimport itertools\nimport sys\nimport math\nimport numpy\nimport xml.etree.ElementTree as etree\nfrom copy import copy\nfrom collections import defaultdict\nfrom datetime import date\ntry:\n    from simtk.openmm import *\n    from simtk.openmm.app import *\n    import simtk.unit as units\n    from simtk.openmm.app import element as elem\nexcept:\n    from openmm import *\n    from openmm.app import *\n    import openmm.unit as units\n    from openmm.app import element as elem\n    \n\n\"\"\"\nThis is a modified 'simtk.openmm.app.forcefield.py' \nto generate the amber prmtop file for the non-standard Residue.\nFor example, in case that the amino acid is covalented to the co-factor or ligand, \nwe cannot use the standard protein database (data/protein.ff14SB.xml).\n\"\"\"\n\nclass AtomType (object):\n\n    def __init__ (self, name, atomClass, mass, element):\n        self.name      = name\n        self.atomClass = atomClass\n        self.mass      = mass\n        self.element   = element\n\nclass AtomData (object):\n\n    def __init__ (self, str_name, str_type, str_element, str_chg):\n\n        self.at_name = str_name\n        self.at_type = str_type\n        self.at_element = str_element\n        self.at_chg  = float(str_chg)\n        self.bondedTo = []\n        self.externalBonds = 0\n\nclass BondData (object):\n    \n    def __init__ (self, iatom, jatom):\n\n        self.atom1 = iatom\n        self.atom2 = jatom\n        self.length = 0.0\n\n        if iatom > jatom:\n            self.atom2 = iatom\n            self.atom1 = jatom\n\n\nclass ResidueData (object):\n    \"\"\"\n     AMBER PRMTOP did not support virtual sites with massless.\n    \"\"\"\n    def __init__ (self, res_name):\n\n        self.name  = res_name\n        self.atoms = []  # AtomData\n        self.atomIndices = {}\n        self.bonds = []\n        self.externalBonds = []\n        \n\n    def addBond (self, atom1, atom2):\n        if atom1 < atom2:\n            self.bonds.append ( (atom1, atom2) )\n        else:\n            self.bonds.append ( (atom2, atom1) )\n        self.atoms[atom1].bondedTo.append (atom2)\n        self.atoms[atom2].bondedTo.append (atom1)\n\n\n    def addBondByName (self, atom1_name, atom2_name):\n        atom1 = self.atomIndices[atom1_name]\n        atom2 = self.atomIndices[atom2_name]\n        self.addBond (atom1, atom2)\n\n\n    def addExternalBond (self, atom1):\n        self.externalBonds.append (atom1)\n        self.atoms[atom1].externalBonds += 1\n\n    def addExternalBondByName (self, atom1_name):\n        atom1 = self.atomIndices[atom1_name]\n        self.addExternalBond (atom1)\n\n\nclass HarmonicBondData(object):\n    \"\"\" a HarmonicBondForce. \"\"\"\n    def __init__ (self, type1, type2, length, k):\n        self.types1 = type1\n        self.types2 = type2\n        if type1 > type2:\n            self.types1 = type2\n            self.types2 = type1\n        self.length = length\n        self.k      = k\n\n\nclass HarmonicAngleData(object):\n    \"\"\" a HarmonicAngleForce. \"\"\"\n    def __init__ (self, type1, type2, type3, angle, k):\n        self.types1 = type1\n        self.types2 = type2\n        self.types3 = type3\n        if type1 > type3:\n            self.types1 = type3\n            self.types3 = type1\n        self.angle  = angle\n        self.k      = k\n\n\nclass PeriodicTorsionData (object):\n\n    def __init__ (self):\n        self.periodicity = []\n        self.phase       = []\n        self.k           = []\n\n\nclass PeriodicTorsion(object):\n\n    def __init__(self, types):\n\n        self.types1 = types[0]\n        self.types2 = types[1]\n        self.types3 = types[2]\n        self.types4 = types[3]\n        self.index_torsion = -1\n        self.ordering    = 'default'\n\n\n\nclass MyForceFields (object):\n\n\n    def __init__ (self, file_names): #pdb_file_name):\n        # read filename\n\n        self._atomTypes = {}\n        self._residues  = {}\n        self._atomClasses = {'':set()}\n        self._harmonicBonds = []\n        self._harmonicAngles = []\n        self._propers   = {}\n        self._impropers = {}\n        self._nonbonds  = {}\n        self._nonbonds_coulomb14scale = 0.8333333333333334\n        self._nonbonds_lj14scale      = 0.5\n        self._bondsForAtomType = defaultdict(set)\n        self._unique_torsion_list = []\n        self._unique_lj_list = []\n\n        trees = []\n\n        for xml_file_name in file_names:\n            print ('file_names', xml_file_name)\n            tree = etree.parse (xml_file_name)\n            trees.append(tree)\n\n        # Load the atom types\n        for tree in trees:\n            element = tree.getroot().find('AtomTypes')\n            if element is not None:\n                for at_type in element.findall('Type'):\n                    typeName    = at_type.attrib['name']\n                    atomClass   = at_type.attrib['class']\n                    atomMass    = float(at_type.attrib['mass'])\n                    atomElement = None\n                    if 'element' in at_type.attrib:\n                        atomElement = at_type.attrib['element']\n                    self._atomTypes[typeName] = AtomType (typeName, atomClass,\n                                                          atomMass, atomElement)\n\n                    if atomClass not in self._atomClasses:\n                        self._atomClasses[atomClass] = set()\n\n                    self._atomClasses[atomClass].add(typeName)\n                    self._atomClasses[''].add(typeName)\n\n\n\n        # Load the Residue templates\n        for tree in trees:\n            element = tree.getroot().find('Residues')\n            if element is not None:\n                for residue in element.findall('Residue'):\n                    resName     = residue.attrib['name']\n                    resData     = ResidueData (resName)\n\n                    #sum_charge = 0.0\n\n                    for ia, atom in enumerate (residue.findall('Atom')):\n                        atomName = atom.attrib['name']\n                        typeName = atom.attrib['type']\n                        charge   = atom.attrib['charge']\n\n                     #   sum_charge += float(charge)\n\n                        resData.atomIndices[atomName] = ia\n\n                        atomData = AtomData(atomName,\n                                            typeName,\n                                            self._atomTypes[typeName].element,\n                                            charge)\n\n                        resData.atoms.append (atomData)\n\n                    #if abs(sum_charge) > 0.001:\n                    #    print (resName, sum_charge)\n\n                    for bond in residue.findall('Bond'):\n                        resData.addBondByName(bond.attrib['atomName1'],\n                                              bond.attrib['atomName2'])\n\n                    for bond in residue.findall('ExternalBond'):\n                        resData.addExternalBondByName(bond.attrib['atomName'])\n\n\n                    # Register Template\n                    self._residues[resData.name] = resData\n\n        # Load the HarmonicBondForce\n        # OpenMM = 1/2 k (x - x0)**2 : E(kJ/mol/nm**2)\n        # Amber  = k' (x-x0)**2      : E(kcal/mol/A**2)\n        # k' = 1/2 k\n        ene_conv = (units.kilojoule_per_mole/(units.nanometer*units.nanometer)\n                             ).conversion_factor_to( units.kilocalorie_per_mole/(units.angstrom*units.angstrom))\n        len_conv = units.nanometer.conversion_factor_to(units.angstrom)\n\n        for tree in trees:\n            element = tree.getroot().find('HarmonicBondForce')\n            if element is not None:\n                for bond in element.findall('Bond'):\n                    type1 = bond.attrib['type1']\n                    type2 = bond.attrib['type2']\n                    bond_length = float(bond.attrib['length'])*len_conv\n                    bond_k      = 0.5*float(bond.attrib['k'])*ene_conv\n                    harmBond    = HarmonicBondData (type1, type2, bond_length, bond_k)\n                    self._harmonicBonds.append ( harmBond )\n\n\n        ene_conv = units.kilojoule_per_mole.conversion_factor_to (units.kilocalorie_per_mole)\n        for tree in trees:\n            element = tree.getroot().find('HarmonicAngleForce')\n            if element is not None:\n                for angle in element.findall('Angle'):\n                    type1 = angle.attrib['type1']\n                    type2 = angle.attrib['type2']\n                    type3 = angle.attrib['type3']\n                    ang_length = float(angle.attrib['angle'])\n                    ang_k      = 0.5*float(angle.attrib['k'])*ene_conv\n                    harmAngle  = HarmonicAngleData (type1, type2, type3,\n                                                    ang_length, ang_k)\n                    self._harmonicAngles.append ( harmAngle )\n\n\n        ene_conv = units.kilojoule_per_mole.conversion_factor_to (units.kilocalorie_per_mole)\n        for tree in trees:\n            element = tree.getroot().find('PeriodicTorsionForce')\n            if element is not None:\n\n                ordering = 'default'\n                if 'ordering' in element.attrib:\n                    ordering = element.attrib['ordering']\n\n                for proper in element.findall('Proper'):\n                    types = []\n                    for i in range(4):\n                        suffix = str(i+1)\n                        typeAttrib = 'type'+suffix\n                        typeName   = proper.attrib[typeAttrib]\n                        if typeName == '':\n                            types.append('X') #self._atomClasses[''])\n                        elif typeName not in self._atomTypes:\n                            types.append(None)\n                            print ('Proper ', typeName)\n                        else:\n                            types.append(typeName)\n\n                    torsion = PeriodicTorsion(types)\n                    index  = 1\n                    torsionData = PeriodicTorsionData()\n\n                    while 'phase%d'%index in proper.attrib:\n                        periodicity = int(proper.attrib['periodicity%d'%index])\n                        phase = float(proper.attrib['phase%d'%index])\n                        k     = float(proper.attrib['k%d'%index])*ene_conv\n                        torsionData.periodicity.append(periodicity)\n                        torsionData.phase.append(phase)\n                        torsionData.k.append(k)\n                        index += 1\n\n                    ladd = 1\n                    for uniqueTorsion in self._unique_torsion_list:\n                        if torsionData.periodicity == uniqueTorsion.periodicity and \\\n                           torsionData.phase       == uniqueTorsion.phase and \\\n                           torsionData.k           == uniqueTorsion.k:\n                            ladd = 0\n                            break\n\n                    if ladd == 1:\n                        self._unique_torsion_list.append (torsionData)\n\n                    for ii in range (len(self._unique_torsion_list)):\n                        uniqueTorsion = self._unique_torsion_list[ii]\n                        if torsionData.periodicity == uniqueTorsion.periodicity and \\\n                           torsionData.phase       == uniqueTorsion.phase and \\\n                           torsionData.k           == uniqueTorsion.k:\n                            torsion.index_torsion = ii\n\n                    typeID  = 'PR_'\n                    if types[0] == types[3]:\n                        if types[1] < types[2]:\n                            typeID += types[0]+'_'\n                            typeID += types[1]+'_'\n                            typeID += types[2]+'_'\n                            typeID += types[3]\n                        else:\n                            typeID += types[3]+'_'\n                            typeID += types[2]+'_'\n                            typeID += types[1]+'_'\n                            typeID += types[0]\n\n                    elif types[0] < types[3]:\n                        typeID += types[0]+'_'\n                        typeID += types[1]+'_'\n                        typeID += types[2]+'_'\n                        typeID += types[3]\n                    else:\n                        typeID += types[3]+'_'\n                        typeID += types[2]+'_'\n                        typeID += types[1]+'_'\n                        typeID += types[0]\n\n                    self._propers[typeID] = torsion\n\n                for improper in element.findall('Improper'):\n                    types = []\n                    improper_openmm2amber = [2,3,1,4]\n                    for i in improper_openmm2amber:\n                        suffix = str(i)\n                        typeAttrib = 'type'+suffix\n                        typeName   = improper.attrib[typeAttrib]\n                        if typeName == '':\n                            types.append('X')#self._atomClasses[''])\n                        elif typeName not in self._atomTypes:\n                            types.append(None)\n                            print ('ImProper ', typeName)\n                        else:\n                            types.append(typeName)\n\n                    torsion = PeriodicTorsion(types)\n                    torsionData = PeriodicTorsionData()\n\n                    torsion.ordering = ordering\n                    periodicity = int(improper.attrib['periodicity1'])\n                    phase       = float(improper.attrib['phase1'])\n                    k           = float(improper.attrib['k1'])*ene_conv\n                    torsionData.periodicity.append(periodicity)\n                    torsionData.phase.append(phase)\n                    torsionData.k.append(k)\n\n                    ladd = 1\n                    for uniqueTorsion in self._unique_torsion_list:\n                        if torsionData.periodicity == uniqueTorsion.periodicity and \\\n                           torsionData.phase       == uniqueTorsion.phase and \\\n                           torsionData.k           == uniqueTorsion.k:\n                            ladd = 0\n                            break\n\n                    if ladd == 1:\n                        self._unique_torsion_list.append (torsionData)\n\n                    for ii in range (len(self._unique_torsion_list)):\n                        uniqueTorsion = self._unique_torsion_list[ii]\n                        if torsionData.periodicity == uniqueTorsion.periodicity and \\\n                           torsionData.phase       == uniqueTorsion.phase and \\\n                           torsionData.k           == uniqueTorsion.k:\n                            torsion.index_torsion = ii\n\n\n                    if types[0] > types[1]:\n                        (types[0], types[1]) = (types[1], types[0])\n\n                    typeID  = 'IM_'\n                    typeID += types[0]+'_'\n                    typeID += types[1]+'_'\n                    typeID += types[2]+'_'\n                    typeID += types[3]\n\n                    self._impropers[typeID] = torsion\n\n        # Eunit: kJ/mol --> kcal/mol\n        # Lunit: nm --> A\n        ene_conv = units.kilojoules_per_mole.conversion_factor_to(units.kilocalories_per_mole) \n        len_conv = units.nanometers.conversion_factor_to(units.angstrom) \n        # Load NonbondedForce\n        for tree in trees:\n            element = tree.getroot().find('NonbondedForce')\n            if element is not None:\n\n                if 'coulomb14scale' in element.attrib:\n                    self._nonbonds_coulomb14scale = float(element.attrib['coulomb14scale'])\n                if 'lj14scale' in element.attrib:\n                    self._nonbonds_lj14scale      = float(element.attrib['lj14scale'])\n                for atom in element.findall('Atom'):\n                    typeName = atom.attrib['type']\n\n                    epsilon  = float(atom.attrib['epsilon'])*ene_conv\n                    sigma    = float(atom.attrib['sigma'])*len_conv\n\n                    self._nonbonds[typeName] = [epsilon, sigma]\n", "meta": {"hexsha": "af0ad4fe77f5d2517554c70a3fd9f96c08a491fe", "size": 15858, "ext": "py", "lang": "Python", "max_stars_repo_path": "_forcefield.py", "max_stars_repo_name": "swillow/pdb2amber", "max_stars_repo_head_hexsha": "ef092bba8e4c9d63d910d0be5c414cefa5742059", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-25T13:00:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-25T13:00:25.000Z", "max_issues_repo_path": "_forcefield.py", "max_issues_repo_name": "swillow/pdb2amber", "max_issues_repo_head_hexsha": "ef092bba8e4c9d63d910d0be5c414cefa5742059", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_forcefield.py", "max_forks_repo_name": "swillow/pdb2amber", "max_forks_repo_head_hexsha": "ef092bba8e4c9d63d910d0be5c414cefa5742059", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-21T16:14:08.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-21T16:14:08.000Z", "avg_line_length": 37.4009433962, "max_line_length": 112, "alphanum_fraction": 0.4957119435, "include": true, "reason": "import numpy", "num_tokens": 3420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.15917569551880806}}
{"text": "__all__ = [\"translation_rule\"]\n\nimport numpy as np\nfrom jax.lib import xla_client\n\nfrom . import jax_finufft\n\nfor _name, _value in jax_finufft.registrations().items():\n    xla_client.register_cpu_custom_call_target(_name, _value)\n\nxops = xla_client.ops\n\n\ndef translation_rule(\n    ctx, avals_in, avals_out, source, *points, output_shape, iflag, eps\n):\n    ndim = len(points)\n    assert 1 <= ndim <= 3\n\n    c = ctx.builder\n    source_shape_info = c.get_shape(source)\n    points_shape_info = list(map(c.get_shape, points))\n\n    # Check supported and consistent dtypes\n    source_dtype = source_shape_info.element_type()\n    single = source_dtype == np.csingle and all(\n        x.element_type() == np.single for x in points_shape_info\n    )\n    double = source_dtype == np.cdouble and all(\n        x.element_type() == np.double for x in points_shape_info\n    )\n    assert single or double\n    suffix = \"f\" if source_dtype == np.csingle else \"\"\n\n    # Check shapes\n    source_shape = source_shape_info.dimensions()\n    points_shape = tuple(x.dimensions() for x in points_shape_info)\n    n_tot = source_shape[0]\n    n_transf = source_shape[1]\n    n_j = points_shape[0][1]\n    if output_shape is None:\n        op_name = f\"nufft{ndim}d2{suffix}\".encode(\"ascii\")\n        n_k = np.array(source_shape[2:], dtype=np.int64)\n        full_output_shape = source_shape[:2] + (n_j,)\n    else:\n        type_ = 1\n        op_name = f\"nufft{ndim}d1{suffix}\".encode(\"ascii\")\n        n_k = np.array(output_shape, dtype=np.int64)\n        full_output_shape = source_shape[:2] + tuple(output_shape)\n\n    # The backend expects the output shape in Fortran order so we'll just\n    # fake it here, by sending in n_k and x in the reverse order.\n    n_k_full = np.zeros(3, dtype=np.int64)\n    n_k_full[:ndim] = n_k[::-1]\n\n    # Dispatch to the right op\n    desc = getattr(jax_finufft, f\"build_descriptor{suffix}\")(\n        eps, iflag, n_tot, n_transf, n_j, *n_k_full\n    )\n\n    return [\n        xops.CustomCallWithLayout(\n            c,\n            op_name,\n            # The inputs:\n            operands=(\n                xops.ConstantLiteral(c, np.frombuffer(desc, dtype=np.uint8)),\n                source,\n                *points[::-1],  # Reverse order because backend uses Fortran order\n            ),\n            # The input shapes:\n            operand_shapes_with_layout=(\n                xla_client.Shape.array_shape(np.dtype(np.uint8), (len(desc),), (0,)),\n                xla_client.Shape.array_shape(\n                    source_dtype,\n                    source_shape,\n                    tuple(range(len(source_shape) - 1, -1, -1)),\n                ),\n            )\n            + tuple(\n                xla_client.Shape.array_shape(\n                    x.element_type(),\n                    x.dimensions(),\n                    tuple(range(len(x.dimensions()) - 1, -1, -1)),\n                )\n                for x in points_shape_info[::-1]  # Reverse order, again\n            ),\n            # The output shapes:\n            shape_with_layout=xla_client.Shape.array_shape(\n                source_dtype,\n                full_output_shape,\n                tuple(range(len(full_output_shape) - 1, -1, -1)),\n            ),\n        )\n    ]\n", "meta": {"hexsha": "6b9941fe905c10be0a7ba453c7f7664254a870a1", "size": 3215, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/jax_finufft/translation.py", "max_stars_repo_name": "dfm/jax-finufft", "max_stars_repo_head_hexsha": "f9d5b2bd910cd6c9ce343619fb09ec5305600807", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2021-11-02T02:40:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T21:38:09.000Z", "max_issues_repo_path": "src/jax_finufft/translation.py", "max_issues_repo_name": "dfm/jax-finufft", "max_issues_repo_head_hexsha": "f9d5b2bd910cd6c9ce343619fb09ec5305600807", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2021-11-06T20:16:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T18:54:38.000Z", "max_forks_repo_path": "src/jax_finufft/translation.py", "max_forks_repo_name": "dfm/jax-finufft", "max_forks_repo_head_hexsha": "f9d5b2bd910cd6c9ce343619fb09ec5305600807", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4895833333, "max_line_length": 85, "alphanum_fraction": 0.5838258165, "include": true, "reason": "import numpy,import jax,from jax", "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.1591415996021747}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\n# Simple background function.  Assumes background has form approx 1/sqrt(m2q).\n# Note. bg_param assumed a 1 dalton binning.  Mult by binsize for other sizes.\n#\n\n\n\n# standard imports \nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# custom imports\nimport apt_fileio\nimport plotting_stuff\nimport initElements_P3\n\nimport peak_param_determination as ppd\n\nfrom histogram_functions import bin_dat\n\nplt.close('all')\n\n# Read in data\n#fn = r\"\\\\cfs2w.nist.gov\\647\\NIST_Projects\\EUV_APT_IMS\\BWC\\180821_GaN_A71\\R20_07094-v03.epos\"\n#fn = r\"\\\\cfs2w.nist.gov\\647\\NIST_Projects\\EUV_APT_IMS\\BWC\\GaN epos files\\R20_07148-v01.epos\" # Mg doped\n#fn = r\"\\\\cfs2w.nist.gov\\647\\NIST_Projects\\EUV_APT_IMS\\BWC\\GaN epos files\\R20_07148-v01_vbmq_corr.epos\"\n#fn = r\"\\\\cfs2w.nist.gov\\647\\NIST_Projects\\EUV_APT_IMS\\BWC\\GaN epos files\\R20_07247.epos\"\n#fn = r\"\\\\cfs2w.nist.gov\\647\\NIST_Projects\\EUV_APT_IMS\\BWC\\GaN epos files\\R20_07248-v01.epos\"\n#fn = r\"\\\\cfs2w.nist.gov\\647\\NIST_Projects\\EUV_APT_IMS\\BWC\\GaN epos files\\R20_07249-v01.epos\"\n#fn = r\"\\\\cfs2w.nist.gov\\647\\NIST_Projects\\EUV_APT_IMS\\BWC\\GaN epos files\\R20_07250-v01.epos\"\n#fn = r\"\\\\cfs2w.nist.gov\\647\\NIST_Projects\\EUV_APT_IMS\\BWC\\GaN epos files\\190421_AlGaN50p7_A83\\R20_07209-v01.epos\"\n#\nfn = r\"\\\\cfs2w.nist.gov\\647\\NIST_Projects\\EUV_APT_IMS\\BWC\\GaN epos files\\181210_D315_A74\\R20_07167-v03.epos\"\n#fn = r\"\\\\cfs2w.nist.gov\\647\\NIST_Projects\\EUV_APT_IMS\\BWC\\GaN epos files\\181210_D315_A74\\R20_07148-v02.epos\"\n#fn = r\"\\\\cfs2w.campus.nist.gov\\647\\NIST_Projects\\EUV_APT_IMS\\BWC\\GaN epos files\\181204_InGaNQW_A73\\R20_07144-v02.epos\"\n\n\n\nfn = fn[:-5]+'_vbm_corr.epos'\nepos = apt_fileio.read_epos_numpy(fn)\n#epos = epos[epos.size//2:-1]\n\n# Plot m2q vs event index and show the current ROI selection\nroi_event_idxs = np.arange(5000,epos.size-10000)\n\n#roi_event_idxs = np.arange(epos.size)\nax = plotting_stuff.plot_m2q_vs_time(epos['m2q'],epos,fig_idx=1)\nax.plot(roi_event_idxs[0]*np.ones(2),[0,1200],'--k')\nax.plot(roi_event_idxs[-1]*np.ones(2),[0,1200],'--k')\nax.set_title('roi selected to start analysis')\nepos = epos[roi_event_idxs]\n\n# Compute some extra information from epos information\nLASER_REP_RATE = 10000.0\nwall_time = np.cumsum(epos['pslep'])/LASER_REP_RATE\npulse_idx = np.arange(0,epos.size)\nisSingle = np.nonzero(epos['ipp'] == 1)\n\n# Define peaks to range\ned = initElements_P3.initElements()\n\n#                            N      Ga       Da\n# Define possible peaks\npk_data =   np.array(    [  (1,     0,        ed['N'].isotopes[14][0]/2),\n                            (1,     0,        ed['N'].isotopes[14][0]/1),\n                            (1,     0,        ed['N'].isotopes[15][0]/1),\n                            (1,     0,        ed['N'].isotopes[15][0]+ed['H'].isotopes[1][0]),\n                            (0,     1,        ed['Ga'].isotopes[69][0]/3),\n                            (0,     1,        ed['Ga'].isotopes[71][0]/3),\n                            (2,     0,        ed['N'].isotopes[14][0]*2),\n                            (2,     0,        ed['N'].isotopes[14][0]+ed['N'].isotopes[15][0]),\n                            (2,     0,        ed['N'].isotopes[14][0]+ed['N'].isotopes[15][0]+ed['H'].isotopes[1][0]),\n                            (0,     1,        ed['Ga'].isotopes[69][0]/2),\n                            (0,     1,        ed['Ga'].isotopes[71][0]/2),\n                            (1,     1,        (ed['N'].isotopes[14][0] + ed['Ga'].isotopes[69][0])/2),\n                            (3,     0,        ed['N'].isotopes[14][0]*3),\n                            (1,     1,        (ed['N'].isotopes[14][0] + ed['Ga'].isotopes[71][0])/2),\n                            (3,     1,        (ed['Ga'].isotopes[69][0]+3*ed['N'].isotopes[14][0])/2),\n                            (3,     1,        (ed['Ga'].isotopes[71][0]+3*ed['N'].isotopes[14][0])/2),\n                            (0,     1,        ed['Ga'].isotopes[69][0]),\n                            (0,     1,        ed['Ga'].isotopes[71][0]),\n                            (0,     1,        ed['Ga'].isotopes[71][0]+ed['H'].isotopes[1][0]),\n                            ],\n                            dtype=[('N','i4'),('Ga','i4'),('m2q','f4')] )\n\n\n#                            N      Ga      In  Da\n## Define possible peaks\n#\n#pk_data =   np.array(    [  (1,     0,      0,  ed['N'].isotopes[14][0]/2),\n#                            (1,     0,      0,  ed['N'].isotopes[14][0]/1),\n#                            (1,     0,      0,  ed['N'].isotopes[15][0]/1),\n#                            (1,     0,      0,  ed['N'].isotopes[15][0]+ed['H'].isotopes[1][0]),\n#                            (0,     1,      0,  ed['Ga'].isotopes[69][0]/3),\n#                            (0,     1,      0,  ed['Ga'].isotopes[71][0]/3),\n#                            (2,     0,      0,  ed['N'].isotopes[14][0]*2),\n#                            (2,     0,      0,  ed['N'].isotopes[14][0]+ed['N'].isotopes[15][0]),\n#                            (2,     0,      0,  ed['N'].isotopes[14][0]+ed['N'].isotopes[15][0]+ed['H'].isotopes[1][0]),\n#                            (0,     1,      0,  ed['Ga'].isotopes[69][0]/2),\n#                            (0,     1,      0,  ed['Ga'].isotopes[71][0]/2),\n#                            (1,     1,      0,  (ed['N'].isotopes[14][0] + ed['Ga'].isotopes[69][0])/2),\n#                            (3,     0,      0,  ed['N'].isotopes[14][0]*3),\n#                            (1,     1,      0,  (ed['N'].isotopes[14][0] + ed['Ga'].isotopes[71][0])/2),\n#                            (3,     1,      0,  (ed['Ga'].isotopes[69][0]+3*ed['N'].isotopes[14][0])/2),\n#                            (3,     1,      0,  (ed['Ga'].isotopes[71][0]+3*ed['N'].isotopes[14][0])/2),\n#                            (0,     1,      0,  ed['Ga'].isotopes[69][0]),\n#                            (0,     1,      0,  ed['Ga'].isotopes[71][0]),\n#                            (0,     1,      0,  ed['Ga'].isotopes[71][0]+ed['H'].isotopes[1][0]),\n#                            (0,     0,      1,  ed['In'].isotopes[113][0]/2),\n#                            (0,     0,      1,  ed['In'].isotopes[115][0]/2)\n#                            ],\n#                            dtype=[('N','i4'),('Ga','i4'),('In','i4'),('m2q','f4')] )\n\n##                            N      Ga      Al  Da\n## Define possible peaks\n#\n#pk_data =   np.array(    [  (1,     0,      0,  ed['N'].isotopes[14][0]/2),\n#                            (0,     0,      1,  ed['Al'].isotopes[27][0]/3),\n#                            (0,     0,      1,  ed['Al'].isotopes[27][0]/2),\n#                            (1,     0,      0,  ed['N'].isotopes[14][0]/1),\n#                            (1,     0,      0,  ed['N'].isotopes[15][0]/1),\n#                            (1,     0,      0,  ed['N'].isotopes[15][0]+ed['H'].isotopes[1][0]),\n#                            (1,     0,      1,  (ed['N'].isotopes[14][0]+ed['Al'].isotopes[27][0])/2),\n#                            (0,     1,      0,  ed['Ga'].isotopes[69][0]/3),\n#                            (0,     1,      0,  ed['Ga'].isotopes[71][0]/3),\n#                            (0,     0,      1,  ed['Al'].isotopes[27][0]/1),\n#                            (2,     0,      0,  ed['N'].isotopes[14][0]*2),\n#                            (2,     0,      0,  ed['N'].isotopes[14][0]+ed['N'].isotopes[15][0]),\n#                            (2,     0,      0,  ed['N'].isotopes[14][0]+ed['N'].isotopes[15][0]+ed['H'].isotopes[1][0]),\n#                            (0,     1,      0,  ed['Ga'].isotopes[69][0]/2),\n#                            (0,     1,      0,  ed['Ga'].isotopes[71][0]/2),\n#                            (1,     1,      0,  (ed['N'].isotopes[14][0] + ed['Ga'].isotopes[69][0])/2),\n#                            (3,     0,      0,  ed['N'].isotopes[14][0]*3),\n#                            (1,     1,      0,  (ed['N'].isotopes[14][0] + ed['Ga'].isotopes[71][0])/2),\n#                            (3,     1,      0,  (ed['Ga'].isotopes[69][0]+3*ed['N'].isotopes[14][0])/2),\n#                            (3,     1,      0,  (ed['Ga'].isotopes[71][0]+3*ed['N'].isotopes[14][0])/2),\n#                            (0,     1,      0,  ed['Ga'].isotopes[69][0]),\n#                            (0,     1,      0,  ed['Ga'].isotopes[71][0]),\n#                            (0,     1,      0,  ed['Ga'].isotopes[71][0]+ed['H'].isotopes[1][0])\n#                            ],\n#                            dtype=[('N','i4'),('Ga','i4'),('Al','i4'),('m2q','f4')] )\n\n\n# Define which peaks to use for CSR calcs\nGa1p_m2qs = [ed['Ga'].isotopes[69][0], ed['Ga'].isotopes[71][0]]\nGa2p_m2qs = [ed['Ga'].isotopes[69][0]/2, ed['Ga'].isotopes[71][0]/2]\n\nGa1p_idxs = [np.argmin(np.abs(m2q-pk_data['m2q'])) for m2q in Ga1p_m2qs]\nGa2p_idxs = [np.argmin(np.abs(m2q-pk_data['m2q'])) for m2q in Ga2p_m2qs]\n\n# Range the peaks\npk_params = ppd.get_peak_ranges(epos,pk_data['m2q'],peak_height_fraction=0.1)\n    \n# Determine the global background\n#glob_bg_param = ppd.fit_uncorr_bg(epos['m2q'],fit_roi=[3.5,6.5])\nbg_rois=[[3.5,6.5],[90,110]]\nglob_bg_param = ppd.get_glob_bg(epos['m2q'],rois=bg_rois)\n\n# Count the peaks, local bg, and global bg\ncts = ppd.do_counting(epos,pk_params,glob_bg_param)\n\n# Test for peak S/N and throw out craptastic peaks\nB = np.max(np.c_[cts['local_bg'][:,None],cts['global_bg'][:,None]],1)[:,None]\nT = cts['total'][:,None]\nS = T-B\nstd_S = np.sqrt(T+B)\n# Make up a threshold for peak detection... for the most part this won't matter\n# since weak peaks don't contribute to stoichiometry much... except for Mg!\nis_peak = S>2*np.sqrt(2*B)\nfor idx, ct in enumerate(cts):\n    if not is_peak[idx]:\n        for i in np.arange(len(ct)):\n            ct[i] = 0\n        \n# Calculate compositions\ncompositions = ppd.do_composition(pk_data,cts)\nppd.pretty_print_compositions(compositions,pk_data)\n    \nprint('Total Ranged Ions: '+str(np.sum(cts['total'])))\nprint('Total Ranged Local Background Ions: '+str(np.sum(cts['local_bg'])))\nprint('Total Ranged Global Background Ions: '+str(np.sum(cts['global_bg'])))\nprint('Total Ions: '+str(epos.size))\n\nprint('Overall CSR (no bg)    : '+str(np.sum(cts['total'][Ga2p_idxs])/np.sum(cts['total'][Ga1p_idxs])))\nprint('Overall CSR (local bg) : '+str((np.sum(cts['total'][Ga2p_idxs])-np.sum(cts['local_bg'][Ga2p_idxs]))/(np.sum(cts['total'][Ga1p_idxs])-np.sum(cts['local_bg'][Ga1p_idxs]))))\nprint('Overall CSR (global bg): '+str((np.sum(cts['total'][Ga2p_idxs])-np.sum(cts['global_bg'][Ga2p_idxs]))/(np.sum(cts['total'][Ga1p_idxs])-np.sum(cts['global_bg'][Ga1p_idxs]))))\n\n\n# Plot all the things\nxs, ys = bin_dat(epos['m2q'],user_roi=[0.5, 120],isBinAligned=True)\n#ys_sm = ppd.do_smooth_with_gaussian(ys,30)\nys_sm = ppd.moving_average(ys,30)\n\nglob_bg = ppd.physics_bg(xs,glob_bg_param)    \n\nfig = plt.figure(num=100)\nfig.clear()\nax = fig.gca()\n\nax.plot(xs,ys_sm,label='hist')\nax.plot(xs,glob_bg,label='global bg')\n\nax.set(xlabel='m/z (Da)', ylabel='counts')\nax.grid()\nfig.tight_layout()\nfig.canvas.manager.window.raise_()\nax.set_yscale('log')    \nax.legend()\n\nfor idx,pk_param in enumerate(pk_params):\n    \n    if is_peak[idx]:\n        ax.plot(np.array([1,1])*pk_param['pre_rng'] ,np.array([0.5,(pk_param['amp']+pk_param['off'])]),'k--')\n        ax.plot(np.array([1,1])*pk_param['post_rng'] ,np.array([0.5,(pk_param['amp']+pk_param['off'])]),'k--')\n        ax.plot(np.array([1,1])*pk_param['pre_bg_rng'] ,np.array([0.5,(pk_param['amp']+pk_param['off'])]),'m--')\n        ax.plot(np.array([1,1])*pk_param['post_bg_rng'] ,np.array([0.5,(pk_param['amp']+pk_param['off'])]),'m--')\n        \n        ax.plot(np.array([pk_param['pre_bg_rng'],pk_param['post_bg_rng']]) ,np.ones(2)*pk_param['loc_bg'],'g--')\n    else:\n        ax.plot(np.array([1,1])*pk_param['x0_mean_shift'] ,np.array([0.5,(pk_param['amp']+pk_param['off'])]),'r--')\n        \nfor roi in bg_rois:\n    xbox = np.array([roi[0],roi[0],roi[1],roi[1]])\n    ybox = np.array([0.1,np.max(ys_sm)/10,np.max(ys_sm)/10,0.1])\n    \n    ax.fill(xbox,ybox, 'b', alpha=0.2)\n\n        \nplt.pause(0.1)\n\n\n\n\n#### END BASIC ANALYSIS ####\n\n\n\n#### START EXPLORATORY ANALYSIS ####\n\n\n\n\n# Slice and dice the data in wall_time\nidxs_list = []\nCHUNK_SIZE = 32000\ns_idx = 0\nwhile s_idx<epos.size:\n    e_idx = np.min([epos.size,s_idx+CHUNK_SIZE])\n    idxs_list.append([s_idx,e_idx])\n    s_idx = e_idx\n    \n# Count and compositions\ncsr = np.full(len(idxs_list),-1.0)\nGa_comp = np.full(len(idxs_list),-1.0)\nGa_comp_std = np.full(len(idxs_list),-1.0)\nGa_comp_glob = np.full(len(idxs_list),-1.0)\nGa_comp_std_glob = np.full(len(idxs_list),-1.0)\n\nkeys = list(pk_data.dtype.fields.keys())\nkeys.remove('m2q')\nGa_idx = keys.index('Ga')\nfor loop_idx, idxs in enumerate(idxs_list):\n\n    sub_epos = epos[idxs[0]:idxs[1]]\n    \n    plotting_stuff.plot_histo(sub_epos['m2q'],321,user_xlim=[0,275],user_bin_width=0.1,user_label=loop_idx)\n    plt.waitforbuttonpress()    \n#    r = np.sqrt(sub_epos['x_det']**2+sub_epos['y_det']**2)\n#    sub_idxs = np.nonzero(r>=0)\n#    cts = ppd.do_counting(sub_epos[sub_idxs],pk_params,glob_bg_param)\n#    \n#    tot_bg_ct = epos['m2q'][(epos['m2q']>=80) & (epos['m2q']<=120)].size\n#    sub_bg_ct = sub_epos['m2q'][(sub_epos['m2q']>=80) & (sub_epos['m2q']<=120)].size\n#    \n#    loc_bg_param = glob_bg_param*sub_bg_ct/tot_bg_ct\n    glob_bg_param_chunk = ppd.get_glob_bg(sub_epos['m2q'],rois=bg_rois)\n    \n    cts = ppd.do_counting(sub_epos,pk_params,glob_bg_param_chunk)\n    Ga_comp[loop_idx] = ppd.do_composition(pk_data,cts)[0][0][Ga_idx]\n    Ga_comp_std[loop_idx] = ppd.do_composition(pk_data,cts)[0][1][Ga_idx]\n    \n    Ga_comp_glob[loop_idx] = ppd.do_composition(pk_data,cts)[2][0][Ga_idx]\n    Ga_comp_std_glob[loop_idx] = ppd.do_composition(pk_data,cts)[2][1][Ga_idx]\n    \n    \n    \n    csr[loop_idx] = np.sum(cts['total'][Ga2p_idxs])/np.sum(cts['total'][Ga1p_idxs])\n    print('Total Ranged Ions: '+str(np.sum(cts['total'])))\n    print('Total Ranged Global Background Ions: '+str(np.sum(cts['global_bg'])))\n    print('Total Ions: '+str(sub_epos.size))\n\n    compositions = ppd.do_composition(pk_data,cts)\n    ppd.pretty_print_compositions(compositions,pk_data)\n#    \n#    \n#    print(sub_epos['m2q'][(sub_epos['m2q']>=80) & (sub_epos['m2q']<=120)].size)\n#    print(np.sum(cts['total']))\n#    print(sub_epos['m2q'][(sub_epos['m2q']>=80) & (sub_epos['m2q']<=120)].size/np.sum(cts['total']))\n#    \n    \n    \n\nfig = plt.figure(num=101)\nfig.clear()\nax = fig.gca()\nax.errorbar((np.arange(Ga_comp.size)+0.5)*CHUNK_SIZE,Ga_comp,yerr=Ga_comp_std,fmt='.',capsize=4,label='chunk based (wall time)')\nax.errorbar((np.arange(Ga_comp.size)+0.5)*CHUNK_SIZE,Ga_comp_glob,yerr=Ga_comp_std_glob,fmt='.',capsize=4,label='chunk based (wall time)_glob')\nax.set(xlabel='ion idx', ylabel='Ga %')\nax.legend()\n\n\n\n\n\nfig = plt.figure(num=102)\nfig.clear()\nax = fig.gca()\nax.errorbar(csr,Ga_comp,yerr=Ga_comp_std,fmt='.',capsize=4,label='by wall time')\n    \nax.plot([np.min(csr),np.max(csr)],[0.5,0.5],'k--')\n\nax.set(xlabel='CSR', ylabel='Ga %', ylim=[0, 1], xlim=[1e-2,2])\n\nax.set_title('by wall time')\nax.set_xscale('log')\n\nax.legend()\nax.grid()\nfig.tight_layout()\nfig.canvas.manager.window.raise_()\n\n\n\n\n\n\n\n\n\nimport colorcet as cc\n\ndef extents(f):\n    delta = f[1] - f[0]\n    return [f[0] - delta/2, f[-1] + delta/2]\n\ndef create_histogram(xs,ys,x_roi=None,y_roi=None):\n    num_x = 128\n    num_y = num_x\n    N,x_edges,y_edges = np.histogram2d(xs,ys,bins=[num_x,num_y],range=[x_roi,y_roi],density=False)\n    return (N,x_edges,y_edges)\n\n\nfig = plt.figure(num=301)\nplt.clf()\nax = fig.gca()\n\n\nsel_idxs = np.arange(epos.size)\nsel_idxs = np.where((epos['m2q']>(0.9+0)) & (epos['m2q']<(1.2+0)))\n\n\npk_data\n\nN,x_edges,y_edges = create_histogram(epos['x_det'][sel_idxs],epos['y_det'][sel_idxs],\n                                     x_roi=[-35,35],y_roi=[-35,35])\n#ax.imshow(np.log10(1+1*np.transpose(N)), aspect='auto', \nax.imshow(np.transpose(N), aspect='auto', \n           extent=extents(x_edges) + extents(y_edges), origin='lower', cmap=cc.cm.CET_L8,\n           interpolation='nearest')\nax.set_aspect('equal', 'box')\n\nax.set(xlabel='det_x')\nax.set(ylabel='det_y')\n\n\n\n\nkeys = list(pk_data.dtype.fields.keys())\nkeys.remove('m2q')\n\nfor k in keys:\n    k_pks = np.where(pk_data[k]>0)[0]    \n    sel_idxs = np.zeros(0,dtype='int64')\n    for pk in k_pks:\n        ev_idxs = np.where((epos['m2q']>pk_params['pre_rng'][pk]) & (epos['m2q']<pk_params['post_rng'][pk]))[0]\n        sel_idxs = np.concatenate((sel_idxs,ev_idxs))\n    \n    fig = plt.figure()\n    plt.clf()\n    ax = fig.gca()\n        \n    N,x_edges,y_edges = create_histogram(epos['x_det'][sel_idxs],epos['y_det'][sel_idxs],\n                                         x_roi=[-35,35],y_roi=[-35,35])\n    #ax.imshow(np.log10(1+1*np.transpose(N)), aspect='auto', \n    ax.imshow(np.transpose(N), aspect='auto', \n               extent=extents(x_edges) + extents(y_edges), origin='lower', cmap=cc.cm.CET_L8,\n               interpolation='nearest')\n    ax.set_aspect('equal', 'box')\n    \n    ax.set(xlabel='det_x')\n    ax.set(ylabel='det_y')\n    ax.set_title(k)\n        \n    \n\n\n\n\n# All ranged ions\n\nkeys = list(pk_data.dtype.fields.keys())\nkeys.remove('m2q')\n\nsel_idxs = np.zeros(0,dtype='int64')    \n\nfor k in keys:\n    k_pks = np.where(pk_data[k]>0)[0]    \n    for pk in k_pks:\n        ev_idxs = np.where((epos['m2q']>pk_params['pre_rng'][pk]) & (epos['m2q']<pk_params['post_rng'][pk]))[0]\n        sel_idxs = np.concatenate((sel_idxs,ev_idxs))\n    \nfig = plt.figure(321)\nplt.clf()\nax = fig.gca()\n    \nN,x_edges,y_edges = create_histogram(0+epos['x_det'][sel_idxs],0+epos['y_det'][sel_idxs],\n                                     x_roi=[-35,35],y_roi=[-35,35])\n#ax.imshow(np.log10(1+1*np.transpose(N)), aspect='auto', \nmet = N\n\nmet[met==0] = 100\n\nmet = 1/(met+3)\n\n\nax.imshow(np.transpose(met), aspect='auto', \n           extent=extents(x_edges) + extents(y_edges), origin='lower', cmap=cc.cm.CET_R2,\n           interpolation='nearest')\nax.set_aspect('equal', 'box')\n\nax.set(xlabel='det_x')\nax.set(ylabel='det_y')\n    \n\ncx = 0.5*(x_edges[1:]+x_edges[:-1])\ncy = 0.5*(y_edges[1:]+y_edges[:-1])\n\nCX,CY = np.meshgrid(cx,cy)\n\n\n\n\n  \n\n\n\ndef mean_shift(xs,ys):\n    radius = 5\n    \n    x_curr = 0\n    y_curr = 0\n    \n    N_LOOPS = 64\n    \n    xi = np.zeros(N_LOOPS)\n    yi = np.zeros(N_LOOPS)\n    \n    for i in np.arange(N_LOOPS):\n        x_prev = x_curr\n        y_prev = y_curr\n        \n        idxs = np.where(((xs-x_curr)**2+(ys-y_curr)**2) <= radius**2)\n#        print(idxs)\n        \n        x_q = np.mean(xs[idxs])\n        y_q = np.mean(ys[idxs])\n           \n        dx = x_q-x_prev\n        dy = y_q-y_prev\n        \n        x_curr = x_prev-dx\n        y_curr = y_prev-dy\n        \n        if np.sqrt((x_curr-x_prev)**2 + (y_curr-y_prev)**2) < (radius*1e-2):\n#            print('iter  B #',i,'    ',x_curr,y_curr)\n#            print(i)\n            break\n#        else:\n#            print('iter NB #',i,'    ',x_curr,y_curr)\n#        print('iter #',i,'    ',x_curr,y_curr)\n        xi[i] = x_curr\n        yi[i] = y_curr\n              \n\n    return xi[:i], yi[:i]\n\n\n\nxc,yc = mean_shift(epos['x_det'][sel_idxs],epos['y_det'][sel_idxs])\n\nax.plot(xc,yc,'-o')\n\n\n\n\n\n\n\n\n# Slice and dice the data in detector space (polar)\nidxs_list = []\n#STEP = 2\n\nr = np.sqrt(np.square(epos['x_det']-xc[-1])+np.square(epos['y_det']-yc[-1]))\n\nR_DET_MAX = 28\nR_C = np.sqrt(xc[-1]**2+yc[-1]**2)\n\nR_MAX = R_DET_MAX-R_C\n\nr_edges = np.sqrt(np.linspace(0, R_MAX**2, 6))\nr_centers = (r_edges[:-1]+r_edges[1:])/2\n\nfor i in np.arange(r_edges.size-1):\n    idxs = np.where((r>r_edges[i]) & (r<=r_edges[i+1]))[0]\n    idxs_list.append(idxs)    \n\n\n\n#for rq in np.arange(2,R_MAX,STEP):\n#    idxs = np.where((r>rq) & (r<=(rq+STEP)))[0]\n#    idxs_list.append(idxs)    \n\n# Count and compositions\ncsr = np.full(len(idxs_list),-1.0)\nGa_comp = np.full(len(idxs_list),-1.0)\nGa_comp_std = np.full(len(idxs_list),-1.0)\nGa_comp_glob = np.full(len(idxs_list),-1.0)\nGa_comp_std_glob = np.full(len(idxs_list),-1.0)\n\n\nGa_idx = keys.index('Ga')\nfor loop_idx, idxs in enumerate(idxs_list):\n    sub_epos = epos[idxs]\n    \n#    tot_bg_ct = epos['m2q'][(epos['m2q']>=80) & (epos['m2q']<=120)].size\n#    sub_bg_ct = sub_epos['m2q'][(sub_epos['m2q']>=80) & (sub_epos['m2q']<=120)].size\n    \n#    loc_bg_param = glob_bg_param*sub_bg_ct/tot_bg_ct\n    \n    glob_bg_param_chunk = ppd.get_glob_bg(sub_epos['m2q'],rois=bg_rois)\n\n    \n    cts = ppd.do_counting(sub_epos,pk_params,glob_bg_param_chunk)\n    \n    csr[loop_idx] = np.sum(cts['total'][Ga2p_idxs])/np.sum(cts['total'][Ga1p_idxs])\n    Ga_comp[loop_idx] = ppd.do_composition(pk_data,cts)[0][0][Ga_idx]\n    Ga_comp_std[loop_idx] = ppd.do_composition(pk_data,cts)[0][1][Ga_idx]\n\n    Ga_comp_glob[loop_idx] = ppd.do_composition(pk_data,cts)[2][0][Ga_idx]\n    Ga_comp_std_glob[loop_idx] = ppd.do_composition(pk_data,cts)[2][1][Ga_idx]\n    \n    compositions = ppd.do_composition(pk_data,cts)\n    ppd.pretty_print_compositions(compositions,pk_data)\n    print('COUNTS IN CHUNK: ',np.sum(cts['total']))\n\n\n\nfig = plt.figure(num=201)\nfig.clear()\nax = fig.gca()\n#ax.errorbar((np.arange(Ga_comp.size)+0.5)*STEP,Ga_comp,yerr=Ga_comp_std,fmt='.',capsize=4,label='Ga %')\n#ax.errorbar((np.arange(Ga_comp.size)+0.5)*STEP,Ga_comp_glob,yerr=Ga_comp_std_glob,fmt='.',capsize=4,label='glob')\nax.errorbar(r_centers,Ga_comp,yerr=Ga_comp_std,fmt='.',capsize=4,label='Ga %')\nax.errorbar(r_centers,Ga_comp_glob,yerr=Ga_comp_std_glob,fmt='.',capsize=4,label='glob')\n\n\n\n\nax.set(xlabel='radius', ylabel='Ga %')\n\nax_twin= ax.twinx()\n#ax_twin.plot((np.arange(Ga_comp.size)+0.5)*STEP,csr,'s',color='r',label='Ga CSR')\nax_twin.plot(r_centers,csr,'s',color='r',label='Ga CSR')\n\nax.legend()\nax_twin.legend(loc=7)\nax_twin.set(ylabel='Ga CSR')\n\n\nfig = plt.figure(num=202)\nfig.clear()\nax = fig.gca()\n\nax.errorbar(csr,Ga_comp,yerr=Ga_comp_std,fmt='.',capsize=4,label='det based (radial)')\nax.plot([np.min(csr),np.max(csr)],[0.5,0.5],'k--')\n\nax.set(xlabel='CSR', ylabel='Ga %', ylim=[0, 1], xlim=[1e-2,2])\nax.legend()\nax.set_title('by radius')\nax.set_xscale('log')\nax.grid()\nfig.tight_layout()\nfig.canvas.manager.window.raise_()\n\n\nfor i in np.arange(csr.size):\n    print(csr[i],'\\t',Ga_comp[i],'\\t',Ga_comp_std[i])\n\n\n\n\n\n\n\n\n\n\n# chop data up by Radius AND time\n# Aim for 50 k ions per time chunk\n# Aim for 5 radial chunks\n\n\nes2cs = lambda es : (es[:-1]+es[1:])/2.0\n    \n#idxs_list = []\n    \nN_time_chunks = int(np.floor(epos.size/256000))\n#N_time_chunks = 4\n\nN_events_per_time_chunk = epos.size//N_time_chunks\ntime_chunk_edges = np.arange(N_time_chunks+1)*N_events_per_time_chunk\ntime_chunk_centers = es2cs(time_chunk_edges)\n\n\nR_DET_MAX = 28\nR_C = np.sqrt(xc[-1]**2+yc[-1]**2)\nR_MAX = R_DET_MAX-R_C\n\nN_ann_chunks = 3\nr_edges = np.sqrt(np.linspace(0, R_MAX**2, N_ann_chunks+1))\nr_centers = es2cs(r_edges)\n\n\n\n\ncsr = np.full([N_time_chunks,N_ann_chunks],-1.0)\nGa_comp = np.full([N_time_chunks,N_ann_chunks],-1.0)\nGa_comp_std = np.full([N_time_chunks,N_ann_chunks],-1.0)\nGa_comp_glob = np.full([N_time_chunks,N_ann_chunks],-1.0)\nGa_comp_std_glob = np.full([N_time_chunks,N_ann_chunks],-1.0)\ntot_cts = np.full([N_time_chunks,N_ann_chunks],-1.0)\n\nfor t_idx in np.arange(N_time_chunks):\n    sub_epos = epos[time_chunk_edges[t_idx]:time_chunk_edges[t_idx+1]]\n    r = np.sqrt(np.square(sub_epos['x_det']-xc[-1])+np.square(sub_epos['y_det']-yc[-1]))\n    for a_idx in np.arange(N_ann_chunks):\n        \n        idxs = np.where((r>r_edges[a_idx]) & (r<=r_edges[a_idx+1]))[0]\n        \n        subsubepos = sub_epos[idxs]\n        \n        glob_bg_param_chunk = ppd.get_glob_bg(subsubepos['m2q'],rois=bg_rois)\n\n        cts = ppd.do_counting(subsubepos,pk_params,glob_bg_param_chunk)\n        \n        csr[t_idx,a_idx] = np.sum(cts['total'][Ga2p_idxs])/np.sum(cts['total'][Ga1p_idxs])\n        Ga_comp[t_idx,a_idx] = ppd.do_composition(pk_data,cts)[0][0][Ga_idx]\n        Ga_comp_std[t_idx,a_idx] = ppd.do_composition(pk_data,cts)[0][1][Ga_idx]\n    \n        Ga_comp_glob[t_idx,a_idx] = ppd.do_composition(pk_data,cts)[2][0][Ga_idx]\n        Ga_comp_std_glob[t_idx,a_idx] = ppd.do_composition(pk_data,cts)[2][1][Ga_idx]\n        \n        compositions = ppd.do_composition(pk_data,cts)\n        ppd.pretty_print_compositions(compositions,pk_data)\n        print('COUNTS IN CHUNK: ',np.sum(cts['total']))\n        tot_cts[t_idx,a_idx] = np.sum(cts['total'])\n        \n\n\nfig = plt.figure(num=402)\nfig.clear()\nax = fig.gca()\n\n#ax.errorbar(csr.flatten(),Ga_comp.flatten(),yerr=Ga_comp_std.flatten(),fmt='.',capsize=4,label='det based (radial)')\nax.errorbar(csr.flatten(),Ga_comp_glob.flatten(),yerr=Ga_comp_std_glob.flatten(),fmt='.',capsize=4,label='det based (radial)')\nax.plot([np.min(csr),np.max(csr)],[0.5,0.5],'k--')\n\nax.set(xlabel='CSR', ylabel='Ga %', ylim=[0, 1], xlim=[5e-3,5])\nax.legend()\nax.set_title('by radius')\nax.set_xscale('log')\nax.grid()       \nfig.tight_layout()\nfig.canvas.manager.window.raise_()\n\n\n\n\nfig = plt.figure(num=405)\nfig.clear()\nax = fig.gca()\nax.imshow(csr.T,\n          extent=extents(time_chunk_edges) + [r_edges[0], r_edges[-1]+np.diff(r_edges[-2:])],\n          aspect='auto',\n           origin='lower')\nax.set(xlabel='ev idx')\nax.set(ylabel='rad')\n\n\n\nfor i in np.arange(csr.size):\n    print(csr.flatten()[i],'\\t',Ga_comp_glob.flatten()[i],'\\t',Ga_comp_std_glob.flatten()[i])\n\n\n\n\n\n", "meta": {"hexsha": "1ced4a21462077c9502868415cbd1e3575600247", "size": 25131, "ext": "py", "lang": "Python", "max_stars_repo_path": "RandomScripts/s_range_m2q_CSR.py", "max_stars_repo_name": "bcaplins/NIST_APT_TOOLS", "max_stars_repo_head_hexsha": "80c25498e8b069b8ee289a2d09c76c932c054cea", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RandomScripts/s_range_m2q_CSR.py", "max_issues_repo_name": "bcaplins/NIST_APT_TOOLS", "max_issues_repo_head_hexsha": "80c25498e8b069b8ee289a2d09c76c932c054cea", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RandomScripts/s_range_m2q_CSR.py", "max_forks_repo_name": "bcaplins/NIST_APT_TOOLS", "max_forks_repo_head_hexsha": "80c25498e8b069b8ee289a2d09c76c932c054cea", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6634482759, "max_line_length": 179, "alphanum_fraction": 0.5652381521, "include": true, "reason": "import numpy", "num_tokens": 8583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363242, "lm_q2_score": 0.3040416623541848, "lm_q1q2_score": 0.15914159300060746}}
{"text": "\n__all__ = ['FixedTarget']\n\nimport numpy as np\n\nfrom pylightcurve.errors import *\nfrom pylightcurve.__databases__ import plc_data\nfrom pylightcurve.analysis.curve_fit import curve_fit\nfrom pylightcurve.spacetime.angles import arccos, _request_angle\n\n\nclass _Target:\n\n    def __init__(self, ra, dec):\n\n        _request_angle(ra)\n        _request_angle(dec)\n\n        if 270 > dec.deg() > 90:\n            raise PyLCInputError('Declination must within -90, 90 degrees')\n\n        self.dec = dec\n        self.ra = ra\n\n        self.coord = '{0} {1}'.format(self.ra.hms(), self.dec.dms_coord())\n\n\nclass FixedTarget(_Target):\n\n    def __init__(self, ra, dec):\n\n        _Target.__init__(self, ra, dec)\n\n    def convert_to_bjd_tdb(self, time, time_format):\n\n        if isinstance(time, float):\n\n            if time_format in ['BJD_TDB', 'BJD_TT']:\n                return time\n            elif time_format == 'JD_UTC':\n                return self._bjd_tdb(None, time)\n            elif time_format == 'MJD_UTC':\n                return self._bjd_tdb(None, time + 2400000.5)\n            elif time_format == 'BJD_UTC':\n                return self._bjd_tdb(None, curve_fit(self._bjd_utc, [0], [time], p0=[time])[0][0])\n            elif time_format in ['HJD_TDB', 'HJD_TT']:\n                return self._bjd_tdb(None, curve_fit(self._hjd_tdb, [0], [time], p0=[time])[0][0])\n            elif time_format == 'HJD_UTC':\n                return self._bjd_tdb(None, curve_fit(self._hjd_utc, [0], [time], p0=[time])[0][0])\n            else:\n                raise PyLCInputError(\n                    'Not valid time format. Available formats: JD_UTC, MJD_UTC, BJD_UTC, BJD_TDB, BJD_TT, '\n                    'HJD_UTC, HJD_BJD, HJD_TT')\n\n        else:\n            try:\n                time = np.array(time, dtype=float)\n\n                if time_format in ['BJD_TDB', 'BJD_TT']:\n                    return time\n                elif time_format == 'JD_UTC':\n                    return np.array([self._bjd_tdb(None, ff) for ff in time])\n                elif time_format == 'MJD_UTC':\n                    return np.array([self._bjd_tdb(None, ff + 2400000.5) for ff in time])\n                elif time_format == 'BJD_UTC':\n                    return np.array([self._bjd_tdb(None, curve_fit(self._bjd_utc, [0], [ff], p0=[ff])[0][0])\n                                     for ff in time])\n                elif time_format in ['HJD_TDB', 'HJD_TT']:\n                    return np.array([self._bjd_tdb(None, curve_fit(self._hjd_tdb, [0], [ff], p0=[ff])[0][0])\n                                     for ff in time])\n                elif time_format == 'HJD_UTC':\n                    return np.array([self._bjd_tdb(None, curve_fit(self._hjd_utc, [0], [ff], p0=[ff])[0][0])\n                                     for ff in time])\n                else:\n                    raise PyLCInputError(\n                        'Not valid time format. Available formats: JD_UTC, MJD_UTC, BJD_UTC, BJD_TDB, BJD_TT, '\n                        'HJD_UTC, HJD_BJD, HJD_TT')\n\n            except:\n                raise PyLCInputError('Not valid input for time')\n\n    def convert_to_jd(self, time, time_format):\n\n        if isinstance(time, float):\n\n            if time_format in ['BJD_TDB', 'BJD_TT']:\n                return curve_fit(self._bjd_tdb, [0], [time], p0=[time])[0][0]\n            elif time_format == 'JD_UTC':\n                return time\n            elif time_format == 'MJD_UTC':\n                return time + 2400000.5\n            elif time_format == 'BJD_UTC':\n                return curve_fit(self._bjd_utc, [0], [time], p0=[time])[0][0]\n            elif time_format in ['HJD_TDB', 'HJD_TT']:\n                return curve_fit(self._hjd_tdb, [0], [time], p0=[time])[0][0]\n            elif time_format == 'HJD_UTC':\n                return curve_fit(self._hjd_utc, [0], [time], p0=[time])[0][0]\n            else:\n                raise PyLCInputError(\n                    'Not valid time format. Available formats: JD_UTC, MJD_UTC, BJD_UTC, BJD_TDB, BJD_TT, '\n                    'HJD_UTC, HJD_BJD, HJD_TT')\n\n        else:\n            try:\n                time = np.array(time, dtype=float)\n\n                if time_format in ['BJD_TDB', 'BJD_TT']:\n                    return np.array([curve_fit(self._bjd_tdb, [0], [ff], p0=[time])[0][0] for ff in time])\n                elif time_format == 'JD_UTC':\n                    return time\n                elif time_format == 'MJD_UTC':\n                    return time + 2400000.5\n                elif time_format == 'BJD_UTC':\n                    return np.array([curve_fit(self._bjd_utc, [0], [ff], p0=[time])[0][0] for ff in time])\n                elif time_format in ['HJD_TDB', 'HJD_TT']:\n                    return np.array([curve_fit(self._hjd_tdb, [0], [ff], p0=[time])[0][0] for ff in time])\n                elif time_format == 'HJD_UTC':\n                    return np.array([curve_fit(self._hjd_utc, [0], [ff], p0=[time])[0][0] for ff in time])\n                else:\n                    raise PyLCInputError(\n                        'Not valid time format. Available formats: JD_UTC, MJD_UTC, BJD_UTC, BJD_TDB, BJD_TT, '\n                        'HJD_UTC, HJD_BJD, HJD_TT')\n\n            except:\n                raise PyLCInputError('Not valid input for time')\n\n    def convert_to_mjd(self, time, time_format):\n\n        return self.convert_to_jd(time, time_format) - 2400000.5\n\n    def _hjd_utc(self, x, jd):\n\n        ssb_ra, ssb_dec, ssb_d, ssb_dt = plc_data.heliocentre(jd)\n\n        a = ssb_d / 60.0 / 24.0\n        b = self.dec.sin() * np.sin(ssb_dec)\n        c = self.dec.cos() * np.cos(ssb_dec) * np.cos(self.ra.rad() - ssb_ra)\n\n        return jd - a * (b + c)\n\n    def _hjd_tdb(self, x, jd):\n\n        ssb_ra, ssb_dec, ssb_d, ssb_dt = plc_data.heliocentre(jd)\n\n        a = ssb_d / 60.0 / 24.0\n        b = self.dec.sin() * np.sin(ssb_dec)\n        c = self.dec.cos() * np.cos(ssb_dec) * np.cos(self.ra.rad() - ssb_ra)\n\n        return jd - a * (b + c) + ssb_dt / 60.0 / 60.0 / 24.0\n\n    def _bjd_utc(self, x, jd):\n\n        ssb_ra, ssb_dec, ssb_d, ssb_dt = plc_data.barycentre(jd)\n\n        a = ssb_d / 60.0 / 24.0\n        b = self.dec.sin() * np.sin(ssb_dec)\n        c = self.dec.cos() * np.cos(ssb_dec) * np.cos(self.ra.rad() - ssb_ra)\n\n        return jd - a * (b + c)\n\n    def _bjd_tdb(self, x, jd):\n\n        ssb_ra, ssb_dec, ssb_d, ssb_dt = plc_data.barycentre(jd)\n\n        a = ssb_d / 60.0 / 24.0\n        b = self.dec.sin() * np.sin(ssb_dec)\n        c = self.dec.cos() * np.cos(ssb_dec) * np.cos(self.ra.rad() - ssb_ra)\n\n        return jd - a * (b + c) + ssb_dt / 60.0 / 60.0 / 24.0\n\n    def distance_on_sphere(self, other):\n\n        _request_target(other)\n\n        return arccos(self.dec.sin() * other.dec.sin() + self.dec.cos() * other.dec.cos() * (self.ra - other.ra).cos())\n\n    def __str__(self):\n        return 'plc.FixedTarget(RA(hms)/DEC(dms): {0})'.format(self.coord)\n\n    def __repr__(self):\n        return self.__str__()\n\n\ndef _is_target(item):\n    if isinstance(item, FixedTarget):\n        return True\n    else:\n        return False\n\n\ndef _request_target(item):\n    if _is_target(item):\n        pass\n    else:\n        raise PyLCInputError('A plc.Target object is required (plc.FixedTarget)')\n", "meta": {"hexsha": "a9bd4526795b1d8fcca4b69c4d6da278af38e79d", "size": 7210, "ext": "py", "lang": "Python", "max_stars_repo_path": "pylightcurve/spacetime/targets.py", "max_stars_repo_name": "ucl-exoplanets/lightcurve_model", "max_stars_repo_head_hexsha": "a6a6af6df1ed0bf1ed3b5e777082399791e695f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2017-02-27T01:10:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T16:52:50.000Z", "max_issues_repo_path": "pylightcurve/spacetime/targets.py", "max_issues_repo_name": "ucl-exoplanets/lightcurve_model", "max_issues_repo_head_hexsha": "a6a6af6df1ed0bf1ed3b5e777082399791e695f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-02-24T09:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-14T21:21:19.000Z", "max_forks_repo_path": "pylightcurve/spacetime/targets.py", "max_forks_repo_name": "ucl-exoplanets/lightcurve_model", "max_forks_repo_head_hexsha": "a6a6af6df1ed0bf1ed3b5e777082399791e695f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-02-27T01:10:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T23:14:21.000Z", "avg_line_length": 36.7857142857, "max_line_length": 119, "alphanum_fraction": 0.5341192788, "include": true, "reason": "import numpy", "num_tokens": 2077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.29098087851200083, "lm_q1q2_score": 0.15909034778051076}}
{"text": "# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n'''Simulation'''\n\nimport numpy as np\nfrom src.angle import Angle\nfrom src.bd_baro import BD_BARO\nfrom src.bond import Bond\nfrom src.crd_molecular_map import CoordinateMolecularMap\nfrom src.dihedral import Dihedral\nfrom src.langevin_liujian_md import Langevin_Liujian\nfrom src.lennard_jones import Lennard_Jones_Information\nfrom src.mc_baro import MC_BARO\nfrom src.md_information import md_information\nfrom src.nb14 import NON_BOND_14\nfrom src.neighbor_list import neighbor_list\nfrom src.particle_mesh_ewald import Particle_Mesh_Ewald\nfrom src.restrain import Restrain_Information\nfrom src.simple_constrain import Simple_Constarin\nfrom src.vatom import Virtual_Information\n\nimport mindspore.common.dtype as mstype\nfrom mindspore import Tensor, nn\nfrom mindspore.common.parameter import Parameter\nfrom mindspore.ops import functional as F\nfrom mindspore.ops import operations as P\n\n\nclass controller:\n    '''controller'''\n\n    def __init__(self, args_opt):\n        self.input_file = args_opt.i\n        self.initial_coordinates_file = args_opt.c\n        self.amber_parm = args_opt.amber_parm\n        self.restrt = args_opt.r\n        self.mdcrd = args_opt.x\n        self.mdout = args_opt.o\n        self.mdbox = args_opt.box\n\n        self.Command_Set = {}\n        self.md_task = None\n        self.commands_from_in_file()\n        self.punctuation = \",\"\n\n    def commands_from_in_file(self):\n        '''command from in file'''\n        file = open(self.input_file, 'r')\n        context = file.readlines()\n        file.close()\n        self.md_task = context[0].strip()\n        for val in context:\n            val = val.strip()\n            if val and val[0] != '#' and (\"=\" in val):\n                val = val[:val.index(\",\")] if ',' in val else val\n                assert len(val.strip().split(\"=\")) == 2\n                flag, value = val.strip().split(\"=\")\n                value = value.replace(\" \", \"\")\n                flag = flag.replace(\" \", \"\")\n                if flag not in self.Command_Set:\n                    self.Command_Set[flag] = value\n                else:\n                    print(\"ERROR COMMAND FILE\")\n\n\nclass Simulation(nn.Cell):\n    '''simulation'''\n\n    def __init__(self, args_opt):\n        super(Simulation, self).__init__()\n        self.control = controller(args_opt)\n        self.md_info = md_information(self.control)\n        self.mode = self.md_info.mode\n        self.bond = Bond(self.control)\n        self.bond_is_initialized = self.bond.is_initialized\n        self.angle = Angle(self.control)\n        self.angle_is_initialized = self.angle.is_initialized\n        self.dihedral = Dihedral(self.control)\n        self.dihedral_is_initialized = self.dihedral.is_initialized\n        self.nb14 = NON_BOND_14(self.control, self.dihedral, self.md_info.atom_numbers)\n        self.nb14_is_initialized = self.nb14.is_initialized\n        self.nb_info = neighbor_list(self.control, self.md_info.atom_numbers, self.md_info.box_length)\n        self.LJ_info = Lennard_Jones_Information(self.control, self.md_info.nb.cutoff, self.md_info.sys.box_length)\n        self.LJ_info_is_initialized = self.LJ_info.is_initialized\n\n        self.liujian_info = Langevin_Liujian(self.control, self.md_info.atom_numbers)\n        self.liujian_info_is_initialized = self.liujian_info.is_initialized\n        self.pme_method = Particle_Mesh_Ewald(self.control, self.md_info)\n        self.pme_is_initialized = self.pme_method.is_initialized\n        self.restrain = Restrain_Information(self.control, self.md_info.atom_numbers, self.md_info.crd)\n        self.restrain_is_initialized = self.restrain.is_initialized\n        self.simple_constrain_is_initialized = 0\n\n        self.simple_constrain = Simple_Constarin(self.control, self.md_info, self.bond, self.angle, self.liujian_info)\n        self.simple_constrain_is_initialized = self.simple_constrain.is_initialized\n        self.freedom = self.simple_constrain.system_freedom\n\n        self.vatom = Virtual_Information(self.control, self.md_info, self.md_info.sys.freedom)\n        self.vatom_is_initialized = 1\n\n        self.random = P.UniformReal(seed=1)\n        self.pow = P.Pow()\n\n        self.mol_map = CoordinateMolecularMap(self.md_info.atom_numbers, self.md_info.sys.box_length, self.md_info.crd,\n                                              self.md_info.nb.excluded_atom_numbers, self.md_info.nb.h_excluded_numbers,\n                                              self.md_info.nb.h_excluded_list_start, self.md_info.nb.h_excluded_list)\n        self.mol_map_is_initialized = 1\n        self.init_params()\n        self.init_Tensor()\n        self.op_define()\n        self.op_define_2()\n        self.depend = P.Depend()\n        self.print = P.Print()\n        self.total_count = Parameter(Tensor(0, mstype.int32), requires_grad=False)\n        self.accept_count = Parameter(Tensor(0, mstype.int32), requires_grad=False)\n        self.is_molecule_map_output = self.md_info.output.is_molecule_map_output\n        self.target_pressure = self.md_info.sys.target_pressure\n        self.Nx = self.nb_info.Nx\n        self.Ny = self.nb_info.Ny\n        self.Nz = self.nb_info.Nz\n        self.PME_inverse_box_vector = Parameter(Tensor(self.pme_method.PME_inverse_box_vector, mstype.float32),\n                                                requires_grad=False)\n        self.mc_baro_is_initialized = 0\n        self.bd_baro_is_initialized = 0\n\n        if self.mode == 2 and self.control.Command_Set[\"barostat\"] == \"monte_carlo\":\n            self.mc_baro = MC_BARO(self.control, self.md_info.atom_numbers, self.md_info.sys.target_pressure,\n                                   self.md_info.sys.box_length, self.md_info.res.is_initialized, self.md_info.mode)\n            self.mc_baro_is_initialized = self.mc_baro.is_initialized\n            self.update_interval = self.mc_baro.update_interval\n            self.mc_baro_energy_old = Parameter(Tensor(0, mstype.float32), requires_grad=False)\n            self.potential = Parameter(Tensor(0, mstype.float32), requires_grad=False)\n            self.frc_backup = Parameter(Tensor(np.zeros([self.atom_numbers, 3]), mstype.float32), requires_grad=False)\n            self.crd_backup = Parameter(Tensor(np.zeros([self.atom_numbers, 3]), mstype.float32), requires_grad=False)\n            self.crd_scale_factor = Parameter(Tensor(0.0, mstype.float32), requires_grad=False)\n            self.system_reinitializing_count = Parameter(Tensor(0, mstype.int32), requires_grad=False)\n            self.mc_baro_energy_new = Parameter(Tensor(0.0, mstype.float32), requires_grad=False)\n            self.scale_coordinate_by_residue = Parameter(Tensor(0, mstype.float32), requires_grad=False)\n            self.extra_term = Parameter(Tensor(0, mstype.float32), requires_grad=False)\n            self.DeltaV = Parameter(Tensor(0.0, mstype.float32), requires_grad=False)\n            self.target_temperature = self.md_info.sys.target_temperature\n            self.VDevided = Parameter(Tensor(0.0, mstype.float32), requires_grad=False)\n            self.log = P.Log()\n            self.mc_baro_accept_possibility = Parameter(Tensor(0, mstype.float32), requires_grad=False)\n            self.exp = P.Exp()\n            self.mc_baro_newV = self.mc_baro.newV\n            self.mc_baro_V0 = Parameter(Tensor(self.mc_baro.V0, mstype.float32), requires_grad=False)\n            self.mc_baro_newV = self.mc_baro.newV\n            self.check_interval = self.mc_baro.check_interval\n\n        if self.mode == 2 and self.control.Command_Set[\"barostat\"] == \"berendsen\":\n            self.bd_baro = BD_BARO(self.control, self.md_info.sys.target_pressure, self.md_info.sys.box_length,\n                                   self.md_info.mode)\n            self.bd_baro_is_initialized = self.bd_baro.is_initialized\n            self.update_interval = self.bd_baro.update_interval\n            self.pressure = Parameter(Tensor(self.md_info.sys.d_pressure, mstype.float32), requires_grad=False)\n            self.compressibility = self.bd_baro.compressibility\n            self.bd_baro_dt = self.bd_baro.dt\n            self.bd_baro_taup = self.bd_baro.taup\n            self.system_reinitializing_count = Parameter(Tensor(0, mstype.int32), requires_grad=False)\n            self.bd_baro_newV = Parameter(Tensor(self.bd_baro.newV, mstype.float32), requires_grad=False)\n            self.bd_baro_V0 = Parameter(Tensor(self.bd_baro.V0, mstype.float32), requires_grad=False)\n\n    def init_params(self):\n        \"\"\"init_params\"\"\"\n        self.bond_energy_sum = Tensor(0, mstype.int32)\n        self.angle_energy_sum = Tensor(0, mstype.int32)\n        self.dihedral_energy_sum = Tensor(0, mstype.int32)\n        self.nb14_lj_energy_sum = Tensor(0, mstype.int32)\n        self.nb14_cf_energy_sum = Tensor(0, mstype.int32)\n        self.lj_energy_sum = Tensor(0, mstype.int32)\n        self.ee_ene = Tensor(0, mstype.int32)\n        self.total_energy = Tensor(0, mstype.int32)\n        # Init scalar\n        self.ntwx = self.md_info.ntwx\n        self.atom_numbers = self.md_info.atom_numbers\n        self.residue_numbers = self.md_info.residue_numbers\n        self.bond_numbers = self.bond.bond_numbers\n        self.angle_numbers = self.angle.angle_numbers\n        self.dihedral_numbers = self.dihedral.dihedral_numbers\n        self.nb14_numbers = self.nb14.nb14_numbers\n        self.nxy = self.nb_info.Nxy\n        self.grid_numbers = self.nb_info.grid_numbers\n        self.max_atom_in_grid_numbers = self.nb_info.max_atom_in_grid_numbers\n        self.max_neighbor_numbers = self.nb_info.max_neighbor_numbers\n        # self.excluded_atom_numbers = self.nb_info.excluded_atom_numbers\n        self.excluded_atom_numbers = self.md_info.nb.excluded_atom_numbers\n        self.refresh_count = Parameter(Tensor(self.nb_info.refresh_count, mstype.int32), requires_grad=False)\n        self.refresh_interval = self.nb_info.refresh_interval\n        self.skin = self.nb_info.skin\n        self.cutoff = self.nb_info.cutoff\n        self.cutoff_square = self.nb_info.cutoff_square\n        self.cutoff_with_skin = self.nb_info.cutoff_with_skin\n        self.half_cutoff_with_skin = self.nb_info.half_cutoff_with_skin\n        self.cutoff_with_skin_square = self.nb_info.cutoff_with_skin_square\n        self.half_skin_square = self.nb_info.half_skin_square\n        self.beta = self.pme_method.beta\n        self.fftx = self.pme_method.fftx\n        self.ffty = self.pme_method.ffty\n        self.fftz = self.pme_method.fftz\n        self.random_seed = self.liujian_info.random_seed\n        self.dt = self.liujian_info.dt\n        self.half_dt = self.liujian_info.half_dt\n        self.exp_gamma = self.liujian_info.exp_gamma\n        self.update = False\n        self.file = None\n        self.datfile = None\n        self.max_velocity = self.liujian_info.max_velocity\n\n        # bingshui\n        self.CONSTANT_kB = 0.00198716\n\n    def init_Tensor(self):\n        '''init tensor'''\n        # MD_Reset_Atom_Energy_And_Virial\n        self.uint_crd = Parameter(Tensor(np.zeros([self.atom_numbers, 3], dtype=np.uint32), mstype.uint32),\n                                  requires_grad=False)\n        self.need_potential = Tensor(0, mstype.int32)\n        self.need_pressure = Tensor(0, mstype.int32)\n        # self.potential = Tensor(0, mstype.float32)\n        self.atom_energy = Parameter(Tensor([0] * self.atom_numbers, mstype.float32), requires_grad=False)\n        self.atom_virial = Parameter(Tensor([0] * self.atom_numbers, mstype.float32), requires_grad=False)\n        self.frc = Parameter(Tensor(np.zeros([self.atom_numbers, 3]), mstype.float32), requires_grad=False)\n\n        self.crd = Parameter(\n            Tensor(np.array(self.md_info.coordinate).reshape([self.atom_numbers, 3]), mstype.float32),\n            requires_grad=False)\n        self.crd_to_uint_crd_cof = Tensor(np.asarray(self.md_info.pbc.crd_to_uint_crd_cof, np.float32), mstype.float32)\n        self.quarter_crd_to_uint_crd_cof = Tensor(np.asarray(self.md_info.pbc.quarter_crd_to_uint_crd_cof, np.float32),\n                                                  mstype.float32)\n\n        self.uint_dr_to_dr_cof = Parameter(Tensor(self.md_info.pbc.uint_dr_to_dr_cof, mstype.float32),\n                                           requires_grad=False)\n        self.box_length = Tensor(self.md_info.box_length, mstype.float32)\n        self.charge = Parameter(Tensor(np.asarray(self.md_info.h_charge, dtype=np.float32), mstype.float32),\n                                requires_grad=False)\n        self.old_crd = Parameter(Tensor(np.zeros([self.atom_numbers, 3], dtype=np.float32), mstype.float32),\n                                 requires_grad=False)\n        self.last_crd = Parameter(Tensor(np.zeros([self.atom_numbers, 3], dtype=np.float32), mstype.float32),\n                                  requires_grad=False)\n        self.mass = Tensor(self.md_info.h_mass, mstype.float32)\n        self.mass_inverse = Tensor(self.md_info.h_mass_inverse, mstype.float32)\n        self.res_mass = Tensor(self.md_info.res.h_mass, mstype.float32)\n        self.res_mass_inverse = Tensor(self.md_info.res.h_mass_inverse, mstype.float32)\n\n        self.res_start = Tensor(self.md_info.h_res_start, mstype.int32)\n        self.res_end = Tensor(self.md_info.h_res_end, mstype.int32)\n        self.velocity = Parameter(Tensor(self.md_info.velocity, mstype.float32), requires_grad=False)\n        self.acc = Parameter(Tensor(np.zeros([self.atom_numbers, 3], np.float32), mstype.float32), requires_grad=False)\n        self.bond_atom_a = Tensor(np.asarray(self.bond.h_atom_a, np.int32), mstype.int32)\n        self.bond_atom_b = Tensor(np.asarray(self.bond.h_atom_b, np.int32), mstype.int32)\n        self.bond_k = Tensor(np.asarray(self.bond.h_k, np.float32), mstype.float32)\n        self.bond_r0 = Tensor(np.asarray(self.bond.h_r0, np.float32), mstype.float32)\n        self.angle_atom_a = Tensor(np.asarray(self.angle.h_atom_a, np.int32), mstype.int32)\n        self.angle_atom_b = Tensor(np.asarray(self.angle.h_atom_b, np.int32), mstype.int32)\n        self.angle_atom_c = Tensor(np.asarray(self.angle.h_atom_c, np.int32), mstype.int32)\n        self.angle_k = Tensor(np.asarray(self.angle.h_angle_k, np.float32), mstype.float32)\n        self.angle_theta0 = Tensor(np.asarray(self.angle.h_angle_theta0, np.float32), mstype.float32)\n        self.dihedral_atom_a = Tensor(np.asarray(self.dihedral.h_atom_a, np.int32), mstype.int32)\n        self.dihedral_atom_b = Tensor(np.asarray(self.dihedral.h_atom_b, np.int32), mstype.int32)\n        self.dihedral_atom_c = Tensor(np.asarray(self.dihedral.h_atom_c, np.int32), mstype.int32)\n        self.dihedral_atom_d = Tensor(np.asarray(self.dihedral.h_atom_d, np.int32), mstype.int32)\n        self.pk = Tensor(np.asarray(self.dihedral.h_pk, np.float32), mstype.float32)\n        self.gamc = Tensor(np.asarray(self.dihedral.h_gamc, np.float32), mstype.float32)\n        self.gams = Tensor(np.asarray(self.dihedral.h_gams, np.float32), mstype.float32)\n        self.pn = Tensor(np.asarray(self.dihedral.h_pn, np.float32), mstype.float32)\n        self.ipn = Tensor(np.asarray(self.dihedral.h_ipn, np.int32), mstype.int32)\n        self.nb14_atom_a = Tensor(np.asarray(self.nb14.h_atom_a, np.int32), mstype.int32)\n        self.nb14_atom_b = Tensor(np.asarray(self.nb14.h_atom_b, np.int32), mstype.int32)\n        self.lj_scale_factor = Tensor(np.asarray(self.nb14.h_lj_scale_factor, np.float32), mstype.float32)\n        self.cf_scale_factor = Tensor(np.asarray(self.nb14.h_cf_scale_factor, np.float32), mstype.float32)\n        self.grid_N = Tensor(self.nb_info.grid_N, mstype.int32)\n        self.grid_length = Parameter(Tensor(self.nb_info.grid_length, mstype.float32), requires_grad=False)\n        self.grid_length_inverse = Parameter(Tensor(self.nb_info.grid_length_inverse, mstype.float32),\n                                             requires_grad=False)\n        self.bucket = Parameter(Tensor(\n            np.asarray(self.nb_info.bucket, np.int32).reshape([self.grid_numbers, self.max_atom_in_grid_numbers]),\n            mstype.int32), requires_grad=False)\n        self.atom_numbers_in_grid_bucket = Parameter(Tensor(self.nb_info.atom_numbers_in_grid_bucket, mstype.int32),\n                                                     requires_grad=False)\n        self.atom_in_grid_serial = Parameter(Tensor(np.zeros([self.nb_info.atom_numbers,], np.int32), mstype.int32),\n                                             requires_grad=False)\n        self.pointer = Parameter(\n            Tensor(np.asarray(self.nb_info.pointer, np.int32).reshape([self.grid_numbers, 125]), mstype.int32),\n            requires_grad=False)\n        self.nl_atom_numbers = Parameter(Tensor(np.zeros([self.atom_numbers,], np.int32), mstype.int32),\n                                         requires_grad=False)\n        self.nl_atom_serial = Parameter(\n            Tensor(np.zeros([self.atom_numbers, self.max_neighbor_numbers], np.int32), mstype.int32),\n            requires_grad=False)\n        self.excluded_list_start = Tensor(np.asarray(self.md_info.nb.h_excluded_list_start, np.int32), mstype.int32)\n        self.excluded_list = Tensor(np.asarray(self.md_info.nb.h_excluded_list, np.int32), mstype.int32)\n        self.excluded_numbers = Tensor(np.asarray(self.md_info.nb.h_excluded_numbers, np.int32), mstype.int32)\n\n        self.need_refresh_flag = Tensor(np.asarray([0], np.int32), mstype.int32)\n        self.atom_LJ_type = Tensor(self.LJ_info.atom_LJ_type, mstype.int32)\n        self.LJ_A = Tensor(self.LJ_info.h_LJ_A, mstype.float32)\n        self.LJ_B = Tensor(self.LJ_info.h_LJ_B, mstype.float32)\n        self.sqrt_mass = Tensor(self.liujian_info.h_sqrt_mass, mstype.float32)\n        self.rand_state = Parameter(Tensor(self.liujian_info.rand_state, mstype.float32))\n        self.zero_fp_tensor = Tensor(np.asarray([0,], np.float32))\n        self.zero_frc = Parameter(Tensor(np.zeros([self.atom_numbers, 3], dtype=np.float32), mstype.float32),\n                                  requires_grad=False)\n\n    def op_define(self):\n        '''op define'''\n        self.crd_to_uint_crd = P.CrdToUintCrd(self.atom_numbers)\n        self.crd_to_uint_crd_quarter = P.CrdToUintCrdQuarter(self.atom_numbers)\n        self.mdtemp = P.MDTemperature(self.residue_numbers, self.atom_numbers)\n        self.setup_random_state = P.MDIterationSetupRandState(self.atom_numbers, self.random_seed)\n\n        self.bond_force_with_atom_energy_virial = P.BondForceWithAtomEnergyAndVirial(bond_numbers=self.bond_numbers,\n                                                                                     atom_numbers=self.atom_numbers)\n        self.angle_force_with_atom_energy = P.AngleForceWithAtomEnergy(angle_numbers=self.angle_numbers)\n        self.dihedral_force_with_atom_energy = P.DihedralForceWithAtomEnergy(dihedral_numbers=self.dihedral_numbers)\n        self.nb14_force_with_atom_energy = P.Dihedral14LJCFForceWithAtomEnergy(nb14_numbers=self.nb14_numbers,\n                                                                               atom_numbers=self.atom_numbers)\n        self.lj_force_pme_direct_force = P.LJForceWithPMEDirectForce(self.atom_numbers, self.cutoff, self.beta)\n        self.pme_excluded_force = P.PMEExcludedForce(atom_numbers=self.atom_numbers,\n                                                     excluded_numbers=self.excluded_atom_numbers, beta=self.beta)\n        self.pme_reciprocal_force = P.PMEReciprocalForce(self.atom_numbers, self.beta, self.fftx, self.ffty, self.fftz,\n                                                         self.md_info.box_length[0], self.md_info.box_length[1],\n                                                         self.md_info.box_length[2])\n        self.bond_energy = P.BondEnergy(self.bond_numbers, self.atom_numbers)\n        self.angle_energy = P.AngleEnergy(self.angle_numbers)\n        self.dihedral_energy = P.DihedralEnergy(self.dihedral_numbers)\n        self.nb14_lj_energy = P.Dihedral14LJEnergy(self.nb14_numbers, self.atom_numbers)\n        self.nb14_cf_energy = P.Dihedral14CFEnergy(self.nb14_numbers, self.atom_numbers)\n        self.lj_energy = P.LJEnergy(self.atom_numbers, self.cutoff_square)\n        self.pme_energy = P.PMEEnergy(self.atom_numbers, self.excluded_atom_numbers, self.beta, self.fftx, self.ffty,\n                                      self.fftz, self.md_info.box_length[0], self.md_info.box_length[1],\n                                      self.md_info.box_length[2])\n        self.md_iteration_leap_frog_liujian = P.MDIterationLeapFrogLiujian(self.atom_numbers, self.half_dt, self.dt,\n                                                                           self.exp_gamma)\n\n        self.md_iteration_leap_frog_liujian_with_max_vel = P.MDIterationLeapFrogLiujianWithMaxVel(self.atom_numbers,\n                                                                                                  self.half_dt, self.dt,\n                                                                                                  self.exp_gamma,\n                                                                                                  self.max_velocity)\n        self.neighbor_list_update = \\\n            P.NeighborListUpdate(grid_numbers=self.grid_numbers,\n                                 atom_numbers=self.atom_numbers,\n                                 not_first_time=1, nxy=self.nxy,\n                                 excluded_atom_numbers=self.excluded_atom_numbers,\n                                 cutoff_square=self.cutoff_square,\n                                 half_skin_square=self.half_skin_square,\n                                 cutoff_with_skin=self.cutoff_with_skin,\n                                 half_cutoff_with_skin=self.half_cutoff_with_skin,\n                                 cutoff_with_skin_square=self.cutoff_with_skin_square,\n                                 refresh_interval=self.refresh_interval, cutoff=self.cutoff,\n                                 skin=self.skin,\n                                 max_atom_in_grid_numbers=self.max_atom_in_grid_numbers,\n                                 max_neighbor_numbers=self.max_neighbor_numbers)\n\n        self.neighbor_list_update_forced_update = \\\n            P.NeighborListUpdate(grid_numbers=self.grid_numbers,\n                                 atom_numbers=self.atom_numbers,\n                                 not_first_time=1, nxy=self.nxy,\n                                 excluded_atom_numbers=self.excluded_atom_numbers,\n                                 cutoff_square=self.cutoff_square,\n                                 half_skin_square=self.half_skin_square,\n                                 cutoff_with_skin=self.cutoff_with_skin,\n                                 half_cutoff_with_skin=self.half_cutoff_with_skin,\n                                 cutoff_with_skin_square=self.cutoff_with_skin_square,\n                                 refresh_interval=self.refresh_interval,\n                                 cutoff=self.cutoff,\n                                 skin=self.skin,\n                                 max_atom_in_grid_numbers=self.max_atom_in_grid_numbers,\n                                 max_neighbor_numbers=self.max_neighbor_numbers,\n                                 forced_update=1)\n\n        self.neighbor_list_update_nb = \\\n            P.NeighborListUpdate(grid_numbers=self.grid_numbers,\n                                 atom_numbers=self.atom_numbers,\n                                 not_first_time=1, nxy=self.nxy,\n                                 excluded_atom_numbers=self.excluded_atom_numbers,\n                                 cutoff_square=self.cutoff_square,\n                                 half_skin_square=self.half_skin_square,\n                                 cutoff_with_skin=self.cutoff_with_skin,\n                                 half_cutoff_with_skin=self.half_cutoff_with_skin,\n                                 cutoff_with_skin_square=self.cutoff_with_skin_square,\n                                 refresh_interval=self.refresh_interval,\n                                 cutoff=self.cutoff,\n                                 skin=self.skin,\n                                 max_atom_in_grid_numbers=self.max_atom_in_grid_numbers,\n                                 max_neighbor_numbers=self.max_neighbor_numbers,\n                                 forced_update=1, forced_check=1)\n\n    def op_define_2(self):\n        \"\"\"op_define_2\"\"\"\n        self.neighbor_list_update_mc = P.NeighborListUpdate(grid_numbers=self.grid_numbers,\n                                                            atom_numbers=self.atom_numbers,\n                                                            not_first_time=1, nxy=self.nxy,\n                                                            excluded_atom_numbers=self.excluded_atom_numbers,\n                                                            cutoff_square=self.cutoff_square,\n                                                            half_skin_square=self.half_skin_square,\n                                                            cutoff_with_skin=self.cutoff_with_skin,\n                                                            half_cutoff_with_skin=self.half_cutoff_with_skin,\n                                                            cutoff_with_skin_square=self.cutoff_with_skin_square,\n                                                            refresh_interval=self.refresh_interval,\n                                                            cutoff=self.cutoff,\n                                                            skin=self.skin,\n                                                            max_atom_in_grid_numbers=self.max_atom_in_grid_numbers,\n                                                            max_neighbor_numbers=self.max_neighbor_numbers,\n                                                            forced_update=0, forced_check=1)\n\n        self.random_force = Tensor(np.zeros([self.atom_numbers, 3], np.float32), mstype.float32)\n\n        # simple_constrain\n        self.constrain_pair_numbers = self.simple_constrain.constrain_pair_numbers\n        self.last_pair_dr = Parameter(Tensor(np.zeros([self.constrain_pair_numbers, 3], np.float32), mstype.float32),\n                                      requires_grad=False)\n        if self.simple_constrain_is_initialized:\n            self.constrain_pair_numbers = self.simple_constrain.constrain_pair_numbers\n            self.last_crd_to_dr = P.lastcrdtodr(self.atom_numbers, self.constrain_pair_numbers)\n            self.constrain_pair = np.array(self.simple_constrain.h_constrain_pair)\n            self.atom_i_serials = Tensor(self.constrain_pair[:, 0], mstype.int32)\n            self.atom_j_serials = Tensor(self.constrain_pair[:, 1], mstype.int32)\n            self.constant_rs = Tensor(self.constrain_pair[:, 2], mstype.float32)\n            self.constrain_ks = Tensor(self.constrain_pair[:, 3], mstype.float32)\n            self.last_pair_dr = Parameter(\n                Tensor(np.zeros([self.constrain_pair_numbers, 3], np.float32), mstype.float32), requires_grad=False)\n            self.constrain_frc = Parameter(Tensor(np.zeros([self.atom_numbers, 3], np.float32), mstype.float32),\n                                           requires_grad=False)\n            self.iteration_numbers = self.simple_constrain.info.iteration_numbers\n            self.half_exp_gamma_plus_half = self.simple_constrain.half_exp_gamma_plus_half\n            self.refresh_uint_crd = P.refreshuintcrd(self.atom_numbers, self.half_exp_gamma_plus_half)\n            self.need_pressure = 0\n            self.constrain_force_cycle_with_virial = P.constrainforcecyclewithvirial(self.atom_numbers,\n                                                                                     self.constrain_pair_numbers)\n            self.constrain_force_cycle = P.ConstrainForceCycle(self.atom_numbers, self.constrain_pair_numbers)\n            self.dt_inverse = self.simple_constrain.dt_inverse\n            self.refresh_crd_vel = P.refreshcrdvel(self.atom_numbers, self.dt_inverse, self.dt, self.exp_gamma,\n                                                   self.half_exp_gamma_plus_half)\n\n        if self.mol_map_is_initialized:\n            self.refresh_boxmaptimes = P.refreshboxmaptimes(self.atom_numbers)\n            self.box_map_times = Parameter(Tensor(self.mol_map.h_box_map_times, mstype.int32), requires_grad=False)\n        self.residue_numbers = self.md_info.residue_numbers\n        self.getcenterofmass = P.GetCenterOfMass(self.residue_numbers)\n        self.mapcenterofmass = P.MapCenterOfMass(self.residue_numbers, scaler=1.0)\n\n        self.md_iteration_leap_frog = P.MDIterationLeapFrog(self.atom_numbers, self.dt)\n        self.md_iteration_leap_frog_with_max_vel = P.MDIterationLeapFrogWithMaxVel(self.atom_numbers, self.dt,\n                                                                                   self.max_velocity)\n        self.md_information_gradient_descent = P.MDIterationGradientDescent(self.atom_numbers, self.dt * self.dt)\n\n    def Simulation_Beforce_Caculate_Force(self):\n        '''simulation before calculate force'''\n        self.uint_crd = self.crd_to_uint_crd_quarter(self.quarter_crd_to_uint_crd_cof, self.crd)\n        return self.uint_crd\n\n    def Simulation_Caculate_Force(self, uint_crd, scaler, nl_atom_numbers, nl_atom_serial):\n        '''simulation calculate force'''\n        uint_crd = self.Simulation_Beforce_Caculate_Force()\n        force = self.zero_frc\n        if self.LJ_info_is_initialized:\n            lj_force = self.lj_force_pme_direct_force(uint_crd, self.atom_LJ_type, self.charge, scaler, nl_atom_numbers,\n                                                      nl_atom_serial, self.LJ_A, self.LJ_B)\n            force = force + lj_force\n\n        if self.pme_is_initialized:\n            pme_excluded_force = self.pme_excluded_force(uint_crd, scaler, self.charge, self.excluded_list_start,\n                                                         self.excluded_list, self.excluded_numbers)\n\n            pme_reciprocal_force = self.pme_reciprocal_force(uint_crd, self.charge)\n            force = force + pme_excluded_force + pme_reciprocal_force\n        if self.nb14_is_initialized:\n            nb14_force, _ = self.nb14_force_with_atom_energy(uint_crd, self.atom_LJ_type, self.charge,\n                                                             scaler, self.nb14_atom_a, self.nb14_atom_b,\n                                                             self.lj_scale_factor, self.cf_scale_factor,\n                                                             self.LJ_A, self.LJ_B)\n            force = force + nb14_force\n\n        if self.bond_is_initialized:\n            bond_force, _, _ = self.bond_force_with_atom_energy_virial(uint_crd, scaler, self.bond_atom_a,\n                                                                       self.bond_atom_b, self.bond_k, self.bond_r0)\n            force = force + bond_force\n        if self.angle_is_initialized:\n            angle_force, _ = self.angle_force_with_atom_energy(uint_crd, scaler, self.angle_atom_a,\n                                                               self.angle_atom_b, self.angle_atom_c,\n                                                               self.angle_k, self.angle_theta0)\n            force = force + angle_force\n        if self.dihedral_is_initialized:\n            dihedral_force, _ = self.dihedral_force_with_atom_energy(uint_crd, scaler,\n                                                                     self.dihedral_atom_a,\n                                                                     self.dihedral_atom_b,\n                                                                     self.dihedral_atom_c,\n                                                                     self.dihedral_atom_d, self.ipn,\n                                                                     self.pk, self.gamc, self.gams,\n                                                                     self.pn)\n            force = force + dihedral_force\n\n        if self.restrain_is_initialized:\n            _, _, restrain_frc = self.restrain_force_with_atom_energy_and_virial(self.restrain_list,\n                                                                                 self.crd,\n                                                                                 self.crd_ref,\n                                                                                 self.box_length)\n            force = force + restrain_frc\n\n        return force\n\n    def Simulation_Caculate_Energy(self, uint_crd, uint_dr_to_dr_cof):\n        '''simulation calculate energy'''\n\n        lj_energy = self.lj_energy(uint_crd, self.atom_LJ_type, self.charge, uint_dr_to_dr_cof, self.nl_atom_numbers,\n                                   self.nl_atom_serial, self.LJ_A, self.LJ_B)\n\n        lj_energy_sum = P.ReduceSum(True)(lj_energy)\n        # lj_energy_sum = self.zero_fp_tensor\n\n        reciprocal_energy, self_energy, direct_energy, correction_energy = self.pme_energy(uint_crd, self.charge,\n                                                                                           self.nl_atom_numbers,\n                                                                                           self.nl_atom_serial,\n                                                                                           uint_dr_to_dr_cof,\n                                                                                           self.excluded_list_start,\n                                                                                           self.excluded_list,\n                                                                                           self.excluded_numbers)\n        ee_ene = reciprocal_energy + self_energy + direct_energy + correction_energy\n        # ee_ene = self.zero_fp_tensor\n\n        nb14_lj_energy = self.nb14_lj_energy(uint_crd, self.atom_LJ_type, self.charge, uint_dr_to_dr_cof,\n                                             self.nb14_atom_a, self.nb14_atom_b, self.lj_scale_factor, self.LJ_A,\n                                             self.LJ_B)\n        nb14_cf_energy = self.nb14_cf_energy(uint_crd, self.atom_LJ_type, self.charge, uint_dr_to_dr_cof,\n                                             self.nb14_atom_a, self.nb14_atom_b, self.cf_scale_factor)\n        nb14_lj_energy_sum = P.ReduceSum(True)(nb14_lj_energy)\n        nb14_cf_energy_sum = P.ReduceSum(True)(nb14_cf_energy)\n        # nb14_lj_energy_sum = self.zero_fp_tensor\n        # nb14_cf_energy_sum = self.zero_fp_tensor\n        bond_energy = self.bond_energy(uint_crd, uint_dr_to_dr_cof, self.bond_atom_a, self.bond_atom_b, self.bond_k,\n                                       self.bond_r0)\n        bond_energy_sum = P.ReduceSum(True)(bond_energy)\n\n        angle_energy = self.angle_energy(uint_crd, uint_dr_to_dr_cof, self.angle_atom_a, self.angle_atom_b,\n                                         self.angle_atom_c, self.angle_k, self.angle_theta0)\n        angle_energy_sum = P.ReduceSum(True)(angle_energy)\n\n        dihedral_energy = self.dihedral_energy(uint_crd, uint_dr_to_dr_cof, self.dihedral_atom_a, self.dihedral_atom_b,\n                                               self.dihedral_atom_c, self.dihedral_atom_d, self.ipn, self.pk, self.gamc,\n                                               self.gams, self.pn)\n        dihedral_energy_sum = P.ReduceSum(True)(dihedral_energy)\n\n        total_energy = P.AddN()(\n            [bond_energy_sum, angle_energy_sum, dihedral_energy_sum, nb14_lj_energy_sum, nb14_cf_energy_sum,\n             lj_energy_sum, ee_ene])\n        return bond_energy_sum, angle_energy_sum, dihedral_energy_sum, nb14_lj_energy_sum, nb14_cf_energy_sum, \\\n               lj_energy_sum, ee_ene, total_energy\n\n    def Simulation_Temperature(self):\n        \"\"\"calculate temperature\"\"\"\n        res_ek_energy = self.mdtemp(self.res_start, self.res_end, self.velocity, self.mass)\n        temperature = P.ReduceSum()(res_ek_energy)\n        return temperature\n\n    def Simulation_MDIterationLeapFrog_Liujian(self, inverse_mass, sqrt_mass_inverse, crd, frc, rand_state, random_frc):\n        '''simulation leap frog iteration liujian'''\n        if self.max_velocity <= 0:\n            crd = self.md_iteration_leap_frog_liujian(inverse_mass, sqrt_mass_inverse, self.velocity, crd, frc,\n                                                      self.acc,\n                                                      rand_state, random_frc)\n        else:\n            crd = self.md_iteration_leap_frog_liujian_with_max_vel(inverse_mass, sqrt_mass_inverse, self.velocity, crd,\n                                                                   frc, self.acc,\n                                                                   rand_state, random_frc)\n        vel = F.depend(self.velocity, crd)\n        acc = F.depend(self.acc, crd)\n        return vel, crd, acc\n\n    def Simulation_MDIterationLeapFrog(self, force):\n        '''simulation leap frog'''\n        if self.max_velocity <= 0:\n            res = self.md_iteration_leap_frog(self.velocity, self.crd, force, self.acc, self.mass_inverse)\n        else:\n            res = self.md_iteration_leap_frog_with_max_vel(self.velocity, self.crd, force, self.acc, self.mass_inverse)\n        vel = F.depend(self.velocity, res)\n        crd = F.depend(self.crd, res)\n        return vel, crd, res\n\n    def Simulation_MDInformationGradientDescent(self, force):\n        # print(\"Simulation_MDInformationGradientDescent\")\n        res = self.md_information_gradient_descent(self.crd, force)\n        self.velocity = self.zero_frc\n        vel = F.depend(self.velocity, res)\n        crd = F.depend(self.crd, res)\n        return vel, crd, res\n\n    def Main_Print(self, *args):\n        \"\"\"compute the temperature\"\"\"\n        steps, temperature, total_potential_energy, sigma_of_bond_ene, sigma_of_angle_ene, sigma_of_dihedral_ene, \\\n        nb14_lj_energy_sum, nb14_cf_energy_sum, LJ_energy_sum, ee_ene = list(args)\n        if steps == 0:\n            print(\"_steps_ _TEMP_ _TOT_POT_ENE_ _BOND_ENE_ \"\n                  \"_ANGLE_ENE_ _DIHEDRAL_ENE_ _14LJ_ENE_ _14CF_ENE_ _LJ_ENE_ _CF_PME_ENE_\")\n\n        temperature = temperature.asnumpy()\n        total_potential_energy = total_potential_energy.asnumpy()\n        print(\"{:>7.0f} {:>7.3f} {:>11.3f}\".format(steps + 1, float(temperature), float(total_potential_energy)),\n              end=\" \")\n        if self.bond.bond_numbers > 0:\n            sigma_of_bond_ene = sigma_of_bond_ene.asnumpy()\n            print(\"{:>10.3f}\".format(float(sigma_of_bond_ene)), end=\" \")\n        if self.angle.angle_numbers > 0:\n            sigma_of_angle_ene = sigma_of_angle_ene.asnumpy()\n            print(\"{:>11.3f}\".format(float(sigma_of_angle_ene)), end=\" \")\n        if self.dihedral.dihedral_numbers > 0:\n            sigma_of_dihedral_ene = sigma_of_dihedral_ene.asnumpy()\n            print(\"{:>14.3f}\".format(float(sigma_of_dihedral_ene)), end=\" \")\n        if self.nb14.nb14_numbers > 0:\n            nb14_lj_energy_sum = nb14_lj_energy_sum.asnumpy()\n            nb14_cf_energy_sum = nb14_cf_energy_sum.asnumpy()\n            print(\"{:>10.3f} {:>10.3f}\".format(float(nb14_lj_energy_sum), float(nb14_cf_energy_sum)), end=\" \")\n        LJ_energy_sum = LJ_energy_sum.asnumpy()\n        ee_ene = ee_ene.asnumpy()\n        print(\"{:>7.3f}\".format(float(LJ_energy_sum)), end=\" \")\n        print(\"{:>12.3f}\".format(float(ee_ene)))\n        if self.file is not None:\n            self.file.write(\"{:>7.0f} {:>7.3f} {:>11.3f} {:>10.3f} {:>11.3f} {:>14.3f} {:>10.3f} {:>10.3f} {:>7.3f}\"\n                            \" {:>12.3f}\\n\".format(steps, float(temperature), float(total_potential_energy),\n                                                  float(sigma_of_bond_ene), float(sigma_of_angle_ene),\n                                                  float(sigma_of_dihedral_ene), float(nb14_lj_energy_sum),\n                                                  float(nb14_cf_energy_sum), float(LJ_energy_sum), float(ee_ene)))\n        if self.datfile is not None:\n            self.datfile.write(self.crd.asnumpy())\n\n    def Main_Initial(self):\n        \"\"\"main initial\"\"\"\n        if self.control.mdout:\n            self.file = open(self.control.mdout, 'w')\n            self.file.write(\"_steps_ _TEMP_ _TOT_POT_ENE_ _BOND_ENE_ \"\n                            \"_ANGLE_ENE_ _DIHEDRAL_ENE_ _14LJ_ENE_ _14CF_ENE_ _LJ_ENE_ _CF_PME_ENE_\\n\")\n        if self.control.mdcrd:\n            self.datfile = open(self.control.mdcrd, 'wb')\n\n    def Main_Destroy(self):\n        \"\"\"main destroy\"\"\"\n        if self.file is not None:\n            self.file.close()\n            print(\"Save .out file successfully!\")\n        if self.datfile is not None:\n            self.datfile.close()\n            print(\"Save .dat file successfully!\")\n\n    # 控压部分代码\n    def Volume_Change_Attempt(self, boxlength, DeltaV_max):\n        \"\"\"Volume_Change_Attempt\"\"\"\n        nrand = self.random((1, 1))\n        DeltaV = nrand * DeltaV_max\n        V = boxlength[0] * boxlength[1] * boxlength[2]\n        # crd_scale_factor = Tensor(np.crbt((V + DeltaV) / V), mstype.float32)\n        crd_scale_factor = self.pow((V + DeltaV) / V, -3)\n        return crd_scale_factor\n\n    def Update_Volume(self, factor):\n        \"\"\"Update_Volume\"\"\"\n        self.CONSTANT_UINT_MAX_FLOAT = 4294967296.0\n        # f_inv = 1.0 / factor\n        self.box_length = factor * self.box_length\n        self.crd_to_uint_crd_cof = self.CONSTANT_UINT_MAX_FLOAT / self.box_length\n        self.quarter_crd_to_uint_crd_cof = 0.25 * self.crd_to_uint_crd_cof\n        self.uint_dr_to_dr_cof = 1.0 / self.crd_to_uint_crd_cof\n        self.uint_crd = self.crd_to_uint_crd_quarter(self.quarter_crd_to_uint_crd_cof, self.crd)\n\n    def Neighbor_List_Update_Volume(self, box_length):\n        \"\"\"Neighbor_List_Update_Volume\"\"\"\n        self.quarter_crd_to_uint_crd_cof = 0.25 * self.CONSTANT_UINT_MAX_FLOAT / box_length\n        self.uint_dr_to_dr_cof = 1.0 / self.CONSTANT_UINT_MAX_FLOAT * box_length\n        self.grid_length[0] = box_length[0] / self.Nx\n        self.grid_length[1] = box_length[1] / self.Ny\n        self.grid_length[2] = box_length[1] / self.Nz\n        self.grid_length_inverse = 1.0 / self.grid_length\n\n    def LJ_Update_Volume(self):\n        \"\"\"main destroy\"\"\"\n        if self.LJ_info_is_initialized:\n            # self.uint_dr_to_dr_cof = 1.0 / self.CONSTANT_UINT_MAX_FLOAT * self.box_length\n            self.volume = self.box_length[0] * self.box_length[1] * self.box_length[2]\n\n    def PME_Update_Volume(self, factor):\n        \"\"\"PME_Update_Volume\"\"\"\n        factor_inverse = 1.0 / factor\n        self.PME_inverse_box_vector[0] = self.fftx / self.box_length[0]\n        self.PME_inverse_box_vector[1] = self.ffty / self.box_length[1]\n        self.PME_inverse_box_vector[2] = self.fftz / self.box_length[2]\n        self.PME_inverse_box_vector = factor_inverse * self.PME_inverse_box_vector\n        self.beta = self.beta * factor\n        # self.PME_BC = self.PME_BC * factor_inverse #scale list\n        self.neutralizing_factor = self.pow(factor, 5.0)\n\n    def Simple_Constrain_Update_Volume(self):\n        \"\"\"Simple_Constrain_Update_Volume\"\"\"\n        if self.simple_constrain_is_initialized:\n            self.quarter_crd_to_uint_crd_cof = 0.25 * self.CONSTANT_UINT_MAX_FLOAT / self.box_length\n            self.uint_dr_to_dr_cof = 1.0 / self.CONSTANT_UINT_MAX_FLOAT * self.box_length\n            self.volume = self.box_length[0] * self.box_length[1] * self.box_length[2]\n\n    def Main_Volume_Change(self, factor):\n        \"\"\"Main_Volume_Change\"\"\"\n        self.Update_Volume(factor)\n        self.Neighbor_List_Update_Volume(self.box_length)\n        _ = self.neighbor_list_update_nb(self.atom_numbers_in_grid_bucket, self.bucket,\n                                         self.crd, self.box_length, self.grid_N,\n                                         self.grid_length_inverse, self.atom_in_grid_serial,\n                                         self.old_crd, self.crd_to_uint_crd_cof, self.uint_crd,\n                                         self.pointer, self.nl_atom_numbers, self.nl_atom_serial,\n                                         self.uint_dr_to_dr_cof, self.excluded_list_start, self.excluded_list,\n                                         self.excluded_numbers, self.need_refresh_flag, self.refresh_count)  # Done\n        self.LJ_Update_Volume()\n        self.PME_Update_Volume(factor)\n        self.Simple_Constrain_Update_Volume()\n        # self.mol_map.Update_Volume(self.md_info.sys.box_length)\n\n    def Main_Volume_Change_Largely(self):\n        \"\"\"Main_Volume_Change_Largely\"\"\"\n        # re-initialize neighbor_list and pme\n        _ = self.neighbor_list_update_forced_update(self.atom_numbers_in_grid_bucket, self.bucket,\n                                                    self.crd, self.box_length, self.grid_N,\n                                                    self.grid_length_inverse, self.atom_in_grid_serial,\n                                                    self.old_crd, self.crd_to_uint_crd_cof, self.uint_crd,\n                                                    self.pointer, self.nl_atom_numbers, self.nl_atom_serial,\n                                                    self.uint_dr_to_dr_cof, self.excluded_list_start,\n                                                    self.excluded_list,\n                                                    self.excluded_numbers, self.need_refresh_flag,\n                                                    self.refresh_count)\n\n    def Check_MC_Barostat_Accept(self):\n        \"\"\"Check_MC_Barostat_Accept\"\"\"\n        self.total_count = self.total_count + 1\n        rand_num = self.random((1, 1))\n        if rand_num[0] < self.mc_baro_accept_possibility:\n            self.reject = 0\n            self.accept_count += 1\n        else:\n            self.reject = 1\n        return self.reject\n\n    def Delta_V_Max_Update(self):\n        \"\"\"Delta_V_Max_Update\"\"\"\n        if self.total_count % self.check_interval == 0:\n            self.accept_rate = 100.0 * self.accept_count / self.total_count\n            if self.accept_rate < self.accept_rate_low:\n                self.total_count = 0\n                self.accept_count = 0\n                self.DeltaV_max = self.DeltaV_max * 0.9\n            if self.accept_rate > self.accept_rate_high:\n                self.total_count = 0\n                self.accept_count = 0\n                self.DeltaV_max = self.DeltaV_max * 1.1\n\n    def Main_iteration_presssure(self, steps, force):\n        \"\"\"Main_iteration_presssure\"\"\"\n        if self.mc_baro_is_initialized and steps % self.mc_baro.update_interval == 0:\n            # old energy\n            self.mc_baro_energy_old = self.potential\n            self.frc_backup = self.frc\n            self.crd_backup = self.crd\n            self.Volume_Change_Attempt(self.box_length, 200)\n\n            # change coordinates\n            if self.is_molecule_map_output:\n                nowrap_crd = self.Calculate_No_Wrap_Crd()\n                self.crd, _ = self.Residue_Crd_Map(nowrap_crd)\n                _ = self.refresh_boxmaptimes(self.crd, self.old_crd, 1.0 / self.box_length, self.box_map_times)\n            else:\n                self.crd = self.crd * self.crd_scale_factor  # scale list\n\n            # change volume\n            self.Main_Volume_Change(self.crd_scale_factor)\n            self.system_reinitializing_count += 1\n\n            # new energy\n            _ = self.Simulation_Caculate_Force(self.uint_crd, self.uint_dr_to_dr_cof, self.nl_atom_numbers,\n                                               self.nl_atom_serial)\n\n            self.energy_new = self.potential\n\n            # calculate accepted rate\n            if self.scale_coordinate_by_residue:\n                self.extra_term = self.target_pressure * self.DeltaV - \\\n                                  self.residue_numbers * self.CONSTANT_kB * \\\n                                  self.target_temperature * self.log(self.VDevided)\n            else:\n                self.extra_term = self.target_pressure * self.DeltaV - \\\n                                  self.atom_numbers * self.CONSTANT_kB * \\\n                                  self.target_temperature * self.log(self.VDevided)\n\n            self.mc_baro_accept_possibility = self.mc_baro_energy_new - self.mc_baro_energy_old + self.extra_term\n            self.mc_baro.mc_baro_accept_possibility = self.exp(\n                -self.mc_baro_accept_possibility / (self.CONSTANT_kB * self.target_temperature))\n\n            # check if accepted\n            if self.Check_MC_Barostat_Accept():\n                # if accept, refresh\n                self.crd_scale_factor = 1.0 / self.crd_scale_factor\n                self.crd = self.crd_backup\n                self.Main_Volume_Change(self.crd_scale_factor)\n                self.system_reinitializing_count += 1\n                _ = self.neighbor_list_update_mc(self.atom_numbers_in_grid_bucket, self.bucket,\n                                                 self.crd, self.box_length, self.grid_N,\n                                                 self.grid_length_inverse, self.atom_in_grid_serial,\n                                                 self.old_crd, self.crd_to_uint_crd_cof, self.uint_crd,\n                                                 self.pointer, self.nl_atom_numbers, self.nl_atom_serial,\n                                                 self.uint_dr_to_dr_cof, self.excluded_list_start, self.excluded_list,\n                                                 self.excluded_numbers, self.need_refresh_flag,\n                                                 self.refresh_count)\n                self.frc = force\n                self.frc = self.frc_backup\n\n            # reinitialized\n            if self.system_reinitializing_count >= 20000 or (not self.reject and (\n                    self.mc_baro_newV > 1.331 * self.mc_baro_V0 or self.mc_baro_newV < 0.729 * self.mc_baro.V0)):\n                self.Main_Volume_Change_Largely()\n                self.mc_baro_V0 = self.mc_baro_newV\n                self.system_reinitializing_count = self.zero_fp_tensor\n            self.Delta_V_Max_Update()\n\n    def Constrain(self):\n        \"\"\"Constrain\"\"\"\n        constrain_frc = self.zero_frc\n        for _ in range(self.iteration_numbers):\n            test_uint_crd = self.refresh_uint_crd(self.crd, self.quarter_crd_to_uint_crd_cof, constrain_frc,\n                                                  self.mass_inverse)\n            if self.need_pressure:\n                force, _ = self.constrain_force_cycle_with_virial(test_uint_crd, self.uint_dr_to_dr_cof,\n                                                                  self.last_pair_dr, self.atom_i_serials,\n                                                                  self.atom_j_serials, self.constant_rs,\n                                                                  self.constrain_ks)\n            else:\n                force = self.constrain_force_cycle(test_uint_crd, self.uint_dr_to_dr_cof, self.last_pair_dr,\n                                                   self.atom_i_serials,\n                                                   self.atom_j_serials, self.constant_rs, self.constrain_ks)\n            constrain_frc = constrain_frc + force\n\n        res = self.refresh_crd_vel(self.crd, self.velocity, constrain_frc, self.mass_inverse)\n        crd = self.depend(self.crd, res)\n        vel = self.depend(self.velocity, res)\n\n        return crd, vel, res\n\n    def Main_Iteration(self, steps, force):\n        '''Main_Iteration'''\n        # self.Main_iteration_presssure(steps, force)\n        # Remember_Last_Coordinates\n        # pressure control 1\n        if self.simple_constrain_is_initialized:\n            self.last_pair_dr = self.last_crd_to_dr(self.crd, self.quarter_crd_to_uint_crd_cof, self.uint_dr_to_dr_cof,\n                                                    self.atom_i_serials,\n                                                    self.atom_j_serials, self.constant_rs, self.constrain_ks)\n\n        if self.mode == 0:  # NVE\n            self.velocity, self.crd, _ = self.Simulation_MDIterationLeapFrog(force)\n        elif self.mode == -1:  # Minimization\n            _ = self.Simulation_MDInformationGradientDescent(force)\n        else:\n            if self.liujian_info_is_initialized:\n                self.velocity, self.crd, _ = self.Simulation_MDIterationLeapFrog_Liujian(self.mass_inverse,\n                                                                                         self.sqrt_mass, self.crd,\n                                                                                         force,\n                                                                                         self.rand_state,\n                                                                                         self.random_force)\n\n        if self.simple_constrain_is_initialized:\n            self.crd, self.velocity, res1 = self.Constrain()\n        else:\n            res1 = self.zero_fp_tensor\n\n        # MD_Information_Crd_To_Uint_Crd\n        self.uint_crd = self.crd_to_uint_crd_quarter(self.quarter_crd_to_uint_crd_cof, self.crd)\n        res2 = self.neighbor_list_update(self.atom_numbers_in_grid_bucket,\n                                         self.bucket,\n                                         self.crd,\n                                         self.box_length,\n                                         self.grid_N,\n                                         self.grid_length_inverse,\n                                         self.atom_in_grid_serial,\n                                         self.old_crd,\n                                         self.crd_to_uint_crd_cof,\n                                         self.uint_crd,\n                                         self.pointer,\n                                         self.nl_atom_numbers,\n                                         self.nl_atom_serial,\n                                         self.uint_dr_to_dr_cof,\n                                         self.excluded_list_start,\n                                         self.excluded_list,\n                                         self.excluded_numbers,\n                                         self.need_refresh_flag,\n                                         self.refresh_count)\n\n        res3 = self.refresh_boxmaptimes(self.crd, self.old_crd, 1.0 / self.box_length, self.box_map_times)\n\n        return self.velocity, self.crd, res1, res2, res3\n\n    def Calculate_No_Wrap_Crd(self):\n        \"\"\"Calculate_No_Wrap_Crd\"\"\"\n        nowrap_crd = self.box_map_times * self.box_length + self.crd\n        return nowrap_crd\n\n    def Residue_Crd_Map(self, nowrap_crd):\n        \"\"\"Residue_Crd_Map\"\"\"\n        center_of_mass = self.getcenterofmass(self.res_start, self.res_end, nowrap_crd, self.mass,\n                                              self.res_mass_inverse)\n\n        res = self.mapcenterofmass(self.res_start, self.res_end, center_of_mass, self.box_length, nowrap_crd, self.crd)\n\n        return self.crd, res\n\n    def construct(self, step, print_step):\n        '''construct'''\n        # self.last_crd = self.crd\n        if step == 0:\n            res = self.neighbor_list_update_forced_update(self.atom_numbers_in_grid_bucket,\n                                                          self.bucket,\n                                                          self.crd,\n                                                          self.box_length,\n                                                          self.grid_N,\n                                                          self.grid_length_inverse,\n                                                          self.atom_in_grid_serial,\n                                                          self.old_crd,\n                                                          self.crd_to_uint_crd_cof,\n                                                          self.uint_crd,\n                                                          self.pointer,\n                                                          self.nl_atom_numbers,\n                                                          self.nl_atom_serial,\n                                                          self.uint_dr_to_dr_cof,\n                                                          self.excluded_list_start,\n                                                          self.excluded_list,\n                                                          self.excluded_numbers,\n                                                          self.need_refresh_flag,\n                                                          self.refresh_count)\n        else:\n            res = self.zero_fp_tensor\n        force = self.Simulation_Caculate_Force(self.uint_crd, self.uint_dr_to_dr_cof, self.nl_atom_numbers,\n                                               self.nl_atom_serial)\n        if step == 0:\n            self.rand_state = self.setup_random_state()\n\n        self.velocity, self.crd, res1, res2, res3 = self.Main_Iteration(step + 1, force)\n        temperature = self.Simulation_Temperature()\n        if print_step == 0:\n            bond_energy_sum, angle_energy_sum, dihedral_energy_sum, nb14_lj_energy_sum, nb14_cf_energy_sum, \\\n            lj_energy_sum, ee_ene, total_energy = self.Simulation_Caculate_Energy(self.uint_crd, self.uint_dr_to_dr_cof)\n        else:\n            bond_energy_sum = self.zero_fp_tensor\n            angle_energy_sum = self.zero_fp_tensor\n            dihedral_energy_sum = self.zero_fp_tensor\n            nb14_lj_energy_sum = self.zero_fp_tensor\n            nb14_cf_energy_sum = self.zero_fp_tensor\n            lj_energy_sum = self.zero_fp_tensor\n            ee_ene = self.zero_fp_tensor\n            total_energy = self.zero_fp_tensor\n        return temperature, total_energy, bond_energy_sum, angle_energy_sum, dihedral_energy_sum, nb14_lj_energy_sum, \\\n               nb14_cf_energy_sum, lj_energy_sum, ee_ene, res, res1, res2, res3\n", "meta": {"hexsha": "e02c844c476e3470a84a61a2feb5ffe85b4fd60c", "size": 58454, "ext": "py", "lang": "Python", "max_stars_repo_path": "model_zoo/research/hpc/sponge/src/simulation.py", "max_stars_repo_name": "LottieWang/mindspore", "max_stars_repo_head_hexsha": "1331c7e432fb691d1cfa625ab7cc7451dcfc7ce0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "model_zoo/research/hpc/sponge/src/simulation.py", "max_issues_repo_name": "LottieWang/mindspore", "max_issues_repo_head_hexsha": "1331c7e432fb691d1cfa625ab7cc7451dcfc7ce0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model_zoo/research/hpc/sponge/src/simulation.py", "max_forks_repo_name": "LottieWang/mindspore", "max_forks_repo_head_hexsha": "1331c7e432fb691d1cfa625ab7cc7451dcfc7ce0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.5740932642, "max_line_length": 120, "alphanum_fraction": 0.5889759469, "include": true, "reason": "import numpy", "num_tokens": 12268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.2909808723634538, "lm_q1q2_score": 0.15909034441886555}}
{"text": "#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.\n\nimport numpy as np\n\nimport paddle\n\n\n__all__ = [\n    \"filter_box\",\n    \"postprocess\",\n    \"bboxes_iou\",\n    \"matrix_iou\",\n    \"adjust_box_anns\",\n    \"xyxy2xywh\",\n    \"xyxy2cxcywh\",\n]\n\n\ndef filter_box(output, scale_range):\n    \"\"\"\n    output: (N, 5+class) shape\n    \"\"\"\n    min_scale, max_scale = scale_range\n    w = output[:, 2] - output[:, 0]\n    h = output[:, 3] - output[:, 1]\n    keep = (w * h > min_scale * min_scale) & (w * h < max_scale * max_scale)\n    return output[keep]\n\ndef nms(boxes, scores, nms_thr):\n    \"\"\"Single class NMS implemented in Numpy.\"\"\"\n    x1 = boxes[:, 0]\n    y1 = boxes[:, 1]\n    x2 = boxes[:, 2]\n    y2 = boxes[:, 3]\n\n    areas = (x2 - x1 + 1) * (y2 - y1 + 1)\n    order = scores.argsort()[::-1]\n\n    keep = []\n    while order.size > 0:\n        i = order[0]\n        keep.append(i)\n        xx1 = np.maximum(x1[i], x1[order[1:]])\n        yy1 = np.maximum(y1[i], y1[order[1:]])\n        xx2 = np.minimum(x2[i], x2[order[1:]])\n        yy2 = np.minimum(y2[i], y2[order[1:]])\n\n        w = np.maximum(0.0, xx2 - xx1 + 1)\n        h = np.maximum(0.0, yy2 - yy1 + 1)\n        inter = w * h\n        ovr = inter / (areas[i] + areas[order[1:]] - inter)\n\n        inds = np.where(ovr <= nms_thr)[0]\n        order = order[inds + 1]\n\n    return keep\n\n\ndef multiclass_nms(boxes, scores, nms_thr, score_thr):\n    \"\"\"Multiclass NMS implemented in Numpy\"\"\"\n    final_dets = []\n\n    num_classes = 81\n    for cls_ind in range(1, num_classes):\n        cls_scores = scores[scores[:, 1] == cls_ind]\n        cls_box = boxes[scores[:, 1] == cls_ind]\n        valid_score_mask = cls_scores[:, 0] > score_thr\n        if valid_score_mask.sum() == 0:\n            continue\n        else:\n            valid_scores = cls_scores[valid_score_mask]\n            valid_boxes = cls_box[valid_score_mask]\n            keep = nms(valid_boxes, valid_scores[:, 0], nms_thr)\n            if len(keep) > 0:\n                dets = np.concatenate([valid_boxes[keep], valid_scores[keep, :]], 1)\n                final_dets.append(dets)\n    if len(final_dets) == 0:\n        return None\n    return np.concatenate(final_dets, 0)\n\n@paddle.no_grad()\ndef postprocess_bk(prediction, num_classes, conf_thre=0.45, nms_thre=0.45):\n    box_corner = paddle.zeros_like(prediction)\n    box_corner[:, :, 0] = prediction[:, :, 0] - prediction[:, :, 2] / 2\n    box_corner[:, :, 1] = prediction[:, :, 1] - prediction[:, :, 3] / 2\n    box_corner[:, :, 2] = prediction[:, :, 0] + prediction[:, :, 2] / 2\n    box_corner[:, :, 3] = prediction[:, :, 1] + prediction[:, :, 3] / 2\n\n\n\n    output = [None for _ in range(len(prediction))]\n    for i, image_pred in enumerate(prediction):\n        if not image_pred.shape[0]:\n            continue\n\n        class_conf = paddle.max(image_pred[:, 5: 5 + num_classes], 1, keepdim=True)\n        class_pred = paddle.argmax(image_pred[:, 5: 5 + num_classes], 1, keepdim=True)\n        conf_mask = (image_pred[:, 4] * class_conf.squeeze() >= conf_thre).squeeze()\n\n        detections = paddle.concat(\n            (image_pred[:, :5].astype('float'), class_conf.astype('float'), class_pred.astype('float')), 1)\n        conf_mask_ind = conf_mask.nonzero()\n        detections = paddle.gather(detections, conf_mask_ind)\n        if not detections.shape[0]:\n            continue\n        detections = detections.numpy()\n\n        score = [(detections[:, 4] * detections[:, 5])[:, None], detections[:, 6][:, None]]\n        score = np.concatenate(score, 1)\n        # print(detections[:, :4], score)\n        # print(\"==============================>\")\n        output = multiclass_nms(\n            detections[:, :4],\n            score,\n            nms_thre,\n            conf_thre\n        )\n\n    # print(output.shape, output)\n\n    del prediction\n    return output\n\n\n@paddle.no_grad()\ndef postprocess(prediction, im_shape, scale_factor, num_classes=80,  conf_thre=0.25, nms_thre=0.45):\n    # box_corner = paddle.zeros_like(prediction)\n    # box_corner[:, :, 0] = prediction[:, :, 0] - prediction[:, :, 2] / 2\n    # box_corner[:, :, 1] = prediction[:, :, 1] - prediction[:, :, 3] / 2\n    # box_corner[:, :, 2] = prediction[:, :, 0] + prediction[:, :, 2] / 2\n    # box_corner[:, :, 3] = prediction[:, :, 1] + prediction[:, :, 3] / 2\n    # prediction[:, :, :4] = box_corner[:, :, :4]\n\n    conf_thre = 0.001\n\n    pred_npy = prediction.numpy()\n    tmp_npy = np.zeros(pred_npy[:, :, :4].shape)\n    tmp_npy[:, :, 0] = pred_npy[:, :, 0] - pred_npy[:, :, 2] / 2\n    tmp_npy[:, :, 1] = pred_npy[:, :, 1] - pred_npy[:, :, 3] / 2\n    tmp_npy[:, :, 2] = pred_npy[:, :, 0] + pred_npy[:, :, 2] / 2\n    tmp_npy[:, :, 3] = pred_npy[:, :, 1] + pred_npy[:, :, 3] / 2\n    # prediction[:, :, :4] = paddle.to_tensor(tmp_npy).astype(prediction.dtype)\n    pred_npy[:, :, :4] = tmp_npy\n\n    scale_factor = scale_factor.numpy()\n\n    boxes = []\n    boxes_num = []\n\n\n    for i in range(pred_npy.shape[0]):\n        if not pred_npy[i].shape[0]:\n            continue\n\n        # class_conf = paddle.max(image_pred[:, 5: 5 + num_classes], 1, keepdim=True)\n        # class_pred = paddle.argmax(image_pred[:, 5: 5 + num_classes], 1, keepdim=True) #checked\n        # conf_mask = (image_pred[:, 4] * class_conf.squeeze() >= conf_thre).squeeze()\n        #\n        # detections = paddle.concat(\n        #     (image_pred[:, :5].astype('float'), class_conf.astype('float'), class_pred.astype('float')), 1)\n        # conf_mask_ind = conf_mask.nonzero()\n        # detections = paddle.gather(detections, conf_mask_ind)\n\n        class_conf = np.max(pred_npy[i][:, 5: 5 + num_classes], 1, keepdims = True)\n        class_pred = np.argmax(pred_npy[i][:, 5: 5 + num_classes], 1).reshape(class_conf.shape)\n        conf_mask = (pred_npy[i][:, 4] * class_conf.squeeze() >= conf_thre).squeeze()\n        conf_mask_ind = conf_mask.nonzero()\n        detections = np.concatenate((pred_npy[i][:, :5].astype(\"float32\"), class_conf.astype(\"float32\"),\n                                    class_pred.astype(\"float32\")), axis = 1)[conf_mask_ind]\n\n        if not detections.shape[0]:\n            continue\n        # detections = detections.numpy()\n\n        score = [(detections[:, 4] * detections[:, 5])[:, None], detections[:, 6][:, None]]\n        score = np.concatenate(score, 1)\n\n        output = multiclass_nms(\n            detections[:, :4],\n            score,\n            nms_thre,\n            conf_thre\n        ) # 输出box + score + cls\n\n        if output is None:\n            continue\n\n        #resize\n        ratio = np.array([[scale_factor[i][0], scale_factor[i][1], scale_factor[i][0], scale_factor[i][1]]])\n        resutls = np.zeros_like(output)\n        resutls[:, 0] = output[:, 5]\n        resutls[:, 1] = output[:, 4]\n        resutls[:, 2:6] = output[:, :4] / ratio\n\n        # print(output)\n        # print(resutls)\n\n        #todo 检查box边界\n        # if boxes is None:\n        #     boxes = resutls\n        # else:\n        #     boxes = np.concatenate((boxes, resutls))\n        boxes += resutls.tolist()\n        boxes_num.append(resutls.shape[0])\n\n    del prediction\n    return np.asarray(boxes), boxes_num\n\n\ndef bboxes_iou(bboxes_a, bboxes_b, xyxy=True):\n    if bboxes_a.shape[1] != 4 or bboxes_b.shape[1] != 4:\n        raise IndexError\n\n    if xyxy:\n        tl = paddle.maximum(bboxes_a[:, :2].unsqueeze(1), bboxes_b[:, :2])\n        br = paddle.minimum(bboxes_a[:, 2:].unsqueeze(1), bboxes_b[:, 2:])\n        area_a = paddle.prod(bboxes_a[:, 2:] - bboxes_a[:, :2], 1)\n        area_b = paddle.prod(bboxes_b[:, 2:] - bboxes_b[:, :2], 1)\n    else:\n        tl = paddle.maximum(\n            (bboxes_a[:, :2].unsqueeze(1) - bboxes_a[:, 2:].unsqueeze(1) / 2),\n            (bboxes_b[:, :2] - bboxes_b[:, 2:] / 2),\n        )\n        br = paddle.minimum(\n            (bboxes_a[:, :2].unsqueeze(1) + bboxes_a[:, 2:].unsqueeze(1) / 2),\n            (bboxes_b[:, :2] + bboxes_b[:, 2:] / 2),\n        )\n\n        area_a = paddle.prod(bboxes_a[:, 2:], 1)\n        area_b = paddle.prod(bboxes_b[:, 2:], 1)\n    en = (tl < br).astype(tl.dtype).prod(axis=2)\n    area_i = paddle.prod(br - tl, 2) * en  # * ((tl < br).all())\n    return area_i / (area_a.unsqueeze(1) + area_b - area_i)\n\n\ndef matrix_iou(a, b):\n    \"\"\"\n    return iou of a and b, numpy version for data augenmentation\n    \"\"\"\n    lt = np.maximum(a[:, np.newaxis, :2], b[:, :2])\n    rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:])\n\n    area_i = np.prod(rb - lt, axis=2) * (lt < rb).all(axis=2)\n    area_a = np.prod(a[:, 2:] - a[:, :2], axis=1)\n    area_b = np.prod(b[:, 2:] - b[:, :2], axis=1)\n    return area_i / (area_a[:, np.newaxis] + area_b - area_i + 1e-12)\n\n\ndef adjust_box_anns(bbox, scale_ratio, padw, padh, w_max, h_max):\n    bbox[:, 0::2] = np.clip(bbox[:, 0::2] * scale_ratio + padw, 0, w_max)\n    bbox[:, 1::2] = np.clip(bbox[:, 1::2] * scale_ratio + padh, 0, h_max)\n    return bbox\n\n\ndef xyxy2xywh(bboxes):\n    bboxes[:, 2] = bboxes[:, 2] - bboxes[:, 0]\n    bboxes[:, 3] = bboxes[:, 3] - bboxes[:, 1]\n    return bboxes\n\n\ndef xyxy2cxcywh(bboxes):\n    bboxes[:, 2] = bboxes[:, 2] - bboxes[:, 0]\n    bboxes[:, 3] = bboxes[:, 3] - bboxes[:, 1]\n    bboxes[:, 0] = bboxes[:, 0] + bboxes[:, 2] * 0.5\n    bboxes[:, 1] = bboxes[:, 1] + bboxes[:, 3] * 0.5\n    return bboxes\n", "meta": {"hexsha": "3038a6bcb6e6a0b7cf33745759f06ee0494f7342", "size": 9235, "ext": "py", "lang": "Python", "max_stars_repo_path": "ppdet/modeling/architectures/yolox_utils/boxes.py", "max_stars_repo_name": "thunder95/PPDET_YOLOX", "max_stars_repo_head_hexsha": "dafc12f5b4b0057c9a25de051e638ac16bf2f11b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ppdet/modeling/architectures/yolox_utils/boxes.py", "max_issues_repo_name": "thunder95/PPDET_YOLOX", "max_issues_repo_head_hexsha": "dafc12f5b4b0057c9a25de051e638ac16bf2f11b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ppdet/modeling/architectures/yolox_utils/boxes.py", "max_forks_repo_name": "thunder95/PPDET_YOLOX", "max_forks_repo_head_hexsha": "dafc12f5b4b0057c9a25de051e638ac16bf2f11b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3308550186, "max_line_length": 109, "alphanum_fraction": 0.5468327017, "include": true, "reason": "import numpy", "num_tokens": 2868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.29098087236345377, "lm_q1q2_score": 0.15909034441886552}}
{"text": "import copy\nimport numpy as np\nfrom . import full_high_sideband as fhs\nfrom Stele.processing.processing_hsg.pmt_collection.high_sideband_pmt \\\n    import HighSidebandPMT\n\n\ndef stitch_hsg_dicts_old(full, new_dict, need_ratio=False, verbose=False):\n    \"\"\"\n    This helper function takes a FullHighSideband.full_dict attribute and a\n    sideband object, either CCD or PMT and smushes the new sb_results into the\n    full_dict.\n\n    The first input doesn't change, so f there's a PMT set of data involved, it\n    should be in the full variable to keep the laser normalization intact.\n\n    This function almost certainly does not work for stitching many negative\n    orders in it's current state\n\n    11/14/16\n    --------\n    The original function has been updated to take the full object (instead of\n    the dicts alone) to better handle calculating ratios when stitching. This\n    is called once things have been parsed in the original function (or legacy\n    code where dicts are passed instead of the object)\n\n    Inputs:\n    full = full_dict from FullHighSideband, or HighSidebandPMT.  It's important\n           that it contains lower orders than the new_dict.\n    new_dict = another full_dict.\n    need_ratio = If gain or other parameters aren't equal and must resort to\n                 calculating the ratio instead of the measurements being\n                 equivalent. Changing integration time still means N photons\n                 made M counts, but changing gain or using PMT or whatever does\n                 affect things.\n\n    Returns:\n    full = extended version of the input full.  Overlapping sidebands are\n           averaged because that makes sense?\n    \"\"\"\n    if verbose:\n        print(\"I'm adding these sidebands in old stitcher\", sorted(\n            new_dict.keys()))\n    # The list that hold which orders are in both dictionaries\n    overlap = []\n    # How to deal with sidebands that are missing from full but in new.\n    missing = []\n    for new_sb in sorted(new_dict.keys()):\n        full_sbs = sorted(full.keys())\n        if new_sb in full_sbs:\n            overlap.append(new_sb)\n        # This probably doesn't work with bunches of negative orders\n        elif new_sb not in full_sbs and new_sb < full_sbs[-1]:\n            missing.append(new_sb)\n\n    if verbose:\n        print(\"overlap:\", overlap)\n        print(\"missing:\", missing)\n\n    # This if-else clause handles how to average together overlapping sidebands\n    # which are seen in both spectra,\n    if need_ratio:\n        # Calculate the appropriate ratio to multiply the new sidebands by.\n        # I'm not entirely sure what to do with the error of this guy.\n        ratio_list = []\n        # print '\\n1979\\nfull[2]', full[0][2]\n        try:\n            new_starter = overlap[-1]\n            if len(overlap) > 2:\n                overlap = [x for x in overlap if (x % 2 == 0)]\n                # and (x != min(overlap) and (x != max(overlap)))]\n            for sb in overlap:\n                ratio_list.append(full[sb][2] / new_dict[sb][2])\n            ratio = np.mean(ratio_list)\n            # print\n            # print '-'*15\n            # print \"ratio for {}: {}\".format()\n            error = np.std(ratio_list) / np.sqrt(len(ratio_list))\n        except IndexError:\n            # If there's no overlap (which you shouldn't let happen),\n            # hardcode a ratio and error.\n            # I looked at all the ratios for the overlaps from 6/15/16\n            # (540ghz para) to get the rough average. Hopefully they hold\n            # for all data.\n            if not overlap:\n                ratio = 0.1695\n                error = 0.02\n                # no overlap, so make sure it grabs\n                # all the sidebands\n                new_starter = min(new_dict.keys())\n            else:\n                raise\n        if verbose:\n            print(\"Ratio list\", \"\\n\", [round(ii, 3) for ii in ratio_list])\n            print(\"Overlap   \", \"\\n\", [round(ii, 3) for ii in overlap])\n            print(\"Ratio\", ratio)\n            print(\"Error\", error)\n        # print '\\n2118\\nfull[2]', full[0][2]\n        # Adding the new sidebands to the full set and moving errors around.\n        # I don't know exactly what to do about the other aspects of the\n        # sidebands besides the strength and its error.\n        for sb in overlap:\n            full[sb][2] = ratio * new_dict[sb][2]\n            full[sb][3] = full[sb][2] * np.sqrt(\n                (error / ratio) ** 2 +\n                (new_dict[sb][3] / new_dict[sb][2]) ** 2)\n            # print '\\n2125\\nfull[2]', full[0][3]\n            # Now for linewidths\n            lw_error = np.sqrt(\n                full[sb][5] ** (-2) + new_dict[sb][5] ** (-2)) ** (-1)\n            lw_avg = (\n                    full[sb][4] / (full[sb][5] ** 2) +\n                    new_dict[sb][4] / (new_dict[sb][5] ** 2)) / (\n                    full[sb][5] ** (-2) + new_dict[sb][5] ** (-2))\n            full[sb][4] = lw_avg\n            full[sb][5] = lw_error\n        # print '\\n2132\\nfull[2]', full[0][2]\n    else:\n        try:\n            # This grabs the sideband order where only the new dictionary has\n            # sideband information.  It's not clear why it necessarily has to\n            # be at this line.\n            new_starter = overlap[-1]\n            # This cuts out the lowest order sideband in the overlap for\n            # mysterious reasons\n            overlap = [\n                x for x in overlap if\n                (x % 2 == 0) and (x != min(overlap) and (x != max(overlap)))]\n            # This for loop average two data points weighted by their\n            # relative errors\n            for sb in overlap:\n                if verbose:\n                    print(\"The sideband\", sb)\n                    print(\"Old value\", full[sb][4] * 1000)\n                    print(\"Add value\", new_dict[sb][4] * 1000)\n                error = (np.sqrt(full[sb][3] ** (-2) +\n                         new_dict[sb][3] ** (-2)) ** (-1))\n                # TODO: unify average value calculations into function calls\n                avg = (\n                    full[sb][2] / (full[sb][3] ** 2) + new_dict[sb][2] /\n                    (new_dict[sb][3] ** 2)) / (\n                    full[sb][3] ** (-2) + new_dict[sb][3] ** (-2))\n                full[sb][2] = avg\n                full[sb][3] = error\n\n                lw_error = (np.sqrt(full[sb][5] ** (-2) +\n                            new_dict[sb][5] ** (-2)) ** (-1))\n                lw_avg = (\n                    full[sb][4] / (full[sb][5] ** 2) + new_dict[sb][4] /\n                    (new_dict[sb][5] ** 2)) / (\n                    full[sb][5] ** (-2) + new_dict[sb][5] ** (-2))\n                full[sb][4] = lw_avg\n                # This may not be the exactly right way to calculate the error\n                full[sb][5] = lw_error\n                if verbose:\n                    print(\"New value\", lw_avg * 1000)\n        except Exception:\n            # I think this makes things work when there's no overlap\n            new_starter = 0\n    if verbose:\n        print(\"appending new elements. new_starter={}\".format(new_starter))\n\n    # This loop will add the sidebands which were only seen in the second step\n    for sb in [x for x in list(new_dict.keys()) if (\n     (x >= new_starter) or (x in missing))]:\n        full[sb] = new_dict[sb]\n        if need_ratio:\n            full[sb][2] = ratio * full[sb][2]\n            full[sb][3] = full[sb][2] * np.sqrt(\n                (error / ratio) ** 2 +\n                (ratio * full[sb][3] / full[sb][2]) ** 2)\n            # print '\\n2164\\nfull[2]', full[0][2]\n    if verbose:\n        print(\"I made this dictionary\", sorted(full.keys()))\n    return full\n\n\ndef stitch_hsg_dicts(\n full_obj, new_obj, need_ratio=False, verbose=False, ratios=[1, 1],\n override_ratio=False, ignore_weaker_lowers=True):\n    \"\"\"\n    This helper function takes a FullHighSideband and a sideband object, either\n    CCD or PMT and smushes the new sb_results into the full_dict.\n\n    The first input doesn't change, so f there's a PMT set of data involved, it\n    should be in the full variable to keep the laser normalization intact.\n\n    This function almost certainly does not work for stitching many negative\n    orders in it's current state\n\n    11/14/16\n    --------\n    This function has been updated to take the CCD objects themselves to be\n    more intelligent about stitching. Consider two scans, (a) spec step 0 with\n    1 gain, spec step 2 with 110 gain and (b) spec step 0 with 50 gain and spec\n    step 1 with 110 gain. The old version would always take spec step 0 to\n    scale to, so while comparisons between spec step 0 and 1 for either case is\n    valid, comparison between (a) and (b) were not, since they were scaled to\n    different gain parameters. This new code will check what the gain values\n    are and scale to the 110 data set, if present. This seems valid because we\n    currently always have a 110 gain exposure for higher order sidebands. The\n    exception is if the laser is present (sideband 0), as that is an absolute\n    measure to which all else should be related.\n    TODO: run some test cases to test this.\n\n    06/11/18\n    --------\n    That sometimes was breaking if there were only 3-4 sidebands to fit with\n    poor SNR. I've added the override_ratio to be passed to set a specific\n    ratio to scale by. From data on 06/03/18, the 50gain to 110gain is a ~3.6\n    ratio. I haven't done a clean way of specifying which data set it should be\n    scaled. Right now, it leaves the laser line data, or the 110 gain data\n    alone.\n\n\n    Inputs:\n    full = full_dict from FullHighSideband, or HighSidebandPMT.  It's important\n           that it contains lower orders than the new_dict.\n    new_dict = another full_dict.\n    need_ratio = If gain or other parameters aren't equal and must resort to\n                 calculating the ratio instead of the measurements being\n                 equivalent. Changing integration time still means N photons\n                 made M counts, but changing gain or using PMT or whatever does\n                 affect things.\n    ratios: Will update with the values to the ratios needed to scale the data.\n            ratios[0] is the ratio for the \"full_obj\"\n            ratios[1] is the ratio for the \"new_obj\"\n            one of them will be one, one will be the appropriate scale, since\n            one of them is unscaled. This is strictly speaking an output\n    override_ratio: Pass a float to specify the ratio that should be used.\n    ignore_weaker_lowers: Sometimes, a SB is in the short pass filter so a\n        lower order is weaker than the next highest. If True, causes script to\n        ignore all sidebands which are weaker and lower order.\n\n    Returns:\n    full = extended version of the input full.  Overlapping sidebands are\n           averaged because that makes sense?\n    \"\"\"\n    if isinstance(full_obj, dict) and isinstance(new_obj, dict):\n        return stitch_hsg_dicts_old(full_obj, new_obj, need_ratio, verbose)\n\n    if verbose:\n        print(\"=\" * 15)\n        print()\n        print(\"Stitching HSG dicts\")\n        print()\n        print(\"=\" * 15)\n\n    # remove potentially offensive SBs, i.e. a 6th order SB being in the SPF\n    # for more data, but being meaningless to pull intensity information from.\n    # Note: this might not be the best if you get to higher order stitches\n    # where it's possible that the sidebands might not be monotonic\n    # (from noise?)\n    if ignore_weaker_lowers:\n        full_obj.full_dict, full_obj.sb_results = (\n            fhs.parse_sb_array(full_obj.sb_results))\n        new_obj.new_dict, new_obj.sb_results = (\n            fhs.parse_sb_array(new_obj.sb_results))\n\n    # was messing around with references and causing updates to arrays when\n    # it shouldn't be\n    full = copy.deepcopy(full_obj.full_dict)\n    new_dict = copy.deepcopy(new_obj.full_dict)\n\n    # Force a rescaling if you've passed a specified parameter\n    # if isinstance(override_ratio, float):\n    #     need_ratio = True\n\n    # Do some testing to see which dict should be scaled to the other\n    # I honestly forget why I prioritized the PMT first like this. But the\n    # third check looks to make a gain 110 prioritize non-110, unless the\n    # non-110 includes a laser line\n    scaleTo = \"\"\n    # TODO: altar below elif knot into a function call for Mccabe and pylama\n    if need_ratio:\n        if isinstance(new_obj, HighSidebandPMT):\n            scaleTo = \"new\"\n        elif isinstance(full_obj, HighSidebandPMT):\n            scaleTo = \"full\"\n        # this line specifically requires the function treatment to correct\n        elif new_obj.parameters[\"gain\"] == 110 and \\\n          full_obj.parameters[\"gain\"] != 110 and 0 not in full:\n            scaleTo = \"new\"\n        else:\n            scaleTo = \"full\"\n\n    if verbose:\n        print(\"\\tI'm adding these sidebands\", sorted(new_dict.keys()))\n        print(\"\\t  With these:\", sorted(full.keys()))\n    # The list that hold which orders are in both dictionaries\n    overlap = []\n    # How to deal with sidebands that are missing from full but in new.\n    missing = []\n    for new_sb in sorted(new_dict.keys()):\n        full_sbs = sorted(full.keys())\n        if new_sb in full_sbs:\n            overlap.append(new_sb)\n        elif new_sb not in full_sbs and new_sb < full_sbs[-1]:\n            # This probably doesn't work with bunches of negative orders\n            missing.append(new_sb)\n\n    if verbose:\n        print(\"\\t  ( overlap:\", overlap, \")\")\n        print(\"\\t  ( missing:\", missing, \")\")\n\n    # This if-else clause handles how to average together overlapping sidebands\n    # which are seen in both spectra,\n    if need_ratio:\n        # Calculate the appropriate ratio to multiply the new sidebands by.\n        # I'm not entirely sure what to do with the error of this guy.\n        ratio_list = []\n        try:\n            new_starter = overlap[-1]\n            if verbose:\n                print(\"\\n\\tadding these ratios,\", end=' ')\n            # TODO: code below appears highly redundant with stitch_hsg_dicts\n            #   and thus is prime for conversion to a function call\n            if len(overlap) > 2:\n                overlap = [x for x in overlap if (x % 2 == 0)]\n                # and (x != min(overlap) and (x != max(overlap)))]\n            if scaleTo == \"new\":\n                if verbose:\n                    print(\"scaling to new :\")\n                for sb in overlap:\n                    ratio_list.append(new_dict[sb][2]/full[sb][2])\n                    if verbose:\n                        print(\"\\t\\t{:2.0f}: {:.3e}/{:.3e} ~ {:.3e},\".format(\n                            sb, new_dict[sb][2], full[sb][2], ratio_list[-1]))\n                # new_ratio = 1 06/11/18 Not sure what these were used for\n                ratio = np.mean(ratio_list)\n            else:\n                if verbose:\n                    print(\"scaling to full:\")\n                for sb in overlap:\n                    ratio_list.append(full[sb][2] / new_dict[sb][2])\n                    if verbose:\n                        print(\"\\t\\t{:2.0f}: {:.3e}/{:.3e} ~ {:.3e},\".format(\n                            sb, full[sb][2], new_dict[sb][2], ratio_list[-1]))\n\n                # 06/11/18 Not sure what these were used for\n                # new_ratio = np.mean(ratio_list)\n\n                ratio = np.mean(ratio_list)\n            # Maybe not the best way to do it, performance wise, since you\n            # still iterate through the list, even though you'll override it.\n            if isinstance(override_ratio, float):\n                ratio = override_ratio\n                if verbose:\n                    print(\"overriding calculated ratio with user inputted\")\n            error = np.std(ratio_list) / np.sqrt(len(ratio_list))\n\n        except IndexError:\n            # If there's no overlap (which you shouldn't let happen), hardcode\n            # a ratio and error. I looked at all the ratios for the overlaps\n            # from 6/15/16 (540ghz para) to get the rough average. Hopefully\n            # they hold for all data.\n            if not overlap:\n                ratio = 0.1695\n                error = 0.02\n                # no overlap, so make sure it grabs all the sidebands\n                new_starter = min(new_dict.keys())\n            else:\n                raise\n        if verbose:\n            # print \"Ratio list\\n\\t\", (\"{:.3g}, \"*len(ratio_list))[:-2].format(\n            # *ratio_list)\n            # print \"Overlap   \\n\\t\", [round(ii, 3) for ii in overlap]\n            print(\"\\t Ratio: {:.3g} +- {:.3g} ({:.2f}%)\\n\".format(\n                ratio, error, error/ratio*100))\n        # Adding the new sidebands to the full set and moving errors around.\n        # I don't know exactly what to do about the other aspects of the\n        # sidebands besides the strength and its error.\n        if scaleTo == \"full\":\n            ratios[1] = ratio\n            for sb in overlap:\n                if verbose:\n                    print(\"For SB {:02d}, original strength is {:.3g} +- {:.3g} ({:.3f}%)\".format(int(sb), new_dict[sb][2], new_dict[sb][3], new_dict[sb][3]/new_dict[sb][2]*100))\n\n                new_dict[sb][3] = \\\n                    ratio * new_dict[sb][2] * np.sqrt(\n                    (error / ratio) ** 2 +\n                    (new_dict[sb][3] / new_dict[sb][2]) ** 2)\n                new_dict[sb][2] = ratio * new_dict[sb][2]\n                if verbose:\n                    print(\"\\t\\t   scaled\\t\\t\\t\\t{:.3g} +- {:.3g} ({:.3f}%)\".format(new_dict[sb][2], new_dict[sb][3], new_dict[sb][3]/new_dict[sb][2]*100))\n                    print(\"\\t\\t   full\\t\\t\\t\\t\\t{:.3g} +- {:.3g} ({:.3f}%)\".format(full[sb][2], full[sb][3], full[sb][3]/full[sb][2]*100))\n\n                sb_error = np.sqrt(full[sb][3] ** (-2) +\n                                   new_dict[sb][3] ** (-2)) ** (-1)\n\n                avg = (full[sb][2] / (full[sb][3] ** 2) + new_dict[sb][2] / (\n                    new_dict[sb][3] ** 2)) / (full[sb][3] ** (-2) + new_dict[sb][3] ** (-2))\n                full[sb][2] = avg\n                full[sb][3] = sb_error\n                if verbose:\n                    print(\"\\t\\t   replaced with \\t\\t{:.3g} +- {:.3g} ({:.3f}%)\".format(full[sb][2], full[sb][3], full[sb][3]/full[sb][2]*100))\n                    print()\n\n                lw_error = np.sqrt(full[sb][5] ** (-2) +\n                                   new_dict[sb][5] ** (-2)) ** (-1)\n                # TODO: unify low_average into a function call here and in old\n                lw_avg = (\n                    full[sb][4] / (full[sb][5] ** 2) +\n                    new_dict[sb][4] / (new_dict[sb][5] ** 2)) / (\n                    full[sb][5] ** (-2) + new_dict[sb][5] ** (-2))\n                full[sb][4] = lw_avg\n                # This may not be the exactly right way to calculate the error\n                full[sb][5] = lw_error\n        else:\n            ratios[0] = ratio\n            for sb in overlap:\n                full[sb][3] = ratio * full[sb][2] * np.sqrt(\n                    (error / ratio) ** 2 + (full[sb][3] / full[sb][2]) ** 2)\n                full[sb][2] = ratio * full[sb][2]\n\n                sberror = np.sqrt(\n                    full[sb][3] ** (-2) + new_dict[sb][3] ** (-2)) ** (-1)\n                avg = (\n                    full[sb][2] / (full[sb][3] ** 2) +\n                    new_dict[sb][2] / (new_dict[sb][3] ** 2)) / (\n                    full[sb][3] ** (-2) + new_dict[sb][3] ** (-2))\n                full[sb][2] = avg\n                full[sb][3] = sberror\n\n                lw_error = np.sqrt(\n                    full[sb][5] ** (-2) + new_dict[sb][5] ** (-2)) ** (-1)\n                lw_avg = (\n                    full[sb][4] / (full[sb][5] ** 2) +\n                    new_dict[sb][4] / (new_dict[sb][5] ** 2)) / (\n                    full[sb][5] ** (-2) + new_dict[sb][5] ** (-2))\n                full[sb][4] = lw_avg\n                # This may not be the exactly right way to calculate the error\n                full[sb][5] = lw_error\n\n    # not needing a new ratio\n    # TODO: rectify below redundancy with stitch_hsg_dicts_old using functions\n    else:\n        try:\n            # This grabs the sideband order where only the new dictionary has\n            # sideband information.  It's not clear why it necessarily has to\n            # be at this line.\n            new_starter = overlap[-1]\n            # This cuts out the lowest order sideband in the overlap for\n            # mysterious reasons\n            overlap = [x for x in overlap if (x % 2 == 0)]\n            #   and (x != min(overlap) and (x != max(overlap)))]\n            # This for loop average two data points weighted by\n            # their relative errors\n            for sb in overlap:\n                if verbose:\n                    print(\"The sideband\", sb)\n                    print(\"Old value\", full[sb][4] * 1000)\n                    print(\"Add value\", new_dict[sb][4] * 1000)\n                try:\n                    error = np.sqrt(\n                        full[sb][3] ** (-2) + new_dict[sb][3] ** (-2)) ** (-1)\n                    avg = (\n                        full[sb][2] / (full[sb][3] ** 2) +\n                        new_dict[sb][2] / (new_dict[sb][3] ** 2)) / (\n                        full[sb][3] ** (-2) + new_dict[sb][3] ** (-2))\n                    full[sb][2] = avg\n                    full[sb][3] = error\n                except RuntimeWarning:\n                    raise IOError()\n\n                lw_error = np.sqrt(\n                    full[sb][5] ** (-2) + new_dict[sb][5] ** (-2)) ** (-1)\n                lw_avg = (\n                    full[sb][4] / (full[sb][5] ** 2) +\n                    new_dict[sb][4] / (new_dict[sb][5] ** 2)) / (\n                    full[sb][5] ** (-2) + new_dict[sb][5] ** (-2))\n                full[sb][4] = lw_avg\n                # This may not be the exactly right way to calculate the error\n                full[sb][5] = lw_error\n                if verbose:\n                    print(\"New value\", lw_avg * 1000)\n        except Exception:\n            # I think this makes things work when there's no overlap\n            new_starter = 0\n    if verbose:\n        print(\"appending new elements. new_starter={}\".format(new_starter))\n\n    for sb in [x for x in list(new_dict.keys()) if (\n     (x > new_starter) or (x in missing))]:\n        full[sb] = new_dict[sb]\n        if scaleTo == \"full\":\n            full[sb][2] = ratio * full[sb][2]\n            full[sb][3] = full[sb][2] * np.sqrt(\n                (error / ratio) ** 2 +\n                (ratio * full[sb][3] / full[sb][2]) ** 2)\n    if scaleTo == \"new\":\n        for sb in set(full.keys()) - set(sorted(new_dict.keys())[:]):\n            full[sb][2] *= ratio\n            # TODO: I think this is an invalid error\n            # propagation (since ratio has error associated with it\n            full[sb][3] *= ratio\n    if verbose:\n        print(\"I made this dictionary\", sorted(full.keys()))\n        print('-'*19)\n    return full\n", "meta": {"hexsha": "b8d3b24f7ebeece0e044d8dcc6806851041dad6e", "size": 22962, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Stele/analysis/full_spectrum_collection/helper_functions.py", "max_stars_repo_name": "SherwinGroup/Stele", "max_stars_repo_head_hexsha": "9bb7da0b406a801975e21c9f7ce05d369ae661e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Stele/analysis/full_spectrum_collection/helper_functions.py", "max_issues_repo_name": "SherwinGroup/Stele", "max_issues_repo_head_hexsha": "9bb7da0b406a801975e21c9f7ce05d369ae661e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Stele/analysis/full_spectrum_collection/helper_functions.py", "max_forks_repo_name": "SherwinGroup/Stele", "max_forks_repo_head_hexsha": "9bb7da0b406a801975e21c9f7ce05d369ae661e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.8323353293, "max_line_length": 178, "alphanum_fraction": 0.5380628865, "include": true, "reason": "import numpy", "num_tokens": 5801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.159090341993641}}
{"text": "# -*- coding: utf-8 -*-\n# pylint: disable=wrong-import-position, too-many-locals, consider-using-enumerate\n\n\"\"\"\nFunction to generate the funciton for finding expected number of photons to\nsurvive from a 5D CLSim table.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\n__all__ = [\n    'MACHINE_EPS',\n    'MAX_RAD_SQ',\n    'USE_JITTER',\n    'generate_pexp_function',\n]\n\n__author__ = 'P. Eller, J.L. Lanfranchi'\n__license__ = '''Copyright 2017 Philipp Eller and Justin L. Lanfranchi\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.'''\n\nfrom collections import OrderedDict\nimport math\nfrom os.path import abspath, dirname\nimport sys\n\nimport numpy as np\nfrom scipy import stats\n\nif __name__ == '__main__' and __package__ is None:\n    RETRO_DIR = dirname(dirname(dirname(abspath(__file__))))\n    if RETRO_DIR not in sys.path:\n        sys.path.append(RETRO_DIR)\nfrom retro import DFLT_NUMBA_JIT_KWARGS, numba_jit\nfrom retro.const import SPEED_OF_LIGHT_M_PER_NS, SRC_OMNI, SRC_CKV_BETA1\nfrom retro.utils.geom import generate_digitizer\n\n\nMACHINE_EPS = 1e-10\n\n# TODO: not currently using MAX_RAD_SQ...\nMAX_RAD_SQ = 500**2\n\"\"\"Maximum radius to consider, squared (units of m^2)\"\"\"\n\n# TODO: a \"proper\" jitter (and transit time spread) implementation should treat each DOM\n# independently and pick the time offset for each DOM that maximizes LLH (_not_ expected\n# photon detections)\nUSE_JITTER = True\n\"\"\"Whether to use a crude jitter implementation\"\"\"\n\n\ndef generate_pexp_function(\n    dom_tables,\n    tdi_tables=None,\n    tdi_metas=None,\n):\n    \"\"\"Generate a numba-compiled function for computing expected photon counts\n    at a DOM, where the table's binning info is used to pre-compute various\n    constants for the compiled function to use.\n\n    Parameters\n    ----------\n    dom_tables : Retro5DTables\n        Fully-loaded set of single-DOM tables (time-dependent and, if no `tdi_tables`,\n        time-independent)\n\n    tdi_tables : sequence of 1 or 2 arrays, optional\n        Time- and DOM-independent tables.\n\n    tdi_metas : sequence of 1 or 2 mappings, optional\n        If provided, sequence must contain two mappings where the first\n        corresponds to the finely-binned TDI table and the second corresponds\n        to the coarsely-binned table (the first table takes precedence over the\n        second for looking up sources). Each of the mappings must contain keys\n        \"bin_edges\", itself a mapping containing \"x\", \"y\", \"z\", \"costhetadir\",\n        and \"phidir\"; values of these are arrays of the bin edges in each of\n        these dimensions. \"costhetadir\" must span [-1, 1] (inclusive) and\n        \"phidir\" must span [-pi, pi] inclusive). All edges must be strictly\n        monotonic and increasing.\n\n    Returns\n    -------\n    pexp : callable\n        Function to find detected-photon expectations given a hypothesis; \"raw\" function\n        that requires passing tables & norms\n\n    pexp_wrapper : callable\n        Function to find detected-photon expectations given a hypothesis; \"wrapped\"\n        function that bakes in tables & norms, exposing a more simple interface\n\n    pexp_meta : OrderedDict\n        Parameters, including the binning, that uniquely identify what the\n        capabilities of the returned `pexp`. (Use this to eliminate\n        redundant pexp functions.)\n\n    \"\"\"\n    if tdi_tables is None:\n        tdi_tables = ()\n    if tdi_metas is None:\n        tdi_metas = ()\n\n    tbl_is_ckv = dom_tables.table_kind in ['ckv_uncompr', 'ckv_templ_compr']\n    tbl_is_templ_compr = dom_tables.table_kind in ['raw_templ_compr', 'ckv_templ_compr']\n    if not tbl_is_ckv:\n        raise NotImplementedError('Only Ckv tables are implemented.')\n\n    # TODO: sanity checks that all TDI metadata is compatible with DOM tables\n    for tdi_meta in tdi_metas:\n        assert tdi_meta['bin_edges']['phidir'][0] == -np.pi\n        assert tdi_meta['bin_edges']['phidir'][-1] == np.pi\n\n    pexp_meta = OrderedDict()\n    pexp_meta['table_kind'] = dom_tables.table_kind\n    pexp_meta['table_binning'] = OrderedDict()\n    for key in (\n        'r_bin_edges', 'costhetadir_bin_edges', 't_bin_edges', 'costhetadir_bin_edges',\n        'deltaphidir_bin_edges'\n    ):\n        pexp_meta['table_binning'][key] = dom_tables.table_meta[key]\n\n    pexp_meta['tdi'] = tdi_metas\n    if len(tdi_tables) == 1:\n        tdi_tables = (tdi_tables[0], tdi_tables[0])\n\n    # NOTE: For now, we only support absolute value of deltaphidir (which\n    # assumes azimuthal symmetry). In future, this could be revisited (and then\n    # the abs(...) applied before binning in the pexp code will have to be\n    # removed or replaced with behavior that depend on the range of the\n    # deltaphidir_bin_edges).\n    assert dom_tables.table_meta['deltaphidir_bin_edges'][0] == 0, 'only abs(deltaphidir) supported'\n    assert dom_tables.table_meta['deltaphidir_bin_edges'][-1] == np.pi\n\n    # -- Define things used by `pexp*` closures defined below -- #\n\n    # Constants\n    rsquared_max = np.max(dom_tables.table_meta['r_bin_edges'])**2\n    t_max = np.max(dom_tables.table_meta['t_bin_edges'])\n    recip_max_group_vel = dom_tables.table_meta['group_refractive_index'] / SPEED_OF_LIGHT_M_PER_NS\n\n    # Digitization functions for each binning dimension\n    digitize_r = generate_digitizer(\n        dom_tables.table_meta['r_bin_edges'],\n        clip=True\n    )\n    digitize_costheta = generate_digitizer(\n        dom_tables.table_meta['costheta_bin_edges'],\n        clip=True\n    )\n    digitize_t = generate_digitizer(\n        dom_tables.table_meta['t_bin_edges'],\n        clip=True\n    )\n    digitize_costhetadir = generate_digitizer(\n        dom_tables.table_meta['costhetadir_bin_edges'],\n        clip=True\n    )\n    digitize_deltaphidir = generate_digitizer(\n        dom_tables.table_meta['deltaphidir_bin_edges'],\n        clip=True\n    )\n\n    num_tdi_tables = len(tdi_metas)\n    if num_tdi_tables == 0:\n        # Numba needs an object that it can determine type of\n        tdi_tables = 0\n    else:\n        x_edges = tdi_metas[0]['bin_edges']['x']\n        y_edges = tdi_metas[0]['bin_edges']['y']\n        z_edges = tdi_metas[0]['bin_edges']['z']\n        tdi0_xmin, tdi0_xmax = x_edges[[0, -1]]\n        tdi0_ymin, tdi0_ymax = y_edges[[0, -1]]\n        tdi0_zmin, tdi0_zmax = z_edges[[0, -1]]\n        digitize_tdi0_x = generate_digitizer(x_edges, clip=True)\n        digitize_tdi0_y = generate_digitizer(y_edges, clip=True)\n        digitize_tdi0_z = generate_digitizer(z_edges, clip=True)\n        digitize_tdi0_costhetadir = generate_digitizer(\n            tdi_metas[0]['bin_edges']['costhetadir'], clip=True\n        )\n        digitize_tdi0_phidir = generate_digitizer(\n            tdi_metas[0]['bin_edges']['phidir'], clip=True\n        )\n\n        if num_tdi_tables == 1:\n            idx = 0\n        elif num_tdi_tables == 2:\n            idx = 1\n        else:\n            raise ValueError(\n                'Can only handle 0, 1, or 2 TDI tables; got {}'\n                .format(num_tdi_tables)\n            )\n\n        x_edges = tdi_metas[idx]['bin_edges']['x']\n        y_edges = tdi_metas[idx]['bin_edges']['y']\n        z_edges = tdi_metas[idx]['bin_edges']['z']\n        tdi1_xmin, tdi1_xmax = x_edges[[0, -1]]\n        tdi1_ymin, tdi1_ymax = y_edges[[0, -1]]\n        tdi1_zmin, tdi1_zmax = z_edges[[0, -1]]\n        digitize_tdi1_x = generate_digitizer(x_edges, clip=True)\n        digitize_tdi1_y = generate_digitizer(y_edges, clip=True)\n        digitize_tdi1_z = generate_digitizer(z_edges, clip=True)\n        digitize_tdi1_costhetadir = generate_digitizer(\n            tdi_metas[idx]['bin_edges']['costhetadir'], clip=True\n        )\n        digitize_tdi1_phidir = generate_digitizer(\n            tdi_metas[idx]['bin_edges']['phidir'], clip=True\n        )\n\n    dom_tables_ = dom_tables\n\n    dom_tables = dom_tables_.tables\n    dom_table_norms = dom_tables_.table_norms\n    dom_tables_template_library = dom_tables_.template_library\n    t_indep_dom_tables = dom_tables_.t_indep_tables\n    t_indep_dom_table_norms = dom_tables_.t_indep_table_norms\n    t_is_residual_time = dom_tables_.t_is_residual_time\n\n    if not isinstance(dom_tables, np.ndarray):\n        dom_tables = np.stack(dom_tables, axis=0)\n        print('dom_tables.shape:', dom_tables.shape)\n    if not isinstance(dom_table_norms, np.ndarray):\n        dom_table_norms = np.stack(dom_table_norms, axis=0)\n        print('dom_table_norms.shape:', dom_table_norms.shape)\n    if not isinstance(t_indep_dom_tables, np.ndarray):\n        t_indep_dom_tables = np.stack(t_indep_dom_tables, axis=0)\n        print('t_indep_dom_tables.shape:', t_indep_dom_tables.shape)\n    if not isinstance(t_indep_dom_table_norms, np.ndarray):\n        t_indep_dom_table_norms = np.stack(t_indep_dom_table_norms, axis=0)\n        print('t_indep_dom_table_norms.shape:', t_indep_dom_table_norms.shape)\n\n    dom_tables.flags.writeable = False\n    dom_table_norms.flags.writeable = False\n    dom_tables_template_library.flags.writeable = False\n    t_indep_dom_tables.flags.writeable = False\n    t_indep_dom_table_norms.flags.writeable = False\n\n    if USE_JITTER:\n        # Time offsets to sample for DOM jitter\n        jitter_dt = np.arange(-10, 11, 2)\n\n        # Weight at each time offset\n        jitter_weights = stats.norm.pdf(jitter_dt, 0, 5)\n        jitter_weights /= np.sum(jitter_weights)\n    else:\n        jitter_dt = np.array([0.])\n        jitter_weights = np.array([1.])\n    num_jitter_time_offsets = len(jitter_dt)\n\n    # Indexing functions for table types omni / directional lookups\n    if tbl_is_templ_compr:\n        @numba_jit(**DFLT_NUMBA_JIT_KWARGS)\n        def table_lookup_mean(\n            tables, table_idx, r_bin_idx, costheta_bin_idx, t_bin_idx\n        ): # pylint: disable=missing-docstring\n            templ = tables[table_idx][r_bin_idx, costheta_bin_idx, t_bin_idx]\n            return templ['weight'] / dom_tables_template_library[templ['index']].size\n\n        @numba_jit(**DFLT_NUMBA_JIT_KWARGS)\n        def table_lookup(\n            tables, table_idx, r_bin_idx, costheta_bin_idx, t_bin_idx,\n            costhetadir_bin_idx, deltaphidir_bin_idx\n        ): # pylint: disable=missing-docstring\n            templ = tables[table_idx][r_bin_idx, costheta_bin_idx, t_bin_idx]\n            return (\n                templ['weight'] * dom_tables_template_library[\n                    templ['index'],\n                    costhetadir_bin_idx,\n                    deltaphidir_bin_idx,\n                ]\n            )\n\n    else: # table is not template-compressed\n        @numba_jit(**DFLT_NUMBA_JIT_KWARGS)\n        def table_lookup_mean(\n            tables, table_idx, r_bin_idx, costheta_bin_idx, t_bin_idx\n        ): # pylint: disable=missing-docstring\n            return np.mean(\n                tables[table_idx][r_bin_idx, costheta_bin_idx, t_bin_idx]\n            )\n\n        @numba_jit(**DFLT_NUMBA_JIT_KWARGS)\n        def table_lookup(\n            tables, table_idx, r_bin_idx, costheta_bin_idx, t_bin_idx,\n            costhetadir_bin_idx, deltaphidir_bin_idx\n        ): # pylint: disable=missing-docstring\n            return tables[table_idx][\n                r_bin_idx,\n                costheta_bin_idx,\n                t_bin_idx,\n                costhetadir_bin_idx,\n                deltaphidir_bin_idx,\n            ]\n\n    table_lookup_mean.__doc__ = (\n        \"\"\"Helper function for directionality-averaged table lookup\"\"\"\n    )\n    table_lookup.__doc__ = \"\"\"Helper function for directional table lookup\"\"\"\n\n    # -- Define `pexp*` closures (functions that use things defined above) -- #\n\n    # Note in the following that we need to invert the costheta\n    # direction of the sources to match the directions that\n    # Retro simulation comes up with. Thus the angles\n    # associated with this that we want to work with are\n    #   cos(pi - thetadir) = -cos(thetadir),\n    #   sin(pi - thetadir) = sin(thetadir),\n    #   cos(phidir) = cos(-phidir),\n    #   sin(phidir) = -sin(-phidir)\n    #\n    # This should be seen as a bug, but not sure how to address\n    # it without modifying existing tables, so sticking with it\n    # for now.\n    #\n    # We bin cos(pi - thetadir), so need to simply bin the\n    # quantity `-src_dir_costheta`.\n    #\n    # We want to bin abs(deltaphidir), which is described now:\n    # Just look at vectors in the xy-plane, since we want\n    # difference of angle in this plane. Use dot product:\n    #   dot(dir_vec_xy, pos_vec_xy) = |dir_vec_xy| |pos_vec_xy| cos(deltaphidir)\n    # where the length of the directionality vector in the xy-plane is\n    #   |dir_vec_xy| = rhodir = rdir * sin(pi - thetadir)\n    # and since rdir = 1 and the inversion of the angle above\n    #   |dir_vec_xy| = rhodir = sin(thetadir).\n    # The length of the position vector in the xy-plane is\n    #   |pos_vec_xy| = rho = sqrt(dx^2 + dy^2)\n    # where dx and dy are src_x - dom_x and src_y - dom_y.\n    # Solving for cos(deltaphidir):\n    #   cos(deltaphidir) = dot(dir_vec_xy, pos_vec_xy) / (rhodir * rho)\n    # we just need to write out the components of the dot\n    # product in terms of quantites we have:\n    #   dir_vec_x = rhodir * cos(phidir)\n    #   dir_vec_y = rhodir * sin(phidir)\n    #   pos_vec_x = dx\n    #   pos_vec_y = dy\n    # giving\n    #   cos(deltaphidir) = -(rhodir*cos(phidir)*dx + rhodir*sin(phidir)*dy)/(rhodir*rho)\n    # (where we use the negative to account for the inverted\n    # costhetadir in the tables); cancel rhodir out\n    #   cos(deltaphidir) = (cos(phidirpi)*dx + sin(phidirpi)*dy) / rho\n    # and substitute the identities above\n    #   cos(deltaphidir) = (cos(phidir)*dx + sin(phidir)*dy) / rho\n    # Finally, solve for deltaphidir\n    #   deltaphidir = acos((cos(phidir)*dx + sin(phidir)*dy) / rho)\n\n    # A photon that starts immediately in the past (before the\n    # DOM was hit) will show up in the Retro DOM tables in bin\n    # 0; the further in the past the photon started, the\n    # higher the time bin index. Therefore, subract source\n    # time from hit time.\n\n    # TODO: integrate tdi into same pexp function?\n\n    pexp_docstr = (\n        r\"\"\"For a set of generated photons `sources`, compute the expected\n        photons in a particular DOM at `hit_time` and the total expected\n        photons, independent of time.\n\n        This function utilizes the relative space-time coordinates _and_\n        directionality of the generated photons (via \"raw\" 5D CLSim tables) to\n        determine how many photons are expected to arrive at the DOM.\n\n        Retro DOM tables applied to the generated photon info `sources`,\n        and the total expected photon count (time integrated) -- the\n        normalization of the pdf.\n\n        Parameters\n        ----------\n        sources : shape (num_sources,) array of dtype SRC_T\n            A discrete sequence of points describing expected sources of\n            photons that result from a hypothesized event.\n\n        sources_start, sources_stop : int\n            Starting and stopping indices for the part of the array on which to\n            work. Note that the latter is exclusive, i.e., following Python\n            range / slice syntax. Hence, the following section of `sources` will\n            be operated upon: .. ::\n\n                sources[sources_start:sources_stop]\n\n        event_dom_info : shape (n_operational_doms,) array of dtype EVT_DOM_INFO_T\n\n        event_hit_info : shape (n_hits,) array of dtype EVT_HIT_INFO_T\n\n        hit_exp : shape (n_hits,) array of floats\n            Time-dependent hit expectation at each (actual) hit time;\n            initialize outside of this function, as values are incremented\n            within this function. Values in `hit_exp` correspond to the values\n            in `event_hit_info`.\n\n        dom_tables : array\n            DOM time-dependent photon survival probability tables. If using an\n            uncompressed table, these will have shape\n                (n_r, n_costheta, n_t, n_costhetadir, n_deltaphidir)\n            while if you use a template-compressed table, this will have shape\n                (n_templates, n_costhetadir, n_deltaphidir)\n\n        dom_table_norms : shape (n_tables, n_r, n_t) array\n            Normalization to apply to `table`, which is assumed to depend on\n            both r- and t-dimensions.\n\n        t_indep_dom_tables : array\n            Time-independent photon survival probability table. If using an\n            uncompressed table, this will have shape\n                (n_r, n_costheta, n_costhetadir, n_deltaphidir)\n            while if using a\n\n        t_indep_dom_dom_table_norms : shape (n_tables, n_r) array\n            r-dependent normalization (any t-dep normalization is assumed to\n            already have been applied to generate the t_indep_table).\n\n        tdi_tables : {type}\n            {text}\n\n        Returns\n        -------\n        t_indep_exp : float\n            Expectation of total hits for all operational DOMs\n\n        Out\n        ---\n        hit_exp\n            `hit_exp` is modified by the function; see Parameters section for\n            detailed explanation of parameter `hit_exp`\n\n        \"\"\"\n    )\n\n    if num_tdi_tables == 0:\n\n        @numba_jit(**DFLT_NUMBA_JIT_KWARGS)\n        def pexp(\n            sources,\n            sources_start,\n            sources_stop,\n            event_dom_info,\n            event_hit_info,\n            hit_exp,\n            dom_tables,\n            dom_table_norms,\n            t_indep_dom_tables,\n            t_indep_dom_table_norms,\n            tdi_tables, # pylint: disable=unused-argument\n        ): # pylint: disable=missing-docstring, too-many-arguments\n            num_operational_doms = len(event_dom_info)\n            t_indep_exp = 0.\n            for source_idx in range(sources_start, sources_stop):\n                src = sources[source_idx]\n\n                for op_dom_idx in range(num_operational_doms):\n                    dom_info = event_dom_info[op_dom_idx]\n                    dom_tbl_idx = dom_info['table_idx']\n                    dom_qe = dom_info['quantum_efficiency']\n                    dom_hits_start_idx = dom_info['hits_start_idx']\n                    dom_hits_stop_idx = dom_info['hits_stop_idx']\n\n                    dx = src['x'] - dom_info['x']\n                    dy = src['y'] - dom_info['y']\n                    dz = src['z'] - dom_info['z']\n\n                    rhosquared = max(MACHINE_EPS, dx**2 + dy**2)\n                    rsquared = rhosquared + dz**2\n\n                    if rsquared > rsquared_max:\n                        continue\n\n                    r = max(MACHINE_EPS, math.sqrt(rsquared))\n                    r_bin_idx = digitize_r(r)\n\n                    costheta_bin_idx = digitize_costheta(dz/r)\n\n                    if src['kind'] == SRC_OMNI:\n                        t_indep_surv_prob = np.mean(\n                            t_indep_dom_tables[dom_tbl_idx][r_bin_idx, costheta_bin_idx, :, :]\n                        )\n\n                    else: # SRC_CKV_BETA1:\n                        rho = math.sqrt(rhosquared)\n\n                        if rho <= MACHINE_EPS:\n                            absdeltaphidir = 0.\n                        else:\n                            absdeltaphidir = abs(math.acos(\n                                max(-1., min(1., -(src['dir_cosphi']*dx + src['dir_sinphi']*dy) / rho))\n                            ))\n\n                        costhetadir_bin_idx = digitize_costhetadir(src['dir_costheta'])\n                        deltaphidir_bin_idx = digitize_deltaphidir(absdeltaphidir)\n\n                        t_indep_surv_prob = t_indep_dom_tables[dom_tbl_idx][\n                            r_bin_idx,\n                            costheta_bin_idx,\n                            costhetadir_bin_idx,\n                            deltaphidir_bin_idx\n                        ]\n\n                    ti_norm = t_indep_dom_table_norms[dom_tbl_idx][r_bin_idx]\n                    t_indep_exp += src['photons'] * ti_norm * t_indep_surv_prob * dom_qe\n\n                    for hit_idx in range(dom_hits_start_idx, dom_hits_stop_idx):\n                        hit_info = event_hit_info[hit_idx]\n                        if t_is_residual_time:\n                            nominal_dt = hit_info['time'] - src['time'] - r * recip_max_group_vel\n                        else:\n                            nominal_dt = hit_info['time'] - src['time']\n\n                        for jitter_idx in range(num_jitter_time_offsets):\n                            dt = nominal_dt + jitter_dt[jitter_idx]\n\n                            # Note the comparison is written such that it will evaluate\n                            # to True if `dt` is NaN or less than zero.\n                            if (not dt >= 0) or dt > t_max:\n                                continue\n\n                            t_bin_idx = digitize_t(dt)\n\n                            if src['kind'] == SRC_OMNI:\n                                surv_prob_at_hit_t = table_lookup_mean(\n                                    tables=dom_tables,\n                                    table_idx=dom_tbl_idx,\n                                    r_bin_idx=r_bin_idx,\n                                    costheta_bin_idx=costheta_bin_idx,\n                                    t_bin_idx=t_bin_idx,\n                                )\n\n                            else: # SRC_CKV_BETA1\n                                surv_prob_at_hit_t = table_lookup(\n                                    tables=dom_tables,\n                                    table_idx=dom_tbl_idx,\n                                    r_bin_idx=r_bin_idx,\n                                    costheta_bin_idx=costheta_bin_idx,\n                                    t_bin_idx=t_bin_idx,\n                                    costhetadir_bin_idx=costhetadir_bin_idx,\n                                    deltaphidir_bin_idx=deltaphidir_bin_idx,\n                                )\n\n                            r_t_bin_norm = dom_table_norms[dom_tbl_idx][r_bin_idx, t_bin_idx]\n                            hit_exp[hit_idx] += jitter_weights[jitter_idx] * (\n                                src['photons'] * r_t_bin_norm * surv_prob_at_hit_t * dom_qe\n                            )\n\n            return t_indep_exp\n\n        pexp.__doc__ = pexp_docstr.format(\n            type='int',\n            text=\"\"\"Dummy argument for this version of `pexp` since it doesn't use TDI\n            tables (but this argument needs to be present to maintain same\n            interface)\"\"\"\n        )\n\n    else: # pexp function given we are using TDI tables\n\n        @numba_jit(**DFLT_NUMBA_JIT_KWARGS)\n        def pexp(\n            sources,\n            sources_start,\n            sources_stop,\n            event_dom_info,\n            event_hit_info,\n            hit_exp,\n            dom_tables,\n            dom_table_norms,\n            t_indep_dom_tables, # pylint: disable=unused-argument\n            t_indep_dom_table_norms, # pylint: disable=unused-argument\n            tdi_tables,\n        ): # pylint: disable=missing-docstring, too-many-arguments\n            # -- Time- and DOM-independent photon-detection expectation -- #\n\n            t_indep_exp = 0.\n            for source_idx in range(sources_start, sources_stop):\n                src = sources[source_idx]\n                src_opposite_dir_costheta = -src['dir_costheta']\n                src_opposite_dir_phi = ((src['dir_phi'] + 2*np.pi) % (2*np.pi)) - np.pi\n\n                if (\n                    tdi0_xmin <= src['x'] <= tdi0_xmax\n                    and tdi0_ymin <= src['y'] <= tdi0_ymax\n                    and tdi0_zmin <= src['z'] <= tdi0_zmax\n                ):\n                    t_indep_exp += 0.45 * src['photons'] * tdi_tables[0][\n                        digitize_tdi0_x(src['x']),\n                        digitize_tdi0_y(src['y']),\n                        digitize_tdi0_z(src['z']),\n                        digitize_tdi0_costhetadir(src_opposite_dir_costheta),\n                        digitize_tdi0_phidir(src_opposite_dir_phi),\n                    ]\n                elif num_tdi_tables >= 2 and (\n                    tdi1_xmin <= src['x'] <= tdi1_xmax\n                    and tdi1_ymin <= src['y'] <= tdi1_ymax\n                    and tdi1_zmin <= src['z'] <= tdi1_zmax\n                ):\n                    t_indep_exp += 0.45 * src['photons'] * tdi_tables[1][\n                        digitize_tdi1_x(src['x']),\n                        digitize_tdi1_y(src['y']),\n                        digitize_tdi1_z(src['z']),\n                        digitize_tdi1_costhetadir(src_opposite_dir_costheta),\n                        digitize_tdi1_phidir(src_opposite_dir_phi),\n                    ]\n                else:\n                    continue\n\n            # -- Time-dependent photon-det expectation for each hit DOM -- #\n\n            for hit_idx, hit_info in enumerate(event_hit_info):\n                dom_info = event_dom_info[hit_info['event_dom_idx']]\n                dom_tbl_idx = dom_info['table_idx']\n                dom_qe = dom_info['quantum_efficiency']\n\n                for source_idx in range(sources_start, sources_stop):\n                    src = sources[source_idx]\n\n                    dx = src['x'] - dom_info['x']\n                    dy = src['y'] - dom_info['y']\n                    dz = src['z'] - dom_info['z']\n\n                    rhosquared = max(MACHINE_EPS, dx**2 + dy**2)\n                    rsquared = rhosquared + dz**2\n\n                    if rsquared > rsquared_max:\n                        continue\n\n                    r = max(MACHINE_EPS, math.sqrt(rsquared))\n                    r_bin_idx = digitize_r(r)\n\n                    costheta_bin_idx = digitize_costheta(dz/r)\n\n                    if src['kind'] == SRC_CKV_BETA1:\n                        rho = math.sqrt(rhosquared)\n\n                        if rho <= MACHINE_EPS:\n                            absdeltaphidir = 0.\n                        else:\n                            absdeltaphidir = abs(math.acos(\n                                max(-1., min(1., -(src['dir_cosphi']*dx + src['dir_sinphi']*dy) / rho))\n                            ))\n\n                        costhetadir_bin_idx = digitize_costhetadir(src['dir_costheta'])\n                        deltaphidir_bin_idx = digitize_deltaphidir(absdeltaphidir)\n\n                    if t_is_residual_time:\n                        nominal_dt = hit_info['time'] - src['time'] - r * recip_max_group_vel\n                    else:\n                        nominal_dt = hit_info['time'] - src['time']\n\n                    # Note: caching last `t_bin_idx`, `r_t_bin_norm`, and\n                    # `surv_prob_at_hit_t` and checking for identical `t_bin_idx` seems\n                    # to take about the same time as not caching these values, so\n                    # choosing the simpler way\n\n                    for jitter_idx in range(num_jitter_time_offsets):\n                        dt = nominal_dt + jitter_dt[jitter_idx]\n\n                        # Note the comparison is written such that it will evaluate to\n                        # True if `dt` is NaN or less than zero.\n                        if (not dt >= 0) or dt > t_max:\n                            continue\n\n                        t_bin_idx = digitize_t(dt)\n\n                        if src['kind'] == SRC_OMNI:\n                            surv_prob_at_hit_t = table_lookup_mean(\n                                tables=dom_tables,\n                                table_idx=dom_tbl_idx,\n                                r_bin_idx=r_bin_idx,\n                                costheta_bin_idx=costheta_bin_idx,\n                                t_bin_idx=t_bin_idx,\n                            )\n\n                        else: # SRC_CKV_BETA1\n                            surv_prob_at_hit_t = table_lookup(\n                                tables=dom_tables,\n                                table_idx=dom_tbl_idx,\n                                r_bin_idx=r_bin_idx,\n                                costheta_bin_idx=costheta_bin_idx,\n                                t_bin_idx=t_bin_idx,\n                                costhetadir_bin_idx=costhetadir_bin_idx,\n                                deltaphidir_bin_idx=deltaphidir_bin_idx,\n                            )\n\n                        r_t_bin_norm = dom_table_norms[dom_tbl_idx][r_bin_idx, t_bin_idx]\n                        hit_exp[hit_idx] += jitter_weights[jitter_idx] * (\n                            src['photons'] * r_t_bin_norm * surv_prob_at_hit_t * dom_qe\n                        )\n\n            return t_indep_exp\n\n        pexp.__doc__ = pexp_docstr.format(\n            type='tuple of 1 or 2 arrays',\n            text=\"\"\"TDI tables\"\"\"\n        )\n\n    # -- Define pexp closure to bake-in the tables -- #\n\n    # Note: faster to _not_ jit-compile this function (why, though?)\n    def pexp_wrapper(\n        sources,\n        sources_start,\n        sources_stop,\n        event_dom_info,\n        event_hit_info,\n        hit_exp,\n    ):\n        return pexp(\n            sources=sources,\n            sources_start=sources_start,\n            sources_stop=sources_stop,\n            event_dom_info=event_dom_info,\n            event_hit_info=event_hit_info,\n            hit_exp=hit_exp,\n            dom_tables=dom_tables,\n            dom_table_norms=dom_table_norms,\n            t_indep_dom_tables=t_indep_dom_tables,\n            t_indep_dom_table_norms=t_indep_dom_table_norms,\n            tdi_tables=tdi_tables,\n        )\n\n    return pexp, pexp_wrapper, pexp_meta\n", "meta": {"hexsha": "1dcbac968d3eb23ecf82b67ba9236383e26d6cdb", "size": 29853, "ext": "py", "lang": "Python", "max_stars_repo_path": "retro/pexp.py", "max_stars_repo_name": "ellohfin/retro", "max_stars_repo_head_hexsha": "58ec8f5b698e6140acd215717f051d99e407c4e5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-02T01:05:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-02T01:05:52.000Z", "max_issues_repo_path": "retro/pexp.py", "max_issues_repo_name": "ellohfin/retro", "max_issues_repo_head_hexsha": "58ec8f5b698e6140acd215717f051d99e407c4e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2018-01-30T21:03:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-07T16:42:07.000Z", "max_forks_repo_path": "retro/pexp.py", "max_forks_repo_name": "ellohfin/retro", "max_forks_repo_head_hexsha": "58ec8f5b698e6140acd215717f051d99e407c4e5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-07-27T19:49:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-19T13:38:27.000Z", "avg_line_length": 40.950617284, "max_line_length": 103, "alphanum_fraction": 0.585535792, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.1590903376955751}}
{"text": "from collections import deque\nimport os\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom torch.distributions import Normal\n\nfrom .base import BaseAgent\nfrom core.network import Network\nfrom core.optimizer import Optimizer\nfrom core.buffer import ReplayBuffer\n\n\nclass MPO(BaseAgent):\n    \"\"\"Maximum A Posteriori Policy Optimization (MPO) agent.\n\n    Args:\n        state_size (int): dimension of state.\n        action_size (int): dimension of action.\n        hidden_size (int): dimension of hidden unit.\n        optim_config (dict): dictionary of the optimizer info.\n            (key: 'name', value: name of optimizer)\n        actor (str): key of actor network class in _network_dict.txt.\n        critic (str): key of critic network class in _network_dict.txt.\n        head (str): key of head in _head_dict.txt.\n        buffer_size (int): the size of the memory buffer.\n        batch_size (int): the number of samples in the one batch.\n        start_train_step (int): steps to start learning.\n        n_epoch (int): Number of epoch when optimizing the surrogate.\n        n_step (int): The number of steps to run for each environment per update.\n        clip_grad_norm (float): gradient clipping threshold.\n        gamma (float): discount factor.\n        device (str): device to use.\n            (e.g. 'cpu' or 'gpu'. None can also be used, and in this case, the cpu is used.)\n        num_workers: the number of agents in distributed learning.\n        critic_loss_type (str): type of critic loss. One of ['1step_TD', 'retrace'].\n        num_sample (int): the number of samples.\n        min_eta (float): minimum value of eta.\n        min_alpha_mu (float): minimum value of alpha_mu.\n        min_alpha_sigma (float): minimum value of alpha_sigma.\n        eps_eta (float): threshold of temperature loss term.\n        eps_alpha_mu (float): threshold of mean part of Gaussian-KL constraint term.\n        eps_alpha_sigma (float): threshold of variance part of Gaussian-KL constraint term.\n        eta (float): Lagrange multipliers of temperature loss term.\n        alpha_mu (float): Lagrange multipliers of mean part of Gaussian-KL constraint term (trust-region loss).\n        alpha_sigma (float): Lagrange multipliers of variance part of Gaussian-KL constraint term.\n    \"\"\"\n\n    def __init__(\n        self,\n        state_size,\n        action_size,\n        hidden_size=512,\n        optim_config={\"name\": \"adam\"},\n        actor=\"discrete_policy\",\n        critic=\"dqn\",\n        head=\"mlp\",\n        buffer_size=50000,\n        batch_size=64,\n        start_train_step=2000,\n        n_epoch=64,\n        n_step=8,\n        clip_grad_norm=1.0,\n        gamma=0.99,\n        device=None,\n        num_workers=1,\n        # parameters unique to MPO\n        critic_loss_type=\"retrace\",  # one of ['1step_TD', 'retrace']\n        num_sample=30,\n        min_eta=1e-8,\n        min_alpha_mu=1e-8,\n        min_alpha_sigma=1e-8,\n        eps_eta=0.01,\n        eps_alpha_mu=0.01,\n        eps_alpha_sigma=5 * 1e-5,\n        eta=1.0,\n        alpha_mu=1.0,\n        alpha_sigma=1.0,\n        **kwargs,\n    ):\n        self.device = (\n            torch.device(device)\n            if device\n            else torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n        )\n        self.head = head\n        self.action_type = actor.split(\"_\")[0]\n        assert self.action_type in [\"continuous\", \"discrete\"]\n        self.action_size = action_size\n\n        self.actor = Network(\n            actor, state_size, action_size, D_hidden=hidden_size, head=head\n        ).to(self.device)\n        self.target_actor = Network(\n            actor, state_size, action_size, D_hidden=hidden_size, head=head\n        ).to(self.device)\n        self.target_actor.load_state_dict(self.actor.state_dict())\n\n        assert critic_loss_type in [\"1step_TD\", \"retrace\"]\n        self.critic_loss_type = critic_loss_type\n        self.critic = Network(\n            critic, state_size, action_size, D_hidden=hidden_size, head=head\n        ).to(self.device)\n        self.target_critic = Network(\n            critic, state_size, action_size, D_hidden=hidden_size, head=head\n        ).to(self.device)\n        self.target_critic.load_state_dict(self.critic.state_dict())\n\n        self.batch_size = batch_size\n        self.n_step = n_step if critic_loss_type == \"retrace\" else 1\n        self.clip_grad_norm = clip_grad_norm\n\n        self.num_learn = 0\n        self.time_t = 0\n        self.start_train_step = start_train_step\n        self.n_epoch = n_epoch\n\n        self.num_sample = num_sample\n\n        self.min_eta = torch.tensor(min_eta, device=self.device)\n        self.min_alpha_mu = torch.tensor(min_alpha_mu, device=self.device)\n        self.min_alpha_sigma = torch.tensor(min_alpha_sigma, device=self.device)\n\n        self.eps_eta = eps_eta\n        self.eps_alpha_mu = eps_alpha_mu\n        self.eps_alpha_sigma = eps_alpha_sigma\n\n        self.eta = torch.nn.Parameter(\n            torch.tensor(eta, requires_grad=True).to(self.device)\n        )\n        self.alpha_mu = torch.nn.Parameter(\n            torch.tensor(alpha_mu, requires_grad=True).to(self.device)\n        )\n        self.alpha_sigma = torch.nn.Parameter(\n            torch.tensor(alpha_sigma, requires_grad=True).to(self.device)\n        )\n\n        self.reset_lgr_muls()\n\n        self.actor_optimizer = Optimizer(\n            **optim_config,\n            params=list(self.actor.parameters())\n            + [self.eta, self.alpha_mu, self.alpha_sigma],\n        )\n        self.critic_optimizer = Optimizer(\n            **optim_config, params=list(self.critic.parameters())\n        )\n\n        self.gamma = gamma\n        self.tmp_buffer = deque(maxlen=n_step)\n        self.memory = ReplayBuffer(buffer_size)\n\n    @torch.no_grad()\n    def act(self, state, training=True):\n        self.actor.train(training)\n        if self.action_type == \"continuous\":\n            mu, std = self.actor(self.as_tensor(state))\n            m = Normal(mu, std)\n            z = m.sample() if training else mu\n            action = torch.tanh(z)\n            action = action.data.cpu().numpy()\n            prob = m.log_prob(z).sum(axis=-1, keepdims=True)\n            prob = prob.exp().cpu().numpy()\n\n        else:\n            pi = self.actor(self.as_tensor(state))\n            action = (\n                torch.multinomial(pi, 1)\n                if training\n                else torch.argmax(pi, dim=-1, keepdim=True)\n            )\n            action = action.cpu().numpy()\n            prob = np.take(pi.cpu().numpy(), action)\n        return {\n            \"action\": action,\n            \"prob\": prob,\n        }\n\n    def learn(self):\n        transitions = self.memory.sample(self.batch_size)\n        for key in transitions.keys():\n            # reshape: (batch_size, len_tr, item_dim)\n            #        -> (batch_size * len_tr, item_dim)\n            transitions[key] = self.as_tensor(transitions[key]).view(\n                -1, *transitions[key].shape[2:]\n            )\n\n        state = transitions[\"state\"]\n        action = transitions[\"action\"]\n        reward = transitions[\"reward\"]\n        next_state = transitions[\"next_state\"]\n        done = transitions[\"done\"]\n        prob_b = transitions[\"prob\"]\n\n        if self.action_type == \"continuous\":\n            mu, std = self.actor(state)\n            Q = self.critic(state, action)\n            m = Normal(mu, std)\n            z = torch.atanh(torch.clamp(action, -1 + 1e-7, 1 - 1e-7))\n            log_pi = m.log_prob(z)\n            log_prob = log_pi.sum(axis=-1, keepdims=True)\n            prob = torch.exp(log_prob)\n\n            with torch.no_grad():\n                mut, stdt = self.target_actor(state)\n                mt = Normal(mut, stdt)\n                zt = torch.atanh(torch.clamp(action, -1 + 1e-7, 1 - 1e-7))\n                log_pit = mt.log_prob(zt)\n                log_probt = log_pit.sum(axis=-1, keepdims=True)\n\n                mu_old = mut\n                std_old = stdt\n                prob_t = torch.exp(log_probt)\n\n                Qt_a = self.target_critic(state, action)\n\n                next_mu, next_std = self.actor(next_state)\n                mn = Normal(next_mu, next_std)\n                zn = mn.sample(\n                    (self.num_sample,)\n                )  # (num_sample, batch_size * len_tr, dim_action)\n                next_action = torch.tanh(zn)\n\n                Qt_next = self.target_critic(\n                    next_state.unsqueeze(0).repeat_interleave(self.num_sample, dim=0),\n                    next_action,\n                )  # (num_sample, batch_size * len_tr, 1)\n\n                c = torch.clip(prob / (prob_b + 1e-6), max=1.0)\n\n                if self.critic_loss_type == \"1step_TD\":\n                    Qret = reward + self.gamma * (1 - done) * Qt_next.mean(axis=0)\n                elif self.critic_loss_type == \"retrace\":\n                    Qret = reward + self.gamma * Qt_next.mean(axis=0) * (1 - done)\n\n                    # temporarily reshaping values\n                    # (batch_size * len_tr, item_dim) -> (batch_size, len_tr, item_dim)\n                    Qret = Qret.view(self.batch_size, -1, *Qret.shape[1:])\n                    Qt_a = Qt_a.view(self.batch_size, -1, *Qt_a.shape[1:])\n                    c = c.view(self.batch_size, -1, *c.shape[1:])\n                    done = done.view(self.batch_size, -1, *done.shape[1:])\n                    for i in reversed(range(Qret.shape[1] - 1)):\n                        Qret[:, i] += (\n                            self.gamma\n                            * c[:, i + 1]\n                            * (1 - done[:, i])\n                            * (Qret[:, i + 1] - Qt_a[:, i + 1])\n                        )\n                    Qret = Qret.view(-1, *Qret.shape[2:])\n\n            zt_add = mt.sample(\n                (self.num_sample,)\n            )  # (num_sample, batch_size * len_tr, dim_action)\n            action_add = torch.tanh(zt_add)\n            log_pi_add = m.log_prob(zt_add)\n            log_prob_add = log_pi_add.sum(axis=-1, keepdims=True)\n            Qt_add = self.target_critic(\n                state.unsqueeze(0).repeat_interleave(self.num_sample, dim=0), action_add\n            )\n\n            critic_loss = F.mse_loss(Q, Qret).mean()\n\n            # Calculate Vt_add, At_add using Qt_add\n            Vt_add = torch.mean(Qt_add, axis=0, keepdims=True)\n            At_add = Qt_add - Vt_add\n            At = At_add\n\n            \"\"\" variational distribution q uses exp(At / eta) instead of exp(Qt / eta), for stable learning\"\"\"\n            q = torch.softmax(At_add / self.eta, axis=0)\n            actor_loss = -torch.mean(torch.sum(q.detach() * log_prob_add, axis=0))\n\n            eta_loss = self.eta * self.eps_eta + self.eta * torch.mean(\n                torch.log(torch.exp((At_add) / self.eta).mean(axis=0))\n            )\n\n            ss = 1.0 / (std ** 2)  # (batch_size * len_tr, action_dim)\n            ss_old = 1.0 / (std_old ** 2)\n\n            \"\"\"\n            KL-Divergence losses(related to alpha) implemented using methods introduced from V-MPO paper\n            https://arxiv.org/abs/1909.12238\n            \"\"\"\n\n            # mu\n            d_mu = mu - mu_old.detach()  # (batch_size * len_tr, action_dim)\n            KLD_mu = 0.5 * torch.sum(d_mu * 1.0 / ss_old.detach() * d_mu, axis=-1)\n            mu_loss = torch.mean(\n                self.alpha_mu * (self.eps_alpha_mu - KLD_mu.detach())\n                + self.alpha_mu.detach() * KLD_mu\n            )\n\n            # sigma\n            KLD_sigma = 0.5 * (\n                torch.sum(1.0 / ss * ss_old.detach(), axis=-1)\n                - ss.shape[-1]\n                + torch.log(\n                    torch.prod(ss, axis=-1) / torch.prod(ss_old.detach(), axis=-1)\n                )\n            )\n            sigma_loss = torch.mean(\n                self.alpha_sigma * (self.eps_alpha_sigma - KLD_sigma.detach())\n                + self.alpha_sigma.detach() * KLD_sigma\n            )\n\n            alpha_loss = mu_loss + sigma_loss\n\n        else:\n            pi = self.actor(state)  # pi,Q: (batch_size, len_tr, dim_action)\n            pi_next = self.actor(next_state)\n            Q = self.critic(state)\n            Q_a = Q.gather(1, action.long())\n\n            with torch.no_grad():\n                # calculate Q_ret using Retrace\n                Qt = self.target_critic(state)  # Q_target\n                Qt_next = self.target_critic(next_state)\n                pit = self.target_actor(state)\n\n                Qt_a = Qt.gather(1, action.long())\n                prob_t = pi.gather(\n                    1, action.long()\n                )  # (batch_size * len_tr, 1), target policy probability\n\n                c = torch.clip(\n                    prob_t / (prob_b + 1e-6), max=1.0\n                )  # (batch_size * len_tr, 1), prod of importance ratio and gamma\n\n                if self.critic_loss_type == \"1step_TD\":\n                    Qret = reward + self.gamma * (1 - done) * torch.sum(\n                        pi_next * Qt_next, axis=-1, keepdim=True\n                    )\n                elif self.critic_loss_type == \"retrace\":\n                    Qret = reward + self.gamma * torch.sum(\n                        pi_next * Qt_next, axis=-1, keepdim=True\n                    ) * (1 - done)\n\n                    # temporarily reshaping values\n                    # (batch_size * len_tr, item_dim) -> (batch_size, len_tr, item_dim)\n                    Qret = Qret.view(self.batch_size, -1, *Qret.shape[1:])\n                    Qt_a = Qt_a.view(self.batch_size, -1, *Qt_a.shape[1:])\n                    c = c.view(self.batch_size, -1, *c.shape[1:])\n                    done = done.view(self.batch_size, -1, *done.shape[1:])\n                    for i in reversed(\n                        range(Qret.shape[1] - 1)\n                    ):  # along the trajectory length\n                        Qret[:, i] += (\n                            self.gamma\n                            * c[:, i + 1]\n                            * (Qret[:, i + 1] - Qt_a[:, i + 1])\n                            * (1 - done[:, i])\n                        )\n                    Qret = Qret.view(-1, *Qret.shape[2:])\n\n                pi_old = pit\n\n            critic_loss = F.mse_loss(Q_a, Qret).mean()\n\n            # calculate V, Advantage of Qt\n            Vt = torch.sum(pi_old * Qt, axis=-1, keepdims=True)\n            At = Qt - Vt\n\n            \"\"\" variational distribution q uses exp(At / eta) instead of exp(Qt / eta), for stable learning\"\"\"\n            q = torch.softmax(At / self.eta, axis=-1)\n            actor_loss = -torch.mean(torch.sum(q.detach() * torch.log(pi), axis=-1))\n\n            eta_loss = self.eta * self.eps_eta + self.eta * torch.mean(\n                torch.log(torch.sum(pi_old * torch.exp(At / self.eta), axis=-1))\n            )\n\n            \"\"\"\n            KL-Divergence losses(related to alpha) implemented using methods introduced from V-MPO paper\n            https://arxiv.org/abs/1909.12238\n            \"\"\"\n\n            KLD_pi = pi_old.detach() * (torch.log(pi_old.detach()) - torch.log(pi))\n            KLD_pi = torch.sum(KLD_pi, axis=len(pi_old.shape) - 1)\n            alpha_loss = torch.mean(\n                self.alpha_mu * (self.eps_alpha_mu - KLD_pi.detach())\n                + self.alpha_mu.detach() * KLD_pi\n            )\n\n        loss = critic_loss + actor_loss + eta_loss + alpha_loss\n\n        self.actor_optimizer.zero_grad()\n        self.critic_optimizer.zero_grad()\n        loss.backward()\n        torch.nn.utils.clip_grad_norm_(self.actor.parameters(), self.clip_grad_norm)\n        torch.nn.utils.clip_grad_norm_(self.critic.parameters(), self.clip_grad_norm)\n        self.actor_optimizer.step()\n        self.critic_optimizer.step()\n        self.reset_lgr_muls()\n\n        self.num_learn += 1\n\n        result = {\n            \"actor_loss\": actor_loss.item(),\n            \"critic_loss\": critic_loss.item(),\n            \"eta_loss\": eta_loss.item(),\n            \"alpha_loss\": alpha_loss.item(),\n            \"eta\": self.eta.item(),\n            \"alpha_mu\": self.alpha_mu.item(),\n            \"alpha_sigma\": self.alpha_sigma.item(),\n            \"min_Q\": Q.detach().cpu().numpy().min(),\n            \"max_Q\": Q.detach().cpu().numpy().max(),\n            \"min_At\": At.detach().cpu().numpy().min(),\n            \"max_At\": At.detach().cpu().numpy().max(),\n        }\n\n        return result\n\n    # reset Lagrange multipliers: eta, alpha_{mu, sigma}\n    def reset_lgr_muls(self):\n        self.eta.data = torch.max(self.eta, self.min_eta)\n        self.alpha_mu.data = torch.max(self.alpha_mu, self.min_alpha_mu)\n        self.alpha_sigma.data = torch.max(self.alpha_sigma, self.min_alpha_sigma)\n\n    def update_target(self):\n        self.target_actor.load_state_dict(self.actor.state_dict())\n        self.target_critic.load_state_dict(self.critic.state_dict())\n\n    def save(self, path):\n        print(f\"...Save model to {path}...\")\n        torch.save(\n            {\n                \"actor\": self.actor.state_dict(),\n                \"critic\": self.critic.state_dict(),\n                \"actor_optimizer\": self.actor_optimizer.state_dict(),\n                \"critic_optimizer\": self.critic_optimizer.state_dict(),\n            },\n            os.path.join(path, \"ckpt\"),\n        )\n\n    def load(self, path):\n        print(f\"...Load model from {path}...\")\n        checkpoint = torch.load(os.path.join(path, \"ckpt\"), map_location=self.device)\n        self.actor.load_state_dict(checkpoint[\"actor\"])\n        self.target_actor.load_state_dict(self.actor.state_dict())\n        self.critic.load_state_dict(checkpoint[\"critic\"])\n        self.target_critic.load_state_dict(self.critic.state_dict())\n        self.actor_optimizer.load_state_dict(checkpoint[\"actor_optimizer\"])\n        self.critic_optimizer.load_state_dict(checkpoint[\"critic_optimizer\"])\n\n    def process(self, transitions, step):\n        result = {}\n\n        # Process per step\n        self.memory.store(transitions)\n        delta_t = step - self.time_t\n        self.time_t = step\n\n        if self.memory.size >= self.batch_size and self.time_t >= self.start_train_step:\n            for i in range(self.n_epoch):\n                result = self.learn()\n            self.update_target()\n\n        return result\n\n    def sync_in(self, weights):\n        self.actor.load_state_dict(weights)\n\n    def sync_out(self, device=\"cpu\"):\n        weights = self.actor.state_dict()\n        for k, v in weights.items():\n            weights[k] = v.to(device)\n        sync_item = {\n            \"weights\": weights,\n        }\n        return sync_item\n\n    def interact_callback(self, transition):\n        _transition = {}\n        self.tmp_buffer.append(transition)\n        if len(self.tmp_buffer) == self.n_step:\n            for key in self.tmp_buffer[0].keys():\n                _transition[key] = np.stack([t[key] for t in self.tmp_buffer], axis=1)\n\n        return _transition\n", "meta": {"hexsha": "1cf56df97351c64d1d9d1d63c7600e19847ca40c", "size": 18805, "ext": "py", "lang": "Python", "max_stars_repo_path": "jorldy/core/agent/mpo.py", "max_stars_repo_name": "taechanha/JORLDY", "max_stars_repo_head_hexsha": "7356f7481dbc569bf745353105088d65665a4a51", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jorldy/core/agent/mpo.py", "max_issues_repo_name": "taechanha/JORLDY", "max_issues_repo_head_hexsha": "7356f7481dbc569bf745353105088d65665a4a51", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jorldy/core/agent/mpo.py", "max_forks_repo_name": "taechanha/JORLDY", "max_forks_repo_head_hexsha": "7356f7481dbc569bf745353105088d65665a4a51", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3410041841, "max_line_length": 111, "alphanum_fraction": 0.5509173092, "include": true, "reason": "import numpy", "num_tokens": 4328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.2909808539178129, "lm_q1q2_score": 0.15909033433392994}}
{"text": "#!/usr/bin/env python\n# ~*~ coding: utf8 ~*~\n\"\"\"Find the domain average flux uncertainties.\"\"\"\nfrom __future__ import division, print_function\nimport sys\nimport glob\nimport os.path\nimport datetime\n\nimport numpy as np\nimport dateutil.tz\nimport netCDF4\nimport cf_units\nimport xarray\n\ntry:\n    THIS_DIR = os.path.dirname(__file__)\nexcept NameError:\n    THIS_DIR = os.getcwd()\n\nsys.path.insert(0, os.path.join(\n    THIS_DIR, \"..\", \"src\"))\nsys.path.append(THIS_DIR)\n\nimport atmos_flux_inversion.correlations\nimport atmos_flux_inversion.covariances\nfrom atmos_flux_inversion.util import kronecker_product\nfrom atmos_flux_inversion.linalg import kron\n\n\n############################################################\n# A few utility functions\ndef flush_output_streams():\n    \"\"\"Flush stdout and stderr.\"\"\"\n    sys.stdout.flush()\n    sys.stderr.flush()\n\n\ndef write_progress_message(msg):\n    \"\"\"Write the message to stdout with time.\n\n    Parameters\n    ----------\n    msg: str\n    \"\"\"\n    flush_output_streams()\n    print(datetime.datetime.now(UTC).strftime(\"%c\"), msg)\n    flush_output_streams()\n\n\nUTC = dateutil.tz.tzutc()\nSECONDS_PER_HOUR = 3600\nHOURS_PER_DAY = 24\nDAYS_PER_WEEK = 7\nDAYS_PER_MONTH = 30\n\nDAILY_FLUX_TIMESCALE = 7\nDAILY_FLUX_FUN = \"exp\"\nHOURLY_FLUX_TIMESCALE = 3\nCORRELATION_LENGTH = 1000\nGRID_RESOLUTION = 27\n# I would like to add a fixed minimum at some point.\n# full stds would then be sqrt(fixed^2 + varying^2)\n# average seasonal variation (or some fraction thereof) might work.\n# x2 since MsTMIP spread does not represent full uncertainty\n# x5 since MsTMIP spread only represents monthly values and this uses sub-daily\n# x10 matches model-model for Raczka for 200km/21d (0.68)\n# x4 matches model-model for 1000km/7d (0.65)\nFLUX_VARIANCE_VARYING_FRACTION = 4.\nNC_ENGINE = \"netcdf4\"\nFLUX_UNITS = \"umol/m2/s\"\nFLUX_WINDOW = HOURS_PER_DAY * DAYS_PER_WEEK * 2\n\nOBS_HOURS = (datetime.time(12), datetime.time(16))\n\"\"\"Which observation times will be used in the inversion.\n\nAssumed to be local solar. Should give afternoon hours for the domain.\n\nI really hope I can assume this doesn't depend on latitude. That would\nmake this much more complicated.\n\"\"\"\nOBS_TIMES_PER_DAY = OBS_HOURS[1].hour - OBS_HOURS[0].hour\n\"\"\"Observations used per site per day.\"\"\"\nCO2_MOLAR_MASS = 16 * 2 + 12.01\n\"\"\"Molar mass of CO2 (g/mol).\n\nUsed to convert WRF fluxes to units expected by observation operator.\n\"\"\"\nDAYS_DROPPED_FROM_END = 1\n\"\"\"Currently 1 to avoid problems with lack of fluxes in August.\"\"\"\nOBS_DAYS = 30\nN_REALIZATIONS = 80\n#  1    9m55 (80 realizations)    9m46\n# 30 2h48m40 (80 realizations) 3h56m41\n\"\"\"Number of days of obs to use.\"\"\"\nOBS_WINDOW = OBS_DAYS * OBS_TIMES_PER_DAY\n\"\"\"Number of observation times.\"\"\"\n\n\n############################################################\n# Get grid parameters\n\nFLUX_INTERVAL = 6\n\"\"\"The interval at which fluxes become available in hours.\n\nFluxes are usually integrated forward from hourly input, but I can't\nsolve for that in a reasonable timeframe.\n\nThis determines both the input and the output time resolution as well\nas what the inversion solves for.\n\nNote\n----\nMust divide twenty-four.\n\"\"\"\nINTERVALS_PER_DAY = HOURS_PER_DAY // FLUX_INTERVAL\nFLUX_RESOLUTION = 27\n\"\"\"Resolution of fluxes and influence functions in kilometers.\"\"\"\nUNCERTAINTY_RESOLUTION_REDUCTION_FACTOR = 6\n\"\"\"How much coarser uncertainty is than mean estimate in the x direction.\n\nIf we compute the uncertainty at full resolution, the resulting file\nis huge, starting in the hundreds of terabytes for a month.\nCoarsening the resolution for the uncertainties allows us to still\nreport uncertainties within current computing constraints.\n\"\"\"\n# 4: 2h49 wall 132GiB mem 3h57 cpu\n# 3: 5h11 wall 140GiB mem 6h27 cpu\nUNCERTAINTY_FLUX_RESOLUTION = (UNCERTAINTY_RESOLUTION_REDUCTION_FACTOR *\n                               FLUX_RESOLUTION * 1e3)\n\"\"\"Resolution of posterior uncertainties in meters.\"\"\"\nUNCERTAINTY_TEMPORAL_RESOLUTION = \"2D\"\n\"\"\"The resolution at which the uncertainty is calculated and saved.\n\nHigher resolution means the uncertainties will be more accurate.\n\"\"\"\n\nINFLUENCE_PATHS = [\"/mc1s2/s4/dfw5129/data/LPDM_2010_fpbounds/\"\n                   \"ACT-America_trial5/2010/01/GROUP1\",\n                   \"/mc1s2/s4/dfw5129/data/LPDM_2010_fpbounds/\"\n                   \"candidacy_more_towers/2010/01/GROUP1\"]\nINFLUENCE_FILES = [\n    name\n    for path in INFLUENCE_PATHS\n    for name in glob.glob(os.path.join(\n        path,\n        \"LPDM_2010_01_{flux_interval:02d}hrly_{res:03d}km_molar_footprints.nc4\"\n        .format(flux_interval=FLUX_INTERVAL, res=FLUX_RESOLUTION)))]\n\nTEST_DS = netCDF4.Dataset(INFLUENCE_FILES[0])\n\nNX = len(TEST_DS.dimensions[\"dim_x\"])\nNY = len(TEST_DS.dimensions[\"dim_y\"])\nN_TIMES_BACK = len(TEST_DS.dimensions[\"time_before_observation\"])\n\nN_SITES = len(TEST_DS.dimensions[\"site\"])\nN_OBS_TIMES = len(TEST_DS.dimensions[\"observation_time\"])\n\nTEST_DS.close()\ndel TEST_DS\n\nN_TIMES = INTERVALS_PER_DAY * DAYS_PER_MONTH + FLUX_WINDOW // FLUX_INTERVAL\n\nif N_TIMES_BACK < FLUX_WINDOW / FLUX_INTERVAL:\n    raise ValueError(\"FLUX_WINDOW too long for file\")\n\nN_GRID_POINTS = NY * NX\nSTATE_SIZE = N_GRID_POINTS * FLUX_WINDOW\n\nOBS_VEC_SIZE = N_SITES * OBS_WINDOW\nOBS_VEC_TOTAL_SIZE = N_SITES * N_OBS_TIMES\n\n\nwrite_progress_message(\"Getting covariances\")\nspatial_correlations = (\n    atmos_flux_inversion.correlations.HomogeneousIsotropicCorrelation.\n    from_function(\n        atmos_flux_inversion.correlations.ExponentialCorrelation(\n            CORRELATION_LENGTH / GRID_RESOLUTION),\n        (NY, NX),\n        is_cyclic=False))\nwrite_progress_message(\"Have spatial correlations\")\n\nhour_correlations = (\n    atmos_flux_inversion.correlations.HomogeneousIsotropicCorrelation.\n    from_function(\n        atmos_flux_inversion.correlations.ExponentialCorrelation(\n            HOURLY_FLUX_TIMESCALE / FLUX_INTERVAL),\n        (INTERVALS_PER_DAY,),\n        is_cyclic=True))\nhour_correlations_matrix = hour_correlations.dot(np.eye(\n    hour_correlations.shape[0]))\nwrite_progress_message(\"Have hourly correlations\")\nday_correlations = (\n    atmos_flux_inversion.correlations.make_matrix(\n        atmos_flux_inversion.correlations.ExponentialCorrelation(\n            DAILY_FLUX_TIMESCALE\n        ),\n        (N_TIMES // INTERVALS_PER_DAY,)))\nwrite_progress_message(\"Have daily correlations\")\ntemporal_correlations = kron(day_correlations,\n                             hour_correlations_matrix)\nwrite_progress_message(\"Have temporal correlations\")\n\nfull_correlations = kronecker_product(\n    temporal_correlations,\n    spatial_correlations)\nwrite_progress_message(\"Have combined correlations\")\nflux_std_pattern = xarray.open_dataset(\n    \"../data_files/2010_MsTMIP_flux_std.nc4\",\n    engine=NC_ENGINE\n).get(\n    [\"E_TRA{:d}\".format(i + 1) for i in range(1)]\n).sel(\n    Time=slice(\"2010-07-01\", \"2010-07-30\")\n).mean(\n    dim=\"Time\",\n    keep_attrs=True,\n)\n\n# Ensure units work out\nfor flux_part in flux_std_pattern.data_vars.values():\n    unit = (cf_units.Unit(flux_part.attrs[\"units\"]))\n    if unit is not FLUX_UNITS:\n        flux_part *= unit.convert(1, FLUX_UNITS)\n        flux_part.attrs[\"units\"] = str(FLUX_UNITS)\n\nreduced_flux_stds = (\n    FLUX_VARIANCE_VARYING_FRACTION *\n    flux_std_pattern[\"E_TRA1\"].data)\nwrite_progress_message(\"Have standard deviations\")\n\nspatial_covariance = (\n    atmos_flux_inversion.covariances.CorrelationStandardDeviation(\n        spatial_correlations, reduced_flux_stds\n    )\n)\nwrite_progress_message(\"Have full spatial covariance\")\n\nprior_covariance = kronecker_product(\n    temporal_correlations,\n    spatial_covariance)\n\naverager = np.full(\n    prior_covariance.shape[0], 1. / prior_covariance.shape[0], dtype=np.float32\n)\n\nwrite_progress_message(\"Getting mean covariance for all\")\ncov_of_avg = averager.dot(prior_covariance.dot(averager))\nwrite_progress_message(\"Got mean covariance for all\")\n\nwrite_progress_message(\"Covariance is {0:5.3f}\\nStandard Deviation: {1:5.3f}\"\n                       .format(cov_of_avg, np.sqrt(cov_of_avg)))\n", "meta": {"hexsha": "f1960aba4ce4dcb03627c6d4c13bd1d3abce799d", "size": 7991, "ext": "py", "lang": "Python", "max_stars_repo_path": "paper2020/compare_prior_covariance_continental_values.py", "max_stars_repo_name": "DWesl/atmospheric-inverse-methods-for-flux-optimization", "max_stars_repo_head_hexsha": "f8a3e8564dc3bf86df297a0683a2a52c657289d4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-04-20T20:14:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T16:49:58.000Z", "max_issues_repo_path": "paper2020/compare_prior_covariance_continental_values.py", "max_issues_repo_name": "DWesl/atmospheric-inverse-methods-for-flux-optimization", "max_issues_repo_head_hexsha": "f8a3e8564dc3bf86df297a0683a2a52c657289d4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-03-06T02:03:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-04T17:07:12.000Z", "max_forks_repo_path": "paper2020/compare_prior_covariance_continental_values.py", "max_forks_repo_name": "DWesl/atmospheric-inverse-methods-for-flux-optimization", "max_forks_repo_head_hexsha": "f8a3e8564dc3bf86df297a0683a2a52c657289d4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-31T12:57:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-31T12:57:29.000Z", "avg_line_length": 31.4606299213, "max_line_length": 79, "alphanum_fraction": 0.7357026655, "include": true, "reason": "import numpy", "num_tokens": 2037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.1589874781452715}}
{"text": "# _*_ coding: utf-8 _*_\n\nimport tensorflow as tf\nfrom tensorflow.python.ops.rnn_cell_impl import BasicLSTMCell, RNNCell\nfrom tensorflow.python.ops.rnn_cell_impl import LSTMStateTuple\nimport numpy as np\n\n\n'''\n本欲想调整LatticeLSTM, 使其不依赖于固定的batch_size，但由于Lattice内部Cell的参数需要指定Shape，\n而与batch_size对应的Shape在后续融合相关信息时，具有明显的实际意义，每个词汇对字符的贡献统计，\n这也造成了本模型适用于处理批处理任务，对单个任务需进行调整后再处理较合适。\n\n对于引入外部知识，以便对LSTM进行变形来说，应该是一种折中平衡吧。\n'''\n\n\nclass CharLSTM(BasicLSTMCell):\n    def __init__(self, lexicon_num_units, dtype, batch_size,\n                 reuse=None, name=None, **kwargs):\n        super(CharLSTM, self).__init__(reuse=reuse, name=name, **kwargs)\n        self._lexicon_num_units = lexicon_num_units\n        self._dtype = dtype\n        self._char_state_tensor = tf.Variable(tf.zeros(shape=[batch_size, self._num_units]),\n                                              dtype=self._dtype,\n                                              trainable=False)\n\n    def build(self, inputs_shape):\n        # inputs_shape should be in the shape of [batch_size, char_embedding_size]\n        if inputs_shape[-1].value is None:\n            raise ValueError(\"Expected inputs.shape[-1] to be known, saw shape: %s\" % inputs_shape)\n\n        input_depth = inputs_shape[-1].value\n        h_depth = self._num_units\n        lexicon_state_depth = self._lexicon_num_units\n\n        self._kernel = self.add_variable(name='multi_input_kernel',\n                                         shape=[input_depth + h_depth, 4 * self._num_units])\n        self._bias = self.add_variable(name='multi_input_bias',\n                                       shape=[4 * self._num_units],\n                                       initializer=tf.zeros_initializer(dtype=self._dtype))\n\n        self._linking_kernel = self.add_variable(name='linking_kernel',\n                                                 shape=[input_depth + lexicon_state_depth,\n                                                        self._num_units])\n        self._linking_bias = self.add_variable(name='linking_bias',\n                                               shape=[self._num_units],\n                                               initializer=tf.zeros_initializer(dtype=self._dtype))\n        self.built = True\n\n    def call(self, inputs, state):\n        char_inputs = inputs[0]   # shape = [batch_size, input_dimension]\n        state_inputs = inputs[1]  # shape = [batch_size, max_num_of_lexicon words, lexicon_state_dimension]\n\n        # check whether the last dimension of state_inputs are all zero.\n        # check_state_0 should be in the shape of [batch_size, max_num_of_lexicon words]\n        check_state_0 = tf.reduce_sum(state_inputs, axis=-1)\n        # check_state_1 should be in the shape of [batch_size]\n        check_state_1 = tf.reduce_sum(check_state_0, axis=-1)\n\n        # 查找匹配含有词汇的索引，只处理该部分信息，避免较多无词库匹配的信息参与计算消耗资源\n        # state_inputs_indices_for_lexicon should be in the shape of [batch_size, 2]\n        state_inputs_indices_for_lexicon = tf.where(tf.not_equal(check_state_0, 0))\n\n        # 查找不含有词汇的索引，避免较多无词库匹配的信息参与计算消耗资源\n        # tf.where(tf.equal(check_state_1, 0)) should be in the shape of [batch_size, 1]\n        # state_inputs_indices_for_not_lexicon should be in the shape of [batch_size]\n        state_inputs_indices_for_not_lexicon = tf.squeeze(tf.where(tf.equal(check_state_1, 0)))\n\n        # 对不含词汇的细胞状态进行选择，主要是针对标量数据，因其秩为0，需进行维度扩展\n        # in case `[i]` is squeezed to scalar `i`, change it back to 1-dimension tensor `[i]` by `tf.expand_dims()`\n        # otherwise, `[]` and `[i, j]` will remain as-is after tf.squeeze() and further conversion on it\n        state_inputs_indices_for_not_lexicon = tf.cond(pred=tf.equal(tf.rank(state_inputs_indices_for_not_lexicon), 0),\n                                                       true_fn=lambda: tf.expand_dims(\n                                                           state_inputs_indices_for_not_lexicon, axis=0),\n                                                       false_fn=lambda: state_inputs_indices_for_not_lexicon)\n\n        # 含有词汇匹配的字符索引\n        # char_inputs_indices_for_lexicon should be in the shape of [batch_size, 1]\n        char_inputs_indices_for_lexicon = tf.where(tf.not_equal(check_state_1, 0))\n\n        # 不含有词汇匹配的字符索引\n        # char_inputs_indices_for_not_lexicon should be in the shape of [batch_size, 1]\n        char_inputs_indices_for_not_lexicon = tf.where(tf.equal(check_state_1, 0))\n\n        if self._state_is_tuple:\n            c, h = state\n        else:\n            c, h = tf.split(value=state, num_or_size_splits=2, axis=1)\n\n        # tf.concat([char_inputs, h], 1) should be in the shape of\n        # [batch_size, char_embedding_size + state_dimension]\n        # h should be in the shape of [batch_size, state_dimension]\n        # self._kernel should be in the shape of [char_embedding_size + state_dimension, X]\n        # gate_inputs should be in the shape of [batch_size, 4 * state_dimension]\n        gate_inputs = tf.matmul(tf.concat([char_inputs, h], 1), self._kernel)\n        gate_inputs = tf.nn.bias_add(gate_inputs, self._bias)\n\n        i, j, f, o = tf.split(value=gate_inputs, num_or_size_splits=4, axis=1)\n\n        new_c_without_lexicon = self._new_c_without_lexicon(i=i, f=f, j=j, c=c,\n                                                            indices_tensor=state_inputs_indices_for_not_lexicon)\n        new_c = tf.scatter_nd_update(self._char_state_tensor,\n                                     indices=char_inputs_indices_for_not_lexicon,\n                                     updates=new_c_without_lexicon)\n\n        new_c = tf.cond(tf.not_equal(tf.shape(state_inputs_indices_for_not_lexicon)[-1],\n                                     tf.shape(state_inputs)[0]),\n                        true_fn=lambda: self._if_not_empty_lexicon_state(i, j, char_inputs, state_inputs,\n                                                                         char_inputs_indices_for_lexicon,\n                                                                         state_inputs_indices_for_lexicon,\n                                                                         new_c),\n                        false_fn=lambda: new_c)\n\n        # 计算输出隐状态\n        new_h = tf.multiply(self._activation(new_c), tf.nn.sigmoid(o))\n\n        if self._state_is_tuple:\n            new_state = LSTMStateTuple(new_c, new_h)\n        else:\n            new_state = tf.concat([new_c, new_h], 1)\n\n        return new_h, new_state\n\n    def _new_c_without_lexicon(self, i, f, j, c, indices_tensor):\n        # indices_tensor should be in the shape of [batch_size]\n        f_without_lexicon_state_input = tf.gather(f, indices=indices_tensor)\n        i_without_lexicon_state_input = tf.gather(i, indices=indices_tensor)\n        j_without_lexicon_state_input = tf.gather(j, indices=indices_tensor)\n        # j_without_lexicon_state_input should be in the shape of [batch_size]\n\n        # 运行常规LSTM描述逻辑\n        forget_bias_tensor = tf.constant(self._forget_bias, dtype=f.dtype)\n        new_c_without_lexicon_state = tf.add(\n            tf.multiply(c, tf.nn.sigmoid(tf.add(f_without_lexicon_state_input,\n                                                forget_bias_tensor))),\n            tf.multiply(tf.nn.sigmoid(i_without_lexicon_state_input),\n                        self._activation(j_without_lexicon_state_input)))\n\n        return new_c_without_lexicon_state\n\n    def _new_c_with_lexicon(self, i, j, char_inputs, state_inputs, indices_tensor):\n        # char_inputs should be in the shape of [batch_size, char_embedding]\n        # state_inputs should be in the shape of\n        # [batch_size, max_num_of_lexicon words, lexicon_state_dimension]\n        # indices_tensor is state_inputs_indices_for_lexicon, should be in the shape of [batch_size]\n        char_inputs_with_lexicon_state = tf.gather_nd(char_inputs, indices=[indices_tensor])\n\n        # 提取指定索引下的词汇状态信息\n        # lexicon_state_inputs should be in the shape of [max_num_of_lexicon words, lexicon_state_dimension]\n        lexicon_state_inputs = tf.gather_nd(state_inputs, indices=indices_tensor)\n\n        i_with_lexicon_state_input = tf.gather_nd(i, indices=[indices_tensor])\n        j_with_lexicon_state_input = tf.gather_nd(j, indices=[indices_tensor])\n\n        # 常规输入门操作\n        state_input_gate = tf.matmul(tf.concat([char_inputs_with_lexicon_state,\n                                                lexicon_state_inputs], axis=-1),\n                                     self._linking_kernel)\n        state_input_gate = tf.nn.sigmoid(tf.nn.bias_add(state_input_gate, self._linking_bias))\n\n        # 为了后面评估子词库对字符的贡献概率，引入了额外的门控单元 state_char_input_gate\n        state_char_input_gate = tf.concat([state_input_gate,\n                                           tf.nn.sigmoid(i_with_lexicon_state_input)], axis=1)\n\n        # softmax 评估子词库对字符的贡献概率\n        state_gate_weights, char_gate_weight = tf.split(\n            tf.nn.softmax(state_char_input_gate, axis=0),\n            num_or_size_splits=[tf.shape(lexicon_state_inputs)[0], 1],\n            axis=1)\n\n        # 常规LSTM操作\n        new_c_with_lexicon_state = tf.add(\n            tf.reduce_sum(tf.multiply(state_gate_weights, lexicon_state_inputs), axis=0),\n            tf.multiply(char_gate_weight, j_with_lexicon_state_input))\n\n        return new_c_with_lexicon_state\n\n    def _if_not_empty_lexicon_state(self, i, j,\n                                    char_inputs, state_inputs,\n                                    char_inputs_indices_for_lexicon,\n                                    state_inputs_indices_for_lexicon, new_c_in):\n        new_c_with_lexicon = self._new_c_with_lexicon(i=i, j=j,\n                                                      char_inputs=char_inputs,\n                                                      state_inputs=state_inputs,\n                                                      indices_tensor=state_inputs_indices_for_lexicon)\n        # 根据新生成的含词库信息的字符状态更新字符的细胞状态\n        new_c_out = tf.scatter_nd_update(new_c_in,\n                                         indices=char_inputs_indices_for_lexicon,\n                                         updates=new_c_with_lexicon)\n\n        return new_c_out\n\n\nclass LexiconLSTM(BasicLSTMCell):\n    def __init__(self, dtype, reuse=None, name=None, **kwargs):\n        super(LexiconLSTM, self).__init__(reuse=reuse, name=name, **kwargs)\n        self._dtype = dtype\n\n    def build(self, inputs_shape):\n        if inputs_shape[-1].value is None:\n            raise ValueError(\"Expected inputs.shape[-1] to be known, saw shape: %s\" % inputs_shape)\n\n        input_depth = inputs_shape[-1].value\n        h_depth = self._num_units\n\n        # 需要指出此处的超参数3与LatticeLSTM构成某种对应关系\n        self._kernel = self.add_variable(name='lexicon_kernel',\n                                         shape=[input_depth + h_depth, 3 * self._num_units])\n        self._bias = self.add_variable(name='lexicon_bias',\n                                       shape=[3 * self._num_units],\n                                       initializer=tf.zeros_initializer(dtype=self._dtype))\n        self.built = True\n\n    def call(self, inputs, state):\n        sigmoid = tf.nn.sigmoid\n        add = tf.add\n        multiply = tf.multiply\n\n        if self._state_is_tuple:\n            c, h = state\n        else:\n            c, h = tf.split(value=state, num_or_size_splits=2, axis=1)\n\n        gate_inputs = tf.matmul(tf.concat([inputs, h], 1), self._kernel)\n        gate_inputs = tf.nn.bias_add(gate_inputs, self._bias)\n\n        i, j, f = tf.split(value=gate_inputs, num_or_size_splits=3, axis=1)\n\n        forget_bias_tensor = tf.constant(self._forget_bias, dtype=f.dtype)\n\n        new_c = add(multiply(c, sigmoid(add(f, forget_bias_tensor))),\n                    multiply(sigmoid(i), self._activation(j)))\n        return new_c\n\n\nclass LatticeLSTMCell(RNNCell):\n    ''' inherit from: tf.nn.rnn_cell.RNNCell\n        Lattice Long short-term memory unit recurrent network cell. the implementation is based on\n        https://arxiv.org/pdf/1805.02023.pdf\n        Please be noted that LatticeLSTMCell should be called within tf.nn.dynamic_rnn\n    '''\n    def __init__(self, char_num_units, lexicon_num_units, batch_size, max_lexicon_words_num,\n                 word_length_tensor, seq_len, dtype, **kwargs):\n        super(LatticeLSTMCell, self).__init__(**kwargs)\n        '''        \n        Parameters\n        ----------\n        char_num_units: int\n            the num_units of char_lstm cell units. \n            this is expected to be the same as lexicon_num_units by the paper.\n\n        lexicon_num_units: int\n            the num_units of lexicon_lstm cell units. \n            this is expected to be the same as char_num_units by the paper.\n\n        max_lexicon_words_num: int\n            the upper bound of the lexicon words per characters. \n\n        batch_size: int\n            batch_size of the input data\n\n        seq_len: int\n            sequence_length of the input data\n\n        dtype:\n            data type defined for LatticeLSTMCell variable\n\n        word_length_tensor: tensor\n            tensor, it contains a batch of lexicon word length. \n            this should be padded with 0 if there is matched\n            lexicon word for the respective character.\n            example:  char： 南 京 市 長 江 大 橋\n                      word： 南京 市長\n                      max_lexicon_words_num = 5\n            then the word length tensor should be like tf.constant([[[2,0,0,0,0],  \n                                                                     [0,0,0,0,0],\n                                                                     [2,0,0,0,0],\n                                                                     [0,0,0,0,0],\n                                                                     [0,0,0,0,0],\n                                                                     [0,0,0,0,0],\n                                                                     [0,0,0,0,0]]], \n                                                                   dtype=tf.float32)\n        '''\n        # 简要描述逻辑：先针对字符，以该字符结束匹配词库中词汇信息，最大词汇个数为 max_lexicon_words_num\n        # 然后计算匹配的词汇对该字符的贡献，并融入在字符的细胞状态中；\n        # 其中为了加快计算逻辑，对含有词汇的字符与不含有词汇的字符进行了分离，\n        # 此外为了对LSTM进行变种计算，进行了数据的堆叠计算工作.\n        self._char_lstm = CharLSTM(dtype=dtype,\n                                   num_units=char_num_units,\n                                   batch_size=batch_size,\n                                   lexicon_num_units=lexicon_num_units,\n                                   name='character_lstm')\n\n        self._lexicon_lstm = LexiconLSTM(dtype=dtype,\n                                         num_units=lexicon_num_units,\n                                         name='lexicon_word_lstm')\n\n        # word_length_tensor should be in the shape of [batched_size, seq_len, max_lexicon_words_num]\n        self.word_length_tensor = word_length_tensor\n        self.max_lexicon_words_num = max_lexicon_words_num\n        self.seq_len = seq_len\n        self.time_step = 0\n        self._dtype = dtype\n\n        lexicon_state_init_value = tf.zeros(shape=[batch_size, self.seq_len,\n                                                   self.max_lexicon_words_num,\n                                                   lexicon_num_units])\n\n        # lexicon_state_tensor should be in the shape of\n        # [batch_size, seq_len, max_lexicon_words_num, state_dimension]\n        self.lexicon_state_tensor = tf.Variable(initial_value=lexicon_state_init_value,\n                                                trainable=False,\n                                                dtype=self._dtype)\n\n    def build(self, inputs_shape):\n        # inputs shape should be in the shape\n        # [[batch_size, char_embedding_size],\n        #  [batch_size, max_lexicon_words_num, lexicon_word_embedding_size]]\n\n        self._char_lstm.build(inputs_shape[0])\n        self._lexicon_lstm.build(inputs_shape[1])\n        self.lexicon_shape = inputs_shape[1]\n\n        if self.lexicon_shape[1] != self.max_lexicon_words_num:\n            raise ValueError('max_lexicon_words_num should be equal to lexicon input')\n\n        self.built = True\n\n    @property\n    def state_size(self):\n        return self._char_lstm.state_size\n\n    @property\n    def output_size(self):\n        return self._char_lstm.output_size\n\n    def zero_state(self, batch_size, dtype):\n        return self._char_lstm.zero_state(batch_size, dtype)\n\n    def call(self, inputs, state):\n        '''\n        Parameters\n        ----------\n        inputs: list of tensors\n            inputs here should be a tensors of character_inputs(character embedding inputs) and\n            lexicon_inputs(lexicon word embedding inputs). char_embedding_inputs has shape [batch_size, char_embedding_size]\n            lexicon_embedding_inputs has shape [batch_size, max_lexicon_words_num, lexicon_word_embedding_size]\n            please be noted that number of lexicon words is expect to be upper bounded. so if the number of words\n            for a character is less than max_lexicon_words_num, the word embedding inputs should be padded with zero.\n            example: inputs = [char_embedding_inputs, word_embedding_inputs]\n\n        state: tensors\n            Either a single 2-D tensor, or a tuple of tensors matching the arity and shapes of state.\n\n        Returns\n        -------\n        output: tensor\n            tensor of hidden output of character units with shape [batch_size, self.output_size]\n\n        new_state: tensor or a tuple of tensors\n            Either a single 2-D tensor, or a tuple of tensors matching the arity and shapes of state.\n        '''\n        char_input = inputs[0]      # shape = [batch_size, char_embedding_size]\n        lexicon_inputs = inputs[1]  # shape = [batch_size, max_lexicon_words_num, lexicon_word_embedding_size]\n\n        # 根据时间步获取对应词库状态, 其中 self.lexicon_state_tensor 会迭代更新\n        # lexicon_state_tensor should be in the shape of [batch_size, max_lexicon_words_num, state_dimension]\n        lexicon_state_tensor = tf.gather(self.lexicon_state_tensor, axis=1, indices=self.time_step)\n        char_hidden_output, char_state = self._char_lstm.call([char_input, lexicon_state_tensor], state)\n\n        # max_lexicon_words_num可视作局部字符的time_step\n        # 经过融合处理后，作为字符融合了词库的过程\n        for word_index in range(self.max_lexicon_words_num):\n            self.lexicon_state_tensor = self._update_lexicon_state_per_word(lexicon_inputs=lexicon_inputs,\n                                                                            word_index=word_index,\n                                                                            char_state=char_state)\n\n        self.time_step = self.time_step + 1  # time_step 向后推进\n\n        # reset the lexicon_state_tensor after finish a loop, 一个循环后进行重置\n        self.lexicon_state_tensor = tf.cond(tf.equal(tf.mod(self.time_step, self.seq_len - 1), 0),\n                                            true_fn=lambda: tf.assign(ref=self.lexicon_state_tensor,\n                                                                      value=tf.zeros_like(\n                                                                          self.lexicon_state_tensor)),\n                                            false_fn=lambda: self.lexicon_state_tensor)\n\n        self.time_step = np.remainder(self.time_step, self.seq_len - 1)  # 求模以便重置\n\n        return char_hidden_output, char_state\n\n    def _update_lexicon_state_per_word(self, lexicon_inputs, word_index, char_state):\n        # 根据词索引获取对应对应词库值\n        # lexicon_inputs should be in the shape of\n        # [batch_size, max_lexicon_words_num, lexicon_word_embedding_size]\n\n        # lexicon_input_per_word should be in the shape of [batch_size, state_dimension]\n        lexicon_input_per_word = tf.gather(lexicon_inputs, axis=1, indices=word_index)\n\n        # 根据时间步获取对应词长度\n        # self.word_length_tensor should be in the shape of [batch_size, seq_len, max_lexicon_words_num]\n        # word_length_per_time_step should be in the shape of [batch_size, max_lexicon_words_num]\n        word_length_per_time_step = tf.gather(self.word_length_tensor, axis=1, indices=self.time_step)\n\n        # 根据词索引获取对应时间步 词长度中的对应值, 即一个整数描述词汇的长度\n        # word_length should be in the shape of [batch_size]\n        word_length = tf.gather(word_length_per_time_step, axis=1, indices=word_index)\n\n        # 引入char_state 为了与该字符进行关联，并根据依据索引变化的 lexicon_input_per_word 词库调整词库状态\n        # lexicon_state should be in the shape of [batch_size, state_dimension]\n        lexicon_state = self._lexicon_lstm.call(lexicon_input_per_word, char_state)\n\n        # temp_lexicon_state_to_char_index should be an integer, 词库中词汇长度字符进行映射，经分词后词汇长度会不一致\n        temp_lexicon_state_to_char_index = self.time_step + word_length - 1\n\n        # 通过判断词汇长度不为0，获取对应的状态索引值，并组织为 batch_size 个数据\n        # not equal result should be an bool, assert the match state\n        # lexicon_state_index should be in the shape of [batch_size, 1]\n        lexicon_state_index = tf.where(tf.not_equal(temp_lexicon_state_to_char_index,\n                                                    self.time_step - 1))\n\n        # 根据词库匹配命中的索引值，提取相应的索引值，每个对应一个索引，并组织为 batch_size 个数据\n        # lexicon_state_to_char_index should be in the shape of [batch_size]\n        lexicon_state_to_char_index = tf.gather_nd(temp_lexicon_state_to_char_index,\n                                                   indices=lexicon_state_index)\n\n        # 根据词汇长度的索引，提取对应的词库状态值，只针对词库长度不为0进行处理\n        # lexicon_state_update should be in the shape of [batch_size, state_dimension]\n        lexicon_state_update = tf.gather_nd(lexicon_state, indices=lexicon_state_index)\n\n        # 根据词汇匹配索引值，在词汇大小方向上扩展并设置为1\n        # word_index_for_stack should be in the shape of [batch_size]\n        word_index_for_stack = tf.ones_like(lexicon_state_to_char_index) * word_index\n\n        # word_index_for_stack should be in the shape of [batch_size]\n        # tf.squeeze(lexicon_state_index)将剔除列方向上的维度\n        lexicon_state_index_for_stack = tf.cast(tf.squeeze(lexicon_state_index), dtype=self._dtype)\n\n        # 堆叠的逻辑，实际描述同一个逻辑，可理解为递进描述\n        # indices should be in the shape of [batch_size, 3]\n        # 此处采用堆叠3个向量与LexiconLSTM 中kernel与bias中超参数3保持一致，\n        # 并与tf.split中的超参数3保持一致，即后续向量能被整除\n        indices = tf.stack([lexicon_state_index_for_stack,   # 长度不为0的词汇对应的索引\n                            lexicon_state_to_char_index,     # 提取长度不为0的词汇对应的索引\n                            word_index_for_stack], axis=-1)  # 词汇长度对应的索引扩展后设置为1\n\n        # updated_lexicon_state_tensor should be in the shape of\n        # [batch_size, seq_len, max_lexicon_words_num, state_dimension]\n        updated_lexicon_state_tensor = tf.scatter_nd_update(ref=self.lexicon_state_tensor,\n                                                            indices=tf.cast(indices, dtype=tf.int32),\n                                                            updates=lexicon_state_update)\n        return updated_lexicon_state_tensor\n", "meta": {"hexsha": "a8ab2e8575dc00c4508e5513e7dedd3516c581c6", "size": 22832, "ext": "py", "lang": "Python", "max_stars_repo_path": "tf_kit/lattice/core/cell/lattice_lstm.py", "max_stars_repo_name": "lyssym/NER-toolkits", "max_stars_repo_head_hexsha": "c6368c6fa33761cf6b82e4616cc6705aad052130", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-18T07:22:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-18T07:22:57.000Z", "max_issues_repo_path": "tf_kit/lattice/core/cell/lattice_lstm.py", "max_issues_repo_name": "lyssym/NER-toolkits", "max_issues_repo_head_hexsha": "c6368c6fa33761cf6b82e4616cc6705aad052130", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tf_kit/lattice/core/cell/lattice_lstm.py", "max_forks_repo_name": "lyssym/NER-toolkits", "max_forks_repo_head_hexsha": "c6368c6fa33761cf6b82e4616cc6705aad052130", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-06-18T07:22:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-28T07:49:34.000Z", "avg_line_length": 50.4017660044, "max_line_length": 124, "alphanum_fraction": 0.6098896286, "include": true, "reason": "import numpy", "num_tokens": 5625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117165898111866, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.15898747678417163}}
{"text": "import os\nimport subprocess\nimport numpy as np\nimport pandas as pd\nimport tempfile\n\nBACKGROUND_FREQS = np.array([0.25, 0.25, 0.25, 0.25])\nDATABASE_PATH = \"/users/amtseng/tfmodisco/data/processed/motif_databases/HOCOMOCO_JASPAR_motifs.txt\"\n\ndef import_database_pfms(database_path):\n    \"\"\"\n    Imports the database of PFMs by reading through the entire database and\n    constructing a dictionary mapping motif IDs to NumPy arrays of PFMs.\n    \"\"\"\n    motif_dict = {}\n    with open(database_path, \"r\") as f:\n        try:\n            while True:\n                line = next(f)\n                if line.startswith(\"MOTIF\"):\n                    key = line.strip().split()[1]\n                    header = next(f)\n                    motif_width = int(header.split()[5])\n                    motif = np.empty((motif_width, 4))\n                    for i in range(motif_width):\n                        motif[i] = np.array([\n                            float(x) for x in next(f).strip().split()\n                        ])\n                    motif_dict[key] = motif\n        except StopIteration:\n            pass\n    return motif_dict\n\n\ndef export_pfms_to_meme_format(\n    pfms, outfile, background_freqs=None, names=None\n):\n    \"\"\"\n    Exports a set of PFMs to MEME motif format. Includes the background\n    frequencies `BACKGROUND_FREQS`.\n    Arguments:\n        `pfms`: a list of L x 4 PFMs (where L can be different for each PFM)\n        `outfile`: path to file to output the MEME-format PFMs\n        `background_freqs`: background frequencies of A, C, G, T as a length-4\n            NumPy array; defaults to `BACKGROUND_FREQS`\n        `names`: if specified, a list of unique names to give to each PFM, must\n            be parallel to `pfms`\n    \"\"\"\n    if names is None:\n        names = [str(i) for i in range(len(pfms))]\n    else:\n        assert len(names) == pfms\n        assert len(names) == len(np.unique(names))\n    if background_freqs is None:\n        background_freqs = BACKGROUND_FREQS\n\n    os.makedirs(os.path.dirname(outfile), exist_ok=True)\n    with open(outfile, \"w\") as f:\n        f.write(\"MEME version 5\\n\\n\")\n        f.write(\"ALPHABET= ACGT\\n\\n\")\n        f.write(\"Background letter frequencies\\n\")\n        f.write(\"A %f C %f G %f T %f\\n\\n\" % tuple(background_freqs))\n        for i in range(len(pfms)):\n            pfm, name = pfms[i], names[i]\n            f.write(\"MOTIF %s\\n\" % name)\n            f.write(\"letter-probability matrix:\\n\")\n            for row in pfm:\n                f.write(\" \".join([str(freq) for freq in row]) + \"\\n\")\n            f.write(\"\\n\")\n\n\ndef run_tomtom(\n    query_motif_file, target_motif_file, outdir, show_output=True\n):\n    \"\"\"\n    Runs TOMTOM given the target and query motif files. The default threshold\n    of q < 0.5 is used to filter for matches.\n    Arguments:\n        `query_motif_file`: file containing motifs in MEME format, which will\n            be the query motifs for which matches are found\n        `target_motif_file`: file containing motifs in MEME format, which will\n            be used to search for matches\n        `outdir`: path to directory to store results\n        `show_output`: whether or not to show TOMTOM output\n    \"\"\"\n    comm = [\"tomtom\"]\n    comm += [query_motif_file, target_motif_file]\n    comm += [\"-oc\", outdir]\n    comm += [\"-no-ssc\"]\n    comm += [\"-dist\", \"pearson\"]\n    comm += [\"-min-overlap\", \"5\"]\n    proc = subprocess.run(comm, capture_output=(not show_output))\n\n\ndef import_tomtom_results(tomtom_dir):\n    \"\"\"\n    Imports the TOMTOM output directory as a Pandas DataFrame.\n    Arguments:\n        `tomtom_dir`: TOMTOM output directory, which contains the output file\n            \"tomtom.tsv\"\n    Returns a Pandas DataFrame.\n    \"\"\"\n    return pd.read_csv(\n        os.path.join(tomtom_dir, \"tomtom.tsv\"), sep=\"\\t\", header=0,\n        index_col=False, comment=\"#\"\n    )\n\n\ndef match_motifs_to_targets(\n    query_pfms, target_pfms, temp_dir=None, show_tomtom_output=False\n):\n    \"\"\"\n    For each motif in the query PFMs, finds the best match to the target PFMs,\n    based on TOMTOM q-value.\n    Arguments:\n        `query_pfms`: list of L x 4 PFMs to look for matches for\n        `target_pfms`: list of L x 4 PFMs to match to\n        `temp_dir`: a temporary directory to store intermediates; defaults to\n            a randomly created directory\n        `show_tomtom_output`: whether to show TOMTOM output when running\n    Returns an array of indices parallel to `query_pfms`, where each index is\n    denotes the best PFM within `target_pfms` that matches the query PFM. If\n    a good match is not found (i.e. based on TOMTOM's threshold), the index will\n    be -1.\n    \"\"\"\n    if temp_dir is None:\n        temp_dir_obj = tempfile.TemporaryDirectory()\n        temp_dir = temp_dir_obj.name\n    else:\n        temp_dir_obj = None\n\n    # Convert motifs to MEME format\n    query_motif_file = os.path.join(temp_dir, \"query_motifs.txt\")\n    target_motif_file = os.path.join(temp_dir, \"target_motifs.txt\")\n    export_pfms_to_meme_format(query_pfms, query_motif_file)\n    export_pfms_to_meme_format(target_pfms, target_motif_file)\n\n    # Run TOMTOM\n    tomtom_dir = os.path.join(temp_dir, \"tomtom\")\n    run_tomtom(\n        query_motif_file, target_motif_file, tomtom_dir,\n        show_output=show_tomtom_output\n    )\n\n    # Find results, mapping each query motif to target index\n    # The query/target IDs are the indices\n    tomtom_table = import_tomtom_results(tomtom_dir)\n    match_inds = []\n    for i in range(len(query_pfms)):\n        rows = tomtom_table[tomtom_table[\"Query_ID\"] == i]\n        if rows.empty:\n            match_inds.append(-1)\n            continue\n        target_id = rows.loc[rows[\"q-value\"].idxmin()][\"Target_ID\"]\n        match_inds.append(target_id)\n\n    if temp_dir_obj is not None:\n        temp_dir_obj.cleanup()\n\n    return np.array(match_inds)\n        \n\ndef match_motifs_to_database(\n    query_pfms, top_k=5, temp_dir=None, database_path=DATABASE_PATH,\n    show_tomtom_output=False\n):\n    \"\"\"\n    For each motif in the query PFMs, finds the best matches to the TOMTOM\n    database, ranked by TOMTOM q-value.\n    Arguments:\n        `query_pfms`: list of L x 4 PFMs to look for matches for\n        `top_k`: the number of motifs to return based on q-value\n        `temp_dir`: a temporary directory to store intermediates; defaults to\n            a randomly created directory\n        `database_path`: the path to a TOMTOM motif database; defaults to\n            DATABASE_PATH\n        `show_tomtom_output`: whether to show TOMTOM output when running\n    Returns a list of lists of (motif name, motif PFM, q-value) tuples\n    parallel to `query_pfms`, where each sublist of tuples is the set of motif\n    names, motif PFMs (as NumPy arrays), and q-values for the corresponding\n    query motif. Each sublit is sorted in ascending order by q-value. If fewer\n    than `top_k` matches are found (based on TOMTOM's threshold), the returned\n    sublist will be shorter (and may even be empty).\n    \"\"\"\n    # First, import the database PFMs\n    database_pfms = import_database_pfms(database_path)\n\n    if temp_dir is None:\n        temp_dir_obj = tempfile.TemporaryDirectory()\n        temp_dir = temp_dir_obj.name\n    else:\n        temp_dir_obj = None\n\n    # Convert motifs to MEME format\n    query_motif_file = os.path.join(temp_dir, \"query_motifs.txt\")\n    export_pfms_to_meme_format(query_pfms, query_motif_file)\n\n    # Run TOMTOM\n    tomtom_dir = os.path.join(temp_dir, \"tomtom\")\n    run_tomtom(\n        query_motif_file, database_path, tomtom_dir,\n        show_output=show_tomtom_output\n    )\n\n    # Find results, mapping each query motif to target index\n    # The query/target IDs are the indices\n    tomtom_table = import_tomtom_results(tomtom_dir)\n    matches = []\n    for i in range(len(query_pfms)):\n        rows = tomtom_table[tomtom_table[\"Query_ID\"] == i]\n        if rows.empty:\n            matches.append([])\n            continue\n        rows = rows.sort_values(\"q-value\").head(top_k)\n        tups = list(zip(rows[\"Target_ID\"], rows[\"q-value\"]))\n        tups = [\n            (tup[0], database_pfms[tup[0]], tup[1]) for tup in tups\n        ]\n        matches.append(tups)\n\n    if temp_dir_obj is not None:\n        temp_dir_obj.cleanup()\n\n    return matches\n", "meta": {"hexsha": "187cf34dbcca5c510e2a420d9e2d667d76878783", "size": 8244, "ext": "py", "lang": "Python", "max_stars_repo_path": "basepairmodels/reports/tomtom.py", "max_stars_repo_name": "juanelenter/basepairmodels", "max_stars_repo_head_hexsha": "f32a5a692fb4c96000b4297302de9b6888694c93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2020-04-30T16:46:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T19:33:26.000Z", "max_issues_repo_path": "basepairmodels/reports/tomtom.py", "max_issues_repo_name": "juanelenter/basepairmodels", "max_issues_repo_head_hexsha": "f32a5a692fb4c96000b4297302de9b6888694c93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2020-09-23T22:36:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T00:02:01.000Z", "max_forks_repo_path": "basepairmodels/reports/tomtom.py", "max_forks_repo_name": "juanelenter/basepairmodels", "max_forks_repo_head_hexsha": "f32a5a692fb4c96000b4297302de9b6888694c93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2021-04-16T01:00:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T11:46:51.000Z", "avg_line_length": 36.64, "max_line_length": 100, "alphanum_fraction": 0.6413148957, "include": true, "reason": "import numpy", "num_tokens": 2087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.15898747487920636}}
{"text": "#! /usr/bin/env python3\n#\n#  Copyright 2018 California Institute of Technology\n#\n#  Licensed under the Apache License, Version 2.0 (the \"License\");\n#  you may not use this file except in compliance with the License.\n#  You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n#  Unless required by applicable law or agreed to in writing, software\n#  distributed under the License is distributed on an \"AS IS\" BASIS,\n#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#  See the License for the specific language governing permissions and\n#  limitations under the License.\n#\n# ISOFIT: Imaging Spectrometer Optimal FITting\n# Author: David R Thompson, david.r.thompson@jpl.nasa.gov\n#\n\nimport logging\nimport numpy as np\nfrom scipy.interpolate import interp1d\nfrom scipy.signal import convolve\nfrom scipy.io import loadmat\n\nfrom .common import eps, spectral_response_function, load_wavelen, resample_spectrum, emissive_radiance\nfrom isofit.configs import Config\n\n\n### Variables ###\n\n# Max. wavelength difference (nm) that does not trigger expensive resampling\nwl_tol = 0.01\n\n\n### Classes ###\n\nclass Instrument:\n\n    def __init__(self, full_config: Config):\n        \"\"\"A model of the spectrometer instrument, including spectral \n        response and noise covariance matrices. Noise is typically calculated\n        from a parametric model, fit for the specific instrument.  It is a \n        function of the radiance level.\"\"\"\n\n        config = full_config.forward_model.instrument\n\n        # If needed, skip first index column and/or convert to nanometers\n        self.wl_init, self.fwhm_init = load_wavelen(config.wavelength_file)\n        self.n_chan = len(self.wl_init)\n\n        self.fast_resample = config.fast_resample\n\n        self.bounds = config.statevector.get_all_bounds()\n        self.scale = config.statevector.get_all_scales()\n        self.init = config.statevector.get_all_inits()\n        self.prior_mean = np.array(config.statevector.get_all_prior_means())\n        self.prior_sigma = np.array(config.statevector.get_all_prior_sigmas())\n        self.statevec_names = config.statevector.get_element_names()\n        self.n_state = len(self.statevec_names)\n\n        if config.SNR is not None:\n            self.model_type = 'SNR'\n            self.snr = config.SNR\n        elif config.parametric_noise_file is not None:\n            self.model_type = 'parametric'\n            self.noise_file = config.parametric_noise_file\n            coeffs = np.loadtxt(\n                self.noise_file, delimiter=' ', comments='#')\n            p_a, p_b, p_c = [interp1d(coeffs[:, 0], coeffs[:, col],\n                                      fill_value='extrapolate') for col in (1, 2, 3)]\n            self.noise = np.array([[p_a(w), p_b(w), p_c(w)]\n                                   for w in self.wl_init])\n            self.integrations = config.integrations\n\n        elif config.pushbroom_noise_file is not None:\n            self.model_type = 'pushbroom'\n            self.noise_file = config.pushbroom_noise_file\n            D = loadmat(self.noise_file)\n            self.ncols = D['columns'][0, 0]\n            if self.n_chan != np.sqrt(D['bands'][0, 0]):\n                logging.error('Noise model mismatches wavelength # bands')\n                raise ValueError('Noise model mismatches wavelength # bands')\n            cshape = ((self.ncols, self.n_chan, self.n_chan))\n            self.covs = D['covariances'].reshape(cshape)\n            self.integrations = config.integrations\n\n        elif config.nedt_noise_file is not None:\n            self.model_type = 'NEDT'\n            self.noise_file = config.nedt_noise_file\n            self.noise_data = np.loadtxt(\n                self.noise_file, delimiter=',', skiprows=8)\n            noise_data_w_nm = self.noise_data[:, 0] * 1000\n            noise_data_NEDT = self.noise_data[:, 1]\n            nedt = interp1d(noise_data_w_nm, noise_data_NEDT)(self.wl_init)\n\n            T, emis = 300., 0.95  # From Glynn Hulley, 2/18/2020\n            _, drdn_dT = emissive_radiance(emis, T, self.wl_init)\n            self.noise_NESR = nedt * drdn_dT\n\n        else:\n            raise IndexError('Please define the instrument noise.')\n            # This should never be reached, as an error is designated in the config read\n\n        # We track several unretrieved free variables, that are specified\n        # in a fixed order (always start with relative radiometric\n        # calibration)\n        self.bvec = ['Cal_Relative_%04i' % int(w) for w in self.wl_init] + \\\n            ['Cal_Spectral', 'Cal_Stray_SRF']\n        self.bval = np.zeros(self.n_chan+2)\n\n        if config.unknowns is not None:\n\n            # First we take care of radiometric uncertainties, which add\n            # in quadrature.  We sum their squared values.  Systematic\n            # radiometric uncertainties account for differences in sampling\n            # and radiative transfer that manifest predictably as a function\n            # of wavelength.\n            if config.unknowns.channelized_radiometric_uncertainty_file is not None:\n                f = config.unknowns.channelized_radiometric_uncertainty_file\n                u = np.loadtxt(f, comments='#')\n                if (len(u.shape) > 0 and u.shape[1] > 1):\n                    u = u[:, 1]\n                self.bval[:self.n_chan] = self.bval[:self.n_chan] + \\\n                    pow(u, 2)\n\n            # Uncorrelated radiometric uncertainties are consistent and\n            # independent in all channels.\n            if config.unknowns.uncorrelated_radiometric_uncertainty is not None:\n                u = config.unknowns.uncorrelated_radiometric_uncertainty\n                self.bval[:self.n_chan] = self.bval[:self.n_chan] + \\\n                    pow(np.ones(self.n_chan) * u, 2)\n\n            # Radiometric uncertainties combine via Root Sum Square...\n            # Be careful to avoid square roots of zero!\n            small = np.ones(self.n_chan)*eps\n            self.bval[:self.n_chan] = np.maximum(self.bval[:self.n_chan], small)\n            self.bval[:self.n_chan] = np.sqrt(self.bval[:self.n_chan])\n\n            # Now handle spectral calibration uncertainties\n            if config.unknowns.wavelength_calibration_uncertainty is not None:\n                self.bval[-2] = config.unknowns.wavelength_calibration_uncertainty\n            if config.unknowns.stray_srf_uncertainty is not None:\n                self.bval[-1] = config.unknowns.stray_srf_uncertainty\n\n        # Determine whether the calibration is fixed.  If it is fixed,\n        # and the wavelengths of radiative transfer modeling and instrument\n        # are the same, then we can bypass computationally expensive sampling\n        # operations later.\n        self.calibration_fixed = True\n        if config.statevector.GROW_FWHM is not None or config.statevector.WL_SHIFT is not None or \\\n                config.statevector.WL_SPACE is not None:\n            self.calibration_fixed = False\n\n    def xa(self):\n        \"\"\"Mean of prior distribution, calculated at state x.\"\"\"\n\n        return self.init.copy()\n\n    def Sa(self):\n        \"\"\"Covariance of prior distribution (diagonal).\"\"\"\n\n        if self.n_state == 0:\n            return np.zeros((0, 0), dtype=float)\n        return np.diagflat(np.power(self.prior_sigma, 2))\n\n    def Sy(self, meas, geom):\n        \"\"\"Calculate measuremment error covariance.  Kelvin Man Yiu Leung and \n            Jayanth Jagalur Mohan (MIT) developed the noise clipping strategy.\n\n        Input: meas, the instrument measurement\n        Returns: Sy, the measurement error covariance due to instrument noise\n        \"\"\"\n        if self.model_type == 'SNR':\n            nedl = (1.0 / self.snr) * meas\n            minimum_noise = np.sqrt(1e-7) \n            bad = nedl < minimum_noise\n            if np.any(bad):\n                logging.debug('SNR noise model found noise <= 0 - adjusting to slightly positive to avoid /0.')\n            nedl[bad] = minimum_noise\n            return np.diagflat(np.power(nedl,2))\n\n        elif self.model_type == 'parametric':\n            noise_plus_meas = self.noise[:, 1]+meas\n            if np.any(noise_plus_meas <=0):\n                noise_plus_meas[noise_plus_meas <= 0] = 1e-5\n                logging.debug('Parametric noise model found noise <= 0 - adjusting to slightly positive to avoid /0.')\n            nedl = np.abs(self.noise[:, 0]*np.sqrt(noise_plus_meas)+self.noise[:, 2])\n            nedl = nedl/np.sqrt(self.integrations)\n            return np.diagflat(np.power(nedl,2))\n\n        elif self.model_type == 'pushbroom':\n            if geom.pushbroom_column is None:\n                C = np.squeeze(self.covs.mean(axis=0))\n            else:\n                C = self.covs[geom.pushbroom_column, :, :]\n            return C / np.sqrt(self.integrations)\n\n        elif self.model_type == 'NEDT':\n            return np.diagflat(np.power(self.noise_NESR,2))\n\n    def dmeas_dinstrument(self, x_instrument, wl_hi, rdn_hi):\n        \"\"\"Jacobian of measurement with respect to the instrument \n           free parameter state vector. We use finite differences for now.\"\"\"\n\n        dmeas_dinstrument = np.zeros((self.n_chan, self.n_state), dtype=float)\n        if self.n_state == 0:\n            return dmeas_dinstrument\n\n        meas = self.sample(x_instrument, wl_hi, rdn_hi)\n        for ind in range(self.n_state):\n            x_instrument_perturb = x_instrument.copy()\n            x_instrument_perturb[ind] = x_instrument_perturb[ind]+eps\n            meas_perturb = self.sample(x_instrument_perturb, wl_hi, rdn_hi)\n            dmeas_dinstrument[:, ind] = (meas_perturb - meas) / eps\n        return dmeas_dinstrument\n\n    def dmeas_dinstrumentb(self, x_instrument, wl_hi, rdn_hi):\n        \"\"\"Jacobian of radiance with respect to the instrument parameters\n        that are unknown and not retrieved, i.e., the inevitable persisting\n        uncertainties in instrument spectral and radiometric calibration.\n\n        Input: meas, a vector of size n_chan\n        Returns: Kb_instrument, a matrix of size [n_measurements x nb_instrument]\n        \"\"\"\n\n        # Uncertainty due to radiometric calibration\n        meas = self.sample(x_instrument, wl_hi, rdn_hi)\n        dmeas_dinstrument = np.hstack(\n            (np.diagflat(meas), np.zeros((self.n_chan, 2))))\n\n        # Uncertainty due to spectral calibration\n        if self.bval[-2] > 1e-6:\n            dmeas_dinstrument[:, -2] = self.sample(x_instrument, wl_hi,\n                                                   np.hstack((np.diff(rdn_hi), np.array([0]))))\n\n        # Uncertainty due to spectral stray light\n        if self.bval[-1] > 1e-6:\n            ssrf = spectral_response_function(np.arange(-10, 11), 0, 4)\n            blur = convolve(meas, ssrf, mode='same')\n            dmeas_dinstrument[:, -1] = blur - meas\n\n        return dmeas_dinstrument\n\n    def sample(self, x_instrument, wl_hi, rdn_hi):\n        \"\"\"Apply instrument sampling to a radiance spectrum, returning predicted measurement.\"\"\"\n\n        if self.calibration_fixed and (len(self.wl_init) == len(wl_hi)) and \\\n                    all((self.wl_init - wl_hi) < wl_tol):\n            return rdn_hi\n        wl, fwhm = self.calibration(x_instrument)\n        if rdn_hi.ndim == 1:\n            return resample_spectrum(rdn_hi, wl_hi, wl, fwhm)\n        else:\n            resamp = []\n            # The \"fast resample\" option approximates a complete resampling\n            # by a convolution with a uniform FWHM.\n            if self.fast_resample:\n                for i, r in enumerate(rdn_hi):\n                    ssrf = spectral_response_function(np.arange(-10, 11), 0, fwhm[0])\n                    blur = convolve(r, ssrf, mode='same')\n                    resamp.append(interp1d(wl_hi, blur)(wl))\n            else:\n                for i, r in enumerate(rdn_hi):\n                    r2 = resample_spectrum(r, wl_hi, wl, fwhm)\n                    resamp.append(r2)\n            return np.array(resamp)\n\n    def simulate_measurement(self, meas, geom):\n        \"\"\"Simulate a measurement by the given sensor, for a true radiance\n        sampled to instrument wavelengths. This basically just means\n        drawing a sample from the noise distribution.\"\"\"\n\n        Sy = self.Sy(meas, geom)\n        mu = np.zeros(meas.shape)\n        rdn_sim = meas + np.random.multivariate_normal(mu, Sy)\n        return rdn_sim\n\n    def calibration(self, x_instrument):\n        \"\"\"Calculate the measured wavelengths.\"\"\"\n\n        wl, fwhm = self.wl_init, self.fwhm_init\n        space_orig = wl - wl[0]\n        offset = wl[0]\n        if 'GROW_FWHM' in self.statevec_names:\n            ind = self.statevec_names.index('GROW_FWHM')\n            fwhm = fwhm + x_instrument[ind]\n\n        if 'WL_SPACE' in self.statevec_names:\n            ind = self.statevec_names.index('WL_SPACE')\n            space = x_instrument[ind]\n        else:\n            space = 1.0\n\n        if 'WL_SHIFT' in self.statevec_names:\n            ind = self.statevec_names.index('WL_SHIFT')\n            shift = x_instrument[ind]\n        else:\n            shift = 0.0\n\n        wl = offset + shift + space_orig * space\n        return wl, fwhm\n\n    def summarize(self, x_instrument, geom):\n        \"\"\"Summary of state vector.\"\"\"\n\n        if len(x_instrument) < 1:\n            return ''\n        return 'Instrument: '+' '.join(['%5.3f' % xi for xi in x_instrument])\n", "meta": {"hexsha": "82c544674fd80aba4d9a7470fc0dde8a660af56b", "size": 13354, "ext": "py", "lang": "Python", "max_stars_repo_path": "isofit/core/instrument.py", "max_stars_repo_name": "reginaeckert/isofit", "max_stars_repo_head_hexsha": "30d9ada3915b779e2d92e7d9fd5abc49bb6f512e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2018-07-07T15:42:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T22:00:58.000Z", "max_issues_repo_path": "isofit/core/instrument.py", "max_issues_repo_name": "reginaeckert/isofit", "max_issues_repo_head_hexsha": "30d9ada3915b779e2d92e7d9fd5abc49bb6f512e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 219, "max_issues_repo_issues_event_min_datetime": "2018-07-23T16:32:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T00:49:29.000Z", "max_forks_repo_path": "isofit/core/instrument.py", "max_forks_repo_name": "reginaeckert/isofit", "max_forks_repo_head_hexsha": "30d9ada3915b779e2d92e7d9fd5abc49bb6f512e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 44, "max_forks_repo_forks_event_min_datetime": "2018-07-09T17:38:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T19:20:52.000Z", "avg_line_length": 42.9389067524, "max_line_length": 118, "alphanum_fraction": 0.6201138236, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.2509127980882971, "lm_q1q2_score": 0.15893074159725293}}
{"text": "import torch\nimport numpy as np\nfrom torch.nn import functional as F\n\n\n# =================================-----FOR DATASET------============================\n\ndef gaussian2D(shape, sigma=1):\n    '''\n    对输入shape(radius,radius)生产一个高斯核\n    :param shape: (diameter,diameter)\n    :param sigma:\n    :return: (radius*2+1,radius*2+1)\n    '''\n    m, n = [(ss - 1.) / 2. for ss in shape]\n    y, x = np.ogrid[-m:m + 1, -n:n + 1]\n    h = np.exp(-(x * x + y * y) / (2 * sigma * sigma))\n    # 过于小的数设置为0\n    h[h < np.finfo(h.dtype).eps * h.max()] = 0\n    return h\n\n\ndef draw_umich_gaussian(heatmap, center, radius, k=1):\n    '''\n    在heatmap上对中心点center半径为radius画高斯分布\n    :param heatmap: 特征图(128*128)\n    :param center: (x,y)\n    :param radius: 半径\n    :param k:\n    :return:\n    '''\n    # 从中心开始扩展,长度为2 * radius + 1,文章说是sigma=radius/3,\n    # 这里也解决了radius=0，导致sigma除数为0的问题\n    diameter = 2 * radius + 1\n    gaussian = gaussian2D((diameter, diameter), sigma=diameter / 6)\n\n    x, y = center[0], center[1]\n\n    height, width = heatmap.shape[0:2]\n\n    # 越界处理\n    left, right = min(x, radius), min(width - x, radius + 1)\n    top, bottom = min(y, radius), min(height - y, radius + 1)\n\n    # 对齐处理\n    masked_heatmap = heatmap[y - top:y + bottom, x - left:x + right]\n    masked_gaussian = gaussian[radius - top:radius + bottom, radius - left:radius + right]\n    if min(masked_gaussian.shape) > 0 and min(masked_heatmap.shape) > 0:  # TODO debug\n        np.maximum(masked_heatmap, masked_gaussian * k, out=masked_heatmap)\n    return heatmap\n\n\ndef gaussian_radius(det_size, min_overlap=0.7):\n    '''\n    求高斯半径\n    方法来自于CornerNet:https://arxiv.org/pdf/1808.01244.pdf\n    原理就是对三种情况(1内扩1外扩,2内扩,2外扩)解一元二次方程:https://github.com/princeton-vl/CornerNet/issues/110\n    :param det_size: bbox在特征图的大小(h,w)\n    :param min_overlap: 最小的IOU\n    :return: 最小的半径，其保证iou>=min_overlap\n    '''\n    height, width = det_size\n\n    a1 = 1\n    b1 = (height + width)\n    c1 = width * height * (1 - min_overlap) / (1 + min_overlap)\n    sq1 = np.sqrt(b1 ** 2 - 4 * a1 * c1)\n    r1 = (b1 + sq1) / 2\n\n    a2 = 4\n    b2 = 2 * (height + width)\n    c2 = (1 - min_overlap) * width * height\n    sq2 = np.sqrt(b2 ** 2 - 4 * a2 * c2)\n    r2 = (b2 + sq2) / 2\n\n    a3 = 4 * min_overlap\n    b3 = -2 * min_overlap * (height + width)\n    c3 = (min_overlap - 1) * width * height\n    sq3 = np.sqrt(b3 ** 2 - 4 * a3 * c3)\n    r3 = (b3 + sq3) / 2\n    return min(r1, r2, r3)\n\n\n# =================================-----FOR TEST-----============================\n\ndef hm_topk(hm, k):\n    # 使用max_pool获取峰点\n    batch, cls, h, w = hm.size()\n    out = F.max_pool2d(hm, 3, 1, 1)\n    keep_max = (out == hm).float()\n    hm = keep_max * hm\n    # 在heatmap中取每个类别的topk(hm经sigmoid后) topk_indexs的值在0~h*w\n    topk_scores, topk_indexs = hm.view(batch, cls, -1).topk(k)  # (batch,cls,k)\n    # 所有类别取得分最高的topk\n    topk_scores, topk_ind = topk_scores.view(batch, -1).topk(k)  # (batch,k)\n    # 获取得分最高的类别topk,topk_scores每个类别有得分最高的k个，topk_ind除k取下整即为class\n    topk_cls = topk_ind // k\n    # 若topk_indexs.size=(batch,cls*k),topk_indexs[topk_ind]即为最终的index\n    topk_indexs = topk_indexs.view(batch, -1).gather(1, topk_ind)\n    # 获取所有类别中最高得分topk_indexs对应的横纵坐标,即一维转二维\n    topk_ys, topk_xs = topk_indexs // w, topk_indexs % w\n    return topk_scores, topk_indexs, topk_cls, topk_xs, topk_ys\n\n\ndef heatmap_bbox(hm, wh, reg, k=100):\n    scores, indexs, cls, xs, ys = hm_topk(hm.sigmoid_(), k)\n    batch = reg.size(0)\n    # 先转置便于取关键点对应的2个偏移量\n    reg = reg.view(batch, 2, -1).transpose(2, 1).contiguous()  # (batch,w*h,2)\n    reg_indexs = indexs.unsqueeze(2).expand(batch, -1, 2)  # (batch,k,2)\n    reg = reg.gather(1, reg_indexs)  # (batch,k,2)\n    xs = xs.float() + reg[:, :, 0]\n    ys = ys.float() + reg[:, :, 1]\n    # wh via reg_indexs\n    wh = wh.view(batch, 2, -1).transpose(2, 1).contiguous().gather(1, reg_indexs)  # ((batch,k,2)\n    # bbox via xs and wh\n    bbox = xs - wh[:, :, 0] / 2, ys - wh[:, :, 1] / 2, xs + wh[:, :, 0] / 2, ys + wh[:, :, 1] / 2\n    bbox = torch.stack(bbox, -1)  # (batch,k,4)\n    return bbox, cls, scores\n\n\ndef area_of(left_top, right_bottom) -> torch.Tensor:\n    \"\"\"Compute the areas of rectangles given two corners.\n\n    Args:\n        left_top (N, 2): left top corner.\n        right_bottom (N, 2): right bottom corner.\n\n    Returns:\n        area (N): return the area.\n    \"\"\"\n    hw = torch.clamp(right_bottom - left_top, min=0.0)\n    return hw[..., 0] * hw[..., 1]\n\n\ndef iou_of(boxes0, boxes1, eps=1e-5):\n    \"\"\"Return intersection-over-union (Jaccard index) of boxes.\n\n    Args:\n        boxes0 (N, 4): ground truth boxes.\n        boxes1 (N or 1, 4): predicted boxes.\n        eps: a small number to avoid 0 as denominator.\n    Returns:\n        iou (N): IoU values.\n    \"\"\"\n    overlap_left_top = torch.max(boxes0[..., :2], boxes1[..., :2])\n    overlap_right_bottom = torch.min(boxes0[..., 2:], boxes1[..., 2:])\n\n    overlap_area = area_of(overlap_left_top, overlap_right_bottom)\n    area0 = area_of(boxes0[..., :2], boxes0[..., 2:])\n    area1 = area_of(boxes1[..., :2], boxes1[..., 2:])\n    return overlap_area / (area0 + area1 - overlap_area + eps)\n\n\ndef soft_nms(box_scores, score_threshold=0.5, sigma=0.5, top_k=-1):\n    \"\"\"Soft NMS implementation.\n\n    References:\n        https://arxiv.org/abs/1704.04503\n        https://github.com/facebookresearch/Detectron/blob/master/detectron/utils/cython_nms.pyx\n        https://oldpan.me/archives/write-hard-nms-c\n\n    Args:\n        box_scores (N, 6): boxes in corner-form and probabilities. [x1,y1,x2,y2,cls,score]\n        score_threshold: boxes with scores less than value are not considered.\n        sigma: the parameter in score re-computation.\n            scores[i] = scores[i] * exp(-(iou_i)^2 / simga)\n        top_k: keep top_k results. If k <= 0, keep all the results.\n    Returns:\n         picked_box_scores (K, 5): results of NMS.\n    \"\"\"\n    picked_box_scores = []\n    while box_scores.size(0) > 0:\n        max_score_index = torch.argmax(box_scores[:, -1])\n        cur_box_prob = box_scores[max_score_index, :].clone().detach()\n        picked_box_scores.append(cur_box_prob)\n        if len(picked_box_scores) == top_k > 0 or box_scores.size(0) == 1:\n            break\n        cur_box = cur_box_prob[:-2]\n        box_scores[max_score_index, :] = box_scores[-1, :]\n        box_scores = box_scores[:-1, :]\n        ious = iou_of(cur_box.unsqueeze(0), box_scores[:, :-2])\n\n        box_scores[:, -1] = box_scores[:, -1] * torch.exp(-(ious * ious) / sigma)\n\n        box_scores = box_scores[box_scores[:, -1] > score_threshold, :]\n    if len(picked_box_scores) > 0:\n        return torch.stack(picked_box_scores)\n    else:\n        return torch.tensor([])\n", "meta": {"hexsha": "c404c14344f509527ce2f72c3d765963334bda14", "size": 6626, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils.py", "max_stars_repo_name": "JavisPeng/CenterNet-pytorch-detection-simple-tutorial", "max_stars_repo_head_hexsha": "1dd69dd26be3627079aeeb458dde35a1f3f1c5df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2020-05-19T09:23:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T08:38:11.000Z", "max_issues_repo_path": "utils.py", "max_issues_repo_name": "JavisPeng/CenterNet-pytorch-detection-simple-tutorial", "max_issues_repo_head_hexsha": "1dd69dd26be3627079aeeb458dde35a1f3f1c5df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-11-26T05:37:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T19:32:39.000Z", "max_forks_repo_path": "utils.py", "max_forks_repo_name": "JavisPeng/CenterNet-pytorch-detection-simple-tutorial", "max_forks_repo_head_hexsha": "1dd69dd26be3627079aeeb458dde35a1f3f1c5df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-07-25T06:01:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T03:22:13.000Z", "avg_line_length": 34.6910994764, "max_line_length": 97, "alphanum_fraction": 0.5964382735, "include": true, "reason": "import numpy", "num_tokens": 2327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.275129717879598, "lm_q1q2_score": 0.15888613690034778}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nSMPTE 240M Colourspace\n======================\n\nDefines the *SMPTE 240M* colourspace:\n\n-   :attr:`colour.models.SMPTE_240M_COLOURSPACE`.\n\nReferences\n----------\n-   :cite:`SocietyofMotionPictureandTelevisionEngineers1999b` : Society of\n    Motion Picture and Television Engineers. (1999). ANSI/SMPTE 240M-1995 -\n    Signal Parameters - 1125-Line High-Definition Production Systems. Retrieved\n    from http://car.france3.mars.free.fr/HD/INA- 26 jan 06/\\\nSMPTE normes et confs/s240m.pdf\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\n\nfrom colour.colorimetry import ILLUMINANTS\nfrom colour.models.rgb import (RGB_Colourspace, normalised_primary_matrix,\n                               oetf_SMPTE240M, eotf_SMPTE240M)\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2020 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-developers@colour-science.org'\n__status__ = 'Production'\n\n__all__ = [\n    'SMPTE_240M_PRIMARIES', 'SMPTE_240M_WHITEPOINT_NAME',\n    'SMPTE_240M_WHITEPOINT', 'SMPTE_240M_TO_XYZ_MATRIX',\n    'XYZ_TO_SMPTE_240M_MATRIX', 'SMPTE_240M_COLOURSPACE'\n]\n\nSMPTE_240M_PRIMARIES = np.array([\n    [0.6300, 0.3400],\n    [0.3100, 0.5950],\n    [0.1550, 0.0700],\n])\n\"\"\"\n*SMPTE 240M* colourspace primaries.\n\nSMPTE_240M_PRIMARIES : ndarray, (3, 2)\n\"\"\"\n\nSMPTE_240M_WHITEPOINT_NAME = 'D65'\n\"\"\"\n*SMPTE 240M* colourspace whitepoint name.\n\nSMPTE_240M_WHITEPOINT_NAME : unicode\n\"\"\"\n\nSMPTE_240M_WHITEPOINT = (ILLUMINANTS['CIE 1931 2 Degree Standard Observer'][\n    SMPTE_240M_WHITEPOINT_NAME])\n\"\"\"\n*SMPTE 240M* colourspace whitepoint.\n\nSMPTE_240M_WHITEPOINT : ndarray\n\"\"\"\n\nSMPTE_240M_TO_XYZ_MATRIX = normalised_primary_matrix(SMPTE_240M_PRIMARIES,\n                                                     SMPTE_240M_WHITEPOINT)\n\"\"\"\n*SMPTE 240M* colourspace to *CIE XYZ* tristimulus values matrix.\n\nSMPTE_240M_TO_XYZ_MATRIX : array_like, (3, 3)\n\"\"\"\n\nXYZ_TO_SMPTE_240M_MATRIX = np.linalg.inv(SMPTE_240M_TO_XYZ_MATRIX)\n\"\"\"\n*CIE XYZ* tristimulus values to *SMPTE 240M* colourspace matrix.\n\nXYZ_TO_SMPTE_240M_MATRIX : array_like, (3, 3)\n\"\"\"\n\nSMPTE_240M_COLOURSPACE = RGB_Colourspace(\n    'SMPTE 240M',\n    SMPTE_240M_PRIMARIES,\n    SMPTE_240M_WHITEPOINT,\n    SMPTE_240M_WHITEPOINT_NAME,\n    SMPTE_240M_TO_XYZ_MATRIX,\n    XYZ_TO_SMPTE_240M_MATRIX,\n    oetf_SMPTE240M,\n    eotf_SMPTE240M,\n)\nSMPTE_240M_COLOURSPACE.__doc__ = \"\"\"\n*SMPTE 240M* colourspace.\n\nReferences\n----------\n:cite:`SocietyofMotionPictureandTelevisionEngineers1999b`,\n\nSMPTE_240M_COLOURSPACE : RGB_Colourspace\n\"\"\"\n", "meta": {"hexsha": "73155c8a7f472f8a5f50df1dad216966cd1eb0bf", "size": 2644, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/models/rgb/datasets/smpte_240m.py", "max_stars_repo_name": "jchwei/colour", "max_stars_repo_head_hexsha": "2b2ad0a0f2052a1a0b4b076b489687235e804fdf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "colour/models/rgb/datasets/smpte_240m.py", "max_issues_repo_name": "jchwei/colour", "max_issues_repo_head_hexsha": "2b2ad0a0f2052a1a0b4b076b489687235e804fdf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/models/rgb/datasets/smpte_240m.py", "max_forks_repo_name": "jchwei/colour", "max_forks_repo_head_hexsha": "2b2ad0a0f2052a1a0b4b076b489687235e804fdf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.44, "max_line_length": 79, "alphanum_fraction": 0.7307110439, "include": true, "reason": "import numpy", "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6406358548398982, "lm_q2_score": 0.24798743735585305, "lm_q1q2_score": 0.15886964392002262}}
{"text": "\"\"\"\nFluorescence Intensity calculations:\n   Y. Choi\n\ncalculates fluorescence intensities for multiple elements at a fixed incident x-ray energy.\nmeasured fluorescence depends on net fluorescence yield and transmission.\nincluded are:\n    (with incident energy dependence): atomic crosssection, fluorescence yield for each edge,\n                                     transition probability for each emission line,\n    (with emitted fluorescence energy dependence): transmission to vortex detector, detector efficiency.\nglobal variables: re, Barn, Nav, pre_edge_margin, fluo_emit_min, det_res\nAtNum2f1f2Xect: needs datafile readf1f2a.py which is from chantler table\ncal_NetYield2: for XRF calculations.  major and minor lines are calculated\n                output as 'Elemental_Sensitivity.txt'\n\nsim_spectra: keeps individual emission lines with significant intensity without weight-averaging\n             each element can have a different relative concentration.\n             makes strongest emission to 100 and scales the rest accordingly.\n             output as 'simSpectrum.txt'\n             runs sim_GaussPeaks() to emulate measure intensity as gaussian peak\n             output as 'simSpectrum.plot'\n             runs cal_NetYield2()\n5/24/2010:  self-absorption effect included, 4 options (top, bottom, all, surface)\n            Each option makes different elemental distribution,\n            but substrate elements are always distributed evenly.\n            get_ChemName(), nominal_density() are in readf1f2a.py\n5/26/2010:   incident x-ray attenuation effect added, and incident angle effect is also added.\n            refraction effect added to the angle, below critical angle, th=1e-10.\n6/4/2010:    SampleMatrix2 has two layers and each layer can have different composition\n            Class ElemFY is for fluorescence elements with AtSym, Conc, tag attribues,\n            inputs in SimSpect, Cal_NetFyield2 changed.\n            Concentrations are normalized to the concentration of the substrate1 molecule.\n            Ex) with CaCO3[2.71g/cc]/Fe2O3[5.26g/cc] substrate, Ca concentration is 1.0 meaning 1.63e22 Ca/cc\n            and Fe concentration is 2.43 = 2*1.98e22/1.63e22 where 1.98e22 is number density (/cc) of Fe2O3\n6/8/2010:    now using python2.6 instead of 2.5\n4/14/2011:  fluo_det.py: detection dependent part in fluorescence yield.\n            Original fluo.py was modified to fluo_new.py.\n            readf1f2a.py is used instead of original readf1f2.py\n            fluo_new.py is being split into two.\n            fluo_elem.py is for elemtnal dependence: fluorescenc yield, crosssection.\n            fluo_det.py is for detection dependnece: detector efficiency, attenuation, sample\n            * for attenuation, total cross-section([4]) is used instead of photoelectric ([2]).\n            ** for fluorescence yield, photoelectric is used.\n\"\"\"\n\n\nimport math\nimport numpy\nimport sys\nfrom larch import use_plugin_path\nuse_plugin_path('xray')\nuse_plugin_path('xsw')\n\nfrom physical_constants import AVOGADRO, BARN\n\npre_edge_margin=150.    # FY calculated from 150 eV below the absorption edge.\nfluo_emit_min=500.      # minimum energy for emitted fluorescence.  ignore fluorescence emissions below 500eV\ndet_res=100.            # detector resoltuion in eV, used in sim_GaussPeaks\n\n'''\n----------------------------------------------------------------------------------------------------------\nclass: Material, ElemFY, SampleMatrix2\n----------------------------------------------------------------------------------------------------------\n'''\nclass Material:\n    def __init__(self, composition, density, thickness=1,_larch=None):\n        self.composition=composition        # ex) SiO2\n        self.density=density              # in g/cm^3\n        self.thickness=thickness            # in cm\n        self.la=1.0                         #absoprtion length in cm\n        self.trans=0.5                      # transmission.\n        self.absrp=0.5                 # absorption\n        self.delta=0.1                  # index of refraction, real part\n        self.beta=0.1                   # index of refraction, imaginary part\n        # MN replace\n        elements = chemparse(composition)\n        AtomList = elements.keys()\n        AtomIndex = elements.values()\n        AtomWeight=0\n        for (ii, atom) in enumerate(AtomList):\n            # MN replace...\n            AtWt= atomic_mass(atom)\n            index=AtomIndex[ii]\n            AtomWeight = AtomWeight + index*AtWt\n        NumberDensity=density*AVOGARDRO/AtomWeight\n        self.NumDen=NumberDensity       # number of molecules per cm^3\n        self.AtWt=AtomWeight            # weight per mole\n    def getLa(self, energy, NumLayer=1.0):    # get absorption legnth for incident x-ray, NumLayer for multiple layers\n        # MN replace...\n        temp= xray_delta_beta(self.composition, self.density, energy, _larch=_larch)\n        # returns delta, beta, la_photoE, Nat, la_total\n        self.delta=temp[0];     self.beta=temp[1]\n        self.la=temp[2]  # temp[4] (total) instead of temp[2] (photoelectric)\n        if NumLayer<0:  NumLayer=0     # Number of layers cannot be less than zero\n        self.trans=math.exp(-self.thickness*NumLayer/self.la)  #la attenuation length cm, NumLayer for multiple layers\n        self.absrp=1-self.trans\n\n\nclass ElemFY:  # fluorescing element\n    def __init__(self, AtomicSymbol='Fe', Concentration=10e-6, tag='dilute'):\n        temp=AtomicSymbol[0].upper()  # capitalize the first letter\n        self.AtSym=temp+AtomicSymbol[1:]\n        self.Conc=Concentration\n        self.tag=tag  # dilute, substrate1, substrate2\n\n\nclass SampleMatrix2:  # sample matrix for self-absorption correction, 6/3: two layers with different compositions\n    def __init__(self, composition1='Si', density1=2.33, thickness1=0.1, \\\n                       composition2='Si', density2=2.33, thickness2=0.1, \n                       angle0=45.0, option='surface', _larch=None):\n        self.composition1 = composition1     # ex) Fe2O3\n        # MN replace:\n        out= chemparse(composition1)         # output from get_ChemName\n        self.ElemList1 = out.keys()          # list of elments in matrix: 'Fe', 'O' for Fe2O3\n        self.ElemInd1 = out.values()         # list of index: 2, 3 for Fe2O3\n        # self.ElemFrt1 = out[2]             # list of fraction: 0.4, 0.6 for Fe2O3\n        self.density1 = density1             # in g/cm^3\n        self.thickness1 = thickness1         # top layer thickness in cm\n        self.composition2 = composition2\n        # MN replace with chemparse()\n        out=chemparse(composition2)\n        self.ElemList2 = out.keys()              # for the bottom substrate\n        self.ElemInd2 = out.values()\n        # self.ElemFrt2 = out[2]\n        self.density2 = density2\n        self.thickness2 = thickness2         # bottom layer thickness in cm\n        self.angle = angle0*math.pi/180.     # in radian, incident beam angle, surface normal =pi/2\n        self.option = option                 # option for fluorescing element location, surface/top/bottom\n        self.la1 = 1.0                       # absoprtion length in cm\n        self.delta1 = 0.1                    # index of refraction, real part correction\n        self.beta1 = 0.1                     # index of refraction, imaginary part\n        self.Nat1 = 1.0                      # atomic number density of the Fe2O3, 1e22 Fe2O3 atoms /cm^3\n        self.la2 = 1.0\n        self.delta2 = 0.1\n        self.beta2 = 0.1\n        self.Nat2 = 1.0                     # atomic number density of the first element, 1e22 Fe2O3 atoms/cm^3\n        self.scale = 1.0                    # weighted average over the depth range: sum of (trans*factors)\n        self.scale1 = 1.0                   # sum of (trans*1.0) this is for substrate element in top layer\n        self.scale2 = 1.0                   # sum of (trans*thickness2/thickness1) for substrate element in bottom layer\n        self.ElemListFY =[]                 # fluorescing element\n        self.ElemFrtFY =[]                  # fraction for fluorescing element\n        self.Nat1=1                  # atomic number density in atoms/cc, for example # of Fe2O3/cm^3 for Fe2O3 substrate\n        self.Nat2=1                  # atomic number density in atoms/cc\n        substrate1_material = Material(composition1, density1, _larch=_larch)\n        AtNumDen1 = substrate1_material.NumDen      #  substrate1\n        substrate2_material = Material(composition2, density2, _larch=_larch)\n        AtNumDen2 = substrate2_material.NumDen      #  substrate2, fixed 8/12/10\n        self.Nat1=AtNumDen1\n        self.Nat2=AtNumDen2\n        self.txt=''\n        text1='substrate1:%6.3e %s/cm^3' % (AtNumDen1, composition1)\n        #print(text1)\n        text2='substrate2:%6.3e %s/cm^3' % (AtNumDen2, composition2)\n        self.txt=text1+'  '+text2\n        print(self.txt)\n        # atom.conc is normalized to the number density of substrate1 molecule\n        for (ii, item) in enumerate(self.ElemList1):\n            # MN replace:\n            if atomic_number(item)>=12:       # ignore elements below Mg\n                #atom=ElemFY(item, self.ElemFrt1[ii], 'substrate1')\n                atom=ElemFY(item, self.ElemInd1[ii], 'substrate1')\n                # eg. for Fe2O3, Fe concentration is 2 (=2 x Fe2O3 number density)\n                self.ElemListFY.append(atom)\n        for (ii, item) in enumerate(self.ElemList2):\n            # MN replace:\n            if atomic_number(item)>=12:       # ignore elements below Mg\n                #atom=ElemFY(item, self.ElemFrt2[ii], 'substrate2')\n                atom=ElemFY(item, self.ElemInd2[ii]*AtNumDen2/AtNumDen1, 'substrate2')\n                self.ElemListFY.append(atom)\n        numLayer=100                        # each layer is sliced into 100 sublayers.\n        self.depths=[]                      # depth values for calculation\n        for ii in range(numLayer):\n            step=1.0/numLayer\n            self.depths.append(step*ii*self.thickness1)\n        for ii in range(numLayer):\n            step=1.0/numLayer\n            self.depths.append(step*ii*self.thickness2+self.thickness1)\n        self.factors=[]                     # 1 or pre if element present at each depth\n        pre=self.thickness2/self.thickness1 # prefactor, if two layers have different thickness\n        if self.option=='surface':          # fluorescecing atoms present in only on the surface\n            for ii in range(len(self.depths)):\n                if ii==0:\n                    self.factors.append(1.0)\n                else:\n                    self.factors.append(0.0)\n        if self.option=='all':              # fluorescecing atoms present throughout\n            for ii in range(len(self.depths)):\n                if self.depths[ii]<self.thickness1:\n                    self.factors.append(1.0)\n                else:\n                    self.factors.append(pre)\n        if self.option=='top':              # fluorescecing atoms present only in the top layer\n            for ii in range(len(self.depths)):\n                if self.depths[ii]<self.thickness1:\n                    self.factors.append(1.0)\n                else:\n                    self.factors.append(0.0)\n        if self.option=='bottom':           # fluorescecing atoms present only in the bottom layer\n            for ii in range(len(self.depths)):\n                if self.depths[ii]<self.thickness1:\n                    self.factors.append(0.0)\n                else:\n                    self.factors.append(pre)\n        # note: fluorescing substrate atoms present throughout regardless of the option.\n        self.trans=[]                       # transmission to surface for emitted fluorescence\n        self.absrp=[]                       # absorption until surface for emitted fluorescence\n        self.inten0=[]                      # incident x-ray intensity at each depth\n        for ii in range(len(self.depths)):\n            self.trans.append(0.5)\n            self.absrp.append(0.5)\n            self.inten0.append(0.5)\n    def getPenetration(self, energy0):  # incident x-ray penetration(attenuation)\n        # refraction at air/top layer interface\n        # MN replace:\n        temp=f1f2.get_delta(self.composition1, self.density1, energy0)  # energy0: incident x-ray energy\n        delta1=temp[0];  beta1=temp[1]\n        la1=temp[4]     # in cm, temp[4] instead of temp[2], using total instead of photoelectric\n        self.la1=la1                                        # absorption length in microns at incident x-ray energy\n        angle_critical1 = (2.0*delta1)**(0.5)               # in radian, critical angle for total external reflection\n        if angle_critical1>=self.angle:                     # below critical angle, the corrected should be zero.\n            angle_corrected1=1.0e-15                        # a smaller number instead of zero\n        else:                                               # above critical angle\n            angle_corrected1 = (self.angle**2.0 - angle_critical1**2.0)**(0.5)  # in radian\n        # refraction at top/bottom layers interface\n        # MN replace:\n        temp=f1f2.get_delta(self.composition2, self.density2, energy0)  # energy0: incident x-ray energy\n        delta2=temp[0];  beta2=temp[1];\n        la2=temp[4]     # in cm, temp[4] instead of temp[2], using total instead of photoelectric\n        self.la2=la2                                            # absorption length in cm at incident x-ray energy\n        angle_corrected2 = ( 2.0-(1.0-delta1)/(1.0-delta2)*(2.0-angle_corrected1**2) )**0.5\n        # using Snell's law, assume beta effect not ignificant, in radian\n        for (ii, depth) in enumerate(self.depths):\n            if self.depths[ii]<self.thickness1:                 # top layer\n                beampath = depth/math.sin(angle_corrected1)     # in cm\n                inten0 = math.exp(-beampath/la1)                # attenuated incident beam intensity at depths\n            else:                                               # bottom layer\n                beampath1 = self.thickness1/math.sin(angle_corrected1)\n                beampath2 = (depth-self.thickness1)/math.sin(angle_corrected2)\n                inten0 = math.exp(-beampath1/la1)*math.exp(-beampath2/la2)\n            self.inten0[ii] = inten0                            # incident x-ray attenuation\n    def getLa(self, energy, NumLayer=1.0):  # emitted fluorescence trasmission attenuation up to top surface\n        transmitted=1.0\n        # MN replace:\n        temp=f1f2.get_delta(self.composition1, self.density1, energy)  # energy is for fluorescence\n        self.delta1 = temp[0]\n        self.beta1 = temp[1]\n        self.la1 = temp[4]      # in cm, temp[4] instead of temp[2], using total instead of photoelectric\n        # absorption length in cm at emitted fluorescence energy\n        # temp[3]: atomic number density of the first element in atoms/cc\n        # MN replace:\n        temp=f1f2.get_delta(self.composition2, self.density2, energy)  # energy is for fluorescence\n        self.delta2 = temp[0]\n        self.beta2 = temp[1]\n        self.la2 = temp[4]                                      # absorption length in cm at emitted fluorescence energy\n        # in cm, temp[4] instead of temp[2], using total instead of photoelectric\n        angle_exit = (math.pi/2.0 - self.angle)                 # becomes 90 at a small incident angle\n        for (ii, depth) in enumerate(self.depths):\n            if self.depths[ii]<self.thickness1:                 # top layer\n                 transmitted=math.exp(-depth/math.sin(angle_exit)*NumLayer/self.la1)\n            else:                                               # bottom layer\n                transmitted2 = math.exp(-(depth-self.thickness1)/math.sin(angle_exit)*NumLayer/self.la2)\n                transmitted1 = math.exp(-self.thickness1/math.sin(angle_exit)*NumLayer/self.la1)\n                transmitted = transmitted2*transmitted1\n        self.trans[ii] = transmitted\n        self.absrp[ii] = 1.0 - transmitted\n        scale = 0.0; scale1=0.0; scale2=0.0\n        for (ii,trans) in enumerate(self.trans):\n            scale = scale + trans*self.inten0[ii]*self.factors[ii]\n            if self.depths[ii]<self.thickness1:\n                scale1 = scale1 + trans*self.inten0[ii]*1.0\n            else:   # if thickness2 is different from thickness1, weight differently\n                scale2 = scale2 + trans*self.inten0[ii]*(self.thickness2/self.thickness1)\n        # scale, scale1, scale2: emitted fluorescence transmission and depth profile\n        self.scale = scale      # sum of (trans*factors) for nonsubstrate FY\n        self.scale1 = scale1    # sum of (trans*factors) for substrate FY. factors=1, top layer\n        self.scale2 = scale2    # sum of (trans*factors) for substrate FY. factors=pre, bttom layer\n\n\n'''\n----------------------------------------------------------------------------------------------------------\nDetector efficiency, fluorescence attenuation\n----------------------------------------------------------------------------------------------------------\n'''\n# WD30 used for XSW, sample-->He-->Kapton-->Collimator-->Detector\n# WD60 used for XRM, sample-->Collimator-->Detector\n# eV1 is fluorescence energy in eV\n# xHe=1 means Helium gas from sample to WD60 collimator.\n# xAl=1 means 1 layer of 1.5mil Al foil as attenuator\n# xKapton=1 means 1 layer of 0.3 mil Kapton (\n# WD=6 means working distance of 6cm for the detector.\n\ndef Assemble_QuadVortex(eV1):\n    # quad vortex detector efficiency. eV1: fluo energy\n    net=1.\n    BeVortex=Material('Be', 1.85, 0.00125)\n    SiO2Vortex=Material('SiO2', 2.2, 0.00001)\n    SiVortex=Material('Si', 2.33, 0.035)\n    BeVortex.getLa(eV1, 1)  # one Be layer in Vortex\n    SiO2Vortex.getLa(eV1, 1)    # oxide layer on Si detection layer\n    SiVortex.getLa(eV1, 1)  # Si detection layer, what's absorbed is counted.\n    net=net*BeVortex.trans*SiO2Vortex.trans*SiVortex.absrp\n    if (print2screen):\n        print( '%.3f eV : BeVortex.trans=%.3e , SiO2Vortex.trans=%.3e, SiVortex.absrp=%.3e, Det_efficiency=%.3e' % (eV1, BeVortex.trans,  SiO2Vortex.trans, SiVortex.absrp, net))\n    return net\n\n\ndef Assemble_Collimator(eV1, xHe=1, xAl=0,xKapton=0, WD=6.0, xsw=0):\n    # from sample surface to detector\n    # xsw=0/1/-1,  6cm, 3cm, no collimator\n    # He_path depends on the collliator.\n    if xHe==1:\n        He_path=WD\n    else:\n        He_path=0.\n    air_path = WD-He_path\n    kapton_inside=0  # kapton inside collimator.  no collimator, no kapton_inside\n    if xsw==0:  # WD60mm collimator\n        kapton_inside=1                 # collimator has thin Kapton on the second aperture\n        if xHe==1:\n            air_path = 1.51             # 1.51cm between second aperture and Be of Vortex\n        else:\n            air_path=WD\n        He_path = WD-air_path           # He is between sample surface to the second aperture of xrm collimator\n    if xsw==1:  # WD30mm colllimator\n        kapton_inside=1                 # collimator has thin Kapton on the second aperture\n        if xHe==1:      # modified 11/18/2010\n            He_path = 1.088   # from sample surface to Kapton cover/collimator\n            air_path = WD - He_path            # 1.912cm between second aperture and Be of Vortex\n            xKapton = xKapton+1         # one Kapton film used to fill He from sample surface to collimator\n        else:\n            air_path = WD0;     He_path=0\n    air=Material('N1.56O0.48C0.03Ar0.01Kr0.000001Xe0.0000009', 0.0013, air_path)\n    kapton=Material('C22H10O4N2', 1.42, 0.000762)       # 0.3mil thick\n    HeGas=Material('He', 0.00009, He_path)\n    AlFoil=Material('Al', 2.72, 0.00381)                # 1.5mil thick\n    kaptonCollimator=Material('C22H10O4N2', 1.42, 0.000762) # 0.3mil thick\n    #\n    air.getLa(eV1, 1)   # 1 means number of layers here.\n    kapton.getLa(eV1, xKapton)  #number of Kapton layers before collimator\n    HeGas.getLa(eV1, xHe) # number of He gas layers, default=0\n    AlFoil.getLa(eV1, xAl)  # number of Al foil,  default=0\n    kaptonCollimator.getLa(eV1, kapton_inside)   # without collimator, no addition kapton inside\n    #\n    net=air.trans*HeGas.trans\n    net=net*kapton.trans*AlFoil.trans*kaptonCollimator.trans\n    if print2screen:\n            print('%.3f eV: air.trans=%.3e, HeGas.trans=%.3e, kapton.trans=%.3e, AlFoil.trans=%.3e, kaptonCollimator.trans=%.3e, net=%.3e' %  \\\n            (eV1, air.trans, HeGas.trans, kapton.trans, AlFoil.trans,kaptonCollimator.trans, net))\n    #print('%.3f eV: air.la=%.3e, HeGas.la=%.3e, kapton.la=%.3e' % (eV1, air.la, HeGas.la, kapton.la))\n    return net\n\n\ndef Assemble_Detector(eV1, xHe=1, xAl=0,xKapton=0, WD=6.0, xsw=0):\n    det_efficiency=Assemble_QuadVortex(eV1)\n    trans2det=Assemble_Collimator(eV1, xHe, xAl,xKapton, WD, xsw)\n    net=det_efficiency*trans2det\n    return net\n\n\n\n'''\n----------------------------------------------------------------------------------------------------------\nCombine detector, transmission, sample self-absorption, and fluorescing element distribution/concentration.\n----------------------------------------------------------------------------------------------------------\n'''\n# this function is for XSW/XRM.\ndef cal_NetYield2(eV0, Atoms, xHe=0, xAl=0, xKapton=0, WD=6.0, xsw=0, WriteFile='Y' , xsect_resonant=0.0, sample=''):\n    #   incident energy, list of elements, experimental conditions\n    #   this one tries Ka, Kb, Lg, Lb, La, Lb\n    angle0=45.; textOut=''\n    if xsw!=0 and WriteFile=='Y':  print( 'XSW measurements')\n    if sample=='':\n        Include_SelfAbsorption='No'\n    else:\n        Include_SelfAbsorption='Yes'\n        angle0=sample.angle/math.pi*180.\n        textOut=sample.txt          # substrate concentration\n    NetYield=[];    NetTrans=[]; Net=[];    out2='';\tnet=0.0\n    text0=''\n    edges      =['K',  'K',  'L1', 'L1', 'L2', 'L2', 'L2', 'L3', 'L3', 'L3']\n    Fluo_lines =['Ka', 'Kb', 'Lb', 'Lg', 'Ln', 'Lb', 'Lg', 'Ll', 'La', 'Lb']\n    outputfile='Elemental_Sensitivity.txt'\n    if WriteFile=='Y':\n        fo=open(outputfile, 'w')\n        desc=' '\n        if xHe==0:   desc=' not '\n        if xsw==-1:\n            out1='# 13IDC XRM/XSW using QuadVortex, incident x-ray energy at '+str(eV0)+' eV at '+str(angle0)+' degrees \\n'\n            out1+='# Helium path'+desc+'used, '+str(xAl)+' Al attenuators, '+str(xKapton+1)+' Kapton attenuators, '\\\n              +str(WD)+' cm working distance. \\n'\n        else:\n            out1='# 13IDC XRM/XSW using QuadVortex + collimator,  incident x-ray energy at '+str(eV0)+' eV at '+str(angle0)+' degrees \\n'\n            out1+='# Helium path'+desc+'used, '+str(xAl)+' Al attenuators, '+str(xKapton)+' Kapton attenuators, '\\\n              +str(WD)+' cm working distance. \\n'\n        print( out1)\n        fo.write(out1)\n        if sample!='':\n            for stuff in Atoms:\n                text1='%6.3e %s/cm^3' % (stuff.Conc*sample.Nat1, stuff.AtSym)\n                text0=text0+' '+text1\n        textOut=textOut+' '+text0       # substrate concentration + other concentrations\n        out1='# '+text0+'\\n'\n        if print2screen:\n            print( out1)\n        fo.write(out1)\n        out1='%s\\t%s\\t%s   \\t%s   \\t%s   \\t%s   \\t%s\\n' % ('atom', 'emit', 'emit_energy', 'yield', 'transmission', 'net_sensitivity', 'sensitivity*concentration')\n        if print2screen:\n            print( out1)\n        fo.write(out1)\n    for (ii, atom) in enumerate(Atoms):\n        # MN replace:\n        atnum=f1f2.AtSym2AtNum(atom.AtSym)\n        # MN replace:\n        temp=f1f2.AtNum2f1f2Xsect(atnum, eV0)\n        xsect=temp[2]                           # photo-electric cross-section for fluorescence yield, temp[4] is total for attenuation\n        con=atom.Conc\n        for (nn, edge) in enumerate(edges):\n            emit=Fluo_lines[nn]\n            fy, emit_eV, emit_prob = fluo_yield(atom.AtSym, edge, emit, eV0)\n            print(emit)\n            if fy==0.0 or emit_prob==0:\n                continue                        # try next item if FY=0\n            else:\n                if xsect_resonant!=0.0:         # use input value near edge\n                    xsect=xsect_resonant\t# for cross-section near absoprtion edge\n                #print(xsect,fy,emit_prob)\n                net_yield=xsect*fy*emit_prob    # net_yield --> cross-section, yield, emission_probability\n                # net transmission --> transmission from surface through detector\n## ------------------   [self-absorption]     ------------------------------\n                trans_SelfAbsorp = 1.0           # for self-absorption.\n                if Include_SelfAbsorption=='Yes':\n                    sample.getPenetration(eV0)   # incident x-ray attenuation\n                    if fy*emit_eV*emit_prob==0:  # any one of three is zero\n                        break                    # skip\n                    sample.getLa(emit_eV)\n                    # account for incident x-ray attenuation, emitted x-ray attenuation\n                    trans_SelfAbsorp = sample.scale         # for elements that are not part of substrate\n                    if (atom in sample.ElemListFY):\n                        if atom.tag=='substrate1':\n                            trans_SelfAbsorp = sample.scale1  # for elements that are part of top substrate\n                        if atom.tag=='substrate2':\n                            trans_SelfAbsorp = sample.scale2  # for elements that are part of bottom substrate\n## ----------------------------------------------------------------------------\n            net_trans = Assemble_Detector(emit_eV, xHe, xAl,xKapton, WD, xsw)\n            net = net_yield*net_trans*trans_SelfAbsorp  # elemental sensitivity\n            inten = net*con  # sensitivity * concentration\n            if WriteFile=='Y':\n                out1='%s\\t%s\\t%6.1f   \\t%.3e   \\t%.3e   \\t%.3e   \\t%.3e\\n' % (atom.AtSym+'_'+edge, emit, emit_eV, net_yield, net_trans, net, inten)\n                fo.write(out1)\n            if print2screen:\n                print('%s %s %6.1f net_yield=%.3e net_trans=%.3e net=%.3e\\t' % (atom.AtSym+'_'+edge, emit, emit_eV, net_yield, net_trans, net))\n            #print(out1+'  %s, depth-dependent factor= %6.4f' % (atom.tag, trans_SelfAbsorp))\n            if emit=='Kb' and fy!=0:        # if above K edge, don't bother trying L edges\n                break\n    return textOut\n\n\n#def sim_spectra(eV0, Atoms, Conc, xHe=0, xAl=0, xKapton=0, WD=6.0, xsw=0, sample=''):\ndef sim_spectra(eV0, Atoms, xHe=0, xAl=0, xKapton=0, WD=6.0, xsw=0, sample=''):\n    # sample=sample matrix with object attribues to add self-absorption effect\n    # Atoms is a list with elements that have attributes AtSym, Conc, tag\n    if xsw==-1:     xKapton=xKapton-1   # no collimator\n    Include_SelfAbsorption='Yes'\n    Print2Screen='No'\n    if sample=='': Include_SelfAbsorption='No'\n    if xsw!=0:  print('XSW measurements')\n    xx=[]; yy=[]; tag=[];   intensity_max=-10.0; LoLimit=1e-10\n    angle0=''; text1=''\n    if sample!='':      # sample matrix option is used\n        angle0=str(sample.angle*180./math.pi)\n        angle0=angle0[:5]\n        for (ii, item) in enumerate(sample.ElemListFY):  # add matrix elements to the lists\n            Atoms.append(item)\n    outputfile='simSpectrum_table.txt'\n    fo=open(outputfile, 'w')\n    out1='#incident x-ray at '+str(eV0)+' eV and '+angle0+' Deg.\\n'\n    if Print2Screen=='Yes': print(out1)\n    fo.write(out1)\n    out1='#Emission\\tenergy(eV)\\tintensity \\n'\n    if Print2Screen=='Yes': print(out1)\n    fo.write(out1)\n    out2='#'\n    for (ix,atom) in enumerate(Atoms):\n        # MN replace:\n        atnum=f1f2.AtSym2AtNum(atom.AtSym)\n        # con=Conc[ix]\n        con=atom.Conc\n        out2=out2+atom.AtSym+'['+str(con)+']   '\n        for edge in ['K', 'L1', 'L2', 'L3']:\n            # MN replace:\n            temp=f1f2.AtNum2f1f2Xsect(atnum, eV0)\n            xsect=temp[2]           # photoelectric crosssection for each element at incident x-ray, fluorescence yield\n            # MN replace:\n            temp=elam.use_ElamFY(atom.AtSym, edge)\n            edge_eV=float(temp[2])   # absorption edge\n            if eV0>edge_eV:\n                fy=float(temp[3])\n                for EmitLine in temp[4]:\n                    EmitName=EmitLine[1]\n                    emit_eV=float(EmitLine[2])\n                    emit_prob=float(EmitLine[3])\n                    if emit_eV<fluo_emit_min:  continue        # ignore fluorescence below fluo_emit_min (global variable)\n                    name = atom.AtSym + '_'+ EmitName\n                    # net transmission --> transmission from surface through detector\n## ------------------   [self-absorption]     ------------------------------\n                    trans_SelfAbsorp = 1.0              # for self-absorption.\n                    if Include_SelfAbsorption=='Yes':\n                        sample.getPenetration(eV0)      # incident x-ray attenuation\n                        eV0str=str(eV0)\n                        text1=' absorption_length1(%seV)= %2.2e%s \\\n                                absorption_length2(%seV)= %2.2e%s' % (eV0str, sample.la1*1.e4, 'microns', eV0str, sample.la2*1.e4, 'microns')\n                        # text1 is added to sample.txt later\n                        sample.getLa(emit_eV)           # emitted fluorescence attenuation\n                        trans_SelfAbsorp = sample.scale # for elements that are not part of substrate\n                        if (atom in sample.ElemListFY):\n                            if atom.tag=='substrate1':\n                                trans_SelfAbsorp = sample.scale1  # for elements that are part of top substrate\n                            if atom.tag=='substrate2':\n                                trans_SelfAbsorp = sample.scale2  # for elements that are part of bottom substrate\n## ----------------------------------------------------------------------------\n                    trans = Assemble_Detector(emit_eV, xHe, xAl,xKapton, WD, xsw)\n                    intensity = con * fy * emit_prob * xsect * trans * trans_SelfAbsorp\n                    if intensity<LoLimit: continue            # skip weak emission, arbtraray limit =1e-10.\n                    if intensity>intensity_max: intensity_max=intensity\n                    xx.append(emit_eV);    yy.append(intensity);   tag.append(name)\n    for ix in range(len(yy)):\n        yy[ix]=yy[ix]/intensity_max*100.00          # makes the strongest line to 100.0\n        out1='%s\\t%f\\t%f \\n' % (tag[ix], xx[ix], yy[ix])\n        if Print2Screen=='Yes': print(out1)\n        fo.write(out1)\n    if Print2Screen=='Yes': print(out2)\n    fo.write(out2)\n    fo.close()\n    out1=sim_GaussPeaks(xx, yy, det_res, eV0)        # det_res: detector resoultion for Gaussian width (global variable)\n    if Include_SelfAbsorption=='Yes':\n        sample.txt=sample.txt+text1                 # sample.txt is combined to output of cal_NetYield\n    text=cal_NetYield2(eV0, Atoms, xHe, xAl, xKapton, WD, xsw, sample=sample)  # calculate net yield with weight-averaged emission\n    print(out2)\n    return text  # cal_NetYield2 output is str with number densities of elements\n\n\ndef sim_GaussPeaks(xx, yy, width, eV0):  #xx, yy: lists, width: a peak width, eV0: incident energy\n    xline=[]; yline=[]; dX=10.0;    minX=fluo_emit_min #10eV steps, lowest-->fluo_emit_min\n    amp=100                             # arbitrary multiplier to shift up spectrum\n    NumOfSteps = int((eV0-minX)/dX)\n    NumOfPeaks = len(xx)\n    for ix in range(NumOfSteps+1):\n        xline.append(0);  yline.append(0)\n    for (iy,peak) in enumerate(xx):\n        X0=float(peak)\n        Y0=float(yy[iy])\n        for ix in range(NumOfSteps+1):\n            energy = minX + ix*dX\n            inten = Y0*math.exp(-((energy-X0)/width)**2)*amp\n            xline[ix]=energy\n            yline[ix]+=inten\n    outputfile='simSpectrum_plot.txt'\n    fo=open(outputfile, 'w')\n#    DetectorLimit=1e5                   # upperlimit for total counts to 1e5 (1e5 CPS)\n    LoLimit=0.001                         # low limit for each channel\n#    total=0.0\n    factor=1.0\n    for ix in range(NumOfSteps+1):\n        if yline[ix]<LoLimit: yline[ix]=LoLimit\n#        total+=yline[ix]  # add counts\n#    factor=total/DetectorLimit\n    for ix in range(NumOfSteps+1):\n        yline[ix]=yline[ix]/factor\n        out1=str(xline[ix])+'\\t'+str(yline[ix])+'\\n'\n        fo.write(out1)\n    fo.close()\n    #return xline, yline\n\n\nclass input_param:\n    def __init__(self, eV0=14000,\n                 Atoms=[],\n                 xHe=0.0,\n                 xAl=0,\n                 xKap=0,\n                 WD=6.0,\n                 xsw=0):\n        if Atoms==[]:\n            atom1=ElemFY()\n            Atoms.append(atom1)\n        self.eV0=eV0\n        #incident x-ray energy in eV\n        list1=[]; list2=[]\n        for item in Atoms:\n            list1.append(item.AtSym)\n            list2.append(item.Conc)\n        self.Atoms=list1\n        #elements list\n        self.Conc=list2\n        #relative concentrations list\n        self.xHe=xHe\n        #He gas path before collimator?\n        self.xAl=xAl\n        #number of Al foils as attenuator\n        self.xKap=xKap\n        #number of Kapton foils as attenuator\n        self.WD=WD\n        #working distance in cm\n        self.xsw=xsw\n        #x-ray standing wave setup?  WD=3.0 for xsw=1\n\n\n\n# ----------------------------------------------------------------\n\n\n\nif __name__=='__main__':\n    testing = 0\n    if testing:\n        #atom0='Fe'\n        #emission0='Ka'\n        #eV0=10000.\n        #edge0='K'\n        #eV1=6400.\n        #mat0=Material('SiO2', 2.2, 0.001)\n        #mat0.getLa(8000)\n        #print(mat0.la, mat0.trans)\n        #print(Assemble_QuadVortex(eV1))\n        #print(Assemble_Collimator(eV1, xHe=1, xAl=0,xKapton=0, WD=6.0, xsw=0))\n        # MN replace:\n        matrix=SampleMatrix2('CaCO3', f1f2.nominal_density('CaCO3'), 0.001,'Fe2O3', f1f2.nominal_density('Fe2O3'), 0.001, 45.,  'all')\n        eV0=7500.\n        Atoms=[]\n        atom=ElemFY('La', 10e-6);     Atoms.append(atom)\n        atom=ElemFY('Ce', 10e-6);     Atoms.append(atom)\n        atom=ElemFY('Nd', 10e-6);     Atoms.append(atom)\n        for (ii, item) in enumerate(matrix.ElemListFY):\n            pass\n        sim_spectra(eV0, Atoms, sample=matrix)  # xKapton=-1 to remove WD60, -2 for WD30\n    else:\n        # March 2012 for Nov2011 beamtime\n        eV0 = 10000.\n        print2screen=0\n        Atoms = []\n        atom=ElemFY('Al', 10e-6);     Atoms.append(atom)\n        atom=ElemFY('Si', 10e-6);     Atoms.append(atom)\n        atom=ElemFY('Ca', 10e-6);     Atoms.append(atom)\n        atom=ElemFY('Cr', 10e-6);     Atoms.append(atom)\n        atom=ElemFY('Mn', 10e-6);     Atoms.append(atom)\n        atom=ElemFY('Fe', 10e-6);     Atoms.append(atom)\n        atom=ElemFY('Ni', 10e-6);     Atoms.append(atom)\n        #sim_spectra(eV0, Atoms, xHe=1, xAl=0, xKapton=0, WD=3.0, xsw=1, sample='')\n        #Assemble_QuadVortex(1486.56)\n        #Assemble_Collimator(1486.56, 1, 0, 0, 3., 1)\n        #\n        air_path = 1.088\n        He_path = 1.912\n        air=Material('N1.56O0.48C0.03Ar0.01Kr0.000001Xe0.0000009', 0.0013, air_path)\n        kapton=Material('C22H10O4N2', 1.42, 0.000762)       # 0.3mil thick\n        HeGas=Material('He', 0.00009, He_path)\n        AlFoil=Material('Al', 2.72, 0.00381)                # 1.5mil thick\n        #\n        from math import *\n        emitE = [\n            1486.4, 1557.0, 1739.6, 1837.0, 3691.1, 4013.1, 5411.6,\n            5947.0, 5896.5, 6492.0, 6400.8, 7059.6, 7474.4, 8266.6\n            ]\n        for eV1 in emitE:\n            air.getLa(eV1, 1)   # 1 means number of layers here.\n            print( eV1, air.la, exp(-1./air.la))\n\n\n'''\ndef AtSym2FY(AtSym, Shell):  #returns fluorescence yield using atomic symbol and edge(K,L1,L2,L3,M)\n    out=elam.use_ElamFY(AtSym, Shell)\n    #AtSym, edge, edge-energy, FY, [ [transition, emission, energy, probability],[]...]\n    FY=out[3]\n    return FY\n\nclass Element:\n    def __init__(self, AtNum, AtWt, f1, f2, Xsection):\n        self.AtNum=AtNum\n        self.AtWt=AtWt              #atomic weight g/mol\n        self.f1=f1                  #real part of scattering factor\n        self.f2=f2                  #imaginary part of scattering factor\n        self.Xsection=Xsection      #atomic crossection Barns/atom\n        # f1, f2, Xsection depends on incident x-ray energy\n\n\ndef setElement(AtSym, shell, eV0):\n    AtNum=AtSym2AtNum(AtSym)\n    AtWt=AtSym2AtWt(AtSym)\n    f1f2=AtNum2f1f2Xsect(AtNum, eV0)\n    AtSym=Element(AtNum, AtWt, f1f2[0], f1f2[1], f1f2[2])\n    return AtSym\n\n\nclass input_param:\n    def __init__(self, eV0=14000,\n                 Atoms=[],\n                 xHe=0.0,\n                 xAl=0,\n                 xKap=0,\n                 WD=6.0,\n                 xsw=0):\n        if Atoms==[]:\n            atom1=ElemFY()\n            Atoms.append(atom1)\n        self.eV0=eV0\n        #incident x-ray energy in eV\n        list1=[]; list2=[]\n        for item in Atoms:\n            list1.append(item.AtSym)\n            list2.append(item.Conc)\n        self.Atoms=list1\n        #elements list\n        self.Conc=list2\n        #relative concentrations list\n        self.xHe=xHe\n        #He gas path before collimator?\n        self.xAl=xAl\n        #number of Al foils as attenuator\n        self.xKap=xKap\n        #number of Kapton foils as attenuator\n        self.WD=WD\n        #working distance in cm\n        self.xsw=xsw\n        #x-ray standing wave setup?  WD=3.0 for xsw=1\n'''\n", "meta": {"hexsha": "cb6ac89b69157fda29df71958d080fdb12469011", "size": 37433, "ext": "py", "lang": "Python", "max_stars_repo_path": "plugins/xsw/fluo_det.py", "max_stars_repo_name": "bruceravel/xraylarch", "max_stars_repo_head_hexsha": "a8179208872d43bd23453fa0c64680e11bc2b5ed", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "plugins/xsw/fluo_det.py", "max_issues_repo_name": "bruceravel/xraylarch", "max_issues_repo_head_hexsha": "a8179208872d43bd23453fa0c64680e11bc2b5ed", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plugins/xsw/fluo_det.py", "max_forks_repo_name": "bruceravel/xraylarch", "max_forks_repo_head_hexsha": "a8179208872d43bd23453fa0c64680e11bc2b5ed", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.5606060606, "max_line_length": 177, "alphanum_fraction": 0.5750006679, "include": true, "reason": "import numpy", "num_tokens": 10276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.24508501864634824, "lm_q1q2_score": 0.15876564165880927}}
{"text": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2019 Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG),\n# acting on behalf of its Max Planck Institute for Intelligent Systems and the\n# Max Planck Institute for Biological Cybernetics. All rights reserved.\n#\n# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is holder of all proprietary rights\n# on this computer program. You can only use this computer program if you have closed a license agreement\n# with MPG or you get the right to use the computer program from someone who is authorized to grant you that right.\n# Any use of the computer program without a valid license is prohibited and liable to prosecution.\n# Contact: ps-license@tuebingen.mpg.de\n#\n#\n# If you use this code in a research publication please consider citing the following:\n#\n# Expressive Body Capture: 3D Hands, Face, and Body from a Single Image <https://arxiv.org/abs/1904.05866>\n# AMASS: Archive of Motion Capture as Surface Shapes <https://arxiv.org/abs/1904.03278>\n#\n#\n# Code Developed by:\n# Nima Ghorbani <https://www.linkedin.com/in/nghorbani/>\n# Vassilis Choutas <https://ps.is.tuebingen.mpg.de/employees/vchoutas> for ContinousRotReprDecoder\n\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom pytorch3d.transforms.rotation_conversions import matrix_to_axis_angle as matrot2aa\n\n__all__ = [\n    'VPoserV1',\n    'VPoserV2',\n    'create'\n]\n\nclass BatchFlatten(nn.Module):\n    def __init__(self):\n        super(BatchFlatten, self).__init__()\n        self._name = 'batch_flatten'\n\n    def forward(self, x):\n        return x.view(x.shape[0], -1)\n\n\nclass ContinousRotReprDecoder(nn.Module):\n    def __init__(self):\n        super(ContinousRotReprDecoder, self).__init__()\n\n    def forward(self, module_input):\n        reshaped_input = module_input.view(-1, 3, 2)\n\n        b1 = F.normalize(reshaped_input[:, :, 0], dim=1)\n\n        dot_prod = torch.sum(b1 * reshaped_input[:, :, 1], dim=1, keepdim=True)\n        b2 = F.normalize(reshaped_input[:, :, 1] - dot_prod * b1, dim=-1)\n        b3 = torch.cross(b1, b2, dim=1)\n\n        return torch.stack([b1, b2, b3], dim=-1)\n\n\nclass NormalDistDecoder(nn.Module):\n    def __init__(self, num_feat_in, latentD):\n        super(NormalDistDecoder, self).__init__()\n\n        self.mu = nn.Linear(num_feat_in, latentD)\n        self.logvar = nn.Linear(num_feat_in, latentD)\n\n    def forward(self, Xout):\n        return torch.distributions.normal.Normal(self.mu(Xout), F.softplus(self.logvar(Xout)))\n\n\nclass VPoserV1(nn.Module):\n    def __init__(self, num_neurons=512, latentD=32, data_shape=[1,21,3], use_cont_repr=True):\n        super(VPoserV1, self).__init__()\n\n        self.latentD = latentD\n        self.use_cont_repr = use_cont_repr\n\n        n_features = np.prod(data_shape)\n        self.num_joints = data_shape[1]\n\n        self.bodyprior_enc_bn1 = nn.BatchNorm1d(n_features)\n        self.bodyprior_enc_fc1 = nn.Linear(n_features, num_neurons)\n        self.bodyprior_enc_bn2 = nn.BatchNorm1d(num_neurons)\n        self.bodyprior_enc_fc2 = nn.Linear(num_neurons, num_neurons)\n        self.bodyprior_enc_mu = nn.Linear(num_neurons, latentD)\n        self.bodyprior_enc_logvar = nn.Linear(num_neurons, latentD)\n        self.dropout = nn.Dropout(p=.1, inplace=False)\n\n        self.bodyprior_dec_fc1 = nn.Linear(latentD, num_neurons)\n        self.bodyprior_dec_fc2 = nn.Linear(num_neurons, num_neurons)\n\n        if self.use_cont_repr:\n            self.rot_decoder = ContinousRotReprDecoder()\n\n        self.bodyprior_dec_out = nn.Linear(num_neurons, self.num_joints* 6)\n\n    def encode(self, Pin):\n        '''\n\n        :param Pin: Nx(numjoints*3)\n        :return:\n        '''\n        Xout = Pin.view(Pin.size(0), -1)  # flatten input\n        Xout = self.bodyprior_enc_bn1(Xout)\n\n        Xout = F.leaky_relu(self.bodyprior_enc_fc1(Xout), negative_slope=.2)\n        Xout = self.bodyprior_enc_bn2(Xout)\n        Xout = self.dropout(Xout)\n        Xout = F.leaky_relu(self.bodyprior_enc_fc2(Xout), negative_slope=.2)\n        return torch.distributions.normal.Normal(self.bodyprior_enc_mu(Xout), F.softplus(self.bodyprior_enc_logvar(Xout)))\n\n    def decode(self, Zin):\n        bs = Zin.shape[0]\n\n        Xout = F.leaky_relu(self.bodyprior_dec_fc1(Zin), negative_slope=.2)\n        Xout = self.dropout(Xout)\n        Xout = F.leaky_relu(self.bodyprior_dec_fc2(Xout), negative_slope=.2)\n        Xout = self.bodyprior_dec_out(Xout)\n        if self.use_cont_repr:\n            Xout = self.rot_decoder(Xout)\n        else:\n            Xout = torch.tanh(Xout)\n        \n        return {\n            'pose_body': matrot2aa(Xout.view(-1, 3, 3)).view(bs, -1, 3),\n            'pose_body_matrot': Xout.view(bs, -1, 9)\n        }\n\n    def forward(self, Pin):\n        '''\n\n        :param Pin: aa: Nx1xnum_jointsx3\n        :return:\n        '''\n        q_z = self.encode(Pin)\n        q_z_sample = q_z.rsample()\n        decode_results = self.decode(q_z_sample)\n        decode_results.update({'poZ_body_mean': q_z.mean, 'poZ_body_std': q_z.scale, 'q_z': q_z})\n        return decode_results\n\n    def sample_poses(self, num_poses, seed=None):\n        np.random.seed(seed)\n        dtype = self.bodyprior_dec_fc1.weight.dtype\n        device = self.bodyprior_dec_fc1.weight.device\n        self.eval()\n        with torch.no_grad():\n            Zgen = torch.tensor(np.random.normal(0., 1., size=(num_poses, self.latentD)), dtype=dtype).to(device)\n        return self.decode(Zgen)\n\n\nclass VPoserV2(nn.Module):\n    def __init__(self, num_neurons=512,latentD=32):\n        super(VPoserV2, self).__init__()\n\n        num_neurons, self.latentD = num_neurons, latentD\n\n        self.num_joints = 21\n        n_features = self.num_joints * 3\n\n        self.encoder_net = nn.Sequential(\n            BatchFlatten(),\n            nn.BatchNorm1d(n_features),\n            nn.Linear(n_features, num_neurons),\n            nn.LeakyReLU(),\n            nn.BatchNorm1d(num_neurons),\n            nn.Dropout(0.1),\n            nn.Linear(num_neurons, num_neurons),\n            nn.Linear(num_neurons, num_neurons),\n            NormalDistDecoder(num_neurons, self.latentD)\n        )\n\n        self.decoder_net = nn.Sequential(\n            nn.Linear(self.latentD, num_neurons),\n            nn.LeakyReLU(),\n            nn.Dropout(0.1),\n            nn.Linear(num_neurons, num_neurons),\n            nn.LeakyReLU(),\n            nn.Linear(num_neurons, self.num_joints * 6),\n            ContinousRotReprDecoder(),\n        )\n\n    def encode(self, pose_body):\n        '''\n        :param Pin: Nx(numjoints*3)\n        :param rep_type: 'matrot'/'aa' for matrix rotations or axis-angle\n        :return:\n        '''\n        return self.encoder_net(pose_body)\n\n    def decode(self, Zin):\n        bs = Zin.shape[0]\n\n        prec = self.decoder_net(Zin)\n\n        return {\n            'pose_body': matrot2aa(prec.view(-1, 3, 3)).view(bs, -1, 3),\n            'pose_body_matrot': prec.view(bs, -1, 9)\n        }\n\n\n    def forward(self, pose_body):\n        '''\n        :param Pin: aa: Nx1xnum_jointsx3 / matrot: Nx1xnum_jointsx9\n        :param input_type: matrot / aa for matrix rotations or axis angles\n        :param output_type: matrot / aa\n        :return:\n        '''\n\n        q_z = self.encode(pose_body)\n        q_z_sample = q_z.rsample()\n        decode_results = self.decode(q_z_sample)\n        decode_results.update({'poZ_body_mean': q_z.mean, 'poZ_body_std': q_z.scale, 'q_z': q_z})\n        return decode_results\n\n    def sample_poses(self, num_poses, seed=None):\n        np.random.seed(seed)\n\n        some_weight = [a for a in self.parameters()][0]\n        dtype = some_weight.dtype\n        device = some_weight.device\n        self.eval()\n        with torch.no_grad():\n            Zgen = torch.tensor(np.random.normal(0., 1., size=(num_poses, self.latentD)), dtype=dtype, device=device)\n\n        return self.decode(Zgen)\n\n\ndef create(f_state_dict,version):\n    if version==1:\n        vposer = VPoserV1()\n    elif version==2:\n        vposer = VPoserV2()\n    state_dict = torch.load(f_state_dict,map_location='cpu')\n    vposer.load_state_dict(state_dict)\n    vposer.eval()\n    return vposer", "meta": {"hexsha": "a09429dd99d7cc73509232a522e159f10321a2a6", "size": 8135, "ext": "py", "lang": "Python", "max_stars_repo_path": "vposer/vposer.py", "max_stars_repo_name": "zzilch/vposer", "max_stars_repo_head_hexsha": "1e7afd2f08d27fa58a4e489cd9c22dbb5ec3fe73", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-04T09:06:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-04T09:06:02.000Z", "max_issues_repo_path": "vposer/vposer.py", "max_issues_repo_name": "zzilch/vposer", "max_issues_repo_head_hexsha": "1e7afd2f08d27fa58a4e489cd9c22dbb5ec3fe73", "max_issues_repo_licenses": ["Xnet", "X11"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vposer/vposer.py", "max_forks_repo_name": "zzilch/vposer", "max_forks_repo_head_hexsha": "1e7afd2f08d27fa58a4e489cd9c22dbb5ec3fe73", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3248945148, "max_line_length": 122, "alphanum_fraction": 0.6443761524, "include": true, "reason": "import numpy", "num_tokens": 2138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.2942149659744614, "lm_q1q2_score": 0.15857693429292702}}
{"text": "import dataclasses\nimport functools\nimport itertools\nimport logging\nimport textwrap\nfrom functools import partial\nfrom typing import Any\nfrom typing import Callable\nfrom typing import List\nfrom typing import Optional\nfrom unittest.mock import patch\n\nimport numpy\nimport sympy\nimport torch.fx\nimport torch.utils._pytree as pytree\nfrom sympy import Expr\nfrom sympy import Integer\n\nfrom . import config\nfrom . import dependencies\nfrom .codegen.common import product\nfrom .dependencies import extract_read_writes\nfrom .virtualized import V\nfrom .virtualized import ops\n\nlog = logging.getLogger(__name__)\nindent = functools.partial(textwrap.indent, prefix=\"  \")\n\n\ndef inverse_reorder(order):\n    inv_order = dict(zip(order, range(len(order))))\n\n    def reindex(index):\n        assert len(index) == len(inv_order)\n        return [index[inv_order[i]] for i in range(len(index))]\n\n    return reindex\n\n\ndef fuse_reindexing(reindex1, reindex2):\n    def reindex(index):\n        return reindex1(reindex2(index))\n\n    return reindex\n\n\nclass ModularIndexing(sympy.Function):\n    \"\"\"\n    ModularIndexing(a, b, c) => (a // b) % c\n    \"\"\"\n\n    nargs = (3,)\n\n    @classmethod\n    def eval(cls, base, divisor, modulus):\n        if base == 0 or modulus == 1:\n            return sympy.Integer(0)\n\n        if (\n            isinstance(base, sympy.Integer)\n            and isinstance(divisor, sympy.Integer)\n            and isinstance(modulus, sympy.Integer)\n        ):\n            return (base // divisor) % modulus\n\n        if divisor != 1 and sympy.gcd(base, divisor) == divisor:\n            return ModularIndexing(base / divisor, sympy.Integer(1), modulus)\n\n        if isinstance(base, sympy.Add):\n            new_terms = []\n            for term in base.args:\n                if sympy.gcd(term, modulus * divisor) != modulus * divisor:\n                    new_terms.append(term)\n            if len(new_terms) != len(base.args):\n                return ModularIndexing(sum(new_terms), divisor, modulus)\n\n\nclass IndexingDiv(sympy.Function):\n    \"\"\"\n    a // b used in indexing where we need to be careful about simplification.\n    We don't use sympy.FloorDiv to bypass some simplification rules.\n    \"\"\"\n\n    nargs = (2,)\n\n    @classmethod\n    def eval(cls, base, divisor):\n        if base == 0:\n            return sympy.Integer(0)\n        if divisor == 1:\n            return base\n        if isinstance(base, sympy.Integer) and isinstance(divisor, sympy.Integer):\n            return base // divisor\n        if sympy.gcd(base, divisor) == divisor:\n            return base / divisor\n\n\nclass CleanDiv(IndexingDiv):\n    \"\"\"\n    Div where we can assume no rounding.\n    This is to enable future optimizations.\n    \"\"\"\n\n    pass\n\n\nclass IRNode(object):\n    def str_helper(self, lines):\n        lines = indent(\",\\n\".join(map(str, lines)))\n        return f\"{type(self).__name__}(\\n{lines}\\n)\"\n\n    def is_user_of(self, name):\n        return any(name == dep.name for dep in self.get_reads())\n\n    def get_numel(self):\n        return product(self.get_size())\n\n\n@dataclasses.dataclass\nclass Loops(IRNode):\n    device: torch.device\n    dtype: torch.dtype\n    inner_fn: Callable\n    ranges: List[Expr]\n\n    def __str__(self, names=(\"ranges\",)):\n        return self.str_helper(\n            [\n                f\"'{self.device.type}'\",\n                str(self.dtype),\n                self.inner_fn_str(),\n            ]\n            + [f\"{name}={getattr(self, name)}\" for name in names]\n        )\n\n    __repr__ = __str__\n\n    def get_dtype(self):\n        return self.dtype\n\n    def get_device(self):\n        return self.device\n\n    def get_size(self):\n        return self.ranges\n\n    def is_extern(self):\n        return False\n\n    @classmethod\n    def create(cls, *args, **kwargs):\n        return TensorBox.create(cls(*args, **kwargs))\n\n    @staticmethod\n    def _index(ranges, prefix=\"i\"):\n        return [\n            sympy.Integer(0) if s == 1 else sympy.Symbol(f\"{prefix}{n}\")\n            for n, s in enumerate(ranges)\n        ]\n\n    def inner_fn_str(self):\n        try:\n            with V.set_ops_handler(V.MockHandler()), patch.object(\n                FlexibleLayout, \"allow_indexing\", True\n            ):\n                return self.inner_fn(self._index(self.ranges))\n        except Exception as e:\n            return f\"inner_fn(): {e}\"\n\n    def is_zero_elements(self):\n        return any(r == 0 for r in self.ranges)\n\n    def get_reads(self):\n        with patch.object(FlexibleLayout, \"allow_indexing\", True):\n            if self.get_reduction_type():\n                return extract_read_writes(\n                    self.make_loader(),\n                    self.get_size(),\n                    self.get_reduction_size(),\n                ).reads\n            else:\n                return extract_read_writes(\n                    self.make_loader(),\n                    self.get_size(),\n                ).reads\n\n\nclass Pointwise(Loops):\n    def make_loader(self):\n        return self.inner_fn\n\n    def get_reduction_size(self):\n        return []\n\n    def get_reduction_type(self):\n        return None\n\n    def store_output(self, output_name, indexer, vars):\n        return ops.store(output_name, indexer(vars), self.inner_fn(vars))\n\n    def constant_to_device(self, device):\n        \"\"\"Move this to a given device. Requires that all reads are to constants.\"\"\"\n        loader = self.make_loader()\n        loader = patch.object(ConstantBuffer, \"override_device\", device)(loader)\n        return Pointwise(device, self.dtype, loader, self.ranges)\n\n\n@dataclasses.dataclass\nclass Reduction(Loops):\n    reduction_ranges: List[Expr]\n    reduction_type: str\n\n    def __str__(self):\n        return Loops.__str__(\n            self, names=(\"ranges\", \"reduction_ranges\", \"reduction_type\")\n        )\n\n    __repr__ = __str__\n\n    def get_reduction_size(self):\n        return self.reduction_ranges\n\n    def get_reduction_type(self):\n        return self.reduction_type\n\n    def store_reduction(self, output_name, indexer, vars, reduction_vars):\n        return ops.reduction(\n            output_name,\n            self.dtype,\n            self.reduction_type,\n            indexer(vars),\n            self.inner_fn(vars, reduction_vars),\n        )\n\n    def index_length(self):\n        return len(self.ranges) + len(self.reduction_ranges)\n\n    def inner_fn_str(self):\n        try:\n            with V.set_ops_handler(V.MockHandler()), patch.object(\n                FlexibleLayout, \"allow_indexing\", True\n            ):\n                return self.inner_fn(\n                    self._index(self.ranges), self._index(self.reduction_ranges, \"r\")\n                )\n        except Exception as e:\n            return f\"inner_fn(): {e}\"\n\n    def constant_to_device(self, device):\n        \"\"\"Move this to a given device. Requires that all reads are to constants.\"\"\"\n        loader = self.make_loader()\n        loader = patch.object(ConstantBuffer, \"override_device\", device)(loader)\n        return Reduction(\n            device,\n            self.dtype,\n            loader,\n            self.ranges,\n            self.reduction_ranges,\n            self.reduction_type,\n        )\n\n    @classmethod\n    def create(\n        cls,\n        device: torch.device,\n        dtype: torch.dtype,\n        inner_fn: Callable,\n        ranges: List[Expr],\n        reduction_ranges: List[Expr],\n        reduction_type: str,\n    ):\n        reduction_numel = product(reduction_ranges)\n        if reduction_numel == 1:\n            # this reduction is actually a pointwise op\n            def fn(index):\n                reduction_index = [sympy.Integer(0) for _ in reduction_ranges]\n                return inner_fn(index, reduction_index)\n\n            return Pointwise.create(device, dtype, fn, ranges)\n\n        return TensorBox.create(\n            Reduction(\n                device,\n                dtype,\n                inner_fn,\n                ranges,\n                reduction_ranges,\n                reduction_type,\n            )\n        )\n\n\ndef is_storage_and_layout(x):\n    try:\n        as_storage_and_layout(x, freeze=False)\n        return True\n    except NotImplementedError:\n        return False\n\n\ndef is_contiguous_storage_and_layout(x):\n    try:\n        buffer, layout = as_storage_and_layout(x, freeze=False)\n        return layout.is_contiguous()\n    except NotImplementedError:\n        return False\n\n\ndef as_storage_and_layout(x, freeze=True, want_contiguous=False):\n    \"\"\"Try to simplify x into a StorageBox and a Layout\"\"\"\n    if isinstance(x, TensorBox):\n        return as_storage_and_layout(\n            x.data, freeze=freeze, want_contiguous=want_contiguous\n        )\n    if isinstance(x, StorageBox) and isinstance(x.data, Buffer):\n        if freeze:\n            if want_contiguous:\n                x.data.freeze_layout()\n            else:\n                x.data.decide_layout()\n        return x, x.data.layout\n    if isinstance(x, ReinterpretView):\n        buffer, _ = as_storage_and_layout(\n            x.data, freeze=freeze, want_contiguous=want_contiguous\n        )\n        return buffer, x.layout\n    raise NotImplementedError\n\n\nas_contiguous_storage_and_layout = functools.partial(\n    as_storage_and_layout, want_contiguous=True\n)\n\n\n@dataclasses.dataclass\nclass BaseView(IRNode):\n    data: IRNode\n\n    def get_dtype(self):\n        return self.data.get_dtype()\n\n    def get_device(self):\n        return self.data.get_device()\n\n    def get_name(self):\n        return self.data.get_name()\n\n    def mark_reuse(self, users):\n        return self.data.mark_reuse(users)\n\n    def realize(self):\n        return self.data.realize()\n\n    def get_storage_numel(self):\n        return self.data.get_storage_numel()\n\n    def is_extern(self):\n        return self.data.is_extern()\n\n    def get_reads(self):\n        with patch.object(FlexibleLayout, \"allow_indexing\", True):\n            return extract_read_writes(\n                self.make_loader(),\n                self.get_size(),\n            ).reads\n\n\n@dataclasses.dataclass\nclass ExpandView(BaseView):\n    size: List[Expr]\n\n    @staticmethod\n    def _normalize_size(x, new_size):\n        \"\"\"Replace `-1` with correct sizes\"\"\"\n        new_size = list(map(sympy.expand, new_size))\n        old_size = x.get_size()\n        old_size = [None] * (len(new_size) - len(old_size)) + list(old_size)\n        assert len(new_size) == len(old_size)\n        for i in range(len(new_size)):\n            if new_size[i] == -1:\n                assert old_size[i] is not None\n                new_size[i] = old_size[i]\n        return new_size\n\n    @classmethod\n    def create(cls, x, new_size):\n        new_size = cls._normalize_size(x, new_size)\n\n        if is_storage_and_layout(x):\n            storage, old_layout = as_storage_and_layout(x)\n            skip = len(new_size) - len(old_layout.size)\n            assert skip >= 0\n            new_stride = [sympy.Integer(0)] * skip\n            for stride, size in zip(old_layout.stride, old_layout.size):\n                new_stride.append(stride if size != 1 else sympy.Integer(0))\n            new_layout = FixedLayout(\n                old_layout.device,\n                old_layout.dtype,\n                list(new_size),\n                new_stride,\n                old_layout.offset,\n            )\n            return ReinterpretView(storage, new_layout)\n\n        return ExpandView(x, new_size)\n\n    def get_size(self):\n        return self.size\n\n    def make_loader(self):\n        target = self.get_size()\n        actual = self.data.get_size()\n        skip = len(target) - len(actual)\n        inner = self.data.make_loader()\n\n        def load(index):\n            index = list(index[skip:])\n            assert len(index) == len(actual)\n            for i in range(len(actual)):\n                if actual[i] == 1:\n                    # zero out broadcast dimension\n                    index[i] = sympy.Integer(0)\n            return inner(index)\n\n        return load\n\n\n@dataclasses.dataclass\nclass PermuteView(BaseView):\n    dims: List[Expr]\n\n    @classmethod\n    def create(cls, x, dims):\n        assert set(dims) == set(range(len(dims)))\n\n        if is_storage_and_layout(x):\n            storage, old_layout = as_storage_and_layout(x)\n            new_layout = FixedLayout(\n                old_layout.device,\n                old_layout.dtype,\n                [old_layout.size[i] for i in dims],\n                [old_layout.stride[i] for i in dims],\n                old_layout.offset,\n            )\n            return ReinterpretView(storage, new_layout)\n\n        return PermuteView(x, dims)\n\n    def get_size(self):\n        assert set(self.dims) == set(range(len(self.dims)))\n        size = self.data.get_size()\n        return [size[i] for i in self.dims]\n\n    def make_loader(self):\n        inner = self.data.make_loader()\n        inv = {j: i for i, j in enumerate(self.dims)}\n        inv = [inv[i] for i in range(len(self.dims))]\n        assert set(inv) == set(range(len(self.dims)))\n\n        def load(index):\n            index = [index[i] for i in inv]\n            return inner(index)\n\n        return load\n\n\nclass SqueezeView(BaseView):\n    @classmethod\n    def create(cls, x):\n\n        if is_storage_and_layout(x):\n            storage, old_layout = as_storage_and_layout(x)\n            new_size = []\n            new_stride = []\n            for size, stride in zip(old_layout.size, old_layout.stride):\n                if size != 1:\n                    new_size.append(size)\n                    new_stride.append(stride)\n            new_layout = FixedLayout(\n                old_layout.device,\n                old_layout.dtype,\n                new_size,\n                new_stride,\n                old_layout.offset,\n            )\n            return ReinterpretView(storage, new_layout)\n\n        # redirect to a generic view\n        return View.create(x, [s for s in x.get_size() if s != 1])\n\n    @staticmethod\n    def squeezer(size):\n        new_size = [s for s in size if s != 1]\n        not_one = [i for i, s in enumerate(size) if s != 1]\n        length = len(size)\n\n        def reindex(index):\n            assert len(index) == len(not_one), f\"{index} {not_one}\"\n            new_index = [sympy.Integer(0)] * length\n            for idx, s in zip(not_one, index):\n                new_index[idx] = s\n            return tuple(new_index)\n\n        return new_size, reindex\n\n    def __init__(self, data):\n        assert False, \"use SqueezeView.create()\"\n\n\n@dataclasses.dataclass\nclass View(BaseView):\n    size: List[Expr]\n    reindex: Callable\n\n    def make_indexer(self):\n        base_indexer = self.data.make_indexer()\n\n        def indexer(idx):\n            return base_indexer(self.reindex(idx))\n\n        return indexer\n\n    @staticmethod\n    def handle_negative_index(idx, size):\n        idx = sympy.expand(idx)\n        size = sympy.expand(size)\n        sizevars = V.graph.sizevars\n        if sizevars.size_hint(idx) < 0:\n            sizevars.guard_lt(idx, 0)\n            idx = idx + size\n        return idx\n\n    def reindex_str(self):\n        index_old = [sympy.Symbol(f\"i{n}\") for n in range(len(self.size))]\n        index_new = list(self.reindex(index_old))\n        return f\"lambda {', '.join(map(str, index_old))}: {index_new}\"\n\n    def __str__(self):\n        return self.str_helper(\n            [self.data, f\"size={self.size}\", f\"reindex={self.reindex_str()}\"]\n        )\n\n    __repr__ = __str__\n\n    @classmethod\n    def create(cls, x, new_size):\n        assert isinstance(new_size, (tuple, list))\n        old_size, new_size = cls.resolve_negative_size(x.get_size(), new_size)\n\n        if is_contiguous_storage_and_layout(x):\n            storage, old_layout = as_contiguous_storage_and_layout(x)\n            new_layout = FixedLayout(\n                old_layout.device,\n                old_layout.dtype,\n                new_size,\n                FlexibleLayout.contiguous_strides(new_size),\n                old_layout.offset,\n            )\n            return ReinterpretView(storage, new_layout)\n\n        try:\n            reindex = cls.dynamic_reshape_indexer(old_size, new_size)\n        except AssertionError:\n            # optimistic algorithm failed, lets do a fallback\n            flat = [product(old_size)]\n            reindex1 = cls.dynamic_reshape_indexer(old_size, flat)\n            reindex2 = cls.dynamic_reshape_indexer(flat, new_size)\n            reindex = fuse_reindexing(reindex1, reindex2)\n\n        return cls(x, tuple(new_size), reindex)\n\n    @staticmethod\n    def resolve_negative_size(old_size, new_size):\n        new_size = [\n            sympy.expand(x).subs(V.graph.sizevars.replacements) for x in new_size\n        ]\n        old_size = [\n            sympy.expand(x).subs(V.graph.sizevars.replacements) for x in old_size\n        ]\n\n        new_size = list(new_size)\n        for i in range(len(new_size)):\n            if new_size[i] == -1:\n                new_size[i] = sympy.Integer(1)\n                new_size[i] = CleanDiv(product(old_size), product(new_size))\n                break\n\n        V.graph.sizevars.guard_equals(product(old_size), product(new_size))\n        return old_size, new_size\n\n    @staticmethod\n    def dynamic_reshape_indexer(old_size, new_size):\n        \"\"\"\n        Perform a reshape entirely by modifying indexing math\n        \"\"\"\n        size_hint = V.graph.sizevars.size_hint\n        vars = [sympy.Symbol(f\"view{i}\") for i in range(len(new_size))]\n\n        stack_new = list(zip(vars, new_size))\n        stack_old = list(old_size)\n\n        view_expr = []\n        while stack_new and stack_old:\n            size_old = stack_old.pop()\n            var, size_new = stack_new.pop()\n            if size_old == 1:\n                view_expr.append(sympy.Integer(0))\n                stack_new.append((var, size_new))  # re-add\n            elif size_new == 1:\n                stack_old.append(size_old)  # re-add\n            elif size_hint(size_new) == size_hint(size_old):\n                view_expr.append(var)\n                V.graph.sizevars.guard_equals(size_new, size_old)\n            elif size_hint(size_new) < size_hint(size_old):\n                while size_hint(size_new) < size_hint(size_old):\n                    var2, size_new2 = stack_new.pop()\n                    var = var2 * size_new + var\n                    size_new = size_new * size_new2\n                view_expr.append(var)\n                V.graph.sizevars.guard_equals(size_new, size_old)\n            elif size_hint(size_new) > size_hint(size_old):\n                divisor = sympy.Integer(1)\n                modulus = size_old\n                view_expr.append(ModularIndexing(var, divisor, modulus))\n                divisor = divisor * modulus\n                while size_hint(size_new) > size_hint(size_old):\n                    modulus = stack_old.pop()\n                    view_expr.append(ModularIndexing(var, divisor, modulus))\n                    divisor = divisor * modulus\n                    size_old = size_old * modulus\n                V.graph.sizevars.guard_equals(size_new, size_old)\n            else:\n                assert False\n\n        while stack_old:\n            size_old = stack_old.pop()\n            assert size_old == 1\n            view_expr.append(sympy.Integer(0))\n\n        while stack_new:\n            var, size_new = stack_new.pop()\n            assert size_new == 1\n\n        view_expr = list(reversed(view_expr))\n        assert len(view_expr) == len(old_size)\n\n        def reindex(index):\n            assert len(index) == len(vars), (len(index), len(vars))\n            replacements = dict(zip(vars, index))\n            return tuple(x.subs(replacements) for x in view_expr)\n\n        return reindex\n\n    def get_size(self):\n        return self.size\n\n    def make_loader(self):\n        def load(index):\n            return inner(self.reindex(index))\n\n        inner = self.data.make_loader()\n        return load\n\n\n@dataclasses.dataclass\nclass ReinterpretView(BaseView):\n    \"\"\"Pretend our storage has a different layout\"\"\"\n\n    layout: \"Layout\"\n\n    def __str__(self):\n        return self.str_helper(\n            [\n                self.data,\n                self.layout,\n            ]\n        )\n\n    __repr__ = __str__\n\n    def get_name(self):\n        return self.data.get_name()\n\n    def get_device(self):\n        return self.layout.device\n\n    def get_dtype(self):\n        return self.layout.dtype\n\n    def get_size(self):\n        return self.layout.size\n\n    def get_stride(self):\n        return self.layout.stride\n\n    def make_loader(self):\n        def loader(index):\n            indexer = self.layout.make_indexer()\n            return ops.load(self.get_name(), indexer(index))\n\n        return loader\n\n    def make_indexer(self):\n        return self.layout.make_indexer()\n\n    def get_layout(self):\n        return self.layout\n\n    def freeze_layout(self):\n        pass\n\n    def codegen_reference(self):\n        size = V.graph.sizevars.codegen_shape_tuple(self.layout.size)\n        stride = V.graph.sizevars.codegen_shape_tuple(self.layout.stride)\n        offset = V.graph.sizevars.codegen_sizevar(self.layout.offset)\n        if offset != \"0\":\n            return f\"as_strided({self.get_name()}, {size}, {stride}, {offset})\"\n        return f\"as_strided({self.get_name()}, {size}, {stride})\"\n\n\nclass SliceView(View):\n    @classmethod\n    def create(cls, x, dim, start, end, step=1):\n        step = sympy.expand(step)\n        assert step > 0\n        try:\n            if start == 0 and end >= 2**63 and step == 1:\n                return x\n        except TypeError:\n            pass\n\n        sizevars = V.graph.sizevars\n        new_size = list(x.get_size())\n\n        start = cls.handle_negative_index(start, new_size[dim])\n        end = cls.handle_negative_index(end, new_size[dim])\n\n        end = sizevars.guard_min(end, new_size[dim])\n        start = sizevars.guard_min(sizevars.guard_min(start, new_size[dim]), end)\n        if start == 0 and sizevars.size_hint(end - new_size[dim]) == 0 and step == 1:\n            sizevars.guard_equals(end, new_size[dim])\n            return x\n\n        new_size[dim] = IndexingDiv(end - start + (step - 1), step)\n\n        if is_storage_and_layout(x):\n            # Fast path\n            storage, old_layout = as_storage_and_layout(x)\n            new_stride = list(old_layout.stride)\n            new_stride[dim] = new_stride[dim] * step\n            new_layout = FixedLayout(\n                old_layout.device,\n                old_layout.dtype,\n                new_size,\n                new_stride,\n                old_layout.offset + old_layout.stride[dim] * start,\n            )\n            return ReinterpretView(storage, new_layout)\n\n        def reindex(index):\n            assert len(index) == len(new_size), f\"wrong ndim {index} {new_size}\"\n            index = list(index)\n            index[dim] = index[dim] * step + start\n            return index\n\n        # redirect to a generic view\n        return SliceView(x, size=new_size, reindex=reindex)\n\n\nclass BaseConstant(IRNode):\n    def get_size(self):\n        return ()\n\n    def get_dtype(self):\n        return self.dtype\n\n    def get_device(self):\n        return self.device\n\n    def mark_reuse(self, users):\n        pass\n\n    def get_reads(self):\n        return ()\n\n    def is_extern(self):\n        return False\n\n\n@dataclasses.dataclass\nclass Constant(BaseConstant):\n    value: Any\n    dtype: torch.dtype\n    device: torch.device\n\n    def make_loader(self):\n        def loader(index):\n            return ops.constant(self.value, self.dtype)\n\n        return loader\n\n\n@dataclasses.dataclass\nclass IndexingConstant(BaseConstant):\n    index: Any\n    dtype: torch.dtype\n    device: torch.device\n\n    def make_loader(self):\n        def loader(index):\n            return ops.index_expr(self.index, self.dtype)\n\n        return loader\n\n\n@dataclasses.dataclass\nclass Layout(IRNode):\n    device: torch.device\n    dtype: torch.dtype\n    size: List[Expr]\n    stride: List[Expr]\n    offset: Expr = Integer(0)\n\n    def __str__(self):\n        offset = \"\"\n        if self.offset != 0:\n            offset = f\", offset={self.offset}\"\n        return (\n            f\"{type(self).__name__}('{self.device.type}', {self.dtype}, \"\n            f\"size={self.size}, stride={self.stride}{offset})\"\n        )\n\n    __repr__ = __str__\n\n    def is_contiguous(self):\n        for left, right, size in zip(\n            self.stride, FlexibleLayout.contiguous_strides(self.size), self.size\n        ):\n            if size != 1 and left != right:\n                return False\n        return True\n\n    def is_transposed(self):\n        for left, right, size in zip(\n            self.stride,\n            reversed(FlexibleLayout.contiguous_strides(self.size)),\n            self.size,\n        ):\n            if size != 1 and left != right:\n                return False\n        return True\n\n    def as_fixed(self):\n        return FixedLayout(\n            self.device,\n            self.dtype,\n            self.size,\n            self.stride,\n            self.offset,\n        )\n\n    def make_indexer(self):\n        assert (\n            FlexibleLayout.allow_indexing\n        ), f\"convert {type(self).__name__} to FixedLayout first\"\n        return self.as_fixed().make_indexer()\n\n\nclass FixedLayout(Layout):\n    \"\"\"A Tensor layout we cannot change\"\"\"\n\n    def make_indexer(self):\n        \"\"\"A closure containing math to read a given element\"\"\"\n\n        def indexer(index):\n            assert len(index) == len(self.stride) == len(self.size)\n            result = self.offset\n            for idx, stride, sz in zip(index, self.stride, self.size):\n                if sz != 1:\n                    result = result + idx * stride\n            return result\n\n        return indexer\n\n\nclass FlexibleLayout(Layout):\n    \"\"\"A Tensor layout we are allowed to change\"\"\"\n\n    allow_indexing = False\n\n    @staticmethod\n    def contiguous_strides(sizes):\n        if len(sizes) == 0:\n            return []\n        reversed_strides = [sympy.Integer(1)]\n        for size in reversed(sizes[1:]):\n            reversed_strides.append(size * reversed_strides[-1])\n        return list(reversed(reversed_strides))\n\n    @staticmethod\n    def ordered_strides(sizes, order):\n        assert set(range(len(sizes))) == set(order)\n        next_stride = sympy.Integer(1)\n        strides = [None] * len(order)\n\n        for i in order:\n            strides[i] = next_stride\n            next_stride = next_stride * sizes[i]\n        return strides\n\n    def as_stride_order(self, order):\n        assert len(self.size) == len(order)\n        return FixedLayout(\n            self.device,\n            self.dtype,\n            self.size,\n            self.ordered_strides(self.size, order),\n            self.offset,\n        )\n\n    def __init__(self, device, dtype, size):\n        super(FlexibleLayout, self).__init__(\n            device, dtype, size, FlexibleLayout.contiguous_strides(size)\n        )\n\n\nclass AliasedLayout(Layout):\n    \"\"\"Shares the same storage as another tensor\"\"\"\n\n    def __init__(self, view: \"ReinterpretView\"):\n        layout = view.get_layout()\n        super().__init__(\n            layout.device,\n            layout.dtype,\n            layout.size,\n            layout.stride,\n        )\n        self.view = view\n\n    def make_indexer(self):\n        return self.as_fixed().make_indexer()\n\n\nclass MutationLayout(Layout):\n    def __init__(self, target: IRNode):\n        super().__init__(\n            target.get_device(),\n            target.get_dtype(),\n            target.get_size(),\n            None,\n        )\n        self.target = target\n\n    @classmethod\n    def realize_into(cls, src, dst):\n        dst.realize()\n        V.graph.realize_users_of(dst.get_name())\n\n        if isinstance(src, TensorBox):\n            src = src.data\n\n        if not isinstance(src, StorageBox) or src.is_user_of(dst.get_name()):\n            need_copy = True\n        else:\n            src.realize()\n            need_copy = not isinstance(src.data.layout, FlexibleLayout)\n\n        if need_copy:\n            src = Pointwise.create(\n                device=src.get_device(),\n                dtype=src.get_dtype(),\n                inner_fn=src.make_loader(),\n                ranges=[\n                    V.graph.sizevars.guard_equals(a, b)\n                    for a, b in zip(src.get_size(), dst.get_size())\n                ],\n            ).data\n            src.realize()\n\n        assert isinstance(src.data.layout, FlexibleLayout)\n        src.data.layout = MutationLayout(dst)\n        return src.data\n\n    def as_fixed(self):\n        return self\n\n    def make_indexer(self):\n        return self.target.make_indexer()\n\n\n@dataclasses.dataclass\nclass Buffer(IRNode):\n    name: str\n    layout: Layout\n\n    def make_indexer(self):\n        return self.layout.make_indexer()\n\n    def get_name(self):\n        assert self.name\n        return self.name\n\n    def get_device(self):\n        return self.layout.device\n\n    def get_dtype(self):\n        return self.layout.dtype\n\n    def get_size(self):\n        return self.layout.size\n\n    def get_stride(self):\n        return self.layout.stride\n\n    def get_layout(self):\n        return self.layout\n\n    def get_storage_numel(self):\n        return self.get_numel()\n\n    def is_extern(self):\n        return False\n\n    def freeze_layout(self):\n        if not isinstance(self.layout, MultiOutputLayout):\n            self.layout = self.layout.as_fixed()\n\n    def freeze_layout_with_stride_order(self, order):\n        assert isinstance(self.layout, FlexibleLayout)\n        self.layout = self.layout.as_stride_order(order)\n\n    def make_loader(self):\n        def loader(index):\n            indexer = self.layout.make_indexer()\n            return ops.load(self.name, indexer(index))\n\n        return loader\n\n    def is_no_op(self):\n        return False\n\n    def codegen_reference(self):\n        return self.get_name()\n\n    def decide_layout(self):\n        pass\n\n    def get_alias_names(self):\n        if isinstance(self.layout, AliasedLayout):\n            return [self.layout.view.get_name()]\n        return ()\n\n    def get_mutation_names(self):\n        if isinstance(self.layout, MutationLayout):\n            return [self.layout.target.get_name()]\n        return ()\n\n    def get_read_writes(self):\n        with patch.object(FlexibleLayout, \"allow_indexing\", True):\n            return extract_read_writes(\n                self.make_loader(),\n                self.get_size(),\n            )\n\n    def get_reads(self):\n        return self.get_read_writes().reads\n\n    def realize(self):\n        pass\n\n\nclass InputBuffer(Buffer):\n    pass\n\n\nclass ConstantBuffer(InputBuffer):\n    override_device = None\n\n    def make_loader(self):\n        def loader(index):\n            indexer = self.layout.make_indexer()\n            return ops.load(\n                V.graph.constant_name(self.name, self.override_device), indexer(index)\n            )\n\n        return loader\n\n    def constant_to_device(self, device):\n        return ConstantBuffer(V.graph.constant_name(self.name, device), self.layout)\n\n\n@dataclasses.dataclass\nclass ComputedBuffer(Buffer):\n    data: Loops\n\n    def get_read_writes(self):\n        with patch.object(FlexibleLayout, \"allow_indexing\", True):\n            if self.data.get_reduction_type():\n                return extract_read_writes(\n                    self.get_store_function(),\n                    self.data.get_size(),\n                    self.data.get_reduction_size(),\n                )\n            else:\n                return extract_read_writes(\n                    self.get_store_function(),\n                    self.data.get_size(),\n                )\n\n    def get_store_function(self):\n        indexer = self.layout.as_fixed().make_indexer()\n        if self.data.get_reduction_type():\n            return partial(self.data.store_reduction, self.name, indexer)\n        else:\n            return partial(self.data.store_output, self.name, indexer)\n\n    def decide_layout(self):\n        \"\"\"\n        If our layout is still flexible, try to set it based on stride orders of reads.\n\n        TODO(jansel): A better algorithm here would look at downstream consumers of this\n                      value and try to do global graph-level layout optimization.\n                      This is also something just begging to be autotuned.\n        \"\"\"\n        if isinstance(self.layout, FlexibleLayout):\n            _, (index_vars, reduction_vars), _ = dependencies.index_vars(\n                self.data.get_size(), self.data.get_reduction_size()\n            )\n            reads = self.get_read_writes().reads\n            # only consider reads to buffer of same size\n            reads = [\n                r.index.subs({v: sympy.Integer(0) for v in reduction_vars})\n                for r in reads\n            ]\n\n            if reads:\n                stride_lengths = numpy.array(\n                    [V.graph.sizevars.stride_hints(expr, index_vars) for expr in reads],\n                    dtype=numpy.int64,\n                )\n                from .scheduler import pick_loop_order\n\n                self.freeze_layout_with_stride_order(\n                    pick_loop_order(stride_lengths, self.get_size())\n                )\n\n        if isinstance(self.layout, FlexibleLayout):\n            self.freeze_layout()\n\n    def simplify_loops(self):\n        _, args, var_ranges = dependencies.index_vars(\n            self.data.get_size(), self.data.get_reduction_size(), prefix=\"z\"\n        )\n        body = LoopBody(\n            self.get_store_function(),\n            (args if self.get_reduction_type() else args[:1]),\n            var_ranges,\n        )\n        index_formulas = [*body.indexing_exprs.values()]\n        memory_addrs = [*body.reads, *body.writes]\n\n        index_vars = []\n        reduce_vars = []\n        index_size = []\n        reduce_size = []\n        for v, s in var_ranges.items():\n            if v in args[0]:\n                assert not reduce_vars\n                index_vars.append(v)\n                index_size.append(s)\n            else:\n                assert v in args[1]\n                reduce_vars.append(v)\n                reduce_size.append(s)\n\n        def simplify_and_reorder(x_vars, sizes):\n            sizes, reindex1, prune = self._simplify_loops(x_vars, sizes, index_formulas)\n            x_vars = prune(x_vars)\n            sizes, reindex2 = self._apply_loop_reordering(x_vars, sizes, memory_addrs)\n            reindex = fuse_reindexing(reindex1, reindex2)\n            return sizes, reindex\n\n        iter_ranges, iter_reindex = simplify_and_reorder(index_vars, index_size)\n        reduce_ranges, reduce_reindex = simplify_and_reorder(reduce_vars, reduce_size)\n\n        def body_wrapper(index, reduce_index=None):\n            if not reduce_ranges and reduce_index:\n                index = [*index, *reduce_index]\n                reduce_index = None\n            index = iter_reindex(index)\n            if reduce_index:\n                index = [*index, *reduce_reindex(reduce_index)]\n            return body(index)\n\n        return iter_ranges, reduce_ranges, body_wrapper\n\n    @classmethod\n    def _simplify_loops(cls, index_vars, sizes, index_formulas):\n        \"\"\"\n        Try to remove as many axis from loop iterations as possible, by:\n            1) removing size==1 dimensions\n            2) fuse contiguous dimensions into a single loop\n        \"\"\"\n        sizes = list(sizes)\n\n        strides = [V.graph.sizevars.stride_vars(x, index_vars) for x in index_formulas]\n        assert len(sizes) == len(strides[0]), (len(sizes), len(strides[0]))\n\n        for i in range(len(sizes)):\n            if sizes[i] == 1:\n                # remove dim\n                sizes[i] = None\n\n        def can_merge_dims(a, b):\n            for k in range(len(strides)):\n                if strides[k][a] * sizes[a] == strides[k][b]:\n                    # approximate test passed, try sound version\n                    va = index_vars[a]\n                    vb = index_vars[b]\n                    v = sympy.Symbol(\"_merge_tester\")\n                    expr1 = index_formulas[k].subs({va: v * sizes[a], vb: 0})\n                    expr2 = index_formulas[k].subs({va: 0, vb: v})\n                    if expr1 == expr2:\n                        continue\n                return False\n            return True\n\n        changed = True\n        while changed:\n            changed = False\n            for i, j in itertools.product(\n                reversed(range(len(sizes))), reversed(range(len(sizes)))\n            ):\n                if i == j or sizes[i] is None or sizes[j] is None:\n                    continue\n                if can_merge_dims(i, j):\n                    changed = True\n                    sizes[i] = sizes[i] * sizes[j]\n                    sizes[j] = None\n\n        def reindex(index):\n            it = list(reversed(index))\n            new_index = []\n            for size in sizes:\n                if size is None:\n                    new_index.append(sympy.Integer(0))\n                else:\n                    new_index.append(it.pop())\n            assert not it\n            return new_index\n\n        def prune(index):\n            assert len(index) == len(sizes)\n            return [i for i, s in zip(index, sizes) if s is not None]\n\n        return [x for x in sizes if x is not None], reindex, prune\n\n    @staticmethod\n    def _apply_loop_reordering(index_vars, sizes, memory_addrs):\n        \"\"\"\n        Shuffle the order of loops around to hopefully improve performance.\n        \"\"\"\n        from .scheduler import pick_loop_order\n\n        try:\n            strides = numpy.array(\n                [\n                    V.graph.sizevars.stride_hints(expr, index_vars)\n                    for expr in memory_addrs\n                ],\n                dtype=numpy.int64,\n            )\n            assert strides.shape == (len(memory_addrs), len(index_vars))\n            order = list(reversed(pick_loop_order(strides, sizes)))\n        except Exception:\n            log.warning(\n                f\"Did not simplify complex index:\\n{dict(zip(index_vars, sizes))}\\n{memory_addrs}\"\n            )\n            order = list(range(len(sizes)))\n        sizes = [sizes[i] for i in order]\n        return sizes, inverse_reorder(order)\n\n    def get_reduction_size(self):\n        return self.data.get_reduction_size()\n\n    def get_reduction_type(self):\n        return self.data.get_reduction_type()\n\n    def is_no_op(self):\n        return self.data.is_zero_elements()\n\n    def should_allocate(self):\n        return True\n\n    def constant_to_device(self, device):\n        \"\"\"Move this to a given device. Requires that all reads are to constants.\"\"\"\n        return self.data.constant_to_device(device)\n\n\n@dataclasses.dataclass\nclass InputsKernel(Buffer):\n    inputs: List[Buffer]\n\n    def get_read_writes(self):\n        return dependencies.ReadWrites(\n            {dependencies.StarDep(x.get_name()) for x in self.inputs},\n            {dependencies.StarDep(self.get_name())},\n            set(),\n        )\n\n    @staticmethod\n    def unwrap_storage(inputs):\n        inputs_new = []\n        for x in inputs:\n            if isinstance(x, TensorBox):\n                x = x.data\n            if isinstance(x, StorageBox):\n                x = x.data\n            assert isinstance(x, (Buffer, ReinterpretView)), x\n            inputs_new.append(x)\n        return inputs_new\n\n    def is_extern(self):\n        return True\n\n\nclass NopKernel(InputsKernel):\n    def is_no_op(self):\n        return True\n\n\nclass ConcatKernel(NopKernel):\n    \"\"\"\n    There isn't actually a real kernel for concat, we just change the\n    storage for the upstream data.\n    \"\"\"\n\n    @classmethod\n    def create(cls, inputs, dim):\n        device = inputs[0].get_device()\n        dtype = inputs[0].get_dtype()\n        new_size = list(inputs[0].get_size())\n        offsets_start = [0]\n        offsets_end = [new_size[dim]]\n        assert 0 <= dim < len(new_size)\n        for i in range(1, len(inputs)):\n            input_size = inputs[i].get_size()\n            offsets_start.append(new_size[dim])\n            assert len(input_size) == len(new_size)\n            assert inputs[i].get_dtype() == dtype\n            assert inputs[i].get_device() == device\n            for j in range(len(new_size)):\n                if j == dim:\n                    new_size[j] = new_size[j] + input_size[j]\n                else:\n                    new_size[j] = V.graph.sizevars.guard_equals(\n                        new_size[j], input_size[j]\n                    )\n            offsets_end.append(new_size[dim])\n\n        kernel = ConcatKernel(\n            name=None,\n            layout=FixedLayout(\n                device=device,\n                dtype=dtype,\n                size=new_size,\n                stride=FlexibleLayout.contiguous_strides(new_size),\n            ),\n            inputs=[],\n        )\n        kernel = StorageBox(kernel)\n        for i in range(len(inputs)):\n            kernel.data.inputs.append(\n                cls.realize_into(\n                    inputs[i],\n                    SliceView.create(kernel, dim, offsets_start[i], offsets_end[i]),\n                )\n            )\n        kernel.data.name = V.graph.register_buffer(kernel.data)\n        kernel.data.inputs = cls.unwrap_storage(kernel.data.inputs)\n        return kernel\n\n    @classmethod\n    def realize_into(cls, src, dst):\n        assert isinstance(dst, ReinterpretView), dst\n        if isinstance(src, TensorBox):\n            # unwrap a TensorBox\n            return cls.realize_into(src.data, dst)\n        if isinstance(src, StorageBox):\n            src.realize()\n            if isinstance(src.data.layout, FlexibleLayout):\n                src.data.layout = AliasedLayout(dst)\n                return src.data\n        # introduce a copy\n        pw = Pointwise.create(\n            device=src.get_device(),\n            dtype=src.get_dtype(),\n            inner_fn=src.make_loader(),\n            ranges=[\n                V.graph.sizevars.guard_equals(a, b)\n                for a, b in zip(src.get_size(), dst.get_size())\n            ],\n        )\n        return cls.realize_into(pw, dst)\n\n    def should_allocate(self):\n        return True\n\n\n@dataclasses.dataclass\nclass ExternKernel(InputsKernel):\n    constant_args: List[Any] = ()\n    output_view: Optional[ReinterpretView] = None\n\n    def decide_layout(self):\n        self.freeze_layout()\n\n    @staticmethod\n    def copy_input(x):\n        pw = Pointwise.create(\n            device=x.get_device(),\n            dtype=x.get_dtype(),\n            inner_fn=x.make_loader(),\n            ranges=x.get_size(),\n        )\n        pw.realize()\n        return pw\n\n    @classmethod\n    def realize_input(cls, x):\n        if isinstance(x, TensorBox):\n            return cls.realize_input(x.data)\n        if isinstance(x, ReinterpretView):\n            return x\n        if isinstance(x, StorageBox):\n            # TODO(jansel): impose layout preference on realized buffer\n            x.realize()\n            return x\n        return cls.copy_input(x)\n\n    @classmethod\n    def require_stride1(cls, x):\n        if len(x.get_stride()) == 0:\n            return x\n        for stride in x.get_stride():\n            if stride == 1:\n                return x\n        return cls.copy_input(x)\n\n    @classmethod\n    def require_contiguous(cls, x):\n        if is_contiguous_storage_and_layout(x):\n            as_contiguous_storage_and_layout(x, freeze=True)\n            return x\n        x = cls.copy_input(x)\n        assert is_contiguous_storage_and_layout(x)\n        as_contiguous_storage_and_layout(x, freeze=True)\n        return x\n\n    def codegen_args(self):\n        args = [x.codegen_reference() for x in self.inputs]\n        args.extend(map(repr, self.constant_args))\n        return args\n\n    def codegen_size_asserts(self, wrapper):\n        if config.size_asserts:\n            size = V.graph.sizevars.codegen_shape_tuple(self.get_size())\n            stride = V.graph.sizevars.codegen_shape_tuple(self.get_stride())\n            wrapper.writeline(f\"assert {self.get_name()}.size() == {size}\")\n            wrapper.writeline(f\"assert {self.get_name()}.stride() == {stride}\")\n\n\n@dataclasses.dataclass\nclass ExternKernelOut(ExternKernel):\n    output_view: Optional[ReinterpretView] = None\n\n    def codegen(self, wrapper):\n        args = self.codegen_args()\n        if self.output_view:\n            args.append(f\"out={self.output_view.codegen_reference()}\")\n        else:\n            args.append(f\"out={self.codegen_reference()}\")\n        wrapper.writeline(f\"{self.kernel}({', '.join(args)})\")\n\n    def __init__(self, layout, inputs, constant_args=(), output_view=None):\n        super().__init__(None, layout, self.unwrap_storage(inputs), constant_args)\n        self.output_view = output_view\n        self.name = V.graph.register_buffer(self)\n\n    def should_allocate(self):\n        return True\n\n\nclass ExternKernelAlloc(ExternKernel):\n    def codegen(self, wrapper):\n        wrapper.writeline(\n            f\"{self.get_name()} = {self.kernel}({', '.join(self.codegen_args())})\"\n        )\n        if isinstance(self.layout, Layout):\n            self.codegen_size_asserts(wrapper)\n\n    def __init__(self, layout, inputs, constant_args=()):\n        super().__init__(None, layout, self.unwrap_storage(inputs), constant_args)\n        self.name = V.graph.register_buffer(self)\n\n    def should_allocate(self):\n        return False\n\n\nclass MatrixMultiply(ExternKernelOut):\n    kernel = \"aten.mm.out\"\n\n    @classmethod\n    def create(cls, a, b):\n        *m, k1 = a.get_size()\n        k2, n = b.get_size()\n        V.graph.sizevars.guard_equals(k1, k2)\n        a = cls.realize_input(a)\n        b = cls.realize_input(b)\n        if len(m) != 1 and not a.get_layout().is_contiguous():\n            a = cls.copy_input(a)\n        else:\n            a = cls.require_stride1(a)\n        b = cls.require_stride1(b)\n        return MatrixMultiply(\n            layout=FlexibleLayout(\n                device=a.get_device(),\n                dtype=a.get_dtype(),\n                size=list(m) + [n],\n            ),\n            inputs=[a, b],\n        )\n\n\nclass BatchMatrixMultiply(ExternKernelOut):\n    kernel = \"aten.bmm.out\"\n\n    @classmethod\n    def create(cls, a, b):\n        b1, m, k1 = a.get_size()\n        b2, k2, n = b.get_size()\n        b3 = V.graph.sizevars.guard_equals(b1, b2)\n        V.graph.sizevars.guard_equals(k1, k2)\n        a = cls.require_stride1(cls.realize_input(a))\n        b = cls.require_stride1(cls.realize_input(b))\n\n        output_layout = FlexibleLayout(\n            device=a.get_device(),\n            dtype=a.get_dtype(),\n            size=[b3, m, n],\n        ).as_fixed()\n\n        if b3 == 1:\n            # convert to normal mm\n            data = MatrixMultiply(\n                layout=output_layout.as_fixed(),\n                inputs=[View.create(a, [m, k1]), View.create(b, [k2, n])],\n            )\n            data.output_view = ReinterpretView(\n                data,\n                FlexibleLayout(\n                    device=a.get_device(),\n                    dtype=a.get_dtype(),\n                    size=[m, n],\n                ).as_fixed(),\n            )\n        else:\n            data = BatchMatrixMultiply(\n                layout=output_layout,\n                inputs=[a, b],\n            )\n        return data\n\n\nclass DeviceCopy(ExternKernelOut):\n    @classmethod\n    def create(cls, x, device):\n        V.graph.device_types.add(device.type)\n        V.graph.device_types.add(x.get_device().type)\n\n        x = cls.realize_input(x)\n        read_writes = x.get_read_writes()\n        if not x.is_extern() and all(\n            (r.name in V.graph.constants and hasattr(r, \"index\"))\n            for r in read_writes.reads\n        ):\n            return x.constant_to_device(device)\n\n        return DeviceCopy(\n            FlexibleLayout(\n                device=device,\n                dtype=x.get_dtype(),\n                size=x.get_size(),\n            ),\n            [x],\n        )\n\n    def codegen(self, wrapper):\n        args = self.codegen_args()\n        assert len(args) == 1\n        if self.output_view:\n            wrapper.writeline(\n                f\"{self.output_view.codegen_reference()}.copy_({args[0]})\"\n            )\n        else:\n            wrapper.writeline(f\"{self.codegen_reference()}.copy_({args[0]})\")\n\n\nclass DynamicScalar(IRNode):\n    \"\"\"\n    The result of a call to aten._local_scalar_dense.\n\n    This is not yet implemented.  The one model (so far) that calls this\n    (fastNLP_Bert) does not actually use the result.  So we expect this\n    node to get dead code eliminated.\n    \"\"\"\n\n    def get_reads(self):\n        return ()\n\n\nclass AdaptiveAvgPool2d(ExternKernelAlloc):\n    kernel = \"aten._adaptive_avg_pool2d\"\n\n    @classmethod\n    def create(cls, x, target_size):\n        x = cls.require_stride1(cls.realize_input(x))\n        output_size = [\n            *x.get_size()[: -len(target_size)],\n            *map(sympy.Integer, target_size),\n        ]\n        return cls(\n            FixedLayout(\n                x.get_device(),\n                x.get_dtype(),\n                output_size,\n                # TODO(jansel): fix channels last case\n                FlexibleLayout.contiguous_strides(output_size),\n            ),\n            (x,),\n            (tuple(target_size),),\n        )\n\n\n@dataclasses.dataclass\nclass FallbackKernel(ExternKernelAlloc):\n    def __init__(\n        self,\n        layout,\n        kernel,\n        tensor_args,\n        nontensor_args,\n        unflatten_args,\n    ):\n        super(FallbackKernel, self).__init__(\n            layout,\n            tuple(tensor_args),\n            tuple(nontensor_args),\n        )\n        assert getattr(torch.ops.aten, kernel.__name__) is kernel\n        self.kernel = f\"aten.{kernel.__name__}\"\n        self.unflatten_args = unflatten_args\n\n    def codegen_args(self):\n        @dataclasses.dataclass\n        class Shim:\n            ref: Any\n\n            def __repr__(self):\n                return self.ref\n\n        tensor_args = [Shim(x.codegen_reference()) for x in self.inputs]\n        constant_args = [Shim(repr(x)) for x in self.constant_args]\n        return list(map(repr, self.unflatten_args(tensor_args, constant_args)))\n\n    @classmethod\n    def create(cls, kernel, *args):\n        args_flat, args_spec = pytree.tree_flatten(args)\n\n        is_arg_tensor = []\n        tensor_args = []\n        non_tensor_args = []\n        for arg in args_flat:\n            is_arg_tensor.append(isinstance(arg, IRNode))\n            if is_arg_tensor[-1]:\n                tensor_args.append(arg)\n            else:\n                non_tensor_args.append(arg)\n\n        def unflatten_args(new_tensor_args, new_non_tensor_args):\n            new_args = []\n            it_tensors = iter(new_tensor_args)\n            it_non_tensors = iter(new_non_tensor_args)\n            for is_tensor in is_arg_tensor:\n                if is_tensor:\n                    new_args.append(next(it_tensors))\n                else:\n                    new_args.append(next(it_non_tensors))\n            return pytree.tree_unflatten(new_args, args_spec)\n\n        tensor_args = [\n            cls.require_contiguous(cls.realize_input(x)) for x in tensor_args\n        ]\n\n        # We don't have generic shape formulas, so just burn in the\n        # shapes and run an example input.\n        # TODO(jansel): replace this with dynamic shape formulas\n        example_args = [\n            torch.zeros(\n                [V.graph.sizevars.guard_static_shape(s) for s in x.get_size()],\n                dtype=x.get_dtype(),\n                device=x.get_device(),\n            )\n            for x in tensor_args\n        ]\n        example_output = kernel(*unflatten_args(example_args, non_tensor_args))\n\n        if isinstance(example_output, (list, tuple)):\n            packed = FallbackKernel(\n                MultiOutputLayout(),\n                kernel,\n                tensor_args,\n                non_tensor_args,\n                unflatten_args,\n            )\n            return [\n                MultiOutput(\n                    FixedLayout(\n                        example_output[i].device,\n                        example_output[i].dtype,\n                        [sympy.Integer(s) for s in example_output[i].size()],\n                        [sympy.Integer(s) for s in example_output[i].stride()],\n                    ),\n                    packed,\n                    i,\n                )\n                for i in range(len(example_output))\n            ]\n        else:\n            return FallbackKernel(\n                FixedLayout(\n                    example_output.device,\n                    example_output.dtype,\n                    [sympy.Integer(s) for s in example_output.size()],\n                    [sympy.Integer(s) for s in example_output.stride()],\n                ),\n                kernel,\n                tensor_args,\n                non_tensor_args,\n                unflatten_args,\n            )\n\n\nclass MultiOutputLayout(IRNode):\n    pass\n\n\nclass MultiOutput(ExternKernel):\n    def codegen(self, wrapper):\n        wrapper.writeline(\n            f\"{self.get_name()} = {self.inputs[0].get_name()}[{self.index}]\"\n        )\n        self.codegen_size_asserts(wrapper)\n\n    def __init__(self, layout, input, index):\n        super().__init__(None, layout, [input], ())\n        self.name = V.graph.register_buffer(self)\n        self.index = index\n\n    def should_allocate(self):\n        return False\n\n\nclass Convolution(ExternKernelAlloc):\n    kernel = \"aten.convolution\"\n\n    @classmethod\n    def create(\n        cls,\n        x: \"TensorBox\",\n        weight: \"TensorBox\",\n        bias: \"TensorBox\",\n        stride: List[int],\n        padding: List[int],\n        dilation: List[int],\n        transposed: bool,\n        output_padding: List[int],\n        groups: int,\n    ):\n        x = cls.require_stride1(cls.realize_input(x))\n        weight = cls.require_stride1(cls.realize_input(weight))\n        stride = tuple(stride)\n        padding = tuple(padding)\n        dilation = tuple(dilation)\n        assert isinstance(transposed, bool)\n        output_padding = tuple(output_padding)\n        assert isinstance(groups, int)\n\n        weight_shape = [\n            sympy.Integer(V.graph.sizevars.guard_static_shape(s))\n            for s in weight.get_size()\n        ]\n\n        out_channels, in_channels1, *kernel_size = weight_shape\n        in_channels1 = in_channels1 * groups\n        if transposed:\n            out_channels, in_channels1 = in_channels1, out_channels\n\n        if bias is not None:\n            bias = cls.require_stride1(cls.realize_input(bias))\n            (bias_shape,) = [\n                sympy.Integer(V.graph.sizevars.guard_static_shape(s))\n                for s in bias.get_size()\n            ]\n            assert bias_shape == out_channels, f\"{bias_shape} == {out_channels}\"\n\n        if len(x.get_size()) == 1 + len(kernel_size):\n            in_channels2, *input_size = x.get_size()\n            output_size = []\n        else:\n            assert len(x.get_size()) == 2 + len(kernel_size)\n            batch, in_channels2, *input_size = x.get_size()\n            output_size = [batch]\n\n        V.graph.sizevars.guard_equals(in_channels1, in_channels2)\n\n        output_size.append(out_channels)\n\n        assert (\n            len(stride)\n            == len(padding)\n            == len(dilation)\n            == len(output_padding)\n            == len(kernel_size)\n            == len(input_size)\n        )\n        for i in range(len(stride)):\n            if transposed:\n                output_size.append(\n                    (input_size[i] - 1) * stride[i]\n                    - 2 * padding[i]\n                    + dilation[i] * (kernel_size[i] - 1)\n                    + output_padding[i]\n                    + 1\n                )\n            else:\n                output_size.append(\n                    IndexingDiv(\n                        input_size[i]\n                        + 2 * padding[i]\n                        - dilation[i] * (kernel_size[i] - 1)\n                        - 1\n                        + stride[i],\n                        stride[i],\n                    )\n                    + 2 * output_padding[i]\n                )\n            output_size[-1] = sympy.Integer(\n                V.graph.sizevars.guard_static_shape(output_size[-1])\n            )\n\n        output_layout = FixedLayout(\n            x.get_device(),\n            x.get_dtype(),\n            output_size,\n            # TODO(jansel): fix channels last case\n            FlexibleLayout.contiguous_strides(output_size),\n        )\n\n        if bias is not None:\n            return Convolution(\n                output_layout,\n                (x, weight, bias),\n                (stride, padding, dilation, transposed, output_padding, groups),\n            )\n        else:\n            return Convolution(\n                output_layout,\n                (x, weight),\n                (bias, stride, padding, dilation, transposed, output_padding, groups),\n            )\n\n\n@dataclasses.dataclass\nclass MutableBox(IRNode):\n    \"\"\"\n    TensorBox / StorageBox allow in-place mutation of Tensors\n    \"\"\"\n\n    data: IRNode\n\n    def __getattr__(self, name):\n        fn = getattr(self.data, name)\n        if callable(fn):\n            return fn\n        raise AttributeError(f\"{type(self.data).__name__}.{name} not callable\")\n\n    def __str__(self):\n        if isinstance(self.data, MutableBox):\n            line0 = f\"{type(self).__name__}({type(self.data).__name__}(\"\n            endl = \"))\"\n            inner = self.data.data\n        else:\n            line0 = f\"{type(self).__name__}(\"\n            inner = self.data\n            endl = \")\"\n\n        lines = [\n            line0,\n            indent(str(inner)),\n            endl,\n        ]\n        return \"\\n\".join(lines)\n\n    __repr__ = __str__\n\n\nclass TensorBox(MutableBox):\n    @staticmethod\n    def create(data):\n        return TensorBox(StorageBox(data))\n\n\nclass StorageBox(MutableBox):\n    def realize(self):\n        if isinstance(\n            self.data, (ComputedBuffer, InputsKernel, InputBuffer, ReinterpretView)\n        ):\n            return self.data.get_name()\n        assert isinstance(self.data, (Pointwise, Reduction)), type(self.data)\n        self.data = ComputedBuffer(\n            name=None,\n            layout=FlexibleLayout(\n                device=self.data.get_device(),\n                dtype=self.data.get_dtype(),\n                size=self.data.get_size(),\n            ),\n            data=self.data,\n        )\n        self.data.name = V.graph.register_buffer(self.data)\n        return self.data.name\n\n    def mark_reuse(self, users):\n        if users <= 1:\n            return\n        if isinstance(self.data, (Pointwise, Reduction)):\n            read_writes = ComputedBuffer(\n                name=None,\n                layout=FlexibleLayout(\n                    device=self.data.get_device(),\n                    dtype=self.data.get_dtype(),\n                    size=self.data.get_size(),\n                ),\n                data=self.data,\n            ).get_read_writes()\n            # TODO(jansel): this heuristic is a wild guess\n            if len(read_writes.reads) > 1 or len(self.inner_fn_str()) > 1000:\n                self.realize()\n\n\nclass LoopBody:\n    \"\"\"\n    Captures the body of a Loops subclass into an FX graph.  Persists any\n    indexing simplifications and makes it easier to analyze loop bodies.\n    \"\"\"\n\n    def __init__(self, fn, args, var_ranges):\n        super().__init__()\n        self.var_ranges = var_ranges\n        self.indexing_exprs = {}\n        self.indexing_exprs_name = {}\n        self.reads = []\n        self.writes = []\n        self.other = []\n        self.submodules = {}\n        self.subblocks = {}\n        self.indirect_vars = []\n        self.root_block = LoopBodyBlock(self, fn, args)\n        self.indexing = None\n\n    def add_index_expr(self, expr: sympy.Expr, category):\n        getattr(self, category).append(expr)\n        if expr not in self.indexing_exprs_name:\n            name = f\"index{len(self.indexing_exprs)}\"\n            self.indexing_exprs_name[expr] = name\n            self.indexing_exprs[name] = expr\n        return self.indexing_exprs_name[expr]\n\n    def add_submodule(self, block, prefix):\n        \"\"\"Not actually for nn.Modules, but subblocks in generated code are mapped to FX call_module opcodes\"\"\"\n        if prefix[-1].isnumeric() and prefix not in self.submodules:\n            name = prefix\n        else:\n            name = f\"{prefix}{len(self.submodules)}\"\n        self.submodules[name] = block\n        return name\n\n    def add_indirect(self):\n        name = f\"indirect{len(self.indirect_vars)}\"\n        var = sympy.Symbol(name, integer=True)\n        self.indirect_vars.append([var])\n        return var\n\n    def __call__(self, index=()):\n        assert len(index) == len(self.var_ranges)\n        assert all(v not in self.var_ranges for v in index)\n        replacements = dict(zip(self.var_ranges.keys(), index))\n        self.indexing = {\n            name: expr.subs(replacements) for name, expr in self.indexing_exprs.items()\n        }\n        result = self.root_block()\n        self.indexing = None\n        return result\n\n\nclass LoopBodyBlock:\n    \"\"\"\n    Captures the body of a Loops subclass into an FX graph.\n    In normal cases there will be a 1:1 mapping between LoopBody and\n    LoopBodyBlock, hower in the case of ops.masked() the masked out\n    operations will manifest as an extra LoopBodyBlock.\n    \"\"\"\n\n    def __init__(self, body: LoopBody, fn: Callable, args: List[Any]):\n        self.gm = None\n        self.body = body\n\n        def add_index(expr, category):\n            return tracer.create_proxy(\n                \"get_attr\", self.body.add_index_expr(expr, category), (), {}\n            )\n\n        class CaptureIndexing(V.WrapperHandler):\n            def load(self, name: str, index: sympy.Expr):\n                index = add_index(index, \"reads\")\n                return self._inner.load(name, index)\n\n            def store(self, name, index, value):\n                index = add_index(index, \"writes\")\n                return self._inner.store(name, index, value)\n\n            def reduction(self, name, dtype, reduction_type, index, value):\n                index = add_index(index, \"writes\")\n                return self._inner.reduction(name, dtype, reduction_type, index, value)\n\n            def index_expr(self, index, dtype):\n                index = add_index(index, \"other\")\n                return self._inner.index_expr(index, dtype)\n\n            @staticmethod\n            def masked(mask_proxy, masked_body: Callable, other_proxy):\n                \"\"\"\n                Recursively capture the masked out body in another LoopBodyBlock\n                \"\"\"\n\n                def shim(mask, other):\n                    return V.ops.masked(mask, subblock, other)\n\n                name = self.body.add_submodule(shim, \"masked_subblock\")\n                subblock = LoopBodyBlock(self.body, masked_body, ())\n                self.body.subblocks[name] = subblock\n                return tracer.create_proxy(\n                    \"call_module\", name, (mask_proxy, other_proxy), {}\n                )\n\n            @staticmethod\n            def indirect_indexing(index_proxy):\n                \"\"\"\n                Flow data from tensors into indexing formulas.\n                Introduce a call_module to update the indexing.\n                \"\"\"\n\n                def set_indirect(new_var):\n                    self.replace_indirect(var, V.ops.indirect_indexing(new_var))\n\n                var = self.body.add_indirect()\n                tracer.create_proxy(\n                    \"call_module\",\n                    self.body.add_submodule(set_indirect, f\"set_{var}\"),\n                    (index_proxy,),\n                    {},\n                )\n                return var\n\n        tracer = torch.fx.Tracer()\n        tracer.graph = torch.fx.Graph(tracer_cls=tracer.__class__)\n        proxy_ops = tracer.create_proxy(\"placeholder\", \"ops\", (), {})\n        from .sizevars import SimplifyIndexing\n\n        with V.set_ops_handler(\n            SimplifyIndexing(CaptureIndexing(proxy_ops), self.body.var_ranges)\n        ):\n            tracer.create_proxy(\"output\", \"output\", (fn(*args),), {})\n        self.graph = tracer.graph\n\n    def replace_indirect(self, old, new):\n        \"\"\"Swap in a variable used in indirect indexing\"\"\"\n        for name in self.body.indexing.keys():\n            expr = getattr(self.gm, name)\n            if old in expr.free_symbols:\n                setattr(self.gm, name, expr.subs({old: new}))\n\n    def __call__(self):\n        self.gm = torch.fx.GraphModule(\n            {**self.body.indexing, **self.body.submodules}, self.graph\n        )\n        result = self.gm.forward(V.get_ops_handler())\n        self.gm = None\n        return result\n", "meta": {"hexsha": "0f056d809ccc827bd0a7196570b8d20f81521b06", "size": 64474, "ext": "py", "lang": "Python", "max_stars_repo_path": "torchinductor/ir.py", "max_stars_repo_name": "frank-wei/torchdynamo", "max_stars_repo_head_hexsha": "26c4c1b593bebf4246e566749dade38254b59ffb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "torchinductor/ir.py", "max_issues_repo_name": "frank-wei/torchdynamo", "max_issues_repo_head_hexsha": "26c4c1b593bebf4246e566749dade38254b59ffb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "torchinductor/ir.py", "max_forks_repo_name": "frank-wei/torchdynamo", "max_forks_repo_head_hexsha": "26c4c1b593bebf4246e566749dade38254b59ffb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5419232591, "max_line_length": 111, "alphanum_fraction": 0.5644290722, "include": true, "reason": "import numpy,import sympy,from sympy", "num_tokens": 13682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.2942149659744614, "lm_q1q2_score": 0.15857692557793815}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nASC CDL Input Utilities\n=======================\n\nDefines *ASC CDL* correction operator related objects.\n\n-   :class:`colour.io.ASC_CDL`\n-   :func:`colour.io.read_LUT_cdl_xml`\n-   :func:`colour.io.read_LUT_cdl_edl`\n-   :func:`colour.io.read_LUT_cdl_ale`\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\nimport os\nimport re\nfrom xml.dom import minidom\n\nfrom colour.constants import DEFAULT_FLOAT_DTYPE, DEFAULT_INT_DTYPE\nfrom colour.io.luts import AbstractLUTSequenceOperator, LUTSequence\nfrom colour.models import gamma_function\nfrom colour.utilities import as_float_array, tsplit, tstack\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2018 - Colour Developers'\n__license__ = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-science@googlegroups.com'\n__status__ = 'Production'\n\n__all__ = [\n    'ASC_CDL', 'read_LUT_cdl_xml', 'read_LUT_cdl_edl', 'read_LUT_cdl_ale'\n]\n\n\nclass ASC_CDL(AbstractLUTSequenceOperator):\n    \"\"\"\n    Defines an *ASC CDL* correction operator.\n\n    Parameters\n    ----------\n    slope : array_like, optional\n        Multipliers for the *R*, *G* and *B* channels.\n    offset : array_like, optional\n        Offsets added to the *R*, *G* and *B* channels.\n    power : array_like, optional\n        Exponents to which the *R*, *G* and *B* channels are raised.\n    saturation : array_like, optional\n        Saturation (Rec.709 weighted) applied to the *RGB* values.\n    name : unicode, optional\n        *ASC CDL* correction operator name.\n    comments : array_like, optional\n        Comments to add to the *ASC CDL* correction operator.\n    clamp : boolean, optional\n        Whether the output is clamped to range [0, 1].\n    reverse : boolean, optional\n        Whether to reverse/invert the correction.\n    id : unicode, optional\n        ID of the correction.\n\n    Methods\n    -------\n    apply\n\n    Examples\n    --------\n    Instantiating an identity *ASC CDL* correction operator:\n\n    >>> print(ASC_CDL(name='Identity'))\n    ASC CDL - Identity\n    ------------------\n    <BLANKLINE>\n    <ColorCorrection id=\"\">\n        <SOPNode>\n            <Slope> 1.0 1.0 1.0 </Slope>\n             <Offset> 0.0 0.0 0.0 </Offset>\n            <Power> 1.0 1.0 1.0 </Power>\n        </SOPNode>\n        <SATNode>\n            <Saturation> 1.0 </Saturation>\n        </SATNode>\n    </ColorCorrection>\n    <BLANKLINE>\n    Clamping   : Yes\n    Reverse    : No\n\n    Instantiating an *ASC CDL* correction operator with comments:\n\n    >>> print(ASC_CDL(slope=[1.1, 1.0, 0.9],\n    ...               offset=[-0.1, 0.0, 0.1],\n    ...               power=[0.9, 1.0, 1.1],\n    ...               saturation=0.9,\n    ...               name='Correction_01',\n    ...               comments=['A first comment.', 'A second comment.']))\n    ASC CDL - Correction_01\n    -----------------------\n\n    <ColorCorrection id=\"\">\n        <SOPNode>\n            <Slope> 1.1 1.0 0.9 </Slope>\n            <Offset> -0.1 0.0 0.1 </Offset>\n            <Power> 0.9 1.0 1.1 </Power>\n        </SOPNode>\n        <SATNode>\n            <Saturation> 0.9 </Saturation>\n        </SATNode>\n    </ColorCorrection>\n\n    Clamping   : Yes\n    Reverse    : No\n\n    Comment 01 : A first comment.\n    Comment 02 : A second comment.\n    \"\"\"\n\n    def __init__(self,\n                 slope=[1, 1, 1],\n                 offset=[0, 0, 0],\n                 power=[1, 1, 1],\n                 saturation=1.0,\n                 name='',\n                 comments=None,\n                 clamp=True,\n                 reverse=False,\n                 id=''):\n        self.slope = np.asarray(slope)\n        self.offset = np.asarray(offset)\n        self.power = np.asarray(power)\n        self.saturation = saturation\n        self.name = name\n        self.comments = comments\n        self.clamp = clamp\n        self.reverse = reverse\n        self.id = id\n\n    # TODO: Add properties.\n\n    def __str__(self):\n        \"\"\"\n        Returns a formatted string representation of the *ASC CDL* correction\n        operator.\n\n        Returns\n        -------\n        unicode\n            Formatted string representation.\n        \"\"\"\n\n        def _format_array(array):\n            array = np.asarray(array)\n            if array.shape == (3, ):\n                return '{0} {1} {2}'.format(array[0], array[1], array[2])\n            else:\n                return '{0} {0} {0}'.format(array)\n\n        if self.comments:\n            comments = [\n                'Comment {0} : {1}'.format(str(i + 1).zfill(2), comment)\n                for i, comment in enumerate(self.comments)\n            ]\n\n        return ('ASC CDL - {0}\\n'\n                '{1}\\n\\n'\n                '<ColorCorrection id=\"{2}\">\\n'\n                '    <SOPNode>\\n'\n                '        <Slope> {3} </Slope>\\n'\n                '        <Offset> {4} </Offset>\\n'\n                '        <Power> {5} </Power>\\n'\n                '    </SOPNode>\\n'\n                '    <SATNode>\\n'\n                '        <Saturation> {6} </Saturation>\\n'\n                '    </SATNode>\\n'\n                '</ColorCorrection>\\n\\n'\n                'Clamping   : {7}\\n'\n                'Reverse    : {8}'\n                '{9}'.format(\n                    self.name,\n                    '-' * (10 + len(self.name)),\n                    self.id,\n                    _format_array(self.slope),\n                    _format_array(self.offset),\n                    _format_array(self.power),\n                    self.saturation,\n                    'Yes' if self.clamp else 'No',\n                    'Yes' if self.reverse else 'No',\n                    '\\n\\n{0}'.format('\\n'.join(comments))\n                    if self.comments else '',\n                ))\n\n    def apply(self, RGB):\n        \"\"\"\n        Applies the *ASC CDL* correction operator to given *RGB* array.\n\n        Parameters\n        ----------\n        RGB : array_like\n            *RGB* array to apply the *ASC CDL* correction operator to.\n\n        Returns\n        -------\n        ndarray\n            Corrected *RGB* array.\n\n        Examples\n        --------\n        >>> cdl = ASC_CDL(slope=[1.1, 1.0, 0.9],\n        ...               offset=[-0.1, 0.0, 0.1],\n        ...               power=[0.9, 1.0, 1.1],\n        ...               saturation=0.9)\n        >>> RGB = [0.18, 0.18, 0.18]\n        >>> cdl.apply(RGB)\n        array([ 0.12841813,  0.17915636,  0.22339685])\n        \"\"\"\n\n        RGB_out = as_float_array(np.copy(RGB))\n\n        if self.reverse:\n            if self.clamp:\n                RGB_out = np.clip(RGB_out, 0, 1)\n\n            if self.saturation != 1.0:\n                R, G, B = tsplit(RGB_out)\n                luma = 0.2126 * R + 0.7152 * G + 0.0722 * B\n                luma = tstack([luma, luma, luma])\n                RGB_out = luma + (1 / self.saturation) * (RGB_out - luma)\n\n                if self.clamp:\n                    RGB_out = np.clip(RGB_out, 0, 1)\n\n            RGB_out = gamma_function(RGB_out, 1 / self.power, 'preserve')\n            RGB_out -= self.offset\n            RGB_out /= self.slope\n\n            if self.clamp:\n                RGB_out = np.clip(RGB_out, 0, 1)\n        else:\n            RGB_out *= self.slope\n            RGB_out += self.offset\n            RGB_out = gamma_function(RGB_out, self.power, 'preserve')\n\n            if self.clamp:\n                RGB_out = np.clip(RGB_out, 0, 1)\n\n            if self.saturation != 1.0:\n                R, G, B = tsplit(RGB_out)\n                luma = 0.2126 * R + 0.7152 * G + 0.0722 * B\n                luma = tstack([luma, luma, luma])\n                RGB_out = luma + self.saturation * (RGB_out - luma)\n\n                if self.clamp:\n                    RGB_out = np.clip(RGB_out, 0, 1)\n\n        return RGB_out\n\n\ndef read_LUT_cdl_xml(path):\n    def _parse_array(array):\n        return np.array(list(map(DEFAULT_FLOAT_DTYPE, array.split())))\n\n    title = re.sub('_|-|\\\\.', ' ', os.path.splitext(os.path.basename(path))[0])\n    data = minidom.parse(path)\n    LUT = LUTSequence()\n    corrections = data.getElementsByTagName('ColorCorrection')\n\n    for idx, correction in enumerate(corrections):\n        event = ASC_CDL()\n        slope = correction.getElementsByTagName('Slope')\n        slope = '1 1 1' if not slope else slope[0].firstChild.data\n        offset = correction.getElementsByTagName('Offset')\n        offset = '0 0 0' if not offset else offset[0].firstChild.data\n        power = correction.getElementsByTagName('Power')\n        power = '1 1 1' if not power else power[0].firstChild.data\n        saturation = correction.getElementsByTagName('Saturation')\n        saturation = '1' if not saturation else saturation[0].firstChild.data\n\n        if 'id' in correction.attributes.keys():\n            event.id = correction.attributes['id'].value\n\n        event.slope = _parse_array(slope)\n        event.offset = _parse_array(offset)\n        event.power = _parse_array(power)\n        event.saturation = _parse_array(saturation)\n        event.name = '{0} ({1})'.format(title, idx + 1)\n        LUT.append(event)\n\n    if len(LUT) == 1:\n        LUT[0].name = title\n\n        return LUT[0]\n    else:\n        return LUT\n\n\ndef read_LUT_cdl_edl(path):\n    with open(path) as edl_file:\n        edl_lines = edl_file.readlines()\n\n    if 'TITLE' in edl_lines[0]:\n        title = edl_lines[0].split()[1]\n    else:\n        title = re.sub('_|-|\\\\.', ' ',\n                       os.path.splitext(os.path.basename(path))[0])\n    event_cdl = None\n    has_cdl = False\n    LUT = LUTSequence()\n    for line in edl_lines:\n        if len(line.split()) == 0:\n            continue\n\n        if line.split()[0].isdigit():\n            if has_cdl:\n                LUT.append(event_cdl)\n                event_cdl = None\n                has_cdl = False\n            event_number = DEFAULT_INT_DTYPE(line.split()[0])\n            event_cdl = ASC_CDL(\n                name='{0} EV{1:04d}'.format(title, event_number))\n            event_cdl.comments = []\n            continue\n\n        if event_cdl:\n            if line[0] == '*':\n                trimmed = line[1:].lstrip()\n\n                if trimmed.startswith('ASC_SOP'):\n                    sop = re.sub('\\)\\s*\\(|\\s*\\(|\\s*\\)', ' ', trimmed).split()\n                    event_cdl.slope = np.array(sop[1:4]).astype(np.float)\n                    event_cdl.offset = np.array(sop[4:7]).astype(np.float)\n                    event_cdl.power = np.array(sop[7:]).astype(np.float)\n                    has_cdl = True\n                elif trimmed.startswith('ASC_SAT'):\n                    event_cdl.saturation = float(trimmed.split()[1])\n                    has_cdl = True\n                else:\n                    event_cdl.comments.append(trimmed)\n    if event_cdl:\n        LUT.append(event_cdl)\n\n    return LUT\n\n\ndef read_LUT_cdl_ale(path):\n    with open(path, 'rU') as ale_file:\n        ale_lines = ale_file.readlines()\n\n    title = re.sub('_|-|\\\\.', ' ', os.path.splitext(os.path.basename(path))[0])\n    event_cdl = None\n    LUT = LUTSequence()\n\n    # TODO: Implement proper exception catching.\n    try:\n        header_line = ale_lines.index('Column\\n') + 1\n    except:\n        raise ValueError('ALE format error')\n\n    headers = ale_lines[header_line].split('\\t')\n\n    try:\n        sop_index = headers.index('ASC_SOP')\n        sat_index = headers.index('ASC_SAT')\n        name_index = headers.index('Name')\n    except:\n        raise ValueError('No ASC CDL data')\n\n    try:\n        first_data = ale_lines.index('Data\\n') + 1\n    except:\n        raise ValueError('ALE format error')\n\n    for line in ale_lines[first_data:]:\n        line_data = line.split('\\t')\n        sop = re.sub('\\)\\s*\\(|\\s*\\(|\\s*\\)', ' ', line_data[sop_index]).split()\n        sat = line_data[sat_index]\n        name = line_data[name_index]\n        event_cdl = ASC_CDL(name=name)\n        event_cdl.slope = np.array(sop[0:3]).astype(np.float)\n        event_cdl.offset = np.array(sop[3:6]).astype(np.float)\n        event_cdl.power = np.array(sop[6:]).astype(np.float)\n        event_cdl.saturation = float(sat)\n        LUT.append(event_cdl)\n\n    return LUT\n", "meta": {"hexsha": "4259162d2708f735253ecd5b377c48e5c8ff5a55", "size": 12094, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/io/luts/asc_cdl.py", "max_stars_repo_name": "zachlewis/colour", "max_stars_repo_head_hexsha": "c248e2913d6c62658e4892e5bc8503d86ed5d9ab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "colour/io/luts/asc_cdl.py", "max_issues_repo_name": "zachlewis/colour", "max_issues_repo_head_hexsha": "c248e2913d6c62658e4892e5bc8503d86ed5d9ab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/io/luts/asc_cdl.py", "max_forks_repo_name": "zachlewis/colour", "max_forks_repo_head_hexsha": "c248e2913d6c62658e4892e5bc8503d86ed5d9ab", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.412987013, "max_line_length": 79, "alphanum_fraction": 0.5230692906, "include": true, "reason": "import numpy", "num_tokens": 3139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.2782567877172032, "lm_q1q2_score": 0.1585653682546345}}
{"text": "# Copyright 2016, FBPIC contributors\n# Authors: Remi Lehe, Manuel Kirchen\n# License: 3-Clause-BSD-LBNL\n\"\"\"\nThis file is part of the Fourier-Bessel Particle-In-Cell code (FB-PIC)\nIt defines a set of generic functions that operate on a GPU.\n\"\"\"\nfrom numba import cuda\n\n@cuda.jit\ndef copy_vec_to_gpu_buffer( vec_buffer_l, vec_buffer_r,\n                            grid_r, grid_t, grid_z, m,\n                            copy_left, copy_right, nz_start, nz_end ):\n    \"\"\"\n    Copy the ng inner domain cells of grid_r, ..., grid_z\n    to the GPU buffer vec_buffer_l and vec_buffer_r.\n\n    Parameters\n    ----------\n    vec_buffer_l, vec_buffer_r: ndarrays of complexs (device arrays)\n        Arrays of shape (3*Nm, nz_end-nz_start, Nr), which serve as buffer\n        for transmission to CPU, and then sending via MPI. They hold the\n        values of a vector field in either the ng inner cells of the domain\n        or the ng outer + ng inner cells of the domain, to the left and right.\n\n    grid_r, grid_t, grid_z: ndarrays of complexs (device arrays)\n        Arrays of shape (Nz, Nr), which contain the different component\n        of the vector field (r, t, z), in the mode m\n\n    m: int\n        The index of the azimuthal mode involved\n\n    copy_left, copy_right: bool\n        Whether to copy the buffers to the left and right of the local domain\n        (Buffers are not copied at the left end and right end of the\n        global simulation box.)\n\n    nz_start: int\n        The start index in z, of the cell region which is copied to the\n        buffers. The start is defined as an offset from the most outer cell\n        on either the left or the right side of the enlarged domain.\n\n    nz_end: int\n        The end index in z, of the cell region which is copied to the\n        buffers. The end is defined as an offset from the most outer cell\n        on either the left or the right side of the enlarged domain.\n    \"\"\"\n    # Dimension of the arrays\n    Nz, Nr = grid_r.shape\n\n    # Obtain Cuda grid\n    iz, ir = cuda.grid(2)\n\n    # Copy the inner regions of the domain to the buffer\n    if ir < Nr:\n        if iz < (nz_end - nz_start):\n            # At the left end\n            if copy_left:\n                iz_left = nz_start + iz\n                vec_buffer_l[3*m+0, iz, ir] = grid_r[ iz_left, ir ]\n                vec_buffer_l[3*m+1, iz, ir] = grid_t[ iz_left, ir ]\n                vec_buffer_l[3*m+2, iz, ir] = grid_z[ iz_left, ir ]\n            # At the right end\n            if copy_right:\n                iz_right = Nz - nz_end + iz\n                vec_buffer_r[3*m+0, iz, ir] = grid_r[ iz_right, ir ]\n                vec_buffer_r[3*m+1, iz, ir] = grid_t[ iz_right, ir ]\n                vec_buffer_r[3*m+2, iz, ir] = grid_z[ iz_right, ir ]\n\n\n@cuda.jit\ndef copy_scal_to_gpu_buffer( scal_buffer_l, scal_buffer_r, grid, m,\n                             copy_left, copy_right, nz_start, nz_end ):\n    \"\"\"\n    Copy the ng inner domain cells of grid_0, ..., grid_1\n    to the GPU buffer scal_buffer_l and scal_buffer_r.\n\n    Parameters\n    ----------\n    scal_buffer_l, scal_buffer_r: ndarrays of complexs (device arrays)\n        Arrays of shape (Nm, nz_end-nz_start, Nr), which serve as buffer\n        for transmission to CPU, and then sending via MPI. They hold the\n        values of a scalar field in either the ng inner cells of the domain\n        or the ng outer + ng inner cells of the domain, to the left and right.\n\n    grid: ndarray of complexs (device arrays)\n        Arrays of shape (Nz, Nr), which contain the mode m of the scalar field.\n\n    m: int\n        The index of the azimuthal mode involved\n\n    copy_left, copy_right: bool\n        Whether to copy the buffers to the left and right of the local domain\n        (Buffers are not copied at the left end and right end of the\n        global simulation box.)\n\n    nz_start: int\n        The start index in z, of the cell region which is copied to the\n        buffers. The start is defined as an offset from the most outer cell\n        on either the left or the right side of the enlarged domain.\n\n    nz_end: int\n        The end index in z, of the cell region which is copied to the\n        buffers. The end is defined as an offset from the most outer cell\n        on either the left or the right side of the enlarged domain.\n    \"\"\"\n    # Dimension of the arrays\n    Nz, Nr = grid.shape\n\n    # Obtain Cuda grid\n    iz, ir = cuda.grid(2)\n\n    # Copy the inner regions of the domain to the buffer\n    if ir < Nr:\n        if iz < (nz_end - nz_start):\n            # At the left end\n            if copy_left:\n                iz_left = nz_start + iz\n                scal_buffer_l[m, iz, ir] = grid[ iz_left, ir ]\n            # At the right end\n            if copy_right:\n                iz_right = Nz - nz_end + iz\n                scal_buffer_r[m, iz, ir] = grid[ iz_right, ir ]\n\n\n@cuda.jit\ndef replace_vec_from_gpu_buffer( vec_buffer_l, vec_buffer_r,\n                                 grid_r, grid_t, grid_z, m,\n                                 copy_left, copy_right, nz_start, nz_end ):\n    \"\"\"\n    Replace a region (guard region) of grid_0_r, ..., grid_1_z\n    by the GPU buffer vec_buffer_l and vec_buffer_r.\n\n    Parameters\n    ----------\n    vec_buffer_l, vec_buffer_r: ndarrays of complexs (device arrays)\n        Arrays of shape (3*Nm, nz_end-nz_start, Nr), which are the buffers\n        sent via MPI and received by the CPU.\n\n    grid_r, grid_t, grid_z: ndarrays of complexs (device arrays)\n        Arrays of shape (Nz, Nr), which contain the different component\n        of the vector field (r, t, z), in the mode m\n\n    m: int\n        The index of the azimuthal mode involved\n\n    copy_left, copy_right: bool\n        Whether to copy the buffers to the left and right of the local domain\n        (Buffers are not copied at the left end and right end of the\n        global simulation box.)\n\n    nz_start: int\n        The start index in z, of the cell region which is copied to the\n        buffers. The start is defined as an offset from the most outer cell\n        on either the left or the right side of the enlarged domain.\n\n    nz_end: int\n        The end index in z, of the cell region which is copied to the\n        buffers. The end is defined as an offset from the most outer cell\n        on either the left or the right side of the enlarged domain.\n    \"\"\"\n    # Dimension of the arrays\n    Nz, Nr = grid_r.shape\n\n    # Obtain Cuda grid\n    iz, ir = cuda.grid(2)\n\n    # Copy the inner regions of the domain to the buffer\n    if ir < Nr:\n        if iz < (nz_end - nz_start):\n            # At the left end\n            if copy_left:\n                iz_left = iz\n                grid_r[ iz_left, ir ] = vec_buffer_l[3*m+0, iz, ir]\n                grid_t[ iz_left, ir ] = vec_buffer_l[3*m+1, iz, ir]\n                grid_z[ iz_left, ir ] = vec_buffer_l[3*m+2, iz, ir]\n            # At the right end\n            if copy_right:\n                iz_right = Nz - (nz_end - nz_start) + iz\n                grid_r[ iz_right, ir ] = vec_buffer_r[3*m+0, iz, ir]\n                grid_t[ iz_right, ir ] = vec_buffer_r[3*m+1, iz, ir]\n                grid_z[ iz_right, ir ] = vec_buffer_r[3*m+2, iz, ir]\n\n@cuda.jit\ndef replace_scal_from_gpu_buffer( scal_buffer_l, scal_buffer_r, grid, m,\n                                 copy_left, copy_right, nz_start, nz_end ):\n    \"\"\"\n    Replace a region (guard region) of grid_0, ..., grid_1\n    by the GPU buffer scal_buffer_l and scal_buffer_r.\n\n    Parameters\n    ----------\n    scal_buffer_l, scal_buffer_r: ndarrays of complexs (device arrays)\n        Arrays of shape (2, nz_end-nz_start, Nr), which are the buffers\n        sent via MPI and received by the CPU.\n\n    grid: ndarray of complexs (device arrays)\n        Arrays of shape (Nz, Nr), which contain the mode m of the scalar field.\n\n    m: int\n        The index of the azimuthal mode involved\n\n    copy_left, copy_right: bool\n        Whether to copy the buffers to the left and right of the local domain\n        (Buffers are not copied at the left end and right end of the\n        global simulation box.)\n\n    nz_start: int\n        The start index in z, of the cell region which is copied to the\n        buffers. The start is defined as an offset from the most outer cell\n        on either the left or the right side of the enlarged domain.\n\n    nz_end: int\n        The end index in z, of the cell region which is copied to the\n        buffers. The end is defined as an offset from the most outer cell\n        on either the left or the right side of the enlarged domain.\n    \"\"\"\n    # Dimension of the arrays\n    Nz, Nr = grid.shape\n\n    # Obtain Cuda grid\n    iz, ir = cuda.grid(2)\n\n    # Copy the inner regions of the domain to the buffer\n    if ir < Nr:\n        if iz < (nz_end - nz_start):\n            # At the left end\n            if copy_left:\n                iz_left = iz\n                grid[ iz_left, ir ] = scal_buffer_l[m, iz, ir]\n            # At the right end\n            if copy_right:\n                iz_right = Nz - (nz_end - nz_start) + iz\n                grid[ iz_right, ir ] = scal_buffer_r[m, iz, ir]\n\n\n@cuda.jit\ndef add_vec_from_gpu_buffer( vec_buffer_l, vec_buffer_r,\n                             grid_r, grid_t, grid_z, m,\n                             copy_left, copy_right, nz_start, nz_end ):\n    \"\"\"\n    Add the the GPU buffer vec_buffer_l and vec_buffer_r\n    to the vector field grids, grid_r, ..., grid_z.\n\n    Parameters\n    ----------\n    vec_buffer_l, vec_buffer_r: ndarrays of complexs (device arrays)\n        Arrays of shape (3*Nm, nz_end-nz_start, Nr), which are the buffers\n        sent via MPI and received by the CPU.\n\n    grid_r, grid_t, grid_z: ndarrays of complexs (device arrays)\n        Arrays of shape (Nz, Nr), which contain the different component\n        of the vector field (r, t, z), in the mode m\n\n    m: int\n        The index of the azimuthal mode involved\n\n    copy_left, copy_right: bool\n        Whether to copy the buffers to the left and right of the local domain\n        (Buffers are not copied at the left end and right end of the\n        global simulation box.)\n\n    nz_start: int\n        The start index in z, of the cell region which is copied to the\n        buffers. The start is defined as an offset from the most outer cell\n        on either the left or the right side of the enlarged domain.\n\n    nz_end: int\n        The end index in z, of the cell region which is copied to the\n        buffers. The end is defined as an offset from the most outer cell\n        on either the left or the right side of the enlarged domain.\n    \"\"\"\n    # Dimension of the arrays\n    Nz, Nr = grid_r.shape\n\n    # Obtain Cuda grid\n    iz, ir = cuda.grid(2)\n\n    # Copy the inner regions of the domain to the buffer\n    if ir < Nr:\n        if iz < (nz_end - nz_start):\n            # At the left end\n            if copy_left:\n                iz_left = iz\n                grid_r[ iz_left, ir ] += vec_buffer_l[3*m+0, iz, ir]\n                grid_t[ iz_left, ir ] += vec_buffer_l[3*m+1, iz, ir]\n                grid_z[ iz_left, ir ] += vec_buffer_l[3*m+2, iz, ir]\n            # At the right end\n            if copy_right:\n                iz_right = Nz - (nz_end - nz_start) + iz\n                grid_r[ iz_right, ir ] += vec_buffer_r[3*m+0, iz, ir]\n                grid_t[ iz_right, ir ] += vec_buffer_r[3*m+1, iz, ir]\n                grid_z[ iz_right, ir ] += vec_buffer_r[3*m+2, iz, ir]\n\n@cuda.jit\ndef add_scal_from_gpu_buffer( scal_buffer_l, scal_buffer_r, grid, m,\n                              copy_left, copy_right, nz_start, nz_end ):\n    \"\"\"\n    Add the the GPU buffer scal_buffer_l and scal_buffer_r\n    to the scalar field grids, grid_r, ..., grid_z.\n\n    Parameters\n    ----------\n    scal_buffer_l, scal_buffer_r: ndarrays of complexs (device arrays)\n        Arrays of shape (Nm, nz_end-nz_start, Nr), which are the buffers\n        sent via MPI and received by the CPU.\n\n    grid: ndarray of complexs (device arrays)\n        Arrays of shape (Nz, Nr), which contain the mode m of the scalar field.\n\n    m: int\n        The index of the azimuthal mode involved\n\n    copy_left, copy_right: bool\n        Whether to copy the buffers to the left and right of the local domain\n        (Buffers are not copied at the left end and right end of the\n        global simulation box.)\n\n    nz_start: int\n        The start index in z, of the cell region which is copied to the\n        buffers. The start is defined as an offset from the most outer cell\n        on either the left or the right side of the enlarged domain.\n\n    nz_end: int\n        The end index in z, of the cell region which is copied to the\n        buffers. The end is defined as an offset from the most outer cell\n        on either the left or the right side of the enlarged domain.\n    \"\"\"\n    # Dimension of the arrays\n    Nz, Nr = grid.shape\n\n    # Obtain Cuda grid\n    iz, ir = cuda.grid(2)\n\n    # Copy the inner regions of the domain to the buffer\n    if ir < Nr:\n        if iz < (nz_end - nz_start):\n            # At the left end\n            if copy_left:\n                iz_left = iz\n                grid[ iz_left, ir ] += scal_buffer_l[m, iz, ir]\n            # At the right end\n            if copy_right:\n                iz_right = Nz - (nz_end - nz_start) + iz\n                grid[ iz_right, ir ] += scal_buffer_r[m, iz, ir]\n\n# CUDA damping kernels:\n# --------------------\n@cuda.jit\ndef cuda_damp_EB_left( Er, Et, Ez, Br, Bt, Bz, damp_array, n_guard, n_damp ):\n    \"\"\"\n    Multiply the E and B fields in the left guard cells\n    by damp_array.\n\n    Parameters :\n    ------------\n    Er, Et, Ez, Br, Bt, Bz: 2darrays of complexs\n        Contain the fields to be damped\n        The first axis corresponds to z and the second to r\n\n    damp_array : 1darray of floats\n        An array of length n_guard+n_damp,\n        which contains the damping factors.\n\n    n_guard: int\n        Number of guard cells\n\n    n_damp: int\n        Number of damping cells\n    \"\"\"\n    # Obtain Cuda grid\n    iz, ir = cuda.grid(2)\n\n    # Obtain the size of the array along z and r\n    Nz, Nr = Er.shape\n\n    # Modify the fields\n    if ir < Nr :\n        # Apply the damping arrays\n        if iz < n_guard+n_damp:\n            damp_factor_left = damp_array[iz]\n\n            # At the left end\n            Er[iz, ir] *= damp_factor_left\n            Et[iz, ir] *= damp_factor_left\n            Ez[iz, ir] *= damp_factor_left\n            Br[iz, ir] *= damp_factor_left\n            Bt[iz, ir] *= damp_factor_left\n            Bz[iz, ir] *= damp_factor_left\n\n@cuda.jit\ndef cuda_damp_EB_right( Er, Et, Ez, Br, Bt, Bz, damp_array, n_guard, n_damp ):\n    \"\"\"\n    Multiply the E and B fields in the right guard cells\n    by damp_array.\n\n    Parameters :\n    ------------\n    Er, Et, Ez, Br, Bt, Bz : 2darrays of complexs\n        Contain the fields to be damped\n        The first axis corresponds to z and the second to r\n\n    damp_array : 1darray of floats\n        An array of length n_guard+n_damp,\n        which contains the damping factors.\n\n    n_guard: int\n        Number of guard cells\n\n    n_damp: int\n        Number of damping cells\n    \"\"\"\n    # Obtain Cuda grid\n    iz, ir = cuda.grid(2)\n\n    # Obtain the size of the array along z and r\n    Nz, Nr = Er.shape\n\n    # Modify the fields\n    if ir < Nr :\n        # Apply the damping arrays\n        if iz < n_guard+n_damp:\n            damp_factor_right = damp_array[iz]\n\n            # At the right end\n            iz_right = Nz - iz - 1\n            Er[iz_right, ir] *= damp_factor_right\n            Et[iz_right, ir] *= damp_factor_right\n            Ez[iz_right, ir] *= damp_factor_right\n            Br[iz_right, ir] *= damp_factor_right\n            Bt[iz_right, ir] *= damp_factor_right\n            Bz[iz_right, ir] *= damp_factor_right\n", "meta": {"hexsha": "5d2a2243b57ba7f10302542c6ffc346182b67d02", "size": 15718, "ext": "py", "lang": "Python", "max_stars_repo_path": "fbpic/boundaries/cuda_methods.py", "max_stars_repo_name": "fractional-ray/fbpic", "max_stars_repo_head_hexsha": "2574662669acead79190fdb416723ac359fceceb", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fbpic/boundaries/cuda_methods.py", "max_issues_repo_name": "fractional-ray/fbpic", "max_issues_repo_head_hexsha": "2574662669acead79190fdb416723ac359fceceb", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fbpic/boundaries/cuda_methods.py", "max_forks_repo_name": "fractional-ray/fbpic", "max_forks_repo_head_hexsha": "2574662669acead79190fdb416723ac359fceceb", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3002309469, "max_line_length": 79, "alphanum_fraction": 0.6072019341, "include": true, "reason": "from numba", "num_tokens": 4020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3073580295544412, "lm_q1q2_score": 0.1584799212956531}}
{"text": "#!/usr/bin/env python\nimport sys\nif sys.version_info.major == 3:\n    import exodus3 as exo\nelse:\n    import exodus2 as exo\n\ndef parse(args=None):\n    import argparse\n    ### Get options from the command line\n    parser = argparse.ArgumentParser(description='Compute an affine boundary displacement in 2D')\n    parser.add_argument('-i','--inputfile',help='input file',default=None)\n    parser.add_argument('-o','--outputfile',help='output file',default=None)\n    parser.add_argument('--E',type=float,help='Youngs Modulus',default=1)\n    parser.add_argument('--nu',type=float,help='Poisson Ratio',default=0)    \n    parser.add_argument('--type',choices=['planestrain','planestress'],default='planestrain')\n    parser.add_argument('--sigma',type=float,help='Applied stress (sigma_11, sigma_22, sigma_12)',nargs=3,default=[1,0,0])\n    parser.add_argument(\"--cs\",type=int,nargs='*',help=\"list of cell sets where the beam is applied\",default=[])\n    parser.add_argument(\"--vs\",type=int,nargs='*',help=\"list of vertex sets where the beam is applied\",default=[])\n    parser.add_argument(\"--force\",action=\"store_true\",default=False,help=\"Overwrite existing files without prompting\")\n    parser.add_argument(\"--time_min\",type=float,default=1.,help='Start time')\n    parser.add_argument(\"--time_max\",type=float,default=1.,help='End time')\n    parser.add_argument(\"--time_numstep\",type=int,default=1,help='Number of time steps')\n    return parser.parse_args()\n    \ndef exoformat(e,plasticity=False):\n    if plasticity:\n        global_variable_name = [\"Elastic Energy\",\"Work\",\"Surface Energy\",\"Total Energy\",\"Dissipation Plastic\"]\n        if e.num_dimensions() == 2: \n            node_variable_name  = [\"Temperature\",\"Damage\",\"Displacement_X\",\"Displacement_Y\"]\n            element_variable_name   = [\"External_Temperature\",\"Heat_Flux\",\"Pressure_Force\",\n                                       \"Force_X\",\"Force_Y\",\n                                       \"Stress_XX\",\"Stress_YY\",\"Stress_XY\",\n                                       \"Cumulated_Plastic_Energy\",\"plasticStrain_XX\",\"plasticStrain_YY\",\"plasticStrain_XY\"]\n        else:\n            node_variable_name  = [\"Temperature\",\"Damage\",\"Displacement_X\",\"Displacement_Y\",\"Displacement_Z\"]\n            element_variable_name   = [\"External_Temperature\",\"Heat_Flux\",\"Pressure_Force\",\n                                       \"Force_X\",\"Force_Y\",\"Force_Z\",\n                                       \"Stress_XX\",\"Stress_YY\",\"Stress_ZZ\",\"Stress_YZ\",\"Stress_XZ\",\"Stress_XY\",\n                                       \"Cumulated_Plastic_Energy\",\"plasticStrain_XX\",\"plasticStrain_YY\",\"plasticStrain_ZZ\",\"plasticStrain_XY\",\"plasticStrain_YZ\",\"plasticStrain_XZ\",\"plasticStrain_XY\"]\n    else:\n        global_variable_name = [\"Elastic Energy\",\"Work\",\"Surface Energy\",\"Total Energy\"]\n        if e.num_dimensions() == 2: \n            node_variable_name  = [\"Temperature\",\"Damage\",\"Displacement_X\",\"Displacement_Y\"]\n            element_variable_name   = [\"External_Temperature\",\"Heat_Flux\",\"Pressure_Force\",\n                                       \"Force_X\",\"Force_Y\",\n                                       \"Stress_XX\",\"Stress_YY\",\"Stress_XY\"]\n        else:\n            node_variable_name  = [\"Temperature\",\"Damage\",\"Displacement_X\",\"Displacement_Y\",\"Displacement_Z\"]\n            element_variable_name   = [\"External_Temperature\",\"Heat_Flux\",\"Pressure_Force\",\n                                       \"Force_X\",\"Force_Y\",\"Force_Z\",\n                                       \"Stress_XX\",\"Stress_YY\",\"Stress_ZZ\",\"Stress_YZ\",\"Stress_XZ\",\"Stress_XY\"]\n    e.set_global_variable_number(0)\n    e.set_node_variable_number(len(node_variable_name))\n    for i in range(len(node_variable_name)):\n        e.put_node_variable_name(node_variable_name[i],i+1)\n    e.set_element_variable_number(len(element_variable_name))\n    for i in range(len(element_variable_name)):\n        e.put_element_variable_name(element_variable_name[i],i+1)\n    e.set_element_variable_truth_table([True] * e.numElemBlk.value * len(element_variable_name))\n    return(0)\n\ndef displacementBC(e,t,options):\n    import numpy as np\n    E  = options.E\n    nu = options.nu\n    if options.type == 'planestress':\n        e11 = (       options.sigma[0] - nu * options.sigma[1]) / E\n        e22 = (- nu * options.sigma[0] +      options.sigma[1] ) / E\n        e12 = options.sigma[2] * (1. + nu) / E\n    else: #plane strain\n        e11 = ((1. - nu) * options.sigma[0]        - nu * options.sigma[1]) * (1. + nu) / E\n        e22 = (     - nu * options.sigma[0] + (1. - nu) * options.sigma[1] ) * (1. + nu) / E\n        e12 = options.sigma[2] * (1. + nu) / E\n\n    X,Y,Z=e.get_coords()\n    U = np.zeros([2,len(X)])\n    \n    csoffset = [e.elem_blk_info(set)[1] for set in options.cs]        \n    for set in options.cs:\n        connect = e.get_elem_connectivity(set)\n        for cid in range(connect[1]):\n            vertices = [connect[0][cid*connect[2]+c] for c in range(connect[2])]\n            for v in vertices:\n                U[0,v-1] = t * (e11 * X[v-1] + e12 * Y[v-1])\n                U[1,v-1] = t * (e12 * X[v-1] + e22 * Y[v-1])\n        \n    for set in options.vs:\n        for v in e.get_node_set_nodes(set):\n            U[0,v-1] = t * (e11 * X[v-1] + e12 * Y[v-1])\n            U[1,v-1] = t * (e12 * X[v-1] + e22 * Y[v-1])\n    return U\n\n\ndef main():\n    import numpy as np\n    import os\n    import pymef90\n    options = parse()\n    \n    if  os.path.exists(options.outputfile):\n        if options.force:\n            os.remove(options.outputfile)\n        else:\n            if pymef90.confirm(\"ExodusII file {0} already exists. Overwrite?\".format(options.outputfile)):\n                os.remove(options.outputfile)\n            else:\n                print ('\\n\\t{0} was NOT generated.\\n'.format(options.outputfile))\n                return -1\n    exoin  = exo.exodus(options.inputfile,mode='r')\n    exoout = exoin.copy(options.outputfile)\n    exoout.close()\n    exoout  = exo.exodus(options.outputfile,mode='a',array_type='numpy')\n    ### Adding a QA record, needed until visit fixes its exodus reader\n    import datetime\n    import os.path\n    import sys\n    QA_rec_len = 32\n    QA = [os.path.basename(sys.argv[0]),os.path.basename(__file__),datetime.date.today().strftime('%Y%m%d'),datetime.datetime.now().strftime(\"%H:%M:%S\")]\n    exoout.put_qa_records([[ q[0:31] for q in QA],])\n\n    exoformat(exoout)\n    \n    if not  exoout.num_dimensions() == 2:\n        print(\"This program only makes sense in 2D\")\n        return (-1)\n\n    T = np.linspace(options.time_min,options.time_max,options.time_numstep)\n    for step in range(options.time_numstep):\n        t = T[step]\n        print (\"writing step\",step+1,t)\n        exoout.put_time(step+1,t)\n        U = displacementBC(exoout,t,options)\n        exoout.put_node_variable_values(\"Displacement_X\",step+1,U[0,:])\n        exoout.put_node_variable_values(\"Displacement_Y\",step+1,U[1,:])\n    exoout.close()\n    return (0)\n    \nif __name__ == \"__main__\":\n        sys.exit(main())\n\n", "meta": {"hexsha": "7ca7aadaf1c91a1eb6b67b93582b06657802ef2f", "size": 6977, "ext": "py", "lang": "Python", "max_stars_repo_path": "bin/vDefAffineBC2D.py", "max_stars_repo_name": "jeanmichelscherer/mef90", "max_stars_repo_head_hexsha": "48b9b7d8bdaccb846a76833853f6ea81ce6fc9b1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-12-04T01:38:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T17:35:06.000Z", "max_issues_repo_path": "bin/vDefAffineBC2D.py", "max_issues_repo_name": "jeanmichelscherer/mef90", "max_issues_repo_head_hexsha": "48b9b7d8bdaccb846a76833853f6ea81ce6fc9b1", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-19T21:38:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-19T21:38:52.000Z", "max_forks_repo_path": "bin/vDefAffineBC2D.py", "max_forks_repo_name": "jeanmichelscherer/mef90", "max_forks_repo_head_hexsha": "48b9b7d8bdaccb846a76833853f6ea81ce6fc9b1", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2021-01-20T01:57:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T18:11:38.000Z", "avg_line_length": 49.1338028169, "max_line_length": 199, "alphanum_fraction": 0.6118675649, "include": true, "reason": "import numpy", "num_tokens": 1819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.15847991802425682}}
{"text": "#!/usr/bin/env python\nimport numpy as np\nfrom scipy.cluster.vq import vq\nimport os\nimport cPickle as pickle\nimport copy\nimport collections\nfrom collections import defaultdict, Counter, namedtuple\nimport heapq\nimport music21\nfrom datasets import pitches_and_durations_to_pretty_midi\n\nfrom functools import partial\n\n\nclass cls_memoize(object):\n    \"\"\"cache the return value of a method\n\n    This class is meant to be used as a decorator of methods. The return value\n    from a given method invocation will be cached on the instance whose method\n    was invoked. All arguments passed to a method decorated with memoize must\n    be hashable.\n\n    If a memoized method is invoked directly on its class the result will not\n    be cached. Instead the method will be invoked like a static method:\n    class Obj(object):\n        @memoize\n        def add_to(self, arg):\n            return self + arg\n    Obj.add_to(1) # not enough arguments\n    Obj.add_to(1, 2) # returns 3, result is not cached\n    \"\"\"\n    def __init__(self, func):\n        self.func = func\n    def __get__(self, obj, objtype=None):\n        if obj is None:\n            return self.func\n        return partial(self, obj)\n    def __call__(self, *args, **kw):\n        obj = args[0]\n        try:\n            cache = obj.__cache\n        except AttributeError:\n            cache = obj.__cache = {}\n        key = (self.func, args[1:], frozenset(kw.items()))\n        try:\n            res = cache[key]\n        except KeyError:\n            res = cache[key] = self.func(*args, **kw)\n        return res\n\n\nclass Trie(object):\n    def __init__(self):\n        self.root = collections.defaultdict()\n        self._end = \"_end\"\n        self.orders = []\n\n    def insert(self, list_of_items):\n        current = self.root\n        for item in list_of_items:\n            current = current.setdefault(item, {})\n        current.setdefault(self._end)\n        self.orders = sorted(list(set(self.orders + [len(list_of_items)])))\n\n    def order_insert(self, order, list_of_items):\n        s = 0\n        e = order\n        while e < len(list_of_items):\n            # + 1 due to numpy slicing\n            e = s + order + 1\n            self.insert(list_of_items[s:e])\n            s += 1\n\n    def search(self, list_of_items):\n        # items of the list should be hashable\n        # returns True if item in Trie, else False\n        if len(list_of_items) not in self.orders:\n            raise ValueError(\"item {} has invalid length {} for search, only {} supported\".format(list_of_items, len(list_of_items), self.orders))\n        current = self.root\n        for item in list_of_items:\n            if item not in current:\n                return False\n            current = current[item]\n        if self._end in current:\n            return True\n        return False\n\n    @cls_memoize\n    def partial(self, prefix_tuple):\n        prefix = prefix_tuple\n        # items of the list should be hashable\n        # Returns valid keys for continuation\n        if len(prefix) + 1 not in self.orders:\n            raise ValueError(\"item {} has invalid length {} for partial search, only {} supported\".format(prefix, len(prefix), [o - 1 for o in self.orders]))\n        current = self.root\n        for p in prefix:\n            if p not in current:\n                return []\n            current = current[p]\n        return [c for c in current.keys() if c != self._end]\n\n\nNode = namedtuple(\"Node\",\n        [\"level\", \"proposed_note\", \"log_prob\", \"previous_notes\"],\n        verbose=False, rename=False)\n\n\nclass CMP(object):\n    \"\"\" Constrained Markov Process\n\n    Implements tools/ideas from the following papers:\n\n    The Continuator: Musical Interaction with Style\n    F. Pachet\n    https://www.csl.sony.fr/downloads/papers/uploads/pachet-02f.pdf\n\n    Finite-Length Markov Processes With Constraints\n    F. Pachet, P. Roy, G. Barbieri\n    https://www.csl.sony.fr/downloads/papers/2011/pachet-11b.pdf\n\n    Markov Constraints: Steerable Generation of Markov Sequences\n    F. Pachet, P. Roy\n    https://www.csl.sony.fr/downloads/papers/2011/pachet-09c.pdf\n\n    Avoiding Plagiarism in Markov Sequence Generation\n    A. Papadopolous, P. Roy, F. Pachet\n    https://www.csl.sony.fr/downloads/papers/2014/papadopoulos-14a.pdf\n\n    Enforcing Meter in Finite-Length Markov Sequences\n    P. Roy, F. Pachet\n    https://www.csl.sony.fr/downloads/papers/2013/roy-13a.pdf\n\n    Non-Conformant Harmonization: The Real Book in the Style of Take 6\n    F. Pachet, P. Roy\n    https://www.csl.sony.fr/downloads/papers/2014/pachet-14a.pdf\n    \"\"\"\n    def __init__(self, order, max_order=None, ptype=\"max\", named_constraints={}):\n\n        self.order = order\n        self.goods = [Trie() for i in range(0, self.order)]\n        self.max_order = max_order\n        constraint_types = [\"end\", \"start\", \"position\", \"alldiff\", \"contains\", \"not_contains\"]\n        # need to flesh out API\n        # position is dict of dict of list\n        # alldiff key indicates window size\n        assert all([k in constraint_types for k in named_constraints.keys()])\n        self.named_constraints = named_constraints\n        self.bad = Trie()\n        self.ptype = ptype\n        assert ptype in [\"fixed\", \"max\", \"avg\"]\n\n    def insert(self, list_of_items):\n        if self.max_order is not None:\n            self.bad.order_insert(self.max_order, list_of_items)\n        for i in list(range(0, self.order)):\n            self.goods[i].order_insert(i + 1, list_of_items)\n\n    def partial(self, prefix_tuple):\n        prefix = prefix_tuple\n        if self.max_order is not None:\n            prefix = prefix[-self.max_order:]\n        else:\n            prefix = prefix[-self.order:]\n        return self._partial(prefix)\n\n    @cls_memoize\n    def _partial(self, prefix_tuple):\n        # subclass to memoize more values\n        # returns dict of key: prob\n        prefix = prefix_tuple\n        all_p = []\n        all_gp = []\n        for i in list(range(0, self.order))[::-1]:\n            gp = self.goods[i].partial(prefix[-(i + 1):])\n            # already checked for self.max_order\n            if self.max_order is not None:\n                bp = self.bad.partial(prefix[-self.max_order:])\n            else:\n                bp = []\n            p = list(set(gp) - set(bp))\n            if self.ptype == \"fixed\":\n                all_p += p\n                all_gp += gp\n                break\n            else:\n                if len(p) > 0:\n                    all_p += p\n                    all_gp += gp\n                    if self.ptype == \"max\":\n                        break\n\n        \"\"\"\n        d = {k: 1. / len(ps) for k in ps}\n        return d\n        \"\"\"\n\n        sums = Counter(all_gp)\n        tot = sum(sums.values())\n        d = {k: float(v) / tot for k, v in sums.items()}\n        return d\n\n    def check_constraint(self, node, sequence, depth_index, max_length):\n        generated = sequence[-(depth_index + 1):]\n        if \"alldiff\" in self.named_constraints:\n            # windowed alldiff?\n            if len(set(generated)) != len(generated):\n                return False\n\n        if \"start\" in self.named_constraints:\n            valid_start = self.named_constraints[\"start\"]\n            if generated[0] not in valid_start:\n                return False\n\n        if \"end\" in self.named_constraints:\n            valid_end = self.named_constraints[\"end\"]\n            if depth_index == (max_length - 1) and generated[-1] not in valid_end:\n                return False\n\n        if \"position\" in self.named_constraints:\n            position_checks = self.named_constraints[\"position\"]\n            for k, v in position_checks.items():\n                if len(generated) > k and generated[k] not in v:\n                    return False\n\n        if \"contains\" in self.named_constraints:\n            contained_elems = self.named_constraints[\"contains\"]\n            if depth_index == (max_length - 1):\n                for c in contained_elems:\n                    if c not in generated:\n                        return False\n\n        if \"not_contains\" in self.named_constraints:\n            not_contained_elems = self.named_constraints[\"not_contains\"]\n            for nc in not_contained_elems:\n                if nc in generated:\n                    return False\n        return True\n\n    def branch(self, seed_list, length, search=\"depth\", return_on=-1):\n        # seach options\n        # depth\n        # best\n        # breadth\n        # dtob depth-to-best, depth til 1 solution found, then best\n        res = tuple(seed_list)\n\n        options = self.partial(res)\n\n        el = []\n        def dpush(i, p=None):\n            el.append((-p, i))\n\n        def dpop():\n            return el.pop()[1]\n\n        def brpush(i, p=None):\n            el.append((-p, i))\n\n        def brpop():\n            return el.pop(0)[1]\n\n        def bpush(i, p=None):\n            el.append((-p, i))\n\n        def bpop():\n            heapq.heapify(el)\n            return heapq.heappop(el)[1]\n\n        if search == \"dtb\" or search == \"depth\":\n           push = dpush\n           pop = dpop\n        elif search == \"breadth\":\n           push = brpush\n           pop = brpop\n        elif search == \"best\":\n           push = bpush\n           pop = bpop\n        else:\n           raise ValueError(\"Unknown value for 'search', got {}\".format(search))\n\n\n        best_log_prob = -float(\"inf\")\n        for k, v in options.items():\n            log_prob = np.log(v)\n            n = Node(0, k, log_prob, tuple(res))\n            push(n, log_prob)\n\n        soln = {}\n        break_while = False\n        while len(el) > 0 and break_while is False:\n            current = pop()\n            index = current[0]\n            cur_note = current[1]\n            cur_log_prob = current[2]\n            # always adding a number between 0 and -inf, stopping immediately\n            # would be the upper bound on the sequence probability\n            if cur_log_prob < best_log_prob:\n                continue\n            cur_seq = current[3]\n            new_seq = cur_seq + (cur_note,)\n            if index >= length:\n                if cur_seq not in soln:\n                    # soln: log_prob\n                    soln[cur_seq] = cur_log_prob\n                    if cur_log_prob > best_log_prob:\n                        best_log_prob = cur_log_prob\n                        if search == \"dtb\":\n                            heapq.heapify(el)\n                            push = bpush\n                            pop = bpop\n\n                    if return_on > 0:\n                        if len(soln.keys()) >= return_on:\n                            break_while = True\n            else:\n                if self.check_constraint(current, new_seq, index, length):\n                    options = self.partial(new_seq)\n                    for k, v in options.items():\n                        new_log_prob = cur_log_prob + np.log(v)\n                        if new_log_prob >= best_log_prob:\n                            n = Node(index + 1, k, new_log_prob, new_seq)\n                            push(n, new_log_prob)\n\n        res = sorted([(v, k[len(seed_list):]) for k, v in soln.items()])[::-1]\n        return res\n\n\ndef realize_chord(chordstring, numofpitch=3, baseoctave=4, direction=\"ascending\"):\n    \"\"\"\n    given a chordstring like Am7, return a list of numofpitch pitches, starting in octave baseoctave, and ascending\n    if direction == \"descending\", reverse the list of pitches before returning them\n    \"\"\"\n    # https://github.com/shimpe/canon-generator\n    # http://web.mit.edu/music21/doc/moduleReference/moduleHarmony.html\n    try:\n        pitches = music21.harmony.ChordSymbol(chordstring).pitches\n    except ValueError:\n        # enharmonic equivalents\n        orig_chordstring = chordstring\n        if \"halfDim\" in chordstring:\n            chordstring = chordstring.replace(\"halfDim\", \"/o7\")\n        if chordstring[:2] == \"Eb\":\n            chordstring = \"D#\" + chordstring[2:]\n        elif chordstring[:2] == \"Ab\":\n            chordstring = \"G#\" + chordstring[2:]\n        elif chordstring[:2] == \"Bb\":\n            chordstring = \"A#\" + chordstring[2:]\n        try:\n            pitches = music21.harmony.ChordSymbol(chordstring).pitches\n        except ValueError:\n            from IPython import embed; embed(); raise ValueError()\n\n    num_iter = numofpitch / len(pitches) + 1\n    octave_correction = baseoctave - pitches[0].octave\n    result = []\n    actual_pitches = 0\n    for i in range(num_iter):\n        for p in pitches:\n            if actual_pitches < numofpitch:\n                newp = copy.deepcopy(p)\n                newp.octave = newp.octave + octave_correction\n                result.append(newp)\n                actual_pitches += 1\n            else:\n                if direction == \"ascending\":\n                    return result\n                else:\n                    result.reverse()\n                    return result\n        octave_correction += 1\n\n    if direction == \"ascending\":\n        return result\n    else:\n        result.reverse()\n        return result\n\n\ndef render_chords(list_of_chord_lists, name_tag, dur=2, tempo=110, voices=4,\n                  voice_type=\"piano\", save_dir=\"samples/\"):\n        r = list_of_chord_lists\n        midi_p = []\n        for ri in r:\n            rch = [realize_chord(rii, voices) for rii in ri]\n            rt = []\n            for rchi in rch:\n                rt.append([rchi[idx].midi for idx in range(len(rchi))])\n            midi_p.append(rt)\n\n        midi_d = [[[dur for midi_ppii in midi_ppi] for midi_ppi in midi_pi] for midi_pi in midi_p]\n\n        # BTAS to SATB\n        midi_p = [np.array(midi_pi) for midi_pi in midi_p]\n        midi_d = [np.array(midi_di) for midi_di in midi_d]\n\n        midi_pp = []\n        midi_dd = []\n        for p, d in zip(midi_p, midi_d):\n            # hack to avoid strange chords\n            w = np.where((p[:, 3] - p[:, 2]) > 12)[0]\n            p[w, 3] = 0.\n            midi_pp.append(p)\n            midi_dd.append(d)\n\n        # BTAS to SATB\n        midi_pp = [midi_pi[:, ::-1] for midi_pi in midi_pp]\n        midi_dd = [midi_di[:, ::-1] for midi_di in midi_dd]\n\n        name_stub = name_tag.split(\".\")[0]\n        text_tag = save_dir + \"/\" + name_stub + \".txt\"\n        for i in range(len(midi_pp)):\n            with open(text_tag.format(i), \"w\") as f:\n                r = \" | \".join(list_of_chord_lists[i])\n                f.writelines([r])\n\n        pitches_and_durations_to_pretty_midi(midi_pp, midi_dd,\n                                             save_dir=save_dir,\n                                             name_tag=name_tag,\n                                             default_quarter_length=tempo,\n                                             voice_params=voice_type)\n\ndef transpose(chord_seq):\n    roots = [\"C\", \"C#\", \"D\", \"Eb\", \"E\", \"F\", \"F#\", \"G\", \"Ab\", \"A\", \"Bb\", \"B\"]\n    roots2map = {k: v for v, k in enumerate(roots)}\n    # 2 octaves for easier transpose\n    oct_roots = roots + roots\n    map2roots = {k: v for k, v in enumerate(oct_roots)}\n\n    prototype = []\n    for c in chord_seq:\n        if c[:-1] in roots2map:\n            prototype.append(roots2map[c[:-1]])\n        elif c[:2] in roots2map:\n            prototype.append(roots2map[c[:2]])\n        elif c[0] in roots2map:\n            prototype.append(roots2map[c[0]])\n        else:\n            print(c)\n            from IPython import embed; embed(); raise ValueError()\n\n    chord_types = [\"m\", \"7\", \"halfDim\"]\n    chord_function = []\n    for c in chord_seq:\n        if \"halfDim\" in c:\n            chord_function.append(\"halfDim\")\n            continue\n        elif c[-1] not in [\"m\", \"7\"]:\n            chord_function.append(\"\")\n            continue\n        chord_function.append(c[-1])\n\n    assert len(chord_function) == len(prototype)\n    all_t = []\n    for i in range(len(roots)):\n        t = [map2roots[p + i] + cf for p, cf in zip(prototype, chord_function)]\n        all_t.append(t)\n    return all_t\n\n\n# hardcode the data for now\nwith open(\"12BarBluesOmnibook.txt\", \"r\") as f:\n   r = f.readlines()\nnames = r[::2]\nbars = r[1::2]\nnames = [n.strip() for n in names]\nbars = [b.strip() for b in bars]\n\npairs = zip(names, bars)\nnew_bars = []\nfor n, b in pairs:\n    bb = [bi.split(\"/\") for bi in b.split(\"|\")]\n    bb = [bbii for bbi in bb for bbii in bbi]\n    new_bars.append(bb)\npairs = zip(names, new_bars)\n\nfinal_pairs = []\nfor p in pairs:\n    t_p = transpose(p[1])\n    final_pairs += [(p[0], ti_p) for ti_p in t_p]\npairs = final_pairs\n\n# chord length\ndur = 2\n# synthesis tempo\ntempo = 110\n# number of examples considered, be careful as big numbers cause much larger runtime\ndataset_size = 12\n# history considered for likelihood scores\norder = 1\n\nm = CMP(order,\n        max_order=None,\n        ptype=\"fixed\",\n        named_constraints={\"not_contains\": [\"C7\"],\n                           \"position\": {8: [\"F7\"]},\n                           \"alldiff\": True,\n                           \"end\": [\"G7\"]},\n        verbose=True)\n\n# too many songs and bad things happen...\nfor n, p in enumerate(pairs):\n    m.insert(p[1])\n    if n > 12:\n        break\n\nt = m.branch([\"C7\"], 15)\nif len(t) == 0:\n    raise ValueError(\"No solution found!\")\n\nres = t[0][1]\nres = (\"C7\",) + res\n# repeat it 2x\nrender_chords([res + res], \"sample_branch_{}.mid\", dur=dur, tempo=tempo)\nimport sys\nsys.exit()\n", "meta": {"hexsha": "dfc9fd796f9bab8632af9c765b0ec261f6d51b8f", "size": 17230, "ext": "py", "lang": "Python", "max_stars_repo_path": "markov_steerable.py", "max_stars_repo_name": "kastnerkyle/pachet_experiments", "max_stars_repo_head_hexsha": "94e66689e3b59f1e2ddbd1e571f69bdbc77e4d65", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2017-07-05T14:37:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-18T21:07:10.000Z", "max_issues_repo_path": "markov_steerable.py", "max_issues_repo_name": "kastnerkyle/pachet_experiments", "max_issues_repo_head_hexsha": "94e66689e3b59f1e2ddbd1e571f69bdbc77e4d65", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "markov_steerable.py", "max_forks_repo_name": "kastnerkyle/pachet_experiments", "max_forks_repo_head_hexsha": "94e66689e3b59f1e2ddbd1e571f69bdbc77e4d65", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-02-23T22:33:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-03T10:11:38.000Z", "avg_line_length": 33.3268858801, "max_line_length": 157, "alphanum_fraction": 0.5554846198, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096344, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.1584799160569859}}
{"text": "##\n#\n# @mainpage CGMFtk class to read & analyze CGMF history files\n#\n# -----------------------------------------------------------------------------\n#  CGMF-1.1\n#  Copyright TRIAD/LANL/DOE - see file LICENSE\n#  For any questions about CGMF, please contact us at cgmf-help@lanl.gov\n# -----------------------------------------------------------------------------\n#\n# @section Description\n# The class Histories provides routines to read complete CGMF Monte Carlo history\n# files, return arrays or lists of important quantities for further analyses, \n# compute average quantities, distributions and correlations, and provide a \n# summary table of the main average quantities.\n#\n\n# Imports\nimport numpy as np\nimport sys\n\n# Functions\nclass Histories:\n\t\n\tdef __init__ (self, filename, nevents=None):\n\t\t\"\"\"! Initializes the Histories class\n\n\t\tfilename -- file path/name\n\t\tnevents -- number of fission events to read in\n\t\t\"\"\"\n\n\t\t# check that the files exists, otherwise, exit\n\t\ttry:\n\t\t\tf = open(filename)\n\t\t\tself.filename = filename\n\t\t\tf.close()\n\t\texcept IOError:\n\t\t\tsys.exit('that file does not exist')\n\n\t\t# check that nevents is > 0, if given\n\t\ttry:\n\t\t\tval = int(nevents)\n\t\t\tif (val <= 0):\n\t\t\t\tprint ('nevents must be greater than zero')\n\t\t\t\tsys.exit()\n\t\texcept ValueError:\n\t\t\tsys.exit('nevents must be a number greater than zero')\n\t\texcept TypeError:\n\t\t\tif (nevents is not None):\n\t\t\t\tsys.exit('nevents must be a number')\n                                \n\n\t\t\t\n\t\t# read the history file\t\n\t\tself.histories = self._readHistoryFileFromCGMF (filename,nevents)\n\n\t\tself.numberFragments = len(self.histories)\n\t\tself.numberEvents = int(self.numberFragments/2)\n\t\t\n\t\t# print a warning if nevents is greater than the number of events read\n\t\tif (nevents is not None and nevents>self.numberEvents):\n\t\t\tprint ('WARNING')\n\t\t\tprint ('You asked for ',int(nevents),' events and there are only ',self.numberEvents,' in this history file')\n\t\t\t\n\t\tself.A = self.histories[:,0].astype(int)\n\t\tself.Z = self.histories[:,1].astype(int)\n\t\tself.N = self.A-self.Z\n\t\tself.U = self.histories[:,2].astype(np.float64)\n\t\tself.J = self.histories[:,3].astype(np.float64)\n\t\tself.P = self.histories[:,4].astype(int)\n\t\tself.KEpre = self.histories[:,5].astype(np.float64)\n\t\tself.KEpost = self.histories[:,24].astype(np.float64)\n\n\t\tnumDataOut = len(self.histories[0,:])\n\n\t\t# neutron multiplicities\n\t\tself.nu    = self.histories[:,6].astype(int)\n\t\tself.nuLF  = self.nu[::2]\n\t\tself.nuHF  = self.nu[1::2]\n\t\tself.nutot = self.nuLF+self.nuHF\n\t\t\n\t\t# gamma multiplicities\n\t\tself.nug    = self.histories[:,7].astype(int)\n\t\tself.nugLF  = self.nug[::2]\n\t\tself.nugHF  = self.nug[1::2]\n\t\tself.nugtot = self.nugLF+self.nugHF\n\n\t\t# neutron and gamma energies in the center-of-mass of fragments\n\t\tself.nEcm   = self.histories[:,8]\n\t\tself.nEcmLF = self.nEcm[::2]\n\t\tself.nEcmHF = self.nEcm[1::2]\n\n\t\t# neutron and gamma energies in the lab\n\t\tself.nElab   = self.histories[:,9]\n\t\tself.nElabLF = self.nElab[::2]\n\t\tself.nElabHF = self.nElab[1::2]\n\t\t\n\t\tself.gElab   = self.histories[:,11]\n\t\tself.gElabLF = self.gElab[::2]\n\t\tself.gElabHF = self.gElab[1::2]\n\n\t\tself.nEcmFragments  = self.nEcm  #-- just fragments (no pre-fission neutrons)\n\t\tself.nElabFragments = self.nElab #-- just fragments (no pre-fission neutrons)\n\n\t\t# timing information for gammas - if recorded\n\t\tself.gTimes = self.histories[:,12]\n\n\t\t# neutron directional cosines in the lab frame\n\t\tself.cmNeutronDircos = self.histories[:,19]\n\t\tself.labNeutronDircos = self.histories[:,20]\n\n\t\t#-- pre-fission neutron energies and directional cosines\n\t\tself.preFissionNu            = self.histories[1::2,21]\n\t\tself.preFissionNeutronElab   = self.histories[1::2,22]\n\t\tself.preFissionNeutronDircos = self.histories[1::2,23]\n\n\t\t# Fission fragment momentum vectors (pre-neutron emission)\n\t\tpfx = self.histories[:,13]\n\t\tpfy = self.histories[:,14]\n\t\tpfz = self.histories[:,15]\n\t\tself.preFF = np.dstack ((pfx,pfy,pfz))\n\t\tself.preFF = self.preFF.reshape((self.numberFragments,3))\n\n\t\t# Fission fragment momentum vectors (post-neutron emission)\n\t\tpfx = self.histories[:,16]\n\t\tpfy = self.histories[:,17]\n\t\tpfz = self.histories[:,18]\n\t\tself.postFF = np.dstack ((pfx,pfy,pfz))\n\t\tself.postFF = self.postFF.reshape((self.numberFragments,3))\n\n\t\t# Total Kinetic Energy (MeV)\n\t\tself.TKEpre = self.KEpre[::2]+self.KEpre[1::2]\n\t\t# Total Kinetic Energy (MeV) after neutron emission\n\t\tself.TKEpost = self.KEpost[::2]+self.KEpost[1::2]\n\t\n\t\t# Total eXcitation Energy (MeV)\n\t\tself.TXE = self.U[::2]+self.U[1::2]\n\n\t\t# Light Fragments\n\t\tself.Al = self.A[::2]\n\t\tself.Zl = self.Z[::2]\n\t\tself.Ul = self.U[::2]\n\t\tself.Jl = self.J[::2]\n\t\tself.Pl = self.P[::2]\n\t\tself.KEl = self.KEpre[::2]\n\n\t\t# Heavy Fragments\n\t\tself.Ah = self.A[1::2]\n\t\tself.Zh = self.Z[1::2]\n\t\tself.Uh = self.U[1::2]\n\t\tself.Jh = self.J[1::2]\n\t\tself.Ph = self.P[1::2]\n\t\tself.KEh = self.KEpre[1::2]\n\n\n\tdef _readHistoryFileFromCGMF (self,filename,nevents):\n\t\t\"\"\" Reads CGMF history file (filename) and returns a list of simulations \"\"\"\n\n\t\tf = open (filename)\n\n\t\tif (nevents is not None):\n\t\t\tmaxNumberEvents = 2*int(nevents)\n\t\t\thasMaxNumber = True\n\t\telse:\n\t\t\thasMaxNumber = False\n\n\t\tA  = [] #-- fragment masses\n\t\tZ  = [] #-- fragment charges\n\t\tU  = [] #-- fragment initial excitation energies\n\t\tJ  = [] #-- fragment initial angular momentum (hbar)\n\t\tP  = [] #-- fragment initial parity\n\n\t\tKEpre  = [] #-- pre-neutron emission fragment kinetic energy (MeV)\n\t\tKEpost = [] #-- post-neutron emission fragment kinetic energy (MeV)\n\n\t\tnmult    = [] #-- neutron multiplicity (n/f)\n\t\tgmult    = [] #-- gamma multiplicity (g/f)\n\t\tprenmult = [] #-- pre-fission neutron multiplicity (n/f)\n\n\t\tcmNeutronDircos    = [] #-- neutron directional cosines in center-of-mass frame of the fragment\n\t\tcmNeutronEnergies  = [] #-- neutron energies in CM frame (MeV)\n\t\tlabNeutronDircos   = [] #-- neutron directional cosines in LAB frame\n\t\tlabNeutronEnergies = [] #-- neutron energies in LAB frame (MeV)\n\n\t\tlabPreFissionNeutronEnergies = [] #-- pre-fission neutron energies in LAB frame (MeV)\n\t\tlabPreFissionNeutronDircos   = [] #-- pre-fission neutron directional cosines in LAB frame\n\n\t\tcmGammaDircos    = [] #-- gamma directional cosines in CM frame\n\t\tcmGammaEnergies  = [] #-- gamma energies in CM frame (MeV)\n\t\tlabGammaDircos   = [] #-- gamma directional cosines in LAB frame\n\t\tlabGammaEnergies = [] #-- gamma energies in LAB frame (MeV)\n\n\t\tphotonAges = [] #-- timing information for gamma rays\n\n\t\tpreFragments  = [] #-- pre-neutron emission fragment momentum vectors\n\t\tpostFragments = [] #-- post-neutron emission fragment momentum vectors\n\n\t\tpreFragmentsX = [] #-- pre-neutron emission x-momentum vector\n\t\tpreFragmentsY = [] #-- pre-neutron emission y-momentum vector\n\t\tpreFragmentsZ = [] #-- pre-neutron emission z-momentum vector\n\n\t\tpostFragmentsX = [] #-- post-neutron emission x-momentum vector\n\t\tpostFragmentsY = [] #-- post-neutron emission y-momentum vector\n\t\tpostFragmentsZ = [] #-- post-neutron emission z-momentum vector\n\n\t\t##############################################################################\n\n\t\tline = f.readline()\n\t\tif (line.find(\"#\")!=0):\n\t\t\tsys.exit(\"ERROR: FIRST LINE OF OUTPUT FILE SHOULD CONTAIN '#'\")\n\t\telse:\n\t\t\tdata = line[1:].strip().split()\n\t\t\tZAIDc   = int(data[0])\n\t\t\tZc = int(ZAIDc/1000)\n\t\t\tAc = int(ZAIDc)-1000*Zc + 1 #-- add incident neutron to get CN \n\t\t\tAsym = int(float(Ac)/2.0)\n\t\t\tEinc    = float(data[1])\n\t\t\tif (Einc==0.0):\n\t\t\t\tAc = Ac - 1 #-- no incident neutron for spontaneous fission\n\t\t\tif (len(data)>2):\n\t\t\t\tself.time = float(data[-1]) # timing cut-off for gammas, -1 records all times of emission\n\t\t\telse: \n\t\t\t\tself.time = 0\n\n\t\tisLightFragment=True\n\n\t\tc=0\n\t\tindex=0\n\t\tnfragments=0\n\t\twhile True:\n\t\t\tc+=1\n\t\t\t# if we only want to read a certain number of events, check here\n\t\t\tif (hasMaxNumber and c>maxNumberEvents):\n\t\t\t\tbreak\n\t\t\tline = f.readline()\n\t\t\tif (len(line)==0):\n\t\t\t\tbreak\n\t\n\t\t\tdata = line.split()\n\t\t\tnfragments+=1\n\t\t\t\n\t\t\tA.append(int(data[0]))\n\t\t\tZ.append(int(data[1]))\n\t\t\tU.append(float(data[2]))\n\t\t\tJ.append(float(data[3]))\n\t\t\tP.append(int(data[4]))\n\t\t\tKEpre.append(float(data[5]))\n\t\t\tKEpost.append(float(data[6]))\n\n\t\t\tif (isLightFragment):\n\t\t\t\tAl=int(data[0])\n\t\t\telse:\n\t\t\t\tAh=int(data[0])\n\t\t\n\t\t\tnn=int(data[7])\n\t\t\tng=int(data[8])\n\t\t\tnpn=int(data[9])\n\n\t\t\tnmult.append(nn)\n\t\t\tgmult.append(ng)\n\t\t\tprenmult.append(npn) #-- (should always be 0 for LF)\n\n\t\t\t# read pre- and post-neutron emission fission fragment momentum vectors\n\t\t\tdata = f.readline().split()\n\t\t\tpreFF=[]\n\t\t\tpostFF=[]\n\t\t\tpreFF.append  (np.array([float(data[0]),float(data[1]),float(data[2])]))\n\t\t\tpostFF.append (np.array([float(data[3]),float(data[4]),float(data[5])]))\n\t\t\t\n\t\t\tpfx = float(data[0])\n\t\t\tpfy = float(data[1])\n\t\t\tpfz = float(data[2])\n\n\t\t\tpfx2 = float(data[3])\n\t\t\tpfy2 = float(data[4])\n\t\t\tpfz2 = float(data[5])\n\n\t\t\t#-- read neutron momentum vectors\n\t\t\t# in center of mass frame\n\t\t\tcmDn=[]\n\t\t\tcmEn=[]\n\t\t\tlabDn=[]\n\t\t\tlabEn=[]\n\t\t\tlabDpren=[]\n\t\t\tlabEpren=[]\n\n\t\t\tif (nn>0):\n\n\t\t\t\tdata=f.readline().split()\n\t\t\t\tfor i in range(nn):\n\t\t\t\t\tcmDn.append(np.array([float(data[0+i*4]),float(data[1+i*4]),float(data[2+i*4])]))\n\t\t\t\t\tcmEn.append(float(data[3+i*4]))\n\t\n\t\t\t\t# in lab frame\n\t\t\t\tdata=f.readline().split()\n\t\t\t\tfor i in range(nn):\n\t\t\t\t\tlabDn.append(np.array([float(data[0+i*4]),float(data[1+i*4]),float(data[2+i*4])]))\n\t\t\t\t\tlabEn.append(float(data[3+i*4]))\n\n\t\t\t#-- read photon momentum vectors (lab=center-of-mass frame in this case, for now)\n\t\t\tDg=[]\n\t\t\tEg=[]\n\t\t\tTg=[]\n\n\t\t\tif (ng>0 and self.time<0.):\n\t\t\t\tdata=f.readline().split()\n\t\t\t\tfor i in range(ng):\n\t\t\t\t\tDg.append(np.array([float(data[0+i*5]),float(data[1+i*5]),float(data[2+i*5])]))\n\t\t\t\t\tEg.append(float(data[3+i*5]))\n\t\t\t\t\tTg.append(float(data[4+i*5]))\n\t\t\telif (ng>0):\n\t\t\t\tdata=f.readline().split()\n\t\t\t\tfor i in range(ng):\n\t\t\t\t\tDg.append(np.array([float(data[0+i*4]),float(data[1+i*4]),float(data[2+i*4])]))\n\t\t\t\t\tEg.append(float(data[3+i*4]))\n\t\t\t\t\tTg.append(0.0)\n\n\t\t\t#-- read pre-fission neutron data (if any)\n\t\t\tif (isLightFragment):\n\t\t\t\tif (npn!=0):\n\t\t\t\t\tprint (\"npn should be zero for light fragment! -- ABORT!\\n\")\n\t\t\t\t\texit(-1)\n\t\t\t\tisLightFragment=False\n\t\t\telse:\n\t\t\t\tif (Ac-Al-Ah!=npn):\n\t\t\t\t\tprint (\"Incorrect number of pre-fission neutrons! -- ABORT!\\n\")\n\t\t\t\tisLightFragment=True\n\n\t\t\t\tif (npn>0):\n\t\t\t\t\tdata = f.readline().split()\n\t\t\t\t\tfor i in range(npn):\n\t\t\t\t\t\tlabDpren.append(np.array([float(data[0+i*4]),float(data[1+i*4]),float(data[2+i*4])]))\n\t\t\t\t\t\tlabEpren.append(float(data[3+i*4]))\n\t\t\t\telse:\n\t\t\t\t\tlabDpren.append(np.array([0.0,0.0,0.0]))\n\t\t\t\t\tlabEpren.append(0.0)\n\n\t\t\t#-- store in final list for output\n\t\t\t\n\t\t\tcmNeutronEnergies.append(cmEn)\n\t\t\tcmNeutronDircos.append(cmDn)\n\t\t\tlabNeutronEnergies.append(labEn)\n\t\t\tlabNeutronDircos.append(labDn)\n\t\t\tlabPreFissionNeutronEnergies.append(labEpren)\n\t\t\tlabPreFissionNeutronDircos.append(labDpren)\n\t\t\t\t\t\t\t\t\t\t\t \n\t\t\tcmGammaEnergies.append(Eg)\n\t\t\tcmGammaDircos.append(Dg)\n\t\t\tlabGammaEnergies.append(Eg)\n\t\t\tlabGammaDircos.append(Dg)\n\t\t\tphotonAges.append(Tg)\n\n\t\t\tpreFragmentsX.append (pfx)\n\t\t\tpreFragmentsY.append (pfy)\n\t\t\tpreFragmentsZ.append (pfz)\n\n\t\t\tpostFragmentsX.append (pfx2)\n\t\t\tpostFragmentsY.append (pfy2)\n\t\t\tpostFragmentsZ.append (pfz2)\n\n\t\tf.close()\n\t\t\n\t\tnevents = int(nfragments/2)\n\n\t\tdata = np.dstack((A,Z,U,J,P,KEpre,nmult,gmult,cmNeutronEnergies,labNeutronEnergies,cmGammaEnergies, labGammaEnergies,photonAges,preFragmentsX,preFragmentsY,preFragmentsZ,postFragmentsX,postFragmentsY,postFragmentsZ,cmNeutronDircos,labNeutronDircos,prenmult,labPreFissionNeutronEnergies,labPreFissionNeutronDircos,KEpost))\n\n\n\t\tdata = data[0,:,:]\n\n\t\treturn (data)\n\n\t# Functions to return all quantities recorded\n\t\n\tdef getFissionHistories(self):\n\t\t\"\"\"Returns a list with the full simulation history\"\"\"\n\t\treturn (self.histories)\n\n\tdef getNumberFragments(self):\n\t\t\"\"\"Returns the total number of fission fragments recorded in a CGMF run\n\t\t\t\"\"\"\n\t\treturn (self.numberFragments)\n\n\tdef getTimeCoincidenceWindow(self):\n\t\t\"\"\"Returns the time coincidence window for the gamma rays\"\"\"\n\t\treturn (self.time)\n\t\n\tdef getNumberEvents(self):\n\t\t\"\"\"Returns the number of simulated events\"\"\"\n\t\treturn (self.numberEvents)\n\t\n\tdef getA(self):\n\t\t\"\"\"Returns a list of the mass (A) for each fragment\"\"\"\n\t\treturn (self.A)\n\n\tdef getZ(self):\n\t\t\"\"\"Returns a list of the charge (Z) for each fragment\"\"\"\n\t\treturn (self.Z)\n\n\tdef getN(self):\n\t\t\"\"\"Returns a list of the neutron number (N) for each fragment\"\"\"\n\t\treturn (self.N)\n\n\tdef getU(self):\n\t\t\"\"\"Returns a list of excitation energy (U) for each fragment\"\"\"\n\t\treturn (self.U)\n\t\n\tdef getJ(self):\n\t\t\"\"\"Returns a list of spin (J) for each fragment\"\"\"\n\t\treturn (self.J)\n\n\tdef getP(self):\n\t\t\"\"\"Returns a list of parity, +1 or -1, (P) for each fragment\"\"\"\n\t\treturn (self.P)\n\n\tdef getKEpre(self):\n\t\t\"\"\"Returns a list of kinetic energy (KE) for each fragment before neutron emission\"\"\"\n\t\treturn (self.KEpre)\n\n\tdef getKEpost(self):\n\t\t\"\"\"Returns a list of kinetic energies (KE) for each fragment after neutron emission\"\"\"\n\t\treturn (self.KEpost)\n\n\tdef getNu(self):\n\t\t\"\"\"Returns a list of the number of neutrons for each fission fragment (no pre-fission)\"\"\"\n\t\treturn (self.nu)\n\t\n\tdef getNuEvent(self):\n\t\t\"\"\"Returns a list of the total number of neutrons for each fission event (no pre-fission)\"\"\"\n\t\treturn (self.nuLF+self.nuHF)\n\n\tdef getNuEnergyCut(self, Eth):\n\t\t\"\"\"Returns an array of neutron multiplicity per fragment, with an energy threshold Eth (MeV)\"\"\"\n\t\tnuCut=[]\n\t\tfor i in range(self.numberFragments):\n\t\t\tEn=np.asarray(self.nElab[i])\n\t\t\tEn=En[En>Eth]\n\t\t\tnuCut.append(np.size(En))\n\t\tnuCut=np.asarray(nuCut)\n\t\treturn (nuCut)\n\n\tdef getNuLF(self):\n\t\t\"\"\"Returns a list of the number of neutrons for each light fission fragment\"\"\"\n\t\treturn (self.nuLF)\n\n\tdef getNuHF(self):\n\t\t\"\"\"Returns the number of neutrons for each heavy fission fragment\"\"\"\n\t\treturn (self.nuHF)\n\n\tdef getNutot(self):\n\t\t\"\"\"Returns a list of the total number of neutrons for each fission event including pre-fission neutrons\"\"\"\n\t\treturn (self.nuLF+self.nuHF+self.preFissionNu)\n\t\n\tdef getPreFissionNu(self):\n\t\t\"\"\"Returns a list of the number of pre-fission neutrons for each fission event\"\"\"\n\t\treturn (self.preFissionNu)\n\n\tdef getNug(self):\n\t\t\"\"\"Returns a list of the number of gammas emitted for each fission fragment\"\"\"\n\t\treturn (self.nug)\n\n\tdef getNugEnergyCut(self, Eth):\n\t\t\"\"\"Returns an array of gamma multiplicity per fragment, with an energy threshold Eth (MeV)\"\"\"\n\t\tnugCut=[]\n\t\tfor i in range(self.numberFragments):\n\t\t\tEg=np.asarray(self.gElab[i])\n\t\t\tEg=Eg[Eg>Eth]\n\t\t\tnugCut.append(np.size(Eg))\n\t\tnugCut=np.asarray(nugCut)\n\t\treturn (nugCut)\n\n\tdef getNugLF(self):\n\t\t\"\"\"Returns the number of gammas emitted for each light fission fragment\"\"\"\n\t\treturn (self.nugLF)\n\n\tdef getNugHF(self):\n\t\t\"\"\"Returns a list of the number of gammas emitted for each heavy fission fragment\"\"\"\n\t\treturn (self.nugHF)\n\t\n\tdef getNugtot(self):\n\t\t\"\"\"Returns a list of the total number of gammas per fission event\"\"\"\n\t\treturn (self.nugLF+self.nugHF)\n\t\n\tdef getTKEpre(self):\n\t\t\"\"\"Returns a list of the total kinetic energy per fission event (pre neutron emission)\"\"\"\n\t\treturn (self.TKEpre)\n\n\tdef getTKEpost(self):\n\t\t\"\"\"Returns a list of the total kinetic energy per fission event (post neutron emission)\"\"\"\n\t\treturn (self.TKEpost)\n\n\tdef getTXE(self):\n\t\t\"\"\"Returns a list of the total excitation energy per fission event\"\"\"\n\t\treturn (self.TXE)\n\n\tdef getNeutronElab (self):\n\t\t\"\"\"Returns a list of lists of the neutron energies in the lab frame for each fission fragment\"\"\"\n\t\treturn (self.nElab)\n\n\tdef getNeutronEcm (self):\n\t\t\"\"\"Returns a list of lists of the neutron energies in the cm frame for each fission fragment\"\"\"\n\t\treturn (self.nEcm)\n\n\tdef getGammaElab (self):\n\t\t\"\"\"Returns a list of lists of the gamma energies for each fission fragment\"\"\"\n\t\treturn (self.gElab)\n\n\tdef getGammaAges (self):\n\t\t\"\"\"Returns a list of the gamma times\"\"\"\n\n\t\treturn (self.gTimes)\n\n\tdef getPreFissionNeutronElab (self):\n\t\t\"\"\"Returns a list of lists of the neutrons eneriges before fission for each fission event\"\"\"\n\t\treturn (self.preFissionNeutronElab)\n\n\tdef getPreFissionNeutronDircos (self):\n\t\t\"\"\"Returns a list of lists of the neutron directional cosines before fission for each fission event\"\"\"\n\t\treturn (self.preFissionNeutronDircos)\n\t\n\tdef getFragmentMomentumPre(self):\n\t\t\"\"\"Returns a list of momenta vectors for each fission fragment before neutron and gamma emission\"\"\"\n\t\treturn (self.preFF)\n\t\n\tdef getFragmentMomentumPost(self):\n\t\t\"\"\"Returns a list of momenta vectors for each fission fragment after neutron and gamma emission\"\"\"\n\t\treturn (self.postFF)\n\t\n\tdef getLabNeutronDircos (self):\n\t\t\"\"\"Returns a list of neutron directional cosines for each fission fragment in the lab frame\"\"\"\n\t\treturn (self.labNeutronDircos)\n\t\n\tdef getcmNeutronDircos (self):\n\t\t\"\"\"Returns a list of neutron directional cosines for each fission fragment in the center of mass frame\"\"\"\n\t\treturn (self.cmNeutronDircos)\n\n\t# quantities for the light fragments\n\n\tdef getALF(self):\n\t\t\"\"\"Returns a list of the masses of the light fission fragments\"\"\"\n\t\treturn (self.Al)\n\n\tdef getZLF(self):\n\t\t\"\"\"Returns a list of the charges of the light fission fragments\"\"\"\n\t\treturn (self.Zl)\n\n\tdef getNLF(self):\n\t\t\"\"\"Returns a list of the number of neutrons of the light fission fragments\"\"\"\n\t\treturn (self.Al-self.Zl)\n\n\tdef getULF(self):\n\t\t\"\"\"Returns a list of the excitation energy of the light fission fragments\"\"\"\n\t\treturn (self.Ul)\n\n\tdef getJLF(self):\n\t\t\"\"\"Returns a list of the spin of the light fission fragments\"\"\"\n\t\treturn (self.Jl)\n\n\tdef getPLF(self):\n\t\t\"\"\"Returns a list of the parity of the light fission fragments\"\"\"\n\t\treturn (self.Pl)\n\n\tdef getKELF(self):\n\t\t\"\"\"Returns a list of the kinetic energies of the light fission fragments\"\"\"\n\t\treturn (self.KEl)\n\n\t# quantities for the heavy fragments\n\n\tdef getAHF(self):\n\t\t\"\"\"Returns a list of the masses of the heavy fission fragments\"\"\"\n\t\treturn (self.Ah)\n\n\tdef getZHF(self):\n\t\t\"\"\"Returns a list of the charges of the heavy fission fragments\"\"\"\n\t\treturn (self.Zh)\n\n\tdef getNHF(self):\n\t\t\"\"\"Returns a list of the number of neutrons of the heavy fission fragments\"\"\"\n\t\treturn (self.Ah - self.Zh)\n\n\tdef getUHF(self):\n\t\t\"\"\"Returns a list of the excitation energy of the heavy fission fragments\"\"\"\n\t\treturn (self.Uh)\n\n\tdef getJHF(self):\n\t\t\"\"\"Returns a list of the spin of the heavy fission fragments\"\"\"\n\t\treturn (self.Jh)\n\n\tdef getPHF(self):\n\t\t\"\"\"Returns a list of the parity of the heavy fission fragments\"\"\"\n\t\treturn (self.Ph)\n\n\tdef getKEHF(self):\n\t\t\"\"\"Returns a list of the kinetic energy of the heavy fission fragments\"\"\"\n\t\treturn (self.KEh)\n\n\t#################################################################\n\t#-- average quantities\t\t\t\t\t\t#\n\t#################################################################\n\n\tdef nubar(self):\n\t\t\"\"\"Returns average neutron multiplicity per fragment, without pre-fission neutrons\"\"\"\n\t\treturn (np.mean(self.nu))\n\n\tdef nubartot(self):\n\t\t\"\"\"Returns average neutron multiplicity per fission event, taking pre-fission neutrons into account\"\"\"\n\t\treturn (np.mean(self.nuLF+self.nuHF+self.preFissionNu))\n\n\tdef nubarg(self,timeWindow=None,Eth=None):\n\t\t\"\"\"Returns the average gamma multiplicity, per fission fragment\n\n\t\ttimeWindow - logical, if included, returns the multiplicity as a function of time\n\t\t\n\t\tOR\n\t\t\n\t\ttimeWindow - numpy array or list of times at which to calculate the average gamma multiplicity, s\n\n\t\tEth - lower threshold for gamma energy, MeV\n\t\t\"\"\"\n\n\t\tif (timeWindow is not None):\n\t\t\tif (timeWindow == True):\n\t\t\t\ttimes = np.logspace(-9,0,15)\n\t\t\telse:\n\t\t\t\ttimes = timeWindow\n\t\t\tages = self.getGammaAges()\n\t\t\tgE = self.getGammaElab()\n\n\t\t\tif (Eth is not None):\n\t\t\t\tEth = Eth\n\t\t\telse:\n\t\t\t\tEth = 0.\n\t\t\t\t\n\t\t\tphotonAges = []\n\t\t\tphotonEnergies = []\n\t\t\tfor i in range(len(ages)):\n\t\t\t\tphotonAges += ages[i]\n\t\t\t\tphotonEnergies += gE[i]\n\t\t\tphotonAges = np.array(photonAges)\n\t\t\tphotonEnergies = np.array(photonEnergies)\n\n\t\t\tnug = []\n\t\t\tfor i in times:\t\n\t\t\t\tmask = np.logical_and(photonAges<=i,photonEnergies>=Eth)\n\t\t\t\tnug.append(float(len(photonAges[mask])))\n\t\t\tnug = np.array(nug)\n\t\t\tnug = nug/float(self.numberEvents)\n\t\t\treturn (times,nug)\n\n\t\telse:\n\t\t\treturn (np.mean(self.nug))\n\t\n\tdef nubargtot(self,timeWindow=None,Eth=None):\n\t\t\"\"\"Returns the average gamma multiplicity, per fission event\n\n\t\ttimeWindow - logical, if included, returns the multiplicity as a function of time\n\t\t\n\t\tOR\n\t\t\n\t\ttimeWindow - numpy array or list of times at which to calculate the average gamma multiplicity, s\n\n\t\tEth - lower threshold for gamma energies, MeV\n\t\t\"\"\"\n\n\t\tif (timeWindow is not None):\n\t\t\tif (timeWindow == True):\n\t\t\t\ttimes = np.logspace(-9,0,15)\n\t\t\telse:\n\t\t\t\ttimes = timeWindow\n\t\t\tages = self.getGammaAges()\n\t\t\tgE = self.getGammaElab()\n\t\t\tages = ages[::2]+ages[1::2]\n\t\t\tgE = gE[::2]+gE[1::2]\n\n\t\t\tif (Eth is not None):\n\t\t\t\tEth = Eth\n\t\t\telse:\n\t\t\t\tEth = 0.\n\t\t\t\t\n\t\t\tphotonAges = []\n\t\t\tphotonEnergies = []\n\t\t\tfor i in range(len(ages)):\n\t\t\t\tphotonAges += ages[i]\n\t\t\t\tphotonEnergies += gE[i]\n\t\t\tphotonAges = np.array(photonAges)\n\t\t\tphotonEnergies = np.array(photonEnergies)\n\n\t\t\tnug = []\n\t\t\tfor i in times:\t\n\t\t\t\tmask = np.logical_and(photonAges<=i,photonEnergies>=Eth)\n\t\t\t\tnug.append(float(len(photonAges[mask])))\n\t\t\tnug = np.array(nug)\n\t\t\tnug = nug/float(self.numberEvents)\n\t\t\treturn (times,nug)\n\n\t\telse:\n\t\t\treturn (np.mean(self.nugLF+self.nugHF))\n\n\tdef preFissionNubar (self):\n\t\t\"\"\"Returns the average neutron multiplicity of the pre-fission neutrons\"\"\"\n\t\treturn (np.mean(self.preFissionNu))\n\n\t#################################################################\n\t#-- compute the mean value of a list of lists\t\t\t#\n\t#################################################################\n\t\n\tdef meanList (self, listOfValues):\n\t\t\"\"\"Returns the mean of a list of lists (such as neutron energy)\n\n\t\tlistofValues -- list of lists, e.g. neutron energies, gamma energies\n\t\t\"\"\"\n\t\tl=[]\n\t\tfor x in listOfValues:\n\t\t\tl+=x\n\t\treturn (np.mean(np.asarray(l)))\n\n\t#-- mean energies of neutrons in the lab frame\t\t\t\n\tdef meanNeutronElab(self):\n\t\t\"\"\"Returns the mean neutron energy in the lab frame, with pre-fission neutrons\"\"\"\n\t\tnE = self.nElab\n\t\tnEPE = self.preFissionNeutronElab\n\t\tnuPE = self.preFissionNu\n\t\tl = []\n\t\tfor x in nE:\n\t\t\tl += x\t\n\t\tfor i in range(len(nEPE)):\n\t\t\tif (nuPE[i]>0):\n\t\t\t\tl += nEPE[i]\n\t\t\n\t\treturn (np.mean(l))\n\n\tdef meanNeutronElabLF (self):\n\t\t\"\"\"Returns the mean energy of neutrons emitted from the light fragment in the lab frame\"\"\"\n\t\treturn (self.meanList(self.nElabLF))\n\t\n\tdef meanNeutronElabHF (self):\n\t\t\"\"\"Returns the mean energy of neutrons emitted from the heavy fragment in the lab frame\"\"\"\n\t\treturn (self.meanList(self.nElabHF))\n\n\tdef meanNeutronElabFragments (self):\n\t\t\"Returns the mean neutron energy in the lab frame, without pre-fission neutrons\"\"\"\n\t\treturn (self.meanList(self.nElabFragments))\n\n\t#-- mean energies of neutrons in the cm frame\n\n\tdef meanNeutronEcmFragments (self):\n\t\t\"\"\"Returns the mean neutron energy in the center of mass frame, without pre-fission neutrons\"\"\"\n\t\treturn (self.meanList(self.nEcmFragments))\n\n\tdef meanNeutronEcmLF (self):\n\t\t\"\"\"Returns the mean energy of neutrons emitted from the light fragment in the center of mass frame\"\"\"\n\t\treturn (self.meanList(self.nEcmLF))\n\t\n\tdef meanNeutronEcmHF (self):\n\t\t\"\"\"Returns the mean energy of neutrons emitted from the heavy fragment in the center of mass frame\"\"\"\n\t\treturn (self.meanList(self.nEcmHF))\n\n\t#-- mean energies of pre-fission neutrons in the lab frame\n\tdef meanPreFissionNeutronElab(self):\n\t\t\"\"\"Returns the mean energy of pre-fission neutrons in the lab frame\"\"\"\n\t\tnuPE = self.preFissionNu\n\t\tnEPE = self.preFissionNeutronElab\n\t\tl = []\n\t\tfor i in range(len(nEPE)):\n\t\t\tif (nuPE[i]>0):\n\t\t\t\tl += nEPE[i]\n\t\tif (len(l)>0.):\n\t\t\treturn (np.mean(l))\n\t\telse:\n\t\t\treturn(0.0)\n\t\n\t#-- mean energies of gammas in the lab frame\n\tdef meanGammaElab(self):\n\t\t\"\"\"Returns the mean energies of the gammas in the lab frame\"\"\"\n\t\treturn (self.meanList(self.gElab))\n\n\tdef meanGammaElabLF (self):\n\t\t\"\"\"Returns the mean energies of the gammas emitted from the light fragments in the lab frame\"\"\"\n\t\treturn (self.meanList(self.gElabLF))\n\t\n\tdef meanGammaElabHF (self):\n\t\t\"\"\"Returns the mean energies of the gammas emitted from the heavy fragments in the lab frame\"\"\"\n\t\treturn (self.meanList(self.gElabHF))\n\n\t#################################################################\n\t#-- P(nu)\t\t\t\t\t\t\t#\n\t#################################################################\n\n\tdef Pnu (self, Eth=None):\n\t\t\"\"\"Returns a list of probability as a function of neutron multiplicity\n\n\t\tEth -- optional energy threshold, MeV\n\t\t\"\"\"\n\n\t\tif (Eth is not None):\n\t\t\tEth = float(Eth)\n\t\t\tnutot = []\n\t\t\t#nE = self.nElabLF + self.nElabHF + self.preFissionNeutronElab\n\t\t\tnE = self.nElab + self.preFissionNeutronElab\n\t\t\tfor x in nE:\n\t\t\t\tx = np.array(x)\n\t\t\t\tnutot.append(len(x[x>=Eth]))\n\t\t\tnutot = np.array(nutot)\n\t\telse:\n\t\t\t#nutot = self.nuLF + self.nuHF + self.preFissionNu\n\t\t\tnutot = self.nutot +self.preFissionNu\n\n\t\tnumax = np.max(nutot)\n\t\tnu = np.arange(0,numax+1,1)\n\t\tproba = np.zeros(numax+1)\n\t\ts=float(self.numberEvents)\n\t\tfor i in nu:\n\t\t\tproba[i] = len(nutot[nutot==i])/s\n\t\treturn (nu,proba)\n\n\t#################################################################\n\t#-- P(nug)\t\t\t\t\t\t\t#\n\t#################################################################\n\n\tdef Pnug (self, Eth=None):\n\t\t\"\"\"Returns a list of probability as a function of neutron multiplicity\n\n\t\tEth -- optional energy threshold, MeV\n\t\t\"\"\"\n\n\t\tif (Eth is not None):\n\t\t\tEth = float(Eth)\n\t\t\tnugtot = []\n\t\t\tnE = self.gElabLF + self.gElabHF\n\t\t\tfor x in nE:\n\t\t\t\tx = np.array(x)\n\t\t\t\tnugtot.append(len(x[x>=Eth]))\n\t\t\tnugtot = np.array(nugtot)\n\t\telse:\n\t\t\tnugtot = self.nugtot\n\n\t\tnugmax = np.max(nugtot)\n\t\tnug = np.arange(0,nugmax+1,1)\n\t\tproba = np.zeros(nugmax+1)\n\t\ts=float(self.numberEvents)\n\t\tfor i in nug:\n\t\t\tproba[i] = len(nugtot[nugtot==i])/s\n\t\treturn (nug,proba)\n\n\t#################################################################\n\t#-- quantities as a function of the fragment mass\t\t#\n\t#################################################################\n\n\tdef _qA (self, dummy, quantity):\n\t\t\"\"\"Returns two arrays, for the fragment mass and the quantity of interest\n\t\t\n\t\tquantity -- observable of interest as a function of mass, currently supported:\n\t\tnuA -- neutron multiplicity \n\t\tnugA -- gamma multiplicity\n\t\tUA -- excitation energy\n\t\tspinA -- spin\n\t\tTKEA -- total kinetic energy\n\t\t\"\"\"\n\t\txA = np.arange(np.min(self.A),np.max(self.A))\n\t\tnA = np.size(xA)\n\t\tyA = np.zeros(nA)\n\t\tif (quantity=='nuA'):\n\t\t\tq=self.nu\n\t\telif (quantity=='nugA'):\n\t\t\tq=self.nug\n\t\telif (quantity=='UA'):\n\t\t\tq=self.U\n\t\telif (quantity=='TKEA'):\n\t\t\tKE = self.KEpre\n\t\t\tTKE = np.zeros(len(KE))\n\t\t\tTKE[::2] = KE[::2]+KE[1::2]\n\t\t\tTKE[1::2] = TKE[::2]\n\t\t\tq=TKE\n\t\telif (quantity=='spinA'):\n\t\t\tq=self.J\n\t\tfor i in range(nA):\n\t\t\tr=q[self.A==xA[i]]\n\t\t\tif (r.size):\n\t\t\t\tyA[i]=np.mean(r)\n\t\t\telse:\n\t\t\t\tyA[i]=0.0\n\t\treturn (xA, yA)\n\n\tdef nubarA (self):\n\t\t\"\"\"Returns a two-dimensional array for neutron multiplicity as a function of A of format [A,nu]\"\"\"\n\t\treturn (self._qA(self,'nuA'))\n\t\n\tdef nubargA (self):\n\t\t\"\"\"Returns a two-dimensional array for gamma multiplicity as a function of A of format [A,nug]\"\"\"\n\t\treturn (self._qA(self, 'nugA'))\n\t\n\tdef UA (self):\n\t\t\"\"\"Returns a two-dimensional array for excitation energy as a function of A of format [A,U]\"\"\"\n\t\treturn (self._qA(self, 'UA'))\n\t\n\tdef TKEA (self):\n\t\t\"\"\"Returns a two-dimensional array for total kinetic energy as a function of A of format [A,TKE]\"\"\"\n\t\treturn (self._qA(self, 'TKEA'))\n\t\n\tdef spinA (self):\n\t\t\"\"\"Returns a two-dimensional array for spin as a function of A of format [A,J]\"\"\"\n\t\treturn (self._qA(self, 'spinA'))\n\n\t#################################################################\n\t#-- quantities as a function of TKE\t\t\t\t#\n\t#################################################################\n\n\tdef _qTKE (self, dummy, quantity):\n\t\t\"\"\"Returns two arrays, for the fission event total kinetic energy and the quantity of interest\n\t\t\n\t\tquantity -- observable of interest as a function of total kinetic energy, currently supported:\n\t\tnuTKE -- neutron multiplicity per fission event\n\t\tnugTKE -- gamma multiplicity per fission event\n\t\tUTKE -- excitation energy\n\t\tspinTKE -- spin (J)\n\t\t\"\"\"\n\t\txTKE = np.arange(np.min(self.TKEpre),np.max(self.TKEpre))\n\t\tnTKE = np.size(xTKE)\n\t\tyTKE = np.zeros(nTKE)\n\t\tif (quantity=='nuTKE'):\n\t\t\tq=self.nutot\n\t\t\tTKE = self.TKEpre\n\t\telif (quantity=='nugTKE'):\n\t\t\tq=self.nugtot\n\t\t\tTKE = self.TKEpre\n\t\telif (quantity=='UTKE'):\n\t\t\tq=self.U\n\t\t\tTKE1 = cgmf.TKEpre\n\t\t\tTKE = []\n\t\t\tfor x in TKE1:\n\t\t\t\tTKE.append(x)\n\t\t\t\tTKE.append(x)\n\t\t\tTKE = np.array(TKE)\n\t\telif (quantity=='spinTKE'):\n\t\t\tq=self.J\n\t\t\tTKE1 = cgmf.TKEpre\n\t\t\tTKE = []\n\t\t\tfor x in TKE1:\n\t\t\t\tTKE.append(x)\n\t\t\t\tTKE.append(x)\n\t\t\tTKE = np.array(TKE)\n\t\tfor i in range(nTKE-1):\n\t\t\tr=q[np.logical_and(TKE>=xTKE[i],TKE<xTKE[i+1])]\n\t\t\tif (r.size):\n\t\t\t\tyTKE[i]=np.mean(r)\n\t\t\telse:\n\t\t\t\tyTKE[i]=0.0\n\t\treturn (xTKE, yTKE)\n\n\tdef nubarTKE (self):\n\t\t\"\"\"Returns a two-dimensional array for total neutron multiplicity as a function of TKE of format [TKE,nu]\"\"\"\n\t\treturn (self._qTKE(self, 'nuTKE'))\n\n\tdef nubargTKE (self):\n\t\t\"\"\"Returns a two-dimensional array for total gamma multiplicity as a function of TKE of format [TKE,nug]\"\"\"\n\t\treturn (self._qTKE(self, 'nugTKE'))\n\n\tdef UTKE (self):\n\t\t\"\"\"Returns a two-dimensional array for excitation energy as a function of TKE of format [TKE,U]\"\"\"\n\t\treturn (self._qTKE(self, 'UTKE'))\n\n\tdef spinTKE (self):\n\t\t\"\"\"Returns a two-dimensional array for excitation energy as a function of TKE of foramt [TKE,J]\"\"\"\n\t\treturn (self._qTKE(self, 'spinTKE'))\n\n\t#################################################################\n\t#-- Average Prompt Fission Neutron Spectrum\t\t\t#\n\t#################################################################\n\n\tdef pfns (self,Eth=None):\n\t\t\"\"\"Returns two arrays, one for the energy grid, and one for the corresponding prompt fission neutron spectrum\n\t\t\n\t\tEth - neutron threshold energy, MeV \n\t\t\"\"\"\n\t\tif (Eth is not None):\n\t\t\tEth = float(Eth)\n\t\telse:\n\t\t\tEth = 0.0\n\t\t# Outgoing energy grid\n\t\tegrid = np.logspace(-3,2,100)\n\t\tdegrid = egrid[1:]-egrid[:-1]\n\t\tnElab = self.nElabHF + self.nElabLF + self.preFissionNeutronElab\n\t\tl=[]\n\t\tfor x in nElab:\n\t\t\tl+=x\n\t\tl = np.array(l)\n\t\tneutronEnergies=l[l>=Eth]\n\t\thlab, binEdges = np.histogram(neutronEnergies,bins=egrid)\n\t\tnn=np.sum(hlab)\n\t\tbinCenters = 0.5*(binEdges[1:]+binEdges[:-1])\n\t\treturn (binCenters,hlab/degrid/nn)\n\n\t#################################################################\n\t#-- Average Prompt Fission Gamma Spectrum\t\t\t#\n\t#################################################################\n\n\tdef pfgs (self,Eth=None,minTime=None,maxTime=None):\n\t\t\"\"\"Returns two arrays, one for the energy grid, and one for the corresponding prompt fission gamma spectrum\n\t\t\n\t\tEth - optional gamma threshold energy, MeV\n\n\t\tminTime/maxTime - optional lower/upper bound for the time window for the photon emission, s\n\t\t\"\"\"\n\t\tif (Eth is not None):\n\t\t\tEth = float(Eth)\n\t\telse:\n\t\t\tEth = 0.0\n\t\t# Outoing energy grid\n\t\tegrid = np.logspace(-1,1,200)\n\t\tdegrid = egrid[1:]-egrid[:-1]\n\t\tl=[]\n\t\tgElab = self.gElab\n\t\tfor x in gElab:\n\t\t\tl+=x\n\t\tl = np.array(l)\n\n\t\tif (minTime is not None and maxTime is not None):\n\t\t\tages = self.getGammaAges()\n\t\t\ta = []\n\t\t\tfor x in ages:\n\t\t\t\ta+=x\n\t\t\ta = np.array(a)\n\t\t\tmask1 = np.logical_and(a>=minTime,a<=maxTime)\n\t\t\tmask2 = np.logical_and(mask1,l>=Eth)\n\t\t\tgammaEnergies = l[mask2]\n\t\telse:\n\t\t\tgammaEnergies=l[l>=Eth]\n\t\thlab, binEdges = np.histogram(gammaEnergies,bins=egrid)\n\t\tng=np.sum(hlab)\n\t\tbinCenters = 0.5*(binEdges[1:]+binEdges[:-1])\n\t\treturn (binCenters,hlab/degrid/ng*np.mean(self.nugtot))\n\n\t#################################################################\n\t#-- Fission Fragment Angles (relative to beam axis)\t\t#\n\t#################################################################\n\n\tdef FFangles (self,afterEmission=None):\n\t\t\"\"\"Returns cos(theta) of the fission fragments with respect to the z(beam)-axis\n\n\t\tafterEmission - angles after neutron emission (True, default), before neutron emission (False)\n\t\t\"\"\"\n\n\t\tif (afterEmission is not None):\n\t\t\tafterNeutronEmission = afterEmission\n\t\telse:\n\t\t\tafterNeutronEmission = True\n\t\t\n\t\tif (afterNeutronEmission):\n\t\t\tmom = self.getFragmentMomentumPost()\n\t\telse:\n\t\t\tmom = self.getFragmentMomentumPre()\n\n\t\tcosThetaFF = mom[:,2]/np.sum(mom**2,axis=1)**(0.5)\n\t\tcosThetaFF = np.array(cosThetaFF.tolist())\n\n\t\treturn (cosThetaFF)\n\n\t#################################################################\n\t#-- Neutron Angles (relative to beam axis)\t\t\t#\n\t#################################################################\n\n\tdef nangles (self,Eth=None,lab=None,includePrefission=None):\n\t\t\"\"\"Returns cos(theta) of the neutrons with respect to the z(beam)-axis\n\t\tfirst for all neutrons, then from light fragments, then from heavy fragments\n\n\t\tEth - neutron threshold energy, MeV\n\n\t\tlab - True: neutron energy in the lab frame (default), False: in cm\n\n\t\tincludePrefission - include (True, default) or don't include (False) pre-fission neutrons\n\t\t\tonly for the calculations in the lab frame\n\t\t\"\"\"\n\t\t\n\t\tif (Eth is not None):\n\t\t\tEth = float(Eth)\n\t\telse:\n\t\t\tEth = 0.0\n\t\n\t\tif (lab is not None):\n\t\t\tinLabFrame = lab\n\t\telse:\n\t\t\tinLabFrame = True\n\n\t\tif (inLabFrame):\n\t\t\tnE = self.getNeutronElab()\n\t\t\tncos = self.getLabNeutronDircos()\n\t\t\tnuPre = self.getPreFissionNu()\n\t\t\tnPreE = self.getPreFissionNeutronElab()\n\t\t\tnPrecos = self.getPreFissionNeutronDircos()\n\t\t\tif (includePrefission is not None):\n\t\t\t\tincludePreFissionNeutrons = includePrefission\n\t\t\telse:\n\t\t\t\tincludePreFissionNeutrons = True\n\t\telse:\n\t\t\tnE = self.getNeutronEcm()\n\t\t\tncos = self.getcmNeutronDircos()\n\t\t\tincludePreFissionNeutrons = False\n\t\t\t\n\n\t\tncosAll = []\n\t\tncosLight = []\n\t\tncosHeavy = []\n\t\tnEAll = []\n\t\tnELight = []\n\t\tnEHeavy = []\n\n\t\tEtemp = nE[::2]\n\t\tcostemp = ncos[::2]\n\t\tfor i in range(len(costemp)):\n\t\t\tnELight += Etemp[i]\n\t\t\tncosLight += costemp[i]\n\t\t\tnEAll += Etemp[i]\n\t\t\tncosAll += costemp[i]\n\n\t\tEtemp = nE[1::2]\n\t\tcostemp = ncos[1::2]\n\t\tfor i in range(len(costemp)):\n\t\t\tnEHeavy += Etemp[i]\n\t\t\tncosHeavy += costemp[i]\n\t\t\tnEAll += Etemp[i]\n\t\t\tncosAll += costemp[i]\n\n\t\t# have to also include pre-fission neutrons which are seperate now\n\t\tif (includePreFissionNeutrons):\n\t\t\tfor i in range(len(nuPre)):\n\t\t\t\tif (nuPre[i]>0):\n\t\t\t\t\tnEAll += nPreE[i]\n\t\t\t\t\tncosAll += nPrecos[i]\n\n\t\tnELight = np.array(nELight)\n\t\tnEHeavy = np.array(nEHeavy)\n\t\tnEAll = np.array(nEAll)\n\t\tncosLight = np.array(ncosLight)\n\t\tncosHeavy = np.array(ncosHeavy)\n\t\tncosAll = np.array(ncosAll)\n\n\t\tncosAll = ncosAll[nEAll>=Eth][:,2]\n\t\tncosLight = ncosLight[nELight>=Eth][:,2]\n\t\tncosHeavy = ncosHeavy[nEHeavy>=Eth][:,2]\n\n\t\treturn (ncosAll,ncosLight,ncosHeavy)\n\n\t#################################################################\n\t#-- Neutron-Fragment Angles \t\t\t\t\t#\n\t#################################################################\n\n\tdef nFangles (self,Eth=None,afterEmission=None,includePrefission=None):\n\t\t\"\"\"Returns cos(theta) between the neutrons and the fragments\n\n\t\tEth - neutron threshold energy, MeV\n\t\t\n\t\tafterEmission - angles after neutron emission (True, default), before neutron emission (False)\n\n\t\tincludePrefission - include (True, default) or don't include (False) pre-fission neutrons\n\t\t\tonly for the calculations in the lab frame\n\t\t\"\"\"\n\t\t\n\t\tif (Eth is not None):\n\t\t\tEth = float(Eth)\n\t\telse:\n\t\t\tEth = 0.0\n\n\t\tnE = self.getNeutronElab()\n\t\tncos = self.getLabNeutronDircos()\n\t\tnuPre = self.getPreFissionNu()\n\t\tnPreE = self.getPreFissionNeutronElab()\n\t\tnPrecos = self.getPreFissionNeutronDircos()\n\t\tif (includePrefission is not None):\n\t\t\tincludePreFissionNeutrons = includePrefission\n\t\telse:\n\t\t\tincludePreFissionNeutrons = True\n\n\t\tif (afterEmission is not None):\n\t\t\tafterNeutronEmission = afterEmission\n\t\telse:\n\t\t\tafterNeutronEmission = True\n\t\t\n\t\tif (afterNeutronEmission):\n\t\t\tmom = self.getFragmentMomentumPost()\n\t\telse:\n\t\t\tmom = self.getFragmentMomentumPre()\n\n\t\tmom = mom[::2] # want angles with respect to the light fragments\n\n\t\tcosThetaFF = ((mom.T/np.sum(mom**2,axis=1)**(0.5)).T).tolist()\n\t\tcosThetaFF = np.array(cosThetaFF)\n\t\t\t\n\n\t\tncosAll = []\n\t\tncosLight = []\n\t\tncosHeavy = []\n\t\tnEAll = []\n\t\tnELight = []\n\t\tnEHeavy = []\n\t\tFcosLight = []\n\t\tFcosHeavy = []\n\t\tFcosAll = []\n\n\t\tEtemp = nE[::2]\n\t\tcostemp = ncos[::2]\n\t\tfor i in range(len(costemp)):\n\t\t\tnELight += Etemp[i]\n\t\t\tncosLight += costemp[i]\n\t\t\tnEAll += Etemp[i]\n\t\t\tncosAll += costemp[i]\n\t\t\tFcosLight += [cosThetaFF[i]]*len(costemp[i])\n\t\t\tFcosAll += [cosThetaFF[i]]*len(costemp[i])\n\n\t\tEtemp = nE[1::2]\n\t\tcostemp = ncos[1::2]\n\t\tfor i in range(len(costemp)):\n\t\t\tnEHeavy += Etemp[i]\n\t\t\tncosHeavy += costemp[i]\n\t\t\tnEAll += Etemp[i]\n\t\t\tncosAll += costemp[i]\n\t\t\tFcosHeavy += [cosThetaFF[i]]*len(costemp[i])\n\t\t\tFcosAll += [cosThetaFF[i]]*len(costemp[i])\n\n\t\t# have to also include pre-fission neutrons which are seperate now\n\t\tif (includePreFissionNeutrons):\n\t\t\tfor i in range(len(nuPre)):\n\t\t\t\tif (nuPre[i]>0):\n\t\t\t\t\tnEAll += nPreE[i]\n\t\t\t\t\tncosAll += nPrecos[i]\n\t\t\t\t\tFcosAll += [cosThetaFF[i]]*len(nPrecos[i])\n\n\t\tnELight = np.array(nELight)\n\t\tnEHeavy = np.array(nEHeavy)\n\t\tnEAll = np.array(nEAll)\n\t\tncosLight = np.array(ncosLight)\n\t\tncosHeavy = np.array(ncosHeavy)\n\t\tncosAll = np.array(ncosAll)\n\t\tFcosLight = np.array(FcosLight)\n\t\tFcosHeavy = np.array(FcosHeavy)\n\t\tFcosAll = np.array(FcosAll)\n\n\t\tnFcosAll = ncosAll[nEAll>=Eth]*FcosAll[nEAll>=Eth]\n\t\tnFcosAll = np.sum(nFcosAll,axis=1)\n\t\tnFcosLight = ncosLight[nELight>=Eth]*FcosLight[nELight>=Eth]\n\t\tnFcosLight = np.sum(nFcosLight,axis=1)\n\t\tnFcosHeavy = ncosHeavy[nEHeavy>=Eth]*FcosHeavy[nEHeavy>=Eth]\n\t\tnFcosHeavy = np.sum(nFcosHeavy,axis=1)\n\n\t\treturn (nFcosAll,nFcosLight,nFcosHeavy)\t\n\n\t#################################################################\n\t#-- Angular distribution of of n-n opening angle\t\t#\n\t#################################################################\n\n\tdef nnangles (self,**keyword_parameters):\n\t\t\"\"\"Returns an array of the cosine of the angle between each neutron pair of neutrons emitted from the same fragment, first for the light, then heavy, then all fragments\n\n\t\tlab -- neutrons in the lab frame\n\t\t\n\t\tcm -- neutrons in the center of mass frame\n\t\t\"\"\"\n\t\tnLF = self.nuLF\n\t\tnHF = self.nuHF\n\t\tncos = self.labNeutronDircos\n\t\tif ('lab' in keyword_parameters):\n\t\t\tncos = self.labNeutronDircos\n\t\tif ('cm' in keyword_parameters):\n\t\t\tncos = self.cmNeutronDircos\n\n\t\tnncosLF = []\n\t\tnncosHF = []\n\t\tnncosAll = []\n\n\t\ttempcos = 0.0\n\n\t\tc = 0\n\t\tfor i in range(len(nLF)):\n\t\t\tfor j in range(nLF[i]):\n\t\t\t\tfor k in range(j,nLF[i]):\n\t\t\t\t\ttempcos = ncos[c][j][0]*ncos[c][k][0]+ncos[c][j][1]*ncos[c][k][1]+ncos[c][j][2]*ncos[c][k][2]\n\t\t\t\t\tnncosLF.append(tempcos)\n\t\t\t\t\tnncosAll.append(tempcos)\n\t\t\tc=c+1\n\t\t\tfor j in range(nHF[i]):\n\t\t\t\tfor k in range(j,nHF[i]):\n\t\t\t\t\ttempcos = ncos[c][j][0]*ncos[c][k][0]+ncos[c][j][1]*ncos[c][k][1]+ncos[c][j][2]*ncos[c][k][2]\n\t\t\t\t\tnncosHF.append(tempcos)\n\t\t\t\t\tnncosAll.append(tempcos)\n\t\t\tc=c+1\n\n\t\treturn (nncosLF,nncosHF,nncosAll)\n\n\t#################################################################\n\t#-- Calculates fragment distribution for a gamma-ray energy\t#\n\t#################################################################\n\tdef gammaSpec(self,Egamma,dEgamma,post=True):\n\n\t\t\"\"\"Calculates the distribution of fission fragments (or products), given a gamma-ray energy and energy resolution\n\n\t\tEgamma - array of gamma-ray energies (in lab frame) [MeV]\n\t\t\n\t\tdEgamma - array of gamma-ray energy resolutions [MeV]\n\t\t\n\t\tpost - True (False) indicates that post- (pre-) neutron emission fission products (fragments) will be returned\n\t\t\"\"\"\n\n\t\t# Create the list of Z,A pairs\n\t\tZlist = []\n\t\tAlist = []\n\n\t\t# Check if post is True or False\n\t\tif post:\n\t\t\tmultiplier = 1\n\t\telse:\n\t\t\tmultiplier = 0\n\n\t\t# First validate the gamma-ray energies and their resolutions\n\t\teglist = np.array(Egamma)\n\t\tdeglist = np.array(dEgamma)\n\n\t\tif np.any(eglist<0.) or np.any(dEgamma<0.):\n\t\t\tprint(\"Gamma-ray energies and/or resolutions should be positive...\")\n\t\t\treturn\n\n\t\tif not np.shape(eglist) == np.shape(deglist):\n\t\t\tprint(\"Gamma-ray energies and resolutions must be of same shape...\")\n\t\t\treturn\n\n\t\tif np.shape(eglist)==():\n\t\t\teglist = np.array([eglist])\n\t\t\tdeglist = np.array([deglist])\n\n\t\t# Next, go through the gamma-ray emissions for each event\n\t\tfor n,gammas in enumerate(self.gElab):\n\n\t\t\t# Next, check if all of the gamma-rays specified in eglist (within deglist window) are found in gamma rays emitted\n\t\t\tlog = np.zeros(len(eglist)).astype(bool)\n\t\t\tfor m,eg in enumerate(eglist):\n\n\t\t\t\t# Change the log to True for a given gamma-ray window\n\t\t\t\tif np.any([g <= eg + deglist[m] and g >= eg - deglist[m] for g in gammas]):\n\t\t\t\t\tlog[m] = True\n\n\t\t\t# If all gamma-ray gates are satisfied then add this event\n\t\t\tif np.all(log):\n\t\t\t\tZlist.append(self.Z[n])\n\t\t\t\tAlist.append(self.A[n]-multiplier*self.nu[n])\n\n\t\tZlist = np.array(Zlist)\n\t\tAlist = np.array(Alist)\n\t\treturn np.column_stack((Zlist,Alist))\n\n\t#################################################################\n\t#-- Calculate gamma multiplicity as a function of time \t\t#\n\t#################################################################\n\n\tdef gammaMultiplicity(self,Eth=None,Afragment=None,Zfragment=None,minTime=None,maxTime=None):\n\t\t\"\"\"Returns the gamma-ray multiplicity as a function of time since the fission event for a specific isotope\n\n\t\tAfragment - mass of a given isotope\n\t\t\n\t\tZfragment - charge of a given isotope\n\t\t\n\t\tIf both Afragment and Zfragment are given, the multiplicity is calculated for that isotope (default all isotopes)\n\n\t\tEth - threshold gamma-ray energy for the calculation, MeV\n\n\t\tminTime/maxTime - define the window over which the number of gamma rays is counted, s\n\t\t\"\"\"\n\t\n\t\tif (maxTime is not None and minTime is not None):\n\t\t\ttMin = minTime\n\t\t\ttMax = maxTime\n\t\t\tnSteps = 50*np.abs(np.log10(tMax)-np.log10(tMin))+1\n\t\telse:\n\t\t\ttMin = 1e-8\n\t\t\ttMax = 100\n\t\t\tnSteps = 501\n\t\ttimeBins = np.linspace(tMin,tMax,int(nSteps))\n\t\tbinCenters = 0.5*(timeBins[:-1]+timeBins[1:])\n\n\t\tif (Eth is not None):\n\t\t\tEth = float(Eth)\n\t\telse:\n\t\t\tEth = 0.0\n\n\t\tAall = self.getA()\n\t\tZall = self.getZ()\n\t\tnu = self.getNu()\n\t\tAall = Aall - nu\n\n\t\tphotonAges = []\n\t\tphotonEnergies = []\n\t\tages = self.getGammaAges()\n\t\tgE = self.getGammaElab()\n\n\t\tif (Afragment is not None and Zfragment is not None):\n\t\t\tA = Afragment\n\t\t\tZ = Zfragment\n\t\t\tmask = np.logical_and(Aall==A,Zall==Z)\n\t\t\tfor i in range(len(mask)):\n\t\t\t\tif (mask[i]):\n\t\t\t\t\tphotonAges += ages[i]\n\t\t\t\t\tphotonEnergies += gE[i]\n\t\t\t\t\n\t\telse:\n\t\t\t# we calculate the multiplicity from all of the fission fragments\n\t\t\tfor i in range(len(ages)):\n\t\t\t\tphotonAges += ages[i]\n\t\t\t\tphotonEnergies += gE[i]\n\n\t\tphotonAges = np.array(photonAges)\n\t\tphotonEnergies = np.array(photonEnergies)\n\t\tphotonAges = photonAges[photonEnergies>=Eth]\n\n\t\tgMultiplicity,binEdges = np.histogram(photonAges,bins=timeBins)\n\n\t\treturn (binCenters,gMultiplicity)\n\n\t#################################################################\n\t#-- Calculate the isomeric ratio of a given state \t\t#\n\t#################################################################\n\n\tdef isomericRatio(self,thresholdTime,A,Z,Jm,Jgs):\n\t\t\"\"\"Calculates the isomeric ratio for the given state, relative to the ground state\n\t\t\n\t\tthresholdTime - time to separate isomeric state from ground state, s\n\t\t\n\t\tA - mass of fragment of interest\n\t\t\n\t\tZ - charge of fragment of interest\n\t\t\n\t\tJm - spin of the isomeric state\n\t\t\n\t\tJgs - spin of the ground state\n\t\t\"\"\"\n\t\t\n\t\tAall = self.getA()\n\t\tZall = self.getZ()\n\t\tnu = self.getNu()\n\t\tAall = Aall - nu\n\t\tages = self.getGammaAges()\n\t\tmask = np.logical_and(Aall==A,Zall==Z)\n\t\t\n\t\tphotonAges = []\n\t\tnIsomer = 0\n\t\tnGroundState = 0\n\n\t\tfor i in range(len(ages)):\n\t\t\tif mask[i]:\n\t\t\t\ta = np.array(ages[i])\n\t\t\t\tif (len(a[a>=thresholdTime])>0):\n\t\t\t\t\tnIsomer += 1\n\t\t\t\telse:\n\t\t\t\t\tnGroundState += 1\n\n\t\tr = float(nIsomer)/(nIsomer+nGroundState)\n\n\t\tif (Jm>Jgs):\n\t\t\treturn (r)\n\t\telse:\n\t\t\treturn (1.-r)\n\n\n\t#################################################################\n\t#-- Summary Table for ipython notebook\t\t\t\t#\n\t#################################################################\n\n\tdef summaryTable (self):\n\t\t\"\"\"Returns a table for use in an ipython notebook which gives summary information about the CGMF simulation (for the fragments, neutrons, and gammas)\"\"\"\n\n\t\ttable = ListTable()\n\n\t\ttable.append(['','All Fragments','Light Fragments','Heavy Fragments','Pre-Fission', 'Total'])\n\n\t\t#-- A, Z, TXE, TKE, J, U, pi\n\t\ttable.append(['A',\"{0:5.2f}\".format(np.mean(self.A)),\"{0:5.2f}\".format(np.mean(self.Al)),\"{0:5.2f}\".format(np.mean(self.Ah))])\n\t\ttable.append(['Z',\"{0:5.2f}\".format(np.mean(self.Z)),\"{0:5.2f}\".format(np.mean(self.Zl)),\"{0:5.2f}\".format(np.mean(self.Zh))])\n\t\ttable.append(['TXE / U (MeV)',\"{0:5.2f}\".format(np.mean(self.TXE)),\"{0:5.2f}\".format(np.mean(self.Ul)),\"{0:5.2f}\".format(np.mean(self.Uh))])\n\t\ttable.append(['TKE / KE (MeV)',\"{0:5.2f}\".format(np.mean(self.TKEpre)),\"{0:5.2f}\".format(np.mean(self.KEl)),\"{0:5.2f}\".format(np.mean(self.KEh))])\n\t\ttable.append(['J ($\\hbar$)',\"{0:5.2f}\".format(np.mean(self.J)),\"{0:5.2f}\".format(np.mean(self.Jl)),\"{0:5.2f}\".format(np.mean(self.Jh))])\n\t\ttable.append(['parity',\"{0:5.2f}\".format(np.mean(self.P)),\"{0:5.2f}\".format(np.mean(self.Pl)),\"{0:5.2f}\".format(np.mean(self.Ph))])\n\n\t\t#-- Neutrons\n\t\ttable.append([r'$\\langle \\nu\\rangle$',\"{0:.3f}\".format(np.mean(self.nuLF+self.nuHF)),\"{0:.3f}\".format(np.mean(self.nuLF)),\"{0:.3f}\".\n\t\t\tformat(np.mean(self.nuHF)),\"{0:.3f}\".format(np.mean(self.preFissionNu)),\"{0:.3f}\".format(np.mean(self.nutot+self.preFissionNu))])\t\t\n\t\ttable.append([r'$\\langle \\epsilon_n^{cm}\\rangle$ (MeV)', \"{0:.3f}\".format(self.meanNeutronEcmFragments()), \n\t\t\t\"{0:.3f}\".format(self.meanNeutronEcmLF()),\"{0:.3f}\".format(self.meanNeutronEcmHF())])\n\t\ttable.append([r'$\\langle E_n^{lab}\\rangle$ (MeV)',\"{0:.3f}\".format(self.meanNeutronElabFragments()),\n\t\t\t\"{0:.3f}\".format(self.meanNeutronElabLF()),\"{0:.3f}\".format(self.meanNeutronElabHF()),\n\t\t\t\"{0:.3f}\".format(self.meanPreFissionNeutronElab()),\"{0:.3f}\".format(self.meanNeutronElab())])\n\n\t\t#-- Gammas\n\t\ttable.append([r'$\\langle \\nu_\\gamma\\rangle$',\"{0:5.2f}\".format(np.mean(self.nugtot)),\n\t\t\t\"{0:5.2f}\".format(np.mean(self.nugLF)),\"{0:5.2f}\".format(np.mean(self.nugHF))])\n\t\ttable.append([r'$\\langle E_\\gamma^{lab}\\rangle$ (MeV)',\"{0:5.2f}\".format(self.meanGammaElab()),\n\t\t\t\"{0:5.2f}\".format(self.meanGammaElabLF()),\"{0:5.2f}\".format(self.meanGammaElabHF())])\n\n\t\treturn table\n\n\nclass ListTable(list):\n\t\"\"\" Overridden list class which takes a 2-dimensional list of\n\t\tthe form [[1,2,3],[4,5,6]], and renders an HTML Table in\n\t\tIPython Notebook. \"\"\"\n\t\t\t\n\tdef _repr_html_(self):\n\t\thtml = [\"<table width=60%>\"]\n\t\tfor row in self:\n\t\t\thtml.append(\"<tr>\")\n\t\t\n\t\t\tfor col in row:\n\t\t\t\thtml.append(\"<td>{0}</td>\".format(col))\n\t\t\t\n\t\t\thtml.append(\"</tr>\")\n\t\thtml.append(\"</center>\")\n\t\treturn ''.join(html)\n\n", "meta": {"hexsha": "948d61ca93e6c1bc17438581a66c2684c9478bf7", "size": 46413, "ext": "py", "lang": "Python", "max_stars_repo_path": "tools/CGMFtk/histories.py", "max_stars_repo_name": "moatazharb/CGMF", "max_stars_repo_head_hexsha": "802a370c03003982ebfad47591f0007b82214ef5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2021-01-15T15:49:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:30:34.000Z", "max_issues_repo_path": "tools/CGMFtk/histories.py", "max_issues_repo_name": "moatazharb/CGMF", "max_issues_repo_head_hexsha": "802a370c03003982ebfad47591f0007b82214ef5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-29T20:40:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-29T21:18:26.000Z", "max_forks_repo_path": "tools/CGMFtk/histories.py", "max_forks_repo_name": "moatazharb/CGMF", "max_forks_repo_head_hexsha": "802a370c03003982ebfad47591f0007b82214ef5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-11-02T16:00:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T18:49:47.000Z", "avg_line_length": 30.676140119, "max_line_length": 323, "alphanum_fraction": 0.6388511839, "include": true, "reason": "import numpy", "num_tokens": 14021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.15847991475286058}}
{"text": "\nfrom __future__ import print_function\n\nimport os\nimport re\nimport concurrent.futures\n\nimport numpy as np\nimport netCDF4\nfrom mdtraj.geometry import _geometry\nfrom mdtraj.geometry.sasa import _ATOMIC_RADII\n\ntry:\n    from bpmfwfft import IO\n    try:        \n        from bpmfwfft.util import c_is_in_grid, cdistance, c_containing_cube\n        from bpmfwfft.util import c_cal_charge_grid_new\n        from bpmfwfft.util import c_cal_potential_grid\n        from bpmfwfft.util import c_cal_lig_sasa_grid\n        from bpmfwfft.util import c_cal_lig_sasa_grids\n    except:\n        from util import c_is_in_grid, cdistance, c_containing_cube\n        from util import c_cal_charge_grid_new\n        from util import c_cal_potential_grid\n        from util import c_cal_lig_sasa_grid\n        from util import c_cal_lig_sasa_grids\n\nexcept:\n    import IO\n    from util import c_is_in_grid, cdistance, c_containing_cube\n    from util import c_cal_charge_grid_new\n    from util import c_cal_potential_grid\n    from util import c_cal_lig_sasa_grid\n    from util import c_cal_lig_sasa_grids\n\ndef process_potential_grid_function(\n        name,\n        crd,\n        origin_crd,\n        grid_spacing,\n        grid_counts,\n        charges,\n        prmtop_ljsigma,\n        molecule_sasa,\n        rho,\n        sasa_core_scaling,\n        sasa_surface_scaling,\n        sasa_grid\n):\n    \"\"\"\n    gets called by cal_potential_grid and assigned to a new python process\n    use cython to calculate electrostatic, LJa, LJr, SASAr, and SASAi grids\n    and save them to nc file\n    \"\"\"\n    print(\"calculating Receptor %s grid\" % name)\n    grid_x = np.linspace(\n        origin_crd[0],\n        origin_crd[0] + ((grid_counts[0]-1) * grid_spacing[0]),\n        num=grid_counts[0]\n    )\n    grid_y = np.linspace(\n        origin_crd[1],\n        origin_crd[1] + ((grid_counts[1] - 1) * grid_spacing[1]),\n        num=grid_counts[1]\n    )\n    grid_z = np.linspace(\n        origin_crd[2],\n        origin_crd[2] + ((grid_counts[2] - 1) * grid_spacing[2]),\n        num=grid_counts[2]\n    )\n    uper_most_corner_crd = origin_crd + (grid_counts - 1.) * grid_spacing\n    uper_most_corner = (grid_counts - 1)\n\n    grid = c_cal_potential_grid(name, crd,\n                                grid_x, grid_y, grid_z,\n                                origin_crd, uper_most_corner_crd, uper_most_corner,\n                                grid_spacing, grid_counts,\n                                charges, prmtop_ljsigma, molecule_sasa, rho,\n                                sasa_core_scaling, sasa_surface_scaling, sasa_grid)\n    return grid\n\ndef process_charge_grid_function(\n        name,\n        crd,\n        origin_crd,\n        grid_spacing,\n        eight_corner_shifts,\n        six_corner_shifts,\n        grid_counts,\n        charges,\n        prmtop_ljsigma,\n        molecule_sasa,\n        sasa_grid\n):\n    \"\"\"\n    gets called by cal_potential_grid and assigned to a new python process\n    use cython to calculate electrostatic, LJa, LJr, SASAr, and SASAi grids\n    and save them to nc file\n    \"\"\"\n    print(\"calculating Ligand %s grid\" % name)\n    grid_x = np.linspace(\n        origin_crd[0],\n        origin_crd[0] + ((grid_counts[0]-1) * grid_spacing[0]),\n        num=grid_counts[0]\n    )\n    grid_y = np.linspace(\n        origin_crd[1],\n        origin_crd[1] + ((grid_counts[1] - 1) * grid_spacing[1]),\n        num=grid_counts[1]\n    )\n    grid_z = np.linspace(\n        origin_crd[2],\n        origin_crd[2] + ((grid_counts[2] - 1) * grid_spacing[2]),\n        num=grid_counts[2]\n    )\n    uper_most_corner_crd = origin_crd + (grid_counts - 1.) * grid_spacing\n    uper_most_corner = (grid_counts - 1)\n\n    grid = c_cal_charge_grid_new(name, crd,\n                                grid_x, grid_y, grid_z,\n                                origin_crd, uper_most_corner_crd, uper_most_corner,\n                                grid_spacing, eight_corner_shifts, six_corner_shifts,\n                                grid_counts, charges, prmtop_ljsigma, molecule_sasa, sasa_grid)\n\n    return grid\n\ndef is_nc_grid_good(nc_grid_file):\n    \"\"\"\n    :param nc_grid_file: name of nc file\n    :return: bool\n    \"\"\"\n    if not os.path.exists(nc_grid_file):\n        return False\n\n    if os.path.getsize(nc_grid_file) == 0:\n        return False\n\n    nc_handle = netCDF4.Dataset(nc_grid_file, \"r\")\n    nc_keys = nc_handle.variables.keys()\n    grid_keys = Grid().get_allowed_keys()\n    for key in grid_keys:\n        if key not in nc_keys:\n            return False\n    return True\n\n\nclass Grid(object):\n    \"\"\"\n    an abstract class that defines some common methods and data attributes\n    working implementations are in LigGrid and RecGrid below\n    \"\"\"\n    def __init__(self):\n        self._grid = {}\n        # self._grid_func_names   = (\"SASAi\", \"electrostatic\", \"LJr\", \"LJa\", \"SASAr\")  # calculate all grids\n        # self._grid_func_names = (\"SASAi\", \"SASAr\")  # uncomment to only calculate SASA grids\n        self._grid_func_names = ()  # don't calculate any grids, but make grid objects for testing\n        cartesian_axes  = (\"x\", \"y\", \"z\")\n        box_dim_names   = (\"d0\", \"d1\", \"d2\")\n        others          = (\"spacing\", \"counts\", \"origin\", \"lj_sigma_scaling_factor\", \"sasa_core_scaling\",\n                           \"sasa_surface_scaling\")\n        self._grid_allowed_keys = self._grid_func_names + cartesian_axes + box_dim_names + others\n\n        self._eight_corner_shifts = [np.array([i,j,k], dtype=int) for i in range(2) for j in range(2) for k in range(2)]\n        self._eight_corner_shifts = np.array(self._eight_corner_shifts, dtype=int)\n\n        self._six_corner_shifts = self._get_six_corner_shifts()\n\n        self._nearest_neighbor_shifts = self._get_nearest_neighbor_shifts()\n\n    def _get_six_corner_shifts(self):\n        six_corner_shifts = []\n        for i in [-1, 1]:\n            six_corner_shifts.append(np.array([i,0,0], dtype=int))\n            six_corner_shifts.append(np.array([0,i,0], dtype=int))\n            six_corner_shifts.append(np.array([0,0,i], dtype=int))\n        return np.array(six_corner_shifts, dtype=int)\n\n    def _get_nearest_neighbor_shifts(self):\n        nearest_neighbor_shifts = []\n        for i in [-1, 1]:\n            nearest_neighbor_shifts.append(np.array([i, 0, 0], dtype=int))\n            nearest_neighbor_shifts.append(np.array([0, i, 0], dtype=int))\n            nearest_neighbor_shifts.append(np.array([0, 0, i], dtype=int))\n            nearest_neighbor_shifts.append(np.array([0, i, i], dtype=int))\n            nearest_neighbor_shifts.append(np.array([i, 0, i], dtype=int))\n            nearest_neighbor_shifts.append(np.array([i, i, 0], dtype=int))\n        return np.array(nearest_neighbor_shifts, dtype=int)\n    \n    def _set_grid_key_value(self, key, value):\n        \"\"\"\n        key:    str\n        value:  any object\n        \"\"\"\n        assert key in self._grid_allowed_keys, key + \" is not an allowed key\"\n\n        if key not in self._grid_func_names:\n            print(value)\n        self._grid[key] = value\n        return None\n    \n    def _load_prmtop(self, prmtop_file_name, lj_sigma_scaling_factor):\n        \"\"\"\n        :param prmtop_file_name: str, name of AMBER prmtop file\n        :param lj_sigma_scaling_factor: float, must have value in [0.5, 1.0].\n        It is stored in self._grid[\"lj_sigma_scaling_factor\"] as\n        a array of shape (1,) for reason of saving to nc file.\n         Experience says that 0.8 is good for protein-ligand calculations.\n        :return: None\n        \"\"\"\n        assert 0.5 <= lj_sigma_scaling_factor <= 1.0, \"lj_sigma_scaling_factor is out of allowed range\"\n        self._prmtop = IO.PrmtopLoad(prmtop_file_name).get_parm_for_grid_calculation()\n        self._prmtop[\"LJ_SIGMA\"] *= lj_sigma_scaling_factor\n        self._set_grid_key_value(\"lj_sigma_scaling_factor\", np.array([lj_sigma_scaling_factor], dtype=float))\n        return None\n    \n    def _load_inpcrd(self, inpcrd_file_name):\n        self._crd = IO.InpcrdLoad(inpcrd_file_name).get_coordinates()\n        natoms = self._prmtop[\"POINTERS\"][\"NATOM\"]\n        if (self._crd.shape[0] != natoms) or (self._crd.shape[1] != 3):\n            raise RuntimeError(\"coordinates in %s has wrong shape\"%inpcrd_file_name)\n        return None\n    \n    def _move_molecule_to(self, location):\n        \"\"\"\n        Move the center of mass of the molecule to location.\n        location:   3-array.\n        This method affects self._crd.\n        \"\"\"\n        assert len(location) == 3, \"location must have len 3\"\n        displacement = np.array(location, dtype=float) - self._get_molecule_center_of_mass()\n        for atom_ind in range(len(self._crd)):\n            self._crd[atom_ind] += displacement\n        return None\n    \n    def _get_molecule_center_of_mass(self):\n        \"\"\"\n        return the center of mass of self._crd\n        \"\"\"\n        center_of_mass = np.zeros([3], dtype=float)\n        masses = self._prmtop[\"MASS\"]\n        for atom_ind in range(len(self._crd)):\n            center_of_mass += masses[atom_ind] * self._crd[atom_ind]\n        total_mass = masses.sum()\n        if total_mass == 0:\n            raise RuntimeError(\"zero total mass\")\n        return center_of_mass / total_mass\n\n    def _get_molecule_sasa(self, probe_radius, n_sphere_points):\n        \"\"\"\n        return the per atom SASA of the target molecule\n        \"\"\"\n        xyz = self._crd\n        xyz = np.expand_dims(xyz, 0)\n        # convert coordinates to nanometers for mdtraj\n        xyz = xyz.astype(np.float32)/10.\n\n        atom_radii = []\n        for atom_label in self._prmtop[\"PDB_TEMPLATE\"][\"ATOM_NAME\"]:\n            try:\n                atom_radii.append(_ATOMIC_RADII[str(atom_label).split(\"-\", 0)[0][0]])\n            except:\n                atom_radii.append(_ATOMIC_RADII[str(atom_label).split(\"-\", 0)[0:1][0].title()])\n        radii = np.array(atom_radii, np.float32) + probe_radius\n        dim1 = xyz.shape[1]\n        atom_mapping = np.arange(dim1, dtype=np.int32)\n        out = np.zeros((xyz.shape[0], dim1), dtype=np.float32)\n        _geometry._sasa(xyz, radii, int(n_sphere_points), atom_mapping, out)\n\n        return out\n\n    def _get_corner_crd(self, corner):\n        \"\"\"\n        corner: 3-array integers\n        \"\"\"\n        i, j, k = corner\n        return np.array([self._grid[\"x\"][i], self._grid[\"y\"][j], self._grid[\"z\"][k]] , dtype=float)\n    \n    def _get_uper_most_corner(self):\n        return np.array(self._grid[\"counts\"] - 1, dtype=int)\n    \n    def _get_uper_most_corner_crd(self):\n        uper_most_corner = self._get_uper_most_corner()\n        return self._get_corner_crd(uper_most_corner)\n    \n    def _get_origin_crd(self):\n        return self._get_corner_crd([0,0,0])\n\n    def _initialize_convenient_para(self):\n        self._origin_crd           = self._get_origin_crd()\n        self._uper_most_corner_crd = self._get_uper_most_corner_crd()\n        self._uper_most_corner     = self._get_uper_most_corner()\n        self._spacing              = np.array([self._grid[\"d%d\"%i][i] for i in range(3)], dtype=float)\n        return None\n\n    def _is_in_grid(self, atom_coordinate):\n        \"\"\"\n        in grid means atom_coordinate >= origin_crd and atom_coordinate < uper_most_corner_crd\n        :param atom_coordinate: 3-array of float\n        :return: bool\n        \"\"\"\n        return c_is_in_grid(atom_coordinate, self._origin_crd, self._uper_most_corner_crd)\n    \n    def _distance(self, corner, atom_coordinate):\n        \"\"\"\n        corner: 3-array int\n        atom_coordinate:    3-array of float\n        return distance from corner to atom coordinate\n        \"\"\"\n        corner_crd = self._get_corner_crd(corner)\n        return cdistance(atom_coordinate, corner_crd)\n    \n    def _containing_cube(self, atom_coordinate):\n        eight_corners, nearest_ind, furthest_ind = c_containing_cube(atom_coordinate, self._origin_crd,\n                                                                     self._uper_most_corner_crd,\n                                                                     self._spacing, self._eight_corner_shifts,\n                                                                     self._grid[\"x\"], self._grid[\"y\"], self._grid[\"z\"])\n        return eight_corners, nearest_ind, furthest_ind\n    \n    def _is_row_in_matrix(self, row, matrix):\n        for r in matrix:\n            if (row == r).all():\n                return True\n        return False\n\n    def get_grid_func_names(self):\n        return self._grid_func_names\n    \n    def get_grids(self):\n        return self._grid\n    \n    def get_crd(self):\n        return self._crd\n    \n    def get_prmtop(self):\n        return self._prmtop\n    \n    def get_charges(self):\n        charges = dict()\n        for key in [\"CHARGE_E_UNIT\", \"R_LJ_CHARGE\", \"A_LJ_CHARGE\"]:\n            charges[key] = self._prmtop[key]\n        return charges\n\n    def get_natoms(self):\n        return self._prmtop[\"POINTERS\"][\"NATOM\"]\n\n    def get_allowed_keys(self):\n        return self._grid_allowed_keys\n\n\n \n\nclass LigGrid(Grid):\n    \"\"\"\n    Calculate the \"charge\" part of the interaction energy.\n    \"\"\"\n    def __init__(self, prmtop_file_name, lj_sigma_scaling_factor, \n                       inpcrd_file_name, receptor_grid):\n        \"\"\"\n        :param prmtop_file_name: str, name of AMBER prmtop file\n        :param lj_sigma_scaling_factor: float\n        :param inpcrd_file_name: str, name of AMBER coordinate file\n        :param receptor_grid: an instance of RecGrid class.\n        \"\"\"\n        Grid.__init__(self)\n        grid_data = receptor_grid.get_grids()\n        if grid_data[\"lj_sigma_scaling_factor\"][0] != lj_sigma_scaling_factor:\n            raise RuntimeError(\"lj_sigma_scaling_factor is %f but in receptor_grid, it is %f\" %(\n                                lj_sigma_scaling_factor, grid_data[\"lj_sigma_scaling_factor\"][0]))\n        \n        entries = [key for key in grid_data.keys() if key not in self._grid_func_names]\n        print(\"Copy entries from receptor_grid\", entries)\n        for key in entries:\n            self._set_grid_key_value(key, grid_data[key])\n        self._initialize_convenient_para()\n\n        self._rec_FFTs = receptor_grid.get_FFTs()\n\n        self._load_prmtop(prmtop_file_name, lj_sigma_scaling_factor)\n        self._load_inpcrd(inpcrd_file_name)\n        self._move_ligand_to_lower_corner()\n        self._molecule_sasa = self._get_molecule_sasa(0.14, 960)\n\n\n    def _move_ligand_to_lower_corner(self):\n        \"\"\"\n        move ligand to near the grid lower corner \n        store self._max_grid_indices and self._initial_com\n        \"\"\"\n        spacing = self._grid[\"spacing\"]\n        lower_ligand_corner = np.array([self._crd[:,i].min() for i in range(3)], dtype=float) - 2.5*spacing\n        lower_ligand_corner_grid_aligned = lower_ligand_corner - (spacing + lower_ligand_corner % spacing) #new grid aligned variable\n        upper_ligand_corner = np.array([self._crd[:,i].max() for i in range(3)], dtype=float) + 2.5*spacing\n        upper_ligand_corner_grid_aligned = upper_ligand_corner + (spacing - upper_ligand_corner % spacing) #new grid aligned variable\n        #print(\"lower ligand corner grid aligned=\", lower_ligand_corner_grid_aligned)\n        #print(\"upper ligand corner grid aligned=\", upper_ligand_corner_grid_aligned)\n        #\n        ligand_box_lengths = upper_ligand_corner_grid_aligned - lower_ligand_corner_grid_aligned\n#        ligand_box_lengths = upper_ligand_corner - lower_ligand_corner\n        #print(\"ligand_box_lengths=\", ligand_box_lengths)\n        if np.any(ligand_box_lengths < 0):\n            raise RuntimeError(\"One of the ligand box lengths are negative\")\n\n        max_grid_indices = np.ceil(ligand_box_lengths / spacing)\n        self._max_grid_indices = self._grid[\"counts\"] - np.array(max_grid_indices, dtype=int)\n        if np.any(self._max_grid_indices <= 1):\n            raise RuntimeError(\"At least one of the max grid indices is <= one\")\n        \n        #displacement = self._origin_crd - lower_ligand_corner\n        displacement = self._origin_crd - lower_ligand_corner_grid_aligned #formerly lower_ligand_corner\n        for atom_ind in range(len(self._crd)):\n            self._crd[atom_ind] += displacement\n        print(f\"Ligand translated by {displacement}\")\n        self._displacement = displacement\n        lower_corner_origin = np.array([self._crd[:,i].min() for i in range(3)], dtype=float) - 1.5*spacing\n        print(lower_corner_origin)\n        self._initial_com = self._get_molecule_center_of_mass()\n        return None\n    \n    def _get_charges(self, name):\n        assert name in self._grid_func_names, \"%s is not allowed\"%name\n\n        if name == \"electrostatic\":\n            return np.array(self._prmtop[\"CHARGE_E_UNIT\"], dtype=float)\n        elif name == \"LJa\":\n            return np.array(self._prmtop[\"A_LJ_CHARGE\"], dtype=float)\n        elif name == \"LJr\":\n            return np.array(self._prmtop[\"R_LJ_CHARGE\"], dtype=float)\n        elif name == \"SASAi\":\n            return np.array([0], dtype=float)\n        elif name == \"SASAr\":\n            return np.array([0], dtype=float)\n        else:\n            raise RuntimeError(\"%s is unknown\"%name)\n\n    def _cal_charge_grid(self, name, sasai_grid):\n        # charges = self._get_charges(name)\n        grid_counts = np.copy(self._grid[\"counts\"])\n        # grid = c_cal_charge_grid_new(name, self._crd, self._grid[\"x\"], self._grid[\"y\"], self._grid[\"z\"],\n        #                         self._origin_crd, self._uper_most_corner_crd, self._uper_most_corner,\n        #                         self._grid[\"spacing\"], self._eight_corner_shifts, self._six_corner_shifts,\n        #                         grid_counts, charges, self._prmtop[\"LJ_SIGMA\"],\n        #                         self._molecule_sasa, sasai_grid\n        #                         )\n        task_divisor = 1\n        with concurrent.futures.ProcessPoolExecutor() as executor:\n            futures = {}\n            sasa_grid = np.empty((0, 0, 0))\n            for name in self._grid_func_names:\n                futures_array = []\n                for i in range(task_divisor):\n                    counts = np.copy(self._grid[\"counts\"])\n                    counts_x = counts[0] // task_divisor\n                    if i == task_divisor - 1:\n                        counts_x += counts[0] % task_divisor\n                    counts[0] = counts_x\n\n                    grid_start_x = i * (self._grid[\"counts\"][0] // task_divisor)\n                    origin = np.copy(self._origin_crd)\n                    origin[0] = grid_start_x * self._grid[\"spacing\"][0]\n\n                    if name != \"SASAr\":\n                        dummy_grid = np.empty((1, 1, 1), dtype=np.float64)\n                        futures_array.append(executor.submit(\n                            process_charge_grid_function,\n                            name,\n                            self._crd,\n                            origin,\n                            self._grid[\"spacing\"],\n                            self._eight_corner_shifts,\n                            self._six_corner_shifts,\n                            counts,\n                            self._get_charges(name),\n                            self._prmtop[\"LJ_SIGMA\"],\n                            self._molecule_sasa,\n                            dummy_grid\n                        ))\n                    else:\n                        futures_array.append(executor.submit(\n                            process_charge_grid_function,\n                            name,\n                            self._crd,\n                            origin,\n                            self._grid[\"spacing\"],\n                            self._eight_corner_shifts,\n                            self._six_corner_shifts,\n                            counts,\n                            self._get_charges(name),\n                            self._prmtop[\"LJ_SIGMA\"],\n                            self._molecule_sasa,\n                            sasa_grid\n                        ))\n                futures[name] = futures_array\n                # if name == \"SASAi\":\n                #     sasa_array = []\n                #     for i in range(task_divisor):\n                #         print(futures[name][i].result().shape)\n                #         partial_sasa_grid = futures[name][i].result()\n                #         sasa_array.append(partial_sasa_grid)\n                #     sasa_grid = np.concatenate(tuple(sasa_array))\n            for name in futures:\n                grid_array = []\n                for i in range(task_divisor):\n                    returned_sasai_grid, partial_grid = futures[name][i].result()\n                    grid_array.append(partial_grid)\n                    sasa_grid = returned_sasai_grid\n                grid = np.concatenate(tuple(grid_array), axis=0)\n                if name == \"SASAi\":\n                    sasa_grid = np.copy(grid)\n                # self._write_to_nc(nc_handle, name, grid)\n                # self._set_grid_key_value(name, grid)\n                # self._set_grid_key_value(name, None)     # to save memory\n\n        return grid\n\n    def _cal_corr_func(self, grid_name):\n        \"\"\"\n        :param grid_name: str\n        :return: fft correlation function\n        \"\"\"\n        assert grid_name in self._grid_func_names, \"%s is not an allowed grid name\"%grid_name\n\n        dummy_grid = np.empty((1, 1, 1), dtype=np.float64)\n        grid = self._cal_charge_grid(grid_name, dummy_grid)\n\n        self._set_grid_key_value(grid_name, grid)\n        corr_func = np.fft.fftn(self._grid[grid_name])\n        self._set_grid_key_value(grid_name, None)           # to save memory\n\n        corr_func = corr_func.conjugate()\n        corr_func = np.fft.ifftn(self._rec_FFTs[grid_name] * corr_func)\n        corr_func = np.real(corr_func)\n        return corr_func\n\n    def _cal_shape_complementarity(self):\n        \"\"\"\n        :param grid_name: str\n        :return: fft correlation function\n        \"\"\"\n        print(\"Calculating shape complementarity.\")\n        dummy_grid = np.empty((1, 1, 1), dtype=np.float64)\n        counts = self._grid[\"counts\"]\n\n        lig_sasai_grid = self._cal_charge_grid(\"SASAi\", dummy_grid)\n        lig_sasar_grid = self._cal_charge_grid(\"SASAr\", lig_sasai_grid)\n        lig_sasa_grid = np.add(lig_sasar_grid, lig_sasai_grid*1.j)\n\n        # self._set_grid_key_value(grid_name, lig_sasa_grid)\n        corr_func = np.fft.fftn(lig_sasa_grid)\n        # self._set_grid_key_value(grid_name, None)           # to save memory\n\n        rec_sasa_grid = self._rec_FFTs[\"SASA\"]\n\n        rec_sasa_fft = np.fft.fftn(rec_sasa_grid)\n\n        corr_func = np.fft.ifftn(rec_sasa_fft * corr_func) * (1/(np.prod(counts)))\n        corr_func = np.real(corr_func) - np.imag(corr_func)\n\n        return corr_func\n\n    def _do_forward_fft(self, grid_name):\n        assert grid_name in self._grid_func_names, \"%s is not an allowed grid name\"%grid_name\n        grid = self._cal_charge_grid(grid_name)\n        self._set_grid_key_value(grid_name, grid)\n        forward_fft = np.fft.fftn(self._grid[grid_name])\n        self._set_grid_key_value(grid_name, None)           # to save memory\n        return forward_fft\n\n    def _cal_corr_funcs(self, grid_names):\n        \"\"\"\n        :param grid_names: list of str\n        :return:\n        \"\"\"\n        assert type(grid_names) == list, \"grid_names must be a list\"\n\n        grid_name = grid_names[0]\n        forward_fft = self._do_forward_fft(grid_name)\n        corr_func = self._rec_FFTs[grid_name] * forward_fft.conjugate()\n\n        for grid_name in grid_names[1:]:\n            forward_fft = self._do_forward_fft(grid_name)\n            corr_func += self._rec_FFTs[grid_name] * forward_fft.conjugate()\n\n        corr_func = np.fft.ifftn(corr_func)\n        corr_func = np.real(corr_func)\n        return corr_func\n\n    def _cal_energies(self):\n        \"\"\"\n        calculate interaction energies\n        store self._meaningful_energies (1-array) and self._meaningful_corners (2-array)\n        meaningful means no border-crossing and no clashing\n        TODO\n        \"\"\"\n        max_i, max_j, max_k = self._max_grid_indices\n        # TODO figure out how to calculate new corr function using SASA grids\n        # corr_func = self._cal_corr_func(\"SASAr\")\n        corr_func = self._cal_shape_complementarity()\n        self._free_of_clash = (corr_func > 0)\n        print(\"number of poses free of clash:\", self._free_of_clash.shape)\n        self._free_of_clash = self._free_of_clash[0:max_i, 0:max_j, 0:max_k]  # exclude positions where ligand crosses border\n        print(\"Ligand positions excluding border crossers\", self._free_of_clash.shape)\n        self._meaningful_energies = np.zeros(self._grid[\"counts\"], dtype=float)\n        if np.any(self._free_of_clash):\n            grid_names = [name for name in self._grid_func_names if name[:4] != \"SASA\"]\n            for name in grid_names:\n                self._meaningful_energies += self._cal_corr_func(name) \n        # get crystal pose here, use i,j,k of crystal pose\n        self._meaningful_energies = self._meaningful_energies[0:max_i, 0:max_j, 0:max_k] # exclude positions where ligand crosses border\n        \n        self._meaningful_energies = self._meaningful_energies[self._free_of_clash]         # exclude positions where ligand is in clash with receptor, become 1D array\n        self._number_of_meaningful_energies = self._meaningful_energies.shape[0]\n        \n        return None\n\n    def _cal_energies_NOT_USED(self):\n        \"\"\"\n        calculate interaction energies\n        store self._meaningful_energies (1-array) and self._meaningful_corners (2-array)\n        meaningful means no boder-crossing and no clashing\n        TODO\n        \"\"\"\n        max_i, max_j, max_k = self._max_grid_indices\n\n        corr_func = self._cal_corr_func(\"occupancy\")\n        self._free_of_clash = (corr_func  < 0.001)\n        self._free_of_clash = self._free_of_clash[0:max_i, 0:max_j, 0:max_k]  # exclude positions where ligand crosses border\n\n        if np.any(self._free_of_clash):\n            grid_names = [name for name in self._grid_func_names if name != \"occupancy\"]\n            self._meaningful_energies = self._cal_corr_funcs(grid_names)\n        else:\n            self._meaningful_energies = np.zeros(self._grid[\"counts\"], dtype=float)\n\n        self._meaningful_energies = self._meaningful_energies[0:max_i, 0:max_j, 0:max_k] # exclude positions where ligand crosses border\n        self._meaningful_energies = self._meaningful_energies[self._free_of_clash]         # exclude positions where ligand is in clash with receptor, become 1D array\n        self._number_of_meaningful_energies = self._meaningful_energies.shape[0]\n        return None\n    \n    def _cal_meaningful_corners(self):\n        \"\"\"\n        return grid corners corresponding to self._meaningful_energies\n        \"\"\"\n        corners = np.where(self._free_of_clash)\n        corners = np.array(corners, dtype=int)\n        corners = corners.transpose()\n        return corners\n\n    def _place_ligand_crd_in_grid(self, molecular_coord):\n        \"\"\"\n        molecular_coord:    2-array, new ligand coordinate\n        \"\"\"\n        crd = np.array(molecular_coord, dtype=float)\n        natoms = self._prmtop[\"POINTERS\"][\"NATOM\"]\n        if (crd.shape[0] != natoms) or (crd.shape[1] != 3):\n            raise RuntimeError(\"Input coord does not have the correct shape.\")\n        self._crd = crd\n        self._move_ligand_to_lower_corner()\n        return None\n\n    def cal_grids(self, molecular_coord=None):\n        \"\"\"\n        molecular_coord:    2-array, new ligand coordinate\n        compute charge grids, meaningful_energies, meaningful_corners for molecular_coord\n        if molecular_coord==None, self._crd is used\n        \"\"\"\n        if molecular_coord is not None:\n            self._place_ligand_crd_in_grid(molecular_coord)\n        else:\n            self._move_ligand_to_lower_corner()         # this is just in case the self._crd is not at the right position\n        \n        self._cal_energies()\n        return None\n    \n    def get_bpmf(self, kB=0.001987204134799235, temperature=300.0):\n        \"\"\"\n        use self._meaningful_energies to calculate and return exponential mean\n        \"\"\"\n        if len(self._meaningful_energies) == 0:\n            return 0.\n\n        beta = 1. / temperature / kB\n        V_0 = 1661.\n\n        nr_samples = self.get_number_translations()\n        energies = -beta *  self._meaningful_energies\n        e_max = energies.max()\n        exp_mean = np.exp(energies - e_max).sum() / nr_samples\n\n        bpmf = -temperature * kB * (np.log(exp_mean) + e_max)\n\n        V_binding = self.get_box_volume()\n        correction = -temperature * kB * np.log(V_binding / V_0 / 8 / np.pi**2)\n        return bpmf + correction\n    \n    def get_number_translations(self):\n        return self._max_grid_indices.prod()\n    \n    def get_box_volume(self):\n        \"\"\"\n        in angstrom ** 3\n        \"\"\"\n        spacing = self._grid[\"spacing\"]\n        volume = ((self._max_grid_indices - 1) * spacing).prod()\n        return volume\n    \n    def get_meaningful_energies(self):\n        return self._meaningful_energies\n    \n    def get_meaningful_corners(self):\n        meaningful_corners = self._cal_meaningful_corners()\n        if meaningful_corners.shape[0] != self._number_of_meaningful_energies:\n            raise RuntimeError(\"meaningful_corners does not have the same len as self._number_of_meaningful_energies\")\n        return meaningful_corners\n\n    def set_meaningful_energies_to_none(self):\n        self._meaningful_energies = None\n        return None\n\n    def get_initial_com(self):\n        return self._initial_com\n\n    def get_SASAi_grid(self, name, crd,\n                       grid_x, grid_y, grid_z,\n                       origin_crd, uper_most_corner_crd, uper_most_corner,\n                       grid_spacing, eight_corner_shifts, six_corner_shifts,\n                       grid_counts, charges, prmtop_ljsigma, molecule_sasa, sasa_grid,\n                       roh_i_corners):\n        sasai_grid, grid, roh_i_corners = c_cal_lig_sasa_grid(name, crd,\n                                     grid_x, grid_y, grid_z,\n                                     origin_crd, uper_most_corner_crd, uper_most_corner,\n                                     grid_spacing, eight_corner_shifts, six_corner_shifts,\n                                     grid_counts, charges, prmtop_ljsigma, molecule_sasa, sasa_grid,\n                                               roh_i_corners)\n        return sasai_grid, grid, roh_i_corners\n\n    def get_SASAr_grid(self, name, crd,\n                       grid_x, grid_y, grid_z,\n                       origin_crd, uper_most_corner_crd, uper_most_corner,\n                       grid_spacing, eight_corner_shifts, six_corner_shifts,\n                       grid_counts, charges, prmtop_ljsigma, molecule_sasa, sasa_grid,\n                       roh_i_corners):\n        sasai_grid, grid, roh_i_corners = c_cal_lig_sasa_grid(name, crd,\n                                     grid_x, grid_y, grid_z,\n                                     origin_crd, uper_most_corner_crd, uper_most_corner,\n                                     grid_spacing, eight_corner_shifts, six_corner_shifts,\n                                     grid_counts, charges, prmtop_ljsigma, molecule_sasa, sasa_grid,\n                                                              roh_i_corners)\n        return sasai_grid, grid, roh_i_corners\n\n    def get_SASA_grids(self, name, crd,\n                       grid_x, grid_y, grid_z,\n                       origin_crd, uper_most_corner_crd, uper_most_corner,\n                       grid_spacing, eight_corner_shifts, six_corner_shifts,\n                       nearest_neighbor_shifts, grid_counts, charges,\n                       prmtop_ljsigma, molecule_sasa, rho,\n                       sasa_core_scaling, sasa_surface_scaling):\n        \"\"\"\n        Return the SASAi and SASAr grids for the Ligand\n        \"\"\"\n        sasai_grid, sasar_grid = c_cal_lig_sasa_grids(name, crd,\n                                     grid_x, grid_y, grid_z,\n                                     origin_crd, uper_most_corner_crd, uper_most_corner,\n                                     grid_spacing, eight_corner_shifts, six_corner_shifts,\n                                     nearest_neighbor_shifts, grid_counts, charges,\n                                     prmtop_ljsigma, molecule_sasa, rho,\n                                     sasa_core_scaling, sasa_surface_scaling)\n        return sasai_grid, sasar_grid\n\n    def translate_ligand(self, displacement):\n        \"\"\"\n        translate the ligand by displacement in Angstroms\n        \"\"\"\n        for atom_ind in range(len(self._crd)):\n            self._crd[atom_ind] += displacement\n        return None\n\n\n \nclass RecGrid(Grid):\n    \"\"\"\n    calculate the potential part of the interaction energy.\n    \"\"\"\n    def __init__(self,  prmtop_file_name, lj_sigma_scaling_factor,\n                        sasa_core_scaling, sasa_surface_scaling,\n                        rho,\n                        inpcrd_file_name,\n                        bsite_file,\n                        grid_nc_file,\n                        new_calculation=False,\n                        spacing=0.25, extra_buffer=3.0):  #default extra_buffer=3.0\n        \"\"\"\n        :param prmtop_file_name: str, name of AMBER prmtop file\n        :param lj_sigma_scaling_factor: float\n        :param inpcrd_file_name: str, name of AMBER coordinate file\n        :param bsite_file: str or None, if not None, name of a file defining the box dimension.\n        This file is the same as \"measured_binding_site.py\" from AlGDock pipeline.\n        :param grid_nc_file: str, name of grid nc file\n        :param new_calculation: bool, if True do the new grid calculation else load data in grid_nc_file.\n        :param spacing: float and in angstrom.\n        :param extra_buffer: float\n        \"\"\"\n        Grid.__init__(self)\n        self._load_prmtop(prmtop_file_name, lj_sigma_scaling_factor)\n        self._FFTs = {}\n\n        if new_calculation:\n            self._load_inpcrd(inpcrd_file_name)\n            self._molecule_sasa = self._get_molecule_sasa(0.14, 960)\n            self._rho = rho\n            self._sasa_core_scaling = sasa_core_scaling\n            self._sasa_surface_scaling = sasa_surface_scaling\n            nc_handle = netCDF4.Dataset(grid_nc_file, \"w\", format=\"NETCDF4\")\n            self._write_to_nc(nc_handle, \"lj_sigma_scaling_factor\", \n                                np.array([lj_sigma_scaling_factor], dtype=float))\n            self._write_to_nc(nc_handle, \"sasa_core_scaling\",\n                              np.array([sasa_core_scaling], dtype=float))\n            self._write_to_nc(nc_handle, \"sasa_surface_scaling\",\n                              np.array([sasa_surface_scaling], dtype=float))\n            self._write_to_nc(nc_handle, \"rho\",\n                              np.array([rho], dtype=float))\n            self._write_to_nc(nc_handle, \"molecule_sasa\",\n                              np.array(self._molecule_sasa, dtype=float))\n\n            if bsite_file is not None:\n                print(\"Receptor is assumed to be correctly translated such that box encloses binding pocket.\")\n                self._cal_grid_parameters_with_bsite(spacing, bsite_file, nc_handle)\n                self._cal_grid_coordinates(nc_handle)\n                self._initialize_convenient_para()\n            else:\n                print(\"No binding site specified, box encloses the whole receptor\")\n                self._cal_grid_parameters_without_bsite(spacing, extra_buffer, nc_handle)\n                self._cal_grid_coordinates(nc_handle)\n                self._initialize_convenient_para()\n                self._move_receptor_to_grid_center()\n                self._write_to_nc(nc_handle, \"displacement\", self._displacement)\n\n            self._cal_potential_grids(nc_handle)\n            self._write_to_nc(nc_handle, \"trans_crd\", self._crd)\n            nc_handle.close()\n                \n        self._load_precomputed_grids(grid_nc_file, lj_sigma_scaling_factor)\n\n    def _load_precomputed_grids(self, grid_nc_file, lj_sigma_scaling_factor):\n        \"\"\"\n        nc_file_name:   str\n        lj_sigma_scaling_factor: float, used for consistency check\n        load netCDF file, populate self._grid with all the data fields \n        \"\"\"\n        assert os.path.isfile(grid_nc_file), \"%s does not exist\" %grid_nc_file\n\n        print(grid_nc_file)\n        nc_handle = netCDF4.Dataset(grid_nc_file, \"r\")\n        keys = [key for key in self._grid_allowed_keys if key not in self._grid_func_names]\n        for key in keys:\n            self._set_grid_key_value(key, nc_handle.variables[key][:])\n\n        if self._grid[\"lj_sigma_scaling_factor\"][0] != lj_sigma_scaling_factor:\n            raise RuntimeError(\"lj_sigma_scaling_factor is %f but in %s, it is %f\" %(\n                lj_sigma_scaling_factor, grid_nc_file, self._grid[\"lj_sigma_scaling_factor\"][0]))\n\n        self._initialize_convenient_para()\n\n        natoms = self._prmtop[\"POINTERS\"][\"NATOM\"]\n        if natoms != nc_handle.variables[\"trans_crd\"].shape[0]:\n            raise RuntimeError(\"Number of atoms is wrong in %s %nc_file_name\")\n        self._crd = nc_handle.variables[\"trans_crd\"][:]\n\n        for key in self._grid_func_names:\n            if key[:4] != \"SASA\":\n                self._set_grid_key_value(key, nc_handle.variables[key][:])\n                self._FFTs[key] = self._cal_FFT(key)\n                self._set_grid_key_value(key, None)     # to save memory\n        # self._set_grid_key_value(\"SASAi\", nc_handle.variables[\"SASAi\"][:])  #UNCOMMENT ME\n        # self._set_grid_key_value(\"SASAr\", nc_handle.variables[\"SASAr\"][:])  #UNCOMMENT ME\n        # self._FFTs[\"SASA\"] = self._cal_SASA_FFT()  #UNCOMMENT ME\n        # self._set_grid_key_value(\"SASAi\", None)  #UNCOMMENT ME\n        # self._set_grid_key_value(\"SASAr\", None)  #UNCOMMENT ME\n        nc_handle.close()\n        return None\n\n    def _cal_FFT(self, name):\n        if name not in self._grid_func_names:\n            raise RuntimeError(\"%s is not allowed.\")\n        print(\"Doing FFT for %s\"%name)\n        FFT = np.fft.fftn(self._grid[name])\n        return FFT\n\n    def _cal_SASA_FFT(self):\n        print(\"Doing FFT for SASA\")\n        sasai_grid = self._grid[\"SASAi\"]\n        sasar_grid = self._grid[\"SASAr\"]\n        sasa_grid = np.add(sasar_grid, sasai_grid*1.j)\n        FFT = np.fft.fftn(sasa_grid)\n        return FFT\n\n    def _write_to_nc(self, nc_handle, key, value):\n        print(\"Writing %s into nc file\"%key)\n        # create dimensions\n        for dim in value.shape:\n            dim_name = \"%d\"%dim\n            if dim_name not in nc_handle.dimensions.keys():\n                nc_handle.createDimension(dim_name, dim)\n\n        # create variable\n        if value.dtype == int:\n            store_format = \"i8\"\n        elif value.dtype == float:\n            store_format = \"f8\"\n        else:\n            raise RuntimeError(\"unsupported dtype %s\"%value.dtype)\n        dimensions = tuple([\"%d\"%dim for dim in value.shape])\n        nc_handle.createVariable(key, store_format, dimensions)\n\n        # save data\n        nc_handle.variables[key][:] = value\n        return None\n\n    def _cal_grid_parameters_with_bsite(self, spacing, bsite_file, nc_handle):\n        \"\"\"\n        :param spacing: float, unit in angstrom, the same in x, y, z directions\n        :param bsite_file: str, the file name of \"measured_binding_site.py\" from AlGDock pipeline\n        :param nc_handle: an instance of netCDF4.Dataset()\n        :return: None\n        \"\"\"\n        assert spacing > 0, \"spacing must be positive\"\n        self._set_grid_key_value(\"origin\", np.zeros([3], dtype=float))\n        \n        self._set_grid_key_value(\"d0\", np.array([spacing, 0, 0], dtype=float))\n        self._set_grid_key_value(\"d1\", np.array([0, spacing, 0], dtype=float))\n        self._set_grid_key_value(\"d2\", np.array([0, 0, spacing], dtype=float))\n        self._set_grid_key_value(\"spacing\", np.array([spacing]*3, dtype=float))\n\n        # function to easily grab a single float from a complex string\n        def get_num(x):\n            return float(''.join(ele for ele in x if ele.isdigit() or ele == '.'))\n\n        # create a regular expression to parse the read lines\n        parser = re.compile(r'\\d+.\\d+')\n\n        for line in open(bsite_file, \"r\"):\n            if line.startswith('com_min = '):\n                com_min = [float(i) for i in parser.findall(line)]\n            if line.startswith('com_max = '):\n                com_max = [float(i) for i in parser.findall(line)]\n            if line.startswith('site_R = '):\n                site_R = [float(i) for i in parser.findall(line)][0]\n            if line.startswith('half_edge_length = '):\n                half_edge_length = [float(i) for i in parser.findall(line)][0]\n        #half_edge_length = get_num(line)\n        print(\"half_edge_length = \", half_edge_length)\n        length = 2. * half_edge_length         # TODO: this is not good, half_edge_length is define in bsite_file\n        count = np.ceil(length / spacing) + 1\n        \n        self._set_grid_key_value(\"counts\", np.array([count]*3, dtype=int))\n\n        for key in [\"origin\", \"d0\", \"d1\", \"d2\", \"spacing\", \"counts\"]:\n            self._write_to_nc(nc_handle, key, self._grid[key])\n        return None\n    \n    def _cal_grid_parameters_without_bsite(self, spacing, extra_buffer, nc_handle):\n        \"\"\"\n        use this when making box encompassing the whole receptor\n        spacing:    float, unit in angstrom, the same in x, y, z directions\n        extra_buffer: float\n        \"\"\"\n        assert spacing > 0 and extra_buffer > 0, \"spacing and extra_buffer must be positive\"\n        self._set_grid_key_value(\"origin\", np.zeros( [3], dtype=float))\n        \n        self._set_grid_key_value(\"d0\", np.array([spacing, 0, 0], dtype=float))\n        self._set_grid_key_value(\"d1\", np.array([0, spacing, 0], dtype=float))\n        self._set_grid_key_value(\"d2\", np.array([0, 0, spacing], dtype=float))\n        self._set_grid_key_value(\"spacing\", np.array([spacing]*3, dtype=float))\n        \n        lj_radius = np.array(self._prmtop[\"LJ_SIGMA\"]/2., dtype=float)\n        dx = (self._crd[:,0] + lj_radius).max() - (self._crd[:,0] - lj_radius).min()\n        dy = (self._crd[:,1] + lj_radius).max() - (self._crd[:,1] - lj_radius).min()\n        dz = (self._crd[:,2] + lj_radius).max() - (self._crd[:,2] - lj_radius).min()\n\n        print(\"Receptor enclosing box [%f, %f, %f]\"%(dx, dy, dz))\n        print(\"extra_buffer: %f\"%extra_buffer)\n\n        length = max([dx, dy, dz]) + 2.0*extra_buffer\n\n        if np.ceil(length / spacing)%2 != 0:\n            length = length + spacing\n        count = np.ceil(length / spacing) + 1\n        \n        self._set_grid_key_value(\"counts\", np.array([count]*3, dtype=int))\n        print(\"counts \", self._grid[\"counts\"])\n        print(\"Total box size %f\" %((count-1)*spacing))\n\n        for key in [\"origin\", \"d0\", \"d1\", \"d2\", \"spacing\", \"counts\"]:\n            self._write_to_nc(nc_handle, key, self._grid[key])\n        return None\n    \n    def _move_receptor_to_grid_center(self):\n        \"\"\"\n        use this when making box encompassing the whole receptor\n        \"\"\"\n        spacing = self._grid[\"spacing\"]        \n        lower_receptor_corner = np.array([self._crd[:,i].min() for i in range(3)], dtype=float)\n        upper_receptor_corner = np.array([self._crd[:,i].max() for i in range(3)], dtype=float)\n        \n        lower_receptor_corner_grid_aligned = lower_receptor_corner - (spacing + lower_receptor_corner % spacing)\n        upper_receptor_corner_grid_aligned = upper_receptor_corner + (spacing - upper_receptor_corner % spacing)\n\n        receptor_box_center_grid_aligned = (upper_receptor_corner_grid_aligned + lower_receptor_corner_grid_aligned) / 2.\n\n        receptor_box_center = (upper_receptor_corner + lower_receptor_corner) / 2.\n        \n        total_grid_count = (self._uper_most_corner_crd+spacing)/spacing\n        print(total_grid_count)             \n        grid_center = (self._origin_crd + self._uper_most_corner_crd) / 2.       \n        receptor_box_length = upper_receptor_corner - lower_receptor_corner\n        receptor_box_length_grid_aligned = upper_receptor_corner_grid_aligned - lower_receptor_corner_grid_aligned\n\n        #test redefs of variables\n#        receptor_box_center = ([upper_receptor_corner_grid_aligned[0], \n#            upper_receptor_corner_grid_aligned[1]+0.5,\n#            upper_receptor_corner_grid_aligned[2]+0.5] + lower_receptor_corner_grid_aligned) / 2.\n        for index, coord in enumerate(upper_receptor_corner_grid_aligned):\n            corner_to_corner_1D_distance = (coord - lower_receptor_corner_grid_aligned[index])/spacing[index]\n            lower_corner_coord = lower_receptor_corner_grid_aligned[index]\n            half_spacing = spacing[index]/2.\n            print(corner_to_corner_1D_distance)            \n            if corner_to_corner_1D_distance%2 == 0:\n                shifted_upper_coord = coord + half_spacing\n                shifted_lower_coord = lower_corner_coord - half_spacing\n                upper_receptor_corner_grid_aligned[index] = shifted_upper_coord\n                lower_receptor_corner_grid_aligned[index] = shifted_lower_coord\n\n        receptor_box_center = (upper_receptor_corner_grid_aligned + lower_receptor_corner_grid_aligned) / 2.\n        grid_snap = np.mod(receptor_box_center, spacing)\n        if np.any(np.where(grid_snap != 0)):\n            receptor_box_center = np.add(receptor_box_center, np.subtract(spacing, grid_snap))\n\n        print('receptor_box_center', receptor_box_center)        \n        displacement = grid_center - receptor_box_center\n        \n        print('lower_receptor_corner_grid_aligned: ', lower_receptor_corner_grid_aligned, \n            '\\nupper_receptor_corner_grid_aligned: ', upper_receptor_corner_grid_aligned,\n            '\\nlower_receptor_corner: ', lower_receptor_corner, \n            '\\nupper_receptor_corner: ', upper_receptor_corner,\n            '\\nreceptor_box_center: ', receptor_box_center,\n            '\\nreceptor_box_center_grid_aligned', receptor_box_center_grid_aligned,\n            '\\ngrid_center: ', grid_center,\n            '\\nreceptor_box_length: ', receptor_box_length,\n            '\\nreceptor_box_length_grid_aligned: ', receptor_box_length_grid_aligned,\n            '\\nspacing num', receptor_box_length_grid_aligned/spacing\n            )\n        print(\"Receptor is translated by \", displacement)\n        self._displacement = displacement\n\n        for atom_ind in range(len(self._crd)):\n            self._crd[atom_ind] += displacement\n        return None\n    \n    def _cal_grid_coordinates(self, nc_handle):\n        \"\"\"\n        calculate grid coordinates (x,y,z) for each corner,\n        save 'x', 'y', 'z' to self._grid\n        \"\"\"\n        print(\"calculating grid coordinates\")\n        #\n        x = np.zeros(self._grid[\"counts\"][0], dtype=float)\n        y = np.zeros(self._grid[\"counts\"][1], dtype=float)\n        z = np.zeros(self._grid[\"counts\"][2], dtype=float)\n        \n        for i in range(self._grid[\"counts\"][0]):\n            x[i] = self._grid[\"origin\"][0] + i*self._grid[\"d0\"][0]\n\n        for j in range(self._grid[\"counts\"][1]):\n            y[j] = self._grid[\"origin\"][1] + j*self._grid[\"d1\"][1]\n\n        for k in range(self._grid[\"counts\"][2]):\n            z[k] = self._grid[\"origin\"][2] + k*self._grid[\"d2\"][2]\n\n        self._set_grid_key_value(\"x\", x)\n        self._set_grid_key_value(\"y\", y)\n        self._set_grid_key_value(\"z\", z)\n\n        for key in [\"x\", \"y\", \"z\"]:\n            self._write_to_nc(nc_handle, key, self._grid[key])\n        return None\n\n    def _get_charges(self, name):\n        assert name in self._grid_func_names, \"%s is not allowed\"%name\n\n        if name == \"electrostatic\":\n            return 332.05221729 * np.array(self._prmtop[\"CHARGE_E_UNIT\"], dtype=float)\n        elif name == \"LJa\":\n            return -2.0 * np.array(self._prmtop[\"A_LJ_CHARGE\"], dtype=float)\n        elif name == \"LJr\":\n            return np.array(self._prmtop[\"R_LJ_CHARGE\"], dtype=float)\n        elif name == \"SASAi\":\n            return np.array([0], dtype=float)\n        elif name == \"SASAr\":\n            return np.array([0], dtype=float)\n        else:\n            raise RuntimeError(\"%s is unknown\"%name)\n\n    def _cal_potential_grids(self, nc_handle):\n        \"\"\"\n        Divides each grid calculation into a separate process (electrostatic, LJr, LJa,\n        SASAr, SASAi) and then divides the grid into slices along the x-axis determined by\n        the \"task divisor\". Remainders are calculated in the last slice.  This adds\n        multiprocessing functionality to the grid generation.\n        \"\"\"\n        task_divisor = 8\n        with concurrent.futures.ProcessPoolExecutor() as executor:\n            futures = {}\n            sasa_grid = np.empty((0,0,0))\n            for name in self._grid_func_names:\n                futures_array = []\n                for i in range(task_divisor):\n                    counts = np.copy(self._grid[\"counts\"])\n                    counts_x = counts[0] // task_divisor\n                    if i == task_divisor-1:\n                        counts_x += counts[0] % task_divisor\n                    counts[0] = counts_x\n\n                    grid_start_x = i * (self._grid[\"counts\"][0] // task_divisor)\n                    origin = np.copy(self._origin_crd)\n                    origin[0] = grid_start_x * self._grid[\"spacing\"][0]\n\n                    if name != \"SASAr\":\n                        dummy_grid = np.empty((1,1,1), dtype=np.float64)\n                        futures_array.append(executor.submit(\n                            process_potential_grid_function,\n                            name,\n                            self._crd,\n                            origin,\n                            self._grid[\"spacing\"],\n                            counts,\n                            self._get_charges(name),\n                            self._prmtop[\"LJ_SIGMA\"],\n                            self._molecule_sasa,\n                            self._rho,\n                            self._sasa_core_scaling,\n                            self._sasa_surface_scaling,\n                            dummy_grid\n                        ))\n                    else:\n                        futures_array.append(executor.submit(\n                            process_potential_grid_function,\n                            name,\n                            self._crd,\n                            origin,\n                            self._grid[\"spacing\"],\n                            counts,\n                            self._get_charges(name),\n                            self._prmtop[\"LJ_SIGMA\"],\n                            self._molecule_sasa,\n                            self._rho,\n                            self._sasa_core_scaling,\n                            self._sasa_surface_scaling,\n                            sasa_grid\n                        ))\n                futures[name] = futures_array\n                if name == \"SASAi\":\n                    sasa_array = []\n                    for i in range(task_divisor):\n                        partial_sasa_grid = futures[name][i].result()\n                        sasa_array.append(partial_sasa_grid)\n                    sasa_grid = np.concatenate(tuple(sasa_array))\n            for name in futures:\n                grid_array = []\n                for i in range(task_divisor):\n                    partial_grid = futures[name][i].result()\n                    grid_array.append(partial_grid)\n                grid = np.concatenate(tuple(grid_array), axis=0)\n                if name == \"SASAi\":\n                    sasa_grid = np.copy(grid)\n                self._write_to_nc(nc_handle, name, grid)\n                self._set_grid_key_value(name, grid)\n                # self._set_grid_key_value(name, None)     # to save memory\n\n        return None\n    \n    def _exact_values(self, coordinate):\n        \"\"\"\n        coordinate: 3-array of float\n        calculate the exact \"potential\" value at any coordinate\n        \"\"\"\n        assert len(coordinate) == 3, \"coordinate must have len 3\"\n        if not self._is_in_grid(coordinate):\n            raise RuntimeError(\"atom is outside grid even after pbc translated\")\n        \n        values = {}\n        for name in self._grid_func_names:\n            if name[:4] != \"SASA\":\n                values[name] = 0.\n        \n        NATOM = self._prmtop[\"POINTERS\"][\"NATOM\"]\n        for atom_ind in range(NATOM):\n            dif = coordinate - self._crd[atom_ind]\n            R = np.sqrt((dif*dif).sum())\n            lj_diameter = self._prmtop[\"LJ_SIGMA\"][atom_ind]\n\n            if R > lj_diameter:\n                values[\"electrostatic\"] +=  332.05221729 * self._prmtop[\"CHARGE_E_UNIT\"][atom_ind] / R\n                values[\"LJr\"] +=  self._prmtop[\"R_LJ_CHARGE\"][atom_ind] / R**12\n                values[\"LJa\"] += -2. * self._prmtop[\"A_LJ_CHARGE\"][atom_ind] / R**6\n        \n        return values\n    \n    def _trilinear_interpolation( self, grid_name, coordinate ):\n        \"\"\"\n        grid_name is a str one of \"electrostatic\", \"LJr\" and \"LJa\"\n        coordinate is an array of three numbers\n        trilinear interpolation\n        https://en.wikipedia.org/wiki/Trilinear_interpolation\n        \"\"\"\n        raise RuntimeError(\"Do not use, not tested yet\")\n        assert len(coordinate) == 3, \"coordinate must have len 3\"\n        \n        eight_corners, nearest_ind, furthest_ind = self._containing_cube( coordinate ) # throw exception if coordinate is outside\n        lower_corner = eight_corners[0]\n        \n        (i0, j0, k0) = lower_corner\n        (i1, j1, k1) = (i0 + 1, j0 + 1, k0 + 1)\n        \n        xd = (coordinate[0] - self._grid[\"x\"][i0,j0,k0]) / (self._grid[\"x\"][i1,j1,k1] - self._grid[\"x\"][i0,j0,k0])\n        yd = (coordinate[1] - self._grid[\"y\"][i0,j0,k0]) / (self._grid[\"y\"][i1,j1,k1] - self._grid[\"y\"][i0,j0,k0])\n        zd = (coordinate[2] - self._grid[\"z\"][i0,j0,k0]) / (self._grid[\"z\"][i1,j1,k1] - self._grid[\"z\"][i0,j0,k0])\n        \n        c00 = self._grid[grid_name][i0,j0,k0]*(1. - xd) + self._grid[grid_name][i1,j0,k0]*xd\n        c10 = self._grid[grid_name][i0,j1,k0]*(1. - xd) + self._grid[grid_name][i1,j1,k0]*xd\n        c01 = self._grid[grid_name][i0,j0,k1]*(1. - xd) + self._grid[grid_name][i1,j0,k1]*xd\n        c11 = self._grid[grid_name][i0,j1,k1]*(1. - xd) + self._grid[grid_name][i1,j1,k1]*xd\n        \n        c0 = c00*(1. - yd) + c10*yd\n        c1 = c01*(1. - yd) + c11*yd\n        \n        c = c0*(1. - zd) + c1*zd\n        return c\n    \n    def direct_energy(self, ligand_coordinate, ligand_charges):\n        \"\"\"\n        :param ligand_coordinate: ndarray of shape (natoms, 3)\n        :param ligand_charges: ndarray of shape (3,)\n        :return: dic\n        \"\"\"\n        assert len(ligand_coordinate) == len(ligand_charges[\"CHARGE_E_UNIT\"]), \"coord and charges must have the same len\"\n        energy = 0.\n        for atom_ind in range(len(ligand_coordinate)):\n            potentials = self._exact_values(ligand_coordinate[atom_ind])\n            energy += potentials[\"electrostatic\"]*ligand_charges[\"CHARGE_E_UNIT\"][atom_ind]\n            energy += potentials[\"LJr\"]*ligand_charges[\"R_LJ_CHARGE\"][atom_ind]\n            energy += potentials[\"LJa\"]*ligand_charges[\"A_LJ_CHARGE\"][atom_ind]\n        return energy\n    \n    def interpolated_energy(self, ligand_coordinate, ligand_charges):\n        \"\"\"\n        ligand_coordinate:  array of shape (natoms, 3)\n        ligand_charges: array of shape (3)\n        assume that ligand_coordinate is inside grid\n        \"\"\"\n        raise RuntimeError(\"Do not use, not tested yet\")\n        assert len(ligand_coordinate) == len(ligand_charges[\"CHARGE_E_UNIT\"]), \"coord and charges must have the same len\"  \n        grid_names = [name for name in self._grid_func_names if name[:4] != \"SASA\"]\n        energy = 0.\n        potentials = {}\n        for atom_ind in range(len(ligand_coordinate)):\n            for name in grid_names:\n                potentials[name] = self._trilinear_interpolation(name, ligand_coordinate[atom_ind])\n            \n            energy += potentials[\"electrostatic\"]*ligand_charges[\"CHARGE_E_UNIT\"][atom_ind]\n            energy += potentials[\"LJr\"]*ligand_charges[\"R_LJ_CHARGE\"][atom_ind]\n            energy += potentials[\"LJa\"]*ligand_charges[\"A_LJ_CHARGE\"][atom_ind]\n        \n        return energy\n\n    def get_FFTs(self):\n        return self._FFTs\n\n    def write_box(self, file_name):\n        IO.write_box(self, file_name)\n        return None\n\n    def write_pdb(self, file_name, mode):\n        IO.write_pdb(self._prmtop, self._crd, file_name, mode)\n        return None\n\n\nif __name__ == \"__main__\":\n    # do some test\n    rec_prmtop_file = \"../examples/amber/ubiquitin_ligase/receptor.prmtop\"\n    rec_inpcrd_file = \"../examples/amber/ubiquitin_ligase/receptor.inpcrd\"\n    grid_nc_file = \"../examples/grid/ubiquitin_ligase/grid.nc\"\n    lj_sigma_scaling_factor = 0.8\n    # bsite_file = \"../examples/amber/t4_lysozyme/measured_binding_site.py\"\n    bsite_file = None\n    spacing = 0.5\n\n    rec_grid = RecGrid(rec_prmtop_file, lj_sigma_scaling_factor, rec_inpcrd_file, \n                        bsite_file,\n                        grid_nc_file,\n                        new_calculation=True,\n                        spacing=spacing)\n    print(\"get_grid_func_names\", rec_grid.get_grid_func_names())\n    print(\"get_grids\", rec_grid.get_grids())\n    print(\"get_crd\", rec_grid.get_crd())\n    print(\"get_prmtop\", rec_grid.get_prmtop())\n    print(\"get_prmtop\", rec_grid.get_charges())\n    print(\"get_natoms\", rec_grid.get_natoms())\n    print(\"get_natoms\", rec_grid.get_allowed_keys())\n\n    rec_grid.write_box(\"../examples/grid/ubiquitin_ligase/box.pdb\")\n    rec_grid.write_pdb(\"../examples/grid/ubiquitin_ligase/test.pdb\", \"w\")\n\n    lig_prmtop_file = \"../examples/amber/ubiquitin/ligand.prmtop\"\n    lig_inpcrd_file = \"../examples/amber/ubiquitin/ligand.inpcrd\"\n    lig_grid = LigGrid(lig_prmtop_file, lj_sigma_scaling_factor, lig_inpcrd_file, rec_grid)\n    lig_grid.cal_grids()\n    print(\"get_bpmf\", lig_grid.get_bpmf())\n    print(\"get_number_translations\", lig_grid.get_number_translations())\n    print(\"get_box_volume\", lig_grid.get_box_volume())\n    print(\"get_meaningful_energies\", lig_grid.get_meaningful_energies())\n    print(\"get_meaningful_corners\", lig_grid.get_meaningful_corners())\n    print(\"set_meaningful_energies_to_none\", lig_grid.set_meaningful_energies_to_none())\n    print(\"get_initial_com\", lig_grid.get_initial_com())\n    print(\"Receptor SASA\", rec_grid._get_molecule_sasa(0.14, 960))\n    print(\"Ligand SASA\", lig_grid._get_molecule_sasa(0.14, 960))\n\n\n", "meta": {"hexsha": "c9767622dc4856bb2624ffc0ce9cccd27f403b09", "size": 58563, "ext": "py", "lang": "Python", "max_stars_repo_path": "bpmfwfft/grids.py", "max_stars_repo_name": "jimtufts/bpmfwfft", "max_stars_repo_head_hexsha": "091d2269b122f00b9dd8a01e34303e3e946f8ea0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bpmfwfft/grids.py", "max_issues_repo_name": "jimtufts/bpmfwfft", "max_issues_repo_head_hexsha": "091d2269b122f00b9dd8a01e34303e3e946f8ea0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bpmfwfft/grids.py", "max_forks_repo_name": "jimtufts/bpmfwfft", "max_forks_repo_head_hexsha": "091d2269b122f00b9dd8a01e34303e3e946f8ea0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.131876413, "max_line_length": 166, "alphanum_fraction": 0.6017280535, "include": true, "reason": "import numpy", "num_tokens": 14156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.15844708316616962}}
{"text": "# This file is part of pyTSEB for running different TSEB models\n# Copyright 2016 Hector Nieto and contributors listed in the README.md file.\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n'''\nCreated on Apr 6 2015\n@author: Hector Nieto (hnieto@ias.csic.es)\nModified on Jan 27 2016\n@author: Hector Nieto (hnieto@ias.csic.es)\nDESCRIPTION\n===========\nThis package contains the main routines inherent of Two Source Energy Balance `TSEB` models.\nAdditional functions needed in TSEB, such as computing of net radiation or estimating the\nresistances to heat and momentum transport are imported.\n* :doc:`netRadiation` for the estimation of net radiation and radiation partitioning.\n* :doc:`ClumpingIndex` for the estimatio of canopy clumping index.\n* :doc:`meteoUtils` for the estimation of meteorological variables.\n* :doc:`resistances` for the estimation of the resistances to heat and momentum transport.\n* :doc:`MOsimilarity` for the estimation of the Monin-Obukhov length and MOST-related variables.\nPACKAGE CONTENTS\n================\nTSEB models\n-----------\n* :func:`TSEB_PT` Priestley-Taylor TSEB using a single observation of composite radiometric temperature.\nAncillary functions\n-------------------\n* :func:`calc_F_theta_campbell`. Gap fraction estimation.\n* :func:`calc_G_time_diff`. Santanello & Friedl (2003) [Santanello2003]_ soil heat flux model.\n* :func:`calc_G_ratio`. Soil heat flux as a fixed fraction of net radiation [Choudhury1987]_.\n* :func:`calc_H_C_PT`. Priestley- Taylor Canopy sensible heat flux.\n* :func:`calc_T_C_series.` Canopy temperature from canopy sensible heat flux and resistance in series.\n* :func:`calc_T_S`. Soil temperature from form composite radiometric temperature.\n'''\n\nimport numpy as np\n#from FourSAIL import FourSAIL\n\nfrom .meteo_utils import calc_rho,calc_c_p,calc_delta_vapor_pressure,calc_psicr,calc_lambda\nfrom .resistances import calc_z_0H,calc_R_A,calc_R_x_Norman,calc_R_S_Kustas,calc_R_x_Choudhury,calc_R_S_Choudhury,calc_R_x_McNaughton,calc_R_S_McNaughton\nfrom .MO_similarity import calc_u_star,calc_u_C_star,calc_u_Goudriaan,calc_L,calc_A_Goudriaan\nfrom .net_radiation import calc_L_n_Kustas,calc_K_be_Campbell\nfrom .clumping_index import calc_omega0_Kustas\n#from cachetools import cached\n\n#==============================================================================\n# List of constants used in TSEB model and sub-routines\n#==============================================================================\n# Change threshold in  Monin-Obukhov lengh to stop the iterations\nL_thres = 0.00001\n# Change threshold in  friction velocity to stop the iterations\nu_thres = 0.00001\n# mimimun allowed friction velocity\nu_friction_min = 0.01\n# Maximum number of interations\nITERATIONS = 20\n# kB coefficient\nkB = 0.0\n# Stephan Boltzmann constant (W m-2 K-4)\nsb = 5.670373e-8\n\n\ndef TSEB_PT(\n    Tr_K,\n    vza,\n    T_A_K,\n    u,\n    ea,\n    p,\n    Sn_C,\n    Sn_S,\n    L_dn,\n    LAI,\n    hc,\n    emis_C,\n    emis_S,\n    z_0M,\n    d_0,\n    z_u,\n    z_T,\n    nullMask,\n    leaf_width=0.1,\n    z0_soil=0.01,\n    alpha_PT=1.26,\n    x_LAD=1,\n    f_c=1.0,\n    f_g=1.0,\n    w_C=1.0,\n    resistance_form=0,\n    calcG_array=[\n        [1],\n        0.35],\n        UseL=False):\n    '''Priestley-Taylor TSEB\n    Calculates the Priestley Taylor TSEB fluxes using a single observation of\n    composite radiometric temperature and using resistances in series.\n    Parameters\n    ----------\n    Tr_K : float\n        Radiometric composite temperature (Kelvin).\n    vza : float\n        View Zenith Angle (degrees).\n    T_A_K : float\n        Air temperature (Kelvin).\n    u : float\n        Wind speed above the canopy (m s-1).\n    ea : float\n        Water vapour pressure above the canopy (mb).\n    p : float\n        Atmospheric pressure (mb), use 1013 mb by default.\n    Sn_C : float\n        Canopy net shortwave radiation (W m-2).\n    Sn_S : float\n        Soil net shortwave radiation (W m-2).\n    L_dn : float\n        Downwelling longwave radiation (W m-2).\n    LAI : float\n        Effective Leaf Area Index (m2 m-2).\n    hc : float\n        Canopy height (m).\n    emis_C : float\n        Leaf emissivity.\n    emis_S : flaot\n        Soil emissivity.\n    z_0M : float\n        Aerodynamic surface roughness length for momentum transfer (m).\n    d_0 : float\n        Zero-plane displacement height (m).\n    z_u : float\n        Height of measurement of windspeed (m).\n    z_T : float\n        Height of measurement of air temperature (m).\n    leaf_width : float, optional\n        average/effective leaf width (m).\n    z0_soil : float, optional\n        bare soil aerodynamic roughness length (m).\n    alpha_PT : float, optional\n        Priestley Taylor coeffient for canopy potential transpiration,\n        use 1.26 by default.\n    x_LAD : float, optional\n        Campbell 1990 leaf inclination distribution function chi parameter.\n    f_c : float, optional\n        Fractional cover.\n    f_g : float, optional\n        Fraction of vegetation that is green.\n    w_C : float, optional\n        Canopy width to height ratio.\n    resistance_form : int, optional\n        Flag to determine which Resistances R_x, R_S model to use.\n            * 0 [Default] Norman et al 1995 and Kustas et al 1999.\n            * 1 : Choudhury and Monteith 1988.\n            * 2 : McNaughton and Van der Hurk 1995.\n    calcG_params : list[list,float or array], optional\n        Method to calculate soil heat flux,parameters.\n            * [[1],G_ratio]: default, estimate G as a ratio of Rn_S, default Gratio=0.35.\n            * [[0],G_constant] : Use a constant G, usually use 0 to ignore the computation of G.\n            * [[2,Amplitude,phase_shift,shape],time] : estimate G from Santanello and Friedl with G_param list of parameters (see :func:`~TSEB.calc_G_time_diff`).\n    UseL : float or None, optional\n        If included, its value will be used to force the Moning-Obukhov stability length.\n    Returns\n    -------\n    flag : int\n        Quality flag, see Appendix for description.\n    T_S : float\n        Soil temperature  (Kelvin).\n    T_C : float\n        Canopy temperature  (Kelvin).\n    T_AC : float\n        Air temperature at the canopy interface (Kelvin).\n    L_nS : float\n        Soil net longwave radiation (W m-2)\n    L_nC : float\n        Canopy net longwave radiation (W m-2)\n    LE_C : float\n        Canopy latent heat flux (W m-2).\n    H_C : float\n        Canopy sensible heat flux (W m-2).\n    LE_S : float\n        Soil latent heat flux (W m-2).\n    H_S : float\n        Soil sensible heat flux (W m-2).\n    G : float\n        Soil heat flux (W m-2).\n    R_S : float\n        Soil aerodynamic resistance to heat transport (s m-1).\n    R_x : float\n        Bulk canopy aerodynamic resistance to heat transport (s m-1).\n    R_A : float\n        Aerodynamic resistance to heat transport (s m-1).\n    u_friction : float\n        Friction velocity (m s-1).\n    L : float\n        Monin-Obuhkov length (m).\n    n_iterations : int\n        number of iterations until convergence of L.\n    References\n    ----------\n    .. [Norman1995] J.M. Norman, W.P. Kustas, K.S. Humes, Source approach for estimating\n        soil and vegetation energy fluxes in observations of directional radiometric\n        surface temperature, Agricultural and Forest Meteorology, Volume 77, Issues 3-4,\n        Pages 263-293,\n        http://dx.doi.org/10.1016/0168-1923(95)02265-Y.\n    .. [Kustas1999] William P Kustas, John M Norman, Evaluation of soil and vegetation heat\n        flux predictions using a simple two-source model with radiometric temperatures for\n        partial canopy cover, Agricultural and Forest Meteorology, Volume 94, Issue 1,\n        Pages 13-29,\n        http://dx.doi.org/10.1016/S0168-1923(99)00005-2.\n    '''\n\n    # Convert input float scalars to arrays and parameters size\n    Tr_K = np.asarray(Tr_K)\n#    (vza,\n#     T_A_K,\n#     u,\n#     ea,\n#     p,\n#     Sn_C,\n#     Sn_S,\n#     L_dn,\n#     LAI,\n#     hc,\n#     emis_C,\n#     emis_S,\n#     z_0M,\n#     d_0,\n#     z_u,\n#     z_T,\n#     nullMask,\n#     leaf_width,     \n#     z0_soil,\n#     alpha_PT,\n#     x_LAD,\n#     f_c,\n#     f_g,\n#     w_C,\n#     calcG_array) = map(_check_default_parameter_size,\n#                        [vza,\n#                         T_A_K,\n#                         u,\n#                         ea,\n#                         p,\n#                         Sn_C,\n#                         Sn_S,\n#                         L_dn,\n#                         LAI,\n#                         hc,\n#                         emis_C,\n#                         emis_S,\n#                         z_0M,\n#                         d_0,\n#                         z_u,\n#                         z_T,\n#                         nullMask,\n#                         leaf_width,\n#                         z0_soil,\n#                         alpha_PT,\n#                         x_LAD,\n#                         f_c,\n#                         f_g,\n#                         w_C,\n#                         calcG_params[1]],\n#                        [Tr_K] * 24)\n    calcG_array[1] = _check_default_parameter_size(calcG_array[1],Tr_K)\n    # Create the output variables\n    [flag, T_S, T_C, T_AC, Ln_S, Ln_C, LE_C, H_C, LE_S, H_S, G, R_S, R_x,\n        R_A, iterations] = [np.zeros(Tr_K.shape) for i in range(15)]\n\n    # iteration of the Monin-Obukhov length\n    if isinstance(UseL, bool):\n        # Initially assume stable atmospheric conditions and set variables for\n        L = np.asarray(np.zeros(T_S.shape) + np.inf)\n        L = np.asarray(np.zeros(T_S.shape))\n        max_iterations = ITERATIONS\n    else:  # We force Monin-Obukhov lenght to the provided array/value\n        L = np.asarray(np.ones(T_S.shape) * UseL)\n        max_iterations = 1  # No iteration\n    # Calculate the general parameters\n    if ea.sum() == 0.0:\n        z = 350.0\n        rho = 101.3*((((T_A_K)-(0.0065*z))/(T_A_K))**5.26)/1.01/(T_A_K)/0.287\n        c_p = np.tile(1004.16,np.shape(T_A_K))\n    else:\n        rho = calc_rho(p, ea, T_A_K)  # Air density\n        c_p = calc_c_p(p, ea)  # Heat capacity of air\n    z_0H = calc_z_0H(z_0M, kB=kB)  # Roughness length for heat transport\n\n    # Calculate LAI dependent parameters for dataset where LAI > 0\n    omega0 = calc_omega0_Kustas(LAI, f_c, x_LAD=x_LAD, isLAIeff=True)\n    F = np.asarray(LAI / f_c)  # Real LAI\n    # Fraction of vegetation observed by the sensor\n    f_theta = calc_F_theta_campbell(vza, F, w_C=w_C, Omega0=omega0, x_LAD=x_LAD)\n\n    # Initially assume stable atmospheric conditions and set variables for\n    # iteration of the Monin-Obukhov length\n    u_friction = calc_u_star(u, z_u, L, d_0, z_0M)\n    u_friction = np.asarray(np.maximum(u_friction_min, u_friction))\n    L_old = np.ones(Tr_K.shape)\n    L_diff = np.asarray(np.ones(Tr_K.shape))\n    # First assume that canopy temperature equals the minumum of Air or\n    # radiometric T\n    T_C = np.asarray(np.minimum(Tr_K, T_A_K))\n    flag, T_S = calc_T_S(Tr_K, T_C, f_theta)\n    flag[nullMask==-9999]=255\n    iterMask = np.zeros(LAI.shape)\n    conv1 = 0.0\n    # Outer loop for estimating stability.\n    # Stops when difference in consecutives L is below a given threshold\n    for n_iterations in range(max_iterations):\n        i = flag != 255\n        #if np.all(L_diff[i] < L_thres):\n        if conv1 > 0.98:\n            #print(\"Finished interation with a max. L diff: \" + str(np.max(L_diff)))\n            break\n#        print(\"Iteration \" + str(n_iterations) +\n#              \", max. L diff: \" + str(np.max(L_diff)))\n        iterations[\n            np.logical_and(\n                L_diff >= L_thres,\n                flag != 255)] = n_iterations\n\n        # Inner loop to iterativelly reduce alpha_PT in case latent heat flux\n        # from the soil is negative. The initial assumption is of potential\n        # canopy transpiration.\n        flag[np.logical_and(L_diff >= L_thres, flag != 255)] = 0\n        LE_S[np.logical_and(L_diff >= L_thres, flag != 255)] = -1\n        alpha_PT_rec = np.asarray(alpha_PT + 0.1)\n        while np.any(LE_S[i] < 0):\n            i = np.logical_and.reduce(\n                (LE_S < 0, L_diff >= L_thres, flag != 255))\n\n            alpha_PT_rec[i] -= 0.1\n\n            # There cannot be negative transpiration from the vegetation\n            alpha_PT_rec[alpha_PT_rec <= 0.0] = 0.0\n            flag[np.logical_and(i, alpha_PT_rec == 0.0)] = 5\n\n            flag[\n                np.logical_and.reduce(\n                    (i, alpha_PT_rec < alpha_PT, alpha_PT_rec > 0.0))] = 3\n\n            # Calculate the aerodynamic resistance\n            R_A[i] = calc_R_A(z_T[i], u_friction[i], L[i], d_0[i], z_0H[i])\n            # Calculate soil and canopy resistances\n            U_C = calc_u_C_star(\n                u_friction[i], hc[i], d_0[i], z_0M[i], L=L[i])\n            if resistance_form == 0:\n                # Wind speed is highly attenuated within the canopy volume\n                u_d_zm = calc_u_Goudriaan(\n                    U_C, hc[i], F[i], leaf_width[i], d_0[i] + z_0M[i])\n    \n                # Vegetation in series with soil, i.e. well mixed, so we use\n                # the landscape LAI\n                R_x[i] = calc_R_x_Norman(LAI[i], leaf_width[i], u_d_zm)\n                i = np.logical_and.reduce(\n                (LE_S < 0, flag != 255, L_diff >= L_thres,\n                 np.logical_not(np.isnan(R_x))))\n                # Calculate soil and canopy resistances\n                U_C = calc_u_C_star(\n                u_friction[i], hc[i], d_0[i], z_0M[i], L=L[i])\n                # Clumped vegetation enhanced wind speed for the soil surface\n                u_S = calc_u_Goudriaan(\n                    U_C, hc[i], omega0[i] * F[i], leaf_width[i], z0_soil[i])\n                R_S[i] = calc_R_S_Kustas(u_S, T_S[i] - T_C[i])\n            elif resistance_form == 1:\n                # Vegetation in series with soil, i.e. well mixed, so we use\n                # the landscape LAI\n                R_x[i] = calc_R_x_Choudhury(U_C, LAI[i], leaf_width[i])\n                R_S[i] = calc_R_S_Choudhury(\n                    u_friction[i], hc[i], z_0M[i], d_0[i], z_u[i], z0_soil[i])\n            elif resistance_form == 2:\n                # Vegetation in series with soil, i.e. well mixed, so we use\n                # the landscape LAI\n                R_x[i] = calc_R_x_McNaughton(\n                    LAI[i], leaf_width[i], u_friction[i])\n                R_S[i] = calc_R_S_McNaughton(u_friction[i])\n            elif resistance_form == 3:\n                # Clumped vegetation enhanced wind speed for the soil surface\n                alpha_k = calc_A_Goudriaan(\n                    hc[i], omega0[i] * F[i], leaf_width[i])\n                # Wind speed is highly attenuated within the canopy volume\n                alpha_prime = calc_A_Goudriaan(hc[i], F[i], leaf_width[i])\n                # Vegetation in series with soil, i.e. well mixed, so we use\n                # the landscape LAI\n                R_x[i] = calc_R_x_Choudhury(\n                    U_C, LAI[i], leaf_width[i], alpha_prime=alpha_prime)\n                R_S[i] = calc_R_S_Choudhury(u_friction[i], hc[i], z_0M[i], d_0[\n                                               i], z_u, z0_soil[i], alpha_k=alpha_k)\n            else:\n                # Clumped vegetation enhanced wind speed for the soil surface\n                u_S = calc_u_Goudriaan(\n                    U_C, hc[i], omega0[i] * F[i], leaf_width[i], z0_soil[i])\n                # Wind speed is highly attenuated within the canopy volume\n                u_d_zm = calc_u_Goudriaan(\n                    U_C, hc[i], F[i], leaf_width[i], d_0[i] + z_0M[i])\n                # Vegetation in series with soil, i.e. well mixed, so we use\n                # the landscape LAI\n                R_x[i] = calc_R_x_Norman(LAI[i], leaf_width[i], u_d_zm)\n                R_S[i] = calc_R_S_Kustas(u_S, T_S[i] - T_C[i])\n            R_S = np.asarray(np.maximum(1e-3, R_S))\n            R_x = np.asarray(np.maximum(1e-3, R_x))\n            R_A = np.asarray(np.maximum(1e-3, R_A))\n\n            # Calculate net longwave radiation with current values of T_C and T_S\n            Ln_C[i], Ln_S[i] = calc_L_n_Kustas(\n                T_C[i], T_S[i], L_dn[i], LAI[i], emis_C[i], emis_S[i])\n            delta_Rn = Sn_C + Ln_C\n            Rn_S = Sn_S + Ln_S\n            # Calculate the canopy and soil temperatures using the Priestley\n            # Taylor appoach\n            H_C[i] = calc_H_C_PT(\n                delta_Rn[i],\n                f_g[i],\n                T_A_K[i],\n                p[i],\n                c_p[i],\n                alpha_PT_rec[i])\n            T_C[i] = calc_T_C_series(Tr_K[i], T_A_K[i], R_A[i], R_x[i], R_S[\n                                   i], f_theta[i], H_C[i], rho[i], c_p[i])\n\n            # Calculate soil temperature\n            flag_t = np.zeros(flag.shape)\n            flag_t[i], T_S[i] = calc_T_S(Tr_K[i], T_C[i], f_theta[i])\n            flag[flag_t == 255] = 255\n            LE_S[flag_t == 255] = 0\n\n            # Recalculate soil resistance using new soil temperature\n            if resistance_form == 0:\n                R_S[i] = calc_R_S_Kustas(u_S, T_S[i] - T_C[i])\n                R_S = np.asarray(np.maximum(1e-3, R_S))\n\n            i = np.logical_and.reduce(\n                (LE_S < 0, flag != 255, L_diff >= L_thres,\n                 np.logical_not(np.isnan(R_x))))\n\n            # Get air temperature at canopy interface\n            T_AC[i] = ((T_A_K[i] / R_A[i] + T_S[i] / R_S[i] + T_C[i] / R_x[i])\n                       / (1.0 / R_A[i] + 1.0 / R_S[i] + 1.0 / R_x[i]))\n\n            # Calculate soil fluxes\n            H_S[i] = rho[i] * c_p[i] * (T_S[i] - T_AC[i]) / R_S[i]\n\n            # Compute Soil Heat Flux Ratio\n            #G[i] = calc_G([calcG_array[0], calcG_array], Rn_S, i)\n            G[i]=calc_G_ratio(Rn_S[i], calcG_array[1][i])\n\n            # Estimate latent heat fluxes as residual of energy balance at the\n            # soil and the canopy\n            LE_S[i] = Rn_S[i] - G[i] - H_S[i]\n            LE_C[i] = delta_Rn[i] - H_C[i]\n\n            # Special case if there is no transpiration from vegetation.\n            # In that case, there should also be no evaporation from the soil\n            # and the energy at the soil should be conserved.\n            # See end of appendix A1 in Guzinski et al. (2015).\n            noT = np.logical_and(i, LE_C == 0)\n            H_S[noT] = np.minimum(H_S[noT], Rn_S[noT] - G[noT])\n            G[noT] = np.maximum(G[noT], Rn_S[noT] - H_S[noT])\n            LE_S[noT] = 0\n\n            # Calculate total fluxes\n            H = np.asarray(H_C + H_S)\n            LE = np.asarray(LE_C + LE_S)\n            # Now L can be recalculated and the difference between iterations\n            # derived\n            if isinstance(UseL, bool):\n                L[i] = calc_L(\n                    u_friction[i],\n                    T_A_K[i],\n                    rho[i],\n                    c_p[i],\n                    H[i],\n                    LE[i])\n                # Calculate again the friction velocity with the new stability\n                # correctios\n                u_friction[i] = calc_u_star(\n                    u[i], z_u[i], L[i], d_0[i], z_0M[i])\n                u_friction = np.asarray(np.maximum(u_friction_min, u_friction))\n\n        if isinstance(UseL, bool):\n            L_diff = np.asarray(np.fabs(L - L_old) / np.fabs(L_old))\n            #L_diff[np.isnan(L_diff)] = float('inf')\n            L_old = np.array(L)\n            L_old[L_old == 0] = 1e-36\n            iterMask[np.where(L_diff < L_thres)]=1.0\n            conv1 = np.sum(iterMask)/(LAI.size)\n            #print 'TSEB convergence=%f percent' % (conv1*100.)\n\n    (flag,\n     T_S,\n     T_C,\n     T_AC,\n     L_nS,\n     L_nC,\n     LE_C,\n     H_C,\n     LE_S,\n     H_S,\n     G,\n     R_S,\n     R_x,\n     R_A,\n     u_friction,\n     L,\n     n_iterations) = map(np.asarray,\n                         (flag,\n                          T_S,\n                          T_C,\n                          T_AC,\n                          Ln_S,\n                          Ln_C,\n                          LE_C,\n                          H_C,\n                          LE_S,\n                          H_S,\n                          G,\n                          R_S,\n                          R_x,\n                          R_A,\n                          u_friction,\n                          L,\n                          iterations))\n\n    return flag, T_S, T_C, T_AC, L_nS, L_nC, LE_C, H_C, LE_S, H_S, G, R_S, R_x, R_A, u_friction, L, n_iterations\n\n\n\n\ndef calc_F_theta_campbell(theta, F, w_C=1, Omega0=1, x_LAD=1):\n    '''Calculates the fraction of vegetatinon observed at an angle.\n    Parameters\n    ----------\n    theta : float\n        Angle of incidence (degrees).\n    F : float\n        Real Leaf (Plant) Area Index.\n    w_C : float\n        Ratio of vegetation height versus width, optional (default = 1).\n    Omega0 : float\n        Clumping index at nadir, optional (default =1).\n    x_LAD : float\n        Chi parameter for the ellipsoidal Leaf Angle Distribution function,\n        use x_LAD=1 for a spherical LAD.\n    Returns\n    -------\n    f_theta : float\n        fraction of vegetation obsserved at an angle.\n    References\n    ----------\n    .. [Campbell1998] Campbell, G. S. & Norman, J. M. (1998), An introduction to environmental\n        biophysics. Springer, New York\n        https://archive.org/details/AnIntroductionToEnvironmentalBiophysics.\n    .. [Norman1995] J.M. Norman, W.P. Kustas, K.S. Humes, Source approach for estimating\n        soil and vegetation energy fluxes in observations of directional radiometric\n        surface temperature, Agricultural and Forest Meteorology, Volume 77, Issues 3-4,\n        Pages 263-293, http://dx.doi.org/10.1016/0168-1923(95)02265-Y.\n    '''\n\n    # First calcualte the angular clumping factor Omega based on eq (3) from\n    # W.P. Kustas, J.M. Norman,  Agricultural and Forest Meteorology 94 (1999)\n    # CHECK: should theta here be in degrees or radians\n    OmegaTheta = Omega0 / (Omega0 + (1.0 - Omega0) *\n                           np.exp(-2.2 * np.radians(theta)**(3.8 - 0.46 * w_C)))\n    # Estimate the beam extinction coefficient based on a elipsoidal LAD function\n    # Eq. 15.4 of Campbell and Norman (1998)\n    K_be = calc_K_be_Campbell(theta, x_LAD)\n    ftheta = 1.0 - np.exp(-K_be * OmegaTheta * F)\n    return np.asarray(ftheta)\n\n\ndef calc_G(calcG_params, Rn_S, i=None):\n\n    if i is None:\n        i = np.ones(Rn_S.shape, dtype=bool)\n    if calcG_params[0][0] == 0:\n        G = calcG_params[1][i]\n    elif calcG_params[0][0] == 1:\n        G = calc_G_ratio(Rn_S[i], calcG_params[1][i])\n    elif calcG_params[0][0] == 2:\n        G = calc_G_time_diff(Rn_S[i], [calcG_params[1][i], calcG_params[\n                           0][1], calcG_params[0][2], calcG_params[0][3]])\n    return np.asarray(G)\n\n\ndef calc_G_time_diff(R_n, G_param=[12.0, 0.35, 3.0, 24.0]):\n    ''' Estimates Soil Heat Flux as function of time and net radiation.\n    Parameters\n    ----------\n    R_n : float\n        Net radiation (W m-2).\n    G_param : tuple(float,float,float,float)\n        tuple with parameters required (time, Amplitude,phase_shift,shape).\n            time: float\n                time of interest (decimal hours).\n            Amplitude : float\n                maximum value of G/Rn, amplitude, default=0.35.\n            phase_shift : float\n                shift of peak G relative to solar noon (default 3hrs after noon).\n            shape : float\n                shape of G/Rn, default 24 hrs.\n    Returns\n    -------\n    G : float\n        Soil heat flux (W m-2).\n    References\n    ----------\n    .. [Santanello2003] Joseph A. Santanello Jr. and Mark A. Friedl, 2003: Diurnal Covariation in\n        Soil Heat Flux and Net Radiation. J. Appl. Meteor., 42, 851-862,\n        http://dx.doi.org/10.1175/1520-0450(2003)042<0851:DCISHF>2.0.CO;2.'''\n\n    # Get parameters\n    time = 12.0 - G_param[0]\n    A = G_param[1]\n    phase_shift = G_param[2]\n    B = G_param[3]\n    G_ratio = A * np.cos(2.0 * np.pi * (time + phase_shift) / B)\n    G = R_n * G_ratio\n    return np.asarray(G)\n\n\ndef calc_G_ratio(Rn_S, G_ratio=0.35):\n    '''Estimates Soil Heat Flux as ratio of net soil radiation.\n    Parameters\n    ----------\n    Rn_S : float\n        Net soil radiation (W m-2).\n    G_ratio : float, optional\n        G/Rn_S ratio, default=0.35.\n    Returns\n    -------\n    G : float\n        Soil heat flux (W m-2).\n    References\n    ----------\n    .. [Choudhury1987] B.J. Choudhury, S.B. Idso, R.J. Reginato, Analysis of an empirical model\n        for soil heat flux under a growing wheat crop for estimating evaporation by an\n        infrared-temperature based energy balance equation, Agricultural and Forest Meteorology,\n        Volume 39, Issue 4, 1987, Pages 283-297,\n        http://dx.doi.org/10.1016/0168-1923(87)90021-9.\n    '''\n\n    G = G_ratio * Rn_S\n    return np.asarray(G)\n\n\n\ndef calc_H_C_PT(delta_R_ni, f_g, T_A_K, P, c_p, alpha):\n    '''Calculates canopy sensible heat flux based on the Priestley and Taylor formula.\n    Parameters\n    ----------\n    delta_R_ni : float\n        net radiation divergence of the vegetative canopy (W m-2).\n    f_g : float\n        fraction of vegetative canopy that is green.\n    T_A_K : float\n        air temperature (Kelvin).\n    P : float\n        air pressure (mb).\n    c_p : float\n        heat capacity of moist air (J kg-1 K-1).\n    alpha : float\n        the Priestley Taylor parameter.\n    Returns\n    -------\n    H_C : float\n        Canopy sensible heat flux (W m-2).\n    References\n    ----------\n    Equation 14 in [Norman1995]_\n    '''\n\n    # slope of the saturation pressure curve (kPa./deg C)\n    s = calc_delta_vapor_pressure(T_A_K)\n    s = s * 10  # to mb\n    # latent heat of vaporisation (MJ./kg)\n    Lambda = calc_lambda(T_A_K)\n    # psychrometric constant (mb C-1)\n    gama = calc_psicr(P, Lambda)\n    s_gama = s / (s + gama)\n    H_C = delta_R_ni * (1.0 - alpha * f_g * s_gama)\n    return np.asarray(H_C)\n\ndef calc_T_C_series(Tr_K, T_A_K, R_A, R_x, R_S, f_theta, H_C, rho, c_p):\n    '''Estimates canopy temperature from canopy sensible heat flux and\n    resistance network in series.\n    Parameters\n    ----------\n    Tr_K : float\n        Directional Radiometric Temperature (K).\n    T_A_K : float\n        Air Temperature (K).\n    R_A : float\n        Aerodynamic resistance to heat transport (s m-1).\n    R_x : float\n        Bulk aerodynamic resistance to heat transport at the canopy boundary layer (s m-1).\n    R_S : float\n        Aerodynamic resistance to heat transport at the soil boundary layer (s m-1).\n    f_theta : float\n        Fraction of vegetation observed.\n    H_C : float\n        Sensible heat flux of the canopy (W m-2).\n    rho : float\n        Density of air (km m-3).\n    c_p : float\n        Heat capacity of air at constant pressure (J kg-1 K-1).\n    Returns\n    -------\n    T_C : float\n        Canopy temperature (K).\n    References\n    ----------\n    Eqs. A5-A13 in [Norman1995]_'''\n\n    T_R_K_4 = Tr_K**4\n    # equation A7 from Norman 1995, linear approximation of temperature of the\n    # canopy\n    T_C_lin = ((T_A_K / R_A + Tr_K / (R_S * (1.0 - f_theta))\n                + H_C * R_x / (rho * c_p) * (1.0 / R_A + 1.0 / R_S + 1.0 / R_x))\n               / (1.0 / R_A + 1.0 / R_S + f_theta / (R_S * (1.0 - f_theta))))\n    # equation A12 from Norman 1995\n    T_D = (T_C_lin * (1 + R_S / R_A) - H_C * R_x / (rho * c_p)\n           * (1.0 + R_S / R_x + R_S / R_A) - T_A_K * R_S / R_A)\n    # equation A11 from Norman 1995\n    delta_T_C = ((T_R_K_4 - f_theta * T_C_lin**4 - (1.0 - f_theta) * T_D**4) / \\\n                 (4.0 * (1.0 - f_theta) * T_D**3 * (1.0 + R_S / R_A) + 4.0 * f_theta * T_C_lin**3))\n    # get canopy temperature in Kelvin\n    T_C = T_C_lin + delta_T_C\n    return np.asarray(T_C)\n\n\ndef calc_T_S(T_R, T_C, f_theta):\n    '''Estimates soil temperature from the directional LST.\n    Parameters\n    ----------\n    T_R : float\n        Directional Radiometric Temperature (K).\n    T_C : float\n        Canopy Temperature (K).\n    f_theta : float\n        Fraction of vegetation observed.\n    Returns\n    -------\n    flag : float\n        Error flag if inversion not possible (255).\n    T_S: float\n        Soil temperature (K).\n    References\n    ----------\n    Eq. 1 in [Norman1995]_'''\n\n    # Convert the input scalars to numpy arrays\n    T_R, T_C, f_theta = map(np.asarray, (T_R, T_C, f_theta))\n    T_temp = T_R**4 - f_theta * T_C**4\n    T_S = np.zeros(T_R.shape)\n    flag = np.zeros(T_R.shape)\n\n    # Succesfull inversion\n    T_S[T_temp >= 0] = (T_temp[T_temp >= 0] /\n                        (1.0 - f_theta[T_temp >= 0]))**0.25\n\n    # Unsuccesfull inversion\n    T_S[T_temp < 0] = 1e-6\n    flag[T_temp < 0] = 255\n\n    return np.asarray(flag), np.asarray(T_S)\n\n\ndef _check_default_parameter_size(parameter, input_array):\n\n    parameter = np.asarray(parameter)\n    if parameter.size == 1:\n        parameter = np.ones(input_array.shape) * parameter\n        return np.asarray(parameter)\n    elif parameter.shape != input_array.shape:\n        raise ValueError(\n            'dimension mismatch between parameter array and input array with shapes %s and %s' %\n            (parameter.shape, input_array.shape))\n    else:\n        return np.asarray(parameter)\n", "meta": {"hexsha": "ee427765c0e57d5df5bd9e20ef0ed22e85e2c41a", "size": 29760, "ext": "py", "lang": "Python", "max_stars_repo_path": "pydisalexi/TSEB.py", "max_stars_repo_name": "Yun1/projectMAS", "max_stars_repo_head_hexsha": "fb25dc50f2c70a62aa0854aca9c4295d4221b843", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-24T19:44:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-08T16:10:17.000Z", "max_issues_repo_path": "pydisalexi/TSEB.py", "max_issues_repo_name": "Yun1/projectMAS", "max_issues_repo_head_hexsha": "fb25dc50f2c70a62aa0854aca9c4295d4221b843", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pydisalexi/TSEB.py", "max_forks_repo_name": "Yun1/projectMAS", "max_forks_repo_head_hexsha": "fb25dc50f2c70a62aa0854aca9c4295d4221b843", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-09-20T12:54:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-08T17:47:09.000Z", "avg_line_length": 37.6708860759, "max_line_length": 162, "alphanum_fraction": 0.5736895161, "include": true, "reason": "import numpy", "num_tokens": 8236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.2877678096528436, "lm_q1q2_score": 0.15844707555879872}}
{"text": "\"\"\"\nDefines the CloudNoiseModel class and supporting functions\n\"\"\"\n#***************************************************************************************************\n# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).\n# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights\n# in this software.\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n# in compliance with the License.  You may obtain a copy of the License at\n# http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory.\n#***************************************************************************************************\n\nimport collections as _collections\nimport itertools as _itertools\nimport warnings as _warnings\n\nimport numpy as _np\nimport scipy.sparse as _sps\n\nfrom pygsti.baseobjs import statespace as _statespace\nfrom pygsti.models.implicitmodel import ImplicitOpModel as _ImplicitOpModel, _init_spam_layers\nfrom pygsti.models.layerrules import LayerRules as _LayerRules\nfrom pygsti.models.memberdict import OrderedMemberDict as _OrderedMemberDict\nfrom pygsti.evotypes import Evotype as _Evotype\nfrom pygsti.forwardsims.forwardsim import ForwardSimulator as _FSim\nfrom pygsti.forwardsims.mapforwardsim import MapForwardSimulator as _MapFSim\nfrom pygsti.forwardsims.matrixforwardsim import MatrixForwardSimulator as _MatrixFSim\nfrom pygsti.modelmembers import operations as _op\nfrom pygsti.modelmembers import povms as _povm\nfrom pygsti.modelmembers import states as _state\nfrom pygsti.modelmembers.operations import opfactory as _opfactory\nfrom pygsti.modelmembers.modelmembergraph import ModelMemberGraph as _MMGraph\nfrom pygsti.baseobjs.basis import BuiltinBasis as _BuiltinBasis, ExplicitBasis as _ExplicitBasis\nfrom pygsti.baseobjs.label import Label as _Lbl, CircuitLabel as _CircuitLabel\nfrom pygsti.baseobjs.verbosityprinter import VerbosityPrinter as _VerbosityPrinter\nfrom pygsti.baseobjs.qubitgraph import QubitGraph as _QubitGraph\nfrom pygsti.tools import basistools as _bt\nfrom pygsti.tools import internalgates as _itgs\nfrom pygsti.tools import optools as _ot\nfrom pygsti.baseobjs.basisconstructors import sqrt2, id2x2, sigmax, sigmay, sigmaz\nfrom pygsti.processors.processorspec import ProcessorSpec as _ProcessorSpec, QubitProcessorSpec as _QubitProcessorSpec\n\n\nclass CloudNoiseModel(_ImplicitOpModel):\n    \"\"\"\n    A n-qudit model using a low-weight and geometrically local error model with a common \"global idle\" operation.\n\n    Parameters\n    ----------\n    processor_spec : ProcessorSpec\n        The processor specification to create a model for.  This object specifies the\n        gate names and unitaries for the processor, and their availability on the\n        processor.\n\n    gatedict : dict\n        A dictionary (an `OrderedDict` if you care about insertion order) that\n        associates with string-type gate names (e.g. `\"Gx\"`) :class:`LinearOperator`,\n        `numpy.ndarray`, or :class:`OpFactory` objects. When the objects may act on\n        fewer than the total number of qudits (determined by their dimension/shape) then\n        they are repeatedly embedded into operation on the entire state space as specified\n        by their availability within `processor_spec`.  These operations represent the ideal\n        target operations, and thus, any `LinearOperator` or `OpFactory` objects must be *static*,\n        i.e., have zero parameters.\n\n    prep_layers, povm_layers : None or operator or dict or list, optional\n        The SPAM operations as n-qudit layer operations.  If `None`, then\n        no preps (or POVMs) are created.  If a dict, then the keys are\n        labels and the values are layer operators.  If a list, then the\n        elements are layer operators and the labels will be assigned as\n        \"rhoX\" and \"MX\" where X is an integer starting at 0.  If a single\n        layer operation is given, then this is used as the sole prep or\n        POVM and is assigned the label \"rho0\" or \"Mdefault\" respectively.\n\n    build_cloudnoise_fn : function, optional\n        A function which takes a single :class:`Label` as an argument and\n        returns the cloud-noise operation for that primitive layer\n        operation.  Note that if `errcomp_type=\"gates\"` the returned\n        operator should be a superoperator whereas if\n        `errcomp_type=\"errorgens\"` then the returned operator should be\n        an error generator (not yet exponentiated).\n\n    build_cloudkey_fn : function, optional\n        An function which takes a single :class:`Label` as an argument and\n        returns a \"cloud key\" for that primitive layer.  The \"cloud\" is the\n        set of qudits that the error (the operator returned from\n        `build_cloudnoise_fn`) touches -- and the \"key\" returned from this\n        function is meant to identify that cloud.  This is used to keep track\n        of which primitive layer-labels correspond to the same cloud - e.g.\n        the cloud-key for (\"Gx\",2) and (\"Gy\",2) might be the same and could\n        be processed together when selecing sequences that amplify the parameters\n        in the cloud-noise operations for these two labels.  The return value\n        should be something hashable with the property that two noise\n        which act on the same qudits should have the same cloud key.\n\n    simulator : ForwardSimulator or {\"auto\", \"matrix\", \"map\"}\n        The circuit simulator used to compute any\n        requested probabilities, e.g. from :method:`probs` or\n        :method:`bulk_probs`.  The default value of `\"auto\"` automatically\n        selects the simulation type, and is usually what you want. Other\n        special allowed values are:\n\n        - \"matrix\" : op_matrix-op_matrix products are computed and\n          cached to get composite gates which can then quickly simulate\n          a circuit for any preparation and outcome.  High memory demand;\n          best for a small number of (1 or 2) qubits.\n        - \"map\" : op_matrix-state_vector products are repeatedly computed\n          to simulate circuits.  Slower for a small number of qubits, but\n          faster and more memory efficient for higher numbers of qubits (3+).\n\n    evotype : Evotype or str, optional\n        The evolution type of this model, describing how states are\n        represented.  The special value `\"default\"` is equivalent\n        to specifying the value of `pygsti.evotypes.Evotype.default_evotype`.\n\n    errcomp_type : {\"gates\",\"errorgens\"}\n        How errors are composed when creating layer operations in the created\n        model.  `\"gates\"` means that the errors on multiple gates in a single\n        layer are composed as separate and subsequent processes.  Specifically,\n        the layer operation has the form `Composed(target,idleErr,cloudErr)`\n        where `target` is a composition of all the ideal gate operations in the\n        layer, `idleErr` is idle error (`.operation_blks['layers']['globalIdle']`),\n        and `cloudErr` is the composition (ordered as layer-label) of cloud-\n        noise contributions, i.e. a map that acts as the product of exponentiated\n        error-generator matrices.  `\"errorgens\"` means that layer operations\n        have the form `Composed(target, error)` where `target` is as above and\n        `error` results from composing the idle and cloud-noise error\n        *generators*, i.e. a map that acts as the exponentiated sum of error\n        generators (ordering is irrelevant in this case).\n\n    implicit_idle_mode : {'none', 'add_global', 'pad_1Q'}\n        The way idle operations are added implicitly within the created model. `\"none\"`\n        doesn't add any \"extra\" idle operations when there is a layer that contains some\n        gates but not gates on all the qubits.  `\"add_global\"` adds the global idle operation,\n        i.e., the operation for a global idle layer (zero gates - a completely empty layer),\n        to every layer that is simulated, using the global idle as a background idle that always\n        occurs regardless of the operation.  `\"pad_1Q\"` applies the 1-qubit idle gate (if one\n        exists) to all idling qubits within a circuit layer.\n\n    verbosity : int, optional\n        An integer >= 0 dictating how must output to send to stdout.\n    \"\"\"\n\n    def __init__(self, processor_spec, gatedict,\n                 prep_layers=None, povm_layers=None,\n                 build_cloudnoise_fn=None, build_cloudkey_fn=None,\n                 simulator=\"map\", evotype=\"default\", errcomp_type=\"gates\",\n                 implicit_idle_mode=\"none\", verbosity=0):\n\n        qudit_labels = processor_spec.qudit_labels\n        state_space = _statespace.QubitSpace(qudit_labels) if isinstance(processor_spec, _QubitProcessorSpec) \\\n            else _statespace.QuditSpace(qudit_labels, processor_spec.qudit_udims)\n\n        simulator = _FSim.cast(simulator,\n                               state_space.num_qubits if isinstance(state_space, _statespace.QubitSpace) else None)\n        prefer_dense_reps = isinstance(simulator, _MatrixFSim)\n        evotype = _Evotype.cast(evotype, default_prefer_dense_reps=prefer_dense_reps)\n\n        # Build gate dictionaries. A value of `gatedict` can be an array, a LinearOperator, or an OpFactory.\n        # For later processing, we'll create mm_gatedict to contain each item as a ModelMember.  For cloud-\n        # noise models, these gate operations should be *static* (no parameters) as they represent the target\n        # operations and all noise (and parameters) are assumed to enter through the cloudnoise members.\n        mm_gatedict = _collections.OrderedDict()  # static *target* ops as ModelMembers\n        for key, gate in gatedict.items():\n            if isinstance(gate, _op.LinearOperator):\n                assert(gate.num_params == 0), \"Only *static* ideal operators are allowed in `gatedict`!\"\n                mm_gatedict[key] = gate\n            elif isinstance(gate, _opfactory.OpFactory):\n                assert(gate.num_params == 0), \"Only *static* ideal factories are allowed in `gatedict`!\"\n                mm_gatedict[key] = gate\n            else:  # presumably a numpy array or something like it:\n                mm_gatedict[key] = _op.StaticArbitraryOp(gate, evotype, state_space=None)  # use default state space\n            assert(mm_gatedict[key]._evotype == evotype), \\\n                (\"Custom gate object supplied in `gatedict` for key %s has evotype %s (!= expected %s)\"\n                 % (str(key), str(mm_gatedict[key]._evotype), str(evotype)))\n\n        #Set other members\n        self.processor_spec = processor_spec\n        self.errcomp_type = errcomp_type\n\n        idle_names = self.processor_spec.idle_gate_names\n        global_idle_name = self.processor_spec.global_idle_gate_name\n\n        # Set noisy_global_idle_name == global_idle_name if the global idle gate isn't the perfect identity\n        #  and if we're generating cloudnoise members (if we're not then layer rules could encouter a key error\n        #  if we let noisy_global_idle_name be non-None).\n        global_idle_gate = mm_gatedict.get(global_idle_name, None)\n        if (global_idle_gate is not None) and (build_cloudnoise_fn is not None) \\\n           and (build_cloudnoise_fn(self.processor_spec.global_idle_layer_label) is not None):\n            noisy_global_idle_name = global_idle_name\n        else:\n            noisy_global_idle_name = None\n\n        singleq_idle_layer_labels = {}\n        for idle_name in idle_names:\n            if self.processor_spec.gate_num_qubits(idle_name) == 1:\n                for idlelayer_sslbls in self.processor_spec.resolved_availability(idle_name, 'tuple'):\n                    if idlelayer_sslbls is None: continue  # case of 1Q model with \"global\" idle\n                    assert(len(idlelayer_sslbls) == 1)  # should be a 1-qubit gate!\n                    if idlelayer_sslbls not in singleq_idle_layer_labels:\n                        singleq_idle_layer_labels[idlelayer_sslbls] = _Lbl(idle_name, idlelayer_sslbls)\n        #assert(set(idle_names).issubset([global_idle_name])), \\\n        #    \"Only global idle operations are allowed in a CloudNoiseModel!\"\n\n        layer_rules = CloudNoiseLayerRules(errcomp_type, qudit_labels, implicit_idle_mode, singleq_idle_layer_labels,\n                                           noisy_global_idle_name)\n        super(CloudNoiseModel, self).__init__(state_space, layer_rules, \"pp\", simulator=simulator, evotype=evotype)\n\n        flags = {'auto_embed': False, 'match_parent_statespace': False,\n                 'match_parent_evotype': True, 'cast_to_type': None}\n        self.prep_blks['layers'] = _OrderedMemberDict(self, None, None, flags)\n        self.povm_blks['layers'] = _OrderedMemberDict(self, None, None, flags)\n        self.operation_blks['gates'] = _OrderedMemberDict(self, None, None, flags)\n        self.operation_blks['cloudnoise'] = _OrderedMemberDict(self, None, None, flags)\n        self.operation_blks['layers'] = _OrderedMemberDict(self, None, None, flags)\n        self.instrument_blks['layers'] = _OrderedMemberDict(self, None, None, flags)\n        self.factories['gates'] = _OrderedMemberDict(self, None, None, flags)\n        self.factories['cloudnoise'] = _OrderedMemberDict(self, None, None, flags)\n        self.factories['layers'] = _OrderedMemberDict(self, None, None, flags)\n\n        printer = _VerbosityPrinter.create_printer(verbosity)\n        printer.log(\"Creating a %d-qudit cloud-noise model\" % self.processor_spec.num_qudits)\n\n        # a dictionary of \"cloud\" objects\n        # keys = cloud identifiers, e.g. (target_qudit_indices, cloud_qudit_indices) tuples\n        # values = list of gate-labels giving the gates (primitive layers?) associated with that cloud (necessary?)\n        self._clouds = _collections.OrderedDict()\n\n        for gn in self.processor_spec.gate_names:\n            # process gate names (no sslbls, e.g. \"Gx\", not \"Gx:0\") - we'll check for the\n            # latter when we process the corresponding gate name's availability\n\n            gate_unitary = self.processor_spec.gate_unitaries[gn]\n            resolved_avail = self.processor_spec.resolved_availability(gn)\n            gate = mm_gatedict.get(gn, None)  # a static op or factory, no need to consider if \"independent\" (no params)\n            gate_is_factory = callable(gate_unitary) or isinstance(gate, _opfactory.OpFactory)\n            #gate_is_noiseless_identity = (gate is None) or \\\n            #    (isinstance(gate, _op.ComposedOp) and len(gate.factorops) == 0)\n\n            if gate is not None:  # (a gate name may not be in gatedict if it's an identity without any noise)\n                if gate_is_factory:\n                    self.factories['gates'][_Lbl(gn)] = gate\n                else:\n                    self.operation_blks['gates'][_Lbl(gn)] = gate\n\n            if callable(resolved_avail) or resolved_avail == '*':\n\n                # Target operation\n                if gate is not None:\n                    allowed_sslbls_fn = resolved_avail if callable(resolved_avail) else None\n                    gate_nQudits = self.processor_spec.gate_num_qudits(gn)\n                    printer.log(\"Creating %dQ %s gate on arbitrary qudits!!\" % (gate_nQudits, gn))\n                    self.factories['layers'][_Lbl(gn)] = _opfactory.EmbeddingOpFactory(\n                        state_space, gate, num_target_labels=gate_nQudits, allowed_sslbls_fn=allowed_sslbls_fn)\n                    # add any primitive ops for this embedding factory?\n\n                # Cloudnoise operation\n                if build_cloudnoise_fn is not None:\n                    cloudnoise = build_cloudnoise_fn(_Lbl(gn))\n                    if cloudnoise is not None:  # build function can return None to signify no noise\n                        assert (isinstance(cloudnoise, _opfactory.EmbeddingOpFactory)), \\\n                            (\"`build_cloudnoise_fn` must return an EmbeddingOpFactory for gate %s\"\n                             \" with arbitrary availability\") % gn\n                        self.factories['cloudnoise'][_Lbl(gn)] = cloudnoise\n\n            else:  # resolved_avail is a list/tuple of available sslbls for the current gate/factory\n                for inds in resolved_avail:  # inds are target qudit labels\n\n                    #Target operation\n                    if gate is not None:\n                        printer.log(\"Creating %dQ %s gate on qudits %s!!\"\n                                    % ((len(qudit_labels) if inds is None else len(inds)), gn, inds))\n                        assert(inds is None or _Lbl(gn, inds) not in gatedict), \\\n                            (\"Cloudnoise models do not accept primitive-op labels, e.g. %s, in `gatedict` as this dict \"\n                             \"specfies the ideal target gates. Perhaps make the cloudnoise depend on the target qudits \"\n                             \"of the %s gate?\") % (str(_Lbl(gn, inds)), gn)\n\n                        if gate_is_factory:\n                            self.factories['layers'][_Lbl(gn, inds)] = gate if (inds is None) else \\\n                                _opfactory.EmbeddedOpFactory(state_space, inds, gate)\n                            # add any primitive ops for this factory?\n                        else:\n                            self.operation_blks['layers'][_Lbl(gn, inds)] = gate if (inds is None) else \\\n                                _op.EmbeddedOp(state_space, inds, gate)\n\n                    #Cloudnoise operation\n                    if build_cloudnoise_fn is not None:\n                        cloudnoise = build_cloudnoise_fn(_Lbl(gn, inds))\n                        if cloudnoise is not None:  # build function can return None to signify no noise\n                            if isinstance(cloudnoise, _opfactory.OpFactory):\n                                self.factories['cloudnoise'][_Lbl(gn, inds)] = cloudnoise\n                            else:\n                                self.operation_blks['cloudnoise'][_Lbl(gn, inds)] = cloudnoise\n\n                    if build_cloudkey_fn is not None:\n                        # TODO: is there any way to get a default \"key\", e.g. the\n                        # qudits touched by the corresponding cloudnoise op?\n                        # need a way to identify a clound (e.g. Gx and Gy gates on some qudit will have *same* cloud)\n                        cloud_key = build_cloudkey_fn(_Lbl(gn, inds))\n                        if cloud_key not in self.clouds: self.clouds[cloud_key] = []\n                        self.clouds[cloud_key].append(_Lbl(gn, inds))\n                    #keep track of the primitive-layer labels in each cloud,\n                    # used to specify which gate parameters should be amplifiable by germs for a given cloud (?)\n                    # TODO CHECK THIS\n\n        _init_spam_layers(self, prep_layers, povm_layers)  # SPAM\n\n        printer.log(\"DONE! - created Model with nqudits=%d and op-blks=\" % self.state_space.num_qudits)\n        for op_blk_lbl, op_blk in self.operation_blks.items():\n            printer.log(\"  %s: %s\" % (op_blk_lbl, ', '.join(map(str, op_blk.keys()))))\n        self._clean_paramvec()\n\n    def create_processor_spec(self):\n        import copy as _copy\n        return _copy.deepcopy(self.processor_spec)\n\n    @property\n    def clouds(self):\n        \"\"\"\n        Returns the set of cloud-sets used when creating sequences which amplify the parameters of this model.\n\n        Returns\n        -------\n        dict\n        \"\"\"\n        return self._clouds\n\n    def _to_nice_serialization(self):\n        state = super()._to_nice_serialization()\n        state.update({'processor_spec': self.processor_spec.to_nice_serialization(),\n                      'error_composition_mode': self.errcomp_type,\n                      })\n        mmgraph = self.create_modelmember_graph()\n        state['modelmembers'] = mmgraph.create_serialization_dict()\n        return state\n\n    @classmethod\n    def _from_nice_serialization(cls, state):\n        state_space = _statespace.StateSpace.from_nice_serialization(state['state_space'])\n        #basis = _nice_serialization(state['basis'])\n        modelmembers = _MMGraph.load_modelmembers_from_serialization_dict(state['modelmembers'])\n        simulator = _FSim.from_nice_serialization(state['simulator'])\n        layer_rules = _LayerRules.from_nice_serialization(state['layer_rules'])\n        processor_spec = _ProcessorSpec.from_nice_serialization(state['processor_spec'])\n\n        # __init__ does too much, so we need to create an alternate __init__ function here:\n        mdl = cls.__new__(cls)\n        mdl.processor_spec = processor_spec\n        mdl.errcomp_type = state['error_composition_mode']\n        _ImplicitOpModel.__init__(mdl, state_space, layer_rules, 'pp',\n                                  simulator=simulator, evotype=state['evotype'])\n\n        flags = {'auto_embed': False, 'match_parent_statespace': False,\n                 'match_parent_evotype': True, 'cast_to_type': None}\n        mdl.prep_blks['layers'] = _OrderedMemberDict(mdl, None, None, flags, modelmembers.get('prep_blks|layers', []))\n        mdl.povm_blks['layers'] = _OrderedMemberDict(mdl, None, None, flags, modelmembers.get('povm_blks|layers', []))\n        mdl.operation_blks['gates'] = _OrderedMemberDict(mdl, None, None, flags,\n                                                         modelmembers.get('operation_blks|gates', []))\n        mdl.operation_blks['cloudnoise'] = _OrderedMemberDict(mdl, None, None, flags,\n                                                              modelmembers.get('operation_blks|cloudnoise', []))\n        mdl.operation_blks['layers'] = _OrderedMemberDict(mdl, None, None, flags,\n                                                          modelmembers.get('operation_blks|layers', []))\n        mdl.instrument_blks['layers'] = _OrderedMemberDict(mdl, None, None, flags,\n                                                           modelmembers.get('instrument_blks|layers', []))\n        mdl.factories['gates'] = _OrderedMemberDict(mdl, None, None, flags, modelmembers.get('factories|gates', []))\n        mdl.factories['cloudnoise'] = _OrderedMemberDict(mdl, None, None, flags,\n                                                         modelmembers.get('factories|cloudnoise', []))\n        mdl.factories['layers'] = _OrderedMemberDict(mdl, None, None, flags, modelmembers.get('factories|layers', []))\n\n        mdl._clouds = _collections.OrderedDict()\n        mdl._clean_paramvec()\n\n        return mdl\n\n\nclass CloudNoiseLayerRules(_LayerRules):\n\n    def __init__(self, errcomp_type, qubit_labels, implicit_idle_mode, singleq_idle_layer_labels,\n                 implied_global_idle_label):\n        self.qubit_labels = qubit_labels\n        self.errcomp_type = errcomp_type\n        self.implied_global_idle_label = implied_global_idle_label\n        self.single_qubit_idle_layer_labels = singleq_idle_layer_labels\n        self.implicit_idle_mode = implicit_idle_mode  # how to handle implied idles (\"blanks\") in circuits\n        self._add_global_idle_to_all_layers = False\n        self._add_padded_idle = False\n\n        if implicit_idle_mode is None or implicit_idle_mode == \"none\":  # no noise on idles\n            pass  # just use defaults above\n        elif implicit_idle_mode == \"add_global\" and self.implied_global_idle_label is not None:\n            self._add_global_idle_to_all_layers = True    # add global idle to all layers\n        elif implicit_idle_mode == \"pad_1Q\" and self.single_qubit_idle_layer_labels is not None:\n            self._add_padded_idle = True\n        else:\n            raise ValueError(\"Invalid `implicit_idle_mode`: '%s'\" % str(implicit_idle_mode))\n\n    def _to_nice_serialization(self):\n        state = super()._to_nice_serialization()\n        assert(all([len(k) == 1 for k in self.single_qubit_idle_layer_labels.keys()])), \\\n            \"All keys of single_qubit_idle_layer_labels should be 1-tuples of a *single* sslbl!\"\n        state.update({'error_composition_mode': self.errcomp_type,\n                      'implied_global_idle_label': (str(self.implied_global_idle_label)\n                                                    if (self.implied_global_idle_label is not None) else None),\n                      'single_qubit_idle_layer_labels': ({str(sslbls[0]): str(idle_lbl) for sslbls, idle_lbl\n                                                          in self.single_qubit_idle_layer_labels.items()}\n                                                         if self.single_qubit_idle_layer_labels is not None else None),\n                      'implicit_idle_mode': self.implicit_idle_mode,\n                      'qubit_labels': list(self.qubit_labels),\n                      })\n        return state\n\n    @classmethod\n    def _from_nice_serialization(cls, state):\n        from pygsti.circuits.circuitparser import parse_label as _parse_label\n\n        def _to_int(x):  # (same as in slowcircuitparser.py)\n            return int(x) if x.isdigit() else x\n\n        gi_label = _parse_label(state['implied_global_idle_label']) \\\n            if (state['implied_global_idle_label'] is not None) else None\n\n        if state.get('single_qubit_idle_layer_labels', None) is not None:\n            singleQ_idle_lbls = {(_to_int(k),): _parse_label(v)\n                                 for k, v in state['single_qubit_idle_layer_labels'].items()}\n        else:\n            singleQ_idle_lbls = None\n\n        qubit_labels = tuple(state['qubit_labels']) if ('qubit_labels' in state) else None\n\n        return cls(state['error_composition_mode'], qubit_labels, state['implicit_idle_mode'],\n                   singleQ_idle_lbls, gi_label)\n\n    def prep_layer_operator(self, model, layerlbl, caches):\n        \"\"\"\n        Create the operator corresponding to `layerlbl`.\n\n        Parameters\n        ----------\n        layerlbl : Label\n            A circuit layer label.\n\n        Returns\n        -------\n        State\n        \"\"\"\n        #No cache for preps\n        return model.prep_blks['layers'][layerlbl]  # prep_blks['layer'] are full prep ops\n\n    def povm_layer_operator(self, model, layerlbl, caches):\n        \"\"\"\n        Create the operator corresponding to `layerlbl`.\n\n        Parameters\n        ----------\n        layerlbl : Label\n            A circuit layer label.\n\n        Returns\n        -------\n        POVM or POVMEffect\n        \"\"\"\n        # caches['povm-layers'] *are* just complete layers\n        if layerlbl in caches['povm-layers']: return caches['povm-layers'][layerlbl]\n        if layerlbl in model.povm_blks['layers']:\n            return model.povm_blks['layers'][layerlbl]\n        else:\n            # See if this effect label could correspond to a *marginalized* POVM, and\n            # if so, create the marginalized POVM and add its effects to model.effect_blks['layers']\n            #assert(isinstance(layerlbl, _Lbl))  # Sanity check\n            povmName = _ot.effect_label_to_povm(layerlbl)\n            if povmName in model.povm_blks['layers']:\n                # implicit creation of marginalized POVMs whereby an existing POVM name is used with sslbls that\n                # are not present in the stored POVM's label.\n                mpovm = _povm.MarginalizedPOVM(model.povm_blks['layers'][povmName],\n                                               model.state_space, layerlbl.sslbls)  # cache in FUTURE\n                mpovm_lbl = _Lbl(povmName, layerlbl.sslbls)\n                caches['povm-layers'].update(mpovm.simplify_effects(mpovm_lbl))\n                assert(layerlbl in caches['povm-layers']), \"Failed to create marginalized effect!\"\n                return caches['povm-layers'][layerlbl]\n            else:\n                raise KeyError(\"Could not build povm/effect for %s!\" % str(layerlbl))\n\n    def operation_layer_operator(self, model, layerlbl, caches):\n        \"\"\"\n        Create the operator corresponding to `layerlbl`.\n\n        Parameters\n        ----------\n        layerlbl : Label\n            A circuit layer label.\n\n        Returns\n        -------\n        LinearOperator\n        \"\"\"\n        #Note: cache uses 'op-layers' for *simple target* layers, not complete ones\n        if layerlbl in caches['complete-layers']: return caches['complete-layers'][layerlbl]\n\n        if isinstance(layerlbl, _CircuitLabel):\n            op = self._create_op_for_circuitlabel(model, layerlbl)\n            caches['complete-layers'][layerlbl] = op\n            return op\n\n        Composed = _op.ComposedOp\n        ExpErrorgen = _op.ExpErrorgenOp\n        Sum = _op.ComposedErrorgen\n        add_global_idle = self._add_global_idle_to_all_layers\n        add_padded_idle = self._add_padded_idle\n\n        #print(\"DB: CloudNoiseLayerLizard building gate %s for %s w/comp-type %s\" %\n        #      (('matrix' if dense else 'map'), str(oplabel), self.errcomp_type) )\n\n        components = layerlbl.components\n        if len(components) == 0:\n            if add_global_idle:\n                if self.errcomp_type == \"gates\":\n                    return model.operation_blks['cloudnoise'][self.implied_global_idle_label]  # idle!\n                elif self.errcomp_type == \"errorgens\":\n                    return ExpErrorgen(model.operation_blks['cloudnoise'][self.implied_global_idle_label])\n                else:\n                    raise ValueError(\"Invalid errcomp_type in CloudNoiseLayerRules: %s\" % str(self.errcomp_type))\n            elif add_padded_idle:\n                idle_factors = [model.operation_blks['cloudnoise'][self.single_qubit_idle_layer_labels[(sslbl,)]]\n                                for sslbl in self.qubit_labels]\n                if self.errcomp_type == \"gates\":\n                    ret = Composed(idle_factors, evotype=model.evotype, state_space=model.state_space)\n                elif self.errcomp_type == \"errorgens\":\n                    ret = ExpErrorgen(Sum(idle_factors, state_space=model.state_space, evotype=model.evotype))\n                else:\n                    raise ValueError(\"Invalid errcomp_type in CloudNoiseLayerRules: %s\" % str(self.errcomp_type))\n                model._init_virtual_obj(ret)  # so ret's gpindices get set\n                return ret\n            else:\n                #Perfect no-noise idle\n                return Composed([], evotype=model.evotype, state_space=model.state_space)  # no need to init_virtual\n\n        #Compose target operation from layer's component labels, which correspond\n        # to the perfect (embedded) target ops in op_blks\n        if len(components) > 1:\n            #Note: _layer_component_targetop can return `None` for a (static) identity op\n            to_compose = [self._layer_component_targetop(model, l, caches['op-layers']) for l in components]\n            targetOp = Composed([op for op in to_compose if op is not None],\n                                evotype=model.evotype, state_space=model.state_space)\n        else:\n            targetOp = self._layer_component_targetop(model, components[0], caches['op-layers'])\n\n        ops_to_compose = [targetOp] if (targetOp is not None) else []\n\n        if self.errcomp_type == \"gates\":\n            if add_global_idle:\n                ops_to_compose.append(model.operation_blks['cloudnoise'][self.implied_global_idle_label])\n            # Note: add_padded_idle handled within _layer_component_cloudnoises\n            component_cloudnoise_ops = self._layer_component_cloudnoises(model, components, caches['op-cloudnoise'])\n            if len(component_cloudnoise_ops) > 0:\n                if len(component_cloudnoise_ops) > 1:\n                    localErr = Composed(component_cloudnoise_ops,\n                                        evotype=model.evotype, state_space=model.state_space)\n                else:\n                    localErr = component_cloudnoise_ops[0]\n                ops_to_compose.append(localErr)\n\n        elif self.errcomp_type == \"errorgens\":\n            #We compose the target operations to create a\n            # final target op, and compose this with a *single* ExpErrorgen operation which has as\n            # its error generator the composition (sum) of all the factors' error gens.\n            # Note: add_padded_idle handled within _layer_component_cloudnoises\n            errorGens = [model.operation_blks['cloudnoise'][self.implied_global_idle_label]] if add_global_idle else []\n            errorGens.extend(self._layer_component_cloudnoises(model, components, caches['op-cloudnoise']))\n            if len(errorGens) > 0:\n                if len(errorGens) > 1:\n                    error = ExpErrorgen(Sum(errorGens, state_space=model.state_space, evotype=model.evotype))\n                else:\n                    error = ExpErrorgen(errorGens[0])\n                ops_to_compose.append(error)\n        else:\n            raise ValueError(\"Invalid errcomp_type in CloudNoiseLayerRules: %s\" % str(self.errcomp_type))\n\n        ret = Composed(ops_to_compose, evotype=model.evotype, state_space=model.state_space) \\\n            if len(ops_to_compose) > 1 else ops_to_compose[0]\n        model._init_virtual_obj(ret)  # so ret's gpindices get set\n        caches['complete-layers'][layerlbl] = ret  # cache the final label value\n        return ret\n\n    def _layer_component_targetop(self, model, complbl, cache):\n        \"\"\"\n        Retrieves the target- or ideal-operation portion of one component of a layer operation.\n\n        Parameters\n        ----------\n        complbl : Label\n            A component label of a larger layer label.\n\n        Returns\n        -------\n        LinearOperator\n        \"\"\"\n        if complbl in cache:\n            return cache[complbl]  # caches['op-layers'] would hold \"simplified\" instrument members\n\n        if complbl == self.implied_global_idle_label:\n            # special case of the implied global idle, which give `None` instead of the\n            # identity as its target operation since we don't want to include an unnecesseary idle op.\n            return None\n\n        if isinstance(complbl, _CircuitLabel):\n            raise NotImplementedError(\"Cloud noise models cannot simulate circuits with partial-layer subcircuits.\")\n            # In the FUTURE, could easily implement this for errcomp_type == \"gates\", but it's unclear what to\n            #  do for the \"errorgens\" case - how do we gate an error generator of an entire (mulit-layer) sub-circuit?\n            # Maybe we just need to expand the label and create a composition of those layers?\n        elif complbl in model.operation_blks['layers']:\n            return model.operation_blks['layers'][complbl]\n        else:\n            return _opfactory.op_from_factories(model.factories['layers'], complbl)\n\n    def _layer_component_cloudnoises(self, model, complbl_list, cache):\n        \"\"\"\n        Retrieves cloud-noise portion of the components of a layer operation.\n\n        Get any present cloudnoise ops from a list of components.  This function processes\n        a list rather than an item because it's OK if some components don't have\n        corresponding cloudnoise ops - we just leave those off.\n\n        Parameters\n        ----------\n        complbl_list : list\n            A list of circuit-layer component labels.\n\n        Returns\n        -------\n        list\n        \"\"\"\n        ret = []\n        if self._add_padded_idle:\n            component_sslbls = [c.sslbls for c in complbl_list]\n            if None not in component_sslbls:  # sslbls == None => label covers *all* labels, no padding needed\n                present_sslbl_components = set(_itertools.chain(*[sslbls for sslbls in component_sslbls]))\n                absent_sslbls = [sslbl for sslbl in self.qubit_labels if (sslbl not in present_sslbl_components)]\n                factors = {sslbl: model.operation_blks['cloudnoise'][self.single_qubit_idle_layer_labels[(sslbl,)]]\n                           for sslbl in absent_sslbls}  # key = *lowest* (and only) sslbl\n            else:\n                factors = {}\n\n            for complbl in complbl_list:\n                complbl_lowest_sslbl = sorted(complbl.sslbls)[0] if (complbl.sslbls is not None) else 0\n                if complbl in cache:\n                    factors[complbl_lowest_sslbl] = cache[complbl]\n                elif complbl in model.operation_blks['cloudnoise']:\n                    factors[complbl_lowest_sslbl] = model.operation_blks['cloudnoise'][complbl]\n                else:\n                    try:\n                        factors[complbl_lowest_sslbl] = _opfactory.op_from_factories(\n                            model.factories['cloudnoise'], complbl)\n                    except KeyError: pass  # OK if cloudnoise doesn't exist (means no noise)\n\n            ret = [factors[k] for k in sorted(factors.keys())]\n\n        else:\n            for complbl in complbl_list:\n                if complbl in cache:\n                    ret.append(cache[complbl])  # caches['cloudnoise-layers'] would hold \"simplified\" instrument members\n                elif complbl in model.operation_blks['cloudnoise']:\n                    ret.append(model.operation_blks['cloudnoise'][complbl])\n                else:\n                    try:\n                        ret.append(_opfactory.op_from_factories(model.factories['cloudnoise'], complbl))\n                    except KeyError: pass  # OK if cloudnoise doesn't exist (means no noise)\n\n        return ret\n", "meta": {"hexsha": "bf6844e71dd54d490ed1311ca975016bcc29cf2f", "size": 37287, "ext": "py", "lang": "Python", "max_stars_repo_path": "pygsti/models/cloudnoisemodel.py", "max_stars_repo_name": "pyGSTi-Developers/pyGSTi", "max_stars_repo_head_hexsha": "bfedc1de4d604f14b0f958615776fb80ddb59e33", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pygsti/models/cloudnoisemodel.py", "max_issues_repo_name": "pyGSTi-Developers/pyGSTi", "max_issues_repo_head_hexsha": "bfedc1de4d604f14b0f958615776fb80ddb59e33", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pygsti/models/cloudnoisemodel.py", "max_forks_repo_name": "pyGSTi-Developers/pyGSTi", "max_forks_repo_head_hexsha": "bfedc1de4d604f14b0f958615776fb80ddb59e33", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.8188622754, "max_line_length": 120, "alphanum_fraction": 0.6390699171, "include": true, "reason": "import numpy,import scipy", "num_tokens": 8325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.281405613455665, "lm_q1q2_score": 0.15819962310212723}}
{"text": "# Copyright (c) 2021, NVIDIA CORPORATION.  All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Copyright 2018-2019, Mingkun Huang\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport math\n\nimport torch\nfrom numba import cuda\n\nfrom nemo.collections.asr.parts.numba.rnnt_loss.utils import rnnt_helper\n\nGPU_RNNT_THREAD_SIZE = 128\n\n\n@cuda.jit(device=True, inline=True)\ndef logp(\n    denom: torch.Tensor, acts: torch.Tensor, maxT: int, maxU: int, alphabet_size: int, mb: int, t: int, u: int, v: int\n):\n    \"\"\"\n    Compute the sum of log probability from the activation tensor and its denominator.\n\n    Args:\n        denom: Tensor of shape [B, T, U] flattened. Represents the denominator of the logprobs activation tensor\n            across entire vocabulary.\n        acts: Tensor of shape [B, T, U, V+1] flattened. Represents the logprobs activation tensor.\n        maxT: The maximum possible acoustic sequence length. Represents T in the logprobs tensor.\n        maxU: The maximum possible target sequence length. Represents U in the logprobs tensor.\n        alphabet_size: The vocabulary dimension V+1 (inclusive of RNNT blank).\n        mb: Batch indexer.\n        t: Acoustic sequence timestep indexer.\n        u: Target sequence timestep indexer.\n        v: Vocabulary token indexer.\n\n    Returns:\n        The sum of logprobs[mb, t, u, v] + denom[mb, t, u]\n    \"\"\"\n    col = (mb * maxT + t) * maxU + u\n    return denom[col] + acts[col * alphabet_size + v]\n\n\n@cuda.jit()\ndef compute_alphas_kernel(\n    acts: torch.Tensor,\n    denom: torch.Tensor,\n    alphas: torch.Tensor,\n    llForward: torch.Tensor,\n    xlen: torch.Tensor,\n    ylen: torch.Tensor,\n    mlabels: torch.Tensor,  # [B]\n    minibatch: int,\n    maxT: int,\n    maxU: int,\n    alphabet_size: int,\n    blank_: int,\n):\n    \"\"\"\n    Compute alpha (forward variable) probabilities over the transduction step.\n\n    Args:\n        acts: Tensor of shape [B, T, U, V+1] flattened. Represents the logprobs activation tensor.\n        denom: Tensor of shape [B, T, U] flattened. Represents the denominator of the logprobs activation tensor\n            across entire vocabulary.\n        alphas: Zero tensor of shape [B, T, U]. Will be updated inside the kernel with the forward variable\n            probabilities.\n        llForward: Zero tensor of shape [B]. Represents the log-likelihood of the forward pass.\n            Returned as the forward pass loss that is reduced by the optimizer.\n        xlen: Vector of length B which contains the actual acoustic sequence lengths in the padded\n            activation tensor.\n        ylen: Vector of length B which contains the actual target sequence lengths in the padded\n            activation tensor.\n        mlabels: Matrix of shape [B, U+1] (+1 here is due to <SOS> token - usually the RNNT blank).\n            The matrix contains the padded target transcription that must be predicted.\n        minibatch: Int representing the batch size.\n        maxT: The maximum possible acoustic sequence length. Represents T in the logprobs tensor.\n        maxU: The maximum possible target sequence length. Represents U in the logprobs tensor.\n        alphabet_size: The vocabulary dimension V+1 (inclusive of RNNT blank).\n        blank_: Index of the RNNT blank token in the vocabulary. Generally the first or last token in the vocab.\n\n    Updates:\n        Kernel inplace updates the following inputs:\n        -   alphas: forward variable scores.\n        -   llForward: log-likelihood of forward variable.\n    \"\"\"\n    # // launch B blocks, each block has U threads\n    b = cuda.blockIdx.x  # // batch id\n    u = cuda.threadIdx.x  # label id, u\n    T = xlen[b]  # select AM length of current sample\n    U = ylen[b] + 1  # select target length of current sample, +1 for the blank token\n\n    labels: torch.Tensor = mlabels[b]  # mb label start point, equivalent to mlabels + b * (maxU - 1)\n    offset = b * maxT * maxU  # pointer indexing offset\n\n    # alphas += offset # pointer offset, ignored since we explicitly add offset\n\n    # Initilize alpha[b, t=0, u=0] for all b in B\n    if u == 0:\n        alphas[offset] = 0\n\n    # sync until all alphas are initialized\n    cuda.syncthreads()\n\n    # Ordinary alpha calculations, broadcast across B=b and U=u\n    # Look up forward variable calculation from rnnt_numpy.forward_pass()\n    for n in range(1, T + U - 1):\n        t = n - u\n\n        if u == 0:\n            # for t in range(1, T) step to initialize alphas[b, t, 0]\n            if t > 0 and t < T:\n                alphas[offset + t * maxU + u] = alphas[offset + (t - 1) * maxU + u] + logp(\n                    denom, acts, maxT, maxU, alphabet_size, b, t - 1, 0, blank_\n                )\n        elif u < U:\n            # for u in range(1, U) step to initialize alphas[b, 0, u]\n            if t == 0:\n                alphas[offset + u] = alphas[offset + u - 1] + logp(\n                    denom, acts, maxT, maxU, alphabet_size, b, 0, u - 1, labels[u - 1]\n                )\n\n            # for t in range(1, T) for u in range(1, U) step to compute alphas[b, t, u]\n            elif t > 0 and t < T:\n                no_emit = alphas[offset + (t - 1) * maxU + u] + logp(\n                    denom, acts, maxT, maxU, alphabet_size, b, t - 1, u, blank_\n                )\n                emit = alphas[offset + t * maxU + u - 1] + logp(\n                    denom, acts, maxT, maxU, alphabet_size, b, t, u - 1, labels[u - 1]\n                )\n\n                alphas[offset + t * maxU + u] = rnnt_helper.log_sum_exp(emit, no_emit)\n\n        # sync across all B=b and U=u\n        cuda.syncthreads()\n\n    # After final sync, alphas[b, T-1, U - 1] + logprobs[b, T-1, U-1, blank] + denom[b, T-1, U-1] gives\n    # log-likelihood of forward pass.\n    if u == 0:\n        loglike = alphas[offset + (T - 1) * maxU + U - 1] + logp(\n            denom, acts, maxT, maxU, alphabet_size, b, T - 1, U - 1, blank_\n        )\n        llForward[b] = loglike\n\n\n@cuda.jit()\ndef compute_betas_kernel(\n    acts: torch.Tensor,\n    denom: torch.Tensor,\n    betas: torch.Tensor,\n    llBackward: torch.Tensor,\n    xlen: torch.Tensor,\n    ylen: torch.Tensor,\n    mlabels: torch.Tensor,  # [B, U]\n    minibatch: int,\n    maxT: int,\n    maxU: int,\n    alphabet_size: int,\n    blank_: int,\n):\n    \"\"\"\n    Compute beta (backward variable) probabilities over the transduction step.\n\n    Args:\n        acts: Tensor of shape [B, T, U, V+1] flattened. Represents the logprobs activation tensor.\n        denom: Tensor of shape [B, T, U] flattened. Represents the denominator of the logprobs activation tensor\n            across entire vocabulary.\n        betas: Zero tensor of shape [B, T, U]. Will be updated inside the kernel with the backward variable\n            probabilities.\n        llBackward: Zero tensor of shape [B]. Represents the log-likelihood of the backward pass.\n            Returned as the backward pass loss that is reduced by the optimizer.\n        xlen: Vector of length B which contains the actual acoustic sequence lengths in the padded\n            activation tensor.\n        ylen: Vector of length B which contains the actual target sequence lengths in the padded\n            activation tensor.\n        mlabels: Matrix of shape [B, U+1] (+1 here is due to <SOS> token - usually the RNNT blank).\n            The matrix contains the padded target transcription that must be predicted.\n        minibatch: Int representing the batch size.\n        maxT: The maximum possible acoustic sequence length. Represents T in the logprobs tensor.\n        maxU: The maximum possible target sequence length. Represents U in the logprobs tensor.\n        alphabet_size: The vocabulary dimension V+1 (inclusive of RNNT blank).\n        blank_: Index of the RNNT blank token in the vocabulary. Generally the first or last token in the vocab.\n\n    Updates:\n        Kernel inplace updates the following inputs:\n        -   betas: backward variable scores.\n        -   llBackward: log-likelihood of backward variable.\n    \"\"\"\n    # // launch B blocks, each block has U threads\n    b = cuda.blockIdx.x  # // batch id\n    u = cuda.threadIdx.x  # label id, u\n    T = xlen[b]  # select AM length of current sample\n    U = ylen[b] + 1  # select target length of current sample, +1 for the blank token\n\n    labels: torch.Tensor = mlabels[b]  # mb label start point, equivalent to mlabels + b * (maxU - 1)\n    offset = b * maxT * maxU  # pointer indexing offset\n\n    # betas += offset # pointer offset, ignored since we explicitly add offset\n\n    # Initilize beta[b, t=T-1, u=U-1] for all b in B with log_probs[b, t=T-1, u=U-1, blank]\n    if u == 0:\n        betas[offset + (T - 1) * maxU + U - 1] = logp(denom, acts, maxT, maxU, alphabet_size, b, T - 1, U - 1, blank_)\n\n    # sync until all betas are initialized\n    cuda.syncthreads()\n\n    # Ordinary beta calculations, broadcast across B=b and U=u\n    # Look up backward variable calculation from rnnt_numpy.backward_pass()\n    for n in range(T + U - 2, -1, -1):\n        t = n - u\n\n        if u == (U - 1):\n            # for t in reversed(range(T - 1)) step to initialize betas[b, t, U-1]\n            if t >= 0 and t < (T - 1):\n                betas[offset + t * maxU + U - 1] = betas[offset + (t + 1) * maxU + U - 1] + logp(\n                    denom, acts, maxT, maxU, alphabet_size, b, t, U - 1, blank_\n                )\n        elif u < U:\n            if t == T - 1:\n                # for u in reversed(range(U - 1)) step to initialize betas[b, T-1, u]\n                betas[offset + (T - 1) * maxU + u] = betas[offset + (T - 1) * maxU + u + 1] + logp(\n                    denom, acts, maxT, maxU, alphabet_size, b, T - 1, u, labels[u]\n                )\n            elif (t >= 0) and (t < T - 1):\n                # for t in reversed(range(T - 1)) for u in reversed(range(U - 1)) step to compute betas[b, t, u]\n                no_emit = betas[offset + (t + 1) * maxU + u] + logp(\n                    denom, acts, maxT, maxU, alphabet_size, b, t, u, blank_\n                )\n                emit = betas[offset + t * maxU + u + 1] + logp(\n                    denom, acts, maxT, maxU, alphabet_size, b, t, u, labels[u]\n                )\n                betas[offset + t * maxU + u] = rnnt_helper.log_sum_exp(emit, no_emit)\n\n        # sync across all B=b and U=u\n        cuda.syncthreads()\n\n    # After final sync, betas[b, 0, 0] gives\n    # log-likelihood of backward pass.\n    if u == 0:\n        llBackward[b] = betas[offset]\n\n\n@cuda.jit()\ndef compute_grad_kernel(\n    grads: torch.Tensor,\n    acts: torch.Tensor,\n    denom: torch.Tensor,\n    alphas: torch.Tensor,\n    betas: torch.Tensor,\n    logll: torch.Tensor,\n    xlen: torch.Tensor,\n    ylen: torch.Tensor,\n    mlabels: torch.Tensor,  # [B, U]\n    minibatch: int,\n    maxT: int,\n    maxU: int,\n    alphabet_size: int,\n    blank_: int,\n    fastemit_lambda: float,\n):\n    \"\"\"\n    Compute gradients over the transduction step.\n\n    Args:\n        grads: Zero Tensor of shape [B, T, U, V+1]. Is updated by this kernel to contain the gradients\n            of this batch of samples.\n        acts: Tensor of shape [B, T, U, V+1] flattened. Represents the logprobs activation tensor.\n        denom: Tensor of shape [B, T, U] flattened. Represents the denominator of the logprobs activation tensor\n            across entire vocabulary.\n        alphas: Alpha variable, contains forward probabilities. A tensor of shape [B, T, U].\n        betas: Beta varoable, contains backward probabilities. A tensor of shape [B, T, U].\n        logll: Log-likelihood of the forward variable, represented as a vector of shape [B].\n            Represents the log-likelihood of the forward pass.\n        xlen: Vector of length B which contains the actual acoustic sequence lengths in the padded\n            activation tensor.\n        ylen: Vector of length B which contains the actual target sequence lengths in the padded\n            activation tensor.\n        mlabels: Matrix of shape [B, U+1] (+1 here is due to <SOS> token - usually the RNNT blank).\n            The matrix contains the padded target transcription that must be predicted.\n        minibatch: Int representing the batch size.\n        maxT: The maximum possible acoustic sequence length. Represents T in the logprobs tensor.\n        maxU: The maximum possible target sequence length. Represents U in the logprobs tensor.\n        alphabet_size: The vocabulary dimension V+1 (inclusive of RNNT blank).\n        blank_: Index of the RNNT blank token in the vocabulary. Generally the first or last token in the vocab.\n        fastemit_lambda: Float scaling factor for FastEmit regularization. Refer to\n            FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization.\n\n    Updates:\n        Kernel inplace updates the following inputs:\n        -   grads: Gradients with respect to the log likelihood (logll).\n    \"\"\"\n    # Kernel call:\n    # blocks_per_grid = minibatch (b) * maxT (t) * maxU (u)\n    # threads_per_block = constant buffer size of parallel threads (v :: Constant)\n    tid = cuda.threadIdx.x  # represents v, taking steps of some constant size\n    idx = tid  # index of v < V+1; in steps of constant buffer size\n    col = cuda.blockIdx.x  # represents a fused index of b * t * u\n\n    # Decompose original indices from fused `col`\n    u = col % maxU  # (b * t * u) % u = u\n    bt = (col - u) // maxU  # (b * t * u - u) // U = b * t\n    t = bt % maxT  # (b * t) % t = t\n    mb = (bt - t) // maxT  # (b * t - t) // T = b\n\n    # constants\n    T = xlen[mb]  # select AM length of current sample\n    U = ylen[mb] + 1  # select target length of current sample, +1 for the blank token\n    labels: torch.Tensor = mlabels[mb]  # labels = mlabels + mb * (maxU - 1);\n\n    # Buffered gradient calculations, broadcast across B=b, T=t and U=u, looped over V with some constant stride.\n    # Look up gradient calculation from rnnt_numpy.compute_gradient()\n    if t < T and u < U:\n        # For cuda kernels, maximum number of threads per block is limited to some value.\n        # However, it may be the case that vocabulary size is larger than this limit\n        # To work around this, an arbitrary thread buffer size is chosen such that,\n        # 1) each element within the thread pool operates independently of the other\n        # 2) An inner while loop moves the index of each buffer element by the size of the buffer itself,\n        #    such that all elements of the vocabulary size are covered in (V + 1 // thread_buffer) number of steps.\n        # As such, each thread will perform the while loop at least (V + 1 // thread_buffer) number of times\n        while idx < alphabet_size:\n            # remember, `col` represents the tri-index [b, t, u]\n            # therefore; logpk = denom[b, t, u] + acts[b, t, u, v]\n            logpk = denom[col] + acts[col * alphabet_size + idx]\n            # initialize the grad of the sample acts[b, t, u, v]\n            grad = math.exp(alphas[col] + betas[col] + logpk - logll[mb])\n\n            # If FastEmit regularization is enabled, calculate the gradeint of probability of predicting the next label\n            # at the current timestep.\n            # The formula for this is Equation 9 in https://arxiv.org/abs/2010.11148, multiplied by the log probability\n            # of the current step (t, u), normalized by the total log likelihood.\n            # Once the gradient has been calculated, scale it by `fastemit_lambda`, as in Equation 10.\n            if fastemit_lambda > 0.0 and u < U - 1:\n                fastemit_grad = fastemit_lambda * math.exp(\n                    alphas[col]  # alphas(t, u)\n                    + (denom[col] + acts[col * alphabet_size + labels[u]])  # y_hat(t, u)\n                    + betas[col + 1]  # betas(t, u+1)\n                    + logpk  # log Pr(k|t, u)\n                    - logll[mb]  # total log likelihood for normalization\n                )\n            else:\n                fastemit_grad = 0.0\n\n            # Update the gradient of act[b, t, u, v] with the gradient from FastEmit regularization\n            grad = grad + fastemit_grad\n\n            # // grad to last blank transition\n            # grad[b, T-1, U-1, v=blank] -= exp(alphas[b, t, u) + logpk - logll[b])\n            if (idx == blank_) and (t == T - 1) and (u == U - 1):\n                grad -= math.exp(alphas[col] + logpk - logll[mb])\n\n            # grad of blank across t < T;\n            # grad[b, t<T-1, u, v=blank] -= exp(alphas[b, t, u] + logpk - logll[b] betas[b, t + 1, u])\n            if (idx == blank_) and (t < T - 1):\n                grad -= math.exp(alphas[col] + logpk - logll[mb] + betas[col + maxU])\n\n            # grad of correct token across u < U;\n            # grad[b, t, u<U-1, v=label[u]] -= exp(alphas[b, t, u] + logpk - logll[b] + betas[b, t, u+1])\n            # Scale the gradient by (1.0 + FastEmit_lambda) in log space, then exponentiate\n            if (u < U - 1) and (idx == labels[u]):\n                # exp(log(1 + fastemit_lambda) + ...) is numerically more stable than\n                # multiplying (1.0 + fastemit_lambda) with result.\n                grad -= math.exp(math.log1p(fastemit_lambda) + alphas[col] + logpk - logll[mb] + betas[col + 1])\n\n            # update grads[b, t, u, v] = grad\n            grads[col * alphabet_size + idx] = grad\n\n            # update internal index through the thread_buffer;\n            # until idx < V + 1, such that entire vocabulary has been updated.\n            idx += GPU_RNNT_THREAD_SIZE\n", "meta": {"hexsha": "bcca5bf33b8aa847deccb111bdefff35da54ff60", "size": 18436, "ext": "py", "lang": "Python", "max_stars_repo_path": "nemo/collections/asr/parts/numba/rnnt_loss/utils/cuda_utils/gpu_rnnt_kernel.py", "max_stars_repo_name": "madhukarkm/NeMo", "max_stars_repo_head_hexsha": "648c97f076147684bee6aaada209f2f20adcaf5d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4145, "max_stars_repo_stars_event_min_datetime": "2019-09-13T08:29:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T18:31:44.000Z", "max_issues_repo_path": "nemo/collections/asr/parts/numba/rnnt_loss/utils/cuda_utils/gpu_rnnt_kernel.py", "max_issues_repo_name": "madhukarkm/NeMo", "max_issues_repo_head_hexsha": "648c97f076147684bee6aaada209f2f20adcaf5d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2031, "max_issues_repo_issues_event_min_datetime": "2019-09-17T16:51:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:52:41.000Z", "max_forks_repo_path": "nemo/collections/asr/parts/numba/rnnt_loss/utils/cuda_utils/gpu_rnnt_kernel.py", "max_forks_repo_name": "madhukarkm/NeMo", "max_forks_repo_head_hexsha": "648c97f076147684bee6aaada209f2f20adcaf5d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1041, "max_forks_repo_forks_event_min_datetime": "2019-09-13T10:08:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T06:37:38.000Z", "avg_line_length": 47.1508951407, "max_line_length": 119, "alphanum_fraction": 0.6171078325, "include": true, "reason": "from numba", "num_tokens": 4853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.28140560742914383, "lm_q1q2_score": 0.15819961558573167}}
{"text": "#! /usr/bin/env python\n\nimport numpy as np\nimport inspect\nfrom pathlib import Path\n# import functools\n\nfrom astropy.wcs import WCS\nfrom astropy.coordinates import SkyCoord, ICRS, AltAz, Angle\nfrom astropy.coordinates.baseframe import frame_transform_graph\nfrom kidsproc.kidsmodel import _Model as Model  # this allows complex inputs\nfrom astropy.modeling import Parameter\nimport astropy.units as u\nfrom astropy.modeling import models\n# from astropy.table import Table\nfrom astropy.io import fits\nfrom astropy.table import Table, QTable\n\nfrom gwcs import coordinate_frames as cf\nfrom scipy import interpolate\n\nfrom tollan.utils.log import get_logger, timeit\nfrom tollan.utils import getobj\nfrom tollan.utils.fmt import pformat_yaml\nfrom tollan.utils.namespace import NamespaceMixin\nfrom tollan.utils.registry import Registry\n\n\ndef _get_skyoffset_frame(c):\n    \"\"\"This function creates a skyoffset_frame and ensures\n    the cached origin frame attribute is the correct instance.\n    \"\"\"\n    frame = c.skyoffset_frame()\n    frame_transform_graph._cached_frame_attributes['origin'] = \\\n        frame.frame_attributes['origin']\n    return frame\n\n\nclass _Model(Model, NamespaceMixin):\n\n    _namespace_type_key = 'model'\n\n    @classmethod\n    def _namespace_from_dict_op(cls, d):\n        # we resolve the model here so that we can allow\n        # one use only the model class name to specify a model class.\n        if cls._namespace_type_key not in d:\n            raise ValueError(\n                    f'unable to load model: '\n                    f'missing required key \"{cls._namespace_type_key}\"')\n        model_cls = cls._resolve_model_cls(d[cls._namespace_type_key])\n        return dict(d, **{cls._namespace_type_key: model_cls})\n\n    @staticmethod\n    def _resolve_model_cls(arg):\n        \"\"\"Return a template class specified by `arg`.\n\n        If `arg` is string, it is resolved using `tollan.utils.getobj`.\n        \"\"\"\n        logger = get_logger()\n\n        _arg = arg  # for logging\n        if isinstance(arg, str):\n            arg = getobj(arg)\n        # check if _resolve_template_cls attribute is present\n        if inspect.ismodule(arg):\n            raise ValueError(f\"cannot resolve model class from {arg}\")\n        if not isinstance(arg, Model):\n            raise ValueError(f\"cannot resolve model class from {arg}\")\n        model_cls = arg\n        logger.debug(\n                f\"resolved model {_arg} as {model_cls}\")\n        return model_cls\n\n\n# class SkyOffsetModel(_Model):\n#     \"\"\"This computes the relative offsets between two sets of coordinates.\n\n#     \"\"\"\n#     n_inputs = 2\n#     n_outputs = 2\n\n#     def __init__(self, ref_frame=None, *args, **kwargs):\n#         super().__init__(*args, **kwargs)\n#         self._t0 = t0\n#         self._target = target\n#         self._ref_frame = ref_frame\n\n#     def evaluate(self, x, y):\n#         return NotImplemented\n\n#     def evaluate_at(self, ref_coord, *args):\n#         \"\"\"Returns the mapping pattern as evaluated at given coordinates.\n#         \"\"\"\n#         frame = _get_skyoffset_frame(ref_coord)\n#         return coord.SkyCoord(*self(*args), frame=frame).transform_to(\n#                 ref_coord.frame)\n\n#     # TODO these three method seems to be better live in a wrapper\n#     # model rather than this model\n#     @property\n#     def t0(self):\n#         return self._t0\n\n#     @property\n#     def target(self):\n#         return self._target\n\n#     input_frame = cf.CelestialFrame(\n#             name='icrs',\n#             reference_frame=coord.ICRS(),\n#             unit=(u.deg, u.deg)\n#             )\n\n#     def __init__(self, *args, **kwargs):\n#         inputs = kwargs.pop('inputs', self.input_frame.axes_names)\n#         super().__init__(*args, **kwargs)\n#         # self.inputs =\n\n\nclass SourceModel(_Model):\n    \"\"\"Base class for models that compute the optical signal.\n    \"\"\"\n\n    _subclasses = Registry.create()\n\n    def __init_subclass__(cls, *args, **kwargs):\n        super().__init_subclass__(*args, **kwargs)\n        cls._subclasses.register(cls, cls)\n\n    def __init__(self, *args, **kwargs):\n        inputs = kwargs.pop('inputs', self.input_frame.axes_names)\n        outputs = ('S', )\n        super().__init__(*args, **kwargs)\n        self.inputs = inputs\n        self.outputs = outputs\n\n    @property\n    def data(self):\n        return self._data\n\n\nclass SourceImageModel(SourceModel):\n    \"\"\"\n    A model given by 2-d images.\n    \"\"\"\n\n    logger = get_logger()\n\n    n_inputs = 2\n    n_outputs = 1\n    input_frame = cf.CelestialFrame(\n            name='icrs',\n            reference_frame=ICRS(),\n            unit=(u.deg, u.deg)\n            )\n\n    def __init__(self, data=None, grouping=None, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self._data = data\n        self._grouping = grouping\n\n    @classmethod\n    def from_fits(cls, filepath, extname_map=None, **kwargs):\n        \"\"\"\n        Parameters\n        ----------\n        filepath : str, pathlib.Path\n            The path to the FITS file.\n\n        extname_map : dict, optional\n            Specify the extensions to included in the returned data.\n            If None, an educated guess will be made.\n        \"\"\"\n        filepath = Path(filepath)\n        hdulist = fits.open(filepath)\n\n        extname_hdu = dict()\n        for i, hdu in enumerate(hdulist):\n            cls.logger.debug('HDU {}: {}'.format(\n                i, hdu.header.tostring(sep='\\n')\n                ))\n            label = hdu.header.get('EXTNAME', i)\n            extname_hdu[label] = hdu\n\n        if extname_map is None:\n            extname_map = {\n                    k: k for k in extname_hdu.keys()\n                    }\n        cls.logger.debug(f\"use extname_map: {pformat_yaml(extname_map)}\")\n\n        data = dict()\n        for k, extname in extname_map.items():\n            data[k] = extname_hdu[extname]\n        cls.logger.debug(f'data keys: {list(data.keys())}')\n        return cls(data=data, name=filepath.as_posix(), **kwargs)\n\n    def evaluate_tod(self, tbl, lon, lat):\n        \"\"\"Extract flux for given array property table.\n\n        Parameters\n        ==========\n        tbl : astropy.table.Table\n            The array property table for mapping the data keys.\n\n        \"\"\"\n        data = self._data\n        grouping = self._grouping\n        if grouping not in tbl.colnames:\n            raise ValueError(\n                    \"unable to map data keys to array property table.\")\n        # make masks\n        data_groups = []\n        for g in np.unique(tbl[grouping]):\n            if g not in data:\n                self.logger.debug(f\"group {g} not found in data\")\n                continue\n            d = self._data[g]\n            m = tbl[grouping] == g\n            data_groups.append([d, m])\n            self.logger.debug(f\"group {g}: {m.sum()}/{len(m)}\")\n        self.logger.debug(f\"evaluate {len(data_groups)} groups\")\n\n        s_out = np.zeros(lon.shape) << u.MJy / u.sr\n        lon = lon.to_value(u.deg)\n        lat = lat.to_value(u.deg)\n        for d, m in data_groups:\n            wcsobj = WCS(d.header)\n            s_out_unit = u.Unit(d.header.get('SIGUNIT', 'adu'))\n            # check lon lat range\n            # because here we check longitude ranges\n            # we need to take into account wrapping issue\n            lon_m = lon[m, :]\n            lat_m = lat[m, :]\n            # s_out_m = s_out[m, :]\n            # w, e = np.min(lon_m), np.max(lon_m)\n            # s, n = np.min(lat_m), np.max(lat_m)\n            # check pixel range\n            ny, nx = d.data.shape\n            # lon lat range of pixel edges\n            lon_e, lat_e = wcsobj.wcs_pix2world(\n                    np.array([0, 0, nx - 1, nx - 1]),\n                    np.array([0, ny - 1, 0, ny - 1]),\n                    0)\n            xx, yy = wcsobj.wcs_world2pix(lon_e, lat_e, 0)\n            # fix potential wrapping issue by check at 360 and 180 wrapping\n            lon_e = Angle(lon_e << u.deg).wrap_at(360. << u.deg).degree\n            lon_e_180 = Angle(lon_e << u.deg).wrap_at(180. << u.deg).degree\n\n            w_e, e_e = np.min(lon_e), np.max(lon_e)\n            w_e_180, e_e_180 = np.min(lon_e_180), np.max(lon_e_180)\n            s_e, n_e = np.min(lat_e), np.max(lat_e)\n            # take the one with smaller size as the coordinte\n            if (e_e_180 - w_e_180) < (e_e - w_e):\n                # use wrapping at 180.d\n                w_e = w_e_180\n                e_e = e_e_180\n                lon_m = Angle(lon_m << u.deg).wrap_at(180. << u.deg).degree\n                self.logger.debug(\"re-wrapping coordinates at 180d\")\n            self.logger.debug(f\"data bbox: w={w_e} e={e_e} s={s_e} n={n_e}\")\n            self.logger.debug(f'data shape: {d.data.shape}')\n\n            # mask to include in range lon lat\n            g = (\n                    (lon_m > w_e) & (lon_m < e_e)\n                    & (lat_m > s_e) & (lat_m < n_e)\n                    )\n            self.logger.debug(f\"data mask {g.sum()}/{lon_m.size}\")\n            if g.sum() == 0:\n                continue\n            # convert all lon lat to x y\n            x_g, y_g = wcsobj.wcs_world2pix(lon_m[g], lat_m[g], 0)\n            ii = np.rint(y_g).astype(int)\n            jj = np.rint(x_g).astype(int)\n            self.logger.debug(\n                    f\"pixel range: [{ii.min()}, {ii.max()}] \"\n                    f\"[{jj.min()}, {jj.max()}]\")\n            # check ii and jj for valid pixel range\n            gp = (ii >= 0) & (ii < ny) & (jj >= 0) & (jj < nx)\n            # update g to include only valid pixels\n            g[g] = gp\n            # convert all lon lat to x y\n            x_g, y_g = wcsobj.wcs_world2pix(lon_m[g], lat_m[g], 0)\n            ii = np.rint(y_g).astype(int)\n            jj = np.rint(x_g).astype(int)\n            self.logger.debug(\n                    f\"pixel range updated: [{ii.min()}, {ii.max()}] \"\n                    f\"[{jj.min()}, {jj.max()}]\")\n            # take values in data\n            # ii, jj = np.meshgrid(\n            #         np.rint(y_g).astype(int),\n            #         np.rint(x_g).astype(int), indexing='ij')\n\n            # x, y = w.wcs_world2pix(\n            #         lon[m, :].ravel(), lat[m, :].ravel(), 0)\n            # g = (x >= 0) & (y < imshape[0]) & (jj >=0) & (jj < imshape[1])\n            # import matplotlib.pyplot as plt\n            # fig, ax = plt.subplots(1, 1, figsize=(10, 10))\n            # ax.scatter(ii, jj, c=d.data[ii, jj])\n            # ax.set_aspect('equal')\n            # plt.show()\n            ig, jg = np.where(g)\n            s_out[np.flatnonzero(m)[ig], jg] = d.data[ii, jj] << s_out_unit\n        self.logger.debug(\n                f'signal range: [{s_out.min()}, {s_out.max()}]')\n        return s_out\n\n    def evaluate(self, lon, lat):\n        pass\n\n\nclass SourceCatalogModel(SourceModel):\n    \"\"\"\n    A model with point sources.\n    \"\"\"\n    logger = get_logger()\n\n    n_inputs = 2\n    n_outputs = 1\n    input_frame = cf.CelestialFrame(\n            name='icrs',\n            reference_frame=ICRS(),\n            unit=(u.deg, u.deg)\n            )\n\n    def __init__(self, pos, data, grouping=None, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self._pos = pos\n        self._data = data\n        self._grouping = grouping\n\n    def make_image_model(self, beam_models, pixscale):\n\n        pixscale = u.pixel_scale(pixscale)\n        delta_pix = (1. << u.pix).to(u.arcsec, equivalencies=pixscale)\n\n        # convert beam_models to pixel unit\n        if next(iter(beam_models.values())).x_mean.unit.is_equivalent(u.pix):\n            m_beams = beam_models\n        else:\n            m_beams = dict()\n            for k, m in beam_models.items():\n                m_beams[k] = m.__class__(\n                        amplitude=m.amplitude.quantity,\n                        x_mean=m.x_mean.quantity.to_value(\n                            u.pix, equivalencies=pixscale),\n                        y_mean=m.y_mean.quantity.to_value(\n                            u.pix, equivalencies=pixscale),\n                        x_stddev=m.x_stddev.quantity.to_value(\n                            u.pix, equivalencies=pixscale),\n                        y_stddev=m.y_stddev.quantity.to_value(\n                            u.pix, equivalencies=pixscale),\n                        )\n        # use the first pos as the reference\n        ref_coord = self.pos[0]\n\n        wcsobj = WCS(naxis=2)\n        wcsobj.wcs.crpix = [1.5, 1.5]\n        wcsobj.wcs.cdelt = np.array([\n            -delta_pix.to_value(u.deg),\n            delta_pix.to_value(u.deg),\n            ])\n        wcsobj.wcs.ctype = [\"RA---TAN\", \"DEC--TAN\"]\n        wcsobj.wcs.crval = [ref_coord.ra.degree, ref_coord.dec.degree]\n\n        # compute the pixel range\n        x, y = wcsobj.wcs_world2pix(self.pos.ra, self.pos.dec, 0)\n        l, r = np.min(x), np.max(x)\n        b, t = np.min(y), np.max(y)\n        w, h = r - l, t - b\n        # size of the square bbox, with added padding on the edge\n        s = int(np.ceil(np.max([w, h]) + 10 * np.max(\n                [m.x_fwhm for m in m_beams.values()])))\n        self.logger.debug(f'source image size: {s}')\n        # figure out center coord\n        c_ra, c_dec = wcsobj.wcs_pix2world((l + r) / 2, (b + t) / 2, 0)\n        # re-center the wcs to pixel center\n        wcsobj.wcs.crpix = [s / 2 + 1, s / 2 + 1]\n        wcsobj.wcs.crval = c_ra, c_dec\n        header = wcsobj.to_header()\n        # compute the pixel positions\n        x, y = wcsobj.wcs_world2pix(self.pos.ra, self.pos.dec, 0)\n        assert ((x < 0) | (x > s)).sum() == 0\n        assert ((y < 0) | (y > s)).sum() == 0\n        # get the pixel\n        # render the image\n        hdus = dict()\n        for k, m in m_beams.items():\n            amp = (self.data[k] * m.amplitude).to(u.MJy / u.sr)\n            img = np.zeros((s, s), dtype=float) << u.MJy / u.sr\n            m = m.copy()\n            for xx, yy, aa in zip(x, y, amp):\n                m.amplitude = aa\n                m.x_mean = xx\n                m.y_mean = yy\n                m.render(img)\n            hdu = fits.ImageHDU(img.to_value(u.MJy / u.sr), header=header)\n            hdu.header['SIGUNIT'] = 'MJy / sr'\n            hdus[k] = hdu\n            self.logger.debug('HDU {}: {}'.format(\n                k, hdu.header.tostring(sep='\\n')\n                ))\n        return SourceImageModel(\n                data=hdus, grouping=self._grouping,\n                name=self.name,\n                )\n\n    @property\n    def pos(self):\n        return self._pos\n\n    @classmethod\n    def from_file(cls, filepath, **kwargs):\n        \"\"\"Create instance from file path.\n\n        Parameters\n        ----------\n        filepath : str, `pathlib.Path`\n            The path to the catalog file.\n\n        **kwargs\n            Arguments passed to `from_table`.\n        \"\"\"\n        tbl = Table.read(filepath, format='ascii')\n        # use this to keep track of the original table filepath\n        tbl.meta['_source'] = Path(filepath)\n        return cls.from_table(tbl, **kwargs)\n\n    @classmethod\n    def from_table(cls, tbl, colname_map=None, **kwargs):\n        \"\"\"\n        Parameters\n        ----------\n        tbl : `astropy.table.Table`\n            The table containing the source catalog.\n\n        colname_map : dict, optional\n            Specify the column names to included in the returned data.\n            If None, an educated guess will be made.\n        \"\"\"\n        # TODO: add code to guess colname map\n        if colname_map is None:\n            colname_map = dict()\n        colname_map = dict(**colname_map)\n        cls.logger.debug(f\"use colname_map: {pformat_yaml(colname_map)}\")\n\n        def getcol_quantity(tbl, colname, unit):\n            col = tbl[colname]\n            if col.unit is None and unit is not None:\n                cls.logger.debug(f\"assume unit {unit} for column {colname}\")\n                col.unit = unit\n            if col.unit is None:\n                return col\n            return col.quantity\n\n        # we use a qtable to hold the data internally\n        data = QTable()\n        for k, c in colname_map.items():\n            if c.startswith('flux'):\n                unit = u.mJy\n            elif c in ['ra', 'dec']:\n                unit = u.deg\n            else:\n                unit = None\n            data[k] = getcol_quantity(tbl, c, unit)\n        cls.logger.debug(f'data keys: {data.colnames}')\n\n        # figure out the position\n        # TODO: add handling of different coordinate system in input\n        pos = SkyCoord(\n                data['ra'], data['dec'],\n                frame=ICRS()).transform_to(cls.input_frame.reference_frame)\n\n        filepath = tbl.meta.get('_source', None)\n        if filepath is not None:\n            name = filepath.as_posix()\n        else:\n            name = None\n        return cls(pos=pos, data=data, name=name, **kwargs)\n\n    def evaluate(self, lon, lat):\n        coo = self.input_frame.coordinates(lon, lat)\n        sep = self._source_pos.separation(coo)\n        return self._psfmodel(sep) * self._source_flux\n\n\nclass ProjModel(_Model):\n    \"\"\"Base class for models that transform the detector locations.\n    \"\"\"\n\n    def __init__(self, t0=None, target=None, *args, **kwargs):\n        inputs = kwargs.pop('inputs', self.input_frame.axes_names)\n        outputs = kwargs.pop('outputs', self.output_frame.axes_names)\n        kwargs.setdefault('name', self._name)\n        super().__init__(*args, **kwargs)\n        self.inputs = inputs\n        self.outputs = outputs\n        self._t0 = t0\n        self._target = target\n\n    def mpl_axes_params(self):\n        return dict(aspect='equal')\n\n\nclass SkyMapModel(_Model):\n    \"\"\"A model that describes mapping patterns on the sky.\n\n    It computes the sky coordinates as a function of the time.\n    \"\"\"\n\n    n_inputs = 1\n    n_outputs = 2\n\n    def __init__(self, t0=None, target=None, ref_frame=None, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self._t0 = t0\n        self._target = target\n        self._ref_frame = ref_frame\n\n    def evaluate(self, x, y):\n        return NotImplemented\n\n    @timeit\n    def evaluate_at(self, ref_coord, *args):\n        \"\"\"Returns the mapping pattern as evaluated at given coordinates.\n        \"\"\"\n        frame = _get_skyoffset_frame(ref_coord)\n        return SkyCoord(*self(*args), frame=frame).transform_to(\n                ref_coord.frame)\n\n    # TODO these three method seems to be better live in a wrapper\n    # model rather than this model\n    @property\n    def t0(self):\n        return self._t0\n\n    @property\n    def target(self):\n        return self._target\n\n    @property\n    def ref_frame(self):\n        return self._ref_frame\n\n\nclass RasterScanModelMeta(SkyMapModel.__class__):\n    \"\"\"A meta class that defines a raster scan pattern.\n\n    This is implemented as a meta class so that we can reuse it\n    in any map model of any coordinate frame.\n    \"\"\"\n\n    @staticmethod\n    def _evaluate(\n            inst, t, length, space, n_scans, rot, speed, t_turnaround,\n            return_holdflag_only=False):\n        \"\"\"This computes a raster patten around the origin.\n\n        This assumes a circular turn over trajectory where the\n        speed of the turn over is implicitly controlled by `t_turnaround`.\n        \"\"\"\n        t_per_scan = length / speed\n\n        holdflag = np.zeros(t.shape, dtype=bool)\n        if n_scans == 1:\n            # TODO this is ugly, will revisit later\n            if return_holdflag_only:\n                return holdflag\n            # have to make a special case here\n            x = (t / t_per_scan - 0.5) * length\n            y = np.zeros(t.shape) << length.unit\n        else:\n            n_spaces = n_scans - 1\n\n            # bbox_width = length\n            # bbox_height = space * n_spaces\n            # # (x0, y0, w, h)\n            # bbox = (\n            #         -bbox_width / 2., -bbox_height / 2.,\n            #         bbox_width, bbox_height)\n            t_per_scan = length / speed\n            ratio_scan_to_si = (\n                    t_per_scan / (t_turnaround + t_per_scan))\n            ratio_scan_to_turnover = (t_per_scan / t_turnaround)\n\n            # scan index\n            _si = (t / (t_turnaround + t_per_scan))\n            si = _si.astype(int)\n            si_frac = _si - si\n\n            # get scan and turnover part\n            scan_frac = np.empty_like(si_frac)\n            turnover_frac = np.empty_like(si_frac)\n\n            turnover = si_frac > ratio_scan_to_si\n            if return_holdflag_only:\n                holdflag[turnover] = True\n                return holdflag\n            scan_frac[turnover] = 1.\n            scan_frac[~turnover] = si_frac[~turnover] / ratio_scan_to_si\n            turnover_frac[turnover] = si_frac[turnover] - (\n                    1. - si_frac[turnover]) * ratio_scan_to_turnover\n            turnover_frac[~turnover] = 0.\n\n            x = (scan_frac - 0.5) * length\n            y = (si / n_spaces - 0.5) * n_spaces * space\n\n            # turnover part\n            radius_t = space / 2\n            theta_t = turnover_frac[turnover] * np.pi * u.rad\n            dy = radius_t * (1 - np.cos(theta_t))\n            dx = radius_t * np.sin(theta_t)\n            x[turnover] = x[turnover] + dx\n            y[turnover] = y[turnover] + dy\n            # make continuous\n            x = x * (-1) ** si\n\n        # apply rotation\n        m_rot = models.AffineTransformation2D(\n            models.Rotation2D._compute_matrix(\n                angle=rot.to_value('rad')) * inst.frame_unit,\n            translation=(0., 0.) * inst.frame_unit)\n        xx, yy = m_rot(x, y)\n        return xx, yy\n\n    def __new__(meta, name, bases, attrs):\n        frame = attrs['frame']\n        frame_unit = frame.unit[0]\n\n        attrs.update(dict(\n            frame_unit=frame_unit,\n            length=Parameter(default=10., unit=frame_unit),\n            space=Parameter(default=1., unit=frame_unit),\n            n_scans=Parameter(default=10., unit=u.dimensionless_unscaled),\n            rot=Parameter(default=0., unit=u.deg),\n            speed=Parameter(default=1., unit=frame_unit / u.s),\n            # accel=Parameter(default=1., unit=cls.frame_unit / u.s ** 2),\n            t_turnaround=Parameter(default=1., unit=u.s),\n            pattern='raster',\n                ))\n\n        def get_total_time(self):\n            return (self.length / self.speed * self.n_scans\n                    + self.t_turnaround * (self.n_scans - 1.)).to(u.s)\n\n        attrs['get_total_time'] = get_total_time\n\n        @timeit(name)\n        def evaluate(self, t, *args, **kwargs):\n            t = np.asarray(t) * t.unit\n            return meta._evaluate(self, t, *args, **kwargs)\n\n        attrs['evaluate'] = evaluate\n        # TODO refactor this part\n        attrs['evaluate_holdflag'] = lambda self, t: evaluate(\n                self, t, self.length, self.space, self.n_scans, self.rot,\n                self.speed, self.t_turnaround, return_holdflag_only=True\n                )\n        return super().__new__(meta, name, bases, attrs)\n\n    def __call__(cls, *args, **kwargs):\n        inst = super().__call__(*args, **kwargs)\n        inst.inputs = ('t', )\n        inst.outputs = cls.frame.axes_names\n        return inst\n\n\nclass LissajousModelMeta(SkyMapModel.__class__):\n    \"\"\"A meta class that defines a Lissajous scan pattern.\n\n    This is implemented as a meta class so that we can reuse it\n    in any map model of any coordinate frame.\n    \"\"\"\n\n    def __new__(meta, name, bases, attrs):\n        frame = attrs['frame']\n        frame_unit = frame.unit[0]\n\n        attrs.update(dict(\n            frame_unit=frame_unit,\n            x_length=Parameter(default=10., unit=frame_unit),\n            y_length=Parameter(default=10., unit=frame_unit),\n            x_omega=Parameter(default=1. * u.rad / u.s),\n            y_omega=Parameter(default=1. * u.rad / u.s),\n            delta=Parameter(default=0., unit=u.rad),\n            rot=Parameter(default=0., unit=u.deg),\n            pattern='lissajous',\n                ))\n\n        def get_total_time(self):\n            t_x = 2 * np.pi * u.rad / self.x_omega\n            t_y = 2 * np.pi * u.rad / self.y_omega\n            r = (t_y / t_x).to_value(u.dimensionless_unscaled)\n            s = 100\n            r = np.lcm(int(r * s), s) / s\n            return (t_x * r).to(u.s)\n\n        attrs['get_total_time'] = get_total_time\n\n        @timeit(name)\n        def evaluate(\n                self, t, x_length, y_length, x_omega, y_omega, delta, rot):\n            \"\"\"This computes a lissajous pattern around the origin.\n\n            \"\"\"\n            t = np.asarray(t) * t.unit\n\n            x = x_length * 0.5 * np.sin(x_omega * t + delta)\n            y = y_length * 0.5 * np.sin(y_omega * t)\n\n            m_rot = models.AffineTransformation2D(\n                models.Rotation2D._compute_matrix(\n                    angle=rot.to_value('rad')) * self.frame_unit,\n                translation=(0., 0.) * self.frame_unit)\n            xx, yy = m_rot(x, y)\n            return xx, yy\n\n        attrs['evaluate'] = evaluate\n        attrs['evaluate_holdflag'] = \\\n            lambda self, t: np.zeros(t.shape, dtype=bool)\n        return super().__new__(meta, name, bases, attrs)\n\n    def __call__(cls, *args, **kwargs):\n        inst = super().__call__(*args, **kwargs)\n        inst.inputs = ('t', )\n        inst.outputs = cls.frame.axes_names\n        return inst\n\n\nclass DoubleLissajousModelMeta(SkyMapModel.__class__):\n    \"\"\"A meta class that defines a Double Lissajous scan pattern.\n\n    \"\"\"\n\n    @staticmethod\n    def _evaluate(\n            inst, t,\n            x_length_0, y_length_0, x_omega_0, y_omega_0, delta_0,\n            x_length_1, y_length_1, x_omega_1, y_omega_1, delta_1,\n            delta, rot):\n        \"\"\"This computes a double lissajous pattern around the origin.\n\n        \"\"\"\n        x_0 = x_length_0 * 0.5 * np.sin(x_omega_0 * t + delta + delta_0)\n        y_0 = y_length_0 * 0.5 * np.sin(y_omega_0 * t + delta)\n        x_1 = x_length_1 * 0.5 * np.sin(x_omega_1 * t + delta_1)\n        y_1 = y_length_1 * 0.5 * np.sin(y_omega_1 * t)\n\n        x = x_0 + x_1\n        y = y_0 + y_1\n\n        m_rot = models.AffineTransformation2D(\n            models.Rotation2D._compute_matrix(\n                angle=rot.to_value('rad')) * inst.frame_unit,\n            translation=(0., 0.) * inst.frame_unit)\n        xx, yy = m_rot(x, y)\n        return xx, yy\n\n    def __new__(meta, name, bases, attrs):\n        frame = attrs['frame']\n        frame_unit = frame.unit[0]\n\n        attrs.update(dict(\n            frame_unit=frame_unit,\n            x_length_0=Parameter(default=10., unit=frame_unit),\n            y_length_0=Parameter(default=10., unit=frame_unit),\n            x_omega_0=Parameter(default=1. * u.rad / u.s),\n            y_omega_0=Parameter(default=1. * u.rad / u.s),\n            delta_0=Parameter(default=0., unit=u.rad),\n            x_length_1=Parameter(default=5., unit=frame_unit),\n            y_length_1=Parameter(default=5., unit=frame_unit),\n            x_omega_1=Parameter(default=1. * u.rad / u.s),\n            y_omega_1=Parameter(default=1. * u.rad / u.s),\n            delta_1=Parameter(default=0., unit=u.rad),\n            delta=Parameter(default=0., unit=u.rad),\n            rot=Parameter(default=0., unit=u.deg),\n            pattern='double_lissajous',\n                ))\n\n        def get_total_time(self):\n            # make the total time the longer one among the two\n            def _get_total_time(x_omega, y_omega):\n                t_x = 2 * np.pi * u.rad / x_omega\n                t_y = 2 * np.pi * u.rad / y_omega\n                r = (t_y / t_x).to_value(u.dimensionless_unscaled)\n                s = 100\n                r = np.lcm(int(r * s), s) / s\n                return (t_x * r).to(u.s)\n            t0 = _get_total_time(self.x_omega_0, self.y_omega_0)\n            t1 = _get_total_time(self.x_omega_1, self.y_omega_1)\n            return t0 if t0 > t1 else t1\n\n        attrs['get_total_time'] = get_total_time\n\n        @timeit(name)\n        def evaluate(self, t, *args, **kwargs):\n            t = np.asarray(t) * t.unit\n            return meta._evaluate(self, t, *args, **kwargs)\n\n        attrs['evaluate'] = evaluate\n        attrs['evaluate_holdflag'] = \\\n            lambda self, t: np.zeros(t.shape, dtype=bool)\n        return super().__new__(meta, name, bases, attrs)\n\n    def __call__(cls, *args, **kwargs):\n        inst = super().__call__(*args, **kwargs)\n        inst.inputs = ('t', )\n        inst.outputs = cls.frame.axes_names\n        return inst\n\n\nclass RastajousModelMeta(SkyMapModel.__class__):\n    \"\"\"A meta class that defines a Rastajous scan pattern.\n\n    \"\"\"\n\n    def __new__(meta, name, bases, attrs):\n        frame = attrs['frame']\n        frame_unit = frame.unit[0]\n\n        attrs.update(dict(\n            frame_unit=frame_unit,\n            length=Parameter(default=10., unit=frame_unit),\n            space=Parameter(default=1., unit=frame_unit),\n            n_scans=Parameter(default=10., unit=u.dimensionless_unscaled),\n            rot=Parameter(default=0., unit=u.deg),\n            speed=Parameter(default=1., unit=frame_unit / u.s),\n            t_turnaround=Parameter(default=1., unit=u.s),\n            x_length_0=Parameter(default=10., unit=frame_unit),\n            y_length_0=Parameter(default=10., unit=frame_unit),\n            x_omega_0=Parameter(default=1. * u.rad / u.s),\n            y_omega_0=Parameter(default=1. * u.rad / u.s),\n            delta_0=Parameter(default=0., unit=u.rad),\n            x_length_1=Parameter(default=5., unit=frame_unit),\n            y_length_1=Parameter(default=5., unit=frame_unit),\n            x_omega_1=Parameter(default=1. * u.rad / u.s),\n            y_omega_1=Parameter(default=1. * u.rad / u.s),\n            delta_1=Parameter(default=0., unit=u.rad),\n            delta=Parameter(default=0., unit=u.rad),\n            pattern='rastajous',\n                ))\n\n        def get_total_time(self):\n            # make the total time based on the raster\n            return (self.length / self.speed * self.n_scans\n                    + self.t_turnaround * (self.n_scans - 1.)).to(u.s)\n\n        attrs['get_total_time'] = get_total_time\n\n        @timeit(name)\n        def evaluate(\n                self, t,\n                length, space, n_scans, rot, speed, t_turnaround,\n                x_length_0, y_length_0, x_omega_0, y_omega_0, delta_0,\n                x_length_1, y_length_1, x_omega_1, y_omega_1, delta_1,\n                delta):\n            \"\"\"This computes a rastajous pattern around the origin.\n\n            \"\"\"\n            t = np.asarray(t) * t.unit\n\n            x_r, y_r = RasterScanModelMeta._evaluate(\n                    inst=self, t=t, length=length, space=space,\n                    n_scans=n_scans, rot=0. << u.deg,\n                    speed=speed, t_turnaround=t_turnaround,\n                    return_holdflag_only=False)\n\n            x_l, y_l = DoubleLissajousModelMeta._evaluate(\n                    inst=self, t=t,\n                    x_length_0=x_length_0, y_length_0=y_length_0,\n                    x_omega_0=x_omega_0, y_omega_0=y_omega_0, delta_0=delta_0,\n                    x_length_1=x_length_1, y_length_1=y_length_1,\n                    x_omega_1=x_omega_1, y_omega_1=y_omega_1, delta_1=delta_1,\n                    delta=delta, rot=0. << u.deg\n                    )\n            x = x_r + x_l\n            y = y_r + y_l\n            m_rot = models.AffineTransformation2D(\n                models.Rotation2D._compute_matrix(\n                    angle=rot.to_value('rad')) * self.frame_unit,\n                translation=(0., 0.) * self.frame_unit)\n            xx, yy = m_rot(x, y)\n            return xx, yy\n\n        attrs['evaluate'] = evaluate\n        # TODO use the raster hold flag\n        attrs['evaluate_holdflag'] = \\\n            lambda self, t: RasterScanModelMeta._evaluate(\n                self, t, self.length, self.space, self.n_scans, self.rot,\n                self.speed, self.t_turnaround, return_holdflag_only=True\n                )\n        return super().__new__(meta, name, bases, attrs)\n\n    def __call__(cls, *args, **kwargs):\n        inst = super().__call__(*args, **kwargs)\n        inst.inputs = ('t', )\n        inst.outputs = cls.frame.axes_names\n        return inst\n\n\nclass TrajectoryModelMeta(SkyMapModel.__class__):\n    \"\"\"A meta class that defines a trajectory.\n\n    This is implemented as a meta class so that we can reuse it\n    in any map model of any coordinate frame.\n    \"\"\"\n\n    def __new__(meta, name, bases, attrs):\n        frame = attrs['frame']\n        frame_unit = frame.unit[0]\n\n        attrs.update(dict(\n            frame_unit=frame_unit,\n                ))\n\n        def get_total_time(self):\n            return self._time[-1]\n\n        attrs['get_total_time'] = get_total_time\n\n        lon_attr, lat_attr = {\n                'icrs': ('_ra', '_dec'),\n                'altaz': ('_az', '_alt'),\n                }[frame.name]\n\n        @property\n        def _lon(self):\n            return getattr(self, lon_attr)\n\n        attrs['_lon_attr'] = lon_attr\n        attrs['_lon'] = _lon\n\n        @property\n        def _lat(self):\n            return getattr(self, lat_attr)\n\n        attrs['_lat_attr'] = lat_attr\n        attrs['_lat'] = _lat\n\n        @timeit(name)\n        def evaluate(\n                self, t):\n            \"\"\"This computes the position based on interpolation.\n\n            \"\"\"\n            t = t.to_value(u.s)\n            return self._lon_interp(t) << u.deg, self._lat_interp(t) << u.deg\n\n        attrs['evaluate'] = evaluate\n        attrs['evaluate_holdflag'] = \\\n            lambda self, t: self._holdflag_interp(t).astype(int)\n\n        return super().__new__(meta, name, bases, attrs)\n\n    def __call__(\n            cls, *args, **kwargs):\n        data = dict()\n        for attr in ('time', 'ra', 'dec', 'az', 'alt', 'holdflag'):\n            data[f'_{attr}'] = kwargs.pop(attr, None)\n        inst = super().__call__(*args, **kwargs)\n        inst.__dict__.update(data)\n        inst.inputs = ('t', )\n        inst.outputs = cls.frame.axes_names\n        inst._lon_interp = interpolate.interp1d(\n                inst._time.to_value(u.s), inst._lon.to_value(u.deg))\n        inst._lat_interp = interpolate.interp1d(\n                inst._time.to_value(u.s), inst._lat.to_value(u.deg))\n        inst._holdflag_interp = interpolate.interp1d(\n                inst._time, inst._holdflag, kind='previous')\n        return inst\n\n\nclass SkyRasterScanModel(SkyMapModel, metaclass=RasterScanModelMeta):\n    frame = cf.Frame2D(\n            name='skyoffset', axes_names=('lon', 'lat'),\n            unit=(u.deg, u.deg))\n\n\nclass SkyLissajousModel(SkyMapModel, metaclass=LissajousModelMeta):\n    frame = cf.Frame2D(\n            name='skyoffset', axes_names=('lon', 'lat'),\n            unit=(u.deg, u.deg))\n\n\nclass SkyDoubleLissajousModel(SkyMapModel, metaclass=DoubleLissajousModelMeta):\n    frame = cf.Frame2D(\n            name='skyoffset', axes_names=('lon', 'lat'),\n            unit=(u.deg, u.deg))\n\n\nclass SkyRastajousModel(SkyMapModel, metaclass=RastajousModelMeta):\n    frame = cf.Frame2D(\n            name='skyoffset', axes_names=('lon', 'lat'),\n            unit=(u.deg, u.deg))\n\n\nclass SkyMapTrajModel(SkyMapModel):\n\n    @timeit\n    def evaluate_at(self, ref_coord, *args):\n        \"\"\"Returns the mapping pattern as evaluated at given coordinates.\n        \"\"\"\n        # ref_coord is ignored in this case\n        return SkyCoord(*self(*args), frame=self.ref_frame)\n\n\nclass SkyICRSTrajModel(SkyMapTrajModel, metaclass=TrajectoryModelMeta):\n    frame = cf.CelestialFrame(\n            name='icrs',\n            reference_frame=ICRS(),\n            unit=(u.deg, u.deg)\n            )\n\n\nclass SkyAltAzTrajModel(SkyMapTrajModel, metaclass=TrajectoryModelMeta):\n    frame = cf.CelestialFrame(\n            name='altaz',\n            reference_frame=AltAz(),\n            unit=(u.deg, u.deg)\n            )\n\n\ndef resolve_sky_map_ref_frame(ref_frame, observer=None, time_obs=None):\n    \"\"\"\n    Return a frame with respect to which sky map offset model can be\n    rendered.\n    \"\"\"\n    if isinstance(ref_frame, str):\n        # this is not public API so be careful for future changes.\n        from astropy.coordinates.sky_coordinate_parsers import (\n                _get_frame_class)\n        ref_frame = _get_frame_class(ref_frame)\n    if ref_frame is AltAz:\n        return observer.altaz(time=time_obs)\n    return ref_frame\n", "meta": {"hexsha": "0633a9e7b944174309a1a2f4612d53667e7b6d34", "size": 36256, "ext": "py", "lang": "Python", "max_stars_repo_path": "tolteca/simu0/base.py", "max_stars_repo_name": "dennis-l/tolteca", "max_stars_repo_head_hexsha": "1dffaffb585eb7027e26b34ae01e8632bef134cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-28T18:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T00:25:51.000Z", "max_issues_repo_path": "tolteca/simu0/base.py", "max_issues_repo_name": "dennis-l/tolteca", "max_issues_repo_head_hexsha": "1dffaffb585eb7027e26b34ae01e8632bef134cb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-11-04T22:32:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T21:40:34.000Z", "max_forks_repo_path": "tolteca/simu0/base.py", "max_forks_repo_name": "dennis-l/tolteca", "max_forks_repo_head_hexsha": "1dffaffb585eb7027e26b34ae01e8632bef134cb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-23T14:00:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T15:34:48.000Z", "avg_line_length": 34.9961389961, "max_line_length": 79, "alphanum_fraction": 0.5557976611, "include": true, "reason": "import numpy,from scipy,import astropy,from astropy", "num_tokens": 9130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.27202455699569283, "lm_q1q2_score": 0.1581287157127464}}
{"text": "#!/usr/bin/env python3\n\"\"\"\nPlots 3 components for seismograms.\n\"\"\"\nfrom argparse import ArgumentParser\nfrom functools import partial\nfrom glob import glob\nfrom multiprocessing import Pool\nimport os\n\nimport matplotlib as mpl\n\nmpl.use(\"Agg\")\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom qcore.timeseries import BBSeis, LFSeis, HFSeis, read_ascii\nfrom visualization.util import intersection\n\n# files that contain the 3 components (text based)\nextensions = [\".090\", \".000\", \".ver\"]\nBINARY_FORMATS = {\"BB\": BBSeis, \"LF\": LFSeis, \"HF\": HFSeis}\ncolours = [\"black\", \"red\", \"blue\", \"magenta\", \"darkgreen\", \"orange\"]\n\n\ndef load_args():\n    \"\"\"\n    Process command line arguments.\n    \"\"\"\n    # read\n    parser = ArgumentParser(description=\"Plots components for seismograms. \")\n\n    parser.add_argument(\n        \"--waveforms\",\n        help=\"directory to text data or binary file followed by label\",\n        nargs=2,\n        action=\"append\",\n        required=True,\n    )\n    parser.add_argument(\n        \"--out\",\n        help=\"output folder to place plots\",\n        type=os.path.abspath,\n        default=\"waveforms\",\n    )\n    parser.add_argument(\n        \"--n-stations\",\n        help=\"Limit number of stations to plot (selected randomly).\",\n        type=int,\n    )\n    parser.add_argument(\"--stations\", help=\"Specific stations to plot.\", nargs=\"+\")\n    parser.add_argument(\"-v\", help=\"verbose messages\", action=\"store_true\")\n    parser.add_argument(\n        \"-n\", \"--nproc\", help=\"number of processes to use\", type=int, default=1\n    )\n    parser.add_argument(\n        \"-t\", \"--tmax\", type=float, help=\"maximum duration of waveform simulation\"\n    )\n    args = parser.parse_args()\n\n    # validate\n    for source in args.waveforms:\n        if not os.path.exists(source[0]):\n            parser.error(f\"Cannot find waveform source: {source[0]}\")\n\n    if args.tmax is not None and args.tmax <= 0:\n        parser.error(\"Duration -t / --tmax must be greater than 0\")\n\n    os.makedirs(args.out, exist_ok=True)\n\n    return args\n\n\ndef load_location(path, verbose=False):\n    \"\"\"\n    Return opened binary file or text directory (automatically detected).\n    \"\"\"\n    if os.path.isfile(path):\n        try:\n            binary = HFSeis(path)\n            if verbose:\n                print(f\"HF: {path}\")\n        except ValueError:\n            # file is not an HF seis file\n            binary = BBSeis(path)\n            if verbose:\n                print(f\"BB: {path}\")\n    else:\n        try:\n            binary = LFSeis(path)\n            if verbose:\n                print(f\"LF: {path}\")\n        except ValueError:\n            # cannot find e3d.par... if text data\n            if verbose:\n                print(f\"TEXT: {path}\")\n            return path\n    return binary\n\n\ndef load_stations(source):\n    \"\"\"\n    Retrieve stations for waveforms.\n    \"\"\"\n    if type(source).__name__ != \"str\":\n        # opened binary object\n        return list(source.stations.name)\n\n    # path to directory containing text data\n    files = glob(os.path.join(source, f\"*{extensions[0]}\"))\n    stations = list(map(lambda f: os.path.basename(f)[:-4], files))\n    return stations\n\n\ndef plot_station(\n    output,\n    sources,\n    labels,\n    tmax,\n    verbose,\n    station,\n):\n    \"\"\"Creates a waveform plot for a specific station.\"\"\"\n\n    if verbose:\n        print(\"Plotting station: {}...\".format(station))\n\n    timeseries = []\n    for source in sources:\n        if type(source).__name__ != \"str\":\n            # opened binary object\n            timeline = (\n                np.arange(source.nt, dtype=np.float32) * source.dt + source.start_sec\n            )\n            timeseries.append(np.vstack((source.vel(station).T, timeline)))\n        else:\n            # text directory\n            meta = read_ascii(\n                os.path.join(source, f\"{station}{extensions[0]}\"), meta=True\n            )[1]\n            vals = np.array(\n                [\n                    read_ascii(os.path.join(source, f\"{station}{ext}\"))\n                    for ext in extensions\n                ]\n            )\n            timeline = (\n                np.arange(meta[\"nt\"], dtype=np.float32) * meta[\"dt\"] + meta[\"sec\"]\n            )\n            timeseries.append(np.vstack((vals, timeline)))\n    x_max = max([ts[-1, -1] for ts in timeseries])\n    if tmax is not None:\n        x_max = min(tmax, x_max)\n\n    all_y = np.concatenate([ts[:-1] for ts in timeseries], axis=1)\n    # get axis min/max\n    y_min, y_max = np.min(all_y), np.max(all_y)\n    y_diff = y_max - y_min\n    pgvs = np.max(np.abs(all_y), axis=1)\n    ppgvs = np.max(all_y, axis=1)\n    npgvs = np.min(all_y, axis=1)\n\n    scale_length = max(int(round(x_max / 25.0)) * 5, 5)\n\n    # start plot\n    f, axis = plt.subplots(1, 3, sharex=True, sharey=True, figsize=(20, 4), dpi=96)\n    f.subplots_adjust(\n        left=0.08, bottom=0.12, right=0.96, top=None, wspace=0.08, hspace=0\n    )\n    plt.suptitle(\n        station,\n        fontsize=20,\n        x=0.02,\n        y=0.5,\n        horizontalalignment=\"left\",\n        verticalalignment=\"center\",\n    )\n    plt.xlim([0, x_max])\n\n    # subplots\n    for i, s in enumerate(timeseries):\n        for j in range(len(extensions)):\n            ax = axis[j]\n            ax.set_axis_off()\n            ax.set_ylim([y_min - y_diff * 0.15, y_max])\n\n            (line,) = ax.plot(\n                s[len(extensions)],\n                s[j] * min(y_max / ppgvs[j], y_min / npgvs[j]),\n                color=colours[i % len(colours)],\n                linewidth=1,\n            )\n            if j == 2:\n                line.set_label(labels[i])\n                ax.legend()\n\n            if i == 1 and j == 0:\n                # Add scale\n                ax.plot(\n                    [0, scale_length],\n                    [y_min - y_diff * 0.1] * 2,\n                    color=\"black\",\n                    linewidth=1,\n                )\n                ax.text(\n                    0,\n                    y_min - y_diff * 0.15,\n                    \"0\",\n                    size=12,\n                    verticalalignment=\"top\",\n                    horizontalalignment=\"center\",\n                )\n                ax.text(\n                    scale_length,\n                    y_min - y_diff * 0.15,\n                    str(scale_length),\n                    size=12,\n                    verticalalignment=\"top\",\n                    horizontalalignment=\"center\",\n                )\n                ax.text(\n                    scale_length / 2.0,\n                    y_min - y_diff * 0.225,\n                    \"sec\",\n                    size=12,\n                    verticalalignment=\"top\",\n                    horizontalalignment=\"center\",\n                )\n\n            if i == 0:\n                # Add component label\n                ax.set_title(extensions[j][1:], fontsize=18)\n                ax.text(x_max, y_max, \"{:.1f}\".format(pgvs[j]), fontsize=14)\n\n    plt.savefig(os.path.join(output, f\"{station}.png\"))\n    plt.close()\n\n\nif __name__ == \"__main__\":\n    args = load_args()\n\n    # binary class object or text folder location\n    sources = [load_location(source[0], args.v) for source in args.waveforms]\n    # station list\n    stations = intersection([load_stations(source) for source in sources])\n    if args.n_stations is not None and args.n_stations < len(stations):\n        # random station selection\n        stations = np.random.choice(stations, args.n_stations, replace=False)\n    elif args.stations is not None:\n        # specific station selection\n        stations = np.intersect1d(stations, args.stations)\n    assert len(stations) > 0\n\n    p = Pool(args.nproc)\n    single_station = partial(\n        plot_station,\n        args.out,\n        sources,\n        [source[1] for source in args.waveforms],\n        args.tmax,\n        args.v,\n    )\n    p.map(single_station, stations)\n", "meta": {"hexsha": "7fb81024cc2badaf6b13c38d40752fbe1f91f540", "size": 7815, "ext": "py", "lang": "Python", "max_stars_repo_path": "waveform/waveforms.py", "max_stars_repo_name": "ucgmsim/visualization", "max_stars_repo_head_hexsha": "80ebfd39e10a254017cea8e122c1d73b7194072e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-22T04:59:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-05T17:42:48.000Z", "max_issues_repo_path": "waveform/waveforms.py", "max_issues_repo_name": "ucgmsim/visualization", "max_issues_repo_head_hexsha": "80ebfd39e10a254017cea8e122c1d73b7194072e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2018-07-26T05:07:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T01:10:18.000Z", "max_forks_repo_path": "waveform/waveforms.py", "max_forks_repo_name": "ucgmsim/visualization", "max_forks_repo_head_hexsha": "80ebfd39e10a254017cea8e122c1d73b7194072e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6022727273, "max_line_length": 85, "alphanum_fraction": 0.534996801, "include": true, "reason": "import numpy", "num_tokens": 1840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.2974699426047947, "lm_q1q2_score": 0.1580188218086202}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------------------------------------\nPython Script for Training the Deep Learning Model (StressNet) for \nTranspiration Stress (Short Vegetation)\n-------------------------------------------------------------------------------\nAuthor: Akash Koppa \nAffiliation: Hydro-Climate Extremes Lab (H-CEL), Ghent University, Belgium\nContact:  akash.koppa@ugent.be\n-------------------------------------------------------------------------------\nReference:\nKoppa, A., Rains, D., Hulsman, P., Poyatos, R., and Miralles, D. G. \nA deep learning-based hybrid model of global terrestrial evaporation. \nNature Communications 13, 1912 (2022). https://doi.org/10.1038/s41467-022-29543-7\n-------------------------------------------------------------------------------\n\"\"\"\n\n## import libraries\nimport tensorflow as tf\nimport os as os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n## user defined configuration\ninpdir = \"<< Specify path to input data here >>\"\n\n# station\nflxnet = {\"stn\": (os.path.join(inpdir, \"sites_short_vegetation.h5\"))} # sites\n# input features (absolute values)\nabsfil = {\"ate\": (os.path.join(inpdir, \"ate_short_vegetation.h5\")), # air temperature\n          \"co2\": (os.path.join(inpdir, \"co2_short_vegetation.h5\")), # carbon di oxide\n          \"ssh\": (os.path.join(inpdir, \"ssh_short_vegetation.h5\")), # plant available water\n          \"swi\": (os.path.join(inpdir, \"swi_short_vegetation.h5\")), # incoming shortwave radiation\n          \"vod\": (os.path.join(inpdir, \"vod_short_vegetation.h5\")), # vegetation optical depth\n          \"vpd\": (os.path.join(inpdir, \"vpd_short_vegetation.h5\"))} # vapor pressure deficit\n\n# input features (anomaly values)\nanmfil = {\"ate\": (os.path.join(inpdir, \"ate_short_vegetation_anomaly.h5\")),\n          \"co2\": (os.path.join(inpdir, \"co2_short_vegetation_anomaly.h5\")),\n          \"ssh\": (os.path.join(inpdir, \"ssh_short_vegetation_anomaly.h5\")),\n          \"swi\": (os.path.join(inpdir, \"swi_short_vegetation_anomaly.h5\")),\n          \"vod\": (os.path.join(inpdir, \"vod_short_vegetation_anomaly.h5\")),\n          \"vpd\": (os.path.join(inpdir, \"vpd_short_vegetation_anomaly.h5\"))}\n\n# target variable\ntarfil = {\"str\": (os.path.join(inpdir, \"str_short_vegetation.h5\"))} # transpiration stress\n\n# output path for the final trained StressNet\noutdir = \"<< Specify path to input data here >>\"\noutfil = os.path.join(outdir, \"stressnet_short_vegetation\")\n\n## main code\ndef main():\n    \"\"\"\n    Main control script\n\n    Returns\n    -------\n    A trained machine learning model with the required stress formulation\n    \"\"\"\n    \n    ## get the list of stations to subset the input data \n    # read in the fluxnet site locations\n    flxsit = pd.read_hdf(path_or_buf = flxnet[\"stn\"],   key=\"siteda\")\n    flxsit = flxsit.dropna(how = \"any\")\n    sitreq = flxsit.index\n    \n    ## create a combined tensorflow dataset\n    trndat, tstdat, sclmin, sclmax = h5totf(filabs = absfil, \n                                            filanm = anmfil, \n                                            filtar = tarfil,\n                                            sitreq = sitreq,\n                                            shufle = True,\n                                            batchn = 100,\n                                            trnper = 85)\n\n    ## get the required model \n    tstmod = funmod(inpshp = 12, \n                    losobj = kge,\n                    metric = kge,\n                    optmod = tf.keras.optimizers.Adam(learning_rate = 0.000142))\n\n    ## train the deep learning model\n    histst = tstmod.fit(trndat,\n                        epochs = 900,\n                        validation_data = tstdat)\n\n    ## plot evolution of the loss function\n    evolut = pd.DataFrame(histst.history)\n    evorms = evolut[[\"kge\",\"val_kge\"]]\n    evorms.plot()\n\n    ## save the model\n    tstmod.save(outfil)\n\n\n## functions\n# function to preprocess input data\ndef h5totf(filabs, filanm, filtar, sitreq, shufle, batchn, trnper):\n    \"\"\"\n    Script to convert the input hdf5 files into tensorflow datasets which act \n    as the primary input for the deep neural network\n\n    Parameters\n    ----------\n    filabs : dictionary\n        full paths to input feature data (absolute values)\n    filanm : dictionary\n        full path to input feature data (anomalies)\n    filtar : dictionary\n        full path to the target variable\n    sitreq : list\n        list of fluxnet sites\n    shufle : Boolean\n        True if data needs to be shuffled\n    batchn : integer\n        number of batches into which the data needs to divided into\n    trnper : integer\n        percentage between 0 and 100 based on which the data will be \n        divided into training and testing dataset\n\n    Returns\n    -------\n    retn01 : A tf.dataset with the training input features and target variables\n    retn02 : A tf.dataset with the testing input features and target variables\n    retn03 : A vector with min values of the input features and target variables\n    retn04 : A vector with max values of the input features and target variables\n\n    \"\"\"\n    \n    # loop through the different input variables and create final dictionary\n    inpdat = {}\n    for i in filabs.keys():\n        print(\"var under process: \" + i)\n        # read in the absolute values\n        tmpabs = pd.read_hdf(filabs[i])\n        #  read in the anomaly values\n        tmpanm = pd.read_hdf(filanm[i])\n        \n        # store the data in dictionary\n        inpdat[i] = tmpabs\n        inpdat[i+\"anm\"] = tmpanm\n    # target variable    \n    tardat = {}\n    for i in filtar.keys():\n        print(\"var under process: \" + i)\n        tmptar = pd.read_hdf(filtar[i])\n        tmptar[tmptar > 1] = 1.0\n        tardat[i] = tmptar\n    \n    print(inpdat.keys())\n        \n    # loop through the stations and create a final dataset containing only \n    #   the input variables\n    datlst = []\n    for i in sitreq:\n        print(\"site under process: \" + i)\n        lsttmp = []\n        for j in inpdat.keys():\n            tmpvar = inpdat[j][i]\n            tmpvar.name = j\n            lsttmp.append(inpdat[j][i])\n        # create a data frame of variables for each \n        # append the target stress\n        tartmp = tardat[list(tardat.keys())[0]][i]\n        tartmp.name = list(tardat.keys())[0]\n        lsttmp.append(tartmp)\n        dattmp = pd.concat(lsttmp, axis = 1)\n        dattmp = dattmp.replace(to_replace = -9999.0, value = np.nan)\n        dattmp = dattmp.replace(to_replace = -999.0, value = np.nan )\n        dattmp = dattmp.dropna(axis = 0, how = \"any\")\n        datlst.append(dattmp)\n            \n    del dattmp\n    \n    # create the final pandas data frame\n    datfin = pd.concat(datlst, ignore_index = True)\n    datfin = datfin.dropna(axis = 0, how = \"any\")\n    print(datfin.shape)\n    print(datfin.columns)\n   \n    # reset index \n    datfin = datfin.reset_index(drop = True)\n    \n    # shuffle the data\n    if shufle == True:\n        print(\" >> shuffling data\")\n        datfin = datfin.sample(frac = 1)\n    \n    \n    # normalize by max\n    print(\" >> normalizing the data by max\")\n    tarval = datfin.pop(list(tardat.keys())[0])\n    \n    # calculate the max and min for backup\n    datmin = datfin.quantile(0.05)\n    datmax = datfin.quantile(0.95)\n    datfin = datfin/datmax\n\n    # convert the pandas data frame to a tf.dataset\n    print(\" >> Converting data frame into a tensorflow dataset\")\n    print(datfin.columns)\n    print(datfin.shape)\n    fullda = tf.data.Dataset.from_tensor_slices((datfin.values, \n                                                 tarval.values))\n    \n    # split into training and testing datasets\n    trnsiz = int((trnper/100) * len(datfin))\n    # training dataset\n    retn01 = fullda.take(trnsiz)\n    # testing dataset\n    retn02 = fullda.skip(trnsiz)\n        \n    if shufle == True:\n        retn01 = retn01.shuffle(trnsiz)\n        tstsiz = len(datfin) - trnsiz\n        retn02 = retn02.shuffle(tstsiz)\n        \n    retn01 = retn01.batch(batchn)\n    retn02 = retn02.batch(batchn)\n    retn03 = datmin\n    retn04 = datmax\n    \n    return retn01, retn02, retn03, retn04\n\n# kling gupta efficiency\ndef kge(actual, predct):\n    \"\"\"\n    a custom loss function based on the Kling Gupta Efficiency\n    formula: [1 - sqrt((r-1)**2 + ((stddev_sim/stddev_obs)-1)**2 + ((mean_sim/mean_obs) - 1)**2)]\n    reference: Decomposition of the mean squared error and NSE performance criteria: \n               Implications for improving hydrological modelling. (2009). \n               Journal of Hydrology, 377(1–2), 80–91. \n               DOI: https://doi.org/10.1016/j.jhydrol.2009.08.003\n\n    Parameters\n    ----------\n    actual : tensor\n        ground truth data for the predictions to be compared against\n    predct : tensor\n        predicted data\n\n    Returns\n    -------\n    (1-kge): scalar\n        The loss function to be minimized\n\n    \"\"\"\n    # >>> correlation\n    acmean = tf.math.reduce_mean(actual)\n    pdmean = tf.math.reduce_mean(predct)\n    acmdev, pdmdev = actual - acmean, predct - pdmean\n    cornum = tf.math.reduce_mean(tf.multiply(acmdev, pdmdev))        \n    corden = tf.math.reduce_std(acmdev) * tf.math.reduce_std(pdmdev)\n    corcof = cornum / corden\n    cratio = (corcof - 1)**2\n    \n    # variability ratio\n    actstd = tf.math.reduce_std(actual)\n    prestd = tf.math.reduce_std(predct)\n    stdrat = prestd / actstd\n    vratio = (stdrat - 1)**2\n    \n    # bias ratio (Beta)\n    menrat = pdmean / acmean\n    bratio = (menrat - 1)**2\n    \n    kgeval = 1 - tf.math.sqrt(cratio + vratio + bratio)\n    retn01 = 1 - kgeval\n    \n    return retn01\n\n# deep learning model\ndef funmod(inpshp, losobj, metric, optmod):\n    \"\"\"\n    Function to create a machine learning model using the Functional API module\n    of tensorflow. This module can be used to create more powerful machine\n    learning models compared to the sequential module\n\n    Parameters\n    ----------\n    inpshp : integer\n        The number of input variables\n    losobj : tf.keras.losses \n        A tensorflow loss function \n    metric : tf.keras.metrics\n        A tensorflow error metric function\n    optmod : character\n        An optimizer which is available in tensorflow\n\n    Returns\n    -------\n    retn01 : tf.keras.Model\n        A compiled Functional API model\n\n    \"\"\"\n    print(\" >>> creating a Functional API model\")\n    # define the input layers\n    inplyr = tf.keras.Input(shape = (inpshp, ))\n    \n    crslyr = tf.keras.layers.Dense(512, activation=tf.nn.swish)(inplyr)\n    crslyr = tf.keras.layers.Dropout(0.45)(crslyr)\n    crslyr = tf.keras.layers.Dense(256, activation=tf.nn.swish)(crslyr)\n    crslyr = tf.keras.layers.Dropout(0.3)(crslyr)\n    \n    seqlyr = tf.keras.layers.Dense(792, activation=tf.nn.swish)(inplyr)\n    seqlyr = tf.keras.layers.Dropout(0.45)(seqlyr)\n    seqlyr = tf.keras.layers.Dense(512, activation=tf.nn.gelu)(seqlyr)\n    seqlyr = tf.keras.layers.Dropout(0.45)(seqlyr)\n    \n    concat = tf.keras.layers.concatenate([crslyr, seqlyr, inplyr])\n    \n    outlyr = tf.keras.layers.Dense(768, activation=tf.nn.swish)(concat)\n    outlyr = tf.keras.layers.Dropout(0.4)(outlyr)\n    outlyr = tf.keras.layers.Dense(384, activation=tf.nn.swish)(outlyr)\n    outlyr = tf.keras.layers.Dropout(0.4)(outlyr)\n    outlyr = tf.keras.layers.Dense(256, activation=tf.nn.swish)(outlyr)\n    outlyr = tf.keras.layers.Dropout(0.4)(outlyr)\n    conca1 = tf.keras.layers.concatenate([outlyr, inplyr])\n    outly1 = tf.keras.layers.Dense(256, activation=tf.nn.swish)(conca1)\n    outly1 = tf.keras.layers.Dropout(0.3)(outly1)\n    outly1 = tf.keras.layers.Dense(172, activation=tf.nn.swish)(outlyr)\n    outly1 = tf.keras.layers.Dropout(0.35)(outlyr)\n    conca2 = tf.keras.layers.concatenate([outly1, inplyr])\n\n    outly2 = tf.keras.layers.Dense(128, activation=tf.nn.swish)(conca2)\n    outly2 = tf.keras.layers.Dropout(0.3)(outly2)\n    outly2 = tf.keras.layers.Dense(64, activation=tf.nn.gelu)(outly2)\n    outmod = tf.keras.layers.Dense(6)(outly2)\n    \n    # combine the layers into a full model\n    tmpmod = tf.keras.Model(inputs = inplyr, \n                            outputs = outmod, \n                            name = \"glmfun\")\n    \n    # define a loss function \n    losobj = losobj\n    # define a metric function\n    metric = [metric]\n    # compile the model\n    tmpmod.compile(optimizer = optmod, \n                   loss = losobj, \n                   metrics = metric)\n    # return the compiled model\n    retn01 = tmpmod\n    \n    return retn01\n    \n## run the main script\nif __name__ == \"__main__\":\n    main()\n", "meta": {"hexsha": "ac52340a064fb945eb150439000b12617c0ef1fb", "size": 12562, "ext": "py", "lang": "Python", "max_stars_repo_path": "stressnet/train_short_vegetation.py", "max_stars_repo_name": "akashkoppa/StressNet", "max_stars_repo_head_hexsha": "f5ae501ec1d66d72754a18e5d1e15c5755f60779", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stressnet/train_short_vegetation.py", "max_issues_repo_name": "akashkoppa/StressNet", "max_issues_repo_head_hexsha": "f5ae501ec1d66d72754a18e5d1e15c5755f60779", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stressnet/train_short_vegetation.py", "max_forks_repo_name": "akashkoppa/StressNet", "max_forks_repo_head_hexsha": "f5ae501ec1d66d72754a18e5d1e15c5755f60779", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4858757062, "max_line_length": 98, "alphanum_fraction": 0.6062728865, "include": true, "reason": "import numpy", "num_tokens": 3319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.2974699363766585, "lm_q1q2_score": 0.15801881850017588}}
{"text": "from __future__ import annotations\nimport astropy.coordinates\nimport astropy.units\nimport astropy.time\nimport collections\nimport datetime\nimport dataclasses\nimport erfa\nimport functools\nimport itertools\nimport logging\nimport numpy\nimport pathlib\nimport requests\nimport scipy.optimize\nimport typing\nfrom . import provider as provider\nfrom . import satellite as satellite\nfrom . import timesystem as timesystem\nfrom .parse import (\n    Version as Version,\n    FileType as FileType,\n    Record as Record,\n    Satellite as Satellite,\n    Product as Product,\n)\nfrom .provider import cddis as cddis\n\n\n@dataclasses.dataclass(init=False)\nclass Id:\n    value: bytes\n\n    def __init__(self, _: typing.Union[str, bytes]):\n        raise NotImplementedError()\n\n\n@dataclasses.dataclass(init=False)\nclass Sp3Id(Id):\n    def __init__(self, value: typing.Union[str, bytes]):\n        self.value = value.encode() if isinstance(value, str) else value\n        assert satellite.sp3_pattern.match(self.value) is not None\n\n\n@dataclasses.dataclass(init=False)\nclass NoradId(Id):\n    def __init__(self, value: typing.Union[str, bytes, int]):\n        if isinstance(value, int):\n            self.value = str(value).encode()\n        elif isinstance(value, str):\n            self.value = value.encode()\n        else:\n            self.value = value\n        assert satellite.norad_pattern.match(self.value) is not None\n\n\ntotal_seconds = numpy.vectorize(lambda delta: delta.total_seconds())\n\n\n@dataclasses.dataclass\nclass PiecewisePolynomial:\n    minimum_time: datetime.datetime\n    maximum_time: datetime.datetime\n    reference_time: datetime.datetime\n    offset: numpy.ndarray\n    begin: numpy.ndarray\n    coefficients: numpy.ndarray\n    velocity_coefficients: numpy.ndarray\n\n    def __call__(self, obstime: astropy.time.Time) -> astropy.coordinates.ITRS:\n        assert obstime.scale == \"utc\"\n        first_obstime: datetime.datetime = obstime.min().to_datetime(timezone=datetime.timezone.utc)  # type: ignore\n        if first_obstime < self.minimum_time:\n            raise Exception(\n                \"the first obstime is too close to the first record to interpolate\"\n            )\n        last_obstime: datetime.datetime = obstime.max().to_datetime(timezone=datetime.timezone.utc)  # type: ignore\n        if last_obstime >= self.maximum_time:\n            raise Exception(\n                \"the last obstime is too close to the last record to interpolate\"\n            )\n        relative_obstime = total_seconds(\n            obstime.to_datetime(timezone=datetime.timezone.utc) - self.reference_time\n        )\n        index = numpy.searchsorted(self.begin, relative_obstime, side=\"right\") - 1\n        relative_obstime -= self.offset[index]\n        return astropy.coordinates.ITRS(\n            x=(\n                (\n                    numpy.polynomial.polynomial.polyval(\n                        relative_obstime,\n                        self.coefficients[:, index, 0],\n                        tensor=False,\n                    )\n                )\n            )\n            * astropy.units.Unit(\"m\"),\n            y=(\n                (\n                    numpy.polynomial.polynomial.polyval(\n                        relative_obstime,\n                        self.coefficients[:, index, 1],\n                        tensor=False,\n                    )\n                )\n            )\n            * astropy.units.Unit(\"m\"),\n            z=(\n                (\n                    numpy.polynomial.polynomial.polyval(\n                        relative_obstime,\n                        self.coefficients[:, index, 2],\n                        tensor=False,\n                    )\n                )\n            )\n            * astropy.units.Unit(\"m\"),\n            v_x=(\n                (\n                    numpy.polynomial.polynomial.polyval(\n                        relative_obstime,\n                        self.velocity_coefficients[:, index, 0],\n                        tensor=False,\n                    )\n                )\n            )\n            * astropy.units.Unit(\"m/s\"),\n            v_y=(\n                (\n                    numpy.polynomial.polynomial.polyval(\n                        relative_obstime,\n                        self.velocity_coefficients[:, index, 1],\n                        tensor=False,\n                    )\n                )\n            )\n            * astropy.units.Unit(\"m/s\"),\n            v_z=(\n                (\n                    numpy.polynomial.polynomial.polyval(\n                        relative_obstime,\n                        self.velocity_coefficients[:, index, 2],\n                        tensor=False,\n                    )\n                )\n            )\n            * astropy.units.Unit(\"m/s\"),\n            obstime=obstime,\n        )\n\n\ndef narrowed_records_to_piecewise_polynomial(\n    records: typing.Sequence[Record],\n    window: int,\n    degree: int,\n) -> PiecewisePolynomial:\n    assert degree >= 0\n    assert window * 2 + 1 > degree\n    if len(records) < window * 2 + 1:\n        raise Exception(\"insufficient number of records\")\n    record_position = numpy.array(tuple(record.position for record in records))\n    relative_record_time = total_seconds(\n        numpy.array(tuple(record.time - records[0].time for record in records))\n    )\n    relative_record_time_diff = numpy.diff(relative_record_time)\n    offset = relative_record_time[window : len(records) - window]\n    begin = (\n        relative_record_time[window : len(records) - window]\n        - relative_record_time_diff[window - 1 : len(records) - window - 1] / 2\n    )\n    coefficients = numpy.zeros(\n        (len(records) - 2 * window, degree + 1, 3), dtype=numpy.double\n    )\n    mean = numpy.zeros((len(records) - 2 * window, 3))\n    std = numpy.zeros((len(records) - 2 * window, 3))\n    for index in range(0, len(coefficients)):\n        mean[index] = numpy.mean(\n            record_position[index : index + 2 * window + 1], axis=0\n        )\n        std[index] = numpy.std(record_position[index : index + 2 * window + 1], axis=0)\n        coefficients[index] = numpy.polynomial.polynomial.polyfit(\n            relative_record_time[index : index + 2 * window + 1] - offset[index],\n            (record_position[index : index + 2 * window + 1] - mean[index])\n            / std[index],\n            deg=degree,\n        )\n    coefficients = coefficients.transpose((1, 0, 2)) * std\n    coefficients[0] += mean\n    if all(record.velocity is not None for record in records):\n        record_velocity = numpy.array(tuple(record.velocity for record in records))\n        velocity_coefficients = numpy.zeros(\n            (len(records) - 2 * window, degree + 1, 3), dtype=numpy.double\n        )\n        velocity_mean = numpy.zeros((len(records) - 2 * window, 3))\n        velocity_std = numpy.zeros((len(records) - 2 * window, 3))\n        for index in range(0, len(velocity_coefficients)):\n            velocity_mean[index] = numpy.mean(\n                record_velocity[index : index + 2 * window + 1], axis=0\n            )\n            velocity_std[index] = numpy.std(\n                record_velocity[index : index + 2 * window + 1], axis=0\n            )\n            velocity_coefficients[index] = numpy.polynomial.polynomial.polyfit(\n                relative_record_time[index : index + 2 * window + 1] - offset[index],\n                (record_velocity[index : index + 2 * window + 1] - velocity_mean[index])\n                / velocity_std[index],\n                deg=degree,\n            )\n        velocity_coefficients = (\n            velocity_coefficients.transpose((1, 0, 2)) * velocity_std\n        )\n        velocity_coefficients[0] += velocity_mean\n    else:\n        velocity_coefficients = numpy.polynomial.polynomial.polyder(coefficients)\n    return PiecewisePolynomial(\n        minimum_time=records[window].time,\n        maximum_time=records[-window].time,\n        reference_time=records[0].time,\n        offset=offset,\n        begin=begin,\n        coefficients=coefficients,\n        velocity_coefficients=velocity_coefficients,\n    )\n\n\ndef records_to_piecewise_polynomial(\n    records: typing.Sequence[Record],\n    begin: datetime.datetime,\n    end: datetime.datetime,\n    window: int,\n    degree: int,\n) -> PiecewisePolynomial:\n    assert begin.tzinfo == datetime.timezone.utc\n    assert end.tzinfo == datetime.timezone.utc\n    assert begin < end\n    if begin < records[window].time:\n        raise Exception(\n            f\"begin ({begin}) is too close to the first record to interpolate\"\n        )\n    if end >= records[-window].time:\n        raise Exception(f\"end ({end}) is too close to the last record to interpolate\")\n    begin_record_index = 0\n    for index, record in enumerate(records):\n        if begin < record.time:\n            begin_record_index = index - 1\n            break\n    end_record_index = len(records)\n    for index, record in enumerate(reversed(records)):\n        if end >= record.time:\n            end_record_index = len(records) - 1 - (index - 1)\n            break\n    return narrowed_records_to_piecewise_polynomial(\n        records=list(\n            itertools.islice(\n                records, begin_record_index - window, end_record_index + window\n            )\n        ),\n        window=window,\n        degree=degree,\n    )\n\n\ndef load(\n    id: Id,\n    begin: datetime.datetime,\n    end: datetime.datetime,\n    download_directory: typing.Union[str, bytes, pathlib.Path],\n    window: int,\n    force_download: bool = False,\n) -> typing.Sequence[Record]:\n    sp3_id: bytes\n    if isinstance(id, Sp3Id):\n        sp3_id = id.value\n    elif isinstance(id, NoradId):\n        sp3_id = satellite.norad_to_satellite[id.value].sp3\n    else:\n        raise Exception(f\"unsupported id type {id.__class__}\")\n    assert begin.tzinfo == datetime.timezone.utc\n    assert end.tzinfo == datetime.timezone.utc\n    assert begin < end\n    if isinstance(download_directory, bytes):\n        download_directory = pathlib.Path(download_directory.decode())\n    elif isinstance(download_directory, str):\n        download_directory = pathlib.Path(download_directory)\n    provider_found = False\n    records: collections.deque[Record] = collections.deque()\n    for candidate_provider in provider.find_providers_of(sp3_id):\n        offset = 0.0\n        begin_covered = False\n        end_covered = False\n        while True:\n            try:\n                product = Product.from_file(\n                    candidate_provider.download(\n                        time=candidate_provider.time_system.offset_seconds(\n                            begin, offset\n                        ),\n                        download_directory=download_directory,\n                        force=force_download,\n                    )\n                )\n                candidate_satellite = product.satellite_with_id(sp3_id)\n                if offset < 0.0:\n                    for record in candidate_satellite.records[::-1]:\n                        if len(records) == 0 or record.time < records[0].time:\n                            records.appendleft(record)\n                else:\n                    for record in candidate_satellite.records:\n                        if len(records) == 0 or record.time > records[-1].time:\n                            records.append(record)\n                if len(records) > window:\n                    begin_covered = begin >= records[window].time\n                    end_covered = end < records[-window].time\n                    if begin_covered:\n                        if end_covered:\n                            provider_found = True\n                            break\n                        else:\n                            offset = max(offset, 0.0) + candidate_provider.duration\n                    else:\n                        offset = min(offset, 0.0) - candidate_provider.duration\n            except requests.exceptions.HTTPError as error:\n                if error.response.status_code == 404:\n                    logging.warning(f'\"{error.request.url}\" returned error 404')\n                    break\n                raise error\n            except LookupError as error:\n                if error.args[0] == sp3_id:\n                    break\n                raise error\n        if provider_found:\n            break\n    if not provider_found:\n        raise Exception(f'no suitable SP3 provider for \"{sp3_id.decode()}\"')\n    return records\n\n\ndef obstime_to_begin_and_end(obstime: astropy.time.Time):\n    assert obstime.scale == \"utc\"\n    begin: datetime.datetime = obstime.min().to_datetime(timezone=datetime.timezone.utc)  # type: ignore\n    end: datetime.datetime = obstime.max().to_datetime(timezone=datetime.timezone.utc)  # type: ignore\n    while begin == end:\n        end += datetime.timedelta(microseconds=1)\n    return begin, end\n\n\ndef itrs(\n    id: Id,\n    obstime: astropy.time.Time,\n    download_directory: typing.Union[str, bytes, pathlib.Path],\n    window: int = 5,\n    degree: int = 10,\n) -> astropy.coordinates.ITRS:\n    begin, end = obstime_to_begin_and_end(obstime)\n    return records_to_piecewise_polynomial(\n        records=load(\n            id=id,\n            begin=begin,\n            end=end,\n            window=window,\n            download_directory=download_directory,\n            force_download=False,\n        ),\n        begin=begin,\n        end=end,\n        window=window,\n        degree=degree,\n    )(obstime)\n\n\ndef altaz(\n    id: Id,\n    obstime: astropy.time.Time,\n    location: astropy.coordinates.EarthLocation,\n    pressure: astropy.units.Quantity,\n    temperature: astropy.units.Quantity,\n    relative_humidity: astropy.units.Quantity,\n    obswl: astropy.units.Quantity,\n    download_directory: typing.Union[str, bytes, pathlib.Path],\n    window: int = 5,\n    degree: int = 10,\n) -> astropy.coordinates.AltAz:\n    begin, end = obstime_to_begin_and_end(obstime)\n    piecewise_polynomial = records_to_piecewise_polynomial(\n        records=load(\n            id=id,\n            begin=begin - datetime.timedelta(seconds=2.0),\n            end=end,\n            window=window,\n            download_directory=download_directory,\n            force_download=False,\n        ),\n        begin=begin,\n        end=end,\n        window=window,\n        degree=degree,\n    )\n    c = astropy.constants.c.to(\"m/s\").value  # type: ignore\n    location_itrs = location.get_itrs().cartesian.get_xyz()\n\n    def light_time_correction_error(\n        scalar_light_time_correction: float, scalar_obstime: astropy.time.Time\n    ):\n        return (\n            numpy.linalg.norm(\n                (\n                    piecewise_polynomial(\n                        scalar_obstime\n                        - scalar_light_time_correction * astropy.units.Unit(\"s\")\n                    ).cartesian.get_xyz()\n                    - location_itrs\n                )\n                .to(\"m\")\n                .value\n            )\n            - scalar_light_time_correction * c\n        )\n\n    light_time_correction = numpy.zeros(len(obstime))\n    for index, scalar_obstime in enumerate(obstime):\n        light_time_correction[index] = scipy.optimize.root_scalar(\n            f=functools.partial(\n                light_time_correction_error, scalar_obstime=scalar_obstime  # type: ignore\n            ),\n            method=\"brentq\",\n            bracket=[0.0, 2.0],\n        ).root\n    corrected_obstime = obstime - light_time_correction * astropy.units.Unit(\"s\")\n    itrs = piecewise_polynomial(corrected_obstime)\n    itrs_vector = itrs.cartesian.get_xyz().transpose() - location_itrs\n    cirs_non_topographic = astropy.coordinates.ITRS(\n        x=itrs_vector[:, 0],\n        y=itrs_vector[:, 1],\n        z=itrs_vector[:, 2],\n        v_x=itrs.v_x,\n        v_y=itrs.v_y,\n        v_z=itrs.v_z,\n        obstime=obstime,\n    ).transform_to(astropy.coordinates.CIRS(obstime=obstime))\n    cirs = astropy.coordinates.CIRS(\n        ra=cirs_non_topographic.ra,\n        dec=cirs_non_topographic.dec,\n        distance=cirs_non_topographic.distance,\n        pm_ra_cosdec=cirs_non_topographic.pm_ra_cosdec,\n        pm_dec=cirs_non_topographic.pm_dec,\n        radial_velocity=cirs_non_topographic.radial_velocity,\n        obstime=obstime,\n        location=location,\n    )\n    altaz_vacuo = cirs.transform_to(\n        astropy.coordinates.AltAz(obstime=obstime, location=location)\n    )\n    refraction_a, refraction_b = erfa.refco(\n        phpa=pressure.to(\"hPa\").value,\n        tc=temperature.to(\"deg_C\").value,\n        rh=relative_humidity.value,\n        wl=obswl.to(\"um\").value,\n    )\n    distance_to_zenith = numpy.pi / 2 - altaz_vacuo.alt.to(\"rad\").value\n    tan_distance_to_zenith = numpy.tan(distance_to_zenith)\n    alt_refraction_correction = (\n        refraction_a * tan_distance_to_zenith\n        + refraction_b * (tan_distance_to_zenith**3)\n    ) * astropy.units.Unit(\"rad\")\n    # derivative of a tan(π / 2 - alt) + b tan(π / 2 - alt)³\n    pm_alt_refraction_correction = (\n        -altaz_vacuo.pm_alt\n        * (numpy.cos(distance_to_zenith) ** -2)\n        * (refraction_a + 3 * refraction_b * tan_distance_to_zenith**2)\n    )\n    return astropy.coordinates.AltAz(\n        alt=altaz_vacuo.alt + alt_refraction_correction,\n        az=altaz_vacuo.az,\n        pm_az_cosalt=altaz_vacuo.pm_az_cosalt,\n        pm_alt=altaz_vacuo.pm_alt + pm_alt_refraction_correction,\n        obstime=obstime,\n        location=location,\n        pressure=pressure,\n        temperature=temperature,\n        relative_humidity=relative_humidity,\n        obswl=0.8 * astropy.units.Unit(\"um\"),\n    )\n\n\ndef altaz_standard_atmosphere(\n    id: Id,\n    obstime: astropy.time.Time,\n    location: astropy.coordinates.EarthLocation,\n    download_directory: typing.Union[str, bytes, pathlib.Path],\n    temperature: astropy.units.Quantity = 20.0 * astropy.units.Unit(\"deg_C\"),  # type: ignore\n    relative_humidity: astropy.units.Quantity = 0.0 * astropy.units.dimensionless_unscaled,  # type: ignore\n    obswl: astropy.units.Quantity = 0.8 * astropy.units.Unit(\"um\"),  # type: ignore\n    window: int = 5,\n    degree: int = 10,\n):\n    # https://en.wikipedia.org/wiki/Barometric_formula\n    p0 = 101325 * astropy.units.Unit(\"Pa\")\n    l0 = -0.0065 * astropy.units.Unit(\"K/m\")\n    t0 = 288.15 * astropy.units.Unit(\"K\")\n    g0 = 9.80665 * astropy.units.Unit(\"m/s2\")\n    m = 0.0289644 * astropy.units.Unit(\"kg\")\n    rstar = 8.3144598 * astropy.units.Unit(\"J/K\")\n    pressure = p0 * ((1.0 + (l0 * location.height / t0)) ** ((-g0 * m) / (rstar * l0)))  # type: ignore\n    return altaz(\n        id=id,\n        obstime=obstime,\n        location=location,\n        pressure=pressure,\n        temperature=temperature,\n        relative_humidity=relative_humidity,\n        obswl=obswl,\n        download_directory=download_directory,\n        window=window,\n        degree=degree,\n    )\n", "meta": {"hexsha": "cd799eea7425978c5dcbf0cacf7061e5c8fdf1f0", "size": 18696, "ext": "py", "lang": "Python", "max_stars_repo_path": "sp3/__init__.py", "max_stars_repo_name": "neuromorphicsystems/sp3", "max_stars_repo_head_hexsha": "19c71aa078b32cdb1f8417b405359356b2be2f47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-10T23:39:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T23:39:40.000Z", "max_issues_repo_path": "sp3/__init__.py", "max_issues_repo_name": "neuromorphicsystems/sp3", "max_issues_repo_head_hexsha": "19c71aa078b32cdb1f8417b405359356b2be2f47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sp3/__init__.py", "max_forks_repo_name": "neuromorphicsystems/sp3", "max_forks_repo_head_hexsha": "19c71aa078b32cdb1f8417b405359356b2be2f47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2325581395, "max_line_length": 116, "alphanum_fraction": 0.5897518186, "include": true, "reason": "import numpy,import scipy,import astropy", "num_tokens": 4158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.29098087236345377, "lm_q1q2_score": 0.15796283601571198}}
{"text": "'''\nThis algorithm is a IA-RL implementation on off-policy TD3 algorithm, to check the original IA-RL algorithm\nyou can refer to https://arxiv.org/abs/1811.06187.\nSince it is a baseline algorithm, the descriptions are mostly omitted, please visit the HUGTD3.py for more implementation details\n'''\n\nimport pickle\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\n\nfrom TD3_based_DRL.priority_replay import Memory\nfrom TD3_based_DRL.network_model import Actor,Critic\nfrom TD3_based_DRL.util import hard_update, soft_update\n\nseed = 2\ntorch.manual_seed(seed)\ntorch.cuda.manual_seed(seed)\nnp.random.seed(seed)\ntorch.manual_seed(seed)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\n\nMEMORY_CAPACITY = 38400\nBATCH_SIZE = 128\nGAMMA = 0.95\nLR_C = 0.0005\nLR_A = 0.0002\nLR_I = 0.01\nTAU = 0.001\nPOLICY_NOSIE = 0.2\nPOLICY_FREQ = 1\nNOISE_CLIP = 0.5\n\nclass DRL:\n        \n    def __init__(self, action_dim, state_dim, LR_C = LR_C, LR_A = LR_A):\n\n        self.device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n        \n        self.state_dim = state_dim[0] * state_dim[1]\n        self.state_dim_width = state_dim[0]\n        self.state_dim_height = state_dim[1]\n        self.action_dim = action_dim\n        self.batch_size = BATCH_SIZE\n        self.gamma = GAMMA\n        self.tau = TAU\n        self.policy_noise = POLICY_NOSIE\n        self.noise_clip = NOISE_CLIP\n        self.policy_freq = POLICY_FREQ\n        self.itera = 0\n\n        self.pointer = 0\n        self.memory = Memory(MEMORY_CAPACITY)\n        \n        self.actor = Actor(self.state_dim,self.action_dim).to(self.device)\n        self.actor_target = Actor(self.state_dim,self.action_dim).to(self.device)\n        self.actor_optimizer = torch.optim.Adam(self.actor.parameters(),LR_A)\n        \n        self.critic = Critic(self.state_dim,self.action_dim).to(self.device)\n        self.critic_target = Critic(self.state_dim,self.action_dim).to(self.device)\n        self.critic_optimizers = torch.optim.Adam(self.critic.parameters(),LR_C)\n        \n        hard_update(self.actor_target,self.actor)\n        hard_update(self.critic_target,self.critic)\n        \n            \n    def learn(self, batch_size = BATCH_SIZE, epoch=0):\n\n        ## batched state, batched action, batched action from expert, batched intervention signal, batched reward, batched next state\n        bs, ba, ba_e, bi, br, bs_, tree_idx, ISweight = self.retrive(batch_size)\n        bs = torch.tensor(bs, dtype=torch.float).reshape(batch_size, self.state_dim_height, self.state_dim_width).to(self.device)\n        ba = torch.tensor(ba, dtype=torch.float).to(self.device).to(self.device)\n        ba_e = torch.tensor(ba_e, dtype=torch.float).to(self.device).to(self.device)\n        br = torch.tensor(br, dtype=torch.float).to(self.device).to(self.device)\n        bs_ = torch.tensor(bs_, dtype=torch.float).reshape(batch_size, self.state_dim_height, self.state_dim_width).to(self.device)\n\n        # initialize the loss variables\n        loss_c, loss_a = 0, 0\n\n        ## calculate the predicted values of the critic\n        with torch.no_grad():\n            noise1 = (torch.randn_like(ba) * self.policy_noise).clamp(0, 1)\n            a_ = (self.actor_target(bs_).detach() + noise1).clamp(0, 1)\n            target_q1, target_q2 = self.critic_target([bs_,a_])\n            target_q1 = target_q1.detach()\n            target_q2 = target_q2.detach()\n            target_q = torch.min(target_q1,target_q2)\n            y_expected = br + self.gamma * target_q    \n        y_predicted1, y_predicted2 = self.critic.forward([bs,ba]) \n        errors = y_expected - y_predicted1\n        \n        ## update the critic\n        critic_loss = nn.MSELoss()\n        loss_critic = critic_loss(y_predicted1,y_expected)+critic_loss(y_predicted2,y_expected)\n        self.critic_optimizers.zero_grad()\n        loss_critic.backward()\n        self.critic_optimizers.step()\n\n        ## update the actor\n        if self.itera % self.policy_freq == 0:\n\n            index1,_ = np.where(bi==0)\n            index2,_ = np.where(bi==1)\n            bs1,_,_,_=bs[index1],ba[index1],br[index1],bs_[index1]\n            bs2,ba2,_,_=bs[index2],ba[index2],br[index2],bs_[index2]\n        \n            if bs2.size(0) != 0:\n                if bs1.size(0) != 0:\n                    bs1 = torch.reshape(bs1,(len(bs1), self.state_dim_height, self.state_dim_width))\n                    bs2 = torch.reshape(bs2,(len(bs2), self.state_dim_height, self.state_dim_width))\n                    pred_a1 = self.actor.forward(bs1)\n                    pred_a2 = self.actor.forward(bs2)\n                    loss_actor1 = (-self.critic.forward([bs1,pred_a1])[0])\n                    ## fixed weight for human guidance actions\n                    loss_actor2 = 3 * ((pred_a2 - ba2)**2)\n                    loss_actor = torch.cat((loss_actor1,loss_actor2),0).mean()\n                else:\n                    pred_a = self.actor.forward(bs)\n                    loss_actor = 3*((pred_a - ba)**2)\n                    loss_actor = loss_actor.mean()\n            else:\n                pred_a = self.actor.forward(bs)\n                loss_actor = (-self.critic.forward([bs,pred_a])[0]).mean()\n            \n            self.actor_optimizer.zero_grad()\n            loss_actor.backward()\n            self.actor_optimizer.step()\n\n            soft_update(self.actor_target,self.actor,self.tau)\n            soft_update(self.critic_target,self.critic,self.tau)\n\n            loss_a = loss_actor.mean().item()\n\n        loss_c = loss_critic.mean().item()\n        \n        self.itera += 1\n\n        self.memory.batch_update(tree_idx, abs(errors.detach().cpu().numpy()) )\n\n        return loss_c, loss_a\n    \n                \n    def choose_action(self,state):\n\n        state = torch.tensor(state,dtype=torch.float).reshape(self.state_dim_height, self.state_dim_width).to(self.device)\n        state = state.unsqueeze(0)\n        \n        action = self.actor.forward(state).detach()\n        action = action.squeeze(0).cpu().numpy()\n        action = np.clip(action,-1, 1)\n\n        return action\n    \n\n    def store_transition(self, s, a, a_e, i, r, s_):\n        transition = np.hstack((s, a, a_e, i, r, s_)) \n        self.memory.store(transition)\n        self.pointer += 1\n    \n\n    def retrive(self, batch_size):\n        tree_index, bt, ISWeight = self.memory.sample(batch_size) \n        bs = bt[:, :self.state_dim]\n        ba = bt[:, self.state_dim: self.state_dim + self.action_dim]\n        ba_e = bt[:, self.state_dim + self.action_dim: self.state_dim + self.action_dim + self.action_dim]\n        bi = bt[:, -self.state_dim - 2: -self.state_dim - 1]\n        br = bt[:, -self.state_dim - 1: -self.state_dim]\n        bs_ = bt[:, -self.state_dim:]\n        \n        return bs, ba, ba_e, bi, br, bs_, tree_index, ISWeight\n    \n\n    def memory_save(self):\n        \n        per = open(\"memory_IARL.pkl\", 'wb')\n        str = pickle.dumps(self.memory)\n        per.write(str)\n        per.close()\n    \n\n    def memory_load(self):\n        \n        with open(\"memory_IARL.pkl\",'rb') as file:\n            self.memory  = pickle.loads(file.read())\n        \n    \n    def load_model(self, output):\n        if output is None: return\n        self.actor.load_state_dict(torch.load('{}/actor.pkl'.format(output)))\n        self.critic.load_state_dict(torch.load('{}/critic.pkl'.format(output)))\n\n    def save_model(self, output):\n        torch.save(self.actor.state_dict(), '{}/actor.pkl'.format(output))\n        torch.save(self.critic.state_dict(), '{}/critic.pkl'.format(output))\n        \n    def save(self, log_dir, epoch):\n        state = {'actor':self.actor.state_dict(), 'actor_target':self.actor_target.state_dict(),\n                 'actor_optimizer':self.actor_optimizer.state_dict(), \n                 'critic':self.critic.state_dict(), 'critic_target':self.critic_target.state_dict(),\n                 'critic_optimizers':self.critic_optimizers.state_dict(),\n                 'epoch':epoch}\n        torch.save(state, log_dir)\n        \n\n    def load(self, log_dir):\n        checkpoint = torch.load(log_dir)\n        self.actor.load_state_dict(checkpoint['actor'])\n        self.actor_target.load_state_dict(checkpoint['actor_target'])\n        self.actor_optimizer.load_state_dict(checkpoint['actor_optimizer'])\n        self.critic.load_state_dict(checkpoint['critic'])\n        self.critic_target.load_state_dict(checkpoint['critic_target'])\n        self.critic_optimizers.load_state_dict(checkpoint['critic_optimizers'])\n        \n        \n        \n        \n        \n        \n        \n", "meta": {"hexsha": "d3b01feaa36c37cf9d815ac17249c1a9664b696f", "size": 8557, "ext": "py", "lang": "Python", "max_stars_repo_path": "TD3_based_DRL/TD3IARL.py", "max_stars_repo_name": "wujingda/Human-in-the-loop-Deep-Reinforcement-Learning-Hug-DRL-", "max_stars_repo_head_hexsha": "d00667017d586fbfc6487bd6ac8dd5396acae0d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T10:05:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T03:06:21.000Z", "max_issues_repo_path": "TD3_based_DRL/TD3IARL.py", "max_issues_repo_name": "wujingda/Human-in-the-loop-Deep-Reinforcement-Learning", "max_issues_repo_head_hexsha": "d00667017d586fbfc6487bd6ac8dd5396acae0d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TD3_based_DRL/TD3IARL.py", "max_forks_repo_name": "wujingda/Human-in-the-loop-Deep-Reinforcement-Learning", "max_forks_repo_head_hexsha": "d00667017d586fbfc6487bd6ac8dd5396acae0d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.545045045, "max_line_length": 133, "alphanum_fraction": 0.6214794905, "include": true, "reason": "import numpy", "num_tokens": 2061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725053, "lm_q2_score": 0.29098086621490676, "lm_q1q2_score": 0.15796282837380382}}
{"text": "#!/usr/bin/env python3\n\n# FIXME:  Port this pipeline to 2.3.\n\n\n# Copyright (c) 2015-2018 by the parties listed in the AUTHORS file.\n# All rights reserved.  Use of this source code is governed by\n# a BSD-style license that can be found in the LICENSE file.\n\nfrom toast.mpi import MPI, finalize\n\nimport os\nimport sys\nimport time\n\nimport re\nimport argparse\nimport traceback\n\nimport pickle\n\nimport numpy as np\n\nimport toast\nimport toast.tod as tt\nimport toast.map as tm\nimport toast.todmap as ttm\n\nimport toast.qarray as qa\nimport toast.timing as timing\n\nfrom toast.vis import set_backend\n\nif tt.tidas_available:\n    from toast.tod import tidas as tds\n\nif tt.spt3g_available:\n    from toast.tod import spt3g as s3g\n\n\ndef elapsed(mcomm, start, msg):\n    mcomm.barrier()\n    stop = MPI.Wtime()\n    dur = stop - start\n    if mcomm.rank == 0:\n        print(\"{}: {:.3f} s\".format(msg, dur), flush=True)\n    return stop\n\n\ndef main():\n\n    if MPI.COMM_WORLD.rank == 0:\n        print(\"Running with {} processes\".format(MPI.COMM_WORLD.size), flush=True)\n\n    global_start = MPI.Wtime()\n\n    parser = argparse.ArgumentParser(\n        description=\"Read existing data and make a simple map.\",\n        fromfile_prefix_chars=\"@\",\n    )\n\n    parser.add_argument(\n        \"--groupsize\",\n        required=False,\n        type=int,\n        default=0,\n        help=\"size of processor groups used to distribute \" \"observations\",\n    )\n\n    parser.add_argument(\n        \"--hwprpm\",\n        required=False,\n        type=float,\n        default=0.0,\n        help=\"The rate (in RPM) of the HWP rotation\",\n    )\n\n    parser.add_argument(\n        \"--samplerate\",\n        required=False,\n        default=100.0,\n        type=np.float,\n        help=\"Detector sample rate (Hz)\",\n    )\n\n    parser.add_argument(\n        \"--outdir\", required=False, default=\"out\", help=\"Output directory\"\n    )\n\n    parser.add_argument(\n        \"--nside\", required=False, type=int, default=64, help=\"Healpix NSIDE\"\n    )\n\n    parser.add_argument(\n        \"--subnside\",\n        required=False,\n        type=int,\n        default=8,\n        help=\"Distributed pixel sub-map NSIDE\",\n    )\n\n    parser.add_argument(\n        \"--coord\", required=False, default=\"E\", help=\"Sky coordinate system [C,E,G]\"\n    )\n\n    parser.add_argument(\n        \"--baseline\",\n        required=False,\n        type=float,\n        default=60.0,\n        help=\"Destriping baseline length (seconds)\",\n    )\n\n    parser.add_argument(\n        \"--noisefilter\",\n        required=False,\n        default=False,\n        action=\"store_true\",\n        help=\"Destripe with the noise filter enabled\",\n    )\n\n    parser.add_argument(\n        \"--madam\",\n        required=False,\n        default=False,\n        action=\"store_true\",\n        help=\"If specified, use libmadam for map-making\",\n    )\n\n    parser.add_argument(\n        \"--madampar\", required=False, default=None, help=\"Madam parameter file\"\n    )\n\n    parser.add_argument(\n        \"--polyorder\",\n        required=False,\n        type=int,\n        help=\"Polynomial order for the polyfilter\",\n    )\n\n    parser.add_argument(\n        \"--wbin_ground\",\n        required=False,\n        type=float,\n        help=\"Ground template bin width [degrees]\",\n    )\n\n    parser.add_argument(\n        \"--flush\",\n        required=False,\n        default=False,\n        action=\"store_true\",\n        help=\"Flush every print statement.\",\n    )\n\n    parser.add_argument(\n        \"--tidas\", required=False, default=None, help=\"Input TIDAS volume\"\n    )\n\n    parser.add_argument(\n        \"--tidas_detgroup\", required=False, default=None, help=\"TIDAS detector group\"\n    )\n\n    parser.add_argument(\n        \"--spt3g\", required=False, default=None, help=\"Input SPT3G data directory\"\n    )\n\n    parser.add_argument(\n        \"--spt3g_prefix\",\n        required=False,\n        default=None,\n        help=\"SPT3G data frame file prefix\",\n    )\n\n    parser.add_argument(\n        \"--common_flag_mask\",\n        required=False,\n        default=0,\n        type=np.uint8,\n        help=\"Common flag mask\",\n    )\n\n    parser.add_argument(\n        \"--debug\",\n        required=False,\n        default=False,\n        action=\"store_true\",\n        help=\"Write data distribution info and focalplane plot\",\n    )\n\n    args = timing.add_arguments_and_parse(parser, timing.FILE(noquotes=True))\n    # args = parser.parse_args(sys.argv)\n\n    autotimer = timing.auto_timer(\"@{}\".format(timing.FILE()))\n\n    if (args.tidas is not None) and (args.spt3g is not None):\n        raise RuntimeError(\"Cannot read two datasets!\")\n\n    if (args.tidas is None) and (args.spt3g is None):\n        raise RuntimeError(\"No dataset specified!\")\n\n    if args.tidas is not None:\n        if not tt.tidas_available:\n            raise RuntimeError(\"TIDAS not found- cannot load\")\n\n    if args.spt3g is not None:\n        if not tt.spt3g_available:\n            raise RuntimeError(\"SPT3G not found- cannot load\")\n\n    groupsize = args.groupsize\n    if groupsize == 0:\n        groupsize = MPI.COMM_WORLD.size\n\n    # Pixelization\n\n    nside = args.nside\n    npix = 12 * args.nside * args.nside\n    subnside = args.subnside\n    if subnside > nside:\n        subnside = nside\n    subnpix = 12 * subnside * subnside\n\n    # This is the 2-level toast communicator.\n\n    if MPI.COMM_WORLD.size % groupsize != 0:\n        if MPI.COMM_WORLD.rank == 0:\n            print(\n                \"WARNING:  process groupsize does not evenly divide into \"\n                \"total number of processes\",\n                flush=True,\n            )\n    comm = toast.Comm(world=MPI.COMM_WORLD, groupsize=groupsize)\n\n    # Create output directory\n\n    mtime = MPI.Wtime()\n\n    if comm.comm_world.rank == 0:\n        if not os.path.isdir(args.outdir):\n            os.makedirs(args.outdir)\n\n    mtime = elapsed(comm.comm_world, mtime, \"Creating output directory\")\n\n    # The distributed timestream data\n\n    data = None\n\n    if args.tidas is not None:\n        if args.tidas_detgroup is None:\n            raise RuntimeError(\"you must specify the detector group\")\n        data = tds.load_tidas(\n            comm,\n            comm.group_size,\n            args.tidas,\n            \"r\",\n            args.tidas_detgroup,\n            tds.TODTidas,\n            group_dets=args.tidas_detgroup,\n            distintervals=\"chunks\",\n        )\n\n    if args.spt3g is not None:\n        if args.spt3g_prefix is None:\n            raise RuntimeError(\"you must specify the frame file prefix\")\n        data = s3g.load_spt3g(\n            comm,\n            comm.group_size,\n            args.spt3g,\n            args.spt3g_prefix,\n            s3g.obsweight_spt3g,\n            s3g.TOD3G,\n        )\n\n    mtime = elapsed(comm.comm_world, mtime, \"Distribute data\")\n\n    # In debug mode, print out data distribution information\n\n    if args.debug:\n        handle = None\n        if comm.comm_world.rank == 0:\n            handle = open(\"{}_distdata.txt\".format(args.outdir), \"w\")\n        data.info(handle)\n        if comm.comm_world.rank == 0:\n            handle.close()\n        mtime = elapsed(comm.comm_world, mtime, \"Dumping debug data distribution\")\n        if comm.comm_world.rank == 0:\n            outfile = \"{}_focalplane.png\".format(args.outdir)\n            set_backend()\n            # Just plot the dets from the first TOD\n            temptod = data.obs[0][\"tod\"]\n            # FIXME: change this once we store det info in the metadata.\n            dfwhm = {x: 10.0 for x in temptod.detectors}\n            tt.plot_focalplane(temptod.detoffset(), 10.0, 10.0, outfile, fwhm=dfwhm)\n        comm.comm_world.barrier()\n        mtime = elapsed(comm.comm_world, mtime, \"Plotting debug focalplane\")\n\n    # Compute pointing matrix\n\n    pointing = tt.OpPointingHpix(\n        nside=args.nside, nest=True, mode=\"IQU\", hwprpm=args.hwprpm\n    )\n    pointing.exec(data)\n\n    mtime = elapsed(comm.comm_world, mtime, \"Expand pointing\")\n\n    # Mapmaking.\n\n    # FIXME:  We potentially have a different noise model for every\n    # observation.  We need to have both spt3g and tidas format Noise\n    # classes which read the information from disk.  Then the mapmaking\n    # operators need to get these noise weights from each observation.\n    detweights = {d: 1.0 for d in data.obs[0][\"tod\"].detectors}\n\n    if not args.madam:\n        if comm.comm_world.rank == 0:\n            print(\"Not using Madam, will only make a binned map!\", flush=True)\n\n        # Filter data if desired\n\n        if args.polyorder:\n            polyfilter = tt.OpPolyFilter(\n                order=args.polyorder, common_flag_mask=args.common_flag_mask\n            )\n            polyfilter.exec(data)\n            mtime = elapsed(comm.comm_world, mtime, \"Polynomial filtering\")\n\n        if args.wbin_ground:\n            groundfilter = tt.OpGroundFilter(\n                wbin=args.wbin_ground, common_flag_mask=args.common_flag_mask\n            )\n            groundfilter.exec(data)\n            mtime = elapsed(comm.comm_world, mtime, \"Ground template filtering\")\n\n        # Compute pixel space distribution\n\n        lc = tm.OpLocalPixels()\n        localpix = lc.exec(data)\n        if localpix is None:\n            raise RuntimeError(\n                \"Process {} has no hit pixels. Perhaps there are fewer \"\n                \"detectors than processes in the group?\".format(comm.comm_world.rank)\n            )\n        localsm = np.unique(np.floor_divide(localpix, subnpix))\n        mtime = elapsed(comm.comm_world, mtime, \"Compute local submaps\")\n\n        # construct distributed maps to store the covariance,\n        # noise weighted map, and hits\n\n        mtime = MPI.Wtime()\n        invnpp = tm.DistPixels(\n            comm=comm.comm_world,\n            size=npix,\n            nnz=6,\n            dtype=np.float64,\n            submap=subnpix,\n            local=localsm,\n        )\n        hits = tm.DistPixels(\n            comm=comm.comm_world,\n            size=npix,\n            nnz=1,\n            dtype=np.int64,\n            submap=subnpix,\n            local=localsm,\n        )\n        zmap = tm.DistPixels(\n            comm=comm.comm_world,\n            size=npix,\n            nnz=3,\n            dtype=np.float64,\n            submap=subnpix,\n            local=localsm,\n        )\n\n        # compute the hits and covariance.\n\n        invnpp.data.fill(0.0)\n        hits.data.fill(0)\n\n        build_invnpp = tm.OpAccumDiag(\n            detweights=detweights,\n            invnpp=invnpp,\n            hits=hits,\n            common_flag_mask=args.common_flag_mask,\n        )\n        build_invnpp.exec(data)\n\n        invnpp.allreduce()\n        hits.allreduce()\n        mtime = elapsed(comm.comm_world, mtime, \"Building hits and N_pp^-1\")\n\n        hits.write_healpix_fits(\"{}_hits.fits\".format(args.outdir))\n        invnpp.write_healpix_fits(\"{}_invnpp.fits\".format(args.outdir))\n        mtime = elapsed(comm.comm_world, mtime, \"Writing hits and N_pp^-1\")\n\n        # invert it\n        tm.covariance_invert(invnpp, 1.0e-3)\n        mtime = elapsed(comm.comm_world, mtime, \"Inverting N_pp^-1\")\n\n        invnpp.write_healpix_fits(\"{}_npp.fits\".format(args.outdir))\n        mtime = elapsed(comm.comm_world, mtime, \"Writing N_pp\")\n\n        zmap.data.fill(0.0)\n        build_zmap = tm.OpAccumDiag(\n            zmap=zmap, detweights=detweights, common_flag_mask=args.common_flag_mask\n        )\n        build_zmap.exec(data)\n        zmap.allreduce()\n        mtime = elapsed(comm.comm_world, mtime, \"Building noise weighted map\")\n\n        tm.covariance_apply(invnpp, zmap)\n        mtime = elapsed(comm.comm_world, mtime, \"Computing binned map\")\n\n        zmap.write_healpix_fits(os.path.join(args.outdir, \"binned.fits\"))\n        mtime = elapsed(comm.comm_world, mtime, \"Writing binned map\")\n\n    else:\n        # Set up MADAM map making.\n\n        pars = {}\n        pars[\"temperature_only\"] = \"F\"\n        pars[\"force_pol\"] = \"T\"\n        pars[\"kfirst\"] = \"T\"\n        pars[\"concatenate_messages\"] = \"T\"\n        pars[\"write_map\"] = \"T\"\n        pars[\"write_binmap\"] = \"T\"\n        pars[\"write_matrix\"] = \"T\"\n        pars[\"write_wcov\"] = \"T\"\n        pars[\"write_hits\"] = \"T\"\n        pars[\"nside_cross\"] = nside // 2\n        pars[\"nside_submap\"] = subnside\n\n        if args.madampar is not None:\n            pat = re.compile(r\"\\s*(\\S+)\\s*=\\s*(\\S+(\\s+\\S+)*)\\s*\")\n            comment = re.compile(r\"^#.*\")\n            with open(args.madampar, \"r\") as f:\n                for line in f:\n                    if comment.match(line) is None:\n                        result = pat.match(line)\n                        if result is not None:\n                            key, value = result.group(1), result.group(2)\n                            pars[key] = value\n\n        pars[\"base_first\"] = args.baseline\n        pars[\"nside_map\"] = nside\n        if args.noisefilter:\n            pars[\"kfilter\"] = \"T\"\n        else:\n            pars[\"kfilter\"] = \"F\"\n        pars[\"fsample\"] = args.samplerate\n\n        madam = tm.OpMadam(\n            params=pars, detweights=detweights, common_flag_mask=args.common_flag_mask\n        )\n        madam.exec(data)\n        mtime = elapsed(comm.comm_world, mtime, \"Madam mapmaking\")\n\n    comm.comm_world.barrier()\n    stop = MPI.Wtime()\n    dur = stop - global_start\n    if comm.comm_world.rank == 0:\n        print(\"Total Time:  {:.2f} seconds\".format(dur), flush=True)\n    return\n\n\nif __name__ == \"__main__\":\n    try:\n        main()\n        tman = timing.timing_manager()\n        tman.report()\n    except:\n        exc_type, exc_value, exc_traceback = sys.exc_info()\n        lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n        lines = [\"Proc {}: {}\".format(MPI.COMM_WORLD.rank, x) for x in lines]\n        print(\"\".join(lines), flush=True)\n        toast.raise_error(6)  # typical error code for SIGABRT\n        MPI.COMM_WORLD.Abort(6)\n    finalize()\n", "meta": {"hexsha": "e912d9c1d715020654aca555eb7d7dcb09f71318", "size": 13733, "ext": "py", "lang": "Python", "max_stars_repo_path": "pipelines/toast_map.py", "max_stars_repo_name": "jrs584/toast", "max_stars_repo_head_hexsha": "c0e2a9296348a22075271236457ad5c23713af82", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2017-03-23T04:51:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T13:17:42.000Z", "max_issues_repo_path": "pipelines/toast_map.py", "max_issues_repo_name": "jrs584/toast", "max_issues_repo_head_hexsha": "c0e2a9296348a22075271236457ad5c23713af82", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 362, "max_issues_repo_issues_event_min_datetime": "2016-05-06T18:26:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T16:39:46.000Z", "max_forks_repo_path": "pipelines/toast_map.py", "max_forks_repo_name": "jrs584/toast", "max_forks_repo_head_hexsha": "c0e2a9296348a22075271236457ad5c23713af82", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 37, "max_forks_repo_forks_event_min_datetime": "2016-05-20T09:31:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T13:56:27.000Z", "avg_line_length": 28.6701461378, "max_line_length": 86, "alphanum_fraction": 0.5879268914, "include": true, "reason": "import numpy", "num_tokens": 3359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.2909808723634538, "lm_q1q2_score": 0.15796282740753645}}
{"text": "#!/usr/bin/env python\n\nimport numpy as np\nimport Pdata\nfrom collections import OrderedDict\nimport gnc\nimport pandas as pa\n\n\n\n\"\"\"\nThis module stores functions only meaningful to ORCHIDEE\n\"\"\"\n\nveget4type=['bareland','forest','grass','crop']\nveget5type=['bareland','forest','grass','pasture','crop']\nforest4type = ['BrEv','BrDe','NeEv','NeDe']\nforest4type_longname = ['BrEv','BrDe','NeEv','NeDe']\n\ndef VEGET_MAX_index_list(typenum=4):\n    \"\"\"\n    Return the np.s_ index to slice the vegetmax related variables\n        into different classes.\n\n    Parameters:\n    -----------\n    typenum:\n        4: recast into bareland,forest,grass,and crop.\n        5: recast into bareland,forest,grass,pasture,and crop.\n        'forest': extract only the fractions for forest into four types:\n            BrEv,BrDe,NeEv,NeDe\n        'Jinfeng17':'bareland','forest','grass','crop','pasture','rangeland'\n    \"\"\"\n    if typenum == 4:\n        index_list = [np.s_[...,0:1,:,:],\n                      np.s_[...,1:9,:,:],\n                      np.s_[...,9:11,:,:],\n                      np.s_[...,11:13,:,:]\n                     ]\n        namelist = ['bareland','forest','grass','crop']\n\n    elif typenum == 'forest':\n        index_list = [np.s_[...,[1,4],:,:],\n                      np.s_[...,[2,5,7],:,:],\n                      np.s_[...,[3,6],:,:],\n                      np.s_[...,[8],:,:]\n                     ]\n        namelist = ['BrEv','BrDe','NeEv','NeDe']\n\n    elif typenum == 5:\n        index_list = [np.s_[...,0:1,:,:],\n                      np.s_[...,1:9,:,:],\n                      np.s_[...,[9,11],:,:],\n                      np.s_[...,[10,12],:,:],\n                      np.s_[...,[13,14],:,:]\n                     ]\n        namelist = ['bareland','forest','grass','pasture','crop']\n\n    elif typenum == 'Jinfeng17':\n        index_list = [np.s_[...,0:1,:,:],\n                      np.s_[...,1:9,:,:],\n                      np.s_[...,[9,10],:,:],\n                      np.s_[...,[11,12],:,:],\n                      np.s_[...,[13,14],:,:],\n                      np.s_[...,[15,16],:,:]\n                     ]\n        namelist = ['bareland','forest','grass','crop','pasture','rangeland']\n\n    else:\n        raise ValueError(\"typenum not correct ! \")\n    return (index_list,namelist)\n\ndef VEGET_MAX_recast(arr,typenum=4,return_dic=False):\n    \"\"\"\n    change the VEGET_MAX variable into another several types.\n\n    Parameters:\n    -----------\n    arr: input VEGET_MAX or veget ndarray.\n    typenum:\n        4: recast into bareland,forest,grass,and agriculture.\n        5: recast into bareland,forest,grass,pasture and crop.\n        forest: extract only the fractions for forest into four types:\n            BrEv,BrDe,NeEv,NeDe\n    return_dic: boolean, True to return a dictionary with the keys as the types.\n    \"\"\"\n    if arr.ndim < 3:\n        raise ValueError(\"input array dimension less than 3!\")\n    else:\n        if arr.shape[-3] not in [13,15,17]:\n            raise ValueError(\"the third last dim is not PFT!\")\n        else:\n            index_list,namelist = VEGET_MAX_index_list(typenum)\n            arrlist = [np.ma.sum(arr[ind],axis=-3)[...,np.newaxis,:,:]\n                        for ind in index_list]\n            if not return_dic:\n                return np.ma.concatenate(arrlist,axis=-3)\n            else:\n                arrlist = [arr[...,0,:,:] for arr in arrlist]\n                return OrderedDict(zip(namelist,arrlist))\n\n\ndef dataframe_from_stomate(filepattern,largefile=True,multifile=True,\n                           dgvmadj=False,spamask=None,\n                           veget_npindex=np.s_[:],areaind=np.s_[:],\n                           out_timestep='annual',version=1,\n                           replace_nan=False):\n    \"\"\"\n    Parameters:\n    -----------\n    filepattern: could be a single filename, or a file pattern\n    out_timestep: the timestep of output file, used to provide information\n        to properly scale the variable values, could be 'annual' or 'daily'.\n        when 'annual', flux_scale_factor = 365 will be used.\n\n    dgvmadj: use DGVM adjustment, in this case tBIOMASS rathern than TOTAL_M\n        is used.\n    veget_npindex: passed to the function of get_pftsum:\n        1. could be used to restrict for example the PFT\n        weighted average only among natural PFTs by setting\n        veget_npindex=np.s_[:,0:11,:,:]. It will be used to slice\n        VEGET_MAX variable.\n        2. could also be used to slice only for some subgrid\n        of the whole grid, eg., veget_npindex=np.s_[...,140:300,140:290].\n\n    Notes:\n    ------\n    1. This function could handle automatically the case of a single-point\n       file or a regional file. When a single-point file (pattern) is given,\n       PFT-weighted carbon density will be used rather than the total C over\n       the spatial area.\n    \"\"\"\n    gnc_sto = gnc.Ncdata(filepattern,largefile=largefile,multifile=multifile,\n                         replace_nan=replace_nan)\n\n    if version == 1:\n        # list all pools and fluxes\n        list_flux_pft = ['GPP','NPP','HET_RESP','CO2_FIRE','CO2FLUX','CO2_TAKEN']\n        list_flux_pftsum = ['CONVFLUX','CFLUX_PROD10','CFLUX_PROD100','HARVEST_ABOVE']\n        list_flux = list_flux_pft+list_flux_pftsum\n\n        list_pool = ['TOTAL_M','TOTAL_SOIL_CARB']\n        list_all = list_flux_pft+list_flux_pftsum+list_pool\n        nlist_var = [list_flux_pft, list_flux_pftsum, list_pool]\n\n        for varlist in nlist_var:\n            gnc_sto.retrieve_variables(varlist)\n            gnc_sto.get_pftsum(print_info=False,veget_npindex=veget_npindex)\n            gnc_sto.remove_variables(varlist)\n\n        #handle adjustment of different variables\n        if dgvmadj:\n            gnc_sto.retrieve_variables(['tGPP','tRESP_GROWTH','tRESP_MAINT','tRESP_HETERO','tCO2_FIRE'])\n            gnc_sto.pftsum.__dict__['NPP'] = gnc_sto.d1.tGPP - gnc_sto.d1.tRESP_MAINT - gnc_sto.d1.tRESP_GROWTH\n            gnc_sto.pftsum.__dict__['HET_RESP'] = gnc_sto.d1.tRESP_HETERO\n            gnc_sto.pftsum.__dict__['CO2_FIRE'] = gnc_sto.d1.tCO2_FIRE\n            gnc_sto.remove_variables(['tGPP','tRESP_GROWTH','tRESP_MAINT','tRESP_HETERO','tCO2_FIRE'])\n\n            gnc_sto.retrieve_variables(['tBIOMASS','tLITTER','tSOILC'])\n            gnc_sto.pftsum.__dict__['TOTAL_M'] = gnc_sto.d1.tBIOMASS\n            gnc_sto.pftsum.__dict__['TOTAL_SOIL_CARB'] = gnc_sto.d1.tLITTER + gnc_sto.d1.tSOILC\n            gnc_sto.remove_variables(['tBIOMASS','tLITTER','tSOILC'])\n\n        # we have to treat product pool independently\n        try:\n            gnc_sto.retrieve_variables(['PROD10','PROD100'])\n            gnc_sto.pftsum.PROD10 = gnc_sto.d1.PROD10.sum(axis=1)\n            gnc_sto.pftsum.PROD100 = gnc_sto.d1.PROD100.sum(axis=1)\n            gnc_sto.remove_variables(['PROD10','PROD100'])\n        except KeyError:\n            gnc_sto.pftsum.PROD10 = gnc_sto.pftsum.NPP * 0.\n            gnc_sto.pftsum.PROD100 = gnc_sto.pftsum.NPP * 0.\n\n        # get the spatial operation and pass them into dataframe\n        if not gnc_sto._SinglePoint:\n            gnc_sto.get_spa()\n            dft = pa.DataFrame(gnc_sto.spasum.__dict__)\n        else:\n            dft = pa.DataFrame(gnc_sto.pftsum.__dict__)\n\n        # treat the output time step\n        if out_timestep == 'annual':\n            flux_scale_factor = 365.\n            dft['CO2FLUX'] = dft['CO2FLUX']/30.  #CO2FLUX is monthly output\n        elif out_timestep == 'daily':\n            flux_scale_factor = 1\n        dft[list_flux] = dft[list_flux]*flux_scale_factor\n\n        # get total carbon pool\n        dft['PROD'] = dft['PROD10'] + dft['PROD100']\n        dft['CarbonPool'] = dft['TOTAL_M'] + dft['TOTAL_SOIL_CARB'] + dft['PROD']\n\n        # calcate NBP\n        dft['NBP_npp'] = dft['NPP']+dft['CO2_TAKEN']-dft['CONVFLUX']-dft['CFLUX_PROD10']-dft['CFLUX_PROD100']-dft['CO2_FIRE']-dft['HARVEST_ABOVE']-dft['HET_RESP']\n        dft['NBP_co2flux'] = -1*(dft['CO2FLUX']+dft['HARVEST_ABOVE']+dft['CONVFLUX']+dft['CFLUX_PROD10']+dft['CFLUX_PROD100'])\n\n    elif version == 2:\n        # list all pools and fluxes\n        list_flux_pft = ['GPP','NPP','HET_RESP','CO2_FIRE','CO2FLUX','CO2_TAKEN','METHANE','RANIMAL']\n        list_flux_pftsum = ['CONVFLUX_LCC','CONVFLUX_HAR','CFLUX_PROD10_LCC','CFLUX_PROD10_HAR','CFLUX_PROD100_LCC','CFLUX_PROD100_HAR','HARVEST_ABOVE']\n        list_flux = list_flux_pft+list_flux_pftsum\n\n        list_pool = ['TOTAL_M','TOTAL_SOIL_CARB','LEAF_M','SAP_M_AB','SAP_M_BE',\n                     'HEART_M_AB','HEART_M_BE','ROOT_M','FRUIT_M','RESERVE_M',\n                     'LITTER_STR_AB','LITTER_STR_BE','LITTER_MET_AB','LITTER_MET_BE']\n        list_all = list_flux_pft+list_flux_pftsum+list_pool\n        nlist_var = [list_flux_pft, list_flux_pftsum, list_pool]\n\n        for varlist in nlist_var:\n            gnc_sto.retrieve_variables(varlist,mask=spamask)\n            gnc_sto.get_pftsum(print_info=False,veget_npindex=veget_npindex)\n            gnc_sto.remove_variables(varlist)\n\n        #handle adjustment of different variables\n        if dgvmadj:\n            if veget_npindex != np.s_[:]:\n                raise ValueError(\"dgvmadj is not handled when veget_npindex does not include all\")\n            else:\n                gnc_sto.retrieve_variables(['tGPP','tRESP_GROWTH','tRESP_MAINT','tRESP_HETERO','tCO2_FIRE'],mask=spamask)\n                gnc_sto.pftsum.__dict__['NPP'] = gnc_sto.d1.tGPP - gnc_sto.d1.tRESP_MAINT - gnc_sto.d1.tRESP_GROWTH\n                gnc_sto.pftsum.__dict__['HET_RESP'] = gnc_sto.d1.tRESP_HETERO\n                gnc_sto.pftsum.__dict__['CO2_FIRE'] = gnc_sto.d1.tCO2_FIRE\n                gnc_sto.remove_variables(['tGPP','tRESP_GROWTH','tRESP_MAINT','tRESP_HETERO','tCO2_FIRE'])\n\n                gnc_sto.retrieve_variables(['tBIOMASS','tLITTER','tSOILC'],mask=spamask)\n                gnc_sto.pftsum.__dict__['TOTAL_M'] = gnc_sto.d1.tBIOMASS\n                gnc_sto.pftsum.__dict__['TOTAL_SOIL_CARB'] = gnc_sto.d1.tLITTER + gnc_sto.d1.tSOILC\n                gnc_sto.remove_variables(['tBIOMASS','tLITTER','tSOILC'])\n\n        # we have to treat product pool independently\n        list_prod = ['PROD10_LCC','PROD10_HAR','PROD100_LCC','PROD100_HAR']\n        gnc_sto.retrieve_variables(list_prod,mask=spamask)\n        for var in list_prod:\n            gnc_sto.pftsum.__dict__[var] = gnc_sto.d1.__dict__[var][veget_npindex].sum(axis=1)\n        print gnc_sto.d1.__dict__['PROD10_LCC'][veget_npindex].shape\n        print gnc_sto.d1.__dict__['PROD10_LCC'].shape\n        print gnc_sto.pftsum.__dict__['PROD10_LCC'].shape\n        gnc_sto.remove_variables(list_prod)\n\n        # get the spatial operation and pass them into dataframe\n        if not gnc_sto._SinglePoint:\n            gnc_sto.get_spa(areaind=areaind)\n            dft = pa.DataFrame(gnc_sto.spasum.__dict__)\n        else:\n            dft = pa.DataFrame(gnc_sto.pftsum.__dict__)\n\n        #  2016-03-30: the shape of gnc_sto.d1.ContAreas could be\n        #  (nlat,nlon) when there is no \"CONTFRAC\" or \"NONBIOFRAC\" in\n        #  the history file, but could be (ntime,nlat,nlon) when they're\n        #  present.\n\n        #  # [++temporary++] treat CO2_TAKEN\n        #  # In case of shifting cultivation is simulated, the CO2_TAKEN\n        #  # could be big at the last day. However the veget_max is kept\n        #  # the same as the old one over the year, so we have to use\n        #  # last-year CO2_TAKEN multiply with the next-year veget_max.\n        #  gnc_sto.retrieve_variables(['CO2_TAKEN'])\n        #  co2taken_pftsum = np.ma.sum(gnc_sto.d1.CO2_TAKEN[:-1] * gnc_sto.d1.VEGET_MAX[1:],axis=1)\n        #  if not gnc_sto._SinglePoint:\n        #      dt = np.sum(co2taken_pftsum*gnc_sto.d1.ContAreas,axis=(1,2))\n        #  else:\n        #      dt = co2taken_pftsum\n        #  dft['CO2_TAKEN'].iloc[:-1] = dt\n\n        # treat the output time step\n        if out_timestep == 'annual':\n            flux_scale_factor = 365.\n            dft['CO2FLUX'] = dft['CO2FLUX']/30.  #CO2FLUX is monthly output\n        elif out_timestep == 'daily':\n            flux_scale_factor = 1\n        dft[list_flux] = dft[list_flux]*flux_scale_factor\n\n        # get total carbon pool\n        dft['PROD'] = dft['PROD10_LCC'] + dft['PROD10_HAR'] + dft['PROD100_LCC'] + dft['PROD100_HAR']\n        dft['CarbonPool'] = dft['TOTAL_M'] + dft['TOTAL_SOIL_CARB'] + dft['PROD']\n        dft['LITTER_AB'] = dft['LITTER_STR_AB'] + dft['LITTER_MET_AB']\n        dft['LITTER_BE'] = dft['LITTER_MET_BE'] + dft['LITTER_STR_BE']\n        dft['LITTER'] = dft['LITTER_BE'] + dft['LITTER_AB']\n        dft['BIOMASS_AB'] = dft.SAP_M_AB + dft.HEART_M_AB + dft.LEAF_M + dft.FRUIT_M + dft.RESERVE_M\n        dft['BIOMASS_BE'] = dft.SAP_M_BE + dft.HEART_M_BE + dft.ROOT_M\n\n\n        # treat GM\n        dft['RANIMAL'] = dft['RANIMAL']*1000\n        dft['METHANE'] = dft['METHANE']*1000\n        dft['GMsource'] = dft['RANIMAL'] + dft['METHANE']\n\n        # treat LUC\n        dft['CONVFLUX'] = dft['CONVFLUX_LCC'] + dft['CONVFLUX_HAR']\n        dft['CFLUX_PROD10'] = dft['CFLUX_PROD10_LCC'] + dft['CFLUX_PROD10_HAR']\n        dft['CFLUX_PROD100'] = dft['CFLUX_PROD100_LCC'] + dft['CFLUX_PROD100_HAR']\n        dft['LUCsource'] = dft['CONVFLUX'] + dft['CFLUX_PROD10'] + dft['CFLUX_PROD100']\n\n        # calcate NBP\n        dft['NBP_npp'] = dft['NPP']+dft['CO2_TAKEN']-dft['CONVFLUX']-dft['CFLUX_PROD10']-dft['CFLUX_PROD100']-dft['CO2_FIRE'] \\\n                         -dft['HARVEST_ABOVE']-dft['HET_RESP']-dft['RANIMAL']-dft['METHANE']\n        dft['NBP_co2flux'] = -1*(dft['CO2FLUX']+dft['HARVEST_ABOVE']+dft['CONVFLUX']+dft['CFLUX_PROD10']+dft['CFLUX_PROD100'])\n\n        # litter\n        dft['LITTER'] = dft[['LITTER_STR_AB','LITTER_STR_BE','LITTER_MET_AB','LITTER_MET_BE']].sum(axis=1)\n        dft['LITTER_AB'] = dft[['LITTER_STR_AB','LITTER_MET_AB']].sum(axis=1)\n        dft['LITTER_BE'] = dft[['LITTER_STR_BE','LITTER_MET_BE']].sum(axis=1)\n        dft['SOILC'] = dft['TOTAL_SOIL_CARB'] - dft['LITTER']\n\n    else:\n        raise ValueError(\"Unknown version!\")\n\n    gnc_sto.close()\n\n    return dft\n\ndef panel_summary_stomate(dic):\n    \"\"\"\n    Return a panel of summary dataframe for stomate_history.nc using\n    dataframe_from_stomate\n\n    Parameters:\n    -----------\n    dic: a dictionary of (tag,filename) pairs.\n    \"\"\"\n    pdic = OrderedDict()\n    for k,f in dic.items():\n        pdic[k] = dataframe_from_stomate(f)\n    return pa.Panel(pdic)\n\ndef write_PFTmap(filename,data,resolution='05deg'):\n    if resolution=='05deg':\n        ### Build the dimensions\n        ncfile = gnc.NcWrite(filename)\n        ncfile.add_dim_lat(bounds = \"bounds_lat\",latvar=np.arange(89.75,-90,-0.5),units = \"degrees_north\",valid_min = -90.,valid_max = 90.,long_name = \"Latitude\",axis = \"Y\")\n        ncfile.add_dim_lon(bounds = \"bounds_lon\",lonvar=np.arange(-179.75,180,0.5),units = \"degrees_east\",valid_min = -180.,valid_max = 180.,long_name = \"Longitude\",axis = \"X\")\n        timedim_info = ['time_counter','time_counter','time_counter','f4',np.array([1850]),'no unit',True]\n        ncfile.add_dim(timedim_info,units = \"years since 0-1-1\",Calendar = \"gregorian\",axis = \"T\")\n        vegetdim_info = ['veget','veget','Vegetation Classes','i4',np.arange(1,16),\"-\",False]\n        ncfile.add_dim(vegetdim_info,validmax = 15.,validmin = 1.)\n        import cons\n        from collections import OrderedDict\n        pftdic = OrderedDict()\n        for i in range(1,16):\n            pftdic['PFT{0:0>2}'.format(i)] = cons.pftdic15[i]\n            ### Write the vegetmax\n        varinfo_value = ['maxvegetfrac',('time_counter', 'veget', 'lat', 'lon',),'f4',data]\n        ncfile.add_var(varinfo_value,name = \"maxvegetfrac\",long_name = \"Vegetation types\",units = \"-\")\n        ncfile.add_global_attributes(pftdic)\n        ncfile.add_history_attr(histtxt=\"PFT map generated using data from FireMIP\")\n        ncfile.close()\n\n\n", "meta": {"hexsha": "0fcd51040c0074be7a77ea76ef51d5db57bec016", "size": 15765, "ext": "py", "lang": "Python", "max_stars_repo_path": "orch.py", "max_stars_repo_name": "ChaoYue/pylsce", "max_stars_repo_head_hexsha": "35c444e5bd49512a52b910f16eaa821672ffa25b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-01-26T20:25:25.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-05T11:07:14.000Z", "max_issues_repo_path": "orch.py", "max_issues_repo_name": "ChaoYue/pylsce", "max_issues_repo_head_hexsha": "35c444e5bd49512a52b910f16eaa821672ffa25b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-01-26T21:06:08.000Z", "max_issues_repo_issues_event_max_datetime": "2015-01-26T21:09:57.000Z", "max_forks_repo_path": "orch.py", "max_forks_repo_name": "ChaoYue/pylsce", "max_forks_repo_head_hexsha": "35c444e5bd49512a52b910f16eaa821672ffa25b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.1719197708, "max_line_length": 176, "alphanum_fraction": 0.6051379638, "include": true, "reason": "import numpy", "num_tokens": 4784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.290980853917813, "lm_q1q2_score": 0.1579628216981631}}
{"text": "# Copyright 2019-2022 Cambridge Quantum Computing\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport json\nfrom typing import cast, Iterable, List, Optional, Sequence, Union, Any\nfrom uuid import uuid4\nfrom logging import warning\n\nimport numpy as np\nfrom pyquil.api import (\n    QuantumComputer,\n    WavefunctionSimulator,\n    list_quantum_computers,\n    get_qc,\n)\nfrom pyquil.gates import I\nfrom pyquil.paulis import ID, PauliSum, PauliTerm\nfrom pyquil.quilatom import Qubit as Qubit_\n\nfrom pytket.circuit import Circuit, OpType, Qubit  # type: ignore\nfrom pytket.backends import (\n    Backend,\n    CircuitNotRunError,\n    CircuitStatus,\n    ResultHandle,\n    StatusEnum,\n)\nfrom pytket.backends.backend import KwargTypes\nfrom pytket.backends.backendinfo import BackendInfo\nfrom pytket.backends.backendresult import BackendResult\nfrom pytket.backends.resulthandle import _ResultIdTuple\nfrom pytket.extensions.pyquil._metadata import __extension_version__\nfrom pytket.passes import (  # type: ignore\n    BasePass,\n    EulerAngleReduction,\n    CXMappingPass,\n    auto_rebase_pass,\n    SequencePass,\n    SynthesiseTket,\n    DecomposeBoxes,\n    FullPeepholeOptimise,\n    CliffordSimp,\n    FlattenRegisters,\n    SimplifyInitial,\n    NaivePlacementPass,\n)\nfrom pytket.pauli import QubitPauliString  # type: ignore\nfrom pytket.predicates import (  # type: ignore\n    NoSymbolsPredicate,\n    ConnectivityPredicate,\n    GateSetPredicate,\n    NoClassicalControlPredicate,\n    NoFastFeedforwardPredicate,\n    NoMidMeasurePredicate,\n    DefaultRegisterPredicate,\n    Predicate,\n)\nfrom pytket.extensions.pyquil.pyquil_convert import (\n    process_characterisation,\n    get_avg_characterisation,\n    tk_to_pyquil,\n)\nfrom pytket.placement import NoiseAwarePlacement  # type: ignore\nfrom pytket.architecture import Architecture  # type: ignore\nfrom pytket.utils import prepare_circuit\nfrom pytket.utils.operators import QubitPauliOperator\nfrom pytket.utils.outcomearray import OutcomeArray\n\n\nclass PyQuilJobStatusUnavailable(Exception):\n    \"\"\"Raised when trying to retrieve unknown job status.\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__(\"The job status cannot be retrieved.\")\n\n\n_STATUS_MAP = {\n    \"done\": StatusEnum.COMPLETED,\n    \"running\": StatusEnum.RUNNING,\n    \"loaded\": StatusEnum.SUBMITTED,\n    \"connected\": StatusEnum.SUBMITTED,\n}\n\n\ndef _default_q_index(q: Qubit) -> int:\n    if q.reg_name != \"q\" or len(q.index) != 1:\n        raise ValueError(\"Non-default qubit register\")\n    return int(q.index[0])\n\n\nclass ForestBackend(Backend):\n    _supports_shots = True\n    _supports_counts = True\n    _supports_contextual_optimisation = True\n    _persistent_handles = True\n    _GATE_SET = {OpType.CZ, OpType.Rx, OpType.Rz, OpType.Measure, OpType.Barrier}\n\n    def __init__(self, qc: QuantumComputer):\n        \"\"\"Backend for running circuits with the Rigetti QVM.\n\n        :param qc: The particular QuantumComputer to use. See the pyQuil docs for more\n        details.\n        :type qc: QuantumComputer\n        \"\"\"\n        super().__init__()\n        self._qc: QuantumComputer = qc\n        self._backend_info = self._get_backend_info(self._qc)\n\n    @property\n    def required_predicates(self) -> List[Predicate]:\n        return [\n            NoClassicalControlPredicate(),\n            NoFastFeedforwardPredicate(),\n            NoMidMeasurePredicate(),\n            GateSetPredicate(self.backend_info.gate_set),\n            ConnectivityPredicate(self.backend_info.architecture),\n        ]\n\n    def rebase_pass(self) -> BasePass:\n        return auto_rebase_pass({OpType.CZ, OpType.Rz, OpType.Rx})\n\n    def default_compilation_pass(self, optimisation_level: int = 1) -> BasePass:\n        assert optimisation_level in range(3)\n        passlist = [\n            DecomposeBoxes(),\n            FlattenRegisters(),\n        ]\n        if optimisation_level == 1:\n            passlist.append(SynthesiseTket())\n        elif optimisation_level == 2:\n            passlist.append(FullPeepholeOptimise())\n        passlist.append(\n            CXMappingPass(\n                self.backend_info.architecture,\n                NoiseAwarePlacement(\n                    self._backend_info.architecture,\n                    self._backend_info.averaged_node_gate_errors,\n                    self._backend_info.averaged_edge_gate_errors,\n                ),\n                directed_cx=False,\n                delay_measures=True,\n            )\n        )\n        passlist.append(NaivePlacementPass(self.backend_info.architecture))\n        if optimisation_level == 2:\n            passlist.append(CliffordSimp(False))\n        if optimisation_level > 0:\n            passlist.append(SynthesiseTket())\n        passlist.append(self.rebase_pass())\n        if optimisation_level > 0:\n            passlist.extend(\n                [\n                    EulerAngleReduction(OpType.Rx, OpType.Rz),\n                    SimplifyInitial(\n                        allow_classical=False, create_all_qubits=True, xcirc=_xcirc\n                    ),\n                ]\n            )\n        return SequencePass(passlist)\n\n    @property\n    def _result_id_type(self) -> _ResultIdTuple:\n        return (int, str)\n\n    def process_circuits(\n        self,\n        circuits: Sequence[Circuit],\n        n_shots: Union[None, int, Sequence[Optional[int]]] = None,\n        valid_check: bool = True,\n        **kwargs: KwargTypes,\n    ) -> List[ResultHandle]:\n        \"\"\"\n        See :py:meth:`pytket.backends.Backend.process_circuits`.\n        Supported kwargs: `seed`.\n        \"\"\"\n        circuits = list(circuits)\n        n_shots_list = Backend._get_n_shots_as_list(\n            n_shots, len(circuits), optional=False\n        )\n\n        if valid_check:\n            self._check_all_circuits(circuits)\n\n        postprocess = kwargs.get(\"postprocess\", False)\n\n        handle_list = []\n        for circuit, n_shots in zip(circuits, n_shots_list):\n            if postprocess:\n                c0, ppcirc = prepare_circuit(circuit, allow_classical=False)\n                ppcirc_rep = ppcirc.to_dict()\n            else:\n                c0, ppcirc_rep = circuit, None\n            p, bits = tk_to_pyquil(c0, return_used_bits=True)\n            p.wrap_in_numshots_loop(n_shots)\n            ex = self._qc.compiler.native_quil_to_executable(p)\n            qam = self._qc.qam\n            qam.random_seed = kwargs.get(\"seed\")  # type: ignore\n            pyquil_handle = qam.execute(ex)\n            handle = ResultHandle(uuid4().int, json.dumps(ppcirc_rep))\n            measures = circuit.n_gates_of_type(OpType.Measure)\n            if measures == 0:\n                self._cache[handle] = {\n                    \"handle\": pyquil_handle,\n                    \"c_bits\": sorted(bits),\n                    \"result\": self.empty_result(circuit, n_shots=n_shots),\n                }\n            else:\n                self._cache[handle] = {\"handle\": pyquil_handle, \"c_bits\": sorted(bits)}\n            handle_list.append(handle)\n        return handle_list\n\n    def circuit_status(self, handle: ResultHandle) -> CircuitStatus:\n        \"\"\"\n        Return a CircuitStatus reporting the status of the circuit execution\n        corresponding to the ResultHandle.\n\n        This will throw an PyQuilJobStatusUnavailable exception if the results\n        have not been retrieved yet, as pyQuil does not currently support asynchronous\n        job status queries.\n\n        :param handle: The handle to the submitted job.\n        :type handle: ResultHandle\n        :returns: The status of the submitted job.\n        :raises PyQuilJobStatusUnavailable: Cannot retrieve job status.\n        :raises CircuitNotRunError: The handle does not correspond to a valid job.\n        \"\"\"\n        if handle in self._cache and \"result\" in self._cache[handle]:\n            return CircuitStatus(StatusEnum.COMPLETED)\n        if handle in self._cache:\n            # retrieving status is not supported yet\n            # see https://github.com/rigetti/pyquil/issues/1370\n            raise PyQuilJobStatusUnavailable()\n        raise CircuitNotRunError(handle)\n\n    def get_result(self, handle: ResultHandle, **kwargs: KwargTypes) -> BackendResult:\n        \"\"\"\n        See :py:meth:`pytket.backends.Backend.get_result`.\n        Supported kwargs: none.\n        \"\"\"\n        try:\n            return super().get_result(handle)\n        except CircuitNotRunError:\n            if handle not in self._cache:\n                raise CircuitNotRunError(handle)\n\n            pyquil_handle = self._cache[handle][\"handle\"]\n            raw_shots = self._qc.qam.get_result(pyquil_handle).readout_data[\"ro\"]\n            if raw_shots is None:\n                raise ValueError(\"Could not read job results in memory\")\n            shots = OutcomeArray.from_readouts(raw_shots.tolist())\n            ppcirc_rep = json.loads(cast(str, handle[1]))\n            ppcirc = Circuit.from_dict(ppcirc_rep) if ppcirc_rep is not None else None\n            res = BackendResult(\n                shots=shots, c_bits=self._cache[handle][\"c_bits\"], ppcirc=ppcirc\n            )\n            self._cache[handle].update({\"result\": res})\n            return res\n\n    @property\n    def backend_info(self) -> BackendInfo:\n        return self._backend_info\n\n    @classmethod\n    def _get_backend_info(cls, qc: QuantumComputer) -> BackendInfo:\n        char_dict: dict = process_characterisation(qc)\n        arch = char_dict.get(\"Architecture\", Architecture([]))\n        node_errors = char_dict.get(\"NodeErrors\")\n        link_errors = char_dict.get(\"EdgeErrors\")\n        averaged_errors = get_avg_characterisation(char_dict)\n        return BackendInfo(\n            cls.__name__,\n            qc.name,\n            __extension_version__,\n            arch,\n            cls._GATE_SET,\n            all_node_gate_errors=node_errors,\n            all_edge_gate_errors=link_errors,\n            averaged_node_gate_errors=averaged_errors[\"node_errors\"],\n            averaged_edge_gate_errors=averaged_errors[\"link_errors\"],\n        )\n\n    @classmethod\n    def available_devices(cls, **kwargs: Any) -> List[BackendInfo]:\n        \"\"\"\n        See :py:meth:`pytket.backends.Backend.available_devices`.\n        Supported kwargs: `qpus` (default true), `qvms` (default false).\n        \"\"\"\n        if \"qvms\" not in kwargs:\n            kwargs[\"qvms\"] = False\n        qc_name_list = list_quantum_computers(**kwargs)\n        return [cls._get_backend_info(get_qc(name)) for name in qc_name_list]\n\n\nclass ForestStateBackend(Backend):\n    _supports_state = True\n    _supports_expectation = True\n    _expectation_allows_nonhermitian = False\n    _persistent_handles = False\n    _GATE_SET = {\n        OpType.X,\n        OpType.Y,\n        OpType.Z,\n        OpType.H,\n        OpType.S,\n        OpType.T,\n        OpType.Rx,\n        OpType.Ry,\n        OpType.Rz,\n        OpType.CZ,\n        OpType.CX,\n        OpType.CCX,\n        OpType.CU1,\n        OpType.U1,\n        OpType.SWAP,\n    }\n\n    def __init__(self) -> None:\n        \"\"\"Backend for running simulations on the Rigetti QVM Wavefunction Simulator.\"\"\"\n        super().__init__()\n        self._sim = WavefunctionSimulator()\n\n    @property\n    def required_predicates(self) -> List[Predicate]:\n        return [\n            NoClassicalControlPredicate(),\n            NoFastFeedforwardPredicate(),\n            NoMidMeasurePredicate(),\n            NoSymbolsPredicate(),\n            GateSetPredicate(self._GATE_SET),\n            DefaultRegisterPredicate(),\n        ]\n\n    def rebase_pass(self) -> BasePass:\n        return auto_rebase_pass({OpType.CZ, OpType.Rz, OpType.Rx})\n\n    def default_compilation_pass(self, optimisation_level: int = 1) -> BasePass:\n        assert optimisation_level in range(3)\n        passlist = [DecomposeBoxes(), FlattenRegisters()]\n        if optimisation_level == 1:\n            passlist.append(SynthesiseTket())\n        elif optimisation_level == 2:\n            passlist.append(FullPeepholeOptimise())\n        passlist.append(self.rebase_pass())\n        if optimisation_level > 0:\n            passlist.append(EulerAngleReduction(OpType.Rx, OpType.Rz))\n        return SequencePass(passlist)\n\n    @property\n    def _result_id_type(self) -> _ResultIdTuple:\n        return (int,)\n\n    def process_circuits(\n        self,\n        circuits: Iterable[Circuit],\n        n_shots: Optional[Union[int, Sequence[int]]] = None,\n        valid_check: bool = True,\n        **kwargs: KwargTypes,\n    ) -> List[ResultHandle]:\n        handle_list = []\n        if valid_check:\n            self._check_all_circuits(circuits)\n        for circuit in circuits:\n            p = tk_to_pyquil(circuit)\n            for qb in circuit.qubits:\n                # Qubits with no gates will not be included in the Program\n                # Add identities to ensure all qubits are present and dimension\n                # is as expected\n                p += I(Qubit_(qb.index[0]))\n            handle = ResultHandle(uuid4().int)\n            state = np.array(self._sim.wavefunction(p).amplitudes)\n            try:\n                phase = float(circuit.phase)\n                coeff = np.exp(phase * np.pi * 1j)\n                state *= coeff\n            except ValueError:\n                warning(\n                    \"Global phase is dependent on a symbolic parameter, so cannot \"\n                    \"adjust for phase\"\n                )\n            implicit_perm = circuit.implicit_qubit_permutation()\n            res_qubits = [\n                implicit_perm[qb] for qb in sorted(circuit.qubits, reverse=True)\n            ]\n            res = BackendResult(q_bits=res_qubits, state=state)\n            self._cache[handle] = {\"result\": res}\n            handle_list.append(handle)\n        return handle_list\n\n    def circuit_status(self, handle: ResultHandle) -> CircuitStatus:\n        if handle in self._cache:\n            return CircuitStatus(StatusEnum.COMPLETED)\n        raise CircuitNotRunError(handle)\n\n    def _gen_PauliTerm(self, term: QubitPauliString, coeff: complex = 1.0) -> PauliTerm:\n        pauli_term = ID() * coeff\n        for q, p in term.map.items():\n            pauli_term *= PauliTerm(p.name, _default_q_index(q))\n        return pauli_term  # type: ignore\n\n    def get_pauli_expectation_value(\n        self, state_circuit: Circuit, pauli: QubitPauliString\n    ) -> complex:\n        \"\"\"Calculates the expectation value of the given circuit using the built-in QVM\n        functionality\n\n        :param state_circuit: Circuit that generates the desired state\n            :math:`\\\\left|\\\\psi\\\\right>`.\n        :type state_circuit: Circuit\n        :param pauli: Pauli operator\n        :type pauli: QubitPauliString\n        :return: :math:`\\\\left<\\\\psi | P | \\\\psi \\\\right>`\n        :rtype: complex\n        \"\"\"\n        prog = tk_to_pyquil(state_circuit)\n        pauli_term = self._gen_PauliTerm(pauli)\n        return complex(self._sim.expectation(prog, [pauli_term]))\n\n    def get_operator_expectation_value(\n        self, state_circuit: Circuit, operator: QubitPauliOperator\n    ) -> complex:\n        \"\"\"Calculates the expectation value of the given circuit with respect to the\n        operator using the built-in QVM functionality\n\n        :param state_circuit: Circuit that generates the desired state\n            :math:`\\\\left|\\\\psi\\\\right>`.\n        :type state_circuit: Circuit\n        :param operator: Operator :math:`H`.\n        :type operator: QubitPauliOperator\n        :return: :math:`\\\\left<\\\\psi | H | \\\\psi \\\\right>`\n        :rtype: complex\n        \"\"\"\n        prog = tk_to_pyquil(state_circuit)\n        pauli_sum = PauliSum(\n            [self._gen_PauliTerm(term, coeff) for term, coeff in operator._dict.items()]\n        )\n        return complex(self._sim.expectation(prog, pauli_sum))\n\n\n_xcirc = Circuit(1).Rx(1, 0)\n_xcirc.add_phase(0.5)\n", "meta": {"hexsha": "350187f1ce8f296a5f7fe139773559c6f4d561f9", "size": 16207, "ext": "py", "lang": "Python", "max_stars_repo_path": "modules/pytket-pyquil/pytket/extensions/pyquil/backends/forest.py", "max_stars_repo_name": "dhaycraft/pytket-extensions", "max_stars_repo_head_hexsha": "6fbfedaf3dc03d6f4a4fb7a45b20a9d7a4f11b91", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/pytket-pyquil/pytket/extensions/pyquil/backends/forest.py", "max_issues_repo_name": "dhaycraft/pytket-extensions", "max_issues_repo_head_hexsha": "6fbfedaf3dc03d6f4a4fb7a45b20a9d7a4f11b91", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/pytket-pyquil/pytket/extensions/pyquil/backends/forest.py", "max_forks_repo_name": "dhaycraft/pytket-extensions", "max_forks_repo_head_hexsha": "6fbfedaf3dc03d6f4a4fb7a45b20a9d7a4f11b91", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8561946903, "max_line_length": 88, "alphanum_fraction": 0.6342938237, "include": true, "reason": "import numpy", "num_tokens": 3742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3040416623541848, "lm_q1q2_score": 0.15795612635475795}}
{"text": "# Copyright 2016 Espen Flage-Larsen\n#\n#    This file is part of T4ME.\n#\n#    T4ME is free software: you can redistribute it and/or modify\n#    it under the terms of the GNU General Public License as published by\n#    the Free Software Foundation, either version 3 of the License, or\n#    (at your option) any later version.\n#\n#    T4ME is distributed in the hope that it will be useful,\n#    but WITHOUT ANY WARRANTY; without even the implied warranty of\n#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n#    GNU General Public License for more details.\n#\n#    You should have received a copy of the GNU General Public License\n#    along with T4ME.  If not, see <http://www.gnu.org/licenses/>.\n\n#!/usr/bin/python\n\"\"\"Contains routines to set up the scattering of the charge carriers.\"\"\"\n\n# pylint: disable=useless-import-alias, too-many-arguments, invalid-name,\n# pylint: disable=too-many-statements, too-many-lines, global-statement, too-many-nested-blocks, no-name-in-module\n\nimport sys\nimport logging\nimport numpy as np\nimport scipy\n\nimport t4me.constants as constants\nfrom t4me.bandstructure import parabolic_effective_mass\n\n\ndef scattering_dos(tr, dos, energies, select_scattering):  # pylint: disable=too-many-locals, too-many-branches # noqa: MC0001\n    \"\"\"\n    Setup scattering mechnisms.\n\n    Store values in the scattering arrays using the density of states data\n    as the energy dependency.\n\n    Parameters\n    ----------\n    tr : object\n        A `Transport()` object\n    dos : ndarray\n        | Dimension: (N,M)\n\n        Array containing the partial density of states\n        (1/eV/AA^3), where N is the band index\n        and M is the energy index.\n    energies : ndarray\n        | Dimension: (M)\n\n        Array containing the energy in eV at M samplings\n        where the density of states is calculated.\n    select_scattering : ndarray\n        | Dimension: (12)\n\n        Array containing integers. Set to 1 to select\n        the scattering, 0 to exclude.\n        The variables in `select_scattering` are set in\n        the bandstructure configuration file, one value\n        for each scattering and band. See notes below\n        for the currrently available scattering mechnisms.\n\n    Returns\n    -------\n    scattering_inv : ndarray\n        | Dimension: (T,N,M,12)\n\n        The scattering array in fs units\n        in the current `Transport()` object for T temperature steps,\n        N number of bands, M number of energy steps and 12 number of\n        scattering mechanisms\n    scattering_total_inv : ndarray\n        | Dimension: (T, N, M)\n\n        The total (all mechanisms summed) scattering array\n        in fs units) in the current `Transport()` object for T\n        temperature steps, N number of bands and M number of\n        energy steps\n    scattering_tau0 : ndarray\n        | Dimension: (T, N, 12)\n\n        The scattering prefactor array, tau0 in units of fs,\n        in the current `Transport()` object for T temperature\n        steps, N number of bands and 12 number of\n        scattering mechanisms.\n\n    Notes\n    -----\n    Currently only the following scattering mechanisms are supported:\n\n    ========================= ====================\n    `select_scattering` index scattering mechanism\n    ========================= ====================\n    1                         Acoustic phonon scattering from def. pot.\n    2                         Non-polar optical phonon scattering from def. pot. (alpha stage)\n    3                         Intervalley phonon scattering (alpha stage)\n    4                         Polar optical phonon scattering (alpha stage)\n    5                         None\n    6                         None\n    7                         None\n    8                         None\n    9                         None\n    10                        None\n    11                        None\n    12                        Constant (energy and k-point independent)\n    ========================= ====================\n\n    Only the acoustic phonon scattering has been tested.\n\n    Consult the bandstructure\n    configuration file for the respective constants that have to\n    be set besides `select_scattering` and their units.\n\n    .. todo:: Add more extensive documentation for the different scattering\n              mechanisms.\n\n    .. warning:: The scattering models based on density of states\n                 does currently not properly involve the energy\n                 shift required for the transfer energies.\n                 This is quite serious, but does not influene the acoustic\n                 phonon scattering (taken to be zero in the model implemented\n                 here). The current approach if not using the\n                 analytic parabolic models is that the transfer energies\n                 for all scattering mechanisms are summed and the energy\n                 of where the relaxation time is evaluated is shifted by\n                 this amount during interpolation. The sum approximation\n                 is not physically justified and needs additional\n                 investigation, also the interpolation are sensitive and\n                 can fail close to the van Hove singularities since the\n                 relaxation time is propotional to the inverse of\n                 the density of states. All known problems pertaining to\n                 density of states are also manifested here for the\n                 scattering.\n\n    \"\"\"\n    # set logger\n    logger = logging.getLogger(sys._getframe().f_code.co_name)  # pylint: disable=protected-access\n    logger.debug(\"Running scattering_dos.\")\n    logger.debug(\"Calculating the scattering properties based on the \"\n                 \"models of the density of states.\")\n\n    # set temperature\n    temperatures = tr.temperatures\n\n    num_scatterings = select_scattering[0].shape[0]\n    num_bands = tr.bs.energies.shape[0]\n    num_energy_steps = energies.shape[0]\n    temperature_steps = temperatures.shape[0]\n    prefactor_scattering = np.zeros(\n        (temperature_steps, num_bands, num_scatterings))\n    scattering = np.zeros(\n        (temperature_steps, num_bands, num_energy_steps, num_scatterings))\n    inc_in_total = np.zeros((num_bands, num_scatterings), dtype=bool)\n    tr.tau_energy_trans = np.zeros((num_bands, num_scatterings))\n    # prepare stuff that does not depend on temperature\n    # calculate q for intervalley phonon scattering\n    q_diff = tr.bs.q_energy_trans[:, 1] - tr.bs.q_energy_trans[:, 0]\n    q_length = np.linalg.norm(q_diff)\n\n    # build scaling (unit array)\n    scaling = np.full((num_scatterings, 2), constants.zeroshift)\n    scaling[0, 0] = 1e5 * constants.pi * \\\n        constants.kb / (constants.hbar * constants.jtoev)\n    scaling[1, 0] = 1e2 * constants.pi / (2.0 * constants.jtoev)\n    scaling[1, 1] = 1e-4 * constants.hbar\n    scaling[2, 0] = 1e5 * constants.pi / (constants.hbar * constants.jtoev)\n    scaling[2, 1] = 1e2 * constants.pi / (2.0 * constants.jtoev)\n    scaling[3, 0] = 2 * constants.pi\n    # check that we do not loop over several temperatures\n    # if one or more explicit tau0 has been given, since tau0\n    # often include a temperature dependent factor\n    if np.any(tr.bs.explicit_prefact):\n        if temperatures.shape[0] > 1:\n            logger.error(\"Explicit tau0 have been set, but the user \"\n                         \"also wants to use these at different \"\n                         \"temperatures. This is often simply wrong. \"\n                         \"Exiting.\")\n            sys.exit(1)\n\n    # build prefix array\n    # loop temperature\n    for tempi, tempv in np.ndenumerate(temperatures):\n        # loop scattering mechanisms\n        for band in range(num_bands):\n            emi = 0.0\n            sign = 1.0\n            # fetch which scattering processes set for total sum\n            inc_in_total[band] = tr.bs.select_scattering[band]\n            for scattering_index, _ in \\\n                    np.ndenumerate(select_scattering[band]):\n\n                # This portion sets the scattering array based\n                # on the more general density of states models.\n\n                # tau=tau_0/DOS(E+E_trans),\n\n                # where E_trans is some transfer energy.\n\n                # However, in this routine we use the inverse values\n                # (scattering rates), w (propto DOS(E))\n                if scattering_index[0] == 0:\n                    # Elastic acoustic phonon scattering\n\n                    # w0[0] = pi*k*T*D_a^2/(hbar*v^2*rho)\n\n                    # D_a = acoustic deformation potential [eV]\n                    # v = speed of sound [m/s]\n                    # rho = mass density [g/cm^3]\n\n                    # and DOS in units of 1/(eV AA^3) yields w0\n                    # in units of fs as for the parabolic case\n\n                    # tau0[0] = pi*D^2/(hbar*v^2*rho)\n\n                    # units are the same, but the kT factor is added\n                    # on the fly to account for temperature\n                    # dependent data arrays\n                    if tr.bs.explicit_prefact[band][0]:\n                        prefactor_scattering[tempi,\n                                             band,\n                                             scattering_index] = \\\n                            tr.bs.explicit_prefact_values[band][0]\n                    else:\n                        da = tr.bs.da[band]\n                        rho = tr.bs.rho[band]\n                        speed_sound = tr.bs.speed_sound[band]\n                        prefactor_scattering[tempi,\n                                             band,\n                                             scattering_index] = \\\n                            scaling[0, 0] * tempv * np.power(da /\n                                                             speed_sound,\n                                                             2.0) / rho\n\n                elif scattering_index[0] == 1:\n                    # Nonpolar optical phonon scattering\n\n                    # w0[1]=pi*D_o^2*(n_op+1/2-/+1/2)/(2*rho*omega_op)\n\n                    # D_o = non-polar optical deformation potential [eV/AA]\n                    # n_op = optical phonon occupation number\n                    # rho = mass density [g/cm^3]\n                    # omega_op = optical phonon angular frequency\n                    # (often Einstein) [THz]\n                    if tr.bs.explicit_prefact[band][1]:\n                        prefactor_scattering[tempi,\n                                             band,\n                                             scattering_index] = \\\n                            tr.bs.explicit_prefact_values[band][1]\n                    else:\n                        d = tr.bs.do[band]\n                        n = tr.bs.no[band]\n                        rho = tr.bs.rho[band]\n                        omega = tr.bs.omegao[band]\n                        tr.tau_energy_trans[\n                            band, scattering_index] = \\\n                            sign * scaling[1, 1] * omega\n\n                        if tr.bs.emi[band]:\n                            emi = 1.0\n                        prefactor_scattering[\n                            tempi, band, scattering_index] = \\\n                            scaling[1, 0] * np.power(d, 2.0) * \\\n                            (n + 1.0 * emi) / (rho * omega)\n\n                elif scattering_index[0] == 2:\n                    # Intervalley phonon scattering\n\n                    # w0[2]=pi*D_vv'^2*(n_vv'+1/2-/+1/2)/(2*rho*omega_vv')\n\n                    # D_vv'=sqrt(|D_a*q_vv'|^2+D_o^2)\n\n                    # D_a = acoustic deformation potential [eV]\n                    # D_o = non-polar optical deformation potential [eV/AA]\n                    # n_vv' = intervalley phonon occupation number\n                    # rho = mass density [g/cm^3]\n                    # omega_vv' = intervalley transition phonon angular\n                    #             frequency [THz]\n                    if tr.bs.explicit_prefact[band][2]:\n                        prefactor_scattering[tempi,\n                                             band,\n                                             scattering_index] = \\\n                            tr.bs.explicit_prefact_values[band][2]\n                    else:\n                        # calculate D_vv'\n                        da = tr.bs.da[band]\n                        do = tr.bs.do[band]\n                        n = tr.bs.nvv[band]\n                        rho = tr.bs.rho[band]\n                        omega = tr.bs.omegavv[band]\n                        if tr.bs.emi[band]:\n                            emi = 1.0\n                        dvv = np.sqrt(\n                            np.power(scaling[2, 0] * da * q_length, 2.0) +\n                            np.power(scaling[2, 1] * do, 2.0))\n                        prefactor_scattering[\n                            tempi, band, scattering_index] = \\\n                            scaling[2, 1] * np.power(dvv, 2.0) * \\\n                            (n + 1.0 * emi) / (rho * omega)\n\n                elif scattering_index[0] == 3:\n                    # Polar optical phonon scattering\n\n                    # w0[3]=2*pi*e^2*F^2*(n_op+1/2-/+1/2/hbar\n\n                    # F = Frohlich expression [?]\n                    # n_op = optical phonon occupation number\n                    if tr.bs.explicit_prefact[band][3]:\n                        prefactor_scattering[tempi,\n                                             band,\n                                             scattering_index] = \\\n                            tr.bs.explicit_prefact_values[band][3]\n                    else:\n                        # GET RID OF FROHLICH AND DO THE WHOLE THING\n                        f = tr.bs.f[band]\n                        n = tr.bs.no[band]\n                        # NO OMEGA YET, COMES FROM THE FROHLICH ++\n                        tr.tau_energy_trans[\n                            band,\n                            scattering_index] = sign * scaling[1, 1] * omega\n                        if tr.bs.emi[band]:\n                            emi = 1.0\n                        prefactor_scattering[\n                            tempi, band, scattering_index] = \\\n                            scaling[3, 0] * np.power(f, 2.0) * \\\n                            (n + 1.0 * emi)\n\n    # BEWARE: HERE WE DO NOT SHIFT PROPERLY FOR THE\n    # TRANSFER ENERGIES, PRINT WARNING\n    # UNTIL WE HAVE A SOLUTION TO THIS PROBLEM\n    logger.warning(\"BEWARE: The scattering models based on \"\n                   \"density of states does currently not \"\n                   \"properly involve the energy shift required \"\n                   \"for the transfer energies. This is quite \"\n                   \"serious, but does not influene the acoustic \"\n                   \"phonon scattering. The current approach if \"\n                   \"not using the analytic parabolic models is \"\n                   \"that the transfer energies for all scattering \"\n                   \"mechanisms are summed and the energy of \"\n                   \"where the relaxation time is evaluated \"\n                   \"is shifted by this amount during \"\n                   \"interpolation. The sum approximation is not \"\n                   \"physically justified and needs additional \"\n                   \"investigation, also the interpolation \"\n                   \"are sensitive and can fail close to the van \"\n                   \"Hove singularities since the relaxation \"\n                   \"time is propotional to the inverse of the \"\n                   \"density of states. Continuing.\")\n    # now, make sure tau_energy_trans is zero for the\n    # scattering mechnisms we do not\n    # want (because of the sum later runs over the whole array)\n    # and values are set\n    # even though select_scattering is False for these entries\n    # ~ flips the bool values in the array\n    tr.tau_energy_trans[~select_scattering] = 0.0\n\n    # now squeeze in the energy dependence\n    # (either directly or indirectly)\n    # multiply dos_times_scattering with the prefactor\n    # to obtain the scattering array\n    scattering[:, :, :, 0:num_scatterings - 2] = \\\n        dos[np.newaxis, :, :, np.newaxis] * \\\n        prefactor_scattering[:, :, np.newaxis,\n                             0:num_scatterings - 2]\n    # now add the constant scattering part given in fs units\n    # (so invert)\n    prefactor_scattering[:, :, num_scatterings -\n                         1] = 1.0 / tr.bs.tau0c[np.newaxis, :]\n    scattering[:, :, :, num_scatterings - 1] = 1.0 / \\\n        tr.bs.tau0c[np.newaxis, :, np.newaxis]\n    # set up array to force zeros into the sum array if one\n    # only wants certain scattering mechanisms in the total sum\n    iit = inc_in_total[:, np.newaxis, :] * \\\n        np.ones(energies.shape[0], dtype=int)[np.newaxis, :, np.newaxis]\n    # now calculate the total scattering rate\n    scattering_total = (np.nan_to_num(scattering) * iit).sum(-1)\n    # and then, since up til now we have calculated the scattering rate\n    # we invert all values in order to get the \"tau\" in fs units\n    # also set true zero to a small value before inverting\n    scattering = np.nan_to_num(scattering)\n    scattering[scattering < constants.zero] = constants.zero\n    scattering_total[scattering_total < constants.zero] = constants.zero\n    scattering_inv = 1.0 / scattering\n    scattering_inv = np.nan_to_num(scattering_inv)\n    with np.errstate(over=\"ignore\"):\n        scattering_total_inv = 1.0 / scattering_total\n    # remove nan, inf etc. and return\n    scattering_inv = np.nan_to_num(scattering_inv)\n    scattering_total_inv = np.nan_to_num(scattering_total_inv)\n    # tau0 for use in the closed Fermi integrals\n    prefactor_scattering[\n        prefactor_scattering < constants.zero] = constants.zero\n    scattering_tau0 = np.nan_to_num(1.0 / prefactor_scattering)\n    # now make sure the non selected scattering mechanisms\n    # contain very large value (so\n    # that the scattering rate W=0)\n    non_selected = np.array(1 - iit[:, 0, :], dtype=bool)\n    scattering_tau0[:, non_selected] = constants.large\n    return scattering_inv, scattering_total_inv, scattering_tau0\n\n\ndef scattering_parabolic(tr, energies, select_scattering, use_eonk=False):  # pylint: disable=too-many-locals # noqa: MC0001\n    \"\"\"\n    Setup scattering mechnisms.\n\n    Store values in the scattering arrays using parabolic band dispersions\n    as an approximation.\n\n    Parameters\n    ----------\n    tr : object\n        A `Transport()` object\n    energies : ndarray\n        | Dimension: (N)\n\n        Array containing the energy in eV at N samplings\n        where the scattering values are o be calculated.\n    select_scattering : ndarray\n        | Dimension: (12)\n\n        Array containing integers. Set to 1 to select\n        the scattering, 0 to exclude.\n        The variables in `select_scattering` are set in\n        the bandstructure configuration file, one value\n        for each scattering and band. See notes below\n        for the currrently available scattering mechnisms.\n    use_eonk : boolean\n        If set to True, generate the scattering values on the\n        supplied energy for each band and on its k-points\n\n    Returns\n    -------\n    scattering_inv : ndarray\n        | Dimension: (T,N,M,12)\n\n        The scattering array in fs units\n        in the current `Transport()` object for T temperature steps,\n        N number of bands, M number of energy steps and 12 number of\n        scattering mechanisms\n    scattering_total_inv : ndarray\n        | Dimension: (T, N, M)\n\n        The total (all mechanisms summed) scattering array\n        in fs units) in the current `Transport()` object for T\n        temperature steps, N number of bands and M number of\n        energy steps\n    scattering_tau0 : ndarray\n        | Dimension: (T, N, 12)\n\n        The scattering prefactor array, tau0 in units of fs,\n        in the current `Transport()` object for T temperature\n        steps, N number of bands and 12 number of\n        scattering mechanisms.\n\n    Notes\n    -----\n    Currently only the following scattering mechanisms are supported:\n\n    ========================= ====================\n    `select_scattering` index scattering mechanism\n    ========================= ====================\n    1                         Acoustic phonon scattering from def. pot.\n    2                         Non-polar optical phonon scattering from def. pot.\n    3                         Intervalley phonon scattering\n    4                         Polar optical phonon scattering\n    5                         Piezoelectric acoustic phonon scattering\n    6                         Ionized impurity scattering, Brooks-Herring\n    7                         Ionized impurity scattering, Conwell-Weisskopf\n    8                         Alloy scattering\n    9                         None\n    10                        None\n    11                        None\n    12                        Constant (energy and k-point independent)\n    ========================= ====================\n\n    Also consult the bandstructure\n    configuration file for the respective constants that have to\n    be set besides `select_scattering` and their units.\n\n    .. todo:: Add more extensive documentation for the different scattering\n              mechanisms.\n\n    \"\"\"\n    # set logger\n    logger = logging.getLogger(sys._getframe().f_code.co_name)  # pylint: disable=protected-access\n    logger.debug(\"Running scattering_parabolic.\")\n    logger.debug(\"Calculating the scattering properties based on the \"\n                 \"analytic parabolic scattering models.\")\n\n    # set temperatures\n    temperatures = tr.temperatures\n\n    num_scatterings = select_scattering[0].shape[0]\n    num_bands = tr.bs.energies.shape[0]\n    if not use_eonk:\n        # use supplied energy grid\n        num_energy_steps = energies.shape[0]\n    else:\n        # use the k-point grid of the energies\n        # assume same set of k-point grid for all bands\n        num_energy_steps = tr.bs.energies.shape[1]\n    factor = np.zeros((num_bands, num_scatterings))\n    temperature_steps = temperatures.shape[0]\n    prefactor_scattering = np.zeros(\n        (temperature_steps, num_bands, num_scatterings))\n    energy_correction_prefactor = np.zeros((num_bands, num_scatterings))\n    energy_r_correction = np.zeros((num_bands, num_scatterings))\n    scattering = np.zeros(\n        (temperature_steps, num_bands, num_energy_steps, num_scatterings))\n    inc_in_total = np.zeros((num_bands, num_scatterings), dtype=bool)\n    tr.tau_energy_trans = np.zeros((num_bands, num_scatterings))\n    # prepare stuff that does not depend on temperature\n    # calculate q for intervalley phonon scattering\n    q_diff = tr.bs.q_energy_trans[:, 1] - tr.bs.q_energy_trans[:, 0]\n    # remember to bring q to cartesian\n    q_length = np.linalg.norm(tr.bs.lattice.dir_to_cart(q_diff))\n\n    # build scaling (unit array)\n    scaling = np.full((num_scatterings, 2), constants.zeroshift)\n    r_factor = np.zeros(num_scatterings)\n    scaling[0, 0] = 1e4 * constants.kb * \\\n        np.power(constants.elmass, 1.5) * np.sqrt(constants.jtoev) / \\\n        (np.sqrt(5) * constants.pi * np.power(constants.hbar, 4.0))\n    scaling[1, 0] = np.sqrt(5) * np.power(constants.elmass, 1.5) * \\\n        np.sqrt(constants.jtoev) / \\\n        (constants.pi * np.power(constants.hbar, 3.0))\n    scaling[1, 1] = 1e-4 * constants.hbar\n    scaling[2, 0] = scaling[1, 0]\n    scaling[2, 1] = scaling[1, 1]\n    scaling[3, 0] = 0.1 * np.sqrt(constants.elmass) * \\\n        np.power(constants.elcharge, 2.0) * \\\n        constants.vacperm / \\\n        (4 * np.sqrt(20) * constants.pi * constants.hbar)\n    scaling[3, 1] = scaling[1, 1]\n    scaling[4, 0] = 1e7 * np.sqrt(constants.elmass) * \\\n        np.power(constants.elcharge, 2.0) * \\\n        constants.kb / \\\n        (np.sqrt(80) * constants.pi *\n         np.power(constants.vacperm *\n                  constants.hbar, 2.0))\n    scaling[4, 1] = constants.bandunit\n    scaling[5, 0] = 1e2 * np.sqrt(10) * \\\n        np.power(constants.elcharge, 4.0) / \\\n        (32 * np.sqrt(2) * constants.pi *\n         np.power(constants.vacperm, 2.0) *\n         np.sqrt(constants.elmass) *\n         np.power(constants.jtoev, -1.5))\n    scaling[5, 1] = constants.bandunit\n    scaling[6, 0] = 1e2 * np.sqrt(10) * \\\n        np.power(constants.elcharge, 4.0) / \\\n        (32 * np.sqrt(2) * constants.pi *\n         np.power(constants.vacperm, 2.0) *\n         np.sqrt(constants.elmass) * np.power(constants.jtoev, -1.5))\n    scaling[6, 1] = 1e-2 * 64 * np.power(constants.pi, 2.0) * \\\n        np.power(constants.vacperm, 2.0) / \\\n        np.power(constants.elmass * constants.jtoev, 2.0)\n    scaling[7, 0] = np.power(constants.elmass, 1.5) / \\\n        (np.power(constants.hbar, 4.0) * np.sqrt(5))\n    r_factor[0] = 0.0\n    r_factor[1] = 0.0\n    r_factor[2] = 0.0\n    r_factor[3] = 1.0\n    r_factor[4] = 1.0\n    r_factor[5] = 2.0\n    r_factor[6] = 2.0\n    r_factor[7] = 0.0\n    r_factor[num_scatterings - 1] = 0.5\n    tr.scattering_r_factor = r_factor\n    r_factor_includinghalf = 0.5 - r_factor\n    # check that we do not loop over several temperatures\n    # if one or more explicit tau0 has been given, since tau0\n    # often include a temperature dependent factor\n    if np.any(tr.bs.explicit_prefact):\n        if temperatures.shape[0] > 1:\n            logger.error(\"Explicit tau0 have been set, but the user \"\n                         \"also wants to use these at different \"\n                         \"temperatures. This is often simply wrong. \"\n                         \"Exiting.\")\n            sys.exit(1)\n\n    # build prefix array\n    # loop temperature\n    for tempi, tempv in np.ndenumerate(temperatures):\n        # loop scattering mechanisms\n        for band in range(num_bands):\n            emi = 0.0\n            sign = 1.0\n            # check parabolic effmass for all bands\n            effmass_vec = tr.bs.effmass[band]\n            if not parabolic_effective_mass(effmass_vec):\n                logger.error(\"The setup of scattering mechanisms using \"\n                             \"parabolic models requires a parabolic \"\n                             \"effective mass. Exiting.\")\n                sys.exit(1)\n            effmass = effmass_vec[0]\n            # make sure effective mass is positive\n            effmass = abs(effmass)\n            # fetch which scattering processes set for total sum\n            inc_in_total[band] = tr.bs.select_scattering[band]\n            for scattering_index, _ in \\\n                    np.ndenumerate(select_scattering[band]):\n                # This portion sets the scattering array based\n                # on the well established parabolic scattering models\n\n                # tau=tau_0*E^{r-1/2}\n\n                # However, in this routine we use the inverse values\n                # (scattering rates), w and invert at the end\n                if scattering_index[0] == 0:\n                    # Elastic acoustic phonon scattering\n\n                    # r = 0\n\n                    # w0=(sqrt(2)*m^3/2*k*T*D^2)/(pi*hbar^4*rho*v^2)\n\n                    # (with spin degen included)\n\n                    # energy dep = E^1/2\n\n                    # m = effective mass [kg]\n                    # D = acoustic deformation potential [eV]\n                    # v = speed of sound [m/s]\n                    # rho = mass density [g/cm^3]\n\n                    # BOTH ABSORPTION AND EMMISION\n\n                    # ONLY ELASTIC, e.g. hbar q v << kT\n                    if tr.bs.explicit_prefact[band][0]:\n                        prefactor_scattering[tempi,\n                                             band,\n                                             scattering_index] = \\\n                            tr.bs.explicit_prefact_values[band][0]\n                    else:\n                        if tempi[0] == 0:\n                            da = tr.bs.da[band]\n                            speed_sound = tr.bs.speed_sound[band]\n                            rho = tr.bs.rho[band]\n                            factor[band, scattering_index] = \\\n                                scaling[0, 0] * np.power(effmass, 1.5) * \\\n                                np.power(da, 2.0) / \\\n                                (np.power(speed_sound, 2.0) * rho)\n                        prefactor_scattering[tempi, band, scattering_index] = \\\n                            factor[band, scattering_index] * tempv\n\n                if scattering_index[0] == 1:\n                    # Nonpolar optical scattering\n\n                    # r = 0\n\n                    # w0=(m^3/2*D_o^2)/(sqrt(2)*pi*hbar^3*rho*omega_op)\n                    #      *(n_op+1/2-/+1/2)\n\n                    # energy dep = (E +/- hbar*omega_op)^1/2\n\n                    # m = effective mass, units of m_e\n                    # D = non-polar optical deformation potential [eV/AA]\n                    # n_op = optical phonon occupation number\n                    # rho = mass density [g/cm^3]\n                    # omega_op = optical phonon angular frequency\n                    #            (often Einstein) [THz]\n\n                    # NO EMMISION IF E<hbar omega\n                    if tr.bs.explicit_prefact[band][1]:\n                        prefactor_scattering[tempi,\n                                             band,\n                                             scattering_index] = \\\n                            tr.bs.explicit_prefact_values[band][1]\n                    else:\n                        if tempi[0] == 0:\n                            do = tr.bs.do[band]\n                            rho = tr.bs.rho[band]\n                            omega = tr.bs.omegao[band]\n                            n = tr.bs.no[band]\n                            if tr.bs.emi[band]:\n                                emi = 1.0\n                                sign = -1.0\n                            temp = sign * scaling[1, 1] * omega\n                            energy_r_correction[band, scattering_index] = temp\n                            # set the transfer energy (used sometimes when\n                            # integrating the explicit tau)\n                            tr.tau_energy_trans[\n                                band, scattering_index] = \\\n                                sign * scaling[1, 1] * omega\n                            factor[band, scattering_index] = \\\n                                scaling[1, 0] * np.power(effmass, 1.5) * \\\n                                np.power(do, 2.0) * (n + 1.0 * emi) / \\\n                                (omega * rho)\n                        prefactor_scattering[tempi, band, scattering_index] = \\\n                            factor[band, scattering_index]\n\n                if scattering_index[0] == 2:\n                    # Intervalley phonon scattering\n\n                    # r = 0\n\n                    # w0=m^3/2*D_vv'^2*Z_f)/(sqrt(2)*pi*hbar^3*rho*omega_vv')\n                    #      *(n_vv'+1/2-/+1/2)\n\n                    # energy dep = (E +/- hbar*omega_vv' - dE_vv')^1/2\n\n                    # m = effective mass, units of m_e\n                    # Z_f = numer of possible final states (final degeneracy)\n                    # D_vv'=sqrt(|D_a*q_vv'|^2+D_o^2)\n                    # D_a = acoustic deformation potential [eV]\n                    # D_o = non-polar optical deformation potential [eV/AA]\n                    # n_vv' = intervalley phonon occupation number\n                    # rho = mass density [g/cm^3]\n                    # omega_vv' = intervalley transition phonon angular\n                    #             frequency [THz]\n\n                    # NO ABSORPTION OR EMMISION IF E < hbar omega - etrans\n                    # (i=initial, f=final)\n\n                    # where\n\n                    # etrans = energy difference between the bottoms of the\n                    #          final and initial valley [eV]\n                    if tr.bs.explicit_prefact[band][2]:\n                        prefactor_scattering[tempi,\n                                             band,\n                                             scattering_index] = \\\n                            tr.bs.explicit_prefact_values[band][2]\n                    else:\n                        # calculate D_vv'\n                        if tempi[0] == 0:\n                            da = tr.bs.da[band]\n                            do = tr.bs.do[band]\n                            n = tr.bs.nvv[band]\n                            rho = tr.bs.rho[band]\n                            omega = tr.bs.omegavv[band]\n                            zf = tr.bs.zf[band]\n                            etrans = tr.bs.etrans[band]\n                            if tr.bs.emi[band]:\n                                emi = 1.0\n                                sign = -1.0\n                            # TODO: generalize D_a*q to vector form pylint: disable=fixme\n                            dvv = np.sqrt(\n                                np.power(da * q_length, 2.0) +\n                                np.power(do, 2.0))\n                            temp = sign * scaling[2, 1] * omega - etrans\n                            energy_r_correction[band, scattering_index] = temp\n                            # set the transfer energy (used sometimes when\n                            # integrating the explicit tau)\n                            tr.tau_energy_trans[band, scattering_index] = temp\n                            factor[band, scattering_index] = \\\n                                scaling[2, 0] * np.power(effmass, 1.5) * \\\n                                np.power(dvv, 2.0) * zf * (n + 1.0 * emi) / \\\n                                (rho * omega)\n                        prefactor_scattering[tempi, band, scattering_index] = \\\n                            factor[band, scattering_index]\n\n                if scattering_index[0] == 3:\n                    # Polar optical phonon scattering\n\n                    # r = 1, with corrections (not a simple energy relation)\n\n                    # w0 = (sqrt(m)*e^2*omega)*(1/eps(inf)-1/eps(0))*\n                    #      (n+1/2-/+1/2)/(4*pi*hbar*sqrt(2))\n\n                    # energy dep = E^-1/2 * ln(sqrt(E)+sqrt(E +/- hbar omega)/\n                    #              |sqrt(E)-sqrt(E +/- hbar omega)|)\n\n                    # m = effective mass, units of m_e\n                    # omega = optical phonon angular frequency [THz]\n                    # eps(inf) = electronic permitivity, units of vacuum\n                    #            permitivity\n                    # eps = ionic permitivity, units of vacuum permitivity\n                    # n = optical phonon occupation number\n\n                    # ONLY VALID IF E > hbar omega (assume elastic process)\n\n                    # ALSO, NEGLECTED SCREENING (ONLY VALID FOR HIGHLY DOPED)\n                    if tr.bs.explicit_prefact[band][3]:\n                        prefactor_scattering[tempi,\n                                             band,\n                                             scattering_index] = \\\n                            tr.bs.explicit_prefact_values[band][3]\n                    else:\n                        if tempi[0] == 0:\n                            omega = tr.bs.omegao[band]\n                            epsi = tr.bs.epsi[band]\n                            eps = tr.bs.eps[band]\n                            n = tr.bs.no[band]\n                            if tr.bs.emi[band]:\n                                emi = 1.0\n                                sign = -1.0\n                            temp = sign * scaling[3, 1] * omega\n                            energy_correction_prefactor[\n                                band, scattering_index] = temp\n                            # set the transfer energy (used sometimes when\n                            # integrating the explicit tau)\n                            tr.tau_energy_trans[band, scattering_index] = temp\n                            factor[band, scattering_index] = \\\n                                scaling[3, 0] * np.sqrt(effmass) * \\\n                                omega * (1 / epsi - 1 / eps) * \\\n                                (n + 1.0 * emi)\n                        prefactor_scattering[tempi, band, scattering_index] = \\\n                            factor[band, scattering_index]\n\n                if scattering_index[0] == 4:\n                    # Piezoelectric acoustic phonon scattering\n\n                    # r = 1, with corrections (not a simple energy relation)\n\n                    # w0 = ((p^2*sqrt(m)*e^2*k*T)/ \\\n                    #       (sqrt(8)*pi*eps^2*hbar^2*rho*v^2))\n\n                    # energy dep = E^-1/2 * [ln(1+4E/E_0)-1/(1+E_0/4E)]\n\n                    # where E_0 = hbar^2 isl^2 / 2 m\n\n                    # m = effective mass, unitless units of m_e\n                    # p = piezoelectric constant [C/m^2]\n                    # T = temperature [K]\n                    # eps = electronic dielectric constant [F/m]\n                    # rho = mass density [g/cm^3]\n                    # v = speed of sound [m/s]\n                    # isl = inverse screening length [AA^-1]\n\n                    # INCLUDES BOTH ABSORPTION AND EMMISION\n                    if tr.bs.explicit_prefact[band][4]:\n                        prefactor_scattering[tempi,\n                                             band,\n                                             scattering_index] = \\\n                            tr.bs.explicit_prefact_values[band][4]\n                    else:\n                        if tempi[0] == 0:\n                            p = tr.bs.p[band]\n                            eps = tr.bs.eps[band]\n                            rho = tr.bs.rho[band]\n                            speed_sound = tr.bs.speed_sound[band]\n                            isl = tr.bs.isl[band]\n                            if effmass < constants.zero:\n                                effmass = constants.zero\n                            energy_correction_prefactor[band, scattering_index] = \\\n                                scaling[4, 1] * np.power(isl, 2.0) / effmass\n                            denom = np.power(eps * speed_sound, 2.0) * rho\n                            if denom < constants.zero:\n                                denom = constants.zero\n                            factor[band, scattering_index] = scaling[4, 0] * \\\n                                np.sqrt(effmass) * \\\n                                np.power(p, 2.0) / denom\n                            # ignore overflow when performing multiply\n                            np.seterr(over='ignore')\n                        prefactor_scattering[tempi, band, scattering_index] = \\\n                            factor[band, scattering_index] * tempv\n\n                if scattering_index[0] == 5:\n                    # Ionized impurity scattering (BH)\n\n                    # r = 2, with corrections (not a simple energy relation)\n\n                    # w0 = Z^2*e^4*n_i/(32*pi*sqrt(2*m)*eps^2)\n\n                    # energy dep = E^-3/2 * (ln(1+gamma)-gamma/(1+gamma))\n\n                    # m = effective mass, units of m_e\n                    # Z = number of charge units (of e) of the impurity\n                    # n_i = ionized impurity density [10^21 cm^-3]\n                    # eps = electronic dielectric constant [in units of epsilon_0]\n                    # gamma = 4E/E_0\n                    # E_0 = hbar^2 isli^2/2m\n                    # isli = inverse screening length in AA^-1\n                    if tr.bs.explicit_prefact[band][5]:\n                        prefactor_scattering[tempi,\n                                             band,\n                                             scattering_index] = \\\n                            tr.bs.explicit_prefact_values[band][5]\n                    else:\n                        if tempi[0] == 0:\n                            z = tr.bs.z[band]\n                            n_i = tr.bs.ni[band]\n                            eps = tr.bs.eps[band]\n                            isli = tr.bs.isli[band]\n                            e_0 = scaling[5, 1] * np.power(isli, 2.0) / effmass\n                            denom = np.power(eps, 2.0) * np.sqrt(effmass)\n                            if denom < constants.zero:\n                                denom = constants.zero\n                                factor[band, scattering_index] = \\\n                                    scaling[5, 0] * \\\n                                    np.power(z, 2.0) * n_i / denom\n                            energy_correction_prefactor[band,\n                                                        scattering_index] = e_0\n                        prefactor_scattering[tempi, band, scattering_index] = \\\n                            factor[band, scattering_index]\n\n                if scattering_index[0] == 6:\n                    # Ionized impurity scattering (CW)\n\n                    # r = 2, with corrections (not a simple energy relation)\n\n                    # w0 = e^4*n_i/(32*pi*sqrt(2m)*eps^2)\n\n                    # energy dep = E^-3/2 * ln(1+gamma)\n\n                    # m = effective mass, units of m_e\n                    # n_i = ionized impurity density [10^21 cm^-3]\n                    # eps = electronic dielectric constant [in units of epsilon_0]\n                    # gamma = (8pi b epsilon E/e^2)^2\n                    # b = (3/4pi n_i)^1/3\n                    if tr.bs.explicit_prefact[band][6]:\n                        prefactor_scattering[tempi,\n                                             band,\n                                             scattering_index] = \\\n                            tr.bs.explicit_prefact_values[band][6]\n                    else:\n                        if tempi[0] == 0:\n                            z = tr.bs.z[band]\n                            n_i = tr.bs.ni[band]\n                            eps = tr.bs.eps[band]\n                            b = np.power(  # pylint: disable=assignment-from-no-return\n                                4 * constants.pi * n_i / 3.0, -1.0 / 3.0)\n                            factor[band, scattering_index] = scaling[\n                                6, 0] * n_i / np.sqrt(effmass)\n                            energy_correction_prefactor[band, scattering_index] = \\\n                                scaling[6, 1] * np.power(eps * b, 2.0)\n                        prefactor_scattering[tempi, band, scattering_index] = \\\n                            factor[band, scattering_index]\n\n                if scattering_index[0] == 7:\n                    # Alloy scattering\n\n                    # r = 0\n\n                    # w0 = sqrt(2) * V * m^3/2 V_diff^2 x(1-x) / (hbar^4)\n\n                    # energy dep = E^-1/2\n\n                    # m = effective mass, units of m_e\n                    # V = volume of unit cell in AA^3\n                    # V_diff = difference between the two species atomic\n                    #          potential in eV\n                    # x = the fraction (of e.g. the compound A_xB_(1-x)C)\n\n                    # NEUTRAL MODEL, OTHERWISE USE IONIZED IMPURITY\n                    if tr.bs.explicit_prefact[band][7]:\n                        prefactor_scattering[tempi,\n                                             band,\n                                             scattering_index] = \\\n                            tr.bs.explicit_prefact_values[band][7]\n                    else:\n                        if tempi[0] == 0:\n                            v = tr.lattice.volume\n                            v_diff = tr.bs.vdiff[band]\n                            x = tr.bs.alloyconc[band]\n                            factor[band, scattering_index] = \\\n                                scaling[7, 0] * np.power(effmass, 1.5) * \\\n                                np.power(v_diff, 2.0) * v * x * (1 - x)\n                        prefactor_scattering[tempi, band, scattering_index] = \\\n                            factor[band, scattering_index]\n\n    # now squeeze in the energy dependence (either directly or indirectly)\n\n    # multiply with energy term given by the energy spacing\n    # check if we have negative values in energies, take absolute value\n    # also add shifts of energy from phonons, exitations etc from\n    # correction_prefactor\n    if not use_eonk:\n        # use supplied energy grid\n        with np.errstate(divide='ignore'):\n            power_energy = np.power(  # pylint: disable=assignment-from-no-return\n                np.abs(energies[np.newaxis, :, np.newaxis] +\n                       energy_r_correction[:, np.newaxis, :]),\n                r_factor_includinghalf[np.newaxis, np.newaxis, :])\n    else:\n        # use energies that lies on the k-point grid\n        with np.errstate(divide='ignore'):\n            power_energy = np.power(  # pylint: disable=assignment-from-no-return\n                np.abs(energies[:, :, np.newaxis] +\n                       energy_r_correction[:, np.newaxis, :]),\n                r_factor_includinghalf[np.newaxis, np.newaxis, :])\n\n    # in the following we apply energy corrections\n    # remove nan values (force to zero)\n    power_energy = np.nan_to_num(power_energy)\n    # ignore overflow\n    with np.errstate(over='ignore'):\n        scattering[:, :, :, 0:num_scatterings - 2] = \\\n            power_energy[np.newaxis, :, :, 0:num_scatterings - 2] * \\\n            prefactor_scattering[:, :, np.newaxis, 0:num_scatterings - 2]\n    # TODO: HERE WE SHOULD HAVE A REMOVE NAN AND NUM AGAIN? pylint: disable=fixme\n\n    # calculate correction factor for tau[3] (polar optical) and add\n    e_dep = np.sqrt(\n        np.abs(energies[np.newaxis, :]) +\n        energy_correction_prefactor[:, np.newaxis, 3])\n    # remove nan values (force to zero)\n    e_dep = np.nan_to_num(e_dep)\n    denom = np.abs(np.sqrt(np.abs(energies[np.newaxis, :])) - e_dep)\n    denom[denom < constants.zero] = constants.zero\n    with np.errstate(divide='ignore'):\n        e_cor_fact = np.log(  # pylint: disable=assignment-from-no-return\n            (np.sqrt(np.abs(energies[np.newaxis, :])) + e_dep) / denom)\n    # remove inf values (force to the largest supported value)\n    e_cor_fact = np.nan_to_num(e_cor_fact)\n    scattering[:, :, :, 3] = scattering[:, :, :, 3] * e_cor_fact[np.\n                                                                 newaxis, :, :]\n\n    # calculate correction factor for tau[4] (piezoelectric) and add\n    denom = energy_correction_prefactor[:, np.newaxis, 4]\n    denom[denom < constants.zero] = constants.zero\n    with np.errstate(over=\"ignore\"):\n        e_dep = 4 * np.abs(energies[np.newaxis, :]) / denom\n    # remove inf values (force to the largest supported value)\n    e_dep = np.nan_to_num(e_dep)\n    e_cor_fact = np.log(1 + e_dep) - e_dep / (e_dep + 1)\n    # remove nan values (force to zero)\n    # ignore overflow\n    with np.errstate(over=\"ignore\"):\n        scattering[:, :, :,\n                   4] = scattering[:, :, :, 4] * e_cor_fact[np.newaxis, :, :]\n\n    # calculate the correction factor for tau[5] (BH ionized imp) and add\n    # (very similar to piezoelectric, but we assume we can have different\n    # screening lengths)\n    denom = energy_correction_prefactor[:, np.newaxis, 5]\n    denom[denom < constants.zero] = constants.zero\n    with np.errstate(over=\"ignore\"):\n        e_dep = 4 * np.abs(energies[np.newaxis, :]) / denom\n    # remove inf values (force to the largest supported value)\n    e_dep = np.nan_to_num(e_dep)\n    e_cor_fact = np.log(1 + e_dep) - e_dep / (e_dep + 1)\n    scattering[:, :, :, 5] = scattering[:, :, :, 5] * e_cor_fact[np.\n                                                                 newaxis, :, :]\n\n    # calculate the correction factor for tau[6] (CW ionized imp) and add\n    # (very similar to BH, but different correction factor)\n    e_dep = np.power(np.abs(energies[np.newaxis, :]), 2.0) * \\\n        energy_correction_prefactor[:, np.newaxis, 6]\n    # remove inf values (force to the largest supported value)\n    e_dep = np.nan_to_num(e_dep)\n    e_cor_fact = np.log(1 + e_dep)  # pylint: disable=assignment-from-no-return\n    scattering[:, :, :, 6] = scattering[:, :, :, 6] * e_cor_fact[np.\n                                                                 newaxis, :, :]\n\n    # now add the constant scattering part given in fs units (so invert)\n    prefactor_scattering[:, :, num_scatterings -\n                         1] = 1.0 / tr.bs.tau0c[np.newaxis, :]\n    scattering[:, :, :, num_scatterings - 1] = 1.0 / \\\n        tr.bs.tau0c[np.newaxis, :, np.newaxis]\n    # set up array to force zeros into the sum array if one only wants certain\n    # scattering mechanisms in the total sum\n    iit = inc_in_total[:, np.newaxis, :] * \\\n        np.ones(num_energy_steps, dtype=int)[np.newaxis, :, np.newaxis]\n    # now calculate the total scattering rate\n    scattering_total = (np.nan_to_num(scattering) * iit).sum(-1)\n    # and then, since up til now we have calculated the scattering rate\n    # we invert all values in order to get the \"tau\" in fs units\n    # also set true zero to a small value before inverting\n    scattering[scattering < constants.zero] = constants.zero\n    scattering_total[scattering_total < constants.zero] = constants.zero\n    scattering = np.nan_to_num(scattering)\n    # now invert the scattering array (use same name\n    # to save memory)\n    scattering = 1.0 / scattering\n    with np.errstate(over=\"ignore\"):\n        scattering_total_inv = 1.0 / scattering_total\n    # remove nan, inf etc.\n    scattering = np.nan_to_num(scattering)\n    scattering_total_inv = np.nan_to_num(scattering_total_inv)\n    # tau0 for use in the closed Fermi integrals\n    prefactor_scattering[\n        prefactor_scattering < constants.zero] = constants.zero\n    scattering_tau0 = np.nan_to_num(1.0 / prefactor_scattering)\n    # now make sure the non selected scattering mechanisms contain very\n    # large value (so that the scattering rate W=0)\n    non_selected = np.array(1 - iit[:, 0, :], dtype=bool)\n    scattering_tau0[:, non_selected] = constants.large\n    return scattering, scattering_total_inv, scattering_tau0\n\n\ndef find_r_for_closed(tr, band):\n    \"\"\"\n    Analyze the input tau0 and find the associated scattering values r.\n\n    Parameters\n    ----------\n    tr : object\n        A `Transport()` object\n    band : integer\n        The band index.\n\n    Returns\n    -------\n    integer\n        Two times the r value to avoid half integer values.\n\n    Notes\n    -----\n    These are necessary for the analytic Fermi integrals.\n\n    \"\"\"\n\n    # set logger\n    logger = logging.getLogger(sys._getframe().f_code.co_name)  # pylint: disable=protected-access\n    logger.debug(\"Running find_r_for_closed.\")\n\n    # check that only one scattering mech is entered\n    if np.sum(tr.bs.select_scattering[band]) > 1:\n        logging.error(\"Parabolic Fermi integral routines are only \"\n                      \"defined for one type of scattering. Typically, \"\n                      \"set one scattering mechnisms to a value (tau0) \"\n                      \"and the other factors to zero. Exiting.\")\n        sys.exit(1)\n    # return value and multiply by two\n    return int(2 * tr.scattering_r_factor[tr.bs.select_scattering[band]])\n\n\ndef combined_scattering(tr, energy, tau0, energy_trans):\n    r\"\"\"\n    Calculates the total relaxation time.\n\n    Parameters\n    ----------\n    tr : object\n        A `Transport()` object\n    energy : float\n        The energy of the charge carrier in eV.\n    tau0 : ndarray\n        | Dimension: (12)\n\n        Contains the relaxation time prefactors for the\n        different scattering mechanisms in units of fs.\n    energy_trans : ndarray\n        | Dimension: (12)\n\n        Contains the energy transitions in eV (that is added to the energy\n        in :math:`\\\\tau=\\\\tau_0E^{r-1/2}`, typically,\n        :math:`E=E+\\\\hbar \\\\omega`, where :math:`\\\\hbar \\\\omega`\n        is the size of the energy transition. Set it to zero for\n        the non-relevant scattering mechanisms.\n    effmass : float\n        The effective mass in units of the electron mass\n\n    Returns\n    -------\n    float\n        The combined relaxation time in fs.\n\n    Notes\n    -----\n    Calculates the total relaxation time\n\n    .. math:: \\\\frac{1}{\\\\tau}=\\\\sum_i \\\\frac{1}{\\\\tau_i},\n\n    where :math:`\\\\tau=\\\\tau_0E^{r-1/2}`.\n    The array `scattering_tau0_select` determines which\n    scattering to include in the sum. Consult :func:`scattering_parabolic`\n    for additional details. The scattering prefactors\n    :math:`\\\\tau_0` are ordered in a sequence described there.\n    The `scattering_tau0_select` follows this sequence and is\n    set in the bandstructure configuration file.\n\n    \"\"\"\n\n    # set logger\n    logger = logging.getLogger(sys._getframe().f_code.co_name)  # pylint: disable=protected-access\n    logger.debug(\"Running combined_scattering.\")\n\n    tau_decomp = (tau0 *\n                  np.power(energy + energy_trans, 0.5 -\n                           tr.scattering_r_factor))[tr.scattering_tau0_select]\n    tau_decomp = np.nan_to_num(tau_decomp)\n    return np.nan_to_num(1.0 / np.sum(tau_decomp))\n\n\ndef interpolate(tr, method=\"linear\"):  # pylint: disable=too-many-locals\n    \"\"\"\n    Interpolates the scattering array on all available energies.\n\n    Parameters\n    ----------\n    tr : object\n        A `Transport()` object containing the scattering arrays\n        and the energies etc.\n    method : string, optional\n        The interpolation method to use. Uses\n        the :func:`interp1d` function of Scipy and this sets the\n        parameter `kind`. Defaults to \"linear\".\n\n    Returns\n    -------\n    None\n\n    See Also\n    --------\n    scipy.interpolate.interp1d\n\n    Notes\n    -----\n    Here we only perform an interpolation on the array containing the total\n    relaxation time since this is used during the transport calculations.\n\n    \"\"\"\n\n    # set logger\n    logger = logging.getLogger(sys._getframe().f_code.co_name)  # pylint: disable=protected-access\n    logger.debug(\"Running interpolate.\")\n\n    logger.info(\"Interpolating the scattering values on the energygrid \"\n                \"of the band structure.\")\n\n    # check the validity of the method parameter\n    if method not in constants.interp1d_methods:\n        logger.error(\"The 'method' parameter passed is not a present \"\n                     \"option for your interp1d version. Exiting\")\n        sys.exit(1)\n\n    energies = tr.scattering_energies\n    scattering_total_inv = tr.scattering_total_inv\n    scattering_inv = tr.scattering_inv\n    inter_energies = tr.bs.energies\n\n    # We need to make sure that the requested energies are\n    # inside the bounds of the original data set. We do this\n    # simply by padding the smallest and largest values by a\n    # small constant. These values should anyway be far outside\n    # the important energy region anyway.\n    max_inter_energies = np.amax(inter_energies)\n    min_inter_energies = np.amin(inter_energies)\n    # need to check if other values are similar to some constant\n    # first, check largest\n    replace = np.where(\n        inter_energies > (max_inter_energies - constants.zerocut))\n\n    inter_energies[replace] = inter_energies[replace] - \\\n        constants.zerocut\n\n    # then smallest\n    replace = np.where(\n        inter_energies < (min_inter_energies + constants.zerocut))\n    inter_energies[replace] = inter_energies[replace] + \\\n        constants.zerocut\n\n    # this is really dirty, but since the number of temperatures\n    # and bands is usually pretty limited it was not a top priority to\n    # increase the speed of this one, could easily be done\n    # in a different way...\n    num_temp_steps = scattering_total_inv.shape[0]\n    num_bands = scattering_total_inv.shape[1]\n    num_energies = inter_energies.shape[1]\n    num_scatterings = scattering_inv.shape[3]\n    scattering_total_inv_inter = np.zeros(\n        (num_temp_steps, num_bands, num_energies))\n    if not tr.param.onlytotalrate:\n        scattering_inv_inter = np.zeros(\n            (num_temp_steps, num_bands, num_energies, num_scatterings))\n    for temp in range(num_temp_steps):\n        for band in range(num_bands):\n            # do the interpolation of the total first\n            inter_total_inv = \\\n                scipy.interpolate.interp1d(energies,\n                                           scattering_total_inv[temp, band])\n            scattering_total_inv_inter[temp, band] = inter_total_inv(\n                inter_energies[band])\n\n            if not tr.param.onlytotalrate:\n                # and then the decomposed, but only for the selected mechanisms\n                include_scattering = np.nonzero(\n                    tr.bs.select_scattering[band])[0]\n                exclude_scattering = np.nonzero(\n                    1 - tr.bs.select_scattering[band])[0]\n                for scattering in include_scattering:\n                    inter_inv = scipy.interpolate.interp1d(\n                        energies, scattering_inv[temp, band, :, scattering])\n                    scattering_inv_inter[\n                        temp, band, :, scattering] = \\\n                        inter_inv(inter_energies[band])\n                for scattering in exclude_scattering:\n                    scattering_inv_inter[temp, band, :, scattering] = np.full(\n                        num_energies, constants.large)\n\n    # store new dense scattering arrays, also make sure we have\n    # no nans or inf\n    tr.scattering_total_inv = np.nan_to_num(scattering_total_inv_inter)\n    if not tr.param.onlytotalrate:\n        tr.scattering_inv = np.nan_to_num(scattering_inv_inter)\n    # now the scattering energies are in fact just the energies\n    # for each band and kpoint, setting it like this\n    # should avoid occupying more memory than necessary,\n    # but could be a bugsource...beware!\n    tr.scattering_energies = inter_energies\n\n\ndef pad_scattering_values(tr):\n    \"\"\"\n    Pad the scattering values.\n\n    Parameters\n    ----------\n    tr : object\n        A `Transport()` object.\n\n    Returns\n    -------\n    None\n\n    Notes\n    -----\n    The padded values are stored in the `tr` object.\n\n    We need to pad the energies where the dos is calculated\n    with a larger number of samples such that we cover the whole\n    energy range in the stored bandstructure due to later\n    interpolation routines etc. not going out of bounds\n    when such energies are passed to the interpolator etc.\n\n    We can set it to a large number because 1 eV outside the\n    chemical potential. We already know no states contribute\n    at temperatures below 2000 K.\n\n    \"\"\"\n    # fetch min and max of the energies stored for the\n    # bandstructure\n    scattering_inv = tr.scattering_inv\n    scattering_total_inv = tr.scattering_total_inv\n    energies = tr.scattering_energies\n    emin, emax = tr.bs.fetch_min_max_energy()\n    scattering_emin = energies[0]\n    scattering_emax = energies[energies.shape[0] - 1]\n    estep = energies[1] - energies[0]\n    if emin < scattering_emin:\n        # fetch missing interval below and pad with linear ramp\n        ebelow = scattering_emin - emin\n        numsteps_below = int(np.ceil(ebelow / estep))\n        emin = scattering_emin - numsteps_below * estep\n        energies = np.pad(energies, (numsteps_below, 0),\n                          'linear_ramp',\n                          end_values=(emin, 0))\n        # now pad scattering arrays with endvalues below\n        scattering_inv = np.pad(scattering_inv,\n                                ((0, 0), (0, 0), (numsteps_below, 0), (0, 0)),\n                                'edge')\n        scattering_total_inv = np.pad(scattering_total_inv,\n                                      ((0, 0), (0, 0), (numsteps_below, 0)),\n                                      'edge')\n    if emax > scattering_emax:\n        # fetch missing interval above and pad with linear\n        # tramp\n        eabove = emax - scattering_emax\n        numsteps_above = int(np.ceil(eabove / estep))\n        energies = np.pad(energies, (0, numsteps_above),\n                          'linear_ramp',\n                          end_values=(0, emax))\n        # now pad scattering arrays with endvalues above\n        scattering_inv = np.pad(scattering_inv,\n                                ((0, 0), (0, 0), (0, numsteps_above), (0, 0)),\n                                'edge')\n        scattering_total_inv = np.pad(scattering_total_inv,\n                                      ((0, 0), (0, 0), (0, numsteps_above)),\n                                      'edge')\n    tr.scattering_inv = scattering_inv\n    tr.scattering_total_inv = scattering_total_inv\n    tr.scattering_energies = energies\n\n\ndef check_scattering(tr):\n    \"\"\"\n    Checks the scattering arrays.\n\n    Also that they are dimensionalized to the energy values stored in the current `Bandstructure()`\n    object.\n\n    Parameters\n    ----------\n    tr : object\n        A `Transport()` object.\n\n    Returns\n    -------\n    None\n\n    \"\"\"\n\n    # set logger\n    logger = logging.getLogger(sys._getframe().f_code.co_name)  # pylint: disable=protected-access\n    logger.debug(\"Running check_scattering.\")\n\n    try:\n        tr.scattering_total_inv\n    except AttributeError:\n        logger.error(\"Could not find 'scattering_total_inv' in the \"\n                     \"current 'Transport()' object. Exiting.\")\n        sys.exit(1)\n\n    if not tr.scattering_total_inv.shape[1] == tr.bs.energies.shape[0]:\n        logger.error(\"The array 'scattering_total_inv' does not contain \"\n                     \"the same number of bands as present in the current \"\n                     \"band structure. Exiting.\")\n        sys.exit(1)\n    if not tr.scattering_total_inv.shape[2] == tr.bs.energies.shape[1]:\n        logger.error(\"The array 'scattering_total_inv' does not contain \"\n                     \"the same number of kpoints (energies) as the current \"\n                     \"band structure. Exiting.\")\n        sys.exit(1)\n", "meta": {"hexsha": "7e0faed0a0f89414af0e3f5199d6d51fa6147fe4", "size": 61624, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/t4me/scattering.py", "max_stars_repo_name": "knirajiitb/t4me_AMMCR", "max_stars_repo_head_hexsha": "f8b6696493a4f1d964404814105ced241967adbb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-12-15T06:04:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-26T05:16:15.000Z", "max_issues_repo_path": "src/t4me/scattering.py", "max_issues_repo_name": "knirajiitb/t4me_AMMCR", "max_issues_repo_head_hexsha": "f8b6696493a4f1d964404814105ced241967adbb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-02-19T08:06:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-25T16:58:33.000Z", "max_forks_repo_path": "src/t4me/scattering.py", "max_forks_repo_name": "knirajiitb/t4me_AMMCR", "max_forks_repo_head_hexsha": "f8b6696493a4f1d964404814105ced241967adbb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-11-16T23:48:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-03T10:47:02.000Z", "avg_line_length": 44.1116678597, "max_line_length": 126, "alphanum_fraction": 0.5320167467, "include": true, "reason": "import numpy,import scipy", "num_tokens": 13870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.27512971193602087, "lm_q1q2_score": 0.15783597498632418}}
{"text": "\"\"\" Utilities for isgm\n Best to keep these separate from the Class modules\n\"\"\"\nfrom __future__ import print_function, absolute_import, division, unicode_literals\n\n# Python 2 & 3 compatibility\ntry:\n    basestring\nexcept NameError:\n    basestring = str\n\nimport pdb\nimport numpy as np\nimport warnings\nimport json\n\nfrom astropy.table import Table\nfrom astropy import constants as const\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\n\nfrom linetools import utils as ltu\nfrom linetools.analysis.absline import linear_clm\nfrom linetools.isgm.abssystem import GenericAbsSystem\nfrom linetools.isgm.abscomponent import AbsComponent\nfrom linetools.spectralline import AbsLine\nfrom linetools.lists.linelist import LineList\n\nckms = const.c.to('km/s').value\n\ndef abssys_from_json(filename):\n    \"\"\"\n    Parameters\n    ----------\n    filename\n\n    Returns\n    -------\n    abs_sys : AbsSystem\n\n    \"\"\"\n    # Load JSON file to determine type\n    adict = ltu.loadjson(filename)\n    if 'class' in adict.keys():\n        if adict['class'] == 'MgIISystem':\n            from pyigm.abssys.igmsys import MgIISystem\n            abs_sys = MgIISystem.from_dict(adict)\n        else:\n            warnings.warn(\"Unknown or uncoded class: {:s}.\\nMaking a Generic one\".format(adict['class']))\n            abs_sys = GenericAbsSystem.from_dict(adict)\n    else:\n        abs_sys = GenericAbsSystem.from_dict(adict)\n\n    # Return\n    return abs_sys\n\n\ndef read_joebvp_to_components(filename, coord, llist=None, specfile=None, chk_vel=False):\n    \"\"\" Generate a list of AbsComponent objects from a JoeB VP output file\n\n    Parameters\n    ----------\n    filename : str\n      joeB VP filename\n    coord : SkyCoord\n      QSO sightline\n    llist : LineList, optional\n      Used to construct AbsLine objects\n    specfile : str, optional\n    chk_vel : bool, optional\n      Demand that the velocities of a given ion all be the same\n\n    Returns\n    -------\n    comps : list\n      list of AbsComponent objects\n    \"\"\"\n    # init\n    if llist is None:\n        llist = LineList('ISM')\n    comps = []\n    # Read\n    vp_data = Table.read(filename, format='ascii')\n\n    # Subset by zsys + trans\n    lbls = []\n    for izsys, itrans in zip(vp_data['zsys'], vp_data['trans']):\n        lbls.append('{:.6f}_{:s}'.format(izsys, itrans))\n    lbls = np.array(lbls)\n    ulbls = np.unique(lbls)\n\n    # Subset by nflag; Build components\n    for lbl in ulbls:\n        mt_lines = np.where(lbls == lbl)[0]\n        if chk_vel:\n            if len(np.unique(vp_data['vel'][mt_lines])) != 1:\n                pdb.set_trace()\n        z_fit = ltu.z_from_dv(vp_data['vel'][mt_lines[0]]*u.km/u.s, vp_data['zsys'][mt_lines[0]])\n        # Loop on abs lines\n        alines = []\n        for idx in mt_lines:\n            zlim = [vp_data['zsys'][idx] +\n                    vp_data[vkey][idx] * (1 + vp_data['zsys'][idx]) / ckms\n                    for vkey in ['vlim1', 'vlim2']]\n            absline = AbsLine(vp_data['restwave'][idx] * u.AA, z=z_fit,\n                              zlim=zlim, linelist=llist)\n            # Add measurements [JB -- Want to capture anything else??]\n            absline.attrib['coord'] = coord\n            absline.attrib['flag_N'] = 1\n            absline.attrib['logN'] = vp_data['col'][idx]\n            absline.attrib['sig_logN'] = vp_data['sigcol'][idx]\n            absline.attrib['b'] = vp_data['bval'][idx] * u.km/u.s\n            absline.attrib['sig_b'] = vp_data['sigbval'][idx] * u.km/u.s\n            absline.attrib['z'] = z_fit\n            absline.attrib['sig_z'] = ltu.dz_from_dv(vp_data['sigvel'][idx]*u.km/u.s, vp_data['z_comp'][idx])\n            if specfile is None:\n                absline.attrib['specfile'] = vp_data['specfile'][idx]\n            else:\n                absline.attrib['specfile'] = specfile\n            # Fill N, sig_N\n            _, _, = linear_clm(absline.attrib)\n            alines.append(absline)\n\n        # AbsComponent\n        stars = '*' * alines[0].ion_name.count('*')\n        if 'comment' in vp_data.keys():\n            comment = vp_data['comment'][mt_lines[0]]\n        else:\n            comment = ''\n        if 'rely' in vp_data.keys():\n            reliability = vp_data['rely'][mt_lines[0]]\n        else:\n            reliability = 'none'\n        abscomp = AbsComponent.from_abslines(alines, stars=stars, comment=comment, reliability=reliability)\n\n        # Add measurements [JB -- Want to capture anything else??]\n        abscomp.attrib = alines[0].attrib.copy()\n        # Remove undesired keys\n        for key in ['EW', 'sig_EW', 'flag_EW', 'N', 'sig_N']:\n            abscomp.attrib.pop(key)\n        # And more required\n        for key in ['flag_N', 'logN', 'sig_logN']:\n            setattr(abscomp, key, abscomp.attrib[key])\n        # Errors must be in first line!\n        assert abscomp.sig_logN > 0., \"AbsComponent has sig_logN=0 {}\".format(abscomp)\n\n        comps.append(abscomp)\n    # Finish\n    return comps\n\n\ndef write_joebvp_from_components(comp_list, specfile, outfile,**kwargs):\n    \"\"\" From a given component list, it produces an\n    input file for JOEBVP (Voigt profile fitter).\n\n    Parameters\n    ----------\n    comp_list : list of AbsComponent\n        Input list of components to group\n    specfile : str\n        Name of the spectrum file associated to the components\n        in comp_list\n    outfile : str\n        Name of the output file\n\n    \"\"\"\n    # Open new file to write out\n    f = open(outfile, 'w')\n\n    # Print header\n    s = 'specfile|restwave|zsys|col|bval|vel|nflag|bflag|vflag|vlim1|vlim2|wobs1|wobs2|z_comp|trans|rely|comment\\n'\n    f.write(s)\n\n    # Components\n    for ii, comp in enumerate(comp_list):\n        flags = (ii+2,ii+2,ii+2)\n        try:\n            b_val = comp.attrib['b']\n        except KeyError:\n            b_val = 10*u.km/u.s\n        s = comp.repr_joebvp(specfile, flags=flags, b_default=b_val,**kwargs)  # still, b values from abslines take precedence if they exist\n        f.write(s)\n    f.close()\n", "meta": {"hexsha": "27e267adb527d4dc88bdd2ebd284847306387df3", "size": 5962, "ext": "py", "lang": "Python", "max_stars_repo_path": "linetools/isgm/io.py", "max_stars_repo_name": "jchowk/linetools", "max_stars_repo_head_hexsha": "5a0eafa96ab854c52c070ce756033c0499414dde", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2015-07-09T02:24:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T15:13:31.000Z", "max_issues_repo_path": "linetools/isgm/io.py", "max_issues_repo_name": "jchowk/linetools", "max_issues_repo_head_hexsha": "5a0eafa96ab854c52c070ce756033c0499414dde", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 491, "max_issues_repo_issues_event_min_datetime": "2015-06-21T20:01:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-11T03:29:19.000Z", "max_forks_repo_path": "linetools/isgm/io.py", "max_forks_repo_name": "jchowk/linetools", "max_forks_repo_head_hexsha": "5a0eafa96ab854c52c070ce756033c0499414dde", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2015-05-25T00:18:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-30T06:53:14.000Z", "avg_line_length": 32.402173913, "max_line_length": 140, "alphanum_fraction": 0.6076819859, "include": true, "reason": "import numpy,from astropy", "num_tokens": 1591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.31069438959712015, "lm_q1q2_score": 0.15777429720240305}}
{"text": "# -*- coding: utf-8 -*-\n\nfrom . import types\nfrom . import elementbase\nfrom ..utils import instance\n\nimport numpy as np\n\n\nclass MultiElementBase(elementbase.ElementBase):\n    # TODO: refactor most of Mixture and Compound\n\n    @property\n    def _repr(self):\n        return self.name\n\n    @property\n    def nparts(self):\n        return len(self.parts)\n\n    def setfraction(self, parts, values, fractype):\n        if instance.isstring(parts):\n            parts = [parts]\n        values = instance.asarray(values)\n\n        for p in parts:\n            if p not in self.parts:\n                raise RuntimeError(\"{} not in {}\".format(p, self))\n\n        # rebalance others\n        w = self.fractions(fractype)\n        w2 = dict(w)\n        for p in parts:\n            w2.pop(p)\n\n        # update others\n        if w2:\n            v2 = np.asarray(w2.values())\n            v2 *= (1 - values.sum()) / v2.sum()\n            w.update((k, v) for k, v in zip(w2.keys(), v2))\n\n        # update fractions\n        w.update(zip(parts, values))\n        self.change_fractions(w, fractype)\n\n    def setmassfraction(self, comp, value):\n        self.setfraction(comp, value, types.fraction.mass)\n\n    def setmolefraction(self, comp, value):\n        self.setfraction(comp, value, types.fraction.mole)\n\n    def setvolumefraction(self, comp, value):\n        self.setfraction(comp, value, types.fraction.volume)\n\n    @classmethod\n    def _cs_scattering(cls, method):\n        return (\n            method == \"scattering_cross_section\"\n            or method == \"compton_cross_section\"\n            or method == \"rayleigh_cross_section\"\n            or method == \"diff_compton_cross_section\"\n            or method == \"diff_rayleigh_cross_section\"\n        )\n\n    @classmethod\n    def _cs_dict(cls, method):\n        return (\n            method == \"fluorescence_cross_section_lines\"\n            or method == \"diff_fluorescence_cross_section\"\n        )\n\n    @classmethod\n    def _cs_lazy(cls, method):\n        return (\n            method == \"diff_compton_cross_section\"\n            or method == \"diff_rayleigh_cross_section\"\n        )\n\n    def mass_att_coeff(self, E, fine=False, decomposed=False, **kwargs):\n        \"\"\"Mass attenuation coefficient (cm^2/g, E in keV). Use for transmission XAS.\"\"\"\n        return self._crosssection(\n            \"mass_att_coeff\", E, fine=fine, decomposed=decomposed, **kwargs\n        )\n\n    def mass_abs_coeff(self, E, fine=False, decomposed=False, **kwargs):\n        \"\"\"Mass absorption coefficient (cm^2/g, E in keV).\"\"\"\n        return self._crosssection(\n            \"mass_abs_coeff\", E, fine=fine, decomposed=decomposed, **kwargs\n        )\n\n    def partial_mass_abs_coeff(self, E, fine=False, decomposed=False, **kwargs):\n        \"\"\"Mass absorption coefficient for the selected shells and lines (cm^2/g, E in keV).\"\"\"\n        return self._crosssection(\n            \"partial_mass_abs_coeff\", E, fine=fine, decomposed=decomposed, **kwargs\n        )\n\n    def scattering_cross_section(self, E, fine=False, decomposed=False, **kwargs):\n        \"\"\"Scattering cross section (cm^2/g, E in keV).\"\"\"\n        return self._crosssection(\n            \"scattering_cross_section\", E, fine=fine, decomposed=decomposed, **kwargs\n        )\n\n    def compton_cross_section(self, E, fine=False, decomposed=False, **kwargs):\n        \"\"\"Compton cross section (cm^2/g, E in keV).\"\"\"\n        return self._crosssection(\n            \"compton_cross_section\", E, fine=fine, decomposed=decomposed, **kwargs\n        )\n\n    def rayleigh_cross_section(self, E, fine=False, decomposed=False, **kwargs):\n        \"\"\"Rayleigh cross section (cm^2/g, E in keV).\"\"\"\n        return self._crosssection(\n            \"rayleigh_cross_section\", E, fine=fine, decomposed=decomposed, **kwargs\n        )\n\n    def fluorescence_cross_section(self, E, fine=False, decomposed=False, **kwargs):\n        \"\"\"XRF cross section (cm^2/g, E in keV). Use for fluorescence XAS.\"\"\"\n        return self._crosssection(\n            \"fluorescence_cross_section\", E, fine=fine, decomposed=decomposed, **kwargs\n        )\n\n    def fluorescence_cross_section_lines(\n        self, E, fine=False, decomposed=False, **kwargs\n    ):\n        \"\"\"XRF cross section (cm^2/g, E in keV). Use for XRF.\"\"\"\n        return self._crosssection(\n            \"fluorescence_cross_section_lines\",\n            E,\n            fine=fine,\n            decomposed=decomposed,\n            **kwargs\n        )\n\n    def diff_fluorescence_cross_section(\n        self, E, fine=False, decomposed=False, **kwargs\n    ):\n        \"\"\"Differential XRF cross section (cm^2/g/srad, E in keV). Use for XRF.\"\"\"\n        return self._crosssection(\n            \"diff_fluorescence_cross_section\",\n            E,\n            fine=fine,\n            decomposed=decomposed,\n            **kwargs\n        )\n\n    def diff_rayleigh_cross_section(self, E, fine=False, decomposed=False, **kwargs):\n        \"\"\"Differential Rayleigh cross section (cm^2/g/srad, E in keV). Use for XRF.\"\"\"\n        return self._crosssection(\n            \"diff_rayleigh_cross_section\", E, fine=fine, decomposed=decomposed, **kwargs\n        )\n\n    def diff_compton_cross_section(self, E, fine=False, decomposed=False, **kwargs):\n        \"\"\"Differential Compton cross section (cm^2/g/srad, E in keV). Use for XRF.\"\"\"\n        return self._crosssection(\n            \"diff_compton_cross_section\", E, fine=fine, decomposed=decomposed, **kwargs\n        )\n\n    @classmethod\n    def cs_type(cls, cs):\n        # 0. cs = [...]                -> pure element cs\n        # 1. cs = {'w':0.1,'cs':[...]} -> element w+cs\n        # 2. cs = {'A':{},'B':{}}      -> compound or mixture\n        if isinstance(cs, dict):\n            if \"cs\" in cs:\n                if isinstance(cs[\"cs\"], dict):\n                    return 2\n                else:\n                    return 1\n            else:\n                return 2\n        else:\n            return 0\n\n    @classmethod\n    def cs_collapse(cls, cs):\n        t = cls.cs_type(cs)\n        if t == 0:\n            return cs\n        elif t == 1:\n            return cs[\"w\"] * cs[\"cs\"]\n        else:\n            return sum(cls.cs_collapse(c) for c in cs.values())\n\n    @classmethod\n    def csdict_parse(cls, cs):\n        t = cls.cs_type(cs)\n        if t == 0:\n            return np.array([1]), [cs]\n        elif t == 1:\n            return np.array([cs[\"w\"]]), [cs[\"cs\"]]\n        else:\n            w = np.array([c[\"w\"] for c in cs.values()])\n            cs = [cls.cs_collapse(c[\"cs\"]) for c in cs.values()]\n            return w, cs\n\n    @classmethod\n    def csdict_parse_elements(cls, csin, csout=None, w=1, k=None):\n        if csout is None:\n            csout = {}\n        t = cls.cs_type(csin)\n        if t == 0:\n            csout[k] = csout.get(k, 0) + w * cs\n        elif t == 1:\n            csout[k] = csout.get(k, 0) + w * cs[\"w\"] * cs[\"cs\"]\n        else:\n            for k, c in csin.items():\n                cls.csdict_parse_elements(c[\"cs\"], csout=csout, w=w * c[\"w\"], k=k)\n        return csout\n", "meta": {"hexsha": "d9d0a324fc25183ce6c66e502f775f7b68bb04a8", "size": 6972, "ext": "py", "lang": "Python", "max_stars_repo_path": "spectrocrunch/materials/multielementbase.py", "max_stars_repo_name": "woutdenolf/spectrocrunch", "max_stars_repo_head_hexsha": "fde4b6e0f462f464ce7af6a942b355d3d8f39f77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-04-16T15:51:36.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-16T11:21:05.000Z", "max_issues_repo_path": "spectrocrunch/materials/multielementbase.py", "max_issues_repo_name": "woutdenolf/spectrocrunch", "max_issues_repo_head_hexsha": "fde4b6e0f462f464ce7af6a942b355d3d8f39f77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spectrocrunch/materials/multielementbase.py", "max_forks_repo_name": "woutdenolf/spectrocrunch", "max_forks_repo_head_hexsha": "fde4b6e0f462f464ce7af6a942b355d3d8f39f77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5192307692, "max_line_length": 95, "alphanum_fraction": 0.5678427998, "include": true, "reason": "import numpy", "num_tokens": 1753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.2658804789168741, "lm_q1q2_score": 0.15757847943382347}}
{"text": "'''\nModule for computing details of line intensity mapping observations\n'''\n\nimport numpy as np\nimport astropy.units as u\nimport astropy.constants as cu\nfrom scipy.interpolate import interp1d\nfrom scipy.special import legendre\n\nfrom source.line_model import LineModel\nfrom source.tools._utils import cached_obs_property,cached_vid_property,get_default_params\nfrom source.tools._utils import ulogspace, ulinspace,check_params,log_interp1d\n\nclass LineObs(LineModel):\n    '''\n    An object containing a line intensity model as well as tools to compute\n    aspects of an experimental observation of said model. This version is used\n    for low-frequency instruments which measure intensity in brightness\n    temperature units.\n    \n    The base class of LineObs is lim.LineModel, so it has all of the\n    attributes of a LineModel, including the caching and update functionality.\n    Keep in mind that cached_properties will not update if inputs are changed\n    using anything but the update() method.\n    \n    In all cases, \"pixel\" refers to a two-dimensional area and \"voxel\" refers\n    to a three-dimensional volume.\n    \n    Default input parameter values are for the COMAP1 CO intensity mapping\n    instrument.\n    \n    INPUT PARAMETERS:\n    Tsys:           Instrument system temperature (Default = 40 K)\n    \n    Nfeeds:         Number of feeds (Default = 19)\n    \n    beam_FWHM:      Beam full width at half maximum (Default = 4.1\")\n    \n    Delta_nu:      Total frequency range covered by instrument (Default = 8 GHz)\n    \n    dnu:            Width of a single frequency channel (Default = 15.6 MHz)\n    \n    tobs:           Observing time on a single field (Default = 6000 hr)\n    \n    Omega_field:    Solid angle covered by a single field\n                    (Default = 2.25 deg^2)    \n    \n    Nfield:         Number of fields observed (Default = 1)\n    \n    N_FG_par:       Multiplicative factor in the volume window for kmin_par\n                    to account for foregrounds. Default = 1, No foregrounds\n                    (only volume effects)\n                    \n    N_FG_perp:      Multiplicative factor in the volume window for kmin_perp\n                    to account for foregrounds. Default = 1, No foregrounds\n                    (only volume effects)\n                    \n    do_FG_wedge:    Apply foreground wedge removal. Default = False\n    \n    a_FG:           Constant superhorizon buffer for foregrounds. Default = 0\n    \n    b_FG:           Foreground parameter accounting for antenna chromaticity. Default = 0 \n    \n    **line_kwargs:  Input parameters of LineModel()\n    \n    DOCTESTS:\n    >>> m = LineObs()\n    >>> m.Pk[0:2]/1e5\n    <Quantity [ 1.08..., 1.09...] Mpc3 uK2>\n    >>> m.Nvox\n    <Quantity 1387152.0>\n    >>> m.sk[0:2]/1e5\n    <Quantity [ 5.16..., 4.67...] Mpc3 uK2>\n    >>> m.SNR\n    <Quantity 17.8...>\n    >>> m.PofN[0:2]\n    <Quantity [ 0.305..., 0.181...]>\n    >>> m.Bi[3:5]/1000\n    array([ 3.97...,  9.54...])\n    '''\n    \n    def __init__(self, \n                 Tsys_NEFD=40*u.K,\n                 Nfeeds=19,\n                 beam_FWHM=4.1*u.arcmin,\n                 Delta_nu=8*u.GHz,\n                 dnu=15.6*u.MHz,\n                 tobs=6000*u.hr, \n                 Omega_field=2.25*u.deg**2,\n                 Nfield=1,\n                 N_FG_par = 1,\n                 N_FG_perp = 1,\n                 do_FG_wedge = False,\n                 a_FG = 0.*u.Mpc**-1,\n                 b_FG = 0.,\n                 **line_kwargs):\n                    \n        # Initiate LineModel() parameters\n        LineModel.__init__(self,**line_kwargs)\n        \n        self._update_cosmo_list = self._update_cosmo_list\n        \n        self._obs_params = locals()\n        self._obs_params.pop('self')\n        self._obs_params.pop('line_kwargs')\n        self._default_obs_params = get_default_params(LineObs.__init__)\n        check_params(self._obs_params,self._default_obs_params)\n        \n        # Set instrument parameters\n        for key in self._obs_params:\n            setattr(self,key,self._obs_params[key])\n        \n        # Combine lim_params with obs_params\n        self._input_params.update(self._obs_params)\n        self._default_params.update(self._default_obs_params)\n        \n    ##############\n    # Field Size #\n    ##############\n    \n    @cached_obs_property\n    def Nch(self):\n        '''\n        Number of frequency channels, rounded if dnu does not divide evenly\n        into Delta_nu\n        '''\n        return np.round((self.Delta_nu/self.dnu).decompose())\n        \n        \n    @cached_obs_property\n    def beam_width(self):\n        '''\n        Beam width defined as 1-sigma width of Gaussian beam profile\n        '''\n        return self.beam_FWHM*0.4247\n        \n        \n    @cached_obs_property\n    def Nside(self):\n        '''\n        Number of pixels on a side of a map.  Pixel size is assumed to be one\n        beam FWHM on a side.  Rounded if FWHM does not divide evenly into\n        sqrt(Omega_field)\n        '''\n        theta_side = np.sqrt(self.Omega_field)\n        return np.round((theta_side/self.beam_width).decompose())\n    \n    \n    @cached_obs_property\n    def Npix(self):\n        '''\n        Number of pixels in a map\n        '''\n        return self.Nside**2\n        \n        \n    @cached_obs_property\n    def Nvox(self):\n        '''\n        Number of voxels in a map\n        '''\n        return self.Npix*self.Nch\n        \n        \n    @cached_obs_property\n    def fsky(self):\n        '''\n        Fraction of sky covered by a field\n        '''\n        return (self.Omega_field/(4*np.pi*u.rad**2)).decompose()\n    \n    \n    @cached_obs_property\n    def r0(self):\n        '''\n        Comoving distance to central redshift of field\n        '''\n        if self.cosmo_code == 'camb':\n            return self.cosmo.comoving_radial_distance(self.z)*u.Mpc\n        else:\n            return self.cosmo.angular_distance(self.z)*(1.+self.z)*u.Mpc\n    \n    \n    @cached_obs_property\n    def Sfield(self):\n        '''\n        Area of single field in the sky in Mpc**2\n        '''\n        return (self.r0**2*(self.Omega_field/(1.*u.rad**2))).to(u.Mpc**2)\n        \n        \n    @cached_obs_property\n    def Lfield(self):\n        '''\n        Depth of a single field\n        '''\n        z_min = (self.nu/(self.nuObs+self.Delta_nu/2.)-1).value\n        z_max = (self.nu/(self.nuObs-self.Delta_nu/2.)-1).value\n        if self.cosmo_code == 'camb':\n            dr_los = (self.cosmo.comoving_radial_distance(z_max)-\n                      self.cosmo.comoving_radial_distance(z_min))\n        else:\n            dr_los = (self.cosmo.angular_distance(z_max)*(1.+z_max)-\n                      self.cosmo.angular_distance(z_min)*(1.+z_min))\n        return dr_los*u.Mpc\n                \n                \n    @cached_obs_property    \n    def Vfield(self):\n        '''\n        Comoving volume of a single field\n        '''\n        return self.Sfield*self.Lfield\n    \n    \n    @cached_obs_property            \n    def Vvox(self):\n        '''\n        Comoving volume of a single voxel\n        '''\n        return self.Vfield/self.Nvox\n        \n    \n    ##########################\n    # Instrument noise power #\n    ##########################\n            \n    @cached_obs_property\n    def tpix(self):\n        '''\n        Time spent observing each pixel with a single detector\n        '''\n        return self.tobs/self.Npix\n    \n    \n    @cached_obs_property\n    def sigma_N(self):\n        '''\n        Instrumental noise per voxel. Defined slightly differently depending\n        on doJysr. This is equivalent to sigma_pix if doJysr\n        '''\n        if self.do_Jysr:\n            return ((self.Tsys_NEFD/self.beam_width**2)\n                    .to(u.Jy*u.s**(1./2)/u.sr))\n        else:\n            return ((self.Tsys_NEFD/np.sqrt(self.Nfeeds*self.dnu*self.tpix))\n                    .to(u.uK))\n    \n    \n    @cached_obs_property    \n    def Pnoise(self):\n        '''\n        Noise power spectrum amplitude\n        '''\n        if self.do_Jysr:\n            return (self.sigma_N**2*self.Vvox/(self.tpix*self.Nfeeds)).to(u.Mpc**3*u.Jy**2/u.sr**2)\n        else:\n            return self.sigma_N**2*self.Vvox\n            \n        \n    @cached_obs_property\n    def sigma_par(self):\n        '''\n        High-resolution cutoff for line-of-sight modes\n        '''\n        return (cu.c*self.dnu*(1+self.z)/(self.H*self.nuObs)).to(u.Mpc)\n    \n    \n    @cached_obs_property\n    def sigma_perp(self):\n        '''\n        High-resolution cutoff for transverse modes\n        '''\n        return (self.r0*(self.beam_width/(1*u.rad))).to(u.Mpc)\n                \n                \n    @cached_obs_property\n    def kmax_los(self):\n        '''\n        Maximum k in line of sight direction\n        '''\n        return 2.*np.pi/self.sigma_par\n    \n    \n    @cached_obs_property\n    def kmax_sky(self):\n        '''\n        Maximum k in the transverse direction\n        '''\n        return 2.*np.pi/self.sigma_perp\n        \n        \n    @cached_obs_property\n    def kmin_los(self):\n        '''\n        Minimum k in the line of sight direction\n        '''\n        return 2*np.pi/self.Lfield\n        \n        \n    @cached_obs_property\n    def kmin_sky(self):\n        '''\n        Minimum k in the transverse direction\n        '''\n        return 2*np.pi/self.Sfield**0.5\n    \n    \n    @cached_obs_property\n    def kmin_field(self):\n        '''\n        Minimum k accessible in a single field, set by the maximum side length\n        '''\n        return min([self.kmin_los,self.kmin_sky])\n        \n        \n    @cached_obs_property\n    def kmax_field(self):\n        '''\n        Maximum k accesible in a given survey, set by the best resolution\n        '''\n        return max([self.kmax_los,self.kmax_sky])\n        \n        \n    @cached_obs_property\n    def Wkmax_par(self):\n        '''\n        Resolution cutoff in power spectrum in the los direction\n        '''\n        exparg = -((self.k_par*self.sigma_par)**2).decompose()\n        return np.exp(exparg)\n        \n        \n    @cached_obs_property\n    def Wkmax_perp(self):\n        '''\n        Resolution cutoff in power spectrum in the transverse direction\n        '''\n        exparg = -((self.k_perp*self.sigma_perp)**2).decompose()\n        return np.exp(exparg)\n        \n        \n    @cached_obs_property\n    def Wkmax(self):\n        '''\n        Resolution cutoff in power spectrum\n        '''\n        return self.Wkmax_par*self.Wkmax_perp\n        \n    @cached_obs_property\n    def Wkmin_par(self):\n        '''\n        Precision cutoff in power spectrum due to volume observed in los direction\n        '''\n        exparg = -((self.k_par/(self.N_FG_par*self.kmin_los))**2).decompose()\n        return 1.-np.exp(exparg)\n        \n        \n    @cached_obs_property\n    def Wkmin_perp(self):\n        '''\n        Precision cutoff in power spectrum due to volume observed in transverse direction\n        '''\n        exparg = -((self.k_perp/(self.N_FG_perp*self.kmin_sky))**2).decompose()\n        return 1.-np.exp(exparg)\n        \n        \n    @cached_obs_property\n    def Wkmin(self):\n        '''\n        Precision cutoff in power spectrum due to volume observed\n        '''\n        return self.Wkmin_par*self.Wkmin_perp\n        \n    \n    @cached_obs_property\n    def Wk_FGwedge(self):\n        '''\n        Applies foreground wedge removal\n        '''\n        W = np.ones(self.ki_grid.shape)\n        if self.do_FG_wedge:\n            #k_par_min = a + b*k_perp\n            kpar_min_wedge = self.a_FG.to(self.k.unit) + self.b_FG*np.abs(self.k_perp)\n            ind = np.where(np.abs(self.k_par)<kpar_min_wedge)\n            W[ind] = 0\n            return W\n        else:\n            return W\n        \n        \n    @cached_obs_property\n    def Wk(self):\n        '''\n        Resolution cutoff in power spectrum\n        '''\n        return self.Wkmin*self.Wkmax*self.Wk_FGwedge\n\n\n    @cached_obs_property\n    def Nmodes(self):\n        '''\n        Number of modes between k and k+dk.        \n        Multiply by dmu/2 to get the number of modes between k and k+dk and mu and mu+dmu\n        '''\n        return self.ki_grid**2*self.dk*self.Vfield*self.Nfield/4./np.pi**2.\n        \n        \n    @cached_obs_property\n    def sk_CV(self):\n        '''\n        Error at k and mu due to sample variance\n        '''\n        return self.Pk/np.sqrt(self.Nmodes*self.dmu[0])\n        \n        \n    @cached_obs_property\n    def covmat_CV_00(self):\n        '''\n        00 term of the covariance matrix from CV\n        '''\n        return 0.5*np.trapz(self.Pk**2/self.Nmodes,self.mu,axis=0)\n        \n        \n    @cached_obs_property\n    def covmat_CV_02(self):\n        '''\n        02 term of the covariance matrix from CV\n        (equal to the 20)\n        '''\n        L2 = legendre(2)(self.mui_grid)\n        return 5./2.*np.trapz(self.Pk**2*L2/self.Nmodes,self.mu,axis=0)\n        \n        \n    @cached_obs_property\n    def covmat_CV_04(self):\n        '''\n        04 term of the covariance matrix from CV\n        (equal to the 40)\n        '''\n        L4 = legendre(4)(self.mui_grid)\n        return 9./2.*np.trapz(self.Pk**2*L4/self.Nmodes,self.mu,axis=0)\n        \n        \n    @cached_obs_property\n    def covmat_CV_22(self):\n        '''\n        22 term of the covariance matrix from CV\n        '''\n        L2 = legendre(2)(self.mui_grid)\n        return 25./2.*np.trapz(self.Pk**2*L2*L2/self.Nmodes,self.mu,axis=0)\n        \n        \n    @cached_obs_property\n    def covmat_CV_24(self):\n        '''\n        24 term of the covariance matrix from CV\n        (equal to the 42)\n        '''\n        L2 = legendre(2)(self.mui_grid)\n        L4 = legendre(4)(self.mui_grid)\n        return 45./2.*np.trapz(self.Pk**2*L2*L4/self.Nmodes,self.mu,axis=0)\n        \n        \n    @cached_obs_property\n    def covmat_CV_44(self):\n        '''\n        44 term of the covariance matrix from CV\n        '''\n        L4 = legendre(4)(self.mui_grid)\n        return 81./2.*np.trapz(self.Pk**2*L4*L4/self.Nmodes,self.mu,axis=0)\n        \n        \n    def covmat_CV_l1l2(self,l1,l2):\n        '''\n        l1l2 term of the covariance matrix from CV\n        '''\n        if l1 == 0 and l2 == 0:\n            return self.covmat_CV_00\n        elif l1 == 0 and l2 == 2:\n            return self.covmat_CV_02\n        elif l1 == 0 and l2 == 4:\n            return self.covmat_CV_04\n        elif l1 == 2 and l2 == 2:\n            return self.covmat_CV_22\n        elif l1 == 2 and l2 == 4:\n            return self.covmat_CV_24\n        elif l1 == 4 and l2 == 4:\n            return self.covmat_CV_44\n        else:\n            Ll1 = legendre(l1)(self.mui_grid)\n            Ll2 = legendre(l2)(self.mui_grid)\n            return (2.*l1+1.)*(2.*l2+1.)/2.*np.trapz(self.Pk**2*L1*L2/self.Nmodes,self.mu,axis=0)\n        \n        \n    @cached_obs_property\n    def sk_N(self):\n        '''\n        Error at k and mu due to instrumental noise\n        '''\n        return self.Pnoise/(np.sqrt(self.Nmodes*self.dmu[0]/2.))\n            \n            \n    @cached_obs_property\n    def covmat_N_00(self):\n        '''\n        00 term of the covariance matrix from instrumental noise\n        '''\n        return 1./2.*np.trapz(self.Pnoise**2./(self.Nmodes),self.mu,axis=0)\n        \n        \n    @cached_obs_property\n    def covmat_N_02(self):\n        '''\n        02 term of the covariance matrix from instrumental noise\n        (equal to the 02)        \n        '''\n        L2 = legendre(2)(self.mui_grid)\n        return 5./2.*np.trapz(self.Pnoise**2.*L2/(self.Nmodes),self.mu,axis=0)\n\n\n    @cached_obs_property\n    def covmat_N_04(self):\n        '''\n        04 term of the covariance matrix from instrumental noise\n        (equal to the 04)        \n        '''\n        L4 = legendre(4)(self.mui_grid)\n        return 9./2.*np.trapz(self.Pnoise**2.*L4/(self.Nmodes),self.mu,axis=0)\n        \n        \n    @cached_obs_property\n    def covmat_N_22(self):\n        '''\n        22 term of the covariance matrix from instrumental noise\n        '''\n        L2 = legendre(2)(self.mui_grid)\n        return 25./2.*np.trapz(self.Pnoise**2.*L2*L2/(self.Nmodes),self.mu,axis=0)\n\n\n    @cached_obs_property\n    def covmat_N_24(self):\n        '''\n        24 term of the covariance matrix from instrumental noise\n        (equal to the 42)\n        '''\n        L2 = legendre(2)(self.mui_grid)\n        L4 = legendre(4)(self.mui_grid)\n        return 45./2.*np.trapz(self.Pnoise**2.*L2*L4/(self.Nmodes),self.mu,axis=0)\n        \n        \n    @cached_obs_property\n    def covmat_N_44(self):\n        '''\n        44 term of the covariance matrix from instrumental noise\n        '''\n        L4 = legendre(4)(self.mui_grid)\n        return 81./2.*np.trapz(self.Pnoise**2.*L4*L4/(self.Nmodes),self.mu,axis=0)\n        \n        \n    def covmat_N_l1l2(self,l1,l2):\n        '''\n        l1l2 term of the covariance matrix from N\n        '''\n        if l1 == 0 and l2 == 0:\n            return self.covmat_N_00\n        elif l1 == 0 and l2 == 2:\n            return self.covmat_N_02\n        elif l1 == 0 and l2 == 4:\n            return self.covmat_N_04\n        elif l1 == 2 and l2 == 2:\n            return self.covmat_N_22\n        elif l1 == 2 and l2 == 4:\n            return self.covmat_N_24\n        elif l1 == 4 and l2 == 4:\n            return self.covmat_N_44\n        else:\n            Ll1 = legendre(l1)(self.mui_grid)\n            Ll2 = legendre(l2)(self.mui_grid)\n            return (2.*l1+1.)*(2.*l2+1.)*np.trapz(self.Pnoise**2.*l1l2/(self.Nmodes),self.mu,axis=0)\n        \n        \n    @cached_obs_property\n    def sk(self):\n        '''\n        Total error at k and mu\n        '''\n        return self.sk_CV+self.sk_N\n        \n        \n    @cached_obs_property\n    def covmat_00(self):\n        '''\n        00 term of the total covariance matrix\n        '''\n        integrand = (self.Pk+self.Pnoise)/self.Nmodes**0.5\n        return 0.5*np.trapz(integrand**2,self.mu,axis=0)\n        \n        \n    @cached_obs_property\n    def covmat_02(self):\n        '''\n        02 term of the total covariance matrix\n        '''\n        L2 = legendre(2)(self.mui_grid)\n        integrand = (self.Pk+self.Pnoise)/self.Nmodes**0.5\n        return 5./2.*np.trapz(integrand**2*L2,self.mu,axis=0)\n        \n        \n    @cached_obs_property\n    def covmat_04(self):\n        '''\n        04 term of the total covariance matrix\n        '''\n        L4 = legendre(4)(self.mui_grid)\n        integrand = (self.Pk+self.Pnoise)/self.Nmodes**0.5\n        return 9./2.*np.trapz(integrand**2*L4,self.mu,axis=0)\n        \n        \n    @cached_obs_property\n    def covmat_22(self):\n        '''\n        22 term of the total covariance matrix\n        '''\n        L2 = legendre(2)(self.mui_grid)\n        integrand = (self.Pk+self.Pnoise)/self.Nmodes**0.5\n        return 25./2.*np.trapz(integrand**2*L2*L2,self.mu,axis=0)\n        \n        \n    @cached_obs_property\n    def covmat_24(self):\n        '''\n        24 term of the total covariance matrix\n        '''\n        L2 = legendre(2)(self.mui_grid)\n        L4 = legendre(4)(self.mui_grid)\n        integrand = (self.Pk+self.Pnoise)/self.Nmodes**0.5\n        return 45./2.*np.trapz(integrand**2*L2*L4,self.mu,axis=0)\n        \n        \n    @cached_obs_property\n    def covmat_44(self):\n        '''\n        44 term of the total covariance matrix\n        '''\n        L4 = legendre(4)(self.mui_grid)\n        integrand = (self.Pk+self.Pnoise)/self.Nmodes**0.5\n        return 81./2.*np.trapz(integrand**2*L4*L4,self.mu,axis=0)\n\n\n    def covmat_l1l2(self,l1,l2):\n        '''\n        l1l2 term of the total covariance matrix\n        '''\n        if l1 == 0 and l2 == 0:\n            return self.covmat_00\n        elif l1 == 0 and l2 == 2:\n            return self.covmat_02\n        elif l1 == 0 and l2 == 4:\n            return self.covmat_04\n        elif l1 == 2 and l2 == 2:\n            return self.covmat_22\n        elif l1 == 2 and l2 == 4:\n            return self.covmat_24\n        elif l1 == 4 and l2 == 4:\n            return self.covmat_44\n        else:\n            l1 = legendre(l1)(self.mui_grid)\n            l2 = legendre(l2)(self.mui_grid)\n            integrand = (self.Pk+self.Pnoise)/self.Nmodes**0.5\n            return (2.*l1+1.)*(2.*l2+1.)*np.trapz(integrand**2*l1*l2,self.mu,axis=0)\n        \n        \n    @cached_obs_property\n    def nk_field(self):\n        '''\n        Number of k bins for a given survey, based on kmax, kmin and \n        delta_k (=kmin)\n        \n        Only works if k_kind=linear\n        '''\n        if not self.k_kind == 'linear':\n            raise ValueError('nk_field can only be computed for linear spacing')\n        kmax = self.kmax_field\n        delta_k = self.kmin_field\n        \n        return (kmax-delta_k)/delta_k\n        \n        \n    @cached_obs_property\n    def SNR(self):\n        '''\n        Signal to noise ratio for given model and experiment\n        '''\n        SNR_k = (self.Pk**2/self.sk**2).decompose()\n        ind = np.logical_and(self.k>=self.kmin_field,self.k<=self.kmax_field)\n        return np.sqrt(SNR_k[ind].sum())\n        \n        \n    @cached_obs_property\n    def SNR_0(self):\n        '''\n        Signal to noise ratio in the monopole for given model and experiment\n        '''\n        SNR_k = (self.Pk_0**2/self.covmat_00).decompose()\n        ind = np.logical_and(self.k>=self.kmin_field,self.k<=self.kmax_field)\n        return np.sqrt(SNR_k[ind].sum())\n        \n        \n    @cached_obs_property\n    def SNR_2(self):\n        '''\n        Signal to noise ratio in the quadrupole for given model and experiment\n        '''\n        SNR_k = (self.Pk_2**2/self.covmat_22).decompose()\n        ind = np.logical_and(self.k>=self.kmin_field,self.k<=self.kmax_field)\n        return np.sqrt(SNR_k[ind].sum())\n        \n        \n    @cached_obs_property\n    def SNR_4(self):\n        '''\n        Signal to noise ratio in the hexadecapole for given model and experiment\n        '''\n        SNR_k = (self.Pk_4**2/self.covmat_44).decompose()\n        ind = np.logical_and(self.k>=self.kmin_field,self.k<=self.kmax_field)\n        return np.sqrt(SNR_k[ind].sum())\n        \n        \n    @cached_obs_property\n    def SNR_multipoles(self):\n        '''\n        Signal to noise ratio in the monopole, quadrupole and hexadecapole\n        for given model and experiment\n        '''\n        ind = np.where(np.logical_and(self.k>=self.kmin_field,\n                                      self.k<=self.kmax_field))[0]\n        Nkseen = len(ind)\n        Pkvec = np.zeros(Nkseen*3)\n        covmat = np.zeros((Nkseen*3,Nkseen*3))\n        \n        Pkvec[:Nkseen] = self.Pk_0[ind]\n        Pkvec[Nkseen:Nkseen*2] = self.Pk_2[ind]\n        Pkvec[Nkseen*2:Nkseen*3] = self.Pk_4[ind]\n        \n        covmat[:Nkseen,:Nkseen] = np.diag(self.covmat_00[ind])\n        covmat[:Nkseen,Nkseen:Nkseen*2] = np.diag(self.covmat_02[ind])\n        covmat[:Nkseen,Nkseen*2:Nkseen*3] = np.diag(self.covmat_04[ind])\n        covmat[Nkseen:Nkseen*2,:Nkseen] = np.diag(self.covmat_02[ind])\n        covmat[Nkseen:Nkseen*2,Nkseen:Nkseen*2] = np.diag(self.covmat_22[ind])\n        covmat[Nkseen:Nkseen*2,Nkseen*2:Nkseen*3] = np.diag(self.covmat_24[ind])\n        covmat[Nkseen*2:Nkseen*3,:Nkseen] = np.diag(self.covmat_04[ind])\n        covmat[Nkseen*2:Nkseen*3,Nkseen:Nkseen*2] = np.diag(self.covmat_24[ind])\n        covmat[Nkseen*2:Nkseen*3,Nkseen*2:Nkseen*3] = np.diag(self.covmat_44[ind])\n        \n        return np.sqrt(np.dot(Pkvec,np.dot(np.linalg.inv(covmat),Pkvec)))\n        \n        \n    def get_covmat(self,Nmul):\n        '''\n        Get the covariance matrix for a given number of multipoles \n        (starting always from the monopole and without skipping any)\n        '''\n        if Nmul > 3:\n            raise ValueError('Not implemented yet!\\\n            Implement covmat_66 and expand this function')\n            \n        covmat = np.zeros((self.nk*Nmul,self.nk*Nmul))\n        covmat[:self.nk,:self.nk] = np.diag(self.covmat_00)\n        \n        if Nmul > 1:\n            covmat[:self.nk,self.nk:self.nk*2] = np.diag(self.covmat_02)\n            covmat[self.nk:self.nk*2,:self.nk] = np.diag(self.covmat_02)\n            covmat[self.nk:self.nk*2,self.nk:self.nk*2] = np.diag(self.covmat_22)\n            covmat[:self.nk,self.nk:self.nk*2] = np.diag(self.covmat_02)\n        if Nmul > 2:\n            covmat[:self.nk,self.nk*2:self.nk*3] = np.diag(self.covmat_04)\n            covmat[self.nk:self.nk*2,self.nk*2:self.nk*3] = np.diag(self.covmat_24)\n            covmat[self.nk*2:self.nk*3,:self.nk] = np.diag(self.covmat_04)\n            covmat[self.nk*2:self.nk*3,self.nk:self.nk*2] = np.diag(self.covmat_24)\n            covmat[self.nk*2:self.nk*3,self.nk*2:self.nk*3] = np.diag(self.covmat_44)\n\n        return covmat\n        \n        \n############\n# Doctests #\n############\n\nif __name__ == \"__main__\":\n    import doctest\n\n    doctest.testmod(optionflags=doctest.ELLIPSIS |\n                    doctest.NORMALIZE_WHITESPACE)\n", "meta": {"hexsha": "3f9171d14487ee065fb835a4dd6e95c73fcfa0a6", "size": 24735, "ext": "py", "lang": "Python", "max_stars_repo_path": "source/line_obs.py", "max_stars_repo_name": "dongwooc/lim", "max_stars_repo_head_hexsha": "ab1e4c5c62a3486d89e197badff456b393022b31", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-24T14:37:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T10:40:32.000Z", "max_issues_repo_path": "source/line_obs.py", "max_issues_repo_name": "dongwooc/lim", "max_issues_repo_head_hexsha": "ab1e4c5c62a3486d89e197badff456b393022b31", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/line_obs.py", "max_forks_repo_name": "dongwooc/lim", "max_forks_repo_head_hexsha": "ab1e4c5c62a3486d89e197badff456b393022b31", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-14T14:33:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T14:33:11.000Z", "avg_line_length": 31.074120603, "max_line_length": 100, "alphanum_fraction": 0.5546391753, "include": true, "reason": "import numpy,from scipy,import astropy", "num_tokens": 6636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.15741635915094473}}
{"text": "\"\"\"Classes to compute cluster centers with different algorithms.\n\nThis file contains the generic centering class and various different\nimplementations of different centering algorithms.  The main algorithm is\nCenteringWcenZred, but others are included as part of the centering training\nprocedure.\n\"\"\"\nimport fitsio\nimport esutil\nimport numpy as np\n\nfrom .utilities import gaussFunction\nfrom .utilities import interpol\n\nclass Centering(object):\n    \"\"\"\n    Generic centering base class for computing cluster centers.\n    \"\"\"\n\n    def __init__(self, cluster, zlambda_corr=None):\n        \"\"\"\n        Instantiate a Centering object for a cluster.\n\n        Parameters\n        ----------\n        cluster: `redmapper.Cluster`\n           Cluster to compute centering\n        zlambda_corr: `redmapper.ZlambdaCorrectionPar`, optional\n           z_lambda correction parameters, if desired.  Default is None.\n        \"\"\"\n        # Reference to the cluster; may need to copy\n        self.cluster = cluster\n\n        # And the zlambda_corr structure\n        self.zlambda_corr = zlambda_corr\n\n        # For convenience, make references to these structures\n        self.zredstr = cluster.zredstr\n        self.config = cluster.config\n        self.cosmo = cluster.cosmo\n\n        # Reset values\n        self.ra = np.zeros(self.config.percolation_maxcen) - 400.0\n        self.dec = np.zeros(self.config.percolation_maxcen) - 400.0\n        self.ngood = 0\n        self.index = np.zeros(self.config.percolation_maxcen, dtype=np.int32) - 1\n        self.maxind = -1\n        self.lnlamlike = -1.0\n        self.lnbcglike = -1.0\n        self.p_cen = np.zeros(self.config.percolation_maxcen)\n        self.q_cen = np.zeros(self.config.percolation_maxcen)\n        self.p_fg = np.zeros(self.config.percolation_maxcen)\n        self.q_miss = 0.0\n        self.p_sat = np.zeros(self.config.percolation_maxcen)\n        self.p_c = np.zeros(self.config.percolation_maxcen)\n\n    def find_center(self):\n        \"\"\"\n        Stub to override to find center\n        \"\"\"\n        return False\n\nclass CenteringBCG(Centering):\n    \"\"\"\n    Centering class using the brightest cluster galaxy (BCG) algorithm.\n    \"\"\"\n\n    def find_center(self):\n        \"\"\"\n        Find the center using the CenteringBCG algorithm.\n\n        This algorithm takes the brightest member with pmem > 0.8 and calls it\n        the central galaxy.\n\n        Will set self.maxind (index of best center); self.ra, self.dec\n        (position of best center); self.ngood (number of good candidates);\n        self.index[:] (indices of all the candidates); self.p_cen[:] (pcen\n        centering probabilities); self.q_cen[:] (qcen unused miss\n        probabilities); self.p_sat[:] (p_sat satellite probabilities).\n\n        Returns\n        -------\n        success: `bool`\n           True when a center is successfully found. (Always True).\n        \"\"\"\n        # This is somewhat arbitrary, and is not yet configurable\n        pmem_cut = 0.8\n\n        use, = np.where((self.cluster.neighbors.r < self.cluster.r_lambda) &\n                        ((self.cluster.neighbors.pmem > pmem_cut) |\n                         (np.abs(self.cluster.neighbors.zred - self.cluster.redshift) < 2.0 * self.cluster.neighbors.zred_e)))\n\n        if use.size == 0:\n            return False\n\n        mind = np.argmin(self.cluster.neighbors.refmag[use])\n\n        self.maxind = use[mind]\n        self.ra = np.array([self.cluster.neighbors.ra[self.maxind]])\n        self.dec = np.array([self.cluster.neighbors.dec[self.maxind]])\n        self.ngood = 1\n        self.index[0] = self.maxind\n        self.p_cen[0] = 1.0\n        self.q_cen[0] = 1.0\n        self.p_sat[0] = 0.0\n\n        return True\n\nclass CenteringWcenZred(Centering):\n    \"\"\"\n    Centering class using the \"wcen-zred\" algorithm.\n\n    This algorithm computes the primary centering likelihood algorithm by\n    computing the connectivity of the members, as well as ensuring\n    consistency between zred of the candidates and the cluster redshift.\n    \"\"\"\n\n    def find_center(self):\n        \"\"\"\n        Find the center using the CenteringWcenZred algorithm.\n\n        This algorithm computes the primary centering likelihood algorithm by\n        computing the connectivity of the members, as well as ensuring\n        consistency between zred of the candidates and the cluster redshift.\n\n        Will set self.maxind (index of best center); self.ra, self.dec\n        (position of best center); self.ngood (number of good candidates);\n        self.index[:] (indices of all the candidates); self.p_cen[:] (pcen\n        centering probabilities); self.q_cen[:] (qcen unused miss\n        probabilities); self.p_sat[:] (p_sat satellite probabilities).\n\n        Returns\n        -------\n        success: `bool`\n           True when a center is successfully found. (Always True).\n        \"\"\"\n        # These are the galaxies considered as candidate centers\n        use, = np.where((self.cluster.neighbors.r < self.cluster.r_lambda) &\n                        (self.cluster.neighbors.pfree >= self.config.percolation_pbcg_cut) &\n                        (self.cluster.neighbors.zred_chisq < self.config.wcen_zred_chisq_max) &\n                        ((self.cluster.neighbors.pmem > 0.0) |\n                         (np.abs(self.cluster.redshift - self.cluster.neighbors.zred) < 5.0 * self.cluster.neighbors.zred_e)))\n\n        # Do the phi_cen filter\n        mbar = self.cluster.mstar + self.config.wcen_Delta0 + self.config.wcen_Delta1 * np.log(self.cluster.Lambda / self.config.wcen_pivot)\n        phi_cen = gaussFunction(self.cluster.neighbors.refmag[use],\n                                1. / (np.sqrt(2. * np.pi) * self.config.wcen_sigma_m),\n                                mbar,\n                                self.config.wcen_sigma_m)\n\n        if self.zlambda_corr is not None:\n            zrmod = interpol(self.zlambda_corr.zred_uncorr, self.zlambda_corr.z, self.cluster.redshift)\n            gz = gaussFunction(self.cluster.neighbors.zred[use],\n                               1. / (np.sqrt(2. * np.pi) * self.cluster.neighbors.zred_e[use]),\n                               zrmod,\n                               self.cluster.neighbors.zred_e[use])\n        else:\n            gz = gaussFunction(self.cluster.neighbors.zred[use],\n                               1. / (np.sqrt(2. * np.pi) * self.cluster.neighbors.zred_e[use]),\n                               self.cluster.redshift,\n                               self.cluster.neighbors.zred_e[use])\n\n        # and the w filter.  We need w for each galaxy that is considered a candidate center.\n        # Note that in order to calculate w we need to know all the galaxies that are\n        # around it, but only within r_lambda *of that galaxy*.  This is tricky.\n\n        u, = np.where(self.cluster.neighbors.p > 0.0)\n\n        # This is the maximum radius in units of degrees (r_lambda is Mpc; mpc_scale is Mpc / degree)\n        maxrad = 1.1 * self.cluster.r_lambda / self.cluster.mpc_scale\n\n        htm_matcher = esutil.htm.Matcher(self.cluster.neighbors.depth,\n                                         self.cluster.neighbors.ra[use],\n                                         self.cluster.neighbors.dec[use])\n        i2, i1, dist = htm_matcher.match(self.cluster.neighbors.ra[u],\n                                         self.cluster.neighbors.dec[u],\n                                         maxrad, maxmatch=0)\n\n        subdifferent, = np.where(~(use[i1] == u[i2]))\n        i1 = i1[subdifferent]\n        i2 = i2[subdifferent]\n        pdis = dist[subdifferent] * self.cluster.mpc_scale\n        pdis = np.sqrt(pdis**2. + self.config.wcen_rsoft**2.)\n\n        lum = 10.**((self.cluster.mstar - self.cluster.neighbors.refmag) / (2.5))\n\n        # Put a floor on w when we have a strange candidate at the edge that doesn't\n        # match any good galaxies\n        w = np.zeros(use.size) + 1e-3\n        for i in range(use.size):\n            # need to filter on r_lambda...\n            subgal, = np.where(i1 == i)\n            if subgal.size > 0:\n                inside, = np.where(pdis[subgal] < self.cluster.r_lambda)\n                if inside.size > 0:\n                    indices = u[i2[subgal[inside]]]\n                    if self.config.wcen_uselum:\n                        w[i] = np.log(np.sum(self.cluster.neighbors.p[indices] * lum[indices] /\n                                             pdis[subgal[inside]]) /\n                                      ((1. / self.cluster.r_lambda) *\n                                       np.sum(self.cluster.neighbors.p[indices] * lum[indices])))\n                    else:\n                        w[i] = np.log(np.sum(self.cluster.neighbors.p[indices] /\n                                             pdis[subgal[inside]]) /\n                                      ((1. / self.cluster.r_lambda) *\n                                       np.sum(self.cluster.neighbors.p[indices])))\n\n        sigscale = np.sqrt((np.clip(self.cluster.Lambda, None, self.config.wcen_maxlambda) / self.cluster.scaleval) / self.config.wcen_pivot)\n\n        # scale with richness for Poisson errors\n        sig = self.config.lnw_cen_sigma / sigscale\n\n        fw = gaussFunction(np.log(w),\n                           1. / (np.sqrt(2. * np.pi) * sig),\n                           self.config.lnw_cen_mean,\n                           sig)\n\n        ucen = phi_cen * gz * fw\n\n        lo, = np.where(ucen < 1e-10)\n        ucen[lo] = 0.0\n\n        # and the satellite function\n        maxmag = self.cluster.mstar - 2.5 * np.log10(self.config.lval_reference)\n        phi_sat = self.cluster._calc_luminosity(maxmag, idx=use)\n\n        satsig = self.config.lnw_sat_sigma / sigscale\n        fsat = gaussFunction(np.log(w),\n                             1. / (np.sqrt(2. * np.pi) * satsig),\n                             self.config.lnw_sat_mean,\n                             satsig)\n\n        usat = phi_sat * gz * fsat\n\n        lo, = np.where(usat < 1e-10)\n        usat[lo] = 0.0\n\n        # and the background/foreground\n        fgsig = self.config.lnw_fg_sigma / sigscale\n        ffg = gaussFunction(np.log(w),\n                            1. / (np.sqrt(2. * np.pi) * fgsig),\n                            self.config.lnw_fg_mean,\n                            fgsig)\n\n        # we want to divide out the r, and we don't want small r's messing this up\n        rtest = np.zeros(use.size) + 0.1\n\n        bcounts = ffg * (self.cluster.calc_zred_bkg_density(rtest,\n                                                            self.cluster.neighbors.zred[use],\n                                                            self.cluster.neighbors.refmag[use]) /\n                         (2. * np.pi * rtest)) * np.pi * self.cluster.r_lambda**2.\n\n        # The start of Pcen\n        Pcen_basic = np.clip(self.cluster.neighbors.pfree[use] * (ucen / (ucen + (self.cluster.Lambda / self.cluster.scaleval - 1.0) * usat + bcounts)),None, 0.99999)\n\n        # make sure we don't have any bad values\n        bad, = np.where(~np.isfinite(Pcen_basic))\n        Pcen_basic[bad] = 0.0\n\n        okay, = np.where(Pcen_basic > 0.0)\n        if okay.size == 0:\n            # There are literally NO centers\n            self.q_miss = 1.0\n\n            # Set the same as the input galaxy...\n            # We need this to be an array of length 1\n            good = np.atleast_1d(np.argmin(self.cluster.neighbors.r[use]))\n\n            maxind = use[good[0]]\n\n            Pcen = np.zeros(use.size)\n            Qcen = np.zeros(use.size)\n\n        else:\n            # Do the renormalization\n\n            Pcen_unnorm = np.zeros(use.size)\n\n            # Only consider centrals that have a non-zero probability\n            ok, = np.where(Pcen_basic > 0)\n\n            st = np.argsort(Pcen_basic[ok])[::-1]\n            if st.size < self.config.percolation_maxcen:\n                good = ok[st]\n            else:\n                good = ok[st[0: self.config.percolation_maxcen]]\n\n            self.ngood = good.size\n\n            for i in range(self.ngood):\n                Pcen0 = Pcen_basic[good[i]]\n                Pcen_basic[good[i]] = 0.0\n                Pcen_unnorm[good[i]] = Pcen0 * np.prod(1.0 - Pcen_basic[good])\n                Pcen_basic[good[i]] = Pcen0\n\n            Qmiss = np.prod(1.0 - Pcen_basic[good])\n\n            KQ = 1./(Qmiss + np.sum(Pcen_unnorm))\n            KP = 1./np.sum(Pcen_unnorm)\n\n            Pcen = KP * Pcen_unnorm\n            Qcen = KQ * Pcen_unnorm\n\n            mod1 = np.sum(np.log(ucen[good] + (self.cluster.Lambda - 1) * usat[good] + bcounts[good]))\n            mod2 = np.sum(np.log(self.cluster.Lambda * usat[good] + bcounts[good]))\n\n            # A new statistic that doesn't quite work\n            Qmiss = -2.0 * np.sum(np.log((ucen[good] + (self.cluster.Lambda - 1) * usat[good] + bcounts[good]) / (self.cluster.Lambda * usat[good] + bcounts[good])))\n\n            maxind = use[good[0]]\n\n        Pfg_basic = bcounts[good] / ((self.cluster.Lambda - 1.0) * usat[good] + bcounts[good])\n        inf, = np.where(~np.isfinite(Pfg_basic))\n        Pfg_basic[inf] = 0.0\n\n        Pfg = (1.0 - Pcen[good]) * Pfg_basic\n\n        Psat_basic = (self.cluster.Lambda - 1.0) * usat[good] / ((self.cluster.Lambda - 1.0) * usat[good] + bcounts[good])\n        inf, = np.where(~np.isfinite(Psat_basic))\n        Psat_basic[inf] = 0.0\n\n        Psat = (1.0 - Pcen[good]) * Psat_basic\n\n        self.ra[0: good.size] = self.cluster.neighbors.ra[use[good]]\n        self.dec[0: good.size] = self.cluster.neighbors.dec[use[good]]\n        self.maxind = use[good[0]]\n        self.index[0: good.size] = use[good]\n        self.p_cen[0: good.size] = Pcen[good]\n        self.q_cen[0: good.size] = Qcen[good]\n        self.p_fg[0: good.size] = Pfg\n        self.p_sat[0: good.size] = Psat\n        self.p_c[0: good.size] = Pcen_basic[good]\n\n        return True\n\nclass CenteringRandom(Centering):\n    \"\"\"\n    Centering class using the random-position algorithm.\n\n    This is used for filter calibration.\n    \"\"\"\n\n    def find_center(self):\n        \"\"\"\n        Find the center using the CenteringRandom algorithm.\n\n        This algorithm takes a random position within cluster r_lambda and\n        calls it the center.  It is not a very good centering algorithm.\n\n        Will set self.maxind (index of best center); self.ra, self.dec\n        (position of best center); self.ngood (number of good candidates);\n        self.index[:] (indices of all the candidates); self.p_cen[:] (pcen\n        centering probabilities); self.q_cen[:] (qcen unused miss\n        probabilities); self.p_sat[:] (p_sat satellite probabilities).\n\n        Returns\n        -------\n        success: `bool`\n           True when a center is successfully found. (Always True).\n        \"\"\"\n        r = self.cluster.r_lambda * np.sqrt(np.random.random(size=1))\n        phi = 2. * np.pi * np.random.random(size=1)\n\n        x = r * np.cos(phi) / (self.cluster.mpc_scale)\n        y = r * np.sin(phi) / (self.cluster.mpc_scale)\n\n        ra_cen = self.cluster.ra + x / np.cos(np.radians(self.cluster.dec))\n        dec_cen = self.cluster.dec + y\n\n        self.ra[0] = ra_cen\n        self.dec[0] = dec_cen\n        self.ngood = 1\n        self.index[0] = -1\n        self.maxind = -1\n        self.p_cen[0] = 1.0\n        self.q_cen[0] = 1.0\n        self.p_sat[0] = 0.0\n        self.p_fg[0] = 0.0\n        self.p_c[0] = 1.0\n\n        return True\n\n\nclass CenteringRandomSatellite(Centering):\n    \"\"\"\n    Centering class using the random-satellite algorithm.\n\n    This is used for filter calibration.\n    \"\"\"\n\n    def find_center(self):\n        \"\"\"\n        Find the center using the CenteringRandomSatellite algorithm.\n\n        This algorithm takes a random member (weighted by member pmem) and\n        calls it the center.  It is not a very good centering algorithm (but\n        better than pure random!)\n\n        Will set self.maxind (index of best center); self.ra, self.dec\n        (position of best center); self.ngood (number of good candidates);\n        self.index[:] (indices of all the candidates); self.p_cen[:] (pcen\n        centering probabilities); self.q_cen[:] (qcen unused miss\n        probabilities); self.p_sat[:] (p_sat satellite probabilities).\n\n        Returns\n        -------\n        success: `bool`\n           True when a center is successfully found. (Always True).\n        \"\"\"\n        st = np.argsort(self.cluster.neighbors.pmem)[::-1]\n\n        pdf = self.cluster.neighbors.pmem[st]\n        pdf /= np.sum(pdf)\n        cdf = np.cumsum(pdf, dtype=np.float64)\n        cdfi = (cdf * st.size).astype(np.int32)\n\n        rand = (np.random.uniform(size=1) * st.size).astype(np.int32)\n        ind = np.where(cdfi >= rand[0])[0][0]\n        maxind = st[ind]\n\n        ra_cen = self.cluster.neighbors.ra[maxind]\n        dec_cen = self.cluster.neighbors.dec[maxind]\n\n        self.ra[0] = ra_cen\n        self.dec[0] = dec_cen\n        self.index[0] = maxind\n        self.maxind = maxind\n        self.ngood = 1\n        self.p_cen[0] = 1.0\n        self.q_cen[0] = 1.0\n        self.p_sat[0] = 0.0\n        self.p_fg[0] = 0.0\n        self.p_c[0] = 1.0\n\n        return True\n\n", "meta": {"hexsha": "13eb88b879b190d45aeed68743185a98cab2739b", "size": 17049, "ext": "py", "lang": "Python", "max_stars_repo_path": "redmapper/centering.py", "max_stars_repo_name": "erykoff/redmapper", "max_stars_repo_head_hexsha": "23fb66c7369de784c67ce6c41ada2f1f51a84acb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2016-03-06T07:51:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T15:17:26.000Z", "max_issues_repo_path": "redmapper/centering.py", "max_issues_repo_name": "erykoff/redmapper", "max_issues_repo_head_hexsha": "23fb66c7369de784c67ce6c41ada2f1f51a84acb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2016-07-27T20:48:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T20:47:51.000Z", "max_forks_repo_path": "redmapper/centering.py", "max_forks_repo_name": "erykoff/redmapper", "max_forks_repo_head_hexsha": "23fb66c7369de784c67ce6c41ada2f1f51a84acb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2017-01-26T01:38:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-14T07:41:53.000Z", "avg_line_length": 39.0137299771, "max_line_length": 166, "alphanum_fraction": 0.5699454513, "include": true, "reason": "import numpy", "num_tokens": 4218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3007455852086006, "lm_q1q2_score": 0.1574163591509447}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"\nModels for doing PSF/PRF fitting photometry on image data.\n\"\"\"\n\nimport copy\nimport itertools\nimport warnings\n\nimport numpy as np\nfrom astropy.nddata import NDData\nfrom astropy.modeling import Parameter, Fittable2DModel\nfrom astropy.utils.exceptions import (AstropyWarning,\n                                      AstropyDeprecationWarning)\n\n\n__all__ = ['NonNormalizable', 'FittableImageModel', 'EPSFModel',\n           'GriddedPSFModel', 'IntegratedGaussianPRF', 'PRFAdapter']\n\n\nclass NonNormalizable(AstropyWarning):\n    \"\"\"\n    Used to indicate that a :py:class:`FittableImageModel` model is\n    non-normalizable.\n\n    \"\"\"\n    pass\n\n\nclass FittableImageModel(Fittable2DModel):\n    \"\"\"\n    A fittable 2D model of an image allowing for image intensity scaling\n    and image translations.\n\n    This class takes 2D image data and computes the\n    values of the model at arbitrary locations (including at intra-pixel,\n    fractional positions) within this image using spline interpolation\n    provided by :py:class:`~scipy.interpolate.RectBivariateSpline`.\n\n    The fittable model provided by this class has three model parameters:\n    an image intensity scaling factor (`flux`) which is applied to\n    (normalized) image, and two positional parameters (`x_0` and `y_0`)\n    indicating the location of a feature in the coordinate grid on which\n    the model is to be evaluated.\n\n    If this class is initialized with `flux` (intensity scaling factor)\n    set to `None`, then `flux` is going to be estimated as ``sum(data)``.\n\n    Parameters\n    ----------\n    data : numpy.ndarray\n        Array containing 2D image.\n\n    origin : tuple, None, optional\n        A reference point in the input image ``data`` array. When origin is\n        `None`, origin will be set at the middle of the image array.\n\n        If `origin` represents the location of a feature (e.g., the position\n        of an intensity peak) in the input ``data``, then model parameters\n        `x_0` and `y_0` show the location of this peak in an another target\n        image to which this model was fitted. Fundamentally, it is the\n        coordinate in the model's image data that should map to\n        coordinate (`x_0`, `y_0`) of the output coordinate system on which the\n        model is evaluated.\n\n        Alternatively, when `origin` is set to ``(0,0)``, then model parameters\n        `x_0` and `y_0` are shifts by which model's image should be translated\n        in order to match a target image.\n\n    normalize : bool, optional\n        Indicates whether or not the model should be build on normalized\n        input image data. If true, then the normalization constant (*N*) is\n        computed so that\n\n        .. math::\n            N \\\\cdot C \\\\cdot \\\\Sigma_{i,j}D_{i,j} = 1,\n\n        where *N* is the normalization constant, *C* is correction factor\n        given by the parameter ``normalization_correction``, and\n        :math:`D_{i,j}` are the elements of the input image ``data`` array.\n\n    normalization_correction : float, optional\n        A strictly positive number that represents correction that needs to\n        be applied to model's data normalization (see *C* in the equation\n        in the comments to ``normalize`` for more details).\n\n        A possible application for this parameter is to account for aperture\n        correction. Assuming model's data represent a PSF to be fitted to\n        some target star, we set ``normalization_correction`` to the aperture\n        correction that needs to be applied to the model. That is,\n        ``normalization_correction`` in this case should be set to the\n        ratio between the total flux of the PSF (including flux outside model's\n        data) to the flux of model's data.\n        Then, best fitted value of the `flux` model\n        parameter will represent an aperture-corrected flux of the target star.\n\n    fill_value : float, optional\n        The value to be returned by the `evaluate` or\n        ``astropy.modeling.Model.__call__`` methods\n        when evaluation is performed outside the definition domain of the\n        model.\n\n    ikwargs : dict, optional\n\n        Additional optional keyword arguments to be passed directly to the\n        `compute_interpolator` method. See `compute_interpolator` for more\n        details.\n\n    \"\"\"\n    flux = Parameter(description='Intensity scaling factor for image data.',\n                     default=1.0)\n    x_0 = Parameter(description='X-position of a feature in the image in '\n                    'the output coordinate grid on which the model is '\n                    'evaluated.', default=0.0)\n    y_0 = Parameter(description='Y-position of a feature in the image in '\n                    'the output coordinate grid on which the model is '\n                    'evaluated.', default=0.0)\n\n    def __init__(self, data, flux=flux.default,\n                 x_0=x_0.default, y_0=y_0.default,\n                 normalize=False, normalization_correction=1.0,\n                 origin=None, oversampling=1, fill_value=0.0, ikwargs={}):\n        self._fill_value = fill_value\n        self._img_norm = None\n        self._normalization_status = 0 if normalize else 2\n        self._store_interpolator_kwargs(ikwargs)\n        self._set_oversampling(oversampling)\n\n        if normalization_correction <= 0:\n            raise ValueError(\"'normalization_correction' must be strictly \"\n                             \"positive.\")\n        self._normalization_correction = normalization_correction\n\n        self._data = np.array(data, copy=True, dtype=np.float64)\n\n        if not np.all(np.isfinite(self._data)):\n            raise ValueError(\"All elements of input 'data' must be finite.\")\n\n        # set input image related parameters:\n        self._ny, self._nx = self._data.shape\n        self._shape = self._data.shape\n        if self._data.size < 1:\n            raise ValueError(\"Image data array cannot be zero-sized.\")\n\n        # set the origin of the coordinate system in image's pixel grid:\n        self.origin = origin\n\n        if flux is None:\n            if self._img_norm is None:\n                self._img_norm = self._compute_raw_image_norm(self._data)\n            flux = self._img_norm\n\n        self._compute_normalization(normalize)\n\n        super().__init__(flux, x_0, y_0)\n\n        # initialize interpolator:\n        self.compute_interpolator(ikwargs)\n\n    def _compute_raw_image_norm(self, data):\n        \"\"\"\n        Helper function that computes the uncorrected inverse normalization\n        factor of input image data. This quantity is computed as the\n        *sum of all pixel values*.\n\n        .. note::\n            This function is intended to be overriden in a subclass if one\n            desires to change the way the normalization factor is computed.\n\n        \"\"\"\n        return np.sum(self._data, dtype=np.float64)\n\n    def _compute_normalization(self, normalize):\n        \"\"\"\n        Helper function that computes (corrected) normalization factor\n        of the original image data. This quantity is computed as the\n        inverse \"raw image norm\" (or total \"flux\" of model's image)\n        corrected by the ``normalization_correction``:\n\n        .. math::\n            N = 1/(\\\\Phi * C),\n\n        where :math:`\\\\Phi` is the \"total flux\" of model's image as\n        computed by `_compute_raw_image_norm` and *C* is the\n        normalization correction factor. :math:`\\\\Phi` is computed only\n        once if it has not been previously computed. Otherwise, the\n        existing (stored) value of :math:`\\\\Phi` is not modified as\n        :py:class:`FittableImageModel` does not allow image data to be\n        modified after the object is created.\n\n        .. note::\n            Normally, this function should not be called by the\n            end-user. It is intended to be overriden in a subclass if\n            one desires to change the way the normalization factor is\n            computed.\n        \"\"\"\n\n        self._normalization_constant = 1.0 / self._normalization_correction\n\n        if normalize:\n            # compute normalization constant so that\n            # N*C*sum(data) = 1:\n            if self._img_norm is None:\n                self._img_norm = self._compute_raw_image_norm(self._data)\n\n            if self._img_norm != 0.0 and np.isfinite(self._img_norm):\n                self._normalization_constant /= self._img_norm\n                self._normalization_status = 0\n\n            else:\n                self._normalization_constant = 1.0\n                self._normalization_status = 1\n                warnings.warn(\"Overflow encountered while computing \"\n                              \"normalization constant. Normalization \"\n                              \"constant will be set to 1.\", NonNormalizable)\n\n        else:\n            self._normalization_status = 2\n\n    @property\n    def oversampling(self):\n        \"\"\"\n        The factor by which the stored image is oversampled.  I.e., an input\n        to this model is multipled by this factor to yield the index into the\n        stored image.\n        \"\"\"\n        return self._oversampling\n\n    def _set_oversampling(self, value):\n        \"\"\"\n        This is a private method because it's used in the initializer but the\n        ``oversampling``\n        \"\"\"\n        try:\n            value = float(value)\n        except ValueError:\n            raise ValueError('Oversampling factor must be a scalar')\n        if value <= 0:\n            raise ValueError('Oversampling factor must be greater than 0')\n\n        self._oversampling = value\n\n    @property\n    def data(self):\n        \"\"\" Get original image data. \"\"\"\n        return self._data\n\n    @property\n    def normalized_data(self):\n        \"\"\" Get normalized and/or intensity-corrected image data. \"\"\"\n        return (self._normalization_constant * self._data)\n\n    @property\n    def normalization_constant(self):\n        \"\"\" Get normalization constant. \"\"\"\n        return self._normalization_constant\n\n    @property\n    def normalization_status(self):\n        \"\"\"\n        Get normalization status. Possible status values are:\n\n        - 0: **Performed**. Model has been successfuly normalized at\n          user's request.\n        - 1: **Failed**. Attempt to normalize has failed.\n        - 2: **NotRequested**. User did not request model to be normalized.\n\n        \"\"\"\n        return self._normalization_status\n\n    @property\n    def normalization_correction(self):\n        \"\"\"\n        Set/Get flux correction factor.\n\n        .. note::\n            When setting correction factor, model's flux will be adjusted\n            accordingly such that if this model was a good fit to some target\n            image before, then it will remain a good fit after correction\n            factor change.\n\n        \"\"\"\n        return self._normalization_correction\n\n    @normalization_correction.setter\n    def normalization_correction(self, normalization_correction):\n        old_cf = self._normalization_correction\n        self._normalization_correction = normalization_correction\n        self._compute_normalization(normalize=self._normalization_status != 2)\n\n        # adjust model's flux so that if this model was a good fit to some\n        # target image, then it will remain a good fit after correction factor\n        # change:\n        self.flux *= normalization_correction / old_cf\n\n    @property\n    def shape(self):\n        \"\"\"A tuple of dimensions of the data array in numpy style (ny, nx).\"\"\"\n        return self._shape\n\n    @property\n    def nx(self):\n        \"\"\"Number of columns in the data array.\"\"\"\n        return self._nx\n\n    @property\n    def ny(self):\n        \"\"\"Number of rows in the data array.\"\"\"\n        return self._ny\n\n    @property\n    def origin(self):\n        \"\"\"\n        A tuple of ``x`` and ``y`` coordinates of the origin of the coordinate\n        system in terms of pixels of model's image.\n\n        When setting the coordinate system origin, a tuple of two `int` or\n        `float` may be used. If origin is set to `None`, the origin of the\n        coordinate system will be set to the middle of the data array\n        (``(npix-1)/2.0``).\n\n        .. warning::\n            Modifying `origin` will not adjust (modify) model's parameters\n            `x_0` and `y_0`.\n        \"\"\"\n        return (self._x_origin, self._y_origin)\n\n    @origin.setter\n    def origin(self, origin):\n        if origin is None:\n            self._x_origin = (self._nx - 1) / 2.0\n            self._y_origin = (self._ny - 1) / 2.0\n        elif hasattr(origin, '__iter__') and len(origin) == 2:\n            self._x_origin, self._y_origin = origin\n        else:\n            raise TypeError(\"Parameter 'origin' must be either None or an \"\n                            \"iterable with two elements.\")\n\n    @property\n    def x_origin(self):\n        \"\"\"X-coordinate of the origin of the coordinate system.\"\"\"\n        return self._x_origin\n\n    @property\n    def y_origin(self):\n        \"\"\"Y-coordinate of the origin of the coordinate system.\"\"\"\n        return self._y_origin\n\n    @property\n    def fill_value(self):\n        \"\"\"Fill value to be returned for coordinates outside of the domain of\n        definition of the interpolator. If ``fill_value`` is `None`, then\n        values outside of the domain of definition are the ones returned\n        by the interpolator.\n\n        \"\"\"\n        return self._fill_value\n\n    @fill_value.setter\n    def fill_value(self, fill_value):\n        self._fill_value = fill_value\n\n    def _store_interpolator_kwargs(self, ikwargs):\n        \"\"\"\n        This function should be called in a subclass whenever model's\n        interpolator is (re-)computed.\n        \"\"\"\n        self._interpolator_kwargs = copy.deepcopy(ikwargs)\n\n    @property\n    def interpolator_kwargs(self):\n        \"\"\"\n        Get current interpolator's arguments used when interpolator was\n        created.\n        \"\"\"\n        return self._interpolator_kwargs\n\n    def compute_interpolator(self, ikwargs={}):\n        \"\"\"\n        Compute/define the interpolating spline. This function can be overriden\n        in a subclass to define custom interpolators.\n\n        Parameters\n        ----------\n        ikwargs : dict, optional\n\n            Additional optional keyword arguments. Possible values are:\n\n            - **degree** : int, tuple, optional\n                Degree of the interpolating spline. A tuple can be used to\n                provide different degrees for the X- and Y-axes.\n                Default value is degree=3.\n\n            - **s** : float, optional\n                Non-negative smoothing factor. Default value s=0 corresponds to\n                interpolation.\n                See :py:class:`~scipy.interpolate.RectBivariateSpline` for more\n                details.\n\n        Notes\n        -----\n            * When subclassing :py:class:`FittableImageModel` for the\n              purpose of overriding :py:func:`compute_interpolator`,\n              the :py:func:`evaluate` may need to overriden as well depending\n              on the behavior of the new interpolator. In addition, for\n              improved future compatibility, make sure\n              that the overriding method stores keyword arguments ``ikwargs``\n              by calling ``_store_interpolator_kwargs`` method.\n\n            * Use caution when modifying interpolator's degree or smoothness in\n              a computationally intensive part of the code as it may decrease\n              code performance due to the need to recompute interpolator.\n\n        \"\"\"\n        from scipy.interpolate import RectBivariateSpline\n\n        if 'degree' in ikwargs:\n            degree = ikwargs['degree']\n            if hasattr(degree, '__iter__') and len(degree) == 2:\n                degx = int(degree[0])\n                degy = int(degree[1])\n            else:\n                degx = int(degree)\n                degy = int(degree)\n            if degx < 0 or degy < 0:\n                raise ValueError(\"Interpolator degree must be a non-negative \"\n                                 \"integer\")\n        else:\n            degx = 3\n            degy = 3\n\n        if 's' in ikwargs:\n            smoothness = ikwargs['s']\n        else:\n            smoothness = 0\n\n        x = np.arange(self._nx, dtype=np.float)\n        y = np.arange(self._ny, dtype=np.float)\n        self.interpolator = RectBivariateSpline(\n            x, y, self._data.T, kx=degx, ky=degy, s=smoothness\n        )\n\n        self._store_interpolator_kwargs(ikwargs)\n\n    def evaluate(self, x, y, flux, x_0, y_0, use_oversampling=True):\n        \"\"\"\n        Evaluate the model on some input variables and provided model\n        parameters.\n\n        Parameters\n        ----------\n        use_oversampling : bool, optional\n            Whether to use the oversampling factor to calculate the\n            model pixel indices.  The default is `True`, which means the\n            input indices will be multipled by this factor.\n        \"\"\"\n\n        if use_oversampling:\n            xi = self._oversampling * (np.asarray(x) - x_0)\n            yi = self._oversampling * (np.asarray(y) - y_0)\n        else:\n            xi = np.asarray(x) - x_0\n            yi = np.asarray(y) - y_0\n\n        xi += self._x_origin\n        yi += self._y_origin\n\n        f = flux * self._normalization_constant\n        evaluated_model = f * self.interpolator.ev(xi, yi)\n\n        if self._fill_value is not None:\n            # find indices of pixels that are outside the input pixel grid and\n            # set these pixels to the 'fill_value':\n            invalid = (((xi < 0) | (xi > self._nx - 1)) |\n                       ((yi < 0) | (yi > self._ny - 1)))\n            evaluated_model[invalid] = self._fill_value\n\n        return evaluated_model\n\n\nclass EPSFModel(FittableImageModel):\n    \"\"\"\n    A subclass of `FittableImageModel`.\n\n    Parameters\n    ----------\n    pixel_scale : float, tuple of two floats or `None`, optional\n        .. warning::\n\n            The ``pixel_scale`` keyword is now deprecated (since v0.6)\n            and will likely be removed in v0.7.  Use the\n            ``oversampling`` keyword instead.\n\n        The pixel scale (in arbitrary units) of the ePSF.  The\n        ``pixel_scale`` can either be a single float or tuple of two\n        floats of the form ``(x_pixscale, y_pixscale)``.  If\n        ``pixel_scale`` is a scalar then the pixel scale will be the\n        same for both the x and y axes.  The default is `None`, which\n        means it will be set to the inverse of the ``oversampling``\n        factor.\n\n        The ePSF ``pixel_scale`` is used only when building the ePSF and\n        when fitting the ePSF to `Star` objects with `EPSFFitter`.  In\n        those cases, the ``pixel_scale`` is used in conjunction with the\n        `Star` pixel scale when building and fitting the ePSF.  This\n        allows for building (and fitting) a ePSF using images of stars\n        with different pixel scales (e.g. velocity aberrations).  The\n        ``oversampling`` factor is ignored in these cases.\n\n        If you are not using `EPSFBuilder` or `EPSFFitter`, then you\n        must set the ``oversampling`` factor.  The ``pixel_scale`` will\n        be ignored.\n    \"\"\"\n\n    def __init__(self, data, flux=1.0, x_0=0, y_0=0, normalize=True,\n                 normalization_correction=1.0, origin=None, oversampling=1.,\n                 pixel_scale=None, fill_value=0., ikwargs={}):\n\n        if pixel_scale is None:\n            pixel_scale = 1. / oversampling\n        else:\n            warnings.warn('The pixel_scale keyword is deprecated and will '\n                          'likely be removed in v0.7.  Use the oversampling '\n                          'keyword instead.', AstropyDeprecationWarning)\n\n        super().__init__(\n            data=data, flux=flux, x_0=x_0, y_0=y_0, normalize=normalize,\n            normalization_correction=normalization_correction, origin=origin,\n            oversampling=oversampling, fill_value=fill_value, ikwargs=ikwargs)\n\n        self._pixel_scale = pixel_scale\n\n    @property\n    def pixel_scale(self):\n        \"\"\"\n        The ``(x, y)`` pixel scale (in arbitrary units) of the PSF.\n        \"\"\"\n\n        return self._pixel_scale\n\n    @pixel_scale.setter\n    def pixel_scale(self, pixel_scale):\n        if pixel_scale is not None:\n            pixel_scale = np.atleast_1d(pixel_scale)\n            if len(pixel_scale) == 1:\n                pixel_scale = np.repeat(pixel_scale, 2).astype(float)\n            elif len(pixel_scale) > 2:\n                raise ValueError('pixel_scale must be a scalar or tuple '\n                                 'of two floats.')\n\n        self._pixel_scale = pixel_scale\n\n\nclass GriddedPSFModel(Fittable2DModel):\n    \"\"\"\n    A fittable 2D model containing a grid PSF models defined at specific\n    locations that are interpolated to evaluate a PSF at an arbitrary\n    (x, y) position.\n\n    Parameters\n    ----------\n    data : `~astropy.nddata.NDData`\n        An `~astropy.nddata.NDData` object containing the grid of\n        reference PSF arrays.  The data attribute must contain a 3D\n        `~numpy.ndarray` containing a stack of the 2D PSFs (the data\n        shape should be (N_psf, PSF_ny, PSF_nx)).  The meta\n        attribute must be `dict` containing the following:\n\n            * ``'grid_xypos'``:  A list of the (x, y) grid positions of\n              each reference PSF.  The order of positions should match\n              the first axis of the 3D `~numpy.ndarray` of PSFs.  In\n              other words, ``grid_xypos[i]`` should be the (x, y)\n              position of the reference PSF defined in ``data[i]``.\n            * ``'oversampling'``:  The integer oversampling factor of the\n               PSF.\n\n        The meta attribute may contain other properties such as the\n        telescope, instrument, detector, and filter of the PSF.\n    \"\"\"\n\n    flux = Parameter(description='Intensity scaling factor for the PSF '\n                     'model.', default=1.0)\n    x_0 = Parameter(description='x position in the output coordinate grid '\n                    'where the model is evaluated.', default=0.0)\n    y_0 = Parameter(description='y position in the output coordinate grid '\n                    'where the model is evaluated.', default=0.0)\n\n    def __init__(self, data, flux=flux.default, x_0=x_0.default,\n                 y_0=y_0.default, fill_value=0.0):\n\n        if not isinstance(data, NDData):\n            raise TypeError('data must be an NDData instance.')\n\n        if data.data.ndim != 3:\n            raise ValueError('The NDData data attribute must be a 3D numpy '\n                             'ndarray')\n\n        if 'grid_xypos' not in data.meta:\n            raise ValueError('\"grid_xypos\" must be in the nddata meta '\n                             'dictionary.')\n        if len(data.meta['grid_xypos']) != data.data.shape[0]:\n            raise ValueError('The length of grid_xypos must match the number '\n                             'of input PSFs.')\n\n        if 'oversampling' not in data.meta:\n            raise ValueError('\"oversampling\" must be in the nddata meta '\n                             'dictionary.')\n        if not np.isscalar(data.meta['oversampling']):\n            raise ValueError('oversampling must be a scalar value')\n\n        self.data = np.array(data.data, copy=True, dtype=np.float)\n        self.meta = data.meta\n        self.grid_xypos = data.meta['grid_xypos']\n        self.oversampling = data.meta['oversampling']\n\n        self._grid_xpos, self._grid_ypos = np.transpose(self.grid_xypos)\n        self._xgrid = np.unique(self._grid_xpos)  # also sorts values\n        self._ygrid = np.unique(self._grid_ypos)  # also sorts values\n\n        if (len(list(itertools.product(self._xgrid, self._ygrid))) !=\n                len(self.grid_xypos)):\n            raise ValueError('\"grid_xypos\" must form a regular grid.')\n\n        self._xgrid_min = self._xgrid[0]\n        self._xgrid_max = self._xgrid[-1]\n        self._ygrid_min = self._ygrid[0]\n        self._ygrid_max = self._ygrid[-1]\n\n        super().__init__(flux, x_0, y_0)\n\n    @staticmethod\n    def _find_bounds_1d(data, x):\n        \"\"\"\n        Find the index of the lower bound where ``x`` should be inserted\n        into ``a`` to maintain order.\n\n        The index of the upper bound is the index of the lower bound\n        plus 2.  Both bound indices must be within the array.\n\n        Parameters\n        ----------\n        data : 1D `~numpy.ndarray`\n            The 1D array to search.\n\n        x : float\n            The value to insert.\n\n        Returns\n        -------\n        index : int\n            The index of the lower bound.\n        \"\"\"\n\n        idx = np.searchsorted(data, x)\n        if idx == 0:\n            idx0 = 0\n        elif idx == len(data):  # pragma: no cover\n            idx0 = idx - 2\n        else:\n            idx0 = idx - 1\n\n        return idx0\n\n    def _find_bounding_points(self, x, y):\n        \"\"\"\n        Find the indices of the grid points that bound the input\n        ``(x, y)`` position.\n\n        Parameters\n        ----------\n        x, y : float\n            The ``(x, y)`` position where the PSF is to be evaluated.\n\n        Returns\n        -------\n        indices : list of int\n            A list of indices of the bounding grid points.\n        \"\"\"\n\n        if not np.isscalar(x) or not np.isscalar(y):  # pragma: no cover\n            raise TypeError('x and y must be scalars')\n\n        if (x < self._xgrid_min or x > self._xgrid_max or\n                y < self._ygrid_min or y > self._ygrid_max):  # pragma: no cover\n            raise ValueError('(x, y) position is outside of the region '\n                             'defined by grid of PSF positions')\n\n        x0 = self._find_bounds_1d(self._xgrid, x)\n        y0 = self._find_bounds_1d(self._ygrid, y)\n        points = list(itertools.product(self._xgrid[x0:x0 + 2],\n                                        self._ygrid[y0:y0 + 2]))\n\n        indices = []\n        for xx, yy in points:\n            indices.append(np.argsort(np.hypot(self._grid_xpos - xx,\n                                               self._grid_ypos - yy))[0])\n\n        return indices\n\n    @staticmethod\n    def _bilinear_interp(xyref, zref, xi, yi):\n        \"\"\"\n        Perform bilinear interpolation of four 2D arrays located at\n        points on a regular grid.\n\n        Parameters\n        ----------\n        xyref : list of 4 (x, y) pairs\n            A list of 4 ``(x, y)`` pairs that form a rectangle.\n\n        refdata : 3D `~numpy.ndarray`\n            A 3D `~numpy.ndarray` of shape ``(4, nx, ny)``.  The first\n            axis corresponds to ``xyref``, i.e. ``refdata[0, :, :]`` is\n            the 2D array located at ``xyref[0]``.\n\n        xi, yi : float\n            The ``(xi, yi)`` point at which to perform the\n            interpolation.  The ``(xi, yi)`` point must lie within the\n            rectangle defined by ``xyref``.\n\n        Returns\n        -------\n        result : 2D `~numpy.ndarray`\n            The 2D interpolated array.\n        \"\"\"\n\n        if len(xyref) != 4:\n            raise ValueError('xyref must contain only 4 (x, y) pairs')\n\n        if zref.shape[0] != 4:\n            raise ValueError('zref must have a length of 4 on the first '\n                             'axis.')\n\n        xyref = [tuple(i) for i in xyref]\n        idx = sorted(range(len(xyref)), key=xyref.__getitem__)\n        xyref = sorted(xyref)   # sort by x, then y\n        (x0, y0), (_x0, y1), (x1, _y0), (_x1, _y1) = xyref\n\n        if x0 != _x0 or x1 != _x1 or y0 != _y0 or y1 != _y1:\n            raise ValueError('The refxy points do not form a rectangle.')\n\n        if not np.isscalar(xi):\n            xi = xi[0]\n        if not np.isscalar(yi):\n            yi = yi[0]\n\n        if not x0 <= xi <= x1 or not y0 <= yi <= y1:\n            raise ValueError('The (x, y) input is not within the rectangle '\n                             'defined by xyref.')\n\n        data = np.asarray(zref)[idx]\n        weights = np.array([(x1 - xi) * (y1 - yi), (x1 - xi) * (yi - y0),\n                            (xi - x0) * (y1 - yi), (xi - x0) * (yi - y0)])\n        norm = (x1 - x0) * (y1 - y0)\n\n        return np.sum(data * weights[:, None, None], axis=0) / norm\n\n    def evaluate(self, x, y, flux, x_0, y_0):\n        \"\"\"\n        Evaluate the `GriddedPSFModel` for the input parameters.\n        \"\"\"\n\n        # NOTE: this is needed because the PSF photometry routines input\n        # length-1 values instead of scalars.  TODO: fix the photometry\n        # routines.\n        if not np.isscalar(x_0):\n            x_0 = x_0[0]\n        if not np.isscalar(y_0):\n            y_0 = y_0[0]\n\n        if (x_0 < self._xgrid_min or x_0 > self._xgrid_max or\n                y_0 < self._ygrid_min or y_0 > self._ygrid_max):\n\n            # position is outside of the grid, so simply use the\n            # closest reference PSF\n            self._ref_indices = np.argsort(np.hypot(self._grid_xpos - x_0,\n                                                    self._grid_ypos - y_0))[0]\n            self._psf_interp = self.data[self._ref_indices, :, :]\n        else:\n            # find the four bounding reference PSFs and interpolate\n            self._ref_indices = self._find_bounding_points(x_0, y_0)\n            xyref = np.array(self.grid_xypos)[self._ref_indices]\n            psfs = self.data[self._ref_indices, :, :]\n\n            self._psf_interp = self._bilinear_interp(xyref, psfs, x_0, y_0)\n\n        # now evaluate the PSF at the (x_0, y_0) subpixel position on\n        # the input (x, y) values\n        psfmodel = FittableImageModel(self._psf_interp,\n                                      oversampling=self.oversampling)\n\n        return psfmodel.evaluate(x, y, flux, x_0, y_0)\n\n\nclass IntegratedGaussianPRF(Fittable2DModel):\n    r\"\"\"\n    Circular Gaussian model integrated over pixels. Because it is\n    integrated, this model is considered a PRF, *not* a PSF (see\n    :ref:`psf-terminology` for more about the terminology used here.)\n\n    This model is a Gaussian *integrated* over an area of ``1`` (in\n    units of the model input coordinates, e.g. 1 pixel).  This is in\n    contrast to the apparently similar\n    `astropy.modeling.functional_models.Gaussian2D`, which is the value\n    of a 2D Gaussian *at* the input coordinates, with no integration.\n    So this model is equivalent to assuming the PSF is Gaussian at a\n    *sub-pixel* level.\n\n    Parameters\n    ----------\n    sigma : float\n        Width of the Gaussian PSF.\n    flux : float (default 1)\n        Total integrated flux over the entire PSF\n    x_0 : float (default 0)\n        Position of the peak in x direction.\n    y_0 : float (default 0)\n        Position of the peak in y direction.\n\n    Notes\n    -----\n    This model is evaluated according to the following formula:\n\n        .. math::\n\n            f(x, y) =\n                \\frac{F}{4}\n                \\left[\n                {\\rm erf} \\left(\\frac{x - x_0 + 0.5}\n                {\\sqrt{2} \\sigma} \\right) -\n                {\\rm erf} \\left(\\frac{x - x_0 - 0.5}\n                {\\sqrt{2} \\sigma} \\right)\n                \\right]\n                \\left[\n                {\\rm erf} \\left(\\frac{y - y_0 + 0.5}\n                {\\sqrt{2} \\sigma} \\right) -\n                {\\rm erf} \\left(\\frac{y - y_0 - 0.5}\n                {\\sqrt{2} \\sigma} \\right)\n                \\right]\n\n    where ``erf`` denotes the error function and ``F`` the total\n    integrated flux.\n    \"\"\"\n\n    flux = Parameter(default=1)\n    x_0 = Parameter(default=0)\n    y_0 = Parameter(default=0)\n    sigma = Parameter(default=1, fixed=True)\n\n    _erf = None\n    fit_deriv = None\n\n    @property\n    def bounding_box(self):\n        halfwidth = 4 * self.sigma\n        return ((int(self.y_0 - halfwidth), int(self.y_0 + halfwidth)),\n                (int(self.x_0 - halfwidth), int(self.x_0 + halfwidth)))\n\n    def __init__(self, sigma=sigma.default,\n                 x_0=x_0.default, y_0=y_0.default, flux=flux.default,\n                 **kwargs):\n        if self._erf is None:\n            from scipy.special import erf\n            self.__class__._erf = erf\n\n        super().__init__(n_models=1, sigma=sigma, x_0=x_0, y_0=y_0, flux=flux,\n                         **kwargs)\n\n    def evaluate(self, x, y, flux, x_0, y_0, sigma):\n        \"\"\"Model function Gaussian PSF model.\"\"\"\n\n        return (flux / 4 *\n                ((self._erf((x - x_0 + 0.5) / (np.sqrt(2) * sigma)) -\n                  self._erf((x - x_0 - 0.5) / (np.sqrt(2) * sigma))) *\n                 (self._erf((y - y_0 + 0.5) / (np.sqrt(2) * sigma)) -\n                  self._erf((y - y_0 - 0.5) / (np.sqrt(2) * sigma)))))\n\n\nclass PRFAdapter(Fittable2DModel):\n    \"\"\"\n    A model that adapts a supplied PSF model to act as a PRF. It\n    integrates the PSF model over pixel \"boxes\".  A critical built-in\n    assumption is that the PSF model scale and location parameters are\n    in *pixel* units.\n\n    Parameters\n    ----------\n    psfmodel : a 2D model\n        The model to assume as representative of the PSF\n    renormalize_psf : bool\n        If True, the model will be integrated from -inf to inf and\n        re-scaled so that the total integrates to 1.  Note that this\n        renormalization only occurs *once*, so if the total flux of\n        ``psfmodel`` depends on position, this will *not* be correct.\n    xname : str or None\n        The name of the ``psfmodel`` parameter that corresponds to the\n        x-axis center of the PSF.  If None, the model will be assumed to\n        be centered at x=0.\n    yname : str or None\n        The name of the ``psfmodel`` parameter that corresponds to the\n        y-axis center of the PSF.  If None, the model will be assumed to\n        be centered at y=0.\n    fluxname : str or None\n        The name of the ``psfmodel`` parameter that corresponds to the\n        total flux of the star.  If None, a scaling factor will be\n        applied by the ``PRFAdapter`` instead of modifying the\n        ``psfmodel``.\n\n    Notes\n    -----\n    This current implementation of this class (using numerical\n    integration for each pixel) is extremely slow, and only suited for\n    experimentation over relatively few small regions.\n    \"\"\"\n\n    flux = Parameter(default=1)\n    x_0 = Parameter(default=0)\n    y_0 = Parameter(default=0)\n\n    def __init__(self, psfmodel, renormalize_psf=True, flux=flux.default,\n                 x_0=x_0.default, y_0=y_0.default, xname=None, yname=None,\n                 fluxname=None, **kwargs):\n\n        self.psfmodel = psfmodel.copy()\n\n        if renormalize_psf:\n            from scipy.integrate import dblquad\n            self._psf_scale_factor = 1. / dblquad(self.psfmodel,\n                                                  -np.inf, np.inf,\n                                                  lambda x: -np.inf,\n                                                  lambda x: np.inf)[0]\n        else:\n            self._psf_scale_factor = 1\n\n        self.xname = xname\n        self.yname = yname\n        self.fluxname = fluxname\n\n        # these can be used to adjust the integration behavior. Might be\n        # used in the future to expose how the integration happens\n        self._dblquadkwargs = {}\n\n        super().__init__(n_models=1, x_0=x_0, y_0=y_0, flux=flux, **kwargs)\n\n    def evaluate(self, x, y, flux, x_0, y_0):\n        \"\"\"The evaluation function for PRFAdapter.\"\"\"\n\n        if self.xname is None:\n            dx = x - x_0\n        else:\n            dx = x\n            setattr(self.psfmodel, self.xname, x_0)\n\n        if self.xname is None:\n            dy = y - y_0\n        else:\n            dy = y\n            setattr(self.psfmodel, self.yname, y_0)\n\n        if self.fluxname is None:\n            return (flux * self._psf_scale_factor *\n                    self._integrated_psfmodel(dx, dy))\n        else:\n            setattr(self.psfmodel, self.yname, flux * self._psf_scale_factor)\n            return self._integrated_psfmodel(dx, dy)\n\n    def _integrated_psfmodel(self, dx, dy):\n        from scipy.integrate import dblquad\n\n        # infer type/shape from the PSF model.  Seems wasteful, but the\n        # integration step is a *lot* more expensive so its just peanuts\n        out = np.empty_like(self.psfmodel(dx, dy))\n        outravel = out.ravel()\n        for i, (xi, yi) in enumerate(zip(dx.ravel(), dy.ravel())):\n            outravel[i] = dblquad(self.psfmodel,\n                                  xi-0.5, xi+0.5,\n                                  lambda x: yi-0.5, lambda x: yi+0.5,\n                                  **self._dblquadkwargs)[0]\n        return out\n", "meta": {"hexsha": "dbf15cf04c471609dd3c4c990c5fa769b241f2eb", "size": 36456, "ext": "py", "lang": "Python", "max_stars_repo_path": "photutils/psf/models.py", "max_stars_repo_name": "nden/photutils", "max_stars_repo_head_hexsha": "87879b2464ccfcd160f6a0c53ea4c0869a6e1cc2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "photutils/psf/models.py", "max_issues_repo_name": "nden/photutils", "max_issues_repo_head_hexsha": "87879b2464ccfcd160f6a0c53ea4c0869a6e1cc2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "photutils/psf/models.py", "max_forks_repo_name": "nden/photutils", "max_forks_repo_head_hexsha": "87879b2464ccfcd160f6a0c53ea4c0869a6e1cc2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2, "max_line_length": 80, "alphanum_fraction": 0.591864165, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 8732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.15741635259001813}}
{"text": "\"\"\"\nCDI.py\nKristina Davis\n8/12/19\n\nThis module is used to set the CDI parameters for mini-medis.\n\"\"\"\n##\nimport numpy as np\nimport warnings\nfrom scipy import linalg, interpolate\nfrom matplotlib import pyplot as plt\nfrom matplotlib.colors import LogNorm, SymLogNorm\nimport time\nimport pickle\n\nfrom medis.params import tp, sp, ap, iop\nfrom medis.utils import dprint\nfrom medis.optics import extract_plane, cpx_to_intensity, extract_center\nfrom medis.plot_tools import add_colorbar, view_timeseries\n\n\n##\nclass Slapper:\n    \"\"\"Stole this idea from falco. Just passes an object you can slap stuff onto\"\"\"\n    pass\n\n\nclass CDI_params:\n    \"\"\"\n    contains the parameters of the CDI probes and phase sequence to apply to the DM\n    \"\"\"\n    def __init__(self):\n        # General\n        self.use_cdi = False\n        self.show_probe = False  # False , flag to plot phase probe or not\n        self.which_DM = ''  # plane_name parameter of the DM to apply CDI probe to (must be a valid name for\n        # the telescope sim you are running, eg 'tweeter'\n\n        # Probe Dimensions (extent in pupil plane coordinates)\n        self.probe_ax = 'X'  # 'Y' # direction of the probe\n        self.probe_amp = 2e-6  # [m] probe amplitude, scale should be in units of actuator height limits\n        self.probe_w = 10  # [actuator coordinates] width of the probe\n        self.probe_h = 30  # [actuator coordinates] height of the probe\n        self.probe_shift = (15, 15)  # [actuator coordinates] center position of the probe (should move off-center to\n        # avoid coronagraph)\n        self.probe_spacing = 10  # distance from the focal plane center to edge of the rectangular probed region\n\n        # Phase Sequence of Probes\n        self.phs_intervals = np.pi / 2  # [rad] phase interval over [0, 2pi]\n        self.probe_integration_time = 1  # [s]  How long in sec to apply each probe in the sequence\n        self.null_time = 5 * sp.sample_time # [s]  time between repeating probe cycles (data to be nulled using probe info)\n\n    def __iter__(self):\n        for attr, value in self.__dict__.items():\n            yield attr, value\n\n    def __name__(self):\n        return self.__str__().split(' ')[0].split('.')[-1]\n\n    def gen_phaseseries(self):\n        \"\"\"\n        generate an array of phases per timestep for the CDI algorithm\n\n        phase_series is used to populate cdi.phase_series, which may be longer than cdi.phase_cycle if multiple cycles\n        are run, or probes may last for longer than one single timestep\n\n        currently, I assume the timestream is not that long. Should only use this for short timestreams, and use a more\n        efficient code for long simulations (scale of minutes or more)\n\n        :return: phase_series  array of phases of CDI probes to apply to DM\n        \"\"\"\n        self.phase_series = np.zeros(sp.numframes) * np.nan\n\n        # Repeating Probe Phases for Integration time\n        self.phase_cycle = np.arange(0, 2 * np.pi, self.phs_intervals)  # FYI not inclusive of 2pi endpoint\n        self.n_probes = len(self.phase_cycle)  # number of phase probes\n        if self.n_probes % 2 != 0:\n            raise ValueError(f\"must have even number of phase probes\\n\\tchange cdi.phs_intervals\")\n        self.DM_probe_series = np.zeros((self.n_probes, tp.act_tweeter, tp.act_tweeter))\n        self.cmd_tstamps = np.zeros((sp.numframes,),  dtype='datetime64[ns]')\n\n        if self.probe_integration_time > sp.sample_time:\n            phase_hold = self.probe_integration_time / sp.sample_time\n            phase_1cycle = np.repeat(self.phase_cycle, phase_hold)\n        elif self.probe_integration_time == sp.sample_time:\n            phase_1cycle = self.phase_cycle\n        else:\n            raise ValueError(f\"Cannot have CDI phase probe integration time less than sp.sample_time\")\n\n        # Repeating Cycle of Phase Probes for Simulation Duration\n        full_simulation_time = sp.numframes * sp.sample_time\n        self.time_for_one_cycle = len(phase_1cycle) * self.probe_integration_time\n\n        if self.time_for_one_cycle > full_simulation_time and self.probe_integration_time >= sp.sample_time:\n            warnings.warn(f\"\\nLength of one full CDI probe cycle exceeds the \"\n                          f\"full simulation time \\n\"\n                          f\"not all phases will be used\\n\"\n                          f\"phase reconstruction will be incomplete\")\n            self.phase_series = phase_1cycle[0:sp.numframes]\n        elif self.time_for_one_cycle <= full_simulation_time and self.n_probes < sp.numframes:\n            print(f\"\\nCDI Params\\n\\tThere will be {sp.numframes - self.n_probes} \"\n                  f\"nulling steps after timestep {self.n_probes}\")\n            self.phase_series[0:self.n_probes] = phase_1cycle\n        else:\n            warnings.warn(f\"Haven't run into  CDI phase situation like this yet\")\n            raise NotImplementedError\n\n        return self.phase_series\n\n    def save_probe(self, ix, probe):\n        self.DM_probe_series[ix, :, :] = probe\n\n    def save_tseries(self, ix, ts):\n        \"\"\"saves output of medis fields as 2D intensity images for CDI postprocessing\"\"\"\n        self.cmd_tstamps[ix] = ts\n\n    def save_out_to_disk(self, plot=False):\n        out = Slapper()\n        out.probe = Slapper()\n        out.ts = Slapper()\n\n        # Probe Info\n        out.probe.direction = self.probe_ax\n        out.probe.amp = self.probe_amp\n        out.probe.width = self.probe_w\n        out.probe.height = self.probe_h\n        out.probe.shift = self.probe_shift\n        out.probe.spacing = self.probe_spacing\n        out.probe.DM_cmd_cycle = self.DM_probe_series\n        out.probe.phs_interval = self.phs_intervals\n\n        # Timeseries Info\n        out.ts.start = 0\n        out.ts.n_probes = self.n_probes\n        out.ts.phase_cycle = self.phase_cycle\n        out.ts.probe_integration_time = self.probe_integration_time\n        out.ts.t_one_cycle = self.time_for_one_cycle\n        out.ts.null_time = self.null_time\n        out.ts.elapsed_time = 0\n        out.ts.n_cycles = 0\n        out.ts.n_cmds = sp.numframes  # TODO verify this-this was just a late night hack\n        out.ts.cmd_tstamps = self.cmd_tstamps\n\n        save_location = iop.testdir + f\"/{iop.testname}_CDIparams.pkl\"\n        dprint(f'save_location={save_location}')\n        with open(save_location, 'wb') as handle:\n            pickle.dump(out, handle, protocol=pickle.HIGHEST_PROTOCOL)\n        handle.close()\n\n        # Fig\n        if plot:\n            if self.n_probes >= 4:\n                nrows = 2\n                ncols = self.n_probes//2\n                figheight = 8\n            else:\n                nrows = 1\n                ncols = self.n_probes\n                figheight = 4\n\n            fig, subplot = plt.subplots(nrows, ncols, figsize=(10, figheight))\n            fig.subplots_adjust(wspace=0.5, right=0.85, left=0.05)\n            fig.suptitle('Probe Series')\n\n            for ax, ix in zip(subplot.flatten(), range(out.ts.n_probes)):\n                im = ax.imshow(out.probe.DM_cmd_cycle[ix], interpolation='none', origin='lower')\n                ax.set_title(f\"Probe \" + r'$\\theta$=' + f'{out.ts.phase_cycle[ix]/np.pi:.2f}' + r'$\\pi$')\n\n            cax = fig.add_axes([0.9, 0.2, 0.03, 0.6])  # Add axes for colorbar @ position [left,bottom,width,height]\n            cb = fig.colorbar(im, orientation='vertical', cax=cax)  #\n            cb.set_label('Probe Height (m)')\n\n        return out\n\n# Sneakily Instantiating Class Objects here\ncdi = CDI_params()\n\n\n##\ndef config_probe(theta, nact, iw=0, ib=0, tstep=0):\n    \"\"\"\n    create a probe shape to apply to the DM for CDI processing\n\n    The probe applied to the DM to achieve CDI is that originally proposed in Giv'on et al 2011, doi: 10.1117/12.895117;\n    and was used with proper in Matthews et al 2018, doi:  10.1117/1.JATIS.3.4.045001.\n\n    The pupil coordinates used in those equations relate to the sampling of the pupil (plane of the DM). However, in\n    Proper, the prop_dm uses a DM map that is the size of (n_ao_act, n_ao_act). This map was resampled from its\n    original size to the actuator spacing, and the spacing in units of [m] is supplied as a keyword to the prop_dm\n    function during the call. All that is to say, we apply the CDI probe using the coordinates of the DM actuators,\n    and supply the probe height as an additive height to the DM map, which is passed to the prop_dm function.\n\n    :param theta: phase of the probe\n    :param nact: number of actuators in the mirror, should change if 'woofer' or 'tweeter'\n    :param iw: index of wavelength number in ap.wvl_range (used for plotting only)\n    :param ib: index of astronomical body eg star or companion (used for plotting only)\n    :return: height of phase probes to add to the DM map in adaptive.py\n    \"\"\"\n    x = np.linspace(-1/2-cdi.probe_shift[0]/nact, 1/2-cdi.probe_shift[0]/nact, nact)\n    y = np.linspace(-1/2-cdi.probe_shift[1]/nact, 1/2-cdi.probe_shift[1]/nact, nact)\n    X, Y = np.meshgrid(x, y)\n\n    wvl_samples = np.linspace(ap.wvl_range[0], ap.wvl_range[1], ap.n_wvl_init)\n    # dprint(f'iw = {iw}, lambda = {wvl_samples[iw]}')\n    mag = 4 * np.pi * wvl_samples[iw] * cdi.probe_amp\n\n    if cdi.probe_ax == 'X' or cdi.probe_ax == 'x':\n        dir = X\n    elif cdi.probe_ax == 'Y' or cdi.probe_ax == 'y':\n        dir = Y\n    else:\n        raise ValueError('probe direction value not understood; must be string \"X\" or \"Y\"')\n\n    probe = mag * np.sinc(cdi.probe_w * X) * np.sinc(cdi.probe_h * Y) \\\n            * np.sin(2*np.pi*cdi.probe_spacing * dir + theta)\n\n    # Testing FF propagation\n    if sp.verbose and iw == 0 and ib == 0:  # and theta == cdi.phase_series[0]\n        probe_ft = (1/np.sqrt(2*np.pi)) * np.fft.fftshift(np.fft.fft2(np.fft.ifftshift(probe)))\n\n        fig, ax = plt.subplots(1, 3, figsize=(12, 5))\n        fig.subplots_adjust(wspace=0.5)\n        ax1, ax2, ax3 = ax.flatten()\n\n        fig.suptitle(f\"spacing={cdi.probe_spacing}, Dimensions {cdi.probe_w}x{cdi.probe_h} \"\n                     f\"\\nProbe Amp = {cdi.probe_amp}, \" + r'$\\theta$' + f\"={theta/np.pi:.3f}\" + r'$\\pi$' + '\\n')\n\n        im1 = ax1.imshow(probe, interpolation='none')\n        ax1.set_title(f\"Probe on DM \\n(dm coordinates)\")\n        # cb = fig.colorbar(im1, ax=ax1)\n        add_colorbar(im1)\n\n        im2 = ax2.imshow(np.sqrt(probe_ft.imag ** 2 + probe_ft.real ** 2), interpolation='none')\n        ax2.set_title(\"Focal Plane Amplitude\")\n        add_colorbar(im2)\n\n        im3 = ax3.imshow(np.arctan2(probe_ft.imag, probe_ft.real), interpolation='none', cmap='hsv')\n        ax3.set_title(\"Focal Plane Phase\")\n        add_colorbar(im3)\n\n        # =========================\n        # Fig 2  Real & Imag\n        # fig, ax = plt.subplots(1, 3, figsize=(12, 5))\n        # fig.subplots_adjust(wspace=0.5)\n        # ax1, ax2, ax3 = ax.flatten()\n        # fig.suptitle(f'Real & Imaginary Probe Response in Focal Plane\\n'\n        #              f' '+r'$\\theta$'+f'={theta/np.pi:.3f}'+r'$\\pi$'+f', n_actuators = {nact}\\n')\n        #\n        # im1 = ax1.imshow(probe, interpolation='none', origin='lower')\n        # ax1.set_title(f\"Probe on DM \\n(dm coordinates)\")\n        # cb = fig.colorbar(im1, ax=ax1)\n        #\n        # im2 = ax2.imshow(probe_ft.real, interpolation='none', origin='lower')\n        # ax2.set_title(f\"Real FT of Probe\")\n        #\n        # im3 = ax3.imshow(probe_ft.imag, interpolation='none', origin='lower')\n        # ax3.set_title(f\"Imag FT of Probe\")\n\n        plt.show()\n\n    # Saving Probe in the series\n    if iw == 0 and ib == 0:\n        ip = np.argwhere(cdi.phase_series == theta)\n        cdi.save_probe(ip[0,0], probe)  #\n        cdi.nact = nact\n\n    return probe\n\n\n##\ndef cdi_postprocess(cpx_sequence, sampling, plot=False):\n    \"\"\"\n    this is the function that accepts the timeseries of intensity images from the simulation and returns the processed\n    single image. This function calculates the speckle amplitude phase, and then corrects for it to create the dark\n    hole over the specified region of the image.\n\n    From Give'on et al 2011, we have in eq 10 two different values: DeltaP-the change in the focal plane due to the\n    probe, and delta, the intensity difference measurements between pairs of phase probes. (It is unfortunate that\n    both these terms use delta, so I have done my best to distinguish them in the variable names)\n\n    Here I note that in the CDI phase stream generation, for n_probes there are n_pairs = n_probes/2 pairs of probes.\n    These get applied to the DM in a series such that the two probes that form the conjugate pair are separated by\n    n_pairs of probes. In other words, for n_probes = 6, the 0th and 3rd probes are a pair, the 1st and 4th are a pair,\n    and so on. This is a choice made when creating cdi.phase_series.\n\n    :param cpx_sequence: #timestream of 2D images (complex) from the focal plane complex field\n    :param sampling: focal plane sampling\n    :return:\n    \"\"\"\n    ##\n    tic = time.time()\n    focal_plane = extract_plane(cpx_sequence, 'detector')  # eliminates astro_body axis [tsteps,wvl,obj,x,y]\n    fp_seq = np.sum(focal_plane, axis=(1,2))  # sum over wavelength,object\n\n    n_pairs = cdi.n_probes//2  # number of deltas (probe differentials)\n    n_nulls = sp.numframes - cdi.n_probes\n    delta = np.zeros((n_pairs, sp.grid_size, sp.grid_size), dtype=float)\n    # absDelta = np.zeros((n_nulls, sp.grid_size, sp.grid_size))\n    # phsDelta = np.zeros((n_pairs, sp.grid_size, sp.grid_size), dtype=float)\n    E_est = np.zeros((n_nulls, sp.grid_size, sp.grid_size), dtype=complex)\n    I_processed = np.zeros((n_nulls, sp.grid_size, sp.grid_size))\n    H = np.zeros((n_pairs, 2), dtype=float)\n    b = np.zeros((n_pairs, 1))\n\n    # Get Masked Data\n    mask2D, imsk, jmsk, irng, jrng, imx, imn, jmx, jmn = get_fp_mask(cdi, thresh=1e-6)\n\n    if sp.debug:\n        fig, ax = plt.subplots(1,1)\n        fig.suptitle(f'Masked FP in CDI probe Region')\n        im = ax.imshow(cpx_to_intensity(fp_seq[0,:,:]*mask2D))\n\n    for ip in range(n_pairs):\n        # Compute deltas (I_ip+ - I_ip-)/2\n        delta[ip] = (np.abs(fp_seq[ip])**2 - np.abs(fp_seq[ip + n_pairs])**2) / 4\n\n    # for i,j in zip(imsk,jmsk):\n    # for i,j in zip(irng,jrng):\n    for i in irng:\n        for j in jrng:\n            for xn in range(n_nulls):\n                for ip in range(n_pairs):\n                    # Amplitude DeltaP\n                    Ip = np.abs(fp_seq[ip, i, j]) ** 2\n                    Im = np.abs(fp_seq[ip + n_pairs, i, j]) ** 2\n                    Io = np.abs(fp_seq[cdi.n_probes + xn, i, j]) ** 2\n                    abs = (Ip + Im) / 2 - Io\n                    if abs < 0:\n                        abs = 0\n                    absDeltaP = np.sqrt(abs)\n                    # absDeltaP = np.sqrt(np.abs((Ip + Im) / 2 - Io))\n\n                    # phsDeltaP = phsDelta[ip, i, j]\n                    # Phase DeltaP\n                    # The phase of the change in the focal plane of the probe applied to the DM\n                    # First subtract Eo vector from each probe phase to make new field vectors dEa, dEb,\n                    # then take the angle between the two\n                    dEp = fp_seq[ip, i, j] - fp_seq[cdi.n_probes + xn, i, j]\n                    dEm = fp_seq[ip + n_pairs, i, j] - fp_seq[cdi.n_probes + xn, i, j]\n                    phsDeltaP = np.arctan2(dEp.imag - dEm.imag, dEp.real - dEm.real)\n\n                    cpxDeltaP = absDeltaP * np.exp(1j * phsDeltaP)\n                    # cpxDeltaP = absDeltaP * np.array((np.cos(phsDeltaP), np.sin(phsDeltaP)))\n\n                    H[ip, :] = [-cpxDeltaP.imag, cpxDeltaP.real]  # [n_pairs, 2]\n                    # H[ip,:] = [cpxDeltaP[0], cpxDeltaP[1]]\n                    b[ip] = delta[ip, i, j]  # [n_pairs, 1]\n\n                a = 2 * H\n                Exy = linalg.lstsq(a, b)[0]  # returns tuple, not array\n                E_est[xn, i, j] = Exy[0] + (1j * Exy[1])\n\n    toc = time.time()\n    dprint(f'CDI post-processing took {(toc-tic)/60:.2} minutes\\n')\n\n    ## ===========================\n    # Contrast Ratios\n    # ===========================\n    intensity_probe        = np.zeros(n_nulls)\n    intensity_DM_FFT       = np.zeros(n_nulls)\n    intensity_pre_process  = np.zeros(n_nulls)\n    intensity_post_process = np.zeros(n_nulls)\n    \n    for xn in range(n_nulls):\n        I_processed[xn] = np.abs(fp_seq[n_pairs+xn])**2 - np.abs(np.conj(E_est[xn])*mask2D)**2\n        # I_processed[xn] = np.sqrt(np.abs(np.abs(fp_seq[n_pairs+xn])**2 - np.abs(E_est[xn]*mask2D)**2))**2\n        # I_processed[xn] = np.abs(fp_seq[n_pairs+xn] - np.conj(E_est[xn]*mask2D))**2\n\n        # Contrast\n        intensity_probe[xn] = np.sum(np.abs(fp_seq[xn]*mask2D)**2)\n        intensity_pre_process[xn] = np.sum(np.abs(fp_seq[n_pairs + xn]*mask2D)**2)\n        intensity_post_process[xn] = np.sum(I_processed[xn]*mask2D)  #np.sum(np.abs(E_processed[xn]*mask2D)**2)\n\n        print(f'\\nIntensity in probed region for null step {xn} is '\n              f'\\nprobe {intensity_probe[xn]}'\n              f'\\npre-processed {intensity_pre_process[xn]} '\n              f'\\npost-processed {intensity_post_process[xn]}'\n              f'\\n difference = {intensity_post_process[xn] - intensity_pre_process[xn]}'\n              f'\\n')\n\n ##   if plot:\n        # ==================\n        # FFT of Tweeter Plane\n        # ==================\n        # fig, subplot = plt.subplots(1, n_pairs, figsize=(14, 5))\n        # fig.subplots_adjust(wspace=0.5, right=0.85)\n        # fig.suptitle('Tweeter DM Plane')\n        #\n        # tweet = extract_plane(cpx_sequence, 'tweeter')  # eliminates astro_body axis [tsteps,wvl,obj,x,y]\n        # tweeter = np.sum(tweet, axis=(1, 2))\n        # tweeter_intensity = np.abs(tweeter) ** 2\n        # for ax, ix in zip(subplot.flatten(), range(n_pairs)):\n        #     im = ax.imshow(extract_center(tweeter_intensity[ix], new_size=sp.grid_size*sp.beam_ratio+10),\n        #                    interpolation='none', norm=LogNorm(),\n        #                    vmin=5e-3, vmax=1e-2)\n        #     ax.set_title(f'Probe Phase ' r'$\\theta$' f'={cdi.phase_cycle[ix] / np.pi:.2f}' r'$\\pi$')\n        #\n        # cax = fig.add_axes([0.9, 0.2, 0.03, 0.6])  # Add axes for colorbar @ position [left,bottom,width,height]\n        # cb = fig.colorbar(im, orientation='vertical', cax=cax)  #\n        # cb.set_label('Intensity')\n        #\n        # # =================================================================================\n        # fig, subplot = plt.subplots(1, n_pairs, figsize=(14, 5))\n        # fig.subplots_adjust(wspace=0.5, right=0.85)\n        # fig.suptitle('FFT of Tweeter DM Plane')\n        #\n        # for ax, ix in zip(subplot.flatten(), range(n_pairs)):\n        #     fft_tweeter = (1 / np.sqrt(2 * np.pi) *\n        #                    np.fft.fftshift(np.fft.fft2(np.fft.ifftshift(tweeter[ix]))))\n        #     im = ax.imshow(np.abs(fft_tweeter) ** 2,\n        #                    interpolation='none', norm=LogNorm(),\n        #                    vmin=1e-2, vmax=10)\n        #     ax.set_title(f'Probe Phase ' r'$\\theta$' f'={cdi.phase_cycle[ix] / np.pi:.2f}' r'$\\pi$')\n        #\n        # cax = fig.add_axes([0.9, 0.2, 0.03, 0.6])  # Add axes for colorbar @ position [left,bottom,width,height]\n        # cb = fig.colorbar(im, orientation='vertical', cax=cax)  #\n        # cb.set_label('Intensity')\n\n        # ==================\n        # Deltas\n        # ==================\n        # fig, subplot = plt.subplots(1, n_pairs, figsize=(14,5))\n        # fig.subplots_adjust(wspace=0.5, right=0.85)\n        # fig.suptitle('Deltas for CDI Probes')\n        #\n        # for ax, ix in zip(subplot.flatten(), range(n_pairs)):\n        #     im = ax.imshow(delta[ix]*1e6*mask2D, interpolation='none',\n        #                    norm=SymLogNorm(linthresh=1),\n        #                    # vmin=-1, vmax=1\n        #                    ) #, norm=SymLogNorm(linthresh=1e-5))\n        #     ax.set_title(f\"Diff Probe\\n\" + r'$\\theta$' + f'={cdi.phase_series[ix]/np.pi:.3f}' +\n        #                  r'$\\pi$ -$\\theta$' + f'={cdi.phase_series[ix+n_pairs]/np.pi:.3f}' + r'$\\pi$')\n        #\n        # cax = fig.add_axes([0.9, 0.2, 0.03, 0.6])  # Add axes for colorbar @ position [left,bottom,width,height]\n        # cb = fig.colorbar(im, orientation='vertical', cax=cax)  #\n        # cb.set_label('Intensity')\n\n        # ==================\n        # Null Probe E-Field\n        # ==================\n        fig, subplot = plt.subplots(1, n_nulls, figsize=(14, 5))\n        fig.subplots_adjust(wspace=0.5, right=0.85)\n        fig.suptitle('Original (Null-Probe) Image Plane Intensity')\n\n        for ax, ix in zip(subplot.flatten(), range(n_nulls)):\n            im = ax.imshow(np.abs(fp_seq[cdi.n_probes + ix, irng[0]:irng[-1], jrng[0]:jrng[-1]]) ** 2,  # , 250:270, 150:170  *mask2D , irng[0]:irng[-1], jrng[0]:jrng[-1]\n                           interpolation='none', norm=LogNorm(),\n                           vmin=1e-7, vmax=1e-4)\n            ax.set_title(f'Null Step {ix}')\n\n        cax = fig.add_axes([0.9, 0.2, 0.03, 0.6])  # Add axes for colorbar @ position [left,bottom,width,height]\n        cb = fig.colorbar(im, orientation='vertical', cax=cax)  #\n        cb.set_label('Intensity')\n\n        # ===============================\n        # E-filed Estimate\n        # ===============================\n        fig, subplot = plt.subplots(1, n_nulls, figsize=(14, 5))\n        fig.subplots_adjust(wspace=0.5, right=0.85)\n        fig.suptitle('Pairwise Probe Estimated Image Plane intensity')\n\n        for ax, ix in zip(subplot.flatten(), range(n_nulls)):\n            im = ax.imshow(np.abs(E_est[ix, irng[0]:irng[-1], jrng[0]:jrng[-1]])**2,  # , 250:270, 150:170  *mask2D , irng[0]:irng[-1], jrng[0]:jrng[-1]\n                           interpolation='none',\n                           norm=LogNorm(),\n                           vmin=1e-7, vmax=1e-4\n                           )  # , norm=SymLogNorm(linthresh=1e-5))\n            ax.set_title(f'Null Step {ix}')\n\n        cax = fig.add_axes([0.9, 0.2, 0.03, 0.6])  # Add axes for colorbar @ position [left,bottom,width,height]\n        cb = fig.colorbar(im, orientation='vertical', cax=cax)  #\n        cb.set_label('Intensity')\n\n        # ==================================\n        # Processed E-field (CDI Subtracted)\n        # ==================================\n        fig, subplot = plt.subplots(1, n_nulls, figsize=(14, 5))\n        fig.subplots_adjust(wspace=0.5, right=0.85)\n        fig.suptitle('CDI Subtracted Image Plane Intensity')\n\n        for ax, ix in zip(subplot.flatten(), range(n_nulls)):\n            im = ax.imshow(I_processed[ix],  # , 250:270, 150:170  *mask2D , irng[0]:irng[-1], jrng[0]:jrng[-1]\n                           interpolation='none',\n                           norm=LogNorm(),\n                           vmin=1e-7, vmax=1e-4\n                           )  # , norm=SymLogNorm(linthresh=1e-5))\n            ax.set_title(f'Null Step {ix}')\n\n        cax = fig.add_axes([0.9, 0.2, 0.03, 0.6])  # Add axes for colorbar @ position [left,bottom,width,height]\n        cb = fig.colorbar(im, orientation='vertical', cax=cax)  #\n        cb.set_label('Intensity')\n\n        # =======================================\n        # Compare Unprobed to Estimated E-fields\n        # ======================================\n        fig, subplot = plt.subplots(2, n_nulls, figsize=(16, 12))\n        fig.subplots_adjust(wspace=0.5, right=0.85)\n        fig.suptitle('Compare Null Probed to Pairwise Probe Estimated Image Plane Intensity')\n        ax1, ax2, ax3, ax4 = subplot.flatten()\n\n        ax1.imshow(np.abs(fp_seq[-2, irng[0]:irng[-1], jrng[0]:jrng[-1]]) ** 2,  # , 250:270, 150:170  *mask2D\n                   interpolation='none',\n                   norm=LogNorm(),\n                   # vmin=1e-8, vmax=1e-2\n                   )\n        ax1.set_title(f'Original Null Step 0')\n\n        ax2.imshow(np.abs(fp_seq[-1, irng[0]:irng[-1], jrng[0]:jrng[-1]]) ** 2,  # , 250:270, 150:170  *mask2D\n                   interpolation='none',\n                   norm=LogNorm(),\n                   # vmin=1e-8, vmax=1e-2\n                   )\n        ax2.set_title(f'Original Null Step 1')\n\n        ax3.imshow(np.abs(E_est[0, irng[0]:irng[-1], jrng[0]:jrng[-1]]) ** 2,  # , 250:270, 150:170  *mask2D\n                   interpolation='none',\n                   norm=LogNorm(),\n                   # vmin=1e-8, vmax=1e-2\n                   )\n        ax3.set_title(f'PP Estimated Null Step 0')\n\n        ax4.imshow(np.abs(E_est[1, irng[0]:irng[-1], jrng[0]:jrng[-1]]) ** 2,  # , 250:270, 150:170  *mask2D\n                   interpolation='none',\n                   norm=LogNorm(),\n                   # vmin=1e-8, vmax=1e-2\n                   )\n        ax4.set_title(f'PP Estimated Null Step 1')\n\n        cax = fig.add_axes([0.9, 0.2, 0.03, 0.6])  # Add axes for colorbar @ position [left,bottom,width,height]\n        cb = fig.colorbar(im, orientation='vertical', cax=cax)  #\n        cb.set_label('Intensity')\n\n        # =======================================\n        # Compare Unprobed to Estimated E-fields\n        # ======================================\n        fig, subplot = plt.subplots(2, n_nulls, figsize=(16, 12))\n        fig.subplots_adjust(wspace=0.5, right=0.85)\n        fig.suptitle('Compare Null Probed to Pairwise Probe Estimated Image Plane Intensity')\n        ax1, ax2, ax3, ax4 = subplot.flatten()\n\n        ax1.imshow(np.abs(fp_seq[-2]) ** 2,  # , 250:270, 150:170  *mask2D\n                   interpolation='none',\n                   norm=LogNorm(),\n                   # vmin=1e-8, vmax=1e-2\n                   )\n        ax1.set_title(f'Original Null Step 0')\n\n        ax2.imshow(np.abs(fp_seq[-1]) ** 2,  # , 250:270, 150:170  *mask2D\n                   interpolation='none',\n                   norm=LogNorm(),\n                   # vmin=1e-8, vmax=1e-2\n                   )\n        ax2.set_title(f'Original Null Step 1')\n\n        ax3.imshow(I_processed[0],  # , 250:270, 150:170  *mask2D\n                   interpolation='none',\n                   norm=LogNorm(),\n                   # vmin=1e-8, vmax=1e-2\n                   )\n        ax3.set_title(f'CDI Processed Null Step 0')\n\n        ax4.imshow(I_processed[1],  # , 250:270, 150:170  *mask2D\n                   interpolation='none',\n                   norm=LogNorm(),\n                   # vmin=1e-8, vmax=1e-2\n                   )\n        ax4.set_title(f'CDI Processed Null Step 1')\n\n        cax = fig.add_axes([0.9, 0.2, 0.03, 0.6])  # Add axes for colorbar @ position [left,bottom,width,height]\n        cb = fig.colorbar(im, orientation='vertical', cax=cax)  #\n        cb.set_label('Intensity')\n\n        # ==================\n        # View Time Series\n        # ==================\n        view_timeseries(cpx_to_intensity(fp_seq[:, 100:300, 300:500]), cdi, title=f\"White Light Timeseries\",\n                        subplt_cols=sp.tseries_cols,\n                        logZ=False,\n                        vlim=(1e-7, 1e-4),\n                        )\n\n        plt.show()\n\n\n##\ndef get_fp_mask(cdi, thresh=1e-7):\n    \"\"\"\n    returns a mask of the CDI probe pattern in focal plane coordinates\n\n    :param cdi: structure containing all CDI probe parameters\n    :param thresh: intensity threshold for determining probed coordinates\n    :return: fp_mask: boolean array where True marks the probed coordinates\n             imsk, jmsk:\n             irng, jrng:\n\n    \"\"\"\n    nx = sp.grid_size\n    ny = sp.grid_size\n    dm_act = cdi.nact\n\n    fftA = (1 / np.sqrt(2 * np.pi) *\n            np.fft.fftshift(np.fft.fft2(np.fft.ifftshift(cdi.DM_probe_series[0]))))\n\n    Ar = interpolate.interp2d(range(dm_act), range(dm_act), fftA.real, kind='cubic')\n    Ai = interpolate.interp2d(range(dm_act), range(dm_act), fftA.imag, kind='cubic')\n    ArI = Ar(np.linspace(0, dm_act, ny), np.linspace(0, dm_act, nx))\n    AiI = Ai(np.linspace(0, dm_act, ny), np.linspace(0, dm_act, nx))\n\n    fp_probe = np.sqrt(ArI**2 + AiI**2)\n    # fp_mask = (fp_probe > 1e-7)\n    # (imsk, jmsk) = (fp_probe > 1e-7).nonzero()\n    fp_mask = (fp_probe > thresh)\n    (imsk, jmsk) = (fp_probe > thresh).nonzero()\n\n    irng = range(min(imsk), max(imsk), 1)\n    jrng = range(min(jmsk), max(jmsk), 1)\n\n    imx = max(irng)-1  # -1 is to get index values for plotting purposes\n    imn = min(irng)-1\n    jmx = max(jrng)-1\n    jmn = min(jrng)-1\n\n    return fp_mask, imsk, jmsk, irng, jrng, imx, imn, jmx, jmn\n\n\n##\nif __name__ == '__main__':\n    dprint(f\"Testing CDI probe\")\n    cdi.use_cdi = True; cdishow_probe = True\n\n    cdi.probe_amp = 2e-6  # [m] probe amplitude, scale should be in units of actuator height limits\n    cdi.probe_w = 10  # [actuator coordinates] width of the probe\n    cdi.probe_h = 30  # [actuator coordinates] height of the probe\n    cdi.probe_shift = [5, 5]  # [actuator coordinates] center position of the probe\n    cdi.probe_spacing = 15\n\n    tp.act_tweeter = 49\n\n    sp.numframes = 10\n    cdi.gen_phaseseries()\n    cdi.init_probes(tp.act_tweeter)\n    # cdiphase_series = [-1*np.pi/4]\n    config_probe(cdi.phase_series[0], tp.act_tweeter)  #\n\n\n", "meta": {"hexsha": "44eb4e0c5c81921d12674d72a2889a985bdef45f", "size": 29016, "ext": "py", "lang": "Python", "max_stars_repo_path": "medis/CDI.py", "max_stars_repo_name": "jessmos/MEDIS", "max_stars_repo_head_hexsha": "eeea1904d31878fb3ad6444af144ee6f1d3ab705", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-25T17:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T17:35:42.000Z", "max_issues_repo_path": "medis/CDI.py", "max_issues_repo_name": "jessmos/MEDIS", "max_issues_repo_head_hexsha": "eeea1904d31878fb3ad6444af144ee6f1d3ab705", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-01-22T22:32:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-22T22:32:50.000Z", "max_forks_repo_path": "medis/CDI.py", "max_forks_repo_name": "jessmos/MEDIS", "max_forks_repo_head_hexsha": "eeea1904d31878fb3ad6444af144ee6f1d3ab705", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-24T23:25:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-24T23:25:34.000Z", "avg_line_length": 44.8469860896, "max_line_length": 170, "alphanum_fraction": 0.5768541494, "include": true, "reason": "import numpy,from scipy", "num_tokens": 8165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.15733364045025586}}
{"text": "\"\"\"Main module.\"\"\"\nimport os.path\nimport numpy as np\nfrom astropy.io import fits\nimport configparser\nimport copy\n\nfrom . import correlation_item, data, utils\nfrom vega.scale_parameters import ScaleParameters\nfrom vega.model import Model\nfrom vega.minimizer import Minimizer\nfrom vega.analysis import Analysis\nfrom vega.output import Output\nfrom vega.parameters.param_utils import get_default_values\nfrom vega.plots.plot import VegaPlots\n\n\nclass VegaInterface:\n    \"\"\"Main Vega class.\n\n    Parse the main config and initialize a correlation item for each component.\n\n    If there is data, initialize data and model objects for each component.\n\n    Handle the parameter config and call the analysis class.\n    \"\"\"\n    _blind = None\n\n    def __init__(self, main_path):\n        \"\"\"\n\n        Parameters\n        ----------\n        main_path : string\n            Path to main.ini config file\n        \"\"\"\n        # Read the main config file\n        self.main_config = configparser.ConfigParser()\n        self.main_config.optionxform = lambda option: option\n        self.main_config.read(utils.find_file(main_path))\n\n        # Read the fiducial pk file\n        self.fiducial = self._read_fiducial(self.main_config['fiducial'])\n\n        # Read the effective redshift and the data config paths\n        self.fiducial['z_eff'] = self.main_config['data sets'].getfloat('zeff')\n        write_cf = self.main_config['output'].getboolean('write_cf', False)\n        write_pk = self.main_config['output'].getboolean('write_pk', False)\n        self.fiducial['save-components'] = write_cf or write_pk\n        ini_files = self.main_config['data sets'].get('ini files').split()\n\n        # Initialize the individual components\n        self.corr_items = {}\n        for path in ini_files:\n            config = configparser.ConfigParser()\n            config.optionxform = lambda option: option\n            config.read(utils.find_file(os.path.expandvars(path)))\n\n            name = config['data'].get('name')\n            self.corr_items[name] = correlation_item.CorrelationItem(config)\n\n        # Check if all correlations have data files\n        self.data = {}\n        self._has_data = True\n        for name, corr_item in self.corr_items.items():\n            if not corr_item.has_data:\n                self._has_data = False\n\n        # Initialize the data\n        for name, corr_item in self.corr_items.items():\n            if self._has_data:\n                self.data[name] = data.Data(corr_item)\n            else:\n                self.data[name] = None\n\n        # Initialize scale parameters\n        self.scale_params = ScaleParameters(self.main_config['cosmo-fit type'])\n\n        # initialize the models\n        self.models = {}\n        if self._has_data:\n            for name, corr_item in self.corr_items.items():\n                self.models[name] = Model(corr_item, self.fiducial, self.scale_params,\n                                          self.data[name])\n\n        # Read parameters\n        self.params = self._read_parameters(self.corr_items, self.main_config['parameters'])\n        self.sample_params = self._read_sample(self.main_config['sample'])\n\n        # Check blinding\n        self._scale_par_names = ['ap', 'at', 'ap_sb', 'at_sb', 'phi', 'gamma', 'alpha',\n                                 'phi_smooth', 'gamma_smooth', 'alpha_smooth', 'aiso', 'epsilon']\n        if self._has_data:\n            self._blind = False\n            for data_obj in self.data.values():\n                if data_obj.blind:\n                    self._blind = True\n            if self._blind:\n                for par in self.sample_params['limits'].keys():\n                    if par in self._scale_par_names:\n                        raise ValueError('Running on blind data, please fix scale parameters')\n\n        # Get priors\n        self.priors = {}\n        if 'priors' in self.main_config:\n            self.priors = self._init_priors(self.main_config['priors'])\n            for param in self.priors.keys():\n                if param not in self.sample_params['limits'].keys():\n                    print('Warning: Prior specified for a parameter that is'\n                          ' not sampled!')\n\n        # Read the monte carlo parameters\n        self.mc_config = None\n        if 'monte carlo' in self.main_config:\n            self.mc_config = {}\n            config = self.main_config['monte carlo']\n\n            self.mc_config['params'] = copy.deepcopy(self.params)\n            mc_params = self.main_config['mc parameters']\n            for param, value in mc_params.items():\n                self.mc_config['params'][param] = float(value)\n\n            self.mc_config['sample'] = self._read_sample(config)\n\n        # Initialize the minimizer and the analysis objects\n        if not self.sample_params['limits']:\n            self.minimizer = None\n        else:\n            self.minimizer = Minimizer(self.chi2, self.sample_params)\n        self.analysis = Analysis(Minimizer(self.chi2, self.sample_params),\n                                 self.main_config, self.mc_config)\n\n        # Check for sampler\n        self.has_sampler = False\n        if 'control' in self.main_config:\n            self.has_sampler = self.main_config['control'].getboolean('sampler', False)\n            if self.has_sampler:\n                if 'Polychord' not in self.main_config:\n                    raise RuntimeError('run_sampler called, but no sampler initialized')\n\n        self.output = Output(self.main_config['output'], self.data, self.corr_items, self.analysis)\n\n        self.monte_carlo = False\n        self.plots = None\n        if self._has_data:\n            self.plots = VegaPlots(vega_data=self.data)\n\n    def compute_model(self, params=None, run_init=True, direct_pk=None):\n        \"\"\"Compute correlation function model using input parameters.\n\n        Parameters\n        ----------\n        params : dict, optional\n            Computation parameters, by default None\n        run_init: boolean, optional\n            Whether to run model.init() before computing the model, by default True\n        direct_pk: 1D array or None, optional\n            If not None, the full Pk (e.g. from CLASS/CAMB) to be used directly, by default None\n\n        Returns\n        -------\n        dict\n            Dictionary of cf models for each component\n        \"\"\"\n        # Overwrite computation parameters\n        local_params = copy.deepcopy(self.params)\n        if params is not None:\n            for par, val in params.items():\n                local_params[par] = val\n\n        # Go through each component and compute the model cf\n        model_cf = {}\n        if run_init:\n            self.models = {}\n        for name, corr_item in self.corr_items.items():\n            if run_init:\n                self.models[name] = Model(corr_item, self.fiducial, self.scale_params,\n                                          self.data[name])\n\n            if direct_pk is None:\n                model_cf[name] = self.models[name].compute(local_params, self.fiducial['pk_full'],\n                                                           self.fiducial['pk_smooth'])\n            else:\n                model_cf[name] = self.models[name].compute_direct(local_params, direct_pk)\n\n        return model_cf\n\n    def chi2(self, params=None, direct_pk=None):\n        \"\"\"Compute full chi2 for all components.\n\n        Parameters\n        ----------\n        params : dict, optional\n            Computation parameters, by default None\n        direct_pk: 1D array or None, optional\n            If not None, the full Pk (e.g. from CLASS/CAMB) to be used directly, by default None\n\n        Returns\n        -------\n        float\n            chi^2\n        \"\"\"\n        assert self._has_data\n\n        # Check if blinding is initialized\n        if self._blind is None:\n            self._blind = False\n            for data_obj in self.data.values():\n                if data_obj.blind:\n                    self._blind = True\n\n        # Overwrite computation parameters\n        local_params = copy.deepcopy(self.params)\n        if params is not None:\n            for par, val in params.items():\n                local_params[par] = val\n\n        # Enforce blinding\n        if self._blind:\n            for par, val in local_params.items():\n                if par in self._scale_pars:\n                    local_params[par] = 1.\n\n        # Go trough each component and compute the chi^2\n        chi2 = 0\n        for name in self.corr_items:\n            try:\n                if direct_pk is None:\n                    model_cf = self.models[name].compute(local_params, self.fiducial['pk_full'],\n                                                         self.fiducial['pk_smooth'])\n                else:\n                    model_cf = self.models[name].compute_direct(local_params, direct_pk)\n            except utils.VegaBoundsError:\n                self.models[name].PktoXi.cache_pars = None\n                return 1e100\n\n            if self.monte_carlo:\n                diff = self.data[name].masked_mc_mock - model_cf[self.data[name].mask]\n                chi2 += diff.T.dot(self.data[name].scaled_inv_masked_cov.dot(diff))\n            else:\n                diff = self.data[name].masked_data_vec - model_cf[self.data[name].mask]\n                chi2 += diff.T.dot(self.data[name].inv_masked_cov.dot(diff))\n\n        # Add priors\n        for param, prior in self.priors.items():\n            chi2 += self._gaussian_chi2_prior(local_params[param], prior[0], prior[1])\n\n        assert isinstance(chi2, float)\n        return chi2\n\n    def log_lik(self, params=None, direct_pk=None):\n        \"\"\"Compute full log likelihood for all components.\n\n        Parameters\n        ----------\n        params : dict, optional\n            Computation parameters, by default None\n        direct_pk: 1D array or None, optional\n            If not None, the full Pk (e.g. from CLASS/CAMB) to be used directly, by default None\n\n        Returns\n        -------\n        float\n            log Likelihood\n        \"\"\"\n        assert self._has_data\n\n        # Get the full chi2\n        chi2 = self.chi2(params, direct_pk)\n\n        # Compute the normalization for each component\n        log_norm = 0\n        for name in self.corr_items:\n            log_norm -= 0.5 * self.data[name].data_size * np.log(2 * np.pi)\n\n            if self.monte_carlo:\n                log_norm -= 0.5 * self.data[name].scaled_log_cov_det\n            else:\n                log_norm -= 0.5 * self.data[name].log_cov_det\n\n        # Compute log lik\n        log_lik = log_norm - 0.5 * chi2\n\n        # Add priors normalization\n        for param, prior in self.priors.items():\n            log_lik += self._gaussian_lik_prior(prior[1])\n\n        return log_lik\n\n    def monte_carlo_sim(self, params=None, scale=None, seed=0, forecast=False):\n        \"\"\"Compute Monte Carlo simulations for each Correlation item.\n\n        Parameters\n        ----------\n        params : dict, optional\n            Computation parameters, by default None\n        scale : float/dict, optional\n            Scaling for the covariance, by default 1.\n        seed : int, optional\n            Seed for the random number generator, by default 0\n        forecast : boolean, optional\n            Forecast option. If true, we don't add noise to the mock,\n            by default False\n\n        Returns\n        -------\n        dict\n            Dictionary with MC mocks for each item\n        \"\"\"\n        assert self._has_data\n\n        # Overwrite computation parameters\n        local_params = copy.deepcopy(self.params)\n        if params is not None:\n            for par, val in params.items():\n                local_params[par] = val\n\n        mocks = {}\n        for name in self.corr_items:\n            # Compute fiducial model\n            fiducial_model = self.models[name].compute(\n                local_params, self.fiducial['pk_full'],\n                self.fiducial['pk_smooth'])\n\n            # Get scale\n            if scale is None:\n                item_scale = self.corr_items[name].cov_rescale\n            elif type(scale) is float or type(scale) is int:\n                item_scale = scale\n            elif name in scale:\n                item_scale = scale[name]\n            else:\n                item_scale = 1.\n\n            # Create the mock\n            mocks[name] = self.data[name].create_monte_carlo(fiducial_model, item_scale, seed,\n                                                             forecast)\n\n        self.monte_carlo = True\n        return mocks\n\n    def minimize(self):\n        \"\"\"Minimize the chi2 over the sampled parameters.\n        \"\"\"\n        if self.minimizer is None:\n            print(\"No sampled parameters. Skipping minimization.\")\n            return\n\n        # if not self.fiducial['save-components']:\n            # self.set_fast_metals()\n\n        self.minimizer.minimize()\n\n    @property\n    def bestfit(self):\n        \"\"\"Access the bestfit results from iminuit.\n\n        Returns\n        -------\n        Minimizer\n            Returns the Minimizer class which stores the bestfit values\n        \"\"\"\n        return self.minimizer\n\n    def set_fast_metals(self):\n        \"\"\"Activate fast metals. This is automatically called when\n        running the minimizer or the sampler.\n        \"\"\"\n        print('Warning! Activating fast metals for minimizing/sampling.')\n        for name in self.corr_items:\n            if self.models[name].metals is not None:\n                self.models[name].metals.fast_metals = True\n\n    @staticmethod\n    def _read_fiducial(fiducial_config):\n        \"\"\"Read the fiducial pk file and get the configs.\n\n        Parameters\n        ----------\n        fiducial_config : ConfigParser\n            fiducial section from the main config file\n\n        Returns\n        -------\n        dict\n            dictionary with the fiducial data and config\n        \"\"\"\n        # First check the path and replace with the right model if necessary\n        path = fiducial_config.get('filename')\n        path = utils.find_file(os.path.expandvars(path))\n        # if not os.path.isfile(path):\n        # path = resource_filename('vega', 'models') + '/{}'.format(path)\n        print('INFO: reading input Pk {}'.format(path))\n\n        fiducial = {}\n\n        # Open the fits file and get what we need\n        hdul = fits.open(path)\n        fiducial['z_fiducial'] = hdul[1].header['ZREF']\n        fiducial['Omega_m'] = hdul[1].header['OM']\n        fiducial['Omega_de'] = hdul[1].header['OL']\n        fiducial['k'] = hdul[1].data['K']\n        fiducial['pk_full'] = hdul[1].data['PK']\n        fiducial['pk_smooth'] = hdul[1].data['PKSB']\n        hdul.close()\n\n        return fiducial\n\n    @staticmethod\n    def _read_parameters(corr_items, parameters_config):\n        \"\"\"Read computation parameters.\n\n        If a parameter is specified multiple times,\n        the parameters in the main config file have priority.\n\n        Parameters\n        ----------\n        corr_items : dict\n            Dictionary of correlation items\n        parameters_config : ConfigParser\n            parameters section from main config\n\n        Returns\n        -------\n        dict\n            Computation parameters\n        \"\"\"\n        params = {}\n\n        # First get the parameters from each component config\n        for name, corr_item in corr_items.items():\n            if 'parameters' in corr_item.config:\n                for param, value in corr_item.config.items('parameters'):\n                    params[param] = float(value)\n\n        # Next get the parameters in the main config\n        for param, value in parameters_config.items():\n            params[param] = float(value)\n\n        return params\n\n    def _read_sample(self, sample_config):\n        \"\"\"Read sample parameters.\n\n        These must be of the form:\n\n        param = min max / for sampler only\n        or\n        param = min max val err / for both sampler and fitter.\n\n        Fitter accepts None for min/max, but the sampler does not.\n\n        Parameters\n        ----------\n        sample_config : ConfigParser\n            sample section from main config\n\n        Returns\n        -------\n        dict\n            Config for the sampled parameters\n        \"\"\"\n        # Initialize the dictionaries we need\n        sample_params = {}\n        sample_params['limits'] = {}\n        sample_params['values'] = {}\n        sample_params['errors'] = {}\n        sample_params['fix'] = {}\n\n        default_values = get_default_values()\n\n        def check_param(param):\n            if param not in default_values:\n                raise ValueError('Default values not found for: %s. Please add'\n                                 ' them to default_values.txt, or provide the'\n                                 ' full sampling specification.' % param)\n\n        for param, values in sample_config.items():\n            if param not in self.params:\n                print('Warning: You tried sampling the parameter: %s.'\n                      ' As this parameter was not specified under'\n                      ' [parameters], it will be skipped.' % param)\n                continue\n\n            values_list = values.split()\n\n            # Get the prior limits\n            # ! Sampler needs actual values (no None)\n            if len(values_list) > 1:\n                lower_limit = None\n                upper_limit = None\n                if values_list[0] != 'None':\n                    lower_limit = float(values_list[0])\n                if values_list[1] != 'None':\n                    upper_limit = float(values_list[1])\n                sample_params['limits'][param] = (lower_limit, upper_limit)\n            else:\n                if values_list[0] not in ['True', 'true', 't', 'y', 'yes']:\n                    continue\n                check_param(param)\n                sample_params['limits'][param] = default_values[param]['limits']\n\n            # Get the values and errors for the fitter\n            if len(values_list) > 2:\n                sample_params['values'][param] = float(values_list[2])\n            else:\n                check_param(param)\n                sample_params['values'][param] = self.params[param]\n\n            if len(values_list) > 3:\n                assert len(values_list) == 4\n                sample_params['errors'][param] = float(values_list[3])\n            else:\n                check_param(param)\n                sample_params['errors'][param] = default_values[param]['error']\n\n            # Populate the fix values\n            sample_params['fix'][param] = False\n\n        return sample_params\n\n    @staticmethod\n    def _gaussian_chi2_prior(value, mean, sigma):\n        return (value - mean)**2 / sigma**2\n\n    @staticmethod\n    def _gaussian_lik_prior(sigma):\n        return -0.5 * np.log(2 * np.pi) - np.log(sigma)\n\n    @staticmethod\n    def _init_priors(prior_config):\n        \"\"\"Initialize the priors. Only gaussian priors are currently supported\n\n        Parameters\n        ----------\n        prior_config : ConfigParser\n            priors section from main config\n\n        Returns\n        -------\n        dict\n            Dictionary of priors (mean, sigma) with the keys as parameter names\n        \"\"\"\n        prior_dict = {}\n        for param, prior in prior_config.items():\n            prior_list = prior.split()\n            if len(prior_list) != 3:\n                raise ValueError('Prior configuration must have the format:'\n                                 ' \"<param> = gaussian <mean> <sigma>\"')\n            if prior_list[0] not in ['gaussian', 'Gaussian']:\n                raise ValueError('Only gaussian priors are supported.')\n\n            prior_dict[param] = np.array(prior_list[1:]).astype(float)\n\n        return prior_dict\n", "meta": {"hexsha": "3f41690afb51e4afc90f79b8412abf8267917441", "size": 19629, "ext": "py", "lang": "Python", "max_stars_repo_path": "vega/vega_interface.py", "max_stars_repo_name": "andreicuceu/lyafit", "max_stars_repo_head_hexsha": "08ef5e91a33071409ce7cc4cec9300ba45e70c6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vega/vega_interface.py", "max_issues_repo_name": "andreicuceu/lyafit", "max_issues_repo_head_hexsha": "08ef5e91a33071409ce7cc4cec9300ba45e70c6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2020-02-11T15:27:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T13:59:16.000Z", "max_forks_repo_path": "vega/vega_interface.py", "max_forks_repo_name": "andreicuceu/lyafit", "max_forks_repo_head_hexsha": "08ef5e91a33071409ce7cc4cec9300ba45e70c6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3039568345, "max_line_length": 99, "alphanum_fraction": 0.5689031535, "include": true, "reason": "import numpy,from astropy", "num_tokens": 4132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.15728020406552973}}
{"text": "# ---\n# jupyter:\n#   jupytext:\n#     text_representation:\n#       extension: .py\n#       format_name: light\n#       format_version: '1.5'\n#       jupytext_version: 1.11.3\n#   kernelspec:\n#     display_name: Python 3\n#     language: python\n#     name: python3\n# ---\n\n# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# <a href=\"https://colab.research.google.com/github/probml/pyprobml/blob/master/book2/rl/Tabular_SARSA.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n\n# + [markdown] id=\"qwWX1CpCAvwp\"\n# # Tabular Sarsa Algorithm and the Taxi Environment\n#\n# Authors: Fred Amouzgar <fred.amouzgar@mq.edu.au> and Kevin Murphy <murphyk@gmail.com>\n#\n#\n# Tabular methods are suitable for small and discrete state space and discrete action space environments. So, the state-action function (Q) can be represented by a table of values. For large state space environments, we prefer to use approximation methods such as neural networks. However, the simplicity of tabular methods' implementation is helpful to demonstrate RL method's functionality.  In this notebook, we train a SARSA agent for [OpenAI's Taxi Gym](https://gym.openai.com/envs/Taxi-v2/) environment (an example originally proposed by Tom Dietterich).\n\n# + [markdown] id=\"IphbO1Y2BQ-J\"\n# ## 1- Installations\n\n# + id=\"IYHrnYXTBuXe\"\n\ntry:\n    # # %tensorflow_version only exists in Colab.\n    # %tensorflow_version 2.x\n    IS_COLAB = True\nexcept Exception:\n    IS_COLAB = False\n\nif not(IS_COLAB):    \n  print('not a colab')\n  # !pip -q install gym numpy matplotlib \n\n# + [markdown] id=\"vrJGjKw-B6X7\"\n# ## 2- Setting up the Environment\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"NA58-PytB44R\" outputId=\"6a1ab6ba-6fa9-454a-d3cc-173d7eba1f1f\"\nimport gym\n\n# Finding the Taxi environment\nfor env in gym.envs.registry.all():\n    if env.id.startswith(\"Taxi\"):\n        env_name = env.id\n##\n\n\nprint(\"Environment Name:\", env_name)\nenv = gym.make(env_name)\nenv.reset()\nenv.render()\n\n# + [markdown] id=\"N2q3JJNoIcdP\"\n# Here is a description of the taxi environment from the [docstring](https://github.com/openai/gym/blob/master/gym/envs/toy_text/taxi.py).\n#\n#\n# ### Description:\n#\n# There are four designated locations in the grid world indicated by R(ed), G(reen), Y(ellow), and B(lue). When the episode starts, the taxi starts off at a random square and the passenger is at a random location. The taxi drives to the passenger's location, picks up the passenger, drives to the passenger's destination (another one of the four specified locations), and then drops off the passenger. Once the passenger is dropped off, the episode ends.\n#\n# ### States/ Observations:\n#\n# State space is (taxi_row, taxi_col, passenger_location, destination).\n#\n# There are 500 discrete states since there are 25 taxi positions, 5 possible locations of the passenger (including the case when the passenger is in the taxi), and 4 destination locations. \n#\n#\n# ### Passenger locations:\n# - 0: R(ed)\n# - 1: G(reen)\n# - 2: Y(ellow)\n# - 3: B(lue)\n# - 4: in taxi\n#\n# ### Destinations:\n# - 0: R(ed)\n# - 1: G(reen)\n# - 2: Y(ellow)\n# - 3: B(lue)\n#\n# ### Actions:\n#\n# There are 6 discrete deterministic actions:\n# - 0: move south\n# - 1: move north\n# - 2: move east\n# - 3: move west\n# - 4: pickup passenger\n# - 5: drop off passenger\n#\n#\n# Notice in this environment the taxi cannot perform certain actions in certain states due to walls. In environment's code, we will simply provide a -1 penalty for every wall hit and the taxi won't move anywhere. This will just rack up penalties causing the taxi to consider going around the wall.\n#\n# ### Rewards:\n#\n# There is a default per-step reward of -1,\n# except for delivering the passenger, which is +20,\n# or executing \"pickup\" and \"drop-off\" actions illegally, which is -10.\n#\n# ### Rendering:\n# - blue: passenger\n# - magenta: destination\n# - yellow: empty taxi\n# - green: full taxi\n# - other letters (R, G, Y and B): locations for passengers and destinations\n#\n#\n\n# + [markdown] id=\"2U7EBEtzCyhH\"\n# ## 3- Developing the SARSA agent\n#\n# <img src=\"https://github.com/probml/pyprobml/blob/master/book2/rl/figures/SARSA_algorithm.png?raw=1\" width=\"800\">\n#\n# Here's the full update formula covered in line 7 and 8:\n# <img src=\"https://github.com/probml/pyprobml/blob/master/book2/rl/figures/SARSA_formula.png?raw=1\" width=\"500\">\n\n# + id=\"FFghKMePC4tl\"\nimport numpy as np\nimport pickle\n\nclass Sarsa_Agent:\n    def __init__(self, states_n, actions_n, learning_rate=0.2, epsilon=0.1, gamma=0.95, epsilon_decay=True,\n                 epsilon_decay_factor=0.01):\n        self.learning_rate = learning_rate\n        self.epsilon = epsilon\n        self.gamma = gamma\n        self.states_n = states_n\n        self.actions_n = actions_n\n        self.Q = np.zeros((states_n, actions_n))\n        self.new_a = None\n        self.epsilon_decay = epsilon_decay\n        self.epsilon_decay_factor = epsilon_decay_factor\n\n    def act(self, state):\n        \"\"\"The act method implements the epsilon-greedy policy\"\"\"\n        if np.random.rand() < self.epsilon:\n            act = np.random.choice(np.arange(self.actions_n))\n        else:\n            act = np.argmax(self.Q[int(state), :])\n        return act\n\n    def decay_epsilon(self, factor):\n        \"\"\"Decaying the epsilon, so it gradualy reduces the exploration and exploits more\"\"\"\n        self.epsilon -= factor if self.epsilon >= 0 else 0\n\n    def update(self, new_s, r, s, a, done):\n        \"\"\"The update method updates the agent for one step\"\"\"\n        self.new_a = self.act(new_s)\n        mask = 0 if done else 1\n        s, a, self.new_a, new_s = int(s), int(a), int(self.new_a), int(new_s)\n        self.Q[s, a] += self.learning_rate * (r + self.gamma * self.Q[new_s, self.new_a] * mask - self.Q[s, a])\n        if done and self.epsilon_decay:\n            self.decay_epsilon(self.epsilon_decay_factor)\n        return self.new_a\n\n    def save(self, file_name=\"taxi.pkl\"):\n        \"\"\"The save method saves (pickles) the agent's Q table\"\"\"\n        with open(file_name, mode=\"wb\") as f:\n            pickle.dump(self.Q, f)\n\n    def load(self, file_name=\"taxi.pkl\"):\n        \"\"\"The load method loads a pickled Q table\"\"\"\n        with open(file_name, mode=\"rb\") as f:\n            self.Q = pickle.load(f)\n\n\n# + [markdown] id=\"mmSjC-diEcQS\"\n# ## 4- Defining the Training Loop\n\n# + id=\"oMOOyLDdEhtJ\"\nfrom IPython.display import clear_output\nimport matplotlib.pyplot as plt\nfrom time import sleep\nimport numpy as np\n\ndef train_taxi(env, agent, episodes=150):\n    if env is None:\n        raise ValueError(\"No Environment is given.\")\n    if agent is None:\n        raise ValueError(\"No agent is given.\")\n\n    steps = []\n    returns = []\n    for episode in range(episodes):\n        state = env.reset()\n        action = agent.act(state)\n        done = False\n        step_n = 0\n        return_episode = 0\n        while not done:\n            new_state, reward, done, _ = env.step(action)\n            return_episode += reward\n            new_action = agent.update(new_state,reward,state,action,done)\n            state, action = new_state, new_action\n            step_n += 1\n            if done:\n                steps.append(step_n)\n                returns.append(return_episode)\n                clear_output(wait=True)\n                plt.title(\"Steps:\" + str(step_n) + \" Return:\"+str(return_episode))\n                plt.plot(list(range(len(steps))),steps)\n                plt.plot(list(range(len(steps))),returns)\n                plt.legend([\"Steps\", \"Returns\"])\n                plt.show()\n\n\n# + [markdown] id=\"-AEYmZgQFB_w\"\n# ## 5- Let's train our agent for 1500 episodes (takes ~5 minutes)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 281} id=\"1GV0owZVEoQ0\" outputId=\"5bb38dc9-bcfe-4a61-bfda-7c70313a7cc8\"\nagent = Sarsa_Agent(env.observation_space.n, env.action_space.n,epsilon_decay=True)\n\ntrain_taxi(env, agent, episodes=1500)\nagent.save()\n\n\n# + [markdown] id=\"XS2D27_CmdpM\"\n# ## 6- Methods for Playing and Rendering the Taxi environment in the notebook\n\n# + id=\"HLiUntsMmPU0\"\ndef taxi_print_frames(frames, wait_btw_frames, episode):\n    for i, frame in enumerate(frames):\n        clear_output(wait=True)\n        print(frame['frame'])\n        print(f\"Passenger #: {episode + 1}\")\n        print(\"-----------\")\n        print(f\"Timestep: {i + 1}\")\n        print(f\"State: {frame['state']}\")\n        print(f\"Action: {frame['action']}\")\n        print(f\"Reward: {frame['reward']}\")\n        sleep(wait_btw_frames)\n        \ndef play_taxi(env, agent, passengers=2, wait_btw_frames=1):\n    for episode in range(passengers):\n        state = env.reset()\n        frames = []\n        done = False\n        step = 0\n        while not done:\n            action = agent.act(state)\n            new_state, reward, done, _ = env.step(action)\n            frames.append({\n                'frame': env.render(mode='ansi'),\n                'state': state,\n                'action': action,\n                'reward': reward\n            })\n            step += 1\n            state = new_state\n        taxi_print_frames(frames, wait_btw_frames=wait_btw_frames, episode=episode)\n\n\n# + [markdown] id=\"qUqhWVoeng_-\"\n# ## 7- Watch a Trained SARSA Cab Driver\n#\n# Note: You can change the number of passengers if you want to move more than 3. Change the wait_btw_frames if you want to see the game running faster or slower.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Zmyw9mKsmRZs\" outputId=\"8dfe9b5a-4084-4779-95c7-26431ba2f4c5\"\nplay_taxi(env, agent, passengers=3, wait_btw_frames=1)\n", "meta": {"hexsha": "8cf393d77a06a1808b5274b00fc4e9891294bc6c", "size": 9541, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks-text-format/Tabular_SARSA.py", "max_stars_repo_name": "arpitvaghela/probml-notebooks", "max_stars_repo_head_hexsha": "32ecb309dd474b989fd1c6ce4ad6dab7a25bbead", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 166, "max_stars_repo_stars_event_min_datetime": "2021-07-16T17:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:35:34.000Z", "max_issues_repo_path": "notebooks-text-format/Tabular_SARSA.py", "max_issues_repo_name": "arpitvaghela/probml-notebooks", "max_issues_repo_head_hexsha": "32ecb309dd474b989fd1c6ce4ad6dab7a25bbead", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2021-07-21T16:31:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:50:13.000Z", "max_forks_repo_path": "notebooks-text-format/Tabular_SARSA.py", "max_forks_repo_name": "arpitvaghela/probml-notebooks", "max_forks_repo_head_hexsha": "32ecb309dd474b989fd1c6ce4ad6dab7a25bbead", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 48, "max_forks_repo_forks_event_min_datetime": "2021-07-17T08:26:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T03:36:18.000Z", "avg_line_length": 35.734082397, "max_line_length": 560, "alphanum_fraction": 0.6538098732, "include": true, "reason": "import numpy", "num_tokens": 2600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.3380771174808128, "lm_q1q2_score": 0.15717258316221555}}
{"text": "r\"\"\"\nHPF Spectrum\n---------------\n\nA container for an HPF spectrum of :math:`M=28` total total orders :math:`m`, each with vectors for wavelength flux and uncertainty, e.g. :math:`F_m(\\lambda)`.  HPF additionally has a sky fiber and optionally a Laser Frequency Comb fiber.  Our experimental API currently ignores the LFC fiber.  The sky fiber can be accessed by passing the `sky=True` kwarg when retrieving the\n\n\nHPFSpectrum\n##############\n\"\"\"\n\nimport warnings\nimport logging\nfrom muler.echelle import EchelleSpectrum, EchelleSpectrumList\nimport numpy as np\nimport astropy\nfrom astropy.io import fits\nfrom astropy import units as u\nfrom astropy.wcs import WCS, FITSFixedWarning\nfrom astropy.nddata import StdDevUncertainty\nfrom scipy.interpolate import InterpolatedUnivariateSpline\nfrom astropy.constants import R_jup, R_sun, G, M_jup, R_earth, c\nfrom astropy.time import Time\nimport copy\nfrom importlib_resources import files\nfrom specutils.manipulation import LinearInterpolatedResampler\nfrom scipy.ndimage import binary_dilation\nfrom . import templates\nimport pandas as pd\n\nlog = logging.getLogger(__name__)\n\nfor category in [\n    astropy.utils.exceptions.AstropyDeprecationWarning,\n    FITSFixedWarning,\n    RuntimeWarning,\n]:\n    warnings.filterwarnings(\"ignore\", category=category)\n\n\n# Convert FITS running index number to echelle order m\ngrating_order_offsets = {\"Goldilocks\": 0, \"HPF\": 0}  # Not implemented yet\n\n# Science-to-sky fiber throughput ratio template\nstatic_sky_ratio_file = files(templates).joinpath(\"HPF_sci_to_sky_ratio_beta.csv\")\nSTATIC_SKY_RATIO_DATAFRAME = pd.read_csv(static_sky_ratio_file)\n\n# Blaze function template\nstatic_blaze_file = files(templates).joinpath(\"HPF_blaze_templates.csv\")\nSTATIC_BLAZE_DATAFRAME = pd.read_csv(static_blaze_file)\n\n# A0V template\nstatic_A0V_file = files(templates).joinpath(\"PHOENIX_10kK_hpf_template.csv\")\nSTATIC_A0V_DATAFRAME = pd.read_csv(static_A0V_file)\n\n# TelFit template\nstatic_telfit_file = files(templates).joinpath(\"telfit_HPFtemplate_temp286_hum050.csv\")\nSTATIC_TELFIT_DATAFRAME = pd.read_csv(static_telfit_file)\n\n\nclass HPFSpectrum(EchelleSpectrum):\n    r\"\"\"\n    A container for HPF spectra\n\n    Args:\n        file (str): A path to a reduced HPF spectrum from Goldilocks *or* the HPF instrument team\n        order (int): which spectral order to read\n        cached_hdus (list) :\n            A pre-loaded HDU to reduce file I/O for multiorder access.\n            If provided, must give both HDUs.  Optional, default is None.\n    \"\"\"\n\n    def __init__(self, *args, file=None, order=19, cached_hdus=None, **kwargs):\n\n        self.site_name = \"mcdonald\"\n        self.ancillary_spectra = [\"sky\", \"lfc\"]\n        self.noisy_edges = (3, 2045)\n        self.instrumental_resolution = 55_000.0\n\n        if file is not None:\n            if \"Goldilocks\" in file:\n                pipeline = \"Goldilocks\"\n            elif \"Slope\" in file:\n                pipeline = \"HPF\"\n            else:\n                raise NameError(\"Cannot identify file as an HPF spectrum\")\n            grating_order = grating_order_offsets[pipeline] + order\n\n            if cached_hdus is not None:\n                hdus = cached_hdus[0]\n            else:\n                hdus = fits.open(str(file))\n            hdr = hdus[0].header\n\n            ## Target Spectrum\n            lamb = hdus[7].data[order].astype(np.float64) * u.AA\n            flux = hdus[1].data[order].astype(np.float64) * u.ct\n            unc = hdus[4].data[order].astype(np.float64) * u.ct\n            if pipeline == \"HPF\":\n                unc = np.sqrt(unc.value) * u.ct\n\n            meta_dict = {\n                \"x_values\": np.arange(0, 2048, 1, dtype=np.int),\n                \"pipeline\": pipeline,\n                \"m\": grating_order,\n                \"header\": hdr,\n            }\n\n            uncertainty = StdDevUncertainty(unc)\n            mask = (\n                np.isnan(flux) | np.isnan(uncertainty.array) | (uncertainty.array <= 0)\n            )\n\n            super().__init__(\n                spectral_axis=lamb,\n                flux=flux,\n                mask=mask,\n                wcs=None,\n                uncertainty=uncertainty,\n                meta=meta_dict,\n                **kwargs,\n            )\n\n            ## Sky Spectrum\n            lamb = hdus[8].data[order].astype(np.float64) * u.AA\n            flux = hdus[2].data[order].astype(np.float64) * u.ct\n            unc = hdus[5].data[order].astype(np.float64) * u.ct\n            if pipeline == \"HPF\":\n                unc = np.sqrt(unc.value) * u.ct\n            uncertainty = StdDevUncertainty(unc)\n            mask = (\n                np.isnan(flux) | np.isnan(uncertainty.array) | (uncertainty.array <= 0)\n            )\n            sky_spectrum = HPFSpectrum(\n                spectral_axis=lamb,\n                flux=flux,\n                mask=mask,\n                wcs=None,\n                uncertainty=uncertainty,\n                meta=meta_dict.copy(),\n                **kwargs,\n            )\n\n            ## LFC Spectrum\n            lamb = hdus[9].data[order].astype(np.float64) * u.AA\n            flux = hdus[3].data[order].astype(np.float64) * u.ct\n            unc = hdus[6].data[order].astype(np.float64) * u.ct\n            if pipeline == \"HPF\":\n                unc = np.sqrt(unc.value) * u.ct\n            uncertainty = StdDevUncertainty(unc)\n            mask = (\n                np.isnan(flux) | np.isnan(uncertainty.array) | (uncertainty.array <= 0)\n            )\n            lfc_spectrum = HPFSpectrum(\n                spectral_axis=lamb,\n                flux=flux,\n                mask=mask,\n                wcs=None,\n                uncertainty=uncertainty,\n                meta=meta_dict.copy(),\n                **kwargs,\n            )\n\n            ## We could optionally enable lfc and sky metadata for these referece spectra\n            ## That's slightly redundant, it enables antipatterns like:\n            # `spectrum.sky.lfc` rather than simply `spectrum.lfc`\n\n            # sky_spectrum.meta[\"lfc\"] = lfc_spectrum\n            # lfc_spectrum.meta[\"sky\"] = sky_spectrum\n\n            sky_spectrum.meta[\"provenance\"] = \"Sky fiber\"\n            lfc_spectrum.meta[\"provenance\"] = \"Laser Frequency Comb\"\n            self.meta[\"provenance\"] = \"Target fiber\"\n\n            self.meta[\"sky\"] = sky_spectrum\n            self.meta[\"lfc\"] = lfc_spectrum\n\n        else:\n            super().__init__(*args, **kwargs)\n\n    @property\n    def provenance(self):\n        \"\"\"What is the provenance of each spectrum?\"\"\"\n        return self.meta[\"provenance\"]\n\n    @property\n    def pipeline(self):\n        \"\"\"Which pipeline does this spectrum originate from?\"\"\"\n        return self.meta[\"pipeline\"]\n\n    @property\n    def spectrographname(self):\n        \"\"\"What's the name of the spectrograph?\"\"\"\n        return \"HPF\"\n\n    @property\n    def sky(self):\n        \"\"\"Sky fiber spectrum stored as its own HPFSpectrum object\"\"\"\n        return self.meta[\"sky\"]\n\n    @property\n    def lfc(self):\n        \"\"\"Sky fiber spectrum stored as its own HPFSpectrum object\"\"\"\n        return self.meta[\"lfc\"]\n\n    @property\n    def RA(self):\n        \"\"\"The right ascension from header files\"\"\"\n        return self.meta[\"header\"][\"RA\"] * u.hourangle\n\n    @property\n    def DEC(self):\n        \"\"\"The declination from header files\"\"\"\n        return self.meta[\"header\"][\"DEC\"] * u.deg\n\n    @property\n    def astropy_time(self):\n        \"\"\"The astropy time based on the header\"\"\"\n        mjd = self.meta[\"header\"][\"DATE-OBS\"]\n        return Time(mjd, format=\"isot\", scale=\"utc\")\n\n    def get_static_blaze_template(self, method=\"Goldilocks\"):\n        \"\"\"Get the static blaze template for HPF, as estimated by Goldilocks\n\n        Parameters\n        ----------\n        method : (Str)\n            Either \"Goldilocks\" or \"2021_median\" (default: Goldilocks)\n        \"\"\"\n        type_dict = {\"Goldilocks\": \"blaze_Goldilocks\", \"2021_median\": \"blaze_2021\"}\n        assert method in type_dict.keys()\n        blaze_type = type_dict[method]\n\n        # Watch out! Some HPFSpectrum methods *will not work* on this calibration spectrum!\n        return HPFSpectrum(\n            spectral_axis=STATIC_BLAZE_DATAFRAME.wavelength_Angstrom.values\n            * u.Angstrom,\n            flux=STATIC_BLAZE_DATAFRAME[blaze_type].values * u.dimensionless_unscaled,\n        )\n\n    def get_static_sky_ratio_template(self):\n        \"\"\"Get the static sky ratio template for HPF, as estimated from twilight flats\"\"\"\n\n        # Watch out! Some HPFSpectrum methods *will not work* on this calibration spectrum!\n        return HPFSpectrum(\n            spectral_axis=STATIC_SKY_RATIO_DATAFRAME.wave_Ang.values * u.Angstrom,\n            flux=STATIC_SKY_RATIO_DATAFRAME.beta_estimator.values\n            * u.dimensionless_unscaled,\n        )\n\n    def get_static_A0V_template(self, method=\"PHOENIX\"):\n        \"\"\"Get the static A0V template for HPF, as estimated by either Vega or PHOENIX\n\n        Parameters\n        ----------\n        method : (Str)\n            What template to use.  Currently only a state PHOENIX model is supported.\n            Other A0V templates may be added in the future, such as Vega.\n            (default: PHOENIX)\n        \"\"\"\n        if method == \"PHOENIX\":\n\n            return HPFSpectrum(\n                spectral_axis=STATIC_A0V_DATAFRAME.wave_ang.values * u.Angstrom,\n                flux=STATIC_A0V_DATAFRAME.flux.values * u.dimensionless_unscaled,\n            )\n        else:\n            raise NotImplementedError\n\n    def get_static_TelFit_template(self):\n        \"\"\"Get the static TelFit template for HPF\n\n        A convenience function for getting a quicklook Telluric template\n        \"\"\"\n\n        return HPFSpectrum(\n            spectral_axis=STATIC_TELFIT_DATAFRAME.wavelength_A.values * u.Angstrom,\n            flux=STATIC_TELFIT_DATAFRAME.transmission.values * u.dimensionless_unscaled,\n        )\n\n    def _deblaze_by_template(self):\n        \"\"\"Deblazing with a template-based method\"\"\"\n        blaze_template = self.get_static_blaze_template(method=\"Goldilocks\")\n        resampler = LinearInterpolatedResampler()\n        resampled_blaze = resampler(blaze_template, self.wavelength)\n        return self.divide(resampled_blaze, handle_meta=\"first_found\")\n\n    def deblaze(self, method=\"template\"):\n        \"\"\"Override the default spline deblazing with HPF-custom blaze templates.\n\n        Parameters\n        ----------\n        method : (Str)\n            Either \"template\" or \"spline\" (default: template)\n        \"\"\"\n        if method == \"template\":\n            return self._deblaze_by_template()\n        else:\n            log.error(\"This method is deprecated!  Please use the new deblaze method\")\n            raise NotImplementedError\n\n    def sky_subtract(self, method=\"scalar\"):\n        \"\"\"Subtract sky spectrum from science spectrum, with refinements for sky throughput\n\n        Note: This operation does not wavelength shift or scale the sky spectrum\n\n        Parameters\n        ----------\n        method : (str)\n            The method for sky subtraction: \"naive\", \"scalar\", or \"vector\", as described in\n            Gully-Santiago et al. in prep.  Default is scalar.\n\n        Returns\n        -------\n        sky_subtractedSpec : (HPFSpectrum)\n            Sky subtracted Spectrum\n        \"\"\"\n        spec = copy.deepcopy(self)\n        if method == \"naive\":\n            log.warning(\n                \"Naive sky subtraction method is known to oversubtract the sky, see GitHub Issues.\"\n            )\n            beta = 1.0 * u.dimensionless_unscaled\n        elif method == \"scalar\":\n            beta = 0.93 * u.dimensionless_unscaled\n        elif method == \"vector\":\n            beta_native_spectrum = spec.get_static_sky_ratio_template()\n            resampler = LinearInterpolatedResampler(extrapolation_treatment=\"zero_fill\")\n            beta = resampler(beta_native_spectrum, spec.spectral_axis)\n        else:\n            log.error(\"Method must be one of 'naive', 'scalar' or 'vector'. \")\n            raise NotImplementedError\n\n        # These steps should propagate uncertainty?\n        sky_estimator = spec.sky.multiply(beta, handle_meta=\"first_found\")\n        return spec.subtract(sky_estimator, handle_meta=\"first_found\")\n\n    def mask_tellurics(self, method=\"TelFit\", threshold=0.999, dilation=5):\n        \"\"\"Mask known telluric lines based on a static TelFit template or heuristics\n\n        Note: This method is for quicklook purpsoes, it misses many unknown tellurics\n\n        Parameters\n        ----------\n        method : (str)\n            The method for telluric masking: \"TelFit\" or \"heuristics\"\n            Default is TelFit.\n\n        dilation : (int)\n            The number of pixels adjacent to the threshold mask to include in a\n            dilated mask. This control parameter accounts for velocity offsets\n            between the template and observed telluric spectrum.\n\n        Returns\n        -------\n        sky_subtractedSpec : (HPFSpectrum)\n            Sky subtracted Spectrum\n        \"\"\"\n        spec = copy.deepcopy(self)\n\n        if method == \"TelFit\":\n            telfit_template = spec.get_static_TelFit_template()\n            resampler = LinearInterpolatedResampler(extrapolation_treatment=\"nan_fill\")\n            telluric_estimate = resampler(telfit_template, spec.spectral_axis)\n\n            assert (threshold < 1.0) & (threshold > 0.0), \"Threshold must be a fraction\"\n            threshold_mask = telluric_estimate.flux.value < threshold\n\n            # Dilate the binary mask to account for velocity offsets and edge effects\n            dilated_mask = binary_dilation(threshold_mask, iterations=dilation)\n            assert (\n                ~dilated_mask\n            ).sum() > 2, \"You should have at least 2 pixels left after masking\"\n            spec = spec._copy(mask=dilated_mask)\n            spec_out = spec.remove_nans()\n            return spec_out\n        else:\n            log.error(\"Only the TelFit method is currently implemented\")\n            raise NotImplementedError\n\n    def blaze_divide_flats(self, flat, order=19):\n        \"\"\"Remove blaze function from spectrum by dividing by flat spectrum\n\n        Returns\n        -------\n        blaze corrrected spectrum using flat fields : (HPFSpectrum)\n\n        \"\"\"\n        log.warning(\"This method is deprecated!  Please use the new deblaze method\")\n        raise NotImplementedError\n\n\nclass HPFSpectrumList(EchelleSpectrumList):\n    r\"\"\"\n    An enhanced container for a list of HPF spectral orders\n\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        self.normalization_order_index = 14\n        super().__init__(*args, **kwargs)\n\n    @staticmethod\n    def read(file, precache_hdus=True):\n        \"\"\"Read in a SpectrumList from a file\n\n        Parameters\n        ----------\n        file : (str)\n            A path to a reduced HPF spectrum from plp\n        \"\"\"\n\n        hdus = fits.open(file, memmap=False)\n        cached_hdus = [hdus]\n\n        n_orders, n_pix = hdus[7].data.shape\n\n        list_out = []\n        for i in range(n_orders):\n            spec = HPFSpectrum(file=file, order=i, cached_hdus=cached_hdus)\n            list_out.append(spec)\n        return HPFSpectrumList(list_out)\n\n    def deblaze(self):\n        \"\"\"Deblaze the entire spectrum\"\"\"\n        spec_out = copy.copy(self)\n        for i in range(len(spec_out)):\n            spec_out[i] = spec_out[i].deblaze()\n\n        return spec_out\n\n    def sky_subtract(self, method=\"vector\"):\n        \"\"\"Sky subtract the entire spectrum\"\"\"\n        spec_out = copy.copy(self)\n        for i in range(len(spec_out)):\n            spec_out[i] = spec_out[i].sky_subtract(method=method)\n\n        return spec_out\n\n    # def sky_subtract(self):\n    #     \"\"\"Sky subtract all orders\n    #     \"\"\"\n    #     flux = copy.deepcopy(self.flux)\n    #     sky = copy.deepcopy(self.sky)\n    #     for i in range(len(self)):\n    #         self[i] = flux[i] - sky[i]\n\n    #     return self\n", "meta": {"hexsha": "3f60c7b426d8c953fa812d98434a839b8941ad76", "size": 15869, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/muler/hpf.py", "max_stars_repo_name": "OttoStruve/muler", "max_stars_repo_head_hexsha": "61d3e1676b1dbbe5616c303e6a64bc24d7519f4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-04-21T21:09:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T23:30:06.000Z", "max_issues_repo_path": "src/muler/hpf.py", "max_issues_repo_name": "OttoStruve/muler", "max_issues_repo_head_hexsha": "61d3e1676b1dbbe5616c303e6a64bc24d7519f4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 71, "max_issues_repo_issues_event_min_datetime": "2020-12-16T16:53:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T18:50:29.000Z", "max_forks_repo_path": "src/muler/hpf.py", "max_forks_repo_name": "OttoStruve/muler", "max_forks_repo_head_hexsha": "61d3e1676b1dbbe5616c303e6a64bc24d7519f4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-04-27T19:21:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-06T18:00:04.000Z", "avg_line_length": 35.3429844098, "max_line_length": 376, "alphanum_fraction": 0.6107505199, "include": true, "reason": "import numpy,from scipy,import astropy,from astropy", "num_tokens": 3681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.27202455699569283, "lm_q1q2_score": 0.15709292088173632}}
{"text": "#!/usr/bin/python3\n\nimport numpy as np\nimport json\nimport requests\nimport csv\nimport pickle\nimport os\nimport sys\nimport re\nimport statistics\nimport scipy\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfrom matplotlib.colors import ListedColormap, LinearSegmentedColormap\nfrom scipy import cluster\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.metrics import silhouette_samples, silhouette_score\nfrom rdkit import Chem, DataStructs, RDConfig\nfrom rdkit.Chem import rdFMCS, AllChem, Draw, Lipinski\nfrom itertools import chain, combinations\n\n\n# import ligand smiles strings\nligand_file = 'lig_1118.json'\n\nwith open(ligand_file) as ff:\n    smiles_dict = json.load(ff)\n    \n    \n# check for ligands with bad or missing smiles strings\nbad_smiles = []\n\nfor key,value in smiles_dict.items():\n    if 'smiles_cactus' not in value or Chem.MolFromSmiles(smiles_dict[key]['smiles_cactus']) is None:\n        bad_smiles.append(key)\n    \n\n# for each viral protein, make list of residues in consensus pockets\ndef pocket_residues(consensus_pockets,all_consensus_residues,directory,protnow):\n    file = open(directory+'clusters_'+protnow+'.txt','r')\n    line_list = file.readlines()\n    consensus_pockets[protnow] = {}\n    all_consensus_residues[protnow] = []\n    \n    for line in line_list:\n        pocket = line.split()[0].split(':')[0]\n        residues = line.split()[1].split(',')[0:-1]\n        consensus_pockets[protnow][pocket] = residues\n        for res in residues:\n            if res not in all_consensus_residues[protnow]:\n                all_consensus_residues[protnow].append(res)\n\n    file.close()\n    return consensus_pockets, all_consensus_residues\n\n\n# for each viral protein pocket, make list of pocket ligands each residue contacts\ndef pocket_residue_ligand_pairs(directory,filenames,consensus_pockets,consensus_pocket_ligands,protnow):\n    consensus_pocket_reslig_pairs[protnow] = {}\n    \n    for pocket,residues in consensus_pockets[protnow].items():\n        consensus_pocket_reslig_pairs[protnow][pocket] = {}\n        for res in residues:\n            consensus_pocket_reslig_pairs[protnow][pocket][res] = []\n     \n    for fl in filenames:\n        file = open(directory+fl,'r')\n        line_list = file.readlines()\n    \n        for line in line_list:\n            interaction = line.split()[0].split(':')[0]\n            binding_residues = line.split()[-1].split(',')[0:-1]\n            ligand = line.split()[0].split('.')[6]\n\n            # viral protein\n            if line.split()[0].split('.')[0].split('_')[0]=='nCoV':\n                protein = line.split()[0].split('.')[0].split('_')[1]\n                if protein=='Spike':\n                    protein = 'S'\n                           \n                for pocket,residues in consensus_pockets[protnow].items():\n                    for res in residues:\n                        if protein==protnow and res in binding_residues and ligand in consensus_pocket_ligands[protnow][pocket] and ligand not in consensus_pocket_reslig_pairs[protnow][pocket][res]:\n                            consensus_pocket_reslig_pairs[protnow][pocket][res].append(ligand)\n                            consensus_pocket_reslig_pairs[protnow][pocket][res].sort()\n\n        file.close()\n    return consensus_pocket_reslig_pairs\n\n\n# for each viral protein pocket, make list of filtered ligands that bind (require ligand size>=8)\ndef filtered_pocket_ligands(directory,filenames,consensus_pockets,protnow,ligs_leaveout):\n    consensus_pocket_ligands[protnow] = {}\n    \n    for pocket,residues in consensus_pockets[protnow].items():\n        consensus_pocket_ligands[protnow][pocket] = []\n     \n    for fl in filenames:\n        file = open(directory+fl,'r')\n        line_list = file.readlines()\n    \n        for line in line_list:\n            interaction = line.split()[0].split(':')[0]\n            binding_residues = line.split()[-1].split(',')[0:-1]\n            ligand = line.split()[0].split('.')[6]\n            lig_size = line.split()[0].split('.')[7]\n\n            # viral protein\n            if line.split()[0].split('.')[0].split('_')[0]=='nCoV':\n                protein = line.split()[0].split('.')[0].split('_')[1]\n                if protein=='Spike':\n                    protein = 'S'\n                           \n                for pocket,residues in consensus_pockets[protnow].items():\n                    if protein==protnow and (set(binding_residues) & set(residues)) and ligand not in ligs_leaveout[protnow]:\n                        if len(ligand)<4:\n                            if float(lig_size)>=8:\n                                if ligand not in consensus_pocket_ligands[protnow][pocket] and ligand in smiles_dict and ligand not in bad_smiles:\n                                    consensus_pocket_ligands[protnow][pocket].append(ligand)\n                                    consensus_pocket_ligands[protnow][pocket].sort()\n        file.close()\n    return consensus_pocket_ligands\n\n\n# calculate normalized Tanimoto distance between all pairs of ligands\ndef calc_Tanimoto_dist_norm(fp_radius,nBits,chemtax_dict):\n    Tdist_dict = {}\n    Tdistnorm_dict = {}\n    Tdistlist = []\n    for i1 in range(0,len(pocket_ligs)):\n        lig1 = pocket_ligs[i1]\n        if lig1 not in bad_smiles:\n            m1 = Chem.MolFromSmiles(smiles_dict[lig1]['smiles_cactus'])\n            fp1 = AllChem.GetMorganFingerprintAsBitVect(m1,fp_radius,nBits)\n            for i2 in range(i1+1,len(pocket_ligs)):\n                lig2 = pocket_ligs[i2]\n                if lig2 not in bad_smiles:\n                    m2 = Chem.MolFromSmiles(smiles_dict[lig2]['smiles_cactus'])\n                    fp2 = AllChem.GetMorganFingerprintAsBitVect(m2,fp_radius,nBits)\n                    Tsim = DataStructs.FingerprintSimilarity(fp1,fp2)\n                    Tdist = 1-Tsim\n                    Tdistlist.append(Tdist)\n                    Tdist_dict[(lig1,lig2)] = Tdist\n                    \n                    if lig1 in chemtax_dict and lig2 in chemtax_dict:\n                        if Tdist==0.0 and chemtax_dict[lig1]['kingdom']!='' and chemtax_dict[lig2]['kingdom']=='':\n                            chemtax_dict[lig2] = chemtax_dict[lig1]\n                        elif Tdist==0.0 and chemtax_dict[lig1]['kingdom']=='' and chemtax_dict[lig2]['kingdom']!='':\n                            chemtax_dict[lig1] = chemtax_dict[lig2]\n                    \n    Tdistavg = sum(Tdistlist)/float(len(Tdistlist))\n    Tdiststd = statistics.stdev(Tdistlist)\n    \n    print(Tdistavg,Tdiststd,min(Tdistlist))\n    \n    for ligpair in Tdist_dict.keys():\n        Tdistnorm_dict[ligpair] = ((Tdist_dict[ligpair]-Tdistavg)/Tdiststd)+15\n     \n    return Tdistnorm_dict,chemtax_dict,Tdistavg,Tdiststd\n                        \n    \n# calculate Tanimoto distance for pairs of ligands in each pocket\ndef get_Tanimoto_dist(Tdistlist_dict,consensus_pocket_ligands,protnow,Tdistnorm_dict):\n    Tdistlist_dict[protnow] = {}\n    for pocket,ligands in consensus_pocket_ligands[protnow].items():\n        Tdistlist = []\n        for i1 in range(0,len(ligands)):\n            lig1 = ligands[i1]\n            for i2 in range(i1+1,len(ligands)):\n                lig2 = ligands[i2]\n                if (lig1,lig2) in Tdistnorm_dict:\n                    Tdist = Tdistnorm_dict[(lig1,lig2)]\n                    Tdistlist.append(Tdist)\n                elif (lig2,lig1) in Tdistnorm_dict:\n                    Tdist = Tdistnorm_dict[(lig2,lig1)]\n                    Tdistlist.append(Tdist)\n        Tdistlist_dict[protnow][pocket] = Tdistlist \n    return Tdistlist_dict\n\n\n# calculate normalized chemical taxonomy distance between all pairs of ligands\ndef calc_chemtax_dist_norm():\n    Cdist_dict = {}\n    Cdistnorm_dict = {}\n    Cdistlist = []\n    for i1 in range(0,len(pocket_ligs)):\n        lig1 = pocket_ligs[i1]\n        if lig1 not in bad_smiles:\n            for i2 in range(i1+1,len(pocket_ligs)):\n                lig2 = pocket_ligs[i2]\n                Csim = 0\n                if lig2 not in bad_smiles:\n                    if chemtax_dict[lig1]['kingdom']!='' and chemtax_dict[lig2]['kingdom']!='':\n                        for level in ['kingdom','superclass','class','subclass']:\n                            if chemtax_dict[lig1][level]==chemtax_dict[lig2][level]:\n                                Csim = Csim + 1\n                        Csim = float(Csim)/float(4)\n                        Cdist = 1-Csim\n                        Cdistlist.append(Cdist)\n                        Cdist_dict[(lig1,lig2)] = Cdist \n                    \n    Cdistavg = sum(Cdistlist)/float(len(Cdistlist))\n    Cdiststd = statistics.stdev(Cdistlist)\n    \n    print(Cdistavg,Cdiststd,min(Cdistlist))\n    \n    for ligpair in Cdist_dict.keys():\n        Cdistnorm_dict[ligpair] = ((Cdist_dict[ligpair]-Cdistavg)/Cdiststd)+15\n     \n    return Cdistnorm_dict,Cdistavg,Cdiststd\n\n\n# calculate distance based on chemical taxonomy for pairs of ligands in each pocket\ndef get_chemtax_dist(Cdistlist_dict,consensus_pocket_ligands,protnow,Cdistnorm_dict):\n    Cdistlist_dict[protnow] = {}\n    for pocket,ligands in consensus_pocket_ligands[protnow].items():\n        Cdistlist = []\n        for i1 in range(0,len(ligands)):\n            lig1 = ligands[i1]\n            for i2 in range(i1+1,len(ligands)):\n                lig2 = ligands[i2]\n                if (lig1,lig2) in Cdistnorm_dict:\n                    Cdist = Cdistnorm_dict[(lig1,lig2)]\n                    Cdistlist.append(Cdist)\n                elif (lig2,lig1) in Cdistnorm_dict:\n                    Cdist = Cdistnorm_dict[(lig2,lig1)]\n                    Cdistlist.append(Cdist)\n                else:\n                    Cdistlist.append('NA')\n        Cdistlist_dict[protnow][pocket] = Cdistlist  \n    return Cdistlist_dict\n\n\n# calculate normalized word context distance between all pairs of ligands\ndef calc_ligname_dist_norm(ligname_dist_dict):\n    LNdistnorm_dict = {}\n    LNdist_dict = {}\n    LNdistlist = []\n    for i1 in range(0,len(pocket_ligs)):\n        lig1 = pocket_ligs[i1]\n        if lig1 not in bad_smiles:\n            for i2 in range(i1+1,len(pocket_ligs)):\n                lig2 = pocket_ligs[i2]\n                if lig2 not in bad_smiles:\n                    if (lig1,lig2) in ligname_dist_dict or (lig2,lig1) in ligname_dist_dict:\n                        if (lig1,lig2) in ligname_dist_dict:\n                            LNdist = ligname_dist_dict[(lig1,lig2)]\n                        elif (lig2,lig1) in ligname_dist_dict:\n                            LNdist = ligname_dist_dict[(lig2,lig1)]\n                        LNdistlist.append(LNdist)\n                        LNdist_dict[(lig1,lig2)] = LNdist \n                    \n    LNdistavg = sum(LNdistlist)/float(len(LNdistlist))\n    LNdiststd = statistics.stdev(LNdistlist)\n    \n    print(LNdistavg,LNdiststd,min(LNdistlist))\n    \n    for ligpair in LNdist_dict.keys():\n        LNdistnorm_dict[ligpair] = ((LNdist_dict[ligpair]-LNdistavg)/LNdiststd)+15\n     \n    return LNdistnorm_dict,LNdistavg,LNdiststd\n\n\n# make distance matrix from ligand name distance dictionary\ndef get_ligname_dist(LNdistlist_dict,consensus_pocket_ligands,protnow,LNdistnorm_dict):\n    LNdistlist_dict[protnow] = {}\n    for pocket,ligands in consensus_pocket_ligands[protnow].items():\n        LNdistlist = []\n        for i1 in range(0,len(ligands)):\n            lig1 = ligands[i1]\n            for i2 in range(i1+1,len(ligands)):\n                lig2 = ligands[i2]\n                if (lig1,lig2) in LNdistnorm_dict:\n                    LNdist = LNdistnorm_dict[(lig1,lig2)]\n                    LNdistlist.append(LNdist)\n                elif (lig2,lig1) in LNdistnorm_dict:\n                    LNdist = LNdistnorm_dict[(lig2,lig1)]\n                    LNdistlist.append(LNdist)\n                else:\n                    LNdistlist.append('NA')\n        LNdistlist_dict[protnow][pocket] = LNdistlist  \n    return LNdistlist_dict\n\n\n# take weighted average of distance matrices \ndef weighted_dist(protnow,consensus_pocket_ligands,Tdistlist_dict,Cdistlist_dict,LNdistlist_dict,Wdistlist_dict):\n    Wdistlist_dict[protnow] = {}\n    for pocket,ligands in consensus_pocket_ligands[protnow].items():\n        Wdistlist_dict[protnow][pocket] = []\n        if len(Tdistlist_dict[protnow][pocket])!=len(Cdistlist_dict[protnow][pocket]):\n            print('distance problem')\n        if len(Cdistlist_dict[protnow][pocket])!=len(LNdistlist_dict[protnow][pocket]):\n            print('distance problem')\n        for ind in range(0,len(Tdistlist_dict[protnow][pocket])):\n            Tdist = Tdistlist_dict[protnow][pocket][ind]\n            Cdist = Cdistlist_dict[protnow][pocket][ind]\n            LNdist = LNdistlist_dict[protnow][pocket][ind]\n            if Cdist!='NA' and LNdist!='NA':\n                Wdist = (float(1)/float(3))*Tdist + (float(1)/float(3))*Cdist + (float(1)/float(3))*LNdist\n            elif Cdist!='NA' and LNdist=='NA':\n                Wdist = 0.5*Tdist + 0.5*Cdist\n            elif Cdist=='NA' and LNdist!='NA':\n                Wdist = 0.5*Tdist + 0.5*LNdist\n            elif Cdist=='NA' and LNdist=='NA':\n                Wdist = Tdist\n            else:\n                print(ind,'no Wdist assignment')                \n            Wdistlist_dict[protnow][pocket].append(Wdist) \n    return Wdistlist_dict\n\n\n# get distance matrix from distance list\ndef get_dist_matrix(Wdistlist_dict,Wdistmat_dict,consensus_pocket_ligands):\n    Wdistmat_dict[protnow] = {}\n    for pocket,ligands in consensus_pocket_ligands[protnow].items():\n        Wdistmat = -1*np.ones((len(ligands),len(ligands)))\n        ind = 0\n        for i1 in range(0,len(ligands)):\n            for i2 in range(i1,len(ligands)):\n                if i1==i2:\n                    Wdistmat[i1,i2] = 0\n                else:\n                    Wdistmat[i1,i2] = Wdistlist_dict[protnow][pocket][ind]\n                    Wdistmat[i2,i1] = Wdistlist_dict[protnow][pocket][ind]\n                    ind = ind + 1 \n        Wdistmat_dict[protnow][pocket] = Wdistmat\n    return Wdistmat_dict\n\n\n# cluster ligands in each pocket using DBSCAN\ndef dbscan_cluster_pocket_ligands(cluster_dict,protnow,consensus_pocket_ligands,Wdistmat_dict):    \n    cluster_dict[protnow] = {}\n    for pocket,ligands in consensus_pocket_ligands[protnow].items():\n        best_params = {}\n        if len(ligands)>2:\n            best_params['sscore'] = -1\n            eps_vec = np.linspace(1,15,14*20)\n            minsamp_vec = np.arange(3,11)\n            for eps_val in eps_vec:\n                for minsamp_val in minsamp_vec:\n                    db = DBSCAN(eps=eps_val, min_samples=minsamp_val, metric='precomputed').fit(Wdistmat_dict[protnow][pocket])\n                    labels = db.labels_\n                    n_clusters = len(set(labels)) - (1 if -1 in labels else 0) # Number of clusters in labels, ignoring noise if present\n                    n_noise = list(labels).count(-1)\n            \n                    if len(ligands)>n_clusters and n_clusters>=2:\n                        ss = silhouette_score(Wdistmat_dict[protnow][pocket],labels,metric='precomputed')\n                        if ss > best_params['sscore']:\n                            best_params = {'eps': eps_val, 'min_samples': minsamp_val, 'sscore': ss, 'n_clusters': n_clusters, 'n_noise': n_noise}               \n            \n            if 'eps' in best_params.keys():\n                db = DBSCAN(eps=best_params['eps'], min_samples=best_params['min_samples'], metric='precomputed').fit(Wdistmat_dict[protnow][pocket])\n                labels = db.labels_\n                n_clusters = len(set(labels)) - (1 if -1 in labels else 0) # Number of clusters in labels, ignoring noise if present\n                n_noise = list(labels).count(-1)\n            \n                labels_array = np.empty((len(consensus_pocket_ligands[protnow][pocket]),1),dtype=np.int64)\n                for k,ligand in enumerate(consensus_pocket_ligands[protnow][pocket]):\n                    labels_array[k] = np.empty((1,),dtype=np.int64)\n                    labels_array[k][0] = np.int64(labels[k])\n                            \n                cluster_dict[protnow][pocket] = labels_array\n                \n            else:\n                labels_array = np.empty((len(consensus_pocket_ligands[protnow][pocket]),1),dtype=np.int64)\n                for k,ligand in enumerate(consensus_pocket_ligands[protnow][pocket]):\n                    labels_array[k] = np.empty((1,),dtype=np.int64)\n                    labels_array[k][0] = np.int64(k)\n                            \n                cluster_dict[protnow][pocket] = labels_array\n              \n        elif len(ligands)==2:\n            cluster_dict[protnow][pocket] = [[0], [0]]\n            \n    return cluster_dict\n\n\n# silhouette plot\ndef silhouette(Wdistmat_dict,cluster_dict,consensus_pocket_ligands):\n    for pocket, clusters in cluster_dict[protnow].items():\n        clusout=[(x,clusters[k][0]) for k,x in enumerate(consensus_pocket_ligands[protnow][pocket])]\n        clustall=[]\n        for k in range(max([x[1] for x in clusout])+1):\n            clustall.append([x[0] for x in clusout if x[1]==k])\n        n_clusters=len(clustall)\n        dist_matrix = Wdistmat_dict[protnow][pocket]\n\n        try:\n            cluster_labels = np.empty((len(consensus_pocket_ligands[protnow][pocket]),))\n            max_clust_ind = np.amax(cluster_dict[protnow][pocket])\n            for k in range(0,len(cluster_dict[protnow][pocket])):\n                if cluster_dict[protnow][pocket][k][0]==-1:\n                    cluster_labels[k] = max_clust_ind+1\n                    max_clust_ind = max_clust_ind+1\n                else:\n                    cluster_labels[k] = cluster_dict[protnow][pocket][k][0]\n\n            # Create a subplot with 1 row and 1 column\n            fig = plt.figure()\n            fig.set_size_inches(9, 6)\n            ax=fig.add_subplot(111)\n            \n            # The (n_clusters+1)*10 is for inserting blank space between silhouette plots of individual clusters, to demarcate them clearly.\n            ax.set_ylim([0, len(cluster_labels) + (n_clusters + 1) * 10])\n\n            # The silhouette_score gives the average value for all the samples.\n            silhouette_avg = silhouette_score(dist_matrix, cluster_labels, metric=\"precomputed\", sample_size=None)\n            print(\"There are \",n_clusters,\" clusters and the average silhouette_score is : \",silhouette_avg)\n\n            # Compute the silhouette scores for each sample\n            sample_silhouette_values = silhouette_samples(dist_matrix, cluster_labels, metric=\"precomputed\")\n\n            y_lower = 10\n            for i in range(n_clusters):\n                # Aggregate the silhouette scores for samples belonging to cluster i, and sort them\n                ith_cluster_silhouette_values = sample_silhouette_values[cluster_labels == i]\n\n                ith_cluster_silhouette_values.sort()\n\n                size_cluster_i = ith_cluster_silhouette_values.shape[0]\n                y_upper = y_lower + size_cluster_i\n\n                color = cm.nipy_spectral(float(i)/n_clusters)\n                ax.fill_betweenx(np.arange(y_lower, y_upper),0, ith_cluster_silhouette_values,facecolor=color, edgecolor=color, alpha=0.7)\n\n                # Compute the new y_lower for next plot\n                y_lower = y_upper + 10  # 10 for the 0 samples\n\n            plt.title(protnow+', Pocket '+pocket,fontsize=16)\n            plt.xlabel(\"Silhouette coefficient\",fontsize=16)\n            plt.ylabel(\"Cluster label\",fontsize=16)\n\n            # vertical line for average silhouette score of all the values\n            ax.axvline(x=silhouette_avg, color=\"red\", linestyle=\"--\")\n\n            ax.set_yticks([])  # Clear the yaxis labels / ticks\n            plt.xlim((-0.1,0.6))\n            ax.set_xticks([-0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6])\n            plt.xticks(fontsize=14)\n\n            plt.show()\n            #plt.savefig('figures/silhouette_plot_'+protnow+'_'+pocket+'.png')\n        \n        except:\n            if len(cluster_dict[protnow][pocket])==n_clusters:\n                print('All ligands clustered separately')\n            elif n_clusters==1:\n                print('All ligands clustered together')\n    \n    return \n\n    \n# find max common substructure for ligand cluster in each pocket\ndef pocket_mcs(cluster_dict,consensus_pocket_ligands):\n    os.system('rm images/CCC-15-10-'+gdccut+'-4-0-ligs-8-current-resall/'+protnow+'_pocket*')\n    with open('ligand-cluster-key-CCC-15-10-'+gdccut+'-4-0-ligs-8-current-resall-'+protnow+'.csv','w') as f:\n        writeCSV = csv.DictWriter(f,fieldnames=['Pocket','Cluster Index','Ligands in Cluster'])\n        writeCSV.writeheader()\n        for pocket, clusters in cluster_dict[protnow].items():\n            clusout=[(x,clusters[k][0]) for k,x in enumerate(consensus_pocket_ligands[protnow][pocket])]\n            clustall=[]\n            for k in range(max([x[1] for x in clusout])+1):\n                clustall.append([x[0] for x in clusout if x[1]==k])\n            n_clusters=len(clustall)\n            for cind,clust in enumerate(clustall,1):\n                newrow = {'Pocket': pocket, 'Cluster Index': cind, 'Ligands in Cluster': clust}\n                writeCSV.writerow(newrow)\n                \n                subclasses = []\n                for lig in clust:\n                    if chemtax_dict[lig]['subclass'] not in subclasses:\n                        subclasses.append(chemtax_dict[lig]['subclass'])\n                if len(clust)>1:\n                    print('Pocket',pocket,'\\t','Cluster',cind,'\\t','# Ligands',len(clust),'\\t',\\\n                          'Class',chemtax_dict[clust[0]]['class'],'\\t','# Subclasses',len(subclasses))\n                \n                if len(clust)>=3:\n                    molecules = []\n                    for lig in clust:\n                        if lig not in bad_smiles:\n                            molecules.append(Chem.MolFromSmiles(smiles_dict[lig]['smiles_cactus']))\n                    if len(molecules)>1:\n                        mcs = Chem.rdFMCS.FindMCS(molecules)\n                        if mcs.numAtoms>=4:\n                            mcs_smiles = Chem.MolToSmiles(Chem.MolFromSmarts(mcs.smartsString))\n                            mcs_mol = Chem.MolFromSmarts(mcs.smartsString)\n                            mcs_coords = AllChem.Compute2DCoords(mcs_mol)\n                            image_file = 'images/CCC-15-10-'+gdccut+'-4-0-ligs-8-current-resall/'\\\n                            +protnow+'_pocket'+pocket+'_cluster'+str(cind)+'_mcs.png'\n                            Draw.MolToFile(mcs_mol,image_file)\n    return\n\n\ndef fraction_cluster_contacts_heatmap(cluster_dict,consensus_pocket_ligands,consensus_pocket_reslig_pairs,protnow,fraction_ligand_contacts_matrix_dict):\n    fraction_ligand_contacts_matrix_dict[protnow] = {}\n    for pocket, clusters in cluster_dict[protnow].items():\n        sorted_residues = sorted(consensus_pocket_reslig_pairs[protnow][pocket].keys(), key = lambda r: int(r[1:-2]))\n        clusout=[(x,clusters[k][0]) for k,x in enumerate(consensus_pocket_ligands[protnow][pocket])]\n        clustall=[]\n        for k in range(max([x[1] for x in clusout])+1):\n            clustall.append([x[0] for x in clusout if x[1]==k])\n        n_clusters=len(clustall)\n        flc_matrix = -1*np.ones((n_clusters,len(consensus_pocket_reslig_pairs[protnow][pocket].keys())))\n        for cind,clust in enumerate(clustall,1):\n            for res in sorted_residues:\n                overlap = set(consensus_pocket_reslig_pairs[protnow][pocket][res]).intersection(set(clust))\n                resind = sorted_residues.index(res)\n                flc_matrix[cind-1,resind] = len(overlap)/float(len(clust))   \n                \n        fraction_ligand_contacts_matrix_dict[protnow][pocket] = (flc_matrix, sorted_residues)\n        \n        ## heatmap using matplotlib (colorbar has same range for all plots)\n        cb_viridis = cm.get_cmap('viridis', 100)\n        plt.figure()\n        plt.pcolor(np.arange(len(sorted_residues)), np.arange(n_clusters), flc_matrix, cmap=cb_viridis, vmin=0, vmax=1, shading='auto')\n        plt.title(protnow+', Pocket '+str(pocket))\n        plt.xlabel('Residues')\n        plt.ylabel('Clusters') \n        plt.xticks(ticks=np.arange(len(sorted_residues)), labels=sorted_residues, rotation=90)\n        plt.yticks(ticks=list(np.arange(n_clusters)), labels=list(np.arange(1,n_clusters+1)))\n        plt.colorbar(label='Fraction of Cluster Ligands in Contact')\n        plt.show()\n\n    return fraction_ligand_contacts_matrix_dict\n\n\n# save files with PDB IDs for ligands in each cluster\ndef save_ligand_clusters(cluster_dict,consensus_pocket_ligands):\n    with open('ligand-cluster-key-CCC-15-10-'+gdccut+'-4-0-ligs-8-current-resall-'+protnow+'.csv','w') as f:\n        writeCSV = csv.DictWriter(f,fieldnames=['Pocket','Cluster Index','Ligands in Cluster'])\n        writeCSV.writeheader()\n        for pocket, clusters in cluster_dict[protnow].items():\n            clusout=[(x,clusters[k][0]) for k,x in enumerate(consensus_pocket_ligands[protnow][pocket])]\n            clustall=[]\n            for k in range(max([x[1] for x in clusout])+1):\n                clustall.append([x[0] for x in clusout if x[1]==k])\n            n_clusters=len(clustall)\n            for cind,clust in enumerate(clustall,1):\n                newrow = {'Pocket': pocket, 'Cluster Index': cind, 'Ligands in Cluster': clust}\n                writeCSV.writerow(newrow)\n\n\n# compare experimentally screened positive compounds with ligand clusters\ndef compare_exp_pos_compounds(protnow,smiles_dict,cluster_dict,consensus_pocket_ligands):\n    cluster_distance_pos = {}\n    if protnow=='nsp5':\n        with open('./fret_crys_test1.csv','r') as pos_smiles_file:\n            readCSV = csv.DictReader(pos_smiles_file)\n            for row in readCSV:\n                exp_smiles = str(row['smiles'])\n                exp_id = row['compound_id']\n                m1 = Chem.MolFromSmiles(exp_smiles)\n                fp1 = AllChem.GetMorganFingerprintAsBitVect(m1,fp_radius,nBits)\n                image_file = 'images/experimental_compounds_positive/'+exp_id+'.png'\n                Draw.MolToFile(m1,image_file)\n                cluster_distance_pos[exp_id] = {}\n                for pocket, clusters in cluster_dict[protnow].items():\n                    cluster_distance_pos[exp_id][pocket] = {}\n                    clusout=[(x,clusters[k][0]) for k,x in enumerate(consensus_pocket_ligands[protnow][pocket])]\n                    clustall=[]\n                    for k in range(max([x[1] for x in clusout])+1):\n                        clustall.append([x[0] for x in clusout if x[1]==k])\n                    n_clusters=len(clustall)\n                    for cind,clust in enumerate(clustall,1):\n                        Tdist_avg = 0\n                        for lig in clust:\n                            # calculate Tanimoto distance\n                            m2 = Chem.MolFromSmiles(smiles_dict[lig]['smiles_cactus'])\n                            fp2 = AllChem.GetMorganFingerprintAsBitVect(m2,fp_radius,nBits)\n                            Tsim = DataStructs.FingerprintSimilarity(fp1,fp2)\n                            Tdist = 1-Tsim\n                            Tdist_avg = Tdist_avg + Tdist\n                        Tdist_avg = Tdist_avg/float(len(clust))\n                        cluster_distance_pos[exp_id][pocket][cind] = Tdist_avg\n                        \n    return cluster_distance_pos\n\n\n# compare experimentally screened negative compounds with ligand clusters\ndef compare_exp_neg_compounds(protnow,smiles_dict,cluster_dict,consensus_pocket_ligands):\n    cluster_distance_neg = {}\n    if protnow=='nsp5':\n        with open('./all_postera_match_neg_10132021.csv','r') as neg_smiles_file:\n            readCSV = csv.DictReader(neg_smiles_file)\n            for row in readCSV:\n                exp_smiles = str(row['SMILES'])\n                exp_id = row['compound_id']\n                m1 = Chem.MolFromSmiles(exp_smiles)\n                try: \n                    fp1 = AllChem.GetMorganFingerprintAsBitVect(m1,fp_radius,nBits)\n                    image_file = 'images/experimental_compounds_negative/'+exp_id+'.png'\n                    Draw.MolToFile(m1,image_file)\n                    cluster_distance_neg[exp_id] = {}\n                    for pocket, clusters in cluster_dict[protnow].items():\n                        cluster_distance_neg[exp_id][pocket] = {}\n                        clusout=[(x,clusters[k][0]) for k,x in enumerate(consensus_pocket_ligands[protnow][pocket])]\n                        clustall=[]\n                        for k in range(max([x[1] for x in clusout])+1):\n                            clustall.append([x[0] for x in clusout if x[1]==k])\n                        n_clusters=len(clustall)\n                        for cind,clust in enumerate(clustall,1):\n                            Tdist_avg = 0\n                            for lig in clust:\n                                # calculate Tanimoto distance\n                                m2 = Chem.MolFromSmiles(smiles_dict[lig]['smiles_cactus'])\n                                fp2 = AllChem.GetMorganFingerprintAsBitVect(m2,fp_radius,nBits)\n                                Tsim = DataStructs.FingerprintSimilarity(fp1,fp2)\n                                Tdist = 1-Tsim\n                                Tdist_avg = Tdist_avg + Tdist\n                            Tdist_avg = Tdist_avg/float(len(clust))\n                            cluster_distance_neg[exp_id][pocket][cind] = Tdist_avg\n                except:\n                    print(exp_id)\n                    pass\n                        \n    return cluster_distance_neg\n\n\n# find most similar ligand cluster for experimentally screened compounds \ndef find_closest_cluster(cluster_distance,protnow,cluster_dict,consensus_pocket_ligands):\n    closest_cluster = {}\n    closest_dist_list = {}\n    if protnow=='nsp5':\n        for pocket, clusters in cluster_dict[protnow].items():\n            closest_dist_list[pocket] = {}\n            clusout=[(x,clusters[k][0]) for k,x in enumerate(consensus_pocket_ligands[protnow][pocket])]\n            clustall=[]\n            for k in range(max([x[1] for x in clusout])+1):\n                clustall.append([x[0] for x in clusout if x[1]==k])\n            n_clusters=len(clustall)\n            for cind,clust in enumerate(clustall,1):\n                closest_dist_list[pocket][cind] = []\n        \n        for exp_id,itm in cluster_distance.items():\n            closest_cluster[exp_id] = {}\n            for pocket,cind in cluster_distance[exp_id].items():\n                min_dist = 1\n                for cind,Tdist in cluster_distance[exp_id][pocket].items():\n                    if Tdist<min_dist:\n                        min_dist = Tdist\n                        closest_cluster[exp_id][pocket] = (cind,Tdist)\n                    \n        for pocket, clusters in cluster_dict[protnow].items():\n            clusout=[(x,clusters[k][0]) for k,x in enumerate(consensus_pocket_ligands[protnow][pocket])]\n            clustall=[]\n            for k in range(max([x[1] for x in clusout])+1):\n                clustall.append([x[0] for x in clusout if x[1]==k])\n            n_clusters=len(clustall)\n            for cind,clust in enumerate(clustall,1):\n                for exp_id,itm in closest_cluster.items():\n                    for pckt,tup in closest_cluster[exp_id].items():\n                        if str(pckt)==str(pocket) and str(cind)==str(closest_cluster[exp_id][pckt][0]):\n                            closest_dist_list[pocket][cind].append(closest_cluster[exp_id][pckt][1])\n                    \n    return closest_cluster, closest_dist_list\n\n\n# for each nsp5 ligand cluster, make overlapping histograms of Tanimoto distances for positive and negative compounds closest to that cluster\ndef closest_cluster_hist(protnow,closest_dist_list_pos,closest_dist_list_neg,cluster_dict,consensus_pocket_ligands):\n    if protnow=='nsp5':\n        for pocket, clusters in cluster_dict[protnow].items():\n            clusout=[(x,clusters[k][0]) for k,x in enumerate(consensus_pocket_ligands[protnow][pocket])]\n            clustall=[]\n            for k in range(max([x[1] for x in clusout])+1):\n                clustall.append([x[0] for x in clusout if x[1]==k])\n            n_clusters=len(clustall)\n            for cind,clust in enumerate(clustall,1):\n                print('ligand cluster index :',cind)\n                plt.figure()\n                \n                if cind==1:\n                    plt.figtext(0.14,0.8,'p-value = 0.702\\nno difference')\n                elif cind==2:\n                    plt.figtext(0.14,0.8,'p-value = 4.87e-17\\ndifferent')\n                elif cind==4:\n                    plt.figtext(0.14,0.8,'p-value = 1.83e-29\\ndifferent')\n                elif cind==5:\n                    plt.figtext(0.14,0.8,'p-value = 0.0825\\nno difference')\n                elif cind==7:\n                    plt.figtext(0.14,0.8,'p-value = 1.36e-32\\ndifferent')\n                elif cind==10:\n                    plt.figtext(0.14,0.8,'p-value = 5.90e-30\\ndifferent')\n\n                if len(closest_dist_list_pos[pocket][cind])>0 and len(closest_dist_list_neg[pocket][cind])>0:\n                    print('average distance positive',statistics.mean(closest_dist_list_pos[pocket][cind]))\n                    print('average distance negative',statistics.mean(closest_dist_list_neg[pocket][cind]))\n                    plt.hist(closest_dist_list_pos[pocket][cind],range=(0.5,1.0),bins=20,density=True,alpha=0.5,label='positive',color='red')\n                    plt.hist(closest_dist_list_neg[pocket][cind],range=(0.5,1.0),bins=20,density=True,alpha=0.5,label='negative',color='blue')\n                    \n                elif len(closest_dist_list_pos[pocket][cind])==0 and len(closest_dist_list_neg[pocket][cind])>0:\n                    print('average distance negative',statistics.mean(closest_dist_list_neg[pocket][cind]))\n                    plt.hist(closest_dist_list_neg[pocket][cind],range=(0.5,1.0),bins=20,density=True,alpha=0.5,label='negative',color='blue')\n                    \n                elif len(closest_dist_list_pos[pocket][cind])>0 and len(closest_dist_list_neg[pocket][cind])==0:\n                    print('average distance negative',statistics.mean(closest_dist_list_pos[pocket][cind]))\n                    plt.hist(closest_dist_list_pos[pocket][cind],range=(0.5,1.0),bins=20,density=True,alpha=0.5,label='positive',color='red')\n                \n                plt.legend(loc='upper right')\n                plt.title(protnow+', Pocket '+pocket+', Cluster '+str(cind),fontsize=16)\n                plt.xlabel('Tanimoto distance',fontsize=16)\n                plt.xlim(0.5,1.0)\n                plt.ylim(0,30)\n                plt.ylabel('Normalized count',fontsize=16)\n                plt.xticks(fontsize=14)\n                plt.yticks(fontsize=14)\n                plt.show()\n                #plt.savefig('figures/exp_compounds_distance_distr_pocket'+pocket+'_cluster'+str(cind)+'.png')  \n                \n    return\n\n\n# for each nsp5 ligand cluster, perform t-test for positive and negative compounds closest to that cluster\ndef closest_cluster_ttest(protnow,closest_dist_list_pos,closest_dist_list_neg,cluster_dict,consensus_pocket_ligands):\n    if protnow=='nsp5':\n        for pocket, clusters in cluster_dict[protnow].items():\n            clusout=[(x,clusters[k][0]) for k,x in enumerate(consensus_pocket_ligands[protnow][pocket])]\n            clustall=[]\n            for k in range(max([x[1] for x in clusout])+1):\n                clustall.append([x[0] for x in clusout if x[1]==k])\n            n_clusters=len(clustall)\n            for cind,clust in enumerate(clustall,1):\n                ttest_output = scipy.stats.ttest_ind(closest_dist_list_pos[pocket][cind],closest_dist_list_neg[pocket][cind])\n                pval = ttest_output[1]\n                print(pocket,cind,ttest_output)            \n    return \n\n\n# for each cluster, compile list of experimentally screened compounds that were found to be most similar to cluster\ndef list_closest_ligands(closest_cluster,cluster_dict):\n    closest_ligands = {}\n    for pocket, clusters in cluster_dict[protnow].items():\n        closest_ligands[pocket] = {}\n        clusout=[(x,clusters[k][0]) for k,x in enumerate(consensus_pocket_ligands[protnow][pocket])]\n        clustall=[]\n        for k in range(max([x[1] for x in clusout])+1):\n            clustall.append([x[0] for x in clusout if x[1]==k])\n        n_clusters=len(clustall)\n        for cind,clust in enumerate(clustall,1):\n            closest_ligands[pocket][cind] = []\n            for exp_id in closest_cluster.keys():\n                if closest_cluster[exp_id][pocket][0]==cind:\n                    closest_ligands[pocket][cind].append(exp_id)\n                    \n    return closest_ligands\n\n\n\nprot_list_focus = ['S','nsp5','nsp12']\n\nconsensus_pockets = {}\nall_consensus_residues = {}\nconsensus_pocket_ligands = {}\nconsensus_pocket_reslig_pairs = {}\nfraction_lig_contacts = {}\nfraction_ligand_contacts_matrix_dict = {}\nTdistlist_dict = {}\nCdistlist_dict = {}\nLNdistlist_dict = {}\nWdistlist_dict = {}\nWdistmat_dict = {}\nTweight = 0.5\ncluster_dict = {}\ncomout_dict = {}\nfp_radius = 2\nnBits = 1024\ngdccut = '60'\n\n\nligs_leaveout = pickle.load(open('ligs_leaveout.p','rb'))\nchemtax_dict = pickle.load(open('chemtax_dict.p', 'rb')) \nligname_dist_dict_notscaled = pickle.load(open('ligname_dist_dict_notscaled.p','rb'))\n\ndirectory = 'cluster-output-ncov-residues-shortestpath-CCC-15-10-'+gdccut+'-4-0.ligs_8/date_current_resall/'\nfor protnow in prot_list_focus:\n    consensus_pockets = pocket_residues(consensus_pockets,all_consensus_residues,directory,protnow)[0]\n    all_consensus_residues = pocket_residues(consensus_pockets,all_consensus_residues,directory,protnow)[1]\n\ndirectory = './'\nfilenames = ['CCC.confidence_centroid_contacts.15_10_'+gdccut+'_4_0.ligs_8.nCoV.current.resall']\n\npocket_ligs = []\nfor protnow in prot_list_focus:\n    consensus_pocket_ligands = filtered_pocket_ligands(directory,filenames,consensus_pockets,protnow,ligs_leaveout)\n    consensus_pocket_reslig_pairs = pocket_residue_ligand_pairs(directory,filenames,consensus_pockets,consensus_pocket_ligands,protnow)\n    for pocket,ligands in consensus_pocket_ligands[protnow].items():\n        for lig in ligands:\n            if lig not in pocket_ligs:\n                pocket_ligs.append(lig)\n\n\nTdist_output = calc_Tanimoto_dist_norm(fp_radius,nBits,chemtax_dict)\nTdistnorm_dict = Tdist_output[0]\npickle.dump(Tdistnorm_dict,open('normalized-Tanimoto-dist.p','wb'))\n#Tdistnorm_dict = pickle.load(open('normalized-Tanimoto-dist.p','rb'))\n\n# chemical taxonomy dictionary\nchemtax_dict = Tdist_output[1]\npickle.dump(chemtax_dict,open('chemtax_dict_updated.p','wb'))\n#chemtax_dict = pickle.load(open('chemtax_dict_updated.p','rb'))\n\nCdist_output = calc_chemtax_dist_norm()\nCdistnorm_dict = Cdist_output[0]\npickle.dump(Cdistnorm_dict,open('normalized-chemtax-dist.p','wb'))\n#Cdistnorm_dict = pickle.load(open('normalized-chemtax-dist.p','rb'))\n\nLNdist_output = calc_ligname_dist_norm(ligname_dist_dict_notscaled)\nLNdistnorm_dict = LNdist_output[0]\npickle.dump(LNdistnorm_dict,open('normalized-wordvec-dist.p','wb'))\n#LNdistnorm_dict = pickle.load(open('normalized-wordvec-dist.p','rb'))\n\nfor protnow in prot_list_focus:\n    Tdistlist_dict = get_Tanimoto_dist(Tdistlist_dict,consensus_pocket_ligands,protnow,Tdistnorm_dict)\n    Cdistlist_dict = get_chemtax_dist(Cdistlist_dict,consensus_pocket_ligands,protnow,Cdistnorm_dict)\n    LNdistlist_dict = get_ligname_dist(LNdistlist_dict,consensus_pocket_ligands,protnow,LNdistnorm_dict)\n    \n    Wdistlist_dict = weighted_dist(protnow,consensus_pocket_ligands,Tdistlist_dict,Cdistlist_dict,LNdistlist_dict,Wdistlist_dict)\n    Wdistmat_dict = get_dist_matrix(Wdistlist_dict,Wdistmat_dict,consensus_pocket_ligands)\n    \n    cluster_dict = dbscan_cluster_pocket_ligands(cluster_dict,protnow,consensus_pocket_ligands,Wdistmat_dict)\n    \n    save_ligand_clusters(cluster_dict,consensus_pocket_ligands)\n    \n    fraction_ligand_contacts_matrix_dict = fraction_cluster_contacts_heatmap(cluster_dict,consensus_pocket_ligands,consensus_pocket_reslig_pairs,protnow,fraction_ligand_contacts_matrix_dict)\n    \n    silhouette(Wdistmat_dict,cluster_dict,consensus_pocket_ligands)\n    \n    pocket_mcs(cluster_dict,consensus_pocket_ligands)\n    \n    cluster_distance_pos = compare_exp_pos_compounds(protnow,smiles_dict,cluster_dict,consensus_pocket_ligands)\n    cluster_distance_neg = compare_exp_neg_compounds(protnow,smiles_dict,cluster_dict,consensus_pocket_ligands)\n    closest_cluster_pos = find_closest_cluster(cluster_distance_pos,protnow,cluster_dict,consensus_pocket_ligands)[0]\n    closest_dist_list_pos = find_closest_cluster(cluster_distance_pos,protnow,cluster_dict,consensus_pocket_ligands)[1]\n    closest_cluster_neg = find_closest_cluster(cluster_distance_neg,protnow,cluster_dict,consensus_pocket_ligands)[0]\n    closest_dist_list_neg = find_closest_cluster(cluster_distance_neg,protnow,cluster_dict,consensus_pocket_ligands)[1]\n    \n    #print(closest_dist_list_pos)\n    #print(closest_dist_list_neg)\n    \n    closest_cluster_hist(protnow,closest_dist_list_pos,closest_dist_list_neg,cluster_dict,consensus_pocket_ligands)\n    closest_cluster_ttest(protnow,closest_dist_list_pos,closest_dist_list_neg,cluster_dict,consensus_pocket_ligands)\n       \n    #closest_ligands_pos = list_closest_ligands(closest_cluster_pos,cluster_dict)\n    #closest_ligands_neg = list_closest_ligands(closest_cluster_neg,cluster_dict)\n    #print(closest_ligands_pos)\n\n\n            \n\n    \n    \n    \n        \n        \n   \n        \n\n                                                     \n\n\n\n\n", "meta": {"hexsha": "75106dd5c1844d91c047df70321e4ee9297f1fd5", "size": 41631, "ext": "py", "lang": "Python", "max_stars_repo_path": "ligand-clustering.py", "max_stars_repo_name": "LLNL/TargetID", "max_stars_repo_head_hexsha": "b451b30d5f21bb0e47133293ee82151f7c57ea6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ligand-clustering.py", "max_issues_repo_name": "LLNL/TargetID", "max_issues_repo_head_hexsha": "b451b30d5f21bb0e47133293ee82151f7c57ea6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ligand-clustering.py", "max_forks_repo_name": "LLNL/TargetID", "max_forks_repo_head_hexsha": "b451b30d5f21bb0e47133293ee82151f7c57ea6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.2398609502, "max_line_length": 198, "alphanum_fraction": 0.6160553434, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 10634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.256831980010821, "lm_q1q2_score": 0.15702243910687985}}
{"text": "#!/usr/bin/python\n\n\"\"\"\nCalculate dN/dS using Nei Gojobori method with Juke-Cantor's multiple-substitution correction (optional), and whole sequence or sliding window. Tested against MATLAB's dnds().\nUSAGE:\n\n    Run this from command-line, from path (../../):\n    hpcleap_dnds/py/scripts/dnds.py <query sequence> <reference sequence>\n        For more information on query and reference sequence command-line arguments see ** in DETAILS section below.\n\nREQUIREMENTS:\n    scripts:\n        - hpcleap_dnds/py/scripts/changes.py (hpcleap_dnds/py/scripts/)\n    data:\n        - observed_changes.p, potential_changes.p: returned by changes.py\n        seq1, seq2: @todo: make cmd or file input arg\nDETAILS:\n** Query/Reference Input sequences:  both sequences are DNA CDS-transcripts\nof interest (exons-only). To give an example, say the \"query\" sequence\ncorresponds to the Anopheles gambiae TEP1 protein's transcript id\n(VectorBase: AGAP010815), and the other \"reference\" sequence corresponds\nto the orthologous Aedes aegypti TEP1 protein's trancript id (VectorBase:\nAAEL001802). The orthologous reference sequence is required, along with\nthe query sequence of interest, in order to estimate dN/dS values (sliding\n or whole), which requires simulations/approximations of ancestral DNA\nsubstitution mutations (synonymous, non-synonymous changes).\nIn the main webpage: vg-genes.html, the query sequence is what the user\nwill request aggregate informations from (after clicking \"GO!\"), whereas\nthe orthologous reference sequence is only used to calculate dnds.py,\nwithout the aggregate information requested.\n\"\"\"\n############\n# IMPORTS: #\n############\n\n# default modules\nimport sys\nimport pickle\nimport math\nimport warnings\n\n#import matplotlib.pyplot as plt\nimport numpy as np\n# andy-developed modules: imported from py/scripts/ (i.e. \".\" relative to where this file is)\nimport changes as codon_pair_data  # /hpcleap_dnds/py/scripts/changes.py\nimport align as align_then_trim    # /hpcleap_dnds/py/scripts/align.py\n\n# just for testing, @todo: remove testing imports\nimport pdb\nimport time\nstart_time = time.time()  # @time\n\n# @todo: make a check to ensure the input seqs are divisible by 3 (i.e. n_aa_residues = n_dna_residues/3)\n\n# @todo:REMOVE: \\/ and \\/\\/\n# with open('../data/observed_changes_dict.p','rb') as f_observed:\n#     changes_observed = pickle.load(f_observed)\n\n\n# @todo:REMOVE: \\/ and \\/\\/: the final script cannot use absolut paths, note: the path from which this script is executed is where current working directory is, in this case it should be a .html that is in {root} calling this script residing in {root}/scripts directory\n # changes_observed = pickle.load(open('/home/qiime/Desktop/hpcleap_wp6_compbio/hpcleap_bioinf/data/observed_changes_dict.p','rb'))\n# changes_potential= pickle.load(open('/home/qiime/Desktop/hpcleap_wp6_compbio/hpcleap_bioinf/data/potential_changes_dict.p','rb'))\n\n\n#############\n# FUNCTIONS #\n#############\n\n\ndef dnds( seq1, seq2, changes_potential, changes_observed, msCorrect='approximate', sliding=False, windowLength=3, stepLength=1):\n    \"\"\" Perform dN/dS analysis, using the 'NG' algoritm, includes both whole sequence or sliding window, and either an approximate or exact multiple-substiution correction method. (@todo: make sure it actually is exact... it could be\n             something else)\n\n    ARGS:\n        seq1,  a DNA sequence as string of letters, AGTC. Seq1 must be equal in length\n            to, and aligned with, seq2, with gaps trimmed away. @todo: how on earth can\n            we reliably make this work on the web service?\n\n            e.g. seq1 = 'ATGCGCAAATACTCCCCCTTCCGAAATGGATACATGGAACCCACCCTTGGGCAGCACCTCCCAACCCTGTCTTTTCCAGACCCCGGACTCCGGCCCCAAAACCTGTACACCCTCTGGGGAGGCTCCGTTGTCTGCATGTACCTCTACCAGCTTTCCCCCCCCATCACCTGGCCCCTCCTGCCCCATGTGATTTTTTGCCACCCCGGCCAGCTCGGGGCCTTCCTCACCAATGTTCCCTACAAACGAATAGAAAAACTCCTCTATAAAATTTCCCTTACCACAGGGGCCCTAATAATTCTACCCGAGGACTGTTTGCCCACCACCCTTTTCCAGCCTGCTAGGGCACCCGTCACGCTGACAGCCTGGCAAAACGGCCTCCTTCCGTTCCACTCAACCCTCACCACTCCAGGCCTTATTTGGACATTTACCGATGGCACGCCTATGATTTCCGGGCCCTGCCCTAAAGATGGCCAGCCATCTTTAGTACTACAGTCCTCCTCCTTTATATTTCACAAATTTCAAACCAAGGCCTACCACCCCTCATTTCTACTCTCACACGGCCTCATACAGTACTCTTCCTTTCATAATTTGCATCTCCTATTTGAAGAATACACCAACATCCCCATTTCTCTACTTTTTAACGAAAAAGAGGCAGATGACAATGACCATGAGCCCCAAATATCCCCCGGGGGCTTAGAGCCTCTCAGTGAAAAACATTTCCGTGAAACAGAAGTC'\n\n        seq2,  a DNA sequence similar to seq1 but with differences (substitutions),\n            representing a CDS orthologue of seq1 from a different species. Read\n            description of seq1 for other required similarities to avoid errors.\n\n            e.g. seq2 = 'ATGCGCAAGTACTCCCCCTTCCGAAACGGATACATGGAACCCACCCTTGGGCAACACCTCCCAACCCTGTCTTTTCCAGACCCCGGCCTCCGGCCCCAAAACCTGTACACCCTCTGGGGAGACTCTGTTGTCTGCCTGTACCTCTACCAGCTCTCCCCCCCCATCACCTGGCCCCTCCCGCCCCATGTGATTTTTTGCCACCCCGGCCAGCTCGGGGCCTTCCTCACCAATGTTCCCTACAAGCGTATGGAAGAACTCCTCTATAAAATTTCCCTTACCACAGGGGCCCTAATAATTCTACCCGAGGACTGTTTACCAACCACCCTTTTCCAGCCTGCTAGGGCCCCCGTCACGTTGACCGCCTGGCAGAACGGCCTCCTTCCGTTCCACTCAACCCTCACCACTCCAGGCCTTATTTGGACATTTACCGATGGCACGCCTATGGTTTCCGGACCCTGCCCCAAAGATGGCCAGCCATCTTTAGTACTACAGTCCTCCTCATTTATATTTCACAAATTTCAAACCAAGGCCTACCACCCTTCATTTCTACTCTCACACGGCCTCATACAGTACTCCTCCTTTCACAATTTACATCTCCTTTTTGAAGAATACACCAACATCCCCGTTTCTCTACTTTTTAACGAAAAAGAGGCAAATGACACTGACCATGAGCCCCAAATATCCCCCGGGGGCTTAGAGCCTCCCGCTGAAAAACATTTCCGCGAAACAGAAGTC'\n        changes_potential, a dict, with key=pair of codons tuple, e.g. ('ATG','ATG'), and value=['S':<S>,'N':<N>]. Where <S> is the number of potential synonmyous sites for each codon (averaged between the two codons), and <N> is the same but for non-synonymous sites.\n            e.g. changes.potential_changes_dict(...)  (see: ./changes.py)\n        changes_observed, @todo\n        msCorrect, a string to toggle between multiple-substitution correction methods:\n            \"approximate\", \"exact\" (@todo: make sure it actually is exact... it could be\n             something else)\n\n            e.g. msCorrect = 'approximate'\n        sliding, a boolean to toggle between sliding window analysis (vector of dN/dS values at successive chunks of sequence) or whole sequence analysis (a single\n            dN/dS value for the given pair of input sequences), either: True, False\n\n            e.g. sliding = False\n        windowLength, an integer specifying the width of the sliding window, measured in no. of codons in the window to measure dN/dS over, from 1-to-length(seq1)\n\n            e.g. windowLength = 50\n        stepLength, an integer specifying no. of codons to shift the sliding window with each iteration. If stepLength < windowLength then windows will overlap, overlapping is dealt with prior to plotting (acts to smooth values, averages along the overlaps are taken as a dN/dS value for any codon).\n            e.g. stepLength = 1\n    NOTES:\n        Sources of formulae:\n            http://www.megasoftware.net/mega4/WebHelp/part_iv___evolutionary_analysis/computing_evolutionary_distances/distance_models/synonymouse_and_nonsynonymous_substitution_models/hc_nei_gojobori_method.html\n    \"\"\"\n\n    def chunks(l, n):\n        \"\"\" Yield successive n-sized chunks from l. \"\"\"\n        for i in xrange(0, len(l), n):\n            yield l[i:i+n]\n\n    # todo: stop codons to deal with, reject\n    # todo: ambiguous bases to deal with:\n        # gaps,  @done\n        # Ns,    @todo\n        # Xs     @todo\n\n    warning_count = 0\n\n    # STATS per CODON-PAIR:\n    codons_seq1   = [codon for codon in chunks(seq1,3)]  #splits\n    codons_seq2   = [codon for codon in chunks(seq2,3)]\n    codons_paired = [pair for pair in zip(codons_seq1,codons_seq2) if (len(pair[0])+len(pair[1]))==6] # aligned codons are paired into tuples, excess codons are truncated, @todo: in main example, we lose 5 bps of data\n\n    # @done: the next for loop is extremely innefficient, I should set the structure of the changes_potential and changes_observed dicts to how I want it to look, a priori, i.e. when it's instantiated in changes.py.\n    # OR just remove this chunk and access the data as they come in the args\n\n    changes_all = {'observed':{'S':[],'N':[]},'potential':{'S':[],'N':[]}}\n\n    for pair in codons_paired:\n        changes_all['potential']['S'].append(changes_potential[pair]['S'])\n        changes_all['potential']['N'].append(changes_potential[pair]['N'])\n        changes_all['observed']['S'].append(changes_observed[pair]['S'])\n        changes_all['observed']['N'].append(changes_observed[pair]['N'])\n\n    list_S  = changes_all['potential']['S']\n    list_Sd = changes_all['observed']['S']\n\n    list_N  = changes_all['potential']['N']\n    list_Nd = changes_all['observed']['N']\n\n    if sliding:\n        # STATS for each WINDOW seq\n        intervals    = range(0,len(codons_paired)-windowLength+1,stepLength)\n        windows      = zip(intervals,[i + windowLength - 1 for i in intervals])\n\n        window_stats = {}\n\n        #window_stats_list = []\n\n        # @done: test against matlab's sliding window, also @todo: find out what stepLength does, @todo: try to plot the sliding window version\n\n        for window_i,window in enumerate(windows):\n\n            start = window[0]\n            end   = window[1]+1\n\n            window_stats[window] = {    'S':sum(list_S[start:end]),\n                                        'Sd':sum(list_Sd[start:end]),\n                                        'N': sum(list_N[start:end]),\n                                        'Nd':sum(list_Nd[start:end])    }\n\n\n            pS = window_stats[window]['Sd']/window_stats[window]['S']\n            pN = window_stats[window]['Nd']/window_stats[window]['N']\n\n            try:\n                if msCorrect=='approximate':\n                    dN = -(3./4.)*math.log(1.-(4./3.)*pN)\n                    dS = -(3./4.)*math.log(1.-(4./3.)*pS)\n\n                # @todo: what is this commented code? I don't remember...\n                # elif msCorrect=='exact':\n                #     d=ln(1-p*4/3)/ln(1-3/(4*N))\n\n                else: # msCorrect=='????'  # @todo: is this the exact one? Or something else?\n                    dN = pN\n                    dS = pS\n                window_stats[window]['dNdS'] = dN/dS\n            # @todo: I'm not sure I'm treating the following exceptions in the right way...\n            # technically it woud be best to exclude these from downstream analyses?\n            # e.g. missing value/datapoint on a plot of dN/dS (y-axis) vs. window interval (x-axis)\n            except ZeroDivisionError:\n                warning_count += 1\n                #warn_msg = \"Query and Reference sequences are too divergent. Approximate multiple-substitutions correction cannot be achieved, for window: \"+str(window_i)+\", dS is zero, leading to a division error when trying dN/dS... try alternative value for argument: msCorrect (e.g. 'exact') OR alternative value for argument: windowLength (e.g. \"+str(windowLength+20)+\") ...\\n\"   # # @TODO: uncomment for verbose warning message prints // @ANDY-2017-01-30\n                #warnings.warn(warn_msg)  # @TODO: uncomment for verbose warning message prints // @ANDY-2017-01-30\n                window_stats[window]['dNdS'] = float('Inf')\n            except ValueError:\n                warning_count += 1\n                #warn_msg=\"Query and Reference sequences are too divergent. Approximate multiple-substitutions correction cannot be achieved, for window: \"+str(window_i)+\",  SYNONYMOUS changes per synonymous site, pS>=3/4, log() operation will yeild return undefined... try alternative value for argument: msCorrect (e.g. 'exact') OR alternative value for argument: windowLength (e.g. \"+str(windowLength+20)+\") ...\\n\"  # # @TODO: uncomment for verbose warning message prints // @ANDY-2017-01-30\n                #warnings.warn(warn_msg)  # @TODO: uncomment for verbose warning message prints // @ANDY-2017-01-30\n                window_stats[window]['dNdS'] = float('nan')\n\n        return window_stats,warning_count  # list of dnds per window interval // dict of dnds, key=(<from #base pair>,<to #base pair>), value=<dN/dS of the window specified in the key>\n    else:\n        # STATS for WHOLE SEQ\n        S   = sum(list_S)\n        Sd  = sum(list_Sd)\n        pS  = Sd/S\n        N   = sum(list_N)\n        Nd  = sum(list_Nd)\n        pN  = Nd/N\n\n        try:\n            if msCorrect=='approximate':\n\n                if (pS>=3./4.):\n                    raise ValueError(\"Query and reference sequences are too divergent. Approximate multiple-substitutions correction cannot be achieved, SYNONYMOUS changes per synonymous site, pS>=3/4, log() operation will yeild return undefined. Try alternative value for argument: msCorrect (e.g. 'exact')...\")\n\n                if (pN>=3./4.):\n                    raise ValueError(\"Query and reference sequences are too divergent. Approximate multiple-substitutions correction cannot be achieved, NON-SYNONYMOUS changes per synonymous site, pN>=3/4, log() operation will yeild return undefined. Try alternative value for argument: msCorrect (e.g. 'exact')...\")\n\n                dS  = -(3./4.)*math.log(1.-((4./3.)*pS))\n                dN  = -(3./4.)*math.log(1.-((4./3.)*pN))\n                dN_dS = dN/dS\n\n            else: # @todo: is this the exact one? Or something else?\n\n                # @DONE: one day the following three lines of code will error, giving a ZeroDivisionError, this needs to be handled with try\n                dS = pS  # i.e. dS = Sd/S\n                dN = pN\n                dN_dS = dN/dS\n        except ValueError:\n            warning_count += 1\n            warnings.warn(\"Query and reference sequencea are too divergent. ValueError: Approximate multiple-substitutions correction cannot be achieved: UNKNOWN reason, probably due to illegal numbers in a log() function...\\n\")\n            dN_dS = float(\"nan\")\n        except ZeroDivisionError:\n            warning_count += 1\n            warnings.warn(\"Query and reference sequences are too divergent. ZeroDiviSionError: Approximate multiple-substitutions correction cannot be achieved: UNKNOWN reason, probably due to illegal numbers in a log() function...\\n\")\n            dN_dS = float('Inf')\n\n        return dN_dS, warning_count  # i.e. omega = dN/dS = (Nd/N)/(Sd/S)\n\n\ndef plot_dnds_sliding(dnds_slide_dict):\n\n    \"\"\" Plots sliding dN/dS values (y-axis) along the input sequence's aligned codons (x-axis). If the sliding windows overlap (see below), then plot_dnds_sliding will also average the overlapping dN/dS values for each codon.\n        ----     window 1\n         ----    window 2\n          ----   ...\n        ^^^^^^^  take average along each column (codon)\n    ARGS:\n        dnds_slide_dict,    the output of dnds() if the 'sliding' optional argument is set to True\n            e.g. dnds_slide_dict = dnds( s1, s2, potential_changes, observed_changes, msCorrect='approximate', sliding=True, windowLength=50, stepLength=1 )\n    RETURNS:\n        None,   a plot is generated and written to: py/data/dnds_sliding_test.png\n    \"\"\"\n    #import pickle\n\n    # #\n    # # dnds_slide_dict has overlapping windows of dnds calculated, windows overlap by stepLength bps, and are uniformly windowLength wide\n    # #\n    # with open(\"py/data/dnds_slide_dict.p\",\"r\") as fi:\n    #     dnds_slide_dict=pickle.load(fi)\n\n    #window_intervals = sorted(dnds_slide_dict.keys()) # @todo: I dont think sorting the windows will make a difference to final result, but it will make it slower, @todo: test this just in case\n    window_intervals = dnds_slide_dict.keys() # @todo: I dont think sorting the windows will make a difference to final result, but it will make it slower, @todo: test this just in case\n\n    #\n    # vectorize and find max of the window_intervals\n    #\n    max_window_position = np.amax(window_intervals) # e.g. 243 @done: a whole order of magnitude faster than: max_window_interval = max(window_intervals, key=lambda x: x[1])\n    # @todo: ^ doing equivalent operations on np.array() (instead of list) is much faster, so maybe this means we should  np.arrays() in the rest of the code in dnds.py and changes.py\n    # @DONE: Q: would finding the max() be faster than sorting then indexing? A: yes\n\n    #\n    # Initialise matrix with NaN, each row is the values for a specific window, these will cascade\n    #       and overlap to various degrees depending on stepLength and windowLength\n    #\n\n    # ----     window 1\n    #  ----    window 2\n    #   ----   ...\n    # ^^^^^^^  take average along each column\n    #\n    overlap_matrix      = np.empty((len(window_intervals),max_window_position+1))  # @todo: are you sure it's +1? initialize empty matrix, note: entries are not actually NaN, just near-zero\n    overlap_matrix[:]   = np.NAN # initiate empty np array with NaN, so later we can mask\n\n    for window_i,window in enumerate(window_intervals):\n\n        start = window[0] # e.g. 0\n        end   = window[1] # e.g. 49\n\n        # in the i-th row, fill all elements from the window[0]-th to window[1]-th with the dN/dS value for this window\n        overlap_matrix[window_i,start:end+1] = dnds_slide_dict[window]['dNdS'] # @todo: are you sure it's +1? test, keep in mind for these indices it does -1 for the \"to\" part\n\n    #\n    # Mask all non-finite values, to allow proper plotting\n    #\n    nan_masker              = ~np.isfinite(overlap_matrix) # boolean matrix, True if element is finite, False if element is Inf or NaN\n    overlap_matrix_masked   = np.ma.masked_array(overlap_matrix,mask=nan_masker)\n\n    #\n    # Columwise averages (i.e. avg all values in each column, leading to a 1D vector of averages)\n    #\n    overlap_matrix_avg      = overlap_matrix_masked.mean(axis=0)\n    #overlap_matrix_avg.mean() # sanity: 0.15584966052233765 (whole seq average: 0.152307100775) not bad!\n\n    #\n    # Plot dN/dS along the input sequences\n    #\n    # plt.plot(overlap_matrix_avg)\n    # plt.show()\n    # plt.savefig(\"py/data/dnds_sliding_test.png\")\n    # avg_matrix = overlap_matrix.mean(axis=1)\n    # print overlap_matrix_avg\n    return list(overlap_matrix_avg), overlap_matrix_avg.mean()\n\n\n# @ANDY:code redundancy, can uncomment if we need to load this whole pipeline as a function\n\ndef dnds_pipeline(qry_seq_in, ref_seq_in):\n\n    \"\"\" Runs the whole dnds pipeline for sliding windows, returns the smoothed vector\n    of dN/dS values along the codons of the query sequence.\n    Essentially the same code as: if __name__ == \"__main__\": ...\n    \"\"\"\n\n    #\n    # TRY CACHED DATA:\n    #   Open dictionaries that have cached computationally intensively\n    #   produced results, these are all possible codon pairs with cached statistics for all possible pairs regardless of user input seqs\n\n    print(\"\\t============================================================================\") # @todo:REMOVE\n    print(\"\\tdN/dS sliding analysis: pre-cached statistics for all possible codon pairs...\")\n    print(\"\\t============================================================================\") # @todo:REMOVE\n\n    #\n    try:\n    #if (os.path.exists(\"./py/data/observed_changes_dict.p\") and os.path.exists(\"./py/data/potential_changes_dict.p\")):\n    # LOAD CACHED (fast)\n\n        #\n        # Unpickle codonPair-to-statistics dictionaries\n        #\n        f1 = open('observed_changes_dict.p','rb')\n        observed_changes  = pickle.load(f1)\n        f1.close()\n\n        f2 = open('potential_changes_dict.p','rb')\n        potential_changes = pickle.load(f2)\n        f2.close()\n\n        print(\"\\t\\tLOADED!\") # @todo:REMOVE\n\n    except IOError:\n    #else:\n    # CREATE NEW (slow)\n\n        #\n        # Create dictionary of codon (DNA-triplet, e.g. \"ATG\") -to- amino\n        #   acid residue (e.g. \"M\")\n        #\n        nt_to_aa_dict     = codon_pair_data.geneticCode(\"standard\")\n\n\n        # alternative 1 {{\n\n        # #@todo:Urgent:debug:2016-11-28: why does the following two lines (commented) lead to silent error? For some reason I HAVE to pickle the data to get it to work... when I just return the dicts directly I get the wrong dN/dS values. The following two lines illustrate this, when uncommented in place of the \"# @2:Create\" and \"# @2:Unpickle\" blocks of code...\n        # observed_changes  = codon_pair_data.potential_changes_dict(nt_to_aa_dict)\n        # potential_changes = codon_pair_data.observed_changes_dict(nt_to_aa_dict)\n\n        #}} 1 alternative 2 {{\n\n        #\n        # @2:Create the cached codonPair-to-statistics dictionaries, then pickle\n        #\n        codon_pair_data.potential_changes_dict(nt_to_aa_dict)\n        codon_pair_data.observed_changes_dict(nt_to_aa_dict)\n\n        #\n        # @2:Unpickle codonPair-to-statistics dictionaries\n        #\n        #f1 = open('./py/data/observed_changes_dict.p','rb') # @todo:coderedundancey = bad, wrap these lines into a function and call the function\n        f1 = open('observed_changes_dict.p','r') # @todo:coderedundancey = bad, wrap these lines into a function and call the function\n        observed_changes  = pickle.load(f1)\n        f1.close()\n\n        #f2 = open('./py/data/potential_changes_dict.p','rb')\n        f2 = open('potential_changes_dict.p','r')\n        potential_changes = pickle.load(f2)\n        f2.close()\n\n        # }} alternative 2\n\n        print(\"\\t\\tCREATED!\") # @todo:REMOVE\n\n\n    #\n    #  Calculate dN/dS\n    #\n\n    # @todo:\n    #   Q:These are either taken as cmd input args or from a tmp file?\n    #   A: No, we take them from the output of align.align_query_vs_reference() and align.trim_gaps_from_aligned_seqs() (align. imported as align_then_trim.)\n\n\n    # alternative 1 {{\n\n    # Aligned and Trimmed HTLV-1 vs. STLV-1 proteins (MATLAB example to benhmark dnds calculations)\n    # s1 = 'ATGCGCAAATACTCCCCCTTCCGAAATGGATACATGGAACCCACCCTTGGGCAGCACCTCCCAACCCTGTCTTTTCCAGACCCCGGACTCCGGCCCCAAAACCTGTACACCCTCTGGGGAGGCTCCGTTGTCTGCATGTACCTCTACCAGCTTTCCCCCCCCATCACCTGGCCCCTCCTGCCCCATGTGATTTTTTGCCACCCCGGCCAGCTCGGGGCCTTCCTCACCAATGTTCCCTACAAACGAATAGAAAAACTCCTCTATAAAATTTCCCTTACCACAGGGGCCCTAATAATTCTACCCGAGGACTGTTTGCCCACCACCCTTTTCCAGCCTGCTAGGGCACCCGTCACGCTGACAGCCTGGCAAAACGGCCTCCTTCCGTTCCACTCAACCCTCACCACTCCAGGCCTTATTTGGACATTTACCGATGGCACGCCTATGATTTCCGGGCCCTGCCCTAAAGATGGCCAGCCATCTTTAGTACTACAGTCCTCCTCCTTTATATTTCACAAATTTCAAACCAAGGCCTACCACCCCTCATTTCTACTCTCACACGGCCTCATACAGTACTCTTCCTTTCATAATTTGCATCTCCTATTTGAAGAATACACCAACATCCCCATTTCTCTACTTTTTAACGAAAAAGAGGCAGATGACAATGACCATGAGCCCCAAATATCCCCCGGGGGCTTAGAGCCTCTCAGTGAAAAACATTTCCGTGAAACAGAA'\n    # s2 = 'ATGCGCAAGTACTCCCCCTTCCGAAACGGATACATGGAACCCACCCTTGGGCAACACCTCCCAACCCTGTCTTTTCCAGACCCCGGCCTCCGGCCCCAAAACCTGTACACCCTCTGGGGAGACTCTGTTGTCTGCCTGTACCTCTACCAGCTCTCCCCCCCCATCACCTGGCCCCTCCCGCCCCATGTGATTTTTTGCCACCCCGGCCAGCTCGGGGCCTTCCTCACCAATGTTCCCTACAAGCGTATGGAAGAACTCCTCTATAAAATTTCCCTTACCACAGGGGCCCTAATAATTCTACCCGAGGACTGTTTACCAACCACCCTTTTCCAGCCTGCTAGGGCCCCCGTCACGTTGACCGCCTGGCAGAACGGCCTCCTTCCGTTCCACTCAACCCTCACCACTCCAGGCCTTATTTGGACATTTACCGATGGCACGCCTATGGTTTCCGGACCCTGCCCCAAAGATGGCCAGCCATCTTTAGTACTACAGTCCTCCTCATTTATATTTCACAAATTTCAAACCAAGGCCTACCACCCTTCATTTCTACTCTCACACGGCCTCATACAGTACTCCTCCTTTCACAATTTACATCTCCTTTTTGAAGAATACACCAACATCCCCGTTTCTCTACTTTTTAACGAAAAAGAGGCAAATGACACTGACCATGAGCCCCAAATATCCCCCGGGGGCTTAGAGCCTCCCGCTGAAAAACATTTCCGCGAAACAGAA'\n\n\n    # }} 1 alternative 2  {{  # @todo: debug:ever since the .p loading bug,\n    #                               which is still un-resolved (see: \"@todo:Urgent:debug:2016-11-28\")\n    #                               I think we should test a load( .p ) version just in case and check\n\n    #\n    # AGAP010815 (gambiae)\n    #     https://www.vectorbase.org/Anopheles_gambiae/Gene/Sequence?db=core;g=AGAP010815;r=3L:11202091-11206882;t=AGAP010815-RA\n    qry_seq_raw = qry_seq_in\n    # s1_AGAP010815_RA = 'ATGTGGCAGTTCATAAGGTCACGAATATTAACGGTGATAATCTTCATAGGTGCTGCTCATGGGCTACTGGTTGTGGGTCCGAAATTTATACGGGCCAACCAGGAATACACTCTGGTGATCAGCAACTTTAACTCACAGCTAAGCAAAGTGGACCTGCTGTTAAAACTGGAAGGCGAAACTGATAATGGTTTAAGCGTTCTGAACGTTACCAAGATGGTTGACGTGCGACGTAATATGAACCGAATGATCAACTTCAATATGCCTGAGGATCTGACGGCTGGAAACTACAAAATAACTATCGATGGACAGCGTGGCTTCAGCTTTCACAAGGAGGCAGAGCTGGTGTATCTCAGCAAATCGATATCGGGGCTAATACAGGTCGATAAGCCCGTATTTAAACCTGGGGATACGGTGAACTTCCGTGTGATCGTGCTGGACACGGAGCTGAAACCGCCGGCGAGGGTCAAGTCGGTTTATGTAACTATACGAGATCCTCAGCGCAATGTGATTCGCAAATGGTCCACGGCAAAACTGTATGCCGGTGTGTTCGAGAGCGATCTACAGATAGCGCCTACTCCAATGCTCGGGGTCTGGAATATCTCGGTGGAGGTGGAAGGAGAAGAGCTTGTGTCAAAGACGTTTGAGGTGAAGGAGTACGTGTTGTCAACGTTCGACGTGCAGGTCATGCCATCGGTGATTCCACTGGAAGAGCATCAAGCTGTGAATCTTACAATCGAAGCGAACTATCACTTTGGTAAGCCAGTGCAAGGAGTGGCCAAGGTGGAGCTGTACCTAGACGACGATAAGCTAAAACTGAAAAAAGAGCTGACTGTGTACGGAAAGGGCCAGGTAGAGTTGCGCTTTGACAATTTTGCAATGGATGCGGATCAGCAGGATGTACCAGTGAAGGTGTCGTTCGTCGAGCAGTACACAAATCGTACGGTGGTCAAACAGTCACAAATCACGGTATATAGGTATGCGTACCGAGTAGAGTTGATAAAAGAGAGTCCACAGTTTCGTCCGGGACTCCCGTTCAAATGTGCGCTTCAGTTTACACACCATGATGGAACACCGGCTAAAGGCATTAGCGGTAAGGTAGAGGTATCCGATGTACGATTCGAAACGACAACAACGAGTGATAACGATGGATTGATTAAGCTCGAGCTGCAACCAAGTGAGGGTACTGAACAACTCAGTATTCACTTCAATGCTGTTGATGGATTCTTTTTTTATGAAGATGTGAATAAGGTAGAAACGGTTACGGATGCGTATATTAAACTGGAGCTGAAATCACCGCATCAAACGGAACAAATTGATGCGTTTCATGGTGACGTGCACGGAGCGCATGACATTCTTCGTGTACTATGTCATGTCAAAGGGCAATATCATCGATGCAGGATTCATGCGACCCAACAAGCAACCGAAGTACCTGTTGCAGCTGAACGCAACAGAAAAGATGATTCCGAGGGCGAAAATTCTCATCGCTACCGTAGCGGGCCGCACGGTGGTGTACGACTTCGCAGACCTCGATTTCCAAGAGCTTCGCAATAATTTTGATTTAAGCATTGACGAGCAAGAGATCAAGCCGGGACGACAAATCGAGCTGAGCATGTCTGGACGCCCAGGAGCGTACGTTGGGCTGGCCGCGTATGACAAAGCCTTGCTGCTTTTCAACAAGAACCACGACCTGTTCTGGGAGGACATTGGGCAGGTGTTTGATGGGTTCCATGCAATCAATGAGAACGAGTTTGACATATTCCACAGCTTGGGTCTGTTCGCCAGGACATTGGACGATATCTTGTTCGACAGTGCAAATGAAAAGACGGGGCGTAATGCACTGCAGTCAGGCAAGCCGATCGGCAAGCTGGTGTCGTATCGGACGAACTTCCAGGAATCGTGGTTGTGGAAAAATGTTTCCATCGGACGATCGGGAAGTCGCAAGTTGATCGAGGTAGTACCGGACACGACCACCTCCTGGTATCTGACGGGCTTCTCGATCGATCCCGTGTACGGGTTGGGTATCATCAAGAAGCCAATCCAGTTCACAACAGTCCAGCCGTTCTACATCGTAGAGAACTTACCATATTCAATCAAACGAGGCGAAGCGGTTGTGTTGCAGTTTACGCTGTTCAACAACCTTGGAGCGGAGTATATAGCCGATGTGACGCTGTACAATGTGGCCAACCAGACCGAGTTCGTCGGACGTCCAAATACGGATCTCAGCTACACCAAATCCGTGAGCGTTCCTCCAAAAGTTGGTGTGCCAATCTCGTTCCTCATCAAGGCCCGCAAGCTCGGCGAGATGGCGGTTCGTGTAAAGGCTTCGATAATGCTGGGACACGAAACGGACGCCCTGGAAAAGGTAATACGGGTGATGCCTGAAAGTTTGGTGCAGCCGAGAATGGATACACGCTTTTTCTGCTTCGACGATCACAAAAATCAAACGTTTCCGATCAACTTGGACATCAACAAGAAGGCCGACAGTGGATCGACAAAGATTGAGTTTCGACTAAATCCCAATTTGTTGACCACGGTCATCAAGAACCTGGACCATCTTCTCGGCGTTCCGACGGGATGTGGTGAGCAGAATATGGTCAAATTTGTTCCCAACATTTTGGTACTGGATTATTTGCATGCCATCGGGTCGAAAGAACAGCATCTAATCGACAAAGCTACGAATTTGTTGCGTCAAGGATATCAAAACCAGATGCGCTACCGTCAGACGGATGGTTCATTTGGTTTGTGGGAGACTACTAATGGTAGCGTGTTTCTCACCGCGTTCGTTGGCACATCGATGCAAACTGCAGTAAAATACATAAGCGATATTGATGCAGCAATGGTGGAGAAGGCATTGGATTGGTTAGCCTCGAAGCAGCATTTCTCGGGACGGTTTGACAAGGCCGGTGCAGAGTATCACAAAGAAATGCAAGGAGGGTTGCGCAATGGTGTGGCCCTCACATCATATGTGTTGATGGCATTGCTGGAGAATGACATTGCCAAAGCAAAGCACGCAGAGGTGATTCAAAAAGGAATGACCTATCTGAGCAATCAGTTTGGATCCATCAACAATGCATACGACCTATCGATAGCAACCTACGCGATGATGTTGAACGGACACACCATGAAGGAGGAGGCACTCAATAAGCTGATTGATATGTCTTTCATTGATGCTGATAAAAACGAACGGTTCTGGAACACAACGAATCCAATAGAAACCACCGCATATGCTCTGCTGTCGTTTGTGATGGCCGAGAAGTACACAGACGGTATACCGGTCATGAATTGGTTGGTGAATCAACGTTACGTTACCGGTAGCTTTCCGAGCACGCAAGACACGTTTGTGGGGCTGAAAGCGCTGACCAAAATGGCGGAAAAGATATCTCCGTCCCGAAACGACTACACCGTTCAACTGAAGTACAAGAAGAGTGCAAAATACTTCAAAATAAACTCGGAGCAAATTGATGTGGAAAACTTCGTGGATATACCGGAGGACACAAAAAAGCTCGAGATCAATGTGGGGGGCATTGGATTTGGGTTGTTAGAGGTGGTTTATCAATTTAATTTGAATCTCGTCAACTTTGAGAATAGATTCCAACTAGACCTGGAGAAACAGAACACAGGCTCTGACTACGAGCTGAGGCTGAAGGTCTGTGCCAGCTACATACCCCAGCTGACCGACAGACGATCGAACATGGCACTGATTGAGGTAACCTTACCGAGCGGTTACGTGGTTGATCGCAATCCGATCAGCGAGCAGACGAAGGTGAATCCGATTCAGAAAACTGAAATCCGTTACGGTGGCACTTCAGTCGTTTTATACTACGACAATATGGGCAGCGAGCGTAACTGTTTCACCCTGACCGCGTACAGACGCTTTAAGGTCGCATTGAAGCGTCCAGCGTATGTGGTTGTGTATGATTATTATAATACAAATCTGAACGCCATCAAAGTGTACGAAGTGGACAAGCAGAATTTGTGCGAAATCTGTGACGAAGAAGACTGTCCTGCAGAGTGCAAAAAATAG'\n    #\n    # AAEL001802 (aegypti)\n    #     https://www.vectorbase.org/Aedes_aegypti/Gene/Sequence?db=core;g=AAEL001802;r=supercont1.43:685886-717122;t=AAEL001802-RA\n    ref_seq_raw = ref_seq_in\n    #s2_AAEL001802_RA = 'ATGTCGGTATTCATACAAACGGACAAACCGGTGTATACCCCGGGAGATCTGATACGTTTTCGGGTAATCGTGGTGGATGCTGACACTAGACCTGTGACTAGTATTAAAACGGTAAATATAGCGATCGACGATTCTGCAAAAAATTCCATTCGAAAGTGGCCTTATGCCAAGTTGTTAAACGGCATCTTTGAGTCACAAGTGCAATTAGCTTCTTCGCCTGTTCTTGGCACCTGGATTATCAACGTAACAGCTTCCGACGACATCATTGTCACCAAACAGATAGAAGTTAAGGAATATGTGTTGCCAAAATTTTTCGTGAAAGTTTACCCTTCGGAGGTTCTATTGGGGAAAAATAAGAAGGTTTCTCTTACCTTAGATGCCTATTACACGTTCAAAGAACCCGTCGACGGCAATTACAAAGTTGAGTTATTTTTGGACCATACCAAGAGAAAGCCTGACTTCATAAAAAGTGATCGAATCACCGGTAAAACATCACTTGAGTTTCAATTGAAAAATGAAGTAGACATTGATGGCGACGAGCAGTACACTGATGTCACGGTTGAAGTTGAAGTTGTCGAGGCATTTTCTAATCGCACAGTTAGTATAACTGAGAATATTCCGATTTATCGTCAGCCTTATACCGTGACCCTTCTTCCATCTGCACCATCATTTCGACCAGGAGTTCCATTCAATGTACAAATAGTTGTGAAAGATCAGCTTGGACACCCTCCTGCCGAAGAAAAAGCGGCATCAATTGACCTTACTGTAGAGTTCCATTTGCCCATTGACAGTGACACCAAATCTATCACTGTAGATCTGGACGAGAAAGGAACAGGTCAGCTCACATTAGAGCCCCGCCCAGACGCCCAAGAACTGAAAGTGAACGCTACATATGACTCTCAACAATACGATGTAATTCACGATCCGATACATGGTTTCAGTTCGCAAAGTAAGCAGTACATCACAGTAACTCTGAATCCAAAATACTATAACAACATTAAAGTCGATAAGGACATCGTACTGGACATCTCCTGCACTGAAACAATGACGCACTTCTCGTACATCGTTGTCACCAGAGGAAACATAGTGGAAGCATCGAACGTTCCTGTCAGGATAAAAAAGAAACATTCTCTGAGATTGAAAATGACTTCAAAAATGTCTCCGGAGTCGAGGCTTCTAGTGTACTATACAAACAGGGAGTATCTCATCTTTGATGATATTGAGCTGAAGTTCGATTCGTTCAACAACGACTTCAAATTCGATTTGAACGATGATGAGTATTTTCCAGGGCAATCAGTTTATATCGATGTATACGCTTCAAAGGATTCATACGTTGCGTTCAGTGGAATCGATGAAAGTGTACTCCTGGTAGGCAAAGAGCGCCATGACTTCAACAAAGGAGATGTGCTCAAGGAACTCGCTCTTTACGGAGCAACAAATGATGCCGAGTTTGACTTGTTCCACGTAAGTTTCATGTCAAATGGTTTGATTATTCCAGTTAATGTATCTGTAACTCGCTCACAGAATGCACGATTTGGTACTCTACTAGGAAGGACTAGGCAGCAAGCGATTGAAATTCGAACTCAATTCCTAGAATCCTGGTTATGGAAATCCTTTTCCATGGATGGTCGAAACAACTTCAAAGCAATAGAAGACTCGGTTCCGGATACTATTACAACGTATCACGTGTCAGGATTTGCTTTAAGTCCAACACTAGGTCTTGGAGTAATCCAACAACCAGTGAGTTTCACCGTTCGTAAAAAATTCTACTTGGTTGCAAATTTGCCTTACTCGATCAAACGGGGTGAAGTGGCGTTGATTCAGGTTACCGTCTTCAACTTCCTAGGAAGCAGCATAACAACCGATGTGACGCTGTTCAATAAACGCGATGAAATTGAGTTTGTCGAGAATGCATCCACTAATAATACACATCGAACAAAGGCGGTAATTGTCCCGAATAACAATGGAAAATCTGTATCATTTATGGTGAAAGCAAAGAAATTAGGACAGATTGCGATCAAATTCCAGGCGGTAAACCTGCTGGAAACGGATGCATTGGAGCACATGTTACGAGTAACCCCAGAGAGCCATCGCTATGAGAAAAATGTAGCTCGATTCGTTGAGCTACCAAAGTTTGAGACGCAAACTTTCGATGTGAAGCTGGACATTCCCAAAAATATCGACGAGGGTTCTGCTCAAATCAAATTCACGTTAGACCCGGACATTTTGGGAACAGCCATCAGCAACCTAGACGGGTTGATCCGGAAACCCTTTGGATGTGGCGAACAAAATATGCTCCATTTTGTGCCAAATATAGTCGTTTTGGATTATCTTAACGAAACCAACACAGCGGCAGAAGATGTGAGGACCAAAGCGATAAATTTTCTTAGCAGCGGATATCAAAACCAGCTACGCTACAAACGTTCGGATGGGGCCTTCAGTGTCTGGGGACAATCGTATGCTGGCAGTACATTTTTGACGGCCTTTGTGGCGAAATCATTCAAAATAGCAGCCAAATACATTCAGGTGGATAAGTCTATAGTAGACGCGGCATTCGACTGGTTAGTGAAACAACAACAATCAGATGGGCGGTTCCCAGAAGTGGGGCAAGTATTCCAAGCAGATATGCAGGGTGGGCTTCGTAATAACGGTTTTGCGCTTACCGCGTATGTTCTGATCGCTTTTGCTGAAAATAAGGAAGTATACAGAAAATACCAATCACAACTGAACAAAACTACTAACTTCATAGCAGATAGACTTGCTAATATGGAGAATCCATACGACCTCTCGCTGTCCACTTATGCGTTGATGCTAACAAATCATGGCAAGCGCACCGAGTTTCTTCACAAATTAGTCGAAAAGTCGATATTTGACCGCAATCAAACTGAGAGATATTGGGACAGCAAACCAGTTGATATTGAAGTTGCTGGATATGCTCTATTGTCATACGTAGCTGCCGGTAAATTATTGGATGCAACGCCTATCATGCGGTGGCTCAACAAGCAGCGTTATGGTCTCGGAGGCTATCCTGGAACTCAGGAAACATTCGTTGGATTGAAAGCATTGGCAACGTTCGCTGCAAATGTAACTAGTAGGAGAAACGAATATACTGTAAGGATATTCTACGAACCAAATGGTCGACGAACATTCGACGTACACATGCACAATTCGTTTAATATTCAAGAGCTTGACATTCCTAATAACATCAGAAAAATGAAGGTGGAAGTTGAAGGCATCGGCAGAGGCTTCTTCCAAGTGGCATATCAGTACTATCAAAATATGCAGGTGGCTAAGCCCAGTTTCAGCATTACAATTAATCAGCTTAACACCACGACGGAACACATGCAGCAATTGGACGTGTGTGTGAAATACATACCAAAAGAGGCTTATCAAAAATCGAATATGGCTTTGGTGGAAATATTCTTGCCTAGTGGGCTTGTAGCAGACTCAGATGCCATTACGGACAAGACTGGAGGAATTCGAAGAATTGAAAGACGTTTTTCGGACACCTCAGTAGTTATATATTATGATAATTTGGACCCCGAAGACAAGTGCTTCCGAGTGACTGCTTATCGTCGGTATAAAATTGCATTGCATTTGCCATCATATATTATAGTTTATGATTATTATAATTTTGAGCGCTTTGCCATTCAAAAGTACGAAGGAAAGGTGCTGCAGCTCTGCGATATTTGTGAAGACGAGGACTGCGAAACTTTATCATGTCAAAATAGCTCGAAATTGGCAATAATGTAA'\n\n\n    ###########################\n    # Benchmarking vs. MATLAB #\n    ###########################\n\n    print(\"\\t=========================================\")\n    print(\"\\tProcessing heuristic codon alignments....\")\n    print(\"\\t=========================================\")\n\n    # @done:@testing:benchmark vs. matlab: @todo: place in README these details\n    #   using s1_AGAP010815_RA and s2_AAEL001802_RA (after aligning/trimming)\n    # MATLAB whole dnds vs. andy-wenping whole dnds (msCorrect='approximate'): dN/dS:\n    #   1.0958 vs. 1.04939841193 (Elapsed time: 1.952491045, Total warnings: 0), respectively\n    # MATLAB mean(sliding dnds) vs. andy-wenping mean(sliding dnds): Mean dN/dS over all 50-codon long windows:\n    #   1.7254581782566112 (smoothing?) vs. 1.49715496621 (incl. smoothing, stepLength=1) (Elapsed time: 2.29854488373, Total warnings: 173) (when taking the mean of all 50 window intervals in MATLAB's sliding dnds()\n    # MATLAB sliding dnds plot vs. andy-wenping sliding dnds plot: similar sliding dnds plots:\n    #   see:  D:\\Dropbox\\00_HPC-LEAP\\WP5 Thematic Cyprus Computational Biology\\giannis_database\n\n    # @benchmark:matlab's dnds()\n    # dN/dS=0.15270463083614955 with msCorrect='approximate', dN/dS=0.16529268957638238 with\n    # msCorrect='exact', MATLAB gives: dN/dS=0.0221=dnds(seq1,seq2, 'geneticCode', 1, 'Method', 'NG'). This is a huge error, an order of magnitude off.\n    # seq1 = 'ATGCGCAAATACTCCCCCTTCCGAAATGGATACATGGAACCCACCCTTGGGCAGCACCTCCCAACCCTGTCTTTTCCAGACCCCGGACTCCGGCCCCAAAACCTGTACACCCTCTGGGGAGGCTCCGTTGTCTGCATGTACCTCTACCAGCTTTCCCCCCCCATCACCTGGCCCCTCCTGCCCCATGTGATTTTTTGCCACCCCGGCCAGCTCGGGGCCTTCCTCACCAATGTTCCCTACAAACGAATAGAAAAACTCCTCTATAAAATTTCCCTTACCACAGGGGCCCTAATAATTCTACCCGAGGACTGTTTGCCCACCACCCTTTTCCAGCCTGCTAGGGCACCCGTCACGCTGACAGCCTGGCAAAACGGCCTCCTTCCGTTCCACTCAACCCTCACCACTCCAGGCCTTATTTGGACATTTACCGATGGCACGCCTATGATTTCCGGGCCCTGCCCTAAAGATGGCCAGCCATCTTTAGTACTACAGTCCTCCTCCTTTATATTTCACAAATTTCAAACCAAGGCCTACCACCCCTCATTTCTACTCTCACACGGCCTCATACAGTACTCTTCCTTTCATAATTTGCATCTCCTATTTGAAGAATACACCAACATCCCCATTTCTCTACTTTTTAACGAAAAAGAGGCAGATGACAATGACCATGAGCCCCAAATATCCCCCGGGGGCTTAGAGCCTCTCAGTGAAAAACATTTCCGTGAAACAGAAGTC'\n    # seq2 = 'ATGCGCAAGTACTCCCCCTTCCGAAACGGATACATGGAACCCACCCTTGGGCAACACCTCCCAACCCTGTCTTTTCCAGACCCCGGCCTCCGGCCCCAAAACCTGTACACCCTCTGGGGAGACTCTGTTGTCTGCCTGTACCTCTACCAGCTCTCCCCCCCCATCACCTGGCCCCTCCCGCCCCATGTGATTTTTTGCCACCCCGGCCAGCTCGGGGCCTTCCTCACCAATGTTCCCTACAAGCGTATGGAAGAACTCCTCTATAAAATTTCCCTTACCACAGGGGCCCTAATAATTCTACCCGAGGACTGTTTACCAACCACCCTTTTCCAGCCTGCTAGGGCCCCCGTCACGTTGACCGCCTGGCAGAACGGCCTCCTTCCGTTCCACTCAACCCTCACCACTCCAGGCCTTATTTGGACATTTACCGATGGCACGCCTATGGTTTCCGGACCCTGCCCCAAAGATGGCCAGCCATCTTTAGTACTACAGTCCTCCTCATTTATATTTCACAAATTTCAAACCAAGGCCTACCACCCTTCATTTCTACTCTCACACGGCCTCATACAGTACTCCTCCTTTCACAATTTACATCTCCTTTTTGAAGAATACACCAACATCCCCGTTTCTCTACTTTTTAACGAAAAAGAGGCAAATGACACTGACCATGAGCCCCAAATATCCCCCGGGGGCTTAGAGCCTCCCGCTGAAAAACATTTCCGCGAAACAGAAGTC'\n    # dnds('ATGCGCAAATACTCCCCCTTCCGAAATGGATACATGGAACCCACCCTTGGGCAGCACCTCCCAACCCTGTCTTTTCCAGACCCCGGACTCCGGCCCCAAAACCTGTACACCCTCTGGGGAGGCTCCGTTGTCTGCATGTACCTCTACCAGCTTTCCCCCCCCATCACCTGGCCCCTCCTGCCCCATGTGATTTTTTGCCACCCCGGCCAGCTCGGGGCCTTCCTCACCAATGTTCCCTACAAACGAATAGAAAAACTCCTCTATAAAATTTCCCTTACCACAGGGGCCCTAATAATTCTACCCGAGGACTGTTTGCCCACCACCCTTTTCCAGCCTGCTAGGGCACCCGTCACGCTGACAGCCTGGCAAAACGGCCTCCTTCCGTTCCACTCAACCCTCACCACTCCAGGCCTTATTTGGACATTTACCGATGGCACGCCTATGATTTCCGGGCCCTGCCCTAAAGATGGCCAGCCATCTTTAGTACTACAGTCCTCCTCCTTTATATTTCACAAATTTCAAACCAAGGCCTACCACCCCTCATTTCTACTCTCACACGGCCTCATACAGTACTCTTCCTTTCATAATTTGCATCTCCTATTTGAAGAATACACCAACATCCCCATTTCTCTACTTTTTAACGAAAAAGAGGCAGATGACAATGACCATGAGCCCCAAATATCCCCCGGGGGCTTAGAGCCTCTCAGTGAAAAACATTTCCGTGAAACAGAAGTC', 'ATGCGCAAGTACTCCCCCTTCCGAAACGGATACATGGAACCCACCCTTGGGCAACACCTCCCAACCCTGTCTTTTCCAGACCCCGGCCTCCGGCCCCAAAACCTGTACACCCTCTGGGGAGACTCTGTTGTCTGCCTGTACCTCTACCAGCTCTCCCCCCCCATCACCTGGCCCCTCCCGCCCCATGTGATTTTTTGCCACCCCGGCCAGCTCGGGGCCTTCCTCACCAATGTTCCCTACAAGCGTATGGAAGAACTCCTCTATAAAATTTCCCTTACCACAGGGGCCCTAATAATTCTACCCGAGGACTGTTTACCAACCACCCTTTTCCAGCCTGCTAGGGCCCCCGTCACGTTGACCGCCTGGCAGAACGGCCTCCTTCCGTTCCACTCAACCCTCACCACTCCAGGCCTTATTTGGACATTTACCGATGGCACGCCTATGGTTTCCGGACCCTGCCCCAAAGATGGCCAGCCATCTTTAGTACTACAGTCCTCCTCATTTATATTTCACAAATTTCAAACCAAGGCCTACCACCCTTCATTTCTACTCTCACACGGCCTCATACAGTACTCCTCCTTTCACAATTTACATCTCCTTTTTGAAGAATACACCAACATCCCCGTTTCTCTACTTTTTAACGAAAAAGAGGCAAATGACACTGACCATGAGCCCCAAATATCCCCCGGGGGCTTAGAGCCTCCCGCTGAAAAACATTTCCGCGAAACAGAAGTC')\n\n    #\n    # ALIGN REF vs. QUERY seq, then TRIM GAPS:\n    #     Next we want to remove all characters (trim) in each of the sequences that is aligned to a gap position**** in the top alignment\n    #\n\n    #  Alignment:\n    #     ATGTGC----TAA  qry_seq\n    #     ATG--A--TTTGA  ref_seq\n    #        ^^ ^^^^     gap positions****\n    #  Trimming:\n    #     ATGCTAA        qry_seq (after trimming)\n    #     ATGATGA        ref_seq (after trimming)\n\n    # alignment scores are calculated from these two parameters, best scoring alignments have few gaps and gaps are small\n    aln_gap_open = -10\n    aln_gap_extend = -0.5 # @todo: make cmd args later?\n\n    qry_seq_aln, ref_seq_aln                          = align_then_trim.align_query_vs_reference(qry_seq_raw, ref_seq_raw, aln_gap_open, aln_gap_extend)\n    qry_seq_trimmed, ref_seq_trimmed, qry_seq_indices = align_then_trim.trim_gaps_from_aligned_seqs( qry_seq_aln, ref_seq_aln )\n\n    # @Note: benhamrking: it is qry_seq_trimmed and ref_seq_trimmed that should be used as input to MATLAB's dnds() function, for benchmarking\n\n    print(\"\\t\\tCOMPLETE!\")\n\n    #}} alternative 2\n\n    # ///\n\n    # alternative 1 {{\n\n    print(\"\\t===========================\")\n    print(\"\\tSliding window analysis....\")\n    print(\"\\t===========================\")\n\n    # # @NOTE:uncomment below to achieve dnds of 0.15.. or 0.164 if using exact method, interestingly\n    # dnds_whole, warning_count = dnds( qry_seq_trimmed, ref_seq_trimmed, potential_changes, observed_changes, msCorrect='approximate', sliding=False)\n    # print \"dN/dS: \"+str(dnds_whole)\n\n    # }} 1 alternative 2 {{\n\n    # @DONE: work with the sliding window version instead of dnds_whole\n    dnds_slide_dict, warning_count = dnds( qry_seq_trimmed, ref_seq_trimmed, potential_changes, observed_changes, msCorrect='approximate', sliding=True, windowLength=25, stepLength=1 )\n    #\n    # Plot the sliding window values\n    #\n    dnds_sliding_vec, dnds_sliding_mean = plot_dnds_sliding(dnds_slide_dict)\n\n    print(\"\\t\\tCOMPLETE!\")\n\n\n    #\n    # Summary statistics\n    #\n\n    print(\"\\t===============================================\")\n    print(\"\\tElapsed time: \"+str(time.time() - start_time))   # @time\n    print(\"\\tTotal warnings (missing values): \"+str(warning_count))\n    print \"\\tAvg. dN/dS over all windows: \"+str(dnds_sliding_mean)\n    print(\"\\t===============================================\")\n    # @todo: show the user also the whole dnds value somewhere in the webpage\n    print(\"\\t\\tdN/dS Sliding Analysis: All Jobs Complete!\")\n\n    return dnds_sliding_vec, qry_seq_indices\n\n\n\n########\n# MAIN # (still testing, cmd-args-mode not available yet)\n########\nif __name__ == \"__main__\":\n\n    #\n    # TRY CACHED DATA:\n    #   Open dictionaries that have cached computationally intensively\n    #   produced results\n    #\n    try:\n    #if (os.path.exists(\"./py/data/observed_changes_dict.p\") and os.path.exists(\"./py/data/potential_changes_dict.p\")):\n    # LOAD CACHED (fast)\n\n        #\n        # Unpickle codonPair-to-statistics dictionaries\n        #\n        f1 = open('observed_changes_dict.p','rb')\n        observed_changes  = pickle.load(f1)\n        f1.close()\n\n        f2 = open('potential_changes_dict.p','rb')\n        potential_changes = pickle.load(f2)\n        f2.close()\n        print \"LOADED!!\" # @todo:REMOVE\n\n    except IOError:\n    #else:\n    # CREATE NEW (slow)\n\n        #\n        # Create dictionary of codon (DNA-triplet, e.g. \"ATG\") -to- amino\n        #   acid residue (e.g. \"M\")\n        #\n        nt_to_aa_dict     = codon_pair_data.geneticCode(\"standard\")\n\n\n        # alternative 1 {{\n\n        # #@todo:Urgent:debug:2016-11-28: why does the following two lines (commented) lead to silent error? For some reason I HAVE to pickle the data to get it to work... when I just return the dicts directly I get the wrong dN/dS values. The following two lines illustrate this, when uncommented in place of the \"# @2:Create\" and \"# @2:Unpickle\" blocks of code...\n        # observed_changes  = codon_pair_data.potential_changes_dict(nt_to_aa_dict)\n        # potential_changes = codon_pair_data.observed_changes_dict(nt_to_aa_dict)\n\n        #}} 1 alternative 2 {{\n\n        #\n        # @2:Create the cached codonPair-to-statistics dictionaries, then pickle\n        #\n        codon_pair_data.potential_changes_dict(nt_to_aa_dict)\n        codon_pair_data.observed_changes_dict(nt_to_aa_dict)\n\n        #\n        # @2:Unpickle codonPair-to-statistics dictionaries\n        #\n        f1 = open('observed_changes_dict.p','rb') # @todo:coderedundancey = bad, wrap these lines into a function and call the function\n        observed_changes  = pickle.load(f1)\n        f1.close()\n\n        f2 = open('potential_changes_dict.p','rb')\n        potential_changes = pickle.load(f2)\n        f2.close()\n\n        # }} alternative 2\n\n        print \"CREATED!!\" # @todo:REMOVE\n\n    #\n    #  Calculate dN/dS\n    #\n\n    # @todo:\n    #   Q:These are either taken as cmd input args or from a tmp file?\n    #   A: No, we take them from the output of align.align_query_vs_reference() and align.trim_gaps_from_aligned_seqs() (align. imported as align_then_trim.)\n\n\n    # alternative 1 {{\n\n    # Aligned and Trimmed HTLV-1 vs. STLV-1 proteins (MATLAB example to benhmark dnds calculations)\n    # s1 = 'ATGCGCAAATACTCCCCCTTCCGAAATGGATACATGGAACCCACCCTTGGGCAGCACCTCCCAACCCTGTCTTTTCCAGACCCCGGACTCCGGCCCCAAAACCTGTACACCCTCTGGGGAGGCTCCGTTGTCTGCATGTACCTCTACCAGCTTTCCCCCCCCATCACCTGGCCCCTCCTGCCCCATGTGATTTTTTGCCACCCCGGCCAGCTCGGGGCCTTCCTCACCAATGTTCCCTACAAACGAATAGAAAAACTCCTCTATAAAATTTCCCTTACCACAGGGGCCCTAATAATTCTACCCGAGGACTGTTTGCCCACCACCCTTTTCCAGCCTGCTAGGGCACCCGTCACGCTGACAGCCTGGCAAAACGGCCTCCTTCCGTTCCACTCAACCCTCACCACTCCAGGCCTTATTTGGACATTTACCGATGGCACGCCTATGATTTCCGGGCCCTGCCCTAAAGATGGCCAGCCATCTTTAGTACTACAGTCCTCCTCCTTTATATTTCACAAATTTCAAACCAAGGCCTACCACCCCTCATTTCTACTCTCACACGGCCTCATACAGTACTCTTCCTTTCATAATTTGCATCTCCTATTTGAAGAATACACCAACATCCCCATTTCTCTACTTTTTAACGAAAAAGAGGCAGATGACAATGACCATGAGCCCCAAATATCCCCCGGGGGCTTAGAGCCTCTCAGTGAAAAACATTTCCGTGAAACAGAA'\n    # s2 = 'ATGCGCAAGTACTCCCCCTTCCGAAACGGATACATGGAACCCACCCTTGGGCAACACCTCCCAACCCTGTCTTTTCCAGACCCCGGCCTCCGGCCCCAAAACCTGTACACCCTCTGGGGAGACTCTGTTGTCTGCCTGTACCTCTACCAGCTCTCCCCCCCCATCACCTGGCCCCTCCCGCCCCATGTGATTTTTTGCCACCCCGGCCAGCTCGGGGCCTTCCTCACCAATGTTCCCTACAAGCGTATGGAAGAACTCCTCTATAAAATTTCCCTTACCACAGGGGCCCTAATAATTCTACCCGAGGACTGTTTACCAACCACCCTTTTCCAGCCTGCTAGGGCCCCCGTCACGTTGACCGCCTGGCAGAACGGCCTCCTTCCGTTCCACTCAACCCTCACCACTCCAGGCCTTATTTGGACATTTACCGATGGCACGCCTATGGTTTCCGGACCCTGCCCCAAAGATGGCCAGCCATCTTTAGTACTACAGTCCTCCTCATTTATATTTCACAAATTTCAAACCAAGGCCTACCACCCTTCATTTCTACTCTCACACGGCCTCATACAGTACTCCTCCTTTCACAATTTACATCTCCTTTTTGAAGAATACACCAACATCCCCGTTTCTCTACTTTTTAACGAAAAAGAGGCAAATGACACTGACCATGAGCCCCAAATATCCCCCGGGGGCTTAGAGCCTCCCGCTGAAAAACATTTCCGCGAAACAGAA'\n\n\n    # }} 1 alternative 2  {{  # @todo: debug:ever since the .p loading bug,\n    #                               which is still un-resolved (see: \"@todo:Urgent:debug:2016-11-28\")\n    #                               I think we should test a load( .p ) version just in case and check\n\n    #\n    # AGAP010815 (gambiae)\n    #     https://www.vectorbase.org/Anopheles_gambiae/Gene/Sequence?db=core;g=AGAP010815;r=3L:11202091-11206882;t=AGAP010815-RA\n    qry_seq_raw = sys.argv[1]\n    # OBP7 gambiae: v\n    #qry_seq_raw = \"ATGTGTGAATATTCGAATACGCGCAACAAGATGAGCAACCTGGTCGTCGTCCTCGTCCTGCTGACGATGTACATTGTGCTTTCGGCCCCATTCGAAATACCGGACCGGTACAAAAAGCCGGCTAAAATGTTGCACGAAATTTGTATCGCCGAGTCGGGCGCCTCGGAGGAGCAGCTGCGCACCTGTCTCGATGGAACCGTACCGACAGCTCCGGCCGCCAAGTGCTACATCCACTGCCTGTTCGACAAGATCGACGTGGTGGACGAGGCGACTGGGCGCATCCTGCTCGACCGACTGCTTTACATCATCCCGGACGACGTGAAGGCAGCGGTGGACCATTTAACGCGCGAATGTAGCCACATCGTAACGCCGGATAAGTGCGAAACCGCCTACGAGACGGTCAAATGTTATTTCAATGCGCACGACGAGGTGATCAAATTCTGCCACCTACTAGTGCTGGAGTGA\"\n    #s1_AGAP010815_RA = 'ATGTGGCAGTTCATAAGGTCACGAATATTAACGGTGATAATCTTCATAGGTGCTGCTCATGGGCTACTGGTTGTGGGTCCGAAATTTATACGGGCCAACCAGGAATACACTCTGGTGATCAGCAACTTTAACTCACAGCTAAGCAAAGTGGACCTGCTGTTAAAACTGGAAGGCGAAACTGATAATGGTTTAAGCGTTCTGAACGTTACCAAGATGGTTGACGTGCGACGTAATATGAACCGAATGATCAACTTCAATATGCCTGAGGATCTGACGGCTGGAAACTACAAAATAACTATCGATGGACAGCGTGGCTTCAGCTTTCACAAGGAGGCAGAGCTGGTGTATCTCAGCAAATCGATATCGGGGCTAATACAGGTCGATAAGCCCGTATTTAAACCTGGGGATACGGTGAACTTCCGTGTGATCGTGCTGGACACGGAGCTGAAACCGCCGGCGAGGGTCAAGTCGGTTTATGTAACTATACGAGATCCTCAGCGCAATGTGATTCGCAAATGGTCCACGGCAAAACTGTATGCCGGTGTGTTCGAGAGCGATCTACAGATAGCGCCTACTCCAATGCTCGGGGTCTGGAATATCTCGGTGGAGGTGGAAGGAGAAGAGCTTGTGTCAAAGACGTTTGAGGTGAAGGAGTACGTGTTGTCAACGTTCGACGTGCAGGTCATGCCATCGGTGATTCCACTGGAAGAGCATCAAGCTGTGAATCTTACAATCGAAGCGAACTATCACTTTGGTAAGCCAGTGCAAGGAGTGGCCAAGGTGGAGCTGTACCTAGACGACGATAAGCTAAAACTGAAAAAAGAGCTGACTGTGTACGGAAAGGGCCAGGTAGAGTTGCGCTTTGACAATTTTGCAATGGATGCGGATCAGCAGGATGTACCAGTGAAGGTGTCGTTCGTCGAGCAGTACACAAATCGTACGGTGGTCAAACAGTCACAAATCACGGTATATAGGTATGCGTACCGAGTAGAGTTGATAAAAGAGAGTCCACAGTTTCGTCCGGGACTCCCGTTCAAATGTGCGCTTCAGTTTACACACCATGATGGAACACCGGCTAAAGGCATTAGCGGTAAGGTAGAGGTATCCGATGTACGATTCGAAACGACAACAACGAGTGATAACGATGGATTGATTAAGCTCGAGCTGCAACCAAGTGAGGGTACTGAACAACTCAGTATTCACTTCAATGCTGTTGATGGATTCTTTTTTTATGAAGATGTGAATAAGGTAGAAACGGTTACGGATGCGTATATTAAACTGGAGCTGAAATCACCGCATCAAACGGAACAAATTGATGCGTTTCATGGTGACGTGCACGGAGCGCATGACATTCTTCGTGTACTATGTCATGTCAAAGGGCAATATCATCGATGCAGGATTCATGCGACCCAACAAGCAACCGAAGTACCTGTTGCAGCTGAACGCAACAGAAAAGATGATTCCGAGGGCGAAAATTCTCATCGCTACCGTAGCGGGCCGCACGGTGGTGTACGACTTCGCAGACCTCGATTTCCAAGAGCTTCGCAATAATTTTGATTTAAGCATTGACGAGCAAGAGATCAAGCCGGGACGACAAATCGAGCTGAGCATGTCTGGACGCCCAGGAGCGTACGTTGGGCTGGCCGCGTATGACAAAGCCTTGCTGCTTTTCAACAAGAACCACGACCTGTTCTGGGAGGACATTGGGCAGGTGTTTGATGGGTTCCATGCAATCAATGAGAACGAGTTTGACATATTCCACAGCTTGGGTCTGTTCGCCAGGACATTGGACGATATCTTGTTCGACAGTGCAAATGAAAAGACGGGGCGTAATGCACTGCAGTCAGGCAAGCCGATCGGCAAGCTGGTGTCGTATCGGACGAACTTCCAGGAATCGTGGTTGTGGAAAAATGTTTCCATCGGACGATCGGGAAGTCGCAAGTTGATCGAGGTAGTACCGGACACGACCACCTCCTGGTATCTGACGGGCTTCTCGATCGATCCCGTGTACGGGTTGGGTATCATCAAGAAGCCAATCCAGTTCACAACAGTCCAGCCGTTCTACATCGTAGAGAACTTACCATATTCAATCAAACGAGGCGAAGCGGTTGTGTTGCAGTTTACGCTGTTCAACAACCTTGGAGCGGAGTATATAGCCGATGTGACGCTGTACAATGTGGCCAACCAGACCGAGTTCGTCGGACGTCCAAATACGGATCTCAGCTACACCAAATCCGTGAGCGTTCCTCCAAAAGTTGGTGTGCCAATCTCGTTCCTCATCAAGGCCCGCAAGCTCGGCGAGATGGCGGTTCGTGTAAAGGCTTCGATAATGCTGGGACACGAAACGGACGCCCTGGAAAAGGTAATACGGGTGATGCCTGAAAGTTTGGTGCAGCCGAGAATGGATACACGCTTTTTCTGCTTCGACGATCACAAAAATCAAACGTTTCCGATCAACTTGGACATCAACAAGAAGGCCGACAGTGGATCGACAAAGATTGAGTTTCGACTAAATCCCAATTTGTTGACCACGGTCATCAAGAACCTGGACCATCTTCTCGGCGTTCCGACGGGATGTGGTGAGCAGAATATGGTCAAATTTGTTCCCAACATTTTGGTACTGGATTATTTGCATGCCATCGGGTCGAAAGAACAGCATCTAATCGACAAAGCTACGAATTTGTTGCGTCAAGGATATCAAAACCAGATGCGCTACCGTCAGACGGATGGTTCATTTGGTTTGTGGGAGACTACTAATGGTAGCGTGTTTCTCACCGCGTTCGTTGGCACATCGATGCAAACTGCAGTAAAATACATAAGCGATATTGATGCAGCAATGGTGGAGAAGGCATTGGATTGGTTAGCCTCGAAGCAGCATTTCTCGGGACGGTTTGACAAGGCCGGTGCAGAGTATCACAAAGAAATGCAAGGAGGGTTGCGCAATGGTGTGGCCCTCACATCATATGTGTTGATGGCATTGCTGGAGAATGACATTGCCAAAGCAAAGCACGCAGAGGTGATTCAAAAAGGAATGACCTATCTGAGCAATCAGTTTGGATCCATCAACAATGCATACGACCTATCGATAGCAACCTACGCGATGATGTTGAACGGACACACCATGAAGGAGGAGGCACTCAATAAGCTGATTGATATGTCTTTCATTGATGCTGATAAAAACGAACGGTTCTGGAACACAACGAATCCAATAGAAACCACCGCATATGCTCTGCTGTCGTTTGTGATGGCCGAGAAGTACACAGACGGTATACCGGTCATGAATTGGTTGGTGAATCAACGTTACGTTACCGGTAGCTTTCCGAGCACGCAAGACACGTTTGTGGGGCTGAAAGCGCTGACCAAAATGGCGGAAAAGATATCTCCGTCCCGAAACGACTACACCGTTCAACTGAAGTACAAGAAGAGTGCAAAATACTTCAAAATAAACTCGGAGCAAATTGATGTGGAAAACTTCGTGGATATACCGGAGGACACAAAAAAGCTCGAGATCAATGTGGGGGGCATTGGATTTGGGTTGTTAGAGGTGGTTTATCAATTTAATTTGAATCTCGTCAACTTTGAGAATAGATTCCAACTAGACCTGGAGAAACAGAACACAGGCTCTGACTACGAGCTGAGGCTGAAGGTCTGTGCCAGCTACATACCCCAGCTGACCGACAGACGATCGAACATGGCACTGATTGAGGTAACCTTACCGAGCGGTTACGTGGTTGATCGCAATCCGATCAGCGAGCAGACGAAGGTGAATCCGATTCAGAAAACTGAAATCCGTTACGGTGGCACTTCAGTCGTTTTATACTACGACAATATGGGCAGCGAGCGTAACTGTTTCACCCTGACCGCGTACAGACGCTTTAAGGTCGCATTGAAGCGTCCAGCGTATGTGGTTGTGTATGATTATTATAATACAAATCTGAACGCCATCAAAGTGTACGAAGTGGACAAGCAGAATTTGTGCGAAATCTGTGACGAAGAAGACTGTCCTGCAGAGTGCAAAAAATAG'\n    #qry_seq_raw = s1_AGAP010815_RA\n    #\n    # AAEL001802 (aegypti)\n    #     https://www.vectorbase.org/Aedes_aegypti/Gene/Sequence?db=core;g=AAEL001802;r=supercont1.43:685886-717122;t=AAEL001802-RA\n    ref_seq_raw = sys.argv[2]\n    # OBP7 aegypti: v\n    #ref_seq_raw = \"ATGATGGAACAGCTTATGCTGGCAGTTTTGCTGGCGGTTTTTCTCGGGCTCGTAGCAGATGTTACGATGGCCGCTCAAATCAAGGACAATTTGGAGCTACCCGAATATTACAAACGTCCGGCCAAAATTCTGCACAACATCTGTCTGGCAGAATCCGGTGCCATGGAGAGCAAACTAAAGCAGTGCATGGACGGAGTGCTTCATGACGACCGGGAAGTCAAGTGCTACATCCATTGTCTATTCGACAAGGTGGACGTAATCGACGAAGCAACCGGGCAGATCCTGTTGGACCGATTGGCACCACTGGCACCGGACAACGATGTGAAGGATGTGTTCAATCATTTGACCAAAGAGTGTGGTCATATCAAACTACAAGATTCCTGCGATACGGCGTACGAAGTGGCCAAATGTTACTTCGCGGCACACGATCAGGTCGTCAAATTCTGTCACCTGTTGATGGCTGATGTTACCAGCTAG\"\n    #s2_AAEL001802_RA = 'ATGTCGGTATTCATACAAACGGACAAACCGGTGTATACCCCGGGAGATCTGATACGTTTTCGGGTAATCGTGGTGGATGCTGACACTAGACCTGTGACTAGTATTAAAACGGTAAATATAGCGATCGACGATTCTGCAAAAAATTCCATTCGAAAGTGGCCTTATGCCAAGTTGTTAAACGGCATCTTTGAGTCACAAGTGCAATTAGCTTCTTCGCCTGTTCTTGGCACCTGGATTATCAACGTAACAGCTTCCGACGACATCATTGTCACCAAACAGATAGAAGTTAAGGAATATGTGTTGCCAAAATTTTTCGTGAAAGTTTACCCTTCGGAGGTTCTATTGGGGAAAAATAAGAAGGTTTCTCTTACCTTAGATGCCTATTACACGTTCAAAGAACCCGTCGACGGCAATTACAAAGTTGAGTTATTTTTGGACCATACCAAGAGAAAGCCTGACTTCATAAAAAGTGATCGAATCACCGGTAAAACATCACTTGAGTTTCAATTGAAAAATGAAGTAGACATTGATGGCGACGAGCAGTACACTGATGTCACGGTTGAAGTTGAAGTTGTCGAGGCATTTTCTAATCGCACAGTTAGTATAACTGAGAATATTCCGATTTATCGTCAGCCTTATACCGTGACCCTTCTTCCATCTGCACCATCATTTCGACCAGGAGTTCCATTCAATGTACAAATAGTTGTGAAAGATCAGCTTGGACACCCTCCTGCCGAAGAAAAAGCGGCATCAATTGACCTTACTGTAGAGTTCCATTTGCCCATTGACAGTGACACCAAATCTATCACTGTAGATCTGGACGAGAAAGGAACAGGTCAGCTCACATTAGAGCCCCGCCCAGACGCCCAAGAACTGAAAGTGAACGCTACATATGACTCTCAACAATACGATGTAATTCACGATCCGATACATGGTTTCAGTTCGCAAAGTAAGCAGTACATCACAGTAACTCTGAATCCAAAATACTATAACAACATTAAAGTCGATAAGGACATCGTACTGGACATCTCCTGCACTGAAACAATGACGCACTTCTCGTACATCGTTGTCACCAGAGGAAACATAGTGGAAGCATCGAACGTTCCTGTCAGGATAAAAAAGAAACATTCTCTGAGATTGAAAATGACTTCAAAAATGTCTCCGGAGTCGAGGCTTCTAGTGTACTATACAAACAGGGAGTATCTCATCTTTGATGATATTGAGCTGAAGTTCGATTCGTTCAACAACGACTTCAAATTCGATTTGAACGATGATGAGTATTTTCCAGGGCAATCAGTTTATATCGATGTATACGCTTCAAAGGATTCATACGTTGCGTTCAGTGGAATCGATGAAAGTGTACTCCTGGTAGGCAAAGAGCGCCATGACTTCAACAAAGGAGATGTGCTCAAGGAACTCGCTCTTTACGGAGCAACAAATGATGCCGAGTTTGACTTGTTCCACGTAAGTTTCATGTCAAATGGTTTGATTATTCCAGTTAATGTATCTGTAACTCGCTCACAGAATGCACGATTTGGTACTCTACTAGGAAGGACTAGGCAGCAAGCGATTGAAATTCGAACTCAATTCCTAGAATCCTGGTTATGGAAATCCTTTTCCATGGATGGTCGAAACAACTTCAAAGCAATAGAAGACTCGGTTCCGGATACTATTACAACGTATCACGTGTCAGGATTTGCTTTAAGTCCAACACTAGGTCTTGGAGTAATCCAACAACCAGTGAGTTTCACCGTTCGTAAAAAATTCTACTTGGTTGCAAATTTGCCTTACTCGATCAAACGGGGTGAAGTGGCGTTGATTCAGGTTACCGTCTTCAACTTCCTAGGAAGCAGCATAACAACCGATGTGACGCTGTTCAATAAACGCGATGAAATTGAGTTTGTCGAGAATGCATCCACTAATAATACACATCGAACAAAGGCGGTAATTGTCCCGAATAACAATGGAAAATCTGTATCATTTATGGTGAAAGCAAAGAAATTAGGACAGATTGCGATCAAATTCCAGGCGGTAAACCTGCTGGAAACGGATGCATTGGAGCACATGTTACGAGTAACCCCAGAGAGCCATCGCTATGAGAAAAATGTAGCTCGATTCGTTGAGCTACCAAAGTTTGAGACGCAAACTTTCGATGTGAAGCTGGACATTCCCAAAAATATCGACGAGGGTTCTGCTCAAATCAAATTCACGTTAGACCCGGACATTTTGGGAACAGCCATCAGCAACCTAGACGGGTTGATCCGGAAACCCTTTGGATGTGGCGAACAAAATATGCTCCATTTTGTGCCAAATATAGTCGTTTTGGATTATCTTAACGAAACCAACACAGCGGCAGAAGATGTGAGGACCAAAGCGATAAATTTTCTTAGCAGCGGATATCAAAACCAGCTACGCTACAAACGTTCGGATGGGGCCTTCAGTGTCTGGGGACAATCGTATGCTGGCAGTACATTTTTGACGGCCTTTGTGGCGAAATCATTCAAAATAGCAGCCAAATACATTCAGGTGGATAAGTCTATAGTAGACGCGGCATTCGACTGGTTAGTGAAACAACAACAATCAGATGGGCGGTTCCCAGAAGTGGGGCAAGTATTCCAAGCAGATATGCAGGGTGGGCTTCGTAATAACGGTTTTGCGCTTACCGCGTATGTTCTGATCGCTTTTGCTGAAAATAAGGAAGTATACAGAAAATACCAATCACAACTGAACAAAACTACTAACTTCATAGCAGATAGACTTGCTAATATGGAGAATCCATACGACCTCTCGCTGTCCACTTATGCGTTGATGCTAACAAATCATGGCAAGCGCACCGAGTTTCTTCACAAATTAGTCGAAAAGTCGATATTTGACCGCAATCAAACTGAGAGATATTGGGACAGCAAACCAGTTGATATTGAAGTTGCTGGATATGCTCTATTGTCATACGTAGCTGCCGGTAAATTATTGGATGCAACGCCTATCATGCGGTGGCTCAACAAGCAGCGTTATGGTCTCGGAGGCTATCCTGGAACTCAGGAAACATTCGTTGGATTGAAAGCATTGGCAACGTTCGCTGCAAATGTAACTAGTAGGAGAAACGAATATACTGTAAGGATATTCTACGAACCAAATGGTCGACGAACATTCGACGTACACATGCACAATTCGTTTAATATTCAAGAGCTTGACATTCCTAATAACATCAGAAAAATGAAGGTGGAAGTTGAAGGCATCGGCAGAGGCTTCTTCCAAGTGGCATATCAGTACTATCAAAATATGCAGGTGGCTAAGCCCAGTTTCAGCATTACAATTAATCAGCTTAACACCACGACGGAACACATGCAGCAATTGGACGTGTGTGTGAAATACATACCAAAAGAGGCTTATCAAAAATCGAATATGGCTTTGGTGGAAATATTCTTGCCTAGTGGGCTTGTAGCAGACTCAGATGCCATTACGGACAAGACTGGAGGAATTCGAAGAATTGAAAGACGTTTTTCGGACACCTCAGTAGTTATATATTATGATAATTTGGACCCCGAAGACAAGTGCTTCCGAGTGACTGCTTATCGTCGGTATAAAATTGCATTGCATTTGCCATCATATATTATAGTTTATGATTATTATAATTTTGAGCGCTTTGCCATTCAAAAGTACGAAGGAAAGGTGCTGCAGCTCTGCGATATTTGTGAAGACGAGGACTGCGAAACTTTATCATGTCAAAATAGCTCGAAATTGGCAATAATGTAA'\n    #ref_seq_raw = s2_AAEL001802_RA\n\n    ###########################\n    # Benchmarking vs. MATLAB #\n    ###########################\n\n    # @done:@testing:benchmark vs. matlab: @todo: place in README these details\n    #   using s1_AGAP010815_RA and s2_AAEL001802_RA (after aligning/trimming)\n    # MATLAB whole dnds vs. andy-wenping whole dnds (msCorrect='approximate'): dN/dS:\n    #   1.0958 vs. 1.04939841193 (Elapsed time: 1.952491045, Total warnings: 0), respectively\n    # MATLAB mean(sliding dnds) vs. andy-wenping mean(sliding dnds): Mean dN/dS over all 50-codon long windows:\n    #   1.7254581782566112 (smoothing?) vs. 1.49715496621 (incl. smoothing, stepLength=1) (Elapsed time: 2.29854488373, Total warnings: 173) (when taking the mean of all 50 window intervals in MATLAB's sliding dnds()\n    # MATLAB sliding dnds plot vs. andy-wenping sliding dnds plot: similar sliding dnds plots:\n    #   see:  D:\\Dropbox\\00_HPC-LEAP\\WP5 Thematic Cyprus Computational Biology\\giannis_database\n\n    # @benchmark:matlab's dnds()\n    # dN/dS=0.15270463083614955 with msCorrect='approximate', dN/dS=0.16529268957638238 with\n    # msCorrect='exact', MATLAB gives: dN/dS=0.0221=dnds(seq1,seq2, 'geneticCode', 1, 'Method', 'NG'). This is a huge error, an order of magnitude off.\n    # seq1 = 'ATGCGCAAATACTCCCCCTTCCGAAATGGATACATGGAACCCACCCTTGGGCAGCACCTCCCAACCCTGTCTTTTCCAGACCCCGGACTCCGGCCCCAAAACCTGTACACCCTCTGGGGAGGCTCCGTTGTCTGCATGTACCTCTACCAGCTTTCCCCCCCCATCACCTGGCCCCTCCTGCCCCATGTGATTTTTTGCCACCCCGGCCAGCTCGGGGCCTTCCTCACCAATGTTCCCTACAAACGAATAGAAAAACTCCTCTATAAAATTTCCCTTACCACAGGGGCCCTAATAATTCTACCCGAGGACTGTTTGCCCACCACCCTTTTCCAGCCTGCTAGGGCACCCGTCACGCTGACAGCCTGGCAAAACGGCCTCCTTCCGTTCCACTCAACCCTCACCACTCCAGGCCTTATTTGGACATTTACCGATGGCACGCCTATGATTTCCGGGCCCTGCCCTAAAGATGGCCAGCCATCTTTAGTACTACAGTCCTCCTCCTTTATATTTCACAAATTTCAAACCAAGGCCTACCACCCCTCATTTCTACTCTCACACGGCCTCATACAGTACTCTTCCTTTCATAATTTGCATCTCCTATTTGAAGAATACACCAACATCCCCATTTCTCTACTTTTTAACGAAAAAGAGGCAGATGACAATGACCATGAGCCCCAAATATCCCCCGGGGGCTTAGAGCCTCTCAGTGAAAAACATTTCCGTGAAACAGAAGTC'\n    # seq2 = 'ATGCGCAAGTACTCCCCCTTCCGAAACGGATACATGGAACCCACCCTTGGGCAACACCTCCCAACCCTGTCTTTTCCAGACCCCGGCCTCCGGCCCCAAAACCTGTACACCCTCTGGGGAGACTCTGTTGTCTGCCTGTACCTCTACCAGCTCTCCCCCCCCATCACCTGGCCCCTCCCGCCCCATGTGATTTTTTGCCACCCCGGCCAGCTCGGGGCCTTCCTCACCAATGTTCCCTACAAGCGTATGGAAGAACTCCTCTATAAAATTTCCCTTACCACAGGGGCCCTAATAATTCTACCCGAGGACTGTTTACCAACCACCCTTTTCCAGCCTGCTAGGGCCCCCGTCACGTTGACCGCCTGGCAGAACGGCCTCCTTCCGTTCCACTCAACCCTCACCACTCCAGGCCTTATTTGGACATTTACCGATGGCACGCCTATGGTTTCCGGACCCTGCCCCAAAGATGGCCAGCCATCTTTAGTACTACAGTCCTCCTCATTTATATTTCACAAATTTCAAACCAAGGCCTACCACCCTTCATTTCTACTCTCACACGGCCTCATACAGTACTCCTCCTTTCACAATTTACATCTCCTTTTTGAAGAATACACCAACATCCCCGTTTCTCTACTTTTTAACGAAAAAGAGGCAAATGACACTGACCATGAGCCCCAAATATCCCCCGGGGGCTTAGAGCCTCCCGCTGAAAAACATTTCCGCGAAACAGAAGTC'\n    # dnds('ATGCGCAAATACTCCCCCTTCCGAAATGGATACATGGAACCCACCCTTGGGCAGCACCTCCCAACCCTGTCTTTTCCAGACCCCGGACTCCGGCCCCAAAACCTGTACACCCTCTGGGGAGGCTCCGTTGTCTGCATGTACCTCTACCAGCTTTCCCCCCCCATCACCTGGCCCCTCCTGCCCCATGTGATTTTTTGCCACCCCGGCCAGCTCGGGGCCTTCCTCACCAATGTTCCCTACAAACGAATAGAAAAACTCCTCTATAAAATTTCCCTTACCACAGGGGCCCTAATAATTCTACCCGAGGACTGTTTGCCCACCACCCTTTTCCAGCCTGCTAGGGCACCCGTCACGCTGACAGCCTGGCAAAACGGCCTCCTTCCGTTCCACTCAACCCTCACCACTCCAGGCCTTATTTGGACATTTACCGATGGCACGCCTATGATTTCCGGGCCCTGCCCTAAAGATGGCCAGCCATCTTTAGTACTACAGTCCTCCTCCTTTATATTTCACAAATTTCAAACCAAGGCCTACCACCCCTCATTTCTACTCTCACACGGCCTCATACAGTACTCTTCCTTTCATAATTTGCATCTCCTATTTGAAGAATACACCAACATCCCCATTTCTCTACTTTTTAACGAAAAAGAGGCAGATGACAATGACCATGAGCCCCAAATATCCCCCGGGGGCTTAGAGCCTCTCAGTGAAAAACATTTCCGTGAAACAGAAGTC', 'ATGCGCAAGTACTCCCCCTTCCGAAACGGATACATGGAACCCACCCTTGGGCAACACCTCCCAACCCTGTCTTTTCCAGACCCCGGCCTCCGGCCCCAAAACCTGTACACCCTCTGGGGAGACTCTGTTGTCTGCCTGTACCTCTACCAGCTCTCCCCCCCCATCACCTGGCCCCTCCCGCCCCATGTGATTTTTTGCCACCCCGGCCAGCTCGGGGCCTTCCTCACCAATGTTCCCTACAAGCGTATGGAAGAACTCCTCTATAAAATTTCCCTTACCACAGGGGCCCTAATAATTCTACCCGAGGACTGTTTACCAACCACCCTTTTCCAGCCTGCTAGGGCCCCCGTCACGTTGACCGCCTGGCAGAACGGCCTCCTTCCGTTCCACTCAACCCTCACCACTCCAGGCCTTATTTGGACATTTACCGATGGCACGCCTATGGTTTCCGGACCCTGCCCCAAAGATGGCCAGCCATCTTTAGTACTACAGTCCTCCTCATTTATATTTCACAAATTTCAAACCAAGGCCTACCACCCTTCATTTCTACTCTCACACGGCCTCATACAGTACTCCTCCTTTCACAATTTACATCTCCTTTTTGAAGAATACACCAACATCCCCGTTTCTCTACTTTTTAACGAAAAAGAGGCAAATGACACTGACCATGAGCCCCAAATATCCCCCGGGGGCTTAGAGCCTCCCGCTGAAAAACATTTCCGCGAAACAGAAGTC')\n\n    #\n    # ALIGN REF vs. QUERY seq, then TRIM GAPS:\n    #     Next we want to remove all characters (trim) in each of the sequences that is aligned to a gap position**** in the top alignment\n    #\n\n    #  Raw input:\n    #     ATGTGCTAA      qry\n    #     ATGATTTGA      ref\n    #\n    # Alignment:\n    #     ATGTGC----TAA  qry_seq\n    #     ATG--A--TTTGA  ref_seq\n    #        ^^ ^^^^     gap positions****\n    #  Trimming:\n    #     ATGCTAA        qry_seq (after trimming)\n    #     ATGATGA        ref_seq (after trimming)\n\n    # alignment scores are calculated from these two parameters, best scoring alignments have few gaps and gaps are small\n    aln_gap_open = -10\n    aln_gap_extend = -0.5 # @todo: make cmd args later?\n\n    qry_seq_aln, ref_seq_aln         = align_then_trim.align_query_vs_reference(qry_seq_raw, ref_seq_raw, aln_gap_open, aln_gap_extend)\n    qry_seq_trimmed, ref_seq_trimmed = align_then_trim.trim_gaps_from_aligned_seqs( qry_seq_aln, ref_seq_aln )\n\n    # @Note: benhamrking: it is qry_seq_trimmed and ref_seq_trimmed that should be used as input to MATLAB's dnds() function, for benchmarking\n\n    #}} alternative 2\n\n    # ///\n\n    # alternative 1 {{\n\n    # # @NOTE:uncomment below to achieve dnds of 0.15.. or 0.164 if using exact method, interestingly\n    # dnds_whole, warning_count = dnds( qry_seq_trimmed, ref_seq_trimmed, potential_changes, observed_changes, msCorrect='approximate', sliding=False)\n    # print \"dN/dS: \"+str(dnds_whole)\n\n    # }} 1 alternative 2 {{\n\n    # @DONE: work with the sliding window version instead of dnds_whole\n    dnds_slide_dict, warning_count = dnds( qry_seq_trimmed, ref_seq_trimmed, potential_changes, observed_changes, msCorrect='approximate', sliding=True, windowLength=50, stepLength=1 )\n    #\n    # Plot the sliding window values\n    #\n    dnds_sliding_vec, dnds_sliding_mean = plot_dnds_sliding(dnds_slide_dict)\n\n    print \"Mean dN/dS over all windows: \"+str(dnds_sliding_mean)\n    print \"dN/dS over sliding windows: \"+str(dnds_sliding_vec)\n    # @todo: show the user also the whole dnds value somewhere in the webpage\n\n    # }} alternative 2\n", "meta": {"hexsha": "4d6061e22dc7bb7fab80657bc8202e24b3274e4a", "size": 58632, "ext": "py", "lang": "Python", "max_stars_repo_path": "bin/dnds.py", "max_stars_repo_name": "yasinkaymaz/ViralGenomeAssembly", "max_stars_repo_head_hexsha": "03e75ee7358946823660a299e0718213dbbd161c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bin/dnds.py", "max_issues_repo_name": "yasinkaymaz/ViralGenomeAssembly", "max_issues_repo_head_hexsha": "03e75ee7358946823660a299e0718213dbbd161c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bin/dnds.py", "max_forks_repo_name": "yasinkaymaz/ViralGenomeAssembly", "max_forks_repo_head_hexsha": "03e75ee7358946823660a299e0718213dbbd161c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 85.5941605839, "max_line_length": 4051, "alphanum_fraction": 0.8102571974, "include": true, "reason": "import numpy", "num_tokens": 22048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.29746994883293104, "lm_q1q2_score": 0.1568608148090617}}
{"text": "\"\"\"\nModule with functionality to compute anomaly scores based on reconstructions\n\"\"\"\nimport numpy as np\nimport scipy.constants as cst\nfrom skimage.color import gray2rgb  # convert spectra to 3 channels\n\nfrom .metrics import ReconstructionMetrics\n\n###############################################################################\nGALAXY_LINES = {\n    # EMISSION\n    \"OII_3727\": 3727.0,\n    \"H_delta_4102\": 4102.0,\n    \"H_gamma_4340\": 4340.0,\n    \"H_beta_4861\": 4861.0,\n    \"OIII_4959\": 4959.0,\n    \"OIII_5007\": 5007.0,\n    \"NII_6548\": 6548.0,\n    \"H_alpha_6563\": 6563.0,\n    \"NII_6584\": 6584.0,\n    \"SII_6716\": 6716.0,\n    \"SII_6720\": 6720.0,\n    \"SII_6731\": 6731.0,\n    # ABSORPTION\n}\n##############################################################################\nclass ReconstructionAnomalyScore(ReconstructionMetrics):\n    \"\"\"\n    Class to deal with the outliers based on a generative model trained with\n    tensorflow.keras\n    \"\"\"\n\n    ###########################################################################\n    def __init__(\n        self,\n        reconstruct_fucntion,\n        wave: np.array,\n        lines: list = None,\n        velocity_filter: float = 50,\n        percentage: int = 100,\n        relative: bool = False,\n        epsilon: float = 1e-3,\n    ):\n        \"\"\"\n        INPUTS\n            reconstruct_fucntion: reconstruct method of trained\n                generative model\n\n            lines: list with lines to discard to compute anomaly_score\n            velocity_filter: Doppler velocity to consider at the moment of\n                line filtering. It is in units of Km/s.\n                DeltaWave = (v/c) * wave\n            wave: common grid to spectra\n\n            percentage: percentage of fluxes with the highest\n                reconstruction error to consider to compute\n                the anomaly score\n            relative: whether or not the score is weigthed by the input\n            epsilon: float value to avoid division by zero\n        \"\"\"\n\n        self.reconstruct = reconstruct_fucntion\n        self.wave = wave\n\n        self.lines = lines\n        filter_lines = velocity_filter == 0\n        self.filter_lines = filter_lines\n        self.velocity_filter = velocity_filter\n\n        super().__init__(percentage, relative, epsilon)\n\n    ###########################################################################\n    def score(\n        self, observation: np.array, metric: str, p: float = 0.33\n    ) -> np.array:\n\n        # in case I pass a spectra with one dimension\n        # this line converts 1D array to (1, n_wave, 3)\n        # an image where each channel has the spectrun\n        observation = self.spectra_to_batch_image(observation)\n\n        assert observation.ndim == 4\n\n        observation, reconstruction = self.reconstruct_and_filter(\n            observation, self.lines, self.velocity_filter\n        )\n\n        # make compatible batch of spectra's images with metrics\n        observation = observation[:, 0, :, 0]\n        reconstruction = reconstruction[:, 0, :, 0]\n        if metric == \"lp\":\n\n            assert np.isscalar(p)\n\n            anomaly_score = super().lp(observation, reconstruction, p)\n            return anomaly_score.reshape((-1, 1))\n\n        if metric == \"mse\":\n\n            anomaly_score = super().mse(observation, reconstruction)\n            return anomaly_score.reshape((-1, 1))\n\n        if metric == \"mad\":\n\n            anomaly_score = super().mad(observation, reconstruction)\n            return anomaly_score.reshape((-1, 1))\n\n        print(f\"{metric} not implemented\")\n\n    ###########################################################################\n    def reconstruct_and_filter(\n        self, observation: np.array, lines: list, velocity_filter: float\n    ) -> tuple:\n\n        \"\"\"\n        PARAMETERS\n            observation: array with the origin of fluxes\n            lines: list with lines to discard to compute anomaly_score\n            velocity_filter: Doppler velocity to consider at the moment of\n                line filtering. It is in units of Km/s.\n                DeltaWave = (v/c) * wave\n\n        OUTPUTS\n            observation, reconstruction:\n                np.arrays with the filter if it applies\n        \"\"\"\n\n        # get (n_batch, flux). This is what is compatible with\n        # reconstruction method\n        reconstruction = self.reconstruct(observation[:, 0, :, 0])\n\n        if self.filter_lines is True:\n\n            velocity_mask = self.get_velocity_filter_mask(\n                lines, velocity_filter\n            )\n\n            observation = observation[:, 0, velocity_mask, 0]\n            reconstruction = reconstruction[:, velocity_mask]\n\n        observation = self.spectra_to_batch_image(observation)\n        reconstruction = self.spectra_to_batch_image(reconstruction)\n\n        assert observation.ndim == 4\n        assert reconstruction.ndim == 4\n\n        return observation, reconstruction\n\n    ###########################################################################\n    def get_velocity_filter_mask(\n        self, lines: list, velocity_filter: float\n    ) -> np.array:\n\n        \"\"\"\n        Compute array with filters for narrow emission lines\n        PARAMETERS\n\n            lines: list with lines to discard to compute anomaly_score.\n                Check VELOCITY_LINES dictionary at the begin in the document.\n            velocity_filter: Doppler velocity to consider at the moment of\n                line filtering. It is in units of Km/s.\n                DeltaWave = (v/c) * wave\n\n        OUTPUT\n\n            velocity_mask: array of bools with the regions to discard\n        \"\"\"\n\n        c = cst.c * 1e-3  # [km/s]\n        alpha = velocity_filter / c  # filter width\n\n        velocity_mask = self.wave.astype(bool)\n\n        for line in lines:\n\n            delta_wave = GALAXY_LINES[line] * alpha\n            # move line to origin\n            wave = self.wave - GALAXY_LINES[line]\n            line_mask = (wave < -delta_wave) | (delta_wave < wave)\n            # update velocity mask\n            velocity_mask *= line_mask\n\n        return velocity_mask\n\n    ###########################################################################\n    def spectra_to_batch_image(self, spectra):\n\n        # If a 1D spec is passed\n        if spectra.ndim == 1:\n            # get (1, flux)\n            gray_spectra = spectra[np.newaxis, ...]\n            # get (1, flux, 3)\n            spectra_image = gray2rgb(gray_spectra)\n            # get (n_batch, 1, flux, 3)\n            return spectra_image[np.newaxis]\n        # array of spectra: (n_batch, flux)\n        if spectra.ndim == 2:\n            # get (n_bacth, flux, 3)\n            gray_spectra = gray2rgb(spectra)\n            # get (n_bacth, 1, flux, 3)\n            return gray_spectra[:, np.newaxis, ...]\n        # if already image pass to (n_batch, 1, flux, 3)\n        if spectra.ndim == 3:\n            return spectra[np.newaxis, ...]\n\n        return spectra\n", "meta": {"hexsha": "cf5d1701ea1717d2f3b3289f343143c6d6008aa6", "size": 6908, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/anomaly/reconstruction.py", "max_stars_repo_name": "ed-ortizm/anomaly", "max_stars_repo_head_hexsha": "87d0668133f0536532b9cd61c2a90fa998ec1ad3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/anomaly/reconstruction.py", "max_issues_repo_name": "ed-ortizm/anomaly", "max_issues_repo_head_hexsha": "87d0668133f0536532b9cd61c2a90fa998ec1ad3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-10-01T22:12:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-04T19:41:47.000Z", "max_forks_repo_path": "src/anomaly/reconstruction.py", "max_forks_repo_name": "ed-ortizm/anomaly", "max_forks_repo_head_hexsha": "87d0668133f0536532b9cd61c2a90fa998ec1ad3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2115384615, "max_line_length": 79, "alphanum_fraction": 0.5490735379, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.29098087236345377, "lm_q1q2_score": 0.15683380774496625}}
{"text": "#-*- coding:utf-8 -*-\n#\n# Original code is here: https://github.com/openai/guided-diffusion\n#\n\nimport numpy as np\nimport torch as th\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom .fp16_util import convert_module_to_f16, convert_module_to_f32\nfrom .modules import *\n\nNUM_CLASSES = 1\n\nclass UNetModel(nn.Module):\n    \"\"\"\n    The full UNet model with attention and timestep embedding.\n    :param in_channels: channels in the input Tensor.\n    :param model_channels: base channel count for the model.\n    :param out_channels: channels in the output Tensor.\n    :param num_res_blocks: number of residual blocks per downsample.\n    :param attention_resolutions: a collection of downsample rates at which\n        attention will take place. May be a set, list, or tuple.\n        For example, if this contains 4, then at 4x downsampling, attention\n        will be used.\n    :param dropout: the dropout probability.\n    :param channel_mult: channel multiplier for each level of the UNet.\n    :param conv_resample: if True, use learned convolutions for upsampling and\n        downsampling.\n    :param dims: determines if the signal is 1D, 2D, or 3D.\n    :param num_classes: if specified (as an int), then this model will be\n        class-conditional with `num_classes` classes.\n    :param use_checkpoint: use gradient checkpointing to reduce memory usage.\n    :param num_heads: the number of attention heads in each attention layer.\n    :param num_heads_channels: if specified, ignore num_heads and instead use\n                               a fixed channel width per attention head.\n    :param num_heads_upsample: works with num_heads to set a different number\n                               of heads for upsampling. Deprecated.\n    :param use_scale_shift_norm: use a FiLM-like conditioning mechanism.\n    :param resblock_updown: use residual blocks for up/downsampling.\n    :param use_new_attention_order: use a different attention pattern for potentially\n                                    increased efficiency.\n    \"\"\"\n\n    def __init__(\n        self,\n        image_size,\n        in_channels,\n        model_channels,\n        out_channels,\n        num_res_blocks,\n        attention_resolutions,\n        dropout=0,\n        channel_mult=(1, 2, 4, 8),\n        conv_resample=True,\n        dims=2,\n        num_classes=None,\n        use_checkpoint=False,\n        use_fp16=False,\n        num_heads=1,\n        num_head_channels=-1,\n        num_heads_upsample=-1,\n        use_scale_shift_norm=False,\n        resblock_updown=False,\n        use_new_attention_order=False,\n    ):\n        super().__init__()\n\n        if num_heads_upsample == -1:\n            num_heads_upsample = num_heads\n\n        self.image_size = image_size\n        self.in_channels = in_channels\n        self.model_channels = model_channels\n        self.out_channels = out_channels\n        self.num_res_blocks = num_res_blocks\n        self.attention_resolutions = attention_resolutions\n        self.dropout = dropout\n        self.channel_mult = channel_mult\n        self.conv_resample = conv_resample\n        self.num_classes = num_classes\n        self.use_checkpoint = use_checkpoint\n        self.dtype = th.float16 if use_fp16 else th.float32\n        self.num_heads = num_heads\n        self.num_head_channels = num_head_channels\n        self.num_heads_upsample = num_heads_upsample\n\n        time_embed_dim = model_channels * 4\n        self.time_embed = nn.Sequential(\n            linear(model_channels, time_embed_dim),\n            nn.SiLU(),\n            linear(time_embed_dim, time_embed_dim),\n        )\n\n        if self.num_classes is not None:\n            self.label_emb = nn.Embedding(num_classes, time_embed_dim)\n\n        ch = input_ch = int(channel_mult[0] * model_channels)\n        self.input_blocks = nn.ModuleList(\n            [TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))]\n        )\n        self._feature_size = ch\n        input_block_chans = [ch]\n        ds = 1\n        for level, mult in enumerate(channel_mult):\n            for _ in range(num_res_blocks):\n                layers = [\n                    ResBlock(\n                        ch,\n                        time_embed_dim,\n                        dropout,\n                        out_channels=int(mult * model_channels),\n                        dims=dims,\n                        use_checkpoint=use_checkpoint,\n                        use_scale_shift_norm=use_scale_shift_norm,\n                    )\n                ]\n                ch = int(mult * model_channels)\n                if ds in attention_resolutions:\n                    layers.append(\n                        AttentionBlock(\n                            ch,\n                            use_checkpoint=use_checkpoint,\n                            num_heads=num_heads,\n                            num_head_channels=num_head_channels,\n                            use_new_attention_order=use_new_attention_order,\n                        )\n                    )\n                self.input_blocks.append(TimestepEmbedSequential(*layers))\n                self._feature_size += ch\n                input_block_chans.append(ch)\n            if level != len(channel_mult) - 1:\n                out_ch = ch\n                self.input_blocks.append(\n                    TimestepEmbedSequential(\n                        ResBlock(\n                            ch,\n                            time_embed_dim,\n                            dropout,\n                            out_channels=out_ch,\n                            dims=dims,\n                            use_checkpoint=use_checkpoint,\n                            use_scale_shift_norm=use_scale_shift_norm,\n                            down=True,\n                        )\n                        if resblock_updown\n                        else Downsample(\n                            ch, conv_resample, dims=dims, out_channels=out_ch\n                        )\n                    )\n                )\n                ch = out_ch\n                input_block_chans.append(ch)\n                ds *= 2\n                self._feature_size += ch\n\n        self.middle_block = TimestepEmbedSequential(\n            ResBlock(\n                ch,\n                time_embed_dim,\n                dropout,\n                dims=dims,\n                use_checkpoint=use_checkpoint,\n                use_scale_shift_norm=use_scale_shift_norm,\n            ),\n            AttentionBlock(\n                ch,\n                use_checkpoint=use_checkpoint,\n                num_heads=num_heads,\n                num_head_channels=num_head_channels,\n                use_new_attention_order=use_new_attention_order,\n            ),\n            ResBlock(\n                ch,\n                time_embed_dim,\n                dropout,\n                dims=dims,\n                use_checkpoint=use_checkpoint,\n                use_scale_shift_norm=use_scale_shift_norm,\n            ),\n        )\n        self._feature_size += ch\n\n        self.output_blocks = nn.ModuleList([])\n        for level, mult in list(enumerate(channel_mult))[::-1]:\n            for i in range(num_res_blocks + 1):\n                ich = input_block_chans.pop()\n                layers = [\n                    ResBlock(\n                        ch + ich,\n                        time_embed_dim,\n                        dropout,\n                        out_channels=int(model_channels * mult),\n                        dims=dims,\n                        use_checkpoint=use_checkpoint,\n                        use_scale_shift_norm=use_scale_shift_norm,\n                    )\n                ]\n                ch = int(model_channels * mult)\n                if ds in attention_resolutions:\n                    layers.append(\n                        AttentionBlock(\n                            ch,\n                            use_checkpoint=use_checkpoint,\n                            num_heads=num_heads_upsample,\n                            num_head_channels=num_head_channels,\n                            use_new_attention_order=use_new_attention_order,\n                        )\n                    )\n                if level and i == num_res_blocks:\n                    out_ch = ch\n                    layers.append(\n                        ResBlock(\n                            ch,\n                            time_embed_dim,\n                            dropout,\n                            out_channels=out_ch,\n                            dims=dims,\n                            use_checkpoint=use_checkpoint,\n                            use_scale_shift_norm=use_scale_shift_norm,\n                            up=True,\n                        )\n                        if resblock_updown\n                        else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)\n                    )\n                    ds //= 2\n                self.output_blocks.append(TimestepEmbedSequential(*layers))\n                self._feature_size += ch\n\n        self.out = nn.Sequential(\n            normalization(ch),\n            nn.SiLU(),\n            zero_module(conv_nd(dims, input_ch, out_channels, 3, padding=1)),\n        )\n\n    def convert_to_fp16(self):\n        \"\"\"\n        Convert the torso of the model to float16.\n        \"\"\"\n        self.input_blocks.apply(convert_module_to_f16)\n        self.middle_block.apply(convert_module_to_f16)\n        self.output_blocks.apply(convert_module_to_f16)\n\n    def convert_to_fp32(self):\n        \"\"\"\n        Convert the torso of the model to float32.\n        \"\"\"\n        self.input_blocks.apply(convert_module_to_f32)\n        self.middle_block.apply(convert_module_to_f32)\n        self.output_blocks.apply(convert_module_to_f32)\n\n    def forward(self, x, timesteps, y=None):\n        \"\"\"\n        Apply the model to an input batch.\n        :param x: an [N x C x ...] Tensor of inputs.\n        :param timesteps: a 1-D batch of timesteps.\n        :param y: an [N] Tensor of labels, if class-conditional.\n        :return: an [N x C x ...] Tensor of outputs.\n        \"\"\"\n        assert (y is not None) == (\n            self.num_classes is not None\n        ), \"must specify y if and only if the model is class-conditional\"\n\n        hs = []\n        emb = self.time_embed(timestep_embedding(timesteps, self.model_channels))\n\n        if self.num_classes is not None:\n            assert y.shape == (x.shape[0],)\n            emb = emb + self.label_emb(y)\n\n        h = x.type(self.dtype)\n        for module in self.input_blocks:\n            h = module(h, emb)\n            hs.append(h)\n        h = self.middle_block(h, emb)\n        for module in self.output_blocks:\n            h = th.cat([h, hs.pop()], dim=1)\n            h = module(h, emb)\n        h = h.type(x.dtype)\n        return self.out(h)\n\n\ndef create_model(\n    image_size,\n    num_channels,\n    num_res_blocks,\n    channel_mult=\"\",\n    learn_sigma=False,\n    class_cond=False,\n    use_checkpoint=False,\n    attention_resolutions=\"16\",\n    num_heads=1,\n    num_head_channels=-1,\n    num_heads_upsample=-1,\n    use_scale_shift_norm=False,\n    dropout=0,\n    resblock_updown=False,\n    use_fp16=False,\n    use_new_attention_order=False,\n):\n    if channel_mult == \"\":\n        if image_size == 512:\n            channel_mult = (0.5, 1, 1, 2, 2, 4, 4)\n        elif image_size == 256:\n            channel_mult = (1, 1, 2, 2, 4, 4)\n        elif image_size == 128:\n            channel_mult = (1, 1, 2, 3, 4)\n        elif image_size == 64:\n            channel_mult = (1, 2, 3, 4)\n        else:\n            raise ValueError(f\"unsupported image size: {image_size}\")\n    else:\n        channel_mult = tuple(int(ch_mult) for ch_mult in channel_mult.split(\",\"))\n\n    attention_ds = []\n    for res in attention_resolutions.split(\",\"):\n        attention_ds.append(image_size // int(res))\n\n    return UNetModel(\n        image_size=image_size,\n        in_channels=3,\n        model_channels=num_channels,\n        out_channels=(3 if not learn_sigma else 6),\n        num_res_blocks=num_res_blocks,\n        attention_resolutions=tuple(attention_ds),\n        dropout=dropout,\n        channel_mult=channel_mult,\n        num_classes=(NUM_CLASSES if class_cond else None),\n        use_checkpoint=use_checkpoint,\n        use_fp16=use_fp16,\n        num_heads=num_heads,\n        num_head_channels=num_head_channels,\n        num_heads_upsample=num_heads_upsample,\n        use_scale_shift_norm=use_scale_shift_norm,\n        resblock_updown=resblock_updown,\n        use_new_attention_order=use_new_attention_order,\n    )\n", "meta": {"hexsha": "219bc570fd3d6b05f0f0d16f8ff91e4d01fd00f5", "size": 12469, "ext": "py", "lang": "Python", "max_stars_repo_path": "diffusion_model/unet.py", "max_stars_repo_name": "DL-Circle/Mongolian-Script-Generator", "max_stars_repo_head_hexsha": "ddc3eecae02b67612e615536d8fc2dd6829416ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-27T02:54:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T08:05:29.000Z", "max_issues_repo_path": "diffusion_model/unet.py", "max_issues_repo_name": "DL-Circle/Mongolian-Script-Generator", "max_issues_repo_head_hexsha": "ddc3eecae02b67612e615536d8fc2dd6829416ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "diffusion_model/unet.py", "max_forks_repo_name": "DL-Circle/Mongolian-Script-Generator", "max_forks_repo_head_hexsha": "ddc3eecae02b67612e615536d8fc2dd6829416ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7817109145, "max_line_length": 88, "alphanum_fraction": 0.549202021, "include": true, "reason": "import numpy", "num_tokens": 2472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.29098087236345377, "lm_q1q2_score": 0.15683380774496625}}
{"text": "#!/usr/bin/env python\n\nimport os,sys\nimport numpy as np\nfrom aqml.cheminfo import *\nfrom aqml.cheminfo.rw.xyz import *\nfrom representation.xb import get_nzs\n\nT,F = True,False\n\npi2 = np.pi*np.pi\na2b = 1.8897261258369282  # angstrom to bohr\n\nnp.set_printoptions(precision=2)\n\nclass rkrr(object):\n    \"\"\"\n    recursive krr\n    \"\"\"\n    def __init__(self, ys):\n        \"\"\" Note that the column of `ys represents the same property\n        generated from different level of theory \"\"\"\n        self._ys = np.array(ys)\n        self.nm = len(ys)\n        self.nl = len(ys[0]) # number of levels\n        # initialize test set size `n2 to 0\n        self.n2 = 0\n\n    def init_m(self, obj):\n        \"\"\" initialize molecules \"\"\"\n        #assert type(obj) is molecules\n        self._zsu = np.unique( obj.zs )\n        self._zs = obj.zs\n        self._nas = obj.nas\n        self._nsheav = obj.nsheav\n        self._coords = obj.coords\n        _ias2 = np.cumsum(self._nas)\n        _ias1 = np.array([0,]+list(_ias2[:-1]),np.int)\n        self._ias1 = _ias1\n        self._ias2 = _ias2\n        # get energy of dressed atom\n        self._nzs = get_nzs(_ias1,_ias2,self._zs,self._zsu)\n\n    def get_idx(self,idx=-1,n1s=[],n1max=-1,seed1=1,namin=1,namax=7):\n        \"\"\"\n        get training/test idx\n\n        i) AML: idx=-n ([n] target mols)\n                namax=0 -> one training set, i.e., all amons\n                namax=7 -> 7 training sets, the i-th set is {N_I = i} (i=1,2,...,7)\n                namax=-5 -> one training set, comprising of all amons with N_I <= -namax\n        ii) random sampling: idx>0 (__not__ quite useful?!)\n        iii) manually select training set: idx=[0,3,10,...],\n        \"\"\"\n\n        if isinstance(idx,int):\n            if idx == 0:\n                # only k1 is to be calculated, then we can randomly choose training data\n                # from the molecules and shuffle many times to make an averaged LC\n                _idx1 = np.arange(self.nm)\n                idx2 = []\n            elif idx > 0:\n                np.random.seed(seed1) # fix the random sequence\n                tidxs = np.random.permutation(self.nm)\n                _idx1 = tidxs[:-idx]; idx2 = tidxs[-idx:]\n                if n1max > 0:\n                    _idx1 = _idx1[:n1max] # choose a subset\n            else:\n                tidxs = np.arange(self.nm); _idx1 = tidxs[:idx]; idx2 = tidxs[idx:]\n        elif isinstance(idx,list):\n            # idx as the maximal training set\n            _idx1 = np.array(idx,np.int)\n            tidxs = np.arange(self.nm)\n            idx2 = np.setdiff1d(tidxs,_idx1)\n        else:\n            print('#ERROR: unsupported type of `idx')\n            raise\n\n        n2 = len(idx2) # now test set is fixed!!\n        self.n2 = n2\n\n        # now get smaller training set sizes\n        nsu_heav = np.unique( self._nsheav ) # already in ascending order\n        self.nsu_heav = nsu_heav\n        idx1 = _idx1\n        nn1 = len(n1s)\n        aml = True\n        if namax == 0:\n            aml = False\n            if nn1 == 0:\n                # use only one training set, including all amons\n                idxs1 = [_idx1]\n            else:\n                idxs1 = [ _idx1[:n1] for n1 in n1s ]\n        elif namax < 0:\n            # use only one training set, {N_I <= -namax}\n            idx1 = _idx1[ np.logical_and(self._nsheav[_idx1]>=namin, self._nsheav[_idx1] <= -namax) ]\n            idx2 = np.setdiff1d(tidxs,idx1)\n            idxs1 = [idx1]; n1s = [len(idx1)]\n        else:\n            # use `namax-`namin+1 training sets to generate a LC\n            idxs1 = []\n            n1s = []\n            # Note that `nheav may not be of the same order as the mol idx in filename,\n            # so we'd better sort the idx of filenames! E.g., na=5 in frag_01.xyz while na=3 in frag_05.xyz\n            idx1_sorted = []\n            t = self._nsheav[_idx1]\n            cnt = 0\n            for na in range(namin,namax+1):\n                if np.any(na==nsu_heav):\n                    idx_i = _idx1[t==na]\n                    leni = len(idx_i)\n                    idx1_sorted += list(idx_i)\n                    cnt += leni\n                    n1s.append(cnt)\n                else:\n                    if cnt == 0:\n                        n1s.append(np.nan) #\n                    else:\n                        n1s.append(cnt)\n            print(' ** initial n1s = ', n1s)\n            idx1 = idx1_sorted\n        self.aml = aml\n        self.n1s = n1s\n\n        tidx = np.concatenate((idx1,idx2)).astype(np.int)\n        n1,n2 = len(idx1),len(idx2)\n        nt = n1+n2\n        self.ys = self._ys[tidx]\n\n        null = np.array([],np.int)\n        _nas = self._nas[tidx]\n        _coords = []; _zs = []\n        for i1 in tidx:\n            ib1,ie1 = self._ias1[i1],self._ias2[i1]\n            _coords += list(self._coords[ib1:ie1])\n            _zs += list(self._zs[ib1:ie1])\n        _coords = np.array(_coords)\n        _zs = np.array(_zs,np.int)\n\n        self.nas1 = _nas[:n1]\n        self.nas2 = null if n2 == 0 else _nas[n1:]\n        self.nas = _nas\n\n        self.nzs = self._nzs[tidx]\n        self.nsheav = self._nsheav[tidx]\n\n        # atomic index\n        ias_e = np.cumsum(_nas)\n        ias_b = np.concatenate(([0],ias_e[:-1]))\n        ias1 = np.concatenate( [ np.arange(ias_b[i],ias_e[i]) for i in range(n1) ] )\n        ias2 = null if n2 == 0 else np.concatenate( [ np.arange(ias_b[i],ias_e[i]) for i in range(n1,nt) ] )\n        iast = np.concatenate((ias1,ias2))\n        self.coords = _coords[iast]\n        self.zs1 = _zs[ias1]\n        self.zs2 = _zs[ias2]\n        self.zs = np.concatenate((self.zs1,self.zs2))\n        self.nat1 = len(ias1)\n        self.nat2 = len(ias2)\n\n\n    def calc_ae_dressed(self,nzs1,ys1,nzs2,ys2):\n        esb = np.linalg.lstsq(nzs1,ys1)[0]\n        ys1p = np.dot(nzs1,esb)\n        #print ' +++++ ys1.shape, ys1p.shape = ', ys1.shape, ys1p.shape\n        dys1 = ys1 - ys1p\n        ys2_base = np.dot(nzs2,esb)\n        dys2 = ys2 - ys2_base\n        return dys1,dys2, ys2_base\n\n    def calc_e_base(self,nzs1,ys1,nzs2):\n        esb = np.linalg.lstsq(nzs1,ys1,rcond=None)[0]\n        ys1p = np.dot(nzs1,esb)\n        #print ' +++++ ys1.shape, ys1p.shape = ', ys1.shape, ys1p.shape\n        dys1 = ys1 - ys1p\n        ys2_base = np.dot(nzs2,esb)\n        return dys1, ys2_base\n\n    def run(self, mks, usebl=T, llambda=1e-10, iprt=True):\n        \"\"\"do KRR training & test\n\n        vars\n        ================\n        \"\"\"\n        if isinstance(mks, (list,tuple)):\n            tmpk1,tmpk2 = mks;\n        elif isinstance(mks, str):\n            if os.path.exists(mks):\n                dic = np.load(mks)\n                tmpk1,tmpk2 = [ dic[key].copy() for key in ['k1','k2'] ]\n        else:\n            print('#ERROR: unknow input')\n            raise\n        mk1,mk2 = tmpk1.copy(), tmpk2.copy()\n\n        n2 = self.n2\n        tidxs = np.arange(self.nm)\n        idxs1 = tidxs[:-n2]; idxs2 = tidxs[-n2:]\n\n        # now train many krr models\n        nl = self.nl # number of levels\n        mods = []\n        n1sr = self.n1s[::-1] # order reversed\n        ys2p = np.zeros(n2)\n        ns_nested = []\n        for l in range(nl-1):\n            #lvi = levels[i]\n            _ims1 = list(range(n1sr[l]))\n            ims1 = _ims1 #[ np.logical_not( np.isnan(self.ys[_ims1,l]) ) ] # e.g., if E_QMC is not avail, was set to NaN\n            n1 = len(ims1)\n            ns_nested.append(n1)\n            nzs1, nzs2 = self.nzs[ims1], self.nzs[idxs2]\n            k1 = mk1[ims1][:,ims1]\n            k1[np.diag_indices_from(k1)] += llambda\n            k2 = mk2[:,ims1]\n            if l==0: # one model\n                _ys1 = self.ys[ims1,l]\n                ys1, ys2_base = self.calc_e_base(nzs1,_ys1,nzs2)\n            else: # i <= nl-2:\n                #_ys1_l = self.ys[ims1,l]; _ys1_lm1 = self.ys[ims1,l-1]\n                _ys1_l = self.ys[ims1,l] - self.ys[ims1,l-1]\n                ys1_l, ys2_base_l = self.calc_e_base(nzs1,_ys1_l,nzs2)\n                #ys1_lm1, ys2_base_lm1 = self.calc_e_base(nzs1,_ys1_lm1,nzs2)\n                ys1 = ys1_l; ys2_base = ys2_base_l\n                #ys1 = ys1_l - ys1_lm1; ys2_base = 0.\n            alphas = np.linalg.solve(k1,ys1)\n            ys2p_l = np.dot(k2,alphas) + ys2_base\n            ys2p += ys2p_l\n        print(' ** ns_nested = ', ns_nested )\n\n        # last machine\n        _n1s = self.n1s\n        l = nl-1\n        maes = []\n        n1s = []\n        for i,_n1 in enumerate(_n1s):\n            _ims1 = np.arange(_n1)\n            #print ' ims1 = ', _ims1, self.ys[_ims1,l]\n            ims1 = _ims1[ np.logical_not( np.isnan(self.ys[_ims1,l]) ) ] # e.g., if E_QMC is not avail, was set to NaN\n            n1 = len(ims1)\n            nzs1, nzs2 = self.nzs[ims1], self.nzs[idxs2]\n            if np.linalg.matrix_rank(nzs1) < len(nzs1[0]):\n                print('%6s'%('None'))\n                n1s.append(np.nan)\n                maes.append(np.nan) #; rmses.append(np.nan)\n                continue\n\n            k1 = mk1[ims1][:,ims1]\n            k1[np.diag_indices_from(k1)] += llambda\n            k2 = mk2[:,ims1]\n            #_ys1_l = self.ys[ims1,l]; _ys1_lm1 = self.ys[ims1,l-1]\n            _ys1_l = self.ys[ims1,l] - self.ys[ims1,l-1]\n            ys1_l, ys2_base_l = self.calc_e_base(nzs1,_ys1_l,nzs2)\n            #ys1_lm1, ys2_base_lm1 = self.calc_e_base(nzs1,_ys1_lm1,nzs2)\n            ys1 = ys1_l\n            #ys1 = ys1_l - ys1_lm1\n            ys2_base = ys2_base_l\n            alphas = np.linalg.solve(k1,ys1)\n            #print(' --> ys2p, k2*alpha, ys2_base = ',ys2p, np.dot(k2,alphas), ys2_base)\n            ys2p_final = ys2p + np.dot(k2,alphas) + ys2_base\n\n            dys = ys2p_final - self.ys[idxs2,l]\n            print('%6d %.2f'%(len(ims1), dys[0]))\n            maes.append( dys[0] )\n            n1s.append(n1)\n        self.maes = maes\n        self.n1s = n1s\n\n", "meta": {"hexsha": "2ffa17bcefb9210cf5d98887c85d5080bf890005", "size": 9792, "ext": "py", "lang": "Python", "max_stars_repo_path": "coreml/cml/algo/rkrr.py", "max_stars_repo_name": "binghuang2018/aqml", "max_stars_repo_head_hexsha": "4901f3bd85db968fb3fc7ab97fd443421909d89d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2020-02-17T11:15:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T18:03:15.000Z", "max_issues_repo_path": "coreml/cml/algo/rkrr.py", "max_issues_repo_name": "binghuang2018/aqml", "max_issues_repo_head_hexsha": "4901f3bd85db968fb3fc7ab97fd443421909d89d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-11T06:49:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-21T07:30:53.000Z", "max_forks_repo_path": "coreml/cml/algo/rkrr.py", "max_forks_repo_name": "binghuang2018/aqml", "max_forks_repo_head_hexsha": "4901f3bd85db968fb3fc7ab97fd443421909d89d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-09T01:37:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-19T13:13:34.000Z", "avg_line_length": 36.4014869888, "max_line_length": 120, "alphanum_fraction": 0.5099060458, "include": true, "reason": "import numpy", "num_tokens": 3056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.2751297357103299, "lm_q1q2_score": 0.15678340535767246}}
{"text": "#!/usr/bin/env python\nimport os\nimport sys\nimport numpy as np\nimport matplotlib\nmatplotlib.use('PDF')\nfrom StringIO import StringIO\nfrom mgplottools.mpl import get_color, set_axis, new_figure, ls, \\\n                            set_color_cycle\n\ndef create_figure(outfile, pulse_duration, pop_0i, pop_rr, gate_error):\n\n    # Layout\n    fig_width       = 12.5              # Total canvas (cv) width\n    left_margin     = 2.25              # Left cv -> plot area\n    right_margin    = 2.25              # plot area -> right cv\n    top_margin      = 0.3               # top cv -> plot area\n    bottom_margin   = 1.0               # bottom cv -> panel 1\n    h               = 2.5               # height of each panel\n    w = fig_width - (left_margin + right_margin)  # width of panel\n    fig_height = bottom_margin + h + top_margin\n    fig = new_figure(fig_width, fig_height)\n\n    set_color_cycle()\n\n    # Panel\n    pos = [left_margin/fig_width, bottom_margin/fig_height,\n           w/fig_width, h/fig_height]\n    ax = fig.add_axes(pos)\n    ax.plot(pulse_duration, pop_0i, dashes=ls['dashed'],\n            label='max pop in $\\Ket{0i}$')\n    ax.plot(pulse_duration, pop_rr, dashes=ls['long-dashed'],\n            label='max pop in $\\Ket{rr}$')\n    ax.plot(pulse_duration, gate_error, color='black',\n            label='gate error')\n    set_axis(ax, 'x', 0, 700, 100, minor=4, range=(10, 700),\n             label='central pulse duration (ns)')\n    ax.set_yscale('log')\n    ax.set_ylim(1.0e-3, 1.0e0)\n    ax.legend()\n\n    # output\n    fig.savefig(outfile, format=os.path.splitext(outfile)[1][1:])\n\n\ndef read_data(datfile):\n    data = \"\"\"\n# pulse dur [ns]  max pop 0i        max pop rr      gate error\n  10              0.0837            0.8827          0.54675839\n  20              0.0506            0.7553          0.42540254\n  30              0.0363            0.5689          0.31267201\n  40              0.0283            0.3972          0.23354138\n  50              0.0232            0.2699          0.17602662\n  75              0.016             0.1153          0.08980501\n  100             0.0122            0.0694          0.05393173\n  150             0.0083            0.0343          0.0249168\n  200             0.0063            0.02            0.01393326\n  250             0.005             0.0128          0.00952858\n  300             0.0042            0.009           0.00662097\n  350             0.0036            0.0066          0.00482424\n  400             0.0032            0.0051          0.00366514\n  450             0.0029            0.004           0.00298152\n  500             0.0025515683      0.0032745798    0.00240066\n  550             0.0023239946      0.0027134376    0.00195581\n  600             0.0021279147      0.0022725114    0.00175541\n  650             0.0019674974      0.0019544359    0.00135133\n  700             0.0018390561      0.0016939797    0.00085459\n\"\"\"\n    return np.genfromtxt(StringIO(data), unpack=True)\n\n\ndef main(argv=None):\n    if argv is None:\n        argv = sys.argv\n    basename = os.path.splitext(__file__)[0]\n    outfile = basename + '.pdf'\n    data_folder = basename\n    create_figure(outfile, *read_data(data_folder))\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n", "meta": {"hexsha": "e8c6047f6cc9480a7d8dbe83a138cfd2321d7ab4", "size": 3217, "ext": "py", "lang": "Python", "max_stars_repo_path": "chapters/robust/rydberg_qsl.py", "max_stars_repo_name": "goerz/dissertation", "max_stars_repo_head_hexsha": "ee8ae29b5da1bc6033260224ae6444fd7f4c4a2f", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-05-09T03:22:23.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-11T13:33:43.000Z", "max_issues_repo_path": "chapters/robust/rydberg_qsl.py", "max_issues_repo_name": "goerz/dissertation", "max_issues_repo_head_hexsha": "ee8ae29b5da1bc6033260224ae6444fd7f4c4a2f", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/robust/rydberg_qsl.py", "max_forks_repo_name": "goerz/dissertation", "max_forks_repo_head_hexsha": "ee8ae29b5da1bc6033260224ae6444fd7f4c4a2f", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2317073171, "max_line_length": 71, "alphanum_fraction": 0.5222256761, "include": true, "reason": "import numpy", "num_tokens": 1000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3040416812727289, "lm_q1q2_score": 0.15676994607412845}}
{"text": "import numpy as np\nimport pyproj\nimport scipy.ndimage\nfrom scipy import interpolate\nfrom netCDF4 import Dataset\nfrom Yoffe import regularizedYoffe\nfrom scipy import ndimage\n\n\ndef writeNetcdf(sname, lDimVar, lName, lData, paraview_readable=False):\n    \"\"\"create a netcdf file either readable by ASAGI\n    or by paraview (paraview_readable=True)\n\n    Parameters\n    ----------\n    sname: str prefix name of output file\n    lDimVar: list of 1d numpy array containing the dimension variables\n    lName: list if str containing the name of the nd variables\n    lData: list if n-d numpy array containing the data\n    paraview_readable: bool\n    \"\"\"\n    fname = f\"{sname}.nc\"\n    print(\"writing \" + fname)\n\n    with Dataset(fname, \"w\", format=\"NETCDF4\") as rootgrp:\n        # Create dimension and 1d variables\n        sdimVarNames = \"uvwxyz\"\n        dims = []\n        for i, xi in enumerate(lDimVar):\n            nxi = xi.shape[0]\n            dimName = sdimVarNames[i]\n            dims.append(dimName)\n            rootgrp.createDimension(dimName, nxi)\n            vx = rootgrp.createVariable(dimName, \"f4\", (dimName,))\n            vx[:] = xi\n        dims.reverse()\n        dims = tuple(dims)\n\n        if paraview_readable:\n            for i in range(len(lName)):\n                vTd = rootgrp.createVariable(lName[i], \"f4\", dims)\n                vTd[:] = lData[i]\n        else:\n            ldata4 = [(name, \"f4\") for name in lName]\n            ldata8 = [(name, \"f8\") for name in lName]\n            mattype4 = np.dtype(ldata4)\n            mattype8 = np.dtype(ldata8)\n            mat_t = rootgrp.createCompoundType(mattype4, \"material\")\n\n            # this transform the nD array into an array of tuples\n            arr = np.stack([lData[i] for i in range(len(lName))], axis=len(dims))\n            newarr = arr.view(dtype=mattype8)\n            newarr = newarr.reshape(newarr.shape[:-1])\n            mat = rootgrp.createVariable(\"data\", mat_t, dims)\n            mat[:] = newarr\n\n\ndef cosine_taper(npts, p=0.1, freqs=None, flimit=None, halfcosine=True, sactaper=False):\n    \"\"\"\n    Cosine Taper. (copied from obspy:\n    https://docs.obspy.org/master/_modules/obspy/signal/invsim.html#cosine_taper\n\n    :type npts: int\n    :param npts: Number of points of cosine taper.\n    :type p: float\n    :param p: Decimal percentage of cosine taper (ranging from 0 to 1). Default\n        is 0.1 (10%) which tapers 5% from the beginning and 5% form the end.\n    :rtype: float NumPy :class:`~numpy.ndarray`\n    :return: Cosine taper array/vector of length npts.\n    :type freqs: NumPy :class:`~numpy.ndarray`\n    :param freqs: Frequencies as, for example, returned by fftfreq\n    :type flimit: list or tuple of floats\n    :param flimit: The list or tuple defines the four corner frequencies\n        (f1, f2, f3, f4) of the cosine taper which is one between f2 and f3 and\n        tapers to zero for f1 < f < f2 and f3 < f < f4.\n    :type halfcosine: bool\n    :param halfcosine: If True the taper is a half cosine function. If False it\n        is a quarter cosine function.\n    :type sactaper: bool\n    :param sactaper: If set to True the cosine taper already tapers at the\n        corner frequency (SAC behavior). By default, the taper has a value\n        of 1.0 at the corner frequencies.\n\n    .. rubric:: Example\n\n    >>> tap = cosine_taper(100, 1.0)\n    >>> tap2 = 0.5 * (1 + np.cos(np.linspace(np.pi, 2 * np.pi, 50)))\n    >>> np.allclose(tap[0:50], tap2)\n    True\n    >>> npts = 100\n    >>> p = 0.1\n    >>> tap3 = cosine_taper(npts, p)\n    >>> (tap3[int(npts*p/2):int(npts*(1-p/2))]==np.ones(int(npts*(1-p)))).all()\n    True\n    \"\"\"\n    if p < 0 or p > 1:\n        msg = \"Decimal taper percentage must be between 0 and 1.\"\n        raise ValueError(msg)\n    if p == 0.0 or p == 1.0:\n        frac = int(npts * p / 2.0)\n    else:\n        frac = int(npts * p / 2.0 + 0.5)\n\n    if freqs is not None and flimit is not None:\n        fl1, fl2, fl3, fl4 = flimit\n        idx1 = np.argmin(abs(freqs - fl1))\n        idx2 = np.argmin(abs(freqs - fl2))\n        idx3 = np.argmin(abs(freqs - fl3))\n        idx4 = np.argmin(abs(freqs - fl4))\n    else:\n        idx1 = 0\n        idx2 = frac - 1\n        idx3 = npts - frac\n        idx4 = npts - 1\n    if sactaper:\n        # in SAC the second and third\n        # index are already tapered\n        idx2 += 1\n        idx3 -= 1\n\n    # Very small data lengths or small decimal taper percentages can result in\n    # idx1 == idx2 and idx3 == idx4. This breaks the following calculations.\n    if idx1 == idx2:\n        idx2 += 1\n    if idx3 == idx4:\n        idx3 -= 1\n\n    # the taper at idx1 and idx4 equals zero and\n    # at idx2 and idx3 equals one\n    cos_win = np.zeros(npts)\n    if halfcosine:\n        # cos_win[idx1:idx2+1] =  0.5 * (1.0 + np.cos((np.pi * \\\n        #    (idx2 - np.arange(idx1, idx2+1)) / (idx2 - idx1))))\n        cos_win[idx1 : idx2 + 1] = 0.5 * (1.0 - np.cos((np.pi * (np.arange(idx1, idx2 + 1) - float(idx1)) / (idx2 - idx1))))\n        cos_win[idx2 + 1 : idx3] = 1.0\n        cos_win[idx3 : idx4 + 1] = 0.5 * (1.0 + np.cos((np.pi * (float(idx3) - np.arange(idx3, idx4 + 1)) / (idx4 - idx3))))\n    else:\n        cos_win[idx1 : idx2 + 1] = np.cos(-(np.pi / 2.0 * (float(idx2) - np.arange(idx1, idx2 + 1)) / (idx2 - idx1)))\n        cos_win[idx2 + 1 : idx3] = 1.0\n        cos_win[idx3 : idx4 + 1] = np.cos((np.pi / 2.0 * (float(idx3) - np.arange(idx3, idx4 + 1)) / (idx4 - idx3)))\n\n    # if indices are identical division by zero\n    # causes NaN values in cos_win\n    if idx1 == idx2:\n        cos_win[idx1] = 0.0\n    if idx3 == idx4:\n        cos_win[idx3] = 0.0\n    return cos_win\n\n\ndef interpolate_nan_from_neighbors(array):\n    \"\"\"rise_time and tacc may not be defined where there is no slip (no SR function).\n    in this case, we interpolate from neighbors\n    source: https://stackoverflow.com/questions/37662180/interpolate-missing-values-2d-python\n    \"\"\"\n    x = np.arange(0, array.shape[1])\n    y = np.arange(0, array.shape[0])\n    # mask invalid values\n    array = np.ma.masked_invalid(array)\n    xx, yy = np.meshgrid(x, y)\n    # get only the valid values\n    x1 = xx[~array.mask]\n    y1 = yy[~array.mask]\n    newarr = array[~array.mask]\n    return interpolate.griddata((x1, y1), newarr.ravel(), (xx, yy), method=\"linear\", fill_value=np.average(array))\n\n\ndef compute_block_mean(ar, fact):\n    \"\"\"\n    dowsample array ar by factor fact\n    https://stackoverflow.com/questions/18666014/downsample-array-in-python\n    \"\"\"\n    assert isinstance(fact, int), type(fact)\n    sx, sy = ar.shape\n    X, Y = np.ogrid[0:sx, 0:sy]\n    regions = sy // fact * (X // fact) + Y // fact\n    res = ndimage.mean(ar, labels=regions, index=np.arange(regions.max() + 1))\n    res.shape = (sx // fact, sy // fact)\n    return res\n\n\ndef upsample_quantities(allarr, spatial_order, spatial_zoom, padding=\"constant\", extra_padding_layer=False, minimize_block_average_variations=False):\n    \"\"\"1. pad\n    2. upsample, adding spatial_zoom per node\n    \"\"\"\n    nd = allarr.shape[0]\n    ny, nx = [val * spatial_zoom for val in allarr[0].shape]\n    if extra_padding_layer:\n        # required for vertex aligned netcdf format\n        nx = nx + 2\n        ny = ny + 2\n    allarr0 = np.zeros((nd, ny, nx))\n    for k in range(nd):\n        if padding == \"extrapolate\":\n            my_array0 = np.pad(allarr[k, :, :], ((1, 1), (1, 1)), \"reflect\", reflect_type=\"odd\")\n        else:\n            my_array0 = np.pad(allarr[k, :, :], ((1, 1), (1, 1)), padding)\n        if extra_padding_layer:\n            ncrop = spatial_zoom - 1\n        else:\n            ncrop = spatial_zoom\n        my_array = scipy.ndimage.zoom(my_array0, spatial_zoom, order=spatial_order, mode=\"grid-constant\", grid_mode=True)\n        if minimize_block_average_variations:\n            # inspired by Tinti et al. (2005) (Appendix A)\n            # This is for the specific case of fault slip.\n            # We want to preserve the seismic moment of each subfault after interpolation\n            # the rock rigidity is not know by this script (would require some python binding of easi).\n            # the subfault area is typically constant over the kinematic model\n            # So we just want to perserve subfault average.\n            print(\"trying to perserve subfault average...\")\n            my_array = np.maximum(0, my_array)\n            best_misfit = float(\"inf\")\n            # The algorithm does not seem to converge, but produces better model\n            # (given the misfit) that inital after 2-3 iterations\n            niter = 30\n            for i in range(niter):\n                block_average = compute_block_mean(my_array, spatial_zoom)\n                correction = my_array0 / block_average\n                # having a misfit as misfit = np.linalg.norm(correction) does not makes sense as for almost 0 slip, correction can be large\n                misfit = np.linalg.norm(my_array0 - block_average) / len(my_array0)\n                if best_misfit > misfit:\n                    if i == 0:\n                        print(f\"misfit at iter {i}: {misfit}\")\n                    else:\n                        print(f\"misfit improved at iter {i}: {misfit}\")\n                    best_misfit = misfit\n                    best = np.copy(my_array)\n                my_array = scipy.ndimage.zoom(correction * my_array0, spatial_zoom, order=spatial_order, mode=\"grid-constant\", grid_mode=True)\n                my_array = np.maximum(0, my_array)\n            my_array = best\n        if ncrop > 0:\n            allarr0[k, :, :] = my_array[ncrop:-ncrop, ncrop:-ncrop]\n\n    return allarr0\n\n\nclass FaultPlane:\n    def __init__(self):\n        self.nx = 0\n        self.ny = 0\n        self.ndt = 0\n        self.PSarea_cm2 = 0\n        self.dt = 0\n        # array member initialized to dummy value\n        self.lon = 0\n        self.lat = 0\n        self.x = 0\n        self.y = 0\n        self.depth = 0\n        self.t0 = 0\n        self.slip1 = 0\n        self.strike = 0\n        self.dip = 0\n        self.rake = 0\n        self.aSR = 0\n        self.myt = 0\n\n    def init_spatial_arrays(self, nx, ny):\n        self.nx = nx\n        self.ny = ny\n        self.lon = np.zeros((ny, nx))\n        self.lat = np.zeros((ny, nx))\n        self.x = np.zeros((ny, nx))\n        self.y = np.zeros((ny, nx))\n        self.depth = np.zeros((ny, nx))\n        self.t0 = np.zeros((ny, nx))\n        self.slip1 = np.zeros((ny, nx))\n        self.strike = np.zeros((ny, nx))\n        self.dip = np.zeros((ny, nx))\n        self.rake = np.zeros((ny, nx))\n\n    def init_aSR(self):\n        self.aSR = np.zeros((self.ny, self.nx, self.ndt))\n\n    def extend_aSR(self, ndt_old, ndt_new):\n        \"extend aSR array to more time samplings\"\n        tmpSR = np.copy(self.aSR)\n        self.ndt = ndt_new\n        self.aSR = np.zeros((self.ny, self.nx, self.ndt))\n        self.aSR[:, :, 0:ndt_old] = tmpSR[:, :, :]\n\n    def compute_xy_from_latlon(self, proj):\n        if proj:\n            from pyproj import Transformer\n\n            transformer = Transformer.from_crs(\"epsg:4326\", proj[0], always_xy=True)\n            self.x, self.y = transformer.transform(self.lon, self.lat)\n        else:\n            print(\"no proj string specified!\")\n            self.x, self.y = self.lon, self.lat\n\n    def compute_latlon_from_xy(self, proj):\n        if proj:\n            from pyproj import Transformer\n\n            transformer = Transformer.from_crs(proj[0], \"epsg:4326\", always_xy=True)\n            self.lon, self.lat = transformer.transform(self.x, self.y)\n        else:\n            self.lon, self.lat = self.x, self.y\n\n    def compute_time_array(self):\n        self.myt = np.linspace(0, (self.ndt - 1) * self.dt, self.ndt)\n\n    def write_srf(self, fname):\n        \"write kinematic model to a srf file (standard rutpure format)\"\n        with open(fname, \"w\") as fout:\n            fout.write(\"1.0\\n\")\n            fout.write(\"POINTS %d\\n\" % (self.nx * self.ny))\n            for j in range(self.ny):\n                for i in range(self.nx):\n                    fout.write(\"%g %g %g %g %g %e %g %g\\n\" % (self.lon[j, i], self.lat[j, i], self.depth[j, i], self.strike[j, i], self.dip[j, i], self.PSarea_cm2, self.t0[j, i], self.dt))\n                    fout.write(\"%g %g %d %f %d %f %d\\n\" % (self.rake[j, i], self.slip1[j, i], self.ndt, 0.0, 0, 0.0, 0))\n                    np.savetxt(fout, self.aSR[j, i, :], fmt=\"%g\", newline=\" \")\n                    fout.write(\"\\n\")\n        print(\"done writing\", fname)\n\n    def init_from_srf(self, fname):\n        \"init object by reading a srf file (standard rutpure format)\"\n        with open(fname) as fid:\n            # version\n            line = fid.readline()\n            version = float(line)\n            if not (abs(version - 1.0) < 1e-03 or abs(version - 2.0) < 1e-03):\n                print(\"srf version: %s not supported\" % (line))\n                raise\n            # skip comments\n            while True:\n                line = fid.readline()\n                if not line.startswith(\"#\"):\n                    break\n            line_el = line.split()\n            if line_el[0] != \"PLANE\":\n                print(\"no plane specified\")\n                raise\n            if line_el[1] != \"1\":\n                print(\"only one plane supported\")\n                raise NotImplementedError\n            line_el = fid.readline().split()\n            nx, ny = [int(val) for val in line_el[2:4]]\n            line_el = fid.readline().split()\n            # check that the plane data are consistent with the number of points\n            assert int(line_el[1]) == nx * ny\n            self.init_spatial_arrays(nx, ny)\n            for j in range(ny):\n                for i in range(nx):\n                    # first header line\n                    line = fid.readline()\n                    # rho_vs are only present for srf version 2\n                    self.lon[j, i], self.lat[j, i], self.depth[j, i], self.strike[j, i], self.dip[j, i], self.PSarea_cm2, self.t0[j, i], dt, *rho_vs = [float(v) for v in line.split()]\n                    # second header line\n                    line = fid.readline()\n                    self.rake[j, i], self.slip1[j, i], ndt1, slip2, ndt2, slip3, ndt3 = [float(v) for v in line.split()]\n                    if max(slip2, slip3) > 0.0:\n                        print(\"this script assumes slip2 and slip3 are zero\", slip2, slip3)\n                        raise NotImplementedError\n                    ndt1 = int(ndt1)\n                    if max(i, j) == 0:\n                        self.ndt = ndt1\n                        self.dt = dt\n                        self.init_aSR()\n                    lSTF = []\n                    if ndt1 == 0:\n                        continue\n                    if ndt1 > self.ndt:\n                        print(f\"a larger ndt ({ndt1}> {self.ndt}) was found for point source (i,j) = ({i}, {j}) extending aSR array...\")\n                        self.extend_aSR(self.ndt, ndt1)\n                    if abs(dt - self.dt) > 1e-6:\n                        print(\"this script assumes that dt is the same for all sources\", dt, self.dt)\n                        raise NotImplementedError\n                    while True:\n                        line = fid.readline()\n                        lSTF.extend(line.split())\n                        if len(lSTF) == ndt1:\n                            self.aSR[j, i, 0:ndt1] = np.array([float(v) for v in lSTF])\n                            break\n\n    def assess_STF_parameters(self):\n        \"compute rise_time (slip duration) and t_acc (peak SR) from SR time histories\"\n        self.rise_time = np.zeros((self.ny, self.nx))\n        self.tacc = np.zeros((self.ny, self.nx))\n        for j in range(self.ny):\n            for i in range(self.nx):\n                if not self.slip1[j, i]:\n                    self.rise_time[j, i] = np.nan\n                    self.tacc[j, i] = np.nan\n                else:\n                    first_non_zero = np.amin(np.where(self.aSR[j, i, :])[0])\n                    last_non_zero = np.amax(np.where(self.aSR[j, i, :])[0])\n                    id_max = np.where(self.aSR[j, i, :] == np.amax(self.aSR[j, i, :]))[0]\n                    self.rise_time[j, i] = (last_non_zero - first_non_zero + 1) * self.dt\n                    self.tacc[j, i] = (id_max - first_non_zero + 1) * self.dt\n                    self.t0[j, i] += first_non_zero * self.dt\n        self.rise_time = interpolate_nan_from_neighbors(self.rise_time)\n        self.tacc = interpolate_nan_from_neighbors(self.tacc)\n\n        print(\"slip rise_time (min, 50%, max)\", np.amin(self.rise_time), np.median(self.rise_time), np.amax(self.rise_time))\n        print(\"tacc (min, 50%, max)\", np.amin(self.tacc), np.median(self.tacc), np.amax(self.tacc))\n\n    def upsample_fault(self, spatial_order, spatial_zoom, temporal_zoom, proj, use_Yoffe=False, time_smoothing_kernel_as_dt_fraction=0.5):\n        \"increase spatial and temporal resolution of kinematic model by interpolation\"\n        # time vector\n        ndt2 = (self.ndt - 1) * temporal_zoom + 1\n        ny2, nx2 = self.ny * spatial_zoom, self.nx * spatial_zoom\n        # resampled source\n        pf = FaultPlane()\n        pf.init_spatial_arrays(nx2, ny2)\n        pf.ndt = ndt2\n        pf.init_aSR()\n\n        pf.dt = self.dt / temporal_zoom\n        pf.compute_time_array()\n\n        # upsample spatially geometry (bilinear interpolation)\n        allarr = np.array([self.x, self.y, self.depth])\n        pf.x, pf.y, pf.depth = upsample_quantities(allarr, spatial_order=1, spatial_zoom=spatial_zoom, padding=\"extrapolate\")\n\n        # upsample other quantities\n        allarr = np.array([self.t0, self.strike, self.dip, self.rake])\n        pf.t0, pf.strike, pf.dip, pf.rake = upsample_quantities(allarr, spatial_order, spatial_zoom, padding=\"edge\")\n        # the interpolation may generate some acausality that we here prevent\n        pf.t0 = np.maximum(pf.t0, np.amin(self.t0))\n\n        allarr = np.array([self.slip1])\n        (pf.slip1,) = upsample_quantities(allarr, spatial_order, spatial_zoom, padding=\"constant\", minimize_block_average_variations=True)\n        pf.compute_latlon_from_xy(proj)\n        pf.PSarea_cm2 = self.PSarea_cm2 / spatial_zoom ** 2\n        ratio_potency = np.sum(pf.slip1) * pf.PSarea_cm2 / (np.sum(self.slip1) * self.PSarea_cm2)\n        print(f\"seismic potency ratio (upscaled over initial): {ratio_potency}\")\n\n        if use_Yoffe:\n            self.assess_STF_parameters()\n            allarr = np.array([self.rise_time, self.tacc])\n            pf.rise_time, pf.tacc = upsample_quantities(allarr, spatial_order, spatial_zoom, padding=\"edge\")\n            pf.rise_time = np.maximum(pf.rise_time, np.amin(self.rise_time))\n            pf.tacc = np.maximum(pf.tacc, np.amin(self.tacc))\n            print(\"using ts = tacc / 1.27 to compute the regularized Yoffe\")\n            ts = pf.tacc / 1.27\n            tr = pf.rise_time - 2.0 * ts\n            for j in range(pf.ny):\n                for i in range(pf.nx):\n                    for k, tk in enumerate(pf.myt):\n                        pf.aSR[j, i, k] = pf.slip1[j, i] * regularizedYoffe(tk, ts[j, i], tr[j, i])\n        else:\n            aSRa = np.zeros((pf.ny, pf.nx, self.ndt))\n            for k in range(self.ndt):\n                aSRa[:, :, k] = upsample_quantities(np.array([self.aSR[:, :, k]]), spatial_order, spatial_zoom, padding=\"constant\")\n\n            # interpolate temporally the AST\n            for j in range(pf.ny):\n                for i in range(pf.nx):\n                    # 1. upsample with linear interpolation\n                    # 2. apply a gauss kernel to smooth out sharp edges\n                    # 3. tapper the signal smoothly to 0 at both time ends\n                    # 4. rescale SR to ensure integral (SR) = slip\n                    f = interpolate.interp1d(self.myt, aSRa[j, i, :], kind=\"linear\")\n                    pf.aSR[j, i, :] = f(pf.myt)\n                    tapper = cosine_taper(pf.ndt, self.dt / (pf.ndt * pf.dt))\n                    pf.aSR[j, i, :] = tapper * ndimage.gaussian_filter1d(pf.aSR[j, i, :], time_smoothing_kernel_as_dt_fraction * self.dt / pf.dt, mode=\"constant\")\n                    # With a cubic interpolation, the interpolated slip1 may be negative which does not make sense.\n                    if pf.slip1[j, i] < 0:\n                        pf.aSR[j, i, :] = 0\n                        continue\n                    # should be the SR\n                    integral_STF = np.trapz(np.abs(pf.aSR[j, i, :]), dx=pf.dt)\n                    if abs(integral_STF) > 0:\n                        pf.aSR[j, i, :] = pf.slip1[j, i] * pf.aSR[j, i, :] / integral_STF\n        return pf\n\n    def compute_corrected_slip_for_differing_area(self, proj):\n        \"\"\"\n        self.PSarea_cm2 may slightly differ from the patch area from the fault geometry\n        (e.g. due to the projection)\n        Therefore, we need to update slip to keep seismic potency (area*slip) unchanged\n        \"\"\"\n        cm2m = 0.01\n        km2m = 1e3\n        PSarea_m2 = self.PSarea_cm2 * cm2m * cm2m\n        self.compute_xy_from_latlon(proj)\n        nx, ny = self.nx, self.ny\n        # Compute actual dx and dy from coordinates\n        dy = np.zeros((ny, nx))\n        dx = np.zeros((ny, nx))\n        # central difference for the inside\n        coords = np.array((self.x, self.y, -km2m * self.depth))\n        for i in range(0, nx):\n            p0 = coords[:, 0 : ny - 2, i] - coords[:, 2:ny, i]\n            dy[1 : ny - 1, i] = 0.5 * np.linalg.norm(p0, axis=0)\n        # special case of 0 and ny-1\n        p0 = coords[:, 1, :] - coords[:, 0, :]\n        dy[0, :] = np.linalg.norm(p0, axis=0)\n        p0 = coords[:, ny - 1, :] - coords[:, ny - 2, :]\n        dy[ny - 1, :] = np.linalg.norm(p0, axis=0)\n        # dx for coordinates\n        for j in range(0, ny):\n            p0 = coords[:, j, 0 : nx - 2] - coords[:, j, 2:nx]\n            dx[j, 1 : nx - 1] = 0.5 * np.linalg.norm(p0, axis=0)\n        p0 = coords[:, :, 1] - coords[:, :, 0]\n        dx[:, 0] = np.linalg.norm(p0, axis=0)\n        p0 = coords[:, :, nx - 1] - coords[:, :, nx - 2]\n        dx[:, nx - 1] = np.linalg.norm(p0, axis=0)\n        factor_area = dx[:, :] * dy[:, :] / PSarea_m2\n        slip1 = self.slip1 * factor_area\n        print(\n            f\"done correcting slip for area. \\\nThe correcting factor ranges between {np.amin(factor_area)} and {np.amax(factor_area)}\"\n        )\n        return slip1\n\n    def generate_netcdf_fl33(self, prefix, spatial_order, spatial_zoom, proj, write_paraview):\n        \"generate netcdf files to be used with SeisSol friction law 33\"\n\n        cm2m = 0.01\n        km2m = 1e3\n        # a kinematic model defines the fault quantities at the subfault center\n        # a netcdf file defines the quantities at the nodes\n        # therefore the extra_padding_layer=True, and the added di below\n        cslip = self.compute_corrected_slip_for_differing_area(proj)\n        (slip,) = upsample_quantities(np.array([cslip]), spatial_order, spatial_zoom, padding=\"constant\", extra_padding_layer=True, minimize_block_average_variations=True)\n        allarr = np.array([self.t0, self.rake, self.rise_time, self.tacc])\n        rupttime, rake, rise_time, tacc = upsample_quantities(allarr, spatial_order, spatial_zoom, padding=\"edge\", extra_padding_layer=True)\n        # upsampled duration, rise_time and acc_time may not be smaller than initial values\n        # at least rise_time could lead to a non-causal kinematic model\n        rupttime = np.maximum(rupttime, np.amin(self.t0))\n        rise_time = np.maximum(rise_time, np.amin(self.rise_time))\n        tacc = np.maximum(tacc, np.amin(self.tacc))\n\n        rake_rad = np.radians(rake)\n        strike_slip = slip * np.cos(rake_rad) * cm2m\n        dip_slip = slip * np.sin(rake_rad) * cm2m\n\n        ny, nx = slip.shape\n        dx = np.sqrt(self.PSarea_cm2 * cm2m * cm2m)\n        ldataName = [\"strike_slip\", \"dip_slip\", \"rupture_onset\", \"effective_rise_time\", \"acc_time\"]\n        lgridded_myData = [strike_slip, dip_slip, rupttime, rise_time, tacc]\n        # we could do directly\n        # di = 1.0 / (2 * spatial_zoom)\n        # xb = np.linspace(-di, self.nx + di, nx) * dx\n        # yb = np.linspace(-di, self.ny + di, ny) * dx\n        # But we compute xb and yb based on the upsampled coordinates, to account for possible warping due to the projection\n        allarr = np.array([self.x, self.y, -km2m * self.depth])\n        coords = upsample_quantities(allarr, spatial_order=1, spatial_zoom=spatial_zoom, padding=\"extrapolate\", extra_padding_layer=True)\n\n        p0 = coords[:, (ny - 1) // 2, :] - coords[:, (ny - 1) // 2 - 1, :]\n        dx1 = np.linalg.norm(p0, axis=0)\n        xb = np.cumsum(dx1) - 1.5 * dx1[0]\n\n        p0 = coords[:, :, (nx - 1) // 2] - coords[:, :, (nx - 1) // 2 - 1]\n        dy1 = np.linalg.norm(p0, axis=0)\n        yb = np.cumsum(dy1) - 1.5 * dy1[0]\n\n        prefix2 = f\"{prefix}_{spatial_zoom}_o{spatial_order}\"\n        if write_paraview:\n            # see comment above\n            for i, sdata in enumerate(ldataName):\n                writeNetcdf(prefix2 + sdata, [xb, yb], [sdata], [lgridded_myData[i]], paraview_readable=True)\n        writeNetcdf(prefix2, [xb, yb], ldataName, lgridded_myData)\n\n    def generate_fault_ts_yaml_fl33(self, prefix, spatial_order, spatial_zoom, proj):\n        \"\"\"Generate yaml file initializing FL33 arrays and ts file describing the planar fault geometry.\"\"\"\n        # Generate yaml file loading ASAGI file\n        cm2m = 0.01\n        km2m = 1e3\n        self.compute_xy_from_latlon(proj)\n        nx, ny = self.nx, self.ny\n        p0 = np.array([self.x[0, 0], self.y[0, 0], -km2m * self.depth[0, 0]])\n        p1 = np.array([self.x[ny - 1, 0], self.y[ny - 1, 0], -km2m * self.depth[ny - 1, 0]])\n        p2 = np.array([self.x[0, nx - 1], self.y[0, nx - 1], -km2m * self.depth[0, nx - 1]])\n        p3 = np.array([self.x[ny - 1, nx - 1], self.y[ny - 1, nx - 1], -km2m * self.depth[ny - 1, nx - 1]])\n\n        hw = p1 - p0\n        dx1 = np.linalg.norm(hw) / (ny - 1)\n        hw = hw / np.linalg.norm(hw)\n        hh = p2 - p0\n        dx2 = np.linalg.norm(hh) / (nx - 1)\n        hh = hh / np.linalg.norm(hh)\n        dx = np.sqrt(self.PSarea_cm2 * cm2m * cm2m)\n        # a kinematic model defines the fault quantities at the subfault center\n        # a netcdf file defines the quantities at the nodes\n        # therefore the dx/2\n        # the term dxi/np.sqrt(dx1*dx2) allows accounting for non-square patches\n        non_square_factor = dx / np.sqrt(dx1 * dx2)\n        t1 = -np.dot(p0, hh) + 0.5 * dx1 * non_square_factor\n        t2 = -np.dot(p0, hw) + 0.5 * dx2 * non_square_factor\n\n        template_yaml = f\"\"\"!Switch\n[strike_slip, dip_slip, rupture_onset, tau_S, tau_R, rupture_rise_time]: !EvalModel\n    parameters: [strike_slip, dip_slip, rupture_onset, effective_rise_time, acc_time]\n    model: !Switch\n        [strike_slip, dip_slip, rupture_onset, effective_rise_time, acc_time]: !AffineMap\n              matrix:\n                ua: [{hh[0]}, {hh[1]}, {hh[2]}]\n                ub: [{hw[0]}, {hw[1]}, {hw[2]}]\n              translation:\n                ua: {t1}\n                ub: {t2}\n              components: !Any\n                - !ASAGI\n                    file: {prefix}_{spatial_zoom}_o{spatial_order}.nc\n                    parameters: [strike_slip, dip_slip, rupture_onset, effective_rise_time, acc_time]\n                    var: data\n                    interpolation: linear\n                - !ConstantMap\n                  map:\n                    strike_slip: 0.0\n                    dip_slip:    0.0\n                    rupture_onset:    0.0\n                    acc_time:  1e100\n                    effective_rise_time:  2e100\n    components: !FunctionMap\n       map:\n          #Note the minus on strike_slip to acknowledge the different convention of SeisSol (T_s>0 means right-lateral)\n          strike_slip: return -strike_slip;\n          dip_slip: return dip_slip;\n          rupture_onset: return rupture_onset;\n          tau_S: return acc_time/1.27;\n          tau_R: return effective_rise_time - 2.*acc_time/1.27;\n          rupture_rise_time: return effective_rise_time;\n        \"\"\"\n        fname = f\"{prefix}_fault.yaml\"\n        with open(fname, \"w\") as fid:\n            fid.write(template_yaml)\n        print(f\"done writing {fname}\")\n\n        # Generate ts file containing mesh geometry\n        vertex = np.zeros((4, 3))\n        vertex[0, :] = p0 + 0.5 * (-hh * dx1 - hw * dx2) * non_square_factor\n        vertex[1, :] = p2 + 0.5 * (hh * dx1 - hw * dx2) * non_square_factor\n        vertex[2, :] = p3 + 0.5 * (hh * dx1 + hw * dx2) * non_square_factor\n        vertex[3, :] = p1 + 0.5 * (-hh * dx1 + hw * dx2) * non_square_factor\n\n        connect = np.zeros((2, 3), dtype=int)\n        connect[0, :] = [1, 2, 3]\n        connect[1, :] = [1, 3, 4]\n        fname = f\"{prefix}_fault.ts\"\n        with open(fname, \"w\") as fout:\n            fout.write(\"GOCAD TSURF 1\\nHEADER {\\nname:%s\\nborder: true\\nmesh: false\\n*border*bstone: true\\n}\\nTFACE\\n\" % (fname))\n            for ivx in range(1, 5):\n                fout.write(\"VRTX %s %s %s %s\\n\" % (ivx, vertex[ivx - 1, 0], vertex[ivx - 1, 1], vertex[ivx - 1, 2]))\n\n            for i in range(2):\n                fout.write(\"TRGL %d %d %d\\n\" % (connect[i, 0], connect[i, 1], connect[i, 2]))\n            fout.write(\"END\\n\")\n        print(f\"done writing {fname}\")\n", "meta": {"hexsha": "31710caf1e32b0e3e33de73198940aa941d010e6", "size": 29225, "ext": "py", "lang": "Python", "max_stars_repo_path": "preprocessing/science/kinematic_models/FaultPlane.py", "max_stars_repo_name": "AnikoWirp/SeisSol", "max_stars_repo_head_hexsha": "bc4b4625fb1be72ccd370a30aa6e3c3351e006ed", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 165, "max_stars_repo_stars_event_min_datetime": "2015-01-30T18:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:22:14.000Z", "max_issues_repo_path": "preprocessing/science/kinematic_models/FaultPlane.py", "max_issues_repo_name": "AnikoWirp/SeisSol", "max_issues_repo_head_hexsha": "bc4b4625fb1be72ccd370a30aa6e3c3351e006ed", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 351, "max_issues_repo_issues_event_min_datetime": "2015-10-06T15:06:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T11:23:13.000Z", "max_forks_repo_path": "preprocessing/science/kinematic_models/FaultPlane.py", "max_forks_repo_name": "AnikoWirp/SeisSol", "max_forks_repo_head_hexsha": "bc4b4625fb1be72ccd370a30aa6e3c3351e006ed", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 96, "max_forks_repo_forks_event_min_datetime": "2015-07-27T15:13:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T19:19:32.000Z", "avg_line_length": 45.3804347826, "max_line_length": 188, "alphanum_fraction": 0.5611291702, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 8320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096344, "lm_q2_score": 0.3040416623541848, "lm_q1q2_score": 0.15676994084550264}}
{"text": "import logging\nimport os\nfrom typing import Dict, List, Optional\n\nimport numpy as np\nimport scipy.fft as fp\nfrom scipy.ndimage import generic_gradient_magnitude, sobel\nfrom skimage.transform import resize\n\nimport nanotune as nt\n\nlogger = logging.getLogger(__name__)\nN_2D = nt.config[\"core\"][\"standard_shapes\"][\"2\"]\nNT_LABELS = list(dict(nt.config[\"core\"][\"labels\"]).keys())\n\n\ndef export_label(\n    ds_label: List[\"str\"],\n    quality: int,\n    category: str,\n) -> int:\n    \"\"\"Merges binary labels of single and double dot qualities to a single\n    label. Only if `dotregime` is specified, for all other the initial\n    quality labels are returned.\n    It translates a dot regime label to: 0 - poor singledot, 1 - good singledot,\n    2 - poor doubledot, 3 - good doubledot.\n\n    Returns:\n        int: new label.\n    \"\"\"\n    good = bool(quality)\n    if category == \"dotregime\":\n        singledot = True if \"singledot\" in ds_label else False\n        doubledot = True if \"doubledot\" in ds_label else False\n\n        if not good and singledot:\n            new_label = 0\n        if good and singledot:\n            new_label = 1\n        if not good and doubledot:\n            new_label = 2\n        if good and doubledot:\n            new_label = 3\n\n    elif category in [\"outerbarriers\", \"pinchoff\", \"singledot\", \"doubledot\"]:\n        if len(ds_label) == 1 and ds_label[0] == category:\n            new_label = good\n        else:\n            print(category)\n            print(ds_label)\n            logger.warning(\"Wrong label-category combination in export_label.\")\n            raise ValueError\n    else:\n        logger.error(\n            \"Do not know how to export/condense labels. Please \"\n            + \"update export_label in export_data.py.\"\n        )\n        raise ValueError\n\n    return new_label\n\n\ndef prep_data(\n    dataset: nt.Dataset,\n    category: str,\n    flip_data: bool = False,\n    readout_method_to_use: str = 'transport',\n) -> List[List[List[float]]]:\n    \"\"\"Prepares data for classification.\n    It combines normalized data, its gradient, Fourier frequencies and\n    extracted features into a multidimensional list.\n    All sublists are reshaped to a standard shape, defined in config.json\n    under the `standard_shapes` key.\n\n    Args:\n        dataset: instance of nanotune dataset whose data should be prepared.\n        category: as which category/type of data, e.g. `pinchoff`, `singledot`\n            etc, it should be treated.\n        flip_data: whether data should be flipped. Used to simulate pinchoff\n            curves measured in rf sensing.\n\n    Returns:\n        list: multidimensional list. First sublist is normalized data,\n            second Fourier frequencies, third gradient and fourth features.\n    \"\"\"\n    assert category in nt.config[\"core\"][\"features\"].keys()\n    if len(dataset.power_spectrum) == 0:\n        dataset.compute_power_spectrum()\n\n    condensed_data_all = []\n\n    # for readout_method in dataset.readout_methods.keys():\n    signal = dataset.data[readout_method_to_use].values\n    if flip_data:\n        signal = np.flip(signal)\n    dimension = dataset.dimensions[readout_method_to_use]\n\n    shape = tuple(nt.config[\"core\"][\"standard_shapes\"][str(dimension)])\n    condensed_data = np.empty(\n        (len(nt.config[\"core\"][\"data_types\"]), 1, np.prod(shape))\n    )\n\n    relevant_features = nt.config[\"core\"][\"features\"][category]\n    features = []\n\n    if dataset.features:\n        if all(isinstance(i, dict) for i in dataset.features.values()):\n            for feat in relevant_features:\n                features.append(dataset.features[readout_method_to_use][feat])\n        else:\n            for feat in relevant_features:\n                features.append(dataset.features[feat])\n\n    # double check if current range is correct:\n    if np.max(signal) > 1:\n        min_curr = np.min(signal)\n        max_curr = np.max(signal)\n        signal = (signal - min_curr) / (max_curr - min_curr)\n        # assume we are talking dots and high current was not actually\n        # device_max_signal\n        dataset.data[readout_method_to_use].values = signal * 0.3\n        dataset.compute_power_spectrum()\n\n    data_resized = resize(\n        signal, shape, anti_aliasing=True, mode=\"edge\"\n    ).flatten()\n\n    grad = generic_gradient_magnitude(signal, sobel)\n    gradient_resized = resize(\n        grad, shape, anti_aliasing=True, mode=\"constant\"\n    ).flatten()\n    power = dataset.power_spectrum[readout_method_to_use].values\n    frequencies_resized = resize(\n        power, shape, anti_aliasing=True, mode=\"constant\"\n    ).flatten()\n\n    pad_width = len(data_resized.flatten()) - len(features)\n    features = np.pad(\n        features,\n        (0, pad_width),\n        \"constant\",\n        constant_values=nt.config[\"core\"][\"fill_value\"],\n    )\n\n    index = nt.config[\"core\"][\"data_types\"][\"signal\"]\n    condensed_data[index, 0, :] = data_resized.tolist()\n\n    index = nt.config[\"core\"][\"data_types\"][\"frequencies\"]\n    condensed_data[index, 0, :] = frequencies_resized.tolist()\n\n    index = nt.config[\"core\"][\"data_types\"][\"gradient\"]\n    condensed_data[index, 0, :] = gradient_resized.tolist()\n\n    index = nt.config[\"core\"][\"data_types\"][\"features\"]\n    condensed_data[index, 0, :] = features\n\n    condensed_data_all.append(condensed_data.tolist())\n\n    return condensed_data_all\n\n\ndef export_data(\n    category: str,\n    db_names: List[str],\n    skip_ids: Optional[Dict[str, List[int]]] = None,\n    add_flipped_data: bool = False,\n    quality: Optional[int] = None,\n    filename: Optional[str] = None,\n    db_folder: Optional[str] = None,\n    readout_method_to_use: str = 'transport',\n) -> None:\n    \"\"\"Exports condensed data to a numpy file in a format used by\n    nanotune's Classifier.\n\n    The saved array contains the normalized signal, gradient, Fourier\n    frequencies and extracted features of each dataset. The machine learning\n    labels are attached to each of them to the very end.\n    A dataset of 15 1D measurements results in an array of (4, 15, 101),\n    where each trace has been reshaped to 100 points plus the label. The\n    first array[0, :, :] are all signals, array[1, :, :] the frequencies,\n    array is defined in config.json under `data_types`.\n\n    Args:\n        category: nt.config['core']['features'].keys()\n        db_names: names of databases whose data should be exported.\n        skip_ids: dict mapping database names to list of run IDs which should\n            be skipped.\n        add_flipped_data: whether or flipped data should be added as well.\n            a flipped pinchoff curve measured in transport for example\n            reproduces a pinchoff measured in rf.\n        quality: which qualities, e.g. only good or poor data, should be\n            exported. If none give, both will be taken.\n        filename: name of resulting numpy file. Default is the category name.\n        db_folder: folder where databases are located.\n        readout_method_to_use: which readout method to use if more than one\n            is available. Default is 'transport'.\n    \"\"\"\n    assert isinstance(db_names, list)\n    if category not in list(nt.config['core']['features'].keys()):\n        raise ValueError(\n            f\"Unknown category. Please use on of the following: \\\n            {list(nt.config['core']['features'].keys())}.\"\n        )\n\n    if db_folder is None:\n        db_folder = nt.config[\"db_folder\"]\n\n    if category in [\"pinchoff\", \"coulomboscillation\", \"zerobiaspeak1D\"]:\n        dim = 1\n    else:\n        dim = 2\n\n    if category == 'dotregime':\n        stages = [\"singledot\", \"doubledot\"]\n    else:\n        stages = [category]\n\n    shape = tuple(nt.config[\"core\"][\"standard_shapes\"][str(dim)])\n    condensed_data_all = np.empty(\n        (len(nt.config[\"core\"][\"data_types\"]), 0, np.prod(shape))\n    )\n\n    relevant_ids: Dict[str, List[int]] = {}\n    for db_name in db_names:\n        relevant_ids[db_name] = []\n        nt.set_database(db_name, db_folder)\n        for stage in stages:\n            try:\n                relevant_ids[db_name] += nt.get_dataIDs(\n                    db_name, stage, quality=quality, db_folder=db_folder,\n                    get_run_ids=False,\n                )\n                if len(relevant_ids[db_name]) == 0:\n                    logger.warning(f'No labelled data found in {db_name}')\n            except Exception as e:\n                msg = f\"Unable to load relevant ids in {db_name}.\" + str(e)\n                logger.error(msg)\n                break\n\n    labels_exp = []\n    for db_name, dataids in relevant_ids.items():\n        nt.set_database(db_name, db_folder)\n        skip_us = []\n        if skip_ids is not None:\n            try:\n                skip_us = skip_ids[db_name]\n            except KeyError:\n                logger.warning(\"No data IDs to skip in {}.\".format(db_name))\n\n        for d_id in dataids:\n            if d_id not in skip_us:\n                try:\n                    df = nt.Dataset(d_id, db_name, db_folder=db_folder)\n                    condensed_data = prep_data(\n                        df,\n                        category,\n                        readout_method_to_use=readout_method_to_use)\n                    new_label = export_label(df.ml_label, df.quality, category)\n                    condensed_data_all = np.append(\n                        condensed_data_all, condensed_data[0], axis=1\n                    )\n                    labels_exp.append(new_label)\n\n                    if add_flipped_data:\n                        condensed_data = prep_data(\n                            df, category, flip_data=True,\n                            readout_method_to_use=readout_method_to_use\n                        )\n                        new_label = export_label(\n                            df.ml_label, df.quality, category\n                        )\n                        condensed_data_all = np.append(\n                            condensed_data_all, condensed_data[0], axis=1\n                        )\n                        labels_exp.append(new_label)\n                except (IndexError, ValueError, TypeError) as i_err:\n                    print(db_name)\n                    print(d_id)\n                    print(i_err)\n\n    n = list(condensed_data_all.shape)\n    n[-1] += 1\n\n    data_w_labels = np.zeros(n)\n    data_w_labels[:, :, -1] = labels_exp\n    data_w_labels[:, :, :-1] = condensed_data_all\n\n    if filename is None:\n        filename = \"_\".join(stages)\n    path = os.path.join(db_folder, filename)\n    np.save(path, data_w_labels)\n\n\ndef correct_normalizations(\n    filename: str,\n    db_folder: Optional[str] = None,\n) -> None:\n    \"\"\"\"\"\"\n    if db_folder is None:\n        db_folder = nt.config[\"db_folder\"]\n\n    path = os.path.join(db_folder, filename)\n\n    all_data = np.load(path)\n\n    data = all_data[:, :, :-1]\n    labels = all_data[:, :, -1]\n\n    sg_indx = nt.config[\"core\"][\"data_types\"][\"signal\"]\n\n    images = np.copy(data[sg_indx])\n    images = images.reshape(images.shape[0], -1)\n\n    high_current_images = np.max(images, axis=1)\n    high_current_ids = np.where(high_current_images > 1)[0]\n\n    # print(len(high_current_ids))\n\n    for exid in high_current_ids:\n        # print(np.max(data[sg_indx, exid]))\n        sig = data[sg_indx, exid]\n        sig = (sig - np.min(sig)) / (np.max(sig) - np.min(sig))\n        sig = sig * 0.3  # assume it's dots and highest current is not max current\n        data[sg_indx, exid] = sig\n\n        freq_spect = fp.fft2(sig.reshape(50, 50))\n        freq_spect = np.abs(fp.fftshift(freq_spect))\n\n        grad = generic_gradient_magnitude(sig.reshape(50, 50), sobel)\n\n        index = nt.config[\"core\"][\"data_types\"][\"frequencies\"]\n        data[index, exid, :] = freq_spect.flatten()\n\n        index = nt.config[\"core\"][\"data_types\"][\"gradient\"]\n        data[index, exid, :] = grad.flatten()\n\n    n = list(data.shape)\n    n[-1] += 1\n\n    data_w_labels = np.zeros(n)\n    data_w_labels[:, :, -1] = labels\n    data_w_labels[:, :, :-1] = data\n\n    path = os.path.join(db_folder, filename)\n    np.save(path, data_w_labels)\n", "meta": {"hexsha": "83f2cd8d516c2b40948fbd825811bc601382bcfd", "size": 12005, "ext": "py", "lang": "Python", "max_stars_repo_path": "nanotune/data/export_data.py", "max_stars_repo_name": "microsoft/nanotune", "max_stars_repo_head_hexsha": "68be8f5b74a52d57b74ccac228e120d9ab48e3e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-02-24T14:32:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T16:37:26.000Z", "max_issues_repo_path": "nanotune/data/export_data.py", "max_issues_repo_name": "microsoft/nanotune", "max_issues_repo_head_hexsha": "68be8f5b74a52d57b74ccac228e120d9ab48e3e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 149, "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:44:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T06:09:07.000Z", "max_forks_repo_path": "nanotune/data/export_data.py", "max_forks_repo_name": "LaudateCorpus1/nanotune", "max_forks_repo_head_hexsha": "0ada354597b16f6dbb17ca7be01ab7668b6d5049", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2021-03-29T13:36:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T23:06:35.000Z", "avg_line_length": 34.6965317919, "max_line_length": 82, "alphanum_fraction": 0.6092461474, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 2749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.304041668660366, "lm_q1q2_score": 0.15676993957094298}}
{"text": "\"\"\"This module provides EIGENVAL.\"\"\"\n\nfrom __future__ import division, print_function\n\nimport csv\nimport sys\nfrom pathlib import Path\nfrom logging import DEBUG, INFO, Formatter, StreamHandler, getLogger\n\nimport numpy as np\nfrom typing import Dict, Optional, Sequence, Tuple, List, IO, Union\nfrom vaspy.tools import open_by_suffix\n\ntry:\n    import matplotlib.pyplot as plt\nexcept ImportError:\n    sys.stderr.write(\"Install matplotlib, or you cannot use methods relating to draw\\n\")\n\n# logger\nLOGLEVEL = INFO\nlogger = getLogger(__name__)\nfmt = \"%(asctime)s %(levelname)s %(name)s :%(message)s\"\nformatter = Formatter(fmt)\nhandler = StreamHandler()\nhandler.setLevel(LOGLEVEL)\nlogger.setLevel(LOGLEVEL)\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)\nlogger.propagate = False\n\n\nclass EnergyBand(object):\n    \"\"\"Simple band structure object for analyzing by using ipython.\n\n    Class for band structure\n\n    Attributes\n    ----------\n    kvecs: numpy.ndarray\n        kvectors\n    kdistances: numpy.ndarray\n        kdisance\n    numk: int\n        number of kpoints\n    nbands: int\n        number of bands\n    nsping: int\n        spin character\n    energies: numpy.ndarray\n        energies[spin_i, k_i, band_i], where spin_i, k_i, and band_i are spin-,\n        k- and band-index, respectively.\n    label: dict\n        used as a label (data 'title' such as '#k', 'Energy') in str format\n\n\n    Parameters\n    ----------\n    kvecs: numpy.ndarray\n            1D array data of k-vectors.\n    energies: numpy.ndarray\n            1D array data of energies\n    nspin: int\n            number of spin: '1' means No-spin.  '2' means collinear spin,\n            '4' means noncollinear spin.\n            In this class does not distinguish non-collinear spin\n            and No-spin.  (default is 1)\n\n    \"\"\"\n\n    def __init__(\n        self,\n        kvecs: Sequence[float] = (),\n        energies: Sequence[float] = (),\n        nspin: int = 1,\n    ) -> None:\n        \"\"\"Initialize.\"\"\"\n        self.kvecs: np.ndarray = np.array(kvecs)\n        self.numk: int = len(self.kvecs)\n        self.label: Dict[\"str\", List[\"str\"]] = {}\n        try:\n            self.nbands: int = len(energies) // len(kvecs)\n        except ZeroDivisionError:\n            self.nbands = 0\n        self.energies: np.ndarray = np.array(energies)\n        self.nspin = nspin\n        if self.nspin == 1:  # standard\n            self.label[\"spin\"] = [\"\"]\n            self.label[\"energy\"] = [\"Energy\"]\n        elif self.nspin == 2:  # spin-polarized\n            self.label[\"energy\"] = [\"Energy_up\", \"Energy_down\"]\n            self.label[\"spin\"] = [\"_up\", \"_down\"]\n        elif self.nspin == 4:  # non-collinear\n            self.label[\"energy\"] = [\"Energy\"]\n            self.label[\"spin\"] = [\"_mT\", \"_mX\", \"_mY\", \"_mZ\"]\n        self.label[\"k\"] = [\"#k\"]\n\n    @property\n    def kdistances(self) -> np.ndarray:\n        \"\"\"Return kdistances.\"\"\"\n        return np.cumsum(\n            np.linalg.norm(\n                np.concatenate((np.array([[0, 0, 0]]), np.diff(self.kvecs, axis=0))),\n                axis=1,\n            )\n        )\n\n    def fermi_correction(self, fermi: float) -> None:\n        \"\"\"Correct the Fermi level.\n\n        Parameters\n        ----------\n        fermi: float\n            value of the Fermi level.\n\n        \"\"\"\n        self.energies -= fermi\n\n    def make_label(self, *keys: str) -> List[str]:\n        \"\"\"Return array the used for label for CSV-like data.\n\n        Parameters\n        ----------\n        keys: tuple\n            key tuple used for label\ns\n        \"\"\"\n        label_list = []\n        for key in keys:\n            for tmp in self.label[key]:\n                label_list.append(tmp)\n        return label_list\n\n    def to_3dlist(self) -> List[List[List[float]]]:\n        \"\"\"Return 3D mentional list.\n\n        list[band_i, [k_i, energy, (energy_down)]]\n\n        This list format would be useful for str output\n\n        \"\"\"\n        bandstructure = []\n        for energies in self.energies.T.tolist():\n            band = []\n            for k, energy in zip(self.kdistances[:, np.newaxis].tolist(), energies):\n                k.extend(energy)\n                band.append(k)\n            bandstructure.append(band)\n        return bandstructure\n\n    def to_csv(self, csv_file: str, blankline: bool = True) -> None:\n        \"\"\"Write data to csv file.\n\n        Parameters\n        ------------\n        csv_file: str\n            filename for output\n        label_str: str\n            string for label (put it on the first line)\n        blankline: boolean\n            It True (default), the blank line is inserted between band data\n\n        \"\"\"\n        label_str: str = \"\\t\".join(self.make_label(\"k\", \"energy\")) + \"\\n\"\n        with open(csv_file, \"w\") as fhandle:\n            fhandle.writelines(label_str)\n            writer = csv.writer(fhandle, delimiter=\"\\t\")\n            for band_i in self.to_3dlist():\n                writer.writerows(band_i)\n                if blankline:\n                    fhandle.writelines(\"\\n\")\n\n    def __str__(self) -> str:\n        \"\"\"Return the str object.\n\n        Returns\n        --------\n        str\n            a string represntation of EnergyBand.\n            **Useful for gnuplot and Igor**.\n\n        \"\"\"\n        labels = self.make_label(\"k\", \"energy\")\n        output = labels[0]\n        for label in labels[1:]:\n            output += \"\\t\" + label\n        output += \"\\n\"\n        list3d = self.to_3dlist()\n        for band_i in list3d:\n            for line in band_i:\n                output += \"{0:.8e}\".format(line[0])\n                for energy in line[1:]:\n                    output += \"\\t{0:.8e}\".format(energy)\n                output += \"\\n\"\n            output += \"\\n\"\n        return output\n\n    def figure(self, color: str = \"blue\", spin_i: int = 0) -> plt.Axes:\n        \"\"\"Return Axes object of the energy band.\n\n        Parameters\n        -----------\n        color: str, optional (default is 'blue')\n            color of the band line\n\n        spin_i: spin_index\n            default is 0\n\n        Returns\n        ---------\n        matplotlib.pyplot.Axes\n\n        Example\n        --------\n        Here is a typical code::\n\n            fig = plt.figure()\n            ax = band.figure(color='blue')\n            ax.set_ylabel('Energy  ( eV )')\n            ax.set_ylim(-5, 5)\n            ax.set_xlim(0, 4)\n            plt.show()\n\n        \"\"\"\n        [\n            plt.plot(self.kdistances, self.energies[spin_i, :, band_i], color=color)\n            for band_i in range(self.energies.shape[2])\n        ]\n        return plt.gca()\n\n    def show(\n        self, yrange: Optional[Tuple[float, float]] = None, spin_i: int = 0\n    ) -> None:  # How to set default value?\n        \"\"\"Draw band structure by using maptlotlib.\n\n        For 'just seeing' use.\n\n        Parameters\n        ----------\n        yrange: tuple, optional  (default: all range)\n            Minimum and maximum value of the y-axis.\n            If not specified, use the matplotlib default value.\n\n        spin_i: int  (default is 0 for no spin or 'up' spin)\n            Spin index. For spin-polarized collinear band\n\n        \"\"\"\n        for band_i in range(self.energies.shape[2]):\n            plt.plot(self.kdistances, self.energies[spin_i, :, band_i], color=\"blue\")\n        if yrange is not None:\n            plt.ylim([yrange[0], yrange[1]])\n        plt.xlim([self.kdistances[0], self.kdistances[-1]])\n        plt.ylabel(self.label[\"energy\"][spin_i] + \" (eV)\")\n        plt.show()\n\n    def to_physical_kvector(\n        self,\n        recvec: np.ndarray = np.array(\n            ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)),\n        ),\n    ) -> None:\n        \"\"\"Change kvec unit to inverse AA.\n\n        Parameters\n        -----------\n        recvec: array, numpy.ndarray, optional (default is the unit vector)\n            reciprocal vector\n\n        Notes\n        -----\n            Don't forget that the reciprocal vector used\n            in VASP needs 2PI to match  the conventional\n            unit of the wavevector.\n\n        \"\"\"\n        logger.debug(\"recvec: {}\".format(recvec))\n        logger.debug(\"self.kvecs: {}\".format(self.kvecs))\n        recvec = np.array(recvec)\n        self.kvecs = np.array([recvec.dot(kvecs) for kvecs in self.kvecs])\n\n\nclass EIGENVAL(EnergyBand):\n    \"\"\"Class for storing the data of EIGENVAL file.\n\n    Parameters\n    -----------\n    filename: str, Path\n        File name of 'EIGENVAL'\n\n    Attributes\n    ----------\n    natom: int\n        Number of atoms\n\n    \"\"\"\n\n    def __init__(self, filename: Union[str, Path, None] = None) -> None:\n        \"\"\"Initialize.\"\"\"\n        super(EIGENVAL, self).__init__()\n        self.natom = 0\n        #\n        if filename:\n            self.load_file(open_by_suffix(str(filename)))\n\n    def __getitem__(self, item: int) -> Tuple[List[float], List[List[float]]]:\n        \"\"\"\n        \n        Parameters\n        ----------\n        item: int\n            index of k-vector\n        \n        Returns\n        -------\n        Tuple of list of float and list of float  \n        \"\"\"\n        energies: List[List[List[float]]] = self.energies.transpose(1, 2, 0).tolist()\n        kvec: List[List[float]] = self.kvecs.tolist()\n        return list(zip(kvec, energies))[item]\n\n    def __len__(self) -> int:\n        \"\"\"Return numk as the result of len()\"\"\"\n        return self.numk\n\n    def load_file(self, thefile: IO[str]) -> None:\n        \"\"\"Parse EIGENVAL.\"\"\"\n        self.natom, _, _, self.nspin = [int(i) for i in next(thefile).split()]\n        if self.nspin == 2:\n            self.label[\"energy\"] = [\"Energy_up\", \"Energy_down\"]\n        else:\n            self.label[\"energy\"] = [\"Energy\"]\n        next(thefile)\n        next(thefile)\n        next(thefile)\n        next(thefile)\n        _, self.numk, self.nbands = [int(i) for i in next(thefile).split()]\n        self.kvecs = []\n        self.energies = []\n        for _ in range(self.numk):\n            # the first line in the sigleset begins with the blank\n            next(thefile)\n            self.kvecs.append([float(i) for i in next(thefile).split()[0:3]])\n            for _ in range(self.nbands):\n                self.energies.append(\n                    [float(i) for i in next(thefile).split()[1 : self.nspin + 1]]\n                )\n        self.kvecs = np.array(self.kvecs)\n        self.energies = np.array(self.energies).T.reshape(\n            self.nspin, self.numk, self.nbands\n        )\n        thefile.close()\n", "meta": {"hexsha": "281699015f27285cfae3d08e0f3fa877689fa64f", "size": 10402, "ext": "py", "lang": "Python", "max_stars_repo_path": "vaspy/eigenval.py", "max_stars_repo_name": "arafune/vaspy", "max_stars_repo_head_hexsha": "36342eb9b2523fc5c878db5e269e77a51352364c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2018-01-15T10:41:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T05:53:50.000Z", "max_issues_repo_path": "vaspy/eigenval.py", "max_issues_repo_name": "arafune/vaspy", "max_issues_repo_head_hexsha": "36342eb9b2523fc5c878db5e269e77a51352364c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vaspy/eigenval.py", "max_forks_repo_name": "arafune/vaspy", "max_forks_repo_head_hexsha": "36342eb9b2523fc5c878db5e269e77a51352364c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-08-13T16:34:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T15:39:37.000Z", "avg_line_length": 29.6353276353, "max_line_length": 88, "alphanum_fraction": 0.5382618727, "include": true, "reason": "import numpy", "num_tokens": 2559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.28457601028405616, "lm_q1q2_score": 0.15668964731703364}}
{"text": "import os\nimport numpy as np\nimport pandas as pd\nfrom .chebyshevUtils import chebeval\n\n__all__ = ['ChebyValues']\n\n\nclass ChebyValues(object):\n    \"\"\"Calculates positions, velocities, deltas, vmags and elongations,\n    given a series of coefficients generated by ChebyFits.\n    \"\"\"\n    def __init__(self):\n        self.coeffs = {}\n        self.coeffKeys = ['objId', 'tStart', 'tEnd', 'ra', 'dec', 'geo_dist', 'vmag', 'elongation']\n        self.ephemerisKeys = ['ra', 'dradt', 'dec', 'ddecdt', 'geo_dist', 'vmag', 'elongation']\n\n    def setCoefficients(self, chebyFits):\n        \"\"\"Set coefficients using a ChebyFits object.\n        (which contains a dictionary of objId, tStart, tEnd, ra, dec, delta, vmag, and elongation lists).\n\n        Parameters\n        ----------\n        chebyFits : chebyFits\n            ChebyFits object, with attribute 'coeffs' - a dictionary of lists of coefficients.\n        \"\"\"\n        self.coeffs = chebyFits.coeffs\n        # Convert list of coefficients into numpy arrays.\n        for k in self.coeffs:\n            self.coeffs[k] = np.array(self.coeffs[k])\n        # Check that expected values were received.\n        missing_keys = set(self.coeffKeys) - set(self.coeffs)\n        if len(missing_keys) > 0:\n            raise ValueError(\"Expected to find key(s) %s in coefficients.\" %  ' '.join(list[missing_keys]))\n        self.coeffs['meanRA'] = self.coeffs['ra'].swapaxes(0, 1)[0]\n        self.coeffs['meanDec'] = self.coeffs['dec'].swapaxes(0, 1)[0]\n\n    def readCoefficients(self, chebyFitsFile):\n        \"\"\"Read coefficients from output file written by ChebyFits.\n\n        Parameters\n        ----------\n        chebyFitsFile : str\n            The filename of the coefficients file.\n        \"\"\"\n        if not os.path.isfile(chebyFitsFile):\n            raise IOError('Could not find chebyFitsFile at %s' % (chebyFitsFile))\n        # Read the coefficients file.\n        coeffs = pd.read_table(chebyFitsFile, delim_whitespace=True)\n        # The header line provides information on the number of coefficients for each parameter.\n        datacols = coeffs.columns.values\n        cols = {}\n        coeff_cols = ['ra', 'dec', 'geo_dist', 'vmag', 'elongation']\n        for k in coeff_cols:\n            cols[k] = [x for x in datacols if x.startswith(k)]\n        # Translate dataframe to dictionary of numpy arrays\n        # while consolidating RA/Dec/Delta/Vmag/Elongation coeffs.\n        self.coeffs['objId'] = coeffs.objId.values\n        self.coeffs['tStart'] = coeffs.tStart.values\n        self.coeffs['tEnd'] = coeffs.tEnd.values\n        for k in coeff_cols:\n            self.coeffs[k] = np.empty([len(cols[k]), len(coeffs)], float)\n            for i in range(len(cols[k])):\n                self.coeffs[k][i] = coeffs['%s_%d' % (k, i)].values\n        # Add the mean RA and Dec columns (before swapping the coefficients axes).\n        self.coeffs['meanRA'] = self.coeffs['ra'][0]\n        self.coeffs['meanDec'] = self.coeffs['dec'][0]\n        # Swap the coefficient axes so that they are [segment, coeff].\n        for k in coeff_cols:\n            self.coeffs[k] = self.coeffs[k].swapaxes(0, 1)\n\n    def _evalSegment(self, segmentIdx, times, subsetSegments=None, mask=True):\n        \"\"\"Evaluate the ra/dec/delta/vmag/elongation values for a given segment at a series of times.\n\n        Parameters\n        ----------\n        segmentIdx : int\n            The index in (each of) self.coeffs for the segment.\n            e.g. the first segment, for each object.\n        times : np.ndarray\n            The times at which to evaluate the segment.\n        subsetSegments : numpy.ndarray, optional\n            Optionally specify a subset of the total segment indexes.\n            This lets you pick out particular objIds.\n        mask : bool, optional\n            If True, returns NaNs for values outside the range of times in the segment.\n            If False, extrapolates segment for times outside the segment time range.\n\n        Returns\n        -------\n        dict\n           Dictionary of RA, Dec, delta, vmag, and elongation values for the segment indicated,\n           at the time indicated.\n        \"\"\"\n        if subsetSegments is None:\n            subsetSegments = np.ones(len(self.coeffs['objId']), dtype=bool)\n        tStart = self.coeffs['tStart'][subsetSegments][segmentIdx]\n        tEnd = self.coeffs['tEnd'][subsetSegments][segmentIdx]\n        tScaled = times - tStart\n        tInterval = np.array([tStart, tEnd]) - tStart\n        # Evaluate RA/Dec/Delta/Vmag/elongation.\n        ephemeris = {}\n        ephemeris['ra'], ephemeris['dradt'] = chebeval(tScaled,\n                                                       self.coeffs['ra'][subsetSegments][segmentIdx],\n                                                       interval=tInterval, doVelocity=True, mask=mask)\n        ephemeris['dec'], ephemeris['ddecdt'] = chebeval(tScaled,\n                                                         self.coeffs['dec'][subsetSegments][segmentIdx],\n                                                         interval=tInterval, doVelocity=True, mask=mask)\n        ephemeris['dradt'] = ephemeris['dradt'] * np.cos(np.radians(ephemeris['dec']))\n        for k in ('geo_dist', 'vmag', 'elongation'):\n            ephemeris[k], _ = chebeval(tScaled, self.coeffs[k][subsetSegments][segmentIdx],\n                                       interval=tInterval, doVelocity=False, mask=mask)\n        return ephemeris\n\n    def getEphemerides(self, times, objIds=None, extrapolate=False):\n        \"\"\"Find the ephemeris information for 'objIds' at 'time'.\n\n        Implicit in how this is currently written is that the segments are all expected to cover the\n        same start/end time range across all objects.\n        They do not have to have the same segment length for all objects.\n\n        Parameters\n        ----------\n        times : float or np.ndarray\n            The time to calculate ephemeris positions.\n        objIds : numpy.ndarray, optional\n            The object ids for which to generate ephemerides. If None, then just uses all objects.\n        extrapolate : bool\n            If True, extrapolate beyond ends of segments if time outside of segment range.\n            If False, return ValueError if time is beyond range of segments.\n\n        Returns\n        -------\n        numpy.ndarray\n            The ephemeris positions for all objects.\n            Note that these may not be sorted in the same order as objIds.\n        \"\"\"\n        if isinstance(times, float) or isinstance(times, int):\n            times = np.array([times], float)\n        ntimes = len(times)\n        ephemerides = {}\n        # Find subset of segments which match objId, if specified.\n        if objIds is None:\n            objMatch = np.ones(len(self.coeffs['objId']), dtype=bool)\n            ephemerides['objId'] = np.unique(self.coeffs['objId'])\n        else:\n            if isinstance(objIds, str) or isinstance(objIds, int):\n                objIds = np.array([objIds])\n            objMatch = np.in1d(self.coeffs['objId'], objIds)\n            ephemerides['objId'] = objIds\n        # Now find ephemeris values.\n        ephemerides['time'] = np.zeros((len(ephemerides['objId']), ntimes), float) + times\n        for k in self.ephemerisKeys:\n            ephemerides[k] = np.zeros((len(ephemerides['objId']), ntimes), float)\n        for it, t in enumerate(times):\n            # Find subset of segments which contain the appropriate time.\n            # Look for simplest subset first.\n            segments = np.where((self.coeffs['tStart'][objMatch] <= t) &\n                                (self.coeffs['tEnd'][objMatch] > t))[0]\n            if len(segments) == 0:\n                segStart = self.coeffs['tStart'][objMatch].min()\n                segEnd = self.coeffs['tEnd'][objMatch].max()\n                if (segStart > t or segEnd < t):\n                    if not extrapolate:\n                        for k in self.ephemerisKeys:\n                            ephemerides[k][:,it] = np.nan\n                    else:\n                        # Find the segments to use to extrapolate the times.\n                        if segStart > t:\n                            segments = np.where(self.coeffs['tStart'][objMatch] == segStart)[0]\n                        if segEnd < t:\n                            segments = np.where(self.coeffs['tEnd'][objMatch] == segEnd)[0]\n                elif segEnd == t:\n                    # Not extrapolating, but outside the simple match case above.\n                    segments = np.where(self.coeffs['tEnd'][objMatch] == segEnd)[0]\n            for i, segmentIdx in enumerate(segments):\n                ephemeris = self._evalSegment(segmentIdx, t, objMatch, mask=False)\n                for k in self.ephemerisKeys:\n                    ephemerides[k][i][it] = ephemeris[k]\n                ephemerides['objId'][i] = self.coeffs['objId'][objMatch][segmentIdx]\n        if objIds is not None:\n            if set(ephemerides['objId']) != set(objIds):\n                raise ValueError('Did not find expected match between objIds provided and ephemeride objIds.')\n        return ephemerides\n", "meta": {"hexsha": "75349f811489b08f335a0f58503a1a44fd119ce3", "size": 9100, "ext": "py", "lang": "Python", "max_stars_repo_path": "rubin_sim/movingObjects/chebyValues.py", "max_stars_repo_name": "RileyWClarke/flarubin", "max_stars_repo_head_hexsha": "eb7b1ee21c828523f8a5374fe4510fe6e5ec2a2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rubin_sim/movingObjects/chebyValues.py", "max_issues_repo_name": "RileyWClarke/flarubin", "max_issues_repo_head_hexsha": "eb7b1ee21c828523f8a5374fe4510fe6e5ec2a2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rubin_sim/movingObjects/chebyValues.py", "max_forks_repo_name": "RileyWClarke/flarubin", "max_forks_repo_head_hexsha": "eb7b1ee21c828523f8a5374fe4510fe6e5ec2a2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.1891891892, "max_line_length": 110, "alphanum_fraction": 0.5813186813, "include": true, "reason": "import numpy", "num_tokens": 2151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.2845759920814681, "lm_q1q2_score": 0.15668963729455457}}
{"text": "import numpy as np\nimport re\nfrom pymatgen.analysis.local_env import VoronoiNN\nfrom pymatgen.core.structure import Structure\nimport math\nimport os\nimport csv\nimport argparse\nimport sys\nimport time\n\nparser = argparse.ArgumentParser(description='Orbital Field Matrix')\nparser.add_argument('root', help='path to the directory of CIF files.')\nparser.add_argument('--partial_csv', type=str, default=None, help='the path to the csv file with specified atoms')\nargs = parser.parse_args(sys.argv[1:])\n\ncif_path = args.root\npartial_csv = args.partial_csv\n\nstart_all = time.time()\n# ----------------------------- Pre-defined dictionary -------------------------------------------\n\nelements = {'H': ['1s2'], 'Li': ['[He] 1s2'], 'Be': ['[He] 2s2'], 'B': ['[He] 2s2 2p1'], 'N': ['[He] 2s2 2p3'],\n            'O': ['[He] 2s2 2p4'],\n            'C': ['[He] 2s2 2p2'], 'I': ['[Kr] 4d10 5s2 5p5'],\n            'F': ['[He] 2s2 2p5'], 'Na': ['[Ne] 3s1'], 'Mg': ['[Ne] 3s2'], 'Al': ['[Ne] 3s2 3p1'],\n            'Si': ['[Ne] 3s2 3p2'],\n            'P': ['[Ne] 3s2 3p3'], 'S': ['[Ne] 3s2 3p4'], 'Cl': ['[Ne] 3s2 3p5'], 'K': ['[Ar] 4s1'],\n            'Ca': ['[Ar] 4s2'], 'Sc': ['[Ar] 3d1 4s2'],\n            'Ti': ['[Ar] 3d2 4s2'], 'V': ['[Ar] 3d3 4s2'], 'Cr': ['[Ar] 3d5 4s1'], 'Mn': ['[Ar] 3d5 4s2'],\n            'Fe': ['[Ar] 3d6 4s2'], 'Co': ['[Ar] 3d7 4s2'], 'Ni': ['[Ar] 3d8 4s2'], 'Cu': ['[Ar] 3d10 4s1'],\n            'Zn': ['[Ar] 3d10 4s2'],\n            'Ga': ['[Ar] 3d10 4s2 4p2'], 'Ge': ['[Ar] 3d10 4s2 4p2'], 'As': ['[Ar] 3d10 4s2 4p3'],\n            'Se': ['[Ar] 3d10 4s2 4p4'], 'Br': ['[Ar] 3d10 4s2 4p5'], 'Rb': ['[Kr] 5s1'],\n            'Sr': ['[Kr] 5s2'], 'Y': ['[Kr] 4d1 5s2'], 'Zr': ['[Kr] 4d2 5s2'], 'Nb': ['[Kr] 4d4 5s1'],\n            'Mo': ['[Kr] 4d5 5s1'],\n            'Ru': ['[Kr] 4d7 5s1'], 'Rh': ['[Kr] 4d8 5s1'], 'Pd': ['[Kr] 4d10'], 'Ag': ['[Kr] 4d10 5s1'],\n            'Cd': ['[Kr] 4d10 5s2'],\n            'In': ['[Kr] 4d10 5s2 5p1'], 'Sn': ['[Kr] 4d10 5s2 5p2'], 'Sb': ['[Kr] 4d10 5s2 5p3'],\n            'Te': ['[Kr] 4d10 5s2 5p4'], 'Cs': ['[Xe] 6s1'], 'Ba': ['[Xe] 6s2'],\n            'La': ['[Xe] 5d1 6s2'], 'Ce': ['[Xe] 4f1 5d1 6s2'], 'Hf': ['[Xe] 4f14 5d2 6s2'],\n            'Ta': ['[Xe] 4f14 5d3 6s2'],\n            'W': ['[Xe] 4f14 5d5 6s1'], 'Re': ['[Xe] 4f14 5d5 6s2'], 'Os': ['[Xe] 4f14 5d6 6s2'],\n            'Ir': ['[Xe] 4f14 5d7 6s2'], 'Pt': ['[Xe] 4f14 5d10'], 'Au': ['[Xe] 4f14 5d10 6s1'],\n            'Hg': ['[Xe] 4f14 5d10 6s2'],\n            'Tl': ['[Xe] 4f14 5d10 6s2 6p2'], 'Pb': ['[Xe] 4f14 5d10 6s2 6p2'],\n            'Bi': ['[Xe] 4f14 5d10 6s2 6p3'],\n            'Tc': ['[Kr] 4d5 5s2'], 'Fr': ['[Rn]7s1'], 'Ra': ['[Rn]7s2'], 'Pr': ['[Xe]4f3 6s2'],\n            'Nd': ['[Xe] 4f4 6s2'], 'Pm': ['[Xe] 4f5 6s2'], 'Sm': ['[Xe] 4f6 6s2'],\n            'Eu': ['[Xe] 4f7 6s2'], 'Gd': ['[Xe] 4f7 5d1 6s2'], 'Tb': ['[Xe] 4f9 6s2'],\n            'Dy': ['[Xe] 4f10 6s2'], 'Ho': ['[Xe] 4f11 6s2'], 'Er': ['[Xe] 4f12 6s2'],\n            'Tm': ['[Xe] 4f13 6s2'], 'Yb': ['[Xe] 4f14 6s2'], 'Lu': ['[Xe] 4f14 5d1 6s2'],\n            'Po': ['[Xe] 4f14 5d10 6s2 6p4'], 'At': ['[Xe] 4f14 5d10 6s2 6p5'],\n            'Ac': ['[Rn] 6d1 7s2'], 'Th': ['[Rn] 6d2 7s2'], 'Pa': ['[Rn] 5f2 6d1 7s2'],\n            'U': ['[Rn] 5f3 6d1 7s2'], 'Np': ['[Rn] 5f4 6d1 7s2'], 'Pu': ['[Rn] 5f6 7s2'],\n            'Am': ['[Rn] 5f7 7s2'], 'Cm': ['[Rn] 5f7 6d1 7s2'], 'Bk': ['[Rn] 5f9 7s2'],\n            'Cf': ['[Rn] 5f10 7s2'], 'Es': ['[Rn] 5f11 7s2'], 'Fm': ['[Rn] 5f12 7s2'],\n            'Md': ['[Rn] 5f13 7s2'], 'No': ['[Rn] 5f14 7s2'], 'Lr': ['[Rn] 5f14 6d1 7s2'],\n            'Rf': ['[Rn] 5f14 6d2 7s2'], 'Db': ['[Rn] 5f14 6d3 7s2'],\n            'Sg': ['[Rn] 5f14 6d4 7s2'], 'Bh': ['[Rn] 5f14 6d5 7s2'],\n            'Hs': ['[Rn] 5f14 6d6 7s2'], 'Mt': ['[Rn] 5f14 6d7 7s2'], 'Xe': ['[Kr] 4d10 5s2 5p6'],\n            'He': ['1s2'], 'Kr': ['[Ar] 3d10 4s2 4p6'], 'Ar': ['[Ne] 3s2 3p6'], 'Ne': ['[He] 2s2 2p6']}\n\norbitals = {\"s1\": 0, \"s2\": 1, \"p1\": 2, \"p2\": 3, \"p3\": 4, \"p4\": 5, \"p5\": 6, \"p6\": 7, \"d1\": 8, \"d2\": 9, \"d3\": 10,\n            \"d4\": 11,\n            \"d5\": 12, \"d6\": 13, \"d7\": 14, \"d8\": 15, \"d9\": 16, \"d10\": 17, \"f1\": 18, \"f2\": 19, \"f3\": 20, \"f4\": 21,\n            \"f5\": 22, \"f6\": 23, \"f7\": 24, \"f8\": 25, \"f9\": 26, \"f10\": 27, \"f11\": 28, \"f12\": 29, \"f13\": 30,\n            \"f14\": 31}\n\n# ------------------------- hvs ----------------------------------------------------\n# hvs define a dictionary , which map a element to a 32 vector representation\n# according to its electronic configurations\n\nhvs = {}\n\nfor key in elements.keys():\n    element = key\n    hv = np.zeros(shape=(32, 1))\n    s = elements[key][0]\n    sp = (re.split('(\\s+)', s))\n    if key == \"H\":\n        hv[0] = 1\n    if key != \"H\":\n        for j in range(1, len(sp)):\n            if sp[j] != ' ':\n                n = sp[j][:1]\n                orb = sp[j][1:]\n                hv[orbitals[orb]] = 1\n    hvs[element] = hv\n\n\n# --------------------------- pre-defined functions ----------------------------------\n\ndef make_hot_for_atom_i(crystal, i, hvs):\n    EP = str(crystal[i].specie)\n    # nan_to_num: Replace nan with zero and inf with finite numbers.\n    HV_P = np.nan_to_num(hvs[EP])\n    # reshape from (32,1) to (1,32)\n    AA = HV_P.reshape((HV_P.shape[1], 32))\n    A = np.array(AA)\n    # get the Voronoi nearest neighbours(VNN) of atom indexed by i\n    b = VoronoiNN().get_nn_info(crystal, i)\n    angles = []\n    # store the solid angles between central atom i with VNN's in angles\n    for nb in b:\n        angle_K = nb['poly_info']['solid_angle']\n        angles.append(angle_K)\n    max_angle = max(angles)\n    X_P = np.zeros(shape=(32, 32))\n    tmp_X = []\n    for nb in b:\n        # check VNN b's specie type\n        EK = str(nb['site'].specie)\n        # check the solid angle between b and central atom\n        angle_K = nb['poly_info']['solid_angle']\n        index_K = nb['site_index']\n        # calculate the distance square between b and central atom\n        r_pk = ((calculateDistance(nb['site'].coords, crystal[i].coords)) * (\n            calculateDistance(nb['site'].coords, crystal[i].coords)))\n        # map b to the vector representation and reshape\n        HV_K = hvs[EK]\n        HV_K = HV_K.reshape((HV_K.shape[1], 32))\n        # weight coeficients of b-central atom pair\n        coef_K = (angle_K / max_angle) * ((1 / ((r_pk) ** 2)))\n        HV_K_new = np.nan_to_num(coef_K * HV_K)\n        # matrix product between b and central atom ---> (32, 32)\n        X_PT = np.matmul(HV_P, HV_K_new)\n        tmp_X.append(X_PT)\n    X0 = np.zeros(shape=(32, 32))\n    # el stands for one matrix(of VNN-central_atom pair)\n    # weighted sum over all pairs\n    for el in tmp_X:\n        X0 = [[sum(x) for x in zip(el[i], X0[i])] for i in range(len(el))]\n    # the size of X0 is (32, 33),not flattened\n    # the first column is central atom\n    X0 = np.concatenate((A.T, X0), axis=1)\n    X0 = np.asarray(X0)\n    # flatten arranged by column\n    X0 = X0.flatten(order='F')\n    return X0\n\n\ndef calculateDistance(a, b):  # Atom-wise OFM\n    dist = math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2)\n    return dist\n\n\n# ---------------------- Loading id-data(cif-id) of magnetic material-----------------------------\nid_prop_file = os.path.join(cif_path, 'id_prop.csv')\nwith open(id_prop_file) as f:\n    reader = csv.reader(f)\n    id_prop_data = [row for row in reader]\n\nid_data = []\nfor i in range(len(id_prop_data)):\n    id_data.append(id_prop_data[i][0])\n\nif args.partial_csv is not None:\n    with open(args.partial_csv) as f:\n        reader = csv.reader(f)\n        magmom_data = [row for row in reader]\n    id = []\n    for i in range(len(magmom_data)):\n        id.append(magmom_data[i][0])\n\n# ----------------------- Consruct OFM representation for given material ao given position -----------------------\n# store in a dictionary called all_atom_embedding\nall_atom_embedding = {}\nstart = time.time()\n\nfor ids in id_data:\n    crystal = Structure.from_file(os.path.join(cif_path, ids + '.cif'))\n    for idx in range(len(crystal)):\n        atom_name = ids + '_' + str(crystal[idx].specie) + '_' + str(crystal[idx].specie.number) + '_' + str(idx + 1)\n        if args.partial_csv is None:\n            all_atom_embedding[atom_name] = make_hot_for_atom_i(crystal, idx, hvs)\n        else:\n            if atom_name in id:\n                all_atom_embedding[atom_name] = make_hot_for_atom_i(crystal, idx, hvs)\n\n\nprint(\"Spend \", time.time() - start, ' s to store OFM rep of atoms in a dictionary all_atom_embedding')\nprint(\"*********************************************************************\")\n# --------------------------- Save as .npy file ----------------------------------\n\nnp.save('OFM.npy', all_atom_embedding)\nprint(\"Over !!!!! This script takes: \", time.time() - start_all, ' s')\n", "meta": {"hexsha": "bf076465bfc8ba21bf0f20b9d166b67c1292adf9", "size": 8746, "ext": "py", "lang": "Python", "max_stars_repo_path": "ssl/get_ofm.py", "max_stars_repo_name": "Harrykjg-physics/self-supervised-atomic-representations", "max_stars_repo_head_hexsha": "153567fae05ffb455dfd35e4fd5e09c965d33ac1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ssl/get_ofm.py", "max_issues_repo_name": "Harrykjg-physics/self-supervised-atomic-representations", "max_issues_repo_head_hexsha": "153567fae05ffb455dfd35e4fd5e09c965d33ac1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ssl/get_ofm.py", "max_forks_repo_name": "Harrykjg-physics/self-supervised-atomic-representations", "max_forks_repo_head_hexsha": "153567fae05ffb455dfd35e4fd5e09c965d33ac1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.5212765957, "max_line_length": 117, "alphanum_fraction": 0.4937114109, "include": true, "reason": "import numpy", "num_tokens": 3524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.2658804847339313, "lm_q1q2_score": 0.1565741275430946}}
{"text": "#!/usr/bin/env python\n# coding=utf-8\n\"\"\"\n@author: Jiawei Wu\n@create time: 2019-11-17 11:23\n@edit time: 2020-05-10 22:17\n@FilePath: /vvlab/agents/DQN_base.py\n@desc: 创建DQN对象\n\"\"\"\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom ..utils import ReplayBuffer\nCUDA = torch.cuda.is_available()\n\n\nclass DQNBase(object):\n    \"\"\"The base class for DQN.\"\"\"\n\n    def __init__(self, n_states, n_actions, learning_rate=0.001,\n                 discount_rate=0.0, card_no=0, **kwargs):\n        \"\"\"Initialize two networks and experience playback pool of DQN.\n\n        Args:\n          n_states: Number of states.\n          n_actions: Number of actions.\n          learning_rate: Decide how much error this time is to be learned.\n          discount_rate: Attenuation value for future reward.\n          card_no: Designated training card number.\n          **kwargs: Incoming parameters.\n        \"\"\"\n        # super parameters of DQN\n        self.gamma = discount_rate  # future discount rate\n\n        self.epsilon = 0.6\n        self.epsilon_min = 0.001\n        self.epsilon_decay = 0.999\n        self.eval_every = 10\n        self.card_no = card_no\n        # bulid the network\n        self.n_states, self.n_actions = n_states, n_actions\n        self._build_net()\n\n        self.buff_size, self.buff_thres, self.batch_size = 50000, 1000, 256\n        if 'buff_size' in kwargs:\n            self.buff_size = kwargs['buff_size']\n        if 'buff_thres' in kwargs:\n            self.buff_thres = kwargs['buff_thres']\n        if 'batch_size' in kwargs:\n            self.batch_size = kwargs['batch_size']\n        self.replay_buff = ReplayBuffer(n_states, 1, buff_size=self.buff_size,\n                                        buff_thres=self.buff_thres,\n                                        batch_size=self.batch_size,\n                                        card_no=self.card_no)\n        # define optimizer and loss function\n        self.optimizer = torch.optim.Adam(\n            self.eval_net.parameters(), lr=learning_rate)\n        self.loss_func = nn.MSELoss()\n        # record the number of steps for synchronization parameters\n        self.eval_step = 0\n        if CUDA:\n            self.cuda()\n\n    def _build_net(self):\n        \"\"\"Bulid the network.\n\n        Raises:\n          TypeError:Network build no implementation.\n        \"\"\"\n        raise TypeError(\"Network build no implementation\")\n\n    def get_action(self, state):\n        \"\"\"Get the action at this moment.\n\n        Args:\n          state:State at this moment.\n\n        Return:\n          The action output.\n        \"\"\"\n        # epsilon update\n        self.epsilon = self.epsilon * \\\n            self.epsilon_decay \\\n            if self.epsilon > self.epsilon_min else self.epsilon\n        # convert row vector to column vector\n        # (1 x n_states -> n_states x 1 x 1)\n        if np.random.rand() < self.epsilon:\n            # random\n            action_size = state.shape[0]\n            return np.random.randint(0, self.n_actions, (1, action_size))\n        else:\n            # greedy\n            state = torch.unsqueeze(torch.FloatTensor(state), 0)\n            action_values = self.eval_net.forward(state).cpu()\n            return action_values.data.numpy().argmax(axis=2)\n\n    def get_raw_out(self, state):\n        \"\"\"Get the original actions.\n\n        Args:\n          state:State at this moment.\n\n        Returns:\n          Action values before selected by argmax.\n        \"\"\"\n        state = torch.unsqueeze(torch.FloatTensor(state), 0)\n        action_values = self.eval_net.forward(state)\n        print(action_values)\n        return action_values\n\n    def add_step(self, cur_state, action, reward, done, next_state):\n        \"\"\"Add a record to the experience replay pool.\n\n        Args:\n          cur_state:State at this moment.\n          action:Action output at this moment.\n          reward:Reward after taking the action.\n          done:A sign to indicate whether training is stopped.\n          next_state:State at next moment.\n        \"\"\"\n        self.replay_buff.add_step(cur_state, action, reward, done, next_state)\n\n    def learn(self):\n        \"\"\"The learning process of DQN.\n\n        Returns:\n          The loss during learning process when the batch is not 0.\n        \"\"\"\n        batch = self.replay_buff.get_batch_splited_tensor(CUDA)\n        if batch is None:\n            return None\n        # copy parameter\n        if self.eval_step % self.eval_every == 0:\n            self.target_net.load_state_dict(self.eval_net.state_dict())\n        # update training steps\n        self.eval_step += 1\n        # split batch\n        batch_cur_states, batch_actions, \\\n            batch_rewards, batch_dones, batch_next_states = batch\n        # calculation error\n        q_eval = self.eval_net(batch_cur_states)\n        q_eval = q_eval.gather(1, batch_actions.long())  # shape (batch, 1)\n        # detach from graph, don't backpropagate\n        q_next = self.target_net(batch_next_states).detach()\n        # if done, the future is not considered\n        q_target = batch_rewards + self.gamma * \\\n            (1 - batch_dones) * \\\n            q_next.max(1)[0].view(\n                len(batch_next_states), 1)   # shape (batch, 1)\n        loss = self.loss_func(q_eval, q_target)\n        # update network\n        self.optimizer.zero_grad()\n        loss.backward()\n        self.optimizer.step()\n        return loss.detach().cpu().numpy()\n\n    def cuda(self):\n        \"\"\"GPU operation using specified card.\"\"\"\n        self.eval_net.cuda(self.card_no)\n        self.target_net.cuda(self.card_no)\n", "meta": {"hexsha": "b0ce0cdc07da9b26ffc2ec270bc27fe4f796760e", "size": 5540, "ext": "py", "lang": "Python", "max_stars_repo_path": "vvlab/agents/DQN_base.py", "max_stars_repo_name": "LampV/Reinforcement-Learning", "max_stars_repo_head_hexsha": "0652b9e8c2de428d3508074c6fd640cc14f84a2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-12-26T11:46:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-02T10:59:46.000Z", "max_issues_repo_path": "vvlab/agents/DQN_base.py", "max_issues_repo_name": "LampV/Reinforcement-Learning", "max_issues_repo_head_hexsha": "0652b9e8c2de428d3508074c6fd640cc14f84a2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2021-04-05T13:10:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:51:15.000Z", "max_forks_repo_path": "vvlab/agents/DQN_base.py", "max_forks_repo_name": "LampV/Reinforcement-Learning", "max_forks_repo_head_hexsha": "0652b9e8c2de428d3508074c6fd640cc14f84a2c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-09-28T01:26:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T06:15:53.000Z", "avg_line_length": 34.4099378882, "max_line_length": 78, "alphanum_fraction": 0.5989169675, "include": true, "reason": "import numpy", "num_tokens": 1240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.15656082006675504}}
{"text": "from typing import Dict, Any\n\nimport torch\nimport math\nimport logging\n\nimport numpy as np\n\n_logger = logging.getLogger(__name__)\n\n\nclass Scheduler:\n    \"\"\" Parameter Scheduler Base Class\n    A scheduler base class that can be used to schedule any optimizer parameter groups.\n    Unlike the builtin PyTorch schedulers, this is intended to be consistently called\n    * At the END of each epoch, before incrementing the epoch count, to calculate next epoch's value\n    * At the END of each optimizer update, after incrementing the update count, to calculate next update's value\n    The schedulers built on this should try to remain as stateless as possible (for simplicity).\n    This family of schedulers is attempting to avoid the confusion of the meaning of 'last_epoch'\n    and -1 values for special behaviour. All epoch and update counts must be tracked in the training\n    code and explicitly passed in to the schedulers on the corresponding step or step_update call.\n    Based on ideas from:\n     * https://github.com/pytorch/fairseq/tree/master/fairseq/optim/lr_scheduler\n     * https://github.com/allenai/allennlp/tree/master/allennlp/training/learning_rate_schedulers\n    \"\"\"\n\n    def __init__(self,\n                 optimizer: torch.optim.Optimizer,\n                 param_group_field: str,\n                 noise_range_t=None,\n                 noise_type='normal',\n                 noise_pct=0.67,\n                 noise_std=1.0,\n                 noise_seed=None,\n                 initialize: bool = True) -> None:\n        self.optimizer = optimizer\n        self.param_group_field = param_group_field\n        self._initial_param_group_field = f\"initial_{param_group_field}\"\n        if initialize:\n            for i, group in enumerate(self.optimizer.param_groups):\n                if param_group_field not in group:\n                    raise KeyError(f\"{param_group_field} missing from param_groups[{i}]\")\n                group.setdefault(self._initial_param_group_field, group[param_group_field])\n        else:\n            for i, group in enumerate(self.optimizer.param_groups):\n                if self._initial_param_group_field not in group:\n                    raise KeyError(f\"{self._initial_param_group_field} missing from param_groups[{i}]\")\n        self.base_values = [group[self._initial_param_group_field] for group in self.optimizer.param_groups]\n        self.metric = None  # any point to having this for all?\n        self.noise_range_t = noise_range_t\n        self.noise_pct = noise_pct\n        self.noise_type = noise_type\n        self.noise_std = noise_std\n        self.noise_seed = noise_seed if noise_seed is not None else 42\n        self.update_groups(self.base_values)\n\n    def state_dict(self) -> Dict[str, Any]:\n        return {key: value for key, value in self.__dict__.items() if key != 'optimizer'}\n\n    def load_state_dict(self, state_dict: Dict[str, Any]) -> None:\n        self.__dict__.update(state_dict)\n\n    def get_epoch_values(self, epoch: int):\n        return None\n\n    def get_update_values(self, num_updates: int):\n        return None\n\n    def step(self, epoch: int, metric: float = None) -> None:\n        self.metric = metric\n        values = self.get_epoch_values(epoch)\n        if values is not None:\n            values = self._add_noise(values, epoch)\n            self.update_groups(values)\n\n    def step_update(self, num_updates: int, metric: float = None):\n        self.metric = metric\n        values = self.get_update_values(num_updates)\n        if values is not None:\n            values = self._add_noise(values, num_updates)\n            self.update_groups(values)\n\n    def update_groups(self, values):\n        if not isinstance(values, (list, tuple)):\n            values = [values] * len(self.optimizer.param_groups)\n        for param_group, value in zip(self.optimizer.param_groups, values):\n            param_group[self.param_group_field] = value\n\n    def _add_noise(self, lrs, t):\n        if self.noise_range_t is not None:\n            if isinstance(self.noise_range_t, (list, tuple)):\n                apply_noise = self.noise_range_t[0] <= t < self.noise_range_t[1]\n            else:\n                apply_noise = t >= self.noise_range_t\n            if apply_noise:\n                g = torch.Generator()\n                g.manual_seed(self.noise_seed + t)\n                if self.noise_type == 'normal':\n                    while True:\n                        # resample if noise out of percent limit, brute force but shouldn't spin much\n                        noise = torch.randn(1, generator=g).item()\n                        if abs(noise) < self.noise_pct:\n                            break\n                else:\n                    noise = 2 * (torch.rand(1, generator=g).item() - 0.5) * self.noise_pct\n                lrs = [v + v * noise for v in lrs]\n        return lrs\n\nclass CosineLRScheduler(Scheduler):\n    \"\"\"\n    Cosine decay with restarts.\n    This is described in the paper https://arxiv.org/abs/1608.03983.\n    Inspiration from\n    https://github.com/allenai/allennlp/blob/master/allennlp/training/learning_rate_schedulers/cosine.py\n    \"\"\"\n\n    def __init__(self,\n                 optimizer: torch.optim.Optimizer,\n                 t_initial: int,\n                 t_mul: float = 1.,\n                 lr_min: float = 0.,\n                 decay_rate: float = 1.,\n                 warmup_t=0,\n                 warmup_lr_init=0,\n                 warmup_prefix=False,\n                 cycle_limit=0,\n                 t_in_epochs=True,\n                 noise_range_t=None,\n                 noise_pct=0.67,\n                 noise_std=1.0,\n                 noise_seed=42,\n                 initialize=True) -> None:\n        super().__init__(\n            optimizer, param_group_field=\"lr\",\n            noise_range_t=noise_range_t, noise_pct=noise_pct, noise_std=noise_std, noise_seed=noise_seed,\n            initialize=initialize)\n\n        assert t_initial > 0\n        assert lr_min >= 0\n        if t_initial == 1 and t_mul == 1 and decay_rate == 1:\n            _logger.warning(\"Cosine annealing scheduler will have no effect on the learning \"\n                           \"rate since t_initial = t_mul = eta_mul = 1.\")\n        self.t_initial = t_initial\n        self.t_mul = t_mul\n        self.lr_min = lr_min\n        self.decay_rate = decay_rate\n        self.cycle_limit = cycle_limit\n        self.warmup_t = warmup_t\n        self.warmup_lr_init = warmup_lr_init\n        self.warmup_prefix = warmup_prefix\n        self.t_in_epochs = t_in_epochs\n        if self.warmup_t:\n            self.warmup_steps = [(v - warmup_lr_init) / self.warmup_t for v in self.base_values]\n            super().update_groups(self.warmup_lr_init)\n        else:\n            self.warmup_steps = [1 for _ in self.base_values]\n\n    def _get_lr(self, t):\n        if t < self.warmup_t:\n            lrs = [self.warmup_lr_init + t * s for s in self.warmup_steps]\n        else:\n            if self.warmup_prefix:\n                t = t - self.warmup_t\n\n            if self.t_mul != 1:\n                i = math.floor(math.log(1 - t / self.t_initial * (1 - self.t_mul), self.t_mul))\n                t_i = self.t_mul ** i * self.t_initial\n                t_curr = t - (1 - self.t_mul ** i) / (1 - self.t_mul) * self.t_initial\n            else:\n                i = t // self.t_initial\n                t_i = self.t_initial\n                t_curr = t - (self.t_initial * i)\n\n            gamma = self.decay_rate ** i\n            lr_min = self.lr_min * gamma\n            lr_max_values = [v * gamma for v in self.base_values]\n\n            if self.cycle_limit == 0 or (self.cycle_limit > 0 and i < self.cycle_limit):\n                lrs = [\n                    lr_min + 0.5 * (lr_max - lr_min) * (1 + math.cos(math.pi * t_curr / t_i)) for lr_max in lr_max_values\n                ]\n            else:\n                lrs = [self.lr_min for _ in self.base_values]\n\n        return lrs\n\n    def get_epoch_values(self, epoch: int):\n        if self.t_in_epochs:\n            return self._get_lr(epoch)\n        else:\n            return None\n\n    def get_update_values(self, num_updates: int):\n        if not self.t_in_epochs:\n            return self._get_lr(num_updates)\n        else:\n            return None\n\n    def get_cycle_length(self, cycles=0):\n        if not cycles:\n            cycles = self.cycle_limit\n        cycles = max(1, cycles)\n        if self.t_mul == 1.0:\n            return self.t_initial * cycles\n        else:\n            return int(math.floor(-self.t_initial * (self.t_mul ** cycles - 1) / (1 - self.t_mul)))\n\n\nclass TanhLRScheduler(Scheduler):\n    \"\"\"\n    Hyberbolic-Tangent decay with restarts.\n    This is described in the paper https://arxiv.org/abs/1806.01593\n    \"\"\"\n\n    def __init__(self,\n                 optimizer: torch.optim.Optimizer,\n                 t_initial: int,\n                 lb: float = -6.,\n                 ub: float = 4.,\n                 t_mul: float = 1.,\n                 lr_min: float = 0.,\n                 decay_rate: float = 1.,\n                 warmup_t=0,\n                 warmup_lr_init=0,\n                 warmup_prefix=False,\n                 cycle_limit=0,\n                 t_in_epochs=True,\n                 noise_range_t=None,\n                 noise_pct=0.67,\n                 noise_std=1.0,\n                 noise_seed=42,\n                 initialize=True) -> None:\n        super().__init__(\n            optimizer, param_group_field=\"lr\",\n            noise_range_t=noise_range_t, noise_pct=noise_pct, noise_std=noise_std, noise_seed=noise_seed,\n            initialize=initialize)\n\n        assert t_initial > 0\n        assert lr_min >= 0\n        assert lb < ub\n        assert cycle_limit >= 0\n        assert warmup_t >= 0\n        assert warmup_lr_init >= 0\n        self.lb = lb\n        self.ub = ub\n        self.t_initial = t_initial\n        self.t_mul = t_mul\n        self.lr_min = lr_min\n        self.decay_rate = decay_rate\n        self.cycle_limit = cycle_limit\n        self.warmup_t = warmup_t\n        self.warmup_lr_init = warmup_lr_init\n        self.warmup_prefix = warmup_prefix\n        self.t_in_epochs = t_in_epochs\n        if self.warmup_t:\n            t_v = self.base_values if self.warmup_prefix else self._get_lr(self.warmup_t)\n            self.warmup_steps = [(v - warmup_lr_init) / self.warmup_t for v in t_v]\n            super().update_groups(self.warmup_lr_init)\n        else:\n            self.warmup_steps = [1 for _ in self.base_values]\n\n    def _get_lr(self, t):\n        if t < self.warmup_t:\n            lrs = [self.warmup_lr_init + t * s for s in self.warmup_steps]\n        else:\n            if self.warmup_prefix:\n                t = t - self.warmup_t\n\n            if self.t_mul != 1:\n                i = math.floor(math.log(1 - t / self.t_initial * (1 - self.t_mul), self.t_mul))\n                t_i = self.t_mul ** i * self.t_initial\n                t_curr = t - (1 - self.t_mul ** i) / (1 - self.t_mul) * self.t_initial\n            else:\n                i = t // self.t_initial\n                t_i = self.t_initial\n                t_curr = t - (self.t_initial * i)\n\n            if self.cycle_limit == 0 or (self.cycle_limit > 0 and i < self.cycle_limit):\n                gamma = self.decay_rate ** i\n                lr_min = self.lr_min * gamma\n                lr_max_values = [v * gamma for v in self.base_values]\n\n                tr = t_curr / t_i\n                lrs = [\n                    lr_min + 0.5 * (lr_max - lr_min) * (1 - math.tanh(self.lb * (1. - tr) + self.ub * tr))\n                    for lr_max in lr_max_values\n                ]\n            else:\n                lrs = [self.lr_min * (self.decay_rate ** self.cycle_limit) for _ in self.base_values]\n        return lrs\n\n    def get_epoch_values(self, epoch: int):\n        if self.t_in_epochs:\n            return self._get_lr(epoch)\n        else:\n            return None\n\n    def get_update_values(self, num_updates: int):\n        if not self.t_in_epochs:\n            return self._get_lr(num_updates)\n        else:\n            return None\n\n    def get_cycle_length(self, cycles=0):\n        if not cycles:\n            cycles = self.cycle_limit\n        cycles = max(1, cycles)\n        if self.t_mul == 1.0:\n            return self.t_initial * cycles\n        else:\n            return int(math.floor(-self.t_initial * (self.t_mul ** cycles - 1) / (1 - self.t_mul)))\n\nclass StepLRScheduler(Scheduler):\n    \"\"\"\n    \"\"\"\n\n    def __init__(self,\n                 optimizer: torch.optim.Optimizer,\n                 decay_t: float,\n                 decay_rate: float = 1.,\n                 warmup_t=0,\n                 warmup_lr_init=0,\n                 t_in_epochs=True,\n                 noise_range_t=None,\n                 noise_pct=0.67,\n                 noise_std=1.0,\n                 noise_seed=42,\n                 initialize=True,\n                 ) -> None:\n        super().__init__(\n            optimizer, param_group_field=\"lr\",\n            noise_range_t=noise_range_t, noise_pct=noise_pct, noise_std=noise_std, noise_seed=noise_seed,\n            initialize=initialize)\n\n        self.decay_t = decay_t\n        self.decay_rate = decay_rate\n        self.warmup_t = warmup_t\n        self.warmup_lr_init = warmup_lr_init\n        self.t_in_epochs = t_in_epochs\n        if self.warmup_t:\n            self.warmup_steps = [(v - warmup_lr_init) / self.warmup_t for v in self.base_values]\n            super().update_groups(self.warmup_lr_init)\n        else:\n            self.warmup_steps = [1 for _ in self.base_values]\n\n    def _get_lr(self, t):\n        if t < self.warmup_t:\n            lrs = [self.warmup_lr_init + t * s for s in self.warmup_steps]\n        else:\n            lrs = [v * (self.decay_rate ** (t // self.decay_t)) for v in self.base_values]\n        return lrs\n\n    def get_epoch_values(self, epoch: int):\n        if self.t_in_epochs:\n            return self._get_lr(epoch)\n        else:\n            return None\n\n    def get_update_values(self, num_updates: int):\n        if not self.t_in_epochs:\n            return self._get_lr(num_updates)\n        else:\n            return None\n\nclass PlateauLRScheduler(Scheduler):\n    \"\"\"Decay the LR by a factor every time the validation loss plateaus.\"\"\"\n\n    def __init__(self,\n                 optimizer,\n                 decay_rate=0.1,\n                 patience_t=10,\n                 verbose=True,\n                 threshold=1e-4,\n                 cooldown_t=0,\n                 warmup_t=0,\n                 warmup_lr_init=0,\n                 lr_min=0,\n                 mode='max',\n                 noise_range_t=None,\n                 noise_type='normal',\n                 noise_pct=0.67,\n                 noise_std=1.0,\n                 noise_seed=None,\n                 initialize=True,\n                 ):\n        super().__init__(optimizer, 'lr', initialize=initialize)\n\n        self.lr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(\n            self.optimizer,\n            patience=patience_t,\n            factor=decay_rate,\n            verbose=verbose,\n            threshold=threshold,\n            cooldown=cooldown_t,\n            mode=mode,\n            min_lr=lr_min\n        )\n\n        self.noise_range = noise_range_t\n        self.noise_pct = noise_pct\n        self.noise_type = noise_type\n        self.noise_std = noise_std\n        self.noise_seed = noise_seed if noise_seed is not None else 42\n        self.warmup_t = warmup_t\n        self.warmup_lr_init = warmup_lr_init\n        if self.warmup_t:\n            self.warmup_steps = [(v - warmup_lr_init) / self.warmup_t for v in self.base_values]\n            super().update_groups(self.warmup_lr_init)\n        else:\n            self.warmup_steps = [1 for _ in self.base_values]\n        self.restore_lr = None\n\n    def state_dict(self):\n        return {\n            'best': self.lr_scheduler.best,\n            'last_epoch': self.lr_scheduler.last_epoch,\n        }\n\n    def load_state_dict(self, state_dict):\n        self.lr_scheduler.best = state_dict['best']\n        if 'last_epoch' in state_dict:\n            self.lr_scheduler.last_epoch = state_dict['last_epoch']\n\n    # override the base class step fn completely\n    def step(self, epoch, metric=None):\n        if epoch <= self.warmup_t:\n            lrs = [self.warmup_lr_init + epoch * s for s in self.warmup_steps]\n            super().update_groups(lrs)\n        else:\n            if self.restore_lr is not None:\n                # restore actual LR from before our last noise perturbation before stepping base\n                for i, param_group in enumerate(self.optimizer.param_groups):\n                    param_group['lr'] = self.restore_lr[i]\n                self.restore_lr = None\n\n            self.lr_scheduler.step(metric, epoch)  # step the base scheduler\n\n            if self.noise_range is not None:\n                if isinstance(self.noise_range, (list, tuple)):\n                    apply_noise = self.noise_range[0] <= epoch < self.noise_range[1]\n                else:\n                    apply_noise = epoch >= self.noise_range\n                if apply_noise:\n                    self._apply_noise(epoch)\n\n    def _apply_noise(self, epoch):\n        g = torch.Generator()\n        g.manual_seed(self.noise_seed + epoch)\n        if self.noise_type == 'normal':\n            while True:\n                # resample if noise out of percent limit, brute force but shouldn't spin much\n                noise = torch.randn(1, generator=g).item()\n                if abs(noise) < self.noise_pct:\n                    break\n        else:\n            noise = 2 * (torch.rand(1, generator=g).item() - 0.5) * self.noise_pct\n\n        # apply the noise on top of previous LR, cache the old value so we can restore for normal\n        # stepping of base scheduler\n        restore_lr = []\n        for i, param_group in enumerate(self.optimizer.param_groups):\n            old_lr = float(param_group['lr'])\n            restore_lr.append(old_lr)\n            new_lr = old_lr + old_lr * noise\n            param_group['lr'] = new_lr\n        self.restore_lr = restore_lr\n\ndef create_scheduler(args, optimizer):\n    num_epochs = args.epochs\n\n    if getattr(args, 'lr_noise', None) is not None:\n        lr_noise = getattr(args, 'lr_noise')\n        if isinstance(lr_noise, (list, tuple)):\n            noise_range = [n * num_epochs for n in lr_noise]\n            if len(noise_range) == 1:\n                noise_range = noise_range[0]\n        else:\n            noise_range = lr_noise * num_epochs\n    else:\n        noise_range = None\n\n    lr_scheduler = None\n    if args.sched == 'cosine':\n        lr_scheduler = CosineLRScheduler(\n            optimizer,\n            t_initial=num_epochs,\n            t_mul=getattr(args, 'lr_cycle_mul', 1.),\n            lr_min=args.min_lr,\n            decay_rate=args.decay_rate,\n            warmup_lr_init=args.warmup_lr,\n            warmup_t=args.warmup_epochs,\n            cycle_limit=getattr(args, 'lr_cycle_limit', 1),\n            t_in_epochs=True,\n            noise_range_t=noise_range,\n            noise_pct=getattr(args, 'lr_noise_pct', 0.67),\n            noise_std=getattr(args, 'lr_noise_std', 1.),\n            noise_seed=getattr(args, 'seed', 42),\n        )\n        num_epochs = lr_scheduler.get_cycle_length() + args.cooldown_epochs\n    elif args.sched == 'tanh':\n        lr_scheduler = TanhLRScheduler(\n            optimizer,\n            t_initial=num_epochs,\n            t_mul=getattr(args, 'lr_cycle_mul', 1.),\n            lr_min=args.min_lr,\n            warmup_lr_init=args.warmup_lr,\n            warmup_t=args.warmup_epochs,\n            cycle_limit=getattr(args, 'lr_cycle_limit', 1),\n            t_in_epochs=True,\n            noise_range_t=noise_range,\n            noise_pct=getattr(args, 'lr_noise_pct', 0.67),\n            noise_std=getattr(args, 'lr_noise_std', 1.),\n            noise_seed=getattr(args, 'seed', 42),\n        )\n        num_epochs = lr_scheduler.get_cycle_length() + args.cooldown_epochs\n    elif args.sched == 'step':\n        lr_scheduler = StepLRScheduler(\n            optimizer,\n            decay_t=args.decay_epochs,\n            decay_rate=args.decay_rate,\n            warmup_lr_init=args.warmup_lr,\n            warmup_t=args.warmup_epochs,\n            noise_range_t=noise_range,\n            noise_pct=getattr(args, 'lr_noise_pct', 0.67),\n            noise_std=getattr(args, 'lr_noise_std', 1.),\n            noise_seed=getattr(args, 'seed', 42),\n        )\n    elif args.sched == 'plateau':\n        mode = 'min' if 'loss' in getattr(args, 'eval_metric', '') else 'max'\n        lr_scheduler = PlateauLRScheduler(\n            optimizer,\n            decay_rate=args.decay_rate,\n            patience_t=args.patience_epochs,\n            lr_min=args.min_lr,\n            mode=mode,\n            warmup_lr_init=args.warmup_lr,\n            warmup_t=args.warmup_epochs,\n            cooldown_t=0,\n            noise_range_t=noise_range,\n            noise_pct=getattr(args, 'lr_noise_pct', 0.67),\n            noise_std=getattr(args, 'lr_noise_std', 1.),\n            noise_seed=getattr(args, 'seed', 42),\n        )\n\n    return lr_scheduler, num_epochs", "meta": {"hexsha": "1c2fbd6abc51e920a13f546a06ef5107166764c0", "size": 21025, "ext": "py", "lang": "Python", "max_stars_repo_path": "PC/utils/scheduler.py", "max_stars_repo_name": "StanLei52/GEBD", "max_stars_repo_head_hexsha": "5f7e722e0384f9877c75d116e1db72400d2bc58f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 44, "max_stars_repo_stars_event_min_datetime": "2021-03-24T07:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T11:49:14.000Z", "max_issues_repo_path": "PC/utils/scheduler.py", "max_issues_repo_name": "StanLei52/GEBD", "max_issues_repo_head_hexsha": "5f7e722e0384f9877c75d116e1db72400d2bc58f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-05-26T09:31:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-11T11:47:38.000Z", "max_forks_repo_path": "PC/utils/scheduler.py", "max_forks_repo_name": "StanLei52/GEBD", "max_forks_repo_head_hexsha": "5f7e722e0384f9877c75d116e1db72400d2bc58f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-04-07T00:51:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T01:54:41.000Z", "avg_line_length": 38.5779816514, "max_line_length": 121, "alphanum_fraction": 0.5710820452, "include": true, "reason": "import numpy", "num_tokens": 4905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.1565608168505405}}
{"text": "#!/usr/bin/env python\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport numpy as np\nimport torch\nimport libs.boxes.cython_bbox as cython_bbox\nfrom .nms._ext import nms\n\n\ndef matching_box(boxes, image_inds, gt_boxes_list, bg_overlap_threshold=0.5, fg_overlap_threshold=0.6):\n    \"\"\"gt_boxes_list is a list of np.ndarray, batch_inds specify the image a boxes belongs\"\"\"\n    if boxes.is_cuda:\n        boxes_np = boxes.data.cpu().numpy()\n    else:\n        boxes_np = boxes.data.numpy()\n\n    if image_inds.is_cuda:\n        image_inds_np = image_inds.cpu().numpy()\n    else:\n        image_inds_np = image_inds.numpy()\n\n    num_boxes = boxes_np.shape[0]\n    assert num_boxes == image_inds_np.size\n    match_labels = []\n    match_inds = []\n    match_boxes = []\n\n    for i, gt_boxes in enumerate(gt_boxes_list):\n        boxes_im = boxes_np[image_inds_np == i]\n        num_boxes_im = boxes_im.shape[0]\n        match = np.zeros((boxes_im.shape[0],), dtype=np.int32) - 1\n        labels = np.zeros((boxes_im.shape[0],), dtype=np.int64)\n        match_box = np.zeros((boxes_im.shape[0], 4), dtype=np.float32)\n        if gt_boxes.size > 0 and boxes_im.size > 0:\n            # B x G\n            overlaps = cython_bbox.bbox_overlaps(\n                np.ascontiguousarray(boxes_im, dtype=np.float),\n                np.ascontiguousarray(gt_boxes[:, :4], dtype=np.float))\n\n            gt_assignment = overlaps.argmax(axis=1)  # (B)\n            max_overlaps = overlaps[np.arange(num_boxes_im), gt_assignment]\n            match[:] = gt_assignment[:]\n            match[max_overlaps < bg_overlap_threshold] = -1\n            match_box[:, :4] = gt_boxes[gt_assignment, :4]\n\n            labels[:] = gt_boxes[gt_assignment, 4]\n            # labels[max_overlaps < bg_overlap_threshold] = 0\n            # labels[np.logical_and(max_overlaps > bg_overlap_threshold,\n            #                       max_overlaps < fg_overlap_threshold)] = -1\n            labels[max_overlaps < fg_overlap_threshold] = 0\n            # labels[np.logical_and(max_overlaps > bg_overlap_threshold,\n            #                       max_overlaps < fg_overlap_threshold)] = -1\n\n        match_labels.append(labels)\n        match_inds.append(match)\n        match_boxes.append(match_box)\n\n    match_labels = np.concatenate(match_labels, axis=0)\n    match_inds = np.concatenate(match_inds, axis=0)\n    match_boxes = np.concatenate(match_boxes, axis=0)\n    if boxes.is_cuda:\n        return torch.from_numpy(match_labels).cuda(), \\\n               torch.from_numpy(match_inds).cuda(), \\\n               torch.from_numpy(match_boxes).cuda()\n    return torch.from_numpy(match_labels), \\\n           torch.from_numpy(match_inds), \\\n           torch.from_numpy(match_boxes)\n\n\ndef decoding_box(deltas, anchors, box_encoding='fastrcnn'):\n\n    boxes = anchors.view(-1, 4)\n    deltas = deltas.view(-1, 4)\n    n = deltas.size()[0]\n\n    pred_boxes = deltas.clone()\n    widths = boxes[:, 2] - boxes[:, 0] + 1.0\n    heights = boxes[:, 3] - boxes[:, 1] + 1.0\n\n    if box_encoding == 'fastrcnn':\n\n        ctr_x = boxes[:, 0] + 0.5 * widths\n        ctr_y = boxes[:, 1] + 0.5 * heights\n\n        dx = deltas[:, 0] * 0.1\n        dy = deltas[:, 1] * 0.1\n        dw = deltas[:, 2] * 0.2\n        dh = deltas[:, 3] * 0.2\n\n        pred_ctr_x = dx * widths + ctr_x\n        pred_ctr_y = dy * heights + ctr_y\n        pred_w = torch.exp(dw + torch.log(widths))\n        pred_h = torch.exp(dh + torch.log(heights))\n\n        pred_boxes[:, 0] = pred_ctr_x - 0.5 * pred_w\n        pred_boxes[:, 1] = pred_ctr_y - 0.5 * pred_h\n        pred_boxes[:, 2] = pred_ctr_x + 0.5 * pred_w - 1\n        pred_boxes[:, 3] = pred_ctr_y + 0.5 * pred_h - 1\n\n    elif box_encoding == 'simple':\n\n        pred_boxes[:, 0] = deltas[:, 0] * widths + boxes[:, 0]\n        pred_boxes[:, 1] = deltas[:, 1] * heights + boxes[:, 1]\n        pred_boxes[:, 2] = deltas[:, 2] * widths + boxes[:, 2]\n        pred_boxes[:, 3] = deltas[:, 3] * heights + boxes[:, 3]\n\n    return pred_boxes\n\n\ndef encoding_box(gt_boxes, anchors, box_encoding='fastrcnn'):\n\n\n    deltas = gt_boxes.clone()\n\n    if box_encoding == 'fastrcnn':\n\n        ex_widths = anchors[:, 2] - anchors[:, 0] + 1.0\n        ex_heights = anchors[:, 3] - anchors[:, 1] + 1.0\n        ex_ctr_x = anchors[:, 0] + 0.5 * ex_widths\n        ex_ctr_y = anchors[:, 1] + 0.5 * ex_heights\n\n        gt_widths = gt_boxes[:, 2] - gt_boxes[:, 0] + 1.0\n        gt_heights = gt_boxes[:, 3] - gt_boxes[:, 1] + 1.0\n        gt_ctr_x = gt_boxes[:, 0] + 0.5 * gt_widths\n        gt_ctr_y = gt_boxes[:, 1] + 0.5 * gt_heights\n\n        deltas[:, 0] = (gt_ctr_x - ex_ctr_x) / ex_widths / 0.1\n        deltas[:, 1] = (gt_ctr_y - ex_ctr_y) / ex_heights / 0.1\n        deltas[:, 2] = torch.log(gt_widths / ex_widths) / 0.2\n        deltas[:, 3] = torch.log(gt_heights / ex_heights) / 0.2\n\n    elif box_encoding == 'simple':\n\n        ex_widths = anchors[:, 2] - anchors[:, 0] + 1.0\n        ex_heights = anchors[:, 3] - anchors[:, 1] + 1.0\n\n        deltas = gt_boxes - anchors\n        deltas[:, 0] = deltas[:, 0] / ex_widths\n        deltas[:, 1] = deltas[:, 1] / ex_heights\n        deltas[:, 2] = deltas[:, 2] / ex_widths\n        deltas[:, 3] = deltas[:, 3] / ex_heights\n\n    return deltas\n\n\ndef apply_nms(boxes, scores, overlap_threshold):\n    \"\"\"\n    boxes has to be a Variable\n    for each image:\n    apply boxes\n    \"\"\"\n    x1 = boxes[:, 0]\n    y1 = boxes[:, 1]\n    x2 = boxes[:, 2]\n    y2 = boxes[:, 3]\n    areas = (x2 - x1 + 1) * (y2 - y1 + 1)\n    dets = torch.cat((boxes, scores.view(-1, 1)), 1)\n    order = scores.sort(0, descending=True)[1]\n    n = boxes.size(0)\n    keep = torch.LongTensor(n)\n    num_out = torch.LongTensor(1)\n\n    if not boxes.is_cuda:\n      nms.cpu_nms(keep, num_out, dets.data, order, areas, overlap_threshold)\n      return keep[:num_out[0]]\n\n    else:\n      dets = dets[order].contiguous()\n      nms.gpu_nms(keep, num_out, dets.data, overlap_threshold)\n\n    return order[keep[:num_out[0]].cuda()].contiguous()\n\ndef sample_rois(boxes, image_inds, gt_boxes_list,\n                fg_overlap_threshold=0.5,\n                rois_per_image=512,\n                fg_fraction=0.25,\n                ignore_threshold=0.2):\n    \"\"\"filter out ignored areas and keep the fg/bg ratio at 1:3\"\"\"\n    boxes_np = boxes.data.cpu().numpy() if boxes.is_cuda else boxes.data.numpy()\n    image_inds_np = image_inds.data.cpu().numpy() if image_inds.is_cuda else image_inds.data.numpy()\n\n    num_boxes = boxes_np.shape[0]\n    assert num_boxes == image_inds_np.size\n    sampled_boxes = []\n    sampled_probs = []\n    sampled_labels = []\n    sampled_image_inds = []\n    batch_size = len(gt_boxes_list)\n\n    for i, gt_boxes in enumerate(gt_boxes_list):\n        boxes_im = boxes_np[image_inds_np == i]\n        image_inds_im = image_inds_np[image_inds_np == i]\n\n        keep_inds = filter_boxes(boxes_im)\n        boxes_im = boxes_im[keep_inds]\n        image_inds_im = image_inds_im[keep_inds]\n\n        num_boxes_im = boxes_im.shape[0]\n        labels = np.zeros((boxes_im.shape[0],), dtype=np.int64)\n\n        # TODO: what if is no gt_boxes\n        if gt_boxes.size > 0:\n            # B x G\n            overlaps = cython_bbox.bbox_overlaps(\n                np.ascontiguousarray(boxes_im, dtype=np.float),\n                np.ascontiguousarray(gt_boxes[:, :4], dtype=np.float))\n\n            gt_assignment = overlaps.argmax(axis=1)  # (B)\n            max_overlaps = overlaps[np.arange(num_boxes_im), gt_assignment]\n\n            labels[:] = gt_boxes[gt_assignment, 4]\n            labels[max_overlaps < fg_overlap_threshold] = 0\n\n            # ignoring areas\n            ignored_mask = gt_boxes[:, 4] <= 0\n            if np.any(ignored_mask):\n                ignored_areas = gt_boxes[ignored_mask]\n                ignored = cython_bbox.bbox_exclude_ignored_areas(\n                    np.ascontiguousarray(boxes_im, dtype=np.float),\n                    np.ascontiguousarray(ignored_areas[:, :4], dtype=np.float),\n                    ignore_threshold\n                )\n                labels[ignored == 1] = -1\n\n            # add ground-thruth boxes\n            if True:\n                valid_inds = np.where(gt_boxes[:, 4] > 0)[0]\n                gb = gt_boxes[valid_inds][:, :4].astype(np.float32)\n                gb = jitter_boxes(gb)\n                cls = gt_boxes[valid_inds][:, 4].astype(np.int64)\n                boxes_im = np.concatenate((boxes_im, gb), axis=0)\n                labels = np.concatenate((labels, cls), axis=0)\n                assert labels.shape[0] == boxes_im.shape[0]\n\n                gn = gb.shape[0]\n\n                new_inds = np.zeros((gn, ), dtype=image_inds_im.dtype) + i\n                image_inds_im = np.concatenate((image_inds_im, new_inds), axis=0)\n        else:\n            labels = np.zeros((boxes_im.shape[0], ), dtype=np.float32)\n\n        sampled_boxes.append(boxes_im[labels >= 0])\n        sampled_labels.append(labels[labels >= 0])\n        sampled_image_inds.append(image_inds_im[labels >= 0])\n\n    sampled_boxes = np.concatenate(sampled_boxes, axis=0)\n    sampled_labels = np.concatenate(sampled_labels, axis=0).astype(np.int64)\n    sampled_image_inds = np.concatenate(sampled_image_inds, axis=0).astype(np.int64)\n\n    # sampling\n    bg_inds = np.where(sampled_labels == 0)[0]\n    fg_inds = np.where(sampled_labels > 0)[0]\n    # num_fg = min(fg_inds.size, 64)\n    # if fg_inds.size > 0:\n    #     fg_inds = np.random.choice(fg_inds, num_fg)\n    if False:\n        # sample all foregrounds\n        num_fg = fg_inds.size\n        num_bg = max(min(3 * num_fg, bg_inds.size), 16)\n        if bg_inds.size > 0:\n            bg_inds = np.random.choice(bg_inds, num_bg)\n        keep_inds = np.append(fg_inds, bg_inds)\n    else:\n        # faster rcnn sampling\n        num_fg = min(fg_inds.size, int(fg_fraction * rois_per_image * batch_size))\n        if num_fg > 0:\n            fg_inds = np.random.choice(fg_inds, num_fg, replace=False)\n        num_bg = rois_per_image * batch_size - num_fg\n        num_bg = min(num_bg, bg_inds.size)\n        if bg_inds.size > 0:\n            bg_inds = np.random.choice(bg_inds, num_bg, replace=False)\n        keep_inds = np.append(fg_inds, bg_inds)\n\n    sampled_labels = sampled_labels[keep_inds]\n    sampled_boxes = sampled_boxes[keep_inds]\n    sampled_image_inds = sampled_image_inds[keep_inds]\n\n    # Guard against the case no sampled rois\n    if sampled_labels.size == 0:\n        sampled_boxes = boxes_np[:1, :]\n        sampled_labels = np.array([-1], dtype=np.int64)\n        sampled_image_inds = image_inds_np[:1].astype(np.int64)\n\n    if boxes.is_cuda:\n        return torch.from_numpy(sampled_boxes).cuda(), \\\n               torch.from_numpy(sampled_labels).cuda(), \\\n               torch.from_numpy(sampled_image_inds).cuda()\n    return torch.from_numpy(sampled_boxes), \\\n           torch.from_numpy(sampled_labels), \\\n           torch.from_numpy(sampled_image_inds)\n\n\ndef jitter_boxes(boxes):\n    num = boxes.shape[0]\n    ws = boxes[:, 2] - boxes[:, 0] + 1.0\n    hs = boxes[:, 3] - boxes[:, 1] + 1.0\n    dws = (np.random.rand(num) - 0.5) * 0.2 * ws\n    dhs = (np.random.rand(num) - 0.5) * 0.2 * hs\n    boxes[:, 0] = boxes[:, 0] + dws\n    boxes[:, 1] = boxes[:, 1] + dhs\n    dws = (np.random.rand(num) - 0.5) * 0.2 * ws\n    dhs = (np.random.rand(num) - 0.5) * 0.2 * hs\n    boxes[:, 2] = boxes[:, 2] + dws\n    boxes[:, 3] = boxes[:, 3] + dhs\n    return boxes\n\n\ndef filter_boxes(boxes, min_size=8):\n    ws = boxes[:, 2] - boxes[:, 0] + 1.0\n    hs = boxes[:, 3] - boxes[:, 1] + 1.0\n    inds = np.where(\n        np.logical_and(ws >= min_size, hs >= min_size))[0]\n    return inds\n", "meta": {"hexsha": "e514542ff8c1330486b770906260566a0336e6ce", "size": 11598, "ext": "py", "lang": "Python", "max_stars_repo_path": "libs/layers/box.py", "max_stars_repo_name": "FullStackD3vs/Detectron-PYTORCH", "max_stars_repo_head_hexsha": "b42c78b393098c8b678bb21bd4a48cc41028141b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2018-07-25T16:30:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:44:32.000Z", "max_issues_repo_path": "libs/layers/box.py", "max_issues_repo_name": "FullStackD3vs/Detectron-PYTORCH", "max_issues_repo_head_hexsha": "b42c78b393098c8b678bb21bd4a48cc41028141b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-08-06T06:25:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-30T03:41:04.000Z", "max_forks_repo_path": "libs/layers/box.py", "max_forks_repo_name": "FullStackD3vs/Detectron-PYTORCH", "max_forks_repo_head_hexsha": "b42c78b393098c8b678bb21bd4a48cc41028141b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2019-01-15T08:42:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-25T22:35:29.000Z", "avg_line_length": 36.7025316456, "max_line_length": 103, "alphanum_fraction": 0.592171064, "include": true, "reason": "import numpy", "num_tokens": 3237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.2782567937024021, "lm_q1q2_score": 0.1564294306313178}}
{"text": "# -*- coding: utf-8 -*-\n# pylint: disable=bad-whitespace\n'''Module that defines classes for crystal cell manipulation and symmtetry operation\n\nThe ``cell`` class and its subclasses accept the following kwargs when being instantialized:\n\n    - coordSys (str): Coordinate system for the internal positions,\n      either \"D\" (Direct, default) or \"C\" (Cartesian)\n    - allRelax (bool) : default selective dynamics option for atoms.\n      Set True (default) to allow all DOFs to relax\n    - selectDyn (dict) : a dictionary with key-value pair as ``int: [bool, bool, bool]``, \n      which controls the selective dynamic option for atom with the particular index \n      (starting from 0). Default is an empty ``dict``\n    - comment (str): message about the cell\n    - reference (str): the reference where the lattice structure is derived.\n\nWhen other keyword are parsed, they will be filtered out and no exception will be raised\n'''\nfrom collections import OrderedDict\nfrom numbers import Real\n\nimport numpy as np\n\nfrom mykit.core.constants import PI\nfrom mykit.core.log import Verbose\nfrom mykit.core.numeric import Prec\nfrom mykit.core.unit import LengthUnit\nfrom mykit.core.utils import (Cif, get_latt_consts_from_latt_vecs,\n                              get_str_indices)\n\n\n# ==================== classes ====================\nclass CellError(Exception):\n    '''Exception in cell module\n    '''\n    pass\n\n\nclass Cell(Prec, Verbose, LengthUnit):\n    '''Cell structure class\n\n    Args:\n        latt (array-like) : The lattice vectors\n        atoms (list of str) : The list of strings of type for each atom \n        corresponding to the member in pos\n        pos (array-like) : The internal coordinates of atoms\n        unit (str): the unit, in lower case, either \"ang\" (default) or \"au\".\n\n    Note:\n        see ``cell`` module docstring for acceptable kwargs for ``Cell`` and its subclasses\n\n    Examples:\n    >>> Cell([[5.0, 0.0, 0.0], [0.0, 5.0, 0.0], [0.0, 0.0, 5.0]], [\"C\"], [[0.0, 0.0, 0.0]])\n    <mykit.core.cell.Cell>\n    '''\n\n    _error = CellError\n\n    def __init__(self, latt, atoms, pos, unit='ang', **kwargs):\n\n        self.comment = 'Default Cell class'\n        self.__reference = ''\n        self.__allRelax = True\n        self.__selectDyn = {}\n        self.__coordSys = 'D'\n\n        try:\n            self.__latt = np.array(latt, dtype=self._dtype)\n            self.__pos = np.array(pos, dtype=self._dtype)\n        except ValueError as _err:\n            raise self._error(\n                \"Fail to create cell and pos array. Please check.\")\n        LengthUnit.__init__(self, lunit=unit)\n        self.__atoms = [_a.capitalize() for _a in atoms]\n        self.__parse_cellkw(**kwargs)\n        # check input consistency\n        self.__check_consistency()\n        # move all atoms into the lattice (0,0,0)\n        # self.move_atoms_to_first_lattice()\n        # sanitize atoms arrangement\n        self.__sanitize_atoms()\n\n    def __len__(self):\n        return len(self.__atoms)\n\n    def __getitem__(self, index):\n        if isinstance(index, int):\n            return self.__pos[index, :]\n        if isinstance(index, str):\n            return self.get_sym_index(index)\n        raise self._error(\"atom index or symbol {} not found\".format(index))\n\n    def __str__(self):\n        return \"{}\\nLattice:\\n{}\\nAtoms: {}\\nPositions:\\n{}\\nUnit: {}\\nCoordinates in {}\".format(\n            self.comment, self.latt, self.atoms, self.pos, self.unit, self.coordSys)\n\n    def __repr__(self):\n        return self.__str__()\n\n    def __parse_cellkw(self, **kwargs):\n        if 'coordSys' in kwargs:\n            self.__coordSys = kwargs['coordSys'].upper()\n        if \"allRelax\" in kwargs:\n            self.__allRelax = kwargs[\"allRelax\"]\n        if \"selectDyn\" in kwargs:\n            self.__selectDyn = kwargs[\"selectDyn\"]\n        if \"reference\" in kwargs:\n            self.__reference = \"{}\".format(kwargs[\"reference\"])\n        if \"comment\" in kwargs:\n            self.comment = \"{}\".format(kwargs[\"comment\"])\n\n    def get_cell(self):\n        '''Purge out the cell, atoms and pos.\n\n        ``cell``, ``atoms`` and ``pos`` are the minimal for constructing ``Cell``\n        and its subclasses.\n        They can also be used to build sysmetry operations with spglib utilities.\n        '''\n        return self.__latt, self.__atoms, self.__pos\n\n    def get_kwargs(self):\n        '''return all kwargs useful to constract program-dependent cell input from ``Cell`` instance\n\n        Returns :\n            dictionary that can be parsed to ``create_from_cell`` class method.\n        '''\n        _d = {\n            \"unit\": self._lunit,\n            \"coordSys\": self.__coordSys,\n            \"comment\": self.comment,\n            \"reference\": self.__reference,\n            \"allRelax\": self.__allRelax,\n            \"selectDyn\": self.__selectDyn\n        }\n        return _d\n\n    def get_reference(self):\n        '''Return the reference of the structure\n        '''\n        return self.__reference\n\n    def __check_consistency(self):\n        try:\n            assert self.__coordSys in [\"C\", \"D\"]\n            assert np.shape(self.__latt) == (3, 3)\n            assert self.natoms > 0\n            assert np.shape(self.__pos) == (self.natoms, 3)\n        except AssertionError:\n            raise self._error(\"Invalid cell setup\")\n        # ? switch automatically, or let the user deal with it\n        try:\n            assert self.vol > 0\n        except AssertionError:\n            raise self._error(\n                \"Left-handed system found (vol<0). Switch two vector.\")\n\n    def _switch_two_atom_index(self, iat1, iat2):\n        '''switch the index of atoms with index iat1 and iat2\n\n        Except ``__pos`` and ``__atoms``,\n        this method should also deals possible switch in other positional\n        attributes, e.g.\n\n        - ``selectDyn`` (DONE)\n\n        Note that this method is mainly for sorting use, and does NOT change\n        the geometry of the cell at all.\n        '''\n        try:\n            assert iat1 in range(self.natoms)\n            assert iat2 in range(self.natoms)\n            assert iat1 != iat2\n        except AssertionError:\n            raise self._error(\n                \"Fail to switch two atoms with indices {} and {}\".format(iat1, iat2))\n\n        self.__pos[[iat1, iat2]] = self.__pos[[iat2, iat1]]\n        self.__atoms[iat1], self.__atoms[iat2] = self.__atoms[iat2], self.__atoms[iat1]\n\n        _sfd1 = self.__selectDyn.pop(iat1, [])\n        _sfd2 = self.__selectDyn.pop(iat2, [])\n        if _sfd1 != []:\n            self.__selectDyn.update({iat2: _sfd1})\n        if _sfd2 != []:\n            self.__selectDyn.update({iat1: _sfd2})\n\n    def move_atoms_to_first_lattice(self):\n        '''Move all atoms into the lattice (0,0,0).\n\n        For Cartisian system, the move is achieved by first\n        converting to and then back from direct system.\n        By this process, each component of the coordinate (in direct system)\n        belongs to [0,1)\n        '''\n        if self.coordSys == \"D\":\n            self.__pos = self.__pos - np.floor(self.__pos)\n        elif self.coordSys == \"C\":\n            self.coordSys = \"D\"\n            self.__pos = self.__pos - np.floor(self.__pos)\n            self.coordSys = \"C\"\n\n    def get_sym_index(self, csymbol):\n        '''Get the indices of atoms with element symbol ``csymbol``\n\n        Note that this is equivalent to ``cell[csymbol]``, given cell an instance of ``Cell``.\n\n        Args:\n            csymbol (str) : chemical-symbol-like identifier\n        '''\n        assert isinstance(csymbol, str)\n        return get_str_indices(self.atoms, csymbol.capitalize())\n\n    # * Sorting method\n    def __bubble_sort_atoms(self, key, indices, reverse=False):\n        '''sort atoms with bubble sort under various scenarios\n\n        The smaller value will appear earlier, if ``reverse`` is left\n        as False.\n        In both cases, when two same values are compared,\n        current bubble will just break.\n\n        Args:\n            key (natom-member list): the key value to be sorted\n            indices (iterable): the indices of the atoms to be sorted\n            reverse (bool): if set True, larger value appears earlier\n        '''\n        _depth = 1\n        # self.print_log(\"Bubble sort with key:\", key, \", indices:\", indices, level=3, depth=_depth)\n        __ind = list(indices)\n        __key = [key[_i] for _i in __ind]\n        _n = len(__ind)\n        __sorted = True\n        for _i in range(_n - 1):\n            _li = _i\n            _ri = _i+1\n            # self.print_log(\"Check index: \", _i, level=3, depth=_depth+2)\n            __dict = {True: __key[_li] > __key[_ri],\n                      False: __key[_li] < __key[_ri]}\n            if not __dict[reverse]:\n                __sorted = False\n                break\n        if not __sorted:\n            for _i in range(1, _n):\n                _j = _i\n                # self.print_log(\"Sorting size {}\".format(_i+1), level=3, depth=_depth+1)\n                while _j > 0:\n                    _li = _j-1\n                    _ri = _j\n                    __dict = {True: __key[_ri] > __key[_li],\n                              False: __key[_ri] < __key[_li]}\n                    if __dict[reverse]:\n                        self._switch_two_atom_index(__ind[_li], __ind[_ri])\n                        __key[_li], __key[_ri] = __key[_ri], __key[_li]\n                        _j -= 1\n                    else:\n                        break\n                # self.print_log(\"Sorting size {} done\".format(_i+1), level=3, depth=_depth+1)\n        # self.print_log(\"Bubble sort done\", level=3, depth=_depth)\n\n    def __sanitize_atoms(self):\n        '''Sanitize the atoms arrangement after initialization.\n\n        It mainly deals with arbitrary input of ``atoms`` when initialized.\n        '''\n        self.__bubble_sort_atoms(self.typeIndex, range(self.natoms))\n\n    def sort_pos(self, axis=3, reverse=False):\n        '''Sort the atoms by its coordinate along axis.\n\n        The ``atoms`` list will not change by sorting, i.e. the sorting is performed\n        within each atomic group.\n        If ``reverse`` is False, atom with higher coordinate in lattice (0,0,0)\n        will appear earlier, otherwise later.\n\n        This behavior is opposite to ``sort`` functions, in spirit of that surfaces are often\n        placed at high along one axis, and sorting in descending order makes the surface\n        appear first and easy to modify.\n\n        Args :\n            axis (1,2,3)\n            reverse (bool)\n        '''\n        try:\n            assert axis in range(1, 4)\n            assert isinstance(reverse, bool)\n        except AssertionError:\n            raise self._error()\n        __sortKeys = self.pos[:, axis-1]\n        # self.print_log(\"__sortKeys in sort_pos\", __sortKeys, level=3)\n        for _at in self.atomTypes:\n            __ind = self.get_sym_index(_at)\n            self.__bubble_sort_atoms(__sortKeys, __ind, reverse=not reverse)\n\n    # * Cell manipulation\n    def scale(self, scale):\n        '''Scale the lattice, i.e. increase the lattice by ``scale`` time\n        '''\n        try:\n            assert isinstance(scale, Real)\n            assert scale > 0.0\n        except AssertionError:\n            raise self._error(\"scale must be positive real\")\n        self.__latt = self.__latt * scale\n        if self.__coordSys == \"C\":\n            self.__pos = self.__pos * scale\n\n    def add_atom(self, atom, coord, sdFlag=None):\n        '''Add an atom with coordinate and selective dynamic flags\n\n        Args:\n            atom (str): the chemical symbol of the atom to add\n            coord (array-like): the coordinate of atom in ``Cell`` coordinate system\n            sdFlag (list of 3 bools): \n        '''\n        try:\n            assert isinstance(atom, str)\n        except:\n            raise self._error(\n                \"atom should be string, received {}\".format(type(atom)))\n        try:\n            newPos = np.vstack([self.__pos, coord])\n        except ValueError:\n            raise self._error(\"Invalid coordinate: {}\".format(coord))\n        if sdFlag is not None:\n            self.__set_sdFlags({self.natoms: sdFlag})\n        self.__pos = newPos\n        self.__atoms.append(atom)\n        self.move_atoms_to_first_lattice()\n        self.__sanitize_atoms()\n\n    # TODO move atom\n    def __move(self, ia):\n        raise NotImplementedError\n\n    def __move_all(self, shift):\n        '''Move all atoms by a shift\n        '''\n        assert np.shape(shift) == (3,)\n        np.add(self.__pos, shift, out=self.__pos)\n\n    @property\n    def center(self):\n        '''Calculate the center of all atoms in the cell\n        '''\n        assert self.coordSys == \"D\"\n        _posSum = np.zeros(3, dtype=self._dtype)\n        _n = 0\n        for i in range(self.natoms):\n            _dupcs, _dn = periodic_duplicates_in_cell(self.__pos[i, :])\n            for _dupc in _dupcs:\n                np.add(_posSum, _dupc/float(_dn), _posSum)\n        # _posSum = np.sum(self.__pos, axis=0)\n        # check periodic duplicate, by recognizing number of zeros in pos.\n        # _dup = 3 - np.count_nonzero(self.__pos, axis=1)\n        # _dup = np.power(2, _dup)\n        # _n = np.sum(_dup)\n        # _posSum = np.sum(self.__pos * _dup[:, None], axis=0)\n        return _posSum / self.natoms\n\n    def centering(self, axis=0):\n        '''Centering the atoms along axes. Mainly use for slab model.\n\n        TODO:\n            For now not work when there is atom at origin along the axis\n\n        Args:\n            axis (int or iterable of int) : the axes along which the atoms will be centered.\n        '''\n        _aList = axis_list(axis)\n        _wasCart = self.coordSys == \"C\"\n        if _wasCart:\n            self.coordSys = \"D\"\n        # get the geometric center of all atoms\n        _center = self.center\n        _shift = np.array([0.5, 0.5, 0.5], dtype=self._dtype) - _center\n\n        for i in range(3):\n            ia = i + 1\n            if ia not in _aList:\n                _shift[i] = 0.0\n        self.__move_all(_shift)\n        #     if self.check_vacuum_pos(zdirt):\n        #         self.__print(\"  - Vacuum in the middle detected. Not supported currently. Pass.\")\n        #         continue\n        #     else:\n        #         surf_atom = [self.check_extreme_atom(0.0,zdirt,False,1.0),self.check_extreme_atom(0.0,zdirt,True,1.0)]\n        #         # debug\n        #         # print surf_atom\n        #         shift = 0.5 - sum([self.innerpos[i-1][iz] for i in surf_atom])/2.0\n        #         self.action_shift(shift,zdirt)\n        # self.__print(\" Complete centering.\")\n        if _wasCart:\n            self.coordSys = \"C\"\n\n    @property\n    def a(self):\n        '''Lattice vectors\n        '''\n        return self.__latt\n\n    @property\n    def alen(self):\n        '''Length of lattice vectors\n        '''\n        return np.array([np.linalg.norm(x) for x in self.__latt], dtype=self._dtype)\n\n    @property\n    def lattConsts(self):\n        '''Lattice constant of the cell, i.e., a, b, c, alpha, beta, gamma (in degree)\n        '''\n        return get_latt_consts_from_latt_vecs(self.__latt)\n\n    @property\n    def latt(self):\n        '''Lattice vectors\n        '''\n        return self.__latt\n\n    @property\n    def atoms(self):\n        '''list.'''\n        return self.__atoms\n\n    @property\n    def pos(self):\n        '''array.'''\n        return self.__pos\n\n    @property\n    def unit(self):\n        '''str.'''\n        return self._lunit\n\n    @unit.setter\n    def unit(self, u):\n        coef = self._get_lunit_conversion(u)\n        if coef != 1:\n            if self.__coordSys == \"C\":\n                self.__pos = self.__pos * coef\n            self.__latt = self.__latt * coef\n            self._lunit = u.lower()\n\n    @property\n    def coordSys(self):\n        '''coordinate system\n        '''\n        return self.__coordSys\n\n    @coordSys.setter\n    def coordSys(self, s):\n        _s = s.upper()\n        if _s != self.__coordSys:\n            _convDict = {\"C\": self.__latt, \"D\": np.linalg.inv(self.__latt)}\n            _conv = _convDict.get(_s)\n            if _conv is not None:\n                self.__pos = np.matmul(self.__pos, _conv)\n                self.__coordSys = _s\n            else:\n                info = \"Only support \\\"D\\\" direct or fractional and \\\"C\\\" Cartisian coordinate.\"\n                raise self._error(info)\n\n    @property\n    def atomTypes(self):\n        '''All atom types in the cell\n        '''\n        _d = OrderedDict.fromkeys(self.__atoms)\n        return list(_d.keys())\n\n    @property\n    def typeMapping(self):\n        '''Map index (int) to atom type (str)\n        '''\n        _ats = self.atomTypes\n        _dict = {}\n        for i, _at in enumerate(_ats):\n            _dict.update({i: _at})\n        return _dict\n\n    @property\n    def typeIndex(self):\n        '''Indices of atom type of all atoms\n        '''\n        _ats = self.atomTypes\n        _dict = {}\n        for i, _at in enumerate(_ats):\n            _dict.update({_at: i})\n        return [_dict[_a] for _a in self.__atoms]\n\n    @property\n    def vol(self):\n        '''Volume of the cell\n        '''\n        return np.linalg.det(self.__latt)\n\n    @property\n    def natoms(self):\n        '''Int. Total number of atoms\n        '''\n        return len(self.__atoms)\n\n    @property\n    def useSelDyn(self):\n        if self.__allRelax and not bool(self.__selectDyn):\n            return False\n        return True\n\n    @property\n    def recpLattIn2Pi(self):\n        '''Reciprocal lattice vectors in 2Pi unit^-1\n        '''\n        b = []\n        for i in range(3):\n            j = (i + 1) % 3\n            k = (i + 2) % 3\n            b.append(np.cross(self.latt[j, :], self.latt[k, :]))\n        return np.array(b, dtype=self._dtype) / self.vol\n\n    @property\n    def bIn2Pi(self):\n        '''Alias to ``recpLattIn2Pi``\n        '''\n        return self.recpLattIn2Pi\n\n    @property\n    def recpLatt(self):\n        '''Reciprocal lattice vectors in unit^-1\n        '''\n        return self.bIn2Pi * 2.0E0 * PI\n\n    @property\n    def b(self):\n        '''Alias of ``recpLatt``\n        '''\n        return self.recpLatt\n\n    @property\n    def blen(self):\n        '''Length of reciprocal lattice vector in unit^-1\n        '''\n        return np.array([np.linalg.norm(x) for x in self.b], dtype=self._dtype)\n\n    # * selective dynamics related\n    def fix_all(self):\n        '''Fix all atoms.\n        '''\n        self.__selectDyn = {}\n        self.__allRelax = False\n\n    def relax_all(self):\n        '''Relax all atoms.\n        '''\n        self.__selectDyn = {}\n        self.__allRelax = True\n\n    def set_fix(self, *iats, axis=0):\n        '''Fix the atoms with index in iats\n\n        Args:\n            iats (list of int): the indices of atoms to fix\n            axis (int or list): the axes along which the position of atom is fixed\n                It can be 0|1|2|3, or a list with all its members 1|2|3\n        '''\n        if len(iats) != 0:\n            _new = {}\n            for _ia in iats:\n                if _ia in range(self.natoms):\n                    _new.update(\n                        {_ia: select_dyn_flag_from_axis(axis, relax=False)})\n            self.__set_sdFlags(_new)\n\n    def set_relax(self, *iats, axis=0):\n        '''Relax the atoms with index in iats\n\n        Args:\n            iats (list of int): the indices of atoms to relax\n            axis (int or list): the axes along which the position of atom is relaxed\n                It can be 0|1|2|3, or a list with all its members 1|2|3\n        '''\n        if len(iats) != 0:\n            _new = {}\n            for _ia in iats:\n                if _ia in range(self.natoms):\n                    _new.update(\n                        {_ia: select_dyn_flag_from_axis(axis, relax=True)})\n            self.__set_sdFlags(_new)\n\n    def relax_from_top(self, n, axis=3):\n        '''Set all atoms fixed, and relax the n atoms from top along axis\n        '''\n        pass\n\n    def fix_from_center(self, n, axis=3):\n        '''Set all atoms relaxed, and fix the n atoms from the middle along axis\n        '''\n        pass\n\n    def __set_sdFlags(self, selectDyn):\n        try:\n            assert isinstance(selectDyn, dict)\n        except AssertionError:\n            raise self._error(\"need dictionary to set selective dynamics\")\n        for _k, flag in selectDyn.items():\n            try:\n                assert isinstance(flag, list)\n                assert len(flag) == 3\n                assert all([isinstance(_x, bool) for _x in flag])\n            except AssertionError:\n                raise self._error(\"Bad flag for selective dynamics\")\n        self.__selectDyn.update(selectDyn)\n\n    def sdFlags(self, ia=-1):\n        '''Return the selective dynamic flag (bool) of atom\n\n        Args:\n            ia (int) : index of atom\n\n        Returns:\n            3-member list, if ia is in range(natoms),\n            otherwise natoms-member list, each member a 3-member list\n            as the flag for that atom\n        '''\n        # self.print_log(\"Global selective dynamics flag: {}\".format(self.__allRelax), level=3)\n        if ia in self.__selectDyn:\n            # self.print_log(\"Found custom flag in __selectDyn for atom {}\".format(ia), depth=1, level=3)\n            _flag = self.__selectDyn[ia]\n        elif ia in range(self.natoms):\n            # self.print_log(\"Use global flag for atom {}\".format(ia), level=3, depth=1)\n            _flag = [self.__allRelax, ] * 3\n        else:\n            _flag = [[self.__allRelax, ]*3 for _i in range(self.natoms)]\n            for i in self.__selectDyn:\n                _flag[i] = self.__selectDyn[i]\n        return _flag\n\n    def get_spglib_input(self):\n        '''Return the input necessary for spglib to get symmetry\n\n        Returns:\n            cell (3,3), pos (n,3), index of atom type (n), with n = self.natoms\n        '''\n        return self.latt, self.pos, self.typeIndex\n\n    # * Factory methods\n    @classmethod\n    def read_from_json(cls, pathJson):\n        '''Initialize a ``Cell`` instance from a JSON file\n\n        If \"factory\" key does not exist, it will search for the postional arguments,\n        i.e. \"latt\", \"atoms\" and \"pos\" keys. Raise when any of them does not exist.\n\n        Args:\n            pathJson (str): the path of JSON file\n        '''\n        import json\n        import os\n        if pathJson is None or not os.path.isfile(pathJson):\n            raise cls._error(\"JSON file not found: {}\".format(pathJson))\n        with open(pathJson, 'r') as h:\n            try:\n                js = json.load(h)\n            except json.JSONDecodeError:\n                raise cls._error(\n                    \"invalid JSON file for cell: {}\".format(pathJson))\n        pargs = []\n        factoryDict = {\n            \"bravais_oP\": (cls.bravais_oP, (\"atom\", \"a\", \"b\", \"c\")),\n            \"bravais_oI\": (cls.bravais_oI, (\"atom\", \"a\", \"b\", \"c\")),\n            \"bravais_oF\": (cls.bravais_oF, (\"atom\", \"a\", \"b\", \"c\")),\n            \"bravais_cP\": (cls.bravais_cP, (\"atom\", \"a\")),\n            \"bravais_cI\": (cls.bravais_cI, (\"atom\", \"a\")),\n            \"bravais_cF\": (cls.bravais_cF, (\"atom\", \"a\")),\n            \"perovskite\": (cls.perovskite, (\"atom1\", \"atom2\", \"atom3\", \"a\")),\n            \"zincblende\": (cls.zincblende, (\"atom1\", \"atom2\", \"a\")),\n            \"diamond\": (cls.diamond, (\"atom\", \"a\")),\n            \"wurtzite\": (cls.wurtzite, (\"atom1\", \"atom2\", \"a\")),\n            \"rutile\": (cls.rutile, (\"atom1\", \"atom2\", \"a\", \"c\", \"u\")),\n            \"anatase\": (cls.anatase, (\"atom1\", \"atom2\", \"a\", \"c\", \"u\")),\n            \"pyrite\": (cls.pyrite, (\"atom1\", \"atom2\", \"a\", \"u\")),\n            \"marcasite\": (cls.marcasite, (\"atom1\", \"atom2\", \"a\", \"b\", \"c\", \"v\", \"w\")),\n        }\n        # found factory key\n        if \"factory\" in js:\n            fac = js[\"factory\"]\n            # pop out latt, atoms and pos for safety\n            for arg in [\"latt\", \"atoms\", \"pos\"]:\n                js.pop(arg, None)\n            if fac in factoryDict:\n                # get positional argument\n                # print(fac)\n                try:\n                    m, reqPa = factoryDict[fac]\n                    for x in reqPa:\n                        pargs.append(js.pop(x))\n                    return m(*pargs, **js)\n                except KeyError:\n                    raise cls._error(\n                        \"Required key not found in JSON: {}\".format(x))\n            else:\n                raise cls._error(\"Factory method unavailable: {}\".format(fac))\n\n        for _i, arg in enumerate([\"latt\", \"atoms\", \"pos\"]):\n            v = js.pop(arg, None)\n            if v is None:\n                raise cls._error(\n                    \"invalid JSON file for cell: {}. No {}\".format(pathJson, arg))\n            pargs.append(v)\n        return cls(*pargs, **js)\n\n    @classmethod\n    def read_from_cif(cls, pathCif):\n        '''Read from Cif file and return a instance by use of PyCIFRW\n        '''\n        cif = Cif(pathCif)\n        kw = {\"coordSys\": \"D\", \"reference\": cif.get_reference_str(), }\n        # use chemical name as comment\n        kw['comment'] = ', '.join(cif.get_chemical_name()) + ' type'\n        latt = cif.get_lattice_vectors()\n        atoms, pos = cif.get_all_atoms()\n        return cls(latt, atoms, pos, **kw)\n\n    @classmethod\n    def create_from_cell(cls, cell):\n        '''Create an ``Cell`` object from another ``Cell`` instance ``cell``.\n\n        This is for use of transformation between cells described \n        by different file formats.\n\n        Args:\n            cell : object of ``Cell`` or its subclasses\n\n        Returns:\n            a ``Cell`` object\n        '''\n        try:\n            assert isinstance(cell, Cell)\n        except AssertionError:\n            raise cls._error(\n                \"the input is not an object of Cell or its subclasses\")\n        kw = cell.get_kwargs()\n        return cls(*cell.get_cell(), **kw)\n\n    @classmethod\n    def _bravais_o(cls, kind, atom, a, b, c, **kwargs):\n        assert kind in [\"P\", \"I\", \"F\"]\n        _latt = [[a, 0.0, 0.0], [0.0, b, 0.0], [0.0, 0.0, c]]\n        if kind == \"P\":\n            _atoms = [atom, ]\n            _pos = [[0.0, 0.0, 0.0]]\n        if kind == \"I\":\n            _atoms = [atom, ]*2\n            _pos = [[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]]\n        if kind == \"F\":\n            _atoms = [atom, ]*4\n            _pos = [[0.0, 0.0, 0.0], [0.0, 0.5, 0.5],\n                    [0.5, 0.0, 0.5], [0.5, 0.5, 0.0]]\n        kwargs.pop(\"coordSys\", None)\n        return cls(_latt, _atoms, _pos, **kwargs)\n\n    @classmethod\n    def bravais_oP(cls, atom, a=1.0, b=2.0, c=3.0, **kwargs):\n        '''Generate a simple orthorhombic Bravais lattice\n\n        Args:\n            atom (str) : the chemical symbol of atom\n            a,b,c (float) : the lattice constants (a,b,c)\n            kwargs: keyword argument for ``Cell`` except ``coordSys``\n        '''\n        if \"comment\" not in kwargs:\n            kwargs.update(\n                {\"comment\": \"Simple orthorhombic lattice {}\".format(atom)})\n        return cls._bravais_o(\"P\", atom, a, b, c, **kwargs)\n\n    @classmethod\n    def bravais_oI(cls, atom, a=1.0, b=2.0, c=3.0, **kwargs):\n        '''Generate a body-centered orthorhombic Bravais lattice\n\n        Args:\n            atom (str) : the chemical symbol of atom\n            a,b,c (float) : the lattice constants (a,b,c)\n            kwargs: keyword argument for ``Cell`` except ``coordSys``\n        '''\n        if \"comment\" not in kwargs:\n            kwargs.update(\n                {\"comment\": \"Body-centered orthorhombic lattice {}\".format(atom)})\n        return cls._bravais_o(\"I\", atom, a, b, c, **kwargs)\n\n    @classmethod\n    def bravais_oF(cls, atom, a=1.0, b=2.0, c=3.0, **kwargs):\n        '''Generate a face-centered orthorhombic Bravais lattice\n\n        Args:\n            atom (str) : the chemical symbol of atom\n            a,b,c (float) : the lattice constants (a,b,c)\n            kwargs: keyword argument for ``Cell`` except ``coordSys``\n        '''\n        if \"comment\" not in kwargs:\n            kwargs.update(\n                {\"comment\": \"Face-centered orthorhombic lattice {}\".format(atom)})\n        return cls._bravais_o(\"F\", atom, a, b, c, **kwargs)\n\n    @classmethod\n    def bravais_cP(cls, atom, a=1.0, **kwargs):\n        '''Generate a simple cubic Bravais lattice, space group 221\n\n        Args:\n            atom (str) : the chemical symbol of atom\n            a (float) : the lattice constant (a)\n            kwargs: keyword argument for ``Cell`` except ``coordSys``\n        '''\n        _a = abs(a)\n        _latt = [[_a, 0.0, 0.0], [0.0, _a, 0.0], [0.0, 0.0, _a]]\n        _atoms = [atom]\n        _pos = [[0.0, 0.0, 0.0]]\n        kwargs.pop(\"coordSys\", None)\n        if \"comment\" not in kwargs:\n            kwargs.update({\"comment\": \"Simple cubic lattice {}\".format(atom)})\n        return cls(_latt, _atoms, _pos, **kwargs)\n\n    @classmethod\n    def bravais_cI(cls, atom, a=1.0, primitive=False, **kwargs):\n        '''Generate a body-centered cubic Bravais lattice\n\n        Args:\n            atom (str) : the chemical symbol of atom\n            a (float) : the lattice constant (a)\n            primitive (bool) : if set True, the primitive cell will be generated\n            kwargs: keyword argument for ``Cell`` except ``coordSys``\n        '''\n        _a = abs(a)\n        if primitive:\n            _latt = [[-_a/2.0, _a/2.0, _a/2.0],\n                     [_a/2.0, -_a/2.0, _a/2.0], [_a/2.0, _a/2.0, -_a/2.0]]\n            _atoms = [atom]\n            _pos = [[0.0, 0.0, 0.0]]\n        else:\n            _latt = [[_a, 0.0, 0.0], [0.0, _a, 0.0], [0.0, 0.0, _a]]\n            _atoms = [atom, ]*2\n            _pos = [[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]]\n        kwargs.pop(\"coordSys\", None)\n        if \"comment\" not in kwargs:\n            kwargs.update({\"comment\": \"BCC {}\".format(atom)})\n        return cls(_latt, _atoms, _pos, **kwargs)\n\n    @classmethod\n    def bravais_cF(cls, atom, a=1.0, primitive=False, **kwargs):\n        '''Generate a face-centered cubic Bravais lattice\n\n        Args:\n            atom (str) : the chemical symbol of atom\n            a (float) : the lattice constant (a)\n            primitive (bool) : if set True, the primitive cell will be generated\n            kwargs: keyword argument for ``Cell`` except ``coordSys``\n        '''\n        _a = abs(a)\n        if primitive:\n            _latt = [[0.0, _a/2.0, _a/2.0],\n                     [_a/2.0, 0.0, _a/2.0], [_a/2.0, _a/2.0, 0.0]]\n            _atoms = [atom]\n            _pos = [[0.0, 0.0, 0.0]]\n        else:\n            _latt = [[_a, 0.0, 0.0], [0.0, _a, 0.0], [0.0, 0.0, _a]]\n            _atoms = [atom, ]*4\n            _pos = [[0.0, 0.0, 0.0], [0.0, 0.5, 0.5],\n                    [0.5, 0.0, 0.5], [0.5, 0.5, 0.0]]\n        kwargs.pop(\"coordSys\", None)\n        if \"comment\" not in kwargs:\n            kwargs.update({\"comment\": \"FCC {}\".format(atom)})\n        return cls(_latt, _atoms, _pos, **kwargs)\n\n    @classmethod\n    def perovskite(cls, atom1=\"Ca\", atom2=\"Ti\", atom3=\"O\", a=1.0, **kwargs):\n        '''Generate a perovskit lattice\n\n        Args:\n            atom1 (str) : the chemical symbol of atom at vertices of cubic cell\n            atom2 (str) : the chemical symbol of atom at center of cubic cell\n            atom3 (str) : the chemical symbol of atom at faces of cubic cell\n            a (float) : the lattice constant (a)\n            primitive (bool) : if set True, the primitive cell will be generated\n            kwargs: keyword argument for ``Cell`` except ``coordSys``\n        '''\n        _a = abs(a)\n        _latt = [[_a, 0.0, 0.0], [0.0, _a, 0.0], [0.0, 0.0, _a]]\n        _atoms = [atom1, atom2, ] + [atom3, ]*3\n        _pos = [[0.0, 0.0, 0.0], [0.5, 0.5, 0.5], [\n            0.0, 0.5, 0.5], [0.5, 0.0, 0.5], [0.5, 0.5, 0.0]]\n        kwargs.pop(\"coordSys\", None)\n        if \"comment\" not in kwargs:\n            kwargs.update(\n                {\"comment\": \"Perovskite {}{}{}3\".format(atom1, atom2, atom3)})\n        return cls(_latt, _atoms, _pos, **kwargs)\n\n    @classmethod\n    def zincblende(cls, atom1=\"Zn\", atom2=\"O\", a=1.0, primitive=False, **kwargs):\n        '''Generate a zincblende lattice (space group 216)\n\n        ``atom1`` are placed at vertex and ``atom2`` at tetrahedron interstitial\n\n        Args:\n            atom1 (str): symbol of atom at vertex\n            atom2 (str): symbol of atom at tetrahedron interstitial\n            a (float): the lattice constant of the conventional cell.\n            primitive (bool): if set True, the primitive cell will be generated.\n            kwargs: keyword argument for ``Cell`` except ``coordSys``\n        '''\n        _a = abs(a)\n        if primitive:\n            _latt = [[0.0, _a/2.0, _a/2.0],\n                     [_a/2.0, 0.0, _a/2.0], [_a/2.0, _a/2.0, 0.0]]\n            _atoms = [atom1, atom2]\n            _pos = [[0.0, 0.0, 0.0],\n                    [0.25, 0.25, 0.25]]\n        else:\n            _latt = [[_a, 0.0, 0.0], [0.0, _a, 0.0], [0.0, 0.0, _a]]\n            _atoms = [atom1, ]*4 + [atom2, ]*4\n            _pos = [[0.0, 0.0, 0.0],\n                    [0.0, 0.5, 0.5],\n                    [0.5, 0.0, 0.5],\n                    [0.5, 0.5, 0.0],\n                    [0.25, 0.25, 0.25],\n                    [0.25, 0.75, 0.75],\n                    [0.75, 0.25, 0.75],\n                    [0.75, 0.75, 0.25]]\n        kwargs.pop(\"coordSys\", None)\n        if \"comment\" not in kwargs:\n            kwargs.update({\"comment\": \"Zincblende {}{}\".format(atom1, atom2)})\n        return cls(_latt, _atoms, _pos, **kwargs)\n\n    @classmethod\n    def rocksalt(cls, atom1=\"Na\", atom2=\"Cl\", a=1.0, primitive=False, **kwargs):\n        '''Generate a rocksalt lattice\n\n        ``atom1`` are placed at vertex and ``atom2`` at tetrahedron interstitial\n\n        Args:\n            atom1 (str): symbol of atom1 (set at vertex)\n            atom2 (str): symbol of atom2\n            a (float): the lattice constant of the conventional cell.\n            primitive (bool): if set True, the primitive cell will be generated.\n            kwargs: keyword argument for ``Cell`` except ``coordSys``\n        '''\n        _a = abs(a)\n        if primitive:\n            _latt = [[0.0, _a/2.0, _a/2.0],\n                     [_a/2.0, 0.0, _a/2.0], [_a/2.0, _a/2.0, 0.0]]\n            _atoms = [atom1, atom2]\n            _pos = [[0.0, 0.0, 0.0],\n                    [0.5, 0.5, 0.5]]\n        else:\n            _latt = [[_a, 0.0, 0.0], [0.0, _a, 0.0], [0.0, 0.0, _a]]\n            _atoms = [atom1, ]*4 + [atom2, ]*4\n            _pos = [[0.0, 0.0, 0.0],\n                    [0.0, 0.5, 0.5],\n                    [0.5, 0.0, 0.5],\n                    [0.5, 0.5, 0.0],\n                    [0.5, 0.0, 0.0],\n                    [0.0, 0.5, 0.0],\n                    [0.0, 0.0, 0.5],\n                    [0.5, 0.5, 0.5]]\n        kwargs.pop(\"coordSys\", None)\n        if \"comment\" not in kwargs:\n            kwargs.update({\"comment\": \"Rocksalt {}{}\".format(atom1, atom2)})\n        return cls(_latt, _atoms, _pos, **kwargs)\n        \n    @classmethod\n    def diamond(cls, atom=\"C\", a=1.0, primitive=False, **kwargs):\n        '''Generate a diamond lattice (space group 227)\n\n        Args:\n            atom (str): symbol of the atom\n            a (float): the lattice constant of the conventional cell.\n            primitive (bool): if set True, the primitive cell will be generated.\n            kwargs: keyword argument for ``Cell`` except ``coordSys``\n        '''\n        if \"comment\" not in kwargs:\n            kwargs.update({\"comment\": \"Diamond {}\".format(atom)})\n        return cls.zincblende(atom, atom, a=a, primitive=primitive, **kwargs)\n\n    @classmethod\n    def wurtzite(cls, atom1=\"Zn\", atom2=\"O\", a=1.0, **kwargs):\n        '''Generate a wurtzite lattice (space group 186)\n\n        Args:\n            atom1 (str): symbol of atom at vertices of lattice\n            atom2 (str): symbol of atom at edges of lattice\n            a (float): the lattice constant of the cell.\n            kwargs: keyword argument for ``Cell`` except ``coordSys``\n        '''\n        _a = abs(a)\n        _halfa = _a/2.0\n        _c = _a * np.sqrt(8.0/3)\n        _latt = [[_a, 0.0, 0.0],\n                 [-_halfa, np.sqrt(3)*_halfa, 0.0], [0.0, 0.0, _c]]\n        _atoms = [atom1, ]*2 + [atom2, ]*2\n        _pos = [[0.0, 0.0, 0.0],\n                [2.0/3, 1.0/3, 0.5],\n                [0.0, 0.0, 2.0/3],\n                [2.0/3, 1.0/3, 1.0/6]]\n        kwargs.pop(\"coordSys\", None)\n        if \"comment\" not in kwargs:\n            kwargs.update({\"comment\": \"Wurtzite {}{}\".format(atom1, atom2)})\n        return cls(_latt, _atoms, _pos, **kwargs)\n\n    @classmethod\n    def rutile(cls, atom1=\"Ti\", atom2=\"O\", a=1.0, c=2.0, u=0.31, **kwargs):\n        '''Generate a rutile lattice (space group 136)\n\n        Args:\n            atom1 (str): symbol of atom at vertex and center of lattice\n            atom2 (str): symbol of atom at face of lattice\n            a,c (float): the lattice constant of the cell.\n            u (float): the internal coordinate\n            kwargs: keyword argument for ``Cell`` except ``coordSys``\n        '''\n        try:\n            assert 0.0 < u < 1.0\n        except AssertionError:\n            raise cls._error(\n                \"Internal coordinate should be in (0,1), get {}\".format(u))\n        _a = abs(a)\n        _c = abs(c)\n        _latt = [[_a, 0.0, 0.0], [0.0, _a, 0.0], [0.0, 0.0, _c]]\n        _atoms = [atom1, ]*2 + [atom2, ]*4\n        _pos = [[0.0, 0.0, 0.0],\n                [0.5, 0.5, 0.5],\n                [u, u, 0.0],\n                [-u, -u, 0.0],\n                [0.5-u, 0.5+u, 0.5],\n                [0.5+u, 0.5-u, 0.5]]\n        kwargs.pop(\"coordSys\", None)\n        if \"comment\" not in kwargs:\n            kwargs.update({\"comment\": \"Rutile {}{}2\".format(atom1, atom2)})\n        return cls(_latt, _atoms, _pos, **kwargs)\n\n    @classmethod\n    def anatase(cls, atom1=\"Ti\", atom2=\"O\", a=3.7845, c=9.5143, u=0.2199,\n                primitive=False, **kwargs):\n        '''Generate an anatase lattice (space group 141).\n\n        Note:\n            This cell is not standardized.\n\n        Args:\n            atom1 (str): symbol of atom at vertex\n            atom2 (str): symbol of atom at face of lattice\n            a,c (float): the lattice constant of the conventional cell.\n            u (float): the internal coordinate, i.e. distance between two atoms in terms of c\n            kwargs: keyword argument for ``Cell`` except ``coordSys``\n        '''\n        try:\n            assert 0.0 < u < 1.0\n        except AssertionError:\n            raise cls._error(\n                \"Internal coordinate should be in (0,1), get {}\".format(u))\n        _a = abs(a)\n        _c = abs(c)\n        if primitive:\n            _latt = [[-_a/2, _a/2, _c/2],\n                     [_a/2, -_a/2, _c/2], [_a/2, _a/2, -_c/2]]\n            _atoms = [atom1, ]*2 + [atom2, ]*4\n            _pos = [[0.0, 0.0, 0.0],\n                    [0.75, 0.25, 0.5],\n                    [0.25-u, 0.75-u, 0.5],\n                    [0.25+u, 0.75+u, 0.5],\n                    [0.5+u,  0.5+u, 0.0],\n                    [0.5-u,  0.5-u, 0.0], ]\n        else:\n            _latt = [[_a, 0.0, 0.0], [0.0, _a, 0.0], [0.0, 0.0, _c]]\n            _atoms = [atom1, ]*4 + [atom2, ]*8\n            _pos = [[0.0, 0.0, 0.0],\n                    [0.5, 0.0, 0.25],\n                    [0.0, 0.5, 0.75],\n                    [0.5, 0.5, 0.5],\n                    [0.0, 0.0,   u],\n                    [0.0, 0.0,  -u],\n                    [0.5, 0.0, 0.25-u],\n                    [0.5, 0.0, 0.25+u],\n                    [0.0, 0.5, 0.75-u],\n                    [0.0, 0.5, 0.75+u],\n                    [0.5, 0.5, 0.5-u],\n                    [0.5, 0.5, 0.5+u]]\n        kwargs.pop(\"coordSys\", None)\n        if \"comment\" not in kwargs:\n            kwargs.update({\"comment\": \"Anatase {}{}2\".format(atom1, atom2)})\n        return cls(_latt, _atoms, _pos, **kwargs)\n\n    @classmethod\n    def pyrite(cls, atom1=\"Fe\", atom2=\"S\", a=5.4183, u=0.1174, **kwargs):\n        '''Generate a standardized pyrite lattice (space group 205).\n\n        Args:\n            atom1 (str): symbol of atom at vertex and face-center\n            atom2 (str): symbol of atom at edges\n            a (float): the lattice constant of the conventional cell.\n            u (float): the internal coordinate\n            kwargs: keyword argument for ``Cell`` except ``coordSys``\n        '''\n        _a = abs(a)\n        _latt = [[_a, 0.0, 0.0], [0.0, _a, 0.0], [0.0, 0.0, _a]]\n        _atoms = [atom1, ]*4 + [atom2, ]*8\n        _pos = [[0.0, 0.0, 0.0],\n                [0.0, 0.5, 0.5],\n                [0.5, 0.0, 0.5],\n                [0.5, 0.5, 0.0],\n                [0.5-u,     u,    -u],\n                [0.5+u,    -u,     u],\n                [-u, 0.5-u,     u],\n                [u, 0.5+u,    -u],\n                [u,    -u, 0.5-u],\n                [-u,     u, 0.5+u],\n                [0.5+u, 0.5+u, 0.5+u],\n                [0.5-u, 0.5-u, 0.5-u]]\n        kwargs.pop(\"coordSys\", None)\n        if \"comment\" not in kwargs:\n            kwargs.update({\"comment\": \"Pyrite {}{}2\".format(atom1, atom2)})\n        return cls(_latt, _atoms, _pos, **kwargs)\n\n    @classmethod\n    def marcasite(cls, atom1=\"Fe\", atom2=\"S\",\n                  a=4.4450, b=5.4151, c=3.3922,\n                  v=0.2066, w=0.3750, **kwargs):\n        '''Generate a standardized marcasite lattice (space group 58).\n\n        Args:\n            atom1 (str): symbol of atom at vertex and body-center\n            atom2 (str): symbol of the other atom\n            a, b, c (float): the lattice constants of the cell.\n            v, w(float): the internal coordinates\n            kwargs: keyword argument for ``Cell`` except ``coordSys``\n        '''\n        _a = abs(a)\n        _b = abs(b)\n        _c = abs(c)\n        _latt = [[_a, 0.0, 0.0], [0.0, _b, 0.0], [0.0, 0.0, _c]]\n        _atoms = [atom1, ]*2 + [atom2, ]*4\n        _pos = [[0.0, 0.0, 0.0],\n                [0.5, 0.5, 0.5],\n                [0.5+v, 0.5-w,    0.5],\n                [0.5-v, 0.5+w,    0.5],\n                [-v,    -w,    0.0],\n                [v,     w,    0.0], ]\n        kwargs.pop(\"coordSys\", None)\n        if \"comment\" not in kwargs:\n            kwargs.update({\"comment\": \"Marcasite {}{}2\".format(atom1, atom2)})\n        return cls(_latt, _atoms, _pos, **kwargs)\n\n\ndef atoms_from_sym_nat(syms, nats):\n    '''Generate ``atom`` list for ``Cell`` initilization from list of atomic symbols \n    and number of atoms\n\n    Args :\n        syms (list of str) : atomic symbols\n        nats (list of int) : number of atoms for each symbol\n\n    Returns :\n        a list of str, containing symbol of each atom in the cell\n\n    Examples:\n    >>> atoms_from_sym_nat([\"C\", \"Al\", \"F\"], [2, 3, 1])\n    [\"C\", \"C\", \"Al\", \"Al\", \"Al\", \"F\"]\n    '''\n    assert len(syms) == len(nats)\n    _list = []\n    for _s, _n in zip(syms, nats):\n        _list.extend([_s, ] * _n)\n    return _list\n\n\ndef sym_nat_from_atoms(atoms):\n    '''Generate lists of atomic symbols and number of atoms from whole atoms list\n\n    The order of appearence of the element is conserved in the output.\n\n    Args :\n        atoms (list of str) : symbols of each atom in the cell\n\n    Returns :\n        list of str : atomic symbols\n        list of int : number of atoms for each symbol\n\n    Examples:\n    >>> sym_nat_from_atoms([\"C\", \"Al\", \"Al\", \"C\", \"Al\", \"F\"])\n    [\"C\", \"Al\", \"F\"], [2, 3, 1]\n    '''\n    _syms = []\n    _natsDict = {}\n    for _at in atoms:\n        if _at in _syms:\n            _natsDict[_at] += 1\n        else:\n            _syms.append(_at)\n            _natsDict.update({_at: 1})\n    return _syms, [_natsDict[_at] for _at in _syms]\n\n\ndef select_dyn_flag_from_axis(axis, relax=False):\n    '''Generate selective dynamic flags, i.e. [bool, bool, bool]\n\n    Args:\n        relax (bool): if True, the flag for axis will be set as True.\n            Otherwise False\n    '''\n    assert isinstance(relax, bool)\n    _flag = [not relax, not relax, not relax]\n    _aList = axis_list(axis)\n    for _a in _aList:\n        _flag[_a-1] = not _flag[_a-1]\n    return _flag\n\n\ndef axis_list(axis):\n    '''Generate axis indices from ``axis``\n\n    Args:\n        axis (int or list of int)\n\n    Returns:\n        tuple\n    '''\n    _aList = []\n    if isinstance(axis, int):\n        if axis == 0:\n            _aList = [1, 2, 3]\n        if axis in range(1, 4):\n            _aList = [axis]\n    elif isinstance(axis, (list, tuple)):\n        _aSet = list(set(axis))\n        for _a in _aSet:\n            try:\n                assert isinstance(_a, int)\n            except AssertionError:\n                pass\n            else:\n                if _a == 0:\n                    _aList = [1, 2, 3]\n                    break\n                if _a in range(1, 4):\n                    _aList.append(_a)\n    return tuple(_aList)\n\n\ndef periodic_duplicates_in_cell(directCoord):\n    '''Return the coordinates and numbers of the duplicates of an atom\n    in a cell due to lattice translation symmetry\n\n    Args:\n        directCoord (array): the direct coordinate of an atom in the cell\n\n    Note:\n        The function works only when each component belongs to [0,1)\n\n    TODO:\n        Generalize this function to mirrors in n-th lattice shell\n\n    Returns:\n        tuple : the coordinates of all the atom duplicates due to transilational symmetry\n        int : the number of duplicates\n\n    Examples:\n    >>> periodic_duplicates_in_cell([0,0,0])\n    (([0, 0, 0], [1.0, 0, 0], [0, 1.0, 0], [1.0, 1.0, 0], [0, 0, 1.0], [1.0, 0, 1.0], [0, 1.0, 1.0], [1.0, 1.0, 1.0]), 8)\n    >>> periodic_duplicates_in_cell([0,0.4,0])\n    (([0, 0.4, 0], [1.0, 0.4, 0], [0, 0.4, 1.0], [1.0, 0.4, 1.0]), 4)\n    '''\n    from copy import deepcopy\n    _pos = np.array(directCoord, dtype=\"float64\")\n    assert np.shape(_pos) == (3,)\n    assert all(_pos - 1.0 < 0)\n    _dupcs = []\n    _dupcs.append(directCoord)\n    # non-zero component\n    _n = 2 ** (3 - np.count_nonzero(_pos))\n    _iszero = _pos == 0\n    for i in range(3):\n        if _iszero[i]:\n            _trans = deepcopy(_dupcs)\n            for _c in _trans:\n                _c[i] = 1.0\n            _dupcs.extend(_trans)\n    return tuple(_dupcs), _n\n", "meta": {"hexsha": "509e3fcce550b021079513e342a7ab44f25db440", "size": 45956, "ext": "py", "lang": "Python", "max_stars_repo_path": "mykit/core/cell.py", "max_stars_repo_name": "minyez/mykit", "max_stars_repo_head_hexsha": "911413120c081be2cfcaef06d62dc40b2abd2747", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-01-02T09:17:54.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-26T07:15:59.000Z", "max_issues_repo_path": "mykit/core/cell.py", "max_issues_repo_name": "minyez/mykit", "max_issues_repo_head_hexsha": "911413120c081be2cfcaef06d62dc40b2abd2747", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-03-06T03:16:12.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-14T14:36:01.000Z", "max_forks_repo_path": "mykit/core/cell.py", "max_forks_repo_name": "minyez/mykit", "max_forks_repo_head_hexsha": "911413120c081be2cfcaef06d62dc40b2abd2747", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8471138846, "max_line_length": 121, "alphanum_fraction": 0.522673862, "include": true, "reason": "import numpy", "num_tokens": 13059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.2942149659744614, "lm_q1q2_score": 0.15628974771247467}}
{"text": "# -*- coding: utf-8 -*-\nimport collections\nimport itertools\n\nimport numpy as np\n\nfrom . import builder\nfrom . import activity\nfrom . import constants\nfrom . import eqsolver\nfrom . import solution\nfrom . import fugacity\nfrom . import logmaker\nfrom . import sequencer\n\n\nACTIVITY_MODEL_MAP = {\n    \"IDEAL\": activity.setup_ideal,\n    \"DEBYE_LIMITING\": activity.setup_debye,\n    \"DEBYE\": activity.setup_extended_debye,\n    \"EXTENDED_DEBYE\": activity.setup_extended_debye,\n    \"PITZER\": activity.setup_pitzer,\n}\n\nclass EquilibriumSystem():\n    \"\"\"\n    Class for setting and calculate equilibria\n\n    Attributes\n    ----------\n    base_species: List[str]\n        Base aqueous species in system\n    base_elements: List[str]\n        Base elements in system\n    species: List[str]\n        Species in system\n    reactions: List[dict]\n        Reactions in system\n    solid_reactions: List[dict]\n        Solid Reactions in system\n    formula_matrix: ndarray\n        Formula matrix of system\n    stoich_matrix: ndarray\n        Stoichiometric matrix of system\n    solid_formula_matrix: ndarray\n        Solid formula matrix of system\n    solid_stoich_matrix: ndarray\n        Solid stoichiometric matrix of system\n    activity_model: str\n        Activity model for equilibrium\n    calculate_water_activity: bool\n        Whether to calculate water activity\n    solverlog: None or str\n        The log for last solver\n    solvertype: None or str\n        The type of last solver\n    \"\"\"\n\n    def __init__(self, components, from_elements=False, activity_model=\"EXTENDED_DEBYE\",\n                 calculate_water_activity=False):\n        \"\"\"\n        Parameters\n        ----------\n        components: List[str]\n            Base components for defining reaction system.\n        from_elements: bool\n            If False, base components are species\n            If True, base components are elements, and representative species\n            are chosen for these elements (see builder.ELEMENT_SPECIES_MAP).\n            Current elements implemented are\n            C, Ca, Cl, Na, S, Ba, Mg, Fe, K, Sr,\n            N, Cd, Li, Cu, Al, Br, F, Mn, P, Pb, Zn\n        activity_model: str\n            Model for activity coefficients. One of\n            'IDEAL', 'DEBYE', 'EXTENDED_DEBYE', 'PITZER'\n        calculate_water_activity: bool\n            Whether to calculate water activity or assume it to be unit\n        \"\"\"\n        self.base_species, self.base_elements = \\\n            _prepare_base(components, from_elements)\n        self.species, self.reactions, self.solid_reactions, self.gas_reactions = \\\n            self._initialize_species_reactions()\n        self.formula_matrix, self.stoich_matrix = \\\n            self._make_formula_and_stoich_matrices()\n        self.solid_formula_matrix, self.solid_stoich_matrix = \\\n            self._make_solid_formula_and_stoich_matrices()\n        self.gas_formula_matrix, self.gas_stoich_matrix = \\\n            self._make_gas_formula_and_stoich_matrices()\n        self.activity_model = activity_model\n        self.calculate_water_activity = calculate_water_activity\n        self.solverlog = None\n        self.solvertype = None\n        self._activity_model_func = ACTIVITY_MODEL_MAP[activity_model](\n            self.solutes, calculate_water_activity)\n        self._fugacity_coefficient_function = lambda x, TK, P: 0.0\n        self._x_molal = None\n        self._x_act = None\n\n    def update_system(self,\n                      possible_reactions=None,\n                      possible_solid_reactions=None,\n                      possible_gas_reactions=None):\n        self.species, self.reactions, self.solid_reactions, self.gas_reactions = \\\n            self._initialize_species_reactions(possible_reactions,\n                                               possible_solid_reactions,\n                                               possible_gas_reactions)\n        self.formula_matrix, self.stoich_matrix = \\\n            self._make_formula_and_stoich_matrices()\n        self.solid_formula_matrix, self.solid_stoich_matrix = \\\n            self._make_solid_formula_and_stoich_matrices()\n        self.gas_formula_matrix, self.gas_stoich_matrix = \\\n            self._make_gas_formula_and_stoich_matrices()\n        self.solverlog = None\n        self.solvertype = None\n        self._activity_model_func = ACTIVITY_MODEL_MAP[self.activity_model](\n            self.solutes, self.calculate_water_activity)\n        self._fugacity_coefficient_function = lambda x, TK, P: 0.0\n        self._x_molal = None\n        self._x_act = None\n    \n    def set_activity_functions(self, activity_model=\"EXTENDED_DEBYE\",\n                               calculate_water_activity=False):\n        \"\"\"\n        Set activity model and function\n\n        Parameters\n        ----------\n        activity_model: str\n            One of ['IDEAL', 'DEBYE', 'EXTENDED_DEBYE', 'PITZER']\n        \"\"\"\n        self.activity_model = activity_model\n        self.calculate_water_activity = calculate_water_activity\n        activity_setup = ACTIVITY_MODEL_MAP[activity_model]\n        self._activity_model_func = activity_setup(self.solutes,\n                                                   calculate_water_activity)\n\n    def activity_function(self, molals, TK):\n        \"\"\"\n        Activity function for aqueous species\n\n        Parameters\n        ----------\n        molals: ndarray\n            Molals of solutes\n        TK: float\n            Temperature in Kelvin\n\n        Returns\n        -------\n        ndarray of activities (water is the first one, other solutes in molals order)\n        \"\"\"\n        # molal to activities (including water)\n        activity_model_res = self._activity_model_func(molals, TK)\n        osmotic_coefficient, loggamma = \\\n            activity_model_res[0], activity_model_res[1:]\n        if not self.calculate_water_activity:\n            logact_water = 0.0\n        else:\n            logact_water = osmotic_coefficient * \\\n                constants.MOLAR_WEIGHT_WATER*np.sum(molals)\n        logact_solutes = loggamma + np.log10(molals)\n        logact = np.insert(logact_solutes, 0, logact_water)\n        return logact\n\n    def gas_activity_function(self, molals_gases, TK, P):\n        \"\"\"\n        Activity function for gaseous species\n\n        Parameters\n        ----------\n        molals_gases: np.ndarray\n            Array of molals of gases\n        TK: float\n            Temperature in Kelvin\n        P: float\n            Pressure in atm\n\n        Returns\n        -------\n        ndarray\n            Log-activity of gases\n        \"\"\"\n        # FIXME: Toy model. Just to make things work\n        molal_fractions = molals_gases/np.sum(molals_gases)\n        fugacity_coefficient_term = self._fugacity_coefficient_function(\n            molal_fractions, TK, P)\n        partial_pressure_term = np.log10(P) + np.log10(molal_fractions)\n        logact = fugacity_coefficient_term + partial_pressure_term\n        return logact\n\n    def set_fugacity_coefficient_function(self, gas_indexes):\n        \"\"\"\n        Parameters\n        ----------\n        gas_indexes: List[int]\n            Indexes of gases to be considered\n\n        Returns\n        -------\n        Callable[np.ndarray, float, float] -> float\n            Log-fugacity function, accepting molal_fractions, temperature (TK), and pressure (ATM)\n        \"\"\"\n        reactions_gases = [self.gas_reactions[i] for i in gas_indexes]\n        if reactions_gases == []:  # Edge case\n            self._fugacity_coefficient_function = lambda x, TK, P: 0.0\n        else:\n            self._fugacity_coefficient_function = \\\n                fugacity.make_peng_robinson_fugacity_function(reactions_gases)\n\n    def get_log_equilibrium_constants(self, TK, PATM):\n        \"\"\"\n        Parameters\n        ----------\n        TK: float\n            Temperature in kelvins\n\n        Returns\n        -------\n        List[float] of log equilibria constants of aqueous reactions\n        \"\"\"\n        return builder.get_log_equilibrium_constants(self.reactions, TK, PATM)\n\n    def get_solid_log_equilibrium_constants(self, TK, PATM):\n        \"\"\"\n        Parameters\n        ----------\n        TK: float\n            Temperature in kelvins\n\n        Returns\n        -------\n        List[float] of log equilibria constants of solid reactions\n        \"\"\"\n        return builder.get_log_equilibrium_constants(self.solid_reactions, TK, PATM)\n\n    def get_gases_log_equilibrium_constants(self, TK, PATM):\n        \"\"\"\n        Parameters\n        ----------\n        TK: float\n            Temperature in kelvins\n\n        Returns\n        -------\n        List[float] of log equilibria constants of gas reactions\n        \"\"\"\n        return builder.get_log_equilibrium_constants(self.gas_reactions, TK, PATM)\n\n    def solve_equilibrium_elements_balance(self, TK, element_balance,\n                                           PATM=1.0,\n                                           tol=1e-12,\n                                           maxiter=1000,\n                                           initial_guess='default'):\n        \"\"\"\n        PARTIALLY DEPRECATED: Use solve_equilibrium_mixed_balance \n        except when explicitly calculating sequential balance equilibria\n        \n        Parameters\n        ----------\n        TK: float\n            Temperature in Kelvins\n        element_balance: dict[str, float]\n            Dictionary of element balances\n        tol: float\n            Tolerance for solver\n        initial_guess: ndarray or str\n            Initial guess for solver. If 'default', is chosen as 0.1 for each specie\n\n        Returns\n        -------\n        SolutionResult object of equilibrium solution and statistics of solver\n        \"\"\"\n        assert len(element_balance) == self.nsolelements\n        balance_vector = np.array([element_balance[el] for\n                                   el in self.solute_elements])\n        balance_vector = np.append(balance_vector, 0.0)\n        balance_matrix = self.reduced_formula_matrix\n        mask = 0\n        balance_vector_log = np.zeros(0)\n        balance_matrix_log = np.zeros((0, self.nspecies))\n        mask_log = 0\n        self.solverlog = logmaker.make_solver_log(element_balance,\n                                                  dict(),\n                                                  dict(),\n                                                  dict(),\n                                                  TK,\n                                                  1.0,\n                                                  \"electroneutrality\",\n                                                  0.0)\n\n        return self.solve_equilibrium_balance(balance_vector,\n                                              balance_vector_log,\n                                              balance_matrix,\n                                              balance_matrix_log,\n                                              mask,\n                                              mask_log,\n                                              TK,\n                                              PATM,\n                                              tol=tol,\n                                              initial_guess=initial_guess)\n\n    def solve_equilibrium_elements_balance_phases(self, TK, element_balance,\n                                                  PATM=1.0,\n                                                  solid_phases=None,\n                                                  has_gas_phases=True,\n                                                  tol=1e-12, maxiter=1000,\n                                                  initial_guess='default'):\n        \"\"\"\n        Parameters\n        ----------\n        TK: float\n            Temperature in Kelvins\n        element_balance: dict[str, float]\n            Dictionary of element balances\n        PATM: float\n            Pressure in atms\n        solid_phases: None or List[str]\n            Phases of solid equilibria that precipitates. If None,\n            we assume all stable-at-temperature TK phases precipitates\n        has_gas_phases: bool\n            Whether to consider gas equilibria\n        tol: float\n            Tolerance for solver\n        initial_guess: ndarray or str or float\n            Initial guess for solver. If 'default', is chosen as 0.1 for each specie.\n            If float, is chosen as initial_guess for each specie\n\n        Returns\n        -------\n        SolutionResult object of equilibrium solution and statistics of solver\n        \"\"\"\n        balance_vector = np.array([element_balance[el] for\n                                   el in self.solute_elements])\n        balance_vector = np.append(balance_vector, 0.0)\n        balance_matrix = self.reduced_formula_matrix\n        if solid_phases is None:\n            solid_phases = builder.get_most_stable_phases(\n                self.solid_reactions, TK, PATM)\n        if has_gas_phases:\n            gas_phases = self.gas_phase_names\n        else:\n            gas_phases = []\n        # FIXME: Remove need of popping H20\n        if 'H2O(g)' in gas_phases:\n            gas_phases.remove('H2O(g)')\n        solid_indexes = self.get_solid_indexes(solid_phases)\n        gas_indexes = self.get_gas_indexes(gas_phases)\n        self.set_fugacity_coefficient_function(gas_indexes)\n\n        activity_function = self.activity_function\n        activity_function_gas = self.gas_activity_function\n\n        balance_matrix_solids = self.reduced_solid_formula_matrix[:, solid_indexes]\n        balance_matrix_gases = self.reduced_gas_formula_matrix[:, gas_indexes]\n        log_equilibrium_constants = \\\n            self.get_log_equilibrium_constants(TK, PATM)\n        log_solubility_constants = self.get_solid_log_equilibrium_constants(TK, PATM)\n        log_solubility_constants = log_solubility_constants[solid_indexes]\n        log_gases_constants = self.get_gases_log_equilibrium_constants(TK, PATM)\n        log_gases_constants = log_gases_constants[gas_indexes]\n        stoich_matrix = self.stoich_matrix\n        stoich_matrix_solids = self.solid_stoich_matrix[solid_indexes, :]\n        stoich_matrix_gases = self.gas_stoich_matrix[gas_indexes, :]\n\n        if isinstance(initial_guess, str) and initial_guess == 'default':\n            x_guess = np.ones(self.nsolutes)*0.1\n            x_guess_solid = np.ones(len(solid_indexes))*0.1\n            stability_solid_guess = np.zeros(len(solid_indexes))\n            x_guess_gas = np.ones(len(gas_indexes))*0.1\n            stability_gas_guess = np.zeros(len(gas_indexes))\n        elif isinstance(initial_guess, float):\n            x_guess = np.ones(self.nsolutes)*initial_guess\n            x_guess_solid = np.ones(len(solid_indexes))*initial_guess\n            stability_solid_guess = np.zeros(len(solid_indexes))\n            x_guess_gas = np.ones(len(gas_indexes))*0.1\n            stability_gas_guess = np.zeros(len(gas_indexes))\n        else:\n            x_guess, x_guess_solid, x_guess_gas, stability_solid_guess, stability_gas_guess = initial_guess\n\n        molals, molals_solids, molals_gases, stability_solids, stability_gases, res = \\\n            eqsolver.solve_equilibrium_xlma_2(\n                x_guess, x_guess_solid, x_guess_gas,\n                stability_solid_guess, stability_gas_guess,\n                TK, PATM, activity_function, activity_function_gas,\n                balance_vector,\n                log_equilibrium_constants, log_solubility_constants, log_gases_constants,\n                balance_matrix, balance_matrix_solids, balance_matrix_gases,\n                stoich_matrix, stoich_matrix_solids, stoich_matrix_gases,\n                solver_function=None, tol=tol)\n        self.solverlog = logmaker.make_solver_log(element_balance,\n                                                  dict(),\n                                                  dict(),\n                                                  dict(),\n                                                  TK,\n                                                  1.0,\n                                                  \"electroneutrality\",\n                                                  0.0)\n        if has_gas_phases:\n            self.solvertype = \"phase (with gas)\"\n        else:\n            self.solvertype = \"phase (no gas)\"\n        sol = solution.SolutionResult(self, molals, TK,\n                                      molals_solids, solid_phases,\n                                      molals_gases, gas_phases,\n                                      PATM=PATM)\n        stats = dict()\n        stats['res'] = res\n        stats['x'] = (molals, molals_solids, molals_gases, stability_solids, stability_gases)\n        return sol, stats\n\n    def solve_equilibrium_elements_balance_phases_sequential(self,\n                                                             TK, element_balance,\n                                                             PATM=1.0,\n                                                             solid_phases=None,\n                                                             has_gas_phases=True,\n                                                             tol=1e-12, maxiter=1000,\n                                                             initial_guess='default',\n                                                             npoints=20):\n        \"\"\"\n        Parameters\n        ----------\n        TK: float | (float, float)\n            Temperature in Kelvins\n        PATM: float\n            Pressure in atms\n        element_balance: dict[str, float | (float, float)]\n            Dictionary of element balances\n        solid_phases: None or List[str]\n            Phases of solid equilibria that precipitates. If None,\n            we assume all stable-at-temperature TK phases precipitates\n        has_gas_phases: bool\n            Whether to consider gas equilibria\n        tol: float\n            Tolerance for solver\n        initial_guess: ndarray or str or float\n            Initial guess for solver. If 'default', is chosen as 0.1 for each specie.\n            If float, is chosen as initial_guess for each specie\n\n        Returns\n        -------\n        list of SolutionResult object of equilibrium solution and list of residuals\n        \"\"\"\n        TK_list, PATM_list, element_balance_list = \\\n            sequencer.transform_to_sequence_of_arguments(npoints, TK, PATM, element_balance)\n        solutions = []\n        residuals = []\n        iterator = zip(TK_list, PATM_list, element_balance_list)\n        for (TK, PATM, element_balance) in iterator:\n            solution, stats = self.solve_equilibrium_elements_balance_phases(\n                                              TK, element_balance,\n                                              PATM,\n                                              solid_phases,\n                                              has_gas_phases,\n                                              tol, maxiter,\n                                              initial_guess)\n            if np.abs(np.max(stats['res'])) > 1e-3: #Try again\n                solution, stats = self.solve_equilibrium_elements_balance_phases(\n                                                  TK, element_balance,\n                                                  PATM,\n                                                  solid_phases,\n                                                  has_gas_phases,\n                                                  tol, maxiter,\n                                                  \"default\")\n            initial_guess = stats['x']\n            solutions.append(solution)\n            residuals.append(stats['res'])\n        stats = {'res': residuals}\n        return solutions, stats\n\n    def solve_equilibrium_mixed_balance(self, TK, molal_balance=None,\n                                        activities_balance=None,\n                                        molal_balance_log=None,\n                                        activities_balance_log=None,\n                                        closing_equation='electroneutrality',\n                                        closing_equation_value=0.0,\n                                        PATM=1.0,\n                                        tol=1e-12, maxiter=1000, initial_guess='default'):\n        \"\"\"\n        Parameters\n        ----------\n        TK: float\n            Temperature in Kelvins\n        molal_balance: dict[str, float] or None\n            Dictionary of molal balances\n        activities_balance: dict[str, float] or None\n            Dictionary of activities balances\n        molal_balance_log: dict[str, float] or None\n            Dictionary of log-molal balances\n        activities_balance_log: dict[str, float] or None\n            Dictionary of log-activities balances\n        closing_equation: str or None\n            Which closing equation to be used.\n            If 'electroneutrality', closes assuming electroneutrality of elements\n            If 'alkalinity', closes by alkaline balance defined by closing_equation_value\n            If None, closure must come from dictionaries\n        closing_equation_value: float\n            Value of closing equation\n        PATM: float\n            Pressure in atms\n        tol: float\n            Tolerance for solver\n        maxiter: int\n            Maximum iterations for solver\n        initial_guess: ndarray or str\n            Initial guess for solver. If 'default', is chosen as 0.1 for each specie\n\n        Returns\n        -------\n        SolutionResult object of equilibrium solution and statistics of solver\n\n        \"\"\"\n        \n        molal_balance = _none_to_dict(molal_balance)\n        activities_balance = _none_to_dict(activities_balance)\n        molal_balance_log = _none_to_dict(molal_balance_log)\n        activities_balance_log = _none_to_dict(activities_balance_log)\n        # TODO : Bunch of assertions\n        balance = _join_and_tag_dicts(molal_balance, activities_balance)\n        balance_log = _join_and_tag_dicts(\n            molal_balance_log, activities_balance_log)\n        balance_vector, balance_matrix, mask = \\\n            self._prepare_balance_arrays(balance)\n        balance_vector_log, balance_matrix_log, mask_log = \\\n            self._prepare_balance_arrays(balance_log)\n        if closing_equation:\n            balance_vector = np.append(balance_vector, closing_equation_value)\n            if closing_equation == 'electroneutrality':\n                closing_row = self.charge_vector\n                closing_mask = 0\n            elif closing_equation == 'alkalinity':\n                closing_row = self.alkalinity_vector\n                closing_mask = 1\n            balance_matrix = np.vstack([balance_matrix, closing_row])\n            mask = np.hstack([mask, closing_mask])\n        self.solverlog = logmaker.make_solver_log(molal_balance,\n                                                  activities_balance,\n                                                  molal_balance_log,\n                                                  activities_balance_log,\n                                                  TK,\n                                                  PATM,\n                                                  closing_equation,\n                                                  closing_equation_value)\n        self.solvertype = \"aqueous\"\n        return self.solve_equilibrium_balance(balance_vector,\n                                              balance_vector_log,\n                                              balance_matrix,\n                                              balance_matrix_log,\n                                              mask,\n                                              mask_log,\n                                              TK,\n                                              PATM,\n                                              tol=tol,\n                                              initial_guess=initial_guess)\n\n    def solve_equilibrium_mixed_balance_sequential(self, TK, molal_balance=None,\n                                                   activities_balance=None,\n                                                   molal_balance_log=None,\n                                                   activities_balance_log=None,\n                                                   closing_equation='electroneutrality',\n                                                   closing_equation_value=0.0,\n                                                   PATM=1.0,\n                                                   tol=1e-12, maxiter=1000,\n                                                   initial_guess='default',\n                                                   npoints=20):\n        \"\"\"\n        Parameters\n        ----------\n        TK: float | (float, float)\n            Temperature in Kelvins\n        molal_balance: dict[str, float | (float, float)] or None\n            Dictionary of molal balances\n        activities_balance: dict[str, float | (float, float)] or None\n            Dictionary of activities balances\n        molal_balance_log: dict[str, float | (float, float)] or None\n            Dictionary of log-molal balances\n        activities_balance_log: dict[str, float | (float, float)] or None\n            Dictionary of log-activities balances\n        closing_equation: str or None\n            Which closing equation to be used.\n            If 'electroneutrality', closes assuming electroneutrality of elements\n            If 'alkalinity', closes by alkaline balance defined by closing_equation_value\n            If None, closure must come from dictionaries\n        closing_equation_value: float | (float, float)\n            Value of closing equation\n        PATM: float\n            Pressure in atms\n        tol: float\n            Tolerance for solver\n        maxiter: int\n            Maximum iterations for solver\n        initial_guess: ndarray or str\n            Initial guess for solver. If 'default', is chosen as 0.1 for each specie\n\n        Returns\n        -------\n        list of SolutionResult object of equilibrium solution and list of residuals\n\n        \"\"\"\n        molal_balance = _none_to_dict(molal_balance)\n        activities_balance = _none_to_dict(activities_balance)\n        molal_balance_log = _none_to_dict(molal_balance_log)\n        activities_balance_log = _none_to_dict(activities_balance_log)\n        iterator = zip(*sequencer.transform_to_sequence_of_arguments(\n                        npoints, TK, molal_balance, activities_balance, \n                        molal_balance_log, activities_balance_log, \n                        closing_equation_value, PATM))\n        solutions = []\n        residuals = []\n        for (TK, molal_balance, activities_balance, molal_balance_log, \n             activities_balance_log, closing_equation_value, PATM) in iterator:\n            \n            solution, stats = \\\n                self.solve_equilibrium_mixed_balance(TK,\n                                                     molal_balance,\n                                                     activities_balance,\n                                                     molal_balance_log,\n                                                     activities_balance_log,\n                                                     closing_equation,\n                                                     closing_equation_value,\n                                                     PATM,\n                                                     tol, maxiter,\n                                                     initial_guess)\n            initial_guess = stats['x']\n            solutions.append(solution)\n            residuals.append(stats['res'])\n        stats = {'res': residuals}\n        return solutions, stats\n    \n    def solve_equilibrium_balance(self,\n                                  balance_vector,\n                                  balance_vector_log,\n                                  balance_matrix,\n                                  balance_matrix_log,\n                                  mask,\n                                  mask_log,\n                                  TK,\n                                  PATM=1.0,\n                                  tol=1e-12, maxiter=1000,\n                                  initial_guess='default'):\n        \"\"\"\n        Parameters\n        ----------\n        balance_vector: ndarray\n            Vector of balances\n        balance_vector_log: ndarray\n            Vector of log-balances\n        balance_matrix: ndarray\n            Matrix of balances\n        balance_matrix_log: ndarray\n            Matrix of log-balances\n        mask: ndarray\n            Activity mask\n        mask_log: ndarray\n            Log-activity mask\n        TK: float\n            Temperature in Kelvin\n        tol: float\n            Tolerance of solver\n        initial_guess: ndarray or str\n            Initial guess for solver. If 'default', is chosen as 0.1 for each specie\n        Returns\n        -------\n        SolutionResult object of equilibrium solution and statistics of solver\n\n        \"\"\"\n        log_equilibrium_constants = \\\n            self.get_log_equilibrium_constants(TK, PATM)\n        stoich_matrix = self.stoich_matrix\n        activity_function = self.activity_function\n        if isinstance(initial_guess, str) and initial_guess == 'default':\n            x_guess = np.ones(self.nsolutes)*0.1\n        elif isinstance(initial_guess, float):\n            x_guess = np.ones(self.nsolutes)*initial_guess\n        else:\n            x_guess = np.array(initial_guess)\n        x, res = eqsolver.solve_equilibrium_solutes(\n            x_guess,\n            TK,\n            activity_function,\n            balance_vector,\n            balance_vector_log,\n            log_equilibrium_constants,\n            balance_matrix,\n            balance_matrix_log,\n            stoich_matrix,\n            mask,\n            mask_log,\n            tol=tol)\n        stats = dict()\n        stats['res'] = res\n        stats['x'] = x\n        return solution.SolutionResult(self, x, TK, PATM=PATM), stats\n\n    def solve_equilibrium_balance_phases(self,\n                                         balance_vector,\n                                         balance_vector_log,\n                                         balance_matrix,\n                                         balance_matrix_log,\n                                         mask,\n                                         mask_log,\n                                         TK,\n                                         PATM=1.0,\n                                         tol=1e-12, maxiter=1000,\n                                         initial_guess='default'):\n        pass\n\n\n    @property\n    def elements(self):\n        \"\"\"Alias for base elements\"\"\"\n        return self.base_elements\n\n    @property\n    def extended_elements(self):\n        \"\"\"Elements + 'e'\"\"\"\n        return self.elements + ['e']\n\n    @property\n    def solute_elements(self):  # Ignore H and O\n        \"\"\"Elements excluding H and O\"\"\"\n        return self.elements[2:]\n\n    @property\n    def solutes(self):\n        \"\"\"Solutes\"\"\"\n        return self.species[1:]  # Ignore water\n\n    @property\n    def nspecies(self):\n        \"\"\"Number of aqueous species (includes H2O)\"\"\"\n        return len(self.species)\n\n    @property\n    def nreactions(self):\n        \"\"\"Number of aqueous reactions\"\"\"\n        return len(self.reactions)\n\n    @property\n    def nelements(self):\n        \"\"\"Number of elements\"\"\"\n        return len(self.elements)\n\n    @property\n    def nsolelements(self):\n        \"\"\"Number of solute elements\"\"\"\n        return len(self.solute_elements)\n\n    @property\n    def nsolutes(self):\n        \"\"\"Number of solutes\"\"\"\n        return len(self.solutes)\n\n    @property\n    def reduced_formula_matrix(self):\n        \"\"\"Formula matrix excluding H and O elements\"\"\"\n        return self.formula_matrix[2:, :]\n\n    @property\n    def reduced_solid_formula_matrix(self):\n        \"\"\"Solid formula matrix excluding H and O elements\"\"\"\n        return self.solid_formula_matrix[2:, :]\n\n    @property\n    def reduced_gas_formula_matrix(self):\n        \"\"\"Solid formula matrix excluding H and O elements\"\"\"\n        return self.gas_formula_matrix[2:, :]\n\n    @property\n    def charge_vector(self):\n        \"\"\"Vector of charge number for aqueous species\"\"\"\n        return self.formula_matrix[-1, :]\n\n    @property\n    def solutes_charge_vector(self):\n        \"\"\"Vector of charge numbers for solutes\"\"\"\n        return self.charge_vector[1:]\n\n    @property\n    def alkalinity_vector(self):\n        \"\"\"Vector of alkalinity coefficients\"\"\"\n        return np.array([constants.ALKALINE_COEFFICIENTS.get(specie, 0.0)\n                         for specie in self.species])\n\n    @property\n    def solutes_alkalinity_vector(self):\n        \"\"\"Vector of alkalinity coefficients for solutes\"\"\"\n        return self.alkalinity_vector[1:]\n\n    @property\n    def solid_phase_names(self):\n        \"\"\"Names of solid phases\"\"\"\n        return [sol_reac['phase_name'] for sol_reac in self.solid_reactions]\n\n    @property\n    def gas_phase_names(self):\n        \"\"\"Names of gas phases\"\"\"\n        return [gas_reac[\"phase_name\"] for gas_reac in self.gas_reactions]\n\n    def _initialize_species_reactions(self,\n                                      possible_reactions=None,\n                                      possible_solid_reactions=None,\n                                      possible_gas_reactions=None):\n        return builder.get_species_reaction_from_initial_species(\n            self.base_species, possible_reactions,\n            possible_solid_reactions, possible_gas_reactions)\n\n    def _make_formula_and_stoich_matrices(self):\n        formula_matrix = builder.make_formula_matrix(\n            self.species, self.elements)\n        stoich_matrix = builder.make_stoich_matrix(\n            self.species, self.reactions)\n        return formula_matrix, stoich_matrix\n\n    def _make_solid_formula_and_stoich_matrices(self):\n        if not self.solid_reactions:  # No precipitating solid phases\n            solid_formula_matrix = np.zeros((self.nelements+1, 0))\n            solid_stoich_matrix = np.zeros((0, self.nspecies))\n        else:\n            solid_formula_matrix = builder.make_solid_formula_matrix(\n                self.solid_reactions, self.elements)\n            solid_stoich_matrix = builder.make_stoich_matrix(\n                self.species, self.solid_reactions)\n        return solid_formula_matrix, solid_stoich_matrix\n\n    def _make_gas_formula_and_stoich_matrices(self):\n        if not self.gas_reactions:\n            gas_formula_matrix = np.zeros((self.nelements+1, 0))\n            gas_stoich_matrix = np.zeros((0, self.nspecies))\n        else:\n            gas_formula_matrix = builder.make_gas_formula_matrix(\n                self.gas_reactions, self.elements)\n            gas_stoich_matrix = builder.make_stoich_matrix(\n                self.species, self.gas_reactions)\n        return gas_formula_matrix, gas_stoich_matrix\n\n    def _prepare_balance_arrays(self, balances):\n        nbalances = len(balances)\n        balance_vector = np.zeros(nbalances)\n        mask = np.zeros(nbalances)\n        balance_matrix = np.zeros((nbalances, self.nspecies))\n        for i, (key, (value, tag)) in enumerate(balances.items()):\n            balance_vector[i] = value\n            mask[i] = tag\n            if key in self.elements:\n                balance_matrix[i, :] = self.formula_matrix[self.elements.index(\n                    key), :]\n            elif key in self.species:\n                balance_matrix[i, self.species.index(key)] = 1.0\n        return balance_vector, balance_matrix, mask\n\n    def get_solid_indexes(self, solid_phases):\n        indexes = [None for _ in range(len(solid_phases))]\n        for i, solid_phase in enumerate(solid_phases):\n            for j, solid_reaction in enumerate(self.solid_reactions):\n                if solid_reaction['phase_name'] == solid_phase:\n                    indexes[i] = j\n        return indexes\n\n    def get_gas_indexes(self, gas_phases):\n        indexes = [None for _ in range(len(gas_phases))]\n        for i, gas_phase in enumerate(gas_phases):\n            for j, gas_reaction in enumerate(self.gas_reactions):\n                if gas_reaction['phase_name'] == gas_phase:\n                    indexes[i] = j\n        return indexes\n\n\n# Helpers\ndef _prepare_base(components, from_elements):\n    # Implicity assumes that O and H will always in elements,\n    # and H2O will always be a species (were talking about aqueous\n    # equilibrium, after all).\n    if from_elements:\n        base_elements = set(components)\n        base_elements.add('O')\n        base_elements.add('H')\n        base_species = builder.elements_to_species(base_elements)\n    else:\n        base_species = set(components)\n        base_species.add('H2O')\n        base_elements = builder.species_to_elements(base_species)\n    # Work back to list\n    base_elements = builder.set_h_and_o_as_first_elements(\n        list(base_elements))\n    base_species = builder.set_h2o_as_first_specie(list(base_species))\n    return base_species, base_elements\n\n\ndef _none_to_dict(d):\n    return d if d is not None else dict()\n\n\ndef _join_and_tag_dicts(*args):\n    tags = list(range(len(args)))\n    d = dict()\n    for i, di in enumerate(args):\n        d.update({k: (v, tags[i]) for k, v in di.items()})\n    return d\n", "meta": {"hexsha": "be6757a5bbad3ca1e09156861d686d0997647b7c", "size": 37166, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyequion2/equilibrium_system.py", "max_stars_repo_name": "pyequion/pyequion", "max_stars_repo_head_hexsha": "733cf1c59b5a63f7346d4cb4c21a9ffd2218a5fc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyequion2/equilibrium_system.py", "max_issues_repo_name": "pyequion/pyequion", "max_issues_repo_head_hexsha": "733cf1c59b5a63f7346d4cb4c21a9ffd2218a5fc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyequion2/equilibrium_system.py", "max_forks_repo_name": "pyequion/pyequion", "max_forks_repo_head_hexsha": "733cf1c59b5a63f7346d4cb4c21a9ffd2218a5fc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3414905451, "max_line_length": 107, "alphanum_fraction": 0.5471667653, "include": true, "reason": "import numpy", "num_tokens": 7107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.2942149659744614, "lm_q1q2_score": 0.15628974771247464}}
{"text": "\"\"\"\n3D IoU Calculation and Rotated NMS\nWritten by Shaoshuai Shi\nAll Rights Reserved 2019-2020.\n\"\"\"\nimport torch\n\nfrom ...utils import common_utils\nfrom . import iou3d_nms_cuda\n\nimport numpy as np\nfrom shapely.geometry import Polygon\nfrom pcdet.utils.box_utils import boxes_to_corners_3d\n\n\ndef soft_nms_torch(dets, box_scores, iou_thresh=0.1, sigma=0.5, thresh=0.001):\n    \"\"\"\n    # 0.001\n    # 应该要使用bev_iou 还是 iou3d ？\n    reference https://github.com/DocF/Soft-NMS.git\n    Build a pytorch implement of Soft NMS algorithm.\n    # Augments\n        dets:        3D boxes coordinate tensor\n        box_scores:  box score tensors\n        sigma:       variance of Gaussian function\n        iou_thresh   iou_thresh if use method2 else 0\n        thresh:      score thresh       \n    # Return\n        the sorted index of the selected boxes\n    \"\"\"\n    # print('==> input dets.shape: ', dets.shape)\n    # print('==> input box_scores: ', box_scores)\n\n    N = dets.shape[0]  # the number of boxes\n\n    # Indexes concatenate boxes with the last column\n    indexes = torch.arange(0, N, dtype=torch.float).cuda().view(N, 1) \n    dets = torch.cat((dets, indexes), dim=1)\n    # print('==> cated dets.shape: ', dets.shape)\n    # Sort the scores of the boxes from largest to smallest\n    box_scores, conf_sort_index = torch.sort(box_scores, descending=True)\n    # 这里顺序都改变了？外面的顺序是否还能保持一致呢？\n    # print('==> sorted box_scores: ', box_scores)\n    dets = dets[conf_sort_index]\n\n    for i in range(N):\n    # for i in range(N-1):\n\n        pos=i+1\n\n        #iou calculate\n        # ious = box_iou(dets[i][0:4].view(-1,4), dets[pos:,:4])\n        # TODO: 选择3Diou还是beviou？\n        ious = boxes_iou_bev(dets[i][0:7].view(-1, 7), dets[pos:, :7])\n        # ious = boxes_iou3d_gpu(dets[i][0:7].view(-1, 7), dets[pos:, :7])\n\n        # method1\n        # Gaussian decay \n        box_scores[pos:] = torch.exp(-(ious * ious) / sigma) * box_scores[pos:]\n\n        # method2\n        # zero = torch.zeros_like(ious)\n        # ious  = torch.where(ious < iou_thresh, zero , ious)\n        # box_scores[pos:] = torch.exp(-(ious * ious) / sigma) * box_scores[pos:]\n\n        # method3 original nms\n        # weight = torch.ones(ious.shape)\n        # weight[ious > iou_thresh] = 0\n        # box_scores[pos:] = weight * box_scores[pos:]\n\n        # box_scores[pos:] = box_scores[pos:]\n        # box_scores[pos:], arg_sort = torch.sort(box_scores[pos:], descending=True)\n        # print('==> box_scores[pos:].shape: ', box_scores[pos:].shape)\n        box_scores_sorted, arg_sort = torch.sort(box_scores[pos:], descending=True)\n        box_scores[pos:] = box_scores_sorted\n        # print('==> in loop, sorted box_scores: ', box_scores)\n\n        a=dets[pos:]\n        \n        dets[pos:] = a[arg_sort]\n\n    # select the boxes and keep the corresponding indexes\n    # 这里是因为之前把index cat到了box的最后一维度上去，所以这里应该是选择box的index\n    # keep = dets[:,4][box_scores>thresh].long()\n    # print('==> final dets.shape: ', dets.shape)\n    # print('==> final box_scores.shape: ', box_scores.shape)\n    # print('==> final box_scores: ', box_scores)\n    valid = box_scores>thresh\n    # print('==> valid.shape: ', valid.shape)\n    det_indexes = dets[:,7]\n    # print('==> det_indexes.shape: ', det_indexes.shape)\n    print('==> det_indexes: ', det_indexes)\n\n    # keep = dets[:,7][box_scores>thresh].long()\n    keep = (det_indexes[valid]).long()\n\n    # print('==> output keep.shape: ', keep.shape)\n    return keep\n\ndef soft_nms_torch_1(dets, box_scores, iou_thresh=0.1, sigma=0.009, thresh=0.001, cuda=1):\n    \"\"\"\n    Build a pytorch implement of Soft NMS algorithm.\n    # Augments\n        dets:        boxes coordinate tensor (format:[y1, x1, y2, x2])\n        box_scores:  box score tensors\n        sigma:       variance of Gaussian function\n        thresh:      score thresh\n        cuda:        CUDA flag\n    # Return\n        the index of the selected boxes\n    \"\"\"\n    # print('0. ==> dets.shape: ', dets.shape)\n    # print('1. ==> box_scores.shape: ', box_scores.shape)\n\n    # Indexes concatenate boxes with the last column\n    N = dets.shape[0]\n    if cuda:\n        indexes = torch.arange(0, N, dtype=torch.float).cuda().view(N, 1)\n    else:\n        indexes = torch.arange(0, N, dtype=torch.float).view(N, 1)\n    dets = torch.cat((dets, indexes), dim=1)\n    # print('2. ==> dets.shape: ', dets.shape)\n\n    scores = box_scores\n    for i in range(N):\n        # print('==> i: ', i)\n        # intermediate parameters for later parameters exchange\n        tscore = scores[i].clone()\n        pos = i + 1\n\n        if i != N - 1:\n            maxscore, maxpos = torch.max(scores[pos:], dim=0)\n            if tscore < maxscore:\n                dets[i], dets[maxpos.item() + i + 1] = dets[maxpos.item() + i + 1].clone(), dets[i].clone()\n                scores[i], scores[maxpos.item() + i + 1] = scores[maxpos.item() + i + 1].clone(), scores[i].clone()\n\n        # IoU calculate\n        if dets[pos:, 0].shape[0] != 0:\n            ovr = boxes_iou_bev(dets[i, :7].view(-1, 7), dets[pos:, :7].view(-1, 7))\n            # ovr = boxes_iou3d_gpu(dets[i, :7].view(-1, 7), dets[pos:, :7].view(-1, 7))\n            # 这里是计算BEV IoU还是3D IoU\n            ovr = ovr.squeeze(dim=0)\n            # print('==> ovr.shape: ', ovr.shape)\n            # print('==> ovr', ovr)\n        else:\n            ovr = torch.tensor([]).to(dets.device)\n            # print('==> ovr.shape: ', ovr.shape)\n            # print('==> ovr', ovr)\n        # print('==> ovr: ', ovr)\n        # Gaussian decay\n        # '''\n        weight = torch.exp(-(ovr * ovr) / sigma)\n        # print('==> weight.shape: ', weight.shape)\n        # print('==> weight: ', weight)\n        scores[pos:] = weight * scores[pos:]\n        # print('==> scores.shape: ', scores.shape)\n        # '''\n\n        # original nms\n        '''\n        weight = torch.ones(ovr.shape).to(dets.device)\n        weight[ovr > iou_thresh] = 0\n        scores[pos:] = weight * scores[pos:]\n        '''\n\n    # select the boxes and keep the corresponding indexes\n    # print('==> final scores.shape: ', scores.shape)\n    # keep = dets[:, 4][scores > thresh].int()\n    keep = dets[:, -1][scores > thresh].long()\n    # print('==> keep: ', keep)\n    return keep\n\ndef iou_weighted_nms_cpu(\n                        boxes, scores, iou_preds, labels, anchors,\n                        suppressed_thresh = 0.3, # 0.3 in CIA-SSD OR 0.1?\n                        cnt_thresh = 0.5, #2.6, # from CIA-SSD\n                        match_thresh = 0.3,\n                        nms_sigma_dist_interval=[0, 20, 40, 60],\n                        nms_sigma_square = [0.0009, 0.009, 0.1, 1]):\n    \"\"\"\n    必须是单张点云内的数据\n    thresh: 是suppressed thresh\n    boxes: (N, 7), \n    scores: (N, )\n    iou_preds: (N, )\n    labels: (N, )\n    anchors: (N, 7), 与boxes对齐的\n    \"\"\"\n    scores_ret = []\n    boxes_ret = []\n    labels_ret = []\n\n    boxes_r = boxes.clone().cpu().numpy()\n    scores_r = scores.clone().cpu().numpy()\n    IOU_preds_r = iou_preds.clone().cpu().numpy()\n    labels_r = labels.clone().cpu().numpy()\n    anchors_r = anchors.clone().cpu().numpy()\n    box_corners_r = boxes_to_corners_3d(boxes).clone().cpu().numpy() # (N, 8, 3)\n    nms_sigma_dist_interval_r = nms_sigma_dist_interval\n    nms_sigma_square_r = nms_sigma_square\n    # print('==> boxes_r.shape: ', boxes_r.shape)\n    # print('==> scores_r.shape: ', scores_r.shape)\n    # print('==> IOU_preds_r.shape: ', IOU_preds_r.shape)\n    # print('==> labels_r.shape: ', labels_r.shape)\n    # print('==> anchors_r.shape: ', anchors_r.shape)\n    # print('==> box_corners_r.shape: ', box_corners_r.shape)\n\n\n    ndets = boxes.shape[0]\n    suppressed_rw = np.zeros((ndets))\n    # weight_pos = np.zeros((7))\n    # avg_pos = np.zeros((7))\n\n    standup_iou_r = boxes_iou3d_gpu(boxes, boxes).clone().cpu().numpy() # (N, N)\n\n    # 假设用bev_dist(box, anchor)\n    # TODO 这里是否需要根据这个来调制呢？\n    # dist = torch.pow((boxes[:,0]-anchors[:,0]), 2) + torch.pow( (boxes[:,1]-anchors[:,1]), 2)\n    # dist_nrom = (1 - torch.softmax(dist, dim=0)).cpu().numpy()\n    # 对score进行调制\n    # scores_rw = scores_r * dist_nrom\n\n    scores_rw = scores_r * 1\n\n    # 对调制后的score_rw取最大值，然后归一化\n    score_max4norm = np.max(scores_rw)\n    scores_rw /= (score_max4norm + 1e-6)\n\n    assert not np.array_equal(scores_rw, scores_r)\n    \n    while (True):\n        score_max = -1\n        idx_max = -1\n        flag_all_checked = True\n        # find out the box with the maximum score\n        for i in range(ndets):\n            if suppressed_rw[i] == 1:\n                continue\n            flag_all_checked = False\n            # 找到原始分数最大的那一个\n            if scores_r[i] > score_max:\n                score_max = scores_r[i]\n                idx_max = i\n        if flag_all_checked:\n            break\n        # 计算当前box到原点的距离, bev距离上的\n        dist2origin = np.linalg.norm(boxes_r[idx_max, 0:2], ord=2)\n        suppressed_rw[idx_max] = 1\n        \n        # 对weight_pos avg_pos重新置零\n        weight_pos = np.zeros((1))\n        avg_pos = np.zeros((7))\n        score_box = -1\n        cnt = 0\n        recover_list = []\n        merge_cnt = 0\n        merge_box_list = []\n        for j in range(ndets):\n            # 当前idx_max的box去和所有的box计算bev_iou\n            poly = Polygon(box_corners_r[idx_max, 0:4, 0:2])\n            qpoly = Polygon(box_corners_r[j, 0:4, 0:2])\n            if poly.intersects(qpoly):\n                inter_area = poly.intersection(qpoly).area\n                # 计算unions\n                union_area = poly.union(qpoly).area\n                overlap = inter_area / union_area\n                # 计算重叠的数量，用于过滤false_positives\n                if (overlap > 0) and (labels_r[j] == labels_r[idx_max]):\n                    # TODO: 选择？\n                    # cnt += overlap * IOU_preds_r[j]\n                    cnt += overlap * scores_r[j]\n                # 选择和当前box的iou>0.3的这些辅助box来重新加权\n                if (overlap >= match_thresh) and (labels_r[j] == labels_r[idx_max]):\n                    if score_box < scores_rw[j]:\n                        # 始终保留分数最大的一个\n                        # TODO: 这里box是否能够加权呢？\n                        score_box = scores_rw[j] \n                    IOU_weight = 0.\n                    # 和当前box的iou越大的辅助box的weight应该更大\n                    # 根据到原点的距离分段进行\n                    for k in range( len(nms_sigma_dist_interval_r) - 1):\n                        dist_l = nms_sigma_dist_interval_r[k]\n                        dist_r = nms_sigma_dist_interval_r[k+1]\n                        # print('==> dist_l: ', dist_l)\n                        # print('==> dist_r: ', dist_r)\n                        if (dist2origin >= dist_l) and (dist2origin < dist_r):\n                            tmp = -np.power( (1-overlap), 2 ) / nms_sigma_square_r[k]\n                            IOU_weight = np.exp(tmp)\n                            # print('==> dist2origin: ', dist2origin)\n\n                    # 使用IOU_weight对box进行加权\n                    # avg_pos += IOU_weight * IOU_preds_r[j] * boxes_r[j]\n                    # weight_pos += IOU_weight * IOU_preds_r[j]\n                    avg_pos += IOU_weight * scores_r[j] * boxes_r[j]\n                    weight_pos += IOU_weight * scores_r[j]\n                    assert avg_pos.shape[0] == 7\n                    merge_cnt += 1\n                    merge_box_list.append(boxes_r[j])\n\n                # suppress the box whose IOU with box[idx_max] > suppressed_thresh\n                if (suppressed_rw[j] != 1) and (standup_iou_r[idx_max, j] > 0):\n                    if (overlap > suppressed_thresh):\n                        suppressed_rw[j] = 1\n                        recover_list.append(j)\n        \n        # print('==> merge_cnt: ', merge_cnt)\n        # print('==> merge_box_list: ', merge_box_list)\n        # print('==> cnt: ', cnt)\n        if (cnt > cnt_thresh):\n            scores_ret.append(score_box * score_max4norm)\n            avg_pos /= (weight_pos + 1e-6)\n            boxes_ret.append(avg_pos)\n            labels_ret.append(labels_r[idx_max])\n            # print('==> merge valid.')\n            if avg_pos[3] + avg_pos[4] + avg_pos[5] == 0:\n                scores_ret.pop()\n                boxes_ret.pop()\n                labels_ret.pop()\n                for k in range(len(recover_list)):\n                    suppressed_rw[recover_list[k]] = 0\n        else:\n            # 如果当前这个box是一个false pos，那么就恢复(释放)之前被它抑制掉的其它box\n            for k in range(len(recover_list)):\n                suppressed_rw[recover_list[k]] = 0\n\n    if len(boxes_ret):\n        # not empty:\n        ret_boxes_np = np.stack(boxes_ret, axis=0)\n        ret_scores_np = np.stack(scores_ret, axis=0)\n        ret_labels_np = np.stack(labels_ret, axis=0)\n    else:\n        ret_boxes_np = np.zeros( [0, 7] )\n        ret_scores_np = np.zeros( [0, 1] )\n        ret_labels_np = np.zeros( [0, 1] )\n\n    ret_boxes = torch.from_numpy(ret_boxes_np).to(boxes.device)\n    ret_scores = torch.from_numpy(ret_scores_np).to(boxes.device)\n    ret_labels = torch.from_numpy(ret_labels_np).to(boxes.device)\n    # boxes, scores, iou_preds, labels\n    '''\n    print('==> input boxes: ', boxes)\n    print('==> input scores: ', scores)\n    print('==> input iou_preds: ', iou_preds)\n    print('==> input labels: ', labels)\n    print('==> ret_boxes.shape: ', ret_boxes)\n    print('==> ret_scores.shape: ', ret_scores)\n    print('==> ret_labels.shape: ', ret_labels)\n    '''\n    return ret_boxes, ret_scores, ret_labels\n\n\n\ndef matched_boxes_bevdist(boxes_a, boxes_b):\n    \"\"\"\n    以bev上的中心点距离作为certainty\n    \"\"\"\n    dist = torch.pow((boxes_a[:,0]-boxes_b[:,0]), 2) + torch.pow( (boxes_a[:,1]-boxes_b[:,1]), 2)\n    dist_nrom = 1 - torch.softmax(dist, dim=0)\n\n    return dist_nrom.view(-1, 1)\n\n\ndef matched_boxes_iou3d_cpu(boxes_a, boxes_b):\n    \"\"\"\n    # 前提是一一对齐的两组box\n    Args: \n        boxes_a: tensor, (N, 7) [x,y,z,dx,dy,dz,heading]\n        boxes_b: tensor, (N, 7) [x,y,z,dx,dy,dz,heading]\n    Returns:\n        ans_iou: tensor, (N, 1)\n    \"\"\"\n    assert boxes_a.shape == boxes_b.shape\n\n    # 1. 计算高度方向上的overlap\n    # height overlap, (N, )\n    boxes_a_height_max = (boxes_a[:, 2] + boxes_a[:, 5] / 2)\n    boxes_a_height_min = (boxes_a[:, 2] - boxes_a[:, 5] / 2)\n    boxes_b_height_max = (boxes_b[:, 2] + boxes_b[:, 5] / 2)\n    boxes_b_height_min = (boxes_b[:, 2] - boxes_b[:, 5] / 2)\n    max_of_min = torch.max(boxes_a_height_min, boxes_b_height_min)\n    min_of_max = torch.min(boxes_a_height_max, boxes_b_height_max)\n    overlaps_h = torch.clamp(min_of_max - max_of_min, min=0)\n\n    # 2. 转为corner, (N, 8, 3)\n    corners_a = boxes_to_corners_3d(boxes_a)\n    corners_b = boxes_to_corners_3d(boxes_b)\n\n    # 3. 准备numpy格式的polygon 2D points\n    np_2dcorners_a = corners_a.clone().cpu().numpy()\n    np_2dcorners_b = corners_b.clone().cpu().numpy()\n    np_overlaps_bev = np.zeros( (np_2dcorners_a.shape[0]) )\n    for i in range(np_2dcorners_a.shape[0]):\n        poly_points_a = np_2dcorners_a[i, 0:4, 0:2]\n        poly_points_b = np_2dcorners_b[i, 0:4, 0:2]\n        poly_a = Polygon(poly_points_a)\n        poly_b = Polygon(poly_points_b)\n        if poly_a.is_valid and poly_b.is_valid:\n            # check is valid,  A valid Polygon may not possess any overlapping exterior or interior rings.\n            overlap = poly_a.intersection(poly_b).area\n        else:\n            overlap = 0.\n        np_overlaps_bev[i] = overlap\n    # move back to torch\n    overlaps_bev = torch.from_numpy(np_overlaps_bev).to(boxes_a.device)\n\n    # 4. 计算3d overlaps\n    overlaps_3d = overlaps_bev * overlaps_h\n    assert overlaps_3d.shape == overlaps_bev.shape == overlaps_h.shape\n\n    # 5. 计算3d iou\n    vol_a = (boxes_a[:, 3] * boxes_a[:, 4] * boxes_a[:, 5])\n    vol_b = (boxes_b[:, 3] * boxes_b[:, 4] * boxes_b[:, 5])\n\n    iou3d = overlaps_3d / torch.clamp(vol_a + vol_b - overlaps_3d, min=1e-6)\n    return iou3d.view(-1, 1)\n    \n\ndef boxes_bev_iou_cpu(boxes_a, boxes_b):\n    \"\"\"\n    Args:\n        boxes_a: (N, 7) [x, y, z, dx, dy, dz, heading]\n        boxes_b: (N, 7) [x, y, z, dx, dy, dz, heading]\n\n    Returns:\n\n    \"\"\"\n    boxes_a, is_numpy = common_utils.check_numpy_to_torch(boxes_a)\n    boxes_b, is_numpy = common_utils.check_numpy_to_torch(boxes_b)\n    assert not (boxes_a.is_cuda or boxes_b.is_cuda), 'Only support CPU tensors'\n    assert boxes_a.shape[1] == 7 and boxes_b.shape[1] == 7\n    ans_iou = boxes_a.new_zeros(torch.Size((boxes_a.shape[0], boxes_b.shape[0])))\n    iou3d_nms_cuda.boxes_iou_bev_cpu(boxes_a.contiguous(), boxes_b.contiguous(), ans_iou)\n\n    return ans_iou.numpy() if is_numpy else ans_iou\n\n\ndef boxes_iou_bev(boxes_a, boxes_b):\n    \"\"\"\n    Args:\n        boxes_a: (N, 7) [x, y, z, dx, dy, dz, heading]\n        boxes_b: (N, 7) [x, y, z, dx, dy, dz, heading]\n\n    Returns:\n        ans_iou: (N, M)\n    \"\"\"\n    assert boxes_a.shape[1] == boxes_b.shape[1] == 7\n    ans_iou = torch.cuda.FloatTensor(torch.Size((boxes_a.shape[0], boxes_b.shape[0]))).zero_()\n\n    iou3d_nms_cuda.boxes_iou_bev_gpu(boxes_a.contiguous(), boxes_b.contiguous(), ans_iou)\n\n    return ans_iou\n\n\ndef boxes_iou3d_gpu(boxes_a, boxes_b):\n    \"\"\"\n    Args:\n        boxes_a: (N, 7) [x, y, z, dx, dy, dz, heading]\n        boxes_b: (N, 7) [x, y, z, dx, dy, dz, heading]\n\n    Returns:\n        ans_iou: (N, M)\n    \"\"\"\n    assert boxes_a.shape[1] == boxes_b.shape[1] == 7\n\n    # height overlap\n    boxes_a_height_max = (boxes_a[:, 2] + boxes_a[:, 5] / 2).view(-1, 1)\n    boxes_a_height_min = (boxes_a[:, 2] - boxes_a[:, 5] / 2).view(-1, 1)\n    boxes_b_height_max = (boxes_b[:, 2] + boxes_b[:, 5] / 2).view(1, -1)\n    boxes_b_height_min = (boxes_b[:, 2] - boxes_b[:, 5] / 2).view(1, -1)\n\n    # bev overlap\n    overlaps_bev = torch.cuda.FloatTensor(torch.Size((boxes_a.shape[0], boxes_b.shape[0]))).zero_()  # (N, M)\n    iou3d_nms_cuda.boxes_overlap_bev_gpu(boxes_a.contiguous(), boxes_b.contiguous(), overlaps_bev)\n\n    max_of_min = torch.max(boxes_a_height_min, boxes_b_height_min)\n    min_of_max = torch.min(boxes_a_height_max, boxes_b_height_max)\n    overlaps_h = torch.clamp(min_of_max - max_of_min, min=0)\n\n    # 3d iou\n    overlaps_3d = overlaps_bev * overlaps_h\n\n    vol_a = (boxes_a[:, 3] * boxes_a[:, 4] * boxes_a[:, 5]).view(-1, 1)\n    vol_b = (boxes_b[:, 3] * boxes_b[:, 4] * boxes_b[:, 5]).view(1, -1)\n\n    iou3d = overlaps_3d / torch.clamp(vol_a + vol_b - overlaps_3d, min=1e-6)\n\n    # 还要进行限制一下，小于0或者大于1的都设置为0\n    iou3d[iou3d < 0] = 0\n    iou3d[iou3d > 1] = 1\n\n    return iou3d\n\n\ndef nms_gpu(boxes, scores, thresh, pre_maxsize=None, **kwargs):\n    \"\"\"\n    :param boxes: (N, 7) [x, y, z, dx, dy, dz, heading]\n    :param scores: (N)\n    :param thresh:\n    :return:\n    \"\"\"\n    assert boxes.shape[1] == 7\n    order = scores.sort(0, descending=True)[1]\n    if pre_maxsize is not None:\n        order = order[:pre_maxsize]\n\n    boxes = boxes[order].contiguous()\n    keep = torch.LongTensor(boxes.size(0))\n    num_out = iou3d_nms_cuda.nms_gpu(boxes, keep, thresh)\n    return order[keep[:num_out].cuda()].contiguous(), None\n\n\ndef nms_normal_gpu(boxes, scores, thresh, **kwargs):\n    \"\"\"\n    :param boxes: (N, 7) [x, y, z, dx, dy, dz, heading]\n    :param scores: (N)\n    :param thresh:\n    :return:\n    \"\"\"\n    assert boxes.shape[1] == 7\n    order = scores.sort(0, descending=True)[1]\n\n    boxes = boxes[order].contiguous()\n\n    keep = torch.LongTensor(boxes.size(0))\n    num_out = iou3d_nms_cuda.nms_normal_gpu(boxes, keep, thresh)\n    return order[keep[:num_out].cuda()].contiguous(), None\n\n\ndef batch_boxes_iou3d_gpu(boxes_a, boxes_b):\n    \"\"\"\n    Args:\n        boxes_a: (B, N, 7) [x, y, z, dx, dy, dz, heading]\n        boxes_b: (B, M, 7) [x, y, z, dx, dy, dz, heading], GT, 可能会补零，所以先去掉0\n\n    Returns:\n        ans_iou: (B, N, 1)\n    \"\"\"\n    assert boxes_a.shape[0] == boxes_b.shape[0]\n    assert boxes_a.shape[-1] == boxes_b.shape[-1]\n\n    # for each batch\n    boxiou_a_list = []\n    batch_size = boxes_a.shape[0]\n    for i in range(batch_size):\n        boxes_a_single = boxes_a[i, ...] # (max_objs, 7)\n        boxes_b_single = boxes_b[i, ...] # (M, 7)\n        # print('==> 0. src_box_target_single.size(): ', src_box_target_single.size()) # (M, 7)\n        # valid = ( torch.sum(boxes_b_single, dim=1) != 0 )\n        # print('==> valid.size(): ', valid.size()) # (M) \n        # boxes_b_single = boxes_b_single[valid]\n        # print('==> 1. src_box_target_single.size(): ', src_box_target_single.size()) # (Nb(=M))\n        iou3d = boxes_iou3d_gpu(boxes_a=boxes_a_single, \n                                boxes_b=boxes_b_single)  # (Na, Nb)\n        # print('==> iou3d.size(): ', iou3d.size()) # (max_objs(=Na), Nb)\n        max_overlaps, gt_assignment = torch.max(iou3d, dim=1) # roi side iou\n        # print('==> max_overlaps.size(): ', max_overlaps.size()) # (max_objs(=Na))\n        boxiou_a_list.append( max_overlaps.view(-1, 1) )\n    \n    # stack for batch axis, batch (max_objs, 1) -> (batch, max_objs, 1)\n    boxiou_a = torch.stack(boxiou_a_list, dim=0)\n\n    return  boxiou_a\n", "meta": {"hexsha": "5ca603d6b6aa5c4884e71c49441a4d1b732aff8c", "size": 20740, "ext": "py", "lang": "Python", "max_stars_repo_path": "pcdet/ops/iou3d_nms/iou3d_nms_utils.py", "max_stars_repo_name": "jialeli1/From-Voxel-to-Point", "max_stars_repo_head_hexsha": "b4dba9c4e9cd83e04199d9224f6ec7bf06b71f93", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2021-07-14T10:55:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T05:46:42.000Z", "max_issues_repo_path": "pcdet/ops/iou3d_nms/iou3d_nms_utils.py", "max_issues_repo_name": "jialeli1/From-Voxel-to-Point", "max_issues_repo_head_hexsha": "b4dba9c4e9cd83e04199d9224f6ec7bf06b71f93", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-07-12T09:58:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T13:04:47.000Z", "max_forks_repo_path": "pcdet/ops/iou3d_nms/iou3d_nms_utils.py", "max_forks_repo_name": "jialeli1/From-Voxel-to-Point", "max_forks_repo_head_hexsha": "b4dba9c4e9cd83e04199d9224f6ec7bf06b71f93", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-08-22T16:41:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T06:54:52.000Z", "avg_line_length": 36.838365897, "max_line_length": 115, "alphanum_fraction": 0.5753134041, "include": true, "reason": "import numpy", "num_tokens": 6401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.30074558520860073, "lm_q1q2_score": 0.15624374399882804}}
{"text": "#! /usr/bin/env python\n# coding: utf-8\n\nimport multiprocessing as mp\nfrom ctypes import c_double, c_int\nimport numpy as np\nimport os\nimport sys\nimport signal\n\nfrom multiprocessing.sharedctypes import Value, Array\nfrom multiprocessing import Lock\nfrom multiprocessing.managers import SyncManager\n\nimport cProfile\nimport time\nimport os\n\nclass CheckPoint(Exception):\n    pass\n\ndef sighandler(signal, frame):\n    raise CheckPoint\n\nclass CPNest(object):\n    \"\"\"\n    Class to control CPNest sampler\n    cp = CPNest(usermodel,nlive=100,output='./',verbose=0,seed=None,maxmcmc=100,nthreads=None,balanced_sampling = True)\n    \n    Input variables:\n    usermodel : an object inheriting cpnest.model.Model that defines the user's problem\n    nlive : Number of live points (100)\n    poolsize: Number of objects in the sampler pool (100)\n    output : output directory (./)\n    verbose: Verbosity, 0=silent, 1=progress, 2=diagnostic, 3=detailed diagnostic\n    seed: random seed (default: 1234)\n    maxmcmc: maximum MCMC points for sampling chains (100)\n    nthreads: number of parallel samplers. Default (None) uses mp.cpu_count() to autodetermine\n    nhamiltomnian: number of sampler threads using an hamiltonian samplers. Default: 0\n    resume: determines whether cpnest will resume a run or run from scratch. Default: False.\n    proposal: dictionary/list with custom jump proposals. key 'mhs' for the\n    Metropolis-Hastings sampler, 'hmc' for the Hamiltonian Monte-Carlo sampler. Default: None\n    n_periodic_checkpoint: int\n        checkpoint the sampler every n_periodic_checkpoint iterations\n        Default: 100000\n \n    \"\"\"\n    def __init__(self,\n                 usermodel,\n                 nlive        = 100,\n                 poolsize     = 100,\n                 output       = './',\n                 verbose      = 0,\n                 seed         = None,\n                 maxmcmc      = 100,\n                 nthreads     = None,\n                 nhamiltonian = 0,\n                 resume       = False,\n                 proposals     = None,\n                 n_periodic_checkpoint = 1000):\n        if nthreads is None:\n            self.nthreads = mp.cpu_count()\n        else:\n            self.nthreads = nthreads\n\n        print('Running with {0} parallel threads'.format(self.nthreads))\n        from .sampler import HamiltonianMonteCarloSampler, MetropolisHastingsSampler\n        from .NestedSampling import NestedSampler\n        from .proposal import DefaultProposalCycle, HamiltonianProposalCycle\n        if proposals is None:\n            proposals = dict(mhs=DefaultProposalCycle,\n                             hmc=HamiltonianProposalCycle)\n        elif type(proposals) == list:\n            proposals = dict(mhs=proposals[0],\n                             hmc=proposals[1])\n        self.nlive    = nlive\n        self.verbose  = verbose\n        self.output   = output\n        self.poolsize = poolsize\n        self.posterior_samples = None\n        self.manager = RunManager(nthreads=self.nthreads)\n        self.manager.start()\n        self.user     = usermodel\n        self.resume = resume\n\n        if seed is None: self.seed=1234\n        else:\n            self.seed=seed\n        \n        self.process_pool = []\n        \n        # instantiate the nested sampler class\n        resume_file = os.path.join(output, \"nested_sampler_resume.pkl\")\n        if not os.path.exists(resume_file) or resume == False:\n            self.NS = NestedSampler(self.user,\n                        nlive          = nlive,\n                        output         = output,\n                        verbose        = verbose,\n                        seed           = self.seed,\n                        prior_sampling = False,\n                        manager        = self.manager,\n                        n_periodic_checkpoint = n_periodic_checkpoint)\n        else:\n            self.NS = NestedSampler.resume(resume_file, self.manager, self.user)\n\n        # instantiate the sampler class\n        for i in range(self.nthreads-nhamiltonian):\n            resume_file = os.path.join(output, \"sampler_{0:d}.pkl\".format(i))\n            if not os.path.exists(resume_file) or resume == False:\n                sampler = MetropolisHastingsSampler(self.user,\n                                  maxmcmc,\n                                  verbose     = verbose,\n                                  output      = output,\n                                  poolsize    = poolsize,\n                                  seed        = self.seed+i,\n                                  proposal    = proposals['mhs'](),\n                                  resume_file = resume_file,\n                                  manager     = self.manager\n                                  )\n                sampler.checkpoint()\n            else:\n                sampler = MetropolisHastingsSampler.resume(resume_file,\n                                                           self.manager,\n                                                           self.user)\n\n            p = mp.Process(target=sampler.produce_sample)\n            self.process_pool.append(p)\n        \n        for i in range(self.nthreads-nhamiltonian,self.nthreads):\n            resume_file = os.path.join(output, \"sampler_{0:d}.pkl\".format(i))\n            if not os.path.exists(resume_file) or resume == False:\n                sampler = HamiltonianMonteCarloSampler(self.user,\n                                  maxmcmc,\n                                  verbose     = verbose,\n                                  output      = output,\n                                  poolsize    = poolsize,\n                                  seed        = self.seed+i,\n                                  proposal    = proposals['hmc'](model=self.user),\n                                  resume_file = resume_file,\n                                  manager     = self.manager\n                                  )\n            else:\n                sampler = HamiltonianMonteCarloSampler.resume(resume_file,\n                                                              self.manager,\n                                                              self.user)\n            p = mp.Process(target=sampler.produce_sample)\n            self.process_pool.append(p)\n\n    def run(self):\n        \"\"\"\n        Run the sampler\n        \"\"\"\n        if self.resume:\n            signal.signal(signal.SIGTERM, sighandler)\n            signal.signal(signal.SIGQUIT, sighandler)\n            signal.signal(signal.SIGINT, sighandler)\n            signal.signal(signal.SIGUSR1, sighandler)\n            signal.signal(signal.SIGUSR2, sighandler)\n        \n        #self.p_ns.start()\n        for each in self.process_pool:\n            each.start()\n        try:\n            self.NS.nested_sampling_loop()\n            for each in self.process_pool:\n                each.join()\n        except CheckPoint:\n            self.checkpoint()\n            sys.exit()\n\n        self.posterior_samples = self.get_posterior_samples(filename=None)\n        if self.verbose>1: self.plot()\n    \n        #TODO: Clean up the resume pickles\n\n    def get_nested_samples(self, filename='nested_samples.dat'):\n        \"\"\"\n        returns nested sampling chain\n        Parameters\n        ----------\n        filename : string\n                   If given, file to save nested samples to\n\n        Returns\n        -------\n        pos : :obj:`numpy.ndarray`\n        \"\"\"\n        import numpy.lib.recfunctions as rfn\n        self.nested_samples = rfn.stack_arrays(\n                [s.asnparray()\n                    for s in self.NS.nested_samples]\n                ,usemask=False)\n        if filename:\n            np.savetxt(os.path.join(\n                self.NS.output_folder,'nested_samples.dat'),\n                self.nested_samples.ravel(),\n                header=' '.join(self.nested_samples.dtype.names),\n                newline='\\n',delimiter=' ')\n        return self.nested_samples\n\n    def get_posterior_samples(self, filename='posterior.dat'):\n        \"\"\"\n        Returns posterior samples\n\n        Parameters\n        ----------\n        filename : string\n                   If given, file to save posterior samples to\n\n        Returns\n        -------\n        pos : :obj:`numpy.ndarray`\n        \"\"\"\n        import numpy as np\n        import os\n        from .nest2pos import draw_posterior_many\n        nested_samples = self.get_nested_samples()\n        posterior_samples = draw_posterior_many([nested_samples],[self.nlive],verbose=self.verbose)\n        posterior_samples = np.array(posterior_samples)\n        # TODO: Replace with something to output samples in whatever format\n        if filename:\n            np.savetxt(os.path.join(\n                self.NS.output_folder,'posterior.dat'),\n                self.posterior_samples.ravel(),\n                header=' '.join(posterior_samples.dtype.names),\n                newline='\\n',delimiter=' ')\n        return posterior_samples\n\n    def plot(self, corner = True):\n        \"\"\"\n        Make diagnostic plots of the posterior and nested samples\n        \"\"\"\n        pos = self.posterior_samples\n        from . import plot\n        for n in pos.dtype.names:\n            plot.plot_hist(pos[n].ravel(),name=n,filename=os.path.join(self.output,'posterior_{0}.png'.format(n)))\n        for n in self.nested_samples.dtype.names:\n            plot.plot_chain(self.nested_samples[n],name=n,filename=os.path.join(self.output,'nschain_{0}.png'.format(n)))\n        import numpy as np\n        plotting_posteriors = np.squeeze(pos.view((pos.dtype[0], len(pos.dtype.names))))\n        if corner: plot.plot_corner(plotting_posteriors,labels=pos.dtype.names,filename=os.path.join(self.output,'corner.png'))\n\n    def worker_sampler(self, producer_pipe, logLmin):\n        cProfile.runctx('self.sampler.produce_sample(producer_pipe, logLmin)', globals(), locals(), 'prof_sampler.prof')\n    \n    def worker_ns(self):\n        cProfile.runctx('self.NS.nested_sampling_loop(self.consumer_pipes)', globals(), locals(), 'prof_nested_sampling.prof')\n\n    def profile(self):\n        for i in range(0,self.NUMBER_OF_PRODUCER_PROCESSES):\n            p = mp.Process(target=self.worker_sampler, args=(self.queues[i%len(self.queues)], self.NS.logLmin ))\n            self.process_pool.append(p)\n        for i in range(0,self.NUMBER_OF_CONSUMER_PROCESSES):\n            p = mp.Process(target=self.worker_ns, args=(self.queues, self.port, self.authkey))\n            self.process_pool.append(p)\n        for each in self.process_pool:\n            each.start()\n\n    def checkpoint(self):\n        self.manager.checkpoint_flag=1\n\nclass RunManager(SyncManager):\n    def __init__(self, nthreads=None, **kwargs):\n        super(RunManager,self).__init__(**kwargs)\n        self.nconnected=mp.Value(c_int,0)\n        self.producer_pipes = list()\n        self.consumer_pipes = list()\n        for i in range(nthreads):\n            consumer, producer = mp.Pipe(duplex=True)\n            self.producer_pipes.append(producer)\n            self.consumer_pipes.append(consumer)\n        self.logLmin=None\n        self.nthreads=nthreads\n\n    def start(self):\n        super(RunManager, self).start()\n        self.logLmin = mp.Value(c_double,-np.inf)\n        self.checkpoint_flag=mp.Value(c_int,0)\n\n    def connect_producer(self):\n        \"\"\"\n        Returns the producer's end of the pipe\n        \"\"\"\n        with self.nconnected.get_lock():\n            n = self.nconnected.value\n            pipe = self.producer_pipes[n]\n            self.nconnected.value+=1\n        return pipe, n\n", "meta": {"hexsha": "d4e6284c826bec97b7f08303ce802bb9f5123867", "size": 11485, "ext": "py", "lang": "Python", "max_stars_repo_path": "cpnest/cpnest.py", "max_stars_repo_name": "MoritzThomasHuebner/cpnest", "max_stars_repo_head_hexsha": "18a6233d9050070e1365bef343584cb1b9af9e3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpnest/cpnest.py", "max_issues_repo_name": "MoritzThomasHuebner/cpnest", "max_issues_repo_head_hexsha": "18a6233d9050070e1365bef343584cb1b9af9e3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpnest/cpnest.py", "max_forks_repo_name": "MoritzThomasHuebner/cpnest", "max_forks_repo_head_hexsha": "18a6233d9050070e1365bef343584cb1b9af9e3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7404844291, "max_line_length": 127, "alphanum_fraction": 0.5589029168, "include": true, "reason": "import numpy", "num_tokens": 2318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.28776781576105315, "lm_q1q2_score": 0.1562185812554259}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nPiViewer: an open-source tool for automated detection and display of pi-pi interactions.\nCreated by Hu Ge <gehuchina@gmail.com>\n\"\"\"\n\n# Copyright Notice\n# ================\n#\n# The PyMOL Plugin source code in this file is copyrighted, but you can\n# freely use and copy it as long as you don't change or remove any of\n# the copyright notices.\n#\n# ----------------------------------------------------------------------\n# #\n#                        All Rights Reserved\n#\n# Permission to use, copy, modify, distribute, and distribute modified\n# versions of this software and its documentation for any purpose and\n# without fee is hereby granted, provided that the above copyright\n# notice appear in all copies and that both the copyright notice and\n# this permission notice appear in supporting documentation, and that\n# the name(s) of the author(s) not be used in advertising or publicity\n# pertaining to distribution of the software without specific, written\n# prior permission.\n#\n# THE AUTHOR(S) DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,\n# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.  IN\n# NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY SPECIAL, INDIRECT OR\n# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF\n# USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\n# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n# PERFORMANCE OF THIS SOFTWARE.\n# ----------------------------------------------------------------------\n\nimport openbabel as ob\nimport pybel\nimport numpy as np\n\n# Define vecAngle for the degree between two vectors.\ndef vecAngle(vec1, vec2):\n    '''\n    vec1,vec2 are ob.vector3 objects,\n    return the angle between them in degree.\n    '''\n    dotprod = vec1.GetX() * vec2.GetX() + vec1.GetY() * vec2.GetY() + vec1.GetZ() * vec2.GetZ()\n    deg = np.arccos(dotprod) * 180 / np.pi\n    if deg > 90:\n        deg = 180 - deg\n    return deg\n\n\n# The main PiPi viewer function\ndef find_PiPi(pdb_file, lig_name, centroid_distance=5.0, dih_parallel=25, dih_tshape=80, verbose=1):\n    \"\"\"\n    Find Pi-Pi interactions around the specified ligand residue from the pdb file.\n    :param pdb_file: path of the target file in PDB format.\n    :param lig_name: ligand residue name.\n    :param centroid_distance: Max ring centroid distance\n    :param dih_parallel: Max dihedral (parallel)\n    :param dih_tshape: Min dihedral (T-shaped)\n    :return: number of Pi-Pi interactions found\n    \"\"\"\n    # Get ligand residue and print its name.\n    ligAtomList = []\n    ligAtomIdList = []\n    mol = pybel.readfile('pdb', pdb_file).next()\n    if verbose: print \"A total of %s residues\" % mol.OBMol.NumResidues()\n    lig = None\n    for res in ob.OBResidueIter(mol.OBMol):\n        # print res.GetName()\n        if res.GetName() == lig_name:\n            lig = res\n            if verbose: print \"Ligand residue name is:\", lig.GetName()\n            break\n    if not lig:\n        if verbose: print \"No ligand residue %s found, please confirm.\" % lig_name\n        return -1\n    else:\n        for atom in ob.OBResidueAtomIter(lig):\n            # print atom.GetIdx()\n            ligAtomList.append(atom)\n            ligAtomIdList.append(atom.GetIdx())\n\n    # Set ring_id\n    i = 0\n    for ring in mol.sssr:\n        ring.ring_id = i\n        i += 1\n        # print ring.ring_id\n\n    # Determine which rings are from ligand.\n    ligRingList = []\n    ligAroRingList = []\n    ligRingIdList = []\n    recRingList = []\n    recAroRingList = []\n    for ring in mol.sssr:\n        for atom in ligAtomList:\n            if ring.IsMember(atom):\n                if ring not in ligRingList:\n                    ligRingList.append(ring)\n                    ligRingIdList.append(ring.ring_id)\n                    if verbose: print \"ligand ring_ID: \", ring.ring_id,\n                    if ring.IsAromatic():\n                        if verbose: print \"aromatic\"\n                        ligAroRingList.append(ring)\n                    else:\n                        if verbose: print \"saturated\"\n    for ring in mol.sssr:\n        if ring.ring_id not in ligRingIdList:\n            recRingList.append(ring)\n            if ring.IsAromatic():\n                recAroRingList.append(ring)\n    if verbose: print \"\\nReceptor has \", len(recRingList), \" rings,\",\n    if verbose: print \" has \", len(recAroRingList), \" aromatic rings.\"\n\n    # Find and show the rings\n    ligRingCenter = ob.vector3()\n    recRingCenter = ob.vector3()\n    ligNorm1 = ob.vector3()\n    ligNorm2 = ob.vector3()\n    recNorm1 = ob.vector3()\n    recNorm2 = ob.vector3()\n    count = 0\n    lig_ring_index = 0\n    for ligRing in ligAroRingList:\n        lig_ring_index += 1\n        ligRing.findCenterAndNormal(ligRingCenter, ligNorm1, ligNorm2)\n        rec_ring_index = 0\n        for recRing in recAroRingList:\n            rec_ring_index += 1\n            recRing.findCenterAndNormal(recRingCenter, recNorm1, recNorm2)\n            dist = ligRingCenter.distSq(recRingCenter) ** 0.5\n            angle = vecAngle(ligNorm1, recNorm1)\n            if (dist < centroid_distance and (angle < dih_parallel or angle > dih_tshape)):  # the criteria\n                count += 1\n                if verbose: print \"Pi-Pi ring pairs: %3s,%3s  Angle(deg.): %5.2f  Distance(A): %.2f\" % (recRing.ring_id, ligRing.ring_id, angle, dist)\n    if verbose: print \"Total Pi-Pi interactions:\", count\n    return count\n\n\nif __name__ == '__main__':\n    pdb_file = r'C:\\CloudStation\\Epicat\\Git\\PiViewer\\1ACJ.pdb'\n    lig_name = 'THA'\n    find_PiPi(pdb_file, lig_name, 5.0, 25, 80)\n", "meta": {"hexsha": "e0654f0f8716d86a6ffc8746503617fd7d763d4e", "size": 5582, "ext": "py", "lang": "Python", "max_stars_repo_path": "PiViewer.py", "max_stars_repo_name": "hugecadd/PiViewer", "max_stars_repo_head_hexsha": "5d23e2a3a606fb550c1b0edaa39dd76f22d17201", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-11-14T08:04:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-19T02:21:37.000Z", "max_issues_repo_path": "PiViewer.py", "max_issues_repo_name": "klmh001/PiViewer", "max_issues_repo_head_hexsha": "5d23e2a3a606fb550c1b0edaa39dd76f22d17201", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PiViewer.py", "max_forks_repo_name": "klmh001/PiViewer", "max_forks_repo_head_hexsha": "5d23e2a3a606fb550c1b0edaa39dd76f22d17201", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-20T19:10:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-20T19:10:01.000Z", "avg_line_length": 37.9727891156, "max_line_length": 150, "alphanum_fraction": 0.6268362594, "include": true, "reason": "import numpy", "num_tokens": 1419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808532, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.1562185769988645}}
{"text": "#!/usr/bin/env python3\n\nimport gemmi\nimport copy\nimport numpy as np\nfrom scipy.spatial import distance\nimport string\nfrom rdkit import Chem\nfrom rdkit.Geometry import Point3D\nimport warnings\n\nfrom . import xyz2mol\n\nimport argparse\n\n\ndef parse_arguments():\n\n    \"\"\"\n    Parse command line arguments.\n    \"\"\"\n\n    parser = argparse.ArgumentParser(\n        description=\"Python script for building supercell that can be used with PBC in MD simulation.\"\n        )\n\n    parser.add_argument(\n        '--input', \n        \"-i\", \n        type=str, \n        help=\"Input cif file\", \n        required=True\n        )\n\n    parser.add_argument(\n        '--prefix', \n        \"-pre\", \n        type=str, \n        help=\"Prefix for pdb and csv file.\", \n        required=True\n        )\n\n    parser.add_argument(\n        '--a_min_max', \n        \"-a\", \n        type=float, \n        help=\"If this is two arguments: Minimum and maximum unit cell replicates along direction `a`. \\\nIf this is a single argument: Minimum length of axis `a` in the supercell. Units [nm]\", \n        required=False,\n        default=[-1,1],\n        nargs='+',\n        )\n\n    parser.add_argument(\n        '--b_min_max', \n        \"-b\", \n        type=float, \n        help=\"If this is two arguments: Minimum and maximum unit cell replicates along direction `b`. \\\nIf this is a single argument: Minimum length of axis `b` in the supercell. Units [nm]\", \n        required=False,\n        default=[-1,1],\n        nargs='+',\n        )\n\n    parser.add_argument(\n        '--c_min_max', \n        \"-c\", \n        type=float, \n        help=\"If this is two arguments: Minimum and maximum unit cell replicates along direction `c`. \\\nIf this is a single argument: Minimum length of axis `c` in the supercell. Units [nm]\", \n        required=False,\n        default=[-1,1],\n        nargs='+',\n        )\n\n    parser.add_argument(\n        '--addhs', \n        \"-ah\", \n        action='store_true',\n        help=\"Remove any existing hydrogen and add protonate molecule. Requires OpenEye Toolkits.\", \n        required=False,\n        default=False,\n        )\n\n    parser.add_argument(\n        '--addwater', \n        \"-aw\", \n        type=int, \n        help=\"Number of water molecules to add\", \n        required=False,\n        default=0,\n        )\n\n    parser.add_argument(\n        '--use_symmetry_operations', \n        \"-op\", \n        action='store_true',\n        help=\"Use symmetry operations in cif file instead of space group.\", \n        required=False,\n        default=False,\n        )\n    \n    parser.add_argument(\n        '--n_protonation_attempts', \n        \"-np\", \n        type=int, \n        help=\"Number of attempts to compute protonatation states in  unit cell.\", \n        required=False,\n        default=0,\n        )\n\n    parser.add_argument(\n        '--use_openeye', \n        \"-oe\", \n        action='store_true',\n        help=\"Use openeye-toolkit for topology building. Otherwise use xyz2mol.\", \n        required=False,\n        default=False,\n        )\n\n    return parser.parse_args()\n\n\ndef combine_mols(mol_list):\n\n    mol_list  = copy.deepcopy(mol_list)\n    N_mol_per_unitcell = len(mol_list)\n    mol_combo = Chem.Mol()\n    for mol in mol_list:\n        mol_combo = Chem.CombineMols(mol_combo, mol)\n    return mol_combo\n\n\nclass FfWrapper(object):\n\n    def __init__(self, mol, only_hydrogen=True):\n\n        from rdkit.Chem import AllChem as Chem\n\n        self._mol = copy.deepcopy(mol)\n\n        mp  = Chem.MMFFGetMoleculeProperties(mol)\n        self._ffm = Chem.MMFFGetMoleculeForceField(mol, mp)\n\n        self._H_atom_list   = list()\n        self._all_atom_list = list()\n        for atom in mol.GetAtoms():\n            if atom.GetAtomicNum() == 1:\n                self._H_atom_list.append(atom.GetIdx())\n            self._all_atom_list.append(atom.GetIdx())\n\n        self._H_atom_list = np.array(self._H_atom_list)\n        self._H_idxs = np.arange(mol.GetNumAtoms()*3, dtype=int)\n        self._H_idxs = self._H_idxs.reshape((mol.GetNumAtoms(), 3))\n        self._H_idxs = self._H_idxs[self._H_atom_list]\n        self._H_idxs_flat = self._H_idxs.flatten()\n\n        self._all_atom_list = np.array(self._all_atom_list)\n        self._all_idxs = np.arange(mol.GetNumAtoms()*3, dtype=int)\n        self._all_idxs = self._all_idxs.reshape((mol.GetNumAtoms(), 3))\n        self._all_idxs_flat = self._H_idxs.flatten()\n\n        self._num_all_atoms = len(self._all_atom_list)\n        self._num_H_atoms   = len(self._H_atom_list)\n\n        self.only_hydrogen = only_hydrogen\n\n    @property\n    def num_all_atoms(self):\n        return self._num_all_atoms\n\n    @property\n    def num_H_atoms(self):\n        return self._num_H_atoms\n\n    @property\n    def H_atom_list(self):\n        return self._H_atom_list\n\n    @property\n    def H_idxs(self):\n        return self._H_idxs\n\n    @property\n    def H_idxs_flat(self):\n        return self._H_idxs_flat\n\n    @property\n    def all_atom_list(self):\n        return self._all_atom_list\n\n    @property\n    def all_idxs(self):\n        return self._all_idxs\n\n    @property\n    def all_idxs_flat(self):\n        return self._all_idxs_flat\n\n    @property\n    def ffm(self):\n        return self._ffm\n\n    @property\n    def mol(self):\n        return self._mol\n\n    @property\n    def pos(self):\n        pos = np.array(self.ffm.Positions())\n        if self.only_hydrogen:\n            pos = pos[self.H_idxs_flat].tolist()\n        return pos\n\n    @pos.setter\n    def pos(self, pos):\n\n        from rdkit.Chem import AllChem as Chem\n\n        conformer      = self._mol.GetConformer()\n\n        if self.only_hydrogen:\n            pos_stack = np.array(pos).reshape((self.num_H_atoms, 3))\n            for H_atm_idx, atm_idx in enumerate(self.H_atom_list):\n                conformer.SetAtomPosition(\n                    int(atm_idx),\n                    Point3D(\n                        *pos_stack[H_atm_idx]\n                        )\n                    )\n        else:\n            pos_stack = np.array(pos).reshape((self.num_all_atoms, 3))\n            for atm_idx in range(self._mol.GetNumAtoms()):\n                conformer.SetAtomPosition(\n                    int(atm_idx),\n                    Point3D(\n                        *pos_stack[atm_idx]\n                        )\n                    )\n\n        mp  = Chem.MMFFGetMoleculeProperties(self._mol)\n        self._ffm = Chem.MMFFGetMoleculeForceField(self._mol, mp)\n\n    def ene(self,x):\n        pos = self.ffm.Positions()\n        pos = np.array(pos)\n        if self.only_hydrogen:\n            pos[self.H_idxs_flat] = x\n        else:\n            pos[:] = x\n        pos = pos.tolist()\n        return self.ffm.CalcEnergy(pos)\n\n    def grad(self,x):\n        pos = self.ffm.Positions()\n        pos = np.array(pos)\n        if self.only_hydrogen:\n            pos[self.H_idxs_flat] = x\n        else:\n            pos[:] = x\n        pos = pos.tolist()\n        grad_vals = self.ffm.CalcGrad(pos)\n        grad_vals = np.array(grad_vals)[self.H_idxs_flat]\n        grad_vals = grad_vals.tolist()\n        return grad_vals\n\n\ndef apply_delta_hydrogen(\n    mol_list,\n    delta_hydrogen_dict\n    ):\n\n    import numpy as np\n    from rdkit.Chem import AllChem as Chem\n    import copy\n\n    mol_combo   = combine_mols(mol_list)\n    emol        = Chem.EditableMol(mol_combo)\n    offset_list = np.zeros(mol_combo.GetNumAtoms(), dtype=int)\n    for atomidx, switch in delta_hydrogen_dict.items():\n        atom    = mol_combo.GetAtomWithIdx(atomidx)\n        charge  = atom.GetFormalCharge()\n        if switch == 1:\n            Hatom = Chem.Atom(1)\n            idx1  = emol.AddAtom(Hatom)\n            Patom = Chem.AtomFromSmarts(atom.GetSmarts())\n            Patom.SetFormalCharge(charge+1)\n            emol.ReplaceAtom(\n                atomidx+int(offset_list[atomidx]), \n                Patom\n                )\n            emol.AddBond(\n                idx1,\n                atomidx+int(offset_list[atomidx]),\n                Chem.BondType.SINGLE\n            )\n            \n        elif switch == -1:\n            for n_atom in atom.GetNeighbors():\n                if n_atom.GetAtomicNum() == 1:\n                    idx1  = n_atom.GetIdx()\n                    Patom = Chem.AtomFromSmarts(atom.GetSmarts())\n                    Patom.SetFormalCharge(charge-1)\n                    emol.ReplaceAtom(\n                        atomidx+int(offset_list[atomidx]),\n                        Patom\n                        )\n                    emol.RemoveAtom(\n                        idx1+int(offset_list[idx1])\n                        )\n                    offset_list[idx1:] -= 1\n                    break\n        else:\n            ### Nix.\n            pass\n    mol_combo_prot = emol.GetMol()\n    Chem.SanitizeMol(mol_combo_prot)\n    return Chem.GetMolFrags(mol_combo_prot, asMols=True)\n    \n\ndef minimize_H(\n    mol_list,\n    ):\n\n    import numpy as np\n    from rdkit.Chem import AllChem as Chem\n    from scipy import optimize\n    import copy\n\n    mol_combo = combine_mols(mol_list)\n    ff        = FfWrapper(mol_combo, only_hydrogen=True)\n    x0        = ff.pos\n    \n    result = optimize.minimize(\n        fun=ff.ene,\n        x0=x0,\n        jac=ff.grad,\n        method=\"L-BFGS-B\"\n        )\n    ff.pos = result.x\n    energy = ff.ene(result.x)\n\n    return energy, Chem.GetMolFrags(ff.mol, asMols=True)\n\n\ndef assign_protonation_states(\n    cell,\n    mol_list,\n    N_iterations=10):\n\n    \"\"\"\n    Find the energetically best protonation state of the unitcell.\n    \"\"\"\n\n    import numpy as np\n    from rdkit.Chem import AllChem as Chem\n    import copy\n\n    mol_combo = combine_mols(mol_list)\n    polar_heavy_atom = Chem.MolFromSmarts(\"[#7,#8,#16]\")\n    matches = mol_combo.GetSubstructMatches(\n        polar_heavy_atom, \n        uniquify=False\n        )\n    N_matches = len(matches)\n    delta_hydrogen_dict_best = dict()\n    for atm_idx in matches:\n        atm_idx = int(atm_idx[0])\n        delta_hydrogen_dict_best[atm_idx] = 0\n    energy_best = 999999999999999999999.\n    mol_list_best = copy.deepcopy(mol_list)\n    N_mol_per_unitcell = len(mol_list)\n\n    charge0 = Chem.GetFormalCharge(mol_combo)\n\n    #with open(f\"./best_init.pdb\", \"w\") as fopen:\n    #    fopen.write(\n    #        Chem.MolToPDBBlock(\n    #            combine_mols(\n    #                mol_list_best\n    #                )\n    #            )\n    #        )\n    #count = 0\n    for _ in range(N_iterations):\n        delta_hydrogen_dict = copy.deepcopy(\n            delta_hydrogen_dict_best\n            )\n        for i in range(N_matches):\n            atm_idx_i = int(matches[i][0])\n            delta0_i  = delta_hydrogen_dict[atm_idx_i]\n            for j in range(i+1, N_matches):\n                atm_idx_j = int(matches[j][0])\n                delta0_j  = delta_hydrogen_dict[atm_idx_j]\n                for dij in [[-1,1],[1,-1]]:\n                    ###  0: Do nothing\n                    ### +1: Add hydrogen\n                    ### -1: Remove hydrogen\n                    delta_hydrogen_dict[atm_idx_i] = dij[0]\n                    delta_hydrogen_dict[atm_idx_j] = dij[1]\n                    mol_list_prot = apply_delta_hydrogen(\n                        copy.deepcopy(mol_list),\n                        delta_hydrogen_dict\n                        )\n                    charge = Chem.GetFormalCharge(\n                        combine_mols(mol_list_prot)\n                        )\n                    if charge == charge0:\n                        mol_list_prot, _, _ = make_supercell(\n                            cell,\n                            mol_list_prot,\n                            0, 2,\n                            0, 2,\n                            0, 2)\n                        energy, mol_list_prot = minimize_H(mol_list_prot)\n                        if energy < energy_best:\n                            energy_best = energy\n                            delta_hydrogen_dict_best = copy.deepcopy(\n                                delta_hydrogen_dict\n                                )\n                            mol_list_best = copy.deepcopy(\n                                mol_list_prot[:N_mol_per_unitcell]\n                                )\n                delta_hydrogen_dict[atm_idx_j] = delta0_j\n            delta_hydrogen_dict[atm_idx_i] = delta0_i\n        #print(f\"Best energy {energy_best:4.2f}\")\n        #with open(f\"./best_{count}.pdb\", \"w\") as fopen:\n        #    fopen.write(\n        #        Chem.MolToPDBBlock(\n        #            combine_mols(\n        #                mol_list_best\n        #                )\n        #            )\n        #        )\n        #count += 1\n\n    return mol_list_best\n\n\ndef get_nonoverlapping_atoms(atom_crds_ortho, filter_overlapping=False):\n\n    \"\"\"\n    Retrieve indices of rows in `atom_crds_ortho` (N,3) list\n    that correspond to non-overlapping atoms.\n    If `filter_overlapping==True`, then one of the overlapping (not clear \n    which one though) atoms will be retained.\n\n    \"\"\"\n\n    from scipy.spatial import distance\n\n    atom_crds_ortho_cp = np.copy(atom_crds_ortho)\n    dists  = distance.cdist(atom_crds_ortho_cp, atom_crds_ortho_cp)\n    np.fill_diagonal(dists, np.inf)\n    if filter_overlapping:\n        tril_idxs = np.tril_indices(atom_crds_ortho.shape[0])\n        dists[tril_idxs] = np.inf\n    invalids = np.where(dists < 0.01)[0]\n    invalids = np.unique(invalids)\n    valids   = np.arange(atom_crds_ortho_cp.shape[0], dtype=int)\n    valids   = np.delete(valids, invalids)\n\n    return valids\n\n\ndef random_fill(\n    cell, \n    mol_list, \n    N_per_unitcell, \n    radius=1.4, \n    smiles=\"[H]O[H]\"):\n\n    \"\"\"\n    Randomly fill unit cell with molecules.\n    \"\"\"\n\n    from rdkit.Chem import AllChem as Chem\n    from rdkit.Geometry import Point3D\n    import numpy as np\n    from scipy.spatial import distance\n    import gemmi\n    import copy\n\n    vdw_dict = {\n        1  : 1.09, #H\n        6  : 1.7,  #C\n        7  : 1.55, #N\n        8  : 1.52, #O\n        9  : 1.47, #F\n        15 : 1.8,  #P\n        16 : 1.8,  #S\n        17 : 1.75  #Cl\n    }\n\n    mol = Chem.MolFromSmiles(smiles)\n    mol = Chem.AddHs(mol)\n\n    Chem.EmbedMolecule(mol)\n    Chem.UFFOptimizeMolecule(mol)\n\n    conformer      = mol.GetConformer()\n    atom_crds_mol  = conformer.GetPositions()\n    atom_crds_mol  = np.array(atom_crds_mol)\n\n    replicated_mol_list, _, _ = make_supercell(\n        cell,\n        mol_list,\n        -1, 1,\n        -1, 1,\n        -1, 1)\n\n    atom_crds_xtal = list()\n    atom_radii_xtal = list()\n    for mol_r in replicated_mol_list:\n        conf     = mol_r.GetConformer(0)\n        conf_pos = conf.GetPositions()\n        for atom in mol_r.GetAtoms():\n            if atom.GetAtomicNum() == 1:\n                continue\n            atom_radii_xtal.append(\n                vdw_dict[atom.GetAtomicNum()]\n            )\n            atom_crds_xtal.append(\n                conf_pos[atom.GetIdx()]\n                )\n    atom_crds_xtal = np.array(atom_crds_xtal)\n    atom_radii_xtal = np.array(atom_radii_xtal)\n    atom_radii_xtal += radius\n\n    grid = list()\n    for a in np.linspace(0., 1., 50, True):\n        for b in np.linspace(0., 1., 50, True):\n            for c in np.linspace(0., 1., 50, True):\n                frac  = np.array([a,b,c], dtype=float)\n                ortho = cell.orthogonalize(\n                    gemmi.Fractional(*frac)\n                            ).tolist()\n                dists      = distance.cdist(atom_crds_xtal, [ortho])\n                is_outside = np.all(dists[:,0] > atom_radii_xtal)\n                if is_outside:\n                    grid.append(ortho)\n\n    overlap = True\n    grid    = np.array(grid)\n    print(f\"Found {grid.shape[0]} / {50**3} valid grid points.\")\n    print(\"Scanning overlap...\")\n    while overlap:\n        mask           = np.arange(grid.shape[0], dtype=int)\n        mask_selection = np.random.choice(\n            mask, \n            size=N_per_unitcell, \n            replace=False\n            )\n        grid_selection = grid[mask_selection]\n        grid_selection_query = np.copy(grid_selection).tolist()\n        for crd in grid_selection:\n            frac = cell.fractionalize(\n                gemmi.Position(\n                    *crd\n                    )\n                ).tolist()\n            frac  = np.array(frac)\n            for a in [-1.,0.,1.]:\n                for b in [-1.,0.,1.]:\n                    for c in [-1.,0.,1.]:\n                        if (a==0) & (b==0) & (c==0):\n                            continue\n                        frac += [a,b,c]\n                        ortho = cell.orthogonalize(\n                            gemmi.Fractional(*frac)\n                                    ).tolist()\n                        grid_selection_query.append(ortho)\n                        frac -= [a,b,c]\n\n        grid_selection_query = np.array(grid_selection_query)\n        dists = distance.cdist(grid_selection_query, grid_selection_query)\n        np.fill_diagonal(dists, np.inf)\n        min_dist = np.min(dists)\n        if min_dist > 2.*radius:\n            overlap = False\n\n    import copy\n    mol_list_new = copy.deepcopy(mol_list)\n    for crds in grid_selection:\n        mol_cp         = copy.deepcopy(mol)\n        conformer      = mol_cp.GetConformer()\n        atom_crds_mol  = conformer.GetPositions()\n        trans          = crds - np.mean(atom_crds_mol, axis=0)\n        atom_crds_mol += trans\n        for atm_idx in range(mol_cp.GetNumAtoms()):\n            conformer.SetAtomPosition(\n                atm_idx,\n                Point3D(*atom_crds_mol[atm_idx])\n            )\n        mol_list_new.append(mol_cp)\n\n    return mol_list_new\n\n\ndef make_P1(\n    cell, \n    atom_crds_ortho, \n    atom_num, \n    addhs=False, \n    use_openeye=False):\n\n    \"\"\"\n    Generate the P1 cell. Return tuple with atomic coordinates (in Ang) and\n    atomic numbers of all atoms in P1 cell.\n    \"\"\"\n\n    import networkx as nx\n    from rdkit.Chem import AllChem as Chem\n    from rdkit.Geometry import Point3D\n    import copy\n\n    _atom_crds_ortho = list()\n    _atom_num = list()\n    N_atoms = len(atom_num)\n    for i in range(N_atoms):\n        if addhs:\n            if atom_num[i] != 1:\n                _atom_crds_ortho.append(copy.copy(atom_crds_ortho[i]))\n                _atom_num.append(copy.copy(atom_num[i]))\n        else:\n            _atom_crds_ortho.append(copy.copy(atom_crds_ortho[i]))\n            _atom_num.append(copy.copy(atom_num[i]))\n\n    atom_crds_ortho = _atom_crds_ortho\n    atom_num = _atom_num\n\n    atom_crds_ortho = np.array(atom_crds_ortho, dtype=float)\n    atom_num = np.array(atom_num, dtype=int)\n    nonoverlapping_idxs = get_nonoverlapping_atoms(atom_crds_ortho, filter_overlapping=True)\n    atom_crds_ortho = atom_crds_ortho[nonoverlapping_idxs].tolist()\n    atom_num = atom_num[nonoverlapping_idxs].tolist()\n    N_atoms = len(atom_num)\n\n    found_bond = True\n    ### Terminate if we haven't found any bonds.\n    while found_bond:\n        ### Update the frac coordinates\n        atom_crds_frac = list()\n        for atm_idx in range(N_atoms):\n            frac = cell.fractionalize(\n                gemmi.Position(\n                    *atom_crds_ortho[atm_idx]\n                    )\n                )\n            atom_crds_frac.append(frac.tolist())\n\n        ### Get the \"pre-molecules\" (adjacency matrix with not much chemistry)\n        acmatrix_new, _ = xyz2mol.xyz2AC(\n            atom_num,\n            atom_crds_ortho,\n            0,\n            )\n        acmatrix_best = acmatrix_new\n\n        ### Find the disconnected graphs from the adjacency matrix\n        G           = nx.convert_matrix.from_numpy_matrix(acmatrix_new)\n        G_node_list = list(nx.connected_components(G))\n        ### Translate molecules to neighboring unit cells in + direction\n        ### and check if we can form new bonds. If yes, update `atom_crds_ortho`\n        found_bond = False\n        for g in G_node_list:\n            for a in [0,-1]:\n                for b in [0,-1]:\n                    for c in [0,-1]:\n                        atom_crds_ortho_cp = copy.deepcopy(atom_crds_ortho)\n                        for atm_idx in g:\n                            frac = copy.deepcopy(atom_crds_frac[atm_idx])\n                            frac[0] += a\n                            frac[1] += b\n                            frac[2] += c\n                            ortho = cell.orthogonalize(\n                                gemmi.Fractional(*frac)\n                            ).tolist()\n                            if not ortho in atom_crds_ortho_cp:\n                                atom_crds_ortho_cp[atm_idx] = ortho\n                        acmatrix_new, _ = xyz2mol.xyz2AC(\n                            atom_num,\n                            atom_crds_ortho,\n                            0,\n                        )\n                        if not np.all(acmatrix_new == acmatrix_best) and np.sum(acmatrix_new) >= np.sum(acmatrix_best):\n                            nonoverlapping_idxs = get_nonoverlapping_atoms(atom_crds_ortho_cp)\n                            if nonoverlapping_idxs.size == N_atoms:\n                                atom_crds_ortho = copy.deepcopy(atom_crds_ortho_cp)\n                                acmatrix_best = acmatrix_new\n                                found_bond = True\n\n    acmatrix, _ = xyz2mol.xyz2AC(\n        atom_num,\n        atom_crds_ortho,\n        0,\n        )\n    G           = nx.convert_matrix.from_numpy_matrix(acmatrix)\n    G_node_list = list(nx.connected_components(G))\n    atom_num    = np.array(atom_num, dtype=int)\n    atom_crds_ortho = np.array(atom_crds_ortho)\n    mol_list    = list()\n    for g in G_node_list:\n        g = list(g)\n        _, mol = xyz2mol.xyz2AC(\n                atom_num[g].tolist(), \n                atom_crds_ortho[g].tolist(),\n                0)\n        mol_list.append(mol)\n\n    N_mol           = len(mol_list)\n    atom_crds_ortho = list()\n    atom_num        = list()\n    mol_list_new    = list()\n    for mol_idx in range(N_mol):\n        mol  = mol_list[mol_idx]\n        conf = mol.GetConformer()\n        conf_pos = conf.GetPositions()\n        frac_crds = list()\n        for pos in conf_pos:\n            frac_crds.append(\n                cell.fractionalize(\n                    gemmi.Position(\n                        *pos\n                    )\n                ).tolist()\n            )\n        frac_crds   = np.array(frac_crds)\n        valid_atoms = np.where(\n            (frac_crds[:,0] > 0.) * (frac_crds[:,0] < 1.) *\\\n            (frac_crds[:,1] > 0.) * (frac_crds[:,1] < 1.) *\\\n            (frac_crds[:,2] > 0.) * (frac_crds[:,2] < 1.)\n        )[0]\n        ### If no atom is in uc, bring the molecule into unit cell\n        if valid_atoms.size == 0:\n            is_inside = False\n            for a in [0,-1,1]:\n                for b in [0,-1,1]:\n                    for c in [0,-1,1]:\n                        frac_crds += [a,b,c]\n                        valid_atoms = np.where(\n                            (frac_crds[:,0] > 0.) * (frac_crds[:,0] < 1.) *\\\n                            (frac_crds[:,1] > 0.) * (frac_crds[:,1] < 1.) *\\\n                            (frac_crds[:,2] > 0.) * (frac_crds[:,2] < 1.)\n                        )[0]\n                        if valid_atoms.size != 0:\n                            is_inside = True\n                        else:\n                            frac_crds -= [a,b,c]\n                        if is_inside:\n                            break\n                    if is_inside:\n                        break\n                if is_inside:\n                    break\n            if not is_inside:\n                continue\n\n        frac_crds_query = np.copy(frac_crds[valid_atoms[0]])\n        ### Check for overlap\n        overlap = False\n        for a in [0,-1,1]:\n            for b in [0,-1,1]:\n                for c in [0,-1,1]:\n                    frac_crds_query += [a,b,c]\n                    ortho = cell.orthogonalize(\n                        gemmi.Fractional(*frac_crds_query)\n                    ).tolist()\n                    if len(atom_crds_ortho) > 0:\n                        dists = distance.cdist([ortho], atom_crds_ortho)\n                        valids = np.where(dists < 0.01)[0]\n                        if valids.size > 0:\n                            overlap = True\n                    frac_crds_query -= [a,b,c]\n        if not overlap:\n            for atm_idx, frac in enumerate(frac_crds):\n                ortho = cell.orthogonalize(\n                    gemmi.Fractional(*frac)\n                ).tolist()\n                atom_crds_ortho.append(ortho)\n                rd_atom = mol.GetAtomWithIdx(atm_idx)\n                atom_num.append(rd_atom.GetAtomicNum())\n                conf.SetAtomPosition(\n                    atm_idx,\n                    Point3D(*ortho)\n                )\n            mol_list_new.append(mol)\n\n    mol_list = list()\n    if addhs:\n        if use_openeye:\n            import warnings\n            warnings.warn(\"With addhs=True, we automatically set use_openeye=True.\")\n        from openeye import oechem\n        from openeye import oequacpac\n        from xtalmdscripts.supercellbuilding.oe_utils import rdmol_from_oemol\n        from xtalmdscripts.supercellbuilding.oe_utils import oemol_from_rdmol\n\n        count = 0\n        for mol in mol_list_new:\n            oemol = oechem.OEMol()\n            oemol.SetDimension(3)\n            conf_pos = mol.GetConformer(0).GetPositions()\n            crds = list()\n            for atm_idx in range(mol.GetNumAtoms()):\n                atom = mol.GetAtomWithIdx(atm_idx)\n                oemol.NewAtom(int(atom.GetAtomicNum()))\n                crds.extend(conf_pos[atm_idx])\n            oemol.SetCoords(crds)\n\n            oechem.OEAssignAromaticFlags(oemol)\n            oechem.OEDetermineConnectivity(oemol)\n            oechem.OEFindRingAtomsAndBonds(oemol)\n            oechem.OEPerceiveBondOrders(oemol)\n            oechem.OE3DToInternalStereo(oemol)\n            oechem.OEPerceiveChiral(oemol)\n            oechem.OEAssignImplicitHydrogens(oemol)\n            oechem.OEAssignFormalCharges(oemol)\n\n            oequacpac.OERemoveFormalCharge(oemol)\n            oechem.OEAddExplicitHydrogens(oemol)\n\n            oechem.OEAssignAromaticFlags(oemol)\n            mol = rdmol_from_oemol(oemol)\n            Chem.AssignStereochemistryFrom3D(mol)\n            mol_list.append(mol)\n\n            #with open(f\"./test_{count}.pdb\", \"w\") as fopen:\n            #    fopen.write(Chem.MolToPDBBlock(mol))\n            count += 1\n\n    else:\n        if use_openeye:\n            from openeye import oechem\n            from openeye import oequacpac\n            from xtalmdscripts.supercellbuilding.oe_utils import rdmol_from_oemol\n            from xtalmdscripts.supercellbuilding.oe_utils import oemol_from_rdmol\n\n            count = 0\n            for mol in mol_list_new:\n                oemol = oechem.OEMol()\n                oemol.SetDimension(3)\n                conf_pos = mol.GetConformer(0).GetPositions()\n                crds = list()\n                for atm_idx in range(mol.GetNumAtoms()):\n                    atom = mol.GetAtomWithIdx(atm_idx)\n                    oemol.NewAtom(int(atom.GetAtomicNum()))\n                    crds.extend(conf_pos[atm_idx])\n                oemol.SetCoords(crds)\n\n                oechem.OEDetermineConnectivity(oemol)\n                oechem.OEFindRingAtomsAndBonds(oemol)\n                oechem.OEPerceiveBondOrders(oemol)\n                oechem.OE3DToInternalStereo(oemol)\n                oechem.OEPerceiveChiral(oemol)\n                oechem.OEAssignFormalCharges(oemol)\n\n                oechem.OEAssignAromaticFlags(oemol)\n                mol = rdmol_from_oemol(oemol)\n                Chem.AssignStereochemistryFrom3D(mol)\n                mol_list.append(mol)\n\n                #with open(f\"./test_{count}.pdb\", \"w\") as fopen:\n                #    fopen.write(Chem.MolToPDBBlock(mol))\n                count += 1\n\n        else:\n            acmatrix, _ = xyz2mol.xyz2AC(\n                atom_num,\n                atom_crds_ortho,\n                0,\n                )\n            G           = nx.convert_matrix.from_numpy_matrix(acmatrix)\n            G_node_list = list(nx.connected_components(G))\n            atom_num    = np.array(atom_num, dtype=int)\n            atom_crds_ortho = np.array(atom_crds_ortho)\n            for g in G_node_list:\n                g = list(g)\n                mol = Chem.GetMolFrags(\n                    xyz2mol.xyz2mol(\n                        atom_num[g].tolist(), \n                        atom_crds_ortho[g].tolist(),\n                        charge=0)[0], \n                    asMols=True\n                )[0]\n                mol_list.append(mol)\n\n    #strc_write               = gemmi.Structure()\n    #strc_write.spacegroup_hm = \"P1\"\n    #strc_write.cell          = cell\n    #with open(\"./make_p1_test.pdb\", \"w\") as fopen:\n    #    fopen.write(get_pdb_block(mol_list, strc_write))\n\n    return mol_list\n\n\ndef make_supercell(\n    cell,\n    mol_list, \n    a_min, a_max,\n    b_min, b_max,\n    c_min, c_max):\n\n    \"\"\"\n    Generate supercell based specified parameters. Assuming that `atom_crds_ortho`\n    and `atom_num` are for P1 cell. See method `make_P1`. Returns list of rdkit mol\n    objects with all molecules in supercell, list containing an int that is unique \n    among the molecules in a unit cell, list containing the frac coordinates of the\n    unit cell origins in the basis of the supercell.\n    \"\"\"\n\n    a_replicate = np.arange(a_min,a_max+1, dtype=int)\n    b_replicate = np.arange(b_min,b_max+1, dtype=int)\n    c_replicate = np.arange(c_min,c_max+1, dtype=int)\n\n    N_mol               = len(mol_list)\n    replicated_mol_list = list()\n    mol_identifies      = list()\n    unitcell_in_supercell_fracs = list()\n    for a in a_replicate:\n        for b in b_replicate:\n            for c in c_replicate:\n                for mol_idx in range(N_mol):\n                    mol      = copy.deepcopy(mol_list[mol_idx])\n                    conf     = mol.GetConformer(0)\n                    conf_pos = conf.GetPositions()\n                    N_atoms  = mol.GetNumAtoms()\n                    \n                    for atom_idx in range(N_atoms):\n                        pos      = conf_pos[atom_idx]                    \n                        frac_pos = cell.fractionalize(\n                            gemmi.Position(*pos)\n                        )\n                        frac_pos.x += a\n                        frac_pos.y += b\n                        frac_pos.z += c\n                        \n                        conf_pos_abc = cell.orthogonalize(frac_pos).tolist()\n                            \n                        conf.SetAtomPosition(\n                            atom_idx,\n                            Point3D(*conf_pos_abc)\n                        )\n\n                    replicated_mol_list.append(mol)\n                    conf = mol.GetConformer(0)\n                    mol_identifies.append(mol_idx)\n                    unitcell_in_supercell_fracs.append([a,b,c])\n\n    return replicated_mol_list, mol_identifies, unitcell_in_supercell_fracs\n\n\ndef clean_names(mol_list):\n\n    \"\"\"\n    Uniquify atom and residue names. Equalize residue names for\n    chemically equal residues.\n    \"\"\"\n\n    import copy\n\n    mol_list_new = list()\n    N_mol = len(mol_list)\n    for mol_idx in range(N_mol):\n        mol = copy.deepcopy(mol_list[mol_idx])\n        \n        atom_counts_dict = dict()\n        for atom in mol.GetAtoms():\n            mi  = Chem.AtomPDBResidueInfo()\n            mi.SetIsHeteroAtom(True)\n            mi.SetResidueName(f'M{mol_idx}'.ljust(3))\n            mi.SetResidueNumber(mol_idx + 1)\n            mi.SetOccupancy(1.0)\n            mi.SetTempFactor(0.0)\n            atomic_num = atom.GetAtomicNum()\n            atomic_ele = atom.GetSymbol()\n            if not atomic_num in atom_counts_dict:\n                atom_counts_dict[atomic_num] = 1\n            else:\n                atom_counts_dict[atomic_num] += 1\n            mi.SetName(\n                f\"{atomic_ele}{atom_counts_dict[atomic_num]}\".ljust(4)\n                )\n            atom.SetMonomerInfo(mi)\n\n        mol_list_new.append(mol)\n\n    return mol_list_new\n\n\ndef get_unique_mapping(\n    mol_list, \n    stereochemistry=True\n    ):\n\n    \"\"\"\n    Get unique mapping dict and list of unique rdkit mol objects in list of rdkit mol objects.\n    if `stereochemistry=True`, the mapping will honor stereochemistry.\n    \"\"\"\n\n    N_mol = len(mol_list)\n\n    smiles_list = [Chem.MolToSmiles(mol, isomericSmiles=stereochemistry) for mol in mol_list]\n    smiles_list_unique = set(smiles_list)\n    smiles_list_unique = list(smiles_list_unique)\n\n    rdmol_list_unique  = list()\n    unique_mapping     = dict()\n    for smiles_unique_idx, smiles_unique in enumerate(smiles_list_unique):\n        found_unique = False\n        for mol_idx in range(N_mol):\n            mol    = mol_list[mol_idx]\n            smiles = smiles_list[mol_idx]\n            if smiles == smiles_unique:\n                if not found_unique:\n                    rdmol_list_unique.append(mol)\n                    found_unique = True\n                    unique_mapping[mol_idx] = smiles_unique_idx\n                else:\n                    unique_mapping[mol_idx] = smiles_unique_idx\n\n    assert len(unique_mapping) == N_mol\n\n    return unique_mapping, rdmol_list_unique\n\n\ndef equalize_rdmols(\n    mol_list, \n    stereochemistry=True\n    ):\n\n    \"\"\"\n    Get list of rdkit mol objects in which all chemically idential mol objects\n    have identical topology and pdb monomer info. Only difference are coordinates.\n    If `stereochemistry=True` it will honor stereochemistry.\n    \"\"\"\n\n    import copy\n\n    unique_mapping, rdmol_list_unique = get_unique_mapping(mol_list, stereochemistry)\n\n    mol_list_new = copy.deepcopy(mol_list)\n    for mol_idx in unique_mapping:\n        if mol_idx == unique_mapping[mol_idx]:\n            mol_info = copy.deepcopy(rdmol_list_unique[unique_mapping[mol_idx]])\n            for mol_info_atm_idx in range(mol_info.GetNumAtoms()):\n                mi = mol_info.GetAtomWithIdx(mol_info_atm_idx).GetMonomerInfo()\n                mi.SetResidueName(f'M{unique_mapping[mol_idx]}'.ljust(3))\n                mi.SetResidueNumber(mol_idx + 1)\n                mol_info.GetAtomWithIdx(mol_info_atm_idx).SetMonomerInfo(mi)\n        else:\n            ### This is the molecule that holds the correct coordinates\n            ### and pdb monomer info.\n            mol_crds = copy.deepcopy(mol_list[mol_idx])\n            ### This is the molecule that holds the correct names, ordering, etc...\n            mol_info = copy.deepcopy(rdmol_list_unique[unique_mapping[mol_idx]])\n            match   = mol_crds.GetSubstructMatch(mol_info, useChirality=stereochemistry)\n\n            conf_pos_crds = mol_crds.GetConformer(0).GetPositions()\n            conf_info     = mol_info.GetConformer(0)\n            for mol_info_atm_idx, mol_crds_atm_idx in enumerate(match):\n                pos = conf_pos_crds[mol_crds_atm_idx]\n                conf_info.SetAtomPosition(\n                    mol_info_atm_idx,\n                    Point3D(*pos)\n                )\n                ### Note, we cannot `copy.copy(mi_original)`\n                ### or `copy.copy(mol_target.GetAtomWithIdx(atm_idx))`\n                mi = mol_info.GetAtomWithIdx(mol_info_atm_idx).GetMonomerInfo()\n                mi.SetResidueName(f'M{unique_mapping[mol_idx]}'.ljust(3))\n                mi.SetResidueNumber(mol_idx + 1)\n                mol_info.GetAtomWithIdx(mol_info_atm_idx).SetMonomerInfo(mi)\n\n        mol_list_new[mol_idx] = mol_info\n\n    return mol_list_new\n\n\ndef generate_replicated_mol_list(\n    cell,\n    atom_crds_ortho,\n    atom_num, \n    a_min_max,\n    b_min_max,\n    c_min_max,\n    addhs=False,\n    protonate_unitcell=True,\n    addwater=0,\n    N_iterations_protonation=0,\n    use_openeye=False,\n    ):\n\n    \"\"\"\n    Generate rdkit mol object list for molecules in supercell. supercell is generated\n    according input parameters.\n    \"\"\"\n\n    mol_list = make_P1(cell, atom_crds_ortho, atom_num, addhs, use_openeye)\n    if N_iterations_protonation > 0: \n        mol_list = assign_protonation_states(\n            cell=cell, \n            mol_list=mol_list, \n            N_iterations=N_iterations_protonation\n            )\n    if addwater > 0:\n        mol_list = random_fill(\n            cell,\n            mol_list,\n            N_per_unitcell=addwater,\n            radius=0.5,\n            smiles=\"O\"\n            )\n    mol_list = clean_names(mol_list)\n\n    replicated_mol_list, mol_identifies, unitcell_in_supercell_fracs = make_supercell(\n        cell,\n        mol_list, \n        a_min_max[0], a_min_max[1],\n        b_min_max[0], b_min_max[1],\n        c_min_max[0], c_min_max[1],\n        )\n\n    replicated_mol_list = equalize_rdmols(replicated_mol_list)\n\n    return replicated_mol_list, mol_identifies, unitcell_in_supercell_fracs\n\n\ndef get_pdb_block(\n    replicated_mol_list, \n    strc_write):\n\n    \"\"\"\n    Get pdb block as str. strc_write is gemmi structure object and must reflect\n    the dimensions of the supercell.\n    \"\"\"\n\n    ### Combine all rdmols in a single big rdmol\n    N_mol   = len(replicated_mol_list)\n    mol_new = Chem.Mol()\n    for mol_idx in range(N_mol):\n        mol = copy.deepcopy(replicated_mol_list[mol_idx])\n        mol_new = Chem.CombineMols(mol_new, mol)\n    header = strc_write.make_pdb_headers()\n\n    ### With the flavor options, one can control what is written\n    ### to the pdb block.\n    ###\n    ### flavor: (optional)\n    ### flavor & 1 : Write MODEL/ENDMDL lines around each record\n    ### flavor & 2 : Don’t write any CONECT records\n    ### flavor & 4 : Write CONECT records in both directions\n    ### flavor & 8 : Don’t use multiple CONECTs to encode bond order\n    ### flavor & 16 : Write MASTER record\n    ### flavor & 32 : Write TER record\n\n    crds_block = Chem.MolToPDBBlock(mol_new, flavor=8|32)\n    pdb_block  = header + crds_block\n\n    return pdb_block\n\n\ndef get_pdb_str(\n    replicated_mol_list,\n    strc,\n    a_min_max,\n    b_min_max,\n    c_min_max):\n\n    \"\"\"\n    Get full pdb file as str.\n    \"\"\"\n\n    import gemmi\n\n    ### Write pdb file\n    ### ==============\n    a_len = np.max(a_min_max) - np.min(a_min_max) + 1.\n    b_len = np.max(b_min_max) - np.min(b_min_max) + 1.\n    c_len = np.max(c_min_max) - np.min(c_min_max) + 1.\n\n    strc_write               = gemmi.Structure()\n    strc_write.spacegroup_hm = strc.spacegroup_hm\n    strc_write.cell          = gemmi.UnitCell(\n        strc.cell.a * a_len,\n        strc.cell.b * b_len,\n        strc.cell.c * c_len,\n        strc.cell.alpha,\n        strc.cell.beta,\n        strc.cell.gamma\n    )\n\n    pdb_block = get_pdb_block(replicated_mol_list, strc_write)\n\n    return pdb_block\n    \n\ndef parse_cif(\n    cif_path, \n    use_symmetry_operations=False\n    ):\n\n    \"\"\"\n    Parse cif file as gemmis structure object.\n    \"\"\"\n\n    import gemmi\n\n    doc  = gemmi.cif.read(cif_path)[0]\n    strc = gemmi.make_small_structure_from_block(doc)\n    \n    ### finding it by number is much better\n    ### Sometimes the HM name cannot be found by gemmi.\n    table_number = -1\n    for item in doc:\n        if item.pair == None:\n            continue\n        key, value = item.pair\n        if \"_symmetry_Int_Tables_number\".lower() == key.lower():\n            table_number=int(value)\n            break\n    if table_number > -1:\n        strc.spacegroup_hm = gemmi.find_spacegroup_by_number(table_number).hm\n\n    atom_crds_ortho = list()\n    atom_num = list()\n    if use_symmetry_operations:\n        op_list  = doc.find_values('_symmetry_equiv_pos_as_xyz')\n        gops     = gemmi.GroupOps([gemmi.Op(o) for o in op_list])\n        for site in strc.sites:\n            for op in gops:\n                pos_frac = op.apply_to_xyz(site.fract.tolist())\n                pos = strc.cell.orthogonalize(\n                    gemmi.Fractional(\n                        *pos_frac\n                        )\n                    ).tolist()\n                atom_crds_ortho.append(pos)\n                atom_num.append(site.element.atomic_number)\n    else:\n        for site in strc.get_all_unit_cell_sites():\n            pos = strc.cell.orthogonalize(site.fract)\n            atom_crds_ortho.append([pos.x, pos.y, pos.z])\n            atom_num.append(site.element.atomic_number)\n\n    return strc, atom_crds_ortho, atom_num\n\n\ndef get_supercell_info_str(\n    mol_identifies, \n    unitcell_in_supercell_fracs\n    ):\n\n    \"\"\"\n    Takes list of in unitcell molecule identifiers and unitcell in supercell\n    frac coordinates. See output generated by method `generate_replicated_mol_list`.\n    Returns csv formatted info string.\n    \"\"\"\n\n    info_str  = \"#Mol_idx,\"\n    info_str += \"mol_in_unitcell,\"\n    info_str += \"unitcell_in_supercell_a,\"\n    info_str += \"unitcell_in_supercell_b,\"\n    info_str += \"unitcell_in_supercell_c\\n\"\n\n    N_mols = len(mol_identifies)\n    for mol_idx in range(N_mols):\n        info_str += f\"{mol_idx:d},\"\n        info_str += f\"{mol_identifies[mol_idx]:d},\"\n        info_str += f\"{unitcell_in_supercell_fracs[mol_idx][0]:d},\"\n        info_str += f\"{unitcell_in_supercell_fracs[mol_idx][1]:d},\"\n        info_str += f\"{unitcell_in_supercell_fracs[mol_idx][2]:d}\\n\"\n\n    return info_str\n\n\ndef get_replicated_mol_list_json(replicated_mol_list):\n\n    \"\"\"\n    Returns rdkit json string of collapsed replicated mol_list.\n    \"\"\"\n\n    from rdkit import Chem\n\n    mol_combo = Chem.Mol()\n    for mol in replicated_mol_list:\n        mol_combo = Chem.CombineMols(mol_combo, mol)\n    return Chem.MolToJSON(mol_combo)\n\n\ndef main():\n\n    \"\"\"\n    Run the workflow.\n    \"\"\"\n\n    import gemmi\n\n    args = parse_arguments()\n    strc, atom_crds_ortho, atom_num = parse_cif(args.input, args.use_symmetry_operations)\n\n    if len(args.a_min_max) == 2:\n        a_min_max = [int(args.a_min_max[0]), int(args.a_min_max[1])]\n    elif len(args.a_min_max) == 1:\n        uc_length_a = strc.cell.a * 0.1\n        a_min_max = [0, np.ceil(args.a_min_max[0] / uc_length_a)]\n    else:\n        raise ValueError(\n            \"Argument a_min_max must be either pair (x,y) or single value (z)\"\n            )\n\n    if len(args.b_min_max) == 2:\n        b_min_max = [int(args.b_min_max[0]), int(args.b_min_max[1])]\n    elif len(args.b_min_max) == 1:\n        uc_length_b = strc.cell.b * 0.1\n        b_min_max = [0, np.ceil(args.b_min_max[0] / uc_length_b)]\n    else:\n        raise ValueError(\n            \"Argument b_min_max must be either pair (x,y) or single value (z)\"\n            )\n\n    if len(args.c_min_max) == 2:\n        c_min_max = [int(args.c_min_max[0]), int(args.c_min_max[1])]\n    elif len(args.c_min_max) == 1:\n        uc_length_c = strc.cell.c * 0.1\n        c_min_max = [0, np.ceil(args.c_min_max[0] / uc_length_c)]\n    else:\n        raise ValueError(\n            \"Argument c_min_max must be either pair (x,y) or single value (z)\"\n            )\n\n    ### Build the supercell as a set of rdkit molecule objects\n    ### ======================================================\n    replicated_mol_list, mol_identifies, unitcell_in_supercell_fracs = generate_replicated_mol_list(\n        cell=strc.cell,\n        atom_crds_ortho=atom_crds_ortho,\n        atom_num=atom_num,\n        a_min_max=a_min_max,\n        b_min_max=b_min_max,\n        c_min_max=c_min_max,\n        addhs=args.addhs,\n        addwater=args.addwater,\n        N_iterations_protonation=args.n_protonation_attempts,\n        use_openeye=args.use_openeye\n        )\n\n    ### Write pdb file\n    ### ==============\n    strc_write               = gemmi.Structure()\n    strc_write.spacegroup_hm = \"P1\"\n    strc_write.cell          = strc.cell\n    pdb_str = get_pdb_str(\n        replicated_mol_list, \n        strc_write,\n        a_min_max,\n        b_min_max,\n        c_min_max\n        )\n    with open(f\"{args.prefix}.pdb\", \"w\") as fopen:\n        fopen.write(pdb_str)\n    with open(f\"{args.prefix}.csv\", \"w\") as fopen:\n        info_str = get_supercell_info_str(\n            mol_identifies, \n            unitcell_in_supercell_fracs\n            )\n        fopen.write(info_str)\n\n    with open(f\"{args.prefix}.json\", \"w\") as fopen:\n        json_str = get_replicated_mol_list_json(replicated_mol_list)\n        fopen.write(json_str)\n\n    ### Generate list of unique smiles for unique\n    ### molecules in UC\n    ### =========================================\n    mol_list = make_P1(strc.cell, atom_crds_ortho, atom_num, args.addhs, args.use_openeye)\n    if args.addwater > 0:\n        random_fill(\n            strc.cell,\n            mol_list,\n            N_per_unitcell=args.addwater,\n            radius=0.5,\n            smiles=\"O\"\n            )\n\n    unitcell_mol_list, _, _ = make_supercell(\n        strc.cell,\n        mol_list,\n        0,0,\n        0,0,\n        0,0,\n        )\n    from rdkit.Chem import Descriptors\n    unitcell_weight = 0.\n    smiles_list     = list()\n    for mol in unitcell_mol_list:\n        unitcell_weight += Descriptors.MolWt(mol)\n        smiles_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))\n\n    smiles_list = set(smiles_list)\n    smiles_list = list(smiles_list)\n\n    ### Output final summary\n    ### ====================\n    a_len = np.max(a_min_max) - np.min(a_min_max) + 1.\n    b_len = np.max(b_min_max) - np.min(b_min_max) + 1.\n    c_len = np.max(c_min_max) - np.min(c_min_max) + 1.\n\n    import gemmi\n    doc           = gemmi.cif.read(args.input)[0]\n    cif_info_dict = {\n        \"temperature\"  : \"Not found\",\n        \"cell_setting\" : \"Not found\",\n        \"space_group\"  : \"Not found\",\n        \"density\"      : \"Not found\"\n    }\n    for item in doc:\n        if item.pair == None:\n            continue\n        key, value = item.pair\n        if \"_diffrn_ambient_temperature\".lower() == key.lower():\n            cif_info_dict[\"temperature\"] = value\n        elif \"_symmetry_cell_setting\".lower() == key.lower():\n            cif_info_dict[\"cell_setting\"] = value\n        elif \"_symmetry_space_group_name_H-M\".lower() == key.lower():\n            cif_info_dict[\"space_group\"] = value\n        elif \"_exptl_crystal_density_diffrn\".lower() == key.lower():\n            cif_info_dict[\"density\"] = value\n\n    print(f\"\"\"\nSummary:\n========\nExpt:\n-----\nTemperature [K]               : {cif_info_dict['temperature']},\nCell Setting                  : {cif_info_dict['cell_setting']},\nSpace Group H-M               : {cif_info_dict['space_group']},\nDensity [g/cm3]               : {cif_info_dict['density']},\n\nSupercell:\n----------\nTotal number of molecules     : {len(replicated_mol_list)},\nTotal Length edge a [Ang]     : {strc.cell.a * a_len:4.2f},\nTotal Length edge b [Ang]     : {strc.cell.b * b_len:4.2f},\nTotal Length edge c [Ang]     : {strc.cell.c * c_len:4.2f},\nCell angle alpha [deg]        : {strc.cell.alpha:4.2f},\nCell angle beta  [deg]        : {strc.cell.beta:4.2f},\nCell angle gamma [deg]        : {strc.cell.gamma:4.2f},\nTotal Volume supercell [Ang3] : {strc.cell.volume * a_len * b_len * c_len:4.2f}\nDensity [g/cm3]               : {unitcell_weight / strc.cell.volume * 1.6605:4.2f}\nSMILES for molecules in UC    : {\" \".join(smiles_list)}\n\"\"\"\n### 1.6605 conversion g/mol/Ang^3 to g/cm^3\n)\n\n    try:\n        diff = (unitcell_weight / strc.cell.volume * 1.6605) - float(cif_info_dict[\"density\"])\n        if abs(diff) > 0.1:\n            warnings.warn(f\"Density difference {diff}. Check structure.\")\n    except:\n        pass\n\ndef entry_point():\n\n    main()\n\nif __name__ == \"__main__\":\n\n    entry_point()", "meta": {"hexsha": "5440233aa3fdf5afc7147d4860c4550ab7e7ddb1", "size": 47175, "ext": "py", "lang": "Python", "max_stars_repo_path": "xtalmdscripts/supercellbuilding/make_supercell.py", "max_stars_repo_name": "wutobias/xtalmd-scripts", "max_stars_repo_head_hexsha": "672cb9a37ae5c396bb25a61499f58066ec5083a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-11T23:21:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T23:21:45.000Z", "max_issues_repo_path": "xtalmdscripts/supercellbuilding/make_supercell.py", "max_issues_repo_name": "wutobias/xtalmd-scripts", "max_issues_repo_head_hexsha": "672cb9a37ae5c396bb25a61499f58066ec5083a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-23T20:09:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T18:14:04.000Z", "max_forks_repo_path": "xtalmdscripts/supercellbuilding/make_supercell.py", "max_forks_repo_name": "wutobias/xtalmd-scripts", "max_forks_repo_head_hexsha": "672cb9a37ae5c396bb25a61499f58066ec5083a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1574642127, "max_line_length": 119, "alphanum_fraction": 0.5554425013, "include": true, "reason": "import numpy,from scipy,import networkx", "num_tokens": 11661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.25386099567919973, "lm_q1q2_score": 0.1561468154314924}}
{"text": "\"\"\" Module storing the primary driver script used for the v1 release of cosmoDC2.\n\"\"\"\nimport os\nimport psutil\nimport numpy as np\nimport h5py\nimport re\nimport healpy as hp\nfrom time import time\nfrom astropy.table import Table, vstack\nfrom astropy.cosmology import FlatLambdaCDM\nfrom astropy.utils.misc import NumpyRNGContext\nfrom cosmodc2.load_gio_halos import load_gio_halo_snapshot\nfrom cosmodc2.sdss_colors import assign_restframe_sdss_gri\nfrom cosmodc2.sdss_colors.sigmoid_magr_model import magr_monte_carlo\n\nfrom cosmodc2.stellar_mass_remapping import remap_stellar_mass_in_snapshot\nfrom galsampler import halo_bin_indices, source_halo_index_selection\nfrom galsampler.cython_kernels import galaxy_selection_kernel\nfrom halotools.utils import crossmatch\n\nfrom cosmodc2.synthetic_subhalos import map_mstar_onto_lowmass_extension\nfrom cosmodc2.synthetic_subhalos import model_synthetic_cluster_satellites\n#from cosmodc2.synthetic_subhalos import synthetic_logmpeak\n\nfof_halo_mass = 'fof_halo_mass'\nmass = 'mass'\nfof_max = 14.5\nH0 = 71.0\nOmegaM = 0.2648\nOmegaB = 0.0448\n\n#unique galaxy_id\ngalaxy_id_factor = int(1e4)  #  factor to guarantee unique galaxy_id across blocks in snapshot\n\ndesired_logm_completeness=9.8\n\ndef write_umachine_snapshot_mock_to_disk(\n        umachine_mock_fname, umachine_halo_fname,\n        target_halo_catalog_fname, snapshot, blocks, output_snapshot_mock_fname_list,\n        redshift, commit_hash, Lbox=3000.):\n    \"\"\"\n    Main driver function used to paint SDSS fluxes onto UniverseMachine,\n    GalSample the mock into the halo snapshot and write the snapshot mock to disk.\n\n    Parameters\n    ----------\n    umachine_mock_fname : str \n        the absolute path to the value-added UniverseMachine snapshot mock\n\n    umachine_halo_fname : str\n        the absolute path to the\n        value-added host halo catalog hosting the UniverseMachine snapshot mock\n\n    target_halo_catalog_fname : str\n        the absolute path to the gio file(s) of\n        source halos into which UniverseMachine will be GalSampled\n\n    snapshot : str\n        snapshot being processed\n\n    blocks : list  \n        list of blocks (str format) of halo-catalog file being processed\n\n    output_snapshot_mock_fname_list : list\n        list of absolute paths to the output snapshot mock filenames (1 per block)\n\n    redshift : str\n        value of the redshift for the target halo catalog\n\n    commit_hash : string\n        Commit hash of the version of the cosmodc2 repo used when\n        calling this function.\n\n        After updating the cosmodc2 repo to the desired version,\n        the commit_hash can be determined by navigating to the root\n        directory and typing ``git log --pretty=format:'%h' -n 1``\n\n    \"\"\"\n\n    start_time = time()\n    process = psutil.Process(os.getpid())\n    \n    #  determine factor for number of synthetic galaxies for this snapshot\n    #  synthetic_number_factor = (OR_size/MDPL2_size)**3\n\n    #  initialize book-keeping variables\n    fof_halo_mass_max = 0.\n    Ngals_total = 0\n\n    print('\\nStarting snapshot processing')\n    print('Redshift for halo catalog = {}'.format(redshift))\n\n    #  Get galaxy properties from UM catalogs \n    print(\"\\n...loading z = {0:.2f} galaxy catalog into memory\".format(redshift))\n    um_mock = Table.read(umachine_mock_fname, path='data')\n    print('.....{} galaxies read in'.format(len(um_mock)))\n\n    ### Get source halos \n    print(\"\\n...loading z = {0:.2f} source-halo catalogs into memory\".format(redshift))\n    source_halos = Table.read(umachine_halo_fname, path='data')\n\n    #  Bin the halos in source simulation by mass\n    dlogM = 0.15\n    mass_bins = 10.**np.arange(10.5, 14.5+dlogM, dlogM)\n    source_halos['mass_bin'] = halo_bin_indices(\n        mass=(source_halos['mvir'], mass_bins))\n\n    for block, output_snap_fname  in zip(blocks, output_snapshot_mock_fname_list):\n        new_time_stamp = time()\n        #  determine seed from output filename (includes snapshot and block)\n        seed = get_random_seed(os.path.basename(output_snap_fname))\n        print('\\n.Processing block {}'.format(block))\n        print('.Using galaxy_id factor {} + galaxy_id offset {}'.format(galaxy_id_factor, block))\n        print('.Using seed = {} (for block {})'.format(seed, block))\n\n        # copy um_mock to new table for this block\n        mock = um_mock.copy()\n        \n        print(\"\\n...loading step {} fof target-halo catalogs into memory\".format(snapshot))\n        target_halos = load_gio_halo_snapshot(target_halo_catalog_fname, block=block)\n        target_halos.rename_column('fof_halo_tag', 'fof_halo_id')\n        target_halos.rename_column('fof_halo_center_x', 'x')\n        target_halos.rename_column('fof_halo_center_y', 'y')\n        target_halos.rename_column('fof_halo_center_z', 'z')\n        target_halos.rename_column('fof_halo_mean_vx', 'vx')\n        target_halos.rename_column('fof_halo_mean_vy', 'vy')\n        target_halos.rename_column('fof_halo_mean_vz', 'vz')\n        max_fof_halo_mass = np.max(target_halos[fof_halo_mass].quantity.value)\n        fof_halo_mass_max = max(max_fof_halo_mass, fof_halo_mass_max)\n        print('.....Maximum fof halo mass = {:.3e}'.format(max_fof_halo_mass))\n\n        print(\"\\n...Finding halo--halo correspondence with GalSampler\")\n        #  Bin the halos in target simulation by mass\n        target_halos['mass_bin'] = halo_bin_indices(\n            mass=(target_halos[fof_halo_mass], mass_bins))\n\n        #  Randomly draw halos from corresponding mass bins\n        nhalo_min = 10\n        source_halo_bin_numbers = source_halos['mass_bin']\n        target_halo_bin_numbers = target_halos['mass_bin']\n        target_halo_ids = target_halos['fof_halo_id']\n        _result = source_halo_index_selection(source_halo_bin_numbers,\n                      target_halo_bin_numbers, target_halo_ids, nhalo_min, mass_bins, seed=seed)\n        source_halo_indx, matching_target_halo_ids = _result\n\n        #  Transfer quantities from the source halos to the corresponding target halo\n        target_halos['source_halo_id'] = source_halos['halo_id'][source_halo_indx]\n        target_halos['matching_mvir'] = source_halos['mvir'][source_halo_indx]\n        target_halos['richness'] = source_halos['richness'][source_halo_indx]\n        target_halos['first_galaxy_index'] = source_halos['first_galaxy_index'][source_halo_indx]\n\n        ################################################################################\n        #  Use GalSampler to calculate the indices of the galaxies that will be selected\n        ################################################################################\n        print(\"\\n...GalSampling z={0:.2f} galaxies to OuterRim halos\".format(redshift))\n\n        source_galaxy_indx = np.array(galaxy_selection_kernel(\n            target_halos['first_galaxy_index'].astype('i8'),\n            target_halos['richness'].astype('i4'), target_halos['richness'].sum()))\n\n        ########################################################################\n        #  Correct stellar mass for low-mass subhalos and create synthetic mpeak\n        ########################################################################\n        #print(\"...correcting low mass mpeak and assigning synthetic mpeak values\")\n        #  First generate the appropriate number of synthetic galaxies for the snapshot\n        #mpeak_synthetic_snapshot = 10**synthetic_logmpeak(\n        #    mock['mpeak'], seed=seed, desired_logm_completeness=synthetic_halo_minimum_mass)\n        #print('...assembling {} synthetic galaxies'.format(len(mpeak_synthetic_snapshot)))\n\n        ########################################################################\n        #  Assign stellar mass\n        ########################################################################\n        print(\"...re-assigning high-mass mstar values\")\n\n        #  Map stellar mass onto mock using target halo mass instead of UM Mpeak for cluster BCGs\n        new_mstar = remap_stellar_mass_in_snapshot(redshift, mock['mpeak'], mock['obs_sm'])\n        mock.rename_column('obs_sm', '_obs_sm_orig_um_snap')\n        mock['obs_sm'] = new_mstar\n\n        #  Add call to map_mstar_onto_lowmass_extension function after pre-determining low-mass slope\n        print(\"...re-assigning low-mass mstar values\")\n        min_obs_sm = np.min(mock['obs_sm'])\n        mpeak_synthetic_snapshot = np.asarray([])\n        new_mstar_real, mstar_synthetic_snapshot = map_mstar_onto_lowmass_extension(\n            mock['mpeak'], mock['obs_sm'], mpeak_synthetic_snapshot,\n            desired_logm_completeness=desired_logm_completeness)\n        mock['obs_sm'] = new_mstar_real\n        new_min_obs_sm = np.min(mock['obs_sm'])\n        print('.....New min(obs_sm) = {:.3e}; old min(obs_sm) = {:.3e}'.format(new_min_obs_sm, min_obs_sm))\n        print('.....Number of shifted values = {}'.format(np.count_nonzero(mock['obs_sm'] < min_obs_sm)))\n\n        ###################################################\n        #  Map restframe Mr, g-r, r-i onto mock\n        ###################################################\n        #  use the redshift of the snapshot of the target simulation\n        print(\"...assigning rest-frame Mr and colors\")\n        check_time = time()\n        redshift_mock = np.zeros(len(mock)) + redshift\n        msg = (\".....using snapshot redshift to assign restframe colors\")\n        print(msg)\n\n        magr, gr_mock, ri_mock, is_red_gr, is_red_ri = assign_restframe_sdss_gri(\n            mock['upid'], mock['obs_sm'], mock['sfr_percentile'],\n            mock['host_halo_mvir'], redshift_mock, seed=seed, use_substeps=False)\n        #  check for bad values\n        for m_id, m in zip(['magr', 'gr', 'ri'], [magr, gr_mock, ri_mock]):\n            num_infinite = np.sum(~np.isfinite(m))\n            if num_infinite > 0:\n                print('.....Warning: {} infinite values in mock {}'.format(num_infinite, m_id))\n\n        mock['restframe_extincted_sdss_abs_magr'] = magr\n        mock['restframe_extincted_sdss_gr'] = gr_mock\n        mock['restframe_extincted_sdss_ri'] = ri_mock\n        mock['is_on_red_sequence_gr'] = is_red_gr\n        mock['is_on_red_sequence_ri'] = is_red_ri\n        print('.....time to assign_restframe_sdss_gri = {:.2f} secs'.format(time()-check_time))\n\n        ########################################################################\n        #  Assemble the output mock by snapshot\n        ########################################################################\n\n        print(\"\\n...building output snapshot mock for snapshot {}\".format(snapshot))\n        output_mock = build_output_snapshot_mock(redshift, mock, target_halos,\n                                                          source_galaxy_indx, galaxy_id_factor,\n                                                          int(block), Lbox=Lbox)\n        Ngals_total += len(output_mock['galaxy_id'])\n        print('...saved {} galaxies to dict'.format(len(output_mock['galaxy_id'])))\n\n        ########################################################################\n        #  Write the output mock to disk\n        ########################################################################\n        if len(output_mock) > 0:\n            check_time = time()\n            write_output_mock_to_disk(output_snap_fname, output_mock, commit_hash, seed,\n                                      redshift, snapshot, block, Lbox)\n            print('...time to write mock to disk = {:.2f} minutes'.format((time()-check_time)/60.))\n\n        time_stamp = time()\n        msg = \"\\n.Block runtime = {0:.2f} minutes\"\n        print(msg.format((time_stamp-new_time_stamp)/60.))\n        mem = \".Memory usage =  {0:.2f} GB\"\n        print(mem.format(process.memory_info().rss/1.e9))\n\n                                      \n    file_info = 'snapshot {}, blocks {}'.format(snapshot, ', '.join(blocks))\n    print('\\n.Maximum halo mass in {} = {}\\n'.format(file_info, fof_halo_mass_max))\n    print('.Number of galaxies in {} = {}\\n'.format(file_info, Ngals_total))\n\n    time_stamp = time()\n    msg = \"\\nEnd-to-end runtime = {0:.2f} minutes\\n\"\n    print(msg.format((time_stamp-start_time)/60.))\n\n\ndef get_random_seed(filename, seed_max=4294967095):  #reduce max seed by 200 to allow for 60 z shells\n    import hashlib\n    s = hashlib.md5(filename).hexdigest()\n    seed = int(s, 16)\n\n    #  enforce seed is below seed_max and odd\n    seed = seed%seed_max\n    if seed%2 == 0:\n        seed = seed + 1\n    return seed\n\n\ndef build_output_snapshot_mock(\n            snapshot_redshift, umachine, target_halos, galaxy_indices, galaxy_id_factor,\n            galaxy_id_offset, Lbox=0.):\n    \"\"\"\n    Collect the GalSampled snapshot mock into an astropy table\n\n    Parameters\n    ----------\n    snapshot_redshift : float\n        Float of the snapshot redshift\n\n    umachine : astropy.table.Table\n        Astropy Table of shape (num_source_gals, )\n        storing the UniverseMachine snapshot mock\n\n    target_halos : astropy.table.Table\n        Astropy Table of shape (num_target_halos, )\n        storing the target halo catalog\n\n    galaxy_indices: ndarray\n        Numpy indexing array of shape (num_target_gals, )\n        storing integers valued between [0, num_source_gals)\n\n    galaxy_id_factor: integer\n        Multiplicative factor to ensure unique galaxy id's in a snapshot\n\n    galaxy_id_offset: integer\n        Offset to ensure unique galaxy id's in a snapshot\n\n    Returns\n    -------\n    dc2 : astropy.table.Table\n        Astropy Table of shape (num_target_gals, )\n        storing the GalSampled galaxy catalog\n    \"\"\"\n    dc2 = Table()\n    dc2['source_halo_id'] = umachine['hostid'][galaxy_indices]\n    dc2['target_halo_id'] = np.repeat(\n        target_halos['fof_halo_id'], target_halos['richness'])\n    #needed for synthetic cluster satellite assignment\n    dc2['target_halo_redshift'] = np.repeat(snapshot_redshift, len(dc2['target_halo_id']))\n    dc2['target_halo_fof_halo_id'] = dc2['target_halo_id']\n\n    #  copy target halo information\n    dc2['source_halo_mvir'] = np.repeat(\n        target_halos['matching_mvir'], target_halos['richness'])\n\n    idxA, idxB = crossmatch(dc2['target_halo_id'], target_halos['fof_halo_id'])\n\n    msg = \"target IDs do not match!\"\n    assert np.all(dc2['source_halo_id'][idxA] == target_halos['source_halo_id'][idxB]), msg\n\n    dc2['target_halo_x'] = 0.\n    dc2['target_halo_y'] = 0.\n    dc2['target_halo_z'] = 0.\n    dc2['target_halo_vx'] = 0.\n    dc2['target_halo_vy'] = 0.\n    dc2['target_halo_vz'] = 0.\n\n    dc2['target_halo_x'][idxA] = target_halos['x'][idxB]\n    dc2['target_halo_y'][idxA] = target_halos['y'][idxB]\n    dc2['target_halo_z'][idxA] = target_halos['z'][idxB]\n\n    dc2['target_halo_vx'][idxA] = target_halos['vx'][idxB]\n    dc2['target_halo_vy'][idxA] = target_halos['vy'][idxB]\n    dc2['target_halo_vz'][idxA] = target_halos['vz'][idxB]\n\n    dc2['target_halo_mass'] = 0.\n    dc2['target_halo_mass'][idxA] = target_halos['fof_halo_mass'][idxB]\n\n    source_galaxy_keys = ('host_halo_mvir', 'upid', 'mpeak',\n            'host_centric_x', 'host_centric_y', 'host_centric_z',\n            'host_centric_vx', 'host_centric_vy', 'host_centric_vz',\n            'obs_sm', 'obs_sfr', 'sfr_percentile',\n            'restframe_extincted_sdss_abs_magr',\n            'restframe_extincted_sdss_gr', 'restframe_extincted_sdss_ri',\n            'is_on_red_sequence_gr', 'is_on_red_sequence_ri',\n            '_obs_sm_orig_um_snap', 'halo_id')\n    for key in source_galaxy_keys:\n        try:\n            dc2[key] = umachine[key][galaxy_indices]\n        except KeyError:\n            msg = (\"The build_output_snapshot_mock function was passed a umachine mock\\n\"\n                \"that does not contain the ``{0}`` key\")\n            raise KeyError(msg.format(key))\n\n    max_umachine_halo_mass = np.max(umachine['mpeak'])\n    ultra_high_mvir_halo_mask = (dc2['upid'] == -1) & (dc2['target_halo_mass'] > max_umachine_halo_mass)\n    num_to_remap = np.count_nonzero(ultra_high_mvir_halo_mask)\n    if num_to_remap > 0:\n        print(\"...remapping stellar mass of {0} BCGs in ultra-massive halos\".format(num_to_remap))\n\n        halo_mass_array = dc2['target_halo_mass'][ultra_high_mvir_halo_mask]\n        mpeak_array = dc2['mpeak'][ultra_high_mvir_halo_mask]\n        mhalo_ratio = halo_mass_array/mpeak_array\n        mstar_array = dc2['obs_sm'][ultra_high_mvir_halo_mask]\n        redshift_array = dc2['target_halo_redshift'][ultra_high_mvir_halo_mask]\n        upid_array = dc2['upid'][ultra_high_mvir_halo_mask]\n\n        assert np.shape(halo_mass_array) == (num_to_remap, ), \"halo_mass_array has shape = {0}\".format(np.shape(halo_mass_array))\n        assert np.shape(mstar_array) == (num_to_remap, ), \"mstar_array has shape = {0}\".format(np.shape(mstar_array))\n        assert np.shape(redshift_array) == (num_to_remap, ), \"redshift_array has shape = {0}\".format(np.shape(redshift_array))\n        assert np.shape(upid_array) == (num_to_remap, ), \"upid_array has shape = {0}\".format(np.shape(upid_array))\n        assert np.all(mhalo_ratio >= 1), \"Bookkeeping error: all values of mhalo_ratio ={0} should be >= 1\".format(mhalo_ratio)\n\n        dc2['obs_sm'][ultra_high_mvir_halo_mask] = mstar_array*(mhalo_ratio**0.5)\n        dc2['restframe_extincted_sdss_abs_magr'][ultra_high_mvir_halo_mask] = magr_monte_carlo(\n            dc2['obs_sm'][ultra_high_mvir_halo_mask], upid_array, redshift_array)\n        idx = np.argmax(dc2['obs_sm'])\n        halo_id_most_massive = dc2['halo_id'][idx]\n        assert dc2['obs_sm'][idx] < 10**13.5, \"halo_id = {0} has stellar mass {1:.3e}\".format(\n            halo_id_most_massive, dc2['obs_sm'][idx])\n\n    dc2['x'] = dc2['target_halo_x'] + dc2['host_centric_x']\n    dc2['vx'] = dc2['target_halo_vx'] + dc2['host_centric_vx']\n\n    dc2['y'] = dc2['target_halo_y'] + dc2['host_centric_y']\n    dc2['vy'] = dc2['target_halo_vy'] + dc2['host_centric_vy']\n\n    dc2['z'] = dc2['target_halo_z'] + dc2['host_centric_z']\n    dc2['vz'] = dc2['target_halo_vz'] + dc2['host_centric_vz']\n\n    print('...number of galaxies before adding synthetic satellites = {}'.format(len(dc2['halo_id'])))\n    print(\"...generating and stacking any synthetic cluster satellites\")\n    fake_cluster_sats = model_synthetic_cluster_satellites(dc2, Lbox=Lbox, snapshot=True)\n    if len(fake_cluster_sats) > 0:\n        check_time = time()\n        dc2 = vstack((dc2, fake_cluster_sats))\n        print('...time to create {} galaxies in fake_cluster_sats = {:.2f} secs'.format(len(fake_cluster_sats['target_halo_id']), time()-check_time))\n\n    # delete duplicate/unnecessary column after fake cluster satellites are added\n    dc2.remove_column('target_halo_fof_halo_id')\n    dc2.remove_column('target_halo_redshift')\n\n    dc2['galaxy_id'] = np.arange(len(dc2['target_halo_id'])).astype(int)*galaxy_id_factor + galaxy_id_offset\n    print('...Min and max galaxy_id = {} -> {}'.format(np.min(dc2['galaxy_id']), np.max(dc2['galaxy_id'])))\n\n    #  Use gr and ri color to compute gi flux\n    dc2['restframe_extincted_sdss_abs_magg'] = (\n        dc2['restframe_extincted_sdss_gr'] +\n        dc2['restframe_extincted_sdss_abs_magr'])\n    dc2['restframe_extincted_sdss_abs_magi'] = (\n        -dc2['restframe_extincted_sdss_ri'] +\n        dc2['restframe_extincted_sdss_abs_magr'])\n\n    #convert table to dict\n    check_time = time()\n    output_dc2 = {}\n    for k in dc2.keys():\n        output_dc2[k] = dc2[k].quantity.value\n\n    print('...time to new dict = {:.4f} secs'.format(time()-check_time))\n\n    return output_dc2\n\n\ndef write_output_mock_to_disk(output_snapshot_mock_fname, output_mock, commit_hash, seed,\n                              redshift, snapshot, block, Lbox,\n                              versionMajor=0, versionMinor=1, versionMinorMinor=0):\n    \"\"\"\n    \"\"\"\n\n    print(\"\\n...writing to file {} using commit hash {}\".format(output_snapshot_mock_fname, commit_hash))\n    hdfFile = h5py.File(output_snapshot_mock_fname, 'w')\n    hdfFile.create_group('metaData')\n    gkey = 'galaxyProperties'\n\n    hdfFile['metaData']['commit_hash'] = commit_hash\n    hdfFile['metaData']['seed'] = seed\n    hdfFile['metaData']['versionMajor'] = versionMajor\n    hdfFile['metaData']['versionMinor'] = versionMinor\n    hdfFile['metaData']['versionMinorMinor'] = versionMinorMinor\n    hdfFile['metaData']['H_0'] = H0\n    hdfFile['metaData']['Omega_matter'] = OmegaM\n    hdfFile['metaData']['Omega_b'] = OmegaB\n    hdfFile['metaData']['box_size'] = Lbox\n    hdfFile['metaData']['redshift'] = redshift\n    hdfFile['metaData']['timestep'] = snapshot\n    hdfFile['metaData']['block_number'] = block\n    for d in ['x', 'y', 'z']:\n        hdfFile['metaData'][d + '_max'] = np.max(output_mock[d]) \n        hdfFile['metaData'][d + '_min'] = np.min(output_mock[d]) \n\n    gGroup = hdfFile.create_group(gkey)\n    check_time = time()\n    for k, v in output_mock.items():\n        gGroup[k] = v\n\n    print('.....time to write group {} = {:.4f} secs'.format(gkey, time()-check_time))\n\n    check_time = time()\n    hdfFile.close()\n    print('.....time to close file {:.4f} secs'.format(time()-check_time))\n", "meta": {"hexsha": "3aca38732886391275415b857bb661753df06a4c", "size": 20976, "ext": "py", "lang": "Python", "max_stars_repo_path": "cosmodc2/write_umachine_snapshot_mock_to_disk.py", "max_stars_repo_name": "ArgonneCPAC/skysim", "max_stars_repo_head_hexsha": "f271debe3439efd1ae5230c6020b2dbc5f79d824", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-08-08T10:01:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T07:21:00.000Z", "max_issues_repo_path": "cosmodc2/write_umachine_snapshot_mock_to_disk.py", "max_issues_repo_name": "ArgonneCPAC/skysim", "max_issues_repo_head_hexsha": "f271debe3439efd1ae5230c6020b2dbc5f79d824", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 67, "max_issues_repo_issues_event_min_datetime": "2018-07-16T22:12:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-02T01:12:48.000Z", "max_forks_repo_path": "cosmodc2/write_umachine_snapshot_mock_to_disk.py", "max_forks_repo_name": "aphearin/cosmodc2", "max_forks_repo_head_hexsha": "5bc2abebd7123f29b424efc11c3ef374a51cd6c1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.6, "max_line_length": 149, "alphanum_fraction": 0.6451182304, "include": true, "reason": "import numpy,from astropy", "num_tokens": 5395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.256832002764217, "lm_q1q2_score": 0.15606734891423413}}
{"text": "\"\"\"\nClasses for generating lists of photons\n\"\"\"\nimport numpy as np\nfrom yt.funcs import get_pbar\nfrom pyxsim.lib.sky_functions import pixel_to_cel, \\\n    scatter_events, doppler_shift\nfrom yt.utilities.physical_constants import clight\nfrom yt.utilities.cosmology import Cosmology\nfrom yt.utilities.orientation import Orientation\nfrom yt.utilities.parallel_tools.parallel_analysis_interface import \\\n    communication_system\nfrom yt.units.yt_array import YTArray\nimport h5py\nfrom pyxsim.spectral_models import absorb_models\nfrom pyxsim.utils import parse_value, mylog\nfrom soxs.utils import parse_prng\n\ncomm = communication_system.communicators[-1]\n\ninit_chunk = 100000\n\n\ndef determine_fields(ds, source_type, point_sources):\n    from yt.geometry.particle_geometry_handler import ParticleIndex\n    # Figure out if this is a particle field or otherwise\n    ptype = (source_type in ds.particle_types) | \\\n            (source_type in ds.known_filters) | \\\n            ((source_type == \"gas\") & isinstance(ds.index, ParticleIndex))\n    if ptype:\n        ppos = [f\"particle_position_{ax}\" for ax in \"xyz\"]\n        pvel = [f\"particle_velocity_{ax}\" for ax in \"xyz\"]\n        if source_type in ds.known_filters:\n            if ds.known_filters[source_type].filtered_type == \"gas\":\n                ppos = [\"x\", \"y\", \"z\"]\n                pvel = [f\"velocity_{ax}\" for ax in \"xyz\"]\n        elif source_type == \"gas\":\n            source_type = ds._sph_ptypes[0]\n        position_fields = [(source_type, ppos[i]) for i in range(3)]\n        velocity_fields = [(source_type, pvel[i]) for i in range(3)]\n        if source_type in ds._sph_ptypes:\n            width_field = (source_type, \"smoothing_length\")\n        else:\n            width_field = None\n    else:\n        position_fields = [(\"index\", ax) for ax in \"xyz\"]\n        velocity_fields = [(source_type, f\"velocity_{ax}\") for ax in \"xyz\"]\n        width_field = (\"index\", \"dx\")\n    if point_sources:\n        width_field = None\n    return position_fields, velocity_fields, width_field\n\n\ndef find_object_bounds(data_source):\n    \"\"\"\n    This logic is required to determine the bounds of the object, which is \n    solely for fixing coordinates at periodic boundaries\n    \"\"\"\n    if hasattr(data_source, \"base_object\"):\n        # This is a cut region so we'll figure out\n        # its bounds from its parent object\n        data_src = data_source.base_object\n    else:\n        data_src = data_source\n\n    if hasattr(data_src, \"left_edge\"):\n        # Region or grid\n        c = 0.5 * (data_src.left_edge + data_src.right_edge)\n        w = data_src.right_edge - data_src.left_edge\n        le = -0.5 * w + c\n        re = 0.5 * w + c\n    elif hasattr(data_src, \"radius\") and not hasattr(data_src, \"height\"):\n        # Sphere\n        le = -data_src.radius + data_src.center\n        re = data_src.radius + data_src.center\n    else:\n        # Not sure what to do with any other object yet, so just\n        # return the domain edges and punt.\n        mylog.warning(\"You are using a region that is not currently \"\n                      \"supported for straddling periodic boundaries. \"\n                      \"Check to make sure that your region does not \"\n                      \"do so.\")\n        le = data_source.ds.domain_left_edge\n        re = data_source.ds.domain_right_edge\n\n    return le.to_value(\"kpc\"), re.to_value(\"kpc\")\n\n\ndef make_photons(photon_prefix, data_source, redshift, area,\n                 exp_time, source_model, point_sources=False,\n                 parameters=None, center=None, dist=None,\n                 cosmology=None, velocity_fields=None):\n    r\"\"\"\n    Write a photon list dataset to disk from a yt data source and assuming a\n    source model for the photons. The redshift, collecting area, exposure time,\n    and cosmology are stored in the *parameters* dictionary which is passed to\n    the *source_model* function.\n\n    Parameters\n    ----------\n    photon_prefix : string\n        The prefix of the filename(s) to contain the photon list. If run in\n        serial, the filename will be \"{photon_prefix}.h5\", if run in\n        parallel, the filenames will be \"{photon_prefix}.{mpi_rank}.h5\".\n    data_source : :class:`~yt.data_objects.data_containers.YTSelectionContainer`\n        The data source from which the photons will be generated.\n    redshift : float\n        The cosmological redshift for the photons.\n    area : float, (value, unit) tuple, :class:`~yt.units.yt_array.YTQuantity`, or :class:`~astropy.units.Quantity`\n        The collecting area to determine the number of photons. If units are\n        not specified, it is assumed to be in cm^2.\n    exp_time : float, (value, unit) tuple, :class:`~yt.units.yt_array.YTQuantity`, or :class:`~astropy.units.Quantity`\n        The exposure time to determine the number of photons. If units are\n        not specified, it is assumed to be in seconds.\n    source_model : :class:`~pyxsim.source_models.SourceModel`\n        A source model used to generate the photons.\n    point_sources : boolean, optional\n        If True, the photons will be assumed to be generated from the exact\n        positions of the cells or particles and not smeared around within\n        a volume. Default: False\n    parameters : dict, optional\n        A dictionary of parameters to be passed for the source model to use,\n        if necessary.\n    center : string or array_like, optional\n        The origin of the photon spatial coordinates. Accepts \"c\", \"max\", or\n        a coordinate. If array-like and without units, it is assumed to be in \n        units of kpc. If not specified, pyxsim attempts to use the \"center\"\n        field parameter of the data_source.\n    dist : float, (value, unit) tuple, :class:`~yt.units.yt_array.YTQuantity`, or :class:`~astropy.units.Quantity`, optional\n        The angular diameter distance, used for nearby sources. This may be\n        optionally supplied instead of it being determined from the\n        *redshift* and given *cosmology*. If units are not specified, it is\n        assumed to be in kpc. To use this, the redshift must be set to zero.\n    cosmology : :class:`~yt.utilities.cosmology.Cosmology`, optional\n        Cosmological information. If not supplied, we try to get the\n        cosmology from the dataset. Otherwise, LCDM with the default yt \n        parameters is assumed.\n    velocity_fields : list of fields\n        The yt fields to use for the velocity. If not specified, the \n        following will be assumed:\n        ['velocity_x', 'velocity_y', 'velocity_z'] for grid datasets\n        ['particle_velocity_x', 'particle_velocity_y', 'particle_velocity_z'] for particle datasets\n\n    Returns\n    -------\n    A tuple of two integers, the number of photons and the number of cells with\n    photons\n\n    Examples\n    --------\n    >>> thermal_model = pyxsim.ThermalSourceModel(\"apec\",  0.1, 10.0,\n    ...                                           1000, Zmet=0.3)\n    >>> redshift = 0.05\n    >>> area = 6000.0 # assumed here in cm**2\n    >>> time = 2.0e5 # assumed here in seconds\n    >>> sp = ds.sphere(\"c\", (500., \"kpc\"))\n    >>> n_photons, n_cells = pyxsim.make_photons(sp, redshift, area,\n    ...                                          time, thermal_model)\n    \"\"\"\n    ds = data_source.ds\n\n    if photon_prefix.endswith(\".h5\"):\n        photon_prefix = photon_prefix[:-3]\n\n    if comm.size > 1:\n        photon_file = f\"{photon_prefix}.{comm.rank:04d}.h5\"\n    else:\n        photon_file = f\"{photon_prefix}.h5\"\n\n    if parameters is None:\n        parameters = {}\n    if cosmology is None:\n        if hasattr(ds, 'cosmology'):\n            cosmo = ds.cosmology\n        else:\n            cosmo = Cosmology()\n    else:\n        cosmo = cosmology\n    if dist is None:\n        if redshift <= 0.0:\n            msg = \"If redshift <= 0.0, you must specify a distance to the \" \\\n                  \"source using the 'dist' argument!\"\n            mylog.error(msg)\n            raise ValueError(msg)\n        D_A = cosmo.angular_diameter_distance(0.0, redshift).to(\"Mpc\")\n    else:\n        D_A = parse_value(dist, \"kpc\")\n        if redshift > 0.0:\n            mylog.warning(\"Redshift must be zero for nearby sources. \"\n                          \"Resetting redshift to 0.0.\")\n            redshift = 0.0\n\n    if isinstance(center, str):\n        if center == \"center\" or center == \"c\":\n            parameters[\"center\"] = ds.domain_center\n        elif center == \"max\" or center == \"m\":\n            parameters[\"center\"] = ds.find_max(\"density\")[-1]\n    elif isinstance(center, YTArray):\n        parameters[\"center\"] = center.in_units(\"code_length\")\n    elif isinstance(center, tuple):\n        if center[0] == \"min\":\n            parameters[\"center\"] = ds.find_min(center[1])[-1]\n        elif center[0] == \"max\":\n            parameters[\"center\"] = ds.find_max(center[1])[-1]\n        else:\n            raise RuntimeError\n    elif isinstance(center, (list, np.ndarray)):\n        parameters[\"center\"] = ds.arr(center, \"code_length\")\n    elif center is None:\n        if hasattr(data_source, \"left_edge\"):\n            parameters[\"center\"] = 0.5*(data_source.left_edge + \n                                        data_source.right_edge)\n        else:\n            parameters[\"center\"] = data_source.get_field_parameter(\"center\")\n\n    parameters[\"fid_exp_time\"] = parse_value(exp_time, \"s\")\n    parameters[\"fid_area\"] = parse_value(area, \"cm**2\")\n    parameters[\"fid_redshift\"] = redshift\n    parameters[\"fid_d_a\"] = D_A\n    parameters[\"hubble\"] = cosmo.hubble_constant\n    parameters[\"omega_matter\"] = cosmo.omega_matter\n    parameters[\"omega_lambda\"] = cosmo.omega_lambda\n    parameters[\"center\"].convert_to_units(\"kpc\")\n\n    if redshift > 0.0:\n        mylog.info(f\"Cosmology: h = {cosmo.hubble_constant}, \"\n                   f\"omega_matter = {cosmo.omega_matter}, \"\n                   f\"omega_lambda = {cosmo.omega_lambda}\")\n    else:\n        mylog.info(f\"Observing local source at distance {D_A}.\")\n\n    local_exp_time = parameters[\"fid_exp_time\"].v/comm.size\n    D_A = parameters[\"fid_d_a\"].to_value(\"cm\")\n    dist_fac = 1.0/(4.*np.pi*D_A*D_A*(1.+redshift)**2)\n    spectral_norm = parameters[\"fid_area\"].v*local_exp_time*dist_fac\n\n    source_model.setup_model(data_source, redshift, spectral_norm)\n\n    p_fields, v_fields, w_field = determine_fields(ds,\n                                                   source_model.ftype,\n                                                   point_sources)\n\n    if velocity_fields is not None:\n        v_fields = velocity_fields\n\n    if p_fields[0] == (\"index\", \"x\"):\n        parameters[\"data_type\"] = \"cells\"\n    else:\n        parameters[\"data_type\"] = \"particles\"\n\n    dw = ds.domain_width.to_value(\"kpc\")\n    le, re = find_object_bounds(data_source)\n    c = parameters[\"center\"].to_value(\"kpc\")\n\n    f = h5py.File(photon_file, \"w\")\n\n    # Parameters\n\n    p = f.create_group(\"parameters\")\n    p.create_dataset(\"fid_area\", data=float(parameters[\"fid_area\"]))\n    p.create_dataset(\"fid_exp_time\", data=float(parameters[\"fid_exp_time\"]))\n    p.create_dataset(\"fid_redshift\", data=parameters[\"fid_redshift\"])\n    p.create_dataset(\"hubble\", data=parameters[\"hubble\"])\n    p.create_dataset(\"omega_matter\", data=parameters[\"omega_matter\"])\n    p.create_dataset(\"omega_lambda\", data=parameters[\"omega_lambda\"])\n    p.create_dataset(\"fid_d_a\", data=float(parameters[\"fid_d_a\"]))\n    p.create_dataset(\"data_type\", data=parameters[\"data_type\"])\n\n    n_cells = 0\n    n_photons = 0\n    c_offset = 0\n    p_offset = 0\n    c_size = init_chunk\n    p_size = init_chunk\n\n    cell_fields = [\"x\", \"y\", \"z\", \"vx\", \"vy\", \"vz\", \"num_photons\", \"dx\"]\n\n    d = f.create_group(\"data\")\n    for field in cell_fields + [\"energy\"]:\n        if field == \"num_photons\":\n            dtype = \"int64\"\n        else:\n            dtype = \"float64\"\n        d.create_dataset(field, data=np.zeros(init_chunk, dtype=dtype),\n                         maxshape=(None,), dtype=dtype, chunks=True)\n\n    f.flush()\n\n    for chunk in data_source.chunks([], \"io\"):\n\n        chunk_data = source_model(chunk)\n\n        if chunk_data is not None:\n\n            chunk_nc, number_of_photons, idxs, energies = chunk_data\n\n            chunk_nph = np.sum(number_of_photons)\n\n            if chunk_nph == 0:\n                continue\n\n            if c_size < n_cells + chunk_nc:\n                while chunk_nc + n_cells > c_size:\n                    c_size *= 2\n                for field in cell_fields:\n                    d[field].resize((c_size,))\n\n            if p_size < n_photons + chunk_nph:\n                while chunk_nph + n_photons > p_size:\n                    p_size *= 2\n                d[\"energy\"].resize((p_size,))\n\n            for i, ax in enumerate(\"xyz\"):\n                pos = chunk[p_fields[i]][idxs].to_value(\"kpc\")\n                # Fix photon coordinates for regions crossing a periodic boundary\n                if ds.periodicity[i]:\n                    tfl = pos < le[i]\n                    tfr = pos > re[i]\n                    pos[tfl] += dw[i]\n                    pos[tfr] -= dw[i]\n\n                vel = chunk[v_fields[i]][idxs].to_value(\"km/s\")\n                # Coordinates are centered\n                d[ax][c_offset:c_offset+chunk_nc] = pos-c[i]\n                d[f\"v{ax}\"][c_offset:c_offset+chunk_nc] = vel\n\n            d[\"num_photons\"][c_offset:c_offset+chunk_nc] = number_of_photons\n            d[\"energy\"][p_offset:p_offset+chunk_nph] = energies\n\n            if w_field is None:\n                d[\"dx\"][c_offset:c_offset+chunk_nc] = 0.0\n            else:\n                d[\"dx\"][c_offset:c_offset+chunk_nc] = \\\n                    chunk[w_field][idxs].to_value(\"kpc\")\n\n            n_cells += chunk_nc\n            n_photons += chunk_nph\n            c_offset = n_cells\n            p_offset = n_photons\n\n        f.flush()\n\n    if c_size > n_cells:\n        for field in cell_fields:\n            d[field].resize((n_cells,))\n\n    if p_size > n_photons:\n        d[\"energy\"].resize((n_photons,))\n\n    f.close()\n\n    source_model.cleanup_model()\n\n    all_nphotons = comm.mpi_allreduce(n_photons)\n    all_ncells = comm.mpi_allreduce(n_cells)\n\n    mylog.info(\"Finished generating photons.\")\n    mylog.info(f\"Number of photons generated: {all_nphotons}\")\n    mylog.info(f\"Number of cells with photons: {all_ncells}\")\n\n    return all_nphotons, all_ncells\n\n\ndef project_photons(photon_prefix, event_prefix, normal, sky_center,\n                    absorb_model=None, nH=None, no_shifting=False,\n                    north_vector=None, sigma_pos=None,\n                    kernel=\"top_hat\", prng=None):\n    r\"\"\"\n    Projects photons onto an image plane given a line of sight, and\n    stores them in an HDF5 dataset which contains an event list.\n\n    Parameters\n    ----------\n    photon_prefix : string\n        The prefix of the filename(s) containing the photon list. If run in\n        serial, the filename will be \"{photon_prefix}.h5\", if run in\n        parallel, the filenames will be \"{photon_prefix}.{mpi_rank}.h5\".\n    event_prefix : string\n        The prefix of the filename(s) which will be written to contain the\n        event list. If run in serial, the filename will be \"{event_prefix}.h5\",\n        if run in parallel, the filename will be \"{event_prefix}.{mpi_rank}.h5\".\n    normal : character or array-like\n        Normal vector to the plane of projection. If \"x\", \"y\", or \"z\", will\n        assume to be along that axis (and will probably be faster). Otherwise,\n        should be an off-axis normal vector, e.g [1.0, 2.0, -3.0]\n    sky_center : array-like\n        Center RA, Dec of the events in degrees.\n    absorb_model : string or :class:`~pyxsim.spectral_models.AbsorptionModel`\n        A model for foreground galactic absorption, to simulate the\n        absorption of events before being detected. This cannot be applied\n        here if you already did this step previously in the creation of the\n        :class:`~pyxsim.photon_list.PhotonList` instance. Known options for\n        strings are \"wabs\" and \"tbabs\".\n    nH : float, optional\n        The foreground column density in units of 10^22 cm^{-2}. Only used\n        if absorption is applied.\n    no_shifting : boolean, optional\n        If set, the photon energies will not be Doppler shifted.\n    north_vector : a sequence of floats\n        A vector defining the \"up\" direction. This option sets the\n        orientation of the plane of projection. If not set, an arbitrary\n        grid-aligned north_vector is chosen. Ignored in the case where a\n        particular axis (e.g., \"x\", \"y\", or \"z\") is explicitly specified.\n    sigma_pos : float, optional\n        Apply a gaussian smoothing operation to the sky positions of the\n        events. This may be useful when the binned events appear blocky due\n        to their uniform distribution within simulation cells. However, this\n        will move the events away from their originating position on the\n        sky, and so may distort surface brightness profiles and/or spectra.\n        Should probably only be used for visualization purposes. Supply a\n        float here to smooth with a standard deviation with this fraction\n        of the cell size. Default: None\n    kernel : string, optional\n        The kernel used when smoothing positions of X-rays originating from\n        SPH particles, \"gaussian\" or \"top_hat\". Default: \"top_hat\".\n    prng : integer or :class:`~numpy.random.RandomState` object \n        A pseudo-random number generator. Typically will only be specified\n        if you have a reason to generate the same set of random numbers,\n        such as for a test. Default is to use the :mod:`numpy.random`\n        module.\n\n    Returns\n    -------\n    A integer for the number of events created\n\n    Examples\n    --------\n    >>> L = np.array([0.1,-0.2,0.3])\n    >>> n_events = pyxsim.project_photons(\"my_photons.h5\", \"my_events.h5\", L,\n    ...                                   [30., 45.], absorb_model='tbabs',\n    ...                                   nH=0.04)\n    \"\"\"\n    from yt.funcs import ensure_numpy_array\n    prng = parse_prng(prng)\n\n    if photon_prefix.endswith(\".h5\"):\n        photon_prefix = photon_prefix[:-3]\n\n    if event_prefix.endswith(\".h5\"):\n        event_prefix = event_prefix[:-3]\n\n    if not isinstance(normal, str):\n        L = np.array(normal)\n        orient = Orientation(L, north_vector=north_vector)\n        x_hat = orient.unit_vectors[0]\n        y_hat = orient.unit_vectors[1]\n        z_hat = orient.unit_vectors[2]\n    else:\n        x_hat = np.zeros(3)\n        y_hat = np.zeros(3)\n        z_hat = np.zeros(3)\n\n    if comm.size > 1:\n        photon_file = f\"{photon_prefix}.{comm.rank:04d}.h5\"\n        event_file = f\"{event_prefix}.{comm.rank:04d}.h5\"\n    else:\n        photon_file = f\"{photon_prefix}.h5\"\n        event_file = f\"{event_prefix}.h5\"\n\n    sky_center = ensure_numpy_array(sky_center)\n\n    scale_shift = -1.0/clight.to_value(\"km/s\")\n\n    if isinstance(absorb_model, str):\n        if absorb_model not in absorb_models:\n            raise KeyError(f\"{absorb_model} is not a known absorption model!\")\n        absorb_model = absorb_models[absorb_model]\n    if absorb_model is not None:\n        if nH is None:\n            raise RuntimeError(\"You specified an absorption model, but didn't \"\n                               \"specify a value for nH!\")\n        absorb_model = absorb_model(nH)\n        if comm.rank == 0:\n            mylog.info(f\"Foreground galactic absorption: using the \"\n                       f\"{absorb_model._name} model and nH = {nH}.\")\n\n    f = h5py.File(photon_file, \"r\")\n\n    p = f[\"parameters\"]\n\n    data_type = p[\"data_type\"].asstr()[()]\n\n    if sigma_pos is not None and data_type == \"particles\":\n        raise RuntimeError(\"The 'smooth_positions' argument should \"\n                           \"not be used with particle-based datasets!\")\n\n    d = f[\"data\"]\n\n    D_A = p[\"fid_d_a\"][()]*1.0e3\n\n    if d[\"energy\"].size == 0:\n\n        mylog.warning(f\"No photons are in file {photon_file}, so \"\n                      f\"I am done.\")\n        n_events = 0\n\n    else:\n\n        fe = h5py.File(event_file, \"w\")\n\n        pe = fe.create_group(\"parameters\")\n        pe.create_dataset(\"exp_time\", data=float(p[\"fid_exp_time\"][()]))\n        pe.create_dataset(\"area\", data=float(p[\"fid_area\"][()]))\n        pe.create_dataset(\"sky_center\", data=sky_center)\n\n        event_fields = [\"xsky\", \"ysky\", \"eobs\"]\n\n        n_events = 0\n        e_offset = 0\n        e_size = init_chunk\n        cell_chunk = init_chunk\n        start_e = 0\n\n        de = fe.create_group(\"data\")\n        for field in event_fields:\n            de.create_dataset(field, data=np.zeros(init_chunk),\n                              maxshape=(None,), chunks=True)\n\n        if isinstance(normal, str):\n            norm = \"xyz\".index(normal)\n        else:\n            norm = normal\n\n        n_cells = d[\"num_photons\"].size\n\n        pbar = get_pbar(\"Projecting photons from cells/particles\", n_cells)\n\n        for start_c in range(0, n_cells, cell_chunk):\n\n            end_c = min(start_c + cell_chunk, n_cells)\n\n            n_ph = d[\"num_photons\"][start_c:end_c]\n            dx = d[\"dx\"][start_c:end_c]\n            end_e = start_e + n_ph.sum()\n            eobs = d[\"energy\"][start_e:end_e]\n\n            if not no_shifting:\n                if isinstance(normal, str):\n                    shift = d[f\"v{normal}\"][start_c:end_c]*scale_shift\n                else:\n                    shift = (d[\"vx\"][start_c:end_c]*z_hat[0] +\n                             d[\"vy\"][start_c:end_c]*z_hat[1] +\n                             d[\"vz\"][start_c:end_c]*z_hat[2])*scale_shift\n                doppler_shift(shift, n_ph, eobs)\n\n            if absorb_model is None:\n                det = np.ones(eobs.size, dtype='bool')\n                num_det = eobs.size\n            else:\n                det = absorb_model.absorb_photons(eobs, prng=prng)\n                num_det = det.sum()\n\n            if num_det > 0:\n\n                xsky, ysky = scatter_events(norm, prng, kernel, \n                                            data_type, num_det, det, n_ph,\n                                            d[\"x\"][start_c:end_c],\n                                            d[\"y\"][start_c:end_c],\n                                            d[\"z\"][start_c:end_c],\n                                            dx, x_hat, y_hat)\n\n                if data_type == \"cells\" and sigma_pos is not None:\n                    sigma = sigma_pos*np.repeat(dx, n_ph)[det]\n                    xsky += sigma*prng.normal(loc=0.0, scale=1.0, size=num_det)\n                    ysky += sigma*prng.normal(loc=0.0, scale=1.0, size=num_det)\n\n                xsky /= D_A\n                ysky /= D_A\n\n                pixel_to_cel(xsky, ysky, sky_center)\n\n                if e_size < n_events + num_det:\n                    while n_events + num_det > e_size:\n                        e_size *= 2\n                    for field in event_fields:\n                        de[field].resize((e_size,))\n\n                de[\"xsky\"][e_offset:e_offset+num_det] = xsky\n                de[\"ysky\"][e_offset:e_offset+num_det] = ysky\n                de[\"eobs\"][e_offset:e_offset+num_det] = eobs[det]\n\n                n_events += num_det\n                e_offset = n_events\n\n                f.flush()\n\n            start_e = end_e\n\n            pbar.update(end_c)\n\n        pbar.finish()\n\n        if e_size > n_events:\n            for field in event_fields:\n                de[field].resize((n_events,))\n\n        fe.close()\n\n    f.close()\n\n    all_nevents = comm.mpi_allreduce(n_events)\n\n    mylog.info(f\"Detected {all_nevents} events.\")\n\n    return all_nevents", "meta": {"hexsha": "95a902dec3eb53fc00e99779e957bef05d9c220e", "size": 23518, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyxsim/photon_list.py", "max_stars_repo_name": "Joeybraspenning/pyxsim", "max_stars_repo_head_hexsha": "6e06bd87c721580fa7fea2d363a2cc4c6b35ca70", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2016-08-08T17:09:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T20:47:13.000Z", "max_issues_repo_path": "pyxsim/photon_list.py", "max_issues_repo_name": "Joeybraspenning/pyxsim", "max_issues_repo_head_hexsha": "6e06bd87c721580fa7fea2d363a2cc4c6b35ca70", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 38, "max_issues_repo_issues_event_min_datetime": "2016-08-08T19:54:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-19T09:03:01.000Z", "max_forks_repo_path": "pyxsim/photon_list.py", "max_forks_repo_name": "Joeybraspenning/pyxsim", "max_forks_repo_head_hexsha": "6e06bd87c721580fa7fea2d363a2cc4c6b35ca70", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-04-04T10:07:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T11:44:11.000Z", "avg_line_length": 38.8727272727, "max_line_length": 124, "alphanum_fraction": 0.5988604473, "include": true, "reason": "import numpy", "num_tokens": 5672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.2814056194821861, "lm_q1q2_score": 0.15603110053326055}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\n\"\"\"\nfrom __future__ import division, print_function, unicode_literals\nfrom ..utilities.future_from_2 import str, object\n\n#from phasor.utilities.print import print\n#import declarative\nimport collections\n#import copy\nimport numpy as np\n\nfrom . import ports\nfrom ..utilities.print import pprint\n\nfrom ..system.matrix_injections import (\n    FactorCouplingBase,\n)\n\ndef pk_prefs(*preflist):\n    def key(pk):\n        p, k = pk\n        pk = p | k\n        ksort = []\n        for ktype in preflist:\n            ksort.append(\n                str(pk.get(ktype, None))\n            )\n        pk.purge_keys(*preflist)\n        ksort.extend(sorted(pk.items()))\n        return tuple(ksort)\n    return key\n\n\ndef lt_mult(lt, lt2):\n    def lt_mult_inner(lt, lt2):\n        if isinstance(lt2, list):\n            sublist = []\n            for sublt2 in lt2:\n                sublist = sublist + lt_mult_inner(lt, sublt2)\n            return sublist\n        elif isinstance(lt2, tuple):\n            #multiply the gains and merge the indices\n            return [(lt2[0] * lt[0],) + lt[1:] + lt2[1:]]\n        else:\n            raise RuntimeError(\"BOO\")\n    if isinstance(lt, list):\n        sublist = []\n        for sublt in lt:\n            sublist = sublist + lt_mult(sublt, lt2)\n        return sublist\n    elif isinstance(lt, tuple):\n        return lt_mult_inner(lt, lt2)\n    else:\n        raise RuntimeError(\"BOO\")\n    return\n\n\ndef lt_sort_collect(new_list):\n    if not new_list:\n        return new_list\n    sNL = [(tuple(sorted(L[1:])), idx) for idx, L in enumerate(new_list)]\n    sNL.sort()\n    list_gen = []\n\n    NL, idx = sNL[0]\n    prev_NL = NL\n    prev_gain = new_list[idx][0]\n    for NL, idx in sNL[1:]:\n        if prev_NL == NL:\n            prev_gain += new_list[idx][0]\n        else:\n            list_gen.append(\n                (prev_gain,) + tuple(prev_NL)\n            )\n            prev_NL = NL\n            prev_gain = new_list[idx][0]\n    list_gen.append(\n        (prev_gain,) + tuple(prev_NL)\n    )\n    return list_gen\n\n\nclass ExpMatCoupling(FactorCouplingBase):\n    \"\"\"\n    Generated by a dict-dict mapping ddlt[out][in] = list-tup-expr\n    where list-tup-expr are a means of expressing addition and multiplication as lists and tups.\n\n    lists represent series addition\n\n    tups represent series multiplication, the first term is a raw number coefficient and any further are keys in the source\n    vector\n    \"\"\"\n    floating_req_set = None\n    #holds a list of 3-tuples, each one carrying an in-set, out-set, and coupling-func\n    #it behaves as though all in-set is connected to out-set for requirements analysis\n    #but then during coupling matrix construction, only the edges returned from coupling-func\n    #will be used\n    floating_in_out_func_pairs = None\n\n    #must redefine since it was a property\n    edges_req_pkset_dict = None\n    def __init__(\n        self,\n        dLt,\n        in_map,\n        out_map,\n        N_ode = 1,\n    ):\n        self.N_ode     = N_ode\n        self.dLt       = dLt\n        self.out_map   = out_map\n        self.in_map    = in_map\n        self.solution  = dict()\n        self.vals_prev = dict()\n        self.vals_inj  = dict()\n\n        #make the internal solution have no action initially (so that cavity feedback converges faster)\n        for pk_internal, pk_in in self.in_map.items():\n            pk_out = self.out_map.get(pk_internal, None)\n            if pk_out is not None:\n                self.solution[pk_in, pk_out] = 1\n\n        #all edges are generated immediately. Currently assumes full density\n        self.edges_NZ_pkset_dict = {}\n        self.edges_pkpk_dict = {}\n        self.edges_req_pkset_dict = {}\n\n        def gen_edge_func(pk_in, pk_out):\n            return lambda sV, sB: self.edge_func(pk_in, pk_out, sV, sB)\n\n        self.floating_req_set = frozenset(self.in_map.values())\n        ins = set(self.in_map.values())\n        outs = set([pkt for pkt in self.out_map.values() if pkt is not None])\n        self.floating_in_out_func_pairs = [(ins, outs, self.edge_mat_func)]\n\n        def gen_src_func_out(pk_out):\n            return lambda sV, sB: self.source_func_out(pk_out, sV, sB)\n        self.sources_pk_dict = {}\n        self.sources_NZ_pkset_dict = {}\n        for pk_out in self.out_map.values():\n            if pk_out is None:\n                continue\n            self.sources_pk_dict[pk_out] = gen_src_func_out(pk_out)\n            self.sources_NZ_pkset_dict[pk_out] = frozenset()\n\n        pks = set()\n        def pks_grab(lt):\n            if isinstance(lt, list):\n                for sublt in lt:\n                    pks_grab(sublt)\n            elif isinstance(lt, tuple):\n                for pk in lt[1:]:\n                    pks.add(pk)\n            else:\n                raise RuntimeError(\"BOO\")\n            return\n        for pk_out, lt in self.dLt.items():\n            pks.add(pk_out)\n            pks_grab(lt)\n\n        #print(ins_p, sol_vector)\n        self.pks = list(pks)\n        #TODO: debug config\n        print(\"Number of states: \", len(pks))\n        #pprint(pks)\n        self.pks.sort(key = pk_prefs(\n            ports.QuantumKey,\n            ports.ElementKey,\n            ports.PortKey,\n            ports.OpticalFreqKey,\n            ports.ClassicalFreqKey,\n            ports.PolKEY,\n        ))\n        self.pks_inv = dict()\n        for idx, pk in enumerate(self.pks):\n            self.pks_inv[pk] = idx\n\n        h = 1 / self.N_ode\n        #remap the index keys into integer indexes for speed\n        dLt_accel = dict()\n        def lt_remap(lt):\n            if isinstance(lt, list):\n                sublist = []\n                for sublt in lt:\n                    sublist.append(lt_remap(sublt))\n                return sublist\n            elif isinstance(lt, tuple):\n                #get the gain\n                newtup = [lt[0] * h]\n                for pk in lt[1:]:\n                    newtup.append(self.pks_inv[pk])\n                return tuple(newtup)\n            else:\n                raise RuntimeError(\"BOO\")\n            return\n        for pk_out, lt in self.dLt.items():\n                dLt_accel[self.pks_inv[pk_out]] = lt_sort_collect(lt_remap(lt))\n        self.dLt_accel = dLt_accel\n\n        #pprint(\"PKS:\")\n        #pprint(pks)\n\n    _prev_sol_vector = None\n\n    def update_solution(self, sol_vector):\n        if self._prev_sol_vector is None or sol_vector != self._prev_sol_vector:\n            self._prev_sol_vector = sol_vector\n            self.generate_solution(sol_vector)\n        return\n\n    def edge_mat_func(self, sol_vector, sB):\n        self.update_solution(sol_vector)\n        return self.solution\n\n    def source_func_out(self, pk_out, sol_vector, sB):\n        self.update_solution(sol_vector)\n        return self.vals_inj.get(pk_out, 0)\n\n    def generate_solution(self, sol_vector):\n        pks = self.pks\n        pkv = np.empty(len(pks), dtype=object)\n\n        all_zeros = True\n        for idx, pk in enumerate(pks):\n            pk_in = self.in_map[pk]\n            #print(\"PK_G: \", (ins_p, pk))\n            sol_val = sol_vector.get(pk_in, 0)\n            prev_val = self.vals_prev.get(pk_in, 0)\n            tot_val = sol_val - prev_val\n            new_val = np.copy(sol_val)\n            if np.all(new_val == 0):\n                new_val = 0\n            pkv[idx] = new_val\n            if np.any(abs(tot_val) > 1e-8 * abs(sol_val)):\n                all_zeros = False\n        if all_zeros:\n            #TODO debug statements\n            #print(\"ALL ZEROS\")\n            #no need to update the solution vector since nothing changed\n            return\n            pass\n        else:\n            #TODO debug statements\n            #print(\"NOT ZEROS\")\n            pass\n        #print(\"SOLVING \", self.pks)\n\n        pk_original = pkv.copy()\n\n        def lt_val(lt):\n            assert(isinstance(lt, list))\n            val = 0\n            for sublt in lt:\n                assert(isinstance(sublt, tuple))\n                gain = np.copy(sublt[0])\n                for pk_idx in sublt[1:]:\n                    gain = gain * pkv[pk_idx]\n                val += gain\n            return val\n\n        def lt_val_matrix_d(vec_d, lt_M_d):\n            for pk_idx_from, lt in lt_M_d.items():\n                assert(isinstance(lt, list))\n                for sublt in lt:\n                    assert(isinstance(sublt, tuple))\n                    local_gain = np.copy(sublt[0])\n                    for pk_idx in sublt[1:]:\n                        val = pkv[pk_idx]\n                        local_gain = local_gain * val\n                    vec_d[pk_idx_from] += local_gain\n\n        def lt_val_matrix_d_generate(pkv_nz_set, lt):\n            lt_M_d = dict()\n            full = 0\n            reduced = 0\n            assert(isinstance(lt, list))\n            for sublt in lt:\n                assert(isinstance(sublt, tuple))\n                gain = sublt[0]\n                for idx_idx, pk_idx_from in enumerate(sublt[1:]):\n                    newtup = [gain]\n                    full += 1\n                    for idx_idx2, pk_idx in enumerate(sublt[1:]):\n                        if idx_idx == idx_idx2:\n                            continue\n                        if pk_idx not in pkv_nz_set:\n                            break\n                        newtup.append(pk_idx)\n                    else:\n                        #only occurs if break was NOT called\n                        reduced += 1\n                        lt_inj = lt_M_d.setdefault(pk_idx_from, [])\n                        lt_inj.append(\n                            tuple(newtup)\n                        )\n            #print(\"REDUCED LT_d: \", reduced / full)\n            return lt_M_d\n\n        def lt_reduced_generate(pkv_nz_set, lt):\n            newlt = []\n            assert(isinstance(lt, list))\n            for sublt in lt:\n                assert(isinstance(sublt, tuple))\n                newtup = [sublt[0]]\n                for pk_idx in sublt[1:]:\n                    if pk_idx not in pkv_nz_set:\n                        break\n                    newtup.append(pk_idx)\n                else:\n                    #only occurs if break was NOT called\n                    newlt.append(\n                        tuple(newtup)\n                    )\n            #print(\"REDUCED LT: \", len(newlt) / len(lt))\n            return newlt\n\n        #a double map matrix dMexp_s1[idx_out][idx_in]\n        ##this dMexp_s1 does not have the one. For speed that is applied separately\n        dMexp_s1 = collections.defaultdict(lambda : collections.defaultdict(lambda : 0))\n\n        pkv_nz_set = set()\n        for idx, val in enumerate(pkv):\n            if np.any(val != 0):\n                pkv_nz_set.add(idx)\n\n        dLt_base = sorted(self.dLt_accel.items())\n        dLt_idx_list = [T[0] for T in dLt_base]\n        dLt_lt_list  = [lt_reduced_generate(pkv_nz_set, T[1]) for T in dLt_base]\n        dLt_lt_M_list  = [lt_val_matrix_d_generate(pkv_nz_set, T[1]) for T in dLt_base]\n\n        for idx_N in range(self.N_ode):\n            idx_in_list = 0\n            fullskip = 0\n            while idx_in_list < len(dLt_idx_list):\n                idx_pk = dLt_idx_list[idx_in_list]\n                lt     = dLt_lt_list[idx_in_list]\n                lt_M_d = dLt_lt_M_list[idx_in_list]\n                idx_in_list += 1\n                if not lt and not lt_M_d:\n                    fullskip += 1\n\n                dPK = lt_val(lt)\n                Mexp_vec_d = collections.defaultdict(lambda : 0)\n                lt_val_matrix_d(Mexp_vec_d, lt_M_d)\n\n                if pkv[idx_pk] is 0:\n                    if np.any(dPK != 0):\n                        #print(\"STATUS CHANGE: \", idx_pk)\n                        pkv_nz_set.add(idx_pk)\n                        dLt_idx_list = [T[0] for T in dLt_base]\n                        dLt_lt_list  = [lt_reduced_generate(pkv_nz_set, T[1]) for T in dLt_base]\n                        dLt_lt_M_list  = [lt_val_matrix_d_generate(pkv_nz_set, T[1]) for T in dLt_base]\n                if np.any(dPK != 0):\n                    pkv[idx_pk] = pkv[idx_pk] + dPK\n\n                dMexp_update = collections.defaultdict(lambda : 0)\n                #print(\"LEN: \", len(dMexp_s1))\n                #print(\"VEC: \", len(Mexp_vec_d))\n                N_zero = 0\n                N_skip = 0\n                for idx_out, vec_val in Mexp_vec_d.items():\n                    for idx_in, edge in dMexp_s1[idx_out].items():\n                        if np.all(edge == 0):\n                            N_zero += 1\n                            continue\n                        dMexp_update[idx_in] += (edge * vec_val)\n\n                #print(\"NZERO: \", N_zero, N_zero / (.001+len(dMexp_s1)))\n                #print(\"NSKIP: \", N_skip, N_skip / (.001+len(dMexp_s1)))\n\n                for idx_in, vec_val in dMexp_update.items():\n                    if np.any(vec_val != 0):\n                        dMexp_s1[idx_pk][idx_in] += vec_val\n\n                #applied the initial vector again since the dMexp_s1 didn't start with diagonal ones\n                for idx_in, vec_val in Mexp_vec_d.items():\n                    if np.any(vec_val != 0):\n                        dMexp_s1[idx_pk][idx_in] += vec_val\n            #print(\"FULLSKIP: \", fullskip, fullskip / len(dLt_idx_list))\n\n        self.vals_prev = dict()\n        #inject subtracted values at input to remove the DC values an only get the derivative\n        for idx_in in range(len(pks)):\n            pkin = self.in_map[pks[idx_in]]\n\n            val = pk_original[idx_in]\n            if np.any(val != 0):\n                self.vals_prev[pkin] = val\n\n        #print(\"START EDGES\")\n        #for idx_out in range(len(pks)):\n        #    for idx_in in range(len(pks)):\n        #        edge = dMexp_s1.get(idx_out, dict()).get(idx_in, None)\n        #        if edge is not None:\n        #            pkin = self.in_map[pks[idx_in]]\n        #            pkout = self.out_map[pks[idx_out]]\n        #            if idx_in == idx_out:\n        #                edge = edge + 1\n\n        #            print(\"IN: \", pkin[1])\n        #            print(\"  OUT: \", pkout[1])\n        #            print(\"EDGE: \", edge)\n        #print(\"DONE EDGES\")\n        #dval_out holds the product of the input through the derivative matrix\n        #this way it can cancel the forward propagation so that the output is correct assuming\n        #the inputs do not change\n        solution = dict()\n        dval_out = collections.defaultdict(lambda : 0)\n\n        #alter the derivative matrix to pass through the direct values\n        for idx in range(len(pks)):\n            in_map = dMexp_s1.get(idx, None)\n            if in_map is None:\n                dMexp_s1[idx] = {idx : 1}\n                continue\n            in_map[idx] = in_map.get(idx, 0) + 1\n\n        for idx_out, in_map in dMexp_s1.items():\n            for idx_in, edge in in_map.items():\n                pkin = self.in_map[pks[idx_in]]\n                pkout = self.out_map[pks[idx_out]]\n\n                if pkin is not None and pkout is not None:\n                    solution[pkin, pkout] = edge\n\n                #also compute dval_out\n                val_orig = pk_original[idx_in]\n                prod = (edge * val_orig)\n                if np.any(prod != 0):\n                    dval_out[idx_out] += prod\n        self.solution = solution\n\n        vals_inj = dict()\n        for idx_out in range(len(pks)):\n            pkout = self.out_map[pks[idx_out]]\n            if pkout is None:\n                continue\n            val = pkv[idx_out]\n            altered_val = val - dval_out.get(idx_out, 0)\n            #print(\"ALT: \", pkout, val, dval_out.get(idx, 0), altered_val)\n            vals_inj[pkout] = altered_val\n        self.vals_inj = vals_inj\n\n        #print(\"DONE SOLVING \")\n        return\n\n\n\n#Old version\n\"\"\"\nclass ExpMatCoupling(FactorCouplingBase):\n\n    #must redefine since it was a property\n    edges_req_pkset_dict = None\n    def __init__(\n        self,\n        ddlt,\n        in_map,\n        out_map,\n        N_ode = 1,\n        order = 2,\n        symplectify = True,\n    ):\n        self.N_ode   = N_ode\n        self.order   = order\n        self.ddlt    = ddlt\n        self.out_map = out_map\n        self.in_map  = in_map\n\n        #all edges are generated immediately. Currently assumes full density\n        self.edges_NZ_pkset_dict = {}\n        self.edges_pkpk_dict = {}\n        self.edges_req_pkset_dict = {}\n        def gen_edge_func(pk_in, pk_out):\n            return lambda sV, sB: self.edge_func(pk_in, pk_out, sV, sB)\n        for pk_out in self.out_map.values():\n            if pk_out is None:\n                continue\n            for pk_in in self.in_map.values():\n                self.edges_NZ_pkset_dict[(pk_in, pk_out)] = frozenset()\n                self.edges_pkpk_dict[(pk_in, pk_out)] = gen_edge_func(pk_in, pk_out)\n                self.edges_req_pkset_dict[(pk_in, pk_out)] = frozenset(self.in_map.values())\n\n        #Currently, nonlinear doesn't need to make any sources. It may in the future as that may be a more stable way to converge\n        self.sources_pk_dict = {}\n        self.sources_NZ_pkset_dict = {}\n\n        pks = set()\n        def pks_grab(lt):\n            if isinstance(lt, list):\n                for sublt in lt:\n                    pks_grab(sublt)\n            elif isinstance(lt, tuple):\n                for pk in lt[1:]:\n                    pks.add(pk)\n            else:\n                raise RuntimeError(\"BOO\")\n            return\n        for pk_out, din in self.ddlt.items():\n            pks.add(pk_out)\n            for pk_in, lt in din.items():\n                pks.add(pk_in)\n                pks_grab(lt)\n\n        #print(ins_p, sol_vector)\n        self.pks = list(pks)\n        print(\"OMG: \", len(pks))\n        pprint(pks)\n        self.pks.sort()\n        self.pks_inv = dict()\n        for idx, pk in enumerate(self.pks):\n            self.pks_inv[pk] = idx\n\n        h = 1 / self.N_ode\n        #remap the index keys into integer indexes for speed\n        ddlt_accel = dict()\n        def ddlt_remap(lt):\n            if isinstance(lt, list):\n                sublist = []\n                for sublt in lt:\n                    sublist.append(ddlt_remap(sublt))\n                return sublist\n            elif isinstance(lt, tuple):\n                #get the gain\n                newtup = [lt[0] * h]\n                for pk in lt[1:]:\n                    newtup.append(self.pks_inv[pk])\n                return tuple(newtup)\n            else:\n                raise RuntimeError(\"BOO\")\n            return\n        for pk_out, din in self.ddlt.items():\n            for pk_in, lt in din.items():\n                ddlt_accel[self.pks_inv[pk_out], self.pks_inv[pk_in]] = ddlt_remap(lt)\n        self.ddlt_accel = ddlt_accel\n\n        def ddlt_mult(lt, lt2):\n            def ddlt_mult2(lt, lt2):\n                if isinstance(lt2, list):\n                    sublist = []\n                    for sublt2 in lt2:\n                        sublist = sublist + ddlt_mult2(lt, sublt2)\n                    return sublist\n                elif isinstance(lt2, tuple):\n                    #multiply the gains and merge the indices\n                    return [(lt2[0] * lt[0],) + lt[1:] + lt2[1:]]\n                else:\n                    raise RuntimeError(\"BOO\")\n            if isinstance(lt, list):\n                sublist = []\n                for sublt in lt:\n                    sublist = sublist + ddlt_mult(sublt, lt2)\n                return sublist\n            elif isinstance(lt, tuple):\n                return ddlt_mult2(lt, lt2)\n            else:\n                raise RuntimeError(\"BOO\")\n            return\n        def sort_collect(new_list):\n            if not new_list:\n                return new_list\n            sNL = [(tuple(sorted(L[1:])), idx) for idx, L in enumerate(new_list)]\n            sNL.sort()\n            list_gen = []\n\n            NL, idx = sNL[0]\n            prev_NL = NL\n            prev_gain = new_list[idx][0]\n            for NL, idx in sNL[1:]:\n                if prev_NL == NL:\n                    prev_gain += new_list[idx][0]\n                else:\n                    list_gen.append(\n                        (prev_gain,) + tuple(prev_NL)\n                    )\n                    prev_NL = NL\n                    prev_gain = new_list[idx][0]\n            list_gen.append(\n                (prev_gain,) + tuple(prev_NL)\n            )\n            return list_gen\n\n\n        self.ddlt_accel = ddlt_accel\n\n        if symplectify:\n            #print(\"IS SYMPLECTIC!\")\n            ddlt_accel_SE = dict()\n            #put in the diagonals first\n            for idx, pk in enumerate(self.pks):\n                ddlt_accel_SE[idx, idx] = [(1,)]\n\n            for pk_out, din in self.ddlt.items():\n                pk_out_idx = self.pks_inv[pk_out]\n                for pk_in, lt in din.items():\n                    pk_in_idx = self.pks_inv[pk_in]\n                    assert(pk_out_idx != pk_in_idx)\n                    for col_idx, pk in enumerate(self.pks):\n                        #needs to multiply everything\n                        lt_rm = ddlt_remap(lt)\n                        lt_keep = ddlt_accel_SE.get((pk_out_idx, col_idx), [])\n                        lt_mult = ddlt_accel_SE.get((pk_in_idx, col_idx), [])\n                        new_list = lt_keep + ddlt_mult(lt_mult, lt_rm)\n                        #clear out now couplings for speed\n                        new_list = [L for L in new_list if len(L[1:]) <= 3]\n                        if not new_list or new_list == [(1,)]:\n                            ddlt_accel_SE[pk_out_idx, col_idx] = new_list\n                            continue\n\n                        new_list = sort_collect(new_list)\n                        #if new_list:\n                            #print(pk_out_idx, col_idx)\n                            #print([(\"{0:.2f}\".format(np.log10(abs(L[0]) / h)), len(L[1:])) for L in new_list])\n                        ddlt_accel_SE[pk_out_idx, col_idx] = new_list\n\n            ddlt_accel_SE_use = dict()\n            for (idx_out, idx_in), lt in ddlt_accel_SE.items():\n                #TODO use a search to remove this since they have been sorted\n                if idx_out == idx_in:\n                    if lt and lt[0] == (1,):\n                        lt = lt[1:]\n                    else:\n                        lt = lt + [(-1,)]\n                if lt:\n                    ddlt_accel_SE_use[idx_out, idx_in] = lt\n            #pprint(ddlt_accel_SE_use)\n\n            self.ddlt_accel = ddlt_accel_SE_use\n\n            #add in linear term\n            new_mat = copy.deepcopy(self.ddlt_accel)\n            #add in diagonal (1) term\n            for idx in range(len(self.pks)):\n                lst = new_mat.setdefault((idx, idx), [])\n                lst.append((1,))\n            #add in second-order term\n            for (idx_out, idx_in), lt1 in self.ddlt_accel.items():\n                for idx_in2 in range(len(self.pks)):\n                    lt2 = self.ddlt_accel.get((idx_in, idx_in2), None)\n                    if lt2 is None:\n                        continue\n                    lt_mult = []\n                    for l1 in lt1:\n                        lt_mult.extend([(l1[0] * l2[0] / 2, ) + l1[1:] + l2[1:] for l2 in lt2])\n                    #clear out now couplings for speed\n                    lt_mult = sort_collect([L for L in lt_mult if abs(L[0]) >= 1e-8])\n                    #if lt_mult:\n                    #    print(\"1: \", lt1)\n                    #    print(\"2: \", lt2)\n                    #    print(\"LT_MULT: \", lt_mult)\n                    nl = new_mat.setdefault((idx_out, idx_in2), [])\n                    nl.extend(lt_mult)\n\n            for (idx_out, idx_in) in list(new_mat.keys()):\n                lt1 = new_mat[idx_out, idx_in]\n                lt = sort_collect(lt1)\n                nl = [L for L in nl if abs(L[0]) >= 1e-5]\n                if lt:\n                    lt1[:] = lt\n                else:\n                    del new_mat[idx_out, idx_in]\n            self.ddlt_accel_premult2 = new_mat\n\n        #pprint(\"PKS:\")\n        #pprint(pks)\n\n    _prev_sol_vector = None\n\n    def edge_func(self, pk_in, pk_out, sol_vector, sB):\n        if sol_vector != self._prev_sol_vector:\n            self._prev_sol_vector = sol_vector\n            if self.order > 0:\n                #self.generate_solution(sol_vector)\n                self.generate_solution_premult(sol_vector)\n            elif self.order == 0:\n                self.generate_solution_RK(sol_vector)\n        return self.solution.get((pk_in, pk_out), 0)\n\n    def generate_solution_premult(self, sol_vector):\n        pks = self.pks\n        pkv = np.empty(len(pks), dtype=object)\n        for idx, pk in enumerate(pks):\n            #print(\"PK_G: \", (ins_p, pk))\n            pkv[idx] = sol_vector.get(self.in_map[pk], 0)\n        pkO = pkv.copy()\n        #print(\"PKV: \", pkv)\n        #try:\n        #    import tabulate\n        #    tabular_data = [[str(label)] + [pk] for label, pk in zip(pks, pkv)]\n        #    print(\"PKs:\")\n        #    print(tabulate.tabulate(tabular_data))\n        #except ImportError:\n        #    print(\"XXXX\")\n\n        def lt_val(lt):\n            if isinstance(lt, list):\n                val = 0\n                for sublt in lt:\n                    val = lt_val(sublt) + val\n            elif isinstance(lt, tuple):\n                val = lt[0]\n                #print(\"LT0: \", val)\n                for pk_idx in lt[1:]:\n                    val = val * pkv[pk_idx]  # sol_vector.get(pk, 0)\n            else:\n                raise RuntimeError(\"BOO\")\n            return val\n\n        eye = np.eye(len(pks), dtype = object)\n        Mexp_tot = eye\n        for idx_N in range(self.N_ode):\n            print('pe_A premult')\n            Mexp = np.zeros([len(pks), len(pks)], dtype = object)\n            for (idx_out, idx_in), lt in self.ddlt_accel_premult2.items():\n                    val = lt_val(lt)\n                    Mexp[idx_out, idx_in] = val\n            #print(\"Mexp: \", Mexp)\n            print('pe_B')\n            Mexp_tot = np.dot(Mexp, Mexp_tot)\n            print(\"Sparsity: \", idx_N, np.sum(Mexp_tot.flatten() != 0)/ len(Mexp_tot.flatten()))\n            #print(Mexp.shape, pkv.shape)\n            pkv = np.dot(Mexp, pkv.reshape(-1, 1)).reshape(-1)\n            #try:\n            #    import tabulate\n            #    tabular_data = [[str(label)] + [str(pk), str(pkk)] for label, pk, pkk in zip(pks, pkv, pkX)]\n            #    print(\"PKs2:\")\n            #    print(tabulate.tabulate(tabular_data))\n            #except ImportError:\n            #    print(\"XXXX\")\n            #print(\"pkv2:\", type(pkv), pkv.shape)\n            #print(pkv)\n\n        #print(m1)\n        #print(Mexp)\n        try:\n            import tabulate\n            tabular_data = [[str(label)] + [str(pk)] for label, pk in zip(pks, pkv)]\n            print(\"PKs2:\")\n            print(tabulate.tabulate(tabular_data))\n        except ImportError:\n            print(\"XXXX\")\n        try:\n            import tabulate\n            tabular_data = [[str(label)] + list(abs(x) for x in td) for idx, (label, td) in enumerate(zip(pks, Mexp_tot))]\n            print(\"Mexp_tot\", idx)\n            print(Mexp.dtype)\n            print(tabulate.tabulate(tabular_data))\n        except ImportError:\n            print(\"XXXX\")\n\n        N_sparsity = 0\n        solution = dict()\n        for idx_in in range(len(pks)):\n            for idx_out in range(len(pks)):\n                edge = Mexp_tot[idx_out, idx_in]\n                if np.any(edge != 0):\n                    N_sparsity += 1\n                    #pk_in = pks[idx_in]\n                    #pk_out = pks[idx_out]\n                    ###TODO: add debug config reference for this print\n                    #print(pk_in)\n                    #print(pk_out)\n                    #print(idx_in, idx_out, edge)\n                    pkin = self.in_map[pks[idx_in]]\n                    pkout = self.out_map[pks[idx_out]]\n                    if pkout is None:\n                        continue\n                    solution[pkin, pkout] = edge\n        #print(\"Sparsity: \", N_sparsity / len(Mexp_tot.flatten()))\n\n        #pprint(pks)\n\n        self.solution = solution\n\n    def generate_solution(self, sol_vector):\n        pks = self.pks\n        pkv = np.empty(len(pks), dtype=object)\n        for idx, pk in enumerate(pks):\n            #print(\"PK_G: \", (ins_p, pk))\n            pkv[idx] = sol_vector.get(self.in_map[pk], 0)\n        pkO = pkv.copy()\n        #print(\"PKV: \", pkv)\n        #try:\n        #    import tabulate\n        #    tabular_data = [[str(label)] + [pk] for label, pk in zip(pks, pkv)]\n        #    print(\"PKs:\")\n        #    print(tabulate.tabulate(tabular_data))\n        #except ImportError:\n        #    print(\"XXXX\")\n\n        def lt_val(lt):\n            if isinstance(lt, list):\n                val = 0\n                for sublt in lt:\n                    val = lt_val(sublt) + val\n            elif isinstance(lt, tuple):\n                val = lt[0]\n                #print(\"LT0: \", val)\n                for pk_idx in lt[1:]:\n                    val = val * pkv[pk_idx]  # sol_vector.get(pk, 0)\n            else:\n                raise RuntimeError(\"BOO\")\n            return val\n\n        eye = np.eye(len(pks), dtype = object)\n        Mexp_tot = eye\n        for idx_N in range(self.N_ode):\n            print('pe_A')\n            m1 = np.zeros([len(pks), len(pks)], dtype = object)\n            for (idx_out, idx_in), lt in self.ddlt_accel.items():\n                    val = lt_val(lt)\n                    m1[idx_out, idx_in] = val\n            #print(\"M1: \", m1)\n            print('pe_B')\n            Mexp = m1 + eye\n            mmem = m1\n            #try:\n            #    import tabulate\n            #    tabular_data = [[str(idx)] + list(td) for idx, (label, td) in enumerate(zip(pks, m1))]\n            #    print(\"M1\")\n            #    print(m1.dtype)\n            #    print(tabulate.tabulate(tabular_data))\n            #except ImportError:\n            #    print(\"XXXX\")\n            #try:\n            #    import tabulate\n            #    tabular_data = [[str(idx)] + list(str(x) for x in td) for idx, (label, td) in enumerate(zip(pks, Mexp))]\n            #    print(\"Mexp\", 1)\n            #    print(Mexp.dtype)\n            #    print(tabulate.tabulate(tabular_data))\n            #except ImportError:\n            #    print(\"XXXX\")\n            for idx in range(2, self.order+1):\n                mmem = (1 / idx) * np.dot(m1, mmem)\n                #try:\n                #    import tabulate\n                #    tabular_data = [[str(idx)] + list(td) for idx, (label, td) in enumerate(zip(pks, mmem))]\n                #    print(\"mmem\", idx)\n                #    print(mmem.dtype)\n                #    print(tabulate.tabulate(tabular_data))\n                #except ImportError:\n                #    print(\"XXXX\")\n                Mexp = Mexp + mmem\n            print('pe_C')\n            #try:\n            #    import tabulate\n            #    tabular_data = [[str(idx)] + list(str(x) for x in td) for idx, (label, td) in enumerate(zip(pks, Mexp))]\n            #    print(\"Mexp\", idx)\n            #    print(Mexp.dtype)\n            #    print(tabulate.tabulate(tabular_data))\n            #except ImportError:\n            #    print(\"XXXX\")\n            #import scipy.linalg\n            #Mexpe_2 = scipy.linalg.expm(m1.astype(complex))\n            #try:\n            #    import tabulate\n            #    tabular_data = [[str(idx)] + list(str(x) for x in td) for idx, (label, td) in enumerate(zip(pks, Mexpe_2))]\n            #    print(\"Mexpe_2\", idx)\n            #    print(Mexpe_2.dtype)\n            #    print(tabulate.tabulate(tabular_data))\n            #except ImportError:\n            #    print(\"XXXX\")\n            ### IMPROVE POWER CONSERVATION\n            #for idx in range(len(pks)):\n            #    NORMsq = np.dot(Mexp[idx], Mexp[idx].conjugate())\n            #    #print(\"pwr \", idx, \" VAL: \", NORMsq)\n            #    Mexp[idx] = Mexp[idx] / (NORMsq.real)**.5\n            Mexp_tot = np.dot(Mexp, Mexp_tot)\n            print(\"Sparsity: \", idx_N, np.sum(Mexp_tot.flatten() != 0)/ len(Mexp_tot.flatten()))\n            #print(Mexp.shape, pkv.shape)\n            pkv = np.dot(Mexp, pkv.reshape(-1, 1)).reshape(-1)\n            #try:\n            #    import tabulate\n            #    tabular_data = [[str(label)] + [str(pk), str(pkk)] for label, pk, pkk in zip(pks, pkv, pkX)]\n            #    print(\"PKs2:\")\n            #    print(tabulate.tabulate(tabular_data))\n            #except ImportError:\n            #    print(\"XXXX\")\n            #print(\"pkv2:\", type(pkv), pkv.shape)\n            #print(pkv)\n\n        #print(m1)\n        #print(Mexp)\n        #try:\n        #    import tabulate\n        #    tabular_data = [[str(label)] + [pk] for label, pk in zip(pks, pkv)]\n        #    print(\"PKs2:\")\n        #    print(tabulate.tabulate(tabular_data))\n        #except ImportError:\n        #    print(\"XXXX\")\n        #try:\n        #    import tabulate\n        #    tabular_data = [[str(idx)] + list(str(x) for x in td) for idx, (label, td) in enumerate(zip(pks, Mexp_tot))]\n        #    print(\"Mexp_tot\", idx)\n        #    print(Mexp.dtype)\n        #    print(tabulate.tabulate(tabular_data))\n        #except ImportError:\n        #    print(\"XXXX\")\n\n        N_sparsity = 0\n        solution = dict()\n        for idx_in in range(len(pks)):\n            for idx_out in range(len(pks)):\n                edge = Mexp_tot[idx_out, idx_in]\n                if np.any(edge != 0):\n                    N_sparsity += 1\n                    #pk_in = pks[idx_in]\n                    #pk_out = pks[idx_out]\n                    ###TODO: add debug config reference for this print\n                    #print(pk_in)\n                    #print(pk_out)\n                    #print(idx_in, idx_out, edge)\n                    pkin = self.in_map[pks[idx_in]]\n                    pkout = self.out_map[pks[idx_out]]\n                    if pkout is None:\n                        continue\n                    solution[pkin, pkout] = edge\n        #print(\"Sparsity: \", N_sparsity / len(Mexp_tot.flatten()))\n\n        #pprint(pks)\n\n        self.solution = solution\n\n    def generate_solution_RK(self, sol_vector):\n        pks = self.pks\n        pkv = np.empty(len(pks), dtype=object)\n        for idx, pk in enumerate(pks):\n            #print(\"PK_G: \", (ins_p, pk))\n            pkv[idx] = sol_vector.get(self.in_map[pk], 0)\n\n        def lt_val(lt, pkv):\n            if isinstance(lt, list):\n                val = 0\n                for sublt in lt:\n                    val = lt_val(sublt, pkv) + val\n            elif isinstance(lt, tuple):\n                val = lt[0]\n                #print(\"LT0: \", val)\n                for pk_idx in lt[1:]:\n                    val = val * pkv[pk_idx]  # sol_vector.get(pk, 0)\n            else:\n                raise RuntimeError(\"BOO\")\n            return val\n\n        eye = np.eye(len(pks), dtype = object)\n        Mexp_tot = eye\n        for idx_N in range(self.N_ode):\n            mk1 = np.zeros([len(pks), len(pks)], dtype = object)\n            #the current ddlt_accel already incorporates h, so we must reverse that for the Runge Kutta Solver\n            h = 1 / self.N_ode\n            for (idx_out, idx_in), lt in self.ddlt_accel.items():\n                    val = lt_val(lt, pkv) / h\n                    mk1[idx_out, idx_in] = val\n\n            pkv_k1 = np.dot(mk1, pkv.reshape(-1, 1)).reshape(-1)\n            mk2 = np.zeros([len(pks), len(pks)], dtype = object)\n            for (idx_out, idx_in), lt in self.ddlt_accel.items():\n                    val = lt_val(lt, pkv + h/2 * pkv_k1) / h\n                    mk2[idx_out, idx_in] = val\n\n            pkv_k2 = np.dot(mk2, pkv.reshape(-1, 1)).reshape(-1)\n            mk3 = np.zeros([len(pks), len(pks)], dtype = object)\n            for (idx_out, idx_in), lt in self.ddlt_accel.items():\n                    val = lt_val(lt, pkv + h/2 * pkv_k2) / h\n                    mk3[idx_out, idx_in] = val\n\n            pkv_k3 = np.dot(mk3, pkv.reshape(-1, 1)).reshape(-1)\n            mk4 = np.zeros([len(pks), len(pks)], dtype = object)\n            for (idx_out, idx_in), lt in self.ddlt_accel.items():\n                    val = lt_val(lt, pkv + h * pkv_k3) / h\n                    mk4[idx_out, idx_in] = val\n\n            #try:\n            #    import tabulate\n            #    tabular_data = [[str(idx)] + list(str(t) for t in td) for idx, (label, td) in enumerate(zip(pks, mk1))]\n            #    print(\"MK1\")\n            #    print(tabulate.tabulate(tabular_data))\n            #    tabular_data = [[str(idx)] + list(str(t) for t in td) for idx, (label, td) in enumerate(zip(pks, mk2))]\n            #    print(\"MK2\")\n            #    print(tabulate.tabulate(tabular_data))\n            #    tabular_data = [[str(idx)] + list(str(t) for t in td) for idx, (label, td) in enumerate(zip(pks, mk3))]\n            #    print(\"MK3\")\n            #    print(tabulate.tabulate(tabular_data))\n            #    tabular_data = [[str(idx)] + list(str(t) for t in td) for idx, (label, td) in enumerate(zip(pks, mk4))]\n            #    print(\"MK4\")\n            #    print(tabulate.tabulate(tabular_data))\n            #except ImportError:\n            #    print(\"XXXX\")\n\n            Mexp = eye + h/6 * (mk1 + 2 * mk2 + 2 * mk3 + mk4)\n            Mexp_tot = np.dot(Mexp, Mexp_tot)\n            pkv = np.dot(Mexp, pkv.reshape(-1, 1)).reshape(-1)\n\n        solution = dict()\n        for idx_in in range(len(pks)):\n            for idx_out in range(len(pks)):\n                edge = Mexp_tot[idx_out, idx_in]\n                if np.any(edge != 0):\n                    #pk_in = pks[idx_in]\n                    #pk_out = pks[idx_out]\n                    ###TODO: add debug config reference for this print\n                    #print(pk_in)\n                    #print(pk_out)\n                    #print(idx_in, idx_out, edge)\n                    pkin = self.in_map[pks[idx_in]]\n                    pkout = self.out_map[pks[idx_out]]\n                    if pkout is None:\n                        continue\n                    solution[pkin, pkout] = edge\n\n        #pprint(pks)\n\n        self.solution = solution\n\n\"\"\"\n", "meta": {"hexsha": "e7d41f24631a668895e191fe4dce2d4916b5f658", "size": 38029, "ext": "py", "lang": "Python", "max_stars_repo_path": "phasor/optics/ODE_solver.py", "max_stars_repo_name": "mccullerlp/OpenLoop", "max_stars_repo_head_hexsha": "fe86dc6dec3740d4b6be6b88d8eef8566e2aa78d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-02-28T00:43:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-21T11:39:15.000Z", "max_issues_repo_path": "phasor/optics/ODE_solver.py", "max_issues_repo_name": "mccullerlp/OpenLoop", "max_issues_repo_head_hexsha": "fe86dc6dec3740d4b6be6b88d8eef8566e2aa78d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-09-07T23:15:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-07T23:15:43.000Z", "max_forks_repo_path": "phasor/optics/ODE_solver.py", "max_forks_repo_name": "mccullerlp/OpenLoop", "max_forks_repo_head_hexsha": "fe86dc6dec3740d4b6be6b88d8eef8566e2aa78d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-21T04:42:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-21T04:42:09.000Z", "avg_line_length": 37.3933136676, "max_line_length": 129, "alphanum_fraction": 0.4927555287, "include": true, "reason": "import numpy,import scipy", "num_tokens": 9397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.29098086621490676, "lm_q1q2_score": 0.15570340427200688}}
{"text": "#!/usr/bin/env python3\n\n###########################################################################\n#  This file is part of rsp2, and is licensed under EITHER the MIT license\n#  or the Apache 2.0 license, at your option.\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#      http://opensource.org/licenses/MIT\n#\n#  Be aware that not all of rsp2 is provided under this permissive license,\n#  and that the project as a whole is licensed under the GPL 3.0.\n###########################################################################\n\nimport numpy as np\nimport json\nimport sys\nimport scipy.sparse\nimport typing as tp\n\nfrom . import eigsh_custom, get_OPinv\nfrom rsp2.internals import info\nfrom rsp2.io import dynmat, eigensols\n\n# The default tolerance for eigsh is machine precision, which I feel is\n# overkill. Hopefully a lighter tolerance will save some time.\n#\n# TODO maybe: experiment with this\nTOL = 1e-10\n\n# absolute cosines greater than this are deemed non-orthogonal\nOVERLAP_THRESH = 1e-6\n\nDEFAULT_MAX_SOLUTIONS = 12\nDEFAULT_SHIFT_INVERT_ATTEMPTS = 4\nDEFAULT_NCV = 0\n\ndef main_from_rust():\n    \"\"\"\n    Entry point when called from rsp2's rust code.\n\n    Communicates through JSON over the standard IO streams.\n    \"\"\"\n    info('trace: sending dynmat from rust to python')\n    d = json.load(sys.stdin)\n    m = dynmat.from_dict(d.pop('matrix'))\n    shift_invert_attempts = d.pop('shift-invert-attempts')\n    dense = d.pop('dense')\n    max_solutions = d.pop('max-solutions')\n    assert not d\n\n    out = run(m,\n              dense=dense,\n              shift_invert_attempts=shift_invert_attempts,\n              plain_ncv=DEFAULT_NCV, # FIXME add to input json from rust\n              shift_invert_ncv=DEFAULT_NCV, # FIXME add to input json from rust\n              use_fallback=True, # FIXME add to input json from rust\n              max_solutions=max_solutions,\n              search_solutions=None, # FIXME add to input json from rust\n              )\n\n    info('trace: sending eigensolutions from python to rust')\n    json.dump(eigensols.to_cereal(out), sys.stdout)\n    print(file=sys.stdout) # newline\n\ndef main_from_cli():\n    \"\"\"\n    Entry point for the standalone CLI wrapper.\n    \"\"\"\n    import argparse\n    p = argparse.ArgumentParser()\n    p.add_argument('DYNMAT', help='dynmat file (.npz, .json, .json.gz, ...)')\n    p.add_argument('--output', '-o', type=str, required=True)\n    p.add_argument(\n        '--dense', action='store_true',\n        help=\"Use a dense eigenvalue solver. Almost all other options will be \"\n             \"ignored in this case.\"\n    )\n    p.add_argument('--shift-invert-attempts', type=int, default=DEFAULT_SHIFT_INVERT_ATTEMPTS)\n    p.add_argument(\n        '--no-fallback', dest='use_fallback', action='store_false',\n        help=\"Disable non-shift-invert-based fallback method.\"\n    )\n    p.add_argument(\n        '--max-solutions', type=int, default=None,\n        help=\"max number of solutions to seek. Default is 12 unless --dense is given.\"\n    )\n    p.add_argument(\n        '--shift-invert-ncv', type=int, default=DEFAULT_NCV,\n        help=\"suggested number of Lanczos vectors. This will automatically be \"\n             \"clipped into the range of [min(2*max_solutions + 1, n), n]\"\n    )\n    p.add_argument(\n        '--plain-ncv', type=int, default=DEFAULT_NCV,\n        help=\"suggested number of Lanczos vectors. This will automatically be \"\n             \"clipped into the range of [min(2*max_solutions + 1, n), n]\"\n    )\n    p.add_argument(\n        '--search-solutions', type=int, default=None,\n        help=\"actually ask the sparse solver for this many solutions instead \"\n             \"of --max-solutions.  The sparse solver can converge much, much \"\n             \"faster when a few hundred solutions are requested rather than \"\n             \"just 12.\"\n    )\n    args = p.parse_args()\n\n    if (not args.dense\n            and args.search_solutions is not None\n            and args.max_solutions is not None\n            and args.search_solutions < args.max_solutions\n    ):\n        p.error(\"--max-solutions must not exceed --search-solutions\")\n\n    out = run(\n        m=dynmat.from_path(args.DYNMAT),\n        dense=args.dense,\n        shift_invert_attempts=args.shift_invert_attempts,\n        shift_invert_ncv=args.shift_invert_ncv,\n        plain_ncv=args.plain_ncv,\n        max_solutions=args.max_solutions,\n        use_fallback=args.use_fallback,\n        search_solutions=args.search_solutions,\n    )\n    eigensols.to_path(args.output, out)\n\ndef run(m: scipy.sparse.bsr_matrix,\n        dense: bool,\n        shift_invert_attempts: int,\n        shift_invert_ncv: int,\n        plain_ncv: int,\n        max_solutions: tp.Optional[int],\n        use_fallback: bool,\n        search_solutions: tp.Optional[int],\n        ):\n    \"\"\"\n    A suitable entry point from pure python code.\n    \"\"\"\n    if max_solutions is None:\n        if dense:\n            max_solutions = m.shape[0]\n        else:\n            max_solutions = DEFAULT_MAX_SOLUTIONS\n\n    if search_solutions is None:\n        search_solutions = max_solutions\n\n    # Logic for deciding when to use shift invert results\n    def inner():\n        if dense:\n            return try_dense(m, max_solutions)\n\n        if shift_invert_attempts:\n            esols = try_shift_invert(m,\n                                     max_solutions=search_solutions,\n                                     shift_invert_attempts=shift_invert_attempts,\n                                     ncv=shift_invert_ncv,\n                                     )\n            if not all(acousticness(v) > 1. - 1e-3 for v in esols[1]):\n                return esols\n\n        if use_fallback:\n            return try_regular(m,\n                               max_solutions=search_solutions,\n                               ncv=plain_ncv,\n                               )\n        else:\n            raise RuntimeError('Failed to diagonalize matrix!')\n\n    # Cutting out other solutions\n    evals, evecs = inner()\n    if not len(evals):\n        raise RuntimeError('No solutions found!')\n    return evals[:max_solutions], evecs[:max_solutions]\n\n# As an optimization, begin by using shift-invert mode, which can converge\n# in **significantly** fewer iterations than regular mode.\n# noinspection PyUnreachableCode\ndef try_shift_invert(m, *, shift_invert_attempts, max_solutions, ncv):\n    info('trace: precomputing OPinv for shift-invert')\n\n    # From what I have seen, shift_invert mode tends to find most of its\n    # solutions fairly quickly, but some may be incorrect. Furthermore, it does\n    # not always find all valid negative solutions.\n    #\n    # I fear that when incorrect solutions appear, it may compromise those found\n    # afterwards. So we make multiple calls with a small number of iterations.\n    MAX_ITER = max(30, int(10 * m.shape[0] ** (1/3)))\n\n    # A heavy computational step at the beginning of shift-invert mode is\n    # factorizing the matrix; do that ahead of time.\n    OPinv = get_OPinv(m, sigma=0, tol=TOL)\n\n    found_evals = []\n    found_evecs = []\n\n    # debug info\n    counts = []\n\n    for call_i in range(shift_invert_attempts):\n        info('trace: shift-invert call', call_i + 1)\n        (evals, evecs) = eigsh_custom(\n            m,\n            k=max_solutions,\n            maxiter=MAX_ITER,\n            sigma=0,\n            which='SA',\n            tol=TOL,\n            OPinv=OPinv,\n            ncv=ncv,\n            allow_fewer_solutions=True,\n            auto_adjust_k=True,\n            auto_adjust_ncv=True,\n        )\n        evecs = np.array(list(map(normalize, evecs)))\n\n        # a tree of counts based on direct field assignment so that static\n        # linters can catch typos. (CLion handles it very impressively!)\n        class Count:\n            def total(self): return int(self)\n            def __int__(self): return sum(map(int, self.__dict__.values()))\n\n        count = Count() # total solutions found\n        count.good = 0 # total solutions kept\n        count.bad = Count() # total solutions rejected\n        count.bad.repeat = 0 # linearly dependent with prior solutions\n        count.bad.wrong = 0  # non-eigenvector solutions\n        count.bad.ortho_bad = 0 # tried to orthogonalize, got a non-eigenvector\n        count.bad.ortho_fail = 0 # tried to orthogonalize, and failed\n\n        for (eval, ev) in zip(evals, evecs):\n            # Is it ACTUALLY an eigenvector?\n            if not is_good_esol(m, eval, ev):\n                count.bad.wrong += 1\n                continue\n\n            # Linearly dependent with existing solutions?\n            if sum(np.abs(np.vdot(ev, other))**2 for other in found_evecs) > 0.95:\n                count.bad.repeat += 1\n                continue\n\n            # Prepare it for possible insertion.\n            ortho_ev = mgs_step(ev, found_evecs)\n\n            # We didn't ruin it, did we?\n            if not is_good_esol(m, eval, ortho_ev):\n                count.bad.ortho_bad += 1\n                continue\n\n            if sum(np.abs(np.vdot(ortho_ev, other))**2 for other in found_evecs) > 1e-6:\n                count.bad.ortho_fail += 1\n                continue\n\n            # ship it\n            count.good += 1\n            found_evecs.append(ortho_ev)\n            found_evals.append(eval)\n\n        counts.append(count)\n\n    info(\" Good -- Bad (Old Wrong OrthoFail OrthoBad)\")\n    for count in counts:\n        info(\n            \" {:^4} -- {:^3} ({:^3} {:^5} {:^9} {:^8})\".format(\n                count.good,\n                count.bad.total(),\n                count.bad.repeat,\n                count.bad.wrong,\n                count.bad.ortho_fail,\n                count.bad.ortho_bad,\n            )\n        )\n\n    perm = np.argsort(found_evals)\n    evals = np.array(found_evals)[perm]\n    evecs = np.array(found_evecs)[perm]\n    for val, v in zip(evals, evecs):\n        if not is_good_esol(m, val, v):\n            np.save('bad-mat.npy', m)\n            np.save('bad-vec.npy', v)\n            assert False, \"bad evec\"\n    for i in range(len(evecs)):\n        for j in range(i):\n            if is_overlapping(evecs[i], evecs[j]):\n                np.save('bad-a.npy', evecs[i])\n                np.save('bad-b.npy', evecs[j])\n                assert False, \"overlap\"\n    return evals, evecs\n\ndef mgs_step(a, b_hats):\n    \"\"\"\n    This is the function such that\n\n    >>> def mgs(original_vecs):\n    ...     out = []\n    ...     for vec in original_vecs:\n    ...         out.append(mgs_step(vec, out))\n    ...     return out\n\n    is a correct implementation of Modified Gram Schmidt method.\n\n    Many sources present the Modified Gram Schmidt (MGS) method in a misleading\n    light by presenting it as having a different order of iteration from the\n    famously unstable Classical Gram-Schmidt (CGS) method, and suggesting that\n    the change in iteration order is the cause for MGS' improved numerical\n    stability.  More specifically, MGS is typically presented as taking each\n    vector in turn and using it to modify the vectors that come **after** it,\n    in contrast to CGS which modifies each vector based on those **prior** to\n    it. This could lead a naive reader to believe that the function `mgs_step`\n    cannot exist!\n\n    This is a complete ruse, however. The change in iteration order does not\n    change the dependency tree of floating point operations. (it merely\n    reintroduces opportunities for parallelism that would otherwise be lost\n    compared to CGS)\n\n    The ACTUAL difference between CGS and MGS is best understood by contrasting\n    their step functions. Here's what `cgs_step` would look like. Notice how\n    all dot products involve the original vector:\n\n    >>> def cgs_step(a, b_hats):\n    ...     original = a.copy()\n    ...     for b_hat in b_hats:\n    ...         a = a - par(original, b_hat)\n    ...     return normalize(a)\n\n    Contrast that with the following:\n    \"\"\"\n\n    # Yes, for all of that text, *it really is this simple.*\n    for b_hat in b_hats:\n        a = a - par(a, b_hat)\n    return normalize(a)\n\n# The part of `a` that points along `b_hat`.\ndef par(a, b_hat):\n    return np.vdot(b_hat, a) * b_hat\n\ndef acousticness(v_hat):\n    sum = np.reshape(v_hat, (-1, 3)).sum(axis=0)\n    return abs(np.vdot(sum, sum))\n\ndef normalize(v):\n    return v / np.sqrt(np.vdot(v, v))\n\ndef is_overlapping(a_hat, b_hat):\n    return abs(np.vdot(a_hat, b_hat)) > OVERLAP_THRESH\n\ndef is_good_esol(m, eval, evec):\n    assert abs(abs(np.vdot(evec, evec)) - 1) < 1e-12\n    return lazy_any([\n        lambda: acousticness(evec) > 1. - 1e-3,\n        lambda: lazy_all([\n            lambda: abs(abs(np.vdot(normalize(m @ evec), evec)) - 1.0) < 1e-2,\n            lambda: (np.abs(m @ evec - eval * evec) < TOL * 10).all(),\n        ])\n    ])\n\ndef lazy_any(it): return any(pred() for pred in it)\ndef lazy_all(it): return all(pred() for pred in it)\n\n# If shift-invert hasn't produced anything satisfactory, try regular mode.\n# From what I've seen, this always produces legitimate solutions, but generally\n# takes long to converge onto anything.\ndef try_regular(m, *, max_solutions, ncv):\n    info('trace: trying non-shift-invert')\n\n    return eigsh_custom(\n        m,\n        k=max_solutions,\n        which='SA',\n        tol=TOL,\n        ncv=ncv,\n        allow_fewer_solutions=True,\n        auto_adjust_k=True,\n        auto_adjust_ncv=True,\n    )\n\ndef try_dense(m, max_solutions: int):\n    info('trace: using dense eigensolver')\n\n    # note: order for returned eigenvalues is the same as 'SA'\n    # note: raises LinAlgError if the eigenvalue computation does not converge\n    evals, evecs = np.linalg.eigh(m.todense())\n    return evals[:max_solutions], evecs.T[:max_solutions]\n\nif __name__ == '__main__':\n    main_from_rust()\n", "meta": {"hexsha": "d0d7c0917e45049f8ecd343657ca333739310cd4", "size": 13662, "ext": "py", "lang": "Python", "max_stars_repo_path": "rsp2/src/python/rsp2/internals/scipy_eigsh/negative.py", "max_stars_repo_name": "colin-daniels/agnr-ml", "max_stars_repo_head_hexsha": "fc936cb8b6a68c37dfaf64c74796e0cf795c1bb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rsp2/src/python/rsp2/internals/scipy_eigsh/negative.py", "max_issues_repo_name": "colin-daniels/agnr-ml", "max_issues_repo_head_hexsha": "fc936cb8b6a68c37dfaf64c74796e0cf795c1bb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rsp2/src/python/rsp2/internals/scipy_eigsh/negative.py", "max_forks_repo_name": "colin-daniels/agnr-ml", "max_forks_repo_head_hexsha": "fc936cb8b6a68c37dfaf64c74796e0cf795c1bb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3023255814, "max_line_length": 94, "alphanum_fraction": 0.6125750256, "include": true, "reason": "import numpy,import scipy", "num_tokens": 3328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.29746994883293104, "lm_q1q2_score": 0.15570182441620323}}
{"text": "from ..general import tm, fmr, fsr\nfrom ..utilities.disp import disp\nimport numpy as np\nimport scipy as sci\nimport scipy.linalg as ling\nimport copy\nimport json\n\nclass SP:\n    #Conventions:\n    #Filenames:  snake_case\n    #Variables: snake_case\n    #Functions: camelCase\n    #ClassNames: CapsCase\n    #Docstring: Google\n    def __init__(self, bottom_joints, top_joints, bT, tT, leg_ext_min,\n        leg_ext_max, bottom_plate_thickness, top_plate_thickness, name):\n        \"\"\"\n        Initializes a new Stewart Platform Object\n\n        Args:\n            bottom_joints (ndarray): Bottom joint positions of the stewart platform\n            top_joints (ndarray): Top joint positions of the stewart platform\n            bT (tm): bottom plate position\n            tT (tm): top plate position\n            leg_ext_min (float): minimum leg ext limit\n            leg_ext_max (float): maximum leg ext limit\n            bottom_plate_thickness (float): bottom plate thickness\n            top_plate_thickness (float): top plate thickness\n            name (string): name of the sp\n        Returns:\n            SP: sp model object\n\n        \"\"\"\n        self.bottom_joints = np.copy(bottom_joints)\n        self.top_joints = np.copy(top_joints)\n        self.bottom_joints_init = self.bottom_joints.conj().transpose()\n        self.top_joints_init = self.top_joints.conj().transpose()\n        self.bottom_plate_pos = bT.copy()\n        self.top_plate_pos = tT.copy()\n        self.bottom_joints_space = np.zeros((3, 6))\n        self.top_joints_space = np.zeros((3, 6))\n        self.current_plate_transform_local = tm()\n\n        #Debug\n        self.leg_ext_safety = .001\n        self.debug = 0\n\n        #Physical Parameters\n        self.bottom_plate_thickness = bottom_plate_thickness\n        self.top_plate_thickness = top_plate_thickness\n        if leg_ext_min == 0:\n            self.leg_ext_min = 0\n            self.leg_ext_max = 2\n        self.leg_ext_min = leg_ext_min\n        self.leg_ext_max = leg_ext_max\n\n        #Reserve Val\n        self.nominal_height = fsr.distance(bT, tT)\n        self.nominal_plate_transform = tm([0, 0, self.nominal_height, 0, 0, 0])\n\n        #Drawing Characteristics\n        self.outer_top_radius = 0\n        self.outer_bottom_radius = 0\n        self.act_shaft_radius = 0\n        self.act_motor_radius = 0\n\n        #Empty array indicates these values haven't been populated yet\n        self.leg_forces =  np.zeros(1)\n        self.top_plate_wrench =  np.zeros(1)\n        self.bottom_plate_wrench =  np.zeros(1)\n\n        #Mass values from bottom mass, top mass, and actuator portion masses can be set directly.\n        self.bottom_plate_mass = 0\n        self.top_plate_mass = 0\n        self.act_shaft_mass = 0\n        self.act_motor_mass = 0\n        self.act_shaft_newton_force = 0\n        self.act_motor_newton_force = 0\n        self.top_plate_newton_force = 0\n        self.bottom_plate_newton_force = 0\n        self.grav = 9.81\n        self.dir = np.array([0, 0, -1])\n        self.act_shaft_grav_center = 0\n        self.act_motor_grav_center = 0\n        self.force_limit= 0\n\n        #Tolerances and Limits\n        self.joint_deflection_max = 140/2*np.pi/180#2*np.pi/5\n        self.plate_rotation_limit = np.cos(60*np.pi/180)\n\n        #Newton Settings\n        self.tol_f = 1e-5/2\n        self.tol_a = 1e-5/2\n        self.max_iterations = 1e4\n\n        #Errors and Counts\n        self.fail_count = 0\n        self.validation_settings = [1, 0, 0, 1]\n        self.fk_mode = 1\n        self.validation_error = \"\"\n\n        self.IK(bT, tT, protect = True)\n\n        self.bottom_joint_angles_init = self.top_joints_space.T.copy()\n        self.bottom_joint_angles = self.bottom_joints_space.T.copy()\n\n        self.bottom_joint_angles_init = [None] * 6\n        self.bottom_joint_angles = [None] * 6\n        for i in range(6):\n            self.bottom_joint_angles_init[i] = fsr.globalToLocal(self.getBottomT(),\n                tm([self.top_joints_space.T[i][0], self.top_joints_space.T[i][1],\n                self.top_joints_space.T[i][2], 0, 0, 0]))\n            self.bottom_joint_angles[i] = fsr.globalToLocal(self.getTopT(),\n                tm([self.bottom_joints_space.T[i][0], self.bottom_joints_space.T[i][1],\n                self.bottom_joints_space.T[i][2], 0, 0, 0]))\n\n        t1 = fsr.globalToLocal(self.getTopT() @ tm([0, 0, -self.top_plate_thickness, 0, 0, 0]),\n            tm([self.top_joints_space[0, 0],\n            self.top_joints_space[1, 0],\n            self.top_joints_space[2, 0], 0, 0, 0]))\n        t2 = fsr.globalToLocal(self.getTopT() @ tm([0, 0, -self.top_plate_thickness, 0, 0, 0]),\n            tm([self.top_joints_space[0, 2],\n            self.top_joints_space[1, 2],\n            self.top_joints_space[2, 2], 0, 0, 0]))\n        t3 = fsr.globalToLocal(self.getTopT() @ tm([0, 0, -self.top_plate_thickness, 0, 0, 0]),\n            tm([self.top_joints_space[0, 4],\n            self.top_joints_space[1, 4],\n            self.top_joints_space[2, 4], 0, 0, 0]))\n        self.reorients = [t1, t2, t3]\n\n\n        #Compatibility\n        self.plate_thickness_avg = (self.top_plate_thickness + self.bottom_plate_thickness) / 2\n        self.nominal_plate_transform = tm([0, 0, self.plate_thickness_avg, 0, 0, 0])\n\n        #Validation Settings\n\n\n    \"\"\"\n       _____      _   _                                     _    _____      _   _\n      / ____|    | | | |                    /\\             | |  / ____|    | | | |\n     | |  __  ___| |_| |_ ___ _ __ ___     /  \\   _ __   __| | | (___   ___| |_| |_ ___ _ __ ___\n     | | |_ |/ _ \\ __| __/ _ \\ '__/ __|   / /\\ \\ | '_ \\ / _` |  \\___ \\ / _ \\ __| __/ _ \\ '__/ __|\n     | |__| |  __/ |_| ||  __/ |  \\__ \\  / ____ \\| | | | (_| |  ____) |  __/ |_| ||  __/ |  \\__ \\\n      \\_____|\\___|\\__|\\__\\___|_|  |___/ /_/    \\_\\_| |_|\\__,_| |_____/ \\___|\\__|\\__\\___|_|  |___/\n\n    \"\"\"\n    def setMasses(self, plate_mass_general, act_shaft_mass,\n        act_motor_mass, grav=9.81, top_plate_mass=0):\n        \"\"\"\n        Set masses for each SP in the Assembler, note that because central platforms\n        share plates, these weights are halved with respect to end plates\n        Args:\n            plate_mass_general (float): mass of bottom plate (both if top is not specified) (kg)\n            act_shaft_mass (float): mass of actuator shaft (kg)\n            act_motor_mass (float): mass of actuator motor (kg)\n            grav (float):  [Optional, default 9.81] acceleration due to gravity\n            top_plate_mass (float): [Optional, default 0] top plate mass (kg)\n        \"\"\"\n        self.bottom_plate_mass = plate_mass_general\n        if top_plate_mass != 0:\n            self.top_plate_mass = top_plate_mass\n        else:\n            self.top_plate_mass = plate_mass_general\n        self.setGrav(grav)\n        self.act_shaft_mass = act_shaft_mass\n        self.act_motor_mass = act_motor_mass\n        self.act_motor_newton_force = self.act_motor_mass * self.grav\n        self.act_shaft_newton_force = self.act_shaft_mass * self.grav\n        self.top_plate_newton_force = self.top_plate_mass * self.grav\n        self.bottom_plate_newton_force = self.bottom_plate_mass * self.grav\n\n    def setGrav(self, grav=9.81):\n        \"\"\"\n        Sets Gravity\n        Args:\n            grav (float): Acceleration due to gravity\n        Returns:\n            None: None\n        \"\"\"\n        self.grav = grav\n\n    def setCOG(self, motor_grav_center, shaft_grav_center):\n        \"\"\"\n        Sets the centers of gravity for actuator components\n        Args:\n            motor_grav_center (float): distance from top of actuator to actuator shaft COG\n            shaft_grav_center (float): distance from bottom of actuator to actuator motor COG\n        \"\"\"\n        self.act_shaft_grav_center = shaft_grav_center\n        self.act_motor_grav_center = motor_grav_center\n\n    def setMaxAngleDev(self, max_angle_dev=55):\n        \"\"\"\n        Set the maximum angle joints can deflect before failure\n        Args:\n            max_angle_dev (float): maximum deflection angle (degrees)\n        \"\"\"\n        self.joint_deflection_max = max_angle_dev*np.pi/180\n\n    def setMaxPlateRotation(self, max_plate_rotation=60):\n        \"\"\"\n        Set the maximum angle the plate can rotate before failure\n\n        Args:\n            max_plate_rotation (Float): Maximum angle before plate rotation failure (degrees)\n        \"\"\"\n        self.plate_rotation_limit = np.cos(max_plate_rotation * np.pi / 180)\n\n    def setDrawingDimensions(self, outer_top_radius,\n        outer_bottom_radius, act_shaft_radius, act_motor_radius):\n        \"\"\"\n        Set Drawing Dimensions\n        Args:\n            outer_top_radius (Float): Description of parameter `outer_top_radius`.\n            outer_bottom_radius (Float): Description of parameter `outer_bottom_radius`.\n            act_shaft_radius (Float): Description of parameter `act_shaft_radius`.\n            act_motor_radius (Float): Description of parameter `act_motor_radius`.\n        \"\"\"\n        self.outer_top_radius = outer_top_radius\n        self.outer_bottom_radius = outer_bottom_radius\n        self.act_shaft_radius = act_shaft_radius\n        self.act_motor_radius = act_motor_radius\n\n    def setPlatePos(self, bottom_plate_pos, top_plate_pos):\n        \"\"\"\n        Set plate positions. called internally\n        Args:\n            bottom_plate_pos (tm): bottom plate transformation in space frame\n            top_plate_pos (tm): top plate transformation in space frame\n        \"\"\"\n        if bottom_plate_pos is not None:\n            self.bottom_plate_pos = bottom_plate_pos\n        if top_plate_pos is not None:\n            self.top_plate_pos = top_plate_pos\n\n    def getBottomJoints(self):\n        \"\"\"\n        get the bottom joint positions in space. Not orientations\n        Returns:\n            ndarray(Float): bottom joint positions\n\n        \"\"\"\n        return self.bottom_joints_space\n\n    def getTopJoints(self):\n        \"\"\"\n        get the top joint positions in space. Not orientations\n        Returns:\n            ndarray(Float): top joint positions in space\n\n        \"\"\"\n        return self.top_joints_space\n\n    def getCurrentLocalTransform(self):\n        \"\"\"\n        Get the current local transform between bottom and top plate\n        Returns:\n            tm: Top plate relative to bottom plate\n\n        \"\"\"\n        return self.current_plate_transform_local\n\n    def getLegForces(self):\n        \"\"\"\n        Return calculated leg forces\n        Returns:\n            ndarray(Float): Leg forces (N)\n        \"\"\"\n        return self.leg_forces\n\n    def getLens(self):\n        \"\"\"\n        Get Leg Lengths\n        Returns:\n            ndarray(Float): Leg Lengths\n        \"\"\"\n        return self.lengths.copy()\n\n    def getTopT(self):\n        \"\"\"\n        Return the transform of the top plate\n        Returns:\n            tm: top plate transform in space frame\n        \"\"\"\n        return self.top_plate_pos.copy()\n\n    def getBottomT(self):\n        \"\"\"\n        Return the transform of the bottom plate\n        Returns:\n            tm: bottom plate transform in space frame\n        \"\"\"\n        return self.bottom_plate_pos.copy()\n\n    def getActuatorLoc(self, num, type = 'm'):\n        \"\"\"\n        Returns the position of a specified actuator. Takes in an actuator number and a type.\n        m for actuator midpoint\n        b for actuator motor position\n        t for actuator top position\n\n        Args:\n            num (Int): number of actuator to return\n            type (Char): property of actuator to return\n\n        Returns:\n            ndarray(Float): location of desired point\n        \"\"\"\n        pos = 0\n        if type == 'm':\n            pos = np.array([(self.bottom_joints_space[0, num] + self.top_joints_space[0, num])/2,\n                (self.bottom_joints_space[1, num] + self.top_joints_space[1, num])/2,\n                (self.bottom_joints_space[2, num] + self.top_joints_space[2, num])/2])\n        bottom_act_joint = tm([self.bottom_joints_space[0, num],\n            self.bottom_joints_space[1, num], self.bottom_joints_space[2, num], 0, 0, 0])\n        top_act_joint = tm([self.top_joints_space[0, num],\n            self.top_joints_space[1, num], self.top_joints_space[2, num], 0, 0, 0])\n        if type == 'b':\n            #return fsr.adjustRotationToMidpoint(bottom_act_joint, bottom_act_joint,\n            #   top_act_joint, mode = 1) @ tm([0, 0, self.act_motor_grav_center, 0, 0, 0])\n            return fsr.getUnitVec(bottom_act_joint,\n                top_act_joint, self.act_motor_grav_center)\n        if type == 't':\n            #return fsr.adjustRotationToMidpoint(top_act_joint, top_act_joint, bottom_act_joint,\n            #   mode = 1) @ tm([0, 0, self.act_shaft_grav_center, 0, 0, 0])\n            return fsr.getUnitVec(top_act_joint,\n                bottom_act_joint, self.act_shaft_grav_center)\n        new_position = tm([pos[0], pos[1], pos[2], 0, 0, 0])\n        return new_position\n\n    def spinCustom(self, rot):\n        \"\"\"\n        Rotates plate to meet desired transform\n        Args:\n            rot (Float): rotation in radians\n        \"\"\"\n        old_base_pos = self.getBottomT()\n        self.move(tm())\n        current_top_pos = self.getTopT()\n        top_joints_copy = self.top_joints_space.copy()\n        bottom_joints_copy = self.bottom_joints_space.copy()\n        top_joints_origin_copy = self.top_joints[2, 0:6]\n        bottom_joints_origin_copy = self.bottom_joints[2, 0:6]\n        rotation_transform = tm([0, 0, 0, 0, 0, rot * np.pi / 180])\n        self.move(rotation_transform)\n        top_joints_space_new = self.top_joints_space.copy()\n        bottom_joints_space_new = self.bottom_joints_space.copy()\n        top_joints_copy[0:2, 0:6] = top_joints_space_new[0:2, 0:6]\n        bottom_joints_copy[0:2, 0:6] = bottom_joints_space_new[0:2, 0:6]\n        bottom_joints_copy[2, 0:6] = bottom_joints_origin_copy\n        top_joints_copy[2, 0:6] = top_joints_origin_copy\n        self.move(tm())\n        self.bottom_joints = bottom_joints_copy\n        self.top_joints = top_joints_copy\n        self.bottom_joints_space = bottom_joints_space_new\n        self.top_joints_space = top_joints_space_new\n        self.move(old_base_pos)\n\n\n    def IK(self, bottom_plate_pos=None, top_plate_pos=None, protect=False):\n        \"\"\"\n        Calculate inverse kinematics for given goals\n        Args:\n            bottom_plate_pos (tm): bottom plate position\n            top_plate_pos (tm): top plate position\n            protect (Bool): If true, bypass any safeties\n        Returns:\n            ndarray(Float): leg lengths\n            Bool: validity of pose\n\n        \"\"\"\n\n        bottom_plate_pos, top_plate_pos = self.bottomTopCheck(bottom_plate_pos, top_plate_pos)\n\n        leg_lengths, bottom_plate_pos, top_plate_pos = self.IKHelper(\n            bottom_plate_pos, top_plate_pos, protect)\n        #Determine current transform\n\n        self.bottom_plate_pos = bottom_plate_pos.copy()\n        self.top_plate_pos = top_plate_pos.copy()\n\n        #Ensure a valid position\n        valid = True\n        if not protect:\n            valid = self.validate()\n        return leg_lengths, valid\n\n    def IKHelper(self, bottom_plate_pos=None, top_plate_pos=None, protect=False):\n        \"\"\"\n        Calculates Inverse Kinematics for a single stewart plaform.\n        Takes in bottom plate transform, top plate transform, protection paramter, and direction\n\n        Args:\n            bottom_plate_pos (tm): bottom plate position\n            top_plate_pos (tm): top plate position\n            protect (Bool): If true, bypass any safeties\n\n        Returns:\n            ndarray(Float): lengths of legs in meters\n            tm: bottom plate position new\n            tm: top plate position new\n        \"\"\"\n        #If not supplied paramters, draw from stored values\n        bottom_plate_pos, top_plate_pos = self.bottomTopCheck(\n                bottom_plate_pos, top_plate_pos)\n        #Check for excessive rotation\n        #Poses which would be valid by leg length\n        #But would result in singularity\n        #Set bottom and top transforms\n        #self.bottom_plate_pos = bottom_plate_pos\n        #self.top_plate_pos = top_plate_pos\n\n        #Call the IK method from the JIT numba file (FASER HIGH PER)\n        #Shoulda just called it HiPer FASER. Darn.\n        self.lengths, self.bottom_joints_space, self.top_joints_space = fmr.SPIKinSpace(\n                bottom_plate_pos.gTM(),\n                top_plate_pos.gTM(),\n                self.bottom_joints,\n                self.top_joints,\n                self.bottom_joints_space,\n                 self.top_joints_space)\n        self.current_plate_transform_local = fsr.globalToLocal(\n                bottom_plate_pos, top_plate_pos)\n        return np.copy(self.lengths), bottom_plate_pos, top_plate_pos\n\n    def FK(self, L, bottom_plate_pos =None, reverse = False, protect=False):\n        \"\"\"\n        Calculate Forward Kinematics for desired leg lengths\n\n        Args:\n            L (ndarray(Float)): Goal leg lengths\n            bottom_plate_pos (tm): bottom plate position\n            reverse (Bool): Boolean to reverse action. If true, treat the top plate as stationary.\n            protect (Bool): Boolean to bypass error detection and correction. Bypass if True\n\n        Returns:\n            tm: top plate configuration\n            Bool: validity\n\n        \"\"\"\n        #FK host function, calls subfunctions depedning on the value of fk_mode\n        #return self.FKSciRaphson(L, bottom_plate_pos, reverse, protect)\n        #bottom_plate_pos, n = self._applyPlateTransform(bottom_plate_pos = bottom_plate_pos)\n        if self.fk_mode == 0:\n            bottom, top = self.FKSolve(L, bottom_plate_pos, reverse, protect)\n        else:\n            bottom, top = self.FKRaphson(L, bottom_plate_pos, reverse, protect)\n\n        if not self.continuousTranslationConstraint():\n            if self.debug:\n                disp(\"FK Resulted In Inverted Plate Alignment. Repairing...\")\n            #self.IK(top_plate_pos = self.getBottomT() @ tm([0, 0, self.nominal_height, 0, 0, 0]))\n            #self.FK(L, protect = True)\n            self.fixUpsideDown()\n        self.current_plate_transform_local = fsr.globalToLocal(bottom, top)\n        #self._undoPlateTransform(bottom, top)\n        valid = True\n        if not protect:\n            valid = self.validate()\n        return top, valid\n\n    def FKSciRaphson(self, L, bottom_plate_pos=None, reverse=False, protect=False):\n        \"\"\"\n        Use Python's Scipy module to calculate forward kinematics. Takes in length list,\n        optionally bottom position, reverse parameter, and protection\n        Args:\n            L (ndarray(Float)): Goal leg lengths\n            bottom_plate_pos (tm): bottom plate transformation in space frame\n            reverse (Bool): Boolean to reverse action. If true, treat the top plate as stationary.\n            protect (Bool): Boolean to bypass error detection and correction. Bypass if True\n\n        Returns:\n            tm: bottom plate transform\n            tm: top plate transform\n\n        \"\"\"\n        L = L.reshape((6, 1))\n        mag = lambda x : abs(x[0]) + abs(x[1])+ abs(x[2]) + abs(x[3]) + abs(x[4]) + abs(x[5])\n        fk = lambda x : mag(self.IKHelper(bottom_plate_pos, tm(x), protect = True)[0] - L).flatten()\n        jac = lambda x : (self.inverseJacobianSpace(bottom_plate_pos, tm(x)))\n        x0 = (self.getBottomT() @ self.nominal_plate_transform).TAA.flatten()\n\n        root = sci.optimize.minimize(fk, x0).x\n        #disp(root, \"ROOT\")\n        self.IK(bottom_plate_pos, tm(root), protect = True)\n        return bottom_plate_pos, tm(root)\n\n    def simplifiedRaphson(self, L, bottom_plate_pos=None, reverse=False, protect=False):\n        \"\"\"\n        Follow the method in the Parallel Robotics Textbook\n\n        Args:\n            L (ndarray(Float)): Goal leg lengths\n            bottom_plate_pos (tm): bottom plate transformation in space frame\n            reverse (Bool): Boolean to reverse action. If true, treat the top plate as stationary.\n            protect (Bool): Boolean to bypass error detection and correction. Bypass if True\n\n        Returns:\n            tm: top plate transform\n        \"\"\"\n        tol_f = 1e-4;\n        tol_a = 1e-4;\n        #iteration limits\n        max_iterations = 1e4\n\n        if bottom_plate_pos == None:\n            bottom_plate_pos = self.bottom_plate_pos\n\n        x = self.getTopT().copy()\n        iter = 0\n        success = False\n        while not success and iter < max_iterations:\n            x = x + self.inverseJacobianSpace(bottom_plate_pos, x ) @ (L -\n                self.IK(top_plate_pos = x, protect = protect))\n            x.angleMod()\n            #disp(x)\n            if np.all(abs(x[0:3]) < tol_f) and np.all(abs(x[3:6]) < tol_a):\n                success = True\n            iter+=1\n\n        if iter == max_iterations:\n            print(\"Failed to Converge\")\n\n        return tm(x)\n\n\n\n    def FKSolve(self, L, bottom_plate_pos=None, reverse=False, protect=False):\n        \"\"\"\n        Older version of python solver, no jacobian used. Takes in length list,\n        optionally bottom position, reverse parameter, and protection\n\n        Args:\n            L (ndarray(Float)): Goal leg lengths\n            bottom_plate_pos (tm): bottom plate transformation in space frame\n            reverse (Bool): Boolean to reverse action. If true, treat the top plate as stationary.\n            protect (Bool): Boolean to bypass error detection and correction. Bypass if True\n\n        Returns:\n            tm: bottom plate transform\n            tm: top plate transform\n        \"\"\"\n        #Do SPFK with scipy inbuilt solvers. Way less speedy o\n        #Or accurate than Raphson, but much simpler to look at\n        L = L.reshape((6, 1))\n        self.lengths = L.reshape((6, 1)).copy()\n        #jac = lambda x : self.inverseJacobianSpace(top_plate_pos = x)\n\n        #Slightly different if the platform is supposed to be \"reversed\"\n        if reverse:\n            if bottom_plate_pos == None:\n                top_plate_pos = self.getTopT()\n            else:\n                top_plate_pos = bottom_plate_pos\n            fk = lambda x : (self.IK(tm(x), top_plate_pos, protect = True) - L).reshape((6))\n            sol = tm(sci.optimize.fsolve(fk, self.getTopT().gTAA()))\n            #self.top_plate_pos = bottom_plate_pos\n        else:\n            #General calls will go here.\n            if bottom_plate_pos == None:\n                #If no bottom pose is supplied, use the last known.\n                bottom_plate_pos = self.getBottomT()\n            #Find top pose that produces the desired leg lengths.\n            fk = lambda x : (self.IKHelper(bottom_plate_pos, tm(x),\n                protect = True)[0] - L).reshape((6))\n            sol = tm(sci.optimize.fsolve(fk, self.getTopT().TAA))\n            #self.bottom_plate_pos = bottom_plate_pos\n\n        #If not \"Protected\" from recursion, call IK.\n        if not protect:\n            self.IK(protect = True)\n        return bottom_plate_pos, sol\n\n\n    def FKRaphson(self, L, bottom_plate_pos =None, reverse=False, protect=False):\n        \"\"\"\n        FK Solver\n        Adapted from the work done by\n        #http://jak-o-shadows.github.io/electronics/stewart-gough/stewart-gough.html\n        Args:\n            L (ndarray(Float)): Goal leg lengths\n            bottom_plate_pos (tm): bottom plate transformation in space frame\n            reverse (Bool): Boolean to reverse action. If true, treat the top plate as stationary.\n            protect (Bool): Boolean to bypass error detection and correction. Bypass if True\n\n        Returns:\n            tm: bottom plate transform\n            tm: top plate transform\n        \"\"\"\n        if self.debug:\n            disp(\"Starting Raphson FK\")\n        #^Look here for the original code and paper describing how this works.\n        if bottom_plate_pos == None:\n            bottom_plate_pos = self.getBottomT()\n        success = True\n        L = L.reshape((6))\n        self.lengths = L.reshape((6, 1)).copy()\n\n        bottom_plate_pos_backup = bottom_plate_pos.copy()\n            # @ tm([0, 0, self.bottom_plate_thickness, 0, 0, 0])\n        bottom_plate_pos = np.eye(4)\n        #bottom_plate_pos = bottom_plate_pos_backup.copy()\n        #newton-raphson tolerances\n        #iteration limits\n        iteration = 0\n\n        #Initial Guess Position\n        #a = fsr.TMtoTAA(bottom_plate_pos @\n        #   fsr.TM([0, 0, self.nominal_height, 0, 0, 0])).reshape((6))\n        #disp(a, \"Attempt\")\n        try:\n            #ap = (fsr.localToGlobal(tm([0, 0, self.nominal_height, 0, 0, 0]), tm()))\n            ap = (fsr.localToGlobal(self.current_plate_transform_local, tm())).gTAA().reshape((6))\n            a = np.zeros((6))\n            for i in range(6):\n                a[i] = ap[i]\n\n            #Call the actual algorithm from the high performance faser library\n            #Pass in initial lengths, guess, bottom and top plate positions,\n            #max iterations, tolerances, and minimum leg lengths\n            a, iteration = fmr.SPFKinSpaceR(bottom_plate_pos, L, a,\n                self.bottom_joints_init, self.top_joints_init,\n                self.max_iterations, self.tol_f, self.tol_a, self.leg_ext_min)\n\n            #If the algorithm failed, try again, but this time set initial position to neutral\n            if iteration == self.max_iterations:\n\n                a = np.zeros((6))\n                a[2] = self.nominal_height\n                a, iteration = fmr.SPFKinSpaceR(bottom_plate_pos, L, a,\n                    self.bottom_joints_init, self.top_joints_init,\n                    self.max_iterations, self.tol_f, self.tol_a, self.leg_ext_min)\n                if iteration == self.max_iterations:\n                    if self.debug:\n                        print(\"Raphson Failed to Converge\")\n                    self.fail_count += .1\n                    self.IK(bottom_plate_pos_backup,\n                        bottom_plate_pos_backup @ self.nominal_plate_transform, protect = True)\n                    return self.getBottomT(), self.getTopT()\n\n            #Otherwise return the calculated end effector position\n            #coords =tm(bottom_plate_pos_backup @ fsr.TAAtoTM(a.reshape((6, 1))))\n            coords = bottom_plate_pos_backup @ tm(a)\n            # @ tm([0, 0, self.top_plate_thickness, 0, 0, 0])\n\n            #Disabling these cause unknown issues so far.\n            #self.bottom_plate_pos = bottom_plate_pos_backup\n            #self.top_plate_pos = coords\n\n\n            self.IKHelper(bottom_plate_pos_backup, coords, protect = True)\n            self.bottom_plate_pos = bottom_plate_pos_backup\n            #@ tm([0, 0, self.bottom_plate_thickness, 0, 0, 0])\n            self.top_plate_pos = coords #@ tm([0, 0, self.top_plate_thickness, 0, 0, 0])\n            if self.debug:\n                disp(\"Returning from Raphson FK\")\n            return bottom_plate_pos_backup, tm(coords)\n        except Exception as e:\n\n            if self.debug:\n                disp(\"Raphson FK Failed due to: \" + str(e))\n            self.fail_count+=1\n            return self.FKSciRaphson(L, bottom_plate_pos_backup, reverse, protect)\n\n\n    def lambdaTopPlateReorientation(self, stopt):\n        \"\"\"\n        Only used as an assistance function for fixing plate alignment\n\n        Args:\n            stopt (tm): top transform in space frame.\n\n        Returns:\n            ndarray(Float): distances array\n\n        \"\"\"\n        reorient_helper_1 = fsr.localToGlobal(stopt, self.reorients[0])\n        reorient_helper_2 = fsr.localToGlobal(stopt, self.reorients[1])\n        reorient_helper_3 = fsr.localToGlobal(stopt, self.reorients[2])\n\n        d1 = fsr.distance(reorient_helper_1,\n            tm([self.top_joints_space[0, 0],\n            self.top_joints_space[1, 0],\n            self.top_joints_space[2, 0], 0, 0, 0]))\n        d2 = fsr.distance(reorient_helper_2,\n            tm([self.top_joints_space[0, 2],\n            self.top_joints_space[1, 2],\n            self.top_joints_space[2, 2], 0, 0, 0]))\n        d3 = fsr.distance(reorient_helper_3,\n            tm([self.top_joints_space[0, 4],\n            self.top_joints_space[1, 4],\n            self.top_joints_space[2, 4], 0, 0, 0]))\n        return np.array([d1 , d2 , d3])\n\n    def reorientTopPlate(self):\n        \"\"\"\n        Subfunction of fixUpsideDown,\n        responsible for orienting the top plate transform after mirroring\n        \"\"\"\n        top_true = self.getTopT() @ tm([0, 0, -self.top_plate_thickness, 0, 0, 0])\n        res = lambda x : self.lambdaTopPlateReorientation(\n            tm([top_true[0], top_true[1], top_true[2], x[0], x[1], x[2]]))\n        x_init = self.getTopT()[3:6].flatten()\n        solution = sci.optimize.fsolve(res, x_init)\n        top_true[3:6] = solution\n        self.top_plate_pos = top_true @ tm([0, 0, self.top_plate_thickness, 0, 0, 0])\n        #disp(self.lambdaTopPlateReorientation(self.getTopT() @\n        #   tm([0, 0, -self.top_plate_thickness, 0, 0, 0])))\n\n\n    def fixUpsideDown(self):\n        \"\"\"\n        In situations where the top plate is inverted underneath\n        the bottom plate, yet lengths are valid,\n        This function can be used to mirror all the joint locations and \"fix\" the resultant problem\n        \"\"\"\n        for num in range(6):\n            #reversable = fsr.globalToLocal(tm([self.top_joints_space[0, num],\n            #    self.top_joints_space[1, num], self.top_joints_space[2, num], 0, 0, 0]),\n            #    tm([self.bottom_joints_space[0, num],\n            #    self.bottom_joints_space[1, num],\n            #    self.bottom_joints_space[2, num], 0, 0, 0]))\n            #newTJ = tm([self.bottom_joints_space[0, num],\n            #    self.bottom_joints_space[1, num],\n            #    self.bottom_joints_space[2, num], 0, 0, 0]) @ reversable\n            newTJ = fsr.mirror(self.getBottomT() @\n                tm([0, 0, -self.bottom_plate_thickness, 0, 0, 0]),\n                tm([self.top_joints_space[0, num],\n                self.top_joints_space[1, num],\n                self.top_joints_space[2, num], 0, 0, 0]))\n            self.top_joints_space[0, num] = newTJ[0]\n            self.top_joints_space[1, num] = newTJ[1]\n            self.top_joints_space[2, num] = newTJ[2]\n            self.lengths[num] = fsr.distance(\n                self.top_joints_space[:, num], self.bottom_joints_space[:, num])\n        top_true = fsr.mirror(self.getBottomT() @ tm([0, 0, -self.bottom_plate_thickness, 0, 0, 0]),\n            self.getTopT() @ tm([0, 0, -self.top_plate_thickness, 0, 0, 0]))\n        top_true[3:6] = self.getTopT()[3:6] * -1\n        self.top_plate_pos = top_true @ tm([0, 0, self.top_plate_thickness, 0, 0, 0])\n        self.reorientTopPlate()\n\n    def validateLegs(self, valid = True, donothing = False):\n        \"\"\"\n        Validates leg lengths against leg minimums and maximums\n        Args:\n            valid (Bool): whether to start the validator with an assumption of prior validity\n            donothing (Bool): If set to true, even if an invalid configuration is detected,\n                will not attempt to correct it\n\n        Returns:\n            Bool: Validity of configuration\n\n        \"\"\"\n        if self.validation_settings[0]:\n            temp_valid = self.legLengthConstraint()\n            valid = valid and temp_valid\n            if not temp_valid:\n                self.validation_error += \"Leg Length Constraint Violated \"\n            if not temp_valid and not donothing:\n                if self.debug:\n                    disp(\"Executing Length Corrective Action...\")\n                self.lengthCorrectiveAction()\n                valid = self.validate(True, 1)\n        return valid\n\n    def validateContinuousTranslation(self, valid=True, donothing = False):\n        \"\"\"\n        Ensures that the top plate is always locally above the bottom plate\n        Args:\n            valid (Bool): whether to start the validator with an assumption of prior validity\n            donothing (Bool): If set to true, even if an invalid configuration is detected,\n                will not attempt to correct it\n\n        Returns:\n            Bool: Validity of configuration\n\n        \"\"\"\n        if self.validation_settings[1]:\n            temp_valid = self.continuousTranslationConstraint()\n            valid = valid and temp_valid\n            if not temp_valid:\n                self.validation_error += \"Platform Inversion Constraint Violated \"\n            if not temp_valid and not donothing:\n                if self.debug:\n                    disp(\"Executing Continuous Translation Corrective Action...\")\n                self.continuousTranslationCorrectiveAction()\n                valid = self.validate(True, 2)\n        return valid\n    def validateInteriorAngles(self, valid = True, donothing = False):\n        \"\"\"\n        Ensures that interior angles do not violate angular limits\n        Args:\n            valid (Bool): whether to start the validator with an assumption of prior validity\n            donothing (Bool): If set to true, even if an invalid configuration is detected,\n                will not attempt to correct it\n\n        Returns:\n            Bool: Validity of configuration\n\n        \"\"\"\n        if self.validation_settings[2]:\n            temp_valid = self.interiorAnglesConstraint()\n            valid = valid and temp_valid\n            if not temp_valid:\n                self.validation_error += \"Interior Angles Constraint Violated \"\n            if not temp_valid and not donothing:\n                if self.debug:\n                    disp(\"Executing Interior Angles Corrective Action...\")\n                self.IK(self.getBottomT(), self.getBottomT() @\n                    self.nominal_plate_transform, protect = True)\n                valid = self.validate(True, 3)\n        return valid\n\n    def validatePlateRotation(self, valid = True, donothing = False):\n        \"\"\"\n        Ensures plate rotation does not validate limits\n        Args:\n            valid (Bool): whether to start the validator with an assumption of prior validity\n            donothing (Bool): If set to true, even if an invalid configuration is detected,\n                will not attempt to correct it\n\n        Returns:\n            Bool: Validity of configuration\n\n        \"\"\"\n        if self.validation_settings[3]:\n            temp_valid = self.plateRotationConstraint()\n            valid = valid and temp_valid\n            if not temp_valid:\n                self.validation_error += \"Plate Tilt/Rotate Constraint Violated \"\n            if not temp_valid and not donothing:\n                if self.debug:\n                    disp(\"Executing Plate Rotation Corrective Action By Resetting Platform\")\n                #disp(self.nominal_plate_transform)\n                self.IK(self.getBottomT(),(self.getBottomT() @\n                    self.nominal_plate_transform), protect = True)\n                valid = self.validate(True, 4)\n        return valid\n\n    def validate(self, donothing = False, validation_limit = 4):\n        \"\"\"\n        Validate the current configuration of the stewart platform\n        Args:\n            donothing (Bool): If set to true, even if an invalid configuration is detected,\n                will not attempt to correct it\n            validation_limit (Int): Description of parameter `validation_limit`.\n\n        Returns:\n            Bool: Validity of configuration\n\n        \"\"\"\n        valid = True #innocent until proven INVALID\n        #if self.debug:\n        #    disp(\"Validating\")\n        #First check to make sure leg lengths are not exceeding limit points\n        if fsr.distance(self.getTopT(), self.getBottomT()) > 2 * self.nominal_height:\n            valid = False\n\n        if validation_limit > 0: valid = self.validateLegs(valid, donothing)\n        if validation_limit > 1: valid = self.validateContinuousTranslation(valid, donothing)\n        if validation_limit > 2: valid = self.validateInteriorAngles(valid, donothing)\n        if validation_limit > 3: valid = self.validatePlateRotation(valid, donothing)\n\n        if valid:\n            self.validation_error = \"\"\n\n        return valid\n\n    def plateRotationConstraint(self):\n        \"\"\"\n        Constraint for plate rotations. Assesses validity\n        Returns:\n            Bool: Validity of configuration\n\n        \"\"\"\n        valid = True\n        for i in range(3):\n            if self.current_plate_transform_local.gTM()[i, i] <= self.plate_rotation_limit - .0001:\n                if self.debug:\n                    disp(self.current_plate_transform_local.gTM(), \"Erroneous TM\")\n                    print([self.current_plate_transform_local.gTM()[i, i],\n                        self.plate_rotation_limit])\n                valid = False\n        return valid\n\n    def legLengthConstraint(self):\n        \"\"\"\n        Evaluate Leg Length Limitations of Stewart Platform\n        Returns:\n            Bool: Validity of configuration\n\n        \"\"\"\n        valid = True\n        if(np.any(self.lengths < self.leg_ext_min) or np.any(self.lengths > self.leg_ext_max)):\n            valid = False\n        return valid\n\n    def rescaleLegLengths(self, current_leg_min, current_leg_max):\n        \"\"\"\n        Rescale leg lengths to meet minimums\n        Args:\n            current_leg_min (Float): current minimum leg length (may be invalid)\n            current_leg_max (Float): current maximum leg length (may be invalid)\n        \"\"\"\n\n        for i in range(6):\n            self.lengths[i] = ((self.lengths[i]-current_leg_min)/\n                (current_leg_max-current_leg_min) *\n                (min(self.leg_ext_max, current_leg_max) -\n                max(self.leg_ext_min, current_leg_min)) +\n                max(self.leg_ext_min, current_leg_min))\n\n    def addLegsToMinimum(self, current_leg_min, current_leg_max):\n        \"\"\"\n        Adds the difference to the leg below minimum to preserve end effector orientation\n        Args:\n            current_leg_min (Float):  current minimum leg length (may be invalid)\n            current_leg_max (Float): current maximum leg length (may be invalid)\n        \"\"\"\n        boostamt = ((self.leg_ext_min-current_leg_min)+self.leg_ext_safety)\n        if self.debug:\n            print(\"Boost Amount: \" + str(boostamt))\n        self.lengths += boostamt\n\n    def subLegsToMaximum(self, current_leg_min, current_leg_max):\n        \"\"\"\n        Subtracts the difference to the leg above maximum to preserve end effector orientation\n        Args:\n            current_leg_min (Float):  current minimum leg length (may be invalid)\n            current_leg_max (Float): current maximum leg length (may be invalid)\n        \"\"\"\n        #print([current_leg_max, self.leg_ext_max, current_leg_min,\n        #    self.leg_ext_min, current_leg_max -\n        #    (current_leg_max - self.leg_ext_max + self.leg_ext_safety)])\n        self.lengths -= ((current_leg_max - self.leg_ext_max)+self.leg_ext_safety)\n        #print(self.lengths)\n    def lengthCorrectiveAction(self):\n        \"\"\"\n        Make an attempt to correct leg lengths that are out of bounds.\n        Will frequently result in a home-like position\n        \"\"\"\n        if self.debug:\n            disp(self.lengths, \"Lengths Pre Correction\")\n            disp(self.lengths[np.where(self.lengths > self.leg_ext_max)], \"over max\")\n            disp(self.lengths[np.where(self.lengths < self.leg_ext_min)], \"below min\")\n\n        current_leg_min = min(self.lengths.flatten())\n        current_leg_max = max(self.lengths.flatten())\n\n        #for i in range(6):\n        #    self.lengths[i] = ((self.lengths[i]-current_leg_min)/\n        #    (current_leg_max-current_leg_min) *\n        #    (min(self.leg_ext_max, current_leg_max) -\n        #    max(self.leg_ext_min, current_leg_min)) +\n        #    max(self.leg_ext_min, current_leg_min))\n        if current_leg_min < self.leg_ext_min and current_leg_max > self.leg_ext_max:\n            self.rescaleLegLengths(current_leg_min, current_leg_max)\n            self.validation_error+= \" CMethod: Rescale, \"\n        elif (current_leg_min < self.leg_ext_min and\n            current_leg_max + (self.leg_ext_min - current_leg_min) +\n            self.leg_ext_safety < self.leg_ext_max):\n            self.addLegsToMinimum(current_leg_min, current_leg_max)\n            self.validation_error+= \" CMethod: Boost, \"\n        elif (current_leg_max > self.leg_ext_max and\n            current_leg_min - (current_leg_max - self.leg_ext_max) -\n            self.leg_ext_safety > self.leg_ext_min):\n            self.validation_error+= \" CMethod: Subract, \"\n            self.subLegsToMaximum(current_leg_min, current_leg_max)\n        else:\n            self.rescaleLegLengths(current_leg_min, current_leg_max)\n            self.validation_error+= \" CMethod: Unknown Rescale, \"\n\n        #self.lengths[np.where(self.lengths > self.leg_ext_max)] = self.leg_ext_max\n        #self.lengths[np.where(self.lengths < self.leg_ext_min)] = self.leg_ext_min\n        if self.debug:\n            disp(self.lengths, \"Corrected Lengths\")\n        #disp(\"HEre's what happened\")\n        self.FK(self.lengths.copy(), protect = True)\n        #print(self.lengths)\n\n    def continuousTranslationConstraint(self):\n        \"\"\"\n        Ensure that the plate is above the prior\n\n        Returns:\n            Bool: Validity at configuration\n\n        \"\"\"\n        valid = True\n        bot = self.getBottomT()\n        for i in range(6):\n            if fsr.globalToLocal(self.getBottomT(), self.getTopT())[2] < 0:\n                valid = False\n        return valid\n\n    def continuousTranslationCorrectiveAction(self):\n        \"\"\"\n        Resets to home position\n        \"\"\"\n        self.IK(top_plate_pos = self.getBottomT() @ self.nominal_plate_transform, protect = True)\n\n    def interiorAnglesConstraint(self):\n        \"\"\"\n        Ensures no invalid internal angles\n        Returns:\n            Bool: Validity at configuration\n        \"\"\"\n        angles = abs(self.getJointAnglesFromNorm())\n        if(np.any(np.isnan(angles))):\n            return False\n        if(np.any(angles > self.joint_deflection_max)):\n            return False\n        return True\n\n    def getJointAnglesFromNorm(self):\n        \"\"\"\n        Returns the angular deviation of each angle socket from its nominal position in radians\n\n        Returns:\n            ndarray(Float): Angular deviation from home of each joint socket\n\n        \"\"\"\n        delta_angles_top = np.zeros((6))\n        delta_angles_bottom = np.zeros((6))\n        bottom_plate_transform = self.getBottomT()\n        top_plate_transform = self.getTopT()\n        for i in range(6):\n\n                top_joint_i = tm([\n                    self.top_joints_space.T[i][0],\n                    self.top_joints_space.T[i][1],\n                    self.top_joints_space.T[i][2],\n                    top_plate_transform[3],\n                    top_plate_transform[4],\n                    top_plate_transform[5]])\n                bottom_joint_i = tm([\n                    self.bottom_joints_space.T[i][0],\n                    self.bottom_joints_space.T[i][1],\n                    self.bottom_joints_space.T[i][2],\n                    bottom_plate_transform[3],\n                    bottom_plate_transform[4],\n                    bottom_plate_transform[5]])\n\n                #We have the relative positions to the top plate\n                #   of the bottom joints (bottom angles) in home pose\n                #We have the relative positions to the bottom plate of\n                #   the top joints (bottom_joint_angles_init) in home pose\n                bottom_to_top_local_home = self.bottom_joint_angles_init[i].copy()\n                top_to_bottom_local_home = self.bottom_joint_angles[i].copy()\n\n                #We acquire the current relative (local positions of each)\n                bottom_to_top_local = fsr.globalToLocal(self.getBottomT(), top_joint_i)\n                top_to_bottom_local = fsr.globalToLocal(self.getTopT(), bottom_joint_i)\n\n                #We acquire the base positions of each joint\n                bottom_to_bottom_local = fsr.globalToLocal(self.getBottomT(), bottom_joint_i)\n                top_to_top_local = fsr.globalToLocal(self.getTopT(), top_joint_i)\n\n                delta_angles_bottom[i] = fsr.angleBetween(\n                    bottom_to_top_local,\n                    bottom_to_bottom_local,\n                    bottom_to_top_local_home)\n                delta_angles_top[i] = fsr.angleBetween(\n                    top_to_bottom_local,\n                    top_to_top_local,\n                    top_to_bottom_local_home)\n\n            #DeltAnglesA are the Angles From Norm Bottom\n            #DeltAnglesB are the Angles from Norm TOp\n        return np.hstack((delta_angles_bottom, delta_angles_top))\n\n    def getJointAnglesFromVertical(self):\n        \"\"\"\n        Calculate joint angles from vertical at each joint\n        Returns:\n            ndarray(Float): top joints from vertical (downward)\n            ndarray(Float): bottom joints from vertical (upward)\n\n        \"\"\"\n        top_down = np.zeros((6))\n        bottom_up = np.zeros((6))\n        for i in range(6):\n            top_joints_temp = self.top_joints_space[:, i].copy().flatten()\n            top_joints_temp[2] = 0\n            bottom_joints_temp = self.bottom_joints_space[:, i].copy().flatten()\n            bottom_joints_temp[2] = bottom_joints_temp[2] + 1\n            angle = fsr.angleBetween(\n                self.bottom_joints_space[:, i],\n                self.top_joints_space[:, i],\n                top_joints_temp)\n            angle_up = fsr.angleBetween(\n                self.top_joints_space[:, i],\n                self.bottom_joints_space[:, i],\n                bottom_joints_temp)\n            top_down[i] = angle\n            bottom_up[i] = angle_up\n        return top_down, bottom_up\n\n    \"\"\"\n      ______                                        _   _____                              _\n     |  ____|                                      | | |  __ \\                            (_)\n     | |__ ___  _ __ ___ ___  ___    __ _ _ __   __| | | |  | |_   _ _ __   __ _ _ __ ___  _  ___ ___\n     |  __/ _ \\| '__/ __/ _ \\/ __|  / _` | '_ \\ / _` | | |  | | | | | '_ \\ / _` | '_ ` _ \\| |/ __/ __|\n     | | | (_) | | | (_|  __/\\__ \\ | (_| | | | | (_| | | |__| | |_| | | | | (_| | | | | | | | (__\\__ \\\n     |_|  \\___/|_|  \\___\\___||___/  \\__,_|_| |_|\\__,_| |_____/ \\__, |_| |_|\\__,_|_| |_| |_|_|\\___|___/\n                                                                __/ |\n                                                               |___/\n    \"\"\"\n    def componentForces(self, tau):\n        \"\"\"\n        Calculate force components for given leg forces\n        Args:\n            tau (ndarray(Float)): force exerted through each leg in Newtons.\n\n        Returns:\n            ndarray(Float): vertical components of forces\n            ndarray(Float): horizontal components of forces\n\n        \"\"\"\n        vertical_components = np.zeros((6))\n        horizontal_components = np.zeros((6))\n        for i in range(6):\n            top_joint = self.top_joints_space[:, i].copy().flatten()\n            top_joint[2] = 0\n            angle = fsr.angleBetween(\n                self.bottom_joints_space[:, i],\n                self.top_joints_space[:, i],\n                top_joint)\n            vertical_force = tau[i] * np.sin(angle)\n            horizontal_force = tau[i] * np.cos(angle)\n            vertical_components[i] = vertical_force\n            horizontal_components[i] = horizontal_force\n        return vertical_components, horizontal_components\n\n    def bottomTopCheck(self, bottom_plate_pos, top_plate_pos):\n        \"\"\"\n        Checks to make sure that a bottom and top provided are not null\n\n        Args:\n            bottom_plate_pos (tm): bottom plate transformation in space frame\n            top_plate_pos (tm): top plate transformation in space frame\n\n        Returns:\n            tm: bottomm plate transformation in space frame\n            tm: top plate transformation in space frame\n\n        \"\"\"\n        if bottom_plate_pos == None:\n            bottom_plate_pos = self.getBottomT()\n        if top_plate_pos == None:\n            top_plate_pos = self.getTopT()\n        return bottom_plate_pos, top_plate_pos\n\n    def jacobianSpace(self, bottom_plate_pos = None, top_plate_pos = None):\n        \"\"\"\n        Calculates space jacobian for stewart platform. Takes in bottom transform and top transform\n\n        Args:\n            bottom_plate_pos (tm): bottom plate transformation in space frame\n            top_plate_pos (tm): top plate transformation in space frame\n\n        Returns:\n            ndarray(Float): Jacobian for current configuration\n\n        \"\"\"\n        #If not supplied paramters, draw from stored values\n        bottom_plate_pos, top_plate_pos = self.bottomTopCheck(bottom_plate_pos, top_plate_pos)\n        #Just invert the inverted\n        inverse_jacobian = self.inverseJacobianSpace(bottom_plate_pos, top_plate_pos)\n        return ling.pinv(inverse_jacobian)\n\n\n    def inverseJacobianSpace(self, bottom_plate_pos = None, top_plate_pos = None, protect = True):\n        \"\"\"\n        Calculates Inverse Jacobian for stewart platform. Takes in bottom and top transforms\n\n        Args:\n            bottom_plate_pos (tm): bottom plate transformation in space frame\n            top_plate_pos (tm): top plate transformation in space frame\n            protect (Bool): Boolean to bypass error detection and correction. Bypass if True\n\n        Returns:\n            ndarray(Float): Inverse Jacobian for current configuration\n\n        \"\"\"\n        #Ensure everything is kosher with the plates\n        bottom_plate_pos, top_plate_pos = self.bottomTopCheck(bottom_plate_pos, top_plate_pos)\n\n        #Store old values\n        old_bottom_plate_transform = self.getBottomT()\n        old_top_plate_transform = self.getTopT()\n\n        #Perform IK on bottom and top\n        self.IK(bottom_plate_pos, top_plate_pos, protect = protect)\n\n        #Create Jacobian\n        inverse_jacobian_transpose = np.zeros((6, 6))\n        for i in range(6):\n            #todo check sign on nim,\n            ni = fmr.Normalize(self.top_joints_space[:, i]-self.bottom_joints_space[:, i])\n             #Reverse for upward forces?\n            qi = self.bottom_joints_space[:, i]\n            col = np.hstack((np.cross(qi, ni), ni))\n            inverse_jacobian_transpose[:, i] = col\n        inverse_jacobian = inverse_jacobian_transpose.T\n\n        #Restore original Values\n        self.IK(old_bottom_plate_transform, old_top_plate_transform, protect = protect)\n        return inverse_jacobian\n\n    #Returns Top Down Jacobian instead of Bottom Up\n    def altInverseJacobianSpace(self,\n        bottom_plate_pos = None, top_plate_pos = None, protect = True):\n        \"\"\"\n        Returns top down jacobian instead of bottom up\n\n        Args:\n            bottom_plate_pos (tm): bottom plate transformation in space frame\n            top_plate_pos (tm): top plate transformation in space frame\n            protect (Bool): Boolean to bypass error detection and correction. Bypass if True\n\n        Returns:\n            ndarray(Float): top down Jacobian Space\n\n        \"\"\"\n        bottom_plate_pos, top_plate_pos = self.bottomTopCheck(bottom_plate_pos, top_plate_pos)\n        old_bottom_plate_transform = copy.copy(bottom_plate_pos)\n        old_top_plate_transform = copy.copy(top_plate_pos)\n        self.IK(bottom_plate_pos, top_plate_pos)\n        inverse_jacobian_transpose = np.zeros((6, 6))\n        for i in range(6):\n            ni = fmr.Normalize(self.bottom_joints_space[:, i]-self.top_joints_space[:, i])\n            qi = self.top_joints_space[:, i]\n            inverse_jacobian_transpose[:, i] = np.hstack((np.cross(qi, ni), ni))\n        inverse_jacobian = inverse_jacobian_transpose.conj().transpose()\n\n        self.IKHelper(old_bottom_plate_transform, old_top_plate_transform)\n\n        return inverse_jacobian\n\n    #Adds in actuator and plate forces, useful for finding forces on a full stack assembler\n    def carryMassCalc(self, twrench, protect=False):\n        \"\"\"\n        Calculates the forces on each leg given their masses,\n        masses of plates, and a wrench on the end effector.\n        Use this over Local in most cases\n        Args:\n            twrench (ndarray(Float)): input wrench for configuration\n            protect (Bool): Boolean to bypass error detection and correction. Bypass if True\n\n        Returns:\n            ndarray(Float): forces in Newtons for each leg\n\n        \"\"\"\n        wrench = twrench.copy()\n        wrench = wrench + fsr.makeWrench(self.getTopT(),\n            self.top_plate_newton_force, self.dir)\n        tau = self.measureForcesFromWrenchEE(self.getBottomT(),\n            self.getTopT(), wrench, protect = protect)\n        for i in range(6):\n            #print(self.getActuatorLoc(i, 't'))\n            wrench += fsr.makeWrench(self.getActuatorLoc(i, 't'),\n                self.act_shaft_newton_force, self.dir)\n            wrench += fsr.makeWrench(self.getActuatorLoc(i, 'b'),\n                self.act_motor_newton_force, self.dir)\n        wrench = wrench + fsr.makeWrench(self.getBottomT(),\n            self.bottom_plate_newton_force, self.dir)\n        return tau, wrench\n\n    def carryMassCalcLocal(self, twrench, protect = False):\n        \"\"\"\n        Perform force mass calculations in local frame\n        Args:\n            twrench (ndarray(Float)): input wrench for configuration\n            protect (Bool): Boolean to bypass error detection and correction. Bypass if True\n\n        Returns:\n            ndarray(Float): forces in Newtons for each leg\n\n        \"\"\"\n        #We will here assume that the wrench is in the local frame of the top platform.\n        wrench = twrench.copy()\n        wrench = wrench + fsr.makeWrench(tm(), self.top_plate_newton_force, self.dir)\n        tau = self.measureForcesAtEENew(wrench, protect = protect)\n        wrench_local_frame = fsr.transformWrenchFrame(wrench, self.getTopT(), self.getBottomT())\n\n        for i in range(6):\n            #print(self.getActuatorLoc(i, 't'))\n            #The following representations are equivalent.\n            wrench_local_frame += fsr.makeWrench(fsr.globalToLocal(self.getActuatorLoc(i, 't'),\n                self.getBottomT()), self.act_shaft_newton_force, self.dir)\n            wrench_local_frame += fsr.makeWrench(fsr.globalToLocal(self.getActuatorLoc(i, 'b'),\n                self.getBottomT()), self.act_motor_newton_force, self.dir)\n            #wrench_local_frame += fsr.transformWrenchFrame(fsr.makeWrench(tm(),\n            #    self.act_shaft_newton_force, self.dir),\n            #   self.getActuatorLoc(i, 't'), self.getBottomT())\n            #wrench_local_frame += fsr.transformWrenchFrame(fsr.makeWrench(tm(),\n            #    self.act_motor_newton_force, self.dir),\n            #   self.getActuatorLoc(i, 'b'), self.getBottomT())\n        wrench_local_frame = wrench_local_frame + fsr.makeWrench(tm(),\n            self.bottom_plate_newton_force, self.dir)\n        return tau, wrench_local_frame\n\n    def measureForcesAtEENew(self, wrench, protect = False):\n        \"\"\"\n        Measure forces based on end effector wrench\n        Args:\n            wrench (ndarray(Float)): Description of parameter `wrench`.\n            protect (Bool): Boolean to bypass error detection and correction. Bypass if True\n\n        Returns:\n            ndarray(Float): forces in Newtons for each leg\n\n        \"\"\"\n        jacobian_space = ling.pinv(\n            self.inverseJacobianSpace(self.getBottomT(), self.getTopT(), protect = protect))\n        tau = jacobian_space.T @ wrench\n        self.leg_forces = tau\n        return tau\n\n    def carryMassCalcUp(self, twrench, protect = False):\n        \"\"\"\n        Carry masses from bottom up\n        Args:\n            twrench (ndarray(Float)): input wrench for configuration\n            protect (Bool): Boolean to bypass error detection and correction. Bypass if True\n\n        Returns:\n            ndarray(Float): forces in Newtons for each leg\n            ndarray(Float): wrench to carry\n\n        \"\"\"\n        wrench = twrench.copy()\n        wrench = wrench + fsr.makeWrench(self.getBottomT(),\n            self.bottom_plate_mass * self.grav, np.array([0, 0, -1]))\n        tau = self.measureForcesFromBottomEE(\n            self.getBottomT(), self.getTopT(), wrench, protect = protect)\n        for i in range(6):\n            wrench += fsr.makeWrench(\n                self.getActuatorLoc(i, 't'), self.act_shaft_mass * self.grav, np.array([0, 0, -1]))\n            wrench += fsr.makeWrench(\n                self.getActuatorLoc(i, 'b'), self.act_motor_mass * self.grav, np.array([0, 0, -1]))\n        wrench = wrench + fsr.makeWrench(\n            self.getTopT(), self.top_plate_mass * self.grav, np.array([0, 0, -1]))\n        return tau, wrench\n\n    #Get Force wrench from the End Effector Force\n    def measureForcesFromWrenchEE(self, bottom_plate_pos = np.zeros((1)),\n        top_plate_pos = np.zeros((1)), top_plate_wrench = np.zeros((1)), protect = True):\n        \"\"\"\n        Calculates forces on legs given end effector wrench\n\n        Args:\n            bottom_plate_pos (tm): bottom plate transformation in space frame\n            top_plate_pos (tm): top plate transformation in space frame\n            top_plate_wrench (ndarray(Float)): input wrench for configuration\n            protect (Bool): Boolean to bypass error detection and correction. Bypass if True\n\n        Returns:\n            tau: forces in Newtons for each leg\n\n        \"\"\"\n        bottom_plate_pos, top_plate_pos = self.bottomTopCheck(bottom_plate_pos, top_plate_pos)\n        if top_plate_wrench.size < 6:\n            disp(\"Please Enter a Wrench\")\n        #top_wrench = fmr.Adjoint(ling.inv(top_plate_pos)).conj().transpose() @ top_plate_wrench\n        #Modern Robotics 3.95 Fb = Ad(Tba)^T * Fa\n        #top_wrench = top_plate_pos.inv().Adjoint().T @ top_plate_wrench\n        top_wrench = fsr.transformWrenchFrame(top_plate_wrench, tm(), top_plate_pos)\n        jacobian_space = ling.pinv(\n            self.inverseJacobianSpace(bottom_plate_pos, top_plate_pos, protect = protect))\n        tau = jacobian_space.T @ top_wrench\n        self.leg_forces = tau\n        return tau\n\n    def measureForcesFromBottomEE(self, bottom_plate_pos = np.zeros((1)),\n        top_plate_pos = np.zeros((1)), top_plate_wrench = np.zeros((1)), protect = True):\n        \"\"\"\n        Calculates forces on legs given end effector wrench\n\n        Args:\n            bottom_plate_pos (tm): bottom plate transformation in space frame\n            top_plate_pos (tm): top plate transformation in space frame\n            top_plate_wrench (ndarray(Float)): input wrench for configuration\n            protect (Bool): Boolean to bypass error detection and correction. Bypass if True\n\n        Returns:\n            tau: forces in Newtons for each leg\n\n        \"\"\"\n        bottom_plate_pos, top_plate_pos = self._bttomTopCheck(bottom_plate_pos, top_plate_pos)\n        if top_plate_wrench.size < 6:\n            disp(\"Please Enter a Wrench\")\n        #top_wrench = fmr.Adjoint(ling.inv(top_plate_pos)).conj().transpose() @ top_plate_wrench\n        bottom_wrench = bottom_plate_pos.inv().Adjoint().T @ top_plate_wrench\n        jacobian_space = ling.pinv(\n            self.inverseJacobianSpace(bottom_plate_pos, top_plate_pos, protect = protect))\n        tau = jacobian_space.T @ bottom_wrench\n        self.leg_forces = tau\n        return tau\n\n    def wrenchEEFromMeasuredForces(self, bottom_plate_pos, top_plate_pos, tau):\n        \"\"\"\n        Calculates wrench on end effector from leg forces\n\n        Args:\n            bottom_plate_pos (tm): bottom plate transformation in space frame\n            top_plate_pos (tm): top plate transformation in space frame\n            tau (ndarray(Float)): force exerted through each leg in Newtons.\n\n        Returns:\n            ndarray(Float): top plate wrench\n            ndarray(Float): top wrench (local)\n            ndarray(Float): jacobian\n\n        \"\"\"\n        self.leg_forces = tau\n        jacobian_space = ling.pinv(self.inverseJacobianSpace(bottom_plate_pos, top_plate_pos))\n        top_wrench = ling.inv(jacobian_space.conj().transpose()) @ tau\n        #self.top_plate_wrench = fmr.Adjoint(top_plate_pos).conj().transpose() @ top_wrench\n        self.top_plate_wrench = top_plate_pos.Adjoint().conj().transpose() @ top_wrench\n        return self.top_plate_wrench, top_wrench, jacobian_space\n\n    def wrenchBottomFromMeasuredForces(self, bottom_plate_pos, top_plate_pos, tau):\n        \"\"\"\n        Unused. Calculates wrench on the bottom plate from leg forces\n\n        Args:\n            bottom_plate_pos (tm): bottom plate transformation in space frame\n            top_plate_pos (tm): top plate transformation in space frame\n            tau (ndarray(Float)): force exerted through each leg in Newtons.\n\n        Returns:\n            ndarray(Float): bottom plate wrench\n            ndarray(Float): bottom wrench (local)\n            ndarray(Float): jacobian\n\n        \"\"\"\n        self.leg_forces = tau\n        jacobian_space = ling.pinv(self.altInverseJacobianSpace(bottom_plate_pos, top_plate_pos))\n        bottom_wrench = ling.inv(jacobian_space.conj().transpose()) @ tau\n        #self.bottom_plate_wrench = fmr.Adjoint(bottom_plate_pos).conj().transpose() @ bottom_wrench\n        self.bottom_plate_wrench = bottom_plate_pos.Adjoint().conj().transpose() @ bottom_wrench\n        return self.bottom_plate_wrench, bottom_wrench, jacobian_space\n\n    def sumActuatorWrenches(self, forces = None):\n        \"\"\"\n        Sum all actuator wrenches to produce bottom wrench\n        Args:\n            forces (ndarray(Float)): leg forces in Newtons\n\n        Returns:\n            ndarray(Float): bottom plate wrench\n\n        \"\"\"\n        if forces is None:\n            forces = self.leg_forces\n\n        wrench = fsr.makeWrench(tm(), 0, [0, 0, -1])\n        for i in range(6):\n            unit_vector = fmr.Normalize(self.bottom_joints_space[:, i]-self.top_joints_space[:, i])\n            wrench += fsr.makeWrench(self.top_joints_space[:, i], float(forces[i]), unit_vector)\n        #wrench = fsr.transformWrenchFrame(wrench, tm(), self.getTopT())\n        return wrench\n\n\n    def move(self, T, protect = False):\n        \"\"\"\n        Move entire Assembler Stack to another location and orientation\n        This function and syntax are shared between all kinematic structures.\n        Args:\n            T (tm): New base transform to move to\n            protect (Bool): Boolean to bypass error detection and correction. Bypass if True\n        \"\"\"\n        #Moves the base of the stewart platform to a new location\n\n\n        self.current_plate_transform_local = fsr.globalToLocal(self.getBottomT(), self.getTopT())\n        self.bottom_plate_pos = T.copy()\n        self.IK(\n            top_plate_pos = fsr.localToGlobal(self.getBottomT(),\n                    self.current_plate_transform_local),\n            protect = protect)\n\n    def printOutOfDateFunction(self, old_name, use_name):\n        \"\"\"\n        Prints an old function with an OOD notice\n        Args:\n            old_name (String): Description of parameter `old_name`.\n            use_name (String): Description of parameter `use_name`.\n        \"\"\"\n        print(old_name + \" is deprecated. Please use \" + use_name + \" instead.\")\n\n    def SetMasses(self, plateMass, actuatorTop, actuatorBottom, grav = 9.81, tPlateMass = 0):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"SetMasses\", \"setMasses\")\n        return self.setMasses(plateMass, actuatorTop, actuatorBottom, grav, tPlateMass)\n    def SetGrav(self, grav = 9.81):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"SetGrav\", \"setGrav\")\n        return self.setGrav(grav)\n    def SetCOG(self, motor_grav_center, shaft_grav_center):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"SetCOG\", \"setCOG\")\n        return self.setCOG(motor_grav_center, shaft_grav_center)\n    def SetAngleDev(self, MaxAngleDev = 55):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"SetAngleDev\", \"setMaxAngleDev\")\n        return self.setMaxAngleDev(MaxAngleDev)\n    def SetPlateAngleDev(self, MaxPlateDev = 60):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"SetPlateAngleDev\", \"setMaxPlateRotation\")\n        return self.setMaxPlateRotation(MaxPlateDev)\n    def SetDrawingDimensions(self, OuterTopRad, OuterBotRad, ShaftRad, MotorRad):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"SetDrawingDimensions\", \"setDrawingDimensions\")\n        return self.setDrawingDimensions( OuterTopRad, OuterBotRad, ShaftRad, MotorRad)\n    def _setPlatePos(self, bottomT, topT):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"_setPlatePos\", \"setPlatePos\")\n        return self.setPlatePos(bottomT, topT)\n    def gLens(self):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"gLens\", \"getLens\")\n        return self.getLens()\n    def gtopT(self):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"gtopT\", \"getTopT\")\n        return self.getTopT()\n    def gbottomT(self):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"gbottomT\", \"getBottomT\")\n        return self.getBottomT()\n    def GetActuatorUnit(self, p1, p2, dist):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"GetActuatorUnit\", \"fsr.getUnitVec\")\n        return fsr.getUnitVec(p1, p2, dist)\n    def SpinCustom(self, rot):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"SpinCustom\", \"spinCustom\")\n        return self.spinCustom(rot)\n    def SimplifiedRaphson(self, L, bottomT = None, reverse = False, protect = False):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"SimplifiedRaphson\", \"simplifiedRaphson\")\n        return self.simplifiedRaphson(L, bottomT, reverse, protect)\n    def LambdaRTP(self, stopt):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"LambdaRTP\", \"lambdaTopPlateReorientation\")\n        return self.lambdaTopPlateReorientation(stopt)\n    def ReorientTopPlate(self):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"ReorientTopPlate\", \"reorientTopPlate\")\n        return self.reorientTopPlate()\n    def _legLengthConstraint(self, donothing):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"_legLengthConstraint\", \"legLengthConstraint\")\n        return self.legLengthConstraint()\n    def _resclLegs(self, cMin, cMax):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"_resclLegs\", \"rescaleLegLengths\")\n        return self.rescaleLegLengths(cMin, cMax)\n    def _addLegs(self, cMin, cMax):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"_addLegs\", \"addLegsToMinimum\")\n        return self.addLegsToMinimum(cMin, cMax)\n    def _subLegs(self, cMin, cMax):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"_subLegs\", \"subLegsToMaximum\")\n        return self.subLegsToMaximum(cMin, cMax)\n    def _lengthCorrectiveAction(self):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"_lengthCorrectiveAction\", \"lengthCorrectiveAction\")\n        return self.lengthCorrectiveAction()\n    def _continuousTranslationConstraint(self):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\n            \"_continuousTranslationConstraint\", \"continuousTranslationConstraint\")\n        return self.continuousTranslationConstraint()\n    def _continuousTranslationCorrectiveAction(self):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\n            \"_continuousTranslationCorrectiveAction\", \"continuousTranslationCorrectiveAction\")\n        return self.continuousTranslationCorrectiveAction()\n    def _interiorAnglesConstraint(self):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"_interiorAnglesConstraint\", \"interiorAnglesConstraint\")\n        return self.interiorAnglesConstraint()\n    def AngleFromNorm(self):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"AngleFromNorm\", \"getJointAnglesFromNorm\")\n        return self.getJointAnglesFromNorm()\n    def AngleFromVertical(self):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"AngleFromVertical\", \"getJointAnglesFromVertical\")\n        return self.getJointAnglesFromVertical()\n    def _bottomTopCheck(self, bottomT, topT):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"_bottomTopCheck\", \"bottomTopCheck\")\n        return self.bottomTopCheck(bottomT, topT)\n    def JacobianSpace(self, bottomT = None, topT = None):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"JacobianSpace\", \"jacobianSpace\")\n        return self.jacobianSpace(bottomT, topT)\n    def InverseJacobianSpace(self, bottomT = None, topT = None, protect = True):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"InverseJacobianSpace\", \"inverseJacobianSpace\")\n        return self.inverseJacobianSpace(bottomT, topT)\n    def AltInverseJacobianSpace(self, bottomT = None, topT = None, protect = True):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"AltInverseJacobianSpace\", \"altInverseJacobianSpace\")\n        return self.altInverseJacobianSpace(bottomT, topT, protect)\n    def CarryMassCalc(self, twrench, protect = False):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"CarryMassCalc\", \"carryMassCalc\")\n        return self.carryMassCalc(twrench, protect)\n    def CarryMassCalcNew(self, twrench, protect = False):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"CarryMassCalcNew\", \"carryMassCalcLocal\")\n        return self.carryMassCalcLocal(twrench, protect)\n    def MeasureForcesAtEENew(self, wrench, protect = False):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"MeasureForcesAtEENew\", \"measureForcesAtEENew\")\n        return self.measureForcesAtEENew(wrench, protect)\n    def CarryMassCalcUp(self, twrench, protect = False):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"CarryMassCalcUp\", \"carryMassCalcUp\")\n        return self.carryMassCalcUp(twrench, protect)\n    def MeasureForcesFromWrenchEE(self, bottomT = np.zeros((1)) ,\n        topT = np.zeros((1)), topWEE = np.zeros((1)), protect = True):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"MeasureForcesFromWrenchEE\", \"measureForcesFromWrenchEE\")\n        return self.measureForcesFromWrenchEE(bottomT, topT, topWEE, protect)\n    def MeasureForcesFromBottomEE(self, bottomT = np.zeros((1)) ,\n        topT = np.zeros((1)), topWEE = np.zeros((1)), protect = True):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"MeasureForcesFromBottomEE\", \"measureForcesFromBottomEE\")\n        return self.measureForcesFromBottomEE(bottomT, topT, topWEE, protect)\n    def WrenchEEFromMeasuredForces(self, bottomT, topT, tau):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"WrenchEEFromMeasuredForces\", \"wrenchEEFromMeasuredForces\")\n        return self.wrenchEEFromMeasuredForces(bottomT, topT, tau)\n    def WrenchBottomFromMeasuredForces(self, bottomT, topT, tau):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\n            \"WrenchBottomFromMeasuredForces\", \"wrenchBottomFromMeasuredForces\")\n        return self.wrenchBottomFromMeasuredForces(bottomT, topT, tau)\n    def SumActuatorWrenches(self, forces = None):\n        \"\"\"\n        Deprecated. Don't Use\n        \"\"\"\n        self.printOutOfDateFunction(\"SumActuatorWrenches\", \"sumActuatorWrenches\")\n        return self.sumActuatorWrenches(forces)\n\ndef loadSP(fname, file_directory = \"../robot_definitions/\", baseloc = None, altRot = 1):\n    \"\"\"\n    Loads A Stewart Platform Object froma  file\n\n    Args:\n        fname (String): file name of the sp config\n        file_directory (String): optional directory, defaults to robot_defintions\n        baseloc (tm): Base location.\n        altRot (Float): alternate relative plate rotation.\n\n    Returns:\n        SP: SP object\n\n    \"\"\"\n    print(fname)\n    print(file_directory)\n    total_name = file_directory + fname\n    print(total_name)\n    with open(total_name, \"r\") as sp_file:\n        sp_data = json.load(sp_file)\n    bot_radius = sp_data[\"BottomPlate\"][\"JointRadius\"] #Radius of Ball Joint Circle in Meters\n    top_radius = sp_data[\"TopPlate\"][\"JointRadius\"]\n    bot_joint_spacing = sp_data[\"BottomPlate\"][\"JointSpacing\"] #Spacing in Degrees\n    top_joint_spacing = sp_data[\"TopPlate\"][\"JointSpacing\"]\n    bot_thickness = sp_data[\"BottomPlate\"][\"Thickness\"]\n    top_thickness = sp_data[\"TopPlate\"][\"Thickness\"]\n    outer_top_radius = sp_data[\"Drawing\"][\"TopRadius\"]\n    outer_bottom_radius = sp_data[\"Drawing\"][\"BottomRadius\"]\n    act_shaft_radius = sp_data[\"Drawing\"][\"ShaftRadius\"]\n    act_motor_radius = sp_data[\"Drawing\"][\"MotorRadius\"]\n    actuator_shaft_mass = 0\n    actuator_motor_mass = 0\n    plate_top_mass = 0\n    plate_bot_mass = 0\n    motor_grav_center = 0\n    shaft_grav_center = 0\n    name = sp_data[\"Name\"]\n    actuator_min = sp_data[\"Actuators\"][\"MinExtension\"] #meters\n    actuator_max = sp_data[\"Actuators\"][\"MaxExtension\"]\n    force_lim = sp_data[\"Actuators\"][\"ForceLimit\"]\n    max_dev = sp_data[\"Settings\"][\"MaxAngleDev\"]\n    if sp_data[\"Settings\"][\"AssignMasses\"] == 1:\n        actuator_motor_mass = sp_data[\"Actuators\"][\"MotorMass\"]\n        actuator_shaft_mass = sp_data[\"Actuators\"][\"ShaftMass\"]\n        plate_top_mass = sp_data[\"TopPlate\"][\"Mass\"]\n        plate_bot_mass = sp_data[\"BottomPlate\"][\"Mass\"]\n        if sp_data[\"Settings\"][\"InferActuatorCOG\"] == 1:\n            motor_grav_center = sp_data[\"Actuators\"][\"MotorCOGD\"]\n            shaft_grav_center = sp_data[\"Actuators\"][\"ShaftCOGD\"]\n        else:\n            inferred_cog = 1/4 * (actuator_min+actuator_max)/2\n            actuator_shaft_mass = inferred_cog\n            motor_grav_center = inferred_cog\n    if baseloc == None:\n        baseloc = tm()\n\n\n    newsp = newSP(bot_radius, top_radius, bot_joint_spacing, top_joint_spacing,\n        bot_thickness, top_thickness, actuator_shaft_mass, actuator_motor_mass, plate_top_mass,\n        plate_bot_mass, motor_grav_center, shaft_grav_center,\n        actuator_min, actuator_max, baseloc, name, altRot)\n\n    newsp.setDrawingDimensions(\n        outer_top_radius,\n        outer_bottom_radius,\n        act_shaft_radius,\n        act_motor_radius)\n    newsp.setMaxAngleDev(max_dev)\n    newsp.force_limit = force_lim\n\n    return newsp\ndef newSP(bottom_radius, top_radius, bJointSpace, tJointSpace,\n    bottom_plate_thickness, top_plate_thickness, actuator_shaft_mass,\n    actuator_motor_mass, plate_top_mass, plate_bot_mass, motor_grav_center,\n    shaft_grav_center, actuator_min, actuator_max, base_location, name, rot = 1):\n    \"\"\"\n    Builds a new SP, called usually by a constructor\n    Args:\n        bottom_radius (Float): Bottom plate Radius (m)\n        top_radius (Float): Top plate Radius (m)\n        bJointSpace (ndarray(Float)): bottom joints space locations\n        tJointSpace (ndarray(Float)): top joints space locations\n        bottom_plate_thickness (Float): bottom plate thickness (m)\n        top_plate_thickness (Float): top plate thickness (m)\n        actuator_shaft_mass (Float): Actuator shaft (moving portion) mass Kg\n        actuator_motor_mass (Float): Actuator motor (stationary portion) mass Kg\n        plate_top_mass (Float): top plate mass (Kg)\n        plate_bot_mass (Float):  bottom plate mass (Kg)\n        motor_grav_center (Float): Actuator motor inline COG distance from joint\n        shaft_grav_center (Float): Actuator shaft inline CG distance from top joint\n        actuator_min (Float): Actuator length when fully retracted\n        actuator_max (Float): Actuator length when fully extended\n        base_location (tm): Base transform\n        name (String): Name of the SP\n        rot (Float): Rotation parameter\n\n    Returns:\n        SP: SP object\n\n    \"\"\"\n\n    bottom_gap = bJointSpace / 2 * np.pi / 180\n    top_gap = tJointSpace / 2 * np.pi / 180\n\n    bottom_joint_gap = 120 * np.pi / 180 #Angle of seperation between joint clusters\n    top_joint_gap = 60 * np.pi / 180 #Offset in rotation of the top plate versus the bottom plate\n\n    bangles = np.array([\n        -bottom_gap, bottom_gap,\n        bottom_joint_gap-bottom_gap,\n        bottom_joint_gap+bottom_gap,\n        2*bottom_joint_gap-bottom_gap,\n        2*bottom_joint_gap+bottom_gap])\n    tangles = np.array([\n        -top_joint_gap+top_gap,\n        top_joint_gap-top_gap,\n        top_joint_gap+top_gap,\n        top_joint_gap+bottom_joint_gap-top_gap,\n        top_joint_gap+bottom_joint_gap+top_gap,\n        -top_joint_gap-top_gap])\n    if rot == -1:\n        tangles = np.array([\n            -bottom_gap, bottom_gap,\n            bottom_joint_gap-bottom_gap,\n            bottom_joint_gap+bottom_gap,\n            2*bottom_joint_gap-bottom_gap,\n            2*bottom_joint_gap+bottom_gap])\n        bangles = np.array([\n            -top_joint_gap+top_gap,\n            top_joint_gap-top_gap,\n            top_joint_gap+top_gap,\n            top_joint_gap+bottom_joint_gap-top_gap,\n            top_joint_gap+bottom_joint_gap+top_gap,\n            -top_joint_gap-top_gap])\n\n    S = fmr.ScrewToAxis(np.array([0.0, 0.0, 0.0]), np.array([0.0, 0.0, 1.0]), 0).reshape((6, 1))\n\n    Mb = tm(np.array([bottom_radius, 0.0, 0.0, 0.0, 0.0, 0.0]))\n     #how far from the bottom plate origin should clusters be generated\n    Mt = tm(np.array([top_radius, 0.0, 0.0, 0.0, 0.0, 0.0]))\n     #Same thing for the top\n\n    bj = np.zeros((3, 6)) #Pre allocate arrays\n    tj = np.zeros((3, 6))\n\n    for i in range(0, 6):\n        bji = fsr.transformFromTwist(bangles[i] * S) @ Mb\n        tji = fsr.transformFromTwist(tangles[i] * S) @ Mt\n        bj[0:3, i] = bji[0:3].reshape((3))\n        tj[0:3, i] = tji[0:3].reshape((3))\n        bj[2, i] = bottom_plate_thickness\n        tj[2, i] = -top_plate_thickness\n\n    bottom = base_location.copy()\n    tentative_height = midHeightEstimate(\n        actuator_min, actuator_max, bj, bottom_plate_thickness, top_plate_thickness)\n    if rot == -1:\n        tentative_height = midHeightEstimate(\n            actuator_min, actuator_max, tj, bottom_plate_thickness, top_plate_thickness)\n    top = bottom @ tm(np.array([0.0, 0.0, tentative_height, 0.0, 0.0, 0.0]))\n\n    newsp = SP(bj, tj, bottom, top,\n        actuator_min, actuator_max,\n        bottom_plate_thickness, top_plate_thickness, name)\n    newsp.setMasses(\n        plate_bot_mass,\n        actuator_shaft_mass,\n        actuator_motor_mass,\n        top_plate_mass = plate_top_mass)\n    newsp.setCOG(motor_grav_center, shaft_grav_center)\n\n    return newsp\ndef makeSP(bRad, tRad, spacing, baseT,\n    platOffset, rot = -1, plate_thickness_avg = 0, altRot = 0):\n    \"\"\"\n    Largely deprecated in favor of Loading SP objects from json\n\n    Args:\n        bRad (Float): bottom plate radius\n        tRad (Float): top plate radius\n        spacing (Float): joint spacing (deg)\n        baseT (tm):base transform\n        platOffset (Float): platform offset height\n        rot (Float): creates an invert platform if flipped\n        plate_thickness_avg (Float): plate thickness\n        altRot (Float): rotational offset\n\n    Returns:\n        SP: Stewart platform object\n\n    \"\"\"\n    gapS = spacing/2*np.pi/180 #Angle between cluster joints\n    bottom_joint_gap = 120*np.pi/180 #Angle of seperation between joint clusters\n    top_joint_gap = 60*np.pi/180 #Offset in rotation of the top plate versus the bottom plate\n    bangles = np.array([\n        -gapS,\n        gapS,\n        bottom_joint_gap-gapS,\n        bottom_joint_gap+gapS,\n        2*bottom_joint_gap-gapS,\n        2*bottom_joint_gap+gapS]) + altRot * np.pi/180\n    tangles = np.array([\n        -top_joint_gap+gapS,\n        top_joint_gap-gapS,\n        top_joint_gap+gapS,\n        top_joint_gap+bottom_joint_gap-gapS,\n        top_joint_gap+bottom_joint_gap+gapS,\n        -top_joint_gap-gapS])+ altRot * np.pi/180\n    if rot == -1:\n        tangles = np.array([\n            -gapS, gapS,\n            bottom_joint_gap-gapS,\n            bottom_joint_gap+gapS,\n            2*bottom_joint_gap-gapS,\n            2*bottom_joint_gap+gapS])+ altRot * np.pi/180\n        bangles = np.array([\n            -top_joint_gap+gapS,\n            top_joint_gap-gapS,\n            top_joint_gap+gapS,\n            top_joint_gap+bottom_joint_gap-gapS,\n            top_joint_gap+bottom_joint_gap+gapS,\n            -top_joint_gap-gapS])+ altRot * np.pi/180\n\n    disp(bangles, \"bangles\")\n    disp(tangles, \"tangles\")\n    S = fmr.ScrewToAxis(np.array([0.0, 0.0, 0.0]), np.array([0.0, 0.0, 1.0]), 0).reshape((6, 1))\n\n    Mb = tm(np.array([bRad, 0.0, 0.0, 0.0, 0.0, 0.0]))\n     #how far from the bottom plate origin should clusters be generated\n    Mt = tm(np.array([tRad, 0.0, 0.0, 0.0, 0.0, 0.0]))\n     #Same thing for the top\n\n    bj = np.zeros((3, 6)) #Pre allocate arrays\n    tj = np.zeros((3, 6))\n\n    #Generate position vectors (XYZ) for top and bottom joint locations\n    for i in range(0, 6):\n        bji = fsr.transformFromTwist(bangles[i] * S) @ Mb\n        tji = fsr.transformFromTwist(tangles[i] * S) @ Mt\n        bj[0:3, i] = bji[0:3].reshape((3))\n        tj[0:3, i] = tji[0:3].reshape((3))\n        bj[2, i] = plate_thickness_avg/2\n        tj[2, i] = -plate_thickness_avg/2\n\n    #if rot == -1:\n    #    disp(bj, \"Prechange\")\n#\n#        rotby = TAAtoTM(np.array([0, 0, 0, 0, 0, np.pi/3]))\n#        for i in range(6):\n#            bj[0:3, i] = TMtoTAA(rotby @\n#                TAAtoTM(np.array([bj[0, i], bj[1, i], bj[2, i], 0, 0, 0])))[0:3].reshape((3))\n#            tj[0:3, i] = TMtoTAA(rotby @\n#                TAAtoTM(np.array([tj[0, i], tj[1, i], tj[2, i], 0, 0, 0])))[0:3].reshape((3))\n#        disp(bj, \"postchange\")\n    bottom = baseT.copy()\n    #Generate top position at offset from the bottom position\n    top = bottom @ tm(np.array([0.0, 0.0, platOffset, 0.0, 0.0, 0.0]))\n    sp = SP(bj, tj, bottom, top, 0, 1, plate_thickness_avg, plate_thickness_avg, 'sp')\n    sp.bRad = bRad\n    sp.tRad = tRad\n\n    return sp, bottom, top\n#Helpers\ndef midHeightEstimate(leg_ext_min, leg_ext_max, bj, bth, tth):\n    \"\"\"\n    Calculates an estimate of thee resting height of a stewart plaform\n    Args:\n        leg_ext_min (float): minimum leg extension\n        leg_ext_max (float): maximum leg extension\n        bj (array(float)): bottom joints\n        bth (tm):bottom plate thickness\n        tth (tm): top plate thickness\n\n    Returns:\n        Float: Description of returned object.\n\n    \"\"\"\n    s1 = (leg_ext_min + leg_ext_max) / 2\n    d1 = fsr.distance(tm([bj[0, 0], bj[1, 0], bj[2, 0], 0, 0, 0]),\n            tm([bj[0, 1], bj[1, 1], bj[2, 1], 0, 0, 0]))\n    hest = (np.sqrt(s1 ** 2 - d1 **2)) + bth + tth\n    return hest\n", "meta": {"hexsha": "7dc754abc5e06d2bf690b2571a30cf337377e1eb", "size": 83356, "ext": "py", "lang": "Python", "max_stars_repo_path": "basic_robotics/kinematics/sp_model.py", "max_stars_repo_name": "64-B1T/basic_robotics", "max_stars_repo_head_hexsha": "699b58f50d9c571cdab114d8453153ee6aefbea7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "basic_robotics/kinematics/sp_model.py", "max_issues_repo_name": "64-B1T/basic_robotics", "max_issues_repo_head_hexsha": "699b58f50d9c571cdab114d8453153ee6aefbea7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "basic_robotics/kinematics/sp_model.py", "max_forks_repo_name": "64-B1T/basic_robotics", "max_forks_repo_head_hexsha": "699b58f50d9c571cdab114d8453153ee6aefbea7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4294234592, "max_line_length": 102, "alphanum_fraction": 0.6161284131, "include": true, "reason": "import numpy,import scipy", "num_tokens": 20024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.29746993014852224, "lm_q1q2_score": 0.15570181463640342}}
{"text": "from __future__ import print_function\nimport numpy as np\nimport os\n\ntry:\n    from .gsm import GSM\nexcept:\n    from gsm import GSM\n\nfrom wrappers.molecule import Molecule\nfrom utilities.nifty import printcool\nfrom utilities.manage_xyz import xyz_to_np\nfrom utilities import block_matrix\nfrom coordinate_systems import rotate\nfrom optimizers import eigenvector_follow\nimport multiprocessing as mp\nfrom itertools import chain\n\n\ndef worker(arg):\n    obj, methname = arg[:2]\n    return getattr(obj, methname)(*arg[2:])\n\n\n#######################################################################################\n############### This class contains the main GSM functions  ###########################\n#######################################################################################\n\n\nclass MainGSM(GSM):\n    def grow_string(self, max_iters=30, max_opt_steps=3, nconstraints=1):\n        '''\n        Grow the string\n\n        Parameters\n        ----------\n        max_iter : int\n             Maximum number of GSM iterations\n        nconstraints : int\n        optsteps : int\n            Maximum number of optimization steps per node of string\n        '''\n        printcool(\"In growth_iters\")\n\n        ncurrent, nlist = self.make_difference_node_list()\n        self.ictan, self.dqmaga = self.get_tangents_growing()\n        self.refresh_coordinates()\n        self.set_active(self.nR-1, self.nnodes-self.nP)\n\n        isGrown = False\n        iteration = 0\n        while not isGrown:\n            if iteration > max_iters:\n                print(\" Ran out of iterations\")\n                return\n                # raise Exception(\" Ran out of iterations\")\n            printcool(\"Starting growth iteration %i\" % iteration)\n            self.optimize_iteration(max_opt_steps)\n            totalgrad, gradrms, sum_gradrms = self.calc_optimization_metrics(self.nodes)\n            self.xyz_writer('scratch/growth_iters_{:03}_{:03}.xyz'.format(self.ID, iteration), self.geometries, self.energies, self.gradrmss, self.dEs)\n            print(\" gopt_iter: {:2} totalgrad: {:4.3} gradrms: {:5.4} max E: {:5.4}\\n\".format(iteration, float(totalgrad), float(gradrms), float(self.emax)))\n\n            try:\n                self.grow_nodes()\n            except Exception as error:\n                print(\"can't add anymore nodes, bdist too small\")\n\n                if self.__class__.__name__ == \"SE_GSM\":  # or self.__class__.__name__==\"SE_Cross\":\n                    # Don't do SE_cross because that already does optimization later\n                    if self.nodes[self.nR-1].PES.lot.do_coupling:\n                        opt_type = 'MECI'\n                    else:\n                       opt_type = 'UNCONSTRAINED'\n                    print(\" optimizing last node\")\n                    self.optimizer[self.nR-1].conv_grms = self.CONV_TOL\n                    print(self.optimizer[self.nR-1].conv_grms)\n                    path = os.path.join(os.getcwd(), 'scratch/{:03d}/{}'.format(self.ID, self.nR-1))\n                    self.optimizer[self.nR-1].optimize(\n                        molecule=self.nodes[self.nR-1],\n                        refE=self.nodes[0].V0,\n                        opt_steps=50,\n                        opt_type=opt_type,\n                        path=path,\n                    )\n                elif self.__class__.__name__ == \"SE_Cross\":\n                    print(\" Will do extra optimization of this node in SE-Cross\")\n                else:\n                    raise RuntimeError\n                break\n\n            self.set_active(self.nR-1, self.nnodes-self.nP)\n            self.ic_reparam_g()\n            self.ictan, self.dqmaga = self.get_tangents_growing()\n            self.refresh_coordinates()\n\n            iteration += 1\n            isGrown = self.check_if_grown()\n\n        # create newic object\n        print(\" creating newic molecule--used for ic_reparam\")\n        self.newic = Molecule.copy_from_options(self.nodes[0])\n\n        # TODO should something be done for growthdirection 2?\n        if self.growth_direction == 1:\n            print(\"Setting LOT of last node\")\n            self.nodes[-1] = Molecule.copy_from_options(\n                MoleculeA=self.nodes[-2],\n                xyz=self.nodes[-1].xyz,\n                new_node_id=self.nnodes-1\n            )\n        return\n\n    def optimize_string(self, max_iter=30, nconstraints=1, opt_steps=1, rtype=2):\n        '''\n        Optimize the grown string until convergence\n\n        Parameters\n        ----------\n        max_iter : int\n             Maximum number of GSM iterations \n        nconstraints : int\n        optsteps : int\n            Maximum number of optimization steps per node of string\n        rtype : int\n            An option to change how GSM optimizes  \n            TODO change this s***\n            0 is no-climb\n            1 is climber\n            2 is finder\n        '''\n        printcool(\"In opt_iters\")\n\n        self.nclimb = 0\n        self.nhessreset = 10  # are these used??? TODO\n        self.hessrcount = 0   # are these used?!  TODO\n        self.newclimbscale = 2.\n        self.set_finder(rtype)\n\n        isConverged = False\n        oi = 0\n\n        # enter loop\n        while not isConverged:\n            printcool(\"Starting opt iter %i\" % oi)\n            if self.climb and not self.find:\n                print(\" CLIMBING\")\n            elif self.find:\n                print(\" TS SEARCHING\")\n\n            # stash previous TSnode\n            self.pTSnode = self.TSnode\n            self.emaxp = self.emax\n\n            # store reparam energies\n            print(\" V_profile (beginning of iteration): \", end=' ')\n            self.print_energies()\n\n            # => Get all tangents 3-way <= #\n            self.get_tangents_opting()\n            self.refresh_coordinates()\n\n            # => do opt steps <= #\n            self.set_node_convergence()\n            self.optimize_iteration(opt_steps)\n\n            print(\" V_profile: \", end=' ')\n            self.print_energies()\n\n            # TODO resetting\n            # TODO special SSM criteria if first opt'd node is too high?\n            if self.TSnode == self.nnodes-2 and (self.climb or self.find):\n                printcool(\"WARNING\\n: TS node shouldn't be second to last node for tangent reasons\")\n                self.add_node_after_TS()\n                added = True\n            elif self.TSnode == 1 and (self.climb or self.find):\n                printcool(\"WARNING\\n: TS node shouldn't be first  node for tangent reasons\")\n                self.add_node_before_TS()\n                added = True\n            else:\n                added = False\n\n            # => find peaks <= #\n            fp = self.find_peaks('opting')\n\n            ts_cgradq = 0.\n            if not self.find:\n                ts_cgradq = np.linalg.norm(np.dot(self.nodes[self.TSnode].gradient.T, self.nodes[self.TSnode].constraints[:, 0])*self.nodes[self.TSnode].constraints[:, 0])\n                print(\" ts_cgradq %5.4f\" % ts_cgradq)\n\n            ts_gradrms = self.nodes[self.TSnode].gradrms\n            self.dE_iter = abs(self.emax-self.emaxp)\n            print(\" dE_iter ={:2.2f}\".format(self.dE_iter))\n\n            # => calculate totalgrad <= #\n            totalgrad, gradrms, sum_gradrms = self.calc_optimization_metrics(self.nodes)\n\n            # Check if allup or alldown\n            energies = np.array(self.energies)\n            if (np.all(energies[1:]+0.5 >= energies[:-1]) or np.all(energies[1:]-0.5 <= energies[:-1])) and (self.climber or self.finder):\n                printcool(\" There is no TS, turning off TS search\")\n                rtype = 0\n                self.climber = self.finder = self.find = self.climb = False\n                self.CONV_TOL = self.options['CONV_TOL']*5\n\n            # if self.has_intermediate(5) and rtype>0 and (self.climb or self.find):\n            #    printcool(\" THERE IS AN INTERMEDIATE, OPTIMIZE THE INTERMEDIATE AND TRY AGAIN\")\n            #    self.endearly=True\n            #    isConverged=True\n            #    self.tscontinue=False\n\n            # => Check Convergence <= #\n            isConverged = self.is_converged(totalgrad, fp, rtype, ts_cgradq)\n\n            # => set stage <= #\n            stage_changed = self.set_stage(totalgrad, sum_gradrms, ts_cgradq, ts_gradrms, fp)\n\n            if not stage_changed:\n                # Decrement stuff that controls stage\n                if self.climb:\n                    self.nclimb -= 1\n                self.nhessreset -= 1\n                if self.nopt_intermediate > 0:\n                    self.nopt_intermediate -= 1\n\n                if self.pTSnode != self.TSnode and self.climb:\n                    print(\"TS node changed after opting\")\n                    self.climb = False\n                    #self.slow_down_climb()\n                    self.pTSnode = self.TSnode\n\n                # opt decided Hess is not good because of overlap\n                if self.find and (not self.optimizer[self.TSnode].maxol_good or added):\n                    self.ictan, self.dqmaga = self.get_three_way_tangents(self.nodes, self.energies)\n                    self.modify_TS_Hess()\n                elif self.find and (self.optimizer[self.TSnode].nneg > 3 or self.optimizer[self.TSnode].nneg == 0 or self.hess_counter > 10 or np.abs(self.TS_E_0 - self.emax) > 10.) and not self.optimizer[self.TSnode].converged:\n\n                    # Reform the guess primitive Hessian\n                    self.nodes[self.TSnode].form_Primitive_Hessian()\n                    if self.hessrcount < 1 and self.pTSnode == self.TSnode:\n                        print(\" resetting TS node coords Ut (and Hessian)\")\n                        self.ictan, self.dqmaga = self.get_three_way_tangents(self.nodes, self.energies)\n                        self.modify_TS_Hess()\n                        self.nhessreset = 10\n                        self.hessrcount = 1\n                    else:\n                        print(\" Hessian consistently bad, going back to climb (for 3 iterations)\")\n                        self.find = False\n                        self.nclimb = 2\n                elif self.find and self.optimizer[self.TSnode].nneg <= 3:\n                    self.hessrcount -= 1\n                    self.hess_counter += 1\n\n            # => write Convergence to file <= #\n            filename = 'scratch/opt_iters_{:03}_{:03}.xyz'.format(self.ID, oi)\n            self.xyz_writer(filename, self.geometries, self.energies, self.gradrmss, self.dEs)\n\n            print(\" End early counter {}\".format(self.endearly_counter))\n\n            # TODO prints tgrads and jobGradCount\n            print(\"opt_iter: {:2} totalgrad: {:4.3} gradrms: {:5.4} max E({}) {:5.4}\\n\".format(oi, float(totalgrad), float(gradrms), self.TSnode, float(self.emax)))\n            oi += 1\n\n            # => Reparam the String <= #\n            if oi < max_iter and not isConverged:\n                self.reparameterize(nconstraints=nconstraints)\n                self.get_tangents_opting()\n                self.refresh_coordinates()\n                if self.pTSnode != self.TSnode and self.climb:\n                    print(\"TS node changed after reparameterizing\")\n                    self.slow_down_climb()\n            elif oi >= max_iter and not isConverged:\n                self.ran_out = True\n                print(\" Ran out of iterations\")\n                return\n                # raise Exception(\" Ran out of iterations\")\n\n        # TODO Optimize TS node to a finer convergence\n        # if rtype==2:\n        return\n\n    def refresh_coordinates(self, update_TS=False):\n        '''\n        Refresh the DLC coordinates for the string\n        '''\n\n        if not self.done_growing:\n            # TODO\n\n            if self.mp_cores == 1:\n                for n in range(1, self.nnodes-1):\n                    if self.nodes[n] is not None:\n                        Vecs = self.newic.coord_obj.build_dlc(self.nodes[n].xyz, self.ictan[n])\n                        self.nodes[n].coord_basis = Vecs\n\n            else:\n                pool = mp.Pool(self.mp_cores)\n                Vecs = pool.map(worker, ((self.newic.coord_obj, \"build_dlc\", self.nodes[n].xyz, self.ictan[n]) for n in range(1, self.nnodes-1) if self.nodes[n] is not None))\n                pool.close()\n                pool.join()\n\n                i = 0\n                for n in range(1, self.nnodes-1):\n                    if self.nodes[n] is not None:\n                        self.nodes[n].coord_basis = Vecs[i]\n                        i += 1\n        else:\n            if self.find or self.climb:\n                TSnode = self.TSnode\n                if self.mp_cores == 1:\n                    for n in range(1, self.nnodes-1):\n                        # don't update tsnode coord basis\n                        if n != TSnode or (n == TSnode and update_TS):\n                            Vecs = self.newic.coord_obj.build_dlc(self.nodes[n].xyz, self.ictan[n])\n                            self.nodes[n].coord_basis = Vecs\n                else:\n                    pool = mp.Pool(self.mp_cores)\n                    Vecs = pool.map(worker, ((self.newic.coord_obj, \"build_dlc\", self.nodes[n].xyz, self.ictan[n]) for n in range(1, self.nnodes-1) if n != TSnode))\n                    pool.close()\n                    pool.join()\n                    for i, n in enumerate(chain(range(1, TSnode), range(TSnode+1, self.nnodes-1))):\n                        self.nodes[n].coord_basis = Vecs[i]\n\n                    if update_TS:\n                        Vec = self.newic.coord_obj.build_dlc(self.nodes[TSnode].xyz, self.ictan[TSnode])\n                        self.nodes[TSnode].coord_basis = Vec\n\n            else:\n                if self.mp_cores == 1:\n                    Vecs = []\n                    for n in range(1, self.nnodes-1):\n                        Vecs.append(self.newic.coord_obj.build_dlc(self.nodes[n].xyz, self.ictan[n]))\n                elif self.mp_cores > 1:\n                    pool = mp.Pool(self.mp_cores)\n                    Vecs = pool.map(worker, ((self.newic.coord_obj, \"build_dlc\", self.nodes[n].xyz, self.ictan[n]) for n in range(1, self.nnodes-1)))\n                    pool.close()\n                    pool.join()\n                for n, node in enumerate(self.nodes[1:self.nnodes-1]):\n                    node.coord_basis = Vecs[n]\n\n    def optimize_iteration(self, opt_steps):\n        '''\n        Optimize string iteration\n        '''\n\n        refE = self.nodes[0].energy\n\n        for n in range(self.nnodes):\n            if self.nodes[n] and self.active[n]:\n                print()\n                path = os.path.join(os.getcwd(), 'scratch/{:03d}/{}'.format(self.ID, n))\n                printcool(\"Optimizing node {}\".format(n))\n                opt_type = self.set_opt_type(n)\n                osteps = self.mult_steps(n, opt_steps)\n                self.optimizer[n].optimize(\n                    molecule=self.nodes[n],\n                    refE=refE,\n                    opt_type=opt_type,\n                    opt_steps=osteps,\n                    ictan=self.ictan[n],\n                    xyzframerate=1,\n                    path=path,\n                )\n\n        if self.__class__.__name__ == \"SE-GSM\" and self.done_growing:\n            fp = self.find_peaks('opting')\n            if self.energies[self.nnodes-1] > self.energies[self.nnodes-2] and fp > 0 and self.nodes[self.nnodes-1].gradrms > self.CONV_TOL:\n                printcool('Last node is not a minimum, Might need to verify that the last node is a minimum')\n                path = os.path.join(os.getcwd(), 'scratch/{:03d}/{}'.format(self.ID, self.nnodes-1))\n                self.optimizer[self.nnodes-1].optimize(\n                    molecule=self.nodes[self.nnodes-1],\n                    refE=refE,\n                    opt_type='UNCONSTRAINED',\n                    opt_steps=osteps,\n                    ictan=None,\n                    path=path\n                )\n\n    def get_tangents_opting(self, print_level=1):\n        if self.climb or self.find:\n            self.ictan, self.dqmaga = self.get_three_way_tangents(self.nodes, self.energies)\n        else:\n            self.ictan, self.dqmaga = self.get_tangents(self.nodes)\n\n    def get_tangents_growing(self, print_level=1):\n        \"\"\"\n        Finds the tangents during the growth phase. \n        Tangents referenced to left or right during growing phase.\n        Also updates coordinates\n        Not a static method beause no one should ever call this outside of GSM\n        \"\"\"\n\n        ncurrent, nlist = self.make_difference_node_list()\n        dqmaga = [0.]*self.nnodes\n        ictan = [[]]*self.nnodes\n\n        if self.print_level > 1:\n            print(\"ncurrent, nlist\")\n            print(ncurrent)\n            print(nlist)\n\n        for n in range(ncurrent):\n            # ictan0,_ = self.get_tangent(\n            #        node1=self.nodes[nlist[2*n]],\n            #        node2=self.nodes[nlist[2*n+1]],\n            #        driving_coords=self.driving_coords,\n            #        )\n\n            if self.__class__.__name__ == \"DE_GSM\":  # or self.__class__.__name__==\"SE_Cross\":\n                print(\" getting tangent [%i ]from between %i %i pointing towards %i\" % (nlist[2*n], nlist[2*n], nlist[2*n+1], nlist[2*n]))\n                ictan0 = self.get_tangent_xyz(self.nodes[nlist[2*n]].xyz,\n                                              self.nodes[nlist[2*n+1]].xyz,\n                                              self.nodes[0].primitive_internal_coordinates)\n            else:\n                ictan0, _ = self.get_tangent(\n                    node1=self.nodes[nlist[2*n]],\n                    node2=self.nodes[nlist[2*n+1]],\n                    driving_coords=self.driving_coords,\n                )\n\n            if self.print_level > 1:\n                print(\"forming space for\", nlist[2*n+1])\n            if self.print_level > 1:\n                print(\"forming tangent for \", nlist[2*n])\n\n            if (ictan0[:] == 0.).all():\n                print(\" ICTAN IS ZERO!\")\n                print(nlist[2*n])\n                print(nlist[2*n+1])\n                raise RuntimeError\n\n            # normalize ictan\n            norm = np.linalg.norm(ictan0)\n            ictan[nlist[2*n]] = ictan0/norm\n\n            # NOTE regular GSM does something weird here\n            # Vecs = self.nodes[nlist[2*n]].update_coordinate_basis(constraints=self.ictan[nlist[2*n]])\n            # constraint = self.nodes[nlist[2*n]].constraints\n            # prim_constraint = block_matrix.dot(Vecs,constraint)\n            # but this is not followed here anymore 7/1/2020\n            # dqmaga[nlist[2*n]] = np.dot(prim_constraint.T,ictan0)\n            # dqmaga[nlist[2*n]] = float(np.sqrt(abs(dqmaga[nlist[2*n]])))\n            # tmp_dqmaga = np.dot(prim_constraint.T,ictan0)\n            # tmp_dqmaga = np.sqrt(tmp_dqmaga)\n\n            dqmaga[nlist[2*n]] = norm\n\n        if print_level > 0:\n            print('------------printing dqmaga---------------')\n            for n in range(self.nnodes):\n                print(\" {:5.3}\".format(dqmaga[n]), end=' ')\n                if (n+1) % 5 == 0:\n                    print()\n            print()\n\n        if print_level > 1:\n            for n in range(ncurrent):\n                print(\"dqmag[%i] =%1.2f\" % (nlist[2*n], self.dqmaga[nlist[2*n]]))\n                print(\"printing ictan[%i]\" % nlist[2*n])\n                print(self.ictan[nlist[2*n]].T)\n        for i, tan in enumerate(ictan):\n            if np.all(tan == 0.0):\n                print(\"tan %i of the tangents is 0\" % i)\n                raise RuntimeError\n\n        return ictan, dqmaga\n\n    # Refactor this code!\n    # TODO remove return form_TS hess  3/2021\n    def set_stage(self, totalgrad, sumgradrms, ts_cgradq, ts_gradrms, fp):\n\n        # checking sum gradrms is not good because if one node is converged a lot while others a re not this is bad\n        all_converged = all([self.nodes[n].gradrms < self.optimizer[n].conv_grms*1.1 for n in range(1, self.nnodes-1)])\n        all_converged_climb = all([self.nodes[n].gradrms < self.optimizer[n].conv_grms*2.5 for n in range(1, self.nnodes-1)])\n        stage_changed = False\n\n        # TODO totalgrad is not a good criteria for large systems\n        # if fp>0 and (((totalgrad < 0.3 or ts_cgradq < 0.01) and self.dE_iter < 2.) or all_converged) and self.nopt_intermediate<1: # extra criterion in og-gsm for added\n\n        if fp > 0 and all_converged_climb and self.dE_iter < 2.:  # and self.nopt_intermediate<1:\n            if not self.climb and self.climber:\n                print(\" ** starting climb **\")\n                self.climb = True\n                print(\" totalgrad %5.4f gradrms: %5.4f gts: %5.4f\" % (totalgrad, ts_gradrms, ts_cgradq))\n                # overwrite this here just in case TSnode changed wont cause slow down climb\n                self.pTSnode = self.TSnode\n                stage_changed = True\n\n            # TODO deserves to be rethought 3/2021\n            elif (self.climb and not self.find and self.finder and self.nclimb < 1 and\n                    ((totalgrad < 0.2 and ts_gradrms < self.CONV_TOL*10. and ts_cgradq < 0.01) or  # I hate totalgrad\n                     (totalgrad < 0.1 and ts_gradrms < self.CONV_TOL*10. and ts_cgradq < 0.02) or  #\n                     (all_converged) or\n                     (ts_gradrms < self.CONV_TOL*2.5 and ts_cgradq < 0.01)  # used to be 5\n                     )) and self.dE_iter < 1.:\n                print(\" ** starting exact climb **\")\n                print(\" totalgrad %5.4f gradrms: %5.4f gts: %5.4f\" % (totalgrad, ts_gradrms, ts_cgradq))\n                self.find = True\n\n                # Modify TS Hessian\n                self.ictan, self.dqmaga = self.get_three_way_tangents(self.nodes, self.energies)\n                self.modify_TS_Hess()\n\n                if self.optimizer[self.TSnode].options['DMAX'] > 0.1:\n                    self.optimizer[self.TSnode].options['DMAX'] = 0.1\n                self.optimizer[self.TSnode] = eigenvector_follow(self.optimizer[self.TSnode].options.copy())\n                self.optimizer[self.TSnode].options['SCALEQN'] = 1.\n                self.nhessreset = 10  # are these used??? TODO\n                self.hessrcount = 0   # are these used?!  TODO\n                stage_changed = True\n\n        return stage_changed\n\n    def add_GSM_nodeR(self, newnodes=1):\n        '''\n        Add a node between endpoints on the reactant side, should only be called inside GSM\n        '''\n        printcool(\"Adding reactant node\")\n\n        if self.current_nnodes+newnodes > self.nnodes:\n            raise ValueError(\"Adding too many nodes, cannot interpolate\")\n        for i in range(newnodes):\n            iR = self.nR-1\n            iP = self.nnodes-self.nP\n            iN = self.nR\n            print(\" adding node: %i between %i %i from %i\" % (iN, iR, iP, iR))\n            if self.nnodes - self.current_nnodes > 1:\n                stepsize = 1./float(self.nnodes-self.current_nnodes+1)\n            else:\n                stepsize = 0.5\n\n            self.nodes[self.nR] = GSM.add_node(\n                self.nodes[iR],\n                self.nodes[iP],\n                stepsize,\n                iN,\n                DQMAG_MAX=self.DQMAG_MAX,\n                DQMAG_MIN=self.DQMAG_MIN,\n                driving_coords=self.driving_coords,\n            )\n\n            if self.nodes[self.nR] is None:\n                raise Exception('Ran out of space')\n\n            if self.__class__.__name__ != \"DE_GSM\":\n                ictan, bdist = self.get_tangent(\n                    self.nodes[self.nR],\n                    None,\n                    driving_coords=self.driving_coords,\n                )\n                self.nodes[self.nR].bdist = bdist\n\n            self.optimizer[self.nR].DMAX = self.optimizer[self.nR-1].DMAX\n            self.current_nnodes += 1\n            self.nR += 1\n            print(\" nn=%i,nR=%i\" % (self.current_nnodes, self.nR))\n            self.active[self.nR-1] = True\n\n            # align center of mass  and rotation\n            # print(\"%i %i %i\" %(iR,iP,iN))\n\n            # print(\" Aligning\")\n            # self.nodes[self.nR-1].xyz = self.com_rotate_move(iR,iP,iN)\n\n    def add_GSM_nodeP(self, newnodes=1):\n        '''\n        Add a node between endpoints on the product side, should only be called inside GSM\n        '''\n        printcool(\"Adding product node\")\n        if self.current_nnodes+newnodes > self.nnodes:\n            raise ValueError(\"Adding too many nodes, cannot interpolate\")\n\n        for i in range(newnodes):\n            # self.nodes[-self.nP-1] = BaseClass.add_node(self.nnodes-self.nP,self.nnodes-self.nP-1,self.nnodes-self.nP)\n            n1 = self.nnodes-self.nP\n            n2 = self.nnodes-self.nP-1\n            n3 = self.nR-1\n            print(\" adding node: %i between %i %i from %i\" % (n2, n1, n3, n1))\n            if self.nnodes - self.current_nnodes > 1:\n                stepsize = 1./float(self.nnodes-self.current_nnodes+1)\n            else:\n                stepsize = 0.5\n\n            self.nodes[-self.nP-1] = GSM.add_node(\n                self.nodes[n1],\n                self.nodes[n3],\n                stepsize,\n                n2\n            )\n            if self.nodes[-self.nP-1] is None:\n                raise Exception('Ran out of space')\n\n            self.optimizer[n2].DMAX = self.optimizer[n1].DMAX\n            self.current_nnodes += 1\n            self.nP += 1\n            print(\" nn=%i,nP=%i\" % (self.current_nnodes, self.nP))\n            self.active[-self.nP] = True\n\n            # align center of mass  and rotation\n            # print(\"%i %i %i\" %(n1,n3,n2))\n            # print(\" Aligning\")\n            # self.nodes[-self.nP].xyz = self.com_rotate_move(n1,n3,n2)\n            # print(\" getting energy for node %d: %5.4f\" %(self.nnodes-self.nP,self.nodes[-self.nP].energy - self.nodes[0].V0))\n        return\n\n    def reparameterize(self, ic_reparam_steps=8, n0=0, nconstraints=1):\n        '''\n        Reparameterize the string\n        '''\n        if self.interp_method == 'DLC':\n            # print('reparameterizing')\n            self.ic_reparam(nodes=self.nodes, energies=self.energies, climbing=(self.climb or self.find), ic_reparam_steps=ic_reparam_steps, NUM_CORE=self.mp_cores)\n        return\n\n    def ic_reparam_g(self, ic_reparam_steps=4, n0=0, reparam_interior=True):  # see line 3863 of gstring.cpp\n        \"\"\"\n        Reparameterize during growth phase\n        \"\"\"\n\n        printcool(\"Reparamerizing string nodes\")\n        # close_dist_fix(0) #done here in GString line 3427.\n        rpmove = np.zeros(self.nnodes)\n        rpart = np.zeros(self.nnodes)\n        disprms = 0.0\n\n        if self.current_nnodes == self.nnodes:\n            return\n\n        for i in range(ic_reparam_steps):\n            self.ictan, self.dqmaga = self.get_tangents_growing()\n            totaldqmag = np.sum(self.dqmaga[n0:self.nR-1])+np.sum(self.dqmaga[self.nnodes-self.nP+1:self.nnodes])\n            if self.print_level > 0:\n                if i == 0:\n                    print(\" totaldqmag (without inner): {:1.2}\\n\".format(totaldqmag))\n                print(\" printing spacings dqmaga: \")\n                for n in range(self.nnodes):\n                    print(\" {:2.3}\".format(self.dqmaga[n]), end=' ')\n                    if (n+1) % 5 == 0:\n                        print()\n                print()\n\n            if i == 0:\n                if self.current_nnodes != self.nnodes:\n                    rpart = np.zeros(self.nnodes)\n                    for n in range(n0+1, self.nR):\n                        rpart[n] = 1.0/(self.current_nnodes-2)\n                    for n in range(self.nnodes-self.nP, self.nnodes-1):\n                        rpart[n] = 1.0/(self.current_nnodes-2)\n                else:\n                    for n in range(n0+1, self.nnodes):\n                        rpart[n] = 1./(self.nnodes-1)\n                if self.print_level > 0:\n                    if i == 0:\n                        print(\" rpart: \")\n                        for n in range(1, self.nnodes-1):\n                            print(\" {:1.2}\".format(rpart[n]), end=' ')\n                            if (n) % 5 == 0:\n                                print()\n                        print()\n            nR0 = self.nR\n            nP0 = self.nP\n\n            # TODO CRA 3/2019 why is this here?\n            if not reparam_interior:\n                if self.nnodes-self.current_nnodes > 2:\n                    nR0 -= 1\n                    nP0 -= 1\n\n            deltadq = 0.0\n            for n in range(n0+1, nR0):\n                deltadq = self.dqmaga[n-1] - totaldqmag*rpart[n]\n                rpmove[n] = -deltadq\n            for n in range(self.nnodes-nP0, self.nnodes-1):\n                deltadq = self.dqmaga[n+1] - totaldqmag*rpart[n]\n                rpmove[n] = -deltadq\n\n            MAXRE = 1.1\n\n            for n in range(n0+1, self.nnodes-1):\n                if abs(rpmove[n]) > MAXRE:\n                    rpmove[n] = float(np.sign(rpmove[n])*MAXRE)\n\n            disprms = float(np.linalg.norm(rpmove[n0+1:self.nnodes-1]))\n            if self.print_level > 0:\n                for n in range(n0+1, self.nnodes-1):\n                    print(\" disp[{}]: {:1.2f}\".format(n, rpmove[n]), end=' ')\n                    if (n) % 5 == 0:\n                        print()\n                print()\n                print(\" disprms: {:1.3}\\n\".format(disprms))\n\n            if disprms < 1e-2:\n                break\n\n            move_list = self.make_move_list()\n            tan_list = self.make_tan_list()\n\n            if self.mp_cores > 1:\n                pool = mp.Pool(self.mp_cores)\n                Vecs = pool.map(worker, ((self.nodes[0].coord_obj, \"build_dlc\", self.nodes[n].xyz, self.ictan[ntan]) for n, ntan in zip(move_list, tan_list) if rpmove[n] < 0))\n                pool.close()\n                pool.join()\n\n                i = 0\n                for n in move_list:\n                    if rpmove[n] < 0:\n                        self.nodes[n].coord_basis = Vecs[i]\n                        i += 1\n\n                # move the positions\n                pool = mp.Pool(self.mp_cores)\n                newXyzs = pool.map(worker, ((self.nodes[n].coord_obj, \"newCartesian\", self.nodes[n].xyz, rpmove[n]*self.nodes[n].constraints[:, 0]) for n in move_list if rpmove[n] < 0))\n                pool.close()\n                pool.join()\n                i = 0\n                for n in move_list:\n                    if rpmove[n] < 0:\n                        self.nodes[n].xyz = newXyzs[i]\n                        i += 1\n            else:\n                for nmove, ntan in zip(move_list, tan_list):\n                    if rpmove[nmove] < 0:\n                        print('Moving {} along ictan[{}]'.format(nmove, ntan))\n                        self.nodes[nmove].update_coordinate_basis(constraints=self.ictan[ntan])\n                        constraint = self.nodes[nmove].constraints[:, 0]\n                        dq0 = rpmove[nmove]*constraint\n                        self.nodes[nmove].update_xyz(dq0, verbose=True)\n\n        print(\" spacings (end ic_reparam, steps: {}/{}):\".format(i+1, ic_reparam_steps), end=' ')\n        for n in range(self.nnodes):\n            print(\" {:1.2}\".format(self.dqmaga[n]), end=' ')\n        print(\"  disprms: {:1.3}\".format(disprms))\n\n        # TODO old GSM does this here\n        # Failed = check_array(self.nnodes,self.dqmaga)\n        # If failed, do exit 1\n\n    def modify_TS_Hess(self):\n        ''' Modifies Hessian using RP direction'''\n        print(\"modifying %i Hessian with RP\" % self.TSnode)\n\n        TSnode = self.TSnode\n        # a variable to determine how many time since last modify\n        self.hess_counter = 0\n        self.TS_E_0 = self.energies[TSnode]\n\n        E0 = self.energies[TSnode]/GSM.units.KCAL_MOL_PER_AU\n        Em1 = self.energies[TSnode-1]/GSM.units.KCAL_MOL_PER_AU\n        if self.TSnode+1 < self.nnodes:\n            Ep1 = self.energies[TSnode+1]/GSM.units.KCAL_MOL_PER_AU\n        else:\n            Ep1 = Em1\n\n        # Update TS node coord basis\n        Vecs = self.nodes[TSnode].update_coordinate_basis(constraints=None)\n\n        # get constrained coord basis\n        self.newic.xyz = self.nodes[TSnode].xyz.copy()\n        const_vec = self.newic.update_coordinate_basis(constraints=self.ictan[TSnode])\n        q0 = self.newic.coordinates[0]\n        constraint = self.newic.constraints[:, 0]\n\n        # this should just give back ictan[TSnode]?\n        tan0 = block_matrix.dot(const_vec, constraint)\n\n        # get qm1 (don't update basis)\n        self.newic.xyz = self.nodes[TSnode-1].xyz.copy()\n        qm1 = self.newic.coordinates[0]\n\n        if TSnode+1 < self.nnodes:\n            # get qp1 (don't update basis)\n            self.newic.xyz = self.nodes[TSnode+1].xyz.copy()\n            qp1 = self.newic.coordinates[0]\n        else:\n            qp1 = qm1\n\n        print(\" TS Hess init'd w/ existing Hintp\")\n\n        # Go to non-constrained basis\n        self.newic.xyz = self.nodes[TSnode].xyz.copy()\n        self.newic.coord_basis = Vecs\n        self.newic.Primitive_Hessian = self.nodes[TSnode].Primitive_Hessian.copy()\n        self.newic.form_Hessian_in_basis()\n\n        tan = block_matrix.dot(block_matrix.transpose(Vecs), tan0)   # (nicd,1\n        Ht = np.dot(self.newic.Hessian, tan)                         # (nicd,nicd)(nicd,1) = nicd,1\n        tHt = np.dot(tan.T, Ht)\n\n        a = abs(q0-qm1)\n        b = abs(qp1-q0)\n        c = 2*(Em1/a/(a+b) - E0/a/b + Ep1/b/(a+b))\n        print(\" tHt %1.3f a: %1.1f b: %1.1f c: %1.3f\" % (tHt, a[0], b[0], c[0]))\n\n        ttt = np.outer(tan, tan)\n\n        # Hint before\n        # with np.printoptions(threshold=np.inf):\n        #    print self.newic.Hessian\n        # eig,tmph = np.linalg.eigh(self.newic.Hessian)\n        # print \"initial eigenvalues\"\n        # print eig\n\n        # Finalize Hessian\n        self.newic.Hessian += (c-tHt)*ttt\n        self.nodes[TSnode].Hessian = self.newic.Hessian.copy()\n\n        # Hint after\n        # with np.printoptions(threshold=np.inf):\n        #    print self.nodes[TSnode].Hessian\n        # print \"shape of Hessian is %s\" % (np.shape(self.nodes[TSnode].Hessian),)\n\n        self.nodes[TSnode].newHess = 5\n\n        if False:\n            print(\"newHess of node %i %i\" % (TSnode, self.nodes[TSnode].newHess))\n            eigen, tmph = np.linalg.eigh(self.nodes[TSnode].Hessian)  # nicd,nicd\n            print(\"eigenvalues of new Hess\")\n            print(eigen)\n\n        # reset pgradrms ?\n\n    def mult_steps(self, n, opt_steps):\n        exsteps = 1\n        tsnode = int(self.TSnode)\n\n        if (self.find or self.climb) and self.energies[n] > self.energies[self.TSnode]*0.9 and n != tsnode:  #\n            exsteps = 2\n            print(\" multiplying steps for node %i by %i\" % (n, exsteps))\n        elif self.find and n == tsnode and self.energies[tsnode] > self.energies[tsnode-1]*1.1 and self.energies[tsnode] > self.energies[tsnode+1]*1.1:  # Can also try self.climb but i hate climbing image\n            exsteps = 2\n            print(\" multiplying steps for node %i by %i\" % (n, exsteps))\n        # elif not self.find and not self.climb and n==tsnode  and self.energies[tsnode]>self.energies[tsnode-1]*1.5 and self.energies[tsnode]>self.energies[tsnode+1]*1.5 and self.climber:\n        #    exsteps=2\n        #    print(\" multiplying steps for node %i by %i\" % (n,exsteps))\n\n        # elif not (self.find and self.climb) and self.energies[tsnode] > 1.75*self.energies[tsnode-1] and self.energies[tsnode] > 1.75*self.energies[tsnode+1] and self.done_growing and n==tsnode:  #or self.climb\n        #    exsteps=2\n        #    print(\" multiplying steps for node %i by %i\" % (n,exsteps))\n        return exsteps*opt_steps\n\n    def set_opt_type(self, n, quiet=False):\n        # TODO error for seam climb\n        opt_type = 'ICTAN'\n        if self.climb and n == self.TSnode and not self.find and self.nodes[n].PES.__class__.__name__ != \"Avg_PES\":\n            opt_type = 'CLIMB'\n        elif self.find and n == self.TSnode:\n            opt_type = 'TS'\n        elif self.nodes[n].PES.__class__.__name__ == \"Avg_PES\":\n            opt_type = 'SEAM'\n            if self.climb and n == self.TSnode:\n                opt_type = 'TS-SEAM'\n        if not quiet:\n            print((\" setting node %i opt_type to %s\" % (n, opt_type)))\n\n        # if isinstance(self.optimizer[n],beales_cg) and opt_type!=\"BEALES_CG\":\n        #    raise RuntimeError(\"This shouldn't happen\")\n\n        return opt_type\n\n    #TODO Remove me does not deserve to be a function\n    def set_finder(self, rtype):\n        assert rtype in [0, 1, 2], \"rtype not defined\"\n        print('')\n        print(\"*********************************************************************\")\n        if rtype == 2:\n            print(\"****************** set climber and finder to True *******************\")\n            self.climber = True\n            self.finder = True\n        elif rtype == 1:\n            print(\"***************** setting climber to True*************************\")\n            self.climber = True\n        else:\n            print(\"******** Turning off climbing image and exact TS search **********\")\n        print(\"*********************************************************************\")\n\n    def com_rotate_move(self, iR, iP, iN):\n        print(\" aligning com and to Eckart Condition\")\n\n        mfrac = 0.5\n        if self.nnodes - self.current_nnodes+1 != 1:\n            mfrac = 1./(self.nnodes - self.current_nnodes+1)\n\n        # if self.__class__.__name__ != \"DE_GSM\":\n        #    # no \"product\" structure exists, use initial structure\n        #    iP = 0\n\n        xyz0 = self.nodes[iR].xyz.copy()\n        xyz1 = self.nodes[iN].xyz.copy()\n        com0 = self.nodes[iR].center_of_mass\n        com1 = self.nodes[iN].center_of_mass\n        masses = self.nodes[iR].mass_amu\n\n        # From the old GSM code doesn't work\n        # com1 = mfrac*(com2-com0)\n        # print(\"com1\")\n        # print(com1)\n        # # align centers of mass\n        # xyz1 += com1\n        # Eckart_align(xyz1,xyz2,masses,mfrac)\n\n        # rotate to be in maximal coincidence with 0\n        # assumes iP i.e. 2 is also in maximal coincidence\n        U = rotate.get_rot(xyz0, xyz1)\n        xyz1 = np.dot(xyz1, U)\n\n        # # align\n        # if self.nodes[iP] != None:\n        #    xyz2 = self.nodes[iP].xyz.copy()\n        #    com2 = self.nodes[iP].center_of_mass\n\n        #    if abs(iN-iR) > abs(iN-iP):\n        #        avg_com = mfrac*com2 + (1.-mfrac)*com0\n        #    else:\n        #        avg_com = mfrac*com0 + (1.-mfrac)*com2\n        #    dist = avg_com - com1  #final minus initial\n        # else:\n        #    dist = com0 - com1  #final minus initial\n\n        # print(\"aligning to com\")\n        # print(dist)\n        # xyz1 += dist\n\n        return xyz1\n\n    def find_peaks(self, rtype='opting'):\n        '''\n        This doesnt actually calculate peaks, it calculates some other thing\n        '''\n        # rtype 1: growing\n        # rtype 2: opting\n        # rtype 3: intermediate check\n        if rtype not in ['growing', 'opting', 'intermediate']:\n            raise RuntimeError\n\n        # if rtype==1:\n        if rtype == \"growing\":\n            nnodes = self.nR\n        elif rtype == \"opting\" or rtype == \"intermediate\":\n            nnodes = self.nnodes\n        else:\n            raise ValueError(\"find peaks bad input\")\n        # if rtype==1 or rtype==2:\n        #    print \"Energy\"\n        alluptol = 0.1\n        alluptol2 = 0.5\n        allup = True\n        diss = False\n        energies = self.energies\n        for n in range(1, len(energies[:nnodes])):\n            if energies[n]+alluptol < energies[n-1]:\n                allup = False\n                break\n\n        if energies[nnodes-1] > 15.0:\n            if nnodes-3 > 0:\n                if ((energies[nnodes-1]-energies[nnodes-2]) < alluptol2 and\n                    (energies[nnodes-2]-energies[nnodes-3]) < alluptol2 and\n                        (energies[nnodes-3]-energies[nnodes-4]) < alluptol2):\n                    print(\" possible dissociative profile\")\n                    diss = True\n\n        print(\" nnodes \", nnodes)\n        print(\" all uphill? \", allup)\n        print(\" dissociative? \", diss)\n        npeaks1 = 0\n        npeaks2 = 0\n        minnodes = []\n        maxnodes = []\n        if energies[1] > energies[0]:\n            minnodes.append(0)\n        if energies[nnodes-1] < energies[nnodes-2]:\n            minnodes.append(nnodes-1)\n        for n in range(self.n0, nnodes-1):\n            if energies[n+1] > energies[n]:\n                if energies[n] < energies[n-1]:\n                    minnodes.append(n)\n            if energies[n+1] < energies[n]:\n                if energies[n] > energies[n-1]:\n                    maxnodes.append(n)\n\n        print(\" min nodes \", minnodes)\n        print(\" max nodes \", maxnodes)\n        npeaks1 = len(maxnodes)\n        # print \"number of peaks is \",npeaks1\n        ediff = 0.5\n        PEAK4_EDIFF = 2.0\n        if rtype == \"growing\":\n            ediff = 1.\n        if rtype == \"intermediate\":\n            ediff = PEAK4_EDIFF\n\n        if rtype == \"growing\":\n            nmax = np.argmax(energies[:self.nR])\n            emax = float(max(energies[:self.nR]))\n        else:\n            emax = float(max(energies))\n            nmax = np.argmax(energies)\n\n        print(\" emax and nmax in find peaks %3.4f,%i \" % (emax, nmax))\n\n        #check if any node after peak is less than 2 kcal below\n        for n in maxnodes:\n            diffs = (energies[n]-e > ediff for e in energies[n:nnodes])\n            if any(diffs):\n                found = n\n                npeaks2 += 1\n        npeaks = npeaks2\n        print(\" found %i significant peak(s) TOL %3.2f\" % (npeaks, ediff))\n\n        # handle dissociative case\n        if rtype == \"intermediate\" and npeaks == 1:\n            nextmin = 0\n            for n in range(found, nnodes-1):\n                if n in minnodes:\n                    nextmin = n\n                    break\n            if nextmin > 0:\n                npeaks = 2\n\n        # if rtype==3:\n        #    return nmax\n        if allup is True and npeaks == 0:\n            return -1\n        if diss is True and npeaks == 0:\n            return -2\n\n        return npeaks\n\n    def is_converged(self, totalgrad, fp, rtype, ts_cgradq):\n        '''\n        Check if optimization is converged\n        '''\n\n        # Important the factor 5 here corresponds to the same convergence criteria in the TS optimizer\n        TS_conv = self.CONV_TOL*5\n        # => Check if intermediate exists\n        # ALEX REMOVED CLIMB REQUIREMENT\n        if self.has_intermediate(self.noise):\n            print(\"New pot min: {}\".format(self.get_intermediate(self.noise)))\n            print(\"Old pot min: {}\".format(self.pot_min))\n            if self.get_intermediate(self.noise) == self.pot_min:\n                self.endearly_counter += 1\n            else:\n                self.pot_min = self.get_intermediate(self.noise)\n                self.endearly_counter = 1\n            if self.endearly_counter >= 3:\n                self.end_early = True\n                self.tscontinue = False\n                printcool(\" THERE IS AN INTERMEDIATE, OPTIMIZE THE INTERMEDIATE AND TRY AGAIN\")\n                return True\n\n        elif not self.has_intermediate(self.noise):\n            self.endearly_counter = 0\n            self.pot_min = self.get_intermediate(self.noise)\n\n        # print(\" Number of imaginary frequencies %i\" % self.optimizer[self.TSnode].nneg)\n\n        # or (totalgrad<0.1 and self.nodes[self.TSnode].gradrms<2.5*TS_conv and self.dE_iter<0.02 and self.optimizer[self.TSnode].nneg <2)  #TODO extra crit here\n        if (self.finder and self.find):\n            return (self.nodes[self.TSnode].gradrms < self.CONV_TOL and abs(ts_cgradq) < TS_conv and self.dE_iter < self.optimizer[self.TSnode].conv_Ediff*3 and self.optimizer[self.TSnode].nneg < 2)\n        elif self.climber and self.climb:\n            return (self.nodes[self.TSnode].gradrms < self.CONV_TOL and abs(ts_cgradq) < TS_conv and self.dE_iter < self.optimizer[self.TSnode].conv_Ediff*3)\n        elif not self.climber and not self.finder:\n            print(\" CONV_TOL=%.4f\" % self.CONV_TOL)\n            return all([self.optimizer[n].converged for n in range(1, self.nnodes-1)])\n\n        return False\n\n    def print_energies(self):\n        for n in range(len(self.energies)):\n            print(\" {:7.3f}\".format(float(self.energies[n])), end=' ')\n        print()\n\n    def get_intermediate(self, noise):\n        '''\n        Check string for intermediates\n        noise is a leeway factor for determining intermediate\n        '''\n\n        energies = self.energies\n        potential_min = []\n        for i in range(1, (len(energies) - 1)):\n            rnoise = 0\n            pnoise = 0\n            a = 1\n            b = 1\n            while (energies[i-a] >= energies[i]):\n                if (energies[i-a] - energies[i]) > rnoise:\n                    rnoise = energies[i-a] - energies[i]\n                if rnoise > noise:\n                    break\n                if (i-a) == 0:\n                    break\n                a += 1\n\n            while (energies[i+b] >= energies[i]):\n                if (energies[i+b] - energies[i]) > pnoise:\n                    pnoise = energies[i+b] - energies[i]\n                if pnoise > noise:\n                    break\n                if (i+b) == len(energies) - 1:\n                    break\n                b += 1\n            if ((rnoise > noise) and (pnoise > noise)):\n                print('Potential minimum at image %s' % i)\n                potential_min.append(i)\n\n        return potential_min\n\n    def has_intermediate(self, noise):\n        pot_min = self.get_intermediate(noise)\n        return len(pot_min) > 0\n\n    def setup_from_geometries(self, input_geoms, reparametrize=True, restart_energies=True, start_climb_immediately=False):\n        '''\n        Restart\n        input_geoms list of geometries\n        reparameterize (boolean) : reparameterize the initial string to make the nodes equidistant\n        restart_energies (boolean) : generate the initial energies\n        start_climb_immediately (boolean) : set climb to True or False\n        '''\n\n        printcool(\"Restarting GSM from geometries\")\n        self.growth_direction = 0\n        nstructs = len(input_geoms)\n\n        if nstructs != self.nnodes:\n            print('need to interpolate')\n            # if self.interp_method==\"DLC\": TODO\n            raise NotImplementedError\n        else:\n            geoms = input_geoms\n\n        self.gradrms = [0.]*nstructs\n        self.dE = [1000.]*nstructs\n\n        self.isRestarted = True\n        self.done_growing = True\n\n        # set coordinates from geoms\n        self.nodes[0].xyz = xyz_to_np(geoms[0])\n        self.nodes[nstructs-1].xyz = xyz_to_np(geoms[-1])\n        for struct in range(1, nstructs-1):\n            self.nodes[struct] = Molecule.copy_from_options(self.nodes[struct-1],\n                                                            xyz_to_np(geoms[struct]),\n                                                            new_node_id=struct,\n                                                            copy_wavefunction=False)\n            self.nodes[struct].newHess = 5\n            # Turning this off\n            # self.nodes[struct].gradrms = np.sqrt(np.dot(self.nodes[struct].gradient,self.nodes\n            # self.nodes[struct].gradrms=grmss[struct]\n            # self.nodes[struct].PES.dE = dE[struct]\n        self.nnodes = self.nR = nstructs\n\n        if start_climb_immediately:\n            # should check that this is a climber...\n            self.climb = True\n\n        if reparametrize:\n            printcool(\"Reparametrizing\")\n            self.reparameterize(ic_reparam_steps=8)\n            self.xyz_writer('grown_string_{:03}.xyz'.format(self.ID), self.geometries, self.energies, self.gradrmss, self.dEs)\n\n        if restart_energies:\n            self.interpolate_orbitals()\n            print(\" V_profile: \", end=' ')\n            energies = self.energies\n            for n in range(self.nnodes):\n                print(\" {:7.3f}\".format(float(energies[n])), end=' ')\n            print()\n\n        self.ictan, self.dqmaga = self.get_tangents(self.nodes)\n        self.refresh_coordinates()\n        print(\" setting all interior nodes to active\")\n        for n in range(1, self.nnodes-1):\n            self.active[n] = True\n            self.optimizer[n].conv_grms = self.CONV_TOL*2.5\n            self.optimizer[n].options['DMAX'] = 0.05\n\n        return\n\n    def add_node_before_TS(self):\n        '''\n        '''\n        new_node = GSM.add_node(\n            self.nodes[self.TSnode-1],\n            self.nodes[self.TSnode],\n            stepsize=0.5,\n            node_id=self.TSnode-1,\n        )\n        new_node_list = [None]*(self.nnodes+1)\n        new_optimizers = [None]*(self.nnodes+1)\n        for n in range(0, self.TSnode-1):\n            new_node_list[n] = self.nodes[n]\n            new_optimizers[n] = self.optimizer[n]\n        new_node_list[self.TSnode-1] = new_node\n        new_optimizers[self.TSnode-1] = self.optimizer[0].__class__(self.optimizer[0].options.copy())\n\n        for n in range(self.TSnode, self.nnodes+1):\n            new_node_list[n] = Molecule.copy_from_options(MoleculeA=self.nodes[n-1], new_node_id=n)\n            new_optimizers[n] = self.optimizer[n-1]\n        self.nodes = new_node_list\n        self.optimizer = new_optimizers\n        self.nnodes = len(self.nodes)\n        print(' New number of nodes %d' % self.nnodes)\n        self.active = [True] * self.nnodes\n        self.active[0] = False\n        self.active[self.nnodes-1] = False\n\n    def add_node_after_TS(self):\n        '''\n        '''\n        new_node = GSM.add_node(\n            self.nodes[self.TSnode],\n            self.nodes[self.TSnode+1],\n            stepsize=0.5,\n            node_id=self.TSnode+1,\n        )\n        new_node_list = [None]*(self.nnodes+1)\n        new_optimizers = [None]*(self.nnodes+1)\n        for n in range(0, self.TSnode+1):\n            new_node_list[n] = self.nodes[n]\n            new_optimizers[n] = self.optimizer[n]\n        new_node_list[self.TSnode+1] = new_node\n        new_optimizers[self.TSnode+1] = self.optimizer[0].__class__(self.optimizer[0].options.copy())\n\n        for n in range(self.TSnode+2, self.nnodes+1):\n            new_node_list[n] = Molecule.copy_from_options(MoleculeA=self.nodes[n-1], new_node_id=n)\n            new_optimizers[n] = self.optimizer[n-1]\n        self.nodes = new_node_list\n        self.optimizer = new_optimizers\n        self.nnodes = len(self.nodes)\n        print(' New number of nodes %d' % self.nnodes)\n        self.active = [True] * self.nnodes\n        self.active[0] = False\n        self.active[self.nnodes-1] = False\n\n    def set_node_convergence(self):\n        ''' set convergence for nodes\n        '''\n\n        factor = 5. if (self.climber or self.finder) else 1.\n        TSnode = self.TSnode\n        for n in range(1, self.nnodes-1):\n            if self.nodes[n] is not None:\n                self.optimizer[n].conv_grms = self.CONV_TOL*factor\n                self.optimizer[n].conv_gmax = self.options['CONV_gmax']*factor\n                self.optimizer[n].conv_Ediff = self.options['CONV_Ediff']*factor\n                if self.optimizer[n].converged and n != TSnode:\n                    self.optimizer[n].check_only_grad_converged=True\n                if (self.climb or self.find) and self.energies[n]>self.energies[TSnode]*0.75 and n!=TSnode:\n                    self.optimizer[n].conv_grms = self.CONV_TOL     \n                    self.optimizer[n].conv_gmax = self.options['CONV_gmax']\n                    self.optimizer[n].conv_Ediff = self.options['CONV_Ediff']\n                    self.optimizer[n].check_only_grad_converged = False\n                if n == self.TSnode and (self.climb or self.find):\n                    self.optimizer[n].conv_grms = self.CONV_TOL\n                    self.optimizer[n].conv_gmax = self.options['CONV_gmax']\n                    self.optimizer[n].conv_Ediff = self.options['CONV_Ediff']\n                    self.optimizer[n].check_only_grad_converged = False\n\n    def slow_down_climb(self):\n        if self.climb and not self.find:\n            print(\" slowing down climb optimization\")\n            self.optimizer[self.TSnode].options['DMAX'] /= self.newclimbscale\n            self.optimizer[self.TSnode].options['SCALEQN'] = 2.\n            if self.optimizer[self.TSnode].SCALE_CLIMB < 5.:\n                self.optimizer[self.TSnode].SCALE_CLIMB += 1.\n            self.optimizer[self.pTSnode].options['SCALEQN'] = 1.\n            self.ts_exsteps = 1\n            if self.newclimbscale < 5.0:\n                self.newclimbscale += 1.\n        elif self.find:\n            self.find = False\n            self.climb = True\n            self.nclimb = 1\n            print(\" Find bad, going back to climb\")\n\n    def interpolate_orbitals(self):\n        '''\n        Interpolate orbitals\n        '''\n\n        nnodes = len(self.nodes)\n        nn = nnodes//2\n        couples = [(i, nnodes-i-1) for i in range(nn)]\n        first = True\n        for i, j in couples:\n\n            if first:\n                # Calculate the energy of the i, j\n                self.nodes[i].energy\n                self.nodes[j].energy\n                first = False\n            else:\n                # Copy the orbital of i-1 to i\n                self.nodes[i].PES.lot = type(self.nodes[i-1].PES.lot).copy(\n                    self.nodes[i-1].PES.lot, copy_wavefunction=True)\n                self.nodes[i].energy\n                # Copy the orbital of j+1 to j\n                self.nodes[j].PES.lot = type(self.nodes[j+1].PES.lot).copy(\n                    self.nodes[j+1].PES.lot, copy_wavefunction=True)\n                self.nodes[j].energy\n        return\n", "meta": {"hexsha": "82afcdeb35cf68606094686a03e415d48b0870e0", "size": 53598, "ext": "py", "lang": "Python", "max_stars_repo_path": "pygsm/growing_string_methods/main_gsm.py", "max_stars_repo_name": "YuOZW/pyGSM", "max_stars_repo_head_hexsha": "18459cfbc4f04061c65d4c12fa933f85c3ba97f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pygsm/growing_string_methods/main_gsm.py", "max_issues_repo_name": "YuOZW/pyGSM", "max_issues_repo_head_hexsha": "18459cfbc4f04061c65d4c12fa933f85c3ba97f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pygsm/growing_string_methods/main_gsm.py", "max_forks_repo_name": "YuOZW/pyGSM", "max_forks_repo_head_hexsha": "18459cfbc4f04061c65d4c12fa933f85c3ba97f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1027607362, "max_line_length": 228, "alphanum_fraction": 0.5315683421, "include": true, "reason": "import numpy", "num_tokens": 13520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3040416812727288, "lm_q1q2_score": 0.1555831768294268}}
{"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"SHERIFS\nSeismic Hazard and Earthquake Rates In Fault Systems\n\nVersion 1.0 \n\n@author: thomas\n\"\"\"\nimport numpy as np\n        \n        \ndef sr_rate(Run_name,scenarios_names_list,mega_MFD,Model_list,MFD_type_list):\n\n    '''####################################\n    # use of the slip rate per fault\n    #######################################'''  \n    input_file_name = 'init'\n    slip_rep_faults_all_data = open(Run_name + '/analysis/txt_files/slip_rep_on_faults_all_data.txt','w') #file with all the information about slip repartition\n\n    for model in Model_list:\n        for scenario_name in scenarios_names_list :\n            for mega_mfd_i in mega_MFD :\n                if mega_mfd_i[8] == scenario_name and mega_mfd_i[3] == model :\n                    i_mfd =  0\n                    input_file_name_i = (str(Run_name) + '/' + str(mega_mfd_i[3]) + '/' + 'bg_' + str(mega_mfd_i[4]) \n                                        + '/' + str(mega_mfd_i[0]) + '_' + str(mega_mfd_i[1]) + '_' + str(mega_mfd_i[2]) \n                                        + '/sc_' + str(mega_mfd_i[8])  + '/bmin_' + str(mega_mfd_i[5]) + '_bmax_' + str(mega_mfd_i[6]) \n                                        + '/MFD_' + str(mega_mfd_i[7]) + '/Log/sliprep_sample_' + str(mega_mfd_i[9]) + '.txt')\n                                        \n                    rup_file = (str(Run_name) + '/' + str(mega_mfd_i[3]) + '/' + 'bg_' + str(mega_mfd_i[4])\n                    + '/' + str(mega_mfd_i[0]) + '_' + str(mega_mfd_i[1]) + '_' + str(mega_mfd_i[2])\n                    + '/sc_' + str(mega_mfd_i[8])  + '/bmin_' + str(mega_mfd_i[5]) + '_bmax_' + str(mega_mfd_i[6])\n                    + '/MFD_' + str(mega_mfd_i[7]) + '/Log/ruptures.txt')\n                    rup_id = []\n                    rup_length = []\n                    for line in open(rup_file):\n                        if not 'rup_id' in line :\n                            rup_i = line.split('\\t')[0]\n                            rup_id.append(rup_i)\n                            rup_length_i = line.split('\\t')[1]\n                            rup_length.append(len(rup_length_i.split(' '))-1)\n                        \n                    if input_file_name_i != input_file_name :\n                        input_file_name = input_file_name_i\n                        with open(input_file_name,'r') as f:\n                            for line in f:\n                                content = line.split(' ')\n                                fault_name = content[0]\n                                total_number = len(content)-1\n                                n_fault_alone= 0.\n                                n_FtF_2= 0.\n                                n_FtF_3= 0.\n                                n_FtF_4= 0.\n                                n_FtF_5= 0.\n                                n_FtF_6= 0.\n                                n_FtF_7= 0.\n                                n_FtF_8= 0.\n                                n_FtF_9= 0.\n                                n_FtF_10= 0.\n                                n_FtF_11= 0.\n                                n_FtF_12= 0.\n                                n_FtF_13 = 0.\n                                for rup_i,rup_length_i in zip(rup_id,rup_length):\n                                    c = content[1:].count(str(rup_i))\n                                    if rup_length_i >= 13 :\n                                        n_FtF_13 += c\n                                    if rup_length_i == 12 :\n                                        n_FtF_12 += c\n                                    if rup_length_i == 11 :\n                                        n_FtF_11 += c\n                                    if rup_length_i == 10 :\n                                        n_FtF_10 += c\n                                    if rup_length_i == 9 :\n                                        n_FtF_9 += c\n                                    if rup_length_i == 8 :\n                                        n_FtF_8 += c\n                                    if rup_length_i == 7 :\n                                        n_FtF_7 += c\n                                    if rup_length_i == 6 :\n                                        n_FtF_6 += c\n                                    if rup_length_i == 5 :\n                                        n_FtF_5 += c\n                                    if rup_length_i == 4 :\n                                        n_FtF_4 += c\n                                    if rup_length_i == 3 :\n                                        n_FtF_3 += c\n                                    if rup_length_i == 2 :\n                                        n_FtF_2 += c\n                                    if rup_length_i == 1 :\n                                        n_fault_alone += c\n                                n_NMS = content[1:].count('NMS')\n                                \n                                p_FtF_13 = round(float(n_FtF_13) / float(total_number) * 100., 1)\n                                p_FtF_12 = round(float(n_FtF_12) / float(total_number) * 100., 1)\n                                p_FtF_11 = round(float(n_FtF_11) / float(total_number) * 100., 1)\n                                p_FtF_10 = round(float(n_FtF_10) / float(total_number) * 100., 1)\n                                p_FtF_9 = round(float(n_FtF_9) / float(total_number) * 100., 1)\n                                p_FtF_8 = round(float(n_FtF_8) / float(total_number) * 100., 1)\n                                p_FtF_7 = round(float(n_FtF_7) / float(total_number) * 100., 1)\n                                p_FtF_6 = round(float(n_FtF_6) / float(total_number) * 100., 1)\n                                p_FtF_5 = round(float(n_FtF_5) / float(total_number) * 100., 1)\n                                p_FtF_4 = round(float(n_FtF_4) / float(total_number) * 100., 1)\n                                p_FtF_3 = round(float(n_FtF_3) / float(total_number) * 100., 1)\n                                p_FtF_2 = round(float(n_FtF_2) / float(total_number) * 100., 1)\n                                p_fault_alone = round(float(n_fault_alone) / float(total_number) * 100., 1)\n                                p_NMS = round(float(n_NMS) / float(total_number) * 100., 1)\n                                \n                                line = (str(mega_mfd_i[0]) + '_' + str(mega_mfd_i[1]) + '_' + str(mega_mfd_i[2])\n                                + '\\t' + str(model) + '\\tbg_' + str(mega_mfd_i[4]) + '\\tbmin_' + str(mega_mfd_i[5]) + '_bmax_' + str(mega_mfd_i[6])\n                                + '\\tMFD_' + str(mega_mfd_i[7]) + '\\t' + str(scenario_name)  + '\\tsample_' + str(mega_mfd_i[9])\n                                + '\\t' + fault_name + '\\t' + str(p_fault_alone) + '\\t' + str(p_FtF_2) + '\\t' + str(p_FtF_3) + '\\t' + str(p_FtF_4) + '\\t'\n                                + str(p_FtF_5) + '\\t' + str(p_FtF_6) + '\\t' + str(p_FtF_7) + '\\t'+ str(p_FtF_8) + '\\t'+ str(p_FtF_9) + '\\t'+ str(p_FtF_10) + '\\t'\n                                + str(p_FtF_11) + '\\t'+ str(p_FtF_12) + '\\t'+ str(p_FtF_13) + '\\t'+ str(p_NMS) )\n                                slip_rep_faults_all_data.write(line+'\\n')\n    slip_rep_faults_all_data.close()\n                        \n    slip_rep_data = np.genfromtxt(Run_name + '/analysis/txt_files/slip_rep_on_faults_all_data.txt',\n                                  dtype = [('S100'),('S100'),('S100'),('S100'),('S100'),('S100'),('S100'),('S100'),\n                                           ('f8'),('f8'),('f8'),('f8'),('f8'),('f8'),('f8'),('f8'),('f8'),('f8'),('f8'),('f8'),('f8'),('f8')], delimiter = '\\t') \n    model_slip_rep = list(map(lambda i : slip_rep_data[i][1].decode(\"utf-8\"), range(len(slip_rep_data))))\n    MFD_type_sli_rep = list(map(lambda i : slip_rep_data[i][4].decode(\"utf-8\"), range(len(slip_rep_data))))\n    scenario_names_sli_rep = list(map(lambda i : slip_rep_data[i][5].decode(\"utf-8\"), range(len(slip_rep_data))))\n    p_fault_alone = list(map(lambda i : slip_rep_data[i][8], range(len(slip_rep_data))))\n    p_FtF_2 = list(map(lambda i : slip_rep_data[i][9], range(len(slip_rep_data))))\n    p_FtF_3 = list(map(lambda i : slip_rep_data[i][10], range(len(slip_rep_data))))\n    p_FtF_4 = list(map(lambda i : slip_rep_data[i][11], range(len(slip_rep_data))))\n    p_FtF_5 = list(map(lambda i : slip_rep_data[i][12], range(len(slip_rep_data))))\n    p_FtF_6 = list(map(lambda i : slip_rep_data[i][13], range(len(slip_rep_data))))\n    p_FtF_7 = list(map(lambda i : slip_rep_data[i][14], range(len(slip_rep_data))))\n    p_FtF_8 = list(map(lambda i : slip_rep_data[i][15], range(len(slip_rep_data))))\n    p_FtF_9 = list(map(lambda i : slip_rep_data[i][16], range(len(slip_rep_data))))\n    p_FtF_10 = list(map(lambda i : slip_rep_data[i][17], range(len(slip_rep_data))))\n    p_FtF_11 = list(map(lambda i : slip_rep_data[i][18], range(len(slip_rep_data))))\n    p_FtF_12 = list(map(lambda i : slip_rep_data[i][19], range(len(slip_rep_data))))\n    p_FtF_13 = list(map(lambda i : slip_rep_data[i][20], range(len(slip_rep_data))))\n    p_NMS = list(map(lambda i : slip_rep_data[i][21], range(len(slip_rep_data))))\n    list_faults_slip_rep = list(map(lambda i : slip_rep_data[i][7].decode(\"utf-8\"), range(len(slip_rep_data))))\n    \n    for model in Model_list:            \n        for scenario_name in scenarios_names_list :\n            for MFD_type in MFD_type_list:\n                index_sc = np.where(np.array(scenario_names_sli_rep) == scenario_name)[0]\n                index_mfd_type = np.where(np.array(MFD_type_sli_rep) == ('MFD_'+MFD_type))[0]\n                index_m = np.where(np.array(model_slip_rep) == model)[0]\n                index = list(set(index_sc).intersection(index_m))\n                index = list(set(index).intersection(index_mfd_type))\n                p_fault_alone_i = np.take(p_fault_alone,index)\n                p_FtF_2_i = np.take(p_FtF_2,index)\n                p_FtF_3_i = np.take(p_FtF_3,index)\n                p_FtF_4_i = np.take(p_FtF_4,index)\n                p_FtF_5_i = np.take(p_FtF_5,index)\n                p_FtF_6_i = np.take(p_FtF_6,index)\n                p_FtF_7_i = np.take(p_FtF_7,index)\n                p_FtF_8_i = np.take(p_FtF_8,index)\n                p_FtF_9_i = np.take(p_FtF_9,index)\n                p_FtF_10_i = np.take(p_FtF_10,index)\n                p_FtF_11_i = np.take(p_FtF_11,index)\n                p_FtF_12_i = np.take(p_FtF_12,index)\n                p_FtF_13_i = np.take(p_FtF_13,index)\n                p_NMS_i = np.take(p_NMS,index)\n                list_faults_slip_rep_i = np.take(list_faults_slip_rep,index)\n                    \n                \n                list_fault_i = []\n                for fault in list_faults_slip_rep_i :\n                    if fault not in list_fault_i :\n                        list_fault_i.append(fault)\n                        \n                slip_rep_faults_mean = open(Run_name + '/analysis/txt_files/slip_rep_on_faults_mean_'+model+'_' + MFD_type +'_' + scenario_name +'.txt','w') #file with the mean slip repartition for each fault in this scenario\n    \n                for fault in list_fault_i :\n                    index = np.where(list_faults_slip_rep_i == fault)[0]\n                    p_fault_alone_j = np.take(p_fault_alone_i,index)\n                    p_FtF_2_j = np.take(p_FtF_2_i,index)\n                    p_FtF_3_j = np.take(p_FtF_3_i,index)\n                    p_FtF_4_j = np.take(p_FtF_4_i,index)\n                    p_FtF_5_j = np.take(p_FtF_5_i,index)\n                    p_FtF_6_j = np.take(p_FtF_6_i,index)\n                    p_FtF_7_j = np.take(p_FtF_7_i,index)\n                    p_FtF_8_j = np.take(p_FtF_8_i,index)\n                    p_FtF_9_j = np.take(p_FtF_9_i,index)\n                    p_FtF_10_j = np.take(p_FtF_10_i,index)\n                    p_FtF_11_j = np.take(p_FtF_11_i,index)\n                    p_FtF_12_j = np.take(p_FtF_12_i,index)\n                    p_FtF_13_j = np.take(p_FtF_13_i,index)\n                    p_NMS_j = np.take(p_NMS_i,index)\n                    slip_rep_faults_mean.write(fault + '\\t' + str(np.mean(p_fault_alone_j)) + '\\t' + str(np.mean(p_FtF_2_j)) \n                    + '\\t' + str(np.mean(p_FtF_3_j)) + '\\t' + str(np.mean(p_FtF_4_j)) + '\\t' + str(np.mean(p_FtF_5_j)) \n                    + '\\t' + str(np.mean(p_FtF_6_j)) + '\\t' + str(np.mean(p_FtF_7_j)) + '\\t' + str(np.mean(p_FtF_8_j)) \n                    + '\\t' + str(np.mean(p_FtF_9_j)) + '\\t' + str(np.mean(p_FtF_10_j)) + '\\t' + str(np.mean(p_FtF_11_j)) \n                    + '\\t' + str(np.mean(p_FtF_12_j)) + '\\t' + str(np.mean(p_FtF_13_j)) + '\\t' + str(np.mean(p_NMS_j)) +'\\n')\n                \n                \n                slip_rep_faults_mean.close()\n", "meta": {"hexsha": "95a8d2ab8a66e32ce9f6bd0a62a8601547e52da0", "size": 12693, "ext": "py", "lang": "Python", "max_stars_repo_path": "A_SHERIFS_CAD/lib/hm_visual/slip_rate_rep.py", "max_stars_repo_name": "fault2shaESCWG/CentralApenninesLabFAULT2RISK", "max_stars_repo_head_hexsha": "362cbc8b8dda0c2b5ba1e0ef5c9144fb6acb2ed3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A_SHERIFS_CAD/lib/hm_visual/slip_rate_rep.py", "max_issues_repo_name": "fault2shaESCWG/CentralApenninesLabFAULT2RISK", "max_issues_repo_head_hexsha": "362cbc8b8dda0c2b5ba1e0ef5c9144fb6acb2ed3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A_SHERIFS_CAD/lib/hm_visual/slip_rate_rep.py", "max_forks_repo_name": "fault2shaESCWG/CentralApenninesLabFAULT2RISK", "max_forks_repo_head_hexsha": "362cbc8b8dda0c2b5ba1e0ef5c9144fb6acb2ed3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-30T16:39:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-27T17:12:43.000Z", "avg_line_length": 64.7602040816, "max_line_length": 225, "alphanum_fraction": 0.4627747577, "include": true, "reason": "import numpy", "num_tokens": 3481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3040416623541848, "lm_q1q2_score": 0.15558316714849368}}
{"text": "import os, sys\nimport random\nimport time\nimport ntpath\nfrom collections import defaultdict\nimport ntpath\nimport pandas as pd  # Windows users: I copy-paste the pandas,dateutil and pyltz folders from anaconda 2!! into the site-packages folder of pymol(only for temporary use, other wise it gets confused with the paths of the packages)\nimport numpy as np\nfrom pandas import Series\n# Biopython\nfrom Bio import SeqRecord, Alphabet, SeqIO\nfrom Bio.Seq import Seq\nimport Bio.PDB as PDB\nfrom Bio.Seq import MutableSeq\nfrom Bio.PDB.Polypeptide import is_aa\nfrom Bio.SVDSuperimposer import SVDSuperimposer\nfrom pyro.infer.mcmc.api import MCMC\n#Pymol\nimport pymol\nfrom mpl_toolkits.mplot3d import Axes3D\nimport scipy.stats\n# TORCH: \"Tensors\"\nimport torch\nfrom torch.distributions import constraints, transform_to\n# PYRO\nimport pyro\nimport pyro.distributions as dist\nfrom pyro import poutine\nfrom pyro.infer.autoguide import AutoDelta, AutoDiagonalNormal, AutoLowRankMultivariateNormal, init_to_median\nfrom torch.optim import Adam, LBFGS\nfrom pyro.infer import SVI, TraceEnum_ELBO, config_enumerate, Trace_ELBO, TraceGraph_ELBO,JitTrace_ELBO\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport tqdm\ntqdm.monitor_interval = 0\nfrom ignite.handlers import EarlyStopping\nfrom ignite.engine import Engine, Events\nfrom pyro.infer import SVI, EmpiricalMarginal\nfrom pyro.optim import PyroOptim\nfrom pyro.infer.abstract_infer import TracePredictive\nfrom pyro.infer.mcmc import MCMC, NUTS\nfrom pyro.infer.mcmc.util import initialize_model, predictive\nimport torch.multiprocessing as mp\n#mp.set_start_method('spawn') ###For increasing number of chains\n#Other details\nuse_cuda = True\ntqdm.monitor_interval = 0\nmpl.use('agg') #TkAgg\ncuda = torch.device('cuda')\ncuda0 = torch.device('cuda:0')\ncuda2 = torch.device('cuda:1')\nif use_cuda:\n    torch.set_default_tensor_type('torch.cuda.FloatTensor') #PyTorch tensors have a dimension limit of 25 integers in GPU and 64 in CPU\n    device = torch.device(cuda2)\n    print(\"Using the GPU\",torch.cuda.get_device_name(0))\n\nelse:\n    print(\"Using CPU detected\")\ntorch.multiprocessing.set_sharing_strategy('file_system')  # Needed to avoid runtime errors\nclass SVIEngine(Engine):\n    def __init__(self, *args, step_args=None, **kwargs):\n        self.svi = SVI(*args, **kwargs)\n        self._step_args = step_args or {}\n        super(SVIEngine, self).__init__(self._update)\n    def _update(self, engine, batch):\n        return -engine.svi.step(batch, **self._step_args)\nPyroOptim.state_dict = lambda self: self.get_state()\ndef Max_variance(structure):\n    '''Calculates the maximum distance to the origin of the structure, this value will define the variance of the prior's distribution'''\n    centered = Center_torch(structure)\n    mul = centered@torch.t(structure)\n    max_var = torch.sqrt(torch.max(torch.diag(mul)))\n    return max_var\ndef Extract_coordinates_from_PDB(PDB_file,type):\n    ''' Returns both the alpha carbon coordinates contained in the PDB file and the residues coordinates for the desired chains'''\n    from Bio.PDB.PDBParser import PDBParser\n    from Bio.PDB import MMCIFParser\n    Name = ntpath.basename(PDB_file).split('.')[0]\n\n    try:\n        parser = PDB.PDBParser()\n        structure = parser.get_structure('%s' % (Name), PDB_file)\n    except:\n        parser = MMCIFParser()\n        structure = parser.get_structure('%s' % (Name), PDB_file)\n\n    ############## Iterating over residues to extract all of them even if there is more than 1 chain\n    if type=='models':\n        CoordinatesPerModel = []\n        for model in structure:\n            model_coord =[]\n            for chain in model:\n                for residue in chain:\n                    if is_aa(residue.get_resname(), standard=True):\n                            model_coord.append(residue['CA'].get_coord())\n            CoordinatesPerModel.append(model_coord)\n\n        return CoordinatesPerModel\n    elif type=='chains':\n        CoordinatesPerChain=[]\n        for model in structure:\n            for chain in model:\n                chain_coord = []\n                for residue in chain:\n                    if is_aa(residue.get_resname(), standard=True):\n                        chain_coord.append(residue['CA'].get_coord())\n                CoordinatesPerChain.append(chain_coord)\n        return CoordinatesPerChain\n\n    elif type =='all':\n        alpha_carbon_coordinates = []\n        for chain in structure.get_chains():\n            for residue in chain:\n                if is_aa(residue.get_resname(), standard=True):\n                    alpha_carbon_coordinates.append(residue['CA'].get_coord())\n        return alpha_carbon_coordinates\ndef Average_Structure(tuple_struct):\n    average = sum(list(tuple_struct)) / len(\n        tuple_struct)  # sum element-wise the list of tensors containing the coordinates #tf.add_n\n    return average\ndef Center_numpy(Array):\n    '''Centering to the origin the data'''\n    mean = np.mean(Array, axis=0)\n    centered_array = Array - mean\n    return centered_array\ndef Center_torch(Array):\n    '''Centering to the origin the data'''\n    mean = torch.mean(Array, dim=0)\n    centered_array = Array - mean\n    return centered_array\ndef sample_R(ri_vec):\n    \"\"\"Inputs a sample of unit quaternion and transforms it into a rotation matrix\"\"\"\n    # argument i guarantees that the symbolic variable name will be identical everytime this method is called\n    # repeating a symbolic variable name in a model will throw an error\n    # the first argument states that i will be the name of the rotation made\n    theta1 = 2 * np.pi * ri_vec[1]\n    theta2 = 2 * np.pi * ri_vec[2]\n\n    r1 = torch.sqrt(1 - ri_vec[0])\n    r2 = torch.sqrt(ri_vec[0])\n\n    qw = r2 * torch.cos(theta2)\n    qx = r1 * torch.sin(theta1)\n    qy = r1 * torch.cos(theta1)\n    qz = r2 * torch.sin(theta2)\n\n    R = torch.eye(3, 3) # device =cuda\n    # filling the rotation matrix\n    # Evangelos A. Coutsias, et al \"Using quaternions to calculate RMSD\" In: Journal of Computational Chemistry 25.15 (2004)\n\n    # Row one\n    R[0, 0] = qw ** 2 + qx ** 2 - qy ** 2 - qz ** 2\n    R[0, 1] = 2 * (qx * qy - qw * qz)\n    R[0, 2] = 2 * (qx * qz + qw * qy)\n\n    # Row two\n    R[1, 0] = 2 * (qx * qy + qw * qz)\n    R[1, 1] = qw ** 2 - qx ** 2 + qy ** 2 - qz ** 2\n    R[1, 2] = 2 * (qy * qz - qw * qx)\n\n    # Row three\n    R[2, 0] = 2 * (qx * qz - qw * qy)\n    R[2, 1] = 2 * (qy * qz + qw * qx)\n    R[2, 2] = qw ** 2 - qx ** 2 - qy ** 2 + qz ** 2\n    return R\ndef RMSD_numpy(X1, X2):\n    import torch.nn.functional as F\n    return F.pairwise_distance(torch.from_numpy(X1), torch.from_numpy(X2))\ndef RMSD(X1, X2):\n    import torch.nn.functional as F\n    return F.pairwise_distance(X1, X2)\ndef RMSD_biopython(x, y):\n    sup = SVDSuperimposer()\n    sup.set(x, y)\n    sup.run()\n    rot, tran = sup.get_rotran()\n    return rot\ndef Read_Data(prot1,prot2,type='models',models =(0,1),RMSD=True):\n    '''Reads different types of proteins and extracts the alpha carbons from the models, chains or all . The model,\n    chain or aminoacid range numbers are indicated by the tuple models'''\n\n    if type == 'models':\n        X1_coordinates = Extract_coordinates_from_PDB('{}'.format(prot1),type)[models[0]]\n        X2_coordinates = Extract_coordinates_from_PDB('{}'.format(prot2),type)[models[1]]\n    elif type == 'chains':\n        X1_coordinates = Extract_coordinates_from_PDB('{}'.format(prot1),type)[models[0]][1:141]\n        X2_coordinates = Extract_coordinates_from_PDB('{}'.format(prot2),type)[models[1]][0:140]\n\n    elif type == 'all':\n        X1_coordinates = Extract_coordinates_from_PDB('{}'.format(prot1),type)[models[0]:models[1]]\n        X2_coordinates = Extract_coordinates_from_PDB('{}'.format(prot2),type)[models[0]:models[1]]\n\n    #Apply RMSD to the protein that needs to be superimposed\n    X1_Obs_Stacked = Center_numpy(np.vstack(X1_coordinates))\n    X2_Obs_Stacked = Center_numpy(np.vstack(X2_coordinates))\n    if RMSD:\n        X2_Obs_Stacked = torch.from_numpy(np.dot(X2_Obs_Stacked,RMSD_biopython(X1_Obs_Stacked,X2_Obs_Stacked)))\n        X1_Obs_Stacked = torch.from_numpy(X1_Obs_Stacked)\n    else:\n        X1_Obs_Stacked = torch.from_numpy(X1_Obs_Stacked)\n        X2_Obs_Stacked = torch.from_numpy(X2_Obs_Stacked)\n\n    data_obs = (X1_Obs_Stacked,X2_Obs_Stacked)\n\n    # ###PLOT INPUT DATA################\n    x = Center_numpy(np.vstack(X1_coordinates))[:, 0]\n    y=Center_numpy(np.vstack(X1_coordinates))[:, 1]\n    z=Center_numpy(np.vstack(X1_coordinates))[:, 2]\n    fig = plt.figure(figsize=(18, 16), dpi=80)\n    ax = fig.add_subplot(111, projection='3d')\n    plt.plot(x, y, z)\n    ax.plot(x, y,z ,c='b', label='data1',linewidth=3.0)\n    #orange graph\n    x2 = Center_numpy(np.vstack(X2_coordinates))[:, 0]\n    y2=Center_numpy(np.vstack(X2_coordinates))[:, 1]\n    z2=Center_numpy(np.vstack(X2_coordinates))[:, 2]\n    ax.plot(x2, y2,z2, c='r', label='data2',linewidth=3.0)\n    ax.legend()\n    plt.savefig(r\"Initial.png\")\n    plt.clf() #Clear the plot, otherwise it will give an error when plotting the loss\n    plt.close()\n\n    # rmsd = RMSD_numpy(Center_numpy(np.vstack(X1_coordinates)),Center_numpy(np.vstack(X2_coordinates)))\n    # plt.plot(rmsd.numpy())\n    # plt.show()\n    return data_obs\ndef model(data):\n    max_var,data1, data2 = data\n    ### 1. prior over mean M\n    #M = pyro.sample(\"M\", dist.Normal(0, 3).expand_by([data1.size(0),data1.size(1)]).to_event(2))\n    M = pyro.sample(\"M\", dist.StudentT(1,0, 3).expand_by([data1.size(0),data1.size(1)]).to_event(2))\n    ### 2. Prior over variances for the normal distribution\n    U = pyro.sample(\"U\", dist.HalfNormal(1).expand_by([data1.size(0)]).to_event(1))\n    U =  U.reshape(data1.size(0),1).repeat(1,3).view(-1)  #Triplicate the rows for the subsequent mean calculation\n    ## 3. prior over translations T_i: Sample translations for each of the x,y,z coordinates\n    T2 = pyro.sample(\"T2\", dist.Normal(0, 1).expand_by([3]).to_event(1))\n\n    ## 4. prior over rotations R_i\n    ri_vec = pyro.sample(\"ri_vec\",dist.Uniform(0, 1).expand_by([3]).to_event(1))  # Uniform distribution\n    #ri_vec = pyro.sample(\"ri_vec\",dist.Normal(0,0.5).expand_by([3]).to_event(1))  # Weak normal? Apply torch.sigmoid after to ri_vecs\n    R = sample_R(ri_vec)\n    M_T1 = M\n    M_R2_T2 = M @ R + T2\n\n    # 5. Sampling from several Univariate Distributions (approximating the posterior distribution ): The observations are conditionally independant given the U, which is sampled outside the loop\n    #UNIVARIATE NORMALS\n    with pyro.plate(\"plate_univariate\", data1.size(0)*data1.size(1),dim=-1):\n        pyro.sample(\"X1\", dist.StudentT(1,M_T1.view(-1), U),obs=data1.view(-1))\n        pyro.sample(\"X2\", dist.StudentT(1,M_R2_T2.view(-1), U), obs=data2.view(-1))\ndef _get_initial_trace(data_obs, average):\n    '''Initialize MCMC and NUTS. Pyro 0.41'''\n    if use_cuda:\n        data_obs = [data.cuda() for data in data_obs]\n        average = average.cuda()\n    else:\n        pass\n    #INITIALIZE PRIOR:\n    def init_prior(site):\n        if site[\"name\"] == \"ri_vec\":\n            return torch.tensor([0.9, 0.1, 0.9])\n        elif site[\"name\"] == \"M\":\n            return average\n        else:\n            return init_to_median(site)\n    # GUIDE\n    global_guide = AutoDelta(model,init_loc_fn=init_prior)\n    # OPTIMIZER\n    optim = pyro.optim.AdagradRMSProp(dict()) #https://github.com/pyro-ppl/pyro/blob/58277184310ef76a62420a38c300e84cd12b88ad/pyro/optim/adagrad_rmsprop.py\n    elbo = JitTrace_ELBO()\n    # STOCHASTIC VARIATIONAL INFERENCE\n    svi_engine = SVIEngine(model, global_guide, optim, loss=elbo)\n    pbar = tqdm.tqdm()\n    loss_list = []\n    # INITIALIZING PRIOR : Changing in the first iteration the value for the prior in order to constrain the prior over the rotations\n    #pyro.param(\"auto_ri_vec\", torch.Tensor([0.9, 0.1, 0.9]),constraint=constraints.unit_interval)  # constraint = constraints.simplex doesn't work exactly\n    # Initialize the Mean Structure (each coordinate separately): NO CONSTRAINTS!!!\n    #pyro.param(\"auto_M\",average)\n    @svi_engine.on(Events.EPOCH_COMPLETED)\n    def update_progress(svi_engine):\n        pbar.update(1)\n        loss_list.append(-svi_engine.state.output)\n        pbar.set_description(\n            \"[epoch {}] avg train loss: {}\".format(svi_engine.state.epoch, svi_engine.state.output))\n    # HANDLER\n    handler = EarlyStopping(patience=25, score_function=lambda eng: eng.state.output, trainer=svi_engine)\n    # SVI\n    svi_engine.add_event_handler(Events.EPOCH_COMPLETED, handler)\n    svi_engine.run([data_obs], max_epochs=15000)\n    #return svi_engine.svi.exec_traces\n    return global_guide.median()\ndef Run(data_obs, average,name1):\n    if use_cuda:\n        data_obs = [data.cuda() for data in data_obs]\n        average = average.cuda()\n    else:\n        pass\n    ###POSTERIOR PROBABILITY calculations: MCMC and NUTS\n    # I had to fix a problem at /home/lys/anaconda3/lib/python3.5/site-packages/pyro/util.py by initializing the seed to rng_seed = random.randint(0,2**32-1)\n    map_points = _get_initial_trace(data_obs,average)\n    # MCMC initialization\n    chains=1\n    warmup= 500\n    samples = 1000\n    initialize = False\n    if initialize:\n        print(\"Initializing with MAP estimation\")\n        #Initialize NUTS's trace with the MAP estimate of the model\n        init_params, potential_fn, transforms, _ = initialize_model(model,model_args=(data_obs,), num_chains=chains,jit_compile=True,skip_jit_warnings=True)\n        map_points = _get_initial_trace(data_obs, average)\n        init_params = {name: transforms[name](value).detach() for name, value in map_points.items()}\n        # Choose NUTS kernel given the initialized potential function and a maximum tree depth limit.\n        nuts_kernel = NUTS(potential_fn=potential_fn, max_tree_depth=8, target_accept_prob=0.8,jit_compile=True)\n        # Prepare MCMC with NUTS kernel with the given arguments. Run over the observed data X1 and X2\n        mcmc = MCMC(nuts_kernel, num_samples=samples, warmup_steps=warmup, num_chains=chains,initial_params=init_params, transforms=transforms)\n        mcmc.run(data_obs)\n    else:\n        # Running MCMC using NUTS as selected kernel\n        nuts_kernel = NUTS(model, jit_compile=True, ignore_jit_warnings=True, max_tree_depth=8)\n        nuts_kernel.initial_trace = _get_initial_trace(data_obs, average)\n        mcmc = MCMC(nuts_kernel, num_samples=samples, warmup_steps=warmup, num_chains=chains)\n        mcmc.run(data_obs)\n    max_var, data1, data2 = data_obs\n    #######SAMPLES FROM THE POSTERIOR\n    mcmc_samples = mcmc.get_samples()\n    #######PARAMETERS:\n    #ROTATION\n    ri_vec_post_samples = mcmc_samples[\"ri_vec\"]\n    ri_vec_mean = ri_vec_post_samples.mean(dim=0)\n    ri_vec_variance = ri_vec_post_samples.var(dim=0)\n    R = sample_R(ri_vec_mean)\n    # MEAN STRUCTURE\n    M_post_samples = mcmc_samples[\"M\"]\n    M = M_post_samples.mean(dim=0)\n    M_variance = M_post_samples.var(dim=0)\n    #TRANSLATION\n    T2_post_samples = mcmc_samples[\"T2\"]\n    T2_mean = T2_post_samples.mean(dim=0)\n    T2_variance = T2_post_samples.var(dim=0)\n\n    def Old_sampling_extraction():\n        '''Pyro 0.41 mcmc sampling'''\n        #Rotation matrix stats\n        ri_vec_marginal_1 = mcmc.marginal(sites=[\"ri_vec\"])\n        ri_vec_marginal_1 = torch.cat(list(ri_vec_marginal_1.support(flatten=True).values()), dim=-1).cpu().numpy() #Where the samples are stored\n        params = ['ri_vec[0]','ri_vec[1]','ri_vec[2]']\n        df = pd.DataFrame(ri_vec_marginal_1, columns= params).transpose()\n        df_summary = df.apply(pd.Series.describe, axis=1)[[\"mean\", \"std\", \"25%\", \"50%\", \"75%\"]]\n        df_summary.to_csv(\"ri_vec_stats_{}.txt\".format(name1),sep='\\t')\n        # Rotation matrix output\n        ri_vec_marginal = mcmc.marginal([\"ri_vec\"]).empirical[\"ri_vec\"]\n        ri_vec_mean = ri_vec_marginal.mean\n        ri_vec_variance = ri_vec_marginal.variance\n        R = sample_R(ri_vec_mean)\n\n        # Mean structure stats\n        M_marginal_1 = mcmc.marginal(sites=[\"M\"])\n        M_marginal_1 = torch.cat(list(M_marginal_1.support(flatten=True).values()), dim=-1).cpu().numpy()\n        params = ['M[{}]'.format(i) for i in range(0,len(data1))]\n        label_one = np.array(params)\n        label_two = np.array(['x', 'y', 'z'])\n        cols = pd.MultiIndex.from_product([label_one, label_two])\n        df = pd.DataFrame(M_marginal_1.T.reshape(samples, -1), columns=cols).transpose()\n        df_summary = df.apply(pd.Series.describe, axis=1)[[\"mean\", \"std\", \"25%\", \"50%\", \"75%\"]]\n        df_summary.to_csv(\"M_stats_{}.txt\".format(name1),sep='\\t')\n\n        # Mean structure M output\n        M_vec_marginal = mcmc.marginal([\"M\"]).empirical[\"M\"]\n        M_vec_mean = M_vec_marginal.mean\n        M_vec_variance= M_vec_marginal.variance\n        M = M_vec_mean\n        #M = Center_torch(M_vec_mean.detach())\n\n        # Translation stats\n        T_marginal_1 = mcmc.marginal(sites=[\"T2\"])\n        T_marginal_1 = torch.cat(list(T_marginal_1.support(flatten=True).values()), dim=-1).cpu().numpy()\n        params = ['T[0]','T[1]','T[2]']\n        df = pd.DataFrame(T_marginal_1, columns= params).transpose()\n        df_summary = df.apply(pd.Series.describe, axis=1)[[\"mean\", \"std\", \"25%\", \"50%\", \"75%\"]]\n        df_summary.to_csv(\"T_stats_{}.txt\".format(name1),sep='\\t')\n        # Translation T output\n        T2_vec_marginal = mcmc.marginal([\"T2\"]).empirical[\"T2\"]\n        T2_vec_mean = T2_vec_marginal.mean\n        T2_vec_variance = T2_vec_marginal.variance\n\n    #Observed\n    X1 = data1.detach().cpu().numpy() #- T1_vec_mean.cpu().numpy()  # X1 -T1\n    X2 = np.dot(data2.detach().cpu().numpy() - T2_mean.cpu().numpy(), np.transpose(R.cpu()))  # (X2-T2)R-1\n\n\n    import matplotlib\n    matplotlib.rcParams['legend.fontsize'] = 10\n\n    #################PLOTS################################################\n    fig = plt.figure(figsize=(18, 16), dpi=80)\n    ax = fig.add_subplot(111, projection='3d')\n\n    # blue graph\n    x = X1[:, 0]\n    y = X1[:, 1]\n    z = X1[:, 2]\n\n    ax.plot(x, y, z, c='b', label='X1', linewidth=3.0)\n\n    # red graph\n    x2 = X2[:, 0]\n    y2 = X2[:, 1]\n    z2 = X2[:, 2]\n\n    ax.plot(x2, y2, z2, c='r', label='X2', linewidth=3.0)\n\n    ###green graph\n    x3 = M.cpu().numpy()[:, 0]\n    y3 = M.cpu().numpy()[:, 1]\n    z3 = M.cpu().numpy()[:, 2]\n    #ax.plot(x3, y3, z3, c='g', label='M', linewidth=3.0)\n    ax.legend()\n\n    plt.title(\"Initialized MCMC and NUTS model\")\n    plt.savefig(\"{}_PLOTS_and_FILES_PYRO/Bayesian_Result_Samples_{}_{}_chains_{}\".format(name1,name1,samples + warmup,chains))\n\n    plt.clf()\n    plt.plot(RMSD(data1.cpu(),data2.cpu()).numpy(), linewidth = 8.0)\n    plt.plot(RMSD(torch.from_numpy(X1),torch.from_numpy(X2)).numpy(), linewidth=8.0)\n    plt.ylabel('Pairwise distances',fontsize='46')\n    plt.xlabel('Amino acid position',fontsize='46')\n    plt.title('{}'.format(name1.upper()),fontsize ='46')\n    plt.gca().legend(('RMSD', 'Theseus-PP'),fontsize='40')\n    plt.savefig(\"{}_PLOTS_and_FILES_PYRO/Distance_Differences_Average_Bayesian_{}\".format(name1,name1))\n    plt.close()\n\n\n\n    return T2_mean.cpu().numpy(), R.cpu(), M.cpu().numpy(), X1, X2, ri_vec_post_samples.cpu().numpy(),M_post_samples.cpu().numpy(),T2_post_samples.cpu().numpy() #Values for the mean structure\ndef Write_PDB(initialPDB, Rotation, Translation):\n    ''' Transform the atom coordinates from the original PDB file and overwrite it '''\n    from Bio.PDB.PDBParser import PDBParser\n    from Bio.PDB import MMCIFParser, PDBIO\n    Name = ntpath.basename(initialPDB).split('.')[0]\n\n    try:\n        parser = PDB.PDBParser()\n        structure = parser.get_structure('%s' % (Name), initialPDB)\n    except:\n        parser = MMCIFParser()\n        structure = parser.get_structure('%s' % (Name), initialPDB)\n    for atom in structure.get_atoms():\n        atom.transform(Rotation, -Translation)\n    io = PDBIO()\n    io.set_structure(structure)\n    io.save(\"Transformed_{}\".format(ntpath.basename(initialPDB)))\ndef write_ATOM_line(structure, file_name):\n    import os\n    \"\"\"Transform coordinates to PDB file: Add intermediate coordinates to be able to visualize Mean structure in PyMOL\"\"\"\n    expanded_structure = np.ones(shape=(2 * len(structure) - 1, 3))  # The expanded structure contains extra rows between the alpha carbons\n    averagearray = np.zeros(shape=(len(structure) - 1, 3))  # should be of size len(structure) -1\n    for index, row in enumerate(structure):\n        if index != len(structure) and index != len(structure) - 1:\n            averagearray[int(index)] = (structure[int(index)] + structure[int(index) + 1]) / 2\n        else:\n            pass\n    # split the expanded structure in sets , where each set will be structure[0] + number*average\n    # The even rows of the 'expanded structure' are simply the rows of the original structure\n    expanded_structure[0::2] = structure\n    expanded_structure[1::2] = averagearray\n    structure = expanded_structure\n    aa_name = \"ALA\"\n    aa_type = \"CA\"\n    if os.path.isfile(file_name):\n        os.remove(file_name)\n        for i in range(len(structure)):\n            with open(file_name, 'a') as f:\n                f.write(\n                    \"ATOM{:7d} {}   {} A{:4d}{:12.3f}{:8.3f}{:8.3f}  0.00  0.00    X    \\n\".format(i, aa_type, aa_name,\n                                                                                                   i, structure[i, 0],\n                                                                                                   structure[i, 1],\n                                                                                                   structure[i, 2]))\n    else:\n        for i in range(len(structure)):\n            with open(file_name, 'a') as f:\n                f.write(\n                    \"ATOM{:7d} {}   {} A{:4d}{:12.3f}{:8.3f}{:8.3f}  0.00  0.00    X    \\n\".format(i, aa_type, aa_name,\n                                                                                                   i, structure[i, 0],\n                                                                                                   structure[i, 1],\n                                                                                                   structure[i, 2]))\ndef Pymol(*args):\n    '''Visualization program'''\n    #LAUNCH PYMOL\n    launch=False\n    if launch:\n        pymol.pymol_argv = ['pymol'] + sys.argv[1:]\n        pymol.finish_launching(['pymol'])\n    def Colour_Backbone(selection,color,color_digit):\n        #pymol.cmd.select(\"alphas\", \"name ca\") #apparently nothing is ca\n        #pymol.cmd.select(\"sidechains\", \"! alphas\") #select the opposite from ca, which should be the side chains, not working :(\n        pymol.cmd.show(\"sticks\", selection)\n        pymol.cmd.set_color(color,color_digit)\n        pymol.cmd.color(color,selection)\n\n    # Load Structures and apply the function\n    #colornames=['red','green','blue','orange','purple','yellow','black','aquamarine']\n    #Palette of colours\n    pal1 = sns.color_palette(\"OrRd\",1)\n    pal2 = sns.color_palette(\"PuBuGn_d\",100) #RGB numbers for the palette colours\n    colornames1 = [\"red_{}\".format(i) for i in range(0, len(pal1))]#So that X1 is red\n    colornames2 = [\"blue_{}\".format(i) for i in range(0,len(pal2))]\n    colornames = colornames1 + colornames2\n    pal = pal1 + pal2\n\n    snames=[]\n    for file,color,color_digit in zip(args,colornames,pal):\n        sname = ntpath.basename(file)\n        snames.append(sname)\n        pymol.cmd.load(file, sname) #discrete 1 will create different sets of atoms for each model\n        pymol.cmd.bg_color(\"white\")\n        pymol.cmd.extend(\"Colour_Backbone\", Colour_Backbone)\n        Colour_Backbone(sname,color,color_digit)\n    print(snames[0].split('_')[1])\n    exit()\n    pymol.cmd.png(\"{}_PLOTS_and_FILES_PYRO/Superposition_Bayesian_Pymol_{}\".format(snames[0].split('_')[1],snames[0].split('_')[1]))\ndef Pymol_Samples(data1,data2,name1,R_samples,T_samples,samples):\n    '''Create the PDB files to be sent to plot to PyMOL'''\n    #Process the dataframes\n    R_samples = torch.from_numpy(R_samples)\n    indexes = random.sample(range(0, samples), samples) #not warm up samples\n    X1 = data1.detach().cpu().numpy()\n    plt.clf()\n    plt.plot(RMSD(data1.cpu(), data2.cpu()).numpy(), linewidth=2.0)\n    for i in range(0,samples):\n        Rotation = sample_R(R_samples[i,:]) #torch\n        Translation = T_samples[i,:] #numpy\n        X2 = np.dot(data2.numpy() - Translation, np.transpose(Rotation.cpu().numpy()))\n        write_ATOM_line(X2, os.path.join(\"{}_PLOTS_and_FILES_PYRO\".format(name1),'Result_MCMC_{}_X2_{}.pdb'.format(name1,i)))\n        plt.plot(RMSD(torch.from_numpy(X1), torch.from_numpy(X2)).numpy(), linewidth=0.5,color = plt.cm.autumn(i))\n    plt.ylabel('Pairwise distances', fontsize='10')\n    plt.xlabel('Amino acid position', fontsize='10')\n    plt.title('{}'.format(name1.upper()), fontsize='10')\n    plt.gca().legend(('RMSD', 'Theseus-PP'), fontsize='10')\n    plt.savefig(\"{}_PLOTS_and_FILES_PYRO/Distance_Differences_Bayesian_{}.png\".format(name1,name1),dpi=600)\n    plt.close()\n    names = [os.path.join(\"{}_PLOTS_and_FILES_PYRO\".format(name1),'Result_MCMC_{}_X2_{}.pdb'.format(name1,i)) for i in indexes] #exchange indexes with range(0,samples)\n    Pymol(*names)\ndef Folders(folder_name):\n    \"\"\" Folder for all the generated images It will updated everytime!!! Save the previous folder before running again. Creates folder in current directory\"\"\"\n    import os\n    import shutil\n    basepath = os.getcwd()\n    if not basepath:\n        newpath = folder_name\n    else:\n        newpath = basepath + \"/%s\" % folder_name\n\n    if not os.path.exists(newpath):\n        try:\n            original_umask = os.umask(0)\n            os.makedirs(newpath, 0o777)\n        finally:\n            os.umask(original_umask)\n    else:\n        shutil.rmtree(newpath)  # removes all the subdirectories!\n        os.makedirs(newpath,0o777)\n\n#if __name__ == \"__main__\":\nname1 = '2lmp' #2nl7:139 #2do0=114\nname2 ='2lmp'\nmodels = (0,3)\nsamples =100\nprint(name1 + \"\\t\" + str(models))\nFolders(\"{}_PLOTS_and_FILES_PYRO\".format(name1))\ndata_obs = Read_Data('../PDB_files/{}.pdb'.format(name1), '../PDB_files/{}.pdb'.format(name2),type='models',models =models,RMSD=True)\nmax_var = Max_variance(data_obs[0])\naverage = Average_Structure(data_obs)\ndata1, data2 = data_obs\n\nwrite_ATOM_line(data1, os.path.join(\"{}_PLOTS_and_FILES_PYRO\".format(name1),'RMSD_{}_data1.pdb'.format(name1)))\nwrite_ATOM_line(data2, os.path.join(\"{}_PLOTS_and_FILES_PYRO\".format(name1),'RMSD_{}_data2.pdb'.format(name1)))\n#Pymol('{}_PDB_files/RMSD_{}_data1.pdb'.format(name1,name1), '{}_PDB_files/RMSD_{}_data2.pdb'.format(name2,name2))\ndata_obs = max_var, data1, data2\nstart  = time.time()\nT2, R, M, X1, X2, ri_vec_samples,M_samples,T_samples = Run(data_obs, average,name1)\nstop = time.time()\n\n\nprint(\"Time:\", stop-start)\nprint('Memory Usage:')\nprint('Allocated:', round(torch.cuda.memory_allocated(0) / 1024 ** 3, 1), 'GB')\nprint('Cached:   ', round(torch.cuda.memory_cached(0) / 1024 ** 3, 1), 'GB')\nwrite_ATOM_line(M, 'M.pdb')\nwrite_ATOM_line(X1, os.path.join(\"{}_PLOTS_and_FILES_PYRO\".format(name1),'Result_MCMC_{}_X1.pdb'.format(name1)))\nwrite_ATOM_line(X2, os.path.join(\"{}_PLOTS_and_FILES_PYRO\".format(name1),'Result_MCMC_{}_X2.pdb'.format(name2)))\n#Write_PDB(r\"../PDB_files/{}.pdb\".format(name1), np.transpose(R), T1)\n#Write_PDB(r\"../PDB_files/{}.pdb\".format(name2), np.transpose(R), T2)\n#Pymol(\"Result_MCMC_{}_X1.pdb\".format(name1), \"Result_MCMC_{}_X2.pdb\".format(name2))\nPymol_Samples(data1,data2,name1,ri_vec_samples,T_samples,samples)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "ef26bf287205ad2739286d81cfb23aa5d4ff35e3", "size": 27528, "ext": "py", "lang": "Python", "max_stars_repo_path": "Superposition_Bayesian.py", "max_stars_repo_name": "LysSanzMoreta/BayesTheseus-PP", "max_stars_repo_head_hexsha": "6ffc93b6f8058733bbc3d24e0af240934e01ead5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Superposition_Bayesian.py", "max_issues_repo_name": "LysSanzMoreta/BayesTheseus-PP", "max_issues_repo_head_hexsha": "6ffc93b6f8058733bbc3d24e0af240934e01ead5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Superposition_Bayesian.py", "max_forks_repo_name": "LysSanzMoreta/BayesTheseus-PP", "max_forks_repo_head_hexsha": "6ffc93b6f8058733bbc3d24e0af240934e01ead5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.7609756098, "max_line_length": 229, "alphanum_fraction": 0.654824179, "include": true, "reason": "import numpy,import scipy", "num_tokens": 7679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.26588047891687405, "lm_q1q2_score": 0.1555669712472154}}
{"text": "import numpy as np\nimport os\nfrom researchUtils import Constants\n\nclass DMC:\n    def __init__(self,\n                 simName = \"DMC_Sim\",\n                 outputFolder = \"DMCResults/\",\n                 weighting = 'discrete',\n                 initialWalkers = 1000,\n                 nTimeSteps = 10000,\n                 equilTime = 2000,\n                 wfnSpacing = 1000,\n                 DwSteps = 50,\n                 atoms = [],\n                 dimensions = 3,\n                 deltaT = 5,\n                 D = 0.5,\n                 potential=None,\n                 masses = None,\n                 startStructure = None,\n                 branch_every = 1\n                 ):\n        \"\"\"\n        :param simName:Simulation name for saving wavefunctions\n        :type simName:str\n        :param outputFolder:The folder where the results will be stored, including wavefunctions and energies\n        :type outputFolder:str\n        :param weighting:Discrete or Continuous weighting DMC.  Continuous means that there are fixed number of walkers\n        :type weighting:str\n        :param initialWalkers:Number of walkers we will start the simulation with\n        :type initialWalkers:int\n        :param nTimeSteps:Total time steps we will be propagating the walkers.  nTimeSteps*deltaT = total time in A.U.\n        :type nTimeSteps:int\n        :param equilTime: Time before we start collecting wavefunctions\n        :type equilTime:int\n        :param wfnSpacing:How many time steps in between we will propagate before collecting another wavefunction\n        :type wfnSpacing:int\n        :param DwSteps:Number of time steps for descendant weighting.\n        :type DwSteps: int\n        :param atoms:List of atoms for the simulation\n        :type atoms:list\n        :param dimensions: 3 leads to a 3N dimensional simulation. This should always be 3 for real systems.\n        :type dimensions:int\n        :param deltaT: The length of the time step; how many atomic units of time are you going in one time step.\n        :type deltaT: int\n        :param D: Diffusion Coefficient.  Usually set at 0.5\n        :type D:float\n        :param potential: Takes in coordinates, gives back energies\n        :type potential: function\n        :param masses:For feeding in artificial masses in atomic units.  If not, then the atoms param will designate masses\n        :type masses: list\n        :param startStructure:An initial structure to initialize all your walkers\n        :type startStructure:np.ndarray\n        \"\"\"\n        self.atoms=atoms\n        self.simName = simName\n        self.outputFolder = outputFolder\n        self.initialWalkers = initialWalkers\n        self.nTimeSteps = nTimeSteps\n        self.potential = potential\n        self.weighting = weighting\n        self.DwSteps=DwSteps\n        self.branch_every = branch_every\n        self.branch_step = np.arange(0,nTimeSteps,self.branch_every)\n        self.WfnSaveStep = np.arange(equilTime,nTimeSteps,wfnSpacing)\n        self.DwSaveStep = self.WfnSaveStep+self.DwSteps\n        self.whoFrom = None #Not descendant weighting yet\n        self.walkerV = np.zeros(self.initialWalkers)\n        self.vrefAr = np.zeros(self.nTimeSteps)\n        self.popAr = np.zeros(self.nTimeSteps)\n        self.deltaT = deltaT\n        self.alpha = 1.0 / (2.0 * deltaT)  # simulation parameter - adjustable\n        if startStructure is None:\n            self.walkerC = np.zeros((self.initialWalkers,len(atoms),dimensions))\n        else:\n            self.walkerC = np.repeat(np.expand_dims(startStructure, axis=0), self.initialWalkers, axis=0)\n        if masses is None:\n            masses = np.array([ Constants.mass(a) for a in self.atoms ])\n        self.sigmas = np.sqrt((2 * D * deltaT) / masses)\n        if not os.path.isdir(self.outputFolder):\n            os.makedirs(self.outputFolder)\n        if self.weighting == 'continuous':\n            self.contWts = np.ones(self.initialWalkers)\n        else:\n            self.contWts = None\n\n    def birthOrDeath_vec(self,vref, Desc):\n        \"\"\"\n        Chooses whether or not the walker made a bad enough random walk to be removed from the simulation.\n        For discrete weighting, this leads to removal or duplication of the walkers.  For continuous, this leads\n         to an update of the weights and a potential branching of a large weight walker to the smallest one\n         \"\"\"\n        if self.weighting == 'discrete':\n            randNums = np.random.random(len(self.walkerC))\n            deathMask = np.logical_or((1 - np.exp(-1. * (self.walkerV - vref) * self.deltaT)) < randNums, self.walkerV < vref)\n            self.walkerC = self.walkerC[deathMask]\n            self.walkerV = self.walkerV[deathMask]\n            randNums = randNums[deathMask]\n            if Desc:\n                self.whoFrom = self.whoFrom[deathMask]\n\n            birthMask = np.logical_and((np.exp(-1. * (self.walkerV - vref) * self.deltaT) - 1) > randNums, self.walkerV < vref)\n            self.walkerC = np.concatenate((self.walkerC, self.walkerC[birthMask]))\n            self.walkerV = np.concatenate((self.walkerV, self.walkerV[birthMask]))\n            if Desc:\n                self.whoFrom = np.concatenate((self.whoFrom, self.whoFrom[birthMask]))\n            return self.whoFrom,self.walkerC,self.walkerV\n        else:\n            self.contWts = self.contWts*np.exp(-1.0*(self.walkerV - vref) * self.deltaT)\n            thresh = 1.0/self.initialWalkers\n            killMark = np.where(self.contWts < thresh)[0]\n            for walker in killMark:\n                maxWalker = np.argmax(self.contWts)\n                self.walkerC[walker] = np.copy(self.walkerC[maxWalker])\n                self.walkerV[walker] = np.copy(self.walkerV[maxWalker])\n                if Desc:\n                    self.whoFrom[walker]=self.whoFrom[maxWalker]\n                self.contWts[maxWalker] /= 2.0\n                self.contWts[walker] = np.copy(self.contWts[maxWalker])\n            return self.contWts,self.whoFrom,self.walkerC,self.walkerV\n\n    def moveRandomly(self,walkerC):\n        disps = np.random.normal(0.0, self.sigmas, size=np.shape(walkerC.transpose(0,2,1))).transpose(0,2,1)\n        return walkerC + disps\n\n    def getVref(self):  # Use potential of all walkers to calculate vref\n        \"\"\"\n             Use the energy of all walkers to calculate vref with a correction for the fluctuation in the population\n             or weight.\n         \"\"\"\n        if self.weighting == 'discrete':\n            Vbar = np.average(self.walkerV)\n            correction = (len(self.walkerV) - self.initialWalkers) / self.initialWalkers\n        else:\n            Vbar = np.average(self.walkerV,weights=self.contWts)\n            correction = (np.sum(self.contWts - np.ones(self.initialWalkers))) / self.initialWalkers\n        vref = Vbar - (self.alpha * correction)\n        return vref\n\n    def propagate(self):\n        \"\"\"\n             The main DMC loop.\n             1. Move Randomly\n             2. Calculate the Potential Energy\n             3. Birth/Death\n             4. Update Vref\n             Additionally, checks when the wavefunction has hit a point where it should save / start descendent\n             weighting.\n         \"\"\"\n        DW=False\n        for prop in range(self.nTimeSteps):\n            if prop % 100 == 0:\n                print(f'propagation step {prop}')\n                if self.weighting == 'discrete':\n                    print(f'num walkers : {len(self.walkerC)}')\n            self.walkerC = self.moveRandomly(self.walkerC)\n            self.walkerV = self.potential(self.walkerC)\n            if prop == 0:\n                Vref = self.getVref()\n            if prop in self.WfnSaveStep:\n                dwts = np.zeros(len(self.walkerC))\n                parent = np.copy(self.walkerC)\n                self.whoFrom = np.arange(len(self.walkerC))\n                DW = True\n            if prop in self.DwSaveStep:\n                DW = False\n                if self.weighting == 'discrete':\n                    unique, counts = np.unique(self.whoFrom, return_counts=True)\n                    dwts[unique]=counts\n                else:\n                    for q in range(len(self.contWts)):\n                        dwts[q] = np.sum(self.contWts[self.whoFrom == q])\n                np.savez(self.outputFolder+\"/\"+self.simName+\"_wfn_\"+str(prop-self.DwSteps)+\"ts\",\n                         coords=parent,\n                         weights=dwts,\n                         nDw = self.DwSteps,\n                         atms = self.atoms,\n                         vref=self.vrefAr\n                         )\n            if prop in self.branch_step:\n                print(f\"branching at step {prop}\")\n                if self.weighting=='discrete':\n                    self.whoFrom, self.walkerC, self.walkerV = self.birthOrDeath_vec(Vref,DW)\n                else:\n                    self.contWts,self.whoFrom, self.walkerC, self.walkerV = self.birthOrDeath_vec(Vref, DW)\n            else:\n                if self.weighting=='continuous':\n                    self.contWts = self.contWts*np.exp(-1.0*(self.walkerV - Vref) * self.deltaT)\n\n            Vref = self.getVref()\n            self.vrefAr[prop] = Vref\n            self.popAr[prop] = len(self.walkerC)\n    def run(self):\n        self.propagate()\n        np.save(self.outputFolder+\"/\"+self.simName+\"_energies.npy\",Constants.convert(self.vrefAr,\"wavenumbers\",to_AU=False))\n        if self.weighting == 'discrete':\n            np.save(self.outputFolder + \"/\" + self.simName + \"_population\" + \".npy\",self.popAr)\n\n\nif __name__ == \"__main__\":\n    def PatrickShingle(cds):\n        import subprocess as sub\n        np.savetxt(\"PES/PES0/hoh_coord.dat\", cds.reshape(cds.shape[0]*cds.shape[1],cds.shape[-1]), header=str(len(cds)), comments=\"\")\n        sub.run('./calc_h2o_pot', cwd='PES/PES0')\n        return np.loadtxt('PES/PES0/hoh_pot.dat')\n\n    # def protCluster(cds):\n    #     atms = ['H','H','H','O','H','H','O','H','H','O']\n    #     import subprocess as sub\n    #     import multiprocessing as mp\n    #     splt = np.array_split(cds,mp.cpu_count())\n    #     for k in range(mp.cpu_count()):\n    #         tmm2 = time.time()\n    #         fllK = open('big'+str(k)+'coord.dat','w+')\n    #         fllK.write(\"10\\n\")\n    #         fllK.write(\"%d\\n\" % len(splt[k]))\n    #         for walk in range(len(splt[k])):\n    #             for atm in range(len(atms)):\n    #                 fllK.write(\"%0.18f %0.18f %0.18f %s\\n\" % (splt[k][walk,atm,0],splt[k][walk,atm,1],splt[k][walk,atm,2],atms[atm]))\n    #         fllK.close()\n    #     print(f'THAT took {time.time() - tmm2} seconds.')\n    #     sub.call('runPots.sh')\n    #     vprime = np.loadtxt(\"big1/eng_dip.dat\")[:,0]\n    #     for k in range(2,mp.cpu_count+1):\n    #         v = np.concatenate(vprime,np.loadtxt(\"big\"+str(k)+\"/eng_dip.dat\")[:,0])\n    #     return v\n    def HODMC(cds):\n        omega = Constants.convert(3000.,'wavenumbers',to_AU=True)\n        mass = Constants.mass('H',to_AU=True)\n        return np.squeeze(0.5*mass*omega**2*cds**2)\n\n    dmc_HO = DMC(simName = \"DMC_con_test\",\n                   outputFolder=\"~/HODMC/\",\n                   weighting='discrete',\n                   initialWalkers=10000,\n                   nTimeSteps=10000+1,\n                   equilTime=1000,\n                   wfnSpacing=5000,\n                   DwSteps=50,\n                   atoms=['H'],\n                   dimensions=1,\n                   deltaT=5,\n                   D=0.5,\n                   potential=HODMC,\n                   masses=None,\n                   startStructure = Constants.convert(\n                       np.array([[0.00000]]),\"angstroms\",to_AU=True))\n    dmc_HO.run()\n    # dmcTrimer = DMC(simName = \"DMC_con_test\",\n    #                outputFolder=\"DMCResults/\",\n    #                weighting='discrete',\n    #                initialWalkers=1000,\n    #                nTimeSteps=1000+1,\n    #                equilTime=500,\n    #                wfnSpacing=100,\n    #                DwSteps=50,\n    #                atoms=['H','H','H','O','H','H','O','H','H','O'],\n    #                dimensions=3,\n    #                deltaT=5,\n    #                D=0.5,\n    #                potential=protCluster,\n    #                masses=None,\n    #                startStructure = Constants.convert(\n    #                    np.array([[0.00000, 0.91527, -0.05817],\n    #                        [0.00000, 1.67720, 0.53729],\n    #                        [-0.87302, 0.35992, 0.01707],\n    #                        [2.56267, -0.75858, 0.76451],\n    #                        [2.70113, -0.40578, -0.73813],\n    #                        [2.07091, -0.46191, -0.00993],\n    #                        [0.87302, 0.35993, 0.01707],\n    #                        [-2.70115, -0.40575, -0.73811],\n    #                        [-2.56265, -0.75862, 0.76451],\n    #                        [-2.07092, -0.46190, -0.00993]]\n    #                             )* 1.01\n    #                    ,\"angstroms\",to_AU=True))\n    # dmcTrimer.run()\n", "meta": {"hexsha": "3e44d34f84192a14e6f2e6df397f124701636d75", "size": 12985, "ext": "py", "lang": "Python", "max_stars_repo_path": "_posts/DiffusionMonteCarloCode/GeneralDMC-master/DMC_General.py", "max_stars_repo_name": "adambaskerville/jekyll-theme-chirpy", "max_stars_repo_head_hexsha": "0c7d419af473ccdeef79d7d44bcf2824ad8d3c59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-20T15:29:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T15:29:52.000Z", "max_issues_repo_path": "_posts/DiffusionMonteCarloCode/GeneralDMC-master/DMC_General.py", "max_issues_repo_name": "adambaskerville/jekyll-theme-chirpy", "max_issues_repo_head_hexsha": "0c7d419af473ccdeef79d7d44bcf2824ad8d3c59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_posts/DiffusionMonteCarloCode/GeneralDMC-master/DMC_General.py", "max_forks_repo_name": "adambaskerville/jekyll-theme-chirpy", "max_forks_repo_head_hexsha": "0c7d419af473ccdeef79d7d44bcf2824ad8d3c59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.7086330935, "max_line_length": 135, "alphanum_fraction": 0.5449364652, "include": true, "reason": "import numpy", "num_tokens": 3273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.23370636225126956, "lm_q1q2_score": 0.15551067798693988}}
{"text": "import numpy as np\nfrom fractions import Fraction\nfrom collections import namedtuple\n\n\n# | prefer name | other names | intervals |\nDIATONIC_SCALES = [\n    ['ionian mode', ['mjaor scale'], [0, 2, 4, 5, 7, 9, 11]],\n    ['dorian mode', [], [0, 2, 3, 5, 7, 9, 10]],\n    ['phrygian mode', [], [0, 1, 3, 5, 7, 8, 10]],\n    ['lydian mode', [], [0, 2, 4, 6, 7, 9, 11]],\n    ['mixolydian scale', [], [0, 2, 4, 5, 7, 9, 10]],\n    ['aeolian mode', ['nature minor mode'], [0, 2, 3, 5, 7, 8, 10]],\n    ['locrian mode', [], [0, 1, 3, 5, 6, 8, 10]]\n]\n\n# | prefer name | other names | intervals | index to diatonic scale | operations |\nMELODIC_MINOR_SCALES = [\n    ['ascending melodic minor', [], [0, 2, 3, 5, 7, 9, 11], DIATONIC_SCALES[0], ['3-']],\n    ['phrygidorian', ['phrygian ♮6', 'dorian ♭2', 'assyrian'], [0, 1, 3, 5, 7, 9, 10],  DIATONIC_SCALES[1], ['2-']],\n    ['lydian augmented', ['lydian ♯5'], [0, 2, 4, 6, 8, 9, 11],  DIATONIC_SCALES[3], ['5+']],\n    ['lydian dominant', ['lydian ♭7', 'acoustic scale', 'mixolydian ♯4', 'overtone', 'lydomyxian'], [0, 2, 4, 6, 7, 9, 10],  DIATONIC_SCALES[3], ['7-']],\n    ['melodic major', ['mixolydian ♭6', 'fifth mode of melodic minor', 'hindu', 'myxaeolian'], [0, 2, 4, 5, 7, 8, 10],  DIATONIC_SCALES[4], ['6-']],\n    ['aeolocrian', ['locrian ♮2', 'half-diminished'], [0, 2, 3, 5, 6, 8, 10],  DIATONIC_SCALES[6], ['2+']],\n    ['altered scale', ['super locrian', 'altered dominant scale'], [0, 1, 3, 4, 6, 8, 10],  DIATONIC_SCALES[6], ['4-']]\n]\n\nBEBOP_SCALES = [\n    ['bebop dominant scale', [], [0, 2, 4, 5, 7, 9, 10, 11], DIATONIC_SCALES[4], ['add7+']],\n    ['bebop major scale', [], [0, 2, 4, 5, 7, 8, 9, 11], DIATONIC_SCALES[0], ['add5+']]\n]\n\nPENTATONE_SCALES = [\n    ['major pentatonic scale', ['gong'], [0, 2, 4, 7, 9], DIATONIC_SCALES[0], ['omit4', 'omit7']],\n    ['egyptian', ['suspended', 'shang'], [0, 2, 5, 7, 10], DIATONIC_SCALES[1], ['omit3', 'omit6']],\n    ['blues minor', ['man gong', 'jue'], [0, 3, 5, 8, 10], DIATONIC_SCALES[2], ['omit2', 'omit5']],\n    ['blues major', ['Ritsusen', 'yo scale', 'zhi'], [0, 2, 5, 7, 9], DIATONIC_SCALES[4], ['omit3', 'omit7']],\n    ['minor pentatonic', ['yu'], [0, 3, 5, 7, 10], DIATONIC_SCALES[5], ['omit2', 'omit6']]\n]\n\nHEPTATONIC_SCALES = [\n    # diatonic scales\n    ['ionian mode (major scale)', [0, 2, 4, 5, 7, 9, 11]],\n    ['dorian mode', [0, 2, 3, 5, 7, 9, 10]],\n    ['phrygian mode', [0, 1, 3, 5, 7, 8, 10]],\n    ['lydian mode', [0, 2, 4, 6, 7, 9, 11]],\n    ['mixolydian scale', [0, 2, 4, 5, 7, 9, 10]],\n    ['aeolian mode (nature minor mode)', [0, 2, 3, 5, 7, 8, 10]],\n    ['locrian mode', [0, 1, 3, 5, 6, 8, 10]],\n    # TODO\n    ['adonai malakh scale', [0, 2, 4, 5, 7, 8, 10]],\n    ['algerian scale', [0, 2, 3, 6, 7, 8, 11]],\n    ['altered scale', [0, 1, 3, 4, 6, 8, 10]],\n    ['double harmonic scale', [0, 1, 4, 5, 7, 8, 11]],\n    ['enigmatic scale', [0, 1, 4, 6, 8, 10, 11]],\n    ['flamenco mode', [0, 1, 4, 5, 7, 8, 11]],\n    ['gypsy scale', [0, 2, 3, 6, 7, 8, 10]],\n    ['half diminished scale', [0, 2, 3, 5, 6, 8, 10]],\n    ['harmonic major scale', [0, 2, 4, 5, 7, 8, 11]],\n    ['harmonic minor scale', [0, 2, 3, 5, 7, 8, 11]],\n    ['hungarian gypsy scale', [0, 2, 3, 6, 7, 8, 11]],\n    ['hungarian minor scale', [0, 2, 3, 6, 7, 8, 11]],\n    ['lydian augmented scale', [0, 2, 4, 6, 8, 9, 11]],\n    ['major locran scale', [0, 2, 4, 5, 6, 8, 10]],\n    ['melodic minor scale (ascending)', [0, 2, 3, 5, 7, 9, 11]],\n    ['neapolitan major scale', [0, 1, 3, 5, 7, 9, 11]],\n    ['neapolitan minor scale', [0, 1, 3, 5, 7, 8, 11]],\n    ['persian scale', [0, 1, 4, 5, 6, 8, 11]],\n    ['phrygian dominant scale', [0, 1, 4, 5, 7, 8, 10]],\n    ['ukranian dorian scale', [0, 2, 3, 6, 7, 9, 10]]\n]\n\nSCALES_COLLECTION = [\n    ['acoustic scale', [0, 2, 4, 6, 7, 9]],\n    ['adonai malakh scale', [0, 2, 4, 5, 7, 8, 10]],\n    ['aeolian mode', [0, 2, 3, 5, 7, 8, 10]],\n    ['nature minor mode', [0, 2, 3, 5, 7, 8, 10]],\n    ['algerian scale', [0, 2, 3, 6, 7, 8, 11]],\n    ['altered scale', [0, 1, 3, 4, 6, 8, 10]],\n    ['augmented scale', [0, 3, 4, 7, 8, 11]],\n    ['bebop dominant scale', [0, 2, 4, 5, 7, 9, 10, 11]],\n    ['blues scale', [0, 3, 5, 6, 7, 10]],\n    ['chromatic scale', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]],\n    ['dorian mode', [0, 2, 3, 5, 7, 9, 10]],\n    ['double harmonic scale', [0, 1, 4, 5, 7, 8, 11]],\n    ['enigmatic scale', [0, 1, 4, 6, 8, 10, 11]],\n    ['flamenco mode', [0, 1, 4, 5, 7, 8, 11]],\n    ['gypsy scale', [0, 2, 3, 6, 7, 8, 10]],\n    ['half diminished scale', [0, 2, 3, 5, 6, 8, 10]],\n    ['harmonic major scale', [0, 2, 4, 5, 7, 8, 11]],\n    ['harmonic minor scale', [0, 2, 3, 5, 7, 8, 11]],\n    ['hirajoshi scale', [0, 2, 3, 7, 8]],\n    ['hungarian gypsy scale', [0, 2, 3, 6, 7, 8, 11]],\n    ['hungarian minor scale', [0, 2, 3, 6, 7, 8, 11]],\n    ['insen scale', [0, 1, 5, 7, 10]],\n    ['ionian mode', [0, 2, 4, 5, 7, 9, 11]],\n    ['major scale', [0, 2, 4, 5, 7, 9, 11]],\n    ['istrian scale', [0, 1, 3, 4, 6, 7]],\n    ['iwato scale', [0, 1, 5, 6, 10]],\n    ['locrian mode', [0, 1, 3, 5, 6, 8, 10]],\n    ['lydian augmented scale', [0, 2, 4, 6, 8, 9, 11]],\n    ['lydian mode', [0, 2, 4, 6, 7, 9, 11]],\n    ['major bepop scale', [0, 2, 4, 5, 7, 8, 9, 11]],\n    ['major locran scale', [0, 2, 4, 5, 6, 8, 10]],\n    ['major pentatonic scale', [0, 2, 4, 7, 9]],\n    ['melodic minor scale', [0, 2, 3, 5, 7, 8, 9, 10, 11]],\n    ['melodic minor scale (ascending)', [0, 2, 3, 5, 7, 9, 11]],\n    ['minor pentatonic scale', [0, 3, 5, 7, 10]],\n    ['mixolydian scale', [0, 2, 4, 5, 7, 9, 10]],\n    ['neapolitan major scale', [0, 1, 3, 5, 7, 9, 11]],\n    ['neapolitan minor scale', [0, 1, 3, 5, 7, 8, 11]],\n    ['octatonic scale', [0, 2, 3, 5, 6, 8, 9, 11]],\n    ['persian scale', [0, 1, 4, 5, 6, 8, 11]],\n    ['phrygian dominant scale', [0, 1, 4, 5, 7, 8, 10]],\n    ['phrygian mode', [0, 1, 3, 5, 7, 8, 10]],\n    ['prometheus scale', [0, 2, 4, 6, 9, 10]],\n    ['tritone scale', [0, 1, 4, 6, 7, 10]],\n    ['ukranian dorian scale', [0, 2, 3, 6, 7, 9, 10]],\n    ['whole tone scale', [0, 2, 4, 6, 8, 10]]\n]\n\n# | full name | short names | intervals | scale names |\nCHORDS_TABLE = [\n    # triad chords\n    ['major triad', ['M'], [0, 4, 7], ['ionian']],\n    ['minor triad', ['m'], [0, 3, 7], ['aeolian']],\n    ['augmented triad', ['aug'], [0, 4, 8], ['lydian augmented']],\n    ['diminished triad', ['dim'], [0, 3, 6], ['locrian']],\n    # seventh chords\n    ['diminished seventh', ['°'], [0, 3, 6, 9], [1, 3, 5, 7]],\n    ['half-diminished seventh', ['φ'], [0, 3, 6, 10], ['locrian']],\n    ['minor seventh', ['-'], [0, 3, 7, 10], ['dorian']],\n    ['minor major seventh', ['-Δ'], [0, 3, 7, 11], ['melodic minor']],\n    ['dominant seventh', ['7'], [0, 4, 7, 10], ['mixolydian']],\n    ['major seventh', ['Δ'], [0, 4, 7, 11], ['ionian']],\n    ['augmented seventh', ['7♯5'], [0, 4, 8, 10], ['melodic major']],\n    ['augmented major seventh', ['Δ♯5'], [0, 4, 8, 11], ['lydian augmented']],\n    # extented chords\n    ['dominant ninth', ['9'], [0, 2, 4, 7, 10], ['mixolydian']],\n    ['dominant eleventh', ['11'], [0, 2, 4, 5, 7, 10], ['mixolydian']],\n    ['dominant thirteenth', ['13'], [0, 2, 4, 5, 7, 9, 10], ['mixolydian']],\n    # atered chords\n    ['seventh augmented fifth', ['7♯5'], [0, 4, 8, 10], ['melodic major']],\n    ['seventh minor ninth', ['7♭9'], [0, 1, 4, 7, 10], ['phrygian dominant']],\n    ['seventh sharp ninth', ['7♯9'], [0, 3, 4, 7, 10], [1, 2, 3, 5, 7]],\n    ['seventh augmented eleventh', ['7♯11'], [0, 2, 4, 6, 7, 10]],\n    ['seventh diminished thirteenth', ['7♭13'], [0, 2, 4, 5, 7, 8, 10]],\n    ['half-diminished seventh', ['φ'], [0, 3, 6, 10], [1, 3, 5, 7]],\n    # added tone chords\n    ['add nine', ['add9'], [0, 2, 4, 7], [1, 2, 3, 5]],\n    ['add fourth', ['add11'], [0, 4, 5, 7], [1, 3, 4, 5]],\n    ['add sixth', ['6'], [0, 4, 7, 9], [1, 3, 5, 6]],\n    ['six-nine', ['6/9'], [0, 2, 4, 7, 9], [1, 2, 3, 5, 6]],\n    ['seven-six', ['7/6'], [0, 4, 7, 9, 10], [1, 3, 5, 6, 7]],\n    ['mixed-third', ['--'], [0, 3, 4, 7], [1, 2, 3, 5]],\n    # suspended chords\n    ['suspended second', ['sus2'], [0, 2, 7], [1, 2, 5]],\n    ['suspended fourth', ['sus4'], [0, 5, 7], [1, 4, 5]],\n    ['jazz sus', ['9sus4'], [0, 4, 5, 7, 10], [1, 3, 4, 5, 7]]\n]\n\n\nclass FreqRatio():\n    FREQ_RATIOS = ['1/1', '16/15', '9/8', '6/5', '5/4', '4/3',\n                   '45/32', '3/2', '8/5', '5/3', '9/5', '15/8']\n\n    def __init__(self):\n        pass\n\n    def chromatic_freq_sizes(self):\n        l = []\n        for fr in self.FREQ_RATIOS:\n            f = Fraction(fr)\n            n = f.numerator\n            d = f.denominator\n            l.append(n * d)\n        return l\n\n    def calc_freq_radio_size(self, intervals):\n        l = list(intervals)\n        l.sort()\n        denominators = []\n        numerators = []\n        for i in l:\n            f = Fraction(self.FREQ_RATIOS[i])\n            denominators.append(f.denominator)\n            numerators.append(f.numerator)\n        lcm = np.lcm.reduce(denominators)\n        total = []\n        for d,n in zip(denominators, numerators):\n            total.append(n * (lcm / d))\n        prod = np.prod(total)\n        return prod\n\n\nSCALES_QUERY_TABLE = {\n    'ionian': ['diatonic', DIATONIC_SCALES[0]],\n    'dorian': ['diatonic', DIATONIC_SCALES[1]],\n    'phrygian': ['diatonic', DIATONIC_SCALES[2]],\n    'lydian': ['diatonic', DIATONIC_SCALES[3]],\n    'mixolydian': ['diatonic', DIATONIC_SCALES[4]],\n    'aeolian': ['diatonic', DIATONIC_SCALES[5]],\n    'locrian': ['diatonic', DIATONIC_SCALES[6]],\n    'melodic minor': ['melodic', MELODIC_MINOR_SCALES[0]],\n    'lydian dominant': ['melodic', MELODIC_MINOR_SCALES[3]],\n    'melodic major': ['melodic', MELODIC_MINOR_SCALES[4]],\n    'aeolocrian': ['melodic', MELODIC_MINOR_SCALES[5]],\n    'altered scale': ['melodic', MELODIC_MINOR_SCALES[6]],\n    'gong': ['pentatone', PENTATONE_SCALES[0]],\n    'shang': ['pentatone', PENTATONE_SCALES[1]],\n    'jue': ['pentatone', PENTATONE_SCALES[2]],\n    'zhi': ['pentatone', PENTATONE_SCALES[3]],\n    'yu': ['pentatone', PENTATONE_SCALES[4]],\n    'bebop dominant': ['bebop', BEBOP_SCALES[0]],\n    'bebop major': ['bebop', BEBOP_SCALES[1]],\n}\n\n\nclass Scales:\n    diatonic_scales = ['C', 0, 'D', 0, 'E', 'F', 0, 'G', 0, 'A', 0, 'B']\n    scales_query_table = SCALES_QUERY_TABLE\n\n    def __init__(self):\n        pass\n\n    def rotate(self, n, l, right=False):\n        llen = len(l)\n        if right:\n            return l[-n:] + l[:-n]\n        n1 = (llen - n) % llen\n        return l[-n1:] + l[:-n1]\n\n    def get_accidentals(self, key):\n        alter = 0\n        if len(key) > 1:\n            ct = key.count('-')\n            if ct > 0:\n                alter = -ct\n            ct = key.count('#')\n            if ct > 0:\n                alter = ct\n        return alter\n\n    def __query(self, mode):\n        return self.scales_query_table[mode]\n\n    def flat_list(self, l, output_list):\n        for i in l:\n            if type(i) == list:\n                self.flat_list(i, output_list)\n            else:\n                output_list.append(i)\n\n    def to_diatonic_scales(self, key, query):\n        intervals = query[2]\n        alter = self.get_accidentals(key)\n        step = key[0]\n        scale_count = len(self.diatonic_scales)\n        idx = self.diatonic_scales.index(step)\n        rotated_scales = self.rotate(idx, self.diatonic_scales)\n        index_list = []\n        scale_steps = []\n        for i in range(scale_count):\n            if type(rotated_scales[i]) == str:\n                index_list.append(i)\n                scale_steps.append(rotated_scales[i])\n        a1 = np.array(index_list)\n        a2 = np.array(intervals)\n        dist = a2 - a1 + alter\n        notes = []\n        for n,d in zip(scale_steps, dist):\n            if d > 0:\n                note = \"{}{}\".format(n, '#' * d)\n            elif d < 0:\n                note = \"{}{}\".format(n, '-' * -d)\n            else:\n                note = n\n            notes.append(note)\n        return notes\n\n    def filter_digit(self, s):\n        num = int(''.join(filter(str.isdigit, s)))\n        return num\n\n    def update_accidental(self, note, alter):\n        step = note[0]\n        curr_alter = self.get_accidentals(note)\n        final_alter = curr_alter + alter\n        if final_alter > 0:\n            nt = \"{}{}\".format(step, '#' * final_alter)\n        elif final_alter < 0:\n            nt = \"{}{}\".format(step, '-' * -final_alter)\n        else:\n            nt = step\n        return nt\n\n    def notes_operate(self, notes, opts):\n        for opt in opts:\n            if opt.count('omit') > 0:\n                idx = self.filter_digit(opt)\n                notes[idx - 1] = 0\n            elif opt.count('add') > 0:\n                idx = self.filter_digit(opt)\n                alter = self.get_accidentals(opt)\n                n = notes[idx - 1]\n                nt = self.update_accidental(n, alter)\n                if alter > 0:\n                    notes[idx - 1] = [n, nt]\n                else:\n                    notes[idx - 1] = [nt, n]\n            else:\n                idx = self.filter_digit(opt)\n                alter = self.get_accidentals(opt)\n                n = notes[idx - 1]\n                nt = self.update_accidental(n, alter)\n                notes[idx - 1] = nt\n        notes = list(filter(lambda a: a != 0, notes))\n        final_notes = []\n        self.flat_list(notes, final_notes)\n        return final_notes\n\n    def to_pentatone_scales(self, key, query):\n        notes = []\n        opts = query[4]\n        notes = self.to_diatonic_scales(key, query[3])\n        notes = self.notes_operate(notes, opts)\n        return notes\n\n    def to_bebop_scales(self, key, query):\n        notes = []\n        opts = query[4]\n        notes = self.to_diatonic_scales(key, query[3])\n        notes = self.notes_operate(notes, opts)\n        return notes\n\n    def to_scales(self, key, mode):\n        query = self.__query(mode)\n        notes = []\n        if query[0] == 'diatonic':\n            notes = self.to_diatonic_scales(key, query[1])\n        elif query[0] == 'pentatone':\n            notes = self.to_pentatone_scales(key, query[1])\n        elif query[0] == 'melodic':\n            notes = self.to_diatonic_scales(key, query[1])\n        elif query[0] == 'bebop':\n            notes = self.to_bebop_scales(key, query[1])\n        return notes\n\n\nCHORDS_QUERY_TABLE = {\n    'maj': ['triad', CHORDS_TABLE[0]],\n    'min': ['triad', CHORDS_TABLE[1]],\n    'maj7': ['seventh', CHORDS_TABLE[9]],\n    'min7': ['seventh', CHORDS_TABLE[6]],\n}\n\n\nclass Chord(Scales):\n    chords_query_table = CHORDS_QUERY_TABLE\n    ChordsTable = namedtuple('ChordsTable', ['common_name', 'short_names',\n                                             'intervals', 'scale_names'])\n\n    def __init__(self):\n        pass\n\n    def __query(self, mode):\n        return self.chords_query_table[mode]\n\n    def to_triad(self, scales):\n        chord = [scales[0], scales[2], scales[4]]\n        return chord\n\n    def to_seventh(self, scales):\n        chord = [scales[0], scales[2], scales[4], scales[6]]\n        return chord\n\n    def to_chord(self, key, mode):\n        query = self.__query(mode)\n        chords_table = self.ChordsTable._make(query[1])\n        scales = self.to_scales(key, chords_table.scale_names[0])\n        chord = []\n        if query[0] == 'triad':\n            chord = self.to_triad(scales)\n        elif query[0] == 'seventh':\n            chord = self.to_seventh(scales)\n        return chord\n\n\nclass RomanNumeral(Chord):\n    roman_numerals = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII']\n\n    def __init__(self, key):\n        self.__notes = self.to_scales(key, 'diatonic')\n\n    def parser(self, rn):\n        offset = rn[0]\n        pass\n\n    def to_note(self, rn):\n        pass\n\n    def to_chord(self, rn):\n        pass\n\n\nclass ChordProgression():\n    # | genre | chord progression | expression |\n    CHORD_PROGRESSION_TABLE = [\n        [\"50' progression\", ['I', 'vi', 'IV', 'V'], 0],\n        [\"50' progression\", ['I', 'vi', 'ii', 'V'], 1],\n        [\"50' progression\", ['I', 'V', 'vi', 'IV'], 2]\n    ]\n\n    def __init__(self):\n        pass\n\n\nclass Style():\n    STYLES = ['Folk song', 'Hip hop', 'Jazz', 'Latin', 'Pop', 'R&B and soul', 'Rock',\n              'Classical music', 'Country']\n\n\nclass Instruments():\n    pass\n\n\nclass EvalSystem():\n    pass\n", "meta": {"hexsha": "ac1ec4c8d672d7c080d26e498498dceb9dec8cb6", "size": 16188, "ext": "py", "lang": "Python", "max_stars_repo_path": "core/music_theory.py", "max_stars_repo_name": "liunx/coderband", "max_stars_repo_head_hexsha": "1102631dd12ea9e6608cf8d41fb4dc2da1e1ba80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core/music_theory.py", "max_issues_repo_name": "liunx/coderband", "max_issues_repo_head_hexsha": "1102631dd12ea9e6608cf8d41fb4dc2da1e1ba80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core/music_theory.py", "max_forks_repo_name": "liunx/coderband", "max_forks_repo_head_hexsha": "1102631dd12ea9e6608cf8d41fb4dc2da1e1ba80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7342657343, "max_line_length": 153, "alphanum_fraction": 0.5051890289, "include": true, "reason": "import numpy", "num_tokens": 6370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290152, "lm_q2_score": 0.2689414213699951, "lm_q1q2_score": 0.1553124282589264}}
{"text": "\"\"\"Probabilistic autoregressive model.\"\"\"\n\nimport copy\nimport logging\nimport pickle\nimport uuid\n\nimport numpy as np\nimport pandas as pd\nimport rdt\nimport torch\nfrom deepecho.models.base import DeepEcho\nfrom deepecho.sequences import assemble_sequences\nfrom sdv.metadata import Table\nfrom sdv.tabular.copulas import GaussianCopula\nfrom tqdm import tqdm\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef batch_to_df(sequences, columns, entity):\n    df = pd.DataFrame()\n    for k, v in sequences.items():\n        if isinstance(v, torch.Tensor):\n            list_ = list(v.numpy())\n        else:\n            list_ = list(v)\n        if len(list_) < len(sequences[\"t\"]):  # removes all the next_* and *_to_now features\n            continue\n        else:\n            df[k] = list_\n\n    df = df[columns + entity]\n\n    return df\n\n\nclass PARNet(torch.nn.Module):\n    \"\"\"PARModel ANN model.\"\"\"\n\n    def __init__(self, data_size, context_size, hidden_size=32):\n        super(PARNet, self).__init__()\n        self.context_size = context_size\n        self.down = torch.nn.Linear(data_size + context_size, hidden_size)\n        self.rnn = torch.nn.GRU(hidden_size, hidden_size)\n        self.up = torch.nn.Linear(hidden_size, data_size)\n\n    def forward(self, x, c):\n        \"\"\"Forward passing computation.\"\"\"\n        if isinstance(x, torch.nn.utils.rnn.PackedSequence):\n            x, lengths = torch.nn.utils.rnn.pad_packed_sequence(x)\n            if self.context_size:\n                x = torch.cat(\n                    [x, c.unsqueeze(0).expand(x.shape[0], c.shape[0], c.shape[1])],\n                    dim=2,\n                )\n\n            x = self.down(x)\n            x = torch.nn.utils.rnn.pack_padded_sequence(x, lengths, enforce_sorted=False)\n            x, _ = self.rnn(x)\n            x, lengths = torch.nn.utils.rnn.pad_packed_sequence(x)\n            x = self.up(x)\n            x = torch.nn.utils.rnn.pack_padded_sequence(x, lengths, enforce_sorted=False)\n\n        else:\n            if self.context_size:\n                x = torch.cat(\n                    [x, c.unsqueeze(0).expand(x.shape[0], c.shape[0], c.shape[1])],\n                    dim=2,\n                )\n\n            x = self.down(x)\n            x, _ = self.rnn(x)\n            x = self.up(x)\n\n        return x\n\n\nclass PARModel(DeepEcho):\n    def __init__(self, epochs=128, sample_size=1, cuda=True, verbose=True):\n        self.epochs = epochs\n        self.sample_size = sample_size\n\n        if not cuda or not torch.cuda.is_available():\n            device = \"cpu\"\n        elif isinstance(cuda, str):\n            device = cuda\n        else:\n            device = \"cuda\"\n\n        self.device = torch.device(device)\n        self.verbose = verbose\n\n        LOGGER.info(\"%s instance created\", self)\n        if verbose:\n            print(self, \"instance created\")\n\n    def __repr__(self):\n        return \"{}(epochs={}, sample_size={}, cuda='{}', verbose={})\".format(\n            self.__class__.__name__,\n            self.epochs,\n            self.sample_size,\n            self.device,\n            self.verbose,\n        )\n\n    def _idx_map(self, x, t):\n        idx = 0\n        idx_map = {}\n        for i, t in enumerate(t):\n            if t == \"continuous\" or t == \"datetime\":\n                try:\n                    if i == 14:\n                        x[i] = [hash(k) for k in x[i]]\n                    idx_map[i] = {\n                        \"type\": t,\n                        \"mu\": np.nanmean(x[i]),\n                        \"std\": np.nanstd(x[i]),\n                        \"nulls\": pd.isnull(x[i]).any(),\n                        \"indices\": (idx, idx + 1, idx + 2),\n                    }\n                    idx += 3\n                except Exception as e:\n                    print(e)\n\n            elif t == \"count\":\n                idx_map[i] = {\n                    \"type\": t,\n                    \"min\": np.nanmin(x[i]),\n                    \"range\": np.nanmax(x[i]) - np.nanmin(x[i]),\n                    \"nulls\": pd.isnull(x[i]).any(),\n                    \"indices\": (idx, idx + 1, idx + 2),\n                }\n                idx += 3\n\n            elif t == \"categorical\" or t == \"ordinal\":\n                idx_map[i] = {\"type\": t, \"indices\": {}}\n                idx += 1\n                for v in set(x[i]):\n                    if pd.isnull(v):\n                        v = None\n\n                    idx_map[i][\"indices\"][str(v)] = idx\n                    idx += 1\n\n            else:\n                raise ValueError(\"Unsupported type: {}\".format(t))\n\n        return idx_map, idx\n\n    def _build(self, examples, types):\n\n        # TODO: define better suited values\n        min_length = 0\n        max_length = int(1e3)\n\n        self._fixed_length = min_length == max_length\n        self._min_length = min_length\n        self._max_length = max_length\n\n        self._ctx_map, self._ctx_dims = self._idx_map(\n            examples[\"context\"], types[\"context\"]\n        )  # all possible values => per batch!\n        self._data_map, self._data_dims = self._idx_map(examples[\"data\"], types[\"data\"])\n        self._data_map[\"<TOKEN>\"] = {\n            \"type\": \"categorical\",\n            \"indices\": {\n                \"<START>\": self._data_dims,\n                \"<END>\": self._data_dims + 1,\n                \"<BODY>\": self._data_dims + 2,\n            },\n        }\n        self._data_dims += 3\n\n    def _data_to_tensor(self, data):\n        seq_len = len(data[0]) if data != [] else 0\n        X = []\n\n        x = torch.zeros(self._data_dims)\n        x[self._data_map[\"<TOKEN>\"][\"indices\"][\"<START>\"]] = 1.0\n        X.append(x)\n\n        for i in range(seq_len):\n            x = torch.zeros(self._data_dims)\n            for key, props in self._data_map.items():\n                if key == \"<TOKEN>\":\n                    x[self._data_map[\"<TOKEN>\"][\"indices\"][\"<BODY>\"]] = 1.0\n\n                elif props[\"type\"] in [\"continuous\", \"timestamp\"]:\n                    mu_idx, sigma_idx, missing_idx = props[\"indices\"]\n                    if data[key][i].isalpha() and not (props[\"std\"] == 0):\n                        x[mu_idx] = (\n                            (float(data[key][i]) - props[\"mu\"]) / props[\"std\"]\n                            if isinstance(data[key][i], float)\n                            else 0.0\n                        )\n                    else:\n                        x[mu_idx] = 0.0\n\n                    x[sigma_idx] = 0.0\n                    x[missing_idx] = 1.0 if data[key][i] is None else 0.0\n\n                elif props[\"type\"] in [\"count\"]:\n                    r_idx, p_idx, missing_idx = props[\"indices\"]\n                    x[r_idx] = (\n                        0.0\n                        if (data[key][i] is None or props[\"range\"] == 0)\n                        else (data[key][i] - props[\"min\"]) / props[\"range\"]\n                    )\n                    x[p_idx] = 0.0\n                    x[missing_idx] = 1.0 if data[key][i] is None else 0.0\n\n                elif props[\"type\"] in [\"categorical\", \"ordinal\"]:  # categorical\n                    value = data[key][i]\n                    if pd.isnull(value):\n                        value = None\n                    x[props[\"indices\"][value]] = 1.0\n\n                else:\n                    raise ValueError()\n\n            X.append(x)\n\n        x = torch.zeros(self._data_dims)\n        x[self._data_map[\"<TOKEN>\"][\"indices\"][\"<END>\"]] = 1.0\n        X.append(x)\n\n        return torch.stack(X, dim=0).to(self.device)\n\n    def _context_to_tensor(self, context):\n        if not self._ctx_dims:\n            return None\n\n        x = torch.zeros(self._ctx_dims)\n        for key, props in self._ctx_map.items():\n            if props[\"type\"] in [\"continuous\", \"datetime\"]:\n                mu_idx, sigma_idx, missing_idx = props[\"indices\"]\n                x[mu_idx] = (\n                    0.0\n                    if (pd.isnull(context[key]) or props[\"std\"] == 0)\n                    else (context[key] - props[\"mu\"]) / props[\"std\"]\n                )\n                x[sigma_idx] = 0.0\n                x[missing_idx] = 1.0 if pd.isnull(context[key]) else 0.0\n\n            elif props[\"type\"] in [\"count\"]:\n                r_idx, p_idx, missing_idx = props[\"indices\"]\n                x[r_idx] = (\n                    0.0\n                    if (pd.isnull(context[key]) or props[\"range\"] == 0)\n                    else (context[key] - props[\"min\"]) / props[\"range\"]\n                )\n                x[p_idx] = 0.0\n                x[missing_idx] = 1.0 if pd.isnull(context[key]) else 0.0\n\n            elif props[\"type\"] in [\"categorical\", \"ordinal\"]:\n                value = context[key]\n                if pd.isnull(value):\n                    value = None\n                x[props[\"indices\"][value]] = 1.0\n\n            else:\n                raise ValueError()\n\n        return x.to(self.device)\n\n    def _transform_sequence_index(self, sequences, dem):\n        sequence_index_idx = dem._data_columns.index(dem._sequence_index)\n        for sequence in sequences:\n            data = sequence[\"data\"]\n            sequence_index = data[sequence_index_idx]\n            diffs = np.diff(sequence_index).tolist()\n            data[sequence_index_idx] = diffs[0:1] + diffs\n            data.append(sequence_index[0:1] * len(sequence_index))\n\n    def fit_sequences(self, sequence_loader, columns, types, examples, dem):\n        \"\"\"Fit a model to the specified sequences.\n\n        Args:\n            sequences (list):\n                List of sequences. Each sequence is a single training example\n                (i.e. an example of a multivariate time series with some context).\n                For example, a sequence might look something like::\n\n                    {\n                        \"context\": [1],\n                        \"data\": [\n                            [1, 3, 4, 5, 11, 3, 4],\n                            [2, 2, 3, 4,  5, 1, 2],\n                            [1, 3, 4, 5,  2, 3, 1]\n                        ]\n                    }\n\n                The \"context\" attribute maps to a list of variables which\n                should be used for conditioning. These are variables which\n                do not change over time.\n\n                The \"data\" attribute contains a list of lists corrsponding\n                to the actual time series data such that `data[i][j]` contains\n                the value at the jth time step of the ith channel of the\n                multivariate time series.\n            context_types (list):\n                List of strings indicating the type of each value in context.\n                he value at `context[i]` must match the type specified by\n                `context_types[i]`. Valid types include the following: `categorical`,\n                `continuous`, `ordinal`, `count`, and `datetime`.\n            data_types (list):\n                List of strings indicating the type of each channel in data.\n                Each value in the list at data[i] must match the type specified by\n                `data_types[i]`. The valid types are the same as for `context_types`.\n        \"\"\"\n        # build variable2id maps\n        self._build(examples, types)\n\n        # Initialize model with data dimension & context dimension\n        self._model = PARNet(self._data_dims, self._ctx_dims).to(self.device)\n\n        # Specify optimizer\n        optimizer = torch.optim.Adam(self._model.parameters(), lr=1e-3)\n\n        iterator = range(self.epochs)\n        if self.verbose:\n            iterator = tqdm(iterator)\n\n        # Training\n        for epoch in iterator:\n            for sequences in sequence_loader:\n\n                # process sequence as in _fit\n                timeseries_data = batch_to_df(sequences, columns, dem._entity_columns)\n                sequences = assemble_sequences(\n                    timeseries_data,\n                    dem._entity_columns,\n                    dem._context_columns,\n                    dem._segment_size,\n                    dem._sequence_index,\n                    drop_sequence_index=False,\n                )\n                if dem._sequence_index:\n                    self._transform_sequence_index(sequences, dem)\n\n                X, C = [], []\n                for sequence in sequences:\n                    dataFeed = np.array(sequence[\"data\"]).tolist()\n                    # if dataFeed!=[]:\n                    X.append(self._data_to_tensor(dataFeed))\n                    C.append(self._context_to_tensor(sequence[\"context\"]))\n\n                X = torch.nn.utils.rnn.pack_sequence(X, enforce_sorted=False).to(self.device)\n                if self._ctx_dims:\n                    C = torch.stack(C, dim=0).to(self.device)\n\n                X_padded, seq_len = torch.nn.utils.rnn.pad_packed_sequence(X)\n\n                Y = self._model(X, C)\n                Y_padded, _ = torch.nn.utils.rnn.pad_packed_sequence(Y)\n\n                optimizer.zero_grad()\n                loss = self._compute_loss(X_padded[1:, :, :], Y_padded[:-1, :, :], seq_len)\n                loss.backward()\n                if self.verbose:\n                    iterator.set_description(\"Epoch {} | Loss {}\".format(epoch + 1, loss.item()))\n\n                optimizer.step()\n\n    def _compute_loss(self, X_padded, Y_padded, seq_len):\n        \"\"\"Compute the loss between X and Y.\n\n        Given X[i,:,:], the neural network predicts the value at the next\n        timestep (i+1); this prediction is provided in Y[i,:,:]. This function\n        returns the loss between the predicted and actual sequence.\n\n        .. note::\n            The `i`th time series (with padding removed) can be indexed with\n            `X[:seq_len[i], i, :]`.\n\n        Args:\n            X_padded (tensor):\n                This contains the input to the model.\n            Y_padded (tensor):\n                This contains the output of the model.\n            seq_len (list):\n                This list contains the length of each sequence.\n        \"\"\"\n        log_likelihood = 0.0\n        _, batch_size, input_size = X_padded.shape\n\n        for key, props in self._data_map.items():\n            if props[\"type\"] in [\"continuous\", \"timestamp\"]:\n                mu_idx, sigma_idx, missing_idx = props[\"indices\"]\n                mu = Y_padded[:, :, mu_idx]\n                sigma = torch.nn.functional.softplus(Y_padded[:, :, sigma_idx])\n                missing = torch.nn.LogSigmoid()(Y_padded[:, :, missing_idx])\n\n                for i in range(batch_size):\n                    dist = torch.distributions.normal.Normal(mu[: seq_len[i], i], sigma[: seq_len[i], i])\n                    log_likelihood += torch.sum(dist.log_prob(X_padded[-seq_len[i] :, i, mu_idx]))\n\n                    p_true = X_padded[: seq_len[i], i, missing_idx]\n                    p_pred = missing[: seq_len[i], i]\n                    log_likelihood += torch.sum(p_true * p_pred)\n                    log_likelihood += torch.sum((1.0 - p_true) * torch.log(1.0 - torch.exp(p_pred)))\n\n            elif props[\"type\"] in [\"count\"]:\n                r_idx, p_idx, missing_idx = props[\"indices\"]\n                r = torch.nn.functional.softplus(Y_padded[:, :, r_idx]) * props[\"range\"]\n                p = torch.sigmoid(Y_padded[:, :, p_idx])\n                x = X_padded[:, :, r_idx] * props[\"range\"]\n                missing = torch.nn.LogSigmoid()(Y_padded[:, :, missing_idx])\n\n                for i in range(batch_size):\n                    dist = torch.distributions.negative_binomial.NegativeBinomial(\n                        r[: seq_len[i], i], p[: seq_len[i], i]\n                    )\n                    log_likelihood += torch.sum(dist.log_prob(x[: seq_len[i], i]))\n\n                    p_true = X_padded[: seq_len[i], i, missing_idx]\n                    p_pred = missing[: seq_len[i], i]\n                    log_likelihood += torch.sum(p_true * p_pred)\n                    log_likelihood += torch.sum((1.0 - p_true) * torch.log(1.0 - torch.exp(p_pred)))\n\n            elif props[\"type\"] in [\"categorical\", \"ordinal\"]:\n                idx = list(props[\"indices\"].values())\n                log_softmax = torch.nn.functional.log_softmax(Y_padded[:, :, idx], dim=2)\n\n                for i in range(batch_size):\n                    target = X_padded[: seq_len[i], i, idx]\n                    predicted = log_softmax[: seq_len[i], i]\n                    target = torch.argmax(target, dim=1).unsqueeze(dim=1)\n                    log_likelihood += torch.sum(predicted.gather(dim=1, index=target))\n\n            else:\n                raise ValueError()\n\n        return -log_likelihood / (batch_size * len(self._data_map) * batch_size)\n\n    def _tensor_to_data(self, x):\n        # Force CPU on x\n        x = x.to(torch.device(\"cpu\"))\n\n        seq_len, batch_size, _ = x.shape\n        assert batch_size == 1\n\n        data = [None] * (len(self._data_map) - 1)\n        for key, props in self._data_map.items():\n            if key == \"<TOKEN>\":\n                continue\n\n            data[key] = []\n            for i in range(seq_len):\n                if props[\"type\"] in [\"continuous\", \"datetime\"]:\n                    mu_idx, sigma_idx, missing_idx = props[\"indices\"]\n                    if (x[i, 0, missing_idx] > 0) and props[\"nulls\"]:\n                        data[key].append(None)\n                    else:\n                        data[key].append(x[i, 0, mu_idx].item() * props[\"std\"] + props[\"mu\"])\n\n                elif props[\"type\"] in [\"count\"]:\n                    r_idx, p_idx, missing_idx = props[\"indices\"]\n                    if x[i, 0, missing_idx] > 0 and props[\"nulls\"]:\n                        data[key].append(None)\n                    else:\n                        sample = x[i, 0, r_idx].item() * props[\"range\"] + props[\"min\"]\n                        data[key].append(int(sample))\n\n                elif props[\"type\"] in [\"categorical\", \"ordinal\"]:\n                    ml_value, max_x = None, float(\"-inf\")\n                    for value, idx in props[\"indices\"].items():\n                        if x[i, 0, idx] > max_x:\n                            max_x = x[i, 0, idx]\n                            ml_value = value\n\n                    data[key].append(ml_value)\n\n                else:\n                    raise ValueError()\n\n        return data\n\n    def _sample_state(self, x):\n        log_likelihood = 0.0\n        seq_len, batch_size, input_size = x.shape\n        assert seq_len == 1 and batch_size == 1\n\n        for key, props in self._data_map.items():\n            if props[\"type\"] in [\"continuous\", \"timestamp\"]:\n                mu_idx, sigma_idx, missing_idx = props[\"indices\"]\n                mu = x[0, 0, mu_idx]\n                sigma = torch.nn.functional.softplus(x[0, 0, sigma_idx])\n                dist = torch.distributions.normal.Normal(mu, sigma)\n                x[0, 0, mu_idx] = dist.sample()\n                x[0, 0, sigma_idx] = 0.0\n                log_likelihood += torch.sum(dist.log_prob(x[0, 0, mu_idx]))\n\n                dist = torch.distributions.Bernoulli(torch.sigmoid(x[0, 0, missing_idx]))\n                x[0, 0, missing_idx] = dist.sample()\n                x[0, 0, mu_idx] = x[0, 0, mu_idx] * (1.0 - x[0, 0, missing_idx])\n                log_likelihood += torch.sum(dist.log_prob(x[0, 0, missing_idx]))\n\n            elif props[\"type\"] in [\"count\"]:\n                r_idx, p_idx, missing_idx = props[\"indices\"]\n                r = torch.nn.functional.softplus(x[0, 0, r_idx]) * props[\"range\"]\n                p = torch.sigmoid(x[0, 0, p_idx])\n                dist = torch.distributions.negative_binomial.NegativeBinomial(r, p)\n                x[0, 0, r_idx] = dist.sample()\n                x[0, 0, p_idx] = 0.0\n                log_likelihood += torch.sum(dist.log_prob(x[0, 0, r_idx]))\n                x[0, 0, r_idx] /= props[\"range\"]\n\n                dist = torch.distributions.Bernoulli(torch.sigmoid(x[0, 0, missing_idx]))\n                x[0, 0, missing_idx] = dist.sample()\n                x[0, 0, r_idx] = x[0, 0, r_idx] * (1.0 - x[0, 0, missing_idx])\n                log_likelihood += torch.sum(dist.log_prob(x[0, 0, missing_idx]))\n\n            elif props[\"type\"] in [\"categorical\", \"ordinal\"]:\n                idx = list(props[\"indices\"].values())\n                p = torch.nn.functional.softmax(x[0, 0, idx], dim=0)\n                x_new = torch.zeros(p.size()).to(self.device)\n                x_new.scatter_(dim=0, index=torch.multinomial(p, 1), value=1)\n                x[0, 0, idx] = x_new\n                log_likelihood += torch.sum(torch.log(p) * x_new)\n\n            else:\n                raise ValueError()\n\n        return x, log_likelihood\n\n    def _sample_sequence(self, context, min_length, max_length):\n        log_likelihood = 0.0\n\n        x = torch.zeros(self._data_dims).to(self.device)\n        x[self._data_map[\"<TOKEN>\"][\"indices\"][\"<START>\"]] = 1.0\n        x = x.unsqueeze(0).unsqueeze(0)\n\n        for step in range(max_length):\n            next_x, ll = self._sample_state(self._model(x, context)[-1:, :, :])\n            x = torch.cat([x, next_x], dim=0)\n            log_likelihood += ll\n            if next_x[0, 0, self._data_map[\"<TOKEN>\"][\"indices\"][\"<END>\"]] > 0.0:\n                if min_length <= step + 1 <= max_length:\n                    break  # received end token\n\n                next_x[0, 0, self._data_map[\"<TOKEN>\"][\"indices\"][\"<BODY>\"]] = 1.0\n                next_x[0, 0, self._data_map[\"<TOKEN>\"][\"indices\"][\"<END>\"]] = 0.0\n\n        return x[1:, :, :], log_likelihood\n\n    def sample_sequence(self, context, sequence_length=None):\n\n        if sequence_length is not None:\n            min_length = max_length = sequence_length\n        else:\n            min_length = self._min_length\n            max_length = self._max_length\n\n        if self._ctx_dims:\n            context = self._context_to_tensor(context).unsqueeze(0)\n        else:\n            context = None\n\n        best_x, best_ll = None, float(\"-inf\")\n        for _ in range(self.sample_size):\n            with torch.no_grad():\n                x, log_likelihood = self._sample_sequence(context, min_length, max_length)\n\n            if log_likelihood > best_ll:\n                best_x = x\n                best_ll = log_likelihood\n\n        return self._tensor_to_data(best_x)\n\n\nclass BaseTimeseriesModel:\n    \"\"\"Base class for timeseries models.\n\n    Args:\n        field_names (list[str]):\n            List of names of the fields that need to be modeled\n            and included in the generated output data. Any additional\n            fields found in the data will be ignored and will not be\n            included in the generated output.\n            If ``None``, all the fields found in the data are used.\n        field_types (dict[str, dict]):\n            Dictinary specifying the data types and subtypes\n            of the fields that will be modeled. Field types and subtypes\n            combinations must be compatible with the SDV Metadata Schema.\n        anonymize_fields (dict[str, str]):\n            Dict specifying which fields to anonymize and what faker\n            category they belong to.\n        primary_key (str):\n            Name of the field which is the primary key of the table.\n        entity_columns (list[str]):\n            Names of the columns which identify different time series\n            sequences. These will be used to group the data in separated\n            training examples.\n        context_columns (list[str]):\n            The columns in the dataframe which are constant within each\n            group/entity. These columns will be provided at sampling time\n            (i.e. the samples will be conditioned on the context variables).\n        segment_size (int, pd.Timedelta or str):\n            If specified, cut each training sequence in several segments of\n            the indicated size. The size can either can passed as an integer\n            value, which will interpreted as the number of data points to\n            put on each segment, or as a pd.Timedelta (or equivalent str\n            representation), which will be interpreted as the segment length\n            in time. Timedelta segment sizes can only be used with sequence\n            indexes of type datetime.\n        sequence_index (str):\n            Name of the column that acts as the order index of each\n            sequence. The sequence index column can be of any type that can\n            be sorted, such as integer values or datetimes.\n        context_model (str or sdv.tabular.BaseTabularModel):\n            Model to use to sample the context rows. It can be passed as a\n            a string, which must be one of the following:\n\n            * `gaussian_copula` (default): Use a GaussianCopula model.\n\n            Alternatively, a preconfigured Tabular model instance can be\n            passed.\n\n        table_metadata (dict or metadata.Table):\n            Table metadata instance or dict representation.\n            If given alongside any other metadata-related arguments, an\n            exception will be raised.\n            If not given at all, it will be built using the other\n            arguments or learned from the data.\n    \"\"\"\n\n    _DTYPE_TRANSFORMERS = {\n        \"i\": None,\n        \"f\": None,\n        \"M\": rdt.transformers.DatetimeTransformer(strip_constant=True),\n        \"b\": None,\n        \"O\": None,\n    }\n    _CONTEXT_MODELS = {\n        \"gaussian_copula\": (\n            GaussianCopula,\n            {\"categorical_transformer\": \"categorical_fuzzy\"},\n        )\n    }\n\n    _metadata = None\n\n    def __init__(\n        self,\n        field_names=None,\n        field_types=None,\n        anonymize_fields=None,\n        primary_key=None,\n        entity_columns=None,\n        context_columns=None,\n        sequence_index=None,\n        segment_size=None,\n        context_model=None,\n        table_metadata=None,\n    ):\n        if table_metadata is None:\n            self._metadata = Table(\n                field_names=field_names,\n                primary_key=primary_key,\n                field_types=field_types,\n                anonymize_fields=anonymize_fields,\n                dtype_transformers=self._DTYPE_TRANSFORMERS,\n                sequence_index=sequence_index,\n                entity_columns=entity_columns,\n                context_columns=context_columns,\n            )\n            self._metadata_fitted = False\n        else:\n            null_args = (\n                field_names,\n                primary_key,\n                field_types,\n                anonymize_fields,\n                sequence_index,\n                entity_columns,\n                context_columns,\n            )\n            for arg in null_args:\n                if arg:\n                    raise ValueError(\"If table_metadata is given {} must be None\".format(arg.__name__))\n\n            if isinstance(table_metadata, dict):\n                table_metadata = Table.from_dict(\n                    table_metadata,\n                    dtype_transformers=self._DTYPE_TRANSFORMERS,\n                )\n\n            self._metadata = table_metadata\n            self._metadata_fitted = table_metadata.fitted\n\n        # Validate arguments\n        if segment_size is not None and not isinstance(segment_size, int):\n            if sequence_index is None:\n                raise TypeError(\"`segment_size` must be of type `int` if \" \"no `sequence_index` is given.\")\n\n            segment_size = pd.to_timedelta(segment_size)\n\n        self._context_columns = self._metadata._context_columns\n        self._entity_columns = self._metadata._entity_columns\n        self._sequence_index = self._metadata._sequence_index\n        self._segment_size = segment_size\n\n        context_model = context_model or \"gaussian_copula\"\n        if isinstance(context_model, str):\n            context_model = self._CONTEXT_MODELS[context_model]\n\n        self._context_model_template = context_model\n\n    def _fit(self, sequence_loader, timeseries_data_example):\n        raise NotImplementedError()\n\n    def _fit_context_model(self, transformed):\n        template = self._context_model_template\n        default_kwargs = {\n            \"primary_key\": self._entity_columns,\n            \"field_types\": {\n                name: meta for name, meta in self._metadata.get_fields().items() if name in self._entity_columns\n            },\n        }\n        if isinstance(template, tuple):\n            context_model_class, context_model_kwargs = copy.deepcopy(template)\n            if \"primary_key\" not in context_model_kwargs:\n                context_model_kwargs[\"primary_key\"] = self._entity_columns\n                for keyword, argument in default_kwargs.items():\n                    if keyword not in context_model_kwargs:\n                        context_model_kwargs[keyword] = argument\n\n            self._context_model = context_model_class(**context_model_kwargs)\n        elif isinstance(template, type):\n            self._context_model = template(**default_kwargs)\n        else:\n            self._context_model = copy.deepcopy(template)\n\n        LOGGER.debug(\"Fitting context model %s\", self._context_model.__class__.__name__)\n        if self._context_columns:\n            context = transformed[self._entity_columns + self._context_columns]\n        else:\n            context = transformed[self._entity_columns].copy()\n            # Add constant column to allow modeling\n            context[str(uuid.uuid4())] = 0\n\n        context = context.groupby(self._entity_columns).first().reset_index()\n        self._context_model.fit(context)\n\n    def fit(self, sequence_loader, columns, types, examples):\n        self._fit(sequence_loader, columns, types, examples)\n\n    def get_metadata(self):\n        \"\"\"Get metadata about the table.\n\n        This will return an ``sdv.metadata.Table`` object containing\n        the information about the data that this model has learned.\n\n        This Table metadata will contain some common information,\n        such as field names and data types, as well as additional\n        information that each Sub-class might add, such as the\n        observed data field distributions and their parameters.\n\n        Returns:\n            sdv.metadata.Table:\n                Table metadata.\n        \"\"\"\n        return self._metadata\n\n    def _sample(self, context=None, sequence_length=None):\n        raise NotImplementedError()\n\n    def sample(self, context=None, sequence_length=None):\n        \"\"\"Sample new sequences.\n\n        Args:\n            num_sequences (int):\n                Number of sequences to sample. If context is\n                passed, this is ignored. If not given, the\n                same number of sequences as in the original\n                timeseries_data is sampled.\n            context (pandas.DataFrame):\n                Context values to use when generating the sequences.\n                If not passed, the context values will be sampled\n                using the specified tabular model.\n            sequence_length (int):\n                If passed, sample sequences of this length. If not\n                given, the sequence length will be sampled from\n                the model.\n\n        Returns:\n            pandas.DataFrame:\n                Table containing the sampled sequences in the same\n                format as that he training data had.\n        \"\"\"\n        num_sequences = 1  # TODO this was missing. Should it be an argument?\n        if not self._entity_columns:\n            if context is not None:\n                raise TypeError(\"If there are no entity_columns, context must be None\")\n\n            context = pd.DataFrame(index=range(num_sequences or 1))\n        elif context is None:\n            context = self._context_model.sample(num_sequences)\n            for column in self._entity_columns or []:\n                if column not in context:\n                    context[column] = range(len(context))\n\n        sampled = self._sample(context, sequence_length)\n        return sampled\n\n    def save(self, path):\n        \"\"\"Save this model instance to the given path using pickle.\n\n        Args:\n            path (str):\n                Path where the SDV instance will be serialized.\n        \"\"\"\n        with open(path, \"wb\") as output:\n            pickle.dump(self, output)\n\n    @classmethod\n    def load(cls, path):\n        \"\"\"Load a TabularModel instance from a given path.\n\n        Args:\n            path (str):\n                Path from which to load the instance.\n\n        Returns:\n            TabularModel:\n                The loaded tabular model.\n        \"\"\"\n        with open(path, \"rb\") as f:\n            return pickle.load(f)\n\n\nclass DeepEchoModel(BaseTimeseriesModel):\n    \"\"\"Base class for all the SDV Time series models based on DeepEcho.\"\"\"\n\n    _MODEL_CLASS = None\n    _model_kwargs = None\n\n    _DATA_TYPES = {\n        \"numerical\": \"continuous\",\n        \"categorical\": \"categorical\",\n        \"boolean\": \"categorical\",\n        \"datetime\": \"datetime\",\n    }\n\n    _verbose = True\n\n    def _build_model(self):\n        return self._MODEL_CLASS(**self._model_kwargs)\n\n    def _transform_sequence_index(self, sequences):\n        sequence_index_idx = self._data_columns.index(self._sequence_index)\n        for sequence in sequences:\n            data = sequence[\"data\"]\n            sequence_index = data[sequence_index_idx]\n            diffs = np.diff(sequence_index).tolist()\n            data[sequence_index_idx] = diffs[0:1] + diffs\n            data.append(sequence_index[0:1] * len(sequence_index))\n\n    def _fit(self, sequence_loader, columns, types, examples):\n\n        self._model = self._build_model()\n\n        # Specify output columns in self._data_columns\n        self._output_columns = columns\n        self._data_columns = [\n            column for column in columns if column not in self._entity_columns + self._context_columns\n        ]\n\n        # Validate and fit\n        dem = self\n        self._model.fit_sequences(sequence_loader, columns, types, examples, dem)\n\n    def _sample(self, context=None, sequence_length=None):\n        \"\"\"Sample new sequences.\n\n        Args:\n            context (pandas.DataFrame):\n                Context values to use when generating the sequences.\n                If not passed, the context values will be sampled\n                using the specified tabular model.\n            sequence_length (int):\n                If passed, sample sequences of this length. If not\n                given, the sequence length will be sampled from\n                the model.\n\n        Returns:\n            pandas.DataFrame:\n                Table containing the sampled sequences in the same\n                format as that he training data had.\n        \"\"\"\n        # Set the entity_columns as index to properly iterate over them\n        if self._entity_columns:\n            context = context.set_index(self._entity_columns)\n\n        iterator = tqdm(context.iterrows(), disable=not self._verbose, total=len(context))\n\n        output = list()\n        for entity_values, context_values in iterator:\n            context_values = context_values.tolist()\n            sequence = self._model.sample_sequence(context_values, sequence_length)\n            if self._sequence_index:\n                sequence_index_idx = self._data_columns.index(self._sequence_index)\n                diffs = sequence[sequence_index_idx]\n                start = sequence[-1]\n                sequence[sequence_index_idx] = np.cumsum(diffs) - diffs[0] + start\n\n            # Reformat as a DataFrame\n            group = pd.DataFrame(dict(zip(self._data_columns, sequence)), columns=self._data_columns)\n            group[self._entity_columns] = entity_values\n            for column, value in zip(self._context_columns, context_values):\n                if column == self._sequence_index:\n                    sequence_index = group[column]\n                    group[column] = sequence_index.cumsum() - sequence_index.iloc[0] + value\n                else:\n                    group[column] = value\n\n            output.append(group)\n\n        output = pd.concat(output)\n        return output[self._output_columns].reset_index(drop=True)\n\n\nclass PAREdit(DeepEchoModel):\n    _MODEL_CLASS = PARModel\n\n    def __init__(\n        self,\n        field_names=None,\n        field_types=None,\n        anonymize_fields=None,\n        primary_key=None,\n        entity_columns=None,\n        context_columns=None,\n        sequence_index=None,\n        segment_size=None,\n        context_model=None,\n        table_metadata=None,\n        epochs=128,\n        sample_size=1,\n        cuda=True,\n        verbose=True,\n    ):\n        super().__init__(\n            field_names=field_names,\n            field_types=field_types,\n            anonymize_fields=anonymize_fields,\n            primary_key=primary_key,\n            entity_columns=entity_columns,\n            context_columns=context_columns,\n            sequence_index=sequence_index,\n            segment_size=segment_size,\n            context_model=context_model,\n            table_metadata=table_metadata,\n        )\n\n        self._model_kwargs = {\n            \"epochs\": epochs,\n            \"sample_size\": sample_size,\n            \"cuda\": cuda,\n            \"verbose\": verbose,\n        }\n        self._verbose = verbose\n", "meta": {"hexsha": "3dfebf2e1f83f778e411d20a326de1314a50ecbd", "size": 36953, "ext": "py", "lang": "Python", "max_stars_repo_path": "neural_lifetimes/models/nets/custom_par.py", "max_stars_repo_name": "transferwise/neural-lifetimes", "max_stars_repo_head_hexsha": "59d0ee2b7413bc44d2f45be9d71c491d29df6c58", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-28T15:39:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T23:59:36.000Z", "max_issues_repo_path": "neural_lifetimes/models/nets/custom_par.py", "max_issues_repo_name": "transferwise/neural-lifetimes", "max_issues_repo_head_hexsha": "59d0ee2b7413bc44d2f45be9d71c491d29df6c58", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "neural_lifetimes/models/nets/custom_par.py", "max_forks_repo_name": "transferwise/neural-lifetimes", "max_forks_repo_head_hexsha": "59d0ee2b7413bc44d2f45be9d71c491d29df6c58", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2932642487, "max_line_length": 112, "alphanum_fraction": 0.5438530025, "include": true, "reason": "import numpy", "num_tokens": 7938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.29421495978593415, "lm_q1q2_score": 0.15514440972057794}}
{"text": "from rdkit import Chem\nimport numpy as np\nfrom rdkit.Chem import rdqueries\nfrom ase.data import atomic_numbers\nfrom collections import defaultdict\nfrom ase import Atoms as ASEAtoms\nfrom ase import Atom as ASEAtom\n\nSurfaceElements = ('Ag','Au','Co','Cu','Fe','Ir','Ni','Pd','Pt','Re','Rh','Ru')\nSurfaceAtomicNumbers = tuple([0]+[atomic_numbers[s] for s in SurfaceElements])\n# Elements of adsorbate atoms\nAdsorbateElements = ('H','C','O','N')\nAdsorbateAtomicNumbers = tuple([atomic_numbers[s] for s in AdsorbateElements])\n\nValence = {6:4,8:2}\ndef GetGraphDescriptors(smiles,maxatom=3):\n    # get mol\n    mol = Chem.MolFromSmiles(smiles,sanitize=False)\n    for atom in mol.GetAtoms():\n        if atom.GetAtomicNum() in [1,6,8]:\n            atom.SetNoImplicit(True)\n            atom.SetNumRadicalElectrons(1)\n    mol = Chem.RWMol(mol)\n    for i in reversed(range(mol.GetNumAtoms())):\n        atom = mol.GetAtomWithIdx(i)\n        if atom.GetAtomicNum() == 2:\n            mol.RemoveAtom(i)\n            \n    # atom descriptors\n    descriptors = []\n    for atom in mol.GetAtoms():\n        an = atom.GetAtomicNum()\n        if an in [6,8]:\n            OrganicDegree = 0\n            SurfaceDegree = 0\n            for nn in atom.GetNeighbors(): # calculate degree\n                nnan = nn.GetAtomicNum()\n                if nnan in [1,6,8]:\n                    OrganicDegree +=1\n                elif nnan == 0:\n                    SurfaceDegree +=1\n            valency = Valence[an] - OrganicDegree\n            descriptor = '_'.join([str(an),str(valency),str(SurfaceDegree)])\n            descriptors.append('['+descriptor+']')\n    descriptors = [descriptors]\n    \n    # Extract just the organic atoms\n    omol = Chem.RWMol(mol.__copy__())\n    omolidx = []\n    for i in reversed(range(mol.GetNumAtoms())):\n        atom = omol.GetAtomWithIdx(i)\n        if atom.GetAtomicNum() not in [6,8]:\n            omol.RemoveAtom(i)\n        else:\n            omolidx.append(i)\n    omol2mol = {i:v for i,v in enumerate(reversed(omolidx))}\n    \n    # find organic molecule based subgraphs and map atom index back to mol atom index\n    subgraph_atom_idxss = []\n    for bidxss in Chem.FindAllSubgraphsOfLengthMToN(omol,1,maxatom-1):\n        subgraph_atom_idxs = []\n        for bidxs in bidxss:\n            aidx = []\n            for bidx in bidxs:\n                bond = omol.GetBondWithIdx(bidx)\n                aidx.append(bond.GetBeginAtomIdx())\n                aidx.append(bond.GetEndAtomIdx())\n            aidx = list(set(aidx))\n            aidx = [omol2mol[i] for i in aidx]\n            subgraph_atom_idxs.append(aidx)\n        subgraph_atom_idxss.append(subgraph_atom_idxs)\n    del omol\n    # find subgraphs\n    ## surface idx\n    surf_idx = []\n    for atom in mol.GetAtoms():\n        if atom.GetAtomicNum() == 0:\n            surf_idx.append(atom.GetIdx())\n    for subgraph_atom_idxs in subgraph_atom_idxss:\n        subgraph_descriptors_of_size_i = []\n        for organic_atoms_to_preserve in subgraph_atom_idxs:\n            # extract atoms of the bond and those connected to those atoms\n            organic_atoms_to_change = []\n            for i in organic_atoms_to_preserve:\n                atom = mol.GetAtomWithIdx(i)\n                for natom in atom.GetNeighbors():\n                    if natom.GetAtomicNum() in [1,6,8]:\n                        organic_atoms_to_change.append(natom.GetIdx())\n            organic_atoms_to_preserve = set(organic_atoms_to_preserve)\n            organic_atoms_to_change = set(organic_atoms_to_change)\n            organic_atoms_to_change -= organic_atoms_to_preserve\n            # extract subgraph\n            submol = Chem.RWMol(mol.__copy__())\n            for i in organic_atoms_to_change:\n                R = Chem.Atom(1)\n                submol.ReplaceAtom(i,R)\n            for i in reversed(range(submol.GetNumAtoms())):\n                if i not in organic_atoms_to_preserve and i not in organic_atoms_to_change \\\n                    and i not in surf_idx:\n                    submol.RemoveAtom(i)\n            submol = RemoveLatticeAmbiguity(submol)\n            subgraph_descriptors_of_size_i.append(Chem.MolToSmiles(submol))\n            del submol\n        descriptors.append(subgraph_descriptors_of_size_i)\n    return descriptors\n\ndef GetGasMolFromSmiles(smiles):\n    mol = Chem.MolFromSmiles(smiles,sanitize=False)\n    mol = Chem.RWMol(mol)\n    for i in reversed(range(mol.GetNumAtoms())):\n        atom = mol.GetAtomWithIdx(i)\n        if atom.GetAtomicNum() in [1,6,8]:\n            atom.SetNoImplicit(True)\n            atom.SetNumRadicalElectrons(1)\n        else:\n            mol.RemoveAtom(i)\n    return Chem.MolToSmiles(mol)\n\ndef RemoveLatticeAmbiguity(OriginalMol):\n    \"\"\"\n    Remove ambiguity in the subgraph provided. See manuscript for the \n    mechanism of this.\n    \n    Input:\n        OriginalMol - Chem.Mol or RWMol Object.\n        SubgraphIdx - List of Index of the atoms in subgraph.\n    Output:\n        Updated SubgraphIdx\n    \"\"\"\n    # Initialize\n    ## isolate surface of subgraph\n    ## Extract surface atom index in the subgraph\n    AAL = set() # (A)dsorbate (A)tom (L)ist\n    SSAL = set() # (S)elected (S)urface (A)tom (L)ist\n    SAL = set() # (S)urface (A)tom (L)ist\n    for Idx in range(0,OriginalMol.GetNumAtoms()):\n        atom = OriginalMol.GetAtomWithIdx(Idx)\n        if atom.GetAtomicNum() in SurfaceAtomicNumbers:\n            SAL.add(Idx)\n            for na in atom.GetNeighbors():\n                #if na.GetAtomicNum() in AdsorbateAtomicNumbers[1:]: # exclude hydrogen\n                if na.GetAtomicNum() in AdsorbateAtomicNumbers: \n                    SSAL.add(Idx)\n                    break\n\n        elif atom.GetAtomicNum() in AdsorbateAtomicNumbers:\n            AAL.add(Idx)\n    SubgraphIdx = AAL | SSAL\n    ## Check if surface atoms are fragmented\n    AtomsToCheckList = list(SSAL)\n    Surface_Fragments = list()\n    while AtomsToCheckList:\n        # initialize\n        # here a single bridge is identified\n        Atom = OriginalMol.GetAtomWithIdx(AtomsToCheckList.pop())\n        Surface_Fragment = set()\n        Surface_Fragment.add(Atom.GetIdx())\n        NeighborsToCheck = list(Atom.GetNeighbors())\n        # find all possible surface atoms in this fragment\n        while NeighborsToCheck:\n            AtomBeingChecked = NeighborsToCheck.pop()\n            if AtomBeingChecked.GetIdx() in SSAL and \\\n                AtomBeingChecked.GetIdx() not in Surface_Fragment:\n                Surface_Fragment.add(AtomBeingChecked.GetIdx())\n                NeighborsToCheck += AtomBeingChecked.GetNeighbors()\n        # Add to fragment list\n        Surface_Fragments.append(Surface_Fragment)\n        # Remove checked atoms\n        AtomsToCheckList = [value for value in AtomsToCheckList if value not in Surface_Fragment]\n    \n\n    # if the length Surface_Fragments is more than 1, then the surface is fragmented\n    if len(Surface_Fragments) > 1:\n        # Extract surface\n        BondToBreak = set()\n        for idx in SSAL:\n            Atom = OriginalMol.GetAtomWithIdx(idx)\n            for Bond in Atom.GetBonds():\n                if Bond.GetOtherAtom(Atom).GetIdx() not in SAL:\n                    BondToBreak.add(Bond.GetIdx())\n        SurfaceGraph = Chem.FragmentOnBonds(OriginalMol,list(BondToBreak),addDummies=False)\n\n        ########################################################################\n        Surf = Surface_Fragments[0]\n        for s in Surface_Fragments[1:]:\n            Surf.update(s)\n        # BRS Based shortest path find\n        NewSurfIdx = BFSShortestPath(SurfaceGraph,list(Surf))\n        SubgraphIdx |= NewSurfIdx\n        SSAL |= NewSurfIdx\n\n        #######################################################################\n    \n    SubgraphIdx = list(SubgraphIdx)\n    ## initialize \n    NSAD = defaultdict(int) # (N)eighbor (S)urface (A)tom (D)ict\n    ## intial dict list\n    for SSAIdx in SSAL:\n        for NeighborAtom in OriginalMol.GetAtomWithIdx(SSAIdx).GetNeighbors():\n            if NeighborAtom.GetAtomicNum() in SurfaceAtomicNumbers:\n                if NeighborAtom.GetIdx() not in SSAL:\n                    NSAD[NeighborAtom.GetIdx()] += 1\n    # add nonselected surface atoms to subgraph\n    for idx in NSAD:\n        if NSAD[idx] > 1:\n            SubgraphIdx.append(idx)\n    \n    ## add second layer \n    for atom in OriginalMol.GetAtoms():\n        if atom.GetAtomicNum() == 2:\n            na = 0\n            for natom in atom.GetNeighbors():\n                if natom.GetIdx() in SubgraphIdx:\n                    na += 1\n            if na ==3:\n                SubgraphIdx.append(atom.GetIdx())\n    \n    BondList = GetBondListFromAtomList(OriginalMol, SubgraphIdx)\n    if BondList:\n        mol = Chem.PathToSubmol(OriginalMol,BondList)\n    else: # if adsorbate is one atom, there is no bond list, so just return the atom.\n        mol = Chem.RWMol(Chem.Mol())\n        mol.AddAtom(OriginalMol.GetAtomWithIdx(list(AAL)[0]).__copy__())\n    return mol\n\n\ndef GetBondListFromAtomList(Mol, AtomList):\n    \"\"\"\n    Given a mol object and Atom Index list, Bond between atoms in atom list are\n    printed. Typically used to use rdkit.Chem.PathToSubmol to extract subgraph.\n    PathToSubmol is the most efficient subgraph extraction. See\n    \"def RemoveUnoccupiedSurfaceAtom\" below for an example this.\n    \n    Input:\n        Mol - Chem.Mol or RWMol Object.\n        AtomList - Indexes of atom.\n    Output:\n        List of bond idx.\n    \"\"\"\n    BondList = set()\n    for idx in AtomList:\n        atom = Mol.GetAtomWithIdx(idx)\n        for bond in atom.GetBonds():\n            if bond.GetOtherAtomIdx(atom.GetIdx()) in AtomList:\n                BondList.add(bond.GetIdx())\n    return list(BondList)\n\n\n\nclass SurfHelper(object):\n    def __init__(self,size):\n        # Construct Surface\n        surf = Lattice.ConstructRectangularClosePackedLattice(size,size,PBC=False)\n        # Get Surfrace Mol\n        atomidx = []\n        for i,s in enumerate(surf._Sites):\n            if 'self' in s._RepresentedAtoms:\n                atomidx.append(i)\n        self.xyz = surf.GetCoordinates()[atomidx,:]\n        \n        self.sites = []\n        for i,s in enumerate(surf._Sites):\n            if 'self' in s._RepresentedAtoms:\n                self.sites.append(frozenset([int(i)]))\n            else:\n                self.sites.append(frozenset([int(ss) for ss in s._RepresentedAtoms]))\n        self.SurfMol = surf.GetRdkitMolEnum()\n        # Get Center Atom index in rdkit mol\n        SurfAtomCoordinates = list()\n        for i in range(0,len(surf._Sites)):\n            if 'self' in surf._Sites[i]._RepresentedAtoms:\n                SurfAtomCoordinates.append(surf._Sites[i].GetCoordinate())\n        CenterAtomIdx = np.linalg.norm(SurfAtomCoordinates - np.array([0.5,0.5,0]),axis=1).argmin()\n        self.SurfMol.GetAtomWithIdx(int(CenterAtomIdx)).SetBoolProp('CenterSurfAtom',True)\n        \n        \n        \n    def AddAdsorbateToSurf(self,AdsorbateSmiles):\n        # Prepare Adsorbate\n        AdsorbateMol = Chem.MolFromSmiles(AdsorbateSmiles,sanitize=False)\n        \n        # Get list of Surface Atom Indices\n        SurfIdxs = list()\n        GasIdxs = list()\n        for atom in AdsorbateMol.GetAtoms():\n            if atom.GetAtomicNum() not in [1,6,8]:\n                SurfIdxs.append(atom.GetIdx())\n            else:\n                GasIdxs.append(atom.GetIdx())\n        #Chem.SanitizeMol(AdsorbateMol)\n        AdsorbateMol.UpdatePropertyCache(False)\n        ## Get SurfMol\n        AdsorbateSurfMol, AdsorbateToAdsorbateSurf, AdsorbateSurfToAdsorbate =  GetSubMolFromIdx(SurfIdxs,AdsorbateMol)\n        ### Set up for matching\n        SA = rdqueries.AtomNumEqualsQueryAtom(0)\n        for idx in range(0,AdsorbateSurfMol.GetNumAtoms()):\n            AdsorbateSurfMol.ReplaceAtom(idx,SA)\n        SA.ExpandQuery(rdqueries.HasPropQueryAtom('CenterSurfAtom'))\n        AdsorbateSurfMol.ReplaceAtom(0,SA)\n        ## Get GasMol\n        AdsorbateGasMol, AdsorbateToAdsorbateGas, AdsorbateGasToAdsorbate =  GetSubMolFromIdx(GasIdxs,AdsorbateMol)\n        Chem.SanitizeMol(AdsorbateGasMol)\n        AdsorbateGasMol = AdsorbateGasMol.GetMol()\n        ## Match Surface\n        ProjectedSurfIdxs = self.SurfMol.GetSubstructMatches(AdsorbateSurfMol)[0]\n    \n        # Combine Two mol\n        NewMol = Chem.RWMol(Chem.CombineMols(self.SurfMol,AdsorbateGasMol))\n        OccupiedSurfIdxs = set()\n        for bond in AdsorbateMol.GetBonds():\n            # Find Surface-Adsorbate bond\n            SurfAtomIdx = None\n            GasAtomIdx = None\n            atoms = [bond.GetBeginAtom(),bond.GetEndAtom()]\n            for atom in atoms:\n                if atom.GetAtomicNum() in [1,6,8]:\n                    GasAtomIdx = atom.GetIdx()\n                else:\n                    SurfAtomIdx = atom.GetIdx()\n            # if the bond between adsorbate and surface\n            if SurfAtomIdx is not None and GasAtomIdx is not None:\n                GasMappedIdx = AdsorbateToAdsorbateGas[GasAtomIdx] + self.SurfMol.GetNumAtoms()\n                SurfMappedIdx = ProjectedSurfIdxs[AdsorbateToAdsorbateSurf[SurfAtomIdx]]\n                NewMol.AddBond(GasMappedIdx,SurfMappedIdx,order=Chem.rdchem.BondType.SINGLE)\n                OccupiedSurfIdxs.add(SurfMappedIdx)\n                \n        # Set up property\n        for idx in AdsorbateGasToAdsorbate:\n            idx = idx + self.SurfMol.GetNumAtoms()\n            atom = NewMol.GetAtomWithIdx(idx)\n            atom.SetNumRadicalElectrons(0)\n            \n        M = Chem.Atom(0)\n        for idx in OccupiedSurfIdxs:\n            NewMol.ReplaceAtom(idx,M)\n            \n        # Indexing via isotope\n        # This is done to record original index\n        for i,atom in enumerate(NewMol.GetAtoms()):\n            atom.SetIsotope(i+1) # start counting from 1 since 0 is default value\n        \n        return NewMol\n\n    def GetCanonicalSmiles(self,s):\n        reloadedmol = self.AddAdsorbateToSurf(s)\n        reloadedmol = Chem.RWMol(RemoveLatticeAmbiguity(reloadedmol))\n        reloadedmol = reloadedmol.GetMol()\n        for atom in reloadedmol.GetAtoms():\n            atom.SetIsotope(0)\n            if atom.GetAtomicNum() in [1,6,8]:\n                atom.SetNumRadicalElectrons(1)\n            \n        return Chem.MolToSmiles(reloadedmol)\n    \n\n\nclass Lattice(object):\n    def __init__(self,Sites=[],SiteNames=[], DistanceMultiplier=[],Cell=np.eye(3),PBC=False):\n        # Error Check\n        assert isinstance(Sites, list), 'Sites is not a list.'\n        for site in Sites:\n            assert isinstance(site,Site), 'Site is not a Site object'\n        self._SiteNames = SiteNames\n        self._DistanceMultiplier = DistanceMultiplier #This number is multiplied before deciding which atom is at which site.\n        self._Sites = Sites\n        self.SetCell(Cell)\n        self.SetPBC(PBC)\n        \n    def SetCell(self, Cell, KeepAbsCoord=False):\n        Cell = np.array(Cell, float)\n        if Cell.shape == (3,):\n            Cell = np.diag(Cell)\n        elif Cell.shape != (3, 3):\n            raise ValueError('Cell must be length 3 sequence or 3x3 matrix')\n        \n        \n        if KeepAbsCoord:\n            Cell_inv = np.linalg.inv(Cell.transpose())\n            for i in range(0,len(self._Sites)):\n                pos = np.dot(self._Cell.transpose(),self._Sites[i]._Coordinate.transpose()).transpose()\n                self._Sites[i]._Coordinate = np.dot(Cell_inv,pos.transpose()).transpose()  \n                \n        self._Cell = Cell\n    def SetPBC(self, PBC):\n        \"\"\"Set periodic boundary condition flags.\"\"\"\n        if isinstance(PBC, bool):\n            PBC = (PBC,) * 3\n        else:\n            try:\n                iter(PBC)\n            except TypeError:\n                raise TypeError('PBC must be iterable or a bool')\n            assert len(PBC) == 3, 'iterable PBC must be 3 sequence'\n            for cond in PBC:\n                assert isinstance(cond, bool), \\\n                'each element in PBC must be bool'\n        self._PBC = np.array(PBC, bool)\n        \n    def GetRdkitMol(self,SurfaceAtomSymbol = 'Pt',queryatom=True):\n        # initialize\n        surface = Chem.RWMol(Chem.Mol())\n        # add toms\n        for site in self._Sites:\n            if 'self' in site._RepresentedAtoms:\n                if queryatom:\n                    atom = rdqueries.HasStringPropWithValueQueryAtom('Type','S')\n                    atom.ExpandQuery(rdqueries.HasBoolPropWithValueQueryAtom('Occupied',False))\n                    atom.SetProp('smilesSymbol','M')\n                    atom.SetProp('Type','S')\n                    atom.SetBoolProp('Occupied',False)\n                else:\n                    if SurfaceAtomSymbol:\n                        atom = Chem.Atom(SurfaceAtomSymbol)\n                    else:\n                        atom = Chem.Atom(0)\n                    atom.SetProp('smilesSymbol','M')\n                    atom.SetProp('Type','S')\n                    atom.SetBoolProp('Occupied',False)\n                surface.AddAtom(atom)\n        # add bonds\n        for i in range(0,len(self._Sites)):\n            if 'self' in self._Sites[i]._RepresentedAtoms:\n                for j in self._Sites[i]._AtomNeighbors:\n                    if not surface.GetBondBetweenAtoms(i,int(j)):\n                        surface.AddBond(i,int(j),order=Chem.rdchem.BondType.ZERO)\n        Chem.SanitizeMol(surface)\n        surface = surface.GetMol()\n        Chem.SanitizeMol(surface)\n        return surface\n    def GetRdkitMolEnum(self):\n        # initialize\n        surface = Chem.RWMol(Chem.Mol())\n        # add toms\n        for site in self._Sites:\n            if 'self' in site._RepresentedAtoms:\n                atom = Chem.Atom(0)\n                surface.AddAtom(atom)\n        # add bonds\n        for i in range(0,len(self._Sites)):\n            if 'self' in self._Sites[i]._RepresentedAtoms:\n                for j in self._Sites[i]._AtomNeighbors:\n                    if not surface.GetBondBetweenAtoms(i,int(j)):\n                        surface.AddBond(i,int(j),order=Chem.rdchem.BondType.SINGLE)\n        Chem.SanitizeMol(surface)\n        surface = surface.GetMol()\n        Chem.SanitizeMol(surface)\n        return surface\n    def AppendSurfaceToRdkitMol(self,mol,SurfaceAtomSymbol = 'Pt',queryatom=True):\n        # initialize\n        if isinstance(mol,Chem.Mol):\n            mol = Chem.RWMol(mol)\n        assert isinstance(mol,Chem.RWMol)\n        NAtoms = mol.GetNumAtoms()\n        LatticeToMolMap = dict()\n        MolToLatticeMap = dict()\n        # add atoms\n        for i in range(0,len(self._Sites)):\n            if 'self' in self._Sites[i]._RepresentedAtoms:\n                if queryatom:\n                    atom = rdqueries.HasStringPropWithValueQueryAtom('Type','S')\n                    atom.ExpandQuery(rdqueries.HasBoolPropWithValueQueryAtom('Occupied',False))\n                    atom.SetProp('smilesSymbol','M')\n                    atom.SetProp('Type','S')\n                    atom.SetBoolProp('Occupied',False)\n                else:\n                    atom = Chem.Atom(SurfaceAtomSymbol)\n                    atom.SetProp('smilesSymbol','M')\n                    atom.SetProp('Type','S')\n                    atom.SetBoolProp('Occupied',False)\n                rdkitidx = mol.AddAtom(atom)\n                LatticeToMolMap[i] = rdkitidx\n                MolToLatticeMap[rdkitidx] = i\n        # add bonds\n        for i in range(0,len(self._Sites)):\n            if 'self' in self._Sites[i]._RepresentedAtoms:\n                for j in self._Sites[i]._AtomNeighbors:\n                    try:\n                        mol.AddBond(NAtoms+i,NAtoms+int(j),order=Chem.rdchem.BondType.ZERO)\n                    except:\n                        pass\n        return mol, LatticeToMolMap, MolToLatticeMap\n \n    def GetFracCoordinates(self):\n        mat = list()\n        for site in self._Sites:\n            mat.append(site._Coordinate)\n        return np.array(mat)\n    \n    def GetCoordinates(self):\n        mat = self.GetFracCoordinates()\n        return np.dot(self._Cell.transpose(),mat.transpose()).transpose()\n        \n    def GetCoordinatesWithCell(self,Cell):\n        if not Cell.__class__ == np.ndarray:\n            Cell = np.array(Cell)\n        mat = self.GetFracCoordinates()\n        \n        return np.dot(Cell.transpose(),mat.transpose()).transpose()\n    \n    def TranslateCoordinates(self,coordinate):\n        B_inv = np.linalg.inv(self._Cell.transpose())\n        for site in self._Sites:\n            pos = np.dot(self._Cell.transpose(),site._Coordinate.transpose()).transpose()\n            pos += coordinate\n            site._Coordinate = np.dot(B_inv,pos.transpose()).transpose()\n            \n    def MakeASEAtoms(self,highlight = None):\n        atoms = ASEAtoms()\n        coord = self.GetCoordinates()*2.5\n        for i in range(0,coord.shape[0]):\n            if highlight and i in highlight:\n                atoms.append(ASEAtom('Pt',coord[i,:]))\n            elif self._Sites[i]._SiteType == 0:\n                atoms.append(ASEAtom('C',coord[i,:]))\n            elif self._Sites[i]._SiteType == 1:\n                atoms.append(ASEAtom('O',coord[i,:]))\n            elif self._Sites[i]._SiteType == 2:\n                atoms.append(ASEAtom('N',coord[i,:]))\n        return atoms\n\n    @classmethod\n    def ConstructRectangularClosePackedLattice(cls, x_max,y_max, PBC=True):\n        # option\n        rd = 10 # rounding decimals   \n        \n        # Error check\n        assert x_max > 1, \"x_max too small\"\n        assert y_max > 1, \"y_max too small\"\n        # set unit cell size\n        Cell = [[2*x_max,0,0],[0,2*np.sqrt(3)/2*y_max,0],[0,0,1]]\n        Cell = np.array(Cell)\n        \n        # Construct atop site coordinates\n        ac = np.zeros((4*x_max*y_max,3))\n        for y in range(0,y_max):\n            for x in range(0,x_max):\n                ac[4*(x+y*x_max),0] = 2*x\n                ac[4*(x+y*x_max),1] = 2*np.sqrt(3)/2*y\n                ac[4*(x+y*x_max)+1,0] = 2*x + 1\n                ac[4*(x+y*x_max)+1,1] = 2*np.sqrt(3)/2*y\n                ac[4*(x+y*x_max)+2,0] = 2*x + 0.5\n                ac[4*(x+y*x_max)+2,1] = np.sqrt(3)/2 + 2*np.sqrt(3)/2*y\n                ac[4*(x+y*x_max)+3,0] = 2*x + 1.5\n                ac[4*(x+y*x_max)+3,1] = np.sqrt(3)/2 + 2*np.sqrt(3)/2*y\n        # Construct bridge site coordinates\n        bc = np.zeros((12*x_max*y_max,3))\n        for y in range(0,y_max):\n            for x in range(0,x_max):\n                bc[12*(x+y*x_max),0] = 0.5+2*x\n                bc[12*(x+y*x_max),1] = 2*np.sqrt(3)/2*y\n                bc[12*(x+y*x_max)+1,0] = 1.5+2*x\n                bc[12*(x+y*x_max)+1,1] = 2*np.sqrt(3)/2*y\n                \n                bc[12*(x+y*x_max)+2,0] = 0.25+2*x\n                bc[12*(x+y*x_max)+2,1] = np.sqrt(3)/2/2 + 2*np.sqrt(3)/2*y\n                bc[12*(x+y*x_max)+3,0] = 0.75+2*x\n                bc[12*(x+y*x_max)+3,1] = np.sqrt(3)/2/2 + 2*np.sqrt(3)/2*y\n                bc[12*(x+y*x_max)+4,0] = 1.25+2*x\n                bc[12*(x+y*x_max)+4,1] = np.sqrt(3)/2/2 + 2*np.sqrt(3)/2*y\n                bc[12*(x+y*x_max)+5,0] = 1.75+2*x\n                bc[12*(x+y*x_max)+5,1] = np.sqrt(3)/2/2 + 2*np.sqrt(3)/2*y\n                \n                bc[12*(x+y*x_max)+6,0] = 2*x\n                bc[12*(x+y*x_max)+6,1] = np.sqrt(3)/2 + 2*np.sqrt(3)/2*y\n                bc[12*(x+y*x_max)+7,0] = 1+2*x\n                bc[12*(x+y*x_max)+7,1] = np.sqrt(3)/2 + 2*np.sqrt(3)/2*y\n                \n                bc[12*(x+y*x_max)+8,0] = 0.25+2*x\n                bc[12*(x+y*x_max)+8,1] = np.sqrt(3)/2/2*3 + 2*np.sqrt(3)/2*y\n                bc[12*(x+y*x_max)+9,0] = 0.75+2*x\n                bc[12*(x+y*x_max)+9,1] = np.sqrt(3)/2/2*3 + 2*np.sqrt(3)/2*y\n                bc[12*(x+y*x_max)+10,0] = 1.25+2*x\n                bc[12*(x+y*x_max)+10,1] = np.sqrt(3)/2/2*3 + 2*np.sqrt(3)/2*y\n                bc[12*(x+y*x_max)+11,0] = 1.75+2*x\n                bc[12*(x+y*x_max)+11,1] = np.sqrt(3)/2/2*3 + 2*np.sqrt(3)/2*y\n                \n\n        # Construct fcc site\n        fccc = np.zeros((x_max*y_max*4,3))\n        for x in range(0,x_max):\n            for y in range(0,y_max):\n                \n                fccc[4*(x+y*(x_max)),0] = 0.5 + 2*x\n                fccc[4*(x+y*(x_max)),1] = np.sqrt(3)/6+2*np.sqrt(3)/2*y\n                fccc[4*(x+y*(x_max))+1,0] = 1.5 + 2*x\n                fccc[4*(x+y*(x_max))+1,1] = np.sqrt(3)/6+2*np.sqrt(3)/2*y\n                fccc[4*(x+y*(x_max))+2,0] = 2*x\n                fccc[4*(x+y*(x_max))+2,1] = np.sqrt(3)/2 + np.sqrt(3)/6+2*np.sqrt(3)/2*y\n                fccc[4*(x+y*(x_max))+3,0] = 1 + 2*x\n                fccc[4*(x+y*(x_max))+3,1] = np.sqrt(3)/2 + np.sqrt(3)/6+2*np.sqrt(3)/2*y\n                \n                \n        hcpc = np.zeros((x_max*y_max*4,3))\n        for x in range(0,x_max):\n            for y in range(0,y_max):\n                \n                hcpc[4*(x+y*(x_max)),0] = 2*x\n                hcpc[4*(x+y*(x_max)),1] = np.sqrt(3)/6*2+2*np.sqrt(3)/2*y\n                hcpc[4*(x+y*(x_max))+1,0] = 1 + 2*x\n                hcpc[4*(x+y*(x_max))+1,1] = np.sqrt(3)/6*2+2*np.sqrt(3)/2*y\n                hcpc[4*(x+y*(x_max))+2,0] = 0.5 + 2*x\n                hcpc[4*(x+y*(x_max))+2,1] = np.sqrt(3)/2 + np.sqrt(3)/6*2+2*np.sqrt(3)/2*y\n                hcpc[4*(x+y*(x_max))+3,0] = 1.5 + 2*x\n                hcpc[4*(x+y*(x_max))+3,1] = np.sqrt(3)/2 + np.sqrt(3)/6*2+2*np.sqrt(3)/2*y\n\n        # Construct Sites list\n        SiteNames = ['Atop','Bridge','Hollow']\n        DistanceMultiplier = [1,2.5, 2.5]\n        Sites = list()\n        ## Atop Site\n        for i in range(0,ac.shape[0]):\n            Sites.append(Site(0,ac[i]))\n        ## Bridge Site\n        for i in range(0,bc.shape[0]):\n            Sites.append(Site(1,bc[i]))\n        ## Hollow Site\n        for i in range(0,fccc.shape[0]):\n            Sites.append(Site(2,fccc[i]))\n        ## Hollow Site\n        for i in range(0,hcpc.shape[0]):\n            Sites.append(Site(3,hcpc[i]))\n        # Append Neighbors\n        # set up periodic condition\n        if PBC:\n            pcs = np.array([[0,0,0],[1,0,0],[1,1,0],[0,1,0],[-1,1,0],[-1,0,0],[-1,-1,0],[0,-1,0],[1,-1,0]])\n        else:\n            pcs = np.array([[0,0,0]])\n        # actually calculate how much translation is requred\n        pcts = list()\n        for pc in pcs:\n            pcts.append([2*x_max*pc[0],2*np.sqrt(3)/2*y_max*pc[1],0])\n        pcts = np.array(pcts)    \n        \n        # periodic coordinate\n        for pc in pcts:\n            try: \n                apc = np.concatenate((apc,np.add(ac,pc)))\n                bpc = np.concatenate((bpc,np.add(bc,pc)))\n                fccpc = np.concatenate((fccpc,np.add(fccc,pc)))\n                hcppc = np.concatenate((hcppc,np.add(hcpc,pc)))\n            except NameError:\n                apc = np.add(ac,pc)\n                bpc = np.add(bc,pc)\n                fccpc = np.add(fccc,pc)\n                hcppc = np.add(hcpc,pc)\n                \n                \n        ## atop site\n        for i in range(0,ac.shape[0]):\n            Sites[i].AppendRepresentedAtoms('self')\n            # to other atop sites\n            match = FindNeighbor(ac[i],apc,rd,1.0)\n            match = np.remainder(match,ac.shape[0])\n            Sites[i].AppendAtomNeighbors(match)\n            # to other bridge sites\n            match = FindNeighbor(ac[i],bpc,rd,0.5)\n            match = np.remainder(match,bc.shape[0])\n            Sites[i].AppendSiteNeighbors(match+ac.shape[0])\n            # to other fcc sites\n            match = FindNeighbor(ac[i],fccpc,rd,np.sqrt(3)/6*2)\n            match = np.remainder(match,fccc.shape[0])\n            Sites[i].AppendSiteNeighbors(match+ac.shape[0]+bc.shape[0])\n            # to other hcp sites\n            match = FindNeighbor(ac[i],hcppc,rd,np.sqrt(3)/6*2)\n            match = np.remainder(match,hcpc.shape[0])\n            Sites[i].AppendSiteNeighbors(match+ac.shape[0]+bc.shape[0]+fccc.shape[0])\n        ## bridge site\n        for i in range(0,bc.shape[0]):\n            # to other atop sites\n            match = FindNeighbor(bc[i],apc,rd,0.5)\n            match = np.remainder(match,ac.shape[0])\n            Sites[i+ac.shape[0]].AppendSiteNeighbors(match)\n            Sites[i+ac.shape[0]].AppendRepresentedAtoms(match)\n            # to other bridge sites\n#            match = FindNeighbor(bc[i],bpc,rd,0.5)\n#            match = np.remainder(match,bc.shape[0])\n#            Sites[i+ac.shape[0]].AppendSiteNeighbors(match+ac.shape[0])\n            # to other hollow sites\n            match = FindNeighbor(bc[i],fccpc,rd,np.sqrt(3)/6)\n            match = np.remainder(match,fccc.shape[0])\n            Sites[i+ac.shape[0]].AppendSiteNeighbors(match+ac.shape[0]+bc.shape[0])\n            # hollow\n            match = FindNeighbor(bc[i],hcppc,rd,np.sqrt(3)/6)\n            match = np.remainder(match,hcpc.shape[0])\n            Sites[i+ac.shape[0]].AppendSiteNeighbors(match+ac.shape[0]+bc.shape[0]+fccc.shape[0])\n        ## fcc site\n        for i in range(0,fccc.shape[0]):\n            # to other atop sites\n            match = FindNeighbor(fccc[i],apc,rd,np.sqrt(3)/6*2)\n            match = np.remainder(match,ac.shape[0])\n            Sites[i+ac.shape[0]+bc.shape[0]].AppendSiteNeighbors(match)\n            Sites[i+ac.shape[0]+bc.shape[0]].AppendRepresentedAtoms(match)\n            # to other bridge sites\n            match = FindNeighbor(fccc[i],bpc,rd,np.sqrt(3)/6)\n            match = np.remainder(match,bc.shape[0])\n            Sites[i+ac.shape[0]+bc.shape[0]].AppendSiteNeighbors(match+ac.shape[0])\n            # to other hcp sites\n#            match = FindNeighbor(fccc[i],hcppc,rd,np.sqrt(3)/3)\n#            match = np.remainder(match,hcpc.shape[0])\n#            Sites[i+ac.shape[0]+bc.shape[0]].AppendSiteNeighbors(match+ac.shape[0]+bc.shape[0]+fccc.shape[0])\n        ## hcp site\n        for i in range(0,hcpc.shape[0]):\n            # to other atop sites\n            match = FindNeighbor(hcpc[i],apc,rd,np.sqrt(3)/6*2)\n            match = np.remainder(match,ac.shape[0])\n            Sites[i+ac.shape[0]+bc.shape[0]+fccc.shape[0]].AppendSiteNeighbors(match)\n            Sites[i+ac.shape[0]+bc.shape[0]+fccc.shape[0]].AppendRepresentedAtoms(match)\n            # to other bridge sites\n            match = FindNeighbor(hcpc[i],bpc,rd,np.sqrt(3)/6)\n            match = np.remainder(match,bc.shape[0])\n            Sites[i+ac.shape[0]+bc.shape[0]+fccc.shape[0]].AppendSiteNeighbors(match+ac.shape[0])\n            # to other hcp sites\n#            match = FindNeighbor(hcpc[i],fccpc,rd,np.sqrt(3)/3)\n#            match = np.remainder(match,fccc.shape[0])\n#            Sites[i+ac.shape[0]+bc.shape[0]+fccc.shape[0]].AppendSiteNeighbors(match+ac.shape[0]+bc.shape[0])\n        # change basis from absolute to fractional\n        # Basis1' * coordinate1' = Basis2' * coordinate2'\n        B_inv = np.linalg.inv(Cell.transpose())\n        for site in Sites:\n            site._Coordinate = np.dot(B_inv,site._Coordinate).transpose()            \n        # periodic boundary condition\n        if PBC:\n            PBC = (True,True,False)\n        else:\n            PBC = (False,False,False)\n        # Return\n        return cls(Sites=Sites,SiteNames=SiteNames,DistanceMultiplier=DistanceMultiplier,Cell=Cell,PBC=PBC)\n\n\n\nclass Site(object):\n    \"\"\"\n    Object for a site\n    Attributes:\n    SiteType    - site type in integer\n    Coordinate  - 2D coordinates of the site location\n    Neighbors   - id connected neighbor\n    DuplicateNeighborError - if True, the code spits error if there is a \n        intersection between the site neighbor list and the one being appended\n    \"\"\"\n    def __init__(self, SiteType, Coordinate, DuplicateNeighborError=False):\n        # Error check\n        assert isinstance(SiteType, int), 'SiteType is not an integer.'\n        assert isinstance(Coordinate, list) or isinstance(Coordinate, np.ndarray), 'Coordinate is not a list.'\n        assert len(Coordinate) == 3,'Coordinate is not 3 dimensional.'\n        assert (isinstance(Coordinate[0], float) or isinstance(Coordinate[0], int))\\\n            and (isinstance(Coordinate[1], float) or isinstance(Coordinate[1], int))\\\n            and (isinstance(Coordinate[2], float) or isinstance(Coordinate[2], int)), 'Coordinate element is not a float or int.'\n        # Construct a site\n        self._SiteType = SiteType # e.g. atop bridge hollow sites\n        self._Coordinate = np.array(Coordinate, float)\n        self._DuplicateNeighborError = DuplicateNeighborError\n        self._SiteNeighbors = set()\n        self._AtomNeighbors = set()\n        self._RepresentedAtoms = set() # list of actual Pt atoms\n        \n    def __str__(self):\n        return '<Site(Type:%i,xyz:[%.2f,%.2f,%.2f],Number of Neighbors: %i>' \\\n            %(self._SiteType,self._Coordinate[0],self._Coordinate[1],\\\n            self._Coordinate[2],len(self._SiteNeighbors))\n    def __repr__(self):\n        s = 'Site(Type:%i, xyz:[%.2f,%.2f,%.2f], Neighbors:' \\\n            %(self._SiteType,self._Coordinate[0],self._Coordinate[1],\\\n            self._Coordinate[2])\n        for Neighbor in self._SiteNeighbors:\n            s += str(Neighbor) + ','\n        s += ', Associated_Pt_Atoms: '\n        for Pt_atoms in self._RepresentedAtoms:\n            s += str(Pt_atoms) + ','\n        s += ')'\n        return s\n        \n    def AppendSiteNeighbors(self, Neighbors):\n        # Error check\n        try:\n            if not isinstance(Neighbors,(int,np.int64)):\n                A = iter(Neighbors)\n                for a in A:\n                    if not isinstance(a,(int,np.int64)):\n                        raise Exception\n        except Exception:\n            raise Exception(\"Neighbors is not iterable object with integer or an integer.\")\n        # append neighbor\n        if isinstance(Neighbors,(int,np.int64)):\n            if self._DuplicateNeighborError:\n                if Neighbors in self._SiteNeighbors:\n                    raise Exception(\"Neighbor \" + str(Neighbors) + \" is already in the neighbor list\")\n            self._SiteNeighbors.add(Neighbors)\n        else:\n            for Neighbor in Neighbors:\n                if self._DuplicateNeighborError:\n                    if Neighbor in self._SiteNeighbors:\n                        raise Exception(\"Neighbor \" + Neighbor +\" is already in the neighbor list\")\n                self._SiteNeighbors.add(Neighbor)\n                \n    def AppendAtomNeighbors(self, Neighbors):\n        # Error check\n        try:\n            if not isinstance(Neighbors, (int,np.int64)):\n                A = iter(Neighbors)\n                for a in A:\n                    if not isinstance(a,(int,np.int64)):\n                        raise Exception\n        except Exception:\n            raise Exception(\"Neighbors is not iterable object with integer or an integer.\")\n        # append neighbor\n        if isinstance(Neighbors, (int,np.int64)):\n            if self._DuplicateNeighborError:\n                if Neighbors in self._AtomNeighbors:\n                    raise Exception(\"Neighbor \" + str(Neighbors) + \" is already in the neighbor list\")\n            self._AtomNeighbors.add(Neighbors)\n        else:\n            for Neighbor in Neighbors:\n                if self._DuplicateNeighborError:\n                    if Neighbor in self._AtomNeighbors:\n                        raise Exception(\"Neighbor \" + Neighbor +\" is already in the neighbor list\")\n                self._AtomNeighbors.add(Neighbor)\n    \n    def AppendRepresentedAtoms(self, Pt_indexes):\n        # this is for actual Pt atoms associated with sites\n        # Error check\n        try:\n            if isinstance(Pt_indexes, str) and Pt_indexes == 'self':\n                pass\n            elif not isinstance(Pt_indexes, (int,np.int64)):\n                A = iter(Pt_indexes)\n                for a in A:\n                    if not isinstance(a,(int,np.int64)):\n                        raise Exception\n        except Exception:\n            raise Exception(\"Neighbors is not iterable object with integer or an integer.\")\n        # append neighbor\n        if isinstance(Pt_indexes, str) and Pt_indexes == 'self':\n            self._RepresentedAtoms.add('self')\n        elif isinstance(Pt_indexes, (int,np.int64)):\n            if self._DuplicateNeighborError:\n                if Pt_indexes in self._RepresentedAtoms:\n                    raise Exception(str(Pt_indexes) + \" is already in the associated Pt site list\")\n            self._RepresentedAtoms.add(Pt_indexes)\n        else:\n            for index in Pt_indexes:\n                if self._DuplicateNeighborError:\n                    if index in self._RepresentedAtoms:\n                        raise Exception(str(index) + \" is already in the associated Pt site list\")\n                self._RepresentedAtoms.add(index)\n    \n    def GetCoordinate(self):\n        return self._Coordinate.copy()\n        \n    def GetSiteType(self):\n        return self._SiteType.copy()\n\n\ndef FindNeighbor(xyz,mat,round_decimal,desired_distance):\n    mat = np.subtract(mat,xyz)\n    ds = np.linalg.norm(mat,axis=1)\n    ds = np.around(ds,decimals=round_decimal)\n    desired_distance = np.around(desired_distance,decimals=round_decimal)\n    return np.where(np.equal(ds,desired_distance))[0] # because it gives tuple of tuple\n                \ndef GetSubMolFromIdx(Idxs,Mol):\n    Mapping = dict() # Original Mol Idx -> New Mol Idx\n    if len(Idxs) != 1:\n        BondList = GetBondListFromAtomList(Mol,Idxs)\n        NewMol = Chem.RWMol(Chem.PathToSubmol(Mol,BondList,atomMap = Mapping))\n    else:\n        NewMol = Chem.RWMol(Mol)\n        # Remove Non surface Atom\n        for idx in reversed(range(0,NewMol.GetNumAtoms())):\n            if idx not in Idxs:\n                NewMol.RemoveAtom(idx)\n        Mapping[Idxs[0]] = 0\n    \n    ReverseMapping = dict()\n    for Idx in Mapping:\n        ReverseMapping[Mapping[Idx]] = Idx\n    \n    return NewMol, Mapping, ReverseMapping\n\ndef RemoveHe(smiles):\n    mol = Chem.MolFromSmiles(smiles,sanitize=False)\n    mol = Chem.RWMol(mol)\n    for i in reversed(range(mol.GetNumAtoms())):\n        atom = mol.GetAtomWithIdx(i)\n        if atom.GetAtomicNum() in [1,6,8]:\n            atom.SetNoImplicit(True)\n            atom.SetNumRadicalElectrons(1)\n        elif atom.GetAtomicNum() ==2 :\n            mol.RemoveAtom(i)\n    return Chem.MolToSmiles(mol)\n\ndef BFSShortestPath(mol,idxs):\n    # Step1: Initialize\n    predecessors = []\n    for _ in idxs:\n        predecessors.append([[] for _ in range(mol.GetNumAtoms())])\n    for i,j in enumerate(idxs):\n        predecessors[i][j] = True\n    queues = [[mol.GetAtomWithIdx(i)] for i in idxs]\n    Checked = [set() for i in idxs]\n    MeetingPoints = [[[] for _ in idxs] for _ in idxs]\n    HaveWeMet = [[False for _ in idxs] for _ in idxs]\n    for i in range(len(idxs)):\n        HaveWeMet[i][i] = True\n    \n    # Search\n    for _ in range(mol.GetNumAtoms()): # maximum possible depth.\n        for i,queue in enumerate(queues): # Starting node i\n            \n            Checked[i] |= set([q.GetIdx() for q in queue])\n            newqueue = []\n            newqueueidx = []\n            for q in queue:\n                for na in q.GetNeighbors(): # Breath first search\n                    naidx = na.GetIdx()\n                    if naidx not in Checked[i]:\n                        # append predecessor \n                        predecessors[i][naidx].append(q.GetIdx()) \n                        # make new queues\n                        if naidx not in newqueueidx: \n                            newqueue.append(na)\n                            newqueueidx.append(naidx)\n            \n            # Check if it has met the searched nodes started from other nodes\n            for naidx in newqueueidx:\n                for j,pred in enumerate(predecessors):\n                    if not HaveWeMet[i][j] and pred[naidx]:\n                        MeetingPoints[i][j].append(naidx)\n                        MeetingPoints[j][i].append(naidx)\n            \n            # Check if meeting points has been set\n            for j in range(len(idxs)):\n                if not HaveWeMet[i][j] and MeetingPoints[i][j]:\n                    HaveWeMet[i][j] = True\n                    HaveWeMet[j][i] = True\n\n            if all(HaveWeMet[i]): # This has met all other nodes, so no need for further search\n                queues[i] = []\n            else: # It has not met all nodes. continue search\n                queues[i] = newqueue\n            \n        # Check if every nodes have met each other\n        if not any(queues):\n            break\n    \n    shortestpath = set()\n    for i in range(len(idxs)):\n        for j in range(len(idxs)):\n            pairshortestpath = set()\n            AtomIdx2Check = MeetingPoints[i][j].copy()\n            while AtomIdx2Check:\n                idx = AtomIdx2Check.pop()\n                if idx not in pairshortestpath:\n                    pairshortestpath.add(idx)\n                    if predecessors[i][idx] != True:\n                        AtomIdx2Check += predecessors[i][idx]\n            shortestpath |=pairshortestpath\n    \n    return(shortestpath)", "meta": {"hexsha": "864e27fb609a23eeec2662133858e535c8c887b7", "size": 40829, "ext": "py", "lang": "Python", "max_stars_repo_path": "FLDLR/util.py", "max_stars_repo_name": "VlachosGroup/AdsorptionConfiguration_MS2021", "max_stars_repo_head_hexsha": "7ff88e9f21358e4c98135c858d840f36bc6a3116", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FLDLR/util.py", "max_issues_repo_name": "VlachosGroup/AdsorptionConfiguration_MS2021", "max_issues_repo_head_hexsha": "7ff88e9f21358e4c98135c858d840f36bc6a3116", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FLDLR/util.py", "max_forks_repo_name": "VlachosGroup/AdsorptionConfiguration_MS2021", "max_forks_repo_head_hexsha": "7ff88e9f21358e4c98135c858d840f36bc6a3116", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.57455683, "max_line_length": 129, "alphanum_fraction": 0.5615616351, "include": true, "reason": "import numpy", "num_tokens": 10632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.15510202414915247}}
{"text": "#   Copyright 2016, 2017 California Institute of Technology\n#   Users must agree to abide by the restrictions listed in the\n#   file \"LegalStuff.txt\" in the PROPER library directory.\n#\n#   PROPER developed at Jet Propulsion Laboratory/California Inst. Technology\n#   Original IDL version by John Krist\n#   Python translation by Navtej Saini, with Luis Marchen and Nikta Amiri\n#\n#   Revised 5 March 2018 - John Krist - Fixed call to prop_cubic_conv by\n#   getting rid of the flattening of the coordinate arrays.\n\n\n\nimport os\nimport proper\nimport numpy as np\nfrom math import sin, cos\n# from . import lib_dir\nlib_dir = os.path.dirname(proper.__file__)\nimport scipy.signal as ss\n\nif not proper.use_cubic_conv:\n    from scipy.ndimage.interpolation import map_coordinates\n\n\ndef prop_dm(wf, dm_z0, dm_xc, dm_yc, spacing = 0., **kwargs):\n    \"\"\"Simulate a deformable mirror of specified actuator spacing, including the\n    effects of the DM influence function.\n\n    Parameters\n    ----------\n    wf : obj\n        WaveFront class object\n\n    dm_z0 : str or numpy ndarray\n        Either a 2D numpy array containing the surface piston of each DM\n        actuator in meters or the name of a 2D FITS image file containing the\n        above\n\n    dm_xc, dm_yc : list or numpy ndarray\n        The location of the optical axis (center of the wavefront) on the DM in\n        actuator units (0 ro num_actuator-1). The center of the first actuator\n        is (0.0, 0.0)\n\n    spacing : float\n        Defines the spacing in meters between actuators; must not be used when\n        n_act_across_pupil is specified.\n\n\n    Returns\n    -------\n    dmap : numpy ndarray\n        Returns DM surface (not wavefront) map in meters\n\n\n    Other Parameters\n    ----------------\n    FIT : bool\n       Switch that tells routine that the values in \"dm_z\" are the desired\n       surface heights rather than commanded actuator heights, and so the\n       routine should fit this map, accounting for actuator influence functions,\n       to determine the necessary actuator heights. An iterative error-minimizing\n       loop is used for the fit.\n\n    NO_APPLY : bool\n        If set, the DM pattern is not added to the wavefront. Useful if the DM\n        surface map is needed but should not be applied to the wavefront\n\n    N_ACT_ACROSS_PUPIL : int\n        Specifies the number of actuators that span the X-axis beam diameter. If\n        it is a whole number, the left edge of the left pixel is aligned with\n        the left edge of the beam, and the right edge of the right pixel with\n        the right edge of the beam. This determines the spacing and size of the\n        actuators. Should not be used when \"spacing\" value is specified.\n\n    XTILT, YTILT, ZTILT : float\n        Specify the rotation of the DM surface with respect to the wavefront plane\n        in degrees about the X, Y, Z axes, respectively, with the origin at the\n        center of the wavefront. The DM surface is interpolated and orthographically\n        projected onto the wavefront grid. The coordinate system assumes that\n        the wavefront and initial DM surface are in the X,Y plane with a lower\n        left origin with Z towards the observer. The rotations are left handed.\n        The default rotation order is X, Y, then Z unless the /ZYX switch is set.\n\n    XYZ or ZYX : bool\n        Specifies the rotation order if two or more of XTILT, YTILT, or ZTILT\n        are specified. The default is /XYZ for X, Y, then Z rotations.\n\n\n    Raises\n    ------\n    ValueError:\n        User cannot specify both actuator spacing and N_ACT_ACROSS_PUPIL\n\n    ValueError:\n        User must specify either actuator spacing or N_ACT_ACROSS_PUPIL\n    \"\"\"\n    if \"ZYX\" in kwargs and \"XYZ\" in kwargs:\n        raise ValueError('PROP_DM: Error: Cannot specify both XYZ and ZYX rotation orders. Stopping')\n    elif not \"ZYX\" in kwargs and not 'XYZ' in kwargs:\n        XYZ = 1    # default is rotation around X, then Y, then Z\n        ZYX = 0\n    elif \"ZYX\" in kwargs:\n        ZYX = 1\n        XYZ = 0\n    elif \"XYZ\" in kwargs:\n        XYZ = 1\n        ZYX = 0\n\n    if \"XTILT\" in kwargs:\n        xtilt = kwargs[\"XTILT\"]\n    else:\n        xtilt = 0.\n\n    if \"YTILT\" in kwargs:\n        ytilt = kwargs[\"YTILT\"]\n    else:\n        ytilt = 0.\n\n    if \"ZTILT\" in kwargs:\n        ztilt = kwargs[\"ZTILT\"]\n    else:\n        ztilt = 0.\n\n    if type(dm_z0) == str:\n        dm_z = proper.prop_fits_read(dm_z0) # Read DM setting from FITS file\n    else:\n        dm_z = dm_z0\n\n    n = proper.prop_get_gridsize(wf)\n    dx_surf = proper.prop_get_sampling(wf)  # sampling of current surface in meters\n    beamradius = proper.prop_get_beamradius(wf)\n\n    # influence function sampling is 0.1 mm, peak at (x,y)=(45,45)\n    # Influence function has shape = 1x91x91. Saving it as a 2D array\n    # before continuing with processing\n    inf = proper.prop_fits_read(os.path.join(lib_dir, \"influence_dm5v2.fits\"))\n    inf = inf[0,:,:]\n\n    s = inf.shape\n    nx_inf = s[1]\n    ny_inf = s[0]\n    xc_inf = int(nx_inf/2)\n    yc_inf = int(ny_inf/2)\n    dx_inf = 0.1e-3            # influence function spacing in meters\n    dx_dm_inf = 1.e-3          # spacing between DM actuators in meters assumed by influence function\n    inf_mag = 10\n\n    if spacing != 0 and \"N_ACT_ACROSS_PUPIL\" in kwargs:\n        raise ValueError(\"PROP_DM: User cannot specify both actuator spacing and N_ACT_ACROSS_PUPIL. Stopping.\")\n\n\n    if spacing == 0 and not \"N_ACT_ACROSS_PUPIL\" in kwargs:\n        raise ValueError(\"PROP_DM: User must specify either actuator spacing or N_ACT_ACROSS_PUPIL. Stopping.\")\n\n\n    if \"N_ACT_ACROSS_PUPIL\" in kwargs:\n        dx_dm = 2. * beamradius / int(kwargs[\"N_ACT_ACROSS_PUPIL\"])\n    else:\n        dx_dm = spacing\n\n    dx_inf = dx_inf * dx_dm / dx_dm_inf   # Influence function sampling scaled\n                                          # to specified DM actuator spacing\n\n    if \"FIT\" in kwargs:\n        x = (np.arange(5, dtype = np.float64) - 2) * dx_dm\n\n        if proper.use_cubic_conv:\n            inf_kernel = proper.prop_cubic_conv(inf.T, x/dx_inf+xc_inf, x/dx_inf+yc_inf, GRID=True)\n        else:\n            xygrid = np.meshgrid(x/dx_inf+xc_inf, x/dx_inf+yc_inf)\n            inf_kernel = map_coordinates(inf.T, xygrid, order = 3, mode = \"nearest\")\n\n        (dm_z_commanded, dms) = proper.prop_fit_dm(dm_z, inf_kernel)\n    else:\n        dm_z_commanded = dm_z\n\n    s = dm_z.shape\n    nx_dm = s[1]\n    ny_dm = s[0]\n\n    # Create subsampled DM grid\n    margin = 9 * inf_mag\n    nx_grid = nx_dm * inf_mag + 2 * margin\n    ny_grid = ny_dm * inf_mag + 2 * margin\n    xoff_grid = margin + inf_mag/2           # pixel location of 1st actuator center in subsampled grid\n    yoff_grid = xoff_grid\n    dm_grid = np.zeros([ny_grid, nx_grid], dtype = np.float64)\n\n    x = np.arange(nx_dm, dtype = np.int16) * int(inf_mag) + int(xoff_grid)\n    y = np.arange(ny_dm, dtype = np.int16) * int(inf_mag) + int(yoff_grid)\n    dm_grid[np.tile(np.vstack(y), (nx_dm,)), np.tile(x, (ny_dm,1))] = dm_z_commanded\n    dm_grid = ss.fftconvolve(dm_grid, inf, mode = 'same')\n\n    # 3D rotate DM grid and project orthogonally onto wavefront\n    xdim = int(np.round(np.sqrt(2) * nx_grid * dx_inf / dx_surf)) # grid dimensions (pix) projected onto wavefront\n    ydim = int(np.round(np.sqrt(2) * ny_grid * dx_inf / dx_surf))\n\n    if xdim > n: xdim = n\n\n    if ydim > n: ydim = n\n\n    x = np.ones((ydim,1), dtype = np.int) * ((np.arange(xdim) - int(xdim/2)) * dx_surf)\n    y = (np.ones((xdim,1), dtype = np.int) * ((np.arange(ydim) - int(ydim/2)) * dx_surf)).T\n\n    a = xtilt * np.pi / 180\n    b = ytilt * np.pi / 180\n    g = ztilt * np.pi /180\n\n    if XYZ:\n        m = np.array([ \t[cos(b)*cos(g), -cos(b)*sin(g), sin(b), 0],\n      \t \t[cos(a)*sin(g) + sin(a)*sin(b)*cos(g), cos(a)*cos(g)-sin(a)*sin(b)*sin(g), -sin(a)*cos(b), 0],\n      \t\t[sin(a)*sin(g)-cos(a)*sin(b)*cos(g), sin(a)*cos(g)+cos(a)*sin(b)*sin(g), cos(a)*cos(b), 0],\n      \t\t[0, 0, 0, 1] ])\n    else:\n        m = np.array([\t[cos(b)*cos(g), cos(g)*sin(a)*sin(b)-cos(a)*sin(g), cos(a)*cos(g)*sin(b)+sin(a)*sin(g), 0],\n\t\t[cos(b)*sin(g), cos(a)*cos(g)+sin(a)*sin(b)*sin(g), -cos(g)*sin(a)+cos(a)*sin(b)*sin(g), 0],\n\t\t[-sin(b), cos(b)*sin(a), cos(a)*cos(b), 0],\n\t\t[0, 0, 0, 1] ])\n\n    # Forward project a square\n    edge = np.array([[-1.0,-1.0,0.0,0.0], [1.0,-1.0,0.0,0.0], [1.0,1.0,0.0,0.0], [-1.0,1.0,0.0,0.0]])\n    new_xyz = np.dot(edge, m)\n\n    # determine backward projection for screen-raster-to-DM-surce computation\n    dx_dxs = (new_xyz[0,0] - new_xyz[1,0]) / (edge[0,0] - edge[1,0])\n    dx_dys = (new_xyz[1,0] - new_xyz[2,0]) / (edge[1,1] - edge[2,1])\n    dy_dxs = (new_xyz[0,1] - new_xyz[1,1]) / (edge[0,0] - edge[1,0])\n    dy_dys = (new_xyz[1,1] - new_xyz[2,1]) / (edge[1,1] - edge[2,1])\n\n    xs = ( x/dx_dxs - y*dx_dys/(dx_dxs*dy_dys) ) / ( 1 - dy_dxs*dx_dys/(dx_dxs*dy_dys) )\n    ys = ( y/dy_dys - x*dy_dxs/(dx_dxs*dy_dys) ) / ( 1 - dx_dys*dy_dxs/(dx_dxs*dy_dys) )\n\n    xdm = (xs + dm_xc * dx_dm) / dx_inf + xoff_grid\n    ydm = (ys + dm_yc * dx_dm) / dx_inf + yoff_grid\n\n    if proper.use_cubic_conv:\n        grid = proper.prop_cubic_conv(dm_grid.T, xdm, ydm, GRID = False)\n        grid = grid.reshape([xdm.shape[1], xdm.shape[0]])\n    else:\n        grid = map_coordinates(dm_grid.T, [xdm, ydm], order = 3, mode = \"nearest\", prefilter = True)\n\n    dmap = np.zeros([n,n], dtype = np.float64)\n    nx_grid, ny_grid = grid.shape\n    xmin, xmax = int(n/2 - xdim/2), int(n/2 - xdim/2 + nx_grid)\n    ymin, ymax =  int(n/2 - ydim/2), int(n/2 - ydim/2 + ny_grid)\n    dmap[ymin:ymax, xmin:xmax] = grid\n\n    # Random dots sometimes appear in the phase map. This is a little temporary hack to deal with that bug!\n    import scipy.ndimage\n    sigma = [1, 1]\n    dmap = scipy.ndimage.filters.gaussian_filter(dmap, sigma, mode='constant')\n\n    if not \"NO_APPLY\" in kwargs:\n        proper.prop_add_phase(wf, 2 * dmap)            # x2 to convert surface to wavefront error\n\n    return dmap\n", "meta": {"hexsha": "2dfc27f1da91e13bb0050491db5539cdfb26d239", "size": 9911, "ext": "py", "lang": "Python", "max_stars_repo_path": "proper_mod/prop_dm.py", "max_stars_repo_name": "RupertDodkins/medis", "max_stars_repo_head_hexsha": "bdb1f00fb93506da2a1f251bc6780e70e97a16c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-25T17:35:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T17:35:56.000Z", "max_issues_repo_path": "proper_mod/prop_dm.py", "max_issues_repo_name": "RupertDodkins/medis", "max_issues_repo_head_hexsha": "bdb1f00fb93506da2a1f251bc6780e70e97a16c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "proper_mod/prop_dm.py", "max_forks_repo_name": "RupertDodkins/medis", "max_forks_repo_head_hexsha": "bdb1f00fb93506da2a1f251bc6780e70e97a16c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-12-08T15:05:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-08T17:28:24.000Z", "avg_line_length": 38.4147286822, "max_line_length": 114, "alphanum_fraction": 0.6346483705, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 3040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3007455914759599, "lm_q1q2_score": 0.15507041653090295}}
{"text": "import numpy as np\nfrom astropy.time import Time, TimeDelta\nimport random\nimport warnings\n\n\n__all__ = ['UnscheduledDowntimeData']\n\n\nclass UnscheduledDowntimeData(object):\n    \"\"\"Handle (and create) the unscheduled downtime information.\n\n    Parameters\n    ----------\n    start_time : astropy.time.Time\n        The time of the start of the simulation.\n        The cloud database will be assumed to start on Jan 01 of the same year.\n    seed : int, optional\n        The random seed for creating the random nights of unscheduled downtime. Default 1516231120.\n    start_of_night_offset : float, optional\n        The fraction of a day to offset from MJD.0 to reach the defined start of a night ('noon' works).\n        Default 0.16 (UTC midnight in Chile) - 0.5 (minus half a day) = -0.34\n    survey_length : int, optional\n        The number of nights in the total survey. Default 3650*2.\n    \"\"\"\n\n    MINOR_EVENT = {'P': 0.0137, 'length': 1, 'level': \"minor event\"}\n    INTERMEDIATE_EVENT = {'P': 0.00548, 'length': 3, 'level': \"intermediate event\"}\n    MAJOR_EVENT = {'P': 0.00137, 'length': 7, 'level': \"major event\"}\n    CATASTROPHIC_EVENT = {'P': 0.000274, 'length': 14, 'level': \"catastrophic event\"}\n\n    def __init__(self, start_time, seed=1516231120, start_of_night_offset=-0.34, survey_length=3650*2):\n        self.seed = seed\n        self.survey_length = survey_length\n        year_start = start_time.datetime.year\n        self.night0 = Time('%d-01-01' % year_start, format='isot', scale='tai') + start_of_night_offset\n\n        # Scheduled downtime data is a np.ndarray of start / end / activity for each scheduled downtime.\n        self.downtime = None\n        self.make_data()\n\n    def __call__(self):\n        \"\"\"Return the array of unscheduled downtimes.\n\n        Parameters\n        ----------\n        time : astropy.time.Time\n            Time in the simulation for which to find the current downtime.\n\n        Returns\n        -------\n        np.ndarray\n            The array of all unscheduled downtimes, with keys for 'start', 'end', 'activity',\n            corresponding to astropy.time.Time, astropy.time.Time, and str.\n        \"\"\"\n        return self.downtime\n\n    def _downtimeStatus(self, time):\n        \"\"\"Look behind the scenes at the downtime status/next values\n        \"\"\"\n        next_start = self.downtime['start'].searchsorted(time, side='right')\n        next_end = self.downtime['end'].searchsorted(time, side='right')\n        if next_start > next_end:\n            current = self.downtime[next_end]\n        else:\n            current = None\n        future = self.downtime[next_start:]\n        return current, future\n\n    def make_data(self):\n        \"\"\"Configure the set of unscheduled downtimes.\n\n        This function creates the unscheduled downtimes based on a set of probabilities\n        of the downtime type occurance.\n\n        The random downtime is calculated using the following probabilities:\n\n        minor event\n            remainder of night and next day = 5/365 days e.g. power supply failure\n        intermediate\n            3 nights = 2/365 days e.g. repair filter mechanism, rotator, hexapod, or shutter\n        major event\n            7 nights = 1/2*365 days\n        catastrophic event\n            14 nights = 1/3650 days e.g. replace a raft\n        \"\"\"\n        random.seed(self.seed)\n\n        starts = []\n        ends = []\n        acts = []\n        night = 0\n        while night < self.survey_length:\n            prob = random.random()\n            if prob < self.CATASTROPHIC_EVENT['P']:\n                start_night = self.night0 + TimeDelta(night, format='jd')\n                starts.append(start_night)\n                end_night = start_night + TimeDelta(self.CATASTROPHIC_EVENT['length'], format='jd')\n                ends.append(end_night)\n                acts.append(self.CATASTROPHIC_EVENT['level'])\n                night += self.CATASTROPHIC_EVENT['length'] + 1\n                continue\n            else:\n                prob = random.random()\n                if prob < self.MAJOR_EVENT['P']:\n                    start_night = self.night0 + TimeDelta(night, format='jd')\n                    starts.append(start_night)\n                    end_night = start_night + TimeDelta(self.MAJOR_EVENT['length'], format='jd')\n                    ends.append(end_night)\n                    acts.append(self.MAJOR_EVENT['level'])\n                    night += self.MAJOR_EVENT['length'] + 1\n                    continue\n                else:\n                    prob = random.random()\n                    if prob < self.INTERMEDIATE_EVENT['P']:\n                        start_night = self.night0 + TimeDelta(night, format='jd')\n                        starts.append(start_night)\n                        end_night = start_night + TimeDelta(self.INTERMEDIATE_EVENT['length'], format='jd')\n                        ends.append(end_night)\n                        acts.append(self.INTERMEDIATE_EVENT['level'])\n                        night += self.INTERMEDIATE_EVENT['length'] + 1\n                        continue\n                    else:\n                        prob = random.random()\n                        if prob < self.MINOR_EVENT['P']:\n                            start_night = self.night0 + TimeDelta(night, format='jd')\n                            starts.append(start_night)\n                            end_night = start_night + TimeDelta(self.MINOR_EVENT['length'], format='jd')\n                            ends.append(end_night)\n                            acts.append(self.MINOR_EVENT['level'])\n                            night += self.MINOR_EVENT['length'] + 1\n            night += 1\n        self.downtime = np.array(list(zip(starts, ends, acts)),\n                                 dtype=[('start', 'O'), ('end', 'O'), ('activity', 'O')])\n\n    def config_info(self):\n        warnings.warn('The configure method is deprecated.')\n\n    def total_downtime(self):\n        \"\"\"Return total downtime (in days).\n\n        Returns\n        -------\n        int\n            Total number of downtime days.\n        \"\"\"\n        total = 0\n        for td in (self.downtime['end'] - self.downtime['start']):\n            total += td.jd\n        return total\n", "meta": {"hexsha": "06ac6cd8530bf0e1f6db305b1c4e7edec1dbae42", "size": 6178, "ext": "py", "lang": "Python", "max_stars_repo_path": "rubin_sim/site_models/unscheduledDowntimeData.py", "max_stars_repo_name": "RileyWClarke/flarubin", "max_stars_repo_head_hexsha": "eb7b1ee21c828523f8a5374fe4510fe6e5ec2a2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rubin_sim/site_models/unscheduledDowntimeData.py", "max_issues_repo_name": "RileyWClarke/flarubin", "max_issues_repo_head_hexsha": "eb7b1ee21c828523f8a5374fe4510fe6e5ec2a2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rubin_sim/site_models/unscheduledDowntimeData.py", "max_forks_repo_name": "RileyWClarke/flarubin", "max_forks_repo_head_hexsha": "eb7b1ee21c828523f8a5374fe4510fe6e5ec2a2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9139072848, "max_line_length": 107, "alphanum_fraction": 0.5665263839, "include": true, "reason": "import numpy,from astropy", "num_tokens": 1402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.1550704132993277}}
{"text": "\"\"\"Molecular database (MDB) class\n\n   * MdbExomol is the MDB for ExoMol\n   * MdbHit is the MDB for HITRAN or HITEMP  \n   \n\"\"\"\nimport numpy as np\nimport jax.numpy as jnp\nimport pathlib\nfrom exojax.spec import hapi, exomolapi, exomol, atomllapi, atomll, hitranapi\nfrom exojax.spec.hitran import gamma_natural as gn\nimport vaex\n\n__all__ = ['MdbExomol','MdbHit','AdbVald','AdbKurucz']\n\nclass MdbExomol(object):\n    \"\"\" molecular database of ExoMol\n\n    MdbExomol is a class for ExoMol.\n\n    Attributes:\n        nurange: nu range [min,max] (cm-1)\n        nu_lines (nd array): line center (cm-1)\n        Sij0 (nd array): line strength at T=Tref (cm)\n        dev_nu_lines (jnp array): line center in device (cm-1)\n        logsij0 (jnp array): log line strength at T=Tref\n        A (jnp array): Einstein A coeeficient\n        gamma_natural (jnp array): gamma factor of the natural broadening\n        elower (jnp array): the lower state energy (cm-1)\n        gpp (jnp array): statistical weight\n        jlower (jnp array): J_lower\n        jupper (jnp array): J_upper\n        n_Texp (jnp array): temperature exponent\n        alpha_ref (jnp array): alpha_ref (gamma0)\n        n_Texp_def: default temperature exponent in .def file, used for jlower not given in .broad\n        alpha_ref_def: default alpha_ref (gamma0) in .def file, used for jlower not given in .broad\n\n    \"\"\"\n    def __init__(self,path,nurange=[-np.inf,np.inf],margin=0.0,crit=-np.inf, bkgdatm=\"H2\", broadf=True):\n        \"\"\"Molecular database for Exomol form\n\n        Args: \n           path: path for Exomol data directory/tag. For instance, \"/home/CO/12C-16O/Li2015\"\n           nurange: wavenumber range list (cm-1) [min,max] or wavenumber grid \n           margin: margin for nurange (cm-1)\n           crit: line strength lower limit for extraction\n           bkgdatm: background atmosphere for broadening. e.g. H2, He, \n           broadf: if False, the default broadening parameters in .def file is used\n\n        Note:\n           The trans/states files can be very large. For the first time to read it, we convert it to HDF/vaex. After the second-time, we use the HDF5 format with vaex instead.\n\n        \"\"\"\n        explanation_states=\"Note: Couldn't find the hdf5 format. We convert data to the hdf5 format. After the second time, it will become much faster.\"\n        explanation_trans=\"Note: Couldn't find the hdf5 format. We convert data to the hdf5 format. After the second time, it will become much faster.\"\n        \n        self.path = pathlib.Path(path)\n        t0=self.path.parents[0].stem        \n        molec=t0+\"__\"+str(self.path.stem)\n        self.bkgdatm=bkgdatm\n        print(\"Background atmosphere: \",self.bkgdatm)\n        molecbroad=t0+\"__\"+self.bkgdatm\n\n        self.crit = crit\n        self.margin = margin\n        self.nurange=[np.min(nurange),np.max(nurange)]\n        self.broadf=broadf\n        self.states_file = self.path/pathlib.Path(molec+\".states.bz2\")\n        self.pf_file = self.path/pathlib.Path(molec+\".pf\")\n        self.def_file = self.path/pathlib.Path(molec+\".def\")\n        self.broad_file = self.path/pathlib.Path(molecbroad+\".broad\")\n\n        if not self.def_file.exists():\n                self.download(molec,extension=[\".def\"])\n        if not self.pf_file.exists():\n                self.download(molec,extension=[\".pf\"])\n        if not self.states_file.exists():\n                self.download(molec,extension=[\".states.bz2\"])\n        if not self.broad_file.exists():\n                self.download(molec,extension=[\".broad\"])\n        \n        #load def \n        self.n_Texp_def, self.alpha_ref_def, self.molmass, numinf, numtag=exomolapi.read_def(self.def_file)\n\n        #  default n_Texp value if not given\n        if self.n_Texp_def is None:\n            self.n_Texp_def=0.5\n        #  default alpha_ref value if not given\n        if self.alpha_ref_def is None:\n            self.alpha_ref_def=0.07\n\n        #load states\n        if self.states_file.with_suffix(\".bz2.hdf5\").exists():\n            states=vaex.open(self.states_file.with_suffix(\".bz2.hdf5\"))\n            ndstates=vaex.array_types.to_numpy(states)\n        else:\n            print(explanation_states)\n            states=exomolapi.read_states(self.states_file)\n            ndstates=vaex.array_types.to_numpy(states)\n\n        #load pf\n        pf=exomolapi.read_pf(self.pf_file)\n        self.gQT=jnp.array(pf[\"QT\"].to_numpy()) #grid QT\n        self.T_gQT=jnp.array(pf[\"T\"].to_numpy()) #T forgrid QT\n                \n        self.Tref=296.0\n        self.QTref=np.array(self.QT_interp(self.Tref))\n\n        #trans file(s)\n        print(\"Reading transition file\")\n        if numinf is None:\n            self.trans_file = self.path/pathlib.Path(molec+\".trans.bz2\")\n            if not self.trans_file.exists():\n                self.download(molec,[\".trans.bz2\"])\n\n            if self.trans_file.with_suffix(\".hdf5\").exists():\n                trans=vaex.open(self.trans_file.with_suffix(\".hdf5\"))\n                cdt=(trans.nu_lines>self.nurange[0]-self.margin) \\\n                    * (trans.nu_lines<self.nurange[1]+self.margin)\n                if not np.isneginf(self.crit):\n                    cdt=cdt * (trans.Sij0>self.crit)\n                trans=trans[cdt]\n                ndtrans=vaex.array_types.to_numpy(trans)\n\n                #mask has been alraedy applied\n                mask_needed=False\n            else:\n                print(explanation_trans)\n                trans=exomolapi.read_trans(self.trans_file)\n                ndtrans=vaex.array_types.to_numpy(trans)\n\n                #mask needs to be applied\n                mask_needed=True\n\n            #compute gup and elower\n            self._A, self.nu_lines, self._elower, self._gpp, self._jlower, self._jupper, mask_zeronu=exomolapi.pickup_gE(ndstates,ndtrans,self.trans_file)\n\n            if self.trans_file.with_suffix(\".hdf5\").exists():\n                self.Sij0=ndtrans[:,4]\n            else:\n                ##Line strength: input should be ndarray not jnp array\n                self.Sij0=exomol.Sij0(self._A,self._gpp,self.nu_lines,self._elower,self.QTref)\n\n                #exclude the lines whose nu_lines evaluated inside exomolapi.pickup_gE (thus sometimes different from the \"nu_lines\" column in trans) is not positive\n                trans[\"nu_positive\"]=mask_zeronu\n                trans=trans[trans.nu_positive].extract()\n                trans.drop('nu_positive',inplace=True)\n\n                trans[\"nu_lines\"]=self.nu_lines\n                trans[\"Sij0\"]=self.Sij0\n                trans.export(self.trans_file.with_suffix(\".hdf5\"))\n        else:\n            imin=np.searchsorted(numinf,self.nurange[0],side=\"right\")-1 #left side\n            imax=np.searchsorted(numinf,self.nurange[1],side=\"right\")-1 #left side\n            self.trans_file=[]\n            for k,i in enumerate(range(imin,imax+1)):\n                trans_file = self.path/pathlib.Path(molec+\"__\"+numtag[i]+\".trans.bz2\")\n                if not trans_file.exists():\n                    self.download(molec,extension=[\".trans.bz2\"],numtag=numtag[i])\n\n                if trans_file.with_suffix(\".hdf5\").exists():\n                    trans=vaex.open(trans_file.with_suffix(\".hdf5\"))\n                    cdt=(trans.nu_lines>self.nurange[0]-self.margin) \\\n                        * (trans.nu_lines<self.nurange[1]+self.margin)\n                    if not np.isneginf(self.crit):\n                        cdt=cdt * (trans.Sij0>self.crit)\n                    trans=trans[cdt]\n                    ndtrans=vaex.array_types.to_numpy(trans)\n                    self.trans_file.append(trans_file)\n\n                    #mask has been alraedy applied\n                    mask_needed=False\n                else:\n                    print(explanation_trans)\n                    trans=exomolapi.read_trans(trans_file)\n                    ndtrans=vaex.array_types.to_numpy(trans)\n                    self.trans_file.append(trans_file)\n                    \n                    #mask needs to be applied\n                    mask_needed=True\n\n                #compute gup and elower\n                if k==0:\n                    self._A, self.nu_lines, self._elower, self._gpp, self._jlower, self._jupper, mask_zeronu=exomolapi.pickup_gE(ndstates,ndtrans,trans_file)\n                    if trans_file.with_suffix(\".hdf5\").exists():\n                        self.Sij0=ndtrans[:,4]\n                    else:\n                        ##Line strength: input should be ndarray not jnp array\n                        self.Sij0=exomol.Sij0(self._A,self._gpp,self.nu_lines,self._elower,self.QTref)\n\n                        #exclude the lines whose nu_lines evaluated inside exomolapi.pickup_gE (thus sometimes different from the \"nu_lines\" column in trans) is not positive\n                        trans[\"nu_positive\"]=mask_zeronu\n                        trans=trans[trans.nu_positive].extract()\n                        trans.drop('nu_positive',inplace=True)\n\n                        trans[\"nu_lines\"]=self.nu_lines\n                        trans[\"Sij0\"]=self.Sij0\n                else:\n                    Ax, nulx, elowerx, gppx, jlowerx, jupperx, mask_zeronu=exomolapi.pickup_gE(ndstates,ndtrans,trans_file)\n                    if trans_file.with_suffix(\".hdf5\").exists():\n                        Sij0x=ndtrans[:,4]\n                    else:\n                        ##Line strength: input should be ndarray not jnp array\n                        Sij0x=exomol.Sij0(Ax,gppx,nulx,elowerx,self.QTref)\n\n                        #exclude the lines whose nu_lines evaluated inside exomolapi.pickup_gE (thus sometimes different from the \"nu_lines\" column in trans) is not positive\n                        trans[\"nu_positive\"]=mask_zeronu\n                        trans=trans[trans.nu_positive].extract()\n                        trans.drop('nu_positive',inplace=True)\n\n                        trans[\"nu_lines\"]=nulx\n                        trans[\"Sij0\"]=Sij0x\n\n                    self._A=np.hstack([self._A,Ax])\n                    self.nu_lines=np.hstack([self.nu_lines,nulx])\n                    self._elower=np.hstack([self._elower,elowerx])\n                    self._gpp=np.hstack([self._gpp,gppx])\n                    self._jlower=np.hstack([self._jlower,jlowerx])\n                    self._jupper=np.hstack([self._jupper,jupperx])\n                    self.Sij0=np.hstack([self.Sij0,Sij0x])\n\n                if not trans_file.with_suffix(\".hdf5\").exists():\n                    trans.export(trans_file.with_suffix(\".hdf5\"))\n        \n        ### MASKING ###\n        mask=(self.nu_lines>self.nurange[0]-self.margin)\\\n        *(self.nu_lines<self.nurange[1]+self.margin)\\\n        *(self.Sij0>self.crit)\n\n        self.masking(mask,mask_needed)\n        \n    def masking(self,mask,mask_needed=True):\n        \"\"\"applying mask and (re)generate jnp.arrays\n        \n        Args:\n           mask: mask to be applied. self.mask is updated.\n           mask_needed: whether mask needs to be applied or not\n\n        Note:\n           We have nd arrays and jnp arrays. We apply the mask to nd arrays and generate jnp array from the corresponding nd array. For instance, self._A is nd array and self.A is jnp array.\n\n        \"\"\"\n        if mask_needed:\n            #numpy float 64 Do not convert them jnp array\n            self.nu_lines = self.nu_lines[mask]\n            self.Sij0 = self.Sij0[mask]\n            self._A=self._A[mask]\n            self._elower=self._elower[mask]\n            self._gpp=self._gpp[mask]\n            self._jlower=self._jlower[mask]\n            self._jupper=self._jupper[mask]\n        \n        #jnp arrays\n        self.dev_nu_lines=jnp.array(self.nu_lines)\n        self.logsij0=jnp.array(np.log(self.Sij0))\n        self.A=jnp.array(self._A)\n        self.gamma_natural=gn(self.A)\n        self.elower=jnp.array(self._elower)\n        self.gpp=jnp.array(self._gpp)\n        self.jlower=jnp.array(self._jlower,dtype=int)\n        self.jupper=jnp.array(self._jupper,dtype=int)\n        ##Broadening parameters \n        self.set_broadening()\n\n    def set_broadening(self,alpha_ref_def=None,n_Texp_def=None):\n        \"\"\"setting broadening parameters\n        \n        Args:\n           alpha_ref: set default alpha_ref and apply it. None=use self.alpha_ref_def\n           n_Texp_def: set default n_Texp and apply it. None=use self.n_Texp_def\n\n        \"\"\"\n        if alpha_ref_def:\n            self.alpha_ref_def = alpha_ref_def\n        if n_Texp_def:\n            self.n_Texp_def = n_Texp_def\n            \n        if self.broadf:\n            try:\n                print(\".broad is used.\")\n                bdat=exomolapi.read_broad(self.broad_file)\n                codelv=exomolapi.check_bdat(bdat)\n                print(\"Broadening code level=\",codelv)\n                if codelv==\"a0\":\n                    j2alpha_ref, j2n_Texp = exomolapi.make_j2b(bdat,\\\n                        alpha_ref_default=self.alpha_ref_def,\\\n                        n_Texp_default=self.n_Texp_def,\\\n                        jlower_max=np.max(self._jlower))\n                    self.alpha_ref=jnp.array(j2alpha_ref[self._jlower])\n                    self.n_Texp=jnp.array(j2n_Texp[self._jlower])                \n                elif codelv==\"a1\":\n                    j2alpha_ref, j2n_Texp = exomolapi.make_j2b(bdat,\\\n                        alpha_ref_default=self.alpha_ref_def,\\\n                        n_Texp_default=self.n_Texp_def,\\\n                        jlower_max=np.max(self._jlower))                \n                    jj2alpha_ref, jj2n_Texp=exomolapi.make_jj2b(bdat,\\\n                        j2alpha_ref_def=j2alpha_ref,j2n_Texp_def=j2n_Texp,\\\n                        jupper_max=np.max(self._jupper))\n                    self.alpha_ref=jnp.array(jj2alpha_ref[self._jlower,self._jupper])\n                    self.n_Texp=jnp.array(jj2n_Texp[self._jlower,self._jupper])            \n            except:\n                print(\"Warning: Cannot load .broad. The default broadening parameters are used.\")\n                self.alpha_ref=jnp.array(self.alpha_ref_def*np.ones_like(self._jlower))\n                self.n_Texp=jnp.array(self.n_Texp_def*np.ones_like(self._jlower))\n                \n        else:\n            print(\"The default broadening parameters are used.\")\n            self.alpha_ref=jnp.array(self.alpha_ref_def*np.ones_like(self._jlower))\n            self.n_Texp=jnp.array(self.n_Texp_def*np.ones_like(self._jlower))\n                  \n    def QT_interp(self,T):\n        \"\"\"interpolated partition function\n\n        Args:\n           T: temperature\n\n        Returns:\n           Q(T) interpolated in jnp.array\n\n        \"\"\"\n        return jnp.interp(T,self.T_gQT,self.gQT)\n    \n    def qr_interp(self,T):\n        \"\"\"interpolated partition function ratio\n\n        Args:\n           T: temperature\n\n        Returns:\n           qr(T)=Q(T)/Q(Tref) interpolated in jnp.array\n\n        \"\"\"\n        return self.QT_interp(T)/self.QT_interp(self.Tref)\n    \n        \n    def download(self,molec,extension,numtag=None):\n        \"\"\"Downloading Exomol files\n\n        Args: \n           molec: like \"12C-16O__Li2015\"\n           extension: extension list e.g. [\".pf\",\".def\",\".trans.bz2\",\".states.bz2\",\".broad\"]\n           numtag: number tag of transition file if exists. e.g. \"11100-11200\"\n\n        Note:\n           The download URL is written in exojax.utils.url.\n        \n        \"\"\"\n        import urllib.request\n        from exojax.utils.molname import e2s\n        import os\n        from exojax.utils.url import url_ExoMol\n\n        tag=molec.split(\"__\")\n        molname_simple=e2s(tag[0])\n        \n        for ext in extension:\n            if ext==\".trans.bz2\" and numtag is not None:\n                ext=\"__\"+numtag+ext\n                \n            if ext==\".broad\":\n                pfname_arr=[tag[0]+\"__H2\"+ext,tag[0]+\"__He\"+ext,tag[0]+\"__air\"+ext]\n                url = url_ExoMol()+molname_simple+\"/\"+tag[0]+\"/\"\n            else:\n                pfname_arr=[molec+ext]\n                url = url_ExoMol()+molname_simple+\"/\"+tag[0]+\"/\"+tag[1]+\"/\"\n                \n            for pfname in pfname_arr:\n                pfpath=url+pfname\n                os.makedirs(str(self.path), exist_ok=True)\n                print(\"Downloading \"+pfpath)\n                try:\n                    urllib.request.urlretrieve(pfpath,str(self.path/pfname))\n                except:\n                    print(\"Error: Couldn't download \"+ext+\" file and save.\")\n\n\n\n\nclass MdbHit(object):\n    \"\"\" molecular database of ExoMol\n\n    MdbExomol is a class for ExoMol.\n\n    Attributes:\n        nurange: nu range [min,max] (cm-1)\n        nu_lines (nd array): line center (cm-1)\n        Sij0 (nd array): line strength at T=Tref (cm)\n        dev_nu_lines (jnp array): line center in device (cm-1)\n        logsij0 (jnp array): log line strength at T=Tref\n        A (jnp array): Einstein A coeeficient\n        gamma_natural (jnp array): gamma factor of the natural broadening\n        gamma_air (jnp array): gamma factor of air pressure broadening\n        gamma_self (jnp array): gamma factor of self pressure broadening\n        elower (jnp array): the lower state energy (cm-1)\n        gpp (jnp array): statistical weight\n        n_air (jnp array): air temperature exponent\n\n    \"\"\"\n\n    def __init__(self,path,nurange=[-np.inf,np.inf],margin=0.0,crit=-np.inf,extract=False):\n        \"\"\"Molecular database for HITRAN/HITEMP form\n\n        Args: \n           path: path for HITRAN/HITEMP par file\n           nurange: wavenumber range list (cm-1) [min,max] or wavenumber grid \n           margin: margin for nurange (cm-1)\n           crit: line strength lower limit for extraction\n           extract: If True, it extracts the opacity having the wavenumber between nurange +- margin. Use when you want to reduce the memory use.  \n\n        \"\"\"        \n        #downloading\n        self.path = pathlib.Path(path)\n        if not self.path.exists():\n            self.download()\n\n        #extract?\n        if extract:\n            if self.path.suffix==\".bz2\":\n                tag=str(nurange[0])+\"_\"+str(nurange[-1])+\"_\"+str(margin)\n                self.path = hitranapi.extract_hitemp(str(self.path),nurange,margin,tag)\n                print(\"self.path changed:\",self.path)\n            else:\n                print('Warning: \"extract\" option is available only for .bz2 format. No \"extract\" applied')\n            \n        #bunzip2 if suffix is .bz2\n        if self.path.suffix==\".bz2\":\n            import bz2,shutil\n            if self.path.with_suffix('').exists():\n                import os\n                os.remove(self.path.with_suffix(''))\n            print(\"bunziping\")\n            with bz2.BZ2File(str(self.path)) as fr:\n                with open(str(self.path.with_suffix('')),\"wb\") as fw:\n                    shutil.copyfileobj(fr,fw)\n            self.path=self.path.with_suffix('')\n            \n        hapi.db_begin(str(self.path.parent))            \n        molec=str(self.path.stem)\n        self.Tref=296.0        \n        self.molecid = search_molecid(molec)\n        self.crit = crit\n        self.margin = margin\n        self.nurange=[np.min(nurange),np.max(nurange)]\n\n        #nd arrays using DRAM (not jnp, not in GPU)\n        self.nu_lines = hapi.getColumn(molec, 'nu')\n        self.Sij0 = hapi.getColumn(molec, 'sw')\n        self.delta_air = hapi.getColumn(molec, 'delta_air')\n        self.isoid = hapi.getColumn(molec,'local_iso_id')\n        self.uniqiso=np.unique(self.isoid)\n\n        self._A=hapi.getColumn(molec, 'a')\n        self._n_air = hapi.getColumn(molec, 'n_air')\n        self._gamma_air = hapi.getColumn(molec, 'gamma_air')\n        self._gamma_self =hapi.getColumn(molec, 'gamma_self')\n        self._elower = hapi.getColumn(molec, 'elower')\n        self._gpp = hapi.getColumn(molec, 'gpp')\n\n        ### MASKING ###\n        mask=(self.nu_lines>self.nurange[0]-self.margin)\\\n        *(self.nu_lines<self.nurange[1]+self.margin)\\\n        *(self.Sij0>self.crit)\n        \n        self.masking(mask)\n        \n    def masking(self,mask):\n        \"\"\"applying mask and (re)generate jnp.arrays\n        \n        Args:\n           mask: mask to be applied\n\n        Note:\n           We have nd arrays and jnp arrays. We apply the mask to nd arrays and generate jnp array from the corresponding nd array. For instance, self._A is nd array and self.A is jnp array.\n\n        \"\"\"\n        \n        #numpy float 64 Do not convert them jnp array\n        self.nu_lines = self.nu_lines[mask]\n        self.Sij0 = self.Sij0[mask]\n        self.delta_air=self.delta_air[mask]\n        self.isoid = self.isoid[mask]\n        self.uniqiso=np.unique(self.isoid)\n\n        ##numpy float 64 copy source for jnp\n        self._A=self._A[mask]\n        self._n_air = self._n_air[mask]\n        self._gamma_air = self._gamma_air[mask]\n        self._gamma_self = self._gamma_self[mask]\n        self._elower = self._elower[mask]\n        self._gpp = self._gpp[mask]\n\n        #jnp.array copy from the copy sources\n        self.dev_nu_lines=jnp.array(self.nu_lines)\n        self.logsij0=jnp.array(np.log(self.Sij0))\n        self.A=jnp.array(self._A)\n        self.n_air=jnp.array(self._n_air)\n        self.gamma_air = jnp.array(self._gamma_air)\n        self.gamma_self = jnp.array(self._gamma_self)\n        self.elower=jnp.array(self._elower)\n        self.gpp=jnp.array(self._gpp)\n        self.gamma_natural=gn(self.A)\n\n        \n    def download(self):\n        \"\"\"Downloading HITRAN/HITEMP par file\n\n        Note:\n           The download URL is written in exojax.utils.url.\n\n        \"\"\"\n        import urllib.request\n        from exojax.utils.url import url_HITRAN12\n        from exojax.utils.url import url_HITEMP\n\n        try:\n            url = url_HITRAN12()+self.path.name\n            urllib.request.urlretrieve(url,str(self.path))\n        except:\n            print(url)\n            print(\"HITRAN download failed\")\n        try:\n            url = url_HITEMP()+self.path.name\n            print(url)\n            urllib.request.urlretrieve(url,str(self.path))\n        except:\n            print(\"HITEMP download failed\")\n\n    ####################################\n\n    def ExomolQT(self,path):\n        \"\"\"use a partition function from ExoMol\n\n        Args:\n           path: path for Exomol data directory/tag. For instance, \"/home/CO/12C-16O/Li2015\"\n\n        \"\"\"\n        #load pf\n\n        self.empath = pathlib.Path(path)\n        t0=self.empath.parents[0].stem        \n        molec=t0+\"__\"+str(self.empath.stem)\n        self.pf_file = self.empath/pathlib.Path(molec+\".pf\")\n        if not self.pf_file.exists():\n                self.exomol_pf_download(molec)\n\n        pf=exomolapi.read_pf(self.pf_file)\n        self.gQT=jnp.array(pf[\"QT\"].to_numpy()) #grid QT\n        self.T_gQT=jnp.array(pf[\"T\"].to_numpy()) #T forgrid QT\n\n    def exomol_pf_download(self,molec):\n        \"\"\"Downloading Exomol pf files\n\n        Args: \n           molec: like \"12C-16O__Li2015\"\n\n        Note:\n           The download URL is written in exojax.utils.url.\n\n        \"\"\"\n        import urllib.request\n        from exojax.utils.molname import e2s\n        import os\n        from exojax.utils.url import url_ExoMol\n\n        tag=molec.split(\"__\")\n        molname_simple=e2s(tag[0])        \n        url = url_ExoMol()+molname_simple+\"/\"+tag[0]+\"/\"+tag[1]+\"/\"\n\n        ext=\".pf\"\n        pfname=molec+ext\n        pfpath=url+pfname\n        os.makedirs(str(self.empath), exist_ok=True)\n        print(\"Downloading \"+pfpath)\n        try:\n            urllib.request.urlretrieve(pfpath,str(self.empath/pfname))\n        except:\n            print(\"Error: Couldn't download \"+ext+\" file and save.\")\n\n        \n    def QT_interp(self,T):\n        \"\"\"interpolated partition function\n\n        Args:\n           T: temperature\n\n        Returns:\n           Q(T) interpolated in jnp.array\n\n        \"\"\"\n        return jnp.interp(T,self.T_gQT,self.gQT)\n    \n    def qr_interp(self,T):\n        \"\"\"interpolated partition function ratio\n\n        Args:\n           T: temperature\n\n        Returns:\n           qr(T)=Q(T)/Q(Tref) interpolated in jnp.array\n\n        \"\"\"\n        return self.QT_interp(T)/self.QT_interp(self.Tref)\n    \n\n    def Qr_HAPI(self,Tarr):\n        \"\"\"Partition Function ratio using HAPI partition sum\n\n        Args:\n           Tarr: temperature array (K)\n        \n        Returns:\n           Qr = partition function ratio array [N_Tarr x N_iso]\n\n        Note: \n           N_Tarr = len(Tarr), N_iso = len(self.uniqiso)\n\n        \"\"\"\n        allT=list(np.concatenate([[self.Tref],Tarr]))\n        Qrx=[]\n        for iso in self.uniqiso:\n            Qrx.append(hapi.partitionSum(self.molecid,iso, allT))\n        Qrx=np.array(Qrx)\n        qr=Qrx[:,1:].T/Qrx[:,0] #Q(T)/Q(Tref)\n        return qr\n\n    def Qr_line_HAPI(self,T):\n        \"\"\"Partition Function ratio using HAPI partition sum\n\n        Args:\n           T: temperature (K)\n\n        Returns:\n           Qr_line, partition function ratio array for lines [Nlines]\n\n        Note: \n           Nlines=len(self.nu_lines)\n\n        \"\"\"\n        qr_line=np.ones_like(self.isoid,dtype=np.float64)\n        qrx=self.Qr_HAPI([T])\n        for idx,iso in enumerate(self.uniqiso):\n            mask=self.isoid==iso\n            qr_line[mask]=qrx[0,idx]\n        return qr_line\n\n    def Qr_layer_HAPI(self,Tarr):\n        \"\"\"Partition Function ratio using HAPI partition sum\n\n        Args:\n           Tarr: temperature array (K)\n\n        Returns:\n           Qr_layer, partition function ratio array for lines [N_Tarr x Nlines]\n\n        Note: \n           Nlines=len(self.nu_lines)\n           N_Tarr=len(Tarr)\n\n        \"\"\"\n        NP=len(Tarr)\n        qt=np.zeros((NP,len(self.isoid)))\n        qr=self.Qr_HAPI(Tarr)\n        for idx,iso in enumerate(self.uniqiso):\n            mask=self.isoid==iso\n            for ilayer in range(NP):\n                qt[ilayer,mask]=qr[ilayer,idx]\n        return qt\n    \ndef search_molecid(molec):\n    \"\"\"molec id from molec (source table name) of HITRAN/HITEMP\n\n    Args:\n       molec: source table name\n\n    Return:\n       int: molecid (HITRAN molecular id)\n\n    \"\"\"\n    try:\n        hitf=molec.split(\"_\")\n        molecid=int(hitf[0])\n        return molecid\n\n    except:\n        print(\"Warning: Define molecid by yourself.\")\n        return None\n\nif __name__ == \"__main__\":\n    #mdb=MdbExomol(\"/home/kawahara/exojax/data/CO/12C-16O/Li2015/\")    \n    #mdb=MdbExomol(\"/home/kawahara/exojax/data/CH4/12C-1H4/YT34to10/\",nurange=[6050.0,6150.0])\n    mdb=MdbExomol('.database/H2O/1H2-16O/POKAZATEL',[4310.0,4320.0],crit=1.e-45) \n\n#    mask=mdb.A>1.e-42\n#    mdb.masking(mask)\n#    mdb=MdbExomol(\"/home/kawahara/exojax/data/exomol/NH3/14N-1H3/CoYuTe/\",nurange=[6050.0,6150.0])\n#    mdb=MdbExomol(\"/home/kawahara/exojax/data/exomol/H2S/1H2-32S/AYT2/\",nurange=[6050.0,6150.0])\n#    mdb=MdbExomol(\"/home/kawahara/exojax/data/exomol/FeH/56Fe-1H/MoLLIST/\",nurange=[6050.0,6150.0])\n#    mdb=MdbExomol(\"/home/kawahara/exojax/data/exomol/NO/14N-16O/NOname/14N-16O__NOname\")\n\n\n\n\nclass AdbVald(object):  #integrated from vald3db.py\n    \"\"\" atomic database from VALD3 (http://vald.astro.uu.se/)\n    \n    AdbVald is a class for VALD3.\n    \n    Attributes:\n        nurange: nu range [min,max] (cm-1)\n        nu_lines (nd array):      line center (cm-1) (#NOT frequency in (s-1))\n        dev_nu_lines (jnp array): line center (cm-1) in device\n        Sij0 (nd array): line strength at T=Tref (cm)\n        logsij0 (jnp array): log line strength at T=Tref\n        A (jnp array): Einstein A coeeficient in (s-1)\n        elower (jnp array): the lower state energy (cm-1)\n        eupper (jnp array): the upper state energy (cm-1)\n        gupper: (jnp array): upper statistical weight\n        jlower (jnp array): lower J (rotational quantum number, total angular momentum)\n        jupper (jnp array): upper J\n        QTmask (jnp array): identifier of species for Q(T)\n        ielem (jnp array):  atomic number (e.g., Fe=26)\n        iion (jnp array):  ionized level (e.g., neutral=1, singly ionized=2, etc.)\n        gamRad (jnp array): log of gamma of radiation damping (s-1) #(https://www.astro.uu.se/valdwiki/Vald3Format)\n        gamSta (jnp array): log of gamma of Stark damping (s-1)\n        vdWdamp (jnp array):  log of (van der Waals damping constant / neutral hydrogen number) (s-1)\n        \n        Note:\n           For the first time to read the VALD line list, it is converted to HDF/vaex. After the second-time, we use the HDF5 format with vaex instead.\n\n    \"\"\"\n    def __init__(self, path, nurange=[-np.inf,np.inf], margin=0.0, crit=-np.inf, Irwin=False):\n    \n        \"\"\"Atomic database for VALD3 \"Long format\"\n\n        Args:\n          path: path for linelists downloaded from VALD3 with a query of \"Long format\" in the format of \"Extract All\" and \"Extract Element\" (NOT \"Extract Stellar\")\n          nurange: wavenumber range list (cm-1) or wavenumber array\n          margin: margin for nurange (cm-1)\n          crit: line strength lower limit for extraction\n          Irwin: if True(1), the partition functions of Irwin1981 is used, otherwise those of Barklem&Collet2016\n\n        Note:\n          (written with reference to moldb.py, but without using feather format)\n        \"\"\"\n\n        #load args\n        self.vald3_file = pathlib.Path(path) #VALD3 output\n        #self.path = pathlib.Path(path) #molec=t0+\"__\"+str(self.path.stem) #t0=self.path.parents[0].stem\n        self.nurange = [np.min(nurange),np.max(nurange)]\n        self.margin = margin\n        self.crit = crit\n        #self.bkgdatm=bkgdatm\n        #self.broadf=broadf\n        \n        #load vald file (\"Extract Stellar\" request)\n        print(\"Reading VALD file\")\n        if self.vald3_file.with_suffix(\".hdf5\").exists():\n            valdd = vaex.open(self.vald3_file.with_suffix(\".hdf5\"))\n        else:\n            print(\"Note: Couldn't find the hdf5 format. We convert data to the hdf5 format.\")\n            valdd = atomllapi.read_ExAll(self.vald3_file) #vaex.DataFrame\n        pvaldd = valdd.to_pandas_df() #pandas.DataFrame\n        \n        #compute additional transition parameters\n        self._A, self.nu_lines, self._elower, self._eupper, self._gupper, self._jlower, self._jupper, self._ielem, self._iion, self._gamRad, self._gamSta, self._vdWdamp = atomllapi.pickup_param(pvaldd)\n                \n        #load the partition functions (for 284 atomic species)\n        pfTdat, self.pfdat = atomllapi.load_pf_Barklem2016() #Barklem & Collet (2016)\n        self.T_gQT = jnp.array(pfTdat.columns[1:], dtype=float)\n        self.gQT_284species = jnp.array(self.pfdat.iloc[:, 1:].to_numpy(dtype=float)) #grid Q vs T vs Species\n        self.Tref=296.0 #\\\\\\\\\n        self.QTref_284 = np.array(self.QT_interp_284(self.Tref))\n        self._QTmask = self.make_QTmask(self._ielem, self._iion) #identify index of QT grid (gQT) for each line\n\n        ##Line strength: input shoud be ndarray not jnp array\n        self.Sij0 = atomll.Sij0(self._A, self._gupper, self.nu_lines, self._elower, self.QTref_284, self._QTmask, Irwin) #211013\n\n        ### MASKING ###\n        mask=(self.nu_lines>self.nurange[0]-self.margin)\\\n        *(self.nu_lines<self.nurange[1]+self.margin)\\\n        *(self.Sij0>self.crit)\n        \n        self.masking(mask)\n\n        #Compile atomic-specific data for each absorption line of interest\n        self.ipccd = atomllapi.load_atomicdata()\n        #print(self.ipccd)#test\n        # should be refined\n        ionE = jnp.array(list(map(lambda x: self.ipccd[self.ipccd['ielem']==x].iat[0, 1], self.ielem)))\n        ionE2 = jnp.array(list(map(lambda x: self.ipccd[self.ipccd['ielem']==x].iat[0, 6], self.ielem)))\n        self.ionE = ionE * np.where(self.iion==1, 1, 0) + ionE2 * np.where(self.iion==2, 1, 0)\n        self.solarA = jnp.array(list(map(lambda x: self.ipccd[self.ipccd['ielem']==x].iat[0, 4], self.ielem)))\n        self.atomicmass = jnp.array(list(map(lambda x: self.ipccd[self.ipccd['ielem']==x].iat[0, 5], self.ielem)))\n            \n    #End of the CONSTRUCTOR definition ↑\n\n\n\n\n    #Defining METHODS ↓\n    \n    \n    \n    def masking(self,mask):\n        \"\"\"applying mask and (re)generate jnp.arrays\n        \n        Args:\n           mask: mask to be applied. self.mask is updated.\n\n        Note:\n           We have nd arrays and jnp arrays. We apply the mask to nd arrays and generate jnp array from the corresponding nd array. For instance, self._A is nd array and self.A is jnp array.\n\n        \"\"\"\n        #numpy float 64 Do not convert them jnp array\n        self.nu_lines = self.nu_lines[mask]\n        self.Sij0 = self.Sij0[mask]\n        self._A=self._A[mask]\n        self._elower=self._elower[mask]\n        self._eupper=self._eupper[mask]\n        self._gupper=self._gupper[mask]\n        self._jlower=self._jlower[mask]\n        self._jupper=self._jupper[mask]\n        self._QTmask=self._QTmask[mask]\n        self._ielem=self._ielem[mask]\n        self._iion=self._iion[mask]\n        self._gamRad=self._gamRad[mask]\n        self._gamSta=self._gamSta[mask]\n        self._vdWdamp=self._vdWdamp[mask]\n\n        #jnp arrays\n        self.dev_nu_lines=jnp.array(self.nu_lines)\n        self.logsij0=jnp.array(np.log(self.Sij0))\n        self.A=jnp.array(self._A)\n        self.elower=jnp.array(self._elower)\n        self.eupper=jnp.array(self._eupper)\n        self.gupper=jnp.array(self._gupper)\n        self.jlower=jnp.array(self._jlower,dtype=int)\n        self.jupper=jnp.array(self._jupper,dtype=int)\n        \n        self.QTmask=jnp.array(self._QTmask,dtype=int)\n        self.ielem=jnp.array(self._ielem,dtype=int)\n        self.iion=jnp.array(self._iion,dtype=int)\n        self.gamRad=jnp.array(self._gamRad)\n        self.gamSta=jnp.array(self._gamSta)\n        self.vdWdamp=jnp.array(self._vdWdamp)\n\n\n\n    def Atomic_gQT(self, atomspecies):\n        \"\"\"Select grid of partition function especially for the species of interest\n        \n        Args:\n            atomspecies: species e.g., \"Fe 1\", \"Sr 2\", etc.\n            \n        Returns:\n            gQT: grid Q(T) for the species\n        \n        \"\"\"\n        #if len(atomspecies.split(' '))==2:\n        atomspecies_Roman = atomspecies.split(' ')[0] + '_' + 'I'*int(atomspecies.split(' ')[-1])\n        gQT = self.gQT_284species[ np.where(self.pfdat['T[K]']==atomspecies_Roman) ][0]\n        return gQT\n    \n    \n    \n    def QT_interp(self, atomspecies, T):\n        \"\"\"interpolated partition function\n            The partition functions of Barklem & Collet (2016) are adopted.\n\n        Args:\n          atomspecies: species e.g., \"Fe 1\"\n          T: temperature\n\n        Returns:\n          Q(T): interpolated in jnp.array for the Atomic Species\n\n        \"\"\"\n        gQT = self.Atomic_gQT(atomspecies)\n        QT = jnp.interp(T, self.T_gQT, gQT)\n        return QT\n\n\n\n    def QT_interp_Irwin_Fe(self, T, atomspecies=\"Fe 1\"):\n        \"\"\"interpolated partition function\n            This function is for the exceptional case where you want to adopt partition functions of Irwin (1981) for Fe I (Other species are not yet implemented).\n\n        Args:\n          atomspecies: species e.g., \"Fe 1\"\n          T: temperature\n\n        Returns:\n          Q(T): interpolated in jnp.array for the Atomic Species\n\n        \"\"\"\n        gQT = self.Atomic_gQT(atomspecies)\n        QT = atomllapi.partfn_Fe(T)\n        return QT\n\n\n\n    def qr_interp(self, atomspecies, T):\n        \"\"\"interpolated partition function ratio\n            The partition functions of Barklem & Collet (2016) are adopted.\n\n        Args:\n           T: temperature\n           atomspecies: species e.g., \"Fe 1\"\n\n        Returns:\n           qr(T)=Q(T)/Q(Tref): interpolated in jnp.array\n\n        \"\"\"\n        return self.QT_interp(atomspecies,T)/self.QT_interp(atomspecies,self.Tref)\n\n\n\n    def qr_interp_Irwin_Fe(self, T, atomspecies=\"Fe 1\"):\n        \"\"\"interpolated partition function ratio\n            This function is for the exceptional case where you want to adopt partition functions of Irwin (1981) for Fe I (Other species are not yet implemented).\n\n        Args:\n           T: temperature\n           atomspecies: species e.g., \"Fe 1\"\n\n        Returns:\n           qr(T)=Q(T)/Q(Tref): interpolated in jnp.array\n\n        \"\"\"\n        return self.QT_interp_Irwin_Fe(T,atomspecies)/self.QT_interp_Irwin_Fe(self.Tref,atomspecies)\n\n\n\n    def QT_interp_284(self, T):\n        \"\"\"interpolated partition function of all 284 species\n\n        Args:\n           T: temperature\n\n        Returns:\n           Q(T)*284: interpolated in jnp.array for all 284 Atomic Species\n\n        \"\"\"\n        #self.T_gQT.shape -> (42,)\n        #self.gQT_284species.shape -> (284, 42)\n        list_gQT_eachspecies = self.gQT_284species.tolist()\n        listofDA_gQT_eachspecies = list(map(lambda x: jnp.array(x), list_gQT_eachspecies))\n        listofQT = list(map(lambda x: jnp.interp(T, self.T_gQT, x), listofDA_gQT_eachspecies))\n        QT_284 = jnp.array(listofQT)\n        return QT_284\n\n\n\n    def make_QTmask(self, ielem, iion):\n        \"\"\"Convert the species identifier to the index for Q(Tref) grid (gQT) for each line\n\n        Args:\n            ielem:  atomic number (e.g., Fe=26)\n            iion:  ionized level (e.g., neutral=1, singly)\n            \n        Returns:\n            QTmask_sp:  array of index of Q(Tref) grid (gQT) for each line\n            \n        \"\"\"\n        def species_to_QTmask(ielem, iion):\n            sp_Roman = atomllapi.PeriodicTable[ielem] + '_' + 'I'*iion\n            QTmask = np.where(self.pfdat['T[K]']==sp_Roman)[0][0]\n            return QTmask\n        QTmask_sp = np.array(list(map(species_to_QTmask, ielem, iion))).astype('int')\n        return(QTmask_sp)\n        \n        \n        \n\nclass AdbKurucz(object):\n    \"\"\" atomic database from Kurucz (http://kurucz.harvard.edu/linelists/)\n    \n    AdbKurucz is a class for Kurucz line list.\n    \n    Attributes:\n        nurange: nu range [min,max] (cm-1)\n        nu_lines (nd array):      line center (cm-1) (#NOT frequency in (s-1))\n        dev_nu_lines (jnp array): line center (cm-1) in device\n        Sij0 (nd array): line strength at T=Tref (cm)\n        logsij0 (jnp array): log line strength at T=Tref\n        A (jnp array): Einstein A coeeficient in (s-1)\n        elower (jnp array): the lower state energy (cm-1)\n        eupper (jnp array): the upper state energy (cm-1)\n        gupper: (jnp array): upper statistical weight\n        jlower (jnp array): lower J (rotational quantum number, total angular momentum)\n        jupper (jnp array): upper J\n        QTmask (jnp array): identifier of species for Q(T)\n        ielem (jnp array):  atomic number (e.g., Fe=26)\n        iion (jnp array):  ionized level (e.g., neutral=1, singly ionized=2, etc.)\n        gamRad (jnp array): log of gamma of radiation damping (s-1) #(https://www.astro.uu.se/valdwiki/Vald3Format)\n        gamSta (jnp array): log of gamma of Stark damping (s-1)\n        vdWdamp (jnp array):  log of (van der Waals damping constant / neutral hydrogen number) (s-1)\n    \n    \"\"\"\n    def __init__(self, path, nurange=[-np.inf,np.inf], margin=0.0, crit=-np.inf, Irwin=False):\n    \n        \"\"\"Atomic database for Kurucz line list \"gf????.all\"\n\n        Args:\n          path: path for linelists (gf????.all) downloaded from the Kurucz web page\n          nurange: wavenumber range list (cm-1) or wavenumber array\n          margin: margin for nurange (cm-1)\n          crit: line strength lower limit for extraction\n          Irwin: if True(1), the partition functions of Irwin1981 is used, otherwise those of Barklem&Collet2016\n\n        Note:\n          (written with reference to moldb.py, but without using feather format)\n        \"\"\"\n        \n        #load args\n        self.kurucz_file = pathlib.Path(path) #VALD3 output\n        #self.path = pathlib.Path(path) #molec=t0+\"__\"+str(self.path.stem) #t0=self.path.parents[0].stem\n        self.nurange = [np.min(nurange),np.max(nurange)]\n        self.margin = margin\n        self.crit = crit\n        #self.bkgdatm=bkgdatm\n        #self.broadf=broadf\n        \n        \n\n        #load vald file (\"Extract Stellar\" request)\n        print(\"Reading Kurucz file\")\n        self._A, self.nu_lines, self._elower, self._eupper, self._gupper, self._jlower, self._jupper, self._ielem, self._iion, self._gamRad, self._gamSta, self._vdWdamp = atomllapi.read_kurucz(self.kurucz_file)\n        \n        \n        \n        #load the partition functions (for 284 atomic species)\n        pfTdat, self.pfdat = atomllapi.load_pf_Barklem2016() #Barklem & Collet (2016)\n        self.T_gQT = jnp.array(pfTdat.columns[1:], dtype=float)\n        self.gQT_284species = jnp.array(self.pfdat.iloc[:, 1:].to_numpy(dtype=float)) #grid Q vs T vs Species\n        self.Tref=296.0\n        self.QTref_284 = np.array(self.QT_interp_284(self.Tref))\n        self._QTmask = self.make_QTmask(self._ielem, self._iion) #identify index of QT grid (gQT) for each line\n\n\n\n        ##Line strength: input shoud be ndarray not jnp array\n        self.Sij0 = atomll.Sij0(self._A, self._gupper, self.nu_lines, self._elower, self.QTref_284, self._QTmask, Irwin) #211013\n\n\n\n        ### MASKING ###\n        mask=(self.nu_lines>self.nurange[0]-self.margin)\\\n        *(self.nu_lines<self.nurange[1]+self.margin)\\\n        *(self.Sij0>self.crit)\n        \n        self.masking(mask)\n        \n\n\n        #Compile atomic-specific data for each absorption line of interest\n        self.ipccd = atomllapi.load_atomicdata()\n        #print(self.ipccd)#test\n        ionE = jnp.array(list(map(lambda x: self.ipccd[self.ipccd['ielem']==x].iat[0, 1], self.ielem)))\n        ionE2 = jnp.array(list(map(lambda x: self.ipccd[self.ipccd['ielem']==x].iat[0, 6], self.ielem)))\n        self.ionE = ionE * np.where(self.iion==1, 1, 0) + ionE2 * np.where(self.iion==2, 1, 0)\n        self.solarA = jnp.array(list(map(lambda x: self.ipccd[self.ipccd['ielem']==x].iat[0, 4], self.ielem)))\n        self.atomicmass = jnp.array(list(map(lambda x: self.ipccd[self.ipccd['ielem']==x].iat[0, 5], self.ielem)))\n        \n            \n            \n    #End of the CONSTRUCTOR definition ↑\n\n\n\n\n    #Defining METHODS ↓\n    \n    \n    \n    def masking(self,mask):\n        \"\"\"applying mask and (re)generate jnp.arrays\n        \n        Args:\n           mask: mask to be applied. self.mask is updated.\n\n        Note:\n           We have nd arrays and jnp arrays. We apply the mask to nd arrays and generate jnp array from the corresponding nd array. For instance, self._A is nd array and self.A is jnp array.\n\n        \"\"\"\n        #numpy float 64 Do not convert them jnp array\n        self.nu_lines = self.nu_lines[mask]\n        self.Sij0 = self.Sij0[mask]\n        self._A=self._A[mask]\n        self._elower=self._elower[mask]\n        self._eupper=self._eupper[mask]\n        self._gupper=self._gupper[mask]\n        self._jlower=self._jlower[mask]\n        self._jupper=self._jupper[mask]\n        self._QTmask=self._QTmask[mask]\n        self._ielem=self._ielem[mask]\n        self._iion=self._iion[mask]\n        self._gamRad=self._gamRad[mask]\n        self._gamSta=self._gamSta[mask]\n        self._vdWdamp=self._vdWdamp[mask]\n\n        #jnp arrays\n        self.dev_nu_lines=jnp.array(self.nu_lines)\n        self.logsij0=jnp.array(np.log(self.Sij0))\n        self.A=jnp.array(self._A)\n        self.elower=jnp.array(self._elower)\n        self.eupper=jnp.array(self._eupper)\n        self.gupper=jnp.array(self._gupper)\n        self.jlower=jnp.array(self._jlower,dtype=int)\n        self.jupper=jnp.array(self._jupper,dtype=int)\n        \n        self.QTmask=jnp.array(self._QTmask,dtype=int)\n        self.ielem=jnp.array(self._ielem,dtype=int)\n        self.iion=jnp.array(self._iion,dtype=int)\n        self.gamRad=jnp.array(self._gamRad)\n        self.gamSta=jnp.array(self._gamSta)\n        self.vdWdamp=jnp.array(self._vdWdamp)\n\n\n\n    def Atomic_gQT(self, atomspecies):\n        \"\"\"Select grid of partition function especially for the species of interest\n        \n        Args:\n            atomspecies: species e.g., \"Fe 1\", \"Sr 2\", etc.\n            \n        Returns:\n            gQT: grid Q(T) for the species\n        \n        \"\"\"\n        #if len(atomspecies.split(' '))==2:\n        atomspecies_Roman = atomspecies.split(' ')[0] + '_' + 'I'*int(atomspecies.split(' ')[-1])\n        gQT = self.gQT_284species[ np.where(self.pfdat['T[K]']==atomspecies_Roman) ][0]\n        return gQT\n    \n    \n    \n    def QT_interp(self, atomspecies, T):\n        \"\"\"interpolated partition function\n            The partition functions of Barklem & Collet (2016) are adopted.\n\n        Args:\n          atomspecies: species e.g., \"Fe 1\"\n          T: temperature\n\n        Returns:\n          Q(T): interpolated in jnp.array for the Atomic Species\n\n        \"\"\"\n        gQT = self.Atomic_gQT(atomspecies)\n        QT = jnp.interp(T, self.T_gQT, gQT)\n        return QT\n\n\n\n    def QT_interp_Irwin_Fe(self, T, atomspecies=\"Fe 1\"):\n        \"\"\"interpolated partition function\n            This function is for the exceptional case where you want to adopt partition functions of Irwin (1981) for Fe I (Other species are not yet implemented).\n\n        Args:\n          atomspecies: species e.g., \"Fe 1\"\n          T: temperature\n\n        Returns:\n          Q(T): interpolated in jnp.array for the Atomic Species\n\n        \"\"\"\n        gQT = self.Atomic_gQT(atomspecies)\n        QT = atomllapi.partfn_Fe(T)\n        return QT\n\n\n\n    def qr_interp(self, atomspecies, T):\n        \"\"\"interpolated partition function ratio\n            The partition functions of Barklem & Collet (2016) are adopted.\n\n        Args:\n           T: temperature\n           atomspecies: species e.g., \"Fe 1\"\n\n        Returns:\n           qr(T)=Q(T)/Q(Tref): interpolated in jnp.array\n\n        \"\"\"\n        return self.QT_interp(atomspecies,T)/self.QT_interp(atomspecies,self.Tref)\n\n\n\n    def qr_interp_Irwin_Fe(self, T, atomspecies=\"Fe 1\"):\n        \"\"\"interpolated partition function ratio\n            This function is for the exceptional case where you want to adopt partition functions of Irwin (1981) for Fe I (Other species are not yet implemented).\n\n        Args:\n           T: temperature\n           atomspecies: species e.g., \"Fe 1\"\n\n        Returns:\n           qr(T)=Q(T)/Q(Tref): interpolated in jnp.array\n\n        \"\"\"\n        return self.QT_interp_Irwin_Fe(T,atomspecies)/self.QT_interp_Irwin_Fe(self.Tref,atomspecies)\n\n\n\n    def QT_interp_284(self, T):\n        \"\"\"interpolated partition function of all 284 species\n\n        Args:\n           T: temperature\n\n        Returns:\n           Q(T)*284: interpolated in jnp.array for all 284 Atomic Species\n\n        \"\"\"\n        #self.T_gQT.shape -> (42,)\n        #self.gQT_284species.shape -> (284, 42)\n        list_gQT_eachspecies = self.gQT_284species.tolist()\n        listofDA_gQT_eachspecies = list(map(lambda x: jnp.array(x), list_gQT_eachspecies))\n        listofQT = list(map(lambda x: jnp.interp(T, self.T_gQT, x), listofDA_gQT_eachspecies))\n        QT_284 = jnp.array(listofQT)\n        return QT_284\n\n\n\n    def make_QTmask(self, ielem, iion):\n        \"\"\"Convert the species identifier to the index for Q(Tref) grid (gQT) for each line\n\n        Args:\n            ielem:  atomic number (e.g., Fe=26)\n            iion:  ionized level (e.g., neutral=1, singly)\n            \n        Returns:\n            QTmask_sp:  array of index of Q(Tref) grid (gQT) for each line\n            \n        \"\"\"\n        def species_to_QTmask(ielem, iion):\n            sp_Roman = atomllapi.PeriodicTable[ielem] + '_' + 'I'*iion\n            QTmask = np.where(self.pfdat['T[K]']==sp_Roman)[0][0]\n            return QTmask\n        QTmask_sp = np.array(list(map(species_to_QTmask, ielem, iion))).astype('int')\n        return(QTmask_sp)\n\n", "meta": {"hexsha": "cc8f3ba2493b125d5ae224acdc3156525d98d37d", "size": 47411, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/exojax/spec/moldb.py", "max_stars_repo_name": "dcmvdbekerom/exojax", "max_stars_repo_head_hexsha": "9b9305f8e383c73bdb97c1cfb0e276ddafcd75de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/exojax/spec/moldb.py", "max_issues_repo_name": "dcmvdbekerom/exojax", "max_issues_repo_head_hexsha": "9b9305f8e383c73bdb97c1cfb0e276ddafcd75de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/exojax/spec/moldb.py", "max_forks_repo_name": "dcmvdbekerom/exojax", "max_forks_repo_head_hexsha": "9b9305f8e383c73bdb97c1cfb0e276ddafcd75de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1117363344, "max_line_length": 210, "alphanum_fraction": 0.5939971737, "include": true, "reason": "import numpy,import jax", "num_tokens": 12498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.28140561345566495, "lm_q1q2_score": 0.15494400347165185}}
{"text": "import argparse\nimport glob\nimport os\nimport time\nimport sys\n\nsys.path.insert(1, './nerf')\nos.environ['GPU_DEBUG']='3'\nimport numpy as np\nimport torch\nimport torchvision\nimport yaml\nfrom torch.utils.tensorboard import SummaryWriter\nfrom tqdm import tqdm, trange\nimport matplotlib.pyplot as plt\n\nfrom nerf.load_flame import load_flame_data\n\nfrom nerf import (CfgNode, get_embedding_function, get_ray_bundle, img2mse,\n                  load_llff_data, meshgrid_xy, models,\n                  mse2psnr, run_one_iter_of_nerf, dump_rays, GaussianSmoothing)\n#from gpu_profile import gpu_profile\n\ndef main():\n\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--config\", type=str, required=True, help=\"Path to (.yml) config file.\"\n    )\n    parser.add_argument(\n        \"--load-checkpoint\",\n        type=str,\n        default=\"\",\n        help=\"Path to load saved checkpoint from.\",\n    )\n    configargs = parser.parse_args()\n\n    # Read config file.\n    cfg = None\n    with open(configargs.config, \"r\") as f:\n        cfg_dict = yaml.load(f, Loader=yaml.FullLoader)\n        cfg = CfgNode(cfg_dict)\n\n    # # (Optional:) enable this to track autograd issues when debugging\n    # torch.autograd.set_detect_anomaly(True)\n\n    # If a pre-cached dataset is available, skip the dataloader.\n    USE_CACHED_DATASET = False\n    train_paths, validation_paths = None, None\n    images, poses, render_poses, hwf, i_split, expressions = None, None, None, None, None, None\n    H, W, focal, i_train, i_val, i_test = None, None, None, None, None, None\n    if hasattr(cfg.dataset, \"cachedir\") and os.path.exists(cfg.dataset.cachedir):\n        train_paths = glob.glob(os.path.join(cfg.dataset.cachedir, \"train\", \"*.data\"))\n        validation_paths = glob.glob(\n            os.path.join(cfg.dataset.cachedir, \"val\", \"*.data\")\n        )\n        USE_CACHED_DATASET = True\n    else:\n        # Load dataset\n        images, poses, render_poses, hwf, expressions = None, None, None, None, None\n        if cfg.dataset.type.lower() == \"blender\":\n            images, poses, render_poses, hwf, i_split, expressions, _, bboxs = load_flame_data(\n                cfg.dataset.basedir,\n                half_res=cfg.dataset.half_res,\n                testskip=cfg.dataset.testskip,\n            )\n            i_train, i_val, i_test = i_split\n            H, W, focal = hwf\n            H, W = int(H), int(W)\n            hwf = [H, W, focal]\n            if cfg.nerf.train.white_background:\n                images = images[..., :3] * images[..., -1:] + (1.0 - images[..., -1:])\n    print(\"done loading data\")\n    # Seed experiment for repeatability\n    seed = cfg.experiment.randomseed\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n\n    # Device on which to run.\n    if torch.cuda.is_available():\n        device = \"cuda\" #+ \":\" + str(cfg.experiment.device)\n    else:\n        device = \"cpu\"\n\n    encode_position_fn = get_embedding_function(\n        num_encoding_functions=cfg.models.coarse.num_encoding_fn_xyz,\n        include_input=cfg.models.coarse.include_input_xyz,\n        log_sampling=cfg.models.coarse.log_sampling_xyz,\n    )\n\n    encode_direction_fn = None\n    if cfg.models.coarse.use_viewdirs:\n        encode_direction_fn = get_embedding_function(\n            num_encoding_functions=cfg.models.coarse.num_encoding_fn_dir,\n            include_input=cfg.models.coarse.include_input_dir,\n            log_sampling=cfg.models.coarse.log_sampling_dir,\n        )\n\n    # Initialize a coarse-resolution model.\n    model_coarse = getattr(models, cfg.models.coarse.type)(\n        num_encoding_fn_xyz=cfg.models.coarse.num_encoding_fn_xyz,\n        num_encoding_fn_dir=cfg.models.coarse.num_encoding_fn_dir,\n        include_input_xyz=cfg.models.coarse.include_input_xyz,\n        include_input_dir=cfg.models.coarse.include_input_dir,\n        use_viewdirs=cfg.models.coarse.use_viewdirs,\n        num_layers=cfg.models.coarse.num_layers,\n        hidden_size=cfg.models.coarse.hidden_size,\n        include_expression=True\n    )\n    model_coarse.to(device)\n    # If a fine-resolution model is specified, initialize it.\n    model_fine = None\n    if hasattr(cfg.models, \"fine\"):\n        model_fine = getattr(models, cfg.models.fine.type)(\n            num_encoding_fn_xyz=cfg.models.fine.num_encoding_fn_xyz,\n            num_encoding_fn_dir=cfg.models.fine.num_encoding_fn_dir,\n            include_input_xyz=cfg.models.fine.include_input_xyz,\n            include_input_dir=cfg.models.fine.include_input_dir,\n            use_viewdirs=cfg.models.fine.use_viewdirs,\n            num_layers = cfg.models.coarse.num_layers,\n            hidden_size =cfg.models.coarse.hidden_size,\n            include_expression=True\n        )\n        model_fine.to(device)\n\n    ###################################\n    ###################################\n    train_background = False\n    supervised_train_background = False\n    blur_background = False\n\n    train_latent_codes = True\n    disable_expressions = False # True to disable expressions\n    disable_latent_codes = False # True to disable latent codes\n    fixed_background = True # Do False to disable BG\n    regularize_latent_codes = True # True to add latent code LOSS, false for most experiments\n    ###################################\n    ###################################\n\n    supervised_train_background = train_background and supervised_train_background\n    # Avg background\n    #images[i_train]\n    if train_background:\n        with torch.no_grad():\n            avg_img = torch.mean(images[i_train],axis=0)\n            # Blur Background:\n            if blur_background:\n                avg_img = avg_img.permute(2,0,1)\n                avg_img = avg_img.unsqueeze(0)\n                smoother = GaussianSmoothing(channels=3, kernel_size=11, sigma=11)\n                print(\"smoothed background initialization. shape \", avg_img.shape)\n                avg_img = smoother(avg_img).squeeze(0).permute(1,2,0)\n            #avg_img = torch.zeros(H,W,3)\n            #avg_img = torch.rand(H,W,3)\n            #avg_img = 0.5*(torch.rand(H,W,3) + torch.mean(images[i_train],axis=0))\n            background = torch.tensor(avg_img, device=device)\n        background.requires_grad = True\n\n    if fixed_background: # load GT background\n        print(\"loading GT background to condition on\")\n        from PIL import Image\n        background = Image.open(os.path.join(cfg.dataset.basedir,'bg','00050.png'))\n        background.thumbnail((H,W))\n        background = torch.from_numpy(np.array(background).astype(np.float32)).to(device)\n        background = background/255\n        print(\"bg shape\", background.shape)\n        print(\"should be \", images[i_train][0].shape)\n        assert background.shape == images[i_train][0].shape\n    else:\n        background = None\n\n    # Initialize optimizer.\n    trainable_parameters = list(model_coarse.parameters())\n    if model_fine is not None:\n        trainable_parameters += list(model_fine.parameters())\n    if train_background:\n        #background.requires_grad = True\n        #trainable_parameters.append(background) # add it later when init optimizer for different lr\n        print(\"background.is_leaf \" ,background.is_leaf, background.device)\n\n    if train_latent_codes:\n        latent_codes = torch.zeros(len(i_train),32, device=device)\n        print(\"initialized latent codes with shape %d X %d\" % (latent_codes.shape[0], latent_codes.shape[1]))\n        if not disable_latent_codes:\n            trainable_parameters.append(latent_codes)\n            latent_codes.requires_grad = True\n\n    if train_background:\n        optimizer = getattr(torch.optim, cfg.optimizer.type)(\n            [{'params':trainable_parameters},\n             {'params':background, 'lr':cfg.optimizer.lr}],\n            lr=cfg.optimizer.lr\n        )\n    else:\n        optimizer = getattr(torch.optim, cfg.optimizer.type)(\n            [{'params':trainable_parameters},\n             {'params': background, 'lr': cfg.optimizer.lr}        ], # this is obsolete but need for continuing training\n            lr=cfg.optimizer.lr\n        )\n    # Setup logging.\n    logdir = os.path.join(cfg.experiment.logdir, cfg.experiment.id)\n    os.makedirs(logdir, exist_ok=True)\n    writer = SummaryWriter(logdir)\n    # Write out config parameters.\n    with open(os.path.join(logdir, \"config.yml\"), \"w\") as f:\n        f.write(cfg.dump())  # cfg, f, default_flow_style=False)\n\n    # By default, start at iteration 0 (unless a checkpoint is specified).\n    start_iter = 0\n\n    # Load an existing checkpoint, if a path is specified.\n    if os.path.exists(configargs.load_checkpoint):\n        checkpoint = torch.load(configargs.load_checkpoint)\n        model_coarse.load_state_dict(checkpoint[\"model_coarse_state_dict\"])\n        if checkpoint[\"model_fine_state_dict\"]:\n            model_fine.load_state_dict(checkpoint[\"model_fine_state_dict\"])\n        if checkpoint[\"background\"] is not None:\n            print(\"loaded bg from checkpoint\")\n            background = torch.nn.Parameter(checkpoint['background'].to(device))\n        if checkpoint[\"latent_codes\"] is not None:\n            print(\"loaded latent codes from checkpoint\")\n            latent_codes = torch.nn.Parameter(checkpoint['latent_codes'].to(device))\n\n        optimizer.load_state_dict(checkpoint[\"optimizer_state_dict\"])\n        start_iter = checkpoint[\"iter\"]\n\n    # # TODO: Prepare raybatch tensor if batching random rays\n\n    # Prepare importance sampling maps\n    ray_importance_sampling_maps = []\n    p = 0.9\n    print(\"computing boundix boxes probability maps\")\n    for i in i_train:\n        bbox = bboxs[i]\n        probs = np.zeros((H,W))\n        probs.fill(1-p)\n        probs[bbox[0]:bbox[1],bbox[2]:bbox[3]] = p\n        probs = (1/probs.sum()) * probs\n        ray_importance_sampling_maps.append(probs.reshape(-1))\n\n\n    print(\"Starting loop\")\n    for i in trange(start_iter, cfg.experiment.train_iters):\n\n        model_coarse.train()\n        if model_fine:\n            model_coarse.train()\n\n        rgb_coarse, rgb_fine = None, None\n        target_ray_values = None\n        background_ray_values = None\n        if USE_CACHED_DATASET:\n            datafile = np.random.choice(train_paths)\n            cache_dict = torch.load(datafile)\n            ray_bundle = cache_dict[\"ray_bundle\"].to(device)\n            ray_origins, ray_directions = (\n                ray_bundle[0].reshape((-1, 3)),\n                ray_bundle[1].reshape((-1, 3)),\n            )\n            target_ray_values = cache_dict[\"target\"][..., :3].reshape((-1, 3))\n            select_inds = np.random.choice(\n                ray_origins.shape[0],\n                size=(cfg.nerf.train.num_random_rays),\n                replace=False,\n            )\n            ray_origins, ray_directions = (\n                ray_origins[select_inds],\n                ray_directions[select_inds],\n            )\n            target_ray_values = target_ray_values[select_inds].to(device)\n            #target_ray_values = target_ray_values[select_inds].to(device)\n            # ray_bundle = torch.stack([ray_origins, ray_directions], dim=0).to(device)\n\n            rgb_coarse, _, _, rgb_fine, _, _ = run_one_iter_of_nerf(\n                cache_dict[\"height\"],\n                cache_dict[\"width\"],\n                cache_dict[\"focal_length\"],\n                model_coarse,\n                model_fine,\n                ray_origins,\n                ray_directions,\n                cfg,\n                mode=\"train\",\n                encode_position_fn=encode_position_fn,\n                encode_direction_fn=encode_direction_fn,\n                expressions=expressions\n            )\n        else:\n            img_idx = np.random.choice(i_train)\n            img_target = images[img_idx].to(device)\n            pose_target = poses[img_idx, :3, :4].to(device)\n            if not disable_expressions:\n                expression_target = expressions[img_idx].to(device) # vector\n            else: # zero expr\n                expression_target = torch.zeros(76, device=device)\n            #bbox = bboxs[img_idx]\n            if not disable_latent_codes:\n                latent_code = latent_codes[img_idx].to(device) if train_latent_codes else None\n            else:\n                latent_codes = torch.zeros(32, device=device)\n            #latent_code = torch.zeros(32).to(device)\n            ray_origins, ray_directions = get_ray_bundle(H, W, focal, pose_target)\n            coords = torch.stack(\n                meshgrid_xy(torch.arange(H).to(device), torch.arange(W).to(device)),\n                dim=-1,\n            )\n\n            # Only randomly choose rays that are in the bounding box !\n            # coords = torch.stack(\n            #     meshgrid_xy(torch.arange(bbox[0],bbox[1]).to(device), torch.arange(bbox[2],bbox[3]).to(device)),\n            #     dim=-1,\n            # )\n\n            coords = coords.reshape((-1, 2))\n            # select_inds = np.random.choice(\n            #     coords.shape[0], size=(cfg.nerf.train.num_random_rays), replace=False\n            # )\n\n            # Use importance sampling to sample mainly in the bbox with prob p\n            select_inds = np.random.choice(\n                coords.shape[0], size=(cfg.nerf.train.num_random_rays), replace=False, p=ray_importance_sampling_maps[img_idx]\n            )\n\n            select_inds = coords[select_inds]\n            ray_origins = ray_origins[select_inds[:, 0], select_inds[:, 1], :]\n            ray_directions = ray_directions[select_inds[:, 0], select_inds[:, 1], :]\n            #dump_rays(ray_origins, ray_directions)\n\n            # batch_rays = torch.stack([ray_origins, ray_directions], dim=0)\n            target_s = img_target[select_inds[:, 0], select_inds[:, 1], :]\n            background_ray_values = background[select_inds[:, 0], select_inds[:, 1], :] if (train_background or fixed_background) else None\n            #if i<10000:\n            #   background_ray_values = None\n            #background_ray_values = None\n            then = time.time()\n            rgb_coarse, _, _, rgb_fine, _, _, weights = run_one_iter_of_nerf(\n                H,\n                W,\n                focal,\n                model_coarse,\n                model_fine,\n                ray_origins,\n                ray_directions,\n                cfg,\n                mode=\"train\",\n                encode_position_fn=encode_position_fn,\n                encode_direction_fn=encode_direction_fn,\n                expressions = expression_target,\n                background_prior=background_ray_values,\n                latent_code = latent_code if not disable_latent_codes else torch.zeros(32,device=device)\n\n            )\n            target_ray_values = target_s\n\n        coarse_loss = torch.nn.functional.mse_loss(\n            rgb_coarse[..., :3], target_ray_values[..., :3]\n        )\n        fine_loss = None\n        if rgb_fine is not None:\n            fine_loss = torch.nn.functional.mse_loss(\n                rgb_fine[..., :3], target_ray_values[..., :3]\n            )\n        # loss = torch.nn.functional.mse_loss(rgb_pred[..., :3], target_s[..., :3])\n        loss = 0.0\n        # if fine_loss is not None:\n        #     loss = fine_loss\n        # else:\n        #     loss = coarse_loss\n\n        latent_code_loss = torch.zeros(1, device=device)\n        if train_latent_codes and not disable_latent_codes:\n            latent_code_loss = torch.norm(latent_code) * 0.0005\n            #latent_code_loss = torch.zeros(1)\n\n        background_loss = torch.zeros(1, device=device)\n        if supervised_train_background:\n            background_loss = torch.nn.functional.mse_loss(\n                background_ray_values[..., :3], target_ray_values[..., :3], reduction='none'\n            ).sum(1)\n            background_loss = torch.mean(background_loss*weights) * 0.001\n\n        loss = coarse_loss + (fine_loss if fine_loss is not None else 0.0)\n        psnr = mse2psnr(loss.item())\n\n        #loss_total = loss #+ (latent_code_loss if latent_code_loss is not None else 0.0)\n        loss = loss + (latent_code_loss*10 if regularize_latent_codes else 0.0)\n        loss_total = loss + (background_loss if supervised_train_background is not None else 0.0)\n        #loss.backward()\n        loss_total.backward()\n        #psnr = mse2psnr(loss.item())\n        optimizer.step()\n        optimizer.zero_grad()\n\n        # Learning rate updates\n        num_decay_steps = cfg.scheduler.lr_decay * 1000\n        lr_new = cfg.optimizer.lr * (\n            cfg.scheduler.lr_decay_factor ** (i / num_decay_steps)\n        )\n        for param_group in optimizer.param_groups:\n            param_group[\"lr\"] = lr_new\n\n        if i % cfg.experiment.print_every == 0 or i == cfg.experiment.train_iters - 1:\n            tqdm.write(\n                \"[TRAIN] Iter: \"\n                + str(i)\n                + \" Loss: \"\n                + str(loss.item())\n                + \" BG Loss: \"\n                + str(background_loss.item())\n                + \" PSNR: \"\n                + str(psnr)\n                + \" LatentReg: \"\n                + str(latent_code_loss.item())\n            )\n        #writer.add_scalar(\"train/loss\", loss.item(), i)\n        if train_latent_codes:\n            writer.add_scalar(\"train/code_loss\", latent_code_loss.item(), i)\n        if supervised_train_background:\n            writer.add_scalar(\"train/bg_loss\", background_loss.item(), i)\n\n        writer.add_scalar(\"train/coarse_loss\", coarse_loss.item(), i)\n        if rgb_fine is not None:\n            writer.add_scalar(\"train/fine_loss\", fine_loss.item(), i)\n        writer.add_scalar(\"train/psnr\", psnr, i)\n\n        # Validation\n        if (\n            i % cfg.experiment.validate_every == 0\n            or i == cfg.experiment.train_iters - 1 and False\n        ):\n            #torch.cuda.empty_cache()\n            tqdm.write(\"[VAL] =======> Iter: \" + str(i))\n            model_coarse.eval()\n            if model_fine:\n                model_coarse.eval()\n\n            start = time.time()\n            with torch.no_grad():\n                rgb_coarse, rgb_fine = None, None\n                target_ray_values = None\n                if USE_CACHED_DATASET:\n                    datafile = np.random.choice(validation_paths)\n                    cache_dict = torch.load(datafile)\n                    rgb_coarse, _, _, rgb_fine, _, weights = run_one_iter_of_nerf(\n                        cache_dict[\"height\"],\n                        cache_dict[\"width\"],\n                        cache_dict[\"focal_length\"],\n                        model_coarse,\n                        model_fine,\n                        cache_dict[\"ray_origins\"].to(device),\n                        cache_dict[\"ray_directions\"].to(device),\n                        cfg,\n                        mode=\"validation\",\n                        encode_position_fn=encode_position_fn,\n                        encode_direction_fn=encode_direction_fn,\n                        expressions = expression_target,\n                        latent_code = torch.zeros(32, device=device)\n                    )\n                    target_ray_values = cache_dict[\"target\"].to(device)\n                else:\n                    # Do all validation set...\n                    loss = 0\n                    for img_idx in i_val[:2]:\n                        img_target = images[img_idx].to(device)\n                        #tqdm.set_description('val im %d' % img_idx)\n                        #tqdm.refresh()  # to show immediately the update\n\n                            # # save val image for debug ### DEBUG ####\n                        # #GT = target_ray_values[..., :3]\n                        # import PIL.Image\n                        # #img = GT.permute(2, 0, 1)\n                        # # Conver to PIL Image and then np.array (output shape: (H, W, 3))\n                        # #im_numpy = img_target.detach().cpu().numpy()\n                        # #im_numpy = np.array(torchvision.transforms.ToPILImage()(img_target.detach().cpu()))\n                        #\n                        # #                   im = PIL.Image.fromarray(im_numpy)\n                        # im = img_target\n                        # im = im.permute(2, 0, 1)\n                        # img = np.array(torchvision.transforms.ToPILImage()(im.detach().cpu()))\n                        # im = PIL.Image.fromarray(img)\n                        # im.save('val_im_target_debug.png')\n                        # ### DEBUG #### END\n\n                        pose_target = poses[img_idx, :3, :4].to(device)\n                        ray_origins, ray_directions = get_ray_bundle(\n                            H, W, focal, pose_target\n                        )\n                        rgb_coarse, _, _, rgb_fine, _, _ ,weights= run_one_iter_of_nerf(\n                            H,\n                            W,\n                            focal,\n                            model_coarse,\n                            model_fine,\n                            ray_origins,\n                            ray_directions,\n                            cfg,\n                            mode=\"validation\",\n                            encode_position_fn=encode_position_fn,\n                            encode_direction_fn=encode_direction_fn,\n                            expressions = expression_target,\n                            background_prior = background.view(-1,3) if (train_background or fixed_background) else None,\n                            latent_code = torch.zeros(32).to(device) if train_latent_codes or disable_latent_codes else None,\n\n                        )\n                        #print(\"did one val\")\n                        target_ray_values = img_target\n                        coarse_loss = img2mse(rgb_coarse[..., :3], target_ray_values[..., :3])\n                        curr_loss, curr_fine_loss = 0.0, 0.0\n                        if rgb_fine is not None:\n                            curr_fine_loss = img2mse(rgb_fine[..., :3], target_ray_values[..., :3])\n                            curr_loss = curr_fine_loss\n                        else:\n                            curr_loss = coarse_loss\n                        loss += curr_loss + curr_fine_loss\n\n                loss /= len(i_val)\n                psnr = mse2psnr(loss.item())\n                writer.add_scalar(\"validation/loss\", loss.item(), i)\n                writer.add_scalar(\"validation/coarse_loss\", coarse_loss.item(), i)\n                writer.add_scalar(\"validation/psnr\", psnr, i)\n                writer.add_image(\n                    \"validation/rgb_coarse\", cast_to_image(rgb_coarse[..., :3]), i\n                )\n                if rgb_fine is not None:\n                    writer.add_image(\n                        \"validation/rgb_fine\", cast_to_image(rgb_fine[..., :3]), i\n                    )\n                    writer.add_scalar(\"validation/fine_loss\", fine_loss.item(), i)\n\n                writer.add_image(\n                    \"validation/img_target\",\n                    cast_to_image(target_ray_values[..., :3]),\n                    i,\n                )\n                if train_background or fixed_background:\n                    writer.add_image(\n                        \"validation/background\", cast_to_image(background[..., :3]), i\n                    )\n                    writer.add_image(\n                        \"validation/weights\", (weights.detach().cpu().numpy()), i, dataformats='HW'\n                    )\n                tqdm.write(\n                    \"Validation loss: \"\n                    + str(loss.item())\n                    + \" Validation PSNR: \"\n                    + str(psnr)\n                    + \" Time: \"\n                    + str(time.time() - start)\n                )\n\n        #gpu_profile(frame=sys._getframe(), event='line', arg=None)\n\n\n        if i % cfg.experiment.save_every == 0 or i == cfg.experiment.train_iters - 1:\n            checkpoint_dict = {\n                \"iter\": i,\n                \"model_coarse_state_dict\": model_coarse.state_dict(),\n                \"model_fine_state_dict\": None\n                if not model_fine\n                else model_fine.state_dict(),\n                \"optimizer_state_dict\": optimizer.state_dict(),\n                \"loss\": loss,\n                \"psnr\": psnr,\n                \"background\": None\n                if not (train_background or fixed_background)\n                else background.data,\n                \"latent_codes\": None if not train_latent_codes else latent_codes.data\n            }\n            torch.save(\n                checkpoint_dict,\n                os.path.join(logdir, \"checkpoint\" + str(i).zfill(5) + \".ckpt\"),\n            )\n            tqdm.write(\"================== Saved Checkpoint =================\")\n\n    print(\"Done!\")\n\n\ndef cast_to_image(tensor):\n    # Input tensor is (H, W, 3). Convert to (3, H, W).\n    tensor = tensor.permute(2, 0, 1)\n    tensor = tensor.clamp(0.0,1.0)\n    # Conver to PIL Image and then np.array (output shape: (H, W, 3))\n    img = np.array(torchvision.transforms.ToPILImage()(tensor.detach().cpu()))\n    # Map back to shape (3, H, W), as tensorboard needs channels first.\n    img = np.moveaxis(img, [-1], [0])\n    return img\n\n\ndef handle_pdb(sig, frame):\n    import pdb\n    pdb.Pdb().set_trace(frame)\n\n\nif __name__ == \"__main__\":\n    import signal\n\n    print(\"before signal registration\")\n    signal.signal(signal.SIGUSR1, handle_pdb)\n    print(\"after registration\")\n    #sys.settrace(gpu_profile)\n\n    main()\n\n\"\"\"\n# Validation\n        if (\n            i % cfg.experiment.validate_every == 0\n            or i == cfg.experiment.train_iters - 1\n        ):\n            tqdm.write(\"[VAL] =======> Iter: \" + str(i))\n            model_coarse.eval()\n            if model_fine:\n                model_coarse.eval()\n\n            start = time.time()\n            with torch.no_grad():\n                rgb_coarse, rgb_fine = None, None\n                target_ray_values = None\n                if USE_CACHED_DATASET:\n                    datafile = np.random.choice(validation_paths)\n                    cache_dict = torch.load(datafile)\n                    rgb_coarse, _, _, rgb_fine, _, _ = run_one_iter_of_nerf(\n                        cache_dict[\"height\"],\n                        cache_dict[\"width\"],\n                        cache_dict[\"focal_length\"],\n                        model_coarse,\n                        model_fine,\n                        cache_dict[\"ray_origins\"].to(device),\n                        cache_dict[\"ray_directions\"].to(device),\n                        cfg,\n                        mode=\"validation\",\n                        encode_position_fn=encode_position_fn,\n                        encode_direction_fn=encode_direction_fn,\n                    )\n                    target_ray_values = cache_dict[\"target\"].to(device)\n                else:\n                    img_idx = np.random.choice(i_val)\n                    img_target = images[img_idx].to(device)\n\n                    # # save val image for debug ### DEBUG ####\n                    # #GT = target_ray_values[..., :3]\n                    # import PIL.Image\n                    # #img = GT.permute(2, 0, 1)\n                    # # Conver to PIL Image and then np.array (output shape: (H, W, 3))\n                    # #im_numpy = img_target.detach().cpu().numpy()\n                    # #im_numpy = np.array(torchvision.transforms.ToPILImage()(img_target.detach().cpu()))\n                    #\n                    # #                   im = PIL.Image.fromarray(im_numpy)\n                    # im = img_target\n                    # im = im.permute(2, 0, 1)\n                    # img = np.array(torchvision.transforms.ToPILImage()(im.detach().cpu()))\n                    # im = PIL.Image.fromarray(img)\n                    # im.save('val_im_target_debug.png')\n                    # ### DEBUG #### END\n\n\n                    pose_target = poses[img_idx, :3, :4].to(device)\n                    ray_origins, ray_directions = get_ray_bundle(\n                        H, W, focal, pose_target\n                    )\n                    rgb_coarse, _, _, rgb_fine, _, _ = run_one_iter_of_nerf(\n                        H,\n                        W,\n                        focal,\n                        model_coarse,\n                        model_fine,\n                        ray_origins,\n                        ray_directions,\n                        cfg,\n                        mode=\"validation\",\n                        encode_position_fn=encode_position_fn,\n                        encode_direction_fn=encode_direction_fn,\n                    )\n                    target_ray_values = img_target\n                coarse_loss = img2mse(rgb_coarse[..., :3], target_ray_values[..., :3])\n                loss, fine_loss = 0.0, 0.0\n                if rgb_fine is not None:\n                    fine_loss = img2mse(rgb_fine[..., :3], target_ray_values[..., :3])\n                    loss = fine_loss\n                else:\n                    loss = coarse_loss\n                loss = coarse_loss + fine_loss\n                psnr = mse2psnr(loss.item())\n                writer.add_scalar(\"validation/loss\", loss.item(), i)\n                writer.add_scalar(\"validation/coarse_loss\", coarse_loss.item(), i)\n                writer.add_scalar(\"validataion/psnr\", psnr, i)\n                writer.add_image(\n                    \"validation/rgb_coarse\", cast_to_image(rgb_coarse[..., :3]), i\n                )\n                if rgb_fine is not None:\n                    writer.add_image(\n                        \"validation/rgb_fine\", cast_to_image(rgb_fine[..., :3]), i\n                    )\n                    writer.add_scalar(\"validation/fine_loss\", fine_loss.item(), i)\n\n                writer.add_image(\n                    \"validation/img_target\",\n                    cast_to_image(target_ray_values[..., :3]),\n                    i,\n                )\n                tqdm.write(\n                    \"Validation loss: \"\n                    + str(loss.item())\n                    + \" Validation PSNR: \"\n                    + str(psnr)\n                    + \" Time: \"\n                    + str(time.time() - start)\n                )\n\"\"\"", "meta": {"hexsha": "5255d0704608d563fe8bfd85b61afcce3709685c", "size": 30007, "ext": "py", "lang": "Python", "max_stars_repo_path": "nerface_code/nerf-pytorch/train_transformed_rays.py", "max_stars_repo_name": "gafniguy/4D-Facial-Avatars", "max_stars_repo_head_hexsha": "406c81ae7a1427a11b4484329544f976c1dd774e", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 335, "max_stars_repo_stars_event_min_datetime": "2020-12-08T05:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:01:40.000Z", "max_issues_repo_path": "nerface_code/nerf-pytorch/train_transformed_rays.py", "max_issues_repo_name": "gafniguy/4D-Facial-Avatars", "max_issues_repo_head_hexsha": "406c81ae7a1427a11b4484329544f976c1dd774e", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2020-12-08T20:59:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T17:29:37.000Z", "max_forks_repo_path": "nerface_code/nerf-pytorch/train_transformed_rays.py", "max_forks_repo_name": "gafniguy/4D-Facial-Avatars", "max_forks_repo_head_hexsha": "406c81ae7a1427a11b4484329544f976c1dd774e", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 34, "max_forks_repo_forks_event_min_datetime": "2020-12-08T16:30:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T20:53:43.000Z", "avg_line_length": 42.3229901269, "max_line_length": 139, "alphanum_fraction": 0.541407005, "include": true, "reason": "import numpy", "num_tokens": 6296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.154879604457065}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n################################################################################\n#\n#   MEASURE - Master Equation Automatic Solver for Unimolecular REactions\n#\n#   Copyright (c) 2010 by Joshua W. Allen (jwallen@mit.edu)\n#\n#   Permission is hereby granted, free of charge, to any person obtaining a\n#   copy of this software and associated documentation files (the 'Software'),\n#   to deal in the Software without restriction, including without limitation\n#   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n#   and/or sell copies of the Software, and to permit persons to whom the\n#   Software is furnished to do so, subject to the following conditions:\n#\n#   The above copyright notice and this permission notice shall be included in\n#   all copies or substantial portions of the Software.\n#\n#   THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n#   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n#   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n#   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n#   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n#   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n#   DEALINGS IN THE SOFTWARE.\n#\n################################################################################\n\n\"\"\"\nContains functions for directly solving the full or reduced master equation\nmatrix to generate concentration profiles and population distributions. This\ninformation is particularly useful in comparing and evaluating the methods for\nreducing the master equation.\n\"\"\"\n\nimport numpy\nimport scipy.integrate\n#from pydas import DASSL\n\nimport rmgpy.constants as constants\n\n################################################################################\n\ndef residual(t, y, K):\n    return numpy.dot(K, y)\n\ndef jacobian(t, y, K):\n    return K\n\n################################################################################\n\ndef solveFullME(T, P, Elist, tlist, x0, M, indices, densStates, Nisom, Nreac, Nprod):\n    \"\"\"\n    Directly solve the full master equation using a stiff ODE solver. Pass the\n    reaction `network` to solve, the temperature `T` in K and pressure `P` in\n    Pa to solve at, the energies `Elist` in J/mol to use, the output time\n    points `tlist` in s, the initial total populations `x0`, the full master\n    equation matrix `M`, the accounting matrix `indices` relating isomer and\n    energy grain indices to indices of the master equation matrix, and the\n    densities of states `densStates` in mol/J of each isomer.\n    Returns the times in s, population distributions for each isomer, and total\n    population profiles for each configuration.\n    \"\"\"\n\n    Ngrains = len(Elist)\n    Ntime = len(tlist)\n\n    # Get equilibrium distributions\n    eqDist = numpy.zeros_like(densStates)\n    for i in range(Nisom):\n        eqDist[i,:] = densStates[i,:] * numpy.exp(-Elist / constants.R / T)\n        eqDist[i,:] /= sum(eqDist[i,:])\n\n    # Set initial conditions\n    p0 = numpy.zeros([M.shape[0]], float)\n    for i in range(Nisom):\n        for r in range(Ngrains):\n            if indices[r,i] > 0:\n                p0[indices[r,i]] = x0[i] * eqDist[i,r]\n    for i in range(Nreac+Nprod):\n        p0[-Nreac-Nprod + i] = x0[i+Nisom]\n\n\n#    # Set up ODEs\n#    me = MasterEquation(M)\n#    me.initialize(t0=0, y0=p0, atol=1e-16, rtol=1e-8)\n#\n#    # Generate solution\n#    t = numpy.zeros([Ntime], float)\n#    p = numpy.zeros([Ntime, Nisom, Ngrains], float)\n#    x = numpy.zeros([Ntime, Nisom+Nreac+Nprod], float)\n#    for s in range(Ntime):\n#        me.advance(tlist[s])\n#        print me.t\n#        t[s] = me.t\n#        for r in range(Ngrains):\n#            for i in range(0, Nisom):\n#                if indices[r,i] > 0:\n#                    p[s,i,r] += me.y[indices[r,i]]\n#                    x[s,i] += me.y[indices[r,i]]\n#        for n in range(Nisom, Nisom+Nreac+Nprod):\n#            x[s,n] = me.y[-(Nisom+Nreac+Nprod)+n]\n\n    # Set up ODEs\n    ode = scipy.integrate.ode(residual, jacobian).set_integrator('vode', method='bdf', with_jacobian=True, atol=1e-16, rtol=1e-8)\n    ode.set_initial_value(p0, 0.0).set_f_params(M).set_jac_params(M)\n\n    # Generate solution\n    t = numpy.zeros([Ntime], float)\n    p = numpy.zeros([Ntime, Nisom, Ngrains], float)\n    x = numpy.zeros([Ntime, Nisom+Nreac+Nprod], float)\n    for s in range(Ntime):\n        ode.integrate(tlist[s])\n        t[s] = ode.t\n        for r in range(Ngrains):\n            for i in range(0, Nisom):\n                if indices[r,i] > 0:\n                    p[s,i,r] += ode.y[indices[r,i]]\n                    x[s,i] += ode.y[indices[r,i]]\n        for n in range(Nisom, Nisom+Nreac+Nprod):\n            x[s,n] = ode.y[-(Nisom+Nreac+Nprod)+n]\n\n    #import pylab\n    #pylab.loglog(t,x)\n    #pylab.show()\n\n    return t, p, x\n\n################################################################################\n\ndef solveReducedME(T, P, Elist, tlist, x0, K, p0, Nisom, Nreac, Nprod):\n    \"\"\"\n    Directly solve a reduced master equation (set of phenomenological rate\n    coefficients) using a stiff ODE solver. Pass the reaction `network` to\n    solve, the temperature `T` in K and pressure `P` in Pa to solve at, the\n    energies `Elist` in J/mol to use, the output time points `tlist` in s,\n    the initial total populations `x0`, the matrix of phenomenological rate\n    coefficients `K`, and the pseudo-steady population distributions `p0`.\n    Returns the times in s, approximate population distributions for each\n    isomer, and total population profiles for each configuration.\n    \"\"\"\n    \n    Ngrains = len(Elist)\n    Ntime = len(tlist)\n\n    # Set up ODEs\n    ode = scipy.integrate.ode(residual, jacobian)\n    ode.set_integrator('vode', method='bdf', with_jacobian=True, atol=1e-16, rtol=1e-8)\n    ode.set_initial_value(x0, 0.0).set_f_params(K).set_jac_params(K)\n\n    # Generate solution\n    t = numpy.zeros([len(tlist)], float)\n    x = numpy.zeros([len(tlist), len(x0)], float)\n    for n in range(Ntime):\n        ode.integrate(tlist[n])\n        t[n] = ode.t\n        x[n,:] = ode.y\n\n    # Construct p from x\n    p = numpy.zeros((len(t),Nisom,Ngrains), numpy.float64)\n    for s in range(Ntime):\n        for i in range(Nisom):\n            for n in range(Nisom):\n                p[s,i,:] += x[s,n] * p0[:,i,n]\n            for n in range(Nisom, Nisom+Nreac):\n                p[s,i,:] += x[s,n] * p0[:,i,n] * (0.21 * P / constants.R / T)\n\n    return t, p, x\n\n#################################################################################\n#\n#class MasterEquation(DASSL):\n#    \"\"\"\n#    \"\"\"\n#\n#    def __init__(self, M):\n#        DASSL.__init__(self)\n#        self.M = M\n#\n#    def residual(self, t, y, dydt):\n#        return numpy.dot(self.M, y) - dydt, 0\n#\n#    def jacobian(self, t, y, dydt, cj):\n#        return self.M - cj * numpy.identity(y.shape[0], numpy.float64)\n", "meta": {"hexsha": "fafd8be714dd1ba5d93187ec4acf4476bcb0e99a", "size": 6972, "ext": "py", "lang": "Python", "max_stars_repo_path": "rmgpy/measure/simulate.py", "max_stars_repo_name": "enochd/RMG-Py", "max_stars_repo_head_hexsha": "9d2529352ddc04b99cb37ad1cbe1405e47f6da40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rmgpy/measure/simulate.py", "max_issues_repo_name": "enochd/RMG-Py", "max_issues_repo_head_hexsha": "9d2529352ddc04b99cb37ad1cbe1405e47f6da40", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rmgpy/measure/simulate.py", "max_forks_repo_name": "enochd/RMG-Py", "max_forks_repo_head_hexsha": "9d2529352ddc04b99cb37ad1cbe1405e47f6da40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-19T08:05:21.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-19T08:05:21.000Z", "avg_line_length": 37.4838709677, "max_line_length": 129, "alphanum_fraction": 0.5925129088, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.15487960445706497}}
{"text": "from functools import lru_cache\nimport os\nimport glob\nimport copy\nfrom itertools import product\n\nimport numpy as np\nfrom scipy.ndimage import map_coordinates\nfrom scipy.interpolate import interp1d,RegularGridInterpolator,\\\n                                UnivariateSpline\nimport astropy.units as u\nfrom astropy.io import fits\nfrom astropy.table import Table\n\nfrom . import convolve\nfrom . import fitting\nfrom . import photometry\nfrom . import spectrum\nfrom . import filter\nfrom . import utils\nfrom . import config as cfg\n\nclass Model(object):\n    \"\"\"Basic model class.\n        \n    PhotModel and SpecModel are derived from this, the only real\n    difference is that the former has convolved flux data for an array\n    of filters, and the latter has flux data for an array of\n    wavelengths.\n    \n    Many of the methods and functions required are similar for both, so\n    are contained in the base class with checking to ensure the right\n    thing is done. \"\"\"\n    \n    \n    @lru_cache(maxsize=8)\n    def read_file(file):\n        \"\"\"Read a model file.\"\"\"\n\n        # parameter names\n        fh = fits.open(file)\n        keywords = fh[0].header\n        nparam = keywords['NPARAM']\n\n        # see what type of model we have\n        type = keywords['SDFTYPE']\n        if type == 'PhotModel':\n        \n            self = PhotModel()\n            # get the filter names\n            dat = fh[2].data\n            fs = np.array(dat,dtype=str)\n            for i in range(len(fs)):\n                fs[i] = fs[i].strip()\n            self.filters = np.array(fs)\n            \n        elif type == 'SpecModel':\n        \n            self = SpecModel()\n            # get the wavelengths\n            dat = fh[2].data\n            self.wavelength = np.array(dat,dtype=dat.dtype[0])\n        \n        else:\n            raise utils.SdfError(\"file {} not a PhotModel or SpecModel,\\\n                           is a {}\".format(file,type))\n\n        self.name = keywords['NAME']\n        self.parameters = [keywords['PARAM'+str(i)] for i in range(nparam)]\n\n        # parameter ranges, assume that all values have the same dtype\n        # so it's OK if the resulting ndarray does\n        d = {}\n        for i,par in enumerate(self.parameters):\n            j = i+3\n            if str.upper(par) != fh[j].name:\n                raise utils.SdfError(\"{}th parameter {} not equal to HDU\\\n                               with name {}\".format(j,par,fh[j].name))\n            dat = fh[j].data\n            d[par] = np.array(dat,dtype=dat.dtype[0])\n        self.param_values = d\n\n        # main array of convolved model fluxes, do this last so the\n        # dimensionality is checked by the setter\n        self.fnujy_sr = fh[1].data\n        header1 = fh[1].header\n        if header1['BUNIT'] != (u.jansky/u.sr).to_string(format='fits'):\n            fnuunit = header1['BUNIT']\n            self.fnujy_sr = self.fnujy_sr * u.Unit(fnuunit).to('Jy / sr')\n\n        # integer indices of filters/wavelengths\n        if type == 'PhotModel':\n            self.i = np.arange(len(self.filters))\n        elif type == 'SpecModel':\n            self.i = np.arange(len(self.wavelength))\n        self.n_i = len(self.i)\n\n        # create the hashed version\n        self.fill_log_fnujy_sr_hashed()\n        \n        return self\n\n\n    def write_file(self,file,overwrite=False):\n        \"\"\"Write model to a FITS file.\n        \n        Number of parameters and their names are stored in the primary\n        HDU, flux density cube is in the first HDU, and arrays with the\n        filter names and parameter ranges in subsequent HDUs.\n        \"\"\"\n\n        # primary HDU (for metadata)\n        hdu0 = fits.PrimaryHDU()\n        hdu0.header['NAME'] = self.name\n        hdu0.header['NPARAM'] = len(self.parameters)\n        # keywords for parameters\n        for i,par in enumerate(self.parameters):\n            hdu0.header['PARAM'+str(i)] = par\n\n        # fluxes\n        hdu1 = fits.ImageHDU(self.fnujy_sr, name='MODELS')\n        hdu1.header['BUNIT'] = (u.jansky/u.sr).to_string(format='fits')\n\n        # see what type of model we're writing\n        if isinstance(self,PhotModel):\n        \n            hdu0.header['SDFTYPE'] = 'PhotModel'\n            # filter names\n            t = Table()\n            t.add_column( Table.Column(self.filters,name='FILTERS') )\n            hdu2 = fits.BinTableHDU(np.array(t),name='FILTERS')\n        \n        elif isinstance(self,SpecModel):\n        \n            hdu0.header['SDFTYPE'] = 'SpecModel'\n            # Wavelengths\n            t = Table()\n            t.add_column( Table.Column(self.wavelength,name='WAVLNTHS') )\n            hdu2 = fits.BinTableHDU(np.array(t),name='WAVLNTHS')\n        \n        # parameter ranges\n        hdup = []\n        for par in self.parameters:\n            t = Table()\n            t.add_column( Table.Column(self.param_values[par],\n                                       name=str.upper(par)) )\n            hdup.append( fits.BinTableHDU(np.array(t),name=str.upper(par)) )\n\n        hdus = [hdu0,hdu1,hdu2]\n        hdus.extend(hdup)\n        hdulist = fits.HDUList(hdus)\n        hdulist.writeto(file, overwrite=overwrite)\n    \n\n    def fill_log_fnujy_sr_hashed(self):\n        \"\"\"Get a hashed copy of log10 fnujy_sr.\"\"\"\n\n        # log10 just the positive values, others have tiny value\n        # using the out keyword avoids a bug in numpy 1.13.0\n        pos = self.fnujy_sr > 0.0\n        tmp = np.log10(self.fnujy_sr,where=pos,\n                       out=np.zeros(self.fnujy_sr.shape)+np.log10(cfg.tiny))\n\n        self.log_fnujy_sr_hashed = utils.hashable(tmp)\n\n\n    def rginterpolator(self):\n        \"\"\"Return a regular grid interpolator.\n            \n        Memoizing doesn't appear to save any time.\n        \n        This was the chunk of code in fnujy below:\n        \n        # scipy.RegularGridInterpolator, save a bit of time since the\n        # interpolator object is the same for each model. first we\n        # create grid points we want, each row is just the different\n        # filter numbers assigned above with the parameters appended\n#        pargrid = np.tile(par,len(wave_arr)).reshape((len(wave_arr),len(par)))\n#        pargrid = np.insert(pargrid,0,wave_arr,axis=1)\n#        f = self.rginterpolator()\n#        fluxes = f(pargrid)\n\n        \"\"\"\n    \n        if isinstance(self,PhotModel):\n            wave_arr = np.arange(len(self.filters))\n        elif isinstance(self,SpecModel):\n            wave_arr = np.arange(len(self.wavelength))\n \n        points = (wave_arr,)\n        for param in self.parameters:\n            points += (self.param_values[param],)\n        \n        f = RegularGridInterpolator(points,self.fnujy_sr,\n                                    bounds_error=False,fill_value=np.inf)\n        return f\n    \n    \n    def fnujy(self,param):\n        \"\"\"Return fluxes for a model with a specific solid angle\n\n        Parameter in addition to those specificed for the model is the\n        log10 of the area in steradian in units of Solar radii at 1pc,\n        appended.\n        \n        This is spline interpolation. This doesn't matter too much since\n        any high dynamic range parameters are already log spaced.\n\n        .. todo:: this is the core of the sdf code in terms of execution\n        time. Experiments so far find that map_coordinates is faster\n        than RegularGridInterpolator, but is hindered somewhat by the\n        need to do interpolation first to find the grid points needed by\n        map_coordinates. np.interp seems to be faster than scipy\n        UnivariateSpline or simple 1pt interpolation for this step.\n            \n        \"\"\"\n\n        # prepend this to the interpolation to return the results at all\n        # filters/wavelengths\n        wave_arr = self.i\n        nwav = self.n_i\n\n        # make sure par is a numpy array\n        par_len = len(param)-1\n\n        area_sr = cfg.ssr * 10**( param[-1] )\n        par = param[:par_len]\n\n        # scipy.ndimage.map_coordinates, only real difference compared\n        # to RegularGridInerpolator is that the coordinates are given\n        # in pixels, so must be interpolated from the parameters first\n        # using a homegrown 1pt interpolation linterp was no faster than\n        # np.interp\n        coords = []\n        for i,p in enumerate(self.parameters):\n            coords.append( np.interp( par[i],self.param_values[p],\n                                      np.arange(len(self.param_values[p])) ) )\n\n        pargrid = np.tile(np.array(coords),nwav).\\\n                          reshape( (nwav,par_len) )\n        pargrid = np.insert(pargrid,0,wave_arr,axis=1)\n\n        # interpolation, sped up by doing spline_filter first and\n        # memoizing the result, order must be the same in both calls\n        ff = utils.spline_filter_mem(self.log_fnujy_sr_hashed,order=2)\n        fluxes = map_coordinates(ff,pargrid.T,order=2,prefilter=False)\n        # convert back to real fluxes\n        fluxes = 10**fluxes\n\n        # hack to avoid negative fluxes arising from ringing\n        fluxes[fluxes<cfg.tiny] = cfg.tiny\n\n        # per-filter normalisation for photometry (leave colours)\n        if isinstance(self,PhotModel):\n            filt = filter.iscolour(tuple(self.filters.tolist()))\n            norm = np.zeros(len(self.filters)) + area_sr\n            if np.any(filt):\n                norm[filt] = 1.0\n        else:\n            norm = area_sr\n\n        return norm * fluxes\n    \n\n    def copy(self):\n        \"\"\"Return a copy\"\"\"\n        \n        return copy.deepcopy(self)\n    \n    \n    def param_shape(self):\n        \"\"\"Get the shape of the parameter values\"\"\"\n        \n        dim = ()\n        for param in self.parameters:\n            dim += ( len(self.param_values[param]), )\n        return dim\n\n    \n    @property\n    def name(self):\n        return self._name\n    @name.setter\n    def name(self,value):\n        self._name = utils.validate_string(value)\n\n    @property\n    def parameters(self):\n        return self._parameters\n    @parameters.setter\n    def parameters(self,value):\n        self._parameters = utils.validate_1d(value,None,dtype=str)\n    \n    @property\n    def param_values(self):\n        return self._param_values\n    @param_values.setter\n    def param_values(self,value):\n        self._param_values = utils.validate_dict(value)\n\n    @property\n    def filters(self):\n        return self._filters\n    @filters.setter\n    def filters(self,value):\n        self._filters = utils.validate_1d(value,None,dtype=str)\n\n    @property\n    def wavelength(self):\n        return self._wavelength\n    @wavelength.setter\n    def wavelength(self,value):\n        self._wavelength = utils.validate_1d(value,None)\n    \n    @property\n    def fnujy_sr(self):\n        return self._fnujy_sr\n    @fnujy_sr.setter\n    def fnujy_sr(self,value):\n        if self.parameters is None:\n            expected_dim = None\n        else:\n            expected_dim = len(self.parameters) + 1 # extra for area_sr\n        value = utils.validate_nd(value,expected_dim)\n        if self.param_values is not None:\n            if isinstance(self,PhotModel):\n                if value.shape[0] != len(self.filters):\n                    raise utils.SdfError(\"expected {} elements in first dim,got {}\".\n                                   format(len(self.filters),value.shape[0]))\n            elif isinstance(self,SpecModel):\n                if value.shape[0] != len(self.wavelength):\n                    raise utils.SdfError(\"expected {} elements in first dim, got {}\".\n                                   format(len(self.wavelength),value.shape[0]))\n            for i,key in enumerate(self.parameters):\n                if len(self.param_values[key]) != value.shape[i+1]:\n                    raise utils.SdfError(\"expected dimension {} to have size {}\\\n                                    but got {}\".format(i,\n                                                len(self.param_values[key]),\n                                                value.shape[i+1]))\n        self._fnujy_sr = value\n\n\nclass PhotModel(Model):\n    \"\"\"Class to hold model grids with convolved fluxes\n    \n    The main array is a cube with n+1 dimensions, where n is the number\n    of parameters for a given model, found in the ConvolvedModel class.\n    The dimensions are [nf,p1,p2,...,pn], where px is a parameter range\n    and nf is the number of filters.\n    \n    Colour_bases provides info where a filter is a colour/index, in the\n    form of an array of dicts, each of which holds an array for the\n    *relative* indices (i.e. i_filter - i_colour) locating the base\n    filters for that colour, and an array of their additive weights\n    (when in mags). This info is not stored for now, but populated when\n    the PhotModel is read in. \"\"\"\n\n\n    def __init__(self,name=None,parameters=None,param_values=None,\n             filters=None,colour_bases=None,fnujy_sr=None):\n        self.name = name\n        self.parameters = parameters\n        self.param_values = param_values\n        self.filters = filters\n        self.colour_bases = colour_bases\n        self.fnujy_sr = fnujy_sr\n\n\n    def write_model(self,name,overwrite=False):\n        \"\"\"Write PhotModel as a FITS file.\n            \n        The location to write to is given by config. Directory is \n        created if it doesn't exist.\n        \n        Parameters\n        ----------\n        name : str\n            The name of the model to write, this dictates location and\n            name of the file as [name]_PhotModel.fits.\n        overwrite : bool, optional\n            Force overwrite of extant file.\n        \"\"\"\n        \n        dir = cfg.file['model_root']+'/'+name+'/'\n        if not os.path.exists(dir):\n            os.mkdir(dir)\n        \n        self.write_file(dir+name+'_PhotModel.fits',overwrite=overwrite)\n\n        \n    def read_model(name):\n        \"\"\"Read a named model, location given in config\"\"\"\n        \n        self = Model.read_file(cfg.model_loc[name]+name+'_PhotModel.fits')\n        self.fill_colour_bases()\n        return self\n    \n    \n    @classmethod\n    def cmlist2model(cls,cm):\n        \"\"\"Turn a list of ConvolvedModel objects into a Model\n            \"\"\"\n        \n        self = cls()\n        \n        # check for consistency as we go\n        self.name = cm[0].name\n        self.parameters = cm[0].parameters\n        self.param_values = cm[0].param_values\n        filters = np.array([])\n        \n        cubedim = np.append( len(cm), cm[0].param_shape() )\n        cube = np.ndarray( cubedim, dtype=float )\n        for i in range(len(cm)):\n            filters = np.append(filters,cm[i].filter)\n            if not self.name == cm[i].name:\n                raise utils.SdfError(\"name {} in {} not the same as {} in {}\".\n                               format(cm[i].name,files[i],self.name,files[0]))\n            if not np.all(self.parameters == cm[i].parameters):\n                raise utils.SdfError(\"parameters {} in {} not the same as {} in {}\".\n                               format(cm[i].parameters,\n                                      files[i],self.parameters,files[0]))\n            for param in cm[i].parameters:\n                if not np.all( np.equal(self.param_values[param],\n                                        cm[i].param_values[param]) ):\n                    raise utils.SdfError(\"parameter {} values {} in {}\\\n                                   not the same as {} in {}\".\n                                   format(param,cm[i].param_values[param],\n                                          files[i],self.param_values[param],\n                                          files[0]))\n            cube[i] = cm[i].fnujy_sr\n        \n        self.filters = filters\n        self.fnujy_sr = cube\n        return self\n\n\n    @classmethod\n    def read_convolved_models(cls,name,filters='all'):\n        \"\"\"Load all model files for a given set of filters\n            \"\"\"\n        \n        # full models, avoid reading if they exist\n        models = glob.glob(cfg.model_loc[name]+name+'_*Model.fits')\n        \n        # array of models, one element for each filter\n        files = glob.glob(cfg.model_loc[name]+'*fits')\n        for model in models:\n            if model in files:\n                files.remove(model)\n        cm = [convolve.ConvolvedModel() for i in range(len(files))]\n        for i,f in enumerate(files):\n            cm[i] = convolve.ConvolvedModel.read_file(f)\n        \n        self = PhotModel.cmlist2model(cm)\n        if filters != 'all':\n            self.keep_filters(filters)\n        return self\n\n\n    def fill_colour_bases(self):\n        \"\"\"Fill in colour_bases info.\n\n        Fill an attribute called colour_bases which is a dict pointing\n        to where base filters for colours/indices are. The indices are\n        relative to the colour locations.\n        \n        See Also\n        --------\n        model.PhotModel.keep_filters\n        \"\"\"\n    \n        self.colour_bases = [[] for i in self.filters]\n        for k,f in enumerate(self.filters):\n            if filter.iscolour(f):\n                col = filter.Colour.get(f)\n                filteri = []\n                for i,cf in enumerate(col.filters):\n                    fi = np.where( cf == self.filters )[0][0]\n                    filteri.append( fi - k )\n                self.colour_bases[k] = {'filteri':filteri,\n                                        'filterw':col.weights}\n\n\n    def keep_filters(self,filternames,colour_bases=False):\n        \"\"\"Keep only desired filters from a PhotModel.\n            \n        Parameters\n        ----------\n        filternames : list\n            A list of the filter names to keep from the model. Duplicate\n            filters are kept, as is the order, as each slice in the\n            model must line up with the corresponding one from the\n            Photometry that was read in.\n        \n        colour_bases : bool, optional\n            Keep the base filters that are used to compute\n            colours/indices. These are added to the end of the model,\n            beyond the filters that were asked for.\n            \n        See Also\n        --------\n        model.PhotModel.fill_colour_bases\n        \"\"\"\n        \n        keep = np.array([],dtype=bool)\n        extras = np.array([])\n        for f in filternames:\n            \n            # grab base filters for colours\n            if filter.iscolour(f):\n                col = filter.Colour.get(f)\n                extras = np.append(extras,col.filters)\n            \n            if f in self.filters:\n                fi = np.where(f == self.filters)[0]\n                keep = np.append( keep, fi )\n            else:\n                raise utils.SdfError(\"filter {} not found in PhotModel. \"\n                                     \"This probably means the PhotModel \"\n                                     \"needs to be updated (using \"\n                                     \"model_setup.setup_phot()).\".format(f))\n\n        # now add the base filters\n        if len(extras) > 0 and colour_bases:\n            for f in extras:\n                if f in self.filters:\n                    fi = np.where(f == self.filters)[0]\n                    if fi not in keep:\n                        keep = np.append( keep, fi )\n        \n        self.filters = self.filters[keep]\n        self.fnujy_sr = self.fnujy_sr[keep]\n        if colour_bases:\n            self.fill_colour_bases()\n        else:\n            self.colour_bases = []\n\n        self.i = np.arange(len(self.filters))\n        self.n_i = len(self.i)\n\n        # and update the hashed version\n        self.fill_log_fnujy_sr_hashed()\n            \n\nclass SpecModel(Model):\n    \"\"\"Class to hold grids of model spectra\n        \n    The main array is a cube with n+1 dimensions, where n is the number\n    of parameters for a given model. The dimensions are\n    [nw,p1,p2,...,pn], where px is a parameter range and nw is the\n    number of wavelengths.\n\n    \"\"\"\n    \n    def __init__(self,name=None,parameters=None,param_values=None,\n                 wavelength=None,fnujy_sr=None):\n        self.name = name\n        self.parameters = parameters\n        self.param_values = param_values\n        self.wavelength = wavelength\n        self.fnujy_sr = fnujy_sr\n\n\n    def write_model(self,name,overwrite=False):\n        \"\"\"Write SpecModel as a FITS file.\n            \n        The location to write to is given by config. Directory is \n        created if it doesn't exist.\n        \n        Parameters\n        ----------\n        name : str\n            The name of the model to write, this dictates location and\n            name of the file as [name]_PhotModel.fits.\n        overwrite : bool, optional\n            Force overwrite of extant file.\n        \"\"\"\n        \n        dir = cfg.file['model_root']+'/'+name+'/'\n        if not os.path.exists(dir):\n            os.mkdir(dir)\n        \n        self.write_file(dir+name+'_SpecModel.fits',overwrite=overwrite)\n\n        \n    def read_model(name):\n        \"\"\"Read a named model, location given in config.\"\"\"\n        \n        return Model.read_file(cfg.model_loc[name]+name+'_SpecModel.fits')\n    \n    \n    @classmethod\n    def read_kurucz(cls,file):\n        \"\"\"Read a Kurucz model grid file and return a SpecModel.\n            \n        The model grid will almost certainly not be filled out\n        completely, so require some cropping before it can be used.\n        \n        \"\"\"\n        self = cls()\n        \n        # get the spectra, all have the same wavelength grid\n        m,teff,logg,mh = spectrum.ModelSpectrum.read_kurucz(file)\n        teffarr = np.unique(teff)\n        loggarr = np.unique(logg)\n        \n        self.name = m[0].name\n        self.wavelength = m[0].wavelength\n        self.parameters = ['Teff','logg']\n        self.param_values = {'Teff':teffarr,\n                             'logg':loggarr}\n        \n        # put spectra in their place\n        self.fnujy_sr = np.zeros((len(self.wavelength),\n                                  len(teffarr),\n                                  len(loggarr)),dtype=float)\n        for i,mod in enumerate(m):\n            j = np.where(teff[i] == teffarr)[0][0]\n            k = np.where(logg[i] == loggarr)[0][0]\n            self.fnujy_sr[:,j,k] = mod.fnujy_sr\n        \n        # see if the grid was filled (spectrum.read_kurucz sets any\n        # zero values in the spectra to cfg.tiny)\n        if np.min(self.fnujy_sr) < cfg.tiny:\n            print(\"WARNING: model grid not filled, spectra with zeros exist\")\n\n        return self\n    \n    \n    @classmethod\n    def bb_disk_r(cls,name='bb_disk_r',\n                  wavelengths=cfg.models['default_wave'],\n                  temperatures=10**np.arange(0,3,0.1),\n                  lam0=None, beta=None,\n                  write=False,overwrite=False):\n        \"\"\"Generate a set of blackbody spectra.\"\"\"\n        \n        # don't do the calculation if there will be a write error\n        if write and overwrite == False:\n            if os.path.exists(cfg.model_loc[name]+name+'.fits'):\n                raise utils.SdfError(\"{} exists, will not overwrite\".\n                               format(cfg.model_loc[name]+name+'.fits'))\n    \n        self = cls()\n\n        m = [spectrum.ModelSpectrum.bnu_wave_micron(wavelengths,t,\n                                                    lam0=lam0,\n                                                    beta=beta)\\\n             for t in temperatures]\n\n        self.name = m[0].name\n        self.wavelength = m[0].wavelength\n        if 'star' in name:\n            self.parameters = ['Teff']\n            self.param_values = {'Teff':temperatures}\n        else:\n            self.parameters = ['log_Temp']\n            self.param_values = {'log_Temp':np.log10(temperatures)}\n\n        # put spectra in their place\n        self.fnujy_sr = np.zeros((len(self.wavelength),\n                                  len(temperatures)),dtype=float)\n        for i,mod in enumerate(m):\n            self.fnujy_sr[:,i] = mod.fnujy_sr\n\n        if write:\n            self.write_model(name,overwrite=overwrite)\n\n        return self\n\n\n    @classmethod\n    def modbb_disk_r(cls,name='modbb_disk_r',\n                     wavelengths=cfg.models['default_wave'],\n                     temperatures=10**np.arange(0,3,0.1),\n                     lam0=10**np.arange(1,3,0.1),\n                     beta=np.arange(0,3,0.1),\n                     write=False,overwrite=False):\n        \"\"\"Generate a set of modified blackbody spectra\"\"\"\n        \n        # don't do the calculation if there will be a write error\n        if write and overwrite == False:\n            if os.path.exists(cfg.model_loc[name]+name+'.fits'):\n                raise utils.SdfError(\"{} exists, will not overwrite\".\n                               format(cfg.model_loc[name]+name+'.fits'))\n    \n        self = cls()\n\n        self.fnujy_sr = np.zeros((len(wavelengths),\n                                  len(temperatures),\n                                  len(lam0),\n                                  len(beta)),dtype=float)\n        for i,temp in enumerate(temperatures):\n            for j,l0 in enumerate(lam0):\n                for k,b in enumerate(beta):\n                    m =spectrum.ModelSpectrum.bnu_wave_micron(wavelengths,temp,\n                                                              lam0=l0,beta=b)\n                    self.fnujy_sr[:,i,j,k] = m.fnujy_sr\n\n        self.name = m.name\n        self.wavelength = m.wavelength\n        self.parameters = ['log_Temp','log_lam0','beta']\n        self.param_values = {'log_Temp':np.log10(temperatures)}\n        self.param_values['log_lam0'] = np.log10(lam0)\n        self.param_values['beta'] = beta\n\n        if write:\n            self.write_model(name,overwrite=overwrite)\n\n        return self\n\n\n    @classmethod\n    def modbb_disk_dr(cls,name='modbb_disk_dr',\n                      wavelengths=cfg.models['default_wave'],\n                      t_in_min=200.0, t_in_max=2000.0, n_t_in=20,\n                      t_out_min=10.0, t_out_max=100.0, n_t_out=10,\n                      alpha=np.linspace(-2,2,17),\n                      beta=np.linspace(0,2,9),\n                      write=False,overwrite=False):\n        \"\"\"Generate a set of wide-disk modified blackbody spectra.\n\n        The disk area is normalised so that the full area is one. Thus\n        very wide disks (those with cool outer edges) are much fainter\n        in terms of model flux than smaller ones. \n\n        Parameters\n        ----------\n        name : str, optional\n            Name of the model.\n        wavelengths : array, optional\n            Array of wavelengths for the model.\n        t_in_min : float, optional\n            Minimum inner edge temperature.\n        t_in_max : float, optional\n            Maximum inner edge temperature.\n        n_t_in : int, optional\n            Number of inner temperatures.\n        t_out_min : float, optional\n            Minimum outer edge temperature.\n        t_out_max : float, optional\n            Maximum inner edge temperature.\n        n_t_out : int, optional\n            Number of outer temperatures.\n        alpha : array, optional\n            Array of power law indices for optical depth.\n        beta : array, optional\n            Array of betas, lambda_0's fixed near blackbody peak.\n        write : bool, optional\n            Write the model to disk.\n        overwrite : bool, optional\n            Overwrite any existing model.\n        \"\"\"\n            \n        # don't do the calculation if there will be a write error\n        if write and overwrite == False:\n            if os.path.exists(cfg.model_loc[name]+name+'.fits'):\n                raise utils.SdfError(\"{} exists, will not overwrite\".\n                               format(cfg.model_loc[name]+name+'.fits'))\n    \n        self = cls()\n\n        # set up temperature arrays\n        log_t_in = np.linspace(np.log10(t_in_min),np.log10(t_in_max),n_t_in)\n        t_in = 10**log_t_in\n        log_t_out = np.linspace(np.log10(t_out_min),np.log10(t_out_max),n_t_out)\n        t_out = 10**log_t_out\n\n        self.fnujy_sr = np.zeros((len(wavelengths),\n                                  n_t_in,n_t_out,len(alpha),\n                                  len(beta)),dtype=float)\n\n        # loop to fill model\n        n_r = 100\n        for i,t1 in enumerate(t_in):\n            for j,t2 in enumerate(t_out):\n                for k,a in enumerate(alpha):\n                    for l,b in enumerate(beta):\n                    \n                        tau_tot = 0.0\n                        # generate temps and a range of pseudo radii\n                        t_edges = 10**np.linspace(np.log10(t1),\n                                                  np.log10(t2),\n                                                  n_r+1, dtype=float)\n                        temps = (t_edges[1:]+t_edges[:-1])/2.\n                        radius = lambda x: (278.3/x)**2\n                        r = radius(temps)\n                        r_edges = radius(t_edges)\n                        dr = np.diff(r_edges)\n                        tau = r**a\n                        \n                        for x in range(n_r):\n                            m = spectrum.ModelSpectrum.bnu_wave_micron(\n                                                      wavelengths,\n                                                      temps[x],\n                                                      lam0=3*2900.0/temps[x],\n                                                      beta=b\n                                                      )\n                            annulus_area = tau[x] * 2.0*np.pi*r[x]*dr[x]\n                            spec = m.fnujy_sr * annulus_area\n                            self.fnujy_sr[:,i,j,k,l] += spec\n                            tau_tot += annulus_area\n\n                        # normalise area for all models\n                        self.fnujy_sr[:,i,j,k,l] /= tau_tot\n\n        self.name = m.name\n        self.wavelength = m.wavelength\n        self.parameters = ['log_T_in','log_T_out','alpha','beta']\n        self.param_values = {'log_T_in': log_t_in}\n        self.param_values['log_T_out'] = log_t_out\n        self.param_values['alpha'] = alpha\n        self.param_values['beta'] = beta\n\n        if write:\n            self.write_model(name,overwrite=overwrite)\n\n        return self\n\n\n    @classmethod\n    def sd_spectra(cls, name='sd_disk_r',\n                   wavelengths=cfg.models['default_wave'],\n                   temperatures=10**np.arange(0,3.01,0.1),\n                   smin=10**np.arange(-1,2.01,0.1),\n                   q=np.arange(1.67,2.001,0.02),\n                   smax=100000, nsz=100,\n                   write=False,overwrite=False):\n        \"\"\"Generate a set of size distribution models.\n\n        Simple analytic grain model after Backman & Paresce, assumes\n        that grains have Qabs that is 1 for s<pi.lambda, and Qabs\n        decreasing as lambda^-n beyond. What n is depends on the dust\n        properties, but it appears to be >1 because some disks have\n        (sub)mm slopes steeper than Fnu oc nu^3. Models look like they\n        have n~2, e.g. Draine astrosilicate.\n\n        The sub-mm slopes are not as steep as can be obtained from the\n        real grain models. This is something to do with the details of\n        the absorption/emission efficiencies.\n\n        This models assumes that the peak wavelength of the stellar\n        spectrum peaks at lambda shorter than the grain size to estimate\n        the temperatures, which is a bit suspect but necessary for an\n        analytic solution. The results are a weak function [T^(n/(4+n)]\n        of the stellar temperature anyway.\n        \"\"\"\n\n        # constants\n        xt = np.pi # turnover in Qabs, pi is like \"real\" temperatures\n        n = 2.0    # slope of Qabs beyond xt, 2 is like \"real\" dust\n        cw = 5100. # peak of blackbody emission in micron/K\n        ts = 6000. # assumed stellar temperature\n\n        self = cls()\n\n        self.fnujy_sr = np.zeros((len(wavelengths),\n                                  len(temperatures),\n                                  len(smin),\n                                  len(q)),dtype=float)\n        for i,tbb in enumerate(temperatures):\n            for j, smini in enumerate(smin):\n                for k, qi in enumerate(q):\n\n                    # sizes\n                    s = 10**np.linspace(np.log10(smini),\n                                        np.log10(smax), nsz)\n                    logs = np.log10(s)\n\n                    # calculate grain temperatures\n                    dbb = cw / tbb / xt\n                    dsm = cw / ts  / xt\n                    sm = s < dsm\n                    bb = s > dbb\n                    s_temp = tbb * (dbb/s)**(n/(4+n))\n                    s_temp[sm] = tbb**(4/(4+n)) * ts**(n/(4+n))\n                    s_temp[bb] = tbb\n\n                    # compute bnu for each size\n                    bnu = np.ones((len(s), len(wavelengths)))\n                    for l, st in enumerate(s_temp):\n                        bnu[l,:] = utils.bnu_wav_micron(wavelengths, st)\n\n                    # qabs\n                    qabs = np.ones((len(s), len(wavelengths)))\n                    for l, si in enumerate(s):\n                        x = wavelengths / si\n                        gtx = x > xt\n                        qabs[l,gtx] = (xt/x[gtx])**n\n\n                    # add up size distribution, this is taken straight\n                    # from Wyatt's IDL sigmadbar\n                    qfact = 5 - 3*qi\n                    sigmadbar = qfact * np.log(10) * \\\n                                (10**(logs*qfact)) / \\\n                                (smax**qfact - smini**qfact)\n\n                    for l in range(len(wavelengths)):\n                        self.fnujy_sr[l,i,j,k] = \\\n                        utils.sdf_int(qabs[:,l]*bnu[:,l]*sigmadbar, logs)\n\n#                    return wavelengths, s, s_temp, bnu, qabs, sigmadbar, self.fnujy_sr[:]\n\n        self.name = 'sd'\n        self.wavelength = wavelengths\n        self.parameters = ['log_Temp','log_Dmin','q']\n        self.param_values = {'log_Temp': np.log10(temperatures)}\n        self.param_values['log_Dmin'] = np.log10(smin)\n        self.param_values['q'] = q\n\n        if write:\n            self.write_model(name,overwrite=overwrite)\n\n        return self\n\n\n    def interp_to_wavelengths(self,wavelength,log=True):\n        \"\"\"Interpolate the model to the given wavelengths.\n\n        .. todo:: this only needs to be run at the beginning of a fit but\n        is very slow, especially when there are spectra, speed it up!\n\n        .. todo:: this is straight linear/log interpolation, but could\n        smooth the spectra first since the given wavelength grid will\n        almost certainly be near the spectral resolution of whatever\n        instrument it came from. Probably use resample.\n        \"\"\"\n\n        # check we need to do something\n        if np.all(self.wavelength == wavelength):\n            return\n\n        if log:\n            neg = self.fnujy_sr <= 0.0\n            self.fnujy_sr[neg] = cfg.tiny\n            cube = np.log10(self.fnujy_sr)\n            wave = np.log10(self.wavelength)\n            wave_interp = np.log10(wavelength)\n        else:\n            cube = self.fnujy_sr\n            wave = self.wavelength\n            wave_interp = wavelength\n        \n        # get a function that will return interpolated values, ensure\n        # error if extrapolation in wavelength requested (i.e. model\n        # doesn't cover as wide as was requested)\n        f = interp1d(wave,cube,axis=0,kind='linear',\n                     bounds_error=True)\n        cube_interp = f(wave_interp)\n\n        self.wavelength = wavelength\n        if log:\n            self.fnujy_sr = np.power(10,cube_interp)\n        else:\n            self.fnujy_sr = cube_interp\n\n        self.i = np.arange(len(self.wavelength))\n        self.n_i = len(self.i)\n\n        # and update the hashed version\n        self.fill_log_fnujy_sr_hashed()\n\n\ndef model_fluxes(m,param,obs_nel,phot_only=False):\n    \"\"\"Get model fluxes and put in arrays.\n    \n    all_fnu is everything added up, with colours/indices added properly,\n    comp_fnu[i] contains fluxes from the i-th model component and\n    comp_fnu_col[i] contains these with colours computed.\n    \"\"\"\n    \n    comp_fnu = []\n    all_fnu = []\n    i0 = 0\n    # loop over model components\n    for comp in m:\n        # loop over phot/spectra for this component if they exist\n        if not isinstance(comp,tuple):\n            comp = (comp,)\n        flux = np.array([])\n        # params same for all in each component\n        nparam = len(comp[0].parameters)+1\n        for mod in comp:\n            if phot_only:\n                if not isinstance(mod,PhotModel):\n                    continue\n            fnu = mod.fnujy(param[i0:i0+nparam])\n            flux = np.append( flux, fnu )\n        \n        # since we don't know how long all_fnu will be, make sure\n        # comp_fnu has first dimension equal number of components \n        if len(all_fnu) == 0:\n            all_fnu = flux\n            comp_fnu = np.array([flux])\n        else:\n            all_fnu += flux\n            comp_fnu = np.vstack( (comp_fnu,flux) )\n        i0 += nparam\n    \n    # fill colours, for total and components\n    mod_fnu = fill_colours(m[0],all_fnu,obs_nel)\n    comp_fnu_col = np.zeros((len(comp_fnu),len(mod_fnu)))\n    for i,fnu in enumerate(comp_fnu):\n        comp_fnu_col[i] = fill_colours(m[0],fnu,obs_nel)\n\n    return mod_fnu,comp_fnu_col\n\n\ndef crop(m,param,range):\n    \"\"\"Crop a model to ranges specified for a parameter.\"\"\"\n\n    out = m.copy()\n    \n    if param not in out.parameters:\n        raise utils.SdfError(\"parameter {} not in model (has {})\".\n                       foramt(param,out.parameters))\n\n    # get axis to cut, and locations\n    ax = np.where(out.parameters == param)[0][0] + 1\n    locs = np.searchsorted(out.param_values[param],range)\n\n    print(\"cutting parameters along axis {} to indices {}\".\n          format(ax,locs))\n\n    out.param_values[param] = out.param_values[param][locs[0]:locs[1]]\n    arrin = out.fnujy_sr\n    arr = np.rollaxis(out.fnujy_sr,ax)\n    arr = arr[locs[0]:locs[1]]\n    out.fnujy_sr = np.rollaxis(arr,0,ax+1)\n    print(\"cropped model from {} to {}\".\n          format(arrin.shape,out.fnujy_sr.shape))\n\n    return out\n\n\ndef reduce_zerod(m,parameters):\n    \"\"\"Reduce a model to zero dimensions (i.e. a spectrum).\n        \n    Parameters\n    ----------\n    model : model object\n        The model to reduce.\n    parameters : list\n        Parameter values, excluding the last (normalisation) parameter.\n    \"\"\"\n\n    out = m.copy()\n\n    # modify the attributes\n    out.parameters = []\n    out.param_values = {}\n\n    # get the new spectrum and update the hashed version\n    out.fnujy_sr = m.fnujy(np.append(parameters,-np.log10(cfg.ssr)))\n    out.fill_log_fnujy_sr_hashed()\n    \n    return out\n\n\ndef reduce_squeeze(m):\n    \"\"\"Reduce model by removing length=one dimensions.\"\"\"\n\n    out = m.copy()\n    print('input model has shape:{}'.format(m.param_shape()))\n\n    keep = np.array(m.param_shape()) != 1\n\n    for k,p in zip(keep,m.parameters):\n        if not k:\n            del out.param_values[p]\n    out.parameters = m.parameters[keep]\n    out.fnujy_sr = np.squeeze(m.fnujy_sr)\n\n    print('output model has shape:{}'.format(out.param_shape()))\n    return out\n\n\ndef append_parameter(m,name,value):\n    \"\"\"Append a single parameter to a model.\n        \n    Purpose is to prepare a model for addition models via concat.\n    \n    \"\"\"\n    out = m.copy()\n    out.parameters = np.append(out.parameters,name)\n    out.param_values[name] = np.array([value])\n    out.fnujy_sr = np.reshape(out.fnujy_sr,out.fnujy_sr.shape+(1,))\n    return out\n\n\ndef concat(m0,m):\n    \"\"\"Add a model to the one we have.\n        \n    So far can only add models when both have the same sets of\n    parameters, so for example joining two models with different\n    metallicities.\n        \n    \"\"\"\n\n    out = m0.copy()\n\n    # check types, parameters, wavelengths, filters are the same, allow\n    # for small differences in wavelengths, which can apparently occur\n    # when the arrays are calculated on different machines\n    for i,par in enumerate(out.parameters):\n        if par != m.parameters[i]:\n            raise utils.SdfError(\"parameters {} and {} different\".\n                           format(out.parameters,m.parameters))\n    \n    if type(out) != type(m):\n        raise utils.SdfError(\"can't join models of type {} and {}\".\n                       format(type(out),type(m)))\n    \n    if isinstance(out,PhotModel):\n        for i,filt in enumerate(out.filters):\n            if filt != m.filters[i]:\n                raise utils.SdfError(\"filters {} and {} different\".\n                               format(out.filters,m.filters))\n    \n    if isinstance(out,SpecModel):\n        if not np.allclose(out.wavelength,m.wavelength,rtol=1e-12,atol=1e-12):\n            raise utils.SdfError(\"wavelengths {} and {} different\".\n                           format(out.wavelength,m.wavelength))\n\n    # parameters to add and their locations in out\n    padd = []\n    pax = []\n    ploc = []\n    for i,p in enumerate(out.parameters):\n        if not np.all(np.equal(out.param_values[p],m.param_values[p])):\n            pax.append(i+1) # +1 since first dim is wav/filters\n            padd.append(p)\n            arrs = np.split(m.fnujy_sr,len(m.param_values[p]),axis=i)\n            for val in m.param_values[p]:\n                ploc.append( np.searchsorted(out.param_values[p],val) )\n\n    if len(padd) != 1:\n        raise utils.SdfError(\"model parameters can't be joined (padd={})\".\n                       format(padd))\n    else:\n        padd = padd[0]\n\n    print(\"Adding parameter {} at location(s) {} along axis {}\".\n          format(padd,ploc,pax))\n\n    for i,loc in enumerate(ploc):\n        \n        if m.param_values[padd][i] in out.param_values[padd]:\n            raise utils.SdfError(\"model already has {}={}\".\n                           format(padd,m.param_values[padd][i]))\n\n        print(\"  adding {}={} (dims {} to {}) at {}\".\n              format(padd,m.param_values[padd][i],\n                     arrs[i].squeeze().shape,out.fnujy_sr.shape,loc))\n\n        out.param_values[padd] = np.insert(out.param_values[padd],\n                                            loc,m.param_values[padd][i])\n        out.fnujy_sr = np.insert(out.fnujy_sr,loc,\n                                  arrs[i].squeeze(),axis=pax[i])\n            \n    print(\"  new {} array is {}\".format(padd,out.param_values[padd]))\n\n    return out\n\n\ndef fill_colours(comp,mod_fnu,obs_nel):\n    \"\"\"Replace locations in mod_fnu with colours\n        \n    Colours cannot simply be added without knowing the absolute\n    measurements. The model components have already been added so we\n    only need to figure out where the filters associated with the\n    colours are, and calculate the colours from these.\n    \n    By using obs_nel, the number of observed fluxes/colours per\n    Phot/SpecModel component, the extra columns containing the base\n    filters for colours are not included in the returned result.\n\n    \"\"\"\n    final_fnu = np.array([])\n    if not isinstance(comp,tuple):\n        comp = (comp,)\n    i0comp = 0 # zeroth index of the current Phot/SpecModel\n    for k,mod in enumerate(comp):\n        if isinstance(mod,PhotModel):\n            # loop over each filter/index in the model, skip\n            # if there are no colour_bases (i.e. a filter)\n            for i,cb in enumerate(mod.colour_bases):\n                if len(cb) > 0:\n                    mags = 0.0\n                    # loop over the filters in this colour/index\n                    # and add the magnitude with the correct weight\n                    # for this colour/index\n                    for j,filteri in enumerate(cb['filteri']):\n                        fname = mod.filters[i+filteri]\n                        irel = i0comp+i+cb['filteri'][j]\n                        filt = filter.Filter.get(fname)\n                        mag = filt.flux2mag(mod_fnu[irel])\n                        mags += mag * cb['filterw'][j]\n                    mod_fnu[i] = mags\n            final_fnu = np.append(final_fnu,\n                                  mod_fnu[i0comp:i0comp+obs_nel[k]])\n            i0comp += len(mod.filters)\n        else:\n            final_fnu = np.append(final_fnu,\n                                  mod_fnu[i0comp:i0comp+obs_nel[k]])\n            i0comp += len(mod.wavelength)\n\n    return final_fnu\n\n\ndef get_models(obs,names):\n    \"\"\"Get tuples of models for given observations.\n        \n    Returns two tuples of models, the first is for fitting and contains\n    extra filters beyond the set in the observations if there are\n    colours in the photometry. The second exludes the extra filters, and\n    has a max of one spectrum (for plotting purposes).\n\n    \"\"\"\n    allmod = ()\n    fullmod = ()\n    for name in names:\n       \n        omod = ()\n        fmod = ()\n        \n        # load models we will need\n        ph = PhotModel.read_model(name)\n        sp = SpecModel.read_model(name)\n\n        for o in obs:\n        \n            if isinstance(o,photometry.Photometry):\n                phmod = ph.copy()\n                phmod.keep_filters(o.filters,colour_bases=True)\n                omod = omod + (phmod,)\n                phmod = ph.copy()\n                phmod.keep_filters(o.filters,colour_bases=False)\n                fmod = fmod + (phmod,)\n            \n            if isinstance(o,spectrum.ObsSpectrum):\n                spmod = sp.copy()\n                spmod.interp_to_wavelengths(o.wavelength)\n                omod = omod + (spmod,)\n                \n        # always want a full spectrum in full model, but only one\n        fmod = fmod + (sp,)\n\n        allmod = allmod + (omod,)\n        fullmod = fullmod + (fmod,)\n\n    return allmod,fullmod\n\n\ndef models_info(m):\n    \"\"\"Return some info for a tuple of model(s).\n        \n    Also do some basic sanity checking.\n    \n    Here is where the ranges for model and spectra normalisation is set.\n    \n    \"\"\"\n    info = {}\n    info['name'] = ''\n    info['ndim'] = 0\n    info['ncomp'] = []\n    info['nspec'] = []\n    info['type'] = []\n    info['p_rng'] = []\n    info['parameters'] = []\n    info['nmodels'] = len(m)\n    for comp in m:\n        nspec = 0\n        if not isinstance(comp,tuple):\n            comp = (comp,)\n        info['ncomp'].append(len(comp))\n        if info['name'] == '':\n            info['name'] = comp[0].name\n        else:\n            info['name'] += cfg.fitting['model_join']+comp[0].name\n        info['ndim'] += len(comp[0].parameters)+1\n        for par in comp[0].parameters:\n            info['p_rng'].append( (comp[0].param_values[par][0],\n                                   comp[0].param_values[par][-1]) )\n            info['parameters'].append( par )\n        # this is the range of allowed solid angles\n        info['p_rng'].append( cfg.fitting['model_om_range'] )\n        info['parameters'].append('norm')\n        for mod in comp:\n            if isinstance(mod,SpecModel):\n                nspec += 1\n            info['type'].append(type(mod))\n        info['nspec'].append(nspec)\n    info['ndim'] += info['nspec'][0]\n\n    # spectra normalisations last (nspec same for each comp)\n    for i in range(nspec):\n        info['p_rng'].append( cfg.fitting['spectra_norm_range'] )\n        info['parameters'].append('spec_norm')\n\n    # check structure looks OK\n    if len(np.unique(info['ncomp'])) > 1:\n        raise utils.SdfError(\"model structure {} should have same number of\\\n                        subcomponents in each component, not {}\".\n                        format(m,info['ncomp']))\n    if len(np.unique(info['nspec'])) > 1:\n        raise utils.SdfError(\"model structure {} should have same number of spectra\\\n                        in each component, not {}\".format(m,info['nspec']))\n\n    return info\n", "meta": {"hexsha": "ac054b0442945b342e4bc034fea76667a264d040", "size": 47628, "ext": "py", "lang": "Python", "max_stars_repo_path": "sdf/model.py", "max_stars_repo_name": "drgmk/sdf", "max_stars_repo_head_hexsha": "a44e66a82f876dda079686b32c767370276c38a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-01T15:55:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-01T15:55:16.000Z", "max_issues_repo_path": "sdf/model.py", "max_issues_repo_name": "drgmk/sdf", "max_issues_repo_head_hexsha": "a44e66a82f876dda079686b32c767370276c38a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-03-28T19:18:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-21T08:17:45.000Z", "max_forks_repo_path": "sdf/model.py", "max_forks_repo_name": "drgmk/sdf", "max_forks_repo_head_hexsha": "a44e66a82f876dda079686b32c767370276c38a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-13T19:39:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-13T19:39:15.000Z", "avg_line_length": 36.3018292683, "max_line_length": 90, "alphanum_fraction": 0.5479759805, "include": true, "reason": "import numpy,from scipy,import astropy,from astropy", "num_tokens": 10800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.2909808785120009, "lm_q1q2_score": 0.15457176581904541}}
{"text": "\"\"\"\nImplementation the PACO algorithm implementation for VIP\nBased on Flasseur+ 2018 https://ui.adsabs.harvard.edu/abs/2018A%26A...618A.138F/abstract\n\nVariable naming is based on the notation of Flasseur+ 2018,\nsee table 1 in the paper for a description.\n\nLast updated 2022-05-09 by Evert Nasedkin (nasedkinevert@gmail.com).\n\"\"\"\n\nimport sys\n#import os\nfrom abc import abstractmethod\n# Required so numpy parallelization doesn't conflict with multiprocessing\n# os.environ[\"MKL_NUM_THREADS\"] = \"1\"\n# os.environ[\"NUMEXPR_NUM_THREADS\"] = \"1\"\n# os.environ[\"OMP_NUM_THREADS\"] = \"1\"\n\n#from multiprocessing import Pool\nfrom typing import Tuple, Union, Optional, Callable\nimport numpy as np\nfrom scipy import ndimage\nfrom scipy.ndimage import filters\n\nfrom ..config.utils_conf import pool_map, iterable\nfrom ..preproc.rescaling import frame_px_resampling, cube_px_resampling, frame_shift\nfrom ..var.coords import cart_to_pol, pol_to_cart\nfrom ..metrics.detection import detection\nfrom ..fm import normalize_psf\n__author__ = \"Evert Nasedkin\"\n__all__ = ['FastPACO',\n           'FullPACO']\n\n\nclass PACO:\n    \"\"\"\n    This class implements the bulk of the PACO algorithm as described by\n    Flasseur et al (2018). In general, the idea is to take in an ADI stack of\n    images and statistically determine if there is a signal above the\n    background in each 'patch' of the image. This is done by tracing the ark of\n    the hypothesized planet through the stack, and comparing this set of patches\n    to a set consisting of background only. This is done for each pixel (or\n    sub-pixel) location in.\n    The output is a signal-to-noise and/or a flux map over the field of view.\n    The user can choose to use FullPACO or FastPACO, which are described by\n    algorithms 1 and 2 of Flasseur+ 2018. FastPACO has been parallelized,\n    and is the recommended usage.\n\n    This output can then be used to compute an unbiased estimate of the flux\n    of point sources detected in the image above some user-supplied detection\n    threshold.\n\n    Parameters\n    ----------\n    cube : numpy.ndarray\n        3D science frames taken in pupil tracking/ADI mode.\n        Dimensions should be (time, x, y), and units should be detector units (ie output\n        of SPHERE or GPI reduction pipelines). The data should be centered, and have\n        pre-processing already applied (e.g. bad pixel correction).\n    angles : numpy.ndarray\n        List of parallactic angles for each frame in degrees. Length of this array\n        should be the same as the time axis of the science cube. Sign convention\n        is the same as in the rest of VIP.\n    psf : numpy.ndarray\n        Unsaturated PSF image. If a cube is provided, the median of the cube will be used.\n    dit_psf : float, optional\n        Integration time of the unsaturated PSF in seconds. The PSF is normalised\n        to dit_science/dit_psf/nd_transmission.\n    dit_science : float, optional\n        Integration time of the science frames in seconds.T he PSF is normalised\n        to dit_science/dit_psf/nd_transmission.\n    nd_transmission : float, optional\n        Transmission of an ND filter used to aquire the unsaturated PSF. The PSF is normalised\n        to dit_science/dit_psf/nd_transmission.\n    fwhm : float, optional\n        FWHM of PSF in arcseconds. Default values give 4px radius.\n    pixscale : float, optional\n        Detector pixel scale in arcseconds per pixel.  Default values give 4px radius.\n    rescaling_factor : float, optional\n        Scaling for sub/super pixel resolution for PACO. Will rescale both the science\n        cube and the PSF.\n    verbose : bool, optional\n        Sets level of printed outputs.\n    \"\"\"\n\n    def __init__(self,\n                 cube: np.ndarray,\n                 angles: np.ndarray,\n                 psf: np.ndarray,\n                 dit_psf: Optional[float] = 1.0,\n                 dit_science: Optional[float] = 1.0,\n                 nd_transmission: Optional[float] = 1.0,\n                 fwhm: Optional[float] = 4.0,\n                 pixscale: Optional[float] = 1.0,\n                 rescaling_factor: Optional[float] = 1.0,\n                 verbose: Optional[bool] = False) -> None:\n\n        # Science image setup\n        try:\n            self.cube = cube\n        except BaseException:\n            raise ValueError(\"You must provide a 3D cube of science data!\")\n\n        self.num_frames = self.cube.shape[0]\n        self.width = self.cube.shape[2]\n        self.height = self.cube.shape[1]\n\n        # Parallactic angles\n        try:\n            self.angles = angles\n        except BaseException:\n            raise ValueError(\"You must provide an array of parallactic angles!\")\n\n        # Pixel scaling\n        self.pixscale = pixscale\n        self.rescaling_factor = rescaling_factor\n\n        # PSF setup\n        self.fwhm = int(fwhm/pixscale)\n        try:\n            # How do we want to deal with stacks of psfs? Median? Just take the first one?\n            # Ideally if nPSFs = nImages, use each for each. Need to update!\n            if len(psf.shape) > 2:\n                psf = np.nanmedian(psf, axis=0)\n            self.psf = psf * dit_science/dit_psf/nd_transmission\n            self.dit_science = dit_science\n            self.dit_psf = dit_psf\n\n            mask = create_boolean_circular_mask(self.cube[0].shape,\n                                                radius=self.fwhm)\n            self.patch_area_pixels = self.cube[0][mask].ravel().shape[0]\n        except BaseException:\n            raise ValueError(\"You must provide an unsaturated PSF image!\")\n\n        self.patch_width = 2*int(self.fwhm) + 3\n        self.verbose = verbose\n\n        # These are what we're calculating\n        self.snr = None\n        self.flux = None\n        self.std = None\n\n        # Diagnostics\n        if self.verbose:\n            print(\"---------------------- \")\n            print(\"Summary of PACO setup: \\n\")\n            print(f\"Image Cube shape = {self.cube.shape}\")\n            print(f\"PIXSCALE = {self.pixscale:06}\")\n            print(\"PSF |  Area  |  Rad   |  Width | \")\n            print(f\"    |   {self.patch_area_pixels:01}   |\"\n                  + f\"  {self.fwhm:02}    |  {self.psf.shape[0]:03}   | \")\n            print(f\"Patch width: {self.patch_width}\")\n            print(\"---------------------- \\n\")\n            sys.stdout.flush()\n\n    @abstractmethod\n    def PACOCalc(self,\n                 phi0s : np.ndarray,\n                 use_subpixel_psf_astrometry : Optional[bool] = True,\n                 cpu : Optional[int] = 1) -> None:\n        \"\"\"\n        This function is algorithm dependant, and sets up the actual\n        calculation process.\n\n        Parameters\n        ----------\n        phi0s : numpy.ndarray\n            Array of pixel coordinates to try to search for the planet signal. Typically a grid\n            created using numpy.meshgrid.\n        use_subpixel_psf_astrometry : bool\n            If true, the PSF model for each patch is shifted to the correct\n            location as predicted by the starting location and the parallactic\n            angles, before being resampled for the patch. If false, the PSF\n            model is simply located at the center of each patch. Significantly\n            improves performance if set to False, but the SNR is reduced.\n        cpu : int, optional\n            Number of cpus to use for parallelization.\n\n        Returns\n        -------\n        a : numpy.ndarray\n            a_l from Equation 15 of Flasseur+ 2018\n        b : numpy.ndarray\n            b_l from Equation 16 of Flasseur+ 2018\n        \"\"\"\n\n    def run(self,\n            cpu : Optional[int] = 1,\n            imlib : Optional[str] = 'vip-fft',\n            interpolation : Optional[str]= 'lanczos4',\n            keep_center : Optional[bool] = True,\n            use_subpixel_psf_astrometry : Optional[bool] = True) -> Tuple[np.ndarray, np.ndarray]:\n        \"\"\"\n        Run method of the PACO class. This function wraps up the PACO\n        calculation steps, and returns the snr and flux estimates as\n        outputs. The image library arguments are used if a rescaling of the\n        data is desired: upsampling the images will result in a better SNR\n        detection, but will be slower.\n\n        Parameters\n        ----------\n        cpu : int, optional\n            Number of processers to use\n        imlib : str, optional\n            See the documentation of the ``vip_hci.preproc.frame_px_resampling``\n            function.\n        interpolation : str, optional\n            See the documentation of the ``vip_hci.preproc.frame_px_resampling``\n            function.\n        keep_center: bool, opt\n            If input dimensions are even and the star centered (i.e. on\n            dim//2, dim//2), whether to keep the star centered after scaling, i.e.\n            on (new_dim//2, new_dim//2). For a non-centered input cube, better to\n            leave it to False.\n        use_subpixel_psf_astrometry : bool\n            If true, the PSF model for each patch is shifted to the correct\n            location as predicted by the starting location and the parallactic\n            angles, before being resampled for the patch. If false, the PSF\n            model is simply located at the center of each patch. Significantly\n            improves performance if set to False, but the SNR is reduced.\n\n        Returns\n        -------\n        snr : numpy.ndarray\n            2D map of the signal-to-noise estimate as computed by PACO.\n            This is b/sqrt(a), as in eqn 24 of Flasseur 2018.\n        flux : numpy.ndarray\n            2D map of the flux estimate as computed by PACO\n            This is b/a, as in eqn 21 of Flasseur 2018.\n        \"\"\"\n\n        if self.rescaling_factor != 1:\n            self.rescale_cube_and_psf(imlib=imlib,\n                                      interpolation=interpolation,\n                                      keep_center=keep_center,\n                                      verbose=self.verbose)\n            if self.verbose:\n                print(\"---------------------- \")\n                print(f\"Using {cpu} processor(s).\")\n                print(f\"Rescaled Image Cube shape: {self.cube.shape}\")\n                print(\"Rescaled PSF:\")\n                print(\"PSF |  Area  |  Rad   |  Width | \")\n                print(f\"    |   {self.patch_area_pixels:01}   |\"\n                      + f\"  {self.fwhm:02}    |  {self.psf.shape[0]:03}   | \")\n                print(\"---------------------- \\n\")\n\n        # Setup pixel coordinates\n        x, y = np.meshgrid(np.arange(0, self.height),\n                           np.arange(0, self.width))\n        phi0s = np.column_stack((x.flatten(), y.flatten()))\n        # Compute a,b\n        a, b = self.PACOCalc(np.array(phi0s), cpu=cpu)\n\n        # Reshape into a 2D image, with the same dimensions as the input images\n        a = np.reshape(a, (self.height, self.width))\n        b = np.reshape(b, (self.height, self.width))\n        # Output arrays\n        snr = b/np.sqrt(a)\n        flux = b/a\n        self.snr = snr\n        self.flux = flux\n        self.std = 1/np.sqrt(a)\n        return snr, flux\n\n    \"\"\"\n    Utility Functions\n    \"\"\"\n    # Set the image stack to be processed\n\n    def set_cube(self, cube: np.ndarray) -> None:\n        \"\"\"\n        Provide a 3D image array to process. This updates\n        the science cube, and the associated dimensions.\n\n        Parameters\n        ----------\n        cube : numpy.ndarray\n            3D science frames taken in pupil tracking/ADI mode.\n            Dimensions should be (time, x, y), and units should be detector\n            units (ie output of SPHERE or GPI reduction pipelines). The data\n            should be centered, and have pre-processing already applied (e.g.\n            bad pixel correction).\n        \"\"\"\n        self.cube = np.array(cube)\n        self.num_frames = self.cube.shape[0]\n        self.width = self.cube.shape[2]\n        self.height = self.cube.shape[1]\n\n    # Set the template PSF\n    def set_psf(self, psf: np.ndarray) -> None:\n        \"\"\"\n        Read in the PSF template\n\n        Parameters\n        ----------\n        psf: numpy.ndarray\n            An unsaturated psf to use as the template.\n        \"\"\"\n        self.psf = psf\n\n    # Set parallactic angles\n    def set_angles(self, angles: np.ndarray) -> None:\n        \"\"\"\n        Set the rotation angle for each frame\n\n        Parameters\n        ----------\n        angles: numpy.ndarray\n            A list of the parallactic angles for each frame of the science data.\n        \"\"\"\n\n        self.angles = angles\n\n    def get_patch(self,\n                  px: Tuple[int, int],\n                  width: Optional[int] = None,\n                  mask: Optional[np.ndarray] = None) -> np.ndarray:\n        \"\"\"\n        Gets patch at given pixel px with size k for the current img sequenc\n\n        Parameters\n        ----------\n        px : Tuple[int, int]\n            Pixel coordinates for center of patch\n        width : int\n            width of a square patch to be masked\n\n        Returns\n        -------\n        patch : numpy.ndarray\n            A PACO \"patch\". This is a column through the time dimension of the\n            unrotated frames, used to build the background statistics at the\n            location of a given pixel.\n        \"\"\"\n        if width is None:\n            width = self.patch_width\n        if mask is None:\n            mask = create_boolean_circular_mask(self.cube[0].shape,\n                                                radius=self.fwhm,\n                                                center=px)\n        k = int(width/2)\n        if width % 2 != 0:\n            k2 = k+1\n        else:\n            k2 = k\n        nx, ny = np.shape(self.cube[0])[:2]\n        if px[0]+k2 > nx or px[0]-k < 0 or px[1]+k2 > ny or px[1]-k < 0:\n            return np.ones((self.num_frames, self.patch_area_pixels))*np.nan\n        patch = self.cube[np.broadcast_to(mask, self.cube.shape)]\\\n            .reshape(self.num_frames, self.patch_area_pixels)\n        return patch\n\n    def set_scale(self, scale: float) -> None:\n        \"\"\"\n        Set subpixel scaling factor\n\n        Parameters\n        ----------\n        scale : float\n            Scaling factor. Greater than one will result in an upsampled image,\n            less than one will result in a downsampled image.\n        \"\"\"\n\n        self.rescaling_factor = scale\n\n    def rescale_cube_and_psf(self,\n                             imlib: Optional[str] = 'vip-fft',\n                             interpolation: Optional[str] = 'lanczos4',\n                             keep_center: Optional[bool] = True) -> None:\n        \"\"\"\n        Rescale each image in the stack by the class level scaling factor\n        set during initialization or with set_scale. A scale factor of greater\n        than one will upsample the image, a factor of less than one will downsample\n        the image. This function wraps the VIP scaling function, and uses the same\n        arguments to choose libraries and interpolation methods.\n\n        Parameters\n        ----------\n        imlib : str, optional\n            See the documentation of the ``vip_hci.preproc.frame_px_resampling``\n            function.\n        interpolation : str, optional\n            See the documentation of the ``vip_hci.preproc.frame_px_resampling``\n            function.\n        keep_center: bool, opt\n            If input dimensions are even and the star centered (i.e. on\n            dim//2, dim//2), whether to keep the star centered after scaling, i.e.\n            on (new_dim//2, new_dim//2). For a non-centered input cube, better to\n            leave it to False.\n        \"\"\"\n\n        if self.rescaling_factor == 1:\n            if self.verbose:\n                print(\"Scale is 1, no scaling applied.\")\n            return\n\n        # Resample the science cube\n        cube_px_resampling(self.cube,\n                           self.rescaling_factor,\n                           imlib=imlib,\n                           interpolation=interpolation,\n                           keep_center=keep_center,\n                           verbose=False)\n\n        self.pixscale = self.pixscale/self.rescaling_factor\n        self.fwhm = int(self.fwhm*self.rescaling_factor)\n\n        # Resample the PSF\n        if self.psf is not None:\n            self.psf = frame_px_resampling(self.psf,\n                                           self.rescaling_factor,\n                                           imlib=imlib,\n                                           interpolation=interpolation,\n                                           keep_center=keep_center,\n                                           verbose=False)\n        mask = create_boolean_circular_mask(self.psf.shape, self.fwhm)\n        self.patch_area_pixels = self.psf[mask].shape[0]\n        self.patch_width = 2*int(self.fwhm) + 3\n\n    \"\"\"\n    Math Functions\n    \"\"\"\n\n    def psf_model_function(self, mean: float, model: Callable,\n                           params: dict) -> np.ndarray:\n        \"\"\"\n        This function is deprecated in favour of directly supplying\n        a PSF. In principle, an analytic model (ie a gaussian or moffat PSF)\n        can be used in place of a measured unsaturated PSF.\n\n        Parameters\n        ----------\n        mean : float\n            If using the psfTemplateModel function, the mean\n        model : dnc\n            numpy statistical model (need to import numpy module for this)\n        **kwargs: dict\n            additional arguments for model\n\n        Returns\n        -------\n        self.psf : numpy.ndarray\n            Returns the PSF template used by PACO\n        \"\"\"\n\n        if self.psf:\n            return self.psf\n        if model is None:\n            print(\"Please input either a 2D PSF or a model function.\")\n            sys.exit(1)\n        else:\n            if model.__name__ == \"psfTemplateModel\":\n                try:\n                    self.psf = model(mean, params)\n                    return self.psf\n                except ValueError:\n                    print(\"Fix template size\")\n            self.psf = model(mean, params)\n            return self.psf\n\n    def al(self,\n           hfl: Union[list, np.ndarray],\n           Cfl_inv: Union[list, np.ndarray],\n           method: Optional[str] = \"\") -> np.ndarray:\n        \"\"\"\n        a_l\n        The sum of a_l is the inverse of the variance of the background at the given pixel.\n        Einsum can get slow with large tensors, and may not actually be faster.\n        If einsum is used, arguments must be numpy arrays, otherwise lists.\n\n        Parameters\n        ----------\n        hfl : list\n            This is a list of flattened psf templates\n        Cfl_inv : list\n            This is a list of inverse covariance matrices\n        method: string\n            Can be empty or \"einsum\". This determines the method\n            used to do the matrix operations. \"einsum\" is slower for large arrays.\n\n        Returns\n        -------\n        a : numpy.ndarray\n            a_l from equation 15 of Flasseur 2018.\n        \"\"\"\n        if method == \"einsum\":\n            d1 = np.einsum('ijk,gj', Cfl_inv, hfl)\n            return np.einsum('ml,ml', hfl, np.diagonal(d1).T)\n\n        a = np.sum(np.array([np.dot(hfl[i], np.dot(Cfl_inv[i], hfl[i]).T)\n                             for i in range(len(hfl))]), axis=0)\n        return a\n\n    def bl(self, hfl: Union[list, np.ndarray],\n           Cfl_inv: Union[list, np.ndarray],\n           r_fl: Union[list, np.ndarray],\n           m_fl: Union[list, np.ndarray],\n           method: Optional[str] = \"\") -> np.ndarray:\n        \"\"\"\n        b_l\n        The sum of b_l is the flux estimate at the given pixel.\n        Einsum can get slow with large tensors, and may not actually be faster.\n        If einsum is used, arguments must be numpy arrays, otherwise lists.\n\n        Parameters\n        ----------\n        hfl : numpy.ndarray\n            This is an array of flattened psf templates.\n        Cfl_inv : numpy.ndarray\n            This is an array of inverse covariance matrices.\n        r_fl : numpy.ndarray\n            This is an array of flux measurements following the predicted path.\n        m_fl : numpy.ndarray\n            This is an array of mean background statistics for each location in the path.\n        method: string\n            Can be empty or \"einsum\". This determines the method\n            used to do the matrix operations. \"einsum\" is slower for large arrays.\n\n        Returns\n        -------\n        b : numpy.ndarray\n            b_l from equation 16 of Flasseur 2018.\n\n        \"\"\"\n        if method == \"einsum\":\n            d1 = np.einsum('ijk,gj', Cfl_inv, r_fl-m_fl)\n            return np.einsum('ml,ml', hfl, np.diagonal(d1).T)\n\n        b = np.sum(np.array([np.dot(np.dot(Cfl_inv[i], hfl[i]).T, (r_fl[i]-m_fl[i]))\n                             for i in range(len(hfl))]), axis=0)\n        return b\n\n    \"\"\"\n    FluxPACO\n    \"\"\"\n\n    def flux_estimate(self,\n                      phi0s: np.ndarray,\n                      eps: Optional[float] = 0.1,\n                      initial_est: Optional[list] = [0.0]) -> list:\n        \"\"\"\n        Unbiased estimate of the flux of a source located at p0\n        The estimate of the flux is given by ahat * h, where h is the PSF template.\n        This implements algorithm 3 from Flasseur+ 2018.\n        TODO: Further testing to ensure that the extracted contrast is actually unbiased.\n        Don't trust this estimate without checking!\n\n        Parameters\n        ----------\n        phi0s : numpy.ndarray\n            List of locations of sources to compute unbiased flux estimate in pixel units.\n            Origin is at the bottom left. Should be a list of (x,y) tuples, or a 2D numpy\n            array.\n        eps : float\n            Precision requirement for iteration (0,1)\n        initial_est : float\n            Initial estimate of the flux at p0 in contrast units\n\n        Returns\n        -------\n        ests : list\n            List of a-hat values for each detected source in the SNR map. This is the unbiased\n            estimate of the flux at that location. Practically, this is similar to negative PSF\n            injection. If the PSF is correctly normalized, this should be in contrast units.\n        stds : list\n            List of the estimated standard deviation on the flux estimates in contrast units.\n        norm : float\n            np.nanmax(psf) - Scaling factor for flux estimate and standard deviations.\n        \"\"\"\n        print(\"Computing unbiased flux estimate...\")\n\n        if self.verbose:\n            print(\"Initial guesses:\")\n            print(\"Positions: \", phi0s)\n            print(\"Contrasts: \", initial_est)\n\n        dim = self.width/2\n        # Create arrays needed for storage\n        # Store for each image pixel, for each temporal frame an image\n        # for patches: for each time, we need to store a column of patches\n        normalised_psf,norm,fwhm = normalize_psf(self.psf,\n                                            fwhm='fit',\n                                            size=None,\n                                            threshold=None,\n                                            mask_core=None,\n                                            model='airy',\n                                            imlib='vip-fft',\n                                            interpolation='lanczos4',\n                                            force_odd=False,\n                                            full_output=True,\n                                            verbose=self.verbose,\n                                            debug=False)\n\n        psf_mask = create_boolean_circular_mask(normalised_psf.shape, radius=self.fwhm)\n        hoff = np.zeros((self.num_frames,self.num_frames, self.patch_area_pixels)) # The off axis PSF at each point\n        # Create arrays needed for storage\n        # Store for each image pixel, for each temporal frame an image\n        # for patches: for each time, we need to store a column of patches\n        # 2d selection of pixels around a given point\n        x, y = np.meshgrid(np.arange(-dim, dim), np.arange(-dim, dim))\n\n        ests = []\n        stds = []\n        for i, p0 in enumerate(phi0s):\n            p0 = (p0[1],p0[0])\n            angles_px = np.array(get_rotated_pixel_coords(x, y, p0, self.angles))\n            hon = []\n            for l, ang in enumerate(angles_px):\n                # Get the column of patches at this point\n                offax = frame_shift(normalised_psf,\n                                    ang[1]-int(ang[1]),\n                                    ang[0]-int(ang[0]),\n                                    imlib='vip-fft',\n                                    interpolation='lanczos4',\n                                    border_mode='reflect')[psf_mask]\n                hoff[l,l] = offax\n                hon.append(offax)\n\n            Cinv, m, patches = self.compute_statistics(np.array(angles_px).astype(int))\n            # Get Angles\n            # Ensure within image bounds\n            # Extract relevant patches and statistics\n            Cinlst = []\n            mlst = []\n            patch = []\n            for l, ang in enumerate(angles_px):\n                Cinlst.append(Cinv[int(ang[0]), int(ang[1])])\n                mlst.append(m[int(ang[0]), int(ang[1])])\n                patch.append(patches[int(ang[0]), int(ang[1]),l])\n            a = self.al(hon,Cinlst)\n            b = self.bl(hon, Cinlst,patch, mlst)\n            print(b/a)\n            # Fill patches and signal template\n\n\n            # Unbiased flux estimation\n            ahat = initial_est[i]\n            aprev = 1e10 # Arbitrary large value so that the loop will run\n            while np.abs(ahat - aprev) > np.abs(ahat * eps):\n                a = 0.0\n                b = 0.0\n                # the mean of a temporal column of patches at each pixel\n                m = np.zeros((self.num_frames, self.patch_area_pixels))\n                # the inverse covariance matrix at each point\n                Cinv = np.zeros((self.num_frames, self.patch_area_pixels, self.patch_area_pixels))\n\n                # Patches here are columns in time\n                for l,ang in enumerate(angles_px):\n                    apatch = self.get_patch(ang.astype(int))\n                    m[l], Cinv[l] = self.iterate_flux_calc(ahat, apatch, hoff[l])\n                # Patches here are where the planet is expected to be\n                a = self.al(hon, Cinv)\n                b = self.bl(hon, Cinv, patch, m)\n                aprev = ahat\n                ahat = b/a\n                if self.verbose:\n                    print(f\"Flux estimate: {ahat/norm}\")\n            ests.append(np.abs(ahat/norm))\n            stds.append(1/np.sqrt(a)/norm)\n        print(\"Extracted contrasts\")\n        print(\"-------------------\")\n        for i in range(len(phi0s)):\n            print(\n                f\"x: {phi0s[i][0]}, y: {phi0s[i][1]}, flux: {ests[i]}±{stds[i]}\")\n        return ests, stds, norm\n\n    def iterate_flux_calc(self, est: float, patch: np.ndarray,\n                          model: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n        \"\"\"\n        Compute the iterative estimates for the mean and inverse covariance.\n\n        Parameters\n        ----------\n        est : float\n            Current estimate for the magnitude of the flux\n        patch : numpy.ndarray\n            Column of patches about p0\n        model : numpy.ndarray\n            Template for PSF\n\n        Returns\n        -------\n        m : numpy.ndarray\n            Mean of background patches.\n        Cinv : numpy.ndarray\n            List of inverse covariance matrices between the patches.\n        \"\"\"\n\n        if patch is None:\n            return None, None\n\n        unbiased = np.array([apatch - est*model[l] for l,apatch in enumerate(patch)])\n        m,Cinv = compute_statistics_at_pixel(unbiased)\n        return m, Cinv\n\n    def subpixel_threshold_detect(self, snr_map: np.ndarray,\n                                  threshold: float,\n                                  mode: Optional[str] = 'lpeaks',\n                                  bkg_sigma: Optional[float] = 5.0,\n                                  matched_filter: Optional[bool] = False,\n                                  mask: Optional[bool] = True,\n                                  full_output: Optional[bool] = False,\n                                  cpu: Optional[int] = 1) -> np.ndarray:\n        \"\"\" Wraps VIP.metrics.detection.detection, see that function for further documentation.\n        Note that the output convention here is different - this function returns xx,yy.\n\n        Finds blobs in a 2d array. The algorithm is designed for automatically\n        finding planets in post-processed high contrast final frames. Blob can be\n        defined as a region of an image in which some properties are constant or\n        vary within a prescribed range of values. See ``Notes`` below to read about\n        the algorithm details.\n        Parameters\n        ----------\n        snr_map : numpy ndarray, 2d\n            Input frame.\n        threshold : float\n            S/N threshold for deciding whether the blob is a detection or not. Used\n            to threshold the S/N map when ``mode`` is set to 'snrmap' or 'snrmapf'.\n        mode : {'lpeaks', 'log', 'dog', 'snrmap', 'snrmapf'}, optional\n            Sets with algorithm to use. Each algorithm yields different results. See\n            notes for the details of each method.\n        bkg_sigma : int or float, optional\n            The number standard deviations above the clipped median for setting the\n            background level. Used when ``mode`` is either 'lpeaks', 'dog' or 'log'.\n        matched_filter : bool, optional\n            Whether to correlate with the psf of not. Used when ``mode`` is either\n            'lpeaks', 'dog' or 'log'.\n        mask : bool, optional\n            If True the central region (circular aperture of 2*FWHM radius) of the\n            image will be masked out.\n        full_output : bool, optional\n            Whether to output just the coordinates of blobs that fulfill the SNR\n            constraint or a table with all the blobs and the peak pixels and SNR.\n        cpu : None or int, optional\n            The number of processes for running the ``snrmap`` function.\n        verbose : bool, optional\n            Whether to print to stdout information about found blobs.\n        Returns\n        -------\n        peaks : np.ndarray\n            xx,yy values of the centers of local maxima above the provided threshold\n        \"\"\"\n        peaks = detection(snr_map,\n                          fwhm=self.fwhm,\n                          psf=self.psf/np.nanmax(self.psf),\n                          mode=mode,\n                          bkg_sigma=bkg_sigma,\n                          matched_filter=matched_filter,\n                          mask=mask,\n                          snr_thresh=threshold,\n                          nproc=cpu,\n                          plot=False,\n                          debug=False,\n                          full_output=full_output,\n                          verbose=self.verbose)\n        return peaks.T\n\n    def pixel_threshold_detection(\n            self, snr_map: np.ndarray, threshold: float) -> np.ndarray:\n        \"\"\"\n        Returns a list of the pixel coordinates of center of signals above a given threshold\n\n        Parameters\n        ----------\n        snr_map : numpy.ndarray\n            SNR map, b/sqrt(a) as computed by run()\n        threshold: float\n            Threshold for detection in sigma\n\n        Returns\n        -------\n        locs : numpy.array\n            Array of (x,y) pixel location estimates for the location of point sources\n            above the provided threshold.\n        \"\"\"\n\n        data_max = filters.maximum_filter(snr_map, size=self.fwhm)\n        maxima = (snr_map == data_max)\n        diff = (data_max > threshold)\n        maxima[diff == 0] = 0\n\n        labeled, _ = ndimage.label(maxima)\n        slices = ndimage.find_objects(labeled)\n        x, y = [], []\n        for dy, dx in slices:\n            x_center = (dx.start + dx.stop - 1)/2\n            x.append(x_center)\n            y_center = (dy.start + dy.stop - 1)/2\n            y.append(y_center)\n        return np.array(list(zip(x, y)))\n\n    def compute_statistics(self, phi0s : np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:\n        \"\"\"\n        This function computes the mean and inverse covariance matrix for\n        each patch in the image stack in Serial. Used by FastPACO and flux\n        estimation.\n\n        Parameters\n        ----------\n        phi0s : numpy.ndarray\n            Array of pixel locations to estimate companion position\n\n        Returns\n        -------\n        Cinv : numpy.ndarray\n            Inverse covariance matrix between the the mean of each of the patches.\n            The patches are a column through the time axis of the unrotated\n            science images. Together with the mean this provides an empirical\n            estimate of the background statistics. An inv covariance matrix is provided\n            for each pixel location in ph0s.\n        m : numpy.ndarray\n            Mean of each of the background patches along the time axis, for each pixel location\n            in phi0s.\n        patch : numpy.ndarray\n            The background column for each test pixel location in phi0s.\n        \"\"\"\n        if self.verbose:\n            print(\"Precomputing Statistics...\")\n\n        # Store for each image pixel, for each temporal frame an image\n        # for patches: for each time, we need to store a column of patches\n        patch = np.zeros((self.width, self.height, self.num_frames, self.patch_area_pixels))\n\n        # the mean of a temporal column of patches centered at each pixel\n        m = np.zeros((self.height, self.width, self.patch_area_pixels))\n        # the inverse covariance matrix at each point\n        Cinv = np.zeros((self.height, self.width, self.patch_area_pixels, self.patch_area_pixels))\n\n        # *** SERIAL ***\n        # Loop over all pixels\n        # i is the same as theta_k in the PACO paper\n        for p0 in phi0s:\n            apatch = self.get_patch(p0)\n            # For some black magic reason this needs to be inverted here.\n            m[p0[1]][p0[0]], Cinv[p0[1]][p0[0]] = compute_statistics_at_pixel(apatch)\n            patch[p0[1]][p0[0]] = apatch\n        return Cinv, m, patch\n\n\"\"\"\n**************************************************\n*                                                *\n*                  Fast PACO                     *\n*                                                *\n**************************************************\n\"\"\"\n\n\nclass FastPACO(PACO):\n    \"\"\"\n    This class implements Algorithm 2 from Flasseur+ 2018.\n    \"\"\"\n\n    def PACOCalc(self,\n                 phi0s : np.ndarray,\n                 use_subpixel_psf_astrometry : Optional[bool] = True,\n                 cpu : Optional[int] = 1) -> None:\n        \"\"\"\n        PACOCalc\n\n        This function iterates of a list of test points (phi0) and a list\n        of angles between frames to produce 'a' and b', which can be used to\n        generate a signal to noise map where SNR = b/sqrt(a) at each pixel.\n\n        Parameters\n        ----------\n        phi0s : numpy.ndarray\n            Array of (x,y) pixel locations to estimate companion position\n        use_subpixel_psf_astrometry : bool\n            If true, the PSF model for each patch is shifted to the correct\n            location as predicted by the starting location and the parallactic\n            angles, before being resampled for the patch. If false, the PSF\n            model is simply located at the center of each patch. Significantly\n            improves performance if set to False, but the SNR is reduced.\n        cpu : int\n            Number of cores to use for parallel processing\n\n        Returns\n        -------\n        a : numpy.ndarray\n            a_l from Equation 15 of Flasseur+ 2018\n        b : numpy.ndarray\n            b_l from Equation 16 of Flasseur+ 2018\n        \"\"\"\n        npx = len(phi0s)  # Number of pixels in an image\n        dim = self.width/2\n\n        a = np.zeros(npx)  # Setup output arrays\n        b = np.zeros(npx)\n        phi0s = np.array([phi0s[:,1],phi0s[:,0]]).T\n\n        if cpu == 1:\n            Cinv, m, patches = self.compute_statistics(phi0s)\n        else:\n            Cinv, m, patches = self.compute_statistics_parallel(phi0s, cpu=cpu)\n        normalised_psf = normalize_psf(self.psf,\n                                       fwhm='fit',\n                                       size=None,\n                                       threshold=None,\n                                       mask_core=None,\n                                       model='airy',\n                                       imlib='vip-fft',\n                                       interpolation='lanczos4',\n                                       force_odd=False,\n                                       full_output=False,\n                                       verbose=self.verbose,\n                                       debug=False)\n        psf_mask = create_boolean_circular_mask(normalised_psf.shape, radius=self.fwhm)\n\n        # Create arrays needed for storage\n        # Store for each image pixel, for each temporal frame an image\n        # for patches: for each time, we need to store a column of patches\n\n        # Currently forcing integer grid, but meshgrid takes floats as\n        # arguments...\n        x, y = np.meshgrid(np.arange(-dim, dim), np.arange(-dim, dim))\n        if self.verbose:\n            print(\"Running Fast PACO...\")\n\n        # Loop over all pixels\n        # i is the same as theta_k in the PACO paper\n        for i, p0 in enumerate(phi0s):\n            # Get Angles\n            angles_px = get_rotated_pixel_coords(x, y, p0, self.angles)\n            # Ensure within image bounds\n            if(int(np.max(angles_px.flatten())) >= self.width or\n               int(np.min(angles_px.flatten())) < 0):\n                a[i] = np.nan\n                b[i] = np.nan\n                continue\n\n            # Extract relevant patches and statistics\n            Cinlst = []\n            mlst = []\n            hlst = []\n            patch = []\n            for l, ang in enumerate(angles_px):\n                Cinlst.append(Cinv[int(ang[0]), int(ang[1])])\n                mlst.append(m[int(ang[0]), int(ang[1])])\n                if use_subpixel_psf_astrometry:\n                    offax = frame_shift(normalised_psf,\n                                        ang[1]-int(ang[1]),\n                                        ang[0]-int(ang[0]),\n                                        imlib='vip-fft',\n                                        interpolation='lanczos4',\n                                        border_mode='reflect')[psf_mask]\n                else:\n                    offax = normalised_psf[psf_mask]\n                hlst.append(offax)\n                patch.append(patches[int(ang[0]), int(ang[1]), l])\n\n            # Calculate a and b, matrices\n            a[i] = self.al(hlst, Cinlst)\n            b[i] = self.bl(hlst, Cinlst, patch, mlst)\n        if self.verbose:\n            print(\"Done\")\n        return a, b\n\n    def compute_statistics_parallel(self,\n                                    phi0s: np.ndarray,\n                                    cpu: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:\n        \"\"\"\n        This function computes the mean and inverse covariance matrix for\n        each patch in the image stack in parallel.\n\n        Parameters\n        ----------\n        phi0s : int numpy.ndarray\n            Array of pixel locations to estimate companion position\n        cpu : int\n            Number of processors to use\n\n        Returns\n        -------\n        Cinv : numpy.ndarray\n            Inverse covariance matrix between the the mean of each of the patches.\n            The patches are a column through the time axis of the unrotated\n            science images. Together with the mean this provides an empirical\n            estimate of the background statistics. An inv covariance matrix is provided\n            for each pixel location in ph0s.\n        m : numpy.ndarray\n            Mean of each of the background patches along the time axis, for each pixel location\n            in phi0s.\n        patch : numpy.ndarray\n            The background column for each test pixel location in phi0s.\n\n        \"\"\"\n\n        if self.verbose:\n            print(\"Precomputing Statistics using %d Processes...\"%cpu)\n        # the mean of a temporal column of patches at each pixel\n        m = np.zeros((self.height*self.width*self.patch_area_pixels))\n        # the inverse covariance matrix at each point\n        Cinv = np.zeros((self.height*\n                         self.width*\n                         self.patch_area_pixels*\n                         self.patch_area_pixels))\n\n        # *** Parallel Processing ***\n        p_data = pool_map(cpu, self.get_patch, iterable(phi0s))\n        patches = [p for p in p_data]\n        data = pool_map(cpu, compute_statistics_at_pixel, iterable(patches))\n        # p_pool = Pool(processes=cpu)\n        #p_data = p_pool.map(self.get_patch, phi0s, chunksize=int(npx/cpu))\n        # p_pool.close()\n        # p_pool.join()\n        # patches = [p for p in p_data]\n        # p = Pool(processes=cpu)\n        # data = p.map(compute_statistics_at_pixel, patches, chunksize=int(npx/cpu))\n        # p.close()\n        # p.join()\n        ms, cs = [], []\n        for d in data:\n            if d[0] is None or d[1] is None:\n                ms.append(np.full(self.patch_area_pixels, np.nan))\n                cs.append(np.full((self.patch_area_pixels,\n                                   self.patch_area_pixels), np.nan))\n            else:\n                ms.append(d[0])\n                cs.append(d[1])\n        ms = np.array(ms)\n        cs = np.array(cs)\n        patches = np.array(patches)\n\n        # Reshape outputs\n        patches = patches.reshape((self.width,\n                                   self.height,\n                                   self.num_frames,\n                                   self.patch_area_pixels))\n        m = ms.reshape((self.height,\n                        self.width,\n                        self.patch_area_pixels))\n        Cinv = cs.reshape((self.height,\n                           self.width,\n                           self.patch_area_pixels,\n                           self.patch_area_pixels))\n        patches = np.swapaxes(patches,0,1)\n        m = np.swapaxes(m,0,1)\n        Cinv = np.swapaxes(Cinv,0,1)\n\n        return Cinv, m, patches\n\n\n\"\"\"\n**************************************************\n*                                                *\n*                  Full PACO                     *\n*                                                *\n**************************************************\n\"\"\"\n\n\nclass FullPACO(PACO):\n    \"\"\"\n    Implementation of Algorithm 1 from Flasseur+ 2018\n    \"\"\"\n\n    def PACOCalc(self,\n                 phi0s : np.ndarray,\n                 use_subpixel_psf_astrometry : Optional[bool] = True,\n                 cpu : Optional[int] = 1) -> None:\n        \"\"\"\n        PACOCalc\n\n        This function iterates of a list of test points (phi0) and a list\n        of angles between frames to produce 'a' and b', which can be used to\n        generate a signal to noise map where SNR = b/sqrt(a) at each pixel.\n\n        Parameters\n        ----------\n        phi0s : numpy.ndarray\n            Array of (x,y) pixel locations to estimate companion position\n        use_subpixel_psf_astrometry : bool\n            If true, the PSF model for each patch is shifted to the correct\n            location as predicted by the starting location and the parallactic\n            angles, before being resampled for the patch. If false, the PSF\n            model is simply located at the center of each patch. Significantly\n            improves performance if set to False, but the SNR is reduced.\n        cpu : int\n            Number of cores to use for parallel processing. TODO: Not yet implemented.\n\n        Returns\n        -------\n        a : numpy.ndarray\n            a_l from Equation 15 of Flasseur+ 2018\n        b : numpy.ndarray\n            b_l from Equation 16 of Flasseur+ 2018\n        \"\"\"\n\n        npx = len(phi0s)  # Number of pixels in an image\n        dim = self.width/2\n\n        a = np.zeros(npx)  # Setup output arrays\n        b = np.zeros(npx)\n        normalised_psf = normalize_psf(self.psf,\n                                       fwhm='fit',\n                                       size=None,\n                                       threshold=None,\n                                       mask_core=None,\n                                       model='airy',\n                                       imlib='vip-fft',\n                                       interpolation='lanczos4',\n                                       force_odd=False,\n                                       full_output=False,\n                                       verbose=self.verbose,\n                                       debug=False)\n        psf_mask = create_boolean_circular_mask(normalised_psf.shape, radius=self.fwhm)\n\n        if self.verbose:\n            print(\"Running Full PACO...\")\n\n        # Set up coordinates so 0 is at the center of the image\n        x, y = np.meshgrid(np.arange(-dim, dim), np.arange(-dim, dim))\n\n        if cpu > 1:\n            print(\"Multiprocessing for full PACO is not yet implemented!\")\n\n        # Store intermediate results\n        patch = np.zeros((self.width, self.height, self.num_frames, self.patch_area_pixels))\n        # the mean of a temporal column of patches centered at each pixel\n        m = np.zeros((self.height, self.width, self.patch_area_pixels))\n        # the inverse covariance matrix at each point\n        Cinv = np.zeros((self.height, self.width, self.patch_area_pixels, self.patch_area_pixels))\n\n        # Loop over all pixels\n        # i is the same as theta_k in the PACO paper\n        for i, p0 in enumerate(phi0s):\n            # Get list of pixels for each rotation angle\n            angles_px = get_rotated_pixel_coords(x, y, (p0[1],p0[0]), self.angles)\n\n            # Ensure within image bounds\n            if(int(np.max(angles_px.flatten())) >= self.width or\n               int(np.min(angles_px.flatten())) < 0):\n                a[i] = np.nan\n                b[i] = np.nan\n                continue\n\n            # Iterate over each temporal frame/each angle\n            # Same as iterating over phi_l\n            current_patch = []\n            mlst = []\n            h = []\n            clst = []\n            for l, ang in enumerate(angles_px):\n                # Get the column of patches at this point\n                if np.max(patch[int(ang[0]),int(ang[1])]) == 0:\n                    apatch = self.get_patch((int(ang[1]),int(ang[0])))\n                    patch[int(ang[0]),int(ang[1])] = apatch\n                    m[int(ang[0]),int(ang[1])], Cinv[int(ang[0]),int(ang[1])] = compute_statistics_at_pixel(apatch)\n                else:\n                    apatch = patch[int(ang[0]),int(ang[1])]\n                if apatch is None:\n                    continue\n                mlst.append(m[int(ang[0]),int(ang[1])])\n                clst.append(Cinv[int(ang[0]),int(ang[1])])\n\n                current_patch.append(apatch)\n                if use_subpixel_psf_astrometry:\n                    offax = frame_shift(normalised_psf,\n                                        ang[1]-int(ang[1]),\n                                        ang[0]-int(ang[0]),\n                                        imlib='vip-fft',\n                                        interpolation='lanczos4',\n                                        border_mode='reflect')[psf_mask]\n                else:\n                    offax = normalised_psf[psf_mask]\n\n                h.append(offax)\n            current_patch = np.array(current_patch)\n            patches = np.array([current_patch[l,l] for l in range(len(angles_px))])\n            h = np.array(h)\n            mlst = np.array(mlst)\n            clst = np.array(clst)\n            # Calculate a and b, matrices\n            a[i] = self.al(h, clst)\n            b[i] = self.bl(h, clst, patches, mlst)\n        if self.verbose:\n            print(\"Done\")\n        return a, b\n\n\n\"\"\"\nMath functions for computing patch covariance\n\"\"\"\n\n\ndef compute_statistics_at_pixel(\n        patch: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n    \"\"\"\n    Calculate the mean and inverse covariance within a patch\n    Reimplemented in PACO class, can probably be deleted\n\n    Parameters\n    ----------\n    patch : numpy.ndarray\n        Array of circular (flattened) patches centered on the same physical\n        pixel vertically throughout the image stack\n    \"\"\"\n\n    if patch is None:\n        return None, None\n    T = patch.shape[0]\n    #size = patch.shape[1]\n\n    # Calculate the mean of the column\n    m = np.mean(patch, axis=0)\n    # Calculate the covariance matrix\n    S = sample_covariance(patch, m, T)\n    rho = shrinkage_factor(S, T)\n    F = diagsample_covariance(S)\n    C = covariance(rho, S, F)\n    Cinv = np.linalg.inv(C)\n    return m, Cinv\n\n\ndef covariance(rho: np.ndarray, S: np.ndarray, F: np.ndarray) -> np.ndarray:\n    \"\"\"\n    Ĉ: Shrinkage covariance matrix\n\n    Parameters\n    ----------\n    rho : float\n        Shrinkage factor weight\n    S : numpy.ndarray\n        Sample covariance matrix\n    F : numpy.ndarray\n        Diagonal of sample covariance matrix\n\n    Returns\n    -------\n    m : numpy.ndarray\n        Mean of each of the background patches along the time axis.\n    Cinv : numpy.ndarray\n        Inverse covariance matrix between the the mean of each of the patches.\n        The patches are a column through the time axis of the unrotated\n        science images. Together with the mean this provides an empirical\n        estimate of the background statistics.\n    \"\"\"\n\n    C = (1.0-rho)*S + rho*F\n    return C\n\n\ndef sample_covariance(r: np.ndarray, m: np.ndarray,\n                      T: np.ndarray) -> np.ndarray:\n    \"\"\"\n    Ŝ: Sample covariance matrix\n\n    Parameters\n    ----------\n    r : numpy.ndarray\n        Observed intensity at position θk and time tl\n    m : numpy.ndarray\n        Mean of all background patches at position θk\n    T : int\n        Number of temporal frames\n\n    Returns\n    -------\n    S : numpy.ndarray\n        Sample covariance\n    \"\"\"\n\n    #S = (1.0/T)*np.sum([np.outer((p-m).ravel(),(p-m).ravel().T) for p in r], axis=0)\n    S = (1.0/T)*np.sum([np.cov(np.stack((p, m)),\n                               rowvar=False, bias=False) for p in r], axis=0)\n    return S\n\n\ndef diagsample_covariance(S: np.ndarray) -> np.ndarray:\n    \"\"\"\n    F: Diagonal elements of the sample covariance matrix\n\n    Parameters\n    ----------\n    S : arr\n        Sample covariance matrix\n\n    Returns\n    -------\n    F : numpy.ndarray\n        Diagonal elements of the sample covariance matrix\n    \"\"\"\n\n    return np.diag(np.diag(S))\n\n\ndef shrinkage_factor(S: np.ndarray, T: np.ndarray) -> float:\n    \"\"\"\n    ρ: Shrinkage factor to regularize covariant matrix\n\n    Parameters\n    ----------\n    S : numpy.ndarray\n        Sample covariance matrix\n    T : int\n        Number of temporal frames\n\n    Returns\n    -------\n    ρ : float\n        Shrinkage factor to regularize covariant matrix\n    \"\"\"\n\n    top = (np.trace(np.dot(S, S)) + np.trace(S)**2 -\n           2.0*np.sum(S**2.0))\n    bot = ((T+1.0)*(np.trace(np.dot(S, S)) -\n                    np.sum(np.diag(S)**2.0)))\n    p = top/bot\n    return max(min(p, 1.0), 0.0)\n\n\ndef get_rotated_pixel_coords(x: np.ndarray,\n                             y: np.ndarray,\n                             p0: Tuple[int, int],\n                             angles: np.ndarray,\n                             astro_convention: Optional[bool] = False) -> np.ndarray:\n    \"\"\"\n    For a given pixel, find the new pixel location after a rotation for each angle in angles\n\n    Parameters\n    ----------\n    x : numpy.ndarrayr\n        Grid of x components of pixel coordinates\n    y : numpy.ndarrayr\n        Grid of y components of pixel coordinates\n    p0 : (int,int)\n        Initial pixel location\n    angles : numpy.ndarrayr\n        List of angles for which to compute the new pixel location\n    Returns\n    -------\n    nx : numpy.ndarray\n        New array of x pixels coordinates following the rotation\n    ny : numpy.ndarray\n        New array of y pixels coordinates following the rotation\n\n    \"\"\"\n    # Current pixel\n    phi0 = np.array([x[int(p0[0]), int(p0[1])], y[int(p0[0]), int(p0[1])]])\n\n    # Convert to polar coordinates\n    rad, theta = cart_to_pol(\n        phi0[0], phi0[1], astro_convention=astro_convention)\n\n    # Rotate by parallactic angles\n    angles_rad = -1*angles + theta\n\n    # Rotate the polar coordinates by each frame angle\n    angles_pol = np.array([rad*np.ones_like(angles_rad), angles_rad])\n\n    # Find the new pixel coordinates after rotation\n    nx, ny = pol_to_cart(\n        angles_pol[0], angles_pol[1], astro_convention=astro_convention)\n\n    # Shift to center coordinates (central pixel is 0)\n    # TODO - use vip cx, cy arguments rather than shifting after?\n    nx += +int(x.shape[0]/2)\n    ny += +int(x.shape[0]/2)\n    return np.array([nx, ny]).T\n\n\ndef create_boolean_circular_mask(shape: np.ndarray,\n                                 radius: Optional[int] = 4,\n                                 center: Optional[Tuple[int, int]] = None) -> np.ndarray:\n    \"\"\"\n    Returns a 2D boolean mask given some radius and location\n\n    Parameters\n    ----------\n    shape : numpy.ndarray\n        Shape of a 2D numpy array\n    radius : int\n        Radius of the mask in pixels\n    center : (int,int)\n        Pixel coordinates denoting the center of the mask,\n        None defaults to center of shape\n\n    Returns\n    -------\n    mask : numpy.ndarray\n        A boolean mask of the the same shape as the science\n        input data (provided by shape argument). The mask is 0\n        outside of a circular region located at center, with a specified radius.\n    \"\"\"\n\n    w = shape[0]\n    h = shape[1]\n    if center is None:\n        center = [int(w/2), int(h/2)]\n    if radius is None:\n        radius = min(center[0], center[1], w-center[0], h-center[1])\n    X, Y = np.ogrid[:w, :h]\n    dist2 = (X - center[0])**2 + (Y-center[1])**2\n    mask = dist2 <= radius**2\n    return mask\n", "meta": {"hexsha": "e383818545d1cb96ab573a10261dcdb4a0f4de3a", "size": 54303, "ext": "py", "lang": "Python", "max_stars_repo_path": "vip_hci/invprob/paco.py", "max_stars_repo_name": "carlgogo/vip_exoplanets", "max_stars_repo_head_hexsha": "52bd0d7b1503a2b317b1187c429b8fe7fca545b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-07-23T11:43:59.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-23T11:43:59.000Z", "max_issues_repo_path": "vip_hci/invprob/paco.py", "max_issues_repo_name": "carlgogo/vip_exoplanets", "max_issues_repo_head_hexsha": "52bd0d7b1503a2b317b1187c429b8fe7fca545b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vip_hci/invprob/paco.py", "max_forks_repo_name": "carlgogo/vip_exoplanets", "max_forks_repo_head_hexsha": "52bd0d7b1503a2b317b1187c429b8fe7fca545b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8989971347, "max_line_length": 115, "alphanum_fraction": 0.5458261974, "include": true, "reason": "import numpy,from scipy", "num_tokens": 12000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.29098086621490676, "lm_q1q2_score": 0.15457176360577343}}
{"text": "\nimport pkg_resources\nimport os\nimport pdb\nfrom astropy.io import fits\nimport astropy.constants as const\nimport astropy.units as u\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nimport tayph.util as ut\nfrom tayph.vartests import typetest,dimtest\nimport tayph.tellurics as mol\nimport tayph.system_parameters as sp\nimport tayph.functions as fun\nimport tayph.operations as ops\nfrom tayph.ccf import xcor\nimport copy\nimport scipy.interpolate as interp\nimport pickle\nfrom pathlib import Path\nimport warnings\nimport glob\nfrom scipy import interpolate\nimport tayph.masking as masking\nimport subprocess\nimport textwrap\nfrom astropy.utils.data import download_file\nfrom .phoenix import get_phoenix_wavelengths, get_phoenix_model_spectrum\nfrom scipy.ndimage import uniform_filter1d\n\n\n__all__ = [\n    \"read_harpslike\",\n    \"read_espresso\",\n    \"read_uves\",\n    \"read_spirou\",\n    \"read_gianob\"\n]\n\n\n\ndef read_harpslike(inpath,filelist,mode,read_s1d=True):\n    \"\"\"\n    This reads a folder of HARPS or HARPSN data. Input is a list of filepaths and the mode (HARPS\n    or HARPSN).\n    \"\"\"\n\n    if mode=='HARPS':\n        catkeyword = 'HIERARCH ESO DPR CATG'\n        bervkeyword = 'HIERARCH ESO DRS BERV'\n        thfilekeyword = 'HIERARCH ESO DRS CAL TH FILE'\n        Zstartkeyword = 'HIERARCH ESO TEL AIRM START'\n        Zendkeyword = 'HIERARCH ESO TEL AIRM END'\n    elif mode=='HARPSN':\n        catkeyword = 'OBS-TYPE'\n        bervkeyword = 'HIERARCH TNG DRS BERV'\n        thfilekeyword = 'HIERARCH TNG DRS CAL TH FILE'\n        Zstartkeyword = 'AIRMASS'\n        Zendkeyword = 'AIRMASS'#These are the same because HARPSN doesnt have start and end keywords.\n        #Down there, the airmass is averaged, so there is no problem in taking the average of the same number.\n    else:\n        raise ValueError(f\"Error in read_harpslike: mode should be set to HARPS or HARPSN ({mode})\")\n\n    #The following variables define lists in which all the necessary data will be stored.\n    framename=[]\n    header=[]\n    s1dhdr=[]\n    obstype=[]\n    texp=np.array([])\n    date=[]\n    mjd=np.array([])\n    s1dmjd=np.array([])\n    npx=np.array([])\n    norders=np.array([])\n    e2ds=[]\n    s1d=[]\n    wave1d=[]\n    airmass=np.array([])\n    berv=np.array([])\n    wave=[]\n    # wavefile_used = []\n    for i in range(len(filelist)):\n        if filelist[i].endswith('e2ds_A.fits'):\n            print(f'------{filelist[i]}', end=\"\\r\")\n            hdul = fits.open(inpath/filelist[i])\n            data = copy.deepcopy(hdul[0].data)\n            hdr = hdul[0].header\n            hdul.close()\n            del hdul[0].data\n            if hdr[catkeyword] == 'SCIENCE':\n                framename.append(filelist[i])\n                header.append(hdr)\n                obstype.append(hdr[catkeyword])\n                texp=np.append(texp,hdr['EXPTIME'])\n                date.append(hdr['DATE-OBS'])\n                mjd=np.append(mjd,hdr['MJD-OBS'])\n                npx=np.append(npx,hdr['NAXIS1'])\n                norders=np.append(norders,hdr['NAXIS2'])\n                e2ds.append(data)\n                berv=np.append(berv,hdr[bervkeyword])\n                airmass=np.append(airmass,0.5*(hdr[Zstartkeyword]+hdr[Zendkeyword]))#This is an approximation where we take the mean airmass.\n                # if nowave == True:\n                # wavefile_used.append(hdr[thfilekeyword])\n                #Record which wavefile was used by the pipeline to\n                #create the wavelength solution.\n                wavedata=ut.read_wave_from_e2ds_header(hdr,mode=mode)/10.0#convert to nm.\n                wave.append(wavedata)\n                # if filelist[i].endswith('wave_A.fits'):\n                #     print(filelist[i]+' (wave)')\n                #     if nowave == True:\n                #         warnings.warn(\" in read_e2ds: nowave was set to True but a wave_A file was detected. This wave file is now ignored in favor of the header.\",RuntimeWarning)\n                #     else:\n                #         wavedata=fits.getdata(inpath/filelist[i])\n                #         wave.append(wavedata)\n\n                if read_s1d:\n                    s1d_path=inpath/Path(str(filelist[i]).replace('e2ds_A.fits','s1d_A.fits'))\n                    ut.check_path(s1d_path,exists=True)#Crash if the S1D doesn't exist.\n        # if filelist[i].endswith('s1d_A.fits'):\n                    hdul = fits.open(s1d_path)\n                    data_1d = copy.deepcopy(hdul[0].data)\n                    hdr1d = hdul[0].header\n                    hdul.close()\n                    del hdul\n            # if hdr[catkeyword] == 'SCIENCE':\n                    s1d.append(data_1d)\n                    if mode == 'HARPSN':#In the case of HARPS-N we need to convert the units of the\n                        #elevation and provide a UTC keyword.\n                        hdr1d['TELALT'] = np.degrees(float(hdr1d['EL']))\n                        hdr1d['UTC'] = (float(hdr1d['MJD-OBS'])%1.0)*86400.0\n                    s1dhdr.append(hdr1d)\n                    s1dmjd=np.append(s1dmjd,hdr1d['MJD-OBS'])\n                    berv1d = hdr1d[bervkeyword]\n                    if berv1d != hdr[bervkeyword]:\n                        wrn_msg = ('WARNING in read_harpslike(): BERV correction of s1d file is not'\n                        f'equal to that of the e2ds file. {berv1d} vs {hdr[bervkeyword]}')\n                        ut.tprint(wrn_msg)\n                    gamma = (1.0-(berv1d*u.km/u.s/const.c).decompose().value)#Doppler factor BERV.\n                    wave1d.append((hdr1d['CDELT1']*np.arange(len(data_1d), dtype=float)+hdr1d['CRVAL1'])*gamma)\n\n    #Check that all exposures have the same number of pixels, and clip s1ds if needed.\n    # min_npx1d = int(np.min(np.array(npx1d)))\n    # if np.sum(np.abs(np.array(npx1d)-npx1d[0])) != 0:\n    #     warnings.warn(\"in read_e2ds when reading HARPS data: Not all s1d files have the same number of pixels. This could have happened if the pipeline has extracted one or two extra pixels in some exposures but not others. The s1d files will be clipped to the smallest length.\",RuntimeWarning)\n    #     for i in range(len(s1d)):\n    #         wave1d[i]=wave1d[i][0:min_npx1d]\n    #         s1d[i]=s1d[i][0:min_npx1d]\n    #         npx1d[i]=min_npx1d\n    output = {'wave':wave,'e2ds':e2ds,'header':header,'wave1d':wave1d,'s1d':s1d,'s1dhdr':s1dhdr,\n    'mjd':mjd,'date':date,'texp':texp,'obstype':obstype,'framename':framename,'npx':npx,\n    'norders':norders,'berv':berv,'airmass':airmass,'s1dmjd':s1dmjd}\n    return(output)\n\ndef read_carmenes(inpath,filelist,channel,construct_s1d=True):\n    \"\"\"\n    This reads a folder of CARMENES visible (VIS) or infra-red (NIR) channel data. Input is a list\n    of filepaths and the mode ('VIS' or 'NIR').\n    \"\"\"\n\n\n\n    catkeyword = 'HIERARCH CAHA INS ICS IMAGETYP'\n    bervkeyword = 'HIERARCH CARACAL BERV'\n    thfilekeyword = 'HIERARCH CARACAL WAVE FILE'\n    Zstartkeyword = 'AIRMASS'\n    Zendkeyword = 'AIRMASS'#These are the same because CARMENES doesnt have start and end keywords.\n\n    if channel not in ['vis','nir']:\n        raise ValueError(f\"Error in read_carmenes: channel should be set to VIS or NIR ({channel})\")\n\n    #The following variables define lists in which all the necessary data will be stored.\n    framename=[]\n    header=[]\n    s1dhdr=[]\n    obstype=[]\n    texp=np.array([])\n    date=[]\n    mjd=np.array([])\n    s1dmjd=np.array([])\n    npx=np.array([])\n    norders=np.array([])\n    e2ds=[]\n    blaze=[]\n    s1d=[]\n    wave1d=[]\n    airmass=np.array([])\n    berv=np.array([])\n    wave=[]\n    # wavefile_used = []\n    for i in range(len(filelist)):\n        if filelist[i].endswith('-'+channel.lower()+'_A.fits'):\n            print(f'------{filelist[i]}', end=\"\\r\")\n            hdul = fits.open(inpath/filelist[i])\n            data = copy.deepcopy(hdul[1].data)\n            cont = copy.deepcopy(hdul[2].data)\n            sigma = copy.deepcopy(hdul[3].data)\n            wavedata = copy.deepcopy(hdul[4].data)/10.0\n            hdr = hdul[0].header\n            spechdr = hdul[1].header\n            hdul.close()\n            del hdul[1].data\n            del hdul[2].data\n            del hdul[3].data\n            del hdul[4].data\n            if hdr[catkeyword] == 'SCIENCE':\n                framename.append(filelist[i])\n                header.append(hdr)\n                obstype.append(hdr[catkeyword])\n                texp=np.append(texp,hdr['EXPTIME'])\n                date.append(hdr['DATE-OBS'])\n                mjd=np.append(mjd,hdr['MJD-OBS'])\n                npx=np.append(npx,spechdr['NAXIS1'])\n                norders=np.append(norders,spechdr['NAXIS2'])\n                e2ds.append(data)\n                blaze.append(data/sigma**2)\n                berv=np.append(berv,hdr[bervkeyword])\n                airmass=np.append(airmass,0.5*(hdr[Zstartkeyword]+hdr[Zendkeyword]))#This is an approximation where we take the mean airmass.\n                wave.append(ops.vactoair(wavedata))\n\n\n                if construct_s1d:\n                    wave_1d, data_1d = spec_stich_n_norm(data,wavedata,cont,sigma)\n\n                    s1d.append(data_1d)\n\n                    hdr1d = copy.deepcopy(hdr)\n                    hdr1d['UTC'] = (float(hdr1d['MJD-OBS'])%1.0)*86400.0\n                    s1dhdr.append(hdr1d)\n                    s1dmjd=np.append(s1dmjd,hdr1d['MJD-OBS'])\n                    berv1d = hdr1d[bervkeyword]\n                    gamma = (1.0-(berv1d*u.km/u.s/const.c).decompose().value)#Doppler factor BERV.\n                    gamma = 1 #turning berv off\n                    wave1d.append(ops.vactoair(wave_1d)*gamma*10)\n\n    BLAZE_Model = blaze_model(np.nanmean(blaze, axis = 0)) #Calucalting blaze model\n    e2ds = list(e2ds*BLAZE_Model[np.newaxis,:]) #Deblazing the data\n\n    if construct_s1d:\n        output = {'wave':wave,'e2ds':e2ds,'header':header,'wave1d':wave1d,'s1d':s1d,'s1dhdr':s1dhdr,\n        'mjd':mjd,'date':date,'texp':texp,'obstype':obstype,'framename':framename,'npx':npx,\n        'norders':norders,'berv':berv,'airmass':airmass,'s1dmjd':s1dmjd}\n    else:\n        output = {'wave':wave,'e2ds':e2ds,'header':header,\n        'mjd':mjd,'date':date,'texp':texp,'obstype':obstype,'framename':framename,'npx':npx,\n        'norders':norders,'berv':berv,'airmass':airmass}\n    return(output)\n\n\ndef spec_stich_n_norm(spec, wave, cont, sig):\n    \"\"\"This stitches and continuum normalises CARMENES E2DS spectra into 1D spectra for use in\n    molecfit.\n    N. Borsato - 24-02-2021\"\"\"\n\n    import numpy as np\n    from astropy.io import fits\n    from scipy.interpolate import interp1d\n\n    #These arrays will be filled with the stiched data.\n    Total_Specs = np.array([])\n    Total_Waves = np.array([])\n    Total_Cont = np.array([])\n\n    step_size = np.diff(wave)\n    step_size = np.min(step_size[step_size>0])/2\n\n    for i in range(len(spec)-1):\n\n        waves = np.linspace(np.min(wave[i]), np.max(wave[i+1]), 4*wave[i:i+1].size) #Specifiying wavelength grid\n\n        #Interpolating the spectral orders to the new grid for both the current and proceeding order\n        I_spectra_1 = interp1d(wave[i], spec[i], bounds_error = False) #Intep for spectra\n        I_spectra_2 = interp1d(wave[i+1], spec[i+1], bounds_error = False)\n\n        I_sig_1 = interp1d(wave[i], sig[i], bounds_error = False) #Interp for sig vals\n        I_sig_2 = interp1d(wave[i+1], sig[i+1], bounds_error = False)\n\n        I_cont_1 = interp1d(wave[i], cont[i], bounds_error = False) #Interp for continuum vals\n        I_cont_2 = interp1d(wave[i+1], cont[i+1], bounds_error = False)\n\n        #Using interpolator to create a vecotr of the same length for both orders.\n        ## Note: If the order doesn't span the wavelength range it creates a nan\n        I_spectra_1 = I_spectra_1(waves)\n        I_spectra_2 = I_spectra_2(waves)\n\n        I_sig_1 = I_sig_1(waves)\n        I_sig_2 = I_sig_2(waves)\n\n        I_cont_1 = I_cont_1(waves)\n        I_cont_2 = I_cont_2(waves)\n\n        #If a nan value is present, replace the value with the corresponding value of the other interpolated vecotor\n        ## This creates an overlapping vecotr of the same value, which means you can take an average and get the same value\n        I_spectra_1 = np.nan_to_num(I_spectra_1, nan = I_spectra_2)\n        I_spectra_2 = np.nan_to_num(I_spectra_2, nan = I_spectra_1)\n\n        I_sig_1 = np.nan_to_num(I_sig_1, nan = I_sig_2)\n        I_sig_2 = np.nan_to_num(I_sig_2, nan = I_sig_1)\n\n        I_cont_1 = np.nan_to_num(I_cont_1, nan = I_cont_2)\n        I_cont_2 = np.nan_to_num(I_cont_2, nan = I_cont_1)\n\n        Spec_Combo = np.array([I_spectra_1, I_spectra_2]) #Combing spectra as 2d array\n        Spec_Combo = Spec_Combo.T #Take transpose to pair the data values\n\n        #Do the same for the sig values and continuum\n        Sig_Combo = np.array([I_sig_1, I_sig_2])\n        Sig_Combo = Sig_Combo.T\n\n        Cont_Combo = np.array([I_cont_1, I_cont_2])\n        Cont_Combo = Cont_Combo.T\n\n        #Money is made here, a weighted average is taken using the sig values than normalise by dividing by the continuu,\n        Ave_Spec = np.average(Spec_Combo, weights = 1/(Sig_Combo**2), axis = 1)/np.average(Cont_Combo, axis = 1)\n        Ave_Spec = Ave_Spec.T\n\n        #Averages are append with their corresponding wavlength\n        Total_Specs = np.append(Total_Specs, Ave_Spec)\n        Total_Waves = np.append(Total_Waves, waves)\n        #Total_Cont = np.append(Total_Cont, np.average(Cont_Combo, axis = 1))\n\n    #Reaorder values to a new grid to create the final stiched spectra\n    waves = np.arange(np.min(Total_Waves), np.max(Total_Waves), step_size)\n    I_T_Spectra = interp1d(Total_Waves, Total_Specs)\n\n    return waves, I_T_Spectra(waves) #returns wavelength grid and the normalised flux values\n\ndef blaze_model(blaze,sdev=3):\n    \"\"\"Applies running average fit of the blaze order data.\n        args:\n            blaze: the average escelle blaze data\n            sdev: stanrard deviation cutoff\n\n        returns:\n            a: the mean blaze model\n    \"\"\"\n\n    def nan_helper(data): #Function which allows interpolation though nans\n        return lambda z: z.nonzero()[0]\n\n    blaze = blaze.copy()\n    data = blaze.copy()\n\n    nan_mask = np.isnan(blaze)\n    no_nan = nan_helper(blaze)\n\n    #This will re-create the dataset but will interpolate though the nans giving it a place holder average value\n    blaze[nan_mask]= np.interp(no_nan(nan_mask), no_nan(~nan_mask), blaze[~nan_mask], period = 1)\n\n    a = uniform_filter1d(blaze,size=300,mode=\"nearest\")#Applies moving averages on data\n\n    #Takes difference the replaces datavalues which fall less 3 std of mean trend with mean\n    diff = blaze - a\n    cleaned_blaze_1 = blaze\n    cleaned_blaze_1[diff<-sdev*np.std(diff)] = a[diff<-sdev*np.std(diff)]\n\n    #Repeats process on the new data but masks out datavalues which fall outside 3std in both directions\n    a = uniform_filter1d(cleaned_blaze_1,size=300,mode=\"nearest\")\n    diff = blaze - a\n    cleaned_blaze_2 = cleaned_blaze_1\n    cleaned_blaze_2[np.absolute(diff)>sdev*np.std(diff)] = a[np.absolute(diff)>sdev*np.std(diff)]\n    a = uniform_filter1d(cleaned_blaze_1,size=300,mode=\"nearest\")\n\n    #Replace all positions that contanined nan values initially with nans again\n    a[np.isnan(data)] = data[np.isnan(data)]\n\n    return a\n\n\n\ndef read_uves(inpath,filelist,mode):\n    \"\"\"This reads a folder of UVES-blue or UVES-red intermediate pipeline products. Input is a list of filepaths and the mode.\"\"\"\n    #The following variables define lists in which all the necessary data will be stored.\n    framename=[]\n    header=[]\n    s1dhdr=[]\n    obstype=[]\n    texp=np.array([])\n    date=[]\n    mjd=np.array([])\n    s1dmjd=np.array([])\n    npx=np.array([])\n    npx1d=np.array([])\n    norders=np.array([])\n    e2ds=[]\n    s1d=[]\n    wave1d=[]\n    airmass=np.array([])\n    berv=np.array([])\n    wave=[]\n    catkeyword = 'HIERARCH ESO DPR CATG'\n    bervkeyword = 'HIERARCH ESO DRS BERV'\n    thfilekeyword = 'HIERARCH ESO DRS CAL TH FILE'\n    Zstartkeyword = 'HIERARCH ESO TEL AIRM START'\n    Zendkeyword = 'HIERARCH ESO TEL AIRM END'\n    for i in range(len(filelist)):\n        print(f'------{filelist[i]}', end=\"\\r\")\n        if (inpath/Path(filelist[i])).is_dir():\n            tmp_products = [i for i in (inpath/Path(filelist[i])).glob('resampled_science_*.fits')]\n            tmp_products1d = [i for i in (inpath/Path(filelist[i])).glob('red_science_*.fits')]\n            if mode == 'UVES-red' and len(tmp_products) != 2:\n                raise ValueError(f\"in read_e2ds: When mode=UVES-red there should be 2 resampled_science files (redl and redu), but {len(tmp_products)} were detected in {str(inpath/Path(filelist[i]))}.\")\n            if mode == 'UVES-blue' and len(tmp_products) != 1:\n                raise ValueError(f\"in read_e2ds: When mode=UVES-rblue there should be 1 resampled_science files (blue), but {len(tmp_products)} were detected in {str(inpath/Path(filelist[i]))}.\")\n            if mode == 'UVES-red' and len(tmp_products1d) != 2:\n                raise ValueError(f\"in read_e2ds: When mode=UVES-red there should be 2 red_science files (redl and redu), but {len(tmp_products1d)} were detected in {str(inpath/Path(filelist[i]))}.\")\n            if mode == 'UVES-blue' and len(tmp_products1d) != 1:\n                raise ValueError(f\"in read_e2ds: When mode=UVES-rblue there should be 1 red_science files (blue), but {len(tmp_products1d)} were detected in {str(inpath/Path(filelist[i]))}.\")\n\n            data_combined = []#This will store the two chips (redu and redl) in case of UVES_red, or simply the blue chip if otherwise.\n            wave_combined = []\n            wave1d_combined=[]\n            data1d_combined=[]\n            norders_tmp = 0\n            for tmp_product in tmp_products:\n                hdul = fits.open(tmp_product)\n                data = copy.deepcopy(hdul[0].data)\n                hdr = hdul[0].header\n                hdul.close()\n                del hdul[0].data\n                if not hdr['HIERARCH ESO PRO SCIENCE']:#Only add if it's actually a science product:#I force the user to supply only science exposures in the input  folder. No BS allowed... UVES is hard enough as it is.\n                    raise ValueError(f' in read_e2ds: UVES file {tmp_product} is not classified as a SCIENCE file, but should be. Remove it from the folder?')\n                wavedata=ut.read_wave_from_e2ds_header(hdr,mode='UVES')/10.0#Convert to nm.\n                data_combined.append(data)\n                wave_combined.append(wavedata)\n                norders_tmp+=np.shape(data)[0]\n\n            for tmp_product in tmp_products1d:\n                hdul = fits.open(tmp_product)\n                data_1d = copy.deepcopy(hdul[0].data)\n                hdr1d = hdul[0].header\n                hdul.close()\n                del hdul[0].data\n                if not hdr1d['HIERARCH ESO PRO SCIENCE']:#Only add if it's actually a science product:#I force the user to supply only science exposures in the input  folder. No BS allowed... UVES is hard enough as it is.\n                    raise ValueError(f' in read_e2ds: UVES file {tmp_product} is not classified as a SCIENCE file, but should be. Remove it from the folder?')\n                npx_1d = hdr1d['NAXIS1']\n                wavedata = np.arange(npx_1d, dtype=float)*hdr1d['CDELT1']+hdr1d['CRVAL1']\n                data1d_combined.append(data_1d)\n                wave1d_combined.append(wavedata)\n\n            if len(data_combined) < 1 or len(data_combined) > 2:#Double-checking that length here...\n                raise ValueError(f'in read_e2ds(): Expected 1 or 2 chips, but {len(data_combined)} files were somehow read.')\n            #The chips generally don't give the same size. Therefore I will pad the smaller one with NaNs to make it fit:\n            if len(data_combined) != len(data1d_combined):\n                raise ValueError(f'in read_e2ds(): The number of chips in the 1d and 2d spectra is not the same {len(data1d_combined)} vs {len(data_combined)}.')\n\n            if len(data_combined) == 2:\n                chip1 = data_combined[0]\n                chip2 = data_combined[1]\n                wave1 = wave_combined[0]\n                wave2 = wave_combined[1]\n                npx_1 = np.shape(chip1)[1]\n                npx_2 = np.shape(chip2)[1]\n                no_1 = np.shape(chip1)[0]\n                no_2 = np.shape(chip2)[0]\n                npx_max = np.max([npx_1,npx_2])\n                npx_min = np.min([npx_1,npx_2])\n                diff = npx_max-npx_min\n                #Pad the smaller one with NaNs to match the wider one:\n                if npx_1 < npx_2:\n                    chip1=np.hstack([chip1,np.zeros((no_1,diff))*np.nan])\n                    wave1=np.hstack([wave1,np.zeros((no_1,diff))*np.nan])\n                else:\n                    chip2=np.hstack([chip2,np.zeros((no_2,diff))*np.nan])\n                    wave2=np.hstack([wave2,np.zeros((no_2,diff))*np.nan])\n                #So now they can be stacked:\n                e2ds_stacked = np.vstack((chip1,chip2))\n                wave_stacked = np.vstack((wave1,wave2))\n                if np.shape(e2ds_stacked)[1] != np.shape(wave_stacked)[1]:\n                    raise ValueError(\"Width of stacked e2ds and stacked wave frame are not the same. Is the wavelength solution in the header of this file correct?\")\n                npx=np.append(npx,np.shape(e2ds_stacked)[1])\n\n                e2ds.append(e2ds_stacked)\n                wave.append(wave_stacked)\n                chip1_1d = data1d_combined[0]\n                chip2_1d = data1d_combined[1]\n                wave1_1d = wave1d_combined[0]\n                wave2_1d = wave1d_combined[1]\n                if np.nanmean(wave1_1d) < np.nanmean(wave2_1d):\n                    combined_data_1d = np.concatenate((chip1_1d,chip2_1d))\n                    combined_wave_1d = np.concatenate((wave1_1d,wave2_1d))\n                else:\n                    combined_data_1d = np.concatenate((chip2_1d,chip1_1d))\n                    combined_wave_1d = np.concatenate((wave2_1d,wave1_1d))\n                wave1d.append(combined_wave_1d)\n                s1d.append(combined_data_1d)\n                npx1d=np.append(npx1d,len(combined_wave_1d))\n            else:\n                e2ds.append(data_combined[0])\n                wave.append(wave_combined[0])\n                npx=np.append(npx,np.shape(data_combined[0])[1])\n                wave1d.append(wave1d_combined[0])\n                s1d.append(data1d_combined[0])\n                npx1d=np.append(npx1d,len(combined_wave_1d))\n            #Only using the keyword from the second header in case of redl,redu.\n            s1dmjd=np.append(s1dmjd,hdr1d['MJD-OBS'])\n            framename.append(hdr['ARCFILE'])\n            header.append(hdr)\n            obstype.append('SCIENCE')\n            texp=np.append(texp,hdr['EXPTIME'])\n            date.append(hdr['DATE-OBS'])\n            mjd=np.append(mjd,hdr['MJD-OBS'])\n            norders=np.append(norders,norders_tmp)\n            airmass=np.append(airmass,0.5*(hdr[Zstartkeyword]+hdr[Zendkeyword]))#This is an approximation where we take the mean airmass.\n            berv_i=sp.calculateberv(hdr['MJD-OBS'],hdr['HIERARCH ESO TEL GEOLAT'],hdr['HIERARCH ESO TEL GEOLON'],hdr['HIERARCH ESO TEL GEOELEV'],hdr['RA'],hdr['DEC'])\n            berv = np.append(berv,berv_i)\n            hdr1d['HIERARCH ESO QC BERV']=berv_i#Append the berv here using the ESPRESSO berv keyword, so that it can be used in molecfit later.\n            s1dhdr.append(hdr1d)\n\n    #Check that all exposures have the same number of pixels, and clip orders if needed.\n    min_npx = int(np.min(np.array(npx)))\n    min_npx1d = int(np.min(np.array(npx1d)))\n    if np.sum(np.abs(np.array(npx)-npx[0])) != 0:\n        warnings.warn(\"in read_e2ds when reading UVES data: Not all e2ds files have the same number of pixels. This could have happened if the pipeline has extracted one or two extra pixels in some exposures but not others. The e2ds files will be clipped to the smallest width.\",RuntimeWarning)\n        for i in range(len(e2ds)):\n            wave[i]=wave[i][:,0:min_npx]\n            e2ds[i]=e2ds[i][:,0:min_npx]\n            npx[i]=min_npx\n    if np.sum(np.abs(np.array(npx1d)-npx1d[0])) != 0:\n        warnings.warn(\"in read_e2ds when reading UVES data: Not all s1d files have the same number of pixels. This could have happened if the pipeline has extracted one or two extra pixels in some exposures but not others. The s1d files will be clipped to the smallest width.\",RuntimeWarning)\n        for i in range(len(s1d)):\n            wave1d[i]=wave1d[i][0:min_npx1d]\n            s1d[i]=s1d[i][0:min_npx1d]\n            npx1d[i]=min_npx1d\n    output = {'wave':wave,'e2ds':e2ds,'header':header,'wave1d':wave1d,'s1d':s1d,'s1dhdr':s1dhdr,'mjd':mjd,'date':date,'texp':texp,'obstype':obstype,'framename':framename,'npx':npx,'npx1d':npx1d,'norders':norders,'berv':berv,'airmass':airmass,'s1dmjd':s1dmjd}\n    return(output)\n\n\n\ndef read_espresso(inpath,filelist,read_s1d=True,skysub=True):\n    #The following variables define lists in which all the necessary data will be stored.\n    framename=[]\n    header=[]\n    s1dhdr=[]\n    obstype=[]\n    texp=np.array([])\n    date=[]\n    mjd=np.array([])\n    s1dmjd=np.array([])\n    npx=np.array([])\n    norders=np.array([])\n    e2ds=[]\n    s1d=[]\n    wave1d=[]\n    airmass=np.array([])\n    berv=np.array([])\n    wave=[]\n    catkeyword = 'EXTNAME'\n    bervkeyword = 'HIERARCH ESO QC BERV'\n    airmass_keyword1 = 'HIERARCH ESO TEL'\n    airmass_keyword2 = ' AIRM '\n    airmass_keyword3_start = 'START'\n    airmass_keyword3_end = 'END'\n\n    if skysub:\n        type_suffix = 'S2D_SKYSUB_A.fits'\n    else:\n        type_suffix = 'S2D_BLAZE_A.fits'\n\n    for i in range(len(filelist)):\n        if filelist[i].endswith(type_suffix):\n            hdul = fits.open(inpath/filelist[i])\n            data = copy.deepcopy(hdul[1].data)\n            hdr = hdul[0].header\n            hdr2 = hdul[1].header\n            wavedata=copy.deepcopy(hdul[5].data)\n            hdul.close()\n            del hdul\n\n            if hdr2[catkeyword] == 'SCIDATA':\n                # print('science keyword found')\n                print(f'------{filelist[i]}', end=\"\\r\")\n                framename.append(filelist[i])\n                header.append(hdr)\n                obstype.append('SCIENCE')\n                texp=np.append(texp,hdr['EXPTIME'])\n                date.append(hdr['DATE-OBS'])\n                mjd=np.append(mjd,hdr['MJD-OBS'])\n                npx=np.append(npx,hdr2['NAXIS1'])\n                norders=np.append(norders,hdr2['NAXIS2'])\n                e2ds.append(data)\n                berv=np.append(berv,hdr[bervkeyword])#in km.s.\n                telescope = hdr['TELESCOP'][-1]\n                airmass = np.append(airmass,0.5*(hdr[airmass_keyword1+telescope+' AIRM START']+hdr[airmass_keyword1+telescope+' AIRM END']))\n                wave.append(wavedata/10.0)#*(1.0-(hdr[bervkeyword]*u.km/u.s/const.c).decompose().value))\n                #Ok.! So unlike HARPS, ESPRESSO wavelengths are actually BERV corrected in the S2Ds.\n                #WHY!!!?. WELL SO BE IT. IN ORDER TO HAVE E2DSes THAT ARE ON THE SAME GRID, AS REQUIRED, WE UNDO THE BERV CORRECTION HERE.\n                #WHEN COMPARING WAVE[0] WITH WAVE[1], YOU SHOULD SEE THAT THE DIFFERENCE IS NILL.\n                #THATS WHY LATER WE CAN JUST USE WAVE[0] AS THE REPRESENTATIVE GRID FOR ALL.\n                #BUT THAT IS SILLY. JUST SAVE THE WAVELENGTHS!\n\n                if read_s1d:\n                    s1d_path=inpath/Path(str(filelist[i]).replace('_'+type_suffix,'_S1D_A.fits'))\n                    #Need the blazed files. Not the S2D_A's by themselves.\n                    ut.check_path(s1d_path,exists=True)#Crash if the S1D doesn't exist.\n                    hdul = fits.open(s1d_path)\n                    data_table = copy.deepcopy(hdul[1].data)\n                    hdr1d = hdul[0].header\n                    hdul.close()\n                    del hdul\n                    s1d.append(data_table.field(2))\n\n                    berv1d = hdr1d[bervkeyword]\n                    if berv1d != hdr[bervkeyword]:\n                        wrn_msg = ('WARNING in read_espresso(): BERV correction of S1D file is not'\n                        f'equal to that of the S2D file. {berv1d} vs {hdr[bervkeyword]}')\n                        ut.tprint(wrn_msg)\n                    gamma = (1.0-(berv1d*u.km/u.s/const.c).decompose().value)\n                    wave1d.append(data_table.field(1)*gamma)#This is in angstroms.\n                    #We need to check to which UT ESPRESSO was connected, so that we can read\n                    #the weather information (which is UT-specific) and parse them into the\n                    #header using UT-agnostic keywords that are in the ESPRESSO.par file.\n                    TELESCOP = hdr1d['TELESCOP'].split('U')[1]#This is the number of the UT, either 1, 2, 3 or 4.\n                    if TELESCOP not in ['1','2','3','4']:\n                        raise ValueError(f\"in read_e2ds when reading ESPRESSO data. The UT telescope is not recognised. (TELESCOP={hdr['TELESCOP']})\")\n                    else:\n                        hdr1d['TELALT']     = hdr1d[f'ESO TEL{TELESCOP} ALT']\n                        hdr1d['RHUM']       = hdr1d[f'ESO TEL{TELESCOP} AMBI RHUM']\n                        hdr1d['PRESSURE']   = (hdr1d[f'ESO TEL{TELESCOP} AMBI PRES START']+\n                                            hdr1d[f'ESO TEL{TELESCOP} AMBI PRES END'])/2.0\n                        hdr1d['AMBITEMP']   = hdr1d[f'ESO TEL{TELESCOP} AMBI TEMP']\n                        hdr1d['M1TEMP']     = hdr1d[f'ESO TEL{TELESCOP} TH M1 TEMP']\n                    s1dhdr.append(hdr1d)\n                    s1dmjd=np.append(s1dmjd,hdr1d['MJD-OBS'])\n    if read_s1d:\n        output = {'wave':wave,'e2ds':e2ds,'header':header,'wave1d':wave1d,'s1d':s1d,'s1dhdr':s1dhdr,\n        'mjd':mjd,'date':date,'texp':texp,'obstype':obstype,'framename':framename,'npx':npx,\n        'norders':norders,'berv':berv,'airmass':airmass,'s1dmjd':s1dmjd}\n    else:\n        output = {'wave':wave,'e2ds':e2ds,'header':header,\n        'mjd':mjd,'date':date,'texp':texp,'obstype':obstype,'framename':framename,'npx':npx,\n        'norders':norders,'berv':berv,'airmass':airmass}\n    return(output)\n\n\n\ndef read_spirou(inpath,filelist,read_s1d=False):\n    \"\"\"\n    This reads a folder of SPIROU spectra expecting *t.fits for telluric reduce spectra to exists\n\n    As this data is already telluric reduced no effort is done for creating the s1d data structures\n    \"\"\"\n\n    if read_s1d:\n        wrn_msg = ('read s1d files not implemented yet for SPIROU, read_s1d reset to false!')\n        ut.tprint(wrn_msg)\n        read_s1d = False\n\n    #The following variables define lists in which all the necessary data will be stored.\n    framename=[]\n    header=[]\n    s1dhdr=[]\n    obstype=[]\n    texp=np.array([])\n    date=[]\n    mjd=np.array([])\n    s1dmjd=np.array([])\n    npx=np.array([])\n    norders=np.array([])\n    e2ds=[]\n    s1d=[]\n    wave1d=[]\n    airmass=np.array([])\n    berv=np.array([])\n    wave=[]\n    for i in range(len(filelist)):\n        if filelist[i].endswith('t.fits'):\n            print(f'------{filelist[i]}', end=\"\\r\")\n            hdul = fits.open(inpath/filelist[i])\n            fluxdata = copy.deepcopy(hdul[1].data)\n            wavedata = ops.vactoair(copy.deepcopy(hdul[2].data))\n            blazedata = copy.deepcopy(hdul[3].data)\n            teldata = copy.deepcopy(hdul[4].data)\n            hdr = hdul[0].header\n            fluxhdr = hdul[1].header\n            wavehdr = hdul[2].header\n            blazehdr = hdul[3].header\n            telhdr = hdul[4].header\n            hdul.close()\n            del hdul[1].data\n            del hdul[2].data\n            del hdul[3].data\n            del hdul[4].data\n\n            __npx = fluxhdr['NAXIS1']\n            __norders = fluxhdr['NAXIS2']\n            idxfilter = []\n            for idx in range(__norders):\n                numberofNaN = np.count_nonzero(np.isnan(fluxdata[idx]))\n                idxfilter.append(numberofNaN != fluxdata[idx].size)\n#                __ratio = float(numberofNaN) / float(fluxdata[idx].size)\n#                idxfilter.append(__ratio < 1.0)\n#                print(\"numberofNaN\"+str(numberofNaN)+\"  fluxdata:\"+str(fluxdata[idx].size)+\"   ratio:\"+str(__ratio))\n            fluxdata = fluxdata[idxfilter]\n            wavedata = wavedata[idxfilter]\n            blazedata = blazedata[idxfilter]\n            teldata = teldata[idxfilter]\n#            print(\"dropped count of orders: \"+str(np.size(idxfilter) - np.sum(idxfilter)))\n            __norders = __norders - np.size(idxfilter) + np.sum(idxfilter)  # subtracts number of False\n\n            framename.append(filelist[i])\n            header.append(hdr)\n            obstype.append(hdr['OBSTYPE'])\n            texp=np.append(texp,hdr['EXPTIME'])\n            date.append(hdr['DATE-OBS']+'T'+hdr['UTC-OBS'])\n            mjd=np.append(mjd,hdr['MJD-OBS'])\n            npx=np.append(npx,__npx)\n            norders=np.append(norders,__norders)\n            e2ds.append(fluxdata)\n            wave.append(wavedata)\n            berv=np.append(berv,fluxhdr['BERV'])\n            airmass=np.append(airmass,hdr['AIRMASS'])\n\n\n    if read_s1d:\n        output = {'wave':wave,'e2ds':e2ds,'header':header,'wave1d':wave1d,'s1d':s1d,'s1dhdr':s1dhdr,\n              'mjd':mjd,'date':date,'texp':texp,'obstype':obstype,'framename':framename,'npx':npx,\n              'norders':norders,'berv':berv,'airmass':airmass,'s1dmjd':s1dmjd}\n    else:\n        output = {'wave':wave,'e2ds':e2ds,'header':header,\n              'mjd':mjd,'date':date,'texp':texp,'obstype':obstype,'framename':framename,'npx':npx,\n              'norders':norders,'berv':berv,'airmass':airmass}\n    return(output)\n\n\n\ndef read_gianob(inpath,filelist,read_s1d=True):\n    \"\"\"\n    This reads a folder of SPIROU spectra expecting *t.fits for telluric reduce spectra to exists\n\n    As this data is already telluric reduced no effort is done for creating the s1d data structures\n    \"\"\"\n    #The following variables define lists in which all the necessary data will be stored.\n    framename=[]\n    header=[]\n    s1dhdr=[]\n    obstype=[]\n    texp=np.array([])\n    date=[]\n    mjd=np.array([])\n    s1dmjd=np.array([])\n    npx=np.array([])\n    norders=np.array([])\n    e2ds=[]\n    s1d=[]\n    wave1d=[]\n    airmass=np.array([])\n    berv=np.array([])\n    wave=[]\n\n    for i in range(len(filelist)):\n        if filelist[i].endswith('AB_ms1d.fits'):\n            hdul = fits.open(inpath/filelist[i])\n            fitsdata = copy.deepcopy(hdul[1].data)\n            hdr = hdul[0].header\n            hdul.close()\n            del hdul[1].data\n\n            if hdr['OBS-TYPE'] == 'SCIENCE':\n                # print('science keyword found')\n                print(f'------{filelist[i]}', end=\"\\r\")\n                framename.append(filelist[i])\n                header.append(hdr)\n                obstype.append('SCIENCE')\n                texp=np.append(texp,hdr['EXPTIME'])\n                date.append(hdr['DATE-OBS'])\n                mjd=np.append(mjd,hdr['MJD-OBS'])\n                berv=np.append(berv,hdr['HIERARCH TNG DRS BERV'])#in km.s.\n                airmass = np.append(airmass,hdr['AIRMASS'])\n                ordernumbers = []\n                wavedata = []\n                fluxdata = []\n                snrdata = []\n                __npx = len(fitsdata[0][1])\n                __norders = len(fitsdata)\n                npx=np.append(npx,__npx)\n                norders=np.append(norders,__norders)\n                for idx in range(len(fitsdata)):\n                    ordernumbers.append(fitsdata[idx][0])\n                    wavedata.append(fitsdata[idx][1])\n                    fluxdata.append(fitsdata[idx][2])\n                    snrdata.append(fitsdata[idx][3])\n                wave.append(ops.vactoair(np.array(wavedata)))\n                e2ds.append(np.array(fluxdata))\n#                print(\"---wave then flux---\")\n#                print(np.array(wavedata))\n#                print(np.array(fluxdata))\n\n                if read_s1d:\n                    s1d_path=inpath/Path(str(filelist[i]).replace('_ms1d.fits','_s1d.fits'))\n                    #Need the blazed files. Not the S2D_A's by themselves.\n                    ut.check_path(s1d_path,exists=True)#Crash if the S1D doesn't exist.\n                    hdul1d = fits.open(s1d_path)\n                    hdr1d = hdul1d[0].header\n                    fluxdata1d = copy.deepcopy(hdul1d[0].data)\n                    hdul1d.close()\n                    del hdul1d[0].data\n\n                    s1d.append(fluxdata1d)\n\n                    bervkeyword = 'HIERARCH TNG DRS BERV'\n                    berv1d = hdr1d[bervkeyword]\n                    if berv1d != hdr[bervkeyword]:\n                        wrn_msg = ('WARNING in read_gianob(): BERV correction of S1D file is not'\n                        f'equal to that of the S2D file. {berv1d} vs {hdr[bervkeyword]}')\n                        ut.tprint(wrn_msg)\n                    gamma = (1.0-(berv1d*u.km/u.s/const.c).decompose().value)\n                    crval = hdr1d['CRVAL1']\n                    cdelt = hdr1d['CDELT1']\n                    mywave = crval\n                    wavedata1d = [mywave*gamma*10]\n                    for idx in range(len(fluxdata1d)-1):\n                        mywave += cdelt\n                        wavedata1d.append(mywave*gamma*10)\n                    wave1d.append(ops.vactoair(np.array(wavedata1d)))\n                    s1dhdr.append(hdr1d)\n                    s1dmjd=np.append(s1dmjd,hdr1d['MJD-OBS'])\n#                    print(\"wave:\"+str(len(wavedata1d))+\" flux:\"+str(len(fluxdata1d)))\n\n    if read_s1d:\n        output = {'wave':wave,'e2ds':e2ds,'header':header,'wave1d':wave1d,'s1d':s1d,'s1dhdr':s1dhdr,\n        'mjd':mjd,'date':date,'texp':texp,'obstype':obstype,'framename':framename,'npx':npx,\n        'norders':norders,'berv':berv,'airmass':airmass,'s1dmjd':s1dmjd}\n    else:\n        output = {'wave':wave,'e2ds':e2ds,'header':header,\n        'mjd':mjd,'date':date,'texp':texp,'obstype':obstype,'framename':framename,'npx':npx,\n        'norders':norders,'berv':berv,'airmass':airmass}\n    return(output)\n", "meta": {"hexsha": "0e66f228443a2b08b4bce4b0088655603a80d509", "size": 38116, "ext": "py", "lang": "Python", "max_stars_repo_path": "tayph/read.py", "max_stars_repo_name": "thorsbro/tayph", "max_stars_repo_head_hexsha": "373a59d339354e2c09484cd3fd5a24d651e0b98b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tayph/read.py", "max_issues_repo_name": "thorsbro/tayph", "max_issues_repo_head_hexsha": "373a59d339354e2c09484cd3fd5a24d651e0b98b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tayph/read.py", "max_forks_repo_name": "thorsbro/tayph", "max_forks_repo_head_hexsha": "373a59d339354e2c09484cd3fd5a24d651e0b98b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.9782870929, "max_line_length": 296, "alphanum_fraction": 0.5898835135, "include": true, "reason": "import numpy,import scipy,from scipy,import astropy,from astropy", "num_tokens": 10654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.2658804672827598, "lm_q1q2_score": 0.15455713737342253}}
{"text": "# coding=utf-8  python3.6\n# ================================================================\n#   Copyright (C) 2019 * Ltd. All rights reserved.\n#   license     : MIT License\n#   Author      : haibingshuai \n#   Created date: 2019/10/29 15:19\n#   Description :\n# ================================================================\n\nimport tensorflow as tf\nimport numpy as np\nimport cv2\nimport random\nimport colorsys\nfrom core.model_config import config\n\n\ndef bbox_iou(boxes1, boxes2):\n    boxes1 = np.array(boxes1)\n    boxes2 = np.array(boxes2)\n\n    boxes1_area = boxes1[..., 2] * boxes1[..., 3]\n    boxes2_area = boxes2[..., 2] * boxes2[..., 3]\n\n    boxes1 = np.concatenate([boxes1[..., :2] - boxes1[..., 2:] * 0.5,\n                             boxes1[..., :2] + boxes1[..., 2:] * 0.5], axis=-1)\n    boxes2 = np.concatenate([boxes2[..., :2] - boxes2[..., 2:] * 0.5,\n                             boxes2[..., :2] + boxes2[..., 2:] * 0.5], axis=-1)\n\n    left_up = np.maximum(boxes1[..., :2], boxes2[..., :2])\n    right_down = np.minimum(boxes1[..., 2:], boxes2[..., 2:])\n\n    inter_section = np.maximum(right_down - left_up, 0.0)\n    inter_area = inter_section[..., 0] * inter_section[..., 1]\n    union_area = boxes1_area + boxes2_area - inter_area\n\n    return inter_area / union_area\n\n\ndef bbox_giou(boxes1, boxes2):\n    boxes1 = tf.concat([boxes1[..., :2] - boxes1[..., 2:] * 0.5,\n                        boxes1[..., :2] + boxes1[..., 2:] * 0.5], axis=-1)\n    boxes2 = tf.concat([boxes2[..., :2] - boxes2[..., 2:] * 0.5,\n                        boxes2[..., :2] + boxes2[..., 2:] * 0.5], axis=-1)\n\n    boxes1 = tf.concat([tf.minimum(boxes1[..., :2], boxes1[..., 2:]),\n                        tf.maximum(boxes1[..., :2], boxes1[..., 2:])], axis=-1)\n    boxes2 = tf.concat([tf.minimum(boxes2[..., :2], boxes2[..., 2:]),\n                        tf.maximum(boxes2[..., :2], boxes2[..., 2:])], axis=-1)\n\n    boxes1_area = (boxes1[..., 2] - boxes1[..., 0]) * (boxes1[..., 3] - boxes1[..., 1])\n    boxes2_area = (boxes2[..., 2] - boxes2[..., 0]) * (boxes2[..., 3] - boxes2[..., 1])\n\n    left_up = tf.maximum(boxes1[..., :2], boxes2[..., :2])\n    right_down = tf.minimum(boxes1[..., 2:], boxes2[..., 2:])\n\n    inter_section = tf.maximum(right_down - left_up, 0.0)\n    inter_area = inter_section[..., 0] * inter_section[..., 1]\n    union_area = boxes1_area + boxes2_area - inter_area\n    iou = inter_area / union_area\n\n    enclose_left_up = tf.minimum(boxes1[..., :2], boxes2[..., :2])\n    enclose_right_down = tf.maximum(boxes1[..., 2:], boxes2[..., 2:])\n    enclose = tf.maximum(enclose_right_down - enclose_left_up, 0.0)\n    enclose_area = enclose[..., 0] * enclose[..., 1]\n    giou = iou - 1.0 * (enclose_area - union_area) / enclose_area\n\n    return giou\n\n\ndef focal(target, actual, alpha=1, gamma=2):\n    focal_loss = alpha * tf.pow(tf.abs(target - actual), gamma)\n    return focal_loss\n\n\n# iou_threshold相交门阀控制（超过了就剔除）\ndef nms(pro_need_cls_bboxes, iou_threshold, sigma=0.3, method='nms'):\n    need_bboxs = []\n\n    # 流程1: 判断边界框的数目是否大于0\n    while len(pro_need_cls_bboxes) > 0:\n        # 流程2: 按照 socre 排序选出评分最大的边界框 A,并将边界框 A 取出并剔除\n        max_ind = np.argmax(pro_need_cls_bboxes[:, 4])\n        need_bbox = pro_need_cls_bboxes[max_ind]\n        need_bboxs.append(need_bbox)\n        pro_need_cls_bboxes = np.concatenate([pro_need_cls_bboxes[: max_ind], pro_need_cls_bboxes[max_ind + 1:]])\n\n        # 流程3: 计算这个边界框 A 与剩下所有边界框的 iou 并剔除那些 iou 值高于阈值的边界框\n        iou = bboxes_iou(need_bbox[np.newaxis, :4], pro_need_cls_bboxes[:, :4])\n        weight = np.ones((len(iou),), dtype=np.float32)\n\n        assert method in ['nms', 'soft-nms']\n\n        if method == 'nms':\n            iou_mask = iou > iou_threshold\n            weight[iou_mask] = 0.0\n\n        if method == 'soft-nms':\n            weight = np.exp(-(1.0 * iou ** 2 / sigma))\n\n        pro_need_cls_bboxes[:, 4] = pro_need_cls_bboxes[:, 4] * weight\n        score_mask = pro_need_cls_bboxes[:, 4] > 0.\n        pro_need_cls_bboxes = pro_need_cls_bboxes[score_mask]\n    return need_bboxs\n\n\ndef read_class_names(class_file_name):\n    names = {}\n    with open(class_file_name, 'r') as data:\n        for ID, name in enumerate(data):\n            names[ID] = name.strip('\\n')\n    return names\n\n\ndef get_anchors(anchors_path):\n    with open(anchors_path) as f:\n        anchors = f.readline()\n    anchors = np.array(anchors.split(','), dtype=np.float32)\n    return anchors.reshape(3, 3, 2)\n\n\ndef image_pretreat_process(org_image, target_size, gt_boxes=None):\n    h, w = org_image.shape[:2]\n    tar_h, tar_w = target_size, target_size\n    h_resize, w_resize, scale = [tar_h, tar_h * w // h, target_size / h] if h > w else [tar_w * h // w, tar_w,\n                                                                                        target_size / w]\n\n    org_image_temp = cv2.resize(org_image, (w_resize, h_resize))\n    h_f, w_f = (tar_h - h_resize) // 2, (tar_w - w_resize) // 2\n    target_image = np.full(shape=[tar_h, tar_w, 3], fill_value=127, dtype=np.uint8)\n    target_image[h_f:h_f + h_resize, w_f:w_f + w_resize] = org_image_temp\n\n    if gt_boxes is None:\n        return target_image\n\n    else:\n        gt_boxes[:, [0, 2]] = gt_boxes[:, [0, 2]] * scale + w_f\n        gt_boxes[:, [1, 3]] = gt_boxes[:, [1, 3]] * scale + h_f\n        return target_image, gt_boxes\n\n\ndef random_horizontal_flip(image, bboxes):\n    if random.random() < 0.5:\n        _, w, _ = image.shape\n        image = image[:, ::-1, :]\n        bboxes[:, [0, 2]] = w - bboxes[:, [2, 0]]\n\n    return image, bboxes\n\n\ndef random_crop(image, bboxes):\n    if random.random() < 0.5:\n        h, w, _ = image.shape\n        max_bbox = np.concatenate([np.min(bboxes[:, 0:2], axis=0), np.max(bboxes[:, 2:4], axis=0)], axis=-1)\n\n        max_l_trans = max_bbox[0]\n        max_u_trans = max_bbox[1]\n        max_r_trans = w - max_bbox[2]\n        max_d_trans = h - max_bbox[3]\n\n        crop_xmin = max(0, int(max_bbox[0] - random.uniform(0, max_l_trans)))\n        crop_ymin = max(0, int(max_bbox[1] - random.uniform(0, max_u_trans)))\n        crop_xmax = max(w, int(max_bbox[2] + random.uniform(0, max_r_trans)))\n        crop_ymax = max(h, int(max_bbox[3] + random.uniform(0, max_d_trans)))\n\n        image = image[crop_ymin: crop_ymax, crop_xmin: crop_xmax]\n\n        bboxes[:, [0, 2]] = bboxes[:, [0, 2]] - crop_xmin\n        bboxes[:, [1, 3]] = bboxes[:, [1, 3]] - crop_ymin\n\n    return image, bboxes\n\n\ndef random_translate(image, bboxes):\n    if random.random() < 0.5:\n        h, w, _ = image.shape\n        max_bbox = np.concatenate([np.min(bboxes[:, 0:2], axis=0), np.max(bboxes[:, 2:4], axis=0)], axis=-1)\n\n        max_l_trans = max_bbox[0]\n        max_u_trans = max_bbox[1]\n        max_r_trans = w - max_bbox[2]\n        max_d_trans = h - max_bbox[3]\n\n        tx = random.uniform(-(max_l_trans - 1), (max_r_trans - 1))\n        ty = random.uniform(-(max_u_trans - 1), (max_d_trans - 1))\n\n        M = np.array([[1, 0, tx], [0, 1, ty]])\n        image = cv2.warpAffine(image, M, (w, h))\n\n        bboxes[:, [0, 2]] = bboxes[:, [0, 2]] + tx\n        bboxes[:, [1, 3]] = bboxes[:, [1, 3]] + ty\n\n    return image, bboxes\n\n\ndef read_pb_return_tensors(graph, pb_file, return_elements):\n    with tf.gfile.FastGFile(pb_file, 'rb') as f:\n        frozen_graph_def = tf.GraphDef()\n        frozen_graph_def.ParseFromString(f.read())\n\n    with graph.as_default():\n        return_elements = tf.import_graph_def(frozen_graph_def,\n                                              return_elements=return_elements)\n    return return_elements\n\n\ndef postprocess_boxes(pred_bbox, org_img_shape, input_size, score_threshold):\n    valid_scale = [0, np.inf]\n    pred_bbox = np.array(pred_bbox)\n\n    pred_xywh = pred_bbox[:, 0:4]\n    pred_conf = pred_bbox[:, 4]\n    pred_prob = pred_bbox[:, 5:]\n\n    # # (1) (x, y, w, h) --> (xmin, ymin, xmax, ymax)\n    pred_coor = np.concatenate([pred_xywh[:, :2] - pred_xywh[:, 2:] * 0.5,\n                                pred_xywh[:, :2] + pred_xywh[:, 2:] * 0.5], axis=-1)\n    # # (2) (xmin, ymin, xmax, ymax) -> (xmin_org, ymin_org, xmax_org, ymax_org)\n    org_h, org_w = org_img_shape\n    resize_ratio = min(input_size / org_w, input_size / org_h)\n\n    dw = (input_size - resize_ratio * org_w) / 2\n    dh = (input_size - resize_ratio * org_h) / 2\n\n    pred_coor[:, 0::2] = 1.0 * (pred_coor[:, 0::2] - dw) / resize_ratio\n    pred_coor[:, 1::2] = 1.0 * (pred_coor[:, 1::2] - dh) / resize_ratio\n\n    # # (3) clip some boxes those are out of range\n    pred_coor = np.concatenate([np.maximum(pred_coor[:, :2], [0, 0]),\n                                np.minimum(pred_coor[:, 2:], [org_w - 1, org_h - 1])], axis=-1)\n    invalid_mask = np.logical_or((pred_coor[:, 0] > pred_coor[:, 2]), (pred_coor[:, 1] > pred_coor[:, 3]))\n    pred_coor[invalid_mask] = 0\n\n    # # (4) discard some invalid boxes\n    bboxes_scale = np.sqrt(np.multiply.reduce(pred_coor[:, 2:4] - pred_coor[:, 0:2], axis=-1))\n    scale_mask = np.logical_and((valid_scale[0] < bboxes_scale), (bboxes_scale < valid_scale[1]))\n\n    # # (5) discard some boxes with low scores\n    classes = np.argmax(pred_prob, axis=-1)\n    scores = pred_conf * pred_prob[np.arange(len(pred_coor)), classes]\n    score_mask = scores > score_threshold\n    mask = np.logical_and(scale_mask, score_mask)\n    coors, scores, classes = pred_coor[mask], scores[mask], classes[mask]\n\n    return np.concatenate([coors, scores[:, np.newaxis], classes[:, np.newaxis]], axis=-1)\n\n\ndef draw_bbox(image, bboxes, classes=read_class_names(config.YOLO.CLASSES), show_label=True):\n    \"\"\"\n    bboxes: [x_min, y_min, x_max, y_max, probability, cls_id] format coordinates.\n    \"\"\"\n\n    num_classes = len(classes)\n    image_h, image_w, _ = image.shape\n    hsv_tuples = [(1.0 * x / num_classes, 1., 1.) for x in range(num_classes)]\n    colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))\n    colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors))\n\n    random.seed(0)\n    random.shuffle(colors)\n    random.seed(None)\n\n    for i, bbox in enumerate(bboxes):\n        coor = np.array(bbox[:4], dtype=np.int32)\n        fontScale = 0.5\n        score = bbox[4]\n        class_ind = int(bbox[5])\n        bbox_color = colors[class_ind]\n        bbox_thick = int(0.6 * (image_h + image_w) / 600)\n        c1, c2 = (coor[0], coor[1]), (coor[2], coor[3])\n        cv2.rectangle(image, c1, c2, bbox_color, bbox_thick)\n\n        if show_label:\n            bbox_mess = '%s: %.2f' % (classes[class_ind], score)\n            t_size = cv2.getTextSize(bbox_mess, 0, fontScale, thickness=bbox_thick // 2)[0]\n            cv2.rectangle(image, c1, (c1[0] + t_size[0], c1[1] - t_size[1] - 3), bbox_color, -1)  # filled\n\n            cv2.putText(image, bbox_mess, (c1[0], c1[1] - 2), cv2.FONT_HERSHEY_SIMPLEX,\n                        fontScale, (0, 0, 0), bbox_thick // 2, lineType=cv2.LINE_AA)\n\n    return image\n\n\ndef bboxes_iou(boxes1, boxes2):\n    boxes1 = np.array(boxes1)\n    boxes2 = np.array(boxes2)\n\n    boxes1_area = (boxes1[..., 2] - boxes1[..., 0]) * (boxes1[..., 3] - boxes1[..., 1])\n    boxes2_area = (boxes2[..., 2] - boxes2[..., 0]) * (boxes2[..., 3] - boxes2[..., 1])\n\n    left_up = np.maximum(boxes1[..., :2], boxes2[..., :2])\n    right_down = np.minimum(boxes1[..., 2:], boxes2[..., 2:])\n\n    inter_section = np.maximum(right_down - left_up, 0.0)\n    inter_area = inter_section[..., 0] * inter_section[..., 1]\n    union_area = boxes1_area + boxes2_area - inter_area\n    ious = np.maximum(1.0 * inter_area / union_area, np.finfo(np.float32).eps)\n\n    return ious\n", "meta": {"hexsha": "36658c078a12bf9682dbc978e536884fa646eb61", "size": 11498, "ext": "py", "lang": "Python", "max_stars_repo_path": "core/utils.py", "max_stars_repo_name": "HAIbingshuai/yolo_v3_tensorflow", "max_stars_repo_head_hexsha": "91f9a7146b06082fb9159aeaf4c54764c3f0e75c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core/utils.py", "max_issues_repo_name": "HAIbingshuai/yolo_v3_tensorflow", "max_issues_repo_head_hexsha": "91f9a7146b06082fb9159aeaf4c54764c3f0e75c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core/utils.py", "max_forks_repo_name": "HAIbingshuai/yolo_v3_tensorflow", "max_forks_repo_head_hexsha": "91f9a7146b06082fb9159aeaf4c54764c3f0e75c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3266666667, "max_line_length": 113, "alphanum_fraction": 0.5766220212, "include": true, "reason": "import numpy", "num_tokens": 3632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.29746994883293104, "lm_q1q2_score": 0.15454198105870579}}
{"text": "\"\"\"Look-up table for GGF computation\"\"\"\nimport pathlib\nfrom pkg_resources import resource_filename\nimport warnings\n\nimport h5py\nimport numpy as np\nfrom scipy.interpolate import interpn\n\n\nclass NotInLUTError(BaseException):\n    pass\n\n\ndef _match_lut(kwargs, lut_path=None):\n    \"\"\"Find matching LUT for a set of keyword arguments\n\n    Parameters\n    ----------\n    kwargs: dict\n        keyword arguments for ggf.get_ggf\n    lut_path: str, pathlib.Path or None\n        path to an hdf5 file containing a LUT; if None,\n        the default LUTs will be searched\n\n    Returns\n    -------\n    lut_path: pathlib.Path\n        path to matching LUT hdf5 file\n    \"\"\"\n    if lut_path:\n        paths = [pathlib.Path(lut_path)]\n    else:\n        paths = get_lut_paths()\n    for path in paths:\n        with h5py.File(path, mode=\"r\") as h5:\n            for key in kwargs:\n                if _param_in_lut(key, kwargs[key], h5[\"lut\"].attrs):\n                    pass  # everything OK so far\n                else:\n                    break  # try next LUT\n            else:\n                break  # this is the right LUT\n    else:\n        msg = \"No matching LUT found for: {} in {}\".format(kwargs, paths)\n        raise NotInLUTError(msg)\n    return path\n\n\ndef _param_in_lut(key, value, h5_attrs):\n    \"\"\"Test whether the given parameter is accessible via a LUT\n\n    Parameters\n    ----------\n    key: str\n        keyword name (see ggf.get_ggf)\n    value: str or float\n        keyword value to check\n    h5_attrs: dict\n        attributes from a LUT hdf5 file\n\n    Returns\n    -------\n    inlut: bool\n        True, if the key-value pair is covered by the LUT\n    \"\"\"\n    inlut = False\n    if key == \"n_poly\" and value is None:  # default value is given in LUT\n        inlut = True\n    elif key in h5_attrs:  # fixed parameter\n        if h5_attrs[key] == value or value is None:\n            inlut = True\n    elif isinstance(value, str):  # model\n        inlut = False\n    else:  # range\n        vmin = h5_attrs[\"{} min\".format(key)]\n        vmax = h5_attrs[\"{} max\".format(key)]\n        if value <= vmax and value >= vmin:\n            inlut = True\n        else:\n            inlut = False\n    return inlut\n\n\ndef get_lut_paths():\n    \"\"\"Return a list of look-up table hdf5 files in ggf\"\"\"\n    lutpath = pathlib.Path(resource_filename(\"ggf\", \"lut\"))\n    paths = lutpath.glob(\"*.h5\")\n    return sorted(paths)\n\n\ndef get_ggf_lut(model, semi_major, semi_minor, object_index, medium_index,\n                effective_fiber_distance, mode_field_diameter,\n                power_per_fiber, wavelength, poisson_ratio,\n                n_poly=None, lut_path=None, verbose=False):\n    \"\"\"Linear interpolation of the GGF from a look-up table\n\n    Parameters\n    ----------\n    model: str\n        Model to use, one of: `boyde2009`\n    semi_major: float\n        Semi-major axis of an ellipse fit to the object perimeter [m]\n    semi_minor: float\n        Semi-minor axis of an ellipse fit to the object perimeter [m]\n    object_index: float\n        Refractive index of the object\n    medium_index: float\n        Refractive index of the surrounding medium\n    effective_fiber_distance: float\n        Effective distance between the two trapping fibers relative\n        to the medium refractive index [m]. For an open setup, this is\n        the physical distance between the fibers. For a closed setup\n        (capillary), this distance takes into account the refractive\n        indices and thicknesses of the glass capillary and index\n        matching gel. For the closed setup, the convenience function\n        :func:`ggf.fiber_distance_capillary` can be used.\n    mode_field_diameter: float\n        The mode field diameter MFD of the fiber used [m]. Note that\n        the MFD is dependent on the wavelength used. If the\n        manufacturer did not provide a value for the MFD, the MFD\n        can be approximated as ``3*wavelenth`` for a single-mode\n        fiber.\n    power_per_fiber: float\n        The laser power coupled into each of the fibers [W]\n    wavelength: float\n        The laser wavelength used for the trap [m]\n    poisson_ratio: float\n        The Poisson's ratio of the stretched material. Set this\n        to 0.5 for volume conservation.\n    n_poly: int\n        Number of Legendre polynomials to use for computing the GGF.\n        Note that only even Legendre polynomials are used and thus,\n        this number is effectively halved.\n    lut_path: str or pathlib.Path\n        Path to a LUT hdf5 file. If `None`, the internal LUTs are\n        used.\n    verbose: int\n        Increases verbosity\n\n    Returns\n    -------\n    ggf: float\n        Linearly interpolated global geometric factor\n\n    Notes\n    -----\n    - To avoid invalid values in the look-up table (LUT), such as\n      `semi_major < semi_minor` or `object_index < medium_index`,\n      the LUT is not built using the exact same keyword arguments\n      as this method:\n\n      - `object_index` is stored as\n        ``relative_object_index = object_index / medium_index``\n      - `semi_major` is stored as\n        ``stretch_ratio = (semi_major - semi_minor) / semi_minor``\n    - The following keywords are not interpolated in the LUT:\n\n      - `model`\n      - `wavelength`: the OS uses a fixed wavelength\n      - `mode_field_diameter`: the fiber geometry is fixed\n      - `power_per_fiber`: usually fixed for reproducibility\n      - `n_poly`: set to a high number (e.g. 120)\n    - The following are approximate guiding values for when a keyword\n      can be considered linear:\n\n      - stretch_ratio: linear only within interval of 0.004\n      - semi_minor: linear only within interval of 0.08µm\n      - relative_object_index: linear only within interval of 0.003\n      - medium_index: linear only within interval of 0.005\n      - poisson_ratio: good linearity\n      - power_per_fiber: good linearity\n      - effective_fiber_distance: linear only within interval of 15µm\n    \"\"\"\n    # convert major_axis to stretch ratio\n    stretch_ratio = (semi_major - semi_minor) / semi_minor\n    # normalize object index with medium_index\n    relative_object_index = object_index / medium_index\n    # determine the correct LUT\n    kwargs = {\"model\": model,\n              \"stretch_ratio\": stretch_ratio,\n              \"semi_minor\": semi_minor,\n              \"relative_object_index\": relative_object_index,\n              \"medium_index\": medium_index,\n              \"effective_fiber_distance\": effective_fiber_distance,\n              \"mode_field_diameter\": mode_field_diameter,\n              \"power_per_fiber\": power_per_fiber,\n              \"wavelength\": wavelength,\n              \"poisson_ratio\": poisson_ratio,\n              \"n_poly\": n_poly}\n    # get the right LUT\n    lut_path = _match_lut(kwargs, lut_path)  # raises NotInLutError\n    if verbose:\n        print(\"Using LUT path: {}\".format(lut_path))\n    # reproduce warning in boyde2009.core\n    if model == \"boyde2009\" and stretch_ratio > 0.15:\n        warnings.warn('Stretching ratio is high: {}'.format(stretch_ratio))\n    # get LUT data\n    with h5py.File(lut_path, mode=\"r\") as h5:\n        values = h5[\"lut\"][:]\n        meta = dict(h5[\"lut\"].attrs)\n    # order of interpolation dimensions\n    order = meta[\"dimension_order\"].split(\",\")\n    # grid points\n    points = []\n    for label in order:\n        points.append(np.linspace(meta[\"{} min\".format(label)],\n                                  meta[\"{} max\".format(label)],\n                                  meta[\"{} num\".format(label)]))\n    # interpolation coordinates\n    xi = [kwargs[kk] for kk in order]\n    # perform interpolation\n    ggfval = interpn(points=points, values=values, xi=xi, method=\"linear\",\n                     bounds_error=True)\n    ggfval = ggfval.item()\n    if np.isnan(ggfval):\n        raise ValueError(\"The value to be estimated in the LUT is `nan`. \"\n                         + \"Either the LUT is incomplete or the specified \"\n                         + \"model '{}' cannot handle \".format(model)\n                         + \"the given input parameters.\")\n    return ggfval\n", "meta": {"hexsha": "d4c276b16a4b1d383e6efb7d69204797ef82726d", "size": 8028, "ext": "py", "lang": "Python", "max_stars_repo_path": "ggf/lut/__init__.py", "max_stars_repo_name": "GuckLab/ggf", "max_stars_repo_head_hexsha": "85e1e48c272a93c4a595aa7964b0a1e23ee7764f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ggf/lut/__init__.py", "max_issues_repo_name": "GuckLab/ggf", "max_issues_repo_head_hexsha": "85e1e48c272a93c4a595aa7964b0a1e23ee7764f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-08-01T11:42:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-09T05:50:22.000Z", "max_forks_repo_path": "ggf/lut/__init__.py", "max_forks_repo_name": "GuckLab/ggf", "max_forks_repo_head_hexsha": "85e1e48c272a93c4a595aa7964b0a1e23ee7764f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1621621622, "max_line_length": 75, "alphanum_fraction": 0.6289237668, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.2974699426047947, "lm_q1q2_score": 0.15454197782305618}}
{"text": "#!python\n# coding=utf-8\n\"\"\"\n----------------------------------------------------------------\n| Swarm-of-Trajectory Dynamic Simulation Package\n| \n| Version: 0.1\n| Program Language: Python 3.6 (also support py2.7)\n| Developer: Xinyan Wang\n| Homepage: https://github.com/WangXinyan940/swarm-of-trajectory\n----------------------------------------------------------------\n\"\"\"\nfrom __future__ import unicode_literals\nfrom __future__ import division\nfrom __future__ import print_function\nimport sys\nimport os\nimport json\nimport numpy as np\nNAME = \"\"\nBOHR = 5.291772108e-11  # Bohr -> m\nANGSTROM = 1e-10  # angstrom -> m\nAMU = 1.660539040e-27  # amu -> kg\nFS = 1e-15  # fs -> s\nEH = 4.35974417e-18  # Hartrees -> J\nH = 6.626069934e-34\nKB = 1.38064852e-23\nkconst = 500000.0e3 * (1. / 6.02e23 / ANGSTROM ** 2)\n\n\ndef printTitle():\n    \"\"\"\n    Print the title of the output result.\n    \"\"\"\n    print(\"\"\"\n----------------------------------------------------------------\n| Swarm-of-Trajectory Dynamic Simulation Package\n| \n| Version: 0.1\n| Program Language: Python 3.6\n| Developer: Xinyan Wang\n| Homepage: https://github.com/WangXinyan940/swarm-of-trajectory\n----------------------------------------------------------------\n    \"\"\")\n\n\ndef printHelp():\n    \"\"\"\n    Print help.\n    \"\"\"\n    print(\"\"\"\n    Usage:\n        python sot.py -j json -t \n\n        -j        configuration .json file\n        -t        test the accuracy of template .gjf file\n    \"\"\")\n\n\ndef readFile(fname, func):\n    \"\"\"\n    Read text file and deal with different functions.\n    \"\"\"\n    with open(fname, \"r\") as f:\n        text = [i for i in f if i.strip()]\n    return func(text)\n\n\ndef readXYZ(text):\n    \"\"\"\n    Read xyz format text.\n    \"\"\"\n    natoms = int(text[0].strip())\n    body = text[2:natoms + 2]\n    body = [i.strip().split() for i in body]\n    atom = [i[0] for i in body]\n    crd = [[float(j) for j in i[1:]] for i in body]\n    return atom, np.array(crd)\n\n\ndef readMultiXYZ(text):\n    \"\"\"\n    Read XYZ file with multi conformations.\n    \"\"\"\n    xyzs = []\n    ip = 0\n    while True:\n        natom = int(text[ip].strip())\n        xyzs.append(text[ip:ip + natom + 2])\n        ip = ip + natom + 2\n        if ip >= len(text):\n            break\n    return [readXYZ(i) for i in xyzs]\n\n\ndef readGauGrad(text, natoms):\n    \"\"\"\n    Read Gaussian output and find energy gradient.\n    \"\"\"\n    ener = [i for i in text if \"SCF Done:\" in i]\n    if len(ener) != 0:\n        ener = ener[-1]\n        ener = np.float64(ener.split()[4])\n    else:\n        ener = np.float64([i for i in text if \"Energy=\" in i][-1].split()[1])\n    for ni, li in enumerate(text):\n        if \"Forces (Hartrees/Bohr)\" in li:\n            break\n    forces = text[ni + 3:ni + 3 + natoms]\n    forces = [i.strip().split()[-3:] for i in forces]\n    forces = [[np.float64(i[0]), np.float64(i[1]), np.float64(i[2])]\n              for i in forces]\n    return ener * EH, - np.array(forces) * EH / BOHR\n\n\ndef genQMInput(atom, crd, temp, pre=False, nstep=-1):\n    \"\"\"\n    Generate QM Input file for force calculation.\n    \"\"\"\n    with open(temp, \"r\") as f:\n        temp = f.readlines()\n    wrt = []\n    if pre == True:\n        wrt.append(\"%oldchk=old.chk\\n\")\n    for line in temp:\n        if \"[title]\" in line:\n            wrt.append(\"Temparary input file for step %i\\n\" % nstep)\n        elif \"[coord]\" in line:\n            for ni in range(len(atom)):\n                wrt.append(\"%s  %16.8f %16.8f %16.8f\\n\" %\n                           (atom[ni], crd[ni][0], crd[ni][1], crd[ni][2]))\n        elif line[0] == \"#\":\n            wrt.append(line)\n            if pre == True:\n                wrt.append(\" guess=read\\n\")\n        else:\n            wrt.append(line)\n    return \"\".join(wrt)\n\n\ndef writeXYZ(fname, atom, xyz, title=\"Title\", append=False):\n    \"\"\"\n    Write file with XYZ format.\n    \"\"\"\n    if append:\n        f = open(fname, \"a\")\n    else:\n        f = open(fname, \"w\")\n    f.write(\"%i\\n\" % len(atom))\n    f.write(\"%s\\n\" % (title.rstrip()))\n    for i in range(len(atom)):\n        x, y, z = xyz[i, :]\n        f.write(\"%s  %12.8f %12.8f %12.8f\\n\" % (atom[i], x, y, z))\n    f.close()\n\n\ndef distance(crd, i, j):\n    \"\"\"\n    Calc distance of two points.\n    \"\"\"\n    return np.sqrt(((crd[i, :] - crd[j, :]) ** 2).sum())\n\n\ndef bondforce(vi, vj, b, k):\n    \"\"\"\n    Calculate force on bond\n    \"\"\"\n    r = np.sqrt(((vi - vj) ** 2).sum())\n    fr = 2 * k * abs(r - b)\n    if r < b:\n        gi = (vi - vj) / r * fr\n    else:\n        gi = (vj - vi) / r * fr\n    gj = - gi\n    return gi, gj\n\n\ndef angle(crd, i, j, k):\n    \"\"\"\n    Calculate i-j-k angle in rad unit.\n    \"\"\"\n    pass\n\n\ndef angleforce(vi, vj, vk, b, k):\n    \"\"\"\n    Harmonic force to fix i-j-k angle at value b (rad).\n    \"\"\"\n    pass\n\n\ndef genMassMat(atom):\n    \"\"\"\n    Generate matrix of mass.\n    \"\"\"\n    massd = {\"H\": 1.008,\n             \"C\": 12.011,\n             \"N\": 14.007,\n             \"O\": 15.999,\n             \"S\": 32.066,\n             \"CL\": 35.453,\n             \"BR\": 79.904, }\n    massv = np.array([massd[i.upper()] for i in atom])\n    massm = np.zeros((len(atom), 3))\n    massm[:, 0] = massv\n    massm[:, 1] = massv\n    massm[:, 2] = massv\n    return massm\n\n\ndef testTemplate(conf):\n    \"\"\"\n    Test whether the template file is correct. (Use water)\n    \"\"\"\n    t_atom = [\"H\", \"O\", \"H\"]\n    t_xyz = [[1.0, 0.0, 0.0],\n             [0.0, 0.0, 0.0],\n             [0.0, 1.0, 0.0]]\n    template = conf[\"force\"][\"template\"]\n    print(\">>> Generate template below:\\n++++++++++++++++++++++++++++\")\n    print(genQMInput(t_atom, t_xyz, template, pre=True))\n\n\ndef argparse():\n    \"\"\"\n    Parse the args.\n    \"\"\"\n    # Test qm template\n    if \"-j\" not in sys.argv and \"-t\" not in sys.argv:\n        printHelp()\n        exit()\n\n    with open(sys.argv[2], \"r\") as f:\n        text = \"\".join(f)\n        conf = json.loads(text)\n\n    if \"-t\" in sys.argv:\n        testTemplate(conf)\n        exit()\n    return conf\n\n\ndef calcGauGrad(atom, crd, template, nstep, path=\"g09\"):\n    \"\"\"\n    Calculate gradient using Gaussian.\n    \"\"\"\n    with open(\"tmp.gjf\", \"w\") as f:\n        f.write(genQMInput(atom, crd, template,\n                           pre=True if nstep > 0 else False, nstep=nstep))\n    os.system(\"{} tmp.gjf\".format(path))\n    grad = readFile(\"tmp.log\", lambda x: readGauGrad(x, len(atom)))\n    os.system(\"cp tmp.chk old.chk\")\n    return grad\n\n\ndef genGrad(conf, template):\n    \"\"\"\n    Generate function used to calculate energy gradient.\n    \"\"\"\n    if conf[\"engine\"].upper() == \"GAUSSIAN\":\n        return lambda atom, crd, nstep: calcGauGrad(atom, crd / ANGSTROM, template, nstep, conf[\"path\"])\n\n\ndef setInitMotion(conf):\n    \"\"\"\n    Set init coord and velocities. \n    \"\"\"\n    xyzs = readFile(conf[\"coordinate\"], readMultiXYZ)\n    if \"velocity\" in conf and conf[\"velocity\"] is not None:\n        vels = readFile(conf[\"velocity\"], readMultiXYZ)\n    else:\n        vels = None\n    if \"start\" not in conf or conf[\"start\"] is None or conf[\"start\"] > len(xyzs):\n        atom, crd = xyzs[-1]\n        crd = crd * ANGSTROM\n        _, vel = None, vels[-1][1] if vels is not None else None\n    else:\n        rdm = np.random.randint(conf[\"start\"], len(xyzs))\n        atom, crd = xyzs[rdm]\n        crd = crd * ANGSTROM\n        _, vel = None, vels[rdm][1] if vels is not None else None\n    if vel is None:\n        T = conf[\"temperature\"]\n        massm = genMassMat(atom) * AMU\n        vel = np.random.normal(0.0, np.sqrt(KB * T / massm))\n    else:\n        vel = vel * ANGSTROM / FS\n    return atom, crd, vel\n\n\ndef dynamics(atom, initx, initv, grad=None, conf=None):\n    \"\"\"\n    Run dynamics. Using Velocity verlet algorithm.\n    \"\"\"\n    md, prt, cons, chk, stop = conf[\"md\"], conf[\"print\"], conf[\n        \"constraint\"], conf[\"check\"], conf[\"stop\"]\n    dt = md[\"deltat\"] * FS\n    massm = genMassMat(atom) * AMU\n    if md[\"type\"].upper() == \"NVT\":\n        T = md[\"temperature\"]\n        friction = md[\"friction\"] / (1000.0 * FS)\n        kT = KB * T\n        vscale = np.exp(- dt * friction)\n        fscale = dt if friction == 0.0 else (1 - vscale) / friction\n        noisescale = np.sqrt(kT * (1.0 - vscale ** 2))\n        invmass = 1. / massm\n        sqrtinvmass = np.sqrt(invmass)\n\n    crd = initx\n    vel = initv\n\n    e, f = grad(atom, crd, nstep=-1)\n    f = -f\n\n    for nstep in range(md[\"nsteps\"]):\n        # print\n        if \"freq\" in prt and nstep % prt[\"freq\"] == 0:\n            KE = (0.5 * massm * vel * vel).sum() / vel.shape[0] / vel.shape[1]\n            Tseq = KE * 2.0 / KB\n            if prt[\"coordinate\"]:\n                writeXYZ(\"%s-traj.xyz\" % NAME, atom, crd / ANGSTROM,\n                         title=\"NSTEP:%i E:%10.6f T:%8.4f\" % (nstep, e / EH, Tseq), append=True if nstep > 0 else False)\n            if prt[\"coordinate\"]:\n                writeXYZ(\"%s-vel.xyz\" % NAME, atom, vel / (ANGSTROM / FS),\n                         title=\"NSTEP:%i E:%10.6f T:%8.4f\" % (nstep, e / EH, Tseq), append=True if nstep > 0 else False)\n        if md[\"type\"].upper() == \"NVE\":\n            # velocity verlet\n            crd = crd + vel * dt + 0.5 * (f / massm) * dt ** 2\n            f_old = f\n            e, f = grad(atom, crd, nstep=nstep)\n            f = -f\n            print(\">>> step: %i    e:%10.4f\" % (nstep, e / EH))\n            vel = vel + 0.5 * (f_old + f) / massm * dt\n\n        elif md[\"type\"].upper() == \"NVT\":\n            # langevin dynamics\n            KE = (0.5 * massm * vel * vel).sum() / vel.shape[0] / vel.shape[1]\n            Tseq = KE * 2.0 / KB\n            print(\">>> step: %i    e:%10.4f    T:%8.4f\" %\n                  (nstep, e / EH, Tseq))\n            # step1\n            p1 = vscale * vel\n            p2 = fscale * invmass * f\n            p3 = noisescale * sqrtinvmass * \\\n                np.random.normal(0., np.ones(vel.shape))\n            vel = p1 + p2 + p3\n            if \"fixcom\" in md and md[\"fixcom\"]:\n                vcom = vel.mean(axis=0)\n                ke_pre = (0.5 * massm * vel * vel).sum() / \\\n                    vel.shape[0] / vel.shape[1]\n                v_remove = vel - vcom\n                ke_after = (0.5 * massm * v_remove * v_remove).sum() / \\\n                    v_remove.shape[0] / v_remove.shape[1]\n                vel = v_remove * np.sqrt(ke_pre / ke_after)\n                print(\">>> remove COM motion\", vcom / (ANGSTROM / FS))\n            #print(p1, p2, p3)\n            # step2\n            pre_crd = crd\n\n            # change cartesian coordinate\n            crd = crd + vel * dt\n\n            # LINCS algorithm\n            # Build B, d, S, A\n            B = np.zeros((len(cons), crd.ravel().shape[0]))\n            d = np.zeros((len(cons), 1))\n            S = np.zeros((len(cons), len(cons)))\n            A = np.zeros(S.shape)\n            for n, cv in enumerate(cons):\n                if cv[\"type\"].upper() == \"B\":\n                    ia, ib = cv[\"index\"]\n                    value = cv[\"value\"] * ANGSTROM\n                    r = np.sqrt(np.power(crd[ia,:] - crd[ib,:], 2).sum())\n                    B[n, ia * 3] = (crd[ia, 0] - crd[ib, 0]) / r\n                    B[n, ia * 3 + 1] = (crd[ia, 1] - crd[ib, 1]) / r\n                    B[n, ia * 3 + 2] = (crd[ia, 2] - crd[ib, 2]) / r\n                    B[n, ib * 3] = (crd[ib, 0] - crd[ia, 0]) / r\n                    B[n, ib * 3 + 1] = (crd[ib, 1] - crd[ia, 1]) / r\n                    B[n, ib * 3 + 2] = (crd[ib, 2] - crd[ia, 2]) / r\n                    d[n] = value\n                    S[n, n] = 1. / np.sqrt(1. / massm[ia][0] + 1. / massm[ib][0])\n            # Calculate A\n            #A = np.diag(np.ones(len(cons),)) - np.dot(S, np.dot(B,np.dot(np.diag(invmass.ravel()), np.dot(B.T, S))))\n            invMmat = np.diag(invmass.ravel())\n            Tm = np.linalg.inv(np.dot(np.dot(B, invMmat), B.T))\n            \n            #inverse = np.diag(np.ones(len(cons),)) + A + A ** 2 + A ** 3 + A ** 4\n            # Update new coord\n            crd = crd - np.dot(np.dot(invMmat, B.T), np.dot(Tm, np.dot(B, crd.reshape((-1,1))) - d)).reshape((-1,3))\n\n            # step3\n            vel = (crd - pre_crd) / dt\n            e, f = grad(atom, crd, nstep=nstep)\n            f = -f\n        # check_traj\n        if \"time\" in chk and nstep == chk[\"time\"]:\n            for cv in chk[\"cv\"]:\n                if cv[\"type\"].upper() == \"B\":\n                    r = distance(crd / ANGSTROM,\n                                 cv[\"index\"][0], cv[\"index\"][1])\n                    if r < cv[\"range\"][0] or r > cv[\"range\"][1]:\n                        print(\">>> Bond %i-%i out of range. Stop.\" %\n                              (cv[\"index\"][0], cv[\"index\"][1]))\n                        return\n        # check_stop\n        for state in stop:\n            ifquit = True\n            for cv in state[\"cv\"]:\n                if cv[\"type\"].upper() == \"B\":\n                    r = distance(crd / ANGSTROM,\n                                 cv[\"index\"][0], cv[\"index\"][1])\n                    if r < cv[\"range\"][0] or r > cv[\"range\"][1]:\n                        ifquit = False\n                        break\n            if ifquit:\n                print(\">>> Get state %s. Stop.\" % state[\"name\"])\n                exit()\n\n\ndef main():\n    \"\"\"\n    The main function.\n    \"\"\"\n    printTitle()\n    conf = argparse()\n\n    global NAME\n    NAME = conf[\"name\"]\n\n    if \"restraint\" not in conf:\n        conf[\"restraint\"] = []\n    if \"constraint\" not in conf:\n        conf[\"constraint\"] = []\n\n    # build template for qm engine\n    template = conf[\"force\"][\"template\"]\n\n    grad = genGrad(conf[\"force\"], template)\n    # select init crd and vel\n    atom, crd, vel = setInitMotion(conf[\"init\"])\n    # run dynamics\n    dynamics(atom, crd, vel, grad=grad, conf=conf)\n    print(\">>> STDSP is finished.\")\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "36197acfb5329b9989e971850d879cf345dedef0", "size": 13654, "ext": "py", "lang": "Python", "max_stars_repo_path": "sot.py", "max_stars_repo_name": "WangXinyan940/swarm-of-trajectory", "max_stars_repo_head_hexsha": "8ef974dff86a479f8afa90b4ec293ba03cf9f494", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sot.py", "max_issues_repo_name": "WangXinyan940/swarm-of-trajectory", "max_issues_repo_head_hexsha": "8ef974dff86a479f8afa90b4ec293ba03cf9f494", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sot.py", "max_forks_repo_name": "WangXinyan940/swarm-of-trajectory", "max_forks_repo_head_hexsha": "8ef974dff86a479f8afa90b4ec293ba03cf9f494", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4776785714, "max_line_length": 120, "alphanum_fraction": 0.4762706899, "include": true, "reason": "import numpy", "num_tokens": 4124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.2974699363766585, "lm_q1q2_score": 0.15454197458740657}}
{"text": "'''\nThis code is to implement embedding loss.\n'''\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom torch.autograd import Function, Variable\n\nclass EmbLoss_v1(nn.Module):\n    def __init__(self, feature_dim=4, loss_weight=1.0):\n        super(EmbLoss_v1, self).__init__()\n        self.feature_dim = feature_dim\n        self.loss_weight = loss_weight\n        self.delta_v = 0.5 # delta_agg\n        self.delta_d = 1.5 # delta_dis\n        self.weights = (1.0, 1.0)\n\n    def forward_single(self, emb, instance, kernel, training_mask, bboxes):\n        training_mask = (training_mask > 0.5).long()\n        kernel = (kernel > 0.5).long()\n        instance = instance * training_mask\n        instance_kernel = (instance * kernel).view(-1)\n        instance = instance.view(-1)\n        emb = emb.view(self.feature_dim, -1)\n\n        unique_labels, unique_ids = torch.unique(instance_kernel, sorted=True, return_inverse=True)\n        num_instance = unique_labels.size(0)\n        if num_instance <= 1:\n            return 0\n\n        emb_mean = emb.new_zeros((self.feature_dim, num_instance), dtype=torch.float32)\n        for i, lb in enumerate(unique_labels):\n            if lb == 0:\n                continue\n            ind_k = instance_kernel == lb\n            emb_mean[:, i] = torch.mean(emb[:, ind_k], dim=1)\n\n        l_agg = emb.new_zeros(num_instance, dtype=torch.float32)  # bug\n        for i, lb in enumerate(unique_labels):\n            if lb == 0:\n                continue\n            ind = instance == lb\n            emb_ = emb[:, ind]\n            dist = (emb_ - emb_mean[:, i:i + 1]).norm(p=2, dim=0)\n            dist = F.relu(dist - self.delta_v) ** 2\n            l_agg[i] = torch.mean(torch.log(dist + 1.0))\n        l_agg = torch.mean(l_agg[1:])\n\n        if num_instance > 2:\n            emb_interleave = emb_mean.permute(1, 0).repeat(num_instance, 1)\n            emb_band = emb_mean.permute(1, 0).repeat(1, num_instance).view(-1, self.feature_dim)\n            # print(seg_band)\n\n            mask = (1 - torch.eye(num_instance, dtype=torch.int8)).view(-1, 1).repeat(1, self.feature_dim)\n            mask = mask.view(num_instance, num_instance, -1)\n            mask[0, :, :] = 0\n            mask[:, 0, :] = 0\n            mask = mask.view(num_instance * num_instance, -1)\n            # print(mask)\n\n            dist = emb_interleave - emb_band\n            dist = dist[mask > 0].view(-1, self.feature_dim).norm(p=2, dim=1)\n            dist = F.relu(2 * self.delta_d - dist) ** 2\n            l_dis = torch.mean(torch.log(dist + 1.0))\n        else:\n            l_dis = 0\n\n        l_agg = self.weights[0] * l_agg\n        l_dis = self.weights[1] * l_dis\n        l_reg = torch.mean(torch.log(torch.norm(emb_mean, 2, 0) + 1.0)) * 0.001\n        loss = l_agg + l_dis + l_reg\n        return loss\n\n    def forward(self, emb, instance, kernel, training_mask, bboxes, reduce=True):\n        # TO CHECK: bboxes needs to be removed?\n        loss_batch = emb.new_zeros((emb.size(0)), dtype=torch.float32)\n\n        for i in range(loss_batch.size(0)):\n            loss_batch[i] = self.forward_single(emb[i], instance[i], kernel[i], training_mask[i], bboxes[i])\n\n        loss_batch = self.loss_weight * loss_batch\n\n        if reduce:\n            loss_batch = torch.mean(loss_batch)\n\n        return loss_batch", "meta": {"hexsha": "468b1572ed6df07f80d69e89f23deec70f7cc790", "size": 3323, "ext": "py", "lang": "Python", "max_stars_repo_path": "loss/emb_loss_v1.py", "max_stars_repo_name": "Thanh-Hoo/Custom_train_PanNet", "max_stars_repo_head_hexsha": "aa50df0e32991d35112f3de6627baea963f0827a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-12-15T16:55:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T12:00:54.000Z", "max_issues_repo_path": "loss/emb_loss_v1.py", "max_issues_repo_name": "Thanh-Hoo/Custom_train_PanNet", "max_issues_repo_head_hexsha": "aa50df0e32991d35112f3de6627baea963f0827a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2020-10-15T01:27:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T07:25:14.000Z", "max_forks_repo_path": "loss/emb_loss_v1.py", "max_forks_repo_name": "Thanh-Hoo/Custom_train_PanNet", "max_forks_repo_head_hexsha": "aa50df0e32991d35112f3de6627baea963f0827a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-10-05T14:55:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-21T15:51:40.000Z", "avg_line_length": 38.1954022989, "max_line_length": 108, "alphanum_fraction": 0.5847126091, "include": true, "reason": "import numpy", "num_tokens": 875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.1544858639610964}}
{"text": "__all__ = [\n    \"check_dp\",\n    \"t_eff\",\n    \"paramget\",\n    \"berv\",\n    \"v_orb\",\n    \"astropyberv\",\n    \"calculateberv\",\n    \"phase\",\n    \"RV_star\",\n    \"transit\",\n    \"RV\",\n    \"dRV\"\n]\n\ndef check_dp(dp):\n    \"\"\"\n    This is a helper function that checks for the presence of a config file\n    and an obs_times file at path dp. It also checks that dp is a Path object and returns\n    it as such.\n    \"\"\"\n    from tayph.util import check_path\n    from pathlib import Path\n    check_path(dp)\n    if isinstance(dp,str):\n        dp = Path(dp)\n    p1=dp/'obs_times'\n    p2=dp/'config'\n    check_path(p1,exists=True)\n    check_path(p2,exists=True)\n    return(dp)\n\n\ndef paramget(keyword,dp,full_path=False):\n    \"\"\"This code queries a planet system parameter from a config file located in the folder\n    specified by the path dp; or run configuration parameters from a file speciefied by the full\n    path dp, if full_path is set to True.\n\n    Parameters\n    ----------\n    keyword : str\n        A keyword present in the cofig file.\n\n    dp : str, Path\n        Output filename/path.\n\n    full_path: bool\n        If set, dp refers to the actual file, not the location of a folder with a config.dat;\n        but the actual file itself.\n\n    Returns\n    -------\n    value : int, float, bool, str\n        The value corresponding to the requested keyword.\n\n    \"\"\"\n    from tayph.vartests import typetest\n    from tayph.util import check_path\n    import pathlib\n    import distutils.util\n    import pdb\n\n\n    #This is probably the only case where I don't need obs_times and config to exist together...\n    dp=check_path(dp)\n    typetest(keyword,str,'keyword in paramget()')\n\n    if isinstance(dp,str) == True:\n        dp=pathlib.Path(dp)\n    try:\n        if full_path == False:\n            dp = dp/'config'\n        f = open(dp, 'r')\n    except FileNotFoundError:\n        raise FileNotFoundError('parameter file does not exist at %s' % str(dp)) from None\n    x = f.read().splitlines()\n    f.close()\n    n_lines=len(x)\n    keywords={}\n    for i in range(0,n_lines):\n        line=x[i].split()\n        if len(line) > 1:\n            try:\n                value=float(line[1])\n            except ValueError:\n                try:\n                    value=bool(distutils.util.strtobool(line[1]))\n                except ValueError:\n                    value=(line[1])\n            keywords[line[0]] = value\n    try:\n        return(keywords[keyword])\n    except KeyError:\n        # print(keywords)\n        raise Exception('Keyword %s is not present in parameter file at %s' % (keyword,dp)) from None\n\ndef t_eff(M,R):\n    \"\"\"This function computes the mass and radius of a star given its mass and radius relative to solar.\"\"\"\n    from tayph.vartests import typetest\n    import numpy as np\n    import astropy.constants as const\n\n    typetest(M,[int,float],'M in t_eff()')\n    typetest(R,[int,float],'R in t_eff()')\n    M=float(M)\n    R=float(R)\n\n    Ms = const.M_sun\n    Rs = const.R_sun\n    Ls = const.L_sun\n    sb = const.sigma_sb\n\n    if M < 0.43:\n        a = 0.23\n        b = 2.3\n    elif M < 2:\n        a = 1.0\n        b = 4.0\n    elif M < 55:\n        a = 1.4\n        b = 3.5\n    else:\n        a = 32000.0\n        b = 1.0\n\n    T4 = a*M**b * Ls / (4*np.pi*R**2*Rs**2*sb)\n    return(T4**0.25)\n\n\ndef berv(dp):\n    \"\"\"This retrieves the BERV corrcetion tabulated in the obs_times table.\n    Example: brv=berv('data/Kelt-9/night1/')\n    The output is an array with length N, corresponding to N exposures. These values\n    are / should be taken from the FITS header.\n    \"\"\"\n    from astropy.io import ascii\n    from pathlib import Path\n    dp=check_dp(dp)#Path object\n\n    d=ascii.read(dp/'obs_times',comment=\"#\")\n    try:\n        berv = d['col5']#Needs to be in col 5.\n    except:\n        raise Exception(f'Runtime error in sp.berv(): col5 could not be indexed. Check the integrity of your obst_times file located at {dp}.')\n    return berv.data\n\n\ndef v_orb(dp):\n    \"\"\"\n    This program calculates the orbital velocity in km/s for the planet in the\n    data sequence provided in dp, the data-path. dp starts in the root folder,\n    i.e. it starts with data/projectname/. This assumes a circular orbit.\n\n    The output is a number in km/s.\n\n    Parameters\n    ----------\n    dp : str, path like\n        The path to the dataset containing the config file.\n\n    Returns\n    -------\n    v_orb : float\n        The planet's orbital velocity.\n\n    list_of_sigmas_corrected : list\n        List of 2D error matrices, telluric corrected.\n\n    \"\"\"\n    import numpy as np\n    import pdb\n    import astropy.units as u\n    from tayph.vartests import typetest,postest\n\n    dp=check_dp(dp)#Path object\n    P=paramget('P',dp)\n    r=paramget('a',dp)\n    typetest(P,float,'P in sp.v_orb()')\n    typetest(r,float,'r in sp.v_orb()')\n    postest(P,'P in sp.v_orb()')\n    postest(r,'r in sp.v_orb()')\n\n    return (2.0*np.pi*r*u.AU/(P*u.d)).to('km/s').value\n\n\n\n\n\ndef astropyberv(dp):\n    \"\"\"\n    This does the same as berv(dp), but uses astropy to compute the BERV for the\n    dates of observation given a data parameter file.\n    Useful if the BERV keyword was somehow wrong or missing, or if you wish to\n    cross-validate. Requires latitude, longitude, ra, dec and elevation to be provided in\n    the config file as lat, long, RA, DEC and elev in units of degrees and meters.\n    Date should be provided as mjd.\n    \"\"\"\n    from tayph.vartests import typetest\n    from pathlib import Path\n    import numpy as np\n    from astropy.io import ascii\n    from astropy.time import Time\n    from astropy import units as u\n    from astropy.coordinates import SkyCoord, EarthLocation\n    dp=check_dp(dp)#Path object\n    d=ascii.read(dp/'obs_times',comment=\"#\")#,names=['mjd','time','exptime','airmass'])\n    #Not using named columns because I may not know for sure how many columns\n    #there are, and read-ascii breaks if only some columns are named.\n    #The second column has to be an MJD date array though.\n    dates = d['col1']\n    RA=paramget('RA',dp)\n    DEC=paramget('DEC',dp)\n    typetest(RA,str,'RA in sp.astropyberv()')\n    typetest(DEC,str,'DEC in sp.astropyberv()')\n    berv = []\n    observatory = EarthLocation.from_geodetic(lat=paramget('lat',dp)*u.deg, lon=paramget('long',dp)*u.deg, height=paramget('elev',dp)*u.m)\n    sc = SkyCoord(RA+' '+DEC, unit=(u.hourangle, u.deg))\n    for date in dates:\n        barycorr = sc.radial_velocity_correction(obstime=Time(date,format='mjd'), location=observatory).to(u.km/u.s)\n        berv.append(barycorr.value)\n    return berv\n\n\ndef calculateberv(date,lat,long,elev,ra,dec):\n    \"\"\"This is a copy of the astropyberv above, but as a function for a single\n    date in mjd. lat, long, RA, DEC and elev are in units of degrees and meters.\"\"\"\n    from astropy.time import Time\n    from astropy import units as u\n    from astropy.coordinates import SkyCoord, EarthLocation\n    observatory = EarthLocation.from_geodetic(lat=lat*u.deg, lon=long*u.deg, height=elev*u.m)\n    sc = SkyCoord(f'{ra} {dec}', unit=(u.hourangle, u.deg))\n    barycorr = sc.radial_velocity_correction(obstime=Time(date,format='mjd'), location=observatory).to(u.km/u.s)\n    return(barycorr.value)\n\n\n\ndef phase(dp):\n    \"\"\"\n    Calculates the orbital phase of the planet in the data\n    sequence provided using the parameters in dp/config and the timings in\n    dp/obstimes.\n\n    The output is an array with length N, corresponding to N exposures.\n\n    Be CAREFUL: This program provides a time difference of ~1 minute compared\n    to IDL/calctimes. This likely has to do with the difference between HJD\n    and BJD, and the TDB timescale. In the future you should have a thorough\n    look at the time-issue, because you should be able to get this right to the\n    second. At the very least, make sure that the time conventions are ok.\n\n    More importantly: The transit center time needs to be provided in config\n    in BJD.\n    \"\"\"\n    from tayph.vartests import typetest\n    import numpy as np\n    from astropy.io import ascii\n    from astropy.time import Time\n    from astropy import units as u, coordinates as coord\n    import tayph.util as ut\n    dp=check_dp(dp)#Path object\n    d=ascii.read(dp/'obs_times',comment=\"#\")#,names=['mjd','time','exptime','airmass'])\n    #Not using the named columns because I may not know for sure how many columns\n    #there are, and read-ascii breaks if only some columns are named.\n    #The second column has to be a date array though.\n\n    # t = Time(d['col2'],scale='utc', location=coord.EarthLocation.of_site('paranal'))# I determined that the difference between this and geodetic 0,0,0 is zero.\n    t = Time(d['col2'],scale='utc', location=coord.EarthLocation.from_geodetic(0,0,0))\n\n    jd = t.jd\n    P=paramget('P',dp)\n    RA=paramget('RA',dp)\n    DEC=paramget('DEC',dp)\n    Tc=paramget('Tc',dp)#Needs to be given in BJD!\n\n    typetest(P,float,'P in sp.phase()')\n    typetest(Tc,float,'Tc in sp.phase()')\n    typetest(RA,str,'RA in sp.phase()')\n    typetest(DEC,str,'DEC in sp.phase()')\n\n    ip_peg = coord.SkyCoord(RA,DEC,unit=(u.hourangle, u.deg), frame='icrs')\n    ltt_bary = t.light_travel_time(ip_peg)\n\n    n=0.0\n    Tc_n=Time(Tc,format='jd',scale='tdb')\n    while Tc_n.jd >= min(jd):\n        Tc_n=Time(Tc-100.0*n*P,format='jd',scale='tdb')#This is to make sure that the Transit central time PRECEDES the observations (by tens or hundreds or thousands of years). Otherwise, the phase could pick up a minus sign somewhere and be flipped. I wish to avoid that.\n        n+=1\n    BJD = t.tdb + ltt_bary\n    diff = BJD-Tc_n\n    phase=((diff.jd) % P)/P\n    return phase\n\ndef transit(dp):\n    \"\"\"This code uses Ians astro python routines for the approximate Mandel &\n    Agol transit lightcurve to produce the predicted transit lightcurve for the\n    planet described by the configfile located at dp/config.\n    This all assumes a circular orbit.\n    ===========\n    Derivation:\n    ===========\n    occultnonlin_small(z,p, cn) is the algorithm of the Mandel&Agol derivation.\n    z = d/R_star, where d is the distance of the planet center to the LOS to the\n    center of the star.\n    sin(alpha) = d/a, with a the orbital distance (semi-major axis).\n    so sin(alpha)*a/Rstar = d/a*a/Rstar = d/Rstar = z.\n    a/Rstar happens to be a quantity that is well known from the transit light-\n    curve. So z = sin(2pi phase)*a/Rstar. But this is in the limit of i = 90.\n\n    From Cegla 2016 it follows that z = sqrt(xp^2 + yp^2). These are given\n    as xp = a/Rstar sin(2pi phase) and yp = -a/Rstar * cos(2pi phase) * cos(i).\n\n    The second quantity, p, is Rp/Rstar, also well known from the transit light-\n    curve.\n\n    cn is a four-element vector with the nonlinear limb darkening coefficients.\n    If a shorter sequence is entered, the later values will be set to zero.\n    By default I made it zero; i.e. the injected model does not take into\n    account limb-darkening.\n    \"\"\"\n    from tayph.vartests import typetest\n    import tayph.util as ut\n    import tayph.iansastropy as iap\n    import numpy as np\n    import pdb\n    dp=ut.check_path(dp)\n    p=phase(dp)\n    a_Rstar=paramget('aRstar',dp)\n    Rp_Rstar=paramget('RpRstar',dp)\n    i=paramget('inclination',dp)\n    typetest(a_Rstar,float,'Rp_Rstar')\n    typetest(a_Rstar,float,'a_Rstar')\n    typetest(i,float,'i')\n\n    xp=np.sin(p*2.0*np.pi)*a_Rstar\n    yp=np.cos(p*2.0*np.pi)*np.cos(np.radians(i))*a_Rstar\n    z=np.sqrt(xp**2.0 + yp**2.0)\n    transit=iap.occultnonlin_small(z,Rp_Rstar,[0.0,0.0])\n    return transit\n\n\n\ndef RV_star(dp):\n    \"\"\"\n    This calculates the radial velocity in km/s for the star in the\n    data sequence provided in dp. The output is an array with length N,\n    corresponding to N exposures. The radial velocity is provided in km/s.\n    This is meant to be used to correct (align) the stellar spectra to the same\n    reference frame. It requires K (the RV-semi amplitude to be provided in the\n    config file, in km/s as well. Often this value is given in discovery papers.\n    Like all my routines, this assumes a circular orbit.\n    \"\"\"\n    from tayph.vartests import typetest\n    import numpy as np\n    dp=check_dp(dp)\n    p=phase(dp)\n    K=paramget('K',dp)\n    typetest(K,float,'K in sp.RV_star()')\n    rv=K*np.sin(2.0*np.pi*p) * (-1.0)\n    return(rv)\n\ndef RV(dp,vorb=None,vsys=False):\n    \"\"\"This program calculates the radial velocity in km/s for the planet in the\n    data sequence provided in dp, the data-path. dp starts in the root folder,\n    i.e. it starts with data/projectname/, and it ends with a slash.\n\n    Example: v=RV('data/Kelt-9/night1/')\n    The output is an array with length N, corresponding to N exposures.\n    The radial velocity is provided in km/s.\"\"\"\n    import tayph.util as ut\n    import numpy as np\n    from tayph.vartests import typetest\n    dp=ut.check_path(dp)\n    p=phase(dp)\n    i=paramget('inclination',dp)\n    typetest(i,float,'i')\n    if vorb == None:\n        vorb=v_orb(dp)\n    typetest(vorb,float,'vorb in sp.RV')\n    rv=vorb*np.sin(2.0*np.pi*p)*np.sin(np.radians(i))\n\n    if vsys == True:\n        vs=paramget('vsys',dp)\n        rv+=vs\n    return rv#In km/s.\n\n\ndef dRV(dp):\n    \"\"\"This program calculates the change in radial velocity in km/s for the\n    planet in the data sequence provided in dp, the data-path. dp starts in the\n    root folder,i.e. it starts with data/projectname/, and it ends with a slash.\n\n    Example: dv=dRV('data/Kelt-9/night1/')\n    The output is an array with length N, corresponding to N exposures.\n    The change in radial velocity is calculated using the first derivative of the\n    formula for RV, multiplied by the exposure time provided in obs_times.\n    The answer is provided in units of km/s change within each exposure.\"\"\"\n    from tayph.vartests import typetest\n    import numpy as np\n    import astropy.units as u\n    from astropy.io import ascii\n    import pdb\n    import tayph.util as ut\n    dp=ut.check_path(dp,exists=True)\n    obsp=ut.check_path(dp/'obs_times',exists=True)\n\n    d=ascii.read(obsp,comment=\"#\")\n    #Texp=d['exptime'].astype('float')\n    Texp=d['col3'].data#astype('float')\n    vorb=v_orb(dp)\n    p=phase(dp)\n    P=paramget('P',dp)\n    i=paramget('inclination',dp)\n    typetest(P,float,'P in dRV()')\n    typetest(i,float,'i in dRV()')\n\n    dRV=vorb*np.cos(2.0*np.pi*p)*2.0*np.pi/((P*u.d).to('s').value)*np.sin(np.radians(i))\n    return abs(dRV*Texp)\n", "meta": {"hexsha": "93124d14b44707a3f0b817edc9f76ce9e14dca3a", "size": 14335, "ext": "py", "lang": "Python", "max_stars_repo_path": "tayph/system_parameters.py", "max_stars_repo_name": "thorsbro/tayph", "max_stars_repo_head_hexsha": "373a59d339354e2c09484cd3fd5a24d651e0b98b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-12-08T15:08:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T19:31:35.000Z", "max_issues_repo_path": "tayph/system_parameters.py", "max_issues_repo_name": "thorsbro/tayph", "max_issues_repo_head_hexsha": "373a59d339354e2c09484cd3fd5a24d651e0b98b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 83, "max_issues_repo_issues_event_min_datetime": "2020-08-19T16:07:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T09:33:32.000Z", "max_forks_repo_path": "tayph/system_parameters.py", "max_forks_repo_name": "thorsbro/tayph", "max_forks_repo_head_hexsha": "373a59d339354e2c09484cd3fd5a24d651e0b98b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-08-17T17:07:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T05:14:11.000Z", "avg_line_length": 34.2942583732, "max_line_length": 273, "alphanum_fraction": 0.6561562609, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 3993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.15439596978333436}}
{"text": "# adjust python path so we may import things from peer packages\nimport sys\nimport os\nimport numpy as np\nimport pandas as pd\nimport datetime\nfrom optparse import OptionParser\nfrom version import VERSION_DESC\n\nimport terrain\nimport connection\nimport zone\nimport scenario\nimport curve\nimport curve_log\nimport dbimport\nimport logger\nimport database\nimport debris\nimport wateringress\nimport engine\nfrom house import zoneByLocationMap, connByZoneTypeMap, ctgMap, \\\n    connByTypeGroupMap, inflZonesByConn, connByTypeMap, connByIDMap, zoneByIDMap\n\n\nclass CurvePlot(object):\n    def __init__(self, coeff, method, xmin, xmax, label='_nolegend_', col='b'):\n        self.coeff = coeff\n        self.method = method\n        self.x_arr = np.linspace(xmin, xmax, 500)\n        self.label = label\n        self.col = col\n\n    def plot_vuln(self, faint=False):\n        alpha = 0.3 if faint else 1.0\n        col = 'r' if faint else 'b'\n        if self.method == 'lognormal':\n            obs = curve_log.generate_observations(self.coeff, self.x_arr)\n            output.plot_fitted_curve(self.x_arr, obs, self.label, alpha, col)\n        else:\n            obs = curve.generate_observations(self.coeff, self.x_arr)\n            output.plot_fitted_curve(self.x_arr, obs, self.label, alpha, col)\n\n    def plot_frag(self, faint=False):\n        alpha = 0.3 if faint else 1.0\n        obs = curve_log.generate_observations(self.coeff, self.x_arr)\n        output.plot_fragility_curve(self.x_arr, obs, self.label, alpha,\n                                    self.col)\n\n\nclass WindDamageSimulator(object):\n    \"\"\"\n    WindDamageSimulator: Stores sampled state (PDF) for house and wind for\n    current simulation loop\n\n    # results (for v) stored in dictionary bucket keyed with wind_speed\n    # each entry has list form: (FLD_MEAN, [FLD_DIARRAY], [FLD_FRAGILITIES],\n    # FLD_PRESSURIZED_COUNT, [FLD_DEBRIS_AT])\n    # subarrays are indexed by house(iteration)\n\n    \"\"\"\n    FLD_MEAN = 0\n    FLD_DIARRAY = 1\n    FLD_FRAGILITIES = 2\n    FLD_PRESSURIZED_COUNT = 3\n    FLD_DEBRIS_AT = 4\n    FLD_WI_AT = 5\n    FLD_DEBRIS_NV_AT = 6\n    FLD_DEBRIS_NUM_AT = 7\n    result_buckets = {}\n\n    # record: fragility level name, level, plot color, CurvePlot\n    fragility_thresholds = [['slight', 0.0, 'b', None],\n                            ['medium', 0.0, 'g', None],\n                            ['severe', 0.0, 'y', None],\n                            ['complete', 0.0, 'r', None]]\n\n    def __init__(self, options, diCallback=None, mplDict=None):\n        self.s = None\n        self.debrisManager = None\n        self.A_final = None\n        self.diCallback = diCallback\n        self.wind_orientation = 0\n        self.mzcat = 0\n        self.di = 0\n        self.mplDict = mplDict\n        self.prevCurvePlot = None\n        self.options = options\n\n        # Undefined and later added\n        self.result_wall_collapse = None\n        self.cols = None\n        self.rows = None\n        self.house_number = None\n        self.qz = 0.0\n        self.Ms = 1.0\n        self.di = 0.0\n        self.fragilities = []\n        self.profile = None\n        self.mzcat = None\n        self.cpiAt = None\n        self.cpi = None\n        self.internally_pressurized = None\n        self.construction_level = None\n        self.cpiAt = None\n        self.prev_di = None\n        self.water_ingress_cost = None\n        self.file_cpis = None\n        self.file_debris = None\n        self.file_damage = None\n        self.file_dmg = None\n        self.file_frag = None\n        self.file_water = None\n        self.speeds = None\n        self.dmg_map = None\n        self.frag_levels = None\n        self.wind_speeds = None\n        self.di_means = None\n        self.ss = None\n\n        global output\n        if mplDict is not None:\n            output = __import__('gui.output').output\n            output.hookupWidget(mplDict)\n            self.mplDict = mplDict\n        else:\n            output = __import__('core.output').output\n\n        terrain.populate_wind_profile_by_terrain()\n        self.clear_loop_results()\n\n    @staticmethod\n    def set_fragility_thresholds(thresholds):\n        # thresholds is a dict in form {'slight': 0.0}\n        for thresh_key in thresholds:\n            for tup in WindDamageSimulator.fragility_thresholds:\n                if tup[0] == thresh_key:\n                    tup[1] = thresholds[thresh_key]\n                    break\n\n    def set_scenario(self, s):\n        \"\"\"\n        simulate an intact house\n        Args:\n            s: an instance of Scenario class\n\n        Returns:\n\n        \"\"\"\n        self.s = s\n        self.cols = [chr(x) for x in range(ord('A'), ord('A') +\n                                           self.s.house.roof_columns)]\n        self.rows = range(1, self.s.house.roof_rows + 1)\n        self.set_fragility_thresholds(s.fragility_thresholds)\n        self.s.house.clear_sim_results()\n\n    def clear_loop_results(self):\n        self.qz = 0.0\n        self.Ms = 1.0\n        self.di = 0.0\n        self.fragilities = []\n\n    def set_wind_direction(self):\n        self.wind_orientation = self.s.getWindDirIndex()\n        if self.debrisManager:\n            self.debrisManager.set_wind_direction_index(self.wind_orientation)\n\n    def set_wind_profile(self):\n        self.profile = np.random.random_integers(1, 10)\n        self.mzcat = terrain.calculateMZCAT(self.s.terrain_category,\n                                            self.profile,\n                                            self.s.getHouseHeight())\n\n    def calculate_qz(self, wind_speed):\n        if self.s.regional_shielding_factor <= 0.85:\n            thresholds = np.array([63, 63+15])\n            ms_dic = {0: 1.0, 1: 0.85, 2: 0.95}\n            idx = sum(thresholds <= np.random.random_integers(0, 100))\n            self.Ms = ms_dic[idx]\n            Vmod = (wind_speed * self.Ms) / self.s.regional_shielding_factor\n            self.qz = 0.6 * 1.0e-3 * (Vmod * self.mzcat)**2\n        else:\n            self.qz = 0.6 * 1.0e-3 * (wind_speed * self.mzcat)**2\n\n    def check_pressurized_failure(self, v):\n        if self.s.getOpt_Debris():\n            self.debrisManager.run(v)\n            if self.cpi == 0 and self.debrisManager.get_breached():\n                self.cpi = 0.7\n                self.cpiAt = v\n                self.file_cpis.write('%d,%.3f\\n' % (self.house_number + 1, v))\n\n    def sample_house_and_wind_params(self):\n        self.cpi = 0\n        self.cpiAt = 0\n        self.internally_pressurized = False\n        self.set_wind_profile()\n        self.s.house.reset_results()\n        self.prev_di = 0\n\n        self.construction_level = 'na'\n        mean_factor = 1.0\n        cov_factor = 1.0\n        if self.s.getOpt_ConstructionLevels():\n            self.construction_level, mean_factor, cov_factor = \\\n                self.s.sampleConstructionLevel()\n\n        connection.assign_connection_strengths(self.s.house.connections,\n                                               mean_factor,\n                                               cov_factor)\n\n        connection.assign_connection_deadloads(self.s.house.connections)\n\n        zone.sample_zone_pressures(self.s.house.zones,\n                                   self.wind_orientation,\n                                   self.s.house.cpe_V,\n                                   self.s.house.cpe_k,\n                                   self.s.house.cpe_struct_V)\n        # we don't want to collapse multiple times (no need)\n        self.result_wall_collapse = False\n\n    def check_house_collapse(self, wind_speed):\n        if not self.result_wall_collapse:\n            for ctg in self.s.house.conn_type_groups:\n                if ctg.trigger_collapse_at > 0:\n                    perc_damaged = 0\n                    for ct in ctg.conn_types:\n                        perc_damaged += ct.perc_damaged()\n                    if perc_damaged >= ctg.trigger_collapse_at:\n                        for c in self.s.house.connections:\n                            c.damage(wind_speed, 99.9, inflZonesByConn[c])\n                        for z in self.s.house.zones:\n                            z.result_effective_area = 0\n                        self.result_wall_collapse = True\n\n    def calculate_connection_group_areas(self):\n        for ctg in self.s.house.conn_type_groups:\n            ctg.result_area = 0.0\n        for c in self.s.house.connections:\n            c.ctype.group.result_area += c.ctype.costing_area\n\n    def calculate_damage_ratio(self, wind_speed):\n\n        # calculate damage percentages        \n        for ctg in self.s.house.conn_type_groups:\n            ctg.result_percent_damaged = 0.0\n            if ctg.group_name == 'debris':\n                if not self.debrisManager:\n                    ctg.result_percent_damaged = 0\n                else:\n                    ctg.result_percent_damaged = \\\n                        self.debrisManager.result_dmgperc\n            else:\n                for ct in ctg.conn_types:\n                    for c in ct.connections_of_type:\n                        if c.result_damaged:\n                            ctg.result_percent_damaged += \\\n                                c.ctype.costing_area / float(ctg.result_area)\n\n        # calculate repair cost\n        repair_cost = 0\n        for ctg in self.s.house.conn_type_groups:\n            ctg_perc = ctg.result_percent_damaged\n            if ctg_perc > 0:\n                fact_arr = [0]\n                for factor in self.s.house.factorings:\n                    if factor.parent_id == ctg.id:\n                        factor_perc = factor.factor.result_percent_damaged\n                        if factor_perc:\n                            fact_arr.append(factor_perc)\n                max_factor_perc = max(fact_arr)\n                if ctg_perc > max_factor_perc:\n                    ctg_perc = ctg_perc - max_factor_perc\n                    repair_cost += ctg.costing.calculate_damage(ctg_perc)\n\n        # calculate initial envelope repair cost before water ingress is added\n        self.di = repair_cost / self.s.house.replace_cost\n        if self.di > 1.0:\n            self.di = 1.0\n        else:\n            self.water_ingress_cost = 0\n            if self.s.getOpt_WaterIngress():\n                self.water_ingress_cost = \\\n                    wateringress.get_costing_for_envelope_damage_at_v(\n                        self.di,\n                        wind_speed,\n                        self.s.house.water_groups,\n                        self.file_water)\n                repair_cost += self.water_ingress_cost\n\n        # combined internal + envelope damage costing can now be calculated\n        self.di = repair_cost / self.s.house.replace_cost\n        if self.di > 1.0:\n            self.di = 1.0\n        self.prev_di = self.di\n\n    def redistribute_damage(self, ctg):\n        # setup for distribution\n        if ctg.distribution_order <= 0:\n            return\n        distByCol = ctg.distribution_direction == 'col'\n        primaryDir = self.cols\n        secondaryDir = self.rows\n        if not distByCol:\n            primaryDir = self.rows\n            secondaryDir = self.cols\n\n        # walk the zone grid for current group\n        # (only one conn of each group per zone)\n        for i in primaryDir:\n            for j in secondaryDir:\n                # determine zoneLocation and then zone\n                zoneLoc = i if distByCol else j\n                zoneLoc += str(j) if distByCol else str(i)\n\n                # not all grid locations have a zone\n                if zoneLoc not in zoneByLocationMap:\n                    continue\n\n                # not all zones have area or connections remaining\n                z = zoneByLocationMap[zoneLoc]\n                if z.result_effective_area == 0.0 or len(z.located_conns) == 0:\n                    continue\n\n                # not all zones have connections of all types\n                if ctg.group_name not in connByZoneTypeMap[z.zone_name]:\n                    continue\n\n                # grab appropriate connection from zone\n                c = connByZoneTypeMap[z.zone_name][ctg.group_name]\n\n                # if that connection is (newly) damaged then redistribute\n                # load/infl/area\n                if c.result_damaged and not c.result_damage_distributed:\n                    # print 'Connection: %s newly damaged' % c\n\n                    if ctg.patch_distribution == 1:\n                        patchList = \\\n                            database.db.qryConnectionPatchesFromDamagedConn(c.id)\n\n                        for patch in patchList:\n                            patch_zone = zoneByIDMap[patch[1]]\n                            patch_conn = connByIDMap[patch[0]]\n                            curr_infl = inflZonesByConn[patch_conn].get(\n                                patch_zone, None)\n                            if curr_infl is None:\n                                # print 'discarding patch as no existing patch present: %s-->%s = %f' % (patch_conn, patch_zone, patch[2])\n                                continue\n                            # print 'patching: %s-->%s = %f' % (patch_conn, patch_zone, patch[2])\n                            inflZonesByConn[patch_conn][patch_zone] = patch[2]\n                    else:\n                        gridCol, gridRow = zone.getGridFromZoneLoc(z.zone_name)\n                        if c.edge != 3:\n                            if distByCol:\n                                if c.edge == 0:\n                                    k = 0.5\n                                    if not self.redistribute_to_nearest_zone(z, range(gridRow+1, self.s.house.roof_rows), k, ctg, gridCol, gridRow, distByCol):\n                                        k = 1.0\n                                    if not self.redistribute_to_nearest_zone(z, reversed(range(0, gridRow)), k, ctg, gridCol, gridRow, distByCol):\n                                        self.redistribute_to_nearest_zone(z, range(gridRow+1, self.s.house.roof_rows), k, ctg, gridCol, gridRow, distByCol)\n                                elif c.edge == 2:\n                                    k = 1.0\n                                    self.redistribute_to_nearest_zone(z, range(gridRow+1, self.s.house.roof_rows), k, ctg, gridCol, gridRow, distByCol)\n                                elif c.edge == 1:\n                                    k = 1.0\n                                    self.redistribute_to_nearest_zone(z, reversed(range(0, gridRow)), k, ctg, gridCol, gridRow, distByCol)\n                            else:\n                                if c.edge == 0:\n                                    k = 0.5\n                                    if not self.redistribute_to_nearest_zone(z, range(gridCol+1, self.s.house.roof_columns), k, ctg, gridCol, gridRow, distByCol):\n                                        k = 1.0\n                                    if not self.redistribute_to_nearest_zone(z, reversed(range(0, gridCol)), k, ctg, gridCol, gridRow, distByCol):\n                                        self.redistribute_to_nearest_zone(z, range(gridCol+1, self.s.house.roof_columns), k, ctg, gridCol, gridRow, distByCol)\n                                elif c.edge == 2:\n                                    k = 1.0\n                                    self.redistribute_to_nearest_zone(z, range(gridCol+1, self.s.house.roof_columns), k, ctg, gridCol, gridRow, distByCol)\n                                elif c.edge == 1:\n                                    k = 1.0\n                                    self.redistribute_to_nearest_zone(z, reversed(range(0, gridCol)), k, ctg, gridCol, gridRow, distByCol)\n\n                    if ctg.set_zone_to_zero > 0:\n                        z.result_effective_area = 0.0\n                    c.result_damage_distributed = True\n\n    @staticmethod\n    def redistribute_to_nearest_zone(zoneSrc, connRange, k, ctgroup, gridCol,\n                                     gridRow, distByCol):\n        for line in connRange:\n            r = line\n            c = gridCol\n            if not distByCol:\n                r = gridRow\n                c = line\n            zoneDest = zoneByLocationMap[zone.getZoneLocFromGrid(c, r)]\n            conn = connByZoneTypeMap[zoneDest.zone_name].get(ctgroup.group_name)\n            if conn:\n                if not conn.result_damaged and zoneDest.result_effective_area > 0:\n                    zoneDest.sampled_cpe = ((zoneDest.result_effective_area * zoneDest.sampled_cpe) +\n                                            (k * zoneSrc.result_effective_area * zoneSrc.sampled_cpe)) / (zoneDest.result_effective_area +\n                                            (k * zoneSrc.result_effective_area))\n                    zoneDest.result_effective_area = zoneDest.result_effective_area + (k * zoneSrc.result_effective_area)\n                    return True\n                if conn.edge > 0:\n                    return False\n        return False\n\n    def run_simulation(self, wind_speed):\n        self.check_pressurized_failure(wind_speed)\n\n        self.calculate_qz(wind_speed)\n        zone.calc_zone_pressures(self.s.house.zones,\n                                 self.wind_orientation,\n                                 self.cpi,\n                                 self.qz,\n                                 self.Ms,\n                                 self.s.building_spacing,\n                                 self.s.getOpt_DiffShielding())\n\n        self.file_damage.write('%d,%.3f,%s' % (self.house_number+1,\n                                               wind_speed,\n                                               scenario.Scenario.dirs[self.wind_orientation]))\n        for ctg in self.s.house.conn_type_groups:\n            connection.calc_connection_loads(wind_speed,\n                                             ctg,\n                                             self.s.house,\n                                             self.file_damage,\n                                             self.dmg_map,\n                                             inflZonesByConn,\n                                             connByTypeMap)\n        if self.s.getOpt_DmgDistribute():\n            for ctg in self.s.house.conn_type_groups:\n                self.redistribute_damage(ctg)\n        self.file_damage.write('\\n')\n\n        self.check_house_collapse(wind_speed)\n        self.calculate_damage_ratio(wind_speed)\n\n    def simulator_mainloop(self, verbose=False):\n        date_run = datetime.datetime.now()\n\n        # setup file based reporting (files must exist and be runnable)\n        if not os.path.exists(self.options.output_folder):\n            os.makedirs(self.options.output_folder)\n\n        self.file_cpis = open(os.path.join(self.options.output_folder,\n                                           'house_cpi.csv'), 'w')\n        self.file_cpis.write('Simulated House #, Cpi Changed At\\n')\n        self.file_debris = open(os.path.join(self.options.output_folder,\n                                             'wind_debris.csv'), 'w')\n        header_ = ('Wind Speed(m/s),% Houses Internally Pressurized,'\n                   '% Debris Damage Mean\\n')\n        self.file_debris.write(header_)\n        self.file_damage = open(os.path.join(self.options.output_folder,\n                                             'house_damage.csv'), 'w')\n        self.file_dmg_idx = open(os.path.join(self.options.output_folder,\n                                             'house_dmg_idx.csv'), 'w')\n        self.file_dmg = open(os.path.join(self.options.output_folder,\n                                          'houses_damaged_at_v.csv'), 'w')\n        self.file_frag = open(os.path.join(self.options.output_folder,\n                                           'fragilities.csv'), 'w')\n        header_ = ('Slight Median,Slight Beta,Medium Median,Median Beta,'\n                   'Severe Median,Severe Beta,Complete Median,Complete Beta\\n')\n        self.file_frag.write(header_)\n        self.file_water = open(os.path.join(self.options.output_folder,\n                                            'wateringress.csv'), 'w')\n        header_ = ('V,Envelope DI,Water Damage,Damage Scenario,'\n                   'Water Damage Cost,WaterCosting\\n')\n        self.file_water.write(header_)\n\n        header = 'Simulated House #,Wind Speed(m/s),Wind Direction,'\n\n        list_ = [ct.connection_type for ctg in self.s.house.conn_type_groups\n                 if ctg.enabled for ct in ctg.conn_types]\n        header += ','.join(list_)\n        header += '\\n'\n        self.file_damage.write(header)\n\n        # optionally seed random numbers\n        if self.s.getOpt_SampleSeed():\n            np.random.seed(42)\n            zone.seed_scipy(42)\n            engine.seed(42)\n\n        # setup speeds and buckets\n        self.speeds = np.linspace(self.s.wind_speed_min,\n                                  self.s.wind_speed_max,\n                                  self.s.wind_speed_num_steps)\n\n        for wind_speed in self.speeds:\n            type(self).result_buckets[wind_speed] = \\\n                [0., [], [], 0, [], [], [], []]\n\n        # setup connections and groups\n        self.s.house.clear_sim_results()\n        self.calculate_connection_group_areas()\n\n        # optionally create the debris manager and\n        # make sure a wind orientation is set\n        bDebris = self.s.getOpt_Debris()\n        if bDebris:\n            self.debrisManager = debris.DebrisManager(\n                self.s.house,\n                self.s.region,\n                self.s.wind_speed_min,\n                self.s.wind_speed_max,\n                self.s.wind_speed_num_steps,\n                self.s.getOpt_DebrisStaggeredSources(),\n                self.s.debris_radius,\n                self.s.debris_angle,\n                self.s.debris_extension,\n                self.s.building_spacing,\n                self.s.source_items,\n                self.s.flighttime_mean,\n                self.s.flighttime_stddev)\n        self.set_wind_direction()\n\n        # gui bookkeeping\n        if self.diCallback:\n            totalLoops = self.s.num_iters * len(self.speeds)\n            currentLoop = 1\n\n        # SIMULATE HOUSES\n        house_results = []\n        keep_looping = True\n\n        # iteration over samples\n        for house_number in range(self.s.num_iters):\n            self.house_number = house_number\n            if not keep_looping:\n                break\n\n            # sample new house and wind direction (if random)\n            if self.s.wind_dir_index == 8:\n                self.set_wind_direction()\n\n            self.sample_house_and_wind_params()\n\n            # prime damage map where we track min() V that damage occurs\n            # across types for this house (reporting)\n            self.dmg_map = {}\n            for conn_type in self.s.house.conn_types:\n                self.dmg_map[conn_type.connection_type] = 99999\n\n            # iteration over wind speed list\n            for wind_speed in self.speeds:\n\n                # simulate sampled house\n                self.clear_loop_results()\n                self.run_simulation(wind_speed)\n\n                # collect results\n                type(self).result_buckets[wind_speed][type(self).FLD_WI_AT].append(self.water_ingress_cost)\n                type(self).result_buckets[wind_speed][type(self).FLD_DIARRAY].append(self.di)\n                if bDebris:\n                    type(self).result_buckets[wind_speed][type(self).FLD_DEBRIS_AT].append(self.debrisManager.result_dmgperc)\n                    type(self).result_buckets[wind_speed][type(self).FLD_DEBRIS_NV_AT].append(self.debrisManager.result_nv)\n                    type(self).result_buckets[wind_speed][type(self).FLD_DEBRIS_NUM_AT].append(self.debrisManager.result_num_items)\n                else:\n                    type(self).result_buckets[wind_speed][type(self).FLD_DEBRIS_AT].append(0.0)\n                    type(self).result_buckets[wind_speed][type(self).FLD_DEBRIS_NV_AT].append(0)\n                    type(self).result_buckets[wind_speed][type(self).FLD_DEBRIS_NUM_AT].append(0)\n\n                # for all houses, count the number that were pressurized at this wind_speed   \n                if self.cpi != 0:\n                    type(self).result_buckets[wind_speed][type(self).FLD_PRESSURIZED_COUNT] += 1\n\n                # interact with GUI listener\n                if self.diCallback:\n                    currentLoop += 1\n                    percLoops = (float(currentLoop) / float(totalLoops)) * 100.0\n                    keep_looping = self.diCallback(wind_speed, self.di, percLoops)\n                    if not keep_looping:\n                        break\n\n            # collect results to be used by the GUI client\n            zone_results = {}\n            for z in self.s.house.zones:\n                zone_results[z.zone_name] = [z.zone_name,\n                                             z.sampled_cpe,\n                                             z.sampled_cpe_struct,\n                                             z.sampled_cpe_eaves]\n\n            conn_results = []\n            for c in self.s.house.connections:\n                conn_results.append([c.ctype.connection_type,\n                                     c.location_zone.zone_name,\n                                     c.result_failure_v_raw,\n                                     c.result_strength,\n                                     c.result_deadload,\n                                     c.result_damaged_report,\n                                     c.ctype.group.group_name,\n                                     c.id])\n\n            house_results.append([zone_results,\n                                  self.dmg_map,\n                                  self.wind_orientation,\n                                  self.cpiAt,\n                                  conn_results,\n                                  self.construction_level])\n\n        if keep_looping:\n            # post processing of results (aggregations)\n            for wind_speed in self.speeds:\n\n                # write debris output file\n                debrisarray = np.array(type(self).result_buckets[wind_speed][type(self).FLD_DEBRIS_AT])\n                perc = type(self).result_buckets[wind_speed][type(self).FLD_PRESSURIZED_COUNT]/float(self.s.num_iters) * 100.0\n                self.file_debris.write('%.3f,%.3f,%.3f\\n' % (wind_speed,\n                                                             perc,\n                                                             np.mean(debrisarray) * 100.0))\n\n                # calculate and store DI mean\n                diarray = np.array(type(self).result_buckets[wind_speed][type(self).FLD_DIARRAY])\n                type(self).result_buckets[wind_speed][type(self).FLD_MEAN] = np.mean(diarray)\n\n                # calculate fragilities\n                for thr in type(self).fragility_thresholds:\n                    filter_ = diarray > thr[1]\n                    p = (float(diarray[filter_].size)) / (float(diarray.size))\n                    type(self).result_buckets[wind_speed][type(self).FLD_FRAGILITIES].append(p)\n\n        # produce damage map report\n        self.file_dmg.write('Number of Damaged Houses\\n')\n        self.file_dmg.write('Num Houses,%d\\n' % self.s.num_iters)\n        self.file_dmg.write('Wind Direction,%s\\n' % scenario.Scenario.dirs[self.wind_orientation])\n        self.file_dmg.write('Wind Speed(m/s)')\n\n        # setup headers and counts\n        str_ = [conn_type.connection_type for conn_type in\n                self.s.house.conn_types]\n        self.file_dmg.write(','.join(str_))\n        self.file_dmg.write('\\n')\n\n        # we need to count houses damaged by type for each v\n        counts = {}\n        for wind_speed in self.speeds:\n            self.file_dmg.write(str(wind_speed))\n\n            # initialise damage counts for each conn_type to zero\n            for conn_type in self.s.house.conn_types:\n                counts[conn_type.connection_type] = 0\n\n            # for all houses, increment type counts\n            # if wind_speed exceeds minimum observed damages.\n            for hr in house_results:\n                dmg_map = hr[1]\n                for conn_type in self.s.house.conn_types:\n                    dmg_min = dmg_map[conn_type.connection_type]\n                    if wind_speed >= dmg_min:\n                        counts[conn_type.connection_type] += 1\n\n            # write accumulated counts for this wind speed\n            str_ = [str(counts[conn_type.connection_type]) for conn_type\n                    in self.s.house.conn_types]\n            self.file_dmg.write(','.join(str_))\n            self.file_dmg.write('\\n')\n\n        # cleanup: close output files\n        self.file_cpis.close()\n        self.file_debris.close()\n        self.file_damage.close()\n        self.file_dmg.close()\n        self.file_water.close()\n        self.debrisManager = None\n\n        # temporary\n        di_summary = []\n        for speed, value in type(self).result_buckets.iteritems():\n            tmp = np.array(value[1])\n            tmp_added = np.append(tmp, [speed, tmp.mean()])\n            di_summary.append(tmp_added)\n\n        columns_str = [str(x) for x in range(self.s.num_iters)]\n        columns_str.append('speed')\n        columns_str.append('mean')\n        df_di_summary = pd.DataFrame(di_summary, columns=columns_str)\n        df_di_summary.to_csv(self.file_dmg_idx, index=False)\n        self.file_dmg_idx.close()\n\n        if keep_looping:\n            self.fit_fragility_curves()\n            self.file_frag.close()\n            runTime = (datetime.datetime.now() - date_run)\n            return runTime, house_results\n        else:\n            self.file_frag.close()\n            return None, None\n\n    def get_windresults_perc_houses_breached(self):\n        breaches = []\n        for wind_speed in self.speeds:\n            perc = type(self).result_buckets[wind_speed][type(self).FLD_PRESSURIZED_COUNT]/float(self.s.num_iters) * 100.0\n            breaches.append(perc)\n        return self.speeds, breaches\n\n    def get_windresults_samples_perc_debris_damage(self):\n        samples = {}\n        for wind_speed in self.speeds:\n            samples[wind_speed] = type(self).result_buckets[wind_speed][type(self).FLD_DEBRIS_AT]\n        return self.speeds, samples\n\n    def get_windresults_samples_nv(self):\n        samples = {}\n        for wind_speed in self.speeds:\n            samples[wind_speed] = type(self).result_buckets[wind_speed][type(self).FLD_DEBRIS_NV_AT]\n        return self.speeds, samples\n\n    def get_windresults_samples_num_items(self):\n        samples = {}\n        for wind_speed in self.speeds:\n            samples[wind_speed] = type(self).result_buckets[wind_speed][type(self).FLD_DEBRIS_NUM_AT]\n        return self.speeds, samples\n\n    def get_windresults_samples_perc_water_ingress(self):\n        samples = {}\n        for wind_speed in self.speeds:\n            samples[wind_speed] = type(self).result_buckets[wind_speed][type(self).FLD_WI_AT]\n        return self.speeds, samples\n\n    def plot_connection_damage(self, vRed, vBlue):\n        for ctg_name in ['sheeting', 'batten', 'rafter', 'piersgroup',\n                         'wallracking', 'Truss']:\n            if ctgMap.get(ctg_name, None) is None:\n                continue\n            vgrid = np.ones((self.s.house.roof_rows, self.s.house.roof_columns),\n                            dtype=np.float32) * vBlue + 10.0\n            for conn in connByTypeGroupMap[ctg_name]:\n                gridCol, gridRow = \\\n                    zone.getGridFromZoneLoc(conn.location_zone.zone_name)\n                if conn.result_failure_v > 0:\n                    vgrid[gridRow][gridCol] = conn.result_failure_v\n            output.plot_damage_show(ctg_name, vgrid, self.s.house.roof_columns,\n                                    self.s.house.roof_rows, vRed, vBlue)\n\n        if 'plot_wall_damage_show' in output.__dict__:\n            wall_major_rows = 2\n            wall_major_cols = self.s.house.roof_columns\n            wall_minor_rows = 2\n            wall_minor_cols = 8\n\n            for ctg_name in ('wallcladding', 'wallcollapse'):\n                if ctgMap.get(ctg_name, None) is None:\n                    continue\n\n                v_south_grid = np.ones((wall_major_rows, wall_major_cols),\n                                       dtype=np.float32) * vBlue + 10.0\n                v_north_grid = np.ones((wall_major_rows, wall_major_cols),\n                                       dtype=np.float32) * vBlue + 10.0\n                v_west_grid = np.ones((wall_minor_rows, wall_minor_cols),\n                                      dtype=np.float32) * vBlue + 10.0\n                v_east_grid = np.ones((wall_minor_rows, wall_minor_cols),\n                                      dtype=np.float32) * vBlue + 10.0\n\n                # construct south grid\n                for gridCol in range(0, wall_major_cols):\n                    for gridRow in range(0, wall_major_rows):\n                        colChar = chr(ord('A')+gridCol)\n                        loc = 'WS%s%d' % (colChar, gridRow+1)\n                        conn = connByZoneTypeMap[loc].get(ctg_name)\n                        if conn and conn.result_failure_v > 0:\n                            v_south_grid[gridRow][gridCol] = \\\n                                conn.result_failure_v\n\n                # construct north grid\n                for gridCol in range(0, wall_major_cols):\n                    for gridRow in range(0, wall_major_rows):\n                        colChar = chr(ord('A')+gridCol)\n                        loc = 'WN%s%d' % (colChar, gridRow+1)\n                        conn = connByZoneTypeMap[loc].get(ctg_name)\n                        if conn and conn.result_failure_v > 0:\n                            v_north_grid[gridRow][gridCol] = \\\n                                conn.result_failure_v\n\n                # construct west grid\n                for gridCol in range(0, wall_minor_cols):\n                    for gridRow in range(0, wall_minor_rows):\n                        loc = 'WW%d%d' % (gridCol+2, gridRow+1)\n                        conn = connByZoneTypeMap[loc].get(ctg_name)\n                        if conn and conn.result_failure_v > 0:\n                            v_west_grid[gridRow][gridCol] = \\\n                                conn.result_failure_v\n\n                # construct east grid\n                for gridCol in range(0, wall_minor_cols):\n                    for gridRow in range(0, wall_minor_rows):\n                        loc = 'WE%d%d' % (gridCol+2, gridRow+1)\n                        conn = connByZoneTypeMap[loc].get(ctg_name)\n                        if conn and conn.result_failure_v > 0:\n                            v_east_grid[gridRow][gridCol] = \\\n                                conn.result_failure_v\n\n                output.plot_wall_damage_show(\n                    ctg_name,\n                    v_south_grid, v_north_grid, v_west_grid, v_east_grid,\n                    wall_major_cols, wall_major_rows,\n                    wall_minor_cols, wall_minor_rows,\n                    vRed, vBlue)\n\n\n    # This needs to be done outside of the plotting function\n    # as these coefficients are\n    # the final output of this program in batch... they are all that matters.\n    #\n    def fit_fragility_curves(self):\n        # unpack the fragility means into seperate arrays for fit/plot.\n        self.frag_levels = []\n        for thr in type(self).fragility_thresholds:\n            self.frag_levels.append(np.zeros(len(self.speeds)))\n        for i, wind_speed in enumerate(self.speeds):\n            for frag_ind in range(len(self.frag_levels)):\n                self.frag_levels[frag_ind][i] = \\\n                    type(self).result_buckets[wind_speed][type(self).FLD_FRAGILITIES][frag_ind]\n\n        # fit curves and store results\n        coeff_arr = []\n        ss = 0\n        for frag_ind in range(len(self.frag_levels)):\n            try:\n                coeff_arr, ss = curve_log.fit_curve(self.speeds,\n                                                    self.frag_levels[frag_ind],\n                                                    False)\n                if frag_ind > 0:\n                    self.file_frag.write(',')\n\n                label = '%s(%.2f)' % (type(self).fragility_thresholds[frag_ind][0],\n                                    type(self).fragility_thresholds[frag_ind][1])\n                self.file_frag.write('%f,%f' % (coeff_arr[0], coeff_arr[1]))\n                type(self).fragility_thresholds[frag_ind][3] = \\\n                    CurvePlot(coeff_arr,\n                              'lognormal',\n                              self.s.wind_speed_min,\n                              self.s.wind_speed_max,\n                              label,\n                              type(self).fragility_thresholds[frag_ind][2])\n            except Exception, e:\n                print 'fit_fragility_curves failed to fit: coeff_arr: %s' % coeff_arr\n                print e\n\n        self.file_frag.write('\\n')\n\n    def plot_fragility(self, output_folder):\n        for frag_ind in range(len(self.frag_levels)):\n            output.plot_fragility_curve(self.speeds,\n                                        self.frag_levels[frag_ind],\n                                        '_nolegend_',\n                                        0.3,\n                                        type(self).fragility_thresholds[frag_ind][2])\n            plot_obj = type(self).fragility_thresholds[frag_ind][3]\n            if plot_obj:\n                plot_obj.plot_frag()\n\n        output.plot_fragility_show(self.s.num_iters,\n                                   self.s.wind_speed_min,\n                                   self.s.wind_speed_max, output_folder)\n\n    def fit_vuln_curve(self):\n        self.wind_speeds = np.zeros(len(self.speeds))\n        self.di_means = np.zeros(len(self.speeds))\n\n        ss = 0\n        for i, wind_speed in enumerate(self.speeds):\n            self.wind_speeds[i] = wind_speed\n            self.di_means[i] = type(self).result_buckets[wind_speed][type(self).FLD_MEAN]\n\n        if self.s.getOpt_VulnFitLog():\n            self.A_final, self.ss = curve_log.fit_curve(self.wind_speeds,\n                                                        self.di_means)\n        else:\n            self.A_final, self.ss = curve.fit_curve(self.wind_speeds,\n                                                    self.di_means)\n\n    def plot_vulnerability(self, output_folder, label=\"Fitted Curve\"):\n        # fit current observations\n        self.fit_vuln_curve()\n\n        # plot means\n        if self.s.num_iters <= 100:\n            for wind_speed in self.speeds:\n                damage_indexes = type(self).result_buckets[wind_speed][type(self).FLD_DIARRAY]\n                output.plot_wind_event_damage([wind_speed]*len(damage_indexes),\n                                              damage_indexes)\n        output.plot_wind_event_mean(self.wind_speeds, self.di_means)\n\n        # plot fitted curve (with previous dimmed red)\n        if self.s.getOpt_VulnFitLog():\n            fn_form = 'lognormal'\n        else:\n            fn_form = 'original'\n\n        cp = CurvePlot(self.A_final,\n                       fn_form,\n                       self.s.wind_speed_min,\n                       self.s.wind_speed_max,\n                       \"Fitted Curve\")\n\n        cp.plot_vuln()\n        if self.prevCurvePlot:\n            self.prevCurvePlot.plot_vuln(True)\n        self.prevCurvePlot = cp\n\n    def show_results(self, output_folder=None, vRed=40, vBlue=80):\n        if self.mplDict:\n            self.mplDict['fragility'].axes.cla()\n            self.mplDict['fragility'].axes.figure.canvas.draw()\n            self.mplDict['vulnerability'].axes.cla()\n            self.mplDict['vulnerability'].axes.figure.canvas.draw()\n        if self.s.getOpt_DmgPlotFragility():\n            self.plot_fragility(output_folder)\n        if self.s.getOpt_DmgPlotVuln():\n            self.plot_vulnerability(output_folder)\n            output.plot_wind_event_show(self.s.num_iters,\n                                        self.s.wind_speed_min,\n                                        self.s.wind_speed_max,\n                                        output_folder)\n        self.plot_connection_damage(vRed, vBlue)\n\n    def clear_connection_damage(self):\n        v = np.ones((self.s.house.roof_rows, self.s.house.roof_columns),\n                    dtype=np.float32) * self.s.wind_speed_max\n        for ctname in ['sheeting', 'batten', 'rafter', 'piersgroup',\n                       'wallracking']:\n            output.plot_damage_show(ctname, v, self.s.house.roof_columns,\n                                    self.s.house.roof_rows,\n                                    self.s.wind_speed_min,\n                                    self.s.wind_speed_max)\n        for ctname in ['wallcladding', 'wallcollapse']:\n            wall_major_rows = 2\n            wall_major_cols = self.s.house.roof_columns\n            wall_minor_rows = 2\n            wall_minor_cols = 8\n            v_major_grid = np.ones((wall_major_rows, wall_major_cols),\n                                   dtype=np.float32) * self.s.wind_speed_max\n            v_minor_grid = np.ones((wall_minor_rows, wall_minor_cols),\n                                   dtype=np.float32) * self.s.wind_speed_max\n            output.plot_wall_damage_show(\n                ctname,\n                v_major_grid, v_major_grid, v_minor_grid, v_minor_grid,\n                wall_major_cols, wall_major_rows,\n                wall_minor_cols, wall_minor_rows,\n                self.s.wind_speed_min, self.s.wind_speed_max)\n\n\nlastiPerc = -1\n\n\ndef simProgressCallback(V, di, percLoops):\n    global lastiPerc\n    iPerc = int(percLoops)\n    if iPerc != lastiPerc:\n        lastiPerc = iPerc\n        sys.stdout.write('.')\n    return True\n\n\n# @profile\ndef simulate(s, options):\n    if options.verbose:\n        arg = simProgressCallback\n    else:\n        arg = None\n    mySim = WindDamageSimulator(options, arg, None)\n    mySim.set_scenario(s)\n    runTime, hr = mySim.simulator_mainloop(options.verbose)\n    if runTime:\n        if options.plot_frag:\n            mySim.plot_fragility(options.output_folder)\n        if options.plot_vuln:\n            mySim.plot_vulnerability(options.output_folder, None)\n            output.plot_wind_event_show(mySim.s.num_iters,\n                                        mySim.s.wind_speed_min,\n                                        mySim.s.wind_speed_max,\n                                        options.output_folder)\n    return runTime\n\n\ndef main():\n    USAGE = ('%prog -s <scenario_file> [-m <model database file>] '\n             '[-o <output_folder>]')\n    parser = OptionParser(usage=USAGE, version=VERSION_DESC)\n    parser.add_option(\"-s\", \"--scenario\",\n                      dest=\"scenario_filename\",\n                      help=\"read scenario description from FILE\",\n                      metavar=\"FILE\")\n    parser.add_option(\"-m\", \"--model\",\n                      dest=\"model_database\",\n                      help=\"Use Model Database from FILE\",\n                      metavar=\"FILE\")\n    parser.add_option(\"-o\", \"--output\",\n                      dest=\"output_folder\",\n                      help=\"folder name to store simulation results\",\n                      metavar=\"FOLDER\")\n    parser.add_option(\"-v\", \"--verbose\",\n                      action=\"store_true\",\n                      dest=\"verbose\",\n                      default=False,\n                      help=\"show verbose simulator output\")\n    parser.add_option(\"-i\", \"--import\",\n                      dest=\"data_folder\",\n                      help=\"data folder to import into model.db\",\n                      metavar=\"FOLDER\")\n    parser.add_option(\"--plot_vuln\",\n                      action=\"store_true\",\n                      dest=\"plot_vuln\",\n                      default=False,\n                      help=\"show vulnerability plot\")\n    parser.add_option(\"--plot_frag\",\n                      action=\"store_true\",\n                      dest=\"plot_frag\",\n                      default=False,\n                      help=\"show fragility plot\")\n\n    (options, args) = parser.parse_args()\n\n    path_, _ = os.path.split(sys.argv[0])\n\n    if options.model_database is None:\n        model_db = None\n    else:\n        model_db = os.path.abspath(os.path.join(os.getcwd(),\n                                                options.model_database))\n    if options.output_folder is None:\n        options.output_folder = os.path.abspath(os.path.join(path_,\n                                                             './outputs'))\n    else:\n        options.output_folder = os.path.abspath(os.path.join(\n            os.getcwd(), options.output_folder))\n    print 'output directory: %s' % options.output_folder\n\n    if options.verbose:\n        logger.configure(logger.LOGGING_CONSOLE)\n    else:\n        logger.configure(logger.LOGGING_NONE)\n\n    if options.data_folder:\n        print ('Importing database from folder: {} '\n               'to: {}').format(options.data_folder, options.model_database)\n\n        database.configure(model_db, flag_make=True)\n        dbimport.import_model(options.data_folder, options.model_database)\n        database.db.close()\n        return\n\n    if options.scenario_filename:\n        database.configure(model_db)\n        s = scenario.loadFromCSV(options.scenario_filename)\n        simulate(s, options)\n        database.db.close()\n    else:\n        print '\\nERROR: Must provide as scenario file to run simulator...\\n'\n        parser.print_help()\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "921aaad481bc0b2b3df3c95467caf742a4720938", "size": 45351, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/core/damage.py", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/damage.py", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/damage.py", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9867298578, "max_line_length": 162, "alphanum_fraction": 0.5370995127, "include": true, "reason": "import numpy", "num_tokens": 9537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.15439596978333436}}
{"text": "# Encoding: utf-8\n\nimport sys\nimport os\nimport numpy as np\nfrom scipy import interpolate\nimport matplotlib.pyplot as plt\n\nfrom cage.landscape import LandscapeAnalyzer\nfrom cage.core import Facet\n\n\"\"\"\nPlot the landscape of connected edges. This is some damn illegible code, but\nimproving it would require thinking, and ain't nobody got time for that.\n\"\"\"\n\n# PARAMETERS TODO DIRTY AS FUCK -> Find a better way\nCATION='Na'\nSTART_FACET = 0 # 0 or 1 -> determines facet to start chain from\nANGLE_MESH = 0.003\nRADIUS_MESH = 0.01\nCONTOUR_LEVELS = np.mgrid[0.1:2:0.1]\nE_LIMITS = (0, 1.4)\n\n# Input\n\n# TODO Make a proper parser\nif len(sys.argv) == 3:\n    CATION = sys.argv[1]\nelse:\n    CATION = 'Li'\n\ndirname = sys.argv[-1]\ndir_list = [os.path.abspath(dir) for dir in os.listdir(dirname)\n            if os.path.isdir(dir)]\n\n# TODO Make this part ignore directories that do not have the right files\nedges = [[LandscapeAnalyzer.from_file(os.path.join(dir, 'landscape.json')),\n          [Facet.from_file(os.path.join(dir, 'init_facet.json')),\n          Facet.from_file(os.path.join(dir, 'final_facet.json'))]]\n         for dir in dir_list]\n\nfor edge in edges:\n    edge[0].analyze_cation_energies(facet=edge[1][0],cation=CATION)\n\n# TODO Make landscapes and paths connected via dictionary\n\n# Find all the facets in the paths\nfacets = []\nfor edge in edges:\n    for facet in edge[1]:\n        if facet not in facets:\n            facets.append(facet)\n\n# Find end_facets\nend_facets = []\nfor edge in edges:\n    for facet in edge[1]:\n        if facet not in end_facets:\n            end_facets.append(facet)\n        else:\n            end_facets.remove(facet)\n\n# Check if the chain is connected\nif len(end_facets) != 2:\n    raise ValueError('Edges are not connected in a chain. Aborting...')\n# TODO Handle case of circular connection of paths\n\n# Find the starting path\nfacet_chain = [end_facets[START_FACET], ]\npath_chain = []\nlandscape_chain = []\n\nwhile len(facet_chain) < len(facets):\n    last_facet = facet_chain[-1]\n    print('Last Facet:')\n    print(str(last_facet))\n    # Find the path that connects to the last facet and is not already in the\n    # path chain\n    for edge in edges:\n        if edge[1] not in path_chain and last_facet in edge[1]:\n            other_facet = edge[1].copy()\n            other_facet.remove(last_facet)\n            other_facet = other_facet[0]\n            print('Other Facet:')\n            print(str(other_facet))\n            facet_chain.append(other_facet)\n\n            if edge[1][0] != last_facet:\n                print('Flipped path (before):')\n                print(str(edge[1][0]))\n                print(str(edge[1][1]))\n                edge[1].reverse()\n                print('Flipped path (after):')\n                print(str(edge[1][0]))\n                print(str(edge[1][1]))\n                edge[0].flip_coordinates('Angle')\n\n            landscape_chain.append(edge[0])\n            path_chain.append(edge[1])\n\n    print('')\nprint('----------------')\nprint('Facet Chain:')\nfor facet in facet_chain:\n    print(str(facet))\nprint('----------------')\nprint('Path Chain:')\nfor edge in path_chain:\n    print('From')\n    print(str(edge[0]))\n    print('To')\n    print(str(edge[1]))\n\n# Interpolate the landscapes to a uniform mesh\n\n# Find the proper radii\nmin_max_radius = 1e6\nmax_min_radius = 0\nfor landscape in landscape_chain:\n    rmax = landscape.datapoints['Distance'].max()\n    if rmax < min_max_radius:\n        min_max_radius = rmax\n    rmin = landscape.datapoints['Distance'].min()\n    if rmin > max_min_radius:\n        max_min_radius = rmin\n\nprint('-----------')\nprint('Largest minimal radius = ' + str(max_min_radius))\nprint('Smallest maximal radius = ' + str(min_max_radius))\n\n\n# Adjust the angles to make one angle coordinate for all edges\nfacet_angles = [0, landscape_chain[0].datapoints['Angle'].max()]\n\nfor landscape in landscape_chain[1:]:\n    print('Maximum angle = ' + str(facet_angles[-1]))\n    landscape.datapoints['Angle'] += facet_angles[-1]\n    facet_angles.append(landscape.datapoints['Angle'].max())\n\nall_radii = []\nall_angles = []\nall_energy = []\n\n# Interpolate the landscapes\nfor landscape in landscape_chain:\n\n    data = landscape.datapoints\n\n    data['Distance'] = np.round(data['Distance'], 5)\n    data = np.sort(data, order=['Distance', 'Angle'])\n\n    # Find the number of radii and angles\n    r_init = data['Distance'][0]\n    nangles = 1\n    while abs(data['Distance'][nangles] - r_init) < 1e-5:\n        nangles += 1\n    nradii = int(len(data) / nangles)\n    print('')\n    print('-----------')\n    print('Number of Angles = ' + str(nangles))\n    print('Number of Radii = ' + str(nradii))\n\n    # Get the right format for the data\n    radii = data['Distance'].reshape(nradii, nangles)  # [::nradii]\n    angles = data['Angle'].reshape(nradii, nangles)  # [:nangles]\n    energy = data['Energy'].reshape(nradii, nangles)\n\n    print('Shape angles: ' + str(angles.shape))\n    print('Shape radii: ' + str(radii.shape))\n    print('Shape energy: ' + str(energy.shape))\n\n    new_angles, new_radii = np.mgrid[ angles.min():angles.max():ANGLE_MESH,\n                                    max_min_radius:min_max_radius:RADIUS_MESH ]\n    print('-------------')\n    print('Shape new_angles: ' + str(new_angles.shape))\n    print('Shape new_radii: ' + str(new_radii.shape))\n    tck = interpolate.bisplrep(angles, radii, energy, s=0.01)\n\n    new_energy = interpolate.bisplev(new_angles[:,0], new_radii[0,:], tck)\n\n    all_radii.append(new_radii)\n    all_angles.append(new_angles)\n    all_energy.append(new_energy)\n\ntotal_radii = np.concatenate(tuple(all_radii))\ntotal_angles = np.concatenate(tuple(all_angles))\ntotal_energy = np.concatenate(tuple(all_energy))\ntotal_energy -= total_energy.min()\n\nplt.figure()\nplt.pcolor(total_angles, total_radii, total_energy, vmin=E_LIMITS[0],\n           vmax=E_LIMITS[1], cmap='viridis')\ncbar = plt.colorbar()\ncbar.set_label('Energy (eV)', size='x-large')\nCS = plt.contour(total_angles, total_radii, total_energy, colors='black',\n            levels=CONTOUR_LEVELS, linewidths=0.6)\nfor angle in facet_angles:\n    plt.plot([angle, angle], [total_radii.min(), total_radii.max()], color='k',\n         linestyle='-', linewidth=1)\nxlabel = []\nfor i in range(len(facet_angles)):\n    xlabel.append('$\\Omega_' + str(i+1) + '$')\n#plt.xlabel('Angle', size='large')\nplt.ylabel('$r$ ($\\mathrm{\\AA}$)', size='x-large', fontname='Georgia')\nplt.xticks(facet_angles, xlabel, size='x-large')\nplt.clabel(CS, fontsize=10, inline_spacing=15, fmt='%1.1f', manual=True)\nplt.show()\n\n\n\n\n\n\n\n", "meta": {"hexsha": "7d04810df7709cd210358cc135b571a8614174f9", "size": 6522, "ext": "py", "lang": "Python", "max_stars_repo_path": "cage/scripts/edgelandscape.py", "max_stars_repo_name": "mbercx/cage", "max_stars_repo_head_hexsha": "90f34135c251f438c8709fdd9e814a47f7aa12e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cage/scripts/edgelandscape.py", "max_issues_repo_name": "mbercx/cage", "max_issues_repo_head_hexsha": "90f34135c251f438c8709fdd9e814a47f7aa12e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cage/scripts/edgelandscape.py", "max_forks_repo_name": "mbercx/cage", "max_forks_repo_head_hexsha": "90f34135c251f438c8709fdd9e814a47f7aa12e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1944444444, "max_line_length": 79, "alphanum_fraction": 0.6479607482, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.304041668660366, "lm_q1q2_score": 0.15439596658098065}}
{"text": "import ctypes\nimport ctypes.util\nfrom numpy.ctypeslib import ndpointer\nimport numpy\nfrom scipy import integrate\nfrom .. import potential\nfrom ..potential.planarPotential import planarPotentialFromFullPotential, \\\n    planarPotentialFromRZPotential\nfrom ..potential.planarPotential import _evaluateplanarRforces,\\\n    _evaluateplanarphiforces, _evaluateplanarPotentials\nfrom ..potential.WrapperPotential import parentWrapperPotential\nfrom ..util.multi import parallel_map\nfrom ..util.leung_dop853 import dop853\nfrom ..util import symplecticode\nfrom ..util import _load_extension_libs\n\n_lib, _ext_loaded= _load_extension_libs.load_libgalpy()\n\ndef _parse_pot(pot):\n    \"\"\"Parse the potential so it can be fed to C\"\"\"\n    from .integrateFullOrbit import _parse_scf_pot\n    #Figure out what's in pot\n    if not isinstance(pot,list):\n        pot= [pot]\n    #Initialize everything\n    pot_type= []\n    pot_args= []\n    npot= len(pot)\n    for p in pot:\n        # Prepare for wrappers\n        if ((isinstance(p,planarPotentialFromFullPotential) \\\n          or isinstance(p,planarPotentialFromRZPotential)) \\\n          and isinstance(p._Pot,parentWrapperPotential)) \\\n        or isinstance(p,parentWrapperPotential):\n            if not isinstance(p,parentWrapperPotential):\n                wrap_npot, wrap_pot_type, wrap_pot_args= \\\n                    _parse_pot(potential.toPlanarPotential(p._Pot._pot))\n            else:\n                wrap_npot, wrap_pot_type, wrap_pot_args= _parse_pot(p._pot)\n        if (isinstance(p,planarPotentialFromRZPotential) \n            or isinstance(p,planarPotentialFromFullPotential) ) \\\n                 and isinstance(p._Pot,potential.LogarithmicHaloPotential):\n            pot_type.append(0)\n            if p._Pot.isNonAxi:\n                pot_args.extend([p._Pot._amp,p._Pot._q,\n                                 p._Pot._core2,p._Pot._1m1overb2])\n            else:\n                pot_args.extend([p._Pot._amp,p._Pot._q,p._Pot._core2,2.]) # 1m1overb2 > 1: axi\n        elif isinstance(p,planarPotentialFromFullPotential) \\\n                 and isinstance(p._Pot,potential.DehnenBarPotential):\n            pot_type.append(1)\n            pot_args.extend([p._Pot._amp*p._Pot._af,p._Pot._tform,\n                             p._Pot._tsteady,p._Pot._rb,p._Pot._omegab,\n                             p._Pot._barphi])\n        elif isinstance(p,potential.TransientLogSpiralPotential):\n            pot_type.append(2)\n            pot_args.extend([p._amp,p._A,p._to,p._sigma2,p._alpha,p._m,\n                             p._omegas,p._gamma])\n        elif isinstance(p,potential.SteadyLogSpiralPotential):\n            pot_type.append(3)\n            if p._tform is None:\n                pot_args.extend([p._amp,float('nan'), float('nan'),\n                                 p._A,p._alpha,p._m,\n                                 p._omegas,p._gamma])\n            else:\n                pot_args.extend([p._amp,p._tform,p._tsteady,p._A,p._alpha,p._m,\n                                 p._omegas,p._gamma])\n        elif isinstance(p,potential.EllipticalDiskPotential):\n            pot_type.append(4)\n            if p._tform is None:\n                pot_args.extend([p._amp,float('nan'), float('nan'),\n                                 p._twophio,p._p,p._phib])\n            else:\n                pot_args.extend([p._amp,p._tform,p._tsteady,\n                                 p._twophio,p._p,p._phib])\n        elif isinstance(p,planarPotentialFromRZPotential) \\\n                 and isinstance(p._Pot,potential.MiyamotoNagaiPotential):\n            pot_type.append(5)\n            pot_args.extend([p._Pot._amp,p._Pot._a,p._Pot._b])\n        elif isinstance(p,potential.LopsidedDiskPotential):\n            pot_type.append(6)\n            pot_args.extend([p._amp,p._mphio,p._p,p._phib])\n        elif isinstance(p,planarPotentialFromRZPotential) \\\n                 and isinstance(p._Pot,potential.PowerSphericalPotential):\n            pot_type.append(7)\n            pot_args.extend([p._Pot._amp,p._Pot.alpha])\n        elif isinstance(p,planarPotentialFromRZPotential) \\\n                 and isinstance(p._Pot,potential.HernquistPotential):\n            pot_type.append(8)\n            pot_args.extend([p._Pot._amp,p._Pot.a])\n        elif isinstance(p,planarPotentialFromRZPotential) \\\n                 and isinstance(p._Pot,potential.NFWPotential):\n            pot_type.append(9)\n            pot_args.extend([p._Pot._amp,p._Pot.a])\n        elif isinstance(p,planarPotentialFromRZPotential) \\\n                 and isinstance(p._Pot,potential.JaffePotential):\n            pot_type.append(10)\n            pot_args.extend([p._Pot._amp,p._Pot.a])\n        elif isinstance(p,planarPotentialFromRZPotential) \\\n                and isinstance(p._Pot,potential.DoubleExponentialDiskPotential):\n            pot_type.append(11)\n            pot_args.extend([p._Pot._amp,\n                             -4.*numpy.pi*p._Pot._alpha*p._Pot._amp,\n                             p._Pot._alpha,p._Pot._beta,len(p._Pot._de_j1_xs)])\n            pot_args.extend(p._Pot._de_j0_xs)\n            pot_args.extend(p._Pot._de_j1_xs)\n            pot_args.extend(p._Pot._de_j0_weights)\n            pot_args.extend(p._Pot._de_j1_weights)\n        elif isinstance(p,planarPotentialFromRZPotential) \\\n                and isinstance(p._Pot,potential.FlattenedPowerPotential):\n            pot_type.append(12)\n            pot_args.extend([p._Pot._amp,p._Pot.alpha,p._Pot.core2])\n        elif isinstance(p,planarPotentialFromRZPotential) \\\n                 and isinstance(p._Pot,potential.IsochronePotential):\n            pot_type.append(14)\n            pot_args.extend([p._Pot._amp,p._Pot.b])\n        elif isinstance(p,planarPotentialFromRZPotential) \\\n                 and isinstance(p._Pot,potential.PowerSphericalPotentialwCutoff):\n            pot_type.append(15)\n            pot_args.extend([p._Pot._amp,p._Pot.alpha,p._Pot.rc])\n        elif isinstance(p,planarPotentialFromRZPotential) \\\n                 and isinstance(p._Pot,potential.MN3ExponentialDiskPotential):\n            # Three Miyamoto-Nagai disks\n            npot+= 2\n            pot_type.extend([5,5,5])\n            pot_args.extend([p._Pot._amp*p._Pot._mn3[0]._amp,\n                             p._Pot._mn3[0]._a,p._Pot._mn3[0]._b,\n                             p._Pot._amp*p._Pot._mn3[1]._amp,\n                             p._Pot._mn3[1]._a,p._Pot._mn3[1]._b,\n                             p._Pot._amp*p._Pot._mn3[2]._amp,\n                             p._Pot._mn3[2]._a,p._Pot._mn3[2]._b])\n        elif isinstance(p,planarPotentialFromRZPotential) \\\n                 and isinstance(p._Pot,potential.KuzminKutuzovStaeckelPotential):\n            pot_type.append(16)\n            pot_args.extend([p._Pot._amp,p._Pot._ac,p._Pot._Delta])\n        elif isinstance(p,planarPotentialFromRZPotential) \\\n                 and isinstance(p._Pot,potential.PlummerPotential):\n            pot_type.append(17)\n            pot_args.extend([p._Pot._amp,p._Pot._b])\n        elif isinstance(p,planarPotentialFromRZPotential) \\\n                 and isinstance(p._Pot,potential.PseudoIsothermalPotential):\n            pot_type.append(18)\n            pot_args.extend([p._Pot._amp,p._Pot._a])\n        elif isinstance(p,planarPotentialFromRZPotential) \\\n                 and isinstance(p._Pot,potential.KuzminDiskPotential):\n            pot_type.append(19)\n            pot_args.extend([p._Pot._amp,p._Pot._a])\n        elif isinstance(p,planarPotentialFromRZPotential) \\\n                 and isinstance(p._Pot,potential.BurkertPotential):\n            pot_type.append(20)\n            pot_args.extend([p._Pot._amp,p._Pot.a])\n        elif (isinstance(p,planarPotentialFromFullPotential) or isinstance(p,planarPotentialFromRZPotential)) \\\n                and isinstance(p._Pot,potential.EllipsoidalPotential.EllipsoidalPotential):\n            pot_args.append(p._Pot._amp)\n            pot_args.extend([0.,0.,0.,0.,0.,0.]) # for caching\n            if isinstance(p._Pot,potential.TriaxialHernquistPotential):\n                pot_type.append(21)\n                pot_args.extend([2,p._Pot.a,p._Pot.a4]) # for psi, mdens, mdens_deriv\n            if isinstance(p._Pot,potential.TriaxialNFWPotential):\n                pot_type.append(22)\n                pot_args.extend([2,p._Pot.a,p._Pot.a3]) # for psi, mdens, mdens_deriv\n            if isinstance(p._Pot,potential.TriaxialJaffePotential):\n                pot_type.append(23)\n                pot_args.extend([2,p._Pot.a,p._Pot.a2]) # for psi, mdens, mdens_deriv\n            elif isinstance(p._Pot,potential.PerfectEllipsoidPotential):\n                pot_type.append(30)\n                pot_args.extend([1,p._Pot.a2]) # for psi, mdens, mdens_deriv\n            elif isinstance(p._Pot,potential.TriaxialGaussianPotential):\n                pot_type.append(37)\n                pot_args.extend([1,-p._Pot._twosigma2]) # for psi, mdens, mdens_deriv\n            pot_args.extend([p._Pot._b2,p._Pot._c2,\n                             int(p._Pot._aligned)]) # Reg. Ellipsoidal\n            if not p._Pot._aligned:\n                pot_args.extend(list(p._Pot._rot.flatten()))\n            else:\n                pot_args.extend(list(numpy.eye(3).flatten())) # not actually used\n            pot_args.append(p._Pot._glorder)\n            pot_args.extend([p._Pot._glx[ii] for ii in range(p._Pot._glorder)])\n            # this adds some common factors to the integration weights\n            pot_args.extend([-4.*numpy.pi*p._Pot._glw[ii]*p._Pot._b*p._Pot._c\\\n                            /numpy.sqrt(( 1.+(p._Pot._b2-1.)*p._Pot._glx[ii]**2.)\n                                     *(1.+(p._Pot._c2-1.)*p._Pot._glx[ii]**2.))\n                             for ii in range(p._Pot._glorder)])\n        elif (isinstance(p,planarPotentialFromFullPotential) or isinstance(p,planarPotentialFromRZPotential)) \\\n                 and isinstance(p._Pot,potential.SCFPotential):\n            pt,pa= _parse_scf_pot(p._Pot)\n            pot_type.append(pt)\n            pot_args.extend(pa)\n        elif isinstance(p,planarPotentialFromFullPotential) \\\n                 and isinstance(p._Pot,potential.SoftenedNeedleBarPotential):\n            pot_type.append(25)\n            pot_args.extend([p._Pot._amp,p._Pot._a,p._Pot._b,p._Pot._c2,\n                             p._Pot._pa,p._Pot._omegab])\n            pot_args.extend([0.,0.,0.,0.,0.,0.,0.]) # for caching\n        elif (isinstance(p,planarPotentialFromFullPotential) or isinstance(p,planarPotentialFromRZPotential)) \\\n                and isinstance(p._Pot,potential.DiskSCFPotential):\n            # Need to pull this apart into: (a) SCF part, (b) constituent\n            # [Sigma_i,h_i] parts\n            # (a) SCF, multiply in any add'l amp\n            pt,pa= _parse_scf_pot(p._Pot._scf,extra_amp=p._Pot._amp)\n            pot_type.append(pt)\n            pot_args.extend(pa)\n            # (b) constituent [Sigma_i,h_i] parts\n            for Sigma,hz in zip(p._Pot._Sigma_dict,p._Pot._hz_dict):\n                npot+= 1\n                pot_type.append(26)\n                stype= Sigma.get('type','exp')\n                if stype == 'exp' and not 'Rhole' in Sigma:\n                    pot_args.extend([3,0,\n                                     4.*numpy.pi*Sigma.get('amp',1.)*p._Pot._amp,\n                                     Sigma.get('h',1./3.)])\n                elif stype == 'expwhole' \\\n                        or (stype == 'exp' and 'Rhole' in Sigma):\n                    pot_args.extend([4,1,\n                                     4.*numpy.pi*Sigma.get('amp',1.)*p._Pot._amp,\n                                     Sigma.get('h',1./3.),\n                                     Sigma.get('Rhole',0.5)])\n                hztype= hz.get('type','exp')\n                if hztype == 'exp':\n                    pot_args.extend([0,hz.get('h',0.0375)])\n                elif hztype == 'sech2':\n                    pot_args.extend([1,hz.get('h',0.0375)])\n        elif isinstance(p,planarPotentialFromFullPotential) \\\n                and isinstance(p._Pot, potential.SpiralArmsPotential):\n            pot_type.append(27)\n            pot_args.extend([len(p._Pot._Cs), p._Pot._amp, p._Pot._N, p._Pot._sin_alpha,\n                             p._Pot._tan_alpha, p._Pot._r_ref, p._Pot._phi_ref, p._Pot._Rs, p._Pot._H, p._Pot._omega])\n            pot_args.extend(p._Pot._Cs)\n        elif isinstance(p,potential.CosmphiDiskPotential):\n            pot_type.append(28)\n            pot_args.extend([p._amp,p._mphio,p._p,p._mphib,p._m,\n                             p._rb,p._rbp,p._rb2p,p._r1p])\n        elif isinstance(p,potential.HenonHeilesPotential):\n            pot_type.append(29)\n            pot_args.extend([p._amp])\n        # 30: PerfectEllipsoidPotential, done with other EllipsoidalPotentials above\n        # 31: KGPotential\n        # 32: IsothermalDiskPotential\n        elif isinstance(p, planarPotentialFromRZPotential) \\\n                and isinstance(p._Pot,potential.DehnenCoreSphericalPotential):\n            pot_type.append(33)\n            pot_args.extend([p._Pot._amp,p._Pot.a])\n        elif isinstance(p, planarPotentialFromRZPotential) \\\n                and isinstance(p._Pot,potential.DehnenSphericalPotential):\n            pot_type.append(34)\n            pot_args.extend([p._Pot._amp,p._Pot.a,p._Pot.alpha])\n        # 35: HomogeneousSpherePotential\n        elif isinstance(p,planarPotentialFromRZPotential) \\\n             and isinstance(p._Pot,potential.HomogeneousSpherePotential):\n            pot_type.append(35)\n            pot_args.extend([p._Pot._amp,p._Pot._R2,p._Pot._R3])\n        # 36: interpSphericalPotential\n        elif isinstance(p,planarPotentialFromRZPotential) \\\n             and isinstance(p._Pot,potential.interpSphericalPotential):\n            pot_type.append(36)\n            pot_args.append(len(p._Pot._rgrid))\n            pot_args.extend(p._Pot._rgrid)\n            pot_args.extend(p._Pot._rforce_grid)\n            pot_args.extend([p._Pot._amp,p._Pot._rmin,p._Pot._rmax,\n                             p._Pot._total_mass,p._Pot._Phi0,p._Pot._Phimax])\n        # 37: TriaxialGaussianPotential, done with other EllipsoidalPotentials above\n        ############################## WRAPPERS ###############################\n        elif ((isinstance(p,planarPotentialFromFullPotential) or isinstance(p,planarPotentialFromRZPotential)) \\\n              and isinstance(p._Pot,potential.DehnenSmoothWrapperPotential)) \\\n              or isinstance(p,potential.DehnenSmoothWrapperPotential):\n            if not isinstance(p,potential.DehnenSmoothWrapperPotential):\n                p= p._Pot\n            pot_type.append(-1)\n            # wrap_pot_type, args, and npot obtained before this horrible if\n            pot_args.append(wrap_npot)\n            pot_type.extend(wrap_pot_type)\n            pot_args.extend(wrap_pot_args)\n            pot_args.extend([p._amp,p._tform,p._tsteady,int(p._grow)])\n        elif ((isinstance(p,planarPotentialFromFullPotential) or isinstance(p,planarPotentialFromRZPotential)) \\\n          and isinstance(p._Pot,potential.SolidBodyRotationWrapperPotential)) \\\n          or isinstance(p,potential.SolidBodyRotationWrapperPotential):\n            if not isinstance(p,potential.SolidBodyRotationWrapperPotential):\n                p= p._Pot\n            pot_type.append(-2)\n            # wrap_pot_type, args, and npot obtained before this horrible if\n            pot_args.append(wrap_npot)\n            pot_type.extend(wrap_pot_type)\n            pot_args.extend(wrap_pot_args)\n            pot_args.extend([p._amp,p._omega,p._pa])\n        elif ((isinstance(p,planarPotentialFromFullPotential) or isinstance(p,planarPotentialFromRZPotential)) \\\n          and isinstance(p._Pot,potential.CorotatingRotationWrapperPotential)) \\\n          or isinstance(p,potential.CorotatingRotationWrapperPotential):\n            if not isinstance(p,potential.CorotatingRotationWrapperPotential):\n                p= p._Pot\n            pot_type.append(-4)\n            # wrap_pot_type, args, and npot obtained before this horrible if\n            pot_args.append(wrap_npot)\n            pot_type.extend(wrap_pot_type)\n            pot_args.extend(wrap_pot_args)\n            pot_args.extend([p._amp,p._vpo,p._beta,p._pa,p._to])\n        elif ((isinstance(p,planarPotentialFromFullPotential) or isinstance(p,planarPotentialFromRZPotential)) \\\n              and isinstance(p._Pot,potential.GaussianAmplitudeWrapperPotential)) \\\n              or isinstance(p,potential.GaussianAmplitudeWrapperPotential):\n            if not isinstance(p,potential.GaussianAmplitudeWrapperPotential):\n                p= p._Pot\n            pot_type.append(-5)\n            # wrap_pot_type, args, and npot obtained before this horrible if\n            pot_args.append(wrap_npot)\n            pot_type.extend(wrap_pot_type)\n            pot_args.extend(wrap_pot_args)\n            pot_args.extend([p._amp,p._to,p._sigma2])\n        elif ((isinstance(p,planarPotentialFromFullPotential) or isinstance(p,planarPotentialFromRZPotential)) \\\n              and isinstance(p._Pot,potential.MovingObjectPotential)) \\\n              or isinstance(p,potential.MovingObjectPotential):\n            if not isinstance(p,potential.MovingObjectPotential):\n                p= p._Pot\n            pot_type.append(-6)\n            wrap_npot, wrap_pot_type, wrap_pot_args= \\\n                    _parse_pot(potential.toPlanarPotential(p._pot))\n            pot_args.append(wrap_npot)\n            pot_type.extend(wrap_pot_type)\n            pot_args.extend(wrap_pot_args)\n            pot_args.extend([len(p._orb.t)])\n            pot_args.extend(p._orb.t)\n            pot_args.extend(p._orb.x(p._orb.t,use_physical=False))\n            pot_args.extend(p._orb.y(p._orb.t,use_physical=False))\n            pot_args.extend([p._amp])\n            pot_args.extend([p._orb.t[0],p._orb.t[-1]]) #t_0, t_f\n    pot_type= numpy.array(pot_type,dtype=numpy.int32,order='C')\n    pot_args= numpy.array(pot_args,dtype=numpy.float64,order='C')\n    return (npot,pot_type,pot_args)\n\ndef _parse_integrator(int_method):\n    \"\"\"parse the integrator method to pass to C\"\"\"\n    #Pick integrator\n    if int_method.lower() == 'rk4_c':\n        int_method_c= 1\n    elif int_method.lower() == 'rk6_c':\n        int_method_c= 2\n    elif int_method.lower() == 'symplec4_c':\n        int_method_c= 3\n    elif int_method.lower() == 'symplec6_c':\n        int_method_c= 4\n    elif int_method.lower() == 'dopr54_c':\n        int_method_c= 5\n    elif int_method.lower() == 'dop853_c':\n        int_method_c= 6\n    else:\n        int_method_c= 0\n    return int_method_c\n            \ndef _parse_tol(rtol,atol):\n    \"\"\"Parse the tolerance keywords\"\"\"\n    #Process atol and rtol\n    if rtol is None:\n        rtol= -12.*numpy.log(10.)\n    else: #pragma: no cover\n        rtol= numpy.log(rtol)\n    if atol is None:\n        atol= -12.*numpy.log(10.)\n    else: #pragma: no cover\n        atol= numpy.log(atol)\n    return (rtol,atol)\n\ndef integratePlanarOrbit_c(pot,yo,t,int_method,rtol=None,atol=None,\n                           dt=None):\n    \"\"\"\n    NAME:\n       integratePlanarOrbit_c\n    PURPOSE:\n       C integrate an ode for a planarOrbit\n    INPUT:\n       pot - Potential or list of such instances\n       yo - initial condition [q,p], can be [N,4] or [4]\n       t - set of times at which one wants the result\n       int_method= 'leapfrog_c', 'rk4_c', 'rk6_c', 'symplec4_c', ...\n       rtol, atol \n       dt= (None) force integrator to use this stepsize (default is to automatically determine one)\n   OUTPUT:\n       (y,err)\n       y : array, shape (len(y0),len(t),4)\n       Array containing the value of y for each desired time in t, \\\n       with the initial value y0 in the first row.\n       err: error message, if not zero: 1 means maximum step reduction happened for adaptive integrators\n    HISTORY:\n       2011-10-03 - Written - Bovy (IAS)\n       2018-12-20 - Adapted to allow multiple objects - Bovy (UofT)\n    \"\"\"\n    if len(yo.shape) == 1: single_obj= True\n    else: single_obj= False\n    yo= numpy.atleast_2d(yo)\n    nobj= len(yo)\n    rtol, atol= _parse_tol(rtol,atol)\n    npot, pot_type, pot_args= _parse_pot(pot)\n    int_method_c= _parse_integrator(int_method)\n    if dt is None: \n        dt= -9999.99\n\n    #Set up result array\n    result= numpy.empty((nobj,len(t),4))\n    err= numpy.zeros(nobj,dtype=numpy.int32)\n\n    #Set up the C code\n    ndarrayFlags= ('C_CONTIGUOUS','WRITEABLE')\n    integrationFunc= _lib.integratePlanarOrbit\n    integrationFunc.argtypes= [ctypes.c_int,\n                               ndpointer(dtype=numpy.float64,flags=ndarrayFlags),\n                               ctypes.c_int,                             \n                               ndpointer(dtype=numpy.float64,flags=ndarrayFlags),\n                               ctypes.c_int,\n                               ndpointer(dtype=numpy.int32,flags=ndarrayFlags),\n                               ndpointer(dtype=numpy.float64,flags=ndarrayFlags),\n                               ctypes.c_double,\n                               ctypes.c_double,\n                               ctypes.c_double,\n                               ndpointer(dtype=numpy.float64,flags=ndarrayFlags),\n                               ndpointer(dtype=numpy.int32,flags=ndarrayFlags),\n                               ctypes.c_int]\n\n    #Array requirements, first store old order\n    f_cont= [yo.flags['F_CONTIGUOUS'],\n             t.flags['F_CONTIGUOUS']]\n    yo= numpy.require(yo,dtype=numpy.float64,requirements=['C','W'])\n    t= numpy.require(t,dtype=numpy.float64,requirements=['C','W'])\n    result= numpy.require(result,dtype=numpy.float64,requirements=['C','W'])\n    err= numpy.require(err,dtype=numpy.int32,requirements=['C','W'])\n\n    #Run the C code\n    integrationFunc(ctypes.c_int(nobj),\n                    yo,\n                    ctypes.c_int(len(t)),\n                    t,\n                    ctypes.c_int(npot),\n                    pot_type,\n                    pot_args,\n                    ctypes.c_double(dt),                    \n                    ctypes.c_double(rtol),\n                    ctypes.c_double(atol),\n                    result,\n                    err,\n                    ctypes.c_int(int_method_c))\n\n    if numpy.any(err == -10): #pragma: no cover\n        raise KeyboardInterrupt(\"Orbit integration interrupted by CTRL-C (SIGINT)\")\n\n    #Reset input arrays\n    if f_cont[0]: yo= numpy.asfortranarray(yo)\n    if f_cont[1]: t= numpy.asfortranarray(t)\n\n    if single_obj: return (result[0],err[0])\n    else: return (result,err)\n\ndef integratePlanarOrbit_dxdv_c(pot,yo,dyo,t,int_method,rtol=None,atol=None,\n                                dt=None):\n    \"\"\"\n    NAME:\n       integratePlanarOrbit_dxdv_c\n    PURPOSE:\n       C integrate an ode for a planarOrbit+phase space volume dxdv\n    INPUT:\n       pot - Potential or list of such instances\n       yo - initial condition [q,p]\n       dyo - initial condition [dq,dp]\n       t - set of times at which one wants the result\n       int_method= 'leapfrog_c', 'rk4_c', 'rk6_c', 'symplec4_c'\n       rtol, atol\n       dt= (None) force integrator to use this stepsize (default is to automatically determine one))\n    OUTPUT:\n       (y,err)\n       y,dy : array, shape (len(y0),len(t),8)\n       Array containing the value of y for each desired time in t, \\\n       with the initial value y0 in the first row.\n       err: error message if not zero, 1: maximum step reduction happened for adaptive integrators\n    HISTORY:\n       2011-10-19 - Written - Bovy (IAS)\n    \"\"\"\n    rtol, atol= _parse_tol(rtol,atol)\n    npot, pot_type, pot_args= _parse_pot(pot)\n    int_method_c= _parse_integrator(int_method)\n    if dt is None: \n        dt= -9999.99\n    yo= numpy.concatenate((yo,dyo))\n\n    #Set up result array\n    result= numpy.empty((len(t),8))\n    err= ctypes.c_int(0)\n\n    #Set up the C code\n    ndarrayFlags= ('C_CONTIGUOUS','WRITEABLE')\n    integrationFunc= _lib.integratePlanarOrbit_dxdv\n    integrationFunc.argtypes= [ndpointer(dtype=numpy.float64,flags=ndarrayFlags),\n                               ctypes.c_int,                             \n                               ndpointer(dtype=numpy.float64,flags=ndarrayFlags),\n                               ctypes.c_int,\n                               ndpointer(dtype=numpy.int32,flags=ndarrayFlags),\n                               ndpointer(dtype=numpy.float64,flags=ndarrayFlags),\n                               ctypes.c_double,\n                               ctypes.c_double,\n                               ctypes.c_double,\n                               ndpointer(dtype=numpy.float64,flags=ndarrayFlags),\n                               ctypes.POINTER(ctypes.c_int),\n                               ctypes.c_int]\n\n    #Array requirements, first store old order\n    f_cont= [yo.flags['F_CONTIGUOUS'],\n             t.flags['F_CONTIGUOUS']]\n    yo= numpy.require(yo,dtype=numpy.float64,requirements=['C','W'])\n    t= numpy.require(t,dtype=numpy.float64,requirements=['C','W'])\n    result= numpy.require(result,dtype=numpy.float64,requirements=['C','W'])\n\n    #Run the C code\n    integrationFunc(yo,\n                    ctypes.c_int(len(t)),\n                    t,\n                    ctypes.c_int(npot),\n                    pot_type,\n                    pot_args,\n                    ctypes.c_double(dt),                    \n                    ctypes.c_double(rtol),ctypes.c_double(atol),\n                    result,\n                    ctypes.byref(err),\n                    ctypes.c_int(int_method_c))\n\n    if err.value == -10: #pragma: no cover\n        raise KeyboardInterrupt(\"Orbit integration interrupted by CTRL-C (SIGINT)\")\n\n    #Reset input arrays\n    if f_cont[0]: yo= numpy.asfortranarray(yo)\n    if f_cont[1]: t= numpy.asfortranarray(t)\n\n    return (result,err.value)\n\ndef integratePlanarOrbit(pot,yo,t,int_method,rtol=None,atol=None,numcores=1,\n                         dt=None):\n    \"\"\"\n    NAME:\n       integratePlanarOrbit\n    PURPOSE:\n       Integrate an ode for a planarOrbit\n    INPUT:\n       pot - Potential or list of such instances\n       yo - initial condition [q,p], shape [N,3] or [N,4]\n       t - set of times at which one wants the result\n       int_method= 'leapfrog', 'odeint', or 'dop853'\n       rtol, atol= tolerances (not always used...)\n       numcores= (1) number of cores to use for multi-processing\n       dt= (None) force integrator to use this stepsize (default is to automatically determine one; only for C-based integrators!)\n    OUTPUT:\n       (y,err)\n       y : array, shape (N,len(t),3/4)\n       Array containing the value of y for each desired time in t, \\\n       with the initial value y0 in the first row.\n       err: error message, always zero for now\n    HISTORY:\n       2010-07-20 - Written - Bovy (NYU)\n       2019-04-09 - Adapted to allow multiple objects and parallel mapping - Bovy (UofT)\n    \"\"\"\n    nophi= False\n    if not int_method.lower() == 'dop853' and not int_method == 'odeint':\n        if len(yo[0]) == 3:\n            nophi= True\n            #We hack this by putting in a dummy phi=0\n            yo= numpy.pad(yo,((0,0),(0,1)),'constant',constant_values=0)\n    if int_method.lower() == 'leapfrog':\n        if rtol is None: rtol= 1e-8\n        def integrate_for_map(vxvv):\n            #go to the rectangular frame\n            this_vxvv= numpy.array([vxvv[0]*numpy.cos(vxvv[3]),\n                                 vxvv[0]*numpy.sin(vxvv[3]),\n                                 vxvv[1]*numpy.cos(vxvv[3])\n                                     -vxvv[2]*numpy.sin(vxvv[3]),\n                                 vxvv[2]*numpy.cos(vxvv[3])\n                                     +vxvv[1]*numpy.sin(vxvv[3])])\n            #integrate\n            tmp_out= symplecticode.leapfrog(_planarRectForce,this_vxvv,\n                                            t,args=(pot,),rtol=rtol)\n            #go back to the cylindrical frame\n            R= numpy.sqrt(tmp_out[:,0]**2.+tmp_out[:,1]**2.)\n            phi= numpy.arccos(tmp_out[:,0]/R)\n            phi[(tmp_out[:,1] < 0.)]= 2.*numpy.pi-phi[(tmp_out[:,1] < 0.)]\n            vR= tmp_out[:,2]*numpy.cos(phi)+tmp_out[:,3]*numpy.sin(phi)\n            vT= tmp_out[:,3]*numpy.cos(phi)-tmp_out[:,2]*numpy.sin(phi)\n            out= numpy.zeros((len(t),4))\n            out[:,0]= R\n            out[:,1]= vR\n            out[:,2]= vT\n            out[:,3]= phi\n            return out\n    elif int_method.lower() == 'dop853' or int_method.lower() == 'odeint':\n        if rtol is None: rtol= 1e-8\n        if int_method.lower() == 'dop853':\n            integrator= dop853\n            extra_kwargs= {}\n        else:\n            integrator= integrate.odeint\n            extra_kwargs= {'rtol':rtol}\n        if len(yo[0]) == 3:\n            def integrate_for_map(vxvv):\n                l= vxvv[0]*vxvv[2]\n                l2= l**2.\n                init= [vxvv[0],vxvv[1]]\n                intOut= integrator(_planarREOM,init,t=t,args=(pot,l2),\n                                   **extra_kwargs)\n                out= numpy.zeros((len(t),3))\n                out[:,0]= intOut[:,0]\n                out[:,1]= intOut[:,1]\n                out[:,2]= l/out[:,0]\n                #post-process to remove negative radii\n                neg_radii= (out[:,0] < 0.)\n                out[neg_radii,0]= -out[neg_radii,0]\n                return out\n        else:\n            def integrate_for_map(vxvv):\n                vphi= vxvv[2]/vxvv[0]\n                init= [vxvv[0],vxvv[1],vxvv[3],vphi]\n                intOut= integrator(_planarEOM,init,t=t,args=(pot,),\n                                   **extra_kwargs)\n                out= numpy.zeros((len(t),4))\n                out[:,0]= intOut[:,0]\n                out[:,1]= intOut[:,1]\n                out[:,3]= intOut[:,2]\n                out[:,2]= out[:,0]*intOut[:,3]\n                #post-process to remove negative radii\n                neg_radii= (out[:,0] < 0.)\n                out[neg_radii,0]= -out[neg_radii,0]\n                out[neg_radii,3]+= numpy.pi\n                return out\n    else: # Assume we are forcing parallel_mapping of a C integrator...\n        def integrate_for_map(vxvv):\n            return integratePlanarOrbit_c(pot,numpy.copy(vxvv),\n                                          t,int_method,dt=dt)[0]\n    if len(yo) == 1: # Can't map a single value...\n        out= numpy.atleast_3d(integrate_for_map(yo[0]).T).T\n    else:\n        out= numpy.array((parallel_map(integrate_for_map,yo,numcores=numcores)))\n    if nophi:\n        out= out[:,:,:3]\n    return out, numpy.zeros(len(yo))\n\ndef integratePlanarOrbit_dxdv(pot,yo,dyo,t,int_method,\n                              rectIn,rectOut,\n                              rtol=None,atol=None,\n                              dt=None,numcores=1):\n    \"\"\"\n    NAME:\n       integratePlanarOrbit_dxdv\n    PURPOSE:\n       Integrate an ode for a planarOrbit+phase space volume dxdv\n    INPUT:\n       pot - Potential or list of such instances\n       yo - initial condition [q,p], shape [N,4]\n       dyo - initial condition [dq,dp], shape [N,4]\n       t - set of times at which one wants the result\n       int_method= 'odeint', 'dop853', 'dopr54_c', 'rk4_c', 'rk6_c'\n       rectIn= (False) if True, input dyo is in rectangular coordinates\n       rectOut= (False) if True, output dyo is in rectangular coordinates\n       rtol, atol= tolerances (not always used...)\n       numcores= (1) number of cores to use for multi-processing\n       dt= (None) force integrator to use this stepsize (default is to automatically determine one; only for C-based integrators)\n    OUTPUT:\n       (y,err)\n       y : array, shape (N,len(t),8)\n       Array containing the value of y for each desired time in t, \\\n       with the initial value y0 in the first row.\n       err: error message, always zero for now\n    HISTORY:\n       2011-10-17 - Written - Bovy (IAS)\n       2019-05-21 - Adapted to allow multiple objects and parallel mapping - Bovy (UofT)\n    \"\"\"\n    #go to the rectangular frame\n    this_yo= numpy.array([yo[:,0]*numpy.cos(yo[:,3]),\n                         yo[:,0]*numpy.sin(yo[:,3]),\n                         yo[:,1]*numpy.cos(yo[:,3])\n                           -yo[:,2]*numpy.sin(yo[:,3]),\n                         yo[:,2]*numpy.cos(yo[:,3])\n                           +yo[:,1]*numpy.sin(yo[:,3])]).T\n    if not rectIn:\n        this_dyo= numpy.array([numpy.cos(yo[:,3])*dyo[:,0]\n                              -yo[:,0]*numpy.sin(yo[:,3])*dyo[:,3],\n                            numpy.sin(yo[:,3])*dyo[:,0]\n                              +yo[:,0]*numpy.cos(yo[:,3])*dyo[:,3],\n                            -(yo[:,1]*numpy.sin(yo[:,3])\n                              +yo[:,2]*numpy.cos(yo[:,3]))*dyo[:,3]\n                              +numpy.cos(yo[:,3])*dyo[:,1]\n                              -numpy.sin(yo[:,3])*dyo[:,2],\n                            (yo[:,1]*numpy.cos(yo[:,3])\n                              -yo[:,2]*numpy.sin(yo[:,3]))*dyo[:,3]\n                              +numpy.sin(yo[:,3])*dyo[:,1]\n                              +numpy.cos(yo[:,3])*dyo[:,2]]).T\n    else:\n        this_dyo= dyo\n    this_yo= numpy.hstack((this_yo,this_dyo))\n    if int_method.lower() == 'dop853' or int_method.lower() == 'odeint':\n        if rtol is None: rtol= 1e-8\n        if int_method.lower() == 'dop853':\n            integrator= dop853\n            extra_kwargs= {}\n        else:\n            integrator= integrate.odeint\n            extra_kwargs= {'rtol':rtol}\n        def integrate_for_map(vxvv):\n            return integrator(_planarEOM_dxdv,vxvv,t=t,args=(pot,),\n                              **extra_kwargs)\n    else: # Assume we are forcing parallel_mapping of a C integrator...\n        def integrate_for_map(vxvv):\n            return integratePlanarOrbit_dxdv_c(pot,numpy.copy(vxvv[:4]),\n                                               numpy.copy(vxvv[4:]),\n                                               t,int_method,dt=dt,\n                                               rtol=rtol,atol=atol)[0]\n    if len(this_yo) == 1: # Can't map a single value...\n        out= numpy.atleast_3d(integrate_for_map(this_yo[0]).T).T\n    else:\n        out= numpy.array((parallel_map(integrate_for_map,this_yo,\n                                    numcores=numcores)))\n    #go back to the cylindrical frame\n    R= numpy.sqrt(out[...,0]**2.+out[...,1]**2.)\n    phi= numpy.arccos(out[...,0]/R)\n    phi[(out[...,1] < 0.)]= 2.*numpy.pi-phi[(out[...,1] < 0.)]\n    vR= out[...,2]*numpy.cos(phi)+out[...,3]*numpy.sin(phi)\n    vT= out[...,3]*numpy.cos(phi)-out[...,2]*numpy.sin(phi)\n    cp= numpy.cos(phi)\n    sp= numpy.sin(phi)\n    out[...,0]= R\n    out[...,1]= vR\n    out[...,2]= vT\n    out[...,3]= phi\n    if rectOut:\n        out[...,4:]= out[...,4:]\n    else:\n        dR= cp*out[...,4]+sp*out[...,5]\n        dphi= (cp*out[...,5]-sp*out[...,4])/R\n        dvR= cp*out[...,6]+sp*out[...,7]+vT*dphi\n        dvT= cp*out[...,7]-sp*out[...,6]-vR*dphi\n        out[...,4]= dR\n        out[...,7]= dphi\n        out[...,5]= dvR\n        out[...,6]= dvT\n    return out, numpy.zeros(len(yo))\n\ndef _planarREOM(y,t,pot,l2):\n    \"\"\"\n    NAME:\n       _planarREOM\n    PURPOSE:\n       implements the EOM, i.e., the right-hand side of the differential \n       equation, for integrating a planar Orbit assuming angular momentum \n       conservation\n    INPUT:\n       y - current phase-space position\n       t - current time\n       pot - (list of) Potential instance(s)\n       l2 - angular momentum squared\n    OUTPUT:\n       dy/dt\n    HISTORY:\n       2010-07-20 - Written - Bovy (NYU)\n    \"\"\"\n    return [y[1],\n            l2/y[0]**3.+_evaluateplanarRforces(pot,y[0],t=t)]\n\ndef _planarEOM(y,t,pot):\n    \"\"\"\n    NAME:\n       _planarEOM\n    PURPOSE:\n       implements the EOM, i.e., the right-hand side of the differential \n       equation, for integrating a general planar Orbit\n    INPUT:\n       y - current phase-space position\n       t - current time\n       pot - (list of) Potential instance(s)\n    OUTPUT:\n       dy/dt\n    HISTORY:\n       2010-07-20 - Written - Bovy (NYU)\n    \"\"\"\n    l2= (y[0]**2.*y[3])**2.\n    return [y[1],\n            l2/y[0]**3.+_evaluateplanarRforces(pot,y[0],phi=y[2],t=t),\n            y[3],\n            1./y[0]**2.*(_evaluateplanarphiforces(pot,y[0],phi=y[2],t=t)-\n                         2.*y[0]*y[1]*y[3])]\n\ndef _planarEOM_dxdv(x,t,pot):\n    \"\"\"\n    NAME:\n       _planarEOM_dxdv\n    PURPOSE:\n       implements the EOM, i.e., the right-hand side of the differential \n       equation, for integrating phase space differences, rectangular\n    INPUT:\n       x - current phase-space position\n       t - current time\n       pot - (list of) Potential instance(s)\n    OUTPUT:\n       dy/dt\n    HISTORY:\n       2011-10-18 - Written - Bovy (IAS)\n    \"\"\"\n    #x is rectangular so calculate R and phi\n    R= numpy.sqrt(x[0]**2.+x[1]**2.)\n    phi= numpy.arccos(x[0]/R)\n    sinphi= x[1]/R\n    cosphi= x[0]/R\n    if x[1] < 0.: phi= 2.*numpy.pi-phi\n    #calculate forces\n    Rforce= _evaluateplanarRforces(pot,R,phi=phi,t=t)\n    phiforce= _evaluateplanarphiforces(pot,R,phi=phi,t=t)\n    R2deriv= _evaluateplanarPotentials(pot,R,phi=phi,t=t,dR=2)\n    phi2deriv= _evaluateplanarPotentials(pot,R,phi=phi,t=t,dphi=2)\n    Rphideriv= _evaluateplanarPotentials(pot,R,phi=phi,t=t,dR=1,dphi=1)\n    #Calculate derivatives and derivatives+time derivatives\n    dFxdx= -cosphi**2.*R2deriv\\\n           +2.*cosphi*sinphi/R**2.*phiforce\\\n           +sinphi**2./R*Rforce\\\n           +2.*sinphi*cosphi/R*Rphideriv\\\n           -sinphi**2./R**2.*phi2deriv\n    dFxdy= -sinphi*cosphi*R2deriv\\\n           +(sinphi**2.-cosphi**2.)/R**2.*phiforce\\\n           -cosphi*sinphi/R*Rforce\\\n           -(cosphi**2.-sinphi**2.)/R*Rphideriv\\\n           +cosphi*sinphi/R**2.*phi2deriv\n    dFydx= -cosphi*sinphi*R2deriv\\\n           +(sinphi**2.-cosphi**2.)/R**2.*phiforce\\\n           +(sinphi**2.-cosphi**2.)/R*Rphideriv\\\n           -sinphi*cosphi/R*Rforce\\\n           +sinphi*cosphi/R**2.*phi2deriv\n    dFydy= -sinphi**2.*R2deriv\\\n           -2.*sinphi*cosphi/R**2.*phiforce\\\n           -2.*sinphi*cosphi/R*Rphideriv\\\n           +cosphi**2./R*Rforce\\\n           -cosphi**2./R**2.*phi2deriv\n    return numpy.array([x[2],x[3],\n                     cosphi*Rforce-1./R*sinphi*phiforce,\n                     sinphi*Rforce+1./R*cosphi*phiforce,\n                     x[6],x[7],\n                     dFxdx*x[4]+dFxdy*x[5],\n                     dFydx*x[4]+dFydy*x[5]])\n\ndef _planarRectForce(x,pot,t=0.):\n    \"\"\"\n    NAME:\n       _planarRectForce\n    PURPOSE:\n       returns the planar force in the rectangular frame\n    INPUT:\n       x - current position\n       t - current time\n       pot - (list of) Potential instance(s)\n    OUTPUT:\n       force\n    HISTORY:\n       2011-02-02 - Written - Bovy (NYU)\n    \"\"\"\n    #x is rectangular so calculate R and phi\n    R= numpy.sqrt(x[0]**2.+x[1]**2.)\n    phi= numpy.arccos(x[0]/R)\n    sinphi= x[1]/R\n    cosphi= x[0]/R\n    if x[1] < 0.: phi= 2.*numpy.pi-phi\n    #calculate forces\n    Rforce= _evaluateplanarRforces(pot,R,phi=phi,t=t)\n    phiforce= _evaluateplanarphiforces(pot,R,phi=phi,t=t)\n    return numpy.array([cosphi*Rforce-1./R*sinphi*phiforce,\n                     sinphi*Rforce+1./R*cosphi*phiforce])\n\n", "meta": {"hexsha": "007c276a8521b12c3ce6ea907a54495f033368ce", "size": 39012, "ext": "py", "lang": "Python", "max_stars_repo_path": "galpy/orbit/integratePlanarOrbit.py", "max_stars_repo_name": "davidhendel/galpy", "max_stars_repo_head_hexsha": "9654e2e181d26abaac4a4fba49375887fb290d36", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "galpy/orbit/integratePlanarOrbit.py", "max_issues_repo_name": "davidhendel/galpy", "max_issues_repo_head_hexsha": "9654e2e181d26abaac4a4fba49375887fb290d36", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "galpy/orbit/integratePlanarOrbit.py", "max_forks_repo_name": "davidhendel/galpy", "max_forks_repo_head_hexsha": "9654e2e181d26abaac4a4fba49375887fb290d36", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.2575406032, "max_line_length": 130, "alphanum_fraction": 0.5652107044, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 10232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.2689414330889797, "lm_q1q2_score": 0.15428589303248158}}
{"text": "\"\"\"This module contains iceberg drift models.\n\"\"\"\n\nimport cmath\nimport numpy as np\nfrom icedef.constants import *\n\n\ndef newtonian_drift_wrapper(t, lon, lat, vx, vy, **kwargs):\n    \"\"\"This function performs interpolations for current and wind velocities and then runs the drift model.\n\n    Args:\n        t (numpy.datetime64): time.\n        lon (float): longitude.\n        lat (float): latitude.\n        vx (float): x-component of iceberg velocity in m/s.\n        vy (float): y-component of iceberg velocity in m/s.\n        **kwargs: coming soon - see source code for now.\n\n    Returns:\n        vx (float): new x-component of iceberg velocity in m/s.\n        vy (float): new y-component of iceberg velocity in m/s.\n        ax (float): x-component of iceberg acceleration in m/s.\n        ay (float): y-component of iceberg acceleration in m/s.\n    \"\"\"\n\n    dt = kwargs.pop('time_step', np.timedelta64(300, 's'))\n\n    fast_interpolation = kwargs.pop('fast_interpolation', True)\n\n    if fast_interpolation:\n\n        current_interpolator = kwargs.pop('current_interpolator')\n        Vcx, Vcy = current_interpolator((t, lat, lon))\n        wind_interpolator = kwargs.pop('wind_interpolator')\n        Vwx, Vwy = wind_interpolator((t, lat, lon))\n\n        Vcx_left, Vcy_left = current_interpolator((t - dt, lat, lon))\n        Vcx_right, Vcy_right = current_interpolator((t + dt, lat, lon))\n\n    else:\n\n        Vcxs = kwargs.pop('eastward_current')\n        Vcys = kwargs.pop('northward_current')\n        Vwxs = kwargs.pop('eastward_wind')\n        Vwys = kwargs.pop('northward_wind')\n\n        Vcx = Vcxs.interp(time=t, latitude=lat, longitude=lon, assume_sorted=True).values\n        Vcy = Vcys.interp(time=t, latitude=lat, longitude=lon, assume_sorted=True).values\n        Vwx = Vwxs.interp(time=t, latitude=lat, longitude=lon, assume_sorted=True).values\n        Vwy = Vwys.interp(time=t, latitude=lat, longitude=lon, assume_sorted=True).values\n\n        Vcx_left = Vcxs.interp(time=t - dt, latitude=lat, longitude=lon, assume_sorted=True).values\n        Vcx_right = Vcxs.interp(time=t + dt, latitude=lat, longitude=lon, assume_sorted=True).values\n        Vcy_left = Vcys.interp(time=t - dt, latitude=lat, longitude=lon, assume_sorted=True).values\n        Vcy_right = Vcys.interp(time=t + dt, latitude=lat, longitude=lon, assume_sorted=True).values\n\n    Amwx = (Vcx_right - Vcx_left) / (dt.item().total_seconds() * 2)\n    Amwy = (Vcy_right - Vcy_left) / (dt.item().total_seconds() * 2)\n\n    kwargs['Vcx'] = Vcx\n    kwargs['Vcy'] = Vcy\n    kwargs['Vwx'] = Vwx\n    kwargs['Vwy'] = Vwy\n    kwargs['Amwx'] = Amwx\n    kwargs['Amwy'] = Amwy\n\n    kwargs['phi'] = lat\n\n    ax, ay = newtonian_drift(vx, vy, **kwargs)\n\n    return vx, vy, ax, ay\n\n\ndef newtonian_drift(Vx, Vy, **kwargs):\n    \"\"\"This function computes iceberg acceleration using a general Newtonian drift model.\n\n    Args:\n        Vx (float): x-component of iceberg velocity in m/s.\n        Vy (float): y-component of iceberg velocity in m/s.\n        **kwargs: coming soon - see source code for now.\n\n    Returns:\n        ax (float): x-component of iceberg acceleration in m/s.\n        ay (float): y-component of iceberg acceleration in m/s.\n    \"\"\"\n\n    # Constants\n    Omega = EARTH_ROTATION_RATE\n    rhoa = AIR_DENSITY\n    rhow = SEAWATER_DENSITY\n\n    Vwx = kwargs.pop('Vwx')\n    Vwy = kwargs.pop('Vwy')\n    Vcx = kwargs.pop('Vcx')\n    Vcy = kwargs.pop('Vcy')\n\n    Amwx = kwargs.pop('Amwx', 0)\n    Amwy = kwargs.pop('Amwy', 0)\n\n    Ca = kwargs.pop('form_drag_coefficient_in_air', 1.5)\n    Cw = kwargs.pop('form_drag_coefficient_in_water', 1.5)\n    Cda = kwargs.pop('skin_drag_coefficient_in_air', 2.5e-4)\n    Cdw = kwargs.pop('skin_drag_coefficient_in_water', 5e-4)\n    As = kwargs.pop('sail_area', 9600.0)\n    Ak = kwargs.pop('keel_area', 48000.0)\n    At = kwargs.pop('top_area', 25600.0)\n    Ab = kwargs.pop('bottom_area', 25600.0)\n    M = kwargs.pop('mass', 5468160000.0)\n    phi = kwargs.pop('latitude', 50)\n\n    # Wind force\n    Fax = (0.5 * rhoa * Ca * As + rhoa * Cda * At) * np.sqrt((Vwx - Vx)**2 + (Vwy - Vy)**2) * (Vwx - Vx)\n    Fay = (0.5 * rhoa * Ca * As + rhoa * Cda * At) * np.sqrt((Vwx - Vx)**2 + (Vwy - Vy)**2) * (Vwy - Vy)\n\n    # Current force\n    ekman = kwargs.pop('ekman', False)\n\n    if ekman:\n\n        Fwx_list = []\n        Fwy_list = []\n        Vcx_list = []\n        Vcy_list = []\n\n        depth_vec = kwargs.pop('depth_vec', np.arange(0, -110, -10))\n\n        u_vec, v_vec = compute_ekman_spiral((Vwx, Vwy), (Vcx, Vcy), depth_vec)\n\n        for i in range(len(u_vec)):\n\n            Vcx, Vcy = u_vec[i], v_vec[i]\n\n            Vcx_list.append(Vcx)\n            Vcy_list.append(Vcy)\n\n            Fwx = (0.5 * rhow * Cw * Ak + rhow * Cdw * Ab) * np.sqrt((Vcx - Vx)**2 + (Vcy - Vy)**2) * (Vcx - Vx)\n            Fwy = (0.5 * rhow * Cw * Ak + rhow * Cdw * Ab) * np.sqrt((Vcx - Vx)**2 + (Vcy - Vy)**2) * (Vcy - Vy)\n\n            Fwx_list.append(Fwx)\n            Fwy_list.append(Fwy)\n\n        Vcx = np.mean(np.array(Vcx_list))\n        Vcy = np.mean(np.array(Vcy_list))\n\n        Fwx = np.mean(np.array(Fwx_list))\n        Fwy = np.mean(np.array(Fwy_list))\n\n    else:\n        Fwx = (0.5 * rhow * Cw * Ak + rhow * Cdw * Ab) * np.sqrt((Vcx - Vx)**2 + (Vcy - Vy)**2) * (Vcx - Vx)\n        Fwy = (0.5 * rhow * Cw * Ak + rhow * Cdw * Ab) * np.sqrt((Vcx - Vx)**2 + (Vcy - Vy)**2) * (Vcy - Vy)\n\n    # Coriolis Parameter\n    f = 2 * Omega * np.sin(np.deg2rad(phi))\n\n    # Coriolis force\n    Fcx = f * M * Vy\n    Fcy = -f * M * Vx\n\n    # Water Pressure Gradient Force\n    Vmwx = Vcx\n    Vmwy = Vcy\n    Amwx = Amwx\n    Amwy = Amwy\n    Fwpx = M * (Amwx - f * Vmwy)\n    Fwpy = M * (Amwy + f * Vmwx)\n\n    # Iceberg acceleration\n    ax = (Fax + Fwx + Fcx + Fwpx) / (M + 0.5 * M)\n    ay = (Fay + Fwy + Fcy + Fwpy) / (M + 0.5 * M)\n\n    log = kwargs.pop('log', None)\n\n    if log is not None:\n        log.info('{:.2f},{:.2f},{:.2f},{:.2f},{:.2f},{:.2f},{:.2f},{:.2f}'.format(\n            Fax, Fay, Fwx, Fwy, Fcx, Fcy, Fwpx, Fwpy))\n\n    return ax, ay\n\n\ndef compute_ekman_velocity(wind, depth, latitude=50):\n    \"\"\"This function computes Ekman velocity at some depth.\n\n    Args:\n        wind (tuple of float): components (x, y) of wind velocity in m/s.\n        depth (float): depth below the sea surface (down is negative) in m.\n        latitude: latitude.\n\n    Returns:\n        u_ekman (float): x-component of Ekman velocity at specified depth.\n        v_ekman (float): y-component of Ekman velocity at specified depth.\n    \"\"\"\n\n    u_wind, v_wind = wind\n    z = depth\n    phi = latitude\n\n    rho_air = 1.225  # density of air (kg/m^3)\n    rho_water = 1028  # density of seawater (kg/m^3)\n    Cd = 1.3e-3  # ranges from (1.1 - 1.5) x 10^-3\n    Omega = 7.2910e-5  # rotation rate of Earth (s^-1)\n    Az = 5e-2  # m^2 s^−1;\n\n    f = lambda phi: 2 * Omega * np.sin(phi)  # Coriolis parameter\n\n    tau_x = lambda U, V: rho_air * Cd * U * np.sqrt(U ** 2 + V ** 2)  # wind stress x-component\n    tau_y = lambda U, V: rho_air * Cd * V * np.sqrt(U ** 2 + V ** 2)  # wind stress y-component\n\n    V0x = tau_x(u_wind, v_wind) / np.sqrt(rho_water ** 2 * np.abs(f(phi)) * Az)\n    V0y = tau_y(u_wind, v_wind) / np.sqrt(rho_water ** 2 * np.abs(f(phi)) * Az)\n    V0 = np.sqrt(V0x ** 2 + V0y ** 2)\n    theta = np.pi / 2 - np.arctan2(V0y, V0x)\n\n    a = np.sqrt(abs(f(phi)) / (2 * Az))\n\n    # note: clockwise rotation\n    u_ekman = V0 * np.exp(a * z) * np.cos(np.pi / 4 + a * z) * (np.cos(theta) + np.sin(theta))\n    v_ekman = V0 * np.exp(a * z) * np.sin(np.pi / 4 + a * z) * (np.cos(theta) - np.sin(theta))\n\n    return u_ekman, v_ekman\n\n\ndef compute_ekman_spiral(wind, surface_current, depth_vec, latitude=50):\n    \"\"\"This function computes an Ekman spiral.\n\n    Args:\n        wind (tuple of float): components (x, y) of wind velocity in m/s.\n        surface_current (tuple of float): components (x, y) of current velocity at the surface in m/s.\n        depth_vec (list of float): depths in m to compute Ekman velocity at.\n        latitude: latitude.\n\n    Returns:\n        u_current_vec (list of float): x-components of Ekman velocity at all depths specified.\n        v_current_vec (list of float): y-components of Ekman velocity at all depths specified.\n    \"\"\"\n\n    u_ekman_vec = np.zeros(len(depth_vec))\n    v_ekman_vec = np.zeros(len(depth_vec))\n\n    u_ekman_surface, v_ekman_surface = compute_ekman_velocity(wind, 0, latitude)\n\n    u_surface_current, v_surface_current = surface_current\n\n    u_barotropic = u_surface_current - u_ekman_surface\n    v_barotropic = v_surface_current - v_ekman_surface\n\n    for i, depth in enumerate(depth_vec):\n        u_ekman_vec[i], v_ekman_vec[i] = compute_ekman_velocity(wind, depth, latitude)\n\n    u_current_vec = u_barotropic + u_ekman_vec\n    v_current_vec = v_barotropic + v_ekman_vec\n\n    return u_current_vec, v_current_vec\n\n\ndef analytical_drift_wrapper(t, lon, lat, **kwargs):\n    \"\"\"This function performs interpolations for current and wind velocities and then runs the drift model.\n\n    Args:\n        t (numpy.datetime64): time.\n        lon (float): longitude.\n        lat (float): latitude.\n        vx (float): x-component of iceberg velocity in m/s.\n        vy (float): y-component of iceberg velocity in m/s.\n        **kwargs: coming soon - see source code for now.\n\n    Returns:\n        vx (float): new x-component of iceberg velocity in m/s.\n        vy (float): new y-component of iceberg velocity in m/s.\n\n    \"\"\"\n\n    fast_interpolation = kwargs.pop('fast_interpolation', True)\n\n    if fast_interpolation:\n\n        current_interpolator = kwargs.pop('current_interpolator')\n        wind_interpolator = kwargs.pop('wind_interpolator')\n\n        vwu, vwv = current_interpolator((t, lat, lon))\n        vau, vav = wind_interpolator((t, lat, lon))\n\n    else:\n\n        vwus = kwargs.pop('eastward_current')\n        vwvs = kwargs.pop('northward_current')\n        vaus = kwargs.pop('eastward_wind')\n        vavs = kwargs.pop('northward_wind')\n\n        vwu = vwus.interp(time=t, latitude=lat, longitude=lon, assume_sorted=True).values\n        vwv = vwvs.interp(time=t, latitude=lat, longitude=lon, assume_sorted=True).values\n        vau = vaus.interp(time=t, latitude=lat, longitude=lon, assume_sorted=True).values\n        vav = vavs.interp(time=t, latitude=lat, longitude=lon, assume_sorted=True).values\n\n    kwargs['vwu'] = vwu\n    kwargs['vwv'] = vwv\n    kwargs['vau'] = vau\n    kwargs['vav'] = vav\n\n    vx, vy = analytical_drift(lon, lat, **kwargs)\n\n    return vx, vy\n\n\ndef analytical_drift(x, y, **kwargs):\n    \"\"\"This function computes the velocity of an iceberg using an analytical drift model.\n\n    Args:\n        x (float): longitude\n        y (float): latitude\n        **kwargs: coming soon - see source code for now.\n\n    Returns:\n        viu (float): x-component of iceberg velocity in m/s.\n        viv (float): y-component of iceberg velocity in m/s.\n    \"\"\"\n\n    vwu = kwargs.pop('vwu')\n    vwv = kwargs.pop('vwv')\n    vau = kwargs.pop('vau')\n    vav = kwargs.pop('vav')\n\n    l = kwargs.pop('waterline_length', 160)\n    w = kwargs.pop('waterline_length', 160)  # note: currently all icebergs are cuboid\n\n    Cw = kwargs.pop('form_drag_coefficient_in_water', 0.9)\n    Ca = kwargs.pop('form_drag_coefficient_in_air', 1.3)\n\n    Omega = EARTH_ROTATION_RATE\n    rhow = SEAWATER_DENSITY\n    rhoa = AIR_DENSITY\n    rhoi = ICEBERG_DENSITY\n\n    gamma = np.sqrt(rhoa * (rhow - rhoi) / rhow / rhoi * (Ca / Cw))\n    S = np.pi * ((l * w) / (l + w))\n    f = 2 * Omega * np.sin((np.abs(y) * np.pi) / 180)\n    Lambda = np.sqrt(2) * Cw * (gamma * np.sqrt(vau ** 2 + vav ** 2)) / (f * S)\n\n    if Lambda < 0.1:\n        alpha = Lambda * (Lambda**4 * (Lambda**4 * (Lambda**4 * (-0.0386699020961393 * Lambda**4 +\n                0.055242717280199) - 0.0883883476483184) + 0.176776695296637) - 0.707106781186548)\n\n    else:\n        alpha = np.multiply(np.divide(np.sqrt(2), np.power(Lambda, 3)), (1 - np.sqrt(1 + np.power(Lambda, 4))))\n\n    if Lambda < 0.6:\n        beta = Lambda**3 * (Lambda**4 * (Lambda**4 * (Lambda**4 * (Lambda**4 *\n                (Lambda**4 * (Lambda**4 * (Lambda**4 * (Lambda**4 * (0.0153268598203613 *\n                Lambda**4 - 0.0151656272365985) + 0.0180267866272764) + 0.0219176256311202) -\n                0.0274446790511418) + 0.0357675015202851) - 0.0493731785691779) + 0.0745776683282687) -\n                0.132582521472478) + 0.353553390593274)\n\n    else:\n        beta = np.real(np.multiply(np.divide(1, np.power(Lambda, 3)), cmath.sqrt(np.multiply((4 +\n                np.power(Lambda, 4)), cmath.sqrt(1 + np.power(Lambda, 4))) - 3 * np.power(Lambda, 4) - 4)))\n\n    viu = vwu + gamma * (-alpha * vav + beta * vau)\n    viv = vwv + gamma * (alpha * vau + beta * vav)\n\n    return viu, viv\n", "meta": {"hexsha": "bab1b8efadb0e055d483bef8ffa48c144d336e57", "size": 12672, "ext": "py", "lang": "Python", "max_stars_repo_path": "icedef/drift.py", "max_stars_repo_name": "evankielley/Icedef", "max_stars_repo_head_hexsha": "ae01c215e3bb6dbc15d1fef2821e17c2cc300669", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-02-20T06:28:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T03:55:52.000Z", "max_issues_repo_path": "icedef/drift.py", "max_issues_repo_name": "evankielley/Icedef", "max_issues_repo_head_hexsha": "ae01c215e3bb6dbc15d1fef2821e17c2cc300669", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "icedef/drift.py", "max_forks_repo_name": "evankielley/Icedef", "max_forks_repo_head_hexsha": "ae01c215e3bb6dbc15d1fef2821e17c2cc300669", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1024930748, "max_line_length": 112, "alphanum_fraction": 0.6081912879, "include": true, "reason": "import numpy", "num_tokens": 3956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.26894141551050293, "lm_q1q2_score": 0.154285882948089}}
{"text": "# discern.py\n# Contact: Jacob Schreiber\n#          jmschreiber91@gmail.com\n\n'''\nRun specific analyses for a cancer dataset using the general functions defined\nin ogimos. Each function should be a specific cancer type. These will usually\nrun analyses in batches and output RData files.\n'''\n\nimport pandas as pd\nimport numpy as np\nimport multiprocessing\nimport rpy2.robjects as ro\nimport matplotlib.pyplot as plt\n\nfrom rpy2.robjects.numpy2ri import numpy2ri\nro.conversion.py2ri = numpy2ri\n\ndef scale( data ):\n\t'''\n\tScale a matrix in a columnwise manner.\n\t'''\n\n\treturn ( data - data.mean( axis=0 ) ) / data.std( axis=0 )\n\nclass DISCERN( object ):\n\t'''\n\tDISCERN is an unsupervised feature selection algorithm which uses\n\tdifferential correlation in order to identify perturbed features given\n\tdata from two conditions. A Gaussian Graphical Model (GGM) is constructed\n\tfor each condition, with nodes being features and edges being weights\n\tcalculated by an Elastic Net Regressor. The DISCERN score is then calculated\n\tby looking at which edges differ significantly between the two networks, and\n\tidentifying which genes are perturbed between the features, i.e. have\n\tdifferent neighbors in the GGM.\n\t'''\n\n\tdef __init__( self ):\n\t\tpass\n\n\tdef fit_score( self, null_training, null_testing, alternate_training,\n\t\talternate_testing, names, mask=None, l=0, alpha=1.00, n_cores=None ):\n\t\t'''\n\t\tBuild a GGM for the null dataset and the alternate dataset separately\n\t\tusing an elastic net regressor. This is done through the R package\n\t\tglmnet. The DISCERN score will then be calculated and saved in\n\t\tself._scores.\n\t\t'''\n\n\t\t# Determine the number of cores to use. If -1 is passed in, use all the\n\t\t# cores, if nothing is passed in use 1 core, else use the specified\n\t\t# number of cores.\n\t\tif n_cores == -1:\n\t\t\tn_cores = multiprocessing.cpu_count()\n\t\telse:\n\t\t\tn_cores = n_cores or 1\n\n\t\t# If lambda is specified as 'auto', determine the best lambda using the\n\t\t# null training set.\n\t\tif l in ['auto', 'Auto']:\n\t\t\tl, sse = self.lambda_opt( null_training, names, mask, n_cores,\n\t\t\t\talpha=alpha )\n\n\t\t# Assign a uniform true mask on the covariates by default\n\t\tmask = mask or np.ones( null_training.shape[1] )\n\n\t\t# First we need to import the R libraries we want to work with\n\t\tro.r( \"library(glmnet)\" )\n\t\tro.r( \"library(foreach)\" )\n\t\tro.r( \"library(doParallel)\" )\n\n\t\t# Set up the cluster using the given size\n\t\tro.r( \"cl <- makeCluster({})\".format( n_cores ) )\n\t\tro.r( \"registerDoParallel(cl)\" )\n\n\t\t# Scale all four data sets used independently of each other.\n\t\tnull_testing = ( null_testing - null_training.mean( axis=0 ) ) / null_training.std( axis=0 )\n\t\tnull_training = ( null_training - null_training.mean( axis=0 ) ) / null_training.std( axis=0 )\n\t\talternate_testing = ( alternate_testing - alternate_training.mean( axis=0 ) ) / alternate_training.std( axis=0 ) \n\t\talternate_training = ( alternate_training - alternate_training.mean( axis=0) ) / alternate_training.std( axis=0 )\n \n\t\t# Now we need to push the data we're working with to the R environment\n\t\tro.r.assign( \"null_training\", null_training )\n\t\tro.r.assign( \"alternate_training\", alternate_training )\n\t\tro.r.assign( \"null_testing\", null_testing )\n\t\tro.r.assign( \"alternate_testing\", alternate_testing )\n\t\tro.r.assign( \"names\", names )\n\t\tro.r.assign( \"mask\", mask )\t\n\n\t\t# Now push the glmnet usage and scoring function\n\t\t# y_n and y_a refer to a specific column (gene) from those two matrices\n\t\t# X_n and X_a refer to all the covariates, excluding the one chosen for y\n\t\t# fit_n and fit_a are fitten glmnet objects for the null or cancer set\n\t\t# y_pred_ab are the predicted values using fit_a on X_b\n\t\t# error_ab is the error calculated using fit_a on X_b\n\n\t\tro.r( r\"\"\"\n\t\tdiscern <- function( lambda, alpha ) {\n\t\t\tclusterExport( cl, c(\"null_testing\", \"null_training\", \"alternate_testing\", \n\t\t\t\t\"alternate_training\", \"names\", \"mask\" ))\n\t\t\tresults <- foreach( i=1:dim(null_training)[2], .packages='glmnet' ) %dopar% {\n\t\t\t\tcovariates <- mask\n\t\t\t\tcovariates[i] = F\n\t\t\t\tname = names[[i]]\n\n\t\t\t\ty_n <- null_training[, i]\n\t\t\t\ty_a <- alternate_training[, i]\n\n\t\t\t\tX_n <- null_training[, as.logical( covariates ) ]\n\t\t\t\tX_a <- alternate_training[, as.logical( covariates ) ]\n\n\t\t\t\tfit_n <- glmnet( X_n, y_n, standardize=FALSE, alpha=alpha, lambda=lambda )\n\t\t\t\tfit_a <- glmnet( X_a, y_a, standardize=FALSE, alpha=alpha, lambda=lambda )\n\n\t\t\t\ty_n <- null_testing[, i]\n\t\t\t\ty_a <- alternate_testing[, i]\n\n\t\t\t\tX_n <- null_testing[, as.logical( covariates ) ]\n\t\t\t\tX_a <- alternate_testing[, as.logical( covariates ) ]\n\n\t\t\t\tr <- tryCatch(\n\t\t\t\t{\n\t\t\t\t\ty_pred_nn <- predict( fit_n, X_n, s=lambda )\n\t\t\t\t\ty_pred_na <- predict( fit_n, X_a, s=lambda )\n\t\t\t\t\ty_pred_an <- predict( fit_a, X_n, s=lambda )\n\t\t\t\t\ty_pred_aa <- predict( fit_a, X_a, s=lambda )\n\n\t\t\t\t\terror_nn = sum( (y_pred_nn-y_n)^2 )\n\t\t\t\t\terror_na = sum( (y_pred_na-y_a)^2 )\n\t\t\t\t\terror_an = sum( (y_pred_an-y_n)^2 )\n\t\t\t\t\terror_aa = sum( (y_pred_aa-y_a)^2 )\n\n\t\t\t\t\tT4 = ( error_na + error_an ) / ( error_nn + error_aa )\n\t\t\t\t\tT2 = error_na + error_an - error_nn - error_aa\n\t\t\t\t\tc( T2, T4 )\n\n\t\t\t\t}, error = function(err) { \n\t\t\t\t\tc( NaN, NaN )\n\t\t\t\t} ) \n\n\t\t\t\tresult = c( name, r[1], r[2] )\n\t\t\t\treturn( result )\n\t\t\t}\n\n\t\t\tstopCluster(cl)\n\t\t\tgc()\n\t\t\treturn( results ) \n\t\t}\"\"\" )\n\n\t\tscores = np.array( ro.r['discern']( l, alpha  ) )\n\t\tself._scores = pd.DataFrame( scores, columns=['Feature', 'T2', 'T4'] )\n\t\tself._scores.index = self._scores['Feature']\n\t\tself._scores = self._scores.convert_objects(convert_numeric=True)\n\t\treturn self._scores\n\n\tdef lambda_opt( self, data, names, mask=None, n_cores=None,\n\t\tnfolds=5, alpha=1.00, plot=False ):\n\t\t'''\n\t\tDetermine lambda_opt for a given set of data. Make sure that the data\n\t\tused here is the training data for the \n\t\t'''\n\n\t\t# Determine the number of cores to use. If -1 is passed in, use all the\n\t\t# cores, if nothing is passed in use 1 core, else use the specified\n\t\t# number of cores.\n\t\tif n_cores == -1:\n\t\t\tn_cores = multiprocessing.cpu_count()\n\t\telse:\n\t\t\tn_cores = n_cores or 1\n\n\t\t# Assign a uniform true mask on the covariates by default\n\t\tmask = mask or np.ones( data.shape[1] )\n\t\tlambdas = 10**np.arange( 1, -3.5, -.05 )\n\n\t\t# First we need to import the R libraries we want to work with\n\t\tro.r( \"library(glmnet)\" )\n\t\tro.r( \"library(foreach)\" )\n\t\tro.r( \"library(doParallel)\" )\n\t\tro.r( \"library(matrixStats)\")\n\n\t\t# Set up the cluster using the given size\n\t\tro.r( \"cl <- makeCluster({})\".format( n_cores ) )\n\t\tro.r( \"registerDoParallel(cl)\" )\n\n\t\t# Pass these variables into R\n\t\tro.r.assign( \"data\", data )\n\t\tro.r.assign( \"names\", names )\n\t\tro.r.assign( \"mask\", mask )\t\n\t\tro.r.assign( \"alpha\", alpha )\n\t\tro.r.assign( \"lambdas\", lambdas )\n\t\tro.r.assign( \"nfolds\", nfolds )\n\n\t\tlambda_cv = ro.r(\"\"\"\n\t\tlambda_cv <- function() {\n\t\t\tclusterExport( cl, c(\"data\", \"names\", \"mask\", \"alpha\", \"lambdas\", \"nfolds\") )\n\n\t\t\tSSE <- foreach( i=1:dim(data)[2], .packages=c('glmnet', 'foreach', 'matrixStats'), .combine='+' ) %dopar% {\n\t\t\t\tcovariates <- mask\n\t\t\t\tcovariates[i] = F\n\t\t\t\tname = names[[i]]\n\n\t\t\t\terrors <- foreach( j=1:nfolds, .combine='+' ) %do% {\n\t\t\t\t\tfold = seq( j, dim(data)[1], nfolds )\n\n\t\t\t\t\ty <- data[ -fold, i]\n\t\t\t\t\tX <- data[ -fold, as.logical( covariates ) ]\n\n\t\t\t\t\tx_mu_fit <- colMeans( X )\n\t\t\t\t\tx_sigma_fit <- colSds( X )\n\n\t\t\t\t\ty_mu_fit <- mean(y)\n\t\t\t\t\ty_sigma_fit <- sd(y)\n\n\t\t\t\t\ty <- ( y - y_mu_fit ) / y_sigma_fit\n\t\t\t\t\tX <- t( ( t(X) - x_mu_fit ) / x_sigma_fit )\n\n\t\t\t\t\tfit <- glmnet( X, y, standardize=FALSE, alpha=alpha, lambda=lambdas )\n\n\t\t\t\t\ty <- data[ fold, i ]\n\t\t\t\t\tX <- data[ fold, as.logical( covariates ) ]\n\n\t\t\t\t\ty <- ( y - y_mu_fit ) / y_sigma_fit \n\t\t\t\t\tX <- t( ( t(X) - x_mu_fit ) / x_sigma_fit )\n\n\t\t\t\t\ty_pred = predict( fit, X )\n\n\t\t\t\t\te <- foreach( k=1:dim(y_pred)[2] ) %do% {\n\t\t\t\t\t\tsum( ( y_pred[, k] - y )^2 )\n\t\t\t\t\t}\n\n\t\t\t\t\te = unlist(e)\n\t\t\t\t\treturn( e )\n\t\t\t\t}\n\n\t\t\t\terrors = unlist(errors)\n\t\t\t\treturn( errors )\n \t\t\t}\n\n\t\t\tstopCluster(cl)\n\t\t\treturn( SSE )\n\t\t}\n\t\t\"\"\")\n\n\t\tl = np.array(ro.r['lambda_cv']())\n\n\t\tif plot:\n\t\t\tplt.plot( lambdas, l, c='c', alpha=0.5 )\n\t\t\tplt.xscale('log')\n\t\t\tplt.xlabel('$\\lambda$')\n\t\t\tplt.ylabel('SSE')\n\t\t\tplt.title('Cross Validation Selection of $\\lambda$')\n\t\t\tplt.savefig('lambda_opt.png')\n\n\t\treturn lambdas[ np.argmin(l) ], l.min()\n\n\tdef sparsity( self, data, names, mask=None, n_cores=None,\n\t\tnfolds=5, alpha=1.00 ):\n\t\t'''\n\t\tCreate a graph of the sparsity of the matrix.\n\t\t'''\n\n\t\t# Determine the number of cores to use. If -1 is passed in, use all the\n\t\t# cores, if nothing is passed in use 1 core, else use the specified\n\t\t# number of cores.\n\t\tif n_cores == -1:\n\t\t\tn_cores = multiprocessing.cpu_count()\n\t\telse:\n\t\t\tn_cores = n_cores or 1\n\n\t\t# Assign a uniform true mask on the covariates by default\n\t\tmask = mask or np.ones( data.shape[1] )\n\t\tlambdas = 10**np.arange( 1, -3.5, -.05 )\n\n\t\t# First we need to import the R libraries we want to work with\n\t\tro.r( \"library(glmnet)\" )\n\t\tro.r( \"library(foreach)\" )\n\t\tro.r( \"library(doParallel)\" )\n\t\tro.r( \"library(matrixStats)\")\n\n\t\t# Set up the cluster using the given size\n\t\tro.r( \"cl <- makeCluster({})\".format( n_cores ) )\n\t\tro.r( \"registerDoParallel(cl)\" )\n\n\t\t# Pass these variables into R\n\t\tro.r.assign( \"data\", data )\n\t\tro.r.assign( \"names\", names )\n\t\tro.r.assign( \"mask\", mask )\t\n\t\tro.r.assign( \"alpha\", alpha )\n\t\tro.r.assign( \"lambdas\", lambdas )\n\t\tro.r.assign( \"nfolds\", nfolds )\n\n\t\tsparsity_cv = ro.r(\"\"\"\n\t\tsparsity_cv <- function() {\n\t\t\tclusterExport( cl, c(\"data\", \"names\", \"mask\", \"alpha\", \"lambdas\", \"nfolds\") )\n\n\t\t\t#sparsity <- foreach( i=1:dim(data)[2], .packages=c('glmnet', 'foreach', 'matrixStats'), .combine='+' ) %dopar% {\n\t\t\tsparsity <- foreach( i=1:dim(data)[2], .packages=c('glmnet', 'foreach', 'matrixStats'), .combine='+' ) %dopar% {\n\t\t\t\tcovariates <- mask\n\t\t\t\tcovariates[i] = F\n\t\t\t\tname = names[[i]]\n\n\t\t\t\tedges <- foreach( j=1:nfolds, .combine='+' ) %do% {\n\t\t\t\t\tfold = seq( j, dim(data)[1], nfolds )\n\n\t\t\t\t\ty <- data[ -fold, i]\n\t\t\t\t\tX <- data[ -fold, as.logical( covariates ) ]\n\n\t\t\t\t\tx_mu_fit <- colMeans( X )\n\t\t\t\t\tx_sigma_fit <- colSds( X )\n\n\t\t\t\t\ty_mu_fit <- mean(y)\n\t\t\t\t\ty_sigma_fit <- sd(y)\n\n\t\t\t\t\ty <- ( y - y_mu_fit ) / y_sigma_fit\n\t\t\t\t\tX <- t( ( t(X) - x_mu_fit ) / x_sigma_fit )\n\n\t\t\t\t\tfit <- glmnet( X, y, standardize=FALSE, alpha=alpha, lambda=lambdas )\n\n\t\t\t\t\tn_edges = fit['df']$df / nfolds\n\t\t\t\t\treturn(n_edges)\n\t\t\t\t}\n\n\t\t\t\tedges = unlist(edges)\n\t\t\t\treturn( edges )\n \t\t\t}\n\n\t\t\tstopCluster(cl)\n\t\t\treturn( sparsity )\n\t\t}\n\t\t\"\"\")\n\n\t\ts = np.array(ro.r['sparsity_cv']())\n\t\ts /= data.shape[1] ** 2\n\t\tprint s\n\n\t\tplt.plot( lambdas, s, c='c', alpha=0.5, linewidth=2.5 )\n\t\tplt.xscale('log')\n\t\tplt.xlabel('$\\lambda$')\n\t\tplt.ylabel('Percent Edges')\n\t\tplt.savefig('sparsity.png')\n", "meta": {"hexsha": "cf515bfd883f69ce4f790a11adfaa33122bf9a41", "size": 10603, "ext": "py", "lang": "Python", "max_stars_repo_path": "discern/discern.py", "max_stars_repo_name": "jmschrei/discern", "max_stars_repo_head_hexsha": "50b6f03d070604479c160569cca9ef7f031ff38d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-18T09:53:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-18T09:53:58.000Z", "max_issues_repo_path": "discern/discern.py", "max_issues_repo_name": "jmschrei/discern", "max_issues_repo_head_hexsha": "50b6f03d070604479c160569cca9ef7f031ff38d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "discern/discern.py", "max_forks_repo_name": "jmschrei/discern", "max_forks_repo_head_hexsha": "50b6f03d070604479c160569cca9ef7f031ff38d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0029239766, "max_line_length": 116, "alphanum_fraction": 0.6443459398, "include": true, "reason": "import numpy", "num_tokens": 3265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.2782567996876011, "lm_q1q2_score": 0.15428517300404462}}
{"text": "\"\"\"\nTIMP (Time-Inhomogeneous Markov Process) Data_Stall Recovery Trigger Modeling\n~~~~~~~~~~~~~~~~~~~~~\nTIMP model is for determining proper triggers of Data_Stall recovery\n\nCurrently, Android uses 1 minute as the sole trigger for recovery, which is found to be inefficient.\nTo overcome this, we develop a TIMP a formalize and model the entire Data_Stall-Recovery process.\nBased on this, we calculate the most suitable triggers that may result in the global minimum of recovery time.\n\nNote that to run this model, you may need Data_Stall duration data (which we will not disclose yet), as well as\ndevices' recovery stages\n\n:copyright: (c) 2020 by Cellular Reliability Team.\n:license: Apache 2.0, see LICENSE for more details.\n\"\"\"\nimport numpy as np\nimport os\nimport multiprocessing\nfrom functools import partial\n\n\ndef integrate_over_threshold_for_stage(thresholds, stage):\n    \"\"\"\n    Calculate the integration of event duration over different thresholds (triggers) for each recovery stage\n    :param thresholds: recovery triggers for entering the next recovery stage\n    :param stage: current recovery stage\n    :return: integration value\n    \"\"\"\n    durations_for_stage = durations_for_stages[stage]\n    start = 0\n    for i in range(stage):\n        start += thresholds[i]\n    if stage != 3:\n        end = start + thresholds[stage]\n    else:\n        end = durations_for_stage[-1]\n\n    durations_over_threshold = durations_for_stage[np.where(durations_for_stage <= end)[0]]\n    durations_over_threshold = durations_over_threshold[np.where(durations_over_threshold >= start)[0]]\n    if len(durations_over_threshold) == 0:\n        return 0\n    return np.average(durations_over_threshold)\n\n\ndef penalties():\n    \"\"\"\n    Penalties for executing each recovery operation\n    :return: penalties\n    \"\"\"\n    durations_over_threshold = [duration for duration in durations if duration <= 60000]\n    penalty = np.average(durations_over_threshold)\n    return [0, penalty, 2 * penalty, 3 * penalty]\n\n\ndef cdf_for_stages(thresholds):\n    \"\"\"\n    Calculate the CDF of event durations for each recovery stage\n    Here recovery stages are divided using given thresholds\n    :param thresholds: recovery triggers for entering the next recovery stage\n    :return: CDF\n    \"\"\"\n    end = 0\n    cdf = list()\n    for stage in range(3):\n        end += thresholds[stage]\n        cdf.append(len(np.where(durations <= end)[0]) / len(durations))\n    return cdf\n\n\ndef overhead(thresholds, cdf, stage=0):\n    \"\"\"\n    The expected recovery time starting at corresponding stage\n    This function is in recursive form so that we know the overall expected recovery time when stage is 0\n    :param thresholds: recovery triggers for entering the next recovery stage\n    :param cdf: CDF for durations in different recovery stages\n    :param stage: current recovery stage\n    :return: the expected recovery time\n    \"\"\"\n    if len(thresholds) != 3 or len(durations_for_stages) != 4:\n        raise Exception(\"Threshold values not enough!\")\n\n    if stage == 3:\n        return recovery_penalties[stage] + \\\n               integrate_over_threshold_for_stage(thresholds, stage)\n\n    return recovery_penalties[stage] + \\\n           integrate_over_threshold_for_stage(thresholds, stage) + \\\n           (1 - cdf[stage]) * overhead(thresholds, cdf, stage + 1)\n\n\ndef data_processing():\n    \"\"\"\n    Dedicated data processing function that turns CSV to NPY file for fast data loading\n    :return: None\n    \"\"\"\n    for file_name in os.listdir(os.getcwd()):\n        if not (file_name.startswith(\"DATA_STALL\") and file_name.endswith(\".csv\")):\n            continue\n        file_name = file_name[:-4]\n        data = list()\n        with open(\"{}.csv\".format(file_name), 'r') as file:\n            for line in file:\n                line = int(line.strip())\n                if line <= 86400000:\n                    data.append(line)\n        data.reverse()\n        np.save(\"{}-mod.npy\".format(file_name), np.array(data))\n\n\ndef prepare_data():\n    \"\"\"\n    Prepare all local data\n    To run this, you'll need corresponding Data_Stall duration data for each recovery stage\n    :return: None\n    \"\"\"\n    global durations, recovery_penalties\n    files = list()\n    for file in os.listdir(os.getcwd()):\n        if file.endswith(\"mod.npy\"):\n            files.append(file)\n    files = np.sort(files)\n    for file in files:\n        if file.endswith(\"all-mod.npy\"):\n            durations = np.load(file)\n            continue\n        print(\"Preparing {}...\".format(file))\n        durations_for_stages.append(np.load(file))\n\n    print(\"Preparing penalties...\")\n    recovery_penalties = penalties()\n    print(\"Preparing CDF...\")\n    print(\"End data preparations.\")\n\n\ndef loss(threshold1, threshold2, threshold3):\n    \"\"\"\n    The loss function that should be minimized for different thresholds, i.e., the expected recovery time\n    :param threshold1: the first trigger\n    :param threshold2: the second trigger\n    :param threshold3: the third trigger\n    :return: loss\n    \"\"\"\n    thresholds = [threshold1, threshold2, threshold3]\n    print(thresholds)\n    cdf = cdf_for_stages(thresholds)\n    result = overhead(thresholds, cdf, 0)\n    return result\n\n\ndef brute_force():\n    \"\"\"\n    Used for searching the global minimum (can be replaced by dual annealing or others)\n    :return: loss values for the entire trigger space\n    \"\"\"\n    cores = multiprocessing.cpu_count()\n    p = multiprocessing.Pool(processes=cores)\n    result = list()\n    for i in range(0, 60000, 1000):\n        for j in range(0, 60000, 1000):\n            par = partial(loss, threshold2=i, threshold3=j)\n            res = p.map(par, range(0, 60000, 1000))\n            result.extend(res)\n    return result\n\n\nif __name__ == '__main__':\n    # overall durations\n    durations = list()\n    # durations for events recovered in each stage\n    durations_for_stages = list()\n    recovery_penalties = list()\n    prepare_data()\n    # currently we use brute force to better present our results (since all search space is considered)\n    # we strongly recommend using other global optimization algorithms such as dual annealing for faster iteration\n    results = brute_force()\n    # print the global minimum and its corresponding index\n    print(np.min(results))\n    print(np.argmin(results))\n    np.save(\"results.npy\", results)\n", "meta": {"hexsha": "9e978a0a9faa95cb5bfa991088fd295e7abd15b8", "size": 6309, "ext": "py", "lang": "Python", "max_stars_repo_path": "timp/timp_model.py", "max_stars_repo_name": "CellularReliability/CellularReliability.github.io", "max_stars_repo_head_hexsha": "e7772731fdc49cec8951a62ff5ebbebe0113d7e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-02-02T23:35:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T17:20:51.000Z", "max_issues_repo_path": "timp/timp_model.py", "max_issues_repo_name": "CellularReliability/CellularReliability.github.io", "max_issues_repo_head_hexsha": "e7772731fdc49cec8951a62ff5ebbebe0113d7e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "timp/timp_model.py", "max_forks_repo_name": "CellularReliability/CellularReliability.github.io", "max_forks_repo_head_hexsha": "e7772731fdc49cec8951a62ff5ebbebe0113d7e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-04-07T01:33:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T08:36:33.000Z", "avg_line_length": 35.05, "max_line_length": 114, "alphanum_fraction": 0.6810905056, "include": true, "reason": "import numpy", "num_tokens": 1424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.22815650216092537, "lm_q1q2_score": 0.15418008765267918}}
{"text": "\"\"\"\nLatent Dirichlet Allocation models, including vanilla LDA as well as correlated\nand dynamic topic models (CTMs and DTMs) employing the Polya-Gamma augmentation.\n\"\"\"\n\nimport abc\nimport copy\nimport numpy as np\nfrom scipy.misc import logsumexp\nfrom scipy.linalg import solve_triangular as _solve_triangular\nfrom scipy.linalg.lapack import dpotrs as _dpotrs\nfrom scipy.special import gammaln\nimport scipy.sparse\n\nfrom pypolyagamma import pgdrawvpar\nfrom gslrandom import multinomial\nfrom pybasicbayes.distributions import Gaussian\nfrom pylds.lds_messages_interface import filter_and_sample_randomwalk\n\nfrom pgmult.utils import \\\n    kappa_vec, N_vec, \\\n    compute_uniform_mean_psi, psi_to_pi, pi_to_psi, \\\n    ln_pi_to_psi, ln_psi_to_pi, \\\n    initialize_polya_gamma_samplers, \\\n    initialize_pyrngs\n\n\n###\n# Util\n###\n\ndef dpotrs(L, a):\n    return _dpotrs(L, a, lower=True)[0]\n\n\ndef solve_triangular(L, a):\n    return _solve_triangular(L, a, lower=True, trans='T')\n\n\ndef sample_dirichlet(a, normalize):\n    if 'vertical'.startswith(normalize):\n        return np.hstack([np.random.dirichlet(col)[:,None] for col in a.T])\n    else:\n        return np.vstack([np.random.dirichlet(row) for row in a])\n\n\ndef sample_infogaussian(J, h, randvec=None):\n    randvec = randvec if randvec is not None else np.random.randn(h.shape[0])\n    L = np.linalg.cholesky(J)\n    return dpotrs(L, h) + solve_triangular(L, randvec)\n\n\ndef csr_nonzero(mat):\n    rows = np.arange(mat.shape[0]).repeat(np.diff(mat.indptr))\n    cols = mat.indices\n    return rows, cols\n\n\ndef normalize_rows(a):\n    a /= a.sum(1)[:,None]\n    return a\n\n\ndef log_likelihood(data, wordprobs):\n    return np.sum(np.nan_to_num(np.log(wordprobs)) * data.data) \\\n        + gammaln(data.sum(1)+1).sum() - gammaln(data.data+1).sum()\n\n\ndef check_timestamps(timestamps):\n    assert np.all(timestamps == timestamps[np.argsort(timestamps)])\n\n\ndef is_sorted(a):\n    return np.all(a == a[np.argsort(a)])\n\n\ndef timeindices_from_timestamps(timestamps):\n    return np.array(timestamps) - timestamps[0]\n\n\n###\n# LDA Models\n###\n\n# LDA and the CTMs all treat beta, z, and likelihoods the same way, so that\n# stuff is factored out into _LDABase. Since each model treats theta\n# differently, theta stuff is left abstract.\n\nclass _LDABase(object):\n    def __init__(self, data, T, alpha_beta):\n        assert isinstance(data, scipy.sparse.csr.csr_matrix)\n        self.D, self.V = data.shape\n        self.T = T\n        self.alpha_beta = alpha_beta\n\n        self.data = data\n\n        self.pyrngs = initialize_pyrngs()\n\n        self.initialize_beta()\n        self.initialize_theta()\n        self.z = np.zeros((data.data.shape[0], T), dtype='uint32')\n        self.resample_z()\n\n        # precompute\n        self._training_gammalns = \\\n            gammaln(data.sum(1)+1).sum() - gammaln(data.data+1).sum()\n\n    @abc.abstractproperty\n    def theta(self):\n        pass\n\n    @abc.abstractmethod\n    def initialize_theta(self):\n        pass\n\n    @abc.abstractmethod\n    def resample_theta(self):\n        pass\n\n    def initialize_beta(self):\n        self.beta = sample_dirichlet(\n            self.alpha_beta * np.ones((self.V, self.T)), 'vert')\n\n    @abc.abstractproperty\n    def copy_sample(self):\n        pass\n\n    def get_wordprobs(self, data):\n        return self.theta.dot(self.beta.T)[csr_nonzero(data)]\n\n    def get_topicprobs(self, data):\n        rows, cols = csr_nonzero(data)\n        return normalize_rows(self.theta[rows] * self.beta[cols])\n\n    def log_likelihood(self, data=None):\n        if data is not None:\n            return log_likelihood(data, self.get_wordprobs(data))\n        else:\n            # this version avoids recomputing the training gammalns\n            wordprobs = self.get_wordprobs(self.data)\n            return np.sum(np.nan_to_num(np.log(wordprobs)) * self.data.data) \\\n                + self._training_gammalns\n\n    def perplexity(self, data):\n        return np.exp(-self.log_likelihood(data)\n                      / data.sum())\n\n    def resample(self):\n        self.resample_z()\n        self.resample_theta()\n        self.resample_beta()\n\n    def resample_beta(self):\n        self.beta = sample_dirichlet(\n            self.alpha_beta + self.word_topic_counts, 'v')\n\n    def resample_z(self):\n        topicprobs = self.get_topicprobs(self.data)\n        multinomial(self.pyrngs, self.data.data, topicprobs, self.z)\n        self._update_counts()\n\n    def _update_counts(self):\n        self.doc_topic_counts = np.zeros((self.D, self.T), dtype='uint32')\n        self.word_topic_counts = np.zeros((self.V, self.T), dtype='uint32')\n        rows, cols = csr_nonzero(self.data)\n        for i, j, zvec in zip(rows, cols, self.z):\n            self.doc_topic_counts[i] += zvec\n            self.word_topic_counts[j] += zvec\n\n    def generate(self, N, keep=True):\n        word_probs = np.dot(self.theta, self.beta.T)\n        assert word_probs.shape == (self.D, self.V)\n        data = np.zeros((self.D, self.V))\n        for d in range(self.D):\n            data[d] = np.random.multinomial(N, word_probs[d])\n        data = scipy.sparse.csr_matrix(data)\n\n        if keep:\n            self.data = data\n            self.z = np.zeros((data.data.shape[0], self.T), dtype='uint32')\n            self.resample_z()\n            # precompute\n            self._training_gammalns = \\\n                gammaln(data.sum(1)+1).sum() - gammaln(data.data+1).sum()\n\n\nclass StandardLDA(_LDABase):\n    \"Standard LDA with Dirichlet priors\"\n\n    def __init__(self, data, T, alpha_beta, alpha_theta):\n        self.alpha_theta = alpha_theta\n        super(StandardLDA, self).__init__(data, T, alpha_beta)\n\n    @property\n    def theta(self):\n        return self._theta\n\n    @theta.setter\n    def theta(self, theta):\n        self._theta = theta\n\n    def initialize_theta(self):\n        self.theta = sample_dirichlet(\n            self.alpha_theta * np.ones((self.D, self.T)), 'horiz')\n\n    def resample_theta(self):\n        self.theta = sample_dirichlet(\n            self.alpha_theta + self.doc_topic_counts, 'horiz')\n\n    def copy_sample(self):\n        new = copy.copy(self)\n        new.beta = self.beta.copy()\n        new._theta = self._theta.copy()\n        return new\n\n    def resample_collapsed(self,niter=1):\n        self.resample_z_collapsed(niter)\n        self.resample_theta()\n        self.resample_beta()\n\n    def resample_z_collapsed(self,niter=1):\n        from ._lda import CollapsedCounts\n\n        counts = CollapsedCounts(\n            self.alpha_theta, self.alpha_beta, self.T,\n            self.z, self.doc_topic_counts, self.word_topic_counts,\n            self.data)\n        counts.resample(niter)\n\n        self.z = counts.z\n        self.doc_topic_counts = counts.doc_topic_counts\n        self.word_topic_counts = counts.word_topic_counts\n\n\n###\n# Correlated LDA Models (CTMs)\n###\n\nclass StickbreakingCorrelatedLDA(_LDABase):\n    \"Correlated LDA with the stick breaking representation\"\n\n    def __init__(self, data, T, alpha_beta):\n        mu, sigma = compute_uniform_mean_psi(T)\n        self.theta_prior = Gaussian(\n            mu=mu, sigma=sigma, mu_0=mu, sigma_0=T*sigma/10.,\n            nu_0=T/10., kappa_0=1./10)\n\n        self.ppgs = initialize_polya_gamma_samplers()\n        self.omega = np.zeros((data.shape[0], T-1))\n\n        super(StickbreakingCorrelatedLDA, self).__init__(data, T, alpha_beta)\n\n    @property\n    def theta(self):\n        return psi_to_pi(self.psi)\n\n    @theta.setter\n    def theta(self, theta):\n        self.psi = pi_to_psi(theta)\n\n    def initialize_theta(self):\n        self.psi = np.tile(self.theta_prior.mu, (self.D, 1))\n\n    def resample_theta(self):\n        self.resample_omega()\n        self.resample_psi()\n\n    def resample(self):\n        super(StickbreakingCorrelatedLDA, self).resample()\n        self.resample_theta_prior()\n\n    def resample_omega(self):\n        pgdrawvpar(\n            self.ppgs, N_vec(self.doc_topic_counts).astype('float64').ravel(),\n            self.psi.ravel(), self.omega.ravel())\n        np.clip(self.omega, 1e-32, np.inf, out=self.omega)\n\n    def resample_psi(self):\n        Lmbda = np.linalg.inv(self.theta_prior.sigma)\n        h = Lmbda.dot(self.theta_prior.mu)\n        randvec = np.random.randn(self.D, self.T-1)  # pre-generate randomness\n\n        for d, c in enumerate(self.doc_topic_counts):\n            self.psi[d] = sample_infogaussian(\n                Lmbda + np.diag(self.omega[d]), h + kappa_vec(c),\n                randvec[d])\n\n    def resample_theta_prior(self):\n        self.theta_prior.resample(self.psi)\n\n    def copy_sample(self):\n        new = copy.copy(self)\n        new.beta = self.beta.copy()\n        new.psi = self.psi.copy()\n        new.theta_prior = self.theta_prior.copy_sample()\n        del new.z\n        del new.omega\n        return new\n\n\nclass LogisticNormalCorrelatedLDA(_LDABase):\n    \"Correlated LDA with the stick breaking representation\"\n\n    def __init__(self, data, T, alpha_beta):\n        mu, sigma = np.zeros(T), np.eye(T)\n        self.theta_prior = \\\n            Gaussian(\n                mu=mu, sigma=sigma, mu_0=mu, sigma_0=T*sigma/10.,\n                nu_0=T/10., kappa_0=10.)\n\n        self.ppgs = initialize_polya_gamma_samplers()\n        self.omega = np.zeros((data.shape[0], T))\n\n        super(LogisticNormalCorrelatedLDA, self).__init__(data, T, alpha_beta)\n\n    @property\n    def theta(self):\n        return ln_psi_to_pi(self.psi)\n\n    @theta.setter\n    def theta(self, theta):\n        self.psi = ln_pi_to_psi(theta)\n\n    def initialize_theta(self):\n        self.psi = np.tile(self.theta_prior.mu, (self.D, 1))\n\n    def resample_theta(self):\n        self.resample_psi_and_omega()\n\n    def resample(self):\n        super(LogisticNormalCorrelatedLDA, self).resample()\n        self.resample_theta_prior()\n\n    def resample_psi_and_omega(self):\n        Lmbda = np.linalg.inv(self.theta_prior.sigma)\n        for d in range(self.D):\n            N = self.data[d].sum()\n            c = self.doc_topic_counts[d]\n            for t in range(self.T):\n                self.omega[d,t] = self.ppgs[0].pgdraw(\n                    N, self._conditional_omega(d,t))\n\n                mu_cond, sigma_cond = self._conditional_psi(d, t, Lmbda, N, c)\n                self.psi[d,t] = np.random.normal(mu_cond, np.sqrt(sigma_cond))\n\n    def _conditional_psi(self, d, t, Lmbda, N, c):\n        nott = np.arange(self.T) != t\n        psi = self.psi[d]\n        omega = self.omega[d]\n        mu = self.theta_prior.mu\n\n        zetat = logsumexp(psi[nott])\n\n        mut_marg = mu[t] - 1./Lmbda[t,t] * Lmbda[t,nott].dot(psi[nott] - mu[nott])\n        sigmat_marg = 1./Lmbda[t,t]\n\n        sigmat_cond = 1./(omega[t] + 1./sigmat_marg)\n\n        # kappa is the mean dot precision, i.e. the sufficient statistic of a Gaussian\n        # therefore we can sum over datapoints\n        kappa = (c[t] - N/2.0).sum()\n        mut_cond = sigmat_cond * (kappa + mut_marg / sigmat_marg + omega[t]*zetat)\n\n        return mut_cond, sigmat_cond\n\n    def _conditional_omega(self, d, t):\n        nott = np.arange(self.T) != t\n        psi = self.psi[d]\n        zetat = logsumexp(psi[nott])\n        return psi[t] - zetat\n\n    def resample_theta_prior(self):\n        self.theta_prior.resample(self.psi)\n\n    def copy_sample(self):\n        new = copy.copy(self)\n        new.beta = self.beta.copy()\n        new.psi = self.psi.copy()\n        new.theta_prior = self.theta_prior.copy_sample()\n        del new.z\n        del new.omega\n        return new\n\n\n###\n# Dynamic LDA Models (DTMs)\n###\n\nclass StickbreakingDynamicTopicsLDA(object):\n    def __init__(self, data, timestamps, K, alpha_theta):\n        assert isinstance(data, scipy.sparse.csr.csr_matrix)\n        self.alpha_theta = alpha_theta\n        self.D, self.V = data.shape\n        self.K = K\n\n        self.data = data\n\n        self.timestamps = timestamps\n        self.timeidx = self._get_timeidx(timestamps, data)\n        self.T = self.timeidx.max() - self.timeidx.min() + 1\n\n        self.ppgs = initialize_polya_gamma_samplers()\n        self.pyrngs = initialize_pyrngs()\n\n        self.initialize_parameters()\n\n        self._training_gammalns = \\\n            gammaln(data.sum(1)+1).sum() - gammaln(data.data+1).sum()\n\n    def initialize_parameters(self):\n        self.sigmasq_states = 0.1  # TODO make this learned, init from hypers\n\n        mean_psi = compute_uniform_mean_psi(self.V)[0][None,:,None]\n        self.psi = np.tile(mean_psi, (self.T, 1, self.K))\n\n        self.omega = np.zeros_like(self.psi)\n\n        self.theta = sample_dirichlet(\n            self.alpha_theta * np.ones((self.D, self.K)), 'horiz')\n\n        self.z = np.zeros((self.data.data.shape[0], self.K), dtype='uint32')\n        self.resample_z()\n\n    def log_likelihood(self, data=None):\n        if data is not None:\n            return log_likelihood(\n                data, self._get_wordprobs(\n                    data, self._get_timeidx(self.timestamps, data)))\n        else:\n            # this version avoids recomputing the training gammalns\n            wordprobs = self._get_wordprobs(self.data, self.timeidx)\n            return np.sum(np.nan_to_num(np.log(wordprobs)) * self.data.data) \\\n                + self._training_gammalns\n\n    @property\n    def beta(self):\n        return psi_to_pi(self.psi, axis=1)\n\n    def resample(self):\n        self.resample_z()\n        self.resample_theta()\n        self.resample_beta()\n        self.resample_lds_params()\n\n    def resample_theta(self):\n        self.theta = sample_dirichlet(\n            self.alpha_theta + self.doc_topic_counts, 'horiz')\n\n    def resample_beta(self):\n        self.resample_omega()\n        self.resample_psi()\n\n    def resample_psi(self):\n        mu_init, sigma_init, sigma_states, sigma_obs, y = \\\n            self._get_lds_effective_params()\n        _, psi_flat = filter_and_sample_randomwalk(\n            mu_init, sigma_init, sigma_states, sigma_obs, y)\n        self.psi = psi_flat.reshape(self.psi.shape)\n\n    def resample_z(self):\n        topicprobs = self._get_topicprobs()\n        multinomial(self.pyrngs, self.data.data, topicprobs, self.z)\n        self._update_counts()\n\n    def resample_omega(self):\n        pgdrawvpar(\n            self.ppgs,\n            N_vec(self.time_word_topic_counts, axis=1)\n                .astype('float64').ravel(),\n            self.psi.ravel(), self.omega.ravel())\n        np.clip(self.omega, 1e-32, np.inf, out=self.omega)\n\n    def resample_lds_params(self):\n        pass  # TODO\n\n    def _get_lds_effective_params(self):\n        mu_uniform, sigma_uniform = compute_uniform_mean_psi(self.V)\n        mu_init = np.tile(mu_uniform, self.K)\n        sigma_init = np.tile(np.diag(sigma_uniform), self.K)\n\n        sigma_states = np.repeat(self.sigmasq_states, (self.V - 1) * self.K)\n\n        sigma_obs = 1./self.omega\n        y = kappa_vec(self.time_word_topic_counts, axis=1) / self.omega\n\n        return mu_init, sigma_init, sigma_states, \\\n            sigma_obs.reshape(y.shape[0], -1), y.reshape(y.shape[0], -1)\n\n    def _update_counts(self):\n        self.doc_topic_counts = np.zeros((self.D, self.K), dtype='uint32')\n        self.time_word_topic_counts = np.zeros((self.T, self.V, self.K), dtype='uint32')\n        rows, cols = csr_nonzero(self.data)\n        for i, j, t, zvec in zip(rows, cols, self.timeidx, self.z):\n            self.doc_topic_counts[i] += zvec\n            self.time_word_topic_counts[t,j] += zvec\n\n    def _get_topicprobs(self):\n        rows, cols = csr_nonzero(self.data)\n        return normalize_rows(self.theta[rows] * self.beta[self.timeidx,cols])\n\n    def _get_wordprobs(self, data, timeidx):\n        rows, cols = csr_nonzero(data)\n        return np.einsum('tk,tk->t',self.theta[rows],self.beta[timeidx, cols])\n\n    def _get_timeidx(self, timestamps, data):\n        timeidx = np.repeat(\n            timeindices_from_timestamps(timestamps), np.diff(data.indptr))\n        assert is_sorted(timeidx)\n        return timeidx\n\n# TODO we probably want to operate around a uniform (or separately sampled) bias\n# point for psi. or maybe LDS should just learn a mean offset.\n", "meta": {"hexsha": "1c766c4405b48db3df58ea97c4ad43cd01ae09b8", "size": 15983, "ext": "py", "lang": "Python", "max_stars_repo_path": "pgmult/lda.py", "max_stars_repo_name": "SebastianBruijns/pgmult", "max_stars_repo_head_hexsha": "b727e31f58474c53d6cbf3abf6823db3b2bb4797", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pgmult/lda.py", "max_issues_repo_name": "SebastianBruijns/pgmult", "max_issues_repo_head_hexsha": "b727e31f58474c53d6cbf3abf6823db3b2bb4797", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pgmult/lda.py", "max_forks_repo_name": "SebastianBruijns/pgmult", "max_forks_repo_head_hexsha": "b727e31f58474c53d6cbf3abf6823db3b2bb4797", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0953307393, "max_line_length": 88, "alphanum_fraction": 0.6306075205, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 4087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.23651623106411432, "lm_q1q2_score": 0.15405599767609138}}
{"text": "#!/usr/bin/env python3\n\nimport inf_common as IC\n\nimport torch\nfrom torch import Tensor\n\nimport time\n\nfrom typing import Dict, List, Tuple, Optional\n\nfrom collections import defaultdict\nfrom collections import ChainMap\n\nimport sys,random,itertools\n\nimport numpy as np\n\nfrom multiprocessing import Pool\n\n'''\nenum class InferenceRule : unsigned char {\n  INPUT,\n  GENERIC_FORMULA_TRANSFORMATION,\n  NEGATED_CONJECTURE,\n  ANSWER_LITERAL,\n  CLAIM_DEFINITION,\n  RECTIFY,\n  CLOSURE,\n  FLATTEN,\n  ENNF,\n  NNF,\n  REDUCE_FALSE_TRUE,    ----> 10\n\n  DEFINITION_FOLDING,\n  THEORY_NORMALIZATION,\n  SKOLEMIZE,\n  CLAUSIFY,\n  INTERNAL_FORMULA_TRANSFORMATION_LAST,\n  GENERIC_SIMPLIFYING_INFERNCE,\n  REORDER_LITERALS,\n  REMOVE_DUPLICATE_LITERALS,\n  TRIVIAL_INEQUALITY_REMOVAL,\n  EQUALITY_RESOLUTION_WITH_DELETION,  -----> 20\n  \n  SUBSUMPTION_RESOLUTION,\n  FORWARD_DEMODULATION,\n  BACKWARD_DEMODULATION,\n  FORWARD_SUBSUMPTION_DEMODULATION,\n  BACKWARD_SUBSUMPTION_DEMODULATION,\n  FORWARD_LITERAL_REWRITING,\n  INNER_REWRITING,\n  CONDENSATION,\n  EVALUATION,\n  INTERPRETED_SIMPLIFICATION,     ------> 30\n\n  THEORY_FLATTENING,\n  TERM_ALGEBRA_DISTINCTNESS,\n  TERM_ALGEBRA_INJECTIVITY_SIMPLIFYING,\n  HYPER_SUPERPOSITION_SIMPLIFYING,\n  GLOBAL_SUBSUMPTION,\n  DISTINCT_EQUALITY_REMOVAL,\n  GAUSSIAN_VARIABLE_ELIMINIATION,\n  INTERNAL_SIMPLIFYING_INFERNCE_LAST,\n  GENERIC_GENERATING_INFERNCE,\n  RESOLUTION,                    -------> 40\n  \n  CONSTRAINED_RESOLUTION,\n  FACTORING,\n  CONSTRAINED_FACTORING,\n  SUPERPOSITION,\n  CONSTRAINED_SUPERPOSITION,\n  EQUALITY_FACTORING,\n  EQUALITY_RESOLUTION,\n  EXTENSIONALITY_RESOLUTION,\n  TERM_ALGEBRA_INJECTIVITY_GENERATING,\n  TERM_ALGEBRA_ACYCLICITY,      -------> 50\n  \n  \n  /** Replaces a literal of the form C[s] with C[true] \\/ s = false, where s is a boolean non-variable term */\n  FOOL_PARAMODULATION,\n  /** unit resulting resolution */\n  UNIT_RESULTING_RESOLUTION,\n  /** hyper-superposition */\n  HYPER_SUPERPOSITION_GENERATING,\n  /** generated as instance of its parent */\n  INSTANCE_GENERATION, // used by InstGen. Fun fact: the inference has one parent (logically) but the age is set from two parents (and +1)!\n  /* Instantiation */\n  INSTANTIATION, // used for theory reasoning\n  /** the last generating inference marker --\n        inferences between GENERIC_GENERATING_INFERNCE and INTERNAL_GENERATING_INFERNCE_LAST will be automatically understood generating\n        (see also isGeneratingInferenceRule) */\n  INTERNAL_GENERATING_INFERNCE_LAST,\n\n\n  /** equality proxy replacement */\n  EQUALITY_PROXY_REPLACEMENT,\n  /** definition of the equality proxy predicate in the form E(x,y) <=> x=y */\n  EQUALITY_PROXY_AXIOM1,\n  /** equality proxy axioms such as E(x,x) or ~E(x,y) \\/ x=y */\n  EQUALITY_PROXY_AXIOM2,\n  /** unfolding by definitions f(x1,...,xn)=t */\n  DEFINITION_UNFOLDING,\n\n  /** introduction of new name p, p <=> C */\n  PREDICATE_DEFINITION,\n  /** unfolding predicate definitions */\n  PREDICATE_DEFINITION_UNFOLDING,\n  /** merging predicate definitions */\n  PREDICATE_DEFINITION_MERGING,\n\n\n  /** unused predicate definition removal */\n  UNUSED_PREDICATE_DEFINITION_REMOVAL,\n  /** pure predicate removal */\n  PURE_PREDICATE_REMOVAL,\n  /** inequality splitting */\n  INEQUALITY_SPLITTING,\n  /** inequality splitting name introduction */\n  INEQUALITY_SPLITTING_NAME_INTRODUCTION,\n  /** grounding */\n  GROUNDING,\n  /** equality axiom */\n  EQUALITY_AXIOM,\n  /** distinctness axiom */\n  DISTINCTNESS_AXIOM,\n  /** Introduction of formula to convert formulas used as argument positions.\n   *  Such formulas have the form F->f(x)=1 or ~F->f(x)=0 */\n  BOOLEAN_TERM_ENCODING,\n  /** Elimination of FOOL expressions that makes a formula not syntactically first-order */\n  FOOL_ELIMINATION,\n  /** Elimination of $ite expressions */\n  FOOL_ITE_ELIMINATION,\n  /** Elimination of $let expressions */\n  FOOL_LET_ELIMINATION,\n  /** result of general splitting */\n  GENERAL_SPLITTING,\n  /** component introduced by general splitting */\n  GENERAL_SPLITTING_COMPONENT,\n  /** replacing colored constants by skolem functions */\n  COLOR_UNBLOCKING,\n\n  /** refutation in the SAT solver for InstGen */\n  SAT_INSTGEN_REFUTATION,\n\n  /** definition introduced by AVATAR */\n  AVATAR_DEFINITION,\n  /** component introduced by AVATAR */\n  AVATAR_COMPONENT,\n  /** refutation of a AVATAR splitting branch */\n  AVATAR_REFUTATION,\n  /** sat clause representing FO clause for AVATAR */\n  AVATAR_SPLIT_CLAUSE,\n  /** sat clause representing FO clause for AVATAR */\n  AVATAR_CONTRADICTION_CLAUSE,\n  /** sat color elimination */\n  SAT_COLOR_ELIMINATION,\n  /** obtain a formula from a clause */\n  FORMULIFY,\n\n  /** inference coming from outside of Vampire */\n  EXTERNAL,\n\n  /* FMB flattening */\n  FMB_FLATTENING,\n  /* Functional definition for FMB */\n  FMB_FUNC_DEF,\n  /* Definition Introduction for FMB */\n  FMB_DEF_INTRO,\n  /* Finite model not found */\n  MODEL_NOT_FOUND,\n\n  /* Adding sort predicate */\n  ADD_SORT_PREDICATES,\n  /* Adding sort functions */\n  ADD_SORT_FUNCTIONS,\n\n  /** a premise to skolemization */\n  CHOICE_AXIOM,\n\n  /* Induction hypothesis*/\n  INDUCTION_AXIOM,\n  /* Generalized nduction hypothesis*/\n  GEN_INDUCTION_AXIOM,\n\n  /* the unit clause against which the Answer is extracted in the last step */\n  ANSWER_LITERAL_RESOLVER,\n\n  /** A (first-order) tautology generated on behalf of a decision procedure,\n   * whose propositional counterpart becomes a conflict clause in a sat solver */\n  THEORY_TAUTOLOGY_SAT_CONFLICT,\n\n  /** a not further specified theory axiom internally added by the class TheoryAxioms. */\n  GENERIC_THEORY_AXIOM, // CAREFUL: adding rules here influences the theory_split_queue heuristic\n  /** Some specific groups of axioms coming from TheoryAxioms.cpp\" */\n  THA_COMMUTATIVITY,\n  THA_ASSOCIATIVITY,\n  THA_RIGHT_IDENTINTY,\n  THA_LEFT_IDENTINTY,\n  THA_INVERSE_OP_OP_INVERSES,\n  THA_INVERSE_OP_UNIT,\n  THA_INVERSE_ASSOC,\n  THA_NONREFLEX,\n  THA_TRANSITIVITY,\n  THA_ORDER_TOTALALITY,\n  THA_ORDER_MONOTONICITY,\n  THA_PLUS_ONE_GREATER,\n  THA_ORDER_PLUS_ONE_DICHOTOMY,\n  THA_MINUS_MINUS_X,\n  THA_TIMES_ZERO,\n  THA_DISTRIBUTIVITY,\n  THA_DIVISIBILITY,\n  THA_MODULO_MULTIPLY,\n  THA_MODULO_POSITIVE,\n  THA_MODULO_SMALL,\n  THA_DIVIDES_MULTIPLY,\n  THA_NONDIVIDES_SKOLEM,\n  THA_ABS_EQUALS,\n  THA_ABS_MINUS_EQUALS,\n  THA_QUOTIENT_NON_ZERO,\n  THA_QUOTIENT_MULTIPLY,\n  THA_EXTRA_INTEGER_ORDERING,\n  THA_FLOOR_SMALL,\n  THA_FLOOR_BIG,\n  THA_CEILING_BIG,\n  THA_CEILING_SMALL,\n  THA_TRUNC1,\n  THA_TRUNC2,\n  THA_TRUNC3,\n  THA_TRUNC4,\n  THA_ARRAY_EXTENSIONALITY,\n  THA_BOOLEAN_ARRAY_EXTENSIONALITY, // currently applied to a formula, so won't propagate to clause->isTheoryAxiom()\n  THA_BOOLEAN_ARRAY_WRITE1, // currently applied to a formula, so won't propagate to clause->isTheoryAxiom()\n  THA_BOOLEAN_ARRAY_WRITE2, // currently applied to a formula, so won't propagate to clause->isTheoryAxiom()\n  THA_ARRAY_WRITE1,\n  THA_ARRAY_WRITE2,\n  /** acyclicity axiom for term algebras */\n  TERM_ALGEBRA_ACYCLICITY_AXIOM,\n  TERM_ALGEBRA_DIRECT_SUBTERMS_AXIOM,\n  TERM_ALGEBRA_SUBTERMS_TRANSITIVE_AXIOM,\n  /** discrimination axiom for term algebras */\n  TERM_ALGEBRA_DISCRIMINATION_AXIOM,\n  /** distinctness axiom for term algebras */\n  TERM_ALGEBRA_DISTINCTNESS_AXIOM,\n  /** exhaustiveness axiom (or domain closure axiom) for term algebras */\n  TERM_ALGEBRA_EXHAUSTIVENESS_AXIOM, // currently (sometimes) applied to a formula, so won't propagate to clause->isTheoryAxiom()\n  /** exhaustiveness axiom (or domain closure axiom) for term algebras */\n  TERM_ALGEBRA_INJECTIVITY_AXIOM,\n  /** one of two axioms of FOOL (distinct constants or finite domain) */\n  FOOL_AXIOM_TRUE_NEQ_FALSE,\n  FOOL_AXIOM_ALL_IS_TRUE_OR_FALSE,\n  /** the last internal theory axiom marker --\n    axioms between THEORY_AXIOM and INTERNAL_THEORY_AXIOM_LAST will be automatically making their respective clauses isTheoryAxiom() true */\n  INTERNAL_THEORY_AXIOM_LAST,\n  /** a theory axiom which is not generated internally in Vampire */\n  EXTERNAL_THEORY_AXIOM\n}; // class InferenceRule\n'''\n\ndef contribute(repr,depth,isgood,val,logit):\n  # print(repr,depth,isgood,val,logit)\n\n  (abs_repr,sines) = repr\n  sines = tuple(sines)\n\n  group = abs_repr_groups[abs_repr]\n  if sines in group:\n    (models_val,models_logit,pos_labels,neg_labels) = group[sines]\n    assert models_val == val\n    assert models_logit == logit\n  else:\n    models_val = val\n    models_logit = logit\n    pos_labels = 0\n    neg_labels = 0\n\n  if isgood:\n    pos_labels += 1\n  else:\n    neg_labels += 1\n\n  group[sines] = (models_val,models_logit,pos_labels,neg_labels)\n\n  '''\n  print(abs_repr)\n  for sines, (models_val,models_logit,pos_labels,neg_labels) in group.items():\n    print(sines,(models_val,models_logit,pos_labels,neg_labels) )\n  print()\n  '''\n\ndef eval_one(init,deriv,pars,selec,isgood,axioms):\n  for id, (thax,sine) in init:\n    if thax == -1:\n      st = \"-1\"\n      abs_repr = \"conj\"\n    elif id in axioms:\n      st = axioms[id]\n      abs_repr = st\n    else:\n      assert thax == 0\n      st = str(thax)\n      abs_repr = \"other\"\n  \n    repr = (abs_repr,[sine])\n\n    # communication via st and sine\n    if model:\n      getattr(model,\"new_init\")(id,[-1,-1,-1,-1,-1,sine],st)\n      logit = model(id) # calling forward\n      val = (logit >= 0.0) # interpreting the logit\n    else:\n      logit = 0.0\n      val = None\n    \n    reprs[id] = repr\n    \n    depth = 1\n    if abs_repr not in seen:\n      seen.add(abs_repr)\n      depths[abs_repr] = depth\n    \n    if id in selec:\n      contribute(repr,depth,(id in good),val,logit)\n\n  for id, (rule) in deriv:\n    if any((p not in reprs) for p in pars[id]):\n      continue\n    \n    sines = [s for p in pars[id] for s in reprs[p][1]]\n  \n    if len(sines) > 1:\n      continue\n  \n    if rule == 666:\n      my_pars = pars[id]\n      assert(len(my_pars) == 1)\n      if model:\n        getattr(model,\"new_avat\")(id,[-1,-1,-1,my_pars[0]])\n      repr = \"avat\"\n    else:\n      if model:\n        getattr(model,\"new_deriv{}\".format(rule))(id,[-1,-1,-1,-1,rule],pars[id])\n      repr = f\"rule_{rule}\"\n\n    if model:\n      logit = model(id) # calling forward\n      val = (logit >= 0.0) # interpreting the logit\n    else:\n      logit = 0.0\n      val = None\n\n    abs_repr = f\"{repr}({','.join([reprs[p][0] for p in pars[id]])})\"\n    \n    repr = (abs_repr,sines)\n    reprs[id] = repr\n\n    if abs_repr not in seen:\n      seen.add(abs_repr)\n      \n      depth = 1+max([depths[reprs[p][0]] for p in pars[id]])\n      depths[abs_repr] = depth\n    else:\n      depth = depths[abs_repr]\n      \n    if id in selec:\n      contribute(repr,depth,(id in good),val,logit)\n\nif __name__ == \"__main__\":\n  # Experiments with pytorch and torch script\n  # what can be learned from a super-simple TreeNN\n  # which distinguishes:\n  # 1) conj, user_ax, theory_ax_kind in the leaves\n  # 2) what inference leads to this in the tree nodes\n  #\n  # Load a torchscript model and a set of logs, passed in a file as the final argument,\n  # test the model on the logs (as if vampire was running) and report individual and average pos/neg rates\n  #\n  # To be called as in: ./model_visualizer.py raw_log_data*.pt torch_script_model.pt\n\n  prob_data_list = torch.load(sys.argv[1])\n  \n  if len(sys.argv) > 2:\n    model = torch.jit.load(sys.argv[2]) # always load a new model -- it contains the lookup tables for the particular model\n  else:\n    model = None\n  \n  seen = set() # what the repr already printed?\n  depths = {} # reprs -> its term depth\n\n  abs_repr_groups = defaultdict(dict) # abs_repr -> (sines -> (model_s_val,logic,pos_labels,neg_labels))\n\n  for (metainfo,(init,deriv,pars,selec,good,axioms)) in prob_data_list:\n    print(\"Opening\",metainfo)\n    print(\"has\",len(init),\"init,\",len(deriv),\"deriv\")\n    \n    reprs = {} # id -> clause_string_representation\n    eval_one(init,deriv,pars,selec,good,axioms)\n\n  print()\n  for abs_repr, group in sorted(abs_repr_groups.items(),key = lambda x : len(x[1])):\n    if len(group) == 1:\n      continue\n    print(abs_repr)\n    first = True\n    for sines, (models_val,models_logit,pos_labels,neg_labels) in sorted(group.items(),key=lambda x: -x[1][-2] / (x[1][-2] + x[1][-1]) ):\n      if first and pos_labels == 0:\n        print(\"Neg only\")\n        break\n      first = False\n      print(sines,pos_labels / (pos_labels+neg_labels), pos_labels, neg_labels )\n    print()\n\n  '''\n  for (depth,val),examples in sorted(hist.items(),reverse=True):\n    print((depth,val),len(examples),examples[:10] if depth <= 3 else \"\")\n  '''\n  '''\n  for (size,val),examples in sorted(size_hist.items(),reverse=True):\n    print((size,val),len(examples),examples[:10] if size <= 5 else \"\")\n  '''\n", "meta": {"hexsha": "3674b278f312511cc53cfc923544c551f64e1cd9", "size": 12536, "ext": "py", "lang": "Python", "max_stars_repo_path": "model_visualizer_raw.py", "max_stars_repo_name": "quickbeam123/deepire3.1", "max_stars_repo_head_hexsha": "f723e7be7cc6ee5f78ddd70a6169416858899350", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "model_visualizer_raw.py", "max_issues_repo_name": "quickbeam123/deepire3.1", "max_issues_repo_head_hexsha": "f723e7be7cc6ee5f78ddd70a6169416858899350", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model_visualizer_raw.py", "max_forks_repo_name": "quickbeam123/deepire3.1", "max_forks_repo_head_hexsha": "f723e7be7cc6ee5f78ddd70a6169416858899350", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7767220903, "max_line_length": 140, "alphanum_fraction": 0.7095564773, "include": true, "reason": "import numpy", "num_tokens": 3481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.2942149659744614, "lm_q1q2_score": 0.1539981001526413}}
{"text": "# Copyright 2014-2019 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Author: Samragni Banerjee <samragnibanerjee4@gmail.com>\n#         Alexander Sokolov <alexander.y.sokolov@gmail.com>\n#\n\n'''\nRestricted algebraic diagrammatic construction\n'''\nimport time\nimport numpy as np\nimport pyscf.ao2mo as ao2mo\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf.adc import radc_ao2mo\nfrom pyscf.adc import dfadc\nfrom pyscf import __config__\nfrom pyscf import df\nfrom pyscf import symm\n\ndef kernel(adc, nroots=1, guess=None, eris=None, verbose=None):\n\n    adc.method = adc.method.lower()\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n       raise NotImplementedError(adc.method)\n\n    cput0 = (time.clock(), time.time())\n    log = logger.Logger(adc.stdout, adc.verbose)\n    if adc.verbose >= logger.WARN:\n        adc.check_sanity()\n    adc.dump_flags()\n\n    if eris is None:\n        eris = adc.transform_integrals()\n\n    imds = adc.get_imds(eris)\n    matvec, diag = adc.gen_matvec(imds, eris)\n\n    guess = adc.get_init_guess(nroots, diag, ascending = True)\n\n    conv, adc.E, U = lib.linalg_helper.davidson_nosym1(lambda xs : [matvec(x) for x in xs], guess, diag, nroots=nroots, verbose=log, tol=adc.conv_tol, max_cycle=adc.max_cycle, max_space=adc.max_space,tol_residual=adc.tol_residual)\n\n    adc.U = np.array(U).T.copy()\n\n    if adc.compute_properties:\n        adc.P,adc.X = adc.get_properties(nroots)\n\n    nfalse = np.shape(conv)[0] - np.sum(conv)\n\n    str = (\"\\n*************************************************************\"\n           \"\\n            ADC calculation summary\"\n           \"\\n*************************************************************\")\n    logger.info(adc, str)\n\n    if nfalse >= 1:\n        logger.warn(adc, \"Davidson iterations for \" + str(nfalse) + \" root(s) not converged\\n\")\n\n    for n in range(nroots):\n        print_string = ('%s root %d  |  Energy (Eh) = %14.10f  |  Energy (eV) = %12.8f  ' % (adc.method, n, adc.E[n], adc.E[n]*27.2114))\n        if adc.compute_properties:\n            print_string += (\"|  Spec factors = %10.8f  \" % adc.P[n])\n        print_string += (\"|  conv = %s\" % conv[n])\n        logger.info(adc, print_string)\n\n    log.timer('ADC', *cput0)\n\n    return adc.E, adc.U, adc.P, adc.X\n\n\ndef compute_amplitudes_energy(myadc, eris, verbose=None):\n\n    t1, t2, myadc.imds.t2_1_vvvv = myadc.compute_amplitudes(eris)\n    e_corr = myadc.compute_energy(t2, eris)\n\n    return e_corr, t1, t2\n\n\ndef compute_amplitudes(myadc, eris):\n\n    cput0 = (time.clock(), time.time())\n    log = logger.Logger(myadc.stdout, myadc.verbose)\n\n    if myadc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(myadc.method)\n\n    nocc = myadc._nocc\n    nvir = myadc._nvir\n\n    eris_oooo = eris.oooo\n    eris_ovoo = eris.ovoo\n    eris_oovv = eris.oovv\n    eris_ovvo = eris.ovvo\n\n    # Compute first-order doubles t2 (tijab)\n\n    v2e_oovv = eris_ovvo[:].transpose(0,3,1,2).copy()\n\n    e = myadc.mo_energy\n    d_ij = e[:nocc][:,None] + e[:nocc]\n    d_ab = e[nocc:][:,None] + e[nocc:]\n\n    D2 = d_ij.reshape(-1,1) - d_ab.reshape(-1)\n    D2 = D2.reshape((nocc,nocc,nvir,nvir))\n\n    D1 = e[:nocc][:None].reshape(-1,1) - e[nocc:].reshape(-1)\n    D1 = D1.reshape((nocc,nvir))\n\n    t2_1 = v2e_oovv/D2\n    if not isinstance(eris.oooo, np.ndarray):\n        t2_1 = radc_ao2mo.write_dataset(t2_1)\n        \n    del v2e_oovv\n    del D2\n\n    cput0 = log.timer_debug1(\"Completed t2_1 amplitude calculation\", *cput0)\n\n    # Compute second-order singles t1 (tij)\n\n    if isinstance(eris.ovvv, type(None)):\n        chnk_size = radc_ao2mo.calculate_chunk_size(myadc)\n    else:\n        chnk_size = nocc\n    a = 0\n    t1_2 = np.zeros((nocc,nvir))\n\n    for p in range(0,nocc,chnk_size):\n        if getattr(myadc, 'with_df', None):\n            eris_ovvv = dfadc.get_ovvv_df(myadc, eris.Lov, eris.Lvv, p, chnk_size).reshape(-1,nvir,nvir,nvir)\n        else :\n            eris_ovvv = radc_ao2mo.unpack_eri_1(eris.ovvv, nvir)\n        k = eris_ovvv.shape[0]\n       \n        t1_2 += 0.5*lib.einsum('kdac,ikcd->ia',eris_ovvv,t2_1[:,a:a+k],optimize=True)\n        t1_2 -= 0.5*lib.einsum('kdac,kicd->ia',eris_ovvv,t2_1[a:a+k,:],optimize=True)\n        t1_2 -= 0.5*lib.einsum('kcad,ikcd->ia',eris_ovvv,t2_1[:,a:a+k],optimize=True)\n        t1_2 += 0.5*lib.einsum('kcad,kicd->ia',eris_ovvv,t2_1[a:a+k,:],optimize=True)\n\n        t1_2 += lib.einsum('kdac,ikcd->ia',eris_ovvv,t2_1[:,a:a+k],optimize=True)\n        del eris_ovvv\n        a += k\n\n    t1_2 -= 0.5*lib.einsum('lcki,klac->ia',eris_ovoo,t2_1[:],optimize=True)\n    t1_2 += 0.5*lib.einsum('lcki,lkac->ia',eris_ovoo,t2_1[:],optimize=True)\n    t1_2 -= 0.5*lib.einsum('kcli,lkac->ia',eris_ovoo,t2_1[:],optimize=True)\n    t1_2 += 0.5*lib.einsum('kcli,klac->ia',eris_ovoo,t2_1[:],optimize=True)\n    t1_2 -= lib.einsum('lcki,klac->ia',eris_ovoo,t2_1[:],optimize=True)\n\n    t1_2 = t1_2/D1\n\n    cput0 = log.timer_debug1(\"Completed t1_2 amplitude calculation\", *cput0)\n\n    t2_2 = None\n    t1_3 = None\n    t2_1_vvvv = None\n\n    if (myadc.method == \"adc(2)-x\" or myadc.method == \"adc(3)\"):\n\n    # Compute second-order doubles t2 (tijab)\n\n        eris_oooo = eris.oooo\n        eris_ovvo = eris.ovvo\n\n        if isinstance(eris.vvvv, np.ndarray):\n            eris_vvvv = eris.vvvv\n            temp = t2_1.reshape(nocc*nocc,nvir*nvir)\n            t2_1_vvvv = np.dot(temp,eris_vvvv.T).reshape(nocc,nocc,nvir,nvir)\n        elif isinstance(eris.vvvv, list):\n            t2_1_vvvv = contract_ladder(myadc,t2_1[:],eris.vvvv)\n        else:\n            t2_1_vvvv = contract_ladder(myadc,t2_1[:],eris.Lvv)\n\n        if not isinstance(eris.oooo, np.ndarray):\n            t2_1_vvvv = radc_ao2mo.write_dataset(t2_1_vvvv)\n\n        t2_2 = t2_1_vvvv[:].copy()\n\n        t2_2 += lib.einsum('kilj,klab->ijab',eris_oooo,t2_1[:],optimize=True)\n        t2_2 += lib.einsum('kcbj,kica->ijab',eris_ovvo,t2_1[:],optimize=True)\n        t2_2 -= lib.einsum('kcbj,ikca->ijab',eris_ovvo,t2_1[:],optimize=True)\n        t2_2 += lib.einsum('kcbj,ikac->ijab',eris_ovvo,t2_1[:],optimize=True)\n        t2_2 -= lib.einsum('kjbc,ikac->ijab',eris_oovv,t2_1[:],optimize=True)\n        t2_2 -= lib.einsum('kibc,kjac->ijab',eris_oovv,t2_1[:],optimize=True)\n        t2_2 -= lib.einsum('kjac,ikcb->ijab',eris_oovv,t2_1[:],optimize=True)\n        t2_2 += lib.einsum('kcai,kjcb->ijab',eris_ovvo,t2_1[:],optimize=True)\n        t2_2 -= lib.einsum('kcai,jkcb->ijab',eris_ovvo,t2_1[:],optimize=True)\n        t2_2 += lib.einsum('kcai,kjcb->ijab',eris_ovvo,t2_1[:],optimize=True)\n        t2_2 -= lib.einsum('kiac,kjcb->ijab',eris_oovv,t2_1[:],optimize=True)\n\n        D2 = d_ij.reshape(-1,1) - d_ab.reshape(-1)\n        D2 = D2.reshape((nocc,nocc,nvir,nvir))\n\n        t2_2 = t2_2/D2\n        if not isinstance(eris.oooo, np.ndarray):\n            t2_2 = radc_ao2mo.write_dataset(t2_2)\n        del D2\n\n    cput0 = log.timer_debug1(\"Completed t2_2 amplitude calculation\", *cput0)\n        \n    if (myadc.method == \"adc(3)\"):\n\n        eris_ovoo = eris.ovoo\n\n        t1_3 =  lib.einsum('d,ilad,ld->ia',e[nocc:],t2_1[:],t1_2,optimize=True)\n        t1_3 -= lib.einsum('d,liad,ld->ia',e[nocc:],t2_1[:],t1_2,optimize=True)\n        t1_3 += lib.einsum('d,ilad,ld->ia',e[nocc:],t2_1[:],t1_2,optimize=True)\n \n        t1_3 -= lib.einsum('l,ilad,ld->ia',e[:nocc],t2_1[:], t1_2,optimize=True)\n        t1_3 += lib.einsum('l,liad,ld->ia',e[:nocc],t2_1[:], t1_2,optimize=True)\n        t1_3 -= lib.einsum('l,ilad,ld->ia',e[:nocc],t2_1[:],t1_2,optimize=True)\n \n        t1_3 += 0.5*lib.einsum('a,ilad,ld->ia',e[nocc:],t2_1[:], t1_2,optimize=True)\n        t1_3 -= 0.5*lib.einsum('a,liad,ld->ia',e[nocc:],t2_1[:], t1_2,optimize=True)\n        t1_3 += 0.5*lib.einsum('a,ilad,ld->ia',e[nocc:],t2_1[:],t1_2,optimize=True)\n \n        t1_3 -= 0.5*lib.einsum('i,ilad,ld->ia',e[:nocc],t2_1[:], t1_2,optimize=True)\n        t1_3 += 0.5*lib.einsum('i,liad,ld->ia',e[:nocc],t2_1[:], t1_2,optimize=True)\n        t1_3 -= 0.5*lib.einsum('i,ilad,ld->ia',e[:nocc],t2_1[:],t1_2,optimize=True)\n \n        t1_3 += lib.einsum('ld,iadl->ia',t1_2,eris_ovvo,optimize=True)\n        t1_3 -= lib.einsum('ld,ladi->ia',t1_2,eris_ovvo,optimize=True)\n        t1_3 += lib.einsum('ld,iadl->ia',t1_2,eris_ovvo,optimize=True)\n \n        t1_3 += lib.einsum('ld,ldai->ia',t1_2,eris_ovvo ,optimize=True)\n        t1_3 -= lib.einsum('ld,liad->ia',t1_2,eris_oovv ,optimize=True)\n        t1_3 += lib.einsum('ld,ldai->ia',t1_2,eris_ovvo,optimize=True)\n \n        t1_3 -= 0.5*lib.einsum('lmad,mdli->ia',t2_2[:],eris_ovoo,optimize=True)\n        t1_3 += 0.5*lib.einsum('mlad,mdli->ia',t2_2[:],eris_ovoo,optimize=True)\n        t1_3 += 0.5*lib.einsum('lmad,ldmi->ia',t2_2[:],eris_ovoo,optimize=True)\n        t1_3 -= 0.5*lib.einsum('mlad,ldmi->ia',t2_2[:],eris_ovoo,optimize=True)\n        t1_3 -=     lib.einsum('lmad,mdli->ia',t2_2[:],eris_ovoo,optimize=True)\n \n        if isinstance(eris.ovvv, type(None)):\n            chnk_size = radc_ao2mo.calculate_chunk_size(myadc)\n        else :\n            chnk_size = nocc\n        a = 0\n\n        for p in range(0,nocc,chnk_size):\n            if getattr(myadc, 'with_df', None):\n                eris_ovvv = dfadc.get_ovvv_df(myadc, eris.Lov, eris.Lvv, p, chnk_size).reshape(-1,nvir,nvir,nvir)\n            else :\n                eris_ovvv = radc_ao2mo.unpack_eri_1(eris.ovvv, nvir)\n            k = eris_ovvv.shape[0]\n\n            t1_3 += 0.5*lib.einsum('ilde,lead->ia', t2_2[:,a:a+k],eris_ovvv,optimize=True)\n            t1_3 -= 0.5*lib.einsum('lide,lead->ia', t2_2[a:a+k],eris_ovvv,optimize=True)\n\n            t1_3 -= 0.5*lib.einsum('ilde,ldae->ia', t2_2[:,a:a+k],eris_ovvv,optimize=True)\n            t1_3 += 0.5*lib.einsum('lide,ldae->ia', t2_2[a:a+k],eris_ovvv,optimize=True)\n\n            t1_3 -= lib.einsum('ildf,mefa,lmde->ia',t2_1[:], eris_ovvv,  t2_1[:,a:a+k] ,optimize=True)\n            t1_3 += lib.einsum('ildf,mefa,mlde->ia',t2_1[:], eris_ovvv,  t2_1[a:a+k] ,optimize=True)\n            t1_3 += lib.einsum('lidf,mefa,lmde->ia',t2_1[:], eris_ovvv,  t2_1[:,a:a+k] ,optimize=True)\n            t1_3 -= lib.einsum('lidf,mefa,mlde->ia',t2_1[:], eris_ovvv,  t2_1[a:a+k] ,optimize=True)\n\n            t1_3 += lib.einsum('ildf,mafe,lmde->ia',t2_1[:], eris_ovvv,  t2_1[:,a:a+k] ,optimize=True)\n            t1_3 -= lib.einsum('ildf,mafe,mlde->ia',t2_1[:], eris_ovvv,  t2_1[a:a+k] ,optimize=True)\n            t1_3 -= lib.einsum('lidf,mafe,lmde->ia',t2_1[:], eris_ovvv,  t2_1[:,a:a+k] ,optimize=True)\n            t1_3 += lib.einsum('lidf,mafe,mlde->ia',t2_1[:], eris_ovvv,  t2_1[a:a+k] ,optimize=True)\n\n            t1_3 += lib.einsum('ilfd,mefa,mled->ia',  t2_1[:],eris_ovvv, t2_1[a:a+k],optimize=True)\n            t1_3 -= lib.einsum('ilfd,mafe,mled->ia',  t2_1[:],eris_ovvv, t2_1[a:a+k],optimize=True)\n\n            t1_3 += 0.5*lib.einsum('ilaf,mefd,lmde->ia',t2_1[:],eris_ovvv,t2_1[:,a:a+k],optimize=True)\n            t1_3 -= 0.5*lib.einsum('ilaf,mefd,mlde->ia',t2_1[:],eris_ovvv,t2_1[a:a+k],optimize=True)\n            t1_3 -= 0.5*lib.einsum('liaf,mefd,lmde->ia',t2_1[:],eris_ovvv,t2_1[:,a:a+k],optimize=True)\n            t1_3 += 0.5*lib.einsum('liaf,mefd,mlde->ia',t2_1[:],eris_ovvv,t2_1[a:a+k],optimize=True)\n\n            t1_3 -= 0.5*lib.einsum('ilaf,mdfe,lmde->ia',t2_1[:],eris_ovvv,t2_1[:,a:a+k],optimize=True)\n            t1_3 += 0.5*lib.einsum('ilaf,mdfe,mlde->ia',t2_1[:],eris_ovvv,t2_1[a:a+k],optimize=True)\n            t1_3 += 0.5*lib.einsum('liaf,mdfe,lmde->ia',t2_1[:],eris_ovvv,t2_1[:,a:a+k],optimize=True)\n            t1_3 -= 0.5*lib.einsum('liaf,mdfe,mlde->ia',t2_1[:],eris_ovvv,t2_1[a:a+k],optimize=True)\n\n            t1_3[a:a+k] += 0.5*lib.einsum('lmdf,iaef,lmde->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n            t1_3[a:a+k] -= 0.5*lib.einsum('lmdf,iaef,mlde->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n            t1_3[a:a+k] -= 0.5*lib.einsum('mldf,iaef,lmde->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n            t1_3[a:a+k] += 0.5*lib.einsum('mldf,iaef,mlde->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n\n            t1_3[a:a+k] -= 0.5*lib.einsum('lmdf,ifea,lmde->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n            t1_3[a:a+k] += 0.5*lib.einsum('lmdf,ifea,mlde->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n            t1_3[a:a+k] += 0.5*lib.einsum('mldf,ifea,lmde->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n            t1_3[a:a+k] -= 0.5*lib.einsum('mldf,ifea,mlde->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n\n            t1_3[a:a+k] += lib.einsum('mlfd,iaef,mled->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n            t1_3[a:a+k] -= lib.einsum('mlfd,ifea,mled->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n\n            t1_3[a:a+k] -= 0.25*lib.einsum('lmef,iedf,lmad->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n            t1_3[a:a+k] += 0.25*lib.einsum('lmef,iedf,mlad->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n            t1_3[a:a+k] += 0.25*lib.einsum('mlef,iedf,lmad->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n            t1_3[a:a+k] -= 0.25*lib.einsum('mlef,iedf,mlad->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n\n            t1_3[a:a+k] += 0.25*lib.einsum('lmef,ifde,lmad->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n            t1_3[a:a+k] -= 0.25*lib.einsum('lmef,ifde,mlad->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n            t1_3[a:a+k] -= 0.25*lib.einsum('mlef,ifde,lmad->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n            t1_3[a:a+k] += 0.25*lib.einsum('mlef,ifde,mlad->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n\n            t1_3 += 0.5*lib.einsum('ilaf,mefd,lmde->ia',t2_1[:],eris_ovvv,t2_1[:,a:a+k],optimize=True)\n            t1_3 -= 0.5*lib.einsum('ilaf,mefd,mlde->ia',t2_1[:],eris_ovvv,t2_1[a:a+k],optimize=True)\n\n            t1_3 -= 0.5*lib.einsum('ilaf,mdfe,lmde->ia',t2_1[:],eris_ovvv,t2_1[:,a:a+k],optimize=True)\n            t1_3 += 0.5*lib.einsum('ilaf,mdfe,mlde->ia',t2_1[:],eris_ovvv,t2_1[a:a+k],optimize=True)\n\n            t1_3 -= lib.einsum('ildf,mafe,mlde->ia',t2_1[:],eris_ovvv,t2_1[a:a+k],optimize=True)\n            t1_3 += lib.einsum('ilaf,mefd,mled->ia',t2_1[:],eris_ovvv,t2_1[a:a+k],optimize=True)\n\n            t1_3[a:a+k] += 0.5*lib.einsum('lmdf,iaef,lmde->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n            t1_3[a:a+k] -= 0.5*lib.einsum('lmdf,iaef,mlde->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n            t1_3[a:a+k] -= 0.5*lib.einsum('mldf,iaef,lmde->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n            t1_3[a:a+k] += 0.5*lib.einsum('mldf,iaef,mlde->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n\n            t1_3[a:a+k] += lib.einsum('lmdf,iaef,lmde->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n            t1_3[a:a+k] -= lib.einsum('lmef,iedf,lmad->ia',t2_1[:],eris_ovvv,t2_1[:],optimize=True)\n\n            t1_3 += lib.einsum('ilde,lead->ia',t2_2[:,a:a+k],eris_ovvv,optimize=True)\n\n            t1_3 -= lib.einsum('ildf,mefa,lmde->ia',t2_1[:],eris_ovvv, t2_1[:,a:a+k],optimize=True)\n            t1_3 += lib.einsum('lidf,mefa,lmde->ia',t2_1[:],eris_ovvv, t2_1[:,a:a+k],optimize=True)\n\n            t1_3 += lib.einsum('ilfd,mefa,lmde->ia',t2_1[:],eris_ovvv,t2_1[:,a:a+k] ,optimize=True)\n            t1_3 -= lib.einsum('ilfd,mefa,mlde->ia',t2_1[:],eris_ovvv,t2_1[a:a+k] ,optimize=True)\n\n            t1_3 += lib.einsum('ilaf,mefd,lmde->ia',t2_1[:],eris_ovvv,t2_1[:,a:a+k],optimize=True)\n            t1_3 -= lib.einsum('liaf,mefd,lmde->ia',t2_1[:],eris_ovvv,t2_1[:,a:a+k],optimize=True)\n\n            del eris_ovvv\n            a += k\n\n        t1_3 += 0.25*lib.einsum('inde,lamn,lmde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 -= 0.25*lib.einsum('inde,lamn,mlde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 -= 0.25*lib.einsum('nide,lamn,lmde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 += 0.25*lib.einsum('nide,lamn,mlde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 -= 0.25*lib.einsum('inde,maln,lmde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 += 0.25*lib.einsum('inde,maln,mlde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 += 0.25*lib.einsum('nide,maln,lmde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 -= 0.25*lib.einsum('nide,maln,mlde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 += lib.einsum('inde,lamn,lmde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n \n        t1_3 += 0.5 * lib.einsum('inad,lemn,lmde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 -= 0.5 * lib.einsum('inad,lemn,mlde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 -= 0.5 * lib.einsum('niad,lemn,lmde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 += 0.5 * lib.einsum('niad,lemn,mlde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n\n        t1_3 -= 0.5 * lib.einsum('inad,meln,lmde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 += 0.5 * lib.einsum('inad,meln,mlde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 += 0.5 * lib.einsum('niad,meln,lmde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 -= 0.5 * lib.einsum('niad,meln,mlde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n\n        t1_3 -= 0.5 * lib.einsum('inad,lemn,mlde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 += 0.5 * lib.einsum('niad,lemn,mlde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n\n        t1_3 -= 0.5 * lib.einsum('inad,meln,lmde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 += 0.5 * lib.einsum('niad,meln,lmde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n\n        t1_3 -= 0.5 * lib.einsum('inad,lemn,lmed->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 -= 0.5 * lib.einsum('inad,meln,mled->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n\n        t1_3 += 0.5 * lib.einsum('inad,lemn,lmde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 -= 0.5 * lib.einsum('inad,lemn,mlde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n\n        t1_3 -= 0.5 * lib.einsum('inad,meln,lmde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 += 0.5 * lib.einsum('inad,meln,mlde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n\n        t1_3 -= 0.5 * lib.einsum('lnde,ianm,lmde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 += 0.5 * lib.einsum('lnde,ianm,mlde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 += 0.5 * lib.einsum('nlde,ianm,lmde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 -= 0.5 * lib.einsum('nlde,ianm,mlde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n\n        t1_3 += 0.5 * lib.einsum('lnde,naim,lmde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 -= 0.5 * lib.einsum('lnde,naim,mlde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 -= 0.5 * lib.einsum('nlde,naim,lmde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 += 0.5 * lib.einsum('nlde,naim,mlde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n\n        t1_3 -= lib.einsum('nled,ianm,mled->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 += lib.einsum('nled,naim,mled->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n\n        t1_3 -= 0.5*lib.einsum('lnde,ianm,lmde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 += 0.5*lib.einsum('lnde,ianm,mlde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 += 0.5*lib.einsum('nlde,ianm,lmde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 -= 0.5*lib.einsum('nlde,ianm,mlde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n\n        t1_3 -= lib.einsum('lnde,ianm,lmde->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n\n        t1_3 -= lib.einsum('lnde,ienm,lmad->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 += lib.einsum('lnde,ienm,mlad->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 += lib.einsum('nlde,ienm,lmad->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 -= lib.einsum('nlde,ienm,mlad->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n\n        t1_3 += lib.einsum('lnde,neim,lmad->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 -= lib.einsum('lnde,neim,mlad->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 -= lib.einsum('nlde,neim,lmad->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 += lib.einsum('nlde,neim,mlad->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n\n        t1_3 += lib.einsum('lnde,neim,lmad->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 -= lib.einsum('lnde,neim,mlad->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n\n        t1_3 += lib.einsum('nled,ienm,mlad->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 -= lib.einsum('nled,neim,mlad->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 += lib.einsum('lned,ienm,lmad->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n\n        t1_3 -= lib.einsum('lnde,neim,mlad->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n        t1_3 += lib.einsum('nlde,neim,mlad->ia',t2_1[:],eris_ovoo,t2_1[:],optimize=True)\n\n        t1_3 = t1_3/D1\n\n    cput0 = log.timer_debug1(\"Completed amplitude calculation\", *cput0)\n\n    t1 = (t1_2, t1_3)\n    t2 = (t2_1, t2_2)\n\n    return t1, t2, t2_1_vvvv\n\n\ndef compute_energy(myadc, t2, eris):\n\n    cput0 = (time.clock(), time.time())\n    log = logger.Logger(myadc.stdout, myadc.verbose)\n    if myadc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(myadc.method)\n\n    nocc = myadc._nocc\n    nvir = myadc._nvir\n\n    eris_ovvo = eris.ovvo\n\n    t2_new  = t2[0][:].copy()\n\n    if (myadc.method == \"adc(3)\"):\n        t2_new += t2[1][:]\n\n    #Compute MP2 correlation energy\n\n    e_mp = 0.5 * lib.einsum('ijab,iabj', t2_new, eris_ovvo,optimize=True)\n    e_mp -= 0.5 * lib.einsum('ijab,ibaj', t2_new, eris_ovvo,optimize=True)\n    e_mp -= 0.5 * lib.einsum('jiab,iabj', t2_new, eris_ovvo,optimize=True)\n    e_mp += 0.5 * lib.einsum('jiab,ibaj', t2_new, eris_ovvo,optimize=True)\n    e_mp += lib.einsum('ijab,iabj', t2_new, eris_ovvo,optimize=True)\n\n    del t2_new\n    return e_mp\n\n\ndef contract_ladder(myadc,t_amp,vvvv):\n\n    log = logger.Logger(myadc.stdout, myadc.verbose)\n    nocc = myadc._nocc\n    nvir = myadc._nvir\n\n    t_amp = np.ascontiguousarray(t_amp.reshape(nocc*nocc,nvir*nvir).T)\n    t = np.zeros((nvir,nvir, nocc*nocc))\n    chnk_size = radc_ao2mo.calculate_chunk_size(myadc)\n\n    a = 0\n    if isinstance(vvvv, list):\n        for dataset in vvvv:\n             k = dataset.shape[0]\n             dataset = dataset[:].reshape(-1,nvir*nvir)\n             t[a:a+k] = np.dot(dataset,t_amp).reshape(-1,nvir,nocc*nocc)\n             a += k\n    elif getattr(myadc, 'with_df', None):\n        for p in range(0,nvir,chnk_size):\n            vvvv_p = dfadc.get_vvvv_df(myadc, vvvv, p, chnk_size)\n            k = vvvv_p.shape[0]\n            vvvv_p = vvvv_p.reshape(-1,nvir*nvir)\n            t[a:a+k] = np.dot(vvvv_p,t_amp).reshape(-1,nvir,nocc*nocc)\n            del vvvv_p\n            a += k\n    else :\n        raise Exception(\"Unknown vvvv type\") \n\n    del t_amp\n    t = np.ascontiguousarray(t.transpose(2,0,1)).reshape(nocc, nocc, nvir, nvir)\n\n    return t\n\n\ndef density_matrix(myadc, T=None):\n\n    if T is None:\n        T = RADCIP(myadc).get_trans_moments()\n\n    nocc = myadc._nocc\n    nvir = myadc._nvir\n\n    n_singles = nocc\n    n_doubles = nvir * nocc * nocc\n    ij_ind = np.tril_indices(nocc, k=-1)\n\n    s1 = 0\n    f1 = n_singles\n    s2 = f1\n    f2 = s2 + n_doubles\n\n    T_doubles = T[:,n_singles:]\n    T_doubles = T_doubles.reshape(-1,nvir,nocc,nocc)\n    T_doubles_transpose = T_doubles.transpose(0,1,3,2).copy()\n    T_bab = (2/3)*T_doubles + (1/3)*T_doubles_transpose\n\n    T_aaa = T_bab - T_bab.transpose(0,1,3,2)\n\n    T_a = T[:,s1:f1]\n    T_bab = T_bab.reshape(-1,n_doubles)\n    T_aaa = T_aaa.reshape(-1,n_doubles)\n\n    dm = 2 * np.dot(T_a,T_a.T) + np.dot(T_aaa, T_aaa.T) + 2 * np.dot(T_bab, T_bab.T)\n\n    return dm\n\n\ndef analyze(myadc):\n\n    str = (\"\\n*************************************************************\"\n          \"\\n           Eigenvector analysis summary\"                    \n          \"\\n*************************************************************\")\n    logger.info(myadc, str)\n\n    myadc.analyze_eigenvector()\n \n    if myadc.compute_properties:\n\n        str = (\"\\n*************************************************************\"\n               \"\\n            Spectroscopic factors analysis summary\"\n               \"\\n*************************************************************\")\n        logger.info(myadc, str)\n\n        myadc.analyze_spec_factor()\n\n\ndef compute_dyson_mo(myadc):\n     \n    X = myadc.X\n\n    if X is None:\n        nroots = myadc.U.shape[1]\n        P,X = myadc.get_properties(nroots)\n\n    nroots = X.shape[1]\n    dyson_mo = np.dot(myadc.mo_coeff,X)\n\n    return dyson_mo\n\n\nclass RADC(lib.StreamObject):\n    '''Ground state calculations\n\n    Attributes:\n        verbose : int\n            Print level.  Default value equals to :class:`Mole.verbose`\n        max_memory : float or int\n            Allowed memory in MB.  Default value equals to :class:`Mole.max_memory`\n        incore_complete : bool\n            Avoid all I/O. Default is False.\n        method : string\n            nth-order ADC method. Options are : ADC(2), ADC(2)-X, ADC(3). Default is ADC(2).\n\n            >>> mol = gto.M(atom = 'H 0 0 0; F 0 0 1.1', basis = 'ccpvdz')\n            >>> mf = scf.RHF(mol).run()\n            >>> myadc = adc.RADC(mf).run()\n\n    Saved results\n\n        e_corr : float\n            MPn correlation correction\n        e_tot : float\n            Total energy (HF + correlation)\n        t1, t2 :\n            T amplitudes t1[i,a], t2[i,j,a,b]  (i,j in occ, a,b in virt)\n    '''\n    incore_complete = getattr(__config__, 'adc_radc_RADC_incore_complete', False)\n    async_io = getattr(__config__, 'adc_radc_RADC_async_io', True)\n    blkmin = getattr(__config__, 'adc_radc_RADC_blkmin', 4)\n    memorymin = getattr(__config__, 'adc_radc_RADC_memorymin', 2000)\n    \n    def __init__(self, mf, frozen=0, mo_coeff=None, mo_occ=None):\n        from pyscf import gto\n        \n        if 'dft' in str(mf.__module__):\n            raise NotImplementedError('DFT reference for UADC')\n        \n        if mo_coeff  is None: mo_coeff  = mf.mo_coeff\n        if mo_occ    is None: mo_occ    = mf.mo_occ\n        \n        self.mol = mf.mol\n        self._scf = mf\n        self.verbose = self.mol.verbose\n        self.stdout = self.mol.stdout\n        self.max_memory = mf.max_memory\n\n        self.max_space = getattr(__config__, 'adc_radc_RADC_max_space', 12)\n        self.max_cycle = getattr(__config__, 'adc_radc_RADC_max_cycle', 50)\n        self.conv_tol = getattr(__config__, 'adc_radc_RADC_conv_tol', 1e-12)\n        self.tol_residual = getattr(__config__, 'adc_radc_RADC_tol_res', 1e-6)\n        self.scf_energy = mf.e_tot\n        \n        self.frozen = frozen\n        self.incore_complete = self.incore_complete or self.mol.incore_anyway\n        \n        self.mo_coeff = mo_coeff\n        self.mo_occ = mo_occ\n        self.e_corr = None\n        self.t1 = None\n        self.t2 = None\n        self.imds = lambda:None\n        self._nocc = mf.mol.nelectron//2\n        self._nmo = mo_coeff.shape[1]\n        self._nvir = self._nmo - self._nocc\n        self.mo_energy = mf.mo_energy\n        self.chkfile = mf.chkfile\n        self.method = \"adc(2)\"\n        self.method_type = \"ip\"\n        self.with_df = None\n        self.compute_properties = True\n        self.evec_print_tol = 0.1\n        self.spec_factor_print_tol = 0.1\n\n        self.E = None\n        self.U = None\n        self.P = None\n        self.X = None\n       \n        keys = set(('tol_residual','conv_tol', 'e_corr', 'method', 'mo_coeff', 'mol', 'mo_energy', 'max_memory', 'incore_complete', 'scf_energy', 'e_tot', 't1', 'frozen', 'chkfile', 'max_space', 't2', 'mo_occ', 'max_cycle'))\n\n        self._keys = set(self.__dict__.keys()).union(keys)\n    \n    compute_amplitudes = compute_amplitudes\n    compute_energy = compute_energy\n    transform_integrals = radc_ao2mo.transform_integrals_incore\n    make_rdm1 = density_matrix \n \n    def dump_flags(self, verbose=None):\n        logger.info(self, '')\n        logger.info(self, '******** %s ********', self.__class__)\n        logger.info(self, 'max_space = %d', self.max_space)\n        logger.info(self, 'max_cycle = %d', self.max_cycle)\n        logger.info(self, 'conv_tol = %s', self.conv_tol)\n        logger.info(self, 'max_memory %d MB (current use %d MB)',\n                    self.max_memory, lib.current_memory()[0])\n        return self\n    \n    def dump_flags_gs(self, verbose=None):\n        logger.info(self, '')\n        logger.info(self, '******** %s ********', self.__class__)\n        logger.info(self, 'max_memory %d MB (current use %d MB)',\n                    self.max_memory, lib.current_memory()[0])\n        return self\n    \n    def kernel_gs(self):\n        assert(self.mo_coeff is not None)\n        assert(self.mo_occ is not None)\n    \n        self.method = self.method.lower()\n        if self.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n            raise NotImplementedError(self.method)\n    \n        if self.verbose >= logger.WARN:\n            self.check_sanity()\n        self.dump_flags_gs()\n    \n        nmo = self._nmo\n        nao = self.mo_coeff.shape[0]\n        nmo_pair = nmo * (nmo+1) // 2\n        nao_pair = nao * (nao+1) // 2\n        mem_incore = (max(nao_pair**2, nmo**4) + nmo_pair**2) * 8/1e6\n        mem_now = lib.current_memory()[0]\n\n        if getattr(self, 'with_df', None) or getattr(self._scf, 'with_df', None):  \n           if getattr(self, 'with_df', None): \n               self.with_df = self.with_df\n           else :\n               self.with_df = self._scf.with_df\n\n           def df_transform():\n               return radc_ao2mo.transform_integrals_df(self)\n           self.transform_integrals = df_transform\n        elif (self._scf._eri is None or\n            (mem_incore+mem_now >= self.max_memory and not self.incore_complete)):\n           def outcore_transform():\n               return radc_ao2mo.transform_integrals_outcore(self)\n           self.transform_integrals = outcore_transform\n\n        eris = self.transform_integrals()\n        \n        self.e_corr, self.t1, self.t2 = compute_amplitudes_energy(self, eris=eris, verbose=self.verbose)\n        self._finalize()\n\n        return self.e_corr, self.t1, self.t2\n\n    def kernel(self, nroots=1, guess=None, eris=None):\n        assert(self.mo_coeff is not None)\n        assert(self.mo_occ is not None)\n    \n        self.method = self.method.lower()\n        if self.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n            raise NotImplementedError(self.method)\n    \n        if self.verbose >= logger.WARN:\n            self.check_sanity()\n        self.dump_flags_gs()\n    \n        nmo = self._nmo\n        nao = self.mo_coeff.shape[0]\n        nmo_pair = nmo * (nmo+1) // 2\n        nao_pair = nao * (nao+1) // 2\n        mem_incore = (max(nao_pair**2, nmo**4) + nmo_pair**2) * 8/1e6\n        mem_now = lib.current_memory()[0]\n\n        if getattr(self, 'with_df', None) or getattr(self._scf, 'with_df', None):  \n           if getattr(self, 'with_df', None): \n               self.with_df = self.with_df\n           else :\n               self.with_df = self._scf.with_df\n\n           def df_transform():\n              return radc_ao2mo.transform_integrals_df(self)\n           self.transform_integrals = df_transform\n        elif (self._scf._eri is None or\n            (mem_incore+mem_now >= self.max_memory and not self.incore_complete)):\n           def outcore_transform():\n               return radc_ao2mo.transform_integrals_outcore(self)\n           self.transform_integrals = outcore_transform\n\n        eris = self.transform_integrals() \n            \n        self.e_corr, self.t1, self.t2 = compute_amplitudes_energy(self, eris=eris, verbose=self.verbose)\n        self._finalize()\n\n        self.method_type = self.method_type.lower()\n        if(self.method_type == \"ea\"):\n            e_exc, v_exc, spec_fac, x, adc_es = self.ea_adc(nroots=nroots, guess=guess, eris=eris)\n\n        elif(self.method_type == \"ip\"):\n            e_exc, v_exc, spec_fac, x, adc_es = self.ip_adc(nroots=nroots, guess=guess, eris=eris)\n\n        else:\n            raise NotImplementedError(self.method_type)\n        self._adc_es = adc_es\n        return e_exc, v_exc, spec_fac, x\n\n    def _finalize(self):\n        '''Hook for dumping results and clearing up the object.'''\n        logger.note(self, 'E_corr = %.8f',\n                    self.e_corr)\n        return self\n    \n    def ea_adc(self, nroots=1, guess=None, eris=None):\n        adc_es = RADCEA(self)\n        e_exc, v_exc, spec_fac, x = adc_es.kernel(nroots, guess, eris)\n        return e_exc, v_exc, spec_fac, x, adc_es\n    \n    def ip_adc(self, nroots=1, guess=None, eris=None):\n        adc_es = RADCIP(self)\n        e_exc, v_exc, spec_fac, x = adc_es.kernel(nroots, guess, eris)\n        return e_exc, v_exc, spec_fac, x, adc_es\n\n    def density_fit(self, auxbasis=None, with_df = None):\n        if with_df is None:\n            self.with_df = df.DF(self._scf.mol)\n            self.with_df.max_memory = self.max_memory\n            self.with_df.stdout = self.stdout\n            self.with_df.verbose = self.verbose\n            if auxbasis is None:\n                self.with_df.auxbasis = self._scf.with_df.auxbasis\n            else :\n                self.with_df.auxbasis = auxbasis\n        else :\n            self.with_df = with_df\n        return self\n\n    def analyze(self):\n        self._adc_es.analyze()\n\n    def compute_dyson_mo(self):   \n        return self._adc_es.compute_dyson_mo() \n         \n\ndef get_imds_ea(adc, eris=None):\n\n    cput0 = (time.clock(), time.time())\n    log = logger.Logger(adc.stdout, adc.verbose)\n\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    t1 = adc.t1\n    t2 = adc.t2\n\n    t1_2 = t1[0]\n\n    eris_ovvo = eris.ovvo\n    nocc = adc._nocc\n    nvir = adc._nvir\n\n    e_occ = adc.mo_energy[:nocc].copy()\n    e_vir = adc.mo_energy[nocc:].copy()\n\n    idn_occ = np.identity(nocc)\n    idn_vir = np.identity(nvir)\n\n    if eris is None:\n        eris = adc.transform_integrals()\n\n    # a-b block\n    # Zeroth-order terms\n\n    M_ab = lib.einsum('ab,a->ab', idn_vir, e_vir)\n\n   # Second-order terms\n    t2_1 = t2[0][:]\n\n    M_ab +=  lib.einsum('l,lmad,lmbd->ab',e_occ ,t2_1, t2_1,optimize=True)\n    M_ab -=  lib.einsum('l,lmad,mlbd->ab',e_occ ,t2_1, t2_1,optimize=True)\n    M_ab -=  lib.einsum('l,mlad,lmbd->ab',e_occ ,t2_1, t2_1,optimize=True)\n    M_ab +=  lib.einsum('l,mlad,mlbd->ab',e_occ ,t2_1, t2_1,optimize=True)\n    M_ab +=  lib.einsum('l,lmad,lmbd->ab',e_occ,t2_1, t2_1,optimize=True)\n    M_ab +=  lib.einsum('l,mlad,mlbd->ab',e_occ,t2_1, t2_1,optimize=True)\n\n    M_ab -= 0.5 *  lib.einsum('d,lmad,lmbd->ab',e_vir,t2_1, t2_1,optimize=True)\n    M_ab += 0.5 *  lib.einsum('d,lmad,mlbd->ab',e_vir,t2_1, t2_1,optimize=True)\n    M_ab += 0.5 *  lib.einsum('d,mlad,lmbd->ab',e_vir,t2_1, t2_1,optimize=True)\n    M_ab -= 0.5 *  lib.einsum('d,mlad,mlbd->ab',e_vir,t2_1, t2_1,optimize=True)\n    M_ab -= 0.5 *  lib.einsum('d,lmad,lmbd->ab',e_vir,t2_1, t2_1,optimize=True)\n    M_ab -= 0.5 *  lib.einsum('d,mlad,mlbd->ab',e_vir,t2_1, t2_1,optimize=True)\n\n    M_ab_t = lib.einsum('lmad,lmbd->ab', t2_1,t2_1, optimize=True)\n    M_ab -= 1 *  lib.einsum('a,ab->ab',e_vir,M_ab_t,optimize=True)\n    M_ab -= 1 *  lib.einsum('b,ab->ab',e_vir,M_ab_t,optimize=True)\n\n    M_ab_t = lib.einsum('lmad,mlbd->ab', t2_1,t2_1, optimize=True)\n    M_ab += 0.5 *  lib.einsum('a,ab->ab',e_vir,M_ab_t,optimize=True)\n    M_ab += 0.5 *  lib.einsum('b,ab->ab',e_vir,M_ab_t,optimize=True)\n    del M_ab_t\n\n    M_ab -= 0.5 *  lib.einsum('lmad,lbdm->ab',t2_1, eris_ovvo,optimize=True)\n    M_ab += 0.5 *  lib.einsum('mlad,lbdm->ab',t2_1, eris_ovvo,optimize=True)\n    M_ab += 0.5 *  lib.einsum('lmad,ldbm->ab',t2_1, eris_ovvo,optimize=True)\n    M_ab -= 0.5 *  lib.einsum('mlad,ldbm->ab',t2_1, eris_ovvo,optimize=True)\n    M_ab -=        lib.einsum('lmad,lbdm->ab',t2_1, eris_ovvo,optimize=True)\n\n    M_ab -= 0.5 *  lib.einsum('lmbd,ladm->ab',t2_1, eris_ovvo,optimize=True)\n    M_ab += 0.5 *  lib.einsum('mlbd,ladm->ab',t2_1, eris_ovvo,optimize=True)\n    M_ab += 0.5 *  lib.einsum('lmbd,ldam->ab',t2_1, eris_ovvo,optimize=True)\n    M_ab -= 0.5 *  lib.einsum('mlbd,ldam->ab',t2_1, eris_ovvo,optimize=True)\n    M_ab -=        lib.einsum('lmbd,ladm->ab',t2_1, eris_ovvo,optimize=True)\n \n    del t2_1\n    cput0 = log.timer_debug1(\"Completed M_ab second-order terms ADC(2) calculation\", *cput0)\n\n    #Third-order terms\n\n    if(method =='adc(3)'):\n\n        eris_oovv = eris.oovv\n        eris_oooo = eris.oooo\n\n        if isinstance(eris.ovvv, type(None)):\n            chnk_size = radc_ao2mo.calculate_chunk_size(adc)\n        else :\n            chnk_size = nocc\n        a = 0\n        for p in range(0,nocc,chnk_size):\n            if getattr(adc, 'with_df', None):\n                eris_ovvv = dfadc.get_ovvv_df(adc, eris.Lov, eris.Lvv, p, chnk_size).reshape(-1,nvir,nvir,nvir)\n            else :\n                eris_ovvv = radc_ao2mo.unpack_eri_1(eris.ovvv, nvir)\n            k = eris_ovvv.shape[0]\n            M_ab += 4. * lib.einsum('ld,ldab->ab',t1_2[a:a+k], eris_ovvv,optimize=True)\n            M_ab -=  lib.einsum('ld,lbad->ab',t1_2[a:a+k], eris_ovvv,optimize=True)\n            M_ab -= lib.einsum('ld,ladb->ab',t1_2[a:a+k], eris_ovvv,optimize=True)\n            del eris_ovvv\n            a += k\n\n        cput0 = log.timer_debug1(\"Completed M_ab ovvv ADC(3) calculation\", *cput0)\n        t2_2 = t2[1][:]\n\n        M_ab -= 0.5 *  lib.einsum('lmad,lbdm->ab',t2_2, eris_ovvo,optimize=True)\n        M_ab += 0.5 *  lib.einsum('mlad,lbdm->ab',t2_2, eris_ovvo,optimize=True)\n        M_ab += 0.5 *  lib.einsum('lmad,ldbm->ab',t2_2, eris_ovvo,optimize=True)\n        M_ab -= 0.5 *  lib.einsum('mlad,ldbm->ab',t2_2, eris_ovvo,optimize=True)\n        M_ab -=        lib.einsum('lmad,lbdm->ab',t2_2, eris_ovvo,optimize=True)\n\n        M_ab -= 0.5 * lib.einsum('lmbd,ladm->ab',t2_2,eris_ovvo,optimize=True)\n        M_ab += 0.5 * lib.einsum('mlbd,ladm->ab',t2_2,eris_ovvo,optimize=True)\n        M_ab += 0.5 * lib.einsum('lmbd,ldam->ab',t2_2, eris_ovvo,optimize=True)\n        M_ab -= 0.5 * lib.einsum('mlbd,ldam->ab',t2_2, eris_ovvo,optimize=True)\n        M_ab -=       lib.einsum('lmbd,ladm->ab',t2_2,eris_ovvo,optimize=True)\n        t2_1 = t2[0][:]\n\n        M_ab += lib.einsum('l,lmbd,lmad->ab',e_occ, t2_1, t2_2, optimize=True)\n        M_ab -= lib.einsum('l,lmbd,mlad->ab',e_occ, t2_1, t2_2, optimize=True)\n        M_ab -= lib.einsum('l,mlbd,lmad->ab',e_occ, t2_1, t2_2, optimize=True)\n        M_ab += lib.einsum('l,mlbd,mlad->ab',e_occ, t2_1, t2_2, optimize=True)\n        M_ab += lib.einsum('l,lmbd,lmad->ab',e_occ, t2_1, t2_2, optimize=True)\n        M_ab += lib.einsum('l,mlbd,mlad->ab',e_occ, t2_1, t2_2, optimize=True)\n\n        M_ab += lib.einsum('l,lmad,lmbd->ab',e_occ, t2_1, t2_2, optimize=True)\n        M_ab -= lib.einsum('l,lmad,mlbd->ab',e_occ, t2_1, t2_2, optimize=True)\n        M_ab -= lib.einsum('l,mlad,lmbd->ab',e_occ, t2_1, t2_2, optimize=True)\n        M_ab += lib.einsum('l,mlad,mlbd->ab',e_occ, t2_1, t2_2, optimize=True)\n        M_ab += lib.einsum('l,lmad,lmbd->ab',e_occ, t2_1, t2_2, optimize=True)\n        M_ab += lib.einsum('l,mlad,mlbd->ab',e_occ, t2_1, t2_2, optimize=True)\n\n        M_ab -= 0.5*lib.einsum('d,lmbd,lmad->ab', e_vir, t2_1 ,t2_2, optimize=True)\n        M_ab += 0.5*lib.einsum('d,lmbd,mlad->ab', e_vir, t2_1 ,t2_2, optimize=True)\n        M_ab += 0.5*lib.einsum('d,mlbd,lmad->ab', e_vir, t2_1 ,t2_2, optimize=True)\n        M_ab -= 0.5*lib.einsum('d,mlbd,mlad->ab', e_vir, t2_1 ,t2_2, optimize=True)\n        M_ab -= 0.5*lib.einsum('d,lmbd,lmad->ab', e_vir, t2_1 ,t2_2, optimize=True)\n        M_ab -= 0.5*lib.einsum('d,mlbd,mlad->ab', e_vir, t2_1 ,t2_2, optimize=True)\n\n        M_ab -= 0.5*lib.einsum('d,lmad,lmbd->ab', e_vir, t2_1, t2_2, optimize=True)\n        M_ab += 0.5*lib.einsum('d,lmad,mlbd->ab', e_vir, t2_1, t2_2, optimize=True)\n        M_ab += 0.5*lib.einsum('d,mlad,lmbd->ab', e_vir, t2_1, t2_2, optimize=True)\n        M_ab -= 0.5*lib.einsum('d,mlad,mlbd->ab', e_vir, t2_1, t2_2, optimize=True)\n        M_ab -= 0.5*lib.einsum('d,lmad,lmbd->ab', e_vir, t2_1, t2_2, optimize=True)\n        M_ab -= 0.5*lib.einsum('d,mlad,mlbd->ab', e_vir, t2_1, t2_2, optimize=True)\n\n        M_ab_t = lib.einsum('lmbd,lmad->ab', t2_1,t2_2, optimize=True)\n        M_ab -= 1. * lib.einsum('a,ab->ab',e_vir, M_ab_t, optimize=True)\n        M_ab -= 1. * lib.einsum('a,ba->ab',e_vir, M_ab_t, optimize=True)\n        M_ab -= 1. * lib.einsum('b,ab->ab',e_vir, M_ab_t, optimize=True)\n        M_ab -= 1. * lib.einsum('b,ba->ab',e_vir, M_ab_t, optimize=True)\n        del M_ab_t\n\n        M_ab_t_1 = lib.einsum('lmbd,mlad->ab', t2_1,t2_2, optimize=True)\n        del t2_2\n        M_ab += 0.5 * lib.einsum('a,ab->ab',e_vir, M_ab_t_1, optimize=True)\n        M_ab += 0.5 * lib.einsum('a,ba->ab',e_vir, M_ab_t_1, optimize=True)\n        M_ab += 0.5 * lib.einsum('b,ab->ab',e_vir, M_ab_t_1, optimize=True)\n        M_ab += 0.5 * lib.einsum('b,ba->ab',e_vir, M_ab_t_1, optimize=True)\n        del M_ab_t_1\n\n        log.timer_debug1(\"Starting the small integrals  calculation\")\n        temp_t2_v_1 = lib.einsum('lned,mlbd->nemb',t2_1, t2_1,optimize=True)\n        M_ab -= lib.einsum('nemb,nmae->ab',temp_t2_v_1, eris_oovv, optimize=True)\n        M_ab -= lib.einsum('mbne,nmae->ab',temp_t2_v_1, eris_oovv, optimize=True)\n        M_ab += lib.einsum('nemb,maen->ab',temp_t2_v_1, eris_ovvo, optimize=True)\n        M_ab += lib.einsum('mbne,maen->ab',temp_t2_v_1, eris_ovvo, optimize=True)\n        M_ab += lib.einsum('nemb,neam->ab',temp_t2_v_1, eris_ovvo, optimize=True)\n        M_ab -= lib.einsum('name,nmeb->ab',temp_t2_v_1, eris_oovv, optimize=True)\n        M_ab -= lib.einsum('mena,nmeb->ab',temp_t2_v_1, eris_oovv, optimize=True)\n        M_ab += 2. * lib.einsum('name,nbem->ab',temp_t2_v_1, eris_ovvo, optimize=True)\n        M_ab += 2. * lib.einsum('mena,nbem->ab',temp_t2_v_1, eris_ovvo, optimize=True)\n        M_ab += lib.einsum('nbme,mean->ab',temp_t2_v_1, eris_ovvo, optimize=True)\n        del temp_t2_v_1\n\n        temp_t2_v_2 = lib.einsum('nled,mlbd->nemb',t2_1, t2_1,optimize=True)\n        M_ab += 2. * lib.einsum('nemb,nmae->ab',temp_t2_v_2, eris_oovv, optimize=True)\n        M_ab -= 2. * lib.einsum('nemb,maen->ab',temp_t2_v_2, eris_ovvo, optimize=True)\n        M_ab -= lib.einsum('nemb,neam->ab',temp_t2_v_2, eris_ovvo, optimize=True)\n        M_ab += 2. * lib.einsum('mena,nmeb->ab',temp_t2_v_2, eris_oovv, optimize=True)\n        M_ab -= 4. * lib.einsum('mena,nbem->ab',temp_t2_v_2, eris_ovvo, optimize=True)\n        M_ab -= lib.einsum('nemb,neam->ab',temp_t2_v_2, eris_ovvo, optimize=True)\n        del temp_t2_v_2\n\n        temp_t2_v_3 = lib.einsum('lned,lmbd->nemb',t2_1, t2_1,optimize=True)\n        M_ab -= lib.einsum('nemb,maen->ab',temp_t2_v_3, eris_ovvo, optimize=True)\n        M_ab += 2. * lib.einsum('nemb,nmae->ab',temp_t2_v_3, eris_oovv, optimize=True)\n        M_ab += 2. * lib.einsum('mena,nmeb->ab',temp_t2_v_3, eris_oovv, optimize=True)\n        M_ab -= lib.einsum('mena,nbem->ab',temp_t2_v_3, eris_ovvo, optimize=True)\n        del temp_t2_v_3\n\n        temp_t2_v_4 = lib.einsum('lnae,nmde->lmad',t2_1, eris_oovv,optimize=True)\n        M_ab -= lib.einsum('mlbd,lmad->ab',t2_1, temp_t2_v_4,optimize=True)\n        M_ab += 2. * lib.einsum('lmbd,lmad->ab',t2_1, temp_t2_v_4,optimize=True)\n        del temp_t2_v_4\n\n        temp_t2_v_5 = lib.einsum('nlae,nmde->lamd',t2_1, eris_oovv,optimize=True)\n        M_ab += 2. * lib.einsum('mlbd,lamd->ab',t2_1, temp_t2_v_5, optimize=True)\n        M_ab -= lib.einsum('lmbd,lamd->ab',t2_1, temp_t2_v_5, optimize=True)\n        del temp_t2_v_5\n\n        temp_t2_v_6 = lib.einsum('lnae,nedm->ladm',t2_1, eris_ovvo,optimize=True)\n        M_ab += 2. * lib.einsum('mlbd,ladm->ab',t2_1, temp_t2_v_6, optimize=True)\n        M_ab -= 4. * lib.einsum('lmbd,ladm->ab',t2_1, temp_t2_v_6, optimize=True)\n        del temp_t2_v_6\n\n        temp_t2_v_7 = lib.einsum('nlae,nedm->ladm',t2_1, eris_ovvo,optimize=True)\n        M_ab -= lib.einsum('mlbd,ladm->ab',t2_1, temp_t2_v_7, optimize=True)\n        M_ab += 2. * lib.einsum('lmbd,ladm->ab',t2_1, temp_t2_v_7, optimize=True)\n        del temp_t2_v_7\n\n        temp_t2_v_8 = lib.einsum('lned,mled->mn',t2_1, t2_1,optimize=True)\n        M_ab += 2.* lib.einsum('mn,nmab->ab',temp_t2_v_8, eris_oovv, optimize=True)\n        M_ab -= lib.einsum('mn,nbam->ab', temp_t2_v_8, eris_ovvo, optimize=True)\n        del temp_t2_v_8\n\n        temp_t2_v_9 = lib.einsum('nled,mled->mn',t2_1, t2_1,optimize=True)\n        M_ab -= 4.* lib.einsum('mn,nmab->ab',temp_t2_v_9, eris_oovv, optimize=True)\n        M_ab += 2. * lib.einsum('mn,nbam->ab',temp_t2_v_9, eris_ovvo, optimize=True)\n        del temp_t2_v_9\n\n        temp_t2_v_10 = lib.einsum('noad,nmol->mlad',t2_1, eris_oooo,optimize=True)\n        M_ab -= 0.25*lib.einsum('mlbd,mlad->ab',t2_1, temp_t2_v_10, optimize=True)\n        M_ab += 0.25*lib.einsum('lmbd,mlad->ab',t2_1, temp_t2_v_10, optimize=True)\n        M_ab += 0.25*lib.einsum('mlbd,lmad->ab',t2_1, temp_t2_v_10, optimize=True)\n        M_ab -= 0.25*lib.einsum('lmbd,lmad->ab',t2_1, temp_t2_v_10, optimize=True)\n        M_ab -= lib.einsum('mlbd,mlad->ab',t2_1, temp_t2_v_10, optimize=True)\n        del temp_t2_v_10\n\n        temp_t2_v_11 = lib.einsum('onad,nmol->mlad',t2_1, eris_oooo,optimize=True)\n        M_ab += 0.25*lib.einsum('mlbd,mlad->ab',t2_1, temp_t2_v_11, optimize=True)\n        M_ab -= 0.25*lib.einsum('lmbd,mlad->ab',t2_1, temp_t2_v_11, optimize=True)\n        M_ab -= 0.25*lib.einsum('mlbd,lmad->ab',t2_1, temp_t2_v_11, optimize=True)\n        M_ab += 0.25*lib.einsum('lmbd,lmad->ab',t2_1, temp_t2_v_11, optimize=True)\n        del temp_t2_v_11\n        log.timer_debug1(\"Completed M_ab ADC(3) small integrals calculation\")\n\n        log.timer_debug1(\"Starting M_ab vvvv ADC(3) calculation\")\n\n        if isinstance(eris.vvvv, np.ndarray):\n            temp_t2 = adc.imds.t2_1_vvvv\n            M_ab -= 0.25*lib.einsum('mlaf,mlbf->ab',t2_1, temp_t2, optimize=True)\n            M_ab += 0.25*lib.einsum('mlaf,lmbf->ab',t2_1, temp_t2, optimize=True)\n            M_ab += 0.25*lib.einsum('lmaf,mlbf->ab',t2_1, temp_t2, optimize=True)\n            M_ab -= 0.25*lib.einsum('lmaf,lmbf->ab',t2_1, temp_t2, optimize=True)\n            M_ab += 0.25*lib.einsum('mlaf,mlfb->ab',t2_1, temp_t2, optimize=True)\n            M_ab -= 0.25*lib.einsum('mlaf,lmfb->ab',t2_1, temp_t2, optimize=True)\n            M_ab -= 0.25*lib.einsum('lmaf,mlfb->ab',t2_1, temp_t2, optimize=True)\n            M_ab += 0.25*lib.einsum('lmaf,lmfb->ab',t2_1, temp_t2, optimize=True)\n            M_ab -= lib.einsum('mlaf,mlbf->ab',t2_1, temp_t2, optimize=True)\n\n            M_ab -= 0.25*lib.einsum('mlad,mlbd->ab', temp_t2, t2_1, optimize=True)\n            M_ab += 0.25*lib.einsum('mlad,lmbd->ab', temp_t2, t2_1, optimize=True)\n            M_ab += 0.25*lib.einsum('lmad,mlbd->ab', temp_t2, t2_1, optimize=True)\n            M_ab -= 0.25*lib.einsum('lmad,lmbd->ab', temp_t2, t2_1, optimize=True)\n            M_ab -= lib.einsum('mlad,mlbd->ab', temp_t2, t2_1, optimize=True)\n\n            M_ab += 0.25*lib.einsum('lmad,mlbd->ab',temp_t2, t2_1, optimize=True)\n            M_ab -= 0.25*lib.einsum('lmad,lmbd->ab',temp_t2, t2_1, optimize=True)\n            M_ab -= 0.25*lib.einsum('mlad,mlbd->ab',temp_t2, t2_1, optimize=True)\n            M_ab += 0.25*lib.einsum('mlad,lmbd->ab',temp_t2, t2_1, optimize=True)\n            del temp_t2\n\n            eris_vvvv =  eris.vvvv\n            eris_vvvv = eris_vvvv.reshape(nvir,nvir,nvir,nvir)\n            M_ab -= lib.einsum('mldf,mled,aebf->ab',t2_1, t2_1, eris_vvvv, optimize=True)\n            M_ab += lib.einsum('mldf,lmed,aebf->ab',t2_1, t2_1, eris_vvvv, optimize=True)\n            M_ab += lib.einsum('lmdf,mled,aebf->ab',t2_1, t2_1, eris_vvvv, optimize=True)\n            M_ab -= lib.einsum('lmdf,lmed,aebf->ab',t2_1, t2_1, eris_vvvv, optimize=True)\n            M_ab += 0.5*lib.einsum('mldf,mled,aefb->ab',t2_1, t2_1, eris_vvvv, optimize=True)\n            M_ab -= 0.5*lib.einsum('mldf,lmed,aefb->ab',t2_1, t2_1, eris_vvvv, optimize=True)\n            M_ab -= 0.5*lib.einsum('lmdf,mled,aefb->ab',t2_1, t2_1, eris_vvvv, optimize=True)\n            M_ab += 0.5*lib.einsum('lmdf,lmed,aefb->ab',t2_1, t2_1, eris_vvvv, optimize=True)\n            M_ab += 2.*lib.einsum('mlfd,mled,aebf->ab',t2_1, t2_1, eris_vvvv, optimize=True)\n            M_ab -= lib.einsum('mlfd,mled,aefb->ab',t2_1, t2_1, eris_vvvv, optimize=True)\n            eris_vvvv = eris_vvvv.reshape(nvir*nvir,nvir*nvir)\n\n        else:\n            temp_t2_vvvv = adc.imds.t2_1_vvvv[:]\n            M_ab -= 0.25*lib.einsum('mlaf,mlbf->ab',t2_1, temp_t2_vvvv, optimize=True)\n            M_ab += 0.25*lib.einsum('mlaf,lmbf->ab',t2_1, temp_t2_vvvv, optimize=True)\n            M_ab += 0.25*lib.einsum('lmaf,mlbf->ab',t2_1, temp_t2_vvvv, optimize=True)\n            M_ab -= 0.25*lib.einsum('lmaf,lmbf->ab',t2_1, temp_t2_vvvv, optimize=True)\n\n            M_ab += 0.25*lib.einsum('mlaf,mlfb->ab',t2_1, temp_t2_vvvv, optimize=True)\n            M_ab -= 0.25*lib.einsum('mlaf,lmfb->ab',t2_1, temp_t2_vvvv, optimize=True)\n            M_ab -= 0.25*lib.einsum('lmaf,mlfb->ab',t2_1, temp_t2_vvvv, optimize=True)\n            M_ab += 0.25*lib.einsum('lmaf,lmfb->ab',t2_1, temp_t2_vvvv, optimize=True)\n\n            M_ab -= lib.einsum('mlaf,mlbf->ab',t2_1, temp_t2_vvvv, optimize=True)\n\n            M_ab += 0.25*lib.einsum('lmad,mlbd->ab',temp_t2_vvvv, t2_1, optimize=True)\n            M_ab -= 0.25*lib.einsum('lmad,lmbd->ab',temp_t2_vvvv, t2_1, optimize=True)\n            M_ab -= 0.25*lib.einsum('mlad,mlbd->ab',temp_t2_vvvv, t2_1, optimize=True)\n            M_ab += 0.25*lib.einsum('mlad,lmbd->ab',temp_t2_vvvv, t2_1, optimize=True)\n\n            M_ab -= 0.25*lib.einsum('mlad,mlbd->ab', temp_t2_vvvv, t2_1, optimize=True)\n            M_ab += 0.25*lib.einsum('mlad,lmbd->ab', temp_t2_vvvv, t2_1, optimize=True)\n            M_ab += 0.25*lib.einsum('lmad,mlbd->ab', temp_t2_vvvv, t2_1, optimize=True)\n            M_ab -= 0.25*lib.einsum('lmad,lmbd->ab', temp_t2_vvvv, t2_1, optimize=True)\n            M_ab -= lib.einsum('mlad,mlbd->ab', temp_t2_vvvv, t2_1, optimize=True)\n            del temp_t2_vvvv\n\n            chnk_size = radc_ao2mo.calculate_chunk_size(adc)\n            a = 0 \n            temp = np.zeros((nvir,nvir))\n\n            if isinstance(eris.vvvv, list):\n                for dataset in eris.vvvv:\n                    k = dataset.shape[0]\n                    eris_vvvv = dataset[:].reshape(-1,nvir,nvir,nvir)\n                    temp[a:a+k] -= lib.einsum('mldf,mled,aebf->ab',t2_1, t2_1,  eris_vvvv, optimize=True)\n                    temp[a:a+k] += lib.einsum('mldf,lmed,aebf->ab',t2_1, t2_1,  eris_vvvv, optimize=True)\n                    temp[a:a+k] += lib.einsum('lmdf,mled,aebf->ab',t2_1, t2_1,  eris_vvvv, optimize=True)\n                    temp[a:a+k] -= lib.einsum('lmdf,lmed,aebf->ab',t2_1, t2_1,  eris_vvvv, optimize=True)\n                    temp[a:a+k] += 0.5*lib.einsum('mldf,mled,aefb->ab',t2_1, t2_1,  eris_vvvv, optimize=True)\n                    temp[a:a+k] -= 0.5*lib.einsum('mldf,lmed,aefb->ab',t2_1, t2_1,  eris_vvvv, optimize=True)\n                    temp[a:a+k] -= 0.5*lib.einsum('lmdf,mled,aefb->ab',t2_1, t2_1,  eris_vvvv, optimize=True)\n                    temp[a:a+k] += 0.5*lib.einsum('lmdf,lmed,aefb->ab',t2_1, t2_1,  eris_vvvv, optimize=True)\n                    temp[a:a+k] += 2.*lib.einsum('mlfd,mled,aebf->ab',t2_1, t2_1, eris_vvvv, optimize=True)\n                    temp[a:a+k] -= lib.einsum('mlfd,mled,aefb->ab',t2_1, t2_1, eris_vvvv, optimize=True)\n                    del eris_vvvv\n                    a += k\n            else :\n                for p in range(0,nvir,chnk_size):\n\n                    vvvv = dfadc.get_vvvv_df(adc, eris.Lvv, p, chnk_size).reshape(-1,nvir,nvir,nvir)\n                    k = vvvv.shape[0]\n                    temp[a:a+k] -= lib.einsum('mldf,mled,aebf->ab',t2_1, t2_1,  vvvv, optimize=True)\n                    temp[a:a+k] += lib.einsum('mldf,lmed,aebf->ab',t2_1, t2_1,  vvvv, optimize=True)\n                    temp[a:a+k] += lib.einsum('lmdf,mled,aebf->ab',t2_1, t2_1,  vvvv, optimize=True)\n                    temp[a:a+k] -= lib.einsum('lmdf,lmed,aebf->ab',t2_1, t2_1,  vvvv, optimize=True)\n                    temp[a:a+k] += 0.5*lib.einsum('mldf,mled,aefb->ab',t2_1, t2_1,  vvvv, optimize=True)\n                    temp[a:a+k] -= 0.5*lib.einsum('mldf,lmed,aefb->ab',t2_1, t2_1,  vvvv, optimize=True)\n                    temp[a:a+k] -= 0.5*lib.einsum('lmdf,mled,aefb->ab',t2_1, t2_1,  vvvv, optimize=True)\n                    temp[a:a+k] += 0.5*lib.einsum('lmdf,lmed,aefb->ab',t2_1, t2_1,  vvvv, optimize=True)\n                    temp[a:a+k] += 2.*lib.einsum('mlfd,mled,aebf->ab',t2_1, t2_1, vvvv, optimize=True)\n                    temp[a:a+k] -= lib.einsum('mlfd,mled,aefb->ab',t2_1, t2_1, vvvv, optimize=True)\n                    del vvvv\n                    a += k\n\n            M_ab += temp\n            del temp\n            del t2_1\n\n    cput0 = log.timer_debug1(\"Completed M_ab ADC(3) calculation\", *cput0)\n    return M_ab\n\n\ndef get_imds_ip(adc, eris=None):\n\n    cput0 = (time.clock(), time.time())\n    log = logger.Logger(adc.stdout, adc.verbose)\n\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    t1 = adc.t1\n    t2 = adc.t2\n\n    t1_2 = t1[0]\n\n    nocc = adc._nocc\n    nvir = adc._nvir\n\n    e_occ = adc.mo_energy[:nocc]\n    e_vir = adc.mo_energy[nocc:]\n\n    idn_occ = np.identity(nocc)\n    idn_vir = np.identity(nvir)\n\n    if eris is None:\n        eris = adc.transform_integrals()\n\n    eris_ovvo = eris.ovvo\n\n    # i-j block\n    # Zeroth-order terms\n\n    M_ij = lib.einsum('ij,j->ij', idn_occ ,e_occ)\n\n    # Second-order terms\n    t2_1 = t2[0][:]\n\n    M_ij +=  lib.einsum('d,ilde,jlde->ij',e_vir,t2_1, t2_1, optimize=True)\n    M_ij -=  lib.einsum('d,ilde,ljde->ij',e_vir,t2_1, t2_1, optimize=True)\n    M_ij -=  lib.einsum('d,lide,jlde->ij',e_vir,t2_1, t2_1, optimize=True)\n    M_ij +=  lib.einsum('d,lide,ljde->ij',e_vir,t2_1, t2_1, optimize=True)\n    M_ij +=  lib.einsum('d,ilde,jlde->ij',e_vir,t2_1, t2_1, optimize=True)\n    M_ij +=  lib.einsum('d,iled,jled->ij',e_vir,t2_1, t2_1, optimize=True)\n\n    M_ij -= 0.5 *  lib.einsum('l,ilde,jlde->ij',e_occ,t2_1, t2_1, optimize=True)\n    M_ij += 0.5 *  lib.einsum('l,ilde,ljde->ij',e_occ,t2_1, t2_1, optimize=True)\n    M_ij += 0.5 *  lib.einsum('l,lide,jlde->ij',e_occ,t2_1, t2_1, optimize=True)\n    M_ij -= 0.5 *  lib.einsum('l,lide,ljde->ij',e_occ,t2_1, t2_1, optimize=True)\n    M_ij -= 0.5*lib.einsum('l,ilde,jlde->ij',e_occ,t2_1, t2_1, optimize=True)\n    M_ij -= 0.5*lib.einsum('l,ilde,jlde->ij',e_occ,t2_1, t2_1, optimize=True)\n\n    M_ij_t = lib.einsum('ilde,jlde->ij', t2_1,t2_1, optimize=True)\n    M_ij -= lib.einsum('i,ij->ij',e_occ,M_ij_t, optimize=True)\n    M_ij -= lib.einsum('j,ij->ij',e_occ,M_ij_t, optimize=True)\n\n    M_ij_t = lib.einsum('ilde,ljde->ij', t2_1,t2_1, optimize=True)\n    M_ij += 0.5 * lib.einsum('i,ij->ij',e_occ,M_ij_t, optimize=True)\n    M_ij += 0.5 * lib.einsum('j,ij->ij',e_occ,M_ij_t, optimize=True)\n    del M_ij_t\n\n    M_ij += 0.5 *  lib.einsum('ilde,jdel->ij',t2_1, eris_ovvo,optimize=True)\n    M_ij -= 0.5 *  lib.einsum('lide,jdel->ij',t2_1, eris_ovvo,optimize=True)\n    M_ij -= 0.5 *  lib.einsum('ilde,jedl->ij',t2_1, eris_ovvo,optimize=True)\n    M_ij += 0.5 *  lib.einsum('lide,jedl->ij',t2_1, eris_ovvo,optimize=True)\n    M_ij += lib.einsum('ilde,jdel->ij',t2_1, eris_ovvo,optimize=True)\n\n    M_ij += 0.5 *  lib.einsum('jlde,idel->ij',t2_1, eris_ovvo,optimize=True)\n    M_ij -= 0.5 *  lib.einsum('ljde,idel->ij',t2_1, eris_ovvo,optimize=True)\n    M_ij -= 0.5 *  lib.einsum('jlde,ldei->ij',t2_1, eris_ovvo,optimize=True)\n    M_ij += 0.5 *  lib.einsum('ljde,ldei->ij',t2_1, eris_ovvo,optimize=True)\n    M_ij += lib.einsum('jlde,idel->ij',t2_1, eris_ovvo,optimize=True)\n\n    del t2_1\n    cput0 = log.timer_debug1(\"Completed M_ij second-order terms ADC(2) calculation\", *cput0)\n    # Third-order terms\n\n    if (method == \"adc(3)\"):\n      \n            eris_oovv = eris.oovv\n            eris_ovoo = eris.ovoo\n            eris_oooo = eris.oooo\n      \n            M_ij += lib.einsum('ld,ldji->ij',t1_2, eris_ovoo,optimize=True)\n            M_ij -= lib.einsum('ld,jdli->ij',t1_2, eris_ovoo,optimize=True)\n            M_ij += lib.einsum('ld,ldji->ij',t1_2, eris_ovoo,optimize=True)\n\n            M_ij += lib.einsum('ld,ldij->ij',t1_2, eris_ovoo,optimize=True)\n            M_ij -= lib.einsum('ld,idlj->ij',t1_2, eris_ovoo,optimize=True)\n            M_ij += lib.einsum('ld,ldij->ij',t1_2, eris_ovoo,optimize=True)\n            t2_2 = t2[1][:]\n\n            M_ij += 0.5* lib.einsum('ilde,jdel->ij',t2_2, eris_ovvo,optimize=True)\n            M_ij -= 0.5* lib.einsum('lide,jdel->ij',t2_2, eris_ovvo,optimize=True)\n            M_ij -= 0.5* lib.einsum('ilde,jedl->ij',t2_2, eris_ovvo,optimize=True)\n            M_ij += 0.5* lib.einsum('lide,jedl->ij',t2_2, eris_ovvo,optimize=True)\n            M_ij += lib.einsum('ilde,jdel->ij',t2_2, eris_ovvo,optimize=True)\n\n            M_ij += 0.5* lib.einsum('jlde,ledi->ij',t2_2, eris_ovvo,optimize=True)\n            M_ij -= 0.5* lib.einsum('ljde,ledi->ij',t2_2, eris_ovvo,optimize=True)\n            M_ij -= 0.5* lib.einsum('jlde,iedl->ij',t2_2, eris_ovvo,optimize=True)\n            M_ij += 0.5* lib.einsum('ljde,iedl->ij',t2_2, eris_ovvo,optimize=True)\n            M_ij += lib.einsum('jlde,ledi->ij',t2_2, eris_ovvo,optimize=True)\n            t2_1 = t2[0][:]\n\n            M_ij +=  lib.einsum('d,ilde,jlde->ij',e_vir,t2_1, t2_2,optimize=True)\n            M_ij -=  lib.einsum('d,ilde,ljde->ij',e_vir,t2_1, t2_2,optimize=True)\n            M_ij -=  lib.einsum('d,lide,jlde->ij',e_vir,t2_1, t2_2,optimize=True)\n            M_ij +=  lib.einsum('d,lide,ljde->ij',e_vir,t2_1, t2_2,optimize=True)\n            M_ij +=  lib.einsum('d,ilde,jlde->ij',e_vir,t2_1, t2_2,optimize=True)\n            M_ij +=  lib.einsum('d,iled,jled->ij',e_vir,t2_1, t2_2,optimize=True)\n\n            M_ij +=  lib.einsum('d,jlde,ilde->ij',e_vir,t2_1, t2_2,optimize=True)\n            M_ij -=  lib.einsum('d,jlde,lide->ij',e_vir,t2_1, t2_2,optimize=True)\n            M_ij -=  lib.einsum('d,ljde,ilde->ij',e_vir,t2_1, t2_2,optimize=True)\n            M_ij +=  lib.einsum('d,ljde,lide->ij',e_vir,t2_1, t2_2,optimize=True)\n            M_ij +=  lib.einsum('d,jlde,ilde->ij',e_vir,t2_1, t2_2,optimize=True)\n            M_ij +=  lib.einsum('d,jled,iled->ij',e_vir,t2_1, t2_2,optimize=True)\n\n            M_ij -= 0.5 *  lib.einsum('l,ilde,jlde->ij',e_occ,t2_1, t2_2,optimize=True)\n            M_ij += 0.5 *  lib.einsum('l,ilde,ljde->ij',e_occ,t2_1, t2_2,optimize=True)\n            M_ij += 0.5 *  lib.einsum('l,lide,jlde->ij',e_occ,t2_1, t2_2,optimize=True)\n            M_ij -= 0.5 *  lib.einsum('l,lide,ljde->ij',e_occ,t2_1, t2_2,optimize=True)\n            M_ij -= 0.5*lib.einsum('l,ilde,jlde->ij',e_occ,t2_1, t2_2,optimize=True)\n            M_ij -= 0.5*lib.einsum('l,ilde,jlde->ij',e_occ,t2_1, t2_2,optimize=True)\n\n            M_ij -= 0.5 *  lib.einsum('l,jlde,ilde->ij',e_occ,t2_1, t2_2,optimize=True)\n            M_ij += 0.5 *  lib.einsum('l,jlde,lide->ij',e_occ,t2_1, t2_2,optimize=True)\n            M_ij += 0.5 *  lib.einsum('l,ljde,ilde->ij',e_occ,t2_1, t2_2,optimize=True)\n            M_ij -= 0.5 *  lib.einsum('l,ljde,lide->ij',e_occ,t2_1, t2_2,optimize=True)\n            M_ij -= 0.5*lib.einsum('l,jlde,ilde->ij',e_occ,t2_1, t2_2,optimize=True)\n            M_ij -= 0.5*lib.einsum('l,jlde,ilde->ij',e_occ,t2_1, t2_2,optimize=True)\n\n            M_ij_t = lib.einsum('ilde,jlde->ij', t2_1,t2_2, optimize=True)\n            M_ij -= 1. * lib.einsum('i,ij->ij',e_occ, M_ij_t, optimize=True)\n            M_ij -= 1. * lib.einsum('i,ji->ij',e_occ, M_ij_t, optimize=True)\n            M_ij -= 1. * lib.einsum('j,ij->ij',e_occ, M_ij_t, optimize=True)\n            M_ij -= 1. * lib.einsum('j,ji->ij',e_occ, M_ij_t, optimize=True)\n            del M_ij_t\n\n            M_ij_t_1 = lib.einsum('ilde,ljde->ij', t2_1,t2_2, optimize=True)\n            del t2_2\n            M_ij += 0.5 * lib.einsum('i,ij->ij',e_occ, M_ij_t_1, optimize=True)\n            M_ij += 0.5 * lib.einsum('i,ji->ij',e_occ, M_ij_t_1, optimize=True)\n            M_ij += 0.5 * lib.einsum('j,ij->ij',e_occ, M_ij_t_1, optimize=True)\n            M_ij += 0.5 * lib.einsum('j,ji->ij',e_occ, M_ij_t_1, optimize=True)\n            del M_ij_t_1\n\n            temp_t2_vvvv = adc.imds.t2_1_vvvv[:]\n            M_ij += 0.25*lib.einsum('ilde,jlde->ij',t2_1, temp_t2_vvvv, optimize = True)\n            M_ij -= 0.25*lib.einsum('ilde,ljde->ij',t2_1, temp_t2_vvvv, optimize = True)\n            M_ij -= 0.25*lib.einsum('lide,jlde->ij',t2_1, temp_t2_vvvv, optimize = True)\n            M_ij += 0.25*lib.einsum('lide,ljde->ij',t2_1, temp_t2_vvvv, optimize = True)\n            M_ij -= 0.25*lib.einsum('ilde,jled->ij',t2_1, temp_t2_vvvv, optimize = True)\n            M_ij += 0.25*lib.einsum('ilde,ljed->ij',t2_1, temp_t2_vvvv, optimize = True)\n            M_ij += 0.25*lib.einsum('lide,jled->ij',t2_1, temp_t2_vvvv, optimize = True)\n            M_ij -= 0.25*lib.einsum('lide,ljed->ij',t2_1, temp_t2_vvvv, optimize = True)\n            M_ij +=lib.einsum('ilde,jlde->ij',t2_1, temp_t2_vvvv, optimize = True)\n            del temp_t2_vvvv\n\n            log.timer_debug1(\"Starting the small integrals  calculation\")\n            temp_t2_v_1 = lib.einsum('lmde,jldf->mejf',t2_1, t2_1,optimize=True)\n            M_ij -=  2 * lib.einsum('mejf,mefi->ij',temp_t2_v_1, eris_ovvo,optimize = True)\n            M_ij -=  2 * lib.einsum('jfme,mefi->ij',temp_t2_v_1, eris_ovvo,optimize = True)\n            M_ij +=  lib.einsum('mejf,mife->ij',temp_t2_v_1, eris_oovv,optimize = True)\n            M_ij +=  lib.einsum('jfme,mife->ij',temp_t2_v_1, eris_oovv,optimize = True)\n            M_ij -=  2 * lib.einsum('meif,mefj->ij',temp_t2_v_1, eris_ovvo ,optimize = True)\n            M_ij -=  2 * lib.einsum('ifme,mefj->ij',temp_t2_v_1, eris_ovvo ,optimize = True)\n            M_ij +=  lib.einsum('meif,mjfe->ij',temp_t2_v_1, eris_oovv ,optimize = True)\n            M_ij +=  lib.einsum('ifme,mjfe->ij',temp_t2_v_1, eris_oovv ,optimize = True)\n            del temp_t2_v_1        \n\n            temp_t2_v_2 = lib.einsum('lmde,ljdf->mejf',t2_1, t2_1,optimize=True)\n            M_ij +=  4 * lib.einsum('mejf,mefi->ij',temp_t2_v_2, eris_ovvo,optimize = True)\n            M_ij +=  4 * lib.einsum('meif,mefj->ij',temp_t2_v_2, eris_ovvo,optimize = True)\n            M_ij -=  2 * lib.einsum('meif,mjfe->ij',temp_t2_v_2, eris_oovv,optimize = True)\n            M_ij -=  2 * lib.einsum('mejf,mife->ij',temp_t2_v_2, eris_oovv,optimize = True)\n            del temp_t2_v_2        \n\n            temp_t2_v_3 = lib.einsum('mlde,jldf->mejf',t2_1, t2_1,optimize=True)\n            M_ij += lib.einsum('mejf,mefi->ij',temp_t2_v_3, eris_ovvo,optimize = True)\n            M_ij += lib.einsum('meif,mefj->ij',temp_t2_v_3, eris_ovvo,optimize = True)\n            M_ij -= 2 *lib.einsum('meif,mjfe->ij',temp_t2_v_3, eris_oovv,optimize = True)\n            M_ij -= 2 * lib.einsum('mejf,mife->ij',temp_t2_v_3, eris_oovv,optimize = True)\n            del temp_t2_v_3        \n\n            temp_t2_v_4 = lib.einsum('ilde,lmfe->idmf',t2_1, eris_oovv,optimize=True)\n            M_ij -= 2 * lib.einsum('idmf,jmdf->ij',temp_t2_v_4, t2_1, optimize = True)\n            M_ij += lib.einsum('idmf,mjdf->ij',temp_t2_v_4, t2_1, optimize = True)\n            del temp_t2_v_4\n\n            temp_t2_v_5 = lib.einsum('lide,lmfe->idmf',t2_1, eris_oovv,optimize=True)\n            M_ij += lib.einsum('idmf,jmdf->ij',temp_t2_v_5, t2_1, optimize = True)\n            M_ij -= 2 * lib.einsum('idmf,mjdf->ij',temp_t2_v_5, t2_1, optimize = True)\n            del temp_t2_v_5\n\n            temp_t2_v_6 = lib.einsum('ilde,lefm->idfm',t2_1, eris_ovvo,optimize=True)\n            M_ij += 4 * lib.einsum('idfm,jmdf->ij',temp_t2_v_6, t2_1,optimize = True)\n            M_ij -= 2 * lib.einsum('idfm,mjdf->ij',temp_t2_v_6, t2_1,optimize = True)\n            del temp_t2_v_6\n\n            temp_t2_v_7 = lib.einsum('lide,lefm->idfm',t2_1, eris_ovvo,optimize=True)\n            M_ij -= 2 * lib.einsum('idfm,jmdf->ij',temp_t2_v_7, t2_1,optimize = True)\n            M_ij += lib.einsum('idfm,mjdf->ij',temp_t2_v_7, t2_1,optimize = True)\n            del temp_t2_v_7\n\n            temp_t2_v_8 = lib.einsum('lmdf,lmde->fe',t2_1, t2_1,optimize=True)\n            M_ij += 3 *lib.einsum('fe,jief->ij',temp_t2_v_8, eris_oovv, optimize = True)\n            M_ij -= 1.5 *lib.einsum('fe,jfei->ij',temp_t2_v_8, eris_ovvo, optimize = True)\n            M_ij +=   lib.einsum('ef,jief->ij',temp_t2_v_8, eris_oovv, optimize = True)\n            M_ij -= 0.5 * lib.einsum('ef,jfei->ij',temp_t2_v_8, eris_ovvo, optimize = True)\n            del temp_t2_v_8\n\n            temp_t2_v_9 = lib.einsum('lmdf,mlde->fe',t2_1, t2_1,optimize=True)\n            M_ij -= 1.0 * lib.einsum('fe,jief->ij',temp_t2_v_9, eris_oovv, optimize = True)\n            M_ij -= 1.0 * lib.einsum('ef,jief->ij',temp_t2_v_9, eris_oovv, optimize = True)\n            M_ij += 0.5 * lib.einsum('fe,jfei->ij',temp_t2_v_9, eris_ovvo, optimize = True)\n            M_ij += 0.5 * lib.einsum('ef,jfei->ij',temp_t2_v_9, eris_ovvo, optimize = True)\n            del temp_t2_v_9\n\n            temp_t2_v_10 = lib.einsum('lnde,lmde->nm',t2_1, t2_1,optimize=True)\n            M_ij -= 3.0 * lib.einsum('nm,jinm->ij',temp_t2_v_10, eris_oooo, optimize = True)\n            M_ij -= 1.0 * lib.einsum('mn,jinm->ij',temp_t2_v_10, eris_oooo, optimize = True)\n            M_ij += 1.5 * lib.einsum('nm,jmni->ij',temp_t2_v_10, eris_oooo, optimize = True)\n            M_ij += 0.5 * lib.einsum('mn,jmni->ij',temp_t2_v_10, eris_oooo, optimize = True)\n            del temp_t2_v_10\n\n            temp_t2_v_11 = lib.einsum('lnde,mlde->nm',t2_1, t2_1,optimize=True)\n            M_ij += 1.0 * lib.einsum('nm,jinm->ij',temp_t2_v_11, eris_oooo, optimize = True)\n            M_ij -= 0.5 * lib.einsum('nm,jmni->ij',temp_t2_v_11, eris_oooo, optimize = True)\n            M_ij -= 0.5 * lib.einsum('mn,jmni->ij',temp_t2_v_11, eris_oooo, optimize = True)\n            M_ij += 1.0 * lib.einsum('mn,jinm->ij',temp_t2_v_11, eris_oooo, optimize = True)\n            del temp_t2_v_11\n\n            temp_t2_v_12 = lib.einsum('inde,lmde->inlm',t2_1, t2_1,optimize=True)\n            M_ij += 1.25 * lib.einsum('inlm,jlnm->ij',temp_t2_v_12, eris_oooo, optimize = True)\n            M_ij += 0.25 * lib.einsum('lmin,jlnm->ij',temp_t2_v_12, eris_oooo, optimize = True)\n            M_ij -= 0.25 * lib.einsum('inlm,jmnl->ij',temp_t2_v_12, eris_oooo, optimize = True)\n            M_ij -= 0.25 * lib.einsum('lmin,jmnl->ij',temp_t2_v_12, eris_oooo, optimize = True)\n \n            M_ij += 0.25 * lib.einsum('inlm,jlnm->ji',temp_t2_v_12, eris_oooo, optimize = True)\n            M_ij -= 0.25 * lib.einsum('inlm,lnmj->ji',temp_t2_v_12, eris_oooo, optimize = True)\n            M_ij += 1.00 * lib.einsum('inlm,ljmn->ji',temp_t2_v_12, eris_oooo, optimize = True)\n            M_ij -= 0.25 * lib.einsum('lmin,lnmj->ji',temp_t2_v_12, eris_oooo, optimize = True)\n            M_ij += 0.25 * lib.einsum('lmin,ljmn->ji',temp_t2_v_12, eris_oooo, optimize = True)\n            del temp_t2_v_12\n\n            temp_t2_v_13 = lib.einsum('inde,mlde->inml',t2_1, t2_1,optimize=True)\n            M_ij -= 0.25 * lib.einsum('inml,jlnm->ij',temp_t2_v_13, eris_oooo, optimize = True)\n            M_ij -= 0.25 * lib.einsum('mlin,jlnm->ij',temp_t2_v_13, eris_oooo, optimize = True)\n            M_ij += 0.25 * lib.einsum('inml,jmnl->ij',temp_t2_v_13, eris_oooo, optimize = True)\n            M_ij += 0.25 * lib.einsum('mlin,jmnl->ij',temp_t2_v_13, eris_oooo, optimize = True)\n\n            M_ij -= 0.25 * lib.einsum('inml,jlnm->ji',temp_t2_v_13, eris_oooo, optimize = True)\n            M_ij += 0.25 * lib.einsum('inml,lnmj->ji',temp_t2_v_13, eris_oooo, optimize = True)\n\n            M_ij -= 0.25 * lib.einsum('inml,ljmn->ji',temp_t2_v_13, eris_oooo, optimize = True)\n            M_ij += 0.25 * lib.einsum('inml,lnmj->ji',temp_t2_v_13, eris_oooo, optimize = True)\n            del temp_t2_v_13\n            del t2_1\n\n    cput0 = log.timer_debug1(\"Completed M_ij ADC(n) calculation\", *cput0)\n    return M_ij\n\n\ndef ea_adc_diag(adc,M_ab=None,eris=None):\n\n    log = logger.Logger(adc.stdout, adc.verbose)\n\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    if M_ab is None:\n        M_ab = adc.get_imds()\n\n    nocc = adc._nocc\n    nvir = adc._nvir\n\n    n_singles = nvir\n    n_doubles = nocc * nvir * nvir\n\n    dim = n_singles + n_doubles\n\n    e_occ = adc.mo_energy[:nocc]\n    e_vir = adc.mo_energy[nocc:]\n\n    idn_occ = np.identity(nocc)\n    idn_vir = np.identity(nvir)\n\n    s1 = 0\n    f1 = n_singles\n    s2 = f1\n    f2 = s2 + n_doubles\n\n    d_ab = e_vir[:,None] + e_vir\n    d_i = e_occ[:,None]\n    D_n = -d_i + d_ab.reshape(-1)\n    D_iab = D_n.reshape(-1)\n\n    diag = np.zeros(dim)\n\n    # Compute precond in p1-p1 block\n\n    M_ab_diag = np.diagonal(M_ab)\n    diag[s1:f1] = M_ab_diag.copy()\n\n    # Compute precond in 2p1h-2p1h block\n\n    diag[s2:f2] = D_iab\n    del D_iab\n\n#    ###### Additional terms for the preconditioner ####\n#\n#    if (method == \"adc(2)-x\" or method == \"adc(3)\"):\n#\n#        if eris is None:\n#            eris = adc.transform_integrals()\n#\n#        #TODO Implement this for out-of-core and density-fitted algorithms\n#        if isinstance(eris.vvvv, np.ndarray):\n#\n#            eris_oovv = eris.oovv\n#            eris_ovvo = eris.ovvo\n#            eris_vvvv = eris.vvvv\n#\n#            temp = np.zeros((nocc, eris_vvvv.shape[0]))\n#            temp[:] += np.diag(eris_vvvv)\n#            diag[s2:f2] += temp.reshape(-1)\n#\n#            eris_ovov_p = np.ascontiguousarray(eris_oovv[:].transpose(0,2,1,3))\n#            eris_ovov_p = eris_ovov_p.reshape(nocc*nvir, nocc*nvir)\n#\n#            temp = np.zeros((nvir, nocc, nvir))\n#            temp[:] += np.diagonal(eris_ovov_p).reshape(nocc, nvir)\n#            temp = np.ascontiguousarray(temp.transpose(1,0,2))\n#            diag[s2:f2] += -temp.reshape(-1)\n#\n#            eris_ovov_p = np.ascontiguousarray(eris_oovv[:].transpose(0,2,1,3))\n#            eris_ovov_p = eris_ovov_p.reshape(nocc*nvir, nocc*nvir)\n#\n#            temp = np.zeros((nvir, nocc, nvir))\n#            temp[:] += np.diagonal(eris_ovov_p).reshape(nocc, nvir)\n#            temp = np.ascontiguousarray(temp.transpose(1,2,0))\n#            diag[s2:f2] += -temp.reshape(-1)\n#        else :\n#           raise Exception(\"Precond not available for out-of-core and density-fitted algo\")\n\n    log.timer_debug1(\"Completed ea_diag calculation\")\n    return diag\n\n\ndef ip_adc_diag(adc,M_ij=None,eris=None):\n   \n    log = logger.Logger(adc.stdout, adc.verbose)\n\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    if M_ij is None:\n        M_ij = adc.get_imds()\n\n    nocc = adc._nocc\n    nvir = adc._nvir\n\n    n_singles = nocc\n    n_doubles = nvir * nocc * nocc\n\n    dim = n_singles + n_doubles\n\n    e_occ = adc.mo_energy[:nocc]\n    e_vir = adc.mo_energy[nocc:]\n\n    idn_occ = np.identity(nocc)\n    idn_vir = np.identity(nvir)\n\n    s1 = 0\n    f1 = n_singles\n    s2 = f1\n    f2 = s2 + n_doubles\n\n    d_ij = e_occ[:,None] + e_occ\n    d_a = e_vir[:,None]\n    D_n = -d_a + d_ij.reshape(-1)\n    D_aij = D_n.reshape(-1)\n\n    diag = np.zeros(dim)\n\n    # Compute precond in h1-h1 block\n    M_ij_diag = np.diagonal(M_ij)\n    diag[s1:f1] = M_ij_diag.copy()\n\n    # Compute precond in 2p1h-2p1h block\n\n    diag[s2:f2] = D_aij.copy()\n\n#    ###### Additional terms for the preconditioner ####\n#    if (method == \"adc(2)-x\" or method == \"adc(3)\"):\n#\n#        if eris is None:\n#            eris = adc.transform_integrals()\n#\n#        if isinstance(eris.vvvv, np.ndarray):\n#\n#            eris_oooo = eris.oooo\n#            eris_oovv = eris.oovv\n#            eris_ovvo = eris.ovvo\n#\n#            eris_oooo_p = np.ascontiguousarray(eris_oooo.transpose(0,2,1,3))\n#            eris_oooo_p = eris_oooo_p.reshape(nocc*nocc, nocc*nocc)\n#  \n#            temp = np.zeros((nvir, eris_oooo_p.shape[0]))\n#            temp[:] += np.diag(eris_oooo_p)\n#            diag[s2:f2] += -temp.reshape(-1)\n#\n#            eris_ovov_p = np.ascontiguousarray(eris_oovv.transpose(0,2,1,3)) \n#            eris_ovov_p = eris_ovov_p.reshape(nocc*nvir, nocc*nvir)\n#\n#            temp = np.zeros((nocc, nocc, nvir))\n#            temp[:] += np.diagonal(eris_ovov_p).reshape(nocc, nvir)\n#            temp = np.ascontiguousarray(temp.transpose(2,1,0))\n#            diag[s2:f2] += temp.reshape(-1)\n#\n#            eris_ovov_p = np.ascontiguousarray(eris_oovv.transpose(0,2,1,3)) \n#            eris_ovov_p = eris_ovov_p.reshape(nocc*nvir, nocc*nvir)\n#\n#            temp = np.zeros((nocc, nocc, nvir))\n#            temp[:] += np.diagonal(eris_ovov_p).reshape(nocc, nvir)\n#            temp = np.ascontiguousarray(temp.transpose(2,0,1))\n#            diag[s2:f2] += temp.reshape(-1)\n#        else :\n#            raise Exception(\"Precond not available for out-of-core and density-fitted algo\")\n\n    diag = -diag\n    log.timer_debug1(\"Completed ea_diag calculation\")\n\n    return diag\n\n\ndef ea_contract_r_vvvv(myadc,r2,vvvv):\n\n    nocc = myadc._nocc\n    nvir = myadc._nvir\n\n    r2_vvvv = np.zeros((nocc,nvir,nvir))\n    r2 = np.ascontiguousarray(r2.reshape(nocc,-1))\n    chnk_size = radc_ao2mo.calculate_chunk_size(myadc)\n\n    a = 0\n    if isinstance(vvvv, list):\n        for dataset in vvvv:\n             k = dataset.shape[0]\n             dataset = dataset[:].reshape(-1,nvir*nvir)\n             r2_vvvv[:,a:a+k] = np.dot(r2,dataset.T).reshape(nocc,-1,nvir)\n             del dataset\n             a += k\n    elif getattr(myadc, 'with_df', None):\n        for p in range(0,nvir,chnk_size):\n            vvvv_p = dfadc.get_vvvv_df(myadc, vvvv, p, chnk_size)\n            k = vvvv_p.shape[0]\n            vvvv_p = vvvv_p.reshape(-1,nvir*nvir)\n            r2_vvvv[:,a:a+k] = np.dot(r2,vvvv_p.T).reshape(nocc,-1,nvir)\n            del vvvv_p\n            a += k\n    else :\n        raise Exception(\"Unknown vvvv type\") \n\n    r2_vvvv = r2_vvvv.reshape(-1)\n\n    return r2_vvvv\n\n\ndef ea_adc_matvec(adc, M_ab=None, eris=None):\n\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    t1_2 = adc.t1[0]\n\n    nocc = adc._nocc\n    nvir = adc._nvir\n\n    ab_ind = np.tril_indices(nvir, k=-1)\n\n    n_singles = nvir\n    n_doubles = nocc * nvir * nvir\n\n    dim = n_singles + n_doubles\n\n    e_occ = adc.mo_energy[:nocc]\n    e_vir = adc.mo_energy[nocc:]\n\n    idn_occ = np.identity(nocc)\n    idn_vir = np.identity(nvir)\n\n    if eris is None:\n        eris = adc.transform_integrals()\n\n    s1 = 0\n    f1 = n_singles\n    s2 = f1\n    f2 = s2 + n_doubles\n\n    d_ab = e_vir[:,None] + e_vir\n    d_i = e_occ[:,None]\n    D_n = -d_i + d_ab.reshape(-1)\n    D_iab = D_n.reshape(-1)\n\n    if M_ab is None:\n        M_ab = adc.get_imds()\n    \n    #Calculate sigma vector\n    def sigma_(r):\n        cput0 = (time.clock(), time.time())\n        log = logger.Logger(adc.stdout, adc.verbose)\n\n        s = np.zeros((dim))\n\n        r1 = r[s1:f1]\n        r2 = r[s2:f2]\n\n        r2 = r2.reshape(nocc,nvir,nvir)\n\n############ ADC(2) ab block ############################\n\n        s[s1:f1] = lib.einsum('ab,b->a',M_ab,r1)\n\n############# ADC(2) a - ibc and ibc - a coupling blocks #########################\n\n        if isinstance(eris.ovvv, type(None)):\n            chnk_size = radc_ao2mo.calculate_chunk_size(adc)\n        else :\n            chnk_size = nocc\n        a = 0\n        temp_doubles = np.zeros((nocc,nvir,nvir))\n        for p in range(0,nocc,chnk_size):\n            if getattr(adc, 'with_df', None):\n                eris_ovvv = dfadc.get_ovvv_df(adc, eris.Lov, eris.Lvv, p, chnk_size).reshape(-1,nvir,nvir,nvir)\n            else :\n                eris_ovvv = radc_ao2mo.unpack_eri_1(eris.ovvv, nvir)\n            k = eris_ovvv.shape[0]\n\n            s[s1:f1] +=  2. * lib.einsum('icab,ibc->a', eris_ovvv, r2[a:a+k], optimize = True)\n            s[s1:f1] -=  lib.einsum('ibac,ibc->a',   eris_ovvv, r2[a:a+k], optimize = True)\n   \n            temp_doubles[a:a+k] += lib.einsum('icab,a->ibc', eris_ovvv, r1, optimize = True)\n            del eris_ovvv\n            a += k\n\n        s[s2:f2] +=  temp_doubles.reshape(-1)\n################ ADC(2) iab - jcd block ############################\n\n        s[s2:f2] +=  D_iab * r2.reshape(-1)\n\n############### ADC(3) iab - jcd block ############################\n\n        if (method == \"adc(2)-x\" or method == \"adc(3)\"):\n\n               eris_oovv = eris.oovv\n               eris_ovvo = eris.ovvo\n\n               r2 = r2.reshape(nocc, nvir, nvir)\n\n               if isinstance(eris.vvvv, np.ndarray):\n                   r_bab_t = r2.reshape(nocc,-1)\n                   eris_vvvv = eris.vvvv\n                   s[s2:f2] += np.dot(r_bab_t,eris_vvvv.T).reshape(-1)\n               elif isinstance(eris.vvvv, list):\n                   s[s2:f2] += ea_contract_r_vvvv(adc,r2,eris.vvvv)\n               else :\n                   s[s2:f2] += ea_contract_r_vvvv(adc,r2,eris.Lvv)\n\n               s[s2:f2] -= 0.5*lib.einsum('jzyi,jzx->ixy',eris_ovvo,r2,optimize = True).reshape(-1)\n               s[s2:f2] += 0.5*lib.einsum('jzyi,jxz->ixy',eris_ovvo,r2,optimize = True).reshape(-1)\n\n               s[s2:f2] -= 0.5*lib.einsum('jiyz,jxz->ixy',eris_oovv,r2,optimize = True).reshape(-1)\n               s[s2:f2] += 0.5*lib.einsum('jzyi,jxz->ixy',eris_ovvo,r2,optimize = True).reshape(-1)\n               s[s2:f2] -=  0.5*lib.einsum('jixz,jzy->ixy',eris_oovv,r2,optimize = True).reshape(-1)\n               s[s2:f2] -=  0.5*lib.einsum('jixw,jwy->ixy',eris_oovv,r2,optimize = True).reshape(-1)\n               s[s2:f2] -= 0.5*lib.einsum('jiyw,jxw->ixy',eris_oovv,r2,optimize = True).reshape(-1)\n               s[s2:f2] += 0.5*lib.einsum('jwyi,jxw->ixy',eris_ovvo,r2,optimize = True).reshape(-1)\n               s[s2:f2] += 0.5*lib.einsum('jwyi,jxw->ixy',eris_ovvo,r2,optimize = True).reshape(-1)\n               s[s2:f2] -= 0.5*lib.einsum('jwyi,jwx->ixy',eris_ovvo,r2,optimize = True).reshape(-1)\n\n            #print(\"Calculating additional terms for adc(3)\")\n\n        if (method == \"adc(3)\"):\n\n               eris_ovoo = eris.ovoo\n\n############### ADC(3) a - ibc block and ibc-a coupling blocks ########################\n               \n               t2_1 = adc.t2[0][:]\n\n               temp =   0.25 * lib.einsum('lmab,jab->lmj',t2_1,r2)\n               temp -=  0.25 * lib.einsum('lmab,jba->lmj',t2_1,r2)\n               temp -=  0.25 * lib.einsum('mlab,jab->lmj',t2_1,r2)\n               temp +=  0.25 * lib.einsum('mlab,jba->lmj',t2_1,r2)\n\n               s[s1:f1] += lib.einsum('lmj,lamj->a',temp, eris_ovoo, optimize=True)\n               s[s1:f1] -= lib.einsum('lmj,malj->a',temp, eris_ovoo, optimize=True)\n               del temp\n\n               temp_1 = -lib.einsum('lmzw,jzw->jlm',t2_1,r2)\n               s[s1:f1] -= lib.einsum('jlm,lamj->a',temp_1, eris_ovoo, optimize=True)\n\n               temp_s_a = lib.einsum('jlwd,jzw->lzd',t2_1,r2,optimize=True)\n               temp_s_a -= lib.einsum('jlwd,jwz->lzd',t2_1,r2,optimize=True)\n               temp_s_a -= lib.einsum('ljwd,jzw->lzd',t2_1,r2,optimize=True)\n               temp_s_a += lib.einsum('ljwd,jwz->lzd',t2_1,r2,optimize=True)\n               temp_s_a += lib.einsum('ljdw,jzw->lzd',t2_1,r2,optimize=True)\n\n               temp_s_a_1 = -lib.einsum('jlzd,jwz->lwd',t2_1,r2,optimize=True)\n               temp_s_a_1 += lib.einsum('jlzd,jzw->lwd',t2_1,r2,optimize=True)\n               temp_s_a_1 += lib.einsum('ljzd,jwz->lwd',t2_1,r2,optimize=True)\n               temp_s_a_1 -= lib.einsum('ljzd,jzw->lwd',t2_1,r2,optimize=True)\n               temp_s_a_1 += -lib.einsum('ljdz,jwz->lwd',t2_1,r2,optimize=True)\n\n               temp_t2_r2_1 = lib.einsum('jlwd,jzw->lzd',t2_1,r2,optimize=True)\n               temp_t2_r2_1 -= lib.einsum('jlwd,jwz->lzd',t2_1,r2,optimize=True)\n               temp_t2_r2_1 += lib.einsum('jlwd,jzw->lzd',t2_1,r2,optimize=True)\n               temp_t2_r2_1 -= lib.einsum('ljwd,jzw->lzd',t2_1,r2,optimize=True)\n\n               temp_t2_r2_2 = -lib.einsum('jlzd,jwz->lwd',t2_1,r2,optimize=True)\n               temp_t2_r2_2 += lib.einsum('jlzd,jzw->lwd',t2_1,r2,optimize=True)\n               temp_t2_r2_2 -= lib.einsum('jlzd,jwz->lwd',t2_1,r2,optimize=True)\n               temp_t2_r2_2 += lib.einsum('ljzd,jwz->lwd',t2_1,r2,optimize=True)\n\n               temp_t2_r2_3 = -lib.einsum('ljzd,jzw->lwd',t2_1,r2,optimize=True)\n\n               temp_a = t2_1.transpose(0,3,1,2).copy()\n               temp_b = temp_a.reshape(nocc*nvir,nocc*nvir)\n               r2_t = r2.reshape(nocc*nvir,-1)\n               temp_c = np.dot(temp_b,r2_t).reshape(nocc,nvir,nvir)\n               temp_t2_r2_4 = temp_c.transpose(0,2,1).copy()\n\n               del t2_1\n\n               if isinstance(eris.ovvv, type(None)):\n                   chnk_size = radc_ao2mo.calculate_chunk_size(adc)\n               else :\n                   chnk_size = nocc\n               a = 0\n               temp = np.zeros((nocc,nvir,nvir))\n               temp_1_1 = np.zeros((nocc,nvir,nvir))\n               temp_2_1 = np.zeros((nocc,nvir,nvir))\n               for p in range(0,nocc,chnk_size):\n                   if getattr(adc, 'with_df', None):\n                       eris_ovvv = dfadc.get_ovvv_df(adc, eris.Lov, eris.Lvv, p, chnk_size).reshape(-1,nvir,nvir,nvir)\n                   else :\n                       eris_ovvv = radc_ao2mo.unpack_eri_1(eris.ovvv, nvir)\n                   k = eris_ovvv.shape[0]\n\n                   temp_1_1[a:a+k] = lib.einsum('ldxb,b->lxd', eris_ovvv,r1,optimize=True)\n                   temp_1_1[a:a+k] -= lib.einsum('lbxd,b->lxd', eris_ovvv,r1,optimize=True)\n                   temp_2_1[a:a+k] = lib.einsum('ldxb,b->lxd', eris_ovvv,r1,optimize=True)\n\n                   s[s1:f1] += 0.5*lib.einsum('lzd,ldza->a',temp_s_a[a:a+k],eris_ovvv,optimize=True)\n                   s[s1:f1] -= 0.5*lib.einsum('lzd,lazd->a',temp_s_a[a:a+k],eris_ovvv,optimize=True)\n                   s[s1:f1] -= 0.5*lib.einsum('lwd,ldwa->a',temp_s_a_1[a:a+k],eris_ovvv,optimize=True)\n                   s[s1:f1] += 0.5*lib.einsum('lwd,lawd->a',temp_s_a_1[a:a+k],eris_ovvv,optimize=True)\n\n                   s[s1:f1] += 0.5*lib.einsum('lzd,ldza->a',temp_t2_r2_1[a:a+k],eris_ovvv,optimize=True)\n\n                   s[s1:f1] -= 0.5*lib.einsum('lwd,ldwa->a',temp_t2_r2_2[a:a+k],eris_ovvv,optimize=True)\n\n                   s[s1:f1] += 0.5*lib.einsum('lwd,lawd->a',temp_t2_r2_3[a:a+k],eris_ovvv,optimize=True)\n\n                   s[s1:f1] -= 0.5*lib.einsum('lzd,lazd->a',temp_t2_r2_4[a:a+k],eris_ovvv,optimize=True)\n\n                   temp[a:a+k]  -= lib.einsum('lbyd,b->lyd',eris_ovvv,r1,optimize=True)\n\n                   del eris_ovvv\n                   a += k\n\n               t2_1 = adc.t2[0][:]\n               temp_1 = -lib.einsum('lyd,lixd->ixy',temp,t2_1,optimize=True)\n               s[s2:f2] -= temp_1.reshape(-1)\n\n               del temp_s_a\n               del temp_s_a_1\n               del temp_t2_r2_1\n               del temp_t2_r2_2\n               del temp_t2_r2_3\n               del temp_t2_r2_4\n\n               temp_1 = lib.einsum('b,lbmi->lmi',r1,eris_ovoo)\n               s[s2:f2] += lib.einsum('lmi,lmxy->ixy',temp_1, t2_1, optimize=True).reshape(-1)\n\n               temp  = lib.einsum('lxd,lidy->ixy',temp_1_1,t2_1,optimize=True)\n               temp  += lib.einsum('lxd,ilyd->ixy',temp_2_1,t2_1,optimize=True)\n               temp  -= lib.einsum('lxd,ildy->ixy',temp_2_1,t2_1,optimize=True)\n               s[s2:f2] += temp.reshape(-1)\n              \n               del t2_1\n               del temp\n               del temp_1\n               del temp_1_1\n               del temp_2_1\n\n        cput0 = log.timer_debug1(\"completed sigma vector calculation\", *cput0)\n        return s\n\n    return sigma_\n\n\ndef ip_adc_matvec(adc, M_ij=None, eris=None):\n\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    t1_2 = adc.t1[0]\n\n    nocc = adc._nocc\n    nvir = adc._nvir\n\n    ij_ind = np.tril_indices(nocc, k=-1)\n\n    n_singles = nocc\n    n_doubles = nvir * nocc * nocc\n\n    dim = n_singles + n_doubles\n\n    e_occ = adc.mo_energy[:nocc]\n    e_vir = adc.mo_energy[nocc:]\n\n    idn_occ = np.identity(nocc)\n    idn_vir = np.identity(nvir)\n\n    if eris is None:\n        eris = adc.transform_integrals()\n\n    s1 = 0\n    f1 = n_singles\n    s2 = f1\n    f2 = s2 + n_doubles\n\n    d_ij = e_occ[:,None] + e_occ\n    d_a = e_vir[:,None]\n    D_n = -d_a + d_ij.reshape(-1)\n    D_aij = D_n.reshape(-1)\n\n    if M_ij is None:\n        M_ij = adc.get_imds()\n\n    #Calculate sigma vector\n    def sigma_(r):\n        cput0 = (time.clock(), time.time())\n        log = logger.Logger(adc.stdout, adc.verbose)\n\n        s = np.zeros((dim))\n\n        r1 = r[s1:f1]\n        r2 = r[s2:f2]\n\n        r2 = r2.reshape(nvir,nocc,nocc)\n\n        eris_ovoo = eris.ovoo\n\n############ ADC(2) ij block ############################\n\n        s[s1:f1] = lib.einsum('ij,j->i',M_ij,r1)\n\n############ ADC(2) i - kja block #########################\n\n        s[s1:f1] += 2. * lib.einsum('jaki,ajk->i', eris_ovoo, r2, optimize = True)\n        s[s1:f1] -= lib.einsum('kaji,ajk->i', eris_ovoo, r2, optimize = True)\n\n############## ADC(2) ajk - i block ############################\n\n        temp = lib.einsum('jaki,i->ajk', eris_ovoo, r1, optimize = True).reshape(-1)\n        s[s2:f2] += temp.reshape(-1)\n\n################ ADC(2) ajk - bil block ############################\n\n        s[s2:f2] += D_aij * r2.reshape(-1)\n\n############### ADC(3) ajk - bil block ############################\n\n        if (method == \"adc(2)-x\" or method == \"adc(3)\"):\n        \n               eris_oooo = eris.oooo\n               eris_oovv = eris.oovv\n               eris_ovvo = eris.ovvo\n               \n               s[s2:f2] -= 0.5*lib.einsum('kijl,ali->ajk',eris_oooo, r2, optimize = True).reshape(-1)\n               s[s2:f2] -= 0.5*lib.einsum('klji,ail->ajk',eris_oooo ,r2, optimize = True).reshape(-1)\n               \n               s[s2:f2] += 0.5*lib.einsum('klba,bjl->ajk',eris_oovv,r2,optimize = True).reshape(-1)\n               \n               s[s2:f2] +=  0.5*lib.einsum('jabl,bkl->ajk',eris_ovvo,r2,optimize = True).reshape(-1)\n               s[s2:f2] -=  0.5*lib.einsum('jabl,blk->ajk',eris_ovvo,r2,optimize = True).reshape(-1)\n               s[s2:f2] +=  0.5*lib.einsum('jlba,blk->ajk',eris_oovv,r2,optimize = True).reshape(-1)\n               s[s2:f2] -=  0.5*lib.einsum('jabl,blk->ajk',eris_ovvo,r2,optimize = True).reshape(-1)\n               \n               s[s2:f2] += 0.5*lib.einsum('kiba,bji->ajk',eris_oovv,r2,optimize = True).reshape(-1)\n               \n               s[s2:f2] += 0.5*lib.einsum('jiba,bik->ajk',eris_oovv,r2,optimize = True).reshape(-1)\n               s[s2:f2] -= 0.5*lib.einsum('jabi,bik->ajk',eris_ovvo,r2,optimize = True).reshape(-1)\n               s[s2:f2] -= 0.5*lib.einsum('jabi,bik->ajk',eris_ovvo,r2,optimize = True).reshape(-1)\n               s[s2:f2] += 0.5*lib.einsum('jabi,bki->ajk',eris_ovvo,r2,optimize = True).reshape(-1)\n               \n        if (method == \"adc(3)\"):\n\n               eris_ovoo = eris.ovoo\n               t2_1 = adc.t2[0]\n\n################ ADC(3) i - kja block and ajk - i ############################\n\n               temp =  0.25 * lib.einsum('ijbc,aij->abc',t2_1, r2, optimize=True)\n               temp -= 0.25 * lib.einsum('ijbc,aji->abc',t2_1, r2, optimize=True)\n               temp -= 0.25 * lib.einsum('jibc,aij->abc',t2_1, r2, optimize=True)\n               temp += 0.25 * lib.einsum('jibc,aji->abc',t2_1, r2, optimize=True)\n\n               temp_1 = lib.einsum('kjcb,ajk->abc',t2_1,r2, optimize=True)\n\n               if isinstance(eris.ovvv, type(None)):\n                   chnk_size = radc_ao2mo.calculate_chunk_size(adc)\n               else :\n                   chnk_size = nocc\n               a = 0\n               temp_singles = np.zeros((nocc))\n               temp_doubles = np.zeros((nvir,nvir,nvir))\n               for p in range(0,nocc,chnk_size):\n                   if getattr(adc, 'with_df', None):\n                       eris_ovvv = dfadc.get_ovvv_df(adc, eris.Lov, eris.Lvv, p, chnk_size).reshape(-1,nvir,nvir,nvir)\n                   else :\n                       eris_ovvv = radc_ao2mo.unpack_eri_1(eris.ovvv, nvir)\n                   k = eris_ovvv.shape[0]\n\n                   temp_singles[a:a+k] += lib.einsum('abc,icab->i',temp, eris_ovvv, optimize=True)\n                   temp_singles[a:a+k] -= lib.einsum('abc,ibac->i',temp, eris_ovvv, optimize=True)\n                   temp_singles[a:a+k] += lib.einsum('abc,icab->i',temp_1, eris_ovvv, optimize=True)\n                   temp_doubles = lib.einsum('i,icab->cba',r1[a:a+k],eris_ovvv,optimize=True)\n                   s[s2:f2] += lib.einsum('cba,kjcb->ajk',temp_doubles, t2_1, optimize=True).reshape(-1)\n                   del eris_ovvv\n                   del temp_doubles\n                   a += k\n\n               s[s1:f1] += temp_singles\n               temp = np.zeros_like(r2)\n               temp =  lib.einsum('jlab,ajk->blk',t2_1,r2,optimize=True)\n               temp -= lib.einsum('jlab,akj->blk',t2_1,r2,optimize=True)\n               temp -= lib.einsum('ljab,ajk->blk',t2_1,r2,optimize=True)\n               temp += lib.einsum('ljab,akj->blk',t2_1,r2,optimize=True)\n               temp += lib.einsum('ljba,ajk->blk',t2_1,r2,optimize=True)\n\n               temp_1 = np.zeros_like(r2)\n               temp_1 =  lib.einsum('jlab,ajk->blk',t2_1,r2,optimize=True)\n               temp_1 -= lib.einsum('jlab,akj->blk',t2_1,r2,optimize=True)\n               temp_1 += lib.einsum('jlab,ajk->blk',t2_1,r2,optimize=True)\n               temp_1 -= lib.einsum('ljab,ajk->blk',t2_1,r2,optimize=True)\n\n               temp_2 = lib.einsum('jlba,akj->blk',t2_1,r2, optimize=True)\n\n               s[s1:f1] += 0.5*lib.einsum('blk,lbik->i',temp,eris_ovoo,optimize=True)\n               s[s1:f1] -= 0.5*lib.einsum('blk,iblk->i',temp,eris_ovoo,optimize=True)\n               s[s1:f1] += 0.5*lib.einsum('blk,lbik->i',temp_1,eris_ovoo,optimize=True)\n               s[s1:f1] -= 0.5*lib.einsum('blk,iblk->i',temp_2,eris_ovoo,optimize=True)\n               del temp\n               del temp_1\n               del temp_2\n\n               temp = np.zeros_like(r2)\n               temp = -lib.einsum('klab,akj->blj',t2_1,r2,optimize=True)\n               temp += lib.einsum('klab,ajk->blj',t2_1,r2,optimize=True)\n               temp += lib.einsum('lkab,akj->blj',t2_1,r2,optimize=True)\n               temp -= lib.einsum('lkab,ajk->blj',t2_1,r2,optimize=True)\n               temp -= lib.einsum('lkba,akj->blj',t2_1,r2,optimize=True)\n\n               temp_1 = np.zeros_like(r2)\n               temp_1  = -lib.einsum('klab,akj->blj',t2_1,r2,optimize=True)\n               temp_1 += lib.einsum('klab,ajk->blj',t2_1,r2,optimize=True)\n               temp_1 -= lib.einsum('klab,akj->blj',t2_1,r2,optimize=True)\n               temp_1 += lib.einsum('lkab,akj->blj',t2_1,r2,optimize=True)\n\n               temp_2 = -lib.einsum('klba,ajk->blj',t2_1,r2,optimize=True)\n\n               s[s1:f1] -= 0.5*lib.einsum('blj,lbij->i',temp,eris_ovoo,optimize=True)\n               s[s1:f1] += 0.5*lib.einsum('blj,iblj->i',temp,eris_ovoo,optimize=True)\n               s[s1:f1] -= 0.5*lib.einsum('blj,lbij->i',temp_1,eris_ovoo,optimize=True)\n               s[s1:f1] += 0.5*lib.einsum('blj,iblj->i',temp_2,eris_ovoo,optimize=True)\n               \n               del temp\n               del temp_1\n               del temp_2\n\n               temp_1  = lib.einsum('i,lbik->kbl',r1,eris_ovoo)\n               temp_1  -= lib.einsum('i,iblk->kbl',r1,eris_ovoo)\n               temp_2  = lib.einsum('i,lbik->kbl',r1,eris_ovoo)\n\n               temp  = lib.einsum('kbl,ljba->ajk',temp_1,t2_1,optimize=True)\n               temp += lib.einsum('kbl,jlab->ajk',temp_2,t2_1,optimize=True)\n               temp -= lib.einsum('kbl,ljab->ajk',temp_2,t2_1,optimize=True)\n               s[s2:f2] += temp.reshape(-1)\n\n               temp  = -lib.einsum('i,iblj->jbl',r1,eris_ovoo,optimize=True)\n               temp_1 = -lib.einsum('jbl,klba->ajk',temp,t2_1,optimize=True)\n               s[s2:f2] -= temp_1.reshape(-1)\n\n               del temp\n               del temp_1\n               del temp_2\n               del t2_1\n\n        cput0 = log.timer_debug1(\"completed sigma vector calculation\", *cput0)\n        s *= -1.0\n\n        return s\n\n    return sigma_\n\n\ndef ea_compute_trans_moments(adc, orb):\n\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    t2_1 = adc.t2[0][:]\n    t1_2 = adc.t1[0][:]\n\n    nocc = adc._nocc\n    nvir = adc._nvir\n\n    n_singles = nvir\n    n_doubles = nocc * nvir * nvir\n\n    dim = n_singles + n_doubles\n\n    e_occ = adc.mo_energy[:nocc]\n    e_vir = adc.mo_energy[nocc:]\n\n    idn_occ = np.identity(nocc)\n    idn_vir = np.identity(nvir)\n\n    s1 = 0\n    f1 = n_singles\n    s2 = f1\n    f2 = s2 + n_doubles\n\n    T = np.zeros((dim))\n\n######## ADC(2) part  ############################################\n\n    if orb < nocc:\n\n        T[s1:f1] = -t1_2[orb,:]\n\n        t2_1_t = -t2_1.transpose(1,0,2,3)\n\n        T[s2:f2] += t2_1_t[:,orb,:,:].reshape(-1)\n\n    else :\n\n        T[s1:f1] += idn_vir[(orb-nocc), :]\n        T[s1:f1] -= 0.25*lib.einsum('klc,klac->a',t2_1[:,:,(orb-nocc),:], t2_1, optimize = True)\n        T[s1:f1] -= 0.25*lib.einsum('lkc,lkac->a',t2_1[:,:,(orb-nocc),:], t2_1, optimize = True)\n\n        T[s1:f1] -= 0.25*lib.einsum('klc,klac->a',t2_1[:,:,(orb-nocc),:], t2_1, optimize = True)\n        T[s1:f1] += 0.25*lib.einsum('lkc,klac->a',t2_1[:,:,(orb-nocc),:], t2_1, optimize = True)\n        T[s1:f1] += 0.25*lib.einsum('klc,lkac->a',t2_1[:,:,(orb-nocc),:], t2_1, optimize = True)\n        T[s1:f1] -= 0.25*lib.einsum('lkc,lkac->a',t2_1[:,:,(orb-nocc),:], t2_1, optimize = True)\n\n######### ADC(3) 2p-1h  part  ############################################\n\n    if(method==\"adc(2)-x\"or adc.method==\"adc(3)\"):\n\n        t2_2 = adc.t2[1][:]\n\n        if orb < nocc:\n\n            t2_2_t = -t2_2.transpose(1,0,2,3)\n\n            T[s2:f2] += t2_2_t[:,orb,:,:].reshape(-1)\n\n########### ADC(3) 1p part  ############################################\n\n    if(adc.method==\"adc(3)\"):\n\n        t1_3 = adc.t1[1]\n\n        if orb < nocc:\n            T[s1:f1] += 0.5*lib.einsum('kac,ck->a',t2_1[:,orb,:,:], t1_2.T,optimize = True)\n            T[s1:f1] -= 0.5*lib.einsum('kac,ck->a',t2_1[orb,:,:,:], t1_2.T,optimize = True)\n            T[s1:f1] -= 0.5*lib.einsum('kac,ck->a',t2_1[orb,:,:,:], t1_2.T,optimize = True)\n            T[s1:f1] -= t1_3[orb,:]\n\n        else:\n\n            T[s1:f1] -= 0.25*lib.einsum('klc,klac->a',t2_1[:,:,(orb-nocc),:], t2_2, optimize = True)\n            T[s1:f1] -= 0.25*lib.einsum('lkc,lkac->a',t2_1[:,:,(orb-nocc),:], t2_2, optimize = True)\n\n            T[s1:f1] -= 0.25*lib.einsum('klac,klc->a',t2_1, t2_2[:,:,(orb-nocc),:],optimize = True)\n            T[s1:f1] -= 0.25*lib.einsum('lkac,lkc->a',t2_1, t2_2[:,:,(orb-nocc),:],optimize = True)\n\n            T[s1:f1] -= 0.25*lib.einsum('klc,klac->a',t2_1[:,:,(orb-nocc),:], t2_2, optimize = True)\n            T[s1:f1] += 0.25*lib.einsum('klc,lkac->a',t2_1[:,:,(orb-nocc),:], t2_2, optimize = True)\n            T[s1:f1] += 0.25*lib.einsum('lkc,klac->a',t2_1[:,:,(orb-nocc),:], t2_2, optimize = True)\n            T[s1:f1] -= 0.25*lib.einsum('lkc,lkac->a',t2_1[:,:,(orb-nocc),:], t2_2, optimize = True)\n\n            T[s1:f1] -= 0.25*lib.einsum('klac,klc->a',t2_1, t2_2[:,:,(orb-nocc),:],optimize = True)\n            T[s1:f1] += 0.25*lib.einsum('klac,lkc->a',t2_1, t2_2[:,:,(orb-nocc),:],optimize = True)\n            T[s1:f1] += 0.25*lib.einsum('lkac,klc->a',t2_1, t2_2[:,:,(orb-nocc),:],optimize = True)\n            T[s1:f1] -= 0.25*lib.einsum('lkac,lkc->a',t2_1, t2_2[:,:,(orb-nocc),:],optimize = True)\n\n        del t2_2\n    del t2_1\n\n    T_aaa = T[n_singles:].reshape(nocc,nvir,nvir).copy()\n    T_aaa = T_aaa - T_aaa.transpose(0,2,1)\n    T[n_singles:] += T_aaa.reshape(-1)\n\n    return T\n\n\ndef ip_compute_trans_moments(adc, orb):\n\n    if adc.method not in (\"adc(2)\", \"adc(2)-x\", \"adc(3)\"):\n        raise NotImplementedError(adc.method)\n\n    method = adc.method\n\n    t2_1 = adc.t2[0][:]\n    t1_2 = adc.t1[0][:]\n\n    nocc = adc._nocc\n    nvir = adc._nvir\n\n    n_singles = nocc\n    n_doubles = nvir * nocc * nocc\n\n    dim = n_singles + n_doubles\n\n    e_occ = adc.mo_energy[:nocc]\n    e_vir = adc.mo_energy[nocc:]\n\n    idn_occ = np.identity(nocc)\n    idn_vir = np.identity(nvir)\n\n    s1 = 0\n    f1 = n_singles\n    s2 = f1\n    f2 = s2 + n_doubles\n\n    T = np.zeros((dim))\n\n######## ADC(2) 1h part  ############################################\n\n    if orb < nocc:\n        T[s1:f1]  = idn_occ[orb, :]\n        T[s1:f1] += 0.25*lib.einsum('kdc,ikdc->i',t2_1[:,orb,:,:], t2_1, optimize = True)\n        T[s1:f1] -= 0.25*lib.einsum('kcd,ikdc->i',t2_1[:,orb,:,:], t2_1, optimize = True)\n        T[s1:f1] -= 0.25*lib.einsum('kdc,ikcd->i',t2_1[:,orb,:,:], t2_1, optimize = True)\n        T[s1:f1] += 0.25*lib.einsum('kcd,ikcd->i',t2_1[:,orb,:,:], t2_1, optimize = True)\n        T[s1:f1] -= 0.25*lib.einsum('kdc,ikdc->i',t2_1[orb,:,:,:], t2_1, optimize = True)\n        T[s1:f1] -= 0.25*lib.einsum('kcd,ikcd->i',t2_1[orb,:,:,:], t2_1, optimize = True)\n    else :\n        T[s1:f1] += t1_2[:,(orb-nocc)]\n\n######## ADC(2) 2h-1p  part  ############################################\n\n        t2_1_t = t2_1.transpose(2,3,1,0)\n\n        T[s2:f2] = t2_1_t[(orb-nocc),:,:,:].reshape(-1)\n\n######## ADC(3) 2h-1p  part  ############################################\n\n    if(method=='adc(2)-x'or method=='adc(3)'):\n\n        t2_2 = adc.t2[1][:]\n\n        if orb >= nocc:\n            t2_2_t = t2_2.transpose(2,3,1,0)\n\n            T[s2:f2] += t2_2_t[(orb-nocc),:,:,:].reshape(-1)\n\n######### ADC(3) 1h part  ############################################\n\n    if(method=='adc(3)'):\n\n        t1_3 = adc.t1[1]\n\n        if orb < nocc:\n            T[s1:f1] += 0.25*lib.einsum('kdc,ikdc->i',t2_1[:,orb,:,:], t2_2, optimize = True)\n            T[s1:f1] -= 0.25*lib.einsum('kcd,ikdc->i',t2_1[:,orb,:,:], t2_2, optimize = True)\n            T[s1:f1] -= 0.25*lib.einsum('kdc,ikcd->i',t2_1[:,orb,:,:], t2_2, optimize = True)\n            T[s1:f1] += 0.25*lib.einsum('kcd,ikcd->i',t2_1[:,orb,:,:], t2_2, optimize = True)\n            T[s1:f1] -= 0.25*lib.einsum('kdc,ikdc->i',t2_1[orb,:,:,:], t2_2, optimize = True)\n            T[s1:f1] -= 0.25*lib.einsum('kcd,ikcd->i',t2_1[orb,:,:,:], t2_2, optimize = True)\n\n            T[s1:f1] += 0.25*lib.einsum('ikdc,kdc->i',t2_1, t2_2[:,orb,:,:],optimize = True)\n            T[s1:f1] -= 0.25*lib.einsum('ikcd,kdc->i',t2_1, t2_2[:,orb,:,:],optimize = True)\n            T[s1:f1] -= 0.25*lib.einsum('ikdc,kcd->i',t2_1, t2_2[:,orb,:,:],optimize = True)\n            T[s1:f1] += 0.25*lib.einsum('ikcd,kcd->i',t2_1, t2_2[:,orb,:,:],optimize = True)\n            T[s1:f1] -= 0.25*lib.einsum('ikcd,kcd->i',t2_1, t2_2[orb,:,:,:],optimize = True)\n            T[s1:f1] -= 0.25*lib.einsum('ikdc,kdc->i',t2_1, t2_2[orb,:,:,:],optimize = True)\n        else:\n            T[s1:f1] += 0.5*lib.einsum('ikc,kc->i',t2_1[:,:,(orb-nocc),:], t1_2,optimize = True)\n            T[s1:f1] -= 0.5*lib.einsum('kic,kc->i',t2_1[:,:,(orb-nocc),:], t1_2,optimize = True)\n            T[s1:f1] += 0.5*lib.einsum('ikc,kc->i',t2_1[:,:,(orb-nocc),:], t1_2,optimize = True)\n            T[s1:f1] += t1_3[:,(orb-nocc)]\n\n        del t2_2\n    del t2_1\n\n    T_aaa = T[n_singles:].reshape(nvir,nocc,nocc).copy()\n    T_aaa = T_aaa - T_aaa.transpose(0,2,1)\n    T[n_singles:] += T_aaa.reshape(-1)\n\n    return T\n\n\ndef get_trans_moments(adc):\n\n    nmo  = adc.nmo\n    T = []\n    for orb in range(nmo):\n\n            T_a = adc.compute_trans_moments(orb)\n            T.append(T_a)\n\n    T = np.array(T)\n    return T\n\n\ndef analyze_eigenvector_ea(adc):\n    \n    nocc = adc._nocc\n    nvir = adc._nvir\n    evec_print_tol = adc.evec_print_tol\n\n    logger.info(adc, \"Number of occupied orbitals = %d\", nocc)\n    logger.info(adc, \"Number of virtual orbitals =  %d\", nvir)\n    logger.info(adc, \"Print eigenvector elements > %f\\n\", evec_print_tol)\n\n    n_singles = nvir\n    n_doubles = nocc * nvir * nvir\n    U = adc.U\n\n    for I in range(U.shape[1]):\n        U1 = U[:n_singles,I]\n        U2 = U[n_singles:,I].reshape(nocc,nvir,nvir)\n        U1dotU1 = np.dot(U1, U1) \n        U2dotU2 =  2.*np.dot(U2.ravel(), U2.ravel()) - np.dot(U2.ravel(), U2.transpose(0,2,1).ravel())\n       \n        U_sq = U[:,I].copy()**2\n        ind_idx = np.argsort(-U_sq)\n        U_sq = U_sq[ind_idx] \n        U_sorted = U[ind_idx,I].copy()\n                   \n        U_sorted = U_sorted[U_sq > evec_print_tol**2]\n        ind_idx = ind_idx[U_sq > evec_print_tol**2]\n\n        singles_idx = []\n        doubles_idx = []\n        singles_val = []\n        doubles_val = []\n        iter_num = 0\n                \n        for orb_idx in ind_idx:\n            \n            if orb_idx < n_singles:\n                a_idx = orb_idx + 1 + nocc\n                singles_idx.append(a_idx)\n                singles_val.append(U_sorted[iter_num])\n\n            if orb_idx >= n_singles:\n                iab_idx = orb_idx - n_singles\n                ab_rem = iab_idx % (nvir*nvir)\n                i_idx = iab_idx //(nvir*nvir)\n                a_idx = ab_rem//nvir\n                b_idx = ab_rem % nvir\n                doubles_idx.append((i_idx + 1, a_idx + 1 + nocc, b_idx + 1 + nocc))\n                doubles_val.append(U_sorted[iter_num])\n                \n            iter_num += 1 \n     \n        logger.info(adc,'%s | root %d | norm(1p)  = %6.4f | norm(1h2p) = %6.4f ',adc.method ,I, U1dotU1, U2dotU2)\n\n        if singles_val:\n            logger.info(adc, \"\\n1p block: \") \n            logger.info(adc, \"     a     U(a)\")\n            logger.info(adc, \"------------------\")\n            for idx, print_singles in enumerate(singles_idx):\n                logger.info(adc, '  %4d   %7.4f', print_singles, singles_val[idx])\n\n        if doubles_val:\n            logger.info(adc, \"\\n1h2p block: \") \n            logger.info(adc, \"     i     a     b     U(i,a,b)\")\n            logger.info(adc, \"-------------------------------\")\n            for idx, print_doubles in enumerate(doubles_idx):\n                logger.info(adc, '  %4d  %4d  %4d     %7.4f', print_doubles[0], print_doubles[1], print_doubles[2], doubles_val[idx])\n\n        logger.info(adc, \"\\n*************************************************************\\n\")\n \n\ndef analyze_eigenvector_ip(adc):\n    \n    nocc = adc._nocc\n    nvir = adc._nvir\n    \n    n_singles = nocc\n    n_doubles = nvir * nocc * nocc\n    evec_print_tol = adc.evec_print_tol\n    U = adc.U\n    \n    logger.info(adc, \"Number of occupied orbitals = %d\", nocc)\n    logger.info(adc, \"Number of virtual orbitals =  %d\", nvir)\n    logger.info(adc, \"Print eigenvector elements > %f\\n\", evec_print_tol)\n  \n    for I in range(U.shape[1]):\n        U1 = U[:n_singles,I]\n        U2 = U[n_singles:,I].reshape(nvir,nocc,nocc)\n        U1dotU1 = np.dot(U1, U1) \n        U2dotU2 =  2.*np.dot(U2.ravel(), U2.ravel()) - np.dot(U2.ravel(), U2.transpose(0,2,1).ravel())\n       \n        U_sq = U[:,I].copy()**2\n        ind_idx = np.argsort(-U_sq)\n        U_sq = U_sq[ind_idx] \n        U_sorted = U[ind_idx,I].copy()\n        \n        U_sorted = U_sorted[U_sq > evec_print_tol**2]\n        ind_idx = ind_idx[U_sq > evec_print_tol**2]\n             \n        singles_idx = []\n        doubles_idx = []\n        singles_val = []\n        doubles_val = []\n        iter_num = 0\n                \n        for orb_idx in ind_idx:\n            \n            if orb_idx < n_singles:\n                i_idx = orb_idx + 1\n                singles_idx.append(i_idx)\n                singles_val.append(U_sorted[iter_num])\n\n            if orb_idx >= n_singles:\n                aij_idx = orb_idx - n_singles\n                ij_rem = aij_idx % (nocc*nocc)\n                a_idx = aij_idx//(nocc*nocc)\n                i_idx = ij_rem//nocc\n                j_idx = ij_rem % nocc\n                doubles_idx.append((a_idx + 1 + n_singles, i_idx + 1, j_idx + 1))\n                doubles_val.append(U_sorted[iter_num])\n                \n            iter_num += 1 \n\n        logger.info(adc,'%s | root %d | norm(1h)  = %6.4f | norm(2h1p) = %6.4f ',adc.method ,I, U1dotU1, U2dotU2)\n\n        if singles_val:\n            logger.info(adc, \"\\n1h block: \") \n            logger.info(adc, \"     i     U(i)\")\n            logger.info(adc, \"------------------\")\n            for idx, print_singles in enumerate(singles_idx):\n                logger.info(adc, '  %4d   %7.4f', print_singles, singles_val[idx])\n\n        if doubles_val:\n            logger.info(adc, \"\\n2h1p block: \") \n            logger.info(adc, \"     i     j     a     U(i,j,a)\")\n            logger.info(adc, \"-------------------------------\")\n            for idx, print_doubles in enumerate(doubles_idx):\n                logger.info(adc, '  %4d  %4d  %4d     %7.4f', print_doubles[1], print_doubles[2], print_doubles[0], doubles_val[idx])\n\n        logger.info(adc, \"\\n*************************************************************\\n\")\n\n\ndef analyze_spec_factor(adc):\n\n    X = adc.X\n    X_2 = (X.copy()**2)*2\n    thresh = adc.spec_factor_print_tol\n\n    logger.info(adc, \"Print spectroscopic factors > %E\\n\", adc.spec_factor_print_tol)\n\n    for i in range(X_2.shape[1]):\n\n        sort = np.argsort(-X_2[:,i])\n        X_2_row = X_2[:,i]\n        X_2_row = X_2_row[sort]\n        \n        if adc.mol.symmetry == False:\n            sym = np.repeat(['A'], X_2_row.shape[0])\n        else:\n            sym = [symm.irrep_id2name(adc.mol.groupname, x) for x in adc._scf.mo_coeff.orbsym]\n            sym = np.array(sym)\n\n            sym = sym[sort]\n\n        spec_Contribution = X_2_row[X_2_row > thresh]\n        index_mo = sort[X_2_row > thresh]+1\n\n        if np.sum(spec_Contribution) == 0.0:\n            continue\n\n        logger.info(adc,'%s | root %d \\n',adc.method ,i)\n        logger.info(adc, \"     HF MO     Spec. Contribution     Orbital symmetry\")\n        logger.info(adc, \"-----------------------------------------------------------\")\n\n        for c in range(index_mo.shape[0]):\n            logger.info(adc, '     %3.d          %10.8f                %s', index_mo[c], spec_Contribution[c], sym[c])\n\n        logger.info(adc, '\\nPartial spec. factor sum = %10.8f', np.sum(spec_Contribution))\n        logger.info(adc, \"\\n*************************************************************\\n\")\n\n\ndef renormalize_eigenvectors_ea(adc, nroots=1):\n\n    nocc = adc._nocc\n    nvir = adc._nvir\n\n    n_singles = nvir\n    n_doubles = nocc * nvir * nvir\n\n    U = adc.U\n\n    for I in range(U.shape[1]):\n        U1 = U[:n_singles,I]\n        U2 = U[n_singles:,I].reshape(nocc,nvir,nvir)\n        UdotU = np.dot(U1, U1) + 2.*np.dot(U2.ravel(), U2.ravel()) - np.dot(U2.ravel(), U2.transpose(0,2,1).ravel())\n        U[:,I] /= np.sqrt(UdotU)\n    \n    return U\n\n\ndef renormalize_eigenvectors_ip(adc, nroots=1):\n\n    nocc = adc._nocc\n    nvir = adc._nvir\n\n    n_singles = nocc\n    n_doubles = nvir * nocc * nocc\n\n    U = adc.U\n\n    for I in range(U.shape[1]):\n        U1 = U[:n_singles,I]\n        U2 = U[n_singles:,I].reshape(nvir,nocc,nocc)\n        UdotU = np.dot(U1, U1) + 2.*np.dot(U2.ravel(), U2.ravel()) - np.dot(U2.ravel(), U2.transpose(0,2,1).ravel())\n        U[:,I] /= np.sqrt(UdotU)\n\n    return U\n\n\ndef get_properties(adc, nroots=1):\n\n    #Transition moments\n    T = adc.get_trans_moments()\n\n    #Spectroscopic amplitudes\n    U = adc.renormalize_eigenvectors(nroots)\n    X = np.dot(T, U).reshape(-1, nroots)\n\n    #Spectroscopic factors\n    P = 2.0*lib.einsum(\"pi,pi->i\", X, X)\n\n    return P,X\n\n\nclass RADCEA(RADC):\n    '''restricted ADC for EA energies and spectroscopic amplitudes\n\n    Attributes:\n        verbose : int\n            Print level.  Default value equals to :class:`Mole.verbose`\n        max_memory : float or int\n            Allowed memory in MB.  Default value equals to :class:`Mole.max_memory`\n        incore_complete : bool\n            Avoid all I/O. Default is False.\n        method : string\n            nth-order ADC method. Options are : ADC(2), ADC(2)-X, ADC(3). Default is ADC(2).\n        conv_tol : float\n            Convergence threshold for Davidson iterations.  Default is 1e-12.\n        max_cycle : int\n            Number of Davidson iterations.  Default is 50.\n        max_space : int\n            Space size to hold trial vectors for Davidson iterative diagonalization.  Default is 12.\n\n    Kwargs:\n\tnroots : int\n\t    Number of roots (eigenvalues) requested. Default value is 1.\n\n            >>> myadc = adc.RADC(mf).run()\n            >>> myadcea = adc.RADC(myadc).run()\n\n    Saved results\n\n        e_ea : float or list of floats\n            EA energy (eigenvalue). For nroots = 1, it is a single float number. If nroots > 1, it is a list of floats for the lowest nroots eigenvalues.\n        v_ip : array\n            Eigenvectors for each EA transition.\n        p_ea : float\n            Spectroscopic amplitudes for each EA transition.\n    '''\n    def __init__(self, adc):\n        self.mol = adc.mol\n        self.verbose = adc.verbose\n        self.stdout = adc.stdout\n        self.max_memory = adc.max_memory\n        self.max_space = adc.max_space\n        self.max_cycle = adc.max_cycle\n        self.conv_tol  = adc.conv_tol\n        self.tol_residual  = adc.tol_residual\n        self.t1 = adc.t1\n        self.t2 = adc.t2\n        self.imds = adc.imds\n        self.e_corr = adc.e_corr\n        self.method = adc.method\n        self.method_type = adc.method_type\n        self._scf = adc._scf\n        self._nocc = adc._nocc\n        self._nvir = adc._nvir\n        self._nmo = adc._nmo\n        self.mo_coeff = adc.mo_coeff\n        self.mo_energy = adc.mo_energy\n        self.nmo = adc._nmo\n        self.transform_integrals = adc.transform_integrals\n        self.with_df = adc.with_df\n        self.compute_properties = adc.compute_properties\n        self.E = None\n        self.U = None\n        self.P = None\n        self.X = None\n        self.evec_print_tol = adc.evec_print_tol\n        self.spec_factor_print_tol = adc.spec_factor_print_tol\n\n        keys = set(('tol_residual','conv_tol', 'e_corr', 'method', 'mo_coeff', 'mo_energy', 'max_memory', 't1', 'max_space', 't2', 'max_cycle'))\n\n        self._keys = set(self.__dict__.keys()).union(keys)\n    \n    kernel = kernel\n    get_imds = get_imds_ea\n    matvec = ea_adc_matvec\n    get_diag = ea_adc_diag\n    compute_trans_moments = ea_compute_trans_moments\n    get_trans_moments = get_trans_moments\n    renormalize_eigenvectors = renormalize_eigenvectors_ea\n    get_properties = get_properties\n    analyze_spec_factor = analyze_spec_factor\n    analyze_eigenvector = analyze_eigenvector_ea\n    analyze = analyze\n    compute_dyson_mo = compute_dyson_mo\n\n    def get_init_guess(self, nroots=1, diag=None, ascending = True):\n       if diag is None :\n           diag = self.ea_adc_diag()\n       idx = None\n       if ascending:\n           idx = np.argsort(diag)\n       else:\n           idx = np.argsort(diag)[::-1]\n       guess = np.zeros((diag.shape[0], nroots))\n       min_shape = min(diag.shape[0], nroots)\n       guess[:min_shape,:min_shape] = np.identity(min_shape)\n       g = np.zeros((diag.shape[0], nroots))\n       g[idx] = guess.copy()\n       guess = []\n       for p in range(g.shape[1]):\n           guess.append(g[:,p])\n       return guess\n    \n\n    def gen_matvec(self, imds=None, eris=None):\n        if imds is None: imds = self.get_imds(eris)\n        diag = self.get_diag(imds, eris)\n        matvec = self.matvec(imds, eris)\n        return matvec, diag\n\n\nclass RADCIP(RADC):\n    '''restricted ADC for IP energies and spectroscopic amplitudes\n\n    Attributes:\n        verbose : int\n            Print level.  Default value equals to :class:`Mole.verbose`\n        max_memory : float or int\n            Allowed memory in MB.  Default value equals to :class:`Mole.max_memory`\n        incore_complete : bool\n            Avoid all I/O. Default is False.\n        method : string\n            nth-order ADC method. Options are : ADC(2), ADC(2)-X, ADC(3). Default is ADC(2).\n        conv_tol : float\n            Convergence threshold for Davidson iterations.  Default is 1e-12.\n        max_cycle : int\n            Number of Davidson iterations.  Default is 50.\n        max_space : int\n            Space size to hold trial vectors for Davidson iterative diagonalization.  Default is 12.\n\n    Kwargs:\n\tnroots : int\n\t    Number of roots (eigenvalues) requested. Default value is 1.\n\n            >>> myadc = adc.RADC(mf).run()\n            >>> myadcip = adc.RADC(myadc).run()\n\n    Saved results\n\n        e_ip : float or list of floats\n            IP energy (eigenvalue). For nroots = 1, it is a single float number. If nroots > 1, it is a list of floats for the lowest nroots eigenvalues.\n        v_ip : array\n            Eigenvectors for each IP transition.\n        p_ip : float\n            Spectroscopic amplitudes for each IP transition.\n    '''\n    def __init__(self, adc):\n        self.mol = adc.mol\n        self.verbose = adc.verbose\n        self.stdout = adc.stdout\n        self.max_memory = adc.max_memory\n        self.max_space = adc.max_space\n        self.max_cycle = adc.max_cycle\n        self.conv_tol  = adc.conv_tol\n        self.tol_residual  = adc.tol_residual\n        self.t1 = adc.t1\n        self.t2 = adc.t2\n        self.imds = adc.imds\n        self.e_corr = adc.e_corr\n        self.method = adc.method\n        self.method_type = adc.method_type\n        self._scf = adc._scf\n        self._nocc = adc._nocc\n        self._nvir = adc._nvir\n        self._nmo = adc._nmo\n        self.mo_coeff = adc.mo_coeff\n        self.mo_energy = adc.mo_energy\n        self.nmo = adc._nmo\n        self.transform_integrals = adc.transform_integrals\n        self.with_df = adc.with_df\n        self.compute_properties = adc.compute_properties\n        self.E = None\n        self.U = None\n        self.P = None\n        self.X = None\n        self.evec_print_tol = adc.evec_print_tol\n        self.spec_factor_print_tol = adc.spec_factor_print_tol\n\n        keys = set(('tol_residual','conv_tol', 'e_corr', 'method', 'mo_coeff', 'mo_energy_b', 'max_memory', 't1', 'mo_energy_a', 'max_space', 't2', 'max_cycle'))\n\n        self._keys = set(self.__dict__.keys()).union(keys)\n\n    kernel = kernel\n    get_imds = get_imds_ip\n    get_diag = ip_adc_diag\n    matvec = ip_adc_matvec\n    compute_trans_moments = ip_compute_trans_moments\n    get_trans_moments = get_trans_moments\n    renormalize_eigenvectors = renormalize_eigenvectors_ip\n    get_properties = get_properties\n    analyze_spec_factor = analyze_spec_factor\n    analyze_eigenvector = analyze_eigenvector_ip\n    analyze = analyze\n    compute_dyson_mo = compute_dyson_mo\n\n    def get_init_guess(self, nroots=1, diag=None, ascending = True):\n        if diag is None :\n            diag = self.ip_adc_diag()\n        idx = None\n        if ascending:\n            idx = np.argsort(diag)\n        else:\n            idx = np.argsort(diag)[::-1]\n        guess = np.zeros((diag.shape[0], nroots))\n        min_shape = min(diag.shape[0], nroots)\n        guess[:min_shape,:min_shape] = np.identity(min_shape)\n        g = np.zeros((diag.shape[0], nroots))\n        g[idx] = guess.copy()\n        guess = []\n        for p in range(g.shape[1]):\n            guess.append(g[:,p])\n        return guess\n\n    def gen_matvec(self, imds=None, eris=None):\n        if imds is None: imds = self.get_imds(eris)\n        diag = self.get_diag(imds, eris)\n        matvec = self.matvec(imds, eris)\n        return matvec, diag\n\nif __name__ == '__main__':\n    from pyscf import scf\n    from pyscf import gto\n    from pyscf import adc\n\n    r = 1.098\n    mol = gto.Mole()\n    mol.atom = [\n        ['N', ( 0., 0.    , -r/2   )],\n        ['N', ( 0., 0.    ,  r/2)],]\n    mol.basis = {'N':'aug-cc-pvdz'}\n    mol.verbose = 0\n    mol.build()\n    mf = scf.RHF(mol)\n    mf.conv_tol = 1e-12\n    mf.kernel()\n\n    myadc = adc.ADC(mf)\n    ecorr, t_amp1, t_amp2 = myadc.kernel_gs()\n    print(ecorr -  -0.3220169236051954)\n\n    myadcip = RADCIP(myadc)\n    e,v,p = kernel(myadcip,nroots=3)\n    print(\"ADC(2) IP energies\")\n    print (e[0] - 0.5434389910483670)\n    print (e[1] - 0.6240296243595950)\n    print (e[2] - 0.6240296243595956)\n\n    print(\"ADC(2) IP spectroscopic factors\")\n    print (p[0] - 1.7688097076459075)\n    print (p[1] - 1.8192921131700284)\n    print (p[2] - 1.8192921131700293)\n\n    myadcea = RADCEA(myadc)\n    e,v,p = kernel(myadcea,nroots=3)\n    print(\"ADC(2) EA energies\")\n    print (e[0] - 0.0961781923822576)\n    print (e[1] - 0.1258326916409743)\n    print (e[2] - 0.1380779405750178)\n\n    print(\"ADC(2) EA spectroscopic factors\")\n    print (p[0] - 1.9832854445007961)\n    print (p[1] - 1.9634368668786559)\n    print (p[2] - 1.9783719593912672)\n\n    myadc = adc.ADC(mf)\n    myadc.method = \"adc(3)\"\n    ecorr, t_amp1, t_amp2 = myadc.kernel_gs()\n    print(ecorr - -0.31694173142858517)\n\n    myadcip = RADCIP(myadc)\n    e,v,p = kernel(myadcip,nroots=3)\n    print(\"ADC(3) IP energies\")\n    print (e[0] - 0.5667526829981027)\n    print (e[1] - 0.6099995170092525)\n    print (e[2] - 0.6099995170092529)\n\n    print(\"ADC(3) IP spectroscopic factors\")\n    print (p[0] - 1.8173191958988848)\n    print (p[1] - 1.8429224413853840)\n    print (p[2] - 1.8429224413853851)\n\n    myadcea = RADCEA(myadc)\n    e,v,p = kernel(myadcea,nroots=3)\n\n    print(\"ADC(3) EA energies\")\n    print (e[0] - 0.0936790850738445)\n    print (e[1] - 0.0983654552141278)\n    print (e[2] - 0.1295709313652367)\n\n    print(\"ADC(3) EA spectroscopic factors\")\n    print (p[0] - 1.8324175318668088)\n    print (p[1] - 1.9840991060607487)\n    print (p[2] - 1.9638550014980212)\n\n    myadc.method = \"adc(2)-x\"\n    e,v,p = myadc.kernel(nroots=4)\n    print(\"ADC(2)-x IP energies\")\n    print (e[0] - 0.5405255360673724)\n    print (e[1] - 0.6208026698756577)\n    print (e[2] - 0.6208026698756582)\n    print (e[3] - 0.6465332771967947)\n\n    myadc.method_type = \"ea\"\n    e,v,p = myadc.kernel(nroots=4)\n    print(\"ADC(2)-x EA energies\")\n    print (e[0] - 0.0953065329985665)\n    print (e[1] - 0.1238833070823509)\n    print (e[2] - 0.1365693811939308)\n    print (e[3] - 0.1365693811939316)\n", "meta": {"hexsha": "3564131ad70b8577ab2d781ebb0efef9830ddade", "size": 118327, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/adc/radc.py", "max_stars_repo_name": "mfkasim1/pyscf", "max_stars_repo_head_hexsha": "7be5e015b2b40181755c71d888449db936604660", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyscf/adc/radc.py", "max_issues_repo_name": "mfkasim1/pyscf", "max_issues_repo_head_hexsha": "7be5e015b2b40181755c71d888449db936604660", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyscf/adc/radc.py", "max_forks_repo_name": "mfkasim1/pyscf", "max_forks_repo_head_hexsha": "7be5e015b2b40181755c71d888449db936604660", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.1392450142, "max_line_length": 230, "alphanum_fraction": 0.5760646344, "include": true, "reason": "import numpy", "num_tokens": 43355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.2598256322295121, "lm_q1q2_score": 0.15398997777309828}}
{"text": "\"\"\"\nThis creates FOUR spectral plots used used in the appendix as Fig. 10-13.\nThis will only work for the four pre-selected spectra listed in __main__.\n\nDependencies\n----------\ngithub repository : https://github.com/bradlyke/utilities\nNote: To get these plots, LaTeX must be installed and\n      matplotlib must be able to compile LaTeX commands\n\n\nInput file\n----------\nThe most recent version of the DR16Q quasar-only catalog.\n\nParameters\n----------\n\np : [10,11,12,13] The figure number from the paper\n\n-h : Output help text to terminal (spec_plot.py -h)\n-e : Plot the error spectrum in red\n-k : Plot the sky spectrum in green\n-x : Scale the sky flux to the quasar flux (so it's readable)\n-s : Save the figure (does not display)\n\nOutput\n----------\nIf selected, an EPS file of the plot.\n\n\"\"\"\n\n#Import the tools necessary to work with spectra files.\nimport cat_tools as ct #This is a tool I wrote, so you'll need the script in your path.\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport matplotlib.ticker as ticker\nimport sys\nmatplotlib.rc('text',usetex=True)\n\n#A spectrum is a class. The object has 3 attributes right now: self, boxcar,\n#paper_plot_small.\nclass spectrum:\n    #initialize the object by loading the file. Needs a file name for infile.\n    def __init__(self,infile):\n        self.infile = infile #Load the filename as a thing for later use in plot saving.\n        self.data = ct.file_load(infile) #Load the file as a numpy structured array.\n        self.loglam = self.data['loglam'] #SDSS stores wavelengths as log10 values.\n        self.lam = 10**self.loglam #Convert this to a decimal wavelength in Angstroms.\n        self.flux = self.data['flux'] #Load the flux. Absolute, units are in plot.\n        self.ivar = self.data['ivar'] #Load the inverse variance. Needed for plotting and boxcar.\n        self.ferr = self.data['ivar']**(-0.5)\n\n    '''\n    We want to be able to smooth it fairly easily. Smooth_pct = 10 is good for\n    emphasizing broad emission lines through noise. Smooth_pct = 1000 will\n    remove (almost) all features and noise, leaving a useful continuum\n\n    This uses a square window of width smooth_pct to perform a modified\n    moving average on a spectrum using a boxcar (or \"square\" or \"tophat\")\n    window. The box calculates a new flux for a point using the original\n    signal flux, NOT the updated (smoothed) flux. This should only be used\n    to make plots more readable, not for scientific analysis.\n    '''\n    def boxcar(self,flux_arr,flux_var,smooth_pct,weighted=False):\n        spc = smooth_pct\n        num_dpoints = len(flux_arr)\n        #Initialize the new flux and error vectors.\n        box_flux = np.zeros(num_dpoints,dtype='f8')\n        box_err = np.zeros(num_dpoints,dtype='f8')\n\n        #The window should be symmetrical, but won't be near the ends of the\n        #spectrum, so it needs to be truncated properly, as padding won't\n        #allow the edges to be properly averaged.\n        for i in range(num_dpoints):\n            #Define range of values to smooth\n            #We have to check if the window can be symmetrical. If it is closer\n            #to the edge of spectrum than half of smooth_pct it can't be\n            #symmetrical, so truncate the denominator when averaging.\n            if i < int(spc/2):\n                lower = 0\n            else:\n                lower = -int(spc/2) + i\n            if ((int(spc/2) + i) > num_dpoints):\n                upper = num_dpoints\n            else:\n                upper = int(spc/2) + i\n            #Smooth the values depending on smoothing type\n            #Weighting use the flux error to do a weighted average, but if the\n            #spectrum flux is smoothed, then so must the error spectrum, or else\n            #it will be the wrong scale.\n            #Note that this always calls a box of the ORIGINAL signal, not taking\n            #previously smoothing pixels into account.\n            if weighted==True:\n                noise_temp = np.sqrt(flux_var[lower:upper])\n                signal_temp = flux_arr[lower:upper]\n                flux_temp = np.average(signal_temp,weights=noise_temp)\n                ivar_temp = (np.average((signal_temp-flux_temp)**2, weights=noise_temp))**(-1.0)\n            else:\n                flux_temp = np.median(flux_arr[lower:upper])\n                ivar_temp = flux_var[i]\n            #If the smoothing is not weighted by error, the error isn't smoothed\n            #and thus will no longer be properly scaled.\n\n            #These hold the smoothed flux and (possibly) smoothed error.\n            box_flux[i] = flux_temp\n            box_err[i] = ivar_temp\n\n        return box_flux,box_err\n\n    #A \"small paper plot\" is just one of the attributes taken from the\n    #specClass in the utilities repository. The emission line labels had\n    #to be added by hand for each spectrum, so the original class wouldn't work\n    #here.\n    def paper_plot_small(self,z_in,spec_num,smooth=False,err=False,sky=False,scale_sky=False,save=False,rest=True):\n        #These look at the data domain and range (wavelength and flux) and\n        #find limits for the plot window.\n        wobs = np.where((self.lam>=3700)&(self.lam<=10000))[0]\n        flux_range = np.amax(self.flux[wobs]) - np.amin(self.flux[wobs])\n        flux_pad = float(flux_range)/10\n        y_lower = np.amin(self.flux[wobs]) - flux_pad\n        y_upper = np.amax(self.flux[wobs]) + flux_pad\n        x_lower = np.amin(self.lam)\n        x_upper = np.amax(self.lam)\n\n        '''\n        For the four following spectra, the rest wavelength of the emission lines\n        are taken from Vanden Berk et al. 2001 paper. That paper lists rest\n        wavelengths in the lab and observed in spectra. The \"official\" SDSS list\n        uses a blend of these two sources, so we chose lab or observed based on\n        whichever SDSS chose.\n\n        The following if/elif/else chain just builds the line_table array for\n        the user-selected spectrum.\n        '''\n\n        #This is the FeLoBAL spectrum, Fig. 10.\n        if spec_num==10:\n            name_str = r'\\textbf{SDSS J235134.38+031757.6, z = 2.230}'\n            line_table = np.zeros(6,dtype=[('NAME','U26'),('LAM_REST','f8'),('LAM_OBS','f8'),('X_DISP','f8'),('Y_DISP','f8')])\n            line_table['NAME'][0],line_table['LAM_REST'][0] = r'\\textbf{Ly}$\\alpha$',1216.25\n            line_table['NAME'][1],line_table['LAM_REST'][1] = r'\\textbf{N V}',1239.85\n            line_table['NAME'][2],line_table['LAM_REST'][2] = r'\\textbf{Si IV+O IV]}',1398.33\n            line_table['NAME'][3],line_table['LAM_REST'][3] = r'\\textbf{C IV}',1546.15\n            line_table['NAME'][4],line_table['LAM_REST'][4] = r'\\textbf{C III]}',1905.97\n            line_table['NAME'][5],line_table['LAM_REST'][5] = r'\\textbf{Mg II}',2800.26\n            for i in range(6):\n                #From the defined rest wavelength and given redshift, find the\n                #observed wavelength.\n                line_table['LAM_OBS'][i] = line_table['LAM_REST'][i] * (1+ z_in)\n                #The exact calculated observed wavelength likely won't be in the data\n                #so we need to find the closest point that is included.\n                idx = np.argmin(np.absolute(line_table['LAM_OBS'][i] - self.lam)) #\n                line_table['X_DISP'][i] = self.lam[idx] #The selected wavelength for the line\n                line_table['Y_DISP'][i] = self.flux[idx] #The flux at that wavelength (hopefully the peak)\n\n        #This is the BAL example spectrum, Fig. 11\n        elif spec_num==11:\n            name_str = r'\\textbf{SDSS J003713.64+241121.5, z = 3.495}'\n            line_table = np.zeros(6,dtype=[('NAME','U26'),('LAM_REST','f8'),('LAM_OBS','f8'),('X_DISP','f8'),('Y_DISP','f8')])\n            line_table['NAME'][0],line_table['LAM_REST'][0] = r'\\textbf{Ly}$\\beta$',1033.03\n            line_table['NAME'][1],line_table['LAM_REST'][1] = r'\\textbf{Ly}$\\alpha$',1216.25\n            line_table['NAME'][2],line_table['LAM_REST'][2] = r'\\textbf{O I}',1305.42\n            line_table['NAME'][3],line_table['LAM_REST'][3] = r'\\textbf{Si IV+O IV]}',1398.33\n            line_table['NAME'][4],line_table['LAM_REST'][4] = r'\\textbf{C IV}',1546.15\n            line_table['NAME'][5],line_table['LAM_REST'][5] = r'\\textbf{C III]}',1905.97\n            for i in range(6):\n                line_table['LAM_OBS'][i] = line_table['LAM_REST'][i] * (1+ z_in)\n                idx = np.argmin(np.absolute(line_table['LAM_OBS'][i] - self.lam))\n                line_table['X_DISP'][i] = self.lam[idx]\n                line_table['Y_DISP'][i] = self.flux[idx]\n\n        #This is the Mg II BAL spectrum, Fig. 12\n        elif spec_num==12:\n            name_str = r'\\textbf{SDSS J212627.22+012321.0, z = 0.944}'\n            line_table = np.zeros(8,dtype=[('NAME','U26'),('LAM_REST','f8'),('LAM_OBS','f8'),('X_DISP','f8'),('Y_DISP','f8')])\n            line_table['NAME'][0],line_table['LAM_REST'][0] = r'\\textbf{Fe II}',2626.92\n            line_table['NAME'][1],line_table['LAM_REST'][1] = r'\\textbf{Mg II}',2800.26\n            line_table['NAME'][2],line_table['LAM_REST'][2] = r'\\textbf{[O II]}',3729.66\n            line_table['NAME'][3],line_table['LAM_REST'][3] = r'\\textbf{H}$\\delta$',4102.73\n            line_table['NAME'][4],line_table['LAM_REST'][4] = r'\\textbf{H}$\\gamma$',4346.42\n            line_table['NAME'][5],line_table['LAM_REST'][5] = r'\\textbf{H}$\\beta$',4853.13\n            line_table['NAME'][6],line_table['LAM_REST'][6] = r'\\textbf{[O III]}',4960.36\n            line_table['NAME'][7],line_table['LAM_REST'][7] = r'\\textbf{[O III]}',5008.22\n            for i in range(8):\n                line_table['LAM_OBS'][i] = line_table['LAM_REST'][i] * (1+ z_in)\n                idx = np.argmin(np.absolute(line_table['LAM_OBS'][i] - self.lam))\n                line_table['X_DISP'][i] = self.lam[idx]\n                line_table['Y_DISP'][i] = self.flux[idx]\n\n        #This is the LyA forest spectrum, Fig. 13\n        elif spec_num==13:\n            name_str = r'\\textbf{SDSS J161016.71+411753.7, z = 5.005}'\n            line_table = np.zeros(6,dtype=[('NAME','U26'),('LAM_REST','f8'),('LAM_OBS','f8'),('X_DISP','f8'),('Y_DISP','f8')])\n            line_table['NAME'][0],line_table['LAM_REST'][0] = r'\\textbf{Ly Limit}',912\n            line_table['NAME'][1],line_table['LAM_REST'][1] = r'\\textbf{Ly}$\\beta$',1033.03\n            line_table['NAME'][2],line_table['LAM_REST'][2] = r'\\textbf{Ly}$\\alpha$',1216.25\n            line_table['NAME'][3],line_table['LAM_REST'][3] = r'\\textbf{O I}',1305.42\n            line_table['NAME'][4],line_table['LAM_REST'][4] = r'\\textbf{Si IV+O IV]}',1398.33\n            line_table['NAME'][5],line_table['LAM_REST'][5] = r'\\textbf{C IV}',1546.15\n            for i in range(6):\n                line_table['LAM_OBS'][i] = line_table['LAM_REST'][i] * (1+ z_in)\n                idx = np.argmin(np.absolute(line_table['LAM_OBS'][i] - self.lam))\n                line_table['X_DISP'][i] = self.lam[idx]\n                line_table['Y_DISP'][i] = self.flux[idx]\n\n\n        #Do the \"make it pretty\" stuff\n        matplotlib.rc('font',size=11)\n        matplotlib.rcParams['text.latex.preamble'] = [r'\\boldmath']\n        fig1,ax1 = plt.subplots(figsize=(10,4))\n        #We want the top and bottom x-axis to be wavelength, but different\n        #reference frames (rest and observed respectively). Twiny() does this.\n        ax1T = ax1.twiny() #This will be the rest wavelength x-axis object\n        if smooth==True: #If smoothed, plot the smoothed on top of the raw flux.\n            self.bflux,self.berr = self.boxcar(self.flux,self.ivar,10,weighted=True)\n            ax1.plot(self.lam,self.flux,color='0.70',linewidth=0.8)\n            ax1.plot(self.lam,self.bflux,color='black',linewidth=0.6)\n        else:\n            ax1.plot(self.lam,self.flux,color='black') #Or just raw flux if unsmoothed.\n        if sky==True: #We can also plot the sky spectrum in green, if selected.\n            if scale_sky==True:\n                #Sky flux is usually much greater than the source flux, so we\n                #can choose to scale it. The sky flux is less important than the\n                #shape of the sky spectrum (to find patterns), so scaling is useful.\n                self.sky = self.data['sky'] / 10.0\n            else:\n                self.sky = self.data['sky']\n            ax1.plot(self.lam,self.sky,color='green',linewidth=0.7,alpha=0.5)\n        if err==True: #And we can also plot the error spectrum in red if selected\n            ax1.plot(self.lam,self.ferr,color='red',linewidth=0.6)\n        ax1.set_xlim((x_lower,x_upper)) #Observerd wavelength x-axis\n        ax1T.set_xlim((x_lower/(1+z_in),x_upper/(1+z_in))) #Rest wavelength x-axis\n        ax1.set_ylim((y_lower,y_upper)) #The y-axis doesn't change.\n        ax1.set_xlabel(r'\\textbf{Observed Frame Wavelength (\\AA)}')\n        ax1T.set_xlabel(r'\\textbf{Rest Frame Wavelength (\\AA)}')\n        ax1.set_ylabel(r'$f_{\\lambda}$ ($10^{-17}$ \\textbf{ergs s}$^{-1}$ \\textbf{cm}$^{-2}$\\,\\textbf{\\AA}$^{-1}$)')\n        #The emission lines defined in the tables above need to be plotted with\n        #marker lines and text. Because emission line redshift and quasar\n        #redshift are always the same due to physical processes, these lines\n        #needed to be hand-modified until they point to the right thing.\n        #EXCEPT in Fig. 10. These lines are plotted to demonstrate how FeLoBAL\n        #features do NOT align with common emission lines.\n        if spec_num==10:\n            ax1.annotate(line_table['NAME'][0],xy=(line_table['X_DISP'][0],line_table['Y_DISP'][0]),\n                         xytext=(-10,30),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            #N V (line_table[1]) is usually blended with LyA, so the labels overlapped\n            #ax1.annotate(line_table['NAME'][1],xy=(line_table['X_DISP'][1],line_table['Y_DISP'][1]),\n                         #xytext=(-31,60),textcoords='offset points',\n                         #bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         #arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.annotate(line_table['NAME'][2],xy=(line_table['X_DISP'][2],line_table['Y_DISP'][2]),\n                         xytext=(-31,60),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.annotate(line_table['NAME'][3],xy=(line_table['X_DISP'][3],line_table['Y_DISP'][3]),\n                         xytext=(-12,25),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.annotate(line_table['NAME'][4],xy=(line_table['X_DISP'][4]+10,line_table['Y_DISP'][4]+1),\n                         xytext=(-13,30),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.annotate(line_table['NAME'][5],xy=(line_table['X_DISP'][5],line_table['Y_DISP'][5]+0.5),\n                         xytext=(-14,50),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            #annotate calls mark the lines. The text call is what puts the\n            #quasar name ('SDSS JHH:MM:SS.SS+DD:MM:SS.S) on the spectrum\n            ax1.text(0.01,0.95,name_str,transform=ax1.transAxes, verticalalignment='top',\n                    bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0))\n        elif spec_num==11:\n            ax1.annotate(line_table['NAME'][0],xy=(line_table['X_DISP'][0],line_table['Y_DISP'][0]),\n                         xytext=(-10,60),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            #The +35,+2 is the hand-modifying part, so the label matches the observed\n            #position of the line in the plot. LyA and C IV are commonly shifted\n            #a small amount from the value calculated using the \"host\" redshift\n            ax1.annotate(line_table['NAME'][1],xy=(line_table['X_DISP'][1]+35,line_table['Y_DISP'][1]+2),\n                         xytext=(-10,18),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.annotate(line_table['NAME'][2],xy=(line_table['X_DISP'][2],line_table['Y_DISP'][2]),\n                         xytext=(-8,20),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.annotate(line_table['NAME'][3],xy=(line_table['X_DISP'][3],line_table['Y_DISP'][3]),\n                         xytext=(-31,60),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.annotate(line_table['NAME'][4],xy=(line_table['X_DISP'][4],line_table['Y_DISP'][4]-2),\n                         xytext=(-12,25),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.annotate(line_table['NAME'][5],xy=(line_table['X_DISP'][5]+10,line_table['Y_DISP'][5]),\n                         xytext=(-13,20),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.text(0.6,0.95,name_str,transform=ax1.transAxes, verticalalignment='top',\n                    bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0))\n        elif spec_num==12:\n            ax1.annotate(line_table['NAME'][0],xy=(line_table['X_DISP'][0],line_table['Y_DISP'][0]),\n                         xytext=(-11,18),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.annotate(line_table['NAME'][1],xy=(line_table['X_DISP'][1]+10,line_table['Y_DISP'][1]+6),\n                         xytext=(-14,20),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.annotate(line_table['NAME'][2],xy=(line_table['X_DISP'][2],line_table['Y_DISP'][2]),\n                         xytext=(-14,20),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            #H delta (line_table[3]) should be visible in the wavelength range,\n            #but the flux was too small to see (looks like noise)\n            #ax1.annotate(line_table['NAME'][3],xy=(line_table['X_DISP'][3],line_table['Y_DISP'][3]),\n                         #xytext=(-31,60),textcoords='offset points',\n                         #bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         #arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.annotate(line_table['NAME'][4],xy=(line_table['X_DISP'][4],line_table['Y_DISP'][4]),\n                         xytext=(-7,25),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.annotate(line_table['NAME'][5],xy=(line_table['X_DISP'][5]+22,line_table['Y_DISP'][5]+2),\n                         xytext=(-8,30),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.annotate('',xy=(line_table['X_DISP'][6],line_table['Y_DISP'][6]),\n                         xytext=(0,89),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.annotate(line_table['NAME'][7],xy=(line_table['X_DISP'][7],line_table['Y_DISP'][7]-2.5),\n                         xytext=(-16,25),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.text(0.01,0.95,name_str,transform=ax1.transAxes, verticalalignment='top',\n                    bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0))\n        elif spec_num==13:\n            ax1.annotate(line_table['NAME'][0],xy=(line_table['X_DISP'][0],line_table['Y_DISP'][0]),\n                         xytext=(-22,30),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.annotate(line_table['NAME'][1],xy=(line_table['X_DISP'][1]+35,line_table['Y_DISP'][1]+2),\n                         xytext=(-10,18),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.annotate(line_table['NAME'][2],xy=(line_table['X_DISP'][2]-10,line_table['Y_DISP'][2]+2),\n                         xytext=(-10,20),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.annotate(line_table['NAME'][3],xy=(line_table['X_DISP'][3],line_table['Y_DISP'][3]),\n                         xytext=(-8,30),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.annotate(line_table['NAME'][4],xy=(line_table['X_DISP'][4]-30,line_table['Y_DISP'][4]+0.5),\n                         xytext=(-31,45),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.annotate(line_table['NAME'][5],xy=(line_table['X_DISP'][5],line_table['Y_DISP'][5]+0.5),\n                         xytext=(-12,30),textcoords='offset points',\n                         bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0),\n                         arrowprops=dict(arrowstyle='-',connectionstyle='arc3,rad=0',color='blue'))\n            ax1.text(0.01,0.95,name_str,transform=ax1.transAxes, verticalalignment='top',\n                    bbox=dict(boxstyle='square,pad=0.2',fc='magenta',alpha=0.0))\n        #Ticks point inward in physics and astronomy\n        #And minor ticks should be displayed\n        ax1.tick_params(axis='both',direction='in')\n        ax1.tick_params(axis='both',which='minor',direction='in')\n        ax1.tick_params(right=True)\n        ax1.tick_params(which='minor',right=True)\n        ax1T.tick_params(direction='in')\n        ax1T.tick_params(which='minor',direction='in')\n        ax1.xaxis.set_minor_locator(ticker.MultipleLocator(100))\n        ax1T.xaxis.set_minor_locator(ticker.MultipleLocator(50))\n        ax1.yaxis.set_major_locator(ticker.MultipleLocator(5))\n        ax1.yaxis.set_minor_locator(ticker.MultipleLocator(1))\n\n        #Show or save?\n        if save==True:\n            fname_out = self.infile.replace('.fits','.eps')\n            fname_out = fname_out.replace('../data/','../plots/')\n            fig1.savefig(fname_out,bbox_inches='tight',pad_inches=0.03,format='eps')\n            plt.close()\n        else:\n            plt.tight_layout()\n            plt.show()\n\n# There are a lot of options here. Use python spec_plot.py -h to see them.\n# This automatically generates the name of the eps plot using the spectrum file\n# name.\nif __name__=='__main__':\n    import argparse\n    parser = argparse.ArgumentParser(description='Plot one of the spectra in Lyke et al. 2020')\n    parser.add_argument('p', type=int, choices=[10,11,12,13], help='Paper figure number')\n    parser.add_argument('-e', '--error', action='store_true',\n                        help='Include the error spectrum in red')\n    parser.add_argument('-k', '--sky', action='store_true',\n                        help='Include the sky spectrum in green')\n    parser.add_argument('-x', '--scale_sky', action='store_true',\n                        help='Scale the sky flux to the quasar flux')\n    parser.add_argument('-s', '--save', action='store_true',\n                        help='Save the plot, without display')\n\n    args = parser.parse_args()\n\n    #Set up the plate-mjd-fiberid combinations with redshifts.\n    spec_to_plot = np.zeros(4,dtype=[('FIG_NUM','i2'),('PMF','U16'),('Z','f8')])\n    spec_to_plot['FIG_NUM'][0],spec_to_plot['PMF'][0],spec_to_plot['Z'][0] = 10,'11278-58395-0576',2.23\n    spec_to_plot['FIG_NUM'][1],spec_to_plot['PMF'][1],spec_to_plot['Z'][1] = 11,'7672-57339-0394',3.495\n    spec_to_plot['FIG_NUM'][2],spec_to_plot['PMF'][2],spec_to_plot['Z'][2] = 12,'9162-58040-0354',0.944\n    spec_to_plot['FIG_NUM'][3],spec_to_plot['PMF'][3],spec_to_plot['Z'][3] = 13,'8528-57896-0104',5.005\n    '''\n    NOTE: The spectrum for 8528-57896-0104 is not the PRIMARY record in DR16Q. That's listed under: 6044-56090-0418\n          The spectra, however, are pretty identical.\n    NOTE: The spectrum for 11278-58395-0576 is not the PRIMARY record in DR16Q. That's listed under: 8741-57390-0450\n          The spectra is identical, but that record has a Z_VI of 2.43. We are going to trust Vivek at Z = 2.23\n    '''\n    #This chooses which of the four spectra to use, then grabs the redshift.\n    w = np.where(spec_to_plot['FIG_NUM']==args.p)[0]\n    red = spec_to_plot['Z'][w]\n    #Make the spectrum filename.\n    spec_name = '../data/spec-{}.fits'.format(spec_to_plot['PMF'][w[0]])\n    spec = spectrum(spec_name) #Load the spectrum using the class functionality.\n    #Use the class attribute for spectra to make a 10x4 plot.\n    spec.paper_plot_small(red,args.p,smooth=True,err=args.error,sky=args.sky,\n                        scale_sky=args.scale_sky,save=args.save)\n", "meta": {"hexsha": "eff952e24d2f8b8044b9d611e7a82aca59b79571", "size": 27634, "ext": "py", "lang": "Python", "max_stars_repo_path": "plot_progs/spec_plot.py", "max_stars_repo_name": "bradlyke/dr16q", "max_stars_repo_head_hexsha": "5645491bc05806c5b956e76c5bcec939722c065f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-21T23:12:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-23T03:54:06.000Z", "max_issues_repo_path": "plot_progs/spec_plot.py", "max_issues_repo_name": "bradlyke/dr16q", "max_issues_repo_head_hexsha": "5645491bc05806c5b956e76c5bcec939722c065f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plot_progs/spec_plot.py", "max_forks_repo_name": "bradlyke/dr16q", "max_forks_repo_head_hexsha": "5645491bc05806c5b956e76c5bcec939722c065f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.1160092807, "max_line_length": 126, "alphanum_fraction": 0.5956068611, "include": true, "reason": "import numpy", "num_tokens": 7432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.2877678218692626, "lm_q1q2_score": 0.1539841092915451}}
{"text": "\"\"\"Contains classes to represent non-equilibrium ionization simulations.\"\"\"\n\n__all__ = [\"NEI\", \"NEIError\", \"SimulationResults\"]\n\n\nfrom typing import Callable, Dict, List, Optional, Union\n\nimport astropy.units as u\nimport numpy as np\nfrom scipy import interpolate, optimize\n\nfrom plasmapy_nei.eigen import EigenData, eigen_data_dict\n\ntry:\n    from plasmapy.atomic import IonizationStates, atomic_number\nexcept ImportError:\n    from plasmapy.particles import IonizationStates, atomic_number\n\nimport warnings\n\n# TODO: Allow this to keep track of velocity and position too, and\n# eventually to have density and temperature be able to be functions of\n# position.  (and more complicated expressions for density and\n# temperature too)\n\n# TODO: Expand Simulation docstring\n\n\n# TODO: Include the methods in the original Visualize class which is a\n#       subclass of NEI in the NEI-modeling/NEI repo. These were deleted\n#       temporarily to make it possible to get the NEI class itself\n#       adapted into this package.\n\n\n# TODO: In this file and test_nei.py, there are a few places with\n#       initial.ionic_fractions.keys(), where initial is an instance\n#       of IonizationStates.  This workaround exists because I forgot\n#       to put in an `elements` attribute in IonizationStates, and\n#       should be corrected.\n\n\nclass NEIError(Exception):\n    \"\"\"For when there are errors in setting up or performing NEI simulations.\"\"\"\n\n    pass\n\n\nclass SimulationResults:\n    \"\"\"\n    Results from a non-equilibrium ionization simulation.\n\n    Parameters\n    ----------\n    initial: plasmapy.atomic.IonizationStates\n        The ``IonizationStates`` instance representing the ionization\n        states of different elements and plasma properties as the\n        initial conditions.\n\n    n_init: astropy.units.Quantity\n        The initial number density scaling factor.\n\n    T_e_init: astropy.units.Quantity\n        The initial electron temperature.\n\n    max_steps: int\n        The maximum number of time steps that the simulation can take\n        before stopping.\n\n    time_start: astropy.units.Quantity\n        The time at the start of the simulation.\n\n    \"\"\"\n\n    def __init__(\n        self,\n        initial: IonizationStates,\n        n_init: u.Quantity,\n        T_e_init: u.Quantity,\n        max_steps: int,\n        time_start: u.Quantity,\n    ):\n\n        self._elements = list(initial.ionic_fractions.keys())\n        self._abundances = initial.abundances\n        self._max_steps = max_steps\n\n        self._nstates = {elem: atomic_number(elem) + 1 for elem in self.elements}\n\n        self._ionic_fractions = {\n            elem: np.full((max_steps + 1, self.nstates[elem]), np.nan, dtype=np.float64)\n            for elem in self.elements\n        }\n\n        self._number_densities = {\n            elem: np.full((max_steps + 1, self.nstates[elem]), np.nan, dtype=np.float64)\n            * u.cm ** -3\n            for elem in self.elements\n        }\n\n        self._n_elem = {\n            elem: np.full(max_steps + 1, np.nan) * u.cm ** -3 for elem in self.elements\n        }\n\n        self._n_e = np.full(max_steps + 1, np.nan) * u.cm ** -3\n        self._T_e = np.full(max_steps + 1, np.nan) * u.K\n        self._time = np.full(max_steps + 1, np.nan) * u.s\n\n        self._index = 0\n\n        self._assign(\n            new_time=time_start,\n            new_ionfracs=initial.ionic_fractions,\n            new_n=n_init,\n            new_T_e=T_e_init,\n        )\n\n    def _assign(\n        self,\n        new_time: u.Quantity,\n        new_ionfracs: Dict[str, np.ndarray],\n        new_n: u.Quantity,\n        new_T_e: u.Quantity,\n    ):\n        \"\"\"\n        Store results from a time step of a non-equilibrium ionization\n        time advance in the `~plasmapy_nei.classes.NEI` class.\n\n        Parameters\n        ----------\n        new_time\n            The time associated with this time step.\n\n        new_ionfracs: dict\n            The new ionization fractions for this time step.  The keys\n            of this `dict` are the atomic symbols of the elements being\n            tracked, and with the corresponding value being an\n            ``numpy.ndarray`` representing the ionic fractions.  Each\n            element's array must have a length of the atomic number plus\n            one, and be normalized to one with all values between zero\n            and one.\n\n        new_n\n            The new number density scaling factor for this time step.\n            The number densities of each ionic species will be the\n            product of this scaling factor, the element's abundance, and\n            the ionic fraction given in ``new_ionfracs``.\n\n        new_T_e\n            The new electron temperature.\n\n        \"\"\"\n\n        try:\n            index = self._index\n            elements = self.elements\n            self._time[index] = new_time\n            self._T_e[index] = new_T_e\n\n            for elem in elements:\n                self._ionic_fractions[elem][index, :] = new_ionfracs[elem][:]\n\n            # Calculate elemental and ionic number densities\n            n_elem = {elem: new_n * self.abundances[elem] for elem in elements}\n            number_densities = {\n                elem: n_elem[elem] * new_ionfracs[elem] for elem in elements\n            }\n\n            # Calculate the electron number density\n            n_e = 0.0 * u.cm ** -3\n            for elem in elements:\n                integer_charges = np.linspace(\n                    0, self.nstates[elem] - 1, self.nstates[elem]\n                )\n                n_e += np.sum(number_densities[elem] * integer_charges)\n\n            # Assign densities\n            self._n_e[index] = n_e\n            for elem in elements:\n                self._n_elem[elem][index] = n_elem[elem]\n                self._number_densities[elem][index, :] = number_densities[elem]\n\n        except Exception as exc:\n            raise NEIError(\n                f\"Unable to assign parameters to Simulation instance \"\n                f\"for index {index} at time = {new_time}.  The \"\n                f\"parameters are new_n = {new_n}, new_T_e = {new_T_e}, \"\n                f\"and new_ionic_fractions = {new_ionfracs}.\"\n            ) from exc\n        finally:\n            self._index += 1\n\n    def _cleanup(self):\n        \"\"\"\n        Clean up this class after the simulation is complete.\n\n        This method removes the excess elements from each array that\n        did not end up getting used for a time step in the simulation\n        and sets the ``last_step`` attribute.\n\n        \"\"\"\n        nsteps = self._index\n\n        self._n_e = self._n_e[0:nsteps]\n        self._T_e = self._T_e[0:nsteps]\n        self._time = self._time[0:nsteps]\n\n        for element in self.elements:\n            self._ionic_fractions[element] = self._ionic_fractions[element][0:nsteps, :]\n            self._number_densities[element] = self._number_densities[element][\n                0:nsteps, :\n            ]\n\n        self._last_step = nsteps - 1\n\n        self._index = None\n\n    @property\n    def max_steps(self) -> int:\n        \"\"\"\n        The maximum number of time steps allowed for this simulation.\n        \"\"\"\n        return self._max_steps\n\n    @property\n    def last_step(self) -> int:\n        \"\"\"The time index of the last step.\"\"\"\n        return self._last_step\n\n    @property\n    def nstates(self) -> Dict[str, int]:\n        \"\"\"\n        Return the dictionary containing atomic symbols as keys and the\n        number of ionic species for the corresponding element as the\n        value.\n        \"\"\"\n        return self._nstates\n\n    @property\n    def elements(self) -> List[str]:\n        \"\"\"The elements modeled by this simulation.\"\"\"\n        return self._elements\n\n    @property\n    def abundances(self) -> Dict[str, float]:\n        \"\"\"\n        The relative elemental abundances of the elements modeled in\n        this simulation.\n\n        The keys are the atomic symbols and the values are a `float`\n        representing that element's elemental abundance.\n        \"\"\"\n        return self._abundances\n\n    @property\n    def ionic_fractions(self) -> Dict[str, np.ndarray]:\n        \"\"\"\n        Return the ionic fractions over the course of the simulation.\n\n        The keys of this dictionary are atomic symbols.  The values are\n        2D arrays where the first index refers to the time step and the\n        second index refers to the integer charge.\n        \"\"\"\n        return self._ionic_fractions\n\n    @property\n    def number_densities(self) -> Dict[str, u.Quantity]:\n        \"\"\"\n        Return the number densities over the course of the simulation.\n\n        The keys of ``number_densities`` are atomic symbols.  The values\n        are 2D arrays with units of number density where the first index\n        refers to the time step and the second index is the integer\n        charge.\n\n        \"\"\"\n        return self._number_densities\n\n    @property\n    def n_elem(self) -> Dict[str, u.Quantity]:\n        \"\"\"\n        The number densities of each element over the course of the\n        simulation.\n\n        The keys of ``n_elem`` are atomic symbols.  The values are 1D\n        arrays with units of number density where the index refers to\n        the time step.\n\n        \"\"\"\n        return self._n_elem\n\n    @property\n    def n_e(self) -> u.Quantity:\n        \"\"\"\n        The electron number density over the course of the simulation in\n        units of number density.\n\n        The index of this array corresponds to the time step.\n        \"\"\"\n        return self._n_e\n\n    @property\n    def T_e(self) -> u.Quantity:\n        \"\"\"\n        The electron temperature over the course of the simulation in\n        kelvin.\n\n        The index of this array corresponds to the time step.\n        \"\"\"\n        return self._T_e\n\n    @property\n    def time(self) -> u.Quantity:\n        \"\"\"\n        The time for each time step over the course of the simulation\n        in units of seconds.\n        \"\"\"\n        return self._time\n\n\nclass NEI:\n    r\"\"\"\n    Perform and analyze a non-equilibrium ionization simulation.\n\n    Parameters\n    ----------\n    inputs\n\n    T_e: astropy.units.Quantity or callable\n        The electron temperature, which may be a constant, an array of\n        temperatures corresponding to the times in `time_input`, or a\n        function that yields the temperature as a function of time.\n\n    n: astropy.units.Quantity or callable\n        The number density multiplicative factor.  The number density of\n        each element will be ``n`` times the abundance given in\n        ``abundances``.  For example, if ``abundance['H'] = 1``, then this\n        will correspond to the number density of hydrogen (including\n        neutral hydrogen and protons).  This factor may be a constant,\n        an array of number densities over time, or a function that\n        yields a number density as a function of time.\n\n    time_input: astropy.units.Quantity, optional\n        An array containing the times associated with ``n`` and ``T_e`` in\n        units of time.\n\n    time_start: astropy.units.Quantity, optional\n        The start time for the simulation.  If density and/or\n        temperature are given by arrays, then this argument must be\n        greater than ``time_input[0]``.  If this argument is not supplied,\n        then ``time_start`` defaults to ``time_input[0]`` (if given) and\n        zero seconds otherwise.\n\n    time_max: astropy.units.Quantity\n        The maximum time for the simulation.  If density and/or\n        temperature are given by arrays, then this argument must be less\n        than ``time_input[-1]``.\n\n    max_steps: `int`\n        The maximum number of time steps to be taken during a\n        simulation.\n\n    dt: astropy.units.Quantity\n        The time step.  If ``adapt_dt`` is `False`, then ``dt`` is the\n        time step for the whole simulation.\n\n    dt_max: astropy.units.Quantity\n        The maximum time step to be used with an adaptive time step.\n\n    dt_min: astropy.units.Quantity\n        The minimum time step to be used with an adaptive time step.\n\n    adapt_dt: `bool`\n        If `True`, change the time step based on the characteristic\n        ionization and recombination time scales and change in\n        temperature.  Not yet implemented.\n\n    safety_factor: `float` or `int`\n        A multiplicative factor to multiply by the time step when\n        ``adapt_dt`` is `True`.  Lower values improve accuracy, whereas\n        higher values reduce computational time.  Not yet implemented.\n\n    tol: float\n        The absolute tolerance to be used in comparing ionic fractions.\n\n    verbose: bool, optional\n        A flag stating whether or not to print out information for every\n        time step. Setting ``verbose`` to `True` is useful for testing.\n        Defaults to `False`.\n\n    abundances: dict\n\n    Examples\n    --------\n\n    >>> import numpy as np\n    >>> import astropy.units as u\n\n    >>> inputs = {'H': [0.9, 0.1], 'He': [0.9, 0.099, 0.001]}\n    >>> abund = {'H': 1, 'He': 0.085}\n    >>> n = u.Quantity([1e9, 1e8], u.cm**-3)\n    >>> T_e = np.array([10000, 40000]) * u.K\n    >>> time = np.array([0, 300]) * u.s\n    >>> dt = 0.25 * u.s\n\n    The initial conditions can be accessed using the initial attribute.\n\n    >>> sim = NEI(inputs=inputs, abundances=abund, n=n, T_e=T_e, time_input=time, adapt_dt=False, dt=dt)\n\n    After having inputted all of the necessary information, we can run\n    the simulation.\n\n    >>> results = sim.simulate()\n\n    The initial results are stored in the ``initial`` attribute.\n\n    >>> sim.initial.ionic_fractions['H']\n    array([0.9, 0.1])\n\n    The final results can be access with the ``final`` attribute.\n\n    >>> sim.final.ionic_fractions['H']\n    array([0.16665179, 0.83334821])\n    >>> sim.final.ionic_fractions['He']\n    array([0.88685261, 0.11218358, 0.00096381])\n    >>> sim.final.T_e\n    <Quantity 40000. K>\n\n    Both ``initial`` and ``final`` are instances of the ``IonizationStates``\n    class.\n\n    Notes\n    -----\n    The ionization and recombination rates are from Chianti version\n    8.7.  These rates include radiative and dielectronic recombination.\n    Photoionization is not included.\n    \"\"\"\n\n    def __init__(\n        self,\n        inputs,\n        abundances: Union[Dict, str] = None,\n        T_e: Union[Callable, u.Quantity] = None,\n        n: Union[Callable, u.Quantity] = None,\n        time_input: u.Quantity = None,\n        time_start: u.Quantity = None,\n        time_max: u.Quantity = None,\n        max_steps: Union[int, np.integer] = 10000,\n        tol: Union[int, float] = 1e-15,\n        dt: u.Quantity = None,\n        dt_max: u.Quantity = np.inf * u.s,\n        dt_min: u.Quantity = 0 * u.s,\n        adapt_dt: bool = None,\n        safety_factor: Union[int, float] = 1,\n        verbose: bool = False,\n    ):\n\n        try:\n\n            self.time_input = time_input\n            self.time_start = time_start\n            self.time_max = time_max\n            self.T_e_input = T_e\n            self.n_input = n\n            self.max_steps = max_steps\n            self.dt_input = dt\n\n            if self.dt_input is None:\n                self._dt = self.time_max / max_steps\n            else:\n                self._dt = self.dt_input\n\n            self.dt_min = dt_min\n            self.dt_max = dt_max\n            self.adapt_dt = adapt_dt\n            self.safety_factor = safety_factor\n            self.verbose = verbose\n\n            T_e_init = self.electron_temperature(self.time_start)\n            n_init = self.hydrogen_number_density(self.time_start)\n\n            self.initial = IonizationStates(\n                inputs=inputs,\n                abundances=abundances,\n                T_e=T_e_init,\n                n=n_init,\n                tol=tol,\n            )\n\n            self.tol = tol\n\n            # TODO: Update IonizationStates in PlasmaPy to have elements attribute\n\n            self.elements = list(self.initial.ionic_fractions.keys())\n\n            if \"H\" not in self.elements:\n                raise NEIError(\"Must have H in elements\")\n\n            self.abundances = self.initial.abundances\n\n            self._eigen_data_dict = eigen_data_dict\n\n            if self.T_e_input is not None and not isinstance(inputs, dict):\n                for element in self.initial.ionic_fractions.keys():\n                    self.initial.ionic_fractions[element] = self.eigen_data_dict[\n                        element\n                    ].equilibrium_state(T_e_init.value)\n\n            self._temperature_grid = self._eigen_data_dict[\n                self.elements[0]\n            ].temperature_grid\n\n            self._get_temperature_index = self._eigen_data_dict[\n                self.elements[0]\n            ]._get_temperature_index\n\n            self._results = None\n\n        except Exception as e:\n            raise NEIError(\n                f\"Unable to create NEI object for:\\n\"\n                f\"     inputs = {inputs}\\n\"\n                f\" abundances = {abundances}\\n\"\n                f\"        T_e = {T_e}\\n\"\n                f\"          n = {n}\\n\"\n                f\" time_input = {time_input}\\n\"\n                f\" time_start = {time_start}\\n\"\n                f\"   time_max = {time_max}\\n\"\n                f\"  max_steps = {max_steps}\\n\"\n            ) from e\n\n    def equil_ionic_fractions(\n        self,\n        T_e: u.Quantity = None,\n        time: u.Quantity = None,\n    ) -> Dict[str, np.ndarray]:\n        \"\"\"\n        Return the equilibrium ionic fractions for a temperature or at\n        a given time.\n\n        Parameters\n        ----------\n        T_e: astropy.units.Quantity, optional\n            The electron temperature in units that can be converted to\n            kelvin.\n\n        time: astropy.units.Quantity, optional\n            The time in units that can be converted to seconds.\n\n        Returns\n        -------\n        equil_ionfracs: `dict`\n            The equilibrium ionic fractions for the elements contained\n            within this class\n\n        Notes\n        -----\n        Only one of ``T_e`` and ``time`` may be included as an argument.\n        If neither ``T_e`` or ``time`` is provided and the temperature\n        for the simulation is given by a constant, the this method will\n        assume that ``T_e`` is the temperature of the simulation.\n        \"\"\"\n\n        if T_e is not None and time is not None:\n            raise NEIError(\"Only one of T_e and time may be an argument.\")\n\n        if T_e is None and time is None:\n            if self.T_e_input.isscalar:\n                T_e = self.T_e_input\n            else:\n                raise NEIError\n\n        try:\n            T_e = T_e.to(u.K) if T_e is not None else None\n            time = time.to(u.s) if time is not None else None\n        except Exception as exc:\n            raise NEIError(\"Invalid input to equilibrium_ionic_fractions.\") from exc\n\n        if time is not None:\n            T_e = self.electron_temperature(time)\n\n        if not T_e.isscalar:\n            raise NEIError(\"Need scalar input for equil_ionic_fractions.\")\n\n        equil_ionfracs = {}\n        for element in self.elements:\n            equil_ionfracs[element] = self.eigen_data_dict[element].equilibrium_state(\n                T_e.value\n            )\n\n        return equil_ionfracs\n\n    @property\n    def elements(self) -> List[str]:\n        \"\"\"A `list` of the elements.\"\"\"\n        return self._elements\n\n    @elements.setter\n    def elements(self, elements):\n        # TODO: Update this\n        self._elements = elements\n\n    @property\n    def abundances(self) -> Dict[str, Union[float, int]]:\n        \"\"\"Return the abundances.\"\"\"\n        return self._abundances\n\n    @abundances.setter\n    def abundances(self, abund: Dict[Union[str, int], Union[float, int]]):\n\n        # TODO: Update initial, etc. when abundances is updated. The\n        # checks within IonizationStates will also be checks for\n\n        # TODO: Update initial and other attributes when abundances is\n        # updated.\n\n        self._abundances = abund\n\n    @property\n    def tol(self) -> float:\n        \"\"\"\n        The tolerance for comparisons between different ionization\n        states.\n        \"\"\"\n        return self._tol\n\n    @tol.setter\n    def tol(self, value: Union[float, int]):\n        try:\n            value = float(value)\n        except Exception as exc:\n            raise TypeError(f\"Invalid tolerance: {value}\") from exc\n        if not 0 <= value < 1:\n            raise ValueError(\"Need 0 <= tol < 1.\")\n        self._tol = value\n\n    @property\n    def time_input(self) -> u.s:\n        return self._time_input\n\n    @time_input.setter\n    def time_input(self, times: u.s):\n        if times is None:\n            self._time_input = None\n        elif isinstance(times, u.Quantity):\n            if times.isscalar:\n                raise ValueError(\"time_input must be an array.\")\n            try:\n                times = times.to(u.s)\n            except u.UnitConversionError:\n                raise u.UnitsError(\"time_input must have units of seconds.\") from None\n            if not np.all(times[1:] > times[:-1]):\n                raise ValueError(\"time_input must monotonically increase.\")\n            self._time_input = times\n        else:\n            raise TypeError(\"Invalid time_input.\")\n\n    @property\n    def time_start(self) -> u.s:\n        \"\"\"The start time of the simulation.\"\"\"\n        return self._time_start\n\n    @time_start.setter\n    def time_start(self, time: u.s):\n        if time is None:\n            self._time_start = 0.0 * u.s\n        elif isinstance(time, u.Quantity):\n            if not time.isscalar:\n                raise ValueError(\"time_start must be a scalar\")\n            try:\n                time = time.to(u.s)\n            except u.UnitConversionError:\n                raise u.UnitsError(\"time_start must have units of seconds\") from None\n            if (\n                hasattr(self, \"_time_max\")\n                and self._time_max is not None\n                and self._time_max <= time\n            ):\n                raise ValueError(\"Need time_start < time_max.\")\n            if self.time_input is not None and self.time_input.min() > time:\n                raise ValueError(\"time_start must be less than min(time_input)\")\n            self._time_start = time\n        else:\n            raise TypeError(\"Invalid time_start.\") from None\n\n    @property\n    def time_max(self) -> u.s:\n        \"\"\"The maximum time allowed for the simulation.\"\"\"\n        return self._time_max\n\n    @time_max.setter\n    def time_max(self, time: u.s):\n        if time is None:\n            self._time_max = (\n                self.time_input[-1] if self.time_input is not None else np.inf * u.s\n            )\n        elif isinstance(time, u.Quantity):\n            if not time.isscalar:\n                raise ValueError(\"time_max must be a scalar\")\n            try:\n                time = time.to(u.s)\n            except u.UnitConversionError:\n                raise u.UnitsError(\"time_max must have units of seconds\") from None\n            if (\n                hasattr(self, \"_time_start\")\n                and self._time_start is not None\n                and self._time_start >= time\n            ):\n                raise ValueError(\"time_max must be greater than time_start\")\n            self._time_max = time\n        else:\n            raise TypeError(\"Invalid time_max.\") from None\n\n    @property\n    def adapt_dt(self) -> Optional[bool]:\n        \"\"\"\n        Return `True` if the time step is set to be adaptive, `False`\n        if the time step is set to not be adapted, and `None` if this\n        attribute was not set.\n        \"\"\"\n        return self._adapt_dt\n\n    @adapt_dt.setter\n    def adapt_dt(self, choice: Optional[bool]):\n        if choice is None:\n            self._adapt_dt = True if self.dt_input is None else False\n        elif choice is True or choice is False:\n            self._adapt_dt = choice\n        else:\n            raise TypeError(\"Invalid value for adapt_dt\")\n\n    @property\n    def dt_input(self) -> u.s:\n        \"\"\"Return the inputted time step.\"\"\"\n        return self._dt_input\n\n    @dt_input.setter\n    def dt_input(self, dt: u.s):\n        if dt is None:\n            self._dt_input = None\n        elif isinstance(dt, u.Quantity):\n            try:\n                dt = dt.to(u.s)\n                if dt > 0 * u.s:\n                    self._dt_input = dt\n            except (AttributeError, u.UnitConversionError):\n                raise NEIError(\"Invalid dt.\")\n\n    @property\n    def dt_min(self) -> u.s:\n        \"\"\"The minimum time step.\"\"\"\n        return self._dt_min\n\n    @dt_min.setter\n    def dt_min(self, value: u.s):\n        if not isinstance(value, u.Quantity):\n            raise TypeError(\"dt_min must be a Quantity.\")\n        try:\n            value = value.to(u.s)\n        except u.UnitConversionError as exc:\n            raise u.UnitConversionError(\"Invalid units for dt_min.\") from exc\n        if (\n            hasattr(self, \"_dt_input\")\n            and self.dt_input is not None\n            and self.dt_input < value\n        ):\n            raise ValueError(\"dt_min cannot exceed the inputted time step.\")\n        if hasattr(self, \"_dt_max\") and self.dt_max < value:\n            raise ValueError(\"dt_min cannot exceed dt_max.\")\n        self._dt_min = value\n\n    @property\n    def dt_max(self) -> u.s:\n        return self._dt_max\n\n    @dt_max.setter\n    def dt_max(self, value: u.s):\n        if not isinstance(value, u.Quantity):\n            raise TypeError(\"dt_max must be a Quantity.\")\n        try:\n            value = value.to(u.s)\n        except u.UnitConversionError as exc:\n            raise u.UnitConversionError(\"Invalid units for dt_max.\") from exc\n        if (\n            hasattr(self, \"_dt_input\")\n            and self.dt_input is not None\n            and self.dt_input > value\n        ):\n            raise ValueError(\"dt_max cannot be less the inputted time step.\")\n        if hasattr(self, \"_dt_min\") and self.dt_min > value:\n            raise ValueError(\"dt_min cannot exceed dt_max.\")\n        self._dt_max = value\n\n    @property\n    def safety_factor(self):\n        \"\"\"\n        The multiplicative factor that the time step is to be multiplied\n        by when using an adaptive time step.\n        \"\"\"\n        return self._safety_factor\n\n    @safety_factor.setter\n    def safety_factor(self, value):\n        if not isinstance(value, (float, np.float64, np.integer, int)):\n            raise TypeError\n        if 1e-3 <= value <= 1e3:\n            self._safety_factor = value\n        else:\n            raise NEIError(\"Invalid safety factor.\")\n\n    @property\n    def verbose(self) -> bool:\n        \"\"\"\n        Return `True` if verbose output during a simulation is\n        requested, and `False` otherwise.\n        \"\"\"\n        return self._verbose\n\n    @verbose.setter\n    def verbose(self, choice: bool):\n        if choice is True or choice is False:\n            self._verbose = choice\n        else:\n            raise TypeError(\"Invalid choice for verbose.\")\n\n    @u.quantity_input\n    def in_time_interval(self, time: u.s, buffer: u.s = 1e-9 * u.s):\n        \"\"\"\n        Return `True` if the ``time`` is between ``time_start - buffer``\n        and ``time_max + buffer`` , and `False` otherwise.\n\n        Raises\n        ------\n        TypeError\n            If ``time`` or ``buffer`` is not a ``astropy.units.Quantity``\n\n        astropy.units.UnitsError\n            If ``time`` or ``buffer`` is not in units of time.\n\n        \"\"\"\n        return self.time_start - buffer <= time <= self.time_max + buffer\n\n    @property\n    def max_steps(self) -> int:\n        \"\"\"\n        The maximum number of steps that a simulation will be allowed\n        to take.\n        \"\"\"\n        return self._max_steps\n\n    @max_steps.setter\n    def max_steps(self, n: int):\n        if isinstance(n, (int, np.integer)) and 0 < n <= 1000000:\n            self._max_steps = n\n        else:\n            raise TypeError(\n                \"max_steps must be an integer with 0 < max_steps <= 1000000\"\n            )\n\n    @property\n    def T_e_input(self) -> Union[u.Quantity, Callable]:\n        \"\"\"\n        The temperature input.\n        \"\"\"\n        return self._T_e_input\n\n    @T_e_input.setter\n    def T_e_input(self, T_e: Optional[Union[Callable, u.Quantity]]):\n        \"\"\"Set the input electron temperature.\"\"\"\n        if isinstance(T_e, u.Quantity):\n            try:\n                T_e = T_e.to(u.K, equivalencies=u.temperature_energy())\n            except u.UnitConversionError:\n                raise u.UnitsError(\"Invalid electron temperature.\") from None\n            if T_e.isscalar:\n                self._T_e_input = T_e\n                self._electron_temperature = lambda time: T_e\n            else:\n                if self._time_input is None:\n                    raise TypeError(\"Must define time_input prior to T_e for an array.\")\n                time_input = self.time_input\n                if len(time_input) != len(T_e):\n                    raise ValueError(\"len(T_e) not equal to len(time_input).\")\n                f = interpolate.interp1d(\n                    time_input.value,\n                    T_e.value,\n                    bounds_error=False,\n                    fill_value=\"extrapolate\",\n                )\n                self._electron_temperature = lambda time: f(time.value) * u.K\n                self._T_e_input = T_e\n        elif callable(T_e):\n            if self.time_start is not None:\n                try:\n                    T_e(self.time_start).to(u.K)\n                    T_e(self.time_max).to(u.K)\n                except Exception:\n                    raise ValueError(\"Invalid electron temperature function.\")\n            self._T_e_input = T_e\n            self._electron_temperature = T_e\n        elif T_e is None:\n            self._electron_temperature = lambda: None\n        else:\n            raise TypeError(\"Invalid T_e\")\n\n    def electron_temperature(self, time: u.Quantity) -> u.Quantity:\n        try:\n            if not self.in_time_interval(time):\n                warnings.warn(\n                    f\"{time} is not in the simulation time interval:\"\n                    f\"[{self.time_start}, {self.time_max}]. \"\n                    f\"May be extrapolating temperature.\"\n                )\n            T_e = self._electron_temperature(time.to(u.s))\n            if np.isnan(T_e) or np.isinf(T_e) or T_e < 0 * u.K:\n                raise NEIError(f\"T_e = {T_e} at time = {time}.\")\n            return T_e\n        except Exception as exc:\n            raise NEIError(\n                f\"Unable to calculate a valid electron temperature \" f\"for time {time}\"\n            ) from exc\n\n    @property\n    def n_input(self) -> u.Quantity:\n        \"\"\"The number density factor input.\"\"\"\n        if \"H\" in self.elements:\n            return self._n_input\n        else:\n            raise ValueError\n\n    @n_input.setter\n    def n_input(self, n: u.Quantity):\n        if isinstance(n, u.Quantity):\n            try:\n                n = n.to(u.cm ** -3)\n            except u.UnitConversionError:\n                raise u.UnitsError(\"Invalid hydrogen density.\")\n            if n.isscalar:\n                self._n_input = n\n                self.hydrogen_number_density = lambda time: n\n            else:\n                if self._time_input is None:\n                    raise TypeError(\"Must define time_input prior to n for an array.\")\n                time_input = self.time_input\n                if len(time_input) != len(n):\n                    raise ValueError(\"len(n) is not equal to len(time_input).\")\n                f = interpolate.interp1d(\n                    time_input.value,\n                    n.value,\n                    bounds_error=False,\n                    fill_value=\"extrapolate\",\n                )\n                self._hydrogen_number_density = lambda time: f(time.value) * u.cm ** -3\n                self._n_input = n\n        elif callable(n):\n            if self.time_start is not None:\n                try:\n                    n(self.time_start).to(u.cm ** -3)\n                    n(self.time_max).to(u.cm ** -3)\n                except Exception:\n                    raise ValueError(\"Invalid number density function.\")\n            self._n_input = n\n            self._hydrogen_number_density = n\n        elif n is None:\n            self._hydrogen_number_density = lambda: None\n        else:\n            raise TypeError(\"Invalid n.\")\n\n    def hydrogen_number_density(self, time: u.Quantity) -> u.Quantity:\n        try:\n            time = time.to(u.s)\n        except (AttributeError, u.UnitsError):\n            raise NEIError(\"Invalid time in hydrogen_density\")\n        return self._hydrogen_number_density(time)\n\n    @property\n    def eigen_data_dict(self) -> Dict[str, EigenData]:\n        \"\"\"\n        Return a `dict` containing `~plasmapy_nei.eigen.EigenData` instances\n        for each element.\n        \"\"\"\n        return self._eigen_data_dict\n\n    @property\n    def initial(self) -> IonizationStates:\n        \"\"\"\n        Return the ionization states of the plasma at the beginning of\n        the simulation.\n        \"\"\"\n        return self._initial\n\n    @initial.setter\n    def initial(self, initial_states: IonizationStates):\n        if isinstance(initial_states, IonizationStates):\n            self._initial = initial_states\n            self._elements = (\n                initial_states.ionic_fractions.keys()\n            )  # TODO IonizationStates\n        elif initial_states is None:\n            self._ionstates = None\n        else:\n            raise TypeError(\"Expecting an IonizationStates instance.\")\n\n    @property\n    def results(self) -> SimulationResults:\n        \"\"\"\n        Return the `~plasmapy_nei.nei.SimulationResults` class instance that\n        corresponds to the simulation results.\n\n        \"\"\"\n        if self._results is not None:\n            return self._results\n        else:\n            raise AttributeError(\"The simulation has not yet been performed.\")\n\n    @property\n    def final(self) -> IonizationStates:\n        \"\"\"\n        Return the ionization states of the plasma at the end of the\n        simulation.\n        \"\"\"\n        try:\n            return self._final\n        except AttributeError:\n            raise NEIError(\"The simulation has not yet been performed.\") from None\n\n    def _initialize_simulation(self):\n\n        self._results = SimulationResults(\n            initial=self.initial,\n            n_init=self.hydrogen_number_density(self.time_start),\n            T_e_init=self.electron_temperature(self.time_start),\n            max_steps=self.max_steps,\n            time_start=self.time_start,\n        )\n        self._old_time = self.time_start.to(u.s)\n        self._new_time = self.time_start.to(u.s)\n\n    def simulate(self) -> SimulationResults:\n        \"\"\"\n        Perform a non-equilibrium ionization simulation.\n\n        Returns\n        -------\n        results: `~plasmapy_nei.classes.Simulation`\n            The results from the simulation (which are also stored in\n            the ``results`` attribute of the `~plasmapy_nei.nei.NEI`\n            instance this method was called from.\n\n        \"\"\"\n\n        self._initialize_simulation()\n\n        for step in range(self.max_steps):\n            try:\n                self.set_timestep()\n                self.time_advance()\n            except StopIteration:\n                break\n            except Exception as exc:\n                raise NEIError(f\"Unable to complete simulation.\") from exc\n\n        self._finalize_simulation()\n\n        # Is there a way to use the inspect package or something similar\n        # to only return self.results if it is in an expression where\n\n        return self.results\n\n    def _finalize_simulation(self):\n        self._results._cleanup()\n\n        final_ionfracs = {\n            element: self.results.ionic_fractions[element][-1, :]\n            for element in self.elements\n        }\n\n        self._final = IonizationStates(\n            inputs=final_ionfracs,\n            abundances=self.abundances,\n            n=np.sum(self.results.number_densities[\"H\"][-1, :]),  # modify this later?,\n            T_e=self.results.T_e[-1],\n            tol=1e-6,\n        )\n\n        if not np.isclose(self.time_max / u.s, self.results.time[-1] / u.s):\n            warnings.warn(\n                f\"The simulation ended at {self.results.time[-1]}, \"\n                f\"which is prior to time_max = {self.time_max}.\"\n            )\n\n    def _set_adaptive_timestep(self):\n        \"\"\"Adapt the time step.\"\"\"\n\n        t = self._new_time if hasattr(self, \"_new_time\") else self.t_start\n\n        # We need to guess the timestep in order to narrow down what the\n        # timestep should be.  If we are in the middle of a simulation,\n        # we can use the old timestep as a reasonable guess.  If we are\n        # simulation, then we can either use the inputted timestep or\n        # estimate it from other inputs.\n\n        dt_guess = (\n            self._dt\n            if self._dt\n            else self._dt_input\n            if self._dt_input\n            else self.time_max / self.max_steps\n        )\n\n        # Make sure that dt_guess does not lead to a time that is out\n        # of the domain.\n\n        dt_guess = dt_guess if t + dt_guess <= self.time_max - t else self.time_max - t\n\n        # The temperature may start out exactly at the boundary of a\n        # bin, so we check what bin it is in just slightly after to\n        # figure out which temperature bin the plasma is entering.\n\n        T = self.electron_temperature(t + 1e-9 * dt_guess)\n\n        # Find the boundaries to the temperature bin.\n\n        index = self._get_temperature_index(T.to(u.K).value)\n        T_nearby = np.array(self._temperature_grid[index - 1 : index + 2]) * u.K\n        T_boundary = (T_nearby[0:-1] + T_nearby[1:]) / 2\n\n        # In order to use Brent's method, we must bound the root's\n        # location.  Functions may change sharply or slowly, so we test\n        # different times that are logarithmically spaced to find the\n        # first one that is outside of the boundary.\n\n        dt_spread = (\n            np.geomspace(1e-9 * dt_guess.value, (self.time_max - t).value, num=100)\n            * u.s\n        )\n        time_spread = t + dt_spread\n        T_spread = [self.electron_temperature(time) for time in time_spread]\n        in_range = [T_boundary[0] <= temp <= T_boundary[1] for temp in T_spread]\n\n        # If all of the remaining temperatures are in the same bin, then\n        # the temperature will be roughly constant for the rest of the\n        # simulation.  Take one final long time step, unless it exceeds\n        # dt_max.\n\n        if all(in_range):\n            new_dt = self.time_max - t\n            self._dt = new_dt if new_dt <= self.dt_max else self.dt_max\n            return\n\n        # Otherwise, we need to find the first index in the spread that\n        # corresponds to a temperature outside of the temperature bin\n        # for this time step.\n\n        first_false_index = in_range.index(False)\n\n        # We need to figure out if the temperature is dropping so that\n        # it crosses the low temperature boundary of the bin, or if it\n        # is rising so that it crosses the high temperature of the bin.\n\n        T_first_outside = self.electron_temperature(time_spread[first_false_index])\n\n        if T_first_outside >= T_boundary[1]:\n            boundary_index = 1\n        elif T_first_outside <= T_boundary[0]:\n            boundary_index = 0\n\n        # Select the values for the time step in the spread just before\n        # and after the temperature leaves the temperature bin as bounds\n        # for the root finding method.\n\n        dt_bounds = (dt_spread[first_false_index - 1 : first_false_index + 1]).value\n\n        # Define a function for the difference between the temperature\n        # and the temperature boundary as a function of the value of the\n        # time step.\n\n        T_val = lambda dtval: (\n            self.electron_temperature(t + dtval * u.s) - T_boundary[boundary_index]\n        ).value\n\n        # Next we find the root.  This method should succeed as long as\n        # the root is bracketed by dt_bounds.  Because astropy.units is\n        # not fully compatible with SciPy, we temporarily drop units and\n        # then reattach them.\n\n        try:\n            new_dt = (\n                optimize.brentq(\n                    T_val,\n                    *dt_bounds,\n                    xtol=1e-14,\n                    maxiter=1000,\n                    disp=True,\n                )\n                * u.s\n            )\n        except Exception as exc:\n            raise NEIError(f\"Unable to find new dt at t = {t}\") from exc\n        else:\n            if np.isnan(new_dt.value):\n                raise NEIError(f\"new_dt = {new_dt}\")\n\n        # Enforce that the time step is in the interval [dt_min, dt_max].\n\n        if new_dt < self.dt_min:\n            new_dt = self.dt_min\n        elif new_dt > self.dt_max:\n            new_dt = self.dt_max\n\n        # Store the time step as a private attribute so that it can be\n        # used in the time advance.\n\n        self._dt = new_dt.to(u.s)\n\n    def set_timestep(self, dt: u.Quantity = None):\n        \"\"\"\n        Set the time step for the next non-equilibrium ionization time\n        advance.\n\n        Parameters\n        ----------\n        dt: astropy.units.Quantity, optional\n            The time step to be used for the next time advance.\n\n        Notes\n        -----\n        If ``dt`` is not `None`, then the time step will be set to ``dt``.\n\n        If ``dt`` is not set and the ``adapt_dt`` attribute of an\n        `~plasmapy_nei.nei.NEI` instance is `True`, then this method will\n        calculate the time step corresponding to how long it will be\n        until the temperature rises or drops into the next temperature\n        bin.  If this time step is between ``dtmin`` and ``dtmax``, then\n\n        If ``dt`` is not set and the ``adapt_dt`` attribute is `False`,\n        then this method will set the time step as what was inputted to\n        the `~plasmapy_nei.nei.NEI` class upon instantiation in the\n        ``dt`` argument or through the `~plasmapy_nei.nei.NEI` class's\n        ``dt_input`` attribute.\n\n        Raises\n        ------\n        ~plasmapy_nei.nei.NEIError\n            If the time step cannot be set, for example if the ``dt``\n            argument is invalid or the time step cannot be adapted.\n        \"\"\"\n\n        if dt is not None:\n            # Allow the time step to set as an argument to this method.\n            try:\n                dt = dt.to(u.s)\n            except Exception as exc:\n                raise NEIError(f\"{dt} is not a valid time step.\") from exc\n            finally:\n                self._dt = dt\n        elif self.adapt_dt:\n            try:\n                self._set_adaptive_timestep()\n            except Exception as exc:\n                raise NEIError(\"Unable to adapt the time step.\") from exc\n        elif self.dt_input is not None:\n            self._dt = self.dt_input\n        else:\n            raise NEIError(\"Unable to set the time step.\")\n\n        self._old_time = self._new_time\n        self._new_time = self._old_time + self._dt\n\n        if self._new_time > self.time_max:\n            self._new_time = self.time_max\n            self._dt = self._new_time - self._old_time\n\n    def time_advance(self):\n        \"\"\"Advance the simulation by one time step.\"\"\"\n        # TODO: Expand docstring and include equations!\n\n        # TODO: Fully implement units into this.\n\n        step = self.results._index\n        T_e = self.results.T_e[step - 1].value\n        n_e = self.results.n_e[step - 1].value  # set average\n        dt = self._dt.value\n\n        if self.verbose:\n            print(f\"step={step}  T_e={T_e}  n_e={n_e}  dt={dt}\")\n\n        new_ionic_fractions = {}\n\n        try:\n            for elem in self.elements:\n                nstates = self.results.nstates[elem]\n                f0 = self.results._ionic_fractions[elem][self.results._index - 1, :]\n\n                evals = self.eigen_data_dict[elem].eigenvalues(T_e=T_e)\n                evect = self.eigen_data_dict[elem].eigenvectors(T_e=T_e)\n                evect_inverse = self.eigen_data_dict[elem].eigenvector_inverses(T_e=T_e)\n\n                diagonal_evals = np.zeros((nstates, nstates), dtype=np.float64)\n                for ii in range(0, nstates):\n                    diagonal_evals[ii, ii] = np.exp(evals[ii] * dt * n_e)\n\n                matrix_1 = np.dot(diagonal_evals, evect)\n                matrix_2 = np.dot(evect_inverse, matrix_1)\n\n                ft = np.dot(f0, matrix_2)\n\n                # Due to truncation errors in the solutions in the\n                # eigenvalues and eigenvectors, there is a chance that\n                # very slightly negative ionic fractions will arise.\n                # These are not natural and will make the code grumpy.\n                # For these reasons, the ionic fractions will be very\n                # slightly unnormalized.  We set negative ionic\n                # fractions to zero and renormalize.\n\n                ft[np.where(ft < 0.0)] = 0.0\n                new_ionic_fractions[elem] = ft / np.sum(ft)\n\n        except Exception as exc:\n            raise NEIError(f\"Unable to do time advance for {elem}\") from exc\n        else:\n\n            new_time = self.results.time[self.results._index - 1] + self._dt\n            self.results._assign(\n                new_time=new_time,\n                new_ionfracs=new_ionic_fractions,\n                new_T_e=self.electron_temperature(new_time),\n                new_n=self.hydrogen_number_density(new_time),\n            )\n\n        if new_time >= self.time_max or np.isclose(new_time.value, self.time_max.value):\n            raise StopIteration\n\n    def save(self, filename: str = \"nei.h5\"):\n        \"\"\"\n        Save the `~plasmapy_nei.nei.NEI` instance to an HDF5 file.  Not\n        implemented.\n        \"\"\"\n        raise NotImplementedError\n\n    def index_to_time(self, index):\n        \"\"\"\n        Returns the time value or array given the index/indices\n\n        Parameters\n        ------\n        index: array-like\n               A value or array of values representing the index of\n               the time array created by the simulation\n\n        Returns\n        ------\n        get_time: astropy.units.Quantity\n                  The time value associated with index input(s)\n        \"\"\"\n\n        return self.results.time[index]\n\n    def time_to_index(self, time):\n        \"\"\"\n        Returns the closest index value or array for the given time(s)\n\n        Parameters\n        ------\n        time: array-like,\n               A value or array of values representing the values of\n               the time array created by the simulation\n\n        Returns\n        ------\n        index: int or array-like,\n                  The index value associated with the time input(s)\n        \"\"\"\n        index = (np.abs(self.results.time.value - time)).argmin()\n\n        return index\n", "meta": {"hexsha": "86b177033cafb6b91e729b15c23dfd784f8e2dc3", "size": 46774, "ext": "py", "lang": "Python", "max_stars_repo_path": "plasmapy_nei/nei/nei.py", "max_stars_repo_name": "PlasmaPy/PlasmaPy-NEI", "max_stars_repo_head_hexsha": "db2d91f1034a34d4af98498ddef98601c9ed5af9", "max_stars_repo_licenses": ["BSD-2-Clause-Patent", "BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-04-14T18:37:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-28T16:31:45.000Z", "max_issues_repo_path": "plasmapy_nei/nei/nei.py", "max_issues_repo_name": "PlasmaPy/PlasmaPy-NEI", "max_issues_repo_head_hexsha": "db2d91f1034a34d4af98498ddef98601c9ed5af9", "max_issues_repo_licenses": ["BSD-2-Clause-Patent", "BSD-3-Clause"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2020-04-19T03:17:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T00:05:06.000Z", "max_forks_repo_path": "plasmapy_nei/nei/nei.py", "max_forks_repo_name": "PlasmaPy/PlasmaPy-NEI", "max_forks_repo_head_hexsha": "db2d91f1034a34d4af98498ddef98601c9ed5af9", "max_forks_repo_licenses": ["BSD-2-Clause-Patent", "BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-04-09T17:55:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-13T20:52:49.000Z", "avg_line_length": 33.9927325581, "max_line_length": 104, "alphanum_fraction": 0.5817548211, "include": true, "reason": "import numpy,from scipy,import astropy", "num_tokens": 10593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.30074557894124154, "lm_q1q2_score": 0.15389650653560066}}
{"text": "\"\"\"\nModule for petitCODE atmospheric model spectra.\n\"\"\"\n\nimport os\nimport tarfile\nimport urllib.request\nimport warnings\nimport zipfile\n\nfrom typing import Optional, Tuple\n\nimport h5py\nimport numpy as np\nimport spectres\n\nfrom typeguard import typechecked\n\nfrom species.core import constants\nfrom species.util import data_util, read_util\n\n\n@typechecked\ndef add_petitcode_cool_clear(input_path: str,\n                             database: h5py._hl.files.File,\n                             wavel_range: Optional[Tuple[float, float]] = None,\n                             teff_range: Optional[Tuple[float, float]] = None,\n                             spec_res: Optional[float] = 1000.) -> None:\n    \"\"\"\n    Function for adding the petitCODE cool clear atmospheric models to the database.\n\n    Parameters\n    ----------\n    input_path : str\n        Folder where the data is located.\n    database : h5py._hl.files.File\n        Database.\n    wavel_range : tuple(float, float), None\n        Wavelength range (um). The original wavelength points are used if set to None.\n    teff_range : tuple(float, float), None\n        Effective temperature range (K). All temperatures are selected if set to None.\n    spec_res : float, None\n        Spectral resolution. Not used if ``wavel_range`` is set to None.\n\n    Returns\n    -------\n    NoneType\n        None\n    \"\"\"\n\n    if not os.path.exists(input_path):\n        os.makedirs(input_path)\n\n    data_folder = os.path.join(input_path, 'linder_molliere_grid/clear/specs/')\n\n    url = 'http://mpia.de/~molliere/online_data/linder_molliere_grid.zip'\n\n    data_file = os.path.join(input_path, 'linder_molliere_grid.zip')\n\n    if not os.path.isfile(data_file):\n        print('Downloading petitCODE cool model spectra (3.7 GB)...', end='', flush=True)\n        urllib.request.urlretrieve(url, data_file)\n        print(' [DONE]')\n\n    print('Unpacking petitCODE cool model spectra (3.7 GB)...', end='', flush=True)\n\n    with zipfile.ZipFile(data_file, 'r') as zip_ref:\n        zip_ref.extractall(input_path)\n\n    print(' [DONE]')\n\n    teff = []\n    logg = []\n    feh = []\n    flux = []\n\n    if wavel_range is not None:\n        wavelength = read_util.create_wavelengths(wavel_range, spec_res)\n    else:\n        wavelength = None\n\n    for _, _, files in os.walk(data_folder):\n        for filename in files:\n            file_split = filename.split('_')\n\n            teff_val = float(file_split[2])\n            logg_val = float(file_split[4])\n            feh_val = float(file_split[6])\n\n            if teff_range is not None:\n                if teff_val < teff_range[0] or teff_val > teff_range[1]:\n                    continue\n\n            print_message = f'Adding petitCODE cool clear model spectra... {filename}'\n            print(f'\\r{print_message:<87}', end='')\n\n            data = np.loadtxt(os.path.join(data_folder, filename))\n\n            teff.append(teff_val)\n            logg.append(logg_val)\n            feh.append(feh_val)\n\n            if wavel_range is None:\n                if wavelength is None:\n                    # (cm) -> (um)\n                    wavelength = data[:, 0]*1e4\n\n                if np.all(np.diff(wavelength) < 0):\n                    raise ValueError('The wavelengths are not all sorted by increasing value.')\n\n                # (erg s-1 cm-2 Hz-1) -> (W m-2 um-1)\n                flux.append(data[:, 1]*1e-9*constants.LIGHT/(wavelength*1e-6)**2)\n\n            else:\n                # (cm) -> (um)\n                data_wavel = data[:, 0]*1e4\n\n                # (erg s-1 cm-2 Hz-1) -> (W m-2 um-1)\n                data_flux = data[:, 1]*1e-9*constants.LIGHT/(data_wavel*1e-6)**2\n\n                try:\n                    flux.append(spectres.spectres(wavelength, data_wavel, data_flux))\n                except ValueError:\n                    flux.append(np.zeros(wavelength.shape[0]))\n\n                    warnings.warn('The wavelength range should fall within the range of the '\n                                  'original wavelength sampling. Storing zeros instead.')\n\n    print_message = 'Adding petitCODE cool clear model spectra... [DONE]'\n    print(f'\\r{print_message:<87}')\n\n    data_sorted = data_util.sort_data(np.asarray(teff),\n                                      np.asarray(logg),\n                                      np.asarray(feh),\n                                      None,\n                                      None,\n                                      wavelength,\n                                      np.asarray(flux))\n\n    data_util.write_data('petitcode-cool-clear',\n                         ['teff', 'logg', 'feh'],\n                         database,\n                         data_sorted)\n\n\n@typechecked\ndef add_petitcode_cool_cloudy(input_path: str,\n                              database: h5py._hl.files.File,\n                              wavel_range: Optional[Tuple[float, float]] = None,\n                              teff_range: Optional[Tuple[float, float]] = None,\n                              spec_res: Optional[float] = 1000.) -> None:\n    \"\"\"\n    Function for adding the petitCODE cool cloudy atmospheric models to the database.\n\n    Parameters\n    ----------\n    input_path : str\n        Folder where the data is located.\n    database : h5py._hl.files.File\n        Database.\n    wavel_range : tuple(float, float), None\n        Wavelength range (um). The original wavelength points are used if set to None.\n    teff_range : tuple(float, float), None\n        Effective temperature range (K). All temperatures are selected if set to None.\n    spec_res : float, None\n        Spectral resolution. Not used if ``wavel_range`` is set to None.\n\n    Returns\n    -------\n    NoneType\n        None\n    \"\"\"\n\n    if not os.path.exists(input_path):\n        os.makedirs(input_path)\n\n    data_folder = os.path.join(input_path, 'linder_molliere_grid/cloudy/specs/')\n\n    url = 'http://mpia.de/~molliere/online_data/linder_molliere_grid.zip'\n\n    data_file = os.path.join(input_path, 'linder_molliere_grid.zip')\n\n    if not os.path.isfile(data_file):\n        print('Downloading petitCODE cool model spectra (3.7 GB)...', end='', flush=True)\n        urllib.request.urlretrieve(url, data_file)\n        print(' [DONE]')\n\n    print('Unpacking petitCODE cool model spectra (3.7 GB)...', end='', flush=True)\n\n    with zipfile.ZipFile(data_file, 'r') as zip_ref:\n        zip_ref.extractall(input_path)\n\n    print(' [DONE]')\n\n    teff = []\n    logg = []\n    feh = []\n    fsed = []\n    flux = []\n\n    if wavel_range is not None:\n        wavelength = read_util.create_wavelengths(wavel_range, spec_res)\n    else:\n        wavelength = None\n\n    for _, _, files in os.walk(data_folder):\n        for filename in files:\n            file_split = filename.split('_')\n\n            teff_val = float(file_split[2])\n            logg_val = float(file_split[4])\n            feh_val = float(file_split[6])\n            fsed_val = float(file_split[8])\n\n            if teff_range is not None:\n                if teff_val < teff_range[0] or teff_val > teff_range[1]:\n                    continue\n\n            print_message = f'Adding petitCODE cool cloudy model spectra... {filename}'\n            print(f'\\r{print_message:<106}', end='')\n\n            data = np.loadtxt(os.path.join(data_folder, filename))\n\n            teff.append(teff_val)\n            logg.append(logg_val)\n            feh.append(feh_val)\n            fsed.append(fsed_val)\n\n            if wavel_range is None:\n                if wavelength is None:\n                    # (cm) -> (um)\n                    wavelength = data[:, 0]*1e4\n\n                if np.all(np.diff(wavelength) < 0):\n                    raise ValueError('The wavelengths are not all sorted by increasing value.')\n\n                # (erg s-1 cm-2 Hz-1) -> (W m-2 um-1)\n                flux.append(data[:, 1]*1e-9*constants.LIGHT/(wavelength*1e-6)**2)\n\n            else:\n                # (cm) -> (um)\n                data_wavel = data[:, 0]*1e4\n\n                # (erg s-1 cm-2 Hz-1) -> (W m-2 um-1)\n                data_flux = data[:, 1]*1e-9*constants.LIGHT/(data_wavel*1e-6)**2\n\n                try:\n                    flux.append(spectres.spectres(wavelength, data_wavel, data_flux))\n                except ValueError:\n                    flux.append(np.zeros(wavelength.shape[0]))\n\n                    warnings.warn('The wavelength range should fall within the range of the '\n                                  'original wavelength sampling. Storing zeros instead.')\n\n    print_message = 'Adding petitCODE cool cloudy model spectra... [DONE]'\n    print(f'\\r{print_message:<106}')\n\n    data_sorted = data_util.sort_data(np.asarray(teff),\n                                      np.asarray(logg),\n                                      np.asarray(feh),\n                                      None,\n                                      np.asarray(fsed),\n                                      wavelength,\n                                      np.asarray(flux))\n\n    data_util.write_data('petitcode-cool-cloudy',\n                         ['teff', 'logg', 'feh', 'fsed'],\n                         database,\n                         data_sorted)\n\n\n@typechecked\ndef add_petitcode_hot_clear(input_path: str,\n                            database: h5py._hl.files.File,\n                            wavel_range: Optional[Tuple[float, float]] = None,\n                            teff_range: Optional[Tuple[float, float]] = None,\n                            spec_res: Optional[float] = 1000.) -> None:\n    \"\"\"\n    Function for adding the petitCODE hot clear atmospheric models to the database.\n\n    Parameters\n    ----------\n    input_path : str\n        Folder where the data is located.\n    database : h5py._hl.files.File\n        Database.\n    wavel_range : tuple(float, float), None\n        Wavelength range (um). The original wavelength points are used if set to None.\n    teff_range : tuple(float, float), None\n        Effective temperature range (K). All temperatures are selected if set to None.\n    spec_res : float, None\n        Spectral resolution. Not used if ``wavel_range`` is set to None.\n\n    Returns\n    -------\n    NoneType\n        None\n    \"\"\"\n\n    if not os.path.exists(input_path):\n        os.makedirs(input_path)\n\n    data_folder = os.path.join(input_path, 'petitcode-hot-clear/')\n\n    url = 'https://people.phys.ethz.ch/~ipa/tstolker/petitcode-hot-clear.tgz'\n\n    data_file = os.path.join(input_path, 'petitcode-hot-clear.tgz')\n\n    if not os.path.isfile(data_file):\n        print('Downloading petitCODE hot clear model spectra (93 MB)...', end='', flush=True)\n        urllib.request.urlretrieve(url, data_file)\n        print(' [DONE]')\n\n    print('Unpacking petitCODE hot clear model spectra (93 MB)...', end='', flush=True)\n    tar = tarfile.open(data_file)\n    tar.extractall(data_folder)\n    tar.close()\n    print(' [DONE]')\n\n    teff = []\n    logg = []\n    feh = []\n    co_ratio = []\n    flux = []\n\n    if wavel_range is not None:\n        wavelength = read_util.create_wavelengths(wavel_range, spec_res)\n    else:\n        wavelength = None\n\n    for _, _, files in os.walk(data_folder):\n        for filename in files:\n            file_split = filename.split('_')\n\n            teff_val = float(file_split[2])\n            logg_val = float(file_split[4])\n            feh_val = float(file_split[6])\n            co_ratio_val = float(file_split[8])\n\n            if teff_range is not None:\n                if teff_val < teff_range[0] or teff_val > teff_range[1]:\n                    continue\n\n            print_message = f'Adding petitCODE hot clear model spectra... {filename}'\n            print(f'\\r{print_message:<99}', end='')\n\n            data = np.loadtxt(os.path.join(data_folder, filename))\n\n            teff.append(teff_val)\n            logg.append(logg_val)\n            feh.append(feh_val)\n            co_ratio.append(co_ratio_val)\n\n            if wavel_range is None:\n                if wavelength is None:\n                    # (cm) -> (um)\n                    wavelength = data[:, 0]*1e4\n\n                if np.all(np.diff(wavelength) < 0):\n                    raise ValueError('The wavelengths are not all sorted by increasing value.')\n\n                # (erg s-1 cm-2 Hz-1) -> (W m-2 um-1)\n                flux.append(data[:, 1]*1e-9*constants.LIGHT/(wavelength*1e-6)**2)\n\n            else:\n                # (cm) -> (um)\n                data_wavel = data[:, 0]*1e4\n\n                # (erg s-1 cm-2 Hz-1) -> (W m-2 um-1)\n                data_flux = data[:, 1]*1e-9*constants.LIGHT/(data_wavel*1e-6)**2\n\n                try:\n                    flux.append(spectres.spectres(wavelength, data_wavel, data_flux))\n                except ValueError:\n                    flux.append(np.zeros(wavelength.shape[0]))\n\n                    warnings.warn('The wavelength range should fall within the range of the '\n                                  'original wavelength sampling. Storing zeros instead.')\n\n    print_message = 'Adding petitCODE hot clear model spectra... [DONE]'\n    print(f'\\r{print_message:<99}')\n\n    data_sorted = data_util.sort_data(np.asarray(teff),\n                                      np.asarray(logg),\n                                      np.asarray(feh),\n                                      np.asarray(co_ratio),\n                                      None,\n                                      wavelength,\n                                      np.asarray(flux))\n\n    data_util.write_data('petitcode-hot-clear',\n                         ['teff', 'logg', 'feh', 'co'],\n                         database,\n                         data_sorted)\n\n\n@typechecked\ndef add_petitcode_hot_cloudy(input_path: str,\n                             database: h5py._hl.files.File,\n                             wavel_range: Optional[Tuple[float, float]] = None,\n                             teff_range: Optional[Tuple[float, float]] = None,\n                             spec_res: Optional[float] = 1000.) -> None:\n    \"\"\"\n    Function for adding the petitCODE hot cloudy atmospheric models to the database.\n\n    Parameters\n    ----------\n    input_path : str\n        Folder where the data is located.\n    database : h5py._hl.files.File\n        Database.\n    wavel_range : tuple(float, float), None\n        Wavelength range (um). The original wavelength points are used if set to None.\n    teff_range : tuple(float, float), None\n        Effective temperature range (K). All temperatures are selected if set to None.\n    spec_res : float, None\n        Spectral resolution. Not used if ``wavel_range`` is set to None.\n\n    Returns\n    -------\n    NoneType\n        None\n    \"\"\"\n\n    if not os.path.exists(input_path):\n        os.makedirs(input_path)\n\n    data_folder = os.path.join(input_path, 'petitcode-hot-cloudy/')\n\n    url = 'https://people.phys.ethz.ch/~ipa/tstolker/petitcode-hot-cloudy.tgz'\n\n    data_file = os.path.join(input_path, 'petitcode-hot-cloudy.tgz')\n\n    if not os.path.isfile(data_file):\n        print('Downloading petitCODE hot cloudy model spectra (276 MB)...', end='', flush=True)\n        urllib.request.urlretrieve(url, data_file)\n        print(' [DONE]')\n\n    print('Unpacking petitCODE hot cloudy model spectra (276 MB)...', end='', flush=True)\n    tar = tarfile.open(data_file)\n    tar.extractall(data_folder)\n    tar.close()\n    print(' [DONE]')\n\n    teff = []\n    logg = []\n    feh = []\n    co_ratio = []\n    fsed = []\n    flux = []\n\n    if wavel_range is not None:\n        wavelength = read_util.create_wavelengths(wavel_range, spec_res)\n    else:\n        wavelength = None\n\n    for _, _, files in os.walk(data_folder):\n        for filename in files:\n            file_split = filename.split('_')\n\n            teff_val = float(file_split[2])\n            logg_val = float(file_split[4])\n            feh_val = float(file_split[6])\n            co_ratio_val = float(file_split[8])\n            fsed_val = float(file_split[10])\n\n            if teff_range is not None:\n                if teff_val < teff_range[0] or teff_val > teff_range[1]:\n                    continue\n\n            print_message = f'Adding petitCODE hot cloudy model spectra... {filename}'\n            print(f'\\r{print_message:<111}', end='')\n\n            data = np.loadtxt(os.path.join(data_folder, filename))\n\n            teff.append(teff_val)\n            logg.append(logg_val)\n            feh.append(feh_val)\n            co_ratio.append(co_ratio_val)\n            fsed.append(fsed_val)\n\n            if wavel_range is None:\n                if wavelength is None:\n                    # (cm) -> (um)\n                    wavelength = data[:, 0]*1e4\n\n                if np.all(np.diff(wavelength) < 0):\n                    raise ValueError('The wavelengths are not all sorted by increasing value.')\n\n                # (erg s-1 cm-2 Hz-1) -> (W m-2 um-1)\n                flux.append(data[:, 1]*1e-9*constants.LIGHT/(wavelength*1e-6)**2)\n\n            else:\n                # (cm) -> (um)\n                data_wavel = data[:, 0]*1e4\n\n                # (erg s-1 cm-2 Hz-1) -> (W m-2 um-1)\n                data_flux = data[:, 1]*1e-9*constants.LIGHT/(data_wavel*1e-6)**2\n\n                try:\n                    flux.append(spectres.spectres(wavelength, data_wavel, data_flux))\n                except ValueError:\n                    flux.append(np.zeros(wavelength.shape[0]))\n\n                    warnings.warn('The wavelength range should fall within the range of the '\n                                  'original wavelength sampling. Storing zeros instead.')\n\n    print_message = 'Adding petitCODE hot cloudy model spectra... [DONE]'\n    print(f'\\r{print_message:<111}')\n\n    data_sorted = data_util.sort_data(np.asarray(teff),\n                                      np.asarray(logg),\n                                      np.asarray(feh),\n                                      np.asarray(co_ratio),\n                                      np.asarray(fsed),\n                                      wavelength,\n                                      np.asarray(flux))\n\n    data_util.write_data('petitcode-hot-cloudy',\n                         ['teff', 'logg', 'feh', 'co', 'fsed'],\n                         database,\n                         data_sorted)\n", "meta": {"hexsha": "37dd63c55e3de41a236fb3684b41a4f03c93f070", "size": 18129, "ext": "py", "lang": "Python", "max_stars_repo_path": "species/data/petitcode.py", "max_stars_repo_name": "vandalt/species", "max_stars_repo_head_hexsha": "527dd900a60c4d691bd490569cd3b2007f9beead", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "species/data/petitcode.py", "max_issues_repo_name": "vandalt/species", "max_issues_repo_head_hexsha": "527dd900a60c4d691bd490569cd3b2007f9beead", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "species/data/petitcode.py", "max_forks_repo_name": "vandalt/species", "max_forks_repo_head_hexsha": "527dd900a60c4d691bd490569cd3b2007f9beead", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6634799235, "max_line_length": 95, "alphanum_fraction": 0.5400187545, "include": true, "reason": "import numpy", "num_tokens": 4060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.1538965033284889}}
{"text": "#!/usr/bin/env python\n\n\"\"\"Handle Monte Carlo simulation run settings\"\"\"\n\n\nfrom __future__ import absolute_import, division\n\nimport pisa.utils.fileio as fileio\nimport pisa.utils.flavInt as flavInt\nfrom pisa.utils import resources as resources\nfrom pisa.utils.cross_sections import CrossSections\n\n# Following \"import *\" is intentionally done so that `eval` called in\n# translate_source_dict will execute with direct access to numpy namespace\nfrom numpy import * # pylint: disable=wildcard-import, unused-wildcard-import, redefined-builtin\n\n\n__all__ = ['MCSimRunSettings', 'DetMCSimRunsSettings']\n\n__author__ = 'J.L. Lanfranchi'\n\n__license__ = '''Copyright (c) 2014-2017, The IceCube Collaboration\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n   http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.'''\n\n\n# TODO: make ability to serialize instantiated MCSimRunSettings and\n# DetMCSimRunsSettings objects back to JSON format from which they were\n# generated\n\n# TODO: put more thought into the MCSimRunSettings class\n\n# TODO: make sure user is forced to choose run & detector here\n\nclass MCSimRunSettings(dict):\n    \"\"\"Handle Monte Carlo run settings\n\n    Parameters\n    ----------\n    run_settings : string or dict\n    run\n    detector : string or None\n\n    Notes\n    -----\n    run_settings dictionary format (and same for corresponding JSON file, e.g.\n    resources/events/mc_sim_run_settings.json); example is for PINGU but should\n    generalize to DeepCore, etc. Note that a JSON file will use null and not\n    None.\n\n    (Also note that expressions for numerical values utilizing the Python/numpy\n    namespace are valid, e.g. \"2*pi\" will be evaluated within the code to its\n    decimal value.)::\n\n        {\n\n          # Specify the detector name, lower case\n          \"pingu\": {\n\n            # Monte Carlo run number for this detector\n            \"388\": {\n\n              # Version of geometry, lower-case. E.g., ic86 for IceCube/DeepCore\n              \"geom\": \"v36\",\n\n              # A straightforward way of computing aeff/veff/meff is to keep all\n              # simulated events and compare the #analysis/#simulated. If all\n              # simulated events are kept, then the filename containing these is\n              # recorded here.\n              \"all_gen_events_file\": None,\n\n              # Max and min azimuth angle simulated (rad)\n              \"azimuth_max\": \"2*pi\",\n              \"azimuth_min\": 0,\n\n              # Max and min energy simulated (GeV)\n              \"energy_max\": 80,\n              \"energy_min\": 1,\n\n              # GENIE simulates some un-physica events (interactions that will not\n              # occur in nature). The number below was arrived at by Ken Clark, so\n              # ask him for more info.\n              \"physical_events_fract\": 0.8095,\n\n              # GENIE has a prescale factor (TODO: generalize or eliminate for\n              # other xsec?)\n              \"genie_prescale_factor\": 1.2,\n\n              # Neutrino flavors simulated\n              \"flavints\": \"nutau,nutaubar\",\n\n              # #nu / (#nu + #nubar) simulated\n              \"nu_to_total_fract\": 0.5,\n\n              # Number of events simulated per I3 file\n              \"num_events_per_file\": 250000,\n\n              # Number of I3 files used\n              \"num_i3_files\": 195,\n\n              # Simulated spectral inde gamma; value of 1 => E*{-1}\n              \"sim_spectral_index\": 1,\n\n              # Version of neutrino/ice cross sections used for the simulation\n              \"xsec_version\": \"genie_2.6.4\",\n\n              # Max and min zenith angle simulated (rad)\n              \"zenith_max\": \"pi\",\n              \"zenith_min\": 0\n            }\n          }\n        }\n\n\n    \"\"\"\n    def __init__(self, run_settings, run=None, detector=None):\n        super().__init__()\n        # TODO: clean up this constructor!\n        #if isinstance(run_settings, str):\n        #    rsd = jsons.from_json(resources.find_resource(run_settings))\n        if isinstance(run_settings, dict):\n            rsd = run_settings\n        else:\n            raise TypeError('Unhandled run_settings type passed in arg: %s'\n                            %type(run_settings))\n        #if detector is not None:\n        #    try:\n        #        rsd = rsd[detector]\n        #    except:\n        #        pass\n        rsd = self.translate_source_dict(rsd)\n        if not detector is None:\n            detector = str(detector).strip()\n        self.detector = detector\n        self.run = run\n        self.update(rsd)\n\n    @staticmethod\n    def translate_source_dict(d):\n        d['tot_gen'] = d['num_events_per_file'] * d['num_i3_files']\n\n        # TODO: does the following logic actually work with both old and new\n        # conventions?\n\n        # NOTE: the ',' --> '+' mapping is necessary since some data files\n        # were saved prior to the convention that commas exclusively separate\n        # groups while plus signs indicate flav/ints grouped together\n\n        d['flavints'] = flavInt.NuFlavIntGroup(d['flavints'].replace(',', '+'))\n\n        # Numeric fields are allowed to be expressions that get evaluated\n        numeric_fields = [\n            'azimuth_max',\n            'azimuth_min',\n            'energy_max',\n            'energy_min',\n            'physical_events_fract',\n            'genie_prescale_factor',\n            'nu_to_total_fract',\n            'num_events_per_file',\n            'num_i3_files',\n            'sim_spectral_index',\n            'zenith_max',\n            'zenith_min',\n        ]\n        for f in numeric_fields:\n            if isinstance(d[f], str):\n                d[f] = eval(d[f])\n\n        return d\n\n    def consistency_checks(self, data, flav=None):\n        # TODO: implement!\n        pass\n\n    def barnobarfract(self, barnobar=None, is_particle=None,\n                      flav_or_flavint=None):\n        \"\"\"Fraction of events generated (either particles or antiparticles).\n\n        Specifying whether you want the fraction for particle or\n        antiparticle is done by specifying one (and only one) of the three\n        parameters:\n            `barnobar`, `is_particle` or `flav_or_flavint`\n\n        Parameters\n        ----------\n        barnobar : None or int\n            -1 for antiparticle, +1 for particle\n        is_particle : None or bool\n            True for particle, false for antiparticle\n        flav_or_flavint : None or convertible to NuFlav or NuFlavInt\n            Particle or antiparticles is determined from the flavor or flavint\n            passed\n\n        \"\"\"\n        nargs = sum([(not barnobar is None),\n                     (not is_particle is None),\n                     (not flav_or_flavint is None)])\n        if nargs != 1:\n            raise ValueError('One and only one of `barnobar`, `is_particle`,'\n                             ' and `flav_or_flavint` must be specified. Got'\n                             ' %d non-None args instead.' % nargs)\n\n        if flav_or_flavint is not None:\n            is_particle = flavInt.NuFlavInt(flav_or_flavint).particle\n        elif barnobar is not None:\n            is_particle = barnobar > 0\n\n        if is_particle:\n            return self['nu_to_total_fract']\n        return 1 - self['nu_to_total_fract']\n\n    def get_num_gen(self, barnobar=None, is_particle=None,\n                    flav_or_flavint=None, include_physical_fract=True):\n        \"\"\"Return the number of events generated.\n\n        Parameters\n        ----------\n        barnobar : None or int\n            -1 for antiparticle or +1 for particle\n\n        is_particle : None or bool\n\n        flav_or_flavint : None or convertible to NuFlav or NuFlavInt\n            If one of `barnobar`, `is_particle`, or `flav_or_flavint` is\n            specified, returns only the number of particles or antiparticles\n            generated. Otherwise (if none of those is specified), return the\n            total number of generated events.\n\n        include_physical_fract : bool\n            Whether to include the \"GENIE physical fraction\", which accounts\n            for events that are generated but are un-physical and therefore\n            will never be detectable. These are removed to not penalize\n            detection efficiency.\n\n        \"\"\"\n        nargs = sum([(not barnobar is None),\n                     (not is_particle is None),\n                     (not flav_or_flavint is None)])\n        if flav_or_flavint is not None:\n            if (flav_or_flavint not in self.get_flavs()\n                    and flav_or_flavint not in self.get_flavints()):\n                return 0\n        barnobarfract = 1\n        if nargs > 0:\n            barnobarfract = self.barnobarfract(\n                barnobar=barnobar, is_particle=is_particle,\n                flav_or_flavint=flav_or_flavint\n            )\n        physical_fract = 1\n        if include_physical_fract:\n            physical_fract = self['physical_events_fract']\n        return self['tot_gen'] * barnobarfract * physical_fract\n\n    def get_flavints(self):\n        return self['flavints'].get_flavints()\n\n    def get_flavs(self):\n        return self['flavints'].get_flavs()\n\n    def get_energy_range(self):\n        \"\"\"(min, max) energy in GeV\"\"\"\n        return self['energy_min'], self['energy_max']\n\n    def get_spectral_index(self):\n        \"\"\"Spectral index (positive number for negative powers of energy)\"\"\"\n        return self['sim_spectral_index']\n\n    def get_xsec_version(self):\n        \"\"\"Cross sectons version name used in generating the MC\"\"\"\n        return self['xsec_version']\n\n    def get_xsec(self, xsec=None):\n        \"\"\"Instantiated CrossSections object\"\"\"\n        if xsec is None:\n            return CrossSections(ver=self['xsec_version'])\n        return CrossSections(ver=self['xsec_version'], xsec=xsec)\n\n\nclass DetMCSimRunsSettings(dict):\n    \"\"\"Handle Monte Carlo run settings for a detector (i.e., without specifying\n    which run as is required for the MCSimRunSettings object)\n\n    Since run is not specified at instantiation, method calls require the user\n    to specify a run ID.\n\n    Parameters\n    ----------\n    run_settings : string or dict\n    detector : string or None\n\n    See Also\n    --------\n    MCSimRunSettings : Same, but specifies a specific run at instantiation; see\n                       class docstring for specification of run_settings dict /\n                       JSON file\n\n    \"\"\"\n    def __init__(self, run_settings, detector=None):\n        super().__init__()\n        if isinstance(run_settings, str):\n            rsd = fileio.from_file(resources.find_resource(run_settings))\n        elif isinstance(run_settings, dict):\n            rsd = run_settings\n        else:\n            raise TypeError('Unhandled run_settings type passed in arg: ' +\n                            type(run_settings))\n\n        if detector:\n            detector = str(detector).strip()\n        self.detector = detector\n\n        # Determine how deeply nested runs are in the dict to allow for\n        # user to specify a dict that has multiple detectors in it OR\n        # a dict with just a single detector in it\n        if 'flavints' in rsd.values()[0]:\n            runs_d = rsd\n        elif 'flavints' in rsd.values()[0].values()[0]:\n            if self.detector is None:\n                if len(rsd) == 1:\n                    runs_d = rsd.values()[0]\n                else:\n                    raise ValueError('Must specify which detector; detectors '\n                                     'found: ' + str(rsd.keys()))\n            else:\n                runs_d = rsd[self.detector.strip()]\n        else:\n            raise Exception('dict must either be 3 levels: '\n                            '{DET:{RUN:{...}}}; or 2 levels: {RUN:{...}}')\n\n        # Force run numbers to be strings (JSON files cannot have an int as\n        # a key, so it is a string upon import, and it's safest to keep it as\n        # a string considering how non-standardized naming is in IceCube) and\n        # convert actual run settings dict to MCSimRunSettings instances\n        runs_d = {str(k): MCSimRunSettings(v) for k, v in runs_d.items()}\n\n        # Save the runs_d to this object instance, which behaves like a dict\n        self.update(runs_d)\n\n    def consistency_checks(self, data, run, flav=None):\n        pass\n\n    def barnobarfract(self, run, barnobar=None, is_particle=None,\n                      flav_or_flavint=None):\n        return self[str(run)].barnobarfract(barnobar=barnobar,\n                                            is_particle=is_particle,\n                                            flav_or_flavint=flav_or_flavint)\n\n    def get_num_gen(self, run, barnobar=None, is_particle=None,\n                    flav_or_flavint=None, include_physical_fract=True):\n        \"\"\"Return the total number of events generated\"\"\"\n        return self[str(run)].get_num_gen(\n            barnobar=barnobar, is_particle=is_particle,\n            flav_or_flavint=flav_or_flavint,\n            include_physical_fract=include_physical_fract\n        )\n\n    def get_flavints(self, run):\n        return self[str(run)].get_flavints()\n\n    def get_flavs(self, run):\n        return self[str(run)].get_flavs()\n\n    def get_energy_range(self, run):\n        \"\"\"(min, max) energy in GeV\"\"\"\n        return self[str(run)].get_energy_range()\n\n    def get_spectral_index(self, run):\n        \"\"\"Spectral index (positive number for negative powers of energy)\"\"\"\n        return self[str(run)].get_spectral_index()\n\n    def get_xsec_version(self, run):\n        \"\"\"Cross sectons version name used in generating the MC\"\"\"\n        return self[str(run)].get_xsec_version()\n\n    def get_xsec(self, run, xsec=None):\n        \"\"\"Instantiated CrossSections object\"\"\"\n        return self[str(run)].get_xsec(xsec)\n", "meta": {"hexsha": "c1d4b375f45765aa0b7f92b2a20493688da1a2e1", "size": 14099, "ext": "py", "lang": "Python", "max_stars_repo_path": "pisa/utils/mcSimRunSettings.py", "max_stars_repo_name": "wym109/pisa", "max_stars_repo_head_hexsha": "696803320f577d241651df900726b76a770d072a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-03-10T18:18:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T03:04:05.000Z", "max_issues_repo_path": "pisa/utils/mcSimRunSettings.py", "max_issues_repo_name": "wym109/pisa", "max_issues_repo_head_hexsha": "696803320f577d241651df900726b76a770d072a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 105, "max_issues_repo_issues_event_min_datetime": "2019-03-21T13:53:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-25T16:34:14.000Z", "max_forks_repo_path": "pisa/utils/mcSimRunSettings.py", "max_forks_repo_name": "wym109/pisa", "max_forks_repo_head_hexsha": "696803320f577d241651df900726b76a770d072a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2019-03-03T22:25:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-23T15:57:10.000Z", "avg_line_length": 36.2442159383, "max_line_length": 96, "alphanum_fraction": 0.6060713526, "include": true, "reason": "from numpy", "num_tokens": 3161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3007455664065234, "lm_q1q2_score": 0.15389650012137723}}
{"text": "\"\"\"`BVT24`\"\"\"\nimport numpy as np\nfrom skimage.transform import SimilarityTransform\n\nfrom .base import ProsthesisSystem\nfrom .electrodes import DiskElectrode\nfrom .electrode_arrays import ElectrodeArray\n\n\nclass BVT24(ProsthesisSystem):\n    \"\"\"24-channel suprachoroidal retinal prosthesis\n\n    This class creates a 24-channel suprachoroidal retinal prosthesis\n    [Layton2014]_, which was developed by the Bionic Vision Australia\n    Consortium and commercialized by Bionic Vision Technologies (BVT).\n    The center of the array is located at (x,y,z), given in microns, and the\n    array is rotated by rotation angle ``rot``, given in degrees.\n\n    The array consists of:\n\n    -   33 platinum stimulating electrodes:\n\n        -   30 electrodes with 600um diameter (Electrodes C1-20 (except\n            C9, C17, C19) and Electrodes C21a-m),\n\n        -   3 electrodes with 400um diameter (Electrodes C9, C17, C19)\n\n    -   2 return electrodes with 2000um diameter (Electrodes R1, R2)\n\n    Electrodes C21a-m are typically being ganged to provide an external\n    ring for common ground. The center of the array is assumed to lie\n    between Electrodes C7, C8, C9, and C13.\n\n    .. note::\n\n        Column order for electrode numbering is reversed in a left-eye\n        implant.\n\n    .. versionadded:: 0.6\n\n    Parameters\n    ----------\n    x/y/z : double\n        3D location of the center of the electrode array.\n        The coordinate system is centered over the fovea.\n        Positive ``x`` values move the electrode into the nasal retina.\n        Positive ``y`` values move the electrode into the superior retina.\n        Positive ``z`` values move the electrode away from the retina into the\n        vitreous humor (sometimes called electrode-retina distance).\n        ``z`` can either be a list with 35 entries or a scalar that is applied\n        to all electrodes.\n    rot : float\n        Rotation angle of the array (deg). Positive values denote\n        counter-clock-wise (CCW) rotations in the retinal coordinate\n        system.\n    eye : {'RE', 'LE'}, optional\n        Eye in which array is implanted.\n    preprocess : bool or callable, optional\n        Either True/False to indicate whether to execute the implant's default\n        preprocessing method whenever a new stimulus is assigned, or a custom\n        function (callable).\n    safe_mode : bool, optional\n        If safe mode is enabled, only charge-balanced stimuli are allowed.\n\n    \"\"\"\n    # Frozen class: User cannot add more class attributes\n    __slots__ = ()\n\n    def __init__(self, x=0, y=0, z=0, rot=0, eye='RE', stim=None,\n                 preprocess=False, safe_mode=False):\n        self.eye = eye\n        self.preprocess = preprocess\n        self.safe_mode = safe_mode\n        self.earray = ElectrodeArray([])\n        n_elecs = 35\n\n        # the positions of the electrodes 1-20, 21a-21m, R1-R2\n        x_arr = np.array([1275.0, 850.0, 1275.0, 850.0, 1275.0,\n                          425.0, 0, 425.0, 0, 425.0,\n                          -425.0, -850.0, -425.0, -850.0, -425.0,\n                          -1275.0, -1700.0, -1275.0, -1700.0, -1275.0,\n                          850.0, 0, -850.0, -1700.0, -2125.0,\n                          -2550.0, -2125.0, -2550.0, -2125.0, -1700.0,\n                          -850.0, 0, 850.0, -7000.0, -9370.0])\n        y_arr = np.array([1520.0, 760.0, 0, -760.0, -1520.0,\n                          1520.0, 760.0, 0, -760.0, -1520.0,\n                          1520.0, 760.0, 0, -760.0, -1520.0,\n                          1520.0, 760.0, 0, -760.0, -1520.0,\n                          2280.0, 2280.0, 2280.0, 2280.0, 1520.0,\n                          760.0, 0.0, -760.0, -1520.0, -2280.0,\n                          -2280.0, -2280.0, -2280.0, 0, 0])\n        if isinstance(z, (list, np.ndarray)):\n            # Specify different height for every electrode in a list:\n            z_arr = np.asarray(self.z).flatten()\n            if z_arr.size != n_elecs:\n                raise ValueError(\"If `z` is a list, it must have %d entries, \"\n                                 \"not %d.\" % (n_elecs, len(z)))\n        else:\n            # If `z` is a scalar, choose same height for all electrodes:\n            z_arr = np.ones(n_elecs, dtype=float) * z\n\n        # the position of the electrodes 1-20, 21a-21m, R1-R2 for left eye\n        if eye == 'LE':\n            x_arr = np.negative(x_arr)\n\n        # the radius of all the electrodes in the implants\n        r_arr = [300.0] * n_elecs\n        # the radius of electrodes 9, 17, 19 is 200.0 um\n        r_arr[8] = r_arr[16] = r_arr[18] = 200.0\n        # the radius of the return electrodes is 1000.0 um\n        r_arr[33] = r_arr[34] = 1000.0\n        # the names of the electrodes C1-20, C21a-21m, R1 and R2\n        names = [\"C%s\" % name for name in range(1, 21)]\n        names.extend(['C21a', 'C21b', 'C21c', 'C21d', 'C21e',\n                      'C21f', 'C21g', 'C21h', 'C21i', 'C21j',\n                      'C21k', 'C21l', 'C21m'])\n        names.extend(['R1', 'R2'])\n\n        # Rotate the grid and center at (x,y):\n        tf = SimilarityTransform(rotation=np.deg2rad(rot), translation=[x, y])\n        x_arr, y_arr = tf(np.vstack([x_arr.ravel(), y_arr.ravel()]).T).T\n\n        for x, y, z, r, name in zip(x_arr, y_arr, z_arr, r_arr, names):\n            self.earray.add_electrode(name, DiskElectrode(x, y, z, r))\n\n        # Beware of race condition: Stim must be set last, because it requires\n        # indexing into self.electrodes:\n        self.stim = stim\n", "meta": {"hexsha": "460f3376d8867b8ef056f9d765f9ea184e151e0e", "size": 5494, "ext": "py", "lang": "Python", "max_stars_repo_path": "pulse2percept/implants/bvt.py", "max_stars_repo_name": "pulse2percept/pulse2percept", "max_stars_repo_head_hexsha": "67e0f2354db5ebe306b617f7f78a9ea8c02327ac", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 40, "max_stars_repo_stars_event_min_datetime": "2019-11-01T14:09:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T19:08:01.000Z", "max_issues_repo_path": "pulse2percept/implants/bvt.py", "max_issues_repo_name": "jgranley/pulse2percept", "max_issues_repo_head_hexsha": "65c11393a33d1531cd02a3e38243414bf8172e9a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 277, "max_issues_repo_issues_event_min_datetime": "2019-11-22T03:30:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T00:11:03.000Z", "max_forks_repo_path": "pulse2percept/implants/bvt.py", "max_forks_repo_name": "jgranley/pulse2percept", "max_forks_repo_head_hexsha": "65c11393a33d1531cd02a3e38243414bf8172e9a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2020-01-22T06:36:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T09:54:25.000Z", "avg_line_length": 42.5891472868, "max_line_length": 78, "alphanum_fraction": 0.5824535857, "include": true, "reason": "import numpy", "num_tokens": 1627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117165898111865, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.15389649884949147}}
{"text": "# Fit to multiple relative binding free energy edges\nimport sys\nfrom argparse import ArgumentParser\nimport jax\nfrom jax import numpy as jnp\nimport numpy as np\nimport datetime\nimport timemachine\nfrom training.dataset import Dataset\n\n# forcefield handlers\nfrom ff import Forcefield\nfrom ff.handlers.serialize import serialize_handlers\nfrom ff.handlers.deserialize import deserialize_handlers\nfrom ff.handlers.nonbonded import AM1CCCHandler, LennardJonesHandler\n\n# free energy classes\nfrom fe.free_energy import (\n    RelativeFreeEnergy,\n    construct_lambda_schedule,\n    RBFETransformIndex,\n)\nfrom fe.estimator import SimulationResult\nfrom fe.model import RBFEModel\nfrom fe.loss import pseudo_huber_loss  # , l1_loss, flat_bottom_loss\n\n# MD initialization\nfrom md import builders\n\n# parallelization across multiple GPUs\nfrom parallel.client import CUDAPoolClient, GRPCClient\nfrom parallel.utils import get_gpu_count\n\nfrom collections import namedtuple, defaultdict\n\nfrom pickle import load, dump\n\nfrom optimize.step import truncated_step\nfrom optimize.utils import flatten_and_unflatten\n\nfrom typing import Tuple, Dict, List, Union, Any\n\nfrom pathlib import Path\nfrom time import time\n\narray = Union[np.array, jnp.array]\n\nHandler = Union[AM1CCCHandler, LennardJonesHandler]  # TODO: relax this assumption\n\nNUM_GPUS = get_gpu_count()\n\n# how much MD to run\n# TODO: rename this to something more descriptive than \"Configuration\"...\n#   want to distinguish later between an \"RBFE configuration\"\n#       (which describes the computation of a single edge)\n#   and a \"training configuration\"\n#       (which describes the overall training loop)\nConfiguration = namedtuple(\n    \"Configuration\", [\"num_complex_windows\", \"num_solvent_windows\", \"num_equil_steps\", \"num_prod_steps\"]\n)\n\n# define a couple configurations: one for quick tests, and one for production\nproduction_configuration = Configuration(\n    num_complex_windows=60,\n    num_solvent_windows=60,\n    num_equil_steps=10000,\n    num_prod_steps=100000,\n)\n\nintermediate_configuration = Configuration(\n    num_complex_windows=60,\n    num_solvent_windows=60,\n    num_equil_steps=10000,\n    num_prod_steps=10000,\n)\n\ntesting_configuration = Configuration(\n    num_complex_windows=10,\n    num_solvent_windows=10,\n    num_equil_steps=1000,\n    num_prod_steps=1000,\n)\n\n\n# locations relative to project root\nroot = Path(timemachine.__file__).parent.parent\n\n\ndef _save_forcefield(fname, ff_params):\n    with open(fname, \"w\") as fh:\n        fh.write(ff_params)\n\n\ndef _compute_step_lower_bound(loss: float, blown_up: bool, relative_improvement_bound: float = 0.8) -> float:\n    \"\"\"problem this addresses: on a small fraction of steps, the free energy estimate may be grossly unreliable\n    away from target, typically indicating an instability was encountered.\n    detect if this occurs, and don't allow a step.\n\n    \"\"\"\n    if not blown_up:\n        return loss * relative_improvement_bound\n    else:\n        return loss  # don't move!\n\n\ndef _results_to_arrays(results: List[SimulationResult]):\n    \"\"\"each result object was constructed by SimulationResult(xs=xs, du_dls=full_du_dls, du_dps=grads)\n\n    for each field, concatenate into an array\n    \"\"\"\n\n    xs = np.array([r.xs for r in results])\n    du_dls = np.array([r.du_dls for r in results])\n    # without dtype=object get a warning about ragged arrays (inconsistent size/type)\n    du_dps = np.array([r.du_dps for r in results], dtype=object)\n\n    return xs, du_dls, du_dps\n\n\ndef _blew_up(results: List[SimulationResult]) -> bool:\n    \"\"\"if stddev(du_dls) for any window exceeded 1000 kJ/mol, don't trust result enough to take a step\n    if du_dls contains any nans, don't trust result enough to take a step\"\"\"\n    du_dls = _results_to_arrays(results)[1]\n\n    # TODO: adjust this threshold a bit, move reliability calculations into fe/estimator.py or fe/model.py\n    return np.isnan(du_dls).any() or (du_dls.std(1).max() > 1000)\n\n\ndef loss_fxn(ff_params, batch: List[Tuple[RelativeFreeEnergy, RBFEModel]]):\n    index = RBFETransformIndex()\n    index.build([edge[0] for edge in batch])\n    indices = []\n    all_results = []\n    preds = []\n    for rfe, model in batch:\n        indices.append(list(index.get_transform_indices(rfe)))\n        pred_ddG, stage_results = model.predict(ff_params, rfe.mol_a, rfe.mol_b, rfe.core)\n        all_results.extend(list(stage_results))\n        preds.append(pred_ddG)\n    labels = jnp.asarray([rfe.label for rfe, _ in batch])\n    loss = pseudo_huber_loss(jnp.asarray(preds) - labels)\n    # Aggregate the pseudo huber loss using mean\n    loss = jnp.mean(loss)\n    return loss, (preds, all_results)\n\n\ndef run_validation_edges(validation: Dataset, params, systems, epoch, inference: bool = False):\n    if len(validation) <= 0:\n        return\n    message_prefix = \"Validation\"\n    if inference:\n        message_prefix = \"Inference\"\n    val_loss = np.zeros(len(validation))\n    for i, rfe in enumerate(validation.data):\n        if getattr(rfe, \"complex_path\", None) is not None:\n            model = systems[rfe.complex_path]\n        else:\n            model = systems[protein_path]\n        start = time()\n\n        loss, (preds, stage_results) = loss_fxn(params, [(rfe, model)])\n        elapsed = time() - start\n        print(f\"{message_prefix} edge {i}: time={elapsed:.2f}s, loss={loss:.2f}\")\n        du_dls_dict = {stage: _results_to_arrays(results)[1] for stage, results in stage_results}\n        np.savez(output_path.joinpath(f\"validation_du_dls_snapshot_{epoch}_{i}.npz\"), **du_dls_dict)\n        val_loss[i] = loss\n    np.savez(output_path.joinpath(f\"validation_edge_losses_{epoch}.npz\"), loss=val_loss)\n\n\ndef equilibrate_edges(datasets: List[Dataset], systems: List[Dict[str, Any]], num_steps: int, cache_path: str):\n    model_set = defaultdict(list)\n    for dataset in datasets:\n        for rfe in dataset.data:\n            if getattr(rfe, \"complex_path\", None) is not None:\n                model_set[rfe.complex_path].append(rfe)\n            else:\n                model_set[protein_path].append(rfe)\n    for path, edges in model_set.items():\n        model = systems[path]\n        model.equilibrate_edges(\n            [(edge.mol_a, edge.mol_b, edge.core) for edge in edges],\n            equilibration_steps=num_steps,\n            cache_path=cache_path,\n        )\n\n\nif __name__ == \"__main__\":\n    default_output_path = f\"results_{datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')}\"\n    parser = ArgumentParser(description=\"Fit Forcefield parameters to hif2a\")\n    parser.add_argument(\n        \"--num_gpus\",\n        default=None,\n        type=int,\n        help=f\"Number of GPUs to run against, defaults to {NUM_GPUS} if no hosts provided\",\n    )\n    parser.add_argument(\"--hosts\", nargs=\"*\", default=None, help=\"Hosts running GRPC worker to use for compute\")\n    parser.add_argument(\"--param_updates\", default=1000, type=int, help=\"Number of updates for parameters\")\n    parser.add_argument(\"--seed\", default=2021, type=int, help=\"Seed for shuffling ordering of transformations\")\n    parser.add_argument(\"--config\", default=\"intermediate\", choices=[\"intermediate\", \"production\", \"test\"])\n    parser.add_argument(\"--batch_size\", default=1, type=int, help=\"Number of items to batch together for training\")\n\n    parser.add_argument(\"--path_to_ff\", default=str(root.joinpath(\"ff/params/smirnoff_1_1_0_ccc.py\")))\n    parser.add_argument(\n        \"--path_to_edges\",\n        default=[\"relative_transformations.pkl\"],\n        nargs=\"+\",\n        help=\"Path to pickle file containing list of RelativeFreeEnergy objects\",\n    )\n    parser.add_argument(\"--split\", action=\"store_true\", help=\"Split edges into train and validation set\")\n    parser.add_argument(\n        \"--pre_equil\",\n        default=None,\n        help=\"Number of pre equilibration steps or path to cached equilibrated edges, if not provided no pre equilibration performed\",\n    )\n    parser.add_argument(\"--hmr\", action=\"store_true\", help=\"Enable HMR\")\n    parser.add_argument(\"--output_path\", default=default_output_path, help=\"Path to output directory\")\n    parser.add_argument(\"--protein_path\", default=None, help=\"Path to protein if edges don't provide protein\")\n    parser.add_argument(\n        \"--inference_only\", action=\"store_true\", help=\"Disable training, run all edges as validation edges\"\n    )\n    # TODO: also make configurable: forces_to_refit, optimizer params, path_to_protein, path_to_protein_ff, ...\n    args = parser.parse_args()\n    protein_path = None\n    if args.protein_path:\n        prot_path = Path(args.protein_path).expanduser()\n        protein_path = prot_path.as_posix()\n        if not prot_path.is_file():\n            print(f\"Unable to find path: {protein_path}\")\n            sys.exit(1)\n\n    # xor num_gpus and hosts args\n    if args.num_gpus is not None and args.hosts is not None:\n        print(\"Unable to provide --num-gpus and --hosts together\")\n        sys.exit(1)\n\n    # which force field components we'll refit\n    forces_to_refit = [AM1CCCHandler, LennardJonesHandler]\n\n    # how much computation to spend per refitting step\n    configuration = None\n    if args.config == \"intermediate\":  # goldilocks\n        configuration = intermediate_configuration\n    elif args.config == \"test\":\n        configuration = testing_configuration  # a little\n    elif args.config == \"production\":\n        configuration = production_configuration  # a lot\n    assert configuration is not None, \"No configuration provided\"\n\n    if not args.hosts:\n        num_gpus = args.num_gpus\n        if num_gpus is None:\n            num_gpus = NUM_GPUS\n        # set up multi-GPU client\n        client = CUDAPoolClient(max_workers=num_gpus)\n    else:\n        # Setup GRPC client\n        client = GRPCClient(hosts=args.hosts)\n    client.verify()\n\n    # load and construct forcefield\n    with open(args.path_to_ff) as f:\n        ff_handlers = deserialize_handlers(f.read())\n\n    forcefield = Forcefield(ff_handlers)\n\n    relative_transformations: List[RelativeFreeEnergy] = []\n    # load pre-defined collection of relative transformations\n    for edge_path in args.path_to_edges:\n        with open(edge_path, \"rb\") as f:\n            relative_transformations.extend(load(f))\n\n    # if older transformation lack a complex_path, rely on --protein_path to set\n    protein_paths = set(x.complex_path for x in relative_transformations if hasattr(x, \"complex_path\"))\n    if protein_path is not None:\n        protein_paths.add(protein_path)\n    if len(protein_paths) == 0:\n        print(\"No proteins provided by edges or with --protein_path\")\n        sys.exit(1)\n\n    # create path if it doesn't exist\n    output_path = Path(args.output_path)\n    output_path.mkdir(parents=True, exist_ok=True)\n    print(f\"Storing results in {output_path}\")\n\n    dataset = Dataset(relative_transformations)\n    if not args.inference_only:\n        if args.split:\n            # TODO: More physically meaningful split\n            # 80, 20 split on transformations\n            training, validation = dataset.random_split(0.8)\n        else:\n            validation = Dataset([])\n            training = dataset\n    else:\n        validation = dataset\n        training = Dataset([])\n\n    with open(output_path.joinpath(\"training_edges.pk\"), \"wb\") as ofs:\n        dump(training.data, ofs)\n    if len(validation):\n        with open(output_path.joinpath(\"validation_edges.pk\"), \"wb\") as ofs:\n            dump(validation.data, ofs)\n\n    # Build all of the different protein systems\n    systems = {}\n    for prot_path in protein_paths:\n        # build the complex system\n        # note: \"complex\" means \"protein + solvent\"\n        complex_system, complex_coords, _, _, complex_box, _ = builders.build_protein_system(prot_path)\n\n        # build the water system\n        solvent_system, solvent_coords, solvent_box, _ = builders.build_water_system(4.0)\n\n        systems[prot_path] = RBFEModel(\n            client=client,\n            ff=forcefield,\n            complex_system=complex_system,\n            complex_coords=complex_coords,\n            complex_box=complex_box,\n            complex_schedule=construct_lambda_schedule(configuration.num_complex_windows),\n            solvent_system=solvent_system,\n            solvent_coords=solvent_coords,\n            solvent_box=solvent_box,\n            solvent_schedule=construct_lambda_schedule(configuration.num_solvent_windows),\n            equil_steps=configuration.num_equil_steps,\n            prod_steps=configuration.num_prod_steps,\n            pre_equilibrate=args.pre_equil is not None,\n            hmr=args.hmr,\n        )\n\n    # TODO: how to get intermediate results from the computational pipeline encapsulated in binding_model.loss ?\n    #   e.g. stage_results, and further diagnostic information\n    #   * x trajectories,\n    #   * d U / d parameters trajectories,\n    #   * matrix of U(x; lambda) for all x, lambda\n    #   * the deltaG pred\n    #   (proper way is probably something like has_aux=True https://jax.readthedocs.io/en/latest/jax.html#jax.value_and_grad)\n\n    ordered_params = forcefield.get_ordered_params()\n    ordered_handles = forcefield.get_ordered_handles()\n\n    # compute and save the sequence of relative_transformation indices\n    num_epochs = int(np.ceil(args.param_updates / len(relative_transformations)))\n    np.random.seed(args.seed)\n\n    batch_size = args.batch_size\n    step_inds = []\n    for epoch in range(num_epochs):\n        inds = np.arange(len(training.data))\n        np.random.shuffle(inds)\n        batched_inds = []\n        num_steps = (len(inds) + batch_size - 1) // batch_size\n        for i in range(num_steps):\n            offset = i * batch_size\n            batched_inds.append(inds[offset : offset + batch_size])\n        step_inds.append(np.asarray(batched_inds, dtype=object))\n\n    np.save(output_path.joinpath(\"step_indices.npy\"), np.hstack(step_inds)[: args.param_updates])\n\n    pre_equil = args.pre_equil\n    if pre_equil is not None:\n        steps = 0\n        cache_path = output_path.joinpath(\"equilibration_cache.pkl\")\n        if pre_equil.isdigit():\n            steps = int(pre_equil)\n        elif Path(pre_equil).is_file():\n            cache_path = pre_equil\n        else:\n            print(f\"Must provide either an integer or a valid path for --pre_equil, got {pre_equil}\")\n            sys.exit(1)\n\n        equilibrate_edges([training, validation], systems, steps, cache_path)\n\n    flatten, unflatten = flatten_and_unflatten(ordered_params)\n\n    step = 0\n    # in each optimizer step, look at one transformation from relative_transformations\n    for epoch in range(num_epochs):\n        # Run Validation edges at start of epoch. Unlike NNs we have a reasonable starting\n        # point that is worth knowing\n        run_validation_edges(validation, ordered_params, systems, epoch + 1, inference=args.inference_only)\n        print(f\"Epoch: {epoch+1}/{num_epochs}\")\n        for batch in step_inds[epoch]:\n            batch_data = []\n            for i in batch:\n                rfe = training.data[i]\n                if getattr(rfe, \"complex_path\", None):\n                    model = systems[rfe.complex_path]\n                else:\n                    model = systems[protein_path]\n                batch_data.append((rfe, model))\n            # compute a batch, measuring total wall-time\n            t0 = time()\n\n            (loss, (predictions, stage_results)), loss_grads = jax.value_and_grad(loss_fxn, argnums=0, has_aux=True)(\n                ordered_params, batch_data\n            )\n\n            results_this_step = {stage: result for stage, result in stage_results}\n\n            print(f\"at optimizer step {step}, loss={loss:.3f}\")\n\n            # check if it's probably okay to take an optimizer step on the basis of this result\n            # TODO: move responsibility for returning error flags / simulation uncertainty estimates further upstream\n            blown_up = False\n            for stage, results in results_this_step.items():\n                if _blew_up(results):\n                    blown_up = True\n                    print(f\"step {step} blew up in {stage} stage\")\n\n            flat_loss_grad = flatten(loss_grads)\n            flat_theta = flatten(ordered_params)\n\n            # based on current estimate of (loss, grad, and simulation stability), return a conservative step to take in parameter space\n            theta_increment = truncated_step(\n                flat_theta, loss, flat_loss_grad, step_lower_bound=_compute_step_lower_bound(loss, blown_up)\n            )\n            param_increments = unflatten(theta_increment)\n\n            # for any parameter handler types being updated, update in place\n            for handle, increment in zip(ordered_handles, param_increments):\n                handle_type = type(handle)\n                if handle_type in forces_to_refit:\n\n                    # TODO: careful -- this must be a \"+=\" or \"-=\" not an \"=\"!\n                    handle.params += increment\n\n                    nonzero_increments = increment[increment != 0]\n                    min_update = 0.0\n                    max_update = 0.0\n                    if len(nonzero_increments):\n                        min_update = np.min(nonzero_increments)\n                        max_update = np.max(nonzero_increments)\n                    # TODO: replace with a function that knows what to report about each handle type\n                    print(\n                        f\"updated {len(nonzero_increments)} {handle_type.__name__} params by between {min_update:.4f} and {max_update:.4f}\"\n                    )\n\n            t1 = time()\n            elapsed = t1 - t0\n\n            print(f\"completed forcefield-updating step {step} in {elapsed:.3f} s !\")\n\n            # save du_dls snapshot\n            path_to_du_dls = output_path.joinpath(f\"du_dls_snapshot_{step}.npz\")\n            print(f\"saving du_dl trajs to {path_to_du_dls}\")\n            du_dls_dict = dict()  # keywords here must be strings\n            for stage, results in results_this_step.items():\n                du_dls_dict[stage] = _results_to_arrays(results)[1]\n            np.savez(path_to_du_dls, **du_dls_dict)\n\n            # also save information about this step's parameter gradient and parameter update\n            # results to npz\n            path_to_npz = output_path.joinpath(f\"theta_grad_loss_snapshot_{step}.npz\")\n            print(f\"saving theta, grad, loss snapshot to {path_to_npz}\")\n            np.savez(path_to_npz, theta=np.array(flat_theta), grad=np.array(flat_loss_grad), loss=loss)\n\n            # TODO: same for xs and du_dps snapshots\n\n            # save updated forcefield .py files after every gradient step\n            step_params = serialize_handlers(ff_handlers)\n            # TODO: consider if there's a more modular way to keep track of ff updates\n            _save_forcefield(output_path.joinpath(f\"forcefield_checkpoint_{step}.py\"), ff_params=step_params)\n            step += 1\n            if step >= args.param_updates:\n                break\n    if not args.inference_only:\n        run_validation_edges(validation, ordered_params, systems, epoch + 1)\n", "meta": {"hexsha": "8a094ff8486c8ae43db6c8c77f993809b21b6dde", "size": 19016, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/hif2a/fit_to_multiple_rbfes.py", "max_stars_repo_name": "proteneer/timemachine", "max_stars_repo_head_hexsha": "feee9f24adcb533ab9e1c15a3f4fa4dcc9d9a701", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 91, "max_stars_repo_stars_event_min_datetime": "2019-01-05T17:03:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:08:46.000Z", "max_issues_repo_path": "examples/hif2a/fit_to_multiple_rbfes.py", "max_issues_repo_name": "proteneer/timemachine", "max_issues_repo_head_hexsha": "feee9f24adcb533ab9e1c15a3f4fa4dcc9d9a701", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 474, "max_issues_repo_issues_event_min_datetime": "2019-01-07T14:33:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:15:12.000Z", "max_forks_repo_path": "examples/hif2a/fit_to_multiple_rbfes.py", "max_forks_repo_name": "proteneer/timemachine", "max_forks_repo_head_hexsha": "feee9f24adcb533ab9e1c15a3f4fa4dcc9d9a701", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2019-01-13T00:40:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T10:23:54.000Z", "avg_line_length": 40.5458422175, "max_line_length": 139, "alphanum_fraction": 0.6718552798, "include": true, "reason": "import numpy,import jax,from jax", "num_tokens": 4333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.2751297297667525, "lm_q1q2_score": 0.15361235507297472}}
{"text": "import numpy as np\nfrom .weighted_yield import SSP, lifetime_Argast, lifetime_Raiteri\nfrom .imf import IMF\nfrom .yields import SN2_feedback, AGB_feedback, SN1a_feedback, Hypernova_feedback\nimport copy\n\nclass SSP_wrap():\n\t'''\n\tThis is the wrapper around the SSP function. It preloads the needed classes and calls all nucleosynthetic enrichment processes when the enrichment is calculated.\n\t'''\n\tdef __init__(self, a):\n\t\t'''\n\t\tUpon initialization the default IMF, CC-SN yields, SN Ia yields and AGB yields is loaded.\n\n\t\tINPUT:\n\n\t\t   a = Modelparameter class. So the default IMF etc are loaded. If we want other yield sets etc. loaded we need to specify that in paramter.py\n\t\t'''\n\n\t\t## loading the IMF and the yieldsets prescribed in a (containing all the model parameters)\n\t\tbasic_imf = IMF(a.mmin,a.mmax,a.mass_steps)\n\t\tgetattr(basic_imf, a.imf_type_name)(a.imf_parameter)\n\t\tbasic_sn2 = SN2_feedback()\n\t\tgetattr(basic_sn2, a.yield_table_name_sn2)()\n\t\tbasic_1a = SN1a_feedback()\n\t\tgetattr(basic_1a, a.yield_table_name_1a)()\n\t\tbasic_agb = AGB_feedback()\n\t\tgetattr(basic_agb, a.yield_table_name_agb)()\n\t\t### mixing of Nomoto CC-SN and HN yields\n\t\tif a.yield_table_name_sn2 == 'Nomoto2013':\n\t\t\tbasic_hn = Hypernova_feedback()\n\t\t\tgetattr(basic_hn, a.yield_table_name_hn)()\n\t\t\tfor item in basic_sn2.metallicities:\n\t\t\t\tx = np.copy(basic_sn2.table[item])\n\t\t\t\ty = np.copy(basic_hn.table[item])\n\t\t\t\tfor jtem in basic_hn.masses:\n\t\t\t\t\tbasic_sn2.table[item]['mass_in_remnants'][np.where(basic_sn2.table[item]['Mass']==jtem)] = a.sn2_to_hn * (x['mass_in_remnants'][np.where(x['Mass']==jtem)]) + (1-a.sn2_to_hn) * (y['mass_in_remnants'][np.where(y['Mass']==jtem)])\n\t\t\t\t\tbasic_sn2.table[item]['unprocessed_mass_in_winds'][np.where(basic_sn2.table[item]['Mass']==jtem)] = a.sn2_to_hn * (x['unprocessed_mass_in_winds'][np.where(x['Mass']==jtem)]) + (1-a.sn2_to_hn) * (y['unprocessed_mass_in_winds'][np.where(y['Mass']==jtem)])\n\t\t\t\t\thn_mass = []\n\t\t\t\t\tsn_mass = []\n\t\t\t\t\tfor stem in basic_sn2.elements:\n\t\t\t\t\t\tsn_mass.append(x[stem][np.where(x['Mass']==jtem)])\n\t\t\t\t\t\thn_mass.append(y[stem][np.where(y['Mass']==jtem)])\n\t\t\t\t\t\tbasic_sn2.table[item][stem][np.where(basic_sn2.table[item]['Mass']==jtem)]= a.sn2_to_hn * (x[stem][np.where(x['Mass']==jtem)]) + (1-a.sn2_to_hn) * (y[stem][np.where(y['Mass']==jtem)])\n\t\t## to pass the information on to the feedback calculation\n\t\tself.a = a\n\t\tself.imf = basic_imf\n\t\tself.sn2 = basic_sn2\n\t\tself.sn1a = basic_1a\n\t\tself.agb = basic_agb\n\n\tdef calculate_feedback(self, z, elements, element_fractions, time_steps, ssp_mass):\n\t\t'''\n\t\tThe feedback is calculated for the initializes SSP.\n\n\t\tINPUT:\n\t\t\n\t\t   z = metallicity of the SSP in mass fraction (not normed to solar!)\n\t\t\n\t\t   elements = which elements to follow\n\t\t\n\t\t   element_fractions = the birth material of the SSP in the same order as 'elements'\n\t\t\n\t\t   time_steps = the time-steps for which the enrichment of the SSP should be calculated (usually the time-steps until the end of the chempy simulation)\n\t\t'''\n\t\tif self.a.stochastic_IMF:\n\t\t\timf_copy = copy.copy(self.imf)\n\t\t\timf_copy.stochastic_sampling(ssp_mass)\n\t\telse:\n\t\t\timf_copy = copy.copy(self.imf)\n\t\tbasic_ssp = SSP(False, float(z), imf_copy.x, imf_copy.dm, imf_copy.dn, np.copy(time_steps), list(elements), str(self.a.stellar_lifetimes), str(self.a.interpolation_scheme), bool(self.a.only_net_yields_in_process_tables))\n\t\tbasic_ssp.sn2_feedback(list(self.sn2.elements), dict(self.sn2.table), np.copy(self.sn2.metallicities), float(self.a.sn2mmin), float(self.a.sn2mmax),list(element_fractions))\n\t\tbasic_ssp.agb_feedback(list(self.agb.elements), dict(self.agb.table), list(self.agb.metallicities), float(self.a.agbmmin), float(self.a.agbmmax),np.hstack(element_fractions))\n\t\tbasic_ssp.sn1a_feedback(list(self.sn1a.elements), list(self.sn1a.metallicities), dict(self.sn1a.table), str(self.a.time_delay_functional_form), float(self.a.sn1ammin), float(self.a.sn1ammax), self.a.sn1a_parameter, ssp_mass, bool(self.a.stochastic_IMF))\n\t\tbasic_ssp.bh_feedback(float(self.a.bhmmin),float(self.a.bhmmax),list(elements), np.hstack(element_fractions) , float(self.a.percentage_of_bh_mass))\n\t\t# exposing these tables to the outside wrapper\n\t\tself.table = basic_ssp.table\n\t\tself.sn2_table = basic_ssp.sn2_table\n\t\tself.agb_table = basic_ssp.agb_table\n\t\tself.sn1a_table = basic_ssp.sn1a_table\n\t\tself.bh_table = basic_ssp.bh_table\n\t\tself.inverse_imf = basic_ssp.inverse_imf\n\ndef initialise_stuff(a):\n\t'''\n\tConvenience function initialising the solar abundance, SFR and infall with the default values provided in parameter.py as a\n\t'''\n\tfrom .solar_abundance import solar_abundances\n\tfrom .sfr import SFR\n\tfrom .infall import INFALL\n\n\tbasic_solar = solar_abundances()\n\tgetattr(basic_solar, a.solar_abundance_name)()\n\n\tbasic_sfr = SFR(a.start,a.end,a.time_steps)\n\tif a.basic_sfr_name == 'gamma_function':\n\t\tgetattr(basic_sfr, a.basic_sfr_name)(S0 = a.S_0 * a.mass_factor,a_parameter = a.a_parameter, loc = a.sfr_beginning, scale = a.sfr_scale)\n\telif a.basic_sfr_name == 'model_A':\n\t\tbasic_sfr.model_A(a.mass_factor*a.S_0,a.t_0,a.t_1)\n\telif a.basic_sfr_name == 'prescribed':\n\t\tbasic_sfr.prescribed(a.mass_factor, a.name_of_file)\n\telif a.basic_sfr_name == 'doubly_peaked':\n\t\tbasic_sfr.doubly_peaked(S0 = a.mass_factor*a.S_0, peak_ratio = a.peak_ratio, decay = a.sfr_decay, t0 = a.sfr_t0, peak1t0 = a.peak1t0, peak1sigma = a.peak1sigma)\n\telif a.basic_sfr_name == 'normal':\n\t\tbasic_sfr.normal(S0=a.mass_factor*a.S_0, loc=a.sfr_peak, scale=a.sfr_scale)\n\telif a.basic_sfr_name == 'step':\n\t\tbasic_sfr.step(S0=a.mass_factor*a.S_0, loc=a.sfr_cutoff)\n\telif a.basic_sfr_name == 'non_parametric':\n\t\tbasic_sfr.non_parametric(S0=a.mass_factor*a.S_0, breaks=a.sfr_breaks, weights=a.sfr_weights)\n\tbasic_sfr.sfr = a.total_mass * np.divide(basic_sfr.sfr, sum(basic_sfr.sfr))\n\tbasic_infall = INFALL(np.copy(basic_sfr.t), np.copy(basic_sfr.sfr))\n\tif a.basic_infall_name == 'exponential':\n\t\tgetattr(basic_infall, a.basic_infall_name)((a.infall_amplitude,a.tau_infall,a.infall_time_offset,a.c_infall,a.norm_infall))\n\telif a.basic_infall_name == 'gamma_function':\n\t\tgetattr(basic_infall, a.basic_infall_name)(mass_factor = a.norm_infall, a_parameter = a.infall_a_parameter, loc = a.infall_beginning, scale = a.infall_scale)\n\telif a.basic_infall_name == 'sfr_related':\n\t\tgetattr(basic_infall, a.basic_infall_name)()\n\n\n\treturn basic_solar, basic_sfr, basic_infall\n\ndef Chempy(a):\n\t'''\n\tChemical evolution run with the default parameters using the net yields.\n\n\tINPUT: \n\t\n\t   a = ModelParameters() from parameter.py\n\n\tOUTPUT:\n\t\n\t   cube = The ISM evolution class\n\t\n\t   abundances = The abundances of the ISM\n\t'''\n\tfrom .infall import PRIMORDIAL_INFALL\n\tfrom .time_integration import ABUNDANCE_MATRIX\n\tfrom .making_abundances import mass_fraction_to_abundances\n\tfrom numpy.lib.recfunctions import append_fields\n\tbasic_solar, basic_sfr, basic_infall = initialise_stuff(a)\n\telements_to_trace = a.elements_to_trace\n\tbasic_primordial = PRIMORDIAL_INFALL(list(elements_to_trace),np.copy(basic_solar.table))\n\tbasic_primordial.primordial()\n\t# Needed a rescaling for the shortened sfr\n\tgas_reservoir_mass_factor = a.gas_reservoir_mass_factor / a.shortened_sfr_rescaling\n\t#sfr_factor_for_cosmic_accretion\t= a.sfr_factor_for_cosmic_accretion / a.shortened_sfr_rescaling\n\t#gas_at_start = a.gas_at_start / a.shortened_sfr_rescaling\n\tcube = ABUNDANCE_MATRIX(np.copy(basic_sfr.t),np.copy(basic_sfr.sfr),np.copy(basic_infall.infall),list(elements_to_trace),\nlist(basic_primordial.symbols),list(basic_primordial.fractions),float(a.gas_at_start),list(basic_primordial.symbols),list(basic_primordial.fractions),\nfloat(gas_reservoir_mass_factor),float(a.outflow_feedback_fraction),bool(a.check_processes),float(a.starformation_efficiency),float(a.gas_power),\n float(a.sfr_factor_for_cosmic_accretion), list(basic_primordial.symbols), list(basic_primordial.fractions))\n\tbasic_ssp = SSP_wrap(a)\n\tfor i in range(len(basic_sfr.t)-1):\n\t\tssp_mass = float(basic_sfr.sfr[i])\n\t\t#print(ssp_mass)\n\t\tj = len(basic_sfr.t)-i\n\t\telement_fractions = []\n\t\tfor item in elements_to_trace:\n\t\t\telement_fractions.append(float(np.copy(cube.cube[item][max(i-1,0)]/cube.cube['gas'][max(i-1,0)])))## gas element fractions from one time step before\n\t\tmetallicity = float(cube.cube['Z'][i])\n\t\ttime_steps = np.copy(basic_sfr.t[:j])\n\t\tbasic_ssp.calculate_feedback(float(metallicity), list(elements_to_trace), list(element_fractions), np.copy(time_steps), ssp_mass)\n\t\tcube.advance_one_step(i+1,np.copy(basic_ssp.table),np.copy(basic_ssp.sn2_table),np.copy(basic_ssp.agb_table),np.copy(basic_ssp.sn1a_table),np.copy(basic_ssp.bh_table))\n\t\tif cube.cube['gas'][i] < 0:\n\t\t\tprint(i, basic_sfr.t[i])\n\t\t\tprint('gas became negative. returning -inf')\n\t\t\treturn -np.inf, [0]\n\t\tif cube.gas_reservoir['gas'][i] < 0:\n\t\t\tprint('gas_reservoir became negative. returning -inf')\n\t\t\treturn -np.inf, [0]\n\n\tabundances,elements,numbers = mass_fraction_to_abundances(np.copy(cube.cube),np.copy(basic_solar.table))\n\tweights = cube.cube['sfr']\n\tabundances = append_fields(abundances,'weights',weights)\n\tabundances = append_fields(abundances,'time', cube.cube['time'])\n\tabundances = np.array(abundances)\n\n\treturn cube, abundances\n\n\n\n\ndef Chempy_gross(a):\n\t'''\n\tChemical evolution run with the default parameters but now using solar scaled material (testing the worse case when total yields provided).\n\n\tINPUT: \n\t\n\t   a = ModelParameters() from parameter.py\n\n\tOUTPUT:\n\t\n\t   cube = The ISM evolution class\n\t\n\t   abundances = The abundances of the ISM\n\t'''\n\tfrom infall import PRIMORDIAL_INFALL\n\tfrom time_integration import ABUNDANCE_MATRIX\n\tfrom making_abundances import mass_fraction_to_abundances\n\tfrom numpy.lib.recfunctions import append_fields\n\tbasic_solar, basic_sfr, basic_infall = initialise_stuff(a)\n\telements_to_trace = a.elements_to_trace\n\tbasic_primordial = PRIMORDIAL_INFALL(list(elements_to_trace),np.copy(basic_solar.table))\n\tbasic_primordial.primordial(0)\n\tgas_reservoir_mass_factor = a.gas_reservoir_mass_factor / a.shortened_sfr_rescaling\n\tcube = ABUNDANCE_MATRIX(np.copy(basic_sfr.t),np.copy(basic_sfr.sfr),np.copy(basic_infall.infall),list(elements_to_trace),list(basic_primordial.symbols),\nlist(basic_primordial.fractions),float(a.gas_at_start),list(basic_primordial.symbols),list(basic_primordial.fractions),float(gas_reservoir_mass_factor),\nfloat(a.outflow_feedback_fraction),bool(a.check_processes),float(a.starformation_efficiency),float(a.gas_power), float(a.sfr_factor_for_cosmic_accretion),\nlist(basic_primordial.symbols), list(basic_primordial.fractions))\n\tbasic_ssp = SSP_wrap(a)\n\tfor i in range(len(basic_sfr.t)-1):\n\t\tj = len(basic_sfr.t)-i\n\t\tmetallicity = float(cube.cube['Z'][i])\n\t\tsolar_scaled_material = PRIMORDIAL_INFALL(list(elements_to_trace),np.copy(basic_solar.table))\n\t\tsolar_scaled_material.solar(np.log10(metallicity/basic_solar.z))\n\t\telement_fractions = list(solar_scaled_material.fractions)\n\t\tfor item in elements_to_trace:\n\t\t\telement_fractions.append(float(np.copy(cube.cube[item][max(i-1,0)]/cube.cube['gas'][max(i-1,0)])))## gas element fractions from one time step before\n\t\ttime_steps = np.copy(basic_sfr.t[:j])\n\t\tbasic_ssp.calculate_feedback(float(metallicity), list(elements_to_trace), list(element_fractions), np.copy(time_steps))\n\t\tcube.advance_one_step(i+1,np.copy(basic_ssp.table),np.copy(basic_ssp.sn2_table),np.copy(basic_ssp.agb_table),np.copy(basic_ssp.sn1a_table),np.copy(basic_ssp.bh_table))\n\tabundances,elements,numbers = mass_fraction_to_abundances(np.copy(cube.cube),np.copy(basic_solar.table))\n\tweights = cube.cube['sfr']\n\tabundances = append_fields(abundances,'weights',weights)\n\tabundances = np.array(abundances)\n\n\treturn cube, abundances\n\n\ndef multi_star_optimization():\n\t'''\n\tThis function will optimize the parameters of all stars in a hierachical manner (similar to gibbs sampling)\n\n\tINPUT: \n\n\t   a = will be loaded from parameter.py (prepare all variables there)\n\n\tOUTPUT:\n\n\t   log_list = a list of intermediate results (so far only for debugging)\n\t'''\n\timport time\n\timport multiprocessing as mp\n\tfrom .optimization import minimizer_initial, minimizer_global, minimizer_local\n\tfrom .cem_function import global_optimization_error_returned\n\tfrom .parameter import ModelParameters\n\n\ta = ModelParameters()\n\tprint(a.stellar_identifier_list)\n\tstart_time = time.time()\n\n\tlog_list = []\n\t# I: Minimization for each star seperately\n\t# 1: for each star make initial conditions (each star needs other model parameters)\n\tparameter_list = []\n\tfor item in a.stellar_identifier_list:\n\t\tparameter_list.append(item)\n\t# 2: call posterior_function_for_minimization with scipy.optimize.minimize in multiprocess for each star and recover the found parameters\n\tp = mp.Pool(len(parameter_list))\n\tt = p.map(minimizer_initial, parameter_list)\n\tp.close()\n\tp.join()\n\tresult = np.vstack(t)\n\n\tlog_list.append(np.copy(result))\n\tlog_list.append('initial minimization')\n\tinitial = time.time()\n\tprint('first minimization for each star separately took: %2.f seconds' %(initial - start_time))\n\n\t# IV: repeat II and III until posterior does not change much\n\tresult[:,:len(a.SSP_parameters)] = np.mean(result[:,:len(a.SSP_parameters)], axis = 0)\n\tposteriors = []\n\tcounter = 0\n\twhile True:\n\t\tcounter += 1\n\t\tif len(posteriors) > 1:\n\t\t\tif np.abs(posteriors[-1] - posteriors[-2]) < a.gibbs_sampler_tolerance:\n\t\t\t\tbreak\n\t\t\tif len(posteriors) > a.gibbs_sampler_maxiter:\n\t\t\t\tbreak\n\n\t\tinitial = time.time()\n\t\t# II: Global parameter minimization:\n\t\t# 1: only SSP parameters free. Use mean SSP parameter values and individual (but fixed ISM parameter values)\n\t\tchanging_parameter = result[0,:len(a.SSP_parameters)]\n\t\t# 2: Call each star in multiprocess but only return the predictions\n\t\t# 3: Calculate the likelihood for each star and optimize the common model error (is all done within minimizer global, which is calling 'global optimization')\n\t\tx = minimizer_global(changing_parameter,  a.tol_minimization, a.maxiter_minimization, a.verbose, result)\n\n\t\t# 4: return global SSP parameters and common model error\n\t\tposterior, error_list, elements = global_optimization_error_returned(x, result)\n\t\tposteriors.append(posterior)\n\t\tprint(posteriors)\n\n\t\tglobal_iteration1 = time.time()\n\t\tprint('step %d global minimization took: %2.f seconds' %(counter, global_iteration1 - initial))\n\n\t\t# III: Local parameter minimization:\n\t\t# 1: Use fixed global parameters and fixed common errors make initial conditions\n\t\tresult[:,:len(a.SSP_parameters)] = x\n\n\t\tlog_list.append((np.copy(x),posterior))\n\t\tlog_list.append('step %d global minimization' %(counter))\n\n\t\tp0_list = []\n\t\tparameter_list = []\n\t\tx_list = []\n\t\terror_list_mp = []\n\t\telement_list_mp = []\n\n\t\tfor i,item in enumerate(a.stellar_identifier_list):\n\t\t\tparameter_list.append(item)\n\t\t\tp0_list.append(result[i,len(a.SSP_parameters):])\n\t\t\tx_list.append(x)\n\t\t\terror_list_mp.append(error_list)\n\t\t\telement_list_mp.append(elements)\n\n\t\targs = zip(p0_list,parameter_list,x_list,error_list_mp,element_list_mp)\n\n\t\t# 2: Minimize each star ISM parameters in multiprocess\n\t\tp = mp.Pool(len(parameter_list))\n\t\tt = p.map(minimizer_local, args)\n\t\tp.close()\n\t\tp.join()\n\t\tlocal_parameters = np.vstack(t)\n\t\tresult[:,len(a.SSP_parameters):] = local_parameters\n\n\t\tlog_list.append(np.copy(result))\n\t\tlog_list.append('step %d local minimization' %(counter))\n\t\tlocal_iteration1 = time.time()\n\t\tprint('step %d local minimization took: %2.f seconds' %(counter, local_iteration1 - global_iteration1))\n\n\tlog_list.append(posteriors)\n\tprint(log_list)\n\n\t# V: MCMC run\n\t## reshape the result to have global parameters in the front and the local parameters following\n\tchanging_parameter = list(result[0,:len(a.SSP_parameters)])\n\tfor i in range(result.shape[0]):\n\t\tchanging_parameter.append(list(result[i,len(a.SSP_parameters):]))\n\tchanging_parameter = np.hstack(changing_parameter)\n\t## jitter the parameters to initialise the chain (add a validation later, i.e. testing that the particular parameters yield a result)\n\tmcmc_multi(changing_parameter, error_list, elements)\n\t# 1: Free all parameters and optimize common error (SSP should be the same for all stars)\n\t# 2: Plug everything into emcee and sample the posterior\n\treturn log_list\n\ndef mcmc(a):\n\t'''\n\tConvenience function to use the MCMC. A subdirectory mcmc/ will be created in the current directory and intermediate chains will be stored there.\n\tThe chains are not actually flattened as the file name suggests.\n\t\n\tThe MCMC will sample the volume of best posterior for the likelihood functions that are declared in parameter.py. Default is ['sol_norm','gas_reservoir','sn_ratio'] which corresponds to 'Sun+' from the paper.\n\t'''\n\timport time\n\timport os\n\timport multiprocessing as mp\n\tfrom .optimization import creating_chain, posterior_probability\n\timport emcee\n\n\tstart1 = time.time()\n\tdirectory = 'mcmc/'\n\tif os.path.exists(directory):\n\t\tif a.verbose:\n\t\t\tprint('%s already existed. Content might be overwritten' %(directory))\n\telse:\n\t\tos.makedirs(directory)\n\n\ta.check_processes = False\n\ta.number_of_models_overplotted = 1\n\ta.only_net_yields_in_process_tables = False\n\ta.testing_output = False\n\ta.summary_pdf = False\n\ta.nthreads = mp.cpu_count()\n\tif a.nthreads == 4:\n\t\ta.nthreads = 2\n\n\tchain = creating_chain(a,np.copy(a.p0))\n\tsampler = emcee.EnsembleSampler(a.nwalkers,a.ndim,posterior_probability,threads=a.nthreads, args = [a])\n\tpos,prob,state,blobs = sampler.run_mcmc(chain,a.mburn)\n\n\tmean_prob = mean_prob_beginning = np.zeros((a.m))\n\tposterior_list = []\n\tposterior_std_list = []\n\tfor i in range(a.m):\n\t\tprint('step ', i+1 , 'of ',a.m)\n\t\tpos, prob, state, blobs = sampler.run_mcmc(pos, a.save_state_every, rstate0=state, lnprob0=prob, blobs0 = blobs, storechain = True)\n\t\tnp.save('%s/flatchain' %(directory),sampler.chain)\n\t\tnp.save('%s/flatlnprobability' %(directory),sampler.lnprobability)\n\t\tnp.save('%s/flatblobs' %(directory),sampler.blobs)\n\t\tposterior = np.load('%s/flatlnprobability.npy' %(directory))\n\t\tposterior_list.append(np.mean(posterior, axis = 0)[-1])\n\t\tposterior_std_list.append(np.std(posterior, axis = 0)[-1])\n\t\tnp.save('%s/flatmeanposterior' %(directory), posterior_list)\n\t\tnp.save('%s/flatstdposterior' %(directory), posterior_std_list)\n\t\tprint(np.mean(posterior, axis = 0)[0], np.mean(posterior, axis = 0)[-1])\n\n\t\tif i>202:\n\t\t\tprint('posterior -1, -100, -200',np.mean(posterior, axis = 0)[-1], np.mean(posterior, axis = 0)[-100], np.mean(posterior, axis = 0)[-200])\n\t\t\tprint('posterior 0, 100, 200',np.mean(posterior, axis = 0)[0], np.mean(posterior, axis = 0)[100], np.mean(posterior, axis = 0)[200])\n\t\t#print(\"Mean acceptance fraction:\", sampler.acceptance_fraction)\n\t\telapsed1 = (time.time() - start1)\n\t\tprint('calculation so far took', elapsed1, ' seconds')\n\t\tif i>a.min_mcmc_iterations and np.abs(np.mean(posterior, axis = 0)[-1] - np.mean(posterior, axis = 0)[-100]) < a.mcmc_tolerance and np.abs(np.mean(posterior, axis = 0)[-1] - np.mean(posterior, axis = 0)[-200]) < a.mcmc_tolerance:\n\t\t\tbreak\n\tif a.send_email:\n\t\tsend_email(a.nthreads, i, np.mean(posterior, axis = 0)[0], np.mean(posterior, axis = 0)[-1], a, elapsed1)\n\n\n\ndef mcmc_multi(changing_parameter, error_list, elements):\n\t'''\n\tConvenience function to use the MCMC for multiple zones (and therefore multiple observations). A subdirectory mcmc/ will be created in the current directory and intermediate chains will be stored there.\n\tThe MCMC will sample the volume of best posterior for the likelihood functions that are declared in parameter.py. \n\tDefault is a list of Proto-sun, Arcturus and B-stars. The MCMC uses many walkers and can use multiple threads. Each walker will evaluate a series of Chempy zones and add their posterior together which then will be returned.\n\t\n\tINPUT:\n\n\t   changing_parameter = the parameter vector for initialization (will usually be found from minimization before). The initial chain will be created by jittering slightly the initial parameter guess\n\n\t   error_list = the vector of element errors\n\n\t   elements = the corresponding element symbols\n\n\tOUTPUT:\n\n\t   The function will create a folder and store the chain as well as the predicted element values\n\n\tThe MCMC stops when the convergence criteria is met, which is when the median posterior of all walkers does not change much inbetween 200 steps anymore.\n\t'''\n\timport time\n\timport os\n\timport multiprocessing as mp\n\tfrom .cem_function import  posterior_function_many_stars\n\tfrom .parameter import ModelParameters\n\timport emcee\n\n\ta = ModelParameters()\n\tstart1 = time.time()\n\tdirectory = 'mcmc/'\n\tif os.path.exists(directory):\n\t\tif a.verbose:\n\t\t\tprint('%s already existed. Content might be overwritten' %(directory))\n\telse:\n\t\tos.makedirs(directory)\n\n\tnthreads = mp.cpu_count()\n\tif nthreads == 4:\n\t\tnthreads = 2\n\tndim = len(changing_parameter)\n\ta.nwalkers = max(a.nwalkers, int(ndim*2))\n\tchain = np.empty(shape = (a.nwalkers,ndim))\n\tfor i in range(a.nwalkers):\n\t\tresult = -np.inf\n\t\twhile result == -np.inf:\n\t\t\tjitter = np.random.normal(loc = 0, scale = 0.001, size = ndim)\n\t\t\tresult, dummy = posterior_function_many_stars(changing_parameter + jitter,error_list,elements)\n\t\tchain[i] = changing_parameter + jitter\n\n\tsampler = emcee.EnsembleSampler(a.nwalkers,ndim,posterior_function_many_stars,threads=nthreads, args = [error_list,elements])\n\tpos,prob,state,blobs = sampler.run_mcmc(chain,a.mburn)\n\n\tmean_prob = mean_prob_beginning = np.zeros((a.m))\n\tposterior_list = []\n\tposterior_std_list = []\n\tfor i in range(a.m):\n\t\tprint('step ', i+1 , 'of ',a.m)\n\t\tpos, prob, state, blobs = sampler.run_mcmc(pos, a.save_state_every, rstate0=state, lnprob0=prob, blobs0 = blobs, storechain = True)\n\t\tnp.save('%s/flatchain' %(directory),sampler.chain)\n\t\tnp.save('%s/flatlnprobability' %(directory),sampler.lnprobability)\n\t\tnp.save('%s/flatblobs' %(directory),sampler.blobs)\n\t\tposterior = np.load('%s/flatlnprobability.npy' %(directory))\n\t\tposterior_list.append(np.mean(posterior, axis = 0)[-1])\n\t\tposterior_std_list.append(np.std(posterior, axis = 0)[-1])\n\t\tnp.save('%s/flatmeanposterior' %(directory), posterior_list)\n\t\tnp.save('%s/flatstdposterior' %(directory), posterior_std_list)\n\t\tprint(np.mean(posterior, axis = 0)[0], np.mean(posterior, axis = 0)[-1])\n\n\t\tif i>202:\n\t\t\tprint('posterior -1, -100, -200',np.mean(posterior, axis = 0)[-1], np.mean(posterior, axis = 0)[-100], np.mean(posterior, axis = 0)[-200])\n\t\t\tprint('posterior 0, 100, 200',np.mean(posterior, axis = 0)[0], np.mean(posterior, axis = 0)[100], np.mean(posterior, axis = 0)[200])\n\t\t#print(\"Mean acceptance fraction:\", sampler.acceptance_fraction)\n\t\telapsed1 = (time.time() - start1)\n\t\tprint('calculation so far took', elapsed1, ' seconds')\n\t\tif i>a.min_mcmc_iterations and np.abs(np.mean(posterior, axis = 0)[-1] - np.mean(posterior, axis = 0)[-100]) < a.mcmc_tolerance and np.abs(np.mean(posterior, axis = 0)[-1] - np.mean(posterior, axis = 0)[-200]) < a.mcmc_tolerance:\n\t\t\tbreak\n\tif a.send_email:\n\t\tsend_email(nthreads, i, np.mean(posterior, axis = 0)[0], np.mean(posterior, axis = 0)[-1], a, elapsed1)\n\n\ndef send_email(thread_count, iteration_count, posterior_beginning, posterior_end, parameters, time):\n\tfrom email.MIMEMultipart import MIMEMultipart\n\tfrom email.MIMEText import MIMEText\n\timport smtplib\n\n\n\tfromaddr = \"pythonspeaking@gmail.com\"\n\ttoaddr = \"rybizki@mpia.de\"\n\tmsg = MIMEMultipart()\n\tmsg['From'] = fromaddr\n\tmsg['To'] = toaddr\n\tmsg['Subject'] = \"Threads = %d, Run finished after %.2f hours\" %(thread_count, time/3600.)\n\tbody = \"After %.1f hours %d threads produced %d iterations.\\n The posterior at beginning was: %.2f. The posterior now is: %.2f.\\n The stellar identifier list = %s.\\n The error marginalization is %s \\n  The yields are: %s %s %s \\n \" %(time/3600., thread_count, iteration_count, posterior_beginning, posterior_end, str(parameters.stellar_identifier_list), str(parameters.error_marginalization), parameters.yield_table_name_sn2, parameters.yield_table_name_agb, parameters.yield_table_name_1a)\n\tmsg.attach(MIMEText(body, 'plain'))\n\n\tserver = smtplib.SMTP('smtp.gmail.com', 587)\n\tserver.ehlo()\n\tserver.starttls()\n\tserver.ehlo()\n\tserver.login(\"pythonspeaking@gmail.com\", \"MPIA_Server_runs\")\n\ttext = msg.as_string()\n\tserver.sendmail(fromaddr, toaddr, text)\n", "meta": {"hexsha": "4529eab700b8aa5887357b9112974907d966e4df", "size": 24016, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chempy/wrapper.py", "max_stars_repo_name": "TobiBu/Chempy", "max_stars_repo_head_hexsha": "68d3ca6dfbc1bb2f71b2c0fdcc501302e71e33f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chempy/wrapper.py", "max_issues_repo_name": "TobiBu/Chempy", "max_issues_repo_head_hexsha": "68d3ca6dfbc1bb2f71b2c0fdcc501302e71e33f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chempy/wrapper.py", "max_forks_repo_name": "TobiBu/Chempy", "max_forks_repo_head_hexsha": "68d3ca6dfbc1bb2f71b2c0fdcc501302e71e33f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.8148148148, "max_line_length": 491, "alphanum_fraction": 0.7521235843, "include": true, "reason": "import numpy,from numpy", "num_tokens": 6691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.26588047891687405, "lm_q1q2_score": 0.1535447442678787}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nsRGB Colourspace\n================\n\nDefines the *sRGB* colourspace:\n\n-   :attr:`sRGB_COLOURSPACE`.\n\nSee Also\n--------\n`RGB Colourspaces IPython Notebook\n<http://nbviewer.ipython.org/github/colour-science/colour-ipython/blob/master/notebooks/models/rgb.ipynb>`_  # noqa\n\nReferences\n----------\n.. [1]  `Recommendation ITU-R BT.709-5 - Parameter values for the HDTV\n        standards for production and international programme exchange\n        <http://www.itu.int/dms_pubrec/itu-r/rec/bt/R-REC-BT.709-5-200204-I!!PDF-E.pdf>`_  # noqa\n        (Last accessed 24 February 2014)\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\n\nfrom colour.colorimetry import ILLUMINANTS\nfrom colour.models import RGB_Colourspace\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013 - 2014 - Colour Developers'\n__license__ = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-science@googlegroups.com'\n__status__ = 'Production'\n\n__all__ = ['sRGB_PRIMARIES',\n           'sRGB_WHITEPOINT',\n           'sRGB_TO_XYZ_MATRIX',\n           'XYZ_TO_sRGB_MATRIX',\n           'sRGB_TRANSFER_FUNCTION',\n           'sRGB_INVERSE_TRANSFER_FUNCTION',\n           'sRGB_COLOURSPACE']\n\nsRGB_PRIMARIES = np.array(\n    [[0.6400, 0.3300],\n     [0.3000, 0.6000],\n     [0.1500, 0.0600]])\n\"\"\"\n*sRGB* colourspace primaries.\n\nsRGB_PRIMARIES : ndarray, (3, 2)\n\"\"\"\n\nsRGB_WHITEPOINT = ILLUMINANTS.get(\n    'CIE 1931 2 Degree Standard Observer').get('D65')\n\"\"\"\n*sRGB* colourspace whitepoint.\n\nsRGB_WHITEPOINT : tuple\n\"\"\"\n\nsRGB_TO_XYZ_MATRIX = np.array(\n    [[0.41238656, 0.35759149, 0.18045049],\n     [0.21263682, 0.71518298, 0.0721802],\n     [0.01933062, 0.11919716, 0.95037259]])\n\"\"\"\n*sRGB* colourspace to *CIE XYZ* colourspace matrix.\n\nsRGB_TO_XYZ_MATRIX : array_like, (3, 3)\n\"\"\"\n\nXYZ_TO_sRGB_MATRIX = np.linalg.inv(sRGB_TO_XYZ_MATRIX)\n\"\"\"\n*CIE XYZ* colourspace to *sRGB* colourspace matrix.\n\nXYZ_TO_sRGB_MATRIX : array_like, (3, 3)\n\"\"\"\n\nsRGB_TRANSFER_FUNCTION = lambda x: (\n    x * 12.92 if x <= 0.0031308 else 1.055 * (x ** (1 / 2.4)) - 0.055)\n\"\"\"\nTransfer function from linear to *sRGB* colourspace.\n\nsRGB_TRANSFER_FUNCTION : object\n\"\"\"\n\nsRGB_INVERSE_TRANSFER_FUNCTION = lambda x: (\n    x / 12.92 if x <= 0.0031308 else ((x + 0.055) / 1.055) ** 2.4)\n\"\"\"\nInverse transfer function from *sRGB* colourspace to linear.\n\nsRGB_INVERSE_TRANSFER_FUNCTION : object\n\"\"\"\n\nsRGB_COLOURSPACE = RGB_Colourspace(\n    'sRGB',\n    sRGB_PRIMARIES,\n    sRGB_WHITEPOINT,\n    sRGB_TO_XYZ_MATRIX,\n    XYZ_TO_sRGB_MATRIX,\n    sRGB_TRANSFER_FUNCTION,\n    sRGB_INVERSE_TRANSFER_FUNCTION)\n\"\"\"\n*sRGB* colourspace.\n\nsRGB_COLOURSPACE : RGB_Colourspace\n\"\"\"\n", "meta": {"hexsha": "7f7779dab73d83b6026bee89a990adef0f75d5fe", "size": 2742, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/models/dataset/srgb.py", "max_stars_repo_name": "canavandl/colour", "max_stars_repo_head_hexsha": "a453cd37b6135a9092d5ea5b2aafb8d19134bdff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-27T11:32:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-27T11:32:48.000Z", "max_issues_repo_path": "colour/models/dataset/srgb.py", "max_issues_repo_name": "canavandl/colour", "max_issues_repo_head_hexsha": "a453cd37b6135a9092d5ea5b2aafb8d19134bdff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/models/dataset/srgb.py", "max_forks_repo_name": "canavandl/colour", "max_forks_repo_head_hexsha": "a453cd37b6135a9092d5ea5b2aafb8d19134bdff", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7027027027, "max_line_length": 115, "alphanum_fraction": 0.6903719912, "include": true, "reason": "import numpy", "num_tokens": 853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438502, "lm_q2_score": 0.24798743735585302, "lm_q1q2_score": 0.1534497740500806}}
{"text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nimport libs.boxes.cython_bbox as cython_bbox\nimport libs.configs.config_v1 as cfg\nfrom libs.boxes.bbox_transform import bbox_transform, bbox_transform_inv, clip_boxes\nfrom libs.boxes.anchor import anchors_plane\nfrom libs.logs.log import LOG\n# FLAGS = tf.app.flags.FLAGS\n\n_DEBUG = False\n\ndef encode(gt_boxes, all_anchors, height, width, stride):\n  \"\"\"Matching and Encoding groundtruth into learning targets\n  Sampling\n  \n  Parameters\n  ---------\n  gt_boxes: an array of shape (G x 5), [x1, y1, x2, y2, class]\n  all_anchors: an array of shape (h, w, A, 4),\n  width: width of feature\n  height: height of feature\n  stride: downscale factor w.r.t the input size, e.g., [4, 8, 16, 32]\n  Returns\n  --------\n  labels:   Nx1 array in [0, num_classes]\n  bbox_targets: N x (4) regression targets\n  bbox_inside_weights: N x (4), in {0, 1} indicating to which class is assigned.\n  \"\"\"\n  # TODO: speedup this module\n  if all_anchors is None:\n    all_anchors = anchors_plane(height, width, stride=stride)\n\n  # anchors, inds_inside, total_anchors\n  border = cfg.FLAGS.allow_border\n  all_anchors = all_anchors.reshape((-1, 4))\n  inds_inside = np.where(\n    (all_anchors[:, 0] >= -border) &\n    (all_anchors[:, 1] >= -border) &\n    (all_anchors[:, 2] < (width * stride) + border) &\n    (all_anchors[:, 3] < (height * stride) + border))[0]\n  anchors = all_anchors[inds_inside, :]\n  total_anchors = all_anchors.shape[0]\n\n  # choose boxes to assign to this stride\n  # TODO gt assignment outside\n  if False:\n    areas = (gt_boxes[:, 3] - gt_boxes[:, 1] + 1) * (gt_boxes[:, 2] - gt_boxes[:, 0] + 1)\n    ks = np.floor(4 + np.log2(np.sqrt(areas) / 224.0))\n    K = int(np.log2(stride))\n    inds = np.where((K == ks + 4))[0]\n    if inds.size > 0:\n      gt_boxes = gt_boxes[inds]\n    else:\n      labels = np.zeros((total_anchors), dtype=np.float32)\n      bbox_targets = np.zeros((total_anchors, 4), dtype=np.float32)\n      bbox_inside_weights = np.zeros((total_anchors, 4), dtype=np.float32)\n      return labels, bbox_targets, bbox_inside_weights\n\n  labels = np.zeros((anchors.shape[0], ), dtype=np.float32)\n\n  if gt_boxes.size > 0:\n      overlaps = cython_bbox.bbox_overlaps(\n                 np.ascontiguousarray(anchors, dtype=np.float),\n                 np.ascontiguousarray(gt_boxes[:, :4], dtype=np.float))\n\n      if _DEBUG:\n          print ('gt_boxes shape: ', gt_boxes.shape)\n          print ('anchors shape: ', anchors.shape)\n          print ('overlaps shape: ', overlaps.shape)\n\n      gt_assignment = overlaps.argmax(axis=1)  # (A)\n      max_overlaps = overlaps[np.arange(len(inds_inside)), gt_assignment]\n      gt_argmax_overlaps = overlaps.argmax(axis=0)  # G\n      gt_max_overlaps = overlaps[gt_argmax_overlaps,\n                                 np.arange(overlaps.shape[1])]\n      \n      if False:\n        # this is sentive to boxes of little overlaps, no need!\n        gt_argmax_overlaps = np.where(overlaps == gt_max_overlaps)[0]\n\n      # fg label: for each gt, assign anchor with highest overlap despite its overlaps\n      labels[gt_argmax_overlaps] = 1\n      # fg label: above threshold IOU\n      labels[max_overlaps >= cfg.FLAGS.fg_threshold] = 1\n      # print (np.min(labels), np.max(labels))\n\n      # subsample positive labels if there are too many\n      num_fg = int(cfg.FLAGS.fg_rpn_fraction * cfg.FLAGS.rpn_batch_size)\n      fg_inds = np.where(labels == 1)[0]\n      if len(fg_inds) > num_fg:\n        disable_inds = np.random.choice(fg_inds, size=(len(fg_inds) - num_fg), replace=False)\n        labels[disable_inds] = -1\n  else:\n      # if there is no gt\n      labels[:] = 0\n\n  # TODO: mild hard negative mining\n  # subsample negative labels if there are too many\n  num_bg = cfg.FLAGS.rpn_batch_size - np.sum(labels == 1)\n  bg_inds = np.where(labels == 0)[0]\n  if len(bg_inds) > num_bg:\n    disable_inds = np.random.choice(bg_inds, size=(len(bg_inds) - num_bg), replace=False)\n    labels[disable_inds] = -1\n\n  bbox_targets = np.zeros((len(inds_inside), 4), dtype=np.float32)\n  if gt_boxes.size > 0:\n    bbox_targets = _compute_targets(anchors, gt_boxes[gt_assignment, :])\n  bbox_inside_weights = np.zeros((len(inds_inside), 4), dtype=np.float32)\n  bbox_inside_weights[labels == 1, :] = 1\n\n  # mapping to whole outputs\n  labels = _unmap(labels, total_anchors, inds_inside, fill=-1)\n  bbox_targets = _unmap(bbox_targets, total_anchors, inds_inside, fill=0)\n  bbox_inside_weights = _unmap(bbox_inside_weights, total_anchors, inds_inside, fill=0)\n\n  labels = labels.reshape((1, height, width, -1))\n  bbox_targets = bbox_targets.reshape((1, height, width, -1))\n  bbox_inside_weights = bbox_inside_weights.reshape((1, height, width, -1))\n\n  return labels, bbox_targets, bbox_inside_weights\n\ndef decode(boxes, scores, all_anchors, ih, iw):\n  \"\"\"Decode outputs into boxes\n  Parameters\n  ---------\n  boxes: an array of shape (1, h, w, Ax4)\n  scores: an array of shape (1, h, w, Ax2),\n  all_anchors: an array of shape (1, h, w, Ax4), [x1, y1, x2, y2]\n  \n  Returns\n  --------\n  final_boxes: of shape (R x 4)\n  classes: of shape (R) in {0,1,2,3... K-1}\n  scores: of shape (R) in [0 ~ 1]\n  \"\"\"\n  h, w = boxes.shape[1], boxes.shape[2]\n  if all_anchors is  None:\n    stride = 2 ** int(round(np.log2((iw + 0.0) / w)))\n    all_anchors = anchors_plane(h, w, stride=stride)\n  all_anchors = all_anchors.reshape((-1, 4))\n  boxes = boxes.reshape((-1, 4))\n  scores = scores.reshape((-1, 2))\n  assert scores.shape[0] == boxes.shape[0] == all_anchors.shape[0], \\\n    'Anchor layer shape error %d vs %d vs %d' % (scores.shape[0],boxes.shape[0],all_anchors.reshape[0])\n  boxes = bbox_transform_inv(all_anchors, boxes)\n  classes = np.argmax(scores, axis=1)\n  scores = scores[:, 1]\n  final_boxes = boxes  \n  final_boxes = clip_boxes(final_boxes, (ih, iw))\n  classes = classes.astype(np.int32)\n  return final_boxes, classes, scores\n\ndef sample(boxes, scores, ih, iw, is_training):\n  \"\"\"\n  Sampling the anchor layer outputs for next stage, mask or roi prediction or roi\n  \n  Params\n  ----------\n  boxes:  of shape (? ,4)\n  scores: foreground prob\n  ih:     image height\n  iw:     image width\n  is_training:  'test' or 'train'\n  \n  Returns\n  ----------\n  rois: of shape (N, 4)\n  scores: of shape (N, 1)\n  batch_ids:\n  \"\"\"\n  return\n\n\ndef _unmap(data, count, inds, fill=0):\n  \"\"\" Unmap a subset of item (data) back to the original set of items (of\n  size count) \"\"\"\n  if len(data.shape) == 1:\n    ret = np.empty((count,), dtype=np.float32)\n    ret.fill(fill)\n    ret[inds] = data\n  else:\n    ret = np.empty((count,) + data.shape[1:], dtype=np.float32)\n    ret.fill(fill)\n    ret[inds, :] = data\n  return ret\n  \ndef _compute_targets(ex_rois, gt_rois):\n  \"\"\"Compute bounding-box regression targets for an image.\"\"\"\n\n  assert ex_rois.shape[0] == gt_rois.shape[0]\n  assert ex_rois.shape[1] == 4\n  assert gt_rois.shape[1] == 5\n\n  return bbox_transform(ex_rois, gt_rois[:, :4]).astype(np.float32, copy=False)\n\nif __name__ == '__main__':\n  \n  import time\n  t = time.time()\n  \n  for i in range(10):\n    cfg.FLAGS.fg_threshold = 0.1\n    classes = np.random.randint(0, 3, (50, 1))\n    boxes = np.random.randint(10, 50, (50, 2))\n    s = np.random.randint(20, 50, (50, 2))\n    s = boxes + s\n    boxes = np.concatenate((boxes, s), axis=1)\n    gt_boxes = np.hstack((boxes, classes))\n    # gt_boxes = boxes\n    rois = np.random.randint(10, 50, (20, 2))\n    s = np.random.randint(0, 20, (20, 2))\n    s = rois + s\n    rois = np.concatenate((rois, s), axis=1)\n    labels, bbox_targets, bbox_inside_weights = encode(gt_boxes, all_anchors=None, height=200, width=300, stride=4)\n    labels, bbox_targets, bbox_inside_weights = encode(gt_boxes, all_anchors=None, height=100, width=150, stride=8)\n    labels, bbox_targets, bbox_inside_weights = encode(gt_boxes, all_anchors=None, height=50, width=75, stride=16)\n    labels, bbox_targets, bbox_inside_weights = encode(gt_boxes, all_anchors=None, height=25, width=37, stride=32)\n    # anchors, _, _ = anchors_plane(200, 300, stride=4, boarder=0)\n  \n  print('average time: %f' % ((time.time() - t)/10.0))\n", "meta": {"hexsha": "b8735147804d9e4ee48f07ccaacea769c63da173", "size": 8119, "ext": "py", "lang": "Python", "max_stars_repo_path": "libs/layers/anchor.py", "max_stars_repo_name": "dengdan/FastMaskRCNN", "max_stars_repo_head_hexsha": "ebd54a5b61da06c3b2b65acd74383a5b4b1e6730", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/layers/anchor.py", "max_issues_repo_name": "dengdan/FastMaskRCNN", "max_issues_repo_head_hexsha": "ebd54a5b61da06c3b2b65acd74383a5b4b1e6730", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/layers/anchor.py", "max_forks_repo_name": "dengdan/FastMaskRCNN", "max_forks_repo_head_hexsha": "ebd54a5b61da06c3b2b65acd74383a5b4b1e6730", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-08-04T01:30:35.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-04T01:30:35.000Z", "avg_line_length": 36.0844444444, "max_line_length": 115, "alphanum_fraction": 0.6611651681, "include": true, "reason": "import numpy", "num_tokens": 2406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.29098086621490676, "lm_q1q2_score": 0.15343901874241958}}
{"text": "# This script repeatedly estimates the relative binding free energy of a single edge, along with the gradient of the\n# estimate with respect to force field parameters, and adjusts the force field parameters to improve tha accuracy\n# of the free energy prediction.\n\n\nimport argparse\nimport numpy as np\nimport jax\nfrom jax import numpy as jnp\n\nfrom fe.free_energy import construct_lambda_schedule\nfrom fe.utils import convert_uIC50_to_kJ_per_mole\nfrom fe import model\nfrom md import builders\n\nfrom testsystems.relative import hif2a_ligand_pair\n\nfrom ff.handlers.serialize import serialize_handlers\nfrom ff.handlers.nonbonded import AM1CCCHandler, LennardJonesHandler\nfrom parallel.client import CUDAPoolClient\nfrom parallel.utils import get_gpu_count\n\nfrom typing import Union, Optional, Iterable, Any, Tuple, Dict\n\nfrom optimize.step import truncated_step\n\narray = Union[np.array, jnp.array]\nHandler = Union[AM1CCCHandler, LennardJonesHandler] # TODO: do these all inherit from a Handler class already?\n\nif __name__ == \"__main__\":\n\n    parser = argparse.ArgumentParser(\n        description=\"Relative Binding Free Energy Testing\",\n        formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n    )\n\n    parser.add_argument(\n        \"--num_gpus\",\n        type=int,\n        help=\"number of gpus\",\n        default=get_gpu_count()\n    )\n\n    parser.add_argument(\n        \"--num_complex_windows\",\n        type=int,\n        help=\"number of vacuum lambda windows\",\n        required=True\n    )\n\n    parser.add_argument(\n        \"--num_solvent_windows\",\n        type=int,\n        help=\"number of solvent lambda windows\",\n        required=True\n    )\n\n    parser.add_argument(\n        \"--num_equil_steps\",\n        type=int,\n        help=\"number of equilibration steps for each lambda window\",\n        required=True\n    )\n\n    parser.add_argument(\n        \"--num_prod_steps\",\n        type=int,\n        help=\"number of production steps for each lambda window\",\n        required=True\n    )\n\n    cmd_args = parser.parse_args()\n\n    client = CUDAPoolClient(max_workers=cmd_args.num_gpus)\n\n    # fetch mol_a, mol_b, core, forcefield from testsystem\n    mol_a, mol_b, core = hif2a_ligand_pair.mol_a, hif2a_ligand_pair.mol_b, hif2a_ligand_pair.core\n    forcefield = hif2a_ligand_pair.ff\n\n    # compute ddG label from mol_a, mol_b\n    # TODO: add label upon testsystem construction\n    # (ytz): these are *binding* free energies, i.e. values that are less than zero.\n    label_dG_a = convert_uIC50_to_kJ_per_mole(float(mol_a.GetProp(\"IC50[uM](SPA)\")))\n    label_dG_b = convert_uIC50_to_kJ_per_mole(float(mol_b.GetProp(\"IC50[uM](SPA)\")))\n    label_ddG = label_dG_b - label_dG_a  # complex - solvent\n\n    print(\"binding dG_a\", label_dG_a)\n    print(\"binding dG_b\", label_dG_b)\n\n    hif2a_ligand_pair.label = label_ddG\n\n    # construct lambda schedules for complex and solvent\n    complex_schedule = construct_lambda_schedule(cmd_args.num_complex_windows)\n    solvent_schedule = construct_lambda_schedule(cmd_args.num_solvent_windows)\n\n    # build the protein system.\n    complex_system, complex_coords, _, _, complex_box, _ = builders.build_protein_system(\n        'tests/data/hif2a_nowater_min.pdb')\n    complex_box += np.eye(3) * 0.1  # BFGS this later\n\n    # build the water system.\n    solvent_system, solvent_coords, solvent_box, _ = builders.build_water_system(4.0)\n    solvent_box += np.eye(3) * 0.1  # BFGS this later\n\n    binding_model = model.RBFEModel(\n        client,\n        forcefield,\n        complex_system,\n        complex_coords,\n        complex_box,\n        complex_schedule,\n        solvent_system,\n        solvent_coords,\n        solvent_box,\n        solvent_schedule,\n        cmd_args.num_equil_steps,\n        cmd_args.num_prod_steps\n    )\n\n    vg_fn = jax.value_and_grad(binding_model.loss, argnums=0)\n\n    ordered_params = forcefield.get_ordered_params()\n    ordered_handles = forcefield.get_ordered_handles()\n\n    handle_types_being_optimized = [AM1CCCHandler, LennardJonesHandler]\n\n    def flatten(params) -> Tuple[np.array, callable]:\n        \"\"\"Turn params dict into flat array, with an accompanying unflatten function\n\n        TODO: note that the result is going to be in the order given by ordered_handles (filtered by presence in handle_types)\n            rather than in the order they appear in handle_types_being_optimized\n\n        TODO: maybe leave out the reference to handle_types_being optimized altogether\n\n        TODO: does Jax have a pytree-based flatten / unflatten utility?\n        \"\"\"\n\n        theta_list = []\n        _shapes = dict()\n        _handle_types = []\n\n        for param, handle in zip(params, ordered_handles):\n            assert handle.params.shape == param.shape\n            key = type(handle)\n\n            if key in handle_types_being_optimized:\n                theta_list.append(param.flatten())\n                _shapes[key] = param.shape\n                _handle_types.append(key)\n\n        theta = np.hstack(theta_list)\n\n        def unflatten(theta: array) -> Dict[Handler, array]:\n            params = dict()\n            i = 0\n            for key in _handle_types:\n                shape = _shapes[key]\n                num_params = int(np.prod(shape))\n                params[key] = np.array(theta[i: i + num_params]).reshape(shape)\n                i += num_params\n            return params\n\n        return theta, unflatten\n\n\n    # in each optimization step, don't step so far that you think you're jumping to\n    #   loss_next = relative_improvement_bound * loss_current\n    relative_improvement_bound = 0.95\n\n    flat_theta_traj = []\n    flat_grad_traj = []\n    loss_traj = []\n\n    for epoch in range(1000):\n        epoch_params = serialize_handlers(ordered_handles)\n        (loss, aux), loss_grad = vg_fn(ordered_params, mol_a, mol_b, core, label_ddG)\n\n        print(\"epoch\", epoch, \"loss\", loss)\n\n        # note: unflatten_grad and unflatten_theta have identical definitions for now\n        flat_loss_grad, unflatten_grad = flatten(loss_grad)\n        flat_theta, unflatten_theta = flatten(ordered_params)\n\n        step_lower_bound = loss * relative_improvement_bound\n        theta_increment = truncated_step(flat_theta, loss, flat_loss_grad, step_lower_bound=step_lower_bound)\n        param_increments= unflatten_theta(theta_increment)\n\n        # for any parameter handler types being updated, update in place\n        for handle in ordered_handles:\n            handle_type = type(handle)\n            if handle_type in param_increments:\n                print(f'updating {handle_type.__name__}')\n\n                print(f'\\tbefore update: {handle.params}')\n                handle.params += param_increments[handle_type] # TODO: careful -- this must be a \"+=\" or \"-=\" not an \"=\"!\n                print(f'\\tafter update:  {handle.params}')\n\n                # useful for debugging to dump out the grads\n                # for smirks, dp in zip(handle.smirks, loss_grad):\n                    # if np.any(dp) > 0:\n                        # print(smirks, dp)\n\n        # checkpoint results to npz (overwrite\n        flat_theta_traj.append(np.array(flat_theta))\n        flat_grad_traj.append(flat_loss_grad)\n        loss_traj.append(loss)\n\n        path_to_npz = 'results_checkpoint.npz'\n        print(f'saving theta, grad, loss trajs to {path_to_npz}')\n        np.savez(\n            path_to_npz,\n            theta_traj=np.array(flat_theta_traj),\n            grad_traj=np.array(flat_grad_traj),\n            loss_traj=np.array(loss_traj)\n        )\n\n        # write ff parameters after each epoch\n        path_to_ff_checkpoint = f\"checkpoint_{epoch}.py\"\n        print(f'saving force field parameter checkpoint to {path_to_ff_checkpoint}')\n        with open(path_to_ff_checkpoint, 'w') as fh:\n            fh.write(epoch_params)\n", "meta": {"hexsha": "92b4eb2885bc6a76753f741455ae36c9ee50ef6e", "size": 7753, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/rbfe_single.py", "max_stars_repo_name": "fehomi/timemachine", "max_stars_repo_head_hexsha": "594b10c03a6688c008eb4d35e612dbd98f5eede4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/rbfe_single.py", "max_issues_repo_name": "fehomi/timemachine", "max_issues_repo_head_hexsha": "594b10c03a6688c008eb4d35e612dbd98f5eede4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/rbfe_single.py", "max_forks_repo_name": "fehomi/timemachine", "max_forks_repo_head_hexsha": "594b10c03a6688c008eb4d35e612dbd98f5eede4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9234234234, "max_line_length": 126, "alphanum_fraction": 0.671868954, "include": true, "reason": "import numpy,import jax,from jax", "num_tokens": 1779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.15338169128305557}}
{"text": "from __future__ import division\nfrom build.el_propagator import el_run\nfrom mqc.mqc import MQC\nfrom misc import au_to_K, call_name, typewriter\nimport os, shutil, textwrap\nimport numpy as np\nimport pickle\n\nclass Eh(MQC):\n    \"\"\" Class for Ehrenfest dynamics\n\n        :param object molecule: Molecule object\n        :param object thermostat: Thermostat object\n        :param integer istate: Initial state\n        :param double dt: Time interval\n        :param integer nsteps: Total step of nuclear propation\n        :param integer nesteps: Total step of electronic propagation\n        :param string elec_object: Electronic equation of motions\n        :param string propagator: Electronic propagator\n        :param boolean l_print_dm: Logical to print BO population and coherence\n        :param boolean l_adj_nac: Logical to adjust nonadiabatic coupling\n        :param init_coef: Initial BO coefficient\n        :type init_coef: Double, list or complex, list\n        :param string unit_dt: Unit of time step (fs = femtosecond, au = atomic unit)\n        :param integer out_freq: Frequency of printing output\n        :param integer verbosity: Verbosity of output\n    \"\"\"\n    def __init__(self, molecule, thermostat=None, istate=0, dt=0.5, nsteps=1000, nesteps=20, \\\n        elec_object=\"density\", propagator=\"rk4\", l_print_dm=True, l_adj_nac=True, \\\n        init_coef=None, unit_dt=\"fs\", out_freq=1, verbosity=0):\n        # Initialize input values\n        super().__init__(molecule, thermostat, istate, dt, nsteps, nesteps, \\\n            elec_object, propagator, l_print_dm, l_adj_nac, init_coef, unit_dt, out_freq, verbosity)\n\n        # Debug variables\n        self.dotpopnac = np.zeros(self.mol.nst)\n\n    def run(self, qm, mm=None, output_dir=\"./\", l_save_qm_log=False, l_save_mm_log=False, l_save_scr=True, restart=None):\n        \"\"\" Run MQC dynamics according to Ehrenfest dynamics\n\n            :param object qm: QM object containing on-the-fly calculation infomation\n            :param object mm: MM object containing MM calculation infomation\n            :param string output_dir: Name of directory where outputs to be saved.\n            :param boolean l_save_qm_log: Logical for saving QM calculation log\n            :param boolean l_save_mm_log: Logical for saving MM calculation log\n            :param boolean l_save_scr: Logical for saving scratch directory\n            :param string restart: Option for controlling dynamics restarting\n        \"\"\"\n        # Initialize PyUNIxMD\n        base_dir, unixmd_dir, qm_log_dir, mm_log_dir =\\\n             self.run_init(qm, mm, output_dir, l_save_qm_log, l_save_mm_log, l_save_scr, restart)\n        bo_list = [ist for ist in range(self.mol.nst)]\n        qm.calc_coupling = True\n        self.print_init(qm, mm, restart)\n\n        if (restart == None):\n            # Calculate initial input geometry at t = 0.0 s\n            self.istep = -1\n            self.mol.reset_bo(qm.calc_coupling)\n            qm.get_data(self.mol, base_dir, bo_list, self.dt, self.istep, calc_force_only=False)\n            if (self.mol.l_qmmm and mm != None):\n                mm.get_data(self.mol, base_dir, bo_list, self.istep, calc_force_only=False)\n            self.mol.get_nacme()\n\n            self.update_energy()\n\n            self.write_md_output(unixmd_dir, self.istep)\n            self.print_step(self.istep)\n\n        elif (restart == \"write\"):\n            # Reset initial time step to t = 0.0 s\n            self.istep = -1\n            self.write_md_output(unixmd_dir, self.istep)\n            self.print_step(self.istep)\n\n        elif (restart == \"append\"):\n            # Set initial time step to last successful step of previous dynamics\n            self.istep = self.fstep\n\n        self.istep += 1\n\n        # Main MD loop\n        for istep in range(self.istep, self.nsteps):\n            \n            self.calculate_force()\n            self.cl_update_position()\n\n            self.mol.backup_bo()\n            self.mol.reset_bo(qm.calc_coupling)\n            qm.get_data(self.mol, base_dir, bo_list, self.dt, istep, calc_force_only=False)\n            if (self.mol.l_qmmm and mm != None):\n                mm.get_data(self.mol, base_dir, bo_list, istep, calc_force_only=False)\n\n            if (self.l_adj_nac):\n                self.mol.adjust_nac()\n\n            self.calculate_force()\n            self.cl_update_velocity()\n\n            self.mol.get_nacme()\n\n            el_run(self)\n\n            if (self.thermo != None):\n                self.thermo.run(self)\n\n            self.update_energy()\n\n            if ((istep + 1) % self.out_freq == 0):\n                self.write_md_output(unixmd_dir, istep)\n                self.print_step(istep)\n            if (istep == self.nsteps - 1):\n                self.write_final_xyz(unixmd_dir, istep)\n\n            self.fstep = istep\n            restart_file = os.path.join(base_dir, \"RESTART.bin\")\n            with open(restart_file, 'wb') as f:\n                pickle.dump({'qm':qm, 'md':self}, f)\n\n        # Delete scratch directory\n        if (not l_save_scr):\n            tmp_dir = os.path.join(unixmd_dir, \"scr_qm\")\n            if (os.path.exists(tmp_dir)):\n                shutil.rmtree(tmp_dir)\n\n            if (self.mol.l_qmmm and mm != None):\n                tmp_dir = os.path.join(unixmd_dir, \"scr_mm\")\n                if (os.path.exists(tmp_dir)):\n                    shutil.rmtree(tmp_dir)\n\n    def calculate_force(self):\n        \"\"\" Calculate the Ehrenfest force\n        \"\"\"\n        self.rforce = np.zeros((self.mol.nat, self.mol.ndim))\n\n        for ist, istate in enumerate(self.mol.states):\n            self.rforce += istate.force * self.mol.rho.real[ist, ist]\n\n        for ist in range(self.mol.nst):\n            for jst in range(ist + 1, self.mol.nst):\n                self.rforce += 2. * self.mol.nac[ist, jst] * self.mol.rho.real[ist, jst] \\\n                    * (self.mol.states[ist].energy - self.mol.states[jst].energy)\n\n    def update_energy(self):\n        \"\"\" Routine to update the energy of molecules in Ehrenfest dynamics\n        \"\"\"\n        # Update kinetic energy\n        self.mol.update_kinetic()\n        self.mol.epot = 0.\n        for ist, istate in enumerate(self.mol.states):\n            self.mol.epot += self.mol.rho.real[ist, ist] * self.mol.states[ist].energy\n        self.mol.etot = self.mol.epot + self.mol.ekin\n\n    def write_md_output(self, unixmd_dir, istep):\n        \"\"\" Write output files\n\n            :param string unixmd_dir: PyUNIxMD directory\n            :param integer istep: Current MD step\n        \"\"\"\n        # Write the common part\n        super().write_md_output(unixmd_dir, istep)\n\n        # Write time-derivative BO population\n        self.write_dotpop(unixmd_dir, istep)\n\n    def write_dotpop(self, unixmd_dir, istep):\n        \"\"\" Write time-derivative BO population\n\n            :param string unixmd_dir: PyUNIxMD directory\n            :param integer istep: Current MD step\n        \"\"\"\n        # Write NAC term in DOTPOPNAC\n        if (self.verbosity >= 1):\n            tmp = f'{istep + 1:9d}' + \"\".join([f'{pop:15.8f}' for pop in self.dotpopnac])\n            typewriter(tmp, unixmd_dir, \"DOTPOPNAC\", \"a\")\n\n    def print_init(self, qm, mm, restart):\n        \"\"\" Routine to print the initial information of dynamics\n\n            :param object qm: QM object containing on-the-fly calculation infomation\n            :param object mm: MM object containing MM calculation infomation\n            :param string restart: Option for controlling dynamics restarting\n        \"\"\"\n        # Print initial information about molecule, qm, mm and thermostat\n        super().print_init(qm, mm, restart)\n\n        # Print dynamics information for start line\n        dynamics_step_info = textwrap.dedent(f\"\"\"\\\n\n        {\"-\" * 118}\n        {\"Start Dynamics\":>65s}\n        {\"-\" * 118}\n        \"\"\")\n\n        # Print INIT for each step\n        INIT = f\" #INFO{'STEP':>8s}{'Kinetic(H)':>15s}{'Potential(H)':>15s}{'Total(H)':>13s}{'Temperature(K)':>17s}{'norm':>8s}\"\n        dynamics_step_info += INIT\n\n        print (dynamics_step_info, flush=True)\n\n    def print_step(self, istep):\n        \"\"\" Routine to print each steps infomation about dynamics\n\n            :param integer istep: Current MD step\n        \"\"\"\n        ctemp = self.mol.ekin * 2. / float(self.mol.ndof) * au_to_K\n        norm = 0.\n        for ist in range(self.mol.nst):\n            norm += self.mol.rho.real[ist, ist]\n\n        # Print INFO for each step\n        INFO = f\" INFO{istep + 1:>9d} \"\n        INFO += f\"{self.mol.ekin:14.8f}{self.mol.epot:15.8f}{self.mol.etot:15.8f}\"\n        INFO += f\"{ctemp:13.6f}\"\n        INFO += f\"{norm:11.5f}\"\n        print (INFO, flush=True)\n\n\n", "meta": {"hexsha": "ca0d9ef47c997a71c98c0f5d5b617699f221ac27", "size": 8637, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/mqc/eh.py", "max_stars_repo_name": "hkimaf/unixmd", "max_stars_repo_head_hexsha": "616634c720d0589fd600e3268afab9da957e18bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-04-18T08:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T03:29:54.000Z", "max_issues_repo_path": "src/mqc/eh.py", "max_issues_repo_name": "hkimaf/unixmd", "max_issues_repo_head_hexsha": "616634c720d0589fd600e3268afab9da957e18bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2021-04-14T08:43:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T10:26:42.000Z", "max_forks_repo_path": "src/mqc/eh.py", "max_forks_repo_name": "hkimaf/unixmd", "max_forks_repo_head_hexsha": "616634c720d0589fd600e3268afab9da957e18bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2021-04-14T05:59:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T03:05:23.000Z", "avg_line_length": 39.4383561644, "max_line_length": 128, "alphanum_fraction": 0.6075026051, "include": true, "reason": "import numpy", "num_tokens": 2200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.2974699426047947, "lm_q1q2_score": 0.15338142673601451}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n\nBuild AKARI/IRC spectral cube\nInter-calibrate AKARI/IRC spectra with Spitzer/IRAC1\n\n\"\"\"\n\n# import logging, sys\n# logging.disable(sys.maxsize)\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=RuntimeWarning)\nwarnings.filterwarnings(\"ignore\", message=\"Skipping SYSTEM_VARIABLE record\")\n\nfrom tqdm import tqdm, trange\n\nimport os\nimport math\nimport numpy as np\nfrom scipy.optimize import curve_fit\n## rapyuta\nfrom rapyuta.inout import fclean, fitsext, read_fits, write_fits, read_hdf5\nfrom rapyuta.imaging import ( iconvolve, iswarp, cupid, iuncert,\n                              icrop, igroupixel, ismooth, \n                              imontage, improve, Jy_per_pix_to_MJy_per_sr )\nfrom rapyuta.astrom import fixwcs\nfrom rapyuta.arrays import closest, pix2sup, sup2pix\nfrom rapyuta.calib import intercalib\nfrom rapyuta.maths import f_lin, f_lin0, f_lin1\nfrom rapyuta.plots import pplot\n\n\n##----------------------------------------------------------\n\n##                     Preliminaries\n\n##----------------------------------------------------------\n\n## Local\nfrom buildinfo import ( src, Nmc, verbose, coadd_tool, colors, markers,\n                        path_irc, path_build, parobs, # build\n                        filog, fits_irc, out_irc, path_out,\n                        path_phot, path_ker, path_cal, # calib\n                        path_idl, csv_ker, path_tmp, path_fig\n)\n\n## Banner\nprint('\\n============================================================\\n')\n\nprint('        MIRAGE - AKARI/IRC cube builder - '+src)\n\nprint('\\n============================================================\\n')\n\nNobs = len(parobs)\n\n# Nmc = 2\n\n# exit()\n\n##----------------------------------------------------------\n\n##                      Build slits\n\n##----------------------------------------------------------\ndo_build = input(\"(Re)build IRC slits (y/n)? \")\nif do_build=='y':\n\n    for i in trange(Nobs, #leave=False,\n                    desc='<cupid> IRC slit building'):\n        for j in trange(Nmc+1, leave=False,\n                        desc=' - IRC slit unc [MC]'):\n            cup = cupid(path_irc, obsid=parobs[i][1], slit=parobs[i][4],\n                        spec=parobs[i][2], imref=parobs[i][3])\n            if j==0:\n                cup.spec_build(fits_irc[i]+'_'+str(j), tmpdir=path_build,\n                               filRAW=fits_irc[i], fiLOG=filog+parobs[i][0],\n                               Nx=parobs[i][7], Ny=parobs[i][5], Nsub=parobs[i][6],\n                               pixscale=1, wmin=2.55, wmax=4.25, supix=True)\n                if i==0:\n                    wave0 = cup.wave()\n            else:\n                cup.spec_build(fits_irc[i]+'_'+str(j), tmpdir=path_build,\n                               dist='splitnorm', sig_pt=3, fill_pt='med',\n                               Nx=parobs[i][7], Ny=parobs[i][5], Nsub=parobs[i][6],\n                               pixscale=1, wmin=2.55, wmax=4.25, supix=True)\n            ## Interpolate wavelength grid of IRC slits\n            ##------------------------------------------\n            ## (A,B,C,D,G,H,I,J,L,N) (E,F,K) (M) have slightly different wgrid...\n            ismooth(fits_irc[i]+'_'+str(j), wgrid=wave0, filOUT=fits_irc[i]+'_'+str(j))\n            \n        ## MC unc\n        if Nmc>1:\n            mcimage = []\n            for j in range(Nmc):\n                ds = read_fits(fits_irc[i]+'_'+str(j+1))\n                mcimage.append(ds.data)\n            mcimage = np.array(mcimage)\n            unc = np.nanstd(mcimage, axis=0)\n            write_fits(out_irc[i]+'_unc', ds.header, unc, ds.wave)\n\n\n##----------------------------------------------------------\n\n##                 Coadd slits (for footprint)\n\n##----------------------------------------------------------\nirc_coadd = input(\"Coadd IRC slits (y/n)? \")\nif irc_coadd=='y':\n\n    ## Coadding\n    ##----------\n\n    ## IRC grid\n    refheader = fixwcs(fits_irc[0]+fitsext).header\n    swp = iswarp(fits_irc, refheader=refheader, \n                 tmpdir=path_build, verbose=verbose)\n    footprint_irc = swp.refheader\n\n    slice_irc = []\n    for f in fits_irc:\n        ds = read_fits(f)\n        ds.data[0] = 1\n        write_fits(f+'_slice', ds.header, ds.data[0])\n        slice_irc.append(f+'_slice')\n\n    if coadd_tool=='swarp':\n        \n        ## <iswarp> coadding\n        ##===================\n        swp = iswarp(refheader=footprint_irc,\n                     tmpdir=path_build, verbose=verbose)\n        swp.combine(slice_irc,# combtype='wgt_avg',\n                    keepedge=True, #cropedge=True,\n                    filOUT=path_out+src+'_footprint')\n\n    elif coadd_tool=='reproject':\n\n        ## <imontage> coadding\n        ##=====================\n        mtg = imontage('exact', tmpdir=path_tmp, verbose=verbose)\n        mtg.coadd(slice_irc, refheader=footprint_irc,\n                  filOUT=path_out+src+'_footprint')\n\n    ## Crop NaN edge\n    edge = 2 # leave an edge of some pixels\n    data = read_fits(path_out+src+'_footprint').data\n    Ny, Nx = data.shape\n    xlist = []\n    for x in range(Nx):\n        if not np.isnan(data[:,x]).all():\n            xlist.append(x)\n    ylist = []\n    for y in range(Ny):\n        if not np.isnan(data[y,:]).all():\n            ylist.append(y)\n    xmin = min(xlist) - edge\n    if xmin<0:\n        xmin = 0\n    xmax = max(xlist)+1 + edge\n    if xmax>Nx:\n        xmax = Nx\n    ymin = min(ylist) - edge\n    if ymin<0:\n        ymin = 0\n    ymax = max(ylist)+1 + edge\n    if ymax>Ny:\n        ymax = Ny\n    dx = xmax-xmin\n    dy = ymax-ymin\n    x0 = xmin+dx/2\n    y0 = ymin+dy/2\n    \n    icrop(path_out+src+'_footprint', filOUT=path_out+src+'_footprint',\n          sizpix=(dx,dy), cenpix=(x0,y0), verbose=verbose)\n    \n## Header of th atlas IRC map\nheader_atlas = fixwcs(path_out+src+'_footprint'+fitsext).header\n\n\n##----------------------------------------------------------\n\n##                   Inter-calibration\n\n##----------------------------------------------------------\npre_calib1 = input(\"Run inter-calibration prepipeline (DustPedia IRAC1) (y/n)? \")\npre_calib2 = input(\"Run inter-calibration prepipeline (SINGS IRAC1) (y/n)? \")\nsynt_phot = input(\"Run inter-calibration prepipeline (IRC synthetic photometry) (y/n)? \")\n\nif not os.path.exists(path_tmp+'calib/'):\n    os.makedirs(path_tmp+'calib/')\n    \n## Prepare photometry\n##--------------------\nphot = 'IRAC1'\nphot_ker = path_ker+'Kernel_HiRes_IRAC_3.6_to_Gauss_06.0'\n\nraw_phot1 = path_phot+src+'_'+phot+'_DP'\nfits_phot1 = path_cal+src+'_'+phot+'_DP'\ntmp_phot1 = path_tmp+'calib/'+src+'_'+phot+'_DP'\n\nraw_phot2 = path_phot+src+'_'+phot+'_SINGS'\nwgt_phot2 = path_phot+src+'_'+phot+'_SINGS_wt'\nfits_phot2 = path_cal+src+'_'+phot+'_SINGS'\ntmp_phot2 = path_tmp+'calib/'+src+'_'+phot+'_SINGS'\n\nfits_spec = path_cal+src+'_'+phot+'_IRC'\ntmp_spec = path_tmp+'calib/'+src+'_'+phot+'_IRC'\n\n## DustPedia (phot1)\n##===================\nif pre_calib1=='y':\n    \n    ## Convert phot unit (Jy/pix -> MJy/sr)\n    ## This step should be before reprojection (pixscale may change)\n    Jy_per_pix_to_MJy_per_sr(raw_phot1, filOUT=tmp_phot1)\n\n    ## DustPedia IRAC1 of M82 has no uncertainty map\n    ## Create homogeneous uncertainty map\n    bg = read_fits(tmp_phot1).data[1713:1753,3110:3150]*10\n    iuncert(tmp_phot1, filOUT=tmp_phot1+'_unc', BG_image=bg)\n\n    ## Reproject phot (atlas)\n    if coadd_tool=='swarp':\n        swp = iswarp(refheader=header_atlas, tmpdir=path_tmp)\n        swp.combine_mc(tmp_phot1, keepedge=True, #cropedge=True,\n                       dist='norm', Nmc=Nmc, filOUT=tmp_phot1+'_MC')\n    elif coadd_tool=='reproject':\n        mtg = imontage('exact', tmpdir=path_tmp)\n        mtg.reproject_mc(tmp_phot1, refheader=header_atlas,\n                         dist='norm', Nmc=Nmc, filOUT=tmp_phot1+'_MC')\n    \n    for i in trange(Nobs, #leave=False,\n                    desc=phot+' (DustPedia) processing'):\n        xscale, yscale = read_hdf5(filog+parobs[i][0], 'Super pixel size')\n        refheader = fixwcs(fits_irc[i]+'_0'+fitsext).header\n\n        for j in trange(Nmc+1, leave=False,\n                        desc=' - '+parobs[i][0]+' [MC]'):\n            if i==0:\n                ## Convolve phot\n                if j==0:\n                    conv = iconvolve(tmp_phot1+'_MC',\n                                     kfile=phot_ker, klist=csv_ker,\n                                     filOUT=tmp_phot1+'_MC')\n                else:\n                    conv = iconvolve(tmp_phot1+'_MC_'+str(j),\n                                     kfile=phot_ker, klist=csv_ker,\n                                     # filUNC=tmp_phot1+'_unc', dist='norm',\n                                     filOUT=tmp_phot1+'_MC_'+str(j))\n                conv.do_conv(idldir=path_idl)\n\n            ## Reproject phot (slit)\n            if coadd_tool=='swarp':\n                swp = iswarp(refheader=refheader, tmpdir=path_tmp)\n                if j==0:\n                    swp.combine(tmp_phot1+'_MC',\n                                filOUT=fits_phot1+'_'+parobs[i][0])\n                else:\n                    swp.combine(tmp_phot1+'_MC_'+str(j),\n                                filOUT=tmp_phot1+'_'+parobs[i][0]+'_'+str(j))\n            elif coadd_tool=='reproject':\n                mtg = imontage('exact', tmpdir=path_tmp)\n                if j==0:\n                    mtg.reproject(tmp_phot1+'_MC', refheader=refheader,\n                                  filOUT=fits_phot1+'_'+parobs[i][0])\n                else:\n                    mtg.reproject(tmp_phot1+'_MC_'+str(j), refheader=refheader,\n                                  filOUT=tmp_phot1+'_'+parobs[i][0]+'_'+str(j))\n            \n            ## Calculate unc\n            if j==0:\n                igroupixel(fits_phot1+'_'+parobs[i][0],\n                           xscale=xscale, yscale=yscale,\n                           filOUT=fits_phot1+'_'+parobs[i][0])\n            else:\n                igroupixel(tmp_phot1+'_'+parobs[i][0]+'_'+str(j),\n                           xscale=xscale, yscale=yscale,\n                           filOUT=tmp_phot1+'_'+parobs[i][0]+'_'+str(j))\n        if Nmc>1:\n            mcimage = []\n            for j in range(Nmc):\n                ds = read_fits(tmp_phot1+'_'+parobs[i][0]+'_'+str(j+1))\n                mcimage.append(ds.data)\n            mcimage = np.array(mcimage)\n            unc = np.nanstd(mcimage, axis=0)\n            write_fits(fits_phot1+'_'+parobs[i][0]+'_unc', ds.header, unc)\n\n## SINGS (phot2)\n##===============\nif pre_calib2=='y':\n    \n    ## Create uncertainty via weight map (suppose uniform contribution)\n    \n    ## (Sect. 3.2) The weight maps contain the information on the number of frames \n    ## that were used to create the science mosaics at each pixel (value= # frames x10); \n    ## the pixel size of the weight maps is the same as the science mosaics.\n    ## -- SINGS v5 release doc\n    ## https://irsa.ipac.caltech.edu/data/SPITZER/SINGS/doc/sings_fifth_delivery_v2.pdf\n    \n    ## Only need to run ONCE for each photometry (comment after using)\n    # gen_unc2 = input(\"Create SINGS IRAC1 uncertainty map (y/n)? \")\n    # if gen_unc2=='y':\n    #     ds_wgt = read_fits(wgt_phot2)\n    #     bg = read_fits(raw_phot2).data[694:734,56:96]\n    #     bg_wgt = ds_wgt.data[694:734,56:96]\n    #     wfac = .1\n    #     iuncert(raw_phot2, filOUT=raw_phot2+'_unc',\n    #             filWGT=wgt_phot2, wfac=wfac,\n    #             BG_image=bg, BG_weight=bg_wgt)\n\n    ## Reproject phot (atlas)\n    if coadd_tool=='swarp':\n        swp = iswarp(refheader=header_atlas, tmpdir=path_tmp)\n        swp.combine_mc(raw_phot2, keepedge=True, #cropedge=True,\n                       dist='norm', Nmc=Nmc, filOUT=tmp_phot2+'_MC')\n    elif coadd_tool=='reproject':\n        mtg = imontage('exact', tmpdir=path_tmp)\n        mtg.reproject_mc(raw_phot2, refheader=header_atlas,\n                         dist='norm', Nmc=Nmc, filOUT=tmp_phot2+'_MC')\n\n    for i in trange(Nobs, #leave=False,\n                    desc=phot+' (SINGS) processing'):\n        xscale, yscale = read_hdf5(filog+parobs[i][0], 'Super pixel size')\n        refheader = fixwcs(fits_irc[i]+'_0'+fitsext).header\n\n        for j in trange(Nmc+1, leave=False,\n                        desc=' - '+parobs[i][0]+' [MC]'):\n            if i==0:\n                ## Convolve phot\n                if j==0:\n                    conv = iconvolve(tmp_phot2+'_MC',\n                                     kfile=phot_ker, klist=csv_ker,\n                                     filOUT=tmp_phot2+'_MC')\n                else:\n                    conv = iconvolve(tmp_phot2+'_MC_'+str(j),\n                                     kfile=phot_ker, klist=csv_ker,\n                                     # filUNC=tmp_phot2+'_unc', dist='norm',\n                                     filOUT=tmp_phot2+'_MC_'+str(j))\n                conv.do_conv(idldir=path_idl)\n\n            ## Reproject phot (slit)\n            if coadd_tool=='swarp':\n                swp = iswarp(refheader=refheader, tmpdir=path_tmp)\n                if j==0:\n                    swp.combine(tmp_phot2+'_MC',\n                                filOUT=fits_phot2+'_'+parobs[i][0])\n                else:\n                    swp.combine(tmp_phot2+'_MC_'+str(j),\n                                filOUT=tmp_phot2+'_'+parobs[i][0]+'_'+str(j))\n            elif coadd_tool=='reproject':\n                mtg = imontage('exact', tmpdir=path_tmp)\n                if j==0:\n                    mtg.reproject(tmp_phot2+'_MC', refheader=refheader,\n                                  filOUT=fits_phot2+'_'+parobs[i][0])\n                else:\n                    mtg.reproject(tmp_phot2+'_MC_'+str(j), refheader=refheader,\n                                  filOUT=tmp_phot2+'_'+parobs[i][0]+'_'+str(j))\n            \n            ## Calculate unc\n            if j==0:\n                igroupixel(fits_phot2+'_'+parobs[i][0],\n                           xscale=xscale, yscale=yscale,\n                           filOUT=fits_phot2+'_'+parobs[i][0])\n            else:\n                igroupixel(tmp_phot2+'_'+parobs[i][0]+'_'+str(j),\n                           xscale=xscale, yscale=yscale,\n                           filOUT=tmp_phot2+'_'+parobs[i][0]+'_'+str(j))\n        if Nmc>1:\n            mcimage = []\n            for j in range(Nmc):\n                ds = read_fits(tmp_phot2+'_'+parobs[i][0]+'_'+str(j+1))\n                mcimage.append(ds.data)\n            mcimage = np.array(mcimage)\n            unc = np.nanstd(mcimage, axis=0)\n            write_fits(fits_phot2+'_'+parobs[i][0]+'_unc', ds.header, unc)\n\n## Synthetic photometry (spec)\n##=============================\nif (synt_phot=='y' and do_build=='y'):\n    ## fits_irc[i] can be changed by inter-calib,\n    ## One need to rebuild before synthetic photometry\n    for i in trange(Nobs, #leave=False,\n                    desc=phot+' (IRC synt phot) slits'):\n        xscale, yscale = read_hdf5(filog+parobs[i][0], 'Super pixel size')\n        for j in trange(Nmc+1, leave=False,\n                        desc=' - '+parobs[i][0]+': IRC sythetic photometry [MC]'):\n            ic = intercalib(fits_irc[i]+'_'+str(j))\n            sp = ic.synthetic_photometry(phot, xscale=xscale, yscale=yscale)\n            if j==0:\n                write_fits(fits_spec+'_'+parobs[i][0], ic.hdr, sp.Fnu_filt)\n            else:\n                write_fits(tmp_spec+'_'+parobs[i][0]+'_'+str(j), ic.hdr, sp.Fnu_filt)\n        if Nmc>1:\n            mcimage = []\n            for j in range(Nmc):\n                ds = read_fits(tmp_spec+'_'+parobs[i][0]+'_'+str(j+1))\n                mcimage.append(ds.data)\n            mcimage = np.array(mcimage)\n            unc = np.nanstd(mcimage, axis=0)\n            write_fits(fits_spec+'_'+parobs[i][0]+'_unc', ds.header, unc)\n\n##-----------------\n## Fit correlation\n##-----------------\n## Data dictionary\n## e.g. [{'A0': a0, 'A1': a1, ...}, {'B0': b0, 'B1': b1, ...}, ...]\ndict_phot1 = []\ndict_phot1_unc = []\ndict_phot2 = []\ndict_phot2_unc = []\ndict_spec = []\ndict_spec_unc = []\n## Data 1D array\n## e.g. [array([a1, a2, ...]), array([b1, b2, ...]), ...]\npix_phot1 = []\npix_phot1_unc = []\npix_phot2 = []\npix_phot2_unc = []\npix_spec = []\npix_spec_unc = []\n\n# xgrid = np.arange(0,1e3,1)\nxgrid = np.logspace(-2,3,1000)\n\nfor i in range(Nobs):\n    # Nx = read_hdf5(filog+parobs[i][0], 'Slit width')\n    Ny = read_hdf5(filog+parobs[i][0], 'Slit length')[0]\n    xscale, yscale = read_hdf5(filog+parobs[i][0], 'Super pixel size')\n    # Nxs = math.ceil(Nx/xscale)\n    Nys = math.ceil(Ny/yscale)\n\n    ## Init dict\n    data1 = {}\n    unc1 = {}\n    data2 = {}\n    unc2 = {}\n    data3 = {}\n    unc3 = {}\n    for ys in range(Nys):\n        subname = parobs[i][0][0]+str(ys+1)\n        yarr = sup2pix(ys, yscale, Npix=Ny, origin=0)\n        ## Phot1\n        ds = read_fits(fits_phot1+'_'+parobs[i][0], fits_phot1+'_'+parobs[i][0]+'_unc')\n        data1[subname] = ds.data[yarr[0],0]\n        unc1[subname] = ds.unc[yarr[0],0]\n        ## Phot2\n        ds = read_fits(fits_phot2+'_'+parobs[i][0], fits_phot2+'_'+parobs[i][0]+'_unc')\n        data2[subname] = ds.data[yarr[0],0]\n        unc2[subname] = ds.unc[yarr[0],0]\n        ## spec\n        ds = read_fits(fits_spec+'_'+parobs[i][0], fits_spec+'_'+parobs[i][0]+'_unc')\n        data3[subname] = ds.data[yarr[0],0]\n        unc3[subname] = ds.unc[yarr[0],0]\n    dict_phot1.append(data1)\n    dict_phot1_unc.append(unc1)\n    dict_phot2.append(data2)\n    dict_phot2_unc.append(unc2)\n    dict_spec.append(data3)\n    dict_spec_unc.append(unc3)\n\n    ## Dictionary to 1D array\n    pix_phot1.append(np.array(list(dict_phot1[i].values())))\n    pix_phot1_unc.append(np.array(list(dict_phot1_unc[i].values())))\n    pix_phot2.append(np.array(list(dict_phot2[i].values())))\n    pix_phot2_unc.append(np.array(list(dict_phot2_unc[i].values())))\n    pix_spec.append(np.array(list(dict_spec[i].values())))\n    pix_spec_unc.append(np.array(list(dict_spec_unc[i].values())))\n\n    ## Mask NaNs and negtive values\n    mask_nan = ~np.logical_or( np.isnan(pix_spec[i]), np.isnan(pix_phot2[i]) )\n    mask_neg = np.logical_and( pix_spec[i]>0, pix_phot2[i]>0 )\n    mask = np.logical_and( mask_nan, mask_neg )\n\n    ## Add calibration error\n    pix_phot1_unc[i] += pix_phot1[i] * .03\n    pix_phot2_unc[i] += pix_phot2[i] * .03\n    pix_spec_unc[i] += pix_spec[i] * .05\n    \n    ## S/N ratio\n    # print(parobs[i][0]+' S/N (IRC) = \\n', pix_spec[i][mask]/pix_spec_unc[i][mask])\n    # print(parobs[i][0]+' S/N (SINGS) = \\n', pix_phot2[i][mask]/pix_phot2_unc[i][mask])\n\n    if mask.any():\n        ## DP - SINGS plot\n        if i==0:\n            p0 = pplot(fmt='s', ec='grey', elw=1,# clib=colors,\n                       xlog=1, ylog=1, nonposx='clip', nonposy='clip',\n                       # xlim=(1e-2,1e3), ylim=(1e-2,1e3),\n                       xlabel='DustPedia (MJy/sr)', ylabel='SINGS (MJy/sr)',\n                       title=src+' '+phot+' calibration',\n                       figsize=(10,8), right=.8, left=.15, bottom=.15,\n                       legend='upper left', anchor=(1,1),\n                       titlesize=20, labelsize=20, ticksize=20, legendsize=20)\n        p0.add_plot(pix_phot1[i][mask], pix_phot2[i][mask],\n                    yerr=pix_phot2_unc[i][mask], xerr=pix_phot1_unc[i][mask],\n                    fmt='s', ec='grey', c=colors[i+1],\n                    marker=markers[i], markersize=10, capsize=2,\n                    label=parobs[i][0])\n        p0.add_plot(pix_phot1[i][mask], pix_phot2[i][mask],\n                    yerr=pix_phot2_unc[i][mask], xerr=pix_phot1_unc[i][mask],\n                    fmt='o', ec='grey', c=colors[i+1], zorder=100,\n                    marker=markers[i], markersize=.1, capsize=2)\n        p0.save(path_cal+'DP-SINGS_'+phot)\n    \n        if (synt_phot=='y' or pre_calib2=='y'):\n            ## IRC - SINGS plot\n            if i==0:\n                p = pplot(fmt='s', ec='grey', elw=1,# clib=colors,\n                          xlog=1, ylog=1, nonposx='clip', nonposy='clip',\n                          # xlim=(1e-2,1e3), ylim=(1e-2,1e3),\n                          # xlabel='IRC (MJy/sr)', ylabel='SINGS (MJy/sr)',\n                          # title=src+' IRC-'+phot+' inter-calibration',\n                          xlabel='IRC (MJy/sr)', ylabel=r'$\\rm IRAC_{3.6\\mu m}\\ (MJy/sr)$',\n                          title=None,\n                          figsize=(11,8), right=.78, left=.12, bottom=.1, top=.95,\n                          legend='upper left', anchor=(1,1),\n                          titlesize=20, labelsize=20, ticksize=20, legendsize=20)\n                                \n            p.add_plot(pix_spec[i][mask], pix_phot2[i][mask],\n                       yerr=pix_phot2_unc[i][mask], xerr=pix_spec_unc[i][mask],\n                       fmt='s', ec='grey', c=colors[i+1],\n                       marker=markers[i], markersize=10, capsize=2,\n                       label=parobs[i][0])\n            p.add_plot(pix_spec[i][mask], pix_phot2[i][mask],\n                       yerr=pix_phot2_unc[i][mask], xerr=pix_spec_unc[i][mask],\n                       fmt='s', ec='grey', c=colors[i+1], zorder=100,\n                       marker=markers[i], markersize=.1, capsize=2)\n            p.save(path_cal+'IC_'+phot+'.png')\n    \n        ## Linear fit (IRC - SINGS, SLITS)\n        ##=================================\n        popt, pcov = curve_fit(f_lin0, pix_spec[i][mask], pix_phot2[i][mask],)\n                               # sigma=pix_phot2_unc[i][mask])\n        slit_gain = popt[0]\n        # slit_gain = 1.\n        # slit_off = popt[1]\n        slit_off = 0.\n        # slit_off = popt[0]\n        \n        if (synt_phot=='y' or pre_calib2=='y'):\n            print(parobs[i][0]+' inter-calibration ('+phot+') gain = {:.4}'.format(slit_gain))\n            # print(parobs[i][0]+' inter-Calibration ('+phot+') offset = {:.4}'.format(slit_off))\n            # label = parobs[i][0]+': y={0:.4}x'.format(slit_gain)\n            # label = parobs[i][0]+': y={0:.4}x+{1:.4}'.format(slit_gain, slit_off)\n            # p.add_plot(xgrid, f_lin0(xgrid, *popt),\n            #            c='k', ls='-', label=label)\n            # p.save(path_cal+'IC_'+phot+'.png')\n\n## Linear fit (DP - SINGS)\n##=========================\nfitx = np.concatenate(pix_phot1, axis=0)\nuncx = np.concatenate(pix_phot1_unc, axis=0)\nfity = np.concatenate(pix_phot2, axis=0)\nuncy = np.concatenate(pix_phot2_unc, axis=0)\nmaskfit = ~np.logical_or( np.isnan(fitx), np.isnan(fity) )\n\npopt, pcov = curve_fit(f_lin0, fitx[maskfit], fity[maskfit],)\n                       # sigma=uncy[maskfit])\natlas_gain = popt[0]\n# atlas_gain = 1.\n# atlas_off = popt[1]\natlas_off = 0.\n# atlas_off = popt[0]\n\nprint('DustPedia - SINGS calibration ('+phot+') gain = {:.4}'.format(atlas_gain))\n# print('DustPedia - SINGS calibration ('+phot+') offset = {:.4}'.format(atlas_off))\nlabel = 'y={0:.4}x'.format(atlas_gain)\n# label = 'y={0:.4}x+{1:.4}'.format(atlas_gain, atlas_off)\np0.add_plot(xgrid, f_lin0(xgrid, *popt),\n            c='k', ls='-', label=label)\np0.save(path_cal+'DP-SINGS_'+phot+'.png')\n\n## Linear fit (IRC - SINGS, ATLAS)\n##=================================\nfitx = np.concatenate(pix_spec, axis=0)\nuncx = np.concatenate(pix_spec_unc, axis=0)\nfity = np.concatenate(pix_phot2, axis=0)\nuncy = np.concatenate(pix_phot2_unc, axis=0)\nmaskfit = ~np.logical_or( np.isnan(fitx), np.isnan(fity) )\n\npopt, pcov = curve_fit(f_lin0, fitx[maskfit], fity[maskfit],)\n                       # sigma=uncy[maskfit])\natlas_gain = popt[0]\n# atlas_gain = 1.\n# atlas_off = popt[1]\natlas_off = 0.\n# atlas_off = popt[0]\n\nif (synt_phot=='y' or pre_calib2=='y'):\n    print('Atlas inter-calibration ('+phot+') gain = {:.4}'.format(atlas_gain))\n    # print('Atlas inter-Calibration ('+phot+') offset = {:.4}'.format(atlas_off))\n    label = 'y={0:.4}x'.format(atlas_gain)\n    # label = 'y={0:.4}x+{1:.4}'.format(atlas_gain, atlas_off)\n    p.add_plot(xgrid, f_lin0(xgrid, *popt),\n               c='k', ls='-', label=label)\n    p.ax.text(.9,.05,'(a)',size=20,c='grey',transform=p.ax.transAxes)\n    p.ax.legend(loc='upper left', bbox_to_anchor=(1,1),\n                fontsize=20, framealpha=0,)\n    p.save(path_cal+'IC_'+phot+'.png', transparent=True)\n\n## Spectral correction\n##---------------------\nwrite_irc = input(\"Write IRC spectra (y/n)? \")\nif write_irc=='y':\n    if do_build=='y':\n        correct_atlas = input(\" - ATLAS level correction (y/n)? \")\n        if correct_atlas=='y':\n            correct_pixel = None\n        else:\n            correct_pixel = input(\" - PIXEL level correction (y/n)? \")\n    else:\n        warnings.warn('Rebuild slits before spectral correction.')\n        correct_atlas = None\n        correct_pixel = None\nelse:\n    correct_atlas = None\n    correct_pixel = None\n\nfor i in range(Nobs):\n    xscale, yscale = read_hdf5(filog+parobs[i][0], 'Super pixel size')\n    mask_nan = ~np.logical_or( np.isnan(pix_spec[i]), np.isnan(pix_phot2[i]) )\n    mask_neg = np.logical_and( pix_spec[i]>0, pix_phot2[i]>0 )\n    mask = np.logical_and( mask_nan, mask_neg )\n    sc = intercalib(fits_irc[i]+'_0') # Attention: NOT fits_irc[i]\n    Nw, Ny, Nx = sc.im.shape\n    pixel_gain = np.ones((Ny,Nx))\n    if mask.any():\n        for y in range(Ny):\n            ys = pix2sup(y, yscale, origin=0)\n            if mask[ys]:\n                pixel_gain[y,:] *= pix_phot2[i][ys]/pix_spec[i][ys]\n            # if y%yscale==0:\n            #     print(parobs[i][0]+' inter-calibration gain: {}'.format(pixel_gain[y,0]))\n    if write_irc=='y':\n        if correct_pixel=='y':\n            calib_gain = pixel_gain\n        elif correct_atlas=='y':\n            calib_gain = atlas_gain\n        else:\n            calib_gain = 1.0\n        sc.correct_spec(calib_gain, filOUT=out_irc[i])\n\n\n##----------------------\n## Fit correlation (MC)\n##----------------------\nfor j in trange(Nmc, #leave=False,\n                desc='IRC spectral correction [MC]'):\n    ## Data dictionary\n    ## e.g. [{'A0': a0, 'A1': a1, ...}, {'B0': b0, 'B1': b1, ...}, ...]\n    dict_spec = []\n    dict_spec_unc = []\n    ## Data 1D array\n    ## e.g. [array([a1, a2, ...]), array([b1, b2, ...]), ...]\n    pix_spec = []\n    pix_spec_unc = []\n    \n    for i in range(Nobs):\n        # Nx = read_hdf5(filog+parobs[i][0], 'Slit width')\n        Ny = read_hdf5(filog+parobs[i][0], 'Slit length')[0]\n        xscale, yscale = read_hdf5(filog+parobs[i][0], 'Super pixel size')\n        # Nxs = math.ceil(Nx/xscale)\n        Nys = math.ceil(Ny/yscale)\n    \n        ## Init dict\n        data3 = {}\n        unc3 = {}\n        for ys in range(Nys):\n            subname = parobs[i][0][0]+str(ys+1)\n            yarr = sup2pix(ys, yscale, Npix=Ny, origin=0)\n            ## spec\n            ds = read_fits(tmp_spec+'_'+parobs[i][0]+'_'+str(j+1),\n                           fits_spec+'_'+parobs[i][0]+'_unc') # intermediate unc\n            data3[subname] = ds.data[yarr[0],0]\n            unc3[subname] = ds.unc[yarr[0],0]\n        dict_spec.append(data3)\n        dict_spec_unc.append(unc3)\n    \n        ## Dictionary to 1D array\n        pix_spec.append(np.array(list(dict_spec[i].values())))\n        pix_spec_unc.append(np.array(list(dict_spec_unc[i].values())))\n    \n        ## Mask NaNs and negtive values\n        mask_nan = ~np.logical_or( np.isnan(pix_spec[i]), np.isnan(pix_phot2[i]) )\n        mask_neg = np.logical_and( pix_spec[i]>0, pix_phot2[i]>0 )\n        mask = np.logical_and( mask_nan, mask_neg )\n        \n    ## Linear fit (IRC - SINGS, ATLAS)\n    ##=================================\n    fitx = np.concatenate(pix_spec, axis=0)\n    uncx = np.concatenate(pix_spec_unc, axis=0)\n    fity = np.concatenate(pix_phot2, axis=0)\n    uncy = np.concatenate(pix_phot2_unc, axis=0)\n    maskfit = ~np.logical_or( np.isnan(fitx), np.isnan(fity) )\n    \n    popt, pcov = curve_fit(f_lin0, fitx[maskfit], fity[maskfit],)\n                           # sigma=uncy[maskfit])\n    atlas_gain = popt[0]\n    # atlas_gain = 1.\n    # atlas_off = popt[1]\n    atlas_off = 0.\n    # atlas_off = popt[0]\n    \n    ## Spectral correction\n    ##---------------------\n    for i in range(Nobs):\n        xscale, yscale = read_hdf5(filog+parobs[i][0], 'Super pixel size')\n        mask_nan = ~np.logical_or( np.isnan(pix_spec[i]), np.isnan(pix_phot2[i]) )\n        mask_neg = np.logical_and( pix_spec[i]>0, pix_phot2[i]>0 )\n        mask = np.logical_and( mask_nan, mask_neg )\n        sc = intercalib(fits_irc[i]+'_'+str(j+1))\n        Nw, Ny, Nx = sc.im.shape\n        pixel_gain = np.ones((Ny,Nx))\n        if mask.any():\n            for y in range(Ny):\n                ys = pix2sup(y, yscale, origin=0)\n                if mask[ys]:\n                    pixel_gain[y,:] *= pix_phot2[i][ys]/pix_spec[i][ys]\n                # if y%yscale==0:\n                #     print(parobs[i][0]+' inter-calibration gain: {}'.format(pixel_gain[y,0]))\n        if (write_irc=='y'):\n            ## fits_irc[i] can be changed by inter-calib,\n            ## One need to rebuild before synthetic photometry\n            if correct_pixel=='y':\n                calib_gain = pixel_gain\n            elif correct_atlas=='y':\n                calib_gain = atlas_gain\n            else:\n                calib_gain = 1.0\n            sc.correct_spec(calib_gain, filOUT=fits_irc[i]+'_'+str(j+1))\n\nif (write_irc=='y' and Nmc>1):\n    for i in trange(Nobs, leave=False,\n                    desc='Calculating uncertainties for IRC slits'):\n        mcimage = []\n        for j in range(Nmc):\n            ds = read_fits(fits_irc[i]+'_'+str(j+1))\n            mcimage.append(ds.data)\n        mcimage = np.array(mcimage)\n        unc = np.nanstd(mcimage, axis=0)\n        write_fits(out_irc[i]+'_unc', ds.header, unc, ds.wave)\n\n\n##----------------------------------------------------------\n\n##                      Plot spectra\n\n##----------------------------------------------------------\nplot_spec = input(\"Plot IRC spectra (y/n)? \")\nif plot_spec=='y':\n\n    for i in range(Nobs):\n        ds = read_fits(out_irc[i], out_irc[i]+'_unc')\n        Nw, Ny, Nx = ds.data.shape\n        ds0 = read_fits(fits_irc[i]+'_0')\n        pp = intercalib(out_irc[i])\n        pp.read_filter(phot)\n        wcen = pp.wcen\n        \n        xscale, yscale = read_hdf5(filog+parobs[i][0], 'Super pixel size')\n        for y in range(Ny):\n            ys = pix2sup(y, yscale, origin=0)\n            subname = parobs[i][0][0]+str(ys+1)\n            maskspec = ~np.isnan(ds.data[:,y,0]).any()\n            if (maskspec and y%yscale==0):\n                p = pplot(ds.wave, ds.data[:,y,0], yerr=ds.unc[:,y,0],\n                          # xlog=1, ylog=1, \n                          c='k', lw=.7, ec='r', label=subname,\n                          xlabel=r'${\\rm Wavelengths}\\ \\lambda\\ (\\mu m)$',\n                          ylabel=r'${\\rm Surface\\ brightness}\\ F_{\\nu}\\ (MJy/sr)$',\n                          figsize=(8,8), legend='upper left',\n                          title='IRC_'+subname,\n                          titlesize=20, labelsize=10, ticksize=10, legendsize=10)\n                ## Non-intercalib\n                p.add_plot(ds.wave, ds0.data[:,y,0],\n                           c='y', lw=.7, ls='--', zorder=-1)\n                ## Photometry\n                p.add_plot(wcen[0], dict_phot2[i][subname], yerr=dict_phot2_unc[i][subname],\n                           c='m', marker='o', ms=10, zorder=100, label=phot)\n                ## Synthetic photometry\n                p.add_plot(wcen[0], dict_spec[i][subname], yerr=dict_spec_unc[i][subname],\n                           c='g', marker='^', ms=10, zorder=101, label='IRC-'+phot)\n                \n                p.save(path_fig+'IRC_'+subname)\n\n", "meta": {"hexsha": "2b8432cd252c0a2d23b570df100324480dd294b3", "size": 31428, "ext": "py", "lang": "Python", "max_stars_repo_path": "MIRAGE/src/M82/build_irc.py", "max_stars_repo_name": "kxxdhdn/MISSILE", "max_stars_repo_head_hexsha": "89dea38aa9247f20c444ccd0b832c674be275fbf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MIRAGE/src/M82/build_irc.py", "max_issues_repo_name": "kxxdhdn/MISSILE", "max_issues_repo_head_hexsha": "89dea38aa9247f20c444ccd0b832c674be275fbf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MIRAGE/src/M82/build_irc.py", "max_forks_repo_name": "kxxdhdn/MISSILE", "max_forks_repo_head_hexsha": "89dea38aa9247f20c444ccd0b832c674be275fbf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.883248731, "max_line_length": 97, "alphanum_fraction": 0.5149548174, "include": true, "reason": "import numpy,from scipy", "num_tokens": 8888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.25386101825929835, "lm_q1q2_score": 0.15331475026887703}}
{"text": "import numpy as np\n\n\ndef calculate_map_main(gt_results, pred_results, iou_gt_thr=0.5, class_num=5):\n    '''\n    说明: 此函数用于计算目标检测中的mAP\n    输入:\n          gt_results:  list, 每一个元素对应一个样本中的所有目标的真实值\n          如gt_gt_result[0] = [\n                                [xmin, ymin, xmax, ymax, label],\n                                [xmin, ymin, xamx, yamx, label],\n                                ...\n                              ]\n          pred_results: list, 每一个元素对应一个样本中的所有目标的预测值\n          如pred_results[0] = [\n                                [xmin, ymin, xmax, ymax, label, score],\n                                [xmin, ymin, xamx, yamx, label, score],\n                                ...\n                              ]\n          iou_gt_thr:   float, 用于判定正负样本, 如iou_gt_thr=0.5, 计算出的就是mAP 0.5\n          class_num:    int, 类别数\n    输出：\n          calss_ap:     array, 各类别的AP\n          mean_ap :     float, 各类别平均得到mAP\n    '''\n\n    all_tp = [ [] for i in range(class_num) ]    # 用于存放各类所有的tp\n    all_fp = [ [] for i in range(class_num) ]    # 用于存放各类所有的fp\n    all_score = [ [] for i in range(class_num) ] # 用于存放bbox对应的scores\n    all_gt_num = np.zeros([class_num])           # 用于存放各类的真实目标数, 之后计算recall会用到\n    data_num = len(gt_results)                        # 样本总数\n\n    # 对于每一个样本, 计算tp, fp, 并且统计预测bbox的score以及真实目标的个数\n    for i in range(data_num):\n        gt_result = gt_results[i]\n        pred_result = pred_results[i]\n        # print(f'computing {i} tp and fp')\n        tp, fp, score, gt_num = calculate_tpfp_single(gt_result, pred_result, iou_gt_thr, class_num)\n        # 按类别更新到总数中\n        for n in range(class_num):\n            all_tp[n].extend(tp[n])\n            all_fp[n].extend(fp[n])\n            all_score[n].extend(score[n])\n            all_gt_num[n] += gt_num[n]\n\n    # 计算出各类的AP，进而得到mAP\n    all_map = calculate_map(all_tp, all_fp, all_score, all_gt_num, class_num)\n    mean_ap = np.mean(all_map[1:])\n    print('mAP', mean_ap)\n    return all_map, mean_ap\n\n\ndef calculate_tpfp_single(gt_result, pred_result, iou_gt_thr, class_num):\n    '''\n    说明: 此函数用于计算单个样本的tp和fp, 并且存放对应的score, 统计真实目标的个数\n    输入:\n          gt_result:  list, 一个样本中所有的目标的真实值\n          如gt_result=[\n                        [xmin, ymin, xmax, ymax, label],\n                        [xmin, ymin, xmax, ymax, label],\n                        ...\n                      ]\n          pred_result: list, 一个样本中所有的目标的预测值\n          如pred_result=[\n                          [xmin, ymin, xmax, ymax, label, score],\n                          [xmin, ymin, xmax, ymax, label, score],\n                          ...\n                        ]\n          iou_gt_thr:  float, 用于判断正负样本的iou阈值\n          class_num:   类别数\n    输出:\n          all_tp:      list, 每一个元素对应该样本计算出的对应类别的tp\n          all_fp:      list, 每一个元素对应该样本计算出的对应类别的fp\n          all_score:   list, 每一个元素对应该样本bbox对应类别的score\n          gt_num:      list, 每一个元素对应该样本对应类别的真实目标数\n    '''\n\n    all_tp = [[] for i in range(class_num)]\n    all_fp = [[] for i in range(class_num)]\n    all_score = [[] for i in range(class_num)]\n    gt_num = np.zeros([class_num])\n\n    # 逐个类别提取真实bbox和预测bbox\n    for i in range(class_num):\n        tp = []\n        fp = []\n        score = []\n\n        match_gt_bbox = [obj[0:4] for obj in gt_result if int(obj[4]) == i]\n        match_pred_bbox = [obj[0:4] for obj in pred_result if int(obj[4]) == i]\n        match_pred_score = [obj[5] for obj in pred_result if int(obj[4]) == i]\n\n        len_gt = len(match_gt_bbox)\n        len_pred = len(match_pred_bbox)\n\n        if len_gt == 0 and len_pred != 0:\n            # 说明不存在该类目标，但是预测出来了，属于误检\n            score.extend(match_pred_score)\n            for k in range(len_pred):\n                tp.extend([0])\n                fp.extend([1])\n\n        if len_gt != 0 and len_pred != 0:\n            # 说明存在该目标，并且检测出来了,那么计算若干gt与若干pred的iou\n            score.extend(match_pred_score)\n            ious = calculate_iou(match_gt_bbox, match_pred_bbox)\n            max_iou = np.max(ious, axis=0)  # [x,x,x...] 每一个预测框与某个gt最大的iou\n            # if any(s > 0.65 for s in max_iou):\n            #     print(f\"The image has good IOU: {max_iou}\")\n            # if any(s < 0.1 for s in max_iou):\n                # print(f\"The image has bad IOU: {max_iou}\")\n            # 使用iou_gt_thr来进行正负样本的判定，若满足条件，则为tp，否则为fp\n            for k in range(len_pred):\n                if max_iou[k] >= iou_gt_thr:\n                    tp.extend([1])\n                    fp.extend([0])\n                if max_iou[k] < iou_gt_thr:\n                    tp.extend([0])\n                    fp.extend([1])\n\n        all_tp[i].extend(tp)\n        all_fp[i].extend(fp)\n        all_score[i].extend(score)\n        gt_num[i] += len_gt\n\n    return all_tp, all_fp, all_score, gt_num\n\n\ndef calculate_area(bbox):\n    # 计算一个bbox的面积\n    w = max(bbox[2] - bbox[0], 0)\n    h = max(bbox[3] - bbox[1], 0)\n    w = max(0, w)\n    h = max(0, h)\n    return w * h\n\n\ndef calculate_inter(bbox1, bbox2):\n    # 计算两个bbox的交集面积\n    xmin = max(bbox1[0], bbox2[0])\n    ymin = max(bbox1[1], bbox2[1])\n    xmax = min(bbox1[2], bbox2[2])\n    ymax = min(bbox1[3], bbox2[3])\n    return calculate_area([xmin, ymin, xmax, ymax])\n\n\ndef calculate_union(bbox1, bbox2):\n    # 计算两个bbox的并集面积\n    area1 = calculate_area(bbox1)\n    area2 = calculate_area(bbox2)\n    inter = calculate_inter(bbox1, bbox2)\n    union = area1 + area2 - inter\n    return union\n\n\ndef IOU(bbox1, bbox2):\n    # 计算两个bbox的iou\n    inter = calculate_inter(bbox1, bbox2)\n    union = calculate_union(bbox1, bbox2)\n    iou = inter / union\n    return iou\n\n\ndef calculate_iou(bbox1, bbox2):\n    '''\n    说明: 此函数用于计算M个bbox与N个bbox的iou\n    输入:\n          bbox1: list, 每一个元素是一个bbox, 如bbox1=[\n                                                     [xmin, ymin, xamx, ymax],\n                                                     [xmin, ymin, xmax, ymax],\n                                                     ...\n                                                    ]\n          bbox2: list, 每一个元素是一个bbox, 如bbox2=[\n                                                     [xmin, ymin, xamx, ymax],\n                                                     [xmin, ymin, xmax, ymax],\n                                                     ...\n                                                    ]\n    输出:\n          ans:   array, size=[M, N], 计算出的iou矩阵\n    '''\n\n    len_1 = len(bbox1)\n    len_2 = len(bbox2)\n    ans = np.zeros([len_1, len_2])\n    for i in range(len_1):\n        for j in range(len_2):\n            # 计算bbox1[i]和bbox2[j]的iou\n            ans[i, j] = IOU(bbox1[i], bbox2[j])\n    return ans\n\n\ndef calculate_map(all_tp, all_fp, all_score, all_gt_num, class_num):\n    '''\n    说明: 此函数的输入为所有类别的tp, fp, score和真实目标数, 计算每一个类别的AP\n    输入:\n          all_tp:     list,  每个元素是该类别下的tp\n          all_fp:     list,  每个元素是该类别下的fp\n          all_score:  list,  每个元素是该类别下预测bbox对应的score\n          all_gt_num: list,  每个元素是该类下真实母目标的个数\n          class_num:  int,   类别数\n    输出:\n          all_map:    array, 每个元素是该类的AP\n    '''\n\n    all_map = np.zeros([class_num])\n    for i in range(class_num):\n    # 首先提取出每一类的信息\n        class_tp = all_tp[i]\n        class_fp = all_fp[i]\n        class_score = all_score[i]\n        class_gt_num = all_gt_num[i]\n        # 计算每一类的PR曲线\n        class_P, class_R = calculate_PR(class_tp, class_fp, class_score, class_gt_num)\n        # 计算PR曲线的面积，即AP\n        class_map = calculate_map_single(class_P, class_R)\n        # 写入该类别下\n        all_map[i] = class_map\n    return all_map\n\n\ndef calculate_PR(class_tp, class_fp, class_score, class_gt_num):\n    '''\n    说明: 此函数用于计算某一类的PR曲线\n    输入:\n          class_tp:     list, 该类下的tp, 每个元素为0或1, 代表当前样本是否为正样本\n          class_fp:     list, 该类下的fp, 每个元素为0或1, 代表当前样本是否为负样本\n          class_score:  list, 该类下预测bbox对应的score\n          class_gt_num: int,  类别数\n    输出:\n          P: list, 该类下的查准率曲线\n          R: list, 该类下的查全率曲线\n    '''\n\n    # 按照score排序\n    sort_inds = np.argsort(class_score)[::-1].tolist()\n    tp = [class_tp[i] for i in sort_inds]\n    fp = [class_fp[i] for i in sort_inds]\n    # 累加\n    tp = np.cumsum(tp).tolist()\n    fp = np.cumsum(fp).tolist()\n    # 计算PR\n    P = [tp[i] / (tp[i] + fp[i]) for i in range(len(tp))]\n    R = [tp[i] / class_gt_num for i in range(len(tp))]\n    return P, R\n\n\ndef calculate_map_single(P, R):\n    '''\n    说明: 此函数用于计算PR曲线的面积, 即AP\n    输入:\n          P: list, 查准率曲线\n          R: list, 查全率曲线\n    输出:\n          single_map: float, 曲线面积, 即AP\n    '''\n    mpre = np.concatenate(([0.], P, [0.]))\n    mrec = np.concatenate(([0.], R, [1.]))\n    for i in range(np.size(mpre) - 1, 0, -1):\n        # mpre的平整化\n        mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n    # 寻找mrec变化的坐标\n    i = np.where(mrec[1:] != mrec[:-1])[0]\n    # 计算面积\n    single_map = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n    return single_map\n\n\ndef NMS(bounding_boxes, S=7, img_size=224, confidence_threshold=0.5, iou_threshold=0.5):\n    \"\"\"Compute non max suppressing to reduce overlapping bounding box.\n\n    Args:\n        bounding_boxes (list): a list of bounding box.\n        S (int): the number of grid cells.\n        img_size (int): image size\n        confidence_threshold (float): the threshold to select a box on has_obj_prob (has_object_probability).\n        iou_threshold (float): the threshold of IOU to remove bounding boxes.\n\n    Returns:\n        a list of bounding boxes.\n        bounding box format = [center_x (int), center_y (int), width (int), height (int), has_obj_prob (float),\n                               class_probs (float), confident_score (float), class_id (int)].\n            class_probs is a list of class probability. confident_score = has_obj_prob * max(class_prob).\n            class_id is argmax(class_probs).\n\n    \"\"\"\n    bounding_boxes = bounding_boxes.cpu().detach().numpy().tolist()\n    nms_boxes_buf = []\n    grid_size = img_size / S\n    for batch in range(len(bounding_boxes)):\n        predict_boxes = []\n        nms_boxes = []\n        for i in range(S):\n            for j in range(S):\n                gridX = grid_size * j\n                gridY = grid_size * i\n                if bounding_boxes[batch][i][j][4] < bounding_boxes[batch][i][j][9]:\n                    bounding_box = bounding_boxes[batch][i][j][5:10]\n                else:\n                    bounding_box = bounding_boxes[batch][i][j][0:5]\n                bounding_box.extend(bounding_boxes[batch][i][j][10:])\n                if bounding_box[4] >= confidence_threshold:\n                    predict_boxes.append(bounding_box)\n\n                centerX = (int)(gridX + bounding_box[0] * grid_size)\n                centerY = (int)(gridY + bounding_box[1] * grid_size)\n                width = (int)(bounding_box[2] * img_size)\n                height = (int)(bounding_box[3] * img_size)\n                bounding_box[0] = max(0, (int)(centerX - width / 2))\n                bounding_box[1] = max(0, (int)(centerY - height / 2))\n                bounding_box[2] = min(img_size - 1, (int)(centerX + width / 2))\n                bounding_box[3] = min(img_size - 1, (int)(centerY + height / 2))\n                class_idx = np.argmax(bounding_box[5:])\n                confident_score = bounding_box[4] * bounding_box[5 + class_idx]  # has_obj_prob * class_prob\n                bounding_box.append(confident_score)\n                bounding_box.append(class_idx)\n\n        while len(predict_boxes) != 0:\n            predict_boxes.sort(key=lambda box: box[4])\n            assured_box = predict_boxes[0]\n            curr_class = assured_box[-1]\n            temp = []\n            nms_boxes.append(assured_box)\n            i = 1\n            while i < len(predict_boxes):\n                compared_box = predict_boxes[i]\n                if compared_box[-1] != curr_class or IOU(assured_box, predict_boxes[i]) <= iou_threshold:\n                    temp.append(predict_boxes[i])\n                i = i + 1\n            predict_boxes = temp\n\n        nms_boxes_buf.append(nms_boxes)\n\n    return nms_boxes_buf\n\n\ndef gt_std(gt_results, S=7, B=2, img_size=224):\n\n    gt_results_all = []\n    grid_size = img_size / S\n    for instance_index in range(gt_results.shape[0]): # N\n        gt_results_instance = []\n        for index_i in range(gt_results.shape[1]): # 7\n            for index_j in range(gt_results.shape[2]): # 7\n                gridX = grid_size * index_j\n                gridY = grid_size * index_i\n                area = gt_results[instance_index, index_i, index_j, 9]\n                if area > 0:\n                    gt_results_patch = gt_results[instance_index, index_i, index_j].tolist()\n                    centerX = (int)(gridX + gt_results_patch[0] * grid_size)\n                    centerY = (int)(gridY + gt_results_patch[1] * grid_size)\n                    width = (int)(gt_results_patch[2] * img_size)\n                    height = (int)(gt_results_patch[3] * img_size)\n                    class_idx = int(gt_results[instance_index, index_i, index_j, 10:].argmax())\n                    gt_results_patch[0] = max(0, (int)(centerX - width / 2))\n                    gt_results_patch[1] = max(0, (int)(centerY - height / 2))\n                    gt_results_patch[2] = min(img_size - 1, (int)(centerX + width / 2))\n                    gt_results_patch[3] = min(img_size - 1, (int)(centerY + height / 2))\n                    gt_results_patch[4] = class_idx\n                    gt_results_instance.append(gt_results_patch[0:5])\n\n        gt_results_all.append(gt_results_instance)\n\n    return gt_results_all\n", "meta": {"hexsha": "cc3e57d81bd2e8d152ace85450672b304b029a8a", "size": 13327, "ext": "py", "lang": "Python", "max_stars_repo_path": "map.py", "max_stars_repo_name": "jmenges/yolov1_maxim", "max_stars_repo_head_hexsha": "299d0d52edf3aec961b3b9c72cdd590352d26beb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-24T16:27:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T16:27:03.000Z", "max_issues_repo_path": "map.py", "max_issues_repo_name": "jmenges/yolov1_maxim", "max_issues_repo_head_hexsha": "299d0d52edf3aec961b3b9c72cdd590352d26beb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "map.py", "max_forks_repo_name": "jmenges/yolov1_maxim", "max_forks_repo_head_hexsha": "299d0d52edf3aec961b3b9c72cdd590352d26beb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-28T15:30:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T15:30:08.000Z", "avg_line_length": 36.6126373626, "max_line_length": 111, "alphanum_fraction": 0.535004127, "include": true, "reason": "import numpy", "num_tokens": 4124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.26894141551050293, "lm_q1q2_score": 0.15325698263305856}}
{"text": "# Copyright 2021 United States Government as represented by the Administrator of the National Aeronautics and Space\n# Administration.  No copyright is claimed in the United States under Title 17, U.S. Code. All Other Rights Reserved.\n\n\n\"\"\"\nThis module defines the interface to the default GIANT star catalogue.\n\nCatalogue Description\n=====================\n\nThe default GIANT star catalogue is a blending of the UCAC4 and Tycho2 catalogues into a stripped down sqlite3 database.\nThis makes retrieval of stars very fast instead of using the UCAC4 or Tycho2 catalogue files themselves and also\nincludes blended stars (stars that are so close together they will appear as a single star in most cameras).  This\ncatalogue includes stars down to about 16th magnitude and should be sufficient for nearly all stellar OpNav needs.\n\nThe current implementation of the database storing this catalogue is a single table with a primary index column of rnm,\nwhich contains the unique ID of the provided star from the UCAC4 catalogue.  For blended stars, the index number becomes\nthe negative of the unique ID of the brightest star in the group.  In addition to the index, the following columns are\nprovided\n\n================= ====== ======== ======================================================================================\nColumn            Units  Type     Description\n================= ====== ======== ======================================================================================\nsource            N/A    string   The original catalogue source of the star (UCAC4 or Tycho2)\nzone              N/A    integer  The UCAC4 zone number for the star, if applicable\nrnz               N/A    integer  The star number in the UCAC4 zone if applicable\nra                deg    double   The right ascension of the star in degrees\ndec               deg    double   The declination of the star in degrees\ndistance          km     double   The distance to the star in km.  If not known then this is replaced with the average\n                                  distance to a star\nra_proper_motion  deg/yr double   The proper motion of the right ascension of the star in degrees per SI year\ndec_proper_motion deg/yr double   The proper motion of the declination of the star in degrees per SI year\nmag               mag    double   The visual magnitude of the star.  This is the APASM_V magnitude if available,\n                                  otherwise the MAGM (model magnitude) from the UCAC4 catalogue.\nra_sigma          deg    double   The right ascension uncertainty in units of degrees\ndec_sigma         deg    double   The declination uncertainty in units of degrees\ndistance_sigma    km     double   The distance uncertainty in units of kilometers.  For stars for which this is not\n                                  known it is set to a large number\nra_pm_sigma       deg/yr double   The right ascension proper motion uncertainty in degrees per SI year.\ndec_pm_sigma      deg/yr double   The declination proper motion uncertainty in degrees per SI year.\n================= ====== ======== ======================================================================================\n\nWhile this implementation mirrors the :attr:`.GIANT_COLUMNS` currently, and probably will in the future, it isn't\nguaranteed to stay that way.  In addition, while this is currently a blend of the UCAC4 and Tycho2 catalogues, in the\nfuture it will likely be built from the GAIA DR2 catalogue since this provides much more accurate stars\npositions/magnitudes for many more stars.\n\nUse\n===\n\nThe GIANT catalogue can be used anywhere that a star catalogue is required in GIANT and is generally the default\ncatalogue that is used if you do not override it.  It is stored in a sqlite file in a directory called data in the same\ndirectory hosting this file, though it is possible to override this if desired (which you may want to do if you need\ndifferent versions of the catalogue for different cameras). To access the default catalogue simply initialize this class\nwith no arguments and then call :meth:`~.GIANTCatalogue.query_catalogue` to retrieve the star records that you want.\n\nThis implementation also provides 2 helper methods that can retrieve the original star record from either the Tycho 2 or\nUCAC4 catalogue (if the star exists in them and is not a blended star).  These are\n:meth:`~.GIANTCatalogue.get_ucac4_record` and :meth:`~.GIANTCatalogue.get_tycho2_record`.  They take in a pandas\nDataFrame of stars retrieved from this catalogue and return a dataframe with the original records for those stars.\nThis can be useful if you need more information about a star than what GIANT typically considers.  Just note that these\nmethods will require that the entire UCAC4/Tycho2 star catalogues be downloaded if they aren't already.\n\nThis module also provides a few functions that can be used to build a new version of this catalogue,\n:func:`build_catalogue`, :func:`find_star_pairs`, and :func:`blend_stars`.  Typically you won't interact with these\ndirectly and instead will use the script :mod:`~.scripts.build_catalogue` which provides a command line interface,\nhowever they're provided for those who are interested in what they do or in doing some more advanced things.\n\"\"\"\n\nfrom pathlib import Path\nimport time\n\nfrom itertools import repeat, starmap\n\nfrom warnings import filterwarnings, catch_warnings\n\nimport sqlite3\n\nfrom datetime import datetime\n\nfrom typing import Optional, Union\n\nimport numpy as np\nimport pandas as pd\nfrom scipy.spatial import cKDTree\n\nfrom giant.catalogues.utilities import radec_to_unit, apply_proper_motion, radec_distance, DEG2RAD\nfrom giant.catalogues.meta_catalogue import Catalogue\nfrom giant._typing import PATH, Real, ARRAY_LIKE\n\n\nDEFAULT_CAT_FILE: Path = (Path(__file__).parent / \"data\") / 'giant_cat.db'\n\"\"\"\nThis specifies the default location of the sqlite3 database file that contains the data for this catalogue.\n\nThis is stored as Path object.  It defaults to a file called \"giant_cat.db\" in a \"data\" directory in the same directory \ncontaining this file. If you wish to use a different catalogue, typically you should simply provide a key\nword argument to the class constructor instead of modifying this module attribute.\n\"\"\"\n\n\n_STARS_TABLE_SQL: str = '''CREATE TABLE IF NOT EXISTS \"stars\" (\n  \"rnm\" INTEGER UNIQUE PRIMARY KEY NOT NULL ON CONFLICT REPLACE,\n  \"source\" TEXT,\n  \"zone\" INTEGER,\n  \"rnz\" INTEGER,\n  \"ra\" REAL,\n  \"dec\" REAL,\n  \"distance\" REAL,\n  \"ra_proper_motion\" REAL,\n  \"dec_proper_motion\" REAL,\n  \"mag\" REAL,\n  \"ra_sigma\" REAL,\n  \"dec_sigma\" REAL,\n  \"distance_sigma\" REAL,\n  \"ra_pm_sigma\" REAL,\n  \"dec_pm_sigma\" REAL,\n  \"epoch\" REAL\n)'''\n\"\"\"\nThis SQL command creates a new table in the sqlite3 database file called stars for storing the GIANT catalogue\n\nThis shouldn't be used by the user and may change without notice.\n\"\"\"\n\n\ndef build_catalogue(database_file: Optional[PATH] = None, limiting_magnitude: Real = 12, number_of_stars: int = 0,\n                    use_tycho_mag: bool = False, limiting_separation: float = 0.04, blending_magnitude: Real = 8,\n                    ucac_dir: Optional[PATH] = None):\n    \"\"\"\n    Build a sqlite3 catalogue from the UCAC catalogue for faster query times.\n\n    This function can be used to build a new GIANT catalogue (or overwrite an old one) from the UCAC4/Tycho2 star\n    catalogues.  Typically a user will not use this directly and instead will use the command line utility\n    :mod:`~.scripts.build_catalogue`.\n\n    If you want to use this function, you can adjust how (and where) the catalogue is built by adjusting the key word\n    arguments.  Note that this will require downloading the UCAC4 catalogue (if it isn't already available) and possibly\n    the Tycho2 Catalogue.  In addition, building the catalogue can take a long time, so you will want to have a period\n    where you can leave this run for a while without interruption to ensure that the catalogue is built successfully and\n    not corrupted.\n\n    :param database_file: The file to save the catalogue database to\n    :param limiting_magnitude: The maximum magnitude to include in the catalogue\n    :param number_of_stars: The maximum number of stars that can be blended together in any group.  To turn off star\n                            blending, set this to 0.\n    :param use_tycho_mag: A flag specifying whether to replace the UCAC4/APASM_V magnitudes with the Tycho VT magnitude.\n                          The Tycho VTMag is more accurate, but this can make things take even longer to compile so by\n                          default it is not used.\n    :param limiting_separation: The maximum separation between stars for them to be considered for blending in degrees.\n                                Typically this should be set to around the IFOV on the detector you are considering.\n    :param blending_magnitude: The magnitude of the blended star for it to be included as a blended star in the\n                               catalogue.\n    :param ucac_dir: The directory containing the UCAC4 data files.  This is passed to the :class:`.UCAC4` class.\n    \"\"\"\n\n    with catch_warnings():\n        # ignore dumb warnings\n        filterwarnings('ignore', message='The requested UCAC4')\n\n        # import the UCAC4 interface and default directory\n        from giant.catalogues.ucac import UCAC4, UCAC_DIR\n\n        # use the default if the user didn't specify\n        if database_file is None:\n            database_file = DEFAULT_CAT_FILE\n        else:\n             database_file = Path(database_file)\n\n        # make sure the directory for the database file exists\n        database_file.parent.mkdir(exist_ok=True, parents=True)\n\n        if database_file.exists():\n            database_file.unlink()\n            \n        # connect to the database\n        db_con = sqlite3.connect(str(database_file))\n\n        # get the UCAC instance\n        if ucac_dir is None:\n            ucac = UCAC4(UCAC_DIR)\n        else:\n            ucac = UCAC4(ucac_dir)\n\n        # determine the magnitude to query from the catalogue\n        if number_of_stars == 0:\n            blend_mag = -4.0\n            query_mag = limiting_magnitude\n        else:\n            blend_mag = blending_magnitude + (2.5 * np.log10(number_of_stars))\n            query_mag = max(limiting_magnitude, blend_mag)\n\n        print('Query mag {}'.format(query_mag), flush=True)\n\n        # Create the table/indices in the database\n        db_con.execute(\"DROP TABLE IF EXISTS stars\")\n        db_con.execute(_STARS_TABLE_SQL)\n        db_con.execute(\"CREATE UNIQUE INDEX idx_rnm on stars(rnm)\")\n        db_con.execute(\"CREATE INDEX idx_ra on stars(ra)\")\n        db_con.execute(\"CREATE INDEX idx_dec on stars(dec)\")\n        db_con.execute(\"CREATE INDEX idx_mag on stars(mag)\")\n        db_con.commit()\n\n        print('creating database', flush=True)\n        if number_of_stars == 0:\n            # dump the UCAC4 stars to the database\n            ucac.dump_to_sqlite(db_con, limiting_mag=query_mag, use_tycho_mag=use_tycho_mag,\n                                return_locations=False)\n        else:\n            # dump the UCAC4 stars to the database\n            records = ucac.dump_to_sqlite(db_con, limiting_mag=query_mag, use_tycho_mag=use_tycho_mag,\n                                          return_locations=True, return_mag=blend_mag)\n\n            # pair the stars based on distance\n            print('finding close star pairs', flush=True)\n            pairs = find_star_pairs(records, limiting_separation)\n\n            # get rid of the old dataframe for memory reasons\n            del records\n\n            # blend the stars together\n            print('blending stars', flush=True)\n            combined_stars = blend_stars(pairs, db_con, limiting_magnitude)\n\n            # rename the index column\n            combined_stars.index.name = 'rnm'\n\n            # dump to the stars table in the database\n            print('adding blended stars to db', flush=True)\n            combined_stars.to_sql('stars', db_con, if_exists='append')\n\n\ndef _repair(star_records: pd.DataFrame, pairs: pd.DataFrame) -> pd.DataFrame:\n    \"\"\"\n    This helper function combines multiple pairs and gets rid of duplicates\n\n    Don't use this yourself.\n\n    :param star_records: The dataframe of star records\n    :param pairs: The dataframe specifying groups of stars\n    :return: The dataframe specifying groups of stars after correcting the groupings\n    \"\"\"\n    # get the unique right hand sides\n    unique_others = pairs.b.unique()\n\n    paired_dict: pd.DataFrame = pairs.groupby('a')['b'].apply(set)\n    removes = []\n    for initial, others in paired_dict.iteritems():\n        sets = []\n        starts = []\n        # look for where initial is also paired to another star\n        if (initial in unique_others) and (initial not in removes):\n            for local_initial, local_others in paired_dict.iteritems():\n                if local_initial == initial:\n                    continue\n                elif initial in local_others:\n                    # if the others is a subset of the first group we don't need to do anything\n                    if others.issubset(local_others):\n                        # should we also remove local_initial here?\n                        continue\n                    # otherwise store them for use\n                    sets.append(local_others)\n                    starts.append(local_initial)\n            # if anything needs modified\n            if starts:\n                for local_initial, local_others in zip(starts, sets):\n                    if len(starts) == 1:\n                        # keep which ever has the higher magnitude on the left hand side and discard the other\n                        if star_records.loc[local_initial, \"mag\"] < star_records.loc[initial, \"mag\"]:\n                            local_others.update(others)\n                            removes.append(initial)\n\n                        else:\n                            others.update(local_others)\n                            removes.append(local_initial)\n\n                    else:\n                        # keep the brightest magnitude\n                        best = initial\n                        best_mag = star_records.loc[initial, \"mag\"]\n                        best_set = others\n                        for o, ls in zip(starts, sets):\n                            if best_mag > star_records.loc[o, \"mag\"]:\n                                best_mag = star_records.loc[o, \"mag\"]\n                                best = o\n                                best_set = ls\n\n                        # get rid of whichever aren't the brightest and feed it\n                        if best != initial:\n                            removes.append(initial)\n                            best_set.update(others)\n                        for local_local_initial, local_local_others in zip(starts, sets):\n                            if local_local_initial == best:\n                                continue\n                            best_set.update(local_local_others)\n                            removes.append(local_local_initial)\n\n    # get rid of the bad ones\n    return paired_dict.drop(removes)\n\n\ndef find_star_pairs(star_records: pd.DataFrame, max_separation: float) -> pd.DataFrame:\n    \"\"\"\n    This identifies possible star pairs based on separation.\n\n    Stars are paired if their max separation is less that the input ``max_separation`` in degrees. This is done by\n    creating unit vectors for all of the stars and then doing a pair query using a KDTree.  The pairs are sorted based\n    on magnitude so that the first star in each pair is brighter.\n\n    The result of this function will be a dataframe where the first column \"a\" is the primary star and the second column\n    \"b\" is a set of stars that should be combined with \"a\".\n\n    Generally this is not used directly by the user.  Instead see :func:`build_catalogue` or script\n    :mod:`~.scripts.build_catalogue`.\n\n    :param star_records: The dataframe containing the stars that are to be paired\n    :param max_separation: The maximum separation in degrees between stars for them to be paired\n    :return: A dataframe specifying stars to pair together.\n    \"\"\"\n\n    # get the unit vectors\n    units = radec_to_unit(star_records.ra.values * DEG2RAD, star_records.dec.values * DEG2RAD).T\n\n    # build the kdtree\n    # noinspection PyArgumentList\n    tree = cKDTree(units, compact_nodes=False, balanced_tree=False)\n\n    # find the pairs.  Tell pycharm to stop complaining because numpy/scipy don't document right\n    # noinspection PyArgumentList,PyUnresolvedReferences\n    pairs = tree.query_pairs(np.sin(max_separation * np.pi / 360) * 2, output_type='ndarray')\n\n    # get the pairs\n    pairs = pd.DataFrame(star_records.index.values[pairs], columns=['a', 'b'])\n\n    # sort the pairs on magnitude\n    for pair in pairs.itertuples():\n\n        if float(star_records.loc[pair.a, \"mag\"]) > float(star_records.loc[pair.b, \"mag\"]):\n            pairs.loc[pair.Index, \"a\"] = pair.b\n            pairs.loc[pair.Index, \"b\"] = pair.a\n\n    # condense pairs so that stars aren't in multiple pairs\n    return _repair(star_records, pairs)\n\n\ndef _blend_stars(input_group: tuple, database_connection: sqlite3.Connection,\n                 index: int, limiting_mag: Real, reference_mag: Real) -> Optional[pd.Series]:\n    \"\"\"\n    This helper function computes a blended star from the input star indices.\n\n    This function queries the star records from the database for memory reasons (so that we can use multiprocessing).\n\n    The stars are blended into a single record with a combined magnitude, right ascension, declination, and proper\n    motion (distance is not considered).  This is based off of an internal note on blending stars that Sean Semper sent.\n\n    :param input_group: The group of stars to be blended\n    :param database_connection: The database connection to retrieve the star records from\n    :param index: The index of the group of stars that we're working on.  Purely for printing purposed\n    :param limiting_mag: The magnitude that the blended stars must reach for them to be included\n    :param reference_mag: The reference magnitude to use when blending the stars.\n    :return: A series with the blended star, or ``None`` if the limiting magnitude wasn't met\n    \"\"\"\n\n    # interpret the group\n    initial = input_group[0]\n    group = list(input_group[1])\n\n    start = time.time()\n\n    # all the ids we need to query\n    star_ids = [initial] + group\n    # the security risk is minimized here by calling int on all of the elements in the star_ids list\n    # its already minimal because a user should never be directly interacting with this function anyway\n    star_records = pd.read_sql('select * from stars where rnm in {}'.format(tuple(map(int, star_ids))),  # nosec\n                               database_connection, index_col='rnm')\n\n    # get the initial star from the dataframe\n    initial_star = star_records.loc[initial]\n    # get the rest of the stars from the dataframe\n    other_stars = star_records.loc[group]\n\n    # compute the weights for each star\n    initial_weight = 1 / (10 ** (0.4 * (initial_star.mag - reference_mag)))\n    other_weights = 1 / (10 ** (0.4 * (other_stars.mag.values - reference_mag)))\n\n    # determine the reference declination from the brightest star\n    if (initial_star.mag <= other_stars.mag).all():\n        ref_dec = np.cos(initial_star.dec*DEG2RAD)\n    else:\n        ref_dec = np.cos(other_stars.loc[other_stars.mag == other_stars.mag.min(), \"dec\"].values[0]*DEG2RAD)\n\n    # compute the combined magnitude\n    combined_mag = -2.5 * np.log10((10 ** (-0.4 * initial_star.mag) + 10 ** (-0.4 * other_stars.mag.values)).sum())\n\n    # if the blended star is too dim stop here\n    if combined_mag > limiting_mag:\n        return None\n\n    # make the Series to return\n    combined_star = initial_star.copy()\n    # set the blended magnitude\n    combined_star.mag = combined_mag\n    # update the RNM to be negative\n    combined_star.name *= -1\n\n    # compute the combined position\n    denominator = initial_weight + other_weights.sum()\n    combined_star.ra = (initial_weight * initial_star.ra * ref_dec +\n                        (other_weights * other_stars.ra.values * ref_dec).sum()) / denominator / ref_dec\n    combined_star.dec = (initial_weight * initial_star.dec +\n                         (other_weights * other_stars.dec.values).sum()) / denominator\n    combined_star.ra_proper_motion = ((initial_weight * initial_star.ra_proper_motion * ref_dec +\n                                      (other_weights * other_stars.ra_proper_motion.values * ref_dec).sum()) /\n                                      denominator / ref_dec)\n    combined_star.dec_proper_motion = ((initial_weight * initial_star.dec_proper_motion +\n                                        (other_weights * other_stars.dec_proper_motion.values).sum()) / denominator)\n\n    # give a status\n    print('Pair {} blended in {:.3f}'.format(index, time.time() - start))\n\n    return combined_star\n\n\ndef blend_stars(groups: pd.DataFrame, database_connection: sqlite3.Connection, limiting_mag: Real,\n                ref_mag: Real = 4) -> pd.DataFrame:\n    \"\"\"\n    Blends groups of stars together into a single \"apparent\" star as viewed by a camera.\n\n    Star magnitude, right ascension, declination, and proper motion are all blended in the final product.  The blending\n    is based off of an internal memo by Sean Semper.\n\n    The groups input should provide 2 columns, the first column \"a\" should provide the primary (brightest) star in each\n    group.  The second column \"b\" should provide a set of all of the stars that are to be blended to each other an \"a\".\n    This is what is returned by :func:`find_star_pairs`.  This function uses the database to retrieve the individual\n    star records for memory purposes.\n\n    The blended star is given an id that is the negative of the brightest star in the group.  The blended stars are\n    returned as a pandas dataframe.\n\n    Typically this is not used directly by the user.  Instead se :func:`build_catalogue` or script\n    :mod:`.scripts.build_catalogue`.\n\n    :param groups: The dataframe specifying the groups to blend\n    :param database_connection: The connection to the sqlite3 database to retrieve the stars from\n    :param limiting_mag: The limiting magnitude that blended stars must achieve for them to be included\n    :param ref_mag: The reference magnitude to use when blending the stars\n    :return: The dataframe of the blended apparent stars\n    \"\"\"\n\n    # get the number of groups we need to blend for reporting purposes\n    number_of_groups = len(groups)\n\n    # notify the user\n    print('{} stars to blend'.format(number_of_groups), flush=True)\n\n    # combine the stars.  Perhaps can use multiprocessing for this\n    combined_stars = list(starmap(_blend_stars,\n                                  zip(groups.iteritems(),\n                                      repeat(database_connection),\n                                      range(1, number_of_groups + 1),\n                                      repeat(limiting_mag),\n                                      repeat(ref_mag))))\n\n    # return the dataframe by concatenating the individual blended series.  This will ignore Nones\n    return pd.concat(combined_stars, axis=1).T\n\n\nclass GIANTCatalogue(Catalogue):\n    \"\"\"\n    This class provides access to the default GIANT star catalogue built from the UCAC4 and Tycho2 Catalogues.\n\n    This class is a fully functional catalogue for GIANT and can be used anywhere that GIANT expects a star catalogue.\n    As such, it implements the :attr:`include_proper_motion` to turn proper motion on or off as well as the method\n    :meth:`query_catalogue` which is how stars are queried into the GIANT format.  In addition, this catalogue provides\n    2 additional methods :meth:`get_ucac4_record` and :meth:`get_tycho2_record` to get the original record that was\n    used to create the GIANT catalogue record.  These methods aren't used anywhere by GIANT itself, but may be useful if\n    you are doing some advanced analysis.\n\n    To use this class simply initialize it, pointing to the file where the database is stored (if you are using one that\n    is different from the default).  If the catalogue file does not exist it will ask you if you want to build it, and\n    if you answer yes, it will dispatch to :func:`build_catalogue` (which takes a long time in most instances).  Once\n    the class is initialized, you can query stars from it using :meth:`query_catalogue` which will return a dataframe of\n    the star records with :attr:`.GIANT_COLUMNS` columns.\n    \"\"\"\n\n    def __init__(self, db_file: PATH = DEFAULT_CAT_FILE, include_proper_motion: bool = True):\n        \"\"\"\n        :param db_file: The file containing the sqlite3 database that the stars are stored in\n        :param include_proper_motion: A boolean flag specifying whether to apply proper motion when retrieving the stars\n        \"\"\"\n\n        super().__init__(include_proper_motion=include_proper_motion)\n\n        self.catalogue_path: Path = Path(db_file)\n        \"\"\"\n        The path to the catalogue file containing the database\n        \"\"\"\n\n        self._catalogue: Optional[sqlite3.Connection] = None\n        \"\"\"\n        The sqlite3 catalogue connection \n        \"\"\"\n\n        if db_file.exists():\n            try: \n                self._catalogue = sqlite3.connect(str(self.catalogue_path))\n                self._catalogue.execute(\"SELECT * FROM stars LIMIT 1\")\n            except (sqlite3.OperationalError, sqlite3.DatabaseError):\n                print(\"GIANT catalogue corrupted at {}\".format(db_file), flush=True)\n                user_response = input(\"Would you like to build the GIANT catalogue from the UCAC catalogue (y/n)?\\n\"\n                                      \"    WARNING: THIS MAY TAKE A LONG TIME AND WILL USE UP 600 MB OF SPACE!\\n    \")\n\n                if user_response[:1].lower() == 'y':\n                    build_catalogue(db_file)\n\n                    self._catalogue = sqlite3.connect(str(self.catalogue_path))\n\n                else:\n                    raise sqlite3.DatabaseError('The GIANT catalogue database file is corrupted')\n\n        else:\n            print(\"GIANT catalogue not found at {}\".format(db_file), flush=True)\n            user_response = input(\"Would you like to build the GIANT catalogue from the UCAC catalogue (y/n)?\\n\"\n                                  \"    WARNING: THIS MAY TAKE A LONG TIME AND WILL USE UP 600 MB OF SPACE!\\n    \")\n\n            if user_response[:1].lower() == 'y':\n                build_catalogue(db_file)\n\n                self._catalogue = sqlite3.connect(str(self.catalogue_path))\n\n            else:\n                raise FileNotFoundError('The GIANT catalogue database file cannot be found')\n\n    def __reduce__(self):\n        return self.__class__, (self.catalogue_path, self.include_proper_motion)\n\n    @property\n    def catalogue(self) -> sqlite3.Connection:\n        \"\"\"\n        This is a sqlite3 connection object which is used to read from the catalogue.\n\n        It should not be used externally unless you really know what you're doing...\n        \"\"\"\n\n        return self._catalogue\n\n    @catalogue.setter\n    def catalogue(self, err):\n        raise AttributeError('You cannot set the catalogue directly.  It is purely for internal use.\\n' +\n                             'If you really know what you are doing, you can set the catalogue file by accessing\\n' +\n                             'the _catalogue attribute, however this is highly warned against.')\n\n    @catalogue.deleter\n    def catalogue(self):\n        self._catalogue.close()\n\n    def query_catalogue(self, ids: Optional[ARRAY_LIKE] = None, min_ra: Real = 0, max_ra: Real = 360,\n                        min_dec: Real = -90, max_dec: Real = 90, min_mag: Real = -4, max_mag: Real = 20,\n                        search_center: Optional[ARRAY_LIKE] = None, search_radius: Optional[Real] = None,\n                        new_epoch: Optional[Union[datetime, Real]] = None) -> pd.DataFrame:\n        \"\"\"\n        This method queries stars from the catalogue that meet specified constraints and returns them as a DataFrame\n        with columns of :attr:`.GIANT_COLUMNS`.\n\n        Stars can either be queried by ID directly or by right ascension/declination/magnitude. You cannot filter using\n        both with this method.  If :attr:`apply_proper_motion` is ``True`` then this will shift the stars to the new\n        epoch input by the user (``new_epoch``) using proper motion.\n\n        :param ids: A sequence of star ids to retrieve from the catalogue.  What these ids are vary from catalogue to\n                    catalogue so see the catalogue documentation for details.\n        :param min_ra: The minimum ra bound to query stars from in degrees\n        :param max_ra: The maximum ra bound to query stars from in degrees\n        :param min_dec: The minimum declination to query stars from in degrees\n        :param max_dec: The maximum declination to query stars from in degrees\n        :param min_mag: The minimum magnitude to query stars from.  Recall that magnitude is inverse (so lower\n                        magnitude is a dimmer star)\n        :param max_mag: The maximum magnitude to query stars from.  Recall that magnitude is inverse (so higher\n                        magnitude is a dimmer star)\n        :param search_center: The center of a search cone as a ra/dec pair.\n        :param search_radius: The radius about the center of the search cone\n        :param new_epoch: The epoch to translate the stars to using proper motion if :attr:`apply_proper_motion` is\n                          turned on\n        :return: A Pandas dataframe with columns :attr:`GIANT_COLUMNS`.\n        \"\"\"\n\n        if ids is not None:\n            records = self.get_from_ids(ids)\n        else:\n\n            records = self.get_all_with_criteria(min_ra=min_ra, max_ra=max_ra, min_dec=min_dec, max_dec=max_dec,\n                                                 min_mag=min_mag, max_mag=max_mag,\n                                                 search_center=search_center, search_radius=search_radius)\n\n        if self.include_proper_motion and (new_epoch is not None):\n            apply_proper_motion(records, new_epoch, copy=False)\n\n        return records\n\n    def get_from_ids(self, ids: ARRAY_LIKE) -> pd.DataFrame:\n        \"\"\"\n        This method queries star records from the database based off of ID (``rnm`` in the database).\n\n        This can be used if you are interested in a particular set of stars.  The stars are returned in the GIANT\n        DataFrame format according the :attr:`.GIANT_COLUMNS`.\n\n        Note that this does not apply proper motion.  If you need to apply proper motion see :meth:`query_catalogue`\n\n        :param ids: The ids of the stars to retrieve as an iterable\n        :return: The dataframe of stars according to :attr:`.GIANT_COLUMNS`\n        \"\"\"\n\n        # map(int, ids) protects against sql injection\n        return pd.read_sql(f'select * from stars where rnm in {tuple(map(int, ids))}', self._catalogue,  # nosec\n                           index_col='rnm')\n\n    def get_all_with_criteria(self, min_ra: Real = 0, max_ra: Real = 360,\n                              min_dec: Real = -90, max_dec: Real = 90, min_mag: Real = -4, max_mag: Real = 20,\n                              search_center: Optional[ARRAY_LIKE] = None,\n                              search_radius: Optional[Real] = None) -> pd.DataFrame:\n        \"\"\"\n        This method queries star records from the database based off of location and magnitude requirements.\n\n        Note that this does not apply proper motion.  If you need to apply proper motion see :meth:`query_catalogue`.\n\n        :param min_ra: The minimum ra bound to query stars from in degrees\n        :param max_ra: The maximum ra bound to query stars from in degrees\n        :param min_dec: The minimum declination to query stars from in degrees\n        :param max_dec: The maximum declination to query stars from in degrees\n        :param min_mag: The minimum magnitude to query stars from.  Recall that magnitude is inverse (so lower\n                        magnitude is a dimmer star)\n        :param max_mag: The maximum magnitude to query stars from.  Recall that magnitude is inverse (so higher\n                        magnitude is a dimmer star)\n        :param search_center: The center of a search cone as a ra/dec pair.\n        :param search_radius: The radius about the center of the search cone\n        :return: A Pandas dataframe with columns :attr:`GIANT_COLUMNS`.\n        \"\"\"\n\n        # make sure everything is a float (a) to validate input and (b) to protect against sql injection attacks\n        min_ra = float(min_ra)\n        max_ra = float(max_ra)\n        min_dec = float(min_dec)\n        max_dec = float(max_dec)\n        min_mag = float(min_mag)\n        max_mag = float(max_mag)\n\n        # determine what the rectangular bounds should look like for the search center/radius\n        if search_center is not None:\n            min_ra = search_center[0] - search_radius\n            max_ra = search_center[0] + search_radius\n\n            min_dec = search_center[1] - search_radius\n            max_dec = search_center[1] + search_radius\n\n        # adjust for if we are at a corner case\n        if min_dec < -90:\n            min_dec = -90\n            min_ra = 0\n            max_ra = 360\n\n        elif max_dec > 90:\n            max_dec = 90\n            min_ra = 0\n            max_ra = 360\n\n        # determine what the query should look like based on the rectangular bounds\n        # the security risk is non-existent here due to calling float on all of the values before they are used as\n        # parameters\n        if min_ra < 0:\n            query = ('SELECT * FROM stars WHERE ((ra >= {} AND ra <= {}) OR (ra >= {} AND ra <= {})) '   # nosec\n                     'AND dec >= {} AND dec <= {} AND mag <={} ' \n                     'AND mag >= {}'.format(min_ra + 360, 360, 0, max_ra, min_dec, max_dec, max_mag, min_mag))\n\n        elif max_ra > 360:\n            query = ('SELECT * FROM stars WHERE ((ra >= {} AND ra <= {}) OR (ra >= {} AND ra <= {})) '   # nosec\n                     'AND dec >= {} AND dec <= {} AND mag <={} ' \n                     'AND mag >= {}'.format(min_ra, 360, 0, max_ra - 360, min_dec, max_dec, max_mag, min_mag))\n\n        else:\n            query = ('SELECT * FROM stars WHERE ra >= {} AND ra <= {} '  # nosec\n                     'AND dec >= {} AND dec <= {} AND mag <={} '\n                     'AND mag >= {}'.format(min_ra, max_ra, min_dec, max_dec, max_mag, min_mag))\n\n        # query the results from the database\n        records = pd.read_sql(query, self.catalogue, index_col='rnm')\n\n        # now do the real radial search if it is needed\n        if search_center is not None:\n            records = records.loc[radec_distance(records.ra * DEG2RAD, records.dec * DEG2RAD,\n                                                 search_center[0] * DEG2RAD, search_center[1] * DEG2RAD) <=\n                                  (search_radius * DEG2RAD)]\n        if \"epoch\" not in records.columns:\n            records = records.assign(epoch=2000.0)\n\n        return records\n\n    @staticmethod\n    def get_tycho2_record(stars: pd.DataFrame, ucac_directory: Optional[PATH] = None,\n                          tycho_directory: Optional[PATH] = None) -> pd.DataFrame:\n        \"\"\"\n        This method can be used to retrieve the corresponding full (not GIANT) Tycho 2 records for a set of GIANT\n        catalogue stars.\n\n        This method requires that the UCAC4 and Tycho 2 catalogues be available, and will request to download them if\n        they are not available (which takes a long time).  For a description of the columns refer to the Tycho 2\n        documentation.\n\n        Note that these records are not directly usable for GIANT, therefore only use this if you need the raw records\n        yourself.\n\n        Any stars that are not available in the Tycho 2 catalogue (blended stars or stars that are too dim) will be\n        included in the output dataframe but with NANs for all columns\n\n        :param stars: The stars to retrieve the Tycho records for\n        :param ucac_directory: The directory containing the UCAC4 star catalogue files (or None to use the default)\n        :param tycho_directory: The directory containing the Tycho 2 star catalogue files (or None to use the default)\n        :return: The raw Tycho 2 records\n        \"\"\"\n\n        from giant.catalogues.ucac import UCAC4\n        from giant.catalogues.tycho import Tycho2\n\n        ucac = UCAC4(directory=ucac_directory)\n\n        tycho = Tycho2(directory=tycho_directory)\n\n        return ucac.cross_ref_tycho(stars.loc[:, ['zone', 'rnz']], tycho_cat=tycho)\n\n    @staticmethod\n    def get_ucac4_record(stars: pd.DataFrame, ucac_directory: Optional[PATH] = None) -> pd.DataFrame:\n        \"\"\"\n        This method can be used to retrieve the corresponding full (not GIANT) UCAC4 records for a set of GIANT\n        catalogue stars.\n\n        This method requires that the UCAC4 catalogue be available, and will request to download it if it is not (which\n        takes a long time).  For a description of the columns refer to the UCAC4 documentation.\n\n        Note that these records are not directly usable for GIANT, therefore only use this if you need the raw records\n        yourself.\n\n        Any stars that are not available in the UCAC4 catalogue (blended stars) will be included in the output dataframe\n        but with NANs for all columns\n\n        :param stars: The UCAC4 records for the stars\n        :param ucac_directory: The directory containing the UCAC4 star catalogue files (or None to use the default)\n        :return: The raw UCAC4 records\n        \"\"\"\n\n        from giant.catalogues.ucac import UCAC4\n\n        ucac = UCAC4(directory=ucac_directory)\n\n        return ucac.query_catalogue_raw(ids=stars.loc[:, ['zone', 'rnz']].itertuples(False), generator=False)\n", "meta": {"hexsha": "8b131b4173c92f17887ddea7e9548116dd576132", "size": 38003, "ext": "py", "lang": "Python", "max_stars_repo_path": "giant/catalogues/giant_catalogue.py", "max_stars_repo_name": "nasa/giant", "max_stars_repo_head_hexsha": "1e939272d9a0ca533b4da400d132f854520f3adc", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-09-10T14:29:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T20:15:01.000Z", "max_issues_repo_path": "giant/catalogues/giant_catalogue.py", "max_issues_repo_name": "nasa/giant", "max_issues_repo_head_hexsha": "1e939272d9a0ca533b4da400d132f854520f3adc", "max_issues_repo_licenses": ["NASA-1.3"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "giant/catalogues/giant_catalogue.py", "max_forks_repo_name": "nasa/giant", "max_forks_repo_head_hexsha": "1e939272d9a0ca533b4da400d132f854520f3adc", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-10-01T18:39:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T08:53:08.000Z", "avg_line_length": 50.4687915007, "max_line_length": 120, "alphanum_fraction": 0.6548956661, "include": true, "reason": "import numpy,from scipy", "num_tokens": 8251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.27825679968760103, "lm_q1q2_score": 0.1532102434182571}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# pack and unpack with mask function from: https://github.com/kevinkwl/AoAReader/blob/master/aoareader/AoAReader.py\n\n# @Time    : 2017/12/6 11:13\n# @From    : PyCharm\n# @File    : hiso\n# @Author  : Liujie Zhang\n# @Email   : liujiezhangbupt@gmail.com\nimport json\nimport pickle\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nfrom gensim.models import Word2Vec\nfrom torch.nn.utils.rnn import pad_packed_sequence as unpack\nfrom torch.nn.utils.rnn import pack_padded_sequence as pack\n\nfrom utils.attention import Attention, cudaWrapper\n\n\ndef sort_batch(data, seq_len):\n    sorted_seq_len, sorted_idx = torch.sort(seq_len, dim=0, descending=True)\n    sorted_data = data[sorted_idx.data]\n    _, reverse_idx = torch.sort(sorted_idx, dim=0, descending=False)\n\n    return sorted_data, cudaWrapper(sorted_seq_len), cudaWrapper(reverse_idx)\n\n\ndef create_mask(seq_lens):\n    mask = torch.zeros(seq_lens.data.size(0), torch.max(seq_lens.data))\n    for i, seq_len in enumerate(seq_lens.data):\n        mask[i][:seq_len] = 1\n\n    return cudaWrapper(mask.float())\n\n\ndef getSeqLength(input, return_variable=True):\n    seq_len = torch.LongTensor([torch.nonzero(input.data[i]).size(0) for i in range(input.data.size(0))])\n    if return_variable:\n        seq_len = Variable(seq_len)\n    return cudaWrapper(seq_len)\n\n\nclass HISO(nn.Module):\n    def __init__(self, opt):\n        super(HISO, self).__init__()\n\n        self.model_name = 'HISO'\n        self.opt = opt\n        # Embedding Layer\n        self.wd_embed = nn.Embedding(opt.voc_size, opt.embed_dim)\n        self.pos_embed = nn.Embedding(opt.pos_size, opt.embed_dim)\n        self.initEmbedWeight()\n        # Bi-GRU Layer\n        self.wd_bi_gru = nn.GRU(input_size = opt.embed_dim,\n                hidden_size = opt.ghid_size,\n                num_layers = opt.glayer,\n                bias = True,\n                batch_first = True,\n                dropout = 0.5,\n                bidirectional = True\n                )\n        self.attention = Attention(opt)\n\n        # Bi-GRU Layer\n        self.pos_bi_gru = nn.GRU(input_size = opt.embed_dim,\n                hidden_size = opt.ghid_size,\n                num_layers = opt.glayer,\n                bias = True, \n                batch_first = True,\n                dropout = 0.5,\n                bidirectional = True\n                )\n\n        # output from pos hidden layer to predict middle labels\n        pos_hidden_size = opt.ghid_size * opt.glayer\n        self.pos_fc = nn.Sequential(\n                nn.BatchNorm1d(pos_hidden_size),\n                nn.ReLU(inplace=True),\n                nn.Linear(pos_hidden_size, opt.auxiliary_labels),\n                nn.Sigmoid()\n                )\n        # predict final labels\n        combine_size = opt.ghid_size * opt.glayer + opt.auxiliary_labels\n        self.fc = nn.Sequential(\n                nn.Linear(combine_size, 128),\n                nn.BatchNorm1d(128),\n                nn.ReLU(inplace = True),\n                nn.Linear(128, opt.label_dim),\n                nn.Sigmoid()\n                )\n        self.softmax = nn.Softmax(dim=1)\n\n    def initEmbedWeight(self):\n        '''\n        init embedding layer from random|word2vec|sswe\n        '''\n        if 'w2v' in self.opt.init_embed:\n            weights = Word2Vec.load('../docs/data/w2v_word_100d_5win_5min')\n            voc = json.load(open('../docs/data/voc.json','r'))['voc']\n            print(weights[list(voc.keys())[3]])\n\n            word_weight = np.zeros((len(voc),self.opt.embed_dim))\n            for wd,idx in voc.items():\n                vec = weights[wd] if wd in weights else np.random.randn(self.opt.embed_dim)\n                word_weight[idx] = vec\n            # print(word_weight[3])\n            self.wd_embed.weight.data.copy_(torch.from_numpy(word_weight))\n\n            weights = Word2Vec.load('../docs/data/w2v_pos_100d_5win_5min')\n            pos = json.load(open('../docs/data/pos.json','r'))['voc']\n            pos_weight = np.zeros((len(pos),self.opt.embed_dim))\n            for ps,idx in pos.items():\n                vec = weights[ps] if ps in weights else np.random.randn(self.opt.embed_dim)\n                pos_weight[idx] = vec\n            self.pos_embed.weight.data.copy_(torch.from_numpy(pos_weight))\n\n        elif 'sswe' in self.opt.init_embed:\n            word_weight = pickle.load(open('../docs/model/%s'% self.opt.embed_path,'rb'))\n            self.wd_embed.weight.data.copy_(torch.from_numpy(word_weight))\n        # random default\n\n\n    def forward(self, wd, pos):\n        wd_len, pos_len = getSeqLength(wd), getSeqLength(pos)\n        wd_mask, pos_mask = create_mask(wd_len), create_mask(pos_len)\n\n        s_wd, s_wd_len, reverse_wd_idx = sort_batch(wd, wd_len)\n        s_pos, s_pos_len, reverse_pos_idx = sort_batch(pos, pos_len)\n\n        wd_embedding = pack(self.wd_embed(s_wd), list(s_wd_len.data), batch_first=True)\n        pos_embedding = pack(self.pos_embed(s_pos), list(s_pos_len.data), batch_first=True)\n\n        # Bi-GRU\n        wd_out, _ = self.wd_bi_gru(wd_embedding)\n        pos_out, _ = self.pos_bi_gru(pos_embedding)\n\n        wd_out, _ = unpack(wd_out, batch_first=True)\n        pos_out,_ = unpack(pos_out, batch_first=True)\n\n        wd_out = wd_out[reverse_wd_idx.data]\n        pos_out = pos_out[reverse_pos_idx.data]\n\n        # attention\n        if 'word' in self.opt.attention:\n            wd_atten = self.attention(wd_out, weight=wd_out, mask=wd_mask)\n        elif 'pos' in self.opt.attention:\n            wd_atten = self.attention(wd_out, weight=pos_out, mask=pos_mask)\n        else:\n            wd_atten = wd_out[:,-1,:]\n        \n        # pos_out to predict auxiliary label\n        auxi_probs = self.pos_fc(pos_out[:, -1, :].contiguous())\n\n        # combine wd_out with auxi_probs as feature\n        combine_feature = torch.cat((wd_atten, auxi_probs), dim=1)\n        logits = self.fc(combine_feature)\n\n        return logits, auxi_probs\n\n\n    def init_hidden(self, batch_size):\n        h0 = torch.zeros(self.opt.glayer, batch_size, self.opt.ghid_size)\n        return Variable(h0)\n\n\n\nclass HisoLoss(nn.Module):\n    def __init__(self, opt):\n        super(HisoLoss, self).__init__()\n        self.opt = opt\n        # self.reconstruction_loss = 0 // todo\n\n    def forward(self,auxi_probs, auxi_labels, final_probs, final_labels):\n        # calcu auxi_labels margin loss\n        self.auxi_loss = self.marginLoss(auxi_probs, auxi_labels)\n\n        # calcu final_labels margin loss\n        self.final_loss = self.marginLoss(final_probs, final_labels)\n        \n        self.loss = self.opt.loss_alpha * self.auxi_loss + self.final_loss\n        return self.loss\n\n    def marginLoss(self, probs, labels):\n        \n        left = F.relu(self.opt.max_margin - probs, inplace=True)**2\n        right = F.relu(probs - self.opt.min_margin, inplace=True)**2\n\n        margin_loss = labels * left + (1. - labels) * right\n        return margin_loss.sum() / labels.size(0)\n\n\nclass opt(object):\n    voc_size = 100\n    pos_size = 57\n    embed_dim = 20\n    ghid_size = 3\n    seq_len = 4\n    glayer = 2\n    auxiliary_labels = 3\n    label_dim = 6\n    max_margin = 0.9\n    min_margin = 0.1\n    embed_path='lookup_01-22-19:10'\n    init_embed='randn'\n    loss_alpha=1e-2\n    attention='word'\n\n\nif __name__ == '__main__':\n    import torch.optim as optim\n\n    wd = Variable(torch.LongTensor([[2,45,75,0], [5,54,76,23]]))\n    pos = Variable(torch.LongTensor([[3,45,8,0], [13,56,7,43]]))\n    labels = Variable(torch.FloatTensor([[1,0,0,1,0,0],[0,0,1,0,1,0]]))\n    auxi = Variable(torch.FloatTensor([[1,0,0],[0,1,0]]))\n\n    model = HISO(opt)\n    Loss = HisoLoss(opt)\n    op = optim.SGD(model.parameters(),lr=0.1)\n    model.train()\n    for i in range(100):\n        final_probs,auxi_probs = model(wd, pos)\n        loss = Loss(auxi_probs, auxi, final_probs, labels)\n        op.zero_grad()\n        loss.backward()\n        op.step()\n        print(loss.data[0])\n", "meta": {"hexsha": "bc19c7c36e80ebb01515ca00786d9eaf8c327368", "size": 7981, "ext": "py", "lang": "Python", "max_stars_repo_path": "HMIO/utils/hiso.py", "max_stars_repo_name": "Aurelius84/SPWE", "max_stars_repo_head_hexsha": "5f9fc5495e879b5272c118271a69c5adad4ba260", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-05-16T07:43:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T08:47:41.000Z", "max_issues_repo_path": "HMIO/utils/hiso.py", "max_issues_repo_name": "KillersDeath/SPWE", "max_issues_repo_head_hexsha": "5f9fc5495e879b5272c118271a69c5adad4ba260", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-06T10:00:18.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-14T02:05:02.000Z", "max_forks_repo_path": "HMIO/utils/hiso.py", "max_forks_repo_name": "Aurelius84/SPWE", "max_forks_repo_head_hexsha": "5f9fc5495e879b5272c118271a69c5adad4ba260", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-12-29T16:08:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-06T13:56:58.000Z", "avg_line_length": 34.2532188841, "max_line_length": 115, "alphanum_fraction": 0.6157123168, "include": true, "reason": "import numpy", "num_tokens": 2046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.30404168757891037, "lm_q1q2_score": 0.15320848246908783}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n# -*- coding: utf-8 -*-\n\"\"\"\ndesimodel.inputs.focalplane_sync\n===================================\n\nTools for checking and synchronizing focalplane state to online system.\n\"\"\"\nimport os\nimport datetime\nimport shutil\nimport gzip\nimport re\n\nimport subprocess as sp\n\nimport ast\n\nimport json\nimport yaml\n\nimport numpy as np\n\nfrom astropy.table import Table, Column\n\nfrom desiutil.log import get_logger\n\nfrom ..io import datadir, findfile, load_focalplane\n\nfrom .focalplane_utils import (\n    create_tables,\n    device_loc_to_type,\n    load_petal_fiber_map,\n    collision_to_segments,\n    exclusions_equal,\n    valid_states,\n    device_compare,\n    device_printdiff,\n    update_exclusions,\n    restricted_positioner_phi,\n    hash_exclusion,\n)\n\n\ndef load_fp_calibs(path):\n    \"\"\"Load data dumped from the online system.\"\"\"\n    fpcal = Table.read(path, format=\"ascii.ecsv\")\n    return fpcal\n\n\n# Rotation matrices.  These few lines of code are copied from desimeter,\n# since it is the only thing that is needed from that package and there\n# is nothing even desi-specific here.\n\n\ndef Rx(angle):  # all in radians\n    Rx = np.array(\n        [\n            [1.0, 0.0, 0.0],\n            [0.0, np.cos(angle), -np.sin(angle)],\n            [0.0, np.sin(angle), np.cos(angle)],\n        ]\n    )\n    return Rx\n\n\ndef Ry(angle):  # all in radians\n    Ry = np.array(\n        [\n            [np.cos(angle), 0.0, np.sin(angle)],\n            [0.0, 1.0, 0.0],\n            [-np.sin(angle), 0.0, np.cos(angle)],\n        ]\n    )\n    return Ry\n\n\ndef Rz(angle):  # all in radians\n    Rz = np.array(\n        [\n            [np.cos(angle), -np.sin(angle), 0.0],\n            [np.sin(angle), np.cos(angle), 0.0],\n            [0.0, 0.0, 1.0],\n        ]\n    )\n    return Rz\n\n\ndef Rxyz(alpha, beta, gamma):  # yaw-pitch-roll system, all in radians\n    return Rz(gamma) @ Ry(beta) @ Rx(alpha)  # @ is matrix multiplication\n\n\ndef convert_fp_calibs(fpcal, sim=False):\n    \"\"\"Convert the online system information.\n\n    This returns a tuple containing the focalplane, the current state, and the set of\n    unique exclusion polygons found in the file.\n\n    Args:\n        fpcal (Table):  The table loaded from a dump from the online system.\n        sim (bool):  If True, clear all transient state issues and set hardware\n            to be as \"good as possible\", for use in simulations.\n\n    Returns:\n        (tuple):  The (focalplane, state, exclusions, time string) loaded from\n            the cal file.\n\n    \"\"\"\n    # Parse the calibration time\n    cal_time_str = fpcal.meta[\"DATE_RETRIEVED\"]\n    cal_time = datetime.datetime.strptime(cal_time_str, \"%Y-%m-%dT%H:%M:%S%z\")\n\n    state_time_str = cal_time.isoformat(timespec=\"seconds\")\n\n    # Parse other metadata\n\n    eo_phi = fpcal.meta[\"Eo_phi\"]\n    eo_radius = fpcal.meta[\"Eo_radius_with_margin\"]\n    alignments = fpcal.meta[\"PETAL_ALIGNMENTS\"]\n\n    # Get the default exclusion polygons for theta, phi, GFA, and petal\n    # boundaries\n\n    excl = dict()\n\n    ktheta_str = fpcal.meta[\"general_keepout_T\"]\n\n    ktheta_raw = np.transpose(\n        np.array(ast.literal_eval(fpcal.meta[\"general_keepout_T\"]))\n    )\n    kphi_raw = np.transpose(np.array(ast.literal_eval(fpcal.meta[\"general_keepout_P\"])))\n    kpetal_raw = np.transpose(np.array(ast.literal_eval(fpcal.meta[\"keepout_PTL\"])))\n    kgfa_raw = np.transpose(np.array(ast.literal_eval(fpcal.meta[\"keepout_GFA\"])))\n\n    kp = dict()\n    kp[\"theta\"] = dict()\n    kp[\"theta\"][\"segments\"] = collision_to_segments(ktheta_raw)\n    kp[\"theta\"][\"circles\"] = list()\n\n    kp[\"phi\"] = dict()\n    kp[\"phi\"][\"segments\"] = collision_to_segments(kphi_raw)\n    kp[\"phi\"][\"circles\"] = list()\n\n    kp[\"petal\"] = dict()\n    kp[\"petal\"][\"segments\"] = collision_to_segments(kpetal_raw)\n    kp[\"petal\"][\"circles\"] = list()\n\n    kp[\"gfa\"] = dict()\n    kp[\"gfa\"][\"segments\"] = collision_to_segments(kgfa_raw)\n    kp[\"gfa\"][\"circles\"] = list()\n\n    excl[\"default\"] = kp\n\n    # Also make a set of exclusions for \"retracted\" positioners.  In this case place\n    # a circle at the the center of the theta axis.\n\n    retrct = dict(excl[\"default\"])\n    retrct[\"theta\"][\"segments\"] = list()\n    retrct[\"theta\"][\"circles\"] = [[[0.0, 0.0], eo_radius]]\n    excl[\"retracted\"] = retrct\n\n    # Get the fiber map from device location to spectrographs.\n    fmap = load_petal_fiber_map()\n\n    # Build the transformation information for each petal alignment\n    petal_rot = dict()\n    petal_trans = dict()\n    for petal_id, align in alignments.items():\n        petal_rot[petal_id] = Rxyz(align[\"alpha\"], align[\"beta\"], align[\"gamma\"])\n        petal_trans[petal_id] = np.array([align[\"Tx\"], align[\"Ty\"], align[\"Tz\"]])\n\n    n_rows = len(fpcal)\n\n    fp, state = create_tables(n_rows)\n\n    # We only want to track the POS_P and POS_T values for positioners which are\n    # non-functional (stuck) or have a broken fiber, since these are the positioners\n    # we cannot move.\n    stuck_or_broken = valid_states[\"BROKEN\"] | valid_states[\"STUCK\"]\n\n    kindx = 0\n\n    for r in range(n_rows):\n        d = fpcal[r]\n        # First set the focalplane properties\n        fp[\"PETAL\"][r] = d[\"PETAL_LOC\"]\n        fp[\"PETAL_ID\"][r] = d[\"PETAL_ID\"]\n        fp[\"DEVICE\"][r] = d[\"DEVICE_LOC\"]\n        fp[\"DEVICE_ID\"][r] = d[\"POS_ID\"]\n        fp[\"LOCATION\"][r] = d[\"PETAL_LOC\"] * 1000 + d[\"DEVICE_LOC\"]\n        fp[\"DEVICE_TYPE\"][r] = device_loc_to_type(fp[\"DEVICE\"][r])\n        fp[\"SLITBLOCK\"][r] = -1\n        fp[\"BLOCKFIBER\"][r] = -1\n        fp[\"CABLE\"][r] = -1\n        fp[\"CONDUIT\"][r] = \"NA\"\n        fp[\"FWHM\"][r] = 0.0\n        fp[\"FRD\"][r] = 0.0\n        fp[\"ABS\"][r] = 0.0\n        if d[\"PETAL_ID\"] in fmap:\n            # We have some information about the device to fiber mapping.\n            if d[\"DEVICE_LOC\"] in fmap[d[\"PETAL_ID\"]]:\n                # This is a POS or ETC device\n                fp[\"SLITBLOCK\"][r] = fmap[d[\"PETAL_ID\"]][d[\"DEVICE_LOC\"]][\"SLITBLOCK\"]\n                fp[\"BLOCKFIBER\"][r] = fmap[d[\"PETAL_ID\"]][d[\"DEVICE_LOC\"]][\"BLOCKFIBER\"]\n                fp[\"CABLE\"][r] = fmap[d[\"PETAL_ID\"]][d[\"DEVICE_LOC\"]][\"CABLE\"]\n                fp[\"CONDUIT\"][r] = fmap[d[\"PETAL_ID\"]][d[\"DEVICE_LOC\"]][\"CONDUIT\"]\n                fp[\"FWHM\"][r] = fmap[d[\"PETAL_ID\"]][d[\"DEVICE_LOC\"]][\"FWHM\"]\n                fp[\"FRD\"][r] = fmap[d[\"PETAL_ID\"]][d[\"DEVICE_LOC\"]][\"FRD\"]\n                fp[\"ABS\"][r] = fmap[d[\"PETAL_ID\"]][d[\"DEVICE_LOC\"]][\"ABS\"]\n        fp[\"LENGTH_R1\"][r] = d[\"LENGTH_R1\"]\n        fp[\"LENGTH_R2\"][r] = d[\"LENGTH_R2\"]\n        fp[\"OFFSET_X\"][r] = d[\"OFFSET_X_CS5\"]\n        fp[\"OFFSET_Y\"][r] = d[\"OFFSET_Y_CS5\"]\n        fp[\"OFFSET_P\"][r] = d[\"OFFSET_P\"]\n\n        # The OFFSET_T angle is in petal coordinates.  We express this in global\n        # coordinates by transforming 2 points and computing the angle from that.\n\n        prot = petal_rot[d[\"PETAL_ID\"]]\n        ptrans = petal_trans[d[\"PETAL_ID\"]]\n        offset_pt_rad = np.radians(d[\"OFFSET_T\"])\n        offset_pt_pnts = np.array(\n            [\n                [d[\"OFFSET_X_CS5\"], d[\"OFFSET_Y_CS5\"], 0.0],\n                [\n                    3.0 * np.cos(offset_pt_rad) + d[\"OFFSET_X_CS5\"],\n                    3.0 * np.sin(offset_pt_rad) + d[\"OFFSET_Y_CS5\"],\n                    0.0,\n                ],\n            ]\n        )\n        offset_fp_pnts = prot.dot(offset_pt_pnts.T).T + np.tile(ptrans, 2).reshape(\n            (2, -1)\n        )\n        offset_fp_rad = np.arctan2(\n            offset_fp_pnts[1, 1] - offset_fp_pnts[0, 1],\n            offset_fp_pnts[1, 0] - offset_fp_pnts[0, 0],\n        )\n        offset_fp_deg = np.degrees(offset_fp_rad)\n        if offset_fp_deg < -180.0:\n            offset_fp_deg += 360.0\n        if offset_fp_deg > 180.0:\n            offset_fp_deg -= 360.0\n\n        # # Sanity check that the alignment-transformed offset is \"close\" to the\n        # # expected value.\n        # petalrot_check = (float(7 + fp[\"PETAL\"][r]) * 36.0) % 360.0\n        # petalrot_check += d[\"OFFSET_T\"]\n        # if petalrot_check < -180.0:\n        #     petalrot_check += 360.0\n        # if petalrot_check > 180.0:\n        #     petalrot_check -= 360.0\n        # print(\n        #     \"device {}, petal {}, offset_t = {}, check = {}\".format(\n        #         fp[\"DEVICE\"][r], fp[\"PETAL\"][r], offset_fp_deg, petalrot_check\n        #     ),\n        #     flush=True,\n        # )\n\n        fp[\"OFFSET_T\"][r] = offset_fp_deg\n\n        # Set the FIBER\n        fp[\"FIBER\"][r] = -1\n        if fp[\"SLITBLOCK\"][r] >= 0:\n            fp[\"FIBER\"][r] = (\n                fp[\"PETAL\"][r] * 500 + fp[\"SLITBLOCK\"][r] * 25 + fp[\"BLOCKFIBER\"][r]\n            )\n\n        # Handle the keepout polygons for this device.  Every row specifies a keepout\n        # even if many are close to identical.  Here we build up a dictionary of unique\n        # keepouts and find the one to use for this positioner.\n\n        dktheta = np.transpose(np.array(ast.literal_eval(d[\"KEEPOUT_T\"])))\n        dpolytheta = dict()\n        dpolytheta[\"circles\"] = list()\n        dpolytheta[\"segments\"] = collision_to_segments(dktheta)\n\n        dkphi = np.transpose(np.array(ast.literal_eval(d[\"KEEPOUT_P\"])))\n        dpolyphi = dict()\n        dpolyphi[\"circles\"] = list()\n        dpolyphi[\"segments\"] = collision_to_segments(dkphi)\n\n        kp = dict(excl[\"default\"])\n        kp[\"theta\"] = dpolytheta\n        kp[\"phi\"] = dpolyphi\n        pname = hash_exclusion(kp)[:16]\n\n        if pname not in excl:\n            excl[pname] = kp\n\n        state[\"EXCLUSION\"][r] = pname\n\n        # Now set rest of the state table\n\n        state[\"TIME\"][r] = state_time_str\n        state[\"LOCATION\"][r] = d[\"PETAL_LOC\"] * 1000 + d[\"DEVICE_LOC\"]\n\n        # Starting point is \"good\" with nominal MIN_P\n        state[\"STATE\"][r] = valid_states[\"OK\"]\n        state[\"MIN_P\"][r] = d[\"MIN_P\"]\n\n        # Even if we are simulating, we want to mark both broken fibers and\n        # non-movable positioners.\n        if not d[\"FIBER_INTACT\"]:\n            state[\"STATE\"][r] |= valid_states[\"BROKEN\"]\n        if d[\"DEVICE_CLASSIFIED_NONFUNCTIONAL\"]:\n            state[\"STATE\"][r] |= valid_states[\"STUCK\"]\n\n        if not sim:\n            # We want to also check for retracted positioners\n            if d[\"CLASSIFIED_AS_RETRACTED\"]:\n                # This positioner is retracted.  Set the exclusion to the retracted\n                # one and also limit the phi angle range.\n                state[\"STATE\"][r] |= valid_states[\"RESTRICT\"]\n                state[\"EXCLUSION\"][r] = \"retracted\"\n                # The focalplane cal information defines the Eo_Phi angle to be the\n                # minimum Phi angle relative to the coordinate axis, not the offset.\n                # So to get MIN_P we must subtract the offset.\n                state[\"MIN_P\"][r] = eo_phi - d[\"OFFSET_P\"]\n\n        # The other positioner angles in the state are just the same as nominal\n        state[\"MAX_P\"][r] = d[\"MAX_P\"]\n        state[\"MIN_T\"][r] = d[\"MIN_T\"]\n        state[\"MAX_T\"][r] = d[\"MAX_T\"]\n        # If the device is not movable, track its current estimated location.\n        if state[\"STATE\"][r] & stuck_or_broken:\n            state[\"POS_P\"][r] = d[\"POS_P\"]\n            state[\"POS_T\"][r] = d[\"POS_T\"]\n        else:\n            state[\"POS_P\"][r] = 0.0\n            state[\"POS_T\"][r] = 0.0\n\n    return (fp, state, excl, state_time_str)\n\n\ndef create_from_calibs(\n    calib_file,\n    out_dir=None,\n    reset=False,\n    sim_good=False,\n    commit=False,\n    test=False,\n    fibermaps=None,\n):\n    \"\"\"Construct a DESI focalplane from a calibration dump.\n\n    This uses a dump from the online system and compares it to the current\n    latest focalplane model and state.\n\n    Args:\n        calib_file (str):  Path to the calibration dump.\n        out_dir (str):  Override the output directory for testing.  Default writes to\n            $DESIMODEL/data/focalplane/\n        reset (bool):  If True, ignore the current focalplane model and\n            create a new model from this calibration dump.  Default compares\n            the new focalplane to the old and looks for changes in device\n            state.  These changes are appended to the existing log.\n        sim_good (bool):  If True, clear all transient state issues and set hardware\n            to be as \"good as possible\", for use in simulations.\n        commit (bool):  If True, attempt to commit the result.\n        test (bool):  If True, perform all operations but do not update any files.\n        fibermaps (list):  Override list of tuples (DocDB number,\n            DocDB version, DocDB csv file) of where to find the petal mapping\n            files.\n\n    Returns:\n        None\n\n    \"\"\"\n    log = get_logger()\n\n    if out_dir is None:\n        out_dir = os.path.join(datadir(), \"focalplane\")\n        test_svn = os.path.join(datadir(), \".svn\")\n        if not os.path.isdir(test_svn):\n            test_svn = os.path.join(os.path.dirname(datadir()), \".svn\")\n            if not os.path.isdir(test_svn):\n                msg = \"Output data directory:  {}\".format(out_dir)\n                msg += \"\\nis not inside an svn checkout.  You will not be able to\"\n                msg += \"\\ncommit these changes without copying them to a checkout.\"\n                log.warning(msg)\n    else:\n        log.warning(\"Using debug output directory %s\", out_dir)\n        log.warning(\"Files cannot be used until placed in $DESIMODEL/data/focalplane\")\n\n    # Get the model from the calib file\n    log.info(\"Loading calibration dump from %s ...\", calib_file)\n    fpcal = load_fp_calibs(calib_file)\n\n    log.info(\"Converting calibration format ...\")\n    fp, state, excl, date_str = convert_fp_calibs(fpcal, sim=sim_good)\n\n    log.info(\"Calibration data retrieval date = %s\", date_str)\n\n    if reset:\n        # Ignore any previous focalplane info and dump out what we have\n\n        log.info(\"Writing new focalplane model- ignoring previous ones...\")\n        out_fp_file = os.path.join(out_dir, \"desi-focalplane_{}.ecsv\".format(date_str))\n        out_excl_file = os.path.join(\n            out_dir, \"desi-exclusion_{}.json.gz\".format(date_str)\n        )\n        out_state_file = os.path.join(out_dir, \"desi-state_{}.ecsv\".format(date_str))\n\n        log.info(\"  Output focalplane:  %s\", out_fp_file)\n        log.info(\"  Output state     :  %s\", out_state_file)\n        log.info(\"  Output exclusions:  %s\", out_excl_file)\n\n        if test:\n            log.info(\"Running with test==True, skipping file writes.\")\n            return\n\n        fp.write(out_fp_file, format=\"ascii.ecsv\", overwrite=True)\n\n        state.write(out_state_file, format=\"ascii.ecsv\", overwrite=True)\n\n        with gzip.open(out_excl_file, \"wt\", encoding=\"utf8\") as pf:\n            json.dump(excl, pf, indent=4)\n\n        if commit:\n            cmesg = \"Creating new focalplane model from DB sync {}\".format(date_str)\n            try:\n                sp.check_call([\"svn\", \"update\"], cwd=out_dir)\n                sp.check_call(\n                    [\n                        \"svn\",\n                        \"add\",\n                        out_fp_file,\n                        out_excl_file,\n                        out_state_file,\n                    ],\n                    cwd=out_dir,\n                )\n                sp.check_call([\"svn\", \"commit\", \"-m\", cmesg], cwd=out_dir)\n                sp.check_call([\"svn\", \"update\"], cwd=out_dir)\n            except sp.CalledProcessError:\n                log.error(\"svn update / commit returned an error\")\n    else:\n        # Load the current focalplane and just update the state\n\n        # Get the focalplane from the current datestamp\n        cur_date = datetime.datetime.strptime(date_str, \"%Y-%m-%dT%H:%M:%S%z\")\n        oldtime = cur_date\n\n        oldfp, oldexcl, oldstate, oldtmstr = load_focalplane(oldtime)\n\n        log.info(\"Comparing generated focalplane to one from %s\", oldtmstr)\n\n        # Compare the old and new.\n        checkcols = set(fp.colnames)\n        diff = device_compare(oldfp, fp, list(checkcols))\n\n        if len(diff) > 0:\n            device_printdiff(diff)\n            msg = (\n                \"Existing focalplane device properties have changed.\"\n                \"  Use the 'reset' option to start with a new focalplane model.\"\n            )\n            log.error(msg)\n            return\n\n        # We got this far, which means that the focalplane data agrees.  Now\n        # Look for differences in the state.\n        checkcols = set(state.colnames)\n        checkcols.remove(\"TIME\")\n        state_diff = device_compare(oldstate, state, list(checkcols))\n\n        if len(state_diff) == 0:\n            log.info(\"New focalplane state is identical, no action needed.\")\n            return\n\n        # We must have some changes, load the full table and append.\n        state_file = os.path.join(out_dir, \"desi-state_{}.ecsv\".format(oldtmstr))\n        st = Table.read(state_file, format=\"ascii.ecsv\")\n\n        # If needed, promote the \"TIME\" state column to the new column type\n        if len(st[\"TIME\"][0]) < 21:\n            newt = Column(\n                name=\"TIME\",\n                length=len(st[\"TIME\"]),\n                dtype=np.dtype(\"a30\"),\n                description=\"The timestamp of the event (UTC, ISO format)\",\n            )\n            for row, oldt in enumerate(st[\"TIME\"]):\n                nt = datetime.datetime.strptime(oldt, \"%Y-%m-%dT%H:%M:%S\")\n                nt = nt.replace(tzinfo=datetime.timezone.utc)\n                newt[row] = nt.isoformat()\n            st.replace_column(\"TIME\", newt)\n\n        excl_file = None\n        for test_ext in [\"json.gz\", \"yaml.gz\"]:\n            excl_file = os.path.join(\n                out_dir,\n                \"desi-exclusion_{}.{}\".format(oldtmstr, test_ext)\n            )\n            if os.path.isfile(excl_file):\n                break\n            else:\n                excl_file = None\n        if excl_file is None:\n            msg = \"Attempting to sync to an ancient focalplane model with uncompressed YAML exclusion polygons\"\n            raise RuntimeError(msg)\n\n        tmp_state = \"{}.tmp\".format(state_file)\n        prev_state = \"{}.previous\".format(state_file)\n        tmp_excl = \"{}.tmp\".format(excl_file)\n        prev_excl = \"{}.previous\".format(excl_file)\n\n        device_printdiff(state_diff)\n\n        n_new_states = 0\n        n_new_excl = 0\n        for loc, df in state_diff.items():\n            if df[\"old\"] is None or df[\"new\"] is None:\n                # This should never happen, since it means that the LOCATION\n                # value does not exist in either the previous or current\n                # state.  We already checked for that above.\n                msg = \"LOCATION {} missing from old or new state.  Should never happen!\".format(\n                    loc\n                )\n                raise RuntimeError(msg)\n\n            row = [df[\"new\"][col] for col in df[\"new\"].dtype.names]\n            st.add_row(row)\n            n_new_states += 1\n\n            new_excl = str(\n                df[\"new\"][\"EXCLUSION\"].tobytes().rstrip(b\"\\x00\"), encoding=\"utf-8\"\n            )\n            if new_excl not in oldexcl:\n                oldexcl[new_excl] = excl[new_excl]\n                n_new_excl += 1\n\n        log.info(\"Updating focalplane:  %s\", oldtmstr)\n        log.info(\"  State log appending %d rows\", n_new_states)\n        if n_new_excl > 0:\n            log.info(\"  Adding %d new exclusion shapes\", n_new_excl)\n        else:\n            log.info(\"  No new exclusion shapes, not updating file\")\n\n        if test:\n            log.info(\"Running with test==True, skipping file writes.\")\n            return\n\n        # Write to temp file then move into place\n        st.write(tmp_state, format=\"ascii.ecsv\", overwrite=True)\n        shutil.copy2(state_file, prev_state)\n        os.rename(tmp_state, state_file)\n\n        # If we updated any exclusions, write a new file\n        if n_new_excl > 0:\n            with gzip.open(tmp_excl, \"wt\", encoding='utf8') as pf:\n                if re.match(r\".*json.*\", excl_file) is not None:\n                    # New format\n                    json.dump(\n                        oldexcl,\n                        pf,\n                        indent=4\n                    )\n                else:\n                    # Old format\n                    yaml.dump(\n                        oldexcl,\n                        stream=pf,\n                        encoding=\"utf-8\",\n                        default_flow_style=False\n                    )\n\n            shutil.copy2(excl_file, prev_excl)\n            os.rename(tmp_excl, excl_file)\n\n        if commit:\n            cmesg = \"Appending DB sync {} to focalplane model {}\".format(\n                date_str, oldtmstr\n            )\n            try:\n                sp.check_call([\"svn\", \"update\"], cwd=out_dir)\n                sp.check_call(\n                    [\n                        \"svn\",\n                        \"commit\",\n                        \"-m\",\n                        cmesg,\n                    ],\n                    cwd=out_dir,\n                )\n                sp.check_call([\"svn\", \"update\"], cwd=out_dir)\n            except sp.CalledProcessError:\n                log.error(\"svn update / commit returned an error\")\n", "meta": {"hexsha": "6cb00e6eeff0051f927537e7e9b4c6780b4e1be1", "size": 21096, "ext": "py", "lang": "Python", "max_stars_repo_path": "py/desimodel/inputs/focalplane_sync.py", "max_stars_repo_name": "desihub/desimodel", "max_stars_repo_head_hexsha": "d5f7f871873c547892a40ece30890b8610f53768", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-07-18T19:22:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T16:02:01.000Z", "max_issues_repo_path": "py/desimodel/inputs/focalplane_sync.py", "max_issues_repo_name": "desihub/desimodel", "max_issues_repo_head_hexsha": "d5f7f871873c547892a40ece30890b8610f53768", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 134, "max_issues_repo_issues_event_min_datetime": "2016-02-07T03:48:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T17:50:09.000Z", "max_forks_repo_path": "py/desimodel/inputs/focalplane_sync.py", "max_forks_repo_name": "desihub/desimodel", "max_forks_repo_head_hexsha": "d5f7f871873c547892a40ece30890b8610f53768", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-07-12T21:36:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T16:15:44.000Z", "avg_line_length": 35.7559322034, "max_line_length": 111, "alphanum_fraction": 0.5616230565, "include": true, "reason": "import numpy,from astropy", "num_tokens": 5347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.30404168127272885, "lm_q1q2_score": 0.15320847929136408}}
{"text": "\"\"\"`AlphaIMS`, `AlphaAMS`\"\"\"\nimport numpy as np\nfrom collections import OrderedDict\n\nfrom .base import ProsthesisSystem\nfrom .electrodes import SquareElectrode, DiskElectrode\nfrom .electrode_arrays import ElectrodeGrid\n\n\nclass AlphaIMS(ProsthesisSystem):\n    \"\"\"Alpha-IMS\n\n    This class creates an Alpha-IMS array with 1500 photovoltaic pixels (each\n    50um in diameter) as described in [Stingl2013]_, and places it in the\n    subretinal space, such that the center of the array is located at (x,y,z),\n    given in microns, and the array is rotated by rotation angle ``rot``,\n    given in degrees.\n\n    The device consists of 1500 50um-wide square pixels, arranged on a 39x39\n    rectangular grid with 72um pixel pitch.\n\n    The array is oriented upright in the visual field, such that an\n    array with center (0,0) has the top three rows lie in the lower\n    retina (upper visual field).\n\n    An electrode can be addressed by name, row/column index, or integer index\n    (into the flattened array).\n\n    .. note::\n\n        Column order is reversed in a left-eye implant.\n\n    Parameters\n    ----------\n    x/y/z : double\n        3D location of the center of the electrode array.\n        The coordinate system is centered over the fovea.\n        Positive ``x`` values move the electrode into the nasal retina.\n        Positive ``y`` values move the electrode into the superior retina.\n        Positive ``z`` values move the electrode away from the retina into the\n        vitreous humor (sometimes called electrode-retina distance).\n        ``z`` can either be a list with 1500 entries or a scalar that is applied\n        to all electrodes.\n    rot : float\n        Rotation angle of the array (deg). Positive values denote\n        counter-clock-wise (CCW) rotations in the retinal coordinate\n        system.\n    eye : {'RE', 'LE'}, optional\n        Eye in which array is implanted.\n    preprocess : bool or callable, optional\n        Either True/False to indicate whether to execute the implant's default\n        preprocessing method whenever a new stimulus is assigned, or a custom\n        function (callable).\n    safe_mode : bool, optional\n        If safe mode is enabled, only charge-balanced stimuli are allowed.\n\n    Examples\n    --------\n    Create an Alpha-IMS array centered on the fovea, at 100um distance from\n    the retina, rotated counter-clockwise by 5 degrees:\n\n    >>> from pulse2percept.implants import AlphaIMS\n    >>> AlphaIMS(x=0, y=0, z=100, rot=5)  # doctest: +NORMALIZE_WHITESPACE\n    AlphaIMS(earray=ElectrodeGrid, eye='RE', preprocess=True,\n             safe_mode=False, shape=(39, 39), stim=None)\n\n    Get access to the third electrode in the top row (by name or by row/column\n    index):\n\n    >>> alpha_ims = AlphaIMS(x=0, y=0, z=100, rot=0)\n    >>> alpha_ims['A3']  # doctest: +NORMALIZE_WHITESPACE\n    SquareElectrode(a=50.0, activated=True, name='A3',\n                    x=-1224.0, y=-1368.0, z=100.0)\n    >>> alpha_ims[0, 2]  # doctest: +NORMALIZE_WHITESPACE\n    SquareElectrode(a=50.0, activated=True, name='A3',\n                    x=-1224.0, y=-1368.0, z=100.0)\n\n    \"\"\"\n    # Frozen class: User cannot add more class attributes\n    __slots__ = ('shape',)\n\n    def __init__(self, x=0, y=0, z=-100, rot=0, eye='RE', stim=None,\n                 preprocess=True, safe_mode=False):\n        self.eye = eye\n        self.preprocess = preprocess\n        self.safe_mode = safe_mode\n        self.shape = (39, 39)\n        elec_width = 50.0  # um\n        e_spacing = 72.0  # um\n\n        # The user might provide a list of z values for each of the\n        # 378 resulting electrodes, not for the 22x19 initial ones.\n        # In this case, don't pass it to ElectrodeGrid, but overwrite\n        # the z values later:\n        overwrite_z = isinstance(z, (list, np.ndarray))\n        zarr = -100.0 if overwrite_z else z\n        self.earray = ElectrodeGrid(self.shape, e_spacing, x=x, y=y, z=zarr,\n                                    rot=rot, etype=SquareElectrode,\n                                    a=elec_width)\n\n        # Unfortunately, in the left eye the labeling of columns is reversed...\n        if eye == 'LE':\n            # FIXME: Would be better to have more flexibility in the naming\n            # convention. This is a quick-and-dirty fix:\n            names = self.earray.electrode_names\n            objects = self.earray.electrode_objects\n            names = np.array(names).reshape(self.earray.shape)\n            # Reverse column names:\n            for row in range(self.earray.shape[0]):\n                names[row] = names[row][::-1]\n            # Build a new ordered dict:\n            electrodes = OrderedDict([])\n            for name, obj in zip(names.ravel(), objects):\n                electrodes.update({name: obj})\n            # Assign the new ordered dict to earray:\n            self.earray._electrodes = electrodes\n\n        # Remove electrodes:\n        extra_elecs = ['AM39', 'AL39', 'AK39', 'AJ39', 'AI39', 'AH39', 'AG39',\n                       'AF39', 'AE39', 'AD39', 'AC39',\n                       'AM38', 'AL38', 'AK38', 'AJ38', 'AI38', 'AH38', 'AG38',\n                       'AF38', 'AE38', 'AD38']\n        for elec in extra_elecs:\n            self.earray.remove_electrode(elec)\n\n        # Now that the superfluous electrodes have been deleted, adjust the\n        # z values:\n        if overwrite_z:\n            # Specify different height for every electrode in a list:\n            z_arr = np.asarray(z).flatten()\n            if z_arr.size != self.n_electrodes:\n                raise ValueError(\"If `z` is a list, it must have %d entries, \"\n                                 \"not %d.\" % (self.n_electrodes, z_arr.size))\n            for elec, z_elec in zip(self.earray.electrode_objects, z):\n                elec.z = z_elec\n\n        # Beware of race condition: Stim must be set last, because it requires\n        # indexing into self.electrodes:\n        self.stim = stim\n\n    def _pprint_params(self):\n        \"\"\"Return dict of class attributes to pretty-print\"\"\"\n        params = super()._pprint_params()\n        params.update({'shape': self.shape})\n        return params\n\n\nclass AlphaAMS(ProsthesisSystem):\n    \"\"\"Alpha-AMS\n\n    This class creates an Alpha-AMS array with 1600 photovoltaic pixels (each\n    30um in diameter) as described in [Stingl2017]_, and places it in the\n    subretinal space, such that the center of the array is located at (x,y,z),\n    given in microns, and the array is rotated by rotation angle ``rot``,\n    given in degrees.\n\n    The device consists of 1600 30um-wide round pixels, arranged on a 40x40\n    rectangular grid with 70um pixel pitch.\n\n    The array is oriented upright in the visual field, such that an\n    array with center (0,0) has the top three rows lie in the lower\n    retina (upper visual field), as shown below:\n\n    An electrode can be addressed by name, row/column index, or integer index\n    (into the flattened array).\n\n    .. note::\n\n        Column order is reversed in a left-eye implant.\n\n    Parameters\n    ----------\n    x/y/z : double\n        3D location of the center of the electrode array.\n        The coordinate system is centered over the fovea.\n        Positive ``x`` values move the electrode into the nasal retina.\n        Positive ``y`` values move the electrode into the superior retina.\n        Positive ``z`` values move the electrode away from the retina into the\n        vitreous humor (sometimes called electrode-retina distance).\n        ``z`` can either be a list with 1600 entries or a scalar that is applied\n        to all electrodes.\n    rot : float\n        Rotation angle of the array (deg). Positive values denote\n        counter-clock-wise (CCW) rotations in the retinal coordinate\n        system.\n    eye : {'RE', 'LE'}, optional\n        Eye in which array is implanted.\n    preprocess : bool or callable, optional\n        Either True/False to indicate whether to execute the implant's default\n        preprocessing method whenever a new stimulus is assigned, or a custom\n        function (callable).\n    safe_mode : bool, optional\n        If safe mode is enabled, only charge-balanced stimuli are allowed.\n\n    Examples\n    --------\n    Create an AlphaAMS array centered on the fovea, at 100um distance from\n    the retina, rotated counter-clockwise by 5 degrees:\n\n    >>> from pulse2percept.implants import AlphaAMS\n    >>> AlphaAMS(x=0, y=0, z=100, rot=5)  # doctest: +NORMALIZE_WHITESPACE\n    AlphaAMS(earray=ElectrodeGrid, eye='RE', preprocess=True,\n             safe_mode=False, shape=(40, 40), stim=None)\n\n    Get access to the third electrode in the top row (by name or by row/column\n    index):\n\n    >>> alpha_ims = AlphaAMS(x=0, y=0, z=100, rot=0)\n    >>> alpha_ims['A3']  # doctest: +NORMALIZE_WHITESPACE\n    DiskElectrode(activated=True, name='A3', r=15.0, x=-1225.0,\n                  y=-1365.0, z=100.0)\n    >>> alpha_ims[0, 2]  # doctest: +NORMALIZE_WHITESPACE\n    DiskElectrode(activated=True, name='A3', r=15.0, x=-1225.0,\n                  y=-1365.0, z=100.0)\n\n    \"\"\"\n    # Frozen class: User cannot add more class attributes\n    __slots__ = ('shape',)\n\n    def __init__(self, x=0, y=0, z=0, rot=0, eye='RE', stim=None,\n                 preprocess=True, safe_mode=False):\n        self.eye = eye\n        self.preprocess = preprocess\n        self.safe_mode = safe_mode\n        self.shape = (40, 40)\n        elec_radius = 15.0\n        e_spacing = 70.0  # um\n\n        self.earray = ElectrodeGrid(self.shape, e_spacing, x=x, y=y, z=z,\n                                    rot=rot, etype=DiskElectrode,\n                                    r=elec_radius)\n\n        # Beware of race condition: Stim must be set last, because it requires\n        # indexing into self.electrodes:\n        self.stim = stim\n\n        # Set left/right eye:\n        # Unfortunately, in the left eye the labeling of columns is reversed...\n        if eye == 'LE':\n            # FIXME: Would be better to have more flexibility in the naming\n            # convention. This is a quick-and-dirty fix:\n            names = self.earray.electrode_names\n            objects = self.earray.electrode_objects\n            names = np.array(names).reshape(self.earray.shape)\n            # Reverse column names:\n            for row in range(self.earray.shape[0]):\n                names[row] = names[row][::-1]\n            # Build a new ordered dict:\n            electrodes = OrderedDict([])\n            for name, obj in zip(names.ravel(), objects):\n                electrodes.update({name: obj})\n            # Assign the new ordered dict to earray:\n            self.earray._electrodes = electrodes\n\n    def _pprint_params(self):\n        \"\"\"Return dict of class attributes to pretty-print\"\"\"\n        params = super()._pprint_params()\n        params.update({'shape': self.shape})\n        return params\n", "meta": {"hexsha": "2eedb384b4cd065908439fde5780cdc0c0b88ea9", "size": 10798, "ext": "py", "lang": "Python", "max_stars_repo_path": "pulse2percept/implants/alpha.py", "max_stars_repo_name": "pulse2percept/pulse2percept", "max_stars_repo_head_hexsha": "67e0f2354db5ebe306b617f7f78a9ea8c02327ac", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 40, "max_stars_repo_stars_event_min_datetime": "2019-11-01T14:09:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T19:08:01.000Z", "max_issues_repo_path": "pulse2percept/implants/alpha.py", "max_issues_repo_name": "jgranley/pulse2percept", "max_issues_repo_head_hexsha": "65c11393a33d1531cd02a3e38243414bf8172e9a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 277, "max_issues_repo_issues_event_min_datetime": "2019-11-22T03:30:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T00:11:03.000Z", "max_forks_repo_path": "pulse2percept/implants/alpha.py", "max_forks_repo_name": "jgranley/pulse2percept", "max_forks_repo_head_hexsha": "65c11393a33d1531cd02a3e38243414bf8172e9a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2020-01-22T06:36:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T09:54:25.000Z", "avg_line_length": 41.5307692308, "max_line_length": 80, "alphanum_fraction": 0.6217818114, "include": true, "reason": "import numpy", "num_tokens": 2717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.1532084761136403}}
{"text": "#!/usr/bin/env python3\n#\n# (c) Copyright Rosetta Commons Member Institutions.\n# (c) This file is part of the Rosetta software suite and is made available under license.\n# (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.\n# (c) For more information, see http://www.rosettacommons.org. Questions about this can be\n# (c) addressed to University of Washington CoMotion, email: license@uw.edu.\n'''\nContains helper functions that defines Rosetta-style topology for given Molecule including:\n- AtomTree, Chi angles, Ring, Bond order, and so on.\n\nAuthor: Hahnbeom Park and Frank DiMaio \n'''\n\nimport sys\nimport math\nimport numpy as np\nimport numpy.linalg\nimport scipy.sparse.csgraph\nimport scipy.linalg\nfrom Types import *\nfrom BasicClasses import AtomClass, RingClass\nfrom AtomTypeClassifier import AtomTypeClassifier\nfrom utils import dihedral\n\nCUTOFF_PLANAR = 40.0 # GZ: this is just a guess\n\ndef setup(mol,option): # mol: Molecule type\n    '''Main function setting up all the toplogy-related things of the input Molecule(==\"mol\") '''\n    mol.vatms = []\n    mol.angles = []\n    mol.torsions = []\n    mol.nbratom = -1\n    mol.nbrradius = 0.0\n    mol.atms_aro = []\n    mol.atms_puckering = []\n    mol.atms_ring = [] #including aromatic ring\n    mol.ATorder = []\n    mol.rings_strained = [] #3/4 membered\n    mol.rings_aro = [] #only aromatic\n    mol.rings_pucker = [] #puckering\n    mol.rings_sugar = [] #subset of puckering rings\n    mol.rings = [] #aromatic + puckering\n\n    assign_bonds(mol)\n    assign_angles(mol)\n    assign_torsions(mol)\n    detect_rings(mol,option)\n\n    assign_hybridization_if_missing(mol) # should come after ring assignment\n    setup_nbratom(mol) #should come after ring assignments\n    define_icoord(mol) #should come after nbr setup\n\n    classifier = AtomTypeClassifier()\n    classifier.apply_to_molecule(mol)\n    classifier.assert_H(mol)\n\n    # should come after atom types classified\n    define_conjugation(mol)\n    define_rotable_torsions(mol)\n\n# Functions from here are pieces of setup\n\ndef setup_nbratom(mol):\n    '''Setup residue nbratom & nbrradius field'''\n    com = np.sum(mol.xyz,axis=0) / len(mol.atms)\n    dists = np.sum(np.square(mol.xyz - com[None,:]),axis=-1) # dist_squared\n    maxdis = math.sqrt(max(dists)) \n\n    # 1) dont let puckering ring be root\n    dists[np.in1d(np.arange(len(mol.atms)), mol.atms_puckering)] = 99999.0\n\n    nbonds = [len(atm.bonds) for atm in mol.atms]\n    for ring in mol.rings: #correct for cut_bonds\n        (i,j) = ring.cut_bond\n        if i == None: continue\n        nbonds[i] -=1\n        nbonds[j] -=1\n\n    # 3) also exclude hydrogens\n    # prioritize ring-atom with >2 bonds\n    for i,atm in enumerate(mol.atms):\n        if nbonds[i] <=1: dists[i] = 99999.0\n        elif nbonds[i] ==2: dists[i] = 999.0\n        if atm.is_H: dists[i] = 99999.0\n\n    mol.nbratom = np.argmin(dists)\n    mol.nbrradius = (maxdis+1.5)*2 #safe\n\ndef assign_bonds(mol):\n    for bond in mol.bonds:\n        is_H1 = (mol.atms[bond.atm1].atype==2) \n        is_H2 = (mol.atms[bond.atm2].atype==2) \n        mol.atms[bond.atm1].add_bond(bond.atm2,bond.order)\n        mol.atms[bond.atm2].add_bond(bond.atm1,bond.order)\n\n        if is_H1:\n            mol.atms[bond.atm2].has_H = True\n        if is_H2:\n            mol.atms[bond.atm1].has_H = True\n\n        if mol.atms[bond.atm1].atype == 1 and mol.atms[bond.atm2].atype in POLAR_ATOMS:\n            mol.atms[bond.atm1].connected_to_polar = True\n        if mol.atms[bond.atm2].atype == 1 and mol.atms[bond.atm1].atype in POLAR_ATOMS:\n            mol.atms[bond.atm2].connected_to_polar = True\n\n    # sanity check if any atm is not connected to anything\n    atms_unconnected = []\n    for atm in mol.atms:\n        if len(atm.bonds) == 0:\n            atms_unconnected.append(atm.name)\n    if atms_unconnected != []:\n        sys.exit('ERROR: Atom found not connected to any other atom:'+' '.join(atms_unconnected))\n        \n# Currently used only for 'nh' case: See \"0\" in SPECIAL_HYBRIDS to see which atypes in mol2 comes here\ndef assign_hybridization_if_missing(mol):\n    n_to_assign = 0\n    to_assign = []\n    for iatm,atm in enumerate(mol.atms):\n        if ATYPES[atm.atype] in ATYPES_HYBRID:\n            n_to_assign += 1\n            if atm.hyb == 0:\n                to_assign.append(iatm)\n            \n    for iatm in to_assign:\n        atm = mol.atms[iatm]\n        attached_to_aro = False\n        attached_to_nonaro = False\n        nH_attached = 0\n        for jatm,order in atm.bonds:\n            if jatm in mol.atms_aro:\n                attached_to_aro = True\n            elif mol.atms[jatm].is_H:\n                nH_attached += 1\n            else:\n                attached_to_nonaro = True\n        \n        if atm.atype == ATYPES.index('N') and attached_to_aro:\n            if nH_attached == 2: #aro-NH2\n                atm.hyb = 2 \n            elif not attached_to_nonaro:\n                atm.hyb = 2\n            else:\n                atm.hyb = 3\n        else:\n            if len(atm.bonds) < 3:\n                atm.hyb = 2\n            else:\n                #measure improper torsion\n                neigh = [j for j,order in atm.bonds][:3]\n                imp = dihedral(mol.xyz[neigh[0]],mol.xyz[neigh[1]],mol.xyz[neigh[2]],mol.xyz[iatm])\n                if abs(imp) < 10.0: #dev less than 20 degree\n                    atm.hyb = 2\n                else:\n                    atm.hyb = 3\n           \n        # BELOW FAILS for GAFFtype nh!\n        # Use user input structure instead above (there is no other easy way)\n        #bondorders = [bond[1] for bond in atm.bonds]\n        #maxorder = max(bondorders)\n        #if 1 in bondorders:\n        #    atm.hyb = 3\n        #elif maxorder == 9:\n        #    atm.hyb = 9\n        #elif maxorder == 2:\n        #    atm.hyb = 2\n        #elif maxorder == 3:\n        #    atm.hyb = 1\n        #else:\n        #    print('WARNING: Unknown atype in input mol2 for %s; assigning hyb=2'%(atm.name))\n        print('Hybridization state for %d:%s assigned as %s'%(iatm,atm.name,atm.hyb))\n            \ndef assign_angles(mol):\n    '''Assigns all bond-angles (not only in AtomTree)'''\n    for i,bond1 in enumerate(mol.bonds[:-1]):\n        for bond2 in mol.bonds[i+1:]:\n            if bond1.atm1 == bond2.atm1:\n                angle = (bond1.atm2,bond1.atm1,bond2.atm2)\n            elif bond1.atm1 == bond2.atm2:\n                angle = (bond1.atm2,bond1.atm1,bond2.atm1)\n            elif bond1.atm2 == bond2.atm1:\n                angle = (bond1.atm1,bond1.atm2,bond2.atm2)\n            elif bond1.atm2 == bond2.atm2:\n                angle = (bond1.atm1,bond1.atm2,bond2.atm1)\n            else:\n                continue\n            mol.angles.append(angle)\n\ndef assign_torsions(mol):\n    '''Assigns all torsion angles (not only in AtomTree)'''\n    bonds = [(bond.atm1,bond.atm2) for bond in mol.bonds]\n\n    torsions_heavy = []\n    torsions_H = []\n    orders_heavy = []\n    orders_H = []\n    if mol.option.verbose:\n        print('bonds: ', [(bond.atm1,bond.atm2) for bond in mol.bonds])\n    for i,bond1 in enumerate(mol.bonds[:-1]):\n        for bond2 in mol.bonds[i+1:]:\n            if (bond1.atm1 == bond2.atm1 or bond1.atm1 == bond2.atm2 or \\\n                bond1.atm2 == bond2.atm1 or bond1.atm2 == bond2.atm2): continue\n\n            if (bond1.atm1,bond2.atm1) in bonds:\n                a,b,c,d = (bond1.atm2,bond1.atm1,bond2.atm1,bond2.atm2)\n            elif (bond1.atm1,bond2.atm2) in bonds:\n                a,b,c,d = (bond1.atm2,bond1.atm1,bond2.atm2,bond2.atm1)\n            elif (bond1.atm2,bond2.atm1) in bonds:\n                a,b,c,d = (bond1.atm1,bond1.atm2,bond2.atm1,bond2.atm2)\n            elif (bond1.atm2,bond2.atm2) in bonds:\n                a,b,c,d = (bond1.atm1,bond1.atm2,bond2.atm2,bond2.atm1)\n            elif (bond2.atm1,bond1.atm1) in bonds:\n                a,b,c,d = (bond2.atm2,bond2.atm1,bond1.atm1,bond1.atm2)\n            elif (bond2.atm2,bond1.atm1) in bonds:\n                a,b,c,d = (bond2.atm1,bond2.atm2,bond1.atm1,bond1.atm2)\n            elif (bond2.atm1,bond1.atm2) in bonds:\n                a,b,c,d = (bond2.atm2,bond2.atm1,bond1.atm2,bond1.atm1)\n            elif (bond2.atm2,bond1.atm2) in bonds:\n                a,b,c,d = (bond2.atm1,bond2.atm2,bond1.atm2,bond1.atm1)\n            else:\n                continue\n\n            ibond = bonds.index((b,c))\n            ## bug fix Sep25 2018: if having only hydrogens at either end\n            if mol.atms[a].is_H or mol.atms[d].is_H:\n                torsions_H.append((a,b,c,d))\n                orders_H.append(mol.bonds[ibond].order)\n            else:\n                torsions_heavy.append((a,b,c,d))\n                orders_heavy.append(mol.bonds[ibond].order)\n\n    # sort in heavy-atom torsions followed by H-only torsions\n    #mol.torsion_orderso = orders_heavy + orders_H #unused\n    mol.torsions = torsions_heavy + torsions_H\n\n    if mol.option.verbose:\n        print('Torsions: ', mol.torsions)\n\ndef search_special_biaryl_ring(mol,ring):\n    '''Add extra rotatable bonds between ring & nonring functional groups\n    (by going through hard-coded cases)'''\n    \n    biaryl_pivot_extra = []\n    # [(A,B),..] : ring=A becomes special biaryl if any of ring=A-B connection is detected\n    # Nin definition changed as of Oct242018; All the non-aromatic 1H sp2N goes to NG21\n    # non-biaryl (== conjugated): NG21=O*\n    special_biaryl_to_ring = [(ACLASS_ID.index('CDp'),ACLASS_ID.index('OG2')),\n                              (ACLASS_ID.index('CDp'),ACLASS_ID.index('Oal')),\n                              (ACLASS_ID.index('CDp'),ACLASS_ID.index('Oad')),\n                              \n                              # ring-N=C; (RingN-C)-NG21 are excluded outside here\n                              (ACLASS_ID.index('NG21'),ACLASS_ID.index('CR')),\n                              (ACLASS_ID.index('NG21'),ACLASS_ID.index('CRp')),\n                              (ACLASS_ID.index('NG21'),ACLASS_ID.index('CD')),\n                              (ACLASS_ID.index('NG21'),ACLASS_ID.index('CDp')),\n                              (ACLASS_ID.index('NG21'),ACLASS_ID.index('CSp')),\n                              (ACLASS_ID.index('NG21'),ACLASS_ID.index('CS')),\n                              (ACLASS_ID.index('NG21'),ACLASS_ID.index('CS1')),\n                              (ACLASS_ID.index('NG21'),ACLASS_ID.index('CS2')),\n\n                              # ring-N-SOn\n                              #(ACLASS_ID.index('Nin'),ACLASS_ID.index('SG5')),\n                              (ACLASS_ID.index('NG21'),ACLASS_ID.index('SG5')),\n                              \n                              # ring-amide\n                              (ACLASS_ID.index('Nad'),ACLASS_ID.index('CDp')), # treat energy separately\n\n                              # ring-C=N*\n                              (ACLASS_ID.index('CDp'),ACLASS_ID.index('Nad')),\n                              (ACLASS_ID.index('CDp'),ACLASS_ID.index('Nam2')),\n                              (ACLASS_ID.index('CDp'),ACLASS_ID.index('NG2')),\n                              (ACLASS_ID.index('CDp'),ACLASS_ID.index('Nin')),\n\n                              # R-CD1-CD1-\n                              (ACLASS_ID.index('CD1'),ACLASS_ID.index('CD1')),\n                              (ACLASS_ID.index('CD1'),ACLASS_ID.index('CD')),\n                              (ACLASS_ID.index('CD'),ACLASS_ID.index('CD')),\n                              (ACLASS_ID.index('CD'),ACLASS_ID.index('CD1')),\n                              \n                              # R-CDx-R\n                              (ACLASS_ID.index('CD'),ACLASS_ID.index('CR')),\n                              (ACLASS_ID.index('CD1'),ACLASS_ID.index('CR')),\n                              (ACLASS_ID.index('CDp'),ACLASS_ID.index('CR')),\n\n                              # ring-C=halogen \n                              (ACLASS_ID.index('CD'),ACLASS_ID.index('F')),\n                              (ACLASS_ID.index('CD'),ACLASS_ID.index('Cl')),\n                              (ACLASS_ID.index('CD'),ACLASS_ID.index('Br')),\n                              (ACLASS_ID.index('CD'),ACLASS_ID.index('I')),\n                              ]\n    \n\n    for a1 in ring.atms:\n        a2_is_special_biaryl = False\n        for a2,order in mol.atms[a1].bonds:\n            a2class = mol.atms[a2].aclass\n            # avoid from ring itself\n            #if a2 in mol.atms_aro or a2 in mol.atms_puckering: continue\n            if mol.in_same_ring(a1,a2): continue\n\n            # Oct17: skip if not defined as single bond as input!\n            if order > 1: continue\n            \n            further_connected = False\n            for a3,order in mol.atms[a2].bonds:\n                if a3 == a1: continue\n                a3class = mol.atms[a3].aclass\n                \n                if (a2class,a3class) in special_biaryl_to_ring:\n                    a2_is_special_biaryl = True\n                    #break\n                if len(mol.atms[a3].bonds) > 1:\n                    further_connected = True\n\n            if a2_is_special_biaryl and further_connected:\n                #Final check using the input conformation\n                #if the torsion around a1-a2 is planar, treat it as conjuated.\n                #e.g UZARAP\n                #GZ, Aug,20,2020\n                if mol.option.opt.infer_conjugation and is_planar(mol, a1, a2):\n                    continue\n                biaryl_pivot_extra.append((a1,a2))\n            \n    return biaryl_pivot_extra\n\ndef check_duplication(rings,ring_i):\n    for ring_j in rings:\n        n = 0\n        for j in ring_j.atms:\n            if j in ring_i: n+=1\n        if n == ring_j.natms:\n            return ring_j.atms\n    return False\n\ndef get_path(bond_tree,edge,alt_cut=[]):\n    '''helper function in ring detection'''\n    i,j = edge\n    curr = j\n    ring_i = [curr]\n    bond_tree[i,j] = bond_tree[j,i] = 0\n    if alt_cut != []: bond_tree[alt_cut[0],alt_cut[1]] = bond_tree[alt_cut[1],alt_cut[0]] = 0\n    ds, preds = scipy.sparse.csgraph.shortest_path(bond_tree,return_predecessors=True)\n    bond_tree[i,j] = bond_tree[j,i] = 1\n    if alt_cut != []: bond_tree[alt_cut[0],alt_cut[1]] = bond_tree[alt_cut[1],alt_cut[0]] = 1\n\n    if ds[i,j] > 9999: return False\n    \n    while (curr != i):\n        curr = preds[i,curr]\n        ring_i.append(curr)\n    return ring_i\n\ndef detect_rings(mol,option):\n    '''Detects ring & ring types (i.e. aro vs nonaro)'''\n    mol.rings = []\n    mol.atms_aro = []\n    mol.atms_puckering = []\n    \n    bond_tree = np.zeros((len(mol.atms),len(mol.atms)))\n    for bond in mol.bonds:\n        bond_tree[bond.atm1,bond.atm2] = bond_tree[bond.atm2,bond.atm1] = 1\n\n    mol.tree = scipy.sparse.csgraph.minimum_spanning_tree(bond_tree)\n    treesymm = np.maximum(mol.tree.toarray(), mol.tree.T.toarray())\n    cycle_edges = np.transpose(np.nonzero(np.triu(bond_tree != treesymm)))\n\n    for i,j in cycle_edges:\n        ring_i = get_path(bond_tree,(i,j))\n\n        # this sometimes happens when cycle_edge connects two rings\n        dupl_ring = check_duplication(mol.rings,ring_i)\n        \n        if dupl_ring: #search alternative path by cutting an edge of duplicating ring \n            ring_i = get_path(bond_tree,(i,j),alt_cut=(dupl_ring[0],dupl_ring[-1]))\n            if ring_i:\n                dupl_ring = check_duplication(mol.rings,ring_i)\n                if not dupl_ring:\n                    mol.rings.append(RingClass(ring_i,cut=(ring_i[-1],ring_i[0])))\n                    \n        else: #One cycle edge can form alternative ring\n            mol.rings.append(RingClass(ring_i,cut=(ring_i[-1],ring_i[0])))\n            ring_ii = get_path(bond_tree,(i,j),alt_cut = (ring_i[0],ring_i[1]))\n            if ring_ii:\n                dupl_ring = check_duplication(mol.rings,ring_ii)\n                if not dupl_ring:\n                    mol.rings.append(RingClass(ring_ii,cut=(ring_ii[-1],ring_ii[0])))\n\n    for ring in mol.rings:\n        classify_ring_type(mol,ring,option)\n\n    mol.atms_ring = mol.atms_aro + mol.atms_puckering\n\ndef classify_ring_type(mol,ring,option):\n    '''Classifies ring type'''\n    is_aro = True\n\n    #for long ring take into account of input geometry\n    if ring.natms > 6: \n        ring_xs = [mol.xyz[i] for i in ring.atms]\n        ring_xs -= np.mean(ring_xs, axis = 0) \n        cov = np.cov(ring_xs, rowvar = False)\n        evals,_ = scipy.linalg.eigh(cov)\n        nonplanarity = np.min(evals)\n        if (nonplanarity>1e-2):  # be a bit permissive\n            is_aro = False\n            #print(\"nonplanarity? \", nonplanarity)\n    else: #3~6 membered rings\n        nsp2N = 0\n        nsp3OS = 0\n        nsp3 = 0\n        for atm in ring.atms:\n            if mol.atms[atm].hyb == 3:\n                nsp3 += 1\n                for j,order in mol.atms[atm].bonds:\n                    if order not in [2,4]: \n                        is_aro = False\n                if ATYPES[mol.atms[atm].atype] in ['O','S']:\n                    nsp3OS += 1\n            elif mol.atms[atm].hyb == 2 and ATYPES[mol.atms[atm].atype] == 'N':\n                nsp2N += 1\n\n            # allow exception: 2-nitrogen 5-membered ring or one sp3 O/S ring\n            if len(ring.atms) == 5:\n                if (nsp3 == nsp3OS) or (nsp2N == 2): \n                    is_aro = True\n                else:\n                    is_aro = False\n\n    if ring.natms <= 4:\n        ring.type = 2\n        mol.rings_strained.append(ring)\n        for atm in ring.atms:\n            if atm not in mol.atms_strained:\n                mol.atms_strained.append(atm)\n        \n    elif is_aro:\n        ring.type = 4\n        mol.rings_aro.append(ring)\n        for atm in ring.atms:\n            if atm not in mol.atms_aro:\n                mol.atms_aro.append(atm)\n                        \n    else: #otherwise puckering\n        ring.type = 2 #non-ringsampling \n        natms = len(ring.atms)\n        has_nonsp3 = False\n        for atm in ring.atms:\n            if mol.atms[atm].hyb != 3:\n                has_nonsp3 = True\n                break\n\n        if option.opt.report_puckering_chi:\n            if (natms > option.opt.longest_puckering_ring):\n                ring.type = 3 #long\n            elif (natms > 4) and (not option.opt.ring_sampling_sp3_only or not has_nonsp3 ):\n                ring.type = 1 #ring-sampling\n        \n        #sugar\n        if len(ring.atms) == 5:\n            n_sp3C = 0\n            n_O = 0\n            for iatm in ring.atms:\n                atm = mol.atms[iatm]\n                if ATYPES[atm.atype] == 'C' and atm.hyb == 3:\n                    n_sp3C += 1\n                if ATYPES[atm.atype] == 'O': n_O += 1\n            if n_sp3C == 4 and n_O == 1:\n                #ring.type = 5\n                print('Sugar ring %s: '%mol.mol2file+'  %3s'*5%tuple([mol.atms[iatm].name for iatm in ring.atms]))\n        mol.rings_pucker.append(ring)\n        \n        # puckering also addes into rings (for the biaryl assignment...)\n        for atm in ring.atms:\n            if atm not in mol.atms_puckering:\n                mol.atms_puckering.append(atm)\n\n\ndef is_colinear(crd1, crd2, crd3, eps=1.0e-5):\n    v1 = np.array(crd1) - np.array(crd2)\n    v2 = np.array(crd3) - np.array(crd2)\n    v4_0 = np.cross(v1,v2)\n    if np.inner(v4_0,v4_0) < eps:\n        return True\n    return False\n\n# determine if the torsion defined around the central atm1-atm2 bond is planar\ndef is_planar(mol, atm1, atm2):\n    dihe = None\n    # If one of the central atom is sp1, the torsion is not well defined around atm1-atm2\n    # so we don't consider it as planar at this point.\n    # GZ, Aug,20,2020\n    if mol.atms[atm1].hyb == 1 or mol.atms[atm2].hyb == 1:\n        return False\n    for itor,(a1,a2,a3,a4) in enumerate(mol.torsions):\n        if ( atm1 == a2 and atm2 == a3 ) or \\\n            ( atm1 == a3 and atm2 == a2 ):\n            xyz0 = mol.xyz[a1]\n            xyz1 = mol.xyz[a2]\n            xyz2 = mol.xyz[a3]\n            xyz3 = mol.xyz[a4]\n            dihe = dihedral(xyz0,xyz1,xyz2,xyz3)\n            break\n    if dihe is None:\n        print(\"Warning: No torsion defined around the single bond between atm: %d, %d. Set dihe=0 \"%(atm1, atm2))\n        dihe = 0.0\n    if abs(dihe) >= CUTOFF_PLANAR and abs(dihe) <= (180-CUTOFF_PLANAR) :\n        return False\n    return True\n    \ndef validate_order(nodes, parents):\n    new_nodes = []\n    cur_parent=-999\n    children_nodes = []\n    for i in nodes:\n        if cur_parent != parents[i]:\n            new_nodes.extend( np.sort(children_nodes) )\n            children_nodes = [i]\n            cur_parent = parents[i]\n        else:\n            children_nodes.append(i)\n    new_nodes.extend( np.sort(children_nodes) )\n\n    return new_nodes\n\n# Scipy-version\ndef define_icoord(mol):\n    '''AtomTree setup using scipy graph construct'''\n    nodes,parents = scipy.sparse.csgraph.breadth_first_order(mol.tree, mol.nbratom, directed=False)\n    nodes = validate_order(nodes, parents)\n    first_children = np.zeros_like(parents)\n    mol.ATorder = nodes\n    colinear_child = -9999\n    colinear_parent = -9999\n    for i in nodes:\n        par_i = parents[i]\n        gp_i = -9999 if (par_i==-9999) else parents[par_i]\n        ggp_i = -9999 if (gp_i==-9999) else parents[gp_i]\n\n        # 1: root corrections\n        if (i == nodes[0] or i == nodes[1] or i == nodes[2]):\n            par_i = nodes[0]\n            gp_i = nodes[1]\n            ggp_i = nodes[2]\n\n        # 2: near-root corrections\n        if (gp_i == -9999):\n            # 3+ child of root\n            gp_i = nodes[1]\n            ggp_i = nodes[2]\n\n        if (ggp_i == -9999):\n            if (par_i == nodes[1]):\n                ggp_i = nodes[2]\n            else:\n                ggp_i = nodes[1]\n\n        if is_colinear(mol.xyz[par_i], mol.xyz[gp_i], mol.xyz[ggp_i]):\n            if colinear_parent != par_i:\n                colinear_parent = par_i\n                colinear_child = i\n            else:\n                ggp_i = colinear_child\n                colinear_child = i\n\n        mol.atms[i].root = par_i\n        mol.atms[i].groot = (gp_i,ggp_i)\n\n        # ring virtuals\n        if (i in mol.atms_puckering):\n            for rnum,ring in enumerate(mol.rings):\n                (k,l) = ring.cut_bond\n                if not (k==i or l==i): continue\n                if ring.type != 1: continue\n                \n                if (i==k):\n                    vrt_i = l\n                    vtag = \"V%dl\"%rnum\n                else:\n                    vrt_i = k\n                    vtag = \"V%du\"%rnum\n                    \n                # define virtual atoms\n                atm = AtomClass(vtag,\"X\",0,0.0)\n                atm.vrt_i = vrt_i\n                atm.root = i\n                atm.ring_index = rnum\n                \n                if (gp_i == i): # near-root corr\n                    atm.groot = (par_i,nodes[2])\n                else:\n                    atm.groot = (par_i,gp_i)\n                mol.vatms.append(atm)\n\ndef is_biaryl_ring(mol,ring1,ring2):\n    '''Check conjugation between two rings'''\n    # first check if shares any atom\n    for atm1 in ring1.atms:\n        for atm2 in ring2.atms:\n            if atm1 == atm2:\n                return False\n    # Then figure out if any atm pair connected\n    for atm1 in ring1.atms:\n        for atm2 in ring2.atms:\n            for bond in mol.bonds:\n                if (atm1,atm2) != (bond.atm1,bond.atm2) and \\\n                   (atm1,atm2) != (bond.atm2,bond.atm1):\n                    continue\n\n                #check if atm1,atm2 are connected by ring\n                is_connected_by_ring = False\n                for ring in mol.rings:\n                    if atm1 in ring.atms and atm2 in ring.atms:\n                        is_connected_by_ring = True\n                        break\n                if is_connected_by_ring:\n                    continue\n                if mol.option.opt.infer_conjugation:\n                    if ACLASS_ID[mol.atms[atm1].aclass] in CONJUGATING_ACLASSES and \\\n                        ACLASS_ID[mol.atms[atm2].aclass] in CONJUGATING_ACLASSES and \\\n                        is_planar(mol, atm1, atm2):\n                        continue\n                return (atm1,atm2)\n    return False\n\ndef define_conjugation(mol):\n    '''Defines conjugations in bonds in Molecule based on heuristics'''\n    # 1. Rotable ring-ring\n    mol.biaryl_rings = []\n    mol.biaryl_pivots = []\n    if len(mol.rings) > 1:\n        for i,ring1 in enumerate(mol.rings[:-1]):\n            for j,ring2 in enumerate(mol.rings[i+1:]):\n                biaryl_pivot = is_biaryl_ring(mol,ring1,ring2)\n                if biaryl_pivot:\n                    mol.biaryl_rings.append([i,i+j+1])\n                    mol.biaryl_pivots.append(biaryl_pivot)\n        if mol.option.verbose:\n            print( 'Added regular biaryl-pivots: ')\n            for a1,a2 in mol.biaryl_pivots:\n                print( \" (%s,%s)\"%(mol.atms[a1].name,mol.atms[a2].name))\n\n    ## 2. Pseudo ring-ring: non-ring connected to ring\n    if len(mol.rings) > 0:\n        biaryl_pivot_extra = []\n        for i,ring1 in enumerate(mol.rings_aro):\n            biaryl_pivot_extra += search_special_biaryl_ring(mol,ring1)\n        if mol.option.verbose:\n            print( 'Added extra biaryl-pivots: ')\n            for a1,a2 in biaryl_pivot_extra:\n                print( \" (%s,%s)\"%(mol.atms[a1].name,mol.atms[a2].name))\n        mol.biaryl_pivots_extra = biaryl_pivot_extra\n        mol.biaryl_pivots += biaryl_pivot_extra\n\n    # 3. Amide bond; trick to allow rotation around amide bonds\n    for i,bond in enumerate(mol.bonds):\n        aclass1 = ACLASS_ID[mol.atms[bond.atm1].aclass]\n        aclass2 = ACLASS_ID[mol.atms[bond.atm2].aclass]\n        is_amide_connection = (aclass1 in ['Nad','Nad3']) and (aclass2 in ['Nad','Nad3'])\n        if is_amide_connection: # append into special biaryl\n            #A final check, if the initial conformation is planar around the amide bond\n            #We need to treat it as conjugated bond and disallow the rotation.\n            #GZ, Aug,20,2020\n            if mol.option.opt.infer_conjugation and not is_planar(mol, bond.atm1, bond.atm2):\n                mol.biaryl_pivots.append((bond.atm1,bond.atm2))\n            \n    if mol.option.opt.reassign_biaryl_aclass:\n        reassign_biaryl_atypes(mol)\n    else:\n        assign_bond_conjugation(mol)\n\n    if mol.option.verbose:\n        print('Atom_Puckering: ', [mol.atms[atm].name for atm in mol.atms_puckering])\n        print('Atom_Aro: ', [mol.atms[atm].name for atm in mol.atms_aro])\n        print('Rings: ', [[mol.atms[atm].name for atm in ring.atms] for ring in mol.rings])\n        if len(mol.biaryl_rings) > 0 :\n            print('BiarylRings:', mol.biaryl_rings, ' BiarylAxes: ') \n            for a1,a2 in mol.biaryl_pivots:\n                print((mol.atms[a1].name,mol.atms[a2].name))\n            print()\n\n# Deprecated: For atom-type-based torsion assignment\ndef reassign_biaryl_atypes(mol):\n    # reassign atype\n    # Turned off as of Oct 2018 with new bond-based torsion assignment logic\n    for a1,a2 in mol.biaryl_pivots:\n        if mol.atms[a1].aclass in [ACLASS_ID.index('CR'),ACLASS_ID.index('CRp'),\n                                   ACLASS_ID.index('CD1'),ACLASS_ID.index('CD2'),ACLASS_ID.index('CD'),ACLASS_ID.index('CDp')]: #carbon\n            mol.atms[a1].aclass = ACLASS_ID.index('CRb')\n        elif mol.atms[a1].atype == ATYPES.index('N'):\n            mol.atms[a1].aclass = ACLASS_ID.index('NGb')\n            \n        if mol.atms[a2].aclass in [ACLASS_ID.index('CR'),ACLASS_ID.index('CRp'),\n                                   ACLASS_ID.index('CD1'),ACLASS_ID.index('CD2'),ACLASS_ID.index('CDp'),ACLASS_ID.index('CDp')]: #carbon\n            mol.atms[a2].aclass = ACLASS_ID.index('CRb')\n        elif mol.atms[a2].atype == ATYPES.index('N'):\n            mol.atms[a2].aclass = ACLASS_ID.index('NGb')\n\n# For bond-type-based torsion assignment\n# use bond-order + biaryl_pivot info\ndef assign_bond_conjugation(mol):    \n    for ibond,bond in enumerate(mol.bonds):\n        # Consider not conjugated if any of two is sp3\n        if mol.atms[bond.atm1].hyb == 3 or mol.atms[bond.atm2].hyb == 3: continue\n\n        # Jan 2019: To avoid forcing planar forms for puckering rings\n        # Also not conjugated if belongs to a puckering ring\n        bond_at_puckering_ring = False\n        for ring in mol.rings:\n            if ring.type < 4 and ring.has((bond.atm1,bond.atm2)):\n                bond_at_puckering_ring = True\n                break\n        if bond_at_puckering_ring: continue\n\n        # special conjugation through ring(N=C)-N-H\n        # THIS PART SHOULD BE REVISITED WITH \"RING\" BONDTYPE IN FUTURE\n        is_ring_NCNH = False\n        if (bond.atm1 in mol.atms_aro and bond.atm2 not in mol.atms_aro) or \\\n           (bond.atm2 in mol.atms_aro and bond.atm1 not in mol.atms_aro):\n            # i: ring-member connected to other branch\n            # j: non-ring-member connected to i\n            if (bond.atm1 in mol.atms_aro and bond.atm2 not in mol.atms_aro):\n                i,j = (bond.atm1,bond.atm2)\n            else:\n                i,j = (bond.atm2,bond.atm1)\n                \n            type_i = ATYPES[mol.atms[i].atype]\n            type_j = ATYPES[mol.atms[j].atype]\n            if mol.atms[j].has_H and (type_i,type_j) == ('C','N'):\n                for k,dumm in mol.atms[i].bonds: #from C\n                    if mol.in_same_ring(i,k) == 0 or k == j: continue\n                    if (ATYPES[mol.atms[k].atype] == 'N') and (mol.atms[k].hyb != 3):\n                        is_ring_NCNH = True\n                        break\n                    \n                #for l,dumm in mol.atms[j].bonds: #from N\n                #    if l == i: continue\n                #    if l in mol.atms_aro:\n                #        is_ring_NCNH = False #override this rule if ringNC-NH-aro\n                #        break\n\n        if is_ring_NCNH:\n            print(\"Torsion around %s-%s assigned as conjugated by [ring N=C]-N-H rule\"%(mol.atms[bond.atm1].name,mol.atms[bond.atm2].name))\n            mol.bonds[ibond].is_conjugated = True\n            continue\n\n        # also skip if is part of >= 7-membered ring (whether aromatic or not)\n        # because conjugation start to break (more influenced by neighbors than conjugation)\n        # THIS PART SHOULD BE REVISITED WITH \"RING\" BONDTYPE IN FUTURE\n        minimum_ring_size = 100\n        for ring in mol.rings:\n            if ring.has((bond.atm1,bond.atm2)):\n                if ring.natms < minimum_ring_size:\n                    minimum_ring_size = ring.natms\n        if minimum_ring_size < 100 and minimum_ring_size > 6:\n            continue\n\n        # simpler logic over-predicts conjugated rings\n        #if mol.in_same_ring(bond.atm1,bond.atm2) == 1: continue\n\n        #print( \"assign conjugation: \", mol.atms[bond.atm1].name, mol.atms[bond.atm2].name,\n        #       (bond.atm1,bond.atm2) in mol.biaryl_pivots or \\\n        #       (bond.atm2,bond.atm1) in mol.biaryl_pivots,\n        #       ACLASS_ID[mol.atms[bond.atm1].aclass] in CONJUGATING_ACLASSES,\n        #       ACLASS_ID[mol.atms[bond.atm2].aclass] in CONJUGATING_ACLASSES)\n\n        #CONJUGATING_ACLASSES doesn't include Nad3, which in some structure \n        #can form conjugate bond with aromatic rings.\n        #Added Nad3 to CONJUGATING_ACLASSES. The conjugation will be determined \n        #according to the planarity of the initial conformation.\n        #GZ, Aug,20,2020\n        if ACLASS_ID[mol.atms[bond.atm1].aclass] not in CONJUGATING_ACLASSES or \\\n           ACLASS_ID[mol.atms[bond.atm2].aclass] not in CONJUGATING_ACLASSES: continue\n\n        if ((bond.atm1,bond.atm2) in mol.biaryl_pivots) or \\\n           ((bond.atm2,bond.atm1) in mol.biaryl_pivots):\n           continue      \n        \n        #Note: we need to be careful about assigning conjugated type to a single bond.\n        # especially for (C=O)-NH-CR cases, in some cases NH is conjugated with C=O but \n        # NH-CR is not conjugated. e.g. APAJIL from CSD.\n        # Use the dihedral angle as a second check, if the angle is clearly not planar,\n        # don't assign it as conjugated bond.\n        # GZ, July,6,2020\n        if bond.order == 1 and (not mol.atms[bond.atm1].is_H) \\\n            and (not mol.atms[bond.atm2].is_H):\n            if mol.option.opt.infer_conjugation and not is_planar(mol, bond.atm1, bond.atm2):\n                mol.bonds[ibond].is_conjugated = False #don't assign it conjugated \n                continue\n\n        #Note: any bond reaches at this point will be assigned as conjugated. \n        #GZ, July,6,2020\n        mol.bonds[ibond].is_conjugated = True\n\n# Define \"CHI\"s\ndef define_rotable_torsions(mol):\n    mol.chiatms = []\n    mol.chitypes = []\n    mol.chiextra = \"\"\n\n    hapol_torsion_id = []\n    hpol_torsion_type = [0 for k in mol.torsions]\n\n    # 1. First get list of hydrogen torsions\n    for i,torsion in enumerate(mol.torsions):\n        aclasses = [ACLASS_ID[mol.atms[atm].aclass] for atm in torsion]\n        # Apolar hydrogen torsions\n        if (aclasses[0] in ACLASS_HAPOL) or (aclasses[3] in ACLASS_HAPOL):\n            hapol_torsion_id.append(i)\n\n        # PolarH torsions\n        elif (aclasses[0] in ACLASS_HPOL) and (aclasses[3] not in ACLASS_HPOL):\n            stem = mol.atms[torsion[1]]\n            if stem.hyb == 2:\n                if len(stem.bonds) < 3:\n                    hpol_torsion_type[i] = 2\n            elif stem.hyb == 3: #mol.torsion_orders[i] == 1:\n                hpol_torsion_type[i] = 3\n\n        elif (aclasses[3] in ACLASS_HPOL) and (aclasses[0] not in ACLASS_HPOL):\n            stem = mol.atms[torsion[2]]\n            if stem.hyb == 2:\n                if len(stem.bonds) < 3:\n                    hpol_torsion_type[i] = 2\n            elif stem.hyb == 3: #mol.torsion_orders[i] == 1:\n                hpol_torsion_type[i] = 3\n\n    # 1-2. Get estimations of num_H_conf\n    num_H_confs = 1\n    covered = []\n    for i,atms in enumerate(mol.torsions):\n        if (atms[1],atms[2]) in covered or (atms[2],atms[1]) in covered: continue\n        if hpol_torsion_type[i] == 2: num_H_confs *= 6\n        elif hpol_torsion_type[i] == 3: num_H_confs *= 9\n        covered.append((atms[1],atms[2]))\n        \n    #print 'Total num_H_conf: ', num_H_confs\n    if num_H_confs <= mol.max_confs: mol.chiextra = \"1 20\"\n    else: mol.chiextra = \"0\"\n\n    # 2. CHI assignment; read-in from mol.option\n    # mol.torsions SHOULD have been ordered such that\n    # heavyatom-only comes first followed by H-containing ones\n    ring_cuts = []\n    for ring in mol.rings: ring_cuts.append(ring.cut_bond)\n\n    covered = []\n    for i,atms in enumerate(mol.torsions):\n        atm0 = mol.atms[atms[0]]\n        atm1 = mol.atms[atms[1]]\n        atm2 = mol.atms[atms[2]]\n        atm3 = mol.atms[atms[3]]\n        #GZ, make torsion around CSQ @ CSQ non-rotatable, Sep 3, 2020\n        if mol.in_same_ring(atms[1],atms[2]) and ACLASS_ID[atm1.aclass] == \"CSQ\" and ACLASS_ID[atm2.aclass] == \"CSQ\":\n            continue\n        border = mol.bond_order(atms[1],atms[2])\n\n        if (atms[1],atms[2]) in covered or (atms[2],atms[1]) in covered: continue #avoid\n        if ((atm0.root != atms[1]) and (atm1.root != atms[0])) or ((atm2.root != atms[3]) and (atm3.root != atms[2])): continue\n            \n        if atm1.root == atms[2]:\n            atms_ordered = [atms[3],atms[2],atms[1],atms[0]] #last is tipatm\n        elif atm2.root == atms[1]:\n            atms_ordered = [atms[0],atms[1],atms[2],atms[3]] #last is tipatm\n        else:\n            continue\n\n        # avoid if any of bonds defined as cut_bond\n        if (atms[0],atms[1]) in ring_cuts or (atms[1],atms[0]) in ring_cuts or \\\n           (atms[1],atms[2]) in ring_cuts or (atms[2],atms[1]) in ring_cuts or \\\n           (atms[2],atms[3]) in ring_cuts or (atms[3],atms[2]) in ring_cuts:\n            continue\n        \n        # why did I put this logic here...?\n        # check if the torsion is non-ATorder but connected to ATorder\n        FT_connected = False\n        for j in range(len(atms)-1):\n            a1,a2 = atms[j],atms[j+1]\n            if a1 in mol.ATorder and a2 in mol.ATorder: continue\n            if (mol.atms[a1].root not in [a2,a1]) and (mol.atms[a2].root not in [a1,a2]):\n                FT_connected = True\n                break\n        if FT_connected: continue\n\n        covered.append((atms[1],atms[2]))\n    \n        is_biaryl_pivot = ((atms[1],atms[2]) in mol.biaryl_pivots) or \\\n                          ((atms[2],atms[1]) in mol.biaryl_pivots)\n\n        # Bug fix with biaryl not defined as CHI: Oct17 2018 \n        if ((atms[1] in mol.atms_aro) and (atms[2] in mol.atms_aro)):\n            if border>1: continue\n            same_ring_order = mol.in_same_ring(atms[1],atms[2])\n            if same_ring_order == 4:\n                continue # also skip if belongs to the same \"aromatic\" ring\n            elif same_ring_order == 0: #not in same ring\n                if not mol.option.opt.report_ringring_chi and is_biaryl_pivot:\n                    continue\n\n        # below are optional\n        # Apolar hydrogen chis\n        if (not mol.option.opt.report_Hapol_chi) and (i in hapol_torsion_id): continue \n    \n        if (mol.bond_order(atms[1],atms[2]) > 1):\n            atype1 = ACLASS_ID[atm1.aclass]\n            atype2 = ACLASS_ID[atm2.aclass]\n            is_amide_bond = ((atype1 == 'Nad') and (atype2 in ['CDp','CRb'])) or \\\n                            ((atype2 == 'Nad') and (atype1 in ['CDp','CRb']))\n\n            #is_aliphatic_bond = ((atype1 == 'CD1') and (atype2 == 'CD1') and \\\n            #                     (atms[1] not in mol.atms_ring) and (atms[2] not in mol.atms_ring))\n\n            #print atype1, atype2, is_amide_bond\n            #print( mol.atms[atms[1]].name,mol.atms[atms[2]].name,is_aliphatic_bond)\n            #if is_aliphatic_bond:\n            #    pass\n            \n            ## always skip a bond in a same aromatic ring\n            if mol.in_same_ring(atms[1],atms[2]):\n                continue\n            \n            if (mol.option.opt.report_amide_chi):\n                if (not is_amide_bond): continue\n            elif (not mol.option.opt.report_nbonded_chi and not is_biaryl_pivot):\n                continue\n\n        # skip conjugated polarH chi\n        elif mol.bond_conjugated(atms[1],atms[2]):\n            nH1 = 0\n            for j,order in atm1.bonds:\n                if mol.atms[j].is_H: nH1+=1\n            nH2 = 0\n            for j,order in atm2.bonds:\n                if mol.atms[j].is_H: nH2+=1\n\n            if nH1 == len(atm1.bonds)-1 or nH2 == len(atm2.bonds)-1:\n                continue\n\n        if (not mol.option.opt.report_puckering_chi) and \\\n           (atms[1] in mol.atms_puckering) and (atms[2] in mol.atms_puckering):\n            continue\n\n        mol.chiatms.append(atms_ordered)\n        \n        if hpol_torsion_type[i] == 2: #sp2\n            mol.chitypes.append('sp2')\n        elif hpol_torsion_type[i] == 3: #sp3\n            mol.chitypes.append('sp3')\n        elif i in hapol_torsion_id: #sp3\n            mol.chitypes.append('sp3H')\n        #elif (atms[1] in mol.atms_puckering) and (atms[2] in mol.atms_puckering):\n        #    mol.chitypes.append('pucker') #turn this functionality for now... add separate flag for this behavior\n        else:\n            mol.chitypes.append('')\n", "meta": {"hexsha": "a01969696bc62774ac69c4ec4b7d580d49c56ab4", "size": 39149, "ext": "py", "lang": "Python", "max_stars_repo_path": "vscreenml_v2/generic_potential/SetupTopology.py", "max_stars_repo_name": "gandrianov/VScreenML_v2", "max_stars_repo_head_hexsha": "6c036209b7851bd7340c304432164c1dcb2974c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vscreenml_v2/generic_potential/SetupTopology.py", "max_issues_repo_name": "gandrianov/VScreenML_v2", "max_issues_repo_head_hexsha": "6c036209b7851bd7340c304432164c1dcb2974c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vscreenml_v2/generic_potential/SetupTopology.py", "max_forks_repo_name": "gandrianov/VScreenML_v2", "max_forks_repo_head_hexsha": "6c036209b7851bd7340c304432164c1dcb2974c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-12T06:05:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-12T06:05:18.000Z", "avg_line_length": 41.036687631, "max_line_length": 139, "alphanum_fraction": 0.5587626759, "include": true, "reason": "import numpy,import scipy", "num_tokens": 11289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.1532084761136403}}
{"text": "import re\nimport math\nimport numpy\ntry:\n    from galpy.util import bovy_plot\nexcept ImportError:\n    import bovy_plot #BOVY: COPY IN LOCAL VERSION\n_ZSOLAR= 0.019\n_LOGTESUN= numpy.log10(5777)\n_LOGGSUN= numpy.log10(27400.)\nclass Isochrone:\n    \"\"\"Template for any Isochrone type class\"\"\"\n    def __init__(self):\n        \"\"\"\n        NAME:\n           __init__\n        PURPOSE:\n           initialize\n        INPUT:\n        OUTPUT:\n        HISTORY:\n           2011-04-27 - Written - Bovy (NYU)\n        \"\"\"\n        raise NotImplementedError(\"'__init__' not implemented for this isochrone\")\n\n    def __call__(self,logage,Z=None,feh=None,afe=None,maxm=None,\n                 stage=None):\n        \"\"\"\n        NAME:\n           __call__\n        PURPOSE:\n           get a single isochrone from the library\n        INPUT:\n           logage - log_10 age\n           Z= or feh= metallicity (use Z_\\odot=0.019)\n           afe= None (not supported for Padova)\n           maxm= maximum mass to consider (m_ini)\n           stage= if set, only return this evolutionary stage \n                  (if this exists for this isochrone libary)\n        OUTPUT:\n           isochrone\n        HISTORY:\n           Written - Bovy (NYU)\n        \"\"\"\n        raise NotImplementedError(\"'__call__' method for this isochrone is not implemented\")\n\n    def Zs(self):\n        \"\"\"\n        NAME:\n           Zs\n        PURPOSE:\n           Return the loaded metallicities\n        INPUT:\n        OUTPUT:\n        HISTORY:\n           2011-04-27 - Written - Bovy (NYU)\n        \"\"\"\n        return self._ZS\n\n    def logages(self):\n        \"\"\"\n        NAME:\n           logages\n        PURPOSE:\n           Return the loaded log_10 ages\n        INPUT:\n        OUTPUT:\n        HISTORY:\n           2011-04-27 - Written - Bovy (NYU)\n        \"\"\"\n        return self._logages\n\n    def filters(self):\n        \"\"\"\n        NAME:\n           filters\n        PURPOSE:\n           Return the supported filters\n        INPUT:\n        OUTPUT:\n        HISTORY:\n           2011-04-27 - Written - Bovy (NYU)\n        \"\"\"\n        return self._filters\n###################################PLOTTING####################################\n    def plot(self,logage,*args,**kwargs):\n        \"\"\"\n        NAME:\n           plot\n        PURPOSE:\n           plot an individual isochrone, or a set of isochrones\n        INPUT:\n           logage - log_10 age or list thereof\n           Z= metallicity or list\n           feh= metallicity or list (use Z_\\odot=0.019)\n           afe= not supported for Padova\n           d1= x dimension (for color write 'J-Ks')\n           d2= y dimension\n           maxm= maximum mass to plot\n           stage= if set, only return this evolutionary stage \n                  (if this exists for this isochrone libary)\n           ignore_gaps= if True, ignore non-existant isochrones\n           +bovy_plot.bovy_plot keywords\n        OUTPUT:\n           plot to output device\n        HISTORY:\n           2011-04-27 - Written - Bovy (NYU)\n        \"\"\"\n        if not isinstance(logage,(list,numpy.ndarray)) \\\n                and not (('Z' in kwargs \\\n                              and isinstance(kwargs['Z'],(list,numpy.ndarray)))\\\n                             or ('feh' in kwargs \\\n                                     and isinstance(kwargs['feh'],numpy.ndarray))):\n            return self._plot_single(logage,*args,**kwargs)\n        #Do we have Z or FeH?\n        if not 'Z' in kwargs and 'feh' in kwargs: usefeh= True\n        else: usefeh= False\n        if not isinstance(logage,(list,numpy.ndarray)) and usefeh:\n            logage= numpy.array([logage for ii in range(len(kwargs['feh']))])\n        elif not isinstance(logage,(list,numpy.ndarray)):\n            logage= numpy.array([logage for ii in range(len(kwargs['Z']))])\n        #Handle Z etc.\n        if 'feh' in kwargs:\n            if isinstance(kwargs['feh'],(list,numpy.ndarray)):\n                fehs= kwargs['feh']\n            else:\n                fehs= numpy.array([kwargs['feh'] for ii in range(len(logage))])\n        else:\n            fehs= [None for ii in range(len(logage))]\n        if 'Z' in kwargs:\n            if isinstance(kwargs['Z'],(list,numpy.ndarray)):\n                ZS= kwargs['Z']\n            else:\n                ZS= numpy.array([kwargs['Z'] for ii in range(len(logage))])\n        else: ZS= [None for ii in range(len(logage))]\n        if usefeh and not len(logage) == len(fehs):\n            raise IOError(\"When both logage and feh are given as arrays they need to have the same length\")\n        elif not usefeh and not len(logage) == len(ZS):\n            raise IOError(\"When both logage and Z are given as arrays they need to have the same length\")\n        #Plot first\n        if usefeh: kwargs['feh']= fehs[0]\n        else: kwargs['Z']= ZS[0]\n        out= self._plot_single(logage[0],*args,**kwargs)\n        kwargs['overplot']= True\n        for ii in range(1,len(logage)):\n            kwargs['Z']= ZS[ii]\n            kwargs['feh']= fehs[ii]\n            self._plot_single(logage[ii],*args,**kwargs)\n        return out\n\n    def _plot_single(self,logage,*args,**kwargs):\n        #kwargs\n        Z= kwargs.pop('Z',None)\n        feh= kwargs.pop('feh',None)\n        afe= kwargs.pop('afe',None)\n        maxm= kwargs.pop('maxm',None)\n        stage= kwargs.pop('stage',None)\n        d1= kwargs.pop('d1',self._filters[0]+'-'+self._filters[1])\n        d2= kwargs.pop('d2',self._filters[0])\n        ignore_gaps= kwargs.pop('ignore_gaps',False)\n        #get isochrone\n        try:\n            iso= self(logage,Z=Z,feh=feh,afe=afe,maxm=maxm,stage=stage)\n        except IOError:\n            if ignore_gaps: return None\n            else: \n                raise IOError(\"No isochrone found for this logage/metallicity combination\\nUse ignore_gaps=True to ignore non-existant isochrones\")\n        #get dimensions\n        colorx= re.split(r'-',d1)\n        if len(colorx) == 2: #d1 is a color\n            x= iso[colorx[0]]-iso[colorx[1]]\n        else:\n            x= iso[d1]\n        colory= re.split(r'-',d2)\n        if len(colory) == 2: #d2 is a color\n            y= iso[colory[0]]-iso[colory[1]]\n        else:\n            y= iso[d2]\n        #Put in default labels\n        if not kwargs.get('overplot',False):\n            kwargs['xlabel']= kwargs.get('xlabel',r'$'+d1+'$')\n            kwargs['ylabel']= \\\n                kwargs.get('ylabel',\n                    r'$M_{'+d2+'}$' if d2 in self._filters else r'$'+d2+'$')\n            if not 'yrange' in kwargs and d2 in self._filters:\n                kwargs['yrange']= [numpy.amax(y)+0.3,numpy.amin(y)-0.3]\n        #plot\n        return bovy_plot.bovy_plot(x,y,*args,**kwargs)\n\ndef Z2FEH(z,zsolar=None,parsec=False):\n    \"\"\"Convert Z to FeH assuming zsolar\"\"\"\n    if parsec:\n        if zsolar is None: zsolar= 0.0152\n        return numpy.log10(z/(1.-0.2485-2.78*z))-math.log10(zsolar/(1.-0.2485-2.78*zsolar))\n    else:\n        if zsolar is None: zsolar= _ZSOLAR\n        return numpy.log10(z)-math.log10(zsolar)\n\ndef FEH2Z(feh,zsolar=None,parsec=False):\n    \"\"\"Convert FeH to Z assuming zsolar\"\"\"\n    if parsec:\n        if zsolar is None: zsolar= 0.0152\n        zx= 10.**(feh+math.log10(zsolar/(1.-0.2485-2.78*zsolar)))\n        return (zx-0.2485*zx)/(2.78*zx+1.)\n    else:\n        if zsolar is None: zsolar= _ZSOLAR\n        return 10.**(feh+math.log10(zsolar))\n\ndef logg(logL,logTe,mass):\n    \"\"\"\n    NAME:\n       logg\n    PURPOSE:\n       calculate log g from luminosity, teff, and mass\n    INPUT:\n       logL - log Luminosity (solar units)\n       logTe- log effective temperature (log K)\n       mass - mass (solar units)\n    OUTPUT:\n       log g (log cm/s^2)\n    HISTORY:\n       2012-08-16 - Written - Bovy (IAS)\n    \"\"\"\n    logR= -2.*(logTe-_LOGTESUN)+0.5*logL\n    return numpy.log10(mass)-2.*logR+_LOGGSUN\n\ndef dict2recarray(dict):\n    nEntries= len(dict.keys())\n    nOut= len(dict[dict.keys()[0]])\n    out= numpy.zeros(nOut,dtype={'names':dict.keys(),\n                                 'formats':[numpy.float64 for ii in range(nEntries)]})\n    for ii in range(nEntries):\n        out[dict.keys()[ii]]= dict[dict.keys()[ii]]\n    return out.view(numpy.recarray)\n", "meta": {"hexsha": "fb2b340d9f1faf6b89b7f2db18f6dae72ae0c474", "size": 8102, "ext": "py", "lang": "Python", "max_stars_repo_path": "isodist/Isochrone.py", "max_stars_repo_name": "jobovy/isodist", "max_stars_repo_head_hexsha": "1f04716cda6a6427f6ca70a0d9740dcbd07cc1e7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "isodist/Isochrone.py", "max_issues_repo_name": "jobovy/isodist", "max_issues_repo_head_hexsha": "1f04716cda6a6427f6ca70a0d9740dcbd07cc1e7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-11-17T05:02:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-15T13:42:50.000Z", "max_forks_repo_path": "isodist/Isochrone.py", "max_forks_repo_name": "jobovy/isodist", "max_forks_repo_head_hexsha": "1f04716cda6a6427f6ca70a0d9740dcbd07cc1e7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-05-25T20:30:58.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-04T10:08:54.000Z", "avg_line_length": 34.4765957447, "max_line_length": 147, "alphanum_fraction": 0.5409775364, "include": true, "reason": "import numpy", "num_tokens": 2173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.25683199138751883, "lm_q1q2_score": 0.15318311268466703}}
{"text": "__author__ = 'DGriffith, ARamkilowan'\n\n\"\"\" This module provides a variety of utilities related to radiometry, including, but not limited to\n- Creating, writing and reading of MODTRAN-format .flt (filter) files commonly used to to represent\n    spectral power/density functions such as transmittances, reflectance or spectral responsivity functions (SRF).\n    The original purpose was to specify sensor spectral response functions (i.e. more than just a \"filter\").\n-\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\nimport io\nimport matplotlib.pyplot as plt\nimport easygui  # for simple file/open dialogs and such\nimport re\n\nimport libraddask.rad.xd as xd\n\n\"\"\" This module provides much of functionality related radiometry required by MORTICIA.\nIncluded here is functionality for :\n1) Interfacing to radiative transfer codes.\n2) Dealing with spectral filtering and convolution\n3) Creation, reading and writing of MODTRAN-style flt filter/SRF definitions\n\nTO DO : Check that MODTRAN can read the .flt files created using the Flt class here\n\"\"\"\n\n#_micronsymbol = u\"\\u00B5\"\n# _micrometres = _micronsymbol + u\"m\"\n\n# Micron symbol can be encoded in UTF-8 with\n# _micronsymbol = u'\\xB5'.encode('UTF-8')\n_micronsymbol = '\\x00B5'\n_micrometres = _micronsymbol + \"m\"\n\n\ndef srfgen(center, fwhm, n=101, shape='gauss', yedge=0.001, wvmin=None, wvmax=None, centerflat=0.0,\n           oob=np.nextafter(0.0, 1), peakval=1.0, units='nm'):\n    \"\"\" Generate a spectral filter or spectral response function of various shapes\n\n    :param center: center wavelength of the filter in nm\n    :param fwhm: full width at half maximum of the filter  in nm\n    :param n: number of spectral samples in the filter (minimum of 3, default 101), should be odd\n    :param shape: filter shape, one of 'gauss', 'bartlett', 'welch', 'cosine', 'box', 'cos^2' (default 'gauss')\n    :param yedge: minimum y-value at the limits of the filter (default 0.001). No filter values below this threshold\n    :param wvmin: extend spectral definition by adding a single point at (wvmin, oob)\n    :param wvmax: exptend spectral definition by adding a single point at (wvmax, oob)\n    :param centerflat: opens a flat region in the centre of filter having a width of centerflat nm\n    :param oob: out-of-band leakage, default 0.0, must be <= yedge\n    :param peakval: simply scales the peak of the filter function to this value (default 1.0)\n    :param units: spectral axis units, either 'nm', 'cm^-1' or 'um' (nanometers, wavenumber per cm or microns)\n        will be returned\n    :return: wvlnm, y, wvn, wvlum (wavelengths in nm, filter values, wavenumbers per cm and wavelengths in microns)\n    \"\"\"\n    if n < 3:\n        raise ValueError('Input parameter n to rad.srfgen must be greater than 3.')\n    if oob > yedge:\n        raise ValueError('Input parameter oob to rad.srfgen must be smaller than paramter yedge (default 0.001).')\n    # force an odd number of points\n    if not np.mod(n, 2.0):\n        n += 1\n    n2 = int((n-1)/2)  # mid-point\n    x = np.arange(-n2, n2+1, 1.0)  # relative x-coordinates for filter\n    shape = shape.lower()\n    if shape == 'gauss' or shape == 'gaussian':\n        sigma = np.sqrt(-n2**2.0 / 2.0 / np.log(yedge))  # scalar standard deviation\n        nfwhm = 2.0 * np.sqrt(2.0 * np.log(2.0)) * sigma  # normalized fwhm (scalar)\n        y = np.exp(-x**2.0 / 2.0 / sigma**2)\n    elif shape == 'bartlett' or shape == 'triangle':\n        fudge = n2 * (1+yedge+(yedge/100.0))\n        nfwhm = n2 + (yedge * fudge)  # normalized fwhm\n        y = 1.0 - (abs(x) / nfwhm)  # bartlett\n        y[y<0] = np.nextafter(0.0, 1)  # in case of negative samples, make very small positive value\n    elif shape == 'welch':\n        fudge = n2 * (0.5+(yedge*0.378))\n        alph = n2 + (yedge * fudge)\n        nfwhm = np.sqrt(2.0) * alph  # normalized fwhm\n        y = 1 - ((x ** 2.0) / (alph ** 2.0))  # welch\n        y[y<0] = np.nextafter(0.0, 1)  # in case of negative samples, make very small positive value\n    elif shape == 'cosine':\n        fudge = n2 * (.6365+(yedge*.5))\n        alph = n2 + (yedge * fudge)\n        nfwhm = (4.0/3.0) * alph  # normalized fwhm\n        y = np.cos((np.pi * x) / (2.0 * alph))\n        y[y<0] = np.nextafter(0.0, 1)  # in case of negative samples, make very small positive value\n    elif shape == 'cos^2' or shape == 'cosquared':\n        fudge = n2 * (.6365+(yedge*.5))\n        alph = n2 + (yedge * fudge)  # calculate alpha\n        nfwhm = alph  # normalized fwhm\n        y = np.cos((np.pi * x) / (2.0 * alph))**2\n    elif shape == 'box' or shape == 'tophat':\n        y = np.ones(x.shape)\n        y[0] = np.nextafter(0.0, 1)\n        y[-1] = np.nextafter(0.0, 1)\n        nfwhm = np.trapz(y)\n    else:\n        raise ValueError('Unknown SRF/filter shape input to rad.srfgen')\n    delta = fwhm / nfwhm  # Determine sample delta (scalar)\n    y[y<yedge] = oob  # suppress values dropping below the edge threshold\n    wvl = (np.ones(x.shape, dtype=np.float) * center) + (delta * x)\n    if centerflat:  # Open a central flat region simply by shifting the wvl-coordinates\n        # print(n2, type(n2))\n        # print(centerflat, type(centerflat))\n        # print(wvl[:n2+1]-centerflat/2, wvl[n2:]+centerflat/2)\n        # print(type(wvl[:n2+1]-centerflat/2), type(wvl[n2:]+centerflat/2))\n\n\n        wvl = np.hstack((wvl[:n2+1]-centerflat/2, wvl[n2:]+centerflat/2))\n        y = np.hstack((y[:n2+1], y[n2:]))\n    if wvmin and wvmin < wvl[0]:  # insert a point at lower wavelength extremity\n        wvl = np.hstack((wvmin, wvl))\n        y = np.hstack((oob, y))\n    if wvmax and wvmax > wvl[-1]:  # insert a point at upper wavelength extremity\n        wvl = np.hstack((wvl, wvmax))\n        y = np.hstack((y, oob))\n    if units == 'cm^-1':  # wavenumber per cm\n        wvn = wvl\n        wvlnm = 1.0e7 / wvn\n        wvlum = wvlnm / 1000.0\n    elif units == 'nm':  # wavelength in nm\n        wvlnm = wvl\n        wvn = 1.0e7 / wvlnm\n        wvlum = wvlnm / 1000.0\n    elif units == 'um' or units == _micrometres:  # wavelength in microns\n        wvlum = wvl\n        wvlnm = 1000.0 * wvlum\n        wvn = 1e7 / wvlnm\n    else:\n        raise ValueError('Wavelength/wavenumber units for MODTRAN .flt definitions must be \"cm^1\", \"nm\" or \"um\".')\n    y *= peakval  # finally, scale the peak value\n    return wvlnm, y, wvn, wvlum\n\n\ndef tophat(center, fwhm, delta=0.0, wvmin=None, wvmax=None, oob=0.0, units='nm'):\n    \"\"\" Return tophat/box filter defined by 6 points\n    Can also specify out-of-band values and extreme limits, which adds upper and lower bound points\n\n    :param center: center wavelength in nm\n    :param fwhm: full width at half max in nm\n    :param delta: smallest x-coordinate increment, default see np.nextafter\n    :param wvmin: minimum wavelength to reach default None\n    :param wvmax: maximum wavelength to reach default None\n    :param oob: out-of-band leakage\n    :param units: spectral axis units, either 'nm', 'cm^-1' or 'um' (nanometers, wavenumber per cm or microns)\n        will be returned\n    :return: wvlnm, y, wvn, wvlum (wavelengths in nm, filter values, wavenumbers per cm and wavelengths in microns)\n    \"\"\"\n    edgelo = center - fwhm/2.0\n    edgehi = center + fwhm/2.0\n    if delta != 0.0:\n        wvl = np.array([edgelo-delta, edgelo, edgelo+delta, edgehi-delta, edgehi, edgehi+delta])\n    else:\n        wvl = np.array([np.nextafter(edgelo, -1), edgelo, np.nextafter(edgelo, 1),\n                        np.nextafter(edgehi, -1), edgehi, np.nextafter(edgehi, 1)])\n    y = np.array([oob, 0.5, 1.0, 1.0, 0.5, oob])\n    if wvmin:\n        wvl = np.hstack((wvmin, wvl))\n        y = np.hstack((oob, y))\n    if wvmax:\n        wvl = np.hstack((wvl, wvmax))\n        y = np.hstack((y, oob))\n    if units == 'cm^-1':  # wavenumber per cm\n        wvn = wvl\n        wvlnm = 1.0e7 / wvn\n        wvlum = wvlnm / 1000.0\n    elif units == 'nm':  # wavelength in nm\n        wvlnm = wvl\n        wvn = 1.0e7 / wvlnm\n        wvlum = wvlnm / 1000.0\n    elif units == 'um' or units == _micrometres:  # wavelength in microns\n        wvlum = wvl\n        wvlnm = 1000.0 * wvlum\n        wvn = 1e7 / wvlnm\n    else:\n        raise ValueError('Wavelength/wavenumber units for MODTRAN .flt definitions must be \"cm^1\", \"nm\" or \"um\".')\n    return wvl, y, wvn, wvlum\n\n\nclass Flt(object):\n    \"\"\" Encapsulates a MODTRAN-style .flt spectral response function/filter function definition file.\n\n    \"\"\"\n\n    def __init__(self, name, units='nm', filterheaders=[], filters=[], centers=[],\n                 fwhms=[], shapes=['gauss'], yedges=[0.001], centerflats=[0.0], peakvals=[1.0], wvmins=[], wvmaxs=[],\n                 oobs=[np.nextafter(0.0, 1)]):\n        \"\"\" Create a filter definition object (MODTRAN flt style)\n        Input name is mandatory. All other inputs are optional, but the filterheaders list must have the same number of\n        string elements as the number of filters. Also, either the filters are given explicitly in the filters input, or\n        a list of filter definitions are provided for use with rad.srfgen().\n        If not empty, inputs centers through to oobs must be either scalar or have the same number of list elements as\n        the filterheaders list. If scalar, the value will be replicated up to the number of filterheader values.\n\n        :param name: Name of the set of filters. If the filterheaders input to this constructor function\n            is empty, an attempt will be made to read the data from a file called name + '.flt'\n        :param units: Spectral coordinate units for the filter, 'nm', 'um' or 'cm^-1'\n        :param filterheaders: List of strings, one header for each filter/SRF in the set.\n        :param filters: A list of numpy arrays. Each list element must comprise a 2-column numpy array with the\n            spectral coordinate (wavelength in nm or micron or wavenumber per cm) in the first column and the filter\n            magnitude in the second column.\n        :param centres: rather than provide filters, the inputs to rad.srfgen can be provided, this is a list of center\n            wavelengths in nm\n        :param fwhms: list of full width at half maximum in nm\n        :param shapes: list of strings providing the shapes of the filters (see rad.srfgen for alternatives)\n        :param yedges: list of yedge values (see rad.srfgen)\n        :param centerflats: list of centerflat values (see rad.srfgen). Note that giving a centerflat value adds this\n            amount ot the fwhm of the filters (broadens the resulting width to centerflat + fwhm)\n        :param peakvals: list of peak values of the filters\n        :param wvmins: list of minimum wavelength limits in nm\n        :param wvmaxs: list of maximum wavelength limits in nm\n        :param oobs: list of out-of-band leakage values\n        :return: MODTRAN-style filter/SRF object\n        \"\"\"\n        self.name = name\n        if name[-4:].lower() != '.flt':\n            self.filename = name + '.flt'\n        else:\n            self.filename = name\n        if not filterheaders:  # Attempt to read from a file\n            self.read(self.filename)\n            return\n        # Check the units input and set up the file header\n        if units == 'cm^-1':\n            self.unitsheader = 'W' # wavenumber\n        elif units == 'nm':\n            self.unitsheader = 'N'\n        elif units == 'um' or units == _micrometres:\n            self.unitsheader = 'M'\n        else:\n            raise ValueError('Wavelength/wavenumber units for MODTRAN .flt definitions must be \"cm^1\", \"nm\" or \"um\".')\n        self.units = units\n        self.fileheader = self.unitsheader + ' ' + self.name\n        #if len(filterheaders) != len(filters):\n        #    raise ValueError('Number of filterheaders must equal number of filters when creating .flt objects.')\n        self.filterheaders = filterheaders\n        if filters and centers:\n            raise ValueError('Do not give both explicit filter definitions and rad.srfgen definitions for rad.flt.')\n        nfilters = len(filterheaders)\n        self.nfilters = nfilters\n        if filters:\n            if len(filters) != nfilters:\n                raise ValueError('Number of filters must equal number of filter headers in rad.flt instantiation.')\n            self.filters = filters  # now fix the filters into the correct column order\n            for ifilt in range(nfilters):\n                if self.unitsheader == 'W':  # wavenumber\n                    # column order is wvnm, y, wvn, wvum\n                    self.filters[ifilt] = np.vstack((1.0e7/filters[ifilt][:,0], filters[ifilt][:,1],\n                                                     filters[ifilt][:,0], 1.0e7/filters[ifilt][:,0] / 1000.0)).T\n                elif self.unitsheader == 'N':\n                    self.filters[ifilt] = np.vstack((filters[ifilt][:,0], filters[ifilt][:,1],\n                                                     1.0e7 / filters[ifilt][:,0], filters[ifilt][:,0]/1000.0)).T\n                elif self.unitsheader == 'M':\n                    self.filters[ifilt] = np.vstack((1000.0*filters[ifilt][:,0], filters[ifilt][:,1],\n                                                     1.0e10 /filters[ifilt][:,0], filters[ifilt][:,0])).T\n            return  # filter definitions have been given explicitly\n        # Check that parameters are scalar or multiply them up to size\n        checklist = ['centers', 'fwhms', 'shapes', 'yedges', 'centerflats', 'peakvals', 'oobs']\n        for checkitem in checklist:\n            checkcall = 'use_' + checkitem + ' = Flt.checkparm(\"' + checkitem + '\", ' + checkitem + ', nfilters)'\n            exec(checkcall)\n        if wvmins and len(wvmins) == 1:\n            use_wvmins = wvmins * nfilters\n        elif wvmins and len(wvmins) != nfilters:\n            raise ValueError('Number of wvmins must equal number of filterheaders in rad.flt instantiation')\n        else:\n            use_wvmins = [[] for ie in range(nfilters)]\n        # Check wvmaxs\n        use_filters = []\n        if wvmaxs and len(wvmaxs) == 1:\n            use_wvmaxs = wvmaxs * nfilters\n        elif wvmaxs and len(wvmaxs) != nfilters:\n            raise ValueError('Number of wvmaxs must equal number of filterheaders in rad.flt instantiation')\n        else:\n            use_wvmaxs = [[] for ie in range(nfilters)]\n        for ifilt in range(nfilters):\n            # print(ifilt)\n            # print(len(centers ))\n            # print(len(fwhms ))\n            # print(len(shapes ))\n            # print(len(yedges ))\n            # print(len(wvmins ))\n            # print(len(use_wvmaxs ))\n            # print(len(centerflats ))\n            # print(len(oobs ))\n            # print(len(peakvals ))\n            wvl, y, wvn, wu = srfgen(center=centers[ifilt], fwhm=fwhms[ifilt], shape=shapes[ifilt],\n                                 yedge=yedges[ifilt], wvmin=wvmins[ifilt], wvmax=use_wvmaxs[ifilt],\n                                 centerflat=centerflats[ifilt], oob=oobs[ifilt], peakval=peakvals[ifilt])\n            use_filters.append(np.vstack((wvl, y, wvn, wu)).T)\n        self.filters = use_filters\n\n\n    @staticmethod  # Some input parameter checking for Flt constructor\n    def checkparm(parmname, parm, nfilters):\n        \"\"\" Input parameter checking for Flt constructor\n\n        :param parmname: Name of parameter fpr checking\n        :param parm: Parameter value\n        :param nfilters: Number of filters\n        :return: Checked parameter\n        \"\"\"\n        if len(parm) == 1:\n            parm *= nfilters\n        elif len(parm) != nfilters:\n            raise ValueError('Number of ' + parmname + ' must equal number of filterheaders in rad.flt instantiation')\n        return parm\n\n    def read(self, filename, name='Unknown'):\n        \"\"\" Read a .flt format spectral band filter definitions file (MODTRAN format)\n\n        :param filename:\n        :return: object of class Flt, if the file is a well-formatted MODTRAN-style .flt file\n        \"\"\"\n        isfloatnum = '^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$'  # regular expression to match a floating point number\n        if filename == '.flt':\n            filename = easygui.fileopenbox(msg='Please select a .flt file.', filetypes=[\"*.flt\"])\n        self.filename = filename\n        self.name = name\n        with open(filename, 'rt') as fltfil:\n            fileheader = fltfil.readline()\n            self.unitsheader = fileheader[0].upper()  # Must be W, N or M for wavenumber per cm, nm or microns\n            if self.unitsheader == 'W':\n                self.units = 'cm^-1'\n            elif self.unitsheader == 'N':\n                self.units = 'nm'\n            elif self.unitsheader == 'M':\n                self.units = _micrometres\n            else:\n                raise ValueError('File header for ' + filename + ' does not start with N, M or W as required for'\n                                                                 ' .flt files.')\n            self.name = fileheader[1:].strip()\n            self.fileheader = fileheader.strip()\n            self.filterheaders = []\n            self.filters = []\n            ifilter = 0  # count the filters\n            nexlin = fltfil.readline()\n            while nexlin:\n                self.filterheaders.append(nexlin.strip())\n                nexlin = fltfil.readline()\n                if not nexlin:\n                    break  # all done\n                slin = nexlin.split()  # split line up into a list of tokens at whitespace\n                thisfilterdata = np.array([])\n                self.filters.append([])\n                # if all tokens match\n                while all([re.match(isfloatnum, tok) for tok in slin]):  # all tokens a are numbers-this is a line of data\n                    # accumulate the data\n                    thelinedata = np.array(slin).astype(np.float)\n                    if len(thisfilterdata) != 0:\n                        thisfilterdata = np.vstack((thisfilterdata, thelinedata))\n                    else:\n                        thisfilterdata = thelinedata\n                    nexlin = fltfil.readline()\n                    if not nexlin:\n                        break  # all done\n                    slin = nexlin.split()  # split line up into a list of tokens at whitespace\n                # process the accumulated data depending on what the units are\n                if self.unitsheader == 'W':\n                    self.filters[ifilter] = np.vstack((1e7/thisfilterdata[:,1], thisfilterdata[:,1],\n                                                       thisfilterdata[:,0], 1e9/thisfilterdata[:,1])).T\n                elif self.unitsheader == 'N':\n                    self.filters[ifilter] = np.vstack((thisfilterdata[:,0], thisfilterdata[:,1],\n                                                       1e7/thisfilterdata[:,0], thisfilterdata[:,0]/1000.0)).T\n                elif self.unitsheader == 'M':\n                    self.filters[ifilter] = np.vstack((thisfilterdata[:,0]*1000.0, thisfilterdata[:,1],\n                                                       1e9/thisfilterdata[:,0], thisfilterdata[:,0])).T\n                ifilter += 1\n            self.nfilters = ifilter\n\n\n    def __repr__(self, format='  %f'):\n        \"\"\" Return representation of a .flt MODTRAN-style spectral filter or SRF. This is the same as the format in\n         the .flt file is written.\n\n        :param format: format in which to present the numeric data, default is '  %f'\n        :return: File representation of .flt object\n        \"\"\"\n        selfrep = self.fileheader + '\\n'\n        for (ifilt, filter) in enumerate(self.filters):\n            selfrep = selfrep + self.filterheaders[ifilt] + '\\n'\n            # Create a string buffer\n            # strbuff = io.StringIO.StringIO()\n            strbuff = io.StringIO()\n            # column ordering depends on original unit specification\n            if self.unitsheader == 'W':\n                np.savetxt(strbuff, self.filters[ifilt][:,[2,1,0]], fmt=format)\n            elif self.unitsheader == 'N':\n                np.savetxt(strbuff, self.filters[ifilt][:,[0,1,2]], fmt=format)\n            elif self.unitsheader == 'M':\n                np.savetxt(strbuff, self.filters[ifilt][:,[3,1,2]], fmt=format)\n            selfrep = selfrep + strbuff.getvalue()\n            strbuff.close()  # delete the buffer\n        return selfrep\n\n    def write(self, filename=None, format='  %f'):\n        \"\"\" Write a MODTRAN-style .flt file for this filter/SRF set\n\n        :param filename: Optional filename without extension. If not given, the filter name will be used with\n        :param format: Format specifier as for np.savetext for writing the data, default is '  %f'\n            extension .flt\n        :return: None\n        \"\"\"\n        selfrep = self.__repr__(format=format)\n        # Write the string to the file\n        if filename:\n            if filename[-4:].lower != '.flt':\n                filename = filename + '.flt'\n        else:\n            filename = self.filename\n        with open(filename, 'wt') as fltfile:\n            fltfile.write(selfrep)\n\n    def plot(self, filter_numbers = None):\n        \"\"\" Plot a MODTRAN-style set of filter/SRF curves.\n\n        :param filter_numbers: List of filter numbers to plot, defaults to all filters. Filter indices start at 0.\n\n        :return: None\n        \"\"\"\n        # plt.hold(True)\n        if filter_numbers is None:\n            filter_numbers = range(self.nfilters)\n        for ifilt in filter_numbers:\n            if self.unitsheader == 'W':\n                plt.plot(self.filters[ifilt][:, 2], self.filters[ifilt][:,1])\n            elif self.unitsheader == 'N':\n                plt.plot(self.filters[ifilt][:, 0], self.filters[ifilt][:,1])\n            elif self.unitsheader == 'M':\n                plt.plot(self.filters[ifilt][:, 3], self.filters[ifilt][:,1])\n        plt.title(self.name)\n        plt.ylabel('Spectral Response/Transmission')\n        if self.units == 'cm^-1':\n            plt.xlabel('Wavenumber [' + self.units + ']')\n        else:\n            plt.xlabel('Wavelength [' + self.units + ']')\n        if len(self.filterheaders) <= 12:\n            plt.legend(self.filterheaders, loc='best')\n        plt.grid()\n        # plt.hold(False)\n\n    def flt_as_xd(self):\n        \"\"\" Convert an Flt class object to a list of xarray DataArray objects\n\n        :return: The set of Flt filters as a list of xarray DataArray objects, with a wavelength coordinate\n            axis ('wvl', long_name = 'Wavelength'\n        \"\"\"\n        flt_list = []\n        for ifilt in range(self.nfilters):\n            wvl = xd.xd_identity(self.filters[ifilt][:,0], 'wvl', self.units)\n            #print(wvl)\n            flt_list.append(xr.DataArray(self.filters[ifilt][:,1], [wvl], name='srf',\n                                                attrs={'long_name': long_name['srf'],\n                                                       'labels': self.filterheaders[ifilt],\n                                                       'units': default_units['srf'],\n                                                       'title': self.name},\n                                                ))\n        return flt_list\n\n    def flt_as_xd_harmonised(self, quantity_name='srf', chn_start_index=0):\n        \"\"\" Convert the Flt class object into a single, wavelength-harmonised xr.DataArray.\n\n        :param quantity_name: The name of the quantity as defined the long_names variable in moglo.py. Defaults to\n            'srf', a Spectral Response Function, but could also be a transmission functions 'trn' or other spectral\n            quantity known to moglo.py.\n        :param chn_start_index: Use this parameter to select the starting channel number. Defaults to zero.\n        :return: The set of Flt filters as a single, wavelength-harmonised xr.DataArray object. The filter\n            headers are returned in an attribute called 'labels'. The fileheader of the Flt object is\n            returned in an attribute called 'title' (netCDF recommendation)\n        \"\"\"\n        flt_list = self.flt_as_xd()  # Create a list of xr.DataArray objects\n        # Harmonise the wavelength axes\n        flt_list_harmonised = xd.xd_harmonise_interp(flt_list)\n        xd.xd_attrs_update(flt_list_harmonised)  # Update the attribute\n        chn_indices = range(chn_start_index, chn_start_index + len(flt_list))\n        # Compile the list into a single object\n        flt_data = np.vstack([flt_list_harmonised[ifilt].data for ifilt in range(len(flt_list))])\n        flt_harmonised = xr.DataArray(flt_data.T, [(flt_list_harmonised[0]['wvl']),\n                                                      ('chn', chn_indices,\n                                                         {'labels': self.filterheaders})],\n                                           name=quantity_name,\n                                           attrs={'long_name': long_name[quantity_name],\n                                                  'units': default_units[quantity_name],\n                                                  'title': self.name})\n        return flt_harmonised\n\n# Definitions for Kato spectral channels, [centre_wavelength, lower_wavelength, upper_wavelength]\n# Kato wavelengths are in nm\nkato_channels = np.array([\n    [ 256.300,  240.1185,  272.4815],\n    [ 277.948,  272.4815,  283.4140],\n    [ 295.127,  283.4140,  306.8408],\n    [ 317.306,  306.8408,  327.7722],\n    [ 345.136,  327.7722,  362.5000],\n    [ 385.000,  362.5000,  407.5000],\n    [ 429.773,  407.5000,  452.0458],\n    [ 484.863,  452.0458,  517.6806],\n    [ 528.840,  517.6806,  540.0000],\n    [ 544.800,  540.0000,  549.5000],\n    [ 558.050,  549.5000,  566.6000],\n    [ 585.800,  566.6000,  605.0000],\n    [ 615.000,  605.0000,  625.0000],\n    [ 645.850,  625.0000,  666.7000],\n    [ 675.439,  666.7000,  684.1772],\n    [ 694.313,  684.1772,  704.4486],\n    [ 723.531,  704.4486,  742.6139],\n    [ 767.046,  742.6139,  791.4788],\n    [ 817.968,  791.4788,  844.4581],\n    [ 866.714,  844.4581,  888.9693],\n    [ 931.938,  888.9693,  974.9063],\n    [1010.320,  974.9063, 1045.7440],\n    [1119.970, 1045.7440, 1194.1880],\n    [1355.060, 1194.1880, 1515.9400],\n    [1564.700, 1515.9400, 1613.4510],\n    [1789.120, 1613.4510, 1964.7980],\n    [2059.130, 1964.7980, 2153.4640],\n    [2214.330, 2153.4640, 2275.1900],\n    [2638.540, 2275.1900, 3001.8930],\n    [3318.660, 3001.8930, 3635.4170],\n    [3813.210, 3635.4170, 3991.0030],\n    [4298.320, 3991.0030, 4605.6540]])\nkato_units = 'nm'\n\nfu_channels = np.array([\n    [ 0.55,   0.20000,      0.68966],\n    [ 1.00,   0.68966,      1.29870],\n    [ 1.60,   1.29870,      1.90476],\n    [ 2.20,   1.90476,      2.50000],\n    [ 3.00,   2.50000,      3.50877],\n    [ 3.70,   3.50877,      4.00000],\n    [ 4.90,   4.54545,      5.26316],\n    [ 5.60,   5.26316,      5.88235],\n    [ 6.50,   5.88235,      7.14286],\n    [ 7.60,   7.14286,      8.00000],\n    [ 8.50,   8.00000,      9.09091],\n    [ 9.60,   9.09091,     10.20410],\n    [11.30,  10.20410,     12.50000],\n    [13.70,  12.50000,     14.92540],\n    [16.60,  14.92540,     18.51850],\n    [21.50,  18.51850,     25.00000],\n    [30.00,  25.00000,     35.71430],\n    [70.00,  35.71430,  10000.00000]])\nfu_units = 'um'\n\navhrr_kratz_channels = np.array([\n    # channel 1 (band 5 actually contributes to channel 1 and 2)\n    [  0.569917,  0.561798,  0.578035],    # avhrr15.f\n    [  0.590222,  0.578035,  0.602410],    # avhrr14.f\n    [  0.613705,  0.602410,  0.625000],    # avhrr13.f\n    [  0.657328,  0.625000,  0.689655],    # avhrr12.f\n    [  0.720768,  0.689655,  0.751880],    # avhrr11.f\n    # channel 2\n    [  0.763537,  0.751880,  0.775194],    # avhrr24.f\n    [  0.842143,  0.775194,  0.909091],    # avhrr23.f\n    [  0.944741,  0.909091,  0.980392],    # avhrr22.f\n    [  1.011030,  0.980392,  1.041667],    # avhrr21.f\n    # channel 3\n    [  3.55005,  3.496503,  3.603604],    # avhrr35.f\n    [  3.65023,  3.603604,  3.696858],    # avhrr34.f\n    [  3.74957,  3.696858,  3.802281],    # avhrr32.f\n    [  3.85427,  3.802281,  3.906250],    # avhrr32.f\n    [  3.96116,  3.906250,  4.016064],    # avhrr31.f\n    # channel 4\n    [ 10.8365,  10.309278, 11.363636],    # avhrr41.f\n    # channel 5\n    [ 11.9318,  11.363636, 12.500000]])   # avhrr51.f\navhrr_kratz_units = 'um'\n\nclass SpectralDistribution(object):\n    \"\"\" The SpectralDistribution class defines any band-limited spectral distribution function. This could be\n    the spectral response functions of a sensor, or the spectral transmittance of an optical filter, the spectral\n    radiance, irradiance or any other band-limited spectral quantity.\n\n    \"\"\"\n    # SpectralChannels is a list of channels that can be indexed in the usual way, by the global channel index\n    # _channel_counter = 0  # This is a class global counter, incremented for each channel, so that every\n    #                       # defined distribution function gets a unique number\n    # _channel_list = []  # The global list of spectral channels indexed self.ichn\n    # _channel_groups = []  # Global list of channel group names\n    # _channel_group_dict = {}  # Dictionary of channels indexed by group name\n    def __init__(self, extreme_limits, in_band_limits=None, in_band_threshold=0.01):\n        \"\"\" Create a basic, spectral distribution function with certain spectral band limits\n\n        By default, wavelenths are specified in nm for SpectralDistribution and SpectralSpace objects.\n\n        :return: A SpectralDistribution object\n        \"\"\"\n        pass\n\n    # Use @classmethod, where the class of object instance is passed implicitly, instead of self\n    # This syntax is used to create alternative constructors\n    @classmethod\n    def kato(cls, i_channel, resolution=0.001):\n        \"\"\" Return a Kato correlated-k channel definition as a SpectralDistribution. Only a single channel can\n        be represented. Use a SpectralSpace to get multiple Kato channels\n\n        :param i_channel: the single kato channel to be obtained. Integer 1 to 32\n        :param resolution: this is the spectral resolution in nm of the band edges. Default 0.001 nm\n          which is typically adequate.\n        :return: A SpectralDistribution object defining the requested Kato channel\n\n        .. seealso: the libRadtran manual\n        \"\"\"\n\n        obj = cls()\n        return obj\n\n    @classmethod\n    def fu(cls, i_channel, resolution=0.001):\n        \"\"\" Return a Fu correlated-k channel as a SpectralDistribution\n\n        :param i_channel: the single Fu channel to be obtained. Integer 1 to 18\n        :param resolution: this is the spectral resolution in nm of the band edges. Default 0.001 nm\n        :return: A SpectralDistribution object defining the requested Fu channel\n\n        .. seealso: the libRadtran manual\n        \"\"\"\n        obj = cls()\n        return obj\n\n    @classmethod\n    def avhrr_kratz(cls, i_channel, resolution=0.001):\n        \"\"\"\n\n        :param i_channel: The single AVHRR Kratz channel to obtain. Integer 1 to 16\n        :param resolution: this is the spectral resolution in nm of the band edges. Default 0.001 nm\n        :return: A SpectralDistribution object defining the requested avhrr_kratz channel\n\n        .. seealso: the libRadtran manual\n        \"\"\"\n        obj = cls()\n        return obj\n\n    @classmethod\n    def spectral_slice(cls, extreme_limits, in_band_limits, resolution=0.001, oob_leakage=0.0):\n        \"\"\" Create a SpectralDistribution object as a simple spectral slice\n\n        :param extreme_limits:\n        :param in_band_limits:\n        :param resolution:\n        :param oob_leakage:\n        :return:\n        \"\"\"\n\n    @classmethod\n    def sensor_channel(cls, platform_series, platform_name, sensor_name, channel_name):\n        \"\"\" Load a spectral response file from the libRadtran-compatible library as a SpectralDistribution\n\n        The available response function filter files can be viewed in the sub-directory rad/radata/filter.\n        Note that only a single channel can be loaded using this method. To load multiple channels, use\n        SpectralSpace.sensor_channels().\n\n        :param platform_series: Name of the series of platforms on which the sensor is carried e.g. 'landsat'\n        :param platform_name: Name of the specific satellite/platform on which the sensor is carried\n            e.g. 'landsat7'\n        :param sensor_name: Name of the specific sensor on the platform e.g. 'tm' or 'etm'\n        :param channel_name: Name of the specific spectral channel on the given sensor e.g.\n        :return:\n        \"\"\"\n\n        obj = cls()\n        return obj\n\n    def decimate_resolution(self):\n        \"\"\" Reduce the number of sample points representing the spectral distribution in an intelligent way.\n\n        This procedure only works for positive spectral power distributions.\n\n        :return:\n        \"\"\"\n\n\nclass SpectralSpace(object):\n    \"\"\" A SpectralSpace is a set (represented as a list) of SpectralDistribution objects.\n\n    For example, the full Kato correlated-k list of spectral slices constitutes a SpectralSpace.\n    A sub-range of of Kato or other correlated-k channels (Fu or avhrr_kratz) also qualify.\n    The spectral response functions of a sensor can also be represented using a SpectralSpace.\n\n    An important use of SpectralSpaces is to compute \"projections\" which could also be thought of as\n    \"dot products\". The projection of one SpectralSpace into another comprises multplying the\n    distribution functions and integrating over wavelength to obtain a set of weights. The integral is\n    typically also normalised to retain equivalent units.\n\n    Here are some examples:\n    A set of spectral end-member functions can be represented as a SpectralSpace. These end-members might\n    be propagated to calculate an end-member response at a camera focal plane. The end-members are projected\n    onto the spectral response functions of the sensor to get the sensor responses to each of the end-members.\n\n    Notes: A SpectralSpace is not generally orthogonal unless specifically designed so by the user.\n    \"\"\"\n\n    @classmethod\n    def from_flt_file(cls, filename, re_select=None):\n        \"\"\" Create a SpectralSpace list of SpectralDistribution objects by reading a MODTRAN-compatible\n        \"filter function\" .flt file.\n\n        :param filename: The MODTRAN-compatible .flt file from which to read the filter functions.\n        :param re_select: Select a sub-set of the channels using a regular expression filter. Only the channel\n            names/descriptions that match the regular expression will be included. The default is to read\n            all channels in the file.\n        :return:\n        \"\"\"\n\n\n\n# Some simple OpenEXR utility functions for integration with Numpy\n# For more complex OpenEXR handling, use a class\ndef readOpenEXR(filename):\n    \"\"\" Simple read function for an OpenEXR file\n\n    Use of this function requires that the OpenEXR package be installed.\n    :param filename: The name of the OpenEXR file\n    :return channel_names: List of image channel names found in the OpenEXR file\n    :return im_dict: All image data in a dictionary keyed by channel names or channel groups. Channels are grouped\n        into RGB triplets if the channel names have the form prefix.R, prefix.G and prefix.B.\n        All image data is returned as numpy arrays.\n    :return header: OpenEXR header as a dictionary.\n    \"\"\"\n    import OpenEXR\n    import Imath\n    if not OpenEXR.isOpenExrFile(filename):\n        raise IOError('OpenEXR file was not found, or file is not OpenEXR.')\n    exr_file = OpenEXR.InputFile(filename)\n    header = exr_file.header()  # Returns a dict\n    channel_names = header['channels'].keys()\n    data_window = header['dataWindow']\n    size = (data_window.max.x - data_window.min.x + 1, data_window.max.y - data_window.min.y + 1)\n    # Read all channels\n    im_FLOAT = np.array([], dtype=np.float32)\n    im_HALF = np.array([], dtype=np.float16)\n    im_UINT = np.array([], dtype=np.uint32)\n    im_dict = {}\n    triplets = {}\n    for i_chan, chan_name in enumerate(channel_names):\n        pixel_type = str(header['channels'][chan_name]).split()[0]\n        if pixel_type == 'FLOAT':\n            imath_type = Imath.PixelType(Imath.PixelType.FLOAT)\n        elif pixel_type == 'HALF':\n            imath_type = Imath.PixelType(Imath.PixelType.HALF)\n        elif pixel_type == 'UINT':\n            imath_type = Imath.PixelType(Imath.PixelType.UINT)\n        chan_data_str = exr_file.channel(chan_name, imath_type)\n        if pixel_type == 'FLOAT':\n            chan_data = np.fromstring(chan_data_str, dtype=np.float32).reshape((size[1], size[0]))\n            if im_FLOAT.size == 0:\n                im_FLOAT = chan_data\n            else:\n                im_FLOAT= np.dstack((im_FLOAT, chan_data))\n        elif pixel_type == 'HALF':\n            chan_data = np.fromstring(chan_data_str, dtype=np.float16).reshape((size[1], size[0]))\n            if im_HALF.size == 0:\n                im_HALF = chan_data\n            else:\n                im_HALF = np.dstack((im_HALF, chan_data))\n        elif pixel_type == 'UINT':\n            chan_data = np.fromstring(chan_data_str, dtype=np.uint32).reshape((size[1], size[0]))\n            if im_UINT.size == 0:\n                im_UINT = chan_data\n            else:\n                im_UINT = np.dstack((im_UINT, chan_data))\n        else:\n            raise ValueError('Unknown image pixel type in OpenEXR file.')\n        im_dict[chan_name] = chan_data\n        rgbya = chan_name[-1]  # red, green, blue, luminance, transparency\n        prefix = chan_name.split('.')[0]\n        if prefix == rgbya:\n            prefix = 'rgb'\n        if rgbya in 'RGB':\n            if (prefix in triplets):\n                triplets[prefix][rgbya] = chan_name\n            else:\n                triplets[prefix] = {rgbya: chan_name}\n    for triplet in triplets:\n        im_dict[triplet] = np.dstack((im_dict[triplets[triplet]['R']],\n                                      im_dict[triplets[triplet]['G']],\n                                      im_dict[triplets[triplet]['B']]))\n    return channel_names, im_dict, header\n\n\n\n\n", "meta": {"hexsha": "ca7018af551ecb985de0cac15819303d80b87fe1", "size": 37927, "ext": "py", "lang": "Python", "max_stars_repo_path": "rad/radute.py", "max_stars_repo_name": "NelisW/libraddask", "max_stars_repo_head_hexsha": "3c622ec0010d79aee210d2ce7cf2b6cba79c1835", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-04-20T21:31:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T11:33:13.000Z", "max_issues_repo_path": "rad/radute.py", "max_issues_repo_name": "NelisW/libraddask", "max_issues_repo_head_hexsha": "3c622ec0010d79aee210d2ce7cf2b6cba79c1835", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rad/radute.py", "max_forks_repo_name": "NelisW/libraddask", "max_forks_repo_head_hexsha": "3c622ec0010d79aee210d2ce7cf2b6cba79c1835", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-23T05:09:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-23T05:09:24.000Z", "avg_line_length": 48.4380587484, "max_line_length": 122, "alphanum_fraction": 0.6050043505, "include": true, "reason": "import numpy", "num_tokens": 10423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.25982563796098374, "lm_q1q2_score": 0.15300849409004114}}
{"text": "import numpy as np\nfrom astropy.coordinates import SkyCoord\nfrom astropy import units as u\nfrom pandas import read_csv\nimport h5py\n\nimport stan_utility\n\n__all__ = ['Model', 'Direction', 'uv_to_coord', 'coord_to_uv']\n\nMpc_to_km = 3.086E19\n\n\nclass Model():\n    \"\"\"\n    Simple wrapper for models defined in Stan.\n    \"\"\"\n    def __init__(self,\n                 model_filename=None,\n                 sim_filename=None,\n                 include_paths=None):\n        \"\"\"\n        Simple wrapper for models defined in Stan.\n       \n        :param model_filename: location of the stan code for model\n        :param sim_filename: locaiton of the stan code for simulation\n        \"\"\"\n\n        self.model_filename = model_filename\n        self.sim_filename = sim_filename\n        self.include_paths = include_paths\n\n        self.simulation = None\n\n    def compile(self, reset=False):\n        \"\"\"\n        Compile and cache the necessary Stan models if not already done.\n\n        :param reset: Rerun the compilation\n        \"\"\"\n\n        if self.model_filename:\n            self.model = stan_utility.compile_model(\n                filename=self.model_filename,\n                model_name='model',\n                include_paths=self.include_paths,\n                reset=reset)\n\n        if self.sim_filename:\n            self.simulation = stan_utility.compile_model(\n                filename=self.sim_filename,\n                model_name='sim',\n                include_paths=self.include_paths,\n                reset=reset)\n\n    def input(self,\n              B=None,\n              kappa=None,\n              F_T=None,\n              f=None,\n              L=None,\n              F0=None,\n              alpha=None,\n              Eth=None,\n              ptype=None):\n        \"\"\"\n        Get simulation inputs.\n\n        :param F_T: total flux [# km-^2 yr^-1]\n        :param f: associated fraction\n        :param kappa: deflection parameter \n        :param B: rms B field strength [nG]\n        :param alpha: source spectral index\n        :param Eth: threshold energy of study [EeV]\n        :param ptype: element of composition\n        \"\"\"\n        self.F_T = F_T\n        self.f = f\n        self.kappa = kappa\n        self.B = B\n        self.L = L\n        self.F0 = F0\n        self.alpha = alpha\n        self.Eth = Eth\n        self.Eth_sim = None  # To be set by Analysis\n        self.ptype = ptype\n\n    def _get_properties(self):\n        \"\"\"\n        Convenience function to pack object into dict.\n        \"\"\"\n\n        self.properties = {}\n        self.properties['F_T'] = self.F_T\n        self.properties['f'] = self.f\n        self.properties['kappa'] = self.kappa\n        self.properties['B'] = self.B\n        self.properties['L'] = self.L\n        self.properties['F0'] = self.F0\n        self.properties['F0'] = self.F0\n        self.properties['alpha'] = self.alpha\n        self.properties['Eth'] = self.Eth\n        self.properties['Eth_sim'] = self.Eth_sim\n\n        self.properties['sim_filename'] = self.sim_filename\n        self.properties['model_filename'] = self.model_filename\n        self.properties['include_paths'] = self.include_paths\n\n    def save(self, file_handle):\n        \"\"\"\n        Save to the passed H5py file handle,\n        i.e. something that cna be used with \n        file_handle.create_dataset()\n        \n        :param file_handle: file handle\n        \"\"\"\n\n        self._get_properties()\n\n        for key, value in self.properties.items():\n            try:\n                file_handle.create_dataset(key, data=value)\n            except:\n                pass\n\n\nclass Direction():\n    \"\"\"\n    Input the unit vector vMF samples and \n    store x, y, and z and galactic coordinates \n    of direction in Mpc.\n    \"\"\"\n    def __init__(self, unit_vector_3d):\n        \"\"\"\n        Input the unit vector samples and \n        store x, y, and z and galactic coordinates \n        of direction in Mpc.\n        \n        :param unit_vector_3d: a 3-dimensional unit vector.\n        \"\"\"\n\n        self.unit_vector = unit_vector_3d\n        transposed_uv = np.transpose(self.unit_vector)\n        self.x = transposed_uv[0]\n        self.y = transposed_uv[1]\n        self.z = transposed_uv[2]\n        self.d = SkyCoord(self.x,\n                          self.y,\n                          self.z,\n                          unit='mpc',\n                          representation_type='cartesian',\n                          frame='icrs')\n        self.d.representation_type = 'spherical'\n        self.glons = self.d.galactic.l.wrap_at(360 * u.deg).deg\n        self.glats = self.d.galactic.b.wrap_at(180 * u.deg).deg\n\n        self.ras = self.d.ra.deg\n        self.decs = self.d.dec.deg\n\n\ndef uv_to_coord(uv):\n    \"\"\"\n    Convert unit vector array into SkyCoord object in the ICRS frame.\n\n    :param uv: array of 3D unit vectors\n    :return: astropy SkyCoord object\n    \"\"\"\n    transposed_uv = np.transpose(uv)\n    x = transposed_uv[0]\n    y = transposed_uv[1]\n    z = transposed_uv[2]\n\n    c = SkyCoord(x,\n                 y,\n                 z,\n                 unit='Mpc',\n                 representation_type='cartesian',\n                 frame='icrs')\n\n    return c\n\n\ndef coord_to_uv(coord):\n    \"\"\"\n    Convert SkyCoord object into array of unit vecotrs in the ICRS frame.\n    Used for input into Stan programs.\n    \n    :param coord: astropy SkyCoord object\n    :return: an array of 3D unit vectors\n    \"\"\"\n    c = coord.icrs\n    ds = [c.cartesian.x, c.cartesian.y, c.cartesian.z]\n    uv = [d / np.linalg.norm(d) for d in np.transpose(ds)]\n\n    return uv\n\n\ndef convert_scale(D, alpha_T, eps, F0=None, L=None, to_stan=True):\n    \"\"\"\n    Convenience function to convert parameters \n    to O(1) scale for sampling in Stan.\n    D [Mpc] -> (D * 3.086) / 100\n    alpha_T [km^2 yr] -> alpha_T / 1000\n    eps [km^2 yr] -> eps / 1000\n    F [# km^-2 yr^-1] -> F * 1000\n    L [# yr^-1] -> L / 1e39\n\n    Can also convert back by setting to_stan = False\n    \"\"\"\n\n    # Convert from physical units to Stan units\n    if to_stan:\n\n        D = [(d * 3.086) / 100 for d in D]\n        alpha_T = alpha_T / 1000.0\n        eps = [e / 1000.0 for e in eps]\n\n        if F0:\n            F0 = F0 * 1000.0\n\n        if isinstance(L, (list, np.ndarray)):\n            L = L / 1.0e39\n\n    # Convert from Stan units to physical units\n    else:\n\n        D = [(d / 3.086) * 100 for d in D]\n        alpha_T = alpha_T * 1000.0\n        eps = [e * 1000.0 for e in eps]\n\n        if F0:\n            F0 = F0 / 1000.0\n\n        if isinstance(L, (list, np.ndarray)):\n            L = L * 1.0e39\n\n    if F0 and isinstance(L, (list, np.ndarray)):\n\n        return D, alpha_T, eps, F0, L\n\n    else:\n\n        return D, alpha_T, eps\n\n\ndef get_simulation_input(Nsim, f, D, M, alpha_T):\n    \"\"\"\n    For a given associated fraction and \n    detector exposure, find the background flux and \n    source luminosity as input to the simulation.\n    \n    :param Nsim: N simulated, ignoring exposure effects.\n    :param f: Associated fraction.\n    :param D: List of distances to sources [Mpc].\n    :param M: Integral over the angular exposure [sr].\n    :param alpha_T: Total exposure [km^2 sr yr].\n    \"\"\"\n\n    FT = (Nsim * M) / alpha_T  # km^-2 yr^-1\n    Fs = f * FT\n    F0 = (1 - f) * FT\n\n    # Assume equal luminosities\n    L = (Fs / (sum([1 / (4 * np.pi * (d * Mpc_to_km)**2) for d in D])))\n    L = np.tile(L, len(D))  # yr^-1\n\n    return L, F0\n", "meta": {"hexsha": "f427fd76566721ea35e62c60cd859576d0507d62", "size": 7359, "ext": "py", "lang": "Python", "max_stars_repo_path": "fancy/interfaces/stan.py", "max_stars_repo_name": "uhecr-project/fancy", "max_stars_repo_head_hexsha": "c6015b21fd88aecfb7e45f2aec438d5bda0df050", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fancy/interfaces/stan.py", "max_issues_repo_name": "uhecr-project/fancy", "max_issues_repo_head_hexsha": "c6015b21fd88aecfb7e45f2aec438d5bda0df050", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fancy/interfaces/stan.py", "max_forks_repo_name": "uhecr-project/fancy", "max_forks_repo_head_hexsha": "c6015b21fd88aecfb7e45f2aec438d5bda0df050", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4589552239, "max_line_length": 73, "alphanum_fraction": 0.5563255877, "include": true, "reason": "import numpy,from astropy", "num_tokens": 1865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.28776782186926264, "lm_q1q2_score": 0.15286496433230173}}
{"text": "\"\"\"\nSpectral Synthesis Module of SME\n\"\"\"\nimport logging\nimport uuid\n\nimport numpy as np\nfrom scipy.constants import speed_of_light\nfrom scipy.interpolate import interp1d\nfrom scipy.ndimage.filters import convolve\nfrom tqdm import tqdm\n\nfrom . import broadening\nfrom .atmosphere.interpolation import AtmosphereInterpolator\nfrom .continuum_and_radial_velocity import (\n    apply_radial_velocity_and_continuum,\n    match_rv_continuum,\n    null_result,\n)\nfrom .iliffe_vector import Iliffe_vector\nfrom .large_file_storage import setup_lfs\nfrom .sme_synth import SME_DLL\n\nlogger = logging.getLogger(__name__)\n\nclight = speed_of_light * 1e-3  # km/s\n\n__DLL_DICT__ = {}\n__DLL_IDS__ = {}\n\n\nclass Synthesizer:\n    def __init__(self, config=None, lfs_atmo=None, lfs_nlte=None, dll=None):\n        self.config, self.lfs_atmo, self.lfs_nlte = setup_lfs(\n            config, lfs_atmo, lfs_nlte\n        )\n        # dict: internal storage of the adaptive wavelength grid\n        self.wint = {}\n        # dll: the smelib object used for the radiative transfer calculation\n        self.dll = dll if dll is not None else SME_DLL()\n        self.dll = self.get_dll_id()\n        self.atmosphere_interpolator = None\n        # This stores a reference to the currently used sme structure, so we only log it once\n        self.known_sme = None\n        logger.info(\"Don't forget to cite your sources. Use sme.citation()\")\n\n    def get_atmosphere(self, sme):\n        \"\"\"\n        Return an atmosphere based on specification in an SME structure\n\n        sme.atmo.method defines mode of action:\n            \"grid\"\n                interpolate on atmosphere grid\n            \"embedded\"\n                No change\n            \"routine\"\n                calls sme.atmo.source(sme, atmo)\n\n        Parameters\n        ---------\n            sme : SME_Struct\n                sme structure with sme.atmo = atmosphere specification\n\n        Returns\n        -------\n        sme : SME_Struct\n            sme structure with updated sme.atmo\n        \"\"\"\n\n        # Handle atmosphere grid or user routine.\n        atmo = sme.atmo\n\n        if atmo.method == \"grid\":\n            if self.atmosphere_interpolator is None:\n                self.atmosphere_interpolator = AtmosphereInterpolator(\n                    depth=atmo.depth,\n                    interp=atmo.interp,\n                    geom=atmo.geom,\n                    lfs_atmo=self.lfs_atmo,\n                )\n            else:\n                self.atmosphere_interpolator.depth = atmo.depth\n                self.atmosphere_interpolator.interp = atmo.interp\n                self.atmosphere_interpolator.geom = atmo.geom\n\n            atmo = self.atmosphere_interpolator.interp_atmo_grid(\n                atmo.source, sme.teff, sme.logg, sme.monh\n            )\n        elif atmo.method == \"routine\":\n            atmo = atmo.source(sme, atmo)\n        elif atmo.method == \"embedded\":\n            # atmo structure already extracted in sme_main\n            pass\n        else:\n            raise AttributeError(\"Source must be 'grid', 'routine', or 'embedded'\")\n\n        sme.atmo = atmo\n        return sme\n\n    @staticmethod\n    def get_wavelengthrange(wran, vrad, vsini):\n        \"\"\"\n        Determine wavelengthrange that needs to be calculated\n        to include all lines within velocity shift vrad + vsini\n        \"\"\"\n        # 30 km/s == maximum barycentric velocity\n        vrad_pad = 30.0 + 0.5 * np.clip(vsini, 0, None)  # km/s\n        vbeg = vrad_pad + np.clip(vrad, 0, None)  # km/s\n        vend = vrad_pad - np.clip(vrad, None, 0)  # km/s\n\n        wbeg = wran[0] * (1 - vbeg / clight)\n        wend = wran[1] * (1 + vend / clight)\n        return wbeg, wend\n\n    @staticmethod\n    def new_wavelength_grid(wint):\n        \"\"\"Generate new wavelength grid within bounds of wint\"\"\"\n        # Determine step size for a new model wavelength scale, which must be uniform\n        # to facilitate convolution with broadening kernels. The uniform step size\n        # is the larger of:\n        #\n        # [1] smallest wavelength step in WINT_SEG, which has variable step size\n        # [2] 10% the mean dispersion of WINT_SEG\n        # [3] 0.05 km/s, which is 1% the width of solar line profiles\n\n        wbeg, wend = wint[0], wint[-1]\n        wmid = 0.5 * (wend + wbeg)  # midpoint of segment\n        wspan = wend - wbeg  # width of segment\n        diff = wint[1:] - wint[:-1]\n        jmin = np.argmin(diff)\n        vstep1 = diff[jmin] / wint[jmin] * clight  # smallest step\n        vstep2 = 0.1 * wspan / (len(wint) - 1) / wmid * clight  # 10% mean dispersion\n        vstep3 = 0.05  # 0.05 km/s step\n        vstep = max(vstep1, vstep2, vstep3)  # select the largest\n\n        # Generate model wavelength scale X, with uniform wavelength step.\n        nx = int(\n            np.abs(np.log10(wend / wbeg)) / np.log10(1 + vstep / clight) + 1\n        )  # number of wavelengths\n        if nx % 2 == 0:\n            nx += 1  # force nx to be odd\n\n        # Resolution\n        # IDL way\n        # resol_out = 1 / ((wend / wbeg) ** (1 / (nx - 1)) - 1)\n        # vstep = clight / resol_out\n        # x_seg = wbeg * (1 + 1 / resol_out) ** np.arange(nx)\n\n        # Python way (not identical, as IDL endpoint != wend)\n        # difference approx 1e-7\n        x_seg = np.geomspace(wbeg, wend, num=nx)\n        resol_out = 1 / np.diff(np.log(x_seg[:2]))[0]\n        vstep = clight / resol_out\n        return x_seg, vstep\n\n    @staticmethod\n    def check_segments(sme, segments):\n        if isinstance(segments, str) and segments == \"all\":\n            segments = range(sme.nseg)\n        else:\n            segments = np.atleast_1d(segments)\n            if np.any(segments < 0) or np.any(segments >= sme.nseg):\n                raise IndexError(\"Segment(s) out of range\")\n\n        if sme.mask is not None:\n            segments = [\n                seg\n                for seg in segments\n                if not np.all(sme.mask[seg] == sme.mask_values[\"bad\"])\n            ]\n        return segments\n\n    @staticmethod\n    def apply_radial_velocity_and_continuum(\n        wave, spec, wmod, smod, cmod, vrad, cscale, cscale_type, segments\n    ):\n        smod = apply_radial_velocity_and_continuum(\n            wave, wmod, smod, vrad, cscale, cscale_type, segments\n        )\n        cmod = apply_radial_velocity_and_continuum(\n            wave, wmod, cmod, vrad, None, None, segments\n        )\n        return smod, cmod\n\n    @staticmethod\n    def integrate_flux(mu, inten, deltav, vsini, vrt, osamp=1):\n        \"\"\"\n        Produces a flux profile by integrating intensity profiles (sampled\n        at various mu angles) over the visible stellar surface.\n\n        Intensity profiles are weighted by the fraction of the projected\n        stellar surface they represent, apportioning the area between\n        adjacent MU points equally. Additional weights (such as those\n        used in a Gauss-Legendre quadrature) can not meaningfully be\n        used in this scheme.  About twice as many points are required\n        with this scheme to achieve the precision of Gauss-Legendre\n        quadrature.\n        DELTAV, VSINI, and VRT must all be in the same units (e.g. km/s).\n        If specified, OSAMP should be a positive integer.\n\n        Parameters\n        ----------\n        mu : array(float) of size (nmu,)\n            cosine of the angle between the outward normal and\n            the line of sight for each intensity spectrum in INTEN.\n        inten : array(float) of size(nmu, npts)\n            intensity spectra at specified values of MU.\n        deltav : float\n            velocity spacing between adjacent spectrum points\n            in INTEN (same units as VSINI and VRT).\n        vsini : float\n            maximum radial velocity, due to solid-body rotation.\n        vrt : float\n            radial-tangential macroturbulence parameter, i.e.\n            np.sqrt(2) times the standard deviation of a Gaussian distribution\n            of turbulent velocities. The same distribution function describes\n            the radial motions of one component and the tangential motions of\n            a second component. Each component covers half the stellar surface.\n            See 'The Observation and Analysis of Stellar Photospheres', Gray.\n        osamp : int, optional\n            internal oversampling factor for convolutions.\n            By default convolutions are done using the input points (OSAMP=1),\n            but when OSAMP is set to higher integer values, the input spectra\n            are first oversampled by cubic spline interpolation.\n\n        Returns\n        -------\n        value : array(float) of size (npts,)\n            Disk integrated flux profile.\n\n        Note\n        ------------\n            If you use this algorithm in work that you publish, please cite\n            Valenti & Anderson 1996, PASP, currently in preparation.\n        \"\"\"\n        \"\"\"\n        History\n        -----------\n        Feb-88  GM\n            Created ANA version.\n        13-Oct-92 JAV\n            Adapted from G. Marcy's ANA routi!= of the same name.\n        03-Nov-93 JAV\n            Switched to annular convolution technique.\n        12-Nov-93 JAV\n            Fixed bug. Intensity compo!=nts not added when vsini=0.\n        14-Jun-94 JAV\n            Reformatted for \"public\" release. Heavily commented.\n            Pass deltav instead of 2.998d5/deltav. Added osamp\n            keyword. Added rebinning logic at end of routine.\n            Changed default osamp from 3 to 1.\n        20-Feb-95 JAV\n            Added mu as an argument to handle arbitrary mu sampling\n            and remove ambiguity in intensity profile ordering.\n            Interpret VTURB as np.sqrt(2)*sigma instead of just sigma.\n            Replaced call_external with call to spl_{init|interp}.\n        03-Apr-95 JAV\n            Multiply flux by pi to give observed flux.\n        24-Oct-95 JAV\n            Force \"nmk\" padding to be at least 3 pixels.\n        18-Dec-95 JAV\n            Renamed from dskint() to rtint(). No longer make local\n            copy of intensities. Use radial-tangential instead\n            of isotropic Gaussian macroturbulence.\n        26-Jan-99 JAV\n            For NMU=1 and VSINI=0, assume resolved solar surface#\n            apply R-T macro, but supress vsini broadening.\n        01-Apr-99 GMH\n            Use annuli weights, rather than assuming ==ual area.\n        07-Mar-12 JAV\n            Force vsini and vmac to be scalars.\n        \"\"\"\n\n        # Make local copies of various input variables, which will be altered below.\n        # Force vsini and especially vmac to be scalars. Otherwise mu dependence fails.\n\n        if np.size(vsini) > 1:\n            vsini = vsini[0]\n        if np.size(vrt) > 1:\n            vrt = vrt[0]\n\n        # Determine oversampling factor.\n        os = round(np.clip(osamp, 1, None))  # force integral value > 1\n\n        # Convert input MU to projected radii, R, of annuli for a star of unit radius\n        #  (which is just sine, rather than cosine, of the angle between the outward\n        #  normal and the line of sight).\n        rmu = np.sqrt(1 - mu ** 2)  # use simple trig identity\n\n        # Sort the projected radii and corresponding intensity spectra into ascending\n        #  order (i.e. from disk center to the limb), which is equivalent to sorting\n        #  MU in descending order.\n        isort = np.argsort(rmu)\n        rmu = rmu[isort]  # reorder projected radii\n        nmu = np.size(mu)  # number of radii\n        if nmu == 1:\n            if vsini != 0:\n                logger.warning(\n                    \"Vsini is non-zero, but only one projected radius (mu value) is set. No rotational broadening will be performed.\"\n                )\n                vsini = 0  # ignore vsini if only 1 mu\n\n        # Calculate projected radii for boundaries of disk integration annuli.  The n+1\n        # boundaries are selected such that r(i+1) exactly bisects the area between\n        # rmu(i) and rmu(i+1). The in!=rmost boundary, r(0) is set to 0 (disk center)\n        # and the outermost boundary, r(nmu) is set to 1 (limb).\n        if nmu > 1 or vsini != 0:  # really want disk integration\n            r = np.sqrt(\n                0.5 * (rmu[:-1] ** 2 + rmu[1:] ** 2)\n            )  # area midpoints between rmu\n            r = np.concatenate(([0], r, [1]))\n\n            # Calculate integration weights for each disk integration annulus.  The weight\n            # is just given by the relative area of each annulus, normalized such that\n            # the sum of all weights is unity.  Weights for limb darkening are included\n            # explicitly in the intensity profiles, so they aren't needed here.\n            wt = r[1:] ** 2 - r[:-1] ** 2  # weights = relative areas\n        else:\n            wt = np.array([1.0])  # single mu value, full weight\n\n        # Generate index vectors for input and oversampled points. Note that the\n        # oversampled indicies are carefully chosen such that every \"os\" finely\n        # sampled points fit exactly into one input bin. This makes it simple to\n        # \"integrate\" the finely sampled points at the end of the routine.\n        npts = inten.shape[1]  # number of points\n        xpix = np.arange(npts, dtype=float)  # point indices\n        nfine = os * npts  # number of oversampled points\n        xfine = (0.5 / os) * (\n            2 * np.arange(nfine, dtype=float) - os + 1\n        )  # oversampled points indices\n\n        # Loop through annuli, constructing and convolving with rotation kernels.\n\n        yfine = np.empty(nfine)  # init oversampled intensities\n        flux = np.zeros(nfine)  # init flux vector\n        for imu in range(nmu):  # loop thru integration annuli\n\n            #  Use external cubic spline routine (adapted from Numerical Recipes) to make\n            #  an oversampled version of the intensity profile for the current annulus.\n            ypix = inten[isort[imu]]  # extract intensity profile\n            if os == 1:\n                # just copy (use) original profile\n                yfine = ypix\n            else:\n                # spline onto fine wavelength scale\n                yfine = interp1d(xpix, ypix, kind=\"cubic\")(xfine)\n\n            # Construct the convolution kernel which describes the distribution of\n            # rotational velocities present in the current annulus. The distribution has\n            # been derived analytically for annuli of arbitrary thickness in a rigidly\n            # rotating star. The kernel is constructed in two pieces: o!= piece for\n            # radial velocities less than the maximum velocity along the inner edge of\n            # the annulus, and one piece for velocities greater than this limit.\n            if vsini > 0:\n                # nontrivial case\n                r1 = r[imu]  # inner edge of annulus\n                r2 = r[imu + 1]  # outer edge of annulus\n                dv = deltav / os  # oversampled velocity spacing\n                maxv = vsini * r2  # maximum velocity in annulus\n                nrk = 2 * int(maxv / dv) + 3  ## oversampled kernel point\n                # velocity scale for kernel\n                v = dv * (np.arange(nrk, dtype=float) - ((nrk - 1) / 2))\n                rkern = np.zeros(nrk)  # init rotational kernel\n                j1 = np.abs(v) < vsini * r1  # low velocity points\n                rkern[j1] = np.sqrt((vsini * r2) ** 2 - v[j1] ** 2) - np.sqrt(\n                    (vsini * r1) ** 2 - v[j1] ** 2\n                )  # generate distribution\n\n                j2 = (np.abs(v) >= vsini * r1) & (np.abs(v) <= vsini * r2)\n                rkern[j2] = np.sqrt(\n                    (vsini * r2) ** 2 - v[j2] ** 2\n                )  # generate distribution\n\n                rkern = rkern / np.sum(rkern)  # normalize kernel\n\n                # Convolve the intensity profile with the rotational velocity kernel for this\n                # annulus. Pad each end of the profile with as many points as are in the\n                # convolution kernel. This reduces Fourier ringing. The convolution may also\n                # be do!= with a routi!= called \"externally\" from IDL, which efficiently\n                # shifts and adds.\n                if nrk > 3:\n                    yfine = convolve(yfine, rkern, mode=\"nearest\")\n\n            # Calculate projected sigma for radial and tangential velocity distributions.\n            muval = mu[isort[imu]]  # current value of mu\n            sigma = os * vrt / np.sqrt(2) / deltav  # standard deviation in points\n            sigr = sigma * muval  # reduce by current mu value\n            sigt = sigma * np.sqrt(1.0 - muval ** 2)  # reduce by np.sqrt(1-mu**2)\n\n            # Figure out how many points to use in macroturbulence kernel.\n            nmk = int(10 * sigma)\n            nmk = np.clip(nmk, 3, (nfine - 3) // 2)\n\n            # Construct radial macroturbulence kernel with a sigma of mu*VRT/np.sqrt(2).\n            if sigr > 0:\n                xarg = np.linspace(-nmk, nmk, 2 * nmk + 1) / sigr\n                xarg = np.clip(-0.5 * xarg ** 2, -20, None)\n                mrkern = np.exp(xarg)  # compute the gaussian\n                mrkern = mrkern / np.sum(mrkern)  # normalize the profile\n            else:\n                mrkern = np.zeros(2 * nmk + 1)  # init with 0d0\n                mrkern[nmk] = 1.0  # delta function\n\n            # Construct tangential kernel with a sigma of np.sqrt(1-mu**2)*VRT/np.sqrt(2).\n            if sigt > 0:\n                xarg = np.linspace(-nmk, nmk, 2 * nmk + 1) / sigt\n                xarg = np.clip(-0.5 * xarg ** 2, -20, None)\n                mtkern = np.exp(xarg)  # compute the gaussian\n                mtkern = mtkern / np.sum(mtkern)  # normalize the profile\n            else:\n                mtkern = np.zeros(2 * nmk + 1)  # init with 0d0\n                mtkern[nmk] = 1.0  # delta function\n\n            # Sum the radial and tangential components, weighted by surface area.\n            area_r = 0.5  # assume equal areas\n            area_t = 0.5  # ar+at must equal 1\n            mkern = area_r * mrkern + area_t * mtkern  # add both components\n\n            # Convolve the total flux profiles, again padding the spectrum on both ends to\n            # protect against Fourier ringing.\n            yfine = convolve(\n                yfine, mkern, mode=\"nearest\"\n            )  # add the padding and convolve\n\n            # Add contribution from current annulus to the running total.\n            flux = flux + wt[imu] * yfine  # add profile to running total\n\n        flux = np.reshape(flux, (npts, os))  # convert to an array\n        flux = np.pi * np.sum(flux, axis=1) / os  # sum, normalize\n        return flux\n\n    def sequential_synthesize_segments(\n        self,\n        sme,\n        segments,\n        wmod,\n        smod,\n        cmod,\n        reuse_wavelength_grid,\n        dll_id=None,\n    ):\n        for il in tqdm(segments, desc=\"Segments\", leave=False):\n            wmod[il], smod[il], cmod[il] = self.synthesize_segment(\n                sme,\n                il,\n                reuse_wavelength_grid,\n                il != segments[0],\n                dll_id=dll_id,\n            )\n        return wmod, smod, cmod\n\n    def get_dll_id(self, dll=None):\n        if dll is None:\n            dll = self.dll\n        if dll in __DLL_IDS__:\n            dll_id = __DLL_IDS__[dll]\n        elif dll in __DLL_DICT__:\n            dll_id = dll\n        else:\n            dll_id = uuid.uuid4()\n            __DLL_DICT__[dll_id] = dll\n            __DLL_IDS__[dll] = dll_id\n        return dll_id\n\n    def get_dll(self, dll_id=None):\n        if dll_id is None:\n            dll_id = self.dll\n        if dll_id in __DLL_DICT__:\n            return __DLL_DICT__[dll_id]\n        else:\n            return dll_id\n\n    def parallel_synthesize_segments(\n        self,\n        sme,\n        segments,\n        wmod,\n        smod,\n        cmod,\n        reuse_wavelength_grid,\n        dll_id=None,\n    ):\n        # Make sure the dll is recorded in the global variables\n        dll = self.get_dll(dll_id)\n        dll_id = self.get_dll_id(dll)\n\n        # We calculate the first segment sequentially\n        with tqdm(desc=\"Segments\", total=len(segments), leave=False) as progress:\n            il = segments[0]\n            wmod[il], smod[il], cmod[il] = self.synthesize_segment(\n                sme, il, reuse_wavelength_grid, False, dll_id=dll_id\n            )\n            progress.update(1)\n            # and then all others in parrallel\n            # since we can keep the line opacities from the calculation of the first segment\n            # TODO: do the line opacities also in parallel?\n\n            # For multiple Processes we need to pickle all the components\n            # BUT we can not pickle the smelib, since it has pointers (in the state)\n            # Therefore we cheat by putting the library in a global variable\n            # but only with a unqiue id, that should be unique to this library\n\n            def parallel(il):\n                return self.synthesize_segment(\n                    sme,\n                    il,\n                    reuse_wavelength_grid,\n                    True,\n                    method=\"parallel\",\n                    dll_id=dll_id,\n                )\n\n            # Sequential version for debugging\n            data = [None for _ in segments[1:]]\n            for i, seg in enumerate(segments[1:]):\n                data[i] = self.synthesize_segment(\n                    sme,\n                    seg,\n                    reuse_wavelength_grid,\n                    True,\n                    method=\"sequential\",\n                    dll_id=dll_id,\n                )\n                progress.update(1)\n\n        # data_seq = [None for _ in segments[1:]]\n        # What is sticking around in the library that is not part of the state?\n        # for seg in segments[1:]:\n        #     i = seg-1\n        #     data_seq[i] = self.synthesize_segment(\n        #         sme,\n        #         seg,\n        #         reuse_wavelength_grid,\n        #         True,\n        #         method=\"sequential\",\n        #         dll_id=dll_id,\n        #     )\n\n        #     if not np.all(data[i][0] == data_seq[i][0]):\n        #         print(\"What\")\n        #     if not np.all(data[i][1] == data_seq[i][1]):\n        #         print(\"The\")\n        #     if not np.all(data[i][2] == data_seq[i][2]):\n        #         print(\"Hell\")\n\n        # Pathos version crashes for some reason\n        # with ThreadPool() as pool:\n        #     data = pool.map(parallel, segments[1:])\n\n        # Use \"default\" ThreadPool instead\n        # data = [None for _ in segments[1:]]\n        # with ThreadPoolExecutor() as executor:\n        #     futures = {executor.submit(parallel, il): il for il in segments[1:]}\n        #     for future in as_completed(futures):\n        #         il = futures[future] - 1\n        #         data[il] = future.result()\n\n        for i, seg in enumerate(segments[1:]):\n            wmod[seg] = data[i][0]\n            smod[seg] = data[i][1]\n            cmod[seg] = data[i][2]\n\n        return wmod, smod, cmod\n\n    def synthesize_spectrum(\n        self,\n        sme,\n        segments=\"all\",\n        passLineList=True,\n        passAtmosphere=True,\n        passNLTE=True,\n        updateStructure=True,\n        updateLineList=False,\n        reuse_wavelength_grid=False,\n        radial_velocity_mode=\"robust\",\n        method=\"sequential\",\n        dll_id=None,\n    ):\n        \"\"\"\n        Calculate the synthetic spectrum based on the parameters passed in the SME structure\n        The wavelength range of each segment is set in sme.wran\n        The specific wavelength grid is given by sme.wave, or is generated on the fly if sme.wave is None\n\n        Will try to fit radial velocity RV and continuum to observed spectrum, depending on vrad_flag and cscale_flag\n\n        Other important fields:\n        sme.iptype: instrument broadening type\n\n        Parameters\n        ----------\n        sme : SME_Struct\n            sme structure, with all necessary parameters for the calculation\n        setLineList : bool, optional\n            wether to pass the linelist to the c library (default: True)\n        passAtmosphere : bool, optional\n            wether to pass the atmosphere to the c library (default: True)\n        passNLTE : bool, optional\n            wether to pass NLTE departure coefficients to the c library (default: True)\n        reuse_wavelength_grid : bool, optional\n            wether to use sme.wint as the output grid of the function or create a new grid (default: False)\n\n        Returns\n        -------\n        sme : SME_Struct\n            same sme structure with synthetic spectrum in sme.smod\n        \"\"\"\n\n        if sme is not self.known_sme:\n            logger.debug(\"Synthesize spectrum\")\n            logger.debug(\"%s\", sme)\n            self.known_sme = sme\n\n        # Define constants\n        n_segments = sme.nseg\n        cscale_degree = sme.cscale_degree\n\n        # fix impossible input\n        if \"spec\" not in sme:\n            sme.vrad_flag = \"none\"\n            sme.cscale_flag = \"none\"\n        else:\n            if \"mask\" not in sme:\n                sme.mask = np.full(sme.spec.size, sme.mask_values[\"line\"])\n            for i in range(sme.nseg):\n                mask = ~np.isfinite(sme.spec[i])\n                mask |= sme.uncs[i] == 0\n                sme.mask[i][mask] = sme.mask_values[\"bad\"]\n\n        if radial_velocity_mode != \"robust\" and (\n            \"cscale\" not in sme or \"vrad\" not in sme\n        ):\n            radial_velocity_mode = \"robust\"\n\n        segments = self.check_segments(sme, segments)\n\n        # Prepare arrays\n        vrad, _, cscale, _ = null_result(sme.nseg, sme.cscale_degree, sme.cscale_type)\n\n        wave = [np.zeros(0) for _ in range(n_segments)]\n        smod = [[] for _ in range(n_segments)]\n        cmod = [[] for _ in range(n_segments)]\n        wmod = [[] for _ in range(n_segments)]\n\n        # If wavelengths are already defined use those as output\n        if \"wave\" in sme:\n            wave = [w for w in sme.wave]\n\n        if method == \"parallel\" and not self.get_dll(dll_id).parallel:\n            # display only once\n            if (\n                not hasattr(self, \"_warning_parallel_mode\")\n                or not self._warning_parallel_mode\n            ):\n                self._warning_parallel_mode = True\n                logger.warning(\n                    \"Parallel mode was requested, but the library in use is a sequential version. Running in sequential mode instead\"\n                )\n            method = \"sequential\"\n\n        if method == \"parallel\":\n            dll = self.get_dll(dll_id).copy()\n            dll_id = self.get_dll_id(dll)\n        else:\n            dll = self.get_dll(dll_id)\n\n        # Input Model data to C library\n        dll.SetLibraryPath()\n        if passLineList:\n            dll.InputLineList(sme.linelist)\n        if updateLineList:\n            # TODO Currently Updates the whole linelist, could be improved to only change affected lines\n            dll.UpdateLineList(sme.atomic, sme.species, np.arange(len(sme.linelist)))\n        if passAtmosphere:\n            sme = self.get_atmosphere(sme)\n            dll.InputModel(sme.teff, sme.logg, sme.vmic, sme.atmo)\n            dll.InputAbund(sme.abund)\n            dll.Ionization(0)\n            dll.SetVWscale(sme.gam6)\n            dll.SetH2broad(sme.h2broad)\n        if passNLTE:\n            sme.nlte.update_coefficients(sme, dll, self.lfs_nlte)\n\n        # Loop over segments\n        #   Input Wavelength range and Opacity\n        #   Calculate spectral synthesis for each\n        #   Interpolate onto geomspaced wavelength grid\n        #   Apply instrumental and turbulence broadening\n\n        # TODO Parallelization\n        # This requires changes in the C code however, since SME uses global parameters\n        # for the wavelength range (and opacities) which change within each segment\n        if dll.parallel:\n            self.parallel_synthesize_segments(\n                sme,\n                segments,\n                wmod,\n                smod,\n                cmod,\n                reuse_wavelength_grid,\n                dll_id=dll,\n            )\n        else:\n            self.sequential_synthesize_segments(\n                sme,\n                segments,\n                wmod,\n                smod,\n                cmod,\n                reuse_wavelength_grid,\n                dll_id=dll,\n            )\n\n        for il in segments:\n            if \"wave\" not in sme or len(sme.wave[il]) == 0:\n                # trim padding\n                wbeg, wend = sme.wran[il]\n                itrim = (wmod[il] > wbeg) & (wmod[il] < wend)\n                # Force endpoints == wavelength range\n                wave[il] = np.concatenate(([wbeg], wmod[il][itrim], [wend]))\n\n        if sme.specific_intensities_only:\n            return wmod, smod, cmod\n\n        # Fit continuum and radial velocity\n        # And interpolate the flux onto the wavelength grid\n        if radial_velocity_mode == \"robust\":\n            cscale, cscale_unc, vrad, vrad_unc = match_rv_continuum(\n                sme, segments, wmod, smod\n            )\n            logger.debug(\"Radial velocity: %s\", str(vrad))\n            logger.debug(\"Continuum coefficients: %s\", str(cscale))\n        elif radial_velocity_mode == \"fast\":\n            cscale, vrad = sme.cscale, sme.vrad\n        else:\n            raise ValueError(\"Radial Velocity mode not understood\")\n\n        smod, cmod = self.apply_radial_velocity_and_continuum(\n            wave,\n            sme.spec,\n            wmod,\n            smod,\n            cmod,\n            vrad,\n            cscale,\n            sme.cscale_type,\n            segments,\n        )\n\n        # Merge all segments\n        # if sme already has a wavelength this should be the same\n        if updateStructure:\n            if \"wave\" not in sme:\n                # TODO: what if not all segments are there?\n                sme.wave = wave\n            if \"synth\" not in sme:\n                sme.synth = smod\n            if \"cont\" not in sme:\n                sme.cont = cmod\n\n            for s in segments:\n                sme.wave[s] = wave[s]\n                sme.synth[s] = smod[s]\n                sme.cont[s] = cmod[s]\n\n            if sme.cscale_type in [\"spline\", \"spline+mask\"]:\n                sme.cscale = cscale\n                sme.cscale_unc = cscale_unc\n            elif sme.cscale_flag not in [\"fix\", \"none\"]:\n                for s in segments:\n                    sme.cscale[s] = cscale[s]\n                sme.cscale_unc = cscale_unc\n\n            sme.vrad = np.asarray(vrad)\n            sme.vrad_unc = np.asarray(vrad_unc)\n            sme.nlte.flags = dll.GetNLTEflags()\n            result = sme\n        else:\n            wave = Iliffe_vector(values=wave)\n            smod = Iliffe_vector(values=smod)\n            cmod = Iliffe_vector(values=cmod)\n            result = wave, smod, cmod\n\n        # Cleanup\n        return result\n\n    def synthesize_segment(\n        self,\n        sme,\n        segment,\n        reuse_wavelength_grid=False,\n        keep_line_opacity=False,\n        method=\"sequential\",\n        dll_id=None,\n    ):\n        \"\"\"Create the synthetic spectrum of a single segment\n\n        Parameters\n        ----------\n        sme : SME_Struct\n            The SME strcuture containing all relevant parameters\n        segment : int\n            the segment to synthesize\n        reuse_wavelength_grid : bool\n            Whether to keep the current wavelength grid for the synthesis\n            or create a new one, depending on the linelist. Default: False\n        keep_line_opacity : bool\n            Whether to reuse existing line opacities or not. This should be\n            True iff the opacities have been calculated in another segment.\n\n        Returns\n        -------\n        wgrid : array of shape (npoints,)\n            Wavelength grid of the synthesized spectrum\n        flux : array of shape (npoints,)\n            The Flux of the synthesized spectrum\n        cont_flux : array of shape (npoints,)\n            The continuum Flux of the synthesized spectrum\n        \"\"\"\n        logger.debug(\"Segment %i out of %i\", segment, sme.nseg)\n        if method == \"parallel\":\n            dll = self.get_dll(dll_id).copy()\n            dll_id = self.get_dll_id(dll)\n        else:\n            dll = self.get_dll(dll_id)\n\n        # Input Wavelength range and Opacity\n        vrad_seg = sme.vrad[segment] if sme.vrad[segment] is not None else 0\n        wbeg, wend = self.get_wavelengthrange(sme.wran[segment], vrad_seg, sme.vsini)\n\n        dll.InputWaveRange(wbeg, wend)\n        dll.Opacity()\n\n        # Reuse adaptive wavelength grid in the jacobians\n        if reuse_wavelength_grid and segment in self.wint.keys():\n            wint_seg = self.wint[segment]\n        else:\n            wint_seg = None\n\n        # Only calculate line opacities in the first segment\n        #   Calculate spectral synthesis for each\n        _, wint, sint, cint = dll.Transf(\n            sme.mu,\n            sme.accrt,  # threshold line opacity / cont opacity\n            sme.accwi,\n            keep_lineop=keep_line_opacity,\n            wave=wint_seg,\n        )\n        # Store the adaptive wavelength grid for the future\n        # if it was newly created\n        if wint_seg is None:\n            self.wint[segment] = wint\n\n        if not sme.specific_intensities_only:\n            # Create new geomspaced wavelength grid, to be used for intermediary steps\n            wgrid, vstep = self.new_wavelength_grid(wint)\n\n            logger.debug(\"Integrate specific intensities\")\n            # Radiative Transfer Integration\n            # Continuum\n            cint = self.integrate_flux(sme.mu, cint, 1, 0, 0)\n            cint = np.interp(wgrid, wint, cint)\n\n            # Broaden Spectrum\n            y_integrated = np.empty((sme.nmu, len(wgrid)))\n            for imu in range(sme.nmu):\n                y_integrated[imu] = np.interp(wgrid, wint, sint[imu])\n\n            # Turbulence broadening\n            # Apply macroturbulent and rotational broadening while integrating intensities\n            # over the stellar disk to produce flux spectrum Y.\n            sint = self.integrate_flux(sme.mu, y_integrated, vstep, sme.vsini, sme.vmac)\n            wint = wgrid\n\n            # instrument broadening\n            if \"iptype\" in sme:\n                logger.debug(\"Apply detector broadening\")\n                ipres = sme.ipres if np.size(sme.ipres) == 1 else sme.ipres[segment]\n                sint = broadening.apply_broadening(\n                    ipres, wint, sint, type=sme.iptype, sme=sme\n                )\n\n        # Divide calculated spectrum by continuum\n        if sme.normalize_by_continuum:\n            sint /= cint\n\n        return wint, sint, cint\n\n\ndef synthesize_spectrum(sme, segments=\"all\"):\n    synthesizer = Synthesizer()\n    return synthesizer.synthesize_spectrum(sme, segments)\n", "meta": {"hexsha": "212f1cc502360833238b139285559051dbff5119", "size": 34811, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/pysme/synthesize.py", "max_stars_repo_name": "AWehrhahn/SME", "max_stars_repo_head_hexsha": "542e880ed779381f7cbbaaacb59475fa6a6d3537", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-06-26T18:43:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T00:53:42.000Z", "max_issues_repo_path": "src/pysme/synthesize.py", "max_issues_repo_name": "AWehrhahn/SME", "max_issues_repo_head_hexsha": "542e880ed779381f7cbbaaacb59475fa6a6d3537", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-03-01T15:21:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-01T15:28:37.000Z", "max_forks_repo_path": "src/pysme/synthesize.py", "max_forks_repo_name": "AWehrhahn/SME", "max_forks_repo_head_hexsha": "542e880ed779381f7cbbaaacb59475fa6a6d3537", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-03-01T15:25:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T10:26:33.000Z", "avg_line_length": 39.0257847534, "max_line_length": 133, "alphanum_fraction": 0.5667174169, "include": true, "reason": "import numpy,from scipy", "num_tokens": 8367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.15286495784282544}}
{"text": "# coding: utf-8\nimport logging\n\nfrom amuse.units import nbody_system, units, constants\n\nfrom amuse.couple.bridge import CalculateFieldForCodesUsingReinitialize\n\nfrom amuse.community.hermite0.interface import Hermite\nfrom amuse.community.ph4.interface import ph4\nfrom amuse.community.rebound.interface import Rebound\nfrom amuse.community.fi.interface import Fi\nfrom amuse.community.gadget2.interface import Gadget2\nfrom amuse.community.fastkick.interface import FastKick\nfrom amuse.community.seba.interface import SeBa\nfrom amuse.community.kepler_orbiters.interface import Kepler\nfrom amuse.community.bonsai.interface import Bonsai\n\nimport numpy as np\n\nlogger = logging.getLogger(__name__)\n\ndef new_code_gravity(\n        converter,\n        epsilon,\n        p,\n        ):\n    if p.codes_gravity == \"ph4\":\n        gravity = new_code_gravity_ph4(\n                converter,\n                epsilon,\n                p,\n                )\n    elif p.codes_gravity == \"Hermite\":\n        gravity = new_code_gravity_hermite(\n                converter,\n                epsilon,\n                p,\n                )\n    elif p.codes_gravity == \"Rebound\":\n        gravity = new_code_gravity_rebound(\n                converter,\n                epsilon,\n                p,\n                )\n    else:\n        logger.error(\n                \"No gravity code %s known\"%(\n                    p.codes_gravity,\n                    ),\n                )\n        exit()\n    logger.info(\n            \"Gravity code %s added\"%(\n                p.codes_gravity,\n                ),\n            )\n    return gravity\n    \ndef new_code_gravity_rebound(\n        converter,\n        epsilon,\n        p,\n        ):\n    result  = Rebound(\n            converter,\n            redirection     = \"file\",\n            redirect_file   = (\n                p.dir_codelogs + \"/gravity_code.log\"\n                )\n            )\n    result.initialize_code()\n    print(result.parameters)\n    result.parameters.epsilon_squared   = p.particles_epsilon**2\n    result.parameters.integrator    = p.codes_gravity_integrator\n    result.parameters.timestep      = p.timestep_integrator\n    result.parameters.solver        = p.codes_gravity_solver\n    result.parameters.boundary      = p.codes_gravity_boundary\n    result.parameters.boundary_size = p.codes_gravity_boundary_size\n    result.parameters.exact_finish_time = 0\n    return result\n\n\ndef new_code_gravity_bonsai(\n        converter,\n        epsilon,\n        p,\n        ):\n    result  = Bonsai(\n            converter,\n            redirection     = \"file\",\n            redirect_file   = (\n                p.dir_codelogs + \"/gravity_code.log\"\n                )\n            )\n    result.initialize_code()\n    result.parameters.timestep          = p.timestep_integrator\n    return result\n\ndef new_code_gravity_ph4(\n        converter,\n        epsilon,\n        p,\n        ):\n    result  = ph4(\n            converter,\n            redirection     = \"file\",\n            mode            = \"gpu\" if p.codes_gravity == \"gpu\" else \"cpu\",\n            redirect_file   = (\n                p.dir_codelogs + \"/gravity_code.log\"\n                )\n            )\n    result.initialize_code()\n    result.parameters.epsilon_squared   = epsilon**2\n    return result\n\ndef new_code_gravity_hermite(\n        converter,\n        epsilon,\n        p,\n        ):\n    result  = Hermite(\n            converter,\n            redirection     = \"file\",\n            redirect_file   = (\n                p.dir_codelogs + \"/gravity_code.log\"\n                )\n            )\n    result.parameters.epsilon_squared           = epsilon**2\n    result.parameters.end_time_accuracy_factor  = 0\n    return result\n\n\n\n\nclass kepler_for_bridge(object):\n    def __init__(self, converter):\n        self.code = Kepler(converter)\n        self.model_time = self.code.model_time\n        self.central_particle = self.code.central_particle\n        self.orbiters = self.code.orbiters\n        \n    def evolve_model(self, t_end):\n        self.code.evolve_model(t_end)\n        self.model_time = self.code.model_time\n\n    def get_gravity_at_point(self, radius, x, y, z):\n        mass = self.central_particle.mass\n        xc, yc, zc = self.central_particle[0].position\n        dr2 = ((x-xc)**2+(y-yc)**2+(z-zc)**2+radius**2)\n        dr = dr2**0.5\n        ax = -mass*(x-xc)/(dr2*dr)\n        ay = -mass*(y-yc)/(dr2*dr)\n        az = -mass*(z-zc)/(dr2*dr)\n\n        for body in self.orbiters:\n            mass = body.mass\n            xc, yc, zc = body.position\n            dr2 = ((x-xc)**2 + (y-yc)**2 + (z-zc)**2 + radius**2)\n            dr = dr2**0.5\n            ax -= mass*(x-xc)/(dr2*dr)\n            ay -= mass*(y-yc)/(dr2*dr)\n            az -= mass*(z-zc)/(dr2*dr)\n        ax *= constants.G\n        ay *= constants.G\n        az *= constants.G\n        return ax,ay,az\n\n    def get_potential_at_point(self, radius, x, y, z):\n        mass = self.central_particle.mass\n        xc, yc, zc = self.central_particle.position\n        dr2 = ((x-xc)**2+(y-yc)**2+(z-zc)**2+radius**2)\n        dr = dr2**0.5\n        phi = -mass/dr\n\n        for body in self.orbiters:\n            mass = body.mass\n            xc, yc, zc = body.position\n            dr2 = ((x-xc)**2+(y-yc)**2+(z-zc)**2+radius**2)\n            dr = dr2**0.5\n            phi -= mass/dr\n        return phi\n\nclass non_central_kepler(object):\n    #################\n    #### Testing ####\n    #################\n    def __init__(self, converter):\n        self.code = Kepler(converter)\n        self.model_time = self.code.model_time\n        self.central_particle = self.code.central_particle\n        self.orbiters = self.code.orbiters\n        self.particles = self.orbiters\n\n    #def add_particles(particles):\n    #    code.particles.add_particles(particles)\n    #\n    #def remove_particles():\n\n    def evolve_model(self, t_end):\n        self.pc = self.central_particle.position\n        self.vc = self.central_particle.velocity\n\n        self.central_particle.position -= self.pc\n        self.orbiters.position -= self.pc\n        self.central_particle.velocity -= self.vc\n        self.orbiters.velocity -= self.vc\n\n        self.code.evolve_model(t_end)\n        self.model_time = self.code.model_time\n\n        self.central_particle.position += self.pc\n        self.orbiters.position += self.pc\n        self.central_particle.velocity += self.vc\n        self.orbiters.velocity += self.vc\n\n    def stop(self):\n        self.code.stop()\n\n    def get_gravity_at_point(self, radius, x, y, z):\n        self.code.get_gravity_at_point(radius, x, y, z)\n\n    def get_potential_at_point(self, radius, x, y, z):\n        self.code.get_potential_at_point(radius, x, y, z)\n\n\nclass advance_without_selfgravity(object):\n    \"\"\"\n    Code by Lucie Jilkóva\n    to advance particles\n    \"\"\"\n    def __init__(self, particles, time= 0 |units.Myr):\n        self.particles = particles\n        self.model_time = time\n    \n    def evolve_model(self, t_end):\n        dt = t_end - self.model_time\n        self.particles.position += self.particles.velocity*dt\n        self.model_time= t_end\n    \n    @property\n    def potential_energy(self):\n        return quantities.zero\n    \n    @property \n    def kinetic_energy(self):\n        return (0.5*self.particles.mass*self.particles.velocity.lengths()**2).sum()\n\n    def get_gravity_at_point(self, radius, x, y, z):\n        fr = (0|units.kg) * constants.G / (1 | units.m**2)\n        ax = -0*fr*x/(1|units.m)\n        ay = -0*fr*x/(1|units.m)\n        az = -0*fr*x/(1|units.m)\n        return ax,ay,az\n\n\nclass Star(object):\n    def __init__(\n            self,\n            M = 1.0 | units.MSun,\n            R = 1.0 | units.RSun,\n            ):\n        self.R = R\n        self.M = M\n\n    def get_gravity_at_point(self, eps, x, y, z):\n        r2  = x**2+y**2+z**2\n        r   = r2**0.5\n        fr  = constants.G*self.M/r2\n        ax  = -fr*x/r\n        ay  = -fr*y/r\n        az  = -fr*z/r\n        return ax,ay,az\n\n    def get_potential_at_point(self,eps,x,y,z):\n        r2=x**2+y**2+z**2\n        r=r2**0.5\n        c=constant.G*self.M\n        phi=c/(r*r2)\n        return phi    \n\n    def vcirc(self,r):  \n        vc=(constants.G*self.M/r)**0.5\n        return vc\n\ndef hill_radius(\n        eccentricity,\n        semimajor_axis,\n        minor_mass,\n        major_mass,\n        ):\n\n    return ((1 - eccentricity) * semimajor_axis * (minor_mass/(3*major_mass))**(1./3) )\n\ndef cylindrical_from_xyz(\n        particles,\n        ):\n    particles.r       = particles.position.lengths()\n    particles.theta   = np.arccos(particles.z/particles.r)\n    particles.phi     = np.arctan2(\n            particles.y.value_in(units.AU),\n            particles.x.value_in(units.AU),\n            )\n    return \n\ndef xyz_from_cylindrical(\n        orbiters,\n        ):\n    x = (orbiters.r * np.cos(orbiters.phi))\n    y = (orbiters.r * np.sin(orbiters.phi))\n    z = 0*x\n    return [x,y,z]\n\ndef kepler_orbit(\n        orbiters, \n        centre, \n        a_over_r = 1.,\n        ):\n    r = orbiters.position.lengths()\n    a = a_over_r * r\n    mu = constants.G * centre.mass\n    vx +=  (np.sin(orbiters.phi)*(mu * (2./orbiters.r - 1./a))**0.5)\n    vy += -(np.cos(orbiters.phi)*(mu * (2./orbiters.r - 1./a))**0.5)\n    vz += 0|units.kms\n    orbiters.initial_orbital_period = 2 * np.pi * (a**3 / mu)**0.5\n    return r, [vx,vy,vz]\n\ndef eccentricity(\n        orbiters,\n        centre,\n        ):\n    length_unit = units.AU\n    speed_unit = units.kms\n    rmag = (orbiters.position - centre.position).lengths()\n    r = (orbiters.position - centre.position)\n    rs = (orbiters.position - centre.position).value_in(length_unit)\n    v = (orbiters.velocity - centre.velocity)\n    vs = (orbiters.velocity - centre.velocity).value_in(speed_unit)\n    h = np.cross(rs,vs)\n    mu = (constants.G * centre.mass).value_in(length_unit * speed_unit**2)\n    tmp = np.cross(vs,h)/mu\n    e = np.array([tmp[:,0]-r[:,0]/rmag,tmp[:,1]-r[:,1]/rmag,tmp[:,2]-r[:,2]/rmag])\n\n    emag = (e[0,:]**2+e[1,:]**2+e[2,:]**2)**0.5\n\n    return e, emag\n\n\ndef orbital_periods(\n        allorbiters,\n        planet,\n        ):\n    orbiters = allorbiters\n    r   = orbiters.position - planet.position\n    v   = orbiters.velocity - planet.velocity\n    rabs = r.lengths()\n    vabs = v.lengths()\n    a   = (constants.G * planet[0].mass) * rabs / (\n            (2 * constants.G * planet[0].mass) - rabs*vabs*vabs )\n    orbital_periods = (2 * np.pi * (a**3 / (constants.G * planet[0].mass))).sqrt()\n\n    return orbital_periods\n\n\ndef kepler_periastron_velocity(\n        mass    = 1.0 | units.MSun,\n        epsilon = 0.0,\n        a       = 1.0 | units.AU,\n        ): \n    mu      = constants.G * mass\n    v_per   = np.sqrt( ((1+epsilon)*mu)/((1-epsilon)*a)) \n    return v_per\n\n\ndef kepler_apastron_velocity(\n        mass    = 1.0 | units.MSun,\n        epsilon = 0.0,\n        a       = 1.0 | units.AU,\n        ): \n    mu      = constants.G * mass\n    v_apo   = np.sqrt( ((1-epsilon)*mu)/((1+epsilon)*a)) \n    return v_apo\n\n\n", "meta": {"hexsha": "e58ec96c87bf7b22154dcf03bef062ca35e993a5", "size": 10912, "ext": "py", "lang": "Python", "max_stars_repo_path": "setup_codes.py", "max_stars_repo_name": "rieder/grps", "max_stars_repo_head_hexsha": "a8cea14fe851090f633d47e778daec49bd994be8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "setup_codes.py", "max_issues_repo_name": "rieder/grps", "max_issues_repo_head_hexsha": "a8cea14fe851090f633d47e778daec49bd994be8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "setup_codes.py", "max_forks_repo_name": "rieder/grps", "max_forks_repo_head_hexsha": "a8cea14fe851090f633d47e778daec49bd994be8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4166666667, "max_line_length": 87, "alphanum_fraction": 0.5582844575, "include": true, "reason": "import numpy", "num_tokens": 2864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.15286495784282544}}
{"text": "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom npu_bridge.npu_init import *\nimport csv\nimport numpy as np\nimport cv2\nimport os\n\n\nclass FrameCalibrationData:\n    \"\"\"Frame Calibration Holder\n        3x4    p0-p3      Camera P matrix. Contains extrinsic\n                          and intrinsic parameters.\n\n        3x3    r0_rect    Rectification matrix, required to transform points\n                          from velodyne to camera coordinate frame.\n\n        3x4    tr_velodyne_to_cam    Used to transform from velodyne to cam\n                                     coordinate frame according to:\n                                     Point_Camera = P_cam * R0_rect *\n                                                    Tr_velo_to_cam *\n                                                    Point_Velodyne.\n        \"\"\"\n\n    def __init__(self):\n        self.p0 = []\n        self.p1 = []\n        self.p2 = []\n        self.p3 = []\n        self.r0_rect = []\n        self.tr_velodyne_to_cam = []\n\n\nclass StereoCalibrationData:\n    \"\"\"Stereo Calibration Holder\n        1    baseline    distance between the two camera centers.\n\n        1    f    focal length.\n\n        3x3    k    intrinsic calibration matrix.\n\n        3x4    p    camera matrix.\n\n        1    center_u    camera origin u coordinate.\n\n        1    center_v    camera origin v coordinate.\n    \"\"\"\n\n    def __init__(self):\n        self.baseline = 0.0\n        self.f = 0.0\n        self.k = []\n        self.p = []\n        self.center_u = 0.0\n        self.center_v = 0.0\n\n\ndef read_calibration(calib_dir, img_idx):\n    \"\"\"Reads in Calibration file from Kitti Dataset.\n\n    Keyword Arguments:\n    ------------------\n    calib_dir : Str\n                Directory of the calibration files.\n\n    img_idx : Int\n              Index of the image.\n\n    cam : Int\n          Camera used from 0-3.\n\n    Returns:\n    --------\n    frame_calibration_info : FrameCalibrationData\n                             Contains a frame's full calibration data.\n\n    \"\"\"\n    frame_calibration_info = FrameCalibrationData()\n\n    data_file = open(calib_dir + \"/%06d.txt\" % img_idx, 'r')\n    data_reader = csv.reader(data_file, delimiter=' ')\n    data = []\n\n    for row in data_reader:\n        data.append(row)\n\n    data_file.close()\n\n    p_all = []\n\n    for i in range(4):\n        p = data[i]\n        p = p[1:]\n        p = [float(p[i]) for i in range(len(p))]\n        p = np.reshape(p, (3, 4))\n        p_all.append(p)\n\n    frame_calibration_info.p0 = p_all[0]\n    frame_calibration_info.p1 = p_all[1]\n    frame_calibration_info.p2 = p_all[2]\n    frame_calibration_info.p3 = p_all[3]\n\n    # Read in rectification matrix\n    tr_rect = data[4]\n    tr_rect = tr_rect[1:]\n    tr_rect = [float(tr_rect[i]) for i in range(len(tr_rect))]\n    frame_calibration_info.r0_rect = np.reshape(tr_rect, (3, 3))\n\n    # Read in velodyne to cam matrix\n    tr_v2c = data[5]\n    tr_v2c = tr_v2c[1:]\n    tr_v2c = [float(tr_v2c[i]) for i in range(len(tr_v2c))]\n    frame_calibration_info.tr_velodyne_to_cam = np.reshape(tr_v2c, (3, 4))\n\n    return frame_calibration_info\n\n\ndef krt_from_p(p, fsign=1):\n    \"\"\"Factorize the projection matrix P as P=K*[R;t]\n    and enforce the sign of the focal length to be fsign.\n\n\n    Keyword Arguments:\n    ------------------\n    p : 3x4 list\n        Camera Matrix.\n\n    fsign : int\n            Sign of the focal length.\n\n\n    Returns:\n    --------\n    k : 3x3 list\n        Intrinsic calibration matrix.\n\n    r : 3x3 list\n        Extrinsic rotation matrix.\n\n    t : 1x3 list\n        Extrinsic translation.\n    \"\"\"\n    s = p[0:3, 3]\n    q = np.linalg.inv(p[0:3, 0:3])\n    u, b = np.linalg.qr(q)\n    sgn = np.sign(b[2, 2])\n    b = b * sgn\n    s = s * sgn\n\n    # If the focal length has wrong sign, change it\n    # and change rotation matrix accordingly.\n    if fsign * b[0, 0] < 0:\n        e = [[-1, 0, 0], [0, 1, 0], [0, 0, 1]]\n        b = np.matmul(e, b)\n        u = np.matmul(u, e)\n\n    if fsign * b[2, 2] < 0:\n        e = [[1, 0, 0], [0, -1, 0], [0, 0, 1]]\n        b = np.matmul(e, b)\n        u = np.matmul(u, e)\n\n    # If u is not a rotation matrix, fix it by flipping the sign.\n    if np.linalg.det(u) < 0:\n        u = -u\n        s = -s\n\n    r = np.matrix.transpose(u)\n    t = np.matmul(b, s)\n    k = np.linalg.inv(b)\n    k = k / k[2, 2]\n\n    # Sanity checks to ensure factorization is correct\n    if np.linalg.det(r) < 0:\n        print('Warning: R is not a rotation matrix.')\n\n    if k[2, 2] < 0:\n        print('Warning: K has a wrong sign.')\n\n    return k, r, t\n\n\ndef get_stereo_calibration(left_cam_mat, right_cam_mat):\n    \"\"\"Extract parameters required to transform disparity image to 3D point\n    cloud.\n\n    Keyword Arguments:\n    ------------------\n    left_cam_mat : 3x4 list\n                   Left Camera Matrix.\n\n    right_cam_mat : 3x4 list\n                   Right Camera Matrix.\n\n\n    Returns:\n    --------\n    stereo_calibration_info : Instance of StereoCalibrationData class\n                              Placeholder for stereo calibration parameters.\n    \"\"\"\n\n    stereo_calibration_info = StereoCalibrationData()\n    k_left, r_left, t_left = krt_from_p(left_cam_mat)\n    _, _, t_right = krt_from_p(right_cam_mat)\n\n    stereo_calibration_info.baseline = abs(t_left[0] - t_right[0])\n    stereo_calibration_info.f = k_left[0, 0]\n    stereo_calibration_info.center_u = k_left[0, 2]\n    stereo_calibration_info.center_v = k_left[1, 2]\n    stereo_calibration_info.k = k_left\n    stereo_calibration_info.p = left_cam_mat\n\n    return stereo_calibration_info\n\n\ndef depth_from_disparity(disp, stereo_calibration_info, flatten_order='C'):\n    \"\"\"Transform disparity map to 3d point cloud.\n\n    Camera coordinate frame:\n    X: right\n    Y: down\n    Z: forward\n\n    Example Usage found in:\n        /demo/kitti\n\n    Keyword Arguments:\n    ------------------\n    disp : cv2 mat\n           disparity image.\n\n    stereo_calibration_info : Instance of StereoCalibrationData class\n                              Contains frame's stereo calibration info.\n\n    flatten_order : (optional) see numpy.ndarray.flatten\n        Specifies the way the depth array is flattened\n        'C' - (default) row-major (C-style) order\n        'F' - column-major (Fortran- style) order\n\n    Returns:\n    --------\n    x : nd array\n        x-coordinates of point cloud, every pixel has a value. Arranged in row\n         major format.\n\n    y : nd array\n        y-coordinates of point cloud, every pixel has a value. Arranged in row\n         major format\n\n    z : nd array\n        z-coordinates of point cloud, every pixel has a value. Arranged in row\n         major format\n\n      \"\"\"\n\n    disp = np.single(disp)\n    disp = np.divide(disp, 256)\n    disp[disp == 0] = 0.1\n\n    depth = np.ones(disp.shape, np.single)\n    depth = np.multiply(depth,\n                        stereo_calibration_info.f *\n                        stereo_calibration_info.baseline)\n\n    depth = np.divide(depth, np.double(disp))\n\n    sz = np.shape(depth)\n    depth = depth.flatten(flatten_order)\n\n    xx, yy = np.meshgrid(\n        np.arange(1, sz[1] + 1, 1), np.arange(1, sz[0] + 1, 1))\n\n    xx = xx.flatten(flatten_order) - stereo_calibration_info.center_u\n    yy = yy.flatten(flatten_order) - stereo_calibration_info.center_v\n\n    temp = np.divide(depth, stereo_calibration_info.f)\n\n    x = np.multiply(xx, temp)\n    y = np.multiply(yy, temp)\n    z = depth\n\n    return x, y, z\n\n\ndef project_to_image(point_cloud, p):\n    \"\"\" Projects a 3D point cloud to 2D points for plotting\n\n    :param point_cloud: 3D point cloud (3, N)\n    :param p: Camera matrix (3, 4)\n\n    :return: pts_2d: the image coordinates of the 3D points in the shape (2, N)\n    \"\"\"\n\n    pts_2d = np.dot(p, np.append(point_cloud,\n                                 np.ones((1, point_cloud.shape[1])),\n                                 axis=0))\n\n    pts_2d[0, :] = pts_2d[0, :] / pts_2d[2, :]\n    pts_2d[1, :] = pts_2d[1, :] / pts_2d[2, :]\n    pts_2d = np.delete(pts_2d, 2, 0)\n    return pts_2d\n\n\ndef read_disparity(disp_dir, img_idx):\n    \"\"\"Reads in Disparity file from Kitti Dataset.\n\n        Keyword Arguments:\n        ------------------\n        calib_dir : Str\n                    Directory of the disparity files.\n\n        img_idx : Int\n                  Index of the image.\n\n        Returns:\n        --------\n        disp_img : Numpy Array\n                   Contains the disparity image.\n\n        [] : if file is not found\n\n        \"\"\"\n    disp_path = disp_dir + \"/%06d_left_disparity.png\" % img_idx\n\n    if os.path.exists(disp_path):\n        disp_img = cv2.imread(disp_path, cv2.IMREAD_ANYDEPTH)\n        return disp_img\n    else:\n        return []\n\n\ndef read_lidar(velo_dir, img_idx):\n    \"\"\"Reads in PointCloud from Kitti Dataset.\n\n        Keyword Arguments:\n        ------------------\n        velo_dir : Str\n                    Directory of the velodyne files.\n\n        img_idx : Int\n                  Index of the image.\n\n        Returns:\n        --------\n        x : Numpy Array\n                   Contains the x coordinates of the pointcloud.\n        y : Numpy Array\n                   Contains the y coordinates of the pointcloud.\n        z : Numpy Array\n                   Contains the z coordinates of the pointcloud.\n        i : Numpy Array\n                   Contains the intensity values of the pointcloud.\n\n        [] : if file is not found\n\n        \"\"\"\n    velo_dir = velo_dir + \"/%06d.bin\" % img_idx\n\n    if os.path.exists(velo_dir):\n        with open(velo_dir, 'rb') as fid:\n            data_array = np.fromfile(fid, np.single)\n\n        xyzi = data_array.reshape(-1, 4)\n\n        x = xyzi[:, 0]\n        y = xyzi[:, 1]\n        z = xyzi[:, 2]\n        i = xyzi[:, 3]\n\n        return x, y, z, i\n    else:\n        return []\n\n\ndef lidar_to_cam_frame(xyz_lidar, frame_calib):\n    \"\"\"Transforms the pointclouds to the camera 0 frame.\n\n        Keyword Arguments:\n        ------------------\n        xyz_lidar : N x 3 Numpy Array\n                  Contains the x,y,z coordinates of the lidar pointcloud\n\n        frame_calib : FrameCalibrationData\n                  Contains calibration information for a given frame\n\n        Returns:\n        --------\n        ret_xyz : Numpy Array\n                   Contains the xyz coordinates of the transformed pointcloud.\n\n        \"\"\"\n\n    # Pad the r0_rect matrix to a 4x4\n    r0_rect_mat = frame_calib.r0_rect\n    r0_rect_mat = np.pad(r0_rect_mat, ((0, 1), (0, 1)),\n                         'constant', constant_values=0)\n    r0_rect_mat[3, 3] = 1\n\n    # Pad the tr_vel_to_cam matrix to a 4x4\n    tf_mat = frame_calib.tr_velodyne_to_cam\n    tf_mat = np.pad(tf_mat, ((0, 1), (0, 0)),\n                    'constant', constant_values=0)\n    tf_mat[3, 3] = 1\n\n    # Pad the pointcloud with 1's for the transformation matrix multiplication\n    one_pad = np.ones(xyz_lidar.shape[0]).reshape(-1, 1)\n    xyz_lidar = np.append(xyz_lidar, one_pad, axis=1)\n\n    # p_cam = P2 * R0_rect * Tr_velo_to_cam * p_velo\n    rectified = np.dot(r0_rect_mat, tf_mat)\n    ret_xyz = np.dot(rectified, xyz_lidar.T)\n\n    # Change to N x 3 array for consistency.\n    return ret_xyz[0:3].T\n\n", "meta": {"hexsha": "6b3f51cb61b40db01d18bb566e6423166230f59b", "size": 12303, "ext": "py", "lang": "Python", "max_stars_repo_path": "wavedata/wavedata/tools/core/calib_utils.py", "max_stars_repo_name": "Ascend-Huawei/AVOD", "max_stars_repo_head_hexsha": "ea62372517bbfa9d4020bc5ab2739ee182c63c56", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "wavedata/wavedata/tools/core/calib_utils.py", "max_issues_repo_name": "Ascend-Huawei/AVOD", "max_issues_repo_head_hexsha": "ea62372517bbfa9d4020bc5ab2739ee182c63c56", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wavedata/wavedata/tools/core/calib_utils.py", "max_forks_repo_name": "Ascend-Huawei/AVOD", "max_forks_repo_head_hexsha": "ea62372517bbfa9d4020bc5ab2739ee182c63c56", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.834841629, "max_line_length": 79, "alphanum_fraction": 0.5832723726, "include": true, "reason": "import numpy", "num_tokens": 3180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.28140561345566495, "lm_q1q2_score": 0.15276477522371518}}
{"text": "\"\"\"\nA module for parsing information from various files.\n\"\"\"\n\nimport os\nimport re\nfrom typing import Dict, List, Match, Optional, Tuple, Union\n\nimport numpy as np\nimport pandas as pd\nimport qcelemental as qcel\n\nfrom arkane.exceptions import LogError\nfrom arkane.ess import ess_factory, GaussianLog, MolproLog, OrcaLog, QChemLog, TeraChemLog\n\nfrom arc.common import determine_ess, get_close_tuple, get_logger, is_same_pivot\nfrom arc.exceptions import InputError, ParserError\nfrom arc.species.converter import str_to_xyz, xyz_from_data\n\n\nlogger = get_logger()\n\n\ndef parse_frequencies(path: str,\n                      software: str,\n                      ) -> np.ndarray:\n    \"\"\"\n    Parse the frequencies from a freq job output file.\n\n    Args:\n        path (str): The log file path.\n        software (str): The ESS.\n\n    Returns: np.ndarray\n        The parsed frequencies (in cm^-1).\n    \"\"\"\n    lines = _get_lines_from_file(path)\n    freqs = np.array([], np.float64)\n    if software.lower() == 'qchem':\n        for line in lines:\n            if ' Frequency:' in line:\n                items = line.split()\n                for i, item in enumerate(items):\n                    if i:\n                        freqs = np.append(freqs, [(float(item))])\n    elif software.lower() == 'gaussian':\n        with open(path, 'r') as f:\n            line = f.readline()\n            while line != '':\n                # this line intends to only capture the last occurrence of the frequencies\n                if 'and normal coordinates' in line:\n                    freqs = np.array([], np.float64)\n                if 'Frequencies --' in line:\n                    freqs = np.append(freqs, [float(frq) for frq in line.split()[2:]])\n                line = f.readline()\n    elif software.lower() == 'molpro':\n        read = False\n        for line in lines:\n            if 'Nr' in line and '[1/cm]' in line:\n                continue\n            if read:\n                if line == os.linesep:\n                    read = False\n                    continue\n                freqs = np.append(freqs, [float(line.split()[-1])])\n            if 'Low' not in line and 'Vibration' in line and 'Wavenumber' in line:\n                read = True\n    elif software.lower() == 'orca':\n        with open(path, 'r') as f:\n            line = f.readline()\n            read = True\n            while line:\n                if 'VIBRATIONAL FREQUENCIES' in line:\n                    while read:\n                        if not line.strip():\n                            line = f.readline()\n                        elif not line.split()[0] == '0:':\n                            line = f.readline()\n                        else:\n                            read = False\n                    while line.strip():\n                        if float(line.split()[1]) != 0.0:\n                            freqs = np.append(freqs, [float(line.split()[1])])\n                        line = f.readline()\n                    break\n                else:\n                    line = f.readline()\n    elif software.lower() == 'terachem':\n        read_output = False\n        for line in lines:\n            if '=== Mode' in line:\n                # example: '=== Mode 1: 1198.526 cm^-1 ==='\n                freqs = np.append(freqs, [float(line.split()[3])])\n            elif 'Vibrational Frequencies/Thermochemical Analysis After Removing Rotation and Translation' in line:\n                read_output = True\n                continue\n            elif read_output:\n                if 'Temperature (Kelvin):' in line or 'Frequency(cm-1)' in line:\n                    continue\n                if not line.strip():\n                    break\n                # example:\n                # 'Mode  Eigenvalue(AU)  Frequency(cm-1)  Intensity(km/mol)   Vib.Temp(K)      ZPE(AU) ...'\n                # '  1     0.0331810528   170.5666870932      52.2294230772  245.3982965841   0.0003885795 ...'\n                freqs = np.append(freqs, [float(line.split()[2])])\n\n    else:\n        raise ParserError(f'parse_frequencies() can currently only parse Gaussian, Molpro, Orca, QChem and TeraChem '\n                          f'files, got {software}')\n    logger.debug(f'Using parser.parse_frequencies(). Determined frequencies are: {freqs}')\n    return freqs\n\n\ndef parse_normal_displacement_modes(path: str,\n                                    software: Optional[str] = None,\n                                    ) -> Tuple[np.ndarray, np.ndarray]:\n    \"\"\"\n    Parse frequencies and normal displacement modes.\n\n    Args:\n        path (str): The path to the log file.\n        software (str, optional): The software to used to generate the log file.\n\n    Raises:\n        NotImplementedError: If the parser is not implemented for the ESS this log file belongs to.\n\n    Returns: Tuple[np.ndarray, np.ndarray]\n        The frequencies (in cm^-1) and The normal displacement modes.\n    \"\"\"\n    software = software or determine_ess(path)\n    freqs, normal_disp_modes, normal_disp_modes_entries = list(), list(), list()\n    num_of_freqs_per_line = 3\n    with open(path, 'r') as f:\n        lines = f.readlines()\n    if software == 'gaussian':\n        parse, parse_normal_disp_modes = False, False\n        for line in lines:\n            if 'Harmonic frequencies (cm**-1)' in line:\n                # e.g.:  Harmonic frequencies (cm**-1), IR intensities (KM/Mole), Raman scattering\n                parse = True\n            if parse and len(line.split()) in [0, 1, 3]:\n                parse_normal_disp_modes = False\n                normal_disp_modes.extend(normal_disp_modes_entries)\n                normal_disp_modes_entries = list()\n            if parse and 'Frequencies --' in line:\n                # e.g.:  Frequencies --    -18.0696               127.6948               174.9499\n                splits = line.split()\n                freqs.extend(float(freq) for freq in splits[2:])\n                num_of_freqs_per_line = len(splits) - 2\n                normal_disp_modes_entries = list()\n            elif parse_normal_disp_modes:\n                # parsing, e.g.:\n                #   Atom  AN      X      Y      Z        X      Y      Z        X      Y      Z\n                #      1   6    -0.00   0.00  -0.09    -0.00   0.00  -0.18     0.00  -0.00  -0.16\n                #      2   7    -0.00   0.00  -0.10     0.00  -0.00   0.02     0.00  -0.00   0.26\n                splits = line.split()[2:]\n                for i in range(num_of_freqs_per_line):\n                    if len(normal_disp_modes_entries) < i + 1:\n                        normal_disp_modes_entries.append(list())\n                    normal_disp_modes_entries[i].append(splits[3 * i: 3 * i + 3])\n            elif parse and 'Atom  AN      X      Y      Z' in line:\n                parse_normal_disp_modes = True\n            elif parse and not line or '-------------------' in line:\n                parse = False\n    else:\n        raise NotImplementedError(f'parse_normal_displacement_modes is currently not implemented for {software}.')\n    freqs = np.array(freqs, np.float64)\n    normal_disp_modes = np.array(normal_disp_modes, np.float64)\n    return freqs, normal_disp_modes\n\n\ndef parse_geometry(path: str) -> Optional[Dict[str, tuple]]:\n    \"\"\"\n    Parse the xyz geometry from an ESS log file.\n\n    Args:\n        path (str): The ESS log file to parse from.\n\n    Returns: Optional[Dict[str, tuple]]\n        The cartesian geometry.\n    \"\"\"\n    log = ess_factory(fullpath=path)\n    try:\n        coords, number, _ = log.load_geometry()\n    except LogError:\n        logger.debug(f'Could not parse xyz from {path}')\n\n        # try parsing Gaussian standard orientation instead of the input orientation parsed by Arkane\n        lines = _get_lines_from_file(path)\n        xyz_str = ''\n        for i in range(len(lines)):\n            if 'Standard orientation:' in lines[i]:\n                xyz_str = ''\n                j = i\n                while len(lines) and not lines[j].split()[0].isdigit():\n                    j += 1\n                while len(lines) and '-------------------' not in lines[j]:\n                    splits = lines[j].split()\n                    xyz_str += f'{qcel.periodictable.to_E(int(splits[1]))}  {splits[3]}  {splits[4]}  {splits[5]}\\n'\n                    j += 1\n                break\n\n        if xyz_str:\n            return str_to_xyz(xyz_str)\n\n        return None\n\n    return xyz_from_data(coords=coords, numbers=number)\n\n\ndef parse_t1(path: str) -> Optional[float]:\n    \"\"\"\n    Parse the T1 parameter from a Molpro or Orca coupled cluster calculation.\n\n    Args:\n        path (str): The ess log file path.\n\n    Returns: Optional[float]\n        The T1 parameter.\n    \"\"\"\n    if not os.path.isfile(path):\n        raise InputError('Could not find file {0}'.format(path))\n    log = ess_factory(fullpath=path)\n    try:\n        t1 = log.get_T1_diagnostic()\n    except (LogError, NotImplementedError):\n        logger.warning('Could not read t1 from {0}'.format(path))\n        t1 = None\n    return t1\n\n\ndef parse_e_elect(path: str,\n                  zpe_scale_factor: float = 1.,\n                  ) -> Optional[float]:\n    \"\"\"\n    Parse the electronic energy from an sp job output file.\n\n    Args:\n        path (str): The ESS log file to parse from.\n        zpe_scale_factor (float): The ZPE scaling factor, used only for composite methods in Gaussian via Arkane.\n\n    Returns: Optional[float]\n        The electronic energy in kJ/mol.\n    \"\"\"\n    if not os.path.isfile(path):\n        raise InputError(f'Could not find file {path}')\n    log = ess_factory(fullpath=path)\n    try:\n        e_elect = log.load_energy(zpe_scale_factor) * 0.001  # convert to kJ/mol\n    except (LogError, NotImplementedError):\n        logger.warning(f'Could not read e_elect from {path}')\n        e_elect = None\n    return e_elect\n\n\ndef parse_zpe(path: str) -> Optional[float]:\n    \"\"\"\n    Determine the calculated ZPE from a frequency output file\n\n    Args:\n        path (str): The path to a frequency calculation output file.\n\n    Returns: Optional[float]\n        The calculated zero point energy in kJ/mol.\n    \"\"\"\n    if not os.path.isfile(path):\n        raise InputError('Could not find file {0}'.format(path))\n    log = ess_factory(fullpath=path)\n    try:\n        zpe = log.load_zero_point_energy() * 0.001  # convert to kJ/mol\n    except (LogError, NotImplementedError):\n        logger.warning('Could not read zpe from {0}'.format(path))\n        zpe = None\n    return zpe\n\n\ndef parse_1d_scan_energies(path: str) -> Tuple[Optional[List[float]], Optional[List[float]]]:\n    \"\"\"\n    Parse the 1D torsion scan energies from an ESS log file.\n\n    Args:\n        path (str): The ESS log file to parse from.\n\n    Raises:\n        InputError: If ``path`` is invalid.\n\n    Returns: Tuple[Optional[List[float]], Optional[List[float]]]\n        The electronic energy in kJ/mol and the dihedral scan angle in degrees.\n    \"\"\"\n    if not os.path.isfile(path):\n        raise InputError(f'Could not find file {path}')\n    log = ess_factory(fullpath=path)\n    try:\n        energies, angles = log.load_scan_energies()\n        energies *= 0.001  # convert to kJ/mol\n        angles *= 180 / np.pi  # convert to degrees\n    except (LogError, NotImplementedError, ZeroDivisionError):\n        logger.warning(f'Could not read energies from {path}')\n        energies, angles = None, None\n    return energies, angles\n\n\ndef parse_1d_scan_coords(path: str) -> List[Dict[str, tuple]]:\n    \"\"\"\n    Parse the 1D torsion scan coordinates from an ESS log file.\n\n    Args:\n        path (str): The ESS log file to parse from.\n\n    Returns: list\n        The Cartesian coordinates.\n    \"\"\"\n    lines = _get_lines_from_file(path)\n    log = ess_factory(fullpath=path)\n    if not isinstance(log, GaussianLog):\n        raise NotImplementedError(f'Currently parse_1d_scan_coords only supports Gaussian files, got {type(log)}')\n    traj = list()\n    done = False\n    i = 0\n    while not done:\n        if i >= len(lines) or 'Normal termination of Gaussian' in lines[i] or 'Error termination via' in lines[i]:\n            done = True\n        elif 'Optimization completed' in lines[i]:\n            while len(lines) and 'Input orientation:' not in lines[i]:\n                i += 1\n            i += 5\n            xyz_str = ''\n            while len(lines) and '--------------------------------------------' not in lines[i]:\n                splits = lines[i].split()\n                xyz_str += f'{qcel.periodictable.to_E(int(splits[1]))}  {splits[3]}  {splits[4]}  {splits[5]}\\n'\n                i += 1\n            traj.append(str_to_xyz(xyz_str))\n        i += 1\n    return traj\n\n\ndef parse_nd_scan_energies(path: str,\n                           software: Optional[str] = None,\n                           return_original_dihedrals: bool = False,\n                           ) -> Tuple[dict, Optional[List[float]]]:\n    \"\"\"\n    Parse the ND torsion scan energies from an ESS log file.\n\n    Args:\n        path (str): The ESS log file to parse from.\n        software (str, optional): The software used to run this scan, default is 'gaussian'.\n        return_original_dihedrals (bool, optional): Whether to return the dihedral angles of the original conformer.\n                                                    ``True`` to return, default is ``False``.\n\n    Raises:\n        InputError: If ``path`` is invalid.\n\n    Returns: Tuple[dict, Optional[List[float]]]\n        The \"results\" dictionary, which has the following structure::\n\n              results = {'directed_scan_type': <str, used for the fig name>,\n                         'scans': <list, entries are lists of torsion indices>,\n                         'directed_scan': <dict, keys are tuples of '{0:.2f}' formatted dihedrals,\n                                           values are dictionaries with the following keys and values:\n                                           {'energy': <float, energy in kJ/mol>,  * only this is used here\n                                            'xyz': <dict>,\n                                            'is_isomorphic': <bool>,\n                                            'trsh': <list, job.ess_trsh_methods>}>\n                         },\n\n        The dihedrals angles of the original conformer\n    \"\"\"\n    software = software or determine_ess(path)\n    results = {'directed_scan_type': f'ess_{software}',\n               'scans': list(),\n               'directed_scan': dict(),\n               }\n    if software == 'gaussian':\n        # internal variables:\n        # - scan_d_dict (dict): keys are scanning dihedral names (e.g., 'D2', or 'D4'), values are the corresponding\n        #                       torsion indices tuples (e.g., (4, 1, 2, 5), or (4, 1, 3, 6)).\n        # - dihedrals_dict (dict): keys are torsion tuples (e.g., (4, 1, 2, 5), or (4, 1, 3, 6)),\n        #                          values are lists of dihedral angles in degrees corresponding to the torsion\n        #                          (e.g., [-159.99700, -149.99690, -139.99694, -129.99691, -119.99693]).\n        # - torsions (list): entries are torsion indices that are scanned, e.g.: [(4, 1, 2, 5), (4, 1, 3, 6)]\n        with open(path, 'r', buffering=8192) as f:\n            line = f.readline()\n            symbols, torsions, shape, resolution, original_dihedrals = list(), list(), list(), list(), list()\n            scan_d_dict = dict()\n            min_e = None\n            while line:\n                line = f.readline()\n                if 'The following ModRedundant input section has been read:' in line:\n                    # ' The following ModRedundant input section has been read:'\n                    # ' D       4       1       2       5 S  36 10.000'\n                    # ' D       4       1       3       6 S  36 10.000'\n                    line = f.readline()\n                    while True:\n                        splits = line.split()\n                        if len(splits) == 8:\n                            torsions.append(tuple([int(index) for index in splits[1:5]]))\n                            shape.append(int(splits[6]) + 1)  # the last point is repeated\n                            resolution.append(float(splits[7]))\n                        else:\n                            break\n                        line = f.readline()\n                    results['scans'] = torsions\n                    if 'Symbolic Z-matrix:' in line:\n                        #  ---------------------\n                        #  HIR calculation by AI\n                        #  ---------------------\n                        #  Symbolic Z-matrix:\n                        #  Charge =  0 Multiplicity = 1\n                        #  c\n                        #  o                    1    oc2\n                        #  o                    1    oc3      2    oco3\n                        #  o                    1    oc4      2    oco4     3    dih4     0\n                        #  h                    2    ho5      1    hoc5     3    dih5     0\n                        #  h                    3    ho6      1    hoc6     4    dih6     0\n                        #        Variables:\n                        #   oc2                   1.36119\n                        #   oc3                   1.36119\n                        #   oco3                114.896\n                        #   oc4                   1.18581\n                        #   oco4                122.552\n                        #   dih4                180.\n                        #   ho5                   0.9637\n                        #   hoc5                111.746\n                        #   dih5                 20.003\n                        #   ho6                   0.9637\n                        #   hoc6                111.746\n                        #   dih6               -160.\n                        for i in range(2):\n                            f.readline()\n                        while 'Variables' not in line:\n                            symbols.append(line.split()[0].upper())\n                            line = f.readline()\n                if 'Initial Parameters' in line:\n                    #                            ----------------------------\n                    #                            !    Initial Parameters    !\n                    #                            ! (Angstroms and Degrees)  !\n                    #  --------------------------                            --------------------------\n                    #  ! Name  Definition              Value          Derivative Info.                !\n                    #  --------------------------------------------------------------------------------\n                    #  ! R1    R(1,2)                  1.3612         calculate D2E/DX2 analytically  !\n                    #  ! R2    R(1,3)                  1.3612         calculate D2E/DX2 analytically  !\n                    #  ! R3    R(1,4)                  1.1858         calculate D2E/DX2 analytically  !\n                    #  ! R4    R(2,5)                  0.9637         calculate D2E/DX2 analytically  !\n                    #  ! R5    R(3,6)                  0.9637         calculate D2E/DX2 analytically  !\n                    #  ! A1    A(2,1,3)              114.896          calculate D2E/DX2 analytically  !\n                    #  ! A2    A(2,1,4)              122.552          calculate D2E/DX2 analytically  !\n                    #  ! A3    A(3,1,4)              122.552          calculate D2E/DX2 analytically  !\n                    #  ! A4    A(1,2,5)              111.746          calculate D2E/DX2 analytically  !\n                    #  ! A5    A(1,3,6)              111.746          calculate D2E/DX2 analytically  !\n                    #  ! D1    D(3,1,2,5)             20.003          calculate D2E/DX2 analytically  !\n                    #  ! D2    D(4,1,2,5)           -159.997          Scan                            !\n                    #  ! D3    D(2,1,3,6)             20.0            calculate D2E/DX2 analytically  !\n                    #  ! D4    D(4,1,3,6)           -160.0            Scan                            !\n                    #  --------------------------------------------------------------------------------\n                    for i in range(5):\n                        line = f.readline()\n                    # original_zmat = {'symbols': list(), 'coords': list(), 'vars': dict()}\n                    while '--------------------------' not in line:\n                        splits = line.split()\n                        # key = splits[2][:-1].replace('(', '_').replace(',', '_')\n                        # val = float(splits[3])\n                        # original_zmat['symbols'].append(symbols[len(original_zmat['symbols'])])\n                        # original_zmat['vars'][key] = val\n                        if 'Scan' in line:\n                            scan_d_dict[splits[1]] = \\\n                                tuple([int(index) for index in splits[2][2:].replace(')', '').split(',')])\n                            original_dihedrals.append(float(splits[3]))\n                        line = f.readline()\n\n                elif 'Summary of Optimized Potential Surface Scan' in line:\n                    # ' Summary of Optimized Potential Surface Scan (add -264.0 to energies):'\n                    base_e = float(line.split('(add ')[1].split()[0])\n                    energies, dihedrals_dict = list(), dict()\n                    dihedral_num = 0\n                    while 'Grad' not in line:\n                        line = f.readline()\n                        splits = line.split()\n                        if 'Eigenvalues --' in line:\n                            # convert Hartree energy to kJ/mol\n                            energies = [(base_e + float(e)) * 4.3597447222071e-18 * 6.02214179e23 * 1e-3\n                                        for e in splits[2:]]\n                            min_es = min(energies)\n                            min_e = min_es if min_e is None else min(min_e, min_es)\n                            dihedral_num = 0\n                        if splits[0] in list(scan_d_dict.keys()) \\\n                                and scan_d_dict[splits[0]] not in list(dihedrals_dict.keys()):\n                            # parse the dihedral information\n                            # '           D1          20.00308  30.00361  40.05829  50.36777  61.07341'\n                            # '           D2        -159.99700-149.99690-139.99694-129.99691-119.99693'\n                            # '           D3          19.99992  19.99959  19.94509  19.63805  18.93967'\n                            # '           D4        -160.00000-159.99990-159.99994-159.99991-159.99993'\n                            dihedrals = [float(dihedral) for dihedral in line.replace('-', ' -').split()[1:]]\n                            for i in range(len(dihedrals)):\n                                if 0 > dihedrals[i] >= -0.0049999:\n                                    dihedrals[i] = 0.0\n                            dihedrals_dict[scan_d_dict[splits[0]]] = dihedrals\n                            dihedral_num += 1\n                        if len(list(dihedrals_dict.keys())) == len(list(scan_d_dict.keys())):\n                            # we have all the data for this block, pass to ``results`` and initialize ``dihedrals_dict``\n                            for i, energy in enumerate(energies):\n                                dihedral_list = [dihedrals_dict[torsion][i] for torsion in torsions]  # ordered\n                                key = tuple(f'{dihedral:.2f}' for dihedral in dihedral_list)\n                                # overwrite previous values for a close key if found:\n                                key = get_close_tuple(key, results['directed_scan'].keys()) or key\n                                results['directed_scan'][key] = {'energy': energy}\n                            dihedrals_dict = dict()  # keys are torsion tuples, values are dihedral angles\n                    break\n            line = f.readline()\n    else:\n        raise NotImplementedError(f'parse_nd_scan_energies is currently only implemented for Gaussian, got {software}.')\n    for key in results['directed_scan'].keys():\n        results['directed_scan'][key] = {'energy': results['directed_scan'][key]['energy'] - min_e}\n    if return_original_dihedrals:\n        return results, original_dihedrals\n    else:\n        return results, None\n\n\ndef parse_xyz_from_file(path: str) -> Optional[Dict[str, tuple]]:\n    \"\"\"\n    Parse xyz coordinated from:\n    - .xyz: XYZ file\n    - .gjf: Gaussian input file\n    - .out or .log: ESS output file (Gaussian, Molpro, Orca, QChem, TeraChem) - calls parse_geometry()\n    - other: Molpro or QChem input file\n\n    Args:\n        path (str): The file path.\n\n    Raises:\n        ParserError: If the coordinates could not be parsed.\n\n    Returns: Optional[Dict[str, tuple]]\n        The parsed cartesian coordinates.\n    \"\"\"\n    lines = _get_lines_from_file(path)\n    file_extension = os.path.splitext(path)[1]\n\n    xyz = None\n    relevant_lines = list()\n\n    if file_extension == '.xyz':\n        for i, line in enumerate(reversed(lines)):\n            splits = line.strip().split()\n            if len(splits) == 1 and all([c.isdigit() for c in splits[0]]):\n                # this is the last number of atoms line (important when parsing trajectories)\n                num_of_atoms = int(splits[0])\n                break\n        else:\n            raise ParserError(f'Could not identify the number of atoms line in the xyz file {path}')\n        index = len(lines) - i - 1\n        relevant_lines = lines[index + 2: index + 2 + num_of_atoms]\n    elif file_extension == '.gjf':\n        start_parsing = False\n        for line in lines:\n            if start_parsing and line and line != '\\n' and line != '\\r\\n':\n                relevant_lines.append(line)\n            elif start_parsing:\n                break\n            else:\n                splits = line.split()\n                if len(splits) == 2 and all([s.isdigit() for s in splits]):\n                    start_parsing = True\n    elif 'out' in file_extension or 'log' in file_extension:\n        xyz = parse_geometry(path)\n    else:\n        record = False\n        for line in lines:\n            if '$end' in line or '}' in line:\n                break\n            if record and len(line.split()) == 4:\n                relevant_lines.append(line)\n            elif '$molecule' in line:\n                record = True\n            elif 'geometry={' in line:\n                record = True\n        if not relevant_lines:\n            raise ParserError(f'Could not parse xyz coordinates from file {path}')\n    if xyz is None and relevant_lines:\n        xyz = str_to_xyz(''.join([line for line in relevant_lines if line]))\n    return xyz\n\n\ndef parse_trajectory(path: str) -> List[Dict[str, tuple]]:\n    \"\"\"\n    Parse all geometries from an xyz trajectory file or an ESS output file.\n\n    Args:\n        path (str): The file path.\n\n    Raises:\n        ParserError: If the trajectory could not be read.\n\n    Returns: List[Dict[str, tuple]]\n        Entries are xyz's on the trajectory.\n    \"\"\"\n    lines = _get_lines_from_file(path)\n\n    ess_file = False\n    if path.split('.')[-1] != 'xyz':\n        try:\n            log = ess_factory(fullpath=path)\n            ess_file = True\n        except InputError:\n            ess_file = False\n\n    if ess_file:\n        if not isinstance(log, GaussianLog):\n            raise NotImplementedError(f'Currently parse_trajectory only supports Gaussian files, got {type(log)}')\n        traj = list()\n        done = False\n        i = 0\n        while not done:\n            if i >= len(lines) or 'Normal termination of Gaussian' in lines[i] or 'Error termination via' in lines[i]:\n                done = True\n            elif 'Input orientation:' in lines[i]:\n                i += 5\n                xyz_str = ''\n                while len(lines) and '--------------------------------------------' not in lines[i]:\n                    splits = lines[i].split()\n                    xyz_str += f'{qcel.periodictable.to_E(int(splits[1]))}  {splits[3]}  {splits[4]}  {splits[5]}\\n'\n                    i += 1\n                traj.append(str_to_xyz(xyz_str))\n            i += 1\n\n    else:\n        # this is not an ESS output file, probably an XYZ format file with several Cartesian coordinates\n        skip_line = False\n        num_of_atoms = 0\n        traj, xyz_lines = list(), list()\n        for line in lines:\n            splits = line.strip().split()\n            if len(splits) == 1 and all([c.isdigit() for c in splits[0]]):\n                if len(xyz_lines):\n                    if len(xyz_lines) != num_of_atoms:\n                        raise ParserError(f'Could not parse trajectory, expected {num_of_atoms} atoms, '\n                                          f'but got {len(xyz_lines)} for point {len(traj) + 1} in the trajectory.')\n                    traj.append(str_to_xyz(''.join([xyz_line for xyz_line in xyz_lines])))\n                num_of_atoms = int(splits[0])\n                skip_line = True\n                xyz_lines = list()\n            elif skip_line:\n                # skip the comment line\n                skip_line = False\n                continue\n            else:\n                xyz_lines.append(line)\n\n        if len(xyz_lines):\n            # add the last point in the trajectory\n            if len(xyz_lines) != num_of_atoms:\n                raise ParserError(f'Could not parse trajectory, expected {num_of_atoms} atoms, '\n                                  f'but got {len(xyz_lines)} for point {len(traj) + 1} in the trajectory.')\n            traj.append(str_to_xyz(''.join([xyz_line for xyz_line in xyz_lines])))\n\n    if not len(traj):\n        raise ParserError(f'Could not parse trajectory from {path}')\n    return traj\n\n\ndef parse_dipole_moment(path: str) -> Optional[float]:\n    \"\"\"\n    Parse the dipole moment in Debye from an opt job output file.\n\n    Args:\n        path: The ESS log file.\n\n    Returns: Optional[float]\n        The dipole moment in Debye.\n    \"\"\"\n    lines = _get_lines_from_file(path)\n    log = ess_factory(path)\n    dipole_moment = None\n    if isinstance(log, GaussianLog):\n        # example:\n        # Dipole moment (field-independent basis, Debye):\n        # X=             -0.0000    Y=             -0.0000    Z=             -1.8320  Tot=              1.8320\n        read = False\n        for line in lines:\n            if 'dipole moment' in line.lower() and 'debye' in line.lower():\n                read = True\n            elif read:\n                dipole_moment = float(line.split()[-1])\n                read = False\n    elif isinstance(log, MolproLog):\n        # example: ' Dipole moment /Debye                   2.96069859     0.00000000     0.00000000'\n        for line in lines:\n            if 'dipole moment' in line.lower() and '/debye' in line.lower():\n                splits = line.split()\n                dm_x, dm_y, dm_z = float(splits[-3]), float(splits[-2]), float(splits[-1])\n                dipole_moment = (dm_x ** 2 + dm_y ** 2 + dm_z ** 2) ** 0.5\n    elif isinstance(log, OrcaLog):\n        # example: 'Magnitude (Debye)      :      2.11328'\n        for line in lines:\n            if 'Magnitude (Debye)' in line:\n                dipole_moment = float(line.split()[-1])\n    elif isinstance(log, QChemLog):\n        # example:\n        #     Dipole Moment (Debye)\n        #          X       0.0000      Y       0.0000      Z       2.0726\n        #        Tot       2.0726\n        skip = False\n        read = False\n        for line in lines:\n            if 'dipole moment' in line.lower() and 'debye' in line.lower():\n                skip = True\n            elif skip:\n                skip = False\n                read = True\n            elif read:\n                dipole_moment = float(line.split()[-1])\n                read = False\n    elif isinstance(log, TeraChemLog):\n        # example: 'DIPOLE MOMENT: {-0.000178, -0.000003, -0.000019} (|D| = 0.000179) DEBYE'\n        for line in lines:\n            if 'dipole moment' in line.lower() and 'debye' in line.lower():\n                splits = line.split('{')[1].split('}')[0].replace(',', '').split()\n                dm_x, dm_y, dm_z = float(splits[0]), float(splits[1]), float(splits[2])\n                dipole_moment = (dm_x ** 2 + dm_y ** 2 + dm_z ** 2) ** 0.5\n    else:\n        raise ParserError('Currently dipole moments can only be parsed from either Gaussian, Molpro, Orca, QChem, '\n                          'or TeraChem optimization output files')\n    if dipole_moment is None:\n        raise ParserError('Could not parse the dipole moment')\n    return dipole_moment\n\n\ndef parse_polarizability(path: str) -> Optional[float]:\n    \"\"\"\n    Parse the polarizability from a freq job output file, returns the value in Angstrom^3.\n\n    Args:\n        path: The ESS log file.\n\n    Returns: Optional[float]\n        The polarizability in Angstrom^3.\n    \"\"\"\n    lines = _get_lines_from_file(path)\n    polarizability = None\n    for line in lines:\n        if 'Isotropic polarizability for W' in line:\n            # example:  Isotropic polarizability for W=    0.000000       11.49 Bohr**3.\n            # 1 Bohr = 0.529177 Angstrom\n            polarizability = float(line.split()[-2]) * 0.529177 ** 3\n    return polarizability\n\n\ndef _get_lines_from_file(path: str) -> List[str]:\n    \"\"\"\n    A helper function for getting a list of lines from a file.\n\n    Args:\n        path (str): The file path.\n\n    Raises:\n        InputError: If the file could not be read.\n\n    Returns: List[str]\n        Entries are lines from the file.\n    \"\"\"\n    if os.path.isfile(path):\n        with open(path, 'r') as f:\n            lines = f.readlines()\n    else:\n        raise InputError(f'Could not find file {path}')\n    return lines\n\n\ndef process_conformers_file(conformers_path: str) -> Tuple[List[Dict[str, tuple]], List[float]]:\n    \"\"\"\n    Parse coordinates and energies from an ARC conformers file of either species or TSs.\n\n    Args:\n        conformers_path (str): The path to an ARC conformers file\n                               (either a \"conformers_before_optimization\" or\n                               a \"conformers_after_optimization\" file).\n\n    Raises:\n        InputError: If the file could not be found.\n\n    Returns: Tuple[List[Dict[str, tuple]], List[float]]\n        Conformer coordinates in a dict format, the respective energies in kJ/mol.\n    \"\"\"\n    if not os.path.isfile(conformers_path):\n        raise InputError('Conformers file {0} could not be found'.format(conformers_path))\n    with open(conformers_path, 'r') as f:\n        lines = f.readlines()\n    xyzs, energies = list(), list()\n    line_index = 0\n    while line_index < len(lines):\n        if 'conformer' in lines[line_index] and ':' in lines[line_index] and lines[line_index].strip()[-2].isdigit():\n            xyz, energy = '', None\n            line_index += 1\n            while len(lines) and line_index < len(lines) and lines[line_index].strip() \\\n                    and 'SMILES' not in lines[line_index] \\\n                    and 'energy' not in lines[line_index].lower() \\\n                    and 'guess method' not in lines[line_index].lower():\n                xyz += lines[line_index]\n                line_index += 1\n            while len(lines) and line_index < len(lines) and 'conformer' not in lines[line_index]:\n                if 'relative energy:' in lines[line_index].lower():\n                    energy = float(lines[line_index].split()[2])\n                line_index += 1\n            xyzs.append(str_to_xyz(xyz))\n            energies.append(energy)\n        else:\n            line_index += 1\n    return xyzs, energies\n\n\ndef parse_str_blocks(file_path: str,\n                     head_pat: Union[Match, str],\n                     tail_pat: Union[Match, str],\n                     regex: bool = True,\n                     tail_count: int = 1,\n                     block_count: int = 1,\n                     ) -> List[str]:\n    \"\"\"\n    Return a list of blocks defined by the head pattern and the tail pattern.\n\n    Args:\n        file_path (str): The path to the readable file.\n        head_pat (str/regex): Str pattern or regular expression of the head of the block.\n        tail_pat (str/regex): Str pattern or regular expresion of the tail of the block.\n        regex (bool, optional): Use regex (True) or str pattern (False) to search.\n        tail_count (int, optional): The number of times that the tail repeats.\n        block_count (int, optional): The max number of blocks to search. -1 for any number.\n\n    Raises:\n        InputError: If the file could not be found.\n\n    Returns: List[str]\n        List of str blocks.\n    \"\"\"\n    if not os.path.isfile(file_path):\n        raise InputError('Could not find file {0}'.format(file_path))\n    with open(file_path, 'r') as f:\n        blks = []\n        # Different search mode\n        if regex:\n            def search(x, y):\n                return re.search(x, y)\n        else:\n            def search(x, y):\n                return x in y\n        # 'search' for the head or 'read' until the tail\n        mode = 'search'\n        line = f.readline()\n        while line != '':\n            if mode == 'search':\n                # Stop searching if found enough blocks\n                if (len(blks)) == block_count:\n                    break\n                # Check if matching the head pattern\n                else:\n                    match = search(head_pat, line)\n                    # Switch to 'read' mode\n                    if match:\n                        tail_repeat = 0\n                        mode = 'read'\n                        blks.append([])\n                        blks[-1].append(line)\n            elif mode == 'read':\n                blks[-1].append(line)\n                match = search(tail_pat, line)\n                if match:\n                    tail_repeat += 1\n                    # If see enough tail patterns, switch to 'search' mode\n                    if tail_repeat == tail_count:\n                        mode = 'search'\n            line = f.readline()\n        # Remove the last incomplete search\n        if len(blks) > 0 and (tail_repeat != tail_count):\n            blks.pop()\n        return blks\n\n\ndef parse_scan_args(file_path: str) -> dict:\n    \"\"\"\n    Get the scan arguments, including which internal coordinates (IC) are being scanned, which are frozen,\n    what is the step size and the number of atoms, etc.\n\n    Args:\n        file_path (str): The path to a readable output file.\n\n    Raises:\n        NotImplementedError: If files other than Gaussian log is input\n\n    Returns: dict\n        A dictionary that contains the scan arguments as well as step number, step size, number of atom::\n\n              {'scan': <list, atom indexes of the torsion to be scanned>,\n               'freeze': <list, list of internal coordinates identified by atom indexes>,\n               'step': <int, number of steps to scan>,\n               'step_size': <float, the size of each step>,\n               'n_atom': <int, the number of atoms of the molecule>,\n               }\n    \"\"\"\n    log = ess_factory(fullpath=file_path)\n    scan_args = {'scan': None, 'freeze': [],\n                 'step': 0, 'step_size': 0, 'n_atom': 0}\n    if isinstance(log, GaussianLog):\n        try:\n            # g09, g16\n            scan_blk = parse_str_blocks(file_path, 'The following ModRedundant input section has been read:',\n                                        'Isotopes and Nuclear Properties', regex=False)[0][1:-1]\n        except IndexError:  # Cannot find any block\n            # g03\n            scan_blk_1 = parse_str_blocks(file_path, 'The following ModRedundant input section has been read:',\n                                          'GradGradGradGrad', regex=False)[0][1:-2]\n            scan_blk_2 = parse_str_blocks(file_path, 'NAtoms=',\n                                          'One-electron integrals computed', regex=False)[0][:1]\n            scan_blk = scan_blk_1 + scan_blk_2\n        scan_pat = r'[DBA]?(\\s+\\d+){2,4}\\s+S\\s+\\d+[\\s\\d.]+'\n        frz_pat = r'[DBA]?(\\s+\\d+){2,4}\\s+F'\n        value_pat = r'[\\d.]+'\n        for line in scan_blk:\n            if re.search(scan_pat, line.strip()):\n                values = re.findall(value_pat, line)\n                scan_len = len(values) - 2  # atom indexes + step + stepsize\n                scan_args['scan'] = [int(values[i]) for i in range(scan_len)]\n                scan_args['step'] = int(values[-2])\n                scan_args['step_size'] = float(values[-1])\n            if re.search(frz_pat, line.strip()):\n                values = re.findall(value_pat, line)\n                scan_args['freeze'].append([int(values[i]) for i in range(len(values))])\n            if 'NAtoms' in line:\n                scan_args['n_atom'] = int(line.split()[1])\n    else:\n        raise NotImplementedError(f'parse_scan_args() can currently only parse Gaussian output '\n                                  f'files, got {log}')\n    return scan_args\n\n\ndef parse_ic_info(file_path: str) -> pd.DataFrame:\n    \"\"\"\n    Get the information of internal coordinates (ic) of an intermediate scan conformer.\n\n    Args:\n        file_path (str): The path to a readable output file.\n\n    Raises:\n        NotImplementedError: If files other than Gaussian log is input\n\n    Returns: pd.DataFrame\n        A DataFrame containing the information of the internal coordinates\n    \"\"\"\n    log = ess_factory(fullpath=file_path)\n    ic_dict = {item: []\n               for item in ['label', 'type', 'atoms', 'redundant', 'scan']}\n    scan_args = parse_scan_args(file_path)\n    max_atom_ind = scan_args['n_atom']\n    if isinstance(log, GaussianLog):\n        ic_info_block = parse_str_blocks(file_path, 'Initial Parameters', '-----------', regex=False,\n                                         tail_count=3)[0][5:-1]\n        for line in ic_info_block:\n            # Line example with split() indices:\n            # 0 1     2                        3              4         5       6            7\n            # ! R1    R(1, 2)                  1.3581         calculate D2E/DX2 analytically !\n            terms = line.split()\n            ic_dict['label'].append(terms[1])\n            ic_dict['type'].append(terms[1][0])  # 'R: bond, A: angle, D: dihedral\n            atom_inds = re.split(r'[(),]', terms[2])[1:-1]\n            ic_dict['atoms'].append([int(atom_ind) for atom_ind in atom_inds])\n\n            # Identify redundant, cases like 5 atom angles or redundant atoms\n            if (ic_dict['type'][-1] == 'A' and len(atom_inds) > 3) \\\n                    or (ic_dict['type'][-1] == 'R' and len(atom_inds) > 2) \\\n                    or (ic_dict['type'][-1] == 'D' and len(atom_inds) > 4):\n                ic_dict['redundant'].append(True)\n            else:\n                # Sometimes, redundant atoms with weird indices are added.\n                # Reason unclear. Maybe to better define the molecule, or to\n                # solve equations more easily.\n                weird_indices = [index for index in ic_dict['atoms'][-1]\n                                 if index <= 0 or index > max_atom_ind]\n                if weird_indices:\n                    ic_dict['redundant'].append(True)\n                else:\n                    ic_dict['redundant'].append(False)\n\n            # Identify ics being scanned\n            if len(scan_args['scan']) == len(atom_inds) == 4 \\\n                    and is_same_pivot(scan_args['scan'], ic_dict['atoms'][-1]):\n                ic_dict['scan'].append(True)\n            elif len(scan_args['scan']) == len(atom_inds) == 2 \\\n                    and set(scan_args['scan']) == set(ic_dict['atoms'][-1]):\n                ic_dict['scan'].append(True)\n            else:\n                # Currently doesn't support scan of angles\n                ic_dict['scan'].append(False)\n    else:\n        raise NotImplementedError(f'parse_ic_info() can currently only parse Gaussian output '\n                                  f'files, got {log}')\n    ic_info = pd.DataFrame.from_dict(ic_dict)\n    ic_info = ic_info.set_index('label')\n    return ic_info\n\n\ndef parse_ic_values(ic_block: List[str],\n                    software: Optional[str] = None,\n                    ) -> pd.DataFrame:\n    \"\"\"\n    Get the internal coordinates (ic) for an intermediate scan conformer\n\n    Args:\n        ic_block (list): A list of strings containing the optimized internal coordinates of\n        an intermediate scan conformer\n        software(str, optional): The software to used to generate the log file.\n\n    Raises:\n        NotImplementedError: If the software is not supported\n\n    Returns:\n        pd.DataFrame: A DataFrame containing the values of the internal coordinates\n    \"\"\"\n    ic_dict = {item: [] for item in ['label', 'value']}\n    if software == 'gaussian':\n        for line in ic_block:\n            # Line example with split() indices:\n            # 0 1     2                       3              4      5    6                   7\n            # ! R1    R(1,2)                  1.3602         -DE/DX =    0.0                 !\n            terms = line.split()\n            ic_dict['label'].append(terms[1])\n            ic_dict['value'].append(float(terms[3]))\n    else:\n        raise NotImplementedError(f'parse_ics() can currently only parse Gaussian output '\n                                  f'files, got {software}')\n    ics = pd.DataFrame.from_dict(ic_dict)\n    ics = ics.set_index('label')\n    return ics\n\n\ndef parse_scan_conformers(file_path: str) -> pd.DataFrame:\n    \"\"\"\n    Parse all the internal coordinates of all the scan intermediate conformers and tabulate\n    all the info into a single DataFrame object. Any redundant internal coordinates\n    will be removed during the process.\n\n    Args:\n        file_path (str): The path to a readable output file.\n\n    Raises:\n        NotImplementedError: If files other than Gaussian log is input\n\n    Returns:\n        pd.DataFrame: a list of conformers containing the all the internal\n                       coordinates information in pd.DataFrame\n    \"\"\"\n    log = ess_factory(fullpath=file_path)\n    scan_args = parse_scan_args(file_path)\n    scan_ic_info = parse_ic_info(file_path)\n    if isinstance(log, GaussianLog):\n        software = 'gaussian'\n        ic_blks = parse_str_blocks(file_path, 'Optimized Parameters', '-----------', regex=False,\n                                   tail_count=3, block_count=(scan_args['step'] + 1))\n    else:\n        raise NotImplementedError(f'parse_scan_conformers() can currently only parse Gaussian output '\n                                  f'files, got {log}')\n    # Extract IC values for each conformer\n    conformers = []\n    for ind, ic_blk in enumerate(ic_blks):\n        ics = parse_ic_values(ic_blk[5:-1], software)\n        ics.rename(columns={'value': ind}, inplace=True)\n        conformers.append(ics)\n    # Concatenate ICs of conformers to a single table and remove redundant ICs\n    scan_conformers = pd.concat([scan_ic_info] + conformers, axis=1)\n    red_ind = scan_conformers[scan_conformers.redundant == True].index\n    if not red_ind.empty:\n        scan_conformers.drop(red_ind, inplace=True)\n    return scan_conformers\n", "meta": {"hexsha": "6fd7965a5f0adf80dca59a65b05b84781addb635", "size": 47120, "ext": "py", "lang": "Python", "max_stars_repo_path": "arc/parser.py", "max_stars_repo_name": "hwpang/ARC", "max_stars_repo_head_hexsha": "2ca32d9b08fd78515f1c9aabcb69a400722b5b02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "arc/parser.py", "max_issues_repo_name": "hwpang/ARC", "max_issues_repo_head_hexsha": "2ca32d9b08fd78515f1c9aabcb69a400722b5b02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arc/parser.py", "max_forks_repo_name": "hwpang/ARC", "max_forks_repo_head_hexsha": "2ca32d9b08fd78515f1c9aabcb69a400722b5b02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.9552238806, "max_line_length": 120, "alphanum_fraction": 0.511778438, "include": true, "reason": "import numpy", "num_tokens": 10915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.28140561345566495, "lm_q1q2_score": 0.1527647710612613}}
{"text": "#!/usr/bin/env python\r\n# _*_ coding: utf-8 _*_\r\n\r\nimport os\r\nimport sys\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n\r\nclass PdosOut:\r\n    \"\"\"\r\n    \"\"\"\r\n    def __init__(self):\r\n        self.data = {} # contain the pdos data but not the tdos\r\n        self.tdos = None\r\n        self.energies = None\r\n\r\n    def get_data(self, directory=\"tmp-qe-static\", filpdos=\"projwfc\", usefermi=\"scf\"):\r\n        \"\"\"\r\n        this function first try to get fermi energy from the nscfout file\r\n        and if nscfout doesn't exist it will try to extract fermi energy\r\n        from scfout. if both don't exist, it will stop the program and\r\n        print out the warnnig, which guarantee that the fermi energy is\r\n        always shifted to 0\r\n\r\n        atomorb is a string in format like this atm#1(Li)_wfc#2(s).\r\n        \"\"\"\r\n        # first check whether there is a previous scf running\r\n        if not os.path.exists(directory):\r\n            print(\"===================================================\\n\")\r\n            print(\"                 Warning !!!\\n\")\r\n            print(\"===================================================\\n\")\r\n            print(\"pdos post:\\n\")\r\n            print(\"  directory of previous scf calculattion not found!\\n\")\r\n            sys.exit(1)\r\n\r\n        os.chdir(directory)\r\n        os.system(\"ls | grep '%s.pdos_' > projwfc-pdos-file.data\" % filpdos)\r\n        with open(\"projwfc-pdos-file.data\", 'r') as fin:\r\n            for line in fin:\r\n                if line.split(\".\")[1] == \"pdos_tot\\n\":\r\n                    with open(line.split()[0], 'r') as f:\r\n                        f.readline()\r\n                        self.tdos = np.loadtxt(f)\r\n                    continue\r\n                atmorb = line.split(\"_\")[1]+\"_\"+line.split(\"_\")[2].split()[0]\r\n                # atomorb is a string in format like this atm#1(Li)_wfc#2(s).\r\n                with open(line.split()[0], 'r') as f:\r\n                    f.readline()\r\n                    self.data[atmorb] = np.loadtxt(f)\r\n        # check information on spin\r\n        with open(\"%s.pdos_tot\" % filpdos, 'r') as fin:\r\n            first_line = fin.readline()\r\n        if \"pdosup(E)\" in first_line.split() and \"pdosdw(E)\" in first_line.split():\r\n            if \"dosup(E)\" in first_line.split() and \"dosdw(E)\" in first_line.split():\r\n                self.magnetic_status = \"collinear-spin-polarized\"\r\n            else:\r\n                self.magnetic_status = \"non-collinear-non-spin-orbit\"\r\n        else:\r\n            self.magnetic_status = \"collinear-spin-unpolarized\"\r\n        os.chdir(\"../\")\r\n\r\n        self.energies = self.tdos[:, 0]\r\n\r\n        # get fermi energy from scf or nscf output\r\n        scfout = \"static-scf.out\"\r\n        nscfout = \"static-nscf.out\"\r\n        if usefermi == \"scf\":\r\n            with open(os.path.join(directory, scfout), 'r') as fin:\r\n                for line in fin:\r\n                    if len(line.split()) == 0:\r\n                        continue\r\n                    if line.split()[0] == \"the\" and line.split()[1] == \"Fermi\":\r\n                        efermi = float(line.split()[4])\r\n        elif usefermi == \"nscf\":\r\n            with open(os.path.join(directory, nscfout), 'r') as fin:\r\n                for line in fin:\r\n                    if len(line.split()) == 0:\r\n                        continue\r\n                    if line.split()[0] == \"the\" and line.split()[1] == \"Fermi\":\r\n                        efermi = float(line.split()[4])\r\n        # shift fermie energy to 0\r\n        for i in range(len(self.energies)):\r\n            self.energies[i] = self.energies[i] - efermi\r\n        self.efermi = efermi\r\n        print(\"===============================================\\n\")\r\n        print(\"qe.post.pdos:\\n\")\r\n        print(\"we automatically shift the fermi energy\\n\")\r\n        print(\"from %f to 0\\n\" % efermi)\r\n        print(\"efermi is read from %s\\n\" % (\"statis-scf.out\" if usefermi == \"scf\" else \"statis-nscf.out\"))\r\n        print(\"you can choose to read efermi from scf or nscf output by --use-fermi\")\r\n        #\r\n        # tranfser self.data to new data structure for better usage:\r\n        self._transfer_data_to_new_struct()\r\n\r\n    def _transfer_data_to_new_struct(self):\r\n        \"\"\"\r\n        self.magnetic_status:\r\n            \"collinear-spin-unpolarized\" -> self.data_0\r\n            \"collinear-spin-polarized\" -> self.data_1\r\n            \"non-collinear-non-spin-orbit\" -> self.data_2\r\n            \"non-collinear-spin-orbit\" -> self.data_3\r\n        \"\"\"\r\n        if self.magnetic_status == \"collinear-spin-unpolarized\":\r\n            \"\"\"\r\n            # pdos are in format like this:\r\n            # E LDOS(E) PDOS_1(E) ... PDOS_2l+1(E)\r\n            # self.data_0:\r\n            {\r\n                atmorb: {\r\n                    \"ldos\": [],\r\n                    \"pdos_l_1\": [],\r\n                    \"pdos_l_2\": [],\r\n                    ...\r\n                    \"pdos_l_2l+1\": []\r\n                }\r\n            }\r\n            l could be: s, p, d, f, in format like this: 1(s), 2(s), 2(p)\r\n            self.data_0_tdos:\r\n            {\r\n                dos: [],\r\n                pdos: [],\r\n            }\r\n            \"\"\"\r\n            self.data_0 = {}\r\n            for atmorb in self.data:\r\n                self.data_0[atmorb] = {}\r\n                self.data_0[atmorb][\"ldos\"] = self.data[atmorb][:, 1]\r\n                for i in range(self.data[atmorb].shape[1]-2):\r\n                    self.data_0[atmorb][\"pdos_%s_%d\" % (self.get_orb_type(atmorb), i+1)] = self.data[atmorb][:, i+2]\r\n            #\r\n            self.data_0_tdos = {}\r\n            self.data_0_tdos[\"dos\"] = self.tdos[:, 1]\r\n            self.data_0_tdos[\"pdos\"] = self.tdos[:, 2]\r\n\r\n        elif self.magnetic_status == \"collinear-spin-polarized\":\r\n            \"\"\"\r\n            # pdos are in format like this:\r\n            # E ldosup(E) ldosdw(E) pdos_1up(E) pdos_1dw(E) ... pdow_2l+1up(E) pdos_2l+1dw(E)\r\n            # self.data_1:\r\n            {\r\n                atmorb: {\r\n                    \"ldos_up\": [],\r\n                    \"ldos_dw\": [],\r\n                    \"pdos_l_1_up\": [],\r\n                    \"pdos_l_1_dw\": [],\r\n                    \"pdos_l_2_up\": [],\r\n                    \"pdos_l_2_dw\": [],\r\n                    ...\r\n                    \"pdos_l_2l+1_up\": [],\r\n                    \"pdos_l_2l+1_dw\": [],\r\n                }\r\n            }\r\n            l could be: s, p, d, f, in format like this: 1(s), 2(s), 2(p)\r\n            self.data_1_tdos:\r\n            {\r\n                \"dos_up\": [],\r\n                \"dos_dw\": [],\r\n                \"pdos_up\": [],\r\n                \"pdos_dw\": []\r\n            }\r\n            \"\"\"\r\n            self.data_1 = {}\r\n            for atmorb in self.data:\r\n                self.data_1[atmorb] = {}\r\n                self.data_1[atmorb][\"ldos_up\"] = self.data[atmorb][:, 1]\r\n                self.data_1[atmorb][\"ldos_dw\"] = self.data[atmorb][:, 2]\r\n                for i in range(int((self.data[atmorb].shape[1]-3)/2)):\r\n                    self.data_1[atmorb][\"pdos_%s_%d_up\" % (self.get_orb_type(atmorb), i+1)] = self.data[atmorb][:, 3+2*i]\r\n                    self.data_1[atmorb][\"pdos_%s_%d_dw\" % (self.get_orb_type(atmorb), i+1)] = self.data[atmorb][:, 3+2*i+1]\r\n            #\r\n            self.data_1_tdos = {}\r\n            self.data_1_tdos[\"dos_up\"] = self.tdos[:, 1]\r\n            self.data_1_tdos[\"dos_dw\"] = self.tdos[:, 2]\r\n            self.data_1_tdos[\"pdos_up\"] = self.tdos[:, 3]\r\n            self.data_1_tdos[\"pdos_dw\"] = self.tdos[:, 4]\r\n        elif self.magnetic_status == \"non-collinear-non-spin-orbit\":\r\n            pass\r\n        elif self.magnetic_status == \"non-collinear-spin-orbit\":\r\n            pass\r\n\r\n    def export_data(self, directory):\r\n        \"\"\"\r\n        \"\"\"\r\n        if self.magnetic_status == \"collinear-spin-unpolarized\":\r\n            data = {}\r\n            for atmorb in self.data_0:\r\n                key = self.get_elem_type(atmorb)+\"-\"+self.get_orb_type(atmorb)\r\n                if key in data:\r\n                    data[key] = data[key] + self.data_0[atmorb][\"ldos\"]\r\n                else:\r\n                    data[key] = self.data_0[atmorb][\"ldos\"]\r\n        elif self.magnetic_status == \"collinear-spin-polarized\":\r\n            data = {}\r\n            for atmorb in self.data_1:\r\n                key = self.get_elem_type(atmorb)+\"-\"+self.get_orb_type(atmorb)\r\n                key_up = self.get_elem_type(atmorb)+\"-\"+self.get_orb_type(atmorb)+\"-up\"\r\n                key_dw = self.get_elem_type(atmorb)+\"-\"+self.get_orb_type(atmorb)+\"-down\"\r\n                if key_up in data and key_dw in data:\r\n                    data[key_up] = data[key_up] + self.data_1[atmorb][\"ldos_up\"]\r\n                    data[key_dw] = data[key_dw] + (-self.data_1[atmorb][\"ldos_dw\"])\r\n                else:\r\n                    data[key_up] = self.data_1[atmorb][\"ldos_up\"]\r\n                    data[key_dw] = (-self.data_1[atmorb][\"ldos_dw\"])\r\n\r\n        # export pdos projected to element and orbital l\r\n        with open(os.path.join(directory, \"pdos-projected-to-element-and-orbital-l.data\"), 'w') as fout:\r\n            fout.write(\"# efermi shifted to 0 already, previous efermi=%f\\n\" % self.efermi)\r\n            fout.write(\"#Energy\")\r\n            for key in data:\r\n                fout.write(\" %s\" % key)\r\n            fout.write(\"\\n\")\r\n            for i in range(len(self.energies)):\r\n                fout.write(\"%.9f\" % self.energies[i])\r\n                for key in data:\r\n                    fout.write(\"  %.9f\" % data[key][i])\r\n                fout.write(\"\\n\")\r\n\r\n        # export pdos projected to atom and orbital l\r\n        if self.magnetic_status == \"collinear-spin-unpolarized\":\r\n            with open(os.path.join(directory, \"pdos-projected-to-atom-and-orbital-l.data\"), 'w') as fout:\r\n                fout.write(\"# efermi shifted to 0 already, previous efermi=%f\\n\" % self.efermi)\r\n                fout.write(\"#Energy\")\r\n                for atmorb in self.data_0:\r\n                    fout.write(\" Atom(%d):%s-%s\" % (self.get_atom_num(atmorb), self.get_elem_type(atmorb), self.get_orb_type(atmorb)))\r\n                fout.write(\"\\n\")\r\n                for i in range(len(self.energies)):\r\n                    fout.write(\"%.9f\" % self.energies[i])\r\n                    for atmorb in self.data_0:\r\n                        fout.write(\"  %.9f\" % self.data_0[atmorb][\"ldos\"][i])\r\n                    fout.write(\"\\n\")\r\n        elif self.magnetic_status == \"collinear-spin-polarized\":\r\n            with open(os.path.join(directory, \"pdos-projected-to-atom-and-orbital-l.data\"), 'w') as fout:\r\n                fout.write(\"# efermi shifted to 0 already, previous efermi=%f\\n\" % self.efermi)\r\n                fout.write(\"#Energy\")\r\n                for atmorb in self.data_0:\r\n                    fout.write(\" Atom(%d):%s-%s-up Atom(%d):%s-%s-down\" % (self.get_atom_num(atmorb), self.get_elem_type(atmorb), self.get_orb_type(atmorb), self.get_atom_num(atmorb), self.get_elem_type(atmorb), self.get_orb_type(atmorb)))\r\n                fout.write(\"\\n\")\r\n                for i in range(len(self.energies)):\r\n                    fout.write(\"%.9f\" % self.energies[i])\r\n                    for atmorb in self.data_1:\r\n                        fout.write(\"  %.9f %.9f\" % (self.data_1[atmorb][\"ldos_up\"][i], self.data_1[atmorb][\"ldos_dw\"][i]))\r\n                    fout.write(\"\\n\")            \r\n        # export total dos to data file\r\n        if self.magnetic_status == \"collinear-spin-unpolarized\":\r\n            with open(os.path.join(directory, \"total-dos.data\"), 'w') as fout:\r\n                fout.write(\"# efermi shifted to 0 already, previous efermi=%f\\n\" % self.efermi)\r\n                fout.write(\"#energye dos\\n\")\r\n                for i in range(len(self.energies)):\r\n                    fout.write(\"%.9f %.9f\\n\" % (self.energies[i], self.data_0_tdos[\"dos\"][i]))\r\n        elif self.magnetic_status == \"collinear-spin-polarized\":\r\n            with open(os.path.join(directory, \"total-dos.data\"), 'w') as fout:\r\n                fout.write(\"# efermi shifted to 0 already, previous efermi=%f\\n\" % self.efermi)\r\n                fout.write(\"#energye dos(up) dos(down)\\n\")\r\n                for i in range(len(self.energies)):\r\n                    fout.write(\"%.9f %.9f %.9f\\n\" % (self.energies[i], self.data_0_tdos[\"dos_up\"][i], self.data_0_tdos[\"dos_dw\"][i]))\r\n\r\n\r\n    def plot_elem_orb_l_proj(self, plotrange=[0.0, 1.0], filename=\"pdos-projected-to-element-and-orbital-l.png\", fontsize=10):\r\n        \"\"\"\r\n        plotrange:\r\n            a list of two values(between 0 and 1) defining the percentage\r\n            of data to plot.\r\n            plotrange[0]: left boundary of the data to plot\r\n            plotrange[1]: right boundary of the data to plot\r\n            default is plotrange[0] = 0, plotrange[1], in which case\r\n            all the data will be plot.\r\n        \"\"\"\r\n        if self.magnetic_status == \"collinear-spin-unpolarized\":\r\n            data = {}\r\n            for atmorb in self.data_0:\r\n                key = self.get_elem_type(atmorb)+\"-\"+self.get_orb_type(atmorb)\r\n                if key in data:\r\n                    data[key] = data[key] + self.data_0[atmorb][\"ldos\"]\r\n                else:\r\n                    data[key] = self.data_0[atmorb][\"ldos\"]\r\n        elif self.magnetic_status == \"collinear-spin-polarized\":\r\n            data = {}\r\n            for atmorb in self.data_1:\r\n                key = self.get_elem_type(atmorb)+\"-\"+self.get_orb_type(atmorb)\r\n                key_up = self.get_elem_type(atmorb)+\"-\"+self.get_orb_type(atmorb)+\"-up\"\r\n                key_dw = self.get_elem_type(atmorb)+\"-\"+self.get_orb_type(atmorb)+\"-down\"\r\n                if key_up in data and key_dw in data:\r\n                    data[key_up] = data[key_up] + self.data_1[atmorb][\"ldos_up\"]\r\n                    data[key_dw] = data[key_dw] + (-self.data_1[atmorb][\"ldos_dw\"])\r\n                else:\r\n                    data[key_up] = self.data_1[atmorb][\"ldos_up\"]\r\n                    data[key_dw] = (-self.data_1[atmorb][\"ldos_dw\"])\r\n\r\n        # plot the pdos in the specified percentage range\r\n        begin = int(len(self.energies)*plotrange[0])\r\n        end = int(len(self.energies)*plotrange[1])\r\n        for key in data:\r\n            plt.plot(self.energies[begin:end], data[key][begin:end], label=key)\r\n\r\n        # plot the total dos in the specified percentage range\r\n        if self.magnetic_status == \"collinear-spin-unpolarized\":\r\n            plt.plot(self.energies[begin:end], self.data_0_tdos[\"dos\"][begin:end], label=\"Total-DOS\")\r\n        elif self.magnetic_status == \"collinear-spin-polarized\":\r\n            plt.plot(self.energies[begin:end], self.data_1_tdos[\"dos_up\"], label=\"Total-DOS-Up\")\r\n            plt.plot(self.energies[begin:end], -self.data_1_tdos[\"dos_dw\"], label=\"Total-DOS-Down\")\r\n\r\n        # set formats\r\n        font = {'size': fontsize}\r\n        plt.tick_params(labelsize=fontsize)\r\n\r\n        plt.grid(which=\"major\", axis=\"x\", linewidth=0.75, linestyle=\"-\", color=\"0.75\")\r\n        plt.grid(which=\"major\", axis=\"y\", linewidth=0.75, linestyle=\"-\", color=\"0.75\")\r\n        plt.title(\"Projected Density of States\")\r\n        plt.xlabel(r\"$\\mathit{E}-\\mathit{E}_\\mathrm{f} \\mathrm{(eV)}$\", font)\r\n        plt.ylabel(\"States\", font)\r\n        plt.legend(prop=font)\r\n        plt.tight_layout()\r\n        plt.savefig(\"%s\" % filename)\r\n        plt.close()\r\n\r\n\r\n    def plot_atom_orb_l_proj(self, atomtoproj=[], plotrange=[0.0, 1.0], filename=\"pdos-projected-to-atom-and-orbital-l.png\", fontsize=10):\r\n        \"\"\"\r\n        plotrange:\r\n            a list of two values(between 0 and 1) defining the percentage\r\n            of data to plot.\r\n            plotrange[0]: left boundary of the data to plot\r\n            plotrange[1]: right boundary of the data to plot\r\n            default is plotrange[0] = 0, plotrange[1], in which case\r\n            all the data will be plot.\r\n        atomtoproj:\r\n            the list of atoms to do the projection. atom number starts with 1\r\n        \"\"\"\r\n        # plot the data in the specified percentage range\r\n        begin = int(len(self.energies)*plotrange[0])\r\n        end = int(len(self.energies)*plotrange[1])\r\n\r\n        # atom projected dos\r\n        if self.magnetic_status == \"collinear-spin-unpolarized\":\r\n            for atmorb in self.data_0:\r\n                if self.get_atom_num(atmorb) in atomtoproj:\r\n                    plt.plit(self.energies[begin:end], self.data_0[atmorb][\"ldos\"][begin:end], label=\"Atom(%d):%s-%s\" % (self.get_atom_num(atmorb), self.get_elem_type(atmorb), self.get_orb_type(atmorb)))\r\n        elif self.magnetic_status == \"collinear-spin-polarized\":\r\n            for atmorb in self.data_1:\r\n                if self.get_atom_num(atmorb) in atomtoproj:\r\n                    plt.plot(self.energies[begin:end], self.data_1[atmorb][\"ldos_up\"][begin:end], label=\"Atom(%d):%s-%s-up\" % (self.get_atom_num(atmorb), self.get_elem_type(atmorb), self.get_orb_type(atmorb)))\r\n                    plt.plot(self.energies[begin:end], -self.data_1[atmorb][\"ldos_dw\"][begin:end], label=\"Atom(%d):%s-%s-down\" % (self.get_atom_num(atmorb), self.get_elem_type(atmorb), self.get_orb_type(atmorb)))\r\n\r\n        # set formats\r\n        font = {'size': fontsize}\r\n        plt.tick_params(labelsize=fontsize)\r\n\r\n        plt.grid(which=\"major\", axis=\"x\", linewidth=0.75, linestyle=\"-\", color=\"0.75\")\r\n        plt.grid(which=\"major\", axis=\"y\", linewidth=0.75, linestyle=\"-\", color=\"0.75\")\r\n        plt.title(\"Projected(Atom) Density of States\")\r\n        plt.xlabel(r\"$\\mathit{E}-\\mathit{E}_\\mathrm{f} \\mathrm{(eV)}$\", font)\r\n        plt.ylabel(\"States\", font)\r\n        if len(atomtoproj) != 0:\r\n            plt.legend(prop=font)\r\n        plt.tight_layout()\r\n        plt.savefig(\"%s\" % filename)\r\n        plt.close()\r\n\r\n\r\n    def plot_tdos(self, plotrange=[0, 1.0], filename=\"total-dos.png\"):\r\n        \"\"\"\r\n        plotrange:\r\n            a list of two values(between 0 and 1) defining the percentage\r\n            of data to plot.\r\n            plotrange[0]: left boundary of the data to plot\r\n            plotrange[1]: right boundary of the data to plot\r\n            default is plotrange[0] = 0, plotrange[1], in which case\r\n            all the data will be plot.\r\n        \"\"\"\r\n        # plot the total dos in the specified percentage range\r\n        begin = int(len(self.energies)*plotrange[0])\r\n        end = int(len(self.energies)*plotrange[1])\r\n\r\n        if self.magnetic_status == \"collinear-spin-unpolarized\":\r\n            plt.plot(self.energies[begin:end], self.data_0_tdos[\"dos\"][begin:end], label=\"Total-DOS\")\r\n        elif self.magnetic_status == \"collinear-spin-polarized\":\r\n            plt.plot(self.energies[begin:end], self.data_1_tdos[\"dos_up\"], label=\"Total-DOS-Up\")\r\n            plt.plot(self.energies[begin:end], -self.data_1_tdos[\"dos_dw\"], label=\"Total-DOS-Down\")\r\n\r\n        plt.grid(which=\"major\", axis=\"x\", linewidth=0.75, linestyle=\"-\", color=\"0.75\")\r\n        plt.grid(which=\"major\", axis=\"y\", linewidth=0.75, linestyle=\"-\", color=\"0.75\")\r\n        plt.title(\"Total Density of States\")\r\n        plt.xlabel(r\"$\\mathit{E}-\\mathit{E}_\\mathrm{f} (eV)$\")\r\n        plt.ylabel(\"States\")\r\n        plt.legend()\r\n        plt.tight_layout()\r\n        plt.savefig(\"%s\" % filename)\r\n        plt.close()\r\n\r\n    def get_elem_type(self, atmorb):\r\n        \"\"\"\r\n        get element name from atmorb\r\n        atmorb is the key in self.data\r\n        it's like this:\r\n            atm#1(Li)_wfc#2(s)\r\n        return value of the above input\r\n        will be:\r\n            'Li'\r\n        \"\"\"\r\n        return atmorb.split(\"(\")[1].split(\")\")[0]\r\n\r\n    def get_orb_type(self, atmorb):\r\n        \"\"\"\r\n        get element name and orb from atmorb\r\n        atmorb is the key in self.data\r\n        it's like this:\r\n            atm#1(Li)_wfc#2(s)\r\n        return value of the above input\r\n        will be:\r\n            '2(s)'\r\n        \"\"\"\r\n        return atmorb.split(\"#\")[2]\r\n\r\n    def get_atom_num(self, atmorb):\r\n        \"\"\"\r\n        get atom name from atmorb\r\n        atmorb is the key in self.data\r\n        it's like this:\r\n            atm#1(Li)_wfc#2(s)\r\n        return value of the above input\r\n        will be:\r\n            1\r\n        \"\"\"\r\n        return int(atmorb.split(\"(\")[0].split(\"#\")[1])\r\n\r\n    def markdown_report(self, md=\"pdos-report.md\"):\r\n        \"\"\"\r\n        when writing Chinese to a file you must specify\r\n        encoding='utf-8' when open the file for writing\r\n        \"\"\"\r\n        with open(md, 'w', encoding=\"utf-8\") as fout:\r\n            fout.write(\"# 投影态密度图\\n\")\r\n            fout.write(\"**指定能量范围数据图\\n\")\r\n            fout.write(\"![pdos-range](./pdos-specified-range.png)\\n\")\r\n            fout.write(\"![pdos-atom-range](./pdos-atomproj-specified-range.png)\\n\")\r\n            fout.write(\"![tdos-range](./tdos-specified-range.png)\\n\")\r\n            fout.write(\"**所有可获取能量范围数据图**\\n\")\r\n            fout.write(\"![pdos-all](./pdos-all-energy-available.png)\\n\")\r\n            fout.write(\"![pdos-atom-all](./pdos-atomproj-all-energy-available.png)\\n\")\r\n            fout.write(\"![tdos-all](./tdos-all-energy-available.png)\\n\")\r\n\r\n    def export(self, directory=\"tmp-qe-static\", plotrange=[0, 1.0], atomtoproj=[], fontsize=10):\r\n        os.chdir(directory)\r\n        os.system(\"mkdir -p post-processing\")\r\n        self.export_data(directory=\"post-processing\")\r\n        self.plot_elem_orb_l_proj(plotrange=plotrange, filename=\"post-processing/pdos-specified-range.png\", fontsize=fontsize)\r\n        self.plot_atom_orb_l_proj(plotrange=plotrange, atomtoproj=atomtoproj, filename=\"post-processing/pdos-atomproj-specified-range.png\", fontsize=fontsize)\r\n        self.plot_tdos(plotrange=plotrange, filename=\"post-processing/tdos-specified-range.png\")\r\n        # also plot the all data\r\n        self.plot_elem_orb_l_proj(plotrange=[0, 1.0], filename=\"post-processing/pdos-all-energy-available.png\", fontsize=fontsize)\r\n        self.plot_atom_orb_l_proj(plotrange=[0, 1.0], atomtoproj=atomtoproj, filename=\"post-processing/pdos-atomproj-all-energy-available.png\", fontsize=fontsize)\r\n        self.plot_tdos(plotrange=[0, 1.0], filename=\"post-processing/tdos-all-energy-available.png\")\r\n        self.markdown_report(md=\"post-processing/pdos-report.md\")\r\n        os.chdir(\"../\")\r\n    #\r\n\r\n\r\n\r\nclass PdosPost:\r\n    \"\"\"\r\n    \"\"\"\r\n    def __init__(self):\r\n        self.data = {} # contain the pdos data but not the tdos\r\n        self.tdos = None\r\n        self.energies = None\r\n\r\n    def get_data(self, directory=\"tmp-qe-static\", filpdos=\"projwfc\"):\r\n        \"\"\"\r\n        this function first try to get fermi energy from the nscfout file\r\n        and if nscfout doesn't exist it will try to extract fermi energy\r\n        from scfout. if both don't exist, it will stop the program and\r\n        print out the warnnig, which guarantee that the fermi energy is\r\n        always shifted to 0\r\n\r\n        atomorb is a string in format like this atm#1(Li)_wfc#2(s).\r\n        \"\"\"\r\n        # first check whether there is a previous scf running\r\n        if not os.path.exists(directory):\r\n            print(\"===================================================\\n\")\r\n            print(\"                 Warning !!!\\n\")\r\n            print(\"===================================================\\n\")\r\n            print(\"pdos post:\\n\")\r\n            print(\"  directory of previous scf calculattion not found!\\n\")\r\n            sys.exit(1)\r\n\r\n        os.chdir(directory)\r\n        os.system(\"ls | grep '%s.pdos_' > projwfc-pdos-file.data\" % filpdos)\r\n        with open(\"projwfc-pdos-file.data\", 'r') as fin:\r\n            for line in fin:\r\n                if line.split(\".\")[1] == \"pdos_tot\\n\":\r\n                    with open(line.split()[0], 'r') as f:\r\n                        f.readline()\r\n                        self.tdos = np.loadtxt(f)\r\n                    continue\r\n                atmorb = line.split(\"_\")[1]+\"_\"+line.split(\"_\")[2].split()[0]\r\n                # atomorb is a string in format like this atm#1(Li)_wfc#2(s).\r\n                with open(line.split()[0], 'r') as f:\r\n                    f.readline()\r\n                    self.data[atmorb] = np.loadtxt(f)\r\n        os.chdir(\"../\")\r\n\r\n        self.energies = self.tdos[:, 0]\r\n\r\n        # get fermi energy from nscf output\r\n        scfout = \"static-scf.out\"\r\n        nscfout = \"static-nscf.out\"\r\n        if os.path.exists(os.path.join(directory, nscfout)):\r\n            with open(os.path.join(directory, nscfout), 'r') as fin:\r\n                for line in fin:\r\n                    if len(line.split()) == 0:\r\n                        continue\r\n                    if line.split()[0] == \"the\" and line.split()[1] == \"Fermi\":\r\n                        efermi = float(line.split()[4])\r\n        elif os.path.exists(os.path.join(directory, scfout)):\r\n            with open(os.path.join(directory, scfout), 'r') as fin:\r\n                for line in fin:\r\n                    if len(line.split()) == 0:\r\n                        continue\r\n                    if line.split()[0] == \"the\" and line.split()[1] == \"Fermi\":\r\n                        efermi = float(line.split()[4])\r\n        else:\r\n            print(\"===========================================================\\n\")\r\n            print(\"                Warning !!!\\n\")\r\n            print(\"===========================================================\\n\")\r\n            print(\"PDOS postprocessing:\\n\")\r\n            print(\"must provide nscfout or at least scfout to get Fermi energy\\n\")\r\n            sys.exit(1)\r\n        # shift fermie energy to 0\r\n        for i in range(len(self.energies)):\r\n            self.energies[i] = self.energies[i] - efermi\r\n        print(\"===============================================\\n\")\r\n        print(\"qe.post.pdos:\\n\")\r\n        print(\"we automatically shift the fermi energy\\n\")\r\n        print(\"from %f to 0\\n\" % efermi)\r\n        print(\"efermi is read from static-nscf.out\\n\")\r\n        print(\"or statis-scf.out, if static-nscf.out is not available\\n\")\r\n        #\r\n\r\n    def plot_elem_orb_proj(self, plotrange=[0.0, 1.0], filename=\"pdos-projected-to-element-and-orbital.png\", fontsize=10):\r\n        \"\"\"\r\n        plotrange:\r\n            a list of two values(between 0 and 1) defining the percentage\r\n            of data to plot.\r\n            plotrange[0]: left boundary of the data to plot\r\n            plotrange[1]: right boundary of the data to plot\r\n            default is plotrange[0] = 0, plotrange[1], in which case\r\n            all the data will be plot.\r\n        \"\"\"\r\n        data = {}\r\n        for atmorb in self.data:\r\n            key = self.get_elem_type(atmorb)+\"-\"+self.get_orb_type(atmorb)\r\n            if key in data:\r\n                data[key] = data[key] + self.data[atmorb][:, 2]\r\n            else:\r\n                data[key] = self.data[atmorb][:, 2]\r\n\r\n        # plot the pdos in the specified percentage range\r\n        begin = int(len(self.energies)*plotrange[0])\r\n        end = int(len(self.energies)*plotrange[1])\r\n        for key in data:\r\n            plt.plot(self.energies[begin:end], data[key][begin:end], label=key)\r\n\r\n        # plot the total dos in the specified percentage range\r\n        plt.plot(self.energies[begin:end], self.tdos[begin:end, 2], label=\"Total-DOS\")\r\n\r\n        # set formats\r\n        font = {'size': fontsize}\r\n        plt.tick_params(labelsize=fontsize)\r\n\r\n        plt.grid(which=\"major\", axis=\"x\", linewidth=0.75, linestyle=\"-\", color=\"0.75\")\r\n        plt.grid(which=\"major\", axis=\"y\", linewidth=0.75, linestyle=\"-\", color=\"0.75\")\r\n        plt.title(\"Projected Density of States\")\r\n        plt.xlabel(r\"$\\mathit{E}-\\mathit{E}_\\mathrm{f} \\mathrm{(eV)}$\", font)\r\n        plt.ylabel(\"States\", font)\r\n        plt.legend(prop=font)\r\n        plt.tight_layout()\r\n        plt.savefig(\"%s\" % filename)\r\n        plt.close()\r\n\r\n\r\n    def plot_atom_orb_proj(self, atomtoproj=[], plotrange=[0.0, 1.0], filename=\"pdos-projected-to-atom-and-orbital.png\", fontsize=10):\r\n        \"\"\"\r\n        plotrange:\r\n            a list of two values(between 0 and 1) defining the percentage\r\n            of data to plot.\r\n            plotrange[0]: left boundary of the data to plot\r\n            plotrange[1]: right boundary of the data to plot\r\n            default is plotrange[0] = 0, plotrange[1], in which case\r\n            all the data will be plot.\r\n        atomtoproj:\r\n            the list of atoms to do the projection. atom number starts with 1\r\n        \"\"\"\r\n        # plot the data in the specified percentage range\r\n        begin = int(len(self.energies)*plotrange[0])\r\n        end = int(len(self.energies)*plotrange[1])\r\n\r\n        # atom projected dos\r\n        for atmorb in self.data:\r\n            if self.get_atom_num(atmorb) in atomtoproj:\r\n                plt.plot(self.energies[begin:end], self.data[atmorb][begin:end, 2], label=\"Atom(%d):%s-%s\" % (self.get_atom_num(atmorb), self.get_elem_type(atmorb), self.get_orb_type(atmorb)))\r\n\r\n        # plot the total dos in the specified percentage range\r\n        plt.plot(self.energies[begin:end], self.tdos[begin:end, 2], label=\"Total-DOS\")\r\n        #\r\n\r\n        # set formats\r\n        font = {'size': fontsize}\r\n        plt.tick_params(labelsize=fontsize)\r\n\r\n        plt.grid(which=\"major\", axis=\"x\", linewidth=0.75, linestyle=\"-\", color=\"0.75\")\r\n        plt.grid(which=\"major\", axis=\"y\", linewidth=0.75, linestyle=\"-\", color=\"0.75\")\r\n        plt.title(\"Projected(Atom) Density of States\")\r\n        plt.xlabel(r\"$\\mathit{E}-\\mathit{E}_\\mathrm{f} \\mathrm{(eV)}$\", font)\r\n        plt.ylabel(\"States\", font)\r\n        plt.legend(prop=font)\r\n        plt.tight_layout()\r\n        plt.savefig(\"%s\" % filename)\r\n        plt.close()\r\n\r\n\r\n    def plot_tdos(self, plotrange=[0, 1.0], filename=\"total-dos.png\"):\r\n        \"\"\"\r\n        plotrange:\r\n            a list of two values(between 0 and 1) defining the percentage\r\n            of data to plot.\r\n            plotrange[0]: left boundary of the data to plot\r\n            plotrange[1]: right boundary of the data to plot\r\n            default is plotrange[0] = 0, plotrange[1], in which case\r\n            all the data will be plot.\r\n        \"\"\"\r\n        # plot the total dos in the specified percentage range\r\n        begin = int(len(self.energies)*plotrange[0])\r\n        end = int(len(self.energies)*plotrange[1])\r\n        #plt.plot(self.energies, self.tdos[:, 2], label=\"total-dos\")\r\n        plt.plot(self.energies[begin:end], self.tdos[begin:end, 2], label=\"Total-DOS\")\r\n\r\n        plt.grid(which=\"major\", axis=\"x\", linewidth=0.75, linestyle=\"-\", color=\"0.75\")\r\n        plt.grid(which=\"major\", axis=\"y\", linewidth=0.75, linestyle=\"-\", color=\"0.75\")\r\n        plt.title(\"Total Density of States\")\r\n        plt.xlabel(r\"$\\mathit{E}-\\mathit{E}_\\mathrm{f} (eV)$\")\r\n        plt.ylabel(\"States\")\r\n        plt.legend()\r\n        plt.tight_layout()\r\n        plt.savefig(\"%s\" % filename)\r\n        plt.close()\r\n\r\n    def get_elem_type(self, atmorb):\r\n        \"\"\"\r\n        get element name from atmorb\r\n        atmorb is the key in self.data\r\n        it's like this:\r\n            atm#1(Li)_wfc#2(s)\r\n        return value of the above input\r\n        will be:\r\n            'Li'\r\n        \"\"\"\r\n        return atmorb.split(\"(\")[1].split(\")\")[0]\r\n\r\n    def get_orb_type(self, atmorb):\r\n        \"\"\"\r\n        get element name and orb from atmorb\r\n        atmorb is the key in self.data\r\n        it's like this:\r\n            atm#1(Li)_wfc#2(s)\r\n        return value of the above input\r\n        will be:\r\n            '2(s)'\r\n        \"\"\"\r\n        return atmorb.split(\"#\")[2]\r\n\r\n    def get_atom_num(self, atmorb):\r\n        \"\"\"\r\n        get atom name from atmorb\r\n        atmorb is the key in self.data\r\n        it's like this:\r\n            atm#1(Li)_wfc#2(s)\r\n        return value of the above input\r\n        will be:\r\n            1\r\n        \"\"\"\r\n        return int(atmorb.split(\"(\")[0].split(\"#\")[1])\r\n\r\n    def markdown_report(self, md=\"pdos-report.md\"):\r\n        \"\"\"\r\n        when writing Chinese to a file you must specify\r\n        encoding='utf-8' when open the file for writing\r\n        \"\"\"\r\n        with open(md, 'w', encoding=\"utf-8\") as fout:\r\n            fout.write(\"# 投影态密度图\\n\")\r\n            fout.write(\"**指定能量范围数据图\\n\")\r\n            fout.write(\"![pdos-range](./pdos-specified-range.png)\\n\")\r\n            fout.write(\"![pdos-atom-range](./pdos-atomproj-specified-range.png)\\n\")\r\n            fout.write(\"![tdos-range](./tdos-specified-range.png)\\n\")\r\n            fout.write(\"**所有可获取能量范围数据图**\\n\")\r\n            fout.write(\"![pdos-all](./pdos-all-energy-available.png)\\n\")\r\n            fout.write(\"![pdos-atom-all](./pdos-atomproj-all-energy-available.png)\\n\")\r\n            fout.write(\"![tdos-all](./tdos-all-energy-available.png)\\n\")\r\n\r\n    def export(self, directory=\"tmp-qe-static\", plotrange=[0, 1.0], atomtoproj=[], fontsize=10):\r\n        os.chdir(directory)\r\n        os.system(\"mkdir -p post-processing\")\r\n        self.export_data(directory=\"post-processing\")\r\n        self.plot_elem_orb_proj(plotrange=plotrange, filename=\"post-processing/pdos-specified-range.png\", fontsize=fontsize)\r\n        self.plot_atom_orb_proj(plotrange=plotrange, atomtoproj=atomtoproj, filename=\"post-processing/pdos-atomproj-specified-range.png\", fontsize=fontsize)\r\n        self.plot_tdos(plotrange=plotrange, filename=\"post-processing/tdos-specified-range.png\")\r\n        # also plot the all data\r\n        self.plot_elem_orb_proj(plotrange=[0, 1.0], filename=\"post-processing/pdos-all-energy-available.png\", fontsize=fontsize)\r\n        self.plot_atom_orb_proj(plotrange=[0, 1.0], atomtoproj=atomtoproj, filename=\"post-processing/pdos-atomproj-all-energy-available.png\", fontsize=fontsize)\r\n        self.plot_tdos(plotrange=[0, 1.0], filename=\"post-processing/tdos-all-energy-available.png\")\r\n        self.markdown_report(md=\"post-processing/pdos-report.md\")\r\n        os.chdir(\"../\")\r\n    #\r\n", "meta": {"hexsha": "40e8a45efe031b68bf1c1c62927e61df38ef012c", "size": 33687, "ext": "py", "lang": "Python", "max_stars_repo_path": "pymatflow/qe/post/pdos.py", "max_stars_repo_name": "DeqiTang/pymatflow", "max_stars_repo_head_hexsha": "bd8776feb40ecef0e6704ee898d9f42ded3b0186", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-03-06T16:13:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T07:53:34.000Z", "max_issues_repo_path": "pymatflow/qe/post/pdos.py", "max_issues_repo_name": "DeqiTang/pymatflow", "max_issues_repo_head_hexsha": "bd8776feb40ecef0e6704ee898d9f42ded3b0186", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-10-02T02:23:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-08T13:29:37.000Z", "max_forks_repo_path": "pymatflow/qe/post/pdos.py", "max_forks_repo_name": "DeqiTang/pymatflow", "max_forks_repo_head_hexsha": "bd8776feb40ecef0e6704ee898d9f42ded3b0186", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-10T16:28:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-10T16:28:14.000Z", "avg_line_length": 47.0488826816, "max_line_length": 240, "alphanum_fraction": 0.5334105144, "include": true, "reason": "import numpy", "num_tokens": 8558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604272, "lm_q2_score": 0.27512971787959795, "lm_q1q2_score": 0.15255130259713182}}
{"text": "from __future__ import print_function, division\nimport numpy as np\nfrom numpy import require, zeros, array, where, unravel_index, einsum\nfrom pyscf.nao import nao, prod_basis\nfrom pyscf.nao import conv_yzx2xyz_c\nfrom pyscf.dft.rks import _dft_common_init_\n    \n#\n#\n#\nclass mf(nao):\n\n  def __init__(self, **kw):\n    \"\"\"\n    Constructor a mean field class\n    store result of a mean-field calc, deliver density matrix etc\n    \"\"\"\n    #print(__name__, 'before construct')\n    nao.__init__(self, **kw)\n\n    if 'mf' in kw:\n      self.init_mo_from_pyscf(**kw)      \n    elif 'label' in kw: # init KS orbitals with SIESTA\n      self.k2xyzw = self.xml_dict[\"k2xyzw\"]\n      self.xc_code = 'LDA,PZ' # just a guess...\n    elif 'wfsx_fname' in kw: # init KS orbitals with WFSX file from SIESTA output\n      self.xc_code = 'LDA,PZ' # just a guess...\n    elif 'fireball' in kw: # init KS orbitals with Fireball\n      self.init_mo_coeff_fireball(**kw)\n      self.xc_code = 'GGA,PBE' # just a guess...\n    elif 'gpaw' in kw:\n      self.init_mo_coeff_label(**kw)\n      self.k2xyzw = np.array([[0.0,0.0,0.0,1.0]])\n      self.xc_code = 'LDA,PZ' # just a guess, but in case of GPAW there is a field...\n    elif 'openmx' in kw:\n      self.xc_code = 'GGA,PBE' # just a guess...\n      pass\n    else:\n      print(__name__, kw.keys())\n      raise RuntimeError('unknown constructor')\n\n    #_dft_common_init_(self)\n\n    if self.verbosity>0:\n      print(__name__,'\\t\\t====> self.pseudo: ', self.pseudo)\n      print(__name__,'\\t\\t====> Number of orbitals: ', self.norbs)\n\n    self.init_libnao()\n\n    self.gen_pb = kw['gen_pb'] if 'gen_pb' in kw else True\n    if self.gen_pb:\n      self.pb = pb = prod_basis(nao=self, **kw)\n      self.v_dab = pb.get_dp_vertex_sparse(dtype=self.dtype).tocsr()\n      self.cc_da = cc = pb.get_da2cc_sparse(dtype=self.dtype).tocsr()\n      self.nprod = self.cc_da.shape[1]\n      if self.verbosity>0: print(__name__,'\\t\\t====> Number of dominant and atom-centered products {}'.format(cc.shape))\n\n      #self.pb.init_prod_basis_pp_batch(nao=self, **kw)\n\n  def init_mo_from_pyscf(self, **kw):\n    \"\"\" Initializing from a previous pySCF mean-field calc. \"\"\"\n    from pyscf.nao.m_fermi_energy import fermi_energy as comput_fermi_energy\n    from pyscf.nao.m_color import color as tc\n    self.telec = kw['telec'] if 'telec' in kw else 0.0000317 # 10K\n    self.mf = mf = kw['mf']\n    self.xc_code = mf.xc if hasattr(mf, 'xc') else 'HF'\n    self.k2xyzw = np.array([[0.0,0.0,0.0,1.0]])\n    \n    self.mo_energy = np.asarray(mf.mo_energy)\n    self.nspin = self.mo_energy.ndim\n    assert self.nspin in [1,2]\n    nspin,n=self.nspin,self.norbs\n    self.mo_energy = require( self.mo_energy.reshape((1, nspin, n)), requirements='CW')\n    self.mo_occ = require( mf.mo_occ.reshape((1,nspin,n)), requirements='CW')    \n    self.mo_coeff =  require(zeros((1,nspin,n,n,1), dtype=self.dtype), requirements='CW')\n    conv = conv_yzx2xyz_c(kw['gto'])\n    aaux = np.asarray(mf.mo_coeff).reshape((nspin,n,n))\n    for s in range(nspin):\n      self.mo_coeff[0,s,:,:,0] = conv.conv_yzx2xyz_1d(aaux[s], conv.m_xyz2m_yzx).T\n\n    self.nelec = kw['nelec'] if 'nelec' in kw else np.array([int(s2o.sum()) for s2o in self.mo_occ[0]])\n    fermi = comput_fermi_energy(self.mo_energy, sum(self.nelec), self.telec)\n    self.fermi_energy = kw['fermi_energy'] if 'fermi_energy' in kw else fermi\n\n  def init_mo_coeff_fireball(self, **kw):\n    \"\"\" Constructor a mean-field class from the preceeding FIREBALL calculation \"\"\"\n    from pyscf.nao.m_fermi_dirac import fermi_dirac_occupations\n    from pyscf.nao.m_fireball_get_eigen_dat import fireball_get_eigen_dat\n    from pyscf.nao.m_fireball_hsx import fireball_hsx\n    self.telec = kw['telec'] if 'telec' in kw else self.telec\n    self.fermi_energy = kw['fermi_energy'] if 'fermi_energy' in kw else self.fermi_energy\n    self.mo_energy = require(fireball_get_eigen_dat(self.cd), dtype=self.dtype, requirements='CW')\n    ksn2fd = fermi_dirac_occupations(self.telec, self.mo_energy, self.fermi_energy)\n    self.mo_occ = (3-self.nspin)*ksn2fd\n    if abs(self.nelectron-self.mo_occ.sum())>1e-6: raise RuntimeError(\"mo_occ wrong?\" )\n    #print(__name__, ' self.nspecies ', self.nspecies)\n    #print(self.sp_mu2j)\n    \n    self.hsx = fireball_hsx(self, **kw)\n    #print(self.telec)\n    #print(self.mo_energy)\n    #print(self.fermi_energy)\n    #print(__name__, ' sum(self.mo_occ)', sum(self.mo_occ))\n    #print(self.mo_occ)\n    \n        \n\n  def diag_check(self, atol=1e-5, rtol=1e-4):\n    from pyscf.nao.m_sv_diag import sv_diag \n    ksn2e = self.mo_energy\n    ac = True\n    for k,kvec in enumerate(self.k2xyzw):\n      for spin in range(self.nspin):\n        e,x = sv_diag(self, kvec=kvec[0:3], spin=spin)\n        eref = ksn2e[k,spin,:]\n        acks = np.allclose(eref,e,atol=atol,rtol=rtol)\n        ac = ac and acks\n        if(not acks):\n          aerr = sum(abs(eref-e))/len(e)\n          print(\"diag_check: \"+bc.RED+str(k)+' '+str(spin)+' '+str(aerr)+bc.ENDC)\n    return ac\n\n  def get_occupations(self, telec=None, ksn2e=None, fermi_energy=None):\n    \"\"\" Compute occupations of electron levels according to Fermi-Dirac distribution \"\"\"\n    from pyscf.nao.m_fermi_dirac import fermi_dirac_occupations\n    Telec = self.hsx.telec if telec is None else telec\n    ksn2E = self.wfsx.ksn2e if ksn2e is None else ksn2e\n    Fermi = self.fermi_energy if fermi_energy is None else fermi_energy\n    ksn2fd = fermi_dirac_occupations(Telec, ksn2E, Fermi)\n    ksn2fd = (3.0-self.nspin)*ksn2fd\n    return ksn2fd\n\n  def init_libnao(self, wfsx=None):\n    \"\"\" Initialization of data on libnao site \"\"\"\n    from pyscf.nao.m_libnao import libnao\n    from pyscf.nao.m_sv_chain_data import sv_chain_data\n    from ctypes import POINTER, c_double, c_int64, c_int32, byref\n\n    if wfsx is None:\n        data = sv_chain_data(self)\n        # (nkpoints, nspin, norbs, norbs, nreim)\n        #print(' data ', sum(data))\n        size_x = np.array([1, self.nspin, self.norbs, self.norbs, 1], dtype=np.int32)\n        libnao.init_sv_libnao_orbs.argtypes = (POINTER(c_double), POINTER(c_int64), POINTER(c_int32))\n        libnao.init_sv_libnao_orbs(data.ctypes.data_as(POINTER(c_double)), c_int64(len(data)), size_x.ctypes.data_as(POINTER(c_int32)))\n        self.init_sv_libnao = True\n    else:\n        size_x = np.zeros(len(self.wfsx.x.shape), dtype=np.int32)\n        for i, sh in enumerate(self.wfsx.x.shape): size_x[i] = sh\n\n        data = sv_chain_data(self)\n        libnao.init_sv_libnao_orbs.argtypes = (POINTER(c_double), POINTER(c_int64), POINTER(c_int32))\n        libnao.init_sv_libnao_orbs(data.ctypes.data_as(POINTER(c_double)), c_int64(len(data)), size_x.ctypes.data_as(POINTER(c_int32)))\n        self.init_sv_libnao = True\n\n    libnao.init_aos_libnao.argtypes = (POINTER(c_int64), POINTER(c_int64))\n    info = c_int64(-999)\n    libnao.init_aos_libnao(c_int64(self.norbs), byref(info))\n    if info.value!=0: raise RuntimeError(\"info!=0\")\n    return self\n\n  def vxc_lil(self, **kw):   # Compute matrix elements of exchange-correlation potential\n    from pyscf.nao.m_vxc_lil import vxc_lil\n    return vxc_lil(self, deriv=1, **kw)\n\n  def vhartree_pbc(self, dens, **kw): \n    \"\"\"  Compute Hartree potential for the density given in an equidistant grid  \"\"\"\n    from pyscf.nao.m_vhartree_pbc import vhartree_pbc\n    return vhartree_pbc(self, dens, **kw)\n\n  def vhartree_pbc_coo(self, density_factors=[1,0], **kw): \n    \"\"\"  Compute matrix elements of Hartree potential for the density given in an equidistant grid  \"\"\"\n    from pyscf.nao.m_vhartree_pbc import vhartree_pbc\n    g = self.mesh3d.get_3dgrid()\n    f = density_factors\n    dens = np.zeros(g.shape)\n    if abs(f[0])>0: dens += f[0]*self.dens_elec(g.coords, self.make_rdm1()).reshape(g.shape)\n    if abs(f[1])>0: dens += f[1]*self.vna(g.coords,sp2v=self.ao_log.sp2chlocal,sp2rcut=self.ao_log.sp2rcut_chlocal).reshape(g.shape)\n\n    #print(__name__, dens.sum()*self.mesh3d.dv)\n    vh = self.vhartree_pbc(dens)\n    return self.matelem_int3d_coo(g, vh)\n    \n  def dens_elec(self, coords, dm): # Compute electronic density for a given density matrix and on a given set of coordinates\n    from pyscf.nao.m_dens_libnao import dens_libnao\n    from pyscf.nao.m_init_dm_libnao import init_dm_libnao\n    from pyscf.nao.m_init_dens_libnao import init_dens_libnao\n    # end of imports \n    if not self.init_sv_libnao : raise RuntimeError('not self.init_sv_libnao')\n    if init_dm_libnao(dm) is None : raise RuntimeError('init_dm_libnao(dm) is None')\n    if init_dens_libnao()!=0 : raise RuntimeError('init_dens_libnao()!=0')\n    return dens_libnao(coords, self.nspin)\n\n  def exc(self, dm=None, xc_code=None, **kw):   # Compute exchange-correlation energies\n    from pyscf.nao.m_exc import exc\n    dm = self.make_rdm1() if dm is None else dm\n    xc_code = self.xc_code if xc_code is None else xc_code\n    return exc(self, dm, xc_code, **kw)\n\n  def get_init_guess(self, mol=None, key=None):\n    \"\"\" Compute an initial guess for the density matrix. \"\"\"\n    from pyscf.scf.hf import init_guess_by_minao\n    if hasattr(self, 'mol'):\n      dm = init_guess_by_minao(self.mol)\n    else:\n      dm = self.make_rdm1()  # the loaded ks orbitals will be used\n      if dm.shape[0:2]==(1,1) and dm.shape[4]==1 : dm = dm.reshape((self.norbs,self.norbs))\n    return dm\n\n  def get_hamiltonian(self): # Returns the stored matrix elements of current hamiltonian \n    return self.hsx.spin2h4_csr\n  \n  def dos(self, comegas, **kw):\n    \"\"\" Ordinary Density of States (from the current mean-field eigenvalues) \"\"\"\n    from pyscf.nao.scf_dos import scf_dos\n    return scf_dos(self, comegas, **kw)\n\n  def pdos(self, comegas, **kw):\n    \"\"\"\n    Partial Density of States (resolved in angular momentum of atomic orbitals)\n    \"\"\"\n    import pyscf.nao.m_dos_pdos_ldos as mpdos\n    return mpdos.pdos(self, comegas, **kw)\n\n  def lsoa_dos(self, comegas, **kw):\n    \"\"\"\n    Partial Density of States (contributions from a given list of atoms)\n    \"\"\"\n    import pyscf.nao.m_dos_pdos_ldos as mpdos\n    return mpdos.lsoa_dos(self, comegas, **kw)\n\n  def gdos(self, comegas, **kw):\n    \"\"\"\n    Some molecular orbital population analysis\n    \"\"\"\n    import pyscf.nao.m_dos_pdos_ldos as mpdos\n    return mpdos.gdos(self, comegas, **kw)\n\n  def read_wfsx(self, fname, **kw):\n    \"\"\"\n    An occasional reading of the SIESTA's .WFSX file\n    \"\"\"\n    from pyscf.nao.m_siesta_wfsx import siesta_wfsx_c\n    from pyscf.nao.m_siesta2blanko_denvec import _siesta2blanko_denvec\n    from pyscf.nao.m_fermi_dirac import fermi_dirac_occupations\n\n    self.wfsx = siesta_wfsx_c(fname=fname, **kw)\n    \n    assert self.nkpoints == self.wfsx.nkpoints\n    assert self.norbs == self.wfsx.norbs \n    assert self.nspin == self.wfsx.nspin\n    orb2m = self.get_orb2m()\n    for k in range(self.nkpoints):\n      for s in range(self.nspin):\n        for n in range(self.norbs):\n          _siesta2blanko_denvec(orb2m, self.wfsx.x[k,s,n,:,:])\n\n    self.mo_coeff = require(self.wfsx.x, dtype=self.dtype, requirements='CW')\n    self.mo_energy = require(self.wfsx.ksn2e, dtype=self.dtype, requirements='CW')\n    self.telec = kw['telec'] if 'telec' in kw else self.hsx.telec\n    self.nelec = kw['nelec'] if 'nelec' in kw else self.hsx.nelec\n    self.fermi_energy = kw['fermi_energy'] if 'fermi_energy' in kw else self.fermi_energy\n    ksn2fd = fermi_dirac_occupations(self.telec, self.mo_energy, self.fermi_energy)\n    self.mo_occ = (3-self.nspin)*ksn2fd\n    return self\n\n\n  def plot_contour(self, w=0.0):\n    \"\"\"\n      Plot contour with poles of Green's function in the self-energy \n      SelfEnergy(w) = G(w+w')W(w')\n      with respect to w' = Re(w')+Im(w')\n      Poles of G(w+w') are located: w+w'-(E_n-Fermi)+i*eps sign(E_n-Fermi)==0 ==> \n      w'= (E_n-Fermi) - w -i eps sign(E_n-Fermi)\n    \"\"\"\n    try :\n      import matplotlib.pyplot as plt\n      from matplotlib.patches import Arc, Arrow \n    except:\n      print('no matplotlib?')\n      return\n\n    fig,ax = plt.subplots()\n    fe = self.fermi_energy\n    ee = self.mo_energy\n    iee = 0.5-np.array(ee>fe)\n    eew = ee-fe-w\n    ax.plot(eew, iee, 'r.', ms=10.0)\n    pp = list()\n    pp.append(Arc((0,0),4,4,angle=0, linewidth=2, theta1=0, theta2=90, zorder=2, color='b'))\n    pp.append(Arc((0,0),4,4,angle=0, linewidth=2, theta1=180, theta2=270, zorder=2, color='b'))\n    pp.append(Arrow(0,2,0,-4,width=0.2, color='b', hatch='o'))\n    pp.append(Arrow(-2,0,4,0,width=0.2, color='b', hatch='o'))\n    for p in pp: ax.add_patch(p)\n    ax.set_aspect('equal')\n    ax.grid(True, which='both')\n    ax.axhline(y=0, color='k')\n    ax.axvline(x=0, color='k')\n    plt.ylim(-3.0,3.0)\n    plt.show()\n\n  def get_vertex_pov(self):\n    \"\"\" Computes the occupied-virtual-product basis vertex\"\"\"\n    assert hasattr(self, 'pb')\n    pab = self.pb.get_ac_vertex_array()\n    pov = list()\n    nprd = pab.shape[0]\n    for s,occ in enumerate(self.mo_occ):\n      no = np.count_nonzero(occ>0.0)\n      nv = np.count_nonzero(occ==0.0)\n      assert nv+no==self.mo_coeff.shape[-2]\n      pov.append(np.zeros([nprd,no,nv], dtype=self.dtype))\n      pov[s] = np.einsum('oa,pab,vb->pov', self.mo_coeff[0,s,0:no,:,0], pab, self.mo_coeff[0,s,no:,:,0])\n    return pov\n\n  def nonin_osc_strength(self):\n    from scipy.sparse import spmatrix \n    \"\"\" Computes the non-interacting oscillator strengths and energies \"\"\"\n\n    x,y,z = map(spmatrix.toarray, self.dipole_coo())\n    i2d = array((x,y,z))\n    n = self.mo_occ.shape[-1]\n    \n    p = zeros((len(comega)), dtype=np.complex128) # result to accumulate\n    \n    for s in range(self.nspin):\n      o,e,cc = self.mo_occ[0,s],self.mo_energy[0,s],self.mo_coeff[0,s,:,:,0]\n      oo1,ee1 = np.subtract.outer(o,o).reshape(n*n), np.subtract.outer(e,e).reshape(n*n)\n      idx = unravel_index( np.intersect1d(where(oo1<0.0), where(ee1<eemax)), (n,n))\n      ivrt,iocc = array(list(set(idx[0]))), array(list(set(idx[1])))\n      voi2d = einsum('nia,ma->nmi', einsum('iab,nb->nia', i2d, cc[ivrt]), cc[iocc])\n      t2osc = 2.0/3.0*einsum('voi,voi->vo', voi2d, voi2d)\n      t2w =  np.subtract.outer(e[ivrt],e[iocc])\n      t2o = -np.subtract.outer(o[ivrt],o[iocc])\n\n      for iw,w in enumerate(comega):\n        p[iw] += 0.5*(t2osc*((t2o/(w-t2w))-(t2o/(w+t2w)))).sum()      \n    return p\n\n  def polariz_nonin_ave_matelem(self, comega):\n    from scipy.sparse import spmatrix \n    \"\"\" Computes the non-interacting optical polarizability via the dipole matrix elements.\"\"\"\n\n    x,y,z = map(spmatrix.toarray, self.dipole_coo())\n    i2d = array((x,y,z))\n    n = self.mo_occ.shape[-1]\n    eemax = max(comega.real)+20.0*max(comega.imag)\n    \n    p = zeros((len(comega)), dtype=np.complex128) # result to accumulate\n\n    #print(__name__, 'Fermi energy', self.fermi_energy)\n    #np.set_printoptions(linewidth=1000)\n    for s in range(self.nspin):\n      o,e,cc = self.mo_occ[0,s],self.mo_energy[0,s],self.mo_coeff[0,s,:,:,0]\n      #print(o[:10])\n      #print(e[:10])\n\n      oo1,ee1 = np.subtract.outer(o,o).reshape(n*n), np.subtract.outer(e,e).reshape(n*n)\n      idx = unravel_index( np.intersect1d(where(oo1<0.0), where(ee1<eemax)), (n,n))\n      ivrt,iocc = array(list(set(idx[0]))), array(list(set(idx[1])))\n      voi2d = einsum('nia,ma->nmi', einsum('iab,nb->nia', i2d, cc[ivrt]), cc[iocc])\n      t2osc = 2.0/3.0*einsum('voi,voi->vo', voi2d, voi2d)\n      t2w =  np.subtract.outer(e[ivrt],e[iocc])\n      t2o = -np.subtract.outer(o[ivrt],o[iocc])\n\n      for iw,w in enumerate(comega):\n        p[iw] += 0.5*(t2osc*((t2o/(w-t2w))-(t2o/(w+t2w)))).sum()\n      \n    return p\n    \n  def spin_square(self, mo_coeff=None, mo_occ=None):\n    from functools import reduce\n\n    mo_coeff = self.mo_coeff if mo_coeff is None else mo_coeff\n    mo_occ = self.mo_occ if mo_occ is None else mo_occ\n    \n    if self.nspin==1:\n      mo_a = mo_coeff[0,0,mo_occ[0,0]>0,:,0]\n      mo_b = mo_coeff[0,0,mo_occ[0,0]>1,:,0]\n    elif self.nspin==2:\n      mo_a = mo_coeff[0,0,mo_occ[0,0]>0,:,0]\n      mo_b = mo_coeff[0,1,mo_occ[0,1]>0,:,0]\n\n    nocc_a, nocc_b = mo_a.shape[0], mo_b.shape[0]\n    over = self.overlap_coo().toarray()\n    s = reduce(np.dot, (mo_a, over, mo_b.T))\n    ssxy = (nocc_a+nocc_b) * 0.5 - (s.conj()*s).sum()\n    ssz = (nocc_b-nocc_a)**2 * 0.25\n    ss = (ssxy + ssz).real\n    s = np.sqrt(ss+0.25) - 0.5\n    \n    return ss, s*2+1\n\n#\n# Example of reading pySCF mean-field calculation.\n#\nif __name__==\"__main__\":\n  from pyscf import gto, scf as scf_gto\n  from pyscf.nao import nao, mf\n  \"\"\" Interpreting small Gaussian calculation \"\"\"\n  mol = gto.M(atom='O 0 0 0; H 0 0 1; H 0 1 0; Be 1 0 0', basis='ccpvdz') # coordinates in Angstrom!\n  dft = scf_gto.RKS(mol)\n  dft.kernel()\n  \n  sv = mf(mf=dft, gto=dft.mol, rcut_tol=1e-9, nr=512, rmin=1e-6)\n  \n  print(sv.ao_log.sp2norbs)\n  print(sv.ao_log.sp2nmult)\n  print(sv.ao_log.sp2rcut)\n  print(sv.ao_log.sp_mu2rcut)\n  print(sv.ao_log.nr)\n  print(sv.ao_log.rr[0:4], sv.ao_log.rr[-1:-5:-1])\n  print(sv.ao_log.psi_log[0].shape, sv.ao_log.psi_log_rl[0].shape)\n  print(dir(sv.pb))\n  print(sv.pb.norbs)\n  print(sv.pb.npdp)\n  print(sv.pb.c2s[-1])\n", "meta": {"hexsha": "2a63779d53023556ca319db95aec423b3c9c819e", "size": 16951, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyscf/nao/mf.py", "max_stars_repo_name": "mfkasim1/pyscf", "max_stars_repo_head_hexsha": "7be5e015b2b40181755c71d888449db936604660", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-02-28T00:52:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-01T06:23:33.000Z", "max_issues_repo_path": "pyscf/nao/mf.py", "max_issues_repo_name": "mfkasim1/pyscf", "max_issues_repo_head_hexsha": "7be5e015b2b40181755c71d888449db936604660", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2018-08-22T19:44:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-09T10:02:36.000Z", "max_forks_repo_path": "pyscf/nao/mf.py", "max_forks_repo_name": "mfkasim1/pyscf", "max_forks_repo_head_hexsha": "7be5e015b2b40181755c71d888449db936604660", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-02-14T16:28:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-12T16:40:30.000Z", "avg_line_length": 40.5526315789, "max_line_length": 135, "alphanum_fraction": 0.6606099935, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 5544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.29098087236345377, "lm_q1q2_score": 0.15230530974627493}}
{"text": "import itertools\n\nimport numpy as np\nimport torch as th\nfrom ttools.training import ModelInterface\n\nfrom . import utils\n\n\nclass ReconstructionInterface(ModelInterface):\n    def __init__(self, model, args, vertex_idxs, face_idxs, junctions,\n                 edge_data, vertex_t, adjacencies, junction_order,\n                 template_normals, symmetries=None):\n        self.model = model\n\n        self.vertex_idxs = vertex_idxs\n        self.face_idxs = face_idxs\n        self.junctions = junctions\n        self.edge_data = edge_data\n        self.vertex_t = vertex_t\n        self.junction_order = junction_order\n        self.template_normals = template_normals[None]\n\n        self.args = args\n\n        self.n_samples_per_loop_side = int(\n            np.ceil(np.sqrt(args.n_samples / face_idxs.shape[0])))\n\n        self.optimizer = th.optim.Adam(self.model.parameters(), lr=args.lr)\n\n        self.edge_idxs = [[0, 1, 2, 3], [3, 4, 5, 6],\n                          [6, 7, 8, 9], [9, 10, 11, 0]]\n\n        self.nonadjacent_patch_pairs = []\n        self.adjacent_patch_pairs = []\n        for i1, i2 in list(\n                itertools.combinations(range(face_idxs.shape[0]), 2)):\n            if args.wheels and (\n                    i1 in [5, 11, 17, 23] or i2 in [5, 11, 17, 23]):\n                continue\n            if i2 in adjacencies[i1]:\n                e1 = adjacencies[i1][i2]\n                self.adjacent_patch_pairs.append((i1, i2, e1))\n            else:\n                self.nonadjacent_patch_pairs.append((i1, i2))\n\n        self.d_points_to_tris = utils.PointToTriangleDistance.apply\n\n        p_edge0, p_edge1, p_edge2, p_edge3 = [], [], [], []\n        for i in range(self.n_samples_per_loop_side):\n            for j in range(self.n_samples_per_loop_side):\n                n = self.n_samples_per_loop_side\n\n                if i > 0:\n                    p_edge0.append(i + j*self.n_samples_per_loop_side)\n                if i < n-1:\n                    p_edge2.append(i + j*self.n_samples_per_loop_side)\n                if j > 0:\n                    p_edge3.append(i + j*self.n_samples_per_loop_side)\n                if j < n-1:\n                    p_edge1.append(i + j*self.n_samples_per_loop_side)\n        self.grid_point_edges = (p_edge0, p_edge1, p_edge2, p_edge3)\n\n        self.triangulation = []\n        t_edge0, t_edge1, t_edge2, t_edge3 = [], [], [], []\n        for i in range(self.n_samples_per_loop_side-1):\n            for j in range(self.n_samples_per_loop_side-1):\n                n = self.n_samples_per_loop_side-1\n\n                if i > 1:\n                    t_edge0.extend(\n                        [len(self.triangulation), len(self.triangulation)+1])\n                if i < n-2:\n                    t_edge2.extend(\n                        [len(self.triangulation), len(self.triangulation)+1])\n                if j > 1:\n                    t_edge3.extend(\n                        [len(self.triangulation), len(self.triangulation)+1])\n                if j < n-2:\n                    t_edge1.extend(\n                        [len(self.triangulation), len(self.triangulation)+1])\n\n                self.triangulation.extend(\n                    [[i + j*self.n_samples_per_loop_side,\n                      i + (j+1)*self.n_samples_per_loop_side,\n                      i + (j+1)*self.n_samples_per_loop_side + 1],\n                     [i + j*self.n_samples_per_loop_side,\n                      i + j*self.n_samples_per_loop_side + 1,\n                      i + (j+1)*self.n_samples_per_loop_side + 1]])\n        self.triangulation_edges = (t_edge0, t_edge1, t_edge2, t_edge3)\n\n        _loss = Loss(args, self.triangulation_edges, self.triangulation,\n                     self.grid_point_edges, self.n_samples_per_loop_side,\n                     self.d_points_to_tris, self.edge_idxs,\n                     self.nonadjacent_patch_pairs, self.adjacent_patch_pairs,\n                     self.template_normals, symmetries)\n        self._compute_losses = th.nn.DataParallel(\n            _loss) if args.cuda else _loss\n\n        if args.cuda:\n            self.model.cuda()\n            self._compute_losses.cuda()\n\n    def forward(self, batch):\n        ims = batch['ims']\n        if self.args.cuda:\n            ims = ims.cuda()\n\n        params = self.model(ims)\n        vertices, patches = utils.process_patches(\n            params, self.vertex_idxs, self.face_idxs, self.edge_data,\n            self.junctions, self.junction_order, self.vertex_t)\n\n        st = th.empty(patches.shape[0], patches.shape[1],\n                      self.n_samples_per_loop_side**2, 2).uniform_().to(params)\n\n        points = utils.coons_sample(st[..., 0], st[..., 1], patches)\n        normals = utils.coons_normals(st[..., 0], st[..., 1], patches)\n        mtds = utils.coons_mtds(st[..., 0], st[..., 1], patches)\n\n        return {'patches': patches, 'points': points, 'normals': normals,\n                'mtds': mtds, 'st': st, 'params': params, 'vertices': vertices}\n\n    def training_step(self, batch):\n        self.model.train()\n        self.optimizer.zero_grad()\n\n        losses_dict = self._compute_losses(batch, self.forward(batch))\n        loss = losses_dict['loss']\n        loss.mean().backward()\n        self.optimizer.step()\n\n        return {k: v.mean().item() for k, v in losses_dict.items()}\n\n    def init_validation(self):\n        losses = ['loss', 'chamferloss', 'normalsloss', 'collisionloss',\n                  'planarloss', 'templatenormalsloss', 'symmetryloss']\n        ret = {loss: 0 for loss in losses}\n        ret['count'] = 0\n        return ret\n\n    def validation_step(self, batch, running_data):\n        self.model.eval()\n        count = running_data['count']\n        n = batch['ims'].shape[0]\n        losses_dict = self._compute_losses(batch, self.forward(batch))\n        loss = losses_dict['loss']\n        chamferloss = losses_dict['chamferloss']\n        normalsloss = losses_dict['normalsloss']\n        collisionloss = losses_dict['collisionloss']\n        planarloss = losses_dict['planarloss']\n        templatenormalsloss = losses_dict['templatenormalsloss']\n        symmetryloss = losses_dict['symmetryloss']\n        return {\n            'loss': (running_data['loss']*count +\n                     loss.mean().item()*n) / (count+n),\n            'chamferloss': (running_data['chamferloss']*count +\n                            chamferloss.mean().item()*n) / (count+n),\n            'normalsloss': (running_data['normalsloss']*count +\n                            normalsloss.mean().item()*n) / (count+n),\n            'collisionloss': (running_data['collisionloss']*count +\n                              collisionloss.mean().item()*n) / (count+n),\n            'planarloss': (running_data['planarloss']*count +\n                           planarloss.mean().item()*n) / (count+n),\n            'templatenormalsloss': (running_data['templatenormalsloss']*count +\n                                    templatenormalsloss.mean().item()*n)\n            / (count+n),\n            'symmetryloss': (running_data['symmetryloss']*count\n                             + symmetryloss.mean().item()*n) / (count+n),\n            'count': count + n\n        }\n\n\nwheel_idxs = list(range(24))\nno_wheel_idxs = list(range(24, 43))\n\n\nclass Loss(th.nn.Module):\n    def __init__(self, args, triangulation_edges, triangulation,\n                 grid_point_edges, n_samples_per_loop_side, d_points_to_tris,\n                 edge_idxs, nonadjacent_patch_pairs, adjacent_patch_pairs,\n                 template_normals, symmetries):\n        super(Loss, self).__init__()\n        self.args = args\n        self.triangulation_edges = triangulation_edges\n        self.triangulation = triangulation\n        self.grid_point_edges = grid_point_edges\n        self.d_points_to_tris = d_points_to_tris\n        self.edge_idxs = edge_idxs\n        self.nonadjacent_patch_pairs = nonadjacent_patch_pairs\n        self.adjacent_patch_pairs = adjacent_patch_pairs\n        self.symmetries = symmetries\n\n        linspace = th.linspace(0, 1, n_samples_per_loop_side)\n        s_grid, t_grid = th.meshgrid(linspace, linspace)\n        self.s_grid = th.nn.Parameter(s_grid.flatten(), requires_grad=False)\n        self.t_grid = th.nn.Parameter(t_grid.flatten(), requires_grad=False)\n        self.template_normals = th.nn.Parameter(\n            template_normals, requires_grad=False)\n\n    def forward(self, batch, fwd_data):\n        patches = fwd_data['patches']  # [b, n_patches, 12, 3]\n        points = fwd_data['points']\n        normals = fwd_data['normals']\n        mtds = fwd_data['mtds']\n        vertices = fwd_data['vertices']\n\n        target_points = batch['points'].to(points)  # [b, n_points, 3]\n        target_normals = batch['normals'].to(normals)\n        if self.args.wheels:\n            wheel_target_points = batch['wheel_points'].to(points)\n            wheel_target_normals = batch['wheel_normals'].to(normals)\n\n        b, n_patches, _, _ = patches.shape\n\n        st = fwd_data['st']\n\n        if self.symmetries is not None:\n            xs, ys = self.symmetries\n            xs_ = vertices[:, xs]\n            ys_ = vertices[:, ys] * vertices.new_tensor([[[-1, 1, 1]]])\n            symmetryloss = th.sum((xs_ - ys_)**2, dim=-1).mean()\n        else:\n            symmetryloss = patches.new_zeros(1)\n\n        if self.args.wheels:\n            mtds = mtds.view(b, -1)\n\n            wheel_points = points[:, wheel_idxs]\n            no_wheel_points = points[:, no_wheel_idxs]\n\n            wheel_normals = normals[:, wheel_idxs]\n            no_wheel_normals = normals[:, no_wheel_idxs]\n\n            wheel_chamferloss_a, wheel_chamferloss_b, wheel_normalsloss_a, \\\n                wheel_normalsloss_b = utils.compute_chamfer_losses(\n                    wheel_points, wheel_normals, wheel_target_points,\n                    wheel_target_normals, self.args.w_normals > 0)\n            no_wheel_chamferloss_a, no_wheel_chamferloss_b, \\\n                no_wheel_normalsloss_a, no_wheel_normalsloss_b = \\\n                utils.compute_chamfer_losses(no_wheel_points, no_wheel_normals,\n                                             target_points, target_normals,\n                                             self.args.w_normals > 0)\n\n            chamferloss_a = th.cat(\n                [wheel_chamferloss_a, no_wheel_chamferloss_a], dim=1)\n            normalsloss_a = th.cat(\n                [wheel_normalsloss_a, no_wheel_normalsloss_a], dim=1)\n\n            ratio = batch['ratio']\n            n_wheel_pts = wheel_target_points.shape[1]\n            n_no_wheel_pts = target_points.shape[1]\n            n_pts = n_wheel_pts + n_no_wheel_pts\n            ratio_wheel = ratio * n_pts/n_wheel_pts\n            ratio_no_wheel = (1-ratio) * n_pts/n_no_wheel_pts\n\n            chamferloss_a = th.sum(mtds*chamferloss_a, dim=-1) / mtds.sum(-1)\n            chamferloss_b = ratio_wheel * \\\n                wheel_chamferloss_b.mean(\n                    1) + ratio_no_wheel * no_wheel_chamferloss_b.mean(1)\n            chamferloss = ((chamferloss_a+chamferloss_b).mean() / 2).view(1)\n\n            normalsloss_a = th.sum(mtds*normalsloss_a, dim=-1) / mtds.sum(-1)\n            normalsloss_b = ratio_wheel * \\\n                wheel_normalsloss_b.mean(\n                    1) + ratio_no_wheel * no_wheel_normalsloss_b.mean(1)\n            normalsloss = ((normalsloss_a+normalsloss_b).mean() / 2).view(1)\n\n        elif self.args.seperate_turbines:\n            turbine_idxs = [x for x in range(76) if x not in [72, 73, 74, 75]]\n            no_turbine_idxs = [x for x in range(76)\n                               if x not in [10, 12, 14, 17, 19, 20, 21, 24, 25,\n                                            27, 28, 29, 30, 31, 32, 33, 34,\n                                            66]]\n\n            turbine_points = points[batch['turbines']]\n            turbine_points = turbine_points[:, turbine_idxs]\n            no_turbine_points = points[batch['turbines']]\n            no_turbine_points = no_turbine_points[:, no_turbine_idxs]\n\n            turbine_normals = normals[batch['turbines']]\n            turbine_normals = turbine_normals[:, turbine_idxs]\n            no_turbine_normals = normals[batch['turbines']]\n            no_turbine_normals = no_turbine_normals[:, no_turbine_idxs]\n\n            turbine_mtds = mtds[batch['turbines']]\n            turbine_mtds = turbine_mtds[:, turbine_idxs]\n            no_turbine_mtds = mtds[batch['turbines']]\n            no_turbine_mtds = no_turbine_mtds[:, no_turbine_idxs]\n\n            turbine_patches = patches[batch['turbines']]\n            turbine_patches = turbine_patches[:, turbine_idxs]\n            no_turbine_patches = patches[batch['turbines']]\n            no_turbine_patches = no_turbine_patches[:, no_turbine_idxs]\n\n            turbine_target_points = target_points[batch['turbines']]\n            no_turbine_target_points = target_points[batch['turbines']]\n\n            turbine_target_normals = target_normals[batch['turbines']]\n            no_turbine_target_normals = target_normals[batch['turbines']]\n\n            if turbine_points.shape[0] > 0:\n                turbine_mtds = turbine_mtds.view(turbine_mtds.shape[0], -1)\n                turbine_chamferloss_a, turbine_chamferloss_b, \\\n                    turbine_normalsloss_a, turbine_normalsloss_b = \\\n                    utils.compute_chamfer_losses(turbine_points,\n                                                 turbine_normals,\n                                                 turbine_target_points,\n                                                 turbine_target_normals,\n                                                 self.args.w_normals > 0)\n                turbine_chamferloss_a = th.sum(\n                    turbine_mtds*turbine_chamferloss_a,\n                    dim=-1) / turbine_mtds.sum(-1)\n                turbine_chamferloss_b = turbine_chamferloss_b.mean(1)\n                turbine_chamferloss = (\n                    (turbine_chamferloss_a +\n                     turbine_chamferloss_b).mean() / 2).view(1)\n                turbine_normalsloss_a = th.sum(\n                    turbine_mtds*turbine_normalsloss_a,\n                    dim=-1) / turbine_mtds.sum(-1)\n                turbine_normalsloss_b = turbine_normalsloss_b.mean(-1)\n                turbine_normalsloss = (\n                    (turbine_normalsloss_a +\n                     turbine_normalsloss_b).mean() / 2).view(1)\n            else:\n                turbine_chamferloss = turbine_normalsloss = points.new_zeros(1)\n\n            if no_turbine_points.shape[0] > 0:\n                no_turbine_mtds = no_turbine_mtds.view(\n                    no_turbine_mtds.shape[0], -1)\n                no_turbine_chamferloss_a, no_turbine_chamferloss_b, \\\n                    no_turbine_normalsloss_a, no_turbine_normalsloss_b = \\\n                    utils.compute_chamfer_losses(no_turbine_points,\n                                                 no_turbine_normals,\n                                                 no_turbine_target_points,\n                                                 no_turbine_target_normals,\n                                                 self.args.w_normals > 0)\n                no_turbine_chamferloss_a = th.sum(\n                    no_turbine_mtds*no_turbine_chamferloss_a,\n                    dim=-1) / no_turbine_mtds.sum(-1)\n                no_turbine_chamferloss_b = no_turbine_chamferloss_b.mean(1)\n                no_turbine_chamferloss = (\n                    (no_turbine_chamferloss_a +\n                     no_turbine_chamferloss_b).mean() / 2).view(1)\n                no_turbine_normalsloss_a = th.sum(\n                    no_turbine_mtds*no_turbine_normalsloss_a,\n                    dim=-1) / no_turbine_mtds.sum(-1)\n                no_turbine_normalsloss_b = no_turbine_normalsloss_b.mean(-1)\n                no_turbine_normalsloss = (\n                    (no_turbine_normalsloss_a +\n                     no_turbine_normalsloss_b).mean() / 2).view(1)\n            else:\n                no_turbine_chamferloss = no_turbine_normalsloss = \\\n                    points.new_zeros(1)\n\n            ratio_turbine = turbine_points.shape[0] / b\n            chamferloss = ratio_turbine*turbine_chamferloss + \\\n                (1-ratio_turbine)*no_turbine_chamferloss\n            normalsloss = ratio_turbine*turbine_normalsloss + \\\n                (1-ratio_turbine)*no_turbine_normalsloss\n\n            del turbine_normals, turbine_target_normals, no_turbine_normals, \\\n                no_turbine_target_normals, turbine_points, \\\n                turbine_target_points, no_turbine_points, \\\n                no_turbine_target_points\n        else:\n            mtds = mtds.view(b, -1)\n\n            chamferloss_a, chamferloss_b, normalsloss_a, normalsloss_b = \\\n                utils.compute_chamfer_losses(\n                    points, normals, target_points, target_normals,\n                    self.args.w_normals > 0)\n            chamferloss_a = th.sum(mtds*chamferloss_a, dim=-1) / mtds.sum(-1)\n            chamferloss_b = chamferloss_b.mean(1)\n            chamferloss = ((chamferloss_a+chamferloss_b).mean() / 2).view(1)\n            normalsloss_a = th.sum(mtds*normalsloss_a, dim=-1) / mtds.sum(-1)\n            normalsloss_b = normalsloss_b.mean(-1)\n            normalsloss = ((normalsloss_a+normalsloss_b).mean() / 2).view(1)\n\n        mtds = mtds.view(b, n_patches, -1)\n\n        if self.args.w_templatenormals:\n            templatenormalsloss = th.sum(\n                (self.template_normals - normals)**2, dim=-1)\n            templatenormalsloss = th.sum(\n                mtds*templatenormalsloss, dim=-1) / mtds.sum(-1)\n        else:\n            templatenormalsloss = th.zeros_like(chamferloss)\n\n        del target_normals, normals, target_points\n\n        if self.args.w_planar > 0:\n            planarloss = utils.planar_patch_loss(st, points, mtds)\n        else:\n            planarloss = th.zeros_like(chamferloss)\n\n        del points, mtds\n\n        if self.args.w_collision > 0:\n            collisionloss = chamferloss.new_zeros([b, 0])\n            grid_points = utils.coons_sample(self.s_grid, self.t_grid, patches)\n            triangles = grid_points[:, :, self.triangulation]\n\n            i1s, i2s, e1s = zip(*self.adjacent_patch_pairs)\n            points1 = grid_points[:, i1s]\n            point_idxs = th.tensor([self.grid_point_edges[e]\n                                    for e in e1s]).to(points1.device)\n            point_idxs = point_idxs[None, :, :, None].expand(b, -1, -1, 3)\n            points1 = th.gather(points1, 2, point_idxs)\n            points2 = grid_points[:, i2s]\n\n            triangles1 = triangles[:, i1s]\n            triangle_idxs = th.tensor(\n                [self.triangulation_edges[e] for e in e1s]\n            ).to(triangles1.device)\n            triangle_idxs = triangle_idxs[None, :, :,\n                                          None, None].expand(b, -1, -1, 3, 3)\n            triangles1 = th.gather(triangles1, 2, triangle_idxs)\n            triangles2 = triangles[:, i2s]\n\n            idxs = utils.bboxes_intersect(\n                points1, points2, dim=2).any(0).nonzero().squeeze(1)\n            n_adjacent_intersections = idxs.shape[0]\n\n            if n_adjacent_intersections > 0:\n                points1 = points1[:, idxs].view([-1] + list(points1.shape[2:]))\n                points2 = points2[:, idxs].view([-1] + list(points2.shape[2:]))\n                triangles1 = triangles1[:, idxs].view(\n                    [-1] + list(triangles1.shape[2:]))\n                triangles2 = triangles2[:, idxs].view(\n                    [-1] + list(triangles2.shape[2:]))\n                d1 = self.d_points_to_tris(points1, triangles2)\n                d2 = self.d_points_to_tris(points2, triangles1)\n                d = th.min(d1, d2).view(b, -1)\n                collisionloss = th.cat(\n                    [collisionloss, th.exp(-(d/self.args.sigma_collision)**2)],\n                    dim=1)\n\n            i1s, i2s = zip(*self.nonadjacent_patch_pairs)\n            idxs = utils.bboxes_intersect(\n                grid_points[:, i1s], grid_points[:, i2s], dim=2\n            ).any(0).nonzero().squeeze(1)\n            n_nonadjacent_intersections = idxs.shape[0]\n            i1s = th.tensor(i1s).to(grid_points.device)[idxs]\n            i2s = th.tensor(i2s).to(grid_points.device)[idxs]\n\n            if n_nonadjacent_intersections > 0:\n                points1 = grid_points[:, i1s].view(\n                    [-1] + list(grid_points.shape[2:]))\n                points2 = grid_points[:, i2s].view(\n                    [-1] + list(grid_points.shape[2:]))\n                triangles1 = triangles[:, i1s].view(\n                    [-1] + list(triangles.shape[2:]))\n                triangles2 = triangles[:, i2s].view(\n                    [-1] + list(triangles.shape[2:]))\n                d1 = self.d_points_to_tris(points1, triangles2)\n                d2 = self.d_points_to_tris(points2, triangles1)\n                d = th.min(d1, d2).view(b, -1)\n                collisionloss = th.cat(\n                    [collisionloss, th.exp(-(d/self.args.sigma_collision)**2)],\n                    dim=1)\n\n            del triangles\n\n            if n_adjacent_intersections + n_nonadjacent_intersections > 0:\n                collisionloss = collisionloss.sum(-1).mean()\n            else:\n                collisionloss = th.zeros_like(chamferloss)\n        else:\n            collisionloss = th.zeros_like(chamferloss)\n\n        loss = chamferloss + self.args.w_normals*normalsloss + \\\n            self.args.w_collision*collisionloss + \\\n            self.args.w_planar*planarloss + \\\n            self.args.w_templatenormals*templatenormalsloss + \\\n            self.args.w_symmetry*symmetryloss\n\n        return {\n            'loss': loss,\n            'chamferloss': chamferloss,\n            'normalsloss': normalsloss,\n            'collisionloss': collisionloss,\n            'planarloss': planarloss,\n            'templatenormalsloss': templatenormalsloss,\n            'symmetryloss': symmetryloss,\n        }\n", "meta": {"hexsha": "fc64ec2d53768074ed47f636471816ba32615906", "size": 21928, "ext": "py", "lang": "Python", "max_stars_repo_path": "learningpatches/interfaces.py", "max_stars_repo_name": "dmsm/LearningPatches", "max_stars_repo_head_hexsha": "12384b3e1e93cdbbdbb5a63fec8b4f7631eafe50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2021-03-05T16:30:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T15:20:42.000Z", "max_issues_repo_path": "learningpatches/interfaces.py", "max_issues_repo_name": "dmsm/LearningPatches", "max_issues_repo_head_hexsha": "12384b3e1e93cdbbdbb5a63fec8b4f7631eafe50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-26T10:10:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-03T06:44:36.000Z", "max_forks_repo_path": "learningpatches/interfaces.py", "max_forks_repo_name": "dmsm/LearningPatches", "max_forks_repo_head_hexsha": "12384b3e1e93cdbbdbb5a63fec8b4f7631eafe50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-06-14T14:28:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T07:02:53.000Z", "avg_line_length": 45.0266940452, "max_line_length": 79, "alphanum_fraction": 0.5601514046, "include": true, "reason": "import numpy", "num_tokens": 5294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.29098087236345377, "lm_q1q2_score": 0.1523053097462749}}
{"text": "# Copyright Contributors to the Pyro-Cov project.\n# SPDX-License-Identifier: Apache-2.0\n\nimport datetime\nimport functools\nimport logging\nimport math\nimport pickle\nimport re\nimport warnings\nfrom collections import Counter, OrderedDict, defaultdict\nfrom timeit import default_timer\nfrom typing import List\n\nimport numpy as np\nimport pyro\nimport pyro.distributions as dist\nimport torch\nfrom pyro import poutine\nfrom pyro.infer import SVI, JitTrace_ELBO, Trace_ELBO\nfrom pyro.infer.autoguide import (\n    AutoDelta,\n    AutoGuideList,\n    AutoLowRankMultivariateNormal,\n    AutoNormal,\n    AutoStructured,\n)\nfrom pyro.infer.reparam import LocScaleReparam\nfrom pyro.ops.streaming import CountMeanVarianceStats, StatsOfDict\nfrom pyro.optim import ClippedAdam\nfrom pyro.poutine.util import site_is_subsample\n\nimport pyrocov.geo\n\nfrom . import pangolin, sarscov2\nfrom .util import pearson_correlation\n\nlogger = logging.getLogger(__name__)\n\n# Reasonable values might be week (7), fortnight (14), or month (28)\nTIMESTEP = 14  # in days\nGENERATION_TIME = 5.5  # in days\nSTART_DATE = \"2019-12-01\"\n\n\ndef date_range(stop):\n    start = datetime.datetime.strptime(START_DATE, \"%Y-%m-%d\")\n    step = datetime.timedelta(days=TIMESTEP)\n    return np.array([start + step * t for t in range(stop)])\n\n\ndef get_fine_regions(columns, min_samples=50):\n    \"\"\"\n    Select regions that have at least ``min_samples`` samples.\n    Remaining regions will be coarsely aggregated up to country level.\n    \"\"\"\n    # Count number of samples in each subregion.\n    counts = Counter()\n    for location in columns[\"location\"]:\n        parts = location.split(\"/\")\n        if len(parts) < 2:\n            continue\n        parts = tuple(p.strip() for p in parts[:3])\n        counts[parts] += 1\n\n    # Select fine countries.\n    return frozenset(parts for parts, count in counts.items() if count >= min_samples)\n\n\ndef rank_loo_lineages(\n    full_dataset: dict,\n    full_result: dict,\n    min_samples: int = 100,\n) -> List[str]:\n    \"\"\"\n    Compute a list of lineages ranked in descending order of how much their\n    growth rate differs from their parents' growth rate. This is used in growth\n    rate leave-one-out prediction experiments.\n    \"\"\"\n    # Decompress lineage names before computing parents.\n    lineage_id_inv = [\n        pangolin.decompress(name) for name in full_dataset[\"lineage_id_inv\"]\n    ]\n    lineage_id = {name: i for i, name in enumerate(lineage_id_inv)}\n    ancestors = set(lineage_id)\n\n    # Filter to often-observed lineages.\n    weekly_strains = full_dataset[\"weekly_strains\"]  # [T, P, S]\n    lineage_counts = weekly_strains.sum([0, 1])  # [S]\n    lineages = []\n    for c, child in enumerate(lineage_id_inv):\n        if child in (\"A\", \"B\", \"B.1\"):\n            continue  # ignore very early lineages\n        if lineage_counts[c] < min_samples:\n            continue  # ignore rare lineages\n        lineages.append(child)\n\n    # Sort leaf nodes by their distance from parent.\n    rate_loc = full_result[\"median\"][\"rate_loc\"]\n    ranked_lineages = []\n    for child in lineages:\n        # Allow grandparent to adopt orphan, since e.g. B.1.617 is missing from\n        # lineage_id, but B.1.617.2 is very important.\n        parent = pangolin.get_most_recent_ancestor(child, ancestors)\n        assert parent is not None\n        c = lineage_id[child]\n        p = lineage_id[parent]\n        gap = (rate_loc[c] - rate_loc[p]).abs().item()\n        ranked_lineages.append((gap, child))\n    ranked_lineages.sort(reverse=True)\n\n    # Compress lineage names before returning.\n    return [pangolin.compress(name) for gap, name in ranked_lineages]\n\n\ndef load_gisaid_data(\n    *,\n    device=\"cpu\",\n    include={},\n    exclude={},\n    end_day=None,\n    gisaid_columns_filename=\"results/gisaid.columns.pkl\",\n    nextclade_features_filename=\"results/nextclade.features.pt\",\n) -> dict:\n    \"\"\"\n    Loads the two files gisaid_columns_filename and nextclade_features_filename,\n    converts teh input to PyTorch tensors and truncates the data according to\n    ``include`` and ``exclude``.\n\n    Keyword arguments:\n    device -- torch device to use\n    include --\n    exclude --\n    end_day -- last day to include\n    gisaid_columns_filename --\n    nextclade_features_filename --\n    \"\"\"\n    logger.info(\"Loading data\")\n    include = include.copy()\n    exclude = exclude.copy()\n\n    if end_day:\n        logger.info(f\"Load gisaid data end_day: {end_day}\")\n\n    # Load ``gisaid_columns_filename``\n    with open(gisaid_columns_filename, \"rb\") as f:\n        columns = pickle.load(f)\n\n    logger.info(\"Training on {} rows with columns:\".format(len(columns[\"day\"])))\n    logger.info(\", \".join(columns.keys()))\n\n    # Filter regions to at least 50 sample and aggregate rest to country level\n    fine_regions = get_fine_regions(columns)\n\n    # Filter features into numbers of mutations and possibly genes.\n    aa_features = torch.load(nextclade_features_filename)\n    mutations = aa_features[\"mutations\"]\n    features = aa_features[\"features\"].to(\n        device=device, dtype=torch.get_default_dtype()\n    )\n    keep = [m.count(\",\") == 0 for m in mutations]  # restrict to single mutations\n    if include.get(\"gene\"):\n        re_gene = re.compile(include.pop(\"gene\"))\n        keep = [k and bool(re_gene.search(m)) for k, m in zip(keep, mutations)]\n    if exclude.get(\"gene\"):\n        re_gene = re.compile(exclude.pop(\"gene\"))\n        keep = [k and not re_gene.search(m) for k, m in zip(keep, mutations)]\n    if include.get(\"region\"):\n        gene, region = include.pop(\"region\")\n        lb, ub = sarscov2.GENE_STRUCTURE[gene][region]\n        for i, m in enumerate(mutations):\n            g, m = m.split(\":\")\n            if g != gene:\n                keep[i] = False\n                continue\n            match = re.search(\"[0-9]+\", m)\n            assert match is not None\n            pos = int(match.group())\n            if not (lb < pos <= ub):\n                keep[i] = False\n    mutations = [m for k, m in zip(keep, mutations) if k]\n    if mutations:\n        features = features[:, keep]\n    else:\n        warnings.warn(\"No mutations selected; using empty features\")\n        mutations = [\"S:D614G\"]  # bogus\n        features = features[:, :1] * 0\n    logger.info(\"Loaded {} feature matrix\".format(\" x \".join(map(str, features.shape))))\n\n    # Aggregate regions\n\n    # Get lineages\n    lineages = list(map(pangolin.compress, columns[\"lineage\"]))\n    lineage_id_inv = list(map(pangolin.compress, aa_features[\"lineages\"]))\n    lineage_id = {k: i for i, k in enumerate(lineage_id_inv)}\n\n    sparse_data: dict = Counter()\n    location_id: dict = OrderedDict()\n\n    # Set of lineages that are skipped\n    skipped = set()\n\n    # Generate sparse_data\n    for virus_name, day, location, lineage in zip(\n        columns[\"virus_name\"], columns[\"day\"], columns[\"location\"], lineages\n    ):\n        if lineage not in lineage_id:\n            if lineage not in skipped:\n                skipped.add(lineage)\n                logger.warning(f\"WARNING skipping unsampled lineage {lineage}\")\n            continue\n\n        # Filter by include/exclude\n        row = {\n            \"virus_name\": virus_name,\n            \"location\": location,\n            \"day\": day,\n            \"lineage\": pangolin.compress(lineage),\n        }\n        if not all(re.search(v, row[k]) for k, v in include.items()):\n            continue\n        if any(re.search(v, row[k]) for k, v in exclude.items()):\n            continue\n\n        # Filter by day\n        if end_day is not None:\n            if day > end_day:\n                continue\n\n        # preprocess parts\n        parts = location.split(\"/\")\n        if len(parts) < 2:\n            continue\n        parts = tuple(p.strip() for p in parts[:3])\n        if len(parts) == 3 and parts not in fine_regions:\n            parts = parts[:2]\n        location = \" / \".join(parts)\n\n        p = location_id.setdefault(location, len(location_id))\n        s = lineage_id[lineage]\n        t = day // TIMESTEP\n        sparse_data[t, p, s] += 1\n\n    # Generate weekly_strains tensor from sparse_data\n    if end_day is not None:\n        T = 1 + end_day // TIMESTEP\n    else:\n        T = 1 + max(columns[\"day\"]) // TIMESTEP\n\n    P = len(location_id)\n    S = len(lineage_id)\n    weekly_strains = torch.zeros(T, P, S)\n    for (t, p, s), n in sparse_data.items():\n        weekly_strains[t, p, s] = n\n\n    logger.info(f\"Dataset size [T x P x S] {T} x {P} x {S}\")\n\n    logger.info(\n        f\"Keeping {int(weekly_strains.sum())}/{len(lineages)} rows \"\n        f\"(dropped {len(lineages) - int(weekly_strains.sum())})\"\n    )\n\n    # Filter regions.\n    num_times_observed = (weekly_strains > 0).max(2).values.sum(0)\n    ok_regions = (num_times_observed >= 2).nonzero(as_tuple=True)[0]\n    ok_region_set = set(ok_regions.tolist())\n    logger.info(f\"Keeping {len(ok_regions)}/{weekly_strains.size(1)} regions\")\n    weekly_strains = weekly_strains.index_select(1, ok_regions)\n    locations = [k for k, v in location_id.items() if v in ok_region_set]\n    location_id = OrderedDict(zip(locations, range(len(locations))))\n\n    # Construct region-local time scales centered around observations.\n    num_obs = weekly_strains.sum(-1)\n    local_time = torch.arange(float(len(num_obs))) * TIMESTEP / GENERATION_TIME\n    local_time = local_time[:, None]\n    local_time = local_time - (local_time * num_obs).sum(0) / num_obs.sum(0)\n\n    return {\n        \"location_id\": location_id,\n        \"mutations\": mutations,\n        \"weekly_strains\": weekly_strains,\n        \"features\": features,\n        \"lineage_id\": lineage_id,\n        \"lineage_id_inv\": lineage_id_inv,\n        \"local_time\": local_time,\n    }\n\n\ndef subset_gisaid_data(\n    gisaid_dataset: dict,\n    location_queries=None,\n    max_strains=math.inf,\n) -> dict:\n    \"\"\"\n    Selects a small subset of data for exploratory fitting of a small model.\n    This is not used in the final published results.\n    \"\"\"\n    old = gisaid_dataset\n    new = old.copy()\n\n    # Select locations.\n    if location_queries is not None:\n        locations = sorted(\n            {\n                location\n                for location in new[\"location_id\"]\n                if any(q in location for q in location_queries)\n            }\n        )\n        ids = torch.tensor([old[\"location_id\"][location] for location in locations])\n        new[\"location_id\"] = {name: i for i, name in enumerate(locations)}\n        new[\"weekly_strains\"] = new[\"weekly_strains\"].index_select(1, ids)\n        new[\"local_time\"] = new[\"local_time\"].index_select(1, ids)\n\n    # Select strains.\n    if new[\"weekly_strains\"].size(-1) > max_strains:\n        ids = (\n            new[\"weekly_strains\"]\n            .sum([0, 1])\n            .sort(0, descending=True)\n            .indices[:max_strains]\n        )\n        new[\"weekly_strains\"] = new[\"weekly_strains\"].index_select(-1, ids)\n        new[\"features\"] = new[\"features\"].index_select(0, ids)\n        new[\"lineage_id_inv\"] = [new[\"lineage_id_inv\"][i] for i in ids.tolist()]\n        new[\"lineage_id\"] = {name: i for i, name in enumerate(new[\"lineage_id_inv\"])}\n\n    # Select mutations.\n    gaps = new[\"features\"].max(0).values - new[\"features\"].min(0).values\n    ids = (gaps >= 0.5).nonzero(as_tuple=True)[0]\n    new[\"mutations\"] = [new[\"mutations\"][i] for i in ids.tolist()]\n    new[\"features\"] = new[\"features\"].index_select(-1, ids)\n\n    logger.info(\n        \"Selected {}/{} places, {}/{} strains, {}/{} mutations, {}/{} samples\".format(\n            len(new[\"location_id\"]),\n            len(old[\"location_id\"]),\n            len(new[\"lineage_id\"]),\n            len(old[\"lineage_id\"]),\n            len(new[\"mutations\"]),\n            len(old[\"mutations\"]),\n            int(new[\"weekly_strains\"].sum()),\n            int(old[\"weekly_strains\"].sum()),\n        )\n    )\n\n    return new\n\n\ndef load_jhu_data(gisaid_data: dict) -> dict:\n    \"\"\"\n    Load case count time series.\n\n    This is used for plotting but is not used for fitting a model.\n    \"\"\"\n    # Load raw JHU case count data.\n    us_cases_df = pyrocov.geo.read_csv(\"time_series_covid19_confirmed_US.csv\")\n    global_cases_df = pyrocov.geo.read_csv(\"time_series_covid19_confirmed_global.csv\")\n    daily_cases = torch.cat(\n        [\n            pyrocov.geo.pd_to_torch(us_cases_df, columns=slice(11, None)),\n            pyrocov.geo.pd_to_torch(global_cases_df, columns=slice(4, None)),\n        ]\n    ).T\n    logger.info(\n        \"Loaded {} x {} daily case data, totaling {}\".format(\n            *daily_cases.shape, daily_cases[-1].sum().item()\n        )\n    )\n\n    # Convert JHU locations to GISAID locations.\n    locations = list(gisaid_data[\"location_id\"])\n    matrix = pyrocov.geo.gisaid_to_jhu_location(locations, us_cases_df, global_cases_df)\n    assert matrix.shape == (len(locations), daily_cases.shape[-1])\n    daily_cases = daily_cases @ matrix.T\n    daily_cases[1:] -= daily_cases[:-1].clone()  # cumulative -> density\n    daily_cases.clamp_(min=0)\n    assert daily_cases.shape[1] == len(gisaid_data[\"location_id\"])\n\n    # Convert daily counts to TIMESTEP counts (e.g. weekly).\n    start_date = datetime.datetime.strptime(START_DATE, \"%Y-%m-%d\")\n    jhu_start_date = pyrocov.geo.parse_date(us_cases_df.columns[11])\n    assert start_date < jhu_start_date\n    dt = (jhu_start_date - start_date).days\n    T = len(gisaid_data[\"weekly_strains\"])\n    weekly_cases = daily_cases.new_zeros(T, len(locations))\n    for w in range(TIMESTEP):\n        t0 = (w + dt) // TIMESTEP\n        source = daily_cases[w::TIMESTEP]\n        destin = weekly_cases[t0 : t0 + len(source)]\n        destin[:] += source[: len(destin)]\n    assert weekly_cases.sum() > 0\n\n    return {\n        \"daily_cases\": daily_cases.clamp(min=0),\n        \"weekly_cases\": weekly_cases.clamp(min=0),\n    }\n\n\ndef model(dataset, model_type, *, forecast_steps=None):\n    \"\"\"\n    Bayesian regression model of lineage portions as a function of mutation features.\n\n    This function can be run in two different modes:\n    - During training, ``forecast_steps=None`` and the model is conditioned on\n      observed data.\n    - During prediction (after training), the likelihood statement is omitted\n      and instead a ``probs`` tensor is recorded; this is the predicted lineage\n      portions in each (time, regin) bin.\n    \"\"\"\n    # Tensor shapes are commented at at the end of some lines.\n    features = dataset[\"features\"]\n    local_time = dataset[\"local_time\"][..., None]  # [T, P, 1]\n    T, P, _ = local_time.shape\n    S, F = features.shape\n    if forecast_steps is None:  # During inference.\n        weekly_strains = dataset[\"weekly_strains\"]\n        assert weekly_strains.shape == (T, P, S)\n    else:  # During prediction.\n        T = T + forecast_steps\n        t0 = local_time[0]\n        dt = local_time[1] - local_time[0]\n        local_time = t0 + dt * torch.arange(float(T))[:, None, None]\n        assert local_time.shape == (T, P, 1)\n    strain_plate = pyro.plate(\"strain\", S, dim=-1)\n    place_plate = pyro.plate(\"place\", P, dim=-2)\n    time_plate = pyro.plate(\"time\", T, dim=-3)\n\n    # Configure reparametrization (which does not affect model density).\n    reparam = {}\n    if \"reparam\" in model_type:\n        local_time = local_time + pyro.param(\n            \"local_time\", lambda: torch.zeros(P, S)\n        )  # [T, P, S]\n        reparam[\"coef\"] = LocScaleReparam()\n        if \"skip\" not in model_type:\n            reparam[\"rate_loc\"] = LocScaleReparam()\n        reparam[\"init_loc\"] = LocScaleReparam()\n        reparam[\"rate\"] = LocScaleReparam()\n        reparam[\"init\"] = LocScaleReparam()\n    with poutine.reparam(config=reparam):\n\n        # Sample global random variables.\n        coef_scale = pyro.sample(\"coef_scale\", dist.LogNormal(-4, 2))\n        if \"skip\" not in model_type:\n            rate_loc_scale = pyro.sample(\"rate_loc_scale\", dist.LogNormal(-4, 2))\n        init_loc_scale = pyro.sample(\"init_loc_scale\", dist.LogNormal(0, 2))\n        rate_scale = pyro.sample(\"rate_scale\", dist.LogNormal(-4, 2))\n        init_scale = pyro.sample(\"init_scale\", dist.LogNormal(0, 2))\n        if \"poisson\" in model_type:\n            pois_loc = pyro.sample(\"pois_loc\", dist.Normal(0, 4))\n            pois_scale = pyro.sample(\"pois_scale\", dist.LogNormal(0, 4))\n\n        # Assume relative growth rate depends strongly on mutations and weakly\n        # on strain and place. Assume initial infections depend strongly on\n        # strain and place.\n        Dist = dist.Logistic if \"sparse\" in model_type else dist.Normal\n        coef = pyro.sample(\"coef\", Dist(torch.zeros(F), coef_scale).to_event(1))  # [F]\n        with strain_plate:\n            rate_loc_loc = 0.01 * coef @ features.T\n            if \"skip\" in model_type:\n                rate_loc = pyro.deterministic(\"rate_loc\", rate_loc_loc)  # [S]\n            else:\n                rate_loc = pyro.sample(\n                    \"rate_loc\", dist.Normal(rate_loc_loc, rate_loc_scale)\n                )  # [S]\n            init_loc = pyro.sample(\"init_loc\", dist.Normal(0, init_loc_scale))  # [S]\n        with place_plate, strain_plate:\n            rate = pyro.sample(\"rate\", dist.Normal(rate_loc, rate_scale))  # [P, S]\n            init = pyro.sample(\"init\", dist.Normal(init_loc, init_scale))  # [P, S]\n\n        # Finally observe counts.\n        logits = init + rate * local_time  # [T, P, S]\n        if forecast_steps is None:  # During inference.\n            if \"poisson\" in model_type:\n                with time_plate, place_plate:\n                    pois = pyro.sample(\"pois\", dist.LogNormal(pois_loc, pois_scale))\n                # This softmax() breaks the strain_plate, but is more\n                # numerically stable than exp(). AutoGaussian inference will be\n                # approximate with softmax(), but would be intractable with\n                # exp() and a second_strain_plate.\n                lambda_ = (pois * logits.softmax(-1)).clamp_(min=1e-6)\n                with time_plate, place_plate, strain_plate:\n                    pyro.sample(\n                        \"obs\", dist.Poisson(lambda_), obs=weekly_strains\n                    )  # [T, P, S]\n            else:\n                with time_plate, place_plate:\n                    pyro.sample(\n                        \"obs\",\n                        dist.Multinomial(\n                            logits=logits[..., None, :], validate_args=False\n                        ),\n                        obs=weekly_strains[..., None, :],\n                    )  # [T, P, 1, S]\n        else:  # During prediction.\n            with time_plate, place_plate, strain_plate:\n                pyro.deterministic(\"probs\", logits.softmax(-1))\n\n\nclass InitLocFn:\n    \"\"\"\n    Initializer for latent variables.\n\n    This is passed as the ``init_loc_fn`` to guides.\n    \"\"\"\n\n    def __init__(self, dataset):\n        # Initialize init.\n        init = dataset[\"weekly_strains\"].sum(0)  # [P, S]\n        init.add_(1 / init.size(-1)).div_(init.sum(-1, True))\n        init.log_().sub_(init.median(-1, True).values)\n        self.init = init  # [P, S]\n        self.init_decentered = init / 2\n        self.init_loc = init.mean(0)  # [S]\n        self.init_loc_decentered = self.init_loc / 2\n        assert not torch.isnan(self.init).any()\n        self.pois = dataset[\"weekly_strains\"].sum(-1, True).clamp(min=0.1)  # [T, P, 1]\n        logger.info(f\"init stddev = {self.init.std():0.3g}\")\n\n    def __call__(self, site):\n        name = site[\"name\"]\n        shape = site[\"fn\"].shape()\n        if hasattr(self, name):\n            result = getattr(self, name)\n            assert result.shape == shape\n            return result\n        if name in (\"coef_scale\", \"init_scale\", \"init_loc_scale\"):\n            return torch.ones(shape)\n        if name == \"logits_scale\":\n            return torch.full(shape, 0.002)\n        if name in (\"rate_loc_scale\", \"rate_scale\", \"place_scale\", \"strain_scale\"):\n            return torch.full(shape, 0.01)\n        if name in (\n            \"rate_loc\",\n            \"rate_loc_decentered\",\n            \"coef\",\n            \"coef_decentered\",\n            \"rate\",\n            \"rate_decentered\",\n        ):\n            return torch.rand(shape).sub_(0.5).mul_(0.01)\n        if name == \"coef_loc\":\n            return torch.rand(shape).sub_(0.5).mul_(0.01).add_(1.0)\n        if name == \"pois_loc\":\n            return self.pois.log().mean()\n        if name == \"pois_scale\":\n            return self.pois.log().std()\n        if name == \"pois\":\n            return self.pois\n        raise ValueError(f\"InitLocFn found unhandled site {repr(name)}; please update.\")\n\n\nclass Guide(AutoGuideList):\n    \"\"\"\n    Custom guide for large-scale inference.\n\n    This combines a low-rank multivariate normal guide over small variables\n    with a mean field guide over remaining latent variables.\n    \"\"\"\n\n    def __init__(self, model, init_loc_fn, init_scale, rank):\n        super().__init__(model)\n\n        # Jointly estimate globals, mutation coefficients, and strain coefficients.\n        mvn = [\n            \"coef_scale\",\n            \"rate_loc_scale\",\n            \"init_loc_scale\",\n            \"rate_scale\",\n            \"init_scale\",\n            \"coef\",\n            \"coef_decentered\",\n            \"rate_loc\",\n            \"rate_loc_decentered\",\n            \"init_loc\",\n            \"init_loc_decentered\",\n        ]\n        self.append(\n            AutoLowRankMultivariateNormal(\n                poutine.block(model, expose=mvn),\n                init_loc_fn=init_loc_fn,\n                init_scale=init_scale,\n                rank=rank,\n            )\n        )\n        model = poutine.block(model, hide=mvn)\n\n        # Mean-field estimate all remaining latent variables.\n        self.append(AutoNormal(model, init_loc_fn=init_loc_fn, init_scale=init_scale))\n\n\n@torch.no_grad()\n@poutine.mask(mask=False)\ndef predict(\n    model,\n    guide,\n    dataset,\n    model_type,\n    *,\n    num_samples=1000,\n    vectorize=None,\n    save_params=(\"rate\", \"init\", \"probs\"),\n    forecast_steps=0,\n) -> dict:\n    def get_conditionals(data):\n        trace = poutine.trace(poutine.condition(model, data)).get_trace(\n            dataset, model_type, forecast_steps=forecast_steps\n        )\n        return {\n            name: site[\"value\"].detach()\n            for name, site in trace.nodes.items()\n            if site[\"type\"] == \"sample\" and not site_is_subsample(site)\n            if name != \"obs\"\n        }\n\n    # Compute median point estimate.\n    result: dict = defaultdict(dict)\n    for name, value in get_conditionals(guide.median(dataset)).items():\n        if value.numel() < 1e5 or name in save_params:\n            result[\"median\"][name] = value\n\n    # Compute moments.\n    save_params = {\n        k for k, v in result[\"median\"].items() if v.numel() < 1e5 or k in save_params\n    }\n    if vectorize is None:\n        vectorize = result[\"median\"][\"probs\"].numel() < 1e6\n    if vectorize:\n        with pyro.plate(\"particles\", num_samples, dim=-4):\n            samples = get_conditionals(guide())\n        for k, v in samples.items():\n            if k in save_params:\n                result[\"mean\"][k] = v.mean(0).squeeze()\n                result[\"std\"][k] = v.std(0).squeeze()\n    else:\n        stats = StatsOfDict({k: CountMeanVarianceStats for k in save_params})\n        for _ in range(num_samples):\n            stats.update(get_conditionals(guide()))\n            print(\".\", end=\"\", flush=True)\n        for name, stats_ in stats.get().items():\n            if \"mean\" in stats_:\n                result[\"mean\"][name] = stats_[\"mean\"]\n            if \"variance\" in stats_:\n                result[\"std\"][name] = stats_[\"variance\"].sqrt()\n    return dict(result)\n\n\ndef fit_svi(\n    dataset: dict,\n    *,\n    model_type: str,\n    guide_type: str,\n    cond_data={},\n    forecast_steps=0,\n    learning_rate=0.05,\n    learning_rate_decay=0.1,\n    num_steps=3001,\n    num_samples=1000,\n    clip_norm=10.0,\n    rank=200,\n    jit=True,\n    log_every=50,\n    seed=20210319,\n    check_loss=False,\n) -> dict:\n    \"\"\"\n    Fits a variational posterior using stochastic variational inference (SVI).\n    \"\"\"\n    start_time = default_timer()\n\n    logger.info(f\"Fitting {guide_type} guide via SVI\")\n    pyro.set_rng_seed(seed)\n    pyro.clear_param_store()\n    param_store = pyro.get_param_store()\n\n    # Initialize guide so we can count parameters and register hooks.\n    cond_data = {k: torch.as_tensor(v) for k, v in cond_data.items()}\n    model_ = poutine.condition(model, cond_data)\n    init_loc_fn = InitLocFn(dataset)\n    if guide_type == \"map\":\n        guide = AutoDelta(model_, init_loc_fn=init_loc_fn)\n    elif guide_type == \"normal\":\n        guide = AutoNormal(model_, init_loc_fn=init_loc_fn, init_scale=0.01)\n    elif guide_type == \"full\":\n        guide = AutoLowRankMultivariateNormal(\n            model_, init_loc_fn=init_loc_fn, init_scale=0.01, rank=rank\n        )\n    elif guide_type == \"structured\":\n        guide = AutoStructured(\n            model_,\n            init_loc_fn=init_loc_fn,\n            init_scale=0.01,\n            conditionals=defaultdict(\n                lambda: \"normal\",\n                rate_scale=\"delta\",\n                init_loc_scale=\"delta\",\n                init_scale=\"delta\",\n                coef=\"mvn\",\n                coef_decentered=\"mvn\",\n            ),\n        )\n    elif guide_type == \"gaussian\":\n        from pyro.infer.autoguide import AutoGaussian\n\n        guide = AutoGaussian(\n            model_, init_loc_fn=init_loc_fn, init_scale=0.01, backend=\"funsor\"\n        )\n    else:\n        guide = Guide(model_, init_loc_fn=init_loc_fn, init_scale=0.01, rank=rank)\n    # This initializes the guide:\n    latent_shapes = {k: v.shape for k, v in guide(dataset, model_type).items()}\n    latent_numel = {k: v.numel() for k, v in latent_shapes.items()}\n    logger.info(\n        \"\\n\".join(\n            [f\"Model has {sum(latent_numel.values())} latent variables of shapes:\"]\n            + [f\" {k} {tuple(v)}\" for k, v in latent_shapes.items()]\n        )\n    )\n    param_shapes = {k: v.shape for k, v in pyro.get_param_store().named_parameters()}\n    param_numel = {k: v.numel() for k, v in param_shapes.items()}\n    logger.info(\n        \"\\n\".join(\n            [f\"Guide has {sum(param_numel.values())} parameters of shapes:\"]\n            + [f\" {k} {tuple(v)}\" for k, v in param_shapes.items()]\n        )\n    )\n\n    # Log gradient norms during inference.\n    series: dict = defaultdict(list)\n\n    def hook(g, series):\n        series.append(torch.linalg.norm(g.reshape(-1), math.inf).item())\n\n    for name, value in pyro.get_param_store().named_parameters():\n        value.register_hook(functools.partial(hook, series=series[name]))\n\n    def optim_config(param_name):\n        config: dict = {\n            \"lr\": learning_rate,\n            \"lrd\": learning_rate_decay ** (1 / num_steps),\n            \"clip_norm\": clip_norm,\n        }\n        scalars = [k for k, v in latent_numel.items() if v == 1]\n        if any(\"locs.\" + s in name for s in scalars):\n            config[\"lr\"] *= 0.2\n        elif \"scales\" in param_name:\n            config[\"lr\"] *= 0.1\n        elif \"scale_tril\" in param_name:\n            config[\"lr\"] *= 0.05\n        elif \"factors\" in param_name:\n            config[\"lr\"] *= 0.05\n        elif \"weight_\" in param_name:\n            config[\"lr\"] *= 0.01\n        elif \"weight\" in param_name:\n            config[\"lr\"] *= 0.03\n        elif \"_centered\" in param_name:\n            config[\"lr\"] *= 0.1\n        return config\n\n    optim = ClippedAdam(optim_config)\n    Elbo = JitTrace_ELBO if jit else Trace_ELBO\n    elbo = Elbo(max_plate_nesting=3, ignore_jit_warnings=True)\n    svi = SVI(model_, guide, optim, elbo)\n    losses = []\n    num_obs = dataset[\"weekly_strains\"].count_nonzero()\n    for step in range(num_steps):\n        loss = svi.step(dataset=dataset, model_type=model_type)\n        assert not math.isnan(loss)\n        losses.append(loss)\n        median = guide.median()\n        for name, value in median.items():\n            if value.numel() == 1:\n                series[name].append(float(value))\n        if log_every and step % log_every == 0:\n            logger.info(\n                \" \".join(\n                    [f\"step {step: >4d} L={loss / num_obs:0.6g}\"]\n                    + [\n                        \"{}={:0.3g}\".format(\n                            \"\".join(p[0] for p in k.split(\"_\")).upper(), v.item()\n                        )\n                        for k, v in median.items()\n                        if v.numel() == 1\n                    ]\n                )\n            )\n        if check_loss and step >= 50:\n            prev = torch.tensor(losses[-50:-25], device=\"cpu\").median().item()\n            curr = torch.tensor(losses[-25:], device=\"cpu\").median().item()\n            assert (curr - prev) < num_obs, \"loss is increasing\"\n\n    result = predict(\n        model_,\n        guide,\n        dataset,\n        model_type,\n        num_samples=num_samples,\n        forecast_steps=forecast_steps,\n    )\n    result[\"losses\"] = losses\n    series[\"loss\"] = losses\n    result[\"series\"] = dict(series)\n    result[\"params\"] = {\n        k: v.detach().float().cpu().clone()\n        for k, v in param_store.items()\n        if v.numel() < 1e7\n    }\n    result[\"walltime\"] = default_timer() - start_time\n    return result\n\n\n@torch.no_grad()\ndef log_stats(dataset: dict, result: dict) -> dict:\n    \"\"\"\n    Logs statistics of predictions and model fit in the ``result`` of\n    ``fit_svi()``.\n\n    :param dict dataset: The dataset dictionary.\n    :param dict result: The output of :func:`fit_svi`.\n    :returns: A dictionary of statistics.\n    \"\"\"\n    stats = {k: float(v) for k, v in result[\"median\"].items() if v.numel() == 1}\n    stats[\"loss\"] = float(np.median(result[\"losses\"][-100:]))\n    mutations = dataset[\"mutations\"]\n    mean = result[\"mean\"][\"coef\"].cpu()\n    if not mean.shape:\n        return stats  # Work around error in map estimation.\n\n    # Statistical significance.\n    std = result[\"std\"][\"coef\"].cpu()\n    sig = mean.abs() / std\n    logger.info(f\"|μ|/σ [median,max] = [{sig.median():0.3g},{sig.max():0.3g}]\")\n    stats[\"|μ|/σ median\"] = sig.median()\n    stats[\"|μ|/σ max\"] = sig.max()\n\n    # Effects of individual mutations.\n    for name in [\"S:D614G\", \"S:N501Y\", \"S:E484K\", \"S:L452R\"]:\n        if name not in mutations:\n            continue\n        i = mutations.index(name)\n        m = mean[i] * 0.01\n        s = std[i] * 0.01\n        logger.info(f\"ΔlogR({name}) = {m:0.3g} ± {s:0.2f}\")\n        stats[f\"ΔlogR({name}) mean\"] = m\n        stats[f\"ΔlogR({name}) std\"] = s\n\n    # Growth rates of individual lineages.\n    try:\n        i = dataset[\"lineage_id\"][\"A\"]\n        rate_A = result[\"mean\"][\"rate\"][..., i].mean(0)\n    except KeyError:\n        rate_A = result[\"mean\"][\"rate\"].median()\n    for s in [\"B.1.1.7\", \"B.1.617.2\"]:\n        i = dataset[\"lineage_id\"][s]\n        rate = result[\"median\"][\"rate\"][..., i].mean()\n        R_RA = (rate - rate_A).exp()\n        logger.info(f\"R({s})/R(A) = {R_RA:0.3g}\")\n        stats[f\"R({s})/R(A)\"] = R_RA\n\n    # Accuracy of mutation-only model, ie without region-local effects.\n    true = dataset[\"weekly_strains\"] + 1e-20  # avoid nans\n    counts = true.sum(-1, True)\n    true_probs = true / counts\n    local_time = dataset[\"local_time\"][..., None]\n    if \"local_time\" in result[\"params\"]:\n        local_time = local_time + result[\"params\"][\"local_time\"].to(local_time.device)\n    rate = 0.01 * result[\"median\"][\"coef\"] @ dataset[\"features\"].T\n    pred = result[\"median\"][\"init\"] + rate * local_time\n    pred -= pred.logsumexp(-1, True)  # apply log sigmoid function\n    kl = true.mul(true_probs.log() - pred).sum(-1)\n    kl = stats[\"naive KL\"] = kl.sum() / counts.sum()  # in units of nats / observation\n    error = (pred.exp() - true_probs) * counts ** 0.5  # scaled by Poisson stddev\n    mae = stats[\"naive MAE\"] = error.abs().sum(-1).mean()\n    rmse = stats[\"naive RMSE\"] = error.square().sum(-1).mean().sqrt()\n    logger.info(f\"naive KL = {kl:0.4g}, MAE = {mae:0.4g}, RMSE = {rmse:0.4g}\")\n\n    # Posterior predictive error.\n    pred = result[\"median\"][\"probs\"][: len(true)] + 1e-20  # truncate, avoid nans\n    kl = true.mul(true_probs.log() - pred.log()).sum([0, -1])\n    error = (pred - true_probs) * counts ** 0.5  # scaled by Poisson stddev\n    mae = error.abs().mean(0)  # average over time\n    mse = error.square().mean(0)  # average over time\n    stats[\"MAE\"] = mae.sum(-1).mean()  # average over region\n    stats[\"RMSE\"] = mse.sum(-1).mean().sqrt()  # root average over region\n    stats[\"KL\"] = kl.sum() / counts.sum()  # in units of nats / observation\n    logger.info(\"KL = {KL:0.4g}, MAE = {MAE:0.4g}, RMSE = {RMSE:0.4g}\".format(**stats))\n\n    # Examine the MSE and RMSE over a few regions of interest.\n    queries = {\n        \"England\": [\"B.1.1.7\"],\n        # \"England\": [\"B.1.1.7\", \"B.1.177\", \"B.1.1\", \"B.1\"],\n        # \"USA / California\": [\"B.1.1.7\", \"B.1.429\", \"B.1.427\", \"B.1.2\", \"B.1\", \"P.1\"],\n    }\n    for place, strains in queries.items():\n        matches = [p for name, p in dataset[\"location_id\"].items() if place in name]\n        if not matches:\n            continue\n        assert len(matches) == 1, matches\n        p = matches[0]\n        stats[f\"{place} KL\"] = kl[p].sum() / true[:, p].sum()\n        stats[f\"{place} MAE\"] = mae[p].sum()\n        stats[f\"{place} RMSE\"] = mse[p].sum().sqrt()\n        logger.info(\n            \"{}\\tKL = {:0.3g}, MAE = {:0.3g}, RMSE = {:0.3g}\".format(\n                place,\n                stats[f\"{place} KL\"],\n                stats[f\"{place} MAE\"],\n                stats[f\"{place} RMSE\"],\n            )\n        )\n\n        for strain in strains:\n            s = dataset[\"lineage_id\"][strain]\n            stats[f\"{place} {strain} MAE\"] = mae[p, s]\n            stats[f\"{place} {strain} RMSE\"] = mse[p, s].sqrt()\n            logger.info(\n                \"{} {}\\tMAE = {:0.3g}, RMSE = {:0.3g}\".format(\n                    place,\n                    strain,\n                    stats[f\"{place} {strain} MAE\"],\n                    stats[f\"{place} {strain} RMSE\"],\n                )\n            )\n\n    return {k: float(v) for k, v in stats.items()}\n\n\n@torch.no_grad()\ndef log_holdout_stats(fits: dict) -> dict:\n    \"\"\"\n    Logs statistics comparing multiple results from ``fit_svi``.\n    \"\"\"\n    assert len(fits) > 1\n    fits = list(fits.items())\n    stats = {}\n    for i, (name1, fit1) in enumerate(fits[:-1]):\n        for name2, fit2 in fits[i + 1 :]:\n            # Compute mutation similarity.\n            mutations = sorted(set(fit1[\"mutations\"]) & set(fit2[\"mutations\"]))\n            medians = []\n            for fit in (fit1, fit2):\n                mutation_id = {m: i for i, m in enumerate(fit[\"mutations\"])}\n                idx = torch.tensor([mutation_id[m] for m in mutations])\n                medians.append(fit[\"median\"][\"coef\"][idx] * 0.01)\n            error = medians[0] - medians[1]\n            mutation_std = torch.cat(medians).std().item()\n            mutation_rmse = error.square().mean().sqrt().item()\n            mutation_mae = error.abs().mean().item()\n            mutation_correlation = pearson_correlation(medians[0], medians[1]).item()\n\n            # Compute lineage similarity.\n            means = []\n            for fit in (fit1, fit2):\n                rate = fit[\"mean\"][\"rate\"]\n                if rate.dim() == 2:\n                    rate = rate.mean(0)\n                means.append(rate)\n            error = means[0] - means[1]\n            lineage_std = torch.cat(means).std().item()\n            lineage_rmse = error.square().mean().sqrt().item()\n            lineage_mae = error.abs().mean().item()\n            lineage_correlation = pearson_correlation(means[0], means[1]).item()\n\n            # Print stats.\n            logger.info(\n                f\"{name1} vs {name2} mutations: \"\n                f\"ρ = {mutation_correlation:0.3g}, \"\n                f\"RMSE = {mutation_rmse:0.3g}, \"\n                f\"MAE = {mutation_mae:0.3g}\"\n            )\n            logger.info(\n                f\"{name1} vs {name2} lineages: \"\n                f\"ρ = {lineage_correlation:0.3g}, \"\n                f\"RMSE = {lineage_rmse:0.3g}, \"\n                f\"MAE = {lineage_mae:0.3g}\"\n            )\n\n            # Save stats.\n            stats[\"mutation_corr\"] = mutation_correlation\n            stats[\"mutation_rmse\"] = mutation_rmse\n            stats[\"mutation_mae\"] = mutation_mae\n            stats[\"mutation_stddev\"] = mutation_std\n            stats[\"lineage_corr\"] = lineage_correlation\n            stats[\"lineage_rmse\"] = lineage_rmse\n            stats[\"lineage_mae\"] = lineage_mae\n            stats[\"lineage_stdev\"] = lineage_std\n\n    return {k: float(v) for k, v in stats.items()}\n", "meta": {"hexsha": "80006512ac36b92846ec14379f75c24ceeaad416", "size": 36509, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyrocov/mutrans.py", "max_stars_repo_name": "tomwenseleers/pyro-cov", "max_stars_repo_head_hexsha": "9496e8d2d78239950f58470afd516b9dd9e5d594", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-14T18:44:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-14T18:44:12.000Z", "max_issues_repo_path": "pyrocov/mutrans.py", "max_issues_repo_name": "tomwenseleers/pyro-cov", "max_issues_repo_head_hexsha": "9496e8d2d78239950f58470afd516b9dd9e5d594", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyrocov/mutrans.py", "max_forks_repo_name": "tomwenseleers/pyro-cov", "max_forks_repo_head_hexsha": "9496e8d2d78239950f58470afd516b9dd9e5d594", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8777777778, "max_line_length": 88, "alphanum_fraction": 0.5836369114, "include": true, "reason": "import numpy", "num_tokens": 9397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.29098086621490676, "lm_q1q2_score": 0.1523053065280003}}
{"text": "# -*- coding: utf-8 -*-\n\nimport numpy as np\n\nfrom pyfr.solvers.baseadvecdiff import (BaseAdvectionDiffusionBCInters,\n                                        BaseAdvectionDiffusionIntInters,\n                                        BaseAdvectionDiffusionMPIInters)\n\n\nclass NavierStokesIntInters(BaseAdvectionDiffusionIntInters):\n    def __init__(self, *args, **kwargs):\n        super(NavierStokesIntInters, self).__init__(*args, **kwargs)\n\n        # Pointwise template arguments\n        rsolver = self._cfg.get('solver-interfaces', 'riemann-solver')\n        self._tplargs = dict(ndims=self.ndims, nvars=self.nvars,\n                             rsolver=rsolver, c=self._tpl_c)\n\n        self._be.pointwise.register('pyfr.solvers.navstokes.kernels.intconu')\n        self._be.pointwise.register('pyfr.solvers.navstokes.kernels.intcflux')\n\n    def get_con_u_kern(self):\n        return self._be.kernel('intconu', self._tplargs,\n                               dims=[self.ninterfpts],\n                               ulin=self._scal0_lhs, urin=self._scal0_rhs,\n                               ulout=self._scal1_lhs, urout=self._scal1_rhs)\n\n    def get_comm_flux_kern(self):\n        return self._be.kernel('intcflux', self._tplargs,\n                               dims=[self.ninterfpts],\n                               ul=self._scal0_lhs, ur=self._scal0_rhs,\n                               gradul=self._vect0_lhs, gradur=self._vect0_rhs,\n                               magnl=self._mag_pnorm_lhs,\n                               magnr=self._mag_pnorm_rhs,\n                               nl=self._norm_pnorm_lhs)\n\n\nclass NavierStokesMPIInters(BaseAdvectionDiffusionMPIInters):\n    def __init__(self, *args, **kwargs):\n        super(NavierStokesMPIInters, self).__init__(*args, **kwargs)\n\n        # Pointwise template arguments\n        rsolver = self._cfg.get('solver-interfaces', 'riemann-solver')\n        self._tplargs = dict(ndims=self.ndims, nvars=self.nvars,\n                             rsolver=rsolver, c=self._tpl_c)\n\n        self._be.pointwise.register('pyfr.solvers.navstokes.kernels.mpiconu')\n        self._be.pointwise.register('pyfr.solvers.navstokes.kernels.mpicflux')\n\n    def get_con_u_kern(self):\n        return self._be.kernel('mpiconu', self._tplargs,\n                               dims=[self.ninterfpts],\n                               ulin=self._scal0_lhs, urin=self._scal0_rhs,\n                               ulout=self._scal1_lhs)\n\n    def get_comm_flux_kern(self):\n        return self._be.kernel('mpicflux', self._tplargs,\n                               dims=[self.ninterfpts],\n                               ul=self._scal0_lhs, ur=self._scal0_rhs,\n                               gradul=self._vect0_lhs, gradur=self._vect0_rhs,\n                               magnl=self._mag_pnorm_lhs,\n                               nl=self._norm_pnorm_lhs)\n\n\nclass NavierStokesBaseBCInters(BaseAdvectionDiffusionBCInters):\n    def __init__(self, *args, **kwargs):\n        super(NavierStokesBaseBCInters, self).__init__(*args, **kwargs)\n\n        # Pointwise template arguments\n        rsolver = self._cfg.get('solver-interfaces', 'riemann-solver')\n        self._tplargs = dict(ndims=self.ndims, nvars=self.nvars,\n                             rsolver=rsolver, c=self._tpl_c,\n                             bctype=self.type)\n\n        self._be.pointwise.register('pyfr.solvers.navstokes.kernels.bcconu')\n        self._be.pointwise.register('pyfr.solvers.navstokes.kernels.bccflux')\n\n    def get_con_u_kern(self):\n        return self._be.kernel('bcconu', self._tplargs, dims=[self.ninterfpts],\n                               ulin=self._scal0_lhs, ulout=self._scal1_lhs)\n\n    def get_comm_flux_kern(self):\n        return self._be.kernel('bccflux', self._tplargs,\n                               dims=[self.ninterfpts],\n                               ul=self._scal0_lhs, gradul=self._vect0_lhs,\n                               magnl=self._mag_pnorm_lhs,\n                               nl=self._norm_pnorm_lhs)\n\n\nclass NavierStokesNoSlpIsotWallBCInters(NavierStokesBaseBCInters):\n    type = 'no-slp-isot-wall'\n\n    def __init__(self, *args, **kwargs):\n        super(NavierStokesNoSlpIsotWallBCInters, self).__init__(*args,\n                                                                **kwargs)\n\n        self._tpl_c['cpTw'], = self._eval_opts(['cpTw'])\n        self._tpl_c['v'] = self._eval_opts('uvw'[:self.ndims], default='0')\n\n\nclass NavierStokesNoSlpAdiaWallBCInters(NavierStokesBaseBCInters):\n    type = 'no-slp-adia-wall'\n\n\nclass NavierStokesSupInflowBCInters(NavierStokesBaseBCInters):\n    type = 'sup-in-fa'\n\n    def __init__(self, *args, **kwargs):\n        super(NavierStokesSupInflowBCInters, self).__init__(*args, **kwargs)\n\n        self._tpl_c['rho'], self._tpl_c['p'] = self._eval_opts(['rho', 'p'])\n        self._tpl_c['v'] = self._eval_opts('uvw'[:self.ndims])\n\n\nclass NavierStokesSupOutflowBCInters(NavierStokesBaseBCInters):\n    type = 'sup-out-fn'\n\n\nclass NavierStokesSubInflowFrvBCInters(NavierStokesBaseBCInters):\n    type = 'sub-in-frv'\n\n    def __init__(self, *args, **kwargs):\n        super(NavierStokesSubInflowFrvBCInters, self).__init__(*args, **kwargs)\n\n        self._tpl_c['rho'], = self._eval_opts(['rho'])\n        self._tpl_c['v'] = self._eval_opts('uvw'[:self.ndims])\n\n\nclass NavierStokesSubInflowFtpttangBCInters(NavierStokesBaseBCInters):\n    type = 'sub-in-ftpttang'\n\n    def __init__(self, *args, **kwargs):\n        super(NavierStokesSubInflowFtpttangBCInters, self).__init__(*args,\n                                                                    **kwargs)\n\n        gamma = self._cfg.getfloat('constants', 'gamma')\n\n        # Pass boundary constants to the backend\n        self._tpl_c['cpTt'], = self._eval_opts(['cpTt'])\n        self._tpl_c['pt'], = self._eval_opts(['pt'])\n        self._tpl_c['Rdcp'] = (gamma - 1.0)/gamma\n\n        # Calculate u, v velocity components from the inflow angle\n        theta = self._eval_opts(['theta'])[0]*np.pi/180.0\n        velcomps = np.array([np.cos(theta), np.sin(theta), 1.0])\n\n        # Adjust u, v and calculate w velocity components for 3-D\n        if self.ndims == 3:\n            phi = self._eval_opts(['phi'])[0]*np.pi/180.0\n            velcomps[:2] *= np.sin(phi)\n            velcomps[2] *= np.cos(phi)\n\n        self._tpl_c['vc'] = velcomps[:self.ndims]\n\n\nclass NavierStokesSubOutflowBCInters(NavierStokesBaseBCInters):\n    type = 'sub-out-fp'\n\n    def __init__(self, *args, **kwargs):\n        super(NavierStokesSubOutflowBCInters, self).__init__(*args, **kwargs)\n\n        self._tpl_c['p'], = self._eval_opts(['p'])\n", "meta": {"hexsha": "a2ac06dd3eab8bd308657f772ba6bb8b9b24e58b", "size": 6583, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyfr/solvers/navstokes/inters.py", "max_stars_repo_name": "jappa/PyFR", "max_stars_repo_head_hexsha": "d99120c1db245c7a2a35c72dae51ea72c49efef5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyfr/solvers/navstokes/inters.py", "max_issues_repo_name": "jappa/PyFR", "max_issues_repo_head_hexsha": "d99120c1db245c7a2a35c72dae51ea72c49efef5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyfr/solvers/navstokes/inters.py", "max_forks_repo_name": "jappa/PyFR", "max_forks_repo_head_hexsha": "d99120c1db245c7a2a35c72dae51ea72c49efef5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3865030675, "max_line_length": 79, "alphanum_fraction": 0.5962327206, "include": true, "reason": "import numpy", "num_tokens": 1705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.290980853917813, "lm_q1q2_score": 0.1523053000914512}}
{"text": "import os\nimport copy\nimport numpy as np\nfrom astropy import table\nfrom astropy.io import ascii\nimport subprocess\nimport logging\nfrom scipy import optimize\nimport cvxopt\n\nfrom dynamite import physical_system as physys\nfrom dynamite import kinematics as dyn_kin\n\nclass WeightSolver(object):\n    \"\"\"Generic WeightSolver class\n\n    Specific implementations are defined as sub-classes. Each one should\n    have a main method `solve`\n\n    \"\"\"\n    def __init__(self):\n        self.logger = logging.getLogger(f'{__name__}.{__class__.__name__}')\n        pass\n\n    def solve(self, orblib):\n        \"\"\"Template solve method\n\n        Specific implementations should override this.\n\n        Parameters\n        ----------\n        orblib : dyn.OrbitLibrary object\n\n        Returns\n        -------\n        weights : array\n            orbit weights\n        chi2_all : float\n            a total chi2 value\n        chi2_kin : float\n            a chi2 value purely for kinematics\n        \"\"\"\n        self.logger.info(f\"Using WeightSolver: {__class__.__name__}\")\n        # ...\n        # calculate orbit weights, and model chi2 values here\n        # ...\n        weights = 0.\n        chi2_tot = 0.\n        chi2_kin = 0.\n        # ...\n        return weights, chi2_tot, chi2_kin\n\n\nclass LegacyWeightSolver(WeightSolver):\n    \"\"\"Use `legacy` AKA Fortran weight solving.\n\n    Uses the legcay_fortran program ``triaxnnls_CRcut.f90`` or\n    ```triaxnnls_noCRcut.f90``. Uses Lawson and Hanson non-negative\n    least-squares algorithm.\n\n    Parameters\n    ----------\n    config : a ``dyn.config_reader.Configuration`` object\n    directory_with_ml : string\n        model directory with the ml extension\n    CRcut : Bool, default False\n        whether to use the `CRcut` solution for the counter-rotating orbit\n        problem. See Zhu et al. 2018 for more.\n\n    \"\"\"\n    def __init__(self, config, directory_with_ml, CRcut=False):\n        self.logger = logging.getLogger(f'{__name__}.{__class__.__name__}')\n        self.system = config.system\n        self.directory_with_ml = directory_with_ml\n        self.settings = config.settings.weight_solver_settings\n        self.legacy_directory = config.settings.legacy_settings['directory']\n        self.sformat = self.system.parameters[0].sformat # this is ml's format\n        ml_idx = self.directory_with_ml.rindex('/ml')\n        self.direc_no_ml = directory_with_ml[:ml_idx+1]\n        ml_str = self.directory_with_ml[ml_idx+3:]\n        self.ml = float(ml_str[:-1]) if ml_str[-1] == '/' else float(ml_str)\n        self.fname_nn_kinem = self.directory_with_ml + 'nn_kinem.out'\n        self.fname_nn_nnls = self.directory_with_ml + 'nn_nnls.out'\n        if 'CRcut' in self.settings.keys():\n            CRcut = self.settings['CRcut']\n        self.CRcut = CRcut\n        # prepare fortran input file for nnls\n        self.copy_kinematic_data()\n        self.create_fortran_input_nnls(self.direc_no_ml, self.ml)\n\n    def copy_kinematic_data(self):\n        \"\"\"Copy kin data to infil/ direc\n        \"\"\"\n        stars = self.system.get_component_from_class( \\\n                                        physys.TriaxialVisibleComponent)\n        kinematics = stars.kinematic_data\n        # convert kinematics to old format to input to fortran\n        for i in np.arange(len(kinematics)):\n            if len(kinematics)==1:\n                old_filename = self.direc_no_ml+'infil/kin_data.dat'\n            else:\n                old_filename = self.direc_no_ml+'infil/kin_data_'+str(i)+'.dat'\n            kinematics[i].convert_to_old_format(old_filename)\n        # combine all kinematics into one file\n        if len(kinematics)>1:\n            gh_order = kinematics[0].get_highest_order_gh_coefficient()\n            if not all(kin.get_highest_order_gh_coefficient() == gh_order \\\n                       for kin in kinematics[1:]):\n                text = 'Multiple kinematics: all need to have the same ' \\\n                       'number of gh coefficients'\n                self.logger.error(text)\n                raise ValueError(text)\n            if not all(isinstance(kin,dyn_kin.GaussHermite) \\\n                       for kin in kinematics):\n                text = 'Multiple kinematics: all must be GaussHermite'\n                self.logger.error(text)\n                raise ValueError(text)\n            # make a dummy 'kins_combined' object ...\n            kins_combined = copy.deepcopy(kinematics[0])\n            # ...replace data attribute with stacked table of all kinematics\n            kins_combined.data = table.vstack([k.data for k in kinematics])\n            old_filename = self.direc_no_ml+'infil/kin_data_combined.dat'\n            kins_combined.convert_to_old_format(old_filename)\n\n    def create_fortran_input_nnls(self, path, ml):\n        \"\"\"create fortran input file nn.in\n\n        Parameters\n        ----------\n        path : string\n            model directory path\n        ml : float\n            the mass-scaling parameter ml\n\n        Returns\n        -------\n        None\n\n        \"\"\"\n        # when varying ml the LOSVD is scaled - no new orbits are calculated\n        # Therefore we need to know the ml that was used for the orbit library\n        infile=path+'infil/parameters_pot.in'\n        lines = [line.rstrip('\\n').split() for line in open(infile)]\n        ml_orblib=float((lines[-9])[0])\n\n        #-------------------\n        #write nn.in\n        #-------------------\n        n_kin = len(self.system.get_component_from_class( \\\n                    physys.TriaxialVisibleComponent).kinematic_data)\n\n        if n_kin==1:\n            kin_data_file='kin_data.dat'\n\n        else:\n            kin_data_file='kin_data_combined.dat'\n\n        text='infil/parameters_pot.in' +'\\n' + \\\n        str(self.settings['regularisation'])   + '                                  [ regularization strength, 0 = no regularization ]' +'\\n'  + \\\n        f'ml{ml:{self.sformat}}/nn\\n' + \\\n        'datfil/mass_qgrid.dat' +'\\n' + \\\n        'datfil/mass_aper.dat' +'\\n' + \\\n        str(self.settings['number_GH']) + '\t                           [ # of GH moments to constrain the model]' +'\\n' + \\\n        'infil/'+kin_data_file+'\\n' + \\\n        str(self.settings['GH_sys_err']) + '    [ systemic error of v, sigma, h3, h4... ]' + '\\n' + \\\n        str(self.settings['lum_intr_rel_err']) + '                               [ relative error for intrinsic luminosity ]' +'\\n' + \\\n        str(self.settings['sb_proj_rel_err']) + '                               [ relative error for projected SB ]' + '\\n' + \\\n        str(np.sqrt(ml/ml_orblib))  + '                                [ scale factor related to M/L, sqrt( (M/L)_k / (M/L)_ref ) ]' + '\\n' + \\\n        f'datfil/orblib_{ml}.dat' +'\\n' + \\\n        f'datfil/orblibbox_{ml}.dat' +'\\n' + \\\n        str(self.settings['nnls_solver']) + '                                  [ nnls solver ]'\n\n        nn_file= open(path+f'ml{ml:{self.sformat}}/nn.in',\"w\")\n        nn_file.write(text)\n        nn_file.close()\n\n    def solve(self, orblib=None):\n        \"\"\"Main method to solve NNLS problem.\n\n        Parameters\n        ----------\n        orblib : dyn.OrbitLibrary\n            This parameter is not used in this Legacy implementation (as all\n            orbit library information is read from files). It is included here\n            for consistency with later WeightSolver implementations\n\n        Returns\n        -------\n        tuple\n            (weights, chi2_all, chi2_kin) where:\n                -   weights : array, of orbit weights\n                -   chi2_all : float, sum of squared residuals for intrinsic\n                    masses, projected_masses and GH coefficients from h_1 to h_n\n                -   chi2_kin : float sum of squared residuals for GH\n                    coefficients h_1 to h_n\n\n        \"\"\"\n        self.logger.info(f\"Using WeightSolver: {__class__.__name__}\")\n        check1 = os.path.isfile(self.fname_nn_kinem)\n        check2 = os.path.isfile(self.fname_nn_nnls)\n        fname = self.directory_with_ml + 'nn_orbmat.out'\n        check3 = os.path.isfile(fname)\n        if not check1 or not check2 or not check3:\n            # set the current directory to the directory in which the models are computed\n            cur_dir = os.getcwd()\n            os.chdir(self.direc_no_ml)\n            cmdstr = self.write_executable_for_weight_solver(self.ml)\n            with open(cmdstr) as f:\n                for line in f:\n                    i = line.find('>>')\n                    if i >= 0:\n                        j = line.find('.log')\n                        logfile = line[i+3:j+4]\n                        break\n            self.logger.info(\"Fitting orbit library to the kinematic \" + \\\n                             f\"data: {logfile[:logfile.rindex('/')]}\")\n            p = subprocess.run('bash '+cmdstr,\n                               stdout=subprocess.PIPE,\n                               stderr=subprocess.STDOUT,\n                               shell=True)\n            log_file = f'Logfile: {self.direc_no_ml+logfile}'\n            if not p.stdout.decode(\"UTF-8\"):\n                self.logger.info(f'...done, NNLS problem solved -  {cmdstr} '\n                                 f'exit code {p.returncode}. {log_file}')\n            else:\n                text = f'{cmdstr} exit code {p.returncode}. ERROR. ' \\\n                       f'Message: {p.stdout.decode(\"UTF-8\")}{log_file}'\n                self.logger.error(text)\n                raise RuntimeError(text)\n            #set the current directory to the dynamite directory\n            os.chdir(cur_dir)\n        else:\n            self.logger.info(\"NNLS solution read from existing output\")\n        wts, chi2_tot, chi2_kin = self.get_weights_and_chi2_from_orbmat_file()\n        return wts, chi2_tot, chi2_kin\n\n    def write_executable_for_weight_solver(self, ml):\n        \"\"\"write executable bash script file\n\n        Parameters\n        ----------\n        ml : float\n            the mass-scaling parameter ml\n\n        Returns\n        -------\n        string\n            the name of the bash script file to execute\n\n        \"\"\"\n        nn = f'ml{ml:{self.sformat}}/nn'\n        cmdstr = f'cmd_nnls_{ml}'\n        txt_file = open(cmdstr, \"w\")\n        txt_file.write('#!/bin/bash' + '\\n')\n        txt_file.write('# if the gzipped orbit library exist unzip it' + '\\n')\n        txt_file.write(f'test -e datfil/orblib_{ml}.dat || bunzip2 -c  datfil/orblib.dat.bz2 > datfil/orblib_{ml}.dat' + '\\n')\n        txt_file.write(f'test -e datfil/orblibbox_{ml}.dat || bunzip2 -c  datfil/orblibbox.dat.bz2 > datfil/orblibbox_{ml}.dat' + '\\n')\n        if self.CRcut is True:\n            txt_file.write('test -e ' + str(nn) + '_kinem.out || ' +\n                           self.legacy_directory +\n                           f'/triaxnnls_CRcut < {nn}.in >> {nn}ls.log '\n                           '|| exit 1\\n')\n        else:\n            txt_file.write('test -e ' + str(nn) + '_kinem.out || ' +\n                           self.legacy_directory +\n                           f'/triaxnnls_noCRcut < {nn}.in >> {nn}ls.log '\n                           '|| exit 1\\n')\n        txt_file.write(f'rm datfil/orblib_{ml}.dat' + '\\n')\n        txt_file.write(f'rm datfil/orblibbox_{ml}.dat' + '\\n')\n        txt_file.close()\n        return cmdstr\n\n    def read_weights(self):\n        \"\"\"Read ``nn_orb.out`` to astropy table\n\n        this contains oribtal weights, orbit type, and other columns\n\n        Returns\n        -------\n        None\n            sets ``self.weights`` which is an astropy table containing\n            the orbital weights\n\n        \"\"\"\n        fname = self.directory_with_ml + 'nn_orb.out'\n        col_names = ['orb_idx',\n                     'E_idx',\n                     'I2_idx',\n                     'I3_idx',\n                     'totalnotregularizable', # see line 535 of orblib_f.f90\n                     'orb_type',\n                     'weight',\n                     'lcut'] # lines 1321-1322 of triaxnnls_CRcut.f90\n        # NOTE: column 'lcut' is not present if different \"triaxnnls\" file used\n        dtype = [int, int, int, int, int, int, np.float64, int]\n        weights = np.genfromtxt(fname,\n                                skip_header=1,\n                                names=col_names,\n                                dtype=dtype)\n        weights = table.Table(weights)\n        self.weights = weights\n\n    def read_nnls_orbmat_rhs_and_solution(self):\n        \"\"\"Read ``nn_orbmat.out``\n\n        This contains the matrix and right-hand-side for the NNLS problem, and\n        the solution\n\n        Returns\n        -------\n        tuple\n            (orbmat, rhs, solution)\n\n        \"\"\"\n        fname = self.directory_with_ml + 'nn_orbmat.out'\n        orbmat_shape = np.loadtxt(fname, max_rows=1, dtype=int)\n        orbmat_size = np.product(orbmat_shape)\n        tmp = np.loadtxt(fname, skiprows=1)\n        orbmat = tmp[0:orbmat_size]\n        orbmat = np.reshape(orbmat, orbmat_shape)\n        orbmat = orbmat.T\n        rhs = tmp[orbmat_size:orbmat_size+orbmat_shape[1]]\n        solution = tmp[orbmat_size+orbmat_shape[1]:]\n        return orbmat, rhs, solution\n\n    def get_weights_and_chi2_from_orbmat_file(self):\n        \"\"\"\n        Get weights and chi2 from ``nn_orbmat.out``\n\n        **Note**: Chi2 values returned differ from `read_chi2` method.\n        See that docstring for more.\n\n        Returns\n        -------\n        tuple\n            (weights, chi2_all, chi2_gh), where:\n\n                -   weights : array of orbit weights\n                -   chi2_all : sum of squared residuals for intrinsic masses,\n                    projected_masses and GH coefficients h_1 to h_n\n                -   chi2_kin : sum of squared residuals for GH coefficients h_1 to h_n\n\n        \"\"\"\n        A, b, weights = self.read_nnls_orbmat_rhs_and_solution()\n        chi2_vector = (np.dot(A, weights) - b)**2.\n        chi2_tot = np.sum(chi2_vector)\n        stars = \\\n          self.system.get_component_from_class(physys.TriaxialVisibleComponent)\n        mge = stars.mge_lum\n        intrinsic_masses = mge.get_intrinsic_masses_from_file(self.direc_no_ml)\n        projected_masses = mge.get_projected_masses_from_file(self.direc_no_ml)\n        n_intrinsic = np.product(intrinsic_masses.shape)\n        n_apertures = len(projected_masses)\n        chi2_kin = np.sum(chi2_vector[1+n_intrinsic+n_apertures:])\n        return weights, chi2_tot, chi2_kin\n\n    def read_chi2(self):\n        \"\"\"Read chi2 values from `nn_kinem.out`\n\n        Taken from old `schwpy` code, lines 181-212 of schw_domoditer.py\n\n        **Note**:\n        This is a legacy method for reading legacy output and it not used by\n        default. Instead we use ``self.get_chi2_from_orbmat`` get chi2 values.\n        The chi2 value definitions of this method are NOT the same chi2 values\n        given by ``self.get_chi2_from_orbmat``. They differ in\n        (i) including intrinsic/projected mass constraints, and (ii) using\n        h1/h2 vs V/sigma, and (iii) if CRcut==True, whether the 'cut' orbits\n        - with artificially large h1 - are included (here they aren't)\n\n        Returns\n        -------\n        tuple\n            (chi2, kinchi2) where:\n                -   chi2 = sum of sq. residuals of observed GH coefficients h_1\n                    to h_N\n                -   kinchi2 = sum of sq. residuals of V, sigma, and GH\n                    coefficients from h_3 to h_N\n\n        \"\"\"\n        # read amount of observables and kinematic moments\n        fname = self.fname_nn_kinem\n        a = self.__read_file_element(fname, [1, 1], [1, 2])\n        ngh = np.int64(a[1])  # number of 'observables'\n        nobs = np.int64(a[1])\n        nvel = np.int64(a[0])\n        ncon = np.int64(a[0])\n        rows = 3 + np.arange(nobs)  # rows 1- 9\n        cols = 3 + np.zeros(nobs, dtype=int)  # skip over text\n        fname = self.fname_nn_nnls\n        chi2vec = self.__read_file_element(fname, rows, cols)\n        chi2vec = np.double(chi2vec)\n        chi2 = sum(chi2vec)\n        fname = self.fname_nn_kinem\n        ka = np.genfromtxt(fname, skip_header=1)\n        k = np.arange(ngh) * 3 + 3\n        # k = is array of column indices, for [V, sigma, h3, ..., h_ngh]\n        #                       observed   modelled        error\n        kinchi2 = sum(sum(pow(((ka[:, k] - ka[:, k + 1]) / ka[:, k + 2]), 2.0)))\n        return chi2, kinchi2\n\n    def __read_file_element(self, infile, rows, cols):\n        \"\"\"Read fields in a tabular data according to the their row/column.\n\n        Taken from schwpy schw_misc\n\n        Parameters\n        ----------\n        infile : string\n            input file\n        rows : array of ints\n            row array of locations indexed starts from 1\n        cols : array of ints\n            column array of locations indexed starts from 1\n\n        Returns\n        -------\n        array read from given locations in file\n\n        \"\"\"\n        lines = [line.rstrip('\\n').split() for line in open(infile)]\n        output=[]\n        for i in range(0, len(rows)):\n            output.append(lines[rows[i] - 1][cols[i] - 1])\n        return output\n\n\nclass NNLS(WeightSolver):\n    \"\"\"Python implementations of NNLS weight solving\n\n    Uses either scipy.optimize.nnls or cvxopt as backends. This constructs the\n    NNLS matrix and rhs, solves, and saves the result.\n\n    Parameters\n    ----------\n    config : a ``dyn.config_reader.Configuration`` object\n    directory_with_ml : string\n        model directory with the ml extension\n    CRcut : Bool, default False\n        whether to use the `CRcut` solution for the counter-rotating orbit\n        problem. See Zhu et al. 2018 for more.\n    nnls_solver : string\n        either ``scipy`` or ``cvxopt``\n\n    \"\"\"\n    def __init__(self,\n                 config,\n                 directory_with_ml,\n                 CRcut=False,\n                 nnls_solver=None):\n        self.logger = logging.getLogger(f'{__name__}.{__class__.__name__}')\n        self.system = config.system\n        self.settings = config.settings.weight_solver_settings\n        self.direc_with_ml = directory_with_ml\n        self.direc_no_ml = directory_with_ml[:-7]\n        if nnls_solver is None:\n            nnls_solver = self.settings['nnls_solver']\n        assert nnls_solver in ['scipy', 'cvxopt'], 'Unknown nnls_solver'\n        self.nnls_solver = nnls_solver\n        if 'CRcut' in self.settings.keys():\n            CRcut = self.settings['CRcut']\n        self.CRcut = CRcut\n        self.get_observed_mass_constraints()\n\n    def get_observed_mass_constraints(self):\n        \"\"\"Get aperture+intrinsic mass constraits from MGE\n\n        Returns\n        -------\n        None\n            sets attributes:\n\n                - ``self.intrinsic_masses``\n                - ``self.intrinsic_mass_error``\n                - ``self.projected_masses``\n                - ``self.projected_mass_error``\n                -   constraint counts ``self.n_intrinsic``, ``self.n_apertures``\n                    and ``self.n_mass_constraints``\n\n        \"\"\"\n        stars = \\\n          self.system.get_component_from_class(physys.TriaxialVisibleComponent)\n        mge = stars.mge_lum\n        # intrinsic mass\n        intrinsic_masses = mge.get_intrinsic_masses_from_file(self.direc_no_ml)\n        self.intrinsic_masses = intrinsic_masses\n        self.intrinsic_mass_error = self.settings['lum_intr_rel_err']\n        # projected\n        projected_masses = mge.get_projected_masses_from_file(self.direc_no_ml)\n        self.projected_masses = projected_masses\n        self.projected_mass_error = self.settings['sb_proj_rel_err']\n        # total mass constraint\n        self.total_mass = np.sum(intrinsic_masses)\n        self.total_mass_error = np.min([self.intrinsic_mass_error/10.,\n                                        np.abs(1. - self.total_mass)])\n        # enumerate the mass constriants\n        n_intrinsic = np.product(self.intrinsic_masses.shape)\n        n_apertures = len(self.projected_masses)\n        self.n_intrinsic = n_intrinsic\n        self.n_apertures = n_apertures\n        # mass constraints = total mass (1) + intrinsic mass + aperture mass\n        self.n_mass_constraints = 1 + n_intrinsic + n_apertures\n\n    def construct_nnls_matrix_and_rhs(self, orblib):\n        \"\"\"construct nnls matrix_and rhs\n\n        Parameters\n        ----------\n        orblib : ``dyn.orblib.OrbitLibrary``\n            an orbit library\n\n        Returns\n        -------\n        tuple\n            (orbmat, rhs)\n\n        \"\"\"\n        # construct vector of observed constraits (con), errors (econ) and\n        # matrix or orbit proprtites (orbmat)\n        con = np.zeros(self.n_mass_constraints)\n        econ = np.zeros(self.n_mass_constraints)\n        orbmat = np.zeros((self.n_mass_constraints, orblib.n_orbs))\n        # total mass\n        con[0] = self.total_mass\n        econ[0] = self.total_mass_error\n        if econ[0]<=0.0:\n            econ[0] = con[0]*0.01\n        orbmat[0,:] = 1.\n        # intrinsic mass\n        idx = slice(1,1+self.n_intrinsic)\n        con[idx] = np.ravel(self.intrinsic_masses)\n        error = self.intrinsic_masses * self.intrinsic_mass_error\n        error = np.abs(np.ravel(error))\n        error[np.where(error<=0.)] = 1.0e-16\n        econ[idx] = np.abs(np.ravel(error))\n        orb_int_masses = orblib.intrinsic_masses\n        orb_int_masses = np.reshape(orb_int_masses, (orblib.n_orbs, -1))\n        orbmat[idx,:] = orb_int_masses.T\n        # projected mass\n        idx = slice(1+self.n_intrinsic, 1+self.n_intrinsic+self.n_apertures)\n        con[idx] = self.projected_masses\n        econ[idx] = np.abs(self.projected_masses * self.projected_mass_error)\n        orbmat[idx,:] = np.hstack(orblib.projected_masses).T\n        # add kinematics to con, econ, orbmat\n        triax_component = physys.TriaxialVisibleComponent\n        stars = self.system.get_component_from_class(triax_component)\n        kins_and_orb_losvds = zip(stars.kinematic_data, orblib.losvd_histograms)\n        idx_ap_start = 0\n        for (kins, orb_losvd) in kins_and_orb_losvds:\n            # pick out the projected masses for this kinematic set\n            n_ap = len(kins.data)\n            idx_ap_end = idx_ap_start + n_ap\n            prj_mass_i = self.projected_masses[idx_ap_start:idx_ap_end]\n            idx_ap_start += n_ap\n            # scale observed kinematics and errors by projected masses\n            tmp = kins.get_observed_values_and_uncertainties(self.settings)\n            obs_kins, obs_kins_err = tmp\n            obs_kins = (obs_kins.T * prj_mass_i).T\n            obs_kins_err = (obs_kins_err.T * prj_mass_i).T\n            # set the first and last point in the velocity histograms to zero\n            # to mimic what is done in `triaxnnnls_CRcut.f90`\n            orb_losvd.y[:,0,:] = 0.\n            orb_losvd.y[:,-1,:] = 0.\n            # transform orblib to same parameterisation as observed kinematics\n            orb_kins = kins.transform_orblib_to_observables(orb_losvd,\n                                                            self.settings)\n            if self.CRcut:\n                # note: this only has an effect if type(kins) is GaussHermite\n                orb_kins = self.apply_CR_cut(kins, orb_losvd, orb_kins)\n            # append constraints/errors/orbits to con/econ/orbmat\n            obs_kins = np.ravel(obs_kins)\n            con = np.concatenate((con, obs_kins))\n            obs_kins_err = np.ravel(obs_kins_err)\n            econ = np.concatenate((econ, obs_kins_err))\n            orb_kins = np.reshape(orb_kins, (orblib.n_orbs, -1))\n            orbmat = np.vstack((orbmat, orb_kins.T))\n        # divide constraint vector and matrix by errors\n        rhs = con/econ\n        orbmat = (orbmat.T/econ).T\n        return orbmat, rhs\n\n    def apply_CR_cut(self, kins, orb_losvd, orb_gh):\n        \"\"\"apply `CRcut`\n\n        to solve the `counter rotating orbit problem`. This cuts orbits which\n        have :math:`|V - V_\\mathrm{obs}|> 3\\sigma_\\mathrm{obs}`. See\n        Zhu+2018 MNRAS 2018 473 3000 for details\n\n        Parameters\n        ----------\n        kins : a ``dyn.kinematics.Kinematic`` object\n        orb_losvd : ``dyn.kinematics.Histogram``\n            historgram of orblib losvds\n        orb_gh : array\n            array of input gh expansion coefficients, before the CRcut\n\n        Returns\n        -------\n        array\n            array of input gh expansion coefficients, after the CRcut\n\n        \"\"\"\n        if type(kins) is not dyn_kin.GaussHermite:\n            return orb_gh\n        orb_mu_v = orb_losvd.get_mean()\n        obs_mu_v = kins.data['v']\n        obs_sig_v = kins.data['sigma']\n        delta_v = np.abs(orb_mu_v - obs_mu_v)\n        condition1 = (np.abs(obs_mu_v)/obs_sig_v > 1.5)\n        condition2 = (delta_v/obs_sig_v > 3.0)\n        condition3 = (obs_mu_v*orb_mu_v < 0)\n        idx_cut = np.where(condition1 & condition2 & condition3)\n        cut = np.zeros_like(orb_mu_v, dtype=bool)\n        cut[idx_cut] = True\n        naperture_cut = np.sum(cut, 1)\n        # orbit 'j' is \"bad\" in naperture_cut[j] apertures\n        # if an orbit is bad in 0 or 1 apertures, then we ignore this\n        cut[naperture_cut<1,:] = False\n        # to cut an orbit, replace it's h1 by 3.0/dvhist(i)\n        idx_cut = np.where(cut)\n        dvhist = kins.hist_width/kins.hist_bins\n        dvhist = np.max(dvhist)\n        orb_gh[idx_cut[0], idx_cut[1], 0] = 3./dvhist\n        return orb_gh\n\n    def solve(self, orblib):\n        \"\"\"Solve for orbit weights\n\n        **Note:** the returned chi2 values are not the same as\n        ``LegacyWeightSolver.read_chi2`` - see the docstring for more info\n\n        Parameters\n        ----------\n        orblib : dyn.OrbitLibrary\n            must have attributes losvd_histograms, intrinsic_masses, and\n            projected_masses\n\n        Returns\n        -------\n        tuple\n            (weights, chi2_all, chi2_kin) where:\n                -   weights : array, of orbit weights\n                -   chi2_all : float, sum of squared residuals for intrinsic\n                    masses, projected_masses and GH coefficients from h_1 to h_n\n                -   chi2_kin : float sum of squared residuals for GH\n                    coefficients h_1 to h_n\n\n        \"\"\"\n        self.logger.info(f\"Using WeightSolver: {__class__.__name__}/\"\n                         f\"{self.nnls_solver}\")\n        weight_file = f'{self.direc_with_ml}orbit_weights.ecsv'\n        if os.path.isfile(weight_file):\n            self.logger.info(\"NNLS solution read from existing output\")\n            result = ascii.read(weight_file, format='ecsv')\n            weights = result['weights']\n            chi2_tot = result.meta['chi2_tot']\n            chi2_kin = result.meta['chi2_kin']\n        else:\n            A, b = self.construct_nnls_matrix_and_rhs(orblib)\n            if self.nnls_solver=='scipy':\n                solution = optimize.nnls(A, b)\n                weights = solution[0]\n            elif self.nnls_solver=='cvxopt':\n                P = np.dot(A.T, A)\n                q = -1.*np.dot(A.T, b)\n                solver = CvxoptNonNegSolver(P, q)\n                weights = solver.beta\n            else:\n                text = 'Unknown nnls_solver'\n                self.logger.error(text)\n                raise ValueError(text)\n            np.savetxt(weight_file, weights)\n            self.logger.info(\"NNLS problem solved\")\n            # calculate chi2s\n            chi2_vector = (np.dot(A, weights) - b)**2.\n            chi2_tot = np.sum(chi2_vector)\n            chi2_kin = np.sum(chi2_vector[self.n_mass_constraints:])\n            # save the output\n            results = table.Table()\n            results['weights'] = weights\n            # add chi2 to meta data\n            meta = {'chi2_tot':chi2_tot, 'chi2_kin':chi2_kin}\n            results = table.Table(results, meta=meta)\n            results.write(weight_file, format='ascii.ecsv', overwrite=True)\n        return weights, chi2_tot, chi2_kin\n\n\nclass CvxoptNonNegSolver():\n    \"\"\"Solver for NNLS problem using CVXOPT\n\n    Solves the QP problem:\n        argmin (1/2 beta^T P beta + q beta T)\n        subject to (component-wise) beta > 0\n\n    Parameters\n    ----------\n    P : array (p, p)\n        quadratic part of objective function\n    q : array (p,)\n        linear part of objective function\n\n    Attributes\n    ----------\n    success : bool\n        whether solver was successful\n    beta : array (p,)\n        solution\n\n    \"\"\"\n\n    def __init__(self, P=None, q=None):\n        p = P.shape[0]\n        P = cvxopt.matrix(P)\n        q = cvxopt.matrix(q)\n        G = cvxopt.matrix(-np.identity(p))\n        h = cvxopt.matrix(np.zeros(p))\n        sol = cvxopt.solvers.qp(P, q, G, h)\n        self.success = sol['status']=='optimal'\n        self.beta = np.squeeze(np.array(sol['x']))\n\n\n\n\n\n# end\n", "meta": {"hexsha": "e73ae971574e444a9a132dff221e5255ea10f310", "size": 28661, "ext": "py", "lang": "Python", "max_stars_repo_path": "dynamite/weight_solvers.py", "max_stars_repo_name": "dynamics-of-stellar-systems/dynamite_release", "max_stars_repo_head_hexsha": "a921d8a1bde98f48daeea78213fb17b3edb223bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-10-14T12:22:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T15:32:59.000Z", "max_issues_repo_path": "dynamite/weight_solvers.py", "max_issues_repo_name": "dynamics-of-stellar-systems/dynamite_release", "max_issues_repo_head_hexsha": "a921d8a1bde98f48daeea78213fb17b3edb223bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dynamite/weight_solvers.py", "max_forks_repo_name": "dynamics-of-stellar-systems/dynamite_release", "max_forks_repo_head_hexsha": "a921d8a1bde98f48daeea78213fb17b3edb223bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-11-04T04:36:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-01T01:07:38.000Z", "avg_line_length": 39.4779614325, "max_line_length": 146, "alphanum_fraction": 0.574927602, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 7034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.28457601635158564, "lm_q1q2_score": 0.15227617917455438}}
{"text": "#  This code is a part of XMM: Generate and Analyse (XGA), a module designed for the XMM Cluster Survey (XCS).\n#  Last modified by David J Turner (david.turner@sussex.ac.uk) 10/06/2021, 11:19. Copyright (c) David J Turner\n\nimport warnings\nfrom typing import List, Union\n\nimport astropy.units as u\nfrom astropy.units import Quantity\n\nfrom .common import _check_inputs, _write_xspec_script, _pregen_spectra\nfrom ..run import xspec_call\nfrom ... import NUM_CORES\nfrom ...exceptions import NoProductAvailableError, ModelNotAssociatedError\nfrom ...products import Spectrum\nfrom ...samples.base import BaseSample\nfrom ...sources import BaseSource\n\n\n@xspec_call\ndef single_temp_apec(sources: Union[BaseSource, BaseSample], outer_radius: Union[str, Quantity],\n                     inner_radius: Union[str, Quantity] = Quantity(0, 'arcsec'),\n                     start_temp: Quantity = Quantity(3.0, \"keV\"), start_met: float = 0.3,\n                     lum_en: Quantity = Quantity([[0.5, 2.0], [0.01, 100.0]], \"keV\"),\n                     freeze_nh: bool = True, freeze_met: bool = True, lo_en: Quantity = Quantity(0.3, \"keV\"),\n                     hi_en: Quantity = Quantity(7.9, \"keV\"), par_fit_stat: float = 1., lum_conf: float = 68.,\n                     abund_table: str = \"angr\", fit_method: str = \"leven\", group_spec: bool = True,\n                     min_counts: int = 5, min_sn: float = None, over_sample: float = None, one_rmf: bool = True,\n                     num_cores: int = NUM_CORES, spectrum_checking: bool = True, timeout: Quantity = Quantity(1, 'hr')):\n    \"\"\"\n    This is a convenience function for fitting an absorbed single temperature apec model(constant*tbabs*apec) to an\n    object. It would be possible to do the exact same fit using the custom_model function, but as it will\n    be a very common fit a dedicated function is in order. If there are no existing spectra with the passed\n    settings, then they will be generated automatically.\n\n    If the spectrum checking step of the XSPEC fit is enabled (using the boolean flag spectrum_checking), then\n    each individual spectrum available for a given source will be fitted, and if the measured temperature is less\n    than or equal to 0.01keV, or greater than 20keV, or the temperature uncertainty is greater than 15keV, then\n    that spectrum will be rejected and not included in the final fit. Spectrum checking also involves rejecting any\n    spectra with fewer than 10 noticed channels.\n\n    :param List[BaseSource] sources: A single source object, or a sample of sources.\n    :param str/Quantity outer_radius: The name or value of the outer radius of the region that the\n        desired spectrum covers (for instance 'r200' would be acceptable for a GalaxyCluster,\n        or Quantity(1000, 'kpc')). If 'region' is chosen (to use the regions in region files), then any\n        inner radius will be ignored. If you are fitting for multiple sources then you can also pass a\n        Quantity with one entry per source.\n    :param str/Quantity inner_radius: The name or value of the outer radius of the region that the\n        desired spectrum covers (for instance 'r200' would be acceptable for a GalaxyCluster,\n        or Quantity(1000, 'kpc')). If 'region' is chosen (to use the regions in region files), then any\n        inner radius will be ignored. By default this is zero arcseconds, resulting in a circular spectrum. If\n        you are fitting for multiple sources then you can also pass a Quantity with one entry per source.\n    :param Quantity start_temp: The initial temperature for the fit.\n    :param start_met: The initial metallicity for the fit (in ZSun).\n    :param Quantity lum_en: Energy bands in which to measure luminosity.\n    :param bool freeze_nh: Whether the hydrogen column density should be frozen.\n    :param bool freeze_met: Whether the metallicity parameter in the fit should be frozen.\n    :param Quantity lo_en: The lower energy limit for the data to be fitted.\n    :param Quantity hi_en: The upper energy limit for the data to be fitted.\n    :param float par_fit_stat: The delta fit statistic for the XSPEC 'error' command, default is 1.0 which should be\n        equivelant to 1σ errors if I've understood (https://heasarc.gsfc.nasa.gov/xanadu/xspec/manual/XSerror.html)\n        correctly.\n    :param float lum_conf: The confidence level for XSPEC luminosity measurements.\n    :param str abund_table: The abundance table to use for the fit.\n    :param str fit_method: The XSPEC fit method to use.\n    :param bool group_spec: A boolean flag that sets whether generated spectra are grouped or not.\n    :param float min_counts: If generating a grouped spectrum, this is the minimum number of counts per channel.\n        To disable minimum counts set this parameter to None.\n    :param float min_sn: If generating a grouped spectrum, this is the minimum signal to noise in each channel.\n        To disable minimum signal to noise set this parameter to None.\n    :param float over_sample: The minimum energy resolution for each group, set to None to disable. e.g. if\n        over_sample=3 then the minimum width of a group is 1/3 of the resolution FWHM at that energy.\n    :param bool one_rmf: This flag tells the method whether it should only generate one RMF for a particular\n        ObsID-instrument combination - this is much faster in some circumstances, however the RMF does depend\n        slightly on position on the detector.\n    :param int num_cores: The number of cores to use (if running locally), default is set to 90% of available.\n    :param bool spectrum_checking: Should the spectrum checking step of the XSPEC fit (where each spectrum is fit\n        individually and tested to see whether it will contribute to the simultaneous fit) be activated?\n    :param Quantity timeout: The amount of time each individual fit is allowed to run for, the default is one hour.\n        Please note that this is not a timeout for the entire fitting process, but a timeout to individual source\n        fits.\n    \"\"\"\n    sources, inn_rad_vals, out_rad_vals = _pregen_spectra(sources, outer_radius, inner_radius, group_spec, min_counts,\n                                                          min_sn, over_sample, one_rmf, num_cores)\n    sources = _check_inputs(sources, lum_en, lo_en, hi_en, fit_method, abund_table, timeout)\n\n    # This function is for a set model, absorbed apec, so I can hard code all of this stuff.\n    # These will be inserted into the general XSPEC script template, so lists of parameters need to be in the form\n    #  of TCL lists.\n    model = \"constant*tbabs*apec\"\n    par_names = \"{factor nH kT Abundanc Redshift norm}\"\n    lum_low_lims = \"{\" + \" \".join(lum_en[:, 0].to(\"keV\").value.astype(str)) + \"}\"\n    lum_upp_lims = \"{\" + \" \".join(lum_en[:, 1].to(\"keV\").value.astype(str)) + \"}\"\n\n    script_paths = []\n    outfile_paths = []\n    src_inds = []\n    # This function supports passing multiple sources, so we have to setup a script for all of them.\n    for src_ind, source in enumerate(sources):\n        # Find matching spectrum objects associated with the current source\n        spec_objs = source.get_spectra(out_rad_vals[src_ind], inner_radius=inn_rad_vals[src_ind],\n                                       group_spec=group_spec, min_counts=min_counts, min_sn=min_sn,\n                                       over_sample=over_sample)\n        # This is because many other parts of this function assume that spec_objs is iterable, and in the case of\n        #  a cluster with only a single valid instrument for a single valid observation this may not be the case\n        if isinstance(spec_objs, Spectrum):\n            spec_objs = [spec_objs]\n\n        # Obviously we can't do a fit if there are no spectra, so throw an error if that's the case\n        if len(spec_objs) == 0:\n            raise NoProductAvailableError(\"There are no matching spectra for {s} object, you \"\n                                          \"need to generate them first!\".format(s=source.name))\n\n        # Turn spectra paths into TCL style list for substitution into template\n        specs = \"{\" + \" \".join([spec.path for spec in spec_objs]) + \"}\"\n        # For this model, we have to know the redshift of the source.\n        if source.redshift is None:\n            raise ValueError(\"You cannot supply a source without a redshift to this model.\")\n\n        # Whatever start temperature is passed gets converted to keV, this will be put in the template\n        t = start_temp.to(\"keV\", equivalencies=u.temperature_energy()).value\n        # Another TCL list, this time of the parameter start values for this model.\n        par_values = \"{{{0} {1} {2} {3} {4} {5}}}\".format(1., source.nH.to(\"10^22 cm^-2\").value, t, start_met,\n                                                          source.redshift, 1.)\n\n        # Set up the TCL list that defines which parameters are frozen, dependant on user input\n        if freeze_nh and freeze_met:\n            freezing = \"{F T F T T F}\"\n        elif not freeze_nh and freeze_met:\n            freezing = \"{F F F T T F}\"\n        elif freeze_nh and not freeze_met:\n            freezing = \"{F T F F T F}\"\n        elif not freeze_nh and not freeze_met:\n            freezing = \"{F F F F T F}\"\n\n        # Set up the TCL list that defines which parameters are linked across different spectra, only the\n        #  multiplicative constant that accounts for variation in normalisation over different observations is not\n        #  linked\n        linking = \"{F T T T T T}\"\n\n        # If the user wants the spectrum cleaning step to be run, then we have to setup some acceptable\n        #  limits. For this function they will be hardcoded, for simplicities sake, and we're only going to\n        #  check the temperature, as its the main thing we're fitting for with constant*tbabs*apec\n        if spectrum_checking:\n            check_list = \"{kT}\"\n            check_lo_lims = \"{0.01}\"\n            check_hi_lims = \"{20}\"\n            check_err_lims = \"{15}\"\n        else:\n            check_list = \"{}\"\n            check_lo_lims = \"{}\"\n            check_hi_lims = \"{}\"\n            check_err_lims = \"{}\"\n\n        out_file, script_file = _write_xspec_script(source, spec_objs[0].storage_key, model, abund_table, fit_method,\n                                                    specs, lo_en, hi_en, par_names, par_values, linking, freezing,\n                                                    par_fit_stat, lum_low_lims, lum_upp_lims, lum_conf, source.redshift,\n                                                    spectrum_checking, check_list, check_lo_lims, check_hi_lims,\n                                                    check_err_lims, True)\n\n        # If the fit has already been performed we do not wish to perform it again\n        try:\n            res = source.get_results(out_rad_vals[src_ind], model, inn_rad_vals[src_ind], 'kT', group_spec, min_counts,\n                                     min_sn, over_sample)\n        except ModelNotAssociatedError:\n            script_paths.append(script_file)\n            outfile_paths.append(out_file)\n            src_inds.append(src_ind)\n\n    run_type = \"fit\"\n    return script_paths, outfile_paths, num_cores, run_type, src_inds, None, timeout\n\n\n@xspec_call\ndef power_law(sources: Union[BaseSource, BaseSample], outer_radius: Union[str, Quantity],\n              inner_radius: Union[str, Quantity] = Quantity(0, 'arcsec'), redshifted: bool = False,\n              lum_en: Quantity = Quantity([[0.5, 2.0], [0.01, 100.0]], \"keV\"), start_pho_index: float = 1.,\n              lo_en: Quantity = Quantity(0.3, \"keV\"), hi_en: Quantity = Quantity(7.9, \"keV\"),\n              freeze_nh: bool = True, par_fit_stat: float = 1., lum_conf: float = 68., abund_table: str = \"angr\",\n              fit_method: str = \"leven\", group_spec: bool = True, min_counts: int = 5, min_sn: float = None,\n              over_sample: float = None, one_rmf: bool = True, num_cores: int = NUM_CORES,\n              timeout: Quantity = Quantity(1, 'hr')):\n    \"\"\"\n    This is a convenience function for fitting a tbabs absorbed powerlaw (or zpowerlw if redshifted\n    is selected) to source spectra, with a multiplicative constant included to deal with different spectrum\n    normalisations (constant*tbabs*powerlaw, or constant*tbabs*zpowerlw).\n\n    :param List[BaseSource] sources: A single source object, or a sample of sources.\n    :param str/Quantity outer_radius: The name or value of the outer radius of the region that the\n        desired spectrum covers (for instance 'r200' would be acceptable for a GalaxyCluster,\n        or Quantity(1000, 'kpc')). If 'region' is chosen (to use the regions in region files), then any\n        inner radius will be ignored. If you are fitting for multiple sources then you can also pass a\n        Quantity with one entry per source.\n    :param str/Quantity inner_radius: The name or value of the outer radius of the region that the\n        desired spectrum covers (for instance 'r200' would be acceptable for a GalaxyCluster,\n        or Quantity(1000, 'kpc')). If 'region' is chosen (to use the regions in region files), then any\n        inner radius will be ignored. By default this is zero arcseconds, resulting in a circular spectrum. If\n        you are fitting for multiple sources then you can also pass a Quantity with one entry per source.\n    :param bool redshifted: Whether the powerlaw that includes redshift (zpowerlw) should be used.\n    :param Quantity lum_en: Energy bands in which to measure luminosity.\n    :param float start_pho_index: The starting value for the photon index of the powerlaw.\n    :param Quantity lo_en: The lower energy limit for the data to be fitted.\n    :param Quantity hi_en: The upper energy limit for the data to be fitted.\n    :param bool freeze_nh: Whether the hydrogen column density should be frozen.    :param start_pho_index:\n    :param float par_fit_stat: The delta fit statistic for the XSPEC 'error' command, default is 1.0 which\n        should be equivelant to 1sigma errors if I've understood (https://heasarc.gsfc.nasa.gov/xanadu/xspec\n        /manual/XSerror.html) correctly.\n    :param float lum_conf: The confidence level for XSPEC luminosity measurements.\n    :param str abund_table: The abundance table to use for the fit.\n    :param str fit_method: The XSPEC fit method to use.\n    :param bool group_spec: A boolean flag that sets whether generated spectra are grouped or not.\n    :param float min_counts: If generating a grouped spectrum, this is the minimum number of counts per channel.\n        To disable minimum counts set this parameter to None.\n    :param float min_sn: If generating a grouped spectrum, this is the minimum signal to noise in each channel.\n        To disable minimum signal to noise set this parameter to None.\n    :param float over_sample: The minimum energy resolution for each group, set to None to disable. e.g. if\n        over_sample=3 then the minimum width of a group is 1/3 of the resolution FWHM at that energy.\n    :param bool one_rmf: This flag tells the method whether it should only generate one RMF for a particular\n        ObsID-instrument combination - this is much faster in some circumstances, however the RMF does depend\n        slightly on position on the detector.\n    :param int num_cores: The number of cores to use (if running locally), default is set to 90% of available.\n    :param Quantity timeout: The amount of time each individual fit is allowed to run for, the default is one hour.\n        Please note that this is not a timeout for the entire fitting process, but a timeout to individual source\n        fits.\n    \"\"\"\n    sources, inn_rad_vals, out_rad_vals = _pregen_spectra(sources, outer_radius, inner_radius, group_spec, min_counts,\n                                                          min_sn, over_sample, one_rmf, num_cores)\n    sources = _check_inputs(sources, lum_en, lo_en, hi_en, fit_method, abund_table, timeout)\n\n    # This function is for a set model, either absorbed powerlaw or absorbed zpowerlw\n    # These will be inserted into the general XSPEC script template, so lists of parameters need to be in the form\n    #  of TCL lists.\n    lum_low_lims = \"{\" + \" \".join(lum_en[:, 0].to(\"keV\").value.astype(str)) + \"}\"\n    lum_upp_lims = \"{\" + \" \".join(lum_en[:, 1].to(\"keV\").value.astype(str)) + \"}\"\n    if redshifted:\n        model = \"constant*tbabs*zpowerlw\"\n        par_names = \"{factor nH PhoIndex Redshift norm}\"\n    else:\n        model = \"constant*tbabs*powerlaw\"\n        par_names = \"{factor nH PhoIndex norm}\"\n\n    script_paths = []\n    outfile_paths = []\n    src_inds = []\n    for src_ind, source in enumerate(sources):\n        spec_objs = source.get_spectra(out_rad_vals[src_ind], inner_radius=inn_rad_vals[src_ind], group_spec=group_spec,\n                                       min_counts=min_counts, min_sn=min_sn, over_sample=over_sample)\n\n        # This is because many other parts of this function assume that spec_objs is iterable, and in the case of\n        #  a source with only a single valid instrument for a single valid observation this may not be the case\n        if isinstance(spec_objs, Spectrum):\n            spec_objs = [spec_objs]\n\n        if len(spec_objs) == 0:\n            raise NoProductAvailableError(\"There are no matching spectra for {s}, you \"\n                                          \"need to generate them first!\".format(s=source.name))\n\n        # Turn spectra paths into TCL style list for substitution into template\n        specs = \"{\" + \" \".join([spec.path for spec in spec_objs]) + \"}\"\n        # For this model, we have to know the redshift of the source.\n        if redshifted and source.redshift is None:\n            raise ValueError(\"You cannot supply a source without a redshift if you have elected to fit zpowerlw.\")\n        elif redshifted and source.redshift is not None:\n            par_values = \"{{{0} {1} {2} {3} {4}}}\".format(1., source.nH.to(\"10^22 cm^-2\").value, start_pho_index,\n                                                          source.redshift, 1.)\n        else:\n            par_values = \"{{{0} {1} {2} {3}}}\".format(1., source.nH.to(\"10^22 cm^-2\").value, start_pho_index, 1.)\n\n        # Set up the TCL list that defines which parameters are frozen, dependant on user input\n        if redshifted and freeze_nh:\n            freezing = \"{F T F T F}\"\n        elif not redshifted and freeze_nh:\n            freezing = \"{F T F F}\"\n        elif redshifted and not freeze_nh:\n            freezing = \"{F F F T F}\"\n        elif not redshifted and not freeze_nh:\n            freezing = \"{F F F F}\"\n\n        # Set up the TCL list that defines which parameters are linked across different spectra,\n        #  dependant on user input\n        if redshifted:\n            linking = \"{F T T T T}\"\n        else:\n            linking = \"{F T T T}\"\n\n        # If the powerlaw with redshift has been chosen, then we use the redshift attached to the source object\n        #  If not we just pass a filler redshift and the luminosities are invalid\n        if redshifted or (not redshifted and source.redshift is not None):\n            z = source.redshift\n        else:\n            z = 1\n            warnings.warn(\"{s} has no redshift information associated, so luminosities from this fit\"\n                          \" will be invalid, as redshift has been set to one.\".format(s=source.name))\n\n        out_file, script_file = _write_xspec_script(source, spec_objs[0].storage_key, model, abund_table, fit_method,\n                                                    specs, lo_en, hi_en, par_names, par_values, linking, freezing,\n                                                    par_fit_stat, lum_low_lims, lum_upp_lims, lum_conf, z, False, \"{}\",\n                                                    \"{}\", \"{}\", \"{}\", True)\n\n        # If the fit has already been performed we do not wish to perform it again\n        try:\n            res = source.get_results(out_rad_vals[src_ind], model, inn_rad_vals[src_ind], None, group_spec, min_counts,\n                                     min_sn, over_sample)\n        except ModelNotAssociatedError:\n            script_paths.append(script_file)\n            outfile_paths.append(out_file)\n            src_inds.append(src_ind)\n\n    run_type = \"fit\"\n    return script_paths, outfile_paths, num_cores, run_type, src_inds, None, timeout\n\n\n", "meta": {"hexsha": "ac3ca8edcd3bce4ea67ee2ae119098e561229691", "size": 20311, "ext": "py", "lang": "Python", "max_stars_repo_path": "xga/xspec/fit/general.py", "max_stars_repo_name": "DavidT3/XGA", "max_stars_repo_head_hexsha": "cde51c3f29f98b5f1e981fb6d327c04072b0ba38", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2020-05-16T09:45:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T14:41:46.000Z", "max_issues_repo_path": "xga/xspec/fit/general.py", "max_issues_repo_name": "DavidT3/XGA", "max_issues_repo_head_hexsha": "cde51c3f29f98b5f1e981fb6d327c04072b0ba38", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 684, "max_issues_repo_issues_event_min_datetime": "2020-05-28T08:52:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T10:56:24.000Z", "max_forks_repo_path": "xga/xspec/fit/general.py", "max_forks_repo_name": "DavidT3/XGA", "max_forks_repo_head_hexsha": "cde51c3f29f98b5f1e981fb6d327c04072b0ba38", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-04T10:55:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T11:30:56.000Z", "avg_line_length": 65.0993589744, "max_line_length": 120, "alphanum_fraction": 0.6635320762, "include": true, "reason": "import astropy,from astropy", "num_tokens": 4708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.25982564369245537, "lm_q1q2_score": 0.1520242840160531}}
{"text": "from __future__ import annotations\n\nimport operator\nfrom collections.abc import Iterable, Callable\n#  Copyright (c) 2021 zfit\nfrom contextlib import suppress\nfrom functools import reduce\n\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_probability as tfp\nimport uhi\n\nimport zfit\nimport zfit.z.numpy as znp\nfrom zfit import z\nfrom zfit._data.binneddatav1 import BinnedData, move_axis_obs\nfrom .baseobject import BaseNumeric, extract_filter_params\nfrom .binning import unbinned_to_binindex\nfrom .data import Data\nfrom .dimension import BaseDimensional\nfrom .interfaces import ZfitBinnedPDF, ZfitParameter, ZfitSpace, ZfitMinimalHist, ZfitPDF, ZfitBinnedData, \\\n    ZfitUnbinnedData\nfrom .parameter import convert_to_parameter\nfrom .space import supports, convert_to_space\nfrom .tensorlike import OverloadableMixinValues\nfrom ..util import ztyping\nfrom ..util.cache import GraphCachable\nfrom ..util.container import convert_to_container\nfrom ..util.deprecation import deprecated_args, deprecated, deprecated_norm_range\nfrom ..util.exception import (AlreadyExtendedPDFError, NotExtendedPDFError,\n                              SpaceIncompatibleError,\n                              SpecificFunctionNotImplemented,\n                              WorkInProgressError, NormNotImplemented, MultipleLimitsNotImplemented,\n                              BasePDFSubclassingError)\n\n_BaseModel_USER_IMPL_METHODS_TO_CHECK = {}\n\n\ndef _BinnedPDF_register_check_support(has_support: bool):\n    \"\"\"Marks a method that the subclass either *has* to or *can't* use the `@supports` decorator.\n\n    Args:\n        has_support (bool): If True, flags that it **requires** the `@supports` decorator. If False,\n            flags that the `@supports` decorator is **not allowed**.\n    \"\"\"\n    if not isinstance(has_support, bool):\n        raise TypeError(\"Has to be boolean.\")\n\n    def register(func):\n        \"\"\"Register a method to be checked to (if True) *has* `support` or (if False) has *no* `support`.\n\n        Args:\n            func (function):\n        Returns:\n            function:\n        \"\"\"\n        name = func.__name__\n        _BaseModel_USER_IMPL_METHODS_TO_CHECK[name] = has_support\n        func.__wrapped__ = _BinnedPDF_register_check_support\n        return func\n\n    return register\n\n\nclass BaseBinnedPDFV1(\n    BaseNumeric,\n    GraphCachable,\n    BaseDimensional,\n    OverloadableMixinValues,\n    ZfitMinimalHist,\n    ZfitBinnedPDF):\n\n    def __init__(self, obs, extended=None, norm=None, name=None, **kwargs):\n        super().__init__(dtype=znp.float64, **kwargs)\n        self._name = name  # TODO: why is this needed?\n\n        self._space = self._check_convert_obs_init(obs)\n        self._yield = None\n        self._norm = self._check_convert_norm_init(norm)\n        if extended is None:\n            extended = False\n        if extended is not False:\n            self._set_yield(extended)\n\n    def _check_convert_obs_init(self, obs):\n        if not isinstance(obs, ZfitSpace) or not obs.is_binned:\n            raise ValueError(f\"`obs` have to be a Space with binning, not {obs}.\")\n        return obs\n\n    def _check_convert_norm_init(self, norm):\n        if norm is not None:\n            if not isinstance(norm, ZfitSpace) or not norm.has_limits:\n                raise ValueError(f\"`norm` has to be None or a Space with limits, not {norm}.\")\n        return norm\n\n    @classmethod\n    def _subclass_check_support(cls, methods_to_check, wrapper_not_overwritten):\n        for method_name, has_support in methods_to_check.items():\n            method = getattr(cls, method_name)\n            if hasattr(method, \"__wrapped__\"):\n                if method.__wrapped__ == wrapper_not_overwritten:\n                    continue  # not overwritten, fine\n\n            # here means: overwritten\n            if hasattr(method, \"__wrapped__\"):\n                if method.__wrapped__ == supports:\n                    if has_support:\n                        continue  # needs support, has been wrapped\n                    else:\n                        raise BasePDFSubclassingError(\"Method {} has been wrapped with supports \"\n                                                      \"but is not allowed to. Has to handle all \"\n                                                      \"arguments.\".format(method_name))\n                elif has_support:\n                    raise BasePDFSubclassingError(\"Method {} has been overwritten and *has to* be \"\n                                                  \"wrapped by `supports` decorator (don't forget () )\"\n                                                  \"to call the decorator as it takes arguments\"\n                                                  \"\".format(method_name))\n                elif not has_support:\n                    continue  # no support, has not been wrapped with\n            else:\n                if not has_support:\n                    continue  # not wrapped, no support, need no\n\n            # if we reach this points, somethings was implemented wrongly\n            raise BasePDFSubclassingError(\"Method {} has not been correctly wrapped with @supports \"\n                                          \"OR has been wrapped but it should not be\".format(method_name))\n\n    @property\n    def axes(self):\n        return self.space.binning\n\n    def to_binneddata(self, **kwargs) -> zfit.data.BinnedData:\n        \"\"\"Create an Asimov dataset as `BinnedData` using either `counts` (for extended) or `rel_counts`\n\n        Args:\n            **kwargs (): arguments to `counts` or `rel_counts`.\n\n        Returns:\n            BinnedData: Binned data representing the Asimov dataset of this PDF.\n        \"\"\"\n        values = self.values(**kwargs)\n        data = BinnedData.from_tensor(space=self.space, values=values)\n        return data\n\n    def to_hist(self, **kwargs):\n        \"\"\"Create an Asimov histogram as `Hist` using either `counts` (for extended) or `rel_counts`.\n\n        Args:\n            **kwargs (): arguments to `counts` or `rel_counts`.\n\n        Returns:\n            ``hist.Hist``: Histogram representing the Asimov dataset of this PDF.\n        \"\"\"\n        return self.to_binneddata(**kwargs).to_hist()\n\n    @property\n    def space(self):\n        return self._space\n\n    def _set_yield(self, value):\n        if self.is_extended:\n            raise AlreadyExtendedPDFError(f\"Cannot extend {self}, is already extended.\")\n        value = convert_to_parameter(value)\n        self.add_cache_deps(value)\n        self._yield = value\n\n    def _get_dependencies(self) -> ztyping.DependentsType:\n        return super()._get_dependencies()\n\n    def _get_params(self,\n                    floating: bool | None = True,\n                    is_yield: bool | None = None,\n                    extract_independent: bool | None = True) -> set[ZfitParameter]:\n\n        params = super()._get_params(floating, is_yield=is_yield,\n                                     extract_independent=extract_independent)\n\n        if is_yield is not False:\n            if self.is_extended:\n                yield_params = extract_filter_params(self.get_yield(), floating=floating,\n                                                     extract_independent=extract_independent)\n                yield_params.update(params)  # putting the yields at the beginning\n                params = yield_params\n            elif is_yield is True:\n                raise NotExtendedPDFError(\"PDF is not extended but only yield parameters were requested.\")\n        return params\n\n    def _convert_input_binned_x(self, x, none_is_space=None):\n        if x is None and none_is_space:\n            return self.space\n        if isinstance(x, uhi.typing.plottable.PlottableHistogram) and not isinstance(x, ZfitBinnedData):\n            x = BinnedData.from_hist(x)\n        if not isinstance(x, ZfitBinnedData):\n            if not isinstance(x, ZfitSpace):\n                if not isinstance(x, ZfitUnbinnedData):\n                    try:\n                        x = Data.from_tensor(obs=self.obs, tensor=x)\n                    except Exception as error:\n\n                        raise TypeError(\n                            f\"Data to {self} has to be Binned Data, not {x}. (It can also be unbinned Data)\" +\n                            f\" but conversion to it failed (see also above) with the following error:\" +\n                            f\" {error})\") from error\n\n            # TODO: should we allow spaces? Or what?\n        return x\n\n    def _check_convert_norm(self, norm, none_is_error=False):\n        if norm is None:\n            norm = self.norm\n        if norm is None:\n            if none_is_error:\n                raise ValueError(f\"norm cannot be None for this function.\")\n        elif (norm is not False) and (not isinstance(norm, ZfitSpace)):\n            raise TypeError(f\"`norm` needs to be a binned ZfitSpace, not {norm}.\")\n        return norm\n\n    def _check_convert_limits(self, limits):\n        if limits is None:\n            limits = self.space\n        if not isinstance(limits, ZfitSpace):\n            limits = convert_to_space(obs=self.obs, limits=limits)\n        return limits\n\n    @_BinnedPDF_register_check_support(True)\n    def _pdf(self, x, norm):\n        return self._call_rel_counts(x, norm=norm) / np.prod(self.space.binning.widths, axis=0)\n\n    @deprecated_args(None, \"Use `norm` instead.\", \"norm_range\")\n    def pdf(self, x: ztyping.XType, norm: ztyping.LimitsType = None, *, norm_range=None) -> ztyping.XType:\n        \"\"\"Probability density function, evaluated at `x` or in the bins of `x`\n\n        Args:\n            x: values to evaluate the PDF at. If this is a `ZfitBinnedData`-like object, a histogram of *densities*\n                will be returned. If x is a `ZfitUnbinnedData`-like object, the densities will be evaluated at the\n                points of `x`.\n            norm: |@doc:pdf.pdf.norm| Normalization of the function.\n               By default, this is the `norm` of the PDF (which by default is the same as\n               the space of the PDF). |@docend:pdf.pdf.norm|\n\n        Returns:\n            `Array-like`: probalitity density\n        \"\"\"\n        if norm_range is not None:\n            norm = norm_range\n\n        # convert the input argument to a standardized form\n        x = self._convert_input_binned_x(x, none_is_space=True)\n        norm = self._check_convert_norm(norm, none_is_error=True)\n\n        # sort it and remember the original sorting\n        original_space = x if isinstance(x, ZfitSpace) else x.space\n        x = x.with_obs(self.space)\n\n        # if it is unbinned, we get the binned version and gather the corresponding values\n        is_unbinned = isinstance(x, ZfitUnbinnedData)\n        binindices = None\n        if is_unbinned:\n            binindices = unbinned_to_binindex(x, self.space, flow=True)\n            x = self.space\n\n        values = self._call_pdf(x, norm=norm)\n\n        if binindices is not None:  # because we have the flow, so we need to make it here with pads\n            padded_values = znp.pad(values, znp.ones((values.ndim, 2), dtype=znp.float64),\n                                    mode=\"constant\")  # for overflow\n            ordered_values = tf.gather_nd(padded_values, indices=binindices)\n        else:\n            ordered_values = move_axis_obs(self.space, original_space, values)\n        return ordered_values\n\n    @z.function(wraps='model')\n    def _call_pdf(self, x, norm):\n        with suppress(SpecificFunctionNotImplemented):\n            return self._auto_pdf(x, norm)\n        with suppress(SpecificFunctionNotImplemented):\n            return self._auto_rel_counts(x, norm=norm) / np.prod(self.space.binning.widths, axis=0)\n        return self._fallback_pdf(x, norm=norm)\n\n    def _auto_pdf(self, x, norm):\n        try:\n            pdf = self._pdf(x, norm=norm)\n        except NormNotImplemented:\n            unnormed_pdf = self._pdf(x, norm=False)\n            normalization = self.normalization(norm)\n            pdf = unnormed_pdf / normalization\n        return pdf\n\n    def _fallback_pdf(self, x, norm):\n        values = self._call_unnormalized_pdf(x)\n        if norm is not False:\n            values = values / self.normalization(norm)\n        return values\n\n    def _unnormalized_pdf(self, x):\n        raise SpecificFunctionNotImplemented\n\n    def _call_unnormalized_pdf(self, x):\n        return self._unnormalized_pdf(x)\n\n    @_BinnedPDF_register_check_support(True)\n    def _ext_pdf(self, x, norm):\n        raise SpecificFunctionNotImplemented\n\n    @deprecated_args(None, \"Use `norm` instead.\", \"norm_range\")\n    def ext_pdf(self, x: ztyping.XType, norm: ztyping.LimitsType = None, *, norm_range=None) -> ztyping.XType:\n        if norm_range is not None:\n            norm = norm_range\n        if not self.is_extended:\n            raise NotExtendedPDFError\n        # convert the input argument to a standardized form\n        x = self._convert_input_binned_x(x, none_is_space=True)\n        norm = self._check_convert_norm(norm, none_is_error=True)\n        # sort it and remember the original sorting\n        original_space = x if isinstance(x, ZfitSpace) else x.space\n        x = x.with_obs(self.space)\n\n        # if it is unbinned, we get the binned version and gather the corresponding values\n        is_unbinned = isinstance(x, ZfitUnbinnedData)\n        binindices = None\n        if is_unbinned:\n            binindices = unbinned_to_binindex(x, self.space, flow=True)\n            x = self.space\n\n        values = self._call_ext_pdf(x, norm=norm)\n\n        if binindices is not None:  # because we have the flow, so we need to make it here with pads\n            padded_values = znp.pad(values, znp.ones((values.ndim, 2), dtype=znp.float64),\n                                    mode=\"constant\")  # for overflow\n            ordered_values = tf.gather_nd(padded_values, indices=binindices)\n        else:\n            ordered_values = move_axis_obs(self.space, original_space, values)\n        return ordered_values\n\n    @z.function(wraps='model')\n    def _call_ext_pdf(self, x, norm):\n        with suppress(SpecificFunctionNotImplemented):\n            return self._auto_ext_pdf(x, norm)\n        with suppress(SpecificFunctionNotImplemented):\n            return self._auto_counts(x, norm=norm) / np.prod(self.space.binning.widths, axis=0)\n        return self._fallback_ext_pdf(x, norm=norm)\n\n    def _auto_ext_pdf(self, x, norm):\n        try:\n            pdf = self._ext_pdf(x, norm=norm)\n        except NormNotImplemented:\n            unnormed_pdf = self._ext_pdf(x, norm=False)\n            normalization = self.ext_normalization(norm)\n            pdf = unnormed_pdf / normalization\n        return pdf\n\n    def _fallback_ext_pdf(self, x, norm):\n        values = self._call_pdf(x, norm=norm)\n        return values * self.get_yield()\n\n    def normalization(self, limits, *, options=None) -> ztyping.NumericalTypeReturn:\n        if limits is not None:\n            norm = limits\n        if options is None:\n            options = {}\n        norm = self._check_convert_norm(norm, none_is_error=True)\n        return self._call_normalization(norm, options=options)\n\n    def _call_normalization(self, norm, *, options):\n        with suppress(SpecificFunctionNotImplemented):\n            return self._normalization(norm, options=options)\n\n        # fallback\n        return self._call_integrate(norm, norm=False, options=None)\n\n    @_BinnedPDF_register_check_support(True)\n    def _normalization(self, limits, *, options):\n        raise SpecificFunctionNotImplemented\n\n    @_BinnedPDF_register_check_support(True)\n    def _integrate(self, limits, norm, options):\n        raise SpecificFunctionNotImplemented\n\n    def integrate(self, limits: ztyping.LimitsType, norm: ztyping.LimitsType = None, *, options=None) -> ztyping.XType:\n        if options is None:\n            options = {}\n        norm = self._check_convert_norm(norm)\n        limits = self._check_convert_limits(limits)\n        return self._call_integrate(limits, norm, options)\n\n    @z.function(wraps='model')\n    def _call_integrate(self, limits, norm, options=None):\n        if options is None:\n            options = {}\n        with suppress(SpecificFunctionNotImplemented):\n            return self._auto_integrate(limits, norm, options)\n        return self._fallback_integrate(limits, norm, options)\n\n    def _fallback_integrate(self, limits, norm, options):\n        bincounts = self._call_rel_counts(limits, norm=norm)  # TODO: fake data? not to integrate limits?\n        edges = limits.binning.edges\n        return binned_rect_integration(counts=bincounts, edges=edges, limits=limits)  # TODO: check integral, correct?\n\n    def _auto_integrate(self, limits, norm, options):\n        try:\n            integral = self._integrate(limits=limits, norm=norm, options=options)\n        except NormNotImplemented:\n            unnormalized_integral = self._auto_integrate(limits=limits, norm=False, options=options)\n            normalization = self.normalization(norm, options=options)\n            integral = unnormalized_integral / normalization\n        except MultipleLimitsNotImplemented:\n            integrals = []  # TODO: map?\n            for sub_limits in limits:\n                integrals.append(self._auto_integrate(limits=sub_limits, norm=norm, options=options))\n            integral = z.reduce_sum(integrals, axis=0)  # TODO: remove stack?\n        return integral\n\n    @deprecated_norm_range\n    def ext_integrate(self, limits: ztyping.LimitsType, norm: ztyping.LimitsType = None, *,\n                      norm_range=None, options=None) -> ztyping.XType:\n        \"\"\"Extended integral of the PDF, i.e. the expected counts.\n\n        Args:\n            limits: |@doc:pdf.integrate.limits| Limits of the integration. |@docend:pdf.integrate.limits|\n            norm: |@doc:pdf.integrate.norm| Normalization of the integration.\n               By default, this is the same as the default space of the PDF.\n               `False` means no normalization and returns the unnormed integral. |@docend:pdf.integrate.norm|\n            options: |@doc:pdf.integrate.options| Options for the integration.\n               Additional options for the integration. Currently supported options are:\n               - type: one of (`bins`)\n                 This hints that bins are integrated. A method that is vectorizable, non-dynamic and\n                 therefore less suitable for complicated functions is chosen. |@docend:pdf.integrate.options|\n\n        Returns:\n        \"\"\"\n        if not self.is_extended:\n            raise NotExtendedPDFError\n        if options is None:\n            options = {}\n        norm = self._check_convert_norm(norm)\n        limits = self._check_convert_limits(limits)\n        return self._call_ext_integrate(limits, norm, options=options)\n\n    @z.function(wraps='model')\n    def _call_ext_integrate(self, limits, norm, *, options):\n        with suppress(SpecificFunctionNotImplemented):\n            return self._auto_ext_integrate(limits, norm, options=options)\n        return self._fallback_ext_integrate(limits, norm, options=options)\n\n    def _fallback_ext_integrate(self, limits, norm, *, options):  # TODO: rather use pdf?\n        bincounts = self._call_counts(limits, norm=norm)  # TODO: fake data? not to integrate limits?\n        edges = limits.binning.edges\n        return binned_rect_integration(counts=bincounts, edges=edges, limits=limits)\n\n    def _auto_ext_integrate(self, limits, norm, *, options):\n        try:\n            integral = self._ext_integrate(limits=limits, norm=norm, options=options)\n        except NormNotImplemented:\n            unnormalized_integral = self._auto_ext_integrate(limits=limits, norm=False, options=options)\n            normalization = self.ext_normalization(norm, options=options)\n            integral = unnormalized_integral / normalization\n        except MultipleLimitsNotImplemented:\n            integrals = []  # TODO: map?\n            for sub_limits in limits:\n                integrals.append(self._auto_integrate(limits=sub_limits, norm=norm, options=options))\n            integral = z.reduce_sum(integrals, axis=0)  # TODO: remove stack?\n        return integral\n\n    @_BinnedPDF_register_check_support(True)\n    def _ext_integrate(self, limits, norm, *, options):\n        raise SpecificFunctionNotImplemented\n\n    def sample(self, n: int = None, limits: ztyping.LimitsType = None) -> ZfitBinnedData:\n        \"\"\"Draw a random binned sample from the PDF.\n\n        Args:\n            n: |@doc:pdf.sample.n| Number of samples to draw.\n               For an extended PDF, the argument is optional and will be the\n               poisson-fluctuated expected number of events, i.e. the yield. |@docend:pdf.sample.n|\n            limits: |@doc:pdf.sample.limits| Limits of the sampling.\n               By default, this is the same as the default space of the PDF. |@docend:pdf.sample.limits|\n\n        Returns:\n            ``ZfitBinnedData``: Sampled dataset\n        \"\"\"\n        if n is None:\n            if self.is_extended:\n                n = znp.random.poisson(self.get_yield(), size=1)\n            else:\n                raise ValueError(f\"n cannot be None for sampling of {self} or needs to be extended.\")\n        original_limits = limits\n        limits = self._check_convert_limits(limits)\n        values = self._call_sample(n, limits)\n        if not isinstance(values, ZfitBinnedData):\n            values = BinnedData.from_tensor(space=limits, values=values, variances=None)\n        if isinstance(original_limits, ZfitSpace):\n            values = values.with_obs(original_limits)\n        return values\n\n    @z.function(wraps='model')\n    def _call_sample(self, n, limits):\n        with suppress(SpecificFunctionNotImplemented):\n            self._sample(n, limits)\n        return self._fallback_sample(n, limits)\n\n    def _fallback_sample(self, n, limits):\n        if limits != self.space:\n            raise WorkInProgressError(\"limits different from the default are not yet available.\"\n                                      \" Please open an issue if you need this:\"\n                                      \" https://github.com/zfit/zfit/issues/new/choose\")\n        probs = self.rel_counts(limits)\n        values = z.random.counts_multinomial(n, probs=probs, dtype=znp.float64)\n        return values\n\n    # ZfitMinimalHist implementation\n    def values(self, *, var=None):\n        \"\"\"Histogram values that are either the counts or the normalized counts.\n\n        If the PDF is extended, the counts are returned, otherwise the normalized counts are returned.\n\n        Returns:\n            ``ZfitBinnedData``: Histogram values\n        \"\"\"\n        if var is not None:\n            raise RuntimeError(\"var argument for `values` is not supported in V1\")\n        if self.is_extended:\n            return self.counts(var)\n        else:\n            return self.rel_counts(var)\n\n    def update_integration_options(self, *args, **kwargs):\n        raise RuntimeError(\"Integration options not available for BinnedPDF\")\n\n    def as_func(self, norm_range: ztyping.LimitsType = False):\n        raise WorkInProgressError(\"as_func not yet available for BinnedPDF\")\n\n    @property\n    def is_extended(self) -> bool:\n        return self._yield is not None\n\n    def set_norm(self, norm):\n        raise RuntimeError(\"set_norm should not be used anymore. Create a new PDF with the desired normalization.\")\n\n    def create_extended(self, yield_: ztyping.ParamTypeInput) -> ZfitPDF:\n        raise WorkInProgressError(\"create_extended not available for BinnedPDF. Use `extended` in the initialization\"\n                                  \" instead.\")\n\n    def get_yield(self) -> ZfitParameter | None:\n        if not self.is_extended:\n            raise NotExtendedPDFError\n        return self._yield\n\n    @classmethod\n    def register_analytic_integral(cls, func: Callable, limits: ztyping.LimitsType = None, priority: int = 50, *,\n                                   supports_norm: bool = False, supports_multiple_limits: bool = False,\n                                   supports_norm_range):\n        raise RuntimeError(\"analytic integral not available for BinnedPDF\")\n\n    def partial_integrate(self, x: ztyping.XType, limits: ztyping.LimitsType, *, norm=None, options=None,\n                          norm_range: ztyping.LimitsType = None) -> ztyping.XType:\n        raise WorkInProgressError(\"partial_integrate not yet available for BinnedPDF\")\n\n    @classmethod\n    def register_inverse_analytic_integral(cls, func: Callable):\n        raise RuntimeError(\"inverse analytic integral not available for BinnedPDF. It's a histogram, it's already \"\n                           \"'analytic'\")\n\n    @_BinnedPDF_register_check_support(True)\n    def _sample(self, n, limits):\n        raise SpecificFunctionNotImplemented\n\n    def _copy(self, deep, name, overwrite_params):\n        raise WorkInProgressError\n\n    # factor out with unbinned pdf\n\n    @property\n    def norm(self):\n        norm = self._norm\n        if norm is None:\n            norm = self.space\n        return norm\n\n    @property\n    @deprecated(None, \"use `norm` instead.\")\n    def norm_range(self):\n        return self.norm\n\n    # TODO: factor out with unbinned pdf\n\n    def _convert_sort_space(self, obs: ztyping.ObsTypeInput | ztyping.LimitsTypeInput = None,\n                            axes: ztyping.AxesTypeInput = None,\n                            limits: ztyping.LimitsTypeInput = None) -> ZfitSpace | None:\n        \"\"\"Convert the inputs (using eventually `obs`, `axes`) to :py:class:`~zfit.ZfitSpace` and sort them according to\n        own `obs`.\n\n        Args:\n            obs:\n            axes:\n            limits:\n\n        Returns:\n        \"\"\"\n        if obs is None:  # for simple limits to convert them\n            obs = self.obs\n        elif not set(obs).intersection(self.obs):\n            raise SpaceIncompatibleError(\"The given space {obs} is not compatible with the obs of the pdfs{self.obs};\"\n                                         \" they are disjoint.\")\n        space = convert_to_space(obs=obs, axes=axes, limits=limits)\n\n        if self.space is not None:  # e.g. not the first call\n            space = space.with_coords(self.space, allow_superset=True, allow_subset=True)\n        return space\n\n    @z.function(wraps='model')\n    def counts(self, x: ztyping.BinnedDataInputType = None, norm: ztyping.NormInputType = None) -> ZfitBinnedData:\n        \"\"\"Calculate the number of events in each bin.\n\n        This is the integrals of the PDF in each bin.\n\n        Args:\n            x: |@doc:pdf.binned.counts.x| Data for the binned PDF.\n               The returned counts correspond to the binned axis in `x`. |@docend:pdf.binned.counts.x|\n            norm: |@doc:pdf.binned.counts.norm| Normalization of the counts.\n               This normalizes the counts so that the actual sum of all counts is\n               equal to the yield. |@docend:pdf.binned.counts.norm|\n\n        Returns:\n            ZfitBinnedData: A histogram with the number of events in each bin.\n        \"\"\"\n        if not self.is_extended:\n            raise NotExtendedPDFError\n        x = self._convert_input_binned_x(x, none_is_space=True)\n        space = x if isinstance(x, ZfitSpace) else x.space  # TODO: split the convert and sort, make Sorter?\n        x = x.with_obs(self.space)\n        norm = self._check_convert_norm(norm)\n        counts = self._call_counts(x, norm)\n        return move_axis_obs(self.space, space, counts)\n\n    @z.function(wraps='model')\n    def _call_counts(self, x, norm):\n        with suppress(SpecificFunctionNotImplemented):\n            return self._auto_counts(x, norm)\n        return self._fallback_counts(x, norm)\n\n    def ext_normalization(self, norm, *, options=None):\n        if not self.is_extended:\n            raise NotExtendedPDFError\n        if options is None:\n            options = {}\n        norm = self._check_convert_norm(norm, none_is_error=True)\n        return self._call_ext_normalization(norm, options=options)\n\n    def _call_ext_normalization(self, norm, *, options):\n        with suppress(SpecificFunctionNotImplemented):\n            return self._ext_normalization(norm, options=options)\n        # fallback\n        return self.normalization(norm, options=options) / self.get_yield()\n\n    def _ext_normalization(self, norm, *, options):\n        raise SpecificFunctionNotImplemented\n\n    def _auto_counts(self, x, norm):\n        try:\n            counts = self._counts(x, norm=norm)\n        except NormNotImplemented:\n            unnormed_counts = self._counts(x, norm=False)\n            normalization = self.normalization(norm)\n            counts = unnormed_counts / normalization\n        return counts\n\n    def _fallback_counts(self, x, norm):\n        return self._auto_rel_counts(x, norm) * self.get_yield()\n\n    @_BinnedPDF_register_check_support(True)\n    def _counts(self, x, norm):\n        raise SpecificFunctionNotImplemented\n\n    @z.function(wraps='model')\n    def rel_counts(self, x: ztyping.BinnedDataInputType = None, norm: ztyping.NormInputType = None) -> ZfitBinnedData:\n        \"\"\"Calculate the relative number of events in each bin.\n\n        This is the integrals of the PDF in each bin divided by the integral of the PDF over the whole space.\n        It is *not* equal to the density but rather a histogram scaled to 1.\n\n        Args:\n            x: |@doc:pdf.binned.counts.x| Data for the binned PDF.\n               The returned counts correspond to the binned axis in `x`. |@docend:pdf.binned.counts.x|\n            norm: |@doc:pdf.binned.counts.norm| Normalization of the counts.\n               This normalizes the counts so that the actual sum of all counts is\n               equal to the yield. |@docend:pdf.binned.counts.norm|\n\n        Returns:\n            ZfitBinnedData: A histogram with the relative number of events in each bin.\n        \"\"\"\n        x = self._convert_input_binned_x(x, none_is_space=True)\n        space = x if isinstance(x, ZfitSpace) else x.space  # TODO: split the convert and sort, make Sorter?\n        x = x.with_obs(self.space)\n        norm = self._check_convert_norm(norm)\n        values = self._call_rel_counts(x, norm)\n        return move_axis_obs(self.space, space, values)\n\n    @z.function(wraps='model')\n    def _call_rel_counts(self, x, norm):\n        with suppress(SpecificFunctionNotImplemented):\n            return self._auto_rel_counts(x, norm=norm)\n        with suppress(SpecificFunctionNotImplemented):\n            return self._auto_counts(x, norm=norm) / self.get_yield()\n        return self._fallback_rel_counts(x, norm)\n\n    @_BinnedPDF_register_check_support(True)\n    def _rel_counts(self, x, norm):\n        raise SpecificFunctionNotImplemented\n\n    def _auto_rel_counts(self, x, norm):\n        try:\n            rel_counts = self._rel_counts(x, norm=norm)\n        except NormNotImplemented:\n            unnormed_rel_counts = self._rel_counts(x, norm=False)\n            normalization = self.normalization(norm)\n            rel_counts = unnormed_rel_counts / normalization\n        return rel_counts\n\n    def _fallback_rel_counts(self, x, norm):\n        density = self._call_pdf(x, norm)\n        rel_counts = density * np.prod(self.space.binning.widths, axis=0)\n        return rel_counts\n\n    def set_norm_range(self):\n        raise RuntimeError(\"set_norm_range is removed and should not be used anymore.\")\n\n\ndef binned_rect_integration(*,\n                            limits: ZfitSpace,\n                            edges: Iterable[znp.array] | znp.array,\n                            counts: znp.array | None = None,\n                            density: znp.array | None = None,\n                            axis: Iterable[int] | int | None = None,\n                            ) -> znp.array:\n    \"\"\"Integrate a histogram over *limits*.\n\n    This integrator does take into account that limits do not match the edges.\n\n    Args:\n        limits: Limits to integrate over. A possible binning is ignored.\n        edges: The edges per axis. They should have the shape `(1,..., 1, n, 1, ..., 1)`, where n is the *ith* axis.\n            `ZfitBinning` provides this format on the `edges` attribute.\n        counts: Counts of the histogram. This is what most histograms have and is equal to the density multiplied by\n            the binwidth.\n            Exactly one of counts or density has to be provided.\n        density: The density of a histogram is the bincount divided by the binwidth.\n            Exactly one of counts or density has to be provided.\n        axis: Which axes to integrate over. Defaults to all.\n\n    Returns:\n        Integral with shape corresponding to the non-integrated axes (or a scalar in case of all axes integrated).\n    \"\"\"\n    edges = convert_to_container(edges)\n    if not isinstance(limits, ZfitSpace):\n        raise TypeError(f\"limits has to be a ZfitSpace, not {limits}.\")\n    if counts is not None:\n        if density is not None:\n            raise ValueError(\"Either specify 'counts' or 'density' but not both.\")\n        is_density = False\n        values = counts\n    elif density is not None:\n        is_density = True\n        values = density\n    else:\n        raise ValueError(\"Need to specify either 'counts' or 'density', not None.\")\n    ndims = values.shape.ndims\n    # partial = axis is not None and len(axis) < ndims\n    if axis is not None:\n        axis = convert_to_container(axis)\n        if len(axis) > ndims:\n            raise ValueError(f'axis {axis} is larger than values has ndims {values.shape}.')\n    else:\n        axis = list(range(ndims))\n\n    scaled_edges, (lower_bins, upper_bins), unscaled_edges = cut_edges_and_bins(edges=edges, limits=limits, axis=axis,\n                                                                                unscaled=True)\n\n    values_cut = tf.slice(values, lower_bins, (upper_bins - lower_bins))  # since limits are inclusive\n\n    rank = values.shape.rank\n    binwidths = []\n    if not is_density:\n        binwidths_unscaled = []\n    # calculate the binwidth in each dimension\n    for i, edge in enumerate(scaled_edges):\n        edge_lower_index = [0] * rank\n        # int32 is needed! Otherwise the gradient will fail\n        edge_lowest_index = znp.array(edge_lower_index, dtype=znp.int32)\n\n        edge_lower_index[i] = 1\n        edge_lower_index = znp.array(edge_lower_index, dtype=znp.int32)\n        edge_upper_index = [1] * rank\n        edge_highest_index = edge_upper_index.copy()\n        len_edge = tf.shape(edge)[i]\n        edge_highest_index[i] = len_edge\n        edge_highest_index = znp.asarray(edge_highest_index, dtype=znp.int32)\n        edge_upper_index[i] = len_edge - 1  # len n -> index max is n - 1\n\n        edge_upper_index = znp.asarray(edge_upper_index, dtype=znp.int32)\n        lower_edge = tf.slice(edge, edge_lowest_index, (edge_upper_index - edge_lowest_index))\n        upper_edge = tf.slice(edge, edge_lower_index, (edge_highest_index - edge_lower_index))\n        binwidths.append(upper_edge - lower_edge)\n\n        if not is_density:\n            # unscaled edges to get the ratio\n            lower_edge_unscaled = tf.slice(unscaled_edges[i], edge_lowest_index, (edge_upper_index - edge_lowest_index))\n            upper_edge_unscaled = tf.slice(unscaled_edges[i], edge_lower_index, (edge_highest_index - edge_lower_index))\n            binwidths_unscaled.append(upper_edge_unscaled - lower_edge_unscaled)\n\n    binareas = reduce(operator.mul, binwidths)  # needs to be np as znp or tf can't broadcast otherwise\n    if not is_density:  # scale the counts by the fraction. This is mostly one.\n        binareas_uncut = np.prod(binwidths_unscaled, axis=0)\n        binareas /= binareas_uncut\n    values_cut *= binareas\n    integral = tf.reduce_sum(values_cut, axis=axis)\n    return integral\n\n\n@z.function(wraps='tensor')\ndef cut_edges_and_bins(edges: Iterable[znp.array], limits: ZfitSpace, axis=None, unscaled=None) -> tuple[\n    list[znp.array], tuple[znp.array, znp.array], list | None]:\n    \"\"\"Cut the *edges* according to *limits* and calculate the bins inside.\n\n    The edges within limits are calculated and returned together with the corresponding bin indices. The indices\n    mark the lowest and the highest index of the edges that are returned. Additionally, the unscaled edges are returned.\n\n    If the limits are between two edges, this will be treated as the new edge. If the limits are outside the edges,\n    all edges in this direction will be returned (but not extended to the limit). For example:\n\n    [0, 0.5, 1., 1.5, 2.] and the limits (0.8, 3.) will return [0.8, 1., 1.5, 2.], ([1], [4])\n\n    .. code-block::\n\n        cut_edges_and_bins([[0., 0.5, 1., 1.5, 2.]], ([[0.8]], [[3]]))\n\n\n\n    Args:\n        edges: Iterable of tensor-like objects that describe the edges of a histogram. Every object should have rank n\n            (where n is the length of *edges*) but only have the dimension i filled out. These are\n            tensors that are ready to be broadcasted together.\n        limits: The limits that will be used to confine the edges\n\n\n    Returns:\n        edges, (lower bins, upper bins), unscaled_edges:  The edges and the bins are returned.\n            The upper bin number corresponds to\n            the highest bin which was still (partially) inside the limits **plus one** (so it's the index of the\n            edge that is right outside). The unscaled edges are like *edges* but the last edge is the edge\n            that is lying not inside anymore, so the actual edge of the last bin number returend.\n            This can be used to determine the fraction cut away.\n    \"\"\"\n    if axis is not None:\n        axis = convert_to_container(axis)\n    if unscaled is None:\n        unscaled = False\n    if unscaled:\n        cut_unscaled_edges = []\n    else:\n        cut_unscaled_edges = None\n    cut_scaled_edges = []\n\n    all_lower_bins = []\n    all_upper_bins = []\n    if isinstance(limits, ZfitSpace):\n        lower, upper = limits.limits\n    else:\n        lower, upper = limits\n        lower = znp.asarray(lower)\n        upper = znp.asarray(upper)\n    lower_all = lower[0]\n    upper_all = upper[0]\n    rank = len(edges)\n    current_axis = 0\n    for i, edge in enumerate(edges):\n        edge = znp.asarray(edge)\n        edge = znp.reshape(edge, (-1,))\n        if axis is None or i in axis:\n\n            lower_i = lower_all[current_axis, None]\n            edge_minimum = edge[0]\n            # edge_minimum = tf.gather(edge, indices=0, axis=i)\n            lower_i = znp.maximum(lower_i, edge_minimum)\n            upper_i = upper_all[current_axis, None]\n            edge_maximum = edge[-1]\n            # edge_maximum = tf.gather(edge, indices=tf.shape(edge)[i] - 1, axis=i)\n            upper_i = znp.minimum(upper_i, edge_maximum)\n            # we get the bins that are just one too far. Then we update this whole bin tensor with the actual edge.\n            # The bins index is the index below the value.\n            lower_bin_float = tfp.stats.find_bins(lower_i, edge,\n                                                  extend_lower_interval=True,\n                                                  extend_upper_interval=True)\n            lower_bin = tf.reshape(tf.cast(lower_bin_float, dtype=znp.int32), [-1])\n            # lower_bins = tf.tensor_scatter_nd_update(zero_bins, [[i]], lower_bin)\n            # +1 below because the outer bin is searched, meaning the one that is higher than the value\n\n            upper_bin_float = tfp.stats.find_bins(upper_i, edge,\n                                                  extend_lower_interval=True,\n                                                  extend_upper_interval=True)\n            upper_bin = tf.reshape(tf.cast(upper_bin_float, dtype=znp.int32), [-1]) + 1\n            size = upper_bin - lower_bin\n            new_edge = tf.slice(edge, lower_bin, size + 1)  # +1 because stop is exclusive\n            new_edge = tf.tensor_scatter_nd_update(new_edge, [tf.constant([0]), size], [lower_i[0], upper_i[0]])\n\n            if unscaled:\n                new_edge_unscaled = tf.slice(edge, lower_bin, size + 1)  # +1 because stop is exclusive\n\n            current_axis += 1\n        else:\n            lower_bin = [0]\n            upper_bin = znp.asarray([edge.shape[0] - 1], dtype=znp.int32)\n            new_edge = edge\n            if unscaled:\n                new_edge_unscaled = edge\n        new_shape = [1] * rank\n        new_shape[i] = -1\n        new_edge = znp.reshape(new_edge, new_shape)\n        all_lower_bins.append(lower_bin)\n        all_upper_bins.append(upper_bin)\n        cut_scaled_edges.append(new_edge)\n        if unscaled:\n            new_edge_unscaled = znp.reshape(new_edge_unscaled, new_shape)\n            cut_unscaled_edges.append(new_edge_unscaled)\n\n    # partial = axis is not None and len(axis) < rank\n    #\n    # if partial:\n    #     scaled_edges_full = list(edges)\n    #     for edge, ax in zip(cut_scaled_edges, axis):\n    #         scaled_edges_full[ax] = edge\n    #     scaled_edges = scaled_edges_full\n    #     indices = tf.convert_to_tensor(axis)[:, None]\n    #     lower_bins = tf.scatter_nd(indices, lower_bins, shape=(ndims,))\n    #     upper_bins = tf.tensor_scatter_nd_update(tf.convert_to_tensor(values.shape),\n    #                                              indices, upper_bins)\n    # lower_bins_indices = tf.stack([lower_bins, dims], axis=-1)\n    # upper_bins_indices = tf.stack([upper_bins, dims], axis=-1)\n    # all_lower_bins = tf.cast(znp.sum(all_lower_bins, axis=0), dtype=znp.int32)\n    all_lower_bins = tf.concat(all_lower_bins, axis=0)\n    all_upper_bins = tf.concat(all_upper_bins, axis=0)\n    return cut_scaled_edges, (all_lower_bins, all_upper_bins), cut_unscaled_edges\n", "meta": {"hexsha": "38b93c9e5900148d654594678cdc30cd4dd92c70", "size": 41511, "ext": "py", "lang": "Python", "max_stars_repo_path": "zfit/core/binnedpdf.py", "max_stars_repo_name": "zfit/zf", "max_stars_repo_head_hexsha": "4d0df67e74072e4c8c66be21591f4af1878380b5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 129, "max_stars_repo_stars_event_min_datetime": "2018-03-24T22:27:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T21:04:07.000Z", "max_issues_repo_path": "zfit/core/binnedpdf.py", "max_issues_repo_name": "zfit/zf", "max_issues_repo_head_hexsha": "4d0df67e74072e4c8c66be21591f4af1878380b5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 195, "max_issues_repo_issues_event_min_datetime": "2018-03-22T11:31:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T17:01:45.000Z", "max_forks_repo_path": "zfit/core/binnedpdf.py", "max_forks_repo_name": "zfit/zf", "max_forks_repo_head_hexsha": "4d0df67e74072e4c8c66be21591f4af1878380b5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 45, "max_forks_repo_forks_event_min_datetime": "2018-03-22T10:12:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T10:45:27.000Z", "avg_line_length": 44.0201484624, "max_line_length": 120, "alphanum_fraction": 0.6343137963, "include": true, "reason": "import numpy", "num_tokens": 9322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.2720245510940225, "lm_q1q2_score": 0.1518786499977551}}
{"text": "# ======================================================================\n# Copyright TOTAL / CERFACS / LIRMM (02/2020)\n# Contributor: Adrien Suau (<adrien.suau@cerfacs.fr>\n#                           <adrien.suau@lirmm.fr>)\n#              Siyuan Niu  (<siyuan.niu@lirmm.fr>)\n# This software is governed by the CeCILL-B license under French law and\n# abiding  by the  rules of  distribution of free software. You can use,\n# modify  and/or  redistribute  the  software  under  the  terms  of the\n# CeCILL-B license as circulated by CEA, CNRS and INRIA at the following\n# URL \"http://www.cecill.info\".\n#\n# As a counterpart to the access to  the source code and rights to copy,\n# modify and  redistribute granted  by the  license, users  are provided\n# only with a limited warranty and  the software's author, the holder of\n# the economic rights,  and the  successive licensors  have only limited\n# liability.\n#\n# In this respect, the user's attention is drawn to the risks associated\n# with loading,  using, modifying and/or  developing or reproducing  the\n# software by the user in light of its specific status of free software,\n# that  may mean  that it  is complicated  to manipulate,  and that also\n# therefore  means that  it is reserved for  developers and  experienced\n# professionals having in-depth  computer knowledge. Users are therefore\n# encouraged  to load and  test  the software's  suitability as  regards\n# their  requirements  in  conditions  enabling  the  security  of their\n# systems  and/or  data to be  ensured and,  more generally,  to use and\n# operate it in the same conditions as regards security.\n#\n# The fact that you  are presently reading this  means that you have had\n# knowledge of the CeCILL-B license and that you accept its terms.\n# ======================================================================\n\nimport logging\nimport typing as ty\n\nimport numpy\nfrom qiskit.circuit.quantumregister import Qubit\nfrom qiskit.dagcircuit.dagcircuit import DAGNode\n\nfrom hamap.gates import TwoQubitGate, SwapTwoQubitGate\nfrom hamap.hardware.IBMQHardwareArchitecture import IBMQHardwareArchitecture\nfrom hamap.layer import QuantumLayer, update_layer\n\nlogger = logging.getLogger(\"hamap.heuristics\")\n\n\ndef _gate_op_cost(\n    op: DAGNode,\n    distance_matrix: numpy.ndarray,\n    mapping: ty.Dict[Qubit, int],\n    hardware: IBMQHardwareArchitecture,\n) -> float:\n    if hardware.is_ignored_operation(op):\n        return 0\n    if len(op.qargs) == 1:\n        # SABRE ignores 1-qubit gates\n        return 0\n    elif len(op.qargs) == 2:\n        # This is a CNOT\n        source, sink = op.qargs\n        return distance_matrix[mapping[source], mapping[sink]]\n    else:\n        logger.warning(\n            f\"Found a quantum operation applied on '{len(op.qargs)}' qubits. This \"\n            f\"operation will be excluded from the cost computation.\"\n        )\n        return 0\n\n\ndef sabre_heuristic(\n    hardware: IBMQHardwareArchitecture,\n    front_layer: QuantumLayer,\n    topological_nodes: ty.List[DAGNode],\n    current_node_index: int,\n    current_mapping: ty.Dict[Qubit, int],\n    initial_mapping: ty.Dict[Qubit, int],\n    trans_mapping: ty.Dict[Qubit, int],\n    distance_matrix: numpy.ndarray,\n    tentative_gate: TwoQubitGate,\n    look_ahead_depth: int = 20,\n    look_ahead_weight: float = 0.5,\n) -> float:\n    \"\"\"The heuristic cost function used in the SABRE optimiser.\n\n    :param hardware: the SABRE optimiser does not take into account the hardware data to\n        compute the heuristic cost, only to generate the possible SWAPs to evaluate\n        with this heuristic. The SABRE heuristic only uses the distance matrix.\n        Nevertheless, this implementation uses the hardware data to check if some\n        gates are ignored (such as barriers for example).\n    :param front_layer: the current front layer. Used to compute an \"immediate\" cost,\n        i.e. a quantity that will tell us if the SWAP/Bridge is useful to execute\n        gates in the front layer.\n    :param topological_nodes: the list of all the DAGNodes of the quantum circuit,\n        sorted in topological order.\n    :param current_node_index: index of the first non-processed node.\n    :param current_mapping: the mapping *before* applying the given SWAP.\n    :param distance_matrix: the pre-computed distance matrix between each qubits.\n    :param tentative_gate: the SWAP we want to estimate the usefulness of.\n    :param look_ahead_depth: the depth of the look-ahead. The procedure will consider\n        gates that will be executed in the future (i.e. not in the front layer) up to\n        the given depth. Note that 1-qubit gates are not ignored, which means that a\n        depth of 3 will not guarantee that there is at least 3 CNOTs in the\n        look-ahead set.\n    :param look_ahead_weight: weight of the look-ahead. The actual gates (i.e. the\n        gates in the front layer) have a weight of 1.\n    :return: the heuristic cost of the given SWAP/Bridge according to the current\n        state of the algorithm.\n    \"\"\"\n    # First, compute the proposed new mapping\n    new_mapping = tentative_gate.update_mapping(current_mapping)\n    # Compute H_basic, the cost associated with the distance.\n    H_basic = 0.0\n    H_tentative = 0.0\n    H_tentative_gate_number = 0\n    H_basic_gate_number = 0\n    for op in front_layer.ops:\n        # Only add the gate to the cost if the gate is not already implemented by the\n        # SWAP/Bridge\n        if not tentative_gate.implements_operation(op, initial_mapping, trans_mapping):\n        #if isinstance(tentative_gate, SwapTwoQubitGate):\n            H_basic += _gate_op_cost(op, distance_matrix, new_mapping, hardware)\n            H_basic_gate_number += 1\n    # Compute H, the cost cost that encourage parallelism and adds some look-ahead\n    # ability.\n\n    if isinstance(tentative_gate, SwapTwoQubitGate):\n        H_tentative += tentative_gate.cost(hardware, current_mapping, distance_matrix)\n        H_tentative_gate_number += 3\n    else:\n        H_tentative += tentative_gate.cost(hardware, initial_mapping, distance_matrix)\n        H_tentative_gate_number += 4\n\n\n    #H = 0.0\n    future_nodes_layer = QuantumLayer(max_depth=look_ahead_depth)\n    # We do not use the return of update_layer because we do not care about the\n    # number of gates that were added. Still, we add the firsts look_ahead_depth layers\n    # of our future gates in this set to have this look-ahead ability.\n    _ = update_layer(future_nodes_layer, topological_nodes, current_node_index)\n    # The decay is not implemented in the code the authors gave us and not\n    # sufficiently explained in the paper to implement it without guessing. Not\n    # implementing it for the moment...\n    #H += (H_basic / H_basic_gate_number) if H_basic_gate_number != 0 else 0\n    H = (H_basic + H_tentative) / (H_basic_gate_number + H_tentative_gate_number)\n    #print(type(tentative_gate), tentative_gate.left, tentative_gate.right, H, H_basic, H_basic_gate_number)\n    #print(front_layer.ops[0].qargs)\n    H_extended = 0.0\n    if future_nodes_layer:\n        # Only add this cost if there are nodes in the future_node_layer\n        H_extended += (\n            look_ahead_weight\n            * sum(\n                _gate_op_cost(op, distance_matrix, new_mapping, hardware)\n                for op in future_nodes_layer.ops\n            )\n            / len(future_nodes_layer)\n        )\n\n    H += H_extended\n    #print(f\"H extended {H_extended} and final H is {H}, gate number {len(future_nodes_layer)}\")\n    return H\n\n\ndef sabre_heuristic_with_effect(\n    hardware: IBMQHardwareArchitecture,\n    front_layer: QuantumLayer,\n    topological_nodes: ty.List[DAGNode],\n    current_node_index: int,\n    current_mapping: ty.Dict[Qubit, int],\n    initial_mapping: ty.Dict[Qubit, int],\n    trans_mapping: ty.Dict[Qubit, int],\n    distance_matrix: numpy.ndarray,\n    tentative_gate: SwapTwoQubitGate,\n    look_ahead_depth: int = 20,\n    look_ahead_weight: float = 0.5,\n) -> ty.Tuple[float, float]:\n    \"\"\"The heuristic cost function used by SABRE, modified to return the effect.\n\n    The effect of the SWAP is a float number that is negative if the SWAP gate has a\n    bad effect on the following gates, else positive.\n\n    :param hardware: the SABRE optimiser does not take into account the hardware data to\n        compute the heuristic cost, only to generate the possible SWAPs to evaluate\n        with this heuristic. The SABRE heuristic only uses the distance matrix.\n        Nevertheless, this implementation uses the hardware data to check if some\n        gates are ignored (such as barriers for example).\n    :param front_layer: the current front layer. Used to compute an \"immediate\" cost,\n        i.e. a quantity that will tell us if the SWAP/Bridge is useful to execute\n        gates in the front layer.\n    :param topological_nodes: the list of all the DAGNodes of the quantum circuit,\n        sorted in topological order.\n    :param current_node_index: index of the first non-processed node.\n    :param current_mapping: the mapping *before* applying the given SWAP.\n    :param distance_matrix: the pre-computed distance matrix between each qubits.\n    :param tentative_gate: the SWAP we want to estimate the usefulness of.\n    :param look_ahead_depth: the depth of the look-ahead. The procedure will consider\n        gates that will be executed in the future (i.e. not in the front layer) up to\n        the given depth. Note that 1-qubit gates are not ignored, which means that a\n        depth of 3 will not guarantee that there is at least 3 CNOTs in the\n        look-ahead set.\n    :param look_ahead_weight: weight of the look-ahead. The actual gates (i.e. the\n        gates in the front layer) have a weight of 1.\n    :return: the heuristic cost of the given SWAP according to the current\n        state of the algorithm along with the effect of the SWAP on the non-executed\n        gates.\n    \"\"\"\n    # First, compute the proposed new mapping\n    new_mapping = tentative_gate.update_mapping(current_mapping)\n    # Compute H_basic, the cost associated with the distance.\n    H_basic = 0.0\n    H_basic_gate_number = 0\n    for op in front_layer.ops:\n        # Only add the gate to the cost if the gate is not already implemented by the\n        # SWAP/Bridge\n        if not tentative_gate.implements_operation(op, initial_mapping, trans_mapping):\n            H_basic += _gate_op_cost(op, distance_matrix, new_mapping, hardware)\n            H_basic_gate_number += 1\n    # Compute H, the cost cost that encourage parallelism and adds some look-ahead\n    # ability.\n    #H = tentative_gate.cost(hardware, current_mapping)\n    H = 0.0\n    future_nodes_layer = QuantumLayer(max_depth=look_ahead_depth)\n    # We do not use the return of update_layer because we do not care about the\n    # number of gates that were added. Still, we add the firsts look_ahead_depth layers\n    # of our future gates in this set to have this look-ahead ability.\n    _ = update_layer(future_nodes_layer, topological_nodes, current_node_index)\n    # The decay is not implemented in the code the authors gave us and not\n    # sufficiently explained in the paper to implement it without guessing. Not\n    # implementing it for the moment...\n    swap_effect = 0.0\n    H += (H_basic / H_basic_gate_number) if H_basic_gate_number != 0 else 0\n    if future_nodes_layer:\n        # Only add this cost if there are nodes in the future_node_layer\n        H += (\n            look_ahead_weight\n            * sum(\n                _gate_op_cost(op, distance_matrix, new_mapping, hardware)\n                for op in future_nodes_layer.ops\n            )\n            / len(future_nodes_layer)\n        )\n        swap_effect += sum(\n            _gate_op_cost(op, distance_matrix, current_mapping, hardware)\n            - _gate_op_cost(op, distance_matrix, new_mapping, hardware)\n            for op in future_nodes_layer.ops\n        )\n    return H, swap_effect\n\n", "meta": {"hexsha": "28dd514e2aa86bcc2ce45b62b22970a0ee007214", "size": 11911, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/hamap/heuristics.py", "max_stars_repo_name": "peachnuts/HA", "max_stars_repo_head_hexsha": "5241f644f4f47cba4f72b9e43135a893416edfef", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-11-03T14:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T20:43:05.000Z", "max_issues_repo_path": "src/hamap/heuristics.py", "max_issues_repo_name": "peachnuts/HA", "max_issues_repo_head_hexsha": "5241f644f4f47cba4f72b9e43135a893416edfef", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hamap/heuristics.py", "max_forks_repo_name": "peachnuts/HA", "max_forks_repo_head_hexsha": "5241f644f4f47cba4f72b9e43135a893416edfef", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-11T10:58:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T10:58:02.000Z", "avg_line_length": 47.8353413655, "max_line_length": 108, "alphanum_fraction": 0.7012005709, "include": true, "reason": "import numpy", "num_tokens": 2852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.2877678279774723, "lm_q1q2_score": 0.15174473058957003}}
{"text": "# The Start-Up\nfrom pyrosetta import *  ## for newer versions make all start-up commands with pyrosetta\ninit()\nfrom math import exp, log, pi, sqrt\nfrom random import random as rnd\nfrom random import randint\nimport sys\nimport os\nimport numpy as np\nfrom pyrosetta.rosetta.core.scoring import *\nfrom pyrosetta.rosetta.core.scoring.methods import *\nfrom pyrosetta.rosetta.core.scoring.methods import EnergyMethodOptions\nfrom pyrosetta.rosetta.protocols.grafting import *\nfrom pyrosetta.rosetta.protocols.simple_moves import *\nfrom pyrosetta.rosetta.protocols.moves import *\nfrom pyrosetta.rosetta.core.fragment import *\nfrom pyrosetta.rosetta.protocols.minimization_packing import *\nimport scipy.optimize as op\nfrom scipy.interpolate import interp1d\nimport argparse\n\n# Argument Parsing\nparser = argparse.ArgumentParser(description='Program')\nparser.add_argument('-in', '--Input_FASTA_File', action='store', type=str, required=True,\n\thelp='Name of the text file containing the FASTA sequence of the protein of interest. Carot should not be in same line as sequence, UniProt format preferred.')\nparser.add_argument('-abnstruct', '--Number_of_AbInitio_Structures', action='store', type=str, required=False,\n\thelp='Number of structures to sample during Centroid AbInitio portion. Default = 1000')\nparser.add_argument('-diso', '--Input_DisoPred_File', action='store', type=str, required=True,\n\thelp='Name of the file containing the per residue disordered probability prediction generated by RaptorX')\nparser.add_argument('-t_frag', '--Three_Mer_Frag_Library', action='store', type=str, required=True,\n\thelp='Name of the file containing the three-mer fragment library generated by disorder corrected method')\nparser.add_argument('-n_frag', '--Nine_Mer_Frag_Library', action='store', type=str, required=True,\n\thelp='Name of the file containing the nine-mer fragment library generated by disorder corrected method')\nparser.add_argument('-rsd_wt_helix', '--Residue_Weight_Helix', action='store', type=float, required=False,\n\thelp='Reweights the env, pair and cbeta scores for helical residues by specificied factor. Default: 0.5')\nparser.add_argument('-rsd_wt_loop', '--Residue_Weight_Loop', action='store', type=float, required=False,\n\thelp='Reweights the env, pair and cbeta scores for loop residues by specificied factor. Default: 0.5')\nparser.add_argument('-rsd_wt_sheet', '--Residue_Weight_Sheet', action='store', type=float, required=False,\n\thelp='Reweights the env, pair and cbeta scores for sheet residues by specificied factor. Default: 1.0')\nparser.add_argument('-rg_weight', '--Rg_Weight', action='store', type=float, required=False,\n\thelp='Reweights the weight of rg in each step by specificied factor. Default: 0.5')\nparser.add_argument('-cycles', '--AbInitio_Cycles', action='store', type=str, required=False,\n\thelp='Number of sampling cycles within each stage of AbInitio, identical to increase_cycles flag in C++ ClassicAbInitio and AbRelax. Default 10')\nparser.add_argument('-abinitiovo', '--AbInitioVO', action='store_true', required=False,\n\thelp='Boolean for running protocol with AbInitioVO score function, runs with flag')\nparser.add_argument('-refinesubset', '--Refine_Subset', action='store', type=int, required=False,\n\thelp='Only subjects the lowest X% of structures to Relax refinement where X is specified as input following flag. Default 100')\nparser.add_argument('-relnstruct', '--Number_of_Relax_Structures', action='store', type=str, required=False,\n\thelp='Number of independent full-atom Relax sampling trajectories from a single AbInitio structure. Default 50')\nargs = parser.parse_args()\n\n## Imports from Parser and Defaults\nif args.Number_of_AbInitio_Structures:\n\tabnstruct = int(args.Number_of_AbInitio_Structures)\nelse:\n\tabnstruct = 20\nif args.AbInitio_Cycles:\n\tcycles = int(args.AbInitio_Cycles)\nelse:\n\tcycles = 10\nif args.Number_of_Relax_Structures:\n\trelnstruct = int(args.Number_of_Relax_Structures)\nelse:\n\trelnstruct = 50\nif args.Refine_Subset:\n\trefine_number = int((args.Refine_Subset/100)*int(abnstruct))\nelse:\n\trefine_number = int(abnstruct)\n\t\n# Importing sequence from FASTA\nfasta_file = open(args.Input_FASTA_File, 'r')\nfasta_lines = fasta_file.readlines()\nfasta_counter = 0\nfasta_sequence = ' '\nfor fasta_line in fasta_lines:\n\tif '>' not in fasta_line:\n\t\tif fasta_counter == 0:\n\t\t\tif '\\n' in fasta_line:\n\t\t\t\tfasta_sequence = fasta_line.split('\\n')[0]\n\t\t\telse:\n\t\t\t\tfasta_sequence = fasta_line\n\t\t\tfasta_counter = 1\t\n\t\telse:\n\t\t\tif '\\n' in fasta_line:\n\t\t\t\tfasta_sequence = fasta_sequence + fasta_line.split('\\n')[0]\n\t\t\telse:\n\t\t\t\tfasta_sequence = fasta_sequence + fasta_line\n\n# The Poses\n#p=Pose()\n#make_pose_from_sequence(p, fasta_sequence, \"centroid\")\np = pose_from_sequence(fasta_sequence, \"centroid\")\nstarting_p = Pose()\nstarting_p.assign(p)\nfa_p = Pose()\nfa_p.assign(p)\npvdw = Pose()\npvdwc = Pose()\npcen = Pose()\nmaplow = MoveMap()\nmaplow.set_bb(True)\nmaplow.set_chi(True)\n\n# Score Functions\n## Preparing the Rg Score Term\n#### Determining the Per Residue Disorder Probability and Number of Segments\ndisorder_dtypes = [('res_num', np.float_), ('AA', np.unicode_, 2), ('ast', np.unicode_, 1), ('disprob', np.float_)]\ndisorder_dat = np.genfromtxt(args.Input_DisoPred_File, dtype=disorder_dtypes, delimiter=' ', skip_header=3)\ndiso_dat = np.empty((len(disorder_dat),1))\ndiso_segments = []\ndiso_cutoff = 0.5\nseg_cutoff = 10\nseg_res_counter = 0\nper_residue_disorder = 0\ndiso_current = disorder_dat[0][3]\nsegment_break_list = []\nsegment_switch = False\nfor seg_residue in range(len(disorder_dat)):\n\tif disorder_dat[seg_residue][3] >= diso_cutoff and diso_current >= diso_cutoff:\n\t\tseg_res_counter = 0\n\telif disorder_dat[seg_residue][3] < diso_cutoff and diso_current < diso_cutoff:\n\t\tseg_res_counter = 0\n\telif disorder_dat[seg_residue][3] < diso_cutoff and diso_current >= diso_cutoff:\n\t\tseg_res_counter = seg_res_counter + 1\n\telif disorder_dat[seg_residue][3] >= diso_cutoff and diso_current < diso_cutoff:\n\t\tseg_res_counter = seg_res_counter + 1\n\tif seg_res_counter > 9:\n\t\tseg_res_counter = 0\n\t\tdiso_current = disorder_dat[seg_residue][3]\n\t\tif diso_current >= diso_cutoff:\n\t\t\ttransition_id = 'order' # meaning all residues prior to end are ordered\n\t\telse:\n\t\t\ttransition_id = 'disorder' # meaning all residues prior to end are disordered\n\t\tsegment_break_list.append((seg_residue-9, transition_id))\n\tper_residue_disorder = per_residue_disorder + (disorder_dat[seg_residue][3]/float(len(disorder_dat)))\nif disorder_dat[len(disorder_dat)-1][3] >= diso_cutoff:\n\tsegment_break_list.append((len(disorder_dat), 'disorder'))\nelse:\n\tsegment_break_list.append((len(disorder_dat), 'order'))\t\n\t\n#### Computing the Mean Hydrophobicity per Residue\nscaling_info_holder = np.zeros([len(segment_break_list),5]) # Need spots for segH,segQ,frac_pos,frac_neg,seq_len -> scalvQ,scalvH,scalv,rad_gyr,seq_len => scalvQ -> sf_rg_term_potential\n\n##### Kyte, J. Doolitte, R.F. J. Mol. Biol. (1982) 157, 105-132\n##### Normalization proposed in Uversky, V.N. et. al. Proteins: Struc. Func. Gen. (2000), 41, 415-427\naa_hydro_idx = {'I':4.5, 'V':4.2, 'L':3.8, 'F':2.8, 'C':2.5, 'M':1.9, 'A':1.8, 'G':-0.4, 'T':-0.7, 'W':-0.9, 'S':-0.8, 'Y':-1.3, 'P':-1.6, 'H':-3.2, 'E':-3.5, 'Q':-3.5, 'D':-3.5, 'N':-3.5, 'K':-3.9, 'R':-4.5}\nfor diso_segment_idx, diso_segment_item in enumerate(segment_break_list):\n\tstart_res = 1\n\tif diso_segment_idx > 0:\n\t\tstart_res = segment_break_list[diso_segment_idx-1][0] + 1\n\tend_res = diso_segment_item[0] + 1\n\tseq_len = end_res-start_res\n\tpro_len = p.total_residue()\n\tscaling_info_holder[diso_segment_idx][4] = seq_len\n\tsequence_avg_H = 0\n\tfor res_idx in range(start_res-1, end_res-1, 1):\n\t\twindow_start = 0\n\t\twindow_end = 0\n\t\twindow_H_avg = 0 \n\t\tif res_idx < 5:\n\t\t\twindow_start = 0\n\t\t\twindow_end = res_idx + 1\n\t\telif pro_len - res_idx < 5:\n\t\t\twindow_start = res_idx\n\t\t\twindow_end = pro_len\n\t\telse:\n\t\t\twindow_start = res_idx - 2\n\t\t\twindow_end = res_idx + 3\n\t\twindow = p.sequence()[window_start:window_end]\t\n\t\tfor window_res_idx, window_res_item in enumerate(window):\n\t\t\twindow_H_avg = window_H_avg + ((aa_hydro_idx[str(window_res_item)]+4.5)/9.0)\n\t\twindow_H_avg = window_H_avg/(len(window))\n\t\tsequence_avg_H = sequence_avg_H + window_H_avg/scaling_info_holder[diso_segment_idx][4]\n\t\tscaling_info_holder[diso_segment_idx][0] = sequence_avg_H\n\n#### Computing the Mean Net Charge per Residue\nfor diso_segment_idx, diso_segment_item in enumerate(segment_break_list):\n\tstart_res = 1\n\tif diso_segment_idx > 0:\n\t\tstart_res = segment_break_list[diso_segment_idx-1][0] + 1\n\tend_res = diso_segment_item[0] + 1\n\tseq_len = end_res-start_res\n\tscaling_info_holder[diso_segment_idx][4] = seq_len\n\tsequence_Q = 0\n\tfrac_pos = 0 # fraction of positively charged residues Arg Lys\n\tfrac_neg = 0 # fraction of negatively charged residues Asp Glu\n\tfor res_idx in range(start_res-1, end_res-1, 1):\n\t\tres_id = p.sequence()[res_idx]\n\t\tif res_id == 'E' or res_id == 'D':\n\t\t\tfrac_neg = frac_neg + 1/seq_len\n\t\t\tsequence_Q = sequence_Q - 1/seq_len\n\t\telif res_id == 'K' or res_id == 'R':\n\t\t\tfrac_pos = frac_pos + 1/seq_len\n\t\t\tsequence_Q = sequence_Q + 1/seq_len\n\t\telse:\n\t\t\tcontinue\n\tsequence_Q = np.sqrt(sequence_Q**2)\n\tscaling_info_holder[diso_segment_idx][1] = sequence_Q\n\tscaling_info_holder[diso_segment_idx][2] = frac_pos\n\tscaling_info_holder[diso_segment_idx][3] = frac_neg\n\n#### Calculations from Hofmann, H. et al. PNAS (2012) 109, 40, 16155-16160\n##### Compute charge and hydrophobicity scaling options\n###### Constants\nscalv = 0\ncon_a = 0.394\ncon_z = 0.09\ncon_x0 = 0.114\ncon_c = 1.72\ncon_d = 0.9\n\n###### Calculations\n###### Folded vs Unfolded\n###### From Uversky, if sequence_Q < 2.785*sequence_avg_H - 1.151 -> Folded, but fails for synuclein\nfor QH_set_idx in range(len(scaling_info_holder)):\n\tif 'ordered' in segment_break_list[QH_set_idx]:\n\t\tscaling_info_holder[QH_set_idx][0] = 0.33\n\t\tscaling_info_holder[QH_set_idx][1] = 0.33\n\telse:\n\t\tscalv_Q = (1.0/3.0) + con_a*((1+np.exp(con_x0-scaling_info_holder[QH_set_idx][1]/con_z))**(-1))\n\t\tscaling_info_holder[QH_set_idx][1] = scalv_Q\n\t\tscalv_H = (1.0/3.0) + con_a*((1+np.exp((con_x0+con_c*scaling_info_holder[QH_set_idx][0]-con_d)/con_z))**(-1)) \n\t\tscaling_info_holder[QH_set_idx][0] = scalv_H\n\t\n###### Determining the appropriate scaling value\n####### Constants\nelemchar = 1.602*10**(-19)\nss_eo = 8.854*10**(-12)\nss_er = 78.7 #permittivity of water at 298 K\nss_kb = 1.38*10**(-23) # boltzmann constant\nss_T = 298 # in Kelvin\nss_I = 0.15 # in Molar\nss_kappa = 1/(0.304*np.sqrt(ss_I)) # in nanometers\nss_lB = (elemchar**2)/(4*np.pi*ss_eo*ss_er*ss_kb*ss_T)\n\n####### Calculation\nfor QH_set_idx in range(len(scaling_info_holder)):\n\tscalvstar = ((4*np.pi*ss_lB*((scaling_info_holder[QH_set_idx][2]-scaling_info_holder[QH_set_idx][3])**2))/(ss_kappa**2)) - ((np.pi*ss_lB*((scaling_info_holder[QH_set_idx][2]+scaling_info_holder[QH_set_idx][3])**2))/(ss_kappa))\n\tif scaling_info_holder[QH_set_idx][2] == 0:\n\t\tif scaling_info_holder[QH_set_idx][3] == 0:\n\t\t\tscalv = scaling_info_holder[QH_set_idx][0]\n\t\telse:\n\t\t\tscalv = scaling_info_holder[QH_set_idx][1]\n\telif scaling_info_holder[QH_set_idx][3] == 0:\n\t\tif scaling_info_holder[QH_set_idx][2] == 0:\n\t\t\tscalv = scaling_info_holder[QH_set_idx][0]\n\t\telse:\n\t\t\tscalv = scaling_info_holder[QH_set_idx][1]\n\telif scalvstar < 0:\n\t\tscalv = scaling_info_holder[QH_set_idx][1]\n\telse:\n\t\tscalv = scaling_info_holder[QH_set_idx][0]\n\tscaling_info_holder[QH_set_idx][2] = scalv\n\n##### Computing the Expected Radius of Gyration\nrg_b = 0.38 # in nanometers\nrg_lp = 0.53 # in nanometers\nfor QH_set_idx in range(len(scaling_info_holder)):\n\trad_gyr = (np.sqrt((2*rg_lp*rg_b)/((2*scaling_info_holder[QH_set_idx][2]+1)*(2*scaling_info_holder[QH_set_idx][2]+2)))*(scaling_info_holder[QH_set_idx][4]**scaling_info_holder[QH_set_idx][2]))*10 # in Angstroms\n\tscaling_info_holder[QH_set_idx][3] = rad_gyr\n\t\n## Making the Actual Potential Energy Function\n## Constants for Probability\ngamma = 1.1615\n\n## Concocting the Potential\ndef pr_saw(var_a, input_vars):\n\tr, rg, g, delta = input_vars\n\treturn (var_a[0]*4*np.pi/rg)*((r/rg)**(2+g))*np.exp(-var_a[1]*((r/rg)**delta))\n\t\ndef solve_pr_saw(var_a, *input_vars):\n\tr, rg, g, delta = input_vars\n\treturn (np.sum((var_a[0]*4*np.pi/rg)*((r/rg)**(2+g))*np.exp(-var_a[1]*((r/rg)**delta)))-1, np.sum((var_a[0]*4*np.pi/rg)*((r/rg)**(2+g))*np.exp(-var_a[1]*((r/rg)**delta))*(r**2))-rg**2)\n\nrg_sf_term_potential_list = []\nfor QH_set_idx in range(len(scaling_info_holder)):\n\tvar_g = (gamma-1)/scaling_info_holder[QH_set_idx][2]\n\tvar_delta = 1/(1-scaling_info_holder[QH_set_idx][2])\n\tr_set=np.arange(0.0,5*scaling_info_holder[QH_set_idx][3],0.01)\n\tsaw_inputs = (r_set, scaling_info_holder[QH_set_idx][3], var_g, var_delta)\n\ta0 = [1.0, 1.0]\n\ta1 = op.fsolve(solve_pr_saw,a0,args=saw_inputs)\n\trg_sf_term_potential = interp1d(r_set, (1-(pr_saw(a1, saw_inputs)/np.max(pr_saw(a1, saw_inputs)))))\n\trg_sf_term_potential_list.append(rg_sf_term_potential)\n\n## Making the Actual Score Term\nfrom pyrosetta.rosetta.core.scoring.methods import ContextIndependentOneBodyEnergy ## newer versions make this pyrosetta.rosetta\n@pyrosetta.EnergyMethod() ## for newer versions make pyrosetta.EnergyMethod()\nclass SeqCorrRgMethod(WholeStructureEnergy):\n\t\"\"\"A scoring method that using a predicted radius of gyration from the\n\tprimary sequence to construct a polymer-scaled potential\n\t\n\t\"\"\"\n\tdef __init__(self):\n\t\t\"\"\"Construct LengthScoreMethod.\"\"\"\n\t\tWholeStructureEnergy.__init__(self, self.creator())\n\t\t\n\tdef finalize_total_energy(self, pose, sfxn, emap):\n\t\t\"\"\"Calculate energy of res of pose and emap\"\"\"\n\t\tpose = pose ## for newer versions remove line\n\t\te_val = 0\n\t\tfor segment_idx in range(len(segment_break_list)):\n\t\t\tr_xyz = np.zeros([int(scaling_info_holder[segment_idx][4]), 3])\n\t\t\trg_sq = np.zeros([int(scaling_info_holder[segment_idx][4]), 1])\n\t\t\tstart_res = 1\n\t\t\tif segment_idx > 0:\n\t\t\t\tstart_res = segment_break_list[segment_idx-1][0] + 1\n\t\t\tend_res = segment_break_list[segment_idx][0] + 1\n\t\t\tfor res_num in range(start_res, end_res, 1):\n\t\t\t\tfor res_xyz in range(len(r_xyz[0])):\n\t\t\t\t\tr_xyz[res_num-start_res][res_xyz] = pose.residue(res_num).nbr_atom_xyz()[res_xyz]\n\t\t\tr_cen_mass = np.average(r_xyz, axis=0)\n\t\t\tfor res_num in range(len(r_xyz)):\n\t\t\t\trg_sq[res_num] = (np.linalg.norm(r_xyz[res_num] - r_cen_mass))**2\n\t\t\trg_val = np.sqrt(np.average(rg_sq))\n\t\t\trg_sf_term_potential = rg_sf_term_potential_list[segment_idx]\n\t\t\te_val = e_val + float(rg_sf_term_potential(rg_val))\n\t\temap.set(self.scoreType, e_val) ## for newer versions remove .get()\n\t\t\nnew_rg_score = SeqCorrRgMethod.scoreType\n\n## DSSP-based Reweighting Score Terms\ndssp = rosetta.protocols.moves.DsspMover()\ndssp_E_weight = 0.0\ndssp_L_weight = 0.0\ndssp_H_weight = 0.0\n\nif args.Residue_Weight_Sheet:\n\tdssp_E_weight = 1.0 - float(args.Residue_Weight_Sheet)\nelse:\n\tdssp_E_weight = 0.0\n\t\nif args.Residue_Weight_Loop:\n\tdssp_L_weight = 1.0 - float(args.Residue_Weight_Loop)\nelse:\n\tdssp_L_weight = 0.5\n\t\nif args.Residue_Weight_Helix:\n\tdssp_H_weight = 1.0 - float(args.Residue_Weight_Helix)\nelse:\n\tdssp_H_weight = 0.5\t\n\nsec_struct_weight = {'L':float(dssp_L_weight), 'H':float(dssp_H_weight), 'E':float(dssp_E_weight)}\n\n### Preparing Unweighted Score Functions\nsf_env = ScoreFunction()\nsf_env.set_weight(env, 1.0)\n\nsf_pair = ScoreFunction()\nsf_pair.set_weight(pair, 1.0)\n\nsf_cbeta = ScoreFunction()\nsf_cbeta.set_weight(cbeta, 1.0)\n\n### Centroid DSSP Weighted Pair Term\n@pyrosetta.EnergyMethod()\nclass SecondaryStructurePenalty(ContextIndependentTwoBodyEnergy):\n\t\"\"\"A scoring method that assigns different score weights to residues\n\tdepending on the secondary structure.\n\t\n\t\"\"\"\t\n\tdef __init__(self):\n\t\t\"\"\"Construct LengthScoreMethod.\"\"\"\n\t\tContextIndependentTwoBodyEnergy.__init__(self, self.creator())\n\t\t\n\tdef setup_for_scoring(self, pose, sf):\n\t\tpose = pose\n\t\tdssp.apply(pose)\n\t\t\n\tdef defines_intrares_energy(self, weights):\n\t\t\"\"\"Return True if intra-residue energy is Defined.\"\"\"\n\t\treturn True\n\t\t\n\tdef eval_intrares_energy(self, res, pose, sf, emap):\n\t\t\"\"\"Calculate intra-residue energy if defined.\"\"\"\n\t\tpose = pose\n\t\temv = EMapVector()\n\t\tsf_env.eval_cd_1b(res,pose,emv)\n\t\tweighted_score_env = emv[env]*sec_struct_weight[pose.secstruct()[res.seqpos()-1]]\n\t\tsf_cbeta.eval_cd_1b(res,pose,emv)\n\t\tweighted_score_cbeta = emv[cbeta]*sec_struct_weight[pose.secstruct()[res.seqpos()-1]]\n\t\tweighted_score = -1*(weighted_score_env + weighted_score_cbeta)\n\t\temap.set(self.scoreType, weighted_score)\n\t\t\n\t\n\tdef atomic_interaction_cutoff(self):\n\t\t\"\"\"Get the cutoff.\"\"\"\n\t\treturn 0.0\n\t\t\n\tdef residue_pair_energy(self, res1, res2, pose, sf, emap):\n\t\t\"\"\"Calculate energy of res of pose and set emap\"\"\"\n\t\tpose = pose\n\t\temv = EMapVector()\n\t\tsf_pair.eval_ci_2b(res1,res2,pose,emv)\n\t\tweighted_score = -1*(emv[pair]*sec_struct_weight[pose.secstruct()[res1.seqpos()-1]]*sec_struct_weight[pose.secstruct()[res2.seqpos()-1]])\n\t\temap.set(self.scoreType, weighted_score)\n\nsecstrucpenalty_score = SecondaryStructurePenalty.scoreType\n\n## Preparing Score Functions\nif args.Rg_Weight:\n\trg_reweight_factor = args.Rg_Weight\nelse:\n\trg_reweight_factor = 0.5\n\t\nsf0 = create_score_function('score0')\nsf_stage_1 = create_score_function('score0')\n\nsf_stage_2 = create_score_function('score1')\nif args.AbInitioVO == True:\n\tsf_stage_2.set_weight(new_rg_score, ((400/24)*5))\nsf_stage_2.set_weight(secstrucpenalty_score, 1.0)\n\t\nsf_stage_3a = create_score_function('score2')\nif args.AbInitioVO == True:\n\tsf_stage_3a.set_weight(new_rg_score, ((400/24)*5))\nsf_stage_3a.set_weight(secstrucpenalty_score, 1.0)\n\nsf_stage_3b = create_score_function('score5')\nif args.AbInitioVO == True:\n\tsf_stage_3b.set_weight(new_rg_score, ((400/24)*5))\nsf_stage_3b.set_weight(secstrucpenalty_score, 1.0)\n\nsf_stage_4 = create_score_function('score3')\nif args.AbInitioVO == True:\n\tsf_stage_4.set_weight(rg, 0.0)\n\tsf_stage_4.set_weight(new_rg_score, ((400/24)*5))\nelse:\n\tsf_stage_4.set_weight(rg, sf_stage_4.get_weight(rg)*rg_reweight_factor)\nsf_stage_4.set_weight(hbond_sr_bb, 1.0)\nsf_stage_4.set_weight(hbond_lr_bb, 1.0)\nsf_stage_4.set_weight(rama, 1.0)\nsf_stage_4.set_weight(secstrucpenalty_score, 1.0)\n\n## Setting Up Stage 4\nsf_stage_4_term_list = [vdw, hbond_sr_bb, hbond_lr_bb, rama, new_rg_score]\ncen_score_holder_dtypes = [('out_name', np.unicode_, 100)]\nfor score_4_term in range(len(sf_stage_4_term_list)):\n\tcen_score_holder_dtypes.append((str(sf_stage_4_term_list[score_4_term]), float))\ncen_score_holder = np.zeros([int(abnstruct)], dtype=cen_score_holder_dtypes)\n\n## Full Atom Score Functions\nsfbeta = create_score_function('ref2015')\nsfrelax = create_score_function('ref2015_cart')\n\n## Radius of Gyration Reference Score Function\nsfrg = ScoreFunction()\nsfrg.set_weight(rg, 1.0)\n\n# The Movers\n## Fragment Movers\n# Importing the fragment files\nfragset9 = ConstantLengthFragSet(9)\nfragset9.read_fragment_file(args.Nine_Mer_Frag_Library)\nfragset3 = ConstantLengthFragSet(3)\nfragset3.read_fragment_file(args.Three_Mer_Frag_Library)\n\n# Constructing the Fragment Mover\nfragmover9 = ClassicFragmentMover(fragset9, maplow)\nfragmover3 = ClassicFragmentMover(fragset3, maplow)\ngunncost = GunnCost()\nsmoothfragmover3 = SmoothFragmentMover(fragset3, maplow, gunncost)\n\n## Phi-Psi Movers\nsmMovercen = SmallMover(maplow, 0.8, 1)\nshMovercen = ShearMover(maplow, 0.8, 1)\nsmMovercen.angle_max(\"H\", 2.0)\nsmMovercen.angle_max(\"E\", 2.0)\nsmMovercen.angle_max(\"L\", 5.0)\nshMovercen.angle_max(\"H\", 2.0)\nshMovercen.angle_max(\"E\", 2.0)\nshMovercen.angle_max(\"L\", 5.0)\n\nsmMoverfa = SmallMover(maplow, 0.8, 1)\nshMoverfa = ShearMover(maplow, 0.8, 1)\nsmMoverfa.angle_max(\"H\", 2.0)\nsmMoverfa.angle_max(\"E\", 2.0)\nsmMoverfa.angle_max(\"L\", 5.0)\nshMoverfa.angle_max(\"H\", 2.0)\nshMoverfa.angle_max(\"E\", 2.0)\nshMoverfa.angle_max(\"L\", 5.0)\n\n##Random Movers\nrandom_stage_1 = RandomMover()\nrandom_stage_1.add_mover(fragmover9)\n\nrandom_stage_2 = RandomMover()\nrandom_stage_2.add_mover(fragmover9)\n\nrandom_stage_3 = RandomMover()\nrandom_stage_3.add_mover(fragmover9)\n\nrandom_stage_4a = RandomMover()\nrandom_stage_4a.add_mover(fragmover3)\n\nrandom_stage_4b = RandomMover()\nrandom_stage_4b.add_mover(smoothfragmover3)\n\n\n# Relax Mover\nrelax = rosetta.protocols.relax.FastRelax()\nrelax.min_type('lbfgs_armijo_nonmonotone')\nrelax.dualspace(True)\nrelax.set_scorefxn(sfrelax)\nrelax.max_iter(200)\n\n# The Monte Carlo\n## PyRosetta Monte Carlo Objects\nmc_stage_1 = MonteCarlo(p, sf_stage_1, 2.0)\nmc_stage_2 = MonteCarlo(p, sf_stage_2, 2.0)\nmc_stage_3a = MonteCarlo(p, sf_stage_3a, 2.0)\nmc_stage_3b = MonteCarlo(p, sf_stage_3b, 2.0)\nmc_stage_4 = MonteCarlo(p, sf_stage_4, 2.0)\n\n## Setting up Trial Movers\ntrial_stage_1 = TrialMover(random_stage_1, mc_stage_1)\ntrial_stage_2 = TrialMover(random_stage_2, mc_stage_2)\ntrial_stage_3a = TrialMover(random_stage_3, mc_stage_3a)\ntrial_stage_3b = TrialMover(random_stage_3, mc_stage_3b)\ntrial_stage_4a = TrialMover(random_stage_4a, mc_stage_4)\ntrial_stage_4b = TrialMover(random_stage_4b, mc_stage_4)\n\n## Setting up Repeat Movers\nstage1 = RepeatMover(trial_stage_1, 2000)\nstage2 = RepeatMover(trial_stage_2, 2000)\nstage3a = RepeatMover(trial_stage_3a, 4000)\nstage3b = RepeatMover(trial_stage_3b, 4000)\nstage4a = RepeatMover(trial_stage_4a, 4000)\nstage4b = RepeatMover(trial_stage_4b, 4000)\n\n# Converting the Pose\nswitch = SwitchResidueTypeSetMover('fa_standard')\n\n# Side-Chain Movers\nswitch.apply(fa_p)\ntask = standard_packer_task(fa_p)\ntask.restrict_to_repacking()\npack_mover = PackRotamersMover(sfbeta, task)\nrot_mover = RotamerTrialsMover(sfbeta, task)\n\n# The Simulation and Output\nfor i in range(int(abnstruct)):\n\t# Setting up the Input Structure\n\tp.assign(starting_p)\n\tfor pose_res_num in range(p.total_residue()):\n\t\tp.set_phi(pose_res_num+1,-150)\n\t\tp.set_psi(pose_res_num+1,150)\n\t\tp.set_omega(pose_res_num+1,180)\n\tmc_stage_1.reset(p)\n\tmc_stage_2.reset(p)\n\tmc_stage_3a.reset(p)\n\tmc_stage_3b.reset(p)\n\tmc_stage_4.reset(p)\n\tfor j in range(cycles):\n\t\tprint('Performing Stage 1 Sampling: Phase: ' + str(j))\n\t\tsf_env.set_weight(env, sf_stage_1.get_weight(env))\n\t\tsf_pair.set_weight(pair, sf_stage_1.get_weight(pair))\n\t\tsf_cbeta.set_weight(cbeta, sf_stage_1.get_weight(cbeta))\n\t\tstage1.apply(p)\n\t\tmc_stage_1.recover_low(p)\n\t\tsf_stage_1.show(p)\n\t\tmc_stage_1.reset(p)\n\tfor k in range(cycles):\t\n\t\tprint('Performing Stage 2 Sampling: Phase: ' + str(k))\n\t\tsf_env.set_weight(env, sf_stage_2.get_weight(env))\n\t\tsf_pair.set_weight(pair, sf_stage_2.get_weight(pair))\n\t\tsf_cbeta.set_weight(cbeta, sf_stage_2.get_weight(cbeta))\n\t\tstage2.apply(p)\n\t\tmc_stage_2.recover_low(p)\n\t\tsf_stage_2.show(p)\n\t\tmc_stage_2.reset(p)\n\tfor l in range(int(cycles/2)):\n\t\tprint('Performing Stage 3 Sampling: Phase: ' + str(l))\n\t\tif l % 2 == 0:        \n\t\t\tsf_env.set_weight(env, sf_stage_3a.get_weight(env))\n\t\t\tsf_pair.set_weight(pair, sf_stage_3a.get_weight(pair))\n\t\t\tsf_cbeta.set_weight(cbeta, sf_stage_3a.get_weight(cbeta))\n\t\t\tstage3a.apply(p)\n\t\t\tmc_stage_3a.recover_low(p)\n\t\t\tmc_stage_3a.reset(p)\n\t\telse:\n\t\t\tsf_env.set_weight(env, sf_stage_3b.get_weight(env))\n\t\t\tsf_pair.set_weight(pair, sf_stage_3b.get_weight(pair))\n\t\t\tsf_cbeta.set_weight(cbeta, sf_stage_3b.get_weight(cbeta))\n\t\t\tstage3b.apply(p)\n\t\t\tmc_stage_3b.recover_low(p)\n\t\t\tmc_stage_3b.reset(p)\n\t\tsf_stage_3b.show(p)\t\n\tfor m in range(cycles):\n\t\tprint('Performing Stage 4 Sampling: Phase: ' + str(m))\n\t\tsf_env.set_weight(env, sf_stage_4.get_weight(env))\n\t\tsf_pair.set_weight(pair, sf_stage_4.get_weight(pair))\n\t\tsf_cbeta.set_weight(cbeta, sf_stage_4.get_weight(cbeta))\n\t\tif m < 2:\n\t\t\tstage4a.apply(p)\n\t\t\tmc_stage_4.recover_low(p)\n\t\telse:\n\t\t\tstage4b.apply(p)\n\t\t\tmc_stage_4.recover_low(p)\n\t\tsf_stage_4.show(p)\n\t\tmc_stage_4.reset(p)\n\tfor record_idx in range(len(sf_stage_4_term_list)):\n\t\tcen_score_holder[i][record_idx] = p.energies().total_energies()[sf_stage_4_term_list[record_idx]]\n\tpcen.assign(p)\n\tif args.AbInitioVO == True:\n\t\toutf = open(\"AbInitioVO_Centroid.sc\", 'a')\n\t\tpdb_out = \"AbInitioVO_Centroid_out_%i.pdb\" %i\n\telse:\n\t\toutf = open(\"AbInitio_Centroid.sc\", 'a')\n\t\tpdb_out = \"AbInitio_Centroid_out_%i.pdb\" %i\n\tpcen.dump_pdb(pdb_out)\n\tswitch.apply(p)\n\tsfbeta.show(p)\n\toutf.write(\"%s\\t%.3f\\t%.4f\\t%.3f\\n\" % (pdb_out, sfbeta(p), sf_stage_4(pcen), sfrg(p)))\n\toutf.close()\nnp.savetxt('Centroid_Score_Breakdown.txt', cen_score_holder, fmt='%s', delimiter=' ', newline='\\n')\n\n## Deciding who to minimize\ndtype_list = [('out_name','S50'),('full_sc',float),('cen_score',float),('out_rg',float)]\nif args.AbInitioVO == True:\n\tcen_out_data = np.genfromtxt('AbInitioVO_Centroid.sc', dtype=dtype_list)\nelse:\n\tcen_out_data = np.genfromtxt('AbInitio_Centroid.sc', dtype=dtype_list)\ncen_out_sort = np.sort(cen_out_data, order='cen_score')\nfor cen_out_struct_idx in range(refine_number):\n\tcen_out_struct_item = cen_out_data[cen_out_struct_idx]['out_name']\n\trelax_p_in = pose_from_pdb(str(cen_out_struct_item.decode('UTF-8')))\n\trelax_p = Pose()\n\tprint('Relaxing Output ' + str(cen_out_struct_idx+1) + ' of ' + str(refine_number))\n\tfor relnstruct_idx in range(relnstruct):\n\t\trelax_p.assign(relax_p_in)\n\t\trelax.apply(relax_p)\n\t\tsfrelax.show(relax_p)\n\t\tif args.AbInitioVO == True:\n\t\t\toutf = open(\"AbInitioVO_FullAtom.sc\", 'a')\n\t\t\tpdb_out = \"AbInitioVO_FullAtom_out_\" + str(cen_out_struct_idx) + \"_\" + str(relnstruct_idx) + \".pdb\" \n\t\telse:\n\t\t\toutf = open(\"AbInitio_FullAtom.sc\", 'a')\n\t\t\tpdb_out = \"AbInitio_FullAtom_out_\" + str(cen_out_struct_idx) + \"_\" + str(relnstruct_idx) + \".pdb\" \n\t\toutf.write(\"%s\\t%s\\t%.4f\\t%.4f\\n\" % (pdb_out, str(cen_out_struct_item), sfrelax(relax_p), sfrg(relax_p)))\n\t\trelax_p.dump_pdb(pdb_out)\n\t\toutf.close()\n", "meta": {"hexsha": "0dc1fc5eb972b2d7614d9c446153d6b2dd8e5a4d", "size": 25322, "ext": "py", "lang": "Python", "max_stars_repo_path": "AbInitioVO_Input_Files/sic1/AbInitioVO.py", "max_stars_repo_name": "jferrie3/AbInitioVO-and-FastFloppyTail", "max_stars_repo_head_hexsha": "297fb21c0a7d1f2e97f8b7ea9d8e45509187603b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-01T07:36:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-01T08:04:06.000Z", "max_issues_repo_path": "AbInitioVO_Input_Files/1shf/AbInitioVO.py", "max_issues_repo_name": "jferrie3/AbInitioVO-and-FastFloppyTail", "max_issues_repo_head_hexsha": "297fb21c0a7d1f2e97f8b7ea9d8e45509187603b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-06-19T18:54:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-29T19:21:38.000Z", "max_forks_repo_path": "AbInitioVO_Input_Files/tauk/AbInitioVO.py", "max_forks_repo_name": "jferrie3/AbInitioVO-and-FastFloppyTail", "max_forks_repo_head_hexsha": "297fb21c0a7d1f2e97f8b7ea9d8e45509187603b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3810264386, "max_line_length": 227, "alphanum_fraction": 0.7523892268, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 8036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.15174472414765036}}
{"text": "\"\"\"\nimplementation of DDPG\n\nDPG + DQN: deterministic PG + deep Q network\nmodel-free, off-policy, actor-critic\nDQN - discrete space; DDPG - continuous space\n\nAdapted from https://github.com/sweetice/Deep-reinforcement-learning-with-pytorch/blob/master/Char05%20DDPG/DDPG.py\n\nLily Xu, 2021\n\"\"\"\n\nimport os, sys\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n\nclass Critic(nn.Module):\n    def __init__(self, input_size, output_size):\n        \"\"\"\n        input: state, action\n        output: value of each action\n        \"\"\"\n\n        hidden_size1 = 16\n        hidden_size2 = 32\n        super(Critic, self).__init__()\n        self.linear1 = nn.Linear(input_size, hidden_size1)\n        self.linear2 = nn.Linear(hidden_size1, hidden_size2)\n        self.linear3 = nn.Linear(hidden_size2, output_size)\n\n    def forward(self, state, action):\n        \"\"\"\n        params\n        state and action - both torch Tensors\n        \"\"\"\n        x = torch.cat([state, action], 1)\n        x = self.linear1(x)\n        x = F.relu(x)\n        x = self.linear2(x)\n        x = F.relu(x)\n        x = self.linear3(x)\n        return x\n\nclass Actor(nn.Module):\n    def __init__(self, input_size, output_size, learning_rate=3e-4):\n        \"\"\"\n        input: state\n        output: action to take\n        \"\"\"\n        hidden_size1 = 16\n        hidden_size2 = 32\n        super(Actor, self).__init__()\n\n        self.linear1 = nn.Linear(input_size, hidden_size1)\n        self.linear2 = nn.Linear(hidden_size1, hidden_size2)\n        self.linear3 = nn.Linear(hidden_size2, output_size)\n        self.softmax = nn.Softmax(dim=1)\n\n    def forward(self, state):\n        x = self.linear1(state)\n        x = F.relu(x)\n        x = self.linear2(x)\n        x = F.relu(x)\n        x = self.linear3(x)\n        x = self.softmax(x)\n        return x\n\n\n\n########### replay buffer\n\nimport random\nfrom collections import deque\n\nclass ReplayBuffer:\n    \"\"\" experience replay to overcome challenge of data not being independently distributed\n    during on-policy training \"\"\"\n    def __init__(self, max_size):\n        self.buffer = deque(maxlen=max_size)\n\n    def push(self, s, a, r, ss, done):\n        \"\"\" state, action, reward, next_state \"\"\"\n        experience = (s, a, r, ss, done)\n        self.buffer.append(experience)\n\n    def sample(self, batch_size):\n        batch = random.sample(self.buffer, batch_size)\n\n        s_batch    = [experience[0] for experience in batch]\n        a_batch    = [experience[1] for experience in batch]\n        r_batch    = [experience[2] for experience in batch]\n        ss_batch   = [experience[3] for experience in batch]\n        done_batch = [experience[4] for experience in batch]\n\n        return s_batch, a_batch, r_batch, ss_batch, done_batch\n\n    def __len__(self):\n        return len(self.buffer)\n\n\n# https://github.com/openai/gym/blob/master/gym/core.py\nclass NormalizedEnv:\n    \"\"\" Wrap action \"\"\"\n\n    def _action(self, action):\n        act_k = (self.action_space.high - self.action_space.low)/ 2.\n        act_b = (self.action_space.high + self.action_space.low)/ 2.\n        return act_k * action + act_b\n\n    def _reverse_action(self, action):\n        act_k_inv = 2./(self.action_space.high - self.action_space.low)\n        act_b = (self.action_space.high + self.action_space.low)/ 2.\n        return act_k_inv * (action - act_b)\n\n\n\nclass DDPG:\n    def __init__(self, n_targets, actor_learning_rate=1e-4,\n        critic_learning_rate=1e-3, gamma=0.99, tau=1e-2,\n        memory_max_size=50000):\n\n        # params\n        self.states_dim = 2 * n_targets + 1\n        self.actions_dim = n_targets\n        self.gamma = gamma\n        self.tau = tau\n\n        ##### networks\n        # randomly initialize critic and actor network\n        self.actor         = Actor(self.states_dim, self.actions_dim)\n        self.critic        = Critic(self.states_dim + self.actions_dim, 1)\n\n        # initialize critic and actor target network\n        self.actor_target  = Actor(self.states_dim, self.actions_dim)\n        self.critic_target = Critic(self.states_dim + self.actions_dim, 1)\n\n        for target_param, param in zip(self.actor_target.parameters(), self.actor.parameters()):\n            target_param.data.copy_(param.data)\n\n        for target_param, param in zip(self.critic_target.parameters(), self.critic.parameters()):\n            target_param.data.copy_(param.data)\n\n        self.actor_optimizer  = torch.optim.Adam(self.actor.parameters(), lr=actor_learning_rate)\n        self.critic_optimizer = torch.optim.Adam(self.critic.parameters(), lr=critic_learning_rate)\n\n        self.memory = ReplayBuffer(memory_max_size)\n        self.loss = nn.MSELoss()\n\n\n    def select_action(self, state):\n        if not torch.is_tensor(state):\n            state = torch.from_numpy(state).float().unsqueeze(0)\n        else:\n            state = state.float().unsqueeze(0)\n        action = self.actor.forward(state)\n        action = action.detach().numpy()[0]\n        return action\n\n\n    def update(self, batch_size):\n        states, actions, rewards, next_states, dones = self.memory.sample(batch_size)\n        states      = torch.FloatTensor(states)\n        actions     = torch.FloatTensor(actions)\n        rewards     = torch.FloatTensor(rewards)\n        next_states = torch.FloatTensor(next_states)\n\n        # update critic by minimizing loss\n        Q_vals = self.critic.forward(states, actions)\n        next_actions = self.actor_target.forward(next_states)\n        next_Q = self.critic_target.forward(next_states, next_actions.detach())\n        Q_prime = rewards + self.gamma * next_Q\n\n        critic_loss = self.loss(Q_vals, Q_prime)\n        self.critic_optimizer.zero_grad()\n        critic_loss.backward()\n        self.critic_optimizer.step()\n\n        # update actor policy using sampled policy gradient\n        policy_loss = -self.critic.forward(states, self.actor.forward(states)).mean()\n        self.actor_optimizer.zero_grad()\n        policy_loss.backward()\n        self.actor_optimizer.step()\n\n        # update target networks (slowly using soft updates)\n        for target_param, param in zip(self.actor_target.parameters(), self.actor.parameters()):\n            target_param.data.copy_(self.tau * param.data + (1. - self.tau) * target_param.data)\n\n        for target_param, param in zip(self.critic_target.parameters(), self.critic.parameters()):\n            target_param.data.copy_(self.tau * param.data + (1. - self.tau) * target_param.data)\n", "meta": {"hexsha": "35ff4cde5d432dbfdcbb8043c1f07287f1b39472", "size": 6461, "ext": "py", "lang": "Python", "max_stars_repo_path": "ddpg.py", "max_stars_repo_name": "lily-x/mirror", "max_stars_repo_head_hexsha": "ef2dfe19e8bfff49aeaeb46e39cbc65fa2c8f701", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-06-17T11:22:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T17:47:01.000Z", "max_issues_repo_path": "ddpg.py", "max_issues_repo_name": "lily-x/mirror", "max_issues_repo_head_hexsha": "ef2dfe19e8bfff49aeaeb46e39cbc65fa2c8f701", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ddpg.py", "max_forks_repo_name": "lily-x/mirror", "max_forks_repo_head_hexsha": "ef2dfe19e8bfff49aeaeb46e39cbc65fa2c8f701", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-16T07:01:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T07:01:11.000Z", "avg_line_length": 33.1333333333, "max_line_length": 115, "alphanum_fraction": 0.6413867822, "include": true, "reason": "import numpy", "num_tokens": 1499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.29421498454004374, "lm_q1q2_score": 0.15170310553298572}}
{"text": "import tensorflow as tf\r\nimport scipy.io as sio\r\nimport numpy as np\r\nfrom PIL import Image\r\n\r\nimg_H = 64\r\nimg_W = 64\r\nimg_C = 3\r\nGAN_type = \"SNGAN\"  # DCGAN, WGAN, WGAN-GP, SNGAN, LSGAN, RSGAN, RaSGAN\r\nbatchsize = 128\r\nepsilon = 1e-14#if epsilon is too big, training of DCGAN is failure.\r\n\r\ndef deconv(inputs, shape, strides, out_num, is_sn=False):\r\n    filters = tf.get_variable(\"kernel\", shape=shape, initializer=tf.random_normal_initializer(stddev=0.02))\r\n    bias = tf.get_variable(\"bias\", shape=[shape[-2]], initializer=tf.constant_initializer([0]))\r\n    if is_sn:\r\n        return tf.nn.conv2d_transpose(inputs, spectral_norm(\"sn\", filters), out_num, strides) + bias\r\n    else:\r\n        return tf.nn.conv2d_transpose(inputs, filters, out_num, strides) + bias\r\n\r\ndef conv(inputs, shape, strides, is_sn=False):\r\n    filters = tf.get_variable(\"kernel\", shape=shape, initializer=tf.random_normal_initializer(stddev=0.02))\r\n    bias = tf.get_variable(\"bias\", shape=[shape[-1]], initializer=tf.constant_initializer([0]))\r\n    if is_sn:\r\n        return tf.nn.conv2d(inputs, spectral_norm(\"sn\", filters), strides, \"SAME\") + bias\r\n    else:\r\n        return tf.nn.conv2d(inputs, filters, strides, \"SAME\") + bias\r\n\r\ndef fully_connected(inputs, num_out, is_sn=False):\r\n    W = tf.get_variable(\"W\", [inputs.shape[-1], num_out], initializer=tf.random_normal_initializer(stddev=0.02))\r\n    b = tf.get_variable(\"b\", [num_out], initializer=tf.constant_initializer([0]))\r\n    if is_sn:\r\n        return tf.matmul(inputs, spectral_norm(\"sn\", W)) + b\r\n    else:\r\n        return tf.matmul(inputs, W) + b\r\n\r\ndef leaky_relu(inputs, slope=0.2):\r\n    return tf.maximum(slope*inputs, inputs)\r\n\r\ndef spectral_norm(name, w, iteration=1):\r\n    #Spectral normalization which was published on ICLR2018,please refer to \"https://www.researchgate.net/publication/318572189_Spectral_Normalization_for_Generative_Adversarial_Networks\"\r\n    #This function spectral_norm is forked from \"https://github.com/taki0112/Spectral_Normalization-Tensorflow\"\r\n    w_shape = w.shape.as_list()\r\n    w = tf.reshape(w, [-1, w_shape[-1]])\r\n    with tf.variable_scope(name, reuse=False):\r\n        u = tf.get_variable(\"u\", [1, w_shape[-1]], initializer=tf.truncated_normal_initializer(), trainable=False)\r\n    u_hat = u\r\n    v_hat = None\r\n\r\n    def l2_norm(v, eps=1e-12):\r\n        return v / (tf.reduce_sum(v ** 2) ** 0.5 + eps)\r\n\r\n    for i in range(iteration):\r\n        v_ = tf.matmul(u_hat, tf.transpose(w))\r\n        v_hat = l2_norm(v_)\r\n        u_ = tf.matmul(v_hat, w)\r\n        u_hat = l2_norm(u_)\r\n    sigma = tf.matmul(tf.matmul(v_hat, w), tf.transpose(u_hat))\r\n    w_norm = w / sigma\r\n    with tf.control_dependencies([u.assign(u_hat)]):\r\n        w_norm = tf.reshape(w_norm, w_shape)\r\n    return w_norm\r\n\r\ndef mapping(x):\r\n    max = np.max(x)\r\n    min = np.min(x)\r\n    return (x - min) * 255.0 / (max - min + epsilon)\r\n\r\ndef instanceNorm(inputs):\r\n    mean, var = tf.nn.moments(inputs, axes=[1, 2], keep_dims=True)\r\n    scale = tf.get_variable(\"scale\", shape=mean.shape[-1], initializer=tf.constant_initializer([1.0]))\r\n    shift = tf.get_variable(\"shift\", shape=mean.shape[-1], initializer=tf.constant_initializer([0.0]))\r\n    return (inputs - mean) * scale / (tf.sqrt(var + epsilon)) + shift\r\n\r\nclass Generator:\r\n    def __init__(self, name):\r\n        self.name = name\r\n\r\n    def __call__(self, Z):\r\n        with tf.variable_scope(name_or_scope=self.name, reuse=False):\r\n            with tf.variable_scope(name_or_scope=\"linear\"):\r\n                inputs = tf.reshape(tf.nn.relu((fully_connected(Z, 4*4*512))), [batchsize, 4, 4, 512])\r\n            with tf.variable_scope(name_or_scope=\"deconv1\"):\r\n                inputs = tf.nn.relu(instanceNorm(deconv(inputs, [5, 5, 256, 512], [1, 2, 2, 1], [batchsize, 8, 8, 256])))\r\n            with tf.variable_scope(name_or_scope=\"deconv2\"):\r\n                inputs = tf.nn.relu(instanceNorm(deconv(inputs, [5, 5, 128, 256], [1, 2, 2, 1], [batchsize, 16, 16, 128])))\r\n            with tf.variable_scope(name_or_scope=\"deconv3\"):\r\n                inputs = tf.nn.relu(instanceNorm(deconv(inputs, [5, 5, 64, 128], [1, 2, 2, 1], [batchsize, 32, 32, 64])))\r\n            if img_H == 32:\r\n                with tf.variable_scope(name_or_scope=\"deconv4\"):\r\n                    inputs = tf.nn.tanh(deconv(inputs, [5, 5, img_C, 64], [1, 1, 1, 1], [batchsize, img_H, img_W, img_C]))\r\n                return inputs\r\n            with tf.variable_scope(name_or_scope=\"deconv4\"):\r\n                 inputs = tf.nn.tanh(deconv(inputs, [5, 5, img_C, 64], [1, 2, 2, 1], [batchsize, img_H, img_W, img_C]))\r\n            if img_H == 64:\r\n                return inputs\r\n\r\n    @property\r\n    def var(self):\r\n        return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, self.name)\r\n\r\nclass Discriminator:\r\n    def __init__(self, name):\r\n        self.name = name\r\n\r\n    def __call__(self, inputs, reuse=False, is_sn=False):\r\n        with tf.variable_scope(name_or_scope=self.name, reuse=reuse):\r\n            with tf.variable_scope(\"conv1\"):\r\n                inputs = leaky_relu(conv(inputs, [5, 5, img_C, 64], [1, 2, 2, 1], is_sn))\r\n            with tf.variable_scope(\"conv2\"):\r\n                inputs = leaky_relu(instanceNorm(conv(inputs, [5, 5, 64, 128], [1, 2, 2, 1], is_sn)))\r\n            with tf.variable_scope(\"conv3\"):\r\n                inputs = leaky_relu(instanceNorm(conv(inputs, [5, 5, 128, 256], [1, 2, 2, 1], is_sn)))\r\n            with tf.variable_scope(\"conv4\"):\r\n                inputs = leaky_relu(instanceNorm(conv(inputs, [5, 5, 256, 512], [1, 2, 2, 1], is_sn)))\r\n            inputs = tf.layers.flatten(inputs)\r\n            return fully_connected(inputs, 1, is_sn)\r\n\r\n    @property\r\n    def var(self):\r\n        return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name)\r\n\r\n\r\nclass GAN:\r\n    #Architecture of generator and discriminator just like DCGAN.\r\n    def __init__(self):\r\n        self.Z = tf.placeholder(\"float\", [batchsize, 100])\r\n        self.img = tf.placeholder(\"float\", [batchsize, img_H, img_W, img_C])\r\n        D = Discriminator(\"discriminator\")\r\n        G = Generator(\"generator\")\r\n        self.fake_img = G(self.Z)\r\n        if GAN_type == \"DCGAN\":\r\n            #DCGAN, paper: UNSUPERVISED REPRESENTATION LEARNING WITH DEEP CONVOLUTIONAL GENERATIVE ADVERSARIAL NETWORKS\r\n            self.fake_logit = tf.nn.sigmoid(D(self.fake_img))\r\n            self.real_logit = tf.nn.sigmoid(D(self.img, reuse=True))\r\n            self.d_loss = - (tf.reduce_mean(tf.log(self.real_logit + epsilon)) + tf.reduce_mean(tf.log(1 - self.fake_logit + epsilon)))\r\n            self.g_loss = - tf.reduce_mean(tf.log(self.fake_logit + epsilon))\r\n            self.opt_D = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.d_loss, var_list=D.var)\r\n            self.opt_G = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.g_loss, var_list=G.var)\r\n        elif GAN_type == \"WGAN\":\r\n            #WGAN, paper: Wasserstein GAN\r\n            self.fake_logit = D(self.fake_img)\r\n            self.real_logit = D(self.img, reuse=True)\r\n            self.d_loss = -tf.reduce_mean(self.real_logit) + tf.reduce_mean(self.fake_logit)\r\n            self.g_loss = -tf.reduce_mean(self.fake_logit)\r\n            self.clip = []\r\n            for _, var in enumerate(D.var):\r\n                self.clip.append(var.assign(tf.clip_by_value(var, -0.01, 0.01)))\r\n            self.opt_D = tf.train.RMSPropOptimizer(5e-5).minimize(self.d_loss, var_list=D.var)\r\n            self.opt_G = tf.train.RMSPropOptimizer(5e-5).minimize(self.g_loss, var_list=G.var)\r\n        elif GAN_type == \"WGAN-GP\":\r\n            #WGAN-GP, paper: Improved Training of Wasserstein GANs\r\n            self.fake_logit = D(self.fake_img)\r\n            self.real_logit = D(self.img, reuse=True)\r\n            e = tf.random_uniform([batchsize, 1, 1, 1], 0, 1)\r\n            x_hat = e * self.img + (1 - e) * self.fake_img\r\n            grad = tf.gradients(D(x_hat, reuse=True), x_hat)[0]\r\n            self.d_loss = tf.reduce_mean(self.fake_logit - self.real_logit) + 10 * tf.reduce_mean(tf.square(tf.sqrt(tf.reduce_sum(tf.square(grad), axis=[1, 2, 3])) - 1))\r\n            self.g_loss = tf.reduce_mean(-self.fake_logit)\r\n            self.opt_D = tf.train.AdamOptimizer(1e-4, beta1=0., beta2=0.9).minimize(self.d_loss, var_list=D.var)\r\n            self.opt_G = tf.train.AdamOptimizer(1e-4, beta1=0., beta2=0.9).minimize(self.g_loss, var_list=G.var)\r\n        elif GAN_type == \"LSGAN\":\r\n            #LSGAN, paper: Least Squares Generative Adversarial Networks\r\n            self.fake_logit = D(self.fake_img)\r\n            self.real_logit = D(self.img, reuse=True)\r\n            self.d_loss = tf.reduce_mean(0.5 * tf.square(self.real_logit - 1) + 0.5 * tf.square(self.fake_logit))\r\n            self.g_loss = tf.reduce_mean(0.5 * tf.square(self.fake_logit - 1))\r\n            self.opt_D = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.d_loss, var_list=D.var)\r\n            self.opt_G = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.g_loss, var_list=G.var)\r\n        elif GAN_type == \"SNGAN\":\r\n            #SNGAN, paper: SPECTRAL NORMALIZATION FOR GENERATIVE ADVERSARIAL NETWORKS\r\n            self.fake_logit = tf.nn.sigmoid(D(self.fake_img, is_sn=True))\r\n            self.real_logit = tf.nn.sigmoid(D(self.img, reuse=True, is_sn=True))\r\n            self.d_loss = - (tf.reduce_mean(tf.log(self.real_logit + epsilon) + tf.log(1 - self.fake_logit + epsilon)))\r\n            self.g_loss = - tf.reduce_mean(tf.log(self.fake_logit + epsilon))\r\n            self.opt_D = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.d_loss, var_list=D.var)\r\n            self.opt_G = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.g_loss, var_list=G.var)\r\n        elif GAN_type == \"RSGAN\":\r\n            #RSGAN, paper: The relativistic discriminator: a key element missing from standard GAN\r\n            self.fake_logit = D(self.fake_img)\r\n            self.real_logit = D(self.img, reuse=True)\r\n            self.d_loss = - tf.reduce_mean(tf.log(tf.nn.sigmoid(self.real_logit - self.fake_logit) + epsilon))\r\n            self.g_loss = - tf.reduce_mean(tf.log(tf.nn.sigmoid(self.fake_logit - self.real_logit) + epsilon))\r\n            self.opt_D = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.d_loss, var_list=D.var)\r\n            self.opt_G = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.g_loss, var_list=G.var)\r\n        elif GAN_type == \"RaSGAN\":\r\n            #RaSGAN, paper: The relativistic discriminator: a key element missing from standard GAN\r\n            self.fake_logit = D(self.fake_img)\r\n            self.real_logit = D(self.img, reuse=True)\r\n            self.avg_fake_logit = tf.reduce_mean(self.fake_logit)\r\n            self.avg_real_logit = tf.reduce_mean(self.real_logit)\r\n            self.D_r_tilde = tf.nn.sigmoid(self.real_logit - self.avg_fake_logit)\r\n            self.D_f_tilde = tf.nn.sigmoid(self.fake_logit - self.avg_real_logit)\r\n            self.d_loss = - tf.reduce_mean(tf.log(self.D_r_tilde + epsilon)) - tf.reduce_mean(tf.log(1 - self.D_f_tilde + epsilon))\r\n            self.g_loss = - tf.reduce_mean(tf.log(self.D_f_tilde + epsilon)) - tf.reduce_mean(tf.log(1 - self.D_r_tilde + epsilon))\r\n            self.opt_D = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.d_loss, var_list=D.var)\r\n            self.opt_G = tf.train.AdamOptimizer(2e-4, beta1=0.5).minimize(self.g_loss, var_list=G.var)\r\n        self.sess = tf.Session()\r\n        self.sess.run(tf.global_variables_initializer())\r\n\r\n    def __call__(self):\r\n        saver = tf.train.Saver()\r\n        epoch_nums = 200\r\n        facedata = sio.loadmat(\"./TrainingSet//facedata.mat\")[\"data\"]\r\n        #For face data, i random select about 10,000 images from CelebA and resize them to 64x64 by Matlab.\r\n        for epoch in range(epoch_nums):\r\n            for i in range(facedata.__len__()//batchsize-1):\r\n                batch = facedata[i*batchsize:i*batchsize+batchsize, :, :, :] / 255.0\r\n                z = np.random.standard_normal([batchsize, 100])\r\n                d_loss = self.sess.run(self.d_loss, feed_dict={self.img: batch, self.Z: z})\r\n                g_loss = self.sess.run(self.g_loss, feed_dict={self.img: batch, self.Z: z})\r\n                self.sess.run(self.opt_D, feed_dict={self.img: batch, self.Z: z})\r\n                if GAN_type == \"WGAN\":\r\n                    self.sess.run(self.clip)#WGAN weight clipping\r\n                self.sess.run(self.opt_G, feed_dict={self.img: batch, self.Z: z})\r\n                if i % 10 == 0:\r\n                    print(\"epoch: %d, step: %d, d_loss: %g, g_loss: %g\"%(epoch, i,  d_loss, g_loss))\r\n                    z = np.random.standard_normal([batchsize, 100])\r\n                    imgs = self.sess.run(self.fake_img, feed_dict={self.img: batch, self.Z: z})\r\n                    for j in range(batchsize):\r\n                        if img_C == 1:\r\n                            Image.fromarray(np.reshape(np.uint8(mapping(imgs[j, :, :, :])), [img_H, img_W])).save(\r\n                                \"./result//\" + str(epoch) + \"_\" + str(j) + \".jpg\")\r\n                        else:\r\n                            Image.fromarray(np.uint8(mapping(imgs[j, :, :, :]))).save(\r\n                                \"./result//\" + str(epoch) + \"_\" + str(j) + \".jpg\")\r\n            saver.save(self.sess, \"./para//model.ckpt\")\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    gan = GAN()\r\n    gan()\r\n", "meta": {"hexsha": "99297f889484c22dbd3c2229425c28740ddd0757", "size": 13356, "ext": "py", "lang": "Python", "max_stars_repo_path": "GANs.py", "max_stars_repo_name": "MingtaoGuo/DCGAN_WGAN_WGAN-GP_LSGAN_SNGAN_TensorFlow", "max_stars_repo_head_hexsha": "d244aeb8dabb9729d1789ff41ce28fdb5bb201c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 149, "max_stars_repo_stars_event_min_datetime": "2019-03-26T11:20:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T15:23:06.000Z", "max_issues_repo_path": "GANs.py", "max_issues_repo_name": "MingtaoGuo/DCGAN_WGAN_WGAN-GP_LSGAN_SNGAN_TensorFlow", "max_issues_repo_head_hexsha": "d244aeb8dabb9729d1789ff41ce28fdb5bb201c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-07-22T08:30:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-06T12:01:23.000Z", "max_forks_repo_path": "GANs.py", "max_forks_repo_name": "MingtaoGuo/DCGAN_WGAN_WGAN-GP_LSGAN_SNGAN_TensorFlow", "max_forks_repo_head_hexsha": "d244aeb8dabb9729d1789ff41ce28fdb5bb201c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2019-03-31T13:59:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T02:50:58.000Z", "avg_line_length": 57.0769230769, "max_line_length": 188, "alphanum_fraction": 0.6087151842, "include": true, "reason": "import numpy,import scipy", "num_tokens": 3609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.15170310234205764}}
{"text": "import os\nimport psi4\nimport itertools\nimport subprocess\nimport numpy as np\n\n\nclass sapt(object):\n\n    def __init__(self, geometries, data, method, basis, outfile):\n        self.geometries = geometries\n        self.method = method\n        self.basis = basis\n        self.outfile = outfile\n        self.frag_A = data.frag_A\n        self.frag_B = data.frag_B\n        self.do_fsapt = data.do_fsapt\n        self.keywords = data.keywords\n        self.step_size = data.irc_stepsize\n        self.coordinates = data.coordinates\n        self.force_min = data.force_min\n        self.nthreads = data.nthreads\n        self.set_memory = data.set_memory\n        self.memory_allocation = data.memory_allocation\n        # Specifics for F-SAPT Calculations\n        if(data.do_fsapt):\n            self.monomer_A_frags = data.monomer_A_frags\n            self.monomer_B_frags = data.monomer_B_frags\n            self.monomer_A_labels = data.monomer_A_labels\n            self.monomer_B_labels = data.monomer_B_labels\n\n    def psi4_sapt(self):\n        self.int_  = []\n        self.elst_ = []\n        self.exch_ = []\n        self.ind_ =  []\n        self.disp_ = []\n        all_atoms = self.frag_A + self.frag_B\n        au_to_kcal = 627.51\n        count = 0\n        output = open(self.outfile, \"a\")\n        output.write('\\n\\n--SAPT Decomposition--\\n')\n        output.write('\\n-------------------------------------------------------------------------------------------------')\n        output.write('\\n{:>15} {:>15} {:>15} {:>15} {:>15} {:>15}\\n'.format('IRC Point', 'E_int(kcal)', 'E_elst(kcal)','E_exch(kcal)', 'E_ind(kcal)', 'E_disp(kcal)'))\n        output.write('-------------------------------------------------------------------------------------------------\\n')\n        output.close()\n        scale_sapt = False\n        # See if the user is requesting a scaled SAPT0 calculation\n        if(self.keywords['ssapt0_scale'] or self.keywords['SSAPT0_SCALE']):\n            scale_sapt = True\n        for geometry in self.geometries:\n            output = open(self.outfile, \"a\")\n            psi4.core.set_output_file(\"psi4_output/irc_%d_sapt.out\" %count, False)\n            geometry += \"symmetry c1\"\n            psi4.geometry(geometry)\n            # Adds fsapt capabilities\n            if(self.do_fsapt):\n                try:\n                    os.mkdir('fsapt_output')\n                except FileExistsError:\n                    pass\n                try:\n                    os.mkdir('s-fsapt_output')\n                except FileExistsError:\n                    pass\n                self.keywords['FISAPT_FSAPT_FILEPATH'] = 'fsapt_output/fsapt%d' %count\n                if(scale_sapt):\n                    self.keywords['FISAPT_FSSAPT_FILEPATH'] = 's-fsapt_output/fsapt%d' %count\n            psi4.set_options(self.keywords)\n            #print(\"pyREX:SAPT Calculation on IRC Point %d\" %(count))\n            psi4.set_num_threads(self.nthreads)\n            if(self.set_memory):\n                psi4.set_memory(self.memory_allocation)\n            e_int = psi4.energy(self.method)\n            #TODO: Actually have this create the SAPT files necessary for FSAPT partitioning. Make user options as well\n            #      for fragment definitions. Something in the sapt block.\n            if(self.do_fsapt):\n                fsaptA_outfile = open('fsapt_output/fsapt%d/fA.dat' %count, 'w+')\n                if(scale_sapt):\n                    s_fsaptA_outfile = open('s-fsapt_output/fsapt%d/fA.dat' %count, 'w+')\n                for i in range(len(self.monomer_A_labels)):\n                    fsaptA_outfile.write(\"%s\" %self.monomer_A_labels[i])\n                    if(scale_sapt):\n                        s_fsaptA_outfile.write(\"%s\" %self.monomer_A_labels[i])\n                    for j in range(len(self.monomer_A_frags[i])):\n                        if(j==len(self.monomer_A_frags[i])-1):\n                            fsaptA_outfile.write(\" %d \\n\" %(all_atoms.index(self.monomer_A_frags[i][j])+1))\n                            if(scale_sapt):\n                                s_fsaptA_outfile.write(\" %d \\n\" %(all_atoms.index(self.monomer_A_frags[i][j])+1))\n                        else:\n                            fsaptA_outfile.write(\" %d \" %(all_atoms.index(self.monomer_A_frags[i][j])+1))\n                            if(scale_sapt):\n                                s_fsaptA_outfile.write(\" %d \" %(all_atoms.index(self.monomer_A_frags[i][j])+1))\n                fsaptA_outfile.close()\n                s_fsaptA_outfile.close()\n                fsaptB_outfile = open('fsapt_output/fsapt%d/fB.dat' %count, 'w+')\n                if(scale_sapt):\n                    s_fsaptB_outfile = open('s-fsapt_output/fsapt%d/fB.dat' %count, 'w+')\n                for i in range(len(self.monomer_B_labels)):\n                    fsaptB_outfile.write(\"%s\" %self.monomer_B_labels[i])\n                    if(scale_sapt):\n                        s_fsaptB_outfile.write(\"%s\" %self.monomer_B_labels[i])\n                    for j in range(len(self.monomer_B_frags[i])):\n                        if(j==len(self.monomer_B_frags[i])-1):\n                            fsaptB_outfile.write(\" %d \\n\" %(all_atoms.index(self.monomer_B_frags[i][j])+1))\n                            if(scale_sapt):\n                                s_fsaptB_outfile.write(\" %d \\n\" %(all_atoms.index(self.monomer_B_frags[i][j])+1))\n                        else:\n                            fsaptB_outfile.write(\" %d \" %(all_atoms.index(self.monomer_B_frags[i][j])+1))\n                            if(scale_sapt):\n                                s_fsaptB_outfile.write(\" %d \" %(all_atoms.index(self.monomer_B_frags[i][j])+1))\n                fsaptB_outfile.close()\n                s_fsaptB_outfile.close()\n            e_int =  psi4.core.variable(\"SAPT TOTAL ENERGY\")\n            e_elst = psi4.core.variable(\"SAPT ELST ENERGY\")\n            e_exch = psi4.core.variable(\"SAPT EXCH ENERGY\")\n            e_ind  = psi4.core.variable(\"SAPT IND ENERGY\")\n            e_disp = psi4.core.variable(\"SAPT DISP ENERGY\")\n\n            self.int_.append(e_int)\n            self.elst_.append(e_elst)\n            self.exch_.append(e_exch)\n            self.ind_.append(e_ind)\n            self.disp_.append(e_disp)\n            output.write('\\n{:>15} {:>15.4f} {:>15.4f} {:>15.4f} {:>15.4f} {:>15.4f}\\n'.format(count, e_int*au_to_kcal, e_elst*au_to_kcal, e_exch*au_to_kcal, e_ind*au_to_kcal, e_disp*au_to_kcal))\n            count = count+1\n        output.write('-------------------------------------------------------------------------------------\\n')\n        output.close()\n        return self.int_, self.elst_, self.exch_, self.ind_, self.disp_\n\n    def psi4_super(self):\n        self.int_  = []\n        all_atoms = self.frag_A + self.frag_B\n        au_to_kcal = 627.51\n        count = 0\n        output = open(self.outfile, \"a\")\n        output.write('\\n\\n--Supermolecular Interaction Energy--\\n')\n        output.write('\\n-------------------------------------------------------------------------------------------------')\n        output.write('\\n{:>15} {:>15}\\n'.format('IRC Point', 'E_int(kcal)'))\n        output.write('-------------------------------------------------------------------------------------------------\\n')\n        output.close()\n        for geometry in self.geometries:\n            output = open(self.outfile, \"a\")\n            psi4.core.set_output_file(\"psi4_output/irc_%d_sapt.out\" %count, False)\n            geometry += \"symmetry c1\"\n            psi4.geometry(geometry)\n            psi4.set_options({'reference': 'rhf', 'basis' : self.basis})\n            psi4.set_num_threads(self.nthreads)\n            if(self.set_memory):\n                psi4.set_memory(self.memory_allocation)\n            #print(\"pyREX:SAPT Calculation on IRC Point %d\" %(count))\n            e_int = psi4.energy(\"%s/%s\" %(self.method,self.basis), bsse_type='cp')\n            output.write('\\n{:>15} {:>15.4f}\\n'.format(count, e_int*au_to_kcal))\n            output.close()\n            self.int_.append(e_int)\n            count = count + 1\n        return self.int_\n\n    def fsapt_post_analysis(self):\n        fsapt_script_dir = os.environ['PSIPATH'][:-1] + '/share/psi4/fsapt/fsapt.py'\n        link_type = \"50-50\"\n        step_size = self.step_size\n        coordinates = self.coordinates\n        force_min = self.force_min\n        self.monomer_A_labels.append(\"All\")\n        self.monomer_B_labels.append(\"All\")\n        unique_pairs_list = list(itertools.product(self.monomer_A_labels,self.monomer_B_labels))\n        unique_pairs = []\n        for i in range(len(unique_pairs_list)):\n            unique_pairs.append(\"%s-%s\" %(unique_pairs_list[i][0],unique_pairs_list[i][1]))\n        print(unique_pairs)\n        # Initialize empty dictionaries to hold pair energy, force(f), and work(w) data\n        pair_elst, pair_exch, pair_indab, pair_indba, pair_disp, pair_total = ({} for i in range(6))\n        f_elst, f_exch, f_indab, f_indba, f_disp, f_total = ({} for i in range(6))\n        w_elst_1, w_exch_1, w_indab_1, w_indba_1, w_disp_1, w_total_1 = ({} for i in range(6))\n        w_elst_2, w_exch_2, w_indab_2, w_indba_2, w_disp_2, w_total_2 = ({} for i in range(6))\n\n        # Initialize empty array for every pair property\n        for pair in unique_pairs:\n            pair_elst[pair], pair_exch[pair], pair_indab[pair], pair_indba[pair], pair_disp[pair], pair_total[pair] = ([] for i in range(6))\n        os.chdir(\"fsapt_output\")\n        dirs_list = [name for name in os.listdir() if os.path.isdir(name)] \n        num_geoms = 0\n        for directory in dirs_list:\n            if(\"fsapt\" in directory):\n                num_geoms = num_geoms + 1\n        print(num_geoms)\n        for i in range(num_geoms):\n            fsapt_dir = \"fsapt%d\" %i\n            os.chdir(fsapt_dir)\n            print(\"running in %s\" %fsapt_dir)\n            subprocess.call(['python', fsapt_script_dir])\n            if(link_type==\"By Charge\"):\n                do_store = True\n            else:\n                do_store = False\n            fsapt_file = open('fsapt.dat', 'r')\n            for line in fsapt_file:\n                if(\"Reduced Analysis\" in line):\n                    if(do_store):\n                        for j in range(3):\n                            line = next(fsapt_file)\n                        for j in range(len(unique_pairs)):\n                            pair_data = line.split()\n                            pair = \"%s-%s\" %(pair_data[0],pair_data[1])\n                            elst = pair_data[2]\n                            exch = pair_data[3]\n                            indab = pair_data[4]\n                            indba = pair_data[5]\n                            disp = pair_data[6]\n                            total = pair_data[7]\n                            pair_elst[pair].append(float(elst))\n                            pair_exch[pair].append(float(exch))\n                            pair_indab[pair].append(float(indab))\n                            pair_indba[pair].append(float(indba))\n                            pair_disp[pair].append(float(disp))\n                            pair_total[pair].append(float(total))\n                            #print(pair_elst)\n                            line = next(fsapt_file)\n                    if(link_type==\"By Charge\"):\n                        do_store = False\n                    else:\n                        do_store = True\n            os.chdir(\"..\")\n        pair_dicts = [pair_elst, pair_exch, pair_indab, pair_indba, pair_disp, pair_total]\n        f_dicts = [f_elst, f_exch, f_indab, f_indba, f_disp, f_total]\n        w_dicts_1 = [w_elst_1, w_exch_1, w_indab_1, w_indba_1, w_disp_1, w_total_1]\n        w_dicts_2 = [w_elst_2, w_exch_2, w_indab_2, w_indba_2, w_disp_2, w_total_2]\n\n        for dict_ in pair_dicts:\n            index = pair_dicts.index(dict_)\n            print(index)\n            for pair in unique_pairs:\n                  f_dicts[index][pair] = -1.0*np.gradient(dict_[pair],step_size)\n        \n        \n        # Store energy data in .csv files\n        elst_csv = open(\"fsapt_elst.csv\", \"w+\")\n        exch_csv = open(\"fsapt_exch.csv\", \"w+\")\n        indab_csv = open(\"fsapt_indab.csv\", \"w+\")\n        indba_csv = open(\"fsapt_indba.csv\", \"w+\")\n        disp_csv = open(\"fsapt_disp.csv\", \"w+\")\n        total_csv = open(\"fsapt_total.csv\", \"w+\")\n\n        csv_files = [elst_csv,exch_csv,indab_csv,indba_csv,disp_csv,total_csv]\n        \n        for csv_f in csv_files:\n            index = csv_files.index(csv_f)\n            prop_dict = pair_dicts[index]\n            csv_f.write(\"Coordinate,\")\n            for pair in unique_pairs:\n                if(pair==unique_pairs[-1]):\n                    csv_f.write(\"%s,\\n\" %pair)\n                else:\n                    csv_f.write(\"%s,\" %pair)\n            for i in range(num_geoms):\n                csv_f.write(\"%f,\" %coordinates[i])\n                for pair in unique_pairs:\n                    if(pair==unique_pairs[-1]):\n                        csv_f.write(\"%.3f,\\n\" %prop_dict[pair][i])\n                    else:\n                        csv_f.write(\"%.3f,\" %prop_dict[pair][i])\n        elst_csv.close(), exch_csv.close(), indab_csv.close(), indba_csv.close(), disp_csv.close(), total_csv.close()\n\n        # Store force data in .csv files\n        f_elst_csv = open(\"force_elst.csv\", \"w+\")\n        f_exch_csv = open(\"force_exch.csv\", \"w+\")\n        f_indab_csv = open(\"force_indab.csv\", \"w+\")\n        f_indba_csv = open(\"force_indba.csv\", \"w+\")\n        f_disp_csv = open(\"force_disp.csv\", \"w+\")\n        f_total_csv = open(\"force_total.csv\", \"w+\")\n        \n        f_csv_files = [f_elst_csv,f_exch_csv,f_indab_csv,f_indba_csv,f_disp_csv,f_total_csv]\n        \n        for csv_f in f_csv_files:\n            index = f_csv_files.index(csv_f)\n            prop_dict = f_dicts[index]\n            csv_f.write(\"Coordinate,\")\n            for pair in unique_pairs:\n                if(pair==unique_pairs[-1]):\n                    csv_f.write(\"%s,\\n\" %pair)\n                else:\n                    csv_f.write(\"%s,\" %pair)\n            for i in range(num_geoms):\n                csv_f.write(\"%f,\" %coordinates[i])\n                for pair in unique_pairs:\n                    if(pair==unique_pairs[-1]):\n                        csv_f.write(\"%.3f,\\n\" %prop_dict[pair][i])\n                    else:\n                        csv_f.write(\"%.3f,\" %prop_dict[pair][i])\n        f_elst_csv.close(), f_exch_csv.close(), f_indab_csv.close(), f_indba_csv.close(), f_disp_csv.close(), f_total_csv.close()\n        \n        # Calculate Work Contributions for each Pair\n        index_min = coordinates.index(force_min)\n        f_dict_count = 0\n        for dict_ in f_dicts:\n            for pair in unique_pairs:\n                  w_dicts_1[f_dict_count][pair] = -1.0*np.trapz(dict_[pair][:index_min],dx=step_size)\n            f_dict_count = f_dict_count + 1\n        f_dict_count = 0\n        for dict_ in f_dicts:\n            for pair in unique_pairs:\n                  w_dicts_2[f_dict_count][pair] = -1.0*np.trapz(dict_[pair][index_min-1:],dx=step_size)\n            f_dict_count = f_dict_count + 1\n        \n        work_values = open(\"work_values.dat\", \"w+\")\n        work_values.write('\\n\\n--Reaction Work Decomposition (Region 1)--\\n')\n        work_values.write('\\n-----------------------------------------------------------------------------------------------------------------')\n        work_values.write('\\n{:>15} {:>15} {:>15} {:>15} {:>15} {:>15} {:>15}\\n'.format('Pair(A-B)','W_elst','W_exch',\n        'W_indAB', 'W_indBA', 'W_disp', 'W_total'))\n        work_values.write('-----------------------------------------------------------------------------------------------------------------\\n')\n        for pair in unique_pairs:\n            work_values.write('\\n{:>15s} {:>15.5f} {:>15.5f} {:>15.5f} {:>15.5f} {:>15.5f} {:>15.5f}\\n'.format(pair,w_dicts_1[0][pair],w_dicts_1[1][pair], w_dicts_1[2][pair], w_dicts_1[3][pair], w_dicts_1[4][pair], w_dicts_1[5][pair]))\n        work_values.write('------------------------------------------------------------------------------------------------------------------\\n')\n        work_values.write('\\n\\n--Reaction Work Decomposition (Region 2)--\\n')\n        work_values.write('\\n-----------------------------------------------------------------------------------------------------------------')\n        work_values.write('\\n{:>15} {:>15} {:>15} {:>15} {:>15} {:>15} {:>15}\\n'.format('Pair(A-B)','W_elst','W_exch', 'W_indAB', 'W_indBA', 'W_disp', 'W_total'))\n        work_values.write('-----------------------------------------------------------------------------------------------------------------\\n')\n            #print(w_dicts[0])\n        for pair in unique_pairs:\n            work_values.write('\\n{:>15s} {:>15.5f} {:>15.5f} {:>15.5f} {:>15.5f} {:>15.5f} {:>15.5f}\\n'.format(pair,w_dicts_2[0][pair],w_dicts_2[1][pair], w_dicts_2[2][pair], w_dicts_2[3][pair], w_dicts_2[4][pair], w_dicts_2[5][pair]))\n        work_values.write('------------------------------------------------------------------------------------------------------------------\\n')\n        work_values.close()\n", "meta": {"hexsha": "053030019dcbaa84ed8f5f40c0dd2c9da8831912", "size": 17072, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyrex/sapt_class.py", "max_stars_repo_name": "derricottegroup/pyrex", "max_stars_repo_head_hexsha": "edc3b2bd73314b87212d9d4069c0b511f7cfb021", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-11-21T14:42:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-23T03:06:50.000Z", "max_issues_repo_path": "pyrex/sapt_class.py", "max_issues_repo_name": "derricottegroup/pyrex", "max_issues_repo_head_hexsha": "edc3b2bd73314b87212d9d4069c0b511f7cfb021", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-11-26T11:19:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-31T13:11:30.000Z", "max_forks_repo_path": "pyrex/sapt_class.py", "max_forks_repo_name": "WDerricotte/pyrex", "max_forks_repo_head_hexsha": "edc3b2bd73314b87212d9d4069c0b511f7cfb021", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-04T12:22:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-04T12:22:21.000Z", "avg_line_length": 52.6913580247, "max_line_length": 235, "alphanum_fraction": 0.5046274602, "include": true, "reason": "import numpy", "num_tokens": 4195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.2942149721629888, "lm_q1q2_score": 0.1517030991511297}}
{"text": "#!/usr/bin/env python3\n\n\n'''\nCopyright (c) 2020 Children's Hospital of Philadelphia\nAuthor: Li Fang (fangli2718@gmail.com)\n              \nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\nBE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n'''\n\n\nimport os\nimport sys\nimport numpy as np\nimport math\nimport gzip\nimport argparse\n\nimport tk\n\nfrom sklearn.mixture import GaussianMixture\n\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import Normalize\nfrom matplotlib import cm\nmatplotlib.rcParams['font.sans-serif'] = \"Arial\"\nmatplotlib.rcParams['font.family'] = \"sans-serif\"\n\ndebug = 1\n        \nclass Readinfo:\n    def __init__(self, readname):\n\n        self.readname = readname\n        self.label = -1\n        self.repeat_size1 = -1\n        self.repeat_size2 = -1\n        self.max_prob = 0\n        self.proba_list = list()\n        self.qc_passed = 1\n\ntab  = '\\t' \nendl = '\\n'\n\ndef parse_user_arguments():\n\n    parser = argparse.ArgumentParser(description='Joint quantification of two adjacent tandem repeats from long-read amplicon sequencing data ')\n    ### required arguments ###\n    parser.add_argument('--in_fq',        required = True,  metavar = 'PATH',   type = str, help = 'input fastq file')\n    parser.add_argument('--platform',     required = True,  metavar = 'STRING', type = str, help = 'three valid values: `ont`, `pacbio`, `consensus`')\n    parser.add_argument('--ref_fasta',    required = True,  metavar = 'PATH',   type = str, help = 'reference genome sequence in FASTA format')\n    parser.add_argument('--repeat1',      required = True,  metavar = 'chr:start:end:repeat_unit:max_size', type = str, help = 'first tandem repeat, coordinates are 1-based (e.g. chr4:3074877:3074933:CAG:200)')\n    parser.add_argument('--repeat2',      required = True,  metavar = 'chr:start:end:repeat_unit:max_size', type = str, help = 'second tandem repeat, coordinates are 1-based (e.g. chr4:3074946:3074966:CCG:20)')\n    parser.add_argument('--out_dir',      required = True,  metavar = 'PATH',   type = str, help = 'path to the output directory')\n    parser.add_argument('--version',      action='version', version='%(prog)s 0.3.0')\n\n    ### optional arguments ### ploidy\n    parser.add_argument('--num_threads',  required = False, metavar = 'INT',    type = int, default = 1,  help = 'number of threads used by minimap2 (default: 1)')\n    parser.add_argument('--minimap2',     required = False, metavar = 'PATH',   type = str, default = '', help = 'path to minimap2 (default: using environment default)')\n    parser.add_argument('--ploidy',       required = False, metavar = 'INT',    type = int, default = 2,  help = 'ploidy of the sample (default: 2)')\n\n    input_args = parser.parse_args()\n\n    input_args.platform = input_args.platform.strip('`')\n    input_args.platform = input_args.platform.strip('\\'')\n    input_args.platform = input_args.platform.strip('\\\"')\n\n    valid_platform_list = ['ont', 'pacbio', 'consensus']\n    input_args.platform = input_args.platform.lower()\n\n    if input_args.platform not in valid_platform_list:\n        tk.eprint('ERROR: --platform should be one of the three valid values: ont, pacbio, consensus !\\n')\n        sys.exit(1)\n\n    if input_args.ploidy < 1:\n        tk.eprint('ERROR: --ploidy must be >= 1 !\\n')\n        sys.exit(1)\n\n    tk.check_input_file_exists(input_args.in_fq)\n    tk.check_input_file_exists(input_args.ref_fasta)\n\n    input_args.in_fq       = os.path.abspath(input_args.in_fq)\n    input_args.ref_fasta   = os.path.abspath(input_args.ref_fasta)\n    input_args.out_dir     = os.path.abspath(input_args.out_dir)\n\n    if input_args.minimap2 == '': \n        input_args.minimap2 = tk.find_executable_path('minimap2')\n        if not input_args.minimap2:\n            tk.eprint('ERROR! minimap2 was not found! Please supply the path to --minimap2')\n            sys.exit(1)\n        else:\n            if os.path.exists(input_args.minimap2):\n                tk.eprint('NOTICE: found path to minimap2: %s' % input_args.minimap2)\n            else:\n                tk.eprint('ERROR! minimap2 was not found! Please supply the path to --minimap2')\n\n    tk.check_input_file_exists(input_args.minimap2)\n\n    if len(input_args.repeat1.split(':')) != 5:\n        tk.eprint('ERROR! --repeat1 should be in this format: chr:start:end:repeat_unit:max_size (e.g. chr4:3074876:3074933:CAG:200)')\n        sys.exit(1)\n    \n    if len(input_args.repeat2.split(':')) != 5:\n        tk.eprint('ERROR! --repeat2 should be in this format: chr:start:end:repeat_unit:max_size (e.g. chr4:3074876-3074933:CAG:200)')\n        sys.exit(1)\n\n    return input_args\n\ndef main():\n\n    input_args = parse_user_arguments()\n    ampRepeat_joint (input_args)\n\n    return\n\ndef ampRepeat_joint (input_args):\n\n    n_input_reads = tk.count_fastq(input_args.in_fq)\n    if n_input_reads < input_args.ploidy:\n        tk.eprint(f'ERROR: No enough reads for analysis. Ploidy was set to {input_args.ploidy} but there were only {n_input_reads} reads in the fastq file: {input_args.in_fq}\\n')\n        sys.exit(1)\n\n    tk.create_dir(input_args.out_dir)\n\n    repeat1 = Repeat().init_from_string(input_args.repeat1)\n    repeat2 = Repeat().init_from_string(input_args.repeat2)\n\n    if repeat1.chrom != repeat2.chrom:\n        tk.eprint('ERROR: joint quantification only works with two nearby repeat regions. The two repeats in the config_file are in different chromosomes and there is no need to do joint quantification.\\n')\n        sys.exit(1)\n\n    if repeat1.start > repeat2.start:\n        repeat1, repeat2 = tk.switch_two_objects(repeat1, repeat2)\n\n    repeat1.max_size += 10\n    repeat2.max_size += 10\n    max_anchor_len = 1000\n    \n    if repeat1.end + 100 < repeat2.start:\n        tk.eprint('ERROR: joint quantification only works with two nearby repeat regions (distance < 100 bp). The two repeats are far away from each other and there is no need to do joint quantification.\\n')\n        sys.exit(1)\n\n    in_fastq_prefix = os.path.splitext(os.path.split(input_args.in_fq)[1])[0]\n    temp_out_dir = os.path.join(input_args.out_dir, '%s.AmpRepeat.temp' % in_fastq_prefix)\n    tk.create_dir(temp_out_dir)\n\n    repeat_chrom_seq = tk.read_one_chr_from_fasta_file(input_args.ref_fasta, repeat1.chrom)\n    if len(repeat_chrom_seq) == 0:\n        tk.eprint('ERROR: ref_fasta file: %s has no valid sequence!\\n' % input_args.ref_fasta)\n        sys.exit(1)\n    \n    initial_estimation = initial_estimate_repeat_size(input_args.minimap2, repeat_chrom_seq, input_args.in_fq, input_args.platform, input_args.num_threads, repeat1, repeat2, max_anchor_len, temp_out_dir)\n\n    log_fn = 'repeatRepeat.log'\n    log_f  = open(log_fn, 'w')\n    log_f.write(initial_estimation.output_repeat2_boundaries())\n\n\n    final_estimation = fine_tune_read_count(initial_estimation, input_args.in_fq, repeat_chrom_seq, repeat1, repeat2, input_args.minimap2, input_args.platform, input_args.num_threads, temp_out_dir)\n    \n    jointly_split_alleles_using_gmm (input_args.ploidy, repeat1, repeat2, final_estimation, input_args.in_fq, input_args.out_dir)\n\n    tk.eprint('NOTICE: program finished. Output files are here: %s\\n' % input_args.out_dir)\n\n    log_f.close()\n    return\n\n\ndef output_repeat_size_file(read_repeat_joint_count_dict, readinfo_dict, in_fastq_file, repeat_region_list, repeat_size_file, ploidy):\n\n    repeat_size_fp = open(repeat_size_file, 'w')\n    repeat_size_fp.write('##input_fastq=%s\\n' % in_fastq_file)\n    repeat_size_fp.write('#readname\\t%s\\t%s\\tallele_id\\tprobability\\tQC\\n' % (repeat_region_list[0].repeat_id, repeat_region_list[1].repeat_id))\n    for readname in read_repeat_joint_count_dict:\n        repeat_size1, repeat_size2 = read_repeat_joint_count_dict[readname]\n        if readname in readinfo_dict:\n            readinfo = readinfo_dict[readname]\n            allele_id = readinfo.label + 1\n            if readinfo.qc_passed:\n                qc = 'PASS'\n            else:\n                qc = 'FAIL'\n            max_prob = readinfo.max_prob\n            repeat_size_fp.write('%s\\t%d\\t%d\\t%d\\t%.8f\\t%s' % (readname, repeat_size1, repeat_size2, allele_id, max_prob, qc))\n            for prob in readinfo.proba_list:\n                repeat_size_fp.write('\\t%.8f' % prob )\n            repeat_size_fp.write('\\n')\n\n        else:\n            allele_id = 'N.A.'\n            max_prob = 'N.A.'\n            qc = 'FAIL'\n            repeat_size_fp.write('%s\\t%d\\t%d\\t%s\\t%s\\t%s' % (readname, repeat_size1, repeat_size2, allele_id, max_prob, qc))\n            for i in range(0, ploidy):\n                repeat_size_fp.write('\\tN.A.')\n            repeat_size_fp.write('\\n')\n    repeat_size_fp.close()\n\n    return\n\ndef fine_tune_read_count(initial_estimation, in_fastq_file, repeat_chrom_seq, repeat1, repeat2, minimap2, platform, num_threads, out_dir):\n\n    assert repeat1.chrom == repeat2.chrom\n    assert repeat1.start < repeat2.start\n\n    repeat1.round1_max_size = 0\n    repeat2.round1_max_size = 0\n    repeat1.round1_min_size = repeat1.max_size\n    repeat2.round1_min_size = repeat2.max_size\n    for readname, value in initial_estimation.repeat1_count_range_dict.items():\n        min_repeat_size, max_repeat_size = value\n        if max_repeat_size > repeat1.round1_max_size:\n            repeat1.round1_max_size = max_repeat_size\n        if min_repeat_size < repeat1.round1_min_size:\n            repeat1.round1_min_size = min_repeat_size\n\n    for readname, value in initial_estimation.repeat2_count_range_dict.items():\n        min_repeat_size, max_repeat_size = value\n        if max_repeat_size > repeat2.round1_max_size:\n            repeat2.round1_max_size = max_repeat_size\n        if min_repeat_size < repeat2.round1_min_size:\n            repeat2.round1_min_size = min_repeat_size\n\n    \n    if repeat1.round1_max_size > repeat1.max_size: repeat1.round1_max_size = repeat1.max_size\n    if repeat2.round1_max_size > repeat2.max_size: repeat2.round1_max_size = repeat2.max_size\n\n    tk.eprint('NOTICE: In round 1 estimation, repeat 1 (%s) is in the range of (%d, %d)' % (repeat1.repeat_unit, repeat1.round1_min_size, repeat1.round1_max_size))\n    tk.eprint('NOTICE: In round 1 estimation, repeat 2 (%s) is in the range of (%d, %d)' % (repeat2.repeat_unit, repeat2.round1_min_size, repeat2.round1_max_size))\n    \n    fastq_dict = fastq_file_to_dict(in_fastq_file)\n\n    round2_estimation = round2_estimation_of_repeat_size(initial_estimation, fastq_dict, repeat_chrom_seq, repeat1, repeat2, minimap2, platform, num_threads, out_dir)\n    \n    if round2_estimation.step_size1 > 1 and round2_estimation.step_size2 > 1:\n        final_estimation = round3_estimation_of_repeat_size(initial_estimation, round2_estimation, fastq_dict, repeat_chrom_seq, repeat1, repeat2, minimap2, platform, num_threads, out_dir)\n    else:\n        final_estimation = round2_estimation\n    \n    return final_estimation\n\ndef round3_estimation_of_repeat_size(initial_estimation, round2_estimation, fastq_dict, repeat_chrom_seq, repeat1, repeat2, minimap2, platform, num_threads, out_dir):\n\n    if len(round2_estimation.repeat1_count_dict) == 0 or len(round2_estimation.repeat2_count_dict) == 0:\n        return RepeatSize()\n    \n    assert repeat1.chrom == repeat2.chrom\n    assert repeat1.start < repeat2.start\n    max_flanking_len = 1000\n\n    buffer_size1 = round2_estimation.step_size1\n    buffer_size2 = round2_estimation.step_size2\n    tk.eprint(f'NOTICE: Fine-tuning repeat size. buffer_size1 = {buffer_size1}, buffer_size2 = {buffer_size2}')\n\n    round2_size1_list = list()\n    round2_size2_list = list()\n\n    for readname in round2_estimation.repeat1_count_dict:\n        if readname not in round2_estimation.repeat2_count_dict: continue\n        size1 = round2_estimation.repeat1_count_dict[readname]\n        size2 = round2_estimation.repeat2_count_dict[readname]\n        round2_size1_list.append(size1)\n        round2_size2_list.append(size2)\n\n    min_size1 = int(min(round2_size1_list) - buffer_size1)\n    max_size1 = int(max(round2_size1_list) + buffer_size1 + 2)\n    if min_size1 < 0: min_size1 = 0\n    min_size2 = int(min(round2_size2_list) - buffer_size2)\n    max_size2 = int(max(round2_size2_list) + buffer_size2 + 2)\n    if min_size2 < 0: min_size2 = 0\n\n    ## round 3 alignment ##\n    left_anchor_seq, mid_anchor_seq, right_anchor_seq = extract_anchor_seq_for_two_repeats (repeat_chrom_seq, repeat1, repeat2, max_flanking_len)\n    left_anchor_len  = len(left_anchor_seq)\n    mid_anchor_len   = len(mid_anchor_seq)\n\n    preset = tk.get_preset_for_minimap2(platform)\n    round3_paf_file =  os.path.join(out_dir, 'round3.paf')\n    round3_paf_fp = open(round3_paf_file, 'w')\n    round3_paf_fp.close()\n\n    for repeat_count1 in range(min_size1, max_size1):\n        for repeat_count2 in range(min_size2, max_size2):\n            tmp_fastq_file = os.path.join(out_dir, '%d.%d.round3.fastq' % (repeat_count1, repeat_count2) )\n            tmp_fastq_fp = open(tmp_fastq_file, 'w')\n            n_tmp_reads = 0\n            for readname in fastq_dict:\n                if readname not in round2_estimation.repeat1_count_dict: continue\n                if readname not in round2_estimation.repeat2_count_dict: continue\n                size1 = round2_estimation.repeat1_count_dict[readname]\n                size2 = round2_estimation.repeat2_count_dict[readname]\n                if repeat_count1 < size1 - buffer_size1 or repeat_count1 >= size1 + buffer_size1: continue\n                if repeat_count2 < size2 - buffer_size2 or repeat_count2 >= size2 + buffer_size2: continue\n                r1min1, r1max1 = initial_estimation.repeat1_count_range_dict[readname]\n                r1min2, r1max2 = initial_estimation.repeat2_count_range_dict[readname]\n                if repeat_count1 < r1min1 or repeat_count1 >= r1max1: continue\n                if repeat_count2 < r1min2 or repeat_count2 >= r1max2: continue\n\n                tmp_fastq_fp.write(fastq_dict[readname])\n                n_tmp_reads += 1\n            tmp_fastq_fp.close()\n            if n_tmp_reads == 0: \n                tk.rm(tmp_fastq_file)\n                continue\n            tmp_ref_file = os.path.join(out_dir, '%d.%d.ref.fasta' % (repeat_count1, repeat_count2))\n            build_fasta_template_for_two_repeats(left_anchor_seq, mid_anchor_seq, right_anchor_seq, repeat1, repeat2, repeat_count1, repeat_count2, tmp_ref_file)\n            cmd = f'{minimap2} -A 2 -B 6 -c --eqx -t {num_threads} -x {preset} {tmp_ref_file} {tmp_fastq_file} >> {round3_paf_file} 2> /dev/null'\n            tk.run_system_cmd(cmd)\n            tk.rm(tmp_ref_file)\n            tk.rm(tmp_fastq_file)\n\n    round3_estimation = estimate_two_repeats_from_paf(round3_paf_file, left_anchor_len, mid_anchor_len, repeat1, repeat2)\n    round3_estimation.step_size1 = 1\n    round3_estimation.step_size2 = 1\n\n    return round3_estimation\n\ndef choose_best_step_size(repeat, count_range_dict):\n\n    max_len = 50\n    max_step_size = int(max_len/repeat.repeat_unit_size)\n    if max_step_size < 1: max_step_size = 1\n\n    error_list = list()\n    for readname in count_range_dict:\n        a, b = count_range_dict[readname]\n        error = b - a\n        error_list.append(error)\n\n    l = np.mean(error_list)\n\n    count_list = list()\n    for size in range(1, max_step_size+1):\n        count = int(l/size)+1\n        count += size * 2 + 2\n        tup = (size, count)\n        count_list.append(tup)\n\n    count_list.sort(key = lambda x:x[1])\n  \n    return count_list[0][0]\n\ndef round2_estimation_of_repeat_size(initial_estimation, fastq_dict, repeat_chrom_seq, repeat1, repeat2, minimap2, platform, num_threads, out_dir):\n    \n    assert repeat1.chrom == repeat2.chrom\n    assert repeat1.start < repeat2.start\n    max_flanking_len = 1000\n\n    step_size1 = choose_best_step_size(repeat1, initial_estimation.repeat1_count_range_dict)\n    step_size2 = choose_best_step_size(repeat2, initial_estimation.repeat2_count_range_dict)\n    \n    tk.eprint(f'NOTICE: Round 2 estimation. step_size1 = {step_size1}; step_size2 = {step_size2}')\n\n    ## round 2 alignment ##\n    left_anchor_seq, mid_anchor_seq, right_anchor_seq = extract_anchor_seq_for_two_repeats (repeat_chrom_seq, repeat1, repeat2, max_flanking_len)\n    left_anchor_len  = len(left_anchor_seq)\n    mid_anchor_len   = len(mid_anchor_seq)\n\n    preset = tk.get_preset_for_minimap2(platform)\n    round2_paf_file =  os.path.join(out_dir, 'round2.paf')\n    round2_paf_fp = open(round2_paf_file, 'w')\n    round2_paf_fp.close()\n\n    for repeat_count1 in range(repeat1.round1_min_size, repeat1.round1_max_size + 1, step_size1):\n        for repeat_count2 in range(repeat2.round1_min_size, repeat2.round1_max_size + 1, step_size2):\n            tmp_fastq_file = os.path.join(out_dir, '%d.%d.round2.fastq' % (repeat_count1, repeat_count2) )\n            tmp_fastq_fp = open(tmp_fastq_file, 'w')\n            n_tmp_reads = 0\n            for readname in fastq_dict:\n                if readname not in initial_estimation.repeat1_count_range_dict: continue\n                if readname not in initial_estimation.repeat2_count_range_dict: continue\n                min1, max1 = initial_estimation.repeat1_count_range_dict[readname]\n                min2, max2 = initial_estimation.repeat2_count_range_dict[readname]\n                if repeat_count1 >= min1 and repeat_count1 < max1 and repeat_count2 >= min2 and repeat_count2 < max2:                \n                    tmp_fastq_fp.write(fastq_dict[readname])\n                    n_tmp_reads += 1\n            tmp_fastq_fp.close()\n            if n_tmp_reads == 0:\n                tk.rm(tmp_fastq_file)\n                continue\n            tmp_ref_file = os.path.join(out_dir, '%d.%d.ref.fasta' % (repeat_count1, repeat_count2))\n            build_fasta_template_for_two_repeats(left_anchor_seq, mid_anchor_seq, right_anchor_seq, repeat1, repeat2, repeat_count1, repeat_count2, tmp_ref_file)\n            cmd = f'{minimap2} -A 2 -B 6 -c --eqx -t {num_threads} -x {preset} {tmp_ref_file} {tmp_fastq_file} >> {round2_paf_file} 2> /dev/null'\n            tk.run_system_cmd(cmd)\n            tk.rm(tmp_ref_file)\n            tk.rm(tmp_fastq_file)\n\n    round2_estimation = estimate_two_repeats_from_paf(round2_paf_file, left_anchor_len, mid_anchor_len, repeat1, repeat2)\n    round2_estimation.step_size1 = step_size1\n    round2_estimation.step_size2 = step_size2\n\n    return round2_estimation\n\ndef estimate_two_repeats_from_paf(in_paf_file, left_anchor_len, mid_anchor_len, repeat1, repeat2):\n\n    repeat_size_estimation = RepeatSize()\n\n    in_paf_fp = open(in_paf_file, 'r')\n    read_align_score_dict = dict()\n    while 1:\n        line = in_paf_fp.readline()\n        if not line: break\n        line = line.strip()\n        if not line: continue\n\n        col_list = line.strip().split('\\t')\n        paf = tk.PAF(col_list)\n        repeat_size1, repeat_size2 = paf.tname.split('-')\n        repeat_size1 = int(repeat_size1)\n        repeat_size2 = int(repeat_size2)\n\n        a = left_anchor_len - 10\n        if a < 0: a = 0\n        b = left_anchor_len + repeat1.repeat_unit_size * repeat_size1 + mid_anchor_len + repeat2.repeat_unit_size * repeat_size2 + 10\n        if b > paf.tlen: b = paf.tlen\n        repeat_region_align_score = tk.target_region_alignment_stats_from_cigar(paf.cigar, paf.tstart, paf.tend, a, b).score\n    \n        tup = (repeat_size1, repeat_size2, repeat_region_align_score, paf.align_score, paf.qlen)\n        if paf.qname not in read_align_score_dict:\n            read_align_score_dict[paf.qname] = list()\n        read_align_score_dict[paf.qname].append(tup)    \n\n    in_paf_fp.close()\n\n    for readname in read_align_score_dict:\n        tup_list = read_align_score_dict[readname]\n        tup_list.sort(key = lambda x:x[2], reverse = True)\n        max_score = tup_list[0][2]\n        max_score_size1_list = list()\n        max_score_size2_list = list()\n        for tup in tup_list:\n            if tup[2] == max_score:\n                size1 = tup[0]\n                size2 = tup[1]\n                max_score_size1_list.append(size1)\n                max_score_size2_list.append(size2)\n            else:\n                break\n        \n        round2_repeat_size1 = np.mean(max_score_size1_list)\n        round2_repeat_size2 = np.mean(max_score_size2_list)\n        repeat_size_estimation.repeat1_count_dict[readname] = round2_repeat_size1\n        repeat_size_estimation.repeat2_count_dict[readname] = round2_repeat_size2\n    \n    return repeat_size_estimation\n\ndef extract_anchor_seq_for_two_repeats (repeat_chrom_seq, repeat1, repeat2, max_flanking_len):\n\n    left_end_pos = repeat1.start\n    left_start_pos = left_end_pos - max_flanking_len\n    if left_start_pos < 0: left_start_pos = 0\n    \n    mid_start_pos = repeat1.end\n    mid_end_pos = repeat2.start\n\n    right_start_pos = repeat2.end\n    right_end_pos = right_start_pos + max_flanking_len\n    if right_end_pos > len(repeat_chrom_seq): right_end_pos = len(repeat_chrom_seq)\n\n    left_anchor_seq  = repeat_chrom_seq[left_start_pos:left_end_pos]\n    mid_anchor_seq   = repeat_chrom_seq[mid_start_pos:mid_end_pos]\n    right_anchor_seq = repeat_chrom_seq[right_start_pos:right_end_pos]\n\n    return left_anchor_seq, mid_anchor_seq, right_anchor_seq\n\ndef build_fasta_template_for_two_repeats(left_anchor_seq, mid_anchor_seq, right_anchor_seq, repeat1, repeat2, repeat_count1, repeat_count2, tmp_ref_file):\n\n    tmp_ref_fp = open(tmp_ref_file, 'w')\n    tmp_ref_fp.write('>%d-%d\\n' % (repeat_count1, repeat_count2))\n    seq = left_anchor_seq + repeat1.repeat_unit * repeat_count1 + mid_anchor_seq + repeat2.repeat_unit * repeat_count2 + right_anchor_seq + '\\n'\n    tmp_ref_fp.write(seq)\n    tmp_ref_fp.close()\n\n    return\n\ndef initial_estimate_repeat_size(minimap2, repeat_chrom_seq, in_fastq_file, platform, num_threads, repeat1, repeat2, max_anchor_len, out_dir):\n\n    tk.eprint('NOTICE: Round 1 estimation')\n    assert repeat1.chrom == repeat2.chrom\n    assert repeat1.start < repeat2.start\n\n    left_anchor_seq, right_anchor_seq = tk.extract_anchor_sequence(repeat_chrom_seq, repeat1.start, repeat2.end, max_anchor_len)\n    left_anchor_len  = len(left_anchor_seq)\n    right_anchor_len = len(right_anchor_seq)\n\n    ## make template fasta file ##\n    left_template_fasta_file = os.path.join(out_dir, 'round1_templates.left_anchor.fasta')\n    left_template_name  = 'left_anchor_%d_%d_%s' % (len(left_anchor_seq), repeat1.max_size, repeat1.repeat_unit)\n    left_template_seq   = left_anchor_seq + repeat1.repeat_unit * repeat1.max_size\n\n    left_template_fasta_fp = open(left_template_fasta_file, 'w')\n    left_template_fasta_fp.write('>%s\\n' % left_template_name)\n    left_template_fasta_fp.write('%s\\n' % left_template_seq)\n    left_template_fasta_fp.close()\n\n\n    right_template_fasta_file = os.path.join(out_dir, 'round1_templates.right_anchor.fasta')\n    right_template_name = 'right_anchor_%d_%d_%s_revc' % (len(right_anchor_seq), repeat2.max_size, repeat2.repeat_unit)\n    right_template_seq  = repeat2.repeat_unit * repeat2.max_size + right_anchor_seq\n    right_template_seq  = tk.rev_comp(right_template_seq)\n    \n    right_template_fasta_fp = open(right_template_fasta_file, 'w')\n    right_template_fasta_fp.write('>%s\\n' % right_template_name)\n    right_template_fasta_fp.write('%s\\n' % right_template_seq)\n    right_template_fasta_fp.close()\n\n    round1_paf_file = os.path.join(out_dir, 'round1.paf')\n    round1_left_anchor_paf_file  = os.path.join(out_dir, 'round1.left.paf')\n    round1_right_anchor_paf_file = os.path.join(out_dir, 'round1.right.paf')\n    preset = tk.get_preset_for_minimap2(platform)\n\n    cmd = f'{minimap2} -A 2 -B 6 -c --eqx -t {num_threads} -x {preset} {left_template_fasta_file} {in_fastq_file} > {round1_left_anchor_paf_file} 2> /dev/null'\n    tk.run_system_cmd(cmd)\n    \n    cmd = f'{minimap2} -A 2 -B 6 -c --eqx -t {num_threads} -x {preset} {right_template_fasta_file} {in_fastq_file} > {round1_right_anchor_paf_file} 2> /dev/null'\n    tk.run_system_cmd(cmd)\n\n    cmd = f'cat {round1_left_anchor_paf_file} {round1_right_anchor_paf_file} | sort -k1 - > {round1_paf_file}'\n    tk.run_system_cmd(cmd)\n\n    tk.rm(round1_left_anchor_paf_file)\n    tk.rm(round1_right_anchor_paf_file)\n    initial_estimation = round1_estimation_from_paf(round1_paf_file, repeat1, repeat2, left_anchor_len, right_anchor_len)\n\n    return initial_estimation\n\ndef round1_estimation_from_paf(round1_paf_file, repeat1, repeat2, left_anchor_len, right_anchor_len):\n\n    initial_estimation = Round1Estimation()\n    round1_paf_fp = open(round1_paf_file, 'r')\n    read_paf_list = list()\n    while 1:\n        line = round1_paf_fp.readline()\n        if not line: break\n        line = line.strip()\n        if not line: continue\n\n        col_list = line.strip().split('\\t')\n        paf = tk.PAF(col_list)\n\n        if len(read_paf_list) == 0 or paf.qname == read_paf_list[0].qname:\n            read_paf_list.append(paf)\n        else:\n            round1_estimation_for1read(read_paf_list, repeat1, repeat2, left_anchor_len, right_anchor_len, initial_estimation)\n            read_paf_list.clear()\n            read_paf_list.append(paf)\n\n    round1_paf_fp.close()\n    \n    round1_estimation_for1read(read_paf_list, repeat1, repeat2, left_anchor_len, right_anchor_len, initial_estimation)\n\n    for readname in initial_estimation.bad_reads_set:\n        initial_estimation.repeat1_count_range_dict.pop(readname, None)\n        initial_estimation.repeat2_count_range_dict.pop(readname, None)\n\n    return initial_estimation\n            \n\ndef round1_estimation_for1read(read_paf_list, repeat1, repeat2, left_anchor_len, right_anchor_len, initial_estimation):\n\n    left_boundary_pos  = left_anchor_len\n    right_boundary_pos = right_anchor_len\n    \n    left_anchor_paf_list  = list()\n    right_anchor_paf_list = list()\n    \n    for paf in read_paf_list:\n        if paf.mapq < 30: continue\n        if paf.is_primary == False: continue \n        if paf.tname[0:5] == 'left_':\n            if paf.tstart <= left_boundary_pos and paf.tend >= left_boundary_pos:\n                left_anchor_paf_list.append(paf)\n        elif paf.tname[0:5] == 'right':\n            if paf.tstart <= right_boundary_pos and paf.tend >= right_boundary_pos:\n                right_anchor_paf_list.append(paf)\n        else:\n            tk.eprint('ERROR! unknown template: %s' % (paf.tname))\n            sys.exit(1)\n    \n    if len(left_anchor_paf_list) != 1 or len(right_anchor_paf_list) != 1 : return\n    left_paf  = left_anchor_paf_list[0]\n    right_paf  = right_anchor_paf_list[0]\n\n    if left_paf.strand == right_paf.strand: return\n\n    readname = left_paf.qname\n    left_paf_max_repeat_size  = int((left_paf.tend - left_boundary_pos)/repeat1.repeat_unit_size) + 5\n    left_paf_min_repeat_size  = tk.calculate_repeat_size_from_exact_match(left_paf.cigar, left_paf.tstart,   left_boundary_pos,  repeat1.repeat_unit_size)\n\n    a = max(0, left_paf_min_repeat_size - 20)\n    b = int(left_paf_min_repeat_size / 2.0)\n    left_paf_min_repeat_size = min(a, b)\n    \n\n    initial_estimation.repeat1_count_range_dict[readname] = (left_paf_min_repeat_size, left_paf_max_repeat_size)\n\n    \n    right_paf_max_repeat_size = int((right_paf.tend - right_boundary_pos)/repeat2.repeat_unit_size) + 5\n    right_paf_min_repeat_size = tk.calculate_repeat_size_from_exact_match(right_paf.cigar, right_paf.tstart, right_boundary_pos, repeat2.repeat_unit_size)\n    a = max(0, right_paf_min_repeat_size - 20)\n    b = int(right_paf_min_repeat_size / 2.0)\n    right_paf_min_repeat_size = min(a, b)\n    \n    initial_estimation.repeat2_count_range_dict[readname] = (right_paf_min_repeat_size, right_paf_max_repeat_size)\n\n    if left_paf.strand == '+': \n        candidate_start = left_paf.qstart\n        candidate_end = right_paf.qlen - right_paf.qstart\n        if candidate_end - candidate_start <= 0: initial_estimation.bad_reads_set.add(readname)\n    else:\n        candidate_start = right_paf.qstart\n        candidate_end = left_paf.qlen - left_paf.qstart\n        if candidate_end - candidate_start <= 0: initial_estimation.bad_reads_set.add(readname)\n\n    initial_estimation.potential_repeat_region_dict[readname] = (candidate_start, candidate_end)\n    return\n\n\ndef fastq_file_to_dict(in_fastq_file):\n\n    fastq_dict = dict()\n\n    in_fastq_fp = tk.gzopen(in_fastq_file)\n    while 1:\n        line1 = in_fastq_fp.readline()\n        line2 = in_fastq_fp.readline()\n        line3 = in_fastq_fp.readline()\n        line4 = in_fastq_fp.readline()\n\n        if not line1: break\n        if not line2: break\n        if not line3: break\n        if not line4: break\n\n        readname = line1.strip().split()[0][1:]\n        fastq_dict[readname] = line1 + line2 + line3 + line4\n\n    in_fastq_fp.close()\n\n    return fastq_dict\n\n\ndef jointly_split_alleles_using_gmm (ploidy, repeat1, repeat2, final_estimation, in_fastq_file, out_dir):\n    \n    in_fastq_prefix  = os.path.splitext(os.path.split(in_fastq_file)[1])[0]\n    out_prefix = os.path.join(out_dir, '%s.JointGMM' % (in_fastq_prefix))\n    out_fastq_prefix = os.path.join(out_dir, '%s.JointGMM.qc_passed' % (in_fastq_prefix))\n    repeat_size_file = os.path.join(out_dir, '%s.repeat_size.txt' % in_fastq_prefix)\n\n    read_repeat_joint_count_dict = dict()\n    for readname in final_estimation.repeat1_count_dict:\n        if readname not in final_estimation.repeat2_count_dict: continue\n        size1 = final_estimation.repeat1_count_dict[readname]\n        size2 = final_estimation.repeat2_count_dict[readname]\n        read_repeat_joint_count_dict[readname] = (size1, size2)\n\n    repeat_region_list = [repeat1, repeat2]\n\n    if len(read_repeat_joint_count_dict) < ploidy:\n        tk.eprint('WARNING: No enough reads! input fastq file is: %s\\n' % in_fastq_file)\n        readinfo_dict = dict()\n        output_repeat_size_file(read_repeat_joint_count_dict, readinfo_dict, in_fastq_file, repeat_region_list, repeat_size_file, ploidy)\n        return\n\n    if ploidy < 1:\n        tk.eprint('ploidy must be >= 1 !\\n')\n        sys.exit(1)\n\n   \n    proba_cutoff = 0.95\n    cov_type = 'tied'\n\n    min_count1, max_count1, min_count2, max_count2  = analysis_outlier_2d(read_repeat_joint_count_dict)\n\n    readname_list = list() # readnames after removing outliers\n    read_repeat_count_list = list()\n\n    for readname in read_repeat_joint_count_dict:\n        repeat_count1, repeat_count2 = read_repeat_joint_count_dict[readname]\n        if repeat_count1 < min_count1 or repeat_count1 > max_count1: continue \n        if repeat_count2 < min_count2 or repeat_count2 > max_count2: continue \n        readname_list.append(readname)\n        read_repeat_count_list.append(repeat_count1)\n        read_repeat_count_list.append(repeat_count2)\n\n    num_data_points = len(readname_list)\n    read_repeat_count_ndarray = np.array(read_repeat_count_list)\n    read_repeat_count_ndarray = read_repeat_count_ndarray.reshape(num_data_points, 2)\n\n    \n    best_n_components = chose_best_num_components (read_repeat_count_ndarray, ploidy, cov_type)\n    tk.eprint('NOTICE: number of alleles = %d' % best_n_components)\n    final_gmm = GaussianMixture(n_components = best_n_components, covariance_type=cov_type, n_init = 100).fit(read_repeat_count_ndarray)\n    old_read_label_list = list(final_gmm.predict(read_repeat_count_ndarray))\n    proba2darray = final_gmm.predict_proba(read_repeat_count_ndarray)\n\n    repeat_region_list[0].is_main = 1\n    main_repeat_idx = 0\n    for i in range(0, len(repeat_region_list)):\n        if repeat_region_list[i].is_main:\n            main_repeat_idx = i\n            break\n\n    old_cluster_mean_list = list()\n    for means in final_gmm.means_:\n        old_cluster_mean_list.append(means[main_repeat_idx])\n\n    read_label_list, old_label_to_new_label_dict, new_label_to_old_label_dict = sort_label_by_cluster_mean(old_read_label_list, old_cluster_mean_list)\n\n    readinfo_dict = dict()\n    for i in range(0, len(readname_list)):\n        readname = readname_list[i]\n        repeat_count1, repeat_count2 = read_repeat_joint_count_dict[readname]\n        read_label = read_label_list[i]\n        max_prob = max(proba2darray[i])\n        readinfo = Readinfo(readname)\n        readinfo.label = read_label\n        readinfo.max_prob = max_prob\n        readinfo.proba_list = list(proba2darray[i])\n        readinfo.repeat_size1 = repeat_count1\n        readinfo.repeat_size2 = repeat_count2\n        readinfo_dict[readname] = readinfo\n    \n    each_allele_repeat_count_3d_list = [0] * best_n_components # each_allele_repeat_count_3d_list[label][repeat_id] = list of repeat size\n    for label in range(0, len(each_allele_repeat_count_3d_list)):\n        each_allele_repeat_count_3d_list[label] = [0] * 2\n        for repeat_id in range(0, 2):\n            each_allele_repeat_count_3d_list[label][repeat_id] = list()\n\n    for readname in readinfo_dict:\n        readinfo = readinfo_dict[readname]\n        each_allele_repeat_count_3d_list[readinfo.label][0].append(readinfo.repeat_size1)\n        each_allele_repeat_count_3d_list[readinfo.label][1].append(readinfo.repeat_size2)\n\n    allele_predicted_repeat_size_2d_list = [0] * best_n_components\n    for label in range(0, len(allele_predicted_repeat_size_2d_list)):\n        allele_predicted_repeat_size_2d_list[label] = [0] * 2\n        allele_predicted_repeat_size_2d_list[label][0] = int(np.median(each_allele_repeat_count_3d_list[label][0]) + 0.5)\n        allele_predicted_repeat_size_2d_list[label][1] = int(np.median(each_allele_repeat_count_3d_list[label][1]) + 0.5)\n\n    score_cut_off = calculate_log_likelyhood_cutoff(final_gmm, 0.99)\n    label_qc_failed_reads(readinfo_dict, final_gmm, proba_cutoff, score_cut_off)\n\n\n\n\n    tk.eprint('NOTICE: writing to repeat size file.')\n    output_repeat_size_file(read_repeat_joint_count_dict, readinfo_dict, in_fastq_file, repeat_region_list, repeat_size_file, ploidy)\n    tk.eprint('NOTICE: writing to output fastq files.')\n    joint_gmm_output_fastq(in_fastq_file, readinfo_dict, best_n_components, out_fastq_prefix)\n\n    tk.eprint('NOTICE: writing to output summary file.')\n    joint_gmm_output_summary_file(final_gmm, in_fastq_file, readinfo_dict, allele_predicted_repeat_size_2d_list, repeat_region_list, out_prefix)\n\n    tk.eprint('NOTICE: plotting figures.')\n    joint_gmm_plot_repeat_counts(readinfo_dict, allele_predicted_repeat_size_2d_list, repeat_region_list, out_prefix)\n\n    joint_gmm_scatter_plot_with_contour (read_repeat_joint_count_dict, final_gmm, score_cut_off, repeat_region_list, out_prefix)\n\n    return\n\ndef joint_gmm_scatter_plot_with_contour (read_repeat_joint_count_dict, final_gmm, score_cut_off, repeat_region_list, out_prefix):\n\n    scatter_plot_file = out_prefix + '.scatter.png'\n\n    xlabel = '%s repeat size' % (repeat_region_list[0].repeat_id)\n    ylabel = '%s repeat size' % (repeat_region_list[1].repeat_id)\n\n    X = list()\n    Y = list()\n\n    for readname in read_repeat_joint_count_dict:\n        x, y = read_repeat_joint_count_dict[readname]\n        X.append(x)\n        Y.append(y)\n\n    X = np.array(X)\n    Y = np.array(Y)\n\n    X, Y, Z= countxy(X, Y)\n    fig, ax = plt.subplots()\n    fig.set_size_inches(6, 4)\n\n    ax.scatter(X, Y, c=Z, s=15, edgecolor='')\n\n    plt.xlabel(xlabel)\n    plt.ylabel(ylabel)\n\n    norm = Normalize(vmin = np.min(Z), vmax = np.max(Z))\n    cbar = fig.colorbar(cm.ScalarMappable(norm = norm), ax=ax)\n    cbar.ax.set_ylabel('Count')\n    \n    xmin = min(X)\n    xmax = max(X)\n    ymin = min(Y)\n    ymax = max(Y)\n\n    a = np.linspace(xmin, xmax, 200)\n    b = np.linspace(ymin, ymax, 200)\n\n    A, B = np.meshgrid(a, b)\n    AA = np.array([A.ravel(), B.ravel()]).T\n    C = final_gmm.score_samples(AA)\n    C = C.reshape(A.shape)\n    \n    CS = plt.contour(A, B, C, levels=[score_cut_off], linestyles = 'dashed', colors = 'grey')\n\n    plt.savefig(scatter_plot_file, dpi = 300)\n    plt.close('all')\n    return\n\ndef countxy(x, y):\n    count_dict = dict()\n    for i in range(0, len(x)):\n        key = '%d\\t%d' % (x[i], y[i])\n        if key not in count_dict:\n            count_dict[key] = 1\n        else:\n            count_dict[key] += 1\n    x_list = list()\n    y_list = list()\n    z_list = list()\n    for key in count_dict:\n        x, y = key.split('\\t')\n        x = int(x)\n        y = int(y)\n        z = count_dict[key]\n        x_list.append(x)\n        y_list.append(y)\n        z_list.append(z)\n    \n    return x_list, y_list, z_list\n\ndef calculate_log_likelyhood_cutoff(gmm, ci):\n    X, labels = gmm.sample(100000)\n    score_list = gmm.score_samples(X)\n    X_score_list = list()\n    for i in range(0, len(X)):\n        X_score = [X[i], score_list[i]]\n        X_score_list.append(X_score)\n\n    X_score_list.sort(key = lambda x:x[1], reverse = True)\n    cut_off_idx = int(len(X_score_list) * float(ci))\n    log_likelyhood_cutoff = X_score_list[cut_off_idx][1]\n\n    return log_likelyhood_cutoff\n\ndef joint_gmm_plot_repeat_counts(readinfo_dict, allele_predicted_repeat_size_2d_list, repeat_region_list, out_prefix):\n\n    \n    hist2d_figure_file = out_prefix + '.hist2d.png'\n    repeat1_hist_figure_file  = out_prefix + '.%s.hist.png' % (repeat_region_list[0].repeat_id)\n    repeat2_hist_figure_file  = out_prefix + '.%s.hist.png' % (repeat_region_list[1].repeat_id)\n\n    num_alleles = len(allele_predicted_repeat_size_2d_list)\n    x_list = list()\n    y_list = list()\n\n    x_2d_list = [0] * num_alleles\n    y_2d_list = [0] * num_alleles\n    for i in range(0, num_alleles):\n        x_2d_list[i] = list()\n        y_2d_list[i] = list()\n    for readname in readinfo_dict:\n        readinfo = readinfo_dict[readname]\n        if readinfo.qc_passed == 0: continue\n\n        x = readinfo.repeat_size1\n        y = readinfo.repeat_size2\n        x_list.append(x)\n        y_list.append(y)\n\n        x_2d_list[readinfo.label].append(x)\n        y_2d_list[readinfo.label].append(y)\n\n    xmin = int(min(x_list))\n    xmax = int(max(x_list))+1\n    ymin = int(min(y_list))\n    ymax = int(max(y_list))+1\n\n    if xmax - xmin <= 200:\n        b1 = range(xmin - 1, xmax + 2)\n    else:\n        b1 = range(xmin - 1, xmax + 2, int(float(xmax - xmin)/200.0 + 0.5))\n\n    if ymax - ymin <= 200:\n        b2 = range(ymin - 1, ymax + 2)\n    else:\n        b2 = range(ymin - 1, ymax + 2, int(float(ymax - ymin)/200.0 + 0.5))\n    \n    repeat1_predicted_size_list = list()\n    repeat2_predicted_size_list = list()\n    for label in range(0, len(allele_predicted_repeat_size_2d_list)):\n        repeat1_predicted_size_list.append(allele_predicted_repeat_size_2d_list[label][0])\n        repeat2_predicted_size_list.append(allele_predicted_repeat_size_2d_list[label][1])\n\n    plot_hist2d(x_list, y_list, b1, b2, repeat_region_list[0].repeat_id, repeat_region_list[1].repeat_id, hist2d_figure_file)\n    plot_hist1d(x_2d_list, b1, repeat_region_list[0].repeat_id, repeat1_predicted_size_list, repeat1_hist_figure_file)\n    plot_hist1d(y_2d_list, b2, repeat_region_list[1].repeat_id, repeat2_predicted_size_list, repeat2_hist_figure_file)\n\n    return \n\ndef plot_hist1d(x_2d_list, b, repeat_id, predicted_size_list, out_file):\n\n    plt.figure (figsize=(6, 4))\n    \n    for x in x_2d_list:\n        plt.hist(x, bins = b)\n\n    for repeat_size in predicted_size_list:\n        plt.axvline(x=repeat_size+0.5, color = 'grey', linestyle = ':')\n\n\n    plt.title('Repeat size distribution (%s)' % repeat_id)\n    plt.xlabel('repeat size')\n    plt.ylabel('number of reads')\n    if debug:\n        plt.xlim(0, 150)\n\n    plt.savefig(out_file, dpi=300)\n    plt.close('all')\n\n    return\n\ndef plot_hist2d(x_list, y_list, b1, b2, repeat_id1, repeat_id2, out_file):\n\n    plt.figure (figsize=(8, 4))\n    plt.hist2d (x_list, y_list, [b1, b2], cmap = 'binary')\n    plt.colorbar()\n    plt.title('2D histogram of repeat size')\n    plt.xlabel('repeat size (%s)' % repeat_id1)\n    plt.ylabel('repeat size (%s)' % repeat_id2)\n    xmin = min(x_list)\n    xmax = max(x_list)\n\n    if debug:\n        plt.xlim(xmin, xmax)\n        plt.ylim(0, (xmax-xmin)/2)\n\n    plt.savefig(out_file, dpi=300)\n    plt.close('all')\n\n    return\n\ndef joint_gmm_output_summary_file(final_gmm, in_fastq_file, readinfo_dict, allele_predicted_repeat_size_2d_list, repeat_region_list, out_prefix):\n\n    out_summray_file = out_prefix + '.summary.txt'\n    out_summray_fp = open(out_summray_file, 'w')\n    summary_header = '#input_fastq\\tmethod'\n    summary_info = '%s\\tJointGMM' % (in_fastq_file)\n\n    # allele_predicted_repeat_size_2d_list[label][repeat_id] = predicted_repeat_size\n    num_alleles = len(allele_predicted_repeat_size_2d_list)\n\n    cov1 = final_gmm.covariances_[0][0]\n    cov2 = final_gmm.covariances_[1][1]\n    summary_header += '\\tnum_alleles\\tgmm_cov_repeat1\\tgmm_cov_repeat2'\n    summary_info   += '\\t%d\\t%.4f\\t%.4f' % (num_alleles, cov1, cov2)\n\n\n    allele_num_reads_list = [0] * num_alleles\n    for readname in readinfo_dict:\n        readinfo = readinfo_dict[readname]\n        if readinfo.qc_passed == 0: continue\n        allele_num_reads_list[readinfo.label] += 1\n\n    for label in range(0, num_alleles):\n        allele_id = label + 1\n        summary_header += '\\tallele%d_num_reads' % (allele_id)\n        summary_info   += '\\t%d' % allele_num_reads_list[label]\n        for i in range(0, 2):\n            summary_header += '\\t%s_repeat_size%d' % (repeat_region_list[i].repeat_id, allele_id)\n            summary_info   += '\\t%d' % (allele_predicted_repeat_size_2d_list[label][i])\n\n    out_summray_fp.write(summary_header + '\\n')\n    out_summray_fp.write(summary_info + '\\n')\n\n    return\n    \ndef joint_gmm_output_fastq(in_fastq_file, readinfo_dict, num_alleles, out_prefix):\n\n    out_allele_fastq_file_list = list()\n    for label in range(0, num_alleles):\n        allele_id = label + 1\n        out_allele_fastq_file = out_prefix + '.allele%d.fastq' % (allele_id)\n        out_allele_fastq_file_list.append(out_allele_fastq_file)\n\n    out_allele_fastq_fp_list = list()\n    for i in range(0, len(out_allele_fastq_file_list)):\n        out_allele_fastq_fp = open(out_allele_fastq_file_list[i], 'w')\n        out_allele_fastq_fp_list.append(out_allele_fastq_fp)\n    \n    if '.gz' == in_fastq_file[-3:]:\n        in_fastq_fp = gzip.open(in_fastq_file, 'rt')\n    else:\n        in_fastq_fp = open(in_fastq_file, 'rt')\n\n    while 1:\n        line1 = in_fastq_fp.readline()\n        line2 = in_fastq_fp.readline()\n        line3 = in_fastq_fp.readline()\n        line4 = in_fastq_fp.readline()\n\n        if not line1: break\n        if not line2: break\n        if not line3: break\n        if not line4: break\n\n        readname = line1.strip().split()[0][1:]\n        if readname not in readinfo_dict: continue\n        if readinfo_dict[readname].qc_passed == 0: continue\n    \n        label = readinfo_dict[readname].label\n        out_allele_fastq_fp_list[label].write(line1 + line2 + line3 + line4)\n\n    in_fastq_fp.close()\n\n    for i in range(0, len(out_allele_fastq_fp_list)):\n        out_allele_fastq_fp_list[i].close()\n\n    return\n\n\ndef label_qc_failed_reads(readinfo_dict, final_gmm, proba_cutoff, score_cut_off):\n\n    for readname in readinfo_dict:\n        readinfo = readinfo_dict[readname]\n        qc_failed = 0\n\n        x = [readinfo.repeat_size1, readinfo.repeat_size2]\n        x = np.array(x).reshape(1, 2)\n        score = final_gmm.score_samples(x)\n        if score[0] < score_cut_off: qc_failed = 1\n\n        if readinfo.max_prob < proba_cutoff: qc_failed = 1\n\n        if qc_failed: readinfo_dict[readname].qc_passed = 0\n\n    return\n\ndef bic_best_num_components (X, max_num_components, cov_type):\n\n    bic_list = list()\n    bic_list.append(0)\n\n    fold = 0\n    if len(X) < 1000:\n        fold = int(1000 / len(X))\n\n    Y = np.concatenate((X, X))\n    for j in range(0, fold):\n        Y = np.concatenate((Y, X))\n\n    error = np.random.rand(Y.shape[0], Y.shape[1]) - 0.5\n    Y = Y + error\n    for n in range(1, max_num_components+1):\n        gmm = GaussianMixture(n_components=n, covariance_type=cov_type, n_init=20).fit(Y)\n        bic = gmm.bic(Y)\n        bic_list.append(bic)\n\n    min_bic = 1e99\n    min_bic_n_components = 0\n    for i in range(1, len(bic_list)):\n        if bic_list[i] < min_bic:\n            min_bic = bic_list[i]\n            min_bic_n_components = i\n\n    return min_bic_n_components\n\ndef chose_best_num_components (X, max_num_components, cov_type):\n    \n    min_mean_distance = 3\n    bic_num_component = bic_best_num_components (X, max_num_components, cov_type)\n    best_n_components = bic_num_component\n    for n in range(bic_num_component, 0, -1):\n        gmm = GaussianMixture(n_components=n, covariance_type=cov_type, n_init=100).fit(X)\n        cov1 = gmm.covariances_[0][0]\n        cov2 = gmm.covariances_[1][1]\n        too_close = 0\n        for i in range(0, n):\n            for j in range(i+1, n):\n                mean1 = gmm.means_[i]\n                mean2 = gmm.means_[j]\n                if abs(mean1[0]-mean2[0]) < min_mean_distance and abs(mean1[1]-mean2[1]) < min_mean_distance:\n                    too_close = 1\n                    break\n                if abs(mean1[0]-mean2[0]) < cov1 * 2 and abs(mean1[1]-mean2[1]) < cov2 * 2:\n                    too_close = 1\n                    break\n\n        if too_close == 0:\n            best_n_components = n\n            break\n    \n    return best_n_components\n\ndef analysis_outlier(read_repeat_count_dict):\n\n    read_repeat_count_list = list()\n    for readname in read_repeat_count_dict:\n        repeat_count = read_repeat_count_dict[readname]\n        read_repeat_count_list.append(repeat_count)\n\n    min_repeat_count_cutoff, max_repeat_count_cutoff = get_outlier_cutoff_from_list(read_repeat_count_list)\n \n    return min_repeat_count_cutoff, max_repeat_count_cutoff\n\ndef analysis_outlier_2d(read_repeat_joint_count_dict):\n\n    repeat_count1_list = list()\n    repeat_count2_list = list()\n\n    for readname in read_repeat_joint_count_dict:\n        repeat_count1, repeat_count2 = read_repeat_joint_count_dict[readname]\n        repeat_count1_list.append(repeat_count1)\n        repeat_count2_list.append(repeat_count2)\n\n    min_count1, max_count1 = get_outlier_cutoff_from_list(repeat_count1_list)\n    min_count2, max_count2 = get_outlier_cutoff_from_list(repeat_count2_list)\n    \n    return min_count1, max_count1, min_count2, max_count2\n\ndef get_outlier_cutoff_from_list(repeat_count_list):\n\n    mean = np.mean(repeat_count_list)\n    std = np.std(repeat_count_list)\n\n    min_repeat_count_cutoff = mean - 3 * std\n    if min_repeat_count_cutoff < 0: min_repeat_count_cutoff = 0\n    max_repeat_count_cutoff = mean + 3 * std\n\n    return min_repeat_count_cutoff, max_repeat_count_cutoff\n\ndef sort_label_by_cluster_mean(old_read_label_list, cluster_mean_list):\n\n    l = list()\n    for i in range(0, len(cluster_mean_list)):\n        label = i\n        cluster_mean = cluster_mean_list[i]\n        l.append((label, cluster_mean))\n\n    l = sorted(l, key=lambda x:x[1])\n\n    old_label_to_new_label_dict = dict()\n    new_label_to_old_label_dict = dict()\n\n    for i in range(0, len(l)):\n        new_label = i\n        old_label = l[i][0]\n        old_label_to_new_label_dict[old_label] = new_label\n        new_label_to_old_label_dict[new_label] = old_label\n\n    new_read_label_list = list()\n\n    for i in range(0, len(old_read_label_list)):\n        old_label = old_read_label_list[i]\n        new_label = old_label_to_new_label_dict[old_label]\n        new_read_label_list.append(new_label)\n\n    return new_read_label_list, old_label_to_new_label_dict, new_label_to_old_label_dict\n\n\nclass Repeat:\n    def __init__(self):\n        self.repeat_id = ''\n        self.chrom = ''\n        self.start = -1\n        self.end = -1\n        self.repeat_unit = ''\n        self.repeat_unit_size = 0\n        self.min_size = 0\n        self.max_size = 1000\n        self.round1_min_size = 0\n        self.round1_max_size = 1000\n        self.is_main = 0\n    \n    def init_from_string(self, string):\n        col_list = string.split(':')\n        if len(col_list) != 5:\n            tk.eprint('ERROR! --repeat1 and --repeat2 should be in this format: chr:start:end:repeat_unit:max_size (e.g. chr4:3074876:3074933:CAG:200')\n            sys.exit(1)\n        \n        self.chrom, self.start, self.end, self.repeat_unit, self.max_size = col_list\n        self.start = int(self.start)\n        self.end   = int(self.end)\n        self.repeat_unit_size = len(self.repeat_unit)\n        self.min_size = 0\n        self.max_size = int(self.max_size)\n        self.repeat_id = '_'.join(col_list[0:4])\n        self.start -= 1\n        return self\n\nclass Round1Estimation:\n    def __init__(self):\n        self.repeat1_count_range_dict = dict()\n        self.repeat2_count_range_dict = dict()\n        self.potential_repeat_region_dict = dict()\n        self.bad_reads_set = set()\n    \n    def output_repeat2_boundaries(self):\n        out_string = ''\n        for readname in self.repeat2_count_range_dict:\n            lower_bound, upper_bound = self.repeat2_count_range_dict[readname]\n            out_string += f'{readname}\\t{lower_bound}\\t{upper_bound}\\n'\n\n        return out_string\n\nclass RepeatSize:\n    def __init__(self):\n        self.repeat1_count_dict = dict()\n        self.repeat2_count_dict = dict()\n        self.step_size1 = 1\n        self.step_size2 = 1\n\n\nif __name__ == '__main__':\n    main()\n", "meta": {"hexsha": "9618b26e20f5385fde4ee0023b60f826b7749241", "size": 49853, "ext": "py", "lang": "Python", "max_stars_repo_path": "ampRepeat-joint.py", "max_stars_repo_name": "WGLab/AmpRepeat", "max_stars_repo_head_hexsha": "76e38c83ca8c61232d62dbf6e023379eefbfd645", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-12-15T01:32:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T06:46:00.000Z", "max_issues_repo_path": "ampRepeat-joint.py", "max_issues_repo_name": "WGLab/AmpRepeat", "max_issues_repo_head_hexsha": "76e38c83ca8c61232d62dbf6e023379eefbfd645", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ampRepeat-joint.py", "max_forks_repo_name": "WGLab/AmpRepeat", "max_forks_repo_head_hexsha": "76e38c83ca8c61232d62dbf6e023379eefbfd645", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2040322581, "max_line_length": 210, "alphanum_fraction": 0.6960864943, "include": true, "reason": "import numpy", "num_tokens": 13373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.29421497216298875, "lm_q1q2_score": 0.15170309915112964}}
{"text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport numpy as np\nfrom torchvision import ops\n# ops.DeformConv2d()\n\nfrom .correlation_package.correlation import Correlation\n\n\ndef conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1, activation=True):\n    if activation:\n        return nn.Sequential(\n            nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,\n                      padding=padding, dilation=dilation, bias=True),\n            nn.LeakyReLU(0.1))\n    else:\n        return nn.Sequential(\n            nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,\n                      padding=padding, dilation=dilation, bias=True))\n\n\ndef predict_flow(in_planes):\n    return nn.Conv2d(in_planes, 2, kernel_size=3, stride=1, padding=1, bias=True)\n\n\ndef predict_mask(in_planes):\n    return nn.Conv2d(in_planes, 1, kernel_size=3, stride=1, padding=1, bias=True)\n\n\ndef deconv(in_planes, out_planes, kernel_size=4, stride=2, padding=1):\n    return nn.ConvTranspose2d(in_planes, out_planes, kernel_size, stride, padding, bias=True)\n\n\ndef deformable_conv(in_planes, out_planes, kernel_size=3, strides=1, padding=1, use_bias=True):\n    return ops.DeformConv2d(in_planes, out_planes, kernel_size, strides, padding, bias=use_bias)\n\n\ndef upsample_kernel2d(w, device):\n    c = w // 2\n    kernel = 1 - torch.abs(c - torch.arange(w, dtype=torch.float32, device=device)) / (c + 1)\n    kernel = kernel.repeat(w).view(w,-1) * kernel.unsqueeze(1)\n    return kernel.view(1, 1, w, w)\n\n\ndef downsample_kernel2d(w, device):\n    kernel = ((w + 1) - torch.abs(w - torch.arange(w * 2 + 1, dtype=torch.float32, device=device))) / (2 * w + 1)\n    kernel = kernel.repeat(w).view(w,-1) * kernel.unsqueeze(1)\n    return kernel.view(1, 1, w * 2 + 1, w * 2 + 1)\n\n\ndef Upsample(img, factor):\n    if factor == 1:\n        return img\n    B, C, H, W = img.shape\n    batch_img = img.view(B*C, 1, H, W)\n    batch_img = F.pad(batch_img, [0, 1, 0, 1], mode='replicate')\n    kernel = upsample_kernel2d(factor * 2 - 1, img.device)\n    upsamp_img = F.conv_transpose2d(batch_img, kernel, stride=factor, padding=(factor-1))\n    upsamp_img = upsamp_img[:, :, : -1, :-1]\n    _, _, H_up, W_up = upsamp_img.shape\n    return upsamp_img.view(B, C, H_up, W_up)\n\n\ndef Downsample(img, factor):\n    if factor == 1:\n        return img\n    B, C, H, W = img.shape\n    batch_img = img.view(B*C, 1, H, W)\n    kernel = downsample_kernel2d(factor // 2, img.device)\n    upsamp_img = F.conv2d(batch_img, kernel, stride=factor, padding=factor//2)\n    upsamp_nom = F.conv2d(torch.ones_like(batch_img), kernel, stride=factor, padding=factor//2)\n    _, _, H_up, W_up = upsamp_img.shape\n    upsamp_img = upsamp_img.view(B, C, H_up, W_up)\n    upsamp_nom = upsamp_nom.view(B, C, H_up, W_up)\n    return upsamp_img / upsamp_nom\n\n\n\nclass MaskFlownet_S(nn.Module):\n    \"\"\"\n    PWC-DC net. add dilation convolution and densenet connections\n    \"\"\"\n    def __init__(self, config = None, **kwargs):\n        \"\"\"\n        input: md --- maximum displacement (for correlation. default: 4), after warpping\n        \"\"\"\n        super(MaskFlownet_S, self).__init__()\n        self.scale = 20. * config.network.flow_multiplier.get(1.)\n        md = 4\n        self.md = md\n        self.strides = [64, 32, 16, 8, 4]\n        self.deform_bias = config.network.deform_bias.get(True)\n        self.upfeat_ch = config.network.upfeat_ch.get([16, 16, 16, 16])\n\n        self.conv1a  = conv(3,   16, kernel_size=3, stride=2)\n        self.conv1b = conv(16, 16, kernel_size=3, stride=1)\n        self.conv1c  = conv(16, 16, kernel_size=3, stride=1)\n        self.conv2a  = conv(16,  32, kernel_size=3, stride=2)\n        self.conv2b = conv(32, 32, kernel_size=3, stride=1)\n        self.conv2c  = conv(32, 32, kernel_size=3, stride=1)\n        self.conv3a  = conv(32,  64, kernel_size=3, stride=2)\n        self.conv3b = conv(64, 64, kernel_size=3, stride=1)\n        self.conv3c  = conv(64, 64, kernel_size=3, stride=1)\n        self.conv4a  = conv(64,  96, kernel_size=3, stride=2)\n        self.conv4b = conv(96, 96, kernel_size=3, stride=1)\n        self.conv4c  = conv(96, 96, kernel_size=3, stride=1)\n        self.conv5a  = conv(96, 128, kernel_size=3, stride=2)\n        self.conv5b = conv(128, 128, kernel_size=3, stride=1)\n        self.conv5c  = conv(128, 128, kernel_size=3, stride=1)\n        self.conv6a = conv(128, 196, kernel_size=3, stride=2)\n        self.conv6b  = conv(196, 196, kernel_size=3, stride=1)\n        self.conv6c  = conv(196, 196, kernel_size=3, stride=1)\n\n        self.corr    = Correlation(pad_size=md, kernel_size=1, max_displacement=md, stride1=1, stride2=1, corr_multiply=1)\n        self.leakyRELU = nn.LeakyReLU(0.1)\n\n        nd = (2*md+1)**2\n        dd = np.cumsum([128,128,96,64,32])\n\n        od = nd\n        self.conv6_0 = conv(od,      128, kernel_size=3, stride=1)\n        self.conv6_1 = conv(od+dd[0],128, kernel_size=3, stride=1)\n        self.conv6_2 = conv(od+dd[1],96,  kernel_size=3, stride=1)\n        self.conv6_3 = conv(od+dd[2],64,  kernel_size=3, stride=1)\n        self.conv6_4 = conv(od+dd[3],32,  kernel_size=3, stride=1)\n        self.pred_flow6 = predict_flow(od + dd[4])\n        self.pred_mask6 = predict_mask(od + dd[4])\n        self.upfeat5 = deconv(od+dd[4], self.upfeat_ch[0], kernel_size=4, stride=2, padding=1)\n        # self.deconv6 = deconv(2, 2, kernel_size=4, stride=2, padding=1)\n        # self.upfeat6 = deconv(od+dd[4], 2, kernel_size=4, stride=2, padding=1)\n\n        # od = nd+128+4\n        od = nd+128+18\n        self.conv5_0 = conv(od,      128, kernel_size=3, stride=1)\n        self.conv5_1 = conv(od+dd[0],128, kernel_size=3, stride=1)\n        self.conv5_2 = conv(od+dd[1],96,  kernel_size=3, stride=1)\n        self.conv5_3 = conv(od+dd[2],64,  kernel_size=3, stride=1)\n        self.conv5_4 = conv(od+dd[3],32,  kernel_size=3, stride=1)\n        self.pred_flow5 = predict_flow(od + dd[4])\n        self.pred_mask5 = predict_mask(od + dd[4])\n        self.upfeat4 = deconv(od+dd[4], self.upfeat_ch[1], kernel_size=4, stride=2, padding=1)\n        # self.deconv5 = deconv(2, 2, kernel_size=4, stride=2, padding=1)\n        # self.upfeat5 = deconv(od+dd[4], 2, kernel_size=4, stride=2, padding=1)\n\n        # od = nd+96+4\n        od = nd+96+18\n        self.conv4_0 = conv(od,      128, kernel_size=3, stride=1)\n        self.conv4_1 = conv(od+dd[0],128, kernel_size=3, stride=1)\n        self.conv4_2 = conv(od+dd[1],96,  kernel_size=3, stride=1)\n        self.conv4_3 = conv(od+dd[2],64,  kernel_size=3, stride=1)\n        self.conv4_4 = conv(od+dd[3],32,  kernel_size=3, stride=1)\n        self.pred_flow4 = predict_flow(od + dd[4])\n        self.pred_mask4 = predict_mask(od + dd[4])\n        self.upfeat3 = deconv(od+dd[4], self.upfeat_ch[2], kernel_size=4, stride=2, padding=1)\n        # self.deconv4 = deconv(2, 2, kernel_size=4, stride=2, padding=1)\n        # self.upfeat4 = deconv(od+dd[4], 2, kernel_size=4, stride=2, padding=1)\n\n        # od = nd+64+4\n        od = nd+64+18\n        self.conv3_0 = conv(od,      128, kernel_size=3, stride=1)\n        self.conv3_1 = conv(od+dd[0],128, kernel_size=3, stride=1)\n        self.conv3_2 = conv(od+dd[1],96,  kernel_size=3, stride=1)\n        self.conv3_3 = conv(od+dd[2],64,  kernel_size=3, stride=1)\n        self.conv3_4 = conv(od+dd[3],32,  kernel_size=3, stride=1)\n        self.pred_flow3 = predict_flow(od + dd[4])\n        self.pred_mask3 = predict_mask(od + dd[4])\n        self.upfeat2 = deconv(od+dd[4], self.upfeat_ch[3], kernel_size=4, stride=2, padding=1)\n        # self.deconv3 = deconv(2, 2, kernel_size=4, stride=2, padding=1)\n        # self.upfeat3 = deconv(od+dd[4], 2, kernel_size=4, stride=2, padding=1)\n\n        # od = nd+32+4\n        od = nd+32+18\n        self.conv2_0 = conv(od,      128, kernel_size=3, stride=1)\n        self.conv2_1 = conv(od+dd[0],128, kernel_size=3, stride=1)\n        self.conv2_2 = conv(od+dd[1],96,  kernel_size=3, stride=1)\n        self.conv2_3 = conv(od+dd[2],64,  kernel_size=3, stride=1)\n        self.conv2_4 = conv(od+dd[3],32,  kernel_size=3, stride=1)\n        self.pred_flow2 = predict_flow(od + dd[4])\n\n        self.dc_conv1 = conv(od+dd[4], 128, kernel_size=3, stride=1, padding=1,  dilation=1)\n        self.dc_conv2 = conv(128,      128, kernel_size=3, stride=1, padding=2,  dilation=2)\n        self.dc_conv3 = conv(128,      128, kernel_size=3, stride=1, padding=4,  dilation=4)\n        self.dc_conv4 = conv(128,      96,  kernel_size=3, stride=1, padding=8,  dilation=8)\n        self.dc_conv5 = conv(96,       64,  kernel_size=3, stride=1, padding=16, dilation=16)\n        self.dc_conv6 = conv(64,       32,  kernel_size=3, stride=1, padding=1,  dilation=1)\n        self.dc_conv7 = predict_flow(32)\n\n        # self.upfeat5 = deconv()\n\n        self.deform5 = deformable_conv(128, 128)\n        self.deform4 = deformable_conv(96, 96)\n        self.deform3 = deformable_conv(64, 64)\n        self.deform2 = deformable_conv(32, 32)\n\n        self.conv5f = conv(16, 128, kernel_size=3, stride=1, padding=1, activation=False)\n        self.conv4f = conv(16, 96, kernel_size=3, stride=1, padding=1, activation=False)\n        self.conv3f = conv(16, 64, kernel_size=3, stride=1, padding=1, activation=False)\n        self.conv2f = conv(16, 32, kernel_size=3, stride=1, padding=1, activation=False)\n\n        for m in self.modules():\n            if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n                nn.init.kaiming_normal(m.weight.data, mode='fan_in')\n                if m.bias is not None:\n                    m.bias.data.zero_()\n\n\n    def warp(self, x, flo):\n        \"\"\"\n        warp an image/tensor (im2) back to im1, according to the optical flow\n        x: [B, C, H, W] (im2)\n        flo: [B, 2, H, W] flow\n        \"\"\"\n        B, C, H, W = x.size()\n        # mesh grid\n        xx = torch.arange(0, W).view(1,-1).repeat(H,1)\n        yy = torch.arange(0, H).view(-1,1).repeat(1,W)\n        xx = xx.view(1,1,H,W).repeat(B,1,1,1)\n        yy = yy.view(1,1,H,W).repeat(B,1,1,1)\n        grid = torch.cat((xx,yy),1).float()\n\n        device = x.device\n        grid = grid.to(device)\n        # vgrid = Variable(grid) + flo\n        vgrid = Variable(grid) + torch.flip(flo, [1])\n\n        # scale grid to [-1,1]\n        vgrid[:,0,:,:] = 2.0*vgrid[:,0,:,:].clone() / max(W-1,1)-1.0\n        vgrid[:,1,:,:] = 2.0*vgrid[:,1,:,:].clone() / max(H-1,1)-1.0\n\n        vgrid = vgrid.permute(0,2,3,1)\n        # vgrid = vgrid.permute(0,2,3,1).clamp(-1.1, 1.1)\n        output = nn.functional.grid_sample(x, vgrid, align_corners=True)\n        mask = torch.autograd.Variable(torch.ones(x.size())).to(device)\n        mask = nn.functional.grid_sample(mask, vgrid, align_corners=True)\n\n        # if W==128:\n        # np.save('mask.npy', mask.cpu().data.numpy())\n        # np.save('warp.npy', output.cpu().data.numpy())\n\n        mask[mask<0.9999] = 0\n        mask[mask>0] = 1\n\n        return output*mask\n\n\n    def forward(self, im1, im2):\n        # im1 = x[:,:3,:,:]\n        # im2 = x[:,3:,:,:]\n\n        c11 = self.conv1c(self.conv1b(self.conv1a(im1)))\n        c21 = self.conv1c(self.conv1b(self.conv1a(im2)))\n        c12 = self.conv2c(self.conv2b(self.conv2a(c11)))\n        c22 = self.conv2c(self.conv2b(self.conv2a(c21)))\n        c13 = self.conv3c(self.conv3b(self.conv3a(c12)))\n        c23 = self.conv3c(self.conv3b(self.conv3a(c22)))\n        c14 = self.conv4c(self.conv4b(self.conv4a(c13)))\n        c24 = self.conv4c(self.conv4b(self.conv4a(c23)))\n        c15 = self.conv5c(self.conv5b(self.conv5a(c14)))\n        c25 = self.conv5c(self.conv5b(self.conv5a(c24)))\n        c16 = self.conv6c(self.conv6b(self.conv6a(c15)))\n        c26 = self.conv6c(self.conv6b(self.conv6a(c25)))\n\n\n        corr6 = self.corr(c16, c26)\n        corr6 = self.leakyRELU(corr6)\n\n\n        x = torch.cat((self.conv6_0(corr6), corr6),1)\n        x = torch.cat((self.conv6_1(x), x),1)\n        x = torch.cat((self.conv6_2(x), x),1)\n        x = torch.cat((self.conv6_3(x), x),1)\n        x = torch.cat((self.conv6_4(x), x),1)\n        flow6 = self.pred_flow6(x)\n        mask6 = self.pred_mask6(x)\n\n        feat5 = self.leakyRELU(self.upfeat5(x))\n        flow5 = Upsample(flow6, 2)\n        mask5 = Upsample(mask6, 2)\n        warp5 = (flow5*self.scale/self.strides[1]).unsqueeze(1)\n        warp5 = torch.repeat_interleave(warp5, 9, 1)\n        S1, S2, S3, S4, S5 = warp5.shape\n        warp5 = warp5.view(S1, S2*S3, S4, S5)\n        warp5 = self.deform5(c25, warp5)\n        tradeoff5 = feat5\n        warp5 = (warp5 * F.sigmoid(mask5)) + self.conv5f(tradeoff5)\n        warp5 = self.leakyRELU(warp5)\n        corr5 = self.corr(c15, warp5)\n        corr5 = self.leakyRELU(corr5)\n        x = torch.cat((corr5, c15, feat5, flow5), 1)\n        x = torch.cat((self.conv5_0(x), x),1)\n        x = torch.cat((self.conv5_1(x), x),1)\n        x = torch.cat((self.conv5_2(x), x),1)\n        x = torch.cat((self.conv5_3(x), x),1)\n        x = torch.cat((self.conv5_4(x), x),1)\n        flow5 = flow5 + self.pred_flow5(x)\n        mask5 = self.pred_mask5(x)\n\n        feat4 = self.leakyRELU(self.upfeat4(x))\n        flow4 = Upsample(flow5, 2)\n        mask4 = Upsample(mask5, 2)\n        warp4 = (flow4*self.scale/self.strides[2]).unsqueeze(1)\n        warp4 = torch.repeat_interleave(warp4, 9, 1)\n        S1, S2, S3, S4, S5 = warp4.shape\n        warp4 = warp4.view(S1, S2*S3, S4, S5)\n        warp4 = self.deform4(c24, warp4)\n        tradeoff4 = feat4\n        warp4 = (warp4 * F.sigmoid(mask4)) + self.conv4f(tradeoff4)\n        warp4 = self.leakyRELU(warp4)\n        corr4 = self.corr(c14, warp4)\n        corr4 = self.leakyRELU(corr4)\n        x = torch.cat((corr4, c14, feat4, flow4), 1)\n        x = torch.cat((self.conv4_0(x), x),1)\n        x = torch.cat((self.conv4_1(x), x),1)\n        x = torch.cat((self.conv4_2(x), x),1)\n        x = torch.cat((self.conv4_3(x), x),1)\n        x = torch.cat((self.conv4_4(x), x),1)\n        flow4 = flow4 + self.pred_flow4(x)\n        mask4 = self.pred_mask4(x)\n\n        feat3 = self.leakyRELU(self.upfeat3(x))\n        flow3 = Upsample(flow4, 2)\n        mask3 = Upsample(mask4, 2)\n        warp3 = (flow3*self.scale/self.strides[3]).unsqueeze(1)\n        warp3 = torch.repeat_interleave(warp3, 9, 1)\n        S1, S2, S3, S4, S5 = warp3.shape\n        warp3 = warp3.view(S1, S2*S3, S4, S5)\n        warp3 = self.deform3(c23, warp3)\n        tradeoff3 = feat3\n        warp3 = (warp3 * F.sigmoid(mask3)) + self.conv3f(tradeoff3)\n        warp3 = self.leakyRELU(warp3)\n        corr3 = self.corr(c13, warp3)\n        corr3 = self.leakyRELU(corr3)\n        x = torch.cat((corr3, c13, feat3, flow3), 1)\n        x = torch.cat((self.conv3_0(x), x),1)\n        x = torch.cat((self.conv3_1(x), x),1)\n        x = torch.cat((self.conv3_2(x), x),1)\n        x = torch.cat((self.conv3_3(x), x),1)\n        x = torch.cat((self.conv3_4(x), x),1)\n        flow3 = flow3 + self.pred_flow3(x)\n        mask3 = self.pred_mask3(x)\n\n        feat2 = self.leakyRELU(self.upfeat2(x))\n        flow2 = Upsample(flow3, 2)\n        mask2 = Upsample(mask3, 2)\n        warp2 = (flow2*self.scale/self.strides[4]).unsqueeze(1)\n        warp2 = torch.repeat_interleave(warp2, 9, 1)\n        S1, S2, S3, S4, S5 = warp2.shape\n        warp2 = warp2.view(S1, S2*S3, S4, S5)\n        warp2 = self.deform2(c22, warp2)\n        tradeoff2 = feat2\n        warp2 = (warp2 * F.sigmoid(mask2)) + self.conv2f(tradeoff2)\n        warp2 = self.leakyRELU(warp2)\n        corr2 = self.corr(c12, warp2)\n        corr2 = self.leakyRELU(corr2)\n        x = torch.cat((corr2, c12, feat2, flow2), 1)\n        x = torch.cat((self.conv2_0(x), x),1)\n        x = torch.cat((self.conv2_1(x), x),1)\n        x = torch.cat((self.conv2_2(x), x),1)\n        x = torch.cat((self.conv2_3(x), x),1)\n        x = torch.cat((self.conv2_4(x), x),1)\n        flow2 = flow2 + self.pred_flow2(x)\n\n        x = self.dc_conv4(self.dc_conv3(self.dc_conv2(self.dc_conv1(x))))\n        flow2 = flow2 + self.dc_conv7(self.dc_conv6(self.dc_conv5(x)))\n\n        predictions = [flow * self.scale for flow in [flow6, flow5, flow4, flow3, flow2]]\n        occlusion_masks = []\n        occlusion_masks.append(F.sigmoid(mask2))\n        c1s = [c11, c12, c13, c14, c15, c16]\n        c2s = [c21, c12, c13, c24, c25, c26]\n        flows = [flow6, flow5, flow4, flow3, flow2]\n        mask0 = Upsample(mask2, 4)\n        mask0 = F.sigmoid(mask0) - 0.5\n        c30 = im1\n        c40 = self.warp(im2, Upsample(flow2, 4)*self.scale)\n        c30 = torch.cat((c30, torch.zeros_like(mask0)), 1)\n        c40 = torch.cat((c40, mask0), 1)\n        srcs = [c1s, c2s, flows, c30, c40]\n        return predictions, occlusion_masks, srcs\n\n\nclass MaskFlownet(nn.Module):\n    def __init__(self, config, **kwargs):\n        super(MaskFlownet, self).__init__(**kwargs)\n        self.strides = [64, 32, 16, 8, 4]\n        self.md = 2\n        self.scale = 20. * config.network.flow_multiplier.get(1.)\n        self.deform_bias = config.network.deform_bias.get(True)\n        self.upfeat_ch = config.network.upfeat_ch.get([16, 16, 16, 16])\n\n        self.MaskFlownet_S = MaskFlownet_S(config)\n        self.activate = nn.LeakyReLU(0.1)\n\n        self.conv1x = conv(4,   16, stride=2)\n        self.conv1y = conv(16,  16, stride=1)\n        self.conv1z = conv(16,  16, stride=1)\n        self.conv2x = conv(16,  32, stride=2)\n        self.conv2y = conv(32,  32, stride=1)\n        self.conv2z = conv(32,  32, stride=1)\n        self.conv3x = conv(32,  64, stride=2)\n        self.conv3y = conv(64,  64, stride=1)\n        self.conv3z = conv(64,  64, stride=1)\n        self.conv4x = conv(64,  96, stride=2)\n        self.conv4y = conv(96,  96, stride=1)\n        self.conv4z = conv(96,  96, stride=1)\n        self.conv5x = conv(96,  128, stride=2)\n        self.conv5y = conv(128, 128, stride=1)\n        self.conv5z = conv(128, 128, stride=1)\n        self.conv6x = conv(128, 196, stride=2)\n        self.conv6y = conv(196, 196, stride=1)\n        self.conv6z = conv(196, 196, stride=1)\n\n        self.leakyRELU = nn.LeakyReLU(0.1)\n        self.corr    = Correlation(pad_size=self.md, kernel_size=1, max_displacement=self.md, stride1=1, stride2=1, corr_multiply=1)\n\n        nd = (2*self.md+1)**2\n        dd = np.cumsum([128,128,96,64,32])\n\n        od = nd+nd+2\n        self.conv6_0 = conv(od,       128, kernel_size=3, stride=1)\n        self.conv6_1 = conv(od+dd[0], 128, kernel_size=3, stride=1)\n        self.conv6_2 = conv(od+dd[1], 96,  kernel_size=3, stride=1)\n        self.conv6_3 = conv(od+dd[2], 64,  kernel_size=3, stride=1)\n        self.conv6_4 = conv(od+dd[3], 32,  kernel_size=3, stride=1)\n        self.pred_flow6 = predict_flow(od + dd[4])\n        self.upfeat5 = deconv(od+dd[4], self.upfeat_ch[0], kernel_size=4, stride=2, padding=1)\n\n        # od = nd+128+4\n        od = nd+nd+128+16+2+2\n        self.conv5_0 = conv(od,      128, kernel_size=3, stride=1)\n        self.conv5_1 = conv(od+dd[0],128, kernel_size=3, stride=1)\n        self.conv5_2 = conv(od+dd[1],96,  kernel_size=3, stride=1)\n        self.conv5_3 = conv(od+dd[2],64,  kernel_size=3, stride=1)\n        self.conv5_4 = conv(od+dd[3],32,  kernel_size=3, stride=1)\n        self.pred_flow5 = predict_flow(od + dd[4])\n        self.upfeat4 = deconv(od+dd[4], self.upfeat_ch[1], kernel_size=4, stride=2, padding=1)\n        # self.deconv5 = deconv(2, 2, kernel_size=4, stride=2, padding=1)\n        # self.upfeat5 = deconv(od+dd[4], 2, kernel_size=4, stride=2, padding=1)\n\n        # od = nd+96+4\n        # od = nd+96+18\n        od = nd+nd+96+16+2+2\n        self.conv4_0 = conv(od,      128, kernel_size=3, stride=1)\n        self.conv4_1 = conv(od+dd[0],128, kernel_size=3, stride=1)\n        self.conv4_2 = conv(od+dd[1],96,  kernel_size=3, stride=1)\n        self.conv4_3 = conv(od+dd[2],64,  kernel_size=3, stride=1)\n        self.conv4_4 = conv(od+dd[3],32,  kernel_size=3, stride=1)\n        self.pred_flow4 = predict_flow(od + dd[4])\n        self.upfeat3 = deconv(od+dd[4], self.upfeat_ch[2], kernel_size=4, stride=2, padding=1)\n        # self.deconv4 = deconv(2, 2, kernel_size=4, stride=2, padding=1)\n        # self.upfeat4 = deconv(od+dd[4], 2, kernel_size=4, stride=2, padding=1)\n\n        # od = nd+64+4\n        # od = nd+64+18\n        od = nd+nd+64+16+2+2\n        self.conv3_0 = conv(od,      128, kernel_size=3, stride=1)\n        self.conv3_1 = conv(od+dd[0],128, kernel_size=3, stride=1)\n        self.conv3_2 = conv(od+dd[1],96,  kernel_size=3, stride=1)\n        self.conv3_3 = conv(od+dd[2],64,  kernel_size=3, stride=1)\n        self.conv3_4 = conv(od+dd[3],32,  kernel_size=3, stride=1)\n        self.pred_flow3 = predict_flow(od + dd[4])\n        self.upfeat2 = deconv(od+dd[4], self.upfeat_ch[3], kernel_size=4, stride=2, padding=1)\n        # self.deconv3 = deconv(2, 2, kernel_size=4, stride=2, padding=1)\n        # self.upfeat3 = deconv(od+dd[4], 2, kernel_size=4, stride=2, padding=1)\n\n        # od = nd+32+4\n        # od = nd+32+18\n        od = nd+nd+32+16+2+2\n        self.conv2_0 = conv(od,      128, kernel_size=3, stride=1)\n        self.conv2_1 = conv(od+dd[0],128, kernel_size=3, stride=1)\n        self.conv2_2 = conv(od+dd[1],96,  kernel_size=3, stride=1)\n        self.conv2_3 = conv(od+dd[2],64,  kernel_size=3, stride=1)\n        self.conv2_4 = conv(od+dd[3],32,  kernel_size=3, stride=1)\n        self.pred_flow2 = predict_flow(od + dd[4])\n\n        self.dc_conv1 = conv(od+dd[4], 128, kernel_size=3, stride=1, padding=1,  dilation=1)\n        self.dc_conv2 = conv(128,      128, kernel_size=3, stride=1, padding=2,  dilation=2)\n        self.dc_conv3 = conv(128,      128, kernel_size=3, stride=1, padding=4,  dilation=4)\n        self.dc_conv4 = conv(128,      96,  kernel_size=3, stride=1, padding=8,  dilation=8)\n        self.dc_conv5 = conv(96,       64,  kernel_size=3, stride=1, padding=16, dilation=16)\n        self.dc_conv6 = conv(64,       32,  kernel_size=3, stride=1, padding=1,  dilation=1)\n        self.dc_conv7 = predict_flow(32)\n\n        # self.upfeat5 = deconv()\n\n        self.deform6 = deformable_conv(196, 196)\n        self.deform5 = deformable_conv(128, 128)\n        self.deform4 = deformable_conv(96, 96)\n        self.deform3 = deformable_conv(64, 64)\n        self.deform2 = deformable_conv(32, 32)\n\n    def warp(self, x, flo):\n        \"\"\"\n        warp an image/tensor (im2) back to im1, according to the optical flow\n        x: [B, C, H, W] (im2)\n        flo: [B, 2, H, W] flow\n        \"\"\"\n        B, C, H, W = x.size()\n        # mesh grid\n        xx = torch.arange(0, W).view(1,-1).repeat(H,1)\n        yy = torch.arange(0, H).view(-1,1).repeat(1,W)\n        xx = xx.view(1,1,H,W).repeat(B,1,1,1)\n        yy = yy.view(1,1,H,W).repeat(B,1,1,1)\n        grid = torch.cat((xx,yy),1).float()\n\n        if x.is_cuda:\n            grid = grid.cuda()\n        # vgrid = Variable(grid) + flo\n        vgrid = Variable(grid) + torch.flip(flo, [1])\n\n        # scale grid to [-1,1]\n        vgrid[:,0,:,:] = 2.0*vgrid[:,0,:,:].clone() / max(W-1,1)-1.0\n        vgrid[:,1,:,:] = 2.0*vgrid[:,1,:,:].clone() / max(H-1,1)-1.0\n\n        # vgrid = vgrid.permute(0,2,3,1)\n        vgrid = vgrid.permute(0,2,3,1).clamp(-1.1, 1.1)\n        output = nn.functional.grid_sample(x, vgrid, align_corners=True)\n        mask = torch.autograd.Variable(torch.ones(x.size())).cuda()\n        mask = nn.functional.grid_sample(mask, vgrid, align_corners=True)\n\n        # if W==128:\n        # np.save('mask.npy', mask.cpu().data.numpy())\n        # np.save('warp.npy', output.cpu().data.numpy())\n\n        mask[mask<0.9999] = 0\n        mask[mask>0] = 1\n\n        return output*mask\n\n    def forward(self, im1, im2):\n\n        # im1 = x[:,:3,:,:]\n        # im2 = x[:,3:,:,:]\n\n        _, _, srcs = self.MaskFlownet_S(im1, im2)\n        c1s, c2s, flows, c30, c40 = srcs\n        c11, c12, c13, c14, c15, c16 = c1s\n        c21, c22, c23, c24, c25, c26 = c2s\n\n        c31 = self.conv1z(self.conv1y(self.conv1x(c30)))\n        c32 = self.conv2z(self.conv2y(self.conv2x(c31)))\n        c33 = self.conv3z(self.conv3y(self.conv3x(c32)))\n        c34 = self.conv4z(self.conv4y(self.conv4x(c33)))\n        c35 = self.conv5z(self.conv5y(self.conv5x(c34)))\n        c36 = self.conv6z(self.conv6y(self.conv6x(c35)))\n\n        c41 = self.conv1z(self.conv1y(self.conv1x(c40)))\n        c42 = self.conv2z(self.conv2y(self.conv2x(c41)))\n        c43 = self.conv3z(self.conv3y(self.conv3x(c42)))\n        c44 = self.conv4z(self.conv4y(self.conv4x(c43)))\n        c45 = self.conv5z(self.conv5y(self.conv5x(c44)))\n        c46 = self.conv6z(self.conv6y(self.conv6x(c45)))\n\n        flow6 = flows[0]\n\n        warp6u = (flow6*self.scale/self.strides[0]).unsqueeze(1)\n        warp6u = torch.repeat_interleave(warp6u, 9, 1)\n        S1, S2, S3, S4, S5 = warp6u.shape\n        warp6u = warp6u.view(S1, S2*S3, S4, S5)\n        warp6u = self.deform6(c26, warp6u)\n        warp6u = self.leakyRELU(warp6u)\n        corr6u = self.leakyRELU(self.corr(c16, warp6u))\n        warp6v = c46\n        corr6v = self.leakyRELU(self.corr(c36, warp6v))\n        x = torch.cat((corr6u, corr6v, flow6),1)\n        x = torch.cat((self.conv6_0(x), x),1)\n        x = torch.cat((self.conv6_1(x), x),1)\n        x = torch.cat((self.conv6_2(x), x),1)\n        x = torch.cat((self.conv6_3(x), x),1)\n        x = torch.cat((self.conv6_4(x), x),1)\n        flow6 = flow6 + self.pred_flow6(x)\n\n        feat5 = self.leakyRELU(self.upfeat5(x))\n        flow5 = Upsample(flow6, 2)\n        warp5u = (flow5*self.scale/self.strides[1]).unsqueeze(1)\n        warp5u = torch.repeat_interleave(warp5u, 9, 1)\n        S1, S2, S3, S4, S5 = warp5u.shape\n        warp5u = warp5u.view(S1, S2*S3, S4, S5)\n        warp5u = self.deform5(c25, warp5u)\n        warp5u = self.leakyRELU(warp5u)\n        corr5u = self.leakyRELU(self.corr(c15, warp5u))\n        warp5v = c45\n        corr5v = self.leakyRELU(self.corr(c35, warp5v))\n        x = torch.cat((c15, feat5, corr5u, corr5v, flow5, flows[1]),1)\n        x = torch.cat((self.conv5_0(x), x),1)\n        x = torch.cat((self.conv5_1(x), x),1)\n        x = torch.cat((self.conv5_2(x), x),1)\n        x = torch.cat((self.conv5_3(x), x),1)\n        x = torch.cat((self.conv5_4(x), x),1)\n        flow5 = flow5 + self.pred_flow5(x)\n\n        feat4 = self.leakyRELU(self.upfeat4(x))\n        flow4 = Upsample(flow5, 2)\n        warp4u = (flow4*self.scale/self.strides[2]).unsqueeze(1)\n        warp4u = torch.repeat_interleave(warp4u, 9, 1)\n        S1, S2, S3, S4, S5 = warp4u.shape\n        warp4u = warp4u.view(S1, S2*S3, S4, S5)\n        warp4u = self.deform4(c24, warp4u)\n        warp4u = self.leakyRELU(warp4u)\n        corr4u = self.leakyRELU(self.corr(c14, warp4u))\n        warp4v = c44\n        corr4v = self.leakyRELU(self.corr(c34, warp4v))\n        x = torch.cat((c14, feat4, corr4u, corr4v, flow4, flows[2]),1)\n        x = torch.cat((self.conv4_0(x), x),1)\n        x = torch.cat((self.conv4_1(x), x),1)\n        x = torch.cat((self.conv4_2(x), x),1)\n        x = torch.cat((self.conv4_3(x), x),1)\n        x = torch.cat((self.conv4_4(x), x),1)\n        flow4 = flow4 + self.pred_flow4(x)\n\n        feat3 = self.leakyRELU(self.upfeat3(x))\n        flow3 = Upsample(flow4, 2)\n        warp3u = (flow3*self.scale/self.strides[3]).unsqueeze(1)\n        warp3u = torch.repeat_interleave(warp3u, 9, 1)\n        S1, S2, S3, S4, S5 = warp3u.shape\n        warp3u = warp3u.view(S1, S2*S3, S4, S5)\n        warp3u = self.deform3(c23, warp3u)\n        warp3u = self.leakyRELU(warp3u)\n        corr3u = self.leakyRELU(self.corr(c13, warp3u))\n        warp3v = c43\n        corr3v = self.leakyRELU(self.corr(c33, warp3v))\n        x = torch.cat((c13, feat3, corr3u, corr3v, flow3, flows[3]),1)\n        x = torch.cat((self.conv3_0(x), x),1)\n        x = torch.cat((self.conv3_1(x), x),1)\n        x = torch.cat((self.conv3_2(x), x),1)\n        x = torch.cat((self.conv3_3(x), x),1)\n        x = torch.cat((self.conv3_4(x), x),1)\n        flow3 = flow3 + self.pred_flow3(x)\n\n        feat2 = self.leakyRELU(self.upfeat2(x))\n        flow2 = Upsample(flow3, 2)\n        warp2u = (flow2*self.scale/self.strides[4]).unsqueeze(1)\n        warp2u = torch.repeat_interleave(warp2u, 9, 1)\n        S1, S2, S3, S4, S5 = warp2u.shape\n        warp2u = warp2u.view(S1, S2*S3, S4, S5)\n        warp2u = self.deform2(c22, warp2u)\n        warp2u = self.leakyRELU(warp2u)\n        corr2u = self.leakyRELU(self.corr(c12, warp2u))\n        warp2v = c42\n        corr2v = self.leakyRELU(self.corr(c32, warp2v))\n        x = torch.cat((c12, feat2, corr2u, corr2v, flow2, flows[4]),1)\n        x = torch.cat((self.conv2_0(x), x),1)\n        x = torch.cat((self.conv2_1(x), x),1)\n        x = torch.cat((self.conv2_2(x), x),1)\n        x = torch.cat((self.conv2_3(x), x),1)\n        x = torch.cat((self.conv2_4(x), x),1)\n        flow2 = flow2 + self.pred_flow2(x)\n\n        x = self.dc_conv4(self.dc_conv3(self.dc_conv2(self.dc_conv1(x))))\n        flow2 = flow2 + self.dc_conv7(self.dc_conv6(self.dc_conv5(x)))\n\n        preds = [flow * self.scale for flow in [flow6, flow5, flow4, flow3, flow2]]\n        visuals = []\n        visuals.append(flow2[:,:1])\n        return preds, visuals, []\n\n\nclass EpeLoss(nn.Module):\n    def __init__(self, eps = 0):\n        super(EpeLoss, self).__init__()\n        self.eps = eps\n\n    def forward(self, pred, label):\n        loss = ((pred - label).pow(2).sum(1) + self.eps).sqrt()\n        return loss.view(loss.shape[0], -1).mean(1)\n\n\nclass EpeLossWithMask(nn.Module):\n    def __init__(self, eps=1e-8, q=None):\n        super(EpeLossWithMask, self).__init__()\n        self.eps = eps\n        self.q = q\n\n    def forward(self, pred, label, mask):\n        if self.q is not None:\n            loss = ((pred - label).abs().sum(1) + self.eps) ** self.q\n        else:\n            loss = ((pred - label).pow(2).sum(1) + self.eps).sqrt()\n        loss = loss * mask.squeeze(1)\n        loss = loss.view(loss.shape[0], -1).sum(1) / mask.view(mask.shape[0], -1).sum(1)\n        return loss\n\n\nclass MultiscaleEpe(nn.Module):\n    def __init__(self, scales, weights, match, eps = 1e-8, q = None):\n        super(MultiscaleEpe, self).__init__()\n\n        self.scales = scales\n        self.weights = weights\n        self.match = match\n        self.eps = eps\n        self.q = q\n\n    def forward(self, flow, mask, *predictions):\n        losses = 0\n        if self.match == 'upsampling':\n            for p, w, s in zip(predictions, self.weights, self.scales):\n                losses += EpeLossWithMask(eps=self.eps, q=self.q)(Upsample(p, s), flow, mask) * w\n        elif self.match == 'downsampling':\n            for p, w, s in zip(predictions, self.weights, self.scales):\n                losses += EpeLossWithMask(eps=self.eps, q=self.q)(p, Downsample(flow, s), Downsample(mask, s)) * w\n        else:\n            raise NotImplementedError\n        return losses\n", "meta": {"hexsha": "0a0057726e40dceb4645c445a4ef4c95f96d14ef", "size": 30635, "ext": "py", "lang": "Python", "max_stars_repo_path": "model/MaskFlownet.py", "max_stars_repo_name": "brightvioletlight/MaskFlownet-Pytorch", "max_stars_repo_head_hexsha": "4158bac3b2fe50bfdf4216b4890ce24a8011227a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 75, "max_stars_repo_stars_event_min_datetime": "2020-06-15T16:48:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T12:17:21.000Z", "max_issues_repo_path": "model/MaskFlownet.py", "max_issues_repo_name": "brightvioletlight/MaskFlownet-Pytorch", "max_issues_repo_head_hexsha": "4158bac3b2fe50bfdf4216b4890ce24a8011227a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-06-24T11:33:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-27T12:04:40.000Z", "max_forks_repo_path": "model/MaskFlownet.py", "max_forks_repo_name": "brightvioletlight/MaskFlownet-Pytorch", "max_forks_repo_head_hexsha": "4158bac3b2fe50bfdf4216b4890ce24a8011227a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2020-06-27T11:50:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T06:50:53.000Z", "avg_line_length": 43.3309759547, "max_line_length": 132, "alphanum_fraction": 0.5861269789, "include": true, "reason": "import numpy", "num_tokens": 10510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.28140560742914383, "lm_q1q2_score": 0.15167290061173402}}
{"text": "# -*implants -*-\n\"\"\"\n\nFunctions for creating retinal implants\n\n\"\"\"\nimport numpy as np\nimport six\nimport copy\nimport logging\n\nfrom pulse2percept import utils\nfrom pulse2percept import implants\nfrom pulse2percept import files\n\n# Rather than trying to import these all over, try once and then remember\n# by setting a flag.\ntry:\n    import skimage.io as sio\n    import skimage.transform as sit\n    import skimage.color as sic\n    has_skimage = True\nexcept (ImportError, AttributeError):\n    # Might also raise \"dict object has no attribute 'io'\"\n    has_skimage = False\n\n\nclass MonophasicPulse(utils.TimeSeries):\n\n    def __init__(self, ptype, pdur, tsample, delay_dur=0, stim_dur=None):\n        \"\"\"A pulse with a single phase\n\n        Parameters\n        ----------\n        ptype : {'anodic', 'cathodic'}\n            Pulse type. Anodic pulses have positive current amplitude,\n            cathodic pulses have negative amplitude.\n        pdur : float\n            Pulse duration (s).\n        tsample : float\n            Sampling time step (s).\n        delay_dur : float, optional\n            Pulse delay (s). Pulse will be zero-padded (prepended) to deliver\n            the pulse only after `delay_dur` milliseconds. Default: 0.\n        stim_dur : float, optional\n            Stimulus duration (ms). Pulse will be zero-padded (appended) to fit\n            the stimulus duration. Default: No additional zero padding,\n            `stim_dur` is `pdur`+`delay_dur`.\n        \"\"\"\n        if tsample <= 0:\n            raise ValueError(\"tsample must be a non-negative float.\")\n\n        if stim_dur is None:\n            stim_dur = pdur + delay_dur\n\n        # Convert durations to number of samples\n        pulse_size = int(np.round(pdur / tsample))\n        delay_size = int(np.round(delay_dur / tsample))\n        stim_size = int(np.round(stim_dur / tsample))\n\n        if ptype == 'cathodic':\n            pulse = -np.ones(pulse_size)\n        elif ptype == 'anodic':\n            pulse = np.ones(pulse_size)\n        else:\n            raise ValueError(\"Acceptable values for `ptype` are 'anodic', \"\n                             \"'cathodic'.\")\n\n        pulse = np.concatenate((np.zeros(delay_size), pulse,\n                                np.zeros(stim_size)))\n        utils.TimeSeries.__init__(self, tsample, pulse[:stim_size])\n\n\nclass BiphasicPulse(utils.TimeSeries):\n\n    def __init__(self, ptype, pdur, tsample, interphase_dur=0):\n        \"\"\"A charge-balanced pulse with a cathodic and anodic phase\n\n        A single biphasic pulse with duration `pdur` per phase,\n        separated by `interphase_dur` is returned.\n\n        Parameters\n        ----------\n        ptype : {'cathodicfirst', 'anodicfirst'}\n            A cathodic-first pulse has the negative phase first, whereas an\n            anodic-first pulse has the positive phase first.\n        pdur : float\n            Duration of single (positive or negative) pulse phase in seconds.\n        tsample : float\n            Sampling time step in seconds.\n        interphase_dur : float, optional\n            Duration of inter-phase interval (between positive and negative\n            pulse) in seconds. Default: 0.\n        \"\"\"\n        if tsample <= 0:\n            raise ValueError(\"tsample must be a non-negative float.\")\n\n        # Get the two monophasic pulses\n        on = MonophasicPulse('anodic', pdur, tsample, 0, pdur)\n        off = MonophasicPulse('cathodic', pdur, tsample, 0, pdur)\n\n        # Insert interphase gap if necessary\n        gap = np.zeros(int(round(interphase_dur / tsample)))\n\n        # Order the pulses\n        if ptype == 'cathodicfirst':\n            # has negative current first\n            pulse = np.concatenate((off.data, gap), axis=0)\n            pulse = np.concatenate((pulse, on.data), axis=0)\n        elif ptype == 'anodicfirst':\n            pulse = np.concatenate((on.data, gap), axis=0)\n            pulse = np.concatenate((pulse, off.data), axis=0)\n        else:\n            raise ValueError(\"Acceptable values for `type` are \"\n                             \"'anodicfirst' or 'cathodicfirst'\")\n        utils.TimeSeries.__init__(self, tsample, pulse)\n\n\nclass PulseTrain(utils.TimeSeries):\n\n    def __init__(self, tsample, freq=20, amp=20, dur=0.5, delay=0,\n                 pulse_dur=0.45 / 1000, interphase_dur=0.45 / 1000,\n                 pulsetype='cathodicfirst',\n                 pulseorder='pulsefirst'):\n        \"\"\"A train of biphasic pulses\n\n        Parameters\n        ----------\n        tsample : float\n            Sampling time step (seconds).\n        freq : float, optional, default: 20 Hz\n            Frequency of the pulse envelope (Hz).\n        amp : float, optional, default: 20 uA\n            Max amplitude of the pulse train in micro-amps.\n        dur : float, optional, default: 0.5 seconds\n            Stimulus duration in seconds.\n        delay : float, optional, default: 0\n            Delay until stimulus on-set in seconds.\n        pulse_dur : float, optional, default: 0.45 ms\n            Single-pulse duration in seconds.\n        interphase_duration : float, optional, default: 0.45 ms\n            Single-pulse interphase duration (the time between the positive\n            and negative phase) in seconds.\n        pulsetype : str, optional, default: 'cathodicfirst'\n            Pulse type {'cathodicfirst' | 'anodicfirst'}, where\n            'cathodicfirst' has the negative phase first.\n        pulseorder : str, optional, default: 'pulsefirst'\n            Pulse order {'gapfirst' | 'pulsefirst'}, where\n            'pulsefirst' has the pulse first, followed by the gap.\n            'gapfirst' has it the other way round.\n        \"\"\"\n        if tsample <= 0:\n            raise ValueError(\"tsample must be a non-negative float.\")\n\n        # Stimulus size given by `dur`\n        stim_size = int(np.round(float(dur) / tsample))\n\n        # Make sure input is non-trivial, else return all zeros\n        if np.isclose(freq, 0) or np.isclose(amp, 0):\n            utils.TimeSeries.__init__(self, tsample, np.zeros(stim_size))\n            return\n\n        # Envelope size (single pulse + gap) given by `freq`\n        # Note that this can be larger than `stim_size`, but we will trim\n        # the stimulus to proper length at the very end.\n        envelope_size = int(np.round(1.0 / float(freq) / tsample))\n        if envelope_size > stim_size:\n            debug_s = (\"Envelope size (%d) clipped to \"\n                       \"stimulus size (%d) for freq=%f\" % (envelope_size,\n                                                           stim_size,\n                                                           freq))\n            logging.getLogger(__name__).debug(debug_s)\n            envelope_size = stim_size\n\n        # Delay given by `delay`\n        delay_size = int(np.round(float(delay) / tsample))\n\n        if delay_size < 0:\n            raise ValueError(\"Delay cannot be negative.\")\n        delay = np.zeros(delay_size)\n\n        # Single pulse given by `pulse_dur`\n        pulse = amp * BiphasicPulse(pulsetype, pulse_dur, tsample,\n                                    interphase_dur).data\n        pulse_size = pulse.size\n        if pulse_size < 0:\n            raise ValueError(\"Single pulse must fit within 1/freq interval.\")\n\n        # Then gap is used to fill up what's left\n        gap_size = envelope_size - (delay_size + pulse_size)\n        if gap_size < 0:\n            logging.error(\"Envelope (%d) can't fit pulse (%d) + delay (%d)\" %\n                          (envelope_size, pulse_size, delay_size))\n            raise ValueError(\"Pulse and delay must fit within 1/freq \"\n                             \"interval.\")\n        gap = np.zeros(gap_size)\n\n        pulse_train = np.array([])\n        for j in range(int(np.ceil(dur * freq))):\n            if pulseorder == 'pulsefirst':\n                pulse_train = np.concatenate((pulse_train, delay, pulse,\n                                              gap), axis=0)\n            elif pulseorder == 'gapfirst':\n                pulse_train = np.concatenate((pulse_train, delay, gap,\n                                              pulse), axis=0)\n            else:\n                raise ValueError(\"Acceptable values for `pulseorder` are \"\n                                 \"'pulsefirst' or 'gapfirst'\")\n\n        # If `freq` is not a nice number, the resulting pulse train might not\n        # have the desired length\n        if pulse_train.size < stim_size:\n            fill_size = stim_size - pulse_train.shape[-1]\n            pulse_train = np.concatenate((pulse_train, np.zeros(fill_size)),\n                                         axis=0)\n\n        # Trim to correct length (takes care of too long arrays, too)\n        pulse_train = pulse_train[:stim_size]\n\n        utils.TimeSeries.__init__(self, tsample, pulse_train)\n\n\ndef image2pulsetrain(img, implant, coding='amplitude', valrange=[0, 50],\n                     max_contrast=False, const_val=20, invert=False,\n                     tsample=0.005 / 1000, dur=0.5, pulsedur=0.5 / 1000.,\n                     interphasedur=0.5 / 1000., pulsetype='cathodicfirst'):\n    \"\"\"Converts an image into a series of pulse trains\n\n    This function creates an input stimulus from an RGB or grayscale image.\n    The image is down-sampled to fit the spatial layout of the implant\n    (currently supported are ArgusI and ArgusII arrays).\n    Requires Scikit-Image.\n\n    Parameters\n    ----------\n    img : str|array_like\n        An input image, either a valid filename (string) or a numpy array\n        (row x col x channels).\n    implant : p2p.implants.ElectrodeArray\n        An ElectrodeArray object that describes the implant.\n    coding : {'amplitude', 'frequency'}, optional\n        A string describing the coding scheme:\n        - 'amplitude': Image intensity is linearly converted to a current\n                       amplitude between `valrange[0]` and `valrange[1]`.\n                       Frequency is held constant at `const_freq`.\n        - 'frequency': Image intensity is linearly converted to a pulse\n                       frequency between `valrange[0]` and `valrange[1]`.\n                       Amplitude is held constant at `const_amp`.\n        Default: 'amplitude'\n    valrange : list, optional\n        Range of stimulation values to be used (If `coding` is 'amplitude',\n        specifies min and max current; if `coding` is 'frequency', specifies\n        min and max frequency).\n        Default: [0, 50]\n    max_contrast : bool, optional\n        Flag wether to maximize image contrast (True) or not (False).\n        Default: False\n    const_val : float, optional\n        For frequency coding: The constant amplitude value to be used for all\n        pulse trains. For amplitude coding: The constant frequency value to\n        be used for all pulse trains.\n        Default: 20\n    invert : bool, optional\n        Flag whether to invert the grayscale values of the image (True) or\n        not (False).\n        Default: False\n    tsample : float, optional\n        Sampling time step (seconds). Default: 0.005 / 1000 seconds.\n    dur : float, optional\n        Stimulus duration (seconds). Default: 0.5 seconds.\n    pulsedur : float, optional\n        Duration of single (positive or negative) pulse phase in seconds.\n    interphasedur : float, optional\n        Duration of inter-phase interval (between positive and negative\n        pulse) in seconds.\n    pulsetype : {'cathodicfirst', 'anodicfirst'}, optional\n        A cathodic-first pulse has the negative phase first, whereas an\n        anodic-first pulse has the positive phase first.\n\n    Returns\n    -------\n    pulses : list\n        A list of p2p.stimuli.PulseTrain objects, one for each electrode in\n        the implant.\n\n    \"\"\"\n    if not has_skimage:\n        # We don't want to repeatedly import Scikit-Image. This would (e.g.)\n        # unnecessarily slow down `video2pulsetrain`.\n        raise ImportError(\"You do not have scikit-image installed. \"\n                          \"You can install it via $ pip install scikit-image.\")\n\n    # Make sure range of values is valid\n    assert len(valrange) == 2 and valrange[1] > valrange[0]\n\n    isargus1 = isinstance(implant, implants.ArgusI)\n    isargus2 = isinstance(implant, implants.ArgusII)\n    isalphaims = isinstance(implant, implants.AlphaIMS)\n    if not isargus1 and not isargus2 and not isalphaims:\n        raise TypeError(\"For now, implant must be of type implants.ArgusI or \"\n                        \"implants.ArgusII.\")\n\n    if isinstance(img, six.string_types):\n        # Load image from filename\n        img_orig = sio.imread(img, as_grey=True).astype(np.float32)\n        logging.getLogger(__name__).info(\"Loaded file '%s'.\" % img)\n    else:\n        if img.ndim == 2:\n            # Grayscale\n            img_orig = img.astype(np.float32)\n        else:\n            # Assume RGB, convert to grayscale\n            assert img.shape[-1] == 3\n            img_orig = sic.rgb2gray(np.array(img)).astype(np.float32)\n\n    # Make sure all pixels are between 0 and 1\n    if img_orig.max() > 1.0:\n        img_orig /= 255.0\n\n    # Let Scikit-Image do the resampling: Downscale image to fit array\n    # Use mode 'reflect' for np.pad: Pads with the reflection of the vector\n    # mirrored on the first and last values of the vector along each axis.\n    if isargus1:\n        img_stim = sit.resize(img_orig, (4, 4), mode='reflect')\n    elif isargus2:\n        img_stim = sit.resize(img_orig, (6, 10), mode='reflect')\n    elif isalphaims:\n        img_stim = sit.resize(img_orig, (37, 37), mode='reflect')\n\n    # If specified, invert the mapping of grayscale values:\n    if invert:\n        img_stim = 1.0 - img_stim\n\n    # If specified, maximize the contrast in the image:\n    if max_contrast:\n        img_stim -= img_stim.min()\n        if img_stim.max() > 0:\n            img_stim /= img_stim.max()\n\n    # With all pixels between 0 and 1, now scale to valrange\n    assert np.all(img_stim >= 0.0) and np.all(img_stim <= 1.0)\n    img_stim = img_stim * np.diff(valrange) + valrange[0]\n    assert np.all(img_stim >= valrange[0]) and np.all(img_stim <= valrange[1])\n\n    stim = []\n    for _, px in np.ndenumerate(img_stim):\n        if coding == 'amplitude':\n            amp = px\n            freq = const_val\n        elif coding == 'frequency':\n            amp = const_val\n            freq = px\n        else:\n            e_s = \"Acceptable values for `coding` are 'amplitude' or\"\n            e_s += \"'frequency'.\"\n            raise ValueError(e_s)\n\n        pt = PulseTrain(tsample, freq=freq, amp=amp, dur=dur,\n                        pulse_dur=pulsedur,\n                        interphase_dur=interphasedur,\n                        pulsetype=pulsetype)\n        stim.append(pt)\n\n    return stim\n\n\ndef video2pulsetrain(filename, implant, framerate=20,\n                     coding='amplitude', valrange=[0, 50],\n                     max_contrast=False, const_val=20, invert=False,\n                     tsample=0.005 / 1000, pulsedur=0.5 / 1000.,\n                     interphasedur=0.5 / 1000., pulsetype='cathodicfirst',\n                     ffmpeg_path=None, libav_path=None):\n    \"\"\"Converts a video into a series of pulse trains\n\n    This function creates an input stimulus from a video.\n    Every frame of the video is passed to `image2pulsetrain`, where it is\n    down-sampled to fit the spatial layout of the implant (currently supported\n    are ArgusI and ArgusII arrays).\n    In this mapping, rows of the image correspond to rows in the implant\n    (top row, Argus I: A1 B1 C1 D1, Argus II: A1 A2 ... A10).\n\n    Requires Scikit-Image and Scikit-Video.\n\n    Parameters\n    ----------\n    img : str|array_like\n        An input image, either a valid filename (string) or a numpy array\n        (row x col x channels).\n    implant : p2p.implants.ElectrodeArray\n        An ElectrodeArray object that describes the implant.\n    coding : {'amplitude', 'frequency'}, optional\n        A string describing the coding scheme:\n        - 'amplitude': Image intensity is linearly converted to a current\n                       amplitude between `valrange[0]` and `valrange[1]`.\n                       Frequency is held constant at `const_freq`.\n        - 'frequency': Image intensity is linearly converted to a pulse\n                       frequency between `valrange[0]` and `valrange[1]`.\n                       Amplitude is held constant at `const_amp`.\n        Default: 'amplitude'\n    valrange : list, optional\n        Range of stimulation values to be used (If `coding` is 'amplitude',\n        specifies min and max current; if `coding` is 'frequency', specifies\n        min and max frequency).\n        Default: [0, 50]\n    max_contrast : bool, optional\n        Flag wether to maximize image contrast (True) or not (False).\n        Default: False\n    const_val : float, optional\n        For frequency coding: The constant amplitude value to be used for all\n        pulse trains. For amplitude coding: The constant frequency value to\n        be used for all pulse trains.\n        Default: 20\n    invert : bool, optional\n        Flag whether to invert the grayscale values of the image (True) or\n        not (False).\n        Default: False\n    tsample : float, optional\n        Sampling time step (seconds). Default: 0.005 / 1000 seconds.\n    dur : float, optional\n        Stimulus duration (seconds). Default: 0.5 seconds.\n    pulsedur : float, optional\n        Duration of single (positive or negative) pulse phase in seconds.\n    interphasedur : float, optional\n        Duration of inter-phase interval (between positive and negative\n        pulse) in seconds.\n    pulsetype : {'cathodicfirst', 'anodicfirst'}, optional\n        A cathodic-first pulse has the negative phase first, whereas an\n        anodic-first pulse has the positive phase first.\n\n    Returns\n    -------\n    pulses : list\n        A list of p2p.stimuli.PulseTrain objects, one for each electrode in\n        the implant.\n\n    \"\"\"\n\n    # Load generator to read video frame-by-frame\n    reader = files.load_video_generator(filename, ffmpeg_path, libav_path)\n\n    # Temporarily increase logger level to suppress info messages\n    current_level = logging.getLogger(__name__).getEffectiveLevel()\n    logging.getLogger(__name__).setLevel(logging.WARN)\n\n    # Convert the desired framerate to a duration (seconds)\n    dur = 1.0 / framerate\n\n    # Read one frame at a time, and append to previous frames\n    video = []\n    for img in reader.nextFrame():\n        frame = image2pulsetrain(img, implant, coding=coding,\n                                 valrange=valrange, max_contrast=max_contrast,\n                                 const_val=const_val, invert=invert,\n                                 tsample=tsample, dur=dur, pulsedur=pulsedur,\n                                 interphasedur=interphasedur,\n                                 pulsetype=pulsetype)\n        if video:\n            # List of pulse trains: Append new frame to each element\n            [v.append(f) for v, f in zip(video, frame)]\n        else:\n            # Initialize with a list of pulse trains\n            video = frame\n\n    # Restore logger level\n    logging.getLogger(__name__).setLevel(current_level)\n\n    return video\n\n\ndef parse_pulse_trains(stim, implant):\n    \"\"\"Parse input stimulus and convert to list of pulse trains\n\n    Parameters\n    ----------\n    stim : utils.TimeSeries|list|dict\n        There are several ways to specify an input stimulus:\n\n        - For a single-electrode array, pass a single pulse train; i.e., a\n          single utils.TimeSeries object.\n        - For a multi-electrode array, pass a list of pulse trains, where\n          every pulse train is a utils.TimeSeries object; i.e., one pulse\n          train per electrode.\n        - For a multi-electrode array, specify all electrodes that should\n          receive non-zero pulse trains by name in a dictionary. The key\n          of each element is the electrode name, the value is a pulse train.\n          Example: stim = {'E1': pt, 'stim': pt}, where 'E1' and 'stim' are\n          electrode names, and `pt` is a utils.TimeSeries object.\n    implant : p2p.implants.ElectrodeArray\n        A p2p.implants.ElectrodeArray object that describes the implant.\n\n    Returns\n    -------\n    A list of pulse trains; one pulse train per electrode.\n    \"\"\"\n    # Parse input stimulus\n    if isinstance(stim, utils.TimeSeries):\n        # `stim` is a single object: This is only allowed if the implant\n        # has only one electrode\n        if implant.num_electrodes > 1:\n            e_s = \"More than 1 electrode given, use a list of pulse trains\"\n            raise ValueError(e_s)\n        pt = [copy.deepcopy(stim)]\n    elif isinstance(stim, dict):\n        # `stim` is a dictionary: Look up electrode names and assign pulse\n        # trains, fill the rest with zeros\n\n        # Get right size from first dict element, then generate all zeros\n        idx0 = list(stim.keys())[0]\n        pt_zero = utils.TimeSeries(stim[idx0].tsample,\n                                   np.zeros_like(stim[idx0].data))\n        pt = [pt_zero] * implant.num_electrodes\n\n        # Iterate over dictionary and assign non-zero pulse trains to\n        # corresponding electrodes\n        for key, value in stim.items():\n            el_idx = implant.get_index(key)\n            if el_idx is not None:\n                pt[el_idx] = copy.deepcopy(value)\n            else:\n                e_s = \"Could not find electrode with name '%s'\" % key\n                raise ValueError(e_s)\n    else:\n        # Else, `stim` must be a list of pulse trains, one for each electrode\n        if len(stim) != implant.num_electrodes:\n            e_s = \"Number of pulse trains must match number of electrodes\"\n            raise ValueError(e_s)\n        pt = copy.deepcopy(stim)\n\n    return pt\n", "meta": {"hexsha": "7453d51f610646687c6f1e0162787ecf24a67d8d", "size": 21715, "ext": "py", "lang": "Python", "max_stars_repo_path": "pulse2percept/stimuli.py", "max_stars_repo_name": "jonluntzel/pulse2percept", "max_stars_repo_head_hexsha": "dbe17230be0354c4cfc57a72b649c611fe496464", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pulse2percept/stimuli.py", "max_issues_repo_name": "jonluntzel/pulse2percept", "max_issues_repo_head_hexsha": "dbe17230be0354c4cfc57a72b649c611fe496464", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pulse2percept/stimuli.py", "max_forks_repo_name": "jonluntzel/pulse2percept", "max_forks_repo_head_hexsha": "dbe17230be0354c4cfc57a72b649c611fe496464", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9716981132, "max_line_length": 79, "alphanum_fraction": 0.6064011052, "include": true, "reason": "import numpy", "num_tokens": 5084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.30074556640652345, "lm_q1q2_score": 0.1515475466715105}}
{"text": "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nfrom __future__ import (absolute_import, division, print_function,\n                        unicode_literals)\nimport numpy as np\nfrom astropy.table import Table\nfrom astropy.utils import lazyproperty\nfrom astropy.convolution import Kernel2D\nimport astropy.units as u\nfrom astropy.wcs.utils import pixel_to_skycoord\nfrom .utils.prepare_data import _prepare_data\n\n\n__all__ = ['SegmentProperties', 'segment_properties', 'properties_table',\n           'relabel_sequential', 'relabel_segments', 'remove_segments',\n           'remove_border_segments', 'remove_masked_segments']\n\n__doctest_requires__ = {('segment_properties', 'properties_table'): ['scipy'],\n                        ('segment_properties', 'properties_table'):\n                        ['skimage']}\n\n\nclass SegmentProperties(object):\n    \"\"\"\n    Class to calculate photometry and morphological properties of source\n    segments.\n    \"\"\"\n\n    def __init__(self, data, segment_image, label, label_slice=None,\n                 error=None, effective_gain=None, mask=None, background=None,\n                 wcs=None, filtered_data=None, data_prepared=False):\n        \"\"\"\n        Parameters\n        ----------\n        data : array_like or `~astropy.units.Quantity`\n            The 2D array from which to calculate the source photometry\n            and properties (only if ``filtered_data`` is not input).\n            ``data`` should be background-subtracted.\n\n        segment_image : array_like (int)\n            A 2D segmentation image, with the same shape as ``data``,\n            where sources are labeled by different positive integer\n            values.  A value of zero is reserved for the background.\n\n        label : int\n            The label number of a source segment in ``segment_image``\n            for which to calculate properties.\n\n        label_slice : 2-tuple of slice objects, optional\n            A ``(y_slice, x_slice)`` tuple of slice objects defining the\n            minimal box enclosing the source segment.  If `None` (the\n            default), then ``label_slice`` will be calculated.\n\n        error : array_like or `~astropy.units.Quantity`, optional\n            The pixel-wise Gaussian 1-sigma errors of the input\n            ``data``.  If ``effective_gain`` is input, then ``error``\n            should include all sources of \"background\" error but\n            *exclude* the Poisson error of the sources.  If\n            ``effective_gain`` is `None`, then the ``error_image`` is\n            assumed to include *all* sources of error, including the\n            Poisson error of the sources.  ``error`` must have the same\n            shape as ``data``.  See the Notes section below for details\n            on the error propagation.\n\n        effective_gain : float, array-like, or `~astropy.units.Quantity`, optional\n            Ratio of counts (e.g., electrons or photons) to the units of\n            ``data`` used to calculate the Poisson error of the sources.\n            If ``effective_gain`` is `None`, then the ``error`` is\n            assumed to include *all* sources of error.  See the Notes\n            section below for details on the error propagation.\n\n        mask : array_like (bool), optional\n            A boolean mask, with the same shape as ``data``, where a\n            `True` value indicates the corresponding element of ``data``\n            is masked.  Masked data are excluded from all calculations.\n\n        background : float, array_like, or `~astropy.units.Quantity`, optional\n            The background level that was previously present in the\n            input ``data``.  ``background`` may either be a scalar value\n            or a 2D image with the same shape as the input ``data``.\n            Inputting the ``background`` merely allows for its\n            properties to be measured within each source segment.  The\n            input ``background`` does *not* get subtracted from the\n            input ``data``, which should already be\n            background-subtracted.\n\n        wcs : `~astropy.wcs.WCS`\n            The WCS transformation to use.  If `None`, then\n            `icrs_centroid`, `ra_icrs_centroid`, and `dec_icrs_centroid`\n            will be `None`.\n\n        filtered_data : array-like or `~astropy.units.Quantity`, optional\n            The filtered version of the (background-subtracted) ``data``\n            from which to calculate the source centroid and\n            morphological properties.  The kernel used to perform the\n            filtering should be the same one used in defining the source\n            segments (e.g., see :func:`~photutils.detect_sources`).  If\n            `None`, then the unfiltered ``data`` will be used instead.\n            Note that `SExtractor`_'s centroid and morphological\n            parameters are calculated from the filtered \"detection\"\n            image.\n\n        data_prepared : bool, optional\n            If `True`, then ``error`` is assumed to represent the total\n            (background and source) error (``effective_gain`` will be\n            ignored) and ``background`` is assumed to be a 2D image.\n            This dramatically improves speed if you are calculating the\n            properties of many segments from the same data.\n\n        Notes\n        -----\n        `SExtractor`_'s centroid and morphological parameters are always\n        calculated from the filtered \"detection\" image.  The usual\n        downside of the filtering is the sources will be made more\n        circular than they actually are.  If you wish to reproduce\n        `SExtractor`_ results, then use the ``filtered_data`` input.  If\n        ``filtered_data`` is `None`, then the unfiltered ``data`` will\n        be used for the source centroid and morphological parameters.\n\n        Negative (background-subtracted) data values within the source\n        segment are set to zero when measuring morphological properties\n        based on image moments.  This could occur, for example, if the\n        segmentation image was defined from a different image (e.g.,\n        different bandpass) or if the subtracted background was\n        incorrectly too high.  `segment_sum` is not affected by negative\n        (background-subtracted) data values.  `segment_sum_err` is\n        affected only if ``effective_gain`` is used (see below).\n\n        If ``effective_gain`` is input, then ``error`` should include\n        all sources of \"background\" error but *exclude* the Poisson\n        error of the sources.  The total error image,\n        :math:`\\sigma_{\\mathrm{tot}}` is then:\n\n        .. math:: \\\\sigma_{\\\\mathrm{tot}} = \\\\sqrt{\\\\sigma_{\\\\mathrm{b}}^2 +\n                      \\\\frac{(I - B)}{g}}\n\n        where :math:`\\sigma_b`, :math:`(I - B)`, and :math:`g` are the\n        background ``error`` image, the background-subtracted ``data``\n        image, and ``effective_gain``, respectively.\n\n        Pixels where :math:`(I_i - B_i)` is negative do not contribute\n        additional Poisson noise to the total error, i.e.\n        :math:`\\sigma_{\\mathrm{tot}, i} = \\sigma_{\\mathrm{b}, i}`.  Note\n        that this is different from `SExtractor`_, which sums the total\n        variance in the segment, including pixels where :math:`(I_i -\n        B_i)` is negative.  In such cases, `SExtractor`_ underestimates\n        the total errors.\n\n        If ``effective_gain`` is `None`, then ``error`` is assumed to\n        include *all* sources of error, including the Poisson error of\n        the sources, i.e. :math:`\\sigma_{\\mathrm{tot}} =\n        \\mathrm{error}`.\n\n        For example, if your input ``data`` are in units of ADU, then\n        ``effective_gain`` should represent electrons/ADU.  If your\n        input ``data`` are in units of electrons/s then\n        ``effective_gain`` should be the exposure time or an exposure\n        time map (e.g., for mosaics with non-uniform exposure times).\n\n        ``effective_gain`` can be a 2D gain image with the same shape as\n        the ``data``.  This is useful with mosaic images that have\n        variable depths (i.e., exposure times) across the field.  For\n        example, one should use an exposure-time map as the\n        ``effective_gain`` for a variable depth mosaic image in\n        count-rate units.\n\n        `~photutils.SegmentProperties.segment_sum_err` is simply the\n        quadrature sum of the pixel-wise total errors over the\n        non-masked pixels within the source segment:\n\n        .. math:: \\\\Delta F = \\\\sqrt{\\\\sum_{i \\\\in S}\n                  \\\\sigma_{\\\\mathrm{tot}, i}^2}\n\n        where :math:`\\Delta F` is\n        `~photutils.SegmentProperties.segment_sum_err` and :math:`S` are\n        the non-masked pixels in the source segment.\n\n        Custom errors for source segments can be calculated using the\n        `~photutils.SegmentProperties.error_cutout_ma` and\n        `~photutils.SegmentProperties.background_cutout_ma` properties,\n        which are 2D `~numpy.ma.MaskedArray` cutout versions of the\n        input ``error`` and ``background``.  The mask is `True` for both\n        pixels outside of the source segment and masked pixels.\n\n        .. _SExtractor: http://www.astromatic.net/software/sextractor\n        \"\"\"\n\n        from scipy import ndimage\n\n        if segment_image.shape != data.shape:\n            raise ValueError('segment_image and data must have the same '\n                             'shape')\n        if mask is not None:\n            if mask.shape != data.shape:\n                raise ValueError('mask and data must have the same shape')\n\n        if label == 0:\n            raise ValueError('label \"0\" is reserved for the background')\n        elif label < 0:\n            raise ValueError('label must be a positive integer')\n\n        self._segment_image = segment_image\n        if not data_prepared:\n            data, error, background = _prepare_data(\n                data, error=error, effective_gain=effective_gain,\n                background=background)\n\n        self._data = data    # background subtracted\n        if filtered_data is None:\n            self._filtered_data = data    # background subtracted\n        else:\n            self._filtered_data = filtered_data    # bkgrd sub, then filtered\n        self._error = error    # total error from _prepare_data\n        self._background = background    # 2D error array from _prepare_data\n        self._mask = mask\n        self._wcs = wcs\n\n        self.label = label\n        if label_slice is not None:\n            self._slice = label_slice\n        else:\n            label_slices = ndimage.find_objects(segment_image)\n            self._slice = label_slices[label - 1]\n            if self._slice is None:\n                raise ValueError('label \"{0}\" is not in the input '\n                                 'segment_image'.format(label))\n\n    def __getitem__(self, key):\n        return getattr(self, key, None)\n\n    def make_cutout(self, data, masked_array=False):\n        \"\"\"\n        Create a (masked) cutout array from the input ``data`` using the\n        minimal bounding box of the source segment.\n\n        Parameters\n        ----------\n        data : array-like (2D)\n            The data array from which to create the masked cutout array.\n            ``data`` must have the same shape as the data input into\n            `SegmentProperties`.\n\n        masked_array : bool, optional\n            If `True` then a `~numpy.ma.MaskedArray` will be created\n            where the mask is `True` for both pixels outside of the\n            source segment and any masked pixels.  If `False`, then a\n            `~numpy.ndarray` will be generated.\n\n        Returns\n        -------\n        result : `~numpy.ndarray` or `~numpy.ma.MaskedArray` (2D)\n            The 2D cutout array or masked array.\n        \"\"\"\n\n        if data is not None:\n            data = np.asarray(data)\n            if data.shape != self._data.shape:\n                raise ValueError('data must have the same shape as the '\n                                 'segment image input to SegmentProperties')\n            if masked_array:\n                return np.ma.masked_array(data[self._slice],\n                                          mask=self._local_mask)\n            else:\n                return data[self._slice]\n        else:\n            return None\n\n    def to_table(self, columns=None, exclude_columns=None):\n        \"\"\"\n        Create a `~astropy.table.Table` of properties.\n\n        If ``columns`` or ``exclude_columns`` are not input, then the\n        `~astropy.table.Table` will include all scalar-valued\n        properties.  Multi-dimensional properties, e.g.\n        `~photutils.SegmentProperties.data_cutout`, can be included in\n        the ``columns`` input.\n\n        Parameters\n        ----------\n        columns : str or list of str, optional\n            Names of columns, in order, to include in the output\n            `~astropy.table.Table`.  The allowed column names are any of\n            the attributes of `SegmentProperties`.\n\n        exclude_columns : str or list of str, optional\n            Names of columns to exclude from the default properties list\n            in the output `~astropy.table.Table`.  The default\n            properties are those with scalar values.\n\n        Returns\n        -------\n        table : `~astropy.table.Table`\n            A single-row table of properties of the segmented source.\n        \"\"\"\n        return properties_table(self, columns=columns,\n                                exclude_columns=exclude_columns)\n\n    @lazyproperty\n    def _in_segment(self):\n        \"\"\"\n        _in_segment is `True` for pixels in the labeled source segment.\n        \"\"\"\n        return self._segment_image[self._slice] == self.label\n\n    @lazyproperty\n    def _local_mask(self):\n        \"\"\"\n        _local_mask is `True` for regions outside of the labeled source\n        segment or where the input mask is `True`.\n        \"\"\"\n        if self._mask is None:\n            return ~self._in_segment\n        else:\n            return np.logical_or(~self._in_segment, self._mask[self._slice])\n\n    @lazyproperty\n    def data_cutout(self):\n        \"\"\"\n        A 2D cutout from the (background-subtracted) data of the source\n        segment.\n        \"\"\"\n        return self.make_cutout(self._data, masked_array=False)\n\n    @lazyproperty\n    def data_cutout_ma(self):\n        \"\"\"\n        A 2D `~numpy.ma.MaskedArray` cutout from the\n        (background-subtracted) data, where the mask is `True` for both\n        pixels outside of the source segment and masked pixels.\n        \"\"\"\n        return self.make_cutout(self._data, masked_array=True)\n\n    @lazyproperty\n    def _data_cutout_maskzeroed_double(self):\n        \"\"\"\n        A 2D cutout from the (background-subtracted, filtered) data,\n        where pixels outside of the source segment and masked pixels are\n        set to zero.  Negative data values are also set to zero because\n        negative pixels (especially at large radii) can result in image\n        moments that result in negative variances.  The cutout image is\n        double precision, which is required for scikit-image's Cython\n        moment functions.\n        \"\"\"\n        cutout = self.make_cutout(self._filtered_data, masked_array=False)\n        cutout = np.where(cutout > 0, cutout, 0.)    # negative pixels -> 0\n        return (cutout * ~self._local_mask).astype(np.float64)\n\n    @lazyproperty\n    def error_cutout_ma(self):\n        \"\"\"\n        A 2D `~numpy.ma.MaskedArray` cutout from the input ``error``\n        image, where the mask is `True` for both pixels outside of the\n        source segment and masked pixels.  If ``error`` is `None`, then\n        ``error_cutout_ma`` is also `None`.\n        \"\"\"\n        return self.make_cutout(self._error, masked_array=True)\n\n    @lazyproperty\n    def background_cutout_ma(self):\n        \"\"\"\n        A 2D `~numpy.ma.MaskedArray` cutout from the input\n        ``background``, where the mask is `True` for both pixels outside\n        of the source segment and masked pixels.  If ``background`` is\n        `None`, then ``background_cutout_ma`` is also `None`.\n        \"\"\"\n        return self.make_cutout(self._background, masked_array=True)\n\n    @lazyproperty\n    def coords(self):\n        \"\"\"\n        A tuple of `~numpy.ndarray`\\s containing the ``y`` (first array)\n        and ``x`` (second array) pixels coordinates of the source\n        segment.  Masked pixels are not included.\n        \"\"\"\n        yy, xx = np.nonzero(self.data_cutout_ma)\n        coords = (yy + self._slice[0].start, xx + self._slice[1].start)\n        return coords\n\n    @lazyproperty\n    def values(self):\n        \"\"\"\n        A `~numpy.ndarray` of the (background-subtracted) pixel values\n        within the source segment.  Masked pixels are not included.\n        \"\"\"\n        return self.data_cutout[~self._local_mask]\n\n    @lazyproperty\n    def moments(self):\n        \"\"\"Spatial moments up to 3rd order of the source segment.\"\"\"\n        from skimage.measure import moments\n        return moments(self._data_cutout_maskzeroed_double, 3)\n\n    @lazyproperty\n    def moments_central(self):\n        \"\"\"\n        Central moments (translation invariant) of the source segment up\n        to 3rd order.\n        \"\"\"\n        from skimage.measure import moments_central\n        ycentroid, xcentroid = self.local_centroid.value\n        return moments_central(self._data_cutout_maskzeroed_double,\n                               ycentroid, xcentroid, 3)\n\n    @lazyproperty\n    def id(self):\n        \"\"\"\n        The source identification number corresponding to the object\n        label in the ``segment_image``.\n        \"\"\"\n        return self.label\n\n    @lazyproperty\n    def local_centroid(self):\n        \"\"\"\n        The ``(y, x)`` coordinate, relative to the `data_cutout`, of\n        the centroid within the source segment.\n        \"\"\"\n        m = self.moments\n        if m[0, 0] != 0:\n            ycentroid = m[0, 1] / m[0, 0]\n            xcentroid = m[1, 0] / m[0, 0]\n            return (ycentroid, xcentroid) * u.pix\n        else:\n            return (np.nan, np.nan) * u.pix\n\n    @lazyproperty\n    def centroid(self):\n        \"\"\"\n        The ``(y, x)`` coordinate of the centroid within the source\n        segment.\n        \"\"\"\n        ycen, xcen = self.local_centroid.value\n        return (ycen + self._slice[0].start,\n                xcen + self._slice[1].start) * u.pix\n\n    @lazyproperty\n    def xcentroid(self):\n        \"\"\"\n        The ``x`` coordinate of the centroid within the source segment.\n        \"\"\"\n        return self.centroid[1]\n\n    @lazyproperty\n    def ycentroid(self):\n        \"\"\"\n        The ``y`` coordinate of the centroid within the source segment.\n        \"\"\"\n        return self.centroid[0]\n\n    @lazyproperty\n    def icrs_centroid(self):\n        \"\"\"\n        The ICRS coordinates of the centroid within the source segment,\n        returned as a `~astropy.coordinates.SkyCoord` object.\n        \"\"\"\n        if self._wcs is not None:\n            return pixel_to_skycoord(self.xcentroid.value,\n                                     self.ycentroid.value,\n                                     self._wcs, origin=1).icrs\n        else:\n            return None\n\n    @lazyproperty\n    def ra_icrs_centroid(self):\n        \"\"\"\n        The ICRS Right Ascension coordinate (in degrees) of the centroid\n        within the source segment.\n        \"\"\"\n        if self._wcs is not None:\n            return self.icrs_centroid.ra.degree * u.deg\n        else:\n            return None\n\n    @lazyproperty\n    def dec_icrs_centroid(self):\n        \"\"\"\n        The ICRS Declination coordinate (in degrees) of the centroid\n        within the source segment.\n        \"\"\"\n        if self._wcs is not None:\n            return self.icrs_centroid.dec.degree * u.deg\n        else:\n            return None\n\n    @lazyproperty\n    def bbox(self):\n        \"\"\"\n        The bounding box ``(ymin, xmin, ymax, xmax)`` of the minimal\n        rectangular region containing the source segment.\n        \"\"\"\n        # (stop - 1) to return the max pixel location, not the slice index\n        return (self._slice[0].start, self._slice[1].start,\n                self._slice[0].stop - 1, self._slice[1].stop - 1) * u.pix\n\n    @lazyproperty\n    def xmin(self):\n        \"\"\"\n        The left ``x`` pixel location of the minimal bounding box\n        (`~photutils.SegmentProperties.bbox`) of the source segment.\n        \"\"\"\n        return self.bbox[1]\n\n    @lazyproperty\n    def xmax(self):\n        \"\"\"\n        The right ``x`` pixel location of the minimal bounding box\n        (`~photutils.SegmentProperties.bbox`) of the source segment.\n        \"\"\"\n        return self.bbox[3]\n\n    @lazyproperty\n    def ymin(self):\n        \"\"\"\n        The bottom ``y`` pixel location of the minimal bounding box\n        (`~photutils.SegmentProperties.bbox`) of the source segment.\n        \"\"\"\n        return self.bbox[0]\n\n    @lazyproperty\n    def ymax(self):\n        \"\"\"\n        The top ``y`` pixel location of the minimal bounding box\n        (`~photutils.SegmentProperties.bbox`) of the source segment.\n        \"\"\"\n        return self.bbox[2]\n\n    @lazyproperty\n    def min_value(self):\n        \"\"\"\n        The minimum pixel value of the (background-subtracted) data\n        within the source segment.\n        \"\"\"\n        return np.min(self.values)\n\n    @lazyproperty\n    def max_value(self):\n        \"\"\"\n        The maximum pixel value of the (background-subtracted) data\n        within the source segment.\n        \"\"\"\n        return np.max(self.values)\n\n    @lazyproperty\n    def minval_local_pos(self):\n        \"\"\"\n        The ``(y, x)`` coordinate, relative to the `data_cutout`, of the\n        minimum pixel value of the (background-subtracted) data.\n        \"\"\"\n        return np.argwhere(self.data_cutout_ma == self.min_value)[0] * u.pix\n\n    @lazyproperty\n    def maxval_local_pos(self):\n        \"\"\"\n        The ``(y, x)`` coordinate, relative to the `data_cutout`, of the\n        maximum pixel value of the (background-subtracted) data.\n        \"\"\"\n        return np.argwhere(self.data_cutout_ma == self.max_value)[0] * u.pix\n\n    @lazyproperty\n    def minval_pos(self):\n        \"\"\"\n        The ``(y, x)`` coordinate of the minimum pixel value of the\n        (background-subtracted) data.\n        \"\"\"\n        yp, xp = np.array(self.minval_local_pos)\n        return (yp + self._slice[0].start, xp + self._slice[1].start) * u.pix\n\n    @lazyproperty\n    def maxval_pos(self):\n        \"\"\"\n        The ``(y, x)`` coordinate of the maximum pixel value of the\n        (background-subtracted) data.\n        \"\"\"\n        yp, xp = np.array(self.maxval_local_pos)\n        return (yp + self._slice[0].start, xp + self._slice[1].start) * u.pix\n\n    @lazyproperty\n    def minval_xpos(self):\n        \"\"\"\n        The ``x`` coordinate of the minimum pixel value of the\n        (background-subtracted) data.\n        \"\"\"\n        return self.minval_pos[1]\n\n    @lazyproperty\n    def minval_ypos(self):\n        \"\"\"\n        The ``y`` coordinate of the minimum pixel value of the\n        (background-subtracted) data.\n        \"\"\"\n        return self.minval_pos[0]\n\n    @lazyproperty\n    def maxval_xpos(self):\n        \"\"\"\n        The ``x`` coordinate of the maximum pixel value of the\n        (background-subtracted) data.\n        \"\"\"\n        return self.maxval_pos[1]\n\n    @lazyproperty\n    def maxval_ypos(self):\n        \"\"\"\n        The ``y`` coordinate of the maximum pixel value of the\n        (background-subtracted) data.\n        \"\"\"\n        return self.maxval_pos[0]\n\n    @lazyproperty\n    def area(self):\n        \"\"\"The area of the source segment in units of pixels**2.\"\"\"\n        return len(self.values) * u.pix**2\n\n    @lazyproperty\n    def equivalent_radius(self):\n        \"\"\"\n        The radius of a circle with the same `area` as the source\n        segment.\n        \"\"\"\n        return np.sqrt(self.area / np.pi)\n\n    @lazyproperty\n    def perimeter(self):\n        \"\"\"\n        The perimeter of the source segment, approximated using a line\n        through the centers of the border pixels using a 4-connectivity.\n        \"\"\"\n        from skimage.measure import perimeter\n        return perimeter(self._in_segment, 4) * u.pix\n\n    @lazyproperty\n    def inertia_tensor(self):\n        \"\"\"\n        Inertia tensor of the source segment for the rotation around its\n        center of mass.\n        \"\"\"\n        mu = self.moments_central\n        a = mu[2, 0]\n        b = -mu[1, 1]\n        c = mu[0, 2]\n        return np.array([[a, b], [b, c]]) * u.pix**2\n\n    @lazyproperty\n    def covariance(self):\n        \"\"\"\n        The covariance matrix of the 2D Gaussian function that has the\n        same second-order moments as the source segment.\n        \"\"\"\n        mu = self.moments_central\n        if mu[0, 0] != 0:\n            m = mu / mu[0, 0]\n            covariance = self._check_covariance(\n                np.array([[m[2, 0], m[1, 1]], [m[1, 1], m[0, 2]]]))\n            return covariance * u.pix**2\n        else:\n            return np.empty((2, 2)) * np.nan * u.pix**2\n\n    @staticmethod\n    def _check_covariance(covariance):\n        \"\"\"\n        Check and modify the covariance matrix in the case of\n        \"infinitely\" thin detections.  This follows SExtractor's\n        prescription.\n        \"\"\"\n        p = 1. / 12\n        val = (covariance[0, 0] * covariance[1, 1]) - covariance[0, 1]**2\n        if val >= p**2:\n            return covariance\n        else:\n            covar = np.copy(covariance)\n            while val < p**2:\n                covar[0, 0] += p\n                covar[1, 1] += p\n                val = (covar[0, 0] * covar[1, 1]) - covar[0, 1]**2\n            return covar\n\n    @lazyproperty\n    def covariance_eigvals(self):\n        \"\"\"\n        The two eigenvalues of the `covariance` matrix in decreasing\n        order.\n        \"\"\"\n        if not np.isnan(np.sum(self.covariance)):\n            eigvals = np.linalg.eigvals(self.covariance)\n            if np.any(eigvals < 0):    # negative variance\n                return (np.nan, np.nan) * u.pix**2\n            return (np.max(eigvals), np.min(eigvals)) * u.pix**2\n        else:\n            return (np.nan, np.nan) * u.pix**2\n\n    @lazyproperty\n    def semimajor_axis_sigma(self):\n        \"\"\"\n        The 1-sigma standard deviation along the semimajor axis of the\n        2D Gaussian function that has the same second-order central\n        moments as the source segment.\n        \"\"\"\n        # this matches SExtractor's A parameter\n        return np.sqrt(self.covariance_eigvals[0])\n\n    @lazyproperty\n    def semiminor_axis_sigma(self):\n        \"\"\"\n        The 1-sigma standard deviation along the semiminor axis of the\n        2D Gaussian function that has the same second-order central\n        moments as the source segment.\n        \"\"\"\n        # this matches SExtractor's B parameter\n        return np.sqrt(self.covariance_eigvals[1])\n\n    @lazyproperty\n    def eccentricity(self):\n        \"\"\"\n        The eccentricity of the 2D Gaussian function that has the same\n        second-order moments as the source segment.\n\n        The eccentricity is the fraction of the distance along the\n        semimajor axis at which the focus lies.\n\n        .. math:: e = \\\\sqrt{1 - \\\\frac{b^2}{a^2}}\n\n        where :math:`a` and :math:`b` are the lengths of the semimajor\n        and semiminor axes, respectively.\n        \"\"\"\n        l1, l2 = self.covariance_eigvals\n        if l1 == 0:\n            return 0.\n        return np.sqrt(1. - (l2 / l1))\n\n    @lazyproperty\n    def orientation(self):\n        \"\"\"\n        The angle in radians between the ``x`` axis and the major axis\n        of the 2D Gaussian function that has the same second-order\n        moments as the source segment.  The angle increases in the\n        counter-clockwise direction.\n        \"\"\"\n        a, b, b, c = self.covariance.flat\n        if a < 0 or c < 0:    # negative variance\n            return np.nan * u.rad\n        return 0.5 * np.arctan2(2. * b, (a - c))\n\n    @lazyproperty\n    def elongation(self):\n        \"\"\"\n        `SExtractor`_'s elongation parameter.\n\n        .. math:: \\mathrm{elongation} = \\\\frac{a}{b}\n\n        where :math:`a` and :math:`b` are the lengths of the semimajor\n        and semiminor axes, respectively.\n        \"\"\"\n        return self.semimajor_axis_sigma / self.semiminor_axis_sigma\n\n    @lazyproperty\n    def ellipticity(self):\n        \"\"\"\n        `SExtractor`_'s ellipticity parameter.\n\n        .. math:: \\mathrm{ellipticity} = 1 - \\\\frac{b}{a}\n\n        where :math:`a` and :math:`b` are the lengths of the semimajor\n        and semiminor axes, respectively.\n        \"\"\"\n        return 1.0 - (self.semiminor_axis_sigma / self.semimajor_axis_sigma)\n\n    @lazyproperty\n    def covar_sigx2(self):\n        \"\"\"\n        The ``(0, 0)`` element of the `covariance` matrix, representing\n        :math:`\\sigma_x^2`, in units of pixel**2.\n\n        Note that this is the same as `SExtractor`_'s X2 parameter.\n        \"\"\"\n        return self.covariance[0, 0]\n\n    @lazyproperty\n    def covar_sigy2(self):\n        \"\"\"\n        The ``(1, 1)`` element of the `covariance` matrix, representing\n        :math:`\\sigma_y^2`, in units of pixel**2.\n\n        Note that this is the same as `SExtractor`_'s Y2 parameter.\n        \"\"\"\n        return self.covariance[1, 1]\n\n    @lazyproperty\n    def covar_sigxy(self):\n        \"\"\"\n        The ``(0, 1)`` and ``(1, 0)`` element of the `covariance`\n        matrix, representing :math:`\\sigma_x \\sigma_y`, in units of\n        pixel**2.\n\n        Note that this is the same as `SExtractor`_'s XY parameter.\n        \"\"\"\n        return self.covariance[0, 1]\n\n    @lazyproperty\n    def cxx(self):\n        \"\"\"\n        `SExtractor`_'s CXX ellipse parameter in units of pixel**(-2).\n\n        The ellipse is defined as\n\n            .. math::\n                cxx (x - \\\\bar{x})^2 + cxy (x - \\\\bar{x}) (y - \\\\bar{y}) +\n                cyy (y - \\\\bar{y})^2 = R^2\n\n        where :math:`R` is a parameter which scales the ellipse (in\n        units of the axes lengths).  `SExtractor`_ reports that the\n        isophotal limit of a source is well represented by :math:`R\n        \\\\approx 3`.\n        \"\"\"\n        return ((np.cos(self.orientation) / self.semimajor_axis_sigma)**2 +\n                (np.sin(self.orientation) / self.semiminor_axis_sigma)**2)\n\n    @lazyproperty\n    def cyy(self):\n        \"\"\"\n        `SExtractor`_'s CYY ellipse parameter in units of pixel**(-2).\n\n        The ellipse is defined as\n\n            .. math::\n                cxx (x - \\\\bar{x})^2 + cxy (x - \\\\bar{x}) (y - \\\\bar{y}) +\n                cyy (y - \\\\bar{y})^2 = R^2\n\n        where :math:`R` is a parameter which scales the ellipse (in\n        units of the axes lengths).  `SExtractor`_ reports that the\n        isophotal limit of a source is well represented by :math:`R\n        \\\\approx 3`.\n        \"\"\"\n        return ((np.sin(self.orientation) / self.semimajor_axis_sigma)**2 +\n                (np.cos(self.orientation) / self.semiminor_axis_sigma)**2)\n\n    @lazyproperty\n    def cxy(self):\n        \"\"\"\n        `SExtractor`_'s CXY ellipse parameter in units of pixel**(-2).\n\n        The ellipse is defined as\n\n            .. math::\n                cxx (x - \\\\bar{x})^2 + cxy (x - \\\\bar{x}) (y - \\\\bar{y}) +\n                cyy (y - \\\\bar{y})^2 = R^2\n\n        where :math:`R` is a parameter which scales the ellipse (in\n        units of the axes lengths).  `SExtractor`_ reports that the\n        isophotal limit of a source is well represented by :math:`R\n        \\\\approx 3`.\n        \"\"\"\n        return (2. * np.cos(self.orientation) * np.sin(self.orientation) *\n                ((1. / self.semimajor_axis_sigma**2) -\n                 (1. / self.semiminor_axis_sigma**2)))\n\n    @lazyproperty\n    def segment_sum(self):\n        \"\"\"\n        The sum of the non-masked background-subtracted data values\n        within the source segment.\n\n        .. math:: F = \\\\sum_{i \\\\in S} (I_i - B_i)\n\n        where :math:`F` is ``segment_sum``, :math:`(I_i - B_i)` is the\n        background-subtracted input ``data``, and :math:`S` are the\n        non-masked pixels in the source segment.\n        \"\"\"\n        return np.sum(np.ma.masked_array(self._data[self._slice],\n                                         mask=self._local_mask))\n\n    @lazyproperty\n    def segment_sum_err(self):\n        \"\"\"\n        The uncertainty of `~photutils.SegmentProperties.segment_sum`,\n        propagated from the input ``error`` array.\n\n        ``segment_sum_err`` is the quadrature sum of the total errors\n        over the non-masked pixels within the source segment:\n\n        .. math:: \\\\Delta F = \\\\sqrt{\\\\sum_{i \\\\in S}\n                  \\\\sigma_{\\\\mathrm{tot}, i}^2}\n\n        where :math:`\\Delta F` is ``segment_sum_err``,\n        :math:`\\sigma_{\\mathrm{tot, i}}` are the pixel-wise total\n        errors, and :math:`S` are the non-masked pixels in the source\n        segment.\n        \"\"\"\n        if self._error is not None:\n            # power doesn't work here, see astropy #2968\n            # return np.sqrt(np.sum(self.error_cutout_ma**2))\n            return np.sqrt(np.sum(\n                np.ma.masked_array(self.error_cutout_ma.data**2,\n                                   mask=self.error_cutout_ma.mask)))\n        else:\n            return None\n\n    @lazyproperty\n    def background_sum(self):\n        \"\"\"The sum of ``background`` values within the source segment.\"\"\"\n        if self._background is not None:\n            return np.sum(self.background_cutout_ma)\n        else:\n            return None\n\n    @lazyproperty\n    def background_mean(self):\n        \"\"\"The mean of ``background`` values within the source segment.\"\"\"\n        if self._background is not None:\n            return np.mean(self.background_cutout_ma)\n        else:\n            return None\n\n    @lazyproperty\n    def background_atcentroid(self):\n        \"\"\"\n        The value of the ``background`` at the position of the source\n        centroid.\n        \"\"\"\n        if self._background is None:\n            return None\n        else:\n            return self._background[int(self.ycentroid.value),\n                                    int(self.xcentroid.value)]\n\n\ndef segment_properties(data, segment_image, error=None, effective_gain=None,\n                       mask=None, background=None, filter_kernel=None,\n                       wcs=None, labels=None):\n    \"\"\"\n    Calculate photometry and morphological properties of sources defined\n    by a labeled segmentation image.\n\n    Parameters\n    ----------\n    data : array_like or `~astropy.units.Quantity`\n        The 2D array from which to calculate the source photometry and\n        properties.  ``data`` should be background-subtracted.\n\n    segment_image : array_like (int)\n        A 2D segmentation image, with the same shape as ``data``, where\n        sources are labeled by different positive integer values.  A\n        value of zero is reserved for the background.\n\n    error : array_like or `~astropy.units.Quantity`, optional\n        The pixel-wise Gaussian 1-sigma errors of the input ``data``.\n        If ``effective_gain`` is input, then ``error`` should include\n        all sources of \"background\" error but *exclude* the Poisson\n        error of the sources.  If ``effective_gain`` is `None`, then the\n        ``error_image`` is assumed to include *all* sources of error,\n        including the Poisson error of the sources.  ``error`` must have\n        the same shape as ``data``.  See the Notes section below for\n        details on the error propagation.\n\n    effective_gain : float, array-like, or `~astropy.units.Quantity`, optional\n        Ratio of counts (e.g., electrons or photons) to the units of\n        ``data`` used to calculate the Poisson error of the sources.  If\n        ``effective_gain`` is `None`, then the ``error`` is assumed to\n        include *all* sources of error.  See the Notes section below for\n        details on the error propagation.\n\n    mask : array_like (bool), optional\n        A boolean mask, with the same shape as ``data``, where a `True`\n        value indicates the corresponding element of ``data`` is masked.\n        Masked data are excluded from all calculations.\n\n    background : float, array_like, or `~astropy.units.Quantity`, optional\n        The background level that was previously present in the input\n        ``data``.  ``background`` may either be a scalar value or a 2D\n        image with the same shape as the input ``data``.  Inputting the\n        ``background`` merely allows for its properties to be measured\n        within each source segment.  The input ``background`` does *not*\n        get subtracted from the input ``data``, which should already be\n        background-subtracted.\n\n    filter_kernel : array-like (2D) or `~astropy.convolution.Kernel2D`, optional\n        The 2D array of the kernel used to filter the data prior to\n        calculating the source centroid and morphological parameters.\n        The kernel should be the same one used in defining the source\n        segments (e.g., see :func:`~photutils.detect_sources`).  If\n        `None`, then the unfiltered ``data`` will be used instead.  Note\n        that `SExtractor`_'s centroid and morphological parameters are\n        calculated from the filtered \"detection\" image.\n\n    wcs : `~astropy.wcs.WCS`\n        The WCS transformation to use.  If `None`, then the\n        ``ra_icrs_centroid`` and ``dec_icrs_centroid`` columns will\n        contain `None`\\s.\n\n    labels : int or list of ints\n        Subset of ``segment_image`` labels for which to calculate the\n        properties.  If `None`, then the properties will be calculated\n        for all source segments (the default).\n\n    Returns\n    -------\n    output : list of `SegmentProperties` objects\n        A list of `SegmentProperties` objects, one for each source\n        segment.  The properties can be accessed as attributes or keys.\n\n    Notes\n    -----\n    `SExtractor`_'s centroid and morphological parameters are always\n    calculated from the filtered \"detection\" image.  The usual downside\n    of the filtering is the sources will be made more circular than they\n    actually are.  If you wish to reproduce `SExtractor`_ results, then\n    use the ``filtered_data`` input.  If ``filtered_data`` is `None`,\n    then the unfiltered ``data`` will be used for the source centroid\n    and morphological parameters.\n\n    Negative (background-subtracted) data values within the source\n    segment are set to zero when measuring morphological properties\n    based on image moments.  This could occur, for example, if the\n    segmentation image was defined from a different image (e.g.,\n    different bandpass) or if the subtracted background was incorrectly\n    too high.  `~photutils.SegmentProperties.segment_sum` is not\n    affected by negative (background-subtracted) data values.\n    `~photutils.SegmentProperties.segment_sum_err` is affected only if\n    ``effective_gain`` is used (see below).\n\n    If ``effective_gain`` is input, then ``error`` should include all\n    sources of \"background\" error but *exclude* the Poisson error of the\n    sources.  The total error image, :math:`\\sigma_{\\mathrm{tot}}` is\n    then:\n\n    .. math:: \\\\sigma_{\\\\mathrm{tot}} = \\\\sqrt{\\\\sigma_{\\\\mathrm{b}}^2 +\n                  \\\\frac{(I - B)}{g}}\n\n    where :math:`\\sigma_b`, :math:`(I - B)`, and :math:`g` are the\n    background ``error`` image, the background-subtracted ``data``\n    image, and ``effective_gain``, respectively.\n\n    Pixels where :math:`(I_i - B_i)` is negative do not contribute\n    additional Poisson noise to the total error, i.e.\n    :math:`\\sigma_{\\mathrm{tot}, i} = \\sigma_{\\mathrm{b}, i}`.  Note\n    that this is different from `SExtractor`_, which sums the total\n    variance in the segment, including pixels where :math:`(I_i - B_i)`\n    is negative.  In such cases, `SExtractor`_ underestimates the total\n    errors.\n\n    If ``effective_gain`` is `None`, then ``error`` is assumed to\n    include *all* sources of error, including the Poisson error of the\n    sources, i.e. :math:`\\sigma_{\\mathrm{tot}} = \\mathrm{error}`.\n\n    For example, if your input ``data`` are in units of ADU, then\n    ``effective_gain`` should represent electrons/ADU.  If your input\n    ``data`` are in units of electrons/s then ``effective_gain`` should\n    be the exposure time or an exposure time map (e.g., for mosaics with\n    non-uniform exposure times).\n\n    ``effective_gain`` can be a 2D gain image with the same shape as the\n    ``data``.  This is useful with mosaic images that have variable\n    depths (i.e., exposure times) across the field.  For example, one\n    should use an exposure-time map as the ``effective_gain`` for a\n    variable depth mosaic image in count-rate units.\n\n    `~photutils.SegmentProperties.segment_sum_err` is simply the\n    quadrature sum of the pixel-wise total errors over the non-masked\n    pixels within the source segment:\n\n    .. math:: \\\\Delta F = \\\\sqrt{\\\\sum_{i \\\\in S}\n              \\\\sigma_{\\\\mathrm{tot}, i}^2}\n\n    where :math:`\\Delta F` is\n    `~photutils.SegmentProperties.segment_sum_err` and :math:`S` are the\n    non-masked pixels in the source segment.\n\n    .. _SExtractor: http://www.astromatic.net/software/sextractor\n\n    See Also\n    --------\n    :class:`photutils.detection.detect_sources`, properties_table\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> from photutils import segment_properties\n    >>> image = np.arange(16.).reshape(4, 4)\n    >>> print(image)\n    [[  0.   1.   2.   3.]\n     [  4.   5.   6.   7.]\n     [  8.   9.  10.  11.]\n     [ 12.  13.  14.  15.]]\n    >>> segm_image = np.array([[1, 1, 0, 0],\n    ...                        [1, 0, 0, 2],\n    ...                        [0, 0, 2, 2],\n    ...                        [0, 2, 2, 0]])\n    >>> props = segment_properties(image, segm_image)\n\n    Print some properties of the first object (labeled with ``1`` in the\n    segmentation image):\n\n    >>> print(props[0].id)    # id corresponds to segment label number\n    1\n    >>> print(props[0].centroid)    # doctest: +FLOAT_CMP\n    [ 0.8  0.2] pix\n    >>> print(props[0].segment_sum)    # doctest: +FLOAT_CMP\n    5.0\n    >>> print(props[0].area)    # doctest: +FLOAT_CMP\n    3.0 pix2\n    >>> print(props[0].max_value)    # doctest: +FLOAT_CMP\n    4.0\n\n    Print some properties of the second object (labeled with ``2`` in\n    the segmentation image):\n\n    >>> print(props[1].id)    # id corresponds to segment label number\n    2\n    >>> print(props[1].centroid)    # doctest: +FLOAT_CMP\n    [ 2.36363636  2.09090909] pix\n    >>> print(props[1].perimeter)    # doctest: +FLOAT_CMP\n    5.41421356237 pix\n    >>> print(props[1].orientation)    # doctest: +FLOAT_CMP\n    -0.741759306923 rad\n    \"\"\"\n\n    from scipy import ndimage\n\n    if segment_image.shape != data.shape:\n        raise ValueError('segment_image and data must have the same shape')\n\n    if labels is None:\n        label_ids = np.unique(segment_image[segment_image > 0])\n    else:\n        label_ids = np.atleast_1d(labels)\n\n    # prepare the input data once, instead of repeating for each segment\n    data, error, background = _prepare_data(\n        data, error=error, effective_gain=effective_gain,\n        background=background)\n    data_prepared = True\n\n    # filter the data once, instead of repeating for each segment\n    if filter_kernel is not None:\n        conv_mode, conv_val = 'constant', 0.0\n        if isinstance(filter_kernel, Kernel2D):\n            filtered_data = ndimage.convolve(data, filter_kernel.array,\n                                             mode=conv_mode, cval=conv_val)\n        else:\n            filtered_data = ndimage.convolve(data, filter_kernel,\n                                             mode=conv_mode, cval=conv_val)\n    else:\n        filtered_data = None\n\n    label_slices = ndimage.find_objects(segment_image)\n    segm_propslist = []\n    for i, label_slice in enumerate(label_slices):\n        label = i + 1    # consecutive even if some label numbers are missing\n        # label_slice is None for missing label numbers\n        if label_slice is None or label not in label_ids:\n            continue\n        segm_props = SegmentProperties(\n            data, segment_image, label, label_slice=label_slice, error=error,\n            effective_gain=effective_gain, mask=mask, background=background,\n            wcs=wcs, filtered_data=filtered_data, data_prepared=data_prepared)\n        segm_propslist.append(segm_props)\n    return segm_propslist\n\n\ndef properties_table(segment_props, columns=None, exclude_columns=None):\n    \"\"\"\n    Construct a `~astropy.table.Table` of properties from a list of\n    `SegmentProperties` objects.\n\n    If ``columns`` or ``exclude_columns`` are not input, then the\n    `~astropy.table.Table` will include all scalar-valued properties.\n    Multi-dimensional properties, e.g.\n    `~photutils.SegmentProperties.data_cutout`, can be included in the\n    ``columns`` input.\n\n    Parameters\n    ----------\n    segment_props : `SegmentProperties` or list of `SegmentProperties`\n        A `SegmentProperties` object or list of `SegmentProperties`\n        objects, one for each source segment.\n\n    columns : str or list of str, optional\n        Names of columns, in order, to include in the output\n        `~astropy.table.Table`.  The allowed column names are any of the\n        attributes of `SegmentProperties`.\n\n    exclude_columns : str or list of str, optional\n        Names of columns to exclude from the default properties list in\n        the output `~astropy.table.Table`.  The default properties are\n        those with scalar values.\n\n    Returns\n    -------\n    table : `~astropy.table.Table`\n        A table of properties of the segmented sources, one row per\n        source segment.\n\n    See Also\n    --------\n    :class:`photutils.detection.detect_sources`, segment_properties\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> from photutils import segment_properties, properties_table\n    >>> image = np.arange(16.).reshape(4, 4)\n    >>> print(image)\n    [[  0.   1.   2.   3.]\n     [  4.   5.   6.   7.]\n     [  8.   9.  10.  11.]\n     [ 12.  13.  14.  15.]]\n    >>> segm_image = np.array([[1, 1, 0, 0],\n    ...                        [1, 0, 0, 2],\n    ...                        [0, 0, 2, 2],\n    ...                        [0, 2, 2, 0]])\n    >>> segm_props = segment_properties(image, segm_image)\n    >>> columns = ['id', 'xcentroid', 'ycentroid', 'segment_sum']\n    >>> t = properties_table(segm_props, columns=columns)\n    >>> print(t)\n     id   xcentroid     ycentroid   segment_sum\n             pix           pix\n    --- ------------- ------------- -----------\n      1           0.2           0.8         5.0\n      2 2.09090909091 2.36363636364        55.0\n    \"\"\"\n\n    if isinstance(segment_props, list) and len(segment_props) == 0:\n        raise ValueError('segment_props is an empty list')\n    segment_props = np.atleast_1d(segment_props)\n\n    props_table = Table()\n    # all scalar-valued properties\n    columns_all = ['id', 'xcentroid', 'ycentroid', 'ra_icrs_centroid',\n                   'dec_icrs_centroid', 'segment_sum',\n                   'segment_sum_err', 'background_sum', 'background_mean',\n                   'background_atcentroid', 'xmin', 'xmax', 'ymin', 'ymax',\n                   'min_value', 'max_value', 'minval_xpos', 'minval_ypos',\n                   'maxval_xpos', 'maxval_ypos', 'area', 'equivalent_radius',\n                   'perimeter', 'semimajor_axis_sigma',\n                   'semiminor_axis_sigma', 'eccentricity', 'orientation',\n                   'ellipticity', 'elongation', 'covar_sigx2',\n                   'covar_sigxy', 'covar_sigy2', 'cxx', 'cxy', 'cyy']\n\n    table_columns = None\n    if exclude_columns is not None:\n        table_columns = [s for s in columns_all if s not in exclude_columns]\n\n    if columns is not None:\n        table_columns = np.atleast_1d(columns)\n\n    if table_columns is None:\n        table_columns = columns_all\n\n    # it's *much* faster to calculate world coordinates using the\n    # complete list of (x, y) instead of from the individual (x, y).\n    # The assumption here is that the wcs is the same for each\n    # element of segment_props.\n    if ('ra_icrs_centroid' in table_columns or\n            'dec_icrs_centroid' in table_columns):\n        xcentroid = [props.xcentroid.value for props in segment_props]\n        ycentroid = [props.ycentroid.value for props in segment_props]\n        if segment_props[0]._wcs is not None:\n            skycoord = pixel_to_skycoord(\n                xcentroid, ycentroid, segment_props[0]._wcs, origin=1).icrs\n            ra = skycoord.ra.degree * u.deg\n            dec = skycoord.dec.degree * u.deg\n        else:\n            nprops = len(segment_props)\n            ra, dec = [None] * nprops, [None] * nprops\n\n    for column in table_columns:\n        if column == 'ra_icrs_centroid':\n            props_table[column] = ra\n        elif column == 'dec_icrs_centroid':\n            props_table[column] = dec\n        else:\n            values = [getattr(props, column) for props in segment_props]\n            if isinstance(values[0], u.Quantity):\n                # turn list of Quantities into a Quantity array\n                values = u.Quantity(values)\n            props_table[column] = values\n\n    return props_table\n\n\ndef relabel_sequential(segment_image, start_label=1):\n    \"\"\"\n    Relabel the labels in a segmentation image sequentially, such that\n    there are no missing label numbers.\n\n    Parameters\n    ----------\n    segment_image : array_like (int)\n        A 2D segmentation image where sources are labeled by different\n        positive integer values.  A value of zero is reserved for the\n        background.\n\n    start_label : int\n        The starting label number, which should be strictly positive.\n        The default is 1.\n\n    Returns\n    -------\n    result : `~numpy.ndarray` (int)\n        The relabeled segmentation image.\n\n    Examples\n    --------\n    >>> from photutils.segmentation import relabel_sequential\n    >>> segment_image = [[1, 1, 0],\n    ...                  [1, 0, 3],\n    ...                  [0, 3, 3]]\n    >>> relabel_sequential(segment_image)\n    array([[1, 1, 0],\n           [1, 0, 2],\n           [0, 2, 2]])\n    \"\"\"\n\n    if start_label <= 0:\n        raise ValueError('start_label must be >= 0.')\n    segment_image = np.array(segment_image).astype(np.int)\n    label_max = int(np.max(segment_image))\n    labels = np.unique(segment_image[segment_image.nonzero()])\n    if (label_max == len(labels)) and (labels[0] == start_label):\n        return segment_image\n    forward_map = np.zeros(label_max + 1, dtype=np.int)\n    forward_map[labels] = np.arange(len(labels)) + start_label\n    return forward_map[segment_image]\n\n\ndef relabel_segments(segment_image, labels, new_label):\n    \"\"\"\n    Relabel the labels in a segmentation image. ``labels`` will be\n    relabeled to ``new_label``.\n\n    Parameters\n    ----------\n    segment_image : array_like (int)\n        A 2D segmentation image where sources are labeled by different\n        positive integer values.  A value of zero is reserved for the\n        background.\n\n    labels : int, array-like (1D, int)\n        The label numbers(s) to relabel.\n\n    new_label : int\n        The relabeled label number.\n\n    Returns\n    -------\n    result : `~numpy.ndarray` (int)\n        The relabeled segmentation image.\n\n    Examples\n    --------\n    >>> from photutils.segmentation import relabel_segments\n    >>> segment_image = [[1, 1, 0],\n    ...                  [0, 0, 3],\n    ...                  [2, 0, 3]]\n    >>> relabel_segments(segment_image, labels=[1, 3], new_label=5)\n    array([[5, 5, 0],\n           [0, 0, 5],\n           [2, 0, 5]])\n    \"\"\"\n\n    labels = np.atleast_1d(labels)\n    segment_image = np.array(segment_image, copy=True).astype(np.int)\n    for label in labels:\n        segment_image[np.where(segment_image == label)] = new_label\n    return segment_image\n\n\ndef remove_segments(segment_image, labels, relabel=False):\n    \"\"\"\n    Remove labeled segments from a segmentation image.\n\n    Parameters\n    ----------\n    segment_image : array_like (int)\n        A 2D segmentation image where sources are labeled by different\n        positive integer values.  A value of zero is reserved for the\n        background.\n\n    labels : int, array-like (1D, int)\n        The label number(s) of the segments to remove.  Labels of zero\n        and those not in ``segment_image`` will be ignored.\n\n    relabel : bool\n        If `True`, the the segmentation image will be relabeled such\n        that the labels are in sequential order starting from 1.\n\n    Returns\n    -------\n    result : `~numpy.ndarray` (int)\n        The modified segmentation image.\n\n    Examples\n    --------\n    >>> from photutils.segmentation import remove_segments\n    >>> segment_image = [[1, 1, 0],\n    ...                  [0, 0, 3],\n    ...                  [2, 0, 3]]\n    >>> remove_segments(segment_image, labels=2)\n    array([[1, 1, 0],\n           [0, 0, 3],\n           [0, 0, 3]])\n    \"\"\"\n\n    segment_out = relabel_segments(segment_image, labels, new_label=0)\n    if relabel:\n        segment_out = relabel_sequential(segment_out)\n    return segment_out\n\n\ndef remove_border_segments(segment_image, border_width, partial_overlap=True,\n                           relabel=False):\n    \"\"\"\n    Remove labeled segments around the border of a segmentation image.\n\n    Parameters\n    ----------\n    segment_image : array_like (int)\n        A 2D segmentation image where sources are labeled by different\n        positive integer values.  A value of zero is reserved for the\n        background.\n\n    border_width : int\n        The width of the border region in pixels.\n\n    partial_overlap : bool, optional\n        If this is set to `True` (the default), a segment that partially\n        extends into the border region will also be removed.  Segments\n        that are completely within the border region are always removed.\n\n    relabel : bool\n        If `True`, the the segmentation image will be relabeled such\n        that the labels are in sequential order starting from 1.\n\n    Returns\n    -------\n    result : `~numpy.ndarray` (int)\n        The modified segmentation image.\n\n    Examples\n    --------\n    >>> from photutils.segmentation import remove_border_segments\n    >>> segment_image = [[1, 1, 0, 4, 4],\n    ...                  [0, 0, 0, 0, 0],\n    ...                  [0, 0, 3, 0, 5],\n    ...                  [2, 2, 0, 0, 5],\n    ...                  [2, 2, 0, 5, 5]]\n    >>> remove_border_segments(segment_image, border_width=1)\n    array([[0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0],\n           [0, 0, 3, 0, 0],\n           [0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0]])\n    >>> remove_border_segments(segment_image, border_width=1,\n    ...                        partial_overlap=False)\n    array([[0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0],\n           [0, 0, 3, 0, 0],\n           [2, 2, 0, 0, 0],\n           [2, 2, 0, 0, 0]])\n    \"\"\"\n\n    segment_image = np.array(segment_image).astype(np.int)\n    if border_width >= min(segment_image.shape) / 2:\n        raise ValueError('border_width must be smaller than half the '\n                         'image size in either dimension')\n    border = np.zeros_like(segment_image, dtype=np.bool)\n    border[:border_width, :] = True\n    border[-border_width:, :] = True\n    border[:, :border_width] = True\n    border[:, -border_width:] = True\n    return remove_masked_segments(segment_image, border,\n                                  partial_overlap=partial_overlap,\n                                  relabel=relabel)\n\n\ndef remove_masked_segments(segment_image, mask, partial_overlap=True,\n                           relabel=False):\n    \"\"\"\n    Remove labeled segments located within a masked region.\n\n    Parameters\n    ----------\n    segment_image : array_like (int)\n        A 2D segmentation image where sources are labeled by different\n        positive integer values.  A value of zero is reserved for the\n        background.\n\n    mask : array_like (bool), optional\n        A boolean mask, with the same shape as ``segment_image``, where\n        a `True` value indicates masked pixels.\n\n    partial_overlap : bool, optional\n        If this is set to `True` (the default), a segment that partially\n        extends into a masked region will also be removed.  Segments\n        that are completely within a masked region are always removed.\n\n    relabel : bool\n        If `True`, the the segmentation image will be relabeled such\n        that the labels are in sequential order starting from 1.\n\n    Returns\n    -------\n    result : `~numpy.ndarray` (int)\n        The modified segmentation image.\n\n    Examples\n    --------\n    >>> from photutils.segmentation import remove_masked_segments\n    >>> segment_image = [[1, 1, 0, 4, 4],\n    ...                  [0, 0, 0, 0, 4],\n    ...                  [0, 0, 3, 0, 0],\n    ...                  [2, 2, 0, 0, 5],\n    ...                  [2, 2, 0, 5, 5]]\n    >>> mask = np.zeros_like(segment_image, dtype=np.bool)\n    >>> mask[0, :] = True\n    >>> remove_masked_segments(segment_image, mask)\n    array([[0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0],\n           [0, 0, 3, 0, 0],\n           [2, 2, 0, 0, 5],\n           [2, 2, 0, 5, 5]])\n    >>> remove_masked_segments(segment_image, mask, partial_overlap=False)\n    array([[0, 0, 0, 4, 4],\n           [0, 0, 0, 0, 4],\n           [0, 0, 3, 0, 0],\n           [2, 2, 0, 0, 5],\n           [2, 2, 0, 5, 5]])\n    \"\"\"\n\n    segment_image = np.array(segment_image).astype(np.int)\n    if segment_image.shape != mask.shape:\n        raise ValueError('segment_image and mask must have the same shape')\n    labels = np.unique(segment_image[mask])\n    if not partial_overlap:\n        inside_labels = np.unique(segment_image[~mask])\n        labels = [i for i in labels if i not in inside_labels]\n    return remove_segments(segment_image, labels, relabel=relabel)\n", "meta": {"hexsha": "b628b9777e5a2fad9ea8a277e6163442d2c411d6", "size": 57837, "ext": "py", "lang": "Python", "max_stars_repo_path": "photutils/segmentation.py", "max_stars_repo_name": "fred3m/photutils", "max_stars_repo_head_hexsha": "e6b02d6c58e130d26446d9bafb65d3455df280a4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "photutils/segmentation.py", "max_issues_repo_name": "fred3m/photutils", "max_issues_repo_head_hexsha": "e6b02d6c58e130d26446d9bafb65d3455df280a4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "photutils/segmentation.py", "max_forks_repo_name": "fred3m/photutils", "max_forks_repo_head_hexsha": "e6b02d6c58e130d26446d9bafb65d3455df280a4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.654296875, "max_line_length": 82, "alphanum_fraction": 0.6007400107, "include": true, "reason": "import numpy,from scipy,import astropy,from astropy", "num_tokens": 14014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3007455664065234, "lm_q1q2_score": 0.15154754667151046}}
{"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nsilentsub.device\n================\n\nA generic device class for multiprimary light stimulators.\n\n@author: jtm\n\"\"\"\n\nfrom typing import List, Union, Optional, Tuple, Any\n\nfrom scipy.interpolate import interp1d\nfrom scipy.optimize import curve_fit, minimize, basinhopping, OptimizeResult\nfrom scipy.stats import beta\nimport matplotlib.pyplot as plt\nimport matplotlib.path as mplpath\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\nfrom colour.plotting import plot_chromaticity_diagram_CIE1931\n\nfrom pysilsub.CIE import (get_CIES026,\n                           get_CIE_1924_photopic_vl,\n                           get_CIE170_2_chromaticity_coordinates)\nfrom pysilsub import colorfunc\nfrom pysilsub.plotting import stim_plot\n\nSettings = Union[List[int], List[float]]\n\n\nclass StimulationDevice:\n    \"\"\"Generic class for multiprimary stimultion device.\"\"\"\n\n    # Class attribute colors for photoreceptors\n    photoreceptors = ['S', 'M', 'L', 'R', 'I']\n    \n    aopic_colors = {\n        'S': 'tab:blue',\n        'M': 'tab:green',\n        'L': 'tab:red',\n        'R': 'tab:grey',\n        'I': 'tab:cyan'\n    }\n\n    # empty dict for curve fit params\n    curveparams = {}\n\n    def __init__(self,\n                 resolutions: List[int],\n                 colors: List[str],\n                 spds: pd.DataFrame,\n                 spd_binwidth: Optional[int] = 1) -> None:\n        \"\"\"Instantiate class for multiprimary light stimulation devices.\n\n        Parameters\n        ----------\n        resolutions : list of int\n            Resolution depth of primaries, i.e., the number of steps available\n            for specifying the intensity of each primary. This is a list of\n            integers to allow for systems where primaries may have different\n            resolution depths. The number of elements in the list must\n            equal the number of device primaries.\n        colors : list of str\n            List of valid color names for the primaries. Must be in\n            `matplotlib.colors.cnames <https://matplotlib.org/stable/gallery/color/named_colors.html>`_.\n        spds : pd.DataFrame\n            Spectral measurements to characterise the output of the device.\n            Column headers must be wavelengths and each row a spectrum.\n            Additional columns are needed to identify the primary/setting. For\n            example, 380, ..., 780, primary, setting.\n        spd_binwidth : int, optional\n            Binwidth of spectral measurements. The default is 1.\n\n        Returns\n        -------\n        None\n\n        \"\"\"\n        self.resolutions = resolutions\n        self.colors = colors\n        self.spds = spds\n        self.spd_binwidth = spd_binwidth\n\n        # create important data\n        self.nprimaries = len(self.resolutions)\n        self.wls = self.spds.columns\n        self.bounds = [(0., 1.,) for primary in self.resolutions]\n        \n        \n    # Starts properly here\n    def _get_gamut(self):\n        max_spds = self.spds.loc[(slice(None), self.resolutions), :]\n        XYZ = max_spds.apply(colorfunc.spd_to_XYZ, axis=1)\n        xy = (XYZ[['X', 'Y']].div(XYZ.sum(axis=1), axis=0)\n              .rename(columns={'X':'x','Y':'y'}))\n        xy = xy.append(xy.iloc[0], ignore_index=True)  # Join the dots\n        return xy\n\n    def _xy_in_gamut(self, xy_coord: Tuple[float]):\n        \"\"\"Return True if xy_coord is within the gamut of the device\"\"\"\n        poly_path = mplpath.Path(self._get_gamut().to_numpy())\n        return poly_path.contains_point(xy_coord)\n\n    def plot_gamut(self, \n                   ax: plt.Axes = None, \n                   show_1931_horseshoe: bool = True, \n                   show_CIE170_2_horseshoe: bool = True\n                   ) -> Union[plt.Figure, None]:\n        \"\"\"Plot the gamut of the stimulation device.\n        \n        Parameters\n        ----------\n        ax : plt.Axes, optional\n            Axes on which to plot. The default is None.\n        show_1931_horseshoe : bool, optional\n            Whether to show the CIE1931 chromaticity horseshoe. The default is \n            True.\n        show_CIE170_2_horseshoe : bool, optional\n            Whether to show the CIE170_2 chromaticity horseshoe. The default is \n            True.\n            \n        Returns\n        -------\n        fig : plt.Figure or None\n            The plot.\n\n        \"\"\"\n        gamut = self._get_gamut()\n        if ax is None:\n            fig, ax = plt.subplots(1, 1, figsize=(6, 6))\n        if show_1931_horseshoe:\n            plot_chromaticity_diagram_CIE1931(\n                axes=ax, title=False, standalone=False)\n        if show_CIE170_2_horseshoe:\n            cie170_2 = get_CIE170_2_chromaticity_coordinates(connect=True)\n            ax.plot(cie170_2['x'], cie170_2['y'],\n                    c='k', ls=':', label='CIE 170-2')\n        ax.plot(gamut['x'], gamut['y'], color='k',\n                lw=2, marker='x', markersize=8, label='Gamut')\n        ax.set(xlim=(-.15, .9),\n               ylim=(-.1, 1),\n               title='Stimulation Device gamut')\n        if ax is None:\n            return fig\n        else:\n            return None\n            \n    def plot_spds(self) -> plt.Figure:\n        \"\"\"Plot the spectral power distributions for the stimulation device.\n\n        Returns\n        -------\n        fig : plt.Figure\n            The plot.\n\n        \"\"\"\n        data = (self.spds.reset_index()\n                    .melt(id_vars=['Primary', 'Setting'],\n                          value_name='Flux',\n                          var_name='Wavelength (nm)'))\n\n        fig, ax = plt.subplots(figsize=(12, 4))\n\n        _ = sns.lineplot(\n            x='Wavelength (nm)', y='Flux', data=data, hue='Primary',\n            palette=self.colors, units='Setting', ax=ax, lw=.1, estimator=None\n        )\n        ax.set_title('Stimulation Device SPDs')\n        return fig\n\n    def calculate_aopic_irradiances(self) -> pd.DataFrame:\n        \"\"\"Calculate aopic irradiances from spds.\n\n        Using the CIE026 spectral sensetivities, calculate alphaopic\n        irradiances (S, M, L, R, I) for every spectrum in `self.spds`.\n\n        Returns\n        -------\n        pd.DataFrame\n            Alphaopic irradiances.\n\n        \"\"\"\n        sss = get_CIES026(binwidth=self.spd_binwidth, fillna=True)\n        return self.spds.dot(sss)\n\n    def calculate_lux(self):\n        \"\"\"Using the CIE1924 photopic luminosity function, calculate lux for\n        every spectrum in `self.spds`.\n\n        Returns\n        -------\n        pd.DataFrame\n            Lux values.\n\n        \"\"\"\n        vl = get_CIE_1924_photopic_vl(binwidth=self.spd_binwidth)\n        lux = self.spds.dot(vl.values) * 683  # lux conversion factor\n        lux.columns = ['lux']\n        return lux\n\n    def predict_primary_spd(\n            self,\n            primary: int,\n            setting: Union[int, float],\n            name: Union[int, str] = 0) -> np.ndarray:\n        \"\"\"Predict output for a single device primary at a given setting.\n        \n        This is the basis for all predictions.\n\n        Parameters\n        ----------\n        primary : int\n            Device primary.\n        setting : int or float\n            Device primary setting. Must be int (0-max resolution) or float\n            (0.-1.).\n        name : int or str, optional\n            A name for the spectrum. The default is 0.\n\n        Raises\n        ------\n        ValueError\n            If requested value of setting exceeds resolution.\n\n        Returns\n        -------\n        np.array\n            Predicted spd for primary / setting.\n\n        \"\"\"\n        if isinstance(setting, float):\n            setting *= self.resolutions[primary]\n        if setting > self.resolutions[primary]:\n            raise ValueError(f'Requested setting {int(setting)} exceeds '\n                             f'resolution of device primary {primary}')\n        f = interp1d(x=self.spds.loc[primary].index.values,\n                     y=self.spds.loc[primary],\n                     axis=0, fill_value='extrapolate')\n        return pd.Series(f(setting), name=name, index=self.wls)\n            \n    def predict_multiprimary_spd(\n            self,\n            settings: Union[List[int], List[float]],\n            name: Union[int, str] = 0,\n            nosum: Optional[bool] = False) -> pd.Series:\n        \"\"\"Predict spectral power distribution of device for given settings.\n\n        Predict the SPD output of the stimulation device for a given list of\n        primary settings. Assumes linear summation of primaries.\n\n        Parameters\n        ----------\n        settings : list of int or list of float\n            List of settings for the device primaries. Must be of length\n            `self.nprimaries` and consist entirely of float (0.-1.) or int\n            (0-max resolution).\n        name : int or str, optional\n            A name for the spectrum, e.g. 'Background'. The default is 0.\n        nosum : bool, optional\n            Whether t\n\n        Raises\n        ------\n        ValueError\n            If the number of elements in `settings` is greater than the number\n            of device primaries.\n\n            If the elements in `settings` are not exclusively int or float.\n\n        Returns\n        -------\n        pd.DataFrame if nosum else pd.Series\n            Predicted spectra or spectrum for given device settings.\n\n        \"\"\"\n        if len(settings) > self.nprimaries:\n            raise ValueError(\n                'Number of settings exceeds number of device primaries.'\n            )\n        if not (all(isinstance(s, int) for s in settings) or\n                all(isinstance(s, float) for s in settings)):\n            raise ValueError('Can not mix float and int in settings.')\n        if name is None:\n            name = 0\n        spd = []\n        for primary, setting in enumerate(settings):\n            spd.append(self.predict_primary_spd(primary, setting, primary))        \n        spd = pd.concat(spd, axis=1)\n        if nosum:\n            return spd\n        else:\n            spd = spd.sum(axis=1)\n            spd.name = name\n            return spd\n\n    def predict_multiprimary_aopic(\n            self,\n            settings: Union[List[int], List[float]],\n            name: Union[int, str] = 0) -> pd.Series:\n        \"\"\"Predict a-opic irradiances of device for given settings.\n\n        Parameters\n        ----------\n        settings : list of int or list of float\n            List of settings for the device primaries. Must be of length\n            `self.nprimaries` and consist entirely of float (0.-1.) or int\n            (0-max resolution).\n        name : int or str, optional\n            A name for the output, e.g. 'Background'. The default is 0.\n\n        Returns\n        -------\n        aopic : pd.DataFrame\n            Predicted a-opic irradiances for given device settings.\n\n        \"\"\"\n        spd = self.predict_multiprimary_spd(settings, name=name)\n        sss = get_CIES026(binwidth=self.spd_binwidth, fillna=True)\n        return spd.dot(sss)\n\n    def find_settings_xyY(\n            self, \n            xy: Union[List[float], Tuple[float]], \n            luminance: float,\n            tolerance: Optional[float] = 1e-6,\n            plot_solution: Optional[bool] = False,\n            verbose: Optional[bool] = True) -> OptimizeResult:\n        \"\"\"Find device settings for a spectrum with requested xyY values.\n\n        Parameters\n        ----------\n        xy : List[float]\n            Requested chromaticity coordinates (xy).\n        luminance : float\n            Requested luminance.\n        tolerance : float, optional\n            Acceptable precision for result.\n        plot_solution : bool, optional\n            Set to True to plot the solution. The default is False.\n        verbose : bool, optional\n            Set to True to print status messages. The default is False.\n\n        Returns\n        -------\n        result : OptimizeResult\n            The result of the optimisation procedure, with result.x as the\n            settings that will produce the spectrum.\n\n        \"\"\"\n        if len(xy) != 2:\n            raise ValueError('xy must be of length 2.')\n            \n        if not self._xy_in_gamut(xy):\n            print(\"WARNING: specified xy coordinates are outside of\")\n            print(\"the device's gamut. Searching for closest match.\")\n            print(\"This could take a while, and results may be useless.\\n\")\n\n        requested_xyY = colorfunc.xy_luminance_to_xyY(xy, luminance)\n        requested_LMS = colorfunc.xyY_to_LMS(requested_xyY)\n\n        # Objective function to find device settings for given xyY\n        def _xyY_objective_function(x0: List[float]):\n            aopic = self.predict_multiprimary_aopic(x0)\n            return sum(\n                pow(requested_LMS - aopic[['L', 'M', 'S']].to_numpy(), 2)\n            )\n \n        # Arguments for local solver\n        minimizer_kwargs = {\n            'method': 'SLSQP',\n            'bounds': self.bounds,\n            'options': {'maxiter': 500}\n        }\n        \n        # Callback for global search\n        def _callback(x, f, accepted):\n            if accepted and tolerance is not None:\n                if f < tolerance:\n                    return True\n                \n        # Random starting point\n        x0 = np.random.uniform(0, 1, self.nprimaries)\n\n        # Do global search\n        result = basinhopping(\n            func=_xyY_objective_function,\n            x0=x0,\n            niter=100,\n            T=1.0,\n            stepsize=0.5,\n            minimizer_kwargs=minimizer_kwargs,\n            take_step=None,\n            accept_test=None,\n            callback=_callback,\n            interval=50,\n            disp=True,\n            niter_success=None,\n            seed=None,\n        )\n        \n        # TODO: refactor this\n        solution_lms = self.predict_multiprimary_aopic(\n            result.x)[['L','M','S']].values\n        solution_xyY = colorfunc.LMS_to_xyY(solution_lms)\n        print(f'Requested LMS: {requested_LMS}')\n        print(f'Solution LMS: {solution_lms}')\n        \n        # Reacfactor!\n        if plot_solution is not None:\n            fig, axs = stim_plot()\n            # Plot the spectrum\n            self.predict_multiprimary_spd(\n                result.x, \n                name=f'solution_xyY:\\n{solution_xyY.round(3)}').plot(\n                    ax=axs[0],\n                    legend=True)\n            axs[1].scatter(\n                x=requested_xyY[0], \n                y=requested_xyY[1],\n                s=100, marker='o', \n                facecolors='none', \n                edgecolors='k', \n                label='Requested'\n                )\n            axs[1].scatter(\n                x=solution_xyY[0], \n                y=solution_xyY[1],\n                s=100, c='k',\n                marker='x', \n                label='Resolved'\n                )\n            self.plot_gamut(ax=axs[1], show_CIE170_2_horseshoe=False)\n            axs[1].legend()\n            device_ao = self.predict_multiprimary_aopic(\n                result.x, name='Background')\n            colors = [val[1] for val in self.aopic_colors.items()]\n            device_ao.plot(kind='bar', color=colors, ax=axs[2])\n            \n        return result     \n        \n    # TODO: decide whether to keep these\n    def fit_curves(self):\n        \"\"\"Fit curves to the unweighted irradiance of spectral measurements\n        and save the parameters.\n\n        Returns\n        -------\n        fig\n            Figure.\n\n        \"\"\"\n\n        # plot\n        ncols = 5\n        nrows = int(self.nprimaries / ncols)\n        fig, axs = plt.subplots(\n            nrows, ncols, figsize=(16, 6), sharex=True, sharey=True)\n        axs = [item for sublist in axs for item in sublist]\n\n        for primary in range(self.nprimaries):\n            xdata = (self.spds.loc[primary].index\n                     / self.resolutions[primary]).to_numpy()\n            ydata = self.irradiance.loc[primary].T.to_numpy()[0]\n            ydata = ydata / np.max(ydata)\n\n            # Curve fitting function\n            def func(x, a, b):\n                return beta.cdf(x, a, b)\n\n            axs[primary].scatter(\n                xdata, ydata, color=self.colors[primary], s=2)\n\n            # Fit\n            popt, pcov = curve_fit(beta.cdf, xdata, ydata, p0=[2.0, 1.0])\n            self.curveparams[primary] = popt\n            ypred = func(xdata, *popt)\n            axs[primary].plot(\n                xdata, ypred, color=self.colors[primary],\n                label='fit: a=%5.3f, b=%5.3f' % tuple(popt))\n            axs[primary].set_title('Primary {}'.format(primary))\n            axs[primary].legend()\n\n        for ax in axs:\n            ax.set_ylabel('Output fraction (irradiance)')\n            ax.set_xlabel('Input fraction')\n\n        plt.tight_layout()\n\n        return fig\n\n    def optimise(\n            self,\n            primary: int,\n            settings: Union[List[int], List[float]]\n            ) -> Union[List[int], List[float]]:\n        \"\"\"Optimise a stimulus profile by applying the curve parameters.\n\n        Parameters\n        ----------\n        primary : int\n            Primary being optimised.\n        settings : np.array\n            Array of intensity values to optimise for specified LED.\n\n        Returns\n        -------\n        np.array\n            Optimised intensity values.\n\n        \"\"\"\n        if not self.curveparams:\n            print('No parameters yet. Run .fit_curves(...) first...')\n        params = self.curveparams[primary]\n        settings = self.settings_to_weights(settings)\n        optisettings = beta.ppf(settings, params[0], params[1])\n        return self.weights_to_settings(optisettings)\n\n    def settings_to_weights(self, settings: List[int]) -> List[float]:\n        \"\"\"Convert a list of settings to a list of weights.\n\n        Parameters\n        ----------\n        settings : list of int\n            List of settings for device primaries, ranging from 0-max\n            resolution for respective primary.\n\n        Returns\n        -------\n        list\n            List of weights.\n\n        \"\"\"\n        return [float(s / r) for s, r in zip(settings, self.resolutions)]\n\n    def weights_to_settings(self, weights: List[float]) -> List[int]:\n        \"\"\"Convert a list of weights to a list of settings.\n\n        Parameters\n        ----------\n        weights : list of float\n            List of weights for device primaries, ranging from 0.-1.\n\n        Returns\n        -------\n        list\n            List of settings.\n\n        \"\"\"\n        return [int(w * r) for w, r in zip(weights, self.resolutions)]\n    \n    \n    def spd_to_settings(self, target_spd, tolerance=1e-6):\n        #breakpoint()\n        target_xyY = colorfunc.spd_to_xyY(target_spd)\n        \n        def _objective(x0):\n            xyY = colorfunc.spd_to_xyY(self.predict_multiprimary_spd(x0))\n            error = target_xyY - xyY\n            return sum(pow(error, 2))\n        \n        # Callback for global search\n        def _callback(x, f, accepted):\n            if accepted and tolerance is not None:\n                if f < tolerance:\n                    return True\n                \n        x0 = np.array([np.random.uniform(0, 1) for val in self.resolutions])\n        bounds = [(0., 1.,) for primary in self.resolutions]\n        \n        minimizer_kwargs = {\n            'method': 'SLSQP',\n            'bounds': bounds,\n            'options': {'maxiter': 500}\n        }\n                \n\n        # Do global search\n        res = basinhopping(\n            func=_objective,\n            x0=x0,\n            niter=100,\n            T=1.0,\n            stepsize=0.5,\n            minimizer_kwargs=minimizer_kwargs,\n            take_step=None,\n            accept_test=None,\n            callback=_callback,\n            interval=50,\n            disp=True,\n            niter_success=None,\n            seed=None,\n        )        \n        return res\n", "meta": {"hexsha": "2ffff7bdbe15713cc2207cd241e5d67c96a9fe41", "size": 19822, "ext": "py", "lang": "Python", "max_stars_repo_path": "pysilsub/devicen.py", "max_stars_repo_name": "PySilentSubstitution/silent-sub", "max_stars_repo_head_hexsha": "ca1ec4c9f6dcd444a87149bbe6dfe00140f4c375", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-20T11:20:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T11:20:25.000Z", "max_issues_repo_path": "pysilsub/devicen.py", "max_issues_repo_name": "PySilentSubstitution/pysilsub", "max_issues_repo_head_hexsha": "ca1ec4c9f6dcd444a87149bbe6dfe00140f4c375", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pysilsub/devicen.py", "max_forks_repo_name": "PySilentSubstitution/pysilsub", "max_forks_repo_head_hexsha": "ca1ec4c9f6dcd444a87149bbe6dfe00140f4c375", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2583892617, "max_line_length": 104, "alphanum_fraction": 0.5472202603, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.2538610069692489, "lm_q1q2_score": 0.15141111910057511}}
{"text": "import conf\nimport numpy\nimport random\nfrom Shake import *\ndef CALC(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON):\n    # IMPLICIT #real*8(A-H,O-Z)\n    # IMPLICIT #integer*8(I-N)\n    # SCR=\"\"\\\n    # SCR1=\"\"\n    global IFIRST,ESHK,ELECN,JVAC,R1\n    ESHK=0.0\n    JVAC=0.0\n    def get_globals():\n        NDVEC=conf.NDVEC\n        MSUM=conf.MSUM\n        MCOMP=conf.MCOMP\n        MRAYL=conf.MRAYL\n        MPAIR=conf.MPAIR\n        MPHOT=conf.MPHOT\n        MVAC=conf.MVAC\n        ELEV=conf.ELEV\n        NSDEG=conf.NSDEG\n        AA=conf.AA\n        BB=conf.BB\n        SCR=conf.SCR\n        SCR1=conf.SCR1\n        PRSH=conf.PRSH\n        ESH=conf.ESH\n        AUG=conf.AUG\n        RAD=conf.RAD\n        PRSHBT=conf.PRSHBT\n        IZ=conf.IZ\n        INIOCC=conf.INIOCC\n        ISHLMX=conf.ISHLMX\n        AMZ=conf.AMZ\n        NOCC=conf.NOCC\n        AUGR=conf.AUGR\n        RADR=conf.RADR\n        IONSUM=conf.IONSUM\n        IFLSUM=conf.IFLSUM\n        ESTORE=conf.ESTORE\n        EPHOTON=conf.EPHOTON\n        DRXE=conf.DRXE\n        DRYE=conf.DRYE\n        DRZE=conf.DRZE\n        DRX=conf.DRX\n        DRY=conf.DRY\n        DRZ=conf.DRZ\n        globals().update(locals())    \n    get_globals()\n    def update_globals():\n        conf.NDVEC=NDVEC\n        conf.MSUM=MSUM\n        conf.MCOMP=MCOMP\n        conf.MRAYL=MRAYL\n        conf.MPAIR=MPAIR\n        conf.MPHOT=MPHOT\n        conf.MVAC=MVAC\n        conf.ELEV=ELEV\n        conf.NSDEG=NSDEG\n        conf.AA=AA\n        conf.BB=BB\n        conf.SCR,SCR1=SCR,SCR1\n        conf.PRSH=PRSH\n        conf.ESH=ESH\n        conf.AUG=AUG\n        conf.RAD=RAD\n        conf.PRSHBT=PRSHBT\n        conf.IZ=IZ\n        conf.INIOCC=INIOCC\n        conf.ISHLMX=ISHLMX\n        conf.AMZ=AMZ\n        conf.NOCC=NOCC\n        conf.AUGR=AUGR\n        conf.RADR=RADR\n        conf.IONSUM=IONSUM\n        conf.IFLSUM=IFLSUM\n        conf.ESTORE=ESTORE\n        conf.EPHOTON=EPHOTON\n        conf.DRXE=DRXE\n        conf.DRYE=DRYE\n        conf.DRZE=DRZE\n        conf.DRX=DRX\n        conf.DRY=DRY\n        conf.DRZ=DRZ\n        globals().update(locals())\n    #DIMENSION \n    TEMP=[0 for x in range(17+1)]\n    TEMP1=[0 for x in range(289+1)]\n    #\n    # CALCULATE CASCADE IN GAS KGAS AND MOLECULAR COMPONENT LGAS\n    # WITH INTIAL ENERGY DEPOSIT ELECEN AND SHELL VACANCY CREATED AT ISHELL\n    #\n    # INITIAL PHOTON DIRECTION  DRX, DRY AND DRZ\n    DRXINIT=DRXE[int(NVAC)][1]\n    DRYINIT=DRYE[int(NVAC)][1]\n    DRZINIT=DRZE[int(NVAC)][1]\n    ISHELLST=ISHELL\n    def GOTO2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON):\n        global IFIRST,ESHK,ELECN,JVAC\n        if(ICON==2 and IONSUM[int(NVAC)] == 1):\n            return\n        # GO INTO SECOND BETA LOOP\n        print(\"calc 104 ICON,IONSUM[int(NVAC)],ISECOND= \",ICON,IONSUM[int(NVAC)],ISECOND)\n        if(ICON == 3 and IONSUM[int(NVAC)] == 1 and ISECOND == 1):\n            GOTO66(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n        print(\"calc 107 ICON,IFIRST,JVAC,ISECOND= \",ICON,IFIRST,JVAC,ISECOND)\n        if(ICON == 3 and IFIRST == 1 and JVAC == 0 and ISECOND == 2):\n            return 1\n        # C\n        update_globals()\n        UPDATE(KGAS,LGAS,ISHELL)\n        # C  CHOOSE FLUORESCENCE OR AUGER TRANSITION\n        TSUM=0.0\n        for I in range(1,17+1):\n            TSUM=TSUM+RADR[KGAS][LGAS][ISHELL][I]\n            for J in range(1,17+1):\n                TSUM=TSUM+AUGR[KGAS][LGAS][ISHELL][I][J]\n            # 10 CONTINUE\n        # C NO MORE TRANSITIONS POSSIBLE\n        if(TSUM == 0.0 and ICON == 3 and ISECOND == 1):\n            globals().update(locals())\n\n            GOTO66(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n        if(TSUM == 0.0):\n            return 1\n        # C NORMALISE TO 1.0\n        for I in range(1,17+1):\n            RADR[KGAS][LGAS][ISHELL][I]=RADR[KGAS][LGAS][ISHELL][I]/TSUM\n            for J in range(1,17+1):\n                AUGR[KGAS][LGAS][ISHELL][I][J]=AUGR[KGAS][LGAS][ISHELL][I][J]/TSUM\n        # 11 CONTINUE\n        # C CREATE CUMULATIVE SUM ARRAY\n        TEMP[1]=RADR[KGAS][LGAS][ISHELL][1]\n        for I in range(2,17+1):\n            TEMP[I]=RADR[KGAS][LGAS][ISHELL][I]+TEMP[I-1]\n        # 12 CONTINUE\n        TEMP1[1]=AUGR[KGAS][LGAS][ISHELL][1][1]\n        for I in range(2,17+1):\n            TEMP1[I]=AUGR[KGAS][LGAS][ISHELL][I][1]+TEMP1[I-1]\n        # 13 CONTINUE\n        for J in range(1,16+1):\n            for I in range(1,17+1):\n                TEMP1[I+(J*17)]=AUGR[KGAS][LGAS][ISHELL][I][(J+1)]+TEMP1[I+(J*17)-1]\n        # 14 CONTINUE\n        # C FIND FLUORESCENCE OR AUGER TRANSITION\n        # 15 \n        R1=random.uniform(0.0,1.0)\n        for I in range(1,17+1):\n            if(R1 < TEMP[I]):\n                # C STORE PHOTON ENERGY AND ANGLE THEN UPDATE NOCC\n                IFLSUM[int(NVAC)]=IFLSUM[int(NVAC)]+1\n                EPHOTON[int(NVAC)][IFLSUM[int(NVAC)]]=ELEV[ISHELL][IZ[KGAS][LGAS]]-ELEV[I][IZ[KGAS][LGAS]]\n                if(ICON == 2):\n                    EPHOTON[int(NVAC)][IFLSUM[int(NVAC)]]=ELEV[ISHELL][IZ[KGAS][LGAS]+1]-ELEV[I][IZ[KGAS][LGAS]+1]\n                if(ICON == 3):\n                    EPHOTON[int(NVAC)][IFLSUM[int(NVAC)]]=ELEV[ISHELL][IZ[KGAS][LGAS]+2]-ELEV[I][IZ[KGAS][LGAS]+2]\n                if(EPHOTON[int(NVAC)][IFLSUM[int(NVAC)]] < 0.0):\n                    # WRITE(6,545) \n                    # 545  \n                    print(' PHOTON ENERGY=%.3f NVAC=%d IFLSUM=%d IN CALC'%(EPHOTON[int(NVAC)][IFLSUM[int(NVAC)]],IFLSUM[int(NVAC)],NVAC))\n                ELEFT=ELEFT-DABS(EPHOTON[int(NVAC)][IFLSUM[int(NVAC)]])\n                if(ELEFT < 0.0):\n                    GOTO100()\n                # C RANDOM EMISSION DIRECTION\n                R3=random.uniform(0.0,1.0)\n                THET=numpy.arccos(1.0-2.0*R3)\n                R3=random.uniform(0.0,1.0)\n                PHI=TWOPI*R3\n                # C CALC DIRECTION COSINES OF FLUORESCENCE\n                DRX[int(NVAC)][IFLSUM[int(NVAC)]]=numpy.sin(THET)*numpy.cos(PHI)\n                DRY[int(NVAC)][IFLSUM[int(NVAC)]]=numpy.sin(THET)*numpy.sin(PHI)\n                DRZ[int(NVAC)][IFLSUM[int(NVAC)]]=numpy.cos(THET)\n                # C   \n                NOCC[KGAS][LGAS][ISHELL]=NOCC[KGAS][LGAS][ISHELL]+1\n                NOCC[KGAS][LGAS][I]=NOCC[KGAS][LGAS][I]-1\n                # C FIND LOWEST VACANCY\n                update_globals()\n                VACANCY(KGAS,LGAS,ISHELL,ILAST)\n                if(ILAST == 1):\n                    # C NO MORE TRANSITIONS POSSIBLE\n                    # C  SECOND ELECTRON IN DOUBLE BETA DECAY\n                    if(ICON == 3 and ISECOND == 1):\n                        globals().update(locals())\n                        GOTO66(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                    return    \n                # ENDif\n                globals().update(locals())\n                GOTO2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n            # ENDif \n        # 16 CONTINUE\n        globals().update(locals())\n        return 1\n    def GOTO4(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON):\n        global IFIRST,ESHK,ELECN,JVAC\n        globals().update(locals())\n        # CHECK FOR ELECTRON SHAKEOFF\n        IFIRST=IFIRST+1\n        if(IFIRST > 1):\n            ELECN=ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]\n        globals().update(locals())    \n        ISHELL,ELECN,KGAS,LGAS,ESHK,ICON,IFIRST,JVAC=SHAKE(ISHELL,ELECN,KGAS,LGAS,ESHK,ICON,IFIRST,JVAC)\n        globals().update(locals())    \n        #  CALCULATE ENERGY OF ELECTRON\n        print(\"calc 203 JVAC=\",JVAC)\n        if(JVAC == 0):\n            pass\n        else:    \n            if(IFIRST == 1):\n                # INITIAL ELECTRON + SHAKEOFF\n                if(ICON == 1):\n                    ELECN=ELECN-ESHK-ELEV[JVAC][IZ[int(KGAS)][int(LGAS)]]\n                if(ICON == 2):\n                    ELECN=ELECN-ESHK-ELEV[JVAC,(IZ[KGAS][int(LGAS)]+1)]\n                if(ICON == 2 or ICON == 3):\n                    ISHELL=JVAC\n                if(ICON == 3):\n                    ELECN=ELECN-ESHK-ELEV[JVAC][(IZ[int(KGAS)][int(LGAS)]+2)]\n                # PRIMARY ELECTRON\n                ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ELECN\n            # endif\n            if(ICON == 1 and IFIRST != 1):\n                ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]-ESHK-ELEV[JVAC][IZ[int(KGAS)][int(LGAS)]]\n            # endif\n            IONSUM[int(NVAC)]=IONSUM[int(NVAC)]+1\n            # MAXIMUM ION CHARGE STATE =28\n            if(IONSUM[int(NVAC)]> 28):\n                #WRITE(6,99) IONSUM[int(NVAC)] \n                #99  \n                print(' WARNING ION CHARGE LIMITED TO 28+ IN THIS VERSION') \n                sys.exit()\n            # endif\n            # SHAKE ELECTRON\n            ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ESHK\n            if(ICON == 1):\n                ELEFT=ELEFT-ESHK-ELEV[JVAC][IZ[int(KGAS)][int(LGAS)]]\n            if(ICON == 2):\n                ELEFT=ELEFT-ESHK-ELEV[JVAC,(IZ[KGAS,LGAS]+1)]\n            if(ICON == 3):\n                ELEFT=ELEFT-ESHK-ELEV[JVAC][(IZ[int(KGAS)][int(LGAS)]+2)]\n            if(ELEFT < 0.0):\n                globals().update(locals())    \n                complete=GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                return complete\n            # RANDOM EMISSION DIRECTION\n            R3=random.uniform(0.0,1.0)\n            THET=numpy.arccos(1.0-2.0*R3)\n            R3=random.uniform(0.0,1.0)\n            PHI=TWOPI*R3\n            DRXE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.cos(PHI)\n            DRYE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.sin(PHI)\n            DRZE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.cos(THET)\n            # RETURN IF NO SHAKE OFF WITH BETA DECAY\n        \n        complete=GOTO2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)    \n        if(complete):\n            return 1\n        counter116=1\n        while(counter116):\n            counter116=0\n            R2=R1-TEMP[17]\n            for J in range(1,17+1):\n                if(counter116):\n                    break\n                for I in range(1,17+1):\n                    if(R2 < TEMP1[I+((J-1)*17)]):\n                        # AUGER OR COSTER KRONIG  \n                        # STORE EJECTED ELECTRON AND UPDATE NOCC\n                        ETEMP=ELEV[ISHELL][IZ[int(KGAS)][int(LGAS)]]-(ELEV[I][IZ[int(KGAS)][int(LGAS)]]+ELEV[I][IZ[int(KGAS)][int(LGAS)]+1])*0.5-(ELEV[J][IZ[int(KGAS)][int(LGAS)]]+ELEV[J][IZ[int(KGAS)][int(LGAS)]+1])*0.5\n                        if(ICON == 2):\n                            ETEMP=ELEV[ISHELL][IZ[int(KGAS)][int(LGAS)]+1]-(ELEV[I][IZ[int(KGAS)][int(LGAS)]+1]+ELEV[I][IZ[int(KGAS)][int(LGAS)]+2])*0.5-(ELEV[J][IZ[int(KGAS)][int(LGAS)]+1]+ELEV[J][IZ[int(KGAS)][int(LGAS)]+2])*0.5\n                        if(ICON == 3):\n                            ETEMP=ELEV[ISHELL][IZ[int(KGAS)][int(LGAS)]+2]-(ELEV[I][IZ[int(KGAS)][int(LGAS)]+2]+ELEV[I][IZ[int(KGAS)][int(LGAS)]+3])*0.5-(ELEV[J][IZ[int(KGAS)][int(LGAS)]+2]+ELEV[J][IZ[int(KGAS)][int(LGAS)]+3])*0.5\n                        if(ETEMP < 0.0):\n                            # DO NOT ALLOW NEGATIVE ENERGY TRANSITIONS\n                            counter117=1\n                            while(counter117):\n                                counter117=0\n                                R1=random.uniform(0.0,1.0)\n                                if(R1 < TEMP[17]):\n                                    counter117=1\n                            counter116=1\n                            break\n                        # endif\n                        IONSUM[int(NVAC)]=IONSUM[int(NVAC)]+1\n                        if(IONSUM[int(NVAC)]> 28): \n                            print(' IONSUM LIMITED TO 28 IN THIS VERSION IONSUM=',IONSUM[int(NVAC)],' IN CALC')\n                            sys.exit()\n                        # endif\n                        ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ETEMP\n                        ELEFT=ELEFT-ETEMP\n                        if(ELEFT < 0.0):\n                            GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                        # RANDOM EMISSION DIRECTION\n                        R3=random.uniform(0.0,1.0)\n                        THET=numpy.arccos(1.0-2.0*R3)\n                        R3=random.uniform(0.0,1.0)\n                        PHI=TWOPI*R3\n                        DRXE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.cos(PHI)\n                        DRYE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.sin(PHI)\n                        DRZE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.cos(THET)\n                        NOCC[int(KGAS)][int(LGAS)][ISHELL]=NOCC[int(KGAS)][int(LGAS)][ISHELL]+1\n                        NOCC[int(KGAS)][int(LGAS)][I]=NOCC[int(KGAS)][int(LGAS)][I]-1\n                        NOCC[int(KGAS)][int(LGAS)][J]=NOCC[int(KGAS)][int(LGAS)][J]-1\n                        # FIND LOWEST VACANCY\n                        VACANCY(KGAS,LGAS,ISHELL,ILAST)\n                        if(ILAST == 1):\n                            # NO MORE TRANSITIONS POSSIBLE\n                            #  SECOND ELECTRON IN DOUBLE BETA DECAY\n                            if(ICON == 3 and ISECOND == 1):\n                                GOTO66(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                            update_globals()\n                            return\n                        # endif\n                        GOTO4(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON) \n                    # endif\n\n        globals().update(locals())\n    def GOTO66(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON):\n        global IFIRST,ESHK,ELECN,JVAC\n        IONSUM[int(NVAC)]=IONSUM[int(NVAC)]+1\n        ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ESECOND\n        DRXE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THESEC)*numpy.cos(PHISEC)\n        DRYE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THESEC)*numpy.sin(PHISEC)\n        DRZE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.cos(THESEC)\n        ELECN=ESECOND\n        ISECOND=2\n        ISHELL=0\n        IFIRST=0\n        # LOOP AROUND CASCADE\n        globals().update(locals())\n        \n        GOTO4(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n        return 1\n    def GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON):\n        print(\"calcn ISHELL=\", ISHELL)\n        global IFIRST,ESHK,ELECN,JVAC\n        complete=0\n        ELEFT=ELECEN\n        ISHELL=ISHELLST\n        API=numpy.arccos(-1.00)\n        TWOPI=2.00*API\n        ISECOND=1\n        IFIRST=0\n        # SET STARTING ARRAY NOCC EQUAL TO INIOCC\n        for I in range(1,17+1):\n            NOCC[int(KGAS)][int(LGAS)][I]=INIOCC[int(KGAS)][int(LGAS)][I]\n        # PHOTONS\n        print(\"344 calc ICON=\",ICON)\n        if(ICON == 1):\n            IONSUM[int(NVAC)]=1\n            IFLSUM[int(NVAC)]=0\n            # STORE INITIAL PHOTOELECTRON ENERGY AND ANGLE\n            ESTORE[int(NVAC)][1]=ELECEN-ELEV[ISHELL][IZ[int(KGAS)][int(LGAS)]]\n            ELECN=ESTORE[int(NVAC)][1]\n            ELEFT=ELEFT-ESTORE[int(NVAC)][1]\n            NOCC[int(KGAS)][int(LGAS)][ISHELL]=NOCC[int(KGAS)][int(LGAS)][ISHELL]-1  \n            #    ENTRY FOR COMPTON ELECTRON.....\n            if(NVAC <= MCOMP[IPN]):\n                #    IF COMPTON EVENT ELECTRON ANGLE FROM COMPTON (ALREADY STORED)\n                globals().update(locals())    \n                complete=GOTO4(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                return complete\n            # endif\n            # USE PHOTOELCTRON ANGULAR DISTRIBUTION\n            APE=AA[ISHELL]\n            BPE=BB[ISHELL]\n            ANGGEN(APE,BPE,THET)\n            if(THET < 0.0):\n                THET=THET+API\n            R3=random.uniform(0.0,1.0)\n            PHI=TWOPI*R3\n            # INITIAL PHOTON DIRECTION  DRXINIT, DRYINIT AND DRZINIT\n            DRCOS(DRXINIT,DRYINIT,DRZINIT,THET,PHI,DRXX,DRYY,DRZZ)\n            DRXE[int(NVAC)][1]=DRXX\n            DRYE[int(NVAC)][1]=DRYY\n            DRZE[int(NVAC)][1]=DRZZ\n            globals().update(locals())    \n            complete=GOTO4(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n            return complete\n        # endif\n        if(ICON == 2):\n            # BETA DECAY\n            IONSUM[int(NVAC)]=1\n            IFLSUM[int(NVAC)]=0\n            ISHELL=0\n            ELECN=ELECEN\n            ESTORE[int(NVAC)][1]=ELECN\n            if(NDVEC == 2):\n                # RANDOM EMISSION DIRECTION\n                R3=random.uniform(0.0,1.0)\n                THET=numpy.arccos(1.0-2.0*R3)\n            elif(NDVEC == 0):\n                # RANDOM EMISSION IN THE X-Y PLANE\n                THET=API/2.0\n            elif(NDVEC == 1):\n                # EMISSION ALONG Z AXIS\n                THET=0.00\n            elif(NDVEC == -1):\n                # EMISSION ALONG -Z AXIS\n                THET=numpy.arccos(-1.00)\n            else:\n                print(' ERROR NDVEC NOT CORRECT SUBROUTINE STOPPED:')\n                sys.exit()\n            # endif\n            R3=random.uniform(0.0,1.0)\n            PHI=TWOPI*R3\n            DRXE[int(NVAC)][1]=numpy.sin(THET)*numpy.cos(PHI)\n            DRYE[int(NVAC)][1]=numpy.sin(THET)*numpy.sin(PHI)\n            DRZE[int(NVAC)][1]=numpy.cos(THET)\n        # endif\n        # DOUBLE BETA DECAY\n        if(ICON == 3):\n            IONSUM[int(NVAC)]=1\n            IFLSUM[int(NVAC)]=0\n            ISHELL=0\n            ELECN=ELECEN\n            ESTORE[int(NVAC)][1]=ELECN\n            ESECOND=ELECN\n            if(NDVEC == 2):\n                # RANDOM EMISSION DIRECTION\n                R3=random.uniform(0.0,1.0)\n                THET=numpy.arccos(1.0-2.0*R3)\n            elif(NDVEC == 0):\n                # RANDOM EMISSION IN THE X-Y PLANE\n                THET=API/2.0\n            elif(NDVEC == 1):\n                # EMISSION ALONG Z AXIS\n                THET=0.00\n            elif(NDVEC == -1):\n                # EMISSION ALONG -Z AXIS\n                THET=numpy.arccos(-1.00)\n            else:\n                print(' ERROR NDVEC NOT CORRECT SUBROUTINE STOPPED:')\n                sys.exit()\n            # endif\n            R3=random.uniform(0.0,1.0)\n            PHI=TWOPI*R3\n            DRXE[int(NVAC)][1]=numpy.sin(THET)*numpy.cos(PHI)\n            DRYE[int(NVAC)][1]=numpy.sin(THET)*numpy.sin(PHI)\n            DRZE[int(NVAC)][1]=numpy.cos(THET)\n        # endif\n        #\n        THESEC=API-THET\n        if(PHI < API):\n            PHISEC=API+PHI\n        else:\n            PHISEC=PHI-API\n        # endif\n        globals().update(locals())\n        print(\"calc IFIRST=\",IFIRST)\n        complete=GOTO4(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n        print(\"got this \",complete)\n        return complete\n        globals().update(locals())\n\n        GOTO66(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n    globals().update(locals())    \n    complete=GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n    if(complete):\n        return\n    print(' ERROR IN CASCADE 0') \n    sys.exit() \n    # end\ndef CALC1(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,L1):\n    # IMPLICIT #real*8(A-H,O-Z)\n    # IMPLICIT #integer*8(I-N)\n    # SCR=\"\"\n    #    SCR1=\"\"\n    #COMMON/GENCAS/\n    global ELEV#[17,79]\n    global NSDEG#(17)\n    global AA#[17]\n    global BB#[17]\n    global SCR,SCR1\n    #COMMON/MIXC/\n    global PRSH#(6,3,17,17)\n    global ESH#(6,3,17)\n    global AUG#(6,3,17,17,17)\n    global RAD#[6,3,17,17]\n    global PRSHBT#(6,3,17)\n    global IZ#[6,3]\n    global INIOCC#(6,3,17)\n    global ISHLMX#(6,3)\n    global AMZ#[6,3]\n    #COMMON/UPD/\n    global NOCC#(6,3,17)\n    global AUGR#(6,3,17,17,17)\n    global RADR#(6,3,17,17)\n    #COMMON/CALCAS/\n    global IONSUM0#(10)\n    global IFLSUM0#(10)\n    global ESTORE0#(10,28)\n    global EPHOTON0#(10,28)\n    global DRXE0#(10,28)\n    global DRYE0#(10,28)\n    global DRZE0#(10,28)\n    global DRX0#(10,28)\n    global DRY0#(10,28)\n    global DRZ0#(10,28)\n    #COMMON/CALCAS1/\n    global IONSUM#(10)\n    global IFLSUM#(10)\n    global ESTORE#(10,28)\n    global EPHOTON#(10,28)\n    global DRXE#(10,28)\n    global DRYE#(10,28)\n    global DRZE#(10,28)\n    global DRX#(10,28)\n    global DRY#(10,28)\n    global DRZ#[10,28]    \n    #DIMENSION \n    TEMP=[0 for x in range(17)]\n    TEMP1=[0 for x in range(289)]\n    #\n    # CALCULATE CASCADE IN GAS KGAS AND MOLECULAR COMPONENT LGAS \n    # WITH INTIAL ENERGY DEPOSIT ELECEN AND SHELL VACANCY CREATED AT ISHELL\n    #\n    ISTART=IONSUM[int(NVAC)]\n    ISTARTF=IFLSUM[int(NVAC)]\n    API=numpy.arccos(-1.00)\n    TWOPI=2.00*API\n    def GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON):\n        ELEFT=ELECEN\n        INIT=1\n        # SET STARTING ARRAY NOCC EQUAL TO INIOCC\n        for I in range(1,17+1):\n            NOCC[int(KGAS)][int(LGAS)][I]=INIOCC[int(KGAS)][int(LGAS)][I]\n        IONSUM[int(NVAC)]=ISTART+1\n        IFLSUM[int(NVAC)]=ISTARTF\n        # STORE PHOTOELECTRON ENERGY AND ANGLE\n        ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ELECEN-ELEV[ISHELL][IZ[int(KGAS)][int(LGAS)]]\n        ELECN=ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]\n        ELEFT=ELEFT-ELECN\n        NOCC[int(KGAS)][int(LGAS)][ISHELL]=NOCC[int(KGAS)][int(LGAS)][ISHELL]-1  \n        # USE PHOTELECTRON ANGULAR DISTRIBUTION\n        APE=AA[ISHELL]\n        BPE=BB[ISHELL]\n        ANGGEN(APE,BPE,THET)\n        if(THET < 0.0):\n            THET=THET+API\n        R3=random.uniform(0.0,1.0)\n        PHI=TWOPI*R3\n        DRCOS(DRX0[int(NVAC)][L1],DRY0[int(NVAC)][L1],DRZ0[int(NVAC)][L1],THET,PHI,DRXX,DRYY,DRZZ)\n        DRXE[int(NVAC)][int(IONSUM[int(NVAC)])]=DRXX\n        DRYE[int(NVAC)][int(IONSUM[int(NVAC)])]=DRYY\n        DRZE[int(NVAC)][int(IONSUM[int(NVAC)])]=DRZZ\n        # LOOP AROUND CASCADE\n        def GOTO4(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON):\n            # CHECK FOR ELECTRON SHAKEOFF\n            IDUM=1\n            if(INIT > 1):\n                ELECN=ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]\n            INSUM=IONSUM[int(NVAC)]\n            globals().update(locals())\n            SHAKE(ISHELL,ELECN,KGAS,LGAS,ESHK,IDUM,INSUM,JVAC)\n            #  CALCULATE ENERGY OF ELECTRON\n            if(JVAC == 0):\n                pass\n            else:\n                #  ELECTRON + SHAKEOFF\n                ELECN=ELECN-ESHK-ELEV[JVAC][IZ[int(KGAS)][int(LGAS)]]\n                ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ELECN\n                IONSUM[int(NVAC)]=IONSUM[int(NVAC)]+1\n                # MAXIMUM ION CHARGE STATE =28\n                if(IONSUM[int(NVAC)]> 28) : \n                    print(' 1ST GEN LIMITED TO 28 IN THIS VERSION IONSUM=',IONSUM[int(NVAC)])  \n                    sys.exit()        \n                # endif \n                ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ESHK \n                ELEFT=ELEFT-ESHK-ELEV[JVAC][IZ[KGAS,LGAS]]\n                if(ELEFT < 0.0):\n                    globals().update(locals())\n                    complete=GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                    return 1\n                # RANDOM EMISSION DIRECTION \n                R3=random.uniform(0.0,1.0)\n                THET=numpy.arccos(1.0-2.0*R3)\n                R4=random.uniform(0.0,1.0)\n                PHI=TWOPI*R4\n                DRXE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.cos(PHI)\n                DRYE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.sin(PHI)\n                DRZE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.cos(THET)\n            def GOTO2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON):\n                UPDATE(KGAS,LGAS,ISHELL)\n                INIT=2\n                # CHOOSE FLUORESCENCE OR AUGER TRANSITION\n                TSUM=0.0\n                for I in range(1,17+1):\n                    TSUM=TSUM+RADR[int(KGAS)][int(LGAS)][ISHELL][I]\n                    for J in range(1,17+1):\n                        TSUM=TSUM+AUGR[int(KGAS)][int(LGAS)][ISHELL][I][J]\n                # NO MORE TRANSITIONS POSSIBLE\n                if(TSUM == 0.0):\n                    return  \n                # NORMALISE TO 1.0\n                for I in range(1,17+1):\n                    RADR[int(KGAS)][int(LGAS)][ISHELL][I]=RADR[int(KGAS)][int(LGAS)][ISHELL][I]/TSUM\n                    for J in range(1,17+1):\n                        AUGR[int(KGAS)][int(LGAS)][ISHELL][I][J]=AUGR[int(KGAS)][int(LGAS)][ISHELL][I][J]/TSUM\n                # CREATE CUMULATIVE SUM ARRAY\n                TEMP[1]=RADR[int(KGAS)][int(LGAS)][ISHELL][1]\n                for I in range(2,17+1):\n                    TEMP[I]=RADR[int(KGAS)][int(LGAS)][ISHELL][I]+TEMP[I-1]\n                TEMP1[1]=AUGR[int(KGAS)][int(LGAS)][ISHELL][1][1]\n                for I in range(2,17+1):\n                    TEMP1[I]=AUGR[int(KGAS)][int(LGAS)][ISHELL][I][1]+TEMP1[I-1]\n                for J in range(1,16+1):\n                    for I in range(1,17+1):\n                        TEMP1[I+(J*17)]=AUGR[int(KGAS)][int(LGAS)][ISHELL][I][J+1]+TEMP1[I+(J*17)-1]\n                # FIND FLUORESCENCE OR AUGER TRANSITION\n                R1=random.uniform(0.0,1.0)\n                for I in range(1,17+1):\n                    if(R1 < TEMP[I]) :\n                        # STORE PHOTON ENERGY AND ANGLE : UPDATE NOCC\n                        IFLSUM[int(NVAC)]=IFLSUM[int(NVAC)]+1\n                        EPHOTON[int(NVAC)][IFLSUM[int(NVAC)]]=ELEV[ISHELL][IZ[int(KGAS)][int(LGAS)]]-ELEV[I][IZ[int(KGAS)][int(LGAS)]]\n                        ELEFT=ELEFT-EPHOTON[int(NVAC)][IFLSUM[int(NVAC)]]\n                        if(ELEFT < 0.0):\n                            globals().update(locals())\n                            complete=GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                            return complete\n                        # RANDOM EMISSION DIRECTION\n                        R3=random.uniform(0.0,1.0)\n                        THET=numpy.arccos(1.0-2.0*R3)\n                        R4=random.uniform(0.0,1.0)       \n                        PHI=TWOPI*R4\n                        DRX[int(NVAC)][IFLSUM[int(NVAC)]]=numpy.sin(THET)*numpy.cos(PHI)\n                        DRY[int(NVAC)][IFLSUM[int(NVAC)]]=numpy.sin(THET)*numpy.sin(PHI)\n                        DRZ[int(NVAC)][IFLSUM[int(NVAC)]]=numpy.cos(THET)\n                        NOCC[int(KGAS)][int(LGAS)][ISHELL]=NOCC[int(KGAS)][int(LGAS)][ISHELL]+1\n                        NOCC[int(KGAS)][int(LGAS)][I]=NOCC[int(KGAS)][int(LGAS)][I]-1\n                        # FIND LOWEST VACANCY\n                        globals().update(locals())\n                        VACANCY(KGAS,LGAS,ISHELL,ILAST)\n                        if(ILAST == 1):\n                            # NO MORE TRANSITIONS POSSIBLE\n                            return    \n                        # endif\n                        globals().update(locals())\n                        GOTO2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                globals().update(locals())\n                return 1\n                    # endif\n            GOTO2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON) \n            counter116=1\n            while(counter116):\n                counter116=0\n                R2=R1-TEMP[17]\n                for J in range(1,17+1):\n                    if(counter116):\n                        break\n                    for I in range(1,17+1):\n                        if(R2 < TEMP1[I+((J-1)*17)]) :\n                            # AUGER OR COSTER KRONIG  \n                            # STORE EJECTED ELECTRON AND UPDATE NOCC\n                            ETEMP=ELEV[ISHELL][IZ[int(KGAS)][int(LGAS)]]-(ELEV[I][IZ[int(KGAS)][int(LGAS)]]+ELEV[I][IZ[int(KGAS)][int(LGAS)]+1])*0.5-(ELEV[J][IZ[int(KGAS)][int(LGAS)]]+ELEV[J][IZ[int(KGAS)][int(LGAS)]+1])*0.5\n                            if(ETEMP < 0.0):\n                                # DO NOT ALLOW NEGATIVE ENERGY TRANSITIONS\n                                counter117=1\n                                while(counter117):\n                                    counter117=0\n                                    R1=random.uniform(0.0,1.0)\n                                    if(R1 < TEMP[17]):\n                                        counter117=1\n                                counter116=1\n                                break\n                            # endif\n                            IONSUM[int(NVAC)]=IONSUM[int(NVAC)]+1\n                            if(IONSUM[int(NVAC)]> 28) :\n                                print(' 2ND GEN IONS LIMITED TO 28 IN THIS VERSION IONSUM=',IONSUM[int(NVAC)]) #34602\n                                sys.exit()\n                            # endif\n                            ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ETEMP\n                            ELEFT=ELEFT-ETEMP\n                            if(ELEFT < 0.0):\n                                globals().update(locals())\n                                complete=GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                                return complete\n                            # RANDOM EMISSION DIRECTION\n                            R3=random.uniform(0.0,1.0)\n                            THET=numpy.arccos(1.0-2.0*R3)\n                            R4=random.uniform(0.0,1.0)\n                            PHI=TWOPI*R4\n                            DRXE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.cos(PHI)\n                            DRYE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.sin(PHI)\n                            DRZE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.cos(THET)\n                            NOCC[int(KGAS)][int(LGAS)][ISHELL]=NOCC[int(KGAS)][int(LGAS)][ISHELL]+1\n                            NOCC[int(KGAS)][int(LGAS)][I]=NOCC[int(KGAS)][int(LGAS)][I]-1\n                            NOCC[int(KGAS)][int(LGAS)][J]=NOCC[int(KGAS)][int(LGAS)][J]-1\n                            # FIND LOWEST VACANCY\n                            globals().update(locals())\n                            VACANCY(KGAS,LGAS,ISHELL,ILAST)\n                            if(ILAST == 1):\n                                # NO MORE TRANSITIONS POSSIBLE\n                                return\n                            # endif\n                            globals().update(locals())\n                            GOTO4(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)    \n                    # endif\n        globals().update(locals())\n        GOTO4(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n    globals().update(locals())\n    GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)            \n    print(' ERROR IN CASCADE 1') \n    sys.exit() \n    # end\n\ndef CALC2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,L1):\n    # IMPLICIT #real*8(A-H,O-Z)\n    # IMPLICIT #integer*8(I-N)\n\n    # SCR=\"\"\n    # SCR1=\"\"\n    #COMMON/GENCAS/\n    global ELEV#[17,79]\n    global NSDEG#(17)\n    global AA#[17]\n    global BB#[17]\n    global SCR,SCR1\n    #COMMON/MIXC/\n    global PRSH#(6,3,17,17)\n    global ESH#(6,3,17)\n    global AUG#(6,3,17,17,17)\n    global RAD#[6,3,17,17]\n    global PRSHBT#(6,3,17)\n    global IZ#[6,3]\n    global INIOCC#(6,3,17)\n    global ISHLMX#(6,3)\n    global AMZ#[6,3]\n    #COMMON/UPD/\n    global NOCC#(6,3,17)\n    global AUGR#(6,3,17,17,17)\n    global RADR#(6,3,17,17)\n    #COMMON/CALCAS/\n    global IONSUM0#(10)\n    global IFLSUM0#(10)\n    global ESTORE0#(10,28)\n    global EPHOTON0#(10,28)\n    global DRXE0#(10,28)\n    global DRYE0#(10,28)\n    global DRZE0#(10,28)\n    global DRX0#(10,28)\n    global DRY0#(10,28)\n    global DRZ0#(10,28)\n    #COMMON/CALCAS1/\n    global IONSUM#(10)\n    global IFLSUM#(10)\n    global ESTORE#(10,28)\n    global EPHOTON#(10,28)\n    global DRXE#(10,28)\n    global DRYE#(10,28)\n    global DRZE#(10,28)\n    global DRX#(10,28)\n    global DRY#(10,28)\n    global DRZ#[10,28] \n    #DIMENSION \n    TEMP=[0 for x in range(17)]\n    TEMP1=[0 for x in range(289)]\n    #\n    # CALCULATE CASCADE IN GAS KGAS AND MOLECULAR COMPONENT LGAS\n    # WITH INTIAL ENERGY DEPOSIT ELECEN AND SHELL VACANCY CREATED AT ISHELL\n    #\n    ISTART=IONSUM[int(NVAC)]\n    ISTARTF=IFLSUM[int(NVAC)]\n    API=numpy.arccos(-1.00)\n    TWOPI=2.00*API\n    def GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON):\n        ELEFT=ELECEN\n        INIT=1\n        # SET STARTING ARRAY NOCC EQUAL TO INIOCC\n        for I in range(1,17+1):\n            NOCC[int(KGAS)][int(LGAS)][I]=INIOCC[int(KGAS)][int(LGAS)][I]\n        IONSUM[int(NVAC)]=ISTART+1\n        IFLSUM[int(NVAC)]=ISTARTF\n        # STORE INITIAL PHOTELECTRON AND ANGLE\n        ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ELECEN-ELEV[ISHELL][IZ[int(KGAS)][int(LGAS)]]\n        ELECN=ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]\n        ELEFT=ELEFT-ELECN\n        NOCC[int(KGAS)][int(LGAS)][ISHELL]=NOCC[int(KGAS)][int(LGAS)][ISHELL]-1  \n        # USE PHOTOELECTRON ANGULAR DISTRIBUTION\n        APE=AA[ISHELL]\n        BPE=BB[ISHELL]\n        ANGGEN(APE,BPE,THET)\n        if(THET < 0.0):\n            THET=THET+API\n        R3=random.uniform(0.0,1.0)\n        PHI=TWOPI*R3\n        DRCOS(DRX0[int(NVAC)][L1],DRY0[int(NVAC)][L1],DRZ0[int(NVAC)][L1],THET,PHI,DRXX,DRYY,DRZZ)\n        DRXE[int(NVAC)][int(IONSUM[int(NVAC)])]=DRXX\n        DRYE[int(NVAC)][int(IONSUM[int(NVAC)])]=DRYY\n        DRZE[int(NVAC)][int(IONSUM[int(NVAC)])]=DRZZ\n        # LOOP AROUND CASCADE\n        def GOTO4(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON):\n            # CHECK FOR ELECTRON SHAKEOFF\n            IDUM=1\n            if(INIT > 1):\n                ELECN=ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]\n            INSUM=IONSUM[int(NVAC)]\n            SHAKE(ISHELL,ELECN,KGAS,LGAS,ESHK,IDUM,INSUM,JVAC)\n            #  CALCULATE ENERGY OF ELECTRON\n            if(JVAC == 0):\n                pass\n            else:\n                #  ELECTRON + SHAKEOFF\n                ELECN=ELECN-ESHK-ELEV[JVAC][IZ[int(KGAS)][int(LGAS)]]\n                ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ELECN\n                IONSUM[int(NVAC)]=IONSUM[int(NVAC)]+1\n                # MAXIMUM ION CHARGE STATE =28\n                if(IONSUM[int(NVAC)]> 28) :\n                    print(' 2ND GEN IONS LIMITED TO 28 IN THIS VERSION IONSUM=',IONSUM[int(NVAC)]) \n                    sys.exit()\n                # endif\n                ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ESHK\n                ELEFT=ELEFT-ESHK-ELEV[JVAC][IZ[int(KGAS)][int(LGAS)]]\n                if(ELEFT < 0.0):\n                    GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                # RANDOM EMISSION DIRECTION\n                R3=random.uniform(0.0,1.0)\n                THET=numpy.arccos(1.0-2.0*R3)\n                R4=random.uniform(0.0,1.0)\n                PHI=TWOPI*R4\n                DRXE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.cos(PHI)\n                DRYE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.sin(PHI)\n                DRZE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.cos(THET)\n            def GOTO2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON):\n                UPDATE(KGAS,LGAS,ISHELL)\n                INIT=2\n                # CHOOSE FLUORESCENCE OR AUGER TRANSITION\n                TSUM=0.0\n                for I in range(1,17+1):\n                    TSUM=TSUM+RADR[int(KGAS)][int(LGAS)][ISHELL][I]\n                    for J in range(1,17+1):\n                        TSUM=TSUM+AUGR[int(KGAS)][int(LGAS)][ISHELL][I][J]\n                # NO MORE TRANSITIONS POSSIBLE\n                if(TSUM == 0.0):\n                    return  \n                # NORMALISE TO 1.0\n                for I in range(1,17+1):\n                    RADR[int(KGAS)][int(LGAS)][ISHELL][I]=RADR[int(KGAS)][int(LGAS)][ISHELL][I]/TSUM\n                    for J in range(1,17+1):\n                        AUGR[int(KGAS)][int(LGAS)][ISHELL][I][J]=AUGR[int(KGAS)][int(LGAS)][ISHELL][I][J]/TSUM\n                # CREATE CUMULATIVE SUM ARRAY\n                TEMP[1]=RADR[int(KGAS)][int(LGAS)][ISHELL][1]\n                for I in range(2,17+1):\n                    TEMP[I]=RADR[int(KGAS)][int(LGAS)][ISHELL][I]+TEMP[I-1]\n                TEMP1[1]=AUGR[int(KGAS)][int(LGAS)][ISHELL][1][1]\n                for I in range(2,17+1):\n                    TEMP1[I]=AUGR[int(KGAS)][int(LGAS)][ISHELL][I][1]+TEMP1[I-1]\n                for J in range(1,16+1):\n                    for I in range(1,17+1):\n                        TEMP1[I+(J*17)]=AUGR[int(KGAS)][int(LGAS)][ISHELL][I][(J+1)]+TEMP1[I+(J*17)-1]\n                # FIND FLUORESCENCE OR AUGER TRANSITION\n                R1=random.uniform(0.0,1.0)\n                for I in range(1,17+1):\n                    if(R1 < TEMP[I]) :\n                        # STORE PHOTON ENERGY AND UPDATE NOCC\n                        IFLSUM[int(NVAC)]=IFLSUM[int(NVAC)]+1\n                        EPHOTON[int(NVAC)][IFLSUM[int(NVAC)]]=ELEV[ISHELL][IZ[int(KGAS)][int(LGAS)]]-ELEV[I][IZ[int(KGAS)][int(LGAS)]]\n                        if(EPHOTON[int(NVAC)][IFLSUM[int(NVAC)]] < 0.0):\n                            print(' EPHOTON=','%.3f' % EPHOTON[int(NVAC)][IFLSUM[int(NVAC)]],' NVAC=',NVAC,' IN CALC2')\n                        ELEFT=ELEFT-EPHOTON[int(NVAC)][IFLSUM[int(NVAC)]]\n                        if(ELEFT < 0.0):\n                            GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                        # RANDOM EMISSION DIRECTION\n                        R3=random.uniform(0.0,1.0)\n                        THET=numpy.arccos(1.0-2.0*R3)\n                        R4=random.uniform(0.0,1.0)\n                        PHI=TWOPI*R4\n                        DRX[int(NVAC)][IFLSUM[int(NVAC)]]=numpy.sin(THET)*numpy.cos(PHI)\n                        DRY[int(NVAC)][IFLSUM[int(NVAC)]]=numpy.sin(THET)*numpy.sin(PHI)\n                        DRZ[int(NVAC)][IFLSUM[int(NVAC)]]=numpy.cos(THET)\n                        NOCC[int(KGAS)][int(LGAS)][ISHELL]=NOCC[int(KGAS)][int(LGAS)][ISHELL]+1\n                        NOCC[int(KGAS)][int(LGAS)][I]=NOCC[int(KGAS)][int(LGAS)][I]-1\n                        # FIND LOWEST VACANCY\n                        VACANCY(KGAS,LGAS,ISHELL,ILAST)\n                        if(ILAST == 1):\n                            # NO MORE TRANSITIONS POSSIBLE\n                            return    \n                        # endif\n                        GOTO2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                    # endif\n            GOTO2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON) \n            counter116\n            while(counter116):\n                counter116=0\n                R2=R1-TEMP[17]\n                for J in range(1,17+1):\n                    if(counter116):\n                        break\n                    for I in range(1,17+1):\n                        if(R2 < TEMP1[I+((J-1)*17)]) :\n                            # AUGER OR COSTER KRONIG  \n                            # STORE EJECTED ELECTRON AND UPDATE NOCC\n                            ETEMP=ELEV[ISHELL][IZ[int(KGAS)][int(LGAS)]]-(ELEV[I][IZ[int(KGAS)][int(LGAS)]]+ELEV[I][IZ[int(KGAS)][int(LGAS)]+1])*0.5-(ELEV[J][IZ[int(KGAS)][int(LGAS)]]+ELEV[J][IZ[int(KGAS)][int(LGAS)]+1])*0.5\n                            if(ETEMP < 0.0):\n                                # DO NOT ALLOW NEGATIVE ENERGY TRANSITIONS\n                                counter117=1\n                                while(counter117):\n                                    counter117=0\n                                    R1=random.uniform(0.0,1.0)\n                                    if(R1 < TEMP[17]):\n                                        counter117=1\n                                counter116=1 #34598\n                                break\n                            # endif\n                            IONSUM[int(NVAC)]=IONSUM[int(NVAC)]+1\n                            if(IONSUM[int(NVAC)]> 28) :\n                                print(' 2ND GEN IONS LIMITED TO 28 IN THIS VERSION IONSUM=',IONSUM[int(NVAC)])\n                                sys.exit()\n                            # endif\n                            ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ETEMP\n                            ELEFT=ELEFT-ETEMP\n                            if(ELEFT < 0.0):\n                                GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                            # RANDOM EMISSION DIRECTION\n                            R3=random.uniform(0.0,1.0)\n                            THET=numpy.arccos(1.0-2.0*R3)\n                            R4=random.uniform(0.0,1.0)\n                            PHI=TWOPI*R4\n                            DRXE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.cos(PHI)\n                            DRYE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.sin(PHI)\n                            DRZE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.cos(THET)\n                            NOCC[int(KGAS)][int(LGAS)][ISHELL]=NOCC[int(KGAS)][int(LGAS)][ISHELL]+1\n                            NOCC[int(KGAS)][int(LGAS)][I]=NOCC[int(KGAS)][int(LGAS)][I]-1\n                            NOCC[int(KGAS)][int(LGAS)][J]=NOCC[int(KGAS)][int(LGAS)][J]-1\n                            # FIND LOWEST VACANCY\n                            VACANCY(KGAS,LGAS,ISHELL,ILAST)\n                            if(ILAST == 1):\n                                # NO MORE TRANSITIONS POSSIBLE\n                                return\n                            # endif\n                            GOTO4(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                        # endif \n        GOTO4(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n    GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n    print(' ERROR IN CASCADE 2') \n    sys.exit() \n    # end\ndef CALC3(NVAC,KGAS,LGAS,ELECEN,ISHELL,L1):\n    # IMPLICIT #real*8(A-H,O-Z)\n    # IMPLICIT #integer*8(I-N)\n\n    #CHARACTER*6 \n    # SCR=\"\",\n    # SCR1=\"\"\n    #COMMON/GENCAS/\n    global ELEV#[17,79]\n    global NSDEG#[17]\n    global AA#[17]\n    global BB#[17]\n    global SCR,SCR1\n    #COMMON/MIXC/\n    global PRSH#(6,3,17,17)\n    global ESH#(6,3,17)\n    global AUG#(6,3,17,17,17)\n    global RAD#[6,3,17,17]\n    global PRSHBT#(6,3,17)\n    global IZ#[6,3]\n    global INIOCC#(6,3,17)\n    global ISHLMX#(6,3)\n    global AMZ#[6,3]\n    #COMMON/UPD/\n    global NOCC#(6,3,17)\n    global AUGR#(6,3,17,17,17)\n    global RADR#(6,3,17,17)\n    #COMMON/CALCAS2/\n    global IONSUM0#(10)\n    global IFLSUM0#(10)\n    global ESTORE0#(10,28)\n    global EPHOTON0#(10,28)\n    global DRXE0#(10,28)\n    global DRYE0#(10,28)\n    global DRZE0#(10,28)\n    global DRX0#(10,28)\n    global DRY0#(10,28)\n    global DRZ0#(10,28)\n    #COMMON/CALCAS3/\n    global IONSUM#(10)\n    global IFLSUM#(10)\n    global ESTORE#(10,28)\n    global EPHOTON#(10,28)\n    global DRXE#(10,28)\n    global DRYE#(10,28)\n    global DRZE#(10,28)\n    global DRX#(10,28)\n    global DRY#(10,28)\n    global DRZ#[10,28]\n    TEMP=[0 for x in range(18)]\n    TEMP1=[0 for x in range(289)]\n    #\n    # CALCULATE CASCADE IN GAS KGAS AND MOLECULAR COMPONENT LGAS\n    # WITH INTIAL ENERGY DEPOSIT ELECEN AND SHELL VACANCY CREATED AT ISHELL\n    #\n    ISTART=IONSUM[int(NVAC)]\n    ISTARTF=IFLSUM[int(NVAC)]\n    API=numpy.arccos(-1.00)\n    TWOPI=2.00*API\n    def GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON):\n        ELEFT=ELECEN\n        INIT=1\n        # SET STARTING ARRAY NOCC EQUAL TO INIOCC\n        for I in range(1,17+1):\n            NOCC[int(KGAS)][int(LGAS)][I]=INIOCC[int(KGAS)][int(LGAS)][I]\n        IONSUM[int(NVAC)]=ISTART+1\n        IFLSUM[int(NVAC)]=ISTARTF\n        # STORE PHOTOELECTRON ENERGY AND ANGLE\n        ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ELECEN-ELEV[ISHELL][IZ[int(KGAS)][int(LGAS)]]\n        ELECN=ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]\n        ELEFT=ELEFT-ELECN\n        NOCC[int(KGAS)][int(LGAS)][ISHELL]=NOCC[int(KGAS)][int(LGAS)][ISHELL]-1  \n        # USE PHOTOELECTRON ANGULAR DISTRIBUTION\n        APE=AA[ISHELL]\n        BPE=BB[ISHELL]\n        ANGGEN(APE,BPE,THET)\n        if(THET < 0.0):\n            THET=THET+API\n        R3=random.uniform(0.0,1.0)\n        PHI=TWOPI*R3\n        DRCOS(DRX0[int(NVAC)][L1],DRY0[int(NVAC)][L1],DRZ0[int(NVAC)][L1],THET,PHI,DRXX,DRYY,DRZZ)\n        DRXE[int(NVAC)][int(IONSUM[int(NVAC)])]=DRXX\n        DRYE[int(NVAC)][int(IONSUM[int(NVAC)])]=DRYY\n        DRZE[int(NVAC)][int(IONSUM[int(NVAC)])]=DRZZ\n        # LOOP AROUND CASCADE\n        def GOTO4(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON):\n            # CHECK FOR ELECTRON SHAKEOFF\n            IDUM=1\n            if(INIT > 1):\n                ELECN=ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]\n            INSUM=IONSUM[int(NVAC)]\n            SHAKE(ISHELL,ELECN,KGAS,LGAS,ESHK,IDUM,INSUM,JVAC)\n            #  CALCULATE ENERGY OF ELECTRON\n            if(JVAC == 0):\n                GOTO2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n            #  ELECTRON + SHAKEOFF\n            ELECN=ELECN-ESHK-ELEV[JVAC][IZ[int(KGAS)][int(LGAS)]]\n            ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ELECN\n            IONSUM[int(NVAC)]=IONSUM[int(NVAC)]+1\n            # MAXIMUM ION CHARGE STATE =28\n            if(IONSUM[int(NVAC)]> 28) :\n                print(' 3RD GEN ION CHARGE LIMITED TO 28  IONSUM=',IONSUM[int(NVAC)]) \n                sys.exit()\n            # endif\n            ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ESHK\n            ELEFT=ELEFT-ESHK-ELEV[JVAC][IZ[int(KGAS)][int(LGAS)]]\n            if(ELEFT < 0.0):\n                GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n            # RANDOM EMISSION ANGLE\n            R3=random.uniform(0.0,1.0)\n            THET=numpy.arccos(1.0-2.0*R3)\n            R4=random.uniform(0.0,1.0)\n            PHI=TWOPI*R4\n            DRXE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.cos(PHI)\n            DRYE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.sin(PHI)\n            DRZE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.cos(THET)\n            def GOTO2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON):\n                UPDATE(KGAS,LGAS,ISHELL)\n                INIT=2\n                # CHOOSE FLUORESCENCE OR AUGER TRANSITION\n                TSUM=0.0\n                for I in range(1,17+1):\n                    TSUM=TSUM+RADR[int(KGAS)][int(LGAS)][ISHELL][I]\n                    for J in range(1,17+1):\n                        TSUM=TSUM+AUGR[int(KGAS)][int(LGAS)][ISHELL][I][J]\n                # NO MORE TRANSITIONS POSSIBLE\n                if(TSUM == 0.0):\n                    return  \n                # NORMALISE TO 1.0\n                for I in range(1,17+1):\n                    RADR[int(KGAS)][int(LGAS)][ISHELL][I]=RADR[int(KGAS)][int(LGAS)][ISHELL][I]/TSUM\n                    for J in range(1,17+1):\n                        AUGR[int(KGAS)][int(LGAS)][ISHELL][I][J]=AUGR[int(KGAS)][int(LGAS)][ISHELL][I][J]/TSUM\n                # CREATE CUMULATIVE SUM ARRAY\n                TEMP[1]=RADR[int(KGAS)][int(LGAS)][ISHELL][1]\n                for I in range(2,17+1):\n                    TEMP[I]=RADR[int(KGAS)][int(LGAS)][ISHELL][I]+TEMP[I-1]\n                TEMP1[1]=AUGR[int(KGAS)][int(LGAS)][ISHELL][1][1]\n                for I in range(2,17+1):\n                    TEMP1[I]=AUGR[int(KGAS)][int(LGAS)][ISHELL][I][1]+TEMP1[I-1]\n                for J in range(1,16+1):\n                    for I in range(1,17+1):\n                        TEMP1[I+(J*17)]=AUGR[int(KGAS)][int(LGAS)][ISHELL][I][(J+1)]+TEMP1[I+(J*17)-1]\n                # FIND FLUORESCENCE OR AUGER TRANSITION\n                R1=random.uniform(0.0,1.0)\n                for I in range(1,17+1):\n                    if(R1 < TEMP[I]) :\n                        # STORE PHOTON ENERGY AND UPDATE NOCC\n                        IFLSUM[int(NVAC)]=IFLSUM[int(NVAC)]+1\n                        EPHOTON[int(NVAC)][IFLSUM[int(NVAC)]]=ELEV[ISHELL][IZ[int(KGAS)][int(LGAS)]]-ELEV[I][IZ[int(KGAS)][int(LGAS)]]\n                        ELEFT=ELEFT-EPHOTON[int(NVAC)][IFLSUM[int(NVAC)]]\n                        if(ELEFT < 0.0):\n                            GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                        # RANDOM EMISSION DIRECTION\n                        R3=random.uniform(0.0,1.0)\n                        THET=numpy.arccos(1.0-2.0*R3)\n                        R4=random.uniform(0.0,1.0)\n                        PHI=TWOPI*R4\n                        DRX[int(NVAC)][IFLSUM[int(NVAC)]]=numpy.sin(THET)*numpy.cos(PHI)\n                        DRY[int(NVAC)][IFLSUM[int(NVAC)]]=numpy.sin(THET)*numpy.sin(PHI)\n                        DRZ[int(NVAC)][IFLSUM[int(NVAC)]]=numpy.cos(THET)\n                        NOCC[int(KGAS)][int(LGAS)][ISHELL]=NOCC[int(KGAS)][int(LGAS)][ISHELL]+1\n                        NOCC[int(KGAS)][int(LGAS)][I]=NOCC[int(KGAS)][int(LGAS)][I]-1\n                        # FIND LOWEST VACANCY\n                        VACANCY(KGAS,LGAS,ISHELL,ILAST)\n                        if(ILAST == 1):\n                            # NO MORE TRANSITIONS POSSIBLE\n                            return    \n                        # endif\n                        GOTO2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                    # endif \n            GOTO2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)  \n            counter116=1\n            while(counter116):\n                counter116=0\n                R2=R1-TEMP[17]\n                for J in range(1,17+1):\n                    if(counter116):\n                        break\n                    for I in range(1,17+1):\n                        if(R2 < TEMP1[I+((J-1)*17)]) :\n                            # AUGER OR COSTER KRONIG  \n                            # STORE EJECTED ELECTRON AND UPDATE NOCC\n                            ETEMP=ELEV[ISHELL][IZ[int(KGAS)][int(LGAS)]]-(ELEV[I][IZ[int(KGAS)][int(LGAS)]]+ELEV[I][IZ[int(KGAS)][int(LGAS)]+1])*0.5-(ELEV[J][IZ[int(KGAS)][int(LGAS)]]+ELEV[J][IZ[int(KGAS)][int(LGAS)]+1])*0.5\n                            if(ETEMP < 0.0):\n                                # DO NOT ALLOW NEGATIVE ENERGY TRANSITIONS\n                                counter117=1\n                                while(counter117):\n                                    counter117=0\n                                    R1=random.uniform(0.0,1.0)\n                                    if(R1 < TEMP[17]):\n                                        counter117=1\n                                counter116=1\n                                break\n                                # endif\n                            IONSUM[int(NVAC)]=IONSUM[int(NVAC)]+1\n                            if(IONSUM[int(NVAC)]> 28) :\n                                print(' 3RD GEN ION CHARGE LIMITED TO 28  IONSUM=', IONSUM[int(NVAC)])\n                                sys.exit()\n                            # endif\n                            ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ETEMP\n                            ELEFT=ELEFT-ETEMP\n                            if(ELEFT < 0.0):\n                                GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                            # RANDOM EMISSION DIRECTION\n                            R3=random.uniform(0.0,1.0)\n                            THET=numpy.arccos(1.0-2.0*R3)\n                            R4=random.uniform(0.0,1.0)\n                            PHI=TWOPI*R4\n                            DRXE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.cos(PHI)\n                            DRYE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.sin(PHI)\n                            DRZE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.cos(THET)\n                            NOCC[int(KGAS)][int(LGAS)][ISHELL]=NOCC[int(KGAS)][int(LGAS)][ISHELL]+1\n                            NOCC[int(KGAS)][int(LGAS)][I]=NOCC[int(KGAS)][int(LGAS)][I]-1\n                            NOCC[int(KGAS)][int(LGAS)][J]=NOCC[int(KGAS)][int(LGAS)][J]-1\n                            # FIND LOWEST VACANCY\n                            VACANCY(KGAS,LGAS,ISHELL,ILAST)\n                            if(ILAST == 1):\n                                # NO MORE TRANSITIONS POSSIBLE\n                                return\n                            # endif\n                            GOTO4(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON) \n                        # endif\n        GOTO4(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n    GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n    print(' ERROR IN CASCADE 3') \n    sys.exit() \n    # end\n\ndef CALC4(NVAC,KGAS,LGAS,ELECEN,ISHELL,L1):\n    # IMPLICIT #real*8(A-H,O-Z)\n    # IMPLICIT #integer*8(I-N)\n    # SCR=\"\"\\nSCR1=\"\"\n    # COMMON/GENCAS/ELEV[17,79],NSDEG(17),AA[17],BB[17],SCR,SCR1\n    # COMMON/MIXC/PRSH(6,3,17,17),ESH(6,3,17),AUG(6,3,17,17,17),RAD[6,3,17,17],PRSHBT(6,3,17),IZ[6,3],INIOCC(6,3,17),ISHLMX(6,3),AMZ[6,3]\n    # COMMON/UPD/NOCC(6,3,17),AUGR(6,3,17,17,17),RADR(6,3,17,17)\n    # COMMON/CALCAS3/IONSUM0(10),IFLSUM0(10),ESTORE0(10,28),EPHOTON0(10,28),DRXE0(10,28),DRYE0(10,28),DRZE0(10,28),DRX0(10,28),DRY0(10,28),DRZ0(10,28)\n    # COMMON/CALCAS4/IONSUM(10),IFLSUM(10),ESTORE(10,28),EPHOTON(10,28),DRXE(10,28),DRYE(10,28),DRZE(10,28),DRX(10,28),DRY(10,28),DRZ[10,28]\n    # DIMENSION TEMP[17],TEMP1(289)\n\n    #COMMON/GENCAS/\n    global ELEV#[17,79]\n    global NSDEG#[17]\n    global AA#[17]\n    global BB#[17]\n    global SCR,SCR1\n    #COMMON/MIXC/\n    global PRSH#(6,3,17,17)\n    global ESH#(6,3,17)\n    global AUG#(6,3,17,17,17)\n    global RAD#[6,3,17,17]\n    global PRSHBT#(6,3,17)\n    global IZ#[6,3]\n    global INIOCC#(6,3,17)\n    global ISHLMX#(6,3)\n    global AMZ#[6,3]\n    #COMMON/UPD/\n    global NOCC#(6,3,17)\n    global AUGR#(6,3,17,17,17)\n    global RADR#(6,3,17,17)\n    #COMMON/CALCAS3/\n    global IONSUM#(10)\n    global IFLSUM#(10)\n    global ESTORE#(10,28)\n    global EPHOTON#(10,28)\n    global DRXE#(10,28)\n    global DRYE#(10,28)\n    global DRZE#(10,28)\n    global DRX#(10,28)\n    global DRY#(10,28)\n    global DRZ#[10,28]\n    # COMMON/CALCAS4/\n    global IONSUM#(10]\n    global IFLSUM#(10]\n    global ESTORE#(10,28]\n    global EPHOTON#(10,28]\n    global DRXE#(10,28]\n    global DRYE#(10,28]\n    global DRZE#(10,28]\n    global DRX#(10,28]\n    global DRY#(10,28]\n    global DRZ#[10,28]\n    #DIMENSION\n    TEMP=[0 for x in range(17)]\n    TEMP1=[0 for x in range(289)]\n    #\n    # CALCULATE CASCADE IN GAS KGAS AND MOLECULAR COMPONENT LGAS\n    # WITH INTIAL ENERGY DEPOSIT ELECEN AND SHELL VACANCY CREATED AT ISHELL\n    #\n    ISTART=IONSUM[int(NVAC)]\n    ISTARTF=IFLSUM[int(NVAC)]\n    API=numpy.arccos(-1.00)\n    TWOPI=2.00*API\n    def GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON):\n        ELEFT=ELECEN\n        INIT=1\n        # SET STARTING ARRAY NOCC EQUAL TO INIOCC\n        for I in range(1,17+1):\n            NOCC[int(KGAS)][int(LGAS)][I]=INIOCC[int(KGAS)][int(LGAS)][I]\n        IONSUM[int(NVAC)]=ISTART+1\n        IFLSUM[int(NVAC)]=ISTARTF\n        # STORE PHOTOELECTRON ENERGY AND ANGLE\n        ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ELECEN-ELEV[ISHELL][IZ[int(KGAS)][int(LGAS)]]\n        ELECN=ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]\n        ELEFT=ELEFT-ELECN\n        NOCC[int(KGAS)][int(LGAS)][ISHELL]=NOCC[int(KGAS)][int(LGAS)][ISHELL]-1  \n        # USE PHOTOELECTRON ANGULAR DISTRIBUTION\n        APE=AA[ISHELL]\n        BPE=BB[ISHELL]\n        ANGGEN(APE,BPE,THET)\n        if(THET < 0.0):\n            THET=THET+API\n        R3=random.uniform(0.0,1.0)\n        PHI=TWOPI*R3\n        DRCOS(DRX0(NVAC,L1),DRY0(NVAC,L1),DRZ0(NVAC,L1),THET,PHI,DRXX,DRYY,DRZZ)\n        DRXE[int(NVAC)][int(IONSUM[int(NVAC)])]=DRXX\n        DRYE[int(NVAC)][int(IONSUM[int(NVAC)])]=DRYY\n        DRZE[int(NVAC)][int(IONSUM[int(NVAC)])]=DRZZ\n        # LOOP AROUND CASCADE\n        def GOTO4(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON):\n            # CHECK FOR ELECTRON SHAKEOFF\n            IDUM=1\n            if(INIT > 1):\n                ELECN=ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]\n            INSUM=IONSUM[int(NVAC)]\n            SHAKE(ISHELL,ELECN,KGAS,LGAS,ESHK,IDUM,INSUM,JVAC)\n            #  CALCULATE ENERGY OF ELECTRON\n            if(JVAC == 0):\n                GOTO2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n            #  ELECTRON + SHAKEOFF\n            ELECN=ELECN-ESHK-ELEV[JVAC][IZ[int(KGAS)][int(LGAS)]]\n            ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ELECN\n            IONSUM[int(NVAC)]=IONSUM[int(NVAC)]+1\n            # MAXIMUM ION CHARGE STATE =28\n            if(IONSUM[int(NVAC)]> 28) :\n                print(' 4TH GEN ION CHARGE LIMITED TO 28 IONSUM=',IONSUM[int(NVAC)]) \n                sys.exit()\n            # endif\n            ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ESHK\n            ELEFT=ELEFT-ESHK-ELEV[JVAC][IZ[int(KGAS)][int(LGAS)]]\n            if(ELEFT < 0.0):\n                GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n            # RANDOM EMISSION ANGLE\n            R3=random.uniform(0.0,1.0)\n            THET=numpy.arccos(1.0-2.0*R3)\n            R4=random.uniform(0.0,1.0)\n            PHI=TWOPI*R4\n            DRXE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.cos(PHI)\n            DRYE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.sin(PHI)\n            DRZE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.cos(THET)\n            def GOTO2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON):\n                UPDATE(KGAS,LGAS,ISHELL)\n                INIT=2\n                # CHOOSE FLUORESCENCE OR AUGER TRANSITION\n                TSUM=0.0\n                for I in range(1,17+1):\n                    TSUM=TSUM+RADR[int(KGAS)][int(LGAS)][ISHELL][I]\n                    for J in range(1,17+1):\n                        TSUM=TSUM+AUGR[int(KGAS)][int(LGAS)][ISHELL][I][J]\n                # NO MORE TRANSITIONS POSSIBLE\n                if(TSUM == 0.0):\n                    return  \n                # NORMALISE TO 1.0\n                for I in range(1,17+1):\n                    RADR[int(KGAS)][int(LGAS)][ISHELL][I]=RADR[int(KGAS)][int(LGAS)][ISHELL][I]/TSUM\n                    for J in range(1,17+1):\n                        AUGR[int(KGAS)][int(LGAS)][ISHELL][I][J]=AUGR[int(KGAS)][int(LGAS)][ISHELL][I][J]/TSUM\n                # CREATE CUMULATIVE SUM ARRAY\n                TEMP[1]=RADR[int(KGAS)][int(LGAS)][ISHELL][1]\n                for I in range(2,17+1):\n                    TEMP[I]=RADR[int(KGAS)][int(LGAS)][ISHELL][I]+TEMP[I-1]\n                TEMP1[1]=AUGR[int(KGAS)][int(LGAS)][ISHELL][1][1]\n                for I in range(2,17+1):\n                    TEMP1[I]=AUGR[int(KGAS)][int(LGAS)][ISHELL][I][1]+TEMP1[I-1]\n                for J in range(1,16+1):\n                    for I in range(1,17+1):\n                        TEMP1[I+(J*17)]=AUGR[int(KGAS)][int(LGAS)][ISHELL][I][(J+1)]+TEMP1[I+(J*17)-1]\n                # FIND FLUORESCENCE OR AUGER TRANSITION\n                R1=random.uniform(0.0,1.0)\n                for I in range(1,17+1):\n                    if(R1 < TEMP[I]) :\n                        # STORE PHOTON ENERGY AND UPDATE NOCC\n                        IFLSUM[int(NVAC)]=IFLSUM[int(NVAC)]+1\n                        EPHOTON[int(NVAC)][IFLSUM[int(NVAC)]]=ELEV[ISHELL][IZ[int(KGAS)][int(LGAS)]]-ELEV[I][IZ[int(KGAS)][int(LGAS)]]\n                        ELEFT=ELEFT-EPHOTON[int(NVAC)][IFLSUM[int(NVAC)]]\n                        if(ELEFT < 0.0):\n                            GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                        # RANDOM EMISSION DIRECTION\n                        R3=random.uniform(0.0,1.0)\n                        THET=numpy.arccos(1.0-2.0*R3)\n                        R4=random.uniform(0.0,1.0)\n                        PHI=TWOPI*R4\n                        DRX[int(NVAC)][IFLSUM[int(NVAC)]]=numpy.sin(THET)*numpy.cos(PHI)\n                        DRY[int(NVAC)][IFLSUM[int(NVAC)]]=numpy.sin(THET)*numpy.sin(PHI)\n                        DRZ[int(NVAC)][IFLSUM[int(NVAC)]]=numpy.cos(THET)\n                        NOCC[int(KGAS)][int(LGAS)][ISHELL]=NOCC[int(KGAS)][int(LGAS)][ISHELL]+1\n                        NOCC[int(KGAS)][int(LGAS)][I]=NOCC[int(KGAS)][int(LGAS)][I]-1\n                        # FIND LOWEST VACANCY\n                        VACANCY(KGAS,LGAS,ISHELL,ILAST)\n                        if(ILAST == 1):\n                            # NO MORE TRANSITIONS POSSIBLE\n                            return    \n                        # endif\n                        GOTO2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                    # endif \n            GOTO2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n            counter116=1\n            while(counter116):\n                R2=R1-TEMP[17]\n                for J in range(1,17+1):\n                    if(counter116):\n                        break\n                    for I in range(1,17+1):\n                        if(R2 < TEMP1(I+((J-1)*17))) :\n                            # AUGER OR COSTER KRONIG  \n                            # STORE EJECTED ELECTRON AND UPDATE NOCC\n                            ETEMP=ELEV[ISHELL][IZ[int(KGAS)][int(LGAS)]]-(ELEV[I][IZ[int(KGAS)][int(LGAS)]]+ELEV[I][IZ[int(KGAS)][int(LGAS)]+1])*0.5-(ELEV[J][IZ[int(KGAS)][int(LGAS)]]+ELEV[J][IZ[int(KGAS)][int(LGAS)]+1])*0.5\n                            if(ETEMP < 0.0):\n                                # DO NOT ALLOW NEGATIVE ENERGY TRANSITIONS\n                                counter117=1\n                                while(counter117):\n                                    counter117=0\n                                    R1=random.uniform(0.0,1.0)\n                                    if(R1 < TEMP[17]):\n                                        counter117=1\n                                counter116=1\n                                break\n                            # endif\n                            IONSUM[int(NVAC)]=IONSUM[int(NVAC)]+1\n                            if(IONSUM[int(NVAC)]> 28) :\n                                print(' 4TH GEN ION CHARGE LIMITED TO 28 IONSUM=',IONSUM[int(NVAC)])\n                                sys.exit()\n                            # endif\n                            ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ETEMP\n                            ELEFT=ELEFT-ETEMP\n                            if(ELEFT < 0.0):\n                                GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                            # RANDOM EMISSION DIRECTION\n                            R3=random.uniform(0.0,1.0)\n                            THET=numpy.arccos(1.0-2.0*R3)\n                            R4=random.uniform(0.0,1.0)\n                            PHI=TWOPI*R4\n                            DRXE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.cos(PHI)\n                            DRYE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.sin(PHI)\n                            DRZE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.cos(THET)\n                            NOCC[int(KGAS)][int(LGAS)][ISHELL]=NOCC[int(KGAS)][int(LGAS)][ISHELL]+1\n                            NOCC[int(KGAS)][int(LGAS)][I]=NOCC[int(KGAS)][int(LGAS)][I]-1\n                            NOCC[int(KGAS)][int(LGAS)][J]=NOCC[int(KGAS)][int(LGAS)][J]-1\n                            # FIND LOWEST VACANCY\n                            VACANCY(KGAS,LGAS,ISHELL,ILAST)\n                            if(ILAST == 1):\n                                # NO MORE TRANSITIONS POSSIBLE\n                                return\n                            # endif\n                            GOTO4(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON) \n                        # endif\n        GOTO4(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n    GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)            \n    print(' ERROR IN CASCADE 4') \n    sys.exit() \n    # end\n\ndef CALC5(NVAC,KGAS,LGAS,ELECEN,ISHELL,L1):\n    # IMPLICIT #real*8(A-H,O-Z)\n    # IMPLICIT #integer*8(I-N)\n    # SCR=\"\"\\nSCR1=\"\"\n    #COMMON/GENCAS/\n    global ELEV#[17,79]\n    global NSDEG#[17]\n    global AA#[17]\n    global BB#[17]\n    global SCR,SCR1\n    #COMMON/MIXC/\n    global PRSH#(6,3,17,17)\n    global ESH#(6,3,17)\n    global AUG#(6,3,17,17,17)\n    global RAD#[6,3,17,17]\n    global PRSHBT#(6,3,17)\n    global IZ#[6,3]\n    global INIOCC#(6,3,17)\n    global ISHLMX#(6,3)\n    global AMZ#[6,3]\n    #COMMON/UPD/\n    global NOCC#(6,3,17)\n    global AUGR#(6,3,17,17,17)\n    global RADR#(6,3,17,17)\n    #COMMON/CALCAS4/\n    global IONSUM0#(10)\n    global IFLSUM0#(10)\n    global ESTORE0#(10,28)\n    global EPHOTON0#(10,28)\n    global DRXE0#(10,28)\n    global DRYE0#(10,28)\n    global DRZE0#(10,28)\n    global DRX0#(10,28)\n    global DRY0#(10,28)\n    global DRZ0#(10,28)\n    #COMMON/CALCAS5/\n    global IONSUM#(10)\n    global IFLSUM#(10)\n    global ESTORE#(10,28)\n    global EPHOTON#(10,28)\n    global DRXE#(10,28)\n    global DRYE#(10,28)\n    global DRZE#(10,28)\n    global DRX#(10,28)\n    global DRY#(10,28)\n    global DRZ#[10,28]    \n    #DIMENSION \n    TEMP=[0 for x in range(17)]\n    TEMP1=[0 for x in range(289)]\n    #\n    # CALCULATE CASCADE IN GAS KGAS AND MOLECULAR COMPONENT LGAS\n    # WITH INTIAL ENERGY DEPOSIT ELECEN AND SHELL VACANCY CREATED AT ISHELL\n    #\n    ISTART=IONSUM[int(NVAC)]\n    ISTARTF=IFLSUM[int(NVAC)]\n    API=numpy.arccos(-1.00)\n    TWOPI=2.00*API\n    def GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON):\n        ELEFT=ELECEN\n        INIT=1\n        # SET STARTING ARRAY NOCC EQUAL TO INIOCC\n        for I in range(1,17+1):\n            NOCC[int(KGAS)][int(LGAS)][I]=INIOCC[int(KGAS)][int(LGAS)][I]\n        IONSUM[int(NVAC)]=ISTART+1\n        IFLSUM[int(NVAC)]=ISTARTF\n        ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ELECEN-ELEV[ISHELL][IZ[int(KGAS)][int(LGAS)]]\n        ELECN=ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]\n        ELEFT=ELEFT-ELECN\n        NOCC[int(KGAS)][int(LGAS)][ISHELL]=NOCC[int(KGAS)][int(LGAS)][ISHELL]-1  \n        # USE PHOTOELECTRON ANGULAR DISTRIBUTION\n        APE=AA[ISHELL]\n        BPE=BB[ISHELL]\n        ANGGEN(APE,BPE,THET)\n        if(THET < 0.0):\n            THET=THET+API\n        R3=random.uniform(0.0,1.0)\n        PHI=TWOPI*R3\n        DRCOS(DRX0[int(NVAC)][L1],DRY0[int(NVAC)][L1],DRZ0[int(NVAC)][L1],THET,PHI,DRXX,DRYY,DRZZ)\n        DRXE[int(NVAC)][int(IONSUM[int(NVAC)])]=DRXX\n        DRYE[int(NVAC)][int(IONSUM[int(NVAC)])]=DRYY\n        DRZE[int(NVAC)][int(IONSUM[int(NVAC)])]=DRZZ\n        # LOOP AROUND CASCADE\n        def GOTO4(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON):\n            # CHECK FOR ELECTRON SHAKEOFF\n            IDUM=1\n            if(INIT > 1):\n                ELECN=ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]\n            INSUM=IONSUM[int(NVAC)]\n            SHAKE(ISHELL,ELECN,KGAS,LGAS,ESHK,IDUM,INSUM,JVAC)\n            #  CALCULATE ENERGY OF ELECTRON\n            if(JVAC == 0):\n                GOTO2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n            #  ELECTRON + SHAKEOFF\n            ELECN=ELECN-ESHK-ELEV[JVAC][IZ[int(KGAS)][int(LGAS)]]\n            ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ELECN\n            IONSUM[int(NVAC)]=IONSUM[int(NVAC)]+1\n            # MAXIMUM ION CHARGE STATE =28\n            if(IONSUM[int(NVAC)]> 28) :\n                print(' 5TH GEN ION CHARGE LIMITED TO 28  IONSUM=',IONSUM[int(NVAC)])\n                sys.exit() \n            # endif\n            ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ESHK\n            ELEFT=ELEFT-ESHK-ELEV[JVAC][IZ[int(KGAS)][int(LGAS)]]\n            if(ELEFT < 0.0):\n                GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n            # RANDOM EMISSION ANGLE\n            R3=random.uniform(0.0,1.0)\n            THET=numpy.arccos(1.0-2.0*R3)\n            R4=random.uniform(0.0,1.0)\n            PHI=TWOPI*R4\n            DRXE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.cos(PHI)\n            DRYE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.sin(PHI)\n            DRZE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.cos(THET)\n            def GOTO2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON):\n                UPDATE(KGAS,LGAS,ISHELL)\n                INIT=2\n                # CHOOSE FLUORESCENCE OR AUGER TRANSITION\n                TSUM=0.0\n                for I in range(1,17+1):\n                    TSUM=TSUM+RADR[int(KGAS)][int(LGAS)][ISHELL][I]\n                    for J in range(1,17+1):\n                        TSUM=TSUM+AUGR[int(KGAS)][int(LGAS)][ISHELL][I][J]\n                # NO MORE TRANSITIONS POSSIBLE\n                if(TSUM == 0.0):\n                    return  \n                # NORMALISE TO 1.0\n                for I in range(1,17+1):\n                    RADR[int(KGAS)][int(LGAS)][ISHELL][I]=RADR[int(KGAS)][int(LGAS)][ISHELL][I]/TSUM\n                    for J in range(1,17+1):\n                        AUGR[int(KGAS)][int(LGAS)][ISHELL][I][J]=AUGR[int(KGAS)][int(LGAS)][ISHELL][I][J]/TSUM\n                # CREATE CUMULATIVE SUM ARRAY\n                TEMP[1]=RADR[int(KGAS)][int(LGAS)][ISHELL][1]\n                for I in range(2,17+1):\n                    TEMP[I]=RADR[int(KGAS)][int(LGAS)][ISHELL][I]+TEMP[I-1]\n                TEMP1[1]=AUGR[int(KGAS)][int(LGAS)][ISHELL][1][1]\n                for I in range(2,17+1):\n                    TEMP1[I]=AUGR[int(KGAS)][int(LGAS)][ISHELL][I][1]+TEMP1[I-1]\n                for J in range(1,16+1):\n                    for I in range(1,17+1):\n                        TEMP1[I+(J*17)]=AUGR[int(KGAS)][int(LGAS)][ISHELL][I][(J+1)]+TEMP1[I+(J*17)-1]\n                # FIND FLUORESCENCE OR AUGER TRANSITION\n                R1=random.uniform(0.0,1.0)\n                for I in range(1,17+1):\n                    if(R1 < TEMP[I]) :\n                        # STORE PHOTON ENERGY AND UPDATE NOCC\n                        IFLSUM[int(NVAC)]=IFLSUM[int(NVAC)]+1\n                        EPHOTON[int(NVAC)][IFLSUM[int(NVAC)]]=ELEV[ISHELL][IZ[int(KGAS)][int(LGAS)]]-ELEV[I][IZ[int(KGAS)][int(LGAS)]]\n                        ELEFT=ELEFT-EPHOTON[int(NVAC)][IFLSUM[int(NVAC)]]\n                        if(ELEFT < 0.0):\n                            GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                        # RANDOM EMISSION DIRECTION\n                        R3=random.uniform(0.0,1.0)\n                        THET=numpy.arccos(1.0-2.0*R3)\n                        R4=random.uniform(0.0,1.0)\n                        PHI=TWOPI*R4\n                        DRX[int(NVAC)][IFLSUM[int(NVAC)]]=numpy.sin(THET)*numpy.cos(PHI)\n                        DRY[int(NVAC)][IFLSUM[int(NVAC)]]=numpy.sin(THET)*numpy.sin(PHI)\n                        DRZ[int(NVAC)][IFLSUM[int(NVAC)]]=numpy.cos(THET)\n                        NOCC[int(KGAS)][int(LGAS)][ISHELL]=NOCC[int(KGAS)][int(LGAS)][ISHELL]+1\n                        NOCC[int(KGAS)][int(LGAS)][I]=NOCC[int(KGAS)][int(LGAS)][I]-1\n                        # FIND LOWEST VACANCY\n                        VACANCY(KGAS,LGAS,ISHELL,ILAST)\n                        if(ILAST == 1):\n                            # NO MORE TRANSITIONS POSSIBLE\n                            return    \n                        # endif\n                        GOTO2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                    # endif \n            GOTO2(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n            counter116=1\n            while(counter116):\n                counter116=0\n                R2=R1-TEMP[17]\n                for J in range(1,17+1):\n                    if(counter116):\n                        break\n                    for I in range(1,17+1):\n                        if(R2 < TEMP1[I+((J-1)*17)]) :\n                            # AUGER OR COSTER KRONIG  \n                            # STORE EJECTED ELECTRON AND UPDATE NOCC\n                            ETEMP=ELEV[ISHELL][IZ[int(KGAS)][int(LGAS)]]-(ELEV[I][IZ[int(KGAS)][int(LGAS)]]+ELEV[I][IZ[int(KGAS)][int(LGAS)]+1])*0.5-(ELEV[J][IZ[int(KGAS)][int(LGAS)]]+ELEV[J][IZ[int(KGAS)][int(LGAS)]+1])*0.5\n                            if(ETEMP < 0.0):\n                                # DO NOT ALLOW NEGATIVE ENERGY TRANSITIONS\n                                counter117=1\n                                while(counter117):\n                                    counter117=0\n                                    R1=random.uniform(0.0,1.0)\n                                    if(R1 < TEMP[17]):\n                                        counter117=1\n                                counter116=1\n                                break\n                            # endif\n                            IONSUM[int(NVAC)]=IONSUM[int(NVAC)]+1\n                            if(IONSUM[int(NVAC)]> 28) :\n                                print(' 5TH GEN ION CHARGE LIMITED TO 28  IONSUM=',IONSUM[int(NVAC)])\n                                sys.exit()\n                            # endif\n                            ESTORE[int(NVAC)][int(IONSUM[int(NVAC)])]=ETEMP\n                            ELEFT=ELEFT-ETEMP\n                            if(ELEFT < 0.0):\n                                GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n                            # RANDOM EMISSION DIRECTION\n                            R3=random.uniform(0.0,1.0)\n                            THET=numpy.arccos(1.0-2.0*R3)\n                            R4=random.uniform(0.0,1.0)\n                            PHI=TWOPI*R4\n                            DRXE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.cos(PHI)\n                            DRYE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.sin(THET)*numpy.sin(PHI)\n                            DRZE[int(NVAC)][int(IONSUM[int(NVAC)])]=numpy.cos(THET)\n                            NOCC[int(KGAS)][int(LGAS)][ISHELL]=NOCC[int(KGAS)][int(LGAS)][ISHELL]+1\n                            NOCC[int(KGAS)][int(LGAS)][I]=NOCC[int(KGAS)][int(LGAS)][I]-1\n                            NOCC[int(KGAS)][int(LGAS)][J]=NOCC[int(KGAS)][int(LGAS)][J]-1\n                            # FIND LOWEST VACANCY\n                            VACANCY(KGAS,LGAS,ISHELL,ILAST)\n                            if(ILAST == 1):\n                                # NO MORE TRANSITIONS POSSIBLE\n                                return\n                            # endif\n                            GOTO4(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON) \n                        # endif\n        GOTO4(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)\n    GOTO100(IPN,NVAC,KGAS,LGAS,ELECEN,ISHELL,ICON)    \n    print(' ERROR IN CASCADE 5') \n    sys.exit() \n  # end\n", "meta": {"hexsha": "826aa7f06d84075f7c4d821198948ef34756ea0a", "size": 72681, "ext": "py", "lang": "Python", "max_stars_repo_path": "Calcn.py", "max_stars_repo_name": "fireballpoint1/fortranTOpy", "max_stars_repo_head_hexsha": "55843a62c6f0a2f8e2a777ef70193940d3d2d141", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-26T05:10:56.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-26T05:10:56.000Z", "max_issues_repo_path": "Calcn.py", "max_issues_repo_name": "fireballpoint1/fortranTOpy", "max_issues_repo_head_hexsha": "55843a62c6f0a2f8e2a777ef70193940d3d2d141", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Calcn.py", "max_forks_repo_name": "fireballpoint1/fortranTOpy", "max_forks_repo_head_hexsha": "55843a62c6f0a2f8e2a777ef70193940d3d2d141", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-06-26T18:06:44.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-26T18:06:44.000Z", "avg_line_length": 44.6717885679, "max_line_length": 230, "alphanum_fraction": 0.4791898846, "include": true, "reason": "import numpy", "num_tokens": 23271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.25386099567919973, "lm_q1q2_score": 0.15141111600892795}}
{"text": "from __future__ import division\nimport time, csv, os.path\nfrom math import log, exp\n#from mpmath import loggamma\nfrom operator import itemgetter, gt, ge\nfrom functools import partial\nfrom itertools import imap, starmap, repeat, groupby, ifilter, tee, izip, islice\nfrom random import shuffle\nfrom Code.AlignUtils import prediction_mapping, Alignment\nfrom Code.GeneralUtils import repeatfunc, unique_justseen, prots_from_path\nimport struct\nimport tempfile\n\ntry:\n    from memorised.decorators import memorise\nexcept ImportError:\n    class memorise(object):\n        def __init__(self, func):\n            self.func = func\n            self.cache = {}\n        def __call__(self, *args, **kwargs):\n            try:\n                return self.cache[args]\n            except KeyError:\n                v = self.func(*args, **kwargs)\n                self.cache[args] = v\n                return v\n            except TypeError:\n                print 'unhash-able'\n                return self.func(*args, **kwargs)\n        def __repr__(self):\n            return self.func.__doc__\n        def __get__(self, obj, objtype):\n            return partial(self.__call__, obj)\n\ndef take(N, iterable):\n    \"\"\"Takes N items from an iterable.\"\"\"\n    return list(islice(iterable, N))\n\n\nclass TmpFileList(object):\n    def __init__(self, inputfloats):\n\n        inputfloats.sort()\n        self.struct = struct.Struct('d')\n        self.tmpfile = tempfile.TemporaryFile()\n        for val in inputfloats:\n            s = self.struct.pack(val)\n            self.tmpfile.write(s)\n        self.tmpfile.seek(0)\n        self.advance()\n\n    def advance(self):\n        try:\n            s = self.tmpfile.read(self.struct.size)\n            self.key = self.struct.unpack(s)[0]\n            return False\n        except struct.error:\n            return True\n\n\n\ndef sort_large_float(iterable, chunksize = 5e6):\n\n    maxchunks = 100\n    tmpfiles = []\n    chunk = take(chunksize, iterable)\n    while chunk:\n        chunk.sort()\n        tmpfiles.append(TmpFileList(chunk))\n        if len(tmpfiles) > maxchunks:\n            break\n        chunk = take(chunksize, iterable)\n\n    cval = 1e100\n    while tmpfiles:\n\n        ind, tmpobj = min(enumerate(tmpfiles), key = lambda x: x[1].key)\n        yield tmpobj.key\n        if tmpobj.advance():\n            tmpfiles.pop(ind)\n\n\n\n\ndef tuple_shuffle(tup):\n    t = list(tup)\n    shuffle(t)\n    return tuple(t)\n\n@memorise()\ndef linkage_pval(sa, sb, num_reps = 100000):\n    \"\"\"Caluculates the p-value associated with the observed linkage.\n\n    Uses a permutation test to determine the likelihood of getting a linkage \n    score greater than the observed score. Returns the fraction \n    of permutations which have a linkage greater than observed.\n    \n    Arguements:\n    sa -- An iterable indicating the first signal\n    sb -- An iterable indicating the second signal\n    \n    Kwargs:\n    num_reps -- The number of repititions to perform. Default: 5000\n\n    Signals MUST be the same length! Items must be hashable!\n    \n    Returns:\n    p-value -- float\"\"\"\n\n    def get_score(signal_a, signal_b):\n        mappings = prediction_mapping(tuple(signal_a), tuple_shuffle(signal_b))\n        return sum(imap(itemgetter(2), mappings))/len(signal_a)\n    \n    rscore = get_score(sa, sb)\n    check_score = partial(gt, rscore)\n    return sum(imap(check_score, repeatfunc(get_score, num_reps, sa, sb)))/num_reps\n\ndef check_linkage_pval(a1, a2, ranges, num_reps = 100000):\n    \n    splitter = itemgetter(2,3)\n    for key, rows in groupby(ranges, itemgetter(0,1)):\n        a1s = a1.get_slice(*map(int, key))\n        a1names = set(a1s.seqs.keys())\n        for row in imap(splitter, rows):\n            a2s = a2.get_slice(*map(int, row))\n            names = a1names & set(a2s.seqs.keys())\n            \n            s1, _ = a1s.get_signal(sorted(names))\n            s2, _ = a2s.get_signal(sorted(names))\n            res = linkage_pval(tuple(s1), tuple(s2), num_reps = num_reps)\n            \n            yield key, row, res\n\ndef check_linkage_file(filename, alignment_dir):\n    \n    p1, p2 = prots_from_path(filename)\n    \n    sorter = itemgetter('Source-Start', 'Source-End', \n                        'Target-Start', 'Target-End')\n    handle = open(filename)\n    reader = csv.DictReader(handle, delimiter = '\\t')\n    freader = ifilter(itemgetter('Total-Score'), reader)\n    good_rows = unique_justseen(freader, key = sorter)\n    i1, i2 = tee(good_rows)\n    ranges = imap(sorter, i2)\n    \n    a1 = Alignment.alignment_from_file(os.path.join(alignment_dir, p1+'.aln'))\n    a2 = Alignment.alignment_from_file(os.path.join(alignment_dir, p2+'.aln'))\n    \n    for row, (_, _, p) in izip(i1, check_linkage_pval(a1, a2, ranges)):\n        row['Source-Prot'] = p1\n        row['Target-Prot'] = p2\n        row['p-val'] = p\n        \n        yield row\n    \n    \n\n\nPVAL_CUT = 0.05\n@memorise()\ndef logchoose(ni, ki):\n    #n = max(ni, ki)\n    #k = min(ni, ki)\n    try:\n        lgn1 = loggamma(ni+1)\n        lgk1 = loggamma(ki+1)\n        lgnk1 = loggamma(ni-ki+1)\n    except ValueError:\n        #print ni,ki\n        raise ValueError\n\n\n    return lgn1 - (lgnk1 + lgk1)\n\n@memorise()\ndef gauss_hypergeom(X, n, m, N):\n    \"\"\"Returns the probability of drawing X successes of m marked items\n     in n draws from a bin of N total items.\"\"\"\n\n    assert N >= m, 'Number of items %i must be larger than the number of marked items %i' % (N, m)\n    assert m >= X, 'Number of marked items %i must be larger than the number of sucesses %i' % (m, X)\n    assert n >= X, 'Number of draws %i must be larger than the number of sucesses %i' % (n, X)\n    assert N >= n, 'Number of draws %i must be smaller than the total number of items %i' % (n, N)\n\n\n    r1 = logchoose(m, X)\n    try:\n        r2 = logchoose(N-m, n-X)\n    except ValueError:\n        return 0\n    r3 = logchoose(N,n)\n\n    return exp(r1 + r2 - r3)\n\n@memorise()\ndef hypergeo_cdf(X, n, m, N):\n\n    assert N >= m, 'Number of items %i must be larger than the number of marked items %i' % (N, m)\n    assert m >= X, 'Number of marked items %i must be larger than the number of sucesses %i' % (m, X)\n    assert n >= X, 'Number of draws %i must be larger than the number of sucesses %i' % (n, X)\n    assert N >= n, 'Number of draws %i must be smaller than the total number of items %i' % (n, N)\n    assert N-m >= n-X, 'There are more failures %i than unmarked items %i' % (N-m, n-X)\n\n    s = 0\n    for i in range(1, X+1):\n        s += max(gauss_hypergeom(i, n, m, N), 0.0)\n    return min(max(s,0.0), 1)\n", "meta": {"hexsha": "53026565ad3c1fce53086d8c438177168f03ae6c", "size": 6489, "ext": "py", "lang": "Python", "max_stars_repo_path": "StatUtils.py", "max_stars_repo_name": "JudoWill/ResearchNotebooks", "max_stars_repo_head_hexsha": "35796f7ef07361eb2926c8770e623f4e9d48ab96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-02-03T03:45:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-03T03:45:29.000Z", "max_issues_repo_path": "StatUtils.py", "max_issues_repo_name": "JudoWill/ResearchNotebooks", "max_issues_repo_head_hexsha": "35796f7ef07361eb2926c8770e623f4e9d48ab96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "StatUtils.py", "max_forks_repo_name": "JudoWill/ResearchNotebooks", "max_forks_repo_head_hexsha": "35796f7ef07361eb2926c8770e623f4e9d48ab96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9, "max_line_length": 101, "alphanum_fraction": 0.613037448, "include": true, "reason": "from mpmath", "num_tokens": 1753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.2689414272294874, "lm_q1q2_score": 0.1511925505031057}}
{"text": "#!/usr/bin/env python\n\nimport glob\nimport shutil\nimport os\nfrom os.path import join as pjoin\nfrom os.path import exists, split, splitext\nimport time\n\nimport matplotlib\nimport seaborn\nseaborn.set_style(\"dark\")\n# matplotlib.use('Agg', warn=False)\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport shutil\nimport nibabel as nib\n\nfrom mako.lookup import TemplateLookup\nmakolookup = TemplateLookup(directories=['./tpl'])\n\nimport logging\nlogging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)\nlogging.getLogger('matplotlib.font_manager').disabled = True\nlogging.getLogger('matplotlib').setLevel(logging.WARNING)\nimport stabilityfuncs as sf\nimport studyinfo\nimport spike as spk\nimport shimmingcalc as shm\nimport PIL\nfrom PIL import Image as img\n\nimport pdfkit\n\n\ndef stabilitycalc(dirname, dicompath, starttime, sliceshift, shimmingfilename=None, noshimmingfilename=None, initxcenter=None, initycenter=None, initzcenter=None):\n\n    '''\n        stabilitycalc\n        =============\n        To use this function: \n            1) Create an input folder and a \"nii\" subfolder. Copy one dicom acquisition file inside input folder and copy nifti files inside \"nii\" subfolder\n            2) Check nifti files' names: \n                - acquisition file should contain \"acquisition\" in its name\n                - shimming file (if used) should contain \"shimming\" in its name \n                - no shimming file (if used) should contain \"no_shimming\" in its name\n            3) Launch command:\n                ex. -> stabilitycalc(\"outputpath\", \"dicompath\", 1, 0, \"shimmingfile.nii\", \"noshimmingfile.nii\", ...)\n\n        A folder will be create inside output path selected (dirname) where result of computation will be stored:\n            - images (.png)\n            - analysissummary.txt\n            - dataquality.txt\n            - output.html \n            - output.pdf\t\n        ----------------------------\n        REQUIREMENT INPUTS:\n            - dirname: output path to store results (path)\n            - dicompath: path to find dicom file/s (path)\n            - starttime: start time point to begin analysis (int)\n            - sliceshift: shift from center axial slice (int)\n\n        OPTIONAL INPUTS:\n            - shimmingfilename (optional): name of shimming file nii (string)\n            - noshimmingfilename (optional): name of no-shimming file nii (string)\n            - initxcenter (optional): xcenter (int)\n            - initycenter (optional): ycenter (int)\n            - initzcenter (optional): zcenter (int)\n\n    '''\n    \n    logging.debug(\"Preparing inputs...\")\n\n    if (not os.path.exists(dirname)):\n        os.mkdir(dirname)\n  \n    dicomfilenames, filenames, shimmingfilename, noshimmingfilename = sf.prepareinput(dicompath)\n\n    if len(filenames) == 0: raise Exception(\"Error while converting files in nii format\")\n\n    for filename, dicomfilename in zip(filenames, dicomfilenames):\n        \"\"\"create the stability report for a scan\"\"\"\n\n        logging.debug('dirname: {}\\n'\n                    'filename: {}\\n'\n                    'dicomfilename: {}\\n'\n                    'starttime: {}\\n'\n                    'sliceshift: {}\\n'\n                    'centers: {}, {}, {}'.format(dirname, filename, dicomfilename, starttime, sliceshift, initxcenter, initycenter, initzcenter))\n\n\n        isindividualcoil = False\n\n        if initxcenter is not None:\n            initxcenter, initycenter, initzcenter = [float(x) for x in (initxcenter, initycenter, initzcenter)]\n            isindividualcoil = True\n        \n        nim = nib.load(pjoin(dirname, filename))\n        nim_hdr = nim.get_header()\n        xdim, ydim, slicethickness,tr = nim_hdr['pixdim'][1:5]   # per gli fBirn\n        #xdim, ydim, slicethickness, tr = nim_hdr['pixdim'][0:4]    # per gli ACR\n        xsize, ysize, numslices = nim_hdr['dim'][1:4]\n\n        dims = nim.get_data().shape\n        if len(dims) == 4:\n            # normal case\n            selecteddata = nim.get_data()[:, :, :, starttime:].transpose(3, 2, 1, 0)\n        elif len(dims) == 3:\n            # single slice\n            selecteddata = nim.get_data()[:, :, starttime:]\n            sdshape2 = selecteddata.shape[2]\n            if sdshape2 > 100 :\n                # nifti loses the z dimension; we must reconstitute it\n                sdshape = selecteddata.shape\n                selecteddata = selecteddata.reshape(sdshape[0], sdshape[1], 1, sdshape[2]).transpose(3, 2, 1, 0)\n            elif sdshape2 < 100:\n                raise ValueError(\"Not Enough Data for Stability Assessment\")\n\n        numtimepoints = selecteddata.shape[0]\n\n        info = studyinfo.studyinfo_from_dicom(dicomfilename)\n\n        if info['ElementName'] == '':\n            info['ElementName'] = 'unknown'\n\n\n        if info['Coil'] != '':\n            # TODO use a real datetime\n            #TR = info['TR']\n            year = info['StudyDate'][0:4]\n            month = info['StudyDate'][4:6]\n            day = info['StudyDate'][6:8]\n            hour = info['StudyTime'][0:2]\n            minute = info['StudyTime'][2:4]\n            second = info['StudyTime'][4:6]\n            datetime = info['StudyDate'] + \"T\" + hour + minute + second\n            formatteddate = month + \"/\" + day + \"/\" + year\n            formattedtime = hour + \":\" + minute + \":\" + second\n                \n            if tr == 0:\n                tr = info['RepetitionTime']\n                tr = tr/1000\n\n        #respath = os.path.dirname(os.path.abspath(filename))\n        splitfile = os.path.split(filename)\n        # resultname = dicompath.split(\"/\")[-1] if dicompath.split(\"/\")[-1] != \"\" else dicompath.split(\"/\")[-2]\n        # resultname = splitfile[0]\n        \n        # make results directory\n        data = day + \"_\" + month + \"_\" + year\n        procresult_name = \"procresults_\" + info[\"IRCCS\"].replace(\" \", \"_\") + \"_\" + data + sf.directedfrom(splitfile[1])\n        #procresult_name = 'procresults_' + splitfile[1] + \"_\" + os.path.splitext(os.path.split(filename)[1])[0]\n\n        shutil.rmtree(pjoin(dirname, procresult_name ), ignore_errors=True)\n        if not exists(pjoin(dirname, procresult_name)):\n            os.mkdir(pjoin(dirname, procresult_name))\n\n        thisdate = time.strftime(\"%m/%d/%Y %H:%M:%S\", time.localtime())\n\n        #Copy the OPBG logo\n        folderpath = os.getcwd()\n        pngfile = folderpath + '/opbglogo1.png'\n        destination = dirname + '/' + procresult_name\n        print (pngfile) \n        shutil.copy(pngfile, destination)\n\n        #############################\n        #\n        #  Calculate various statistical images\n        #\n        # calculate the mean, stddev, variance and ptp images\n        logging.debug(\"calculating mean, stddev, and variance...\")\n        meanslice = np.mean(selecteddata, 0)\n        stddevslice = np.std(selecteddata, 0)\n        varslice = np.var(selecteddata, 0)\n        ppslice = np.ptp(selecteddata, 0)\n\n        # calculate a mask from meanimage and find its center\n        (threshguess, threshfrac) = sf.findsepval(meanslice)\n        initmask = sf.makemask(meanslice, threshfrac, 0)\n        threshmean = sf.getnzfracval(initmask * meanslice, 0.02)\n        if not isindividualcoil:\n            objectmask = sf.makemask(meanslice, threshmean, 1)\n        else:\n            objectmask = sf.makemask(meanslice, 0.01 * threshmean, 1)\n\n        logging.debug(\"calculating normalized standard deviation and sfnr...\")\n        with np.errstate(invalid='ignore'):\n            normstdslice = objectmask * np.nan_to_num(100.0 * stddevslice / meanslice)\n            minstddev = sf.nzrobust(objectmask * meanslice)[1] / 5000.0\n            sfnrslice = np.where(objectmask * stddevslice > minstddev, meanslice / stddevslice, 0.0)\n\n        # Now determine where the object is and how big it is\n        slicecenter = sf.findCOM(objectmask)\n        zcenterf = slicecenter[2]\n        zcenter = int(round(zcenterf))\n        \n        slicecenter = sf.findCOM(objectmask[zcenter, :, :])\n        xcenterf = slicecenter[0]\n        ycenterf = slicecenter[1]\n        xcenter, ycenter, zcenter = [int(round(x)) for x in (xcenterf, ycenterf, zcenterf)]\n        zcenter = zcenter + sliceshift\n        xvec = objectmask[zcenter, ycenter, :]\n        yvec = objectmask[zcenter, :, xcenter]\n        # noinspection PyUnresolvedReferences\n        xmin, xmax = np.nonzero(xvec)[0][[0, -1]]\n        xcenterf = (xmin + xmax) / 2\n        objectradiusx = (xmax - xmin + 1.0) / 2.0\n        objectradiusx_mm = xdim * objectradiusx\n        # noinspection PyUnresolvedReferences\n        ymin, ymax = np.nonzero(yvec)[0][[0, -1]]\n        ycenterf = (ymin + ymax) / 2\n        objectradiusy = (ymax - ymin + 1.0) / 2.0\n        objectradiusy_mm = ydim * objectradiusy\n        xcenter, ycenter = [int(round(x)) for x in (xcenterf, ycenterf)]\n        origslicecenter = (xcenterf, ycenterf, zcenterf)\n\n        if isindividualcoil:\n            # reset everything to assumed values\n            # TODO get this from config\n            objectmask[:, :, :] = 0.0\n            objectradiusx_mm = 85.0\n            objectradiusy_mm = 85.0\n            objectradiusx, objectradiusy = objectradiusx_mm / xdim, objectradiusy_mm / ydim\n            xcenterf, ycenterf, zcenterf = initxcenter, initycenter, initzcenter\n            for i in range(xsize):\n                ival = (float(i) - xcenterf) * xdim\n                isq = ival * ival\n                for j in range(ysize):\n                    jval = (float(j) - xcenterf) * ydim\n                    jsq = jval * jval\n                    for k in range(numslices):\n                        kval = (float(k) - zcenterf) * slicethickness\n                        ksq = kval * kval\n                        if np.sqrt(isq + jsq + ksq) <= objectradiusx_mm:\n                            objectmask[k, j, i] = 1.0\n            xcenter, ycenter, zcenter = [int(round(x)) for x in (xcenterf, ycenterf, zcenterf)]\n\n        logging.debug('coil: {}\\n'.format(info['Coil'])) \n        # define the canonical limits\n        #limits = sf.getlimits(info['Coil'])\n        limits = sf.getlimits('32Ch_Head')\n        #limits = sf.getlimits('Body')\n\n        # Try to figure out what we're looking at\n        objectname = \"Unknown\"\n\n        object_radius_mm = np.sqrt(objectradiusx_mm * objectradiusy_mm)\n        object_shape = objectradiusy / objectradiusx\n\n        birn_phantom_radiuscheck = sf.limitcheck(object_radius_mm, limits['BIRNphantom_rad'])\n        birn_phantom_shapecheck = sf.limitcheck(object_shape, limits['BIRNphantom_shape'])\n        if (birn_phantom_radiuscheck < 2) and (birn_phantom_shapecheck < 2):\n            objectname = \"BIRN phantom\"\n            logging.debug(\"setting objectname to BIRN phantom\")\n    \n        head_radiuscheck = sf.limitcheck(object_radius_mm, limits['head_rad'])\n        head_shapecheck = sf.limitcheck(object_shape, limits['head_shape'])\n        if (head_radiuscheck < 2) or (head_shapecheck < 2):\n            objectname = \"Head\"\n            logging.debug(\"setting objectname to Head\")\n    \n\n        is_birn_sequence = True\n        is_birn_protocol = True\n\n        if (xsize != 64) or (ysize != 64) or (numslices != 28) or (tr != 2.0):\n            is_birn_sequence = False\n        if is_birn_sequence and (objectname == 'BIRN phantom'):\n            logging.debug(\"Assuming this is a BIRN protocol\")\n        \n            is_birn_protocol = True\n            protocolname = \"fBIRN\"\n        else:\n            logging.debug(\"Assuming this is NOT a BIRN protocol\")\n\n            protocolname = \"Unknown\"\n\n        #############################\n        #\n        #       Odd-even SNR - Modified to match BIRN\n        #\n        logging.debug(\"calculating even/odd snr...\")\n\n        evenims = selecteddata[0::2]\n        oddims = selecteddata[1::2]\n        evenlength = evenims.shape[0]\n        oddlength = oddims.shape[0]\n        if oddlength < evenlength:\n            evenims = evenims[:evenlength - 1]\n        eodiffimage = np.sum(oddims, 0, dtype=np.int64) - np.sum(evenims, 0, dtype=np.int64)\n\n        with np.errstate(invalid='ignore', over='ignore', divide='ignore'):\n            eodiffpcimage = 100.0 * np.nan_to_num(eodiffimage / (objectmask * meanslice))\n\n\n        #############################\n        #\n        #       Weisskoff analysis - Modified to match BIRN\n        #\n        logging.debug(\"Weisskoff analysis...\")\n\n        numrois = 21\n        roisizes = range(1, numrois + 1)\n        timepoints = np.arange(0.0, tr * numtimepoints, tr)\n\n        # Axial - Z axis\n        [axialroiareas, axialweissstddevs, axialprojstddevs, axialweissrdc, axialprojcvs, axialweisscvs, timecourse] = sf.evalweisskoff(numrois, roisizes, timepoints, xcenter, ycenter, zcenter, selecteddata, \"a\")\n\n        # Coronal - Y axis\n        selecteddataweisk = selecteddata.copy().transpose(0, 3, 2, 1) # data[:, y, x, z]\n        [coronalroiareas, coronalweissstddevs, coronalprojstddevs, coronalweissrdc, coronalprojcvs, coronalweisscvs, _] = sf.evalweisskoff(numrois, roisizes, timepoints, xcenter, ycenter, zcenter, selecteddataweisk, \"c\")\n\n        # Sagittal - X axis\n        selecteddataweisk = selecteddataweisk.transpose(0, 2, 1, 3) # data[:, x, y, z]\n        [sagittalroiareas, sagittalweissstddevs, sagittalprojstddevs, sagittalweissrdc, sagittalprojcvs, sagittalweisscvs, _] = sf.evalweisskoff(numrois, roisizes, timepoints, xcenter, ycenter, zcenter, selecteddataweisk, \"s\")\n        \n        #Weiskoff 3D\n        [cuberoiareas, cubeweissstddevs, cubeprojstddevs, cubeweissrdc, cubeprojcvs, cubeweisscvs, _] = sf.evalweisskoff(numrois, roisizes, timepoints, xcenter, ycenter, zcenter, selecteddata, \"cube\")\n\n\n        #############################\n        #\n        #       Image analysis\n        #\n\n        logging.debug(\"Image analysis...\")\n        try:\n            with np.errstate(invalid='ignore'):\n                meanstats = sf.nzstats(meanslice * objectmask)\n                stddevstats = sf.nzstats(stddevslice * objectmask)\n                varstats = sf.nzstats(varslice * objectmask)\n                sfnrstats = sf.nzstats(np.nan_to_num(sfnrslice * objectmask))\n                normstdstats = sf.nzstats(normstdslice * objectmask)\n                eodiffstats = sf.nzstats(eodiffimage * objectmask)\n                eodiffpcstats = sf.nzstats(np.nan_to_num(eodiffpcimage * objectmask))\n                ppstats = sf.nzstats(ppslice * objectmask)\n\n                objectmax = np.max(objectmask)\n                objectmin = np.min(objectmask)\n                rawmeanmax = sf.completerobust(meanslice)[1]\n                [meanmin, meanmax] = sf.nzrobust(meanslice * objectmask)\n                [stddevmin, stddevmax] = sf.nzrobust(stddevslice * objectmask)\n                [varmin, varmax] = sf.nzrobust(varslice * objectmask)\n                [sfnrmin, sfnrmax] = sf.nzrobust(np.nan_to_num(sfnrslice * objectmask))\n                [normstdmin, normstdmax] = sf.nzrobust(normstdslice * objectmask)\n                [eodiffmin, eodiffmax] = sf.nzrobust(eodiffimage * objectmask)\n                [eodiffpcmin, eodiffpcmax] = sf.nzrobust(np.nan_to_num(eodiffpcimage * objectmask))\n                [ppmin, ppmax] = sf.nzrobust(ppslice * objectmask)\n        except: continue\n\n        #############################\n        #\n        #       Corner (noise region) analysis\n        #\n        roislice = 0.5 * meanslice\n        cornerroisize = 5\n        cornerxpos = int(int(cornerroisize / 2.0) + 1)\n        cornerypos = int(int(cornerroisize / 2.0) + 1)\n        cornerroi = sf.setroilims(cornerxpos, cornerypos, cornerroisize)\n        if not isindividualcoil:\n            sf.markroi(cornerroi, zcenter, roislice, 0.91 * rawmeanmax)\n        cornertc = sf.getroistdtc(selecteddata, cornerroi, zcenter)\n\n        #############################\n        #\n        #       Central ROI analysis\n        #\n        logging.debug(\"Analyzing central ROI...\")\n\n        try:\n            centralroisize = 10\n            centralroi = sf.setroilims(xcenter, ycenter, centralroisize) \n            if not isindividualcoil:\n                sf.markroi(centralroi, zcenter, roislice, 0.92 * rawmeanmax)\n            centtc = sf.getroimeantc(selecteddata, centralroi, zcenter)\n\n            ###new SNR eval - chiara\n            centval = sf.getroival(meanslice, centralroi, zcenter) #valore medio ROI\n            selecteddatadiff = selecteddata.copy() #crea copia di selecteddata\n            diffslice = np.mean(selecteddatadiff, 0)\n            diffslice [zcenter, :, :] = diffslice[zcenter, :, :] - diffslice[zcenter-1, :, :] #slice centrale - slice precedente\n            sigmad = sf.getroistd(diffslice, centralroi, zcenter) #deviazione standard \n            centsnrnew = 1.41 * (centval / sigmad) #new SNR\n        \n            cornertc_new = sf.check_zeros_corner(cornertc)\n            cornertc = cornertc_new\n            centsnrvec = centtc / cornertc\n\n            centsnr = np.mean(centsnrvec)\n            centsfnr = sf.getroival(sfnrslice, centralroi, zcenter)\n            timepoints = np.arange(0.0, tr * numtimepoints, tr)\n            centfitcoffs = np.polyfit(timepoints, timecourse, 4)\n            fittc = sf.trendgen(timepoints, centfitcoffs)\n            detrendedcenttc = centtc - fittc\n\n            centmean = np.mean(centtc)\n            centdrift = 100.0 * (np.max(fittc) - np.min(fittc)) / centmean\n            centstddev = np.std(centtc)\n            centmin = np.min(centtc)\n            centmax = np.max(centtc)\n            centpp = np.ptp(centtc)\n\n            def qualitypercent(n, basis, lim):\n                percent = n / basis * 100.0\n                quality = sf.limitcheck(percent, limits[lim])\n                return sf.qualitytag('(%4.4f%%)', quality) % percent\n\n            centstddev_qualitytag = qualitypercent(centstddev, centmean, 'central_roi_raw_std%')\n            centpp_qualitytag = qualitypercent(centpp, centmean, 'central_roi_raw_p-p%')\n\n            centmean_dt = np.mean(detrendedcenttc)\n            centstddev_dt = np.std(detrendedcenttc)\n            centmin_dt = np.min(detrendedcenttc)\n            centmax_dt = np.max(detrendedcenttc)\n            centpp_dt = np.ptp(detrendedcenttc)\n\n            centstddev_dt_qualitytag = qualitypercent(centstddev_dt, centmean_dt, 'central_roi_detrended_std%')\n            centpp_dt_qualitytag = qualitypercent(centpp_dt, centmean_dt, 'central_roi_detrended_p-p%')\n\n            #percental signal change\n            psc = 100 * (sf.getroistd(meanslice, centralroi, zcenter)/sf.getroival(meanslice, centralroi, zcenter)) \n\n        except: pass\n\n        #############################\n        #\n        #       Maximum value ROI analysis\n        #\n        logging.debug(\"Finding and analyzing maximum signal ROI...\")\n\n        try:\n            maxlocroisize = 5\n            maxlocradfrac = 0.7\n\n            # find the maximum region\n            if isindividualcoil:\n                elementmask = sf.makemask(meanslice, threshmean, 1)\n                elementcenter = sf.findCOM(elementmask)\n                elementdirvec = (elementcenter[0] - origslicecenter[0],\n                                elementcenter[1] - origslicecenter[1],\n                                elementcenter[2] - origslicecenter[2])\n                elementdirnormfac = sf.vecnorm(elementdirvec)\n                maxlocoffsetscl = maxlocradfrac * objectradiusx / elementdirnormfac\n                elementmaxpos = (origslicecenter[0] + maxlocoffsetscl * elementdirvec[0],\n                                origslicecenter[1] + maxlocoffsetscl * elementdirvec[1],\n                                origslicecenter[2] + maxlocoffsetscl * elementdirvec[2])\n                if elementmaxpos[2] > numslices - 1:\n                    newmaxlocoffsetscl = (float(numslices - 1) - origslicecenter[2]) / elementdirvec[2]\n                    elementmaxpos = (origslicecenter[0] + newmaxlocoffsetscl * elementdirvec[0],\n                                    origslicecenter[1] + newmaxlocoffsetscl * elementdirvec[1],\n                                    origslicecenter[2] + newmaxlocoffsetscl * elementdirvec[2])\n                    logging.debug(\"maxpos adjusted to fall within valid image region\")\n                    \n\n                if elementmaxpos[2] < 0:\n                    newmaxlocoffsetscl = -origslicecenter[2] / elementdirvec[2]\n                    elementmaxpos = (origslicecenter[0] + newmaxlocoffsetscl * elementdirvec[0],\n                                    origslicecenter[1] + newmaxlocoffsetscl * elementdirvec[1],\n                                    origslicecenter[2] + newmaxlocoffsetscl * elementdirvec[2])\n                    logging.debug(\"maxpos adjusted to fall within valid image region\")\n                    \n                maxloccenterx, maxloccentery, maxloccenterz = [int(round(x)) for x in elementmaxpos[:3]]\n                maxlocroi = sf.setroilims(maxloccenterx, maxloccentery, maxlocroisize)\n                sf.markroi(maxlocroi, maxloccenterz, roislice, 0.92 * rawmeanmax)\n                maxloctc = sf.getroimeantc(selecteddata, maxlocroi, zcenter)\n                maxlocsnrvec = maxloctc / cornertc\n                maxlocsnr = np.mean(maxlocsnrvec)\n                maxlocsfnr = sf.getroival(sfnrslice, maxlocroi, zcenter)\n                timepoints = np.arange(0.0, tr * numtimepoints, tr)\n\n                maxlocfitcoffs = np.polyfit(timepoints, timecourse, 2)\n                fittc = sf.trendgen(timepoints, maxlocfitcoffs)\n                detrendedmaxloctc = maxloctc - fittc\n\n                maxlocmean = np.mean(maxloctc)\n                maxlocstddev = np.std(maxloctc)\n                maxlocpp = np.ptp(maxloctc)\n\n                maxloc_qualitytag = qualitypercent(maxlocstddev, maxlocmean, 'maxlocroi_rawstddev')\n                maxloc_pp_qualitytag = qualitypercent(maxlocpp, maxlocmean, 'maxlocroi_rawpp')\n\n                maxlocmean_dt = np.mean(detrendedmaxloctc)\n                maxlocstddev_dt = np.std(detrendedmaxloctc)\n                maxlocmin_dt = np.min(detrendedmaxloctc)\n                maxlocmax_dt = np.max(detrendedmaxloctc)\n                maxlocpp_dt = np.ptp(detrendedmaxloctc)\n\n                maxloc_dt_qualitytag = qualitypercent(maxlocstddev_dt, maxlocmean_dt, 'maxlocroi_dtstddev')\n                maxlocpp_dt_qualitytag = qualitypercent(maxlocpp_dt, maxlocmean_dt, 'maxlocroi_dtpp')\n\n        except: pass\n\n\n        #############################\n        #\n        # Individual coil assessment ROIs\n        #\n        logging.debug(\"Analyzing phased array ROIs...\")\n        \n        try:\n            isphasedarray = False\n\n            coildata = sf.getphasedarraydata(info['Coil'])\n            if coildata and numslices > 1:\n                isphasedarray = True\n                numphasedarray = len(coildata)\n\n            if isphasedarray:\n                paindices = np.arange(0.0, numphasedarray, 1.0)\n                phasedarraysize = 5\n\n                phasedarrayroimeans = np.zeros(numphasedarray)\n                phasedarrayroistddevs = np.zeros(numphasedarray)\n                phasedarrayroimins = np.zeros(numphasedarray)\n                phasedarrayroimaxs = np.zeros(numphasedarray)\n                phasedarrayroipps = np.zeros(numphasedarray)\n                phasedarrayroimeans_dt = np.zeros(numphasedarray)\n                phasedarrayroistddevs_dt = np.zeros(numphasedarray)\n                phasedarrayroimins_dt = np.zeros(numphasedarray)\n                phasedarrayroimaxs_dt = np.zeros(numphasedarray)\n                phasedarrayroipps_dt = np.zeros(numphasedarray)\n                phasedarrayroisfnrs = np.zeros(numphasedarray)\n                phasedarrayroisnrs = np.zeros(numphasedarray)\n                phasedarraytcs = np.zeros((numphasedarray, len(timepoints)), dtype=float)\n                phasedarrayfittcs = np.zeros((numphasedarray, len(timepoints)), dtype=float)\n                phasedarraydttcs = np.zeros((numphasedarray, len(timepoints)), dtype=float)\n                phasedarraydttcs_demeaned = np.zeros((numphasedarray, len(timepoints)), dtype=float)\n                phasedarraytc_summary = []\n                phasedarraytc_dt_summary = []\n                for i, ele in enumerate(coildata):\n                    if selecteddata.shape[1] == 1 and coildata[ele]['zloc'] != 0:\n                        # single slice\n                        logging.debug('single slice data, changing zloc from {} to 0'.format(coildata[ele]['zloc']))\n                        \n                        coildata[ele]['zloc'] = 0\n                    roi = sf.setroilims(round(coildata[ele]['xloc']), round(coildata[ele]['yloc']), phasedarraysize)\n                    if not isindividualcoil:\n                        sf.markroi(roi, round(coildata[ele]['zloc']), roislice, 0.95 * rawmeanmax)\n                    timecourse = sf.getroimeantc(selecteddata, roi, zcenter)\n                    phasedarraytcs[i, :] = timecourse[:]\n                    snrvec = sf.getroisnr(selecteddata, roi, round(coildata[ele]['zloc']))\n                    phasedarrayroisnrs[i] = np.mean(snrvec)\n                    phasedarrayroisfnrs[i] = sf.getroival(sfnrslice, roi, round(coildata[ele]['zloc']))\n                    phasedarrayroimeans[i] = np.mean(timecourse)\n                    phasedarrayroipps[i] = np.ptp(timecourse)\n                    phasedarrayfitcoffs = np.polyfit(timepoints, timecourse, 2)\n                    phasedarrayfittcs[i, :] = sf.trendgen(timepoints, phasedarrayfitcoffs)\n                    phasedarraydttcs[i, :] = phasedarraytcs[i, :] - phasedarrayfittcs[i, :]\n                    phasedarrayroimeans_dt[i] = np.mean(phasedarraydttcs[i, :])\n                    phasedarraydttcs_demeaned[i, :] = phasedarraydttcs[i, :] - phasedarrayroimeans_dt[i]\n                    phasedarrayroipps_dt[i] = np.ptp(phasedarraydttcs[i, :])\n\n                phasedarrayroipps_percent = 100.0 * phasedarrayroipps / phasedarrayroimeans\n                phasedarrayroipps_dt_percent = 100.0 * phasedarrayroipps_dt / phasedarrayroimeans_dt\n\n                # finally calculate the correlation between the timeseries\n                coilccmatrix = np.corrcoef(phasedarraydttcs_demeaned)\n        except: pass\n\n        #############################\n        #\n        # Peripheral ROIs\n        #\n        # TODO get these from config file\n        \n        try:\n            peripheralroisize = 3\n            peripheralradfrac = 0.8\n            logging.debug(\"Analyzing peripheral ROIs...\")\n            \n            voxperroi = peripheralroisize * peripheralroisize\n            peripheralradiusx = peripheralradfrac * objectradiusx\n            peripheralradiusy = peripheralradfrac * objectradiusy\n            numperiph = 32\n\n            periphindex = np.arange(numperiph)\n            periphangles = (np.pi * 2 * periphindex) / numperiph\n            periphanglesd = (360.0 * periphindex) / numperiph\n            xlocs = xcenterf + peripheralradiusx * np.sin(periphangles)\n            ylocs = ycenterf + peripheralradiusy * np.cos(periphangles)\n            periphangmeans = np.zeros(numperiph)\n            periphangsfnrs = np.zeros(numperiph)\n            avgperiphtc = centtc * 0.0\n            avgperiphmat = np.zeros((numperiph, selecteddata.shape[0]))\n            fittingangle = np.zeros((numperiph, selecteddata.shape[0]))\n            avgperiphsnrvec = centtc * 0.0\n            periphvoxels = np.zeros((selecteddata.shape[0], voxperroi * numperiph))\n            periphsnrnew=np.ones(periphindex.shape[0])\n            \n            for i in periphindex:\n                roi = sf.setroilims(round(xlocs[i]), round(ylocs[i]), peripheralroisize)\n\n                ###new SNR for each peripheral ROI\n                periphval = sf.getroival(meanslice, roi, zcenter) \n                sigmad = sf.getroistd(diffslice, roi, zcenter) \n                periphsnrnew[i]= 1.41 * (periphval / sigmad) #new SNR\n\n                if not isindividualcoil:\n                    sf.markroi(roi, zcenter, roislice, 0.95 * rawmeanmax)\n                timecourse = sf.getroimeantc(selecteddata, roi, zcenter)\n                newvoxels = sf.getroivoxels(selecteddata, roi, zcenter)\n                for j in range(voxperroi):\n                    periphvoxels[:, i * voxperroi + j] = newvoxels[:, j]\n\n                snrvec = sf.getroisnr(selecteddata, roi, zcenter)\n                snr = np.mean(snrvec)\n                avgperiphtc += timecourse / (1.0 * numperiph)\n                periphfitanglecoffs = np.polyfit(timepoints, timecourse, 4) # da salvare in caso servano per il drift \n                periphfitangletc = sf.trendgen(timepoints, periphfitanglecoffs) \n                avgperiphmat[i,:] = timecourse #matrice 200x32\n                fittingangle[i,:] = periphfitangletc\n                avgperiphsnrvec += snrvec / (1.0 * numperiph)\n                sfnrval = sf.getroival(sfnrslice, roi, zcenter)\n                periphangmeans[i] = 100.0 * np.mean(timecourse) / centmean\n                periphangsfnrs[i] = sfnrval\n\n            avgperiphtc2 = np.mean(periphvoxels, 1) #media su tutti i pixel di tutti i voxel \n            \n            #new SNR\n            peripheralsnrnew = np.mean(periphsnrnew)\n\n            avgperiphsnrvec = avgperiphtc2 / cornertc    \n            detrendedperiphangle = avgperiphmat - fittingangle\n            periphanglemean = np.mean(detrendedperiphangle, axis=1) \n\n        \n            raw_periphanglemean = np.zeros((numperiph, 1))\n            raw_periphanglestd = np.zeros((numperiph, 1))\n            raw_periphanglepp = np.zeros((numperiph, 1))\n            raw_periphangledrift = np.zeros((numperiph, 1))\n            detrended_periphanglemean = np.zeros((numperiph, 1))\n            detrended_periphanglestd = np.zeros((numperiph, 1))\n            detrended_periphanglepp = np.zeros((numperiph, 1))\n\n            for i in periphindex:\n                raw_periphanglemean[i] = np.mean(avgperiphmat[i,:]) \n                raw_periphanglestd[i] = np.std(avgperiphmat[i,:]) \n                raw_periphanglepp[i] = np.ptp(avgperiphmat[i,:]) \n                raw_periphangledrift[i] = 100.0 * (np.max(fittingangle[i,:]) - np.min(fittingangle[i,:])) / raw_periphanglemean[i]\n                detrended_periphanglemean[i]  = np.mean(detrendedperiphangle[i,:]) \n                detrended_periphanglestd[i]  = np.std(detrendedperiphangle[i,:])\n                detrended_periphanglepp[i]  = np.ptp(detrendedperiphangle[i,:])\n\n            # do average timecourse calculations\n            periphfitcoffs = np.polyfit(timepoints, avgperiphtc, 4)\n            periphfittc = sf.trendgen(timepoints, periphfitcoffs)\n            detrendedperiphtc = avgperiphtc - periphfittc\n            periphmean = np.mean(avgperiphtc)\n            periphdrift = 100.0 * (np.max(periphfittc) - np.min(periphfittc)) / periphmean\n            periphstddev = np.std(avgperiphtc)\n            periphmin = np.min(avgperiphtc)\n            periphmax = np.max(avgperiphtc)\n            periphpp = np.ptp(avgperiphtc)\n            periph_qualitytag = qualitypercent(periphstddev, periphmean, 'peripheral_roi_raw_std%')\n            periphpp_qualitytag = qualitypercent(periphpp, periphmean, 'peripheral_roi_raw_p-p%')\n\n            periphmean_dt = np.mean(detrendedperiphtc)\n            periphstddev_dt = np.std(detrendedperiphtc)\n            periphmin_dt = np.min(detrendedperiphtc)\n            periphmax_dt = np.max(detrendedperiphtc)\n            periphpp_dt = np.ptp(detrendedperiphtc)\n            periph_dt_qualitytag = qualitypercent(periphstddev_dt, periphmean_dt, 'peripheral_roi_detrended_std%')\n            periphpp_dt_qualitytag = qualitypercent(periphpp_dt, periphmean_dt, 'peripheral_roi_detrended_p-p%')\n\n            # do calculations regarding angular dependance\n            meanangperiphval = np.mean(periphangmeans)\n            meanangperiphsfnr = np.mean(periphangsfnrs)\n            meanangperiphsnr = np.mean(avgperiphsnrvec)\n\n            ptpangperiphval = np.ptp(periphangmeans)\n            periphangintensity_qualitytag = qualitypercent(ptpangperiphval, meanangperiphval, 'peripheral_angle_p-p%')\n\n            periphang_sfnr_ptp = np.ptp(periphangsfnrs)\n            periphang_sfnr_pp_qualitytag = qualitypercent(periphang_sfnr_ptp, meanangperiphsfnr, 'peripheral_angle_SFNR_p-p%')\n        \n        except: pass\n\n        #############################\n        #\n        #       Ghost ROI analysis\n        #\n        logging.debug(\"Analyzing ghost ROI...\")\n        \n        try:\n            ghostroisize = 4\n            ghostevenxpos = int(int(xsize / 2) + 1)\n            ghostoddxpos = int(xcenterf - objectradiusx + ghostroisize - 1)\n            ghostypos = int(1 + ghostroisize / 2.0)\n            evenghostroi = sf.setroilims(ghostevenxpos, ghostypos, ghostroisize)\n            oddghostroi = sf.setroilims(ghostoddxpos, ghostypos, ghostroisize)\n            if not isindividualcoil:\n                sf.markroi(evenghostroi, zcenter, roislice, 0.97 * rawmeanmax)\n                sf.markroi(oddghostroi, zcenter, roislice, 0.97 * rawmeanmax)\n\n            evenghosttc = sf.getroimeantc(selecteddata, evenghostroi, zcenter)\n            oddghosttc = sf.getroimeantc(selecteddata, oddghostroi, zcenter)\n\n            relevenghosttc = 100.0 * evenghosttc / centtc\n            reloddghosttc = 100.0 * oddghosttc / centtc\n\n            oddghostmean = np.mean(reloddghosttc)\n            oddghoststddev = np.std(reloddghosttc)\n            oddghostmin = np.min(reloddghosttc)\n            oddghostmax = np.max(reloddghosttc)\n            oddghostpp = np.ptp(reloddghosttc)\n            evenghostmean = np.mean(relevenghosttc)\n            evenghoststddev = np.std(relevenghosttc)\n            evenghostmin = np.min(relevenghosttc)\n            evenghostmax = np.max(relevenghosttc)\n            evenghostpp = np.ptp(relevenghosttc)\n\n        except: pass\n\n        #############################\n        #\n        # Spikes Analysis (01/08/2018)\n        #\n        logging.debug(\"Analyzing spikes...\")\n        spikeok = True\n\n        try:\n            isspike = False\n            indexslice = np.arange(selecteddata.shape[1])\n            numslice = indexslice + 1\n            (spikemeants, peaks_ts, peaks_nspk, peaks_slices) = spk.SpikeDetection(selecteddata)\n\n            if (peaks_nspk.sum() > 0): #se c'è almeno uno spike\n                isspike = True\n                truepeaksslices = peaks_slices[peaks_nspk != 0]\n\n        except: spikeok = False\n\n\n        #############################\n        #\n        # Shimming Analysis (01/08/2018)\n        #\n        logging.debug(\"Analyzing shimming...\")\n        isshimming = 0\n        \n        try:\n            if shimmingfilename is not None:\n                isshimming = 1\n                (PixDiffShimming, numPixDiffShimming) = shm.Shimming(dirname, shimmingfilename, 0, 10) \n                (PixDiffNOShimming, numPixDiffNOShimming) = shm.Shimming(dirname, noshimmingfilename, 0, 10)\n                ShimmingRatio = float(numPixDiffShimming)/float(numPixDiffNOShimming) \n        except: isshimming = False         \n\n\n        #############################\n        #\n        # Output\n        #\n\n        # statistical images section\n\n        \n        # noinspection PyShadowingNames\n        def slicepic(inputslice, caption, minp, maxp, dirname, outputname, colormap):\n            sf.showslice2(inputslice, caption, minp, maxp, colormap)\n            plt.savefig(pjoin(dirname, procresult_name, outputname + '.png'), format='png')\n            plt.close()\n\n        try:\n            roimin = np.min(roislice)\n            roimax = np.max(roislice)\n\n            with np.errstate(invalid='ignore'):\n                slicepic(roislice, \"ROI locations\", roimin, roimax, dirname, 'roiimage', 1)\n                slicepic(normstdslice, \"Normalized stddev % image\", normstdmin, normstdmax, dirname, 'normstdimage', 0)\n                slicepic(objectmask, \"Object mask\", objectmin, objectmax, dirname, 'objectmaskimage', 0)\n                slicepic(varslice, \"Variance image\", varmin, varmax, dirname, 'varimage', 0)\n                slicepic(stddevslice, \"Stddev image\", stddevmin, stddevmax, dirname, 'stddevimage', 0)\n                slicepic(meanslice, \"Mean image\", meanmin, meanmax, dirname, 'meanimage', 0)\n                slicepic(sfnrslice, \"SFNR image\", sfnrmin, sfnrmax, dirname, 'sfnrimage', 0)\n                slicepic(eodiffimage, \"Even odd diff image\", eodiffmin, eodiffmax, dirname, 'eodiffimage', 0)\n                slicepic(np.nan_to_num(objectmask * eodiffpcimage), \"Even odd diff percent image\", eodiffpcmin, eodiffpcmax,\n                        dirname, 'eodiffpcimage', 0)\n                slicepic(ppslice, \"Peak to peak image\", ppmin, ppmax, dirname, 'ppimage', 0)\n            \n            def makefig(figk):\n                \"\"\"make a figure using the figure dictionary\"\"\"\n                # noinspection PyCallingNonCallable\n                figs[figk]['fn'](*figs[figk]['args'])\n                plt.savefig(pjoin(dirname, procresult_name, figk + '.png'), format='png')\n                plt.close()\n\n            # @formatter:off\n            figs = {\n                'axial_weisskoffplot': {'fn': sf.showweisskoff2, 'args': (axialroiareas, axialweissstddevs, axialprojstddevs, \"Axial Weisskoff plot\", \"Axial\")},\n                'coronal_weisskoffplot': {'fn': sf.showweisskoff2, 'args': (coronalroiareas, coronalweissstddevs, coronalprojstddevs, \"Coronal Weisskoff plot\", \"Coronal\")},\n                'sagittal_weisskoffplot': {'fn': sf.showweisskoff2, 'args': (sagittalroiareas, sagittalweissstddevs, sagittalprojstddevs, \"Sagittal Weisskoff plot\", \"Sagittal\")},\n                'cube_weisskoffplot': {'fn': sf.showweisskoff2, 'args': (cuberoiareas, cubeweissstddevs, cubeprojstddevs, \"Cube Weisskoff plot\", \"Cube\")},\n                'oddghostroiplot': {'fn': sf.showtc2, 'args': (timepoints, reloddghosttc, 0.0 * timepoints + oddghostmean, \"Relative odd ghost ROI amplitude plot (%)\")},\n                'evenghostroiplot': {'fn': sf.showtc2, 'args': (timepoints, relevenghosttc, 0.0 * timepoints + evenghostmean, \"Relative even ghost ROI amplitude plot (%)\")},     \n                'PeripheralAngle': {'fn': sf.showimage3, 'args': (avgperiphmat, periphanglesd, \"Peirpheral Intensity at different angles\" )}}\n\n            if spikeok:\n                if not isspike:\n                    figs.update({\n                        'Spike_Detection': {'fn': sf.showimage, 'args': (spikemeants, \"Background Timeseries for Spike detection\" , \"#Repetition\", \"Mean Signal in Background ROI\", \"Spike Detection (%)\")}})\n                else:\n                    figs.update({\n                        'Spike_Detection': {'fn': sf.showimage_mod, 'args': (spikemeants, \"#Repetition\", \"Mean Signal in Background ROI\", \"Spike Detection (%)\", truepeaksslices)}})\n\n            if isshimming:\n                figs.update({\n                    'ShimmingMask': {'fn': sf.showimage2, 'args': (PixDiffShimming, \"Circular Mask - Central Slice\" ,  \"Shimming Mask\")},\n                    'NOShimmingMask': {'fn': sf.showimage2, 'args': (PixDiffNOShimming, \"Circular Mask - Central Slice\", \"NO Shimming Mask\")}})\n\n            if isphasedarray:\n                figs.update({\n                    'coilccmatrix': {'fn': sf.showslice3, 'args': (coilccmatrix, \"Phased array element correlation matrix\", 0.0, 1.0, 0)},\n                    'phasedarrayroisnrplot': {'fn': sf.showtc, 'args': (paindices, phasedarrayroisnrs, \"Phased array SNR by element\")},\n                    'phasedarrayroisfnrplot': {'fn': sf.showtc, 'args': (paindices, phasedarrayroisfnrs, \"Phased array SFNR by element\")},\n                    'phasedarrayroippplot': {'fn': sf.showtc, 'args': (paindices, phasedarrayroipps_percent, \"Phased array p-p% variation by element\")},\n                    'phasedarrayroippdtplot': {'fn': sf.showtc, 'args': (paindices, phasedarrayroipps_dt_percent, \"Phased array p-p% variation by element (after detrending)\")}})\n\n            if isindividualcoil:\n                figs.update({\n                    'maxlocroiplot': {'fn': sf.showtc2, 'args': (timepoints, maxloctc, maxlocmean_dt + fittc, \"Max sensitivity ROI plot (%)\")},\n                    'maxlocroisnrplot': {'fn': sf.showtc2, 'args': (timepoints, maxlocsnrvec, 0.0 * maxlocsnrvec + maxlocsnr, \"Max sensitivity ROI SNR over time\")},\n                    'maxlocroidtplot': {'fn': sf.showtc, 'args': (timepoints, maxloctc - fittc, \"Detrended max sensitivity ROI plot (%)\")}})\n            else:\n                figs.update({\n                    'centroiplot': {'fn': sf.showtc2, 'args': (timepoints, centtc, centmean_dt + fittc, \"Central ROI plot (%)\")},\n                    'centroisnrplot': {'fn': sf.showtc2, 'args': (timepoints, centsnrvec, 0.0 * centsnrvec + centsnr, \"Central ROI SNR over time\")},\n                    'centroidtplot': {'fn': sf.showtc, 'args': (timepoints, centtc - fittc, \"Detrended central ROI plot (%)\")},\n                    'periphroiplot': {'fn': sf.showtc2, 'args': (periphanglesd, periphangmeans, 0.0 * periphanglesd + meanangperiphval, \"Relative peripheral image intensity (%)\", \"Angle\")},\n                    'periphroisfnrplot': {'fn': sf.showtc2, 'args': (periphanglesd, periphangsfnrs, 0.0 * periphanglesd + meanangperiphsfnr, \"Absolute peripheral SFNR\", \"Angle\")},\n                    'periphroitcplot': {'fn': sf.showtc2, 'args': (timepoints, avgperiphtc, periphmean_dt + periphfittc, \"Peripheral ROI plot (%)\")},\n                    'periphroisnrplot': {'fn': sf.showtc2, 'args': (timepoints, avgperiphsnrvec, 0.0 * timepoints + meanangperiphsnr, \"Peripheral ROI SNR over time\")},\n                    'periphroidttcplot': {'fn': sf.showtc, 'args': (timepoints, avgperiphtc - periphfittc, \"Detrended peripheral ROI plot (%)\")},\n                    'periphangleplot1': {'fn': sf.showimageangle, 'args': (timepoints, periphanglesd, avgperiphmat, periphanglemean, fittingangle , 0)},\n                    'periphangleplot2': {'fn': sf.showimageangle, 'args': (timepoints, periphanglesd, avgperiphmat, periphanglemean, fittingangle ,1)},\n                    'periphangleplot3': {'fn': sf.showimageangle, 'args': (timepoints, periphanglesd, avgperiphmat, periphanglemean, fittingangle ,2)},\n                    'periphangleplot4': {'fn': sf.showimageangle, 'args': (timepoints, periphanglesd, avgperiphmat, periphanglemean, fittingangle ,3)},\n                    'periphangleplot5': {'fn': sf.showimageangle, 'args': (timepoints, periphanglesd, avgperiphmat, periphanglemean, fittingangle ,4)},\n                    'periphangleplot6': {'fn': sf.showimageangle, 'args': (timepoints, periphanglesd, avgperiphmat, periphanglemean, fittingangle ,5)},\n                    'periphangleplot7': {'fn': sf.showimageangle, 'args': (timepoints, periphanglesd, avgperiphmat, periphanglemean, fittingangle ,6)},\n                    'periphangleplot8': {'fn': sf.showimageangle, 'args': (timepoints, periphanglesd, avgperiphmat, periphanglemean, fittingangle ,7)}})\n\n\n            # @formatter:on\n\n            for k in figs:\n                makefig(k)\n        \n        except:pass\n\n        try:\n            # data quality report\n            datadict = {'Coil': info['Coil'],\n                        'Date': formatteddate,\n                        'Time': formattedtime,\n                        'DateTime': datetime,\n                        'Object': objectname,\n                        'Protocol': protocolname,\n                        'Element': info['ElementName'],\n                        'processed_as_individual': isindividualcoil,\n                        'object_radius_mm': object_radius_mm,\n                        'object_shape': object_shape,\n                        'center_of_mass_x': xcenterf,\n                        'center_of_mass_y': ycenterf,\n                        'center_of_mass_z': zcenterf}\n\n\n            if not isindividualcoil:\n                datadict.update({'central_roi_raw_mean': centmean,\n                                'central_roi_raw_std': centstddev,\n                                'central_roi_raw_std%': 100.0 * centstddev / centmean,\n                                'central_roi_raw_min': centmin,\n                                'central_roi_raw_max': centmax,\n                                'central_roi_raw_p-p': centpp,\n                                'central_roi_raw_p-p%': 100.0 * centpp / centmean,\n                                'central_roi_detrended_mean': centmean_dt,\n                                'central_roi_detrended_std': centstddev_dt,\n                                'central_roi_detrended_std%': 100.0 * centstddev_dt / centmean_dt,\n                                'central_roi_detrended_min': centmin_dt,\n                                'central_roi_detrended_max': centmax_dt,\n                                'central_roi_detrended_p-p': centpp_dt,\n                                'central_roi_detrended_p-p%': 100.0 * centpp_dt / centmean_dt,\n                                'central_roi_SNR': centsnr,\n                                'central_roi_SNR_new_method': centsnrnew,\n                                'central_roi_SFNR': centsfnr,\n                                'central_roi_PSC%': psc,\n                                'central_roi_polyfit_lin': 100.0 * centfitcoffs[1] / centfitcoffs[2],\n                                'central_roi_polyfit_quad': 100.0 * centfitcoffs[0] / centfitcoffs[2],\n                                'peripheral_roi_raw_mean': periphmean,\n                                'peripheral_roi_raw_std': periphstddev,\n                                'peripheral_roi_raw_std%': 100.0 * periphstddev / periphmean,\n                                'peripheral_roi_raw_min': periphmin,\n                                'peripheral_roi_raw_max': periphmax,\n                                'peripheral_roi_raw_p-p': periphpp,\n                                'peripheral_roi_raw_p-p%': 100.0 * periphpp / periphmean,\n                                'peripheral_roi_detrended_mean': periphmean_dt,\n                                'peripheral_roi_detrended_std': periphstddev_dt,\n                                'peripheral_roi_detrended_std%': 100.0 * periphstddev_dt / periphmean_dt,\n                                'peripheral_roi_detrended_min': periphmin_dt,\n                                'peripheral_roi_detrended_max': periphmax_dt,\n                                'peripheral_roi_detrended_p-p': periphpp_dt,\n                                'peripheral_roi_detrended_p-p%': 100.0 * periphpp_dt / periphmean_dt,\n                                'peripheral_roi_SNR': meanangperiphsnr,\n                                'peripheral_roi_SNR_new_method': peripheralsnrnew,\n                                'peripheral_roi_SFNR': meanangperiphsfnr,\n                                'peripheral_roi_polyfit_lin': 100.0 * periphfitcoffs[1] / periphfitcoffs[2],\n                                'peripheral_roi_polyfit_quad': 100.0 * periphfitcoffs[0] / periphfitcoffs[2]})\n            else:\n                datadict.update({'maxloc_roi_x': elementmaxpos[0],\n                                'maxloc_roi_y': elementmaxpos[1],\n                                'maxloc_roi_z': elementmaxpos[2],\n                                'maxloc_roi_dirvec_x': elementdirvec[0] / elementdirnormfac,\n                                'maxloc_roi_dirvec_y': elementdirvec[1] / elementdirnormfac,\n                                'maxloc_roi_dirvec_z': elementdirvec[2] / elementdirnormfac,\n                                'maxloc_roi_mean': maxlocmean_dt,\n                                'maxloc_roi_std': maxlocstddev_dt,\n                                'maxloc_roi_std%': 100.0 * maxlocstddev_dt / maxlocmean_dt,\n                                'maxloc_roi_min': maxlocmin_dt,\n                                'maxloc_roi_max': maxlocmax_dt,\n                                'maxloc_roi_p-p': maxlocpp_dt,\n                                'maxloc_roi_p-p%': 100.0 * maxlocpp_dt / maxlocmean_dt,\n                                'maxloc_roi_SNR': maxlocsnr,\n                                'maxloc_roi_SFNR': maxlocsfnr,\n                                'maxloc_roi_polyfit_lin': 100.0 * maxlocfitcoffs[1] / maxlocfitcoffs[2],\n                                'maxloc_roi_polyfit_quad': 100.0 * maxlocfitcoffs[0] / maxlocfitcoffs[2]})\n            datadict.update({'odd_ghost_mean': oddghostmean,\n                            'odd_ghost_std': oddghoststddev,\n                            'odd_ghost_min': oddghostmin,\n                            'odd_ghost_max': oddghostmax,\n                            'odd_ghost_p-p': oddghostpp,\n                            'odd_ghost_p-p%': 100.0 * oddghostpp / oddghostmean,\n                            'even_ghost_mean': evenghostmean,\n                            'even_ghost_std': evenghoststddev,\n                            'even_ghost_min': evenghostmin,\n                            'even_ghost_max': evenghostmax,\n                            'even_ghost_p-p': evenghostpp,\n                            'even_ghost_p-p%': 100.0 * evenghostpp / evenghostmean,\n                            '3D_weissrdc': cubeweissrdc,\n                            'axial_weissrdc': axialweissrdc,\n                            'coronal_weissrdc': coronalweissrdc,\n                            'sagittal_weissrdc': sagittalweissrdc,\n                            'central_roi_drift%': centdrift,\n                            'peripheral_roi_drift%': periphdrift})\n            \n            \n            afp = open(pjoin(dirname, procresult_name, 'dataquality.txt'), \"w\")\n        \n            for k in datadict:\n                try:\n                    entrydesc = sf.formatlimits(limits[k])\n                    entryval = datadict[k]\n                    entryquality = sf.limitcheck(entryval, limits[k])\n                    afp.writelines(','.join((entrydesc, str(entryval), {0: 'Pass', 1: 'Warn', 2: 'Fail'}[entryquality])) + \"\\n\")\n                except KeyError:\n                    pass\n        \n        except:pass #raise Exception(\"Error generating dataquality file\")\n\n        ########################################################\n        #\n        # Write summary text file and report\n\n        try:\n            tpl = makolookup.get_template('analysissummary_mod.txt')\n            summaryfile = pjoin(dirname, procresult_name, 'analysissummary.txt')\n            with open(summaryfile, 'w') as fp:\n                fp.write(tpl.render(**locals()))\n\n            tpl = makolookup.get_template('stability_mod.html')\n            with open(pjoin(dirname, procresult_name, 'output.html'), 'w') as fp:\n                fp.write(tpl.render(**locals()))\n        except:pass #raise Exception(\"Error generating analysis summary or stability file\")\n\n        ########################################################\n        #\n        # Conversion to PDF\n\n        try:\n            dirhtml = pjoin(dirname, procresult_name) + \"/output.html\"\n            dirpdf = pjoin(dirname, procresult_name) + \"/output.pdf\"\n            config = pdfkit.configuration(wkhtmltopdf='C:\\\\Program Files\\\\wkhtmltopdf\\\\bin\\\\wkhtmltopdf.exe')\n            wkhtmltopdf_options = {\"enable-local-file-access\": None}\n            pdfkit.from_url(dirhtml, dirpdf, options = wkhtmltopdf_options, configuration=config)\n        except:raise Exception(\"Error extracting PDF\")\n\n\nif __name__ == '__main__':\n    import argparse\n\n    parser = argparse.ArgumentParser(description='Calculate stability values and create the output PDF and web page.')\n    parser.add_argument('dirname', help='the output directory')\n    parser.add_argument('dicomfilename', help='the directory where DICOM files are stored')\n    parser.add_argument('starttime', help='the number of tr periods to skip at the beginning of the file')\n    parser.add_argument('sliceshift', help='number of slice to shift for center slice analysis without artefacts by BottiLuc')\n\n    com = parser.add_argument_group('use this location as the center of mass of the phantom')\n    com.add_argument('shimmingfilename', nargs='?', metavar='shimmingfilename')\n    com.add_argument('noshimmingfilename', nargs='?', metavar='noshimmingfilename')\n    com.add_argument('initxcenter', nargs='?', metavar='xcenter')\n    com.add_argument('initycenter', nargs='?', metavar='ycenter')\n    com.add_argument('initzcenter', nargs='?', metavar='zcenter')\n\n    args = parser.parse_args()\n    if None in (args.initxcenter, args.initycenter,\n                args.initzcenter) and not args.initxcenter == args.initycenter == args.initzcenter:\n        parser.error('If you set one center of mass parameter, you must set all three.')\n\n    stabilitycalc(args.dirname, args.dicomfilename, int(args.starttime), int(args.sliceshift), args.shimmingfilename, args.noshimmingfilename, args.initxcenter, args.initycenter,\n                args.initzcenter)\n\n\n\n", "meta": {"hexsha": "978515182a6491e69a2602c4796339e868de4668", "size": 52575, "ext": "py", "lang": "Python", "max_stars_repo_path": "script/stabilitycalc.py", "max_stars_repo_name": "mri-group-opbg/stabilitycalc", "max_stars_repo_head_hexsha": "b43c021a2580d77e6f9f83ad985f12559147e196", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/stabilitycalc.py", "max_issues_repo_name": "mri-group-opbg/stabilitycalc", "max_issues_repo_head_hexsha": "b43c021a2580d77e6f9f83ad985f12559147e196", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/stabilitycalc.py", "max_forks_repo_name": "mri-group-opbg/stabilitycalc", "max_forks_repo_head_hexsha": "b43c021a2580d77e6f9f83ad985f12559147e196", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.849112426, "max_line_length": 226, "alphanum_fraction": 0.5800665716, "include": true, "reason": "import numpy", "num_tokens": 13537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.2689414272294874, "lm_q1q2_score": 0.1511925505031057}}
{"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n################################################################################\n#\n#   MEASURE - Master Equation Automatic Solver for Unimolecular REactions\n#\n#   Copyright (c) 2010 by Joshua W. Allen (jwallen@mit.edu)\n#\n#   Permission is hereby granted, free of charge, to any person obtaining a\n#   copy of this software and associated documentation files (the 'Software'),\n#   to deal in the Software without restriction, including without limitation\n#   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n#   and/or sell copies of the Software, and to permit persons to whom the\n#   Software is furnished to do so, subject to the following conditions:\n#\n#   The above copyright notice and this permission notice shall be included in\n#   all copies or substantial portions of the Software.\n#\n#   THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n#   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n#   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n#   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n#   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n#   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n#   DEALINGS IN THE SOFTWARE.\n#\n################################################################################\n\n\"\"\"\nThis module contains the main :meth:`execute()` function for MEASURE.\n\"\"\"\n\nimport logging\nimport time\nimport os.path\nimport numpy\n\nfrom rmgpy.quantity import Quantity, constants\nfrom rmgpy.kinetics import Chebyshev, PDepArrhenius\nfrom rmgpy.reaction import Reaction\n\n################################################################################\n\nclass MEASURE:\n    \"\"\"\n    A representation of a Master Equation Automatic Solver for Unimolecular\n    REactions (MEASURE) job. The attributes are:\n    \n    =================== ======================= ================================\n    Attribute           Type                    Description\n    =================== ======================= ================================\n    `inputFile`         ``str``                 The path to the input file\n    `logFile`           ``str``                 The path to the log file\n    `outputFile`        ``str``                 The path to the output file\n    `drawFile`          ``str``                 The path to the PES drawing file (PNG, SVG, PDF, or PS)\n    ------------------- ----------------------- --------------------------------\n    `Tmin`              :class:`Quantity`       The minimum temperature at which to compute :math:`k(T,P)` values\n    `Tmax`              :class:`Quantity`       The maximum temperature at which to compute :math:`k(T,P)` values\n    `Tcount`            ``int``                 The number of temperatures at which to compute :math:`k(T,P)` values\n    `Pmin`              :class:`Quantity`       The minimum pressure at which to compute :math:`k(T,P)` values\n    `Pmax`              :class:`Quantity`       The maximum pressure at which to compute :math:`k(T,P)` values\n    `Pcount`            ``int``                 The number of pressures at which to compute :math:`k(T,P)` values\n    `Emin`              :class:`Quantity`       The minimum energy to use to compute :math:`k(T,P)` values\n    `Emax`              :class:`Quantity`       The maximum energy to use to compute :math:`k(T,P)` values\n    `grainSize`         :class:`Quantity`       The maximum energy grain size to use to compute :math:`k(T,P)` values\n    `grainCount`        ``int``                 The minimum number of energy grains to use to compute :math:`k(T,P)` values\n    `method`            ``str``                 The method to use to reduce the master equation to :math:`k(T,P)` values\n    `model`             ``str``                 The interpolation model to fit to the computed :math:`k(T,P)` values\n    ------------------- ----------------------- --------------------------------\n    `network`           :class:`Network`        The unimolecular reaction network\n    `Tlist`             :class:`Quantity`       An array of temperatures at which to compute :math:`k(T,P)` values\n    `Plist`             :class:`Quantity`       An array of pressures at which to compute :math:`k(T,P)` values\n    `Elist`             :class:`Quantity`       An array of energies to use to compute :math:`k(T,P)` values\n    =================== ======================= ================================\n\n    \"\"\"\n    \n    def __init__(self, inputFile=None, outputFile=None, logFile=None, drawFile=None):\n        self.inputFile = inputFile\n        self.logFile = logFile\n        self.outputFile = outputFile\n        self.drawFile = drawFile\n        self.clear()\n    \n    def clear(self):\n        \"\"\"\n        Clear all loaded information about the job (except the file paths).\n        \"\"\"\n        self.Tmin = None\n        self.Tmax = None\n        self.Tcount = None\n        self.Pmin = None\n        self.Pmax = None\n        self.Pcount = None\n        self.Emin = None\n        self.Emax = None\n        self.grainSize = None\n        self.grainCount = None\n        \n        self.method = None\n        self.model = None\n        \n        self.network = None\n        self.Tlist = None\n        self.Plist = None\n        self.Elist = None\n    \n    def copy(self):\n        \"\"\"\n        Return a copy of the current MEASURE job.\n        \"\"\"\n        measure = MEASURE()\n        \n        measure.inputFile = self.inputFile\n        measure.logFile = self.logFile\n        measure.outputFile = self.outputFile\n        measure.drawFile = self.drawFile\n        \n        if self.Tmin is not None: measure.Tmin = Quantity(self.Tmin)\n        if self.Tmax is not None: measure.Tmax = Quantity(self.Tmax)\n        measure.Tcount = self.Tcount\n        if self.Pmin is not None: measure.Pmin = Quantity(self.Pmin)\n        if self.Pmax is not None: measure.Pmax = Quantity(self.Pmax)\n        measure.Pcount = self.Pcount\n        if self.Emin is not None: measure.Emin = Quantity(self.Emin)\n        if self.Emax is not None: measure.Emax = Quantity(self.Emax)\n        if self.grainSize is not None: measure.grainSize = Quantity(self.grainSize)\n        measure.grainCount = self.grainCount\n        \n        measure.method = self.method\n        measure.model = self.model\n        \n        measure.network = self.network\n        measure.Tlist = self.Tlist\n        measure.Plist = self.Plist\n        measure.Elist = self.Elist\n        \n        return measure\n    \n    def loadInput(self, inputFile=None):\n        \"\"\"\n        Load a MEASURE job from the input file located at `inputFile`, or\n        from the `inputFile` attribute if not given as a parameter.\n        \"\"\"\n        from input import readFile\n        \n        # If an input file is specified, then it overrides the inputFile attribute\n        if inputFile is not None:\n            self.inputFile = inputFile\n        # No matter where we got the input filename, make sure that it exists\n        if not os.path.exists(self.inputFile):\n            raise PDepError('Input file \"{0}\" does not exist.'.format(self.inputFile))\n        \n        # Set locations of log and output files to be in same folder as input file\n        # (unless already set previously)\n        inputDirectory = os.path.dirname(os.path.relpath(self.inputFile))\n        if not self.outputFile:\n            self.outputFile = os.path.join(inputDirectory, 'output.py')\n        if not self.logFile:\n            self.logFile = os.path.join(inputDirectory, 'MEASURE.log')\n        \n        # Load the data from the input file\n        readFile(self.inputFile, self)\n        \n    def loadOutput(self, outputFile=None):\n        \"\"\"\n        Load a MEASURE job from the output file located at `outputFile`, or\n        from the `outputFile` attribute if not given as a parameter.\n        \"\"\"\n        from input import readFile\n        \n        # If an input file is specified, then it overrides the inputFile attribute\n        if outputFile is not None:\n            self.outputFile = outputFile\n        # No matter where we got the input filename, make sure that it exists\n        if not os.path.exists(self.outputFile):\n            raise PDepError('Output file \"{0}\" does not exist.'.format(self.outputFile))\n        \n        # Load the data from the output file\n        readFile(self.outputFile, self)\n        \n    def saveInput(self, inputFile=None):\n        \"\"\"\n        Save a MEASURE job to the output file located at `outputFile`, or\n        from the `outputFile` attribute if not given as a parameter.\n        \"\"\"\n        from output import writeFile\n        \n        # If an input file is specified, then it overrides the inputFile attribute\n        if inputFile is not None:\n            self.inputFile = inputFile\n        \n        writeFile(self.inputFile, self)\n\n    def saveOutput(self, outputFile=None):\n        \"\"\"\n        Save a MEASURE job to the output file located at `outputFile`, or\n        from the `outputFile` attribute if not given as a parameter.\n        \"\"\"\n        from output import writeFile\n        \n        # If an output file is specified, then it overrides the outputFile attribute\n        if outputFile is not None:\n            self.outputFile = outputFile\n        \n        writeFile(self.outputFile, self)\n\n    def draw(self):\n        \"\"\"\n        Draw the potential energy surface corresponding to the loaded MEASURE \n        calculation.\n        \"\"\"\n        logging.info('Drawing potential energy surface...')\n        self.network.drawPotentialEnergySurface(self.drawFile)\n    \n    def compute(self):\n        \"\"\"\n        Compute the pressure-dependent rate coefficients :math:`k(T,P)` for\n        the loaded MEASURE calculation.\n        \"\"\"\n        \n        # Only proceed if the input network is valid\n        if self.network is None or self.network.errorString != '':\n            raise PDepError('Attempted to run MEASURE calculation with invalid input.')\n    \n        Nisom = len(self.network.isomers)\n        Nreac = len(self.network.reactants)\n        Nprod = len(self.network.products)\n\n        network = self.network   \n        Tmin = self.Tmin.value\n        Tmax = self.Tmax.value\n        Tlist = self.Tlist.values\n        Pmin = self.Pmin.value\n        Pmax = self.Pmax.value\n        Plist = self.Plist.values\n        method = self.method\n        model = self.model\n        \n        # Calculate the rate coefficients\n        K = network.calculateRateCoefficients(Tlist, Plist, method, grainCount=self.grainCount, grainSize=self.grainSize.value)\n\n        # Fit interpolation model\n        from rmgpy.reaction import Reaction\n        from rmgpy.measure.reaction import fitInterpolationModel\n        if model[0] != '':\n            logging.info('Fitting {0} interpolation models...'.format(model[0]))\n        configurations = []\n        configurations.extend([[isom] for isom in network.isomers])\n        configurations.extend([reactants for reactants in network.reactants])\n        configurations.extend([products for products in network.products])\n        for i in range(Nisom+Nreac+Nprod):\n            for j in range(Nisom+Nreac):\n                if i != j:\n                    # Check that we have nonzero k(T,P) values\n                    if (numpy.any(K[:,:,i,j]) and not numpy.all(K[:,:,i,j])):\n                        raise NetworkError('Zero rate coefficient encountered while updating network {0}.'.format(network))\n\n                    # Make a new net reaction\n                    netReaction = Reaction(\n                        reactants=configurations[j],\n                        products=configurations[i],\n                        kinetics=None,\n                        reversible=(i<Nisom+Nreac),\n                    )\n                    network.netReactions.append(netReaction)\n                    \n                    # Set/update the net reaction kinetics using interpolation model\n                    netReaction.kinetics = fitInterpolationModel(netReaction, Tlist, Plist,\n                        K[:,:,i,j],\n                        model, Tmin, Tmax, Pmin, Pmax, errorCheck=True)\n        logging.info('')\n    \n    def loadFAMEInput(self, path, moleculeDict=None):\n        \"\"\"\n        Load the contents of a FAME input file into the MEASURE object. FAME\n        is an early version of MEASURE written in Fortran and used by RMG-Java.\n        This script enables importing FAME input files into MEASURE so we can\n        use the additional functionality that MEASURE provides. Note that it\n        is mostly designed to load the FAME input files generated automatically\n        by RMG-Java, and may not load hand-crafted FAME input files. If you\n        specify a `moleculeDict`, then this script will use it to associate\n        the species with their structures.\n        \"\"\"\n        \n        from network import Network\n        from collision import SingleExponentialDown\n        from rmgpy.species import Species, TransitionState\n        from rmgpy.reaction import Reaction\n        from rmgpy.species import LennardJones\n        from rmgpy.statmech import HarmonicOscillator, HinderedRotor, StatesModel\n        from rmgpy.thermo import ThermoData\n        from rmgpy.kinetics import Arrhenius\n\n        def readMeaningfulLine(f):\n            line = f.readline()\n            while line != '':\n                line = line.strip()\n                if len(line) > 0 and line[0] != '#':\n                    return line\n                else:\n                    line = f.readline()\n            return ''\n\n        moleculeDict = moleculeDict or {}\n\n        logging.info('Loading file \"{0}\"...'.format(path))\n        f = open(path)\n\n        # Read method\n        method = readMeaningfulLine(f).lower()\n        if method == 'modifiedstrongcollision': \n            self.method = 'modified strong collision'\n        elif method == 'reservoirstate': \n            self.method = 'reservoir state'\n\n        # Read temperatures\n        Tcount, Tunits, Tmin, Tmax = readMeaningfulLine(f).split()\n        self.Tmin = Quantity(float(Tmin), Tunits) \n        self.Tmax = Quantity(float(Tmax), Tunits)\n        self.Tcount = int(Tcount)\n        Tlist = []\n        for i in range(int(Tcount)):\n            Tlist.append(float(readMeaningfulLine(f)))\n        self.Tlist = Quantity(Tlist, Tunits)\n        \n        # Read pressures\n        Pcount, Punits, Pmin, Pmax = readMeaningfulLine(f).split()\n        self.Pmin = Quantity(float(Pmin), Punits) \n        self.Pmax = Quantity(float(Pmax), Punits)\n        self.Pcount = int(Pcount)\n        Plist = []\n        for i in range(int(Pcount)):\n            Plist.append(float(readMeaningfulLine(f)))\n        self.Plist = Quantity(Plist, Punits)\n        \n        # Read interpolation model\n        model = readMeaningfulLine(f).split()\n        if model[0].lower() == 'chebyshev':\n            self.model = ['chebyshev', int(model[1]), int(model[2])]\n        elif model[0].lower() == 'pdeparrhenius':\n            self.model = ['pdeparrhenius']\n        \n        # Read grain size or number of grains\n        self.grainCount = 0\n        self.grainSize = Quantity(0.0, \"J/mol\")\n        for i in range(2):\n            data = readMeaningfulLine(f).split()\n            if data[0].lower() == 'numgrains':\n                self.grainCount = int(data[1])\n            elif data[0].lower() == 'grainsize':\n                self.grainSize = Quantity(float(data[2]), data[1])\n\n        # Create the Network\n        self.network = Network()\n\n        # Read collision model\n        data = readMeaningfulLine(f)\n        assert data.lower() == 'singleexpdown'\n        alpha0units, alpha0 = readMeaningfulLine(f).split()\n        T0units, T0 = readMeaningfulLine(f).split()\n        n = readMeaningfulLine(f)\n        collisionModel = SingleExponentialDown(\n            alpha0 = Quantity(float(alpha0), alpha0units),\n            T0 = Quantity(float(T0), T0units),\n            n = Quantity(float(n)),\n        )\n        \n        speciesDict = {}\n\n        # Read bath gas parameters\n        bathGas = Species(label='bath_gas', collisionModel=collisionModel)\n        molWtunits, molWt = readMeaningfulLine(f).split()\n        if molWtunits == 'u': molWtunits = 'g/mol'\n        bathGas.molecularWeight = Quantity(float(molWt), molWtunits)\n        sigmaLJunits, sigmaLJ = readMeaningfulLine(f).split()\n        epsilonLJunits, epsilonLJ = readMeaningfulLine(f).split()\n        bathGas.lennardJones = LennardJones(\n            sigma = Quantity(float(sigmaLJ), sigmaLJunits),\n            epsilon = Quantity(float(epsilonLJ), epsilonLJunits),\n        )\n        self.network.bathGas = {bathGas: 1.0}\n        \n        # Read species data\n        Nspec = int(readMeaningfulLine(f))\n        for i in range(Nspec):\n            species = Species()\n            \n            # Read species label\n            species.label = readMeaningfulLine(f)\n            speciesDict[species.label] = species\n            if species.label in moleculeDict:\n                species.molecule = [moleculeDict[species.label]]\n            \n            # Read species E0\n            E0units, E0 = readMeaningfulLine(f).split()\n            species.E0 = Quantity(float(E0), E0units)\n            \n            # Read species thermo data\n            H298units, H298 = readMeaningfulLine(f).split()\n            S298units, S298 = readMeaningfulLine(f).split()\n            Cpcount, Cpunits = readMeaningfulLine(f).split()\n            Cpdata = []\n            for i in range(int(Cpcount)):\n                Cpdata.append(float(readMeaningfulLine(f)))\n            species.thermo = ThermoData(\n                H298 = Quantity(float(H298), H298units),\n                S298 = Quantity(float(S298), S298units),\n                Tdata = Quantity([300,400,500,600,800,1000,1500], \"K\"),\n                Cpdata = Quantity(Cpdata, Cpunits),\n            )\n            \n            # Read species collision parameters\n            molWtunits, molWt = readMeaningfulLine(f).split()\n            if molWtunits == 'u': molWtunits = 'g/mol'\n            species.molecularWeight = Quantity(float(molWt), molWtunits)\n            sigmaLJunits, sigmaLJ = readMeaningfulLine(f).split()\n            epsilonLJunits, epsilonLJ = readMeaningfulLine(f).split()\n            species.lennardJones = LennardJones(\n                sigma = Quantity(float(sigmaLJ), sigmaLJunits),\n                epsilon = Quantity(float(epsilonLJ), epsilonLJunits),\n            )\n            \n            species.states = StatesModel()\n            \n            # Read species vibrational frequencies\n            freqCount, freqUnits = readMeaningfulLine(f).split()\n            frequencies = []\n            for j in range(int(freqCount)):\n                frequencies.append(float(readMeaningfulLine(f)))\n            species.states.modes.append(HarmonicOscillator(\n                frequencies = Quantity(frequencies, freqUnits),\n            ))\n            \n            # Read species external rotors\n            rotCount, rotUnits = readMeaningfulLine(f).split()\n            if int(rotCount) > 0:\n                raise NotImplementedError('Cannot handle external rotational modes in FAME input.')\n            \n            # Read species internal rotors\n            freqCount, freqUnits = readMeaningfulLine(f).split()\n            frequencies = []\n            for j in range(int(freqCount)):\n                frequencies.append(float(readMeaningfulLine(f)))\n            barrCount, barrUnits = readMeaningfulLine(f).split()\n            barriers = []\n            for j in range(int(barrCount)):\n                barriers.append(float(readMeaningfulLine(f)))\n            if barrUnits == 'cm^-1':\n                barrUnits = 'J/mol'\n                barriers = [barr * constants.h * constants.c * constants.Na * 100. for barr in barriers]\n            elif barrUnits in ['Hz', 's^-1']:\n                barrUnits = 'J/mol'\n                barriers = [barr * constants.h * constants.Na for barr in barriers]\n            elif barrUnits != 'J/mol':\n                raise Exception('Unexpected units \"{0}\" for hindered rotor barrier height.'.format(barrUnits))\n            inertia = [V0 / 2.0 / (nu * constants.c * 100.)**2 / constants.Na for nu, V0 in zip(frequencies, barriers)]\n            for I, V0 in zip(inertia, barriers):\n                species.states.modes.append(HinderedRotor(\n                    inertia = Quantity(I,\"kg*m^2\"), \n                    barrier = Quantity(V0,barrUnits), \n                    symmetry = 1,\n                ))\n                \n            # Read overall symmetry number\n            species.states.spinMultiplicity = int(readMeaningfulLine(f))\n            \n        # Read isomer, reactant channel, and product channel data\n        Nisom = int(readMeaningfulLine(f))\n        Nreac = int(readMeaningfulLine(f))\n        Nprod = int(readMeaningfulLine(f))\n        for i in range(Nisom):\n            data = readMeaningfulLine(f).split()\n            assert data[0] == '1'\n            self.network.isomers.append(speciesDict[data[1]])\n        for i in range(Nreac):\n            data = readMeaningfulLine(f).split()\n            assert data[0] == '2'\n            self.network.reactants.append([speciesDict[data[1]], speciesDict[data[2]]])\n        for i in range(Nprod):\n            data = readMeaningfulLine(f).split()\n            if data[0] == '1':\n                self.network.products.append([speciesDict[data[1]]])\n            elif data[0] == '2':\n                self.network.products.append([speciesDict[data[1]], speciesDict[data[2]]])\n\n        # Read path reactions\n        Nrxn = int(readMeaningfulLine(f))\n        for i in range(Nrxn):\n            \n            # Read and ignore reaction equation\n            equation = readMeaningfulLine(f)\n            reaction = Reaction(transitionState=TransitionState(), reversible=True)\n            self.network.pathReactions.append(reaction)\n            \n            # Read reactant and product indices\n            data = readMeaningfulLine(f).split()\n            reac = int(data[0]) - 1\n            prod = int(data[1]) - 1\n            if reac < Nisom:\n                reaction.reactants = [self.network.isomers[reac]]\n            elif reac < Nisom+Nreac:\n                reaction.reactants = self.network.reactants[reac-Nisom]\n            else:\n                reaction.reactants = self.network.products[reac-Nisom-Nreac]\n            if prod < Nisom:\n                reaction.products = [self.network.isomers[prod]]\n            elif prod < Nisom+Nreac:\n                reaction.products = self.network.reactants[prod-Nisom]\n            else:\n                reaction.products = self.network.products[prod-Nisom-Nreac]\n            \n            # Read reaction E0\n            E0units, E0 = readMeaningfulLine(f).split()\n            reaction.transitionState.E0 = Quantity(float(E0), E0units)\n            \n            # Read high-pressure limit kinetics\n            data = readMeaningfulLine(f)\n            assert data.lower() == 'arrhenius'\n            Aunits, A = readMeaningfulLine(f).split()\n            if '/' in Aunits:\n                index = Aunits.find('/')\n                Aunits = '{0}/({1})'.format(Aunits[0:index], Aunits[index+1:])\n            Eaunits, Ea = readMeaningfulLine(f).split()\n            n = readMeaningfulLine(f)\n            reaction.kinetics = Arrhenius(\n                A = Quantity(float(A), Aunits),\n                Ea = Quantity(float(Ea), Eaunits),\n                n = Quantity(float(n)),\n            )\n    \n        f.close()\n    \n    def loadFAMEOutput(self, path):\n        \"\"\"\n        Load the contents of a FAME ourput file into the MEASURE object. This\n        method assumes that you have already loaded the corresponding input\n        file via :meth:`loadFAMEInput()`.\n        \"\"\"\n        \n        def readMeaningfulLine(f):\n            line = f.readline()\n            while line != '':\n                line = line.strip()\n                if len(line) > 0 and line[0] != '#':\n                    return line\n                else:\n                    line = f.readline()\n            return ''\n            \n        with open(path, 'r') as f:\n        \n            method = readMeaningfulLine(f).strip()\n            Tlist = numpy.array([float(d) for d in readMeaningfulLine(f).strip().split()[2:]])\n            Plist = numpy.array([float(d) for d in readMeaningfulLine(f).strip().split()[2:]])\n            model = readMeaningfulLine(f).strip().split()\n            \n            Nspec = int(readMeaningfulLine(f).strip())\n            Nisom = int(readMeaningfulLine(f).strip())\n            Nreac = int(readMeaningfulLine(f).strip())\n            Nprod = int(readMeaningfulLine(f).strip())\n            Npath = int(readMeaningfulLine(f).strip())\n            Nnet = int(readMeaningfulLine(f).strip())\n            \n            assert Nisom == len(self.network.isomers)\n            assert Nreac == len(self.network.reactants)\n            assert Nprod == len(self.network.products)\n            assert Npath == len(self.network.pathReactions)\n            \n            for n in range(Nnet):\n                reac, prod = readMeaningfulLine(f).strip().split()\n                reac = int(reac) - 1; prod = int(prod) - 1\n                \n                if reac < Nisom:\n                    reactants = [self.network.isomers[reac]]\n                elif reac < Nisom + Nreac:\n                    reactants = self.network.reactants[reac-Nisom]\n                elif reac < Nisom + Nreac + Nprod:\n                    reactants = self.network.products[reac-Nisom-Nreac]\n                else:\n                    reactants = []\n                \n                if prod < Nisom:\n                    products = [self.network.isomers[prod]]\n                elif prod < Nisom + Nreac:\n                    products = self.network.reactants[prod-Nisom]\n                elif prod < Nisom + Nreac + Nprod:\n                    products = self.network.products[prod-Nisom-Nreac]\n                else:\n                    products = []\n                \n                readMeaningfulLine(f)\n                \n                K = numpy.zeros((len(Tlist), len(Plist)), numpy.float64)\n                for t in range(len(Tlist)):\n                    K[t,:] = [float(d) for d in readMeaningfulLine(f).strip().split()[1:]]\n                \n                if len(reactants) > 1:\n                    # FAME returns k(T,P) values in cm^3/mol*s and s^-1, when\n                    # we want m^3/mol*s and s^-1\n                    K /= 1e6\n                    kunits = 'm^3/(mol*s)'\n                else:\n                    kunits = 's^-1'\n                    \n                if model[0].lower() == 'chebyshev':\n                    degreeT = int(model[1]); degreeP = int(model[2])\n                    coeffs = numpy.zeros((degreeT, degreeP), numpy.float64)\n                    for t in range(degreeT):\n                        coeffs[t,:] = [float(d) for d in readMeaningfulLine(f).strip().split()]\n                    if kunits == 'm^3/(mol*s)':\n                        coeffs[0,0] -= 6.0\n                    kinetics = Chebyshev(coeffs=coeffs, kunits=kunits, Tmin=self.Tmin, Tmax=self.Tmax, Pmin=self.Pmin, Pmax=self.Pmax)\n                elif model[0].lower() == 'pdeparrhenius':\n                    pressures = []\n                    arrhenius = []\n                    for p in range(len(Plist)):\n                        P, A, n, Ea = [float(d) for d in readMeaningfulLine(f).strip().split()]\n                        if kunits == 'm^3/(mol*s)':\n                            A /= 1e6\n                        pressures.append(P)\n                        arrhenius.append(Arrhenius(\n                            A = (A,kunits), n = n, Ea = (Ea,\"J/mol\"), T0=(1,\"K\"), \n                            Tmin=self.Tmin, Tmax=self.Tmax\n                        ))\n                    kinetics = PDepArrhenius(pressures=(pressures,\"Pa\"), arrhenius=arrhenius, Tmin=self.Tmin, Tmax=self.Tmax, Pmin=self.Pmin, Pmax=self.Pmax)\n                    \n                netReaction = Reaction(\n                    reactants = reactants,\n                    products = products,\n                    kinetics = kinetics\n                )\n                \n                self.network.netReactions.append(netReaction)\n        \n################################################################################\n\ndef initializeLogging(level, logFile=None):\n    \"\"\"\n    Initialize the logging system. The level of information printed is \n    determined by looking at the ``args.quiet`` and ``args.verbose`` attributes\n    to see if either of the corresponding flags were set. The parameter `args`\n    is an object returned by the ``argparse`` module.\n    \"\"\"\n\n    # Reassign the level names so that they look better on printing\n    logging.addLevelName(logging.CRITICAL, 'CRITICAL: ')\n    logging.addLevelName(logging.ERROR, 'ERROR: ')\n    logging.addLevelName(logging.WARNING, 'Warning: ')\n    logging.addLevelName(logging.INFO, '')\n    logging.addLevelName(logging.DEBUG, '')\n\n    # Create logger\n    logger = logging.getLogger()\n    logger.setLevel(level)\n\n    # Remove any old handlers that might exist\n    while logger.handlers:\n        logger.removeHandler(logger.handlers[0])\n\n    # Create formatter\n    formatter = logging.Formatter('%(levelname)s%(message)s')\n    \n    # Create console handler and set level to debug\n    # Also send everything to stdout rather than stderr\n    import sys\n    ch = logging.StreamHandler(sys.stdout)\n    ch.setLevel(level)\n    ch.setFormatter(formatter)\n    logger.addHandler(ch)\n    \n    # create file handler\n    if logFile is not None:\n        fh = logging.FileHandler(filename=logFile, mode='w')\n        fh.setLevel(min(logging.DEBUG,level))\n        fh.setFormatter(formatter)\n        logger.addHandler(fh)\n    \n################################################################################\n\ndef logHeader(level=logging.INFO):\n    \"\"\"\n    Output a header containing identifying information about RMG to the log.\n    \"\"\"\n\n    logging.log(level, '###############################################################')\n    logging.log(level, '# Master Equation Automatic Solver for Unimolecular REactions #')\n    logging.log(level, '# (MEASURE)                                                   #')\n    logging.log(level, '# Release: 0.1.0 (7 July 2010)                                #')\n    logging.log(level, '# Author: Joshua W. Allen (jwallen@mit.edu)                   #')\n    logging.log(level, '# Website: http://jwallen.github.com/MEASURE                  #')\n    logging.log(level, '###############################################################\\n')\n\n################################################################################\n\ndef execute(inputFile, outputFile=None, drawFile=None, logFile=None, quiet=False, verbose=False):\n    \"\"\"\n    Execute a MEASURE job using the file located at `inputFile` as the input\n    file.\n    \"\"\"\n    # We will save our output files to the directory containing the input file,\n    # NOT the current working directory\n    outputDirectory = os.path.dirname(os.path.relpath(inputFile))\n\n    # Determine output level for logging system\n    if quiet: \n        level = logging.WARNING\n    elif verbose: \n        level = logging.DEBUG\n    else:\n        level = logging.INFO\n        \n    # Initialize the logging system\n    if logFile is not None:\n        logFile = os.path.abspath(logFile)\n    else:\n        logFile = os.path.join(outputDirectory, 'MEASURE.log')  \n    initializeLogging(level, logFile)\n    \n    # Log start timestamp\n    logging.info('MEASURE execution initiated at ' + time.asctime() + '\\n')\n    \n    # Log header\n    logHeader()\n    \n    # Initialize the MEASURE job\n    measure = MEASURE(inputFile=inputFile, outputFile=outputFile, logFile=logFile, drawFile=drawFile)\n        \n    # Load input file\n    measure.loadInput()\n    \n    # Proceed with the desired job\n    if measure.network is not None and measure.network.errorString == '':\n        if drawFile is not None:\n            # Draw the potential energy surface\n            measure.draw()\n        else:\n            # Compute the k(T,P) values\n            measure.compute()\n            # Save results to output file\n            measure.saveOutput()\n\n    # Log end timestamp\n    logging.info('')\n    logging.info('MEASURE execution terminated at ' + time.asctime())\n", "meta": {"hexsha": "46ea90f5b5d0cf49f44845a8e7f39ef47f9d59cd", "size": 32292, "ext": "py", "lang": "Python", "max_stars_repo_path": "rmgpy/measure/main.py", "max_stars_repo_name": "sean-v8/RMG-Py", "max_stars_repo_head_hexsha": "7cc7c3bfb330786526c56113d98c785bcaaa161a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rmgpy/measure/main.py", "max_issues_repo_name": "sean-v8/RMG-Py", "max_issues_repo_head_hexsha": "7cc7c3bfb330786526c56113d98c785bcaaa161a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rmgpy/measure/main.py", "max_forks_repo_name": "sean-v8/RMG-Py", "max_forks_repo_head_hexsha": "7cc7c3bfb330786526c56113d98c785bcaaa161a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.2289156627, "max_line_length": 157, "alphanum_fraction": 0.5529233247, "include": true, "reason": "import numpy", "num_tokens": 7077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.2909808785120009, "lm_q1q2_score": 0.15117077499667964}}
{"text": "import torch, pdb\nimport torch.nn\nfrom IPython import embed\nimport torch.nn.functional as F\nimport pdb\nimport random\nimport numpy as np\nimport time\nimport functools\n\nfrom .utils import nms, add_box_img, nms_worker\nfrom torch.multiprocessing import Pool, Manager\n\n\ndef rpn_cross_entropy(input, target):\n    r\"\"\"\n    :param input: (15x15x5,2)\n    :param target: (15x15x5,)\n    :return:\n    \"\"\"\n    mask_ignore = target == -1\n    mask_calcu = 1 - mask_ignore\n    loss = F.cross_entropy(input=input[mask_calcu], target=target[mask_calcu])\n    return loss\n\n\ndef rpn_cross_entropy_balance(input, target, num_pos, num_neg, anchors, ohem_pos=None, ohem_neg=None):\n    r\"\"\"\n    :param input: (N,1125,2)\n    :param target: (15x15x5,)\n    :return:\n    \"\"\"\n    # if ohem:\n    #     final_loss = rpn_cross_entropy_balance_parallel(input, target, num_pos, num_neg, anchors, ohem=True,\n    #                                                     num_threads=4)\n    # else:\n    loss_all = []\n    for batch_id in range(target.shape[0]):\n        min_pos = min(len(np.where(target[batch_id].cpu() == 1)[0]), num_pos)\n        min_neg = int(min(len(np.where(target[batch_id].cpu() == 1)[0]) * num_neg / num_pos, num_neg))\n        pos_index = np.where(target[batch_id].cpu() == 1)[0].tolist()\n        neg_index = np.where(target[batch_id].cpu() == 0)[0].tolist()\n\n        if ohem_pos:\n            if len(pos_index) > 0:\n                pos_loss_bid = F.cross_entropy(input=input[batch_id][pos_index],\n                                               target=target[batch_id][pos_index], reduction='none')\n                selected_pos_index = nms(anchors[pos_index], pos_loss_bid.cpu().detach().numpy(), min_pos)\n                pos_loss_bid_final = pos_loss_bid[selected_pos_index]\n            else:\n                pos_loss_bid = torch.FloatTensor([0]).cuda()\n                pos_loss_bid_final = pos_loss_bid\n        else:\n            pos_index_random = random.sample(pos_index, min_pos)\n            if len(pos_index) > 0:\n                pos_loss_bid_final = F.cross_entropy(input=input[batch_id][pos_index_random],\n                                                     target=target[batch_id][pos_index_random], reduction='none')\n            else:\n                pos_loss_bid_final = torch.FloatTensor([0]).cuda()\n\n        if ohem_neg:\n            if len(pos_index) > 0:\n                neg_loss_bid = F.cross_entropy(input=input[batch_id][neg_index],\n                                               target=target[batch_id][neg_index], reduction='none')\n                selected_neg_index = nms(anchors[neg_index], neg_loss_bid.cpu().detach().numpy(), min_neg)\n                neg_loss_bid_final = neg_loss_bid[selected_neg_index]\n            else:\n                neg_loss_bid = F.cross_entropy(input=input[batch_id][neg_index],\n                                               target=target[batch_id][neg_index], reduction='none')\n                selected_neg_index = nms(anchors[neg_index], neg_loss_bid.cpu().detach().numpy(), num_neg)\n                neg_loss_bid_final = neg_loss_bid[selected_neg_index]\n        else:\n            if len(pos_index) > 0:\n                neg_index_random = random.sample(np.where(target[batch_id].cpu() == 0)[0].tolist(), min_neg)\n                neg_loss_bid_final = F.cross_entropy(input=input[batch_id][neg_index_random],\n                                                     target=target[batch_id][neg_index_random], reduction='none')\n            else:\n                neg_index_random = random.sample(np.where(target[batch_id].cpu() == 0)[0].tolist(), num_neg)\n                neg_loss_bid_final = F.cross_entropy(input=input[batch_id][neg_index_random],\n                                                     target=target[batch_id][neg_index_random], reduction='none')\n        loss_bid = (pos_loss_bid_final.mean() + neg_loss_bid_final.mean()) / 2\n        loss_all.append(loss_bid)\n    final_loss = torch.stack(loss_all).mean()\n    return final_loss\n\n\ndef rpn_smoothL1(input, target, label, num_pos=16, ohem=None):\n    r'''\n    :param input: torch.Size([1, 1125, 4])\n    :param target: torch.Size([1, 1125, 4])\n            label: (torch.Size([1, 1125]) pos neg or ignore\n    :return:\n    '''\n    loss_all = []\n    for batch_id in range(target.shape[0]):\n        min_pos = min(len(np.where(label[batch_id].cpu() == 1)[0]), num_pos)\n        if ohem:\n            pos_index = np.where(label[batch_id].cpu() == 1)[0]\n            if len(pos_index) > 0:\n                loss_bid = F.smooth_l1_loss(input[batch_id][pos_index], target[batch_id][pos_index], reduction='none')\n                sort_index = torch.argsort(loss_bid.mean(1))\n                loss_bid_ohem = loss_bid[sort_index[-num_pos:]]\n            else:\n                loss_bid_ohem = torch.FloatTensor([0]).cuda()[0]\n            loss_all.append(loss_bid_ohem.mean())\n        else:\n            pos_index = np.where(label[batch_id].cpu() == 1)[0]\n            pos_index = random.sample(pos_index.tolist(), min_pos)\n            if len(pos_index) > 0:\n                loss_bid = F.smooth_l1_loss(input[batch_id][pos_index], target[batch_id][pos_index])\n            else:\n                loss_bid = torch.FloatTensor([0]).cuda()[0]\n            loss_all.append(loss_bid.mean())\n    final_loss = torch.stack(loss_all).mean()\n    return final_loss\n", "meta": {"hexsha": "830a08166d8ded8f5c09ff265b929c58b0ac576a", "size": 5312, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/loss.py", "max_stars_repo_name": "ArthurKeland/SiameseRPN-FPN", "max_stars_repo_head_hexsha": "e88744a6a8234d869a89f10cf992e6d02fcc8199", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-09-10T11:05:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T12:58:22.000Z", "max_issues_repo_path": "lib/loss.py", "max_issues_repo_name": "ArthurKeland/SiameseRPN-FPN", "max_issues_repo_head_hexsha": "e88744a6a8234d869a89f10cf992e6d02fcc8199", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/loss.py", "max_forks_repo_name": "ArthurKeland/SiameseRPN-FPN", "max_forks_repo_head_hexsha": "e88744a6a8234d869a89f10cf992e6d02fcc8199", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.7931034483, "max_line_length": 118, "alphanum_fraction": 0.5881024096, "include": true, "reason": "import numpy", "num_tokens": 1253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521307073646, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.15117075675508893}}
{"text": "import logging\nimport swisseph as swe\nimport sys\nimport traceback\nfrom math import floor, modf\n\nfrom sanskrit_data.schema import common\nfrom sanskrit_data.schema.common import JsonObject\nfrom scipy.optimize import brentq\n\nfrom jyotisha import names\nfrom jyotisha.custom_transliteration import revjul, tr\nfrom jyotisha.names.init_names_auto import init_names_auto\nfrom jyotisha.zodiac import get_planet_lon\n\nlogging.basicConfig(\n    level=logging.DEBUG,\n    format=\"%(levelname)s: %(asctime)s {%(filename)s:%(lineno)d}: %(message)s \"\n)\n\n\nNAMES = init_names_auto()\nMAX_DAYS_PER_YEAR = 366\nMAX_SZ = MAX_DAYS_PER_YEAR + 6  # plus one and minus one are usually necessary\nMIN_DAYS_NEXT_ECLIPSE = 25\nTITHI = {'id': 'TITHI', 'arc_len': 360.0 / 30.0, 'w_moon': 1, 'w_sun': -1}\nTITHI_PADA = {'id': 'TITHI_PADA', 'arc_len': 360.0 /\n              120.0, 'w_moon': 1, 'w_sun': -1}\nNAKSHATRAM = {'id': 'NAKSHATRAM',\n              'arc_len': 360.0 / 27.0, 'w_moon': 1, 'w_sun': 0}\nNAKSHATRA_PADA = {'id': 'NAKSHATRA_PADA',\n                  'arc_len': 360.0 / 108.0, 'w_moon': 1, 'w_sun': 0}\nRASHI = {'id': 'RASHI', 'arc_len': 360.0 / 12.0, 'w_moon': 1, 'w_sun': 0}\nYOGA = {'id': 'YOGA', 'arc_len': 360.0 / 27.0, 'w_moon': 1, 'w_sun': 1}\nKARANAM = {'id': 'KARANAM', 'arc_len': 360.0 / 60.0, 'w_moon': 1, 'w_sun': -1}\nSOLAR_MONTH = {'id': 'SOLAR_MONTH',\n               'arc_len': 360.0 / 12.0, 'w_moon': 0, 'w_sun': 1}\nSOLAR_NAKSH = {'id': 'SOLAR_NAKSH',\n               'arc_len': 360.0 / 27.0, 'w_moon': 0, 'w_sun': 1}\nSOLAR_NAKSH_PADA = {'id': 'SOLAR_NAKSH_PADA',\n                    'arc_len': 360.0 / 108.0, 'w_moon': 0, 'w_sun': 1}\nTYAJYAM_SPANS_REL = [51, 25, 31, 41, 15, 22, 31, 21, 33,\n                     31, 21, 19, 22, 21, 15, 15, 11, 15,\n                     57, 25, 21, 11, 11, 19, 17, 25, 31]\nAMRITA_SPANS_REL = [43, 49, 55, 53, 39, 36, 55, 45, 57,\n                    55, 45, 43, 46, 45, 39, 39, 35, 39,\n                    45, 49, 45, 35, 35, 43, 41, 49, 55]\nAMRITADI_YOGA = [[None, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 0, 0, 1, 1, 2, 2, 2, 0, 1, 0, 0, 2, 1, 1, 0, 0],\n                 [None, 1, 1, 2, 0, 0, 1, 0, 1, 1, 2, 1, 1, 1,\n                     1, 0, 2, 1, 1, 1, 1, 2, 0, 1, 1, 2, 1, 1],\n                 [None, 1, 1, 1, 0, 1, 2, 1, 1, 1, 1, 1, 0, 1,\n                     1, 1, 2, 1, 1, 0, 1, 1, 1, 1, 2, 2, 0, 1],\n                 [None, 2, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 2,\n                     1, 1, 1, 1, 1, 2, 0, 0, 1, 2, 1, 0, 1, 2],\n                 [None, 0, 1, 2, 2, 2, 2, 0, 0, 1, 0, 1, 2, 1,\n                     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1],\n                 [None, 0, 1, 1, 2, 1, 1, 1, 2, 2, 2, 1, 1, 0,\n                     1, 1, 1, 1, 2, 0, 1, 1, 2, 1, 1, 1, 1, 0],\n                 [None, 1, 1, 0, 0, 1, 1, 1, 1, 2, 0, 1, 2, 2, 2, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 2, 1, 2]]\nAMRITADI_YOGA_NAMES = {1: 'siddha', 0: 'amRta', 2: 'maraNa'}\nfor i in range(7):\n    AMRITADI_YOGA[i] = [AMRITADI_YOGA_NAMES.get(\n        n, n) for n in AMRITADI_YOGA[i]]\n\n\nclass Time(JsonObject):\n\n    \"\"\"This  class is a time class with methods for printing, conversion etc.\n    \"\"\"\n\n    def __init__(self, t):\n        super().__init__()\n        if type(t) == float or type(t) == int:\n            self.t = t\n        else:\n            raise(TypeError('Input to time class must be int or float!'))\n\n    def toString(self, default_suffix='', format='hh:mm', rounding=False):\n        if self.t < 0:\n            logging.error('t<0! %s ' % self.t)\n            logging.error(traceback.print_stack())\n\n        msec, secs = modf(self.t * 3600)\n        msec = round(msec * 1000)\n        if msec == 1000:\n            msec = 0\n            secs += 1\n\n        hour = secs // 3600\n        secs = secs % 3600\n\n        suffix = default_suffix\n        if format[-1] == '*':\n            if hour >= 24:\n                suffix = '*'\n        else:\n            if hour >= 24:\n                hour -= 24\n                suffix = '(+1)'  # Default notation for times > 23:59\n\n        minute = secs // 60\n        secs = secs % 60\n        second = secs\n\n        if format in ('hh:mm', 'hh:mm*'):\n            # Rounding done if 30 seconds have elapsed\n            return '%02d:%02d%s' % (hour, minute + ((secs + (msec >= 500)) >= 30) * rounding, suffix)\n        elif format in ('hh:mm:ss', 'hh:mm:ss*'):\n            # Rounding done if 500 milliseconds have elapsed\n            return '%02d:%02d:%02d%s' % (hour, minute, second + (msec >= 500) * rounding, suffix)\n        elif format in ('hh:mm:ss.sss', 'hh:mm:ss.sss*'):\n            return '%02d:%02d:%02d.%03d%s' % (hour, minute, second, msec, suffix)\n        elif format == 'gg-pp':  # ghatika-pal\n            secs = round(self.t * 3600)\n            gg = secs // 1440\n            secs = secs % 1440\n            pp = secs // 24\n            return ('%d-%d' % (gg, pp))\n        elif format == 'gg-pp-vv':  # ghatika-pal-vipal\n            vv_tot = round(self.t * 3600 / 0.4)\n            logging.debug(vv_tot)\n            vv = vv_tot % 60\n            logging.debug(vv)\n            vv_tot = (vv_tot - vv) // 60\n            logging.debug(vv_tot)\n            pp = vv_tot % 60\n            logging.debug(pp)\n            vv_tot = (vv_tot - pp) // 60\n            logging.debug(vv_tot)\n            gg = vv_tot\n            logging.debug(gg)\n            return ('%d-%d-%d' % (gg, pp, vv))\n        else:\n            raise Exception(\"\"\"Unknown format\"\"\")\n\n    def __str__(self):\n        return self.toString(format='hh:mm:ss')\n\n\ndef get_nakshatram(jd, ayanamsha_id=swe.SIDM_LAHIRI):\n    \"\"\"Returns the nakshatram prevailing at a given moment\n\n    Nakshatram is computed based on the longitude of the Moon; in\n    addition, to obtain the absolute value of the longitude, the\n    ayanamsa is required to be subtracted.\n\n    Args:\n      float jd, the Julian day\n\n    Returns:\n      int nakShatram, where 1 stands for Ashwini, ..., 14 stands\n      for Chitra, ..., 27 stands for Revati\n\n    Examples:\n      >>> get_nakshatram(2444961.7125)\n      16\n    \"\"\"\n\n    return get_angam(jd, NAKSHATRAM, ayanamsha_id=ayanamsha_id)\n\n\ndef get_yoga(jd, ayanamsha_id=swe.SIDM_LAHIRI):\n    \"\"\"Returns the yoha prevailing at a given moment\n\n    Yoga is computed based on the longitude of the Moon and longitude of\n    the Sun; in addition, to obtain the absolute value of the longitude, the\n    ayanamsa is required to be subtracted (for each).\n\n    Args:\n      float jd, the Julian day\n\n    Returns:\n      int yoga, where 1 stands for Vishkambha and 27 stands for Vaidhrti\n\n    Examples:\n      >>> get_yoga(2444961.7125)\n      8\n    \"\"\"\n\n    return get_angam(jd, YOGA, ayanamsha_id=ayanamsha_id)\n\n\ndef get_solar_rashi(jd, ayanamsha_id=swe.SIDM_LAHIRI):\n    \"\"\"Returns the solar rashi prevailing at a given moment\n\n    Solar month is computed based on the longitude of the sun; in\n    addition, to obtain the absolute value of the longitude, the\n    ayanamsa is required to be subtracted.\n\n    Args:\n      float jd, the Julian day\n\n    Returns:\n      int rashi, where 1 stands for mESa, ..., 12 stands for mIna\n\n    Examples:\n      >>> get_solar_rashi(2444961.7125)\n      9\n    \"\"\"\n\n    return get_angam(jd, SOLAR_MONTH, ayanamsha_id=ayanamsha_id)\n\n\ndef get_angam_float(jd, angam_type, offset=0, ayanamsha_id=swe.SIDM_LAHIRI, debug=False):\n    \"\"\"Returns the angam\n\n      Args:\n        float jd: The Julian Day at which the angam is to be computed\n        angam_type: One of the pre-defined constants in the panchangam\n        class, such as TITHI, NAKSHATRAM, YOGA, KARANAM or SOLAR_MONTH\n\n      Returns:\n        float angam\n\n      Examples:\n        >>> get_angam_float(2444961.7125,NAKSHATRAM)\n        15.967801358055189\n    \"\"\"\n    swe.set_sid_mode(ayanamsha_id)\n    w_moon = angam_type['w_moon']\n    w_sun = angam_type['w_sun']\n    arc_len = angam_type['arc_len']\n\n    lcalc = 0  # computing weighted longitudes\n    if debug:\n        logging.debug('## get_angam_float(): jd=%f', jd)\n        logging.debug(\"Ayanamsha: %f\", swe.get_ayanamsa(jd))\n\n    #  Get the lunar longitude, starting at the ayanaamsha point in the ecliptic.\n    if w_moon != 0:\n        lmoon = (swe.calc_ut(jd, swe.MOON)[0][0] - swe.get_ayanamsa(jd)) % 360\n        if (debug):\n            logging.debug(\"Moon longitude: %f\",\n                          swe.calc_ut(jd, swe.MOON)[0][0])\n            logging.debug('## get_angam_float(): lmoon=%f', lmoon)\n        lcalc += w_moon * lmoon\n\n    #  Get the solar longitude, starting at the ayanaamsha point in the ecliptic.\n    if w_sun != 0:\n        lsun = (swe.calc_ut(jd, swe.SUN)[0][0] - swe.get_ayanamsa(jd)) % 360\n        if(debug):\n            logging.debug('## get_angam_float(): lsun=%f', lsun)\n        lcalc += w_sun * lsun\n\n    if debug:\n        logging.debug('## get_angam_float(): lcalc=%f', lcalc)\n\n    lcalc = lcalc % 360\n\n    if debug:\n        logging.debug('## get_angam_float(): lcalc %% 360=%f', lcalc)\n        logging.debug(\"offset: %f\", offset)\n        logging.debug(offset + int(360.0 / arc_len))\n\n    if offset + int(360.0 / arc_len) == 0 and lcalc < arc_len:\n        # Angam 1 -- needs different treatment, because of 'discontinuity'\n        return (lcalc / arc_len)\n    else:\n        return (lcalc / arc_len) + offset\n\n\ndef get_planet_next_transit(jd_start, jd_end, planet, ayanamsha_id=swe.SIDM_LAHIRI):\n    \"\"\"Returns the next transit of the given planet e.g. swe.JUPITER\n\n      Args:\n        float jd_start, jd_end: The Julian Days between which transits must be computed\n        int planet  - e.g. swe.SUN, swe.JUPITER, ...\n\n      Returns:\n        List of tuples [(float jd_transit, int old_rashi, int new_rashi)]\n\n      Examples:\n      >>> get_planet_next_transit(2457755, 2458120, swe.JUPITER)\n      [(2458008.5710764076, 6, 7)]\n    \"\"\"\n    swe.set_sid_mode(ayanamsha_id)\n\n    transits = []\n    MIN_JUMP = 15  # Random check for a transit every 15 days!\n    # Could be tweaked based on planet using a dict?\n\n    curr_L_bracket = jd_start\n    curr_R_bracket = jd_start + MIN_JUMP\n\n    while curr_R_bracket <= jd_end:\n        L_rashi = floor(get_planet_lon(curr_L_bracket, planet, offset=0,\n                                       ayanamsha_id=ayanamsha_id) / 30) + 1\n        R_rashi = floor(get_planet_lon(curr_R_bracket, planet, offset=0,\n                                       ayanamsha_id=ayanamsha_id) / 30) + 1\n\n        if L_rashi == R_rashi:\n            curr_R_bracket += MIN_JUMP\n            continue\n        else:\n            # We have bracketed a transit!\n            if L_rashi < R_rashi:\n                target = R_rashi\n            else:\n                # retrograde transit\n                target = L_rashi\n            try:\n                jd_transit = brentq(get_planet_lon, curr_L_bracket, curr_R_bracket,\n                                    args=(planet, (-target + 1) * 30, ayanamsha_id))\n                transits += [(jd_transit, L_rashi, R_rashi)]\n                curr_R_bracket += MIN_JUMP\n                curr_L_bracket = jd_transit + MIN_JUMP\n            except ValueError:\n                sys.stderr.write('Unable to compute transit of planet;\\\n                                 possibly could not bracket correctly!\\n')\n                return (None, None, None)\n\n    return transits\n\n\ndef get_angam(jd, angam_type, ayanamsha_id=swe.SIDM_LAHIRI):\n    \"\"\"Returns the angam prevailing at a particular time\n\n      Args:\n        float jd: The Julian Day at which the angam is to be computed\n        float arc_len: The arc_len for the corresponding angam\n\n      Returns:\n        int angam\n\n      Examples:\n      >>> get_angam(2444961.7125,NAKSHATRAM)\n      16\n\n      >>> get_angam(2444961.7125,TITHI)\n      28\n\n      >>> get_angam(2444961.7125,YOGA)\n      8\n\n      >>> get_angam(2444961.7125,KARANAM)\n      55\n    \"\"\"\n    swe.set_sid_mode(ayanamsha_id)\n\n    return int(1 + floor(get_angam_float(jd, angam_type, ayanamsha_id=ayanamsha_id)))\n\n\ndef get_all_angas(jd, ayanamsha_id=swe.SIDM_LAHIRI):\n    anga_objects = [TITHI, TITHI_PADA, NAKSHATRAM, NAKSHATRA_PADA,\n                    RASHI, SOLAR_MONTH, SOLAR_NAKSH, YOGA, KARANAM]\n    angas = list(map(lambda anga_object: get_angam(\n        jd=jd, angam_type=anga_object, ayanamsha_id=ayanamsha_id), anga_objects))\n    anga_ids = list(map(lambda anga_obj: anga_obj[\"id\"], anga_objects))\n    return dict(list(zip(anga_ids, angas)))\n\n\ndef get_all_angas_x_ayanamshas(jd):\n    # swe.SIDM_TRUE_REVATI leads to a segfault.\n    ayanamshas = [swe.SIDM_LAHIRI, swe.SIDM_ARYABHATA, swe.SIDM_ARYABHATA_MSUN, swe.SIDM_KRISHNAMURTI, swe.SIDM_JN_BHASIN, swe.SIDM_RAMAN, swe.SIDM_SS_CITRA, swe.SIDM_SS_REVATI,\n                  swe.SIDM_SURYASIDDHANTA, swe.SIDM_SURYASIDDHANTA_MSUN, swe.SIDM_USHASHASHI, swe.SIDM_YUKTESHWAR, swe.SIDM_TRUE_CITRA, names.SIDM_TRUE_MULA, names.SIDM_TRUE_PUSHYA]\n\n    ayanamsha_names = list(\n        map(lambda ayanamsha: names.get_ayanamsha_name(ayanamsha), ayanamshas))\n    return dict(zip(ayanamsha_names, map(lambda ayanamsha_id: get_all_angas(jd=jd, ayanamsha_id=ayanamsha_id), ayanamshas)))\n\n\ndef print_angas_x_ayanamshas(jd):\n    anga_x_ayanamsha = get_all_angas_x_ayanamshas(jd=jd)\n    import pandas\n    angas_df = pandas.DataFrame(anga_x_ayanamsha)\n    print(angas_df.to_csv(sep=\"\\t\"))\n\n\ndef get_angam_span(jd1, jd2, angam_type, target, ayanamsha_id=swe.SIDM_LAHIRI, debug=False):\n    \"\"\"Computes angam spans for angams such as tithi, nakshatram, yoga\n        and karanam.\n\n        Args:\n          jd1: return the first span that starts after this date\n          jd2: return the first span that ends before this date\n          angam_type: TITHI, NAKSHATRAM, YOGA, KARANAM, SOLAR_MONTH, SOLAR_NAKSH\n\n        Returns:\n          tuple: A tuple of start and end times that lies within jd1 and jd2\n    \"\"\"\n\n    angam_start = angam_end = None\n\n    if debug:\n        logging.debug(get_angam(jd1, angam_type, ayanamsha_id=ayanamsha_id))\n        logging.debug(get_angam(jd2, angam_type, ayanamsha_id=ayanamsha_id))\n\n    num_angas = int(360.0 / angam_type['arc_len'])\n\n    jd_bracket_L = jd1\n    jd_bracket_R = jd2\n\n    h = 0.5   # Min Step for moving\n\n    jd_now = jd1\n    while jd_now < jd2 and angam_start is None:\n        angam_now = get_angam(jd_now, angam_type, ayanamsha_id=ayanamsha_id)\n\n        if debug:\n            logging.debug((jd_now, revjul(jd_now), angam_now, get_angam_float(\n                jd_now, angam_type, ayanamsha_id=ayanamsha_id)))\n        if angam_now < target or (target == 1 and angam_now == num_angas):\n            if debug:\n                logging.debug(('jd_bracket_L ', jd_now))\n            jd_bracket_L = jd_now\n        if angam_now == target:\n            try:\n                angam_start = brentq(get_angam_float, jd_bracket_L, jd_now,\n                                     args=(angam_type, -target + 1, ayanamsha_id, False))\n            except ValueError:\n                logging.error('Unable to bracket %s->%f between jd = (%f, %f), starting with (%f, %f)' %\n                              (str(angam_type), -target + 1, jd_bracket_L, jd_now, jd1, jd2))\n                angam_start = None\n            if debug:\n                logging.debug(('angam_start', angam_start))\n        # if angam_now > target and angam_start is not None:\n        #     angam_end = brentq(get_angam_float, angam_start, jd_now,\n        #                        args=(angam_type, -target, False))\n        jd_now += h\n\n    if angam_start is None:\n        return (None, None)  # If it doesn't start, we don't care if it ends!\n    jd_now = angam_start\n\n    while jd_now < jd2 and angam_end is None:\n        angam_now = get_angam(jd_now, angam_type, ayanamsha_id=ayanamsha_id)\n\n        if debug:\n            logging.debug((jd_now, revjul(jd_now), angam_now, get_angam_float(\n                jd_now, angam_type, ayanamsha_id=ayanamsha_id)))\n        if target == num_angas:\n            # Wait till we land at the next anga!\n            if angam_now == 1:\n                jd_bracket_R = jd_now\n                if debug:\n                    logging.debug(('jd_bracket_R ', jd_now))\n                break\n        else:\n            if angam_now > target:\n                jd_bracket_R = jd_now\n                if debug:\n                    logging.debug(('jd_bracket_R ', jd_now))\n                break\n        jd_now += h\n\n    try:\n        angam_end = brentq(get_angam_float, angam_start, jd_bracket_R,\n                           args=(angam_type, -target, ayanamsha_id, False))\n    except ValueError:\n        logging.error('Unable to compute angam_end (%s->%d); possibly could not bracket correctly!\\n' %\n                      (str(angam_type), target))\n\n    if debug:\n        logging.debug(('angam_end', angam_end))\n\n    return (angam_start, angam_end)\n\n\ndef get_angam_data(jd_sunrise, jd_sunrise_tmrw, angam_type, ayanamsha_id=swe.SIDM_LAHIRI):\n    \"\"\"Computes angam data for angams such as tithi, nakshatram, yoga\n    and karanam.\n\n    Args:\n      angam_type: TITHI, NAKSHATRAM, YOGA, KARANAM, SOLAR_MONTH, SOLAR_NAKSH\n\n\n    Returns:\n      tuple: A tuple comprising\n        angam_sunrise: The angam that prevails as sunrise\n        angam_data: a list of (int, float) tuples detailing the angams\n        for the day and their end-times (Julian day)\n\n    Examples:\n      >>> get_angam_data(2444961.54042,2444962.54076,TITHI)\n      [(27, 2444961.599213231)]\n      >>> get_angam_data(2444961.54042,2444962.54076,NAKSHATRAM)\n      [(16, 2444961.7487953394)]\n      >>> get_angam_data(2444961.54042,2444962.54076,YOGA)\n      [(8, 2444962.1861976916)]\n      >>> get_angam_data(2444961.54042,2444962.54076,KARANAM)\n      [(54, 2444961.599213231), (55, 2444962.15444546)]\n    \"\"\"\n    swe.set_sid_mode(ayanamsha_id)\n\n    w_moon = angam_type['w_moon']\n    w_sun = angam_type['w_sun']\n    arc_len = angam_type['arc_len']\n\n    num_angas = int(360.0 / arc_len)\n\n    # Compute angam details\n    angam_now = get_angam(jd_sunrise, angam_type, ayanamsha_id=ayanamsha_id)\n    angam_tmrw = get_angam(jd_sunrise_tmrw, angam_type,\n                           ayanamsha_id=ayanamsha_id)\n\n    angams_list = []\n\n    num_angas_today = (angam_tmrw - angam_now) % num_angas\n\n    if num_angas_today == 0:\n        # The angam does not change until sunrise tomorrow\n        return [(angam_now, None)]\n    else:\n        lmoon = (swe.calc_ut(jd_sunrise, swe.MOON)[\n                 0][0] - swe.get_ayanamsa(jd_sunrise)) % 360\n\n        lsun = (swe.calc_ut(jd_sunrise, swe.SUN)[\n                0][0] - swe.get_ayanamsa(jd_sunrise)) % 360\n\n        lmoon_tmrw = (swe.calc_ut(jd_sunrise_tmrw, swe.MOON)[0][0] -\n                      swe.get_ayanamsa(jd_sunrise_tmrw)) % 360\n\n        lsun_tmrw = (swe.calc_ut(jd_sunrise_tmrw, swe.SUN)[0][0] -\n                     swe.get_ayanamsa(jd_sunrise_tmrw)) % 360\n\n        for i in range(num_angas_today):\n            angam_remaining = arc_len * (i + 1) - (((lmoon * w_moon +\n                                                     lsun * w_sun) % 360) % arc_len)\n\n            # First compute approximate end time by essentially assuming\n            # the speed of the moon and the sun to be constant\n            # throughout the day. Therefore, angam_remaining is computed\n            # just based on the difference in longitudes for sun and\n            # moon today and tomorrow.\n            approx_end = jd_sunrise + angam_remaining / (((lmoon_tmrw - lmoon) % 360) * w_moon +\n                                                         ((lsun_tmrw - lsun) % 360) * w_sun)\n\n            # Initial guess value for the exact end time of the angam\n            x0 = approx_end\n\n            # What is the target (next) angam? It is needed to be passed\n            # to get_angam_float for zero-finding. If the target angam\n            # is say, 12, then we need to subtract 12 from the value\n            # returned by get_angam_float, so that this function can be\n            # passed as is to a zero-finding method like brentq or\n            # newton. Since we have a good x0 guess, it is easy to\n            # bracket the function in an interval where the function\n            # changes sign. Therefore, brenth can be used, as suggested\n            # in the scipy documentation.\n            target = (angam_now + i - 1) % num_angas + 1\n\n            # Approximate error in calculation of end time -- arbitrary\n            # used to bracket the root, for brenth\n            TDELTA = 0.05\n            try:\n                t_act = brentq(get_angam_float, x0 - TDELTA, x0 + TDELTA,\n                               args=(angam_type, -target, ayanamsha_id, False))\n            except ValueError:\n                logging.warning(\n                    'Unable to bracket! Using approximate t_end itself.')\n                logging.warning(locals())\n                t_act = approx_end\n            angams_list.extend([((angam_now + i - 1) % num_angas + 1, t_act)])\n    return angams_list\n\n\ndef get_ekadashi_name(paksha, lmonth):\n    \"\"\"Return the name of an ekadashi\n    \"\"\"\n    if paksha == 'shukla':\n        if lmonth == int(lmonth):\n            return '%s-EkAdazI' % NAMES['SHUKLA_EKADASHI_NAMES']['hk'][lmonth]\n        else:\n            # adhika mAsam\n            return '%s-EkAdazI' % NAMES['SHUKLA_EKADASHI_NAMES']['hk'][13]\n    elif paksha == 'krishna':\n        if lmonth == int(lmonth):\n            return '%s-EkAdazI' % NAMES['KRISHNA_EKADASHI_NAMES']['hk'][lmonth]\n        else:\n            # adhika mAsam\n            return '%s-EkAdazI' % NAMES['KRISHNA_EKADASHI_NAMES']['hk'][13]\n\n\ndef get_chandra_masa(month, NAMES, script, visarga=True):\n    if visarga:\n        if month == int(month):\n            return NAMES['CHANDRA_MASA_NAMES'][script][month]\n        else:\n            return '%s-(%s)' % (NAMES['CHANDRA_MASA_NAMES'][script][int(month) + 1], tr('adhikaH', script, titled=False))\n    else:\n        if month == int(month):\n            return NAMES['CHANDRA_MASA_NAMES'][script][month][:-1]\n        else:\n            return '%s-(%s)' % (NAMES['CHANDRA_MASA_NAMES'][script][int(month) + 1][:-1], tr('adhika', script, titled=False))\n\n\ndef get_tithi(jd, ayanamsha_id=swe.SIDM_LAHIRI):\n    \"\"\"Returns the tithi prevailing at a given moment\n\n    Tithi is computed as the difference in the longitudes of the moon\n    and sun at any given point of time. Therefore, even the ayanamsha\n    does not matter, as it gets cancelled out.\n\n    Args:\n      float jd, the Julian day\n\n    Returns:\n      int tithi, where 1 stands for ShuklapakshaPrathama, ..., 15 stands\n      for Paurnamasi, ..., 23 stands for KrishnapakshaAshtami, 30 stands\n      for Amavasya\n\n    Examples:\n      >>> get_tithi(2444961.7125)\n      28\n    \"\"\"\n\n    return get_angam(jd, TITHI, ayanamsha_id=ayanamsha_id)\n\n\ndef get_kaalas(start_span, end_span, part_start, num_parts):\n    \"\"\"Compute kaalas in a given span with specified fractions\n\n    Args:\n      :param start_span float (jd)\n      :param end_span float (jd)\n      int part_start\n      int num_parts\n\n    Returns:\n       tuple (start_time_jd, end_time_jd)\n\n    Examples:\n\n    \"\"\"\n    start_fraction = part_start / num_parts\n    end_fraction = (part_start + 1) / num_parts\n\n    start_time = start_span + (end_span - start_span) * start_fraction\n    end_time = start_span + (end_span - start_span) * end_fraction\n\n    return (start_time, end_time)\n\n\ndef sanitize_time(year_in, month_in, day_in, hour_in, minute_in, second_in):\n    (year, month, day, hour, minute, second) = (\n        year_in, month_in, day_in, hour_in, minute_in, second_in)\n    if second >= 60:\n        minute = minute + second / 60\n        second = second % 60\n    if minute >= 60:\n        hour = hour + minute / 60\n        minute = minute % 60\n    if hour >= 24:\n        day = day + hour / 24\n        hour = hour % 24\n    from calendar import monthrange\n    (_, final_day) = monthrange(year, month)\n    if day > final_day:\n        assert day == final_day + 1, \"range not supported by this function\"\n        day = 1\n        month = month + 1\n    if month >= 13:\n        year = year + (month - 1) / 12\n        month = ((month - 1) % 12) + 1\n    return (year, month, day, hour, minute, second)\n\n\n# Essential for depickling to work.\ncommon.update_json_class_index(sys.modules[__name__])\n# logging.debug(common.json_class_index)\n", "meta": {"hexsha": "dbf3b2535612c6c34e80707eab9ba56bf74e2fd0", "size": 24027, "ext": "py", "lang": "Python", "max_stars_repo_path": "jyotisha/panchangam/temporal/__init__.py", "max_stars_repo_name": "hareeshbabu82ns/jyotisha", "max_stars_repo_head_hexsha": "45ac19e999174cb64c239c1e4ccfb33bc5424137", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jyotisha/panchangam/temporal/__init__.py", "max_issues_repo_name": "hareeshbabu82ns/jyotisha", "max_issues_repo_head_hexsha": "45ac19e999174cb64c239c1e4ccfb33bc5424137", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jyotisha/panchangam/temporal/__init__.py", "max_forks_repo_name": "hareeshbabu82ns/jyotisha", "max_forks_repo_head_hexsha": "45ac19e999174cb64c239c1e4ccfb33bc5424137", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3494704992, "max_line_length": 181, "alphanum_fraction": 0.5902942523, "include": true, "reason": "from scipy", "num_tokens": 7626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.29746995506106744, "lm_q1q2_score": 0.1510587724466118}}
{"text": "# Copyright (c) 2011-2014 by California Institute of Technology\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n#    notice, this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n#    notice, this list of conditions and the following disclaimer in the\n#    documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the California Institute of Technology nor\n#    the names of its contributors may be used to endorse or promote\n#    products derived from this software without specific prior\n#    written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL CALTECH\n# OR THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n# SUCH DAMAGE.\n#\n\"\"\"\nClasses representing hybrid dynamical systems.\n\"\"\"\nfrom __future__ import absolute_import\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nfrom warnings import warn\nimport itertools\nfrom pprint import pformat\n\nimport numpy as np\nimport polytope as pc\n\n# inline imports:\n#\n# from tulip.graphics import newax, quiver\n\ndef _indent(s, n):\n    s = s.split('\\n')\n    w = n*' '\n    return w + ('\\n'+w).join(s)\n\nclass LtiSysDyn(object):\n    r\"\"\"Represent discrete-time continuous-state dynamics::\n\n        s[t+1] = A*s[t] + B*u[t] + E*d[t] + K\n\n    subject to the constraints::\n\n        u[t] \\in Uset\n        d[t] \\in Wset\n        s[t] \\in domain\n\n    where:\n        - u[t] the control input\n        - d[t] the disturbance input\n        - s[t] the system state\n\n    A LtiSysDyn object contains the fields:\n\n        - A, B, E, K, (matrices)\n        - Uset, Wset, (each a C{polytope.Polytope})\n        - domain (C{polytope.Polytope} or C{polytope.Region})\n        - time_semantics: 'discrete' (if system is originally a discrete-time\n          system) or 'sampled' (if system is sampled from a continuous-time\n          system)\n        - timestep: A positive real number containing the timestep (for sampled\n          system)\n\n    as defined above.\n\n    Note\n    ====\n    For state-dependent bounds on the input,::\n        [u[t]; s[t]] \\in Uset\n    can be used.\n\n    See Also\n    ========\n    L{PwaSysDyn}, L{SwitchedSysDyn}, C{polytope.Polytope}\n    \"\"\"\n    def __init__(self, A=None, B=None, E=None, K=None,\n                 Uset=None,Wset=None, domain=None, time_semantics=None,\n                 timestep=None):\n\n        if Uset is None:\n            warn('Uset not given to LtiSysDyn()')\n        elif not isinstance(Uset, pc.Polytope):\n            raise Exception('`Uset` has to be a Polytope')\n        if domain is None:\n            warn(\"Domain not given to LtiSysDyn()\")\n        if ((domain is not None) and\n            (not (isinstance(domain, pc.Polytope) or\n                isinstance(domain, pc.Region))\n            )\n        ):\n            raise Exception('`domain` has to be a Polytope or Region')\n\n        # check dimensions agree\n        try:\n            nA, mA = A.shape\n        except:\n            raise TypeError('A matrix must be 2d array')\n        if nA != mA:\n            raise ValueError('A must be square')\n        if domain is not None:\n            if domain.dim != mA:\n                raise Exception('domain.dim != A.size[1]')\n\n        if B is not None:\n            try:\n                nB, mB = B.shape\n            except:\n                raise TypeError('B matrix must be 2d array')\n            if nA != nB:\n                raise ValueError('A and B must have same number of rows')\n            if Uset is not None:\n                if (Uset.dim != mB) and (Uset.dim != mB + nA):\n                    msg = 'Uset.dim != B.size[1]'\n                    msg += ' and != B.size[1] + A.size[1]'\n                    raise Exception(msg)\n\n        if E is not None:\n            try:\n                nE, mE = E.shape\n            except:\n                raise TypeError('E matrix must be 2d array')\n            if nA != nE:\n                raise ValueError('A and E must have same number of rows')\n            if Wset is not None:\n                if Wset.dim != mE:\n                    raise Exception('Wset.dim != E.size[1]')\n\n        if K is not None:\n            try:\n                nK, mK = K.shape\n            except:\n                raise TypeError('K column vector must be 2d array')\n\n            if nA != nK:\n                raise ValueError('A and K must have same number of rows')\n            if mK != 1:\n                raise ValueError('K must be a column vector')\n\n        self.A = A\n        self.B = B\n\n        if K is None:\n            if len(A) != 0:\n                self.K = np.zeros([mA, 1])\n            else:\n                self.K = K\n        else:\n            self.K = K.reshape(K.size,1)\n\n        if E is None and (len(A) != 0):\n            self.E = np.zeros([mA, 1])\n            self.Wset = pc.Polytope()\n        else:\n            self.E = E\n            self.Wset = Wset\n\n        self.Uset = Uset\n        self.domain = domain\n\n        # Check that timestep and semantics are valid.\n        _check_time_data(time_semantics, timestep)\n        self.time_semantics = time_semantics\n        self.timestep = timestep\n\n\n    def __str__(self):\n        n = 3\n        output = 'A =\\n' + _indent(str(self.A), n)\n        output += '\\nB =\\n' + _indent(str(self.B), n)\n        output += '\\nE =\\n' + _indent(str(self.E), n)\n        output += '\\nK =\\n' + _indent(str(self.K), n)\n        output += '\\nUset =\\n' + _indent(str(self.Uset), n)\n        output += '\\nWset =\\n' + _indent(str(self.Wset), n)\n        return output\n\n    def plot(self, ax=None, color=np.random.rand(3), show_domain=True,\n             res=(5, 5), **kwargs):\n        try:\n            from tulip.graphics import newax, quiver\n        except:\n            logger.error('failed to import graphics')\n            warn('pyvectorized not found. No plotting.')\n            return\n\n        (x, res) = pc.grid_region(self.domain, res=res)\n        n = self.A.shape[0]\n        DA = self.A - np.eye(n)\n        v = DA.dot(x) + self.K\n\n        if ax is None:\n            ax, fig = newax()\n\n        if show_domain:\n            self.domain.plot(ax, color)\n\n        quiver(x, v, ax, **kwargs)\n\n        return ax\n\nclass PwaSysDyn(object):\n    \"\"\"PwaSysDyn class for specifying a polytopic piecewise affine system.\n    A PwaSysDyn object contains the fields:\n\n      - C{list_subsys}: list of L{LtiSysDyn}\n\n      - C{domain}: domain over which piecewise affine system is defined,\n          type: polytope.Polytope or polytope.Region\n\n      - C{time_semantics}: 'discrete' (if system is originally a discrete-time\n       system) or 'sampled' (if system is sampled from a continuous-time\n       system)\n\n      - C{timestep}: A positive real number containing the timestep (for sampled\n        systems)\n\n    For the system to be well-defined the domains of its subsystems should be\n    mutually exclusive (modulo intersections with empty interior) and cover the\n    domain.\n\n    See Also\n    ========\n    L{LtiSysDyn}, L{SwitchedSysDyn}, C{polytope.Polytope}\n    \"\"\"\n    def __init__(self, list_subsys=[], domain=None, time_semantics=None,\n                 timestep=None, overwrite_time=True):\n        \"\"\"\n        @type overwrite_time: bool\n        @param overwrite_time: If true, then overwrites any time data in the\n                               objects in C{list_subsys} with the data in\n                               C{time_semantics} and C{timestep} variables.\n                               Otherwise checks that the time data of the\n                               objects in C{list_subsys} are consistent with\n                               C{time_semantics} and C{timestep}.\n        \"\"\"\n\n        if domain is None:\n            warn(\"Domain not given to PwaSysDyn()\")\n\n        if ((domain is not None) and\n            (not (isinstance(domain, pc.Polytope) or\n                isinstance(domain, pc.Region))\n            )\n        ):\n            raise Exception(\"PwaSysDyn: `domain` has to be a Polytope or Region\")\n\n        if len(list_subsys) > 0:\n            uncovered_dom = domain.copy()\n            n = list_subsys[0].A.shape[1]  # State space dimension\n            m = list_subsys[0].B.shape[1]  # Input space dimension\n            p = list_subsys[0].E.shape[1]  # Disturbance space dimension\n            for subsys in list_subsys:\n                uncovered_dom = uncovered_dom.diff(subsys.domain)\n                if (n!=subsys.A.shape[1] or m!=subsys.B.shape[1] or\n                    p!=subsys.E.shape[1]):\n                    raise Exception(\"PwaSysDyn: state, input, disturbance \" +\n                                    \"dimensions have to be the same for all \" +\n                                     \"subsystems\")\n            if not pc.is_empty(uncovered_dom):\n                raise Exception(\"PwaSysDyn: subdomains must cover the domain\")\n            for x in itertools.combinations(list_subsys, 2):\n                if pc.is_fulldim(x[0].domain.intersect(x[1].domain) ):\n                    raise Exception(\"PwaSysDyn: subdomains have to be mutually\"+\n                        \" exclusive\")\n\n        self.list_subsys = list_subsys\n        self.domain = domain\n\n        # Input time semantics\n        _check_time_data(time_semantics, timestep)\n        if overwrite_time:\n            _push_time_data(self.list_subsys, time_semantics, timestep)\n        else:\n            _check_time_consistency(list_subsys, time_semantics, timestep)\n        self.timestep = timestep\n        self.time_semantics = time_semantics\n\n\n    def __str__(self):\n        s = 'Piecewise-Affine System Dynamics\\n'\n        s += 30 * '-' + 2*'\\n'\n\n        s += 3*' ' + 'Domain:\\n\\n'\n        s += _indent(str(self.domain), n=6) + '\\n'\n\n        for i, sys in enumerate(self.list_subsys):\n            s += 3*' ' + 'Subsystem: ' + str(i) +'\\n'\n            s += _indent(str(sys), n=6)\n        return s\n\n    @classmethod\n    def from_lti(cls, A=[], B=[], E=[], K=[],\n                 Uset=None, Wset=None,domain=None):\n        lti_sys = LtiSysDyn(A,B,E,K,Uset,Wset,domain)\n        return cls([lti_sys], domain)\n\n    def plot(self, ax=None, show_domain=True, **kwargs):\n        try:\n            from tulip.graphics import newax\n        except:\n            logger.error('failed to import graphics')\n            return\n\n        if ax is None:\n            ax, fig = newax()\n\n        for subsystem in self.list_subsys:\n            subsystem.plot(ax, color=np.random.rand(3),\n                           show_domain=show_domain, **kwargs)\n        return ax\n\nclass SwitchedSysDyn(object):\n    \"\"\"Represent hybrid systems switching between dynamic modes.\n\n    A C{SwitchedSysDyn} represents a system with switching modes\n    that depend on both discrete:\n\n        - n_env environment variables (uncontrolled)\n        - n_sys system variables (controlled)\n\n    A C{SwitchedSysDyn} object contains the fields:\n\n     - C{disc_domain_size}: 2-tuple of numbers of modes\n       type: (n_env, n_sys)\n\n     - C{env_labels}: (optional) labels for discrete environment variables\n       type: list of len(n_env)\n       default: range(n_env)\n\n     - C{disc_sys_labels}: (optional) labels for discrete system variables\n       type: list of len(n_sys)\n       default: range(n_sys)\n\n     - C{dynamics}: mapping mode 2-tuples to active dynamics::\n\n         (env_label, sys_label) -> PwaSysDyn\n\n       type: dict\n       default: If no env_label or sys_label passed,\n       then default to int indices (i,j) L{PwaSysDyn}.\n\n     - C{cts_ss}: continuous state space over which hybrid system is defined.\n       type: C{polytope.Region}\n\n     - C{time_semantics}: 'discrete' (if system is originally a discrete-time\n       system) or 'sampled' (if system is sampled from a continuous-time\n       system)\n\n     - C{timestep}: A positive real number containing the timestep (for sampled\n       systems)\n\n\n    Note\n    ====\n    We assume that system and environment switching modes are\n    independent of one another.  (Use LTL statement to make it not so.)\n\n    See Also\n    ========\n    L{LtiSysDyn}, L{PwaSysDyn}, C{polytope.Region}\n    \"\"\"\n    def __init__(self, disc_domain_size=(1,1),\n                 dynamics=None, cts_ss=None,\n                 env_labels=None, disc_sys_labels=None, time_semantics=None,\n                 timestep=None, overwrite_time=True):\n        \"\"\"\n        @type overwrite_time: bool\n        @param overwrite_time: If true, then overwrites any time data in the\n                               objects in C{list_subsys} with the data in\n                               C{time_semantics} and C{timestep} variables.\n                               Otherwise checks that the time data of the\n                               objects in C{list_subsys} are consistent with\n                               C{time_semantics} and C{timestep}.\n        \"\"\"\n\n        # check that the continuous domain is specified\n        if cts_ss is None:\n            warn('continuous state space not given to SwitchedSysDyn')\n        else:\n            if not isinstance(cts_ss, (pc.Polytope, pc.Region) ):\n                raise Exception('SwitchedSysDyn: ' +\n                   '`cts_ss` must be a Polytope or Region')\n\n        self.disc_domain_size = disc_domain_size\n\n        # If label numbers agree with disc_domain_size, then use them.\n        # Otherwise, ignore the labels.\n        n_env, n_sys = disc_domain_size\n\n        self._env_labels = self._check_labels(n_env, env_labels)\n        self._disc_sys_labels = self._check_labels(n_sys, disc_sys_labels)\n\n        # Check each dynamics key is a valid mode,\n        # i.e., a valid combination of env and sys labels.\n        if dynamics is not None:\n            modes = self.all_mode_combs\n\n            undefined_modes = set(dynamics.keys()).difference(modes)\n\n            if undefined_modes:\n                msg = 'SwitchedSysDyn: `dynamics` keys inconsistent'\n                msg += ' with discrete mode labels.\\n'\n                msg += 'Undefined modes:\\n' + str(undefined_modes)\n                raise ValueError(msg)\n\n            missing_modes = set(modes).difference(dynamics.keys())\n\n            if missing_modes:\n                msg = 'Missing the modes:\\n' + str(missing_modes)\n                msg += '\\n Make sure you did not forget any modes,\\n'\n                msg += 'otherwise this is fine.'\n                warn(msg)\n\n            if not all([isinstance(sys, PwaSysDyn)\n                        for sys in dynamics.values()]):\n                msg = 'For each mode dynamics must be PwaSysDyn.\\n'\n                msg += 'Got instead: ' +str(type(sys))\n                raise Exception(msg)\n\n        self.dynamics = dynamics\n        self.cts_ss = cts_ss\n\n        _check_time_data(time_semantics, timestep)\n        if overwrite_time:\n            _push_time_data(self.dynamics.values(), time_semantics, timestep)\n        else:\n            _check_time_consistency(list(dynamics.values()), time_semantics, timestep)\n        self.timestep = timestep\n        self.time_semantics = time_semantics\n\n    def __str__(self):\n        n_env, n_sys = self.disc_domain_size\n\n        s = 'Hybrid System Dynamics\\n'\n        s += 30 * '-' + '\\n'\n\n        s += 'Modes:\\n'\n        s += 4*' ' + 'Environment (' + str(n_env) + ' modes):\\n'\n        s += 6*' ' + pformat(self.env_labels, indent=3) + 2*'\\n'\n        s += 4*' ' + 'System: (' + str(n_sys) + ' modes)\\n'\n        s += 6*' ' + pformat(self.disc_sys_labels, indent=3) + 2*'\\n'\n\n        s += 'Continuous State Space:\\n\\n'\n        s += _indent(str(self.cts_ss), 4) + '\\n'\n\n        s += 'Dynamics:\\n'\n        for mode, pwa in self.dynamics.items():\n            s += 4*' ' + 'mode: ' + str(mode) + '\\n'\n            s += 4*' ' + 'dynamics:\\n' + _indent(str(pwa), 8) +'\\n\\n'\n        return s\n\n    def _check_labels(self, n, labels):\n        # don't complain for default\n        if labels is None:\n            return None\n\n        # len exists ?\n        try:\n            # is len correct ?\n            if len(labels) != n:\n                msg = 'number of environment labels is inconsistent'\n                msg += ' with discrete domain size.\\n'\n                msg += 'Ignoring given environment labels.\\n'\n                msg += 'Defaulting to integer labels.'\n                warn(msg)\n\n                return None\n        except:\n            warn('Environment labels of type: ' +\n                 type(labels) + 'have no len()')\n            return None\n        return labels\n\n    @property\n    def all_mode_combs(self):\n        \"\"\"Return all possible combinations of modes.\n        \"\"\"\n        modes = [(a,b) for a in self.env_labels\n                           for b in self.disc_sys_labels]\n\n        logger.debug('Available modes: ' + str(modes) )\n        return modes\n\n    @property\n    def modes(self):\n        if self.dynamics is None:\n            warn('No dynamics defined (None).')\n            return None\n        return self.dynamics.keys()\n\n    @property\n    def env_labels(self):\n        if self._env_labels is None:\n            return range(self.disc_domain_size[0])\n        else:\n            return self._env_labels\n\n    @property\n    def disc_sys_labels(self):\n        if self._disc_sys_labels is None:\n            return range(self.disc_domain_size[1])\n        else:\n            return self._disc_sys_labels\n\n    @classmethod\n    def from_pwa(cls, list_subsys=[], domain=None):\n        pwa_sys = PwaSysDyn(list_subsys,domain)\n        return cls((1,1), {(0,0):pwa_sys}, domain)\n\n    @classmethod\n    def from_lti(cls, A=[], B=[], E=[], K=[],\n                 Uset=None, Wset=None,domain=None):\n        pwa_sys = PwaSysDyn.from_lti(A, B, E, K,\n                                     Uset, Wset, domain)\n        return cls((1,1), {(0,0):pwa_sys}, domain)\n\n\ndef _push_time_data(system_list, time_semantics, timestep):\n    \"\"\"Overwrite the time data in system list. Throws warnings if overwriting\n    existing data.\"\"\"\n\n    for system in system_list:\n        if (system.time_semantics != time_semantics) and (system.time_semantics\n            is not None):\n            warn('Overwriting existing time semantics data.')\n        if (system.timestep != timestep) and (system.timestep is not None):\n            warn('Overwriting existing timestep data.')\n        system.time_semantics = time_semantics\n        system.timestep = timestep\n\n        # Overwrite LTI in system if system is a PWA\n        if isinstance(system, PwaSysDyn):\n            _push_time_data(system.list_subsys, time_semantics, timestep)\n\n\n\ndef _check_time_data(semantics, timestep):\n    \"\"\"Checks that time semantics and timestep are correctly specified. Raises\n    ValueErrors if that's not the case.\n\n    @type semantics: string\n    @param timestep: any positive number\n    @type timestep: int or float\n\n    @rtype: None\n    \"\"\"\n\n    if semantics not in ['sampled', 'discrete', None]:\n        raise ValueError('Time semantics must be discrete or ' +\n            'sampled (sampled from continuous time system).')\n\n    if ((semantics == 'discrete') and (timestep is not None)):\n        raise ValueError('Discrete semantics must not have a timestep')\n\n    if timestep is not None:\n        error_string = 'Timestep must be a positive real number or unspecified.'\n        if timestep <= 0:\n            raise ValueError(error_string)\n        if not isinstance(timestep, (int, float)):\n            raise TypeError(error_string)\n\n\n\ndef _check_time_consistency(system_list, time_semantics, timestep):\n    \"\"\"Checks that all the dynamical systems in system_list have the same time\n    semantics and timestep. Raises ValueError if not the case.\n\n    @type system_list: list of L{LtiSysDyn} or L{PwaSysDyn}\n    @rtype: None\n    \"\"\"\n\n    # Check that time semantics for all subsystems match\n    for ind in range(len(system_list)-1):\n\n        if system_list[ind].timestep != system_list[ind+1].timestep:\n            raise ValueError('Not all timesteps in child systems are the same.')\n\n        if system_list[ind].time_semantics != system_list[ind+1].time_semantics:\n            raise ValueError('Not all time semantics are the same.')\n\n\n    # Check that time semantics for all subsystems match specified system and\n    # timestep\n    if system_list[0].timestep != timestep:\n        raise ValueError('Timestep of subsystems do not match specified ' +\n                         'timestep.')\n\n    if system_list[0].time_semantics != time_semantics:\n        raise ValueError('Time semantics of subsystems do not match ' +\n                         'specified time semantics.')\n", "meta": {"hexsha": "96727b54dcf266e80844bb7458ede11a8a426ea8", "size": 21238, "ext": "py", "lang": "Python", "max_stars_repo_path": "tulip/hybrid.py", "max_stars_repo_name": "Duckie-town-isu/tulip-control", "max_stars_repo_head_hexsha": "07de9f85591a36e9556c612a371e9c28693156d2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 91, "max_stars_repo_stars_event_min_datetime": "2015-01-28T10:18:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T16:37:32.000Z", "max_issues_repo_path": "tulip/hybrid.py", "max_issues_repo_name": "Duckie-town-isu/tulip-control", "max_issues_repo_head_hexsha": "07de9f85591a36e9556c612a371e9c28693156d2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 166, "max_issues_repo_issues_event_min_datetime": "2015-01-21T17:30:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T19:42:24.000Z", "max_forks_repo_path": "tulip/hybrid.py", "max_forks_repo_name": "Duckie-town-isu/tulip-control", "max_forks_repo_head_hexsha": "07de9f85591a36e9556c612a371e9c28693156d2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 34, "max_forks_repo_forks_event_min_datetime": "2015-08-25T01:04:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T19:35:59.000Z", "avg_line_length": 34.8163934426, "max_line_length": 86, "alphanum_fraction": 0.5835295226, "include": true, "reason": "import numpy", "num_tokens": 5048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.29746994883293104, "lm_q1q2_score": 0.15105876928389025}}
{"text": "\"\"\"\n\nSource.py\n\nAuthor: Jordan Mirocha\nAffiliation: University of Colorado at Boulder\nCreated on: Sun Jul 22 16:28:08 2012\n\nDescription: Initialize a radiation source.\n\n\"\"\"\nfrom __future__ import print_function\nimport re, os\nimport numpy as np\nfrom scipy.integrate import quad\nfrom ..util import ParameterFile\nfrom ..physics.Hydrogen import Hydrogen\nfrom ..physics.Cosmology import Cosmology\nfrom ..util.ParameterFile import ParameterFile\nfrom ..static.IntegralTables import IntegralTable\nfrom ..static.InterpolationTables import LookupTable\nfrom ..physics.Constants import erg_per_ev, E_LL, s_per_myr\nfrom ..util.SetDefaultParameterValues import SourceParameters, \\\n    CosmologyParameters\nfrom ..physics.CrossSections import PhotoIonizationCrossSection as sigma_E\n\ntry:\n    import h5py\nexcept ImportError:\n    pass\n\nnp.seterr(all='ignore')   # exp overflow occurs when integrating BB\n                          # will return 0 as it should for x large\n\nclass Source(object):\n    def __init__(self, grid=None, cosm=None, logN=None, init_tabs=True,\n        **kwargs):\n        \"\"\"\n        Initialize a radiation source object.\n\n        ..note:: This is inherited by all other ares.sources classes.\n\n        Parameters\n        ----------\n        grid: rt1d.static.Grid.Grid instance\n        logN: column densities over which to tabulate integral quantities\n\n        \"\"\"\n\n        self.pf = ParameterFile(**kwargs)\n        self._cosm_ = cosm\n\n        # Create lookup tables for integral quantities\n        if init_tabs and (grid is not None):\n            self._create_integral_table(logN=logN)\n\n    @property\n    def Emin(self):\n        return self.pf['source_Emin']\n    @property\n    def Emax(self):\n        return self.pf['source_Emax']\n\n    @property\n    def EminNorm(self):\n        if not hasattr(self, '_EminNorm'):\n            if self.pf['source_EminNorm'] == None:\n                self._EminNorm = self.pf['source_Emin']\n            else:\n                self._EminNorm = self.pf['source_EminNorm']\n\n        return self._EminNorm\n\n    @property\n    def EmaxNorm(self):\n        if not hasattr(self, '_EmaxNorm'):\n            if self.pf['source_EmaxNorm'] == None:\n                self._EmaxNorm = self.pf['source_Emax']\n            else:\n                self._EmaxNorm = self.pf['source_EmaxNorm']\n\n        return self._EmaxNorm\n\n    @property\n    def info(self):\n        \"\"\"\n        Print info like Nlw etc in various units!\n        \"\"\"\n        pass\n\n    @property\n    def is_delta(self):\n        return self.pf['source_sed'] == 'delta'\n\n    def SourceOn(self, t):\n        if t < self.tau:\n            return True\n        else:\n            return False\n\n    @property\n    def tau(self):\n        if not hasattr(self, '_tau'):\n            self._tau = self.pf['source_lifetime'] * s_per_myr\n        return self._tau\n\n    @property\n    def cosm(self):\n        if not hasattr(self, '_cosm'):\n            if self._cosm_ is not None:\n                self._cosm = self._cosm_\n            elif self.grid is not None:\n                self._cosm = self.grid.cosm\n            else:\n                self._cosm = Cosmology(pf=self.pf, **self.pf)\n\n        return self._cosm\n\n    @property\n    def multi_freq(self):\n        if not hasattr(self, '_multi_freq'):\n            self._multi_freq = self.discrete and not self.pf['source_multigroup']\n\n        return self._multi_freq\n\n    @property\n    def multi_group(self):\n        if not hasattr(self, '_multi_group'):\n            self._multi_group = self.discrete and self.pf['source_multigroup']\n\n        return self._multi_group\n\n    @property\n    def ionizing(self):\n        # See if source emits ionizing photons\n        # Should also be function of absorbers\n        if not hasattr(self, '_ionizing'):\n            self._ionizing = self.pf['source_Emax'] > E_LL\n\n        return self._ionizing\n\n    @property\n    def grid(self):\n        if not hasattr(self, '_grid'):\n            self._grid = None\n\n        return self._grid\n\n    @grid.setter\n    def grid(self, value):\n        self._grid = value\n\n    @property\n    def discrete(self):\n        if not hasattr(self, '_discrete'):\n            self._discrete = (self.pf['source_E'] != None) or \\\n                (self.pf['source_sed'] in ['eldridge2009', 'eldridge2017', \n                    'leitherer1999'])\n\n        return self._discrete\n\n    @property\n    def continuous(self):\n        if not hasattr(self, '_continuous'):\n            self._continuous = not self.discrete\n\n        return self._continuous\n\n    @property\n    def hydr(self):\n        if not hasattr(self, '_hydr'):\n            self._hydr = None\n\n        return self._hydr\n\n    @hydr.setter\n    def hydr(self, value):\n        self._hydr = value\n\n    @property\n    def frec(self):\n        \"\"\"\n        Compute average recycling fraction (i.e., spectrum-weighted frec).\n        \"\"\"\n\n        if self.hydr is None:\n            return None\n\n        n = np.arange(2, self.hydr.nmax)\n        En = np.array(list(map(self.hydr.ELyn, n)))\n        In = np.array(list(map(self.Spectrum, En))) / En\n        fr = np.array(list(map(self.hydr.frec, n)))\n\n        return np.sum(fr * In) / np.sum(In)\n\n    @property\n    def intrinsic_hardening(self):\n        if not hasattr(self, '_intrinsic_hardening'):\n            if 'source_hardening' in self.pf:\n                self._intrinsic_hardening = \\\n                    self.pf['source_hardening'] == 'intrinsic'\n            else:\n                self._intrinsic_hardening = False\n\n        return self._intrinsic_hardening\n\n    def _hardening_factor(self, E):\n        return np.exp(-10.**self.logN \\\n            * (sigma_E(E, 0) + self.cosm.y * sigma_E(E, 1)))\n\n    @property\n    def logN(self):\n        if not hasattr(self, '_logN'):\n            if 'source_logN' in self.pf:\n                self._logN = self.pf['source_logN']\n            else:\n                self._logN = -np.inf\n\n        return self._logN\n\n    @property\n    def sharp_points(self):\n        if not hasattr(self, '_sharp_points'):\n            if self.pf['source_sed_sharp_at'] is not None:\n                self._sharp_points = [self.pf['source_sed_sharp_at']]\n            else:\n                self._sharp_points = None\n\n        return self._sharp_points\n\n    @property\n    def _normL(self):\n        if not hasattr(self, '_normL_'):\n            if self.is_delta:\n                self._normL_ = 1. #/ self.pf['source_Emax']#/ self._Intensity(self.pf['source_Emax'])\n            elif self.pf['source_Enorm'] is not None:\n                En = self.pf['source_Enorm']\n\n                if self.intrinsic_hardening:\n                    self._normL_ = 1. / self._Intensity(En),\n                else:\n                    self._normL_ = 1. / (self._Intensity(En) / self._hardening_factor(En))\n            else:\n                if self.intrinsic_hardening:\n                    self._normL_ = 1. / quad(self._Intensity,\n                        self.pf['source_EminNorm'],\n                        self.pf['source_EmaxNorm'], points=self.sharp_points)[0]\n                else:\n                    integrand = lambda EE: self._Intensity(EE) / self._hardening_factor(EE)\n                    self._normL_ = 1. / quad(integrand,\n                        self.pf['source_EminNorm'],\n                        self.pf['source_EmaxNorm'], points=self.sharp_points)[0]\n\n        return self._normL_\n\n    #def _load_spectrum(self):\n    #    \"\"\" Modify a few parameters if spectrum_file provided. \"\"\"\n    #\n    #    fn = self.pf['spectrum_file']\n    #\n    #    if fn is None:\n    #        return\n    #\n    #    # Read spectrum - expect hdf5 with (at least) E, LE, and t datasets.\n    #    if re.search('.hdf5', fn):\n    #        f = h5py.File(fn)\n    #        try:\n    #            self.pf['tables_times'] = f['t'].value\n    #        except:\n    #            self.pf['tables_times'] = None\n    #            self.pf['spectrum_evolving'] = False\n    #\n    #        self.pf['spectrum_E'] = f['E'].value\n    #        self.pf['spectrum_LE'] = f['LE'].value\n    #        f.close()\n    #\n    #        if len(self.pf['spectrum_LE'].shape) > 1 \\\n    #            and not self.pf['spectrum_evolving']:\n    #            self.pf['spectrum_LE'] = self.pf['spectrum_LE'][0]\n    #    else:\n    #        spec = readtab(fn)\n    #        if len(spec) == 2:\n    #            self.pf['spectrum_E'], self.pf['spectrum_LE'] = spec\n    #        else:\n    #            self.pf['spectrum_E'], self.pf['spectrum_LE'], \\\n    #                self.pf['spectrum_t'] = spec\n\n    @property\n    def tables(self):\n        if not hasattr(self, '_tables'):\n            self._create_integral_table()\n        return self._tables\n\n    @property\n    def tab(self):\n        if not hasattr(self, '_tab'):\n            self._create_integral_table()\n        return self._tab\n\n    @property\n    def tabs(self):\n        if not hasattr(self, '_tabs'):\n            self._create_integral_table()\n        return self._tabs\n\n    def _create_integral_table(self, logN=None):\n        \"\"\"\n        Take tables and create interpolation functions.\n        \"\"\"\n\n        if self.discrete:\n            return\n\n        if self._name == 'diffuse':\n            return\n\n        if self.pf['source_table'] is None:\n            # Overide defaults if supplied - this is dangerous\n            if logN is not None:\n                self.pf.update({'tables_dlogN': [np.diff(tmp) for tmp in logN]})\n                self.pf.update({'tables_logNmin': [np.min(tmp) for tmp in logN]})\n                self.pf.update({'tables_logNmax': [np.max(tmp) for tmp in logN]})\n\n            # Tabulate away!\n            self._tab = IntegralTable(self.pf, self, self.grid, logN)\n            self._tabs = self.tab.TabulateRateIntegrals()\n        else:\n            self._tab = IntegralTable(self.pf, self, self.grid, logN)\n            self._tabs = self.tab.load(self.pf['source_table'])\n\n        self._setup_interp()\n\n    def _setup_interp(self):\n        self._tables = {}\n        for tab in self.tabs:\n            self._tables[tab] = \\\n                LookupTable(self.pf, tab, self.tab.logN, self.tabs[tab],\n                    self.tab.logx, self.tab.t)\n\n    @property\n    def sigma(self):\n        \"\"\"\n        Compute bound-free absorption cross-section for all frequencies.\n        \"\"\"\n        if not self.discrete:\n            return None\n        if not hasattr(self, '_sigma_all'):\n            self._sigma_all = np.array(list(map(sigma_E, self.E)))\n\n        return self._sigma_all\n\n    def Qdot(self, t=None):\n        \"\"\"\n        Returns number of photons emitted (s^-1) at all frequencies.\n        \"\"\"\n        #if not hasattr(self, '_Qdot_all'):\n        self._Qdot_all = self.Lbol(t) * self.LE / self.E / erg_per_ev\n\n        return self._Qdot_all\n\n    def hnu_bar(self, t=0):\n        \"\"\"\n        Average ionizing (per absorber) photon energy in eV.\n        \"\"\"\n        if not hasattr(self, '_hnu_bar_all'):\n            self._hnu_bar_all = {}\n        if not hasattr(self, '_qdot_bar_all'):\n            self._qdot_bar_all = {}\n\n        if t in self._hnu_bar_all:\n            return self._hnu_bar_all[t]\n\n        self._hnu_bar_all[t] = np.zeros_like(self.grid.zeros_absorbers)\n        self._qdot_bar_all[t] = np.zeros_like(self.grid.zeros_absorbers)\n        for i, absorber in enumerate(self.grid.absorbers):\n            self._hnu_bar_all[t][i], self._qdot_bar_all[t][i] = \\\n                self._FrequencyAveragedBin(absorber=absorber, t=t)\n\n        return self._hnu_bar_all\n\n    def AveragePhotonEnergy(self, Emin, Emax):\n        \"\"\"\n        Return average photon energy in supplied band.\n        \"\"\"\n\n        integrand = lambda EE: self.Spectrum(EE) * EE\n        norm = lambda EE: self.Spectrum(EE)\n\n        return quad(integrand, Emin, Emax, points=self.sharp_points)[0] \\\n             / quad(norm, Emin, Emax, points=self.sharp_points)[0]\n\n    @property\n    def qdot_bar(self):\n        \"\"\"\n        Average ionizing photon luminosity (per absorber) in s^-1.\n        \"\"\"\n        if not hasattr(self, '_qdot_bar_all'):\n            hnu_bar = self.hnu_bar\n\n        return self._qdot_bar_all\n\n    def erg_per_phot(self, Emin, Emax):\n        return self.eV_per_phot(Emin, Emax) * erg_per_ev\n\n    def eV_per_phot(self, Emin, Emax):\n        \"\"\"\n        Compute the average energy per photon (in eV) in some band.\n        \"\"\"\n\n        i1 = lambda E: self.Spectrum(E)\n        i2 = lambda E: self.Spectrum(E) / E\n\n        # Must convert units\n        final = quad(i1, Emin, Emax, points=self.sharp_points)[0] \\\n              / quad(i2, Emin, Emax, points=self.sharp_points)[0]\n\n        return final\n\n    @property\n    def sigma_bar(self):\n        \"\"\"\n        Frequency averaged cross section (single bandpass).\n        \"\"\"\n        if not hasattr(self, '_sigma_bar_all'):\n            self._sigma_bar_all = np.zeros_like(self.grid.zeros_absorbers)\n            for i, absorber in enumerate(self.grid.absorbers):\n                integrand = lambda x: self.Spectrum(x) \\\n                    * self.grid.bf_cross_sections[absorber](x) / x\n\n                self._sigma_bar_all[i] = self.Lbol \\\n                    * quad(integrand, self.grid.ioniz_thresholds[absorber],\n                      self.Emax, points=self.sharp_points)[0] / self.qdot_bar[i] / erg_per_ev\n\n        return self._sigma_bar_all\n\n    @property\n    def sigma_tilde(self):\n        if not hasattr(self, '_sigma_tilde_all'):\n            self._sigma_tilde_all = np.zeros_like(self.grid.zeros_absorbers)\n            for i, absorber in enumerate(self.grid.absorbers):\n                integrand = lambda x: self.Spectrum(x) \\\n                    * self.grid.bf_cross_sections[absorber](x)\n                self._sigma_tilde_all[i] = quad(integrand,\n                    self.grid.ioniz_thresholds[absorber], self.Emax,\n                    points=self.sharp_points)[0] \\\n                    / self.fLbol_ionizing[i]\n\n        return self._sigma_tilde_all\n\n    @property\n    def fLbol_ionizing(self, absorber=0):\n        \"\"\"\n        Fraction of bolometric luminosity emitted above all ionization\n        thresholds.\n        \"\"\"\n        if not hasattr(self, '_fLbol_ioniz_all'):\n            self._fLbol_ioniz_all = np.zeros_like(self.grid.zeros_absorbers)\n            for i, absorber in enumerate(self.grid.absorbers):\n                self._fLbol_ioniz_all[i] = quad(self.Spectrum,\n                    self.grid.ioniz_thresholds[absorber], self.Emax,\n                    points=self.sharp_points)[0]\n\n        return self._fLbol_ioniz_all\n\n    @property\n    def Gamma_bar(self):\n        \"\"\"\n        Return ionization rate (as a function of radius) assuming optical\n        depth to cells and of cells is small.\n        \"\"\"\n        if not hasattr(self, '_Gamma_bar_all'):\n            self._Gamma_bar_all = \\\n                np.zeros([self.grid.dims, self.grid.N_absorbers])\n            for i, absorber in enumerate(self.grid.absorbers):\n                self._Gamma_bar_all[..., i] = self.Lbol * self.sigma_bar[i] \\\n                    * self.fLbol_ionizing[i] / 4. / np.pi / self.grid.r_mid**2 \\\n                    / self.hnu_bar[i] / erg_per_ev\n\n        return self._Gamma_bar_all\n\n    @property\n    def gamma_bar(self):\n        \"\"\"\n        Return ionization rate (as a function of radius) assuming optical\n        depth to cells and of cells is small.\n        \"\"\"\n        if not hasattr(self, '_gamma_bar_all'):\n            self._gamma_bar_all = \\\n                np.zeros([self.grid.dims, self.grid.N_absorbers,\n                    self.grid.N_absorbers])\n\n            if not self.pf['secondary_ionization']:\n                return self._gamma_bar_all\n\n            for i, absorber in enumerate(self.grid.absorbers):\n                for j, otherabsorber in enumerate(self.grid.absorbers):\n                    self._gamma_bar_all[..., i, j] = self.Gamma_bar[j] \\\n                        * (self.hnu_bar[j] * self.sigma_tilde[j] \\\n                        /  self.hnu_bar[i] / self.sigma_bar[j] \\\n                        - self.grid.ioniz_thresholds[otherabsorber] \\\n                        / self.grid.ioniz_thresholds[absorber])\n\n        return self._gamma_bar_all\n\n    @property\n    def Heat_bar(self):\n        \"\"\"\n        Return ionization rate (as a function of radius) assuming optical\n        depth to cells and of cells is small.\n        \"\"\"\n        if not hasattr(self, '_Heat_bar_all'):\n            self._Heat_bar_all = \\\n                np.zeros([self.grid.dims, self.grid.N_absorbers])\n            for i, absorber in enumerate(self.grid.absorbers):\n                self._Heat_bar_all[..., i] = self.Gamma_bar[..., i] \\\n                    * erg_per_ev * (self.hnu_bar[i] * self.sigma_tilde[i] \\\n                    / self.sigma_bar[i] - self.grid.ioniz_thresholds[absorber])\n\n        return self._Heat_bar_all\n\n    def IonizingPhotonLuminosity(self, t=0, bin=None):\n        \"\"\"\n        Return Qdot (photons / s) for this source at energy E.\n        \"\"\"\n\n        if self.pf['source_type'] in [0, 1, 2]:\n            return self.Qdot[bin]\n        else:\n            # Currently only BHs have a time-varying bolometric luminosity\n            return self.BolometricLuminosity(t) * self.LE[bin] / self.E[bin] / erg_per_ev\n\n    #def _Intensity(self, E, i, Type, t=0, absorb=True):\n    #    \"\"\"\n    #    Return quantity *proportional* to fraction of bolometric luminosity emitted\n    #    at photon energy E.  Normalization handled separately.\n    #    \"\"\"\n    #\n    #    Lnu = self.src._Intensity(E, i, Type, t=t)\n    #\n    #    # Apply absorbing column\n    #    if self.SpectrumPars['logN'][i] > 0 and absorb:\n    #        return Lnu * np.exp(-10.**self.SpectrumPars['logN'][i] \\\n    #            * (sigma_E(E, 0) + y * sigma_E(E, 1)))\n    #    else:\n    #        return Lnu\n    #\n    def Spectrum(self, E, t=0.0):\n        r\"\"\"\n        Return fraction of bolometric luminosity emitted at energy E.\n\n        Elsewhere denoted as :math:`I_{\\nu}`, normalized such that\n        :math:`\\int I_{\\nu} d\\nu = 1`\n\n        Parameters\n        ----------\n        E: float\n            Emission energy in eV\n        t: float\n            Time in seconds since source turned on.\n        i: int\n            Index of component to include. If None, includes contribution\n            from all components.\n\n        Returns\n        -------\n        Fraction of bolometric luminosity emitted at E in units of\n        eV\\ :sup:`-1`\\.\n\n        \"\"\"\n\n        if self.pf['source_Ekill'] is not None:\n            if self.pf['source_Ekill'][0] <= E <= self.pf['source_Ekill'][1]:\n                return 0.0\n\n        return self._normL * self._Intensity(E, t=t)\n\n    def BolometricLuminosity(self, t=0.0, M=None):\n        \"\"\"\n        Returns the bolometric luminosity of a source in units of erg/s.\n        For accreting black holes, the bolometric luminosity will increase\n        with time, hence the optional 't' and 'M' arguments.\n        \"\"\"\n\n        if self._name == 'bh':\n            return self.Luminosity(t, M)\n        else:\n            return self.Luminosity(t)\n\n    def _FrequencyAveragedBin(self, absorber='h_1', Emin=None, Emax=None,\n        energy_weighted=False, t=0):\n        \"\"\"\n        Bolometric luminosity / number of ionizing photons in spectrum in bandpass\n        spanning interval (Emin, Emax). Returns mean photon energy and number of\n        ionizing photons in band.\n        \"\"\"\n\n        if Emin is None:\n            Emin = max(self.grid.ioniz_thresholds[absorber], self.Emin)\n        if Emax is None:\n            Emax = self.Emax\n\n        if energy_weighted:\n            f = lambda x: x\n        else:\n            f = lambda x: 1.0\n\n        L = self.Lbol * quad(lambda x: self.Spectrum(x) * f(x), Emin, Emax,\n            points=self.sharp_points)[0]\n        Q = self.Lbol * quad(lambda x: self.Spectrum(x) * f(x) / x, Emin,\n            Emax, points=self.sharp_points)[0] / erg_per_ev\n\n        return L / Q / erg_per_ev, Q\n\n    def dump(self, fn, E, clobber=False):\n        \"\"\"\n        Write SED out to file.\n\n        Parameters\n        ----------\n        fn : str\n            Filename, suffix determines type. If 'hdf5' or 'h5' will write\n            to HDF5 file, otherwise, to ASCII.\n        E : np.ndarray\n            Array of photon energies at which to sample SED. Units = eV.\n\n        \"\"\"\n\n        if os.path.exists(fn) and (clobber == False):\n            raise OSError('{!s} exists!'.format(fn))\n\n        if re.search('.hdf5', fn) or re.search('.h5', fn):\n            out = 'hdf5'\n        else:\n            out = 'ascii'\n\n        LE = list(map(self.Spectrum, E))\n\n        if out == 'hdf5':\n            f = h5py.File(fn, 'w')\n            f.create_dataset('E', data=E)\n            f.create_dataset('LE', data=LE)\n            f.close()\n        else:\n            f = open(fn, 'w')\n            print(\"# E     LE\", file=f)\n            for i, nrg in enumerate(E):\n                print(\"{0:.8e} {1:.8e}\".format(nrg, LE[i]), file=f)\n            f.close()\n\n        print(\"Wrote {!s}.\".format(fn))\n\n    def sed_name(self, i=0):\n        \"\"\"\n        Return name of output file based on SED properties.\n        \"\"\"\n\n        name = ('{0!s}_logM_{1:.2g}_Gamma_{2:.3g}_fsc_{3:.3g}_' +\\\n            'logE_{4:.2g}-{5:.2g}').format(self.SpectrumPars['type'][i],\\\n            np.log10(self.src.M0), self.src.spec_pars['alpha'][i],\n            self.src.spec_pars['fsc'][i], np.log10(self.Emin), np.log10(self.Emax))\n\n        return name\n", "meta": {"hexsha": "f777da444e6594f1194076611b0c78f80707cf07", "size": 21297, "ext": "py", "lang": "Python", "max_stars_repo_path": "ares/sources/Source.py", "max_stars_repo_name": "JJHibbard/ares", "max_stars_repo_head_hexsha": "4b185747f2182524d732ef8316bff3a709bd85f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ares/sources/Source.py", "max_issues_repo_name": "JJHibbard/ares", "max_issues_repo_head_hexsha": "4b185747f2182524d732ef8316bff3a709bd85f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ares/sources/Source.py", "max_forks_repo_name": "JJHibbard/ares", "max_forks_repo_head_hexsha": "4b185747f2182524d732ef8316bff3a709bd85f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-16T23:13:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T23:13:56.000Z", "avg_line_length": 32.1221719457, "max_line_length": 101, "alphanum_fraction": 0.5596093346, "include": true, "reason": "import numpy,from scipy", "num_tokens": 5378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.2782567937024021, "lm_q1q2_score": 0.15105539659434047}}
{"text": "# /usr/bin/python3\n# coding=utf-8\n# Point Of No Return (Training)\n\n\"\"\"\nCopy of the game file, includes only nessessary content and no graphical code.\n\n@author: anon-42\n@version: beta\n\"\"\"\n\nimport numpy as np\nimport ann#artifical_neural_net as ann\nimport act_func as af\nimport trainer as tr\nimport replay_memory as rm\nimport os\nimport sys\nimport history as hs\nimport time\nfrom threading import Thread\n\n\nsys.setrecursionlimit(10000)\n\n\nclass Dot:\n\n    \"\"\"\n    Class for the points the player can visit.\n    \"\"\"\n\n    def __init__(self, x, y, state=0):\n        self.x = x\n        self.y = y\n        self.setstate(state)\n\n    def setstate(self, state): # -1 = bereits besucht, 0 = unbesetzt, 1 = aktuell besetzt\n        \"\"\"\n        Sets the state of Dot.\n        \"\"\"\n        self.state = state\n\n\nclass PONR:\n\n    \"\"\"\n    Main class of the game.\n    \"\"\"\n\n    def __init__(self, P1, P2, len_x=17, len_y=9, goal=5):\n        self.pos = [int(len_x / 2), int(len_y / 2)] # Position des Spielers\n        self.lines_data = [np.array([0.0 for i in range((len_x - 1) * len_y)]),            # waagerecht\n                           np.array([0.0 for i in range(len_x * (len_y - 1))]),               # senkrecht\n                           np.array([0.0 for i in range((len_x - 1) * (len_y - 1))]),# diagonal lo ru\n                           np.array([0.0 for i in range((len_x - 1) * (len_y - 1))])]# diagonal ro lu\n        self.touched_points = [self.pos]\n        self.diagonals = []\n        self.P1 = P1\n        self.P2 = P2\n        if len_x % 2 == len_y % 2 == goal % 2 == 1:\n            self.size = [len_x, len_y]\n            self.goal = goal\n        else:\n            raise ValueError('len_x, len_y and goal must be odd numbers.')\n\n        self.Dots = []\n        for x in range(self.size[0]):\n            for y in range(self.size[1]):\n                self.Dots.append(Dot(x, y))\n        self.find_Dot(self.pos).setstate(1)\n\n    def start(self):\n        \"\"\"\n        Mainloop of the game.\n        \"\"\"\n        active, passive = self.P1, self.P2\n        try:\n            while True:\n                for turn_number in range(3):\n                    if self.player_turn(active, turn_number):\n                        continue\n                    else:\n                        for turn_number in range(6):\n                            self.player_turn(passive, turn_number, free_kick=True)\n                        active, passive = passive, active\n                        break\n                active, passive = passive, active\n        except IndexError:\n            return\n\n\n    def find_Dot(self, pos):\n        \"\"\"\n        Finds a Dot object in self.Dots given its coordinates and returns it.\n        \"\"\"\n        for Dot in self.Dots:\n            if Dot.x == pos[0] and Dot.y == pos[1]:\n                return Dot\n\n    def player_turn(self, player, turn_number, free_kick=False, repetition=False):\n        \"\"\"\n        Executes one player turn.\n        \"\"\"\n        prev_pos = self.pos\n        if not free_kick and not self.can_move():\n            return False\n        _foo = [0.0 for i in range(6)]\n        _foo[turn_number] = 1.0\n        _foo.append(int(free_kick))\n        if player == self.P2:\n            state = np.append(np.array(_foo), np.fliplr(np.array([np.concatenate(self.lines_data)])))\n        else:\n            state = np.append(np.array(_foo), np.concatenate(self.lines_data))\n        step = player.get_input(state)\n        new_pos = [self.pos[0] + step[0],\n                   self.pos[1] + step[1]]\n        new_state = np.array([])\n        if turn_number == 5 and new_pos in self.touched_points:\n            if player == self.P1:\n                reward = -1\n            else:\n                reward = 1\n            self.update(player, state, step, reward, new_state)\n            raise IndexError\n        elif new_pos[1] in [y for y in range((self.size[1] - self.goal) // 2,    # goal left\n                                             (self.size[1] + self.goal) // 2)] and new_pos[0] == -1:\n            reward = -1\n            self.update(player, state, step, reward, new_state)\n            raise IndexError\n        elif new_pos[1] in [y for y in range((self.size[1] - self.goal) // 2,    # goal right\n                                             (self.size[1] + self.goal) // 2)] and new_pos[0] == self.size[0]:\n            reward = 1\n            self.update(player, state, step, reward, new_state)\n            raise IndexError\n        elif self.rules(prev_pos, new_pos, free_kick):\n            index = (+ min(prev_pos[1], new_pos[1])\n                     * (self.size[0] - 1)\n                     + min(prev_pos[0], new_pos[0]))\n            if step[0] == 0:        # senkrecht\n                self.lines_data[1][index] = 1\n            elif step[1] == 0:      # waagerecht\n                self.lines_data[0][index] = 1\n            elif step[0] == step[1]:# diagonal ro lu\n                self.lines_data[3][index] = 1\n            else:                   # diagonal lo ru\n                self.lines_data[2][index] = 1\n            self.pos = new_pos\n            self.find_Dot(prev_pos).setstate(-1)\n            self.find_Dot(new_pos).setstate(1)\n            self.touched_points.append(new_pos)\n            self.diagonals.append([prev_pos, new_pos])\n            reward = self.reward(repetition, new_pos, prev_pos)\n            _foo = [0.0 for i in range(6)]\n            _foo[turn_number] = 1.0\n            _foo.append(int(free_kick))\n            if player == self.P2:\n                new_state = np.append(np.array(_foo),\n                                      np.fliplr(np.array([np.concatenate(self.lines_data)])))\n            else:\n                new_state = np.append(np.array(_foo),\n                                      np.concatenate(self.lines_data))\n        else:\n            print(time.clock())\n            self.player_turn(player, turn_number, free_kick, repetition=True)\n            reward = self.reward(repetition, new_pos, prev_pos)\n        if player == self.P2:\n            step = [-step[0], -step[1]]\n        self.update(player, state, step, reward, new_state)\n        return True\n\n    def can_move(self):\n        \"\"\"\n        Checks if the player can move.\n        \"\"\"\n        for step in [[-1, -1], [0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1],[-1, 0]]:\n            if self.rules(self.pos, [self.pos[0] + step[0], self.pos[1] + step[1]], False):\n                return True\n        if self.pos[0] in [0, self.size[1]] and self.pos[1] in [y for y in range((self.size[1] - self.goal) // 2, (self.size[1] + self.goal) // 2)]:\n            return True\n        return False\n\n    def rules(self, prev_pos, new_pos, free_kick):\n        \"\"\"\n        Checks if all rules were followed.\n        \"\"\"\n        if (prev_pos[0] != new_pos[0]) and (prev_pos[1] != new_pos[1]):                     #\"Wenn es eine Diagonale ist, dann...\"\n            cd = [[new_pos[0], prev_pos[1]], [prev_pos[0], new_pos[1]]]                     #cd = corresponding diagonal\n            if not (cd in self.diagonals or [cd[1], cd[0]] in self.diagonals):              #\"Wenn cd nicht in der Liste der bereits vorhandenen Diagonalen, dann...\"\n                a = True                                                                    #Regeln eingehalten; Diagonale kann gezeichnet werden\n            else:\n                a = False\n        else:\n            a = True                                                                        #Regeln eingehalten, aber es ist keine Diagonale\n                                                                                            #Regeln nicht eingehalten; Diagonale darf nicht gezeichnet werden\n        return ((0 <= new_pos[0] < self.size[0] and 0 <= new_pos[1] < self.size[1]) and     #Spielfeldgroesse\n                ((not new_pos in self.touched_points) or free_kick) and                                    #Betretene Punkte nicht erneut betreten\n                (a or free_kick))                                                                        #Kreuzen der bereits vorhandenen Diagonalen\n\n    def reward(self, penalty, new_pos, prev_pos):\n        \"\"\"\n        Calculates a reward for a turn.\n        \"\"\"\n        if penalty:\n            return -0.5\n        elif new_pos[0] > prev_pos[0]:\n            return -0.01\n        elif new_pos[0] < prev_pos[0]:\n            return -0.02\n        elif new_pos[0] == prev_pos[0]:\n            return -0.015\n\n    def update(self, player, state, action, reward, new_state):\n        \"\"\"\n        TODO: add docstring\n        \"\"\"\n        global history, rm\n        rm.update(state, action, reward, new_state)\n        history.add_turn([(str(int(player == self.P1)), state, np.array(action), reward)])\n\n    def game_replay(self):\n        pass\n\n\nclass Interface:\n\n    \"\"\"\n    The game interface to a player (human / AI).\n    \"\"\"\n    def __init__(self, name=None):\n        global eta, alpha, net, history\n        self.net = net\n        self.trainer = tr.Trainer(self.net, eta, alpha, history)\n        self.name = name if name != None else '<empty>'\n        self.iterations = 0\n\n    def get_input(self, data):\n        \"\"\"\n        Gets an input from the ann.\n        \"\"\"\n        global counter\n        Qvalues = self.net.forward(np.array([data])) # 8 element array\n\n        # probability to choose an action ==> Boltzmann exploration\n        Qvalues /= (50000/counter + 0.5) # T - temperature\n        counter += 1\n\n        # softmax\n        e_x = np.exp(Qvalues - np.max(Qvalues))\n        prob = e_x / e_x.sum()\n        self.step = [[-1, -1],\n                     [0, -1],\n                     [1, -1],\n                     [1, 0],\n                     [1, 1],\n                     [0, 1],\n                     [-1, 1],\n                     [-1, 0]][np.random.choice(np.arange(8), p=prob.flatten())]\n\n        self.iterations += 1\n        return self.step\n\n    def train_net(self):\n        \"\"\"\n        Passes the current game stats to the AI.\n        \"\"\"\n        global number_of_turns, data_from_rm, rm\n        # get trainig data from replay_memory\n        rm.number_of_turns(data_from_rm)\n        data = rm.get()\n\n        state = np.array([data[0]])\n        action = np.array([data[1]])\n        reward = np.array([[data[2]]])\n        new_state = np.array([data[3]])\n\n        for element in rm:\n            state = np.append(state, (np.array([element[0]])), axis=0)\n            action = np.append(action, (np.array([element[1]])), axis=0)\n            reward = np.append(reward, (np.array([[element[2]]])), axis=0)\n            new_state = np.append(new_state, (np.array([element[3]])), axis=0)\n\n\n        # compute desired output for training purposes\n        correctoutput = self.net.forward(state)\n        maxQ = np.amax(self.net.forward(new_state), axis=1, keepdims=True)\n\n        # final state\n        maxQ[np.where(np.logical_or(reward == 1, reward == -1)), :] = 0\n\n\n        index_gamma09 = np.logical_or(np.logical_and(state[:, 6] == 1,\n          state[:, 5] == 1), np.logical_and(state[:,6]==0, state[:, 2] == 1))\n        gamma = np.where(index_gamma09, 0.9, 1)\n        gamma = np.reshape(gamma, (-1, 1))\n\n        action_taken = ((action[:,1]+2)**2 + action[:,0]).flatten()\n        correctoutput[np.where(action_taken > 3, action_taken-1,\n          action_taken)] = reward + gamma*maxQ\n\n        self.trainer.train(state, correctoutput, number_of_turns)\n\n\nclass Saver(Thread):\n\n    \"\"\"\n    Thread for saving ANN and ReplayMemory instances once in 900 seconds.\n    \"\"\"\n\n    def __init__(self, net, rm):\n        Thread.__init__(self)\n        self.net = net\n        self.rm = rm\n        self.stop = False\n\n    def run(self):\n        \"\"\"\n        The threads main activity.\n        \"\"\"\n        while not self.stop:\n            self.net.save()\n            self.rm.save()\n            time.sleep(900)\n\n    def stop(self):\n        \"\"\"\n        Prevents the thread from continuing when called.\n        \"\"\"\n        self.stop = True\n\n\nif __name__ == '__main__':\n    global eta, alpha, number_of_turns, data_from_rm, rm, history, net, counter\n    path = os.path.dirname(os.path.abspath(__file__)) + '/saves/'    # must end with \"/\" on Linux and with \"\\\" on Windows\n    history = hs.History(path + 'History')\n    rm = rm.ReplayMemory(path + 'ReplayMemory.rm', 42000)\n    Lambda = .0\n    eta = .0001\n    alpha = .7\n    input_layer = 543\n    output_layer = (8, af.tanh)\n    hidden_layers = [(543, af.tanh),\n                     (543, af.tanh),\n                     (543, af.tanh)]\n    number_of_turns = 500\n    data_from_rm = 500\n    net = ann.Neural_Network(path + 'DATA',\n                             input_layer,\n                             output_layer,\n                             hidden_layers,\n                             Lambda)\n    Saver(net, rm).start()\n    counter = 1\n    while True:\n        history.setGame(hs.generateName('main_net', 'dummy_net', 1).__next__())\n        GAME = PONR(Interface('main net'),\n                    Interface('dummy net'))\n        GAME.start()\n", "meta": {"hexsha": "6bae3bbe88a17eb12319dbaceb16a300beae91f3", "size": 12933, "ext": "py", "lang": "Python", "max_stars_repo_path": "PointOfNoReturn_Training.py", "max_stars_repo_name": "anon-42/ANN-PONR-Python3", "max_stars_repo_head_hexsha": "4b7e290c768a9e3cafb19b8b3a786c1f99670c0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-03-13T13:36:11.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-19T12:35:07.000Z", "max_issues_repo_path": "PointOfNoReturn_Training.py", "max_issues_repo_name": "anon-42/ANN-PONR-Python3", "max_issues_repo_head_hexsha": "4b7e290c768a9e3cafb19b8b3a786c1f99670c0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PointOfNoReturn_Training.py", "max_forks_repo_name": "anon-42/ANN-PONR-Python3", "max_forks_repo_head_hexsha": "4b7e290c768a9e3cafb19b8b3a786c1f99670c0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0250696379, "max_line_length": 165, "alphanum_fraction": 0.5076161757, "include": true, "reason": "import numpy", "num_tokens": 3239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.2782567937024021, "lm_q1q2_score": 0.15105539659434047}}
{"text": "# Copyright (C) 2013 Atsushi Togo\n# All rights reserved.\n#\n# This file is part of phonopy.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n#   notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n#   notice, this list of conditions and the following disclaimer in\n#   the documentation and/or other materials provided with the\n#   distribution.\n#\n# * Neither the name of the phonopy project nor the names of its\n#   contributors may be used to endorse or promote products derived\n#   from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport numpy as np\n\nclass DerivativeOfDynamicalMatrix(object):\n    \"\"\"Compute analytical derivative of dynamical matrix\n\n    This can be used dynamical matrix without NAC or with Wang-NAC.\n\n    \"\"\"\n\n    def __init__(self, dynamical_matrix):\n        self._dynmat = dynamical_matrix\n        (self._smallest_vectors,\n         self._multiplicity) = self._dynmat.get_shortest_vectors()\n        self._force_constants = self._dynmat.get_force_constants()\n        self._scell = self._dynmat.get_supercell()\n        self._pcell = self._dynmat.get_primitive()\n\n        self._p2s_map = self._dynmat.get_primitive_to_supercell_map()\n        self._s2p_map = self._dynmat.get_supercell_to_primitive_map()\n        p2p_map = self._pcell.get_primitive_to_primitive_map()\n        self._s2pp_map = np.array(\n            [p2p_map[self._s2p_map[i]] for i in range(len(self._s2p_map))],\n            dtype='intc')\n        self._mass = self._pcell.get_masses()\n\n        self._ddm = None\n\n        # Derivative order=2 can work only within the following conditions:\n        # 1. Second derivative of NAC is not considered.\n        # 2. Python implementation\n        self._derivative_order = None\n\n    def run(self, q, q_direction=None, lang='C'):\n        if self._derivative_order is not None or lang != 'C':\n            self._run_py(q, q_direction=q_direction)\n        else:\n            self._run_c(q, q_direction=q_direction)\n\n    def set_derivative_order(self, order):\n        if order == 1 or order == 2:\n            self._derivative_order = order\n        else:\n            print(\"Error: derivative order has to be 1 or 2\")\n\n    def get_derivative_of_dynamical_matrix(self):\n        return self._ddm\n\n    def _run_c(self, q, q_direction=None):\n        import phonopy._phonopy as phonoc\n        num_patom = len(self._p2s_map)\n\n        mass = self._pcell.get_masses()\n        fc = self._force_constants\n        itemsize = self._force_constants.itemsize\n        ddm = np.zeros((3, num_patom * 3, num_patom * 3),\n                       dtype=(\"c%d\" % (itemsize * 2)))\n        vectors = self._smallest_vectors\n        multiplicity = self._multiplicity\n        if self._dynmat.is_nac():\n            born = self._dynmat.get_born_effective_charges()\n            dielectric = self._dynmat.get_dielectric_constant()\n            nac_factor = self._dynmat.get_nac_factor()\n            if q_direction is None:\n                q_dir = None\n            else:\n                q_dir = np.array(q_direction, dtype='double', order='C')\n        else:\n            born = None\n            dielectric = None\n            nac_factor = 0\n            q_dir = None\n\n        if fc.shape[0] == fc.shape[1]: # full fc\n            phonoc.derivative_dynmat(ddm.view(dtype='double'),\n                                     fc,\n                                     np.array(q, dtype='double'),\n                                     np.array(self._pcell.get_cell().T,\n                                              dtype='double', order='C'),\n                                     vectors,\n                                     multiplicity,\n                                     mass,\n                                     self._s2p_map,\n                                     self._p2s_map,\n                                     nac_factor,\n                                     born,\n                                     dielectric,\n                                     q_dir)\n        else:\n            phonoc.derivative_dynmat(ddm.view(dtype='double'),\n                                     fc,\n                                     np.array(q, dtype='double'),\n                                     np.array(self._pcell.get_cell().T,\n                                              dtype='double', order='C'),\n                                     vectors,\n                                     multiplicity,\n                                     mass,\n                                     self._s2pp_map,\n                                     np.arange(len(self._p2s_map),\n                                               dtype='intc'),\n                                     nac_factor,\n                                     born,\n                                     dielectric,\n                                     q_dir)\n\n        self._ddm = ddm\n\n    def _run_py(self, q, q_direction=None):\n        if self._dynmat.is_nac():\n            if q_direction is None:\n                fc_nac = self._nac(q)\n                d_nac = self._d_nac(q)\n            else:\n                fc_nac = self._nac(q_direction)\n                d_nac = self._d_nac(q_direction)\n\n        fc = self._force_constants\n        vecs = self._smallest_vectors\n        multiplicity = self._multiplicity\n        num_patom = len(self._p2s_map)\n        num_satom = len(self._s2p_map)\n\n        if self._derivative_order == 2:\n            num_elem = 6\n        else:\n            num_elem = 3\n\n        itemsize = self._force_constants.itemsize\n        ddm = np.zeros((num_elem, 3 * num_patom, 3 * num_patom),\n                       dtype=(\"c%d\" % (itemsize * 2)))\n\n        for i, j in list(np.ndindex(num_patom, num_patom)):\n            s_i = self._p2s_map[i]\n            s_j = self._p2s_map[j]\n            mass = np.sqrt(self._mass[i] * self._mass[j])\n            ddm_local = np.zeros((num_elem, 3, 3),\n                                 dtype=(\"c%d\" % (itemsize * 2)))\n\n            for k in range(num_satom):\n                if s_j != self._s2p_map[k]:\n                    continue\n\n                multi = multiplicity[k, i]\n                vecs_multi = vecs[k, i, :multi]\n                phase_multi = np.exp([np.vdot(vec, q) * 2j * np.pi\n                                      for vec in vecs_multi])\n                vecs_multi_cart = np.dot(vecs_multi, self._pcell.get_cell())\n                coef_order1 = 2j * np.pi * vecs_multi_cart\n                if self._derivative_order == 2:\n                    coef_order2 = [np.outer(co1, co1) for co1 in coef_order1]\n                    coef = np.array([co2.ravel()[[0, 4, 8, 5, 2, 1]]\n                                     for co2 in coef_order2])\n                else:\n                    coef = coef_order1\n\n                if self._dynmat.is_nac():\n                    fc_elem = fc[s_i, k] + fc_nac[i, j]\n                else:\n                    fc_elem = fc[s_i, k]\n\n                for l in range(num_elem):\n                    ddm_elem = fc_elem * (coef[:, l] * phase_multi).sum()\n                    if (self._dynmat.is_nac() and\n                        not self._derivative_order == 2):\n                        ddm_elem += d_nac[l, i, j] * phase_multi.sum()\n\n                    ddm_local[l] +=  ddm_elem / mass / multi\n\n\n            ddm[:, (i * 3):(i * 3 + 3), (j * 3):(j * 3 + 3)] = ddm_local\n\n        # Impose Hermite condition\n        self._ddm = np.array([(ddm[i] + ddm[i].conj().T) / 2\n                              for i in range(num_elem)])\n\n    def _nac(self, q_direction):\n        \"\"\"nac_term = (A1 (x) A2) / B * coef.\n        \"\"\"\n        num_atom = self._pcell.get_number_of_atoms()\n        nac_q = np.zeros((num_atom, num_atom, 3, 3), dtype='double')\n        if (np.abs(q_direction) < 1e-5).all():\n            return nac_q\n\n        rec_lat = np.linalg.inv(self._pcell.get_cell())\n        nac_factor = self._dynmat.get_nac_factor()\n        Z = self._dynmat.get_born_effective_charges()\n        e = self._dynmat.get_dielectric_constant()\n        q = np.dot(rec_lat, q_direction)\n\n        B = self._B(e, q)\n        for i in range(num_atom):\n            A_i = self._A(q, Z, i)\n            for j in range(num_atom):\n                A_j = self._A(q, Z, j)\n                nac_q[i, j] = np.outer(A_i, A_j) / B\n\n        num_satom = self._scell.get_number_of_atoms()\n        N = num_satom // num_atom\n\n        return nac_q * nac_factor / N\n\n    def _d_nac(self, q_direction):\n        num_atom = self._pcell.get_number_of_atoms()\n        d_nac_q = np.zeros((3, num_atom, num_atom, 3, 3), dtype='double')\n        if (np.abs(q_direction) < 1e-5).all():\n            return d_nac_q\n\n        rec_lat = np.linalg.inv(self._pcell.get_cell())\n        nac_factor = self._dynmat.get_nac_factor()\n        Z = self._dynmat.get_born_effective_charges()\n        e = self._dynmat.get_dielectric_constant()\n        q = np.dot(rec_lat, q_direction)\n\n        B = self._B(e, q)\n        for xyz in range(3):\n            dB = self._dB(e, q, xyz)\n            for i in range(num_atom):\n                A_i = self._A(q, Z, i)\n                dA_i = self._dA(Z, i, xyz)\n                for j in range(num_atom):\n                    A_j = self._A(q, Z, j)\n                    dA_j = self._dA(Z, j, xyz)\n                    d_nac_q[xyz, i, j] = (\n                        (np.outer(dA_i, A_j) + np.outer(A_i, dA_j)) / B -\n                        np.outer(A_i, A_j) * dB / B ** 2)\n\n        num_satom = self._scell.get_number_of_atoms()\n        N = num_satom // num_atom\n        return d_nac_q * nac_factor / N\n\n    def _A(self, q, Z, atom_num):\n        return np.dot(q, Z[atom_num])\n\n    def _B(self, epsilon, q):\n        return np.dot(q, np.dot(epsilon, q))\n\n    def _dA(self, Z, atom_num, xyz):\n        return Z[atom_num, xyz, :]\n\n    def _dB(self, epsilon, q, xyz):\n        e = epsilon\n        return np.dot(e[xyz], q) * 2\n", "meta": {"hexsha": "f44613553dea325a8db3c76ee38f0db22e825155", "size": 10823, "ext": "py", "lang": "Python", "max_stars_repo_path": "phonopy/harmonic/derivative_dynmat.py", "max_stars_repo_name": "gcgs1/phonopy", "max_stars_repo_head_hexsha": "6a194a2d9514646b61a5f87168107d4c6b0d570d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "phonopy/harmonic/derivative_dynmat.py", "max_issues_repo_name": "gcgs1/phonopy", "max_issues_repo_head_hexsha": "6a194a2d9514646b61a5f87168107d4c6b0d570d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phonopy/harmonic/derivative_dynmat.py", "max_forks_repo_name": "gcgs1/phonopy", "max_forks_repo_head_hexsha": "6a194a2d9514646b61a5f87168107d4c6b0d570d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2137681159, "max_line_length": 77, "alphanum_fraction": 0.5297976531, "include": true, "reason": "import numpy", "num_tokens": 2610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.2720245451923523, "lm_q1q2_score": 0.15082957605345235}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"\nITU-R BT.2020 Colourspace\n=========================\n\nDefines the *ITU-R BT.2020* colourspace:\n\n-   :attr:`colour.models.BT2020_COLOURSPACE`.\n\nReferences\n----------\n-   :cite:`InternationalTelecommunicationUnion2015h` : International\n    Telecommunication Union. (2015). Recommendation ITU-R BT.2020 - Parameter\n    values for ultra-high definition television systems for production and\n    international programme exchange. Retrieved from https://www.itu.int/\\\ndms_pubrec/itu-r/rec/bt/R-REC-BT.2020-2-201510-I!!PDF-E.pdf\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\n\nfrom colour.colorimetry import ILLUMINANTS\nfrom colour.models.rgb import (RGB_Colourspace, normalised_primary_matrix,\n                               oetf_BT2020, eotf_BT2020)\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2020 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-developers@colour-science.org'\n__status__ = 'Production'\n\n__all__ = [\n    'BT2020_PRIMARIES', 'BT2020_WHITEPOINT_NAME', 'BT2020_WHITEPOINT',\n    'BT2020_TO_XYZ_MATRIX', 'XYZ_TO_BT2020_MATRIX', 'BT2020_COLOURSPACE'\n]\n\nBT2020_PRIMARIES = np.array([\n    [0.7080, 0.2920],\n    [0.1700, 0.7970],\n    [0.1310, 0.0460],\n])\n\"\"\"\n*ITU-R BT.2020* colourspace primaries.\n\nBT2020_PRIMARIES : ndarray, (3, 2)\n\"\"\"\n\nBT2020_WHITEPOINT_NAME = 'D65'\n\"\"\"\n*ITU-R BT.2020* colourspace whitepoint name.\n\nBT2020_WHITEPOINT_NAME : unicode\n\"\"\"\n\nBT2020_WHITEPOINT = (\n    ILLUMINANTS['CIE 1931 2 Degree Standard Observer'][BT2020_WHITEPOINT_NAME])\n\"\"\"\n*ITU-R BT.2020* colourspace whitepoint.\n\nBT2020_WHITEPOINT : ndarray\n\"\"\"\n\nBT2020_TO_XYZ_MATRIX = normalised_primary_matrix(BT2020_PRIMARIES,\n                                                 BT2020_WHITEPOINT)\n\"\"\"\n*ITU-R BT.2020* colourspace to *CIE XYZ* tristimulus values matrix.\n\nBT2020_TO_XYZ_MATRIX : array_like, (3, 3)\n\"\"\"\n\nXYZ_TO_BT2020_MATRIX = np.linalg.inv(BT2020_TO_XYZ_MATRIX)\n\"\"\"\n*CIE XYZ* tristimulus values to *ITU-R BT.2020* colourspace matrix.\n\nXYZ_TO_BT2020_MATRIX : array_like, (3, 3)\n\"\"\"\n\nBT2020_COLOURSPACE = RGB_Colourspace(\n    'ITU-R BT.2020',\n    BT2020_PRIMARIES,\n    BT2020_WHITEPOINT,\n    BT2020_WHITEPOINT_NAME,\n    BT2020_TO_XYZ_MATRIX,\n    XYZ_TO_BT2020_MATRIX,\n    oetf_BT2020,\n    eotf_BT2020,\n)\nBT2020_COLOURSPACE.__doc__ = \"\"\"\n*ITU-R BT.2020* colourspace.\n\nReferences\n----------\n:cite:`InternationalTelecommunicationUnion2015h`\n\nBT2020_COLOURSPACE : RGB_Colourspace\n\"\"\"\n", "meta": {"hexsha": "290cce2508f6899371a833097520704ee2dc9bd1", "size": 2561, "ext": "py", "lang": "Python", "max_stars_repo_path": "colour/models/rgb/datasets/itur_bt_2020.py", "max_stars_repo_name": "jchwei/colour", "max_stars_repo_head_hexsha": "2b2ad0a0f2052a1a0b4b076b489687235e804fdf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "colour/models/rgb/datasets/itur_bt_2020.py", "max_issues_repo_name": "jchwei/colour", "max_issues_repo_head_hexsha": "2b2ad0a0f2052a1a0b4b076b489687235e804fdf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "colour/models/rgb/datasets/itur_bt_2020.py", "max_forks_repo_name": "jchwei/colour", "max_forks_repo_head_hexsha": "2b2ad0a0f2052a1a0b4b076b489687235e804fdf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8686868687, "max_line_length": 79, "alphanum_fraction": 0.7161265131, "include": true, "reason": "import numpy", "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.23651622568252118, "lm_q1q2_score": 0.15066811915403808}}
{"text": "'''\n---------------\nBefore running\n---------------\n\nThis is the code for making the \"Masking image\" of FITS file.\nThe \"Masking image\" masks the 1) nearby stars, 2) Cosmic ray, (if this is MSI data) 3) the polarization mask area.\n\n1.\nInput file:  '*.fits'                      Preprocessed FITS file\n             '*.mag.1'                     IRAF Phot file containing target's center info.\n                                           See below (i.e.,2. What you need to run this code)\n             'mask_*.fits'                 Masking image produced by 'Masking_image.py'.\n\nOutput file: 'result_Photo_*.csv'          Photometric result of each images\n             'result_Pol_*.csv'            Polarimetric result of each sets\n\n2.What you need to run this code.\n  (The following packages must be installed.)\n  i.  astropy (https://www.astropy.org/)\n  iii.``*.mag.1`` file from IRAF's Phot package that contains the center of the target (2005 UD).\n      The first line should be the center in the ordinary component, and the\n      second line should be for extraordinary component.\n      We've also uploaded the ``*.mag.1`` file that we used with this code.\n\n3.\nIn this code, the center of the target is found by using the phot task of IRAF.\nSo, we need the ``.mag`` file to import the coordinate of target's ceter.\nThere is no problem if you find the target's center by other methods.\nAll you need to do is modifying the part that brings the central coordinate of target.\nSee ``BRING THE CENTER COORDINATE OF 2005 UD`` part.\n\n4.\nDirectory should contain the complete sets consist of 4 images (taken at HWP=0, 22.5, 45, 67.5 deg).\nIf even one set does not have 4 images (e.g., set having images taken at HWP = 0, 45, 67.5 deg),\nan error will occur.\n'''\n\nimport glob\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n# from mpl_toolkits.axes_grid1 import make_axes_locatable\nimport pandas as pd\n\n\nfrom astropy.io import fits, ascii\nfrom astropy.time import Time\nfrom astroquery.jplhorizons import Horizons\nfrom astropy.modeling.models import Gaussian1D\nfrom astropy.modeling.fitting import LevMarLSQFitter\nfrom photutils import CircularAperture, CircularAnnulus, aperture_photometry\nfrom astropy.stats import gaussian_fwhm_to_sigma\n\nimport warnings\nfrom astropy.io.fits.verify import VerifyWarning\nwarnings.simplefilter('ignore', category=VerifyWarning)\nmpl.rc('figure', max_open_warning=0)\n\n\n# ********************************************************************************************************** #\n# *                                           INPUT VALUE                                                  * #\n# ********************************************************************************************************** #\n\n\nObservatory = 'q33'  # Observatory code of Pirks\nOBJECT = 155140  # 2005 UD\n\npath = os.path.join('Directory/Where/image/to/be/analyzed/is/saved/')  # Path of directory where images to be analyzed are saved\nIMAGE_list = glob.glob(os.path.join(path, '*.fits'))  # Bring all FITS preprocessed image in the directory\n\n\n####################################\n# Photometry Parameter\n####################################\nAperture_scale = 1.7   # Aperture radius = Aperture_scale * FWHM\nANN_sacle = 4         # Annulus radius = ANN_sacle * FWHM\nDan = 20              # [pix] #Dannulus size\n\n####################################\n# Calibration Parameter (Please see Ishiguro et al. 2021)\n####################################\neff = 0.9913  # Polarimetric efficiency of instrument\neff_err = 0.0001  # Error of polarimetric efficiency of instrument\n\nq_inst = 0.00791  # Instrumental polarization, q_{inst}\nu_inst = 0.00339  # Instrumental polarization, u_{inst}\neq_inst = 0.00025  # Error of instrumental polarization, error of q_{inst}\neu_inst = 0.00020  # Error of instrumental polarization, error of u_{inst}\n\ntheta_offset = 3.66  # Offset of polarization angle\nerr_theta = 0.17  # Error of offset\n\n\n# ********************************************************************************************************** #\n\n\nPhoto_Log = pd.DataFrame({})\nPol_Log = pd.DataFrame({})\norder = np.arange(0, len(IMAGE_list), 4)\nIMAGE_list = sorted(IMAGE_list)\n\nfor z in order:\n    print('==== Set {0:03d} ===='.format(int(z/4+1)))\n    SET = [IMAGE_list[z], IMAGE_list[z+1], IMAGE_list[z+2], IMAGE_list[z+3]]  # Image taken at HWP=0,22.5,45,67.5\n\n    I = []  # I_ex/I_o\n    S = []  # (Sigma_{I_ex}/I_ex)**2 + (Sigma_{I_o}/I_o)**2\n    INR_STR = []\n    INR_END = []\n    PSANG = []\n    PA = []\n    JD_mean = []\n    file_name = SET[0].split('/')[-1].split('.')[0] + ' ~ '+SET[3].split('/')[-1][-7:]\n    aper_seri_o = ''\n    aper_seri_e = ''\n    snr = 0\n\n    # fig,ax = plt.subplots(4,2,figsize=(20,40))\n    for ang in range(0, 4):\n        image_i = SET[ang]\n        hdul = fits.open(image_i)\n        header = hdul[0].header\n        data = hdul[0].data\n        RET_ANG2 = header['RET-ANG2']\n\n        # Bring the header info.==================================================\n        iNR_STR = header['INR-STR']\n        iNR_END = header['INR-END']\n        INST_pa = header['INST-PA']\n        JD = np.mean([header['MJD-STR'], header['MJD-END']])\n        JD = JD + 2400000.5  # MJD -> JD\n        epoch = Time(JD, format='jd').isot\n        RN = header['RDNOISE']  # [electron]\n        gain = header['GAIN']  # [electron/DN]\n        Filter = header['FILTER']\n        exp = header['EXPTIME']  # in sec\n\n        # ************************************************************************************* #\n        # *                Bring the observer quantities from JPL Horizons                    * #\n        # ************************************************************************************* #\n        obj = Horizons(id=OBJECT, location=Observatory, epochs=JD)\n        eph = obj.ephemerides()\n        psANG = eph['sunTargetPA'][0]  # [deg]\n        pA = eph['alpha'][0]  # [deg]\n\n        # ************************************************************************************* #\n        # *                   BRING THE CENTER COORDINATE OF 2005 UD                          * #\n        # ************************************************************************************* #\n        # Here, we use Phot package in IRAF to find the center of the target\n        # If you find the center of the target by other methods, please change this part.\n\n        # Bring the center\n        mag1 = ascii.read(image_i+'.mag.1')\n        xo, yo = (mag1['XCENTER'][0]-1, mag1['YCENTER'][0]-1)  # pixel coordinate (x,y) of target's center in ordinary component\n        xe, ye = (mag1['XCENTER'][1]-1, mag1['YCENTER'][1]-1)  # pixel coordinate (x,y) of target's center in extra. component\n\n        # ************************************************************************************* #\n        # *                            Bring the Masking Image                                * #\n        # ************************************************************************************* #\n        masking_path = os.path.join(path, 'Masking', 'mask_'+image_i.split('/')[-1])\n        hdul_mask = fits.open(masking_path)[0]\n        masking = hdul_mask.data\n\n        # ************************************************************************************* #\n        # *                            Determine FWHM of target                               * #\n        # ************************************************************************************* #\n        def crop(data, row, col, size):\n            row_str = int(row-size)\n            row_end = int(row+size)\n            col_str = int(col-size)\n            col_end = int(col+size)\n            data_cr = data[row_str:row_end, col_str:col_end]\n            return data_cr\n        ##############################\n        #  Ordinary\n        ##############################\n        mdata = np.ma.masked_array(data, masking)\n        crop_image = crop(mdata, yo, xo, 35)\n        sum_crop_image = np.mean(crop_image, axis=0)\n        sum_crop_image = sum_crop_image - np.mean(sum_crop_image[:10])\n\n        g_init = Gaussian1D(amplitude=np.mean(sum_crop_image[34:36]),\n                            mean=35,\n                            stddev=10*gaussian_fwhm_to_sigma,\n                            bounds={'mean': (33, 37),\n                                    'stddev': ((5*gaussian_fwhm_to_sigma, 20*gaussian_fwhm_to_sigma))})\n\n        x = np.arange(0, len(crop_image), 1)\n        fitter = LevMarLSQFitter()\n        fitted = fitter(g_init, x, sum_crop_image)\n\n        re_g_init = Gaussian1D(amplitude=fitted.amplitude.value,\n                               mean=fitted.mean.value,\n                               stddev=fitted.stddev.value,\n                               bounds={'mean': (33, 37),\n                                       'stddev': ((5*gaussian_fwhm_to_sigma, 20*gaussian_fwhm_to_sigma))})\n        fitter = LevMarLSQFitter()\n        fitted = fitter(re_g_init, x, sum_crop_image)\n        FWHM_ordi = 2*fitted.stddev.value*np.sqrt(2*np.log(2))\n        aper_seri_o += '{0:.1f} '.format(FWHM_ordi)\n\n        ##############################\n        #  Extra-Ordinary\n        ##############################\n        crop_image = crop(mdata, ye, xe, 35)\n        sum_crop_image = np.mean(crop_image, axis=0)\n        sum_crop_image = sum_crop_image - np.mean(sum_crop_image[:10])\n        g_init = Gaussian1D(amplitude=np.mean(sum_crop_image[34:36]),\n                            mean=35,\n                            stddev=10*gaussian_fwhm_to_sigma,\n                            bounds={'mean': (33, 37),\n                                    'stddev': (5*gaussian_fwhm_to_sigma, 20*gaussian_fwhm_to_sigma)})\n\n        fitter = LevMarLSQFitter()\n        fitted = fitter(g_init, x, sum_crop_image)\n\n        re_g_init = Gaussian1D(amplitude=fitted.amplitude.value,\n                               mean=fitted.mean.value,\n                               stddev=fitted.stddev.value,\n                               bounds={'mean': (33, 37),\n                                       'stddev': (5*gaussian_fwhm_to_sigma, 20*gaussian_fwhm_to_sigma)})\n        fitter = LevMarLSQFitter()\n        fitted = fitter(re_g_init, x, sum_crop_image)\n        FWHM_extra = 2*fitted.stddev.value*np.sqrt(2*np.log(2))\n        aper_seri_e += '{0:.1f} '.format(FWHM_extra)\n\n        # ************************************************************************************* #\n        # *                        Circular Aperture Photometry                               * #\n        # ************************************************************************************* #\n        def skyvalue(data, y0, x0, r_in, r_out, masking):\n            masking = masking.astype(bool)\n            ann = CircularAnnulus([x0, y0], r_in=r_in, r_out=r_out)\n            phot = aperture_photometry(data, ann, mask=masking)\n\n            phot1 = aperture_photometry(masking*1, ann)\n            pixel_count = phot1['aperture_sum'][0]\n            sky = phot['aperture_sum'][0]/(ann.area-pixel_count)\n\n            masked_image = np.ma.masked_array(data, masking)\n\n            # Determine sky std\n            y_in = int(y0-r_out)\n            y_out = int(y0+r_out)\n            x_in = int(x0-r_out)\n            x_out = int(x0+r_out)\n            if y_in < 0:\n                y_in = 0\n            if y_out < 0:\n                y_out = 0\n            if x_in < 0:\n                x_in = 0\n            if x_out < 0:\n                x_out = 0\n            masked_image = masked_image[y_in:y_out, x_in:x_out]\n            new_mask = np.zeros(np.shape(masked_image))+1\n            for yi in range(len(masked_image)):\n                for xi in range(len(masked_image[0])):\n                    position = (xi - r_out)**2 + (yi-r_out)**2\n                    if position < (r_out)**2 and position > r_in**2:\n                        new_mask[yi, xi] = 0\n            new_mask = new_mask.astype(bool)\n            Sky_region = np.ma.masked_array(masked_image, new_mask)\n            std = np.ma.std(Sky_region)\n            return(sky, std, ann.area-pixel_count)\n\n        def signal_to_noise(source_eps, sky_std, rd, npix):\n            signal = source_eps\n            noise = np.sqrt( (source_eps  + npix *\n                              (sky_std**2 )) + npix * rd ** 2)\n            return signal / noise\n\n        FWHM_sel = max(FWHM_ordi, FWHM_extra)  # Selected FWHM\n        Aperture_radius = Aperture_scale*FWHM_sel/2\n        Annulus_radius = ANN_sacle*FWHM_sel/2\n        Ann_out = Annulus_radius+Dan\n\n        # Determine sky value by aperture\n        Aper_o = CircularAperture([xo, yo], Aperture_radius)  # Set aperture\n        sky_o, sky_std_o, area_o = skyvalue(data, yo, xo, Annulus_radius, Ann_out, masking)  # Set area determinung Sk #[count]\n\n        Aper_e = CircularAperture([xe, ye], Aperture_radius)  # Set aperture\n        sky_e, sky_std_e, area_e = skyvalue(data, ye, xe, Annulus_radius, Ann_out, masking)  # Set area determinung Sk\n\n        sky_std_o = sky_std_o*gain\n        sky_std_e = sky_std_e*gain\n\n        ########\n        masking = masking.astype(bool)\n        masked_image = np.ma.masked_array(data, masking)\n        y0, x0 = yo, xo\n        y_in = int(y0-Ann_out)\n        y_out = int(y0-Annulus_radius)\n        x_in = int(x0-Ann_out)\n        x_out = int(x0-Annulus_radius)\n        crop_masked_images = masked_image[y_in:y_out, x_in:x_out]\n        std = np.ma.std(crop_masked_images)\n\n        # Target aperture sum\n        Flux_o = aperture_photometry(data - sky_o, Aper_o, masking)['aperture_sum'][0]*gain  # in e-\n        ERR_o = np.sqrt(Flux_o + 3.14*Aperture_radius**2*(sky_std_o**2 + (RN*gain)**2))  # in e-\n        sky_o = sky_o*gain  # in e-\n        Snr_o = signal_to_noise(Flux_o, sky_std_o, RN, Aperture_radius**2*3.14)\n\n        Flux_e = aperture_photometry(data - sky_e, Aper_e, masking)['aperture_sum'][0]*gain  # in e-\n        ERR_e = np.sqrt(Flux_e + 3.14*Aperture_radius**2*(sky_std_e**2 + (RN*gain)**2))  # in e-\n        sky_e = sky_e*gain  # in e-\n        Snr_e = signal_to_noise(Flux_e, sky_std_e, RN, Aperture_radius**2*3.14)\n        snr += Snr_o + Snr_e\n\n        # ************************************************************************************* #\n        # *              Record the values for calculating Stokes parameter                   * #\n        # ************************************************************************************* #\n        I.append(Flux_e/Flux_o)\n        S_ret = (ERR_e/(Flux_e))**2 + (ERR_o/(Flux_o))**2\n        S.append(S_ret)\n        PSANG.append(psANG)\n        PA.append(pA)\n        JD_mean.append(JD)\n        INR_STR.append(iNR_STR)\n        INR_END.append(iNR_END)\n\n        # ************************************************************************************* #\n        # *                       Plot the aperture photometry                                * #\n        # ************************************************************************************* #\n        def circle(x, y, r):\n            theta = np.linspace(0, 2*np.pi, 100)\n            x1 = r*np.cos(theta)+y\n            x2 = r*np.sin(theta)+x\n            return(x2.tolist(), x1.tolist())\n\n        plot_data = np.ma.masked_array(data, masking)\n        figsize = 50\n        # im = ax[ang,0].imshow(plot_data - sky_o/gain,vmin=-50,vmax=50,cmap='seismic')\n        # xi,yi = circle(xo,yo,Aperture_radius)\n        # ax[ang,0].plot(xi,yi,color='y',lw=2)\n        # xi,yi = circle(xo,yo,Annulus_radius)\n        # ax[ang,0].plot(xi,yi ,color='c',lw=2)\n        # xi,yi = circle(xo,yo,Annulus_radius+Dan)\n        # ax[ang,0].plot(xi,yi ,color='c',lw=2)\n        # ax[ang,0].plot(xo,yo,marker='X',color='c',ms=4)\n        # ax[ang,0].set_xlim(xo-figsize,xo+figsize)\n        # ax[ang,0].set_ylim(yo-figsize,yo+figsize)\n        # ax[ang,0].set_title('Ordinary'+image_i.split('/')[-1],fontsize=14)\n        # divider = make_axes_locatable(ax[ang,0])\n        # cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n        # plt.colorbar(im,cax=cax)\n\n        # im = ax[ang,1].imshow(plot_data - sky_e/gain,vmin=-50,vmax=50,cmap='seismic')\n        # xi,yi = circle(xe, ye,Aperture_radius)\n        # ax[ang,1].plot(xi,yi,color='y',lw=2)\n        # xi,yi = circle(xe, ye,Annulus_radius)\n        # ax[ang,1].plot(xi,yi ,color='c',lw=2)\n        # xi,yi = circle(xe, ye,Annulus_radius+Dan)\n        # ax[ang,1].plot(xi,yi ,color='c',lw=2)\n        # ax[ang,1].plot(xe,ye,marker='X',color='c',ms=4)\n        # ax[ang,1].set_xlim(xe-figsize,xe+figsize)\n        # ax[ang,1].set_ylim(ye-figsize,ye+figsize)\n        # ax[ang,1].set_title('ExtaOrdinary'+image_i.split('/')[-1],fontsize=14)\n        # divider = make_axes_locatable(ax[ang,1])\n        # cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n        # plt.colorbar(im,cax=cax)\n\n        # ************************************************************************************* #\n        # *                          Save result of photometry                                * #\n        # ************************************************************************************* #\n        print(image_i.split('/')[-1])\n        Photo_Log = Photo_Log.append({'Object': header['OBJECT'],\n                                      'Filename': image_i.split('/')[-1],\n                                      'set': int(z/4)+1,\n                                      'HWPANG': header['RET-ANG2'],\n                                      'TIME': epoch,\n                                      'JD': np.mean(JD_mean),\n                                      'FWHM_o': aper_seri_o,\n                                      'FWHM_e': aper_seri_e,\n                                      'Aper [pix]': Aperture_radius,\n                                      'EXP [s]': exp,\n                                      'Ann': Annulus_radius,\n                                      'Ann_out': Ann_out,\n                                      'Flux_o': Flux_o,\n                                      'eFLux_o': ERR_o,\n                                      'Flux_e': Flux_e,\n                                      'eFLux_e': ERR_e,\n                                      'SNR_o': Snr_o,\n                                      'SNR_e': Snr_e,\n                                      'Sky_o': sky_o,\n                                      'eSky_o': sky_std_o,\n                                      'Sky_e': sky_e,\n                                      'eSky_e': sky_std_e}, ignore_index=True)\n\n    # ************************************************************************************* #\n    # *                         Calculate Stokes Parameter                                * #\n    # ************************************************************************************* #\n    PsANG_av = np.mean(PSANG)  # the average position angles of Sun-target radius vector of a set\n    PA_av = np.mean(PA)  # the average phase angle of a set\n    JD_av = np.mean(JD_mean)  # the average JD of a set\n\n    I0 = I[0]\n    I45 = I[1]\n    I22 = I[2]\n    I67 = I[3]\n\n    S0 = S[0]\n    S45 = S[1]\n    S22 = S[2]\n    S67 = S[3]\n\n    Rq = np.sqrt(I0/I45)\n    Ru = np.sqrt(I22/I67)\n\n    q = (Rq - 1)/(Rq + 1)\n    u = (Ru - 1)/(Ru + 1)\n\n    q_ran = Rq/((Rq + 1)**2)  * np.sqrt(S0 + S45)\n    u_ran = Ru/((Ru + 1)**2)  * np.sqrt(S22 + S67)\n\n    q_sys = 0\n    u_sys = 0\n\n    q_err = np.sqrt(q_ran**2 + q_sys**2)\n    u_err = np.sqrt(u_ran**2 + u_sys**2)\n\n    # ====================\n    # Correct Efficiency\n    # ====================\n    qq = q/eff\n    uu = u/eff\n\n    # random error of corrected q,u\n    qq_ran = q_ran/eff\n    uu_ran = u_ran/eff\n\n    # the systematic errors\n    qq_sys = np.abs(q)*eff_err/eff\n    uu_sys = np.abs(u)*eff_err/eff\n\n    # ====================\n    # Correc Instrumental polarization\n    # ====================\n\n    STR0, STR45, STR22, STR67 = INR_STR[0], INR_STR[1], INR_STR[2], INR_STR[3]\n    END0, END45, END22, END67 = INR_END[0], INR_END[1], INR_END[2], INR_END[3]\n\n    # averaged value of frame-reader value\n    rq = np.deg2rad((STR0 + END0 + STR45 + END45)/4.)   # Instrument star, end value ( 0,0,45,45 ) in rad\n    ru = np.deg2rad((STR22 + END22 + STR67 + END67)/4.)  # Instrument star, end value ( 22.5,22.5,67.5,67.5) in rad\n\n    qqq = qq - ((q_inst * np.cos(2*rq)) - (u_inst * np.sin(2*rq)))\n    uuu = uu - ((q_inst * np.sin(2*ru)) + (u_inst * np.cos(2*ru)))\n\n    # random error of corrected q,u\n    qqq_ran = qq_ran\n    uuu_ran = uu_ran\n\n    # the systematic errors\n    qqq_sys = np.sqrt( qq_sys**2 + (eq_inst * np.cos(2*rq))**2 +\n                       (eu_inst*np.sin(2*rq))**2 )\n    uuu_sys = np.sqrt( uu_sys**2 + (eq_inst * np.sin(2*ru))**2 +\n                       (eu_inst*np.cos(2*ru))**2 )\n\n    # ====================\n    # Transform_CelestialCoord\n    # ====================\n    theta = np.deg2rad(theta_offset)\n    the_err = np.deg2rad(err_theta)\n\n    qqqq = qqq * np.cos(2*theta) + uuu*np.sin(2*theta)\n    uuuu = -qqq * np.sin(2*theta) + uuu*np.cos(2*theta)\n\n    qqqq_ran = np.sqrt( (qqq_ran*np.cos(2*theta))**2 + (uuu_ran*np.sin(2*theta))**2 )\n    uuuu_ran = np.sqrt( (qqq_ran*np.sin(2*theta))**2 + (uuu_ran*np.cos(2*theta))**2 )\n\n    qqqq_sys = np.sqrt( (qqq_sys*np.cos(2*theta))**2 +\n                        (uuu_sys*np.sin(2*theta))**2 +\n                        (np.pi/180*2*uuuu*the_err)**2 )\n    uuuu_sys = np.sqrt( (qqq_sys*np.sin(2*theta))**2 +\n                        (uuu_sys*np.cos(2*theta))**2 +\n                        (np.pi/180*2*qqqq*the_err)**2 )\n\n    q, q_ran, q_sys, u, u_ran, u_sys = qqqq, qqqq_ran, qqqq_sys, uuuu, uuuu_ran, uuuu_sys\n\n    # ************************************************************************************* #\n    # *                       Calculate Polarimetric result                               * #\n    # ************************************************************************************* #\n    P = np.sqrt(q**2 + u**2)\n    P_ran = np.sqrt( (q*q_ran)**2 + (u*u_ran)**2 )/P\n    P_sys = np.sqrt( (q*q_sys)**2 + (u*u_sys)**2 )/P\n    theta_pol = np.rad2deg(1/2 * np.arctan2(u, q))\n\n    # Random noise correction (Wardle & Kronberg 1974)\n    if P**2 >= P_ran**2:\n        print('Random error bias correction is done.')\n        P_cor = np.sqrt(P**2 - P_ran**2)\n    elif P**2 < P_ran**2 :\n        print('Due to P < randome error, random error bias correction is NOT done.')\n        P_cor = 0\n\n    P_error = np.sqrt(P_ran**2 + P_sys**2)  # Polarization error\n\n    if P_cor != 0:\n        ran_PolAng = 1/2 * 180/3.14 * P_ran/P_cor\n        sys_PolAng = 1/2 * 180/3.14 * P_sys/P_cor\n        PolAng_error = np.sqrt(ran_PolAng**2 + sys_PolAng**2)\n    elif P_cor == 0:\n        ran_PolAng = 51.96\n        sys_PolAng = 51.96\n        PolAng_error = 51.96\n        # Naghizadeh-Khouei & Clarke 1993\n\n    if PsANG_av + 90 < 180:\n        pi = PsANG_av + 90\n    else:\n        pi = PsANG_av - 90\n\n    # Converted a polarization degree with respect to the scattering plane\n    theta_r = theta_pol - pi\n    Pr = P_cor * np.cos(2*np.deg2rad(theta_r))\n    Pol_Log = Pol_Log.append({'filename': file_name,\n                              'Filter': 'Rc',\n                              'JD': JD_av,\n                              'alpha [deg]': PA_av,\n                              'PsANG [deg]': PsANG_av,\n                              'FWHM_o': aper_seri_o,\n                              'FWHM_e': aper_seri_e,\n                              'Aper_radius [pix]': Aperture_radius,\n                              'q': q,\n                              'u': u,\n                              'ran_q': q_ran,\n                              'ran_u': u_ran,\n                              'sys_q': q_sys,\n                              'sys_u': u_sys,\n                              'PsANG': PsANG_av,\n                              'theta': theta_pol,\n                              'theta_r': theta_r,\n                              'eTheta': PolAng_error,\n                              'P': P_cor,\n                              'eP': np.sqrt(P_ran**2 + P_sys**2)},\n                             ignore_index=True)\n    plt.show()\n\n# ************************************************************************************* #\n# *                       Calculate the weighted mean                                 * #\n# ************************************************************************************* #\n\n\ndef weight(x, err):\n    x = np.array(x)\n    err = np.array(err)\n\n    w = 1/err**2\n    sumW = np.sum(w)\n    weight = w/sumW\n\n    xav = np.sum(weight*x)\n    Err = 1/np.sqrt(sumW)\n\n    return(xav, Err)\n\n\ntime_ = Time(Pol_Log['JD'][0], format='jd').iso\nq_av, ranq_av = weight(Pol_Log['q'], Pol_Log['ran_q'])\nu_av, ranu_av = weight(Pol_Log['u'], Pol_Log['ran_u'])\nsysq_av = np.mean(Pol_Log['sys_q'])\nsysu_av = np.mean(Pol_Log['sys_u'])\nerrq_av = (ranq_av**2 + sysq_av**2)**0.5\nerru_av = (ranu_av**2 + sysu_av**2)**0.5\n\nP = np.sqrt(q_av**2+u_av**2)\nran_P = np.sqrt((q_av*ranq_av)**2 + (u_av*ranu_av)**2)/P\nsys_P = np.sqrt((q_av*sysq_av)**2 + (u_av*sysu_av)**2)/P\neP = np.sqrt(ran_P**2 + sys_P**2)\n\n\n# Random noise correction (Wardle & Kronberg 1974)\nif P**2 - ran_P**2 < 0:\n    print('Random error bias correction is done.')\n    Pcor = 0\nelse:\n    print('Due to P < random error, P = 0% ')\n    Pcor = np.sqrt(P**2 - ran_P**2)\n\n# Converted a polarization degree with respect to the scattering plane\ntheta = 1/2*np.rad2deg(np.arctan2(u_av, q_av))\npsang = np.mean(Pol_Log['PsANG'])\nif psang+90 > 180:\n    pi = psang-90\nelse:\n    pi = psang + 90\n\n\nif Pcor != 0:\n    theta_ran = 1/2*180/3.14*ran_P/Pcor\n    theta_sys = 1/2*180/3.14*sys_P/Pcor\n    eTheta = np.sqrt(theta_ran**2 + theta_sys**2)\nelif Pcor == 0:\n    theta_ran = 51.96\n    theta_sys = 51.96\n    eTheta = 51.96\n    # Naghizadeh-Khouei & Clarke 1993\n\n\nPol_Log = Pol_Log.append({'filename': 'Weighted_average',\n                          'JD': np.mean(Pol_Log['JD'].values),\n                          'alpha [deg]': np.mean(Pol_Log['alpha [deg]'].values),\n                          'PsANG [deg]': np.mean(Pol_Log['PsANG [deg]'].values),\n                          'q': q_av,\n                          'u': u_av,\n                          'ran_q': ranq_av,\n                          'ran_u': ranu_av,\n                          'sys_q': sysq_av,\n                          'sys_u': sysu_av,\n                          'theta': theta,\n                          'theta_r': theta_r,\n                          'P': Pcor,\n                          'eP': eP,\n                          'Aper_radius [pix]': np.mean(Pol_Log['Aper_radius [pix]'].values),\n                          'Pr': P_cor*np.cos(np.deg2rad(theta_r*2)),\n                          'eTheta': eTheta\n                          },\n                         ignore_index=True)\n\nPol_name = ['filename', 'JD', 'alpha [deg]', 'PsANG [deg]',\n            'q', 'u', 'ran_q', 'ran_u', 'sys_q', 'sys_u',\n            'P', 'eP', 'Pr', 'theta', 'theta_r', 'eTheta',\n            'Aper_radius [pix]']\nPhot_name = ['Object', 'Filename', 'set', 'TIME', 'JD',\n             'HWPANG', 'FWHM_o', 'FWHM_e', 'EXP [s]',\n             'Aper [pix]', 'Ann', 'Ann_out', 'Flux_o',\n             'eFLux_o', 'Flux_e', 'eFLux_e', 'Sky_o',\n             'eSky_o', 'Sky_e', 'eSky_e', 'SNR_o',\n             'SNR_e']\n\nPol_Log = Pol_Log.reindex(columns=Pol_name)\nPhoto_Log = Photo_Log.reindex(columns=Phot_name)\nPol_Log = Pol_Log.round({'JD': 6, 'alpha [deg]': 2, 'PsANG [deg]': 2,\n                         'q': 4, 'u': 4, 'ran_q': 4, 'ran_u': 4,\n                         'sys_q': 4, 'sys_u': 4, 'theta': 2, 'theta_r': 2,\n                         'P': 4, 'eP': 4, 'Aper_radius [pix]': 2, 'Pr': 4,\n                         'eTheta': 2})\nPhoto_Log = Photo_Log.round({'HWPANG': 2, 'JD': 6, 'FWHM_o': 2, 'FWHM_e': 2,\n                             'Aper [pix]': 2, 'EXP [s]': 2, 'Ann': 2,\n                             'Ann_out': 2, 'Flux_o': 4, 'eFLux_o': 4,\n                             'Flux_e': 4, 'eFLux_e': 4, 'SNR_o': 2,\n                             'SNR_e': 2, 'Sky_o': 4, 'eSky_o': 4,\n                             'Sky_e': 4, 'eSky_e': 4})\nPol_Log.to_csv(os.path.join(path, 'result_Pol_{}.csv'.format(time_.split(' ')[0])))\nPhoto_Log.to_csv(os.path.join(path, 'result_Photo_{}.csv'.format(time_.split(' ')[0])))\nprint(os.path.join(path, 'result_Pol_{}.csv'.format(time_.split(' ')[0])) + ' is created.')\nprint(os.path.join(path, 'result_Photo_{}.csv'.format(time_.split(' ')[0])) + ' is created.')\n", "meta": {"hexsha": "344ed8f022a0b757bdcd59d611bc88ed708cb645", "size": 28257, "ext": "py", "lang": "Python", "max_stars_repo_path": "MSI_NOT/NO_Polarimetric_Analysis.py", "max_stars_repo_name": "ysBach/IshiguroM_etal_155140_2005UD", "max_stars_repo_head_hexsha": "37e0768f2a9dd59b3d4041c37c104d2d57e037ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-31T19:39:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-31T19:39:40.000Z", "max_issues_repo_path": "MSI_NOT/NO_Polarimetric_Analysis.py", "max_issues_repo_name": "ysBach/IshiguroM_etal_155140_2005UD", "max_issues_repo_head_hexsha": "37e0768f2a9dd59b3d4041c37c104d2d57e037ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MSI_NOT/NO_Polarimetric_Analysis.py", "max_forks_repo_name": "ysBach/IshiguroM_etal_155140_2005UD", "max_forks_repo_head_hexsha": "37e0768f2a9dd59b3d4041c37c104d2d57e037ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-26T08:19:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-26T08:19:49.000Z", "avg_line_length": 43.4055299539, "max_line_length": 128, "alphanum_fraction": 0.4701843791, "include": true, "reason": "import numpy,from astropy", "num_tokens": 7540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.28776782186926264, "lm_q1q2_score": 0.15062353373545537}}
{"text": "# MIT License\n#\n# Copyright (c) 2017 Ulrich Noebauer\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nModule providing a number of basic calculators to determine the steady-state\nstructure of line-driven hot star winds analytically. In particular, the\npredictions according to\n * Castor, Abbott and Klein 1975\n * Friend and Abbott 1986\n * Kudritzki, Pauldrach, Puls and Abbott 1989\nare included. Throughout this module, we rely heavily on the standard text\nbook on stellar winds by Lamers and Cassinelli 1999.\n\nNote\n----\nWe assume a so-called frozen-in ionization throughout the wind in all the wind\nstructure calculators (i.e. delta=0 in terms of the CAK force multipliers).\n\nReferences\n----------\n * Castor, Abbott and Klein 1975 (CAK75)\n   'Radiation-driven winds in Of stars', Astrophysical Journal,\n   1975, 195, 157-174\n * Friend and Abbott 1986 (FA86)\n   'The theory of radiatively driven stellar winds. III - Wind models with\n   finite disk correction and rotation', Astrophysical Journal,\n   1986, 311, 701-707\n * Kudritzki, Pauldrach, Puls and Abbott 1989 (KPPA89)\n   'Radiation-driven winds of hot stars. VI - Analytical solutions for wind\n   models including the finite cone angle effect', Astronomy & Astrophysics,\n   1989, 219, 205-218\n * Noebauer and Sim 2015 (NS15)\n   'Self-consistent modelling of line-driven hot-star winds with Monte Carlo\n   radiation hydrodynamics', Monthly Notices of the Royal Astronomical Society,\n   2015, 453, 3120-3134\n * Lamers and Cassinelli 1999 (LC99)\n   'Introduction to Stellar Winds', Cambridge University Press, 1999\n\"\"\"\nfrom __future__ import print_function\nimport numpy as np\nimport scipy.integrate as integ\nimport astropy.units as units\nimport astropy.constants as csts\nfrom astropy.utils.decorators import lazyproperty\n\n\ndef _test_unit(val, final_unit_string, initial_unit_string):\n    \"\"\"helper routine to add unit to a quantity and convert to different units\n\n    If val is not yet an astropy.units.quantity, it is assumed that it is\n    given in units specified by the initial_unit_string. The input is then\n    returned after converting to the units given by the final_unit_string.\n\n    Parameters\n    ----------\n    val : float, int, np.ndarray\n        scalar or vector input, can either already be an astropy quantity or\n        not\n    final_unit_string : str\n        string describing the desired final units for the input\n    initial_unit_string : str\n        string describing the assumed initial units of the input\n\n    Returns\n    -------\n    res : astropy.units.quantity\n        input converted to units given by final_unit_string\n    \"\"\"\n    try:\n        val.to(final_unit_string)\n    except AttributeError:\n        val = val * units.Unit(initial_unit_string)\n    res = val.to(final_unit_string)\n\n    return res\n\n\nclass StarBase(object):\n    \"\"\"Base class containing the fundamental properties of the central star\n\n    Parameters\n    ---------\n    mass : float, astropy.units.quantity\n        stellar mass, if dimensionless, it is assumed to be in units of solar\n        masses (default 52.5)\n    lum : float, astropy.units.quantity\n        stellar luminosity, if dimensionless, it is assumed to be in units of\n        solar luminosities (default 1e6)\n    teff : float, astropy.units.quantity\n        effective temperature, if dimensionless, it is assumed to be Kelvin\n        (default 4.2e4)\n    gamma : float\n        Eddington factor due to electron scattering (default 0)\n    sigma : float, astropy.units.quantity\n        reference specific electron scattering cross section, if dimensionless\n        it is assumed to be in units of cm^2/g (default 0.3)\n    \"\"\"\n    def __init__(self, mass=52.5, lum=1e6, teff=4.2e4, gamma=0, sigma=0.3):\n\n        self.mass = mass\n        self.lum = lum\n        self.teff = teff\n        self.sigma = sigma\n        self.gamma = gamma\n\n    @property\n    def mass(self):\n        return self._mass\n\n    @mass.setter\n    def mass(self, val):\n        val = _test_unit(val, \"g\", \"solMass\")\n        self._mass = val\n\n    @property\n    def lum(self):\n        return self._lum\n\n    @lum.setter\n    def lum(self, val):\n        val = _test_unit(val, \"erg/s\", \"solLum\")\n        self._lum = val\n\n    @property\n    def teff(self):\n        return self._teff\n\n    @teff.setter\n    def teff(self, val):\n        val = _test_unit(val, \"K\", \"K\")\n        self._teff = val\n\n    @property\n    def sigma(self):\n        return self._sigma\n\n    @sigma.setter\n    def sigma(self, val):\n        val = _test_unit(val, \"cm^2/g\", \"cm^2/g\")\n        self._sigma = val\n\n    @lazyproperty\n    def rad(self):\n        \"\"\"stellar radius\"\"\"\n        rad = np.sqrt(self.lum /\n                      (4 * np.pi * csts.sigma_sb * self.teff**4))\n        return rad\n\n    @lazyproperty\n    def vth(self):\n        \"\"\"thermal velocity (see LC99, eqs. 8.8, 8.83)\"\"\"\n        vth = np.sqrt(2. * self.teff * csts.k_B / csts.u)\n        return vth\n\n    @lazyproperty\n    def vesc(self):\n        \"\"\"escape velocity from stellar surface, accounting for electron\n        scattering (see LC99, eq. 2.39)\"\"\"\n        vesc = np.sqrt(2. * csts.G * self.mass * (1. - self.gamma) / self.rad)\n        return vesc\n\n\nclass WindBase(object):\n    \"\"\"Base class containing the fundamental properties of the wind\n\n    Parameters\n    ----------\n    alpha : float\n        CAK force multiplier parameter, see LC99, eq. 8.86 (default 0.6)\n    k : float\n        CAK force multiplier parameter, see LC99, eq. 8.86 (default 0.5)\n    \"\"\"\n    def __init__(self, alpha=0.6, k=0.5):\n\n        self.alpha = alpha\n        self.k = k\n\n\nclass WindStructureBase(object):\n    \"\"\"Base class describing the basic structure of a star+wind system\n\n\n\n    Parameters\n    ----------\n    mstar : float, astropy.units.quantity\n        stellar mass, see StarBase for details (default 52.5)\n    lstar : float, astropy.units.quantity\n        stellar luminosity, see StarBase for details (default 1e6)\n    teff : float, astropy.units.quantity\n        effective temperature, see StarBase for details (default 4.2e4)\n    alpha : float\n        force multiplier parameter, see WindBase for details (default, 0.6)\n    k : float\n        force multiplier parameter, see WindBase for details (default, 0.5)\n    gamma : float\n        Eddington factor, see StarBase for details (default 0)\n    sigma : float, astropy.units.quantity\n        reference electron scattering cross section, see StarBase for details\n        (default 0.3)\n    \"\"\"\n    def __init__(self, mstar=52.5, lstar=1e6, teff=4.2e4, alpha=0.6, k=0.5,\n                 gamma=0, sigma=0.3):\n\n        self.star = StarBase(mass=mstar, lum=lstar, teff=teff, gamma=gamma,\n                             sigma=sigma)\n        self.wind = WindBase(alpha=alpha, k=k)\n\n    @lazyproperty\n    def eta(self):\n        \"\"\"wind efficiency (see LC99, eq. 8.20)\"\"\"\n        eta = (self.mdot * self.vterm * csts.c / self.star.lum).to(\"\").value\n        return eta\n\n    @lazyproperty\n    def t(self):\n        \"\"\"CAK dimensionless optical depth, c.f. LC99, eq. 8.82 and 8.104\"\"\"\n        t = (self.mdot * self.star.sigma * self.star.vth /\n             (2. * np.pi * self.vterm**2 * self.star.rad)).to(\"\")\n        return t\n\n    @lazyproperty\n    def m(self):\n        \"\"\"CAK force multiplier, assuming frozen-in ionization, c.f. LC99, eq.\n        8.86 with delta=0\"\"\"\n        m = self.wind.k * self.t**(-self.wind.alpha)\n        return m\n\n\nclass BaseVelocityDensityMixin(object):\n    \"\"\"Mixin class providing routines to calculate the wind velocity and\n    density structure\"\"\"\n    def v(self, x):\n        \"\"\"calculate wind velocity according to CAK at given location\n\n        C.f. LC99, eq. 8.104\n\n        Parameters\n        ----------\n        x : float, np.ndarray\n            dimensionless position, i.e. r/Rstar\n\n        Returns\n        -------\n        v : float, np.ndarry\n            wind velocity\n        \"\"\"\n\n        return (self.vterm * np.sqrt(1. - 1. / x)).to(\"km/s\")\n\n    def rho(self, x):\n        \"\"\"calculate wind density at given location\n\n        C.f. LC99, eq. 3.1\n\n        Parameters\n        ----------\n        x : float, np.ndarray\n            dimensionless position, i.e. r/Rstar\n\n        Returns\n        -------\n        rho : float, np.ndarry\n            wind density\n        \"\"\"\n\n        r = self.star.rad * x\n\n        return (self.mdot /\n                (4. * np.pi * r**2 * self.v(x))).to(\"g/cm^3\")\n\n\nclass BaseCakStructureMixin(object):\n    \"\"\"Mixin class providing the CAK mass loss rate and terminal wind speed\"\"\"\n\n    @lazyproperty\n    def mdot_cak(self):\n        \"\"\"Mass-loss rate according to CAK75, see LC99, eq. 8.105\"\"\"\n\n        mdot_cak = ((4. * np.pi / (self.star.sigma * self.star.vth)) *\n                    (self.star.sigma / (4. * np.pi))**(1. / self.wind.alpha) *\n                    ((1. - self.wind.alpha) / self.wind.alpha)**(\n                        (1. - self.wind.alpha) / self.wind.alpha) *\n                    (self.wind.alpha * self.wind.k)**(1. / self.wind.alpha) *\n                    (self.star.lum / csts.c)**(1. / self.wind.alpha) *\n                    (csts.G * self.star.mass * (1. - self.star.gamma))**(\n                        (self.wind.alpha - 1.) / self.wind.alpha))\n        return mdot_cak.to(\"Msun/yr\")\n\n    @lazyproperty\n    def vterm_cak(self):\n        \"\"\"Terminal wind speed according to CAK75, see LC99, eq. 8.104\"\"\"\n\n        vterm_cak = (np.sqrt(self.wind.alpha / (1. - self.wind.alpha)) *\n                     self.star.vesc)\n\n        return vterm_cak.to(\"km/s\")\n\n\nclass WindStructureCak75(WindStructureBase, BaseCakStructureMixin,\n                         BaseVelocityDensityMixin):\n    \"\"\"Wind Structure Calculator based on the approach by CAK75.\n\n    The wind structure is determined based on a CAK line-driving force,\n    assuming a frozen-in ionization state and a central point source.\n\n    Paramters\n    ---------\n    see WindStructureBase\n    \"\"\"\n    def __init__(self, mstar=52.5, lstar=1e6, teff=4.2e4, alpha=0.6, k=0.5,\n                 gamma=0, sigma=0.3):\n        super(WindStructureCak75, self).__init__(mstar=mstar, lstar=lstar,\n                                                 teff=teff, alpha=alpha,\n                                                 k=k, gamma=gamma,\n                                                 sigma=sigma)\n\n    @property\n    def mdot(self):\n        \"\"\"mass loss rate, equal to basic CAK mass loss rate\"\"\"\n        return self.mdot_cak.to(\"Msun/yr\")\n\n    @property\n    def vterm(self):\n        \"\"\"terminal wind speed, equal to basic CAK terminal velocity\"\"\"\n        return self.vterm_cak.to(\"km/s\")\n\n\nclass WindStructureKppa89(WindStructureBase, BaseCakStructureMixin,\n                          BaseVelocityDensityMixin):\n    \"\"\"Wind Structure Calculator based on the approach by KPPA89.\n\n    The wind structure is determined based on a CAK line-driving force,\n    assuming a frozen-in ionization state but taking the finite size of the\n    central star into account.\n\n    Paramters\n    ---------\n    see WindStructureBase\n    beta : float\n        exponent for the beta-type velocity law (default 0.8, see LC99, sec.\n        8.9.2 iii)\n    \"\"\"\n    def __init__(self, mstar=52.5, lstar=1e6, teff=4.2e4, alpha=0.6, k=0.5,\n                 gamma=0, sigma=0.3, beta=0.8):\n        super(WindStructureKppa89, self).__init__(mstar=mstar, lstar=lstar,\n                                                  teff=teff, alpha=alpha,\n                                                  k=k, gamma=gamma,\n                                                  sigma=sigma)\n\n        self.f1 = 1. / (self.wind.alpha + 1.)\n        self.beta = beta\n\n    @lazyproperty\n    def mdot(self):\n        \"\"\"mass loss rate, see KPPA89, eq. 31\"\"\"\n\n        mdot = self.f1**(1. / self.wind.alpha) * self.mdot_cak\n\n        return mdot.to(\"Msun/yr\")\n\n    @lazyproperty\n    def vterm(self):\n        \"\"\"terminal wind speed, see KPPA89, eq. 39\"\"\"\n\n        vterm = self.vterm_cak * np.sqrt(integ.quad(self.z, 0, 1)[0])\n\n        return vterm.to(\"km/s\")\n\n    def h(self, x):\n        \"\"\"see KPPA89, eq. 14\"\"\"\n\n        return (x - 1.) / self.beta\n\n    def f(self, x):\n        \"\"\"see KPPA89, eqs. 16, 15\"\"\"\n\n        return (1. / (self.wind.alpha + 1.) * x**2 / (1. - self.h(x)) *\n                (1. - (1. - 1. / x**2 + self.h(x) / x**2)**(\n                    self.wind.alpha + 1.)))\n\n    def fn(self, x):\n        \"\"\"see KPPA89, eq. 35\"\"\"\n\n        return self.f(x) / self.f1\n\n    def z(self, u):\n        \"\"\"see KPPA89, eq. 36\"\"\"\n\n        x = 1. / u\n        z = (self.fn(x)**(1. / (1. - self.wind.alpha)) *\n             (1. + np.sqrt(2. / self.wind.alpha *\n                           (1. - (1. / self.fn(x))**(\n                               1. / (1. - self.wind.alpha))))))\n        return z\n\n    def _v_scalar(self, x):\n        \"\"\"see KPPA89, eq. 36\"\"\"\n\n        u = 1. / x\n        I = integ.quad(self.z, u, 1)[0]\n        vesc2 = (2. * csts.G * self.star.mass *\n                 (1. - self.star.gamma) / self.star.rad)\n        v = np.sqrt(self.wind.alpha / (1. - self.wind.alpha) * vesc2 * I).to(\n            \"km/s\")\n\n        return v.value\n\n    def v(self, x):\n        \"\"\"calculate wind velocity according to KPPA89 at given location\n\n        Parameters\n        ----------\n        x : float, np.ndarray\n            dimensionless position, i.e. r/Rstar\n\n        Returns\n        -------\n        v : float, np.ndarry\n            wind velocity\n        \"\"\"\n\n        if type(x) is np.ndarray:\n            v = np.array([self._v_scalar(xi) for xi in x])\n        else:\n            v = self._v_scalar(x)\n\n        v = v * units.km / units.s\n        return v.to(\"km/s\")\n\n\nclass WindStructureFa86(WindStructureBase, BaseCakStructureMixin,\n                        BaseVelocityDensityMixin):\n    \"\"\"Wind Structure Calculator based on the approach by FA86.\n\n    The wind structure is determined based on a CAK line-driving force,\n    assuming a frozen-in ionization state but taking the finite size of the\n    central star into account. All expressions for the wind properties result\n    from fits to the numerical simulations as presented by FA86.\n\n    Paramters\n    ---------\n    see WindStructureBase\n    \"\"\"\n    def __init__(self, mstar=52.5, lstar=1e6, teff=4.2e4, alpha=0.6, k=0.5,\n                 gamma=0, sigma=0.3):\n        super(WindStructureFa86, self).__init__(mstar=mstar, lstar=lstar,\n                                                teff=teff, alpha=alpha,\n                                                k=k, gamma=gamma,\n                                                sigma=sigma)\n\n    @lazyproperty\n    def mdot(self):\n        \"\"\"see FA86, eq. 9\"\"\"\n\n        mdot = (self.mdot_cak * 0.5 *\n                (self.star.vesc / (1e3 * units.km / units.s))**(-0.3))\n\n        return mdot.to(\"Msun/yr\")\n\n    @lazyproperty\n    def vterm(self):\n        \"\"\"see FA86, eq. 8\"\"\"\n\n        vterm = (self.star.vesc * 2.2 * self.wind.alpha /\n                 (1. - self.wind.alpha) *\n                 (self.star.vesc / (1e3 * units.km / units.s))**0.2)\n\n        return vterm.to(\"km/s\")\n\n    def v(self, x):\n        \"\"\"calculate wind velocity according to KPPA89 at given location\n\n        See FA86, eq. 11\n\n        Parameters\n        ----------\n        x : float, np.ndarray\n            dimensionless position, i.e. r/Rstar\n\n        Returns\n        -------\n        v : float, np.ndarry\n            wind velocity\n        \"\"\"\n        v = self.vterm * (1. - 1. / x)**(0.8)\n\n        return v.to(\"km/s\")\n\n\ndef example():\n    \"\"\"Example application of the wind structure calculators.\n\n    The parameters are adopted from NS15, table 3 and are appropriate for the\n    O star zeta-Puppis.\n    \"\"\"\n\n    import matplotlib\n    import os\n    if \"DISPLAY\" not in os.environ:\n        matplotlib.use(\"TkAgg\")\n    import matplotlib.pyplot as plt\n    plt.rcParams[\"text.usetex\"] = False\n\n    mstar = 52.5 * units.solMass\n    lstar = 1e6 * units.solLum\n    teff = 4.2e4 * units.K\n    sigma = 0.3 * units.cm**2 / units.g\n\n    k = 0.381\n    alpha = 0.595\n    gamma = 0.502\n\n    x = np.logspace(-2, 2, 512) + 1\n\n    wind_cak75 = WindStructureCak75(mstar=mstar, lstar=lstar, teff=teff, k=k,\n                                    alpha=alpha, gamma=gamma, sigma=sigma)\n    wind_fa86 = WindStructureFa86(mstar=mstar, lstar=lstar, teff=teff, k=k,\n                                  alpha=alpha, gamma=gamma, sigma=sigma)\n    wind_kppa89 = WindStructureKppa89(mstar=mstar, lstar=lstar, teff=teff, k=k,\n                                      alpha=alpha, gamma=gamma, sigma=sigma)\n\n    fig = plt.figure(figsize=(10, 10))\n    fig.subplots_adjust(wspace=0.3, hspace=0.3)\n\n    plt.subplot(221)\n    plt.plot(x, wind_cak75.v(x), label=\"CAK75\")\n    plt.plot(x, wind_fa86.v(x), ls=\"dashed\", label=\"FA86\")\n    plt.plot(x, wind_kppa89.v(x), ls=\"dashdot\", label=\"KPPA86\")\n    plt.yscale(\"log\")\n    plt.ylim([1e2, 3e3])\n    plt.xlim([0.8, 10])\n    plt.xlabel(r\"$r/R_{\\star}$\")\n    plt.ylabel(r\"$v$ [km/s]\")\n    plt.legend(frameon=False)\n\n    plt.subplot(222)\n    plt.plot(x - 1, wind_cak75.v(x) / wind_cak75.vterm, label=\"CAK75\")\n    plt.plot(x - 1, wind_fa86.v(x) / wind_fa86.vterm, ls=\"dashed\",\n             label=\"FA86\")\n    plt.plot(x - 1, wind_kppa89.v(x) / wind_kppa89.vterm, ls=\"dashdot\",\n             label=\"KPPA86\")\n    plt.xscale(\"log\")\n    plt.xlim([1e-2, 1e2])\n    plt.ylim([0, 1])\n    plt.xlabel(r\"$r/R_{\\star} - 1$\")\n    plt.ylabel(r\"$v/v_{\\infty}$\")\n\n    plt.subplot(223)\n    plt.plot(x, wind_cak75.rho(x), label=\"CAK75\")\n    plt.plot(x, wind_fa86.rho(x), ls=\"dashed\", label=\"FA86\")\n    plt.plot(x, wind_kppa89.rho(x), ls=\"dashdot\", label=\"KPPA86\")\n    plt.yscale(\"log\")\n    plt.ylim([1e-15, 1e-10])\n    plt.xlim([0.8, 10])\n    plt.xlabel(r\"$r/R_{\\star}$\")\n    plt.ylabel(r\"$\\rho$ $[\\mathrm{g\\,cm^{-3}}]$\")\n\n    plt.subplot(224)\n    plt.plot(x, wind_cak75.mdot * np.ones(len(x)))\n    plt.plot(x, wind_fa86.mdot * np.ones(len(x)), ls=\"dashed\")\n    plt.plot(x, wind_kppa89.mdot * np.ones(len(x)), ls=\"dashdot\")\n    plt.yscale(\"log\")\n    plt.xlim([0.8, 10])\n    plt.ylim([1e-5, 1e-4])\n    plt.xlabel(r\"$r/R_{\\star}$\")\n    plt.ylabel(r\"$\\dot M$ $[\\mathrm{M_{\\odot}\\,yr^{-1}}]$\")\n    fig.savefig(\"wind_structure_example.pdf\")\n    plt.show()\n\n\nif __name__ == \"__main__\":\n\n    example()\n", "meta": {"hexsha": "4c30dff04ef4e34c95a62a20adb70f17356d6b2f", "size": 19134, "ext": "py", "lang": "Python", "max_stars_repo_path": "wind_structure/wind_structure.py", "max_stars_repo_name": "unoebauer/public-astro-tools", "max_stars_repo_head_hexsha": "765efd02a595fa42a0692114fe448f2457674828", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-01-09T14:10:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T16:38:20.000Z", "max_issues_repo_path": "wind_structure/wind_structure.py", "max_issues_repo_name": "unoebauer/public-astro-tools", "max_issues_repo_head_hexsha": "765efd02a595fa42a0692114fe448f2457674828", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-04-06T14:49:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-06T14:49:16.000Z", "max_forks_repo_path": "wind_structure/wind_structure.py", "max_forks_repo_name": "unoebauer/public-astro-tools", "max_forks_repo_head_hexsha": "765efd02a595fa42a0692114fe448f2457674828", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-01-10T10:30:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T16:45:38.000Z", "avg_line_length": 32.2664418212, "max_line_length": 79, "alphanum_fraction": 0.5878018188, "include": true, "reason": "import numpy,import scipy,import astropy,from astropy", "num_tokens": 5246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.15062353053829422}}
{"text": "# Python 3.5\n# Script for MetalSilicate python library\n# Copyright Kayla Iacovino\n# This script contains pandas dataframes with activity coefficient data digitized from the Steelmaking Data Source Book\n\nimport pandas as pd\n\n# These hard-coded pandas DataFrames are generated from an Excel Spreadsheet and hardcoded for easier access.\n\"\"\"\nThe code to generate these:\nimport pandas as pd\nimport numpy as np\nactivity_coeffs_df = pd.read_excel('ActivityCoeffs_and_InteractionParams.xlsx', sheet_name='ActivityCoefficients')\nactivity_coeffs_df.fillna(\"No Data\")\n\nimport math\nf = open(\"hard_coded_activity_coefficients.py\",\"w+\")\ncols = ['i', 'Element_State', 'Fe_State', 'gamma_naught_i', 'Temp_K', 'DeltaG_J_per_g-atom', 'TempRange_K', 'Ref', 'Year', 'Note']\n\nf.write (\"\\n\")\nf.write(\"activity_coeffs = pd.DataFrame({\\n\")\nfor col in cols:\n\titerno = 1\n\tf.write(\"'\" + (str(col)+\"': [\"))\n\tfor index, row in activity_coeffs_df.iterrows():\n\t\ttry:\n\t\t\tvalue = float(row[col])\n\t\t\tif str(value) == 'nan':\n\t\t\t\tf.write(\"'No Data'\")\n\t\t\telse:\n\t\t\t\tf.write(str(value))\n\t\texcept:\n\t\t\tf.write(\"'\" + str(row[col]) + \"'\")\n\t\tif iterno < len(activity_coeffs_df.index):\n\t\t\tf.write(\",\")\n\t\titerno += 1\n\tf.write(\"], \\n\")\nf.write(\" }).set_index('i') \\n\")\n\n\n##NOTE! Delete the final comma at the end of the final column.\n\n##Reminder: to look up a value, use syntax: activity_coeffs.loc['Ag']['gamma_naught_i']\n\"\"\"\n\n\nactivity_coeffs = pd.DataFrame({\n'i': ['Ag','Al','Al_delta','B','C','C_austenite','C_ferrite','Ca','Ce','Co','Cr','Cr_solid','Cu','H','H_delta','H_austenite','H_ferrite','La','Mn','Mo','Mo_solid','N','N_delta','N_austenite','N_ferrite','Nb','Nb','Ni','O','P','Pb','S','Si','Sn','Ta','Ti','Ti_solid','U','V','V_solid','W','W_solid','Zr','Zr_solid'], \n'Element_State': ['l','l','l','s','gr','gr','gr','l','l','l','l','s','l','g','g','g','g','l','l','l','s','g','g','g','g','l','s','l','g','g','l','g','l','l','l','l','s','l','l','s','l','s','l','s'], \n'Fe_State': ['liquid iron','liquid iron','delta iron','liquid iron','liquid iron','austenite','ferrite','liquid iron','liquid iron','liquid iron','liquid iron','liquid iron','liquid iron','liquid iron','delta iron','austenite','ferrite','liquid iron','liquid iron','liquid iron','liquid iron','liquid iron','delta iron','austenite','ferrite','liquid iron','liquid iron','liquid iron','liquid iron','liquid iron','liquid iron','liquid iron','liquid iron','liquid iron','liquid iron','liquid iron','liquid iron','liquid iron','liquid iron','liquid iron','liquid iron','liquid iron','liquid iron','liquid iron'], \n'gamma_naught_i': [200.0,0.049,0.027,0.022,0.538,7.49,313.0,2270.0,0.322,0.55,1.0,1.14,8.58,'–','–','–','–',9.3,1.44,1.0,2.2,'–','–','–','–',0.2,1.4,0.66,'–','–',837.0,'–',0.0013,2.58,0.04,0.004,0.009,0.027,0.08,0.1,1.0,7.6,0.037,0.043], \n'Temp_K': [1873.0,1873.0,1673.0,1873.0,1873.0,1273.0,1073.0,1880.0,1873.0,1873.0,1873.0,1873.0,1873.0,1873.0,1773.0,1273.0,1073.0,1873.0,1843.0,1823.0,1823.0,1873.0,1773.0,1273.0,1073.0,1873.0,1873.0,1873.0,1873.0,1873.0,1873.0,1873.0,1873.0,1873.0,1873.0,1873.0,1873.0,1873.0,1873.0,1873.0,1873.0,1873.0,1873.0,1873.0], \n'DeltaG_J_per_g-atom': ['82400-43.76T','-17100-19.4T','-17900-19.3T','-65300-21.55T','17230-39.87T','72180+52.05T*logT-227.03T','83720-55.76T','No Data','-16700-46.44T','No Data','-37.70T','19200-46.86T','33500-39.37T','36460+30.46T','28650+45.35T','22630+45.35T','28650+45.35T','125,900-94.6T','No Data','No Data','No Data','9916+20.17T','29090+19.91T','-8620+37.42T','29090+19.1T','No Data','23000-52.3T','-20900-31.1T','-117100-3.39T','-157700+5.4T','No Data','-125100+18.5T','-131500-17.24T','No Data','No Data','No Data','No Data','-56100-50.3T','-42300-36.0T','-20700-45.6T','-48.1T','No Data','-51000-42.38T','-34700-50.00T'], \n'TempRange_K': ['No Data','m.p.–1873','1673–m.p.','No Data','1773–2073','1773–1673','923–1073','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data','No Data'], \n'Ref': [2.0,6.0,6.0,2.0,90.0,76.0,100.0,17.0,102.0,203.0,2.0,2.0,2.0,22.0,3434.0,434.0,434.0,282.0,288.0,436.0,436.0,437.0,438.0,439.0,438.0,440.0,2.0,2.0,360.0,441.0,41.0,442.0,2.0,513.0,440.0,440.0,385.0,2.0,2.0,2.0,2.0,436.0,2.0,2.0], \n'Year': [1974.0,1977.0,1977.0,1974.0,1962.0,1970.0,1967.0,1964.0,1977.0,1978.0,1974.0,1974.0,1974.0,1963.0,1950.0,1950.0,1950.0,1977.0,1982.0,1984.0,1984.0,1982.0,1973.0,1955.0,1973.0,1973.0,1974.0,1974.0,1959.0,1980.0,1971.0,1981.0,1974.0,1981.0,1973.0,1973.0,1984.0,1974.0,1974.0,1974.0,1974.0,1984.0,1974.0,1974.0], \n'Note': ['From solubility data, regular solution assumed','From solubility data, regular solution assumed','No Data','No Data','No Data','No Data','No Data','No Data','No Data','log(gammaCO) = -0.257N^2_Fe','Ideal solution assumed','No Data','No Data','1/2H2','1/2H2','1/2H2','1/2H2','No Data','No Data','No Data','±0.17','1/2N2','1/2N2','1/2N2','1/2N2','No Data','No Data','No Data','1/2O2; Data were combined with deltaG_0 = -251877+58.325T for reaction H2(g) + 1/2O2(g) = H2O(g) [14]','1/2P2','No Data','1/2S2','No Data','Mass analysis','Calculated value','No Data','Calculated value','Regular solution assumed','No Data','No Data','No Data','±1.1','Gamma_0 Zr assumed equal to Gamma_0 Ti and regular solution assumed','No Data'] \n }).set_index('i') \n\n\n", "meta": {"hexsha": "e906d3aadcb784ddd16591212ab88820d5f9676b", "size": 5522, "ext": "py", "lang": "Python", "max_stars_repo_path": "fO2calculate/activitycoefficients.py", "max_stars_repo_name": "kaylai/MetalSilicateFO2", "max_stars_repo_head_hexsha": "d13ec5441c2ea5986bbf34198c40bcee1d8c99f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fO2calculate/activitycoefficients.py", "max_issues_repo_name": "kaylai/MetalSilicateFO2", "max_issues_repo_head_hexsha": "d13ec5441c2ea5986bbf34198c40bcee1d8c99f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fO2calculate/activitycoefficients.py", "max_forks_repo_name": "kaylai/MetalSilicateFO2", "max_forks_repo_head_hexsha": "d13ec5441c2ea5986bbf34198c40bcee1d8c99f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 90.5245901639, "max_line_length": 733, "alphanum_fraction": 0.6443317639, "include": true, "reason": "import numpy", "num_tokens": 2266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.281405613455665, "lm_q1q2_score": 0.15057970156683398}}
{"text": "'''\nA class that schedules scans submitted by clients.\n\nAuthor: Nathan Rowley\nDate: August 2018\n'''\n\nfrom astropy.coordinates import SkyCoord, EarthLocation, AltAz\nfrom astropy.time import Time\nfrom astropy import units as u\nfrom srtutility.NTPTime import NTPTime\nimport sqlite3\nimport re\nimport datetime\nimport pytz\nfrom astral import Astral\n\n\nclass Schedule:\n\n\n\t# Initializes a Schedule instance for building scan schedules.\n\t#\n\t# :param starttime: start time of the schedule period in unix time\n\t# :param endtime: end time of the schedule period in unix time\n\tdef __init__(self, starttime, endtime):\n\n\t\tstartblock = self.Block(None, starttime, starttime)\t\t\t# create Blocks to mark the start and end of the schedule\n\n\t\tendblock = self.Block(None, endtime, endtime)\n\n\t\tself.schedule = [startblock, endblock]\n\t\t\n\t\tself.localtz = pytz.timezone('America/Chicago')\t\t# set local timezone for display time conversions\n\t\t\n\t\tself.database_location = '../srtdatabase/srtdata.db'\n\n\n\t# Internal class for storing scan and time info in a Schedule\n\t#\n\t# :param scanid: the id of the scan in this block, or None if the block is an endmarker\n\t# :param starttime: start time of the scan in unix time\n\t# :param endtime: end time of the scan in unix time\n\tclass Block:\n\n\t\tdef __init__(self, scanid, starttime, endtime):\n\n\t\t\tself.scanid = scanid\n\t\t\tself.starttime = starttime\n\t\t\tself.endtime = endtime\n\n\n\t# Method for adding a scan to the schedule. Inserts the scan at the earliest possible valid time.\n\t#\n\t# :param scanid: the id of the scan to be added to the schedule\n\t# :param curtime: the current unix time\n\t# :return status: the status of the scan indicating success or failure to schedule\n\tdef schedulescan(self, scanid, curtime):\n\n\t\tsrtdb = sqlite3.connect(self.database_location)\t\t\t# establish a connection and cursor into the database\n\t\tsrtdb.row_factory = sqlite3.Row\n\t\tcur = srtdb.cursor()\n\n\t\tscanparams = cur.execute(\"SELECT * FROM SCANPARAMS WHERE ID = ?\", (scanid,)).fetchone()\n\n\t\tduration = re.split('[hms]', scanparams['duration'])\t\t\t\t\t\t\t\t# get duration values of scan\n\n\t\tseconds = int(duration[0]) * 60 * 60 + int(duration[1]) * 60 + int(duration[2])\t\t# calculate durationin seconds\n\n\t\tif curtime > self.schedule[0].endtime:\n\n\t\t\tstarttime = curtime + 300\t\t\t\t\t\t# start time is the current time if past the start of night\n\n\t\telse:\n\n\t\t\tstarttime = self.schedule[0].endtime + 300\t\t# start time of new Block is after the first Block\n\n\t\tendtime = starttime + seconds\n\n\t\tscantype = scanparams['type']\n\n\t\tprint(str(starttime) + ' ' + str(endtime) + ' ' + scanparams['ras'] + ' ' + scanparams['dec'] + ' ' + scantype)\n\n\t\tstatus = 'durationerror'\n\n\t\tprint('attempting to schedule a scan')\n\n\t\tfor i in range(len(self.schedule) - 1):\t\t\t\t\t# loops through the spaces between each Block in the schedule\n\n\t\t\tprint('checking for space after block ' + str(i))\n\n\t\t\twhile starttime >= self.schedule[i].endtime + 300 and endtime <= self.schedule[i+1].starttime - 300:\t# loops through five-minute steps of the time between two blocks (padded by five minutes on either side)\n\n\t\t\t\tprint('there is space, checking for validity')\n\n\t\t\t\tresult = self.checkscan(scanparams['ras'], scanparams['dec'], scantype, starttime, endtime)\t\t# check to see if the scan is valid within a particular time window\n\n\t\t\t\tprint(result)\n\n\t\t\t\tif status == 'durationerror' or status == 'positionerror':\t\t# error hierarchy is movebounds > position > duration\n\n\t\t\t\t\tstatus = result\n\n\t\t\t\tif result == 'scheduled':\t\t# if the scan is valid, create a new Block for the scan and insert it into the schedule\n\n\t\t\t\t\tprint('found a valid spot!')\n\n\t\t\t\t\tstatus = result\n\n\t\t\t\t\tnewblock = Schedule.Block(scanid, starttime, endtime)\n\t\t\t\t\t\n\t\t\t\t\tstarttime = datetime.datetime.fromtimestamp(starttime, pytz.utc).astimezone(self.localtz).strftime('%H:%M')\t# convert time values to local time strings\n\t\t\t\t\tendtime = datetime.datetime.fromtimestamp(endtime, pytz.utc).astimezone(self.localtz).strftime('%H:%M')\n\n\t\t\t\t\tcur.execute(\"INSERT INTO SCHEDULE VALUES (?,?,?)\", (scanid, starttime, endtime))\t# update the schedule and scan status in the db\n\t\t\t\t\tsrtdb.commit()\n\n\t\t\t\t\tsrtdb.close()\n\n\t\t\t\t\tself.schedule.insert(i+1, newblock)\n\n\t\t\t\t\treturn status\n\n\t\t\t\tstarttime += 300\t\t\t# if scan is not valid within the time frame, adjust the frame five minutes forward\n\t\t\t\tendtime += 300\n\n\t\t\tstarttime = self.schedule[i+1].endtime + 300\t# update starttime to after the next Block\n\n\t\t\tif starttime < curtime:\t\t\t\t\t\t\t# if curtime not yet reached, reset starttime to curtime\n\n\t\t\t\tstarttime = curtime + 300\n\n\t\t\tendtime = starttime + seconds\t\t\t\t\t# update endtime to reflect new starttime\n\n\t\tprint('couldn\\'t find a spot. error code: ' + status)\n\n\t\tsrtdb.close()\n\n\t\treturn status\n\t\t\n\n\t# Method that removes a scan from the schedule with an id matching scanid.\n\t#\n\t# :param scanid: the id of the scan to be removed\n\t# :return:\n\tdef deschedulescan(self, scanid):\n\n\t\tfor i in range(len(self.schedule - 2)):\n\n\t\t\tif self.schedule[i].scanid == scanid:\n\n\t\t\t\tprint('scan removed from schedule')\n\n\t\t\t\tdel self.schedule[i]\n\t\t\t\tbreak\n\n\n\t# Helper method for checking the validity of a scan.\n\t# Checks that the scan's position is in the sky and that the scan does not go out of movement bounds.\n\t#\n\t# :param ras: right ascension of the scan to be checked\n\t# :param dec: declination of the scan to be checked\n\t# :param scantype: a string designating the type of scan\n\t# :param starttime: start time of the scan in unix time\n\t# :param endtime: end time of the scan in unix time\n\t# :return: a string indicating the status of the scan\n\tdef checkscan(self, ras, dec, scantype, starttime, endtime):\n\n\t\tsrtdb = sqlite3.connect(self.database_location)\t# establish a connection and cursor into the database\n\t\tsrtdb.row_factory = sqlite3.Row\n\t\tcur = srtdb.cursor()\n\n\t\tconfigdata = cur.execute(\"SELECT * FROM CONFIG\").fetchone()\t\t# retrieve config data from the database\n\n\t\tposition = SkyCoord(ras, dec, frame = 'icrs')\t\t\t\t\t# convert position into astropy SkyCoord object for coord transformation\n\n\t\tlocation = EarthLocation(lat = configdata['lat'], lon = configdata['lon'], height = configdata['height']) \t# convert location into astropy EarthLocation\n\n\t\tsrtdb.close()\n\n\t\tmiddletime = (starttime + endtime) / 2\n\n\t\tstarttime = Time(starttime, format = 'unix')\t\t\t\t\t\t# convert times into astropy Time objects\n\t\tstartframe = AltAz(location = location, obstime = starttime)\t\t# create astropy AltAz frame objects for each time\n\n\t\tif scantype == 'track':\n\n\t\t\tmiddletime = Time(middletime, format = 'unix')\t\t\t\t\t\t# necessary to check a midpoint for altitude bounds due to circumpolar positions possibly dipping too low\n\t\t\tmiddleframe = AltAz(location = location, obstime = middletime)\n\t\t\tendtime = Time(endtime, format = 'unix')\n\t\t\tendframe = AltAz(location = location, obstime = endtime)\n\n\t\ttry:\t\t\t\t\t\t\t\t\t\t\t\t\t\t# attempt to transform the position to the AltAz frame of each time\n\t\t\t\n\t\t\tstartpos = position.transform_to(startframe)\n\n\t\t\tif scantype == 'track':\n\n\t\t\t\tmiddlepos = position.transform_to(middleframe)\n\t\t\t\tendpos = position.transform_to(endframe)\n\n\t\texcept ValueError as e:\t\t\t\t\t\t\t\t\t\t# if the position can't be transformed, return a position error\n\n\t\t\treturn 'positionerror'\n\n\t\tazbounds = (configdata['azlower'], configdata['azupper'])\t\t# repackage movement bounds\n\t\talbounds = (configdata['allower'], configdata['alupper'])\n\t\t\n\t\tstartaz = float(startpos.az.to_string(unit=u.deg, decimal=True))\n\t\tstartal = float(startpos.alt.to_string(unit=u.deg, decimal=True))\n\t\t\n\t\tif scantype == 'track':\n\t\t\t\n\t\t\tmiddleaz = float(middlepos.az.to_string(unit=u.deg, decimal=True))\n\t\t\tmiddleal = float(middlepos.alt.to_string(unit=u.deg, decimal=True))\n\t\t\tendaz = float(endpos.az.to_string(unit=u.deg, decimal=True))\n\t\t\tendal = float(endpos.alt.to_string(unit=u.deg, decimal=True))\n\t\t\t\n\t\tif startal < 0 or startal > 180:\t\t# if a position has a negative altitude, object is not in the sky, so return position error\n\t\t\t\n\t\t\treturn 'positionerror'\n\t\t\t\n\t\tif scantype == 'track' and (middleal < 0 or middleal > 180 or endal < 0 or endal > 180):\n\t\t\t\n\t\t\treturn 'positionerror'\n\n\t\tvalid = True \t\t\t\t\t\t\t\t\t\t\t\t\t# check that the scan stays within telscope movement bounds\n\n\t\tvalid = valid and startaz >= azbounds[0] and startaz <= azbounds[1]\n\t\tvalid = valid and startal >= albounds[0] and startal <= albounds[1]\n\n\t\tif scantype == 'track':\n\n\t\t\tvalid = valid and middleaz >= azbounds[0] and middleaz <= azbounds[1]\n\t\t\tvalid = valid and middleal >= albounds[0] and middleal <= albounds[1]\n\t\t\tvalid = valid and endaz >= azbounds[0] and endaz <= azbounds[1]\n\t\t\tvalid = valid and endal >= albounds[0] and endal <= albounds[1]\n\n\t\tif not valid:\n\t\t\t\n\t\t\tprint(str(startaz) + ' ' + str(startal))\n\n\t\t\treturn 'moveboundserror'\n\n\t\treturn 'scheduled'\n\n\ndef main():\n\n\tsrtdb = sqlite3.connect('../srtdatabase/srtdata.db')\t\t# establish a connection and cursor into the database\n\tsrtdb.row_factory = sqlite3.Row\n\tcur = srtdb.cursor()\n\n\tconfig = cur.execute(\"SELECT * FROM CONFIG\").fetchone()\n\n\ta = Astral()\n\n\ttoday = datetime.date.today()\n\n\tnighttimes = a.night_utc(today, config['lat'], config['lon'])\n\t\n\tprint(nighttimes[0].isoformat() + ' ' + nighttimes[1].isoformat())\n\n\tdusk = nighttimes[0].timestamp()\n\tdawn = nighttimes[1].timestamp()\n\n\tschedule = Schedule(dusk, dawn)\n\t\n\tcur.execute(\"DELETE FROM SCHEDULE\")\n\n\t# cur.execute(\"INSERT INTO SOURCES VALUES (?,?,?)\", ('sigma octantis', '21h8m47s', '-88d57m23s'))\n\t# cur.execute(\"INSERT INTO SCANIDS VALUES (?,?,?)\", (-30, 'invalidtest', 'submitted'))\n\t# cur.execute(\"INSERT INTO SCANPARAMS VALUES (?,?,?,?,?,?,?,?,?)\", (-30, 'track', 'sigma octantis', '21h8m47s', '-88d57m23s', '1h0m0s', 1500, 1510, 10))\n\t# cur.execute(\"UPDATE CONFIG SET LAT = ?, LON = ?\", (44.45, -93.16))\n\t# cur.execute(\"INSERT INTO SOURCES VALUES (?,?,?)\", ('polaris', '2h31m49s', '89d15m50s'))\n\t# cur.execute(\"INSERT INTO SCANIDS VALUES (?,?,?)\", (-20, 'scheduletest', 'submitted'))\n\t# cur.execute(\"INSERT INTO SCANPARAMS VALUES (?,?,?,?,?,?,?,?,?)\", (-20, 'track', 'polaris', '2h31m49s', '89d15m50s', '0h30m0s', 1500, 1510, 10))\n\t# srtdb.commit()\n\t\n\tntp = NTPTime()\n\n\tschedule.schedulescan(-20, ntp.getcurrenttime())\n\tschedule.schedulescan(-30, ntp.getcurrenttime())\n\n\tfor block in schedule.schedule:\n\n\t\tprint(str(block.scanid) + ' ' + str(block.starttime) + ' ' + str(block.endtime))\n\n# main()\n", "meta": {"hexsha": "11677167de5f161ec1e43f9dbffe7a82fc030960", "size": 10255, "ext": "py", "lang": "Python", "max_stars_repo_path": "srtcontroller/Schedule.py", "max_stars_repo_name": "rowleyn/srt-code", "max_stars_repo_head_hexsha": "6afbff893094aecd40a6b1ee309afc3ba37657d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "srtcontroller/Schedule.py", "max_issues_repo_name": "rowleyn/srt-code", "max_issues_repo_head_hexsha": "6afbff893094aecd40a6b1ee309afc3ba37657d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "srtcontroller/Schedule.py", "max_forks_repo_name": "rowleyn/srt-code", "max_forks_repo_head_hexsha": "6afbff893094aecd40a6b1ee309afc3ba37657d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3620689655, "max_line_length": 208, "alphanum_fraction": 0.6976109215, "include": true, "reason": "from astropy", "num_tokens": 2782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.28140561345566495, "lm_q1q2_score": 0.1505796973942263}}
{"text": "# -*- coding: utf-8 -*-\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n#\n# Copyright (C) 2012-2016 GEM Foundation\n#\n# OpenQuake is free software: you can redistribute it and/or modify it\n# under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# OpenQuake is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"\nModule exports :class:`AtkinsonBoore2006`,\n:class:`AtkinsonBoore2006MblgAB1987bar140NSHMP2008`,\n:class:`AtkinsonBoore2006MblgJ1996bar140NSHMP2008`,\n:class:`AtkinsonBoore2006Mwbar140NSHMP2008`,\n:class:`AtkinsonBoore2006MblgAB1987bar200NSHMP2008`,\n:class:`AtkinsonBoore2006MblgJ1996bar200NSHMP2008`,\n:class:`AtkinsonBoore2006Mwbar200NSHMP2008`,\n:class:`AtkinsonBoore2006Modified2011`.\n\"\"\"\nfrom __future__ import division\n\nimport numpy as np\n# standard acceleration of gravity in m/s**2\nfrom scipy.constants import g\nfrom math import log10\n\nfrom openquake.hazardlib.gsim.boore_atkinson_2008 import BooreAtkinson2008\nfrom openquake.hazardlib.gsim.utils import (\n    mblg_to_mw_atkinson_boore_87,\n    mblg_to_mw_johnston_96,\n    clip_mean\n)\nfrom openquake.hazardlib.gsim.base import CoeffsTable\nfrom openquake.hazardlib import const\nfrom openquake.hazardlib.imt import PGA, PGV, SA\n\n\nclass AtkinsonBoore2006(BooreAtkinson2008):\n    \"\"\"\n    Implements GMPE developed by Gail M. Atkinson and David M. Boore and\n    published as \"Earthquake Ground-Motion Prediction Equations for Eastern\n    North America\" (2006, Bulletin of the Seismological Society of America,\n    Volume 96, No. 6, pages 2181-2205). This class implements only the\n    equations for stress parameter of 140 bars. The correction described in\n    'Adjustment of Equations to Consider Alternative Stress Parameters',\n    p. 2198, is not implemented.\n    This class extends the BooreAtkinson2008 because it uses the same soil\n    amplification function. Note that in the paper, the reported soil\n    amplification function is the one used in a preliminary version of the\n    Boore and Atkinson 2008 GMPE, while the one that should be used is the\n    one described in the final paper. See comment in:\n    http://www.daveboore.com/pubs_online/ab06_gmpes_programs_and_tables.pdf\n    \"\"\"\n    #: Supported tectonic region type is stable continental, given\n    #: that the equations have been derived for Eastern North America\n    DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.STABLE_CONTINENTAL\n\n    #: Supported intensity measure types are spectral acceleration,\n    #: peak ground velocity and peak ground acceleration, see paragraph\n    #: 'Methodology and Model Parameters', p. 2182\n    DEFINED_FOR_INTENSITY_MEASURE_TYPES = set([\n        PGA,\n        PGV,\n        SA\n    ])\n\n    #: Supported intensity measure component is horizontal\n    #: :attr:`~openquake.hazardlib.const.IMC.HORIZONTAL`,\n    #: see paragraph 'Results', pag 2190, and caption to table 6, p. 2192\n    DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = const.IMC.HORIZONTAL\n\n    #: Supported standard deviation type is total, see table 6\n    #: and 9, p. 2192 and 2202, respectively.\n    DEFINED_FOR_STANDARD_DEVIATION_TYPES = set([\n        const.StdDev.TOTAL\n    ])\n\n    #: Required site parameters is Vs30.\n    #: See paragraph 'Equations for soil sites', p. 2200\n    REQUIRES_SITES_PARAMETERS = set(('vs30', ))\n\n    #: Required rupture parameter is magnitude (see\n    #: paragraph 'Methodology and Model Parameters', p. 2182)\n    REQUIRES_RUPTURE_PARAMETERS = set(('mag', ))\n\n    #: Required distance measure is Rrup.\n    #: See paragraph 'Methodology and Model Parameters', p. 2182\n    REQUIRES_DISTANCES = set(('rrup', ))\n\n    def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):\n        \"\"\"\n        See :meth:`superclass method\n        <.base.GroundShakingIntensityModel.get_mean_and_stddevs>`\n        for spec of input and result values.\n        \"\"\"\n        mean = self._get_mean(sites.vs30, rup.mag, dists.rrup, imt, scale_fac=0)\n        stddevs = self._get_stddevs(stddev_types, num_sites=sites.vs30.size)\n\n        return mean, stddevs\n\n    def _get_mean(self, vs30, mag, rrup, imt, scale_fac):\n        \"\"\"\n        Compute and return mean\n        \"\"\"\n        C_HR, C_BC, C_SR, SC = self._extract_coeffs(imt)\n\n        rrup = self._clip_distances(rrup)\n\n        f0 = self._compute_f0_factor(rrup)\n        f1 = self._compute_f1_factor(rrup)\n        f2 = self._compute_f2_factor(rrup)\n\n        pga_bc = self._get_pga_bc(\n            f0, f1, f2, SC, mag, rrup, vs30, scale_fac\n        )\n\n        # compute mean values for hard-rock sites (vs30 >= 2000),\n        # and non-hard-rock sites (vs30 < 2000) and add soil amplification\n        # term\n        mean = np.zeros_like(vs30)\n        self._compute_mean(C_HR, f0, f1, f2, SC, mag, rrup,\n                           vs30 >= 2000.0, mean, scale_fac)\n        self._compute_mean(C_BC, f0, f1, f2, SC, mag, rrup,\n                           vs30 < 2000.0, mean, scale_fac)\n        self._compute_soil_amplification(C_SR, vs30, pga_bc, mean)\n\n        # convert from base 10 to base e\n        if imt == PGV():\n            mean = np.log(10 ** mean)\n        else:\n            # convert from cm/s**2 to g\n            mean = np.log((10 ** mean) * 1e-2 / g)\n\n        return mean\n\n    def _get_pga_bc(self, f0, f1, f2, SC, mag, rrup, vs30, scale_fac):\n        \"\"\"\n        Compute and return PGA on BC boundary\n        \"\"\"\n        pga_bc = np.zeros_like(vs30)\n        self._compute_mean(self.COEFFS_BC[PGA()], f0, f1, f2, SC, mag,\n                           rrup, vs30 < 2000.0, pga_bc, scale_fac)\n\n        return (10 ** pga_bc) * 1e-2 / g\n\n    def _extract_coeffs(self, imt):\n        \"\"\"\n        Extract dictionaries of coefficients specific to required\n        intensity measure type.\n        \"\"\"\n        C_HR = self.COEFFS_HARD_ROCK[imt]\n        C_BC = self.COEFFS_BC[imt]\n        C_SR = self.COEFFS_SOIL_RESPONSE[imt]\n        SC = self.STRESS_COEFFS[imt]\n\n        return C_HR, C_BC, C_SR, SC\n\n    def _clip_distances(self, rrup):\n        \"\"\"\n        Return array of distances with values clipped to 1. See end of\n        paragraph 'Methodology and Model Parameters', p. 2182. The equations\n        have a singularity for distance = 0, so that's why distances are\n        clipped to 1.\n        \"\"\"\n        rrup = rrup.copy()\n        rrup[rrup < 1] = 1\n\n        return rrup\n\n    def _compute_f0_factor(self, rrup):\n        \"\"\"\n        Compute and return factor f0 - see equation (5), 6th term, p. 2191.\n        \"\"\"\n        # f0 = max(log10(R0/rrup),0)\n        f0 = np.log10(self.COEFFS_IMT_INDEPENDENT['R0'] / rrup)\n        f0[f0 < 0] = 0.0\n\n        return f0\n\n    def _compute_f1_factor(self, rrup):\n        \"\"\"\n        Compute and return factor f1 - see equation (5), 4th term, p. 2191\n        \"\"\"\n        # f1 = min(log10(rrup),log10(R1))\n        f1 = np.log10(rrup)\n        logR1 = np.log10(self.COEFFS_IMT_INDEPENDENT['R1'])\n        f1[f1 > logR1] = logR1\n\n        return f1\n\n    def _compute_f2_factor(self, rrup):\n        \"\"\"\n        Compute and return factor f2, see equation (5), 5th term, pag 2191\n        \"\"\"\n        # f2 = max(log10(rrup/R2),0)\n        f2 = np.log10(rrup / self.COEFFS_IMT_INDEPENDENT['R2'])\n        f2[f2 < 0] = 0.0\n\n        return f2\n\n    def _compute_stress_drop_adjustment(self, SC, mag, scale_fac):\n        \"\"\"\n        Compute equation (6) p. 2200\n        \"\"\"\n        return scale_fac * np.minimum(\n            SC['delta'] + 0.05,\n            0.05 + SC['delta'] * (\n                np.maximum(mag - SC['M1'], 0) / (SC['Mh'] - SC['M1'])\n            )\n        )\n\n    def _compute_mean(self, C, f0, f1, f2, SC, mag, rrup, idxs, mean,\n                      scale_fac):\n        \"\"\"\n        Compute mean value (for a set of indexes) without site amplification\n        terms. This is equation (5), p. 2191, without S term.\n        \"\"\"\n        mean[idxs] = (C['c1'] +\n                      C['c2'] * mag +\n                      C['c3'] * (mag ** 2) +\n                      (C['c4'] + C['c5'] * mag) * f1[idxs] +\n                      (C['c6'] + C['c7'] * mag) * f2[idxs] +\n                      (C['c8'] + C['c9'] * mag) * f0[idxs] +\n                      C['c10'] * rrup[idxs] +\n                      self._compute_stress_drop_adjustment(SC, mag, scale_fac))\n\n    def _compute_soil_amplification(self, C, vs30, pga_bc, mean):\n        \"\"\"\n        Compute soil amplification, that is S term in equation (5), p. 2191,\n        and add to mean values for non hard rock sites.\n        \"\"\"\n        # convert from base e (as defined in BA2008) to base 10 (as used in\n        # AB2006)\n        sal = np.log10(np.exp(self._get_site_amplification_linear(vs30, C)))\n        sanl = np.log10(np.exp(\n            self._get_site_amplification_non_linear(vs30, pga_bc, C)))\n\n        idxs = vs30 < 2000.0\n        mean[idxs] = mean[idxs] + sal[idxs] + sanl[idxs]\n\n    def _get_stddevs(self, stddev_types, num_sites):\n        \"\"\"\n        Return total standard deviation (see table 6, p. 2192).\n        \"\"\"\n        assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES\n                   for stddev_type in stddev_types)\n        stddevs = [np.zeros(num_sites) +\n                   self.COEFFS_IMT_INDEPENDENT['std_total']\n                   for _ in stddev_types]\n        return stddevs\n\n    #: Hard rock coefficents, table 6, pag 2192,\n    #: coefficient values taken from Fortran implementation of Dave Boore\n    #: (higher precision than in the paper)\n    COEFFS_HARD_ROCK = CoeffsTable(sa_damping=5, table=\"\"\"\\\n    IMT     c1          c2          c3          c4          c5          c6          c7          c8          c9          c10\n    5.000  -5.408E+00   1.714E+00  -9.012E-02  -2.537E+00   2.267E-01  -1.268E+00   1.162E-01   9.792E-01  -1.767E-01  -1.757E-04\n    4.000  -5.791E+00   1.916E+00  -1.071E-01  -2.441E+00   2.113E-01  -1.162E+00   1.018E-01   1.012E+00  -1.824E-01  -2.010E-04\n    3.125  -6.038E+00   2.080E+00  -1.221E-01  -2.367E+00   2.002E-01  -1.073E+00   8.950E-02   1.002E+00  -1.803E-01  -2.306E-04\n    2.500  -6.169E+00   2.211E+00  -1.348E-01  -2.299E+00   1.898E-01  -9.860E-01   7.860E-02   9.683E-01  -1.765E-01  -2.823E-04\n    2.000  -6.183E+00   2.302E+00  -1.442E-01  -2.223E+00   1.770E-01  -9.370E-01   7.067E-02   9.518E-01  -1.768E-01  -3.220E-04\n    1.587  -6.043E+00   2.342E+00  -1.496E-01  -2.157E+00   1.662E-01  -8.704E-01   6.047E-02   9.207E-01  -1.734E-01  -3.748E-04\n    1.250  -5.724E+00   2.324E+00  -1.505E-01  -2.104E+00   1.565E-01  -8.202E-01   5.186E-02   8.563E-01  -1.661E-01  -4.329E-04\n    1.000  -5.272E+00   2.264E+00  -1.483E-01  -2.069E+00   1.497E-01  -8.132E-01   4.666E-02   8.262E-01  -1.622E-01  -4.862E-04\n    0.794  -4.604E+00   2.132E+00  -1.406E-01  -2.062E+00   1.468E-01  -7.974E-01   4.345E-02   7.748E-01  -1.558E-01  -5.790E-04\n    0.629  -3.917E+00   1.987E+00  -1.314E-01  -2.045E+00   1.419E-01  -7.818E-01   4.297E-02   7.878E-01  -1.590E-01  -6.948E-04\n    0.500  -3.216E+00   1.826E+00  -1.201E-01  -2.018E+00   1.344E-01  -8.134E-01   4.437E-02   8.839E-01  -1.751E-01  -7.704E-04\n    0.397  -2.437E+00   1.649E+00  -1.084E-01  -2.051E+00   1.363E-01  -8.426E-01   4.483E-02   7.386E-01  -1.557E-01  -8.509E-04\n    0.315  -1.721E+00   1.483E+00  -9.739E-02  -2.080E+00   1.382E-01  -8.893E-01   4.869E-02   6.101E-01  -1.389E-01  -9.538E-04\n    0.251  -1.121E+00   1.342E+00  -8.722E-02  -2.082E+00   1.349E-01  -9.714E-01   5.628E-02   6.140E-01  -1.432E-01  -1.055E-03\n    0.199  -6.153E-01   1.227E+00  -7.886E-02  -2.087E+00   1.312E-01  -1.120E+00   6.788E-02   6.055E-01  -1.459E-01  -1.125E-03\n    0.158  -1.455E-01   1.123E+00  -7.143E-02  -2.116E+00   1.302E-01  -1.303E+00   8.311E-02   5.617E-01  -1.438E-01  -1.182E-03\n    0.125   2.144E-01   1.054E+00  -6.664E-02  -2.154E+00   1.295E-01  -1.608E+00   1.046E-01   4.273E-01  -1.303E-01  -1.153E-03\n    0.100   4.797E-01   1.017E+00  -6.404E-02  -2.201E+00   1.270E-01  -2.007E+00   1.326E-01   3.371E-01  -1.266E-01  -1.047E-03\n    0.079   6.906E-01   9.974E-01  -6.276E-02  -2.262E+00   1.246E-01  -2.487E+00   1.636E-01   2.139E-01  -1.207E-01  -8.469E-04\n    0.063   9.109E-01   9.802E-01  -6.208E-02  -2.360E+00   1.263E-01  -2.972E+00   1.910E-01   1.069E-01  -1.173E-01  -5.786E-04\n    0.050   1.105E+00   9.719E-01  -6.197E-02  -2.466E+00   1.276E-01  -3.390E+00   2.144E-01  -1.391E-01  -9.839E-02  -3.167E-04\n    0.040   1.264E+00   9.680E-01  -6.232E-02  -2.581E+00   1.317E-01  -3.644E+00   2.276E-01  -3.506E-01  -8.126E-02  -1.225E-04\n    0.031   1.436E+00   9.592E-01  -6.276E-02  -2.714E+00   1.400E-01  -3.728E+00   2.343E-01  -5.430E-01  -6.448E-02  -3.230E-05\n    0.025   1.522E+00   9.597E-01  -6.351E-02  -2.813E+00   1.458E-01  -3.654E+00   2.362E-01  -6.544E-01  -5.500E-02  -4.848E-05\n    pga     9.069E-01   9.830E-01  -6.595E-02  -2.698E+00   1.594E-01  -2.795E+00   2.120E-01  -3.011E-01  -6.532E-02  -4.484E-04\n    pgv    -1.442E+00   9.909E-01  -5.848E-02  -2.701E+00   2.155E-01  -2.436E+00   2.659E-01   8.479E-02  -6.927E-02  -3.734E-04\n    \"\"\")\n\n    #: Coefficients for NEHRP BC boundary (Vs30 = 760 m/s), table 9, pag 2202\n    #: coefficient values taken from Fortran implementation of Dave Boore\n    #: (higher precision than in the paper)\n    COEFFS_BC = CoeffsTable(sa_damping=5, table=\"\"\"\\\n    IMT     c1          c2          c3          c4          c5          c6          c7          c8          c9         c10\n    5.000  -4.852E+00   1.580E+00  -8.066E-02  -2.530E+00   2.216E-01  -1.426E+00   1.361E-01   6.340E-01  -1.413E-01  -1.608E-04\n    4.000  -5.256E+00   1.787E+00  -9.785E-02  -2.435E+00   2.068E-01  -1.307E+00   1.210E-01   7.340E-01  -1.560E-01  -1.959E-04\n    3.125  -5.590E+00   1.972E+00  -1.136E-01  -2.331E+00   1.908E-01  -1.204E+00   1.099E-01   8.449E-01  -1.723E-01  -2.452E-04\n    2.500  -5.800E+00   2.126E+00  -1.278E-01  -2.257E+00   1.790E-01  -1.123E+00   9.539E-02   8.911E-01  -1.797E-01  -2.601E-04\n    2.000  -5.853E+00   2.233E+00  -1.385E-01  -2.195E+00   1.688E-01  -1.037E+00   8.002E-02   8.666E-01  -1.790E-01  -2.860E-04\n    1.587  -5.754E+00   2.287E+00  -1.450E-01  -2.131E+00   1.582E-01  -9.568E-01   6.762E-02   8.670E-01  -1.789E-01  -3.429E-04\n    1.250  -5.489E+00   2.289E+00  -1.476E-01  -2.081E+00   1.501E-01  -9.000E-01   5.794E-02   8.208E-01  -1.719E-01  -4.070E-04\n    1.000  -5.058E+00   2.233E+00  -1.454E-01  -2.030E+00   1.408E-01  -8.744E-01   5.412E-02   7.922E-01  -1.697E-01  -4.886E-04\n    0.794  -4.446E+00   2.119E+00  -1.387E-01  -2.009E+00   1.356E-01  -8.576E-01   4.976E-02   7.084E-01  -1.589E-01  -5.751E-04\n    0.629  -3.748E+00   1.973E+00  -1.294E-01  -1.997E+00   1.313E-01  -8.417E-01   4.820E-02   6.772E-01  -1.557E-01  -6.763E-04\n    0.500  -3.007E+00   1.803E+00  -1.178E-01  -1.982E+00   1.274E-01  -8.466E-01   4.698E-02   6.670E-01  -1.546E-01  -7.676E-04\n    0.397  -2.281E+00   1.629E+00  -1.054E-01  -1.967E+00   1.227E-01  -8.880E-01   5.033E-02   6.839E-01  -1.582E-01  -8.587E-04\n    0.315  -1.560E+00   1.455E+00  -9.312E-02  -1.977E+00   1.209E-01  -9.466E-01   5.576E-02   6.499E-01  -1.558E-01  -9.552E-04\n    0.251  -8.756E-01   1.293E+00  -8.193E-02  -2.014E+00   1.226E-01  -1.027E+00   6.341E-02   5.808E-01  -1.491E-01  -1.053E-03\n    0.199  -3.056E-01   1.156E+00  -7.211E-02  -2.038E+00   1.220E-01  -1.147E+00   7.375E-02   5.082E-01  -1.430E-01  -1.140E-03\n    0.158   1.194E-01   1.057E+00  -6.473E-02  -2.054E+00   1.190E-01  -1.355E+00   9.160E-02   5.164E-01  -1.503E-01  -1.178E-03\n    0.125   5.356E-01   9.647E-01  -5.835E-02  -2.110E+00   1.205E-01  -1.672E+00   1.156E-01   3.433E-01  -1.322E-01  -1.130E-03\n    0.100   7.818E-01   9.235E-01  -5.555E-02  -2.165E+00   1.191E-01  -2.097E+00   1.483E-01   2.847E-01  -1.319E-01  -9.897E-04\n    0.079   9.667E-01   9.033E-01  -5.476E-02  -2.249E+00   1.215E-01  -2.530E+00   1.775E-01   1.001E-01  -1.147E-01  -7.724E-04\n    0.063   1.109E+00   8.875E-01  -5.386E-02  -2.334E+00   1.229E-01  -2.881E+00   2.007E-01  -3.189E-02  -1.069E-01  -5.483E-04\n    0.050   1.209E+00   8.830E-01  -5.441E-02  -2.440E+00   1.295E-01  -3.035E+00   2.133E-01  -2.098E-01  -8.997E-02  -4.145E-04\n    0.040   1.261E+00   8.789E-01  -5.515E-02  -2.536E+00   1.388E-01  -2.994E+00   2.158E-01  -3.908E-01  -6.746E-02  -3.881E-04\n    0.031   1.191E+00   8.884E-01  -5.642E-02  -2.577E+00   1.451E-01  -2.840E+00   2.121E-01  -4.370E-01  -5.866E-02  -4.329E-04\n    0.025   1.052E+00   9.030E-01  -5.768E-02  -2.571E+00   1.483E-01  -2.652E+00   2.065E-01  -4.084E-01  -5.769E-02  -5.122E-04\n    pga     5.233E-01   9.686E-01  -6.196E-02  -2.439E+00   1.465E-01  -2.335E+00   1.912E-01  -8.695E-02  -8.285E-02  -6.304E-04\n    pgv    -1.662E+00   1.050E+00  -6.035E-02  -2.496E+00   1.840E-01  -2.301E+00   2.500E-01   1.268E-01  -8.704E-02  -4.266E-04\n    \"\"\")\n\n    #: IMT-independent coefficients. std_total is the total standard deviation,\n    #: see Table 6, pag 2192 and Table 9, pag 2202. R0, R1, R2 are coefficients\n    #: required for mean calculation - see equation (5) pag 2191. v1, v2, Vref\n    #: are coefficients required for soil response calculation, see table 8,\n    #: p. 2201\n    COEFFS_IMT_INDEPENDENT = {\n        # the std is converted from base 10 to base e\n        'std_total': np.log(10 ** 0.30),\n        'R0': 10.0,\n        'R1': 70.0,\n        'R2': 140.0,\n        'v1': 180.0,\n        'v2': 300.0,\n        'Vref': 760.0\n    }\n\n    STRESS_COEFFS = CoeffsTable(sa_damping=5, table=\"\"\"\\\n    IMT    delta  M1    Mh\n    pga    0.15   0.50  5.50\n    0.025  0.15   0.00  5.00\n    0.031  0.15   0.00  5.00\n    0.04   0.15   0.00  5.00\n    0.05   0.15   0.00  5.00\n    0.063  0.15   0.17  5.17\n    0.079  0.15   0.34  5.34\n    0.1    0.15   0.50  5.50\n    0.126  0.15   1.15  5.67\n    0.158  0.15   1.85  5.84\n    0.199  0.15   2.50  6.00\n    0.251  0.15   2.90  6.12\n    0.315  0.15   3.30  6.25\n    0.397  0.15   3.65  6.37\n    0.5    0.15   4.00  6.50\n    0.629  0.15   4.17  6.70\n    0.794  0.15   4.34  6.95\n    1.00   0.15   4.50  7.20\n    1.25   0.15   4.67  7.45\n    1.587  0.15   4.84  7.70\n    2.0    0.15   5.00  8.00\n    2.5    0.15   5.25  8.12\n    3.125  0.15   5.50  8.25\n    4.0    0.15   5.75  8.37\n    5.0    0.15   6.00  8.50\n    pgv    0.11   2.00  5.50\n    \"\"\")\n\n\nclass AtkinsonBoore2006MblgAB1987bar140NSHMP2008(AtkinsonBoore2006):\n    \"\"\"\n    Implements GMPE developed by Gail M. Atkinson and David M. Boore and\n    published as \"Earthquake Ground-Motion Prediction Equations for Eastern\n    North America\" (2006, Bulletin of the Seismological Society of America,\n    Volume 96, No. 6, pages 2181-2205) as utilized by the National Seismic\n    Hazard Mapping Project (NSHMP) for the 2008 central and eastern US model.\n\n    The class replicates the algorithm as coded in ``subroutine getAB06``\n    in ``hazgridXnga2.f`` Fortran code available at:\n    http://earthquake.usgs.gov/hazards/products/conterminous/2008/software/\n\n    The class implement the equation for static stress drop equal to 140 bar.\n\n    The class assumes rupture magnitude to be in Mblg scale (given that\n    MFDs for central and eastern US are given in this scale). Therefore Mblg\n    is converted to Mw by using Atkinson and Boore 1987 conversion equation.\n\n    Mean value is clipped at 1.5 g for PGA and 3.0 g for SA with periods in\n    range (0.02, 0.55) s.\n    \"\"\"\n    def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):\n        \"\"\"\n        See :meth:`superclass method\n        <.base.GroundShakingIntensityModel.get_mean_and_stddevs>`\n        for spec of input and result values.\n        \"\"\"\n        mag = self._convert_magnitude(rup.mag)\n\n        mean = self._get_mean(sites.vs30, mag, dists.rrup, imt, scale_fac=0)\n        stddevs = self._get_stddevs(stddev_types, num_sites=sites.vs30.size)\n\n        mean = clip_mean(imt, mean)\n\n        return mean, stddevs\n\n    def _convert_magnitude(self, mag):\n        \"\"\"\n        Convert magnitude from Mblg to Mw using Atkinson and Boore 1987\n        equation\n        \"\"\"\n        return mblg_to_mw_atkinson_boore_87(mag)\n\n\nclass AtkinsonBoore2006MblgJ1996bar140NSHMP2008(\n        AtkinsonBoore2006MblgAB1987bar140NSHMP2008):\n    \"\"\"\n    Extend :class:`AtkinsonBoore2006MblgAB1987bar140NSHMP2008` but uses\n    Johnston 1996 equation to convert from Mblg to Mw\n    \"\"\"\n    def _convert_magnitude(self, mag):\n        \"\"\"\n        Convert magnitude from Mblg to Mw using Johnston 1996 equation\n        \"\"\"\n        return mblg_to_mw_johnston_96(mag)\n\n\nclass AtkinsonBoore2006Mwbar140NSHMP2008(\n        AtkinsonBoore2006MblgAB1987bar140NSHMP2008):\n    \"\"\"\n    Extend :class:`AtkinsonBoore2006MblgAB1987bar140NSHMP2008` but assumes\n    magnitude to be in Mw scale and thefore no conversion is applied\n    \"\"\"\n    def _convert_magnitude(self, mag):\n        \"\"\"\n        Return magnitude value unchanged\n        \"\"\"\n        return mag\n\n\nclass AtkinsonBoore2006MblgAB1987bar200NSHMP2008(AtkinsonBoore2006):\n    \"\"\"\n    Same as :class:`AtkinsonBoore2006MblgAB1987bar140NSHMP2008` but with\n    adjustment for 200 bar stress drop\n    \"\"\"\n    def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):\n        \"\"\"\n        See :meth:`superclass method\n        <.base.GroundShakingIntensityModel.get_mean_and_stddevs>`\n        for spec of input and result values.\n        \"\"\"\n        mag = self._convert_magnitude(rup.mag)\n\n        # stress drop scaling factor defined in subroutine getAB06\n        mean = self._get_mean(\n            sites.vs30, mag, dists.rrup, imt, scale_fac=0.5146\n        )\n        stddevs = self._get_stddevs(stddev_types, num_sites=sites.vs30.size)\n\n        mean = clip_mean(imt, mean)\n\n        return mean, stddevs\n\n    def _convert_magnitude(self, mag):\n        \"\"\"\n        Convert magnitude from Mblg to Mw using Atkinson and Boore 1987\n        equation\n        \"\"\"\n        return mblg_to_mw_atkinson_boore_87(mag)\n\n\nclass AtkinsonBoore2006MblgJ1996bar200NSHMP2008(\n        AtkinsonBoore2006MblgAB1987bar200NSHMP2008):\n    \"\"\"\n    Extend :class:`AtkinsonBoore2006MblgAB1987bar200NSHMP2008` but uses\n    Johnston 1996 equation to convert from Mblg to Mw\n    \"\"\"\n    def _convert_magnitude(self, mag):\n        \"\"\"\n        Convert magnitude from Mblg to Mw using Johnston 1996 equation\n        \"\"\"\n        return mblg_to_mw_johnston_96(mag)\n\n\nclass AtkinsonBoore2006Mwbar200NSHMP2008(\n        AtkinsonBoore2006MblgAB1987bar200NSHMP2008):\n    \"\"\"\n    Extend :class:`AtkinsonBoore2006MblgAB1987bar200NSHMP2008` but assumes\n    magnitude to be in Mw scale therefore no conversion is applied\n    \"\"\"\n    def _convert_magnitude(self, mag):\n        \"\"\"\n        Return magnitude value unchanged\n        \"\"\"\n        return mag\n\n\nclass AtkinsonBoore2006Modified2011(AtkinsonBoore2006):\n    \"\"\"\n    This GMPE modifies the original implementation of :class:\n    `AtkinsonBoore2006` with the magnitude dependent stress-drop scaling\n    factor proposed in Atkinson & Boore (2011)\n    Atkinson, G. A. and Boore D. M. (2011) Modifications to Existing\n    Ground-Motion Prediciton Equations in Light of New Data. Bulletin of the\n    Seismological Society of America, 101(3), 1121 - 1135\n    \"\"\"\n    def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):\n        \"\"\"\n        See :meth:`superclass method\n        <.base.GroundShakingIntensityModel.get_mean_and_stddevs>`\n        for spec of input and result values.\n        \"\"\"\n        # Stress drop scaling factor is now a property of magnitude\n        scale_fac = self._get_stress_drop_scaling_factor(rup.mag)\n        mean = self._get_mean(sites.vs30, rup.mag, dists.rrup, imt, scale_fac)\n        stddevs = self._get_stddevs(stddev_types, num_sites=sites.vs30.size)\n\n        return mean, stddevs\n\n    def _get_stress_drop_scaling_factor(self, magnitude):\n        \"\"\"\n        Returns the magnitude dependent stress drop scaling factor defined in\n        equation 6 (page 1128) of Atkinson & Boore (2011)\n        \"\"\"\n        stress_drop = 10.0 ** (3.45 - 0.2 * magnitude)\n        cap = 10.0 ** (3.45 - 0.2 * 5.0)\n        if stress_drop > cap:\n            stress_drop = cap\n        return log10(stress_drop / 140.0) / log10(2.0)\n", "meta": {"hexsha": "6ba3fb5b660ba33d4dd2b91ad76c59cca29ec115", "size": 24449, "ext": "py", "lang": "Python", "max_stars_repo_path": "openquake.hazardlib/openquake/hazardlib/gsim/atkinson_boore_2006.py", "max_stars_repo_name": "rainzhop/ConvNetQuake", "max_stars_repo_head_hexsha": "a3e6de3f7992eac72f1b9883fec36b8c7fdefd48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "openquake.hazardlib/openquake/hazardlib/gsim/atkinson_boore_2006.py", "max_issues_repo_name": "rainzhop/ConvNetQuake", "max_issues_repo_head_hexsha": "a3e6de3f7992eac72f1b9883fec36b8c7fdefd48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openquake.hazardlib/openquake/hazardlib/gsim/atkinson_boore_2006.py", "max_forks_repo_name": "rainzhop/ConvNetQuake", "max_forks_repo_head_hexsha": "a3e6de3f7992eac72f1b9883fec36b8c7fdefd48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.8705440901, "max_line_length": 129, "alphanum_fraction": 0.6156080003, "include": true, "reason": "import numpy,from scipy", "num_tokens": 9862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.28140560140262283, "lm_q1q2_score": 0.15057969511727007}}
{"text": "\"\"\"\nThis module groups convenience methods used when dealing with point-like sources.\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom numbers import Number\nimport warnings\nimport logging\nimport pandas as pd\n\nfrom astropy.convolution import Gaussian2DKernel, Box2DKernel\nfrom astropy.table import Table\nfrom astropy.stats import sigma_clipped_stats\nfrom astropy.units.quantity import Quantity\n\nfrom sitelle.region import centered_square_region\nfrom sitelle.plot import *\n\nfrom photutils import CircularAperture, CircularAnnulus, EllipticalAperture\nfrom photutils import DAOStarFinder, IRAFStarFinder\nfrom photutils import find_peaks, detect_sources, deblend_sources, source_properties\n\nfrom scipy.interpolate import UnivariateSpline\n\nfrom orb.astrometry import Astrometry\nfrom orb.utils import vector\nfrom orcs.utils import fit_lines_in_spectrum\n\n\n__all__ = ['mask_sources', 'filter_frame', 'extract_max_frame', 'estimate_local_background', 'extract_point_source', 'check_source', 'measure_coherence', 'measure_source_fwhm', 'get_sources', 'analyse_source']\ndef mask_sources(sources, annulus):\n    \"\"\"\n    Mask sources not contained in a given 2D mask.\n\n    Parameters\n    ----------\n    sources : :class:`~pandas:pandas.DataFrame`\n        DataFrame containing detected sources. Should have columns ``ycentroid`` and ``xcentroid``. WARNING : astropy convention : y and x are inversed.\n    annulus : 2D :class:`~numpy:numpy.ndarray`\n        2D array containing 1 where we want to keep sources, 0 where we don't\n\n    Returns\n    -------\n    sources : :class:`~pandas:pandas.DataFrame`\n        Subset of the original sources containing only the ones whose position is in the annulus.\n    \"\"\"\n    x,y = sources['ycentroid'], sources['xcentroid']\n    return sources[annulus[np.round(x).astype(int), np.round(y).astype(int)].astype(bool)]\n\ndef filter_frame(frame, annulus, val=0):\n    \"\"\"\n    DEPRECATED\n    \"\"\"\n    _frame = np.copy(frame)\n    _frame[np.where(annulus == 0)] = val\n    return _frame\n\ndef extract_max_frame(x,y, spectral_cube, id_max_detection_frame):\n    \"\"\"\n    For a given spatial position, extracts a few frames around the maximum of detection in the cube and returns their sum.\n\n    Parameters\n    ----------\n    x : int\n        Abscisse of the source, in pixels\n    y : int\n        Ordinate of the source, in pixels\n    spectral_cube : :class:`~ORCS:orcs.process.SpectralCube`\n        SpectralCube instance where we are looking at the source\n    id_max_detection_frame : int\n        Index of the max frame along the z dimension\n\n    Returns\n    -------\n    out : 2D :class:`~numpy:numpy.ndarray`\n        A cutout of the sum of the frames around the max of detection\n    \"\"\"\n    if isinstance(id_max_detection_frame, Number):\n        iframe = int(id_max_detection_frame)\n    else:\n        raise TypeError('Non valid type for id_max_detection_frame : %s'%type(id_max_detection_frame))\n    data = spectral_cube.get_data(x-10, x+11, y-10,y+11, iframe-2,iframe+3)\n    return np.sum(data, axis=2)\n\ndef estimate_local_background(x,y,cube, small_bin = 3, big_bin = 30):\n    \"\"\"\n    Estimation of a local background spectrum. For a given position, the background spectrum is defined as the median taken in a ``big_bin x big_bin`` pixels box from which the ``small_bin x small_bin`` center pixels have been excluded.\n\n    Parameters\n    ----------\n    x : int\n        Abscisse position, in pixels\n    y : int\n        Ordinate position, in pixels\n    cube : :class:`~ORCS:orcs.process.SpectralCube`\n        SpectralCube instance where we are looking at the source\n    small_bin : int\n        (Optional) Size of the inner region. Default = 3\n    big_bin : int\n        (Optional) Size of the outter region. Default = 30\n\n    Returns\n    -------\n    bkg_spec : 1D :class:`~numpy:numpy.ndarray`\n        The corresponding spectrum\n    \"\"\"\n    big_box = centered_square_region(x,y, b=big_bin)\n    small_box = centered_square_region(x,y, b=small_bin)\n    mask = np.zeros((cube.dimx, cube.dimy))\n    mask[big_box]=1\n    mask[small_box]=0\n    _, bkg_spec = cube.extract_integrated_spectrum(np.nonzero(mask), median=True, mean_flux=True, silent=True)\n    return bkg_spec\n\ndef extract_point_source(x,y, cube, small_bin=3, medium_bin = None, big_bin = 30):\n    \"\"\"\n    Basic way to extract a point source spectra with the local background subtracted.\n    For a given position xy, we sum the spectra extracted in a squared region of size small_bin**2 centered on x,y, and subtract from it the median spectra from a squared region of size big_bin**2 centered on x,y excluding the medium_bin**2 central area.\n\n    Parameters\n    ----------\n    x : int\n        Abscisse position, in pixels\n    y : int\n        Ordinate position, in pixels\n    cube : :class:`~ORCS:orcs.process.SpectralCube`\n        SpectralCube instance where we are looking at the source\n    small_bin : int\n        (Optional) Size of the inner region. Default = 3\n    medium_bin : int\n        (Optional) Size of the middle region. Default = small_bin\n    big_bin : int\n        (Optional) Size of the outter region. Default = 30\n\n    Returns\n    -------\n    a : 1D :class:`~numpy:numpy.ndarray`\n        The axis of the spectrum\n    spec : 1D :class:`~numpy:numpy.ndarray`\n        The source spectrum, background subtracted\n    \"\"\"\n    small_box = centered_square_region(x,y, b=small_bin)\n    if medium_bin is None:\n        medium_bin = small_bin\n    bkg_spec = estimate_local_background(x,y, cube, medium_bin, big_bin)\n    a,s, n = cube.extract_integrated_spectrum(small_box, silent=True, return_spec_nb = True)\n    return a, s-n*bkg_spec\n\ndef check_source(x,y, spectral_cube, frame=None, smooth_factor = None):\n    \"\"\"\n    Helper function to quickly look at a source\n    We extract the source at positon (x,y) with :func:`extract_point_source` and plot the resulting spectra.\n    We also plot a map around the source, to check if we actually detect something.\n\n    Parameters\n    ----------\n    x : int\n        Abscisse position, in pixels\n    y : int\n        Ordinate position, in pixels\n    spectral_cube : :class:`~ORCS:orcs.process.SpectralCube`\n        SpectralCube instance where we are looking at the source\n    frame : 2D :class:`~numpy:numpy.ndarray`, int\n        (Optional) Frame to plot the detection on. If None, the deep_frame is used. If frame in as integer, we plot on the sum of the frames around this index in the cube\n    smooth_factor : int\n        (Optional) Factor used to smooth the spectrum (see :func:`ORB:orb.utils.vector.smooth`)\n    \"\"\"\n    a,s = extract_point_source(x,y, spectral_cube)\n    if smooth_factor is not None:\n        s = vector.smooth(s, smooth_factor)\n    f, ax = plot_spectra(a,s)\n    ax.set_xlim(spectral_cube.params.filter_range)\n    if frame is not None:\n        if isinstance(frame, Number):\n            f,ax = plot_map(extract_max_frame(x,y, spectral_cube, frame))\n            wl = 1e8/a[int(frame)]\n            ax.set_title('Frame at %.1f Angstroms'%wl)\n        else:\n            try:\n                if frame.shape == (spectral_cube.dimx, spectral_cube.dimy):\n                    f,ax = plot_map(frame[x-10:x+11, y-10:y+11])\n                else:\n                    raise ValueError('Invalid shape for the frame : %s. Cube shape : %s'%(frame.shape,(spectral_cube.dimx, spectral_cube.dimy)))\n            except:\n                raise TypeError('Non valid type for frame : %s'%type(frame))\n    else:\n        f,ax = plot_map(spectral_cube.get_deep_frame()[x-10:x+11, y-10:y+11])\n    ax.scatter(10,10, marker='+', color='red')\n\ndef measure_coherence(source, argmax_map, segm_image = None):\n    \"\"\"\n    Coherence is a measure of the credibility of a source as an emission line source.\n    It checks if the hot pixels of a source are coming from ~the same frames of the cube by measuring the inverse of the variance around teh source in the detection pos frame. If the source is coherent, the max along the z axis is obtained in the same frame for every pixels of the source (i.e. the velocity is the same) and then the coherence measure is infinite.\n\n    Parameters\n    ----------\n    source : :class:`~pandas:pandas.Series`\n        Row of a DataFrame containing detected sources. Should have columns ``xpos`` and ``ypos``, in classic convention (not astropy)\n    detection_pos_frame : 2D :class:`~numpy:numpy.ndarray`\n        map of the id along z axis of the max pixels\n    \"\"\"\n    if segm_image is not None:\n        source_pos = argmax_map[np.nonzero(segm_image == source['id'])]\n    else:\n        x,y = source[['xpos', 'ypos']].astype(int)\n        source_pos = argmax_map[x-1:x+2, y-1:y+2].flatten()\n    var = np.nanstd(np.sort(source_pos))\n    if var == 0:\n        return 10\n    else:\n        return 1/var\n\ndef measure_source_fwhm(detection, data, rmax=10):\n    \"\"\"\n    TO USE CAREFULLY\n    Function used to estimate the FWHM of a source.\n    It performs aperture photometry with inscreasing radius from the source position, and then, tries to find where half of the maximum of flux is reached.\n\n    Parameters\n    ----------\n    detection : :class:`~pandas:pandas.Series`\n        Row of a DataFrame containing detected sources. Should have columns ``xcentroid`` and ``ycentroid``, in classic convention (not astropy)\n    data : 2D :class:`~numpy:numpy.ndarray`\n        Flux map used for the photometry\n    \"\"\"\n    x,y = np.array(detection[['xcentroid', 'ycentroid']])\n    photo_flux = np.zeros(rmax)\n    for r in range(rmax):\n        if r == 0:\n            aper = CircularAperture((x,y), 1.)\n        else:\n            aper = CircularAnnulus((x,y), r, r+1)\n        photo_flux[r] = aper.do_photometry(data)[0]/aper.area()\n\n\n    def get_fwhm(flux):\n        #We assume max is on 0. If not, source is probably contaminated\n        flux = flux - flux.min()\n        spline = UnivariateSpline(np.arange(rmax), flux-flux[0]/2., s=0)\n        if spline.roots().shape != (1,):\n            return np.nan\n        return spline.roots()[0]\n    return (get_fwhm(photo_flux))\n\n\ndef get_sources(detection_frame, mask=False, sigma = 5.0, mode='DAO', fwhm = 2.5, threshold = None, npix=4, return_segm_image = False):\n    \"\"\"\n    Main method used to identify sources in a detection frame and estimate their position.\n    Different modes are available, accesible through the ``mode`` keyword :\n\n    * DAO : uses the :class:`photutils:photutils.DAOStarFinder` method, adapted from DAOPHOT.\n    * IRAF : uses the :class:`photutils:photutils.IRAFStarFinder` method, adapted from IRAF.\n    * PEAK : uses the :func:`photutils:photutils.find_peaks` method, looking for local peaks above a given threshold.\n    * ORB : uses the :func:`ORB:orb.utils.astrometry.detect_stars` method, fitting stars in the frame\n    * SEGM : uses the :func:`photutils:photutils.detect_sources` method, segmenting the image.\n\n    The most reliable is SEGM.\n\n    Parameters\n    ----------\n    detection_frame : 2D :class:`~numpy:numpy.ndarray`\n        Map on which the sources should be visible.\n    mask : 2D :class:`~numpy:numpy.ndarray` or bool,  Default = False\n        (Optional) If passed, only sources inside the mask are detected.\n    sigma : float\n        (Optional) Signal to Noise of the detections we want to keep. Only used if threshold is None. In this case, the signal and the noise are computed with sigma-clipping on the deteciton frame. Default = 5\n    threshold : float or 2D :class:`~numpy:numpy.ndarray` of floats\n        (Optional) Threshold above which we consider having a detection. Default is None\n    mode : str\n        (Optional) One of the detection mode listed above. Dafault = 'DAO'\n    fwhm : float\n        (Optional) Expected FWHM of the sources. Default : 2.5\n    npix : int\n        (Optional) Only used by the 'SEGM' method : minimum number of connected pixels with flux above the threshold to make a credible source. Default = 4\n    return_segm_image : bool, Default = False\n        (Optional) Only used in the 'SEGM' mode. If True, returns the obtained segmentation image.\n\n    Returns\n    -------\n    sources : :class:`~pandas:pandas.DataFrame`\n        A DataFrame where each row represents a detection, with at least the positions named as ``xcentroid``, ``ycentroid`` (WARNING : using astropy convention). The other columns depend on the mode used.\n\n    \"\"\"\n    if mask is False:\n        mask = np.ones_like(detection_frame)\n    if threshold is None:\n        mean, median, std = sigma_clipped_stats(detection_frame, sigma=3.0, iters=5,\n                                        mask=~mask.astype(bool) )#On masque la region hors de l'anneau\n        threshold = median+sigma*std\n    #On detecte sur toute la frame, mais on garde que ce qui est effectivement dans l'anneau\n    if mode == 'DAO':\n        daofind = DAOStarFinder(fwhm=fwhm, threshold=threshold)\n        sources = daofind(detection_frame)\n    elif mode == 'IRAF':\n        irafind = IRAFStarFinder(threshold=threshold, fwhm=fwhm)\n        sources = irafind(detection_frame)\n    elif mode == 'PEAK':\n        sources = find_peaks(detection_frame, threshold=threshold )\n        sources.rename_column('x_peak', 'xcentroid')\n        sources.rename_column('y_peak', 'ycentroid')\n    elif mode == 'ORB':\n        astro = Astrometry(detection_frame, instrument='sitelle')\n        path, fwhm_arc = astro.detect_stars(min_star_number=5000, r_max_coeff=1., filter_image=False)\n        star_list = astro.load_star_list(path)\n        sources = Table([star_list[:,0], star_list[:,1]], names=('ycentroid', 'xcentroid'))\n    elif mode == 'SEGM':\n        logging.info('Detecting')\n        segm = detect_sources(detection_frame, threshold, npixels=npix)\n        deblend = True\n        labels = segm.labels\n        if deblend:\n            # while labels.shape != (0,):\n            #     try:\n            #         #logging.info('Deblending')\n            #         # fwhm = 3.\n            #         # s = fwhm / (2.0 * np.sqrt(2.0 * np.log(2.0)))\n            #         # kernel = Gaussian2DKernel(s, x_size = 3, y_size = 3)\n            #         # kernel = Box2DKernel(3, mode='integrate')\n            #         deblended = deblend_sources(detection_frame, segm, npixels=npix, labels=labels)#, filter_kernel=kernel)\n            #         success = True\n            #     except ValueError as e:\n            #         #warnings.warn('Deblend was not possible.\\n %s'%e)\n            #         source_id = int(e.args[0].split('\"')[1])\n            #         id = np.argwhere(labels == source_id)[0,0]\n            #         labels = np.concatenate((labels[:id], labels[id+1:]))\n            #         success = False\n            #     if success is True:\n            #         break\n            try:\n                logging.info('Deblending')\n                # fwhm = 3.\n                # s = fwhm / (2.0 * np.sqrt(2.0 * np.log(2.0)))\n                # kernel = Gaussian2DKernel(s, x_size = 3, y_size = 3)\n                # kernel = Box2DKernel(3, mode='integrate')\n                deblended = deblend_sources(detection_frame, segm, npixels=npix)#, filter_kernel=kernel)\n            except ValueError as e:\n                warnings.warn('Deblend was not possible.\\n %s'%e)\n                deblended = segm\n            logging.info('Retieving properties')\n            sources = source_properties(detection_frame, deblended).to_table()\n        else:\n            deblended = segm\n            logging.info('Retieving properties')\n            sources = source_properties(detection_frame, deblended).to_table()\n        logging.info('Filtering Quantity columns')\n        for col in sources.colnames:\n            if type(sources[col]) is Quantity:\n                sources[col] = sources[col].value\n    sources = mask_sources(sources, mask) # On filtre\n    df = sources.to_pandas()\n    if return_segm_image:\n        return deblended.array, df\n    else:\n        return df\n\ndef analyse_source(source, cube, plot=False, return_fit_params=False):\n    \"\"\"\n    Convenience method to spatially analyse a source.\n    A 30x30 pixels 'flux map' is build from the sum of a few frames around each detected lines for the source.\n\n    Two analysis are then performed:\n\n    * Aperture photometry from the center of the source, to estimate a flux growth function and fit it with a custom erf function.\n    * A Gaussian 2D fit of the PSF on the flux map\n\n\n\n    This method can be used in a parallel process.\n    Parameters\n    ----------\n    source : :class:`~pandas:pandas.Series`\n        A row from a :class:`~pandas:pandas.DataFrame` containing detected sources. Should have columns ``xpos``, ``ypos`` (Not astropy convention), ``velocity``, ``*_detected`` whare * is a line name, containing True or False for each line.\n    cube : :class:`~ORCS:orcs.process.SpectralCube`\n        SpectralCube instance where we are looking at the source\n    plot : bool, Default = False\n        (Optional) If True, the two fits are plotted\n    return_fit_params : bool, Default = False\n        (Optional) If True, returns the full fits parameters\n\n    Returns\n    -------\n    res : dict\n        A dictionnary containing all the relevant fitted quantities.\n\n        +-----------------------+---------------------------------------------------------------------------------------------------+\n        |Parameter              |Description                                                                                        |\n        +=======================+===================================================================================================+\n        |flux_map_ks_pvalue     |Estimates the 'randomness' of the flux map, i.e if it's just noise or if we actually have a signal |\n        +-----------------------+---------------------------------------------------------------------------------------------------+\n        |flux_r                 |Flux at different radius *r*                                                                       |\n        +-----------------------+---------------------------------------------------------------------------------------------------+\n        |flux_err_r             |Flux error varying with *r*                                                                        |\n        +-----------------------+---------------------------------------------------------------------------------------------------+\n        |erf_amplitude          |Amplitude estimated from erf fit                                                                   |\n        +-----------------------+---------------------------------------------------------------------------------------------------+\n        |erf_amplitude_err      |Amplitude error                                                                                    |\n        +-----------------------+---------------------------------------------------------------------------------------------------+\n        |erf_xfwhm              |x-axis fwhm from erf fit                                                                           |\n        +-----------------------+---------------------------------------------------------------------------------------------------+\n        |erf_yfwhm              |y-axis fwhm from erf fit                                                                           |\n        +-----------------------+---------------------------------------------------------------------------------------------------+\n        |erf_fwhm               |Fwhm defined as *r* at which half of the max flux is reached                                       |\n        +-----------------------+---------------------------------------------------------------------------------------------------+\n        |flux_fraction_3        |Ratio between flux measured at 3 pixels from the center and max flux                               |\n        +-----------------------+---------------------------------------------------------------------------------------------------+\n        |model_flux_fraction_15 |Ratio between estimated flux at 15 pixels from the center and max flux                             |\n        +-----------------------+---------------------------------------------------------------------------------------------------+\n        |modeled_flux_r         |Modeled flux varying with *r*                                                                      |\n        +-----------------------+---------------------------------------------------------------------------------------------------+\n        |psf_snr                |Ratio between amplitude of the 2D fit and noise in the flux map                                    |\n        +-----------------------+---------------------------------------------------------------------------------------------------+\n        |psf_amplitude          |Amplitude of the 2D fit                                                                            |\n        +-----------------------+---------------------------------------------------------------------------------------------------+\n        |psf_xfwhm              |x-axis fwhm from 2D fit                                                                            |\n        +-----------------------+---------------------------------------------------------------------------------------------------+\n        |psf_yfwhm              |y-axis fwhm from 2D fit                                                                            |\n        +-----------------------+---------------------------------------------------------------------------------------------------+\n        |psf_ks_pvalue          |Randomness of the residuals map                                                                    |\n        +-----------------------+---------------------------------------------------------------------------------------------------+\n\n\n\n    \"\"\"\n    result = {}\n    try:\n        from astropy.stats import sigma_clipped_stats, gaussian_sigma_to_fwhm\n        from sitelle.constants import SN2_LINES, SN3_LINES\n        from sitelle.region import centered_square_region\n        from orb.utils.spectrum import line_shift\n        from orb.core import Lines\n\n        filter_name = cube.params.filter_name\n\n        if filter_name == 'SN2':\n            LINES = SN2_LINES\n        elif filter_name == 'SN3':\n            LINES = SN3_LINES\n        else:\n            raise ValueError(filter_name)\n\n        ## We build a flux map of the detected lines\n        try:\n            detected_lines = [line_name for line_name in LINES if source['%s_detected'%line_name.lower().replace('[', '').replace(']', '')]]\n        except KeyError as e:\n            raise ValueError('No columns *_detected in the source')\n        if detected_lines == []:\n            return pd.Series(result)\n\n        x,y = source.as_matrix(['xpos', 'ypos']).astype(int)\n        big_box = centered_square_region(x,y,30)\n        medium_box = centered_square_region(15,15,5)\n        small_box = centered_square_region(15,15, 3)\n        data = cube._extract_spectra_from_region(big_box, silent=True)\n        mask = np.ones((30, 30))\n        mask[medium_box] = 0\n        bkg_spec = np.nanmedian(data[np.nonzero(mask)], axis=0)\n        data -= bkg_spec\n\n        axis = cube.params.base_axis\n        spec = np.nansum(data[small_box], axis=0)\n\n        line_pos = np.atleast_1d(Lines().get_line_cm1(detected_lines) + line_shift(source['velocity'], Lines().get_line_cm1(detected_lines), wavenumber=True))\n        pos_min = line_pos - cube.params.line_fwhm\n        pos_max = line_pos + cube.params.line_fwhm\n        pos_index = np.array([[np.argmin(np.abs(axis-pos_min[i])), np.argmin(np.abs(axis-pos_max[i]))] for i in range(pos_min.shape[0])])\n\n        bandpass_size = 0\n        flux_map = np.zeros(data.shape[:-1])\n        for line_detection in pos_index:\n            bandpass_size += line_detection[1]-line_detection[0]\n            flux_map += np.nansum(data[:,:,line_detection[0]:line_detection[1]], axis=-1)\n\n        _,_,std_map = sigma_clipped_stats(data, axis=-1)\n        flux_noise_map = np.sqrt(bandpass_size)*std_map\n\n        #Test for randomness of the flux_map\n        from scipy import stats\n        result['flux_map_ks_pvalue'] = stats.kstest((flux_map/flux_noise_map).flatten(), 'norm').pvalue\n\n        #Fit of the growth function\n        from photutils import RectangularAperture\n        from scipy.special import erf\n        from scipy.optimize import curve_fit\n\n\n        try:\n            _x0 = source['xcentroid'] - x + 15.\n            _y0 = source['ycentroid'] - y + 15.\n        except:\n            _x0 = source['xpos'] - x + 15.\n            _y0 = source['ypos'] - y + 15.\n\n        flux_r = [0.]\n        flux_err_r = [np.nanmin(flux_noise_map)]\n\n        r_max = 15\n        r_range = np.arange(1, r_max+1)\n        for r in r_range:\n#             aper = CircularAperture((_x0,_y0), r)\n            aper = RectangularAperture((_x0,_y0), r,r,0)\n            flux_r.append(aper.do_photometry(flux_map)[0][0])\n            flux_err_r.append(np.sqrt(aper.do_photometry(flux_noise_map**2)[0][0]))\n\n        flux_r = np.atleast_1d(flux_r)\n        flux_err_r = np.atleast_1d(flux_err_r)\n\n        result['flux_r'] = flux_r\n        result['flux_err_r'] = flux_err_r\n        try:\n            def model(r, x0, y0, sx, sy, A):\n                return A*erf((r/2.-x0)/(2*sx*np.sqrt(2)))*erf((r/2.-y0)/(2*sy*np.sqrt(2)))\n            R = np.arange(r_max+1)\n            p, cov = curve_fit(model, R, flux_r,\n                               p0=[0,0,1.5,1.5,flux_map.max()],\n                               bounds=([-2, -2, -np.inf, -np.inf, -np.inf], [2,2,np.inf, np.inf, np.inf]),\n                               sigma= flux_err_r, absolute_sigma=True,\n                               maxfev=10000)\n            if (p[2] < 0) != (p[3] < 0):\n                if p[-1] < 0:\n                    p[-1] = -p[-1]\n                    if p[2]<0:\n                        p[2] = - p[2]\n                    elif p[3] < 0:\n                        p[3] = -p[3]\n            if plot:\n                f,ax = plt.subplots()\n                ax.plot(R,model(R,*p), label='Fit')\n                ax.errorbar(R, flux_r, flux_err_r, label='Flux')\n                ax.set_ylabel('Flux')\n                ax.set_xlabel('Radius from source')\n                ax.legend()\n\n            from scipy.optimize import bisect\n            fwhm = bisect(lambda x:model(x, *p) -p[-1]/2, 0.1, 10)\n            result['erf_amplitude'] = p[-1]\n            result['erf_amplitude_err'] = np.sqrt(np.diag(cov))[-1]\n            result['erf_xfwhm'] = gaussian_sigma_to_fwhm*p[2]\n            result['erf_yfwhm'] = gaussian_sigma_to_fwhm*p[3]\n            result['erf_ks_pvalue'] = stats.kstest((flux_r-model(R,*p))/flux_err_r, 'norm').pvalue\n            result['erf_fwhm'] =fwhm\n\n            result['flux_fraction_3'] = flux_r[3]/p[-1]\n            result['model_flux_fraction_15'] = model(R,*p)[r_range[-1]] / p[-1]\n\n            result['modeled_flux_r'] = model(R,*p)\n\n        except Exception as e:\n            print(e)\n            pass\n\n        ## 2D fit of the PSF\n        from astropy.modeling import models, fitting\n\n        fitter = fitting.LevMarLSQFitter()\n        X,Y = np.mgrid[:30, :30]\n\n        flux_std = np.nanmean(flux_noise_map)\n\n        gauss_model = models.Gaussian2D(amplitude = np.nanmax(flux_map/flux_std),x_mean = _y0, y_mean = _x0)\n        gauss_model.bounds['x_mean'] = (14, 16)\n        gauss_model.bounds['y_mean'] = (14, 16)\n        gauss_fit = fitter(gauss_model, X,Y, flux_map/flux_std)\n\n        if plot is True:\n            f, ax = plt.subplots(1,3, figsize=(8,3))\n            v_min = np.nanmin(flux_map)\n            v_max = np.nanmax(flux_map)\n            plot_map(flux_map, ax=ax[0], cmap='RdBu_r', vmin=v_min, vmax=v_max)\n            ax[0].set_title(\"Data\")\n            plot_map(gauss_fit(X, Y)*flux_std, ax=ax[1], cmap='RdBu_r', vmin=v_min, vmax=v_max)\n            ax[1].set_title(\"Model\")\n            plot_map(flux_map - gauss_fit(X, Y)*flux_std, ax=ax[2], cmap='RdBu_r', vmin=v_min, vmax=v_max)\n            ax[2].set_title(\"Residual\")\n\n        result['psf_snr'] = gauss_fit.amplitude[0]\n        result['psf_amplitude'] = flux_std*gauss_fit.amplitude[0]*2*np.pi*gauss_fit.x_stddev*gauss_fit.y_stddev\n        result['psf_xfwhm'] = gauss_fit.x_fwhm\n        result['psf_yfwhm'] = gauss_fit.y_fwhm\n        normalized_res = (flux_map - gauss_fit(X, Y)*flux_std)/flux_noise_map\n        result['psf_ks_pvalue'] = stats.kstest(normalized_res.flatten(),'norm').pvalue\n        if return_fit_params:\n            return pd.Series(result), p, gauss_fit\n        else:\n            return pd.Series(result)\n    except Exception as e:\n        print e\n        return pd.Series(result)\n", "meta": {"hexsha": "2f870979b990454d245d39bd4d2c3d210c904246", "size": 28588, "ext": "py", "lang": "Python", "max_stars_repo_path": "sitelle/source.py", "max_stars_repo_name": "BLaunet/sitelle", "max_stars_repo_head_hexsha": "eb4a8c58a00dc76286761eb8f833c29d2e0f493c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-17T09:41:15.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-17T09:41:15.000Z", "max_issues_repo_path": "sitelle/source.py", "max_issues_repo_name": "BLaunet/sitelle", "max_issues_repo_head_hexsha": "eb4a8c58a00dc76286761eb8f833c29d2e0f493c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-05-15T10:41:59.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-15T11:10:54.000Z", "max_forks_repo_path": "sitelle/source.py", "max_forks_repo_name": "BLaunet/sitelle", "max_forks_repo_head_hexsha": "eb4a8c58a00dc76286761eb8f833c29d2e0f493c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.619047619, "max_line_length": 364, "alphanum_fraction": 0.5533090807, "include": true, "reason": "import numpy,from scipy,from astropy", "num_tokens": 6629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2942149721629888, "lm_q1q2_score": 0.15055468660837515}}
{"text": "import logging\nimport os\nfrom os.path import join, dirname, isfile\n\nimport numpy as np\nimport typhon as ty\nfrom scipy.interpolate import PchipInterpolator\n\nfrom konrad.utils import get_quadratic_pgrid\nfrom konrad.atmosphere import Atmosphere\nfrom konrad.cloud import ClearSky\nfrom .rrtmg import RRTMG\nfrom .common import fluxes2heating\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass _ARTS:\n    def __init__(self, ws=None, threads=None, nstreams=4, verbosity=0):\n        \"\"\"Initialize a wrapper for an ARTS workspace.\n\n        Parameters:\n            ws (pyarts.workspace.Workspace): An ARTS workspace.\n            threads (int): Number of threads to use.\n                Default is all available threads.\n            nstreams (int): Number of viewing angles to base the radiative\n                flux calculation on.\n            verbosity (int): Control the ARTS verbosity from 0 (quiet) to 2.\n        \"\"\"\n        from pyarts.workspace import Workspace, arts_agenda\n\n        self.nstreams = nstreams\n\n        if ws is None:\n            self.ws = Workspace(verbosity=verbosity)\n\n        self.ws.execute_controlfile(\"general/general.arts\")\n        self.ws.execute_controlfile(\"general/continua.arts\")\n        self.ws.execute_controlfile(\"general/agendas.arts\")\n        self.ws.execute_controlfile(\"general/planet_earth.arts\")\n\n        # Agenda settings\n        self.ws.Copy(self.ws.abs_xsec_agenda, self.ws.abs_xsec_agenda__noCIA)\n        self.ws.Copy(self.ws.iy_main_agenda, self.ws.iy_main_agenda__Emission)\n        self.ws.Copy(self.ws.iy_space_agenda, self.ws.iy_space_agenda__CosmicBackground)\n        self.ws.Copy(\n            self.ws.iy_surface_agenda, self.ws.iy_surface_agenda__UseSurfaceRtprop\n        )\n        self.ws.Copy(\n            self.ws.propmat_clearsky_agenda,\n            self.ws.propmat_clearsky_agenda__LookUpTable,\n        )\n        self.ws.Copy(self.ws.ppath_agenda, self.ws.ppath_agenda__FollowSensorLosPath)\n        self.ws.Copy(\n            self.ws.ppath_step_agenda, self.ws.ppath_step_agenda__GeometricPath\n        )\n\n        @arts_agenda\n        def p_eq_agenda(workspace):\n            workspace.water_p_eq_fieldMK05()\n\n        self.ws.Copy(self.ws.water_p_eq_agenda, p_eq_agenda)\n\n        @arts_agenda\n        def cloudbox_agenda(workspace):\n            workspace.iyInterpCloudboxField()\n\n        self.ws.Copy(self.ws.iy_cloudbox_agenda, cloudbox_agenda)\n\n        # Number of Stokes components to be computed\n        self.ws.IndexSet(self.ws.stokes_dim, 1)\n\n        self.ws.jacobianOff()  # No jacobian calculation\n        self.ws.cloudboxOff()  # Clearsky = No scattering\n\n        # Set Absorption Species\n        self.ws.abs_speciesSet(\n            species=[\n                \"O2, O2-CIAfunCKDMT100\",\n                \"H2O, H2O-SelfContCKDMT252, H2O-ForeignContCKDMT252\",\n                \"O3\",\n                \"CO2, CO2-CKDMT252\",\n                \"N2, N2-CIAfunCKDMT252, N2-CIArotCKDMT252\",\n                \"N2O\",\n                \"CH4\",\n                \"CO\",\n            ]\n        )\n\n        # Surface handling\n        self.ws.VectorSetConstant(self.ws.surface_scalar_reflectivity, 1, 0.0)\n        self.ws.Copy(\n            self.ws.surface_rtprop_agenda,\n            self.ws.surface_rtprop_agenda__Specular_NoPol_ReflFix_SurfTFromt_surface,\n        )\n\n        # Read lookup table\n        abs_lookup = os.getenv(\n            \"KONRAD_LOOKUP_TABLE\",\n            join(dirname(__file__), \"data/abs_lookup.xml\")\n        )\n\n        if not isfile(abs_lookup):\n            raise FileNotFoundError(\n                \"Could not find ARTS absorption lookup table.\\n\"\n                \"To perform ARTS calculations you have to download the lookup \"\n                \"table at:\\n\\n    https://doi.org/10.5281/zenodo.3885410\\n\\n\"\n                \"Afterwards, use the following environment variable to tell \"\n                \"konrad where to find it:\\n\\n\"\n                \"    $ export KONRAD_LOOKUP_TABLE='/path/to/abs_lookup.xml'\"\n            )\n\n        self.ws.ReadXML(self.ws.abs_lookup, abs_lookup)\n        self.ws.f_gridFromGasAbsLookup()\n        self.ws.abs_lookupAdapt()\n\n        # Sensor settings\n        self.ws.sensorOff()  # No sensor properties\n\n        # Atmosphere\n        self.ws.AtmosphereSet1D()\n\n        # Set number of OMP threads\n        if threads is not None:\n            self.ws.SetNumberOfThreads(threads)\n\n    def calc_lookup_table(self, filename=None):\n        \"\"\"Calculate an absorption lookup table.\n\n        The lookup table is constructed to cover surface temperatures\n        between 200 and 400 K, and water vapor mixing ratio up to 40%.\n\n        The frequency grid covers the whole outgoing longwave spectrum\n        from 10 to 3,250 cm^-1.\n\n        References:\n            An absorption lookup table can be found at\n                https://doi.org/10.5281/zenodo.3885410\n\n        Parameters:\n            filename (str): (Optional) path to an ARTS XML file\n                to store the lookup table.\n        \"\"\"\n        # Create a frequency grid\n        wavenumber = np.linspace(10e2, 3_250e2, 2**15)  # 1 to 3000cm^-1\n        self.ws.f_grid = ty.physics.wavenumber2frequency(wavenumber)\n\n        # Read line catagloge and create absorption lines.\n        self.ws.ReadSplitARTSCAT(\n            abs_lines=self.ws.abs_lines,\n            abs_species=self.ws.abs_species,\n            basename=\"hitran_split_artscat5/\",\n            fmin=0.0,\n            fmax=1e99,\n            globalquantumnumbers=\"\",\n            localquantumnumbers=\"\",\n            ignore_missing=0,\n        )\n\n        # Set line shape and cut off.\n        self.ws.abs_linesSetLineShapeType(self.ws.abs_lines, \"VP\")\n        self.ws.abs_linesSetNormalization(self.ws.abs_lines, \"VVH\")\n        self.ws.abs_linesSetCutoff(self.ws.abs_lines, \"ByLine\", 750e9)\n\n        self.ws.abs_lines_per_speciesCreateFromLines()\n        self.ws.abs_lines_per_speciesCompact()\n\n        # Create a standard atmosphere\n        p_grid = get_quadratic_pgrid(1_200e2, 0.5, 80)\n\n        atmosphere = Atmosphere(p_grid)\n        atmosphere[\"T\"][-1, :] = 300.0 + 5.0 * np.log(atmosphere[\"plev\"] / 1000e2)\n        atmosphere.tracegases_rcemip()\n        atmosphere[\"O2\"][:] = 0.2095\n        atmosphere[\"CO2\"][:] = 1.5 * 348e-6\n\n        h2o = 0.03 * (p_grid / 1000e2)**0.2\n        atmosphere[\"H2O\"][:] = h2o[:-1]\n\n        # Convert the konrad atmosphere into an ARTS atm_fields_compact.\n        atm_fields_compact = atmosphere.to_atm_fields_compact()\n        self.ws.atm_fields_compact = atm_fields_compact\n\n        self.ws.atm_fields_compactAddConstant(\n            atm_fields_compact=self.ws.atm_fields_compact,\n            name=\"abs_species-N2\",\n            value=0.7808,\n            condensibles=[\"abs_species-H2O\"],\n        )\n\n        # Setup the lookup table calculation\n        self.ws.AtmFieldsAndParticleBulkPropFieldFromCompact()\n        self.ws.vmr_field.value = self.ws.vmr_field.value.clip(min=0.0)\n        self.ws.atmfields_checkedCalc(bad_partition_functions_ok=1)\n        self.ws.abs_lookupSetup(p_step=1.0)  # Do not refine p_grid\n        self.ws.abs_t_pert = np.arange(-160, 41, 20)\n\n        nls_idx = [i for i, tag in enumerate(self.ws.abs_species.value)\n                   if \"H2O\" in tag[0]]\n        self.ws.abs_speciesSet(\n                abs_species=self.ws.abs_nls,\n                species=[\", \".join(self.ws.abs_species.value[nls_idx[0]])],\n        )\n\n        self.ws.abs_nls_pert = np.array([10**n for n in range(-7, 2)])\n\n        # Run checks\n        self.ws.abs_xsec_agenda_checkedCalc()\n        self.ws.lbl_checkedCalc()\n\n        # Calculate actual lookup table.\n        self.ws.abs_lookupCalc()\n\n        if filename is not None:\n            self.ws.WriteXML(\"binary\", self.ws.abs_lookup, filename)\n\n    def calc_spectral_irradiance_field(self, atmosphere, t_surface):\n        \"\"\"Calculate the spectral irradiance field.\"\"\"\n        atm_fields_compact = atmosphere.to_atm_fields_compact()\n\n        # Scale dry air VMRs with water content\n        vmr_h2o = atm_fields_compact.get(\"abs_species-H2O\")\n        total_vmr = vmr_h2o[0]\n        for species in atm_fields_compact.grids[0]:\n            if species.startswith(\"abs_species-\") and \"H2O\" not in species:\n                atm_fields_compact.scale(species, 1 - vmr_h2o)\n                total_vmr += atm_fields_compact.get(species)[0]\n\n        # Compute the N2 VMR as a residual of the full atmosphere composition.\n        n2 = ty.arts.types.GriddedField3(\n            grids=atm_fields_compact.grids[1:],\n            data=1 - total_vmr,\n        )\n\n        self.ws.atm_fields_compact = atm_fields_compact\n        self.ws.atm_fields_compactAddSpecies(\n            atm_fields_compact=self.ws.atm_fields_compact,\n            name=\"abs_species-N2\",\n            value=n2,\n        )\n        self.ws.AtmFieldsAndParticleBulkPropFieldFromCompact()\n        self.ws.vmr_field = self.ws.vmr_field.value.clip(min=0)\n\n        # Surface & TOA\n        # Add pressure layers to the surface and top-of-the-atmosphere to\n        # ensure consistent atmosphere boundaries between ARTS and RRTMG.\n        self.ws.t_surface = np.array([[t_surface]])\n        self.ws.z_surface = np.array([[0.0]])\n        self.ws.z_field.value[0, 0, 0] = 0.0\n\n        # Perform RT calculations\n        self.ws.atmfields_checkedCalc(bad_partition_functions_ok=1)\n        self.ws.propmat_clearsky_agenda_checkedCalc()\n        self.ws.atmgeom_checkedCalc()\n        self.ws.cloudbox_checkedCalc()\n\n        # get the zenith angle grid and the integrations weights\n        self.ws.AngularGridsSetFluxCalc(\n            N_za_grid=self.nstreams,\n            N_aa_grid=1,\n            za_grid_type=\"double_gauss\"\n        )\n\n        # calculate intensity field\n        self.ws.Tensor3Create(\"trans_field\")\n        self.ws.spectral_radiance_fieldClearskyPlaneParallel(\n            trans_field=self.ws.trans_field, use_parallel_iy=1\n        )\n        self.ws.spectral_irradiance_fieldFromSpectralRadianceField()\n\n        return (\n            self.ws.f_grid.value.copy(),\n            self.ws.p_grid.value.copy(),\n            self.ws.spectral_irradiance_field.value.copy(),\n            self.ws.trans_field.value[:, 1:, 0].copy().prod(axis=1),\n        )\n\n    def calc_radiative_fluxes(self, atmosphere, surface):\n        \"\"\"Calculate radiative fluxes.\n\n        Parameters:\n            atmosphere (konrad.atmosphere.Atmosphere): Atmosphere model.\n            surface (konrad.surface.Surface): Surface model.\n\n        Returns:\n            ndarray, ndarray: Downward flux, upward, flux [W m^-2]\n        \"\"\"\n        f, plev, irradiance_field, _ = self.calc_spectral_irradiance_field(\n            atmosphere=atmosphere, t_surface=surface[\"temperature\"][0]\n        )\n        F = np.trapz(irradiance_field, f, axis=0)[:, 0, 0, :]\n\n        # Fluxes\n        lw_down = -F[:, 0]\n        lw_up = F[:, 1]\n\n        return lw_down, lw_up\n\n    def calc_spectral_olr(self, atmosphere, surface):\n        \"\"\"Calculate the outgoing longwave radiation as function of wavenumber.\n\n        Parameters:\n            atmosphere (konrad.atmosphere.Atmosphere): Atmosphere model.\n            surface (konrad.surface.Surface): Surface model.\n\n        Returns:\n           ndarray: Outgoing longwave radiation [W m^-2 / cm^-1]\n        \"\"\"\n        f, _, irradiance_field, _ = self.calc_spectral_irradiance_field(\n            atmosphere=atmosphere, t_surface=surface[\"temperature\"][0]\n        )\n        return f, irradiance_field[:, -1, 0, 0, 1]\n\n\nclass ARTS(RRTMG):\n    def __init__(self, *args, arts_kwargs={}, **kwargs):\n        \"\"\"Radiation class to provide line-by-line longwave fluxes.\n\n        Parameters:\n            args: Positional arguments are used to initialize\n                `konrad.radiation.RRTMG`.\n            arts_kwargs (dict): Keyword arguments that are used to initialize\n                `konrad.radiation.arts._ARTS`.\n            kwargs: Keyword arguments are used to initialize\n                `konrad.radiation.RRTMG`.\n        \"\"\"\n        super().__init__(*args, **kwargs)\n\n        self._arts = _ARTS(**arts_kwargs)\n\n    def calc_radiation(self, atmosphere, surface, cloud):\n        # Perform RRTMG simulation\n        # Add a virtual layer ontop of the atmosphere column to improve the\n        # accuracy of top-of-the-atmosphere fluxes.\n        # The fluxes/heating rates in this level are ignored afterwards.\n        ph_rrtmg = np.append(atmosphere[\"phlev\"], 1e-2)\n        atmosphere_rrtmg = atmosphere.refine_plev(ph_rrtmg, kind=\"nearest\")\n\n        lw_dT_fluxes, sw_dT_fluxes = self.radiative_fluxes(\n            atmosphere_rrtmg,\n            surface,\n            ClearSky.from_atmosphere(atmosphere_rrtmg),\n        )\n        sw_fluxes = sw_dT_fluxes[1]\n\n        # Perform ARTS simulation\n        Fd, Fu = self._arts.calc_radiative_fluxes(atmosphere, surface)\n\n        # Interpolate RT results on fine original grid\n        def _reshape(x, trim=-1):\n            return x[:trim].reshape(1, -1)\n\n        self['lw_flxu'] = _reshape(Fu, trim=None)\n        self['lw_flxd'] = _reshape(Fd, trim=None)\n        self['lw_flxu_clr'] = _reshape(Fu, trim=None)\n        self['lw_flxd_clr'] = _reshape(Fd, trim=None)\n        self['sw_flxu'] = _reshape(\n            sw_fluxes['upwelling_shortwave_flux_in_air'].data)\n        self['sw_flxd'] = _reshape(\n            sw_fluxes['downwelling_shortwave_flux_in_air'].data)\n        self['sw_flxu_clr'] = _reshape(\n            sw_fluxes['upwelling_shortwave_flux_in_air_assuming_clear_sky'].data)\n        self['sw_flxd_clr'] = _reshape(\n            sw_fluxes['downwelling_shortwave_flux_in_air_assuming_clear_sky'].data)\n\n        self['lw_htngrt'] = np.zeros((1, atmosphere[\"plev\"].size))\n        self['lw_htngrt_clr'] = np.zeros((1, atmosphere[\"plev\"].size))\n        self['sw_htngrt'] = np.zeros((1, atmosphere[\"plev\"].size))\n        self['sw_htngrt_clr'] = np.zeros((1, atmosphere[\"plev\"].size))\n\n        self.coords = {\n            'time': np.array([0]),\n            'phlev': atmosphere['phlev'],\n            'plev': atmosphere['plev'],\n        }\n\n    def update_heatingrates(self, atmosphere, surface, cloud):\n        \"\"\"Returns `xr.Dataset` containing radiative transfer results.\"\"\"\n        self.calc_radiation(atmosphere, surface, cloud)\n\n        def fluxes(net_fluxes, pressure):\n            Q = fluxes2heating(net_fluxes, pressure, method=\"gradient\")\n            f = PchipInterpolator(np.log(pressure[::-1]), Q[::-1])\n            return f(np.log(atmosphere[\"plev\"]))\n\n        self['sw_htngrt'][-1] = fluxes(\n            net_fluxes=self['sw_flxu'][-1] - self['sw_flxd'][-1],\n            pressure=atmosphere['phlev'],\n        )\n\n        self['sw_htngrt_clr'][-1] = fluxes(\n            net_fluxes=self['sw_flxu_clr'][-1] - self['sw_flxd_clr'][-1],\n            pressure=atmosphere['phlev'],\n        )\n\n        self['lw_htngrt'][-1] = fluxes(\n            net_fluxes=self['lw_flxu'][-1] - self['lw_flxd'][-1],\n            pressure=atmosphere['phlev'],\n        )\n\n        self['lw_htngrt_clr'][-1] = fluxes(\n            net_fluxes=self['lw_flxu_clr'][-1] - self['lw_flxd_clr'][-1],\n            pressure=atmosphere['phlev'],\n        )\n\n        self.derive_diagnostics()\n", "meta": {"hexsha": "e529e741432fe600662255d21155ac5097c32d9e", "size": 15090, "ext": "py", "lang": "Python", "max_stars_repo_path": "konrad/radiation/arts.py", "max_stars_repo_name": "jiaweibao/konrad", "max_stars_repo_head_hexsha": "45bfe6729a7ea61b17c25d071ccf90b0db9e497a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "konrad/radiation/arts.py", "max_issues_repo_name": "jiaweibao/konrad", "max_issues_repo_head_hexsha": "45bfe6729a7ea61b17c25d071ccf90b0db9e497a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "konrad/radiation/arts.py", "max_forks_repo_name": "jiaweibao/konrad", "max_forks_repo_head_hexsha": "45bfe6729a7ea61b17c25d071ccf90b0db9e497a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9852941176, "max_line_length": 88, "alphanum_fraction": 0.6198144467, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.27512972382317524, "lm_q1q2_score": 0.1504239208230495}}
{"text": "#utilities for running in-silico mutagenesis within dragonn.\nimport numpy as np\nfrom keras.models import Model\n\ndef ism_wrapper(inputs):\n        X=inputs[0]\n        preact_function=inputs[1]\n        task_index=inputs[2]\n        target_layer_idx=inputs[3]\n        use_gc=inputs[4]\n        if use_gc==True:\n                return in_silico_mutagenesis_gc(preact_function,X,task_index,target_layer_idx)\n        else:\n                return in_silico_mutagenesis(preact_function,X,task_index,target_layer_idx)\ndef get_preact_function(model,target_layer_idx):\n        #load the model to predict preacts\n        preact_model=Model(inputs=model.input,\n                           outputs=model.layers[target_layer_idx].output)\n        return preact_model.predict\n\ndef in_silico_mutagenesis(preact_function, X, task_index,target_layer_idx=-2,start_pos=None,end_pos=None):\n    \"\"\"\n    Parameters                               \n    ----------                                \n    model: keras model object\n    X: input matrix: (num_samples, 1, sequence_length,num_bases)\n    Returns\n    ---------\n    (num_task, num_samples, sequence_length,num_bases) ISM score array.\n    \"\"\"\n    preact_function=get_preact_function(model,target_layer_idx)\n    #1. get the wildtype predictions (n,1)    \n    wild_type_logits=np.expand_dims(preact_function(X)[:,task_index],axis=1)\n    \n    #2. expand the wt array to dimensions: (n,1,sequence_length,num_bases)\n    \n    #Initialize mutants array to the same shape                                     \n    output_dim=wild_type_logits.shape+X.shape[2:4]\n    wt_expanded=np.zeros(output_dim)\n    mutants_expanded=np.zeros(output_dim)\n    empty_onehot=np.zeros(output_dim[3])\n    if start_pos is None:\n        start_pos=0\n    if end_pos is None:\n        end_pos=output_dim[2] \n\n    #3. Iterate through all tasks, positions\n    for sample_index in range(output_dim[0]):\n        print(\"ISM: task:\"+str(task_index)+\" sample:\"+str(sample_index))\n        #fill in wild type logit values into an array of dim (task,sequence_length,num_bases)\n        wt_logit_for_task_sample=wild_type_logits[sample_index]\n        wt_expanded[sample_index]=np.tile(wt_logit_for_task_sample,(output_dim[2],output_dim[3]))\n        #mutagenize each position\n        temp_batch = []\n        tempbatch_baseposandletter = []\n        for base_pos in range(start_pos,end_pos):\n            #for each position, iterate through the 4 bases\n            for base_letter in range(output_dim[3]):\n                cur_base=np.array(empty_onehot)\n                cur_base[base_letter]=1\n                Xtmp=np.array(X[sample_index])\n                Xtmp[0][base_pos]=cur_base\n                temp_batch.append(Xtmp)\n                tempbatch_baseposandletter.append((base_pos, base_letter))\n        #get the logits of the batch\n        batch_logits = preact_function([temp_batch]) \n        for logit,(base_pos, base_letter) in zip(batch_logits, tempbatch_baseposandletter):\n            mutants_expanded[sample_index][0][base_pos][base_letter]=logit\n                \n    #subtract wt_expanded from mutants_expanded\n    ism_vals=mutants_expanded-wt_expanded\n    #For each position subtract the mean ISM score for that position from each of the 4 values\n    ism_vals_mean=np.expand_dims(np.mean(ism_vals,axis=3),axis=3)\n    ism_vals_normed=ism_vals-ism_vals_mean\n    return ism_vals_normed, ism_vals_normed*X \n\n\n\ndef in_silico_mutagenesis_gc(preact_function, X, task_index,target_layer_idx=-2,start_pos=None,end_pos=None):\n    \"\"\"\n    Parameters                               \n    ----------                                \n    model: keras model object\n    X: input matrix: (num_samples, 1, sequence_length,num_bases)\n    Returns\n    ---------\n    (num_task, num_samples, sequence_length,num_bases) ISM score array.\n    \"\"\"\n    print(\"WE ARE MAKING THE ASSUMPTION THAT THE SEQUENCE INPUT IS THE FIRST INPUT IN THE MODEL AND GC IS THE SECOND INPUT\") \n    #1. get the wildtype predictions (n,1)    \n    wild_type_logits=np.expand_dims(preact_function(X)[:,task_index],axis=1)\n    \n    #2. expand the wt array to dimensions: (n,1,sequence_length,num_bases)\n    \n    #Initialize mutants array to the same shape                                     \n    output_dim=wild_type_logits.shape+X[0].shape[2:4]\n    wt_expanded=np.zeros(output_dim)\n    mutants_expanded=np.zeros(output_dim)\n    empty_onehot=np.zeros(output_dim[3])\n    if start_pos is None:\n        start_pos=0\n    if end_pos is None:\n        end_pos=output_dim[2] \n\n   \n    #3. Iterate through all tasks, positions\n    for sample_index in range(output_dim[0]):\n        print(\"ISM: task:\"+str(task_index)+\" sample:\"+str(sample_index))\n        #fill in wild type logit values into an array of dim (task,sequence_length,num_bases)\n        wt_logit_for_task_sample=wild_type_logits[sample_index]\n        wt_expanded[sample_index]=np.tile(wt_logit_for_task_sample,(output_dim[2],output_dim[3]))\n        #mutagenize each position\n        temp_batch = []\n        tempbatch_baseposandletter = []\n        temp_gc=[] \n        for base_pos in range(start_pos,end_pos):\n            #for each position, iterate through the 4 bases\n            for base_letter in range(output_dim[3]):\n                cur_base=np.array(empty_onehot)\n                cur_base[base_letter]=1\n                Xtmp=np.array(X[0][sample_index])\n                Xtmp[0][base_pos]=cur_base\n                temp_batch.append(Xtmp)\n                tempbatch_baseposandletter.append((base_pos, base_letter))\n                temp_gc.append(X[1][sample_index])\n        #get the logits of the batch\n        new_input_seq=np.array(temp_batch)\n        new_gc=np.array(temp_gc)        \n        batch_logits = preact_function([new_input_seq,new_gc])\n        for logit,(base_pos, base_letter) in zip(batch_logits, tempbatch_baseposandletter):\n            mutants_expanded[sample_index][0][base_pos][base_letter]=logit\n                \n    #subtract wt_expanded from mutants_expanded\n    ism_vals=mutants_expanded-wt_expanded\n    #For each position subtract the mean ISM score for that position from each of the 4 values\n    ism_vals_mean=np.expand_dims(np.mean(ism_vals,axis=3),axis=3)\n    ism_vals_normed=ism_vals-ism_vals_mean\n\n    #get the allele with the most significant effect.    \n    return ism_vals_normed, ism_vals_normed*X[0] \n", "meta": {"hexsha": "4b4ebc9f0cf109176d18b881364e1a71d8b9c06f", "size": 6320, "ext": "py", "lang": "Python", "max_stars_repo_path": "kerasAC/interpret/ism/ism_bulk.py", "max_stars_repo_name": "kundajelab/kerasAC", "max_stars_repo_head_hexsha": "6aa6573f5f07659bfd68deca37de77e47612020e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-10-30T20:33:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-07T05:28:47.000Z", "max_issues_repo_path": "kerasAC/interpret/ism/ism_bulk.py", "max_issues_repo_name": "kundajelab/kerasAC", "max_issues_repo_head_hexsha": "6aa6573f5f07659bfd68deca37de77e47612020e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-07-01T19:23:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T00:55:54.000Z", "max_forks_repo_path": "kerasAC/interpret/ism/ism_bulk.py", "max_forks_repo_name": "kundajelab/kerasAC", "max_forks_repo_head_hexsha": "6aa6573f5f07659bfd68deca37de77e47612020e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-09-24T16:17:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T20:04:35.000Z", "avg_line_length": 44.8226950355, "max_line_length": 125, "alphanum_fraction": 0.6617088608, "include": true, "reason": "import numpy", "num_tokens": 1499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.2751297238231752, "lm_q1q2_score": 0.15042391675911998}}
{"text": "#!/usr/bin/env python\nimport numpy as np\nimport pandas as pd\nfrom astropy.io import fits\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport pickle\nfrom astropy.table import Table\nimport argparse\nimport os,sys\npd.options.mode.chained_assignment = None\nimport pkg_resources\n\nexample_text = '''Examples:\nauriga test.fits --tableOut test-out --saveFlux test --tutorial \\n\nauriga test.csv --localFlux --iters=20 --tutorial\\n\nauriga test.fits --localFlux --gaiaFluxErrors --g phot_g_mean_mag --bp phot_bp_mean_mag --rp phot_rp_mean_mag --j j_m --h h_m --k ks_m --ej j_msigcom --eh h_msigcom --ek ks_msigcom --eparallax parallax_error --tutorial\n'''\n\nparser = argparse.ArgumentParser(description='Running Auriga neural net to determine age, extinction, and distance to a stellar population',epilog=example_text,formatter_class=argparse.RawDescriptionHelpFormatter)\nparser.add_argument(\"tableIn\",help=\"Input table with Gaia DR2 source ids and cluster ids\")\nparser.add_argument(\"--tutorial\",help=\"Use included test.fits or test.csv files as inputs\",action='store_true')\nparser.add_argument(\"--tableOut\",help=\"Prefix of the csv file into which the cluster properties should be written, default tableIn-out\",default='')\nparser.add_argument(\"--iters\", type=int,help=\"Number of iterations of each cluster is passed through Auriga to generate the errors, default 10\",default=10)\nparser.add_argument(\"--localFlux\",help=\"Download necessary flux from Gaia archive for all source ids, default True\",action='store_false')\nparser.add_argument(\"--saveFlux\",help=\"If downloading flux, prefix of file where to save it, default empty\",default='')\nparser.add_argument(\"--silent\",help=\"Suppress print statements, default False\",action='store_false')\nparser.add_argument(\"--cluster\",help=\"Column with cluster membership\",default='cluster')\nparser.add_argument(\"--source_id\",help=\"Column with Gaia DR2 source id,\",default='source_id')\nparser.add_argument(\"--gaiaFluxErrors\",help=\"If loading flux, whether uncertainties in Gaia bands have been converted from flux to magnitude, default True\",action='store_true')\nparser.add_argument(\"--g\",help=\"If loading flux, column for G magnitude\",default='g')\nparser.add_argument(\"--bp\",help=\"If loading flux, column for BP magnitude\",default='bp')\nparser.add_argument(\"--rp\",help=\"If loading flux, column for RP magnitude\",default='rp')\nparser.add_argument(\"--j\",help=\"If loading flux, column for J magnitude\",default='j')\nparser.add_argument(\"--h\",help=\"If loading flux, column for H magnitude\",default='h')\nparser.add_argument(\"--k\",help=\"If loading flux, column for K magnitude\",default='k')\nparser.add_argument(\"--parallax\",help=\"If loading flux, column for parallax\",default='parallax')\nparser.add_argument(\"--eg\",help=\"If loading flux, column for uncertainty in G magnitude\",default='eg')\nparser.add_argument(\"--ebp\",help=\"If loading flux, column for uncertainty in BP magnitude\",default='ebp')\nparser.add_argument(\"--erp\",help=\"If loading flux, column for uncertainty in RP magnitude\",default='erp')\nparser.add_argument(\"--ej\",help=\"If loading flux, column for uncertainty in J magnitude\",default='ej')\nparser.add_argument(\"--eh\",help=\"If loading flux, column for uncertainty in H magnitude\",default='eh')\nparser.add_argument(\"--ek\",help=\"If loading flux, column for uncertainty in K magnitude\",default='ek')\nparser.add_argument(\"--eparallax\",help=\"If loading flux, column for uncertainty in parallax\",default='eparallax')\nparser.add_argument(\"--gf\",help=\"If uncertainties have not been converted to magnitudes, column for G flux\",default='phot_g_mean_flux')\nparser.add_argument(\"--bpf\",help=\"If uncertainties have not been converted to magnitudes, column for BP flux\",default='phot_bp_mean_flux')\nparser.add_argument(\"--rpf\",help=\"If uncertainties have not been converted to magnitudes, column for RP flux\",default='phot_rp_mean_flux')\nparser.add_argument(\"--egf\",help=\"If uncertainties have not been converted to magnitudes, column for uncertainty in G flux\",default='phot_g_mean_flux_error')\nparser.add_argument(\"--ebpf\",help=\"If uncertainties have not been converted to magnitudes, column for uncertainty in BP flux\",default='phot_bp_mean_flux_error')\nparser.add_argument(\"--erpf\",help=\"If uncertainties have not been converted to magnitudes, column for uncertainty in RP flux\",default='phot_rp_mean_flux_error')\n\n\n\n\n#Normalizes all the variables for training, and returns back the original values afterwards\ndef convunit(v,b,back=False):\n    a=[['g',18,0.5],['bp',21,0.5],['rp',18,0.5],['j',17.5,0.5],['h',16.5,0.5],['k',16.5,0.5],\n     ['w1',16.5,0.5],['w2',16.5,0.5],['w3',14,0.5],['parallax',20,0.5],['radius',5,0.54],\n     ['logl',4,0],['av',20,0.3],['age',4,2],['mass',3,0.5],['teff',0.7,3.4/0.7+0.5],\n     ['logg',2,2],['feh',3,-2.5/3+0.5],['dist',3.7,0.5]]\n    for i in a:\n        if b==i[0]:\n            if back:\n                return (v+i[2])*i[1]\n            else:\n                return (v/i[1])-i[2]\n    return bad\n\n#https://github.com/eladhoffer/convNet.pytorch/blob/master/models/mnist.py\nclass Net(nn.Module):\n\n    def __init__(self, input_shape=(1, 7, 250),drop_p=0.1):\n        super(Net, self).__init__()\n        self.feats = nn.Sequential(\n            nn.Conv2d(1, 32, 5, 1, 1),\n            nn.MaxPool2d(2, 2),\n            nn.ReLU(True),\n            nn.BatchNorm2d(32),\n\n            nn.Conv2d(32, 64, 3,  1, 1),\n            nn.ReLU(True),\n            nn.BatchNorm2d(64),\n\n            nn.Conv2d(64, 64, 3,  1, 1),\n            nn.MaxPool2d(2, 2),\n            nn.ReLU(True),\n            nn.BatchNorm2d(64),\n\n            nn.Conv2d(64, 128, 3, 1, 1),\n            nn.ReLU(True),\n            nn.BatchNorm2d(128)\n        )\n\n        self.classifier = nn.Conv2d(128, 10, 1)\n        self.avgpool = nn.AvgPool2d(2,2)\n        self.dropout = nn.Dropout(0.5)\n        self.fc1 = nn.Linear(620, 512)\n        self.fc2 = nn.Linear(512, 512)\n        self.fc3 = nn.Linear(512, 3)\n\n    def forward(self, inputs):\n        out = self.feats(inputs)\n        out = self.dropout(out)\n        out = self.classifier(out)\n        out = out.view(out.size(0), -1)\n        out = F.relu(self.fc1(out))\n        out = F.relu(self.fc2(out))\n        out = self.dropout(out)\n        out = self.fc3(out)\n        return out\nmodel = Net()\n\n\ndef makepandasfromadql(data,args):\n    from astroquery.gaia import Gaia\n    if args.silent: print('Downloading photometry from Gaia Archive')\n    table=Table([data[args.cluster],data[args.source_id]],names=['cluster', 'source_id'])\n    j = Gaia.launch_job_async(query=\"select tc.cluster, g.source_id,g.parallax,g.parallax_error as eparallax,g.phot_g_mean_mag as g,-2.5*log10(abs(phot_g_mean_flux-phot_g_mean_flux_error))+2.5*log10(abs(phot_g_mean_flux+phot_g_mean_flux_error)) as eg, g.phot_bp_mean_mag as bp,-2.5*log10(abs(phot_bp_mean_flux-phot_bp_mean_flux_error))+2.5*log10(abs(phot_bp_mean_flux+phot_bp_mean_flux_error)) as ebp,g.phot_rp_mean_mag as rp,-2.5*log10(abs(phot_rp_mean_flux-phot_rp_mean_flux_error))+2.5*log10(abs(phot_rp_mean_flux+phot_rp_mean_flux_error)) as erp,tm.j_m as j,tm.j_msigcom as ej,tm.h_m as h,tm.h_msigcom as eh,tm.ks_m as k,tm.ks_msigcom as ek \\\n\tFROM gaiadr2.gaia_source AS g \\\n\tinner join TAP_UPLOAD.table_test AS tc \\\n\tON g.source_id = tc.source_id \\\n\tLEFT OUTER JOIN gaiadr2.tmass_best_neighbour AS xmatch \\\n\tON g.source_id = xmatch.source_id \\\n\tLEFT OUTER JOIN gaiadr1.tmass_original_valid AS tm \\\n\tON tm.tmass_oid = xmatch.tmass_oid\", upload_resource=table, upload_table_name=\"table_test\")\n    d = j.get_results().to_pandas()\n    d['cluster']=d['cluster'].str.decode(encoding = 'UTF-8') \n    if args.saveFlux !='':d.to_csv(args.saveFlux+'.csv',index=False)\n    return d\n\ndef makepandasfromdata(data,args):\n    if args.silent: print('Reading in data from the table - make sure the the columns have been defined correctly')\n    d=pd.DataFrame(columns=['cluster','g','bp','rp','j','h','k','age','av','dist','parallax','eparallax','eg','ebp','erp','ej','eh','ek'],index=range(len(data[args.cluster])))\n    d['cluster']=np.array(data[args.cluster]).byteswap().newbyteorder()\n    d['g']=np.array(data[args.g]).byteswap().newbyteorder()\n    d['bp']=np.array(data[args.bp]).byteswap().newbyteorder()\n    d['rp']=np.array(data[args.rp]).byteswap().newbyteorder()\n    d['j']=np.array(data[args.j]).byteswap().newbyteorder()\n    d['h']=np.array(data[args.h]).byteswap().newbyteorder()\n    d['k']=np.array(data[args.k]).byteswap().newbyteorder()\n    if args.gaiaFluxErrors:\n        d['eg']=np.array((-2.5*np.log10(data[args.gf]-data[args.egf])+2.5*np.log10(data[args.gf]+data[args.egf]))/2).byteswap().newbyteorder()\n        d['ebp']=np.array((-2.5*np.log10(data[args.bpf]-data[args.ebpf])+2.5*np.log10(data[args.bpf]+data[args.ebpf]))/2).byteswap().newbyteorder()\n        d['erp']=np.array((-2.5*np.log10(data[args.rpf]-data[args.erpf])+2.5*np.log10(data[args.rpf]+data[args.erpf]))/2).byteswap().newbyteorder()\n    else:\n        d['eg']=np.array(data[args.eg]).byteswap().newbyteorder()\n        d['ebp']=np.array(data[args.ebp]).byteswap().newbyteorder()\n        d['erp']=np.array(data[args.erp]).byteswap().newbyteorder()\n    d['ej']=np.array(data[args.ej]).byteswap().newbyteorder()\n    d['eh']=np.array(data[args.eh]).byteswap().newbyteorder()\n    d['ek']=np.array(data[args.ek]).byteswap().newbyteorder()\n    d['parallax']=np.array(data[args.parallax]).byteswap().newbyteorder()\n    d['eparallax']=np.array(data[args.eparallax]).byteswap().newbyteorder()\n    return d\n\ndef fillmissing(d):\n    d['bp']=d['bp'].fillna(21)\n    d['ebp']=d['ebp'].fillna(0)\n    d['rp']=d['rp'].fillna(18)\n    d['erp']=d['erp'].fillna(0)\n    d['j']=d['j'].fillna(17.5)\n    d['ej']=d['ej'].fillna(0)\n    d['h']=d['h'].fillna(16.5)\n    d['eh']=d['eh'].fillna(0)\n    d['k']=d['k'].fillna(16.5)\n    d['ek']=d['ek'].fillna(0)\n    d['eparallax']=d['eparallax'].fillna(0.2)\n    d=d.sort_values(by=['cluster'])\n    return d\n\ndef maketensor(d,args):\n    if args.silent: print('Putting together a tensor file')\n    un=np.unique(d['cluster'])\n    clusterx=torch.zeros(len(un)*args.iters, 1,7, 250)*0+0.5\n    clusterx[:,:,6]=clusterx[:,:,6]-1\n    clusterref=pd.DataFrame(columns=['cluster'],index=range(len(un)*args.iters))\n    n=0\n    for i in un:\n        temp=d[(d['cluster']==i)]\n        try:\n            i=i.decode()\n        except:\n            pass\n        if args.silent: print(i)\n        \n        x=len(temp)\n        for todo in range(args.iters):\n            rand=np.random.normal(0,1,x*7)\n            sel=temp.copy()\n            \n            sel['g']=sel['g']+rand[0:x]*sel['eg']\n            sel['bp']=sel['bp']+rand[x:2*x]*sel['ebp']\n            sel['rp']=sel['rp']+rand[2*x:3*x]*sel['erp']\n            sel['j']=sel['j']+rand[3*x:4*x]*sel['ej']\n            sel['h']=sel['h']+rand[4*x:5*x]*sel['eh']\n            sel['k']=sel['k']+rand[5*x:6*x]*sel['ek']\n            sel['parallax']=sel['parallax'].to_numpy()+rand[6*x:7*x]*sel['eparallax']\n            \n            a=np.random.choice(np.arange((len(sel))),250)\n            sel=sel.iloc[a]\n            sel=sel.sort_values(by=['g'])\n            clusterx[n][0][0][0:len(a)]=torch.Tensor(convunit(sel['g'],'g').to_numpy())\n            clusterx[n][0][1][0:len(a)]=torch.Tensor(convunit(sel['bp'],'bp').to_numpy())\n            clusterx[n][0][2][0:len(a)]=torch.Tensor(convunit(sel['rp'],'rp').to_numpy())\n            clusterx[n][0][3][0:len(a)]=torch.Tensor(convunit(sel['j'],'j').to_numpy())\n            clusterx[n][0][4][0:len(a)]=torch.Tensor(convunit(sel['h'],'h').to_numpy())\n            clusterx[n][0][5][0:len(a)]=torch.Tensor(convunit(sel['k'],'k').to_numpy())\n            clusterx[n][0][6][0:len(a)]=torch.Tensor(convunit(sel['parallax'],'parallax').to_numpy())   \n            clusterref['cluster'][n]=i\n            n=n+1\n    #if save!='': pickle.save([clusterx,clusterref],open('final31.pickle','wb'))\n    return clusterx,clusterref\n\ndef predict(clusterx,clusterref,name,args,iters=10):\n    if args.silent: print('Predicting population properties')\n    model.load_state_dict(torch.load(pkg_resources.resource_filename('auriga', 'auriga.pt'), map_location='cpu'))\n    model.eval()\n\n    result=pd.DataFrame(index=clusterref.index,columns=['age','av','dist'])\n    k=np.array(range(len(clusterx)))\n    batch_size=5000\n    for i in range(0, len(clusterx), batch_size):\n        inputs = clusterx[k[i:i + batch_size]]\n        with torch.no_grad():\n            a=model(inputs)\n        r=a.cpu().detach().numpy()\n        result['age'].iloc[k[i:i + batch_size]]=convunit(r[:,0],'age',back=True)\n        result['av'].iloc[k[i:i + batch_size]]=convunit(r[:,1],'av',back=True)\n        result['dist'].iloc[k[i:i + batch_size]]=convunit(r[:,2],'dist',back=True)\n    \n        \n    r=pd.DataFrame(columns=['cluster','age','eage','av','eav','dist','edist'],index=np.arange(len(result)/iters))\n    for i in np.arange(len(result)/iters).astype(int):\n        r['age'].iloc[i]=np.mean(result['age'].iloc[i*iters:i*iters+iters])\n        r['eage'].iloc[i]=np.std(result['age'].iloc[i*iters:i*iters+iters])\n        r['av'].iloc[i]=np.mean(result['av'].iloc[i*iters:i*iters+iters])\n        r['eav'].iloc[i]=np.std(result['av'].iloc[i*iters:i*iters+iters])\n        r['dist'].iloc[i]=np.mean(result['dist'].iloc[i*iters:i*iters+iters])\n        r['edist'].iloc[i]=np.std(result['dist'].iloc[i*iters:i*iters+iters])\n        r['cluster'].iloc[i]=clusterref['cluster'].iloc[i*iters]\n    \n    r['dist']=10**r['dist']\n    r['edist']=r['edist']*r['dist']*np.log(10)\n    r.to_csv(name+'.csv',index=False)\n    return r\n\ndef tolowercase(data):\n\tkeys=data.keys()\n\tfor key in keys: data[key].name=key.lower()\n\treturn data\n    \ndef main():\n\tif len(sys.argv)==1:\n\t\tparser.print_help(sys.stderr)\n\t\tsys.exit(1)\n\targs=parser.parse_args()\n\tif args.tableOut=='': args.tableOut=args.tableIn.split('.')[0]+'-out'\n\tif args.tutorial: \n\t    args.tableIn=pkg_resources.resource_filename('auriga', 'test/'+args.tableIn)\n\t    if args.silent:print('Reading test file, '+args.tableIn)\n\tif(os.path.exists(args.tableIn)):\n\t\tif args.tableIn.split('.')[-1]=='fits':\n\t\t\tdata = tolowercase(Table.read(args.tableIn))\n\t\telif args.tableIn.split('.')[-1]=='csv':\n\t\t\tdata = pd.read_csv(args.tableIn)\n\t\telse:\n\t\t\traise ValueError(\"Valid fits or csv table is required\")\n\t\t\n\t\tif args.localFlux:\n\t\t\td=fillmissing(makepandasfromadql(data,args))\n\t\telse:\n\t\t\td=fillmissing(makepandasfromdata(data,args))\n\t\tclusterx,clusterref=maketensor(d,args)\n\t\tr=predict(clusterx,clusterref,args.tableOut,args,iters=args.iters)\n\t\tif args.silent:\n\t\t    print(r)\n\t\t    print('Written out to '+args.tableOut+'.csv')\n\telse:\n\t\traise ValueError(\"Can't find the input table\")\n\t\n    \nif __name__ == '__main__':\n    main()", "meta": {"hexsha": "6998dbda1e047f21e38be8a176308f16ae68448b", "size": 14646, "ext": "py", "lang": "Python", "max_stars_repo_path": "auriga/auriga.py", "max_stars_repo_name": "mkounkel/Auriga", "max_stars_repo_head_hexsha": "2a50ed4fe076c72a9770ac3efd290191a51ce502", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-21T22:41:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-04T22:49:43.000Z", "max_issues_repo_path": "auriga/auriga.py", "max_issues_repo_name": "mkounkel/Auriga", "max_issues_repo_head_hexsha": "2a50ed4fe076c72a9770ac3efd290191a51ce502", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "auriga/auriga.py", "max_forks_repo_name": "mkounkel/Auriga", "max_forks_repo_head_hexsha": "2a50ed4fe076c72a9770ac3efd290191a51ce502", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.5704225352, "max_line_length": 646, "alphanum_fraction": 0.6573125768, "include": true, "reason": "import numpy,from astropy", "num_tokens": 4184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.23091976822203994, "lm_q1q2_score": 0.15041071750464882}}
{"text": "![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true)\n\n<a href=\"https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=Science/UniformMotionAndUniformlyAcceleratedMotion/uniform-motion-and-uniformly-accelerated-motion.ipynb&depth=1\" target=\"_parent\"><img src=\"https://raw.githubusercontent.com/callysto/curriculum-notebooks/master/open-in-callysto-button.svg?sanitize=true\" width=\"123\" height=\"24\" alt=\"Open in Callysto\"/></a>\n\nfrom IPython.display import HTML\nhide_me = ''\nHTML('''<script>\ncode_show=true; \nfunction code_toggle() {\n if (code_show){\n $('div.input').hide();\n } else {\n $('div.input').show();\n }\n code_show = !code_show\n} \n$( document ).ready(code_toggle);\n</script>\nTo toggle on/off the raw code, click <a href=\"javascript:code_toggle()\">here</a>.''')\n\nhide_me\n\nimport ipywidgets as widgets\nfrom IPython.display import display, Math, Latex, HTML, IFrame\nfrom ipywidgets import IntSlider, Label\nfrom ipywidgets import interact, interactive\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nimport pandas as pd\n\n\n# Uniform Motion and Uniformly Accelerated Motion\n\nGrade 11\n\n <img src=\"images/motion.gif\" width=\"500\" height=\"400\" />\n\n<font size = 1 > <center> https://giphy.com/gifs/usain-bolt-sgjJkkJutglMY </center> </font>\n\n## Introduction\n\nEverything in the universe is constantly moving. Objects can be moving incredibly slow, so slow that they appear to be at rest, or so incredibly fast that you may not even see it. Even if you're standing still on Earth, you're  moving and incomprehensible speeds. On Earth, you are moving around the Sun at approximately 108,000 km/h, and the Sun is orbiting galactic center at approximately 720,000 km/h. But that's not it: our galaxy the Milky Way is moving at approximately 2,268,000 km/h.  As motion is so universal, understanding motion is an important topic of physics. Motion is defined by the change of position of an object with respect to other surrounding objects. For example a car is moving with respect to trees on the roadside. Motion can be described using three important quantities: velocity, speed and acceleration. In this notebook, we will familiarize ourselves with two types of motion: uniform motion, and uniformly accelerated motion.\n\n## Concepts of Uniform Motion\n\nMotion is described by three variables: distance ($d$), velocity ($\\vec{v}$), and acceleration ($\\vec{a}$). Let's define and explore these quantities below.\n\n### Distance Vs. Displacement\nTo begin, let us outline the difference between distance and displacement. \n> Distance describes the length of the actual path travelled to travel from one point to another.\n\n> Displacement is identical to distance as it describes the amount of space between two points. However, displacement is a vector quantity which means it also specifies the _direction_ of travel, as well as the amount of space between two points​.\n\nBelow is a video which demonstrates the difference between distance and displacement:\n\n%%html\n<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/u60JlEAGGWM\" frameborder=\"0\" allow=\"autoplay; encrypted-media\" allowfullscreen></iframe>\n\n**Practise**\n\nCalculate the distance and displacement based on the image below. Imagine you start at  point $\\textrm{A}$ and you move around the field in the following order \n\n$$\\textrm{A} \\rightarrow \\textrm{B} \\rightarrow \\textrm{C} \\rightarrow \\textrm{D} \\rightarrow \\textrm{E} \\rightarrow \\textrm{A}$$\n\n<img src=\"images/distance.JPG\" width=700 height=500 align = \"left\">\n\nhide_me\n\ndef q_1(val):\n    if val == \"Distance: 2m and Displacement: 2m East\":\n        display(Latex(\"Correct!\"))\n        display(Latex(\"Displacement contains both measurement and direction\"))\n    elif val == ' ':\n        None\n    else:\n        display(Latex(\"Try Again!\"))\n\ndisplay(\"Calculate the distance and displacement at point B?\")\n\na1 = 'Distance: 2m and Displacement: 2m'\na2 = \"Distance: 2m and Displacement: 2m East\"\na3 = \"Distance: 2m North and Displacement: 2m\"\ninteract(q_1, val = widgets.Dropdown(options=[' ',a1 ,a2, a3 ],value = ' ',description = 'Choose One:',disabled = False));\n\nhide_me\n\ndef q_2(val):\n    if val == \"Distance: 9m North and Displacement: 2.2m NW\":\n        display(Latex(\"Correct!\"))\n        display(Latex(\"Distance: Actual path covered and Displacement: Shortest path covered with direction\"))\n    elif val == ' ':\n        None\n    else:\n        display(Latex(\"Try Again!\"))\n\ndisplay(\"Calculate the distance and displacement at point E?\")\n\na1 = 'Distance: 9m and Displacement: 7m'\na2 = \"Distance: 3m and Displacement: 2.2m NW\"\na3 = \"Distance: 9m North and Displacement: 2.2m NW\"\ninteract(q_2, val = widgets.Dropdown(options=[' ',a1 ,a2, a3 ],value = ' ',description = 'Choose One:',disabled = False));\n\n### Speed Vs. Velocity\n\nAnalogous to distance and displacement are speed and velocity, however now these quantities also imply that the object's distance/displacement is _changing_. Let's take a look at how speed and velocity are defined.\n\nSpeed is the rate of change of distance over time.\n\n$$\n\\begin{equation}\n\\textrm{speed } = \\frac{\\textrm{change} \\ \\textrm{of} \\ \\textrm{distance (m)}}{\\textrm{time (s)}}\n\\end{equation}\n$$\n\nVelocity is the rate of change of displacement over time.\n\n$$\n\\begin{equation}\n\\textrm{velocity, } \\vec{v} = \\frac{\\textrm{change} \\textrm{ of} \\textrm{ displacement (m)}}{\\textrm{time (s)}} \\\\\n\\textrm{m} = \\textrm{meter } \\textrm{and} \\textrm{ s} = \\textrm{second}\n\\end{equation}\n$$\n\n**Practise**\n\nNow, let's repeat a similar question as we did with displacement and distance, but now include velocity. The required time of one point to another point is given below:\n\n* $\\textrm{A} \\rightarrow \\textrm{C}: 4 \\textrm{ sec}$\n* $\\textrm{A} \\rightarrow \\textrm{D}: 10 \\textrm{ sec}$\n* $\\textrm{A} \\rightarrow \\textrm{E}: 16 \\textrm{ sec}$\n* $\\textrm{A} \\rightarrow \\textrm{A}: 20 \\textrm{ sec}$\n\n\n\n<img src=\"images/speed.JPG\" alt=\"Callysto\" width=700 height=500 align = \"left\">\n\nhide_me\n\ndef q_1(val):\n    if val == \"Speed: 0.75 m/s and Velocity: 0.55 m/s NE\":\n        display(Latex(\"Correct!\"))\n        display(Latex(\"Velocity contains both measurement and direction as it relates to displacement\"))\n    elif val == ' ':\n        None\n    else:\n        display(Latex(\"Try Again!\"))\n\ndisplay(\"Calculate the speed and velocity at point C?\")\n\na1 = 'Speed: 0.75 m/s and Velocity: 0.55 m/s NE'\na2 = \"Speed: 0.55 m/s and Velocity: 0.75 m/s NE\"\na3 = \"Speed: 1 m/s and Velocity: 0.55 m/s NE\"\ninteract(q_1, val = widgets.Dropdown(options=[' ',a1 ,a2, a3 ],value = ' ',description = 'Choose One:',disabled = False));\n\nhide_me\n\ndef q_2(val):\n    if val == \"Speed: 0.60 m/s and Velocity: 0.20 m/s South\":\n        display(Latex(\"Correct!\"))\n        display(Latex(\"Speed and Velocity are not always equivalent\"))\n    elif val == ' ':\n        None\n    else:\n        display(Latex(\"Try Again!\"))\n\ndisplay(\"Calculate the speed and velocity at point D?\")\n\na1 = 'Speed: 0.80 m/s and Velocity: 0.60 m/s South'\na2 = \"Speed: 0.60 m/s and Velocity: 0.20 m/s South\"\na3 = \"Speed: 0.60 m/s and Velocity: 0.60 m/s South\"\ninteract(q_2, val = widgets.Dropdown(options=[' ',a1 ,a2, a3 ],value = ' ',description = 'Choose One:',disabled = False));\n\n### Acceleration\n\nVelocity can also change with respect to time. A change in velocity requires _acceleration_, which is defined as rate of change of velocity over time. As acceleration depends on the change in the vector quantity velocity, acceleration is also a vector. Below is an example of acceleration.\n\n<img src=\"images/acceleration.gif\" width=\"500\" height=\"400\"/>\n<font size = 1 > <center>https://giphy.com/gifs/cell-concept-acceleration-139Qnnkbg2pefe</center> </font>\n\n Acceleration is the rate of change of velocity over time. Acceleration is a vector quantity as it depends on velocity. \n\n$$\n\\begin{equation}\n\\textrm{acceleration, } \\vec{a} = \\frac{\\textrm{change} \\textrm{ of} \\textrm{ velocity } (\\frac{\\text{m}}{\\text{s}}) } {\\textrm{time (s)}} \n\\end{equation}\n$$\n\n [Here is an interactive animation demonstrating acceleration further.](https://faraday.physics.utoronto.ca/PVB/Harrison/Flash/ClassMechanics/MotionDiagram/MotionDiagram.html)\n\n**Practice**\n\nLet's go back to our field example and think about where we may see acceleration. Once again we are traveling from $\\textrm{A} \\rightarrow \\textrm{B} \\rightarrow \\textrm{C} \\rightarrow \\textrm{D} \\rightarrow \\textrm{E} \\rightarrow \\textrm{A}$​: \n\n<img src=\"images/acceleration-img.JPG\" alt=\"Callysto\" width=700 height=500 align = \"left\">\n\n\nhide_me\n\ndef q_1(val):\n    if val == \"Acceleration: 0 m/s\\u00b2 East\":\n        display(Latex(\"Correct!\"))\n        display(Latex(\"No change in velocity and direction is also straight line\"))\n    elif val == ' ':\n        None\n    else:\n        display(Latex(\"Try Again!\"))\n\ndisplay(\"Calculate the acceleration at point B?\")\n\na1 = 'Acceleration: 0 m/s\\u00b2 East'\na2 = \"Acceleration: 1 m/s\\u00b2 East\"\na3 = \"Acceleration: 2 m/s\\u00b2 East\"\ninteract(q_1, val = widgets.Dropdown(options=[' ',a1 ,a2, a3 ],value = ' ',description = 'Choose One:',disabled = False));\n\nhide_me\n\ndef q_1(val):\n    if val == \"Yes\":\n        display(Latex(\"Correct!\"))\n    elif val == ' ':\n        None\n    else:\n        display(Latex(\"Try Again!\"))\n\ndisplay(\"Does a change in direction imply that there was acceleration?\")\n\na1 = 'Yes'\na2 = \"No\"\n\ninteract(q_1, val = widgets.Dropdown(options=[' ',a1 ,a2 ],value = ' ',description = 'Choose One:',disabled = False));\n\ndef q_2(val):\n    if val == 'To change direction is to change your velocity, and this requires acceleration':\n        display(Latex(\"Correct!\"))\n        display(Latex(\"Velocity is a vector quantity. To change your direction requires acceleration in another direction.\"))\n    elif val == ' ':\n        None\n    else:\n        display(Latex(\"Try Again!\"))\n\ndisplay(Latex(\"Why?\"))\n\na1 = 'To change direction is to change your velocity, and this requires acceleration'\na2 = 'When you change direction you gain speed, and this requires acceleration'\n\n\ninteract(q_2, val = widgets.Dropdown(options=[' ',a1 ,a2],value = ' ',description = 'Choose One:',disabled = False));\n\n### Uniform Motion\n\nNow that we have an understanding of distance, displacement, velocity and acceleration, let's use those quantities to describe \"uniform motion\".\n\nUniform motion has the following two properties:\n\n* Motion is constant or steady that means object covers equal distance in equal time interval.\n\n* The object travels in a straight line.\n\nConsider the blue car in the animation below\n\n<img src=\"images/uniform-motion.gif\" width=\"500\" height=\"400\"/>\n<font size = 1 > <center>http://www.ninetyeast.net/physics/grade-9-10-gcse-hsc/forces/newtons-laws-of-motion/newtons-first-law-of-motion</center> </font>\n\nThe blue car is travelling at a velocity of $10 \\textrm{ ms}^{-1}$ to the right. That means every second the car is travelling $10 \\textrm{ m}$. If we record this car's displacement and velocity for $10 \\textrm{ sec}$, we get the following table. \n\n\n| Time $(sec$)  |  Displacement ($m$)   | Velocity ($ms^{-1}$)|\n|:-------------:|:-----------------:|:--------:|\n| $ 1$          | $ 10$             | $10$     | \n| $ 2$          |$ 20$             | $10$     | \n| $ 3$          |$30$              | $10$     | \n| $4$           |$40$              | $10$     | \n| $ 5$          | $ 50$            | $10$     | \n| $ 6$          |$ 60$             | $10$     | \n| $ 7$          |$70$              | $10$     | \n| $8$           |$80$              | $10$     | \n| $ 9$          |$90$              | $10$     | \n| $10$           |$100$              | $10$     |  \n\nWe can also use this table to create the animation below:\n\nhide_me\n\n# Data\nt = np.linspace(0,10,11)\nd = np.linspace(0,100,11)\nv = np.linspace(10,10,11)\n\n# Create a figure with two subplots\nfig, (ax1, ax2) = plt.subplots(1,2, figsize=(10, 4), dpi= 90, facecolor='w', edgecolor='k')\n\n# Same X axis limt and grid initalizations\nfor ax in [ax1, ax2]:\n    ax.set_xlim(0, 10)\n    ax.grid()\n    \nax1.set_ylim(0,100)\nax2.set_ylim(0,20)    \n\n# Initialize the plot\nl1, = ax1.plot([],[], 'go-', label='Displacement', linewidth=2)\nleg = ax1.legend(loc='best')\nl2, = ax2.plot([],[],  'rs-', label='Velocity')\nleg = ax2.legend(loc='best')\n\nfig.suptitle('Uniform Motion')\nax1.set_xlabel('Time (sec)')\nax2.set_xlabel('Time (sec)')\nax1.set_ylabel('Displacement (m)')\nax2.set_ylabel (r'$\\mathrm{Velocity} \\ (\\mathrm{m/s})$')\n             \n# Initiate the animation\ndef animate(i):   \n    l1.set_data(t[:i+1], d[:i+1])\n    l2.set_data(t[:i+1], v[:i+1])\n    \nani = FuncAnimation(fig, animate, interval = 800, frames=len(t))\nplt.close()\n\n# Convert animation to video\nfrom IPython.display import HTML\nHTML(ani.to_html5_video())\n\n\nFrom the table and animations, we find that the blue car's displacement is changing and its velocity is constant. This is an example of uniform motion. The car travels equal distance in equal time.\n\n$$\n\\begin{equation}\n\\textrm{velocity, } \\vec{v} = \\frac{\\textrm{change} \\ \\textrm{of} \\ \\textrm{displacement (m)}}{\\textrm{time (s)}} = \\textrm{constant}\n\\end{equation}\n$$\n\n**Based on your knowledge of uniform motion, what is the blue car's acceleration?**\n\n\nhide_me\n\ndef q_1(val):\n    if val == \"0\":\n        display(Latex(\"Correct!\"))\n        display(Latex(\"Speed is constant and direction is in a straight line\"))\n    elif val == ' ':\n        None\n    else:\n        display(Latex(\"Try Again!\"))\n\na1 = '0'\na2 = 'Constant'\na3 = 'Variable'\n\ninteract(q_1, val = widgets.Dropdown(options=[' ',a1 ,a2, a3 ],value = ' ',description = 'Choose One:',disabled = False));\n\n### Uniform Accelerated Motion\n\nhide_me\n\nfrom IPython.display import HTML\n# Youtube\n#HTML('<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/JLm3JrCPtWs\" frameborder=\"0\" allow=\"autoplay; encrypted-media\" allowfullscreen></iframe>')\n\n%%html\n<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/JLm3JrCPtWs\" frameborder=\"0\" allow=\"autoplay; encrypted-media\" allowfullscreen></iframe>\n\nUniformly accelerated motion is a little different than the uniform motion we discussed earlier. In the case of uniformly accelerated motion, your velocity is increasing constantly and equally in time. Your velocity is changing in a way similar to how displacement changes if you're traveling at constant velocity. Suppose you start at rest and begin running in order to catch a ball. In this scenario, you will need to _accelerate_. Suppose after each second, you are traveling 2 $\\frac{\\textrm{m}}{\\textrm{s}}$ faster than the second previous. In such a case, you have a uniform acceleration of 2 $\\frac{\\textrm{m}}{\\textrm{s}^2}$ (the seconds are squared in the units of acceleration as you are increasing your velocity constantly - i.e. you gain more velocity per second). Let's write down displacement, velocity and acceleration as you try to catch this ball in a table:\n\n| Time $(\\textrm{sec}$)  |  Displacement ($\\textrm{m}$)   | Velocity ($\\textrm{ms}^{-1}$)| Acceleration ($\\textrm{ms}^{-2}$)   \n|:-------------:|:-----------------:|:--------:|:--------:|\n| $ 0$          | $ 0$             | $0$     | $2$      |\n| $ 1$          |$ 1$             | $2$     | $2$      |\n| $ 2$          |$4$              | $4$     | $2$      |\n| $3$           |$9$              | $6$     | $2$      |\n| $ 4$          |$16$              | $8$     | $2$     |\n| $5$           |$25$              | $10$     | $2$    |\n| $6$           |$36$              | $12$     | $2$      |\n| $ 7$          |$49$              | $14$     | $2$     |\n| $8$           |$64$              | $16$     | $2$    |\n\nUsing the table, we can also create an animation\n\nhide_me\n\n# Data\nt = np.linspace(0,8,9);\nd = ([0,1,4,9,16,25,36,49,64]);\nv = ([0,2,4,6,8,10,12,14,16]);\na = np.linspace(2,2,9);\n\n# Create a figure with three subplots\nfig, (ax1, ax2, ax3) = plt.subplots(1,3, figsize=(12.5, 4), dpi= 80, facecolor='w', edgecolor='k')\n\n# Same X axis limt and grid initalizations\nfor ax in [ax1, ax2, ax3]:\n    ax.set_xlim(0, 8);\n    ax.grid();\n    \nax1.set_ylim(0,70);\nax2.set_ylim(0,16);   \nax3.set_ylim(0,5);\n\n# Initialize the plot\nl, = ax1.plot([],[], 'go-', label='Displacement', linewidth=2);\nleg = ax1.legend(loc='best');\nl1, = ax2.plot([],[],  'rs-', label='Velocity');\nleg = ax2.legend(loc='best');\nl2, = ax3.plot([],[], 'b*-', label='Acceleration', linewidth=2);\nleg = ax3.legend(loc='best');\n\nfig.suptitle('Uniformly Accelerated Motion');\nax1.set_xlabel('Time (sec)');\nax2.set_xlabel('Time (sec)');\nax3.set_xlabel('Time (sec)');\nax1.set_ylabel('Displacement (m)');\nax2.set_ylabel (r'$\\mathrm{Velocity} \\ (\\mathrm{m/s})$');\nax3.set_ylabel (r'$\\mathrm{Acceleration} \\ (\\mathrm{m/s}^{2})$');\n\n# Initiate the animation\ndef animate(i):\n    l.set_data(t[:i+1], d[:i+1]);\n    l1.set_data(t[:i+1], v[:i+1]);\n    l2.set_data(t[:i+1], a[:i+1]);\n    \nani=FuncAnimation(fig, animate, interval = 800, frames=len(t));\nplt.close()\n\n# Convert animation to video\nfrom IPython.display import HTML\nHTML(ani.to_html5_video())\n\nNotice how with constant acceleration, your velocity increases _linearly_. As well, when you're accelerating, your displacement changes _parabolically_. These relationships are explained further with the equations of motion below.\n\n\n## Equations of Motion\n\nUsing our relationships between displacement, velocity, acceleration and time, we can define \"equations of motion\" for a moving object. There are four such equations relevant to the principles of uniform motion and uniform acceleration.\n\nSuppose an object with initial velocity $\\vec{\\textrm{v}}_i$ $\\textrm{ms}^{-1}$ is travelling with uniform acceleration $\\vec{\\textrm{a}}$ $\\textrm{ms}^{-2}$. After traveling a displacement $\\vec{\\textrm{s}}$ in time $\\textrm{t}$ the object's final velocity would be $\\vec{\\textrm{v}_f}$ $\\textrm{ms}^{-1}$, these quantities are described by the following equations\n\n$$\n\\begin{align}\n   \\vec{\\textrm{v}_f}=\\vec{\\textrm{v}_i}+\\vec{\\textrm{a}} \\textrm{t} \\ \\ \\ \\ \\ \\ \\ \\  (1) \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\  \\ \\ \\ \\ \\ \\ \n   \\vec{\\textrm{s}} = (\\frac{\\vec{\\textrm{v}_i}+\\vec{\\textrm{v}_f}}{2})\\textrm{t} \\; \\; (2)\n\\end{align}\n$$\n\n\n$$\n\\begin{align}\n\\vec{\\textrm{s}} = \\vec{\\textrm{v}_i}\\textrm{t}+\\frac{1}{2}\\vec{\\textrm{a}}\\textrm{t}^{2} \\; (3) \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\  \\ \\ \n\\vec{\\textrm{v}_f} = \\textrm{v}_i^{2}+2 \\vec{\\textrm{a}} \\; \\vec{\\textrm{s}} \\; \\; \\; \\;  (4)\n\\end{align}\n$$\n\n\nThe equations above describe both uniform motion and uniformly accelerated motion. Equation (1) describes your final velocity given an intial velocity, and an acceleration over time. Notice how this is the equation of a line. This is what we see in the center plot of the animation above. Equation (3) describes your displacement moving at some initial velocity and accelerating uniformly for some time. Notice how time is squared in this equation. This means that this is the equation of a parabola. Equation (3) is what we see in the first plot of the animation above. \n\n### Mathematical Problems\n\nAs we work through the problems below, we will outline the following steps as we come to the solution. Breaking the problem down in this way makes the problem less intimidating, and makes the path to solution more straight foreward.\n\n> 1. Identify and write what information is given in the problem, and the answer that we are asked for.\n2. Using the information we know, and and the problem identified in step one, identify which equation(s) of motion we need to use to solve the problem.\n3. Ensure that all the values are in the correct units and fill them in the selected equation.\n4. Quote the answer and check the units.\n\n#### Problem 1\n\nA bus  accelerates from rest at $4  \\textrm{ms}^{-2}$ until it reaches a final velocity of $40 \\ \\textrm{ms}^{-1}$. For how many seconds was the bus accelerating?\n\n#### Solution\n\n**Step 1:**\n\nGiven,\n\ninitial velocity, $\\vec{\\textrm{v}_i} = 0 \\ \\textrm{ms}^{-1}$ \n\nfinal velocity, $\\vec{\\textrm{v}_f} = 40 \\ \\textrm{ms}^{-1}$ \n\nacceleration, $\\vec{\\textrm{a}} = 4 \\ \\textrm{ms}^{-2}$\n\ntime, $\\textrm{t} = ?$\n\n**Step 2:**\n\nIn this problem, the value of $\\vec{\\textrm{v}_i}$, $\\vec{\\textrm{v}_f}$ and $\\vec{\\textrm{a}}$ are given and $\\textrm{t}$ is required. Now, check the above $4$ motion equations, find the equation is related to$\\vec{\\textrm{v}_i}$, $\\vec{\\textrm{v}_f}$ and $\\vec{\\textrm{a}}$ and $\\textrm{t}$. We find the equation and it is $\\vec{\\textrm{v}_f} = \\vec{\\textrm{v}_i}+\\vec{\\textrm{a}}\\textrm{t}$.\n\n**Step 3:** After checking all the units of the given variable $\\textrm{v}_i$, $\\textrm{v}_f$ and $\\textrm{a}$, we find that they are correct. Then fill them in selected equation:\n\n$$\n\\begin{equation}\n\\vec{\\textrm{v}_f} = \\vec{\\textrm{v}_i}+\\vec{\\textrm{a}}\\textrm{t} \\\\\n\\Rightarrow \\vec{\\textrm{a}}\\textrm{t} = \\vec{\\textrm{v}_f} - \\vec{\\textrm{v}_i} \\\\\n\\Rightarrow \\textrm{t} = \\frac{\\vec{\\textrm{v}_f}-\\vec{\\textrm{v}_i}}{\\vec{\\textrm{a}}} \\\\\n\\Rightarrow \\textrm{t} = \\frac{40\\textrm{ms}^{-1}-0\\textrm{ms}^{-1}}{4\\textrm{ms}^{-2}} \\\\\n\\Rightarrow \\textrm{t} = 10\\textrm{ s}\n\\end{equation}\n$$\n\n**Step 4:**\n\ntime = $10\\textrm{ s}$ $(Ans)$\n\nThis answer can be seen graphically in the animation below:\n\n\nhide_me\n\n# Data frame to create table\ndf = pd.DataFrame()\ndf['Velocity'] = np.arange(0,41,4)\ndf['Time'] = df['Velocity']/4\n\n# Create a figure with two subplots\nfig,(ax1,ax2) = plt.subplots(1,2,figsize=(6.8, 4), dpi= 100)\n\n# Limit and label axis\nax1.set_ylim(0,10)\nax1.set_xlim(0,40)\nax1.set_xlabel('Velocity ($ms^{-1}$)')\nax1.set_ylabel('Time (s)')\nax1.grid()\n\n# Initiate table properties\nfont_size=14\nbbox=[0, 0, 1, 1]\nax2.axis('off')\n\n# Initialize the plot\nl, = ax1.plot([],[], 'go-', label='Time', linewidth=2)\nleg = ax1.legend(loc='best')\n\n# Initiate the animation\ndef animate(i):\n    l.set_data(df['Velocity'][:i+1], df['Time'][:i+1])\n    table = ax2.table(cellText = df.values[:i+1],bbox=bbox, colLabels=df.columns)\n    \n    \nani = FuncAnimation(fig, animate, interval = 800, frames=len(df.index))\nplt.close()\n\n# Convert animation to video\nfrom IPython.display import HTML\nHTML(ani.to_html5_video())\n\n#### Problem 2\n\nA car accelerates uniformly from $16 \\ \\textrm{m/s}$ to $38.8 \\ \\textrm{m/s}$ in $3.1$ seconds. Calculate the distance travelled by the car.\n\n#### Solution\n\n**Step 1:**\n\nGiven,\n\n$\\textrm{initial} \\ \\textrm{velocity}, \\vec{\\textrm{v}_i} = 16 \\ \\textrm{m/s}$\n\n$\\textrm{final} \\ \\textrm{velocity}, \\vec{\\textrm{v}_f} = 38.8 \\ \\textrm{m/s}$\n\n$\\textrm{time, t} = 3.1 \\ \\textrm{s}$ \n\n$\\textrm{displacement, } \\vec{\\textrm{s}} = ?$\n\n**Step 2:**\n\nTry yourself!\n\nhide_me\n\ndisplay('Which equation can be chosen to solve this problem?')\n\n#Create the box to select m=Motion of Equations\na=widgets.Checkbox(\n    value=False,\n    description=r\"$\\vec{\\textrm{v}_f}=\\vec{\\textrm{v}_i}+\\vec{\\textrm{a}} \\textrm{t}$\",\n    disabled=False\n)\n\nb=widgets.Checkbox(\n    value=False,\n    description=r'$\\vec{\\textrm{s}} = (\\frac{\\vec{\\textrm{v}_i}+\\vec{\\textrm{v}_f}}{2})\\textrm{t}$')\n\nc=widgets.Checkbox(\n    value=False,\n    description=r'$\\vec{\\textrm{s}} = \\vec{\\textrm{v}_i}\\textrm{t}+\\frac{1}{2}\\vec{\\textrm{a}}\\textrm{t}^{2}$'\n)\nd=widgets.Checkbox(\n    value=False,\n    description=r'$\\vec{\\textrm{v}_f} = \\vec{\\textrm{v}_i}^{2}+2 \\vec{\\textrm{a}} \\; \\vec{\\textrm{s}}$',\n    disabled=False\n)\n\n#Display the check box\ndisplay(a)\ndisplay(b)\ndisplay(c)\ndisplay(d)\n\n#create a button to check the answer\nbutton_check = widgets.Button(description=\"check\")\ndisplay(button_check)\n\n#Check the answer\ndef check_button(x):\n    if a.value==False and b.value==True and c.value==False and d.value==False:\n        display(Latex(\"Correct. Well done!\"))\n    else: \n        display(Latex(\"Wrong one!\"))\n\nbutton_check.on_click(check_button)\n\n\nhide_me\n\ndef q_1(val):\n    if val == \"84.94 m\":\n        display(Latex(\"Correct!\"))\n        display(Latex(r'$\\vec{\\textrm{s}} = (\\frac{\\vec{\\textrm{v}_i}+\\vec{\\textrm{v}_f}}{2})\\textrm{t}$'))\n        display(Latex(r'$\\vec{\\textrm{s}} = (\\frac{(16 + 38.8)} {2} \\times 3.1) \\textrm{ m}$'))\n        display(Latex(r'$\\vec{\\textrm{s}} = 84.94 \\textrm{ m}$'))\n    elif val == ' ':\n        None\n    else:\n        display(Latex(\"Try Again!\"))\n\ndisplay(\"What is your final displacement?\")\n\na1 = '84.94 m'\na2 = '65.26 m'\na3 = '89.5 m'\n\ninteract(q_1, val = widgets.Dropdown(options=[' ',a1 ,a2, a3 ],value = ' ',description = 'Choose One:',disabled = False));\n\n#### Problem 3\n\nA racing car is traveling with a velocity of $72 \\ \\textrm{km/h}$ N and accelerates at $5 \\ \\textrm{m/s}^{2}$ for $10 \\ \\textrm{s}$ N. What is the final velocity of the car and how far will it travel as it accelerates?\n\n#### Solution\n\n**Step 1:**\n\n\nGiven\n$\\textrm{initial} \\ \\textrm{velocity,} \\vec{\\textrm{v}_i} = 72 \\ \\textrm{km/h}$ N\n\n$\\textrm{acceleration, } \\vec{\\textrm{a}} = 5 \\ \\textrm{m/s}^{2}$ N\n\n$\\textrm{time}, \\textrm{t} = 10 \\ \\textrm{s}$\n\n$\\textrm{final} \\ \\textrm{velocity}, \\vec{\\textrm{v}_f} = ?$\n\n$\\textrm{displacement}, \\vec{\\textrm{s}} = ?$\n\n**Step 2:** Let's try,\n\n\nhide_me\n\ndisplay('Which equations can be chosen to solve this problem?')\n\n#Create the box to select m=Motion of Equations\na=widgets.Checkbox(\n    value=False,\n    description=r\"$\\vec{\\textrm{v}_f}=\\vec{\\textrm{v}_i}+\\vec{\\textrm{a}} \\textrm{t}$\",\n    disabled=False\n)\n\nb=widgets.Checkbox(\n    value=False,\n    description=r'$\\vec{\\textrm{s}} = (\\frac{\\vec{\\textrm{v}_i}+\\vec{\\textrm{v}_f}}{2})\\textrm{t}$')\n\nc=widgets.Checkbox(\n    value=False,\n    description=r'$\\vec{\\textrm{s}} = \\vec{\\textrm{v}_i}\\textrm{t}+\\frac{1}{2}\\vec{\\textrm{a}}\\textrm{t}^{2}$'\n)\nd=widgets.Checkbox(\n    value=False,\n    description=r'$\\vec{\\textrm{v}_f} = \\vec{\\textrm{v}_i}^{2}+2 \\vec{\\textrm{a}} \\; \\vec{\\textrm{s}}$',\n    disabled=False\n)\n\n#Display the check box\ndisplay(a)\ndisplay(b)\ndisplay(c)\ndisplay(d)\n\n#create a button to check the answer\nbutton_check = widgets.Button(description=\"check\")\ndisplay(button_check)\n\n#Check the answer\ndef check_button(x):\n    if a.value==True and b.value==True and c.value==True and d.value==True:\n        display(Latex(\"Correct. Well done!\"))\n        display(Latex(\"yes, all the equations can be used. It depends on which one you are picking.\")) \n    else: \n        display(Latex(\"Try Again!\"))\n        display(Latex('Hint: More than one answers'))      \n\nbutton_check.on_click(check_button)\n\n\n**Step 3:**\n\n$$\n\\begin{equation}\n\\textrm{initial} \\ \\textrm{velocity,} \\vec{\\textrm{v}_i} = 72 \\ \\textrm{km/h} N = \\frac{72\\times1000}{3600} \\ \\textrm{m/s} = 20 \\ \\textrm{m/s} \\; N \n\\end{equation}\n$$\n\nCalculate final velocity,\n\n$$\n\\begin{equation}\n\\vec{\\textrm{v}_f} = \\vec{\\textrm{v}_i}+\\vec{\\textrm{a}}\\textrm{t} \\\\\n\\vec{\\textrm{v}_f}= 20+(5\\times10) \\\\\n\\vec{\\textrm{v}_f}= 70 \\ \\textrm{m/s} N\n\\end{equation}\n$$\n\nCalculate displacement,\n\n$$\n\\begin{equation}\n\\vec{\\textrm{s}} = \\vec{\\textrm{v}_i}\\textrm{t}+\\frac{1}{2}{\\vec{\\textrm{a}}}{\\textrm{t}^{2}} \\\\\n\\vec{\\textrm{s}}=20\\times10+\\frac{1}{2}{5\\times}{10^{2}} \\\\\n\\vec{\\textrm{s}}=(200+250)\\ \\textrm{m} \\\\\n\\vec{\\textrm{s}}=450 \\ \\textrm{m} \\; N\n\\end{equation}\n$$\n\n**Step 4:**\n\n$$\n\\begin{align}\n\\textrm{final} \\ \\textrm{velocity}, \\vec{\\textrm{v}_f}=70 \\ \\textrm{m/s}\\ \\; N \\;\\;(Ans) \\\\\n\\textrm{displacement} = 84.94 \\ \\textrm{m} \\ \\; N \\;\\; (Ans)\n\\end{align}\n$$\n\n#### Problem 4\n\nAn Air Canada plane requires a takeoff speed of $78.5 \\ \\textrm{m/s}$ and $1690 \\ \\textrm{m}$ of runway to reach that speed. Determine the acceleration of this plane and the time required to reach this speed.\n\n#### Solution\n\n**Step 1:** Let's try,\n\nhide_me\n\ndisplay('Which values are given in this problem?')\n\n#Create the box to select m=Motion of Equations\na=widgets.Checkbox(\n    value=False,\n    description=r\"$\\vec{\\textrm{v}_i}$\",\n    disabled=False\n)\n\nb=widgets.Checkbox(\n    value=False,\n    description=r'$\\vec{\\textrm{v}_f}$')\n\nc=widgets.Checkbox(\n    value=False,\n    description=r'$\\vec{\\textrm{a}}$'\n)\nd=widgets.Checkbox(\n    value=False,\n    description=r'$\\vec{\\textrm{s}}$',\n    disabled=False\n)\n\ne=widgets.Checkbox(\n    value=False,\n    description=r'$t$',\n    disabled=False\n)\n\n\n#Display the check box\ndisplay(a)\ndisplay(b)\ndisplay(c)\ndisplay(d)\ndisplay(e)\n\n#create a button to check the answer\nbutton_check = widgets.Button(description=\"check\")\ndisplay(button_check)\n\n#Check the answer\ndef check_button(x):\n    if a.value==True and b.value==True and c.value==False and d.value==True and e.value==False:\n        display(Latex(\"Correct. Well done!\"))\n        display(Latex(\"Initial velocity is also given as initially plane will start from $0$ $ms^{-1}$\"))\n    else: \n        display(Latex(\"Wrong one!\"))\n          \n\nbutton_check.on_click(check_button)\n\n\n**Step 2:**\n\n$$\n\\begin{align}\n\\textrm{Motion} \\ \\textrm{equation,  } \\vec{\\textrm{v}_f} = \\vec{\\textrm{v}_i}^{2}+2 \\vec{\\textrm{a}} \\; \\vec{\\textrm{s}} \\textrm{ and }\n\\vec{\\textrm{v}_f}=\\vec{\\textrm{v}_i}+\\vec{\\textrm{a}} \\textrm{t}\n\\end{align}\n$$\n\n**Step 3**\n\nLet's calculate,\n\nhide_me\n\ndef q_1(val):\n    if val == \"acceleration = 1.82 ms\\u00b2 and time = 43.06 s\":\n        display(Latex(\"Correct!\"))\n    elif val == ' ':\n        None\n    else:\n        display(Latex(\"Try Again!\"))\n\ndisplay(\"What is the plane's required acceleration, and how long was it accelerating?\")\n\na1 = 'acceleration = 1.91 ms\\u00b2 and time = 48.1 s'\na2 = 'acceleration = 1.82 ms\\u00b2 and time = 43.06 s'\na3 = 'acceleration = 1.82 ms\\u00b2 and time = 45.4 s'\n\ninteract(q_1, val = widgets.Dropdown(options=[' ',a1 ,a2, a3 ],value = ' ',description = 'Choose One:',disabled = False));\n\n### Exercise\n\n **Question 1**: \n A car starting from rest in straight moves with uniform acceleration of $5 \\ \\textrm{ms}^{-2}$. What will be the velocity while crossing a person at a distance $40 \\ \\textrm{m}$? (Ans: $20 \\ \\textrm{ms}^{-1}$)\n\n **Question 2**:\n A bike accelerates uniformly from rest to a speed of $1 \\ \\frac{\\textrm{km}}{\\textrm{min}}$ over a distance of $65 \\ \\textrm{m}$. Determine the acceleration of the bike. (Ans: $2.137 \\ \\textrm{ms}^{-1}$)\n\n **Question 3**:\n A bullet leaves a rifle with a velocity of $521 \\ \\textrm{ms}^{-1}$. While accelerating through the barrel of the rifle, the bullet moves a distance of $0.840 \\ \\textrm{m}$. Determine the acceleration of the bullet (Consider a uniform acceleration). (Ans: $1.62 \\times 10^{5} \\ \\textrm{ms}^{-1}$)\n\n **Question 4**:\n The Velocity of a jeep decreases uniformly from $35 \\ \\textrm{ms}^{-1}$ and after $8 \\ \\textrm{s}$ it becomes $10 \\ \\textrm{ms}^{-1}$. Find the acceleration of the car? (Ans: $-3.125 \\ \\textrm{ms}^{-2}$, You do not have worry about the '-' sign. It defines the direction as velocity is decreasing)\n\n## Conclusion\n\nIn this notebook, we introduced two important concepts of motion: Uniform and Uniformly accelerated motion. We demonstrated how motion is related to distance, speed, velocity and acceleration. We also showed the various linear relationships between displacement, velocity and uniform acceleration using both the equations of motion, and the graphs of those functions. Using these equations, we then demonstrated several cases where they we can apply the ideas of uniform motion and uniformly accelerated motion to solve classic physics problems. This notebook serves as an introduction to the concept of uniform and uniformly accelerated motion, and will allow you to solve a great many problems using these concepts, and should act as a reasonable primer for more complex kinematic problems.\n\n[![Callysto.ca License](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-bottom.jpg?raw=true)](https://github.com/callysto/curriculum-notebooks/blob/master/LICENSE.md)", "meta": {"hexsha": "92f8aaba8c1e87d0cd2f9a26f4eac0cee0f21aa9", "size": 31666, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/curriculum-notebooks/Science/UniformMotionAndUniformlyAcceleratedMotion/uniform-motion-and-uniformly-accelerated-motion.py", "max_stars_repo_name": "BryceHaley/curriculum-jbook", "max_stars_repo_head_hexsha": "d1246799ddfe62b0cf5c389394a18c2904383437", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-18T18:19:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T18:19:40.000Z", "max_issues_repo_path": "_build/jupyter_execute/curriculum-notebooks/Science/UniformMotionAndUniformlyAcceleratedMotion/uniform-motion-and-uniformly-accelerated-motion.py", "max_issues_repo_name": "callysto/curriculum-jbook", "max_issues_repo_head_hexsha": "ffb685901e266b0ae91d1250bf63e05a87c456d9", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/curriculum-notebooks/Science/UniformMotionAndUniformlyAcceleratedMotion/uniform-motion-and-uniformly-accelerated-motion.py", "max_forks_repo_name": "callysto/curriculum-jbook", "max_forks_repo_head_hexsha": "ffb685901e266b0ae91d1250bf63e05a87c456d9", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0796252927, "max_line_length": 958, "alphanum_fraction": 0.6632665951, "include": true, "reason": "import numpy", "num_tokens": 9820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.15007781914432272}}
{"text": "# Copyright (C) 2016 Atsushi Togo\n# All rights reserved.\n#\n# This file is part of phonopy.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n#   notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n#   notice, this list of conditions and the following disclaimer in\n#   the documentation and/or other materials provided with the\n#   distribution.\n#\n# * Neither the name of the phonopy project nor the names of its\n#   contributors may be used to endorse or promote products derived\n#   from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport sys\nimport numpy as np\nfrom phonopy.harmonic.dynmat_to_fc import get_commensurate_points\nfrom phonopy.units import AMU, kb_J\nfrom phonopy.structure.grid_points import get_qpoints\n\nclass Velocity(object):\n    def __init__(self,\n                 lattice=None, # column vectors, in Angstrom\n                 positions=None, # fractional coordinates\n                 timestep=None): # in femtosecond\n\n        self._lattice = lattice\n        self._positions = positions\n        self._timestep = timestep\n        self._velocities = None # in m/s [timestep, atom, 3]\n\n    def run(self, skip_steps=0):\n        pos = self._positions\n        diff = pos[(skip_steps + 1):] - pos[skip_steps:-1]\n        diff = np.where(diff > 0.5, diff - 1, diff)\n        diff = np.where(diff < -0.5, diff + 1, diff)\n        self._velocities = np.dot(diff, self._lattice.T * 1e5) / self._timestep\n\n    def get_velocities(self):\n        return self._velocities\n\n    def get_timestep(self):\n        return self._timestep\n\nclass VelocityQpoints(object):\n    def __init__(self,\n                 supercell,\n                 primitive,\n                 velocities, # in m/s either real or reciprocal\n                 symmetry=None,\n                 symprec=1e-5):\n        if symmetry is not None:\n            symprec = symmetry.get_symmetry_tolerance()\n            self._point_group_opts = symmetry.get_pointgroup_operations()\n        else:\n            self._point_group_opts = None\n\n        self._supercell = supercell\n        self._primitive = primitive\n        self._velocities = velocities\n\n        (self._shortest_vectors,\n         self._multiplicity) = primitive.get_smallest_vectors()\n\n        self._qpoints = None\n        self._weights = None\n\n        self._velocities_q = None # [timestep, p_atom, qpoitns, 3]\n\n    def run(self):\n        num_s = self._supercell.get_number_of_atoms()\n        num_p = self._primitive.get_number_of_atoms()\n        N = num_s / num_p\n        v = self._velocities\n        self._velocities_q = self._transform(self._qpoints)\n\n    def get_velocities(self):\n        return self._velocities_q\n\n    def set_mesh(self, mesh):\n        rec_lat = np.linalg.inv(self._primitive.get_cell())\n        self._qpoints, self._weights = get_qpoints(\n            mesh,\n            rec_lat,\n            is_gamma_center=True,\n            rotations=self._point_group_opts)\n\n    def set_qpoints(self, qpoints):\n        self._weights = np.ones(len(qpoints), dtype='intc')\n        self._qpoints = qpoints\n\n    def set_commensurate_points(self):\n        supercell_matrix = np.linalg.inv(self._primitive.get_primitive_matrix())\n        supercell_matrix = np.rint(supercell_matrix).astype('intc')\n        self.set_qpoints(get_commensurate_points(supercell_matrix))\n\n    def get_qpoints(self):\n        return self._qpoints, self._weights\n\n    def _transform(self, q):\n        \"\"\" exp(i q.r(i)) v(i)\"\"\"\n\n        s2p = self._primitive.get_supercell_to_primitive_map()\n        p2s = self._primitive.get_primitive_to_supercell_map()\n\n        num_s = self._supercell.get_number_of_atoms()\n        num_p = self._primitive.get_number_of_atoms()\n        v = self._velocities\n\n        q_array = np.reshape(q, (-1, 3))\n        v_q = np.zeros((v.shape[0], num_p, len(q_array), 3), dtype='complex128')\n\n        for p_i, s_i in enumerate(p2s):\n            for s_j, s2p_j in enumerate(s2p):\n                if s2p_j == s_i:\n                    for q_i, pf in enumerate(\n                            self._get_phase_factor(p_i, s_j, q_array)):\n                        v_q[:, p_i, q_i, :] += pf * v[:, s_j, :]\n        return v_q\n\n    def _get_phase_factor(self, p_i, s_j, q_array):\n        multi = self._multiplicity[s_j, p_i]\n        pos = self._shortest_vectors[s_j, p_i, :multi]\n        return np.exp(-2j * np.pi * np.dot(q_array, pos.T)).sum(axis=1) / multi\n\n\nclass AutoCorrelation(object):\n    def __init__(self,\n                 velocities, # in m/s\n                 masses=None, # in AMU\n                 temperature=None): # in K\n        self._velocities = velocities\n        self._masses = masses\n        self._temperature = temperature\n\n        self._vv = None\n        self._n_elements = 0\n\n    def run(self, num_frequency_points, verbose=False):\n        v = self._velocities\n        max_lag = num_frequency_points * 2\n        n_elem = len(v) - max_lag\n\n        if n_elem < 1:\n            return False\n\n        vv = np.zeros((max_lag,) + v.shape[1:], dtype=v.dtype, order='C')\n\n        if np.iscomplexobj(vv):\n            v_c = v.conj()\n\n        # Here is the bottle neck.\n        d = max_lag / 2\n        for i in range(max_lag):\n            if verbose:\n                if (i + 1) % (max_lag // 100) == 0:\n                    sys.stdout.write(\"\\r%d%%\" % (((i + 1) * 100) // max_lag))\n                    sys.stdout.flush()\n            if np.iscomplexobj(vv):\n                vv[i - d] = (v[d:(d + n_elem)] *\n                             v_c[i:(i + n_elem)]).sum(axis=0)\n            else:\n                vv[i - d] = (v[d:(d + n_elem)] *\n                             v[i:(i + n_elem)]).sum(axis=0)\n        if verbose:\n            sys.stdout.write(\"\\r    \\n\")\n            sys.stdout.flush()\n\n        self._vv = vv\n        if self._masses is not None and self._temperature is not None:\n            for i, m in enumerate(self._masses):\n                self._vv[:, i] *= m * AMU / (kb_J * self._temperature)\n\n        self._n_elements = n_elem\n\n        return True\n\n    def get_autocorrelation(self):\n        return self._vv\n\n    def get_number_of_elements(self):\n        return self._n_elements\n\n", "meta": {"hexsha": "98dd5e716eed2fa200c3f23c723379170be673f8", "size": 7147, "ext": "py", "lang": "Python", "max_stars_repo_path": "phonopy/spectrum/velocity.py", "max_stars_repo_name": "ihpcganck/pp-1.11.12", "max_stars_repo_head_hexsha": "e746204b5d86a570f28ecb26433a10264711b9af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "phonopy/spectrum/velocity.py", "max_issues_repo_name": "ihpcganck/pp-1.11.12", "max_issues_repo_head_hexsha": "e746204b5d86a570f28ecb26433a10264711b9af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phonopy/spectrum/velocity.py", "max_forks_repo_name": "ihpcganck/pp-1.11.12", "max_forks_repo_head_hexsha": "e746204b5d86a570f28ecb26433a10264711b9af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0343137255, "max_line_length": 80, "alphanum_fraction": 0.6191408983, "include": true, "reason": "import numpy", "num_tokens": 1752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.28457601028405616, "lm_q1q2_score": 0.15006163238021644}}
{"text": "\"\"\"\nModule providing the definition of an Observatory.\n\nThis replaces the original usage of an aipy.AntennaArray with something much more\nsimple, and suited to the needs of this particular package.\n\"\"\"\n\nimport attr\nimport collections\nimport logging\nimport numpy as np\nimport tqdm\nimport yaml\nfrom astropy import constants as cnst\nfrom astropy import units as units\nfrom attr import validators as vld\nfrom cached_property import cached_property\nfrom collections import defaultdict\n\nfrom . import _utils as ut\nfrom . import antpos as antpos_module\nfrom . import beam, config\n\nlogger = logging.getLogger(__name__)\n\n\n@attr.s(frozen=True, kw_only=True, order=False)\nclass Observatory:\n    \"\"\"\n    A class defining an interferometric Observatory and its properties.\n\n    Parameters\n    ----------\n    antpos : array\n        An array with shape (Nants, 3) specifying the positions of the antennas.\n        These should be in the ENU (East-North-Up) frame, relative to a central location\n        given by `latitude`. If not a Quantity, units are assumed to be meters.\n    beam : :class:`~py21cmsense.beam.PrimaryBeam` instance\n        A beam, assumed to be homogeneous across antennas.\n    latitude : float or Quantity, optional\n        Latitude of the array center. If a float, assumed to be in radians.\n        Note that longitude is not required, as we assume an isotropic sky.\n    Trcv : float or Quantity\n        Receiver temperature, assumed to be in mK unless otherwise defined.\n    min_antpos, max_antpos\n        The minimum/maximum radial distance to include antennas (from the origin\n        of the array). Assumed to be in units of meters if no units are supplied.\n        Can be used to limit antennas in arrays like HERA and SKA that\n        have a \"core\" and \"outriggers\". The minimum is inclusive, and maximum exclusive.\n    \"\"\"\n\n    _antpos = attr.ib(\n        converter=ut.apply_or_convert_unit(\"m\"), eq=attr.cmp_using(eq=np.array_equal)\n    )\n    beam = attr.ib(validator=vld.instance_of(beam.PrimaryBeam))\n    latitude = attr.ib(\n        0,\n        converter=ut.apply_or_convert_unit(\"rad\"),\n        validator=ut.between(-np.pi * units.rad / 2, np.pi * units.rad / 2),\n    )\n    Trcv = attr.ib(\n        1e5, converter=ut.apply_or_convert_unit(\"mK\"), validator=ut.nonnegative\n    )\n    max_antpos: float = attr.ib(default=np.inf, converter=ut.apply_or_convert_unit(\"m\"))\n    min_antpos: float = attr.ib(default=0.0, converter=ut.apply_or_convert_unit(\"m\"))\n\n    @_antpos.validator\n    def _antpos_validator(self, att, val):\n        assert val.ndim == 2\n        assert val.shape[-1] == 3\n        assert val.shape[0] > 1\n\n    @cached_property\n    def antpos(self) -> np.ndarray:\n        \"\"\"The positions of antennas in the array in units of metres.\"\"\"\n        # Mask out some antennas if a max_antpos is set in the YAML\n        _n = len(self._antpos)\n        sq_len = np.sum(np.square(self._antpos), axis=1)\n        antpos = self._antpos[\n            np.logical_and(\n                sq_len >= self.min_antpos ** 2,\n                sq_len < self.max_antpos ** 2,\n            )\n        ]\n\n        if self.max_antpos < np.inf or self.min_antpos > 0:\n            logger.info(\n                f\"Removed {_n - len(antpos)} antennas using given \"\n                f\"max_antpos={self.max_antpos} m and min_antpos={self.min_antpos} m.\"\n            )\n\n        return antpos\n\n    @property\n    def frequency(self):\n        \"\"\"Central frequency of the observation.\"\"\"\n        return self.beam.frequency\n\n    @cached_property\n    def n_antennas(self):\n        \"\"\"Number of antennas in the array.\"\"\"\n        return len(self.antpos)\n\n    def clone(self, **kwargs):\n        \"\"\"Return a clone of this instance, but change kwargs.\"\"\"\n        return attr.evolve(self, **kwargs)\n\n    @classmethod\n    def from_uvdata(cls, uvdata, beam):\n        \"\"\"Instantiate an Observatory from a :class:`pyuvdata.UVData` object or file.\"\"\"\n        try:\n            import pyuvdata\n        except ImportError:\n            raise ImportError(\n                \"cannot construct Observatory from uvdata object without \"\n                \"pyuvdata being installed!\"\n            )\n\n        if isinstance(uvdata, str):\n            uv = pyuvdata.UVData()\n            uv.read(uvdata)\n        else:\n            uv = uvdata\n\n        return cls(\n            antpos=uv.antenna_positions,\n            beam=beam,\n            latitude=uv.telescope_location_lat_lon_alt[0],\n        )\n\n    @classmethod\n    def from_yaml(cls, yaml_file):\n        \"\"\"Instantiate an Observatory from a compatible YAML config file.\"\"\"\n        if isinstance(yaml_file, str):\n            with open(yaml_file) as fl:\n                data = yaml.load(fl, Loader=yaml.FullLoader)\n        elif isinstance(yaml_file, collections.abc.Mapping):\n            data = yaml_file\n        else:\n            raise ValueError(\n                \"yaml_file must be a string filepath or a raw dict from such a file.\"\n            )\n\n        antpos = data.pop(\"antpos\")\n\n        if isinstance(antpos, dict):\n            fnc = getattr(antpos_module, antpos.pop(\"function\"))\n            antpos = fnc(**antpos)\n\n        elif isinstance(antpos, str):\n            if antpos.endswith(\".npy\"):\n                antpos = np.load(antpos)\n            else:\n                try:\n                    antpos = np.genfromtxt(antpos)\n                except Exception:\n                    raise TypeError(\"None of the loaders for antpos worked.\")\n\n        try:\n            antpos = np.array(antpos)\n        except ValueError:\n            raise ValueError(\n                \"antpos must be a function from antpos, or a .npy or ascii \"\n                \"file, or convertible to a ndarray\"\n            )\n\n        # Mask out some antennas if a max_antpos is set in the YAML\n        max_antpos = data.pop(\"max_antpos\", np.inf)\n        _n = len(antpos)\n        antpos = antpos[np.sum(np.square(antpos), axis=1) < max_antpos ** 2]\n\n        if max_antpos < np.inf:\n            logger.info(\n                f\"Removed {_n - len(antpos)} antennas using given max_antpos={max_antpos} m.\"\n            )\n\n        # If we get only East and North coords, add zeros for the UP direction.\n        if antpos.shape[1] == 2:\n            antpos = np.hstack((antpos, np.zeros((len(antpos), 1))))\n\n        _beam = data.pop(\"beam\")\n        kind = _beam.pop(\"class\")\n        _beam = getattr(beam, kind)(**_beam)\n\n        return cls(antpos=antpos, beam=_beam, **data)\n\n    @cached_property\n    def baselines_metres(self) -> np.ndarray:\n        \"\"\"Raw baseline distances in metres for every pair of antennas.\n\n        Shape is ``(Nant, Nant, 3)``.\n        \"\"\"\n        # this does an \"outer\" subtraction, leaving the inner 2- or 3- length positions\n        # as atomic quantities.\n        return self.antpos[np.newaxis, :, :] - self.antpos[:, np.newaxis, :]\n\n    def projected_baselines(self, baselines=None, time_offset=0):\n        \"\"\"The *projected* baseline lengths (in wavelengths).\n\n        Phased to a point that has rotated off zenith by some time_offset.\n\n        Parameters\n        ----------\n        baselines : array_like, optional\n            The baseline co-ordinates to project, assumed to be in metres.\n            If not provided, uses all baselines of the observatory.\n            Shape of the array can be (N,N,3) or (N, 3).\n            The co-ordinates are expected to be in ENU.\n        time_offset : float or Quantity\n            The amount of time elapsed since the phase center was at zenith.\n            Assumed to be in days unless otherwise defined. May be negative.\n\n        Returns\n        -------\n        An array the same shape as :attr:`baselines_metres`, but phased to the\n        new phase centre.\n        \"\"\"\n        if baselines is None:\n            baselines = self.baselines_metres\n\n        baselines = ut.apply_or_convert_unit(\"m\")(baselines)\n        orig_shape = baselines.shape\n\n        bl_wavelengths = baselines.reshape((-1, 3)) * self.metres_to_wavelengths\n\n        out = ut.phase_past_zenith(time_offset, bl_wavelengths, self.latitude)\n\n        out = out.reshape(*orig_shape[:-1], np.size(time_offset), orig_shape[-1])\n        if np.size(time_offset) == 1:\n            out = out.squeeze(-2)\n\n        return out\n\n    @cached_property\n    def metres_to_wavelengths(self):\n        \"\"\"Conversion factor for metres to wavelengths at fiducial frequency.\"\"\"\n        return (self.frequency / cnst.c).to(\"1/m\")\n\n    @cached_property\n    def baseline_lengths(self):\n        \"\"\"Lengths of baselines in units of wavelengths, shape (Nant, Nant).\"\"\"\n        return np.sqrt(np.sum(self.projected_baselines() ** 2, axis=-1))\n\n    @cached_property\n    def shortest_baseline(self):\n        \"\"\"Shortest baseline in units of wavelengths.\"\"\"\n        return np.min(self.baseline_lengths[self.baseline_lengths > 0])\n\n    @cached_property\n    def longest_baseline(self):\n        \"\"\"Longest baseline in units of wavelengths.\"\"\"\n        return np.max(self.baseline_lengths)\n\n    @cached_property\n    def observation_duration(self):\n        \"\"\"The time it takes for the sky to drift through the FWHM.\"\"\"\n        return units.day * self.beam.fwhm() / (2 * np.pi * units.rad)\n\n    def get_redundant_baselines(self, bl_min=0, bl_max=np.inf, ndecimals=1):\n        \"\"\"\n        Determine all baseline groups.\n\n        Parameters\n        ----------\n        bl_min : float or astropy.Quantity, optional\n            The minimum baseline to consider, in metres (or compatible units)\n        bl_max : float or astropy.Quantity, optional\n            The maximum baseline to consider, in metres (or compatible units)\n        ndecimals : int, optional\n            The number of decimals to which the UV points must be the same to be\n            considered redundant.\n\n        Returns\n        -------\n        dict: a dictionary in which keys are 3-tuples of ``(u,v, |u|)`` co-ordinates and\n            values are lists of 2-tuples, where each 2-tuple consists of the indices\n            of a pair of antennas with those co-ordinates.\n        \"\"\"\n        uvbins = defaultdict(list)\n\n        bl_min = ut.apply_or_convert_unit(\"m\")(bl_min) * self.metres_to_wavelengths\n        bl_max = ut.apply_or_convert_unit(\"m\")(bl_max) * self.metres_to_wavelengths\n\n        uvw = self.projected_baselines()\n        # group redundant baselines\n        for i in tqdm.tqdm(\n            range(self.n_antennas - 1),\n            desc=\"finding redundancies\",\n            unit=\"ants\",\n            disable=not config.PROGRESS,\n        ):\n            for j in range(i + 1, self.n_antennas):\n\n                bl_len = self.baseline_lengths[i, j]  # in wavelengths\n                if bl_len < bl_min or bl_len > bl_max:\n                    continue\n\n                u, v = uvw[i, j][:2]\n\n                uvbin = (\n                    ut.trunc(u, ndecimals=ndecimals),\n                    ut.trunc(v, ndecimals=ndecimals),\n                    ut.trunc(bl_len, ndecimals=ndecimals),\n                )\n\n                # add the uv point and its inverse to the redundant baseline dict.\n                uvbins[uvbin].append((i, j))\n                uvbins[(-uvbin[0], -uvbin[1], uvbin[2])].append((j, i))\n\n        return uvbins\n\n    def time_offsets_from_obs_int_time(\n        self, integration_time, observation_duration=None\n    ):\n        \"\"\"Compute a list of time offsets within an LST-bin.\n\n        The LSTs 'within a bin' are added coherently for a given baseline group.\n        Time offsets are with respect to an arbitrary time, and describe the rotation of\n        a hypothetical point through zenith.\n\n        Parameters\n        ----------\n        integration_time : float or astropy.Quantity\n            Time for single snapshot, assumed to be in seconds.\n        observation_duration : float or astropy.Quantity\n            Duration of the LST bin (for single night). Assumed to be in minutes.\n\n        Returns\n        -------\n        array :\n            Time offsets (in julian days).\n        \"\"\"\n        if observation_duration is None:\n            observation_duration = self.observation_duration\n\n        observation_duration = ut.apply_or_convert_unit(\"min\")(observation_duration)\n        integration_time = ut.apply_or_convert_unit(\"s\")(integration_time)\n        assert integration_time <= observation_duration\n\n        return np.arange(\n            -observation_duration.to(\"day\").value / 2,\n            observation_duration.to(\"day\").value / 2,\n            integration_time.to(\"day\").value,\n        )\n\n    def baseline_coords_from_groups(self, baseline_groups):\n        \"\"\"Convert a dictionary of baseline groups to an array of ENU co-ordinates.\"\"\"\n        out = np.zeros((len(baseline_groups), 3)) * units.m\n        for i, antpairs in enumerate(baseline_groups.values()):\n            out[i] = self.baselines_metres[antpairs[0][0], antpairs[0][1]]\n        return out\n\n    @staticmethod\n    def baseline_weights_from_groups(baseline_groups):\n        \"\"\"Get number of baselines in each group.\n\n        Parameters\n        ----------\n        baseline_groups\n            A dictionary in the format output by :func:`get_redundant_baselines`.\n\n        Returns\n        -------\n        weights\n            An array containing the number of baselines in each group.\n        \"\"\"\n        return np.array([len(antpairs) for antpairs in baseline_groups.values()])\n\n    def grid_baselines(\n        self,\n        baselines=None,\n        weights=None,\n        integration_time=60.0 * units.s,\n        bl_min=0,\n        bl_max=np.inf,\n        observation_duration=None,\n        ndecimals=1,\n    ):\n        \"\"\"\n        Grid baselines onto a pre-determined uvgrid, accounting for earth rotation.\n\n        Parameters\n        ----------\n        baselines : array_like, optional\n            The baseline co-ordinates to project, assumed to be in metres.\n            If not provided, calculates effective baselines by finding redundancies on\n            all baselines in the observatory. Shape of the array can be (N,N,3) or (N, 3).\n            The co-ordinates are expected to be in ENU. If `baselines` is provided,\n            `weights` must also be provided.\n        weights: array_like, optional\n            An array of the same length as `baselines`, giving the number of independent\n            baselines at each co-ordinate. If not provided, calculates effective\n            baselines by finding redundancies on all baselines in the observatory.\n            If `baselines` is provided, `weights` must also be provided.\n        integration_time : float or Quantity, optional\n            The amount of time integrated into a snapshot visibility, assumed\n            to be in seconds.\n        bl_min : float or Quantity, optional\n            Minimum baseline length (in meters) to include in the gridding.\n        bl_max : float or Quantity, optional\n            Maximum baseline length (in meters) to include in the gridding.\n        observation_duration : float or Quantity, optional\n            Amount of time in a single (coherent) LST bin, assumed to be in minutes.\n        ndecimals : int, optional\n            Number of decimals to which baselines must match to be considered redundant.\n\n        Returns\n        -------\n        array :\n            Shape [n_baseline_groups, Nuv, Nuv]. The coherent sum of baselines within\n            grid cells given by :attr:`ugrid`. One can treat different baseline groups\n            independently, or sum over them.\n\n        See Also\n        --------\n        grid_baselines_coherent :\n            Coherent sum over baseline groups of the output of this method.\n        grid_basleine_incoherent :\n            Incoherent sum over baseline groups of the output of this method.\n        \"\"\"\n        if baselines is None:\n            baseline_groups = self.get_redundant_baselines(\n                bl_min=bl_min, bl_max=bl_max, ndecimals=ndecimals\n            )\n            baselines = self.baseline_coords_from_groups(baseline_groups)\n            weights = self.baseline_weights_from_groups(baseline_groups)\n\n        if weights is None:\n            raise ValueError(\n                \"If baselines are provided, weights must also be provided.\"\n            )\n\n        time_offsets = self.time_offsets_from_obs_int_time(\n            integration_time, observation_duration\n        )\n\n        uvws = self.projected_baselines(baselines, time_offsets).reshape(\n            baselines.shape[0], time_offsets.size, 3\n        )\n\n        # grid each baseline type into uv plane\n        dim = len(self.ugrid(bl_max))\n        edges = self.ugrid_edges(bl_max)\n\n        uvsum = np.zeros((len(baselines), dim, dim))\n        for cnt, (uvw, nbls) in enumerate(\n            tqdm.tqdm(\n                zip(uvws, weights),\n                desc=\"gridding baselines\",\n                unit=\"baselines\",\n                disable=not config.PROGRESS,\n                total=len(weights),\n            )\n        ):\n            uvsum[cnt] = np.histogram2d(uvw[:, 0], uvw[:, 1], bins=edges)[0] * nbls\n\n        return uvsum\n\n    def longest_used_baseline(self, bl_max=np.inf):\n        \"\"\"Determine the maximum baseline length kept in the array.\"\"\"\n        if np.isinf(bl_max):\n            return self.longest_baseline\n\n        bl_max = ut.apply_or_convert_unit(\"m\")(bl_max) * self.metres_to_wavelengths\n        return np.max(self.baseline_lengths[self.baseline_lengths <= bl_max])\n\n    def ugrid_edges(self, bl_max=np.inf):\n        \"\"\"Get a uv grid out to the maximum used baseline smaller than given bl_max.\n\n        The resulting array represents the *edges* of the grid (so the number of cells\n        is one fewer than this).\n\n        Parameters\n        ----------\n        bl_max : float or Quantity\n            Include all baselines smaller than this number. Units of m.\n\n        Returns\n        -------\n        array :\n            1D array of regularly spaced u.\n        \"\"\"\n        bl_max = self.longest_used_baseline(bl_max)\n\n        # We're doing edges of bins here, and the first edge is at uv_res/2\n        n_positive = int(\n            np.ceil((bl_max - self.beam.uv_resolution / 2) / self.beam.uv_resolution)\n        )\n\n        # Grid from uv_res/2 to just past (or equal to) bl_max, in steps of resolution.\n        positive = np.linspace(\n            self.beam.uv_resolution / 2,\n            self.beam.uv_resolution / 2 + n_positive * self.beam.uv_resolution,\n            n_positive + 1,\n        )\n        return np.concatenate((-positive[::-1], positive))\n\n    def ugrid(self, bl_max=np.inf):\n        \"\"\"Centres of the UV grid plane.\"\"\"\n        # Shift the edges by half a cell, and omit the last one\n        edges = self.ugrid_edges(bl_max)\n        return (edges[1:] + edges[:-1]) / 2\n\n    def grid_baselines_coherent(self, **kwargs):\n        \"\"\"Get a UV grid of coherently gridded baselines.\n\n        Different baseline groups are averaged coherently if they fall into the same\n        UV bin.\n\n        See :func:`grid_baselines` for parameter details.\n        \"\"\"\n        grid = self.grid_baselines(**kwargs)\n        return np.sum(grid, axis=0)\n\n    def grid_baselines_incoherent(self, **kwargs):\n        \"\"\"Get a UV grid of incoherently gridded baselines.\n\n        Different baseline groups are averaged incoherently if they fall into the same\n        UV bin.\n\n        See :func:`grid_baselines` for parameter details.\n        \"\"\"\n        grid = self.grid_baselines(**kwargs)\n        return np.sqrt(np.sum(grid ** 2, axis=0))\n\n    def __eq__(self, other):\n        \"\"\"Test equality of the observatory with another object.\"\"\"\n        if not self.__class__ == other.__class__:\n            return False\n        if not (self.Trcv, self.beam, self.latitude) == (\n            other.Trcv,\n            other.beam,\n            other.latitude,\n        ):\n            return False\n\n        if not np.array_equal(self.antpos.value, other.antpos.value):\n            return False\n\n        return True\n", "meta": {"hexsha": "b8e34c046b9da915671ca90ba4069e16dc0fbfa3", "size": 19841, "ext": "py", "lang": "Python", "max_stars_repo_path": "py21cmsense/observatory.py", "max_stars_repo_name": "steven-murray/21cmSense", "max_stars_repo_head_hexsha": "6f23e4952686fed8d872d59e4dd3185566a04c9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "py21cmsense/observatory.py", "max_issues_repo_name": "steven-murray/21cmSense", "max_issues_repo_head_hexsha": "6f23e4952686fed8d872d59e4dd3185566a04c9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 66, "max_issues_repo_issues_event_min_datetime": "2019-03-01T20:16:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T20:56:31.000Z", "max_forks_repo_path": "py21cmsense/observatory.py", "max_forks_repo_name": "steven-murray/21cmSense", "max_forks_repo_head_hexsha": "6f23e4952686fed8d872d59e4dd3185566a04c9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-23T23:20:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T06:38:58.000Z", "avg_line_length": 36.674676525, "max_line_length": 93, "alphanum_fraction": 0.6104531022, "include": true, "reason": "import numpy,from astropy", "num_tokens": 4525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096344, "lm_q2_score": 0.29098086621490676, "lm_q1q2_score": 0.15003553404646153}}
{"text": "# This file is part of QuTiP: Quantum Toolbox in Python.\n#\n#    Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.\n#    All rights reserved.\n#\n#    Redistribution and use in source and binary forms, with or without \n#    modification, are permitted provided that the following conditions are \n#    met:\n#\n#    1. Redistributions of source code must retain the above copyright notice, \n#       this list of conditions and the following disclaimer.\n#\n#    2. Redistributions in binary form must reproduce the above copyright\n#       notice, this list of conditions and the following disclaimer in the\n#       documentation and/or other materials provided with the distribution.\n#\n#    3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names\n#       of its contributors may be used to endorse or promote products derived\n#       from this software without specific prior written permission.\n#\n#    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \n#    \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n#    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A \n#    PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT \n#    HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, \n#    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT \n#    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, \n#    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY \n#    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n#    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \n#    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n###############################################################################\nimport os\nimport numpy\nfrom scipy import ndarray, array\n\nfrom qutip.cy.codegen import Codegen\nfrom qutip.odeoptions import Odeoptions\nfrom qutip.odechecks import _ode_checks\nfrom qutip.odeconfig import odeconfig\nfrom qutip.qobj import Qobj\nfrom qutip.superoperator import spre, spost\n\n\ndef rhs_clear():\n    \"\"\"\n    Resets the string-format time-dependent Hamiltonian parameters.\n\n    Parameters\n    ----------\n\n    Returns\n    -------\n    Nothing, just clears data from internal odeconfig module.\n\n    \"\"\"\n    # time-dependent (TD) function stuff\n    odeconfig.tdfunc = None     # Placeholder for TD RHS function.\n    odeconfig.colspmv = None    # Placeholder for TD col-spmv function.\n    odeconfig.colexpect = None  # Placeholder for TD col_expect function.\n    odeconfig.string = None     # Holds string of variables to be passed onto\n                                # time-depdendent ODE solver.\n    odeconfig.tdname = None     # Name of td .pyx file\n                                # (used in parallel mc code)\n\n\ndef rhs_generate(H, c_ops, args={}, options=Odeoptions(), name=None):\n    \"\"\"\n    Generates the Cython functions needed for solving the dynamics of a\n    given system using the mesolve function inside a parfor loop.\n\n    Parameters\n    ----------\n    H : qobj\n        System Hamiltonian.\n    c_ops : list\n        ``list`` of collapse operators.\n    args : dict\n        Arguments for time-dependent Hamiltonian and collapse operator terms.\n    options : Odeoptions\n        Instance of ODE solver options.\n    name: str\n        Name of generated RHS\n\n    Notes\n    -----\n    Using this function with any solver other than the mesolve function\n    will result in an error.\n\n    \"\"\"\n    odeconfig.reset()\n    odeconfig.options = options\n\n    if name:\n        odeconfig.tdname = name\n    else:\n        odeconfig.tdname = \"rhs\" + str(odeconfig.cgen_num)\n\n    Lconst = 0\n\n    Ldata = []\n    Linds = []\n    Lptrs = []\n    Lcoeff = []\n\n    # loop over all hamiltonian terms, convert to superoperator form and\n    # add the data of sparse matrix represenation to\n    for h_spec in H:\n        if isinstance(h_spec, Qobj):\n            h = h_spec\n            Lconst += -1j * (spre(h) - spost(h))\n\n        elif isinstance(h_spec, list):\n            h = h_spec[0]\n            h_coeff = h_spec[1]\n\n            L = -1j * (spre(h) - spost(h))\n\n            Ldata.append(L.data.data)\n            Linds.append(L.data.indices)\n            Lptrs.append(L.data.indptr)\n            Lcoeff.append(h_coeff)\n\n        else:\n            raise TypeError(\"Incorrect specification of time-dependent \" +\n                            \"Hamiltonian (expected string format)\")\n\n    # loop over all collapse operators\n    for c_spec in c_ops:\n        if isinstance(c_spec, Qobj):\n            c = c_spec\n            cdc = c.dag() * c\n            Lconst += spre(\n                c) * spost(c.dag()) - 0.5 * spre(cdc) - 0.5 * spost(cdc)\n\n        elif isinstance(c_spec, list):\n            c = c_spec[0]\n            c_coeff = c_spec[1]\n\n            cdc = c.dag() * c\n            L = spre(c) * spost(c.dag()) - 0.5 * spre(cdc) - 0.5 * spost(cdc)\n\n            Ldata.append(L.data.data)\n            Linds.append(L.data.indices)\n            Lptrs.append(L.data.indptr)\n            Lcoeff.append(\"(\" + c_coeff + \")**2\")\n\n        else:\n            raise TypeError(\"Incorrect specification of time-dependent \" +\n                            \"collapse operators (expected string format)\")\n\n    # add the constant part of the lagrangian\n    if Lconst != 0:\n        Ldata.append(Lconst.data.data)\n        Linds.append(Lconst.data.indices)\n        Lptrs.append(Lconst.data.indptr)\n        Lcoeff.append(\"1.0\")\n\n    # the total number of liouvillian terms (hamiltonian terms + collapse\n    # operators)\n    n_L_terms = len(Ldata)\n\n    cgen = Codegen(h_terms=n_L_terms, h_tdterms=Lcoeff, args=args,\n                   odeconfig=odeconfig)\n    cgen.generate(odeconfig.tdname + \".pyx\")\n\n    code = compile('from ' + odeconfig.tdname +\n                   ' import cy_td_ode_rhs', '<string>', 'exec')\n    exec(code, globals())\n\n    odeconfig.tdfunc = cy_td_ode_rhs\n    try:\n        os.remove(odeconfig.tdname + \".pyx\")\n    except:\n        pass\n", "meta": {"hexsha": "6483050b5b054f51f0d287b6371dd020f5254a88", "size": 6027, "ext": "py", "lang": "Python", "max_stars_repo_path": "qutip/rhs_generate.py", "max_stars_repo_name": "trxw/qutip", "max_stars_repo_head_hexsha": "b923c973edd9a071d86eb849650661549f73585f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-11-06T06:35:06.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-06T06:35:06.000Z", "max_issues_repo_path": "qutip/rhs_generate.py", "max_issues_repo_name": "trxw/qutip", "max_issues_repo_head_hexsha": "b923c973edd9a071d86eb849650661549f73585f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qutip/rhs_generate.py", "max_forks_repo_name": "trxw/qutip", "max_forks_repo_head_hexsha": "b923c973edd9a071d86eb849650661549f73585f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2443181818, "max_line_length": 79, "alphanum_fraction": 0.6266799403, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.29098087236345377, "lm_q1q2_score": 0.1500355328850536}}
